{"text": "\\input{../../style/preamble} \n\\input{../../latex-math/basic-math}\n\\input{../../latex-math/basic-ml}\n\\input{../../latex-math/ml-bagging.tex}\n\\input{../../latex-math/ml-boosting.tex}\n\\input{../../latex-math/ml-trees.tex}\n\n\\newcommand{\\titlefigure}{figure/fig-gb-concept-2.png}\n\\newcommand{\\learninggoals}{\n  \\item Understand idea of forward stagewise modelling\n  \\item Understand fitting process of gradient boosting for regression problems\n}\n\n\\title{Introduction to Machine Learning}\n\\date{}\n\n\\begin{document}\n\n\\lecturechapter{Gradient Boosting}\n\\lecture{Introduction to Machine Learning}\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% \\section{Gradient Boosting}\n\n% \\begin{vbframe}{Gradient descent}\n% % \\begin{vbframe}{Forward stagewise additive modeling}\n% \n% % Let's recall gradient descent from numerical optimization.\n% Let $\\risk(\\theta)$ be (just for the next few slides) an arbitrary, differentiable, unconstrained objective function, which we want to minimize. The gradient $\\nabla \\risk(\\theta)$ is the direction of the steepest ascent, $-\\nabla \\risk(\\theta)$ of \\textbf{steepest descent}.\n% \n% \\lz\n% \n% For an intermediate solution $\\theta^{[k]}$ during minimization, we can iteratively improve by updating\n% $$\n% \\theta^{[k+1]} = \\theta^{[k]} - \\beta \\nabla \\risk(\\theta^{[k]}) \\qquad  \\text{for } 0 < \\beta \\leq c\\left(\\theta^{[k]}\\right)\n% $$\n% % \\enquote{Walking down the hill, towards the valley.}\n% \n% % $f(x_1, x_2) = -\\sin(0.8 x_1) \\cdot \\frac{1}{2\\pi} \\exp\\left( (x_2 x_1 + \\pi / 2)^2 \\right)$\n% <<sd-plot>>=\n% #modified from ../../../cim1/2017/11-Optimierung/functions.\n% \n% sd_plot = function(col = terrain_hcl, theta = 40, phi = 40, xlab = \"x\", ylab = \"y\") {\n%   if (is.function(col)) col = col(nrow(z) * ncol(z))\n% \n%   par(mfrow = c(1, 2))\n% \n%   par(mar = rep(0.5, 4))\n%   require(\"colorspace\")\n%   pmat = persp2(x, y, z, theta = theta, phi = phi, ticktype = \"detailed\",\n%       xlab = xlab, ylab = ylab, zlab = \"\", col = col, lwd = 0.3, border = NA)\n% \n%   for (j in seq_along(p)) {\n%     t3d = trans3d(p[[j]][[1]], p[[j]][[2]], do.call(foo, p[[j]]), pmat)\n%     if (j > 1) {\n%       t3d2 = trans3d(p[[j - 1]][[1]], p[[j - 1]][[2]], do.call(foo, p[[j- 1]]), pmat)\n%       lines(c(t3d$x, t3d2$x), c(t3d$y, t3d2$y))\n%       points(x = t3d2$x, y = t3d2$y, pch = 16, col = heat_hcl(1))\n%     }\n%     points(x = t3d$x, y = t3d$y, pch = 16, col = heat_hcl(1))\n%   }\n%   par(mar = c(4.1, 4.1, 1.1, 1.1))\n%   image(x, y, z, col = col, xlab = xlab, ylab = ylab, useRaster = TRUE)\n%   contour(x, y, z, add = TRUE, nlevels = 15)\n%   for (j in seq_along(p)) {\n%     if (j > 1) {\n%       lines(c(p[[j]][1], p[[j - 1]][1]), c(p[[j]][2], p[[j - 1]][2]))\n%       points(p[[j - 1]][1], p[[j - 1]][2], pch = 16, col = heat_hcl(1))\n%     }\n%     points(p[[j]][1], p[[j]][2], pch = 16, col = heat_hcl(1))\n%   }\n%   invisible(NULL)\n% }\n% \n% @\n% <<gradient-descent, fig.align=\"center\", echo=FALSE, fig.width=8, fig.height=4, out.height=\"3cm\", out.width=\"6cm\">>=\n% foo = function(x, y) {\n%   -1 * sin(.8 * pi*x) * dnorm(-y * x, mean = pi / 2, sd = 0.8)\n% }\n% \n% x = seq(0, 2.5, length = 50)\n% y = seq(-3, 1, length = 50)\n% z = outer(x, y, foo)\n% p = c(list(list(1.8, -.5)), optim0(1.8, -.5, FUN = foo, maximum = FALSE, maxit = 19))\n% \n% sd_plot(phi = 35, theta = -20, xlab = \"x_1\", ylab = \"x_2\", col = viridis::viridis)\n% @\n% \n% % {\\scriptsize step size  $\\beta = 1$}\n% \n% % \\framebreak\n% \n% % $\\beta$ is called \\textbf{step size}, and can be set by\n% % \\begin{itemize}\n% % \\item fixing it to a (smallish) constant\n% % \\item adapting it according to previous gradient values, the local Hessian, etc.\n% % \\item line search methods, which solve $\\beta^{[k]} = \\argmin_{\\beta} f\\left(x^{[k]} - \\beta \\nabla f\\left(x^{[k]}\\right)\\right)$. Only one real parameter $\\beta$, i.e, \\enquote{easy} to solve\\dots\n% % \\end{itemize}\n% \n% \n% \n% \n% \\end{vbframe}\n\n\n\\begin{vbframe}{Forward stagewise additive modeling}\n\nAssume a regression problem for now (as this is simpler to explain);\nand assume a space of base learners $\\mathcal{B}$.\n\n\\lz\n\n% A weak learner should have the property that it delivers better predictions than by random chance (e.g. for a balanced training set a misclassification error less than 1/2).\n\n% \\lz\n\nWe want to learn an additive model:\n\n$$\n\\fx = \\sum_{m=1}^M \\betam \\bmmxth.\n$$\n\nHence, we minimize the empirical risk:\n\n$$\n\\riskef = \\sum_{i=1}^n L\\left(\\yi,\\fxi \\right) =\n\\sum_{i=1}^n L\\left(\\yi, \\sum_{m=1}^M \\betam \\bmmxth\\right)\n$$\n\n\n% \\framebreak\n\n% A common \\textbf{loss} for \\textbf{regression} is the \\textbf{squared error} with\n% $\\Lxy = (y-\\fx)^2$.\n\n% \\lz\n\n% Apparently, $\\risk$ depends on the \\textbf{base learners} $b(x, \\thetam)$,\n% or rather their parameters $\\thetam$ and weights $\\betam$. Hence, we have to optimize these.\n\n% \\lz\n\n\\framebreak\n\\textbf{Why is gradient boosting a good choice for this problem?}\n\\begin{itemize}\n\\item Because of the additive structure it is difficult to jointly minimize $\\riskef$ w.r.t. $\\left(\\left(\\beta^{[1]}, \\bm{\\theta}^{[1]}\\right), \\ldots, \\left(\\beta^{[M]}, \\bm{\\theta}^{[M]}\\right)\\right)$, which is a very high-dimensional parameter space (though this is less of a problem nowadays, especially in the\ncase of numeric parameter spaces).\n% - however, this is nowadays especially in the case of numeric parameter spaces not a real problem anymore.\n\\item Considering trees as base learners is worse as we would have to grow $M$ trees in parallel so they\n  work optimally together as an ensemble.\n\\item Stagewise additive modeling has nice properties, which we want to make use of, e.g. for regularization, early stopping, \\dots\n\\end{itemize}\n\n\\framebreak\n\nHence, we add additive components in a greedy fashion by sequentially minimizing the risk only w.r.t. the next additive component:\n\n$$ \\min \\limits_{\\beta, \\bm{\\theta}} \\sum_{i=1}^n L\\left(\\yi, \\fmdh\\left(\\xi\\right) + \\beta b\\left(\\xi, \\bm{\\theta}\\right)\\right) $$\n\n\\lz\n\nDoing this iteratively is called \\textbf{forward stagewise additive modeling}.\n\n\\input{algorithms/forward_stagewise_additive_modeling.tex}\n\n\\end{vbframe}\n\n\n% \\section{Gradient Boosting}\n\n\\begin{vbframe}{Gradient boosting}\n\n% \\begin{footnotesize}\nThis is not really an algorithm, but an abstract principle.\nTo find $b\\left(\\xv, \\thetam\\right)$ and $\\betam$, we use gradient descent, but in function space!\n\n\\lz\n\\begin{columns}\n\\column{5cm}\n% \\textbf{Thought experiment:}\nConsider a model $f$ whose predictions we can arbitrarily define for each training $\\xi$, i.e.,\n$f$ is a finite vector\n  $$\\left(f\\left(\\xv^{(1)}\\right), \\ldots,  f\\left(\\xv^{(n)}\\right)\\right)^\\top $$\n\nThis implies $n$ parameters $\\fxi$ (and the model would provide no generalization...).\n\nAlso, we let's assume $L$ to be differentiable.\n\n\\column{5cm}\n\\begin{center}\n  \\vspace{-1cm}\n  \\includegraphics[width=\\textwidth]{figure/fig-gb-concept-2.png}\n\\end{center}\n\n\\end{columns}\n% \\end{footnotesize}\n\\end{vbframe}\n\n\\begin{vbframe}{Gradient boosting}\n\n\\textbf{Aim:} Define a movement in function space so we can push our current function towards the data points.\n\n\\vspace*{0.1cm}\n\\textbf{Given:} Regression problem with one feature $x$ and target variable $y$.\n\n\\vspace*{0.1cm}\n\\textbf{Initialization:} Set all parameters to the optimal constant value (e.g., the mean of $y$ for $L2$).\n\n\\begin{figure}\n  \\includegraphics[width=\\textwidth]{figure/fig-gb-concept-1.png}\n\\end{figure}\n\n\n\n\\end{vbframe}\n\n\\begin{frame}{Pseudo Residuals}\n% \\begin{footnotesize}\nHow do we distort our $f$ to move it towards the labels and reduce risk?\n\\vspace*{0.2cm}\nLet's minimize risk with GD.\n\nSo, we calculate the (negative) gradient of the risk for each parameter, which (weirdly) here are the outputs $\\fxi$ \n(0 if $i \\neq j$):\n% \\footnote{The gradient of all terms with $i \\neq j$ are 0.}\n\n$$\n\\tilde{r}^{(i)} = - \\fp{\\riske}{\\fxi} = - \\fp{\\sum_j L(y^{(j)}, f(\\xv^{(j)}))}{\\fxi} = - \\fp{\\Lxyi}{\\fxi}.\n$$\n\n\\vspace*{0.1cm}\n\nAt each point, we would like to change the output via:\n$ \\tilde{r}(f) = - \\fp{L(y, f)}{f} .$\n\n\\begin{columns}\n\\begin{column}{0.45\\textwidth}\n\\begin{center}\n  \\textbf{L2 Example:} The PRs  \n  match the usual residuals:\n  $$    \\tilde{r}(f) = - \\fp{0.5(y - f)^2}{f} = y - f $$\n\\end{center}\n\\end{column}\n\\begin{column}{0.55\\textwidth}\n\\begin{center}\n  \\includegraphics[width=0.7\\textwidth]{figure/pseudo_residual_1.png}\n\\end{center}\n\\end{column}\n\\end{columns}\n\n% \\end{footnotesize}\n\n\\end{frame}\n\n\\begin{vbframe}{Boosting as Gradient Descent}\n\n%\\begin{footnotesize}\n\\vspace*{0.2cm}\nCombining this with \\enquote{forward stagewise modeling}, we are at $\\fmd$ during minimization.\nHere, we calculate the direction of the negative gradient or vector of PRs:\n\n$$ \\rmi = -\\left[\\fp{\\Lxyi}{f(\\xi)}\\right]_{f=\\fmd} $$\n\n\\lz\n\nThe gradient descent update for each vector component of $f$ is:\n\n$$\n  \\fm (\\xi) =  \\fmd (\\xi) + \\beta \\rmi.\n$$\n\nLike this, we should \\enquote{nudge} $f$ in the direction best risk reduction.\n\n%\\end{footnotesize}\n\\end{vbframe}\n\n\n\\begin{vbframe}{Gradient boosting}\n\n\\textbf{Iteration 1:}\n\nLet's move our function $\\fxi$ a fraction towards the pseudo-residuals with a learning rate of $\\beta = 0.6$.\n\n\n\\begin{figure}\n  \\includegraphics[width=\\textwidth]{figure/fig-gb-concept-pseudo-resi-1.png}\n\\end{figure}\n\n\\framebreak\n\n\\textbf{Iteration 2:}\n\nLet's move our function $\\fxi$ a fraction towards the pseudo-residuals with a learning rate of $\\beta = 0.6$.\n\n\n\\begin{figure}\n  \\includegraphics[width=\\textwidth]{figure/fig-gb-concept-pseudo-resi-2.png}\n\\end{figure}\n\n\\framebreak\n% \\begin{footnotesize}\n% We find our $\\betam$ by minimizing with line search:\n\n% $$\n  % \\betam = \\argmin_{\\beta} \\sumin L(\\yi, \\fmdh(x) + \\beta b(x, \\thetamh)),\n% $$\n\n% where $h(x, \\thetam) = \\rmm$.\n\n% \\lz\n\n%What is the point of doing all this? \nAs said, such a model parameterization is pointless.\n\n\\vspace*{0.3cm}\n\n\nSo, we restrict our additive components to $b\\left(\\xv, \\thetam\\right) \\in \\mathcal{B}$.\n\n% \\framebreak\n\nThe pseudo-residuals are calculated exactly as stated above,\nthen we fit a simple model $b(\\xv, \\thetam)$ to them:\n$$ \\thetamh = \\argmin_{\\bm{\\theta}} \\sum_{i=1}^n \\left(\\rmi - b(\\xi, \\bm{\\theta})\\right)^2. $$\n\n\\lz\n\n\\begin{columns}\n\\column{5cm}\nSo, evaluated on the training data,\n$b(\\xv, \\thetam)$ corresponds as closely as possible to the negative risk gradient and generalizes over $\\Xspace$.\n\n\n\\column{5cm}\n\\vspace*{-1cm}\n\\begin{figure}[th]\n  \\includegraphics[width=\\textwidth]{figure/fig-gb-concept-idea.png}\n\\end{figure}\n\n\n\\end{columns}\n% \\end{footnotesize}\n\n\\framebreak\n% \\begin{footnotesize}\n\\textbf{In a nutshell}: One boosting iteration is exactly one approximated gradient descent step in function space,\nwhich minimizes the empirical risk as much as possible.\n\n\n\\vspace*{0.1cm}\n\\textbf{Iteration 1:}\n\\begin{figure}\n  \\includegraphics[width=0.9\\textwidth]{figure/fig-gb-concept-idea-1.png}\n\\end{figure}\n% \\end{footnotesize}\n\\framebreak\n% \\begin{footnotesize}\nInstead of moving the function values for each observation by a fraction closer to the observed data, we fit a regression base learner to the pseudo-residuals (right plot). \n\n\n\\vspace*{0.1cm}\n\\textbf{Iteration 2:}\n\\begin{figure}\n  \\includegraphics[width=0.9\\textwidth]{figure/fig-gb-concept-idea-2.png}\n\\end{figure}\n% \\end{footnotesize}\n\\framebreak\n% \\begin{footnotesize}\nThis BL is added to the of the ensemble, weighted by a learning rate (here: $\\beta = 0.4$).\nThen we iterate.\n\n\n\\vspace*{0.1cm}\n\\textbf{Iteration 3:}\n\\begin{figure}\n  \\includegraphics[width=\\textwidth]{figure/fig-gb-concept-idea-3.png}\n\\end{figure}\n\n% \\begin{footnotesize}\n% This procedure is continued stepwise until the boosting algorithm terminates.\n% \\end{footnotesize}\n% \\end{footnotesize}\n\\end{vbframe}\n%% Combining this with the iterative additive procedure\n%% of \\enquote{forward stagewise modelling}, we are at the spot $\\fmd$ during minimization.\n%% At this point, we now calculate the direction of the negative gradient:\n%%\n%% $$ \\rmi = -\\left[\\fp{\\Lxyi}{f(\\xi)}\\right]_{f=\\fmd} $$\n%%\n%% We will call these $\\rmi$ \\textbf{pseudo residuals}. For squared loss they match the usual residuals\n%%\n%%\n%% $$\n%% - \\fp{\\Lxy}{\\fx} = - \\fp{0.5(y - \\fx)^2}{\\fx} = y - \\fx\n%% $$\n%%\n%%\n%% \\framebreak\n%%\n%% % We find our $\\betam$ by minimizing with line search:\n%%\n%% % $$\n%%   % \\betam = \\argmin_{\\beta} \\sumin L(\\yi, \\fmdh(x) + \\beta b(x, \\thetamh)),\n%% % $$\n%%\n%% % where $h(x, \\thetam) = \\rmm$.\n%%\n%% % \\lz\n%%\n%% What is the point in doing all this? A model parameterized in this way is senseless,\n%% as it is just memorizing the instances of the training data...?\n%%\n%% \\lz\n%%\n%% So, we restrict our additive components to $b\\left(x, \\thetam\\right) \\in \\mathcal{B}$.\n%%\n%% % \\framebreak\n%%\n%% The pseudo-residuals are calculated exactly as stated above,\n%% then we fit a regression model $b(\\bm{x}, \\thetam)$ to them:\n%% $$ \\thetamh = \\argmin_{\\thetab} \\sum_{i=1}^n (\\rmi - b(\\xi, \\thetab))^2 $$\n%% So, evaluated on the training data,\n%% our $b(x, \\thetam)$ corresponds as closely as possible to the negative\n%% loss function gradient and generalizes to the whole space.\n%%\n%% \\lz\n%%\n%% \\textbf{In a nutshell}: One boosting iteration is exactly one approximated gradient step in function space,\n%% which minimizes the empirical risk as much as possible.\n%%\n%% \\end{vbframe}\n\n\\begin{vbframe}{Gradient boosting algorithm}\n\n\\input{algorithms/gradient_boosting_general.tex}\n\nNote that we also initialize the model in a loss-optimal manner. %Also, the constant learning rate can be replaced by a line-search, however a small constant learning rate is commonly used.\n\n\\end{vbframe}\n\n\\begin{vbframe}{Line Search}\nThe learning rate, as always, influences how we converge. \nAlthough a small constant LR is commonly used, we can also run line search,\n% to solve this one-dimensional optimization problem:\n$$\\betamh = \\argmin_{\\beta} \\sumin L(\\yi, \\fmd(\\xv) + \\beta b(\\xv, \\thetamh))$$\n\nAlternatively, an (inexact) backtracking line search can be used to find the \n$\\betam$ that minimizes the above equation.\n\n\\end{vbframe}\n\n\\endlecture\n\\end{document}\n\n", "meta": {"hexsha": "8d435864226dd68e124870dbc2fc128c35c41ef8", "size": 14022, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "slides/boosting/slides-boosting-gradient-boosting-concept.tex", "max_stars_repo_name": "jukaje/lecture_i2ml", "max_stars_repo_head_hexsha": "cd4900f5190e9d319867b4c0eb9d8e19f659fb62", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "slides/boosting/slides-boosting-gradient-boosting-concept.tex", "max_issues_repo_name": "jukaje/lecture_i2ml", "max_issues_repo_head_hexsha": "cd4900f5190e9d319867b4c0eb9d8e19f659fb62", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slides/boosting/slides-boosting-gradient-boosting-concept.tex", "max_forks_repo_name": "jukaje/lecture_i2ml", "max_forks_repo_head_hexsha": "cd4900f5190e9d319867b4c0eb9d8e19f659fb62", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6827133479, "max_line_length": 316, "alphanum_fraction": 0.6676650977, "num_tokens": 4614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765155565327, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.3499320178907083}}
{"text": "\\section{Introduction}\n\tIn plasticity model, plastic deformation depends on the internal state variables which are measurable variables like strain rate, temperature, stress and material variables. The relation between all the internal state variables is expressed using flow rule.\n\t\nIn general, flow rule is the resistance to the plasticity and expressed as the ratio of the plastic driving force to the flow resistance. During plastic deformation, the driving forces direct the internal slip mechanisms which causes shearing. A general power law flow rule representation equ.(\\ref{power_law_equ})$^{\\cite{chowdhury2017}}$ \\par\n\n\\begin{equation}\\label{power_law_equ}\n\\dot{\\gamma}^{(\\alpha)}=\\dot{\\gamma}_{0}\\left|\\frac{\\tau^{\\alpha}}{g^{\\alpha}}\\right|^{n} \\operatorname{sgn}\\left(\\tau^{\\alpha}\\right)\n\\end{equation}\n\nIn equ.(\\ref{power_law_equ}) $\\dot{\\gamma}^{(\\alpha)}$ is slip rate of the slip system $\\alpha$, $\\tau^{\\alpha}$ is the shear stress, $g^{\\alpha}$ is the internal state variable which depends on temperature.\n\nPlasticity is mediated through dislocation. The basic types of dislocations are edge, screw and mixed dislocation. During plastic deformation, dislocation motion will occur in multiple slip system simultaneously. This lead to the interaction of dislocation with dislocations of other slip systems. This collective dislocation dynamics plays an important role in understanding the material response like fatigue, creep, yield.$^{\\cite{Messerschmidt2010}}$ \n\nThe entanglement of different dislocation generate a complex stress field. These complex stress field creates a low energy barriers which act as obstacles for dislocation movement having long range interactions. This complex system of interaction leads to the formation of dislocation avalanches. Dislocation avalanches are the basic mechanism of plastic flow in solids at the nano-scale. Dislocation avalanches are also associated with strain bursts which is a sudden increase in strain rate.\nThey follow power law distribution.\n$^{\\cite{Papanikolaou_2017}}$\n\nA comprehensive overview on dislocation avalanche physics and the phenomena leading to strain bursts in crystal plasticity is discussed further.\n\n\n\n\n", "meta": {"hexsha": "8dc42bbccbc717cbbeb80b059360384261f84cc0", "size": 2195, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Document/Introduction.tex", "max_stars_repo_name": "viswambhar-yasa/IGTO", "max_stars_repo_head_hexsha": "03001db03b17d1d2120740b9d3d7f0efe1f93faf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-11-23T15:55:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-15T17:47:19.000Z", "max_issues_repo_path": "Document/Introduction.tex", "max_issues_repo_name": "bhan5426/IGTO", "max_issues_repo_head_hexsha": "03001db03b17d1d2120740b9d3d7f0efe1f93faf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Document/Introduction.tex", "max_forks_repo_name": "bhan5426/IGTO", "max_forks_repo_head_hexsha": "03001db03b17d1d2120740b9d3d7f0efe1f93faf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-12-27T01:21:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T10:50:31.000Z", "avg_line_length": 95.4347826087, "max_line_length": 493, "alphanum_fraction": 0.8, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3499320008841906}}
{"text": "  \n%% \\listfiles\n\\documentclass[apj]{emulateapj}\n%\\documentclass[preprint2,12pt]{emulateapj}\n%% \\usepackage{natbib}\n\\usepackage{graphicx}\n\\usepackage{epsfig}\n\\usepackage{amssymb,amsmath}\n\\usepackage{array}\n\\usepackage{threeparttable}\n\\usepackage{hyperref,graphicx}    \n\n\\doublespace\n\n%definitions\n\\newcommand{\\Msol}{${\\rm M_{\\sun}}$}\n\n\n%% Editing markup...\n\\usepackage{color}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% WARNING: This LaTeX block was generated automatically by authors.py\n% Do not change by hand: your changes will be lost.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n% --------------------- Ancillary information ---------------------\n\\shortauthors{SURP et al.}\n\\shorttitle{CITA Final Project}\n\n\n\n\n\\begin{document}\n\n\\title{CITA Final Project: Introduction to Galpy}\n %% ---------\n \n\\author{Yumna Arshad}\n%\\altaffiltext{1}{CITA, University of Toronto}\n \n\\section{Introduction}\nMy final project aims to introduce the methods of galpy, a module in python used for modelling the orbital dynamics of objects in the galaxy. \nThe project consists of 2 parts. \nThe first part is an introductory approach to galpy and focuses on specifically learning how to use both potential and orbit objects from the module as well as the various methods associated with them.\nThe second part consists of modelling the accretion of a globular cluster, that is initially bound to a satellite galaxy of the Milky Way, onto the Milky Way galaxy itself. \n\n\n\\section{Part 1: Intro to Galpy Methods}\n\nFor this part of the project there are 3 separate tasks: 1) plotting rotation curve of MW galaxy, 2) integrating orbit of Sun and 3) integrating orbit of a specific tidal stream named GD -1.\n\n\n\\subsection{Rotation Curve of MW Galaxy}\nTo plot the rotation curve of the MW galaxy I created 3 different potential instances corresponding to the potential of the disk, bulge and halo separately and plotted them on one plot using the plotRotcurve method. Then I summed up all the potentials to create the overall galactic rotation curve which peaks at around 225 km/s and slowly declines afterward, this is the sum of the bulge, disk and halo potentials.\nA plot of these rotation curves can be seen in Fig.\\ref{fig:Q1_rot_curve}.\n\n\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=1.0\\columnwidth]{Q1a.pdf}\n    \\caption{Plot of the rotation curve of the Milky Way Galaxy including its labelled components: bulge, halo and disk.}\n    \\label{fig:Q1_rot_curve}\n\\end{figure}\n\n\\subsection{Orbit of Sun in MW Galaxy}\nTo plot the orbit of the Sun in the MW Galaxy I initialized an Orbit instance and integrated it for 10 Gyr using the MW potential in part 1 to properly model the orbit.\nI used the plot method of the sun orbit object to display the plot. \nA figure of this plot is shown in Fig.\\ref{fig:Q1_Sun}\n\n\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=1.0\\columnwidth]{Q1b.pdf}\n    \\caption{Plot of the orbit of the Sun in Milky Way potential for 10 Gyr (integrated forward). The orbit is plotted as: vertical height above plane of galaxy in kpc as a function of galactocentric radius in kpc.}\n    \\label{fig:Q1_Sun}\n\\end{figure}\n\n\n\n\\subsection{GD-1 Tidal Stream}\nThe path of GD-1 tidal stream in the sky is plotted by: initializing an orbit object with the given coordinates for the stream as specified in paper by Bovy and Webb \\cite{GD-1}.\nFigures showing the GD-1 stream in declination vs right ascension are shown in Fig.\\ref{fig:Q1_radec_f} (integrated forwards) and in Fig.\\ref{fig:Q1_radec_b} (integrated backwards).\nFigures showing the GD-1 stream in distance (from the Sun) vs right ascension are shown in Fig.\\ref{fig:Q1_radist_f} (integrated forwards) and in Fig.\\ref{fig:Q1_radist_b} (integrated backwards).\nFor all 4 orbits, the integration period is 50 Myr either forwards or backwards in time.\n\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=1.0\\columnwidth]{Q1c_1.pdf}\n    \\caption{Tidal stream GD-1's declination vs right ascension integrated forwards in time.}\n    \\label{fig:Q1_radec_f}\n\\end{figure}\n\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=1.0\\columnwidth]{Q1c_3.pdf}\n    \\caption{Tidal stream GD-1's declination vs right ascension integrated backwards in time.}\n    \\label{fig:Q1_radec_b}\n\\end{figure}\n\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=1.0\\columnwidth]{Q1c_2.pdf}\n    \\caption{Tidal stream GD-1's distance (from Sun) vs right ascension integrated forwards in time.}\n    \\label{fig:Q1_radist_f}\n\\end{figure}\n\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=1.0\\columnwidth]{Q1c_4.pdf}\n    \\caption{Tidal stream GD-1's distance (from Sun) vs right ascension integrated backwards in time.}\n    \\label{fig:Q1_radist_b}\n\\end{figure}\n\n\n\\section{Part 2: Stimulating Accretion of Globular Cluster onto Milky Way}\n\n\\subsection{Method}\nTo stimulate the accretion of a globular cluster onto the Milky Way Galaxy: the first thing I did was import and integrate the orbits of all the satellite galaxies of the Milky Way and plotted their apocenters and pericenters vs their current galactocentric radii. \nUsing these plots, the satellite with the smallest pericenter is identified to be TucanaIII and the time at which it 1st reaches its smallest galactocentric radius is -1.77 Gyr (i.e 1.77 Gyr in the past). This satellite will be used to model the accretion of the globular cluster. \nTo begin with, the orbit of TucanaIII integrated backwards for 10 Gyr is plotted with the effects of dynamical friction included. Dynamical friction is implemented using an instance of the ChandrasekharDynamicalFrictionForce with the density of the MW potential (imported using MWPotential2014 which is a list of potential objects making up the Milky Way) and given satellite parameters such as mass and size. Then, the orbit of the satellite is integrated back in time using the combined potential of the MW and the dynamical friction. This orbit is shown in Fig.\\ref{fig:Q2_cdf}. The radius of the satellite at 10 Gyr is determined to be 240.6 kpc.\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=1.0\\columnwidth]{Q2c.pdf}\n    \\caption{Plot showing the orbit of TucanaIII satellite galaxy, the satellite with the smallest pericenter radius, integrated backwards in time for 10 Gyr. The orbit is shown in radius vs time.}\n    \\label{fig:Q2_cdf}\n\\end{figure}\n\nA star-cluster is then initialized to be on a circular orbit of radius 4 kpc within the satellite galaxy, the orbital velocity can be determined using Eq.\\ref{equation: v_circ} and this gives a velocity of $\\approx$ 328 km/s.\n\n\\begin{equation}\n     v = \\sqrt{\\frac{GM}{r}}\n    \\label{equation: v_circ}\n\\end{equation}\n\nAs well, the satellite + cluster system are moved to the radius determined above (i.e. 240.6 kpc). To model the orbit of the satellite characerized by a Hernquist potential, a MovingObjectPotential object instance is created with the associated orbit being that of the satellite as previously determined, i.e. orbit of TucanaIII. \nFinally, the orbits of both the satellite and the star-cluster are integrated and plotted. The results are shown in Fig.\\ref{fig:Q2_satellite} and Fig.\\ref{fig:Q2_star_cluster}, respectively. \n\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=1.0\\columnwidth]{Q2_sat.pdf}\n    \\caption{Plot showing the orbit of the satellite galaxy integrated forwards in time for 12 Gyr. The orbit is shown in radius vs time and includes the effects of dynamical friction.}\n    \\label{fig:Q2_satellite}\n\\end{figure}\n\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=1.0\\columnwidth]{Q2_sc.pdf}\n    \\caption{Plot showing the orbit of the star-cluster system within the satellite galaxy for 12 Gyr. Note that r is the galactocentric distance, plotted as a function of time.}\n    \\label{fig:Q2_star_cluster}\n\\end{figure}\n\n\n\n\n\\subsection{Comment on Orbits of Star Cluster and Satellite Galaxy}\nThe orbit of the satellite galaxy as shown in Fig.\\ref{fig:Q2_satellite} is the same as the orbit in Fig.\\ref{fig:Q2_cdf} since it initially starts at its position at -10 Gyr and follows the same path forward in time as it did to go back.\nThe star cluster's orbit within the satellite follows a bound orbit such that it becomes accreted onto the Milky Way galaxy as the satellite spirals in and remains bound to the MW galaxy.\n\n\n\\begin{thebibliography}{99}\n\n\\bibitem{GD-1}\nJ. J. Webb and J. Bovy, “Searching for the GD-1 stream progenitor inGaiaDR2 with directN-body simulations,” Monthly Notices of the Royal Astronomical Society, vol. 485, no. 4, pp. 5929–5938, 2019.\n\n\n\n\\end{thebibliography}\n\n\n\\end{document}\n\n", "meta": {"hexsha": "116e3535f65e6c86fdc474a7382c45341a570e3f", "size": 8652, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Final Project/main.tex", "max_stars_repo_name": "yumnaarshad/CTA200", "max_stars_repo_head_hexsha": "abc1ed35e39365d9344342abfe201586428c1cac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Final Project/main.tex", "max_issues_repo_name": "yumnaarshad/CTA200", "max_issues_repo_head_hexsha": "abc1ed35e39365d9344342abfe201586428c1cac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Final Project/main.tex", "max_forks_repo_name": "yumnaarshad/CTA200", "max_forks_repo_head_hexsha": "abc1ed35e39365d9344342abfe201586428c1cac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.1590909091, "max_line_length": 650, "alphanum_fraction": 0.753814147, "num_tokens": 2253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.349931999626837}}
{"text": "\\documentclass[12pt,a4paper]{article}\n\n\\usepackage[utf8]{inputenc}\n\\usepackage[english]{babel}\n%\\usepackage[english]{isodate}\n%\\usepackage[parfill]{parskip}\n\n\\usepackage{graphicx}\n\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{newtxtext,newtxmath}\n\\usepackage{bm}\n\\usepackage{listings}\n\\usepackage{color}\n\\usepackage{url}\n\\usepackage{intmacros}\n\\usepackage{syntax}\n\\usepackage{manual}\n\n\\lstset{%\n%    backgroundcolor=\\color{yellow!20},%\n    basicstyle=\\ttfamily,%\n    %numbers=left, numberstyle=\\tiny, stepnumber=2, numbersep=5pt,%\n    numbers=left, numberstyle=\\tiny, numbersep=5pt,%\n\tframe=single,%\n    }%\n\n\\lstset{emph={%  \n    let, var, init, at, wait, once, when, goto, then, end, prop, param%\n    },emphstyle={\\color{blue}\\bfseries}%\n}\n\n\\newcommand{\\LNCS}[1]{\\textit{LNCS}~#1}\n\\newcommand{\\ENTCS}[1]{\\textit{ENTCS}~#1}\n\n\\begin{document}\n\n\\title{HySIA Manual (version~0.1.1)}\n\\author{Daisuke Ishii \\quad \\texttt{dsksh@acm.org}}\n\n\\maketitle\n\n\\setlength{\\grammarparsep}{8pt plus 1pt minus 1pt} % increase separation between rules\n\\setlength{\\grammarindent}{8em} % increase separation between LHS/RHS \n\n\\emph{HySIA} is a reliable simulator and verifier for hybrid systems.\n%\nHySIA supports nonlinear \\emph{hybrid automata} (HAs) whose ODEs, guards, and reset functions are specified with nonlinear expressions. It assumes a deterministic class of HA; a transition to another location happens whenever a guard condition holds.\n%\nMain functionalities of HySIA are as follows:\n\n\\textbf{Simulation}.\n%\nHySIA simulates an HA based on interval analysis;\nit computes an overapproximation of a bounded trajectory that is composed of \\emph{boxes} (i.e., closed interval vectors) and \\emph{parallelotopes} (linear transformation of boxes).\n%\nIntensive use of interval analysis techniques distinguishes HySIA from other reachability analysis tools.\n%\nFirst, the simulation process carefully reduces \\emph{wrapping effect} that can expand an enclosure interval. As a result, HySIA is able to simulate HA for more number of steps than other overapproximation-based tools; e.g., it can simulate a periodic bouncing ball for more than a thousand steps.\n%\nSecond, HySIA assures the soundness of each interval computation, so that the resulting overapproximation is verified to contain a theoretical trajectory.\n%This verification often fails, e.g., when an ODE is \\emph{stiff} or when a trajectory and a guard are close to tangent.\n%Thanks to this \\emph{quasi-complete} manner, the simulation process of HySIA is decidable and performs efficiently.\n%\nSee Reference~\\cite{GI2016} for details of the underlying method.\n\n\\textbf{Monitoring}.\n%\nHySIA takes a temporal property as an input and monitors whether a simulated trajectory satisfies the property; otherwise, HySIA computes (an interval overapproximation of) a robustness signal for the property.\nThe verification process is based on a monitoring procedure of the \\emph{signal temporal logic} (STL) formulas~\\cite{Maler2004}, which is extended to handle overapproximation of trajectories.\n%The soundness of interval computation is again utilized here to evaluate the logical negation against an approximated trajectory.\n%\nSee Reference~\\cite{Ishii2016IEICE} for more details.\n\n\n\\section{Short Tutorial}\n\nHySIA provides a specification language for hybrid automata and temporal logic properties.\nAn HA is simulated and analyzed about a property using the \\verb|hysia| command.\nThis section exemplifies the modeling, simulation, and verification of an HA using HySIA.\n\n\\subsection{Modeling Hybrid Automata}\n\nBelow is an example specification that describes a simple bouncing ball model (\\texttt{bb.ha}):\n\\begin{lstlisting}\n(* first part *)\nlet   g = 1\nlet   c = 0.9\nlet   pertb = [-1e-5, 1e-5]\n\n(* second part *)\nvar   y, vy\n\ninit  Loc, 1+pertb, 0+pertb\n\nat Loc wait vy, -g\n      once (y, -vy) goto Loc then y, -c*vy\nend\n\n(* third part *)\nparam order = 20\nparam t_max = 100\nparam dump_interval = 0.1\n\\end{lstlisting}\n%\nThe specification consists of three parts.\nThe first part (Lines~1--4) defines three constants \\verb|g|, \\verb|c|, and \\verb|pertb| to be used in the second part.\nThe values of constants can be either real values or intervals.\n\nThe second part (Lines~6--13) describes an HA.\nLine~7 declared the state variables \\verb|y| and \\verb|vy| of the HA, which are evaluated over timeline.\nLine~9 describes the initial state as a comma-separated list of a location and values for each state variable.\nLines~11--13 defines a location named \\verb|Loc|.\nAfter the keyward \\verb|wait|, the derivatives of the state variable are specified as $\\frac{d}{dt}\\mathtt{y} = \\mathtt{vy}$ and $\\frac{d}{dt}\\mathtt{vy} = -\\mathtt{g}$.\nAt Line~12, an inter-location transition is specified.\nThe tuple after \\verb|once| tells that the guard condition for this transition is $\\mathtt{y} = 0 ~\\land~ \\mathtt{vy} > 0$. (Only the left-hand side of the implicit form is described.)\nWhenever the guard is satisfied, an execution will transit to the same location \\verb|Loc| with a reset of the state variables as $\\mathtt{y} := \\mathtt{y}$ and $\\mathtt{vy} := -\\mathtt{c}\\,\\mathtt{vy}$.\n\nThe last part (Lines~15--18) configures some parameters of the simulator implementation, i.e., the order \\verb|order| of Taylor coefficient expansion, the time horizon \\verb|t_max| of a continuous state evolution, and \\verb|dump_interval| that bounds the step size when computing a dumped data.\n\nIn general, an HA consists of multiple locations. The bouncing ball system can be modeled with two locations by modelling the second part as follows: %(\\texttt{bb1.ha}):\n\\begin{lstlisting}\ninit  Fall, 1+pertb, -0+pertb\n\nat Fall wait vy, -g\n      once (y, vy) goto Rise then y, -c*vy\nend\n\nat Rise wait vy, -g\n      once (vy, -y) goto Fall then y, vy\nend\n\\end{lstlisting}\n\n\\subsection{Simulation of a Model}\n\nOnce a specification is prepared, a user can simulate the model for 10 transitions with the following command:\n\\begin{verbatim}\n$ hysia bb.ha -n 10 -dump\n\\end{verbatim}\nThe option \\verb|-dump| let HySIA to output the result of the simulation to the file \\verb|pped.dat| in a JSON format.\nThe output data consists of a set of \\emph{boxes} (interval vectors) that encloses the trajectories of the HA.\n(In this example, the interval value \\verb|pertb| allows perturbation of trajectories; these trajectories are enclosed within the boxes.)\nThe result can be visualized as shown in Figure~\\ref{f:bb}.\n\n\\begin{figure}[t]\n\\centering\n\\includegraphics[width=0.8\\linewidth]{bb.eps}\n\\caption{Dumped trajectory enclosure of the bouncing ball example}\n\\label{f:bb}\n\\end{figure}\n\nSimulation and verification of HySIA are all computed with validated interval analysis.\nThus, a resulting interval enclosure of a system's state expands as longer the simulation length and more the \\emph{wrapping effect} occurs.\nHowever, thanks to the underlying \\emph{parallelotope}-based simulation method for wrapping effect reduction, HySIA is able to simulate a large number of jumps for various HA.\nIndeed, for the bouncing ball model, when we modify the parameter values as \\verb|c = 1| and \\verb|pertb = 0|, HySIA can simulate for more than a thousand steps.\n\nAs we have seen so far, HySIA allows models to involve some uncertainties derived by interval values.\nHySIA computes (the overapproximation of) the reachable region with respect to the uncertainties.\nHowever, here we may encounter a drawback of HySIA; a simulation is not always successful but may result in an error.\n%\nWhen we modify the value of \\verb|pertb| to a slightly large interval \\verb|[-1e-4, 1e-4]| and run a simulation, \\verb|hysia| will output as follows:\n\\begin{verbatim}\n$ hysia bb.ha -n 10 -dump\nstep 0 (0.000000 < inf) at Loc\nstep 1 (1.414043 < inf) at Loc\nstep 2 (3.959155 < inf) at Loc\nstep 3 (6.249714 < inf) at Loc\nstep 4 (8.310768 < inf) at Loc\nstep 5 (10.163552 < inf) at Loc\nstep 6 (11.809965 < inf) at Loc\nlibc++abi.dylib: terminating with uncaught exception of type std::\nruntime_error: zero in the derivative\nAbort trap: 6\n\\end{verbatim}\nThe simulation fails after the sixth jump. The output implies that HySIA fails in the detection of a discrete change because a state enclosure becomes too large.\nIn fact, in each detection, HySIA checks whether the orientation between the trajectory and the guard is regular enough so that it is sure that each trajectory within an enclosure satisfies the guard.\n\n\n\\subsection{Verification of STL Properties}\n\nHySIA provides a function for verifying properties described in the \\emph{signal temporal logic} (STL).\nFor example, we can add an STL property \n\\begin{lstlisting}\nprop G[0,10] F[0,1] y-0.3\n\\end{lstlisting}\nin the above mentioned model.\n(It should be added in between the second and third parts.)\nThe property intuitively claims that, for the duration of $10$ time units, the height of the ball (\\verb|y|) goes beyond $0.3$ (\\verb|y-0.3| is interpreted as $\\texttt{y} - 0.3 > 0$) within every duration of $1$ time unit.\n\nThe verification can be done with the following command:\n\\begin{verbatim}\n$ hysia bb.ha -a\n\\end{verbatim}\nThe \\verb|hysia| command calculates the \\emph{necessary} simulation length for the verification (in this case, 11 time units), performs a simulation, and evaluates the satisfiability of this property.\nAccordingly, the verification succeeds with the following output:\n\\begin{verbatim}\n$ hysia bb.ha -a\nstep 0 (0.000000 < 11.000000) at Loc\nstep 1 (1.414196 < 11.000000) at Loc\nstep 2 (3.959734 < 11.000000) at Loc\nstep 3 (6.250722 < 11.000000) at Loc\nstep 4 (8.312608 < 11.000000) at Loc\nstep 5 (10.168295 < 11.000000) at Loc\ntrue, 0.036239\n\\end{verbatim}\n\n\n\\section{Getting the Tool}\n\nThe HySIA tool can be obtained and used in three ways.\n\n\\subsection{Web Demonstration}\n\nA web demonstration site is available at:\n\\begin{quote}\n\\url{http://bit.ly/hysia}\n\\end{quote}\n%\nThrough a web browser, you can access a GUI, load the basic examples, modify the HA/STL specification, simulate, and verify the specification.\n\n\n\\subsection{Docker Image}\n\nFor those who are familier with \\emph{Docker},\\footnote{\\url{https://www.docker.com/}} Docker containers are available at: \n\\begin{quote}        \n\\url{https://hub.docker.com/r/dsksh/}\n\\end{quote}        \n\nThe image \\verb|dsksh/hysia-web| contains the server program for the web demonstration. A container can be launched by:\n\\begin{verbatim}\n$ docker run -p 8080:80 dsksh/hysia-web\n\\end{verbatim}\nThen, the server will be available at:\n\\begin{quote}\n\\url{http://localhost:8080}\n\\end{quote}\n\n\n\\subsection{Source Distribution}\n\nThe HySIA source code is distributed via GitHub:\n\\begin{quote}\n\\url{https://github.com/dsksh/hysia}.\n\\end{quote}\n\n\\subsubsection*{Requirements}\n\nIn addition to a standard UNIX-like environment, the following softwares are required to compile HySIA:\n\\begin{itemize}\n    \\item \\emph{C/C++ compiler}.\n        We have compiled with both \\verb|gcc| (versions~4.7.4–4.8.4) and \\verb|clang| (Apple LLVM version~8).\n        %\n    \\item \\emph{OCaml compiler}.\n        We have tested with versions~3.12–4.02.\n        %\n    \\item \\emph{CAPD library}.\\footnote{http://capd.ii.uj.edu.pl/}\n        HySIA is built on an old release of the CAPD-DynSys 3.0 library, which was distributed around 2014, and is not available on the official site.\n        A (slightly modified) source package is available at:\n        \\begin{quote}\\small\n        \\hspace{-4em}\n        \\url{https://www.dropbox.com/s/3uf7t2nsizfebno/capdDynSys-201406.zip}\n        \\end{quote}\n        %\n    \\item \\emph{Boost library}.\\footnote{http://www.boost.org/}\n        HySIA uses \\verb|shared_ptr|.\n        %\n    \\item \\emph{OUnit}.\\footnote{http://ounit.forge.ocamlcore.org/} Optional for test cases compilation.\n    \\item \\emph{Eliom}.\\footnote{http://ocsigen.org/eliom/} Optional for building the web application.\n\\end{itemize}\n\n\n\\subsubsection*{Build}\n\nIn the root directory of the source code, HySIA can be compiled with:\n\\begin{verbatim}\n$ ./configure; make\n\\end{verbatim}\n\nWhen compilation succeeds, the program file\n\\begin{verbatim}\nsrc_ocaml/hss.opt\n\\end{verbatim}\nis generated.\n\n\n\\section{Examples}\n\n\\subsection{Simple Rotation System}\n\nTBD.\n\n\\subsection{Bouncing Planet}\n\nTBD.\n\n\n\\section{Reference Manual}\n\n\\subsection{Command-Line Tool}\n\nThe basic syntax for the command-line execution is as follows:\n\\begin{grammar}\n<command> ::= `hysia' <options> <filename>\n\\end{grammar}\n%\nThe \\texttt{hysia} command accepts the following options:\n\\begin{description}\n\\item[\\texttt{-h}, \\texttt{-help}, or \\texttt{--help}] Displays a summary of the options accepted by the command.\n\\item[\\texttt{-n}] Specifies the number steps to simulate (default is $\\infty$).\n\\item[\\texttt{-t}] Specifies the max simulation time (default is $\\infty$).\n\\item[\\texttt{-a}] Decides the simulation length automatically from the STL property.\n\\item[\\texttt{-g}] Sets the debug flag.\n\\item[\\texttt{-dump}] Activates dumping plot to the file ``pped.dat.''\n\\item[\\texttt{-cm_thres}] Sets the threshold for character matrix selection.\n\\end{description}\n\nThe option \\texttt{-cm_thres} specifies the character matrix $B$ to be used in the parallelotope method (see the corresponding publication for the detail). It is selected as follows:\n\\begin{itemize}\n\t\\item $-1$: $B := (\\mathrm{mid}\\J) A$.\n\t\\item $0$: $B := I$ (i.e., identity matrix).\n\t\\item $1$: $B := \\mathrm{orthogonalize}((\\mathrm{mid}\\J) A)$.\n\t\\item $n > 1$ (default): \n\t\t\\[\n\t\t\tB := \\begin{cases}\n\t\t\t\t(\\mathrm{mid}\\J) A & \\text{if $\\kappa((\\mathrm{mid}\\J) A) < n$} \\\\\n\t\t\t\t\\mathrm{orthogonalize}((\\mathrm{mid}\\J) A) & \\text{otherwise.}\n\t\t\t\\end{cases}\n\t\t\\]\n\\end{itemize}\n\n\n\\subsection{Solving Parameters}\n\n\\begin{description}\n\\item[\\texttt{order}] Order of Taylor expansion.\n\\item[\\texttt{t_max}] Max time horizon assumed in the simulation of each step.\n\\item[\\texttt{h_min}] Min time CAPD integration can take.\n\\item[\\texttt{epsilon}] Specifies the precision of the event detection.\n\\item[\\texttt{dump_interval}] Sets the precision of the dumped flowpipe data.\n\\item[\\texttt{delta}] Parameter for the box inflation process.\n\\item[\\texttt{tau}] Parameter for the box inflation process.\n\\item[\\texttt{cm_thres}] Parameter for the character matrix selection.\n\\end{description}\n\n\n\\subsection{Specification Language}\n\nThis section describes the grammar of the specification language of HySIA.\nA specification consists of the definition of a hybrid automaton, an STL formula, and solving parameter configurations.\n\n\\subsubsection{Lexical conventions}\n\nThe lexical class of digits, letters, and identifiers is the following:\n\\begin{grammar}\n<digit> ::= [`0'--`9']\n\n<letter> ::= [`a'--`z' `A'--`Z']\n\n<id> ::= <letter> (<digit> | <letter> | `_')*\n\\end{grammar}\n\nThe syntax of various numeral expressions is as follows:\n\\begin{grammar}\n<integer> ::= <digit>+\n\n<float> ::= \n%<digit>+ ~~|~~ <digit>+ `.' <digit>*\n<digit>+ ~ (`.' <digit>*)? ~ ( (`e'|`E') (`+'|`-')? <digit>+ )?\n%\\alt <digit>+ `.' <digit>* (`e'|`E')  <digit>+\n%\\alt <digit>+ (`e'|`E') <digit>+\n%\\alt <digit>+ (`e'|`E') (`+'|`-') <digit>+\n\n<float-pn> ::= <float> ~~|~~ `-' <float>\n\n<interval> ::= <interval-noun> ~|~ <float-pn>\n\n<interval-noun> ::= `(' <float-pn> `,' <float-pn> `)'\n\n<interval-list> ::= <interval> <interval-list-rest>\n\\alt `(' <interval> <interval-list-rest> `)'\n\n<interval-list-rest> ::= `,' <interval> <interval-list-rest> ~~|~~ <empty>\n\\end{grammar}\n\n\n\\noindent\n\\textbf{Comments.}\nComments are either enclosed between \\texttt{(*} and \\texttt{*)} (can be nested) or prefixed with \\texttt{\\#}.\n\n\n\\subsubsection{Toplevel syntax}\n\nThe syntax for the toplevel of specifications is the following:\n\\begin{grammar}\n<specification> ::= <statement>+ <property>? <solver-param>*\n\n<statement> ::= \n`let' <id> `=' <interval>\n\\alt `let' <id> `=' `R' <float>\n\\alt `var' <var-list>\n\\alt `init' <expr-list>\n\\alt `at' <id> <flow> <invariant>? <edge>* `end'\n\n<property> ::= `prop' <stl-formula>\n\n<solver-param> ::= `param' <id> `=' <float-pn>\n\n\n<flow> ::= `wait' <expr-list>\n\n<invariant> ::= `inv' <expr-list>\n\n<edge> ::= (`when' | `once') `(' <expr> `,' <expr-list> `)' `goto' <id> `then' <expr-list>\n\\end{grammar}\n\n\n\\subsubsection{Expressions}\n\nThe operators and function application in expressions have the priorities and associativities as shown in the table below (from lowest to greatest priority):\n\\begin{table}[ht]\n\t\\centering\n\t%\\caption{\\label{t:operators} Terms} \n\t%\\small\n    \\begin{tabular}{|l|l|} \\hline\n\t\tconstruct & associativity \\\\\n\t\t\\hline\n\t\t`\\texttt{+}', `\\texttt{-}' & left \\\\\n\t\t`\\texttt{*}', `\\texttt{/}' & left \\\\\n\t\tfunction application & left \\\\\n\t\t`\\texttt{\\^}', `\\texttt{-}' (unary) & --- \\\\\n\t\t\\hline\n\t\\end{tabular}\n\\end{table}\n\nThe syntax for expressions is the following:\n\\begin{grammar}\n<expr> ::= <expr> `+' <expr> ~~|~~ <expr> `-' <expr>\n\\alt <expr> `*' <expr> ~~|~~ <expr> `/' <expr>\n\\alt `-' <expr> ~~|~~ <expr> `^' <integer>\n\\alt <function> <expr>\n\\alt <id> ~~|~~ <interval>\n\\alt `(' <expr> `)' \n\n<function> ::= `sqrt' | `exp' | `log' | `sin' | `cos' | `atan' | `asin' | `acos'\n\n<expr-list> ::= <expr> <expr-list-rest> ~~|~~ `(' <expr> <expr-list-rest> `)'\n\n<expr-list-rest> ::= `,' <expr> <expr-list-rest> ~|~ <empty>\n\\end{grammar}\n\n\n\\subsubsection{STL formulae}\n\nThe operators in formulae have the following priorities and associativities:\n\\begin{table}[ht]\n\t\\centering\n\t%\\caption{\\label{t:operators} Terms} \n\t%\\small\n    \\begin{tabular}{|l|l|} \\hline\n\t\tconstruct & associativity \\\\\n\t\t\\hline\n\t\t`\\texttt{->}' & right \\\\\n\t\t`\\texttt{|}' & right \\\\\n\t\t`\\texttt{\\&}' & right \\\\\n\t\t`\\texttt{U} [$\\cdot$,$\\cdot$]' & right \\\\\n\t\t`\\texttt{G} [$\\cdot$,$\\cdot$]', `\\texttt{F} [$\\cdot$,$\\cdot$]' & --- \\\\\n\t\t`\\texttt{!}' & --- \\\\\n\t\t\\hline\n\t\\end{tabular}\n\\end{table}\n\nThe syntax for formulae is the following:\n\\begin{grammar}\n<stl-formula> ::= `true' ~~|~~ `false'\n\\alt <id> ~~|~~ <expr>\n\\alt `!' <stl-formula>\n\\alt <stl-formula> (`&'|`|'|`->') <stl-formula>\n\\alt (`F'|`G') <noun-interval> <stl-formula>\n\\alt <stl-formula> `U' <noun-interval> <stl-formula>\n\\alt `(' <stl-formula> `)'\n\\end{grammar}\n\n\n\\begin{thebibliography}{99}\n\\bibitem{Donze2013}\n    A. Donz\\'{e}, T. Ferr\\`{e}re, O. Maler: \n    {Efficient Robust Monitoring for STL},\n    Proc. of CAV, pp.~264--279, \\LNCS{8044}, 2013.\n\n\\bibitem{GI2016}\n    A. Goldsztejn, D. Ishii: \n    {A Parallelotope Method for Hybrid System Simulation},\n    Reliable Computing, 23:163--185, 2016.\n\n\\bibitem{Ishii2016IEICE}\n    D. Ishii, N. Yonezaki, A. Goldsztejn: \n    {Monitoring Temporal Properties using Interval Analysis}. \n    IEICE Transactions on Fundamentals of Electronics, Communications and Computer Sciences,\n    E99-A, 2016.\n\n\\bibitem{Ishii2015-NSV}\n    D. Ishii, N. Yonezaki, A. Goldsztejn: \n    {Monitoring Bounded LTL Properties Using Interval Analysis}. \n    Proc. of 8th International Workshop on Numerical Software Verification (NSV), \n    \\ENTCS{317}, pp.~85--100, 2015.\n\n\\bibitem{Maler2004}\n    O. Maler and D. Nickovic:\n    Monitoring Temporal Properties of Continuous Signals,\n    Proc. of FORMATS, pp.~152--166, \\LNCS{3253}, 2004.\n\\end{thebibliography}\n\n\\end{document}\n", "meta": {"hexsha": "85cfe79256af17609d4e2ffc1b108b5b57e5e59e", "size": 19017, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/manual.tex", "max_stars_repo_name": "dsksh/hysia", "max_stars_repo_head_hexsha": "5c3dd4d1b0e3946ad7a7a81e0b7c83154e69a71c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/manual.tex", "max_issues_repo_name": "dsksh/hysia", "max_issues_repo_head_hexsha": "5c3dd4d1b0e3946ad7a7a81e0b7c83154e69a71c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/manual.tex", "max_forks_repo_name": "dsksh/hysia", "max_forks_repo_head_hexsha": "5c3dd4d1b0e3946ad7a7a81e0b7c83154e69a71c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-31T10:21:01.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-31T10:21:01.000Z", "avg_line_length": 36.9262135922, "max_line_length": 297, "alphanum_fraction": 0.7136246516, "num_tokens": 5609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3497575550127163}}
{"text": "\n\\documentclass{article}\n\n\\usepackage{verbatim}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{array}\n\\usepackage{fullpage}\n\n\\author{B.~Barras}\n\\title{An introduction to syntax of Coq V8}\n\n%% Le _ est un caractère normal\n\\catcode`\\_=13\n\\let\\subscr=_\n\\def_{\\ifmmode\\sb\\else\\subscr\\fi}\n\n\\def\\NT#1{\\langle\\textit{#1}\\rangle}\n\\def\\NTL#1#2{\\langle\\textit{#1}\\rangle_{#2}}\n\\def\\TERM#1{\\textsf{\\bf #1}}\n\n\\newenvironment{transbox}\n  {\\begin{center}\\tt\\begin{tabular}{l|ll} \\hfil\\textrm{V7} & \\hfil\\textrm{V8} \\\\ \\hline}\n  {\\end{tabular}\\end{center}}\n\\def\\TRANS#1#2\n  {\\begin{tabular}[t]{@{}l@{}}#1\\end{tabular} & \n   \\begin{tabular}[t]{@{}l@{}}#2\\end{tabular} \\\\}\n\\def\\TRANSCOM#1#2#3\n  {\\begin{tabular}[t]{@{}l@{}}#1\\end{tabular} & \n   \\begin{tabular}[t]{@{}l@{}}#2\\end{tabular} & #3 \\\\}\n\n\\begin{document}\n\n\\maketitle\n\nThe goal of this document is to introduce by example to the new syntax of\nCoq. It is strongly recommended to read first the definition of the new\nsyntax, but this document should also be useful for the eager user who wants\nto start with the new syntax quickly.\n\n\n\\section{Changes in lexical conventions w.r.t. V7}\n\n\\subsection{Identifiers}\n\nThe lexical conventions changed: \\TERM{_} is not a regular identifier\nanymore. It is used in terms as a placeholder for subterms to be inferred\nat type-checking, and in patterns as a non-binding variable.\n\nFurthermore, only letters (unicode letters), digits, single quotes and\n_ are allowed after the first character.\n\n\\subsection{Quoted string}\n\nQuoted strings are used typically to give a filename (which may not\nbe a regular identifier). As before they are written between double\nquotes (\"). Unlike for V7, there is no escape character: characters\nare written normaly but the double quote which is doubled.\n\n\\section{Main changes in terms w.r.t. V7}\n\n\n\\subsection{Precedence of application}\n\nIn the new syntax, parentheses are not really part of the syntax of\napplication. The precedence of application (10) is tighter than all\nprefix and infix notations. It makes it possible to remove parentheses\nin many contexts.\n\n\\begin{transbox}\n\\TRANS{(A x)->(f x)=(g y)}{A x -> f x = g y}\n\\TRANS{(f [x]x)}{f (fun x => x)}\n\\end{transbox}\n\n\n\\subsection{Arithmetics and scopes}\n\nThe specialized notation for \\TERM{Z} and \\TERM{R} (introduced by\nsymbols \\TERM{`} and \\TERM{``}) have disappeared. They have been\nreplaced by the general notion of scope.\n\n\\begin{center}\n\\begin{tabular}{l|l|l}\ntype & scope name & delimiter \\\\\n\\hline\ntypes & type_scope & \\TERM{T} \\\\\n\\TERM{bool} & bool_scope & \\\\\n\\TERM{nat} & nat_scope & \\TERM{nat} \\\\\n\\TERM{Z} & Z_scope & \\TERM{Z} \\\\\n\\TERM{R} & R_scope & \\TERM{R} \\\\\n\\TERM{positive} & positive_scope & \\TERM{P}\n\\end{tabular}\n\\end{center}\n\nIn order to use notations of arithmetics on \\TERM{Z}, its scope must be opened with command \\verb+Open Scope Z_scope.+ Another possibility is using the scope change notation (\\TERM{\\%}). The latter notation is to be used when notations of several scopes appear in the same expression.\n\nIn examples below, scope changes are not needed if the appropriate scope\nhas been opened. Scope nat_scope is opened in the initial state of Coq.\n\\begin{transbox}\n\\TRANSCOM{`0+x=x+0`}{0+x=x+0}{\\textrm{Z_scope}}\n\\TRANSCOM{``0 + [if b then ``1`` else ``2``]``}{0 + if b then 1 else 2}{\\textrm{R_scope}}\n\\TRANSCOM{(0)}{0}{\\textrm{nat_scope}}\n\\end{transbox}\n\nBelow is a table that tells which notation is available in which\nscope. The relative precedences and associativity of operators is the\nsame as in usual mathematics. See the reference manual for more\ndetails. However, it is important to remember that unlike V7, the type\noperators for product and sum are left associative, in order not to\nclash with arithmetic operators.\n\n\\begin{center}\n\\begin{tabular}{l|l}\nscope & notations \\\\\n\\hline\nnat_scope & $+ ~- ~* ~< ~\\leq ~> ~\\geq$ \\\\\nZ_scope & $+ ~- ~* ~/ ~\\TERM{mod} ~< ~\\leq ~> ~\\geq ~?=$ \\\\\nR_scope & $+ ~- ~* ~/ ~< ~\\leq ~> ~\\geq$ \\\\\ntype_scope & $* ~+$ \\\\\nbool_scope & $\\TERM{\\&\\&} ~\\TERM{$||$} ~\\TERM{-}$ \\\\\nlist_scope & $\\TERM{::} ~\\TERM{++}$\n\\end{tabular}\n\\end{center}\n(Note: $\\leq$ is written \\TERM{$<=$})\n\n\n\n\\subsection{Notation for implicit arguments}\n\nThe explicitation of arguments is closer to the \\emph{bindings} notation in\ntactics. Argument positions follow the argument names of the head constant.\n\n\\begin{transbox}\n\\TRANS{f 1!t1 2!t2}{f (x:=t1) (y:=t2)}\n\\TRANS{!f t1 t2}{@f t1 t2}\n\\end{transbox}\n\n\n\\subsection{Universal quantification}\n\nThe universal quantification and dependent product types are now\nmaterialized with the \\TERM{forall} keyword before the binders and a\ncomma after the binders.\n\nThe syntax of binders also changed significantly. A binder can simply be\na name when its type can be inferred. In other cases, the name and the type\nof the variable are put between parentheses. When several consecutive\nvariables have the same type, they can be grouped. Finally, if all variables\nhave the same type parentheses can be omitted.\n\n\\begin{transbox}\n\\TRANS{(x:A)B}{forall (x:~A), B ~~\\textrm{or}~~ forall x:~A, B}\n\\TRANS{(x,y:nat)P}{forall (x y :~nat), P ~~\\textrm{or}~~ forall x y :~nat, P}\n\\TRANS{(x,y:nat;z:A)P}{forall (x y :~nat) (z:A), P}\n\\TRANS{(x,y,z,t:?)P}{forall x y z t, P}\n\\TRANS{(x,y:nat;z:?)P}{forall (x y :~nat) z, P}\n\\end{transbox}\n\n\\subsection{Abstraction}\n\nThe notation for $\\lambda$-abstraction follows that of universal\nquantification. The binders are surrounded by keyword \\TERM{fun}\nand $\\Rightarrow$ (\\verb+=>+ in ascii).\n\n\\begin{transbox}\n\\TRANS{[x,y:nat; z](f a b c)}{fun (x y:nat) z => f a b c}\n\\end{transbox}\n\n\n\\subsection{Pattern-matching}\n\nBeside the usage of the keyword pair \\TERM{match}/\\TERM{with} instead of\n\\TERM{Cases}/\\TERM{of}, the main change is the notation for the type of\nbranches and return type. It is no longer written between \\TERM{$<$ $>$} before\nthe \\TERM{Cases} keyword, but interleaved with the destructured objects.\n\nThe idea is that for each destructured object, one may specify a variable\nname to tell how the branches types depend on this destructured objects (case\nof a dependent elimination), and also how they depend on the value of the\narguments of the inductive type of the destructured objects. The type of\nbranches is then given after the keyword \\TERM{return}, unless it can be\ninferred.\n\nMoreover, when the destructured object is a variable, one may use this\nvariable in the return type.\n\n\\begin{transbox}\n\\TRANS{Cases n of\\\\~~ O => O \\\\| (S k) => (1) end}{match n with\\\\~~ 0 => 0 \\\\| (S k) => 1 end}\n\\TRANS{Cases m n of \\\\~~0 0 => t \\\\| ... end}{match m, n with \\\\~~0, 0 => t \\\\| .. end}\n\\TRANS{<[n:nat](P n)>Cases T of ... end}{match T as n return P n with ... end}\n\\TRANS{<[n:nat][p:(even n)]\\~{}(odd n)>Cases p of\\\\~~ ... \\\\end}{match p in even n return \\~{} odd n with\\\\~~ ...\\\\end}\n\\end{transbox}\n\n\n\\subsection{Fixpoints and cofixpoints}\n\nAn easier syntax for non-mutual fixpoints is provided, making it very close\nto the usual notation for non-recursive functions. The decreasing argument\nis now indicated by an annotation between curly braces, regardless of the\nbinders grouping. The annotation can be omitted if the binders introduce only\none variable. The type of the result can be omitted if inferable.\n\n\\begin{transbox}\n\\TRANS{Fix plus\\{plus [n:nat] : nat -> nat :=\\\\~~ [m]...\\}}{fix plus (n m:nat) \\{struct n\\}: nat := ...}\n\\TRANS{Fix fact\\{fact [n:nat]: nat :=\\\\\n~~Cases n of\\\\~~~~ O => (1) \\\\~~| (S k) => (mult n (fact k)) end\\}}{fix fact\n  (n:nat) :=\\\\\n~~match n with \\\\~~~~0 => 1 \\\\~~| (S k) => n * fact k end}\n\\end{transbox}\n\nThere is a syntactic sugar for mutual fixpoints associated to a local\ndefinition:\n\n\\begin{transbox}\n\\TRANS{let f := Fix f \\{f [x:A] : T := M\\} in\\\\(g (f y))}{let fix f (x:A) : T := M in\\\\g (f x)}\n\\end{transbox}\n\nThe same applies to cofixpoints, annotations are not allowed in that case.\n\n\\subsection{Notation for type cast}\n\n\\begin{transbox}\n\\TRANS{O :: nat}{0 : nat}\n\\end{transbox}\n\n\\section{Main changes in tactics w.r.t. V7}\n\nThe main change is that all tactic names are lowercase. This also holds for\nLtac keywords.\n\n\\subsection{Ltac}\n\nDefinitions of macros are introduced by \\TERM{Ltac} instead of\n\\TERM{Tactic Definition}, \\TERM{Meta Definition} or \\TERM{Recursive\nDefinition}.\n\nRules of a match command are not between square brackets anymore.\n\nContext (understand a term with a placeholder) instantiation \\TERM{inst}\nbecame \\TERM{context}. Syntax is unified with subterm matching.\n\n\\begin{transbox}\n\\TRANS{match t with [C[x=y]] => inst C[y=x]}{match t with context C[x=y] => context C[y=x]}\n\\end{transbox}\n\n\\subsection{Named arguments of theorems}\n\n\\begin{transbox}\n\\TRANS{Apply thm with x:=t 1:=u}{apply thm with (x:=t) (1:=u)}\n\\end{transbox}\n\n\n\\subsection{Occurrences}\n\nTo avoid ambiguity between a numeric literal and the optionnal\noccurrence numbers of this term, the occurrence numbers are put after\nthe term itself. This applies to tactic \\TERM{pattern} and also\n\\TERM{unfold}\n\\begin{transbox}\n\\TRANS{Pattern 1 2 (f x) 3 4 d y z}{pattern (f x at 1 2) (d at 3 4) y z}\n\\end{transbox}\n\n\\section{Main changes in vernacular commands w.r.t. V7}\n\n\n\\subsection{Binders}\n\nThe binders of vernacular commands changed in the same way as those of\nfixpoints. This also holds for parameters of inductive definitions.\n\n\n\\begin{transbox}\n\\TRANS{Definition x [a:A] : T := M}{Definition x (a:A) : T := M}\n\\TRANS{Inductive and [A,B:Prop]: Prop := \\\\~~conj : A->B->(and A B)}%\n      {Inductive and (A B:Prop): Prop := \\\\~~conj : A -> B -> and A B}\n\\end{transbox}\n\n\\subsection{Hints}\n\nThe syntax of \\emph{extern} hints changed: the pattern and the tactic\nto be applied are separated by a \\TERM{$\\Rightarrow$}.\n\\begin{transbox}\n\\TRANS{Hint Extern 4 (toto ?) Apply lemma}{Hint Extern 4 (toto _) => apply lemma}\n\\end{transbox}\n\n\\end{document}\n", "meta": {"hexsha": "ae4b569b36ae2f1c717cb09046ae98a5a8999c90", "size": 9770, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "coq/dev/v8-syntax/memo-v8.tex", "max_stars_repo_name": "reichel3/TacTok", "max_stars_repo_head_hexsha": "c344e76263de04311af8a0030c07aec95d87f71c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-11-23T02:45:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T03:03:33.000Z", "max_issues_repo_path": "coq/dev/v8-syntax/memo-v8.tex", "max_issues_repo_name": "reichel3/TacTok", "max_issues_repo_head_hexsha": "c344e76263de04311af8a0030c07aec95d87f71c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-02-23T03:03:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-13T00:07:38.000Z", "max_forks_repo_path": "coq/dev/v8-syntax/memo-v8.tex", "max_forks_repo_name": "reichel3/TacTok", "max_forks_repo_head_hexsha": "c344e76263de04311af8a0030c07aec95d87f71c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-01-19T17:56:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T04:39:41.000Z", "avg_line_length": 34.0418118467, "max_line_length": 284, "alphanum_fraction": 0.7022517912, "num_tokens": 3005, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.34975754789168645}}
{"text": "\\documentclass[11pt, oneside]{article}   \t% use \"amsart\" instead of \"article\" for AMSLaTeX format\n\\usepackage{geometry}                \t\t% See geometry.pdf to learn the layout options. There are lots.\n\\geometry{letterpaper}                   \t\t% ... or a4paper or a5paper or ... \n%\\geometry{landscape}                \t\t% Activate for rotated page geometry\n%\\usepackage[parfill]{parskip}    \t\t% Activate to begin paragraphs with an empty line rather than an indent\n\\usepackage{graphicx}\t\t\t\t% Use pdf, png, jpg, or eps§ with pdflatex; use eps in DVI mode\n\t\t\t\t\t\t\t\t% TeX will automatically convert eps --> pdf in pdflatex\t\t\n\\usepackage{amssymb}\n\\usepackage{amsmath}\n\\PassOptionsToPackage{hyphens}{url} % url is loaded by hyperref\n\\usepackage[unicode=true]{hyperref}\n\\usepackage{algorithm}\n\\usepackage[noend]{algpseudocode}\n\\usepackage{lineno}\n\\linenumbers\n% math typesetting \n\\let\\vec\\mathbf\n\\newcommand{\\matrx}[1]{{\\left[ \\stackrel{}{#1}\\right]}}\n\n%SetFonts\n\n%SetFonts\n\n\\pagestyle{headings}\n\\markright{Yoav Ram, \\today \\; v2\\hfill}\n\n\n\n\\begin{document}\nHere I describe how I analyzed the stability of a modifier allele $m$ with vertical transmission rate $\\rho$ to invasion by a modifier $M$ with a vertical transmission rate $P$, as described in the main text, eqs. 34-35, in environmental regime $AkBl$.\n\\\\\nThe analysis is similar to that used in the main text to analyze stability in $A1B1$, but it uses computation because the cases where $k>1$ or $l>1$ cannot be analyzed using closed form expressions.\n\\\\\nThe analysis includes the following steps for a fixed $W, w, k,$ and $l$:\n\\begin{enumerate}\n\n\\item Find the stable frequency vector $\\vec{x^*}$ without invader $M$, i.e. $x^*_3=x^*_4=0$. This is done by minimizing the expression $|x_{k+l} - x_{0}|$ where $x_{t}$ is defined in eq. 9 of the main text. The minimization is done by iterating the recurrence until it converges, i.e. until the difference is smaller than machine precision (roughly $10^-8$ when subtracting similar small numbers).\n\n\\item Define $F_A(x)$ by eq. 35 of main text with $w_A=W$ and $w_B=w$ ($W>w$), and similarly $F_B(x)$ with $w_B=W$ and $w_A=w$.\n\n\\item Define, similar to eq. 37 of main text,\n\\begin{equation}\n\\vec{F} = \\underbrace{F_A \\circ \\ldots \\circ F_A}_{k \\text{ times}} \\circ\n\t\\underbrace{F_B \\circ \\ldots \\circ F_B}_{l \\text{ times}}.\n\\label{eq:F}\\end{equation}\n\n\\item Calculate the linear approximation $\\vec{J}$ of $\\vec{F}$  near $\\vec{x^*}$, that is, the Jacobian matrix of $\\vec{F}$ at $\\vec{x^*}$:\n\\begin{equation}\n\\vec{J}_{ij} = \\frac{\\partial F_i}{\\partial x_j}.\n\\label{eq:jacobian}\\end{equation}\n\n\\item Define $\\vec{L}=\\vec{L_{ex}}$ as in eqs. 40-45 in the main text such that\n\\begin{equation}\n\\vec{J} = \\begin{pmatrix}\n\\vec{L_{in}} & * \\\\\n* & \\vec{L_{ex}}\n\\end{pmatrix}.\n\\end{equation}\n\n\\item Calculate the eigenvalues $\\lambda_1 > \\lambda_2$ of $\\vec{L}$; by the Perron-Frobenius theorem, the leading eigenvalue $\\lambda_1$ is real and positive. Denote $\\lambda_1(\\rho, P)$ the resulting leading eigenvalue with resident rate $\\rho$ and invader rate $P$. Note that \n\\begin{equation}\n\\lambda_1(\\rho, \\rho) = 1,\n\\end{equation}\nfor any $\\rho \\in (0,1)$.\n\n\\item The evolutionary stable rate $\\rho^*$ is defined as stable to invasion, that is, \n\\begin{equation}\n\\lambda_1(\\rho^*,\\rho^* \\pm dP) < 1 = \\lambda_1(\\rho^*,\\rho^*)\n\\end{equation}\nfor a small enough $dP>0$.\nTherefore, \n\\begin{equation}\n\\frac{\\partial \\lambda_1}{\\partial P}\\big(\\rho^*,\\rho^*\\big) = 0. \n\\label{eq:dλdP=0} \\end{equation}\n\n\\item We use Brent's root-finding method (Brent, 1971) to find $\\rho^*$ that satisfies \\autoref{eq:dλdP=0}. If, due to numerical instability of the process, we have\n\\begin{equation}\n\\frac{\\partial \\lambda_1}{\\partial P}\\big(0,0\\big) \\cdot \\frac{\\partial \\lambda_1}{\\partial P}\\big(1,1) > 0,\n\\end{equation}\ni.e., the partial derivative sign is identical at $\\rho=P=0$ and $\\rho=P=1$, then we cannot use Brent's method. In these cases we assume that the partial derivative doesn't have a root in $(0,1)$ and we determine the stable rate $\\rho^*$ by the rule\n\\begin{equation}\n\\rho^* = \\begin{cases}\n0, \\quad \\text{if } \\frac{\\partial \\lambda_1}{\\partial P}\\big(0,0\\big) \\le 0, \\\\\n1, \\quad \\text{if } \\frac{\\partial \\lambda_1}{\\partial P}\\big(0,0\\big) > 0.\n\\end{cases}\n\\end{equation}\n\n\\end{enumerate}\n\n\\paragraph{Results}\n\\autoref{fig:AkBk_stable_modifier_w_0.1}, \\autoref{fig:AkBk_stable_modifier_w_0.5} and \\autoref{fig:AkBk_stable_modifier_w_0.9}, show the leading eigenvalue $\\lambda_1$ of the external stability matrix $\\vec{L}$ for different choices of environmental cycles $AkBk$, resident rate $\\rho$ and invader rate $P$. The arrows show a series of invading modifiers generated using Algorithm~\\autoref{algorithm} (this algorithm cannot be efficiently used to determine the stable rate as it requires fine tuning of the meta-parameter $\\eta$).\n\nThe leading eigenvalue calculation is good for small $k$ but for large $k$ and especially for $w=0.1$ the calculation is unstable.\nThis is probably because when the environment is constant for a long period of time, the frequencies are close to the boundaries (i.e. 0 and 1) and the gradient just after the environment changes is very sharp.\nTherefore, the calculation of $\\vec{J}$ is unstable.\nAlso, because most of the time the frequencies don't change by much, the elements of $\\vec{L}$ are small, leading to unstable calculation of the leading eigenvalue.\n\\\\\n\n\\begin{algorithm} \n% https://en.wikibooks.org/wiki/LaTeX/Algorithms\n\\caption{Modifier gradient ascent algorithm}\\label{algorithm}\n\\begin{algorithmic}[1]\n\\State $\\eta > 0$ is a step size\n\\State $\\rho_{0} = 0.5$ is a starting condition\n\\State $t = 0$ is an iteration counter\n\\While {$\\frac{|\\rho_{t} - \\rho_{t-1}|}{\\rho_{t-1}} < \\epsilon \\;\\text{and}\\; \\eta > \\eta_0$}\n\t\\State $P_{t} \\gets \\rho_{t} + \\eta \\frac{\\partial \\lambda_1(\\rho_{t}, \\rho_{t})}{\\partial P}$\n\t\\If {$\\lambda_1(\\rho_{t}, P_{t})$} \n\t\\State {$\\rho_{t+1} \\gets P_{t}$}\n\t\\Else\n\t\\State {$\\eta \\gets \\eta / 2$}\n\t\\EndIf\n\t\\State $t \\gets t+1$\n\\EndWhile\n\\State $\\rho^* \\gets \\rho_t$\n\\end{algorithmic}\n\\end{algorithm}\n\n\\begin{figure}[htbp]\n  \\centering\n    \\includegraphics[width=\\linewidth]{../figures/AkBk_stable_optimal_rate.pdf}\n  \\caption{Fitness \"optimal\" and evolutionary stable vertical transmission rate in $AkBk$ selection regime. \\textbf{(A)} The vertical transmission rate $\\hat{rho}$ that maximized the geometric average of the population mean fitness is zero, i.e. complete oblique transmission, when selection cycles quickly between favoring phenotype $A$ and $B$, and then abruptly transitions to ~0.2, followed by a slow decrease (see Fig. SX for details on the abrupt transition). \n  \\textbf{(B)} The evolutionary stable rate $\\rho^*$ which cannot be invaded by modifiers with either higher or lower vertical transmission rate $P$, rapidly increases from zero when selection cycles are short ($k=1$ or $2$) to roughly 1 when the environment cycles are longer. The stable rate was found by finding the root of $\\frac{\\partial \\lambda_1}{\\partial P}$, the leading eigenvalue of the external stability matrix w.r.t to the rate of the invading modifier (see Supplementary Information for details). The dashed lines shows $1-\\frac{1}{k-1}$, which seems to fit the values for $w=0.5$ (Carja et al. 2011). The values for $w=0.1$ (blue) could not be calculated for $k>21$ due to numerical instability when selection is strong and the duration between selection fluctuations is long.\n  In all cases, $W=1$}\n  \\label{fig:AkBk_stable_modifier_w_0.1}\n\\end{figure}\n\n\\begin{figure}[htbp]\n  \\centering\n    \\includegraphics[width=\\linewidth]{{../figures/AkBk_stable_modifier_w_0.1}.pdf}\n  \\caption{The leading eigenvalue of the external stability matrix in $AkBk$ with selection. The colors show $\\lambda_1(W, w, \\rho, P, k, l)$, the leading eigenvalue of the external stability matrix for combinations of $\\rho$ (y-axis) and $P$ (x-axis), the vertical transmission rates of resident and invader modifiers, respectively. Purple shows values lower than 1, leading to stability of $\\rho$; white equals to 1; green larger than 1, leading to invasion of $P$.\n  The arrows show an \"evolutionary\" path $\\rho_{0} \\to \\rho_{1} \\to \\ldots \\to \\rho^*$: at each step, a modifier with rate $P_t$ invades the resident modifier with rate $\\rho_t$ and becomes the resident modifier $\\rho_{t+1}$, until consecutive invaders have similar rates (see Algorithm~\\autoref{algorithm}).\n  Here, $W=1$ and $w=0.1$.}\n  \\label{fig:AkBk_stable_modifier_w_0.1}\n\\end{figure}\n\n\\begin{figure}[htbp]\n  \\centering\n    \\includegraphics[width=\\linewidth]{{../figures/AkBk_stable_modifier_w_0.5}.pdf}\n  \\caption{The leading eigenvalue of the external stability matrix in $AkBk$ with intermediate selection.\n  Same as~\\autoref{fig:AkBk_stable_modifier_w_0.1} except here, $W=1$ and $w=0.5$.}\n  \\label{fig:AkBk_stable_modifier_w_0.5}\n\\end{figure}\n\n\\begin{figure}[htbp]\n  \\centering\n    \\includegraphics[width=\\linewidth]{{../figures/AkBk_stable_modifier_w_0.9}.pdf}\n  \\caption{The leading eigenvalue of the external stability matrix in $AkBk$ with intermediate selection.\n  Same as~\\autoref{fig:AkBk_stable_modifier_w_0.1} except here, $W=1$ and $w=0.9$.}\n  \\label{fig:AkBk_stable_modifier_w_0.9}\n\\end{figure}\n\n\\paragraph{Note}\nCrucially, the Jacobian $\\vec{J}$ in~\\autoref{eq:jacobian} can be calculated using \\textit{automatic differentiation} with good precision from a function that iteratively calculates $\\vec{F}$ according to~\\autoref{eq:F}. Similarly, the partial derivative $\\frac{\\partial \\lambda_1}{\\partial P}$ in Algorithm~\\autoref{algorithm} can be calculated from a function that calculates $\\lambda_1$ using simple arithmetic operations, as the eigenvalues can be found from a quadratic formula.\n\\\\\nNote that \\textit{automatic differentiation} does not mean \\textit{symbolic} or \\textit{numerical differentiation}, which can lead to inefficient or inaccurate estimation of $\\vec{J}$ when $k$ is not very small. Rather, from Bartholomew-Biggs et al. (2000): \n\\begin{quotation}\\textit{\nAutomatic differentiation is a set of techniques for transforming a program that calculates numerical values of a function, into a program which calculates numerical values for derivatives of that function with about the same accuracy and efficiency as the function values themselves.\n}\\end{quotation}\n\n\\paragraph{References} ~\\\\\n\\begin{itemize}\n\n\\item Bartholomew-Biggs, M., S. Brown, B. Christianson, and L. Dixon. 2000. Automatic differentiation of algorithms. J. Comput. Appl. Math. 124:171–190.\n\n\\item Brent, R. P. 1971. An algorithm with guaranteed convergence for finding a zero of a function. Comput. J. 14:422–425.\n\n\\end{itemize}\n\n\\end{document}  ", "meta": {"hexsha": "62ac2f5c5999e8e415be5df3caa6cd4cfff17a33", "size": 10688, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ms/stability_analysis.tex", "max_stars_repo_name": "yoavram/Milpitas", "max_stars_repo_head_hexsha": "9dc3090cc5bca1a933ef21df75e7d907a89a37b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ms/stability_analysis.tex", "max_issues_repo_name": "yoavram/Milpitas", "max_issues_repo_head_hexsha": "9dc3090cc5bca1a933ef21df75e7d907a89a37b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ms/stability_analysis.tex", "max_forks_repo_name": "yoavram/Milpitas", "max_forks_repo_head_hexsha": "9dc3090cc5bca1a933ef21df75e7d907a89a37b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 62.8705882353, "max_line_length": 792, "alphanum_fraction": 0.7308196108, "num_tokens": 3192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.34975753811872645}}
{"text": "\\section{Model Functions}\n\nThis module is intended to be used an approximation of fuel slosh attached to the spacecraft. It is intended to have multiple fuel slosh particles attached to the spacecraft. Also it is recommended to attach at least 3 fuel slosh particles with different sloshing directions to get motion across all axes. Below is a list of functions that this model performs:\n\n\\begin{itemize}\n\t\\item Compute it's contributions to the mass properties of the spacecraft\n\t\\item Provides matrix contributions for the back substitution method\n\t\\item Compute it's derivatives for $\\rho$, $\\dot{\\rho}$, and $\\dot{m}$\n\t\\item Adds energy and momentum contributions to the spacecraft\n\\end{itemize}\n\n\\section{Model Assumptions and Limitations}\nBelow is a summary of the assumptions/limitations:\n\n\\begin{itemize}\n\t\\item Is an approximation to sloshing fuel\n\t\\item Is derived in such a manner that does not require constraints to be met\n\t\\item A single fuel slosh particle can only move along one direction, $\\hat{\\bm p}_j$, as seen in Figure~\\ref{fig:Flex_Slosh_Figure}\n\t\\item Multiple fuel slosh particles are not interconnected, each fuel slosh particle is attached the rigid body hub independently\n\t\\item Only constant linear spring and damping terms\n\t\\item The mass, spring and damping coefficients can be attenuated to approximate frequencies expected by the fuel slosh\n\t\\item There are no travel limits for the fuel slosh therefore the particles could travel past the limits of the fuel tank boundary (this can be avoided by varying the mass and/or spring constant while considering the expected accelerations of the s/c to stay within the tank)\n\t\\item The mass of the fuel slosh particles add to the total mass of the fuel tank\n\t\\item This model could be used with other fuel slosh models like a pendulum based fuel slosh model\n\\end{itemize}", "meta": {"hexsha": "1621d0e67496c8d82cb309b2810c300f5e4a0e6c", "size": 1848, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/simulation/dynamics/LinearSpringMassDamper/_Documentation/secModelFunctions.tex", "max_stars_repo_name": "ian-cooke/basilisk_mag", "max_stars_repo_head_hexsha": "a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/simulation/dynamics/LinearSpringMassDamper/_Documentation/secModelFunctions.tex", "max_issues_repo_name": "ian-cooke/basilisk_mag", "max_issues_repo_head_hexsha": "a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-03-13T20:52:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-13T20:52:22.000Z", "max_forks_repo_path": "src/simulation/dynamics/LinearSpringMassDamper/_Documentation/secModelFunctions.tex", "max_forks_repo_name": "ian-cooke/basilisk_mag", "max_forks_repo_head_hexsha": "a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 73.92, "max_line_length": 360, "alphanum_fraction": 0.7981601732, "num_tokens": 416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3497261564093474}}
{"text": "\n%\\section{Calibration and Validation}\n%\\section{Validation}\n\\label{sec:validation}\n\n% VALIDATION TODO\n%\n% show major effort\n% table of results\n% show hierarchy\n% precisely define cases \n%\n%\n\n%\n% meshed vanes are 24x more expensive\n%\n\nThe previous chapters briefly outlined the physical phenomenon under\nconsideration, the mathematical models proposed to simulate it,\nand the numerical solution of these models for a variety of system \nconfigurations and scenarios. Before these simulations can be used \nas a tool to evaluate proposed system designs, it is necessary to\nvalidate that the physical models in use accurately represent\nreality. As defined by Moser {\\em et al.}\\cite{Moser2012Validating},\n``validation is the process of determining whether a mathematical model\nis a sufficient representation of reality for the purposes for which the\nmodel will be used--that is, for predicting specified QoIs (Quantities\nof Interest) to inform a specific decision.'' \n\nThis chapter contains a discussion of the validation of the\ncomputational models against existing experimental data and high\nfidelity simulations. This chapter does not exhaustively detail the\nvalidation studies performed in the course of this study. Rather, this\nchapter discusses four representative cases and the overall validation\napproach pursued. \n%A more detailed set of validation data is provided in \n%Appendix~\\ref{app-validation}. \n% The limited validation that was performed\n% for the 2016 field tests in discussed in Chapter~\\ref{sec:field}. \n\nA challenge in this project is the scarcity of experimental data. Only\ntwo or three cases of experimental measurements are available. These\nmeasurements, for reasons detailed in the next section, are not\nsufficient to provide confidence in the output of simulations across a\nwide variety  of scenarios. Therefore, a high fidelity model using \nmeshed vanes with enforced no-slip velocity boundary conditions along\nthe surface of the turning vanes was developed. These ``gridded'' runs have\nbeen validated against the experimental data, which they match quite\nclosely. However, as detailed in Section~\\ref{subsec:vane}, \nexplicitly meshing the vanes would be far too \nexpensive to permit a rapid exploration of a variety of\nsystem configurations. Instead, this high fidelity model is used \nto generate additional reliable data to permit validation of lower\nfidelity models, such as the virtual vanes. Likewise, the results of the\nunsteady virtual vane simulations can be used as validation data for a\nfurther reduced, steady Navier-Stokes model. This hierarchy of\nvalidation is shown in Figure~\\ref{fig:val_hier}, with data sources that\ngenerate more reliable data at the top, and models that are less\nreliable, but also less computationally expensive at the bottom. In\nterms of expense, the steady virtual vane model generates a solution in\napproximately two minutes, versus twelve hours for the unsteady virtual\nvane model. The gridded vanes require another factor of ten in\ncomputational time, and many more man-hours hours of work to generate\nthe mesh (which were generated using gridgen). An example of one of the\ngridded meshes complexity is shown in Figure~\\ref{fig:gridded_mesh}. \nTherefore, it is unrealistic to perform parameter sweeps or\nsystem configuration investigations with the gridded vanes and these\nresults are used only for validation studies. Instead, the\nsteady model is used, with promising results re-evaluated with unsteady\nvirtual vane models. %and so on up the hierarchy if more confidence is necessary. \n\n%\n% https://www.draw.io/\n%\n \\begin{figure}[!htb]\n   \\begin{center}\n    \\includegraphics[width = 8 cm]{figs/validation_hierarchy}\n    \\caption{This figure depicts the validation hierarchy. The\n    experimental measurements are at the top, where the data is expected\n    to be the most reliable, but simultaneously the most\n    limited. Moving down the table leads to simulated data sources that\n    are less reliable but increasingly cheaper in time to generate. At\n    the bottom are the steady virtual vane solutions.} \n    \\label{fig:val_hier}\n   \\end{center}\n \\end{figure}\n\n \\begin{figure}[!htb]\n   \\begin{center}\n    \\includegraphics[width = 8 cm]{figs/gridded_mesh_example}\n    \\caption{An example of the gridded mesh, where the turning vanes\n    are explicitly represented and a no-slip boundary condition is\n    imposed on the surface. This mesh was generated using gridgen.} \n    \\label{fig:gridded_mesh}\n   \\end{center}\n \\end{figure}\n\nThree kinds of experimental validation data are available. These are\ndata generated in the laboratory using a heated plate, data from\nexperiments in the wind tunnel (``Wind-only''), and measurements from field\ntests (``Field'') conducted in Arizona. The available data from\nthese cases and the gridded vanes created to mimic them are are\nsummarized in Table~\\ref{tab:val_data}. Every case shown has been\nsimulated using the virtual vanes.   \n\n%\\large\n\\begin{table}[h]\n\\centering\n\\begin{tabular}{l|l|l|l|}\n           & Wind-Only                   & Thermal-Only                & Field  \\\\\n  \\hline \nExperiment & Straight Vanes $60^{\\circ}$ & Straight Vanes $60^{\\circ}$ & June 2014   \\\\\n           &                           & Straight Vanes $30^{\\circ}$   & August 2014 \\\\\n           &                           & Hybrid (Two tier)             & August 2015 \\\\\n  \\hline \nGridded    & Straight Vanes $60^{\\circ}$ & Straight Vanes $60^{\\circ}$ & \\\\\n           & Straight Vanes $30^{\\circ}$ & Straight Vanes $30^{\\circ}$ & \\\\\n  \\hline \n\\end{tabular}\n  \\caption{Available truth data from the laboratory experiments \n    (cold wind and thermal-only), the field tests, and the gridded\n vanes.}  \n  \\label{tab:val_data}\n\\end{table}\n%\n%\n%\n% http://www.tablesgenerator.com/\n%\n%\n\n\n%\n% experimental challenges\n%\n%\\normalsize\n\\section{Thermal-Only Validation}\nThis section provides examples of the validation performed with the\nrichest experimental data set, the measurements in the laboratory. All of the\nthermal-only the data was generated in a laboratory setting at Georgia\nTech. The general system configuration is depicted in Figure\n\\ref{fig:lab_image}. These data were taken using stereo particle image\nvelocimetry (PIV) at Georgia Tech by Mark Simpson and Ari Glezer, and\nthe errors in in measurement and sampling are \nnot quoted. The particles are seeded outside of the array vanes and\npermitted to naturally convect into the turning vane enclosure. The\nparticles were from a glycol-water theatrical fog (Rosco Fog Fluid). \nOnly velocity measurements are available. Several\npotentially important quantities, such as the pressure and\ntemperature, have not been measured. \n\n%\n% http://convertonlinefree.com/ConvertImageEN.aspx\n%\n \\begin{figure}[!htb]\n   \\begin{center}\n    \\includegraphics[width = 12 cm]{figs/Optimized-lab_setup}\n    \\caption{An example of the single tier straight vane laboratory\n    configuration. The apparatus is shown with a turbine, but that was\n    removed for data gathering. The particles for PIV were seeded\n    outside of the turning vanes and entrained into the central region.}\n    \\label{fig:lab_image}\n   \\end{center}\n \\end{figure}\n\nWhile no sensitivity analysis has been performed, it is likely that the\nlargest uncertainty in the laboratory simulation is a result of the\nventilation of the laboratory. The heated plate at the bottom of the\napparatus generated enough heat to cause an increase in room\ntemperature (30+ Kelvin), which greatly impacts the SoV\nperformance, as the ground to air thermal gradient drives the\nvortex. The laboratory is cooled to maintain\ntemperature by two inlet HVAC ducts in the room. \n%While efforts have been made to characterize the level of ventilation being\n%used, these numbers come with non-trivial uncertainties attached. \nOne vent continuously provides air at 288 Kelvin with a flow rate estimated \nto be 1 $\\text{m}^3$/s.\n%(4-6 m/s with an approximate area of 0.2 $m^2$)\nThe other vent is active only if the room temperature exceeds 301 Kelvin, \nwith a flow rate also estimated at 1 $\\text{m}^3$/s\\cite{mark_comm}.\nFinally, the air leaves through the cracks around the laboratory doors and \nexhaust vents. Preliminary results indicated that an inflow rate of 1\n$\\text{m}^3$/s, the lower bound of the possible inflow rates results in\nexcessive heating of the room, while inflow conditions at the maximum\ninflow rate of 2 $\\text{m}^3$/s result in a simulated room that is too cold,\ncompared to the laboratory.  \n\nOur simulated vortices are sensitive to ambient room temperature and thus \nthe inflow rate. It is likely that the laboratory is run where one of\nthe vents is operating intermittently. \nTo mimic these conditions in our simulations, Dirichlet boundary conditions \non parts of the sides of the computational domain are used to\nestablish a constant inflow of cool air at the rates \nproscribed by our collaborators. Over the remainder of the side walls, \nadiabatic thermal boundary conditions are are used. \n\nThe most significant boundary condition disparity is that flow leaves the\ndomain through the top boundary, instead of out of the sides of the\nroom. Preliminary results suggested that the SoV phenomenon  was not\nsensitive to these boundary condition details. The important element is\nthe  global energy balance in the room. The flow rate into the room is\nadjusted to  1.3 $\\text{m}^3$/s for the validation results discussed here.  \n\n% \\begin{figure}[!htb]\n%   \\begin{center}\n%    \\includegraphics[width = 12 cm]{figs/hybrid_profile}\n%    \\caption{Azimuthal and vertical velocity profiles as a function of\n%    radius. The simulation and experimental data broadly agree, with\n%    the simulation also exhibiting the characteristic ``twin-peak''\n%    structure of the hybrid vanes in the azimuthal velocity. }\n%    \\label{fig:lab}\n%   \\end{center}\n% \\end{figure}\n\n\\begin{figure}[htp!]\n\n  \\centering\n  \\includegraphics[width =0.47\\textwidth]{figs/sim_vs_exp_30_vt}\n%  \\caption{Azimuthal velocity}\n \\hfill\n \\includegraphics[width =0.47\\textwidth]{figs/sim_vs_exp_30_vz}%\n %\\caption{Vertical velocity} \n \\caption{Azimuthal (left figure) and vertical (right figure) velocity \n as a function of radius for the thermal-only cases. Shown are single\n tier straight $30^{\\circ}$ vanes. $V_{\\theta}^V$ (gold line) is\n the virtual vane simulation, $V_{\\theta}^E$ (blue line) the experiment,\n and $V_{\\theta}^G$ (red line) the gridded vane. These results were all\n generated by unsteady simulations and then temporally averaged. \n The lack of smoothness in the data is believed to be\n attributable to finite-time averaging, particularly in the case of the\n gridded vanes, which were expensive calculations. }   \n \\label{fig:val_lab}  \n\\end{figure}\n\nFigure~\\ref{fig:val_lab} is a direct comparison\nbetween laboratory measurements for a simple single tier vane\nconfiguration ($30^{\\circ}$ straight vanes) and nominally identical\nsimulations with the gridded and \nvirtual vanes. The simulations and experiment broadly agree. The\nsimulation correctly reproduce the peak structure in the azimuthal\nvelocity observed for this configuration in the experiment. The gridded\nvanes closely represent the peak radial location, while the\nvirtual vanes over-predict the radial location, likely due to the\nincreased eddy diffusivity that exists in the virtual vanes. The radial\nlocation and magnitude of peak vertical velocity also closely agrees\nwith experiment. \n\nSimilar validation comparisons have been made between several other\nconfigurations with similar levels of agreement,  notably the\n$60^{\\circ}$ single tier straight vane case, and the two-tier hybrid\nvanes. \n%Some of these cases are detailed in Appendix~\\ref{app-validation}.\nThese validation studies have provided a level of confidence that our\nsimulations accurately reproduce the phenomena observed in laboratory.\n\n%\\todo{slices and images of thermal only?} \n\n\\section{Wind Cases}\n\nThe laboratory thermal vortex experiments described in the previous\nsection did not include the effects of the wind, but experience in\nthe field indicated that ambient winds were both pervasive and intense\n(see Section~\\ref{subsec:field_predict} for more details). To ensure that\nthe virtual vanes accurately represent the impact of ambient winds, a\nvalidation study was performed using the data obtained in the wind\ntunnel. \n\nA numerical experiment was performed in which the 60 degree single tier\nstraight vanes were placed in a isothermal wind. The boundary conditions\nare as detailed in Section~\\ref{sec:bc}, but in isothermal\nconditions. These results were compared to an identical experimental\nconfiguration placed in a wind tunnel. However, no measurements (of\nvelocity or any quantity) were made for the vanes in these\nconditions. Qualitative comparisons, based on descriptions of observed\nstructures and videos of smoke visualization were made between the\nsimulations and the wind tunnel experiments. The initial validation was\nfound to have significant qualitative differences between the virtual\nvanes and the experimental images, with the flow visibly exiting out the\nback of the vanes instead of being contained within.  As a result of\nthis inconsistency, the virtual vane model was refined to include a\nseparation model, which is detailed in Section~\\ref{sec:separation}. The\nimages  did not identify any inconsistencies between the refined\nsimulation and experiment.   \n\n\n\\begin{figure}\n  \\begin{subfigure}{0.49\\textwidth}\n   \\centering\n   \\includegraphics[width=.95\\linewidth]{figs/gridded_wind}\n   \\caption{Streamwise Velocity: Gridded Vanes}\n  \\end{subfigure}\n %\\hfill\n  \\begin{subfigure}{0.49\\textwidth}  \n   \\centering\n   \\includegraphics[width=.95\\linewidth]{figs/virtual_wind}\n   \\caption{Streamwise Velocity: Virtual Vanes}\n   \\end{subfigure} \\\\\n  \\begin{subfigure}{0.49\\textwidth}\n   \\centering\n   \\includegraphics[width=.95\\linewidth]{figs/gridded_wind_span}\n   \\caption{Spanwise Velocity: Gridded Vanes}\n  \\end{subfigure}\n %\\hfill\n  \\begin{subfigure}{0.49\\textwidth}\n   \\centering\n  \\includegraphics[width=.95\\linewidth]{figs/virtual_wind_span}\n   \\caption{Spanwise Velocity: Virtual Vanes}\n  \\end{subfigure}\n \\caption{Horizontal slices through the top of the vanes for the\n wind validation cases. On the left are the explicitly gridded vanes,\n and on the right the virtual vanes. The streamwise velocity (top\n images), which moves left to right, shows penetration through the\n region where the vanes are aligned with the flow in both the gridded\n and virtual vanes. The second row shows the spanwise velocity (red for\n flow moving up the page, blue for flow moving down the page) where it\n can be seen that the virtual vane case correctly reproduces the\n direction and magnitude of velocity inside the vanes.}  \n \\label{fig:wind_val}\n\\end{figure}\n\n%\n% Attached in the plate from which we inject the fog from. The holes used\n% for seeding are the center one (0.5\u001b$B!I\u001b(B diameter) and the other 4 ones\n% which are 0.25\u001b$B!I\u001b(B diameter. The smallest holes are for alignment pins in\n% the tunnel so disregard those ones. Please note that this file is in\n% inches and the previous one in millimeters. \n% Hidalgo Ardana Pablo\n%\n% 11/26/14\n%\nHowever, these results are limited, and are\nonly for the cold wind, as the wind tunnel did not include a heated plate.\nTo provide a more quantitative validation study, the virtual vanes were\ncompared to gridded vanes for a cold wind case. Both cases had identical\nboundary conditions, as detailed in Section~\\ref{sec:bc}. A two meter\nper second inlet velocity was selected. Figure~\\ref{fig:wind_val}\ncontains images of the simulated averaged \nstreamwise and  spanwise velocity in a horizontal plane at approximately\nthe height of the vanes obtained from simulations with gridded and\nvirtual vanes. \nThe streamwise velocity penetrates through the region where the vanes\nare aligned with the flow in both the gridded and virtual vanes. This\nindicates the virtual vane region as defined in\nSection~\\ref{subsec:vane} is not turning the flow in locations where\nthe flow velocity is aligned with the vane direction, as intended. \nThe second row contains images of the spanwise velocity, where it can be\nseen that the virtual vane case correctly reproduces the direction and\nmagnitude of velocity inside the vanes. While the wake has similar\nstructure between the two cases for the streamwise velocity, the\nspanwise velocity in the wake is not as closely represented between the\ncases. While there are some differences in the\ndetails of these simulations, the overall character of the flow\ninside the vanes is quite similar. This demonstrates that the virtual\nvane formulation can indeed accurately represent the interaction with the wind, \nat least in the case without thermal differences.  \n\n\\section{Comparisons between Steady and Unsteady Virtual Vanes}\n\\label{sec:steady_val}\n\nAt the bottom of the validation hierarchy are the steady virtual\nvanes. This is expected to be the most inaccurate model. \nSimultaneously, this is by far the cheapest computationally, and \nreduces the run-time from approximately 12 hours (in the case of the\nunsteady) to less than two minutes. This reduced run-time permits\nrapid exploration of the SoV configuration space, making the steady\nvirtual vanes an invaluable design tool. For this reason, the steady\nmodel is used extensively in Chapters~\\ref{sec:results} and\n\\ref{sec:field} to explore new SoV vane design concepts. \n\nHowever, the results of the steady cases must first be\ncompared to the transient case to ensure the output is consistent. \nFigure~\\ref{fig:rom_compare} depicts such a case, where the streamwise\nvelocity in a wind case was used as a direct comparison between the\nsteady and unsteady virtual vane cases. This was a hot-wind case, with\nan ambient freestream velocity of 3 m/s and a temperature difference of 60\nKelvin. The boundary conditions are precisely as described in\nSection~\\ref{sec:bc}. \n%The vanes are an axi-symmetric two-tier structure,\n%with inner vane angles of  and degrees, respectively. \n\nThese two solutions are similar, with comparable velocity magnitudes and \nconsistent signs. A comparison between the azimuthal velocities are\nshown in Figure~\\ref{fig:rom_az}, which makes clear the more diffuse and\nweaker magnitude peak in the steady solution. Ultimately, the steady\nsolution's principle use as a design tool is driven by the response in\nkinetic energy flux to sensitivity to small perturbations in the SoV\ndesign (such as vane or cone geometry). To measure this, a comparison\nwas made between steady and unsteady solutions to changes from a base state \nin response to small ($1^{\\circ}-5^{\\circ}$) perturbations in the vane\nangles. The results of this are shown in Figure~\\ref{fig:rom_it}, where\nthe steady solution typically underestimates, but broadly agrees with,\nthe change in kinetic energy flux attributable to a perturbation in the\nsystem design parameters.  It is for this reason that the steady\nsolution is believed to be a useful tool to explore the system\nconfiguration space, as it accurately represents favorable design\nadjustments, and so can be used in an optimization effort to rapidly\nprobe various configurations and drive the system towards peak kinetic\nenergy flux generation.  \n\n\\begin{figure}[htp!]\n \\begin{subfigure}{0.49\\textwidth}\n \\centering\n \\includegraphics[width =0.95\\textwidth]{figs/rom_steady}\n  \\caption{Steady Virtual Vanes}\n \\end{subfigure}\n \\begin{subfigure}{0.49\\textwidth}\n  %\\hfill\n \\includegraphics[width =0.95\\textwidth]{figs/rom_unsteady}%\n  \\caption{Unsteady Virtual Vanes}\n \\end{subfigure}\n \\caption{A comparison between the streamwise velocity in the averaged\n transient virtual vane solution (right image) and the steady virtual\n vane solution (left image). These horizontal slices were taken at the\n height of the second tier of vanes. The black lines indicate the\n annular vane forcing region. While the steady solution is more diffuse,\n it possesses a similar qualitative structure as the higher fidelity\n solution. The unsteady solution has a larger peak velocity inside the\n apparatus, while simultaneously possessing a larger and more intense\n wake region.}\n \\label{fig:rom_compare}  \n\\end{figure}\n\n% Flow features smeared\n% what type of vanes are these?\n% calibration\n\n\\begin{figure}[htp!]\n \\centering\n \\includegraphics[width =0.7\\textwidth]{figs/rom_radial}\n \\caption{The azimuthal velocity profile as a function of radius for the\n steady and unsteady cases. The profile is extracted from $\\theta =\n 90^{\\circ}$. The unsteady vanes were temporally averaged. The steady\n solution has a similar radial peak location, but a lower velocity\n magnitude and a more diffuse structure.}   \n \\label{fig:rom_az}\n\\end{figure}\n\n\n% The results between these simulations are broadly consistent. \n% Across a range of previously tested configurations the kinetic energy\n% flux typically agrees to within 20\\% and the sensitivities of the energy\n% flux to small perturbations in the system configuration correlate well\n% with the results of the higher fidelity transient model. \n\n\\begin{figure}[htp!]\n \\centering\n \\includegraphics[width =0.7\\textwidth]{figs/rom_iterate}\n \\caption{A comparison between the change in kinetic energy flux due to\n a perturbation in system parameters (vane angle) between the steady and\n unsteady virtual vanes. For each iteration, a design parameter was\n changed, and the \\% change in kinetic energy flux was recorded.}    \n \\label{fig:rom_it}  \n\\end{figure}\n\n\\section{Field Configurations}\n\\label{sec:field_val}\n\nSeveral field tests have been performed by the experimental team. After\neach field test, qualitative observations, measurements and lessons\nlearned are provided by the field team. Actual measurements\nare limited. Due to the complexity of the configuration\n(two vane tiers and a cone) gridded vanes cases have not been developed \nfor the field configurations. This section provides a discussion of some of\nthe results from the latest field test, as an example of typical\nvalidations performed. \n\n \\begin{figure}[!htb]\n  \\begin{center}\n   \\includegraphics[width = 12 cm]{figs/validate_field}\n   \\caption{A comparison between simulated and experimental data for the\n   August 2015 field test. Azimuthal velocity data from the actual field\n   test is shown in blue. Two virtual vane simulations with different\n   scenario parameters are shown in red and gold. The velocity field was\n   temporally averaged but not averaged in space, to reproduce\n   the measurements from the field.}\n   \\label{fig:field_val}\n  \\end{center}\n \\end{figure}\n%\n% provide an example of these validations below\n%\n\nFigure~\\ref{fig:field_val} shows velocity data from the \nAugust 2015 field test in blue. These results were \nobtained using an anemometer at fixed\nazimuthal location (believed to be at a ninety degree angle, where the zero\nis defined to be aligned with the streamwise flow direction) to measure the\nazimuthal velocity. A time\nseries from approximately an hour was gathered. This data included large\nscenario uncertainties, with estimated 3 m/s variations in wind, 20\ndegree wind heading changes, and ten degree Celsius shifts in\ntemperature. Other than the velocities, the only other measurement\ntaken was the temperature. Due to a DAQ malfunction, the\ntemperature was only measured at one location at one meter in height. \nA solidworks CAD file provided by the experimental team\ndefined the vane and cone geometry, which were then represented in the\nsimulations as virtual vanes and a solid surface, as described in \nSections~\\ref{subsec:vane} and \\ref{subsec:solid_surface}. Hence, the\nscenario uncertainty was significant, while the uncertainty in the\nsystem apparatus was small. \n\n\\begin{table}[!htb]\n\\centering\n \\caption{The range of conditions represented in\n Figure~\\ref{fig:field_val}. The heading is with respect to the presumed\n wind direction. The heading may at first appear not to be significant,\n as the vanes are axisymmetric. However, the rake holding\n the anemometer was placed at a $90^{\\circ}$ relative to the presumed\n freestream velocity, and the SoV solution structure is not symmetric.}\n\\begin{tabular}{l|l|l|l}\nCase Name & Wind Velocity (m/s) & Heading & $T_\\text{Surface}$\n (Celsius) \\\\ \n \\hline\n Peak (Red Line) &  5.0  & $0^{\\circ}$ & $60^{\\circ}$ \\\\\n Match (Black Line) &  3.0  & $0^{\\circ}$ & $60^{\\circ}$ \\\\\n Minimum (Gold Line) &  2.0  & $20^{\\circ}$ & $20^{\\circ}$ \\\\\n\\end{tabular}\n \\label{tab:val_cond}\n\\end{table}\n\n\nTo span the range of scenario conditions, several simulations were conducted\nwith different parameters. These simulations were performed with\nunsteady virtual vanes on a wind blown domain as detailed in\nSection~\\ref{sec:bc}.  The azimuthal velocity from two such\nsimulations (red and gold lines) are plotted against the experimental\ndata (blue line) in Figure~\\ref{fig:field_val}. The red line represents\nan upper bound, with the strongest wind speeds and highest thermal\ngradient. The gold line is a lower bound, with a more modest ambient\nfreestream velocity, a lower temperature gradient, and an indirect wind\nheading. \n\nThese simulations accurately bound the experimental data. Furthermore, a\n``Matching'' case was identified that is broadly consistent with the\nfield results. This corresponded to a 3 m/s wind velocity and a 60\ndegree Celsius temperature difference. These range of conditions are\nsummarized in Table~\\ref{tab:val_cond}. \nAs the rake was at fixed azimuthal location, the kinetic energy fluxes were\ncompared by assuming azimuthal symmetry and integrating in a horizontal\nplane at the top of the vanes (where a turbine to extract this energy\nwould likely be placed). By this metric, the ``Matching'' simulation\nkinetic energy flux agrees with the experimental estimate within\n10\\%. This is likely an optimistic measure, as the simulations indicate\nthat the velocity field is highly azimuthally asymmetric. Nevertheless,\nno significant inconsistencies have been identified between the\nexperimental results and the simulations. \n\n\n%\n% validation story is incomplete\n% \n% you have done: \n%\n% 1) comparions between laboratory + gridded + virtual \n% \n% 2) comparisons between gridded + virtual in laboratory\n%    + field configurations, thermal only and wind\n%\n% 3) comparisons of virtual vanes to field observations \n%    quantitative + qualitative\n%\n%\n% You need to discuss what needs to be validated -- the\n% comparison to gridded vanes is a useful validation tool \n%\n", "meta": {"hexsha": "286bcb3c6a0ca8a2b3635e5f859c04bb49ecd454", "size": 26440, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "disputatio/dissertation/chapter-validation.tex", "max_stars_repo_name": "nicholasmalaya/paleologos", "max_stars_repo_head_hexsha": "11959056caa80d3c910759b714a0f8e42f986f0f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-04T17:49:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T17:49:42.000Z", "max_issues_repo_path": "disputatio/dissertation/chapter-validation.tex", "max_issues_repo_name": "nicholasmalaya/paleologos", "max_issues_repo_head_hexsha": "11959056caa80d3c910759b714a0f8e42f986f0f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "disputatio/dissertation/chapter-validation.tex", "max_forks_repo_name": "nicholasmalaya/paleologos", "max_forks_repo_head_hexsha": "11959056caa80d3c910759b714a0f8e42f986f0f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-01-04T16:08:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-16T19:34:24.000Z", "avg_line_length": 46.6313932981, "max_line_length": 87, "alphanum_fraction": 0.7808245083, "num_tokens": 6295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.34972615270122964}}
{"text": "%==============================================================================\n\\chapter{Quantification of the Difference}\n\\label{chap:quantifing}\n%==============================================================================\n\nHaving shown explicitly the discrepancy between the pure and the thermal \ndescriptions as well as where it is most significant, the author will then\nquantify the difference. Related definitions of distances in quantum \nmechanics are introduced in \\cref{chap:distappd}.\n%In this chapter, it will be explained why the difference between the two cases \n%is expected to be negatively correlated to the mass of the black hole, then \n%the difference will be evaluated. \n\n%------------------------------------------------------------------------------\n\\section{The Canonical State} %Popescu--Winter Theorem\n\\label{sec:arbitrary-canonical}\n%------------------------------------------------------------------------------\n\nIt has been shown in \\cite{Popescu2006} that a small subsystem in a large, \nisolated system which is subject to a \\emph{constraint}, is expected to be very \nclose to a \\emph{canonical state} of it, which reduces to the usual \nthermodynamic \\emph{canonical ensemble} when the total system is under an \n\\emph{energy constraint}.\n\nDenoted by $U$, the large system has all its possible pure states in Hilbert \nspace $\\mscrH_U$ which has a finite dimension $d_R = \\dim \\mscrH_U$. A global \nconstraint $R$ is also imposed, which restricts the physical Hilbert space of \n$U$ to $\\mscrH_R \\subseteq \\mscrH_U$. The \\emph{equiprobable state} of $U$ is\n\\begin{equation}\n\\mscrE_R \\coloneqq d_R^{-1} \\Bbbone_R,\n\\end{equation}\nwhere $\\Bbbone_R$ is the identity operator on $\\mscrH_R$. An energy constraint, \nfor instance, reads\n\\begin{equation}\n\\abr{H_U} = E_R,\n\\label{eq:ene-constraint}\n\\end{equation}\nso that a state $\\Ket{\\alpha}$ in $\\mscrH_R^{\\rbr{\\text{E}}}$ satisfies\n\\begin{equation}\nE_R = \\Braket{\\alpha | H_U | \\alpha} = \\sum_E \\vbr{\\Braket{E | \\alpha}}^2 E,\n\\end{equation}\nwhere $\\Ket{E}$ is an energy eigenstate of $U$ with eigenvalue $E$.\n\nThe subsystem in concern is named $S$, with \\emph{all possible} states in the\nHilbert space $\\mscrH_S$; the rest of $U$ is called the \\emph{environment} and \ndenoted by $E$, the pure states of which lie in $\\mscrH_E$. One has\n\\begin{equation}\n\\mscrH_S \\otimes \\mscrH_E = \\mscrH_U \\supseteq \\mscrH_R,\\qquad\nH_U = H_S + H_E + H_\\text{int},\n\\end{equation}\nwhere $H_S$, $H_E$ and $H_\\text{int}$ are the system, environment and \ninteraction Hamiltonian, respectively. \n\nThe \\emph{canonical state} of $S$ is defined as\n\\begin{equation}\n{\\Omega}_S \\coloneqq \\tr_E {\\mscrE}_R,\n\\end{equation}\nwhere the trace is taken over all the degrees of freedom in the environment. \nWhen the energy constraint \\cref{eq:ene-constraint} is used, it can be shown \nthat $\\Omega_S^{(E)}$ is a canonical ensemble\\footnote{A derivation of \n\\cref{eq:canonical-state-def} in classical statistical physics can be found in \n\\cite[sec.~28]{Landau1980}.}\n\\begin{equation}\n\\Omega_S^{(E)} \\propto \\ee^{- H_S/T_\\text{m}}\n= \\sum_{E_S} \\ee^{-E_S/T_\\text{m}} \\Ket{E_S}\\Bra{E_S},\n\\label{eq:canonical-state-def}\n\\end{equation}\nwhere $T_\\text{m}$ can be identified with a temperature, and $\\Ket{E_S}$ is an\neigenstate of the system with eigenvalue $E$. In this case it reduces to \nthe traditional thermodynamic statistical physics.\n\n%To state the theorems, one additional definition is needed: \nThe environment also has an \\emph{effective} dimension\n\\begin{equation}\nd_E^\\text{eff} \\coloneqq \\rbr{\\tr \\Omega_E^2}^{-1} \\geq d_R/d_S,\n\\label{eq:def-effective-dim}\n\\end{equation}\nwhere ${\\Omega}_E = \\tr_S {\\mscrE}_R$. When no constraint is enforced, so that\n$\\mscrH_S \\otimes \\mscrH_E \\equiv \\mscrH_U = \\mscrH_R$, \n\\cref{eq:def-effective-dim} reduces to\n\\begin{equation}\nd_E^\\text{eff} = d_R/d_S = d_E.\n\\end{equation}\nDetailed discussions about $d_E^\\text{eff}$ can be found in \\cite{Popescu2006}.\n\nEquipped with all the definitions above, one picks an arbitrary pure state \n$\\Ket{\\phi}\\in\\mscrH_R$ and denote the \\emph{reduced state} of $S$ by\n\\begin{equation}\n\\rfun{\\rho_S}{\\phi} = \\tr_E \\Ket{\\phi}\\Bra{\\phi}\n\\end{equation}\nThen a lemma states that the average \\emph{trace distance}\\footnote{See \n\\cref{sec:trace-dist}.} between $\\rho_S$ and $\\Omega_S$ is very small in terms \nof the ratio between $d_S$ and $d_S/d_E^\\text{eff}$, i.e.\\\n\\begin{equation}\n\\abr{\\rfun{T}{\\rfun{\\rho_S}{\\phi}, {\\Omega}_S}} \\le \\frac{1}{2}\n\\sqrt{\\frac{d_S}{d_E^\\text{eff}}}.\n\\end{equation}\nIn a typical division where $d_S/d_E$ is small, this average distance will also \nbe tiny.\n\nMore over, the main theorem asserts that those ${\\rho}_S$'s which are close to \n${\\Omega}_S$ dominate; the probability of a large deviation is exponentially \nsmall with respect to the deviation. For an arbitrary $\\epsilon > 0$, the \ntheorem states that\n\\begin{equation}\n\\frac{\\sfun{V}{\\cbr{\\Ket{\\phi} \\in \\mscrH_R |\n\\rfun{T}{\\rfun{\\rho_S}{\\phi}, \\Omega_S} \\geq \\eta}}}\n{\\sfun{V}{\\cbr{\\Ket{\\phi} \\in \\mscrH_R}}} \\leq \\eta',\n\\label{eq:main-theorem-Popescu}\n\\end{equation}\nwhere\n\\begin{equation}\n\\eta = \\epsilon + \\frac{1}{2}\\sqrt{\\frac{d_S}{d_E^\\text{eff}}}; \\qquad\n\\eta' = 4\\rfun{\\exp}{-C d_R \\epsilon^2},\\quad C = \\frac{2}{9\\pp^3}.\n\\label{eq:main-theorem-supp}\n\\end{equation}\nTo understand the theorem, first note that the left-hand side of \n\\cref{eq:main-theorem-Popescu} is a probability measure. More over, one can \nchoose $\\epsilon = d_R^{-1/3}$ as well, so that\n\\begin{equation}\n\\eta = \\epsilon + \\frac{1}{2}\\sqrt{\\frac{d_S}{d_E^\\text{eff}}} \\gtrsim \nd_R^{-1/3};\\qquad\n\\eta' = 4\\rfun{\\exp}{-C d_R \\epsilon^2} = 4\\rfun{\\exp}{-C d_R^{+1/3}},\n\\end{equation}\nwhere $d_E^\\text{eff} \\gg d_S$ is also assumed. In this case, the probability \nof the deviation greater than $d_R^{-1/3}$ is smaller than an \n\\emph{exponential} of $d_R^{+1/3}$.\n\nFurther explanations and proofs of the lemma and the theorem can \nbe found in \\cite{Popescu2006,Popescu2007}.\n\n%------------------------------------------------------------------------------\n\\section{Distance between the Pure and Mixed States}\n\\label{sec:dist-radiation}\n%------------------------------------------------------------------------------\n\nTo apply the aforementioned formalism to the Hawking radiation, one recognises \nthe universe in the CGHS model as the total isolated system $U$, whereas the \ngravitational degrees of freedom as $E$, and the system in concern $S$ is the \nradiation field. It has been shown in \\cite{Demers1996,Kiefer2001} that the \nreduced state of the radiation field can indeed be \\emph{thermal} in certain \n\\emph{decoherence} schemes, while in the collapsing case discussed in \n\\cref{sec:hawrad-1+1dila,sec:1+1ddlt}, the radiation field remains pure.\n\nIn this section, the trace distance between the pure and thermal descriptions \nwill be evaluated. Due to technical difficulties, the distance has not been able \nto be derived exactly. Instead, a lower and an upper bound have been set to the \ndistance by \\emph{Fuchs-van de Graaf inequality} in \\cref{eq:ineq-fvdg}, where \nonly the calculable \\emph{Fidelity} (see \\cref{sec:fidelity}) is needed.\n\nNote that the wave functional of the Hawking radiation field \n\\cref{eq:squeezed-wave-functional} is, roughly speaking, the superposition of \nquantum-mechanical wave functions per Fourier mode,\n\\begin{equation}\n\\sfun{\\chi_b}{g} \\sim \\sum_p \\rfun{\\chi_b^\\rbr{p}}{g_p}\n= \\sum_p \\Braket{g_p | \\chi_b^\\rbr{p}},\n\\label{eq:wave-function-decomposed}\n\\end{equation}\nwhere $g_p \\coloneqq \\rfun{g}{p}$ is the Fourier transform of the field $g$ \nevaluated at $p$. On the other hand, the thermal state of the free field can \nalso be sloppily written as the product of the quantum-mechanical density \noperators per mode,\n\\begin{equation}\n{\\rho}_\\text{th} \\sim \\bigotimes_p {\\rho}_\\text{th}^\\rbr{p}.\n\\end{equation}\nBy \\cref{eq:fidelity-pure-mixed}, the fidelity of $\\sfun{\\chi_b}{g}$ and \n$\\rho_\\text{th}$ can be reduced to the product of the fidelity per mode, because\n\\begin{equation}\n\\Braket{\\chi_b | {\\rho}_\\text{th} | \\chi_b} \\sim \\prod_p \n\\Braket{\\chi_b^\\rbr{p} | {\\rho}_\\text{th}^\\rbr{p} | \\chi_b^\\rbr{p}}.\n\\label{eq:expectation-decomposed}\n\\end{equation}\n\nSince $\\Ket{\\chi_b^\\rbr{p}}$ is just a quantum-mechanical general Gaussian \nstate (see \\cref{sec:single-harosc}), the result in \\cref{eq:fidelity-gg-th} \ncan be adapted by substituting\n\\begin{equation}\n\\Omega = \\vbr{p},\\qquad \\omega = p\\,\\coth\\frac{\\pp p}{2\\lambda}\\quad\n\\text{and}\\quad T = T_\\text{HD} \\equiv \\frac{\\lambda}{2\\pp},\n\\end{equation}\nyielding the \\emph{fidelity per mode}\n\\begin{equation}\nF^\\rbr{p} = \\frac{\\sqrt{u-1}}{\\sqrt[4]{u^2+u+1}},\\qquad\nu \\coloneqq \\ee^q \\equiv \\ee^{\\vbr{p}/T_\\text{HD}},\n\\label{eq:fidelity-pt}\n\\end{equation}\nso that the trace distance per Fourier mode can be evaluated, see \n\\cref{fig:trace-dist-per-mode}.\n\n\\begin{figure}\n\\begin{center}\n\\input{./graphics/graph_trace_dist_mode_bounds}\n\\end{center}\n\\caption[Possible value of the trace distance per Fourier mode]{Possible value \nof the trace distance between mode wave functions in \n\\cref{eq:wave-function-decomposed} and the corresponding thermal density \noperators. One sees that the difference becomes exponentially small with respect \nto $p/T_\\text{HD}$, which suggests it would be difficult to distinguish the pure \nand thermal descriptions by detecting the high-energy modes in the Hawking \nradiation, confirming the results in \\cref{sec:corr_Fourier}.\n\\label{fig:trace-dist-per-mode}}\n%, evaluated in terms of lower and upper bound by fidelity\n\\end{figure}\n\nTo approach the trace distance for the wave functional and the total thermal \nstate, one needs to deal with the product with continuous index in \n\\cref{eq:expectation-decomposed}. A popular way to go to the `continuous limit' \nin \\emph{summation} is\n\\begin{equation}\n\\sum_p \\rfun{g}{p} \\to \\frac{1}{2\\pp\\Lambda} \\int \\dd p\\,\\rfun{g}{p},\n\\end{equation}\nwhere $\\Lambda$ has the same dimension as $p$ in order to fix the dimension; in \nthe box-normalisation scheme, for example, the corresponding $\\Lambda$ would be \nproportional to the volume of the box $V$. A similar method may be used to \nnormalise the product, namely\n\\begin{equation}\n\\prod_p \\rfun{f}{p} = \\cfun{\\exp}{\\sum_p \\ln\\rfun{f}{p}} \\to \n\\cfun{\\exp}{\\frac{1}{2\\pp\\Lambda}\\int \\dd p\\,\\ln\\rfun{f}{p}}.\n\\end{equation}\nNote that the wave functional \\cref{eq:squeezed-wave-functional}, which has \nalways been dealt with, can also be seen as being normalised by the method.\nOne thus derives\n\\begin{equation}\nF = \\cfun{\\exp}{\\frac{2}{2\\pp\\Lambda}\\int_0^{+\\infty}\\dd p\\,\\ln F^\\rbr{p}}\n= \\rfun{\\exp}{-\\frac{\\pp}{9} \\frac{T_\\text{HD}}{\\Lambda}},\n\\end{equation}\nwhich is shown in \\cref{fig:trace-dist-total}.\n\n\\begin{figure}\n\\begin{center}\n\\input{./graphics/graph_trace_dist_total_bounds}\n\\end{center}\n\\caption[Possible value of the trace distance between pure and thermal \ndescriptions]{Possible value of the trace distance between the pure and thermal \ndescriptions of the Hawking radiation field. One sees that the difference \nbetween the two cases is positively (negatively) correlated with the Hawking \ntemperature temperature (mass of black hole). \n\\label{fig:trace-dist-total}}\n\\end{figure}\n\n%------------------------------------------------------------------------------\n\\section{Discussion}\n\\label{sec:dist-discussion}\n%------------------------------------------------------------------------------\nStrictly speaking, the formalism in \\cref{sec:arbitrary-canonical} is \\emph{not}\napplicable to the radiation field considered here, because they were proved for \n\\emph{finite dimensional systems}, while the cases in this work are all \n\\emph{infinite-dimensional}. However, since a regularised result can be \nobtained, it is believable that a mathematically rigorous approach exists, which \nwill justify the result, similar to the renormalisation procedure in quantum \nfield theory.\n\nThough the asymptotic behaviour of the trace distance with respect to Hawking \ntemperature has clearly been revealed by setting bounds to it, it is still \nappealing to calculate its \\emph{exact value}. One possible approach is by \nusing the results in \\cite{Joos1985}, where the eigenfunctions and eigenvalues \nof a general Gaussian density operator have been explicitly solved.\n\nThe evaluation of the trace distance was motivated by \\citeauthor{Hsu2009} in \n\\cite{Hsu2009}, where operational meaning of the distance was also discussed in \nterms of toy models, which is unfortunately not applicable to the field system. \nIn future works, it is expected that the distance between the pure and thermal \nstates will be understood in terms of \\emph{experiments} or \\emph{observations}, \nwhere the essence of physical science lies.\n\n\n%%% Local Variables: \n%%% mode: latex\n%%% TeX-master: \"../mythesis\"\n%%% End: \n", "meta": {"hexsha": "eaaa35262fd7c611f73d5dd9390beff24031777d", "size": 12770, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ubonn-thesis-current/mythesis/sections/thesis_dist.tex", "max_stars_repo_name": "cmp0xff/Masterarbeit", "max_stars_repo_head_hexsha": "b29c84f9a29e4a7c9a3499658a1dfa7f87d64c9c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ubonn-thesis-current/mythesis/sections/thesis_dist.tex", "max_issues_repo_name": "cmp0xff/Masterarbeit", "max_issues_repo_head_hexsha": "b29c84f9a29e4a7c9a3499658a1dfa7f87d64c9c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ubonn-thesis-current/mythesis/sections/thesis_dist.tex", "max_forks_repo_name": "cmp0xff/Masterarbeit", "max_forks_repo_head_hexsha": "b29c84f9a29e4a7c9a3499658a1dfa7f87d64c9c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.1217712177, "max_line_length": 81, "alphanum_fraction": 0.7041503524, "num_tokens": 3764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3497261489931118}}
{"text": "\\hypertarget{classnumpp_1_1matrix_1_1sparse_1_1block}{}\\section{numpp\\+:\\+:matrix\\+:\\+:sparse\\+:\\+:block$<$ T, Rows, Columns $>$ Class Template Reference}\n\\label{classnumpp_1_1matrix_1_1sparse_1_1block}\\index{numpp\\+::matrix\\+::sparse\\+::block$<$ T, Rows, Columns $>$@{numpp\\+::matrix\\+::sparse\\+::block$<$ T, Rows, Columns $>$}}\n\n\nBlock version of sparse matrix.  \n\n\n\n\n{\\ttfamily \\#include $<$sparse\\+\\_\\+block.\\+hpp$>$}\n\n\\subsection*{Public Types}\n\\begin{DoxyCompactItemize}\n\\item \n\\mbox{\\Hypertarget{classnumpp_1_1matrix_1_1sparse_1_1block_ae63cfc45208606404488f5fe326bb1d3}\\label{classnumpp_1_1matrix_1_1sparse_1_1block_ae63cfc45208606404488f5fe326bb1d3}} \nusing {\\bfseries value\\+\\_\\+type} = T\n\\item \n\\mbox{\\Hypertarget{classnumpp_1_1matrix_1_1sparse_1_1block_a9cc87ccc78269d5061ede24a826095b7}\\label{classnumpp_1_1matrix_1_1sparse_1_1block_a9cc87ccc78269d5061ede24a826095b7}} \nusing {\\bfseries size\\+\\_\\+type} = std\\+::size\\+\\_\\+t\n\\item \n\\mbox{\\Hypertarget{classnumpp_1_1matrix_1_1sparse_1_1block_a2e487b67c00d269e7e64f59548e9de61}\\label{classnumpp_1_1matrix_1_1sparse_1_1block_a2e487b67c00d269e7e64f59548e9de61}} \nusing {\\bfseries reference} = T \\&\n\\item \n\\mbox{\\Hypertarget{classnumpp_1_1matrix_1_1sparse_1_1block_a469a9838360107bb0ad15b5f8b22910f}\\label{classnumpp_1_1matrix_1_1sparse_1_1block_a469a9838360107bb0ad15b5f8b22910f}} \nusing {\\bfseries const\\+\\_\\+reference} = const T \\&\n\\item \n\\mbox{\\Hypertarget{classnumpp_1_1matrix_1_1sparse_1_1block_a51437641f0fb291201fa88ade1ecc187}\\label{classnumpp_1_1matrix_1_1sparse_1_1block_a51437641f0fb291201fa88ade1ecc187}} \nusing {\\bfseries pointer} = T $\\ast$\n\\item \n\\mbox{\\Hypertarget{classnumpp_1_1matrix_1_1sparse_1_1block_a810d06f6c2e6b0e92f73bbb971eeff7c}\\label{classnumpp_1_1matrix_1_1sparse_1_1block_a810d06f6c2e6b0e92f73bbb971eeff7c}} \nusing {\\bfseries const\\+\\_\\+pointer} = const T $\\ast$\n\\end{DoxyCompactItemize}\n\\subsection*{Public Member Functions}\n\\begin{DoxyCompactItemize}\n\\item \n\\mbox{\\Hypertarget{classnumpp_1_1matrix_1_1sparse_1_1block_a83470439e34e65f8abc0d59c81bf09c4}\\label{classnumpp_1_1matrix_1_1sparse_1_1block_a83470439e34e65f8abc0d59c81bf09c4}} \n{\\bfseries block} (const \\hyperlink{classnumpp_1_1matrix_1_1sparse_1_1block}{block} \\&)=default\n\\item \n\\mbox{\\Hypertarget{classnumpp_1_1matrix_1_1sparse_1_1block_a48e8a9c7c0610bb7e8b84b67db6e5a6c}\\label{classnumpp_1_1matrix_1_1sparse_1_1block_a48e8a9c7c0610bb7e8b84b67db6e5a6c}} \n{\\bfseries block} (\\hyperlink{classnumpp_1_1matrix_1_1sparse_1_1block}{block} \\&\\&)=default\n\\item \n\\mbox{\\Hypertarget{classnumpp_1_1matrix_1_1sparse_1_1block_aecf67898fb5cd432a940c4cb22b6790b}\\label{classnumpp_1_1matrix_1_1sparse_1_1block_aecf67898fb5cd432a940c4cb22b6790b}} \n\\hyperlink{classnumpp_1_1matrix_1_1sparse_1_1block}{block} \\& {\\bfseries operator=} (\\hyperlink{classnumpp_1_1matrix_1_1sparse_1_1block}{block} \\&\\&)=default\n\\item \n\\mbox{\\Hypertarget{classnumpp_1_1matrix_1_1sparse_1_1block_a8ba9f28a47fd22af6fc63d6ba2a467ce}\\label{classnumpp_1_1matrix_1_1sparse_1_1block_a8ba9f28a47fd22af6fc63d6ba2a467ce}} \n\\hyperlink{classnumpp_1_1matrix_1_1sparse_1_1block}{block} \\& {\\bfseries operator=} (const \\hyperlink{classnumpp_1_1matrix_1_1sparse_1_1block}{block} \\&)=default\n\\item \n\\mbox{\\Hypertarget{classnumpp_1_1matrix_1_1sparse_1_1block_ab613bba3b224199917249af76563a7c3}\\label{classnumpp_1_1matrix_1_1sparse_1_1block_ab613bba3b224199917249af76563a7c3}} \n{\\bfseries block} (std\\+::initializer\\+\\_\\+list$<$ std\\+::initializer\\+\\_\\+list$<$ T $>$$>$ elements)\n\\item \n\\mbox{\\Hypertarget{classnumpp_1_1matrix_1_1sparse_1_1block_a0cafdc2b3674aa15cfe3575ed8d797c4}\\label{classnumpp_1_1matrix_1_1sparse_1_1block_a0cafdc2b3674aa15cfe3575ed8d797c4}} \nsize\\+\\_\\+type {\\bfseries size} () const noexcept\n\\item \n\\mbox{\\Hypertarget{classnumpp_1_1matrix_1_1sparse_1_1block_a36977c382b70c3865ab252138d4617f4}\\label{classnumpp_1_1matrix_1_1sparse_1_1block_a36977c382b70c3865ab252138d4617f4}} \nconst std\\+::array$<$ std\\+::vector$<$ T $>$, Rows $>$ \\& {\\bfseries data} () const noexcept\n\\item \n\\mbox{\\Hypertarget{classnumpp_1_1matrix_1_1sparse_1_1block_acd407b6661d5051136ec040a009651d8}\\label{classnumpp_1_1matrix_1_1sparse_1_1block_acd407b6661d5051136ec040a009651d8}} \nstd\\+::array$<$ std\\+::vector$<$ T $>$, Rows $>$ \\& {\\bfseries data} () noexcept\n\\item \n{\\footnotesize template$<$typename U $>$ }\\\\auto \\hyperlink{classnumpp_1_1matrix_1_1sparse_1_1block_a9ee2ec26bf97fe00dfc11957de26156c}{operator$\\ast$} (const \\hyperlink{classnumpp_1_1vector}{numpp\\+::vector}$<$ U, Columns, false $>$ \\&vec)\n\\end{DoxyCompactItemize}\n\n\n\\subsection{Detailed Description}\n\\subsubsection*{template$<$typename T, std\\+::size\\+\\_\\+t Rows, std\\+::size\\+\\_\\+t Columns$>$\\newline\nclass numpp\\+::matrix\\+::sparse\\+::block$<$ T, Rows, Columns $>$}\n\nBlock version of sparse matrix. \n\n\n\\begin{DoxyTemplParams}{Template Parameters}\n{\\em T} & arithmetic type contained in matrix class \\\\\n\\hline\n{\\em Rows} & number of rows in matrix \\\\\n\\hline\n{\\em Columns} & number of columns in matrix\\\\\n\\hline\n\\end{DoxyTemplParams}\n{\\bfseries This implementation is an experiment in cache hit-\\/rate.~\\newline\n } Whole sparse matrix is contained in one array, divided based on blocks of contiguous non-\\/zero numbers.~\\newline\nAfter each block operation calculating row is performed.\n\n\\begin{DoxyWarning}{Warning}\n{\\bfseries For parallelization of the sparse matrix dense vector multiplication you need compiler with Open\\+MP support} \n\nOnly sparse matrix dense vector multiplication implemented \n\n{\\bfseries Each row has to be seperate std\\+::initializer\\+\\_\\+list}\n\\end{DoxyWarning}\n{\\bfseries Pros\\+:}\n\\begin{DoxyItemize}\n\\item Obviously lower memory overhead, for 50\\% sparse matrix with no blocks it contains only 150\\% storage of dense matrix.\n\\item Higher cache locality (at least in theory)\n\\end{DoxyItemize}\n\n{\\bfseries Cons\\+:}\n\\begin{DoxyItemize}\n\\item Impossible S\\+I\\+MD optimization\n\\item Additional operations of read for every block\n\\end{DoxyItemize}\n\n{\\bfseries Example\\+:} \n\\begin{DoxyCode}\n\\hyperlink{classnumpp_1_1matrix_1_1sparse_1_1nested}{numpp::matrix::sparse::nested<double, 3,3>} mat\\{\\{0,  0,   1\\},\n                                                \\{0,  2.3, 0\\},\n                                                \\{0,  0,   13.7\\}\n                                               \\};\nconstexpr numpp::matrix::vector<double, 3> vec\\{1,2,3\\};\n\\textcolor{keyword}{auto} result = mat*vec;\n\\end{DoxyCode}\n\n\n\n\\begin{DoxyCode}\n\\textcolor{preprocessor}{#include\"numpp/structures/matrices/sparse.hpp\"}\n\\end{DoxyCode}\n \n\n\\subsection{Member Function Documentation}\n\\mbox{\\Hypertarget{classnumpp_1_1matrix_1_1sparse_1_1block_a9ee2ec26bf97fe00dfc11957de26156c}\\label{classnumpp_1_1matrix_1_1sparse_1_1block_a9ee2ec26bf97fe00dfc11957de26156c}} \n\\index{numpp\\+::matrix\\+::sparse\\+::block@{numpp\\+::matrix\\+::sparse\\+::block}!operator$\\ast$@{operator$\\ast$}}\n\\index{operator$\\ast$@{operator$\\ast$}!numpp\\+::matrix\\+::sparse\\+::block@{numpp\\+::matrix\\+::sparse\\+::block}}\n\\subsubsection{\\texorpdfstring{operator$\\ast$()}{operator*()}}\n{\\footnotesize\\ttfamily template$<$typename T , std\\+::size\\+\\_\\+t Rows, std\\+::size\\+\\_\\+t Columns$>$ \\\\\ntemplate$<$typename U $>$ \\\\\nauto \\hyperlink{classnumpp_1_1matrix_1_1sparse_1_1block}{numpp\\+::matrix\\+::sparse\\+::block}$<$ T, Rows, Columns $>$\\+::operator$\\ast$ (\\begin{DoxyParamCaption}\\item[{const \\hyperlink{classnumpp_1_1vector}{numpp\\+::vector}$<$ U, Columns, false $>$ \\&}]{vec }\\end{DoxyParamCaption})\\hspace{0.3cm}{\\ttfamily [inline]}}\n\nFunction multiplying sparse matrix and dense vector\n\n\n\\begin{DoxyParams}{Parameters}\n{\\em vec} & Vector which will be multiplied \\\\\n\\hline\n\\end{DoxyParams}\n\\begin{DoxyReturn}{Returns}\nvector$<$\\+U, Rows, false$>$ \n\\end{DoxyReturn}\n\n\nThe documentation for this class was generated from the following file\\+:\\begin{DoxyCompactItemize}\n\\item \nstructures/matrices/sparse/sparse\\+\\_\\+block.\\+hpp\\end{DoxyCompactItemize}\n", "meta": {"hexsha": "efc3c28b1b7817e435bfed9091c928d3a8cbab7d", "size": 7867, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/classnumpp_1_1matrix_1_1sparse_1_1block.tex", "max_stars_repo_name": "szymonmaszke/numpp", "max_stars_repo_head_hexsha": "9149c9d81f70a6ce833fdd1d2f0f2b584e2ac4d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2018-06-06T01:51:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-02T15:17:00.000Z", "max_issues_repo_path": "docs/classnumpp_1_1matrix_1_1sparse_1_1block.tex", "max_issues_repo_name": "vyzyv/numpp", "max_issues_repo_head_hexsha": "9149c9d81f70a6ce833fdd1d2f0f2b584e2ac4d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-11-28T12:15:46.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-16T00:03:38.000Z", "max_forks_repo_path": "docs/classnumpp_1_1matrix_1_1sparse_1_1block.tex", "max_forks_repo_name": "szymonmaszke/numpp", "max_forks_repo_head_hexsha": "9149c9d81f70a6ce833fdd1d2f0f2b584e2ac4d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-08-06T13:58:27.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-06T06:45:22.000Z", "avg_line_length": 55.013986014, "max_line_length": 316, "alphanum_fraction": 0.7799669506, "num_tokens": 3042, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.3495820469459447}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\marginpar{Tuesday\\\\ 2020-11-3, \\\\ compiled \\\\ \\today}\n\n\\begin{figure}[ht]\n\\centering\n\\includegraphics[width=\\textwidth]{figures/roche-equipotential}\n\\caption{Equipotential lines for the Roche potential \\(\\phi _R\\). \\(M_{1, 2}\\) mark the two masses, while the Lagrange points\\(L\\) are the ones in which the potential is stationary: \\(\\nabla \\phi _R = 0\\).}\n\\label{fig:roche-equipotential}\n\\end{figure}\n\n% The equation of motion of a particle in the corotating frame is \n% %\n% \\begin{align}\n% \\pdv{\\vec{v}}{t} \n% + \\qty(\\vec{v} \\cdot \\vec{\\nabla}) \\vec{v}\n% = - \\frac{1}{\\rho } \\vec{\\nabla} P \n% - \\vec{\\omega} \\wedge \\vec{v}\n% - \\vec{\\nabla} \\phi _R\n% \\,,\n% \\end{align}\n% %\n% where \\(\\phi _R\\) is the Roche potential, which can be written in terms of the parameters \\(q = M_2 / M_1 \\) and \\(a\\);\n%\n% \\todo[inline]{there might be a wrong sign in the last lecture!} \n%\n% \\begin{align}\n% \\phi _R = - \\frac{GM_1}{\\abs{\\vec{r} - \\vec{r}_1}}\n% - \\frac{GM_2}{\\abs{\\vec{r} - \\vec{r}_2}}\n% - \\frac{1}{2} \\qty(\\vec{\\omega} \\wedge \\vec{r})^2\n% \\,.\n% \\end{align}\n% \\todo[inline]{insert diagram for the quantities in the potential}\n\nAlso, if \\(\\theta \\) is the angle between \\(\\vec{\\omega}\\) and \\(\\vec{r}\\) we can write \n%\n\\begin{align}\n\\qty(\\vec{\\omega} \\wedge \\vec{r})^2 = \\omega^2 r^2 \\sin^2 \\theta \n\\,.\n\\end{align}\n\nLet us come back to the Roche potential, whose equipotential contours we sketch in figure \\ref{fig:roche-equipotential}. \nIn terms of the aforementioned variables \\(q\\) and \\(\\theta \\) it can be written as\n%\n\\begin{align}\n\\phi _R &=  \n- G (M_1 + M_2 ) \\qty[ + \\frac{1}{2} \\frac{\\omega^2 r^2 \\sin^2\\theta }{G (M_1 + M_2 )}\n+ \\frac{GM_1 }{G (M_1 + M_2 ) \\abs{\\vec{r} - \\vec{r}_1 }}\n+ \\frac{GM_2 }{G (M_1 + M_2 ) \\abs{\\vec{r} - \\vec{r}_2 }}\n ]  \\\\\n &= - G (M_1 + M_2 )\n \\qty[\n     \\frac{1}{2} \\frac{\\omega^2r^2 \\sin^2\\theta }{G(M_1 + M_2 )} \n     + \\frac{1}{(1 + q) \\abs{\\vec{r} - \\vec{r}_1}}\n     + \\frac{q}{(1 + q) \\abs{\\vec{r} - \\vec{r}_2}}\n ]\n\\,.\n\\end{align}\n\nWe can then use Cartesian coordinates centered in \\(M_1 \\): \nthen, \n%\n\\begin{align}\n\\phi _R = - \\frac{G (M_1 + M_2  )}{2 a^3}\n\\qty[ \\frac{2 a^3}{1 + q}\n\\frac{1}{\\sqrt{x^2 +y^2 +z^2}}\n+\n\\frac{2 q a^3}{1 + q} \n\\frac{1}{\\sqrt{(x-a)^2 + y^2 +z^2}}\n+ \\qty[(x - x _{\\text{CM}})^2 + y^2]\n]\n\\,,\n\\end{align}\n%\nwhere \n%\n\\begin{align}\nx _{\\text{CM}} = \\frac{qa}{1 + q}\n\\,,\n\\end{align}\n%\nso if we rescale all the spatial coordinates by the major semi axis \\(a\\) we get \n%\n\\begin{align}\n\\phi _R = - \\frac{G (M_1 + M_2 )}{2a}\n\\qty[\n\\frac{2}{1 +q}\n\\frac{1}{\\sqrt{x^2 +y^2 +z^2}} \n+\n\\frac{2 q}{1 + q} \n\\frac{1}{\\sqrt{(x-1)^2 + y^2 + z^2}}\n+ \\qty[\\qty(x - \\frac{q}{1 + q})^2 + y^2]\n]\n\\,.\n\\end{align}\n\nIf the stars are stationary, or in slow evolution. Then, their surfaces will be (at least in first approximation) at rest. Therefore, the derivative terms vanish, and we get \n%\n\\begin{align}\n0  = - \\frac{1}{\\rho } \\vec{\\nabla} P - \\vec{\\nabla} \\phi _R\n\\,,\n\\end{align}\n%\nbut the surface is defined by \\(\\vec{\\nabla} P = 0\\), which by this equation corresponds to \\(\\vec{\\nabla} \\phi _R = 0\\). \n\nThe star will then take the shape of an equi-Roche potential surface. \nWhat is this shape? See \\ref{fig:roche-equipotential}.\n\n% \\todo[inline]{Make 2D plots, cuts of the surface}\n\n\\subsection{The Roche lobe}\n\nWe have roughly spherical contours near the stars, and a figure-eight contour eventually.\nThe center of this contour is called \\(L_1 \\), the first or ``inner'' Lagrange point. \n\nAnalogy with a dog food container for Roche Lobe overflow.\n\nIs the overflow stable? It depends on whether the volume of the Roche lobe increases or decreases as the donor star loses mass: in the latter case. \n\n% Tight worn jeans? \n\nWe can introduce a characteristic \\textbf{radius} of the Roche Lobe, calculated by \n%\n\\begin{align}\nV _{\\text{lobe}} = \\frac{4}{3} \\pi R _{\\text{lobe}}^3\n\\,,\n\\end{align}\n%\nalthough the lobe is not a sphere this allows us to give a characteristic number. \nWe can calculate \\cite[]{eggletonApproximationsRadiiRoche1983}:\n%\n\\begin{align}\n\\frac{R_{\\text{lobe}}}{a} = f(q) \\approx\n\\begin{cases}\n    \\num{.38} + \\num{.2} \\log_{10} q  & \\num{.5} < q < \\num{20}\\\\\n    \\num{.46}  \\qty( \\frac{q}{1 + q})^{1/3}\n    & 0 < q < \\num{.5}\n\\end{cases} \n\\,,\n\\end{align}\n%\nand we can see that the dependence on \\(q\\) is quite weak. A plot of this is shown in figure \\ref{fig:roche-lobe-radius}:\n%\n\\begin{figure}[ht]\n\\centering\n\\includegraphics[width=\\textwidth]{figures/roche-lobe-radius}\n\\caption{Radius of the Roche lobe as a function of \\(q\\).}\n\\label{fig:roche-lobe-radius}\n\\end{figure}\n\nHowever, the orbital separation \\(a\\) is itself a function of \\(q\\), and the dependence \\(a(q)\\) is much more relevant than the dependence of \\(R _{\\text{lobe}} / a\\). \n\nIn order to calculate \\(a(q)\\), let us make some assumptions. \n\\begin{enumerate}\n    \\item \\(M_1 + M_2 = \\const\\). This is realistic: it is hard for the binary star system as a whole to lose or gain mass.\n    \\item The total angular momentum \\(L _{\\text{tot}}\\) is a constant. This is a bit tricky: even a small amount of mass loss can result in high angular momentum loss. \n    \\item \\(L _{\\text{tot}} = L _{\\text{orb}}\\): all the angular momentum is orbital. We are neglecting the spins of the stars, and the angular momentum of the gas. This is realistic, since tidal forces move the configuration towards a tidally locked state. \n\\end{enumerate}\n\nThe conservation of mass tells us that \\(M_1 (1 + q)\\) is constant. \nThe orbital angular momentum is written in terms of the distances of the stars from the center of mass:\n%\n\\begin{align}\nL _{\\text{orb}} &= M_1 v_1 a_1 + M_2 v_2 a_2  \\\\\n&= M_1 a_1^2 \\omega + M_2 a_2^2 \\omega \n\\,,\n\\end{align}\n%\nso if we place the origin of our coordinates in the center of mass we can write everything in terms of the orbital separation \\(a = a_1 + a_2 \\):\n% \\todo[inline]{So \\(a\\) is not the semimajor axis}\n%\n\\begin{align}\n-M_1 a_1 + M_2 a_2 &= 0  \\\\\n- (M_1 + M_2 ) a_1 + M_2 a &= 0  \\\\\na_1 &= \\frac{qa}{1+q} \\\\\na_2 &= \\frac{a}{1 +q}\n\\,.\n\\end{align}\n\nIn terms of angular momentum we get \n%\n\\begin{align}\n\\qty[\n    M_1 \\frac{q^2 a^2}{(1 + q)^2}\n    + M_2 \\frac{a^2}{(1+q)^2}\n]\\omega &= \\const \\\\\nM_1 a^2\n\\qty[\n    \\frac{q^2}{(1 + q)^2}\n    + \\frac{q}{(1+q)^2}\n]\\omega &= \\const \n\\,,\n\\end{align}\n%\nwhich means \n%\n\\begin{align}\n\\frac{a^2 M_1 \\omega q}{1 + q} =\n\\frac{a^2 M_1 2 \\pi  q}{P(1 + q)} \n= \\const\n\\,,\n\\end{align}\n%\nsince \\(\\omega = 2\\pi / P\\), where \\(P\\) is the orbital period. \nWe also know that (because of mass conservation) \\(M_1 \\propto (1 + q)^{-1}\\), therefore \n%\n\\begin{align}\n\\frac{a^2 q}{(1+q)^2} \\frac{1}{P}\n\\,,\n\\end{align}\n%\nbut also Kepler's third law tells us that \\(a^3 \\propto P^2\\): so, \\(P \\propto a^{3/2}\\). This yields \n%\n\\begin{align}\n\\frac{a^{2 - 3/2} q}{(1+q)^2} = \\sqrt{a} \\frac{q}{(1+q)^2} = \\const\n\\,,\n\\end{align}\n%\ntherefore \n%\n\\begin{align}\na \\propto \\frac{(1 + q)^{4}}{q^2}\n\\,.\n\\end{align}\n\nThe Roche lobe \\(R_2\\) for \\(M_2\\) is given by \\(R_2 = a f\\), therefore\n%\n\\begin{align}\n\\log R_2 = \\log a + \\log f\n\\,,\n\\end{align}\n%\nand if we consider a variation of \\(q\\), the variation of \\(\\log R_2 \\) will be given by the sum of the variations of the two logarithms. \n\nBecause of the expression we derived, we have \n%\n\\begin{align}\n\\log a &= 4 \\log (1 +q) - 2 \\log q + \\const \\\\\n\\Delta \\log a &= 4 \\frac{\\Delta q}{1 + q} - 2 \\frac{\\Delta q}{q }  \\\\\n&= \\frac{4q -2 -2 q}{(1 + q) q} \\Delta q = 2 \\frac{\\Delta q}{q} \\frac{q -1}{q +1}\n\\,.\n\\end{align}\n\nThen, the fractional variation is approximately \n%\n\\begin{align}\n\\frac{\\Delta R_2}{R_2} = \\Delta \\log R_2 \\approx \n2\\frac{\\Delta q}{q} \\frac{q -1}{q +1}\n\\,,\n\\end{align}\n%\nsince \\(\\Delta \\log f\\) is negligible (see figure \\ref{fig:roche-lobe-relative-corrections}). \nAs the star \\(M_2 \\) donates mass, \\(M_2 \\) decreases and \\(M_1 \\) increases. Then, \\(q = M_2 / M_1 \\) decreases, therefore \\(\\Delta q < 0\\). \n\n\\begin{figure}[ht]\n\\centering\n\\includegraphics[width=\\textwidth]{figures/roche-lobe-relative-corrections.pdf}\n\\caption{Relative size of the corrections --- \\(\\Delta \\) means derivative with respect to \\(q\\). One can notice that for typical \\(q \\gtrsim 2\\) the magnitude of \\(\\Delta \\log a\\) is about one order of magnitude larger than that of \\(\\Delta \\log f\\). Also, we can see that \\(\\Delta \\log a + \\Delta \\log f\\) is indeed positive for \\(q > 1\\) --- the curve is not shown in the region in which it is negative.}\n\\label{fig:roche-lobe-relative-corrections}\n\\end{figure}\n\nIf we want the Roche lobe to shrink, we want \\(\\Delta R_2 < 0\\): so, we want \\(q - 1 > 0\\). \nThis means that \\textbf{Roche lobe accretion is self-sustaining, or stable iff the donor star is larger than the receiver}. \n% Including \\(\\Delta f\\), things don't change by much. \nIf we include \\(\\Delta f\\), as one can see in figure \\ref{fig:roche-lobe-relative-corrections}, the picture is quite similar --- the noticeable correction we have is that systems with \\(\\num{.8} < q < 1\\) might still have Roche Lobe Overflow. \n\nIs this the case in real systems? Usually the mass of the BH is of at least a few solar masses, so we need an unusually large companion. \nFor example, the companion to the BH in Cygnus X-1 is a very large O-star. \n\n\\section{Accretion disks}\n\nNow we will discuss what happens when this is indeed the case. What is the fate of the matter passing through the inner Lagrange point? \n\n\\subsection{Circularization}\n\nLet us change the perspective: we are not comoving with respect to the orbiting stars anymore. \nLet us call \\(b_1 \\) the separation of the \\(L_1 \\) point from the center of star 1. This is slightly larger than \\(R_1 \\). \n\nIf we are stationary at the center the companion compact star will appear to rotate at a large velocity compared to us. \n\nThe components of this velocity can be decomposed into the parallel and perpendicular to the separation vector between the star, however the component \\(v _ \\parallel\\) will be of the order of the speed of sound in the gas: roughly, \n%\n\\begin{align}\nv_{\\parallel} \\approx c_s = \\sqrt{ \\pdv{P}{\\rho }} = \\sqrt{\\frac{k_B T}{\\mu m_p}} \\approx \\num{10} \\sqrt{ \\frac{T}{\\SI{e4}{K}}} \\SI{}{km /s}\n\\,;\n\\end{align}\n%\nwhile the component \\(v_\\perp\\) will be large: of the order of \n%\n\\begin{align}\nv_\\perp \\sim b_1 \\omega \n\\,,\n\\end{align}\n%\nand the distance \\(b_1\\) will be roughly given by \\cite[]{plavecTablesRocheModel1964}\n%\n\\begin{align}\nb_1 \\approx a (\\num{.5} - \\num{.227} \\log q)\n\\,,\n\\end{align}\n%\nwhile by Kepler's third law \n%\n\\begin{align}\n4 \\pi^2 a^3 = G (M_1 + M_2 ) P^2\n\\,,\n\\end{align}\n%\nso \n%\n\\begin{align}\na \\approx \\num{3e11} \\qty(\\frac{M_1 }{M_{\\odot}})^{1/3}\n\\qty(1 + q)^{1/3}\n\\qty(\\frac{P}{\\SI{1}{d}})^{2/3} \n\\SI{}{cm}\n\\,,\n\\end{align}\n%\nwhile the angular velocity is \n%\n\\begin{align}\n\\omega = \\frac{2 \\pi }{P} \\approx \\num{7e-5} \\qty(\\frac{P}{\\SI{1}{d}})^{-1} \\SI{}{rad/s}\n\\,.\n\\end{align}\n\nThis means that the perpendicular velocity is approximately \n%\n\\begin{align}\nv_{\\perp} \\approx \\num{100} \\qty(\\frac{M_1 }{M_{\\odot}})^{1/3}\n\\qty(1 + q)^{1/3}\n\\qty(\\frac{P}{\\SI{1}{d}})^{-1/3}\n\\SI{}{km/s}\n\\,,\n\\end{align}\n%\nan order of magnitude more than the speed of sound. \n\n\\end{document}\n", "meta": {"hexsha": "47b46f48d1f612033bea2e875cd48861e29bb638", "size": 11128, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ap_third_semester/compact_objects/nov03.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "ap_third_semester/compact_objects/nov03.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ap_third_semester/compact_objects/nov03.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 32.7294117647, "max_line_length": 407, "alphanum_fraction": 0.6454888569, "num_tokens": 4032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.34958202995258797}}
{"text": "\\documentclass[../notes.tex]{subfiles}\n\n\\pagestyle{main}\n\\renewcommand{\\chaptermark}[1]{\\markboth{\\chaptername\\ \\thechapter\\ (#1)}{}}\n\\setcounter{chapter}{19}\n\n\\begin{document}\n\n\n\n\n\\chapter{The Second Law of Thermodynamics}\n\\section{Thermodynamic Cycles}\n\\begin{itemize}\n    \\item \\marginnote{8/23:}Examples: Engines and pumps.\n    \\item In a thermodynamic cycle, the energy doesn't change, so $W_\\text{on gas}=-Q$, i.e., $W_\\text{by gas}=Q_\\text{net}$.\n    \\item Thus, $W_\\text{by engine}=Q_\\text{in}-Q_\\text{out}$ per cycle.\n    \\item \\textbf{Otto cycle}: The thermodynamic cycle used in car engines. \\emph{Also known as} \\textbf{auto cycle}.\n    \\begin{figure}[h!]\n        \\centering\n        \\begin{tikzpicture}[\n            scale=1.8,\n            every node/.append style={black},\n            pics/point/.style args={#1:#2}{code={\n                \\node [circle,fill=pix,inner sep=1.5pt,label={#1:$#2$}] {};\n            }}\n        ]\n            \\footnotesize\n            \\draw [stealth-stealth] (0,2) node[above]{$p$} -- (0,0) -- (3,0) node[right]{$V$};\n    \n            \\draw [blx,thick,dashed] plot[domain=1:2.5,samples=500] (\\x,{1.67/\\x});\n            \\draw [blx,thick,dashed] plot[domain=0.6:2.5,samples=500] (\\x,{1/\\x});\n            \\draw [blx,thick,dashed] plot[domain=0.3:2.5,samples=500] (\\x,{0.5/\\x});\n            \\draw [blx,thick,dashed] plot[domain=0.12:2.5,samples=500] (\\x,{0.2/\\x});\n    \n            \\draw [orx,very thick,postaction={decorate},decoration={\n                markings,\n                mark=at position 0.25  with {\\arrow{>} \\node[above right,fill=white,inner sep=1.5pt]{$Q=0$};},\n                mark=at position 0.465 with {\\arrow{>} \\node[right=3pt,fill=white,inner sep=1.5pt]{$Q_\\text{out}$};},\n                mark=at position 0.65  with {\\arrow{>} \\node[below left,fill=white,inner sep=1.5pt]{$Q=0$};},\n                mark=at position 0.91  with {\\arrow{>} \\node[left =3pt,fill=white,inner sep=1.5pt]{$Q_\\text{in}$};}\n            }] plot[domain=0.8:2] (\\x,{0.845/\\x^(1.756)}) -- plot[domain=2:0.8] (\\x,{0.4/\\x^2}) -- cycle;\n    \n            \\pic at (0.8,{1/0.8}) {point=:};\n        \\end{tikzpicture}\n        \\caption{Otto cycle.}\n        \\label{fig:ottoCycle}\n    \\end{figure}\n    \\begin{itemize}\n        \\item Two adiabatic and two isochoric processes.\n    \\end{itemize}\n    \\item \\textbf{Stirling engine cycle}: The thermodynamic cycle used in steam engines.\n    \\begin{figure}[h!]\n        \\centering\n        \\begin{tikzpicture}[\n            scale=1.8,\n            every node/.append style={black},\n            pics/point/.style args={#1:#2}{code={\n                \\node [circle,fill=pix,inner sep=1.5pt,label={#1:$#2$}] {};\n            }}\n        ]\n            \\footnotesize\n            \\draw [stealth-stealth] (0,2) node[above]{$p$} -- (0,0) -- (3,0) node[right]{$V$};\n            \\draw [very thin,dashed] (0.8,{0.5/0.8}) -- (0.8,0) node[below]{$V_1$};\n            \\draw [very thin,dashed] (2,{0.5/2}) -- (2,0) node[below]{$V_2$};\n    \n            \\draw [blx,thick,dashed] plot[domain=1:2.5,samples=500] (\\x,{1.67/\\x});\n            \\draw [blx,thick,dashed] plot[domain=0.6:2.5,samples=500] (\\x,{1/\\x}) node[right]{$T_1$};\n            \\draw [blx,thick,dashed] plot[domain=0.3:2.5,samples=500] (\\x,{0.5/\\x}) node[right]{$T_2$};\n            \\draw [blx,thick,dashed] plot[domain=0.12:2.5,samples=500] (\\x,{0.2/\\x});\n    \n            \\draw [orx,very thick,postaction={decorate},decoration={\n                markings,\n                mark=at position 0.25 with {\\arrow{>} \\node[above=4pt,fill=white,inner sep=1.5pt]{$+Q_2$};},\n                mark=at position 0.45 with {\\arrow{>} \\node[right=3pt,fill=white,inner sep=1.5pt]{$-Q_3$};},\n                mark=at position 0.65 with {\\arrow{>} \\node[below=3pt,fill=white,inner sep=1.5pt]{$-Q_4$};},\n                mark=at position 0.91 with {\\arrow{>} \\node[left =3pt,fill=white,inner sep=1.5pt]{$+Q_1$};}\n            }] plot[domain=0.8:2] (\\x,{1/\\x}) -- plot[domain=2:0.8] (\\x,{0.5/\\x}) -- cycle;\n            \\draw [orx,very thick] plot[domain=0.8:2] (\\x,{1/\\x}) -- plot[domain=2:0.8] (\\x,{0.5/\\x}) -- cycle;\n    \n            \\pic at (0.8,{1/0.8}) {point=:};\n        \\end{tikzpicture}\n        \\caption{Stirling engine cycle.}\n        \\label{fig:stirlingCycle}\n    \\end{figure}\n    \\begin{itemize}\n        \\item Two isothermal and two isochoric processes.\n        \\item For the isothermal processes, $\\Delta E_\\text{int}=0$, so $Q=W_\\text{by gas}=nRT\\ln(V_f/V_i)$.\n        \\item For the isochoric process, $Q=nC_V\\Delta T$.\n        \\item $Q_1+Q_3=nC_V(T_1-T_2)+nC_V(T_2-T_1)=0$, so we only have to worry about $Q_2$ and $Q_4$ to determine the work done by the gas:\n        \\begin{align*}\n            W_\\text{by gas} &= Q_2+Q_4\\\\\n            &= nR\\ln\\left( \\frac{V_2}{V_1} \\right)\\cdot(T_1-T_2)\n        \\end{align*}\n        \\item To get more work, you want the \\textbf{compression factor} to be as big as possible.\n        \\item You also want the difference between the two temperatures to be as big as possible.\n        \\item The engine is powered until $T_1=T_2$, because at that point you can't exchange heat.\n    \\end{itemize}\n    \\item \\textbf{Compression factor}: The ratio of the final volume to the initial volume, i.e., $V_2/V_1$.\n    \\item \\textbf{Efficiency}: The quotient of the work an engine does and the heat you put in per cycle. \\emph{Denoted by} $\\bm{e}$. \\emph{Given by}\n    \\begin{align*}\n        e &= \\frac{W_\\text{engine}}{Q_\\text{in}}\\\\\n        &= \\frac{Q_\\text{in}-Q_\\text{out}}{Q_\\text{in}}\\\\\n        &= 1-\\frac{Q_\\text{out}}{Q_\\text{in}}\n    \\end{align*}\n    \\item \\textbf{Carnot cycle}.\n    \\begin{figure}[h!]\n        \\centering\n        \\begin{tikzpicture}[\n            scale=1.8,\n            every node/.append style={black},\n            pics/point/.style args={#1:#2}{code={\n                \\node [circle,fill=pix,inner sep=1.5pt,label={#1:$#2$}] {};\n            }}\n        ]\n            \\footnotesize\n            \\draw [stealth-stealth] (0,2) node[above]{$p$} -- (0,0) -- (3,0) node[right]{$V$};\n    \n            \\draw [blx,thick,dashed] plot[domain=1:2.5,samples=500] (\\x,{1.67/\\x}) node[right]{$T_H$};\n            \\draw [blx,thick,dashed] plot[domain=0.6:2.5,samples=500] (\\x,{1/\\x});\n            \\draw [blx,thick,dashed] plot[domain=0.3:2.5,samples=500] (\\x,{0.5/\\x}) node[right]{$T_L$};\n            \\draw [blx,thick,dashed] plot[domain=0.12:2.5,samples=500] (\\x,{0.2/\\x});\n    \n            \\draw [orx,very thick,postaction={decorate},decoration={\n                markings,\n                mark=at position 0.13 with {\\arrow{>} \\node[above=6pt,xshift=2pt,fill=white,inner sep=1.5pt]{$Q_\\text{in}$};},\n                mark=at position 0.33 with {\\arrow{>} \\node[right=3pt,fill=white,inner sep=1.5pt]{$Q=0$};},\n                mark=at position 0.58 with {\\arrow{>} \\node[below=3pt,fill=white,inner sep=1.5pt]{$Q_\\text{out}$};},\n                mark=at position 0.81 with {\\arrow{>} \\node[left =3pt,fill=white,inner sep=1.5pt]{$Q=0$};}\n            }] plot[domain=1.1:1.6] (\\x,{1.67/\\x}) plot[domain=1.6:2] (\\x,{21.178/\\x^(6.404)}) plot[domain=2:1.4] (\\x,{0.5/\\x}) plot[domain=1.4:1.1] (\\x,{2.69/\\x^(6.001)});\n    \n            \\pic at (1.1,{1.67/1.1}) {point=:};\n        \\end{tikzpicture}\n        \\caption{Carnot cycle.}\n        \\label{fig:carnotCycle}\n    \\end{figure}\n    \\begin{itemize}\n        \\item Two isothermal and two adiabatic processes.\n        \\item For this engine, $e=1-Q_\\text{out}/Q_\\text{in}=1-T_L/T_H$.\n        \\begin{itemize}\n            \\item Thus, as the temperatures approach each other, efficiency approaches 1.\n            \\item But, you cannot run an engine when the heat bath temperatures are equal to each other.\n        \\end{itemize}\n        \\item Therefore, the Carnot cycle is the most efficient engine you can build, but it's just not physically viable.\n        \\begin{itemize}\n            \\item A car run on the Carnot cycle would have great mileage but wouldn't get you very far.\n        \\end{itemize}\n        \\item Conclusion: The Carnot cycle is interesting, but it does not yield a particularly useful engine.\n    \\end{itemize}\n\\end{itemize}\n\n\n\n\\section{The Second Law}\n\\begin{itemize}\n    \\item \\textbf{Second Law of Thermodynamics}: It is not possible to remove heat at a high temperature and convert it entirely to work done by the engine. In other words, some heat is always exhausted to the low temperature.\n    \\item Maximizing engine efficiency:\n    \\begin{itemize}\n        \\item You want to maximize the temperature difference.\n        \\item You could technically run an engine between air temperature and ice, but it's hard to lug around a bunch of ice.\n        \\item Additionally, you can't have $T_H$ be too high because hotter engines emit nastier exhaust (specifically, exhaust that contributes more to acid rain).\n        \\item Recall that the area on a $pV$-graph encompassed by the cycle is equal to the work done by the gas.\n    \\end{itemize}\n    \\item If you run a heat engine backwards, you get a \\textbf{heat pump}.\n    \\item \\textbf{Heat pump}: A device that removes heat from low temperature sinks and exhausts it into high temperature sinks.\n    \\begin{itemize}\n        \\item This is an air conditioner.\n        \\item The second law of thermodynamics asserts that you can't remove heat at a low temperature and move it to a high temperature without doing work on the gas. Thus, you have to plug in the air conditioner and provide power --- heat won't magically flow from cold to hot.\n    \\end{itemize}\n\\end{itemize}\n\n\n\n\\section{Statistical Mechanics}\n\\begin{itemize}\n    \\item Free expansion.\n    \\begin{itemize}\n        \\item Imagine you have gas on one side of a thermally insulated container separated from the rest of the container by a partition.\n        \\item If you remove the partition, the gas will expand out to fill the entire container.\n        \\item However, the gas is not working against a force ($p=0$) and heat is not flowing in ($Q=0$).\n        \\item Therefore, $\\dd{E_\\text{int}}=\\dd{Q}-p\\dd{V}=0-0\\dd{V}=0$.\n        \\item From this, we can conclude that $\\Delta T=0$.\n        \\item Note that this is an \\textbf{irreversible process}.\n    \\end{itemize}\n    \\item \\textbf{Irreversible process}: A process that looks like it could occur on a microscopic level but could not on a macroscopic level.\n    \\begin{itemize}\n        \\item Imagine a video of the milk molecules moving in a cup of coffee (which would look normal forwards and backwards) vs. a video of milk spreading out in a cup of coffee (which most certainly would not look normal backwards).\n    \\end{itemize}\n    \\item \\textbf{Macrostate}: A set of thermal variables ($n,p,V,T$) defining a system at an instant in time.\n    \\item \\textbf{Microstate}: A way of arranging the molecules in a system that produces a macrostate.\n    \\begin{itemize}\n        \\item Multiple microstates can correspond to the same macrostate.\n    \\end{itemize}\n    \\item Consider a box with 10 molecules inside.\n    \\begin{itemize}\n        \\item Each molecules has a 50/50 chance of being on the left \\emph{or} right side of the box.\n        \\item We want to achieve the macrostate defined by 10 molecules on the left side and 0 on the right.\n        \\begin{itemize}\n            \\item There is only 1 corresponding microstate (namely that just described).\n        \\end{itemize}\n        \\item We want to achieve the macrostate defined by 3 molecules on the left side and 7 on the right.\n        \\begin{itemize}\n            \\item There are $\\frac{10!}{7!3!}=120$ corresponding microstates.\n        \\end{itemize}\n        \\item For the even 5/5 split, there are $\\binom{10}{5}=252$ corresponding microstates.\n    \\end{itemize}\n    \\item If there are $N$ molecules and we want $m$ on the left and $N-m$ on the right, the number of microstates that will realize this macrostate is $\\frac{N!}{m!(N-m)!}$.\n    \\begin{itemize}\n        \\item This corresponds to a binomial distribution.\n    \\end{itemize}\n    \\item \\textbf{Fundamental Assumption of Statistical Physics}: All microstates of a system are equally probable.\n    \\item \\textbf{Number of microstates of a macrostate}: \\emph{Denoted by} $\\bm{\\Omega_\\textbf{macro}}$.\n    \\item It follows from the fundamental assumption that\n    \\begin{equation*}\n        P_\\text{macro} \\propto \\Omega_\\text{macro}\n    \\end{equation*}\n    \\item Relating this back to our example, since $P_{m,N-m}\\propto\\Omega{m,N-m}$ we have that $(5,5)$ is approximately twice as likely as $(3,7)$.\n    \\item If we have $N_A$ of molecules, it is going to be much more likely that the molecules are evenly (or almost evenly) distributed on both sides of the box than anything else.\n    \\begin{itemize}\n        \\item $\\Omega_{N_A,0}=1$ still, but $\\Omega_{N_A/2,N_A/2}=\\frac{N_A!}{(N_A!)^2}\\approx 10^{N_A/3}\\approx 10^{\\num{2e23}}$, which is a huge number.\n    \\end{itemize}\n    \\item If you make $N$ and $m$ continuous rather than integer quantities, the binomial distribution becomes a Gaussian distribution.\n    \\begin{itemize}\n        \\item Thus, Gaussian distributions describe the probability distribution corresponding to the number of molecules on the left and the right.\n        \\item The standard deviation of the Gaussian distribution of $N_A$ macrostates is $\\sigma\\approx\\sqrt{N_A}$.\n        \\item Thus, the fraction of the width of the central peak to all states is $\\sigma/N_A\\approx 10^{-12}$.\n        \\item Therefore, the width of the spike is approximately one-trillionth the width of the whole distribution, meaning that although you won't typically see a perfect 50/50 split, you won't see very large fluctuations (even 49/51 is very unlikely).\n    \\end{itemize}\n    \\item It's not that you \\emph{can't} have all of the air molecules move to one side of the room; it's that you \\emph{won't} have this happen.\n\\end{itemize}\n\n\n\n\\section{Office Hours (Gazes)}\n\\begin{itemize}\n    \\item Preference for sine vs. cosine when describing harmonic waves?\n    \\begin{itemize}\n        \\item No preference.\n        \\item Gazes tends to start with sines, but it really doesn't matter; there is no canonical preference.\n    \\end{itemize}\n    \\item We say that the open end of a pipe is a node and we often say that closed ends are antinodes. However, on the midterm, there was a question with a tuning fork at one end of a pipe with water at the bottom, and we were supposed to infer that the open end with the tuning fork was an antinode and the end with water was a node. As such, I'm wondering if there's any unambiguous way we can identify open and closed ends of pipes.\n    \\begin{itemize}\n        \\item We do assume the end with the tuning fork to be a pressure node and the water to be a pressure antinode.\n        \\item It's a \\emph{pressure} node at the end of the tube, but a displacement antinode.\n        \\item Some transmission does occur at the end of a tube.\n        \\item Flaring the ends of instruments cuts down on reflection and increases transmission.\n    \\end{itemize}\n    \\item How do we know that even rays with not so well understood geometry converge on the image?\n    \\begin{itemize}\n        \\item A computer can just brute force the problem and come to this conclusion.\n    \\end{itemize}\n    \\item When refracting an object through multiple lenses, the side the \\emph{original} object is on is always the $+s$ and $-s'$ side, even when the first image may be on the other side of the next lens?\n    \\begin{itemize}\n        \\item Yes.\n        \\item Because the rays just continue on through the second lens. Those \\emph{rays} act as the object and effectively determine the sign.\n    \\end{itemize}\n    \\item Plano-convex lens on top of a mirror?\n    \\begin{itemize}\n        \\item You can make the contraption image the same way as a concave mirror.\n        \\item Allows analogy of concave mirrors to regular lenses.\n        \\item Also helps define our sign convention: flips what defines positive image distance.\n    \\end{itemize}\n    \\item When do we make use of vibration? In Problem 19.43, shouldn't we have needed to use $\\frac{7}{2}nR\\Delta T$ for every degree Kelvin above $\\SI{1000}{\\kelvin}$?\n    \\begin{itemize}\n        \\item Didn't quite cross over the threshold.\n        \\item Won't have to account for this on the final.\n        \\item Everything is monoatomic on the final!\n    \\end{itemize}\n\\end{itemize}\n\n\n\n\\section{Entropy}\n\\begin{itemize}\n    \\item \\marginnote{8/24:}\\textbf{Entropy} (of a macrostate): The following quantity, where $k$ is the Boltzmann constant. \\emph{Denoted by} $\\bm{S_\\textbf{macro}}$.\n    \\begin{equation*}\n        S_\\text{macro} = k\\ln\\Omega_\\text{macro}\n    \\end{equation*}\n    \\item $\\Delta S>0$ (i.e., entropy increases) for an irreversible process.\n    \\item Entropies of multiple systems:\n    \\begin{itemize}\n        \\item Consider 2 systems in macrostates $A$ and $B$, respectively.\n        \\item The number of microstates pertaining to each macrostate is $\\Omega_A$ and $\\Omega_B$, respectively.\n        \\item We know that $P_A\\propto\\Omega_A$ and $P_B\\propto\\Omega_B$.\n        \\item Moreover, the probability $P_{AB}$ that the combination of the two systems in in microstate $AB$ is equal to $P_AP_B$ by fundamental probability laws, and the total number of microstates for the combination is equal to $\\Omega_A\\Omega_B$.\n        \\item It follows that\n        \\begin{align*}\n            S_{AB} &= k\\ln(\\Omega_A\\Omega_B)\\\\\n            &= k\\ln\\Omega_A+k\\ln\\Omega_B\\\\\n            &= S_A+S_B\n        \\end{align*}\n        i.e., that entropies are additive.\n    \\end{itemize}\n    \\item Primary consequences of the second law of thermodynamics:\n    \\begin{itemize}\n        \\item Wrt heat engines: You will never see gas taking in $Q_\\text{in}$ and converting entirely to $W_\\text{by gas}$ (i.e., there will always be some $Q_\\text{out}$).\n        \\item Wrt heat pumps: You will never see $Q$ extracted from $T_L$ and exhausted to $T_H$ without some $W_\\text{on gas}$.\n        \\item Wrt entropy: You will never see a decrease in entropy.\n    \\end{itemize}\n    \\item Change in entropy for a reversible process:\n    \\begin{itemize}\n        \\item Consider the Carnot cycle (Figure \\ref{fig:carnotCycle}).\n        \\item For the cycle, $\\Delta S_\\text{gas}=0$.\n        \\item If we add or subtract $Q$ of heat at a constant $T$,\n        \\begin{equation*}\n            \\Delta S = \\frac{Q}{T}\n        \\end{equation*}\n        \\item Thus,\n        \\begin{align*}\n            \\Delta S_\\text{univ} &= \\Delta S_{Q_\\text{in}}+\\Delta S_{Q_\\text{out}}\\\\\n            &= \\frac{Q_\\text{in}}{T_H}-\\frac{Q_\\text{out}}{T_L}\\\\\n            \\intertext{The above is true for any thermodynamic cycle. But since $Q_\\text{in}/Q_\\text{out}=T_H/T_L$ for a Carnot cycle\\dots}\n            &= \\frac{Q_\\text{out}T_H/T_L}{T_H}-\\frac{Q_\\text{out}}{T_L}\\\\\n            &= 0\n        \\end{align*}\n        for a Carnot cycle.\n        \\item Thus, overall, $\\Delta S=0$. This is actually true of any reversible process.\n    \\end{itemize}\n    \\item Thus, since every process is either reversible or irreversible, $\\Delta S_\\text{univ}\\geq 0$ for every process in this universe.\n\\end{itemize}\n\n\n\n\n\\end{document}", "meta": {"hexsha": "c7605f50c44445f7013f753d963acb547bfa5459", "size": 19075, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Notes/Chapter20/chapter20.tex", "max_stars_repo_name": "shadypuck/PHYS13300Notes", "max_stars_repo_head_hexsha": "61c7dcb457b6ce79feba5d9a46e991c88cdcde68", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Notes/Chapter20/chapter20.tex", "max_issues_repo_name": "shadypuck/PHYS13300Notes", "max_issues_repo_head_hexsha": "61c7dcb457b6ce79feba5d9a46e991c88cdcde68", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Notes/Chapter20/chapter20.tex", "max_forks_repo_name": "shadypuck/PHYS13300Notes", "max_forks_repo_head_hexsha": "61c7dcb457b6ce79feba5d9a46e991c88cdcde68", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 58.6923076923, "max_line_length": 436, "alphanum_fraction": 0.6379030144, "num_tokens": 5744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.34958202995258797}}
{"text": "% 06Holonomic.tex\n\n\\subsection{6.1. The Robenius Integrability Condition}\n\nCan one always find a surface orthogonal to a family of curves in $\\mathbb{R}^3$?\n\n\\subsection{6.2. Integrability and Constraints}\n\n\\subsection{6.3. Heuristic Thermodynamics via Caratheodory}\n\nCan one go adiabatically from some state to any nearby state?\n\n\\subsubsection{6.3a. Introduction}\n\n\n\n\\subsubsection{6.3b. The First Law of Thermodynamics}\n\nConsider system of regions of fluids separated by ``diathermous'' membranes \\\\\n\\phantom{\\quad \\, } allow only passage of heat, not fluids \\\\\n\nassume system connected \\\\\nassume each state in thermal equilibrium\n\nLet $p_i,v_i$ (uniform) pressure and volume of $i$th region \\\\\n\\phantom{\\quad \\, } at thermal equilibrium, ``equations of state'' $p_iv_i = n_iRT_i$ \\\\\n\\phantom{\\quad \\quad \\, } $p_i v_i = n_iRT_i$ eliminate all but 1 pressure\n\\[\n\\Longrightarrow p_1, v_1,v_2, \\dots v_n\n\\]\nassume globally defined energy function $U$\n\npath in $M^{n+1}$ represents sequence of states each in equilibrium, i.e. assume very slow changes in time, quasi-static irreversible processes, e.g. ``stirring'' \\\\\non $M$, $\\text{dim}{M} = n+1$, assume $\\exists \\, $ work 1-form $W$, work done by system \n\\[\nW = p_i dv_i = p_i(U,v_1\\dots v_n)dv_i \\quad \\quad \\, i=1 \\dots n \n\\]\nheat 1-form, heat added or removed from system, assume $Q \\neq 0$\n\\[\nQ = \\sum_{i=0}^n Q_i(U,v_1 \\dots v_n) dv_i \\quad \\, (v_0 = U)\n\\]\n\n1st. law of thermodynamics \n\\[\ndU = Q-W\n\\]\nenergy conservation \n\n\\subsubsection*{6.3c. Some Elementary Changes of State}\n\n1. Heating at constant volume. \n\n\\phantom{\\quad \\, } path $\\gamma_I \\in M$, $\\text{dim}M = n+1$ s.t. $dv_1 = \\dots = dv_n =0$.  $W=0$\n\\phantom{\\quad \\, } $dU = Q_0 dU$.  $\\dot{\\gamma}_I = c_0 \\frac{\\partial}{ \\partial U}$\n\n2. Quasi-static adiabatic process.  No heat exchanged,\n\\[\nQ(\\dot{\\gamma}_{\\text{II}}) = 0 \\quad \\, \\text{ so } dU = -W\n\\]\n\n3. Stirring at constant volume adiabatic, but not quasistatic  \\\\\n\\phantom{\\quad \\, } $Q,W$ makes no sense but \\\\\n\\phantom{\\quad \\, } work is being done by (or on) system, $U(y') - U(x)$, difference of internal energy \\\\\nassume connected mechanical manifold $V$, $\\text{dim}V =n$ \\\\\n\\phantom{assume } diff. $\\pi:M \\to V$ \\\\\n\\phantom{assume diff} $\\pi$ onto \\\\\n\\phantom{assume diff} $\\pi_*$ onto \\\\\n\\phantom{assume diff} $\\pi$ submersion\n\nBy main thm. on submanifolds of Sec. 1.3d, \\\\\n\\phantom{\\quad \\, } if $v\\in V$, then $\\pi^{-1}(v)$ 1-dim. embedded submanifold of $M$ \\\\\n\\phantom{\\quad \\quad \\, } assume $\\forall \\, \\pi^{-1}(v)$ connected, we're assuming given any pair of states \\\\\n\\phantom{\\quad \\quad \\quad \\, } lying on $\\pi^{-1}(v)$, 1 of them can be obtained by other by ``heating at constant volume''\n\nassume $W$ on $M$ is $0$ when $\\left. W \\right|_{\\pi^{-1}(v)} =0$ \\\\\non the other hand, $Q \\neq 0$ on $\\pi^{-1}(v)$; $dU = Q \\neq 0$ (first law) \\\\\n\\phantom{\\quad \\, } $(U,v^1 \\dots v^n)$ local coordinate system for $M$ ($U$ global coordinate)\n\n\\subsubsection{6.3d. The Second Law of Thermodynamics} \n\ncyclic process starts and ends at the same state\n\nKelvin 2nd. law of thermodynamics \\\\\n\\phantom{\\quad \\, } $\\nexists $ quasistatic cyclic process can $Q$ converted entirely into $W$  \\\\\n\nCaratheodory (1909) 2nd. law of thermodynamics \\\\\n\\phantom{\\quad \\, } $\\forall \\, $ neighborhood $N \\ni $ state $x$, $\\exists \\, y$ not accessible from $x$ via quasistatic adiabatic paths, i.e. paths s.t. $Q=0$\n\n\n\n", "meta": {"hexsha": "67ad927db88602dede75bb21e775f08be54e2cf8", "size": 3400, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "LaTeX_and_pdfs/the geometry of physics problems/06Holonomic.tex", "max_stars_repo_name": "wacfeldwang333/mathphysics", "max_stars_repo_head_hexsha": "59eb794dfa46e2b80e43df0440bb8ec3c472d973", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50, "max_stars_repo_stars_event_min_datetime": "2017-01-10T14:24:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:19:23.000Z", "max_issues_repo_path": "LaTeX_and_pdfs/the geometry of physics problems/06Holonomic.tex", "max_issues_repo_name": "wacfeldwang333/mathphysics", "max_issues_repo_head_hexsha": "59eb794dfa46e2b80e43df0440bb8ec3c472d973", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2017-09-29T09:29:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T03:12:29.000Z", "max_forks_repo_path": "LaTeX_and_pdfs/the geometry of physics problems/06Holonomic.tex", "max_forks_repo_name": "wacfeldwang333/mathphysics", "max_forks_repo_head_hexsha": "59eb794dfa46e2b80e43df0440bb8ec3c472d973", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25, "max_forks_repo_forks_event_min_datetime": "2018-01-21T05:33:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T20:15:13.000Z", "avg_line_length": 37.3626373626, "max_line_length": 165, "alphanum_fraction": 0.6694117647, "num_tokens": 1142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.34958202995258797}}
{"text": "\\clearpage\n\\makeatletter\n\\efloat@restorefloats\n\\makeatother\n\n\n\\begin{appendix}\n\\hypertarget{parallel-set-of-non-bayesian-analyses}{%\n\\section{Parallel set of non-Bayesian\nanalyses}\\label{parallel-set-of-non-bayesian-analyses}}\n\nIn this appendix, we report the output of a parallel set of non-Bayesian\nlinear mixed-effects models for the primary analyses (Reaction Time,\nAccuracy, EWMA) in Experiments 1 and 2. The \\(p\\) values for each\ncoefficient were computed via the Satterthwaite approximation using the\n\\texttt{lmerTest} R package (Kuznetsova, Brockhoff, \\& Christensen,\n2017).\n\n\\begin{table}[h]\n\\begin{center}\n\\begin{threeparttable}\n\\caption{\\label{tab:mle rt trio}Output of the MLE model predicting log reaction time as a function of center stimulus type in Experiment 1.}\n\\begin{tabular}{llllll}\n\\toprule\nterm & \\multicolumn{1}{c}{estimate} & \\multicolumn{1}{c}{std.error} & \\multicolumn{1}{c}{statistic} & \\multicolumn{1}{c}{df} & \\multicolumn{1}{c}{p.value}\\\\\n\\midrule\nIntercept (ASL) & 6.96 & 0.08 & 91.84 & 62.58 & < .001\\\\\nFace & -0.37 & 0.11 & -3.32 & 84.45 & < .01\\\\\nObject & -1.12 & 0.10 & -11.13 & 79.76 & < .001\\\\\nBullseye & -1.30 & 0.13 & -10.04 & 97.77 & < .001\\\\\nscale(Months) & -0.01 & 0.04 & -0.18 & 75.55 & 0.86\\\\\n\\bottomrule\n\\addlinespace\n\\end{tabular}\n\\begin{tablenotes}[para]\n\\normalsize{\\textit{Note.} Model specification: log(RT) \\textasciitilde{} stimuli + scale(Months) + (1 | subid) + (1 | target\\_image)}\n\\end{tablenotes}\n\\end{threeparttable}\n\\end{center}\n\\end{table}\n\n\\begin{table}[h]\n\\begin{center}\n\\begin{threeparttable}\n\\caption{\\label{tab:mle acc trio}Output of the MLE model predicting accuracy as a function of center stimulus type in Experiment 1.}\n\\begin{tabular}{lllll}\n\\toprule\nterm & \\multicolumn{1}{c}{estimate} & \\multicolumn{1}{c}{std.error} & \\multicolumn{1}{c}{statistic} & \\multicolumn{1}{c}{p.value}\\\\\n\\midrule\nIntercept (ASL) & 1.07 & 0.14 & 7.66 & < .001\\\\\nFace & -0.64 & 0.20 & -3.19 & < .01\\\\\nObject & -1.14 & 0.19 & -6.16 & < .001\\\\\nBullseye & -1.15 & 0.22 & -5.26 & < .001\\\\\n\\bottomrule\n\\addlinespace\n\\end{tabular}\n\\begin{tablenotes}[para]\n\\normalsize{\\textit{Note.} Model specification: correct \\textasciitilde{} stimuli + (1 | subid) + (1 | target\\_image)}\n\\end{tablenotes}\n\\end{threeparttable}\n\\end{center}\n\\end{table}\n\n\\begin{table}[h]\n\\begin{center}\n\\begin{threeparttable}\n\\caption{\\label{tab:mle ewma trio prop lang}Output of the MLE model estimating the difference in random responding in the EWMA as a function of center stimulus type in Experiment 1.}\n\\begin{tabular}{lllll}\n\\toprule\nterm & \\multicolumn{1}{c}{estimate} & \\multicolumn{1}{c}{std.error} & \\multicolumn{1}{c}{statistic} & \\multicolumn{1}{c}{p.value}\\\\\n\\midrule\nIntercept (ASL) & 1.73 & 0.21 & 8.31 & < .001\\\\\nFace & -1.80 & 0.29 & -6.26 & < .001\\\\\n\\bottomrule\n\\addlinespace\n\\end{tabular}\n\\begin{tablenotes}[para]\n\\normalsize{\\textit{Note.} Model specification: guess \\textasciitilde{} stimuli + (1 | subid) + (1 | target\\_image)}\n\\end{tablenotes}\n\\end{threeparttable}\n\\end{center}\n\\end{table}\n\n\\begin{table}[h]\n\\begin{center}\n\\begin{threeparttable}\n\\caption{\\label{tab:mle rt noise}Output of the MLE model predicting log reaction time as a function of noise condition and age category (adults vs. children) in Experiment 2.}\n\\begin{tabular}{llllll}\n\\toprule\nterm & \\multicolumn{1}{c}{estimate} & \\multicolumn{1}{c}{std.error} & \\multicolumn{1}{c}{statistic} & \\multicolumn{1}{c}{df} & \\multicolumn{1}{c}{p.value}\\\\\n\\midrule\nIntercept (Clear) & -0.76 & 0.05 & -13.92 & 49.62 & < .001\\\\\nnoise & 0.09 & 0.04 & 2.31 & 54.35 & 0.02\\\\\nadults & 0.16 & 0.06 & 2.88 & 56.01 & < .01\\\\\n\\bottomrule\n\\addlinespace\n\\end{tabular}\n\\begin{tablenotes}[para]\n\\normalsize{\\textit{Note.} Model specification: log(rt) \\textasciitilde{} noise\\_condition + age\\_category + (noise\\_condition | subid) + (1 | target\\_image)}\n\\end{tablenotes}\n\\end{threeparttable}\n\\end{center}\n\\end{table}\n\n\\begin{table}[h]\n\\begin{center}\n\\begin{threeparttable}\n\\caption{\\label{tab:mle acc noise}Output of the MLE model predicting accuracy as a function of noise condition and age category (adults vs. children) in Experiment 2.}\n\\begin{tabular}{lllll}\n\\toprule\nterm & \\multicolumn{1}{c}{estimate} & \\multicolumn{1}{c}{std.error} & \\multicolumn{1}{c}{statistic} & \\multicolumn{1}{c}{p.value}\\\\\n\\midrule\nIntercept (Clear) & 0.48 & 0.13 & 3.78 & < .001\\\\\nnoise & 0.22 & 0.14 & 1.52 & 0.13\\\\\nadults & 1.75 & 0.15 & 11.54 & < .001\\\\\n\\bottomrule\n\\addlinespace\n\\end{tabular}\n\\begin{tablenotes}[para]\n\\normalsize{\\textit{Note.} Model specification: correct \\textasciitilde{} noise\\_condition + age\\_category + (noise\\_condition | subid) + (1 | target\\_image)}\n\\end{tablenotes}\n\\end{threeparttable}\n\\end{center}\n\\end{table}\n\n\\begin{table}[h]\n\\begin{center}\n\\begin{threeparttable}\n\\caption{\\label{tab:mle ewma noise}Output of the MLE model estimating the difference in random responding (EWMA model) as a function of noise condition and age category (adults vs. children) in Experiment 2.}\n\\begin{tabular}{lllll}\n\\toprule\nterm & \\multicolumn{1}{c}{estimate} & \\multicolumn{1}{c}{std.error} & \\multicolumn{1}{c}{statistic} & \\multicolumn{1}{c}{p.value}\\\\\n\\midrule\nIntercept (Clear) & 1.81 & 0.15 & 12.23 & < .001\\\\\nnoise & 0.73 & 0.17 & 4.18 & < .001\\\\\nchildren & -2.56 & 0.10 & -25.75 & < .001\\\\\n\\bottomrule\n\\addlinespace\n\\end{tabular}\n\\begin{tablenotes}[para]\n\\normalsize{\\textit{Note.} Model specification: guess\\_num \\textasciitilde{} noise\\_condition + age\\_category + (noise\\_condition | subid) + (noise\\_condition | target\\_image)}\n\\end{tablenotes}\n\\end{threeparttable}\n\\end{center}\n\\end{table}\n\n\\hypertarget{bayesian-data-analysis-models-experiment-1}{%\n\\section{Bayesian data analysis models: Experiment\n1}\\label{bayesian-data-analysis-models-experiment-1}}\n\nIn this appendix, we report the full output of the Bayesian linear mixed\neffects models in Experiment 1.\n\n\\begin{table}[h]\n\\begin{center}\n\\begin{threeparttable}\n\\caption{\\label{tab:trio-rt-model}Output of the regression predicting reaction time (milliseconds) as a function of center stimulus type in Experiment 1.}\n\\begin{tabular}{lll}\n\\toprule\nCenter Stimulus Type & \\multicolumn{1}{c}{Mean RT} & \\multicolumn{1}{c}{95\\% HDI}\\\\\n\\midrule\nBullseye & 288.71 & [229.8, 355.17]\\\\\nObject & 344.51 & [295.71, 397.31]\\\\\nFace & 724.78 & [603.2, 862.81]\\\\\nASL & 1,047.89 & [897.29, 1213.52]\\\\\n\\bottomrule\n\\end{tabular}\n\\end{threeparttable}\n\\end{center}\n\\end{table}\n\n\\begin{table}[h]\n\\begin{center}\n\\begin{threeparttable}\n\\caption{\\label{tab:trio-acc-model}Output of the logistic regression predicting accuracy as a function of center stimulus type in Experiment 1.}\n\\begin{tabular}{lll}\n\\toprule\nCenter Stimulus Type & \\multicolumn{1}{c}{Mean Accuracy} & \\multicolumn{1}{c}{95\\% HDI}\\\\\n\\midrule\nObject & 0.46 & [0.37, 0.53]\\\\\nBullseye & 0.48 & [0.38, 0.58]\\\\\nFace & 0.63 & [0.54, 0.7]\\\\\nASL & 0.76 & [0.7, 0.81]\\\\\n\\bottomrule\n\\end{tabular}\n\\end{threeparttable}\n\\end{center}\n\\end{table}\n\n\\begin{table}[h]\n\\begin{center}\n\\begin{threeparttable}\n\\caption{\\label{tab:trio-acc-contrasts}Output of the model estimating differences in Accuracy for specific contrasts of interest in Experiment 1.}\n\\begin{tabular}{lll}\n\\toprule\nContrast & \\multicolumn{1}{c}{Mean Difference Accuracy} & \\multicolumn{1}{c}{95\\% HDI}\\\\\n\\midrule\nObject vs. Chance & -0.04 & [-0.13, 0.03]\\\\\nBullseye vs. Chance & -0.02 & [-0.12, 0.08]\\\\\nASL vs. Face & 0.13 & [0.04, 0.23]\\\\\nFace vs. Object/Bullseye & 0.16 & [0.07, 0.24]\\\\\nASL vs. English & 0.23 & [0.17, 0.29]\\\\\n\\bottomrule\n\\end{tabular}\n\\end{threeparttable}\n\\end{center}\n\\end{table}\n\n\\begin{table}[h]\n\\begin{center}\n\\begin{threeparttable}\n\\caption{\\label{tab:trio-rt-contrasts}Output of the model estimating differences in RT for specific contrasts of interest in Experiment 1.}\n\\begin{tabular}{lll}\n\\toprule\nContrast & \\multicolumn{1}{c}{Mean Difference RT} & \\multicolumn{1}{c}{95\\% HDI}\\\\\n\\midrule\nASL vs. Face & 323.10 & [132.3, 522.6]\\\\\nFace vs. Object/Bullseye & 408.20 & [286.6, 546.2]\\\\\nASL vs. English & 595.20 & [444.6, 760.8]\\\\\n\\bottomrule\n\\end{tabular}\n\\end{threeparttable}\n\\end{center}\n\\end{table}\n\n\\begin{table}[h]\n\\begin{center}\n\\begin{threeparttable}\n\\caption{\\label{tab:trio-ewma-cuts}Output of the model estimating the point in the Reaction Time distribution when children's Exponentially Weighted Moving Average statistic crossed the pre-defined guessing threshold for the ASL and Face center stimulus types in Experiment 1.}\n\\begin{tabular}{lll}\n\\toprule\nCenter Stimulus Type & \\multicolumn{1}{c}{Mean EWMA Cut Point} & \\multicolumn{1}{c}{95\\% HDI}\\\\\n\\midrule\nASL & 0.68 & [0.59, 0.78]\\\\\nFace & 0.90 & [0.77, 1.03]\\\\\n\\bottomrule\n\\end{tabular}\n\\end{threeparttable}\n\\end{center}\n\\end{table}\n\n\\begin{table}[h]\n\\begin{center}\n\\begin{threeparttable}\n\\caption{\\label{tab:trio-guess-cuts}Output of the model estimating the mean proportion of shifts categorized as language-driven by the Exponentially Weighted Moving Average model for the ASL and Face center stimulus types in Experiment 1.}\n\\begin{tabular}{lll}\n\\toprule\nCenter Stimulus Type & \\multicolumn{1}{c}{Mean Language-driven} & \\multicolumn{1}{c}{95\\% HDI}\\\\\n\\midrule\nFace & 0.34 & [0.23, 0.46]\\\\\nAsl & 0.75 & [0.65, 0.84]\\\\\n\\bottomrule\n\\end{tabular}\n\\end{threeparttable}\n\\end{center}\n\\end{table}\n\n\\begin{table}[h]\n\\begin{center}\n\\begin{threeparttable}\n\\caption{\\label{tab:trio-hddm}Summary of the Drift Diffusion Model output for the drift rate and boundary separation parameters for both all four center stimulus types in Experiment 1.}\n\\begin{tabular}{llll}\n\\toprule\nParameter & \\multicolumn{1}{c}{Center Stim Type} & \\multicolumn{1}{c}{Mean Param Estimate} & \\multicolumn{1}{c}{95\\% HDI}\\\\\n\\midrule\nBoundary & Face & 1.34 & [1.21, 1.47]\\\\\nBoundary & ASL & 1.76 & [1.65, 1.88]\\\\\nDrift & Face & 0.55 & [0.3, 0.8]\\\\\nDrift & ASL & 0.63 & [0.44, 0.82]\\\\\n\\bottomrule\n\\end{tabular}\n\\end{threeparttable}\n\\end{center}\n\\end{table}\n\n\\hypertarget{bayesian-data-analysis-models-experiment-2}{%\n\\section{Bayesian data analysis models: Experiment\n2}\\label{bayesian-data-analysis-models-experiment-2}}\n\nIn this appendix, we report the full output of the Bayesian linear mixed\neffects models in Experiment 2.\n\n\\begin{table}[h]\n\\begin{center}\n\\begin{threeparttable}\n\\caption{\\label{tab:noise-acc-model}Output of the logistic regression predicting accuracy as a function of noise condition and age group in Experiment 2.}\n\\begin{tabular}{llll}\n\\toprule\nNoise Condition & \\multicolumn{1}{c}{Age Group} & \\multicolumn{1}{c}{Mean Accuracy} & \\multicolumn{1}{c}{95\\% HDI}\\\\\n\\midrule\nClear & children & 0.61 & [0.54, 0.68]\\\\\nNoise & children & 0.67 & [0.6, 0.74]\\\\\nClear & adults & 0.90 & [0.87, 0.93]\\\\\nNoise & adults & 0.92 & [0.89, 0.95]\\\\\n\\bottomrule\n\\end{tabular}\n\\end{threeparttable}\n\\end{center}\n\\end{table}\n\n\\begin{table}[h]\n\\begin{center}\n\\begin{threeparttable}\n\\caption{\\label{tab:noise-rt-model}Output of the regression estimating reaction times (milliseconds) as a function of noise condition and age group in Experiment 2.}\n\\begin{tabular}{llll}\n\\toprule\nNoise Condition & \\multicolumn{1}{c}{Age Group} & \\multicolumn{1}{c}{Mean RT} & \\multicolumn{1}{c}{95\\% HDI}\\\\\n\\midrule\nClear & children & 455.70 & [407, 503.6]\\\\\nNoise & children & 500.20 & [446.6, 555.6]\\\\\nClear & adults & 542.40 & [486.2, 602.4]\\\\\nNoise & adults & 595.20 & [532.4, 665.3]\\\\\n\\bottomrule\n\\end{tabular}\n\\end{threeparttable}\n\\end{center}\n\\end{table}\n\n\\begin{table}[h]\n\\begin{center}\n\\begin{threeparttable}\n\\caption{\\label{tab:noise-guess-cuts}Output of the model estimating the mean proportion of shifts categorized as language-driven by the Exponentially Weighted Moving Average model for the each noise condition and age group in Experiment 2.}\n\\begin{tabular}{llll}\n\\toprule\nNoise Condition & \\multicolumn{1}{c}{Age Group} & \\multicolumn{1}{c}{Mean Language-driven} & \\multicolumn{1}{c}{95\\% HDI}\\\\\n\\midrule\nClear & children & 0.36 & [0.32, 0.4]\\\\\nNoise & children & 0.47 & [0.43, 0.51]\\\\\nClear & adults & 0.81 & [0.77, 0.86]\\\\\nNoise & adults & 0.93 & [0.89, 0.97]\\\\\n\\bottomrule\n\\end{tabular}\n\\end{threeparttable}\n\\end{center}\n\\end{table}\n\n\\begin{table}[h]\n\\begin{center}\n\\begin{threeparttable}\n\\caption{\\label{tab:noise-hddm}Summary of the Drift Diffusion Model output for the drift rate and boundary separation parameters for both processing contexts and age groups in Experiment 2.}\n\\begin{tabular}{llll}\n\\toprule\nParameter & \\multicolumn{1}{c}{Age Group} & \\multicolumn{1}{c}{Mean Parameter Estimate} & \\multicolumn{1}{c}{95\\% HDI}\\\\\n\\midrule\nDrift & Children & 0.59 & [0.3, 0.89]\\\\\nDrift & Adults & 1.86 & [1.48, 2.25]\\\\\nBoundary & Children & 1.16 & [0.94, 1.39]\\\\\nBoundary & Adults & 1.78 & [1.53, 2.05]\\\\\n\\bottomrule\n\\end{tabular}\n\\end{threeparttable}\n\\end{center}\n\\end{table}\n\\end{appendix}\n", "meta": {"hexsha": "c7ae22dbb29504399418034067fde657a0d1a577", "size": 12698, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "writing/journal_submission/paper/speed-acc-appendix.tex", "max_stars_repo_name": "kemacdonald/speed-acc", "max_stars_repo_head_hexsha": "012087b4b604a882c813a2edc7df2af8b9c8e3e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "writing/journal_submission/paper/speed-acc-appendix.tex", "max_issues_repo_name": "kemacdonald/speed-acc", "max_issues_repo_head_hexsha": "012087b4b604a882c813a2edc7df2af8b9c8e3e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-07-07T21:15:31.000Z", "max_issues_repo_issues_event_max_datetime": "2016-07-07T21:16:27.000Z", "max_forks_repo_path": "writing/journal_submission/paper/speed-acc-appendix.tex", "max_forks_repo_name": "kemacdonald/speed-acc", "max_forks_repo_head_hexsha": "012087b4b604a882c813a2edc7df2af8b9c8e3e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-06-23T22:48:28.000Z", "max_forks_repo_forks_event_max_datetime": "2016-06-23T22:48:28.000Z", "avg_line_length": 35.7690140845, "max_line_length": 277, "alphanum_fraction": 0.7072767365, "num_tokens": 4653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241772283033, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.34958202995258786}}
{"text": "\\documentclass{article}\n\\title{Compsci 590T Homework 8}\n\\usepackage[margin=1in]{geometry}\n\\usepackage[loose,nice]{units}\n\\usepackage{enumitem}\n\\usepackage{amsmath}\n\\usepackage{multirow,array}\n\\newcommand{\\pvec}[1]{\\vec{#1}\\mkern2mu\\vphantom{#1}}\n\\usepackage{amssymb}\n\\usepackage{cancel}\n\\usepackage{mathabx}\n\\usepackage{hyperref}\n\\newcommand\\tab[1][1cm]{\\hspace*{#1}}\n\\usepackage{tikz}\n\\newcommand*\\circled[1]{\\tikz[baseline=(char.base)]{\n            \\node[shape=circle,draw,inner sep=2pt] (char) {#1};}}\n\n\\usetikzlibrary{positioning}\n\\tikzset{main node/.style={circle,fill=blue!20,draw,minimum size=4mm,inner sep=0pt},}\n\\author{Student: Brian Sun, Collaborator: Thai On}\n\\date{}\n\n\\begin{document}\n\\maketitle\n\n\n\\section{Problem 1}\nAssume player $i$ (players who values all rooms equally) is not always pay the least amount of rent in any envy-free outcome. If this is true, there will exist an envy-free outcome that at least one player $i'$ who don't value all room the same and pay less than $i$.\\\\\\\\\nTherefore the room $i'$ get is cost less than the room $i$ get.\\\\\nHowever this violate the evny-free property: $v_{i\\sigma(i)} - p_{\\sigma(i)} \\geq v_{ij} - p_j,\\ \\forall j$.\\\\\nSince $i$ values all rooms equally and the room $i'$ get is cost less than the room $i$ get. \\\\\nSo $p_{\\sigma(i)} > p_k \\tab$(define room $k$ is the room player $i'$ get)\\\\\nwhich leads to $v_{i\\sigma(i)} - p_{\\sigma(i)} \\not\\geq v_{ik} - p_k \\tab$\\\\\\\\\nSo the statement \"player $i$ (players who values all rooms equally) is not always pay the least amount of rent in any envy-free outcome\" is false. Therefore player $i$ pays the least amount of rent in any envy-free outcome, since if there exist an player who pay less than $i$, than it's not envy-free anymore.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\newpage\n\\section{Problem 2}\n\nBase on the envy-free property we have: $\\overbrace{v_{i\\sigma(i)}- p_{\\sigma(i)}}^{A} \\geq \\overbrace{v_{ij} - p_j}^{B},\\ \\forall j$\\\\\ndefine $A = v_{i\\sigma(i)}- p_{\\sigma(i)}$ and $B = v_{ij} - p_j$\\\\\nTo satisfy envy-free there will have two different outcome:\\\\\n1: when $A>B$\\\\\n2: when $A=B$\\\\\\\\\nFor case 1:\\\\\nif $A > B$ that means there exist an room $j^*$ such that $v_{i\\sigma(i)}- p_{\\sigma(i)} > v_{ij^*} - p_{j^*}$\\\\\nsince room $j^*$ will assign to a player $i'$ and because everyone have the same valuation for all the rooms so $i' = i$.\\\\\nTherefore we have $v_{i'j^*} - p_{j^*} < v_{i\\sigma(i)} - p_{\\sigma(i)}$,\nsince $v_{i'j^*} - p_{j^*} \\not \\geq v_{i\\sigma(i)} - p_{\\sigma(i)}$ which break the envy-free property.\nTherefore case 1 cannot happen, since when $A > B$, then the outcome is not envy-free.\\\\\\\\\nFor case 2:\\\\\nsince base on case 1 we know $A > B$ cannot satisfy envy-free, so we have to assume $A = B$ for all players, so the outcome satisfy envy-free.\\\\\\\\\nwhen $A = B$ there will have three cases:\\\\\n$a$: $A = B > 0$\\\\\n$b$: $A = B < 0$\\\\\n$c$: $A = B = 0$\\\\\\\\\nFor case $(a)$:\\\\\nif $A = B > 0$ happen, that means $v_{i\\sigma(i)} > p_{\\sigma(i)},\\ \\forall i$\\\\\nTherefore $\\sum_{i = 1}^n v_{i\\sigma(i)} > \\sum_{i = 1}^n p_{\\sigma(i)}$\\\\\\\\\n$\\sum_{i}^n v_{i\\sigma(i)}$ means the sum of all the player value their assign room. Since there are $n$ players and $n$ rooms and everyone cannot get the same room, therefore $\\sum_{i = 1}^n v_{i\\sigma(i)} = \\sum_{j = 1}^n v_{ij}$\\\\\n$\\sum_{i = 1}^n p_{\\sigma(i)}$ means the sum of all the room price that assign to players. Since there are $n$ players and $n$ rooms and everyone cannot get the same room, therefore $\\sum_{i = 1}^n p_{\\sigma(i)} = \\sum_{j = 1}^n p_{j}$\\\\\\\\\nSince $\\sum_{i = 1}^n v_{i\\sigma(i)} = \\sum_{j = 1}^n v_{ij}$ and $\\sum_{i = 1}^n p_{\\sigma(i)} = \\sum_{j = 1}^n p_{j}$ and $\\sum_{i = 1}^n v_{i\\sigma(i)} > \\sum_{i = 1}^n p_{\\sigma(i)}$\\\\\nso we got $\\sum_{j = 1}^n v_{ij} > \\sum_{j = 1}^n p_{j}$\\\\\nWhich this break the requirement from the question: $\\sum_{j = 1}^n v_{ij} = \\sum_{j = 1}^n p_{j}$\\\\\nSince case $a$ break the requirement from the question, therefore case $a$ cannot happen too.\\\\\\\\\nFor case $(b)$:\\\\\nif $A = B > 0$ happen, that means $v_{i\\sigma(i)} < p_{\\sigma(i)},\\ \\forall i$\\\\\nTherefore $\\sum_{i = 1}^n v_{i\\sigma(i)} < \\sum_{i = 1}^n p_{\\sigma(i)}$\\\\\\\\\nSince $\\sum_{i = 1}^n v_{i\\sigma(i)} = \\sum_{j = 1}^n v_{ij}$ and $\\sum_{i = 1}^n p_{\\sigma(i)} = \\sum_{j = 1}^n p_{j}$ and $\\sum_{i = 1}^n v_{i\\sigma(i)} < \\sum_{i = 1}^n p_{\\sigma(i)}$\\\\\nso we got $\\sum_{j = 1}^n v_{ij} < \\sum_{j = 1}^n p_{j}$\\\\\nWhich this break the requirement from the question: $\\sum_{j = 1}^n v_{ij} = \\sum_{j = 1}^n p_{j}$\\\\\nSince case $b$ break the requirement from the question, therefore case $b$ cannot happen too.\\\\\\\\\nFor case $(c)$:\\\\\nif $A=B=0$ happen, that means $v_{i\\sigma(i)} = p_{\\sigma(i)},\\ \\forall i$\\\\\nTherefore $\\sum_{i = 1}^n v_{i\\sigma(i)} = \\sum_{i = 1}^n p_{\\sigma(i)}$\\\\\\\\\nSince $\\sum_{i = 1}^n v_{i\\sigma(i)} = \\sum_{j = 1}^n v_{ij}$ and $\\sum_{i = 1}^n p_{\\sigma(i)} = \\sum_{j = 1}^n p_{j}$ and $\\sum_{i = 1}^n v_{i\\sigma(i)} = \\sum_{i = 1}^n p_{\\sigma(i)}$\\\\\nso we got $\\sum_{j = 1}^n v_{ij} = \\sum_{j = 1}^n p_{j}$.\\\\\nSince case $(c)$ is the only case that satisfy envy-free and $\\sum_{j = 1}^n v_{ij} = \\sum_{j = 1}^n p_{j}$. Therefore there exist only one unique EF price vector. That is $p_{\\sigma(i)} = v_{i\\sigma(i)},\\ \\forall i$ which is set all the room price equal to player's room valuation. \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\newpage\n\\section{Problem 3}\n\nIf this is not true that means there exist an room $j^*$ such that $p_{j} > p_{j^*}$ and the outcome is envy-free.\\\\\nBase on the given information we know every player value room $j$ the least, therefore $v_{ij} < v_{ij^*}$\\\\\\\\\nAssume player $i$ got assign to room $j$\n\\\\therefore base on the envy-free property we know $v_{ij} - p_j \\geq v_{ij^*} - p_{j^*} \\longrightarrow (\\star)$\\\\\\\\\nHowever since $p_{j} > p_{j^*} = -p_{j} < -p_{j^*}$ and  $v_{ij} < v_{ij^*}$ we know $v_{ij} - p_j < v_{ij^*} - p_{j^*}$ which contradict with $(\\star)$.\\\\\\\\\nTherefore the statement \"there exist an room $j^*$ such that $p_{j} > p_{j^*}$ and the outcome is envy-free\" is false. So the price of room $j$ should be the lowest, since if there are room lower that $j$ than it's not envy-free anymore.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\newpage\n\\section{Problem 1.a}\nBase on the VCG mechanism determine the payment for each player we have:\n$$p_i = \\sum_{j \\not = i} v_j(o_{-i}^*) - \\sum_{j \\not = i}v_j(o^*) = \\sum_{j \\not = i}[v_j(o_{-i}^*) - v_j(o^*)] \\longrightarrow (\\star)$$\nDefine $S^*$ as the set contain all the successful bidders from $o^*$. Another way to say this is $S^*$ has all the bidders form $o^*$ who's utility is greater than $0$.\\\\\\\\\nSince there are $k$ items and each bidder only can have one item, therefore both $S^*$ will have the size of $k$ bidders.\\\\\\\\\nBase on VCG mechanism, $o^*_{-i}$ is the socially optimal outcome without $i$. Therefore given any $i$ was in $S^*$ that means we have to make a new set $S^*_{-i}$ to find the substitute bidder $i'$ for $i$.\\\\\nSince we are making the socially optimal outcome, therefore $i'$ should be the highest bidder amount all the bidders who are not in $S^*$. Because if $i'$ is not the highest bidder amount all the bidders who are not in $S^*$, then it's not socially optimal outcome anymore.\\\\\\\\\nBase on $(\\star)$ we know how we assign the value for these successful bidders is base on the sum of $v(j) \\in S^*_{-i}$ minus the sum of $v(j) \\in S^* \\setminus i$ $\\tab \\bullet$($j$ is a player)\\\\\nSince the only different between $S^*$ and $S^*_{-i}$ is $S^*$ have $i$ but don't have $i'$ and $S^*_{-i}$ have $i'$ but don't have $i$. Therefore the only different between $S^*\\setminus i$ and $S^*_{-i}$ is $S^*_{-i}$ have $i'$ but $S^*$ don't have.\\\\\\\\\nSince the only different between $S^*\\setminus i$ and $S^*_{-i}$ is $S^*_{-i}$ have $i'$ but $S^*$ don't have. Therefore the sum of $v(j) \\in S^*_{-i}$ minus the sum of $v(j) \\in S^* \\setminus i$ is always equal to $v(i')$\\\\\\\\\nSince no matter which bidder we take away from $S^*$ VCG will always find the same bidder $i'$ to substitute $i$. Therefore all the successful bidder will have the same pay, since base on $(\\star)$ the formula will always return $v(i')$.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\newpage\n\\section{Problem 1.b}\n It is possible for example: \\\\\n Assume the auction have 4 bidders and 3 items A,B and C.\\\\\n set A and B are identical\\\\\n then we can make a table of each player bids the items.\n \\begin{center}\n\\begin{tabular}{ | m{4em} | m{4em}| m{4em} | m{4em} |} \n  \\hline\n   & A,B & C \\\\ \n  \\hline\n  $p_1$ & 100 & 100 \\\\ \n  \\hline\n  $p_2$ & 100 & 200 \\\\ \n  \\hline\n  $p_3$ & 200 & 100 \\\\ \n  \\hline\n  $p_4$ & 50 & 100 \\\\ \n  \\hline\n\\end{tabular}\n\\end{center}\nBase on the VCG mechanism we know $o^* = 500$ with $p_1$ get item A, $p_2$ get item C and $p_3$ get item B.\\\\\nset $W^+_i = \\sum_{j \\not = i} v_j(o^*)$\\\\\nset $W^-_i = \\sum_{j \\not = i} v_j(o_{-i}^*)$\\\\\\\\\nBase on VCG mechanism we know they way it determine the payment for bidder $i$ will be:\n\\begin{align*}\n&W^+_1 = 400\\\\\n&W^-_1 = 450\\\\\n&p_1 = 450 - 400 = 50\\\\\\\\\n&W^+_2 = 300\\\\\n&W^-_2 = 400\\\\\n&p_2 = 400 - 300 = 100\\\\\\\\\n&W^+_3 = 300\\\\\n&W^-_3 = 350\\\\\n&p_3 = 350 - 300 = 50\\\\\n\\end{align*}\nSince bidder $2$ and $3$ receive items they value the same ($p_2$ get item C and $p_3$ get item B). But $p_3$ pay $50$ and $p_2$ pay $100$. Therefore it is possible that two bidders who receive items they value the same will pay different prices.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\newpage\n\\section{Problem 2}\n\nVCG cannot extract truthful valuations from the bidders.\\\\ \nFor example there exist cases such as:\\\\\n$v_1 > v_2 > v_3 > ... v_n$\\\\\nIn this case if $p_1$ works with $p_2$, they can maximize their joint utility by let $p_2$ say $v_2 = 0$ therefore base on the valuation, we will have  $v_1 > v_3 > ... v_n$\\\\\nBase on this valuation, VCG will let $p_1$ be the winner of the auction and let $p_1$ pay the second highest price, which is $v_3$. Since this is the single item auction, therefore everyone except $p_1$ utility will be $0$ and $p_1$ utility will be $u_1 = v_1 - v_3$. Therefore $p_1$ and $p_2$ joint utility will be $u_1 + u_2 = v_1 - v_3 + 0$\\\\\\\\\nWhich compare to if they don't work together, $p_1$ will be the winner of the auction. $p_1$ will still be the winner, since $p_1$ is the highest and base on VCG, $p_1$ will pay the second price which is $v_2$. Since this is the single item auction therefore everyone's utility will be $0$ except $p_1$'s utility will be: $u_1 = v_1 - v_2$. $p_1$ and $p_2$ joint utility will be $v_1 - v_2 + 0$\\\\\\\\\nSince $v_3 < v_2$ therefore $v_1 - v_2 + 0 < v_1 - v_3 + 0$ Which means $p_1$ and $p_2$ can have a higher joint utility when they work together. therefore VCG cannot extract truthful valuations from the bidders in this case.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\newpage\n\\section{Problem 3.a}\n\nThird price auction is not truthful.\nIf the third price auction is truthful, that means all bidders best response is always to bid truthfully. however this is not truth base on the case where the second highest bidder $i$ bidding honestly or dishonestly will win or lose the auction.\\\\\\\\\nIf $i$ bidding honestly, and $i$ is the second highest bidder, then $i$ cannot win the auction since he is not the highest bidder, therefore $i$'s utility is $0$.\\\\\nIf $i$ bidding untruthfully by increase his value higher the the highest bidder, than $i$ become the highest bidder and win the auction. Since $i$ win the auction so he will pay the third highest prise. Since $i$'s true value for the item is higher than the third highest bidder, therefore it is good for $i$ since he win the auction and pay less than what he actually think the item is.\\\\\\\\\nTherefore third price auction is not truthful, since the second highest bidder can lie his bid to be highest and win the auction without paying more than what he actually values it.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\newpage\n\\section{Problem 3.b}\n\nThis auction is truthful since players lie to increase or decrease their value will not increase their utility.\\\\\\\\\nTo prove this is true, we are going to look at:\\\\\n1. when player $i$ win by telling the truth\\\\\n2. when player $i$ lose by telling the truth\\\\\\\\\nFor the first case:\\\\\nwhen player $i$ win, that means $i$ is going to pay the second highest bid, or the reserve price (whichever is higher).\\\\\nIf $i$ lie by increase his bid, this action will not effect the second highest bid or the reserve price, so he is still going to pay $max(b_2,r)$. Which means his utility still the same $u_i = v_i - max(b_2,r)$.\\\\\nIf $i$ lie by decrease his bid, if $b_i$ still greater than $max(b_2,r)$, then this action will still not effect the second highest bid or the reserve price. So he is still going to pay $max(b_2,r)$ which means his utility still the same $u_i = v_i - max(b_2,r)$.\\\\\nIf $i$ lie by decrease his bid, if $b_i$ less or equal to $max(b_2,r)$, then this action will change the fact that $i$ is the winner, since $b_1 \\leq max(b_2,r)$. Since $i$ is not the winner anymore therefore his utility will from  $u_i = v_i - max(b_2,r)$ to $u_i = 0$ which is worse than before.\\\\\nIn the first case, since no matter how $i$ lie by increase or decrease the value his utility will either be the same or become worse, therefore there is no reason for bidder $i$ to lie.\\\\\\\\\nFor the second case:\\\\\nwhen player $i$ lose the auction, that means it's either: \\\\\na. $b_i$ is the highest bid but less than $r$\\\\\nb. $b_i$ is not the highest bid which $b_i < max(b_1,r)$\\\\\\\\\nFor case a: \\\\\nIf $i$ increase his bid higher but still not greater than $r$, than this action will not change the fact that he lose the auction. Since $i$ still lose the auction, so his utility will still be $0$ like before.\\\\ \nIf $i$ increase his bid higher than $r$, than this action will make him become the winner, but this will decrease his utility since his true valuation is $v_i < r$ and now $i$ has to pay $r$ therefore his utility will be $u_i = v_i - r < 0$ which is worse than before.\\\\\nIf $i$ decrease his bid, than this action ill not change the fact that he lose the auction. Since $i$ still lose the auction, so his utility will still be $0$ like before.\\\\\\\\\nFor case b:\\\\\nIf $i$ increase his bid higher but will not greater than $max(b_1,r)$ than this action will not change the fact that he lose the auction. Since $i$ still lose the auction, so his utility will still be $0$ like before.\\\\\nIf $i$ increase his bid higher than $max(b_1,r)$, than this action will make him become the winner, but this will decrease his utility since his true valuation is $v_i < r$ and now $i$ has to pay $r$ therefore his utility will be $u_i = v_i - max(b_1,r) < 0$ which is worse than before.\\\\\nIf $i$ decrease his bid, than this action ill not change the fact that he lose the auction. Since $i$ still lose the auction, so his utility will still be $0$ like before.\\\\\\\\\nIn the second case, since no matter how $i$ lie by increase or decrease the value, his utility will either be the same or become worse, therefore there is no reason for bidder $i$ to lie.\\\\\\\\\nSince no matter the player win or lose they cannot increase their utility by give a wrong valuation, therefore this auction is truthful.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\newpage\n\\section{Problem 4}\nAssume bidder $i'$ bid $\\frac{n-1}{n}v_{i'}$ and bidder $i$ bids $s_i$\\\\\n$i$ will win when $v_{i'} < \\frac{n-1}{n}s_i$ and will have the utility of $v_i - s_i$, but will lose when $v_{i'} >  \\frac{n-1}{n}s_i$ and will have the utility $0$.\nBase on these information we can have expected probability for player $i$: \n\\begin{align*}\nE[u_i] &= \\int_0^{\\frac{n-1}{n}s_i} (v_r - s_r) dv_{i'} + \\int_{\\frac{n-1}{n}s_i}^1 (0) dv_{i'}\\\\\n&= \\frac{n}{n-1}s_iv_i - \\frac{n}{n-1}s_i^2\n\\end{align*}\nFind player $i$ best bid by derivative the result:\n\\begin{align*}\n\\frac{d}{ds_i}(\\frac{n}{n-1}s_iv_i - \\frac{n}{n-1}s_i^2) &= 0\\\\\n\\frac{n}{n-1}v_i - 2\\frac{n}{n-1}s_i &= 0\\\\\ns_i = \\frac{1}{2}v_i\n\\end{align*}\nThis apply to when $i'$ bit $s_{i'}$\\\\\nSince this is only for two player game, so $n = 2$\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\end{document}", "meta": {"hexsha": "a1675742a731fc3c0d0644523ae4e4eec4c26d5f", "size": 16127, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "590T hw8.tex", "max_stars_repo_name": "briansun1210/Game-Theory-Prov", "max_stars_repo_head_hexsha": "ce14c776b8719bac1cd0c790959b05bc3987e447", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-01-25T20:24:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T20:29:11.000Z", "max_issues_repo_path": "590T hw8.tex", "max_issues_repo_name": "briansun1210/Game-Theory-Prov", "max_issues_repo_head_hexsha": "ce14c776b8719bac1cd0c790959b05bc3987e447", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "590T hw8.tex", "max_forks_repo_name": "briansun1210/Game-Theory-Prov", "max_forks_repo_head_hexsha": "ce14c776b8719bac1cd0c790959b05bc3987e447", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 75.3598130841, "max_line_length": 398, "alphanum_fraction": 0.6546784895, "num_tokens": 5399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.34958202995258786}}
{"text": "%!TEX root = thesis-kdyoung.tex\n\n% \\begin{savequote}%[45mm]\n% If people do not believe that mathematics is simple, it is only because they do not realize how complicated life is.\n% \\qauthor{John von Neumann}\n% \\end{savequote}\n\\begin{savequote}%[45mm]\n---Everything should be made as simple as possible, but not simpler.\n\\qauthor{Albert Einstein}\n\\end{savequote}\n\n\\chapter{Introduction}\n\\label{chap:intro}\nAssembly lines are flow-based production systems widely used by\nthe manufacturing industry.\nDesigning these systems to meet the requirements set\nby the industry gives rise to the Assembly Line\nBalancing Problem (\\albp{}).\nAn assembly line problem consists of a sequence\nof \\emph{stations} and a set of \\emph{tasks}.\nStations are fixed points along the assembly\nline which are operated by either human personnel\nor autonomous machinery.\nA workpiece is launched down the line and \na subset of the tasks are performed on it at each station.\nOnce all required tasks are finished, the completed product\nexits the assembly line.\n% The construction of a single product is completed\n% once all tasks have performed on it \n% To completely construct a single product\n% the all tasks are performed along the line.\nThe workload of tasks must be divided among the stations\nto optimize some performance measure,\nwhile also respecting physical restrictions.\nA standard example of such a restriction would be a\nprecedence relation, which can require\none task to be completed before another can begin\nprocessing on the product.\nThe line itself is a mechanism used to\ntransport the products between stations;\nmost commonly the line is a conveyor belt.\n\nThere are two common objectives when designing an assembly\nline, which each lead a distinct problem.\nThe first is called the type-1 problem and is concerned with\nthe design of a new assembly line where the production rate\nof the product is predefined and the aim is to construct the line\nwith as few stations as possible, in-order to meet this demand.\nThe second problem, called type-2, considers the redesign of an existing\nassembly line where the number of stations is fixed and the rate\nof production is optimized.\nThe second case can arise when a manufacturing company alters their\nproduction process or changes the products they offer.\nOur thesis focuses on solving the type-2 problem.\n\nThe \\emph{cycle time} of an assembly line defines the time each station\nis given to perform its assigned tasks.\nAs such, finding the minimal possible cycle time \nis the primary aim when optimizing the production\nrate of an assembly line.\nSince all stations are connected by a single line,\nthe station with the largest workload will define the\noverall cycle time of the line.\nTo achieve the minimal cycle time value,\nwe aim to balance the workload of the tasks\nas evenly as possible among the stations.\n\nThe structure of the paper is as follows.\nThe remainder of Chapter \\ref{chap:intro}\nprovides illustrative examples of the problem\nand closes with some motivation.\nIn Chapter \\ref{chap:theory} we detail a selection\nof the relevant theory for our problem, spanning\nthe fields of Operations Research and Artificial Intelligence.\nChapter \\ref{chap:mip} presents the mixed-integer\nprograms which were used to compare our\nsolution methodology against.\nThe construction of our logic-based Benders\ndecomposition is presented in Chapter \\ref{chap:benders},\ntogether with many possible modelling choices.\nThe results of our computational experiments are \ngiven in Chapter \\ref{chap:exp}.\nWe conclude in Chapter \\ref{chap:conc}\nwith some remarks on the performance of our\nmethod and finally note a range of possible directions\nfor future research on this topic.\n\n\\section{Preliminaries and Examples}\n\\label{sec:intro:prelim}\nThe fundamental problem in this area is called the\nSimple \\albp{}, or \\sab{}; we denote\nthe type-2 version by \\sab{2}.\nWe now detail some straightforward examples\nto illustrate how the workload\nof an assembly line can be balanced.\nIn Example \\ref{ex:intro:simple} we provide an instance\nof the \\sab{2} with a possible feasible solution and the optimal solution given\nin Figures \\ref{fig:intro:exSchedFeas} and \\ref{fig:intro:exSchedOpt}\nrespectively. Note, that $t_i$ denotes the processing time of task $i$ and\n$c$ denotes the cycle time of the assembly line.\n\n\\begin{example}\\label{ex:intro:simple}\n\tConsider an instance of the problem with four tasks $T_1,\\ldots,T_4$,\n\tand three stations $S_1,\\ldots,S_3$,\n\talong the assembly line.\n\tThe aim is to find an assignment of the tasks to the stations\n\twhich minimizes the cycle time.\n\tThis assignment must respect the precedence relations listed in Figure \\ref{fig:intro:exPrec}, \n\t\\eg task $T_1$ must be completed before task $T_2$.\n\tThe processing time of each task is included in Figure \\ref{fig:intro:exPrec}\n\tnext to each task.\n\n\tA feasible solution to this problem is given in Figure \\ref{fig:intro:exSchedFeas},\n\twhere the stations are spaced along the horizontal axis.\n\tEach station's workload begins at the horizontal axis and proceeds\n\tupward through time until all assigned tasks are completed.\n\tIn this solution, the workload of $S_3$ is the largest\n\tand as such defines the cycle time as $t_3+t_4=2+9=11$.\n\n\tThis feasible solution can be improved by moving task $T_3$ from station\n\t$S_3$ to $S_2$.\n\tFor this assignment to remain feasible, $T_3$ must be processed\n\tafter $T_2$, due to the precedence relations.\n\tThis new assignment leads to the optimal solution listed in\n\tFigure \\ref{fig:intro:exSchedOpt} with a cycle time of nine.\t\\qed\n\\end{example}\n\n\\begin{figure}[tpb]\n\t\\centering\n\t\\caption{Precedence graph}\n\t\\vspace{2mm}\n\t\\includegraphics[width=0.45\\textwidth]{images/precgraphSimple.eps}\n\t\\label{fig:intro:exPrec}\n\\end{figure}\n\n\\begin{figure}[tpb]\n\t\\centering\n\t\\begin{minipage}{0.45\\textwidth}\n\t\t\\centering\n\t\t\\caption{Feasible solution}\n\t\t\\vspace{2mm}\n\t\t\\includegraphics[width=\\linewidth]{images/exSimpleFeas.eps}\n\t\t\\label{fig:intro:exSchedFeas}\n\t\\end{minipage}\n\t\\hfill\n\t\\begin{minipage}{0.45\\textwidth}\n\t\t\\centering\n\t\t\\vfill\n\t\t\\caption{Optimal solution}\n\t\t\\vspace{2mm}\n\t\t\\includegraphics[width=\\linewidth]{images/exSimpleOpt.eps}\n\t\t\\label{fig:intro:exSchedOpt}\n\t\\end{minipage}\n\\end{figure}\n\nThe variant of the \\albp{} which we are concerned with adds the consideration\nof sequence-dependent setup times between consecutive tasks\nwithin a station's workload.\nTheoretical approaches to the \\albp{} usually assume that the assembly\nline workers can decide on an arbitrary precedence-feasible sequence\nto execute their assigned tasks, which will not affect the station's total\nprocessing time.\nHowever, in practice there can be non-trivial setup costs, due\nto walking times or tool changes, which can account for a considerable amount\nof a station's processing time.\nAdding this consideration to the problem\nleads to a scheduling problem arising within each station.\nThis variant of the problem is called the SetUp Assembly Line Balancing and\nScheduling Problem (\\sua{}).\n\nTo realistically model the setup costs that occur\nin assembly lines, two types of setups are introduced;\n\\emph{forward} and \\emph{backward} setups.\nA forward setup time, denoted by $\\phi$, occurs between two consecutive\ntasks within a station's task sequence if both tasks\nare performed on the same product.\nWhereas a backward setup time, denoted by $\\beta$, occurs between the last task\nperformed on a product and the first task performed on\nthe next product along the line.\n\n\\begin{figure}[tpb]\n\t\\centering\n\t\\caption{Cyclic task sequence of a station (adapted from \\cite{Scholl2013})}\n\t\\vspace{2mm}\n\t\\includegraphics[width=0.8\\textwidth]{images/IntroForwBackSetupEx.eps}\n\t\\label{fig:intro:forwBackDifference}\n\\end{figure}\n\nTo see how these setups are differentiated, \nFigure \\ref{fig:intro:forwBackDifference} depicts the sequence of tasks \n$T_i,\\:T_j,\\:T_k$ which are performed in a cyclic manner on consecutive\nproducts.\nThe execution of tasks proceeds chronologically from right to left,\n\\ie $T_1$ is the first task performed in cycle $p$.\nForward setups arise between consecutive tasks operating\non the same product.\nA backward setup cost is incurred between the last\ntask of cycle $p$ and the first task of the next cycle, $p+1$.\nEach cycle begins at time zero with the execution of task $T_i$\ntaking $t_i$ time units to process.\nThen after performing the forward setups $\\phi_{ij}$ and $\\phi_{jk}$\ntogether with processing times $t_j$ and $t_k$,\nthe station operator must perform the necessary backward\nsetup operation before moving to the next\nworkpiece along the line. \nThus, when including this backward setup time $\\beta_{ki}$,\nthe following condition must be satisfied to have a \nfeasible cycle time\n$t_i+\\phi_{ij}+t_j+\\phi_{jk}+t_k+\\beta_{ki} \\leq c$.\nIn Figure \\ref{fig:intro:forwBackDifference}, the gray arrow  from $T_k$ to $T_i$ implies\nthe cyclic nature of the sequence.\n\n% Example \\ref{ex:intro:simpleSetup} alters the previous\n% example into an instance of the \\sua{2}.\n\n\\begin{example}\\label{ex:intro:simpleSetup}\n\tAgain consider the instance from Example \\ref{ex:intro:simple},\n\tbut now with sequence-dependent setup times\n\tbetween tasks.\n\tThe arrays of forward and backward setup costs\n\tcan be found in Tables \\ref{tab:intro:forwSetupTimes}\n\tand \\ref{tab:intro:backSetupTimes} respectively.\n\tNote, that some of the entries in these arrays are\n\tomitted as the corresponding sequence of tasks is not \n\tpossible due to the precedence relations or\n\tlogical restrictions.\n\n\tThe previous optimal solution is amended\n\tto include the required setup costs and is given in Figure \n\t\\ref{fig:intro:exSchedSetupFeas}.\n\tNote that the setup cost of any task to itself is \n\tdefined as zero.\n\t% This results in a large forward setup, $\\phi_{23}$,\n\t% occurring on station $S_2$.\n\tTo reach the optimal solution we must now consider\n\tthe sequence of tasks within each station.\n\n\tBy moving task $T_3$ to station $S_3$ and considering\n\tthe sequencing of $T_3$ and $T_4$, we find the optimal\n\tsolution to this problem, given in Figure \\ref{fig:intro:exSchedSetupOpt}.\n\tThe optimal cycle time is 13 in this case.\t\\qed\n\\end{example}\n\n\\begin{table}[tpb]\n\t\\centering\n\t\\begin{minipage}{0.45\\textwidth}\n\t\t\\def\\arraystretch{1.1}\n\t\t\\centering\n\t\t\\caption{Forward setup times}\n\t\t\\vspace{2mm}\n\t\t\\begin{tabular}{lllll}\n\t\t\t\\toprule\n\t\t\t$\\phi$ & $T_1$ & $T_2$ & $T_3$ & $T_4$ \\\\\\midrule\\midrule\n\t\t\t$T_1$ & -- & 3 & 3 & 3 \\\\\n\t\t\t$T_2$ & -- & -- & 2 & 3 \\\\\n\t\t\t$T_3$ & -- & -- & -- & 1 \\\\\n\t\t\t$T_4$ & -- & -- & 2 & -- \\\\\n\t\t\t\\bottomrule\n\t\t\\end{tabular}\n\t\t\\label{tab:intro:forwSetupTimes}\n\t\\end{minipage}\n\t\\hfill\n\t\\begin{minipage}{0.45\\textwidth}\n\t\t\\def\\arraystretch{1.1}\n\t\t\\centering\n\t\t\\caption{Backward setup times}\n\t\t\\vspace{2mm}\n\t\t\\begin{tabular}{lllll}\n\t\t\t\\toprule\n\t\t\t$\\beta$ & $T_1$ & $T_2$ & $T_3$ & $T_4$ \\\\\\midrule\\midrule\n\t\t\t$T_1$ & 0 & -- & -- & -- \\\\\n\t\t\t$T_2$ & 3 & 0 & -- & -- \\\\\n\t\t\t$T_3$ & 3 & 5 & 0 & 3 \\\\\n\t\t\t$T_4$ & 3 & 3 & 1 & 0 \\\\\n\t\t\t\\bottomrule\n\t\t\\end{tabular}\n\t\t\\label{tab:intro:backSetupTimes}\n\t\\end{minipage}\n\\end{table}\n\n\\begin{figure}[tpb]\n\t\\centering\n\t\\begin{minipage}{0.47\\textwidth}\n\t\t\\centering\n\t\t\\caption{Feasible solution with setup}\n\t\t\\vspace{2mm}\n\t\t\\includegraphics[width=\\linewidth]{images/exSimpleSetupFeas.eps}\n\t\t\\label{fig:intro:exSchedSetupFeas}\n\t\\end{minipage}\n\t\\hfill\n\t\\begin{minipage}{0.47\\textwidth}\n\t\t\\centering\n\t\t\\caption{Optimal solution with setup}\n\t\t\\vspace{2mm}\n\t\t\\includegraphics[width=\\linewidth]{images/exSimpleSetupOpt.eps}\n\t\t\\label{fig:intro:exSchedSetupOpt}\n\t\\end{minipage}\n\\end{figure}\n\n\\section{Motivation}\n\\label{sec:intro:motiv}\nIn this section we provide motivation for why the \\albp{}\nwith setup costs\nis an important problem to be solved and why the approach we\nchose to utilize is well-suited to the problem.\n\n\\subsection{Why the SUALBSP?}\nAssembly lines were originally designed for the production\nof a single type of product in high volumes.\nAlthough, assembly lines able to produce only a single\nproduct are not suitable for consumer-centric markets, \nwhere there is a need to tailor the products\nmore closely to the user's needs.\nSequence-dependent setup times are commonly considered\nin job shop scheduling problems and a range of other\nproduction problems (\\cf \\cite{Allahverdi2008a,Allahverdi2008b,Allahverdi2015}).\nIn those problems, the setup times arise because the products\nare typically assumed to be highly diverse,\nleading to additional configuration effort being required\nbetween any two tasks.\nIn the context of operational planning of assembly lines,\nsequence-dependent setup times have been sparsely\nconsidered by the literature.\n\\authciteb{Scholl2013} list a number of possible\npractical settings where setup times between tasks should not\nbe taken as negligible. Some include the following:\n\\begin{itemize}\n\t\\item In automotive assembly lines where large workpieces (vehicles)\n\tneed to be constructed, work can be performed at numerous\n\tmounting positions on the item.\n\tThe size of the car body can result in walking distances\n\tbetween mounting positions being non-trivial.\n\tThus, the preparation time (setup) can \n\tbe a critical aspect when sequencing the required tasks.\n\t\\item Fixed material containers can be placed along the moving \n\tconveyor system to allow workers to collect parts or tools needed.\n\tFurther to walking times between these containers and the workpiece,\n\tthe time taken to retrieve what is required from the container\n\tmust also be accounted for.\n\tAt a major German car manufacturer, these times contributed $10-15\\%$\n\tof the total cycle time \\cite{Scholl2013}.\n\t\\item Specific tools are often required to perform a task.\n\tIf consecutive tasks need different tools for their\n\texecution a tool-change between tasks will be necessary.\n\tRobotic assemblers used to perform the tasks of a station\n\tcan be built to be highly flexible in the types of tasks\n\tthey can perform.\n\tHowever, this flexibility can mean that numerous tool changes\n\tare required to switch from one task to another\n\tin a sequence.\n\tThus, these sequence-dependent setup costs from tool-changes\n\tare typical in robotic assembly lines.\n\\end{itemize}\nConsequently, accurately modelling the setup costs incurred\ncan be an important aspect when balancing an assembly line.\n\nIn practice, setup times are accounted for in simpler ways, such as\nusing an approximation or incorporating the setup time\ninto the task's processing time.\n\\citeauthor{Scholl2013} note that by using such approximations\n``the planning team need to strike a fragile balance between an underestimation\nof setups, which lead to infeasible line balances, and an overestimation\nof setups, which leads to an allocation of excessive resources.''\nThe procedure used to estimate the cost of setups\ncan be time consuming and is prone to getting stuck in sub-optimal solutions.\n\nFor these reasons we feel that further research into the \neffect of setup times on the \\albp{} is of interest to the\nacademic community and the manufacturing industry.\n\n\\subsection{Why Benders Decomposition?}\nBenders decomposition is a well-known approach\nto optimization problems.\nIt is naturally suited\nto problems where the decisions can be separated into\ntwo distinct sets.\nAdvances in the past few decades to the theory of\nthis method has broadened its applicability to a \nwider array of problems.\nIn our case, a solution to the \\sua{2} can naturally\nbe divided into the assignment portion, which\nassigns each task to a station, and the scheduling\nportion, which decides on the time that each task\nbegins execution within a station.\n\nWe can view this separation of concerns in the following\nway.\nThe manager of an assembly line needs a new item\nto be put into production and so assigns the required\nset of tasks to the stations along the line.\nWhen calculating the line's cycle time the manager only estimates the setup times\nwithin each station.\nEach station operator must then decide if a possible sequencing\nof their assigned tasks exists which can respect the manager's cycle time;\nor if a precedence-feasible sequence exists at all.\n% The worker at each station must then decide if there exists\n% a possible sequencing of their assigned tasks which can\n% respect the manager's cycle time; or if there a\n% precedence-feasible sequence exists at all.\nIf at least one worker cannot find a feasible task-sequence\nthat respects the manager's cycle time\nestimate, then a revision\nmay need to be made to the assignment of tasks.\nThe give-and-take between the assignment and scheduling portions\ncontinues until a mutually satisfactory solution is found.\nThis informal process of communicating information between\nthe station workers and the assembly line manager could be time\nconsuming and not guarantee optimality.\n\nThe informal feedback loop between the two halves of the\ndecision problem suggests that Benders decomposition could be\nemployed to mimic this process.\nThe decision making process can naturally be divided\ninto a master problem, which assigns the tasks\nto the stations along the line,\nand several independent scheduling problems.\nIn total, there is a sub-problem\nfor each of the $m$ stations, which needs to\ndecide the exact execution time of all tasks\nthat station has been assigned.\nEach sub-problem is similar to the asymmetric\nTravelling Salesperson Problem (TSP)\nwith some forbidden paths due to the precedence\nrelations.\nWith this interpretation, the tasks are viewed as the \ncities and distances between them are the setup times.\nTo complete the iterative loop, the sub-problems\nrelay their information back to the master as\nBenders cuts and the assignment problem is re-optimized.\nIn the words of J. N. Hooker,\n``the Benders cuts added to the master problem are\nthe mathematical equivalent of telephone calls''\nfrom the station workers to the line manager \\cite{Hooker2007}.\n\nThe reader may be familiar with the classical version\nof the Benders decomposition method due to the \nwork of \\authciteb{Benders1962} and \\authciteb{Geoffrion1972},\nhowever for the \\sua{}, this approach is inappropriate.\nDue to the sub-problems being highly-combinatorial discrete scheduling\nproblems, formulating them as a linear or non-linear program\nwill not be practical.\nWe instead explore how the more general method of \\emph{logic-based}\nBenders decomposition can be used to solve the \\sua{2}.\n\nBy employing this approach we are able to exploit the comparative\nadvantages of multiple solving technologies to tackle each\nportion of the problem.\nMixed-Integer Programs (MIPs) are well-suited to the assignment\nproblem of the master and Constraint Programming (CP), from \nthe Computer Science discipline, is an effective solving technology\nfor scheduling problems.\n\n\\section{Problem Definition}\n\\label{sec:intro:probDef}\nHere we present the core notation that will be used for the\nremainder of the thesis.\nAlong the conveyor belt of the assembly line\nthere are \\emph{work stations} $K=\\{1,2,\\ldots,m\\}$.\nWorkpieces (or products/items) move down the \nconveyor belt from station to station.\nA workpiece remains at each station for \none cycle, which has a duration given by the \\emph{cycle time}.\nThe objective of the \\albp{} is to optimally partition\nthe total work required among the stations with respect to\na performance measure.\n\nThe work required to complete a single piece is separated into\na set of \\emph{non-preemptive tasks} $V=\\{1,2,\\ldots,n\\}$,\neach with a discrete processing time $t_i$.\nPhysical and technical conditions impose a set of \n\\emph{precedence relations} $E\\subseteq V\\times V$,\nwhich prevent some non-allowed task orderings from occurring.\nIf we consider the graph $G=(V,E)$ with tasks as the vertex set\nand directed edges defined by the precedence relations,\nthen $G$ is a directed acyclic graph (DAG).\t\nWithout loss of generality, we may assume that the vertices\nare numbered topologically so that the following holds:\n$(i,j) \\notin E$ if $i>j$.\n\nBetween each pair of tasks, discrete\n\\emph{forward} and \\emph{backward setup} times\nare predefined.\nWe denote the forward setup time between $i$ and $j$\nby $\\phi_{ij}$ and the backward setup time\nby $\\beta_{ij}$.\nWhen $i=j$, the forward setup time is undefined\nas a task can never follow itself in a station's\nforward work load.\nThe backward setup $\\beta_{ii}$, \\ie the setup cost\nof a task to itself, is defined as zero.\n\nTo fully specify a feasible solution to the \\sua{2},\none must give the following:\nan assignment of tasks to the stations\nand the execution time window of each task within\nits assigned station.\nFrom this specification, the cycle time is calculated by\nthe total processing time of the station with the\nlargest workload.\n\n", "meta": {"hexsha": "f26e43553bfb1c92e8890bd0e0ec55a39cab9192", "size": 20592, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Assembly Task Scheduling/sualbsp-2-master/thesis/chap_intro.tex", "max_stars_repo_name": "BillChan226/ODA-Multi-Manipulator", "max_stars_repo_head_hexsha": "6863558a9fdb946fb16c67a7660172154274cfe0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assembly Task Scheduling/sualbsp-2-master/thesis/chap_intro.tex", "max_issues_repo_name": "BillChan226/ODA-Multi-Manipulator", "max_issues_repo_head_hexsha": "6863558a9fdb946fb16c67a7660172154274cfe0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assembly Task Scheduling/sualbsp-2-master/thesis/chap_intro.tex", "max_forks_repo_name": "BillChan226/ODA-Multi-Manipulator", "max_forks_repo_head_hexsha": "6863558a9fdb946fb16c67a7660172154274cfe0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.1017964072, "max_line_length": 118, "alphanum_fraction": 0.7816142191, "num_tokens": 5174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.34958202074957434}}
{"text": "\\section{SEDflow} \\label{sec:sedflow}\nIn this section, we present \\sedflow, which applies ANPE to galaxy SED modeling\nfor a scalable and accelerated approach.\nFor our SED model, we use the state-of-the-art PROVABGS model from\n\\cite{hahn2022}. \nAlthough many SED models have been recently used in the\nliterature~(\\emph{e.g.} {\\sc Bagpipes}, \\citealt{carnall2018}; \n{\\sc Prospector}, \\citealt{leja2017, johnson2021}), we choose PROVABGS because\nit will be used to analyze >10 million galaxy spectrophotometry measured by the\nDESI Bright Galaxy Survey~(Hahn~\\etal~in prep.).\nBelow, we describe the PROVABGS model, the construction of the\n\\sedflow~training data using PROVABGS, and the training procedure for \\sedflow.\n\n% section explaining specific SED set up \n\\subsection{SED Modeling: PROVABGS} \\label{sec:provabgs}\nWe use the state-of-the-art SPS model of the\nPROVABGS~\\citep{hahn2022}. \nThe SED of a galaxy is modeled as a composite of stellar populations defined by\nstellar evolution theory (in the form of isochrones, stellar spectral\nlibraries, and an initial mass function) and its star\nformation and chemical enrichment histories (SFH and ZH), attenuated by\ndust~\\citep[see][for a review]{walcher2011, conroy2013}. \nThe PROVABGS model, in particular, utilizes a non-parametric SFH with a\nstarburst, a non-parametric ZH that varies with time, and a flexible dust\nattenuation prescription.\n\n% highlight advantages of provabgs \nThe SFH has two components: one based on non-negative matrix factorization\n(NMF) bases and the other, a starburst component.\nThe SFH contribution from the NMF component is a linear combination of four NMF\nSFH basis functions, derived from performing NMF~\\citep{lee1999, cichocki2009,\nfevotte2011} on SFHs of galaxies in the Illustris cosmological hydrodynamical\nsimulation~\\citep{vogelsberger2014, genel2014, nelson2015}.\nThe NMF SFH prescription provides a compact and flexible representation of the\nSFH.\nThe second starburst component consists of a single stellar population (SSP)\nand adds stochasticity to the SFH. \n\nThe ZH is similar defined using two NMF bases dervied from Illustris. \nThis ZH prescription enables us to flexibly model a wide range of ZHs and,\nunlike most SED models, it does not assume constant metallicity over time,\nwhich can significantly bias inferred galaxy properties~\\citep{thorne2021}. \nThe stellar evolution theory is based on Flexible Stellar Population\nSynthesis~\\citep[FSPS;][]{conroy2009, conroy2010c} with the MIST\nisochrones~\\citep{paxton2011, paxton2013, paxton2015, choi2016, dotter2016},  \nthe \\cite{chabrier2003} initial mass function (IMF), and a combination of the\nMILES~\\citep{sanchez-blazquez2006} and BaSeL~\\citep{lejeune1997, lejeune1998,\nwestera2002} libraries.\nThe SFH and ZH are binned into 43 logarithmically-space time and SSPs are\nevalulated at each time bin using FSPS. \nThe SSPs are summed up to get the unattenuated rest-frame galaxy SED. \n\nLastly, PROVABGS attenuates the light from the composite stellar population\nusing the two component \\cite{charlot2000} dust attenuation model with\ndiffuse-dust (ISM) and birth cloud (BC) components. \nAll SSPs are attenuated by the diffuse dust using the \\cite{kriek2013}\nattenuation curve.\nThen, the BC component provides extra dust attenuation on SSPs younger than 100\nMyr with young stars that are embedded in modecular clouds and HII regions. \nIn total the PROVABGS SED model has 12 parameters: stellar mass ($M_*$),\nsix SFH parameters ($\\beta_1, \\beta_2, \\beta_3, \\beta_4, t_{\\rm burst}, f_{\\rm\nburst}$), two ZH parameters ($\\gamma_1, \\gamma2$), and three dust attenuation\nparameters ($\\tau_{\\rm BC}, \\tau_{\\rm ISM}, n_{\\rm dust}$). \nEach PROVABGS model evaluation takes ${\\sim}340$ ms. \n\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=0.85\\textwidth]{figs/training.pdf}\n    \\caption{\\label{fig:data}\n    The distribution of SED model parameters, redshift, photometric\n    magnitudes, and uncertainties of the data used to train \\sedflow.\n    We plot a subset of the parameters ($\\log M_*$, $\\beta_1$) and photometric\n    bands for clarity.\n    The training data was constructed by sampling SED model parameters from the\n    prior and forward modeling optical photometry using the PROVABGS and noise\n    models (Section~\\ref{sec:sedflow}). \n    For comparison, we present the distribution of redshift, magnitudes, and\n    uncertainties for galaxies in the NSA catalog (blue). \n    \\emph{The training set encompasses the observations; thus, {\\sc SEDflow}\n    can be used to infer the posterior for the NSA galaxies}.\n    }\n\\end{center}\n\\end{figure}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% training data \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Training Data} \\label{sec:training}\nIn this section, we describe how we construct the training data for\n\\sedflow~using the PROVABGS SED model.\nFirst, we sample $N_{\\rm train}$ model parameters from a prior: $\\theta'\\sim p(\\theta)$. \nWe use the same priors as \\cite{hahn2022}: uniform priors over $M_*,\nt_{\\rm burst}, f_{\\rm burst}, \\gamma_1, \\gamma_2, \\tau_{\\rm BC}, \\tau_{\\rm ISM},\nn_{\\rm dust}$ with broad conservative ranges and Dirichlet prior over $\\beta_1,\n\\beta_2, \\beta_3, \\beta_4$, chosen to normalize the NMF SFH.\nFor each $\\theta'$, we also uniformly sample a redshift within the range of the\nNSA: $z' \\sim \\mathcal{U}(0., 0.2)$. \nNext, we forward model mock observables. \nWe calculate the rest-frame galaxy SED from PROVABGS and redshift it: \n$F(\\lambda;\\theta', z)$. \nAfterwards, we convolve $F$ with optical broadband filters, $R_X$, to generate\nnoiseless photometric fluxes:\n\\begin{equation}\n    f_X(\\theta', z') = \\int F(\\lambda;\\theta', z') \\, R_X(\\lambda) \\, {\\rm d}\\lambda\n\\end{equation}\nThe next step of the forward model is to apply noise. \nWe assign photometric uncertainties, $\\sigma'_X$, by sampling an estimate of\nthe observed $p(\\sigma_X | f_X)$ of NSA galaxies. \nThen, we apply Gaussian noise\n\\begin{equation} \\label{eq:noise} \n    \\hat{f}_X(\\theta', z', \\sigma'_x) = f_X(\\theta', z') + n_X  \\quad {\\rm where}~n_X \\sim \\mathcal{N}(0, \\sigma'_X)\n\\end{equation}\nto derive the forward modeled photometric flux.\n\nFor our estimate of $p(\\sigma_X | f_X)$, we use an empirical estimate based on\nNSA photometry and measured uncertainties. \nFor each of the five optical bands, we separately estimate  \n\\begin{equation}\n    \\hat{p}(\\sigma_X | f_X) = \\mathcal{N} \\big( \\mu_{\\sigma_X}(f_X),\n    \\sigma_{\\sigma_X}(f_X) \\big)\n\\end{equation}\nas a Gaussian in magnitude-space. \n$\\mu_{\\sigma_X}$ and $\\sigma_{\\sigma_X}$ are the median and standard deviation\nof $\\sigma_X$ as a function of $f_X$ that we estimate by evaluating them in\n$f_X$ bins and interpolating over the bins. \nAny $\\theta'$ that is assigned a negative $\\sigma'_X$ is removed from our\ntraining data. \nWe also remove any training data with $f_X(\\theta')$ outside the range of NSA\nphotometry. \n\nAs SBI requires an accurate noise model, one might be concerned about the\nsimplicity of our model.\nIf the noise model is incorrect, estimates of the parameters $\\theta$ would be\nbiased by an amount that is impossible to predict.\nWe therefore add the noise variances $\\sigma_X$ to the conditioning variables\nof the posterior model, \\emph{i.e.} we train and evaluate \n$p_\\phi(\\btheta\\given\\bfi{x},\\{\\sigma_X\\})$.\nThis means we merely have to ensure that $\\sigma'_X$ spans the observed\n$\\sigma_X$ values in order to have a posterior that is robust to our choice of\nnoise model.\nWe discuss this further in Section~\\ref{sec:discuss}.\n\nIn total, we constuct $N_{\\rm train} = 1,131,561$ sets of SED parameters,\nredshift, photometric uncertainties, and mock NSA photometry. \nIn Figure~\\ref{fig:data}, we present the distribution of the training data\n$\\{(\\theta', z, \\sigma'_X, \\hat{f}_X) \\}$ (black).\nWe include select SED model parameters ($\\log M_*$, $\\beta_1$), redshift,\nphotometry in the $g$ and $r$ bands, and photometric uncertainty in the $r$\nband.\nWe also include the $(z, \\sigma_X, f_X)$ distribution of NSA galaxies (blue),\nfor comparison.\nThe photometry and uncertainties are in magnitude-space. \nThe distribution of the training data spans the distribution of NSA galaxies.\n\n\\subsection{Training \\sedflow} \\label{sec:anpe_train}\nFor \\sedflow, we use a MAF normalizing flow model (Section~\\ref{sec:flow}) with \n15 MADE blocks, each with 2 hidden layers and 500 hidden units.\nIn total, the model has 7,890,330 parameters, $\\bphi$. \nWe determine this architecture through experimentation. \nOur goal is to determine $\\bphi$ of the MAF model, \n$p_\\phi(\\btheta\\given\\bfi{x})$, so that it accurately estimates the\nposterior probability distribution $p(\\btheta\\given\\bfi{x})$. \n$\\btheta$ represent the SED parameters and $\\bfi{x} = (f_X, \\sigma_X, z)$.\nWe do this by minimizing the KL divergence between \n$p_\\phi(\\btheta\\given\\bfi{x})$ and $p(\\btheta\\given\\bfi{x})$: \n$D_{\\rm KL} (p\\,||\\,p_\\phi)$.\n\nIn practice, we split the training data into a training and validation set with\na 90/10 split. \nAfterwards, we maximize the total log likelihood \n$\\sum_i \\log p_\\phi(\\btheta_i\\given \\bfi{x}_i)$ over training set, which is\nequivalent to minimizing $D_{\\rm KL} (p\\,||\\,p_\\phi)$.\nWe use the {\\sc Adam} optimizer~\\citep{kingma2017} with a learning rate of $5\\times10^{-4}$. \nTo prevent overfitting, we evaluate the total log likelihood on the validation\ndata at every training epoch and stop the training when the validation log\nlikelihood fails to increase after 20 epochs.  \nTraining our model with a batch size of 50 takes roughly a day on a single 2.6\nGHz Intel Skylake CPU. \nGiven our small batch size, we find similar training times when using CPUs or\nGPUs. \n", "meta": {"hexsha": "31f04de37ae15633d90f5b63a3905652edb90c2c", "size": 9699, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/paper/sedflow.tex", "max_stars_repo_name": "changhoonhahn/SEDflow", "max_stars_repo_head_hexsha": "4561ecfe3a38cc4c25df263d971a87e8a83f88ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2022-03-16T03:11:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T16:01:42.000Z", "max_issues_repo_path": "docs/paper/sedflow.tex", "max_issues_repo_name": "changhoonhahn/SEDflow", "max_issues_repo_head_hexsha": "4561ecfe3a38cc4c25df263d971a87e8a83f88ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/paper/sedflow.tex", "max_forks_repo_name": "changhoonhahn/SEDflow", "max_forks_repo_head_hexsha": "4561ecfe3a38cc4c25df263d971a87e8a83f88ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.5856353591, "max_line_length": 116, "alphanum_fraction": 0.7456438808, "num_tokens": 2735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.34932965773726726}}
{"text": "% Filename: p2_set_and_functions@tikz_for_teachers.tex\n% This code is part of LaTeX with Vim.\n% \n% Description: TikZ for teachers is free book about TikZ and Sage.\n% \n% Created: 30.03.12 08:25:52 PM\n% Last Change: 30.03.12 08:26:12 PM\n% \n% Author: Raniere Gaia Costa da Silva, r.gaia.cs@gmail.com\n% Organization:  \n% \n% Copyright (c) 2010, 2011, 2012, Raniere Gaia Costa da Silva. All rights \n% reserved.\n% \n% This file is license under the terms of a Creative Commons Attribution \n% 3.0 Unported License, or (at your option) any later version. More details\n% at <http://creativecommons.org/licenses/by/3.0/>.\n\\chapter{Conjuntos e Fun\\c{c}\\~{o}es}\n\n\\section{No\\c{c}\\~{o}es de L\\'{o}gica}\n\n\\section{Conjuntos}\n\n\\example{codes/sets01@tikz_for_teachers}\n\n\\example{codes/sets02@tikz_for_teachers}\n\n\\example{codes/sets03@tikz_for_teachers}\n\n\\example{codes/sets04@tikz_for_teachers}\n\n\\section{Conjuntos Num\\'{e}ricos}\n\n\\section{Rela\\c{c}\\~{o}es}\n\n\\section{Fun\\c{c}\\~{o}es}\n\n\n", "meta": {"hexsha": "911122b78a77a401b5f241ee1680132b647d65fb", "size": 969, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "pt/tikz_for_teachers/p2_set_and_functions@tikz_for_teachers.tex", "max_stars_repo_name": "r-gaia-cs/latex_with_vim", "max_stars_repo_head_hexsha": "1ede258a90230247bf302918ded851c2856a7356", "max_stars_repo_licenses": ["Vim"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pt/tikz_for_teachers/p2_set_and_functions@tikz_for_teachers.tex", "max_issues_repo_name": "r-gaia-cs/latex_with_vim", "max_issues_repo_head_hexsha": "1ede258a90230247bf302918ded851c2856a7356", "max_issues_repo_licenses": ["Vim"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pt/tikz_for_teachers/p2_set_and_functions@tikz_for_teachers.tex", "max_forks_repo_name": "r-gaia-cs/latex_with_vim", "max_forks_repo_head_hexsha": "1ede258a90230247bf302918ded851c2856a7356", "max_forks_repo_licenses": ["Vim"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8461538462, "max_line_length": 75, "alphanum_fraction": 0.7244582043, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.349290659969759}}
{"text": "\\documentclass[bigger]{beamer}\n\n\\input{header-beam} % change to header-handout for handouts\n\n% ====================\n\\title[Lecture 19]{Logic I F13 Lecture 19}\n\\date{November 21, 2013}\n% ====================\n\n\\include{header}\n\n\\setlength{\\fitchprfwidth}{14em}\n\n\\section{Numerical Quantification}\n\n\\subsec{Numerical Quantification}{\n\n\n\\bit\n\\item Cardinal numbers can be determiners:\n\\bit\n\\item \\emph{Three cubes} are left of \\emph{two dodecahedra}\n\\eit\n\\item Not always clear if ``three cubes'' means \\emph{exactly} or \\emph{at least} three\n\\item We'll assume the latter---the ``exactly'' is implicated, not implied\n\\bit\n\\item Do you have two dollars? Yes, I have two dollars. (Uncontroversially true even if you have more than 2\\$)\n\\item How much money do you have? I have two dollars. (True but misleading if you have more.)\n\\eit\n\\item FOL can express all of:\n\\bit\n\\item \\emph{At least $n$} cubes are \\dots \n\\item \\emph{Exactly $n$} cubes are \\dots\n\\item \\emph{At most $n$} cubes are \\dots\n\\eit\n\\eit\n\n}\n\n\\subsec{At least $n$}{\n\n\\bit\n\\item At least 1 cube is small:\n\\[\n\\exists x(Cube(x) \\land Small(x))\n\\]\n\\item At least 2 cubes are small:\n\\[\n\\exists x\\exists y(x \\neq y \\land Cube(x) \\land Small(x) \\land Cube(y) \\land Small(y))\n\\]\n\\eit\n}\n\n\n\\subsec{$\\exists^{\\ge n}x\\, A(x)$}{\n\n\\bit\n\\item $\\exists^{\\ge n}x\\, A(x)$:\n\\begin{align*}\n\\exists x_1\\dots\\exists x_n(x_1 \\neq x_2 \\land x_1 \\neq x_3 \\land \\dots \\land x_1 \\neq x_n & {} \\land {}\\\\\nx_2 \\neq x_3 \\land \\dots \\land x_2 \\neq x_n & {} \\land {}\\\\\n\\ddots\\qquad &\\\\\nx_{n-1} \\neq x_n & {} \\land {}\\\\\n A(x_1) \\land \\dots \\land A(x_n)) \n\\end{align*}\n\\eit\n}\n\n\\subsec{$\\exists^{\\ge n}x\\, A(x)$}{\n\n\n\\bit\n\\item NB: must state that \\emph{every pair} of variables is different, e.g.,\n\\[\\sf\\exists x_1\\exists x_2\\exists x_3(x_1 \\neq x_2 \\land x_2 \\neq x_3 \\land Cube(x_1) \\land Cube(x_2) \\land Cube(x_3))\\]\nonly says ``There are at least two cubes''! \n\\item At least $n$ As are Bs:\\[\n\\exists^{\\ge n} x(A(x) \\land B(x))\n\\]\n\\eit\n}\n\n\\subsec{Exactly One}{\n\n\\bit\n\\item There is exactly one cube:\n\\[\n\\exists x(Cube(x) \\land \\lnot \\exists y(Cube(y) \\land x \\neq y))\n\\]\n\\item This is equivalent to:\n\\[\n\\exists x(Cube(x) \\land \\forall y(Cube(y) \\to x = y))\n\\]\n\\item In general: ``x has property A \\emph{uniquely}'':\n\\begin{align*}\nA(x) \\land & \\forall y(A(y) \\to x = y)\\\\\n\\text{or just:\\qquad} & \\forall y(A(y) \\liff x = y)\n\\end{align*}\n\\eit\n}\n\n\\subsec{$\\exists^{=n} x\\, A(x)$}{\n\n\\bit\n\\item There are exactly $n$ things that satisfy A:\n\\begin{align*}\n\\exists x_1\\dots\\exists x_n(x_1 \\neq x_2 \\land x_1 \\neq x_3 \\land \\dots \\land x_1 \\neq x_n & {} \\land {}\\\\\nx_2 \\neq x_3 \\land \\dots \\land x_2 \\neq x_n & {} \\land {}\\\\\n\\ddots\\qquad &\\\\\nx_{n-1} \\neq x_n & {} \\land {}\\\\\n\\only<1>{ A(x_1) \\land \\dots \\land A(x_n) &{} \\land {}}\\\\\n\\forall y(A(y) \\only<1>{\\to}\\only<2>{\\leftrightarrow} (y = x_1 \\lor \\dots \\lor y=x_n)))\n\\end{align*}\n\\item Exactly $n$ As are Bs:\n\\[\n\\exists^{=n}x (A(x) \\land B(x))\n\\]\n\\eit\n\n}\n\n\\subsec{At most $n$}{\n\n\\bit\n\\item There are \\emph{at most $n$} As $\\IFF$ There aren't \\emph{at least $n+1$} As\n\\[\n\\exists^{\\emph{\\le n}}x\\, A(x) \\IFF \\emph{\\lnot}\\exists^{\\emph{\\ge(n+1)}}x\\, A(x)\n\\]\n\\item $\\lnot\\exists^{\\ge(n+1)}x\\, A(x)$ is equivalent to:\n\\begin{align*}\n\\forall x_1\\dots\\forall x_{n+1}((A(x_1) \\land \\dots \\land A(x_{n+1})) & {} \\to {}\\\\\n(x_1 = x_2 \\lor x_1 = x_3 \\lor \\dots \\lor x_1 = x_{n+1} & {} \\lor {}\\\\\nx_2 = x_3 \\lor \\dots \\lor x_2 = x_{n+1} & {} \\lor {}\\\\\n\\ddots\\qquad &\\\\\nx_n = x_{n+1} & ))\n\\end{align*}\n\\eit\n}\n\n\\subsec{Proofs With Numerical Claims}{\n\n\\fitchprf{\n\\pline{\\exists x\\, P(x)}\\\\\n\\pline{\\forall x\\forall y ((P(x) \\land P(y)) \\to x = y)}}{\n\\pline{\\exists x(P(x) \\land \\forall y(P(y) \\to x = y))}\n}\n}\n\n\\section{``The'', ``Both'', ``Neither''}\n\n\\subsec{Definite Descriptions}{\n\n\\bit\n\\item Definite description: \\emph{the so-and-so}\n\\item Russell's analysis of definite description: to say\\\\\n\\bit\n\\item ``The A is B''\\\\\n\\eit\nis to say:\n\\bit\n\\item There is a unique A\n\\item It is B\n\\eit\n\\item In FOL:\n\\[\n\\exists x(A(x) \\land \\forall y(A(y) \\to x = y) \\land B(x))\n\\]\n\\item or more succinctly:\n\\[\n\\exists x(\\forall y(A(y) \\liff x = y) \\land B(x))\n\\]\n\\eit\n\n}\n\n\\subsec{The vs. Exactly One}{\n\n\\bit \\item Compare:\n\\ben\n\\item The cube is small\n\\[\\exists x(Cube(x) \\land \\forall y(Cube(y) \\to x = y) \\land Small(x))\\]\n\\item There is exactly one small cube\n\\[\\exists x(Cube(x) \\land \\forall y((Cube(y) \\emph{{}\\land Small(y)}) \\to x = y) \\land Small(x))\\]\n\\een\n\\item (2) can be true without (1), but not vice versa\n\\item So (2) is a FO consequence of (1), but not vice versa\n\\eit\n}\n\n\\subsec{Strawson's Analysis}{\n\n\\bit\n\\item According to Russell, ``The cube is small'' is false if there is no cube, or if there is more than one\n\\item Strawson disagrees\n\\item ``There is a unique cube'' is not part of what is \\emph{said}, but is only \\emph{presupposed}\n\\eit\n\n}\n\n\\subsec{``Both'' and ``Neither''}{\n\n\\bit\n\\item ``Both cubes are small'': There are exactly 2 cubes, and each of them is small:\n\\begin{align*}\n\\exists x\\exists y(x \\neq y \\land Cube(x) \\land Cube(y) &{} \\land {}\\\\\n\\forall z(Cube(z) \\to (z = x \\lor z = y)) & {}\\land {}\\\\\n\\forall z(Cube(z) \\to Small(z))&)\n\\end{align*}\n\\item NB: ``Both cubes are small'' implies ``There are exactly two small cubes'', but not vice versa!\n\\item ``Neither cube is small'': There are exactly 2 cubes, and none of them are small:\n\\begin{align*}\n\\exists x\\exists y(x \\neq y \\land Cube(x) \\land Cube(y) & {}\\land {}\\\\\n\\forall z(Cube(z) \\to (z = x \\lor z = y)) &{} \\land {}\\\\\n\\forall z(Cube(z) \\to \\lnot Small(z))&)\n\\end{align*} \n\\eit\n\n}\n\n\\section{Truth-Functional Completeness}\n\n\\subsec{Truth Functions}{\n\n\\begin{block}{Definition}\n\nAn ($n$-place) \\emph{truth function} $t$ is a mapping of $n$-tuples of \\T{} and \\F\\ to either \\T\\ or \\F.\n\\medskip\n\n$n$-place truth functions correspond to truth tables of sentence with $n$ atomic sentences.\n\\medskip\n\nA sentence $S$ containing the atomic sentences $A_1$, \\dots, $A_n$\n\\emph{expresses} the truth function $t$ iff the truth value of $S$ on\nthe truth-value assignment which assigns $v_i$ to $A_i$ is $t(v_1,\n\\dots, v_n)$.\n\\medskip\n\nAn $n$-place truth function is \\emph{expressible} if there is a\nsentence containing atomic sentences $A_1$, \\dots, $A_n$ that\nexpresses it.\n\n\\end{block}\n}\n\n\\subsec{Examples}{\n\n\\begin{tabular}{cc@{\\qquad}cc}\n$\\begin{array}{cc|c}\n&& t_\\land\\\\ \\hline \n\\T & \\T & \\T \\\\\n\\T & \\F & \\F \\\\\n\\F & \\T & \\F \\\\\n\\F & \\F & \\F\n\\end{array}$\n&\n$A_1 \\land A_2$ &\n$\\begin{array}{cc|c}\n&& t_\\lor \\\\ \\hline\n\\T & \\T & \\T \\\\\n\\T & \\F & \\T \\\\\n\\F & \\T & \\T \\\\\n\\F & \\F & \\F\n\\end{array}$\n& $A_1 \\lor A_2$\n\\end{tabular}\n}\n\n\\subsec{Examples}{\n\n\\begin{tabular}{cc@{\\qquad}cc}\n$\\begin{array}{cc|c}\n& & t_1\\\\ \\hline\n\\T & \\T & \\T \\\\\n\\T & \\F & \\T \\\\\n\\F & \\T & \\F \\\\\n\\F & \\F & \\F\n\\end{array}$\n& $A_1$ &\n$\\begin{array}{cc|c}\n& & t_{XOR}\\\\ \\hline\n\\T & \\T & \\F \\\\\n\\T & \\F & \\T \\\\\n\\F & \\T & \\T \\\\\n\\F & \\F & \\F\n\\end{array}$\n&\n$(A_1 \\lor A_2) \\land \\lnot(A_1 \\land A_2)$ \\\\ \\ \\\\\n$\\begin{array}{cc|c}\n& & t_2\\\\ \\hline\n\\T & \\T & \\T \\\\\n\\T & \\F & \\F \\\\\n\\F & \\T & \\T \\\\\n\\F & \\F & \\F\n\\end{array}$\n& $A_2$ \n\\end{tabular}\n}\n\n\n\n\\subsec{Truth-Functional Completeness}{\n\n\\begin{block}{Definition}\n\nA set of connectives is \\emph{truth-functionally complete} if every\ntruth function is expressible by a sentence containing only those\nconnectives.\n\n\\end{block}\n\n}\n\n\\subsec{$\\{\\land, \\lor\\}$ Not Truth-Functionally Complete}{\n\n\\bit\n\\item $\\{\\land, \\lor\\}$ is not truth-functionally complete\n\\item Remember: To be truth functionally complete, \\emph{every} truth\n  function would have to be expressible using only $\\land$ and $\\lor$\n\\item Which 2-place truth-functions can be expressed using $\\land$ and\n  $\\lor$?\n\\item Not this one:\n\\[\n\\begin{array}{cc|c}\n\\T & \\T & \\F \\\\\n\\T & \\F & \\T \\\\\n\\F & \\T & \\T \\\\\n\\F & \\F & \\F\n\\end{array}\n\\]\n  \\eit\n\n}\n\n\n\\subsec{Course Evaluation}{\n\n\\bit\n\\item Please fill out TWO TA evaluations, one for Jared and one for Dan.\n\\item More TopHat instant feedback questions? Or is TopHat not worth the trouble?\n\\item Three tests good, or would you prefer a midterm \nand a final after classes end?\n\\item Timing of homeworks---prefer Friday or Monday?\n\\item PASS sessions: did you go? Was it useful?\n\\eit\n}\n\\end{document}\n\n\\subsec{$\\{\\land, \\lor, \\lnot\\}$ is Truth-functionally Complete}{\n\\[\n\\begin{array}{lll|l@{\\qquad}l}\nA_1 & A_2 & A_3 & t_\\mathrm{ODD} & S \\\\\n\\hline\n\\T & \\T & \\T & \\T & \\uncover<2->{(A_1 \\land A_2 \\land A_3)} \\uncover<6->{{}\\lor}\\\\\n\\T & \\T & \\F & \\F \\\\\n\\T & \\F & \\T & \\F \\\\\n\\T & \\F & \\F & \\T & \\uncover<3->{(A_1 \\land \\lnot A_2 \\land \\lnot A_3)} \\uncover<6->{{}\\lor}\\\\\n\\F & \\T & \\T & \\F \\\\\n\\F & \\T & \\F & \\T & \\uncover<4->{(\\lnot A_1 \\land A_2 \\land \\lnot A_3)} \\uncover<6->{{}\\lor}\\\\\n\\F & \\F & \\T & \\T & \\uncover<5->{(\\lnot A_1 \\land \\lnot A_2 \\land A_3)} \\uncover<6->{{}\\lor}\\\\\n\\F & \\F & \\F & \\F\n\\end{array}\\]\n}\n\n\\subsec{$\\{\\land, \\lor, \\lnot\\}$ is Truth-Functionally Complete}{\n\n\\bit\n\\item $\\lnot A_1 \\land A_2 \\land \\lnot A_3$ is true in, and only in line \\F\\ \\T\\ \\F\n\\item Combine using $\\lor$: make $S$ true in all (and only) the lines where it is supposed to be true\n\\item NB: Procedure results in DNF!\n\\eit\n\n}\n\n\\subsec{The ``neither\\dots nor \\dots'' connective: $\\downarrow$}{\n\n\\[\n\\begin{array}{cc|c}\nP & Q & (P \\downarrow Q)\\\\\n\\hline\n\\T & \\T & \\F\\\\\n\\T & \\F & \\F\\\\\n\\F & \\T & \\F\\\\\n\\F & \\F & \\T\n\\end{array}\n\\]\n\n}\n\n\\subsec{$\\{\\downarrow\\}$ is Truth-Functionally Complete}{\n\n\\bit\n\\item Already know that $\\{\\lnot, \\land, \\lor\\}$ is truth-functionally\n  complete, i.e.,\n\\item Every truth-function can be expressed using only $\\lor$, $\\land$, $\\lnot$\n\\item To show $\\downarrow$ is truth-functionally complete, suffices to\n  show that \\emph{every sentence containing only $\\lnot$, $\\lor$, $\\land$ is\n  tautologically equivalent to one containing only $\\downarrow$}\n\\item For that, it suffices to show that any negated sentence,\n  conjunction, disjunction, can be expressed using only $\\downarrow$\n\\eit\n\n}\n\n\\subsec{Expressing $\\lnot$ Using $\\downarrow$}{\n\n\\begin{columns}\n\\begin{column}{3cm}\n\\[\\begin{array}{cc|c}\nP & Q & (P \\downarrow Q)\\\\\n\\hline\n\\T & \\T & \\F\\\\\n\\T & \\F & \\F\\\\\n\\F & \\T & \\F\\\\\n\\F & \\F & \\T\n\\end{array}\\]\n\\end{column}\n\\begin{column}{7cm}\n\\bits\n\\item Note how $P \\downarrow Q$ is \\F{} in the first line and \\T{} in the last (when $P$ and $Q$ have same truth value)\n\\item So $P \\downarrow P$ is \\F{} if $P$ is \\T, and \\T{} if $P$ is \\F, i.e., \\[\n\\lnot P \\Leftrightarrow (P \\downarrow P)\n\\]\n\\eit\n\\end{column}\n\\end{columns}\n\n}\n\n\\subsec{Expressing $\\lor$ Using $\\downarrow$}{\n\n\\begin{columns}\n\\begin{column}{3cm}\n\\[\\begin{array}{cc|c}\nP & Q & (P \\downarrow Q)\\\\\n\\hline\n\\T & \\T & \\F\\\\\n\\T & \\F & \\F\\\\\n\\F & \\T & \\F\\\\\n\\F & \\F & \\T\n\\end{array}\\]\n\\end{column}\n\\begin{column}{7cm}\n\\bits\n\\item $P \\downarrow Q$ is the ``neither \\dots nor'' connective, which can also\nbe expressed as $\\lnot(P \\lor Q)$, i.e.,\n\\[ \\lnot(P \\lor Q) \\Leftrightarrow P \\downarrow Q \\] \n\\item Negate both sides:\n\\[\nP \\lor Q \\Leftrightarrow \\lnot(P \\downarrow Q)\n\\]\n\\item Apply what we figured out in last slide:\n\\[\nP \\lor Q \\Leftrightarrow (P \\downarrow Q)\\downarrow(P \\downarrow Q)\n\\]\n\\eit\n\\end{column}\n\\end{columns}\n\n}\n\n\\subsec{Expressing $\\land$ Using $\\downarrow$}{\n\n\\begin{columns}\n\\begin{column}{3cm}\n\\[\\begin{array}{cc|c}\nP & Q & (P \\downarrow Q)\\\\\n\\hline\n\\T & \\T & \\F\\\\\n\\T & \\F & \\F\\\\\n\\F & \\T & \\F\\\\\n\\F & \\F & \\T\n\\end{array}\\]\n\\end{column}\n\\begin{column}{7cm}\n\\bits\n\\item $P \\downarrow Q$ is the ``neither \\dots nor'' connective, which can also\nbe expressed as $\\lnot P \\land \\lnot Q$, i.e.,\n\\[ (\\lnot P \\land \\lnot Q) \\Leftrightarrow P \\downarrow Q \\] \n\\item Equivalence holds for \\emph{all sentences} $P$, $Q$, so also if we replace $P$ by $\\lnot R$ and $Q$ by $\\lnot S$:\n\\[\n\\lnot\\lnot R \\land \\lnot\\lnot S \\Leftrightarrow (\\lnot R \\downarrow \\lnot S)\n\\]\n\\item Delete $\\lnot\\lnot$'s, and express $\\lnot$ using $\\downarrow$:\n\\[\nR \\land S \\Leftrightarrow (R \\downarrow R)\\downarrow(S \\downarrow S)\n\\]\n\\eit\n\\end{column}\n\\end{columns}\n\n}\n\n\\subsec{Truth-Functionally Complete Sets of Connectives}{\n\n\\bit\n\\item De Morgan's Law: $\\land$ can be expressed by $\\lor$ and $\\lnot$\n\\item Similarly: $\\lor$ can be expressed by $\\land$, $\\lnot$\n\\item So $\\{\\lor, \\lnot\\}$ and $\\{\\land, \\lnot\\}$ are\n  truth-functionally complete\n\\item $\\{\\to, \\bot\\}$ is truth-functionally complete (HW)\n\\item $\\{\\to, \\lnot\\}$ is truth-functionally complete \n\\item No other sets of connectives that don't contain one of these sets are complete \n\\item ``Neither \\dots nor'' is truth-functionally complete by itself\n\\item ``Not both'' connective is truth-functionally complete by itself (HW)\n\\item No other 2-place connectives are complete by themselves\n\\eit\n\n}\n\n\\end{document}\n\n\n\n\n", "meta": {"hexsha": "b0481cee5f4cf65484fc0241599d8a49f6e145ba", "size": 12586, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "279-lec19.tex", "max_stars_repo_name": "rzach/phil279", "max_stars_repo_head_hexsha": "722ec82ae7a4593d40c72083d830c4e3e4864dc0", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2015-09-23T13:42:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-21T10:48:55.000Z", "max_issues_repo_path": "279-lec19.tex", "max_issues_repo_name": "rzach/phil279", "max_issues_repo_head_hexsha": "722ec82ae7a4593d40c72083d830c4e3e4864dc0", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "279-lec19.tex", "max_forks_repo_name": "rzach/phil279", "max_forks_repo_head_hexsha": "722ec82ae7a4593d40c72083d830c4e3e4864dc0", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.486381323, "max_line_length": 121, "alphanum_fraction": 0.6242650564, "num_tokens": 4777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.3492906565588393}}
{"text": "\\documentclass{article}\n\n\\usepackage[utf8]{inputenc}\n\\usepackage[english]{babel}\n\\usepackage{a4}\n\\usepackage[T1]{fontenc}\n\\usepackage[cyr]{aeguill}\n\\usepackage{graphicx}\n\\usepackage{amsmath}\n\\usepackage{authblk}\n\\usepackage{listings}\n\\usepackage{subfigure}\n\\usepackage{float}\n\\usepackage{geometry}\n\\usepackage[a4paper]{geometry} % Marges plus larges\n\\geometry{hmargin=2.5cm,vmargin=1.65cm}\n\\usepackage[sectionbib]{chapterbib}\n\n\n\n\\title{TS114 Signal processing \\\\ MICA Project}\n\n\n\n\\author{ABIED Imad \\\\ Email: imad.abied@bordeaux-inp.fr\n\n\\and AHALLI Mohamed \\\\ Email: mohamed.ahalli@bordeaux-inp.fr\n\n\\and BIGI Mohamed \\\\ Email:  mohamed.bigi@bordeaux-inp.fr }\n\n\\date{11/05/2021}\n\n                 \n\\sloppy      \n\n\\begin{document}\n\\maketitle\n\\begin{center}\n    ENSEIRB-MATMECA\n\\end{center}\n\n\\tableofcontents\n\n\\newpage\n\n\\section{Introduction}\n\nThe goal of this project was to analyse signals obtained from measuring heart electrical activity. Such a signal is called electrocardiogram, ECG for short.\nECG respects the pattern described in figure 1. Detecting this pattern consists of identifying the four characteristic points P, Q, R,S and T in each R-R interval from a real ECG signal, as shown in figure 2. The algorithm for this task is presented in the technical part below.\n\n\\begin{figure}[htbp]\n\n\\centerline{\\includegraphics[scale = 0.5]{figure_1.png}}\n\\caption{ECG pattern}\n\n\\centerline{\\includegraphics[scale = 0.3]{figure_2.png}}\n\\caption{Real ECG signal}\n\n\\end{figure}\n\nFurthermore, cardiac pathologies are defined from the PQRST mathematical properties. Therefore, the identification of cardiac pathologies can be automatic. Algorithms for automatic identification are discussed in the technical part of this report.\n\nPQRST mathematical properties can change over time for different reasons. For example, the heart rate increases after doing a physical activity. This is why the spectrogram was used during the project. The spectrogram was employed to understand how ECG characteristics change in the course of time, enabling us to choose the right time interval to apply desired algorithms. For that reason the first section of the technical part is dedicated to spectrograms.\n\n\\section{Data visualization (spectrogram) }\nSpectrograms are used to locally represent the spectrum of a signal. As the spectrum is a statistical measurement, it’s necessary to define the term “locally” by a window of a certain length noted N. The larger the window, the greater frequency precision is obtained at the price of losing time accuracy. Conversely, The shorter window, the greater time accuracy is obtained at the cost of losing frequency precision. This is because there is more data to process in order to establish the spectre, which is a statistical measure. Nevertheless, the spectrum computed by a large window is not “very local\".\n\n\\begin{figure}[H]\n\n\\begin{subfigure}\n\n\\centerline{\\includegraphics[scale = 0.6]{figure_3_large_window.png}}\n\\caption{Spectrogram with a large window.}\n\\end{subfigure}\n\n\\begin{subfigure}\n\n\\centerline{\\includegraphics[scale = 0.2]{figure_4_short_window.png}}\n\\caption{Spectrogram with a short window.}\n\\end{subfigure}\n\n\\end{figure}\n\nThis duality between frequency precision and time accuracy can be shown by the example ./src/duality\\_time\\_frequence.m. In this script the spectrogram of the same signal is plotted using a large window in figure 3 and shorter one in figure 4.\n\nIn figure 3, the yellow line is thin compared to the one in figure 3, facilitating to us the reading of frequency value. On the other hand, it’s very difficult to read the transition at 0.25s in comparison with figure 4.\n\n\\section{QRS complex Detection}\n\nThe QRS complex is going to be detected using the Pan and Tompkins algorithm.The first step of this algorithm eliminates the interference of T and P waves with the QRS complex. A well designed filter is proposed by Pan and Tompkins for this task. Its transfer function is given by :\n\n\\begin{equation}\n    H(z) = \\frac{(1-z^{-6})^{2}}{(1-z^{-1})^{2}}\\times\\frac{(-1 + 32z^{-16} -32z^{-17} +z^{-32})}{(1-z^{-1})}\n\\end{equation}\n\nObserving the fact that the R wave is very sharp,the derivative of the ECG signal is going to take big absolute values at the QRS complex.Pan and Tompkins suggests this time a filter with a transfer function equal to :\n\n\\begin{equation}\n    H(z) = \\frac{1}{8T_s}\\times(-z^{-2} - 2z^{-1} +2z +z^{2})\n\\end{equation}\n\nAs a consequence, if a well chosen window is used for moving window integration,the result will be a signal which takes big values for every QRS complex.\n\nIn order to enhance the QRS complex domain, a thresholding operation is applied with a threshold equal to the mean of ECG signal after integration.\n\nAt this point, it’s certain that the computed maximum for every QRS domain corresponds to the unique pick called R.\n\nOnce the R pick is detected, Q and S are detected by searching consecutively the first minimum on the left and the first minimum on the right.\n\nAll those steps are applied to an ECG signal. The result at every step are plotted in figure 5.\n\n\n\\begin{figure}[htbp]\n\n\\centerline{\\includegraphics[scale = 0.4]{figure_5.png}}\n\\caption{ECG signal in each step.}\n\n\\end{figure}\n\n\\begin{tabular}{ |p{5cm}|p{5cm}|p{5cm}|  }\n\\hline\n\\multicolumn{3}{|c|}{Used filters analyse} \\\\\n\\hline\nband-pass filter &  high-pass filter & five-point differentiation filter\\\\\n\\hline\nNature : band-pass & Nature : high-pass & Nature : differentiation\\\\\nType : Infinite Impulse Response & Type : Infinite Impulse Response & Type : Finite Impulse Response \\\\\nCausal : Yes & Causal : Yes   & Causal : No \\\\\nGroup delay : 5 samples &Group delay : 16.49 samples & Group delay : 0 \\\\\nLinear phase : Yes & Linear phase : Yes & Linear phase : Yes\\\\\n\\hline\n\\end{tabular}\n\n\\newpage\n\n\\section{P and T wave detection}\n\\subsection{About P and T waves}\n\nGenerally, P and T waves in an  ECG (electrocardiogram) signal are lower in amplitude compared to a QRS complex, and, they are contaminated with noise from various sources. These factors make the detection of P and T waves within an ECG a challenging task. Unlike a P wave, T waves are slightly asymmetrical,  the peak of the wave is a little closer to its end than to its beginning.\n\\subsection{P and T waves detection method}\nT waves are considered to be the highest peak between the first R peak and 0.7 times the R-R interval. While P waves have the highest peak in the remaining of the interval, as shown in the figures below.\n\n\\begin{figure}[htbp]\n\n\\centerline{\\includegraphics[scale=0.5]{T_70.png}}\n\\caption{Highest peak on 70\\% of R-R interval.}\n\n\\end{figure}\n\n\\begin{figure}[htbp]\n\n\\centerline{\\includegraphics[scale=0.5]{P_30_30.png}}\n\\caption{Highest peak on the remaining 30\\% of R-R interval.}\n\n\\end{figure}\n\n\nIn order to detect P and T waves, two filters are used:\n \\begin{equation}\n     G_1(z) = 1 -z^{-6}\n \\end{equation}\n \n and\n \n \\begin{equation}\n     G_2(z) = \\frac{1-z^{-8}}{1-z^{-1}}\n \\end{equation}\n \n The first filter \\textit{$G_1(z)$} is a differentiator, it allows the detection of maximum, minimum, as well as null values. This is achieved by determining where the signal, after applying the differentiator \\textit{$G_1(z)$}, crosses the level 0.\n \n The Algorithm functions as follows: The R-R interval is divided into two parts, a part containing 70\\% of the R-R interval, in which T waves are located; and another part containing the remaining 30\\% of the R-R interval, in which P waves are located. In each part, the locations in which the signal (after crossing both filers (\\textit{$G_1(z)$} and (\\textit{$G_2(z)$}) crossed the level 0 were determined. As mentioned before, these locations correspond to either a maximum, minimum, or null values in the original ECG signal. Therefore, the locations that provide a maximum value, are where P and T waves are located.\n \n The figures below illustrate the locations of P and T waves in the original signal,as well as their location after each filter.\n \n\n\n\\begin{figure}[H]\n\\centerline{\\includegraphics[scale=0.5]{ori_sig.png}}\n\\caption{Original ECG with locations of P and T waves}\n\\end{figure}\n\n\\begin{figure}[H]\n\\centerline{\\includegraphics[scale=0.5]{sig_G1.png}}\n\\caption{ECG after undergoing first filter}\n\\end{figure}\n\n\\begin{figure}[H]\n\\centerline{\\includegraphics[scale=0.5]{sig_G2.png}}\n\\caption{ECG after undergoing second filter}\n\\end{figure}\n \n\n\\section{Tachycardia/Bradycardia}\n\n\\subsection{Bradycardia}\n\nBradycardia is defined as a heart rate (HR) of less than 50 or 60 bpm (beats per minute), compared to a normal heart rate of 60 to 100 bpm. A slow heart rate is in general a sign of good health and fitness. However, a heart rate that is too slow (\\textit{ie} Bradycardia ), is a sign of a problem with the heart's electrical system. It means that the heart's natural pacemaker isn't working right or that the electrical pathways of the heart are disrupted. The heart beat can be so slow that it can't pump enough blood for the body. Which could be life-threatening if left untreated.\n\n\\subsection{Tachycardia}\n \nTachycardia is defined as a heart rate (HR) of over 100 bpm (beats per minute). With atrial or supraventricular tachycardia, electrical signals in the heart’s upper chambers fire abnormally. This interferes with the heart’s natural pacemaker, and causes abnormal heart rates. This rapid heartbeat keeps the heart’s chambers from filling completely between contractions, which compromises blood flow to the rest of the body. \n\n\\subsection{Detecting cardiac rhythm anomalies: Tachycardia and Bradycardia}\n\nAn algorithm that calculates the heart rate of a patient, would make it possible to detect cardiac rhythm anomalies. The R waves mark the moment in which the heart beats. Therefore, the duration between consecutive R peaks would help determine the heart rate.\nThe value calculated is:\n\n\\begin{equation}\n    \\overline{\\Delta} = \\frac{1}{N}\\times\\sum_{n=0}^{N-1}\\Delta_n\n\\end{equation}\n\n$\\overline{\\Delta}$ is the mean of R-R intervals duration. It's value was converted to bpm (beats per minute) by multiplying with \\textit{$F_s$} and by 60.\n\n\n\\section{Other pathologies}\n\n\\subsection{Ectopic beats}\nAn ectopic heartbeat is when the heart either skips a beat, or adds an extra beat. They are also called premature heartbeats. Ectopic heartbeats are usually not a cause for concern, and they may occur for no known reason. Despite the skipped or added beat, the heart  functions normally.\n\n\\subsection{Detecting ectopic beats}\n\nDetecting premature heartbeats, comes down to detecting irregularities in R-R intervals, since, as mentioned earlier (\\textit{section 5.3}), R peaks characterize the moment in which the heart beats.\n\nThe algorithm devised, calculated the length of different R-R intervals,and chose their maximum value, since an ectopic beat is placed either to close or too far from a regular beat, either a maximum or a minimum value would have been appropriate.\nBy calculating the same value for normal patients, a threshold $\\epsilon$ was determined as $\\epsilon = 1$.\nThis value (\\textit{\\textbf{max}}) was calculated for different patients, and compared with $\\epsilon$.\nThe results were consistent, \\textit{\\textbf{max}} was Superior to $\\epsilon$ in patients with ectopic beats, and inferior or equal on other cases.\n\n\\section{Fibrillation}\n\n\\subsection{Atrial fibrillation}\n\n\nAtrial fibrillation is characterized by a strong heart rhythm irregularity until the point of considering it as white noise. The main property of a white noise is that its autocorrelation function is null except in zero. That is why autocorrelation function of the studied ECG is estimated with the formula :\n\n\\begin{equation}\n    \\hat{\\gamma_k} = \\frac{1}{N-k-1}\\times\\sum_{n=0}^{N-k-1} (\\Delta_{n+k} - \\overline{\\Delta})(\\Delta_{n} - \\overline{\\Delta})\n\\end{equation}\n\n\\begin{figure}\n\\centerline{\\includegraphics[scale=0.4]{figure_6_edge_effect.png}}\n\\caption{Edge effect.}\n\\end{figure}\n\nFigure 11 is an example of an estimated autocorrelation function. At the right of the figure, big random values are remarked because, in this area,the autocorrelation is estimated using a small number of samples so the mean is not representative enough. For that reason, the studied domain of the autocorrelation function is not going to include the values at the right edge.\n\nThe heart rhythm is going to be considered as a white noise if 40\\% of its autocorrelation function at zero is still a maximum of the autocorrelation function.\n\n\\subsection{Ventricular fibrillation}\n\nVentricular fibrillation, or V-fib, is considered the most serious cardiac rhythm disturbance.\nDisordered electrical activity causes the heart’s lower chambers (ventricles) to quiver, or fibrillate, instead of contracting (or beating) normally. This prohibits the heart from pumping blood. Thus leading to collapse and cardiac arrest\n\n\\subsection{Detecting ventricular fibrillation}\n\nTwo main properties are used to detect Ventricular fibrillation: The similarity between the ECG (electrocardiogram) of the patient and the pure sine; as well as a rapid heart rate between 240 and 600 bpm (beats per minute).\nThe similarity between Ventricular fibrillation ECG and the pure sine function was detected by resorting to the Fourier transform. Plotting the two Fourier transforms, illustrates the similarity between them, as shown below.\n\\textbf{N.B: FT = Fourier transform}\n\n\\newpage\n\n\\begin{figure}\n\\centerline{\\includegraphics[scale=0.6]{Fourrier_VF.png}}\n\\caption{TF of ECG}\n\\end{figure}\n\\begin{figure}\n\\centerline{\\includegraphics[scale=0.6]{sin_fou.png}}\n\\caption{TF of sine}\n\\end{figure}\n\n\\newpage\n\nThe FT are similar, with two important peaks at symmetric values of frequency. In order to detect the two peaks,  a threshold was applied to the FT,in order to calculate the number of values superior to $0.8\\times\\textit{n}$; where \\textit{n} is the maximum value of the FT. An ECG with a ventricular fibrillation generally has a low number of values above  $0.8\\times\\textit{n}$, compared to other ECGs, combining this with the condition of a heart rate between 240 and 600 bpm, a case of ventricular fibrillation can be determined\n\n\n\n\n\\section{Conclusion}\nThis report has discussed the implementation of algorithms used to detect PQRST waves and automatic heart pathology identification. Besides that, it has introduced the utility of spectrograms as well as their limitations. The results obtained were satisfying. However, we really wished to develop a graphic user interface to make our work valuable but we could not because we did not have enough time.\n\n\\newpgae\n\n\\begin{thebibliography}{2} \n   \\bibitem[1]{cle} P and T waves https://pubmed.ncbi.nlm.nih.gov/29484531/\n   \\bibitem[2]{cle} Bradycardia   https://www.uofmhealth.org/health-library/aa107571\n   \\bibitem[3]{cle} tachy https://pubmed.ncbi.nlm.nih.gov/29484531/\n   \\bibitem[4]{cle} ectopic https://www.medicalnewstoday.com/articles/323202#what-is-an-ectopic-heartbeat\n   \\bibitem[5]{cle} Ventr fibr https://www.heart.org/en/health-topics/arrhythmia/about-arrhythmia/ventricular-fibrillation\n   \n\\end{thebibliography} \n\n\\end{document}\n\n\n", "meta": {"hexsha": "7017a890a53923ad8b0b4d7f843a8bca1267d6fa", "size": 15119, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "documents/Report_LaTeX/main.tex", "max_stars_repo_name": "ImadABID/MICA_Project", "max_stars_repo_head_hexsha": "892f46ac33c5b2abb495c49768003642d6bf982d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "documents/Report_LaTeX/main.tex", "max_issues_repo_name": "ImadABID/MICA_Project", "max_issues_repo_head_hexsha": "892f46ac33c5b2abb495c49768003642d6bf982d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "documents/Report_LaTeX/main.tex", "max_forks_repo_name": "ImadABID/MICA_Project", "max_forks_repo_head_hexsha": "892f46ac33c5b2abb495c49768003642d6bf982d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.2508474576, "max_line_length": 621, "alphanum_fraction": 0.7722732985, "num_tokens": 3836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.3492906531479197}}
{"text": "% Template file for TeXShop by Michael Sharpe, LPPL\n\\documentclass[11pt]{article} \n\\usepackage[margin=0.9in]{geometry} \n\\usepackage[parfill]{parskip}% Begin paragraphs with an empty line rather than an indent\n\\usepackage{graphicx}\n\\usepackage{amsmath,amsthm}\n\\usepackage{natbib}\n\n\\title{MIT 6.862 Applied Machine Learning \\\\ Project Progress Report}\n\\author{Matthew West, Fall 2019}\n\\begin{document}\n\\date{}\n\\maketitle\n\n\\section{Introduction}\nThis is the progress report for my MIT course 6.862 project, which aims to explore classification in the context of medical diagnosis, and specifically in datasets derived from images of breast cancer. The focus thus far has been on the establishment of a data pipeline and exploratory data analysis, before comparing multiple candidate machine learning models on the basis of classification accuracy.\n\nThis report focuses on the Wisconsin Breast Cancer dataset, \\cite{Dua:2019} an analysis of which first appeared in Street et al., which used a decision tree-based algorithm to classify the data with approximately 97\\% accuracy. \\cite{street1993nuclear, mangasarian1993mathematical} As outlined in the proposal, it was decided that comparison between traditional machine learning on structured data derived from images and the raw images themselves was a desirable direction to take the project in. To this end, I have contacted an original author of this paper in an attempt to acquire the corresponding raw images, though this has not proved fruitful as of yet. There remains the option to extend the analysis to further datasets outlined in the proposal, though such a comparison still won't be straightforward and will introduce substantial roadblocks in the form of data extraction and image segmentation. \n\nThe report is structured as follows: Following this introduction, an account of the progress so far will be given regarding the data, methods, results, and discussion, followed by a brief outline of what will be done with the time remaining, and outlining a specific plot that will appear in the final report.\n\n\\section{Progress}\n\\subsection{Data}\nThe data used in the initial portion of the project thus far is the Wisconsin Breast Cancer dataset, collected by a team at the University of Wisconsin-Madison in the early 1990's. The dataset uses features derived from a set of fine-needle aspirate (FNA) images of breast tissue in patients with either malignant or benign tumours. It is a structured dataset with 569 instances and 30 features, an ID number, and a label, with 212 malignant examples and 357 benign examples. There are 10 base features (radius, texture, perimeter, area, smoothness, compactness, concavity, concave points, symmetry, fractal dimension), and for each of these the mean, standard error, and largest/worst example of these features are included over each image, resulting in 30 features in total. \n\nThe dataset was checked for missing values, before dropping a non-explanatory ID column, an unexplained column of all NaN values, and separating the labels from the feature vectors.\n\n\n\\subsection{Method}\n\nThe machine learning problem at hand is one of classification. If we denote our hypothesis by $\\text{h}(x; \\lambda)$ where the feature vector for each tumour instance is denoted as $x^{(i)}$ and $\\lambda$ denotes a specific vector of parameters that determine a hypothesis, our problem is to identify the optimal $\\lambda$ subject to minimising\n\n$$\\frac{1}{n}\\sum_{i=1}^{n} L(\\text{h}(x; \\lambda), y^{(i)}),$$\n\nwhere $L(g, a)$ is the loss function chosen for a given algorithm, providing a measure of how far away the guess from the hypothesis $g$ is from the actual instance label, $a$. Specifically, this will be evaluated using 5-fold cross validation, as minimising training error will not be a relevant or interesting metric. Selected hypotheses from many such algorithms will be compared to see which of these minimises validation error and is therefore the preferred model in terms of classification accuracy. Multiple algorithms have been investigated so far, with promising results from xgboost, naive Bayes and logistic regression, as seen in table \\ref{table:1}. These were mainly implemented using scikit-learn in Python 3 on my local machine.\n\nA principle component decomposition was done on the dataset, allowing 2 or 3 principle components to represent a substantial portion of the variation across all 30 features. This allows for an intuitive understanding of how separable the dataset is, as two or three principle components can be plotted and understood visually, something that isn't readily doable for higher dimensional data. It is also possible to directly train and test models on the principle component representation of the data, though one loses the interpretability for which features are most important in predicting the outcome variable.\n\n\\subsection{Results}\nThe first result was, having used PCA to represent the data in both 2 and 3 dimensions, it was confirmed that the dataset would be somewhat separable, if not perfectly linearly separable. This was achieved by confirming that the PCA plots showed natural clusters of malignant and benign instances in the reduced latent space.\n\nFurthermore, it was determined preliminarily that tree-based methods such as xgboost are performing better than other algorithms, with xgboost consisently obtaining 96\\% classification accuracy without too much parameter tuning or feature selection. An additional bonus of using tree-based methods is that they allow some quantitative insight into which features are most important in classification, which appear to be those derived from texture and concave points.\n\n\\begin{table}[h!]\n\t\\centering\n\t\\begin{tabular}{ |c|c|c|c| } \n\t\t\\hline\n\t\tAlgorithm & 5-fold accuracy set & 5-fold accuracy ($\\%$) \\\\\n\t\t\\hline\n\t\t\\textbf{xgboost}\t& [0.930, 0.957, 0.992, 0.965, 0.973] & $96\\pm2$ \\\\ \n\t\t\\textbf{Naive Bayes} & [0.922, 0.922, 0.956 0.947, 0.956] & $94\\pm2$ \\\\ \n\t\t\\textbf{Logistic regression} & [0.930, 0.939, 0.973, 0.947, 0.965] & $95\\pm2$ \\\\\n\t\t\\hline\n\t\\end{tabular}\n\\caption{Table of cross-validated results from selected classification algorithms}\n\\label{table:1}\n\\end{table}\n\n\n\\subsection{Discussion}\nGetting rather good results using default hyperameters can be straightforward for some datasets. Marginal performance increases then come from the selection of algorithms together with the set of hyperparameters tuned for that algorithm. Without exploring this vast solution space comprehensively, it has still been possible to obtain classification accuracies close to that initial benchmark described in the orginal paper. One insight that has helped to overcome the `noise' associated with the accuracy metric across this solution space was the decision to use 5-fold cross validation when investigating accuracy.\n\nA key lesson learnt thus far was how to think about exploratory data analysis in a systematic way, such as by using PCA to represent the data. This paralleled nicely with the content covered in class on autoencoders, but simplifying it to a linear combination of original features. This has allowed me to abstract conceptually from thinking about raw features to latent spaces, which is an invaluable tool in applied machine learning. \n\n\n\\section{Looking Ahead}\nAn outline for the next month leading up to the conclusion of the project is given in this section.\n\\begin{itemize}\n\t\\item An investigation into precision and recall. In the context of medical diagnostics, the use of machine learning algorithms is controversial due to the direct impact of such diagnostics on human survival. Therefore, perhaps unlike many other domains in which machine learning is applied, special consideration must be given to precision and recall, as false positives are in general much less serious than false negatives. This presents a different set of potential metrics, and some of these will be investigated to see if a different algorithm is preferred when we take the domain-specific selection of metric into account. Deadline: 11/14\n\t\\item It will hopefully be possible to acquire a set or perhaps representative subset of the original Wisconsin Breast Cancer images from the researchers that first collected this data. If this is the case, then the focus of this milestone will be to investigate the use of convolutional neural networks (CNN's) on these raw images, and compare performance on any relevant metrics. It is of particular interest to me to see if there are advantages to using CNN's in the small dataset regime, despite not expecting a substantial increase in resultant accuracy (e.g. interpretability, automated feature extraction). I identified this as ``time-allowing\" in the project proposal because of the potential time commitment of pre-processing these larger datasets for use in CNN's and also deriving structured datasets from these similar in form to the Wisconsin dataset, for the purposes of making this comparison. Deadline: 12/01\n\\end{itemize}\n\n\\section{Projected Results Section}\nThe key result of this initial stage of the project will be a comparison of accuracies on the Wisconsin dataset using one model for each of the algorithms selected for comparison, by means of a violinplot or boxplot. The horizontal axis will be discrete in the different algorithms, and the vertical axis will be classification accuracy.\n\nEach of these models will have been tuned to select the optimal set of any relevant hyperparameters, using 5 or 10-fold cross-validation. This plot allows the reader to assess visually which algorithm performs better on this dataset, as well as how much variance there is in each estimate of accuracy across the set of folds used for validation. I envision including a set of similar figures that concern performance not just in terms of accuracy, but also on other metrics that take into account sensitivity and specificity.\n\\nocite{*}\n\\bibliographystyle{plain}\n\\bibliography{MIT}\n\n\\end{document}", "meta": {"hexsha": "d845928bf8f4b680245cc4c77093753a99f7ff1b", "size": 9965, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Project/Progress Report/Progress_Report.tex", "max_stars_repo_name": "mwestt/MIT-6.862", "max_stars_repo_head_hexsha": "76e0c15898667ff5c05bfae38f7431cc6e0cff7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Project/Progress Report/Progress_Report.tex", "max_issues_repo_name": "mwestt/MIT-6.862", "max_issues_repo_head_hexsha": "76e0c15898667ff5c05bfae38f7431cc6e0cff7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Project/Progress Report/Progress_Report.tex", "max_forks_repo_name": "mwestt/MIT-6.862", "max_forks_repo_head_hexsha": "76e0c15898667ff5c05bfae38f7431cc6e0cff7c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-18T02:22:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T02:22:00.000Z", "avg_line_length": 123.024691358, "max_line_length": 925, "alphanum_fraction": 0.8031108881, "num_tokens": 2141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.3492906531479197}}
{"text": "%2multibyte Version: 5.50.0.2960 CodePage: 65001\r\n\r\n\\documentclass{article}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\usepackage{amsmath}\r\n\r\n\\setcounter{MaxMatrixCols}{10}\r\n%TCIDATA{OutputFilter=LATEX.DLL}\r\n%TCIDATA{Version=5.50.0.2960}\r\n%TCIDATA{Codepage=65001}\r\n%TCIDATA{<META NAME=\"SaveForMode\" CONTENT=\"1\">}\r\n%TCIDATA{BibliographyScheme=Manual}\r\n%TCIDATA{Created=Monday, November 30, 2015 16:55:25}\r\n%TCIDATA{LastRevised=Wednesday, December 09, 2015 17:26:48}\r\n%TCIDATA{<META NAME=\"GraphicsSave\" CONTENT=\"32\">}\r\n%TCIDATA{<META NAME=\"DocumentShell\" CONTENT=\"Standard LaTeX\\Blank - Standard LaTeX Article\">}\r\n%TCIDATA{CSTFile=40 LaTeX article.cst}\r\n\r\n\\newtheorem{theorem}{Theorem}\r\n\\newtheorem{acknowledgement}[theorem]{Acknowledgement}\r\n\\newtheorem{algorithm}[theorem]{Algorithm}\r\n\\newtheorem{axiom}[theorem]{Axiom}\r\n\\newtheorem{case}[theorem]{Case}\r\n\\newtheorem{claim}[theorem]{Claim}\r\n\\newtheorem{conclusion}[theorem]{Conclusion}\r\n\\newtheorem{condition}[theorem]{Condition}\r\n\\newtheorem{conjecture}[theorem]{Conjecture}\r\n\\newtheorem{corollary}[theorem]{Corollary}\r\n\\newtheorem{criterion}[theorem]{Criterion}\r\n\\newtheorem{definition}[theorem]{Definition}\r\n\\newtheorem{example}[theorem]{Example}\r\n\\newtheorem{exercise}[theorem]{Exercise}\r\n\\newtheorem{lemma}[theorem]{Lemma}\r\n\\newtheorem{notation}[theorem]{Notation}\r\n\\newtheorem{problem}[theorem]{Problem}\r\n\\newtheorem{proposition}[theorem]{Proposition}\r\n\\newtheorem{remark}[theorem]{Remark}\r\n\\newtheorem{solution}[theorem]{Solution}\r\n\\newtheorem{summary}[theorem]{Summary}\r\n\\newenvironment{proof}[1][Proof]{\\noindent\\textbf{#1.} }{\\ \\rule{0.5em}{0.5em}}\r\n\\input{tcilatex}\r\n\\begin{document}\r\n\r\n\r\n\\subsection{Model Assumptions}\r\n\r\nThe world economy is composed of $N$ countries. At a given point in time $t$%\r\n, each country $n$ is endowed with $L_{nt}$ units of a primary (non\r\nproduced) input, which we interpret as equipped labour. There are $J$\r\nsectors (or broad classes of goods) in the economy, whose output is combined\r\ninto a final good through a Cobb-Douglas aggregate. In formulas, aggregate\r\ngross output in the economy is given by: \r\n\\begin{equation}\r\nQ_{nt}=\\prod_{j=1}^{J}\\left( Q_{nt}^{j}\\right) ^{\\alpha ^{j}}\r\n\\label{aggregate}\r\n\\end{equation}%\r\nwhere $Q_{t}^{j}$ is the gross output in sector $j$ and $\\sum_{j=1}^{J}%\r\n\\alpha ^{j}=1$. Competitive firms in each sector $j$ produce a composite\r\ngood according to the following constant-elasticity-of-substitution (CES)\r\ntechnology: \r\n\\begin{equation}\r\nQ_{nt}^{j}=\\left[ \\int_{0}^{1}q_{nt}(\\omega ^{j})^{\\frac{\\eta -1}{\\eta }%\r\n}d\\omega ^{j}\\right] ^{\\frac{\\eta }{\\eta -1}}  \\label{sectoroutput}\r\n\\end{equation}%\r\nwhere $q_{nt}(\\omega ^{j})$ is the quantity of good $\\omega ^{j}$ used by\r\ncountry $n$ in sector $j$ at time $t$, and $\\eta >0$ is the elasticity of\r\nsubstitution across goods within a given sector. The intermediate goods $%\r\n\\omega ^{j}$ can be produced locally or imported from other countries.\r\nDelivering a good from country $n$ to country $m$ in sector $j$ and time\r\nperiod $t$ results in $0<\\kappa _{mnt}^{j}\\leq 1$ goods arriving at $m$; we\r\nassume that $\\kappa _{mnt}^{j}\\geq \\kappa _{mkt}^{j}\\kappa _{knt}^{j}\\quad\r\n\\forall m,n,k,j,t$ and $\\kappa _{nnt}^{j}=1$. All costs incurred are net\r\nlosses.\\footnote{%\r\nIn the calibration, the $\\kappa $s will reflect all trading costs, including\r\ntariffs; so implicitly we adopt the extreme assumption that tariff revenues\r\nare wasted---or at least not rebated back to agents in a way that would\r\ninteract with the allocation of resources in the economy.} Under the\r\nassumption of perfect competition, goods are sourced from the lowest-cost\r\nproducer, after adjusting for transport costs. The technology for producing $%\r\nq_{nt}(\\omega ^{j})$ is given accordingly by the country of origin ($m$)\r\nwith the lowest cost (with $m=n$ when the good is produced locally): \r\n\\begin{equation}\r\nx_{mt}(\\omega ^{j})=A_{mt}^{j}z_{m}(\\omega ^{j})l_{mt}(\\omega ^{j})^{\\beta\r\n^{j}}M_{mt}(\\omega ^{j})^{1-\\beta ^{j}}\r\n\\end{equation}%\r\nwhere $x_{mt}(\\omega ^{j})$ is the production of good $\\omega ^{j}$ by\r\ncountry $m$ at time $t$, $M_{mt}(\\omega ^{j})$ is the amount of the\r\naggregate composite good used by country $m$ to produce $x_{mt}(\\omega ^{j})$\r\nunits of good $\\omega ^{j}$ and $l_{mt}(\\omega ^{j})$ is the corresponding\r\namount of equipped labour. Total factor productivity (TFP) levels vary\r\nacross countries, sectors, and goods. Specifically, each intermediate good $%\r\n\\omega ^{j}$ in sector $j$ of country $n$ has a time-invariant idiosyncratic\r\nproductivity factor $z_{n}(\\omega ^{j})$ and a time-varying factor $%\r\nA_{nt}^{j}$ common to all the goods $\\omega ^{j}$ in sector $j$. Building on\r\nthe literature, we assume the productivities $z_{n}(\\omega ^{j})$ follow a\r\nsector-specific, time-invariant Fr\\'{e}chet distribution $F_{n}^{j}(z)=\\exp\r\n(-T_{n}^{j}z^{-\\theta })$. A higher $T_{n}^{j}$ shifts the distribution of\r\nproductivities to the right, that is leading to probabilistically higher\r\nproductivities. A higher $\\theta $ decreases the dispersion of the\r\nproductivity distribution, and hence reduces the scope for comparative\r\nadvantage. Shocks to $A_{nt}^{j}$ over time are interpreted as standard\r\nsectoral total factor productivity (TFP) shocks.\r\n\r\nThe single final good can be used both as input in the production of\r\nintermediaries $\\omega^{j}$ or for final consumption, $C_{nt}$. Hence,\r\nmarket clearing in the good markets implies: \r\n\\begin{equation*}\r\nQ_{nt} = C_{nt} + \\sum_{j=1}^{J}\\int_{0}^{1}M_{nt}(\\omega^{j})d\\omega ^{j}, \r\n\\end{equation*}\r\nwhere the integral aggregates over the unit-size continuum of goods $%\r\n\\omega^{j}$ entering in the production of each sector's $j$ aggregate good.\r\n\r\nClearing in the input market within a sector implies: \r\n\\begin{equation*}\r\nL_{nt}^{j}=\\int_{0}^{1}l_{nt}(\\omega ^{j})d\\omega ^{j}, \r\n\\end{equation*}%\r\nwhere $l_{nt}(\\omega ^{j})$ denotes the amount of equipped labour used in\r\nthe production of good $\\omega ^{j}$ by country $n$. We assume there is\r\nperfect risk-sharing within a country, but no risk-sharing across countries.%\r\n\\footnote{%\r\nTo motivate the lack of risk-sharing across countries, see our discussion of\r\nFigures 1 and 2.} The (equipped) labour shares allocated to each sector, $%\r\nL_{nt}^{j}/L_{nt},$ with $\\sum\\nolimits_{k=1}^{J}L_{nt}^{k}=L_{nt}$, are\r\ndetermined ex ante (before the realization of the shocks), but can be\r\nadjusted ex-post, at an adjustment cost. At the beginning of each period, a\r\nrepresentative consumer decides on the ex-ante optimal allocation of the\r\nprimary input $L_{nt}$ into different sectors in order to maximize the\r\nexpected value of utility. Then (stochastic) shocks to productivity $%\r\nA_{nt}^{j}$ are realized; equipped labour is reallocated freely within a\r\nsector, while reallocation across sectors implies a disutility cost $%\r\n\\Upsilon .$ Production and consumption take place. The disutility cost of\r\nex-post reallocation across sectors aims at capturing the idea that in the\r\nshort run, it is costly to reallocate productive factors across sectors.\r\n\r\nThe representative consumer's budget constraint in each period is: \r\n\\begin{equation*}\r\nP_{nt}C_{nt}=\\sum_{j=1}^{J}w_{nt}^{j}L_{nt}^{j}, \r\n\\end{equation*}%\r\nwhere $P_{nt}$ is the price of the aggregate good (\\ref{aggregate}), $%\r\nw_{nt}^{j}L_{nt}^{j}$ is the nominal value-added generated in sector $j$.\r\nLifetime utility is given by \r\n\\begin{equation*}\r\nU_{n}=\\sum\\limits_{t=0}^{\\infty }\\delta ^{t}u(C_{nt})+\\Upsilon , \r\n\\end{equation*}%\r\nwhere $u^{\\prime }>0$, $u^{\\prime \\prime }\\leq 0$ and $\\delta $ is the\r\ndiscount factor and $\\Upsilon $ is the sum of quadratic deviations of\r\nsectoral shares from the original sectoral allocation. The cost $\\Upsilon $\r\nis relevant ex-post, when consumers need to reallocate inputs across\r\nsectors. Ex ante, however, the optimal allocation is such that the expected\r\nadjustment costs will be zero. Because there is no intertemporal trade and\r\nno capital in the economy, and given that input shares ex ante will equal\r\nthe expected optimal allocation, each period consumers maximize the expected\r\nstatic utility flow $E\\left[ u\\left( C_{nt}\\right) \\right] $ and the\r\nequilibrium is simply a sequence of static equilibria. In making his labor\r\nallocation decisions the representative consumer takes into account the\r\njoint probability distribution function of sectoral productivities, $%\r\nA_{nt}^{j}$s.\r\n\r\nIn the analysis, we assume log utility and therefore the consumer solves: \r\n\\begin{equation}\r\nL_{nt}^{k\\ast }=\\arg \\max E_{t-1}\\left[ \\ln \\left( \\frac{%\r\n\\sum_{j=1}^{J}w_{nt}^{j}L_{nt}^{j}}{P_{nt}}\\right) \\right]\r\n,s.t.:\\sum\\nolimits_{j=1}^{J}L_{nt}^{j}=L_{nt},  \\label{eq:log:utility}\r\n\\end{equation}%\r\nwhere $E_{t-1}$ indicates that the expectation is taken before the\r\nrealization of period $t$ shocks. This\\ maximization problem leads to the\r\nfollowing first-order conditions for the ex-ante allocation of inputs to\r\nsectors: \r\n\\begin{equation}\r\n\\psi _{nt}^{k\\ast }=\\frac{L_{nt}^{k\\ast }}{L_{nt}}=E_{t-1}\\left[ \\frac{%\r\nw_{nt}^{k}L_{nt}^{k}}{\\sum_{k}w_{nt}^{k}L_{nt}^{k}}\\right] ,\\qquad \\forall\r\nk,t.  \\label{eq:FOC}\r\n\\end{equation}%\r\nIn words, the share of resources allocated ex ante to a given sector equals\r\nits expected share in value added. To gain intuition on this expression note\r\nthat $1/\\sum_{k}w_{nt}^{k}L_{nt}^{k}$ is the marginal utility of consumption\r\nin period $t$; thus, more resources are allocated to higher value-added\r\nsectors, after appropriately weighting by marginal utility. Consider, for\r\nfurther intuition, a (small) sector whose productivity is negatively\r\ncorrelated with the rest of the economy (that is, it has high value added\r\nwhen the rest of the economy has low value added); in states of the world in\r\nwhich overall income is low, the marginal utility of consumption $%\r\n1/\\sum_{k}w_{nt}^{k}L_{nt}^{k}$ will be high and hence the optimal\r\nallocation entails allocating more resources to this sector. In the closed\r\neconomy, the value-added share is pinned down by the Cobb--Douglas\r\ncoefficients $\\alpha ^{j}\\beta ^{j}$, as with Cobb-Douglas technology there\r\nis no variation on expenditures (and sales) shares---and log-utility implies\r\nthe shares determine the sectoral allocation of resources. In the open\r\neconomy this result no longer holds as a country's sectoral shares depend on\r\nits absolute and comparative advantage as well as trading costs vis-\\`{a}%\r\n-vis other countries.\r\n\r\nEx post, as said, labour can potentially be reallocated after incurring the\r\najustment costs. The ex-post sectoral input allocation solves:\r\n\r\n\\begin{equation}\r\nL_{nt}^{k}=\\arg \\max \\left[ \\ln \\left( \\frac{%\r\n\\sum_{j=1}^{J}w_{nt}^{j}L_{nt}^{j}}{P_{nt}}\\right) +\\frac{\\varrho }{2}%\r\n\\sum_{j=1}^{J}\\left[ \\psi _{nt}^{j}-\\psi _{nt}^{j\\ast }\\right] ^{2}\\right] ,%\r\n\\text{ }s.t.:\\sum\\nolimits_{j=1}^{J}L_{nt}^{j}=L_{nt}\r\n\\end{equation}%\r\nwith $\\psi _{nt}^{j}\\equiv \\frac{L_{nt}^{j}}{L_{nt}}$ and $%\r\n\\sum_{j=1}^{J}\\psi _{nt}^{j}=\\sum_{j=1}^{J}\\psi _{nt}^{j\\ast }=1.$ The first\r\norder conditions satisfy%\r\n\\begin{equation}\r\n\\frac{w_{nt}^{k}}{\\sum_{j=1}^{J}w_{nt}^{j}L_{nt}^{j}}+\\varrho \\left[ \\psi\r\n_{nt}^{k}-\\psi _{nt}^{k\\ast }\\right]/L_{nt} =\\lambda\r\n\\end{equation}%\r\nwhere $\\lambda $ is given by $\\lambda =\\frac{\\frac{1}{J}%\r\n\\sum_{j=1}^{J}w_{nt}^{j}}{\\sum_{j=1}^{J}w_{nt}^{j}L_{nt}^{j}}$ and hence\r\n\r\n\\begin{equation*}\r\n\\psi _{nt}^{k}=\\psi _{nt}^{k\\ast }+\\frac{1}{\\varrho }\\left[ \\frac{\\frac{1}{J}%\r\n\\sum_{j=1}^{J}w_{nt}^{j}-w_{nt}^{k}}{\\sum_{j=1}^{J}w_{nt}^{j}L_{nt}^{j}/L_{nt}}%\r\n\\right] \r\n\\end{equation*}%\r\nIn words, the ex post input shares $\\psi _{nt}^{k}$ equal the ex-ante\r\noptimal shares $\\psi _{nt}^{k\\ast }$ plus a fraction of the percentage differential\r\nbetween the average equipped labour cost in the economy $\\frac{1}{J}%\r\n\\sum_{j=1}^{J}w_{nt}^{j}$ and the sectoral input cost $w_{nt}^{k}$. \r\n(Note that the denominator is the average input cost in the economy.)\r\nThe\r\nadjustment cost parameter $\\varrho $ determines the elasticity of sectoral\r\nadjustment to the cost differential. In the extreme, when adjustment costs\r\nare infinite, $\\varrho \\rightarrow \\infty $, the economy simply stays at the\r\ninitial sectoral input shares $\\psi _{nt}^{k}=\\psi _{nt}^{k\\ast }$. As\r\nadjustment costs decrease, the sectoral shares adjust in response to the\r\ncost differential.\r\n\r\n\\bigskip\r\n\r\nPAUSE\r\n\r\n\\subsection{Model Solution}\r\n\r\nWe first discuss the solution under autarky, and then turn to the solution\r\nunder free trade.\r\n\r\n\\paragraph{Solution under Autarky}\r\n\r\nWe solve the model backwards in two stages. First, we solve the model taking\r\nthe sectoral allocation of nonproduced inputs $L_{t}^{j}$ as fixed. We then\r\nsolve for the ex-ante optimal $L_{t}^{j\\prime }s$ before the shocks are\r\nrealized. In the analysis of the autarky case, we omit the country-specific\r\nsubscripts $n$ for convenience.\r\n\r\nThe demand for each sector's composite good is given by \r\n\\begin{equation}\r\nQ_{t}^{j}=\\alpha _{t}^{j}\\left( \\frac{P_{t}^{j}}{P_{t}}\\right) ^{-1}Q_{t},\r\n\\label{QJ}\r\n\\end{equation}%\r\nand the demand for each intermediate good $\\omega ^{j}$ is \r\n\\begin{equation*}\r\nq_{t}(\\omega ^{j})=\\left[ \\frac{p_{t}(\\omega ^{j})}{P_{t}^{j}}\\right]\r\n^{-\\eta }Q_{t}^{j}, \r\n\\end{equation*}%\r\nwhere \r\n\\begin{equation}\r\nP_{t}^{j}=\\left[ \\int_{0}^{1}p_{t}(\\omega ^{j})^{1-\\eta }d\\omega ^{j}\\right]\r\n^{\\frac{1}{1-\\eta }}  \\label{PJ}\r\n\\end{equation}%\r\nis the aggregate price index in sector $j$, and the economy-wide price index\r\nis given by: \r\n\\begin{equation}\r\nP_{t}=\\prod_{j=1}^{J}\\alpha _{t}^{j^{-\\alpha _{t}^{j}}}\\left(\r\nP_{t}^{j}\\right) ^{\\alpha _{t}^{j}}.  \\label{Pt}\r\n\\end{equation}%\r\nThe demand for non-produced inputs $l_{t}(\\omega ^{j})$ and produced inputs $%\r\nM_{t}(\\omega ^{j})$ are given, respectively, by $l_{t}^{j}(\\omega\r\n^{j})=\\beta ^{j}\\frac{p_{t}(\\omega ^{j})q_{t}(\\omega ^{j})}{w_{t}^{j}}$ and $%\r\nM_{t}(\\omega ^{j})=(1-\\beta ^{j})\\frac{p_{t}(\\omega ^{j})q_{t}(\\omega ^{j})}{%\r\nP_{t}}.$ Aggregating over all goods $\\omega ^{j}$ in a given sector, we\r\nobtain \r\n\\begin{equation}\r\nw_{t}^{j}L_{t}^{j}=\\beta ^{j}P_{t}^{j}Q_{t}^{j}  \\label{Labor share}\r\n\\end{equation}%\r\nand, correspondingly, $P_{t}M_{t}^{j}=(1-\\beta ^{j})P_{t}^{j}Q_{t}^{j}.$\r\nLabour shares are given by:\r\n\r\n\\begin{equation*}\r\n\\frac{L_{t}^{j}}{L_{t}}=\\psi _{nt}^{k}=\\psi _{nt}^{k\\ast }+\\frac{1}{\\varrho }%\r\n\\left[ \\frac{\\frac{1}{J}\\sum_{j=1}^{J}w_{nt}^{j}-w_{nt}^{k}}{%\r\n\\sum_{j=1}^{J}w_{nt}^{j}L_{nt}^{j}}\\right] \r\n\\end{equation*}%\r\nand the initial labour allocation, $\\psi _{nt}^{k\\ast }$, is taken as given.\r\n\r\nUsing the input demand functions and the zero profit condition the autarky\r\nprices of intermediate goods are given by: \r\n\\begin{equation}\r\np_{t}(\\omega ^{j})=B^{j}\\left[ A_{t}^{j}\\cdot z(\\omega ^{j})\\right]\r\n^{-1}\\left( w_{t}^{j}\\right) ^{\\beta ^{j}}P_{t}^{1-\\beta ^{j}},\r\n\\label{Frechet}\r\n\\end{equation}%\r\nwhere $B^{j}=$ $\\left( \\beta ^{j}\\right) ^{-\\beta ^{j}}(1-\\beta\r\n^{j})^{-(1-\\beta ^{j})}$. Using (\\ref{Frechet}) and the properties of the Fr%\r\n\\'{e}chet distribution, we can express the sectoral price index as: \r\n\\begin{equation}\r\nP_{t}^{j}=\\xi B^{j}\\left[ A_{t}^{j}\\cdot \\left( T^{j}\\right) ^{\\frac{1}{%\r\n\\theta }}\\right] ^{-1}\\left( w_{t}^{j}\\right) ^{\\beta ^{j}}P_{t}^{1-\\beta\r\n^{j}}\r\n\\end{equation}%\r\nwhere $\\xi =\\left[ \\Gamma \\left( \\frac{\\theta +1-\\eta }{\\theta }\\right) %\r\n\\right] ,$ and $\\Gamma $ is the gamma function.\r\n\r\nUsing (\\ref{QJ}), (\\ref{Labor share}), and (\\ref{Pt}) we obtain real GDP:\r\n\r\n\\begin{eqnarray*}\r\nY_{t} &=&\\sum_{j=1}^{J}\\frac{w_{t}^{j}L_{t}^{j}}{P_{t}}=\\sum_{j=1}^{J}\\beta\r\n^{j}\\frac{P_{t}^{j}Q_{t}^{j}}{P_{t}}=\\sum_{j=1}^{J}\\beta ^{j}\\alpha\r\n_{t}^{j}Q_{t} \\\\\r\n\\text{since }w_{t}^{j}L_{t}^{j} &=&\\beta ^{j}P_{t}^{j}Q_{t}^{j}=\\beta\r\n^{j}\\alpha _{t}^{j}P_{t}Q_{t} \\\\\r\nQ_{t} &=&\\frac{1}{\\alpha _{t}^{j}\\beta ^{j}}\\frac{w_{t}^{j}}{P_{t}}L_{t}^{j}\r\n\\\\\r\n\\text{and since }\\frac{w_{t}^{j}}{P_{t}} &=&\\left( \\xi B^{j}\\right)\r\n^{-1/\\beta ^{j}}\\left[ A_{t}^{j}\\cdot \\left( T^{j}\\right) ^{\\frac{1}{\\theta }%\r\n}\\right] ^{1/\\beta ^{j}}\\left( \\frac{P_{t}^{j}}{P_{t}}\\right) ^{\\frac{1}{%\r\n\\beta ^{j}}}\r\n\\end{eqnarray*}%\r\nWe hence obtain%\r\n\\begin{eqnarray*}\r\nQ_{t} &=&\\left( \\xi B^{j}\\right) ^{-1/\\beta ^{j}}\\left[ A_{t}^{j}\\cdot\r\n\\left( T^{j}\\right) ^{\\frac{1}{\\theta }}\\right] ^{1/\\beta ^{j}}\\left( \\frac{%\r\nP_{t}^{j}}{P_{t}}\\right) ^{\\frac{1}{\\beta ^{j}}}\\frac{1}{\\alpha\r\n_{t}^{j}\\beta ^{j}}L_{t}^{j} \\\\\r\n\\frac{P_{t}^{j}}{P_{t}} &=&\\left( \\xi B^{j}\\right) \\left[ A_{t}^{j}\\cdot\r\n\\left( T^{j}\\right) ^{\\frac{1}{\\theta }}\\right] ^{-1}\\left( \\frac{1}{\\alpha\r\n_{t}^{j}\\beta ^{j}}L_{t}^{j}\\right) ^{-\\beta ^{j}}\\left( Q_{t}\\right)\r\n^{\\beta ^{j}} \\\\\r\n\\prod_{j=1}^{J}\\alpha _{t}^{j^{-\\alpha _{t}^{j}}}\\left( P_{t}^{j}\\right)\r\n^{\\alpha _{t}^{j}} &=&\\prod_{j=1}^{J}\\alpha _{t}^{j^{-\\alpha\r\n_{t}^{j}}}\\left( \\xi B^{j}\\right) ^{\\alpha _{t}^{j}}\\left[ A_{t}^{j}\\cdot\r\n\\left( T^{j}\\right) ^{\\frac{1}{\\theta }}\\right] ^{-\\alpha _{t}^{j}}\\left( \r\n\\frac{1}{\\alpha _{t}^{j}\\beta ^{j}}L_{t}^{j}\\right) ^{-\\beta ^{j}\\alpha\r\n_{t}^{j}}\\left( Q_{t}\\right) ^{\\beta ^{j}\\alpha _{t}^{j}} \\\\\r\n1 &=&\\prod_{j=1}^{J}\\alpha _{t}^{j^{-\\alpha _{t}^{j}}}\\left( \\xi\r\nB^{j}\\right) ^{\\alpha _{t}^{j}}\\left[ A_{t}^{j}\\cdot \\left( T^{j}\\right) ^{%\r\n\\frac{1}{\\theta }}\\right] ^{-\\alpha _{t}^{j}}\\left( \\frac{1}{\\alpha\r\n_{t}^{j}\\beta ^{j}}L_{t}^{j}\\right) ^{-\\beta ^{j}\\alpha _{t}^{j}}Q_{t}^{\\bar{%\r\n\\beta}} \\\\\r\nQ_{t} &=&\\prod_{j=1}^{J}\\left( \\xi B^{j}\\right) ^{-\\alpha ^{j}/\\bar{\\beta}}%\r\n\\left[ A_{t}^{j}\\cdot \\left( T^{j}\\right) ^{\\frac{1}{\\theta }}\\right]\r\n^{\\alpha ^{j}/\\bar{\\beta}}\\alpha _{t}^{j^{-\\alpha _{t}^{j}/\\bar{\\beta}%\r\n}}\\left( \\alpha _{t}^{j}\\beta ^{j}\\right) ^{-\\frac{\\beta ^{j}\\alpha _{t}^{j}%\r\n}{\\bar{\\beta}}}\\left( L_{t}^{j}\\right) ^{\\frac{\\beta ^{j}\\alpha _{t}^{j}}{%\r\n\\bar{\\beta}}} \\\\\r\nY_{t} &=&\\sum_{j=1}^{J}\\frac{w_{t}^{j}L_{t}^{j}}{P_{t}}=\\sum_{k=1}^{J}\\beta\r\n^{k}\\alpha _{t}^{k}Q_{t}=\\bar{\\beta}\\prod_{j=1}^{J}\\left( \\xi B^{j}\\right)\r\n^{-\\alpha ^{j}/\\bar{\\beta}}\\left[ A_{t}^{j}\\cdot \\left( T^{j}\\right) ^{\\frac{%\r\n1}{\\theta }}\\right] ^{\\alpha ^{j}/\\bar{\\beta}}\\alpha _{t}^{j^{-\\alpha\r\n_{t}^{j}/\\bar{\\beta}}}\\left( \\alpha _{t}^{j}\\beta ^{j}\\right) ^{-\\frac{\\beta\r\n^{j}\\alpha _{t}^{j}}{\\bar{\\beta}}}\\left( L_{t}^{j}\\right) ^{\\frac{\\beta\r\n^{j}\\alpha _{t}^{j}}{\\bar{\\beta}}} \\\\\r\nY_{t} &=&\\prod_{j=1}^{J}R^{j}\\left[ A_{t}^{j}\\cdot \\left( T^{j}\\right) ^{%\r\n\\frac{1}{\\theta }}\\right] ^{\\alpha ^{j}/\\bar{\\beta}}\\left( L_{t}^{j}\\right)\r\n^{\\frac{\\beta ^{j}\\alpha _{t}^{j}}{\\bar{\\beta}}}\r\n\\end{eqnarray*}\r\n\r\n\\bigskip where $\\bar{\\beta}=\\sum_{j=1}^{J}\\alpha ^{j}\\beta ^{j}$ and $%\r\nR_{j}\\propto \\prod_{j=1}^{J}\\left( \\beta ^{j}\\alpha ^{j}\\right) ^{-\\frac{%\r\n\\alpha ^{j}\\beta ^{j}}{\\bar{\\beta}}}(B^{j})^{-\\frac{\\alpha ^{j}}{\\bar{\\beta}}%\r\n}\\left( T^{j}\\right) ^{\\frac{\\alpha ^{j}}{\\bar{\\beta}\\cdot \\theta }}$ is a\r\ntime-invariant product. We now need to determine $L_{nt}^{k}$\r\n\r\n\\begin{equation}\r\n\\psi _{nt}^{k\\ast }=\\frac{L_{nt}^{k\\ast }}{L_{nt}}=E_{t-1}\\left[ \\frac{%\r\nw_{nt}^{k}L_{nt}^{k}}{\\sum_{k}w_{nt}^{k}L_{nt}^{k}}\\right] ,\\qquad \\forall\r\nk,t.\r\n\\end{equation}%\r\n\\begin{equation*}\r\n\\psi _{nt}^{k}=\\psi _{nt}^{k\\ast }+\\frac{1}{\\varrho }\\left[ \\frac{\\frac{1}{J}%\r\n\\sum_{j=1}^{J}w_{nt}^{j}-w_{nt}^{k}}{\\sum_{j=1}^{J}w_{nt}^{j}L_{nt}^{j}}%\r\n\\right] \r\n\\end{equation*}\r\n\r\nWe can now move one step backward and solve for the allocation of the\r\nprimary input across sectors, $L_{t}^{j},$ $j=1,...,J$. \r\n\r\n$\\psi _{nt}^{k\\ast }=\\frac{\\alpha ^{j}\\beta ^{j}}{\\bar{\\beta}}$.$.$Hence:\r\n\r\n\\begin{equation*}\r\n\\psi _{t}^{k}=\\frac{\\alpha ^{j}\\beta ^{j}}{\\bar{\\beta}}+\\frac{1}{\\varrho }%\r\n\\left[ \\frac{\\bar{w}_{t}-w_{t}^{k}}{\\sum_{j=1}^{J}w_{t}^{j}L_{t}^{j}}\\right] \r\n\\end{equation*}\r\n\r\n\\begin{eqnarray}\r\nY_{t} &=&\\sum_{j=1}^{J}\\frac{w_{t}^{j}L_{t}^{j}}{P_{t}}=\\prod_{j=1}^{J}R_{j}%\r\n\\left[ A_{t}^{j}\\right] ^{\\frac{\\alpha ^{j}}{\\bar{\\beta}}}\\left( \\frac{%\r\n\\alpha ^{j}\\beta ^{j}}{\\bar{\\beta}}+\\frac{1}{\\varrho }\\left[ \\frac{\\bar{w}%\r\n_{t}-w_{t}^{k}}{\\sum_{j=1}^{J}w_{t}^{j}L_{t}^{j}}\\right] \\right) ^{\\frac{%\r\n\\alpha ^{j}\\beta ^{j}}{\\bar{\\beta}}}L_{t}  \\label{expost} \\\\\r\nY_{t} &=&\\sum_{j=1}^{J}\\frac{w_{t}^{j}L_{t}^{j}}{P_{t}}=\\prod_{j=1}^{J}R_{j}%\r\n\\left[ A_{t}^{j}\\right] ^{\\frac{\\alpha ^{j}}{\\bar{\\beta}}}\\left( \\frac{%\r\n\\alpha ^{j}\\beta ^{j}}{\\bar{\\beta}}+\\frac{1}{\\varrho }\\left[ \\frac{\\frac{%\r\n\\bar{w}_{t}-w_{t}^{k}}{P_{t}}}{Y_{t}}\\right] \\right) ^{\\frac{\\alpha\r\n^{j}\\beta ^{j}}{\\bar{\\beta}}}L_{t}\r\n\\end{eqnarray}\r\n\r\n\\begin{equation*}\r\n\\frac{\\bar{w}_{t}-w_{t}^{k}}{P_{t}}=\\sum_{j\\neq k}^{J}\\left( \\xi\r\nB^{j}\\right) ^{-1/\\beta ^{j}}\\left[ A_{t}^{j}\\cdot \\left( T^{j}\\right) ^{%\r\n\\frac{1}{\\theta }}\\right] ^{1/\\beta ^{j}}\\left( \\frac{P_{t}^{j}}{P_{t}}%\r\n\\right) ^{\\frac{1}{\\beta ^{j}}}\r\n\\end{equation*}\r\n\r\n\\bigskip \r\n\r\n\\bigskip \r\n\r\n\\bigskip \r\n\r\nSTOP HERE\r\n\r\n\\bigskip\r\n\r\n\\paragraph{Solution with International Trade}\r\n\r\nThe key difference in the internationally open economy is that inputs can\r\npotentially be sourced from different countries. Delivering a unit of good $%\r\n\\omega ^{j}$ produced in country $m$ to country $n$ costs: \r\n\\begin{equation*}\r\np_{nmt}^{j}(\\omega ^{j})=\\frac{B^{j}\\left( w_{mt}^{j}\\right) ^{\\beta\r\n^{j}}P_{mt}^{1-\\beta ^{j}}}{A_{mt}^{j}\\kappa _{nmt}^{j}z_{m}(\\omega ^{j})} \r\n\\end{equation*}%\r\nwhere $B^{j}\\left( w_{mt}^{j}\\right) ^{\\beta ^{j}}P_{mt}^{1-\\beta ^{j}}$ is\r\nthe cost of the input bundle in country of origin $m$, sector $j$, at time $%\r\nt $. Because of perfect competition, the price paid in country $n$, denoted $%\r\np_{nt}(\\omega ^{j})$, will be the minimum price across all $N$ potential\r\ntrading partners: $p_{nt}^{j}(\\omega ^{j})=\\min \\left\\{ p_{nmt}^{j}(\\omega\r\n^{j});\\text{ }m=1,...,N\\right\\} .$ Producers of the aggregate good in (\\ref%\r\n{aggregate}) minimize production costs taking prices as given. We assume the\r\ndistribution of efficiencies for any good $\\omega ^{j}$ in sector $j$ and\r\ncountry $n$ are independent across countries and sectors and follow a\r\ntime-invariant Fr\\'{e}chet distribution: $F_{n}^{j}(z)=\\exp\r\n(-T_{n}^{j}z^{-\\theta }).$ Under this assumption, the distribution of prices\r\nin sector $j$ of country $n$, conditional on $\\left\\{ A_{mt}^{j}\\right\\}\r\n_{m=1,...N}$ is given by $G_{nt}^{j}(p)|_{\\left\\{ A_{t}^{j}\\right\\} }=\\Pr\r\n(P_{nt}^{j}<p)=1-\\exp \\left[ -\\Phi _{nt}^{j}p^{\\theta }\\right] $ where $\\Phi\r\n_{nt}^{j}=\\sum_{m=1}^{N}T_{m}^{j}\\left( \\frac{B^{j}\\left( w_{mt}^{j}\\right)\r\n^{\\beta ^{j}}P_{mt}^{1-\\beta ^{j}}}{A_{mt}^{j}\\kappa _{nmt}^{j}}\\right)\r\n^{-\\theta }$. Given that there is a continuum of $\\omega ^{j}$ in each\r\nsector, by the law of large numbers the probability that country $m$\r\nprovides a good in sector $j$ at the lowest price in country $n$ equals the\r\nfraction of goods that country $n$ buys from country $m$ in sector $j$: \r\n\\begin{equation}\r\nd_{nmt}^{j}=\\frac{T_{m}^{j}\\left( \\frac{B^{j}\\left( w_{mt}^{j}\\right)\r\n^{\\beta ^{j}}P_{mt}^{1-\\beta ^{j}}}{A_{mt}^{j}\\kappa _{nmt}^{j}}\\right)\r\n^{-\\theta }}{\\Phi _{nt}^{j}}  \\label{shares}\r\n\\end{equation}%\r\nthat is, $d_{nmt}^{j}$ is the fraction of country $n$'s total spending on\r\nsector-$j$ goods from country $m$ at time $t$. The equilibrium in the open\r\neconomy can be defined as following.\r\n\r\n\\textbf{Equilibrium Definition. } An equilibrium in the open economy is\r\ndefined as a set of resource allocations $\\left\\{ L_{nt}^{j}\\right\\} $,\r\nimport shares $\\left\\{ d_{nit}^{j}\\right\\} $, prices $\\left\\{ P_{nt}\\right\\} \r\n$, $\\left\\{ P_{nt}^{j}\\right\\} $, and $\\left\\{ w_{n}^{j}\\right\\} $ such\r\nthat, given technology $\\left\\{ A_{it}^{j}\\right\\}\r\n,\\left\\{T_{it}^{j}\\right\\} ,$ aggregate endowments $\\left\\{ L_{nt}\\right\\} $\r\nand trading costs $\\left\\{ \\kappa _{int}^{j}\\right\\} $ $i)$ consumers\r\nmaximize expected utility, $ii)$ firms minimize costs and, $iii)$ markets\r\nfor goods and inputs clear, and $iv)$ trade is balanced. In equilibrium,\r\nprices and quantities satisfy (\\ref{eq1})-(\\ref{eq7}): \r\n\\begin{equation}\r\nP_{nt}=\\prod_{j}^{J}\\left( \\frac{1}{\\alpha _{n}^{j}}\\right)\r\n^{\\alpha^{j}}\\left( P_{nt}^{j}\\right) ^{\\alpha ^{j}}  \\label{eq1}\r\n\\end{equation}\r\n\\begin{equation}\r\nP_{nt}^{j}=\\xi\\Phi _{nt}^{j^{-1/}\\theta }  \\label{eq2}\r\n\\end{equation}\r\n\\begin{equation}\r\n\\Phi _{nt}^{j}=\\left( B^{j}\\right) ^{-\\theta\r\n}\\sum_{i=1}^{N}T_{i}^{j}\\left(A_{it}^{j}\\right) ^{\\theta }\\left[ \\frac{%\r\nP_{it}^{1-\\beta ^{j}}\\left(w_{it}^{j}\\right) ^{\\beta ^{j}}}{\\kappa _{nit}^{j}%\r\n}\\right] ^{-\\theta }  \\label{eq3}\r\n\\end{equation}\r\n\\begin{equation}\r\nd_{nmt}^{j}=\\frac{\\left( B^{j}\\right) ^{-\\theta\r\n}T_{m}^{j}\\left(A_{mt}^{j}\\right) ^{\\theta }\\left( \\frac{P_{mt}^{1-\\beta\r\n^{j}}w_{mt}^{j\\beta^{j}}}{\\kappa _{nmt}^{j}}\\right) ^{-\\theta }}{\\Phi\r\n_{nt}^{j}};\\sum\\limits_{m=1}^{N}d_{nmt}^{j}=1  \\label{eq4}\r\n\\end{equation}\r\n\\begin{equation}\r\nw_{nt}^{j}L_{nt}^{j}=\\beta^{j}\\sum_{m=1}^{N}d_{mnt}^{j}\\left[\\alpha^{j}+%\r\n\\frac{1-\\beta^{j}}{\\beta^j} \\cdot \\frac{w_{mt}^{j}L_{mt}^{j}}{w_{mt}L_{mt}}%\r\n\\right] w_{mt}L_{mt}  \\label{eq5}\r\n\\end{equation}\r\n\\begin{equation}\r\nw_{nt}L_{nt}=\\sum_{j=1}^{J}w_{nt}^{j}L_{nt}^{j}  \\label{eq6}\r\n\\end{equation}\r\n\\begin{equation}\r\n\\frac{L_{nt}^{j}}{L_{nt}}=E_{t-1}\\left[ \\frac{w_{nt}^{j}L_{nt}^{j}}{%\r\n\\sum_{k=1}^J w_{nt}^{k}L_{nt}^{k}}\\right]  \\label{eq7}\r\n\\end{equation}\r\n\r\nEquations (\\ref{eq1})--(\\ref{eq3}) show the equilibrium prices as a function\r\nof technology and input costs resulting from firms' cost minimization and\r\nconsumers' maximization problems. The first equation in (\\ref{eq4}) shows\r\nthe value of goods from sector $j$ bought by country $n$ from country $m$ as\r\na share of total spending on goods $j$ by country $n.$ The second equation\r\nsays that the sum of spending shares on goods $j$ from all countries $m$ by\r\ncountry $n$ (including $n$ itself) add to 1, that is, imports plus domestic\r\nexpenditures on goods $j$ by country $n$, add up to the overall spending\r\nvalue on goods $j$ by country $n.$ Equation (\\ref{eq5}) gives the value of\r\ntotal sales accruing to the primitive factor in sector $j$ of country $n;$\r\nit already incorporates the balanced trade condition, i.e., total payments\r\nfor goods flowing out of country $m$ to the rest of the world equal payments\r\nflowing in country $m$ from the rest of the world.\\footnote{%\r\nIn formulas, $\\sum\\nolimits_{j=1}^{J}X_{mt}^{j}=\\sum\\nolimits_{n=1}^{N}\\sum%\r\n\\nolimits_{j=1}^{J}d_{nmt}^{j}X_{nt}^{j}$, where $X_{nt}^{j}$ is total\r\nexpenditure by country $n$ on sector-$j$ goods. The right-hand side is the\r\ntotal demand by all $N$ countries for goods produced in country $m$. The\r\nleft-hand side is the total expenditures by country $m$, which, under trade\r\nbalance also equals its total sales. Recall that $P_{m}^{j}Q_{m}^{j}$ is the\r\ntotal purchases of goods from sector $j$ by country $m.$ Note $%\r\nP_{mt}^{j}Q_{mt}^{j}$, the total purchases of goods from sector $j$ by\r\ncountry $m.$ Hence: $P_{mt}^{j}Q_{mt}^{j}=\\alpha ^{j}w_{mt}L_{mt}+\\frac{%\r\n1-\\beta ^{j}}{\\beta ^{j}}w_{mt}^{j}L_{mt}^{j}$.} Equation (\\ref{eq4})\r\nexpresses total value added in the economy as the sum of sectoral value\r\nadded. (Real value added is given by $Y_{nt}=\\frac{w_{nt}L_{nt}}{P_{nt}}$.)\r\nFinally, (\\ref{eq7}) expresses the resource shares as a function of expected\r\nshares, following the first order conditions in (\\ref{eq:FOC}).\r\n\r\nThe model can conceptually be solved backwards in two steps. First, for any\r\ngiven set of values for $L_{nt}^{j}$, the first five sets of equations can\r\nbe solved for $P_{nt}$, $w_{nt}^{j}$, $P_{nt}^{j}$, $d_{nmt}^{j}$ as a\r\nfunction of the $\\kappa _{mnt}^{j}s$ and the augmented productivity factors\r\ndefined as: \r\n\\begin{equation}\r\nZ_{nt}^{j}\\equiv T_{n}^{j}\\left[ L_{nt}\\left( A_{nt}^{j}\\right) ^{1/\\beta\r\n^{j}}\\right] ^{\\beta ^{j}\\theta }.  \\label{productivityfactor}\r\n\\end{equation}%\r\nThen in a first stage, we can solve for the shares $\\frac{L_{nt}^{j}}{L_{nt}}\r\n$. As seen, with log utility the solution for $\\frac{L_{n}^{j}}{L_{n}}$\r\nsimplifies significantly as it is the expected value of sectoral value-added\r\nshares; in the implementation, we will use the data to help pin down these\r\nexpectations.\r\n\r\n\\subsection{Two Illustrative Cases: Autarky and Costless Trade}\r\n\r\nTo illustrate the mechanism of diversification through trade, we analyze a\r\none-sector version of the model (that is, the Eaton-Kortum model) under two\r\nextreme cases for which we have closed-form analytical solutions for GDP:\r\nautarky and costless trade. We accordingly drop the sector subscripts.\r\n\r\n\\subsubsection{Volatility under Autarky}\r\n\r\nUnder complete autarky, value added in the one-sector economy is given by (%\r\n\\ref{expost}), which can be rewritten as: \r\n\\begin{equation*}\r\nY_{nt}\\propto \\left( Z_{nt}\\right) ^{\\frac{1}{\\beta \\theta }} \r\n\\end{equation*}\r\nwhere $Z_{nt}\\equiv T_{n}\\left( L_{nt}A_{nt}^{1/\\beta }\\right)^{\\beta\\theta\r\n} $. Taking log-differences around the mean (or trend value in the\r\nempirics), we obtain, \r\n\\begin{equation*}\r\n\\hat{Y}_{nt}=\\frac{1}{\\beta \\theta }\\hat{Z}_{nt}. \r\n\\end{equation*}\r\nThus, in the one-sector economy under autarky, shocks to value added are\r\ndriven exclusively by domestic shocks to the productive capacity of the\r\neconomy, $\\hat{Z}_{nt}.$ The variance of GDP, $V(\\hat{Y}_{nt})$ thus depends\r\non the variance of the shocks $V(\\hat{Z}_{nt})$: \r\n\\begin{equation*}\r\nV(\\hat{Y}_{nt})=\\frac{1}{\\left( \\beta \\theta \\right) ^{2}}V(\\hat{Z}_{nt}). \r\n\\end{equation*}\r\n\r\n\\subsubsection{Volatility under Costless Trade}\r\n\r\nUnder costless trade in the one-sector economy ($\\kappa _{nmt}=1$), GDP per\r\ncapita simplifies to:\\footnote{%\r\nSee derivations in the Appendix.} \r\n\\begin{equation*}\r\nY_{nt}=\\left( \\xi B\\right) ^{1/\\beta }Z_{nt}^{\\frac{1}{1+\\beta \\theta }%\r\n}\\left( \\sum_{m=1}^{N}Z_{mt}^{\\frac{1}{1+\\beta \\theta }}\\right) ^{\\frac{1}{%\r\n\\beta \\theta }} \r\n\\end{equation*}%\r\nand hence GDP fluctuations are given by: \r\n\\begin{equation*}\r\n\\hat{Y}_{nt}=\\frac{1}{1+\\beta \\theta }\\left[ \\hat{Z}_{n}+\\frac{1}{\\beta\r\n\\theta }\\sum_{m=1}^{N}\\gamma _{m}\\hat{Z}_{m}\\right] \r\n\\end{equation*}%\r\nwhere $\\gamma _{m}=\\frac{\\bar{Z}_{m}^{\\frac{1}{1+\\beta \\theta }}}{%\r\n\\sum_{i=1}^{N}\\bar{Z}_{i}^{\\frac{1}{1+\\beta \\theta }}}$ is the relative size\r\nof country $j$ evaluated at the mean of $Z_{j}s$. Rearranging, we obtain: \r\n\\begin{equation}\r\n\\hat{Y}_{nt}=\\frac{1}{\\beta \\theta }\\left[ \\frac{\\gamma _{n}+\\beta \\theta }{%\r\n1+\\beta \\theta }\\hat{Z}_{n}+\\frac{1}{1+\\beta \\theta }\\sum_{m\\neq\r\nn}^{N}\\gamma _{m}\\hat{Z}_{m}\\right]\r\n\\end{equation}%\r\nVolatility under free trade is hence given by: \r\n\\begin{equation}\r\nVar(\\hat{Y}_{nt})=\\left( \\frac{1}{\\beta \\theta }\\right) ^{2}\\left\\{ \r\n\\begin{array}{c}\r\n\\left( \\frac{\\gamma _{n}+\\beta \\theta }{1+\\beta \\theta }\\right) ^{2}Var(\\hat{%\r\nZ}_{nt})+\\left[ \\frac{1}{1+\\beta \\theta }\\right] ^{2}\\sum_{m\\neq i}\\gamma\r\n_{m}^{2}Var(\\hat{Z}_{mt}) \\\\ \r\n2\\frac{\\gamma _{n}+\\beta \\theta }{1+\\beta \\theta }\\frac{1}{1+\\beta \\theta }%\r\n\\sum_{m\\neq n}\\gamma _{m}Cov(\\hat{Z}_{m,}\\hat{Z}_{n})%\r\n\\end{array}%\r\n\\right\\}\r\n\\end{equation}%\r\nCompared to the variance in autarky, $V(\\hat{Y}_{nt})=\\frac{1}{\\left( \\beta\r\n\\theta \\right) ^{2}}V(\\hat{Z}_{nt})$, it is clear that the volatility due to\r\ndomestic productivity fluctuations, $Var(\\hat{Z}_{nt}),$ now receives a\r\nsmaller loading, as $\\left( \\frac{\\gamma _{n}+\\beta \\theta }{1+\\beta \\theta }%\r\n\\right) ^{2}<1$ since $\\gamma _{n}<1.$ The smaller the country (as gauged by\r\nits share $\\gamma _{n}$), the smaller the impact of domestic volatility of\r\nshocks, $\\hat{Z}_{n},$ on its GDP, when compared to autarky. Openness to\r\ntrade, however, exposes the economy to other countries' productivity shocks,\r\nwhich will also contribute to the country's overall volatility. Whether or\r\nnot the gain in diversification (given by lower exposure to domestic\r\nproductivity) is bigger than the increased exposure to new shocks depends on\r\nthe variance-covariance matrix of shocks across countries. If all countries\r\nhave the same constant variance $Var(\\hat{Z}_{nt})=\\sigma ,$ and the $\\hat{Z}%\r\n_{nt}$ are uncorrelated, volatility under free trade becomes: \r\n\\begin{equation}\r\nVar(\\hat{Y}_{nt})=\\left( \\frac{1}{\\beta \\theta }\\right) ^{2}\\left\\{ \\left( \r\n\\frac{\\gamma _{n}+\\beta \\theta }{1+\\beta \\theta }\\right) ^{2}+\\left[ \\frac{1%\r\n}{1+\\beta \\theta }\\right] ^{2}\\sum_{m\\neq i}\\gamma _{m}^{2}\\right\\} \\sigma\r\n\\end{equation}%\r\nwhich is unambiguously lower than the volatility in autarky given that%\r\n\\footnote{%\r\nsince $\\left( \\beta \\theta \\right) ^{2}+2\\beta \\theta \\gamma\r\n_{n}+\\sum_{j=1}\\gamma _{j}^{2}<(1+\\beta \\theta )^{2}$ as \r\n\\begin{equation*}\r\n2\\beta \\theta \\gamma _{n}+\\sum_{j=1}\\gamma _{j}^{2}<2\\beta \\theta +1 \r\n\\end{equation*}%\r\n} \r\n\\begin{equation}\r\n\\left( \\frac{\\gamma _{n}+\\beta \\theta }{1+\\beta \\theta }\\right) ^{2}+\\left[ \r\n\\frac{1}{1+\\beta \\theta }\\right] ^{2}\\sum_{m\\neq i}\\gamma _{m}^{2}<1\r\n\\label{derivelater}\r\n\\end{equation}%\r\n(recall $\\gamma _{m}<1$ and\\ $\\sum_{m=1}^{N}\\gamma _{m}^{2}\\leq 1)$. Of\r\ncourse, if other countries have higher variances or the covariance terms are\r\nimportant, then the weights countries receive matter and the resulting\r\nchange in volatility cannot be unambiguously signed.\r\n\r\n\\section{Mapping the Model into Observables}\r\n\r\n\\label{mapping_into_observables}\r\n\r\nIn this section, we connect the model to the data and use it to\r\nquantitatively assess the effect of historical changes in trade barriers on\r\nGDP volatility for a diverse sample of 24\\ core countries and an aggregate\r\nof the remaining countries\\ to which we refer as \\textquotedblleft rest of\r\nthe world\\textquotedblright\\ (ROW).\r\n\r\nThe equilibrium of the model is characterized by equations (\\ref{eq1})-(\\ref%\r\n{eq7}). We solve the model\\ numerically, for which we need to calibrate the\r\nvalues of the exogenous trading costs $\\kappa _{nmt}^{j}$, the productivity\r\nprocess $Z_{nt}^{j}$, and the parameters $\\alpha ^{j}$, $\\beta ^{j}$, $%\r\n\\theta $, and $\\eta $. We consider 24 sectors in the analysis (agriculture,\r\n22 manufacturing sectors, and services). Throughout the study, services are\r\ntreated as a nontradable sector (that is, $\\kappa _{nmt}^{j}=0$ for all $%\r\nn\\neq m$ and $\\kappa _{nmt}^{j}=1$ for $n=m$), whereas agriculture and\\ all\r\nmanufacturing sectors are treated as tradables, with potentially different\r\ntrading costs.\r\n\r\nWe set $\\alpha ^{j}$ so as to match the average share of each sector on\r\ntotal final uses in the OECD Input-Output tables across all countries. The\r\nbetas for each sector are calculated as the ratio of value added to total\r\noutput. A detailed description of the data and the calculations are\r\navailable in the Appendix.\r\n\r\nWe allow for a relatively broad parametric range for $\\theta $, from $\\theta\r\n=2$ to $\\theta =8,$ consistent with the estimates in the literature (see\r\nEaton and Kortum, 2003, Donaldson 2015, and Simonovska and Waugh, 2011). We\r\nuse $\\theta =4$ as the baseline case, and report the results for other\r\nvalues when discussing the sensitivity of our results. We calibrate the\r\nelasticity of substitution across varieties $\\eta =2$, consistent with Broda\r\nand Weinstein (2006). The results are not sensitive to this parametric\r\nchoice.\r\n\r\nWe explain next how we obtain the processes for $\\kappa _{nmt}^{j}$ and $%\r\nZ_{it}^{j}$ using data on sectoral bilateral trade flows, value added,\r\noutput, and prices. Before we specify the details, a quick intuition on how\r\nthese series are backed-out from the model is as follows. We recover trade\r\ncosts $\\kappa _{nmt}^{j}$ using information on bilateral trade shares and\r\ngross output at the sectoral level. Intuitively, if two countries trade\r\nlittle with one another in a given sector (relative to the sectoral gross\r\noutput of these countries), this will signal high trade costs between the\r\ncountries in that sector. Second, we recover productivities relative to a\r\nbenchmark country using the market share of each exporter. If a country has\r\na high export share in a sector, that is a sign of revealed comparative\r\nadvantage, meaning a high relative productivity in the sector relative to\r\nthe benchmark country. To calibrate the absolute level of productivities, we\r\nuse price data for a benchmark country. We explain the procedure in detail\r\nand with formulas in the next section.\r\n\r\n\\subsection{Implementation}\r\n\r\n\\paragraph{Kappas}\r\n\r\nIn order to perform counterfactual experiments we need to back out the\r\nhistorical realizations of the exogenous processes. Following the idea in\r\nHead and Ries (2011), we assume that sectoral bilateral trading costs are\r\nsymmetric, that is: $\\kappa _{nmt}^{j}=\\kappa _{mnt}^{j}$, and hence\r\nbilateral trade costs at the sectoral level can be backed out from\\ the\r\ndata. Indeed, inverting the structural model, we obtain: \r\n\\begin{equation}\r\n\\frac{d_{nmt}^{j}d_{mnt}^{j}}{d_{mmt}^{j}d_{nnt}^{j}}=\\left( \\kappa\r\n_{nmt}^{j}\\right) ^{2\\theta }.  \\label{kappa}\r\n\\end{equation}%\r\nThe left hand side objects can be measured using data on bilateral imports\r\nand gross output at the sectoral level. Specifically, $d_{nmt}^{j}$ is the\r\nvalue of exports from $m$ to $n$ in sector $j$ at $t$ relative to total\r\nspending by $n$ on sector $j$ at time $t$, where total spending is measured\r\nas gross output plus imports minus exports by that sector and country at\r\ntime $t.$ The share $d_{mmt}^{j}$ is obtained as a residual from the\r\naccounting restriction: \r\n\\begin{equation*}\r\nd_{mmt}^{j}=1-\\sum\\limits_{n\\neq m}^{N}d_{mnt}^{j} \r\n\\end{equation*}%\r\nHence, for a given value of $\\theta $, we can obtain the time series of\r\ntrading costs by sector and country-pairs $\\left\\{ \\kappa _{nmt}^{j}\\right\\} \r\n$.\r\n\r\n\\paragraph{Productivity in Tradable Sectors}\r\n\r\nTo back out the productivities, we proceed as follows. First, using the\r\nformula for $d_{nm}^{j}$ in equation (\\ref{eq4}), after some algebra, we\r\nobtain: \r\n\\begin{equation}\r\nd_{nm}^{j}=\\frac{\\left( B^{j}\\right) ^{-\\theta }\\left( \\psi _{m}^{j}\\right)\r\n^{\\beta ^{j}\\theta }Z_{m}^{j}\\left( \\kappa _{nm}^{j}\\right) ^{\\theta }\\left(\r\ny_{m}^{j}\\right) ^{-\\theta \\beta ^{j}}}{P_{m}^{\\theta }\\Phi _{n}^{j}}\\text{, \r\n}  \\label{produc}\r\n\\end{equation}%\r\nwhere $\\psi _{m}^{j}\\equiv \\frac{L_{m}^{j}}{L_{m}}$ and $y_{m}^{j}\\equiv \r\n\\frac{L_{m}^{j}w_{m}^{j}}{P_{m}}$. We can exploit this to recover $%\r\nZ_{m}^{j}. $ In particular, inverting (\\ref{produc}) we have: \r\n\\begin{equation}\r\nZ_{mt}^{j}={B^{j}}^{\\theta }{\\xi }^{\\theta }d_{nmt}^{j}\\left(\r\ny_{m}^{j}\\right) ^{\\theta \\beta ^{j}}\\left( \\kappa _{nmt}^{j}\\right)\r\n^{-\\theta }\\left( \\frac{P_{nt}^{j}}{P_{mt}}\\right) ^{-\\theta }\\left( \\psi\r\n_{mt}^{j}\\right) ^{-\\theta \\beta ^{j}}  \\label{productivity}\r\n\\end{equation}%\r\nTo approximate terms on the right hand side we use data on sectoral import\r\nshares $d_{nmt}^{j}$, sectoral value added $y_{m}^{j}$, sectoral shares $%\r\n\\psi _{mt}^{j}$, and aggregate prices $P_{nt}\\ $along with the calibrated\r\nparameters. (See the Appendix for more details.) The only terms we cannot\r\nback out directly from data are sectoral prices. We thus use the model in\r\nconjunction with the data to infer them. Note first that equation~(\\ref%\r\n{productivity}) holds for all $(n,k)$ pairs of countries and all sectors $j$\r\n(except for services). The procedure becomes clear when we collect known and\r\nunknown terms as follows:%\r\n\\begin{align}\r\nZ_{nt}^{j}& =\\underbrace{\\xi ^{\\theta }{B^{j}}^{\\theta }d_{k,n,t}^{j}\\left(\r\n\\kappa _{k,n,t}^{j}\\right) ^{-\\theta }\\left( w_{n,t}^{j}L_{n,t}^{j}\\right)\r\n^{\\theta \\beta ^{j}}\\left( \\psi _{n,t}^{j}\\right) ^{-\\theta \\beta ^{j}}{%\r\nP_{n,t}}^{\\theta (1-\\beta ^{j})}}_{\\equiv \\exp (\\zeta _{k,n,t}^{j})}{%\r\nP_{k,t}^{j}}^{-\\theta }  \\notag \\\\\r\n& =\\exp (\\zeta _{k,n,t}^{j}){P_{k,t}^{j}}^{-\\theta }\r\n\\end{align}%\r\nNote in particular that this relationship holds for any choice of country $k$%\r\n. Note also that the factor $\\exp (\\zeta _{k,n,t}^{j})$ can be constructed\r\nfrom observable data. We decompose $\\exp (\\zeta\r\n_{k,n,t}^{j})=Z_{nt}^{j}\\left( {P_{k,t}^{j}}\\right) ^{\\theta }$ according to\r\nthe following procedure:\r\n\r\n\\begin{enumerate}\r\n\\item Take logs and rename terms for brevity. \r\n\\begin{align}\r\n\\zeta _{k,n,t}^{j}& =\\ln {Z_{nt}^{j}}+\\theta \\ln {P_{k,t}^{j}} \\\\\r\n& \\equiv \\chi _{nt}^{j}+\\tau _{k,t}^{j}\r\n\\end{align}%\r\nwhere $\\chi _{nt}^{j}\\equiv \\ln {Z_{nt}^{j}}$ and $\\tau _{k,t}^{j}\\equiv\r\n\\theta \\ln {P_{k,t}^{j}}$.\r\n\r\n\\item To proceed we need a benchmark country, so we use sectoral prices in\r\nthe US. \r\n\\begin{equation*}\r\n\\tau _{US,t}^{j}\\equiv \\theta \\ln {P_{US,t}^{j}} \r\n\\end{equation*}%\r\nWe choose units of accounts for each sector so that U.S. nominal sectoral\r\nprices are equal to 1 in 1972.\r\n\r\n\\item Obtain $\\tau _{k,t}^{j}$ for all other countries as: \r\n\\begin{equation}\r\n\\tau _{k,t}^{j}=\\frac{1}{N}\\sum_{n=1}^{N}\\left( \\zeta _{k,n,t}^{j}-\\zeta\r\n_{US,n,t}^{j}\\right) +\\tau _{US,t}^{j}\r\n\\end{equation}%\r\n(Note that this equation holds with and without the averaging operator, $%\r\n\\frac{1}{N}\\sum_{n=1}^{N}$, as $\\tau _{k,t}^{j}$ and $\\tau _{US,t}^{j}$ do\r\nnot depend on the exporter $n$.\\footnote{%\r\nWe use the average in the quantitative analysis to minimize measurement\r\nerror.})\r\n\r\n\\item Back-out $\\chi _{nt}^{j}$ for all other countries:%\r\n\\begin{equation}\r\n\\chi _{nt}^{j}=\\frac{1}{N}\\sum_{k=1}^{N}\\left( \\zeta _{k,n,t}^{j}-\\tau\r\n_{k,t}^{j}\\right)\r\n\\end{equation}\r\n\r\n\\item Recover shocks and prices:%\r\n\\begin{align}\r\nZ_{n,t}^{j}& =\\exp \\left( \\chi _{nt}^{j}\\right) \\\\\r\nP_{k,t}^{j}& =\\exp \\left( \\frac{\\tau _{kt}^{j}}{\\theta }\\right)\r\n\\end{align}\r\n\\end{enumerate}\r\n\r\nAt the end of the procedure we end up with augmented productivity factors $%\r\nZ_{n,t}^{j}$ and sectoral prices for agriculture and all manufacturing\r\nsectors $P_{k,t}^{j}$.\r\n\r\n\\paragraph{Productivity in Nontradables}\r\n\r\nTo compute the productivities in the services sector for each country, we\r\nuse equilibrium equations (\\ref{eq1}), (\\ref{eq2}) and (\\ref{produc}).\r\n\r\n\\begin{enumerate}\r\n\\item As we already have sectoral prices of tradables we can use (\\ref{eq1})\r\nto recover the price of services as follows: \r\n\\begin{equation}\r\nP_{n,t}^{s}=\\left( \\frac{P_{n,t}}{P_{US,t}}P_{US,t}\\right) ^{\\frac{1}{\\alpha\r\n^{s}}}\\left( \\prod_{j=1}^{J}{\\alpha ^{j}}^{-\\alpha ^{j}}\\right) ^{-\\frac{1}{%\r\n\\alpha ^{s}}}\\left[ \\prod_{j\\neq s}\\left( P_{n,t}^{j}\\right) ^{\\alpha ^{j}}%\r\n\\right] ^{-\\frac{1}{\\alpha ^{s}}}\r\n\\end{equation}%\r\nNote that we observe data on the price of country $n$ relative to the price\r\nin the United States, $\\frac{P_{n,t}}{P_{US,t}}$, from the Penn World Tables.\r\n\r\n\\item Now we recover $Z_{n,t}^{s}$ using (\\ref{eq2}), (\\ref{produc}), and $%\r\nn=m$. \r\n\\begin{equation}\r\nZ_{n,t}^{s}=\\xi ^{\\theta }{B^{s}}^{\\theta }\\left( \\frac{%\r\nw_{n,t}^{s}L_{n,t}^{s}}{\\psi _{n,t}^{s}}\\right) ^{\\theta \\beta ^{s}}\\left( \r\n\\frac{P_{n,t}}{P_{US,t}}P_{US,t}\\right) ^{\\theta (1-\\beta ^{s})}{P_{n,t}^{s}}%\r\n^{-\\theta }\r\n\\end{equation}\r\n\\end{enumerate}\r\n\r\n\\paragraph{Sectoral versus Aggregate Shocks}\r\n\r\nNote that the changes in productivity retrieved above, \r\n\\begin{equation}\r\n\\frac{1}{\\beta ^{j}\\theta }\\hat{Z}_{m}^{j}\\equiv \\frac{1}{\\beta ^{j}}\\hat{A}%\r\n_{mt}^{j}+\\hat{L}_{mt},  \\label{prodchanges}\r\n\\end{equation}%\r\ncan be decompose into two factors: a sectoral factor, $\\frac{1}{\\beta ^{j}}%\r\n\\hat{A}_{mt}^{j}$, and an aggregate factor $\\hat{L}_{mt}$. The\r\ninterpretation of $L_{mt}$ as \\textquotedblleft equipped\r\nlabour\\textquotedblright\\ means that it embeds a productivity component too.\r\nGiven the functional form, the split between pure productivity and resources\r\nin $L_{mt}$ is not relevant from the point of view of aggregate volatility.\r\n(A shock to $L_{mt}$ will be equivalent to an aggregate shock to $A_{mt}^{j}$%\r\ns that leaves the relative productivities $A_{mt}^{j}/A_{mt}^{j^{\\prime }}$\r\nunchanged $\\forall j,j^{\\prime }.$) For identification, we impose the\r\nrestriction that \r\n\\begin{equation}\r\n\\sum \\frac{\\alpha ^{j}}{\\beta ^{j}}\\hat{A}_{mt}^{j}=0.  \\label{idrestriction}\r\n\\end{equation}%\r\nThus, changes in the sectoral productivity will correspond to changes in the\r\nrelative value of $A_{mt}^{j}$, while changes in aggregate productivity\r\n(affecting all sectors equally), as well as changes in overall resources,\r\nwill be subsumed in $L_{mt}$. We hence call sectoral shocks, those affecting \r\n$\\hat{A}_{mt}^{j}$ and aggregate shocks those affecting the aggregate factor \r\n$\\hat{L}_{mt}$. The identification restriction implies that any primitive\r\naggregate shock affecting all sectors will be collected in $\\hat{L}_{mt}.$\r\n\r\n\\paragraph{Summary of the Procedure}\r\n\r\nWe can summarize the procedure as follows.\r\n\r\n\\begin{enumerate}\r\n\\item Obtain the\\ inverse of trade costs, $\\kappa $s, from (\\ref{kappa}).\r\n\r\n\\item Compute $\\psi _{mt}^{j}$ as the sectoral value-added share at time $t$.\r\n\r\n\\item Retrieve the panel of sectoral and country productivities$\\left\\{\r\nZ_{mt}^{j}\\right\\} $ from the procedure described above.\\footnote{%\r\nUnits of accounts are chosen so that nominal sectoral prices in the US in\r\n1972 equal 1.}\r\n\r\n\\item Retrieve $L_{mt}$ from (\\ref{prodchanges}) using (\\ref{idrestriction})\r\nand compute $L_{mt}^{j}=\\psi _{mt}^{j}L_{mt}.$\r\n\r\n\\item Solve the equilibrium values of $\\left\\{ d_{nit}^{j}\\right\\} $, $%\r\n\\left\\{ P_{nt}\\right\\} $, $\\left\\{ P_{nt}^{j}\\right\\} $, and $\\left\\{\r\nw_{n}^{j}\\right\\} $ using equations (\\ref{eq1}) through (\\ref{eq6}).\r\n\\end{enumerate}\r\n\r\n\\subsubsection{Counterfactual Equilibria}\r\n\r\nWe discuss next how we compute the equilibrium in the counterfactual\r\nexercise and how we identify the two theoretical mechanisms.\r\n\r\n\\paragraph{Numerical Counterfactual Equilibria}\r\n\r\nFor each new value of (inverse) trading cost $\\kappa $, and the estimated\r\nsequence of sectoral productivities $\\left\\{ Z_{mt}^{j}\\right\\} $, we need\r\nto solve for the sequence of equipped labour allocated to each sector $%\r\n\\left\\{ L_{mt}^{j}\\right\\} $. The rational-expectations equilibrium is a\r\nfixed point of a below mapping on the space of all possible sequences $%\r\n\\left\\{ L_{mt}^{j}\\right\\} $. We proceed as follows.\r\n\r\n\\begin{enumerate}\r\n\\item We start from the initial value $(L_{nt}^j)^0 = \\alpha^j L_{nt}$.\r\n\r\n\\item In iteration $i$ for the actual $(L_{nt}^{j})^{i}$ we get sectoral and\r\naggregate (equipped labour) wages, $(w_{nt}^{j})^{i}$ and $(w_{nt})^{i}$,\r\nfrom the equilibrium equations.\r\n\r\n\\item We calculate the implied total value added and the sectoral value\r\nadded shares as \r\n\\begin{equation*}\r\n\\left(\\frac{w_{nt}^j L_{nt}^j}{w_{nt} L_{nt}}\\right)^i = \\frac{(w_{nt}^j)^i\r\n(L_{nt}^j)^i}{(w_{nt})^i L_{nt}}. \r\n\\end{equation*}\r\n\r\n\\item \r\n\\begin{enumerate}\r\n\\item Decompose all $N\\cdot J$ value-added-share series into trend and cycle\r\ncomponents using an annual band-pass filter. \r\n\\begin{equation*}\r\n\\log \\left( \\frac{w_{nt}^{j}L_{nt}^{j}}{w_{nt}L_{nt}}\\right)\r\n^{i}=trend_{nt}^{j}+cycle_{nt}^{j}. \r\n\\end{equation*}\r\n\r\n\\item Normalize the trend values so that in each period and each country the\r\ntrend values add up to 1: \r\n\\begin{equation*}\r\n\\widehat{\\left( \\frac{w_{nt}^{j}L_{nt}^{j}}{w_{nt}L_{nt}}\\right) ^{i}}=\\frac{%\r\n\\exp (trend_{nt}^{j})}{\\sum_{k}\\exp (trend_{nt}^{k})} \r\n\\end{equation*}\r\n\r\n\\item Replace the expectation with the adjusted trend value. \r\n\\begin{equation*}\r\nE_{t - 1} \\left( \\frac{w_{nt}^j L_{nt}^j}{w_{nt} L_{nt}}\\right) = \\widehat{%\r\n\\left(\\frac{w_{nt}^j L_{nt}^j}{w_{nt} L_{nt}}\\right)^i} \r\n\\end{equation*}\r\n\\end{enumerate}\r\n\r\n\\item Update the resource allocations \r\n\\begin{equation*}\r\n(L_{nt}^j)^{i + 1} = L_{nt} \\widehat{\\left(\\frac{w_{nt}^j L_{nt}^j}{w_{nt}\r\nL_{nt}}\\right)^i} \r\n\\end{equation*}\r\n\r\n\\item Repeat the procedure until convergence.\r\n\\end{enumerate}\r\n\r\n\\paragraph{Productivities in Counterfactual Scenario}\r\n\r\nWe are interested in decomposing the trade effect on volatility on the\r\ncontributions of the two mechanisms, specialization and diversification. To\r\nachieve that, we need to identify the sources of shocks to productivity. We\r\nresort to a factor model that decomposes productivity shocks into sector-\r\nand country-specific components in a way described in Koren and Tenreyro\r\n(2007). To separate per period shocks from trends we use a band pass filter\r\nto detrend each $\\left\\{ \\log {Z_{n,t}^{j}}\\right\\} _{t=1}^{T}$ series. Then\r\nwe calculate the time average of the shocks for each $(n,j)$ pair and\r\nsubtract it from the growth rate to get the object to be decomposed, $\\tilde{%\r\nZ}_{nt}^{j}$. \r\n\\begin{equation*}\r\n\\tilde{Z}_{nt}^{j}=\\hat{Z}_{n,t}^{j}-(T-1)^{-1}\\sum_{t=2}^{T}\\hat{Z}%\r\n_{n,t}^{j} \r\n\\end{equation*}%\r\nWithout loss of generality, we decompose $\\tilde{Z}_{nt}^{j}$ as: \r\n\\begin{equation*}\r\n\\tilde{Z}_{nt}^{j}=\\lambda _{t}^{j}+\\mu _{nt}+\\epsilon _{nt}^{j}, \r\n\\end{equation*}%\r\nwhere ${\\mu _{n,t}}$ is the country-specific factor, affecting all sectors\r\nwithin the country; $\\lambda _{t}^{j}$ is the global sectoral factor,\r\naffecting sector $j$ in all countries;\\ and the residual $\\epsilon\r\n_{n,t}^{j} $ is the idiosyncratic component, specific to the country and\r\nsector. The three factors, $\\lambda ,\\mu $, and $\\epsilon $ are estimated\r\nas: \r\n\\begin{align*}\r\n\\hat{\\lambda}_{t}^{j}& =N^{-1}\\sum_{n=1}^{N}\\tilde{Z}_{nt}^{j} \\\\\r\n\\hat{\\mu}_{nt}& =J^{-1}\\sum_{j=1}^{J}\\left( \\tilde{Z}_{nt}^{j}-\\hat{\\lambda}%\r\n_{t}^{j}\\right) \\\\\r\n\\hat{\\epsilon}_{nt}^{j}& =\\tilde{Z}_{nt}^{j}-\\hat{\\lambda}_{t}^{j}-\\hat{\\mu}%\r\n_{nt}\\text{,}\r\n\\end{align*}%\r\nwith the restriction $\\sum_{n}{\\mu _{n}}=0$ implying that the\r\ncountry-specific effect is expressed relative to the world's aggregate. In\r\nthe counterfactual exercises, we can mute the sector- or country-specific\r\nfactors by setting the corresponding components equal to 0, in order to\r\nidentify the separate effects of the two trade channels affecting volatility.\r\n\r\n\\end{document}\r\n", "meta": {"hexsha": "20fc7de4320766acf67bbc1aa5a70a7f35701ca2", "size": 49452, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "impvol_text/labourrel.tex", "max_stars_repo_name": "ceumicrodata/impvol", "max_stars_repo_head_hexsha": "1b57bff42701d8235d9624f0fd192dc36de6dfec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "impvol_text/labourrel.tex", "max_issues_repo_name": "ceumicrodata/impvol", "max_issues_repo_head_hexsha": "1b57bff42701d8235d9624f0fd192dc36de6dfec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-09-01T10:29:32.000Z", "max_issues_repo_issues_event_max_datetime": "2017-09-01T10:29:32.000Z", "max_forks_repo_path": "impvol_text/labourrel.tex", "max_forks_repo_name": "ceumicrodata/impvol", "max_forks_repo_head_hexsha": "1b57bff42701d8235d9624f0fd192dc36de6dfec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.256097561, "max_line_length": 253, "alphanum_fraction": 0.6566974035, "num_tokens": 17182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.34929065314791957}}
{"text": "% !TEX root = ../thesis.tex\n\n\\chapter{Magnetohydrodynamics}\n\\label{chap:magnetohydrodynamics}\nMagnetohydrodynamics (henceforth abbreviated \\mhd\\!\\!)\nis a combination of the theories of fluid dynamics,\ngoverned by the Navier-Stokes equations,\nand the theory of electrodynamics,\ngoverned by Maxwell’s equations.\nThe field of \\mhd studies electrically conducting fluids,\nthe prime example of which are plasmas.\n\nPlasma physics has promising applications such as nuclear fusion,\na source of energy that unlike nuclear fission does not produce radioactive byproducts.\nA big problem here is the issue of \\emph{plasma confinement}:\nfor controlled fusion, the plasma must be contained in a reactor vessel.\nHowever, the temperature required for nuclear fusion is so high (above 150 million \\textsc{°c}),\nthat no known material is able to withstand this amount of heat.\nThe plasma will melt the walls of the reactor if it makes contact with them.\nTo avoid this, present-day reactors employ intense magnetic fields to confine the plasma.\n\nAlternatives have been proposed,\nwhere the plasma has an inherent stability due to the structure of its magnetic field.\nIn order to understand this,\nwe will first give a bit of background about \\mhd.\nAs we will see, the magnetic field is a key ingredient of this theory,\nbut the electric field plays a secondary role at best.\nNext, we will show how knots and links can be used to provide stability.\nWe formalise this concept with the idea of \\emph{helicity}.\nFinally, we construct several magnetic fields with high helicity.\n\n\\section{Ideal magnetohydrodynamics}\n\\label{sec:ideal-mhd}\nIdeal \\mhd describes the dynamics of a conducting fluid with no net charge.\nThe quantities that play a role here are:\n\\begin{itemize}\n\\setlength{\\itemsep}{-0.5em}\n\\item The mass density $\\rho$\n\\item The fluid velocity $\\vf$ \\pagebreak\n\\item The pressure $p$\n\\item The magnetic field $\\Bf$\n\\end{itemize}\nVector quantities have been set in boldface.\nNote that there is no electric field here;\nin \\mhd the electric field is fully determined by \\kern0.1pt $\\vf$ and $\\Bf$.\nIn ideal \\mhd, the electric resistivity of the fluid is assumed to be zero.\nThat is, the fluid is a perfect conductor.\nThis gives us a first hint about why the electric field may be neglected:\nin electrostatics, the electric field inside a perfect conductor is zero.\nHowever, \\mhd is not a static theory.\nThe reason that the electric field is secondary nonetheless,\nis that the magnitude of the electric field is of the order $|\\vf||\\Bf|$,\nas will be shown below.\nWhereas the time derivative of the electric field does play a role in electromagnetic waves,\nwhere it has a magnitude of the order $c\\,|\\Bf|$,\nits contribution is negligible in \\mhd when the velocity $\\vf$ is nonrelativistic.\n\nThe evolution of a system in ideal \\mhd,\nignoring the effects of gravity,\nis given by the following equations (see also \\parencite[p.~133]{goedbloed2004}):\n\\begingroup\n\\addtolength{\\jot}{1em}\n\\begin{align}\n\\label{eqn:continuity-equation} \\frac{\\partial \\rho}{\\partial t} &= -\\nabla \\cdot (\\rho \\vf) \\\\\n\\label{eqn:cauchy-momentum}     \\rho \\left( \\frac{\\partial}{\\partial t} + \\vf \\cdot \\nabla \\right) \\vf &= \\frac{1}{\\mu_0}(\\nabla \\times \\Bf) \\times \\Bf -\\nabla p \\\\\n\\label{eqn:internal-energy}     \\frac{\\partial p}{\\partial t} &= - \\vf \\cdot \\nabla p - \\gamma p \\nabla \\cdot \\vf \\\\\n\\label{eqn:faraday}             \\frac{\\partial \\Bf}{\\partial t} &= \\nabla \\times {(\\vf \\times \\Bf)} \\\\\n\\label{eqn:no-monopoles}        \\nabla \\cdot \\Bf &= 0\n\\end{align}\n\\endgroup\nEquation~\\ref{eqn:continuity-equation}, the \\emph{continuity equation} embodies conservation of mass:\nif the mass density changes, the fluid must have flowed somewhere else.\nEquation~\\ref{eqn:cauchy-momentum}, the \\emph{momentum equation}, describes the forces acting on the fluid.\nThe left-hand side represents the change in momentum,\nthe right hand side has a Lorentz force term (\\hspace{1pt}$\\jf \\times \\Bf$,\nwhere $\\jf = \\mu_0^{-1} \\nabla \\times \\Bf$ with $\\mu_0$ the magnetic permeability of the vacuum)\nand a pressure term.\nEquation~\\ref{eqn:internal-energy} concerns the \\emph{internal energy} of the fluid.\nA flow in the direction of the pressure gradient will reinforce the gradient (the first term),\nand if there is a net influx of fluid into a volume,\npressure will build up in this volume (the second term).\nHere the constant $\\gamma$ is the \\emph{adiabatic index},\nthe ratio of the heat capacity at constant pressure and the heat capacity at constant volume.\nEquation~\\ref{eqn:faraday} represents Faraday’s law, $\\partial \\Bf / \\partial t = - \\nabla \\times \\Ef$.\nThe expression $\\Ef = - \\vf \\times \\Bf$ is Ohm’s law for a perfect conductor.\nBecause of the infinite conductance of the fluid,\nany electric field will vanish in the reference frame of a test particle moving with the fluid.\nIn the lab frame, we then find an electric field $-\\vf \\times \\Bf$.\nFinally, the magnetic field has no charges (equation~\\ref{eqn:no-monopoles}).\n\n\\section{Linked and knotted fields}\n\\label{sec:linked-and-knotted-fields}\nLinking and knotting provide a promising way of creating stable plasmas,\nbecause in ideal \\mhd they are preserved.\nThis imposes constraints on the evolution of the system.\nConsequently, plasmas with linked or knotted field lines\nmight not be able to relax to a state of global minimum energy.\nIn this manner, topological properties of the field can provide stability.\n\nIn ideal \\mhd, field lines of the magnetic field are said to be \\emph{frozen in} in the fluid.\nThis idea, which is encoded in equation~\\ref{eqn:faraday},\nwas hinted at in \\parencite{alfven1942} and is sometimes called \\emph{Alfvén’s theorem}.\nIt states that the magnetic flux through a surface does not change\nas the surface moves along with the fluid flow.\nFrom this principle it can be derived that points connected by a magnetic field line\nwill remain connected by the same field line as they move with the fluid.\nIn particular, field lines cannot pass through one another.\nLinked field lines will stay linked throughout the evolution of the system.\nA thorough derivation of these effects can be found in \\parencite{stern1966}.\n\nTo study the dynamics of a conducting fluid,\nconsider a circular flux tube (a surface of magnetic field lines)\nwith high flux inside the tube, and zero flux outside.\nWe assume that $V \\approx 2\\pi r \\itTheta$\nis a good approximation of the volume $V$ of this tube,\nwhere $2\\pi r$ is the length of the tube,\nand $\\itTheta$ the surface area of its cross section.\nRecall that the magnetic energy is given by\n\\[ E_B = \\tfrac{1}{2} \\iiint \\!\\!|\\Bf|^2 \\, dx^3 \\]\nIf we assume a magnetic field of constant magnitude $B$ inside the tube,\nthen the flux $\\itPhi$ through a cross section perpendicular to the field\nis simply $B\\itTheta$,\nand conversely $B = \\itPhi / \\itTheta$.\nWe find that\n\\vspace{-0.5\\parskip}\n\\[ E_B \\approx \\pi r \\itTheta B^2 = \\pi r \\itTheta^{-1} \\itPhi^2 \\vspace{0.2\\parskip} \\]\nBy the frozen-in principle,\nthe flux $\\itPhi$ through a cross section of the tube is constant in time.\nScaling the area $\\itTheta$ by a factor $a$\nwhile keeping $\\itPhi$ constant,\nwill change the energy by a factor $a^{-1}$.\nThickening the tube will therefore decrease its magnetic energy.\nOn the other hand, scaling the length of the tube by a factor $b$\nwhile keeping $\\itPhi$ constant\nwill change the energy by a factor $b$.\nContracting the tube will decrease its magnetic energy.\nFrom this we can conclude that an unconstrained flux tube\nwill contract and thicken as it relaxes.\n\nThe single flux tube helps us understand why linking is important for stability.\n\\marginfigure{\n\\tikzexternalenable\n\\tikzsetnextfilename{collapsing-flux-tubes}\n\\begin{center}\n\\hspace{-1em}\n\\begin{tikzpicture}\n\\newcommand*{\\trefoil}[4]{\n\\begin{scope}\n\\tikzstyle{back} = [line width = #4, black]\n\\tikzstyle{knot} = [line width = #3, white]\n\\setlength{\\kr}{#2}\n\\coordinate (A) at ($ #1 + ( 90 : 0.7\\kr)$);\n\\coordinate (B) at ($ #1 + (210 : 0.7\\kr)$);\n\\coordinate (C) at ($ #1 + (330 : 0.7\\kr)$);\n\\coordinate (Z) at ($(B) !.5! (C) + (90 : \\kr)$);\n\\draw[back] ($(C) + (330 : \\kr)$) arc (-30 :  90 : \\kr) -- (Z);\n\\draw[knot] ($(C) + (330 : \\kr)$) arc (-30 :  90 : \\kr) -- (Z);\n\\draw[back] ($(B) + (210 : \\kr)$) arc (210 : 330 : \\kr) --\n            ($(A) + (330 : \\kr)$) arc (-30 :  90 : \\kr);\n\\draw[knot] ($(B) + (210 : \\kr)$) arc (210 : 330 : \\kr) --\n            ($(A) + (330 : \\kr)$) arc (-30 :  90 : \\kr);\n\\draw[back] ($(A) + ( 88 : \\kr)$) arc ( 88 : 210 : \\kr) --\n            ($(C) + (210 : \\kr)$) arc (210 : 332 : \\kr);\n\\draw[knot] ($(A) + ( 86 : \\kr)$) arc ( 86 : 210 : \\kr) --\n            ($(C) + (210 : \\kr)$) arc (210 : 334 : \\kr);\n\\draw[back] (Z) + (0.1pt, 0) -- ($(B) + ( 90 : \\kr)$) arc ( 90 : 212 : \\kr);\n\\draw[knot] (Z) + (0.5pt, 0) -- ($(B) + ( 90 : \\kr)$) arc ( 90 : 214 : \\kr);\n\\end{scope}}\n\\trefoil{(0, 7.4em)}{2.0em}{3.0pt}{3.94pt}\n\\trefoil{(0,   0em)}{1.5em}{4.5pt}{5.44pt}\n\\trefoil{(0,-6.0em)}{1.0em}{10pt}{10.94pt}\n\\end{tikzpicture}\n\\end{center}\n\\vspace{1em}\n\\caption{Like linked flux tubes, a knotted flux tube cannot collapse onto itself.}}\nSuppose that instead of a single flux tube,\nwe have two linked tubes.\nBecause the field lines cannot pass through eachother,\nlinking prevents the tubes from collapsing onto theirselves.\nIn order for one tube to contract,\nthe other tube must become thinner —\nincreasing its flux density and thereby its magnetic energy.\nThis is the way in which linking provides stability.\nA more rigorous discussion can be found in \\parencite{moffatt1969} and \\parencite{arnold1974}.\nThe degree of stability that different types of links and knots provide\nis an area of active research,\nbut this is beyond the scope of this thesis.\n\nTo formalise the concept of linked field lines,\nwe introduce a new quantity.\n\n\\definition\nThe \\emph{magnetic helicity} of the magnetic field $\\Bf = \\nabla \\times \\Af$\nin a bounded volume $V\\!$,\\, such that $\\Bf \\cdot \\nf = 0$ on the boundary of $V$\nwhere $\\nf$ is a unit length normal vector of the boundary,\nis defined by\n\\[ H_V \\, = \\!\\iiint_{\\!V} \\Af \\cdot \\Bf \\ dx^3 \\]\nAn example of such a volume $V$ is a \\emph{flux tube},\na volume formed by all of the field lines that intersect a certain surface.\nSee also \\parencite[p.~156]{goedbloed2004}.\n\nThe definition above is a special case of the Hopf invariant\nas defined in definition~\\ref{def:hopf-invariant-of-subset}.\nIn section~\\ref{sec:the-hopf-invariant} we proved the gauge invariance of $H_V$,\na property that is not obvious from its definition.\nFurthermore, we showed that $H_V$ is invariant when\nboth $V$ and the field lines of $\\Bf$ are transformed\nby an orientation-preserving function.\nThe flow of a fluid is an example of such a function,\nand because of the frozen-in principle,\nthe magnetic field does move along with the fluid flow.\nIt follows that in ideal \\mhd\n\\[ \\frac{dH_V}{dt} = 0 \\]\nThe conservation of this quantity was discovered by \\parencite{woltjer1958}.\nAn alternative derivation can be found in \\parencite[p.~157]{goedbloed2004}.\nBesides the helicity in $V$\nit is possible to define a global helicity by integrating over all space,\nbut this requires restrictions on the field\nif the helicity is to be gauge invariant.\n\nTo show the relation between linking and helicity,\nconsider again the circular flux tube for which\n$V \\approx 2 \\pi r \\itTheta$ is a good approximation of its volume.\nHere $\\itTheta$ is the surface area of its cross section.\nSuppose that $\\Bf$ inside the tube has constant magnitude $B$,\nand zero magnitude outside of the tube.\nAssume that this flux tube is linked once with an identical flux tube,\nrotated by 90 degrees with respect to the first one.\nWe will denote the first tube by $T_1$ and the second tube by $T_2$.\nTo compute the magnetic helicity inside $T_1$,\nwe can factor the integral into a part along the field,\nand a part perpendicular to the field.\nDenote by $\\sigma$ a field line inside $T_1$,\nand let $D$ be the disk of which $\\sigma$ is the boundary.\nLet $dl$ be a line element along $\\sigma$,\nand $dS$ a surface element of $D$.\nNote that $dl$ is parallel to $\\Bf$.\nWe find\n\\[ H_{T_1}\n = \\iiint_{\\!T_1} \\! \\Af \\cdot \\Bf \\ dx^3\n\\ \\approx \\ \\itTheta B \\oint_\\sigma \\! \\Af \\cdot dl\n = \\itTheta B \\iint_{\\!D} (\\nabla \\times \\Af) \\cdot dS\n = \\itTheta B \\iint_{\\!D} \\! \\Bf \\cdot dS\n\\ \\approx \\ (\\itTheta B)^2 \\]\nHere we used Stokes’ theorem to write the integral\nas an integral of $\\Bf$ over $D$,\nwhich picks up a factor $\\itTheta B$ from $T_2$ passing through it once.\nThe field inside $T_1$ does not contribute,\nbecause $\\Bf$ is perpendicular to the surface normal of $D$ there.\nBeware that although we are computing the helicity \\emph{inside} $T_1$,\nit depends on $\\Af$ and $\\Bf$ \\emph{outside} of $T_1$.\nIf $T_2$ would be wound around $T_1$ twice instead of once,\nwe would get an extra factor $2$.\nIn general,\nwhen $T_2$ and $T_1$ are linked $n$ times,\nthe helicity in $T_1$ (and by symmetry, in $T_2$)\nwill be given by $n (\\!\\itTheta B)^2$.\nThe factor $n$ is how topology enters into \\mhd.\n\nWhen resistivity of the fluid is incorporated (non-ideal, resistive, or dissipative \\mhd),\nthe frozen-in principle no longer holds.\nAmong others, an extra term must be added to equation~\\ref{eqn:faraday}.\n\\parencite[p.~162]{goedbloed2004}\nIt follows that magnetic flux is no longer conserved,\nand field lines may break and recombine.\nThe tools of topology break down here:\ncontinuity is at the heart of topology,\nso if field lines can break,\nwe cannot meaningfully speak about linking.\nFortunately, for suitable boundary conditions the helicity remains a well-defined quantity,\nand as argued in \\parencite{taylor1974},\nhelicity is \\emph{approximately conserved},\nmeaning that it changes at timescales much larger\nthan typical timescales of fluid dynamics.\nThe extent to which helicity still provides stability in resistive \\mhd\nis beyond the scope of this thesis,\nbut work is being done in this area.\n\n\\section{Constructing a magnetic field}\n\\label{sec:constructing-a-magnetic-field}\nIn the previous sections we showed that we can construct\nself-stable plasma configurations in \\mhd\nby giving a vector field with high helicity.\nThe field derived in section~\\ref{sec:constructing-a-vector-field} comes to mind:\nits field lines are the fibres of the Hopf map\nprojected stereographically onto $\\R^3\\!$,\nso all of the field lines are linked with every other field line.\n\nThe approach taken in section~\\ref{sec:constructing-a-magnetic-field}\nwas also used in \\parencite{kamchatnov1982} to construct a magnetic field.\nKamchatnov only considered the pullback of $\\omega_0$,\nnot of a general two-form.\nIn his case the vector potential was found in a deus ex machina manner,\nbut obviously this approach does not generalise to different two-forms on $S^2\\!$.\nBy \\poincares lemma the vector potential always exists,\nbut an explicit computation can get quite involved.\nIt was shown by Kamchatnov that the configuration obtained from the Hopf map\nis a magnetohydrodynamic \\emph{soliton}\n— a wave that preserves its shape while propagating.\n\n\\begin{python}\nfrom hopf import *\nfrom sympy import exp\n\ndef identity(x):\n    return x\n\ndef volume_form(x):\n    return x\n\ndef south_form(x):\n    d_sqr = sum(xi ** 2 for xi in sub(x, [-1, 0, 0]))\n    f = exp(-d_sqr * 3)\n    return [xi * f for xi in x]\n\ndef north_form(x):\n    d_sqr = sum(xi ** 2 for xi in sub(x, [ 1, 0, 0]))\n    f = exp(-d_sqr * 3)\n    return [xi * f for xi in x]\n\nwindow = [(x * 2.0 - 1.0) * 1.6 for x in interval_closed(79)]\nwrite_field_energy('generated/energy-volume', volume_form, identity, window)\nwrite_field_energy('generated/energy-south', south_form, identity, window)\nwrite_field_energy('generated/energy-north', north_form, identity, window)\n\\end{python}\n\\begin{figure}[b!]\n\\margincaption[2.7em]{\\label{fig:energy-density}\nMagnetic energy density $\\nsq{\\Bf}$ in the planes $x_1 = 0$,\n$x_2 = 0$ and $x_3 = 0$\nfor the pullback by $h \\circ \\pi^{-1}$ of the following functions on $S^2$:\n$f(x) = 1$ for the top row,\n$f(x) = \\exp(-3\\nsq{x + i})$ for the middle row, and\n$f(x) = \\exp(-3\\nsq{x - i})$ for the bottom row.\nIntensity has been normalised per row.}\n\\begin{center}\n\\tikzexternalenable\n\\tikzsetnextfilename{energy}\n\\begin{tikzpicture}\n% Set custom heat-like colourmap that does not go all the way to black.\n\\pgfplotsset{\n  colormap = {energy}{[1cm]\n    rgb255(0cm) = (128, 0, 0);\n    rgb255(3cm) = (255, 32, 0);\n    rgb255(6cm) = (255, 192, 0);\n    rgb255(8cm) = (255, 255, 255)\n  },\n}\n\\newcommand*{\\energyplot}[1]{\n  \\nextgroupplot[xlabel = $x_2$, ylabel = $x_3$]\n  \\addplot3[surf, shader = interp] table {#1-x2x3.dat};\n\n  \\nextgroupplot[xlabel = $x_3$, ylabel = $x_1$]\n  \\addplot3[surf, shader = interp] table {#1-x3x1.dat};\n\n  \\nextgroupplot[xlabel = $x_1$, ylabel = $x_2$, colorbar]\n  \\addplot3[surf, shader = interp] table {#1-x1x2.dat};\n}\n\\begin{groupplot}[group style = {\n                    group size = 3 by 3,\n                    horizontal sep = 3.5em,\n                    vertical sep = 3.5em\n                  },\n                  width = 0.35\\textwidth, height = 0.35\\textwidth,\n                  view = {0}{90},\n                  point meta min = 0,\n                  point meta max = 1,\n                  ylabel style = {rotate = -90},\n                  ylabel shift = -0.5em,\n                  colorbar style = {\n                    ytick = {0.0, 0.5, 1.0},\n                    width = 1em\n                  },\n                  tick style = {\n                    white,\n                    major tick length = 0.3em\n                  }]\n  \\energyplot{generated/energy-volume}\n  \\energyplot{generated/energy-south}\n  \\energyplot{generated/energy-north}\n\\end{groupplot}\n\\end{tikzpicture}\n\\end{center}\n\\end{figure}\n\nBy the principle given at the end of section~\\ref{sec:constructing-a-vector-field},\nthere are two ways to generalise the field given in equation~\\ref{eqn:hopf-field}\nwhich we now take to be the magnetic field.\nFirstly, we can pull back a different two-form on the sphere.\nAs this affects the magnitude of the field but not its field lines,\nthis allows us to control the \\emph{energy density} of the magnetic energy of the field.\n(See figure~\\ref{fig:energy-density}.)\nSecondly,\nwe may pull back by a different function, or even from a different manifold altogether.\nThe convenient property of linked field lines is a consequence of the Hopf map,\nso this we do not change.\nInstead, we will intersperse a differentiable function $g : S^3 \\to S^3\\!$,\nand pull back by the composition\n\\begin{center}\n\\begin{tikzcd}\n\\R^3 \\ar[r, hook, \"\\pi^{-1}\"] &\nS^3  \\ar[r, \"g\"] &\nS^3  \\ar[r, two heads, \"h\"] &\nS^2  \\ar[r, hook, \"i\"] &\n\\R^3\n\\end{tikzcd}\n\\end{center}\nMany functions $g$ could potentially be interesting here\nand perhaps future research can be done in this area.\nFor instance, by considering $S^3$ as a subgroup of $\\H$ as in section~\\ref{sec:quaternions},\nthe map\n\\[ S^3 \\longto S^3, \\quad q \\longmapsto q^n \\]\nis a differentiable function for all $n \\in \\Z$.\nIf we take $S^3 \\subseteq \\CZ$ instead,\nthe following map is interesting:\n\\begin{equationref}\n\\label{eqn:knot-map}\nS^3 \\longto S^3, \\quad (z_1, \\, z_2) \\longmapsto \\tau(z_1^n, \\, z_2^m)\n\\end{equationref}\nHere $m, n \\in \\Z$ and $\\tau: \\CZ \\surj S^3$ denotes projection onto the sphere.\nThe above map is differentiable because it is the composition of $\\tau$ with a polynomial.\nFor $m, n \\notin \\Z$ the map is not differentiable;\nit is not even continuous,\nso it does not make sense to compute the pullback by such a map.\nIt turns out that for coprime $m, n$ the field lines of the field induced by this map form torus knots.\nIn this way we can produce not only linked field lines,\nbut also knotted field lines.\nSee also figure~\\ref{fig:knotted-field-lines}.\nA slightly different map,\n\\[ S^3 \\longto S^3, \\quad (z_1, z_2) \\longmapsto (z_1^{(n)},\\, z_2^{(m)}) \\]\ncan occasionally be found in literature.\nHere the map $z \\mapsto z^{(n)}$ denotes multiplying the argument of $z$ with $n$.\nUnfortunately the map $z \\mapsto z^{(n)}$ is not differentiable in $0$,\nso the above function is not differentiable.\nIt has been used nevertheless in \\parencite{arrayas2012},\nalbeit in a different construction.\n\nMore generally we could consider the map\n\\[ S^3 \\longto S^3, \\quad (z_1, \\, z_2) \\longmapsto \\tau(p(z_1, z_2),\\, q(z_1, z_2))  \\]\nwhere $p, q \\in \\C[Z_1, Z_2]$ are polynomials that have no common roots except for $(0, 0)$.\nFor polynomials with a common root other than $(0, 0)$ the function\nwould map some $(z_1, z_2) \\in S^3$ to $(0, 0)$,\nbut this is not an element of $\\CZ$;\nthere is no way to project the origin onto the three-sphere.\n\n\\begin{python}\nfrom hopf import *\nfrom math import pi\nbox       = [1.636, 1.636, 1.636]\npr        = orthographic_projection(pi * 0.12, pi * -0.1)\npoints    = [[[0.0, cos(pi * 0.0 / 15.0) * 1.30, sin(pi * 0.0 / 15.0) * 1.30], 'f1c'],\n             [[0.0, cos(pi * 1.0 / 15.0) * 1.30, sin(pi * 1.0 / 15.0) * 1.30], 'f2c'],\n             [[0.0, cos(pi * 5.0 / 15.0) * 1.62, sin(pi * 9.0 / 15.0) * 1.62], 'f3c']]\nfibres    = [[compose(pr, projected_knot_fibre_through(x, 2, 3)),\n              'front, ' + st, 'back'] for [x, st] in points]\ncmds      = generate_raw_draw_2d(0.08, fibres)\nbox       = generate_raw_box_2d(box, pr, 'box')\nwrite_items('generated/field-lines-trefoil.tikz', cons(box, cmds))\n\nfibres    = [[compose(pr, projected_knot_fibre_through(x, 2, 5)),\n              'front, ' + st, 'back'] for [x, st] in points]\ncmds      = generate_raw_draw_2d(0.08, fibres)\nwrite_items('generated/field-lines-cinquefoil.tikz', cons(box, cmds))\n\\end{python}\n\\begin{figure}\n\\margincaption[2em]{\\label{fig:knotted-field-lines}\nA few field lines of fields where $g \\neq \\id$;\nthe function from equation~\\ref{eqn:knot-map} has been interspersed.\nOn the left, $m = 3$ and on the right $m = 5$.\nIn both cases $n = 2$.\nThe field lines form torus knots,\nknotted themselves and linked with eachother.}\n\\tikzexternalenable\n\\tikzsetnextfilename{knotted-field-lines}\n\\hspace{0.5em} % No center here, manual alignment gets us better results.\n\\begin{tikzpicture}\n\\definecolor{f1c}{hsb}{0.6, 0.6, 0.5}\n\\definecolor{f2c}{hsb}{0.0, 0.8, 0.6}\n\\definecolor{f3c}{hsb}{0.5, 0.9, 0.6}\n\\tikzstyle{back}  = [line width = 3pt, white];\n\\tikzstyle{front} = [line width = 1pt];\n\\tikzstyle{box}   = [line width = 0.47pt];\n\\begin{scope}[scale = 1.1]\n\\input{generated/field-lines-trefoil.tikz}\n\\end{scope}\n\\begin{scope}[scale = 1.1, shift = {(5.5, 0)}]\n\\input{generated/field-lines-cinquefoil.tikz}\n\\end{scope}\n\\end{tikzpicture}\n\\vspace{1em}\n\\end{figure}\n\nThe construction used in this thesis to produce magnetic fields\nis not limited to $\\R^3$ or $S^2\\!$,\nand a generalisation of this procedure to electrodynamics could\npotentially be interesting for future research.\nMinkowski space $\\M$ is a four-dimensional pseudo-Riemannian manifold,\nwhere the bilinear form is given by the Lorentzian metric.\nBy mapping $\\M$ to a two-dimensional manifold via a differentiable function,\nwe can construct a two-form $\\omega \\in \\Omega^2 \\M$ that satisfies $d\\omega = 0$.\nMaxwell’s source-free equations can be expressed neatly in the language of differential geometry\nas\n\\[ d\\xi = 0 \\qquad\\textup{and}\\qquad d\\hodge\\xi = 0 \\]\nHere $\\xi \\in \\Omega^2 \\M$ can be identified with the electromagnetic field tensor\n(sometimes called the Faraday tensor)\nand $\\hodge\\xi$ denotes the \\emph{Hodge dual} of $\\xi$.\nSee \\parencite[p.~502]{szekeres2004} for further information on\nexpressing Maxwell’s equations in this form.\nWith the construction in this thesis we can trivially satisfy\n$d\\xi = 0$, which corresponds to solving the two homogeneous equations\n\\[ \\nabla \\cdot \\Bf = 0 \\qquad\\textup{and}\\qquad \\nabla \\times \\Ef + \\frac{\\partial \\Bf}{\\partial t} = 0 \\]\nThe two-form $\\xi$ will not automatically satisfy $d\\hodge\\xi = 0$ in general though.\nIt would be interesting to investigate whether functions $\\M \\to N$\nexists for a two-dimensional manifold $N$\nsuch that the pullback does satisfy $d\\hodge\\xi = 0$ trivially.\n", "meta": {"hexsha": "f06f7d6321b6448f4fabfc5e054e551f4c8fc6ab", "size": 23963, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/magnetohydrodynamics.tex", "max_stars_repo_name": "ruud-v-a/bscthesis", "max_stars_repo_head_hexsha": "7dfc0003ed842b556d530f2ffb6313856ce17721", "max_stars_repo_licenses": ["CNRI-Python", "Naumen", "Condor-1.1", "MS-PL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/magnetohydrodynamics.tex", "max_issues_repo_name": "ruud-v-a/bscthesis", "max_issues_repo_head_hexsha": "7dfc0003ed842b556d530f2ffb6313856ce17721", "max_issues_repo_licenses": ["CNRI-Python", "Naumen", "Condor-1.1", "MS-PL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/magnetohydrodynamics.tex", "max_forks_repo_name": "ruud-v-a/bscthesis", "max_forks_repo_head_hexsha": "7dfc0003ed842b556d530f2ffb6313856ce17721", "max_forks_repo_licenses": ["CNRI-Python", "Naumen", "Condor-1.1", "MS-PL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.5300970874, "max_line_length": 164, "alphanum_fraction": 0.7096356884, "num_tokens": 7221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3492906463260801}}
{"text": "\\chapter{Introduction} \\label{sec:intro}\n\nLarge databases of images exist in various fields. Indexing and searching these using traditional textual descriptors is generally not effective \\cite[p.657]{forsyth2012}. Visual search offers an alternative to this, by allowing a user to search an image collection using an image as the query, with the aim being to return similar images. This is achieved by generating and comparing numeric, vector based, image descriptors which can be treated similar to words.\n\nThis report presents the implementation of such a system in \\gls{matlab}. Several different methodologies will be considered, and their results compared and contrasted.\n\nIn order to test the system, the Microsoft Research Cambridge, object recognition image database, version 2.0 will be used. This is a freely available image database which is split into 20 rows, with each row containing similar images \\cite{criminisi2004}.\n\nFor the purposes of evaluating this system, similarity will be defined using the 20 categories which the image set is sorted into. This is not ideal since the categories encode level 2 meaning, whilst the descriptors used will perform level 1 operations \\cite{eakins1998}. For this reason, it is not expected that the system will have exceptional performance.\n\nIn order to calculate the distance between descriptors, the $L_2$ norm is used. This distance measure, also known as Euclidean distance, returns the straight line distance between two points in a vector space. It is discussed in greater detail, and performance evaluated against other distance measures, in Appendix \\ref{app:dist-measures}. \n\n\\section{System Design} \\label{sec:sys-design}\nA common framework was used to apply generate descriptors from all of the images, compare them, and display results. This framework uses a \\gls{matlab} function handle to input both the descriptor and distance measure. This method allows the core code-body to be generic, so that in order to run a different test only the external descriptor and/or distance measure functions need to be changed.\n\nA block diagram of the operation of the system is shown in Figure \\ref{fig:sys-operation}. In this figure shaded blocks represent functions necessary for the system's core operation, white blocks represent auxillary functions, and dashed blocks represent functions or data which may be omitted. The arrows show the transitions of data. \n\n\\begin{figure}[ht]\n\t\\centering\n\t\\tikzstyle{generalRect} = [rectangle, rounded corners, minimum width=2cm, minimum height=1cm, text centered, draw=black, fill=black!40]\n\t\\tikzstyle{arrow} = [thick,->,>=stealth]\n\t\\begin{tikzpicture}[node distance=1cm]\n\t\t\\node (compute) [generalRect] {Compute Descriptors};\n\t\t\\node (descriptor) [generalRect, right = of compute] {Descriptor Function};\n\t\t\\node (pca) [generalRect, fill=white, above = 0.5cm of descriptor, dashed] {PCA Function};\n\t\t\\node (compare) [generalRect, below= of compute] {Compare Descriptors};\n\t\t\\node (query) [generalRect, fill=white, left = of compare, dashed] {Query Image};\n\t\t\\node (dist) [generalRect, right = of compare] {Distance Measure};\n\t\t\\node (display) [generalRect, below= of compare, fill=white] {Display Results};\n\t\t\\node (plotPR) [generalRect, below= of display, fill=white] {\\shortstack{Plot Precision-Recall Graph}};\n\t\t\n\t\t\\draw [arrow] (compute) -- (compare);\n\t\t\\draw [arrow, <->] (compute) -- (descriptor);\n\t\t\\draw [arrow, <->, dashed] (pca.west) -- (compute.east);\n\t\t\\draw [arrow] (compare) -- (display);\n\t\t\\draw [arrow, <->] (compare) -- (dist);\n\t\t\\draw [arrow, dashed] (query) -- (compare);\n\t\t\\draw [arrow] (display) -- (plotPR);\n\t\\end{tikzpicture}\n\t\\caption{System design}\n\t\\label{fig:sys-operation}\n\\end{figure}\n\n\\chapter{Description Techniques} \\label{sec:techniques-implemented}\nThis Chapter discusses the different descriptor generation techniques implemented, along with the theory of their operation and the difficulties which were encountered whilst implementing them. Details of how each technique was tested is given in Appendix \\ref{app:test-methodology}.\n\n\\section{Global Colour Histogram} \\label{sec:color-histogram}\nA global colour histogram quantises the RGB space into a series of bins. There are $Q$ bins for each dimension, and therefore $Q^3$ bins for the total image. Each pixel in the image is then sorted into the appropriate bin, and the sum of the bin totals is normalised to 1. This vector histogram, of length $Q^3$, can therefore be used to describe the image. A diagrammatic representation of this technique is shown in Figure \\ref{fig:rgb-hist-diag}. This Figure shows the RGB space quantised with a quantisation level of $Q=2$, yielding $2^2=4$ bins. $P_1$, $P_2$, and $P_3$ represent points in the RGB space which will be quantised to their containing boxes.\n\n\\begin{figure}[ht]\n\t\\centering\n\t\\tdplotsetmaincoords{65}{135}\n\t\\newcommand{\\histbox}[3]\n\t{\n\t\t\\draw[dashed, color=#3] (#1) -- (#2x);\n\t\t\\draw[dashed, color=#3] (#1) -- (#2y);\n\t\t\\draw[dashed, color=#3] (#1) -- (#2z);\n\t\t\\draw[dashed, color=#3] (#2x) -- (#2xy);\n\t\t\\draw[dashed, color=#3] (#2y) -- (#2xy);\n\t\t\\draw[dashed, color=#3] (#2x) -- (#2xz);\n\t\t\\draw[dashed, color=#3] (#2z) -- (#2xz);\n\t\t\\draw[dashed, color=#3] (#2y) -- (#2yz);\n\t\t\\draw[dashed, color=#3] (#2z) -- (#2yz);\n\t\t\\draw[dashed, color=#3] (#2xy) -- (#2);\n\t\t\\draw[dashed, color=#3] (#2xz) -- (#2);\n\t\t\\draw[dashed, color=#3] (#2yz) -- (#2);\n\t}\n\t\\begin{tikzpicture}[scale=2,tdplot_main_coords]\n\t\\coordinate (O) at (0,0,0);\n\t\\tdplotgetpolarcoords{1}{1}{1}\n\t\\tdplotsetcoord{A}{1.73205}{\\tdplotrestheta}{\\tdplotresphi}\n\t\\tdplotgetpolarcoords{2}{1}{1}\n\t\\tdplotsetcoord{B}{2.44949}{\\tdplotrestheta}{\\tdplotresphi}\n\t\\tdplotgetpolarcoords{1}{2}{1}\n\t\\tdplotsetcoord{C}{2.44949}{\\tdplotrestheta}{\\tdplotresphi}\n\t\\tdplotgetpolarcoords{1}{1}{2}\n\t\\tdplotsetcoord{D}{2.44949}{\\tdplotrestheta}{\\tdplotresphi}\n\t\n\t\\tdplotgetpolarcoords{2}{2}{1}\n\t\\tdplotsetcoord{E}{3}{\\tdplotrestheta}{\\tdplotresphi}\n\t\\tdplotgetpolarcoords{2}{1}{2}\n\t\\tdplotsetcoord{F}{3}{\\tdplotrestheta}{\\tdplotresphi}\n\t\\tdplotgetpolarcoords{1}{2}{2}\n\t\\tdplotsetcoord{G}{3}{\\tdplotrestheta}{\\tdplotresphi}\n\t\n\t\\tdplotgetpolarcoords{2}{2}{2}\n\t\\tdplotsetcoord{H}{3.464102}{\\tdplotrestheta}{\\tdplotresphi}\n\t\n\t\\draw[thick,->] (0,0,0) -- (2.25,0,0) node[anchor=north east]{R};\n\t\\draw[thick,->] (0,0,0) -- (0,2.25,0) node[anchor=north west]{G};\n\t\\draw[thick,->] (0,0,0) -- (0,0,2.25) node[anchor=south]{B};\n\t\n\t\n\t\\draw plot [mark=*, mark size=2, mark options={color={rgb:red,1.5;green,0.5;blue,0.5}}] coordinates{(1.5,0.5,0.5)};\n\t\\draw plot [mark=*, mark size=2, mark options={color={rgb:red,0.3;green,1.6;blue,1.7}}] coordinates{(0.3,1.6,1.7)};\n\t\\draw plot [mark=*, mark size=2, mark options={color={rgb:red,1.8;green,1.8;blue,0.2}}] coordinates{(1.8,1.8,0.2)};\n\t\\histbox{O}{A}{blue}\n\t\\histbox{O}{B}{blue}\n\t\\histbox{O}{C}{blue}\n\t\\histbox{O}{D}{blue}\n\t\\histbox{O}{E}{blue}\n\t\\histbox{O}{F}{blue}\n\t\\histbox{O}{G}{blue}\n\t\\histbox{O}{H}{blue}\n\t\n\t\\node[left] at (1.5,0.5,0.5) {$P_1$};\n\t\\node[below] at(0.3,1.6,1.7) {$P_2$};\n\t\\node[right] at(1.8,1.8,0.2) {$P_3$};\n\t\n\t\\end{tikzpicture}\n\t\\caption{Visualisation of RGB histogram}\n\t\\label{fig:rgb-hist-diag}\n\\end{figure}\n\n\nThe implementation of this function was relatively straightforward, since example code for the function had been provided \\cite{collomosse2016}. The only modifications made to the code were to explicitly state the histogram bin edges. This was necessary to provide a robust descriptor since the provided code normalised the histogram to the range of the input. Therefore an image containing only values in one area of the RGB space, would appear similar to an image with uniform distribution. The function is implemented as \\texttt{H =  vs\\_compute\\_rgb\\_histogram(img, Q)} where \\texttt{H} is the descriptor returned, \\texttt{img} is the image input, and \\texttt{Q} is the quantisation level for each image dimension. The only variable parameter is therefore $Q$.\n\n\\section{Gridding} \\label{sec:gridding-concatenation}\nGridding of features allows descriptors to apply locally to parts of an image. The implementation of this is fairly simple in \\gls{matlab}. The image can be split using the native array indexing of \\gls{matlab} to select a subset of the image array,  and the descriptor function can then be applied to each of these sub images. The resultant descriptors are then concatenated into a matrix.\n\nGridding is implemented as \\texttt{F = vs\\_grid(img, h\\_level, v\\_level, compute\\_function)}, where \\texttt{img} is the image input, \\texttt{h\\_level} is the horizontal quantisation level, \\texttt{v\\_level} is the vertical quantisation level and \\texttt{compute\\_function} is the descriptor generation function. This configuration therefore gives two independent variables, \\texttt{h\\_level} and \\texttt{v\\_level}.\n\nHowever, since most of the images in the dataset have an aspect ratio of approximately 1.5:1, it makes sense to set the vertical quantisation level to 1.5 times the horizontal quantisation level. Therefore the overall quantisation level, $Q$ can be defined, where \\texttt{h\\_level = ceil(1.5*Q)}, and \\texttt{v\\_level = Q}.\n\n\\section{Edge Orientation Histogram} \\label{sec:texture-histogram}\nTexture is an important concept in computer vision, but is difficult to define. Texture loosely corresponds to a repeating pattern of edge characteristics, examples of which would include grass pebbles, and hair \\cite[p. 194]{forsyth2012}.\n\nOne method of creating a texture based descriptor is to use an edge orientation histogram. This works as follows:\n\\begin{enumerate}\n\t\\item Edges are detected in the image.\n\t\\item An estimation of the orientation of each edge is calculated.\n\t\\item A histogram is created of the edge orientations.\n\\end{enumerate}\n\nThis process is implemented using two functions: an edge orientation function, and a histogram generation function. The edge orientation function returns a two dimensional matrix where each element contains a value corresponding to an estimate of the edge orientation at that location. This estimate is in the range $-\\pi$ to $+\\pi$, but is normalised to $0$ to $1$. Weak edges are set to a normalised value of 0.5, corresponding to \\SI{0}{\\radian}.\n\nIn order to perform the edge detection, and edge angle estimation, the Sobel operator is used \\cite{sobel2015}. The Sobel operator is formed of two kernels which are convolved with input image in order to perform edge detection in the x and y directions respectively. The kernels are defined in Equation \\ref{eq:sobel-kernels}. \n\n\\begin{equation}\n\tK_x = \n\t\\begin{bmatrix}\n\t1 & 0 & -1 \\\\\n\t2 & 0 & -2 \\\\\n\t1 & 0 & -1 \\\\\n\t\\end{bmatrix}\n\tK_y = \n\t\\begin{bmatrix}\n\t1 & 2 & 1 \\\\\n\t0 & 0 & 0 \\\\\n\t-1 & -2 & -1 \\\\\n\t\\end{bmatrix}\n\t\\label{eq:sobel-kernels}\n\\end{equation}\n\nThe edge magnitude and angle are calculated as described in Equations \\ref{eq:sobel-mag} and \\ref{eq:sobel-ang} respectively. It should be noted that the operators in these equations apply on an element-by-element basis, not to the matrices as a whole. In addition, the $K_y$ value is inverted in order to allow the performance to match the \\gls{matlab} library function \\texttt{imgradient}, this allows for easier testing. The pixels with edge magnitudes above a certain threshold are passed to the histogram generation function.\n\\begin{equation}\n\\text{Mag} = \\sqrt{{K_x}^2 + {K_y}^2}\n\\label{eq:sobel-mag}\n\\end{equation}\n\\begin{equation}\n\\theta = \\atantwo(-K_y, K_x)\n\\label{eq:sobel-ang}\n\\end{equation}\n\nThe edge orientation function is implemented as \\texttt{F = vs\\_edge\\_detect(img, compute\\_function, strength)} where \\texttt{F} is the descriptor returned, \\texttt{img} is the image input, \\texttt{compute\\_function} is the histogram generation function, and \\texttt{strength} is the minimum edge strength to consider (range 0--1).\n\nThe histogram generation function is \\texttt{H = vs\\_compute\\_histogram(img, Q)} where \\texttt{H} is the histogram returned, \\texttt{img} is the image input and \\texttt{Q} is the quantisation factor. When \\texttt{vs\\_compute\\_histogram} is used as the \\texttt{compute\\_function} in \\texttt{vs\\_edge\\_detect}, the system can produce an edge orientation histogram, with two independent parameters. These parameters determine the minimum strength edge to consider, as well as the quantisation level of the histogram. These parameters will be referred to as $E$ and $Q$ respectively.\n\nAdditionally, since texture is an inherently local feature, the image will be gridded. The descriptor function handle is therefore : \\texttt{@(x)vs\\_grid(x, v\\_level, h\\_level, @(x)vs\\_edge\\_detect(x, @(x)vs\\_compute\\_histogram(x,Q),E))}.\n\n\\section{Concatenation of Descriptors} \\label{sec:conc-desc}\nDescriptors focusing upon an individual aspect of an image, such as colour or texture have already been discussed, as well as how the can be applied to multiple sections of an image rather than globally.\n\nIt stands to reason therefore that multiple descriptors could be combined to produce a descriptor of even greater effectiveness, such as a combination of an RGB histogram and a texture histogram. This is possible in \\gls{matlab} using the native array indexing interface, but it is clearer to use the \\texttt{horzcat} function.\n\nA combined descriptor can therefore be invoked using the function \\texttt{@(x)horzcat( func\\_1(x) .* M, func\\_2(x))} where \\texttt{texture\\_func(x)} and \\texttt{color\\_func(x)} are function handles for two descriptor functions with a single parameter, \\texttt{x} for the input image. The only other parameter in this function is \\texttt{M}. \\texttt{M} defines a weighting factor between the two descriptors, and can be used to give a greater weighting to one over the other. This works by using a multiplier value to either spread all of the values in the descriptor further apart, or bring them closer together.\n\n\\chapter{Experimental Results} \\label{sec:results}\n\nIn order to evaluate the performance of each descriptor, two test images have been chosen from the data set: 9\\_23\\_s and 13\\_1\\_s. These images have been chosen because they represent two contrasting examples of what could be presented to the algorithm. Image 9\\_23\\_s shows a sheep in a field. This image has two strongly dominant colours: the green of the grass, and the cream of the sheep's wool, as well as two regions of largely uniform texture: the sheep's body, and the grass. Image 13\\_1\\_s strongly contrasts this. This image shows a collection of differently coloured books on a shelf. The image therefore contains a large variety of colours distributed around the image. In addition to this the transitions between the books, as well as the text on the spine of the books means that a large amount of varied texture is distributed across the image.\n\nThe fact that these images contrast in many different ways means that they should be ideal to evaluate the performance of each descriptor in a fair way, as well as determine the optimum parameters for each descriptor function. The performance of the descriptors across the wider images in the dataset will then be presented in Section \\ref{sec:results}.\n\nIn order to evaluate performance, a precision-recall characteristic is plotted for each test. This characteristic is a plot showing the proportion of the returned results which have been relevant (precision), vs the number of relevant results returned (recall). The ideal precision-recall characteristic would be a horizontal line at precision = 1, a system which produced this characteristic would return all the relevant images, and none of the irrelevant images. Most practical systems produce a characteristic which slopes from the top left to the bottom right, this occurs because systems first return the results they are most sure about. These results are likely to be correct, and so precision will be high, but since not many results have yet been returned, recall will be low. As the system returns an increasing number of results, an increasing number of irrelevant results will be returned also, causing precision to decrease as recall increases.\n\n\\section{Global Colour Histogram} \\label{sec:global-colour-histogram-results}\nThe global colour descriptor has one parameter the quantisation level, $Q$, which produces a descriptor of length $Q^3$, as discussed in Section \\ref{sec:color-histogram}.\n\nIn order to analyse the effect of quantisation level on performance, results will be generated for various values of $Q$, and the performance of each image analysed for each test value. The expected result is that higher values of $Q$ will produce better results, up to a certain point, after which performance will decrease. This should happen because at very high quantisation levels values, there are too many possible bins, and as such nominally similar colours will be sorted into different bins. Since each bin is a different dimension in the descriptor, they will not therefore be considered similar by the distance measure function.\n\n\\begin{figure}[ht]\n\t\\begin{minipage}[]{0.3\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width = 0.9\\linewidth]{figs/msrc/9_23_s}\n\t\t\\subcaption{Query image}\n\t\\end{minipage}\n\t\\begin{minipage}[]{0.7\\linewidth}\n\t\t\\centering\n\t\t\\begin{tikzpicture}\n\t\t\\prplot{data/global_colour_hist/9_23_s/pr_2.txt}{Q=2}\n\t\t\\prplotadd{data/global_colour_hist/9_23_s/pr_3.txt}{Q=3}\n\t\t\\prplotadd{data/global_colour_hist/9_23_s/pr_4.txt}{Q=4}\n\t\t%\\prplotadd{data/global_colour_hist/9_23_s/pr_5.txt}{Q=5}\n\t\t\\prplotadd{data/global_colour_hist/9_23_s/pr_6.txt}{Q=6}\n\t\t%\\prplotadd{data/global_colour_hist/9_23_s/pr_7.txt}{Q=7}\n\t\t\\prplotadd{data/global_colour_hist/9_23_s/pr_8.txt}{Q=8}\n\t\t%\\prplotadd{data/global_colour_hist/9_23_s/pr_9.txt}{Q=9}\n\t\t\\prplotadd{data/global_colour_hist/9_23_s/pr_10.txt}{Q=10}\n\t\t\\prplotclose\n\t\t\\end{tikzpicture}\n\t\t\\subcaption{Resultant graph}\n\t\\end{minipage}\n\t\\caption{Global colour histogram results for query image 9\\_23\\_s}\n\t\\label{fig:colour-hist-sheep}\n\\end{figure}\n\n\\begin{figure}[ht]\n\t\\begin{minipage}[]{0.3\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width = 0.9\\linewidth]{figs/msrc/13_1_s}\n\t\t\\subcaption{Query image}\n\t\\end{minipage}\n\t\\begin{minipage}[]{0.7\\linewidth}\n\t\t\\centering\n\t\t\\begin{tikzpicture}\n\t\t\\prplot{data/global_colour_hist/13_1_s/pr_2.txt}{Q=2}\n\t\t\\prplotadd{data/global_colour_hist/13_1_s/pr_3.txt}{Q=3}\n\t\t\\prplotadd{data/global_colour_hist/13_1_s/pr_4.txt}{Q=4}\n\t\t%\\prplotadd{data/global_colour_hist/13_1_s/pr_5.txt}{Q=5}\n\t\t\\prplotadd{data/global_colour_hist/13_1_s/pr_6.txt}{Q=6}\n\t\t%\\prplotadd{data/global_colour_hist/13_1_s/pr_7.txt}{Q=$}\n\t\t\\prplotadd{data/global_colour_hist/13_1_s/pr_8.txt}{Q=8}\n\t\t%\\prplotadd{data/global_colour_hist/13_1_s/pr_9.txt}{Q=9}\n\t\t\\prplotadd{data/global_colour_hist/13_1_s/pr_10.txt}{Q=10}\n\t\t\\prplotclose\n\t\t\\end{tikzpicture}\n\t\t\\subcaption{Resultant graph}\n\t\\end{minipage}\n\t\\caption{Global colour histogram results for query image 13\\_1\\_s}\n\t\\label{fig:colour-hist-books}\n\\end{figure}\n\nThe results shown in Figures \\ref{fig:colour-hist-sheep} and \\ref{fig:colour-hist-books} match expectations suggesting that a very low quantisation value does not deliver good results, yet performance also drops off at higher quantisation levels. Both test images suggest that a quantisation level of $Q=4$, yielding $64$ bins, gives the best result, since the line joining these data points is closest to the top right hand corner.\n\nThe results also show that query image 13\\_1\\_s performs better than 9\\_23\\_s. The reason for this is likely due to the fact that 13\\_1\\_s has a much more varied colour distribution, allowing it to have a much more unique histogram signature. This means that similar images can be better matched. In contrast to this, the green field will dominate the histogram of image 9\\_23\\_s meaning the system may confuse it with other images containing a green background, such as those of other farm animals in a field.\n\n\\FloatBarrier\n\\section{Gridding} \\label{sec:gridding-results}\n\nAs discussed in Section \\ref{sec:gridding-concatenation}, the independent parameters for the gridding function can be reduced to a single quantisation factor $Q$. In a similar manner to that of Section \\ref{sec:global-colour-histogram-results} the optimum quantisation factor will be determined by computing descriptors for various values of $Q$ and then, using the two test images, determining which has best results. \n\nThe same effect of increasing Quantisation factor as experienced with the global colour histogram is expected. Increasing the value should increase performance up to a maximum, at this point the performance should decrease with increasing quantisation factor. One reason for this is that tighter grids mean that small movements in the object could potentially result in the image being quantised in a very different way, meaning visually similar images would be distant from each other in the quantised space.\n\n\n\\begin{figure}[ht]\n\t\\begin{minipage}[]{0.3\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width = 0.9\\linewidth]{figs/msrc/9_23_s}\n\t\t\\subcaption{Query image}\n\t\t\\label{fig:grid-color-sheep-img}\n\t\\end{minipage}\n\t\\begin{minipage}[]{0.7\\linewidth}\n\t\t\\centering\n\t\t\\begin{tikzpicture}\n\t\t\\prplot{data/gridding/color_hist/9_23_s/pr_1.txt}{Q=1}\n\t\t\\prplotadd{data/gridding/color_hist/9_23_s/pr_2.txt}{Q=2}\n\t\t\\prplotadd{data/gridding/color_hist/9_23_s/pr_3.txt}{Q=3}\n\t\t\\prplotadd{data/gridding/color_hist/9_23_s/pr_4.txt}{Q=4}\n\t\t\\prplotadd{data/gridding/color_hist/9_23_s/pr_8.txt}{Q=8}\n\t\t\\prplotadd{data/gridding/color_hist/9_23_s/pr_15.txt}{Q=15}\n\t\t\\prplotadd{data/global_colour_hist/9_23_s/pr_4.txt}{No grid}\n\n\t\t\\prplotclose\n\t\t\\end{tikzpicture}\n\t\t\\subcaption{Resultant graph}\n\t\t\\label{fig:grid-color-sheep-graph}\n\t\\end{minipage}\n\t\\caption{Gridded global colour histogram results for query image 9\\_23\\_s}\n\t\\label{fig:grid-color-sheep}\n\\end{figure}\n\n\n\\begin{figure}[ht]\n\t\\begin{minipage}[]{0.3\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width = 0.9\\linewidth]{figs/msrc/13_1_s}\n\t\t\\subcaption{Query image}\n\t\t\\label{fig:grid-color-books-img}\n\t\\end{minipage}\n\t\\begin{minipage}[]{0.7\\linewidth}\n\t\t\\centering\n\t\t\\begin{tikzpicture}\n\t\t\\prplot{data/gridding/color_hist/13_1_s/pr_1.txt}{Q=1}\n\t\t\\prplotadd{data/gridding/color_hist/13_1_s/pr_2.txt}{Q=2}\n\t\t\\prplotadd{data/gridding/color_hist/13_1_s/pr_3.txt}{Q=3}\n\t\t\\prplotadd{data/gridding/color_hist/13_1_s/pr_4.txt}{Q=4}\n\t\t\\prplotadd{data/gridding/color_hist/13_1_s/pr_8.txt}{Q=8}\n\t\t\\prplotadd{data/gridding/color_hist/13_1_s/pr_15.txt}{Q=15}\n\t\t\\prplotadd{data/global_colour_hist/13_1_s/pr_4.txt}{No grid}\n\t\t\n\t\t\\prplotclose\n\t\t\\end{tikzpicture}\n\t\t\\subcaption{Resultant graph}\n\t\t\\label{fig:grid-color-books-graph}\n\t\\end{minipage}\n\t\\caption{Gridded global colour histogram results for query image 13\\_1\\_s}\n\t\\label{fig:grid-color-books}\n\\end{figure}\n\nFigures \\ref{fig:grid-color-sheep} and \\ref{fig:grid-color-books} show the results of the gridding process.\n\nFigure \\ref{fig:grid-color-sheep} shows little variation across gridding quantisation levels, this is likely due to the fact that the image has only two dominant colours, so all grids have similar colour histograms. Gridding does, in the general case, show slight performance improvement with this image however. Notably increasing precision values for higher recall levels.\n\nFigure \\ref{fig:grid-color-books} on the other hand shows great variation in the result with grid size. Increasing the grid quantisation level to 2 greatly increases the performance up to a recall of around 0.4, and a grid quantisation level of 1 also increases the performance by a large amount also. In addition to this, much higher quantisation steps, such as 8 and 15 show greatly decreased performance.\n\nThe optimum quantisation factor is therefore $Q=2$, yielding \\texttt{h\\_level = 3}, and \\texttt{v\\_level = 2} using the formulae defined in Section \\ref{sec:gridding-concatenation}.\n\n\n\\FloatBarrier\n\\section{Edge Orientation Histogram} \\label{sec:texture-histogram-results}\nAs discussed in Section \\ref{sec:texture-histogram}, the gridded edge orientation histogram implementation has two variable parameters, $E$ and $Q$ (setting the grid quantisation factors to the optimised values from Section \\ref{sec:gridding-results}). Evaluating the effect of changing both together is computationally expensive, and the results are hard to visualise, since a 3-axis plot would be required. Therefore the two variables will be evaluated separately.\n\nInitially the effect of changing the histogram quantisation level, $Q$, will be investigated using a constant $E$ of $0$. This will leave all edges in the image for the consideration of the histogram. The expected result is similar to increasing the quantisation level of the RGB histogram -- increasing $Q$ will increase performance up to a point, but increasing past that point will result in poorer results\n\n\\begin{figure}[ht]\n\t\\begin{minipage}[]{0.3\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width = 0.9\\linewidth]{figs/msrc/9_23_s}\n\t\t\\subcaption{Query image}\n\t\\end{minipage}\n\t\\begin{minipage}[]{0.7\\linewidth}\n\t\t\\centering\n\t\t\\begin{tikzpicture}\n\t\t\\prplot{data/grid_text_hist/E_0/9_23_s/pr_4.txt}{Q=4}\n\t\t\\prplotadd{data/grid_text_hist/E_0/9_23_s/pr_8.txt}{Q=8}\n\t\t\\prplotadd{data/grid_text_hist/E_0/9_23_s/pr_10.txt}{Q=10}\n\t\t\\prplotadd{data/grid_text_hist/E_0/9_23_s/pr_12.txt}{Q=12}\n\t\t\\prplotadd{data/grid_text_hist/E_0/9_23_s/pr_15.txt}{Q=16}\n\t\t\\prplotadd{data/grid_text_hist/E_0/9_23_s/pr_18.txt}{Q=18}\n\t\t\\prplotadd{data/grid_text_hist/E_0/9_23_s/pr_20.txt}{Q=20}\n\t\t\\prplotclose\n\t\t\\end{tikzpicture}\n\t\t\\subcaption{Resultant graph}\n\t\\end{minipage}\n\t\\caption{Gridded texture histogram results for query image 9\\_23\\_s, with $E=0$}\n\t\\label{fig:grid-text-sheep}\n\\end{figure}\n\n\\begin{figure}[ht]\n\t\\begin{minipage}[]{0.3\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width = 0.9\\linewidth]{figs/msrc/13_1_s}\n\t\t\\subcaption{Query image}\n\t\\end{minipage}\n\t\\begin{minipage}[]{0.7\\linewidth}\n\t\t\\centering\n\t\t\\begin{tikzpicture}\n\t\t\\prplot{data/grid_text_hist/E_0/13_1_s/pr_4.txt}{Q=4}\n\t\t\\prplotadd{data/grid_text_hist/E_0/13_1_s/pr_8.txt}{Q=8}\n\t\t\\prplotadd{data/grid_text_hist/E_0/13_1_s/pr_10.txt}{Q=10}\n\t\t\\prplotadd{data/grid_text_hist/E_0/13_1_s/pr_12.txt}{Q=12}\n\t\t\\prplotadd{data/grid_text_hist/E_0/13_1_s/pr_15.txt}{Q=16}\n\t\t\\prplotadd{data/grid_text_hist/E_0/13_1_s/pr_18.txt}{Q=18}\n\t\t\\prplotadd{data/grid_text_hist/E_0/13_1_s/pr_20.txt}{Q=20}\n\t\t\\prplotclose\n\t\t\\end{tikzpicture}\n\t\t\\subcaption{Resultant graph}\n\t\\end{minipage}\n\t\\caption{Gridded texture histogram results for query image 13\\_1\\_s, with $E=0$}\n\t\\label{fig:grid-text-books}\n\\end{figure}\n\nFigure \\ref{fig:grid-text-sheep} shows that for the sheep image, there is very little difference in performance with quantisation levels greater than approximately 4. Figure \\ref{fig:grid-text-books} shows that for the books, on the other hand, performance is strongly dependant on quantisation level. Higher quantisation levels continue to improve performance, up to approximately $Q=16$, after this point performance decreases.\n\n\\begin{figure}[ht]\n\t\\begin{minipage}[]{0.3\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width = 0.9\\linewidth]{figs/msrc/9_23_s}\n\t\t\\subcaption{Query image}\n\t\\end{minipage}\n\t\\begin{minipage}[]{0.7\\linewidth}\n\t\t\\centering\n\t\t\\begin{tikzpicture}\n\t\t\\prplot{data/grid_text_hist/Q_16/9_23_s/pr_0.txt}{E=0}\n\t\t\\prplotadd{data/grid_text_hist/Q_16/9_23_s/pr_1.txt}{E=0.1}\n\t\t\\prplotadd{data/grid_text_hist/Q_16/9_23_s/pr_2.txt}{E=0.2}\n\t\t\\prplotadd{data/grid_text_hist/Q_16/9_23_s/pr_3.txt}{E=0.3}\n%\t\t\\prplotadd{data/grid_text_hist/Q_16/9_23_s/pr_4.txt}{E=0.4}\n\t\t\\prplotadd{data/grid_text_hist/Q_16/9_23_s/pr_5.txt}{E=0.5}\n%\t\t\\prplotadd{data/grid_text_hist/Q_16/9_23_s/pr_6.txt}{E=0.6}\n\t\t\\prplotadd{data/grid_text_hist/Q_16/9_23_s/pr_7.txt}{E=0.7}\n%\t\t\\prplotadd{data/grid_text_hist/Q_16/9_23_s/pr_8.txt}{E=0.8}\n\t\t\\prplotadd{data/grid_text_hist/Q_16/9_23_s/pr_9.txt}{E=0.9}\n%\t\t\\prplotadd{data/grid_text_hist/Q_16/9_23_s/pr_10.txt}{E=1.0}\n\t\t\\prplotclose\n\t\t\\end{tikzpicture}\n\t\t\\subcaption{Resultant graph}\n\t\\end{minipage}\n\t\\caption{Gridded texture histogram results for query image 9\\_23\\_s, with $Q=16$}\n\t\\label{fig:grid-text-sheep-q16}\n\\end{figure}\n\n\\begin{figure}[ht]\n\t\\begin{minipage}[]{0.3\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width = 0.9\\linewidth]{figs/msrc/13_1_s}\n\t\t\\subcaption{Query image}\n\t\\end{minipage}\n\t\\begin{minipage}[]{0.7\\linewidth}\n\t\t\\centering\n\t\t\\begin{tikzpicture}\n\t\t\\prplot{data/grid_text_hist/Q_16/13_1_s/pr_0.txt}{E=0}\n\t\t\\prplotadd{data/grid_text_hist/Q_16/13_1_s/pr_1.txt}{E=0.1}\n\t\t\\prplotadd{data/grid_text_hist/Q_16/13_1_s/pr_2.txt}{E=0.2}\n\t\t\\prplotadd{data/grid_text_hist/Q_16/13_1_s/pr_3.txt}{E=0.3}\n%\t\t\\prplotadd{data/grid_text_hist/Q_16/13_1_s/pr_4.txt}{E=0.4}\n\t\t\\prplotadd{data/grid_text_hist/Q_16/13_1_s/pr_5.txt}{E=0.5}\n%\t\t\\prplotadd{data/grid_text_hist/Q_16/13_1_s/pr_6.txt}{E=0.6}\n\t\t\\prplotadd{data/grid_text_hist/Q_16/13_1_s/pr_7.txt}{E=0.7}\n%\t\t\\prplotadd{data/grid_text_hist/Q_16/13_1_s/pr_8.txt}{E=0.8}\n\t\t\\prplotadd{data/grid_text_hist/Q_16/13_1_s/pr_9.txt}{E=0.9}\n%\t\t\\prplotadd{data/grid_text_hist/Q_16/13_1_s/pr_10.txt}{E=1.0}\n\t\t\\prplotclose\n\t\t\\end{tikzpicture}\n\t\t\\subcaption{Resultant graph}\n\t\\end{minipage}\n\t\\caption{Gridded texture histogram results for query image 13\\_1\\_s, with $Q=16$}\n\t\\label{fig:grid-text-books-q16}\n\\end{figure}\n\nFigures \\ref{fig:grid-text-sheep-q16} and \\ref{fig:grid-text-books-q16} show the result of varying $E$, whilst keeping $Q$ at a constant value of $16$. The results are interesting. For the bookshelves, increasing $E$ above $0$ improves performance up to approximately $E=0.3$, however, for the sheep increasing $E$ above $0$ greatly hinders performance. This is likely due to the fact that whilst the books have lots of strong edges (at the edges of the books), which will remain with increasing values of $E$, the sheep image likely lacks these strong edges, and so increasing $E$ removes almost all of the relevant edges from the generated descriptor.\n\n\\FloatBarrier\n\\section{Concatenation of Descriptors} \\label{sec:conc-desc-results}\nSections \\ref{sec:gridding-results} and \\ref{sec:texture-histogram-results} demonstrate the effectiveness of gridded colour histogram and texture descriptors. It stands to reason therefore that these descriptors could be combined to produce a descriptor of even greater effectiveness. This is possible using the methodology described in Section \\ref{sec:conc-desc}.\n\nIn order to combine the gridded texture and gridded global colour histogram results, the parameters of these functions which were found to be optimal in Sections \\ref{sec:gridding-results} and \\ref{sec:texture-histogram-results} will be used. The only free parameter of the concatenation function is therefore $M$. $M$ is a multiplier that is applied to the texture function in order to adjust the weighting between the texture and colour descriptors. When $M$ is $1$ the two descriptors are equally weighted, however since the colour descriptor is 4 times as long as the texture descriptor (a 64 bin histogram, vs and 8 bin histogram), it is effectively weighted more highly since there are many more dimensions in which values can be distant. Whilst weighting of $M=4$ should therefore make up for this difference in descriptor length, a different value may provide better results.\n\n\\begin{figure}[ht]\n\t\\begin{minipage}[]{0.3\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width = 0.9\\linewidth]{figs/msrc/9_23_s}\n\t\t\\subcaption{Query image}\n\t\\end{minipage}\n\t\\begin{minipage}[]{0.7\\linewidth}\n\t\t\\centering\n\t\t\\begin{tikzpicture}\n\t\t\\prplot{data/grid_text_hist/Q_16/9_23_s/pr_0.txt}{Texture only}\n\t\t\\prplotadd{data/gridding/color_hist/9_23_s/pr_2.txt}{Colour only}\n\t\t\\prplotadd{data/concat/9_23_s/pr_1.txt}{W = 1}\n\t\t\\prplotadd{data/concat/9_23_s/pr_4.txt}{W = 4}\n\t\t\\prplotadd{data/concat/9_23_s/pr_10.txt}{W = 10}\n\t\t\\prplotclose\n\t\t\\end{tikzpicture}\n\t\t\\subcaption{Resultant graph}\n\t\\end{minipage}\n\t\\caption{Concatenated descriptor results for query image 9\\_23\\_s}\n\t\\label{fig:concat-sheep}\n\\end{figure}\n\n\\begin{figure}[ht]\n\t\\begin{minipage}[]{0.3\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width = 0.9\\linewidth]{figs/msrc/13_1_s}\n\t\t\\subcaption{Query image}\n\t\\end{minipage}\n\t\\begin{minipage}[]{0.7\\linewidth}\n\t\t\\centering\n\t\t\\begin{tikzpicture}\n\t\t\\prplot{data/grid_text_hist/Q_16/13_1_s/pr_0.txt}{Texture only}\n\t\t\\prplotadd{data/gridding/color_hist/13_1_s/pr_2.txt}{Colour only}\n\t\t\\prplotadd{data/concat/13_1_s/pr_1.txt}{W = 1}\n\t\t\\prplotadd{data/concat/13_1_s/pr_4.txt}{W = 4}\n\t\t\\prplotadd{data/concat/13_1_s/pr_10.txt}{W = 10}\n\t\t\\prplotclose\n\t\t\\end{tikzpicture}\n\t\t\\subcaption{Resultant graph}\n\t\\end{minipage}\n\t\\caption{Concatenated descriptor results for query image 13\\_1\\_s}\n\t\\label{fig:concat-books}\n\\end{figure}\n\nFigure \\ref{fig:concat-sheep} shows that the concatenated descriptor remains very close to the plot of only the RGB histogram for all values of $W$ plotted. This implies that all of the descriptors are very close in the texture plot, leading to the colour plot dominating the results.\n\nFigure \\ref{fig:concat-books} on the other hand shows that the concatenated descriptor does vary between the two plots with differing values of $W$. This implies that both descriptors are discriminative. The results show that at a value of $W=1$, the results are close to the RGB histogram, but at $W=10$, the results are closer to the edge orientation histogram. A value of $W=4$ provides a compromise between the two as expected. The results are poorer than the RGB histogram for this particular query image, but this is unlikely to hold true for all query images since some images will likely be described by colour well, and others by texture well.\n\n\\section{Overall Results} \\label{sec:overall-results}\n\nFollowing the characterisation each algorithm, discussed in the previous parts of this section, it has been possible to test the performance of each descriptor against the entire database of images. This is achieved by calculating \\gls{map}. \\gls{map} is a single numeric measure for determining the performance of a descriptor across a dataset. Is is the mean of \\gls{ap}, which is defined in Equation \\ref{eq:map}. In this equation P$(i)$ represents the precision at that value of $i$, and Rel$(i)$ is $1$ if the result is relevant, or $0$ if it is not.\n\n\\begin{equation}\n\\text{\\glsentryshort{ap}} = \\frac{\\sum_{i=1}^{n} \\left( \\text{P}(i) \\times \\text{Rel}(i) \\right) }{\\sum_{i=1}^{n}  \\text{Rel}(i) } \\label{eq:map}\n\\end{equation}\n\nTable \\ref{tbl:map-stats} tabulates the \\gls{map} statistics for all images in the dataset, both within each category, as well as globally. These results show \\gls{map} across the entire dataset, so a lot of the numbers are low. The reason for this is that whilst the images have similar Level 2 content, some of the images are very different in terms of colour and texture content. In order to account for this, Table \\ref{tbl:map-stats-at-10} tabulates \\gls{map} statistics for the first 10 relevant recalled images. This data removes the effect of the aforementioned `outlier' images in each category, and better demonstrates how well each type of image content responds to each descriptor.\n\nThe results in Table \\ref{tbl:map-stats-at-10} show that the image sets respond well to some descriptors, and some respond poorly. One example of this is category 4, where the \\gls{map} is 0.71 for the edge orientation histogram, but 0.25 and 0.44 for the global colour histogram and gridded global colour histogram. This can be explained by looking at the type of image category 4 is. Category 4 contains images of aeroplanes. Almost all of these images have a smooth aeroplane body in the middle of the image, with a clear sky at the top, and plain grass at the bottom. This distinctive texture signature is what allows this high \\gls{ap} figure. Other image sets which respond particularly well to the edge orientation histogram are categories 7 and 13 respectively. Category 7 contains cars, and category 13 books on shelves, both of these have distinct texture signatures.\n\nIn general, most of the categories responded better to the gridded colour histogram than the global colour histogram. This is expected since encoding the spatial aspect of the colour data should allow for a more discriminative descriptor. A notable example which does not is category 18. Category 18 is a series of images which all contain water, however the water is in a different location in almost every image, this kind of spatial variance cannot be encoded in the gridded descriptor, so it performs poorly.\n\nTwo categories which responded particularly well to the colour descriptor are categories 2 and 13. These are images of trees, mostly on a background of a washed-out sky, and bookshelves of colourful books respectively. Both images likely work well with this descriptor because they contain a variety of colours which are both common across most of the images, and distinctive in the image set itself. \n\nIn general, concatenation of colour and texture descriptors improved performance over the individual descriptors. The cases where they did not are cases where one descriptor had a much greater performance over the other, such as category 4, which responded particularly well to the texture descriptor and category 2 which responded particularly well to the colour descriptors. One example of a category which showed great improvement with descriptor concatenation are categories 7 and 10. These categories contain differently coloured cars in different orientations and differently coloured flowers, with varying shapes. Concatenation helps with the cars because the variance of colour across the set means that the similarly coloured cars strongly match each other in a colour histogram, but all others are distant, whereas all of the cars are likely moderate matches with the edge orientation histogram. The flowers have a similar effect.\n\nOne category which performed particularly poorly in all cases is category 16. This category contains photographs of dogs, of various sizes and colours, all taken from different camera angles and on different backgrounds. This is an example of Level 2 concepts which do not translate well at all to Level 1 attempts at interpretation.\n\n\n\\begin{table}[ht]\n\t\\rowcolors{2}{gray!25}{white}\n\t\\caption{\\glsentryshort{map} statistics for all methods and categories}\n\t\\label{tbl:map-stats}\n\t\\centering\n\t\\pgfplotstableset{ % Makes bold a whole row of a table\n\t\thighlightrow/.style={\n\t\t\tpostproc cell content/.append code={\n\t\t\t\t\\count0=\\pgfplotstablerow\n\t\t\t\t\\advance\\count0 by1\n\t\t\t\t\\ifnum\\count0=#1\n\t\t\t\t\\pgfkeysalso{@cell content/.add={$\\bf}{$}}\n\t\t\t\t\\fi\n\t\t\t},\n\t\t},\n\t}\n\t\\pgfplotstabletypeset[\n\tcol sep=comma,\n\tstring type,\n\tcolumns/set/.style={column name={\\textbf{Image category}}, column type={r}},\n\tcolumns/gch/.style={column name={\\textbf{\\shortstack{Global colour\\\\histogram}}}, column type={r}},\n\tcolumns/gridch/.style={column name={\\textbf{\\shortstack{Gridded\\\\ colour\\\\histogram}}}, column type={r}},\n\tcolumns/eoh/.style={column name={\\textbf{\\shortstack{Gridded\\\\edge orienatation\\\\histogram}}}, column type={r}},\n\tcolumns/concat/.style={column name={\\textbf{\\shortstack{Concatenated\\\\descriptors}}}, column type={r}},\n\tevery head row/.style={before row=\\toprule, after row=\\midrule},\n\tevery last row/.style={after row=\\bottomrule},\n\thighlightrow={21},\n\t]{data/global_stats/map.txt}\n\\end{table}\n\n\\begin{table}[ht]\n\t\\rowcolors{2}{gray!25}{white}\n\t\\caption{\\glsentryshort{map} statistics for first 10 images in each set, over all methods and categories}\n\t\\label{tbl:map-stats-at-10}\n\t\\centering\n\t\\pgfplotstableset{ % Makes bold a whole row of a table\n\t\thighlightrow/.style={\n\t\t\tpostproc cell content/.append code={\n\t\t\t\t\\count0=\\pgfplotstablerow\n\t\t\t\t\\advance\\count0 by1\n\t\t\t\t\\ifnum\\count0=#1\n\t\t\t\t\\pgfkeysalso{@cell content/.add={$\\bf}{$}}\n\t\t\t\t\\fi\n\t\t\t},\n\t\t},\n\t}\n\t\\pgfplotstabletypeset[\n\tcol sep=comma,\n\tstring type,\n\tcolumns/set/.style={column name={\\textbf{Image category}}, column type={r}},\n\tcolumns/gch/.style={column name={\\textbf{\\shortstack{Global colour\\\\histogram}}}, column type={r}},\n\tcolumns/gridch/.style={column name={\\textbf{\\shortstack{Gridded\\\\ colour\\\\histogram}}}, column type={r}},\n\tcolumns/eoh/.style={column name={\\textbf{\\shortstack{Gridded\\\\edge orienatation\\\\histogram}}}, column type={r}},\n\tcolumns/concat/.style={column name={\\textbf{\\shortstack{Concatenated\\\\descriptors}}}, column type={r}},\n\tevery head row/.style={before row=\\toprule, after row=\\midrule},\n\tevery last row/.style={after row=\\bottomrule},\n\thighlightrow={21},\n\t]{data/global_stats/map_at_10.txt}\n\\end{table}\n\n\\chapter{Conclusion} \\label{sec:conclusion}\nThis report presents several methods of generating descriptors for images, and uses test data to  set their adjustable parameters, the results of which is presented in Section \\ref{sec:results}. The overall results show that the \\gls{matlab} system is capable of performing with a reasonable \\gls{map} over the first 10 images in each set. However performance does suffer when considered over the whole dataset. Overall the concatenated descriptors perform best over the entire dataset with a \\gls{map} of 0.21, or 0.36 if only the first 10 images are considered. A global colour histogram performs most poorly overall with a \\gls{map} of 0.16 over the entire dataset, or 0.26 if only the first 10 images are considered.\n\nThe Appendices present further results which extend the investigation in areas other than investigation of different descriptors. Appendix \\ref{app:pca} investigates \\gls{pca} and shows how descriptors can be made much more compact without impact on performance. The investigated descriptor, a gridded colour histogram, was able to be reduced to 26\\% of it's original size without noticeable performance impact.\n\nAppendix \\ref{app:dist-measures} investigates various distance measures which can be used to compare descriptors and tests their relative performance. The $L_2$ norm, which has been used throughout the remainder of this investigation was found to be the strongest overall performer.\n\nIn addition Appendix \\ref{app:test-methodology} presents the test methodology for verification of the functionality of the descriptor generation functions.\n\nTo conclude the system presented by the report is a modular and extensible visual search system, with characterised performance, and scope to be extended beyond its current functionality. ", "meta": {"hexsha": "f275e3df13df30f69c79fc874f5fc60452413810", "size": 42246, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/docs/body.tex", "max_stars_repo_name": "joshtyler/visual-search", "max_stars_repo_head_hexsha": "63fd7512f18596d5bd9475c7624b631a2205bcb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-12-05T13:05:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-13T22:42:39.000Z", "max_issues_repo_path": "docs/docs/body.tex", "max_issues_repo_name": "joshtyler/visual-search", "max_issues_repo_head_hexsha": "63fd7512f18596d5bd9475c7624b631a2205bcb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/docs/body.tex", "max_forks_repo_name": "joshtyler/visual-search", "max_forks_repo_head_hexsha": "63fd7512f18596d5bd9475c7624b631a2205bcb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-26T21:33:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-26T21:33:35.000Z", "avg_line_length": 73.2166377816, "max_line_length": 958, "alphanum_fraction": 0.7682384131, "num_tokens": 12132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.34928432044220414}}
{"text": "\\section*{Representing Time}\r\n\r\n\r\n\\subsection*{\\\\\r\nThe underspecification of time representations in OWL axioms}\r\n\r\nBoth an axiom in the OBO representational syntax \\todo{more on OBO} \r\n%\r\n\\begin{equation}\r\n\\begin{split}\r\n\\mclass{CellMembrane}\\;\\mirel{continuant\\_part\\_of}\\;\\mclass{Cell}\r\n\\end{split}\r\n\\label{eq:cellobo}\r\n\\end{equation}\r\n%\r\nand the OWL axiom (often considered equivalent)\r\n%\r\n\\begin{equation}\r\n\\begin{split}\r\n\\mclass{CellMembrane}\\;\\mathtt{subClassOf}\\;\\mclass{continuant\\_part\\_of}\\;\\mathtt{some}\\;\\mclass{Cell}\r\n\\end{split}\r\n\\label{eq:celldl}\r\n\\end{equation}\r\n%\r\ndo not exhibit any explicit commitment with regard to time. This is not a side issue, because it makes a\r\ndifference whether, for example, a cell membrane is \\emph{always} part of some cell or\r\nonly \\emph{at some time}. \r\nThe lack of temporal definition of OWL statements is especially unsatisfactory\r\nwhen it comes to transitive properties like $\\mirel{continuant\\_part\\_of}$ or $\\mirel{located\\_in}$,\r\nwhere the suppression of the temporal factor can produce plainly wrong entailments,\r\nespecially at the level of individuals, such as in the following example:\r\n%\r\n\\begin{equation}\r\n\\begin{split}\r\n\\mirel{located\\_in} (\\mirel{Thrombus\\#398}, \\mirel{Heart\\#431})  \\\\\r\n\\mirel{located\\_in} (\\mirel{Heart\\#431}, \\mirel{Patient\\#900})\r\n\\end{split}\r\n\\label{eq:trans}\r\n\\end{equation}\r\n%\r\nIf we now assume that \\mirel{Heart\\#431} is later transplanted to \\mirel{Patient\\#115}, we also have\r\n\r\n\\begin{equation}\r\n\\begin{split}\r\n\\mirel{located\\_in} (\\mirel{Heart\\#431}, \\mirel{Patient\\#115})\r\n\\end{split}\r\n\\label{eq:trans}\r\n\\end{equation}\r\n\r\nThis would entail that one of the patients is located within the other, which is plainly wrong. \r\nAlso, if we assume that the thrombus was no longer in the heart when it was transplanted to Patient\\#115, then the inference to\r\n%\r\n\\begin{equation}\r\n\\begin{split}\r\n\\mirel{located\\_in} (\\mirel{Thrombus\\#398}, \\mirel{Patient\\#115})\r\n\\end{split}\r\n\\label{eq:transEntailment}\r\n\\end{equation}\r\n%\r\nwhich follows from the transitivity of the relation $\\mirel{located\\_in}$, is obviously invalid.\r\n\r\nThis has a far-reaching consequence: by default, OWL statements are temporally ambiguous in a way that may entail unintended consequences when domain ontologies are used for reasoning with real data. (A lack of an explicit treatment of temporal context has previously been implicated in an assessment of the quality of existential restrictions in OBO Foundry ontologies \\cite{boeker2011}.)\r\n\r\n\\subsection*{Strengths of Relatedness}\r\n\r\nWe can now propose a distinction between different temporal \\emph{strengths} of relatedness. These are to be satisfied by temporally qualified such as parthood defined in the OBO Relation Ontology  and apply to relations between continuants only. \r\nWe begin by characterising the ontological status of regions of time , henceforth referred to by the symbol $t$. \r\nTimes are either time intervals or time points. %, assuming that the latter can be approximated by infinitesimally small intervals.\r\nWe restrict ourselves to those ternary relations for which it can be assumed that whenever they hold for a time interval, \r\nthey also hold for any of its subintervals, including time points. For example, if a car is located in a garage during a day, then it is located therein at any time interval during that day. If a patient's cholesterol level is elevated for a whole year, it is elevated over any duration of time during this year. \r\nIn the following, ternary relations are marked by the superscript $^t$, like in $\\mrelt{rel}$, from which binary relations are  distinguished by\r\n$^b$, like in $\\mrelb{rel}$.  \r\n\r\nFormally:\r\n\\begin{equation}\r\n\\begin{split}\r\n\\forall a, b, t, t^\\prime:\\; \\mrelt{rel}(a, b, t) \\wedge \\mirel{within}(t^\\prime,t) \\rightarrow\r\n\\mrelt{rel}(a,b,t^\\prime)\r\n\\end{split}\r\n\\label{eq:temporarily:temp}\r\n\\end{equation}\r\n\r\nThese are called time-distributive relations.\r\n\r\n\\subsubsection*{Temporary Generic Relatedness (TGR)}\r\n\r\nInformally: for all instances $a$ of \\mclass{A} there is some time $t$ and some instance $b$ of\r\n\\mclass{B} such that $a$ is related to $b$ at $t$. Examples:\r\n\\begin{enumerate}[(a)]\r\n\\item for all apple seeds there is\r\nsome apple such that the seed is part of the apple at some time;\r\n\\item for all\r\ntrees there is some leaf such that the leaf is part of the tree at some time.\r\n\\end{enumerate}\r\n\r\nFormally:\r\n\\begin{equation}\r\n\\begin{split}\r\n\\mclass{TemporarilyRelated}(\\mclass{A},\\mclass{B}) =_{def}&\\;\r\n\\forall a, t:\\; \\mrelt{inst}(\\mclass{A}, a, t) \\\\\r\n&\\ \\rightarrow\r\n\\exists b, t^\\prime:\\;(\\mrelt{inst}(\\mclass{B},b,t^\\prime) \\wedge\r\n\\mrelt{rel}(a,b,t^\\prime) \\wedge \\mirel{within}(t^\\prime,t))\r\n\\end{split}\r\n\\label{eq:temporarily:cls}\r\n\\end{equation}\r\n\r\n\\subsubsection*{Permanent Generic Relatedness (PGR)}\r\n\r\nInformally: for all instances $a$ of \\mclass{A} there is, at all times $t$ for which\r\n$a$ exists,\r\nsome instance $b$ of \\mclass{B} such that $a$ is related to $b$ at $t$, but not necessarily\r\nalways the same $b$ at all times $t$. Examples:\r\n\\begin{enumerate}[(a)]\r\n\\item all cells have a water molecule as\r\npart at all times, but not always the same water molecule;\r\n\\item every bacterial colony has some bacteria as parts at all times, but not\r\nalways the same bacteria.\r\n\\end{enumerate}\r\n\r\n\\begin{equation}\r\n\\begin{split}\r\n\\mclass{PermanentlyGenericallyRelated}(\\mclass{A},\\mclass{B}) =_{def}&\\;\r\n\\forall a, t:\\; \\mrelt{inst}(\\mclass{A}, a, t) \\\\\r\n&\\ \\rightarrow\r\n\\exists b:\\;(\\mrelt{inst}(\\mclass{B},b,t) \\wedge\r\n\\mrelt{rel}(a,b,t))\r\n\\end{split}\r\n\\label{eq:generically:cls}\r\n\\end{equation}\r\n\r\nIt is as PGR relations that the standard interpretation of OBO binary class-level relations are understood \r\nsuch as in formula (\\ref{eq:cellobo}) above, according to \\cite{OBO:RO}.\r\n\r\n\\subsubsection*{Permanent Specific Relatedness (PSR)}\r\n\r\nInformally, for all instances $a$ of \\mclass{A} there is, at all times $t$ that $a$ exists, an\r\ninstance $b$ of \\mclass{B} such that $a$ is related to $b$ at $t$; in this case it is the\r\nsame $b$ at all times $t$. Examples:\r\n\\begin{enumerate}[(a)]\r\n\\item a human being has a brain as part at all times, and it is necessarily the same brain;\r\n\\item a radioactively marked molecule of DNA has the radioactive isotope as part\r\nat all times, and it is necessarily the same radioactive isotope.\r\n\\end{enumerate}\r\n\r\n\\begin{equation}\r\n\\begin{split}\r\n\\mclass{Permanently}&\\mclass{SpecificallyRelated}(\\mclass{A},\\mclass{B}) =_{def}\\;\r\n\\forall a, t:\\; \\mrelt{inst}(\\mclass{A}, a, t) \\\\\r\n&\\ \\rightarrow\r\n\\exists b:\\;\\big(\\mrelt{inst}(\\mclass{B},b,t) \\wedge\r\n\\mrelt{rel}(a,b,t))\r\n\\\\\r\n&\\quad\\quad \\wedge \\forall t^\\prime: (\\mrelt{inst}(\\mclass{A},a,t^\\prime)\r\n\\rightarrow (\\mrelt{rel}(a,b,t^\\prime) \\wedge\r\n\\mrelt{inst}(\\mclass{B},b,t^\\prime))\\big)\r\n\\end{split}\r\n\\label{eq:specifically:cls}\r\n\\end{equation}\r\n", "meta": {"hexsha": "28e5b7b3a916dbf5edb2293413e0533863aa69dc", "size": 6840, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/OWL-TIME/bfo-owl-time-problem.tex", "max_stars_repo_name": "zhengj2007/bfo", "max_stars_repo_head_hexsha": "bf988c5747ff1ac517eeb55a534cab2f62ee52e2", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/OWL-TIME/bfo-owl-time-problem.tex", "max_issues_repo_name": "zhengj2007/bfo", "max_issues_repo_head_hexsha": "bf988c5747ff1ac517eeb55a534cab2f62ee52e2", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 193, "max_issues_repo_issues_event_min_datetime": "2015-07-23T20:52:43.000Z", "max_issues_repo_issues_event_max_datetime": "2015-07-24T02:41:37.000Z", "max_forks_repo_path": "docs/OWL-TIME/bfo-owl-time-problem.tex", "max_forks_repo_name": "zhengj2007/bfo", "max_forks_repo_head_hexsha": "bf988c5747ff1ac517eeb55a534cab2f62ee52e2", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.75, "max_line_length": 390, "alphanum_fraction": 0.7257309942, "num_tokens": 2047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3492843138337172}}
{"text": "\\section{Results and discussions}\r\n\\label{section:results_and_discussions}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nIn this section, five DL models of semantic segmentation approach including  Res-UNet, VGG16 encoder-decoder, FCN-DenseNet, PSPNet, and GCN were evaluated on exemplary three damage scenarios of an RMS of the numerically calculated full wavefield interpolated at the bottom surface of the plate in order to identify the delamination.\r\nAdditionally, an experimental scenario was also used to evaluate the performance of the models to show the DL capabilities of generalization.\r\nFor each model, the mean and the max \\(IoU\\) are calculated and presented as a metric of comparison.\r\nMoreover, the Accuracy of classification, Precision, Recall, and F1 score depicted in Eqs~(\\ref{accuracy}-\\ref{f1_score}) respectively, were calculated for each model.\r\n\\begin{equation}\r\n\t\\rm Accuracy\\ = \\frac{TP+TN}{(Total\\ number\\ of\\ tested\\ samples)}\r\n\t\\label{accuracy}\r\n\\end{equation}\r\n\r\n\\begin{equation}\r\n\t\\rm Pricision\\ =\\frac{TP}{TP+FP}\r\n\t\\label{pricisoin}\r\n\\end{equation}\r\n\\begin{equation}\r\n\t\\rm Recall\\ = \\frac{TP}{TP+ FN}\r\n\t\\label{recall}\r\n\\end{equation}\r\n\\begin{equation}\r\n\t\\rm F1 score =\\frac{2 \\times (Pricision\\times Recall)}{(Pricision + Recall)} \r\n\t\\label{f1_score}\r\n\\end{equation}\r\nwhere the Positive/Negative refers to the predicted output as (damage or non-damage) respectively, True Positive (TP) and True Negative (TN)  represent the correct classification, and the False Positive (FP) and False Negative (FN) represent the incorrect classification.\r\n\r\nIn this work, all semantic segmentation models were implemented and trained with Keras API~\\cite{chollet2015keras} running on top of TensorFlow.\r\nFurther, we have replaced the previous NVIDIA RTX2080 GPU utilised in our work~\\cite{Ijjeh2021} with a superior NVIDIA Tesla V100 GPU with \\(32\\)GB memory that enables us to increase the total number of learnable parameters of the DL models that will allow them to learn and extract more features. \r\nFor training purposes, we have used the K-fold cross-validation technique with five folds. \r\nAccordingly, each model has trained for \\(5\\) iterations. \r\nFor each iteration, we calculated the mean accuracy of all folds.\r\nFurther, the number of epochs equals \\(20\\) per iteration.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\subsection{Numerical scenarios}\r\nIn the following, three scenarios of numerical data regarding delamination of different locations, shapes, and angles are presented. \r\nThe first exemplary delamination scenario is shown in Fig.~\\ref{fig:softmax_448}. \r\nThe delamination is located at the left edge of the plate, and it is surrounded by a line to represent its shape and location as shown in Fig.~\\ref{fig:RMS_flat_shell_Vz_448}.\r\nFigures~\\ref{fig:unet_pred_448}-~\\ref{fig:gcn_pred_448} show the predicted output of the Res-UNet, VGG16 encoder-decoder, PSPNet, FCN-DenseNet and GCN models, respectively. \r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nAll models properly indicate the location of the delamination. \r\nMoreover, pixels related to delamination location are clustered into a single spot without any additional noise. \r\nVGG16 encoder-decoder and GCN models better visually resemble the actual shape of the delamination than other models.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\begin{figure}[!h]\r\n\t\\centering\r\n\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n\t\t\\centering\r\n\t\t\\includegraphics[scale=1.0]{RMS_flat_shell_Vz_448_with_square_label.png}\r\n\t\t\\caption{RMS bottom with label}\r\n\t\t\\label{fig:RMS_flat_shell_Vz_448}\r\n\t\\end{subfigure}\r\n\t\\hfill\r\n%\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n%\t\t\\centering\r\n%\t\t\\includegraphics[scale=1.0]{m1_rand_single_delam_448.png}\r\n%\t\t\\caption{Ground truth}\r\n%\t\t\\label{fig:m1_rand_single_delam_448}\r\n%\t\\end{subfigure}\r\n%\t\\hfil\r\n\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n\t\t\\centering\r\n\t\t\\includegraphics[scale=1.0]{residual_unet_num_269.png}\r\n\t\t\\caption{Res-UNet}\r\n\t\t\\label{fig:unet_pred_448}\r\n\t\\end{subfigure}\r\n\t\\hfill\r\n\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n\t\t\\centering\r\n\t\t\\includegraphics[scale=1.0]{VGG16_ecoder_decoder_num_269.png}\r\n\t\t\\caption{VGG16 encoder-decoder}\r\n\t\t\\label{fig:vgg16_pred_448}\r\n\t\\end{subfigure}\r\n\t\\hfill\r\n\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n\t\t\\centering\r\n\t\t\\includegraphics[scale=1.0]{PSPNet_num_269.png}\r\n\t\t\\caption{PSPNet}\r\n\t\t\\label{fig:pspnet_pred_448}\r\n\t\\end{subfigure}\r\n\t\\hfill\r\n\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n\t\t\\centering\r\n\t\t\\includegraphics[scale=1.0]{FCN_DenseNet_num_269.png}\r\n\t\t\\caption{FCN-DenseNet}\r\n\t\t\\label{fig:fcn_densenet_pred_448}\r\n\t\\end{subfigure}\r\n\t\\hfill\r\n\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n\t\t\\centering\r\n\t\t\\includegraphics[scale=1.0]{GCN_num_269.png}\r\n\t\t\\caption{GCN}\r\n\t\t\\label{fig:gcn_pred_448}\r\n\t\\end{subfigure}\r\n\t\\caption{First delamination scenario based on numerical data}\r\n\t\\label{fig:softmax_448}\r\n\\end{figure} \r\n\\clearpage\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nIn the second delamination scenario, shown in Fig.~\\ref{fig:385_softmax}, the delamination is located at the upper left corner of the plate, and it is surrounded by an ellipse to represent its shape and location as shown in Fig.~\\ref{fig:RMS_flat_shell_Vz_385}.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nThis is the most challenging damage scenario because of reflections coming from plate edges overshadows reflections from damage.\r\nAs a result, changes in RMS patterns are barely visible.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nFigures~\\ref{fig:Unet_Pred__softmax_385} -~\\ref{fig:gcn_pred_385} show the predicted output of the Res-UNet, VGG16 encoder-decoder, PSPNet, FCN-DenseNet and GCN models, respectively. \r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nAll models perform reasonably well, considering the difficult damage scenario.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\begin{figure}[!h]\r\n\t\\centering\r\n\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n\t\t\\centering\r\n\t\t\\includegraphics[scale=1.0]{RMS_flat_shell_Vz_27_385_with_label.png}\r\n\t\t\\caption{RMS bottom with label}\r\n\t\t\\label{fig:RMS_flat_shell_Vz_385}\r\n\t\\end{subfigure}\r\n\t\\hfill\r\n%\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n%\t\t\\centering\r\n%\t\t\\includegraphics[scale=1.0]{m1_rand_single_delam_385.png}\r\n%\t\t\\caption{Ground truth}\r\n%\t\t\\label{fig:m1_rand_single_delam_385}\r\n%\t\\end{subfigure}\r\n\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n\t\t\\centering\r\n\t\t\\includegraphics[scale=1.0]{residual_unet_num_17.png}\r\n\t\t\\caption{Res-UNet}\r\n\t\t\\label{fig:Unet_Pred__softmax_385}\r\n\t\\end{subfigure}\r\n\t\\hfill\r\n\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n\t\t\\centering\r\n\t\t\\includegraphics[scale=1.0]{VGG16_ecoder_decoder_num_17.png}\r\n\t\t\\caption{VGG16 encoder-decoder}\t\t\t\\label{fig:vgg16_pred__softmax_385}\t\t\t\r\n\t\\end{subfigure}\r\n\t\\hfill\r\n\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n\t\t\\centering\r\n\t\t\\includegraphics[scale=1.0]{PSPNet_num_17.png}\r\n\t\t\\caption{PSPNet}\r\n\t\t\\label{fig:pspnet_pred__softmax_385}\r\n\t\\end{subfigure}\t\r\n\t\\hfill\r\n\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n\t\t\\centering\r\n\t\t\\includegraphics[scale=1.0]{FCN_DenseNet_num_17.png}\r\n\t\t\\caption{FCN-DenseNet}\r\n\t\t\\label{fig:fcn_densenet_pred__softmax_385}\r\n\t\\end{subfigure}\t\r\n\t\\hfill\r\n\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n\t\t\\centering\r\n\t\t\\includegraphics[scale=1.0]{GCN_num_17.png}\r\n\t\t\\caption{GCN}\r\n\t\t\\label{fig:gcn_pred_385}\r\n\t\\end{subfigure}\r\n\t\\caption{Second delamination scenario based on numerical data}\r\n\t\\label{fig:385_softmax}\r\n\\end{figure}\r\n\\clearpage\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nThe third delamination scenario is shown in Figure~\\ref{fig:475_softmax}. \r\nThe delamination is located at the upper middle of the plate and it is surrounded by an ellipse to represent its shape and location as shown in Fig.~\\ref{fig:RMS_flat_shell_Vz_475}.\r\nFigures~\\ref{fig:Unet_Pred__softmax_475} -~\\ref{fig:gcn_pred_475} show the predicted output of the Res-UNet, VGG16 encoder-decoder, PSPNet, FCN-DenseNet and GCN models, respectively. \r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nIn this case, the elliptical shape of delamination is best preserved by Res-UNet and FCN-DenseNet. \r\nHowever, the highest value of IoU is obtained by GCN (see Table~\\ref{tab:table_numerical_scenarios}).\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\begin{figure}[!h]\r\n\t\\centering\r\n\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n\t\t\\centering\r\n\t\t\\includegraphics[scale=1.0]{RMS_flat_shell_Vz_27_475_with_label.png}\r\n\t\t\\caption{RMS bottom with label}\r\n\t\t\\label{fig:RMS_flat_shell_Vz_475}\r\n\t\\end{subfigure}\r\n\t\\hfill\r\n%\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n%\t\t\\centering\r\n%\t\t\\includegraphics[scale=1.0]{m1_rand_single_delam_475.png}\r\n%\t\t\\caption{Ground truth}\r\n%\t\t\\label{fig:m1_rand_single_delam_475}\r\n%\t\\end{subfigure}\r\n\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n\t\t\\centering\r\n\t\t\\includegraphics[scale=1.0]{residual_unet_num_377.png}\r\n\t\t\\caption{Res-UNet}\r\n\t\t\\label{fig:Unet_Pred__softmax_475}\r\n\t\\end{subfigure}\r\n\t\\hfill\r\n\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n\t\t\\centering\r\n\t\t\\includegraphics[scale=1.0]{VGG16_ecoder_decoder_num_377.png}\r\n\t\t\\caption{VGG16 encoder-decoder}\t\t\t\\label{fig:vgg16_pred__softmax_475}\t\t\t\r\n\t\\end{subfigure}\r\n\t\\hfill\r\n\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n\t\t\\centering\r\n\t\t\\includegraphics[scale=1.0]{PSPNet_num_377.png}\r\n\t\t\\caption{PSPNet}\r\n\t\t\\label{fig:pspnet_pred__softmax_475}\r\n\t\\end{subfigure}\t\r\n\t\\hfill\r\n\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n\t\t\\centering\r\n\t\t\\includegraphics[scale=1.0]{FCN_DenseNet_num_377.png}\r\n\t\t\\caption{FCN-DenseNet}\r\n\t\t\\label{fig:fcn_densenet_pred__softmax_475}\r\n\t\\end{subfigure}\r\n\t\\hfill\r\n\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n\t\t\\centering\r\n\t\t\\includegraphics[scale=1.0]{GCN_num_377.png}\r\n\t\t\\caption{GCN}\r\n\t\t\\label{fig:gcn_pred_475}\r\n\t\\end{subfigure}\t\r\n\t\\caption{Third delamination scenario based on numerical data}\r\n\t\\label{fig:475_softmax}\r\n\\end{figure}\r\n\\clearpage\r\nThe \\(IoU\\) values for all models regarding the predicted delamination are presented in Table.~\\ref{tab:table_numerical_scenarios}.\r\nFor the first and third scenarios, the GCN model has the highest \\(IoU\\) compared to the other models, and for the second scenario, the VGG16 encoder-decoder model has the highest \\(IoU\\) compared to the other models.\r\nFurther, in all models, the predicted outputs have no noise regarding delamination identification.\r\n\\begin{table}[]\r\n\t\\centering\r\n\t\\caption{\\(IoU\\) of Numerical scenarios}\r\n\t\\label{tab:table_numerical_scenarios}\r\n\t\\resizebox{\\textwidth}{!}\r\n\t{\r\n\t\t\\begin{tabular}{cccc}\\hline\r\n\t\t\tModel & 1st scenario & 2nd scenario & 3rd scenario \\\\ \\hline\r\n\t\t\tRes-UNet & \\(0.498\\) & \\(0.782\\) & \\(0.816\\)  \\\\ \r\n\t\t\tVGG16 encoder-decoder & \\(0.512\\) & \\(0.787\\)  & \\(0.662\\)  \\\\\r\n\t\t\tFCN-DenseNet & \\(0.734\\)  & \\(0.612\\)  & \\(0.866\\)  \\\\ \r\n\t\t\tPSPNet & \\(0.389\\) & \\(0.496\\) & \\(0.646\\)  \\\\ \r\n\t\t\tGCN & \\(0.791\\) & \\(0.696\\) & \\(0.875\\) \\\\ \\hline\r\n\t\t\\end{tabular}\r\n\t}\r\n\\end{table}\r\nTable~\\ref{tab:table_iou} presents the mean and maximum values of \\(IoU\\) calculated for the previously unseen numerical test set (380 cases) for all models.\r\nTable~\\ref{tab:table_iou} shows that all models have a relatively high \\(IoU\\), indicating their ability to detect and localise the delamination, which is higher compared to the traditional signal processing techniques such as the adaptive wavenumber filtering presented in our previous work~\\cite{Ijjeh2021}. \r\nThe mean \\(IoU\\) for the adaptive wavenumber filtering technique regarding the whole testing samples was \\(0.373\\) compared to the previous FCN-DenseNet model, which has a mean \\(IoU\\) of \\(0.623\\).\r\n\\begin{table}[]\r\n\t\\centering\r\n\t\\caption{Analysis of numerical data}\r\n\t\\label{tab:table_iou}\r\n\t\\begin{tabular}{ccc}\\hline\r\n\t\tModel & mean \\(IoU\\) & max \\(IoU\\) \\\\ \\hline\r\n\t\tRes-UNet & \\(0.664\\) & \\(0.888\\) \\\\ \r\n\t\tVGG16 encoder-decoder & \\(0.572\\) & \\(0.841\\) \\\\ \r\n\t\tFCN-DenseNet & \\(0.680\\) & \\(0.920\\) \\\\ \r\n\t\tPSPNet & \\(0.549\\) & \\(0.914\\) \\\\ \r\n\t\tGCN & \\(0.763\\) & \\(0.931\\) \\\\ \\hline\r\n\t\\end{tabular}\r\n\\end{table}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nFurther, in Table~\\ref{tab:table_performance} the TP, TN, FP, and FN are presented for all models regarding the test set. \r\n\\begin{table}[]\r\n\t\\centering\r\n\t\\caption{Model classification performance}\r\n\t\\label{tab:table_performance}\r\n\t\\resizebox{\\textwidth}{!}\r\n\t{\r\n\t\t\\begin{tabular}{ccccc} \\hline\r\n\t\t\tModel& True Positive & True Negative & False Positive & False Negative \\\\ \\hline\r\n\t\t\tRes-UNet & 376 & 376 & 4 & 0 \\\\ \r\n\t\t\tVGG16 encoder-decoder & 373 & 373 & 7 & 0 \\\\ \r\n\t\t\tFCN-DenseNet & 378 & 378 & 2 & 0 \\\\ \r\n\t\t\tPSPNet & 368 & 368 & 12 & 0 \\\\ \r\n\t\t\tGCN & 380 & 380 & 0 & 0 \\\\ \\hline\r\n\t\t\\end{tabular}\r\n\t}\r\n\\end{table}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nMoreover, Table~\\ref{tab:evaluation_metric} presents the classification accuracy, precision, recall, and the F1-score values for all models as additional evaluation metrics.\r\nAs shown in Table~\\ref{tab:evaluation_metric}, all models have high classification accuracy, which indicates that all the presented models are capable of predicting the presence of the delamination in all the numerically generated cases. \r\nHowever, the best performance was achieved by GCN.\r\n\\begin{table}[]\r\n\t\\centering\r\n\t\\caption{Evaluation metric}\r\n\t\\label{tab:evaluation_metric}\r\n\t\\resizebox{\\textwidth}{!}\r\n\t{\r\n\t\t\\begin{tabular}{ccccc} \\hline\r\n\t\t\tModel& Accuracy & Precision & Recall & F1-Score \\\\ \\hline\r\n\t\t\tRes-UNet & \\(0.994\\)  & \\(0.989\\) &  \\(1.00\\)  & \\(0.994\\)  \\\\ \r\n\t\t\tVGG16 encoder-decoder & \\(0.991\\)  & \\(0.981\\) & \\(1.00\\) &  \\(0.991\\)\\\\ \r\n\t\t\tFCN-DenseNet & \\(0.997\\)  & \\(0.994\\) & \\(1.00\\)  & \\(0.994\\) \\\\ \r\n\t\t\tPSPNet & \\(0.984\\) & \\(0.968\\) & \\(1.00\\) & \\(0.984\\) \\\\ \r\n\t\t\tGCN & \\(1.00\\) & \\(1.00\\) & \\(1.00\\) & \\(1.00\\) \\\\ \\hline\r\n\t\t\\end{tabular}\r\n\t}\r\n\\end{table}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%Figures~\\ref{fig:res_unet_iou_loss}-\\ref{fig:GCN_iou_loss} show the accuracy and the loss graphs of the training and validation phases during epochs for Res-UNet, VGG16 encoder-decoder, FCN-DenseNet, PSPNet and GCN models, respectively.\r\n%\\begin{figure} [!h]\r\n%\t\\centering\r\n%\t%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n%\t \\centering\t\t\\includegraphics[width=\\textwidth]{Unet_kfold_iou_per_epochs_softmax.png}\t\\caption{}\r\n%\t \\label{fig:unet_accuracy_metric}\r\n%\t\\end{subfigure}\r\n%\t\\hfill\t\r\n%\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n%\t \\centering\r\n%\t \\includegraphics[width=\\textwidth]{Unet_kfold_loss_per_epochs_softmax.png}\r\n%\t \\caption{}\r\n%\t \\label{fig:unet_loss_metric}\r\n%\t\\end{subfigure}\r\n%\t\\caption{Accuracy and loss of the Res-UNet model}\r\n%\t\\label{fig:res_unet_iou_loss}\r\n%\\end{figure}\r\n%\t%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\\begin{figure}[!h]\r\n%\t\\centering\r\n%\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n%\t\t\\centering\r\n%\t\t\\includegraphics[width=\\textwidth]{FCN_VGG16_iou_per_epochs_softmax.png}\r\n%\t\t\\caption{}\r\n%\t\t\\label{fig:vgg16_accuracy_metric}\r\n%\t\\end{subfigure}\t\t\r\n%\t\\hfill\r\n%\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n%\t\t\\centering\r\n%\t\t\\includegraphics[width=\\textwidth]{FCN_VGG16_loss_per_epochs_softmax.png}\r\n%\t\t\\caption{}\r\n%\t\t\\label{fig:vgg16_loss_metric}\r\n%\t\\end{subfigure}\r\n%\t\\caption{Accuracy and loss of the VGG16 encoder-decoder model}\r\n%\t\\label{fig:Vgg16_iou_loss}\r\n%\\end{figure}\r\n%\t%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\\begin{figure}[!h]\r\n%\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n%\t\\centering\r\n%\t\\includegraphics[width=\\textwidth]{FCN_DenseNet_iou_per_epochs_softmax.png}\r\n%\t\\caption{}\r\n%\t\\label{fig:fcn_densenet_accuracy_metric}\r\n%\t\\end{subfigure}\r\n%\t\\hfill\r\n%\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n%\t\\centering\r\n%\t\\includegraphics[width=\\textwidth]{FCN_DenseNet_loss_per_epochs_softmax.png}\r\n%\t\\caption{}\r\n%\t\\label{fig:fcn_densenet_loss_metric}\r\n%\t\\end{subfigure}\t\r\n%\\caption{Accuracy and loss of the FCN-DenseNet model}\r\n%\\label{fig:FCN_DenseNet_iou_loss}\r\n%\\end{figure}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\\begin{figure} [!h]\r\n%\t\\centering\r\n%\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n%\t\t\\centering\r\n%\t\t\\includegraphics[width=\\textwidth]{PSPNet_kfold_iou_per_epochs_softmax.png}\r\n%\t\t\\caption{}\r\n%\t\t\\label{fig:psp_accuracy_metric}\r\n%\t\\end{subfigure}\r\n%\t\\hfill\r\n%\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n%\t\t\\centering\r\n%\t\t\\includegraphics[width=\\textwidth]{PSPNet_kfold_loss_per_epochs_softmax.png}\r\n%\t\\caption{}\r\n%\t\\label{fig:psp_loss_metric}\r\n%\t\\end{subfigure}\r\n%\t\\caption{Accuracy and loss of the PSPNet model}\r\n%\t\\label{fig:PSPNet_iou_loss}\r\n%\\end{figure}\r\n%\t%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\\begin{figure} [!h]\r\n%\t\\centering\r\n%\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n%\t\t\\centering\r\n%\t\t\\includegraphics[width=\\textwidth]{GCN_kfold_iou_per_epochs_softmax.png}\r\n%\t\t\\caption{}\r\n%\t\t\\label{fig:gcn_accuracy_metric}\r\n%\t\\end{subfigure}\r\n%\t\\hfill\r\n%\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n%\t\t\\centering\r\n%\t\t\\includegraphics[width=\\textwidth]{GCN_kfold_loss_per_epochs_softmax.png}\t\t\t\r\n%\t\t\\caption{}\r\n%\t\t\\label{fig:gcn_loss_metric}\r\n%\t\\end{subfigure}\r\n%\t\\caption{Accuracy and loss of the GCN model}\r\n%\t\\label{fig:GCN_iou_loss}\t\r\n%\\end{figure}\r\n%\\clearpage\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nMoreover, the total number of parameters in any DL model is a sum of the trainable parameters (weights of convolution filters) and non-trainable parameters (biases and pooling filters).\r\nTrainable parameters are continuously updated until we reach the minimum loss value, while the non-trainable parameters are not changed during the whole training process.\r\nTable~\\ref{tab:table_parameters} shows the total number of parameters for all implemented models.\r\nFurther, the total number of parameters can reflect the computation complexity of the model.\r\nIt can be noted that as the number of total parameters increases, the required time for training increases.\r\n\\begin{table}[]\r\n\t\\centering\r\n\t\\caption{Model parameters}\r\n\t\\label{tab:table_parameters}\r\n\t\t\\begin{tabular}{cc}\\hline\r\n\t\t\tModel &  Total parameters (\\(\\approx\\)) \\\\ \\hline\r\n\t\t\tRes-UNet & \\(52\\times 10^6\\) \\\\ \r\n\t\t\tVGG16 encoder-decoder & \\(37.3\\times 10^6\\)  \\\\\r\n\t\t\tFCN-DenseNet & \\(2.5\\times 10^6\\) \\\\ \r\n\t\t\tPSPNet & \\(6.6\\times 10^6\\) \\\\ \r\n\t\t\tGCN & \\(36\\times 10^6\\) \\\\ \\hline\r\n\t\t\\end{tabular}\r\n\\end{table}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\subsection{Experimental scenario}\r\nIn this scenario, an experimental case of CFRP with Teflon insert as artificial delamination is investigated presented in Fig.~\\ref{fig:Exp_ERMS_teflon}. \r\nSimilar to the synthetic data set, we applied a frequency of \\(50\\) kHz to excite a signal in a transducer placed at the centre of the plate. \r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nA0 mode wavelength for this particular CFRP material at such frequency is about 20 mm. \r\nThe measurements were performed by Polytec PSV-400 SLDV on a bottom surface of the plate of dimensions 500 by 500 mm. \r\nThe measurement grid spacing was 1 mm and sampling frequency 512 kHz. \r\nThe measured full wavefield was further processed by an energy compensated RMS takes into account wave attenuation. \r\nThe results of such operation are shown in Fig.~\\ref{fig:Delamination}.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nThe delamination is surrounded by a square frame representing its shape and location. \r\nFigures~(\\ref{fig:unet_exp_7_} - \\ref{fig:gcn_exp}) shows delamination prediction maps for Res-UNet, VGG16 encoder-decoder, PSPNet, FCN-DenseNet and GCN models, receptively.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nThe performance of the models were evaluated by using IoU metric which takes into account not only damage location but also its shape and size. \r\nThe following results were obtained: the Res-UNet IoU = 0.577, the VGG16 encoder-decoder \\(IoU = 0.624\\), the\r\nPSPNet \\(IoU = 0.488\\), the FCN-DenseNet \\(IoU = 0.537\\) and the GCN \\(IoU =\r\n0.723\\). \r\nSimilarly to the numerical dataset, the best accuracy was achieved by using GCN.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nAs shown, the models are capable of precise detection and localisation of the delamination. \r\nWe can see that the models can identify the delamination with almost free noise, which indicates the models are capable of generalising and detecting the delamination on previously unseen data. \r\nConsidering the presented models were trained only on the numerically generated dataset, the models show high generalisation capability.\r\nThe performance of the models can be further improved when they are trained on the experimental and the numerical data, as new features will be learned. \r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\begin{figure} [!h]\r\n\t\\centering\r\n\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n\t\t\\centering\r\n\t\t\\includegraphics[scale=1]{ERMS_with_label.png}\r\n\t\t\\caption{ERMS CFRP Teflon inserted \\& Label}\r\n\t\t\\label{fig:Delamination}\t\r\n\t\\end{subfigure}\t\r\n\t\\hfill\r\n\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n\t\t\\centering\r\n\t\t\\includegraphics[scale=1]{residual_unet_decoder_exp_7.png}\r\n\t\t\\caption{Res-UNet} \r\n\t\t\\label{fig:unet_exp_7_}\r\n\t\\end{subfigure}\r\n\t\\hfill\r\n\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n\t\t\\centering\r\n\t\t\\includegraphics[scale=1]{VGG16_ecoder_decoder_exp_7.png}\r\n\t\t\\caption{VGG16 encoder-decoder} \r\n\t\t\\label{fig:vgg16_exp_7_}\r\n\t\\end{subfigure}\r\n\t\\hfill\r\n\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n\t\t\\centering\r\n\t\t\\includegraphics[scale=1]{pspnet_exp_7.png}\r\n\t\t\\caption{PSPNet} \r\n\t\t\\label{fig:pspnet_exp_7_}\r\n\t\\end{subfigure}\r\n\t\\hfill\r\n\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n\t\t\\centering\r\n\t\t\\includegraphics[scale=1]{FCN_DenseNet_exp_7.png}\r\n\t\t\\caption{FCN-DenseNet} \r\n\t\t\\label{fig:fcn_densenet_exp}\r\n\t\\end{subfigure}\r\n\t\\hfill\r\n\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n\t\t\\centering\r\n\t\t\\includegraphics[scale=1]{GCN_exp_7.png}\r\n\t\t\\caption{GCN} \r\n\t\t\\label{fig:gcn_exp}\r\n\t\\end{subfigure}\r\n\t\\caption{Experimental results}\r\n\t\\label{fig:Exp_ERMS_teflon}\r\n\\end{figure}\r\n\\clearpage\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n", "meta": {"hexsha": "e9b5045a54249ce0fc0dbf27fb70d54bb4d22c7e", "size": 22737, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "reports/journal_papers/MSSP_2/results_and_discussions.tex", "max_stars_repo_name": "IFFM-PAS-MISD/aidd", "max_stars_repo_head_hexsha": "9fb0ad6d5e6d94531c34778a66127e5913a3830c", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-03T05:36:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T05:36:07.000Z", "max_issues_repo_path": "reports/journal_papers/MSSP_2/results_and_discussions.tex", "max_issues_repo_name": "IFFM-PAS-MISD/aidd", "max_issues_repo_head_hexsha": "9fb0ad6d5e6d94531c34778a66127e5913a3830c", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "reports/journal_papers/MSSP_2/results_and_discussions.tex", "max_forks_repo_name": "IFFM-PAS-MISD/aidd", "max_forks_repo_head_hexsha": "9fb0ad6d5e6d94531c34778a66127e5913a3830c", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.1721991701, "max_line_length": 333, "alphanum_fraction": 0.6543519374, "num_tokens": 6657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3491914270934561}}
{"text": "%======================================================================\r\n\\chapter{Conclusions and Future Considerations}\r\n%======================================================================\r\n\r\nA summary of the main conclusions from the development of the up-scaling framework as well as the implementation and testing of the framework are presented here. These conclusions represent a successful completion of the research objectives for the thesis. That being said, there are substantial limitations to this research. A series of recommendations are provided to address some of these limitations and to provide guidance on how to extend this research.\r\n\r\n%----------------------------------------------------------------------\r\n\\section{Conclusions}\r\n%----------------------------------------------------------------------\r\nA multi-scale framework for up-scaling \\acrshort{dem} simulations has been developed to address the computational demands of simulating microscale phenomenon in a macroscale domain in the context of NFR. Up-scaling is achieved by matching homogenized stress-strain curves from REV-scale \\acrshort{dem} simulations to single element continuum models using \\acrshort{pso} and LMA optimization algorithms. A Drucker-Prager plasticity model with ductile damage is implemented in the \\acrshort{cdm} model to empirically capture the effect of the degradation (damage) of the NFR as deformation takes place.\r\n\r\n\\subsection*{1. Deformable DEM Homogenization}\r\n\r\nHomogenization algorithms were developed for homogenizing \\acrshort{dem} simulations with deformable bodies to assess the spatially averaged stress-strain behaviour of the REV from the microscale displacements, strains, and stresses. In this homogenization process, the resultant inter-block contact forces and block displacement from the \\acrshort{dem} simulations are converted to average stresses and strains. To apply the homogenization algorithms, a method of automatically assessing a suitable REV given a sufficiently large domain was developed. These algorithms were implemented in Python\\textsuperscript{TM} as the HODS software, which was used as a module for MOUSE.\r\n\r\n\\subsection*{2. Parameterization Methodology}\r\n\r\nTwo examples of the parameterization methodology are presented. Here, the key parameters required to capture the salient features of the model are isolated in order to be able to run the parameter estimation algorithms effectively. the main aspect of this parameterization methodology is the functional assumptions of the hardening/softening and damage evolution functions. In addition, the parameters are rewritten in term of physically meaningful parameters to provide more insight into the mechanics. The Drucker-Prager model with ductile damage is shown to be a reasonable \\acrshort{cdm} model approach to represent NFR in a continuum context, including effects of pressure dependent yield and the triaxiality based damage initiation criterion. Compared to a full \\acrshort{dem} simulation, the \\acrshort{cdm} model shows a good fit pre-damage, but is unable to emulate the subtle post-yield oscillations arising from non-continuous yielding in the NFR.\r\n\r\n\\subsection*{3. Up-Scaling Framework}\r\n\r\nMOUSE software was created and written in Python\\textsuperscript{TM} to provide an implementation of the up-scaling framework presented in this thesis using in house and third-party software modules. The software itself provides a platform through which the four software elements of the up-scaling framework (\\acrshort{dem} module, homogenization module, parameter estimation module, and macroscale module) can communicate with each other. The communication is facilitated by MOUSE through modules which wrap the third party software in such a way that the I/O routines to and from the modules are performed in a consistent capacity regardless of the third party software being used. A consistent set of data protocols were developed for the modules to effectively transfer data between them.\r\n\r\n\\subsection*{4. Framework Verification}\r\n\r\nThe parameter estimation module was tested and yielded an appropriate parameter set that both matched the \\acrshort{dem} data and provided realistic parameters. Additionally, the Drucker-Prager model with ductile damage was found to provide a far superior fit than the damage plasticity model for quasi-brittle materials. Most importantly, the DNS of the slope stability analysis showed that with this up-scaling framework, very significant computational gains can be had with an acceptable error. Very comparable results ($<5\\%$ error) to full \\acrshort{dem} solutions were obtained with the \\acrshort{cdm} method but required two orders of magnitude less computational time. The computational demands were again able to be reduced by another order of magnitude by using a selectively refined continuum mesh at the locations in the domain with high stress gradients.\r\n\r\n%----------------------------------------------------------------------\r\n\\section{Recommendations}\r\n%----------------------------------------------------------------------\r\n\r\nThe main limitation of the presented up-scaling implementation is the macroscale constitutive model module. In the current ABAQUS\\textsuperscript{TM} module, the constitutive models consider only isotropic behaviour. In addition, the model does not consider the effects of pore pressure in the rock mass or fluid flow in any capacity. Though the isotropic assumptions for the elasto-plastic constitutive relationships are likely sufficiently accurate, future implementations of the macroscale constitutive model should consider anisotropic damage behaviour, as anisotropic implementations are found to be completely insufficient. In the case of the Drucker-Prager model with ductile damage, the exponential Johnson-Cook triaxiality based damage initiation criterion provides an excellent fit for monotonic loading, but does not model cyclic loading well. Here, it would be ideal for the cyclic loading capacity of the damage plasticity model for quasi-brittle materials to be incorporated as well. Ultimately, the available damage material subroutines in ABAQUS\\textsuperscript{TM} are insufficient for the key physical characteristics in the system to be captured. As such, a custom anisotropic damage implementation is recommended for the macroscale constitutive model.\r\n\r\nRetrospectively, the functional form of the hardening curve is overly complex. Though it is often necessary to model the softening of the material in the plasticity model, with \\acrshort{cdm} the damage can implicitly model the softening behaviour. Here, it is observed that for the Barcelona model used for the hardening/softening curve, only the hardening portion of the curve is ever used. As such, for future implementations of the plasticity hardening functions, a simpler exponential function could be applied which would also have the benefit of decreasing the number of parameters that need to be estimated, leading to more consistent solutions and faster convergence of the optimization algorithms. \r\n\r\nFurthermore, it is speculated by the author that portions of the parameterization methodology could be modified to yield more consistent solutions. In the parameterization formulations presented in this thesis, too much emphasis was placed on creating physically meaningful parameters rather than numerically consistent parameters. This inconsistency is the case with certain paired parameters if one of the parameters is highly sensitive.\r\n\r\nAdditionally, effectively searching a 11+ dimensional parameter space is computationally expensive. By dividing the problem and exploiting features of the curves and constitutive models, it may be possible to increase the convergence rate and effectively get a better, faster solution. Instead of searching the entire parameter space, it is possible to split the parameters into groups (e.g. pre-damage and post damage). Here, the damage parameters don't actually affect the plasticity calculations until damage is initiated. As such, the plasticity parameters can be estimated using the pre-damage curve and the damage parameters can subsequently be estimated using the post-damage curve.\r\n\r\nA more rigorous examination of other available optimization routines and associated optimization parameters would be another way to potentially reduce the computational cost and increase the accuracy of the parameter estimation process. \\acrshort{pso} and LMA were used in this research, but Dynamically Dimensioned Search (DDS), \r\nReal-Coded Genetic Algorithm (RGA) and Simulated Annealing (SA) were also briefly investigated. As previously stated, rigorously assessing the most effective algorithm was not a priority of this research, but the \\acrshort{pso} + LMA combination was chosen for its simplicity and effectiveness. The other algorithms, if properly applied may provide a faster and more accurate solution.\r\n\t\r\nFor this up-scaling methodology to be more accurate, 3D \\acrshort{dem} simulations are required to capture accurate physical responses of these complex systems. In addition to modifying the \\acrshort{dem} simulations, the associated homogenization algorithms would have to be modified to provide the 3D stress and strain tensors. \r\n\r\nHydro-mechanically coupled \\acrshort{dem} simulations are also an important consideration for more accurate simulations. Here, the homogenization module should be modified to assess the homogenized fluid properties such as pore pressure and flow velocity vectors and the macroscale model needs to be modified to simulate poroelastic physics.\r\n\r\nUltimately, rigorous validation studies should be done with real-world applications to show the viability of this approach. Incorporating some of the above reccomendations will allow this up-scaling framework to validly be applied to complex geomechanical problems in order to avoid the computational demands of \\acrshort{dem} modelling. ", "meta": {"hexsha": "5d84a1cc17026a1ef8b6f681d8a8c019414836d9", "size": 9962, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapter6.tex", "max_stars_repo_name": "yetisir/masters-thesis", "max_stars_repo_head_hexsha": "026fef44fdfcf1175a14b5dd131ef65009653d67", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-07T16:17:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-07T16:17:25.000Z", "max_issues_repo_path": "Chapter6.tex", "max_issues_repo_name": "yetisir/masters-thesis", "max_issues_repo_head_hexsha": "026fef44fdfcf1175a14b5dd131ef65009653d67", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter6.tex", "max_forks_repo_name": "yetisir/masters-thesis", "max_forks_repo_head_hexsha": "026fef44fdfcf1175a14b5dd131ef65009653d67", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 211.9574468085, "max_line_length": 1272, "alphanum_fraction": 0.7909054407, "num_tokens": 1854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.34919141938779563}}
{"text": "\\documentclass[%handout,\n\tsans,\n\t12pt,\n\t%slidescentered,% center text on slide\n\t%draft,\t\t\t% compile as draft version\n\t%notes,\t\t\t% include notes in slides\n\t%compress\t\t% compress navigation bar\n]{beamer}\n\n\\beamertemplatenavigationsymbolsempty\n\n\\usetheme{default}\n\\usecolortheme{orchid}\n\\setbeamertemplate{frametitle}\n{\n    \\vspace*{1.5em}\\insertframetitle\\vspace*{-1.5em}\n}\n\\setbeamertemplate{footline}[frame number]\n\n\\usepackage[T1]{fontenc}\n\\usepackage[utf8x]{inputenc}\n\n\\usepackage{mathpazo}\n\\usepackage[british]{babel}\n\\usepackage{csquotes}\n\n\\newcommand{\\high}[1]{{\\usebeamercolor[fg]{structure} #1}}\n\\newcommand{\\bad}[1]{\\textcolor{red}{#1}}\n\\newcommand{\\gray}[1]{\\textcolor{darkgray}{#1}}\n\\newcommand{\\black}[1]{\\textcolor{black}{#1}}\n\n\\usepackage{amsmath,amssymb}\n\\usepackage{upgreek}\n\\usepackage{booktabs}\n\\usepackage{hyperref}\n\\usepackage{graphicx}\n\\usepackage{colortbl}\n\\usepackage{url}\n\\usepackage{setspace}\n\\usepackage{wrapfig}\n\\usepackage{tabularx}\n\\usepackage{xspace}\n\\usepackage{mathpartir}\n\n\\usepackage{tikz}\n\\usetikzlibrary{trees, positioning}\n\\usetikzlibrary{shapes.geometric}\n\n\\usepackage{isabelle,isabellesym}\n\\isabellestyle{it}\n\\def\\isacartoucheopen{}%\n\\def\\isacartoucheclose{}%\n\n\\newcommand{\\NN}{\\mathbb{N}}\n\\newcommand{\\QQ}{\\mathbb{Q}}\n\\newcommand{\\RR}{\\mathbb{R}}\n\\newcommand{\\CC}{\\mathbb{C}}\n\\renewcommand{\\epsilon}{\\varepsilon}\n\\renewcommand{\\phi}{\\varphi}\n\\def\\braces#1{[#1]}\n\\newcommand{\\wrt}{w.\\,r.\\,t.\\xspace}\n\\newcommand{\\eg}{e.\\,g.\\xspace}\n\\newcommand{\\ie}{i.\\,e.\\xspace}\n\\DeclareMathOperator\\caret{\\char`\\^}\n\n\\newcommand{\\hastype}{\\,:\\,}\n\\newcommand{\\cons}{::}\n\\newcommand{\\corrto}{\\overset{\\scriptscriptstyle\\wedge}{=}}\n\\newcommand{\\listapp}{\\mathbin{@}}\n\\newcommand{\\listnil}{[\\hskip0.3mm]}\n\\newcommand{\\listnth}{\\mathbin{!}}\n\\newcommand{\\expectation}{\\text{\\upshape E}}\n\n\\usepackage{manfnt}\n\\newenvironment{danger}{\\medbreak\\noindent\\hangindent=2pc\\hangafter=-2%\n  \\clubpenalty=10000%\n  \\hbox to0pt{\\hskip-\\hangindent\\hskip0.25em\\raisebox{-0.25em}[0pt][0pt]{\\dbend}\\hfill}\\small\\ignorespaces}%\n  {\\medbreak\\par}\n  %\\raisebox{-1.05em}[0pt][0pt]{\\Huge\\hskip.15em \\stixdanger}\n\n\\newcommand{\\etAl}{\\textit{et al.}\\xspace}\n\n%\\definecolor{mybg}{rgb}{0.9,0.9,0.9}\n\\definecolor{mybg}{rgb}{1,1,1}\n\\setbeamercolor{background canvas}{bg=mybg}\n\n\\title{Verification of an Approximation Algorithm for the Metric Travelling Salesperson Problem}\n\\author{\\normalsize Fabian Hellauer}\n\\institute[]{\\footnotesize Technische Universität München}\n\\date{\\footnotesize16 October 2019}\n\n\\begin{document}\n\n\\maketitle\n\n\\begin{frame}\n\\begin{center}\n\\includegraphics[width=5cm]{isabelle.pdf}\n\\end{center}\n\\end{frame}\n\n\\newcommand{\\pivot}[1]{{\\color{red}#1}}\n\\newcommand{\\ltpiv}[1]{{\\color{blue}#1}}\n\\newcommand{\\gtpiv}[1]{{\\color{olive}#1}}\n\n\\section{Verification of Algorithms}\n\\begin{frame}{Verification of Algorithms}%<very fast>\nReasons:\n\\begin{itemize}\n\t\\item a basis for reliable software\\pause\n\t\\item find mistakes in algorithm explanations\\pause\n\t\\item prove that verification of executable programs\n\tis feasible\\ % when using a modern tool like\n\t\\pause when using \\includegraphics[height=1em]{isabelle.pdf}Isabelle\\pause\n\\end{itemize}\nMathematical results might be a requirement.\n%In this case here, from graph theory.\n\\end{frame}\n\n\\section{Metric TSP}\n\\begin{frame}\n\tTSP is the problem of finding a tour of minimal cost within a graph.\\\\\\pause\n\tWe consider the special case where the nodes form a \\textit{metric space} with their weights.\\\\\\pause\n\tIn particular,\\pause\n\t\\begin{itemize}\n\t\t\\item \\textit{weight} is total\n\t\t% All TSP cities are connected by an edge, in other words we require the graph to be complete.\n\t\t\\item $\\textit{weight}\\ v_1\\ v_3\\ \\leq\\ \\textit{weight}\\ v_1\\ v_2\\ +\\ \\textit{weight}\\ v_2\\ v_3$\n\t\t\\item $0\\ \\leq\\ \\textit{weight}\\ v_1\\ v_2$\\pause\n\t\\end{itemize}\n\tIn such a graph, the cost of a \\textit{minimum spanning tree} is a lower bound on the optimal tour cost.\n\\end{frame}\n\n\\section{Approximation Algorithms}\n\\begin{frame}{Approximation Algorithms}\n\tWhat are Approximation Algorithms?\\pause%based on (metric) TSP\n\t\\vspace{1em}\n\t\\includegraphics[width=\\linewidth]{OPT_line}\n\t%OPT is the performance of an *actual* algorithm, namely the brute-force algorithm that tries all exponentially many node sequences.\n\t\\vspace{1em}\\pause %Since we consider undirected graphs, the reverse of a TSP tour is also a TSP tour (I omitted these duplicates in the graphic)\n\t\n\t\\high{Good solutions for NP-complete problems in polynomial time!}\n\\end{frame}\n\n\\section{Algorithm Explanation}\n\\begin{frame}\n\\begin{center}\n\t\\huge\\high{Algorithm Explanation}\n\\end{center}\n\\end{frame}\n\n\\subsection{Algorithm Overview}\n\\begin{frame}{Algorithm Overview}\nConsider a complete undirected graph$G = (V, E)$ and its minimum spanning tree $T$.\\pause%or rather: let one of its minimum spanning trees be $T$\n\nWe are going to\n\\begin{enumerate}\n\t\\item find such a $T$\\pause\n\t\\item generate a TSP tour using $T$'s edges\n\\end{enumerate}% and we are going to argue that T has cost less than an optimal TSP tour\n\\end{frame}\n\n\\subsection{MST vs.\\ TSP tour}\n\\begin{frame}{MST vs.\\ TSP tour}\n\\begin{center}\n\t\\includegraphics[height=2cm]{complete0.png}\n\\end{center}\n\\end{frame}\n\n\\subsection{MST vs.\\ TSP tour}\n\\begin{frame}{MST vs.\\ TSP tour}\n\\begin{center}\n\t\\includegraphics[height=2cm]{complete1.png}\n\\end{center}\n\\end{frame}\n\n\\subsection{MST vs.\\ TSP tour}\n\\begin{frame}{MST vs.\\ TSP tour}\n\\begin{center}\n\t\\includegraphics[height=2cm]{complete2.png}\n\\end{center}\n\\end{frame}\n\n\\subsection{MST vs.\\ TSP tour}\n\\begin{frame}{MST vs.\\ TSP tour}\n\\begin{center}\n\t\\includegraphics[height=2cm]{complete2.png}\n\\end{center}\n\\begin{isabelle}\n\\isacommand{lemma}\\isamarkupfalse%\n\\ minimum{\\isacharunderscore}spanning{\\isacharunderscore}tree{\\isacharunderscore}le{\\isacharunderscore}OPTWEIGHT{\\isacharcolon}\\isanewline\n\\ \\ \\isakeyword{assumes}\\ {\\isacartoucheopen}minimum{\\isacharunderscore}spanning{\\isacharunderscore}tree\\ T{\\isacharprime}\\ {\\isacharparenleft}symhull\\ E{\\isacharparenright}{\\isacartoucheclose}\\isanewline\n\\ \\ \\isakeyword{assumes}\\ {\\isacartoucheopen}{\\isadigit{2}}\\ {\\isasymle}\\ card\\ V{\\isacartoucheclose}\\isanewline\n\\ \\ \\isakeyword{shows}\\ {\\isacartoucheopen}set{\\isacharunderscore}cost\\ T{\\isacharprime}\\ {\\isasymle}\\ OPTWEIGHT{\\isacartoucheclose}\n\\end{isabelle}\n\\end{frame}\n\n\\subsection{Tour Search}\n\\begin{frame}{Tour Search}\nFind an edge sequence which\\pause\n\\begin{itemize}\n\t\\item uses exactly the MST's edges, each of which twice\\pause\n\t\\item visits every node\\pause\n\t\\item starts and ends at the same node\\pause\n\\end{itemize}\nThis sequence is then called a \\textit{pretour}.\\pause\n\nIts cost is twice the cost of the MST's edges.\n%And the MST's edges are, as mentioned, less than the cost of an optimal tour.\n\\end{frame}\n\n\\subsection{Duplicate Removal}\n\\begin{frame}{Duplicate Removal}\nTransform the pretour into a TSP tour:\n%typically we require TSP tours to visits each node exactly once. Our sequence doesn't do that yet.\n\\begin{itemize}\n\t\\item remove duplicate visits, replace them by shortcuts.\\pause\n\t%That means that when the sequence goes to an already visited node, we instead jump to the next one\n\t\n\t\\high{This can be done at one go.}\n\\end{itemize}\nThese shortcuts always exist and do not increase the cost. %That is why we require a complete metric graph\n\\end{frame}\n\n\\subsection{Time Complexity}%not verified\n\\begin{frame}{Time Complexity}\\pause\n\\begin{itemize}\n\t\\item MST generation: $\\mathcal{O}(|E| \\log |E|) = \\mathcal{O}(n^2 \\log (n^2)) = \\mathcal{O}(2(n^2 \\log n)) = \\mathcal{O}(n^2 \\log n)$%We use Kruskal's, which sorts edges by comparisons\n\t\\pause\n\t\\item Tour: $\\mathcal{O}(n)$ %This is the number of edges in the MST. We discuss later how we can arrange the edges in time linear to this, to-do: Is this actually covered?\n\t\\pause\n\\end{itemize}\noverall: $\\mathcal{O}(n^2 \\log n)$\n\\end{frame}\n\n\\section{Results}\n%What I did in the setting of this algorithm\n\\begin{frame}\n\\begin{center}\n\t\\huge\\high{Results}\n\\end{center}\n\\end{frame}\n\n\\subsection{Algorithm Sketch}\n\\begin{frame}{Algorithm Sketch} %and its Specification?\n%We have a fixed graph here, OPT depends on it\n\\begin{isabelle}\n\t\\isacommand{definition}\\isamarkupfalse%\n\t\\ two{\\isacharunderscore}approx\\ \\isakeyword{where}\\isanewline\n\t\\ \\ {\\isacartoucheopen}two{\\isacharunderscore}approx\\ {\\isacharequal}\\ SPEC\\ {\\isacharparenleft}{\\isasymlambda}T{\\isachardot}\\ is{\\isacharunderscore}tour\\ T\\ {\\isasymand}\\ cost\\ T\\ {\\isasymle}\\ OPT\\ {\\isacharplus}\\ OPT{\\isacharparenright}{\\isacartoucheclose}%explain lack of multiplication\n\t\\vspace{1mm}\\pause\\\\\n\t\\isacommand{definition}\\isamarkupfalse%\n\t\\ algorithm{\\isacharunderscore}sketch\\ \\isakeyword{where}\\ {\\isacartoucheopen}algorithm{\\isacharunderscore}sketch\\ {\\isacharequal}\\isanewline\n\tdo\\ {\\isacharbraceleft}\\isanewline\n\t\\ \\ MST\\ {\\isasymleftarrow}\\ SPEC\\ {\\isacharparenleft}{\\isasymlambda}E{\\isacharprime}{\\isachardot}\\ minimum{\\isacharunderscore}spanning{\\isacharunderscore}tree\\ {\\isacharparenleft}ind\\ E{\\isacharprime}{\\isacharparenright}\\ G{\\isacharparenright}{\\isacharsemicolon}\\isanewline\n\t\\ \\ pretour\\ {\\isasymleftarrow}\\ SPEC\\ {\\isacharparenleft}{\\isasymlambda}pT{\\isachardot}\\ int{\\isacharunderscore}vertices\\ pT\\ {\\isacharequal}\\ nodes\\ G\\\\ \\ \\ \\ \\ {\\isasymand}\\ cost\\ pT\\ {\\isasymle}\\ set{\\isacharunderscore}cost\\ MST\\ {\\isacharplus}\\ set{\\isacharunderscore}cost\\ MST{\\isacharparenright}{\\isacharsemicolon}\\isanewline\n\t\\ \\ tour\\ {\\isasymleftarrow}\\ SPEC\\ {\\isacharparenleft}{\\isasymlambda}T{\\isachardot}\\ is{\\isacharunderscore}tour\\ T\\ {\\isasymand}\\ cost\\ T\\ {\\isasymle}\\ cost\\ pretour{\\isacharparenright}{\\isacharsemicolon}\\isanewline\n\t\\ \\ RETURN\\ tour\\isanewline\n\t{\\isacharbraceright}{\\isacartoucheclose}\n\\end{isabelle}\\pause\n\\vspace{-4mm}\n\\begin{theorem}\n\t\\hspace{2.6cm}$\\textit{algorithm{\\isacharunderscore}sketch} \\le \\textit{two{\\isacharunderscore}approx}$\\\\\n\\upshape if $G$ is a complete finite metric graph.\n\\end{theorem}\n\\end{frame}\n\n\\subsection{Phase I}%MST generation\n%It was already in a library, but had to be adjusted\n\\begin{frame}{Phase I}\n\n\\begin{isabelle}\n\t\\isacommand{locale}\\isamarkupfalse%\n\t\\ finite{\\isacharunderscore}weighted{\\isacharunderscore}connected{\\isacharunderscore}graph\\ {\\isacharequal}\\ finite{\\isacharunderscore}weighted{\\isacharunderscore}graph\\ {\\isacharplus}\\ connected{\\isacharunderscore}graph\\isanewline\n\t\\isakeyword{begin}\\isanewline\n\t\\isanewline\n\t\\ \\ \\isacommand{lemma}\\isamarkupfalse%\n\t\\ kruskal{\\isadigit{0}}{\\isacharunderscore}MST{\\isacharcolon}\\ {\\isacartoucheopen}s{\\isachardot}kruskal{\\isadigit{0}}\\ {\\isasymle}\\ SPEC\\ {\\isacharparenleft}{\\isasymlambda}E{\\isacharprime}{\\isachardot}\\ minimum{\\isacharunderscore}spanning{\\isacharunderscore}tree\\ {\\isacharparenleft}ind\\ E{\\isacharprime}{\\isacharparenright}\\ G{\\isacharparenright}{\\isacartoucheclose}\n\t\\isanewline\n\t\\isanewline\n\t\\isacommand{end}\\isamarkupfalse%\n\\end{isabelle}\\pause%This also includes that the forest is a tree (simple) and that it still is minimal in the symhull (quite a bit of work...)\n\n\\begin{isabelle}\n\t\\isacommand{sublocale}\\isamarkupfalse%\n\t\\ complete{\\isacharunderscore}finite{\\isacharunderscore}weighted{\\isacharunderscore}graph\\ {\\isasymsubseteq}\\\\ \\ \\ finite{\\isacharunderscore}weighted{\\isacharunderscore}connected{\\isacharunderscore}graph\n\t\\end{isabelle}\\pause\nThis required a reorganisation in the \\textit{Kruskal} AFP entry.\n\\end{frame}\n\n\\subsection{Library Connections}\n\\begin{frame}{Library Connections}\\pause\n\\vspace{3mm}\n\\begin{enumerate}\n\t\\item \\textit{Kruskal}: edges with weight field, undirected/directed\\pause\n\t%to-do: vielleicht unterringeln?\n\t% I improved this library: I had to reorganise this one to get what I want without unnecessary assumptions.\n\t\\item \\textit{DFS\\_Framework}: edges are node relations, directed\\pause\n\t\\item \\textit{Koenigsberg\\_Friendship}: edges have a label, undirected\\pause\n\t%Even worse, there are different notions of \"undirected\"\n\t%So we really have the worst case in terms of compatibility.\n\t%Koenigsberg-Friendship also forbids loops, for technical reasons\n\t%It also reinterprets..., Kruskal also has a definition \"is_path_undir\".\n\t%to-do: add Noschinski, a third notion of \"undirected\".\n\t%\"There are even more graph libraries out there: The somewhat new work by Noschinski starts anew,\n\t% with the reasonable modeling of undirected edges as two-element-sets (It sounds reasonable, and is well argued for).\n\t%Sadly, the fresh start did not really establish a new standard.\"\n\\end{enumerate}\n%Example Conversion:\\pause\n\\begin{isabelle}\n\\isacommand{lemma}\\isamarkupfalse%\n\\ ex{\\isadigit{1}}{\\isacharunderscore}the{\\isacharunderscore}path{\\isacharcolon}\\isanewline\n\\ \\ \\isakeyword{assumes}\\ {\\isacartoucheopen}is{\\isacharunderscore}path{\\isacharunderscore}undir\\ G\\ v\\ ps\\ v{\\isacharprime}{\\isacartoucheclose}\\isanewline\n\\ \\ \\isakeyword{shows}\\ {\\isacartoucheopen}{\\isasymexists}{\\isacharbang}ps{\\isacharprime}{\\isachardot}\\ map\\ fst\\ ps{\\isacharprime}\\ {\\isacharequal}\\ map\\ fst\\ ps\\ {\\isasymand}\\ is{\\isacharunderscore}path{\\isacharunderscore}undir\\ G\\ v\\ ps{\\isacharprime}\\ v{\\isacharprime}{\\isacartoucheclose}\n\\isanewline \\pause\n\\isanewline\n\t\\isacommand{definition}\\isamarkupfalse%\n\t\\ the{\\isacharunderscore}path\\ \\isakeyword{where}\\isanewline\n\t\\ \\ {\\isacartoucheopen}the{\\isacharunderscore}path\\ nodelist\\ lst\\ {\\isacharequal}\\ {\\isacharparenleft}case\\ nodelist\\ of\\isanewline\n\t\\ \\ \\ \\ {\\isacharbrackleft}{\\isacharbrackright}\\ {\\isasymRightarrow}\\ {\\isacharbrackleft}{\\isacharbrackright}\\ {\\isacharbar}\\isanewline\n\t\\ \\ \\ \\ n\\ {\\isacharhash}\\ ns\\ {\\isasymRightarrow}\\ THE\\ ps{\\isachardot}\\ map\\ fst\\ ps\\ {\\isacharequal}\\ nodelist\\\\\\ \\ \\ \\ \\ \\ {\\isasymand}\\ is{\\isacharunderscore}path{\\isacharunderscore}undir\\ G\\ n\\ ps\\ lst{\\isacharparenright}{\\isacartoucheclose}\n\\end{isabelle}\n\n\\end{frame}\n\n\\subsection{Library Connections -- Example}\n\\begin{frame}{Library Connections -- Example}\\pause\n\\begin{isabelle}\n\t\\isacommand{lemma}\\isamarkupfalse%\n\t\\ spanning{\\isacharunderscore}forest{\\isacharunderscore}symhull{\\isacharcolon}\\isanewline\n\t\\ \\ {\\isacartoucheopen}spanning{\\isacharunderscore}forest\\ F\\ {\\isasymlparr}nodes{\\isacharequal}V{\\isacharcomma}\\ edges\\ {\\isacharequal}\\ E{\\isasymrparr}\\ \\\\\\ \\ \\ \\ {\\isasymLongrightarrow}\\ spanning{\\isacharunderscore}forest\\ F\\ {\\isasymlparr}nodes{\\isacharequal}V{\\isacharcomma}\\ edges\\ {\\isacharequal}\\ symhull\\ E{\\isasymrparr}{\\isacartoucheclose}\n\\end{isabelle}\\pause\n\\begin{isabelle}\n\t\\isacommand{lemma}\\isamarkupfalse%\n\t\\ {\\isacharparenleft}\\isakeyword{in}\\ finite{\\isacharunderscore}weighted{\\isacharunderscore}graph{\\isacharparenright}\\\\\\ \\ spanning{\\isacharunderscore}forest{\\isacharunderscore}symhull{\\isacharunderscore}preimage{\\isacharcolon}\\isanewline\n\t\\ \\ \\isakeyword{assumes}\\ {\\isacartoucheopen}spanning{\\isacharunderscore}forest\\ {\\isasymlparr}nodes{\\isacharequal}V{\\isacharcomma}\\ edges{\\isacharequal}F{\\isasymrparr}\\ {\\isasymlparr}nodes{\\isacharequal}V{\\isacharcomma}\\\\\\ \\ \\ \\  edges{\\isacharequal}symhull\\ E{\\isasymrparr}{\\isacartoucheclose}\\isanewline\n\t\\ \\ \\isakeyword{shows}\\ {\\isacartoucheopen}{\\isasymexists}F{\\isacharprime}{\\isachardot}\\\\\\ \\ \\ \\ spanning{\\isacharunderscore}forest\\ {\\isasymlparr}nodes{\\isacharequal}V{\\isacharcomma}\\ edges{\\isacharequal}F{\\isacharprime}{\\isasymrparr}\\ {\\isasymlparr}nodes{\\isacharequal}V{\\isacharcomma}\\ edges{\\isacharequal}E{\\isasymrparr}\\isanewline\n\t\\ \\ \\ \\ {\\isasymand}\\ edge{\\isacharunderscore}weight\\ {\\isasymlparr}nodes{\\isacharequal}V{\\isacharcomma}\\ edges{\\isacharequal}F{\\isacharprime}{\\isasymrparr}\\ \\\\\\ \\ \\ \\ \\ \\  {\\isacharequal}\\ edge{\\isacharunderscore}weight\\ {\\isasymlparr}nodes{\\isacharequal}V{\\isacharcomma}\\ edges{\\isacharequal}F{\\isasymrparr}{\\isacartoucheclose}\n\\end{isabelle}\n\\end{frame}\n\n\\subsection{Phase II}\n\\begin{frame}{Phase II}\n\\begin{center}\n\\includegraphics[height=7cm]{Sorted_binary_tree_preorder}\n\\end{center}\n%to-do: attribute \"By Sorted_binary_tree.svg: Milesderivative work: Pluke (talk) - Sorted_binary_tree.svg, Public Domain, https://commons.wikimedia.org/w/index.php?curid=10616003\"\n\\end{frame}\n\n\\subsection{Phase II -- Parametrisation} %to-do: replace according to e-mail\n\\begin{frame}{Phase II -- Parametrisation}\n\\vspace{8mm}\nWe use the \\textit{DFS-Framework}. This is the parametrisation:\n\\vspace{-2mm}\n\\begin{isabelle}\n\t\\isacommand{definition}\\isamarkupfalse%\n\t\\ fp{\\isadigit{0}}{\\isacharunderscore}params\\ {\\isacharcolon}{\\isacharcolon}\\ {\\isachardoublequoteopen}{\\isacharprime}v\\ fp{\\isadigit{0}}{\\isacharunderscore}param{\\isachardoublequoteclose}\\ \\isakeyword{where}\\isanewline\n\t{\\isachardoublequoteopen}fp{\\isadigit{0}}{\\isacharunderscore}params\\ {\\isasymequiv}\\ dflt{\\isacharunderscore}parametrization\\ state{\\isachardot}more\\isanewline\n\t\\ \\ {\\isacharparenleft}RETURN\\ {\\isasymlparr}\\ tour{\\isacharunderscore}list\\ {\\isacharequal}\\ {\\isacharbrackleft}{\\isacharbrackright}\\ {\\isasymrparr}{\\isacharparenright}\\isanewline\n\t\\ \\ {\\isasymlparr}on{\\isacharunderscore}discover\\ {\\isacharcolon}{\\isacharequal}\\ {\\isasymlambda}{\\isacharunderscore}\\ n\\ s{\\isachardot}\\ RETURN\\ {\\isasymlparr}tour{\\isacharunderscore}list\\ {\\isacharequal}\\ tour{\\isacharunderscore}list\\ s\\ {\\isacharat}\\ {\\isacharbrackleft}n{\\isacharbrackright}{\\isasymrparr}\\ {\\isasymrparr}{\\isachardoublequoteclose}\n\\end{isabelle}\\pause\n\\vspace{-5mm}\n\\begin{isabelle}\n\t\\isacommand{locale}\\isamarkupfalse%\n\t\\ node{\\isacharunderscore}and{\\isacharunderscore}MST{\\isacharunderscore}in{\\isacharunderscore}graph\\ {\\isacharequal}\\isanewline\n\t\\ \\ complete{\\isacharunderscore}finite{\\isacharunderscore}metric{\\isacharunderscore}graph\\ G\\ {\\isacharplus}\\isanewline\n\t\\ \\ T{\\isacharcolon}\\ tree\\ T\\isanewline\n\t\\ \\ \\isakeyword{for}\\ G{\\isacharcolon}{\\isacharcolon}{\\isacartoucheopen}{\\isacharparenleft}{\\isacharprime}v{\\isacharcolon}{\\isacharcolon}metric{\\isacharunderscore}space{\\isacharcomma}real{\\isacharparenright}\\ graph{\\isacartoucheclose}\\isanewline\n\t\\ \\ \\isakeyword{and}\\ T{\\isacharcolon}{\\isacharcolon}{\\isacartoucheopen}{\\isacharparenleft}{\\isacharprime}v{\\isacharcomma}real{\\isacharparenright}\\ graph{\\isacartoucheclose}\\ {\\isacharplus}\\isanewline\n\t\\ \\ \\isakeyword{fixes}\\ v\\isactrlsub {\\isadigit{0}}{\\isacharcolon}{\\isacharcolon}{\\isacartoucheopen}{\\isacharprime}v{\\isacartoucheclose}\\isanewline\n\t\\ \\ \\isakeyword{assumes}\\ v{\\isacharunderscore}in{\\isacharunderscore}V{\\isacharcolon}\\ {\\isacartoucheopen}v\\isactrlsub {\\isadigit{0}}\\ {\\isasymin}\\ V{\\isacartoucheclose}\\isanewline\n\t\\ \\ \\isakeyword{and}\\ mst{\\isacharcolon}\\ {\\isacartoucheopen}minimum{\\isacharunderscore}spanning{\\isacharunderscore}tree\\ T\\ G{\\isacartoucheclose}\n\\end{isabelle}\n\\end{frame}\n\n%to-do: simplification of Phase II? not really my work, but something which slowed me down...\n\n\\section{Plans}\n\\begin{frame}\n\\begin{center}\n\t\\huge\\high{Plans}%time ran out sadly...\n\\end{center}\n\\end{frame}\n\n\\subsection{Input Generation}% We need a script that generates the edge weights for us.\n\\begin{frame}{Input Generation}\nConsider a Euclidean space like $\\RR^2$, $\\RR^3$,\\dots\n\t\\begin{itemize}\n\t\t\\item A popular metric is the \\textit{Euclidean} metric.\\pause\n\t\t\n\t\t\\bad{It is often irrational, and thus difficult to store and compare with infinite precision.}\\pause\n\t\t\\item In contrast, the \\textit{maximum metric} and the \\textit{Manhattan metric} return natural numbers. %When the coordinates are natural numbers.\n\t\t%to-do: definition? small drawing?\n\t\\end{itemize}\n\t%application drilling robot\n\\end{frame}\n\n\\subsection{DFS Invariant}\n\\begin{frame}{DFS Invariant}\\pause\n\tfinish this proof\\pause\n\t\\vspace{-2mm}\n\t\\begin{isabelle}\n\t\t\\isacommand{lemma}\\isamarkupfalse%\n\t\t\\ {\\isacartoucheopen}dfs{\\isachardot}is{\\isacharunderscore}invar\\ {\\isacharparenleft}{\\isasymlambda}s{\\isachardot}\\ valid{\\isacharunderscore}graph{\\isachardot}tour\\ {\\isacharparenleft}ind{\\isacharprime}\\ {\\isacharparenleft}dom\\ {\\isacharparenleft}discovered\\ s{\\isacharparenright}{\\isacharparenright}{\\isacharparenright}\\ {\\isacharparenleft}tour{\\isacharunderscore}list\\ s{\\isacharparenright}{\\isacharparenright}{\\isacartoucheclose}\n\t\\end{isabelle}\\pause\n\tAdvancing this proof has already led to generally useful statements for the \\textit{DFS-Framework}, e.g.\\ \\pause\n\t\\begin{isabelle}\n\t\t\\isacommand{lemma}\\isamarkupfalse%\n\t\t\\ i{\\isacharunderscore}snd{\\isacharunderscore}pending{\\isacharunderscore}sane{\\isacharcolon}\\ {\\isacartoucheopen}dfs{\\isachardot}is{\\isacharunderscore}invar\\ {\\isacharparenleft}{\\isasymlambda}s{\\isachardot}\\ snd\\ {\\isacharbackquote}\\ {\\isacharparenleft}pending\\ s{\\isacharparenright}\\ {\\isasymsubseteq}\\ V{\\isacharparenright}{\\isacartoucheclose}\n\t\\end{isabelle}\\pause\n\t\\begin{isabelle}\n\t\t\\isacommand{lemma}\\isamarkupfalse%\n\t\t\\ i{\\isacharunderscore}stack{\\isacharunderscore}sane{\\isacharcolon}\\ {\\isacartoucheopen}dfs{\\isachardot}is{\\isacharunderscore}invar\\ {\\isacharparenleft}{\\isasymlambda}s{\\isachardot}\\ set\\ {\\isacharparenleft}stack\\ s{\\isacharparenright}\\ {\\isasymsubseteq}\\ V{\\isacharparenright}{\\isacartoucheclose}\n\t\\end{isabelle}\\pause\n\t\\begin{isabelle}\n\t\t\\isacommand{lemma}\\isamarkupfalse%\n\t\t\\ i{\\isacharunderscore}discovered{\\isacharunderscore}sane{\\isacharcolon}\\ {\\isacartoucheopen}dfs{\\isachardot}is{\\isacharunderscore}invar\\ {\\isacharparenleft}{\\isasymlambda}s{\\isachardot}\\ dom\\ {\\isacharparenleft}discovered\\ s{\\isacharparenright}\\ {\\isasymsubseteq}\\ V{\\isacharparenright}{\\isacartoucheclose}\n\t\\end{isabelle}\n\\end{frame}\n\n\\section{Conclusion}\n\\begin{frame}{Conclusion}\nEven with parts already verified, formal verification can require a lot of work:\n\\begin{itemize}\n\t\\item Differing graph formalisations\\pause!\\pause\n\t%in particular connecting Digraph.graph_rec to my own finite_complete_weighted...graph\n\t\\item For this particular algorithm, a lot of assumptions have to be collected and formulated.\\pause %complete_finite_weighted is actually complete_finite_weighted_simple_loopfree_metric_graph\n\t\n\t%\"Not really part of a conclusion, but I want to mention it here since I had to leave out much context earlier for brevity.\"\n\t\\item Definitions have many dependencies. %They e.g. have to fix a graph, a subtree and an arbitrary node at the same time.\n\\end{itemize}\n\\end{frame}\n\n\\section{Questions}\n\\begin{frame}\n\\begin{center}\n\t\\huge\\high{Questions}\n\\end{center}\n\\end{frame}\n\n%to-do: Problems?\n\n\\end{document}\n\n%to-do: compare to the plan from the meeting:\n%25+5min\n\n%explain in the presentation:\n\n%Bibliotheken vorstellen, Wahl begründen\n%--> Graphformalisierungen: directed vs. undirected edges in both phases. Welche gibt es alle?\n%edge labels, i.e. a third field besides start node and end node 5min\n%MST lemma zeigen, wieso nicht Graph_Theory? 5min\n%was ist der projektstatus? 5min\n%maybe a slide about the commit count?\n%add dfs-sublocale statement to plans. \"This is already proven. However, the set membership must be implemented...\"\n", "meta": {"hexsha": "d57f3f5aef6b9f06024c710f61d494145723de4a", "size": 22619, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "slides_backup/main.tex", "max_stars_repo_name": "helli/tsp-approximation", "max_stars_repo_head_hexsha": "2b0e2abc06190402f507664980c65bc8ce3fad7f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "slides_backup/main.tex", "max_issues_repo_name": "helli/tsp-approximation", "max_issues_repo_head_hexsha": "2b0e2abc06190402f507664980c65bc8ce3fad7f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slides_backup/main.tex", "max_forks_repo_name": "helli/tsp-approximation", "max_forks_repo_head_hexsha": "2b0e2abc06190402f507664980c65bc8ce3fad7f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.4945295405, "max_line_length": 434, "alphanum_fraction": 0.766523719, "num_tokens": 7460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.34919141938779563}}
{"text": "\\documentclass{fancyArticle}\n\\usepackage{lipsum}\n\n\\title{A Sample Document}\n\\author{Gary Baker}\n\\date{\\today}\n\n\\begin{document}\n\\maketitle\n\n\\begin{abstract}\n  \\lipsum[1]\n\\end{abstract}\n\\pagebreak\n\n\\section{A first section}\n\nThis\\footnote{\\lipsum[1][3]} demonstrates the footnote\nstyle. \\lipsum[4] Here's another footnote\\footnote{\\lipsum[30][1]}\nfollowed by a numbered equation.\n\n\\begin{equation}\n  \\label{eq:1}\n  e^{i\\pi}+1 = 0\n\\end{equation}\n\n\\lipsum[5]\n\n\\subsection{A subsection}\n\n\\lipsum[6]\n\n\\begin{equation*} \n  V(l) = \\max_{\\beta\\geq 0}\\left\\{ -c(\\beta) * \\Delta + e^{-r\\Delta}\n    \\left[ \\int \\frac{1}{2} (\\tanh(l/2)+1) V(l+\\hat{s}) f_\\beta(s) ds \\right]\\right\\}\n\\end{equation*}\n\n\\lipsum[7]\n\n\\section{A section with some citations}\n\n\\cite{Nash1950} and \\cite{Rubinstein1982} say some things about\nbargaining. Those citations are also clickable links to their\nrespective entries in the bibliography.\n\n\\lipsum [20-21]\n\n\\pagebreak\n\\bibliography{sampleBib.bib}\n\n\n\\end{document}", "meta": {"hexsha": "0ac0a08665b49270f2810c2f3a6f964ccf2cf33c", "size": 980, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "sample.tex", "max_stars_repo_name": "ggbaker/fancy-article", "max_stars_repo_head_hexsha": "442b6966216a5d420095293dc1fe71ce428669f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sample.tex", "max_issues_repo_name": "ggbaker/fancy-article", "max_issues_repo_head_hexsha": "442b6966216a5d420095293dc1fe71ce428669f9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sample.tex", "max_forks_repo_name": "ggbaker/fancy-article", "max_forks_repo_head_hexsha": "442b6966216a5d420095293dc1fe71ce428669f9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.8461538462, "max_line_length": 85, "alphanum_fraction": 0.7071428571, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704502361149, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.34919141782045776}}
{"text": "\\documentclass{article}\n\n\\usepackage[british]{babel}\n\\usepackage[useregional]{datetime2}\n\\DTMlangsetup[en-GB]{showdayofmonth=false}\n\n\\usepackage[utf8]{inputenc}\n\n\\usepackage{amsmath}\n\\usepackage{float}\n\\usepackage{graphicx}\n\\usepackage{hyperref}\n\\hypersetup{\n    colorlinks=true,\n    linkcolor=black,\n    filecolor=magenta,      \n    urlcolor=blue,\n}\n\n\\title{Machine Learning}\n\\author{Josh Myers-Dean \\and Robin Cosbey}\n\\date{\\today}\n\n\\begin{document}\n\n\\maketitle\n\\newpage\n\\tableofcontents\n\\newpage\n\n\\section{Introduction} \nThe term ``machine learning'' was defined in 1959 as \\textit{a field of study that gives computers the ability to learn without being explicitly programmed.} This means that rather than giving a computer a list of instructions to follow, we take advantage of the computer's representational abilities. The computer \\textit{learns} patterns in data. Machine learning is essentially a math problem: $y = h(x)$ where $x$ is the input, $y$ is the output and $h$ represents the function (mathematical model) applied. In simple terms we are learning a mapping from $x$ to $y$. The goal of this workshop is to dive into the topics presented in \\ref{fig:flow}, show how the process of each step and provide some resources.\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=3in]{flowchart.jpeg}\n    \\caption{General machine learning workflow. \\href{https://www.freecodecamp.org/news/every-single-machine-learning-course-on-the-internet-ranked-by-your-reviews-3c4a7b8026c0/}{Link}}\n    \\label{fig:flow}\n\\end{figure}\n\n\\subsection{Unsupervised and Supervised Learning}\nWe primarily see \\textit{unsupervised} and \\textit{supervised} learning algorithms. Both are given a set of examples to learn from, known as \\textit{training data}. In the case of supervised learning, we have ground truth output associated with the input data unlike unsupervised learning in which the computer is only given the input and ``clusters'' the examples based on similarity rather than learning from the mappings provided. Most of this workshop will focus on supervised learning. \n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=3.1in]{supervision.png}\n    \\caption{Unsupervised consists of clustering whereas supervised (in this case binary classification) consists of finding a boundary between data points. \\href{https://chatbotsmagazine.com/lets-know-supervised-and-unsupervised-in-an-easy-way-9168363e06ab}{Link}}\n\\end{figure}\n\n\\newpage\n\\subsection{Tasks} \n\nThe two general types of problems that can be solved with supervised machine learning techniques are \\textbf{classification} and \\textbf{regression}. The main difference between the two is the output: classification has a categorical (discrete) output whereas regression has a numerical (continuous) output. \n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=3.5in]{tasks.png}\n    \\caption{Basic distinction between the two types of tasks. \\href{https://medium.com/datadriveninvestor/supervised-vs-unsupervised-machine-learning-5200ffa7301a}{Link}}\n    \\label{fig:tasks}\n\\end{figure}\n\n\\subsubsection{Classification}\nClassification algorithms are used when the outputs are restricted to a limited set of values. The basic form is \\textit{binary classification} as shown in \\ref{fig:tasks} in which the model assigns each input to one of two outputs. For example, if we have a model that identifies if an image contains a dog, the output would be the prediction of either `dog' or `not dog' (true or false).  \n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=3.5in]{dogs.jpg}\n    \\caption{Can you tell which photos contain a dog? Can a computer? \\href{https://www.npr.org/sections/thesalt/2016/03/11/470084215/canine-or-cuisine-this-photo-meme-is-fetching}{Link}}\n\\end{figure}\n\n\\newpage\u0002\n\\subsubsection{Regression}\nRegression involves continuous values such as temperature, length and price. You typically see regression models used for finding relationships between variables and for forecasting. How do age, gender and diet impact height? This is an example of input variables (age, gender and diet), referred to as \\textit{predictor variables}, and their relationship to a single output (height) known as the \\textit{outcome variable}. Unlike classification, we determine a trend from the training data fed into the model.  \n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=3.5in]{regression.png}\n    \\caption{Regression line showing the relationship between hours studied and exam score. \\href{https://stackabuse.com/linear-regression-in-python-with-scikit-learn/}{Link}}\n\\end{figure}\n\n\\newpage\n\\section{Data}\nSo what does data look like in machine learning? \nAside from numerical data, anything that can be encoded as a numerical value or set of numerical values, such as images, words, or audio. \nWith images, we can encode each pixel into their RGB numerical value. \nAudio data can be represented numerically based on features or by way of images with what are called spectograms. \nWords can be encoded as numbers, or word frequencies throughout an entire document might be used. \nWe also use categorical data, a number that represents a group i.e. dogs, cats, or birds used primarily in classification tasks. \nTypically, this data is put into a matrix, let's examine some famous data sets where you can see real examples of data used in machine learning.\n\n\\subsection{Data Sets}\nLet's examine some data sets that are commonly used by those exploring machine learning. Probably the most famous among these data sets, is the MNIST data set; a collection of handwritten numbers. We can use this data set to classify each picture as the number it is meant to represent. The MNIST data set is quite large and machine learning models are able to get up to 99\\% accuracy classifying these images.\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=4.5in]{mnist.png}\n    \\caption{MNIST Data set \\href{http://yann.lecun.com/exdb/mnist/}{dataset linked here}.}\n\\end{figure}\n\n\\newpage\n\nAnother smaller data set is the Iris data set. In this case, we are not dealing with image data, we are given attributes. There are three kinds of iris represented in this data set and we are given four attributes of each flower: the sepal length and width, and the petal length and width.  \n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=4.5in]{iris.png}\n    \\caption{Iris Data set \\href{https://archive.ics.uci.edu/ml/datasets/iris}{dataset linked here}.}\n\\end{figure}\n\nThis is a great data set for beginners because there are only 150 iris samples, making it easy to test and debug. Take a look at the links included to get a feel for what data looks like in machine learning.\n\n\\subsection{Bias in Data}\nAs you begin a machine learning project, one of the first steps is to find the dataset you will be working with. As you are forming the initial questions that you hope to answer with your efforts make sure to also ask the data some questions. Before you start building a model to work with the data, you should have a firm understanding of the distribution and makeup of the data itself. Many news stories have surfaced over the years indicating the explicit, inherent biases in many publicly released face and object recognition systems and it is not hard to believe that similar stories can be found in other domains. \n\nThis analysis of your data is especially important when considering problems directly related to society. As the systems we build gain trust from the public, we, as computer scientists, can have great implications unknowingly on the world we live in. Throughout this analysis be on the lookout for an uneven distribution of data. Additionally, keep in mind that the biases present throughout history can be found implicitly in the datasets produced in those times and by using that data to train a model you are propagating those biases forward through time. Sometimes you may need to evaluate the types of problems you are looking to solve and ensure the value of this pursuit for the community.\n\n\\newpage\n\\subsection{Data Preparation}\nThe above datasets, MNIST and Iris, are \\textit{clean}. There are no missing values, or random Unicode characters that are going to trip you up when trying to parse the data. Often, data needs to be cleaned and made consistent. This process of making sure that data is clean can take up a lot of time. If an entire chunk of data is missing should it be averaged with its neighbors or be given the value of the previous data point? These are considerations a machine learning engineer will encounter. There is also the consideration of how to store input and output data as you will often train and re-train a model many times with different parameters that can be tuned called hyperparameters or maybe parse the data in a different way to see if that leads to any performance gains. Since you will want to run your model many times, you don't want to have to re-parse your cleaned data each time you want to run it as that takes a lot of time, so you will want to store your cleaned data somehow. You may also want to save various configurations of your trained model, so you will need an efficient and organized way to store trained models. You can also create data based off of your current data set, this is called data augmentation and may be something as simple as when building an image classifier reflecting some of your images horizontally or vertically to make you model more robust to image orientation. So, data preparation is a complex beast. There are many techniques that can be explored and many components to consider when preparing data.\n\nAfter our data has been cleaned we typically want to split our data into train, development (sometimes called ``validation''), and test. You'll understand more in depth as to how these data sets are used after reading the \\textit{Training} section. For now, understand that in order to train a model we will need data it can see (train), new data it can see to check its progress while training (development), and more data to see if it learned a pattern that can be applied to unseen data (test). We generally want to reserve 70\\% for our training set, 10\\% for our development set, and 20\\% for our test set. You are not limited to splitting your data in this way and can try out different configurations as well.\n\n\\subsection{Training} \nOnce we have an understanding of the data we are working with, have preprocessed the data appropriately and split the data into a train, development and test set, now it is time to design your model. More on the types of the basic machine learning and deep learning models in future sections. The training phase allows the the model to learn from the examples provided and understand the presents in the data. The development, or validation, phase is when we tune hyperparameters -- \\textit{hyperparameters} are typically related to the model architecture. Slight changes to the hyperparameters will produce different results with the model. This process repeats for a predefined amount of time. Only once we have completed training and hyperparameter tuning do we turn to the test data. The test set is used to independently assess the accuracy of the model on held out data that has not been seen previously. \n\n\\newpage\n\\section{Machine Learning \\& Deep Learning} \nThere are many differences between deep learning and machine learning algorithms. Features are pieces of information that are intended to be relevant to performing a task. For example, if we were to build an animal classifier using a machine learning algorithm a feature we may want to include is the type of coat an animal has: fur, scales, or feathers. We would want to include as many of these distinctive features as possible for each animal and then give those pieces of information to our machine learning algorithm and this would create a model that can classify animals. But with deep learning we wouldn't need to manually identify distinctive characteristics of animals, we can just give our deep learning algorithm thousands of pictures of animals. Deep learning algorithms are capable of finding which pieces of information about a picture for example, are important without human assistance. This is one benefit of deep learning algorithms.\n\nAnother difference between machine learning and deep learning algorithms is their expressiveness. Machine learning algorithms generally revolve around optimizing linear functions to fit our data. However, not all patterns found in data can be expressed by linear functions. \n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=5.0in]{linearvsnonlinear.png}\n    \\caption{Non-linear models are able to model more complex patterns.}\n\\end{figure}\n\nDeep learning algorithms can consist of one or more linear or non-linear transformations. Because of this, deep learning models are able to model both linear and non-linear patterns in data. This is very powerful, and is the \\textit{secret sauce} of deep learning models. Because deep learning algorithms are able to model much more complex and nuanced patterns in data, they require a lot more data than traditional machine learning algorithms which are trying to model simpler patterns. While a machine learning model may require thousands of data points to do well, a deep learning model may require millions making deep learning much more computationally expensive.\n\n\\newpage\n\\subsection{Decision Trees} \nDecision trees are tree-like structures that can represent probability, decisions, and much more.\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=4.5in]{decisiontree.png}\n    \\caption{Decision Tree}\n\\end{figure}\n\n\\subsubsection{Random Forest}\nRandom Forest is a supervised machine learning algorithm that can be used for both classification and regression tasks that consists of a collection of decision trees, hence the name. Here is the general algorithm:\n\n\\begin{enumerate}\n    \\item Split data into $n$ random sets selecting $m$ random features from each sample.\n    \\item Create a decision tree using each subset of data.\n    \\item Given new sample, each of these independent trees makes a prediction.\n    \\item The prediction with the most \"votes\" from our trees is our overall prediction.\n\\end{enumerate}\n\nFor a regression task, we would average the predictions made by all of the decision trees. This idea of averaging decisions of multiple models is called bootstrap aggregating or bagging and can reduce variance and overfitting.\n\nEssentially, every decision tree will make a prediction and the most common prediction in among all of the decision trees will be the outcome. When using the random forest algorithm for regression, we will average the output of each decision tree. \n\n\\newpage\n\\subsection{Support Vector Machines (SVMs)} \nSupport vector machines are a simple model that do not require a large amount of data and separate classes represented in data. SVMs are simple discriminative classifiers that output an optimal decision boundary between the datapoints provided. When new datapoints are fed through the SVM, they are classified based on where they fall in relation to the decision boundary. This boundary is often referred to as a ``hyperplane.''  The margin is the distance from the boundary to the nearest datapoint. We want to find a decision boundary that allows points to be in their respective classes without crossing the boundary into other classes and a good margin is one where this separation is large for all classes represented. scikit-learn offers a SVM tool that is easy to download to test with given data. More information about SVMs and the toolkit can be found \\href{https://scikit-learn.org/stable/modules/svm.html}{here}.\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=3.5in]{svm.jpeg}\n    \\caption{Decision boundary (yellow dashed line) separating the red from blue. \\href{https://medium.com/deep-math-machine-learning-ai/chapter-3-support-vector-machine-with-math-47d6193c82be}{Link}}\n\\end{figure}\n\n\\newpage\n\\subsection{KNN} \nK-Nearest Neighbors is an supervised machine learning algorithm that can be used for classification and regression tasks. Let's focus on classification. In this case we won't do any training using our training data, we will using the position of our training data in space to classify unseen data points.\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=4.0in]{knn.png}\n    \\caption{KNN Algorithm.}\n\\end{figure}\n\n\\begin{enumerate}\n    \\item Select number of neighbors to examine $k$.\n    \\item Given an unseen data point, find $k$ nearest data points.\n    \\item The class that appears the most of those $k$ nearest data points is the class of our unseen data point.\n\\end{enumerate}\n\nYou can experiment with different distance metrics like Euclidean distance, Manhattan distance, or Cosine similarity. Because there is no training time involved, this can be a good option when time is limited and is relatively easy to setup. K-Nearest Neighbors may not be a good idea if you have very high dimensional or feature-rich data. This is because of something called the Curse of Dimensionality; as we go into higher and higher dimensional space distance as we know it becomes more skewed and two things that are very different may seem to be \"close\" to each other in high dimensional space. For more on the Curse of Dimensionality and how higher dimensionality can affect your models read \\href{https://towardsdatascience.com/curse-of-dimensionality-2092410f3d27}{this article}.\n\n\\newpage\n\\subsection{Deep Neural Networks (DNNs)} \nDNNs are commonly used within problem spaces with a lot of available data. Once the data is preprocessed, we provide the data as input to the DNN. The data undergoes a series of non-linear transformations. This is what separates deep neural networks from one-layer, shallow, linear neural networks. These transformations are followed by a linear transformation which produces the output or result. \n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=3.5in]{nn.jpg}\n    \\caption{Simple DNN with two hidden non-linear layers. \\href{https://www.digitaltrends.com/cool-tech/what-is-an-artificial-neural-network/}{Link}}\n\\end{figure}\n\n\\href{https://playground.tensorflow.org}{Tutorial here.}\n\n\\newpage\n\\subsection{Convolutional Neural Networks (CNNs)} \n\nConvolutional Neural Networks are mostly used with image data to perform image classification and other image related tasks.\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=4.5in]{cnn.jpeg}\n    \\caption{Unrolling an RNN. Each input is fed through to produce an output at the given timestep. We also pass context forward through time. \\href{https://towardsdatascience.com/a-comprehensive-guide-to-convolutional-neural-networks-the-eli5-way-3bd2b1164a53}{Link}}\n\\end{figure}\n\n\\subsection{Recurrent Neural Networks (RNNs)} \n\nRecurrent Neural Networks strength lies in finding patterns in sequential data, whether that be sentences, audio, or protein sequences. They have special cells which allow them to keep important information seen from past samples or from future samples. There are many different variations of RNNs, here is a link to some RNN tutorials written in PyTorch \\href{https://github.com/yunjey/pytorch-tutorial/tree/master/tutorials/02-intermediate}{here}.\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=4.5in]{rnn.png}\n    \\caption{Unrolling an RNN. Each input is fed through to produce an output at the given timestep. We also pass context forward through time. \\href{https://medium.com/@jianqiangma/all-about-recurrent-neural-networks-9e5ae2936f6e}{Link}}\n\\end{figure}\n\n\\newpage\n\\section{Further Topics}\n\n\\subsection{Reinforcement Learning}\n\\href{https://deepmind.com/research/publications/playing-atari-deep-reinforcement-learning/}{Paper}\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=4.5in]{rl.jpg}\n    \\caption{In recent years deep learning has been introduced to reinforcement learning algorithms to improve performance. The agent chooses an action and receives updated information of the environment in order to choose a new action. Deep approaches have been used to augment the agent. \\href{https://www.kdnuggets.com/2018/03/5-things-reinforcement-learning.html}{Link}}\n\\end{figure}\n\n\\subsection{Generative Adversarial Networks}\n\\href{https://arxiv.org/abs/1406.2661}{Paper}\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=4.5in]{gans.png}\n    \\caption{We have been able to achieve incredible results using this model to generate things. This is done by training a generator and discriminator model. The generator tries to generate a realistic sample from the training set and the discriminator does its best to tell if the sample given to it is from the training set or a generated \"fake\" sample. By doing this we are able to train a generator that can create extremely good \"fakes\" or generated samples. Things it may try to \"fake\" and generate are images, audio, or video. \\href{https://skymind.ai/wiki/generative-adversarial-network-gan}{Link}}\n\\end{figure}\n\n\\newpage\n\\subsection{Few Shot Learning}\n\\href{https://openreview.net/forum?id=HkxLXnAcFQ}{Paper}\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=4.5in]{fewshot.png}\n    \\caption{Few shot learning works to train a model on very few examples of given classes. Many training episodes are used to understand the distinctions between the classes provided.  \\href{https://medium.com/sap-machine-learning-research/deep-few-shot-learning-a1caa289f18}{Link}}\n\\end{figure}\n\\newpage\n\n\\end{document}\n", "meta": {"hexsha": "83a5d2fbbed259ff41c0d5d5d0364c9534d48e0e", "size": 21602, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "workshop_tex/main.tex", "max_stars_repo_name": "joshmyersdean/MachineLearning-Workshop", "max_stars_repo_head_hexsha": "8a94e1aa9b6bc51aeb5b3cf3dee5906b44acdb75", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-03T19:11:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-03T19:11:32.000Z", "max_issues_repo_path": "workshop_tex/main.tex", "max_issues_repo_name": "joshmyersdean/MachineLearning-Workshop", "max_issues_repo_head_hexsha": "8a94e1aa9b6bc51aeb5b3cf3dee5906b44acdb75", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "workshop_tex/main.tex", "max_forks_repo_name": "joshmyersdean/MachineLearning-Workshop", "max_forks_repo_head_hexsha": "8a94e1aa9b6bc51aeb5b3cf3dee5906b44acdb75", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-26T18:56:57.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-26T18:56:57.000Z", "avg_line_length": 85.3833992095, "max_line_length": 1554, "alphanum_fraction": 0.7900194426, "num_tokens": 4885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.3491914155349654}}
{"text": "\\documentclass[10pt]{article}\n\\usepackage[T1]{fontenc}\n\n% Document Details\n\\newcommand{\\CLASS}{AMATH 563}\n\\newcommand{\\assigmentnum}{Nueral Networks}\n\n\\usepackage[margin = 1in, left=0.75in,right=0.75in]{geometry}\n\\input{../../import/title.tex} % Title Styling\n\\input{../../import/styling.tex} % General Styling\n\\input{../../import/code.tex} % Code Display Setup\n\\input{../../import/math.tex} % Math shortcuts\n\n\\usepackage{dblfloatfix}    % To enable figures at the bottom of page\n\n% Problem\n\\newenvironment{problem}[1]{\\vspace{2em}{\\large\\sffamily\\textbf{#1}}\\itshape\\par}{}\n\n\\usepackage{nameref}\n\\newcommand{\\vln}{\\rotatebox{90}{--}}\n\n\\begin{document}\n\n\\twocolumn[{%\n\\begin{@twocolumnfalse}\n\\maketitle\n\\vspace{2em}\n\\begin{abstract}\nWe outline a how neural networks might be applied to the study of systems governed by possibly unknown PDEs. In particular we show that future state predictions are possible for some systems, even if they are chaotic. We address how high dimensional data can be rank reduced first in order to allow for training on a smaller neural net. While some results are encouraging, we find that it is quite difficult to correctly tune the neural networks in a limited time.\n\\end{abstract}\n\n\\vspace{4em}\n%\\tableofcontents\n%\\vspace{3em}\n\\pagebreak\\end{@twocolumnfalse}\n}]\n\n\\section{Introduction and Overview}\nWith recent increases in computation power and data storage capabilities our ability effectively process data computationally has increases substantially. Machine learning uses statistical techniques to gather information about a dataset and use it to make predictions or understand trends. One class of machine learning methods, neural networks, is particularly effective given large datasets. If neural nets can be effectively used to predict solutions of PDEs then we can step away from trying to guess at the PDEs which actually describe systems and move towards generating trajectories using these neural nets.\n\n\\section{Theoretical Background}\n\\subsection{Neural Network Basics}\nSuppose we have sets \\( \\hat{X}_0 \\) and \\( \\hat{X}_N \\) with elements of size \\( m \\) and \\( n \\) respectively. Let \\( \\hat{f}:\\hat{X}_0 \\to \\hat{X}_N \\) be an injection. The goal of a neural network is to be able to accurately compute this injection to make predictions about elements of \\( \\hat{X}_0 \\) for which we do not know the actual value of \\( \\hat{f} \\).\n\nA feed forward neural network is a function of the form,\n\\begin{align}\n    X_N = f_N(b_{N-1}+\\cdots f_2(b_1+ W_1f_1(b_0 + W_0x_0))) \\label{NN}\n\\end{align}\nwhere the the ``activation'' functions \\( f_j:\\RR\\to\\RR \\) are applied componentwise.\n\nEach ``layer'' is of the form,\n\\begin{align*}\n    x_{j+1} = f_{j+1}j(W_j x_{j} + b_j), && j=0,1,\\ldots, N-1\n\\end{align*}\n\nNote that \\( W_j \\) can be of any shape compatible with \\( x_j \\) with the constraint that \\( W_{N-1} \\) must also give something of the dimension of \\( x_N \\).\n\nThe goal is to set the parameters \\( W_j \\) and \\( b_j \\) so that the neural network is equal to \\( \\hat{f} \\). However, it is clear that unless we know the output of \\( f \\) on all of \\( \\hat{X}_0 \\) this will not be possible even if our neural net has the same form as \\( \\hat{f} \\). Since in general we would like to be able to make predictions about unknown data we will have to settle for the neural network being an approximation to \\( \\hat{f} \\).\n\nMore specifically, let \\( X_0\\subset \\hat{X}_0 \\) and suppose the value of \\( \\hat{f}(x) \\) is known for all \\( x\\in X_0 \\). For convenience we will write \\( X_0 \\) as a matrix of size \\( n\\times t \\). Define \\( X_N\\subset \\hat{X}_N \\) as the \\( m\\times t \\) matrix found by applying \\( \\hat{f} \\) to the columns of \\( X_0 \\). We will use the data from \\( X_0 \\) to train the neural net to (hopefully) give us a good approximation for \\( \\hat{f} \\). Since the neural network can take any element of \\( \\hat{X}_0 \\) as input, we hope that it can be used for predictions about the value of \\( \\hat{f} \\) on these elements.\n\n\n\\subsection{Loss functions}\nGiven a neural network we would like to train it to be able to make predictions. In order to do this we need some way of saying what a good prediction is. In general this is done by defining a loss function which is small when the network gives good predictions, and large when it gives bad predictions.\n\nMore specifically, let \\( X_0\\in\\RR^{n} \\) and \\( X_N\\in\\RR^{m} \\) be the input data and target data respectively. Let \\( f:\\RR^{n}\\times\\RR^{Z}\\to\\RR^{m} \\) be a neural network as defined above, where \\( Z \\) is the number of free parameters. The residual error of the network for a fixed set of parameters \\( \\beta\\in\\RR^{Z} \\) is \\( Y - f(X,\\beta) \\).\n\nIdeally the residual error is zero. By picking some metric with which to measure the residual error, we have a minimization problem. In this paper we often chose to minimize the mean square error, which amounts to solving,\n\\begin{align}\n    \\min_{\\beta} \\sum_{x_0\\in X_0} \\norm{\\hat{f}(x_0)-f(x_0,\\beta)}_2^2 \\label{mse}\n\\end{align}\n\n\\subsection{Optimizers}\nIn order to minimize expressions such as (\\ref{mse}) an optimization algorithm must be applied. Since the input and output lie in such high dimensional spaces, the loss function often has many local minimum or saddle points. As such, traditional methods such as gradient decent may not work very well. Instead there are many popular gradient based algorithms which introduce some stochasticity in order to avoid ``getting stuck''. Since our neural network can be expressed as the composition of fairly straightforward functions, the gradient with respect to entries of \\( \\beta \\) can be easily computed using the chain rule (done by something called back-propagation).\n\n\\subsection{SVD and Data reduction}\nWhen training a neural network the size of the input and output are determine by the data given. This means the network may have to be very large the the beginning and end nodes. On approach to reduce the size of the network is to project the input and target data into lower dimensional subspaces and then train on the projections. This is equivalent to the first and last hidden layers of the neural net being of smaller size and with fixed weights. If the weights are not fixed, the net will determine the ``best'' projection. However, since the SVD already computes the optimal low rank approximation in the 2-norm or Frobenius norm, it may be beneficial to set these weights so that the net does not have to learn them.\n\nSuppose our input data \\( X \\) is in \\( \\RR^{N} \\) and we have \\( T \\) samples. We then have a \\( N\\times T \\) data matrix. We would like to find a subspace of \\( \\RR^{N} \\) of lower dimension where our data can be approximated well. Our data has a rank \\( k \\) reduced SVD,\n\\begin{align}\n    X \\approx U\\Sigma V^* \\label{SVD_eq}\n\\end{align}\nwhere \\( U  \\) is \\( N\\times k \\), \\( \\Sigma \\) is \\( k\\times k \\), and \\( V^* \\) is \\( k\\times T \\). We interpret this in the following way: the columns of \\( U \\) are the dominant modes in our data, and the rows of \\( \\Sigma V^* \\) tell us how these modes vary in time. We can therefore use the columns of \\( \\Sigma V^* \\), which are of height \\( k \\), as our approximation to the input data.\n\nIn general the input and target data will not be of the same size or, for time series data, of the same dynamics. However, in the case that they are the rank reduction used on the input and output can be computed simultaneously saving a large computation. While it will no longer be the optimal reduction for each of these, it will be near optimal. In this paper we are generally building steppers, and so the input and target are of the same system at different times. We therefore compute the low dimensional spaces by taking the SVD of the full data set, and then split it into the input and target data sets.\n\n\\section{Algorithm Implementation and Development}\n\n\\subsection{Neural Network Framework}\nWe use the python libraries Keras and Tensorflow for most of our neural nets. In addition the neural network package for MATLAB is occasionally used.\n\nIn general, the setup and labeling of the data was the primary focus of this project. It is straightforward to change the net structure and tune other hyperparameters once this has been done. However, doing so is time consuming. If any of the nets work at all this should be taken as very encouraging since they were generally chosen at random without much justification.\n\n\n\\subsection{Data Generation}\nTo generate data for our systems we generally use an ODE stepper to solve a system of ODEs corresponding to the discrimination of a PDE. The target data is taken to be the training data one step forward in time (with respect to some fixed time mesh). Multiple initial conditions are generated in a variety of ways depending on\n\n\n\\subsection{Kuramoto-Sivashinsky Equation}\nWe are provided with a stepper to produce solutions to the Kuramoto-Sivashinsky equation (\\ref{KS_eqn}) with periodic boundary conditions on a given mesh (with \\( N \\) spatial points and \\( T \\) time points).\n\\begin{align}\n    \\pp{u}{t} = -u \\pp{u}{x} - \\pp[2]{u}{x} - \\pp[4]{u}{x} \\label{KS_eqn}\n\\end{align}\n\nIn order to train our network to step forward in time we must generate a batch of trajectories stemming from some class of initial conditions. To do this we start with a zero initial condition and then randomly set a fixed (generally two or three) number Fourier modes to have weights with real and imaginary parts uniformly distributed on \\( [-N/2,N/2] \\). This produces periodic initial conditions which lead to fairly nice behavior. We then generate a solutions with these initial conditions and save them.\n\nThe data is then imported to Python and formatted into the training and target data sets by appropriate slicing. A neural net defined in Keras is trained to predict the value of \\( u(t+\\Delta t) \\) given the value of \\( u(t) \\).\n\n\\begin{figure}[t]\\centering\n\\begin{subfigure}{.45\\textwidth}\\centering\n    \\includegraphics[width=\\textwidth]{img/svd_mode_1.pdf}\n    \\caption{1st left singular vector reshaped}\n    \\label{1mode}\n\\end{subfigure}\\hfill\n\\begin{subfigure}{.45\\textwidth}\\centering\n    \\includegraphics[width=\\textwidth]{img/svd_mode_100.pdf}\n    \\caption{100th singular vector reshaped}\n    \\label{100mode}\n\\end{subfigure}\n\\caption{SVD modes for \\( u \\) (left) and \\( v \\) (right) }\n\\label{SVD_modes}\n\\end{figure}\n\n\\begin{figure}[t]\\centering\n\\begin{subfigure}{.45\\textwidth}\\centering\n    \\includegraphics[width=\\textwidth]{img/svd_coeff_1.pdf}\n    \\caption{1st right singular vector varying in time}\n    \\label{1coeff}\n\\end{subfigure}\n\\begin{subfigure}{.45\\textwidth}\\centering\n    \\includegraphics[width=\\textwidth]{img/svd_coeff_100.pdf}\n    \\caption{100th right singular vector varying in time}\n    \\label{100coeff}\n\\end{subfigure}\n\\caption{coefficients of SVD modes vs dataset}\n\\label{SVD_coeff}\n\\end{figure}\n\n\\subsection{ \\( \\boldsymbol\\lambda \\)-\\( \\boldsymbol\\omega \\) Reaction-Diffusion Equation}\nWe can apply similar methods to a PDE in two dimensions.\nWith,\n\\begin{align*}\n    {\\bf u} = \\left[\\begin{array}{c}u \\\\ v\\end{array}\\right], &&\n    {\\bf D} = \\left[\\begin{array}{cc}d_1 \\\\ & d_2 \\end{array}\\right]\n\\end{align*}\nthe Kuramoto-Sivashinsky equation is defined as,\n\\begin{align}\n    \\pp{{\\bf u}}{t} =\n    \\left[\\begin{array}{cc}\n        \\lambda(s) & -\\omega(s) \\\\\n        \\omega(s) & \\lambda(s)\n    \\end{array}\\right]\n    {\\bf u}\n    + {\\bf D} \\nabla^2 {\\bf u} \\label{RD_eqn}\n\\end{align}\nwhere,\n\\begin{align*}\n    s^2 = u^2 + v^2, &&\n    \\lambda = 1-s^2, &&\n    \\omega = -\\beta s^2\n\\end{align*}\n\nAgain we are given a stepper which produces trajectories on a fixed mesh. Like with the KS equation, we generate initial conditions by picking some Fourier modes to be nonzero and use these to generate trajectories which we load into Python.\n\nSince the data is much larger than before, training a neural net (we tried) is very slow. While the size of data used in industry is often massive, they also have massive computers and lots of time. We don't, so to deal with the large data set we reduce the rank of our data and train on the projections. Since the training and target data come from the same space we compute the SVD the entire dataset before splitting it into training and target data. This allows us to find a single subspace for both the training and target data, saving on computing and saving two subspaces (which would turn out to be almost identical since the vast majority of the data in each of these sets would be the same).\n\n\\begin{figure*}[h]\\centering\n\\begin{subfigure}{.45\\textwidth}\\centering\n    \\includegraphics[width=\\textwidth]{img/sample_KS_trajectory.pdf}\n    \\caption{trajectory generated by {\\tt solve\\_ivp}}\n    \\label{sample_KS_trajectory}\n\\end{subfigure}\\hfill\n\\begin{subfigure}{.45\\textwidth}\\centering\n    \\includegraphics[width=\\textwidth]{img/predicted_KS_trajectory.pdf}\n    \\caption{trajectory generated by neural net}\n    \\label{predicted_KS_trajectory}\n\\end{subfigure}\n\\caption{``actual'' and neural net predicted trajectories for Kuramoto-Sivashinsky equation (\\ref{KS_eqn})}\n\\label{KS_trajectory}\n\\end{figure*}\n\nFigure~\\ref{1mode} shows the dominant left singular vector and Figure~\\ref{1coeff} shows how the first right singular vector varies in time. The ``spikes'' down clearly are related to the initial conditions of the data. However, after each spike there is an oscillation in this mode. Moreover, the mode itself has quite a bit of structure, which it seems to have inherited from the way we generated initial conditions. It is not clear whether this structure would die out if we ran the simulations for longer time. Regardless, since the structure is present in our data set we can use this to train a neural net on the rank-reduced data.\n\nWe take the rank \\( k \\) SVD (\\ref{SVD_eq}) (determined by a parameter flag) and then train the network on the weights of the basis of the subspace spanned by the first \\( k \\) columns of \\( U \\).\n\nTo test our prediction we take a trajectory not used for training, project it to the column span of \\( U \\), iteratively apply the network, and then embed back to the original space.\n\n\n\\subsection{Lorenz Equation}\nThe Lorenz equation (\\ref{lorenz_eq}) is a system of ODEs which have chaotic solutions for some parameters. It was demonstrated in \\cite{lecture_notes} that for a fixed \\( \\Delta t \\) a simple neural network can be trained to predict the position at a time \\( t+\\Delta t \\) given the position at time \\( t \\) accurately enough that the trajectory determined by iteratively applying the trained neural net matches the trajectory of a given ODE solver almost exactly. Given that the system is chaotic for these values it is somewhat surprising that the neural net manages to follow the same trajectory by only predicting one step at a time. Training data was generating using Scipy's {\\tt solve\\_ivp} with a tolerance of \\( 10^{-10} \\) and evaluating the solution along a mesh of uniformly spaced times.\n\n\\begin{align}\n    \\pp{}{t} \\left[\\begin{array}{c}x\\\\y\\\\z\\end{array}\\right]\n    =\n    \\left[\\begin{array}{c}\n        \\sigma(y-x) \\\\\n        x (\\rho-z)-y \\\\\n        x y-\\beta z\n    \\end{array}\\right] \\label{lorenz_eq}\n\\end{align}\n\nWe explore the Lorenz equation in two further ways, namely trying to predict trajectories for varying values of the parameter \\( \\rho \\) and trying to predict when the solution will transition from one lobe to another.\n\nThe first task is straightforward. In particular, a neural net is trained on data where the input corresponds to the current position as well as the value of \\( \\rho \\), and the output is the position after a time of \\( \\Delta t \\). More specifically, we fix \\( \\sigma = 10 \\), \\( \\beta = 8/3 \\), and train on data with \\( \\rho = 10,28,40 \\). We then try to use this net to predict trajectories for \\( \\rho = 17 \\) and \\( \\rho = 35 \\).\n\nThe second tasks requires some interpretation. We decided to train a network to determine how long until a lobe switch. To train such a network requires that we know how long it will be until the solution switches lobes. To do this we first classify what it means to be at a given lobe. This is done by separating the data with plane as shown in Figure~\\ref{separating_hyperplane}. Let \\( c \\) be a normal vector for this hyperplane. Then the sign of \\( c^Tx \\) will determine which side of the plane a given point is on.\n\nWe pick \\( c \\) roughly in the direction of the vector connecting the two centers in the \\( x \\)-\\( y \\) plane. While there are probably better ways to do this, it seems like the projection to this plane provides a straightforward way to separate points circle different lobes.\n\nTherefore, given a trajectory \\( X \\), each point in the trajectory can be classified as ``left'' or ``right''. Once this is done, we know that transitions across the plane occur when the trajectory switches from ``left'' to ``right'' or from ``right'' to ``left''. We compute these transition points by taking the difference of consecutive points in \\( \\operatorname{sign}(c^TX) \\). If the difference is nonzero then the trajectory has switched lobes. Once we have these transition points it is relatively straightforward label each point in the trajectory with far each point is from the next crossover.\n\nAs a minor note, some of the data from the end of the each trajectory is discarded because it is not possible to tell when the next transition will occur without stepping out the solution further. We then train a neural network to try and predict the time until a crossover.\n\\begin{figure}[tb!]\\centering\n\\begin{subfigure}{.45\\textwidth}\\centering\n    \\includegraphics[width=\\textwidth]{img/uv_t180.pdf}\n    \\caption{original data}\n    \\label{time_image}\n\\end{subfigure}\\hfill\n\\begin{subfigure}{.45\\textwidth}\\centering\n    \\includegraphics[width=\\textwidth]{img/svd_t180.pdf}\n    \\caption{SVD (rank 100)}\n    \\label{SVD_time_image}\n\\end{subfigure}\n\\caption{snapshot of \\( u \\) (left) and \\( v \\) (right) at time \\( t=180 \\)}\n\\label{RD_SVD}\n\\end{figure}\n\n\\begin{figure}[b!]\\centering\n\\begin{subfigure}{.45\\textwidth}\\centering\n    \\includegraphics[width=\\textwidth]{img/prediction_t15.pdf}\n    \\caption{actual trajectory}\n    \\label{sample_RD_trajectory}\n\\end{subfigure}\\hfill\n\\begin{subfigure}{.45\\textwidth}\\centering\n    \\includegraphics[width=\\textwidth]{img/svd_prediction_t15.pdf}\n    \\caption{predicted trajectory}\n    \\label{predicted_RD_trajectory}\n\\end{subfigure}\n\\caption{``actual'' and neural net predicted trajectories for Reaction Diffusion Equation (\\ref{RD_eqn}) at \\( t=15 \\)}\n\\label{RD_trajectory}\n\\end{figure}\n\n\\begin{figure}[t!]\\centering\n\\begin{subfigure}{.45\\textwidth}\\centering\n\\includegraphics[width=\\textwidth]{img/NN_lrz17_trajectory.pdf}\n\\caption{\\( \\rho = 17 \\)}\n\\end{subfigure}\\hfill\n\\begin{subfigure}{.45\\textwidth}\\centering\n\\includegraphics[width=\\textwidth]{img/NN_lrz35_trajectory.pdf} \\hfill\n\\caption{\\( \\rho = 35 \\)}\n\\end{subfigure}\n\\caption{Actual trajectory (solid) vs predicted trajectory (dotted) for variious values of \\( \\rho \\)}\n\\label{xyz_trajectory}\n\\end{figure}\n\n\n\n\n\\section{Computational Results}\n\n\\subsection{Kuramoto-Sivashinsky Equation}\n\nFigure~\\ref{sample_KS_trajectory} shows a sample trajectory generated by our ODE stepper (not part of traninig data). Figure~\\ref{predicted_KS_trajectory} shows the prediction of the neural net on the same trajectory. However, as time progresses the neural net predicted solution does not really change, while the reaction diffusion equation does continue to evolve.\n\n\n\\subsection{ \\( \\boldsymbol\\lambda \\)-\\( \\boldsymbol\\omega \\) Reaction-Diffusion Equation}\nFigure~\\ref{time_image} shows a snaptshot of a trajectory at time \\( t=180 \\). Figure~\\ref{SVD_time_image} shows the same snapshot after it has been projected into a 100 dimensional subspace determined by the SVD. While a plot of the singular values shows no clear cutoff in the rank, visually it seems that the data is fairly well represented by the first 100 modes. We proceed to train a neural network on the rank reduced data.\n\n\\begin{figure}[bt!]\\centering\n\\begin{subfigure}{.45\\textwidth}\\centering\n\\includegraphics[width=\\textwidth]{img/separating_hyerplane.pdf}\n\\caption{Projection of sample trajectory onto the \\( x \\)-\\( y \\) plane along with image of plane \\( y + 5x +0z = 0 \\).}\n\\label{separating_hyperplane}\n\\end{subfigure}\\hfill\n\\begin{subfigure}{.45\\textwidth}\\centering\n\\includegraphics[width=\\textwidth]{img/jump_predictor.pdf}\n\\caption{Actual time to jump (solid) vs. predicted time to jump (dotted) for sample trajectory .}\n\\label{jump_predictor}\n\\end{subfigure}\n\\caption{}\n\\end{figure}\n\n\\subsection{Lorenz Equation}\nSample predictions for \\( \\rho = 17 \\) and \\( \\rho = 35 \\) produced by the trained net are shown in Figure~\\ref{xyz_trajectory}. Note that we do not cross validate in the normal sense, since that would be testing how well our net can predict one step in the future. In fact, the cross validation would show a very high accuracy since we are able to predict the long term behavior relatively well despite only training n the current position.\n\nFigure~\\ref{jump_predictor} shows the results of applying the trained net to every point in a trajectory. This plot makes it clear that we are actually able to fairly effectively determine when a jump will occur given only the current position. Note here that the horizontal axis labeling is just the index of the point in the trajectory and has no impact on the neural net's prediction as it is applied independently to each point.\n\n\\pagebreak\n\\section{Summary and Conclusions}\nIt is clear that the trajectories of the Kuramoto-Sivashinsky and Reaction Difussion equations were not effectively predicted. On the other hand, solutions to the Lorenz equation, even for values of \\( \\rho \\) which the neural net had never seen, were quite successful. Finally, we were able to train a neural net to predict how long it would take a trajectory to switch lobes.\n\nDue to time constraints only simple nets were used and all hyperparameter training was done by guessing. We instead chose to focus on producing the training data in a scalable way so that in the future it would be a trivial task to generate data at large mesh sizes. With the current state of our codebase, testing new neural nets is as easy as changing a few lines in Keras. Given more time we would have liked to set up convolutional neural nets to see if the local structure of the data would be enough to determine the global behavior. In general we probably did not use enough data, and the nets we used are probably too small to be able to get very good results. However, what we did find is somewhat encouraging and given more time would be worth pursuing.\n\n\n\\bibliographystyle{plain}\n\\bibliography{hw2}\n\n\\onecolumn\n\\section{Appendix A}\n\\label{AppendixA}\nAll functions are included in the code in Appendix B as they are specific to the task performed in each of the files.\n\n%\\pagebreak\n\\section{Appendix B}\n\\lstinputlisting[]{PDECODES/KS_data_gen.m}\n\\lstinputlisting[]{python/hw2_ks.py}\n\\lstinputlisting[]{PDECODES/RD_data_gen.m}\n\\lstinputlisting[]{python/hw2_rd.py}\n\\lstinputlisting[]{python/hw2_lrz.py}\n\\lstinputlisting[]{python/lrz_classifier.py}\n\n\n\\end{document}\n", "meta": {"hexsha": "4f640311ae3686100c2f9479b48d624d5c72a19e", "size": 23246, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "amath563/hw2/hw2.tex", "max_stars_repo_name": "interesting-courses/UW_coursework", "max_stars_repo_head_hexsha": "987e336e70482622c5d03428b5532349483f87f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-08-19T01:59:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-31T12:32:59.000Z", "max_issues_repo_path": "amath563/hw2/hw2.tex", "max_issues_repo_name": "interesting-courses/UW_coursework", "max_issues_repo_head_hexsha": "987e336e70482622c5d03428b5532349483f87f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "amath563/hw2/hw2.tex", "max_forks_repo_name": "interesting-courses/UW_coursework", "max_forks_repo_head_hexsha": "987e336e70482622c5d03428b5532349483f87f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-03-31T22:23:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-29T22:13:01.000Z", "avg_line_length": 74.0318471338, "max_line_length": 801, "alphanum_fraction": 0.7511829992, "num_tokens": 5922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.34919140240913726}}
{"text": "\\documentclass[]{article}\n\\usepackage{proceed2e}\n\\usepackage{amssymb,amsmath,amsthm}\n\\usepackage{graphicx}\n\\usepackage{preamble}\n\\usepackage{natbib}\n\\usepackage{hyperref}\n\\usepackage{color}\n\\definecolor{mydarkblue}{rgb}{0,0.08,0.45}\n\\hypersetup{ %\n    pdftitle={},\n    pdfauthor={},\n    pdfsubject={},\n    pdfkeywords={},\n    pdfborder=0 0 0,\n    pdfpagemode=UseNone,\n    colorlinks=true,\n    linkcolor=mydarkblue,\n    citecolor=mydarkblue,\n    filecolor=mydarkblue,\n    urlcolor=mydarkblue,\n    pdfview=FitH}\n\n\n\n\\title{Bayesian Quadrature minimizes Maximum Mean Discrepancy}\n\n\\author{ {\\bf Ferenc Husz\\'{a}r} \\\\\nDepartment of Engineering\\\\\nCambridge University\\\\ \n\\texttt{fh277@cam.ac.uk}\n\\And \n{\\bf David Duvenaud } \\\\ %\\thanks{Both authors contributed equally.} \\\\ \nDepartment of Engineering\\\\ \nCambridge University \\\\\n\\texttt{dkd23@cam.ac.uk}\n} \n\n\\begin{document} \n \n\\maketitle \n \n%\\begin{abstract} \n%Maximum Mean Discrepancy is equivalent to the posterior variance of an integrated Gaussian process.\n%\\end{abstract} \n\n \n\\section{INTRODUCTION}\nA common problem in statistical machine learning is to compute expectations of functions over probability distributions of the form:\n\\begin{equation}\n\tZ_{f,p} = \\int f(x) p(x) dx \\label{eqn:integral}\n\\end{equation}\nExamples include computing marginal distributions, making predictions marginalizing over parameters, or computing the Bayes risk in a decision problem. %In this paper we assume that the distribution $p(x)$ is known in analytic form, and $f(x)$ can be evaluated at arbitrary locations.\n\n%Monte Carlo methods produce random samples from the distribution $p$ and then approximate the integral by taking the empirical mean $\\hat{Z} = \\frac{1}{N}\\sum_{n=1}^{N}f_{x_n}$ of the function evaluated at those points. This non-deterministic estimate converges at a rate $\\mathcal{O}(\\frac{1}{\\sqrt{N}})$. When exact sampling from $p$ is impossible or impractical, Markov chain Monte Carlo (MCMC) methods are often used. MCMC methods can be applied to almost any problem but convergence of the estimate depends on several factors and is hard to estimate \\citep{CowlesCarlin96}. The focus of this paper is on quasi-Monte Carlo methods that -- instead of sampling randomly -- produce a set of pseudo-samples in a deterministic fashion. These methods operate by directly minimising some sort of discrepancy between the empirical distribution of pseudo-samples and the target distribution. Whenever these methods are applicable, they achieve convergence rates superior to the $\\mathcal{O}(\\frac{1}{\\sqrt{N}})$ rate typical of random sampling.\n\n%In this paper we highlight and explore the connections between two deterministic sampling and integration methods: Bayesian quadrature (\\bq{}) \\citep{BZHermiteQuadrature,BZMonteCarlo} (also known as Bayesian Monte Carlo) and kernel herding \\citep{chen2010super}. Bayesian quadrature estimates integral \\eqref{eqn:integral} by inferring a posterior distribution over $f$ conditioned on the observed evaluations $f_{x_n}$, and then computing the posterior expectation of $Z_{f,p}$. The points where the function should be evaluated can be found via Bayesian experimental design, providing a deterministic procedure for selecting sample locations.% We call this procedure Sequential Bayesian Quadrature (\\sbq).\n\n%Herding, proposed recently by \\cite{chen2010super}, produces pseudosamples by minimising the discrepancy of moments between the sample set and the target distribution. Similarly to traditional Monte Carlo, an estimate is formed by taking the empirical mean over samples $\\hat{Z} = \\frac{1}{N}\\sum_{n=1}^{N}f_{x_n}$. Under certain assumptions, herding has provably fast, $\\mathcal{O}(\\frac{1}{N})$ convergence rates in the parametric case, and has demonstrated strong empirical performance in a variety of tasks.\n\nIn this paper, we make two main contributions.  Firs, we show that the Maximum Mean Discrepancy (MMD) criterion (used to choose samples in kernel herding) is identical to the expected error in the estimate of the integral $Z_{f,p}$ under a Gaussian process prior for $f$.  This expected error is the criterion being minimized when choosing samples for Bayesian quadrature (BQ).  Because Bayesian quadrature assigns different weights to each of the observed function values $f(\\vx)$, we can view Bayesian quadrature as a weighted version of kernel herding.  \n We show that these weights are optimal in a minimax sense over all functions in the Hilbert space defined by our kernel.  This implies that Bayesian quadrature dominates kernel herding and other non-optimally weighted herding in rate of convergence.\n\nWe further show that the MMD, when using BQ weights, is submodular in the samples chosen, which implies that sequential BQ achieves the optimal rate of convergence for any sampling method.\n\n\\section{HERDING} \n\nHerding was introduced by \\cite{welling2009herding} as a method for generating pseudo-samples from a distribution in such a way that certain nonlinear moments of the sample set closely match those of the target distribution.  The empirical mean $\\frac{1}{N}\\sum_{n=1}^{N}f_{x_n}$ over these pseudosamples is then used to estimate integral \\eqref{eqn:integral}.\n\n\\subsection{Maximum Mean Discrepancy}\n\nFor selecting pseudosamples, herding relies on an objective based on the maximum mean discrepancy \\citep[MMD;\\ ][]{Sriperumbudur2010}: %MMD measures the divergence between two distributions, $p$ and $q$ with respect to a class of integrand functions $\\mathcal{F}$ as follows:\n%\n\\begin{align}\n\t\\mmd_{\\mathcal{F}}\\left(p,q\\right) = \\sup_{f\\in\\mathcal{F}}\\left\\vert\\int f_x p(x) dx - \\int f_x q(x) dx \\right\\vert\n\\end{align}\n%\n%Intuitively, if two distributions are close in the MMD sense, then no matter which function $f$ we choose from $\\mathcal{F}$, the difference in its integral over $p$ or $q$ should be small. A particularly interesting case is \n%\nWhen the function class $\\mathcal{F}$ is functions of unit norm from a reproducing kernel Hilbert space (RKHS) $\\He$, the MMD between two distributions can be conveniently expressed using only expectations of the associated kernel $k(x, x')$ \\citep{Sriperumbudur2010}.\n%\n%\\begin{align}\n%MMD^2_{\\He}(p,q) =& \\sup_{\\substack{f\\in\\He\\\\\\Hnorm{f}=1}}\\left\\vert\\int f_x p(x) dx - \\int f_x q(x) dx\\right\\vert^2\\\\\n%\t=& \\Hnorm{\\mu_{p} - \\mu_{q}}^2\\\\\n%\\nonumber\t=&\\iint k(x,y) p(x) p(y) dx dy\\\\\n%\\nonumber\t-2 &\\iint k(x,y) p(x) q(y) dx dy\\\\\n%\t+ &\\iint k(x,y) q(x) q(y) dx dy,\n%\\end{align}\n%\n%where in the above formula $\\mu_{p}=\\int \\phi(\\vx)p(\\vx)d\\vx\\in\\He$ denotes the \\emph{mean element} associated with the distribution $p$.\n% For characteristic kernels, such as the Gaussian kernel, the mapping between a distribution and its mean element is bijective. As a consequence $\\mmd_{\\He}(p,q)=0$ if and only if $p=q$, making it a powerful measure of divergence.\n%\nHerding uses MMD to evaluate how well the sample set $\\{\\vx_1,\\ldots,\\vx_{N}\\}$ represents the target distribution $p$, adding points greedily according to:\n%\n%\\begin{align}\n%\t\\epsilon_{herding}&\\left(\\{\\vx_1,\\ldots,\\vx_{N}\\}\\right) = \\mmd_{\\He}\\left(p,\\frac{1}{N}\\sum_{n=1}^{N}\\delta_{x_n}\\right)\\\\\n%\\nonumber\t=&\\iint k(x,y) p(x) p(y) dx dy\\\\\n%\t\t-2 &\\frac{1}{N}\\sum_{n=1}^{N}\\int k(x,x_n) p(x) dx\n%\t\t+ \\frac{1}{N^2}\\sum_{n,m=1}^{N} k(x_n,x_m)\n%\\label{eq:mmd_assumption}\n%\\end{align}\n%\n%The herding procedure greedily minimizes its objective $\\epsilon_{herding}\\left(\\{\\vx_1,\\ldots,\\vx_{N}\\}\\right)$ , adding pseudosamples $\\vx_n$ one at a time. When selecting the $n+1$-st pseudosample:\n%\n\\begin{align}\n\\vx_{n+1} &\\leftarrow \\argmin_{\\vx \\in \\mathcal{X}} \\label{eqn:herding_criterion} \\epsilon_{herding}\\left(\\{\\vx_1,\\ldots,\\vx_{n},\\vx\\}\\right)\\\\\n\t&= \\argmax_{\\vx \\in \\mathcal{X}} 2 \\expectargs{\\vx' \\sim p}{k(\\vx, \\vx')} - \\frac{1}{n+1}\\sum_{m=1}^{n} k(\\vx,\\vx_m)\\mbox{,}\\notag\n\\end{align}\n%\nassuming $k(\\vx,\\vx) = \\mbox{const}$.\nThe formula \\eqref{eqn:herding_criterion} admits an intuitive interpretation: the first term encourages sampling in areas with high mass under the target distribution $p(\\vx)$.  The second term discourages sampling at points close to existing samples. \n\n\n\n\n\\section{BAYESIAN QUADRATURE} \n\n%\\begin{figure}\n%\\centering\n%\\includegraphics[width=\\columnwidth]{figures/bq_intro4}\n%\\caption{An illustration of Bayesian Quadrature.  The function $f(x)$ is sampled at a set of input locations.  %This induces a Gaussian process posterior distribution on $f$, which is integrated in closed form against the target density, $p(\\vx)$.  Since the amount of volume under $f$ is uncertain, this gives rise to a (Gaussian) posterior distribution over $Z_{f,p}$.}\n%\\label{fig:bq_intro}\n%\\end{figure}\n\nBayesian quadrature (\\bq) puts a prior distribution on $\\vf$, then estimates integral \\eqref{eqn:integral} by inferring a posterior distribution over the function $\\vf$, conditioned on the observations $\\vf(\\vx_n)$ at some query points $\\vx_n$.  For simplicity, $\\vf$ is assigned a Gaussian process prior with kernel function $k$ and mean $0$.  This assumption is very similar to the one made by kernel herding.  The posterior distribution over $f$ then implies a distribution over $Z_{f,p}$. %See Figure \\ref{fig:bq_intro} for an illustration of Bayesian Quadrature.\n%\n%\\subsection{ BQ Estimator}\n%\n%Here we derive the \\bq{} estimate of \\eqref{eqn:integral}, after conditioning on function evaluations $\\vf(\\vx_1) \\dots \\vf(\\vx_N)$, denoted as $f(\\vX)$.  \n The mean of this distribution, $\\expectargs{}{Z}$ is the optimal Bayesian estimator for a squared loss.\n%After conditioning on $\\vf(\\vX)$, we obtain a closed-form posterior over $\\vf$.\n%\n%\\begin{align}\n%p(\\vf(\\vx\\st)|\\vf(\\vX)) = \\N{\\vf(\\vx\\st)}{\\mf(\\vx\\st)}{\\cov(\\vx\\st,\\vx\\st')}\n%\\end{align} \n%where\n%\\begin{align}\n%\\mf(\\vx\\st) = & k(\\vx\\st, \\vX) K^{-1} \\vf(\\vX) \\\\\n%\\cov(\\vx\\st, \\vx\\st') = & k(\\vx\\st,\\vx\\st) - k(\\vx\\st, \\vX) K^{-1} k(\\vX, \\vx\\st)\n%\\end{align} \n%\n%and $K = k(\\vX, \\vX)$. \n%\nConveniently, the \\gp{} posterior allows us to compute the expectation of \\eqref{eqn:integral} in closed form: \n%\n%\\begin{align}\n%Z & = \\int f(\\vx)p(\\vx)d\\vx\n%\\end{align} \n%so we integrate over functions to get:\n\\begin{align}\n\\expectargs{\\gp}{Z} & = \\vz^T K^{-1} \\vf(\\vX)\n\\label{eq:marg_mean_symbolic}\n\\end{align} \nwhere\n\\begin{align}\nz_n & = \\int\\!\\! k(\\vx, \\vx_n) p(\\vx) d\\vx = \\expectargs{\\vx' \\sim p}{k(\\vx_n, \\vx')}.\n\\end{align}\n%\nAs in kernel herding, the desired expectation of $Z_{f,p}$ is simply a linear combination of observed function values $\\vf(\\vx)$:\n%\n\\begin{align}\n\\expectargs{\\gp}{Z} & = \\vz^T K^{-1} \\vf(\\vX) \\\\\n    & = \\sum_n w_{\\bq}^{(n)} f(x_n)  \\quad \\textrm{where} \\quad w_{\\bq}^{(n)} = \\sum_m \\vz_j K^{-1}_{nm}\n\\end{align}  \n%\n%\\begin{align}  \n%w_{\\bq}^{(n)} & = \\sum_m \\vz_j K^{-1}_{nm}\n%\\label{eq:bq_weights}\n%\\end{align}\n%\nThus, we can view the BQ estimate as a weighted version of the herding estimate.\n\n\n\\subsection{Optimal sampling for BQ}\n\nThe posterior variance $\\varianceargs{}{Z_{f,p}|f_{x_1}, \\dots, f_{x_N}}$ quantifies our uncertainty in the estimate of the integral. When selecting locations to evaluate the function $f$, minimising the posterior variance is a sensible strategy. Below, we give a closed form formula for the posterior variance of $Z_{f,p}$, conditioned on the observations $f_{x_1} \\dots f_{x_N}$, which we will denote by $\\epsilon^2_{\\bq{}}$.\n\\begin{align}\n\\epsilon^{2}_{\\bq{}} = \\varianceargs{}{Z_{f,p}|f_{x_1}, \\dots, f_{x_N}} \n% \\nonumber & = \\expectargs{f \\sim \\gp, p\\sim p(x)}{ \\left( f(\\vx) - \\mf(\\vx) \\right)\\left( f(\\vx') - \\mf(\\vx') \\right)} \\\\ \n%\\nonumber & = \\int \\Bigg( \\!\\! \\left( \\int f(\\vx) p(\\vx) d\\vx - \\int \\mf(\\vx') p(\\vx') d\\vx' \\right) \\\\ \n%\\nonumber & \\quad \\times \\left( \\int f(\\vx) p(\\vx) d\\vx - \\int \\mf(\\vx') p(\\vx') d\\vx' \\right) \\!\\! \\Bigg) p(f) df \\\\ \n%\\nonumber & = \\int\\!\\!\\! \\int\\!\\! \\int\\!\\! \\left[ f(\\vx) - \\mf(\\vx) \\right] \\left[ f((\\vx') - \\mf(\\vx') \\right] p(f) df \\\\\n%\\nonumber & \\qquad \\times   p(\\vx) p(\\vx') d\\vx d\\vx' \\\\\n%\\nonumber & = \\int\\!\\! \\!\\int\\!\\! \\Cov \\left[ f((\\vx), f((\\vx') \\right] p(\\vx) p(\\vx') d\\vx d\\vx' \\\\\n%\\nonumber & = \\int\\!\\!\\! \\int\\!\\! \\left[ k(\\vx, \\vx') - k(\\vx, \\vX) K^{-1} k(\\vX, \\vx') \\right] \\\\\n%\\nonumber          & \\qquad \\times p(\\vx) p(\\vx') d\\vx d\\vx' \\\\ \n%\\nonumber & = \\int\\!\\!\\! \\int\\!\\! k(\\vx, \\vx') p(\\vx) p(\\vx') d\\vx d\\vx' \\\\\n%\\nonumber & \\quad - \\left[ \\int\\!\\! k(\\vx, \\vX) p(\\vx) d\\vx \\right] K^{-1} \\left[ \\int\\!\\! k(\\vX, \\vx') p(\\vx') d\\vx' \\right] \\\\\n  = \\expectargs{\\vx, \\vx' \\sim p}{k(\\vx, \\vx')} - \\vz K^{-1} \\vz\\mbox{,}\n\\label{eq:marg_var_symbolic}\n\\end{align}\n%where $\\vz_n = \\expectargs{\\vx' \\sim p}{k(\\vx_n, \\vx')}$ as before. \nPerhaps surprisingly, the posterior variance of $Z_{f,p}$ does not depend on the observed function values, only on the location $x_n$ of samples.  This allows the optimal samples to be computed ahead of time, before observing any values of $f$ at all \\citep{minka2000dqr}.\n%\\begin{align}\n%\\epsilon^{2}_{\\bq{}}(\\vx_1,\\ldots,\\vx_N) = \\expectargs{\\vx, \\vx' \\sim p}{k(\\vx, \\vx')} - \\vz K^{-1} \\vz\n%\\end{align}\n%We can contrast the \\bq{} objective $\\epsilon^{2}_{\\bq{}}$ to the objective being minimized in herding, $\\epsilon^{2}_{herding}$ of equation \\eqref{eq:mmd_assumption}. \n%Just like $\\epsilon^{2}_{herding}$, $\\epsilon^{2}_{\\bq{}}$ expresses a trade-off between accuracy and diversity of samples. On the one hand, as samples get close to high density regions under $p$, the values in $\\vz$ increase, which results in decreasing variance. On the other hand, as samples get closer to each other, eigenvalues of $K$ increase, resulting in an increase in variance. \n\n\\section{RELATING $\\varianceargs{}{Z_{f,p}}$ TO $\\mmd$}\n\nThe similarity in the behaviour of $\\epsilon^{2}_{herding}$ and $\\epsilon^{2}_{\\bq{}}$ is not a coincidence, the two quantities are closely related to each other, and to \\mmd.\n\n\\begin{prop} The expected variance in the Bayesian quadrature $\\epsilon^{2}_{\\bq{}}$  is the maximum mean discrepancy between the target distribution $p$ and $q_{\\bq{}}(x) = \\sum_{n=1}^{N}w^{(n)}_{\\bq{}}\\delta_{x_n}(x)$\n\\end{prop}\n%\n%\\begin{proof} Proof omitted for space reasons.\n%The proof involves invoking the representer theorem, using bilinearity of scalar products and the fact that if $f$ is a standard Gaussian process then $\\forall g\\in\\He: \\left\\langle f,g\\right\\rangle \\sim \\mathcal{N}(0,\\Hnorm{g})$:\n%\\begin{align}\n%&\\varianceargs{}{Z_{f,p}\\vert f_{x_1}, \\dots, f_{x_N}}=\\\\\n%\t&= \\mathbb{E}_{f\\sim GP} \\left( \\int f(x) p(x) dx - \\sum_{n=1}^{N}w^{(n)}_{\\bq{}} f(x_n)\\right)^2\\\\\n%\t&= \\mathbb{E}_{f\\sim GP} \\left( \\int \\left\\langle f, \\phi (x)\\right\\rangle p(x) dx - \\sum_{n=1}^{N}w^{(n)}_{\\bq{}} \\left\\langle f, \\phi (x_n)\\right\\rangle\\right)^2\\\\\n%\t&= \\mathbb{E}_{f\\sim GP} \\left\\langle f ,  \\int\\phi(x) dx - \\sum_{n=1}^{N}w^{(n)}_{\\bq{}}\\phi(x_n)\\right\\rangle^2\\\\\n%\t&= \\Hnorm{\\mu_p - \\mu_{q_{\\bq{}}}}^2\\\\\n%\t&= \\mmd^2(p,q_{\\bq{}})\n%\\end{align}\n%\\end{proof}\n\nWe know that the the posterior mean $\\expectargs{\\gp}{Z_{f,p}\\vert f_1,\\ldots,f_N}$ is a Bayes estimator and has therefore the minimal expected squared error amongst all estimators. This allows us to further rewrite $\\epsilon^{2}_{\\bq{}}$ into the following minimax forms:\n%\n\\begin{align}\n\\epsilon^{2}_{\\bq{}} %&= \\sup_{\\substack{f\\in\\He\\\\\\Hnorm{f}{\\He}=1}} \\left| \\int f_x p(x) dx - \\sum_{n=1}^{N}w^{(n)}_{\\bq{}} f_{x_n}\\right|^2\\\\\n%\t&= \\inf_{\\hat{Z}:\\mathcal{X}^N\\mapsto\\mathbb{R}} \\sup_{\\substack{f\\in\\He\\\\\\Hnorm{f}{\\He}=1}} \\left| Z - \\hat{Z}\\left(f_{x_1},\\ldots,f_{x_N}\\right)\\right|^2\\\\\n\t&= \\inf_{\\bm{w}\\in\\mathbb{R}^N} \\sup_{\\substack{f\\in\\He\\\\\\Hnorm{f}{\\He}=1}} \\left| \\int f_x p(x) dx - \\sum_{n=1}^{N}w_n \tf_{x_n}\\right|^2\n\\end{align}\n%\n%Looking at $\\epsilon^{2}_{\\bq{}}$  this way, we may discover the deep similarity to the criterion $\\epsilon^2_{herding}$ that kernel herding minimises. \nOptimal sampling for Bayesian quadrature minimises the same objective as kernel herding, but with the uniform $\\frac{1}{N}$ weights replaced by the optimal weights. As a corollary\n%\n\\begin{align}\n\\epsilon^{2}_{\\bq{}}(x_1,\\ldots,x_N)  \\leq \\epsilon^{2}_{KH} (x_1,\\ldots,x_N)\n\\end{align}\n%\nIt is interesting that $\\epsilon^{2}_{\\bq{}}$ has both a Bayesian interpretation as posterior variance under a Gaussian process prior, and a frequentist interpretation as a minimax bound on estimation error with respect to an RKHS.  Figure \\ref{fig:bound_curve} demonstrates this closed-form, quickly shrinking bound on the error of the Bayesian estimator.  This equivalence also implies that the MMD is proportional to the expected error when estimating integrals of functions drawn from a GP prior.\n\\begin{figure}\n\\includegraphics[width=\\columnwidth]{figures/bound_curve_rkhs}\n\\caption{The empirical error rate in estimating $Z_{f,p}$,  for the \\sbq{} estimator, on 10 random functions drawn from the RKHS corresponding to the kernel used.  Also shown is the upper bound on the error rate implied by the $\\mmd$.}\n\\label{fig:bound_curve}\n\\end{figure}\n%\n%Figure \\ref{fig:bound_curve} demonstrates the MMD bound on the error of the \\sbq{} estimator, on random functions drawn from the RKHS corresponding to the kernel used.  The empirical error always falls below the bound given by the MMD.\n\n\n\\subsection{Convergence Rates}\n\nIn finite dimensional Hilbert spaces, the herding algorithm has been shown to reduce $\\mmd$ at a rate $\\mathcal{O}(\\frac{1}{N})$, which compares favourably with the $\\mathcal{O}(\\frac{1}{\\sqrt{N}})$ rate obtained by non-deterministic Monte Carlo samplers.% However, as pointed out by \\cite{bach2012equivalence}, this fast convergence is not guaranteed in infinite dimensional Hilbert spaces, such as the RKHS corresponding to the Gaussian kernel.\nwe have shown that the greedy Bayesian estimator obtains the optimal rate for any sampling method.  We have empirical results demonstrating a rate of convergence much faster than $\\mathcal{O}(\\frac{1}{N})$, but this rate is unkown to the authors, and we wish to pose this question to the kernel community.\n\n\\pagebreak\n\n\\bibliographystyle{icml2012}\n\\bibliography{herding}\n\n\\end{document} \n", "meta": {"hexsha": "a038e1748fab8a563d01e4dd2f63567be329161a", "size": 18006, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/icml-workshop-submission.tex", "max_stars_repo_name": "duvenaud/herding-paper", "max_stars_repo_head_hexsha": "cecf8f1af028efd95c6262fb257f4ed9978a57e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2015-04-16T14:19:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T22:45:05.000Z", "max_issues_repo_path": "paper/icml-workshop-submission.tex", "max_issues_repo_name": "duvenaud/herding-paper", "max_issues_repo_head_hexsha": "cecf8f1af028efd95c6262fb257f4ed9978a57e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/icml-workshop-submission.tex", "max_forks_repo_name": "duvenaud/herding-paper", "max_forks_repo_head_hexsha": "cecf8f1af028efd95c6262fb257f4ed9978a57e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-11-23T13:45:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-25T04:31:47.000Z", "avg_line_length": 70.6117647059, "max_line_length": 1040, "alphanum_fraction": 0.7088192825, "num_tokens": 5645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.34915238679154603}}
{"text": "%==============================================================================\n\\chapter{In silico quantitative mapping of force-pCa curves to whole heart contraction and relaxation}\\label{cha:chapter8}\n%==============================================================================\n%\n%\n%\n\\begin{remark}{Outline}\n    In this chapter, we focus on the assessment of the steady-state F-pCa relationship (this is traditionally used to assess the myofilament $\\Ca$ sensitivity) and its quantitative mapping to the LV contractile function. We start by investigating the F-pCa curve using the cell contraction sub-model of our full personalised SHAM rat heart contraction model (Section~\\ref{sec:cellcontr}). Next, using a combination of simulators and emulators (Section~\\ref{subsec:quantlink}), we show that changes in key features of the F-pCa curve cannot be uniquely described by changes in the sarcomere properties (Sections~\\ref{sec:changespCa50result1}--\\ref{sec:changespCa50result2}). At the same time, we show that changes in the LV function (e.g. ejection fraction, isovolumetric relaxation time, peak pressure) cannot be uniquely described by changes in the sarcomere properties (Section~\\ref{sec:changesLVfunctionresult}). By coupling these two pieces of information, we demonstrate that the mapping from the F-pCa curve to the LV function and the corresponding inverse mapping are non-unique (Section~\\ref{sec:ch8nonuniquemappings}). We then include a discussion of results and address specific limitations (Section~\\ref{sec:ch8discussion}), and we conclude with a brief summary (Section~\\ref{sec:ch8summary}).\n\\end{remark}\n\n\n%\n%\n%\n\\section{Motivation}\\label{sec:ch8motivation}\nOne potential assessment for sarcomere modulators is their impact on the F-pCa~\\cite{Walker:2010}, which is a technique that is widely used in many HF diseases including rare/genetic diseases such as dilated and hypertrophic cardiomyopathies~\\cite{Groen:2020,Bai:2013,Michael:2016,Kirschner:2005,Harris:2002}, as well as for HF with reduced and preserved ejection fraction~\\cite{Nagy:2015,Kampourakis:2018,Kieu:2019,Awinda:2021,Mamidi:2018,Sparrow:2020}. The impact on the F-pCa curve is often examined in terms of observed shifts in the curve half-maximal activation ($\\pCaf$), which is used as an index of $\\Ca$ sensitivity. Leftward shifts in the $\\pCaf$ are expected to improve contractility, whereas rightward shifts to decrease contractility. Sometimes there is an assumption that changes in $\\Ca$ sensitivity are a surrogate for changes in whole heart function and that these changes are monotonic in that, for instance, an increase in myofilament $\\Ca$ sensitivity (i.e. a leftward shift) would improve the whole heart cardiac output. In this case study, whose related manuscript is currently in submission~\\cite{Longobardi:2022}, we discuss the limitations of such an assumption and demonstrate why the dynamic whole heart behaviour cannot be predicted or assessed with a shift in the F-pCa curve alone.\n\n\\vspace{0.2cm}\nWe use a mathematical model of active tension generation at the sarcomere level in LV rat myocytes to elucidate the relationship between sarcomere properties and the steady-state F-pCa curve. We next use our previously developed multi-scale model of SHAM rat heart, which integrates the cell tension model within a $3$D biventricular rat heart contraction model (Section~\\ref{sec:ch7rat_heart_contraction_model}) and provides a quantitative link between sarcomere properties and whole heart contractile function to investigate the mapping from F-pCa curves to the LV function. In particular, using our framework, we are able to quantitatively link changes in the F-pCa curve to/from changes in the LV function for the first time to the best of our knowledge. Previously, shifts in the F-pCa curve were linked to changes in cellular tension~\\cite{Chung:2016} but not to the whole-organ dynamic contractile behaviour and without investigating the inverse mapping. We use our modelling framework to show that observations made at the sarcomere level (e.g. a leftward shift in the F-pCa curve) do not uniquely map to desired effects at the whole-organ level (e.g. an increase in EF or improved relaxation). We also show that the opposite holds: given a change in LV function, there exist many ways this could have been achieved through sarcomeric modulation, and thus the same change in LV function can correspond to different shifts in the F-pCa curve. The implications of these phenomena on using F-pCa curves to interpret whole heart dynamics are discussed in Section~\\ref{sec:ch8discussion}.\n\n\n%\n%\n%\n\\section{Methods}\\label{sec:ch8methods}\n\n\n%\n%\n%\n\\subsection{Cellular contraction model}\\label{sec:cellcontr}\nWe employed the Land et al.~\\cite{Land:2012} myocyte contraction model (Section~\\ref{sec:ch2contractionmodel}) to simulate active tension generation at the sarcomere level and isometric steady-state F-pCa relationship in the rat heart. Parameters were all set to the personalised SHAM rat model values (Table~\\ref{tab:bestfitparametersvalues}) when applicable, or to the Land et al.~\\cite{Land:2012} model baseline values when otherwise.\n\n\\vspace{0.2cm}\nWe recall that an experimentally derived F-pCa curve can be described by a Hill-type relationship between the force ($F$) and the negative logarithm of the $\\Ca$ concentration ($\\pCa$)~\\cite{Walker:2010}:\n%\n\\begin{equation}\n    \\frac{F}{F_0} = \\frac{1}{1+10^{h(\\pCaf-\\pCa)}}\n\\end{equation}\n\n\\noindent\nwhere $F_{0}$ is the maximal reference force and $\\pCaf$ and $h$ are, respectively, the negative logarithm of the half-maximal effective $\\Ca$ concentration and the Hill coefficient of this relationship. It immediately follows that F-pCa curves are uniquely determined by the $\\pCaf$ and $h$ values. We have also seen that the steady-state force solution of the Land et al.~\\cite{Land:2012} model can be derived analytically, where both the $\\pCaf$ and $h$ features are expressed in terms of model parameters. In particular, we recall that the $\\pCaf$ was given as:\n%\n\\begin{align}\n    & \\pCaf(\\mathbf{p}) =  -\\log\\left[\\Caif\\left(\\frac{\\koff}{\\kon}\\frac{\\trpnf}{1-\\trpnf}\\right)^{1/\\ntrpn}\\right]\\,,\\quad\\text{with} \\label{eq:pCa50}\\\\\n    & \\mathbf{p} := (\\Caif, \\kon, \\koff, \\trpnf, \\ntrpn) \\label{eq:pCa50params}\n\\end{align}\n\n\\vspace{0.2cm}\\noindent\nIn the next section, we shall make use of equations~\\eqref{eq:pCa50}--\\eqref{eq:pCa50params} to investigate on F-pCa curve shifts. \n\n\n%\n%\n%\n\\subsection{Non-unique mapping of changes in $\\pCaf$ to changes in sarcomere properties}\\label{sec:changespCa50}\nA given change ($\\Delta$) in the $\\pCaf$ feature value of the F-pCa curve can be written as:\n%\n\\begin{equation}\\label{eq:delta}\n    \\Delta = \\pCaf^{\\text{new}} - \\pCaf\n\\end{equation}\n\n\\vspace{0.2cm}\\noindent\nwhere $\\pCaf^{\\text{new}}$ is the feature value characterising the newly observed F-pCa curve. We tested whether a shift of $\\Delta$ units in the $\\pCaf$ could be the result of unique changes in sarcomere properties. Testing for non-unique changes was carried out analytically and numerically (as visualised in Figure~\\ref{fig:2perclwrwshift}) in the case where the change was driven by perturbations in one model parameter (Section~\\ref{sec:changespCa50result1}), and numerically (as visualised in Figure~\\ref{fig:pca50isolines}) in the case where this was driven by perturbations in two model parameters (Section~\\ref{sec:changespCa50result2}).\n\n\\vspace{0.2cm}\nIn the one-parameter case, it sufficed to prove that for each parameter $p_i,\\,i=1,\\,\\dots,\\,5$ of equation~\\eqref{eq:pCa50params} there exists a scaling coefficient $\\alpha_i\\in\\mathbb{R}$ such that\n%\n\\begin{equation}\n    \\mathbf{p}^{\\text{new}} := (p_1,\\,\\dots,\\,\\p_{i-1},\\,\\alpha_i\\times\\p_i,\\,p_{i+1},\\,\\dots,\\,p_5)\n\\end{equation}\n\n\\noindent\nis such that\n%\n\\begin{equation}\n    \\pCaf^{\\text{new}} = \\pCaf(\\mathbf{p}^{\\text{new}})\n\\end{equation}\n\n\\vspace{0.2cm}\\noindent\nWe computed this scaling coefficient for each parameter $\\p_i$ by solving for $\\alpha_i$ equation~\\eqref{eq:delta} for a given $\\Delta$.\n\n\\vspace{0.2cm}\nIn the two-parameter case, we proceeded as follows. We allowed $2$ parameters to take equally-spaced values within a $\\pm\\SI{50}{\\percent}$ perturbation around their baseline values (Table~\\ref{tab:bestfitparametersvalues}). We then generated a $2$D uniform grid from all the combinations of $2$ parameter values and used the Land et al.~\\cite{Land:2012} cell contraction model to calculate the $\\pCaf$ value at each parameter point of the grid. By plotting the resulting $\\pCaf$ values across the grid as a heat map, we could discern regions in the $2$D parameter space that share the same $\\pCaf$ value (isolines). The same process was repeated for pairs of parameters coming from vector $\\mathbf{p}$ (equation~\\eqref{eq:pCa50params}), which was shown to regulate the $\\pCaf$ feature of the F-pCa curve (equation~\\eqref{eq:pCa50}).\n\n\n%\n%\n%\n\\subsection{The relationship between sarcomere properties and LV function}\\label{subsec:quantlink}\nTo quantitatively link sarcomere properties to the LV function, we employed the personalised model of $3$D biventricular healthy (SHAM) rat heart contraction derived in Chapter~\\ref{cha:chapter4} and extended in Chapter~\\ref{cha:chapter7}. This model integrates the Land et al.~\\cite{Land:2012} cell contraction model in the context of whole-organ simulations.\n\n\\vspace{0.2cm}\nWe have seen (Section~\\ref{sec:ch7rat_heart_contraction_model}) that this model can be represented as a multi-scale function (simulator) that maps a $16$D vector of input parameters $\\mathbf{x}$ to a scalar quantity of interest $y_j$ (e.g. $y_1=\\textrm{EDV}$, $y_2=\\textrm{ESV}$, etc.):\n%\n\\begin{align}\\label{eq:fsimul}\n    f_{\\textrm{simul}}\\colon\\mathbb{R}^{16} &\\to\\mathbb{R}\\times\\mathbb{R}\\times\\dots \\\\\n    \\mathbf{x} &\\mapsto (y_1,\\,y_2,\\dots) \\nonumber\n\\end{align}\n\n\\vspace{0.2cm}\\noindent\nAt the same time, we have replaced (Section~\\ref{sec:ch7training_dataset_emulators_global_sensitivity_analysis}) the simulator with a fast-evaluating surrogate model (emulator), based on Gaussian process emulation.\n\n\\vspace{0.2cm}\nWe used the simulator to investigate the dependence of LV volume features, namely EDV, ESV, SV, and EF, on model parameters. Specifically, we were interested in the dependence of the features on the $\\Caif$, $\\koff$, $\\ntrpn$ and $\\trpnf$ parameters as these directly modulated the $\\pCaf$ feature of the F-pCa curve (equation~\\eqref{eq:pCa50}). For each parameter, we performed the following operations. First, the simulator was run at $128$ input points $\\mathbf{x}_i,\\,i=1,\\dots,128$, which had all their $16$ components fixed to baseline values (Table~\\ref{tab:bestfitparametersvalues}) but the component corresponding to the examined parameter, which instead was set to $128$ equally-spaced values between $-\\SI{50}{\\percent}$ and $\\SI{50}{\\percent}$ of perturbation values from baseline. The LV volume features were then extracted from the simulated $128$ LV volume transients so that we could plot the variation of each feature as a function of the parameter variations around its baseline value.\n\n\\vspace{0.2cm}\nWe then used the emulator to perform a GPE-based GSA. We calculated the Sobol' first-order, second-order and total effects (Section~\\ref{sec:ch3globalsensitivityanalysis}) as a measure of model outputs' sensitivity to model inputs. We evaluated the impact of $\\Caif$, $\\koff$, $\\ntrpn$, $\\trpnf$ parameters into affecting the total variance of EDV, ESV, SV, EF features. Parameters whose Sobol' indices' distributions' expectation was below the threshold $0.01$ were determined to have negligible effects.\n\n\n%\n%\n%\n\\subsection{Non-unique mapping of changes in LV function to changes in sarcomere properties}\\label{sec:changesLVfunction}\nLeft ventricular EF can be continuously monitored noninvasively as an index of LV systolic function in patients enrolled for clinical trials investigating HF treating drugs. However, it is important to discern whether detected changes in the EF value directly result from a specific cellular modulation caused by the administered drug or not. From a modelling perspective and in the context of sarcomere modulators, we can test whether changes observed in the LV function at the whole-organ level, as described by the EF feature, can be uniquely explained in terms of sarcomere properties' changes.\n\n\\vspace{0.2cm}\nWe therefore proceeded as in Section~\\ref{sec:changespCa50} by generating a $2$D uniform grid of parameter values for each considered pair of parameters modulating the F-pCa curve (equation~\\eqref{eq:pCa50}). We then used the emulator to predict the EF value at each parameter point of the grid. By plotting the resulting EF values across the grid as a heat map, we could again discern regions in the $2$D parameter space that share the same EF value (isolines).\n\n\n%\n%\n%\n\\subsection{Non-unique mapping of F-pCa curve to LV function and of LV function to F-pCa curve}\nIn order to test if the mapping from the F-pCa curve to LV function is not unique, we considered all the parameter points of the $2$D grids generated in Section~\\ref{sec:changespCa50} that produced the same shift in the reference $\\pCaf$ feature value. As mentioned previously, these points all belong to isolines of the local $2$D parameter space. We then used the emulator to map the points to the corresponding organ-level EF value.\n\n\\vspace{0.2cm}\nWe also tested if the inverse mapping from the LV function to the F-pCa curve is not unique. For this purpose, we considered all the parameter points of the $2$D grids generated in Section~\\ref{sec:changesLVfunction} that produced the same shift in the reference EF feature value. We then used the cellular contraction sub-model of the full simulator to map the points to the corresponding cell-level $\\pCaf$ value.\n\n\n%\n%\n%\n\\section{Results}\n\n\n%\n%\n%\n\\subsection{Non-monotonic relationship between sarcomere parameters and LV function}\nThe variations of EDV, ESV, SV and EF features as a function of the $4$ considered F-pCa curve-modulating parameters (equation~\\eqref{eq:pCa50}) are non-linear and non-monotonic, as shown in Figure~\\ref{fig:EFvsparamsnonmonotonic}. An example of full simulator outputs comprising LV volume and pressure transients and PV loops is provided in Figure~\\ref{fig:EFvskoff} for the EF-vs-$\\koff$ case.\n\n\\begin{figure}[h!]\n    \\myfloatalign\n    \\includegraphics[width=\\textwidth]{figures/chapter08/Fig1.pdf}\n    \\caption{The full $3$D biventricular rat heart contraction model is run at a fixed parameter set with only one parameter taking equally-spaced values in the $\\pm\\SI{50}{\\percent}$ range of perturbation from its baseline value (vertical red dashed lines). The converging mechanics simulations' output PV loops are analysed to extract the corresponding EDV, ESV, SV and EF features' values (open blue dots), given as percentages from their baseline values (horizontal red dashed lines). The process is repeated separately for each parameter regulating the $\\pCaf$ feature of the F-pCa curve. A linear regression (LR) model with second-order degree polynomials is fitted to the data (blue lines) to facilitate the visualisation of non-linear and non-monotonic relationships between the features and each of the parameters considered.}\n    \\label{fig:EFvsparamsnonmonotonic}\n\\end{figure}\n\n\\begin{figure}[h!]\n    \\myfloatalign\n    \\includegraphics[width=\\textwidth]{figures/chapter08/Fig2.pdf}\n    \\caption{The full $3$D biventricular rat heart contraction model is run at a fixed parameter set with only one parameter varying around its baseline value. The resulting LV volume and pressure transients and corresponding PV loops are plotted for some of the parameter values (full lines in blue variants) and compared to the reference parameter set mechanics solution (dashed black line). Example showing $\\koff$ parameter variation in the range obtained as a $\\pm\\SI{40}{\\percent}$ perturbation of its baseline value.}\n    \\label{fig:EFvskoff}\n\\end{figure}\n\n\\vspace{0.2cm}\nThe obtained GSA Sobol' sensitivity indices are displayed as donut charts in Figure~\\ref{fig:gsarestr}. We can see that the reference thin filament $\\Ca$ sensitivity ($\\Caif$) is the most important parameter in explaining the total variance of EDV, ESV, SV and EF features. The second most important parameter is the degree of cooperativity of $\\Ca$ binding to TnC ($\\ntrpn$), followed by the fraction of bound $\\Ca$-TnC complexes for half-maximal cross-bridges activation ($\\trpnf$) and the unbinding rate of $\\Ca$ from TnC ($\\koff$).\n\n\\begin{figure}[h!]\n    \\myfloatalign\n    \\includegraphics[width=\\textwidth]{figures/chapter08/Fig3.pdf}\n    \\caption{The impact of $\\pCaf$-modulating, sarcomere parameters on EDV, ESV, SV and EF organ-scale LV feature. The contribution of each parameter is represented by the sum of its first- and second-order effects. For each LV feature, higher-order interactions (up to the fourth order) are represented by the sum of all total effects minus the sum of all first- and second-order effects.}\n    \\label{fig:gsarestr}\n\\end{figure}\n\n\n%\n%\n%\n\\subsection{$\\pCaf$ changes are non-uniquely explained by sarcomere alterations: the one-parameter case}\\label{sec:changespCa50result1}\nWe show that an observed change in $\\pCaf$ can be caused by multiple different changes in sarcomere proprieties represented by model parameters. For each parameter $p_i,\\,i=1,\\,\\dots,\\,5$ of equation~\\eqref{eq:pCa50params}, we report in Table~\\ref{tab:alphavalues} the corresponding scaling coefficient $\\alpha_i,\\,i=1,\\,\\dots,\\,5$ that would yield a shift of exactly $\\Delta$ units in the $\\pCaf$ value. This proves that an observed change in the F-pCa cannot be uniquely explained by a change in a specific sarcomere property. An example of $\\pm\\SI{2}{\\percent}$ shift from a reference $\\pCaf$ value is displayed in Figure~\\ref{fig:2perclwrwshift}.\n\n\\begin{table}[h!]\n    \\myfloatalign\n    \\begin{tabularx}{\\textwidth}{XX}\n        \\toprule\n        \\tableheadline{Parameter} & \\tableheadline{Scaling coefficient $\\alpha$} \\\\\n        \\midrule\n        & \\\\\n        $\\Caif$ & $10^{\\Delta}$ \\\\ & \\\\\n        $\\kon$ & $10^{-\\Delta\\cdot\\ntrpn}$ \\\\ & \\\\\n        $\\koff$ & $10^{\\Delta\\cdot\\ntrpn}$ \\\\ & \\\\\n        $\\trpnf$ & $\\dfrac{10^{\\Delta\\cdot\\ntrpn}}{\\trpnf(10^{\\Delta\\cdot\\ntrpn}-1)+1}$ \\\\ & \\\\\n        $\\ntrpn$ & $\\dfrac{\\log\\left(\\frac{\\koff}{\\kon}\\frac{\\trpnf}{1-\\trpnf}\\right)}{\\Delta\\cdot\\ntrpn+\\log\\left(\\frac{\\koff}{\\kon}\\frac{\\trpnf}{1-\\trpnf}\\right)}$ \\\\ & \\\\\n        \\bottomrule\n    \\end{tabularx}\n    \\caption{The mapping of sarcomere properties to F-pCa variations is non-unique. By scaling each parameter $p_i$ by the corresponding $\\alpha_i$ coefficient, the cellular contraction model simulates a $\\pCaf$ value which is shifted by exactly $\\Delta$ units from the reference value.}\n    \\label{tab:alphavalues}\n\\end{table}\n\n\\begin{figure}[h!]\n    \\myfloatalign\n    \\includegraphics[width=0.8\\textwidth]{figures/chapter08/Fig4.pdf}\n    \\caption{Different parameters can be individually perturbed to achieve the very same shift in the force-calcium relationship. Example showing $\\SI{2}{\\percent}$ leftwards (upper plot) and rightwards (bottom plot) shifts of the reference $\\pCaf$ value. As $\\trpnf$ and $\\ntrpn$ also regulate the F-pCa curve's Hill coefficient (equation~\\eqref{eq:h}), notice that for these two parameters the shift in the $\\pCaf$ value is also affecting the curve's slope.}\n    \\label{fig:2perclwrwshift}\n\\end{figure}\n\n\n%\n%\n%\n\\subsection{$\\pCaf$ changes are non-uniquely explained by sarcomere alterations: the two-parameter case}\\label{sec:changespCa50result2}\n$\\pCaf$ evaluation on $2$-parameter grids highlighted the presence of isolines, whose parameter points induce the same $\\pCaf$ feature value (Figure~\\ref{fig:pca50isolines}A). This means that moving between any two points on two isolines will result in the same shift in $\\pCaf$, demonstrating also in the two-parameter case the non-uniqueness of changes in the half-activation of the F-pCa curve and a change in sarcomere properties.\n\n\n%\n%\n%\n\\subsubsection{Non-unique mapping of F-pCa curve to LV function}\\label{sec:fpcatolvnonuniquemapping}\nParameter points inducing the same shifts in the $\\pCaf$ feature value (isolines of Figure~\\ref{fig:pca50isolines}A) are quantitatively linked to different EF feature values (Figure~\\ref{fig:pca50isolines}B), showing that the mapping from F-pCa curve to LV function is not unique.\n\n\\begin{figure}[h!]\n    \\myfloatalign\n    \\includegraphics[width=\\textwidth]{figures/chapter08/Fig5.pdf}\n    \\caption{For each pair of parameters regulating the $\\pCaf$ feature of the F-pCa curve, a $2$D uniform grid is constructed using a $\\pm\\SI{50}{\\percent}$ perturbation around the reference parameter set values (black dots). (A) The cell contraction model is then used to calculate the $\\pCaf$ feature value at every parameter point of the grid, and each grid is plotted as a heat map with values given as percentages from the control $\\pCaf$ value. Contour plots are finally added to highlight the presence of isolines, whose many different parameter sets induce the same shift ($-\\SI{2}{\\percent}$ dotted, $\\SI{0}{\\percent}$ full, $+\\SI{2}{\\percent}$ dashed black lines) in the control $\\pCaf$ value. (B) Parameter points from the obtained isolines are mapped by the emulator into EF feature values. These values (given as percentages of the control EF value) are represented by different colour intensities used to colour each parameter point in the isolines, showing that parameters that share the same $\\pCaf$ values are linked to different EF values.}\n    \\label{fig:pca50isolines}\n\\end{figure}\n\n\n%\n%\n%\n\\subsection{LV function changes are non-uniquely explained by sarcomere alterations}\\label{sec:changesLVfunctionresult}\nEF evaluation on $2$-parameter grids highlighted the presence of isolines, where all parameter combinations along these lines result in the same predicted EF (Figure~\\ref{fig:EFisolines}A). This means that moving between any two points on each isoline will result in the same EF, demonstrating the non-uniqueness of the LV function and sarcomere properties.\n\n\n%\n%\n%\n\\subsubsection{Non-unique mapping of LV function to F-pCa curve}\\label{sec:lvtofpcanonuniquemapping}\nParameter points that give rise to the same predicted EF value (isolines of Figure~\\ref{fig:EFisolines}A) are quantitatively linked to different $\\pCaf$ values (Figure~\\ref{fig:EFisolines}B), showing that the mapping from LV function to the F-pCa curve is not unique.\n\n\\begin{figure}[h!]\n    \\myfloatalign\n    \\includegraphics[width=\\textwidth]{figures/chapter08/Fig6.pdf}\n    \\caption{For each pair of parameters regulating the $\\pCaf$ feature of the F-pCa curve, a $2$D uniform grid is constructed using a $\\pm\\SI{50}{\\percent}$ perturbation around the reference parameter set values (black dots). (A) A trained emulator is then used to predict the $\\textrm{EF}$ feature value at every parameter point of the grid, and each grid is plotted as a heat map with values given as percentages from the control $\\textrm{EF}$ value. Contour plots are finally added to highlight the presence of isolines (full black lines), whose many different parameter sets induce the same $\\SI{0}{\\percent}$ shift in the control $\\textrm{EF}$ value. (B) Parameter points from the obtained isolines are mapped by the cell contraction model into $\\pCaf$ feature values. These values (given as percentages of the control $\\pCaf$ value) are represented by different colour intensities used to colour each parameter point in the isolines, showing that parameters that share the same $\\textrm{EF}$ values are linked to different $\\pCaf$ values.}\n    \\label{fig:EFisolines}\n\\end{figure}\n\n\n%\n%\n%\n\\subsection{Non-unique mapping from/to F-pCa curve to/from LV function}\\label{sec:ch8nonuniquemappings}\nIn Sections~\\ref{sec:changespCa50result1}--\\ref{sec:changespCa50result2}, we proved that changes in the $\\pCaf$ value are not uniquely caused by changes in sarcomere properties. In Section~\\ref{sec:fpcatolvnonuniquemapping}, we also showed that changes in the EF value are not uniquely caused by changes in the $\\pCaf$ value. Because of these two findings, we can state that observed changes in the F-pCa curve cannot be uniquely mapped to changes in the LV function.\n\n\\vspace{0.2cm}\nAt the same time, in Section~\\ref{sec:changesLVfunctionresult} we proved that changes in the EF feature value are not uniquely caused by changes in sarcomere properties. In Section~\\ref{sec:lvtofpcanonuniquemapping}, we also showed that changes in the $\\pCaf$ feature value are not uniquely caused by changes in the $\\textrm{EF}$ value. Because of these two other findings, we can state that observed changes in the LV function cannot be uniquely mapped to changes in the F-pCa curve.\n\n\n%\n%\n%\n\\section{Discussion}\\label{sec:ch8discussion}\nIn this study, we have made use of mathematical models to characterise the relationship between sarcomere properties and the LV contractile function in the healthy rat heart. We have highlighted the presence of complex nonlinearities; in particular, we have demonstrated that the relationship between myofilaments' features (e.g. $\\Caif$) and PV loop characteristics (e.g. EF) is non-monotonic. As these sarcomere properties also define the steady-state F-pCa relationship in the cardiac muscle, we extended this result in terms of shifts in the F-pCa curve that are often examined when experimentally assessing the effect of sarcomere-targeting pharmacological compounds. Therefore, we have provided both analytical and simulation study evidence that alterations in the F-pCa curve can cause very different changes in whole heart function. At the same time, we have shown that observed changes in the LV function cannot be attributed to a unique modification in sarcomere properties. Although in the previous sections we have characterised the LV function using EF, the obtained results generally hold for many other clinically relevant indexes of LV systolic and diastolic function, e.g. IVRT and PeakP, as visualised in Figures~\\ref{fig:IVRTisolines}--\\ref{fig:PeakPisolines}. To design new treatment strategies, solely looking at the induced shift in the $\\pCaf$ feature value of the F-pCa curve on its own is therefore not enough to predict or to understand predictions of how this will be translated into whole-organ function changes.\n\n\\begin{figure}[ht!]\n    \\myfloatalign\n    \\includegraphics[width=\\textwidth]{figures/chapter08/Fig6_IVRT.pdf}\n    \\caption{The same IVRT value (A) can be linked to different $\\pCaf$ values (B) (i.e. to differently shifted F-pCa curves).}\n    \\label{fig:IVRTisolines}\n\\end{figure}\n\n\\begin{figure}[ht!]\n    \\myfloatalign\n    \\includegraphics[width=\\textwidth]{figures/chapter08/Fig6_PeakP.pdf}\n    \\caption{The same PeakP value (A) can be linked to different $\\pCaf$ values (B) (i.e. to differently shifted F-pCa curves).}\n    \\label{fig:PeakPisolines}\n\\end{figure}\n\n\\vspace{0.2cm}\nAlso, when studying myofilament $\\Ca$ sensitivity using F-pCa curves, simply considering the $\\pCaf$ value as a stand-alone measurement is not sufficient for translation into dynamic contraction and relaxation. This concept was previously shown for single-cell dynamics by Chung et al.~\\cite{Chung:2016} who highlighted the importance of biophysical measures of $\\koff$ and $\\kon$ to help predict tension dynamics at the cellular level. However, in this work, we expand this concept further to the whole heart level by analysing LV features and exploring the inverse mapping from LV features to F-pCa curves, highlighting the non-uniqueness of both forward and inverse mapping between F-pCa and LV features. We emphasise that, for instance, an increase in $\\Ca$ sensitivity, i.e. a leftward shift in the F-pCa curve, will have two effects. First, it will increase residual tension, decreasing EDV; second, it will increase end-systolic tension, decreasing ESV. The balance of these two effects will impact the change in SV and EF for a given change in $\\Ca$ sensitivity. This impact of changes in $\\pCaf$ depends on the starting F-pCa curve, the $\\Ca$ transient, cardiac material properties and boundary conditions. Determining these multi-scale relationships from experimental preparations remains challenging.\n\n\\vspace{0.2cm}\nThe performed GSA interpreted the variability of EDV, ESV, SV and EF in terms of the uncertainty in F-pCa curve-modulating sarcomere parameters, and it emphasised the importance of the $\\Ca$ sensitivity in affecting these PV loop characteristics. Deeper insight can be gained if we look at higher-order interactions' effects. Although these are present for all the four LV features considered, they are remarkably high only for the SV and EF features, explaining more than half of the total variance for SV and almost half of the total variance for EF. We can notice that for the EDV and ESV features, higher-order interactions' effects are instead small, and dominating effects are mostly of the first-order type. Conversely, for the SV and EF features where higher order interactions' effects are high, dominating lower-order effects are mostly of the second-order type. All these considerations can be summarised by stating that although it is possible to interpret changes in terms of the individual contribution of parameters for the EDV and ESV features, this is not the case for SV and EF features. In this sense, it is more the combined effect of the whole sarcomere to determine the LV function rather than single myofilament components.\n\n\\vspace{0.2cm}\nIndications from the GSA coupled with the information of F-pCa curve vs LV function non-monotonicity shed new light on the problem of interpreting pharmacological interventions' effects on the F-pCa curve in terms of the desired effects on whole-heart function. This concept is illustrated via the schematic in Figure~\\ref{fig:schematic}, which highlights existing feedback mechanisms that regulate contraction in the heart. Modulation of the $\\Ca$ transient can directly affect the active tension which is generated within the sarcomere, and alteration of the sarcomere generated force will eventually affect the PV loop. As the force-volume relationships at the end-diastolic and end-systolic pressures are fixed, sarcomere interventions that aim at shifting the F-pCa might result in no change in LV contractile function. For this reason, treatment strategies should aim at altering both the end-systolic and end-diastolic force-volume relationships or altering one while maintaining the other to yield an effect on EF.\n\n\\begin{figure}[ht!]\n    \\myfloatalign\n    \\includegraphics[width=\\textwidth]{figures/chapter08/Fig7.pdf}\n    \\caption{Force-LV volume curves at the end-diastolic and end-systolic pressures (top right, orange and green lines) can be separately manipulated to modulate the LV contractile function. However, interventions on calcium transient (bottom left, blue line) and sarcomeric generated force (top left, orange and green full lines) both manifest as modifications of the former curves, which in turn causes modification of the PV loop (bottom right, blue full line). In addition, pharmacological modulations on the sarcomere might cause a shift of the force-calcium relationship (top left, orange and green dashed lines). However, this will preserve the EF (bottom right, blue dashed line) without improving LV contractile function, which was the desired outcome of the performed sarcomeric intervention.}\n    \\label{fig:schematic}\n\\end{figure}\n\n\n%\n%\n%\n\\subsection{Limitations}\\label{sec:ch8limitations}\nThe limitations of this study mainly concern the adopted modelling/emulation framework, and are presented fully in Chapter~\\ref{cha:chapter9}, Section~\\ref{sec:ch9limitations}.\n\n%\n%\n%\n\\section{Summary}\\label{sec:ch8summary}\nWe have used a biophysically detailed mathematical model of a healthy rat heart contraction to quantitatively map sarcomere properties to whole heart function. Using this mapping, we demonstrated that the relationship between the F-pCa curve and LV function is non-linear and non-monotonic. This results in the non-interpretability of observed changes in the LV function in terms of unique sarcomere modulations, which highlights the need for muscle experimental findings to be put into a broader context where not only the $\\pCaf$ and Hill coefficient but also active and passive force, length and velocity dependencies, calcium transient and boundary conditions are analysed.", "meta": {"hexsha": "509de0681846afc2d511ae3a67d1420afcbc218b", "size": 32501, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "phd-thesis/chapters/chapter08.tex", "max_stars_repo_name": "stelong/phd-thesis", "max_stars_repo_head_hexsha": "25a2c45d359403bde916b9bcfb9485402b4d2a8a", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "phd-thesis/chapters/chapter08.tex", "max_issues_repo_name": "stelong/phd-thesis", "max_issues_repo_head_hexsha": "25a2c45d359403bde916b9bcfb9485402b4d2a8a", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phd-thesis/chapters/chapter08.tex", "max_forks_repo_name": "stelong/phd-thesis", "max_forks_repo_head_hexsha": "25a2c45d359403bde916b9bcfb9485402b4d2a8a", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 108.6989966555, "max_line_length": 1591, "alphanum_fraction": 0.7747453924, "num_tokens": 8133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3491523698675708}}
{"text": "\\documentclass[dvipdfmx,uplatex,a4paper]{article}\n\\def\\vector#1{\\mbox{\\boldmath $#1$}}\n\\usepackage[hiresbb]{graphicx}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{ascmac}\n\\usepackage{braket}\n\\usepackage{circuitikz}\n\\usepackage{cite}\n\\usepackage{comment}\n\\usepackage{float}\n\\usepackage{listings}\n\\usepackage{nameref}\n\\usepackage{siunitx}\n\\usepackage{tikz}\n\\usepackage[version=3]{mhchem}\n\n\\usepackage[colorlinks=true, bookmarks=true,\nbookmarksnumbered=true, bookmarkstype=toc, linkcolor=blue,\nurlcolor=blue, citecolor=blue]{hyperref}\n\n\\makeatletter\n \\renewcommand{\\theequation}{\n   \\thesubsection.\\arabic{equation}}\n  \\@addtoreset{equation}{section}\n\\makeatother\n\n\\title{Solve RGB+ LEDs PWM from Chromaticity}\n\\author{CHINZEI, Kiyoyuki}\n\\date{\\today}\n\\begin{document}\n\\maketitle\n\n\\begin{abstract}\nThis article\\footnote{To cite, please refer to https://github.com/kchinzei/kch-rgbw-lib/docs/rgbw\\_solver.pdf} is a private note to develop \\texttt{kch-rgbw-lib}, a TypeScript library in \\href{https://github.com/kchinzei/kch-rgbw-lib}{github} and \\href{https://www.npmjs.com/package/kch-rgbw-lib}{npm}. \\texttt{Kch-rgbw-lib} provides classes and functions for multicolor LED, including color space conversions between HSV, RGB, XYZ and xyY and calculation of accurate color composition. This article gives a general solution of multi-number (more than R-G-B) LEDs to represent composite colors. It is not intended to carry new, comprehensive, or most efficient ideas. This document is granted under MIT License.\n\\end{abstract}\n\n\\section{Define the Problem}\n\\subsection{Past works}\\label{s_intro}\nObtaining accurate colors by mixing R-G-B light sources has been utilized as color displays since 1950s. As various colors are available by LED, recent topics are solutions of color composite with additional color sources typically for OLED applications \\cite{Chi2011, Lee2014}. Usually white light sources are used as an additional light source \\cite{AN1562, Chi2011, Lee2014}. For display purposes additional colors other than R-G-B have been also used to expand the possible color ranges (gamut)\\cite{Wikipedia_multicolor}. Sharp once added yellow in Aquos flat-panel TV, but they initially researched 5-primary color display \\cite{Sharp2011}. Amber \\cite{AN2026}, turquoise, and violet can be other colors to expand the gamut.\n\n\\subsection{Given parameters and assumptions}\\label{s_assumptions}\nWe have $N \\geq 3$ color sources (LEDs) with chromaticity $(x_i, y_i)$ and maximum luminance $Y_i$, where $i=1 \\ldots N$. Our problem is to find the optimum composite output ratio (PWM output) $\\boldsymbol{\\alpha} = [\\alpha_1 \\cdots \\alpha_N]^T$ where $0 \\leq \\alpha_i \\leq 1$ to represent a given color input with chromaticity $(x, y)$ and luminance $Y$.\n\nHere, we set our goal of optimization as the following:\n\\begin{enumerate}\n  \\item\\label{I_max_luminance} Under physical constraint $0 \\leq Y \\leq  Y_1 + \\cdots + Y_N$,\n  \\item\\label{I_solution} Obtain exact composite color to represent $(x, y, Y)$.\n  \\item\\label{I_inside_gamut} If $(x, y)$ is outside the gamut of color source, the nearest color in it is used.\n  It can be achieved by projecting the input to the gamut contour.\n  \\item\\label{I_min_energy} When possible, minimize energy consumption $E$, \\\\\n  \\begin{equation}\n    \\label{E_min_energy}\n    E = \\sum_1^N \\alpha_i W_i\n  \\end{equation}\n  where $W_i$ is the power of each LED at the maximum luminance.\n  \\item\\label{I_lifetime} When possible, average turn-on time of LEDs to equalize LEDs lifetime,\n  \\item\\label{I_small_alpha} When possible, set $\\alpha_i$ to null when it's very small.\n  It is preferable to avoid jitter at low PWM output.\n\\end{enumerate}\n\nIt is a typical linear programming (LP) problem. When $N=3$, e.g. R-G-B color sources only, it's a deterministic and not an optimization problem. And when $N=4$, e.g. R-G-B-W LEDs, there is only one parameter to optimize, which makes the problem as simple as we don't need to use sophisticated LP solver.\n% Mathematically, it is dependent to $R = rank(\\boldsymbol{A})$, where $\\boldsymbol{A}$ is a matrix of LEDs, in Eq.~\\eqref{E_X=AY}. We first derive a general description of the problem and solve it for $R=3$, $R=4$ and $R > 4$ cases.\nWe first derive a general description of the problem and solve it for $N=3$, $N=4$ and $N > 4$ cases.\n\n\\section{General solution}\nWe use XYZ color space because a composite of color source in XYZ color space can be obtained as a simple sum of each term.  In XYZ color space, our problem is to determine $\\boldsymbol{\\alpha} = [\\alpha_1 \\cdots \\alpha_N]$ which gives an equation between input color $[X, Y, Z]^T$ and color source $[X_{i}, Y_{i}, Z_{i}]^T$, $i=1 \\ldots N$;\n\n\\begin{equation}\n  \\label{E_XYZcomposite}\n  \\left[\n    \\begin{array}{c}\n      X \\\\\n      Y \\\\\n      Z\n    \\end{array}\n  \\right]\n   = \\alpha_1\n  \\left[\n    \\begin{array}{c}\n        X_1 \\\\\n        Y_1 \\\\\n        Z_1\n    \\end{array}\n  \\right]\n   + \\cdots + \\alpha_N\n  \\left[\n    \\begin{array}{c}\n        X_N \\\\\n        Y_N \\\\\n        Z_N\n    \\end{array}\n  \\right]\n\\end{equation}\n\nColor space $[X, Y, Z]^T$ is expressed by using $(x, y, Y)$:\n\n\\begin{eqnarray}\n  \\label{E_xyY2XYZ}\n  X & = & \\frac{x}{y}  Y \\\\\n  Y & = & Y \\\\\n  Z & = & \\frac{1 - x - y}{y} Y\n\\end{eqnarray}\n\nUsing matrix representation, Eq.~\\eqref{E_XYZcomposite} is written as\n\n\\begin{equation}\n  \\label{E_X=AY}\n  \\left[ \\boldsymbol{X} \\right] =\n  \\left[ \\boldsymbol{A} \\right]\n  \\left[ \\boldsymbol{\\alpha} \\right]\n\\end{equation}\n\n\\noindent\nwhere\n\n\\begin{eqnarray}\n  \\left[ \\boldsymbol{X} \\right] &=&\n  \\left[ X \\, Y \\, Z \\right]^T \\label{E_XYZ^T} \\\\\n%\n  \\left[ \\boldsymbol{A} \\right] &=&\n  \\left[\n    \\begin{array}{ccc}\n      \\frac{x_1}{y_1} Y_1 & \\cdots & \\frac{x_N}{y_N} Y_N \\\\\n      Y_1 & \\cdots & Y_N \\\\\n      \\frac{1 - x_1 - y_1}{y_1}Y_1 & \\cdots & \\frac{1 - x_N - y_N}{y_N}Y_N\n    \\end{array}\n  \\right] \\\\\n%\n  \\left[ \\boldsymbol{\\alpha} \\right] &=&\n  \\left[ \\alpha_1\\, \\cdots\\, \\alpha_N \\right]^T\n\\end{eqnarray}\n\nOur goal is to solve Eq.~\\eqref{E_X=AY} with respect to $ \\boldsymbol{\\alpha} = [\\alpha_1 \\cdots \\alpha_N]^T $. To solve it, we can use the singular value decomposition (SVD) (Eq.~\\eqref{E_SVD})~\\cite{SVD_NRC}.\n\n\\begin{equation}\n  \\label{E_SVD}\n  \\Bigg[ \\boldsymbol{A} \\Bigg] =\n  \\Bigg[ \\boldsymbol{U} \\Bigg]\n  \\left[\n    \\begin{array}{cccc}\n      \\omega_1 & \\\\\n        & \\omega_2 &   &  0 \\cdots 0 \\\\\n        &  & \\omega_3 &\n    \\end{array}\n  \\right]\n  \\Bigg[ \\boldsymbol{V}^T \\Bigg]\n\\end{equation}\n\n\\noindent\nwhere $ \\boldsymbol{A} $ is $ 3 \\times N $,\n$ \\boldsymbol{U} $ is $ 3 \\times 3 $,\n$ [\\omega_1 \\ddots \\omega_3, 0 \\cdots 0] $ is $ 3 \\times N $,\n$ \\boldsymbol{V}^T $ is $ N \\times N $ matrixes\n\\footnote{Many implementations of SVD return 'economy' $\\boldsymbol{V}$ in $ N \\times 3$ instead of calculating full $N \\times N$ size. Matlab, Octave without 'econ' option and \\href{https://www.npmjs.com/package/svd-js}{svd-js} javascript package in NPM with 'f' option (This is my contribution!) give full $\\boldsymbol{V}$.}\nin this specific case, since $ \\boldsymbol{A} $ is a $ 3 \\times N $ matrix and there are upto 3 $\\omega$'s. When $ N \\geq 4 $, $ [\\omega_1 \\ddots \\omega_3 ] $ is null-padded in $ 3 \\times (N-3) $.\nThe pseudo-inverse matrix $ \\boldsymbol{A}^{-1} $ is obtained by\n\n\\begin{equation}\n  \\Bigg[ \\boldsymbol{A} \\Bigg]^{-1} =\n  \\Bigg[ \\boldsymbol{V}_{1-3} \\Bigg]\n  \\left[\n    \\begin{array}{ccc}\n      1/\\omega_1 & & \\\\\n      & 1/\\omega_2 & \\\\\n      & & 1/\\omega_3\n    \\end{array}\n  \\right]\n  \\Bigg[ \\boldsymbol{U}^T \\Bigg]\n\\end{equation}\n\n\\noindent\nwhere $ \\boldsymbol{V}_{1-3} $ is the first 3 columns of $ \\boldsymbol{V} $, those correspond to $ \\omega_1, \\omega_2, \\omega_3 $\n\\footnote{Many implementations of SVD do not sort $ \\boldsymbol{U}, \\boldsymbol{V}$ by $\\omega$s. Matlab and Octave do sort. Algorithm in 'Numerical Recipes in C' and \\href{https://www.npmjs.com/package/svd-js}{svd-js} in NPM do not.}.\nUsing $ \\boldsymbol{A}^{-1} $, we obtain\n\n\\begin{equation}\n  \\label{E_Y=A-1X}\n  \\left[ \\boldsymbol{\\alpha} \\right] =\n  \\left[ \\boldsymbol{A} \\right]^{-1}\n  \\left[ \\boldsymbol{X} \\right]\n\\end{equation}\n\nBy the way, what about the rest of columns in $ \\boldsymbol{V} $? They are null vectors of $ \\boldsymbol{A} $. A null vector $\\boldsymbol{n}$ of $ \\boldsymbol{A}$ is such vector that satisfies $ \\boldsymbol{A} \\boldsymbol{n} = [0]$. By denoting these columns as $ \\boldsymbol{n}_4 \\ldots \\boldsymbol{n}_N $, Eq.~\\eqref{E_Y=A-1X} can be extended as\n\n\\begin{equation}\n  \\label{E_Y=A-1X+n}\n  \\left[ \\boldsymbol{\\alpha} \\right] =\n  \\left[ \\boldsymbol{A} \\right]^{-1}\n  \\left[ \\boldsymbol{X} \\right]\n  + \\beta_4 \\boldsymbol{n}_4 + \\cdots + \\beta_N \\boldsymbol{n}_N\n\\end{equation}\n\\noindent\nwhere $ \\beta_4 \\ldots \\beta_N $ are arbitrary numbers. By choosing these using other constraints, we can obtain the optimum solution.\n\n% The actual number of null vectors is determined by the rank of $\\boldsymbol{A}$.\n\n\n\n\n\\section{Solution of $N=3$ case}\n\nWhen $N=3$, Eq.~\\eqref{E_Y=A-1X} gives a deterministic solution. No optimization. However, the obtained $ \\alpha_i $ should be physically meaningful, i.e., $ 0 \\leq \\alpha_i \\leq 1 $. It can be out of range when\n\\begin{itemize}\n  \\item Input color $[X]$ is out of the gamut defined by the color sources,\n  \\item $Y$ of $[X]$ is greater (brighter) than the color sources.\n\\end{itemize}\n\\noindent\nWhen $ \\alpha_i < 0$, the nearest color in the gamut should be used as the input. We can also truncate such $\\alpha_i$ to 0. In this case, the output color has certain error.\n\nWhen $ \\alpha_i > 1 $, all $\\alpha$s should be normalized by the largest $\\alpha$. This way the color will be correctly obtained, but it will be darker than expected.\n\n\n\n\n\\section{Solution of $N=4$ case}\n\nWhen $N=4$, Eq.~\\eqref{E_Y=A-1X+n} is simple.\n\n\\begin{equation}\n  \\label{E_Y=A-1X+1}\n  \\left[ \\boldsymbol{\\alpha} \\right] =\n  \\left[ \\boldsymbol{A} \\right]^{-1}\n  \\left[ \\boldsymbol{X} \\right]\n  + \\beta_4 \\boldsymbol{n}_4\n\\end{equation}\n\n\\noindent\nWe will determine parameter $\\beta_4$ using the assumptions in section \\ref{s_assumptions}.\nSince it is always $ 0 \\leq \\alpha_i \\leq 1$, by solving it for $\\beta$ (hereafter omitting '$_4$'), we obtain the following conditions.\n\\begin{eqnarray}\n  \\beta & \\geq & \\begin{cases}\n    - \\frac{b_i}{n_i} \\;\\;\\;\\; \\text{ if \\(n_i > 0\\)} \\label{E_betamin} \\\\\n    \\frac{1 - b_i}{n_i} \\;\\;\\;\\; \\text{ if \\(n_i < 0\\)}\n  \\end{cases} \\\\\n%\n  \\beta & \\leq & \\begin{cases}\n    \\frac{1 - b_i}{n_i} \\;\\;\\;\\; \\text{ if \\(n_i > 0\\)} \\\\\n    - \\frac{b_i}{n_i} \\;\\;\\;\\; \\text{ if \\(n_i < 0\\)} \\label{E_betamax}\n  \\end{cases} \\\\\n%\n    E &=& \\sum_{i=1}^4 (\\beta n_i + b_i) W_i \\to min \\label{E_energy_n4}\n\\end{eqnarray}\n\n\\noindent\nwhere $ [b_1,\\, \\ldots{}\\, , b_4]^T = [ \\boldsymbol{A} ]^{-1} [\\boldsymbol{X}] $, $n_i$ are the elements of $\\boldsymbol{n}$. Eq.~\\eqref{E_energy_n4} is from Eq.~\\eqref{E_min_energy}. Finding the largest and smallest values of the right hand side of Eqs.~\\eqref{E_betamin} and \\eqref{E_betamax}, denoted as $\\beta_{min}$ and $\\beta_{max}$, Eqs.~\\eqref{E_betamin} and \\eqref{E_betamax} are rewritten as\n\n\\begin{equation}\n  \\beta_{min} \\leq \\beta \\leq \\beta_{max}\n\\end{equation}\n\nSince Eq.~\\eqref{E_energy_n4} is rewritten as $E = s_1\\beta + s_2$, here $s_1$ and $s_2$ are constants determined by calculating the sums in Eq.~\\eqref{E_energy_n4}, optimized $\\beta$ is determined as\n\n\\begin{equation}\n    \\beta = \\begin{cases}\n      \\beta_{min}  & \\text{if \\(s_1 = \\sum_1^4 n_i W_i > 0\\)} \\\\\n      \\beta_{max}  & \\text{else}\n  \\end{cases}\n\\end{equation}\n\n\\subsection{When $\\beta$ is not determined}\n\nWhen $\\beta_{min} > \\beta_{max}$, there is no feasible answer. Again, there are two cases, when the input color $[\\boldsymbol{X}]$ is out of the gamut, or when $Y$ in Eq.~\\eqref{E_XYZ^T} is greater than the color sources. Since $\\alpha_i \\geq 0$ cannot compromise, we find $\\beta$ that satisfies\n\n\\begin{eqnarray}\n  \\beta & \\geq & - \\frac{b_i}{n_i} \\;\\;\\;\\; \\text{ if \\(n_i > 0\\)} \\label{E_beta0min} \\\\\n  \\beta & \\leq & - \\frac{b_i}{n_i} \\;\\;\\;\\; \\text{ if \\(n_i < 0\\)} \\label{E_beta0miax}\n\\end{eqnarray}\nThen we normalize the largest $\\alpha_i$ to be 1.\n\n\\subsection{When $\\alpha_i$ is small}\n\nTo implement the assumption \\ref{I_small_alpha} in section \\ref{s_assumptions}, we can introduce allowance of small $\\alpha$, $\\alpha_\\varepsilon$, and exchange Eqs.~\\eqref{E_betamin} and \\eqref{E_betamax} as\n\n\\begin{equation}\n  \\beta \\geq \\frac{\\alpha_\\varepsilon - b_i}{n_i}\n\\end{equation}\n\nBut this also needs to assert if $\\beta_{min} \\leq \\beta_{max}$.\n\n\n\n\n\\section{Solution of $N > 4$ case}\nWe can optimize Eq.~\\eqref{E_min_energy} under constraints of $0 \\leq \\alpha_i \\leq 1$ for Eq.~\\eqref{E_Y=A-1X+n} using a linear programming solution\\cite{LP_NRC}.\nTo use linear programming we need to rewrite our problem into the \\textit{normal form}. Normal form of a linear programming problem is\n\n\\begin{itemize}\n  \\item Objective functions are to be minimized,\n  \\item All constraints are equality formulas,\n  \\item All variables $ \\geq 0$.\n\\end{itemize}\n\nSince our constraints $0 \\leq \\alpha_i \\leq 1$ are unequal and $\\beta_i$ can be negative, we introduce \\textit{slack variables} $\\gamma_i, \\delta_i$ and $\\epsilon_i, \\zeta_i$ to replace $\\beta$.\n\n\\begin{itemize}\n  \\item Introduce $\\gamma_i \\geq 0$ such that $b_i + \\beta_4 n_{4i} + \\cdots + \\beta_N n_{Ni} - \\gamma_i = 0$,\n\n  \\item Introduce $\\delta_i \\geq 0$ such that $b_i + \\beta_4 n_{4i} + \\cdots + \\beta_n n_{Ni} + \\delta_i = 1$,\n\n  \\item Replace $\\beta_i = \\epsilon_i - \\zeta_i$, such that $\\epsilon_i \\geq 0 $ and $\\zeta_i \\geq 0$.\n\\end{itemize}\n\nAfter this modification, we have $2N$ equations with $2N$ variables (for $\\gamma$ and $\\delta$) and $2(N-3)$ variables (for $\\epsilon$ and $\\zeta$). Using these replacements, the objective function (Eq.~\\eqref{E_min_energy}) and Eq.~\\eqref{E_Y=A-1X+n} are rewritten as\n\n\\begin{eqnarray}\n%\n  \\label{E_min_energy5}\n  \\sum_{i=1}^N (n_{4i} \\epsilon_4 - n_{4i} \\zeta_4 + \\cdots +  n_{Ni} \\epsilon_N - n_{Ni} \\zeta_N + b_{i}) W_i &\\to& min \\\\\n%\n  \\label{E_bmin5}\n  n_{4i} \\epsilon_4  - n_{4i} \\zeta_4 + \\cdots + n_{Ni} \\epsilon_N  - n_{Ni} \\zeta_N  - \\gamma_i + b_i &=& 0 \\\\\n%\n  \\label{E_bmax5}\n  n_{4i} \\epsilon_4  - n_{4i} \\zeta_4 + \\cdots + n_{Ni} \\epsilon_N  - n_{Ni} \\zeta_N  + \\delta_i + b_i &=& 1\n\\end{eqnarray}\n\n\\noindent\nEq.~\\eqref{E_min_energy5} is the objective function. Solvers applicable to Eqs.~\\eqref{E_min_energy5} - \\eqref{E_bmax5} can be found in many numerical packages. \\href{https://www.npmjs.com/package/kch-rgbw-lib}{\\texttt{Kch-rgbw-lib}} uses \\href{https://www.npmjs.com/package/linear-program-parser}{linear-program-parser} and \\href{https://www.npmjs.com/package/linear-program-solver}{linear-program-solver} in npm.\n\n\\subsection{When solution infeasible}\nLinear programming solver may find it's `infeasible' - no solution to satisfy all constraints in Eqs.~\\eqref{E_bmin5} and \\eqref{E_bmax5}. Another possibility is that the solution would not converge. Yet again, there are two cases, when the input color $[X]$ is out of the gamut, or when $Y$ in Eq.~\\eqref{E_XYZ^T} is greater (brighter) than the color sources.\n\nWhen the object brightness is too large, we can find a solution by omitting Eq.~\\eqref{E_bmax5}. Physically doable solution is to normalize the maximum $Y_i$ to $1.0$.\n\nWe may also see infeasible case when one or more value in solution is very close to zero and Eq.~\\eqref{E_bmin5} fails due to numerical error. If it is the case, you can set a small negative value to the right side of Eq.~\\eqref{E_bmin5} instead of $0$.\n\n\n\n\\section{More to do}\n\nThe following sections discuss items not implemented in \\href{https://www.npmjs.com/package/kch-rgbw-lib}{\\texttt{kch-rgbw-lib}}. We leave them as `homework' fun.\n\n\\subsection{Not to compromise brightness $Y$}\nWhen $Y$ in Eq.~\\eqref{E_XYZ^T} is greater (brighter) than the color source's capacity, there is no solution. Here we suggested a (compromised) solution to normalize $Y_i$. But we can also take another strategy to maintain the goal brightness by compromising the goal color.\n\nThis strategy requires computation of gradient of $Y$ in $\\boldsymbol{\\alpha}$ space.\n\n\n\\subsection{LED's lifetime averaging}\nIn section \\ref{s_assumptions} '\\nameref{s_assumptions}' we introduced an optional condition \\ref{I_lifetime}, 'When possible, average turn-on time of LEDs to equalize LEDs lifetime'. It is equivalent to minimize the variance of $\\alpha_1, \\, \\ldots\\, , \\alpha_N$. It can be an optimization of a quadratic function.\n\nIn $N = 4$ case, we have only one variable $\\beta$ therefore we can optimize only one condition. This means we need to chose between the energy minimization and this condition.\n\n\n\n\\bibliographystyle{unsrt}\n\\bibliography{rgbw}\n\n\\section*{MIT License}\n\nCopyright (c) 2020 Kiyo Chinzei\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n\\end{document}\n", "meta": {"hexsha": "157ed0d3ab6ebe17ea6a58267aeab2e9169e6c36", "size": 17823, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/rgbw_solver.tex", "max_stars_repo_name": "kchinzei/kch-rgbw-lib", "max_stars_repo_head_hexsha": "4714fd3f5aa5952bde2fd2c9288d05f404194003", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-11-08T01:02:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T13:25:27.000Z", "max_issues_repo_path": "docs/rgbw_solver.tex", "max_issues_repo_name": "kchinzei/kch-rgbw-lib", "max_issues_repo_head_hexsha": "4714fd3f5aa5952bde2fd2c9288d05f404194003", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-05-19T14:43:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-20T15:15:55.000Z", "max_forks_repo_path": "docs/rgbw_solver.tex", "max_forks_repo_name": "kchinzei/kch-rgbw-lib", "max_forks_repo_head_hexsha": "4714fd3f5aa5952bde2fd2c9288d05f404194003", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.7828418231, "max_line_length": 730, "alphanum_fraction": 0.700555462, "num_tokens": 5801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.34915236760301044}}
{"text": "\\documentclass[11pt, oneside]{article}\r\n\\usepackage[margin=.9in]{geometry}\r\n\\usepackage{pgfplots}\r\n\\pgfplotsset{compat=default}\r\n\\newcommand{\\cuckoo}{{\\rm cuckoo}}\r\n\\newcommand{\\hash}{{\\rm siphash}}\r\n\\usepackage{hyperref}\r\n\\usepackage{listings}\r\n\\title{Cuckoo Cycle: \\protect\\\\ a memory bound graph-theoretic proof-of-work}\r\n\\author{John Tromp}\r\n\\begin{document}\r\n\\maketitle\r\n\r\n\\begin{abstract}\r\nWe introduce the first graph-theoretic proof-of-work system,\r\nbased on finding small cycles or other structures in large random graphs.\r\nSuch problems are trivially verifiable and arbitrarily scalable, \r\nand appear to require memory linear in graph size to solve efficiently.\r\nWe show that in random bipartite graphs with average degree 1,\r\nlength $L$ cycles occur with frequency approximately $1/L$.\r\nOn these graphs, algorithm \"lean\" finds cycles using one bit per edge, and up to one bit per node.\r\nRuntime is linear in graph size and dominated by random access latency.\r\nWe exhibit two time-memory trade-off (TMTO) algorithms\r\ndecreasing memory usage by a factor $k$ while increasing runtime by a factor $c \\cdot k$.\r\nThe constant $c$ provides a measure of memory-hardness, which is shown to be dependent\r\non cycle length, guiding the latter's choice.\r\nTrading in the other direction, algorithm \"mean\" uses a few dozen bits per edge but is 4x faster\r\nin practice, becoming memory bandwidth bound rather than latency bound.\r\nWe present performance figures for optimized CPU and GPU implementations,\r\nand discuss possible ASIC implementations.\r\n% Both algorithms are shown to parallelize well.\r\n\\end{abstract}\r\n\r\n\\section{Introduction}\r\nA {\\em proof-of-work} (PoW) system allows a verifier to check with negligible\r\neffort that a prover has expended a large amount of computational effort.\r\nOriginally introduced as a spam fighting measure, \r\nwhere the effort is the price paid by an email sender for demanding the\r\nrecipient's attention, they now form one of the cornerstones of crypto currencies.\r\n\r\nAs proof-of-work for new blocks of transactions,\r\nBitcoin~\\cite{nakamoto2009bitcoin} adopted Adam Back's hashcash~\\cite{back2002}.\r\nHashcash entails finding a nonce value such that application of a cryptographic hash function\r\nto this nonce and the rest of the block header, results in a number below a\r\ntarget threshold\\footnote{or, less accurately, results in many leading zeroes}.\r\nThe threshold is dynamically adjusted by the protocol\r\nso as to maintain an average block interval of 10 minutes.\r\n\r\nBitcoin's choice of the simple and purely compute-bound SHA256 hash function\r\nallowed for an easy migration of hash computation from \r\ndesktop processors (CPUs) to graphics-card processors (GPUs),\r\nto field-programmable gate arrays (FPGAs), and finally to custom designed\r\nchips (ASICs), with huge improvements in energy-efficiency at every step.\r\n\r\nSince Bitcoin, many other crypto-currencies have adopted hashcash, with various\r\nchoices of underlying hash function. the most well-known being {\\em scrypt} as\r\nintroduced by Tenebrix~\\cite{tenebrix2011} (since faded into obscurity)\r\nand copied by Litecoin~\\cite{litecoin2011}.\r\nScrypt, designed as a sequential memory-hard key derivation function,\r\nwas specifically chosen to resist the migration away from CPUs and be ``GPU-hostile''.\r\nHowever, to adapt to the efficient verifiability requirement of proof-of-work, its\r\nmemory footprint was severely limited, and migration slowed down only slightly.\r\n\r\nPrimecoin~\\cite{king2013} introduced the notion of a number-theoretic proof-of-work,\r\nthereby offering the first alternative to hashcash among crypto-currencies.\r\nPrimecoin identifies long chains of nearly doubled prime numbers, constrained\r\nby a certain relation to the block header.\r\nVerification of these chains, while very slow compared to bitcoin's, is much faster\r\nthan attempting to find one.\r\nThis asymmetry between proof attempt and verification is typical in non-hashcash proofs of work.\r\nRecently, two other prime-number based crypto-currencies were introduced. Riecoin is based\r\non finding clusters of prime numbers, and Gapcoin on finding large gaps between consecutive prime numbers.\r\n\r\nMomentum~\\cite{larimer2013} proposes finding birthday collisions of hash outputs,\r\nin what could well be the simplest possible asymetric proof-of-work,\r\ncombining scalable memory usage with trivial verifiability.\r\nIn section~\\ref{cycle_length_choice} we show that Momentum is in essence a special case of Cuckoo Cycle,\r\none that is particularly susceptible to time-memory trade-offs.\r\n\r\nAdam Back~\\cite{back2014} has a good overview of proof-of-work papers past and present.\r\n\r\n\\section{Motivation}\r\nCuckoo Cycle aims to be an ``egalitarian'' proof-of-work, that is,\r\nto minimize performance-per-dollar differences across hardware architectures.\r\nThis is to be achieved by making main memory latency or bandwidth the bottleneck, since\r\nDRAM latency and bandwidth vary much less across hardware architecture and process technology\r\nthan compute power.\r\n\r\nOur aim of a memory bound PoW translates to the following desirable properties:\r\n\r\n\\begin{description}\r\n\\item[MB1] a target memory footprint that exceeds a single memory chip\r\n\\item[MB2] a pattern of necessarily random memory accesses\r\n\\item[MB3] minimal computation per random memory access\\footnote{Preferably less than\r\nthe roughly $50$ nanosecond row activation delay for switching rows on a memory bank.}\r\n\\item[MB4] no feasible trade-off of memory for time\\footnote{Rather arbitrarily\r\ndefined as incurring an order of magnitude increase\r\nin $\\mbox{time}\\times\\mbox{memory}$ used per expected solution.}\r\n\\end{description}\r\n\r\nA memory bound PoW aims to take advantage of the huge economies of scale of commodity DRAM production\r\nto make DRAM chips the most cost-effective vehicle for mining.\r\nJust as SRAM is one order of magnitude faster but two orders more expensive than DRAM,\r\nso it is conceivable that development and production of custom memory chips for a memory bound PoW\r\nwill incur a sufficient cost premium to wipe out any performance gains.\r\n\r\nWe thus disagree with the premise of \\cite{poelstra2014} that PoWs should be compute bound\r\nin order to have ongoing energy costs dominate mining, which results in an expensive ASIC\r\ndesign arms race to drive up performance per Watt, rapid hardware obsolescence,\r\nand geographical centralization towards cheap electric power.\r\n\r\nWe will not strive for provable lower bounds on memory usage. Such bounds appear to be\r\nattainable only under the so-called {\\em random oracle model}, where memory tends to be used\r\nmerely as a store for chains of compute-intensive hash outputs.\r\nInstead, we present an efficient proof-finding algorithm\r\nalong with our best attempts at memory-time trade-offs,\r\nand conjecture that these cannot be significantly improved upon.\r\nLacking precise definitions and proofs of memory bound-ness, this work should be considered\r\nmore empirical than formal.\r\n\r\n\\section{Graph-theoretic proofs-of-work}\r\nWe propose to base proofs-of-work on finding certain subgraphs in large pseudo-random graphs.\r\nIn the Erd\\H{o}s-R\\'{e}nyi model, denoted $G(N,M)$, a graph is chosen uniformly at random\r\nfrom the collection of all graphs with $N$ nodes and $M$ edges. Instead, we choose edges\r\ndeterministically from the output of a keyed hash function, whose key could be chosen\r\nuniformly at random. For a well-behaved hash function, these two classes of random graphs\r\nshould have nearly identical properties.\r\n\r\nFormally, fix a keyed hash function\r\n$h: \\{0,1\\}^K \\times \\{0,1\\}^{W_i} \\rightarrow \\{0,1\\}^{W_o}$,\r\nand a small graph $H$ as a target subgraph\\footnote{hash functions generally have arbitrary length inputs,\r\nbut here we fix the input width at $W_i$ bits.}.\r\nNow pick a large number $N \\leq 2^{W_o}$ as the number of nodes,\r\nand $M \\leq 2^{W_i-1}$ as the number of edges.\r\nEach key $k \\in \\{0,1\\}^K$ generates a graph $G_k = (V,E)$ where $V=\\{v_0,\\ldots,v_{N-1}\\}$, and\r\n\\begin{equation}\r\nE=\\{(v_{h(k,2i) \\bmod N},v_{h(k,2i+1) \\bmod N}) | i \\in [0,\\ldots,M-1]\\}\r\n\\end{equation}\r\nThe inputs $i \\in [0,\\ldots,M-1]$ are also called {\\em nonces}\\footnote{These\r\n{\\em micro} nonces should be distinguished from the {\\em macro} nonce used to generate key $k$.}\r\nThe graph has a {\\em solution} if $H$ occurs as a subgraph.\r\nDenote the number of edges in $H$ as $L$.\r\nA proof of solution is an ordered list of $L$ nonces that generate the edges\r\nof $H$'s occurrence in $G_k$.\r\nSuch a proof is verifiable in time depending only on $H$ (typically linear in $L$), independent of $N$ and $M$.\r\n\r\nA simple variation generates random bipartite graphs: $G_k = (V_0 \\cup V_1,E)$ where (assuming $N$ is even)\r\n$V_0=\\{v_0,v_2,\\ldots,v_{N-2}\\}$, $V_1=\\{v_1,v_3,\\ldots,v_{N-1}\\}$, and\r\n\\begin{equation}\r\n\\label{hash_edges}\r\nE=\\{(v_{2(h(k,2i) \\bmod \\frac{N}{2})}, v_{2(h(k,2i+1) \\bmod \\frac{N}{2})+1}) | i \\in [0,\\ldots,M-1]\\}\r\n\\end{equation}\r\n\r\nThe expected number of occurrences of $H$ as a subgraph of $G$ is a function of both $N$ and $M$,\r\nand in many cases is roughly a function of $\\frac{M}{N}$ (half the average node degree).\r\nFor fixed $N$, this function is monotonically increasing in $M$.\r\nTo make the proof-of-work challenging, one chooses a value of $M$ that yields less than one\r\nexpected solution.\r\n\r\nThe simplest possible choice of subgraph is a fully connected one, or a {\\em clique}.\r\nWhile an interesting choice, akin to the number-theoretic notion of a prime-cluster\r\nas used in Riecoin, we leave its consideration to a future paper.\r\n\r\n\\section{Cuckoo Cycle}\r\nIn this paper we focus on what is perhaps the next-simplest possible choice, the {\\em cycle}.\r\nSpecifically, we propose the hash function \\hash\\ with a $K=128$ bit key, $W_i = W_o = 64$ input\r\nand output bits, $N \\leq 2^{64}$ a 2-power, $M=N/2$, and $H$ an $L$-cycle.\r\nUsing the lightweight \\hash\\-2-4 with only 6 rounds helps to attain property MB3.\r\nThe reason for calling the resulting proof-of-work Cuckoo Cycle is that\r\ninserting items in a Cuckoo hashtable naturally leads to cycle formation\r\nin random bipartite graphs.\r\n\r\n\\section{Cuckoo hashing}\r\nIntroduced by Rasmus Pagh and Flemming Friche\r\nRodler~\\cite{Pagh04cuckoohashing}, a Cuckoo hashtable consists of two\r\nsame-sized tables each with its own hash function mapping a key to a table\r\nlocation, providing two possible locations for each key.\r\nUpon insertion of a new key, if both locations are already occupied by keys,\r\nthen one is kicked out and inserted in its alternate location, possibly\r\ndisplacing yet another key, repeating the process until either a vacant\r\nlocation is found, or some maximum number of iterations is reached.\r\nThe latter is bound to happen once cycles have formed in the {\\em Cuckoo graph}.\r\nThis is a bipartite graph with a node for each location and an\r\nedge for every inserted key, connecting the two locations it can reside at.\r\nIt matches the bipartite graph defined above if the cuckoo hashtable\r\nwere based on function $h$.\r\nIn fact, the insertion procedure suggests a simple algorithm for detecting cycles.\r\n\r\n\\section{Cycle detection in Cuckoo Cycle}\r\nWe enumerate the $M$ nonces, but instead of storing the nonce itself as a key\r\nin the Cuckoo hashtable, we store the alternate key location,\r\nand forget about the nonce.  We thus maintain the {\\em directed}\r\ncuckoo graph, in which the edge for a key is directed from the location where\r\nit resides to its alternate location.  Moving a key to its alternate location\r\nthus corresponds to reversing its edge.  The outdegree of every node in this\r\ngraph is either 0 or 1.  When there are no cycles yet, the graph is a {\\em\r\nforest}, a disjoint union of trees.  In each tree, all edges are directed,\r\ndirectly, or indirectly, to its {\\em root}, the only node in the tree with\r\noutdegree 0.  Initially there are just $N$ singleton trees consisting of\r\nindividual nodes which are all roots.\r\nAddition of a new key causes a cycle if and only if its two endpoints are\r\nnodes in the same tree, which we can test by following the path from each\r\nendpoint to its root.\r\nIn case of different roots, we reverse all edges on the shorter of the two\r\npaths, and finally create the edge for the new key itself, thereby joining\r\nthe two trees into one. Let us illustrate this process with an actual example.\r\n\r\nThe left diagram in Figure~\\ref{cycleformation} shows the directed cuckoo graph for header ``39'' on\r\n$N=8+8$ nodes after adding edges\r\n$(2,15),(4,9),(8,5),(4,15),(12,11),(10,5)$ and $(4,13)$ (nodes\r\nwith no incident edges are omitted for clarity).\r\nIn order to add the 8th edge $(10,11)$, we follow the paths $10 \\rightarrow 5\r\n\\rightarrow 8$ and $11 \\rightarrow 12$ to find different roots $8$ and $12$.\r\nSince the latter path is shorter, we reverse it to $12 \\rightarrow 11$ so we\r\ncan add the new edge as $(11 \\rightarrow 10)$, resulting in the middle diagram.\r\nIn order to add to 9th edge\r\n$(10,13)$ we now find the path from $10$ to be the shorter one, so we reverse\r\nthat and add the new edge as $(10 \\rightarrow 13)$, resulting in the right diagram.\r\n\\begin{figure}\r\n\\begin{center}\r\n\\begin{tikzpicture}[>=stealth]\r\n\\node  (2) at (1, 2) [shape=circle,draw] {2};\r\n\\node  (4) at (2, 2) [shape=circle,draw] {4};\r\n\\node  (8) at (3, 2) [shape=circle,draw] {8};\r\n\\node (10) at (4, 2) [shape=circle,draw] {10};\r\n\\node (12) at (5, 2) [shape=circle,draw] {12};\r\n\\node  (5) at (1,-1) [shape=circle,draw] {5};\r\n\\node  (9) at (2,-1) [shape=circle,draw] {9};\r\n\\node (11) at (3,-1) [shape=circle,draw] {11};\r\n\\node (13) at (4,-1) [shape=circle,draw] {13};\r\n\\node (15) at (5,-1) [shape=circle,draw] {15};\r\n\\draw [<-]  (2) -- (15);\r\n\\draw [<-]  (4) -- (9);\r\n\\draw [<-]  (8) -- (5);\r\n\\draw [->]  (4) -- (15);\r\n\\draw [<-] (12) -- (11);\r\n\\draw [->] (10) -- (5);\r\n\\draw [<-]  (4) -- (13);\r\n\\end{tikzpicture}\\hspace{1cm}\\begin{tikzpicture}[>=stealth]\r\n\\node  (2) at (1, 2) [shape=circle,draw] {2};\r\n\\node  (4) at (2, 2) [shape=circle,draw] {4};\r\n\\node  (8) at (3, 2) [shape=circle,draw] {8};\r\n\\node (10) at (4, 2) [shape=circle,draw] {10};\r\n\\node (12) at (5, 2) [shape=circle,draw] {12};\r\n\\node  (5) at (1,-1) [shape=circle,draw] {5};\r\n\\node  (9) at (2,-1) [shape=circle,draw] {9};\r\n\\node (11) at (3,-1) [shape=circle,draw] {11};\r\n\\node (13) at (4,-1) [shape=circle,draw] {13};\r\n\\node (15) at (5,-1) [shape=circle,draw] {15};\r\n\\draw [<-]  (2) -- (15);\r\n\\draw [<-]  (4) -- (9);\r\n\\draw [<-]  (8) -- (5);\r\n\\draw [->]  (4) -- (15);\r\n\\draw [->] (12) -- (11);\r\n\\draw [->] (10) -- (5);\r\n\\draw [<-]  (4) -- (13);\r\n\\draw [<-] (10) -- (11);\r\n\\end{tikzpicture}\\hspace{1cm}\\begin{tikzpicture}[>=stealth]\r\n\\node  (2) at (1, 2) [shape=circle,draw] {2};\r\n\\node  (4) at (2, 2) [shape=circle,draw] {4};\r\n\\node  (8) at (3, 2) [shape=circle,draw] {8};\r\n\\node (10) at (4, 2) [shape=circle,draw] {10};\r\n\\node (12) at (5, 2) [shape=circle,draw] {12};\r\n\\node  (5) at (1,-1) [shape=circle,draw] {5};\r\n\\node  (9) at (2,-1) [shape=circle,draw] {9};\r\n\\node (11) at (3,-1) [shape=circle,draw] {11};\r\n\\node (13) at (4,-1) [shape=circle,draw] {13};\r\n\\node (15) at (5,-1) [shape=circle,draw] {15};\r\n\\draw [<-]  (2) -- (15);\r\n\\draw [<-]  (4) -- (9);\r\n\\draw [->]  (8) -- (5);\r\n\\draw [->]  (4) -- (15);\r\n\\draw [->] (12) -- (11);\r\n\\draw [<-] (10) -- (5);\r\n\\draw [<-]  (4) -- (13);\r\n\\draw [<-] (10) -- (11);\r\n\\draw [->] (10) -- (13);\r\n\\end{tikzpicture}\r\n\\end{center}\r\n\\caption{cycle formation and detection in a Cuckoo graph}\r\n\\label{cycleformation}\r\n\\end{figure}\r\nWhen adding the 10th edge $(8,9)$, we find the paths $8 \\rightarrow 5\r\n\\rightarrow 10 \\rightarrow 13 \\rightarrow 4 \\rightarrow 15 \\rightarrow 2$ and\r\n$9 \\rightarrow 4 \\rightarrow 15 \\rightarrow 2$ with equal roots.\r\nIn this case, we can compute the length of the resulting cycle as\r\n1 plus the sum of the path-lengths to the node where the two paths join.\r\nIn the diagram, the paths join at node $4$, and the cycle length is computed as $1+4+1=6$.\r\n\r\n\\section{Union-find}\r\nThe above representation of the directed cuckoo graph is an example of\r\na {\\em disjoint-set data structure}~\\cite{wikidsds2014}, and our algorithm is\r\nclosely related to the well-known union-find algorithm, where the find operation\r\ndetermines which subset an element is in, and the union operation joins two subsets\r\ninto a single one. For each edge addition to the cuckoo graph we perform the equivalent\r\nof two find operations and one union operation.\r\nThe difference is that the union-find algorithm is free to add\r\ndirected edges between arbitrary elements. Thus it can join two subsets by adding an edge\r\nfrom one root to another, with no need to reverse any edges.\r\nOur algorithm on the other hand solves the union-find problem by maintaining\r\na direction on all union operations while keeping the maximum outdegree at 1.\r\n\r\n\\section{Cuckoo Cycle basic algorithm}\r\nThe above algorithm for inserting edges and detecting cycles forms the basis\r\nfor our basic proof-of-work algorithm.\r\nIf a cycle of length $L$ is found, then we solved the problem, and recover the proof\r\nby storing the cycle edges in a set and enumerating nonces once more to see which ones\r\ngenerate edges in the set.\r\nIf a cycle of a different length is found, then we keep the graph acyclic by ignoring the edge.\r\nThere is some risk of overlooking other $L$-cycles\r\nthrough that edge, but when the expected number of cycles is low (which is what we design for),\r\nthis ignoring of cycle forming edges hardly affects the rate of solution finding.\r\n\r\nThis algorithm is available online at \\url{https://github.com/tromp/cuckoo}\r\nas either the C-program simple\\_miner.cpp or the Java program SimpleMiner.java.\r\nA proof verifier is available as cuckoo.c or Cuckoo.java, while the repository\r\nalso has a Makefile, as well as the latest version of this paper.\r\n% `make test' tests everything.\r\n`make example' reproduces the example shown above.\r\nThe simple program uses 32 bits per node to represent the directed cuckoo graph,\r\nplus about 64KB per thread for two path-following arrays.\r\nThe left plot in Figure~\\ref{runtimes} shows both the total runtime in seconds and the runtime of just\r\nthe hash computation, as a function of (log)size. The latter is purely\r\nlinear, while the former is superlinear due to increasing memory latency\r\nas the nodes no longer fit in cache. The right plot show this more clearly\r\nas the percentage of hashing to total runtime, ending up around 5\\%.\r\n\r\n\\begin{figure}\r\n\\begin{center}\r\n\\begin{tikzpicture}\r\n\\begin{axis}[xlabel={$\\mbox{log}_2(N)$}, ymode=log, ylabel={seconds}, legend pos=north west]\r\n\\addplot[color=red] coordinates {\r\n% (10,0.0000) (11,0.0000) (12,0.0000) (13,0.0001) (14,0.0001)\r\n(15,0.0002) (16,0.0004) (17,0.0008) (18,0.0017) (19,0.0034)\r\n(20,0.0068) (21,0.0139) (22,0.0271) (23,0.0542) (24,0.1084)\r\n(25,0.2166) (26,0.4336) (27,0.8658) (28,1.7322) (29,3.4719)\r\n(30,7.0389) };\r\n\\addlegendentry{hashing runtime}\r\n\\addplot[color=green] coordinates {\r\n% (10,0.0000) (11,0.0000) (12,0.0001) (13,0.0001) (14,0.0003)\r\n(15,0.0002) (16,0.0010) (17,0.0022) (18,0.0049) (19,0.0104)\r\n(20,0.0250) (21,0.0986) (22,0.2465) (23,0.5332) (24,1.1922)\r\n(25,2.5505) (26,5.3394) (27,11.0793) (28,23.1984) (29,54.6811)\r\n(30,128.1682) };\r\n\\addlegendentry{total runtime}\r\n\\end{axis}\r\n\\end{tikzpicture}\r\n% \\hspace{1cm}\r\n\\begin{tikzpicture}\r\n\\begin{axis}[xlabel={$\\mbox{log}_2(N)$}, ylabel={\\% runtime}, legend pos=north east]\r\n\\addplot[color=blue] coordinates {\r\n% (10,38.8889) (11,33.3333) (12,45.1613) (13,39.8496) (14,44.6154)\r\n(15,96.5217) (16,45.9119) (17,38.2180) (18,35.0988) (19,32.6724)\r\n(20,27.2076) (21,14.0874) (22,11.0014) (23,10.1635) (24,9.0964)\r\n(25,8.4921) (26,8.1215) (27,7.8144) (28,7.4670) (29,6.3494)\r\n(30,5.4919) };\r\n\\addlegendentry{hashing percentage}\r\n\\end{axis}\r\n\\end{tikzpicture}\r\n\\end{center}\r\n\\caption{Runtime and compute intensity of the basic algorithm}\r\n\\label{runtimes}\r\n\\end{figure}\r\n\r\nThe left plot in Figure~\\ref{accesses} shows the probability of finding a 42-cycle as a function\r\nof the percentage edges/nodes, while the right plot shows the average number of\r\nmemory reads and writes per edge as a function of the percentage\r\nof processed nonces (progress through main loop).\r\nBoth were determined from 10000 runs at size $2^{20}$;\r\nresults at size $2^{25}$ look almost identical.\r\nIn total the basic algorithm averages 3.3 reads and 1.1 writes per edge.\r\n\r\n\\begin{figure}\r\n\\begin{center}\r\n\\begin{tikzpicture}\r\n\\begin{axis}[xlabel={$\\frac{M}{N}$ in \\%}, ylabel={probability}, legend pos=north west]\r\n\\addplot[color=blue] coordinates {\r\n(40,0) (41,0.00001) (42,0.00003) (43,0.0001) (44,0.00031) (45,0.00067)\r\n(46,0.00141) (47,0.00385) (48,0.00967) (49,0.02222) (50,0.05076)\r\n(51,0.10117) (52,0.17953) (53,0.27993) (54,0.39581) (55,0.51873)\r\n(56,0.63614) (57,0.73955) (58,0.82352) (59,0.88719) (60,0.93182)\r\n(61,0.9616) (62,0.97949) (63,0.98956) (64,0.99503) (65,0.99799)\r\n(66,0.99907) (67,0.9996) (68,0.99989) (69,0.99997) (70,0.99998) (71,1) };\r\n\\addlegendentry{has 42-cycle}\r\n\\end{axis}\r\n\\end{tikzpicture}\r\n% \\hspace{1cm}\r\n\\begin{tikzpicture}\r\n\\begin{axis}[xlabel={\\% nonces processed}, ylabel={\\# memory accesses per nonce}, ymin=0, legend pos=north west]\r\n\\addplot[color=green] coordinates {\r\n(0,2.01) (1,2.02) (2,2.03) (3,2.04) (4,2.05) (5,2.06) (6,2.07) (7,2.08) (8,2.09) (9,2.10) (10,2.11) (11,2.12) (12,2.13) (13,2.15) (14,2.16) (15,2.17) (16,2.18) (17,2.20) (18,2.21) (19,2.22) (20,2.23) (21,2.25) (22,2.26) (23,2.28) (24,2.29) (25,2.30) (26,2.32) (27,2.33) (28,2.35) (29,2.36) (30,2.38) (31,2.40) (32,2.41) (33,2.43) (34,2.45) (35,2.46) (36,2.48) (37,2.50) (38,2.52) (39,2.54) (40,2.56) (41,2.58) (42,2.60) (43,2.62) (44,2.64) (45,2.66) (46,2.68) (47,2.71) (48,2.73) (49,2.76) (50,2.78) (51,2.81) (52,2.83) (53,2.86) (54,2.89) (55,2.92) (56,2.95) (57,2.98) (58,3.01) (59,3.05) (60,3.08) (61,3.12) (62,3.15) (63,3.19) (64,3.23) (65,3.27) (66,3.32) (67,3.36) (68,3.41) (69,3.45) (70,3.51) (71,3.56) (72,3.61) (73,3.67) (74,3.73) (75,3.80) (76,3.86) (77,3.93) (78,4.01) (79,4.09) (80,4.17) (81,4.26) (82,4.36) (83,4.46) (84,4.57) (85,4.69) (86,4.83) (87,4.97) (88,5.13) (89,5.30) (90,5.49) (91,5.71) (92,5.96) (93,6.25) (94,6.59) (95,6.99) (96,7.51) (97,8.18) (98,9.20) (99,10.93) };\r\n\\addlegendentry{reads}\r\n\\addplot[color=red] coordinates {\r\n(0,1.00) (1,1.00) (2,1.00) (3,1.00) (4,1.00) (5,1.00) (6,1.00) (7,1.00) (8,1.00) (9,1.00) (10,1.00) (11,1.00) (12,1.00) (13,1.00) (14,1.00) (15,1.00) (16,1.00) (17,1.00) (18,1.00) (19,1.00) (20,1.00) (21,1.00) (22,1.00) (23,1.01) (24,1.01) (25,1.01) (26,1.01) (27,1.01) (28,1.01) (29,1.01) (30,1.01) (31,1.01) (32,1.01) (33,1.02) (34,1.02) (35,1.02) (36,1.02) (37,1.02) (38,1.02) (39,1.02) (40,1.03) (41,1.03) (42,1.03) (43,1.03) (44,1.03) (45,1.04) (46,1.04) (47,1.04) (48,1.04) (49,1.05) (50,1.05) (51,1.05) (52,1.06) (53,1.06) (54,1.06) (55,1.07) (56,1.07) (57,1.07) (58,1.08) (59,1.08) (60,1.08) (61,1.09) (62,1.09) (63,1.10) (64,1.10) (65,1.11) (66,1.11) (67,1.12) (68,1.13) (69,1.13) (70,1.14) (71,1.14) (72,1.15) (73,1.16) (74,1.16) (75,1.17) (76,1.18) (77,1.19) (78,1.20) (79,1.21) (80,1.22) (81,1.23) (82,1.24) (83,1.25) (84,1.26) (85,1.27) (86,1.29) (87,1.30) (88,1.32) (89,1.33) (90,1.35) (91,1.37) (92,1.39) (93,1.41) (94,1.43) (95,1.46) (96,1.48) (97,1.51) (98,1.54) (99,1.58) };\r\n\\addlegendentry{writes}\r\n\\end{axis}\r\n\\end{tikzpicture}\r\n\\end{center}\r\n\\caption{Threshold nature of solution, and increasing memory usage on threshold approach}\r\n\\label{accesses}\r\n\\end{figure}\r\n\r\n\\section{Difficulty control}\r\nThe ratio $\\frac{M}{N}$ determines a base level of difficulty,\r\nwhich may suffice for applications where difficulty is to remain fixed.\r\nRatios $\\frac{M}{N} \\geq 0.7$ are suitable when a practically guaranteed solution is desired.\r\n\r\nFor crypto currencies, where difficulty must scale in precisely\r\ncontrolled manner across a large range, adjusting the number of edges is not suitable.\r\nThe implementation default $\\frac{M}{N}=\\frac{1}{2}$ gives a solution probability of roughly $2.2\\%$,\r\nwhile the average number of cycles found increases slowly with size; from 2 at $2^{20}$\r\nto 3 at $2^{30}$.\r\n\r\nFor further control, a difficulty target $0 < T < 2^{256}$ is introduced,\r\nand we impose the additional constraint that the sha256 digest of the\r\ncycle nonces in ascending order be less than $T$, thus\r\nreducing the success probability by a factor $\\frac{2^{256}}{T}$.\r\n\r\n\\section{Edge Trimming}\r\n\\label{edge_trimming}\r\nDavid Andersen~\\cite{dga2014} suggested drastically reducing the number of edges\r\nour basic algorithm has to process, by repeatedly identifying nodes of degree one\r\nand eliminating their incident edge. Such {\\em leaf edges} can never be part of a cycle.\r\nThis works well when $\\frac{M}{N} \\leq \\frac{1}{2}$ since the expected degree of a node is then at most 1,\r\nand a significant fraction of edges are expected to be leaf edges.\r\n\r\nTrimming is implemented in our main algorithm in cuckoo\\_miner and hcuckoo\\_miner.cpp.\r\nIt maintains a set of {\\em alive} edges as a bit vector. Initially all edges are alive.\r\nIn each of a given number of trimming rounds, it shrinks this set as follows.\r\nA vector of 2-bit degree counters, one per even node, is initialized to all zeroes.\r\nNext, for all alive edges, compute its even endpoint and increase the corresponding counter,\r\ncapping the value at 2.\r\nNext, for all alive edges, compute its even endpoint and if the corresponding counter is less than 2,\r\nset the edge to be not-alive.\r\nThese steps, both of which cause the random accesses required in property MB2,\r\nare repeated for all odd endpoints.\r\n\r\nPreprocessor symbol PART\\_BITS, whose value we'll denote as $B$,\r\nallows for {\\em counter partitioning}, which trades off node counter storage for runtime,\r\nby processing nodes in multiple passes depending on the value of their $B$ least significant\r\nbits\\footnote{excluding the very least significant bit distinguishing even from odd nodes.}.\r\nThe memory usage is $M$ bits for the alive set and $N / 2^{B}$ for the counters.\r\n\r\nThe diagrams in Figure~\\ref{trimming} show two rounds of edge trimming on the earlier example. In round one\r\neven nodes 2 and 12 lose their single incident edge and in round two, odd nodes 11 and 15 lose\r\ntheir remaining single incident edge. At this point only the 6-cycle is left, so further trimming\r\nwould be pointless.\r\n\r\n\\begin{figure}\r\n\\begin{center}\r\n\\begin{tikzpicture}[>=stealth]\r\n\\node  (2) at (1, 2) [shape=circle,draw] {2};\r\n\\node  (4) at (2, 2) [shape=circle,draw] {4};\r\n\\node  (8) at (3, 2) [shape=circle,draw] {8};\r\n\\node (10) at (4, 2) [shape=circle,draw] {10};\r\n\\node (12) at (5, 2) [shape=circle,draw] {12};\r\n\\node  (5) at (1,-1) [shape=circle,draw] {5};\r\n\\node  (9) at (2,-1) [shape=circle,draw] {9};\r\n\\node (11) at (3,-1) [shape=circle,draw] {11};\r\n\\node (13) at (4,-1) [shape=circle,draw] {13};\r\n\\node (15) at (5,-1) [shape=circle,draw] {15};\r\n\\draw [-]  (2) -- (15);\r\n\\draw [-]  (4) -- (9);\r\n\\draw [-]  (8) -- (5);\r\n\\draw [-]  (4) -- (15);\r\n\\draw [-] (12) -- (11);\r\n\\draw [-] (10) -- (5);\r\n\\draw [-]  (4) -- (13);\r\n\\draw [-] (10) -- (11);\r\n\\draw [-] (10) -- (13);\r\n\\draw [-]  (8) -- (9);\r\n\\end{tikzpicture}\\hspace{1cm}\\begin{tikzpicture}[>=stealth]\r\n\\node  (2) at (1, 2) [shape=circle,draw] {2};\r\n\\node  (4) at (2, 2) [shape=circle,draw] {4};\r\n\\node  (8) at (3, 2) [shape=circle,draw] {8};\r\n\\node (10) at (4, 2) [shape=circle,draw] {10};\r\n\\node (12) at (5, 2) [shape=circle,draw] {12};\r\n\\node  (5) at (1,-1) [shape=circle,draw] {5};\r\n\\node  (9) at (2,-1) [shape=circle,draw] {9};\r\n\\node (11) at (3,-1) [shape=circle,draw] {11};\r\n\\node (13) at (4,-1) [shape=circle,draw] {13};\r\n\\node (15) at (5,-1) [shape=circle,draw] {15};\r\n\\draw [-]  (4) -- (9);\r\n\\draw [-]  (8) -- (5);\r\n\\draw [-]  (4) -- (15);\r\n\\draw [-] (10) -- (5);\r\n\\draw [-]  (4) -- (13);\r\n\\draw [-] (10) -- (11);\r\n\\draw [-] (10) -- (13);\r\n\\draw [-]  (8) -- (9);\r\n\\end{tikzpicture}\\hspace{1cm}\\begin{tikzpicture}[>=stealth]\r\n\\node  (2) at (1, 2) [shape=circle,draw] {2};\r\n\\node  (4) at (2, 2) [shape=circle,draw] {4};\r\n\\node  (8) at (3, 2) [shape=circle,draw] {8};\r\n\\node (10) at (4, 2) [shape=circle,draw] {10};\r\n\\node (12) at (5, 2) [shape=circle,draw] {12};\r\n\\node  (5) at (1,-1) [shape=circle,draw] {5};\r\n\\node  (9) at (2,-1) [shape=circle,draw] {9};\r\n\\node (11) at (3,-1) [shape=circle,draw] {11};\r\n\\node (13) at (4,-1) [shape=circle,draw] {13};\r\n\\node (15) at (5,-1) [shape=circle,draw] {15};\r\n\\draw [-]  (4) -- (9);\r\n\\draw [-]  (8) -- (5);\r\n\\draw [-] (10) -- (5);\r\n\\draw [-]  (4) -- (13);\r\n\\draw [-] (10) -- (13);\r\n\\draw [-]  (8) -- (9);\r\n\\end{tikzpicture}\r\n\\end{center}\r\n\\caption{Trimming of edges which cannot be part of a cycle}\r\n\\label{trimming}\r\n\\end{figure}\r\n\r\nAfter all edge trimming rounds, the counter memory is freed, and allocated to a\r\ncustom cuckoo\\_hashtable (based on \\cite{preshing2013}) that presents the same interface as the\r\nsimple array in the basic algorithm, but gets by with much fewer locations, as long as its {\\em load},\r\nthe ratio of remaining edges to number of locations, is bounded away from 1; e.g. under 90 percent.\r\n\r\nThe number of trimming rounds, which can be set with option {\\tt -n}, defaults to\r\n$1+(B+3)*(B+4)/2$, which was determined empirically to achieve a load close to $50\\%$.\r\n\r\n\\section{Time-Memory Trade-Offs (TMTOs)}\r\nDavid Andersen also suggested an alternative method of trimming that avoids storing a bit per edge.\r\nExpanding on that idea led to the algorithm implemented in tomato\\_miner.h,\r\nwhich, unlike the main algorithm, can trade-off memory directly for runtime.\r\nOn the downside, to even achieve memory parity with the main algorithm, it already incurs a big slowdown.\r\nTo the extent that this slowdown is unavoidable, it can be called\r\nthe {\\em memory hardness} of the proof-of-work.\r\n\r\nThe TMTO algorithm selects a suitably small subset $Z$ of even vertices as a base layer,\r\nand on top of that builds a breadth-first-search\r\n(BFS) forest of depth $L/2$, i.e. half the cycle length.\r\nFor each new BFS layer, it enumerates all edges to see which ones are incident\r\nto the previous layer, adding the other endpoint.\r\nIt maintains a directed forest on all BFS nodes, like the base algorithm does on all nodes.\r\nFor increased efficiency, the base layer $Z$ is filtered for nodes with multiple incident edges.\r\nIf the graph has an $L$-cycle one of whose nodes is in $Z$, then the above procedure will find it.\r\nIf one choice of $Z$ doesn't yield a solution, then the data structures are cleared and the next\r\nsubset is tried.\r\n\r\nA variation on the above algorithm omits the filtering of $Z$, and expands\r\nthe BFS to a whole $L$ levels. This way, an $L$-cycle will be found as long as the distance from (any node in)\r\n$Z$ to the cycle is at most $L/2$. It thus has a much higher chance of finding a cycle, but requires\r\nmore space to store the significantly bigger BFS forest.\r\n\r\nFor each each value of $L \\in \\{2,4,6,8,10,12,14,16,20,24,28,32,40,48,56,64\\}$ we ran these 2 algorithms\r\non 200 graphs of size $2^{25}$ that include an $L$-cycle,\r\nchoosing subset size as a 2-power that results in a memory usage of 4MB,\r\nand analysed the distribution of number of subsets tried before\r\nfinding a solution. Since there is possible overlap between the BFS forests of different initial subsets,\r\nespecially with the second algorithm, the distributions are skewed toward lower numbers. To maximize solution\r\nfinding rate then, it pays to give up on a graph when the first few subsets tried fail to provide a solution.\r\nFor each algorithm and cycle length, we determined the minimum number of tries needed to guarantee solutions\r\nin at least 50 of the 200 graphs. In Figure~\\ref{slowdown} we plot the slowdown relative\r\nto the reference algorithm also using 4MB (2MB for edges and 2MB for nodes).\r\n\r\n\\begin{figure}\r\n\\begin{center}\r\n\\begin{tikzpicture}\r\n% \\begin{axis}[ymin=0, xtick={2,8,16,24,32,40,48,56,64}, xlabel={cycle length $L$}, ylabel={slowdown factor}, legend pos=north west]\r\n\\begin{axis}[ymin=0, xlabel={cycle length $L$}, ylabel={slowdown factor}, legend pos=north west]\r\n\\addplot [color=red] coordinates {\r\n(2,2.8) (4,6.4) (6,9.7) (8,14.5) (10,13.0) (12,25.1) (14,29.0) (16,28.5)\r\n(20,30.4) (24,46.0) (28,36.0) (32,43.3) (40,51.0) (48,82.2) (56,81.0) (64,72.7)\r\n};\r\n\\addlegendentry{BFS($L/2$)}\r\n\\addplot [color=green] coordinates {\r\n(4,14.4) (6,11.6) (8,20.7) (10,21.4) (12,13.9) (14,18.1) (16,26.8) (20,21.9)\r\n(24,18.8) (28,23.3) (32,31.8) (40,42.6) (48,35.6) (56,22.2) (64,41.0)\r\n};\r\n\\addlegendentry{BFS($L$)}\r\n%\\addplot [color=blue, mark=o] coordinates {\r\n%(2, 1.4)\r\n%};\r\n%\\addlegendentry{customized}\r\n\\addlegendentry{}\r\n\\end{axis}\r\n\\end{tikzpicture}\r\n\\end{center}\r\n\\caption{Reduction in solution finding rate for two TMTO algorithms}\r\n\\label{slowdown}\r\n\\end{figure}\r\n\r\nThe zigzagging is caused by the current implementation being limited to 2-power sizes of\r\nboth subsets and cuckoo tables while the load of the latter is kept between 45\\% and 90.\r\n%We plan to lift this restriction in the near future and\r\n%produce smoother plots with constant load cuckoo tables.\r\nThe BFS($L$) algorithm exhibits at least one order of magnitude slowdown, that grows very slowly\r\nwith cycle length, while the BFS($L/2$) algorithm exhibits roughly linear slowdown.\r\nAssuming that these algorithms cannot be significantly improved upon,\r\nthis shows Cuckoo Cycle with larger cycle lengths satisfying property MB4,\r\n\r\n\\section{Choice of cycle length}\r\n\\label{cycle_length_choice}\r\nA cycle of length 2 means that two nonces produce identical edge endpoints---a {\\em collision} in edge space.\r\nThe Momentum proof-of-work looks for collisions on 50 bits of hash output among $2^{26}$ nonces.\r\nThis is in essence Cuckoo Cycle with $N=2^{25}+2^{25}$ nodes and cycle length $L=2$, with\r\ntwo differences.\r\n\r\nFirst, edges are generated not by equation~(\\ref{hash_edges}), but by splitting a SHA512 hash of\r\n$(k,\\mbox{nonce} / 8)$ into 8 64-bit words, taking the most significant 50 bits of the\r\n($\\mbox{nonce} \\bmod 8)th$ one, and viewing that as a pair of two 25-bit edge endpoints, appending\r\na bit to make them even and odd.\r\n\r\nSecond, the choice of $M=2^{26}$ gives a ratio $\\frac{M}{N}$ of 1 rather than $\\frac{1}{2}$ and as such\r\nprohibits the use of edge trimming.\r\n\r\nSince the extreme case of $L=2$ is so special, there is likely to be a greater variety of algorithms that are more\r\nefficient than for the general case. While we haven't found (and don't know of) a improved main algorithm,\r\nwe did find an improved BFS($L/2$) TMTO algorithm (implemented in momentomatum.cpp)\r\nthat cuts the memory usage in half, resulting in a slowdown of only $1.75$---a lack of memory-hardness.\r\n\r\nThe preceding analysis suggests that cycle length should be at least 20 to guard against the more efficient\r\nBFS($L/2$) algorithm, with an additional safety factor of 2.\r\n\r\nIn order to keep proof size manageable, the cycle length should not be too large either.\r\nWe thus consider 20-64 to be a healthy range, and suggest the use of the average of 42.\r\n\r\nThe plot below shows the distribution of cycle lengths found for sizes $2^{10},2^{15},2^{20},2^{25}$,\r\nas determined from 100000,100000,10000, and 10000 runs respectively. The tails of the distributions\r\nbeyond $L=100$ are not shown. For reference, the longest cycle found was of length 2120.\r\n\r\n\\begin{figure}\r\n\\begin{center}\r\n\\begin{tikzpicture}\r\n\\begin{axis}[ymin=0, xlabel={cycle length $L$}, ylabel={probability}, legend pos=north east]\r\n\\addplot[color=orange] coordinates {\r\n(4,0.24862) (6,0.15673) (8,0.10907) (10,0.07952) (12,0.05783) (14,0.04269) (16,0.0303)\r\n(18,0.02237) (20,0.01653) (22,0.01168) (24,0.00815) (26,0.00511) (28,0.00374) (30,0.00251)\r\n(32,0.00191) (34,0.00098) (36,0.00079) (38,0.00029) (40,0.0003) (42,0.00011) (44,0.00018)\r\n(46,8e-05) (48,2e-05) (50,3e-05) };\r\n\\addlegendentry{10}\r\n\\addplot[color=green] coordinates {\r\n(4,0.24822) (6,0.16551) (8,0.12317) (10,0.09749) (12,0.08105) (14,0.07036) (16,0.05871) (18,0.05308)\r\n(20,0.04717) (22,0.04189) (24,0.03801) (26,0.03342) (28,0.03205) (30,0.02822) (32,0.02521)\r\n(34,0.02282) (36,0.0212) (38,0.01852) (40,0.01814) (42,0.01668) (44,0.01511) (46,0.01356)\r\n(48,0.01246) (50,0.01145) (52,0.0101) (54,0.0093) (56,0.00861) (58,0.00778) (60,0.00768)\r\n(62,0.00672) (64,0.00589) (66,0.00565) (68,0.00517) (70,0.00455) (72,0.00435) (74,0.00375)\r\n(76,0.00348) (78,0.00286) (80,0.00276) (82,0.0023) (84,0.00224) (86,0.00204) (88,0.00165)\r\n(90,0.00164) (92,0.00134) (94,0.00126) (96,0.00114) (98,0.00103) (100,0.00101) };\r\n\\addlegendentry{15}\r\n\\addplot[color=red] coordinates {\r\n(4,0.249) (6,0.1666) (8,0.1309) (10,0.0977) (12,0.0821) (14,0.0754) (16,0.0612) (18,0.0569)\r\n(20,0.0504) (22,0.0412) (24,0.0438) (26,0.0385) (28,0.0364) (30,0.0349) (32,0.0328) (34,0.0286)\r\n(36,0.0263) (38,0.0283) (40,0.0244) (42,0.0237) (44,0.0213) (46,0.0197) (48,0.0185) (50,0.0171)\r\n(52,0.0169) (54,0.0204) (56,0.0161) (58,0.0155) (60,0.0153) (62,0.0158) (64,0.0135) (66,0.0135)\r\n(68,0.0118) (70,0.0158) (72,0.0137) (74,0.012) (76,0.0108) (78,0.0119) (80,0.0116) (82,0.0106)\r\n(84,0.0112) (86,0.0102) (88,0.0075) (90,0.0096) (92,0.0091) (94,0.0094) (96,0.0077) (98,0.0089)\r\n(100,0.006) };\r\n\\addlegendentry{20}\r\n\\addplot[color=blue] coordinates {\r\n(4,0.2439) (6,0.1661) (8,0.1216) (10,0.1031) (12,0.0816) (14,0.0755) (16,0.0635) (18,0.055) (20,0.0511) (22,0.0451) (24,0.0427) (26,0.0369) (28,0.0375) (30,0.0336) (32,0.0302) (34,0.0297) (36,0.0264) (38,0.0268) (40,0.0254) (42,0.0215) (44,0.021) (46,0.0205) (48,0.0206) (50,0.0182) (52,0.017) (54,0.0192) (56,0.0172) (58,0.0169) (60,0.0167) (62,0.0147) (64,0.0169) (66,0.0137) (68,0.0169) (70,0.0125) (72,0.0127) (74,0.0123) (76,0.0139) (78,0.0122) (80,0.0131) (82,0.0129) (84,0.012) (86,0.0119) (88,0.0102) (90,0.0088) (92,0.0102) (94,0.0115) (96,0.0108) (98,0.0089) (100,0.0104) };\r\n\\addlegendentry{25}\r\n\\end{axis}\r\n\\end{tikzpicture}\r\n\\end{center}\r\n\\caption{Distribution of cycle lengths in random graphs}\r\n\\label{cyclelengths}\r\n\\end{figure}\r\n\r\n\\section{Parallelization}\r\nAll our implementations allow the number of threads to be set with option {\\tt -t}.\r\nFor $0\\leq t < T$, thread $t$ processes all nonces $t \\bmod T$.\r\nParallelization in the basic algorithm presents some minor algorithmic challenges.\r\nPaths from an edge's two endpoints\r\nare not well-defined when other edge additions and path reversals are still in progress.\r\nOne example of such a path conflict is the check for duplicate edges yielding a false negative,\r\nif in between checking the two endpoints, another thread reverses a path through those nodes.\r\nAnother is the inadvertent creation of cycles when a reversal in progress hampers another thread's\r\npath following causing it to overlook root equality.\r\nThus, in a parallel implementation, path following can no longer be assumed to terminate.\r\nInstead of using a cycle detection algorithm such as~\\cite{1980-brent-cycles}, our implementation\r\nnotices when the path length exceeds MAXPATHLEN (8192 by default),\r\nand reports whether this is due to a path conflict.\r\n\r\nIn the main algorithm, cycle detection only takes a small fraction of total runtime and\r\nthe conflicts above could be avoided altogether by running the cycle detection single threaded.\r\n\r\nIn edge trimming, parallelization is achieved by partitioning the set of edges. To maintain efficient access\r\nto the bitmap of live edges, each thread handles words (of 32 edge-bits each) spaced $T$ apart.\r\n%Partitioning the bitmap over threads by whole words also avoids the need for atomic access.\r\n\r\nAtomic access is used by default for accessing the 2-bit counters. Disabling this results in a small\r\nchance of removing multiple edges incident to a node that access the counter at the same time.\r\n\r\nThe implementation further benefits from bucketing the addresses of counters to be updated or tested,\r\nbased on their most significant bits. Thus, when a bucket becomes full and is emptied by actually\r\nperforming those updates/tests, the accesses are limited to a certain address range, which turns\r\nout to reduce memory access latencies.\r\n\r\nThe plots below show the speedup over single thread performance achieved by multithreading at various\r\ngraph sizes and counter-partition levels.\r\n\r\n\\begin{figure}\r\n\\begin{center}\r\n\\begin{tikzpicture}\r\n\\begin{axis}[ymin=0, xlabel={number of threads}, ylabel={speedup factor}, legend pos=north west]\r\n\\addplot [color=green] coordinates {\r\n(1,1.000) (2,1.921) (3,2.988) (4,3.757) (5,4.668) \r\n(6,5.347) (7,6.138) (8,6.792) (9,7.504) (10,8.108) \r\n(11,8.873) (12,9.380) (13,10.061) (14,10.543) (15,11.190) \r\n(16,11.608) (17,12.231) (18,12.535) (19,13.008) (20,13.433) \r\n};\r\n\\addlegendentry{speedup30}\r\n\\addplot [color=blue] coordinates {\r\n(1,1.336) (2,2.179) (3,3.148) (4,3.984) (5,4.781) \r\n(6,5.462) (7,6.061) (8,6.706) (9,7.354) (10,7.876) \r\n(11,8.333) (12,9.036) (13,9.457) (14,9.838) (15,10.250) \r\n(16,10.713) (17,11.048) (18,11.479) (19,11.736) (20,12.088) \r\n};\r\n\\addlegendentry{speedup30.0}\r\n\\addplot [color=purple] coordinates {\r\n(1,0.795) (2,1.416) (3,2.082) (4,2.683) (5,3.255) \r\n(6,3.762) (7,4.285) (8,4.759) (9,5.222) (10,5.639) \r\n(11,6.105) (12,6.605) (13,7.033) (14,7.400) (15,7.821) \r\n(16,8.144) (17,8.583) (18,9.014) (19,9.303) (20,9.585) \r\n};\r\n\\addlegendentry{speedup30.1}\r\n\\addplot [color=red] coordinates {\r\n(1,0.498) (2,0.919) (3,1.373) (4,1.761) (5,2.176) \r\n(6,2.538) (7,2.913) (8,3.234) (9,3.599) (10,3.883) \r\n(11,4.239) (12,4.527) (13,4.903) (14,5.234) (15,5.570) \r\n(16,5.845) (17,6.194) (18,6.511) (19,6.661) (20,7.003) \r\n};\r\n\\addlegendentry{speedup30.2}\r\n\\end{axis}\r\n\\end{tikzpicture}\r\n% \\hspace{1cm}\r\n\\begin{tikzpicture}\r\n\\begin{axis}[ymin=0, xlabel={number of threads}, ylabel={speedup factor}, legend pos=north west]\r\n\\addplot [color=green] coordinates {\r\n(1,1.000) (2,1.752) (3,2.813) (4,3.439) (5,5.810) \r\n(6,6.762) (7,7.732) (8,8.669) (9,9.646) (10,10.460) \r\n(11,11.348) (12,12.077) (13,13.107) (14,13.663) (15,14.698) \r\n(16,15.363) (17,16.202) (18,16.623) (19,17.446) (20,18.207) \r\n};\r\n\\addlegendentry{speedup32}\r\n\\addplot [color=blue] coordinates {\r\n(1,2.337) (2,3.767) (3,5.445) (4,6.949) (5,8.319) \r\n(6,9.432) (7,10.462) (8,11.632) (9,12.648) (10,13.658) \r\n(11,14.717) (12,15.652) (13,16.461) (14,17.286) (15,18.063) \r\n(16,18.393) (17,19.149) (18,19.647) (19,20.169) (20,20.761) \r\n};\r\n\\addlegendentry{speedup32.0}\r\n\\addplot [color=purple] coordinates {\r\n(1,1.343) (2,2.404) (3,3.534) (4,4.526) (5,5.570) \r\n(6,6.410) (7,7.367) (8,8.208) (9,9.085) (10,9.932) \r\n(11,10.707) (12,11.590) (13,12.297) (14,12.954) (15,13.647) \r\n(16,14.294) (17,15.060) (18,15.718) (19,16.371) (20,16.804) \r\n};\r\n\\addlegendentry{speedup32.1}\r\n\r\n\\end{axis}\r\n\\end{tikzpicture}\r\n\\end{center}\r\n\\caption{Multi-threading speedup}\r\n\\label{speedup}\r\n\\end{figure}\r\n\r\n\\section{Choice of graph size}\r\nFor cryptocurrency purposes, the choice of Cuckoo graph size should be in accordance to its\r\nblock interval time.\r\nTo illustrate, suppose an average desktop machine needs 1 minute for a single proof attempt,\r\nand the block interval time is only 2 minutes. Then it will waste a large fraction (almost half)\r\nof its attempts, as about half the time, someone else finds a proof in under 2 minutes. To reduce such waste\r\nto a small percentage, the time for a single proof attempt should be a similarly small fraction of the block\r\ninterval time. This desirable property is known as {\\em progress-freeness}, and in our case\r\nis achieved more easily with a small graph (and hence memory) size.\r\n\r\nLarger memory sizes have two advantages. Beyond satisfying property MB1,\r\nthey also make it harder for botnets to mine without causing excessive swapping.\r\nSending a computer into swap-hell will likely alert its owner and trigger a cleanup,\r\nso botnet operators can be expected to eschew memory bound PoWs in favor of low-memory ones.\r\n\r\nWe expect these opposing goals to lead to graph sizes from $2^{28}$ to $2^{32}$, with the larger ones geared\r\nmore toward longer block interval times and faster mining hardware.\r\n\r\n\\section{Dynamic Sizing}\r\nIdeally, graph size should grow with evolving memory chip capacities, so as to preserve property MB1.\r\nAlthough these have shown remarkable adherence to Moore's Law in the past,\r\nthis cannot be relied on for the more distant future.\r\nWe therefore propose to re-evaluate the graph size every so-many difficulty adjustments.\r\nIf the difficulty target is sufficiently low, then the\r\ngraph size is deemed to have become \"too easy\" for existing hardware, and gets doubled.\r\n\r\nIn order to make this transition smoother and avoid severe loss of proof-of-work power,\r\nwe propose having a range of sizes allowed at any time,\r\nnamely $k$ consecutive 2-powers for some small number $k\\geq 2$.\r\nAs with Myriad-coin, separate difficulty controls are maintained for each size,\r\nadjusted so that each size accounts for roughly $\\frac{1}{k}$ of all blocks.\r\n\r\nDoubling graph sizes is then equivalent to disabling the smallest 2-power,\r\nand enabling a new largest one, whose initial difficulty target is twice that of the previous largest.\r\nEven if none of the hardware that was working on the smallest 2-power is repurposed for a larger size,\r\nsince this hardware only accounted for a fraction $\\frac{1}{k}$ of the rewards, the loss of\r\nproof-of-work power should be acceptable.\r\n\r\nIt remains to decide what exact form the ``difficulties too low'' condition should take.\r\n\r\n\\section{Conclusion}\r\nCuckoo Cycle is a novel graph-theoretic proof-of-work design that combines\r\nscalable memory requirements with instant verifiability,\r\nand the first where memory latency dominates the runtime.\r\n\r\nBarring any unforeseen memory-time trade-offs, it makes for a near-ideal memory bound proof-of-work\r\nwhose cost effectiveness on commodity hardware could greatly benefit decentralization of mining.\r\n% More research is also needed to determine the effectiveness of GPUs and FPGAs\r\n% at running Cuckoo Cycle.\r\n\r\n\\bibliographystyle{IEEEtran}\r\n\\bibliography{cuckoo}\r\n\r\n\\lstset{language=C,basicstyle=\\footnotesize}\r\n\\section{Appendix A: cuckoo.h}\r\n\\lstinputlisting{../src/cuckoo.h}\r\n\r\n%\\section{Appendix B: cuckoo\\_miner.h}\r\n%\\lstinputlisting{cuckoo_miner.h}\r\n\r\n%\\section{Appendix C: cuckoo\\_miner.cpp}\r\n%\\lstinputlisting{cuckoo_miner.cpp}\r\n\r\n\\end{document}  \r\n", "meta": {"hexsha": "08d7b6ab274089649ab625ea4a5cc878d43e5903", "size": 46032, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "library/cuckoo/doc/cuckoo.tex", "max_stars_repo_name": "reliefs/brominer", "max_stars_repo_head_hexsha": "b37b7131de16ab199fb4bb56a578cef43f9afc30", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "library/cuckoo/doc/cuckoo.tex", "max_issues_repo_name": "reliefs/brominer", "max_issues_repo_head_hexsha": "b37b7131de16ab199fb4bb56a578cef43f9afc30", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "library/cuckoo/doc/cuckoo.tex", "max_forks_repo_name": "reliefs/brominer", "max_forks_repo_head_hexsha": "b37b7131de16ab199fb4bb56a578cef43f9afc30", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-06-04T08:50:33.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-04T08:50:33.000Z", "avg_line_length": 55.8640776699, "max_line_length": 994, "alphanum_fraction": 0.7032716371, "num_tokens": 15213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982043529716, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3491523625378632}}
{"text": "\\documentclass[aps,prl]{revtex4-2}\n\\usepackage{graphicx,amssymb,amsmath}\n\\bibliographystyle{apsrev4-2}\n\\renewcommand*{\\citenumfont}[1]{S#1}\n\\renewcommand*{\\bibnumfmt}[1]{[S#1]}\n\n\n\\begin{document}\n\n\n\\title{Supplementary Information\\\\Vicissitudes of Cities Driven by Re-distributive Growth}\n\\date{\\today}\n\\author{Gezhi Xiu, Jianying Wang, Lei Dong}\n% \\email{xiugz@pku.edu.cn}\n% \\affiliation{IRSGIS, Peking University}\n\n\\author{Yu Liu}\n\\email{liuyu@urban.pku.edu.cn}\n\\affiliation{Institute of Remote Sensing and Geographic Information Systems (IRSGIS), Peking University}\n% \\altaffiliation{CAMS (CNRS/EHESS) 190-198, avenue de France, 75244 Paris Cedex 13, France}\n\n\\pacs{} \n\n% If your reference list includes text notes as well as references,\n% include the following line; otherwise, comment it out.\n\n\n\\maketitle\n\\tableofcontents\n\\vspace{1cm}\n\n\\section{Mathematical Proofs}\n\nThe proofs presented in this section are all derived from the mean field approximations, which differ somehow from the simulated results. Their significance is the null results without random factors such as the spatial conditions.\n\n\\subsection{Zipf's law}\n\nZipf's law is the rank size distribution of cities. Denote by $q_m$ the number of cities having $m$ citizens, then $R(m) = \\int_m^\\infty q(m')dm'$ defines the rank. Empirically, $R(m)\\sim m^{-1}$. The more populated a big city is, the more it is favored by up-comers. In study of city size distributions, SYM is a realization of \\emph{the rich get richer} rule, for the city's growth rate increase proportionally with its present population. Thus, it is similar for cities size distributions to follow Zipf's law. \n\nThe wait time for the $n$th citizen of a city to be born since the $n-1$th is $\\frac{1}{\\beta_2(n-1)}$. So inversely the expected population of a city at time $t$ is $e^{t\\beta_2}$. We denote the sizes of cities at time $t$ as $n_i(t)$, for $i$ in $1,2,3,\\dots$. Meanwhile, we denote the expected population of a city initiated $t$ ago as $Z(t)$. The transition probability of $P(Z_t = j)$ is $e^{-\\beta_2 t}(1-e^{-\\beta_2 t})^{j-1}$. Using Kolmogorov’s Forward Equation\n\\begin{align}p_t'(1,j) = -\\beta_2 j p_t(1,j) + \\beta_2 (j-1) p_t(1,j-1).\\label{forward}\\end{align}  When $j = 1$, we have \\[p_t'(1,1) = -\\beta_2 p_t(1,1), \\] which leads to $p_t=e^{-\\beta_2}$. When $j>1$, we differentiate $P(Z_t = j)$ to have \n\\begin{align}\n\t\\frac{dP(Z_t = j)}{dt} &= -\\beta_2e^{-\\beta_2 t} (1-e^{-\\beta_2 t})^{j-1} + e^{-\\beta_2 t}(j-1)(1-e^{-\\beta_2 t})^{j-2}\\beta_2 e^{-\\beta_2 t}\\notag\\\\\n\t&= -\\beta_2 e^{-\\beta_2 t}(1-e^{-\\beta_2 t})^{j-1} + e^{-\\beta_2 t}(j-1)(1-e^{-\\beta_2 t})^{j-2} [-(1-e^{-\\beta_2 t})\\beta_2+\\beta_2]\\notag\\\\\n\t&= -\\beta_2 e^{-\\beta_2 t}(1-e^{-\\beta_2 t})^{j-1} -\\beta_2 e^{-\\beta_2 t}(j-1)(1-e^{-\\beta_2 t})^{j-1} +\\beta_2e^{-\\beta_2 t}(j-1)(1-e^{-\\beta_2 t})^{j-2}\\notag\\\\\n\t&= -\\beta_2 j e^{-\\beta_2 t}(1-e^{-\\beta_2 t})^{j-1} +\\beta_2e^{-\\beta_2 t}(j-1)(1-e^{-\\beta_2 t})^{j-2}\n\\end{align}\nwhich copes with equation \\ref{forward}. Thus we complete the proof of the probability distribution of a city's population. The probability distribution of the region's population is easy to find according to the given result. The probability distribution of registering $j$ people in $i$ cities at time $t$, is \\[ P_t(i,j) = \\left(\\begin{array}{c}{j-1} \\\\ {i-1}\\end{array}\\right)\\left(e^{-\\beta t}\\right)^{i}\\left(1-e^{-\\beta t}\\right)^{j-i}. \\] \n\nMoreover, tuning the mechanism from pure birth to birth-death process, we receive a different scaling factor.\n\n\\subsection{Clark's law}\n\nIn this part, we use the mean-field approach to derive the spatial distribution of population within a species. This quantity can be interpreted as the spatial distribution mode of a species. The good thing about the mean-field approach is that we can use the potential concept to derive some conclusions. Here, we regard the growing mechanism as a multi-dimensional binary tree. On each dimension, the tree's $i$th layer has $i$ potential nodes. The probability on the $i$th node's generation is is the average of the two nearest nodes' potential generation probability. Basing on the homogeneity of the choice of $\\theta$, the derivation along different axis is the same. Within each city, the spatial distribution of people are captured by the introducing mechanism, $(r,\\theta)$. Clark's law\\cite{clark1951urban} and some variations for multi-centered models\\cite{griffith1981modelling} are empirical clues that correspond to such spatial distributions. Here we reformulate the Clark's law under spatial Yule principles. Since the isotropic setting, the derivation is only needed in one dimension added on a Doppler effect. When spatial constraints are neglected, the expected density distribution along an axis from the origin has an exponential form,$\\rho (R)\\sim e^{-\\alpha R}$. We start the discussion as a node being placed on a broad area. Regardless of adding nodes on else axis, the second is placed at $r$ right-side of the first with a probability of $1/2$. Along this axis, the $n$th node is placed at $k$ from the right end with $C_n^k/2^n$. Using the Stirling formula, it approximately equals to \\begin{align}\n    & \\frac{n^{n+1/2}}{\\sqrt{2\\pi}k^{k+1/2}(n-k)^{n-k+1/2}}\\notag                         \\\\\n=    & \\frac{n-k}{k+1}\\frac{(1+\\frac{1}{n-1-k})^{-k-1/2}}{(1+\\frac{1}{k})^{n-k-1/2}}\\notag \\\\\n=    & \\frac{n-k}{k+1}\\frac{(1+\\frac{1}{n-1-k})^{n-k-1/2}}{(1+\\frac{1}{k})^{k+1/2}}\\notag  \\\\\n\\sim & e^{-k},\n\\end{align}\nwhich turns out to be a exponential distribution. We can interpret it as the local properties of spatial Yule model is a discrete version of a maximum entropy system, since the Clark's law can also be derived by maximum entropy principle\\cite{merity2009accurate}. Recalling the simple mobility assumption as random walk in random direction, we show that individual-level diffusion process can be approximated by the sum of really simple moves.This is a non-trivial result since this is not derived by mean field approach but by random walk assumption of human mobility. To make it precise, at the early stage of the process, a new community can land near the centre of an existing one. In reality, two communities that are too adjacent are sometimes illustrated as two \\emph{districts} in the same city. In our model, a set of communities that destruct others' roundness functions the same with districts within one city. \n\nBy alternating the distributions of step length, we can reproduce other forms of people density distributions. A more skewed distribution of $r$ brings a Levy-like mobility pattern. In particular, a power law mobility distribution brings a Zipf's density distribution $\\rho '(R)\\sim R^{-\\gamma}$\\cite{PhysRevX.4.011008}, where $\\gamma$ is the scaling factor.  In the following part, we focus on global characteristics to derive the area and population distributions among communities.\n\n\\subsection{Competition at the edges}\nWe consider the individual level expansion at urban edges. We denote that the distance between the first and the furthest node of a city as $O$ and $F$, respectively, and the moment that $F$ lands its first offspring as $t+\\tau$, where $t$ is the moment that $F$ is landed. We investigate the radius of the city, which is defined by the distance between $O$ and $F$. The radius of a city at time $t$, $R_t$, changes to $R_{t+\\tau}$ when the offspring is given birth. The expectation of $R_{t+\\tau}$ goes as \n\\begin{align}\n\tE R_{t+\\tau} &= \\int_0^{\\frac{\\pi}{2}} \\sqrt{(R_t+r\\cos\\theta)^2+(r\\sin\\theta)^2} d\\theta \\notag \\\\\n\t&= \\sqrt{2 R_t r} \\int_{0}^{\\frac{\\pi}{2}} \\sqrt{\\frac{R_{t}}{2 r}+\\frac{r}{2 R_{t}}+\\cos \\theta} d \\theta \\notag\\\\\n\t&= 2(R_t+r) \\mathbb{E}\\left(\\pi/4| \\frac{4R_t r}{(R_t+r)^2}\\right)\n\\end{align}where $\\mathbb{E}$ is the elliptic function. We find that it decreases as $r$ increases. So that the smaller cities have more active edging cells.\n\n\\subsection{Average Age within the Memory Kernel}\n\nWe consider the active population over the whole region as working population. The generation speed of population is $N^*\\beta_2 + k\\beta_1$. Thus the population is refreshing, leading to a constant expected age of \\[N^*/\\beta'\\] for $\\beta' := (N^*\\beta_2 + k\\beta_1)/N^*+k$. This leads to a practical implication that the working age allowed in cities shall be related with the sum of working offer from central government of a region. For instance, in the United States, the regressive value of $\\beta$ is around $0.04$. We assume that the working years of a person is 40 years, the expected $N^*$ for the United States is 1,600 units, i.e., 4 millions distributive working opportunities in all cities.\n\n\n\\section{Details on the simulations}\n\nThe simulation results presented here are obtained in the following way. As mentioned in the main text, three rules determine the dynamics of the model.\n\n1) \\textit{spatial growth rule} and \\textit{active citizen rule} both control the city generation and expansion. Instead of conducting the designed protocol, we do it in an equivalent way by stretching the timeline to events labeled in integer. At each time step, we first decide if we add a new city, with probability $p(S)$, or a new meta-population to the existing city, with probability $1 - p(S)$. The probability $p(S)$ is determined by the total ‘‘active’ population and number of cities, $\\frac{k\\beta_1}{k\\beta_1+N\\beta_2}$. If a city is to be built, the place of it is randomly chosen at an empty spot. By empty we mean the cell of the spot contains no existing node. If it is a new node to be generated, we first determine its ancestor node and land it at (r; $\\theta$) of the ancestor node, where r is constant default as 0.5 and $\\theta$ is a realization of a uniformly distributed random variable $U[0; 2\\pi]$. The nodes can survive if the target cell is not taken. The generation and spatial expansion of the city promotes spatial competition. \n\n2). Memory kernel rule captures the resources competition among cities. In the first phase of the simulation, where the total population of each city $i$  less than the population boundary $N^*$,  a new generation of the node is solely accompanied with a record in the memory kernel. However,  when the total population exceeds the $N^*$, a new comer would deactivate a random dweller who is previously recorded in the memory kernel. The growth of the population promotes resource competition among cities.\n\n\\section{Illustrations for the economic constrained phase}\n\n\\subsection{Turnover rate} \n\nRegional development is complex and is affected by different determinants in different time. For example, in Hebei province of China, the largest city Shijiazhuang started to develop fast since it is the crossroad of railways. We interpret this as the redistribution of social resource. There have been plenty of literature\\cite{bowles2019neolithic} that illustrate the interplay between social development and injustice. Jilin City in Jilin province used to be the capital of Jilin province until Changchun, from 1954, changed its status. Obviously, these are redistributions of social resource. In many literature, social injustice is strengthened by the technical revolutions. Stately, agricultural society is more likely to store fortune overtime than nomadic society\\cite{doi:10.1086/701789}. The Gini coefficients in ancient society is also increasing as the productivity grows\\cite{kohler2017greater}. We read this as inequality of human society is born with the desire of better life. \n\nBut what is more interesting is that, when the rich do not get richer. In this Letter we give a possible explanation that the \\emph{memory} of human society is the force of future endeavour. A city's future ability to develop is based on the active population brought by the existing active people. The limited resource is dynamically divided by increasing number of cities, so that there is, though small, but still some odd of overturn. In the following text, we first derive an approximated solution of this problem. We denote the coins share in the $k$th largest city as $n_k$, and investigate the probability that the second largest city becoming the largest, $P_{\\text{overturn}}$. In $m$ successive additions of meta-population from the moment $t_l$, the chance for $n_2(t_l+m)\\ge n_1(t_l+m)$ is equivalent to the case that the city $2$ is picked $n_1(t_l)-n_2(t_l)$ times more than city $1$. The probability of $n_1(t_l)-n_2(t_l)$ picks of city $2$ in a row is $\\frac{n_1!}{n_2!}/N^{n_1-n_2}$. Adding another step brings an probability of $n_1/N$ for $n_1$ to increase to $n_1+1$. So the process ends at $n_1(t_l)-n_2(t_l)+1$ steps is the former probability times $(n_1+1)/N$ and plus a expected latent step length. \n\n\\subsection{Urban shrinkage}\n\nThe urban development is a sequel of the spatial distribution of existing resource. Thus the preferential attachment is not only performed among people, but also on urban land-use. The concentration of urban resource result in urban shrinkage, indicating that the popular definition of resource distribution, say Gross Democratic Product (GDP), may not be the best indicator of regional fortune, since it is not a perfect indication of a place's future. Urban shrinking is widely discussed in recent years. It is always referred with demographic changes such as decreasing fertility, aging, and out-migration\\cite{haase2008urban}. In the comprehension of urban input-output framework, the governmental investment cannot follow up with the spatial growth of population. So the further investment can only go to \\emph{active} area where recent comers to the cities are mostly found. \n\nWe conduct a cell-wise analysis. The speed of a cell's losing active population equals to the speed of others' adding, $[(N^*-n)\\beta_2 +k \\beta_1]\\cdot n/N^*$; The speed of its own adding is $n\\beta_2$. Thus the equilibrium condition is \\[ [(N^*-n)\\beta_2+k\\beta_1]\\cdot \\frac{n}{N^*} = \\beta_2N^*. \\] The equilibrium $n_eq = k/\\beta$. This means that whether a spot in city will be prosperous  has nothing to do with the regional resource $N^*$, but it is related to the strong force of emergence of cities.\n\n\n% \\bibliographystyle{plain}\n\\bibliography{refs.bib}\n    \n\\end{document}", "meta": {"hexsha": "d302dbace97159c8ae388b439c3b1a3fbdb67277", "size": 14215, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Tex/sym_history/sym_april/SI.tex", "max_stars_repo_name": "GXIU/SpatialYule", "max_stars_repo_head_hexsha": "897e4da9f3c47bcc6e379b2473acd12e2d94442c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tex/sym_history/sym_april/SI.tex", "max_issues_repo_name": "GXIU/SpatialYule", "max_issues_repo_head_hexsha": "897e4da9f3c47bcc6e379b2473acd12e2d94442c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tex/sym_history/sym_april/SI.tex", "max_forks_repo_name": "GXIU/SpatialYule", "max_forks_repo_head_hexsha": "897e4da9f3c47bcc6e379b2473acd12e2d94442c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 138.0097087379, "max_line_length": 1626, "alphanum_fraction": 0.7486457967, "num_tokens": 3871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.3490428766721751}}
{"text": "\n\\documentclass[12pt]{article}\n\\usepackage{url} \n%\\usepackage[dvips]{graphicx}\n\\usepackage[pdftex]{graphicx}\n\\usepackage[latin1]{inputenc}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{fancyhdr}\n\\usepackage{bm}\n\\usepackage{float}\n\\usepackage{color}\n\\usepackage[dvipsnames]{xcolor}\n\\usepackage{wrapfig}\n\\usepackage{multicol}\n\\usepackage[colorlinks=true,\n\t\tlinkcolor=red,\n\t\tcitecolor=blue,\n\t\turlcolor=blue]{hyperref}\n\n\\usepackage{titlesec}\n\\usepackage[titletoc]{appendix}\n%\\usepackage{appendix}\n\\setcounter{secnumdepth}{4}\n\n\\titleformat{\\paragraph}\n{\\normalfont\\normalsize\\bfseries}{\\theparagraph}{1em}{}\n\\titlespacing*{\\paragraph}\n{0pt}{3.25ex plus 1ex minus .2ex}{1.5ex plus .2ex}\n\n\\setlength {\\parindent} { 10mm} \n\\setlength{\\textheight}{230mm} \n\\setlength{\\textwidth}{160mm} \n\\setlength{\\oddsidemargin}{0mm}\n\\setlength{\\topmargin}{-10mm} \n% newcommands\n\\newcommand{\\p}{\\partial}\n\\newcommand{\\g}[1]{\\mbox{\\boldmath $#1$}}\n\\newcommand{\\vi}{\\g V_{\\! \\! i}}\n\\newcommand{\\ps}{Pfirsch-Schl\\\"{u}ter} \n\\newcommand{\\lp}{\\left(}\n\\newcommand{\\rp}{\\right)}\n\\newcommand{\\ca}[1]{\\mbox{\\cal $#1$}}\n\\newcommand{\\be}{\\begin{displaymath}}\n\\newcommand{\\ee}{\\end{displaymath}}\n\\newcommand{\\bn}{\\begin{equation}}\n\\newcommand{\\en}{\\end{equation}}\n\\newcommand{\\mygtrsim}{\\mathrel{\\mbox{\\raisebox{-1mm}{$\\stackrel{>}{\\sim}$}}}}\n\\newcommand{\\mylsim}{\\mathrel{\\mbox{\\raisebox{-1mm}{$\\stackrel{<}{\\sim}$}}}}\n\\newcommand{\\vek}{\\bf}\n\\newcommand{\\ten}{\\sf}\n\\newcommand{\\bfm}[1]{\\mbox{\\boldmath$#1$}}\n\\newcommand{\\lang}{\\left\\langle}\n\\newcommand{\\rang}{\\right\\rangle}\n\\newcommand{\\vo}[1]{\\left|\\begin {array}{l} \\mbox{} \\\\ \\mbox{} \\\\$#1$ \\end\n{array}\\right .}  \n\\newcommand{\\von}[2]{\\left |\\begin {array}{l}\n\\mbox{}\\\\$#1$\\\\$#2$ \\end {array}\\right .}\n\\newcommand{\\simgt}{\\:{\\raisebox{-1.5mm}{$\\stackrel\n{\\textstyle{>}}{\\sim}$}}\\:}\n\\newcommand{\\simlt}{\\:{\\raisebox{-1.5mm}{$\\stackrel\n{\\textstyle{<}}{\\sim}$}}\\:}\n%\\renewcommand {\\baselinestretch} {1.67}\n%\\pagestyle{empty}\n\\newcommand{\\todo}[1]{\\textbf{\\textcolor{red}{TODO: #1}}}\n\\newcommand{\\remark}[1]{\\textbf{\\textcolor{red}{REMARK: #1}}}\n\n\\title{Implementation of $\\Phi_1$ in SFINCS}\n\n\\pagestyle{fancy}\n\\fancyhead{}\n\\chead{Albert Moll\\'en %850227-2019\n\\\\ Implementation of $\\Phi_1$ in SFINCS}\n\\cfoot{\\thepage}\n\\renewcommand{\\headrulewidth}{1pt}\n\\renewcommand{\\footrulewidth}{1pt}\n\\setlength{\\headheight}{28pt}\n\\setlength{\\footskip}{25pt}\n\n\\newcommand{\\red}[1]{\\textcolor{red}{#1}}\n\\newcommand{\\mE}{\\mathcal{E}}\n\\newcommand{\\energy}{\\mathcal{E}}\n\\newcommand{\\mK}{\\mathcal{K}}\n\\newcommand{\\mN}{\\mathcal{N}}\n\\newcommand{\\mD}{\\mathcal{D}}\n\\newcommand{\\ord}{\\mathcal{O}}\n\\newcommand{\\Tpe}{T_\\perp}\n\\newcommand{\\Tpa}{T_\\|}\n\\newcommand{\\vpe}{v_\\perp}\n\\newcommand{\\vpa}{v_\\|}\n\\newcommand{\\kpe}{k_\\perp}\n\\newcommand{\\kpa}{k_\\|}\n\\newcommand{\\Bv}{\\mathbf{B}}\n\\newcommand{\\Ev}{\\mathbf{E}}\n\\newcommand{\\bv}{\\mathbf{b}}\n\\newcommand{\\vv}{\\mathbf{v}}\n\\newcommand{\\cd}{\\cdot}\n\\newcommand{\\na}{\\nabla}\n\\newcommand{\\btheta}{\\bar{\\theta}}\n\\newcommand{\\phit}{\\tilde{\\phi}}\n\\newcommand{\\oert}{\\tilde{\\omega}_{Er}}\n\n\\begin{document}\n\\titlepage\n\n\\maketitle\n\n\\section*{EUTERPE old equations vs new equations}\nWe want to modify the implementation of the old EUTERPE equations \\cite{regana} in SFINCS \nto the new equations \\cite{reganaArxiv}.\n\nThe old equations for the particle trajectories and the drift-kinetic equation are\n\\begin{align}\n\\dot{\\bm{R}} & =  v_\\| \\bm{b} - \\frac{\\na \\Phi_0 \\times \\bm{b}}{B}  \\\\\n\\dot{v}_\\| & =  - \\frac{q}{m} \\bm{b} \\cdot \\na \\Phi_1 - \\mu \\bm{b} \\cdot \\na B - \\frac{v_\\|}{B^2} \\left(\\bm{b} \\times \\na B\\right) \\cdot \\na \\Phi_0 \\\\\n\\dot{\\mu} & =  0\n\\label{eq:ParticleTrajEuterpeOld}\n\\end{align}\nand\n\\begin{multline}\n\\frac{\\p f_1}{\\p t} + \\dot{\\bm{R}} \\cdot \\na f_1 + \\dot{v}_\\| \\frac{\\p f_1}{\\p v_\\|} - C = \\\\ =\n- f_M \\left[\\frac{1}{n} \\frac{\\p n}{\\p \\psi} + \\left(\\frac{m v^2}{2 T} - \\frac{3}{2}\\right) \\frac{1}{T} \\frac{\\p T}{\\p \\psi}\\right] \n\\left(\\bm{v}_d + \\bm{v}_{E1}\\right) \\cdot \\na \\psi - \n\\frac{q}{m} \\frac{f_M}{v_{\\mathrm{th}}^2} \\left(v_\\| \\bm{b} + \\bm{v}_d\\right) \\cdot \\left(\\na \\Phi_0 + \\na \\Phi_1\\right).\n\\label{eq:DriftKineticEuterpeOld}\n\\end{multline}\n\nThe new equations are\n\\begin{align}\n\\dot{\\bm{R}} & =  v_\\| \\bm{b} - \\frac{\\na \\Phi_0 \\times \\bm{b}}{B}  \\\\\n\\dot{v}_\\| & =  - \\frac{q}{m} \\bm{b} \\cdot \\na \\Phi_1 - \\mu \\bm{b} \\cdot \\na B - \\frac{v_\\|}{B^2} \\left(\\bm{b} \\times \\na B\\right) \\cdot \\na \\Phi_0 \\\\\n\\dot{\\mu} & =  0\n\\label{eq:ParticleTrajEuterpeNew}\n\\end{align}\nand\n\\begin{multline}\n\\frac{\\p f_1}{\\p t} + \\dot{\\bm{R}} \\cdot \\na f_1 + \\dot{v}_\\| \\frac{\\p f_1}{\\p v_\\|} - C = \\\\ =\n- f_0 \\left[\\frac{1}{n} \\frac{\\p n}{\\p \\psi} + \\frac{q}{T} \\frac{\\p \\Phi_0}{\\p \\psi} + \\left(\\frac{m v^2}{2 T} - \\frac{3}{2} + \\frac{q}{T} \\Phi_1\\right) \\frac{1}{T} \\frac{\\p T}{\\p \\psi}\\right] \n\\left(\\bm{v}_d + \\bm{v}_{E1}\\right) \\cdot \\na \\psi.\n\\label{eq:DriftKineticEuterpeNew}\n\\end{multline}\nHere we have the definitions\n\\begin{equation}\n\\Phi\\left(\\psi, \\theta, \\varphi\\right) \\equiv \\Phi_0\\left(\\psi\\right) + \\Phi_1\\left(\\theta, \\varphi\\right),\n\\label{eq:Phi}\n\\end{equation}\n\\begin{equation}\n\\bm{v}_d = \\frac{m}{q} \\frac{\\mu B + v_\\|^2}{B^2} \\bm{b} \\times \\na B,\n\\label{eq:MagneticDrift}\n\\end{equation}\n\\begin{equation}\n\\bm{v}_{E1} = - \\frac{\\na \\Phi_1 \\times \\bm{b}}{B},\n\\label{eq:ElectricDrift1}\n\\end{equation}\n\\begin{equation}\nf_0 = f_M \\exp \\left(- q \\Phi_1 / T \\right) = \\frac{n_0\\left(\\psi\\right)}{\\left(2 \\pi\\right)^{3/2} v_{\\mathrm{th}}^3} \\exp \\left[- \\frac{\\left(v_\\|^2  + v_\\perp^2\\right)}{2 v_{\\mathrm{th}}^2}\\right] \\exp \\left(- q \\Phi_1 / T \\right),\n\\label{eq:f0}\n\\end{equation}\n$q = Z e$ and $v_{\\mathrm{th}}^2 = T/m$.\\\\\n\n\\noindent The only differences appear in the RHS:s of Eqs.~\\ref{eq:DriftKineticEuterpeOld} and \\ref{eq:DriftKineticEuterpeNew}:\\\\ \nFirstly, $f_M$ has been replaced by $f_0$ containing the $\\exp \\left(- q \\Phi_1 / T \\right)$ factor.\\\\ \nSecondly, some of the terms have been modified. \nWe rewrite the RHS of \\ref{eq:DriftKineticEuterpeNew}:\n\\begin{multline}\n{\\mathrm{RHS}}_{\\mathrm{NEW}} =\n- f_0 \\left[\\frac{1}{n} \\frac{\\p n}{\\p \\psi} + \\frac{q}{T} \\frac{\\p \\Phi_0}{\\p \\psi} + \\left(\\frac{m v^2}{2 T} - \\frac{3}{2} + \\frac{q}{T} \\Phi_1\\right) \\frac{1}{T} \\frac{\\p T}{\\p \\psi}\\right] \n\\left(\\bm{v}_d + \\bm{v}_{E1}\\right) \\cdot \\na \\psi = \\\\ =\n%%\n- f_0 \\left[\\frac{1}{n} \\frac{\\p n}{\\p \\psi} + \\frac{q}{T} \\frac{\\p \\Phi_0}{\\p \\psi} + \\left(\\frac{m v^2}{2 T} - \\frac{3}{2}\\right) \\frac{1}{T} \\frac{\\p T}{\\p \\psi}\\right] \n\\left(\\bm{v}_d + \\bm{v}_{E1}\\right) \\cdot \\na \\psi + \\\\ - \nf_0  \\frac{q}{T} \\Phi_1 \\frac{1}{T} \\frac{\\p T}{\\p \\psi}\n\\left(\\bm{v}_d + \\bm{v}_{E1}\\right) \\cdot \\na \\psi = \\\\ =\n%%\n- f_0 \\left[\\frac{1}{n} \\frac{\\p n}{\\p \\psi} + \\frac{q}{T} \\frac{\\p \\Phi_0}{\\p \\psi} + \\left(\\frac{m v^2}{2 T} - \\frac{3}{2}\\right) \\frac{1}{T} \\frac{\\p T}{\\p \\psi}\\right] \n\\bm{v}_d \\cdot \\na \\psi + \\\\ - \nf_0 \\left[\\frac{1}{n} \\frac{\\p n}{\\p \\psi} + \\left(\\frac{m v^2}{2 T} - \\frac{3}{2}\\right) \\frac{1}{T} \\frac{\\p T}{\\p \\psi}\\right] \n\\bm{v}_{E1} \\cdot \\na \\psi - f_0 \\frac{q}{T} \\frac{\\p \\Phi_0}{\\p \\psi} \\bm{v}_{E1} \\cdot \\na \\psi + \\\\ -\nf_0 \\frac{q}{T} \\Phi_1 \\frac{\\na T}{T} \\cdot\n\\left(\\bm{v}_d + \\bm{v}_{E1}\\right) = \\\\ =\n%%\n- f_0 \\left[\\frac{1}{n} \\frac{\\p n}{\\p \\psi} + \\frac{q}{T} \\frac{\\p \\Phi_0}{\\p \\psi} + \\left(\\frac{m v^2}{2 T} - \\frac{3}{2}\\right) \\frac{1}{T} \\frac{\\p T}{\\p \\psi}\\right] \n\\bm{v}_d \\cdot \\na \\psi + \\\\  \n\\textcolor{blue}{- f_0 \\left[\\frac{1}{n} \\frac{\\p n}{\\p \\psi} + \\left(\\frac{m v^2}{2 T} - \\frac{3}{2}\\right) \\frac{1}{T} \\frac{\\p T}{\\p \\psi}\\right] \n\\bm{v}_{E1} \\cdot \\na \\psi}  + \\\\  \n\\textcolor{red}{- f_0 \\frac{q}{T} \\left[\\na \\Phi_0 \\cdot \\bm{v}_{E1} + \\Phi_1 \\frac{\\na T}{T} \\cdot \\bm{v}_d + \\Phi_1 \\frac{\\na T}{T} \\cdot \\bm{v}_{E1} \\right]}.\n\\label{eq:DriftKineticEuterpeNewRHS}\n\\end{multline}\nSimilarly, the RHS of \\ref{eq:DriftKineticEuterpeOld} is rewritten as:\n\\begin{multline}\n{\\mathrm{RHS}}_{\\mathrm{OLD}} =\n- f_M \\left[\\frac{1}{n} \\frac{\\p n}{\\p \\psi} + \\left(\\frac{m v^2}{2 T} - \\frac{3}{2}\\right) \\frac{1}{T} \\frac{\\p T}{\\p \\psi}\\right] \n\\left(\\bm{v}_d + \\bm{v}_{E1}\\right) \\cdot \\na \\psi - \n\\frac{q}{m} \\frac{f_M}{v_{\\mathrm{th}}^2} \\left(v_\\| \\bm{b} + \\bm{v}_d\\right) \\cdot \\left(\\na \\Phi_0 + \\na \\Phi_1\\right) = \\\\ =\n%%\n- f_M \\left[\\frac{1}{n} \\frac{\\p n}{\\p \\psi} + \\frac{q}{T} \\frac{\\p \\Phi_0}{\\p \\psi} + \\left(\\frac{m v^2}{2 T} - \\frac{3}{2}\\right) \\frac{1}{T} \\frac{\\p T}{\\p \\psi}\\right] \n\\bm{v}_d \\cdot \\na \\psi + \\\\  \n\\textcolor{blue}{- f_M \\left[\\frac{1}{n} \\frac{\\p n}{\\p \\psi} + \\left(\\frac{m v^2}{2 T} - \\frac{3}{2}\\right) \\frac{1}{T} \\frac{\\p T}{\\p \\psi}\\right] \n\\bm{v}_{E1} \\cdot \\na \\psi}  + \\\\  \n\\textcolor{red}{- f_M \\frac{q}{T} \\left[v_\\| \\bm{b} \\cdot  \\na \\Phi_1 + \\bm{v}_d \\cdot  \\na \\Phi_1\\right]}.\n\\label{eq:DriftKineticEuterpeOldRHS}\n\\end{multline}\nComparing ${\\mathrm{RHS}}_{\\mathrm{NEW}}$ to ${\\mathrm{RHS}}_{\\mathrm{OLD}}$ we see that, apart from $f_M \\rightarrow f_0$, only the terms in red have changed. \n\n\\subsection*{What has to be changed in SFINCS}\nThe only part of the drift-kinetic equation block we need to modify is the RHS, where we need to update the red terms and substitute $f_M \\rightarrow f_0$. SFINCS had earlier neglected the $\\bm{v}_d \\cdot  \\na \\Phi_1$-term which is small in the standard $\\rho_\\ast$-expansion. \nThe RHS that was implemented is (see Matt's ISHW poster, also note that $\\bm{v}_{E} \\cdot \\na \\psi = \\bm{v}_{E1} \\cdot \\na \\psi$)\n\\begin{multline}\n{\\mathrm{RHS}}_{\\mathrm{SFINCS, OLD}} =\n- f_M \\left[\\frac{1}{n} \\frac{\\p n}{\\p \\psi} + \\frac{q}{T} \\frac{\\p \\Phi_0}{\\p \\psi} + \\left(\\frac{m v^2}{2 T} - \\frac{3}{2}\\right) \\frac{1}{T} \\frac{\\p T}{\\p \\psi}\\right] \n\\bm{v}_d \\cdot \\na \\psi + \\\\  \n\\textcolor{blue}{- f_M \\left[\\frac{1}{n} \\frac{\\p n}{\\p \\psi} + \\left(\\frac{m v^2}{2 T} - \\frac{3}{2}\\right) \\frac{1}{T} \\frac{\\p T}{\\p \\psi}\\right] \n\\bm{v}_{E} \\cdot \\na \\psi}  %+ \\\\  \n\\textcolor{red}{- f_M \\frac{q}{T} v_\\| \\bm{b} \\cdot  \\na \\Phi_1 }.\n\\label{eq:DriftKineticSFINCSOldRHS}\n\\end{multline}\nWe thus replace \n\\begin{equation}\n\\textcolor{red}{\nv_\\| \\bm{b} \\cdot  \\na \\Phi_1\n}\n\\label{eq:ReplaceOLD}\n\\end{equation}\nwith \n\\begin{equation}\n\\textcolor{red}{\n\\na \\Phi_0 \\cdot \\bm{v}_{E} + \\Phi_1 \\frac{\\na T}{T} \\cdot \\bm{v}_d + \\Phi_1 \\frac{\\na T}{T} \\cdot \\bm{v}_{E}},\n\\label{eq:ReplaceNEW}\n\\end{equation}\nand make the substitution\n\\begin{equation}\n\\textcolor{red}{\nf_M \\rightarrow f_0 = f_M \\exp \\left(- q \\Phi_1 / T \\right)}.\n\\label{eq:substitution}\n\\end{equation}\n%\\remark{In EUTERPE $\\Phi_1$ is only an unknown in the quasi-neutrality equation, in the kinetic equation it is an input which means that there are no nonlinearities. It also means that the exponential in $f_0$ is not expanded in the kinetic equation. \n%Are all terms in Eq.~\\ref{eq:ReplaceNEW} feasible to implement in SFINCS? E.g. is it a problem that the $\\Phi_1 \\frac{\\na T}{T} \\cdot \\bm{v}_{E}$-term contains 3 factors with $\\Phi_1$?}\\\\\n\\\\\n\n\\noindent All terms which contain $\\Phi_1$ are now nonlinear. \nIt does not make sense to have both switches \\textbf{includePhi1} and \\textbf{nonlinear} still available in SFINCS, \nand consequently we will remove the \\textbf{nonlinear} switch.\n\\\\\n\n\\noindent We will also introduce to possibility to run SFINCS with an adiabatic species. \n\n\\newpage\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section*{Implementation in SFINCS}\nOf the equations implemented in SFINCS \\cite{SFINCStechnicalDoc}, the only two we need to modify are the kinetic equation\n\\begin{multline} \nR\\left(f_{1}, \\Phi_1\\right) = \nK \\left\\{\\theta\\right\\} \\frac{\\p f}{\\p \\theta} + K \\left\\{\\zeta\\right\\} \\frac{\\p f}{\\p \\zeta} + \nK \\left\\{x\\right\\} \\frac{\\p f}{\\p x} + K \\left\\{\\xi\\right\\} \\frac{\\p f}{\\p \\xi} + \n\\textcolor{Goldenrod}{K \\left\\{\\psi\\right\\} \\frac{\\p f_{M}}{\\p \\psi}} + \\\\ \n- C \\left\\{f\\right\\} - S_{1} f_{M} - S_{2} f_{M} x^2 - \\frac{Z e v}{T} x \\xi \\frac{\\left\\langle \\bm{E} \\cdot \\bm{B} \\right\\rangle B}{\\left\\langle B^2 \\right\\rangle} f_M = 0\n\\label{eq:KineticEqSFINCS}\n\\end{multline}\nand the quasineutrality equation\n\\begin{equation}\n\\sum_s Z_s \\int d^3v \\, f_s + \\lambda = 0.\n\\label{eq:QuasineutralityEqSFINCS}\n\\end{equation}\nHere $x = v/v_s = v / \\sqrt{2T/m}$ and $\\xi = v_\\| / v$.\\\\\n\n\\noindent In the implementation we need to rewrite all our equations into SFINCS units, using the following identities:\\\\\n$m = \\hat{m} \\bar{m}$, $n = \\hat{n} \\bar{n}$, $T = \\hat{T} \\bar{T}$, $\\Phi = \\hat{\\Phi} \\bar{\\Phi}$, \n$B = \\hat{B} \\bar{B}$, $B_\\zeta = \\bar{R} \\bar{B} \\hat{B}_\\zeta$, $B_\\theta = \\bar{R} \\bar{B} \\hat{B}_\\theta$, $D = \\bar{B} \\hat{D} / \\bar{R}$, \n$\\bar{v} = \\sqrt{2 \\bar{T} / \\bar{m}}$, $\\alpha = e \\bar{\\Phi} / \\bar{T}$,  $\\Delta = \\bar{m} \\bar{v} / \\left(e \\bar{B} \\bar{R} \\right)$, $\\displaystyle \\frac{d X}{d \\psi} = \\frac{1}{\\hat{\\psi}_a \\bar{R}^2 \\bar{B}} \\frac{d X}{d \\psi_N}$, \n$\\hat{\\psi} = \\psi_N \\hat{\\psi}_a$, $\\displaystyle \\frac{1}{\\hat{\\psi}_a} \\frac{d X}{d \\psi_N} = \\frac{d X}{d \\hat{\\psi}}$ \nand \n$\\displaystyle \\alpha \\cdot \\Delta = \\frac{e \\bar{\\Phi}}{\\bar{T}} \\cdot \\frac{\\bar{m} \\bar{v}}{e \\bar{B} \\bar{R}} = \\frac{2^{1/2} \\bar{m}^{1/2} \\bar{\\Phi}}{\\bar{B} \\bar{R} \\bar{T}^{1/2}}$. \nFurthermore, we note that the kinetic equation is made dimensionless by multiplying with the factor \n\\begin{equation}\n  \\label{eq:DimensionlessFactor}\n  \\frac{\\bar{v}^3}{\\bar{n}} \\frac{\\bar{R}}{\\bar{v}} = \\frac{2 \\bar{T} \\bar{R}}{\\bar{m} \\bar{n}}.\n\\end{equation}\n\n\\subsubsection*{Newton's method}\nIn each iteration step we want to calculate the residual and Jacobian of $R\\left(\\bm{X}\\right) = 0$ with $\\bm{X} = \\left(f_{1}, \\Phi_1\\right)$. \nThe residual is $R$ itself, and the Jacobian is $\\displaystyle R' = \\frac{\\delta R\\left(\\bm{X}\\right)}{\\delta \\bm{X}}$. \nThe state-vector is updated as\n\\begin{equation}\n  \\label{eq:StateVectorUpdate}\n  \\bm{X}_{n+1} = \\bm{X}_{n} - \\frac{R\\left(\\bm{X}_{n}\\right)}{R'\\left(\\bm{X}_{n}\\right)}.\n\\end{equation}\n\n\\newpage\n\\subsection*{Drift-kinetic equation}\nFor the residual $R\\left(f_{1}, \\Phi_1\\right)$ the only term in the kinetic equation we need to modify is the one in yellow in Eq.~\\ref{eq:KineticEqSFINCS}. \nWe replace $f_M \\rightarrow f_0 = f_M \\exp \\left(- q \\Phi_1 / T \\right)$, \nand use that $K \\left\\{\\psi\\right\\} = \\bm{v}_E \\cdot \\na \\psi + \\bm{v}_d \\cdot \\na \\psi = \\bm{v}_{E1} \\cdot \\na \\psi + \\bm{v}_d \\cdot \\na \\psi$\nto write \n\\begin{multline}\nK \\left\\{\\psi\\right\\} \\frac{\\p f_{0}}{\\p \\psi} =  \\exp \\left(- q \\Phi_1 / T \\right) \\frac{\\p f_{M}}{\\p \\psi} \\left(\\bm{v}_{E1} \\cdot \\na \\psi + \\bm{v}_d \\cdot \\na \\psi\\right) = \\\\ = \n\\exp \\left(- \\frac{q \\Phi_1}{T}  \\right) f_{M} \\left[\\frac{1}{n} \\frac{\\p n}{\\p \\psi} + \\frac{q}{T} \\frac{\\p \\Phi_0}{\\p \\psi} + \\left(\\frac{m v^2}{2 T} - \\frac{3}{2} + \\frac{q}{T} \\Phi_1\\right) \\frac{1}{T} \\frac{\\p T}{\\p \\psi}\\right] \n \\left(- \\frac{\\na \\Phi_1 \\times \\bm{b}}{B} \\cdot \\na \\psi + \\bm{v}_d \\cdot \\na \\psi\\right) = \\\\ =\n \\left\\| - \\frac{\\na \\Phi_1 \\times \\bm{b}}{B} \\cdot \\na \\psi = - \\frac{ \\bm{B} \\times \\na \\psi}{B^2} \\cdot  \\na \\Phi_1 = \n \\frac{1}{B^2} D \\left[B_\\theta \\frac{\\p \\Phi_1}{\\p \\zeta} - B_\\zeta \\frac{\\p \\Phi_1}{\\p \\theta}\\right] \\right\\| = \\\\ =\n \\exp \\left(- \\frac{q \\Phi_1}{T}  \\right) f_{M} \\left[\\frac{1}{n} \\frac{\\p n}{\\p \\psi} + \\frac{q}{T} \\frac{\\p \\Phi_0}{\\p \\psi} + \\left(\\frac{m v^2}{2 T} - \\frac{3}{2} + \\frac{q}{T} \\Phi_1\\right) \\frac{1}{T} \\frac{\\p T}{\\p \\psi}\\right] \\cdot \\\\\n \\left(\\frac{1}{B^2} D \\left[B_\\theta \\frac{\\p \\Phi_1}{\\p \\zeta} - B_\\zeta \\frac{\\p \\Phi_1}{\\p \\theta}\\right] + \\bm{v}_d \\cdot \\na \\psi\\right)\n\\label{eq:DKresidualNewTerm1}\n\\end{multline}\n(Here $D = \\na \\psi \\cdot \\na \\theta \\times \\na \\zeta$.)\nWritten like this we explicitly see the places where $\\Phi_1$ appears in $\\displaystyle K \\left\\{\\psi\\right\\} \\frac{\\p f_{0}}{\\p \\psi}$. \nFrom Eq.~\\ref{eq:DKresidualNewTerm1} we obtain the corresponding terms in the Jacobian matrix\n\\begin{multline}\n\\frac{\\delta}{\\delta \\Phi_1} \\left(K \\left\\{\\psi\\right\\} \\frac{\\p f_{0}}{\\p \\psi}\\right) = \\textcolor{orange}{\n- \\frac{q}{T}\n \\exp \\left(- \\frac{q \\Phi_1}{T}  \\right) f_{M} \\left[\\frac{1}{n} \\frac{\\p n}{\\p \\psi} + \\frac{q}{T} \\frac{\\p \\Phi_0}{\\p \\psi} + \\left(\\frac{m v^2}{2 T} - \\frac{3}{2} + \\frac{q}{T} \\Phi_1\\right) \\frac{1}{T} \\frac{\\p T}{\\p \\psi}\\right] \\cdot} \\\\ \\textcolor{orange}{\n \\left(\\frac{1}{B^2} D \\left[B_\\theta \\frac{\\p \\Phi_1}{\\p \\zeta} - B_\\zeta \\frac{\\p \\Phi_1}{\\p \\theta}\\right] + \\bm{v}_d \\cdot \\na \\psi\\right)} \\, + \\\\ + \\,\\textcolor{green}{\n \\exp \\left(- \\frac{q \\Phi_1}{T}  \\right) f_{M} \\frac{q}{T} \\frac{1}{T} \\frac{\\p T}{\\p \\psi} \\left(\\frac{1}{B^2} D \\left[B_\\theta \\frac{\\p \\Phi_1}{\\p \\zeta} - B_\\zeta \\frac{\\p \\Phi_1}{\\p \\theta}\\right] + \\bm{v}_d \\cdot \\na \\psi\\right)} \\, + \\\\ + \\,\n\\textcolor{brown}{\n \\exp \\left(- \\frac{q \\Phi_1}{T}  \\right) f_{M} \\left[\\frac{1}{n} \\frac{\\p n}{\\p \\psi} + \\frac{q}{T} \\frac{\\p \\Phi_0}{\\p \\psi} + \\left(\\frac{m v^2}{2 T} - \\frac{3}{2} + \\frac{q}{T} \\Phi_1\\right) \\frac{1}{T} \\frac{\\p T}{\\p \\psi}\\right] \\cdot} \\\\ \\textcolor{brown}{\n \\left(\\frac{1}{B^2} D \\left[B_\\theta \\frac{\\p }{\\p \\zeta} - B_\\zeta \\frac{\\p }{\\p \\theta}\\right]\\right)}\n\\label{eq:DKJacobianNewTerm1}\n\\end{multline}\n\n\\subsubsection*{Residual}\nMany of the terms involving $\\bm{v}_d \\cdot \\na \\psi$ are almost implemented in SFINCS already except that they now contain the $\\exp \\left(- \\frac{q \\Phi_1}{T}  \\right)$-factor. \nWe therefore rewrite Eq.~\\ref{eq:DKresidualNewTerm1} as \n\\begin{equation}\nK \\left\\{\\psi\\right\\} \\frac{\\p f_{0}}{\\p \\psi} = R_m + R_E\n\\label{eq:DKresidualNewTermSplit}\n\\end{equation}\nwhere\n\\begin{equation}\nR_m = \\exp \\left(- \\frac{q \\Phi_1}{T}  \\right) f_{M} \\left[\\frac{1}{n} \\frac{\\p n}{\\p \\psi} + \\frac{q}{T} \\frac{\\p \\Phi_0}{\\p \\psi} + \\left(\\frac{m v^2}{2 T} - \\frac{3}{2} + \\frac{q}{T} \\Phi_1\\right) \\frac{1}{T} \\frac{\\p T}{\\p \\psi}\\right] \\bm{v}_d \\cdot \\na \\psi\n\\label{eq:DKresidualNewTermRm}\n\\end{equation}\nand \n\\begin{equation}\nR_E = \\exp \\left(- \\frac{q \\Phi_1}{T}  \\right) f_{M} \\left[\\frac{1}{n} \\frac{\\p n}{\\p \\psi} + \\frac{q}{T} \\frac{\\p \\Phi_0}{\\p \\psi} + \\left(\\frac{m v^2}{2 T} - \\frac{3}{2} + \\frac{q}{T} \\Phi_1\\right) \\frac{1}{T} \\frac{\\p T}{\\p \\psi}\\right] \\frac{1}{B^2} D \\left[B_\\theta \\frac{\\p \\Phi_1}{\\p \\zeta} - B_\\zeta \\frac{\\p \\Phi_1}{\\p \\theta}\\right].\n\\label{eq:DKresidualNewTermRE}\n\\end{equation}\n\n\\paragraph*{$\\bm{R_m}$}\n$R_m$ will be implemented in evaluateResidual.F90. We write the term as \n\\begin{multline}\nR_m = \\exp \\left(- \\frac{q \\Phi_1}{T}  \\right) f_{M} \\left[\\frac{1}{n} \\frac{\\p n}{\\p \\psi} + \\frac{q}{T} \\frac{\\p \\Phi_0}{\\p \\psi} + \\left(x^2 - \\frac{3}{2}\\right) \\frac{1}{T} \\frac{\\p T}{\\p \\psi}\\right] \\bm{v}_d \\cdot \\na \\psi + \\\\ +  \\textcolor{red}{\n  \\exp \\left(- \\frac{q \\Phi_1}{T}  \\right) f_{M} \\frac{q}{T} \\Phi_1 \\frac{1}{T} \\frac{\\p T}{\\p \\psi} \\bm{v}_d \\cdot \\na \\psi }.\n\\label{eq:DKresidualNewTermRm2}\n\\end{multline}\nNote that the first term in Eq.~\\ref{eq:DKresidualNewTermRm2} can only be implemented in evaluateResidual.F90, since it is not of the form $L\\left[\\Phi_1\\right]$ where $L\\left[\\right]$ is a linear operator.\\\\\nThe first term in Eq.~\\ref{eq:DKresidualNewTermRm2} is already implemented in evaluateResidual.F90 except for the factor \n\\[\n\\exp \\left(- \\frac{q \\Phi_1}{T}  \\right) = \\exp \\left(- \\frac{Z \\alpha \\hat{\\Phi}_1}{\\hat{T}}  \\right)\n\\]\nwhich has to be added.\\\\\nThe second term in Eq.~\\ref{eq:DKresidualNewTermRm2} we rewrite in SFINCS units (also considering the factor Eq.~\\ref{eq:DimensionlessFactor}) as\n\\begin{multline}\n\\textcolor{red}{\n\\left(\\exp \\left(- \\frac{q \\Phi_1}{T}  \\right) f_{M} \\frac{q}{T} \\Phi_1 \\frac{1}{T} \\frac{\\p T}{\\p \\psi} \\bm{v}_d \\cdot \\na \\psi\\right)_{\\mathrm{SFINCS}} = } \\\\ \\textcolor{red}{ =\n\\frac{\\alpha \\Delta}{3 \\pi^{3/2}} \\frac{\\hat{n} \\hat{m}^{3/2} \\hat{D}}{\\hat{T}^{5/2} \\hat{B}^3 } \\hat{\\Phi}_1 \\frac{\\p \\hat{T}}{\\p \\hat{\\psi}}\nx^2 \\left(P_2\\left(\\xi\\right) + 2 P_0\\right)\n\\exp\\left(-x^2\\right) \\exp \\left(- \\frac{Z \\alpha \\hat{\\Phi}_1}{\\hat{T}}\\right) \\left[\\hat{B}_{\\theta} \\frac{\\p \\hat{B}}{\\p \\zeta} - \\hat{B}_{\\zeta} \\frac{\\p \\hat{B}}{\\p \\theta}\\right]. \n}\n\\label{eq:Rmterm2}\n\\end{multline}\nThe first term in Eq.~\\ref{eq:DKresidualNewTermRm2} becomes\n\\begin{multline}\n\\left(\\exp \\left(- \\frac{q \\Phi_1}{T}  \\right) f_{M} \\left[\\frac{1}{n} \\frac{\\p n}{\\p \\psi} + \\frac{q}{T} \\frac{\\p \\Phi_0}{\\p \\psi} + \\left(x^2 - \\frac{3}{2}\\right) \\frac{1}{T} \\frac{\\p T}{\\p \\psi}\\right] \\bm{v}_d \\cdot \\na \\psi \\right)_{\\mathrm{SFINCS}} = \\\\ = \\frac{1}{Z}\n\\frac{\\Delta}{3 \\pi^{3/2}} \\frac{\\hat{n} \\hat{m}^{3/2} \\hat{D}}{\\hat{T}^{1/2} \\hat{B}^3 }\nx^2 \\left(P_2\\left(\\xi\\right) + 2 P_0\\right)\n\\exp\\left(-x^2\\right) \\exp \\left(- \\frac{Z \\alpha \\hat{\\Phi}_1}{\\hat{T}}\\right) \\left[\\hat{B}_{\\theta} \\frac{\\p \\hat{B}}{\\p \\zeta} - \\hat{B}_{\\zeta} \\frac{\\p \\hat{B}}{\\p \\theta}\\right] \\cdot \\\\ \\cdot\n\\left[\\frac{1}{\\hat{n}} \\frac{\\p \\hat{n}}{\\p \\hat{\\psi}} + \\frac{Z \\alpha}{\\hat{T}} \\frac{\\p \\hat{\\Phi}_0}{\\p \\hat{\\psi}} + \\left(x^2 - \\frac{3}{2}\\right) \\frac{1}{\\hat{T}} \\frac{\\p \\hat{T}}{\\p \\hat{\\psi}}\\right].\n\\label{eq:Rmterm1}\n\\end{multline}\n\n\n\\paragraph*{$\\bm{R_E}$}\n$R_E$ we will instead implement in populateMatrix.F90. We write the term as \n\\begin{multline}\nR_E = \\textcolor{blue}{\n\\exp \\left(- \\frac{q \\Phi_1}{T}  \\right) f_{M} \\left[\\frac{1}{n} \\frac{\\p n}{\\p \\psi}  + \\left(x^2 - \\frac{3}{2} \\right) \\frac{1}{T} \\frac{\\p T}{\\p \\psi}\\right] \\frac{1}{B^2} D \\left[B_\\theta \\frac{\\p }{\\p \\zeta} - B_\\zeta \\frac{\\p }{\\p \\theta}\\right] \\Phi_1} + \\\\ +\n\\textcolor{magenta}{\n\\exp \\left(- \\frac{q \\Phi_1}{T}  \\right) f_{M} \\frac{q}{T} \\frac{\\p \\Phi_0}{\\p \\psi} \\frac{1}{B^2} D \\left[B_\\theta \\frac{\\p }{\\p \\zeta} - B_\\zeta \\frac{\\p }{\\p \\theta}\\right]\\Phi_1 } + \\\\ +\n \\textcolor{cyan}{\n \\exp \\left(- \\frac{q \\Phi_1}{T}  \\right) f_{M} \\frac{q}{T} \\Phi_1 \\frac{1}{T} \\frac{\\p T}{\\p \\psi} \\frac{1}{B^2} D \\left[B_\\theta \\frac{\\p }{\\p \\zeta} - B_\\zeta \\frac{\\p }{\\p \\theta}\\right] \\Phi_1}.\n\\label{eq:DKresidualNewTermRE2}\n\\end{multline}\nNote that in the code when evaluating the residual, the matrix added in populateMatrix.F90 is multiplied by the state-vector in evaluateResidual.F90 and therefore the rightmost $\\Phi_1$ should not be added inside populateMatrix.F90.\\\\\nThe first term in Eq.~\\ref{eq:DKresidualNewTermRE2} is already implemented in populateMatrix.F90 except for the factor \n\\[\n\\exp \\left(- \\frac{q \\Phi_1}{T}  \\right) = \\exp \\left(- \\frac{Z \\alpha \\hat{\\Phi}_1}{\\hat{T}}  \\right)\n\\]\nwhich has to be added.\\\\\nThe second term in Eq.~\\ref{eq:DKresidualNewTermRE2} we rewrite in SFINCS units (also considering the factor Eq.~\\ref{eq:DimensionlessFactor}) as\n\\begin{multline}\n\\textcolor{magenta}{\n\\left(\\exp \\left(- \\frac{q \\Phi_1}{T}  \\right) f_{M} \\frac{q}{T} \\frac{\\p \\Phi_0}{\\p \\psi} \\frac{1}{B^2} D \\left[B_\\theta \\frac{\\p \\Phi_1}{\\p \\zeta} - B_\\zeta \\frac{\\p \\Phi_1}{\\p \\theta}\\right] \\right)_{\\mathrm{SFINCS}} } = \\\\ = \\textcolor{magenta}{\n\\frac{Z \\alpha^2 \\Delta}{2 \\pi^{3/2}} \\frac{\\hat{n} \\hat{m}^{3/2} \\hat{D}}{\\hat{T}^{5/2} \\hat{B}^2 } \\frac{\\p \\hat{\\Phi}_0}{\\p \\hat{\\psi}} \n\\exp\\left(-x^2\\right) \\exp \\left(- \\frac{Z \\alpha \\hat{\\Phi}_1}{\\hat{T}}\\right) \\left[\\hat{B}_{\\theta} \\frac{\\p}{\\p \\zeta} - \\hat{B}_{\\zeta} \\frac{\\p}{\\p \\theta}\\right] \\hat{\\Phi}_1.\n}\n\\label{eq:REterm2}\n\\end{multline}\nThe third term in Eq.~\\ref{eq:DKresidualNewTermRE2} we rewrite in SFINCS units (also considering the factor Eq.~\\ref{eq:DimensionlessFactor}) as\n\\begin{multline}\n\\textcolor{cyan}{\n\\left(\\exp \\left(- \\frac{q \\Phi_1}{T}  \\right) f_{M} \\frac{q}{T} \\Phi_1 \\frac{1}{T} \\frac{\\p T}{\\p \\psi} \\frac{1}{B^2} D \\left[B_\\theta \\frac{\\p \\Phi_1}{\\p \\zeta} - B_\\zeta \\frac{\\p \\Phi_1}{\\p \\theta}\\right]\\right)_{\\mathrm{SFINCS}}} = \\\\ = \\textcolor{cyan}{\n\\frac{Z \\alpha^2 \\Delta}{2 \\pi^{3/2}} \\frac{\\hat{n} \\hat{m}^{3/2} \\hat{D}}{\\hat{T}^{7/2} \\hat{B}^2 } \\frac{\\p \\hat{T}}{\\p \\hat{\\psi}} \\hat{\\Phi}_1\n\\exp\\left(-x^2\\right) \\exp \\left(- \\frac{Z \\alpha \\hat{\\Phi}_1}{\\hat{T}}\\right) \\left[\\hat{B}_{\\theta} \\frac{\\p}{\\p \\zeta} - \\hat{B}_{\\zeta} \\frac{\\p}{\\p \\theta}\\right] \\hat{\\Phi}_1.\n}\n\\label{eq:REterm3}\n\\end{multline}\nThe first term in Eq.~\\ref{eq:DKresidualNewTermRE2} in SFINCS units (also considering the factor Eq.~\\ref{eq:DimensionlessFactor}) is \n\\begin{multline}\n\\textcolor{blue}{ \\left(\n\\exp \\left(- \\frac{q \\Phi_1}{T}  \\right) f_{M} \\left[\\frac{1}{n} \\frac{\\p n}{\\p \\psi}  + \\left(x^2 - \\frac{3}{2} \\right) \\frac{1}{T} \\frac{\\p T}{\\p \\psi}\\right] \\frac{1}{B^2} D \\left[B_\\theta \\frac{\\p }{\\p \\zeta} - B_\\zeta \\frac{\\p }{\\p \\theta}\\right] \\Phi_1\\right)_{\\mathrm{SFINCS}} } = \\\\ = \n\\textcolor{blue}{\n\\frac{\\alpha \\Delta}{2 \\pi^{3/2}} \\frac{\\hat{n} \\hat{m}^{3/2} \\hat{D}}{\\hat{T}^{3/2} \\hat{B}^2 }  \\left[\\frac{1}{\\hat{n}} \\frac{\\p \\hat{n}}{\\p \\hat{\\psi}}  + \\left(x^2 - \\frac{3}{2} \\right) \\frac{1}{\\hat{T}} \\frac{\\p \\hat{T}}{\\p \\hat{\\psi}}\\right]\n\\exp\\left(-x^2\\right) \\exp \\left(- \\frac{Z \\alpha \\hat{\\Phi}_1}{\\hat{T}}\\right) \\left[\\hat{B}_{\\theta} \\frac{\\p}{\\p \\zeta} - \\hat{B}_{\\zeta} \\frac{\\p}{\\p \\theta}\\right] \\hat{\\Phi}_1.\n}\n\\label{eq:REterm1}\n\\end{multline}\n\n\\paragraph*{\\textbf{Files to change:}}\n\\begin{verbatim}\nevaluateResidual.F90\npopulateMatrix.F90\n\\end{verbatim}\n\n\n\\subsubsection*{Jacobian}\nThe Jacobian terms will be implemented in populateMatrix.F90. \nIn the code we use SFINCS units, and the Jacobian is calculated from taking the derivative of the residual in SFINCS units with respect to the state-vector in SFINCS units (also considering the factor Eq.~\\ref{eq:DimensionlessFactor}). This implies that what we are calculating here is \n\\[\n\\frac{\\delta}{\\delta \\hat{\\Phi}_1} \\left(\\hat{R}_m + \\hat{R}_E\\right),\n\\]\nwhere $\\hat{R}_m$ and $\\hat{R}_E$ are how the components of the residual are written in SFINCS. \\\\\nWe see that the \\textcolor{brown}{last term} in the Jacobian in Eq.~\\ref{eq:DKJacobianNewTerm1} corresponds to $R_E$ in Eq.~ \\ref{eq:DKresidualNewTermRE} (since the rightmost $\\Phi_1$ in the residual is not implemented in populateMatrix.F90), \nso this term is already implemented by the residual.\\\\\n%%\\remark{Is there no difference implementationwise, when $\\Phi_1$ disappears in the space derivative?}\n\n\\noindent The other two terms should only be added when 'whichMatrix==0' or 'whichMatrix==1'. \nThe \\textcolor{orange}{first term} in the Jacobian is the residual multiplied by $- q / T$. However, since the exponential is \n$ \\displaystyle\n\\exp \\left(- \\frac{q \\Phi_1}{T}  \\right) = \\exp \\left(- \\frac{Z \\alpha \\hat{\\Phi}_1}{\\hat{T}}  \\right), \n$\nin SFINCS the term will be implemented as \n\\begin{equation}\n  \\label{eq:JacobianFirstTerm1}\n  \\textcolor{orange}{- \\frac{Z \\alpha}{\\hat{T}}  \\left(\\hat{R}_m + \\hat{R}_E\\right)}.\n\\end{equation}\n\n\\noindent The \\textcolor{green}{second term} in the Jacobian can be written as \n\\begin{multline}\n  \\label{eq:JacobianSecondTerm1}\n  \\textcolor{green}{\n \\exp \\left(- \\frac{q \\Phi_1}{T}  \\right) f_{M} \\frac{q}{T} \\frac{1}{T} \\frac{\\p T}{\\p \\psi} \\left(\\frac{1}{B^2} D \\left[B_\\theta \\frac{\\p \\Phi_1}{\\p \\zeta} - B_\\zeta \\frac{\\p \\Phi_1}{\\p \\theta}\\right] + \\bm{v}_d \\cdot \\na \\psi\\right)} = \\\\ = \\textcolor{green}{\n\\frac{1}{\\Phi_1}} \\left(\n\\textcolor{cyan}{\n \\exp \\left(- \\frac{q \\Phi_1}{T}  \\right) f_{M} \\frac{q}{T} \\Phi_1 \\frac{1}{T} \\frac{\\p T}{\\p \\psi} \\frac{1}{B^2} D \\left[B_\\theta \\frac{\\p }{\\p \\zeta} - B_\\zeta \\frac{\\p }{\\p \\theta}\\right] \\Phi_1}\n+\n\\textcolor{red}{\n  \\exp \\left(- \\frac{q \\Phi_1}{T}  \\right) f_{M} \\frac{q}{T} \\Phi_1 \\frac{1}{T} \\frac{\\p T}{\\p \\psi} \\bm{v}_d \\cdot \\na \\psi }\n\\right),\n\\end{multline}\nwhere the two terms inside the brackets have already been implemented in $R_E$ and $R_m$ respectively. Consequently, to obtain this term we sum these two terms written in code units, and multiply by $1 / \\hat{\\Phi}_1$.\\\\\nAlthough the \\textcolor{orange}{first term} and the \\textcolor{green}{second term} of the Jacobian consist of terms available in other terms, we need to rewrite them since we cannot access code in evaluateResidual.F90 from populateMatrix.F90, and also the residual terms in populateMatrix.F90 contain a factor $\\Phi_1$ less which instead is in the state-vector.\n\n\n% \\begin{multline}\n% K \\left\\{\\psi\\right\\} \\frac{\\p f_{M}}{\\p \\psi}  =\n% %%\n%  \\exp \\left(- \\frac{q \\Phi_1}{T}  \\right) f_{M} \\left[\\frac{1}{n} \\frac{\\p n}{\\p \\psi} + \\frac{q}{T} \\frac{\\p \\Phi_0}{\\p \\psi} + \\left(\\frac{m v^2}{2 T} - \\frac{3}{2} + \\frac{q}{T} \\Phi_1\\right) \\frac{1}{T} \\frac{\\p T}{\\p \\psi}\\right]  \\bm{v}_d \\cdot \\na \\psi \\, + \\\\ + \\,\n%  \\exp \\left(- \\frac{q \\Phi_1}{T}  \\right) f_{M} \\left[\\frac{1}{n} \\frac{\\p n}{\\p \\psi} + \\frac{q}{T} \\frac{\\p \\Phi_0}{\\p \\psi} + \\left(\\frac{m v^2}{2 T} - \\frac{3}{2} + \\frac{q}{T} \\Phi_1\\right) \\frac{1}{T} \\frac{\\p T}{\\p \\psi}\\right] \\frac{1}{B^2} D \\left[B_\\theta \\frac{\\p \\Phi_1}{\\p \\zeta} - B_\\zeta \\frac{\\p \\Phi_1}{\\p \\theta}\\right] = \\\\ = \n%  %%\n%  \\exp \\left(- \\frac{q \\Phi_1}{T}  \\right) f_{M} \\left[\\frac{1}{n} \\frac{\\p n}{\\p \\psi} + \\frac{q}{T} \\frac{\\p \\Phi_0}{\\p \\psi} + \\left(\\frac{m v^2}{2 T} - \\frac{3}{2} \\right) \\frac{1}{T} \\frac{\\p T}{\\p \\psi}\\right]  \\bm{v}_d \\cdot \\na \\psi \\, + \\\\ + \\,\n%  \\textcolor{blue}{\n%  \\exp \\left(- \\frac{q \\Phi_1}{T}  \\right) f_{M} \\left[\\frac{1}{n} \\frac{\\p n}{\\p \\psi}  + \\left(\\frac{m v^2}{2 T} - \\frac{3}{2} \\right) \\frac{1}{T} \\frac{\\p T}{\\p \\psi}\\right] \\frac{1}{B^2} D \\left[B_\\theta \\frac{\\p \\Phi_1}{\\p \\zeta} - B_\\zeta \\frac{\\p \\Phi_1}{\\p \\theta}\\right]} \\, + \\\\ + \\, \n%  \\textcolor{red}{\n%   \\exp \\left(- \\frac{q \\Phi_1}{T}  \\right) f_{M} \\frac{q}{T} \\Phi_1 \\frac{1}{T} \\frac{\\p T}{\\p \\psi} \\bm{v}_d \\cdot \\na \\psi } \\, + \\\\ + \\,\n%   \\textcolor{magenta}{\n%   \\exp \\left(- \\frac{q \\Phi_1}{T}  \\right) f_{M} \\frac{q}{T} \\frac{\\p \\Phi_0}{\\p \\psi} \\frac{1}{B^2} D \\left[B_\\theta \\frac{\\p \\Phi_1}{\\p \\zeta} - B_\\zeta \\frac{\\p \\Phi_1}{\\p \\theta}\\right] } \\, + \\\\ + \\,\n%   \\textcolor{cyan}{\n%   \\exp \\left(- \\frac{q \\Phi_1}{T}  \\right) f_{M} \\frac{q}{T} \\Phi_1 \\frac{1}{T} \\frac{\\p T}{\\p \\psi} \\frac{1}{B^2} D \\left[B_\\theta \\frac{\\p \\Phi_1}{\\p \\zeta} - B_\\zeta \\frac{\\p \\Phi_1}{\\p \\theta}\\right] }\n% \\label{eq:DKresidualNewTerm2}\n% \\end{multline}\n\n\\paragraph*{\\textbf{Files to change:}}\n\\begin{verbatim}\npopulateMatrix.F90\n\\end{verbatim}\n\n\n\n\\subsubsection*{Additional implementation related to the kinetic equation}\nBesides implementing the above terms, we need to remove the former term in SFINCS corresponding to $\\displaystyle \\frac{Z e}{T} f_M v_\\| \\na_\\| \\Phi_1$. \\\\\n\\\\\nWe will remove the \\textbf{nonlinear} switch from the code, since all terms related to $\\Phi_1$ are now nonlinear. \nThe \\textbf{nonlinear} switch will be incorporated into the \\textbf{includePhi1} switch.\\\\\n\\\\\nWe will replace the \\textbf{includeRadialExBDrive} switch with the \\textbf{includePhi1inKineticEquation} switch which is \\textbf{true} by default. \nThis new switched can be set to \\textbf{false} if one only wants to include $\\Phi_1$ in the quasi-neutrality equation.\n\n\\paragraph*{\\textbf{Files to change:}}\n\\begin{verbatim}\nglobalVariables.F90\npopulateMatrix.F90\npreallocateMatrix.F90\nreadInput.F90\nsfincs.F90\nsolver.F90\nvalidateInput.F90\n\\end{verbatim}\n\n\n\n\n\\newpage\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\newpage\n\\subsection*{Quasi-neutrality equation}\nIn EUTERPE $\\Phi_1$ is calculated from quasi-neutrality by expanding the exponential, assuming adiabatic electrons and neglecting the impurities.\nHowever, this is not a generic quasi-neutrality equation and in SFINCS we can easily implement the full equation. \nTo be able to compare to results from EUTERPE we will allow for both possibilities in the code, and implement an adiabatic species. \nThe option \\textbf{quasineutralityOption = 1} corresponds to the full quasi-neutrality equation and is the default, \nwhereas \\textbf{quasineutralityOption = 2} corresponds to the EUTERPE equations.\n\n\\subsubsection*{Adiabatic species}\nWe will allow for the possibility to run SFINCS with an adiabatic species. \nThe following input parameters will be introduced (with their default values in brackets) in the \\textbf{speciesParameters} namelist:\n\\begin{verbatim}\nlogical :: withAdiabatic  (.false.)\nPetscScalar :: adiabaticZ  (-1)\nPetscScalar :: adiabaticMHat  (5.446170214d-4)\nPetscScalar :: adiabaticNHat  (1.0)\nPetscScalar :: adiabaticTHat  (1.0)\n\\end{verbatim}\nNote that the \nadiabatic species will only enter into the quasi-neutrality equation, \nwe neglect its collisional impact on the kinetic species (the adiabatic species will typically be electrons, and the effect of ion-electron collisions is small compared to ion-ion collisions). \n\n\\paragraph*{\\textbf{Files to change:}}\n\\begin{verbatim}\nglobalVariables.F90\npopulateMatrix.F90\nreadInput.F90\nsfincs.F90\nvalidateInput.F90\nwriteHDF5Output.F90\n\\end{verbatim}\n\n\\subsubsection*{Full quasi-neutrality equation, quasineutralityOption = 1}\n\nFirstly, we need to make sure that the input densities fulfill quasi-neutrality (also considering the adiabatic species if it is used):\n\\begin{equation}\n  \\label{eq:QuasiNeutralityInputFull}\n  \\sum_s Z_s \\hat{n}_s = 0.\n\\end{equation}\n%\nThe densities can be written\n\\begin{equation}\nn_s = n_{s 0} \\left(\\psi\\right) \\, \\exp \\left(- q_s \\Phi_1 / T_s \\right) + n_{s 1},\n\\label{eq:DensityParts}\n\\end{equation}\nand the quasi-neutrality equation is \n\\begin{equation}\n\\sum_s Z_s n_s = 0.\n\\label{eq:Quasineutrality}\n\\end{equation}\nFor an adiabatic species $a$\n\\[\nn_{a 1} = 0.\n\\]\nThe velocity integration in SFINCS is done in $\\left(x, \\xi\\right) = \\left(v / v_s, v_\\| / v\\right)$, and \n\\begin{equation}\n\\int d^3 v = 2 \\pi v_{s}^3 \\int_{0}^{\\infty} dx\\, x^2 \\int_{-1}^{1} d\\xi\n\\label{eq:VelocityIntegration}\n\\end{equation}\nwhere $v_{s} = \\sqrt{2 T_s / m_s}$. \nSince \n\\begin{equation}\n  \\label{eq:ns1Int}\n  n_{s 1} = \\int d^3 v \\, f_{s 1},\n\\end{equation}\nwe can rewrite quasi-neutrality in form of its contribution to the residual of the full linear system as \n\\begin{equation}\nR_{QN}\\left(f_{1}, \\Phi_1\\right) = \\sum_s Z_s n_{s0} \\exp\\left(- \\frac{Z_s e \\Phi_1}{T_s}\\right) + 2\\pi \\sum_{s \\setminus a} v_s^3 Z_s \\int_0^{\\infty} dx \\, x^2 \\int_{-1}^1 d\\xi \\, f_{s 1} = 0\n\\label{eq:Quasineutrality}\n\\end{equation}\n(note that the adiabatic species is excluded in the second summation).\\\\\n\n\\noindent In SFINCS we add a Lagrange multiplier $\\lambda$, divide Eq.~\\ref{eq:Quasineutrality} by $\\bar{n}$, and use $n = \\hat{n} \\bar{n}$, $\\bar{v} = \\sqrt{2 \\bar{T} / \\bar{m}}$, $v_s / \\bar{v} = \\sqrt{\\hat{T}_s / \\hat{m}_s}$, $f_s = \\bar{n} \\hat{f}_s / \\bar{v}^3$, $ \\displaystyle\n\\exp \\left(- \\frac{q_s \\Phi_1}{T_s}  \\right) = \\exp \\left(- \\frac{Z_s \\alpha \\hat{\\Phi}_1}{\\hat{T}_s}  \\right) \n$, to write \n\\begin{multline}\n\\hat{R}_{QN}\\left(\\hat{f}_{1}, \\hat{\\Phi}_1, \\lambda\\right) = \\textcolor{JungleGreen}{\n\\sum_s Z_s \\hat{n}_{s0} \\exp \\left(- \\frac{Z_s \\alpha \\hat{\\Phi}_1}{\\hat{T}_s}  \\right)} + \\\\ + \n\\textcolor{MidnightBlue}{\n2\\pi \\sum_{s \\setminus a} Z_s \\left(\\frac{\\hat{T}_s}{\\hat{m}_s}\\right)^{3/2} \\int_0^{\\infty} dx \\, x^2 \\int_{-1}^1 d\\xi \\, \\hat{f}_{s 1} \\, + \\, \\lambda } = 0.\n\\label{eq:QuasineutralitySFINCS}\n\\end{multline}\nThe first term in Eq.~\\ref{eq:QuasineutralitySFINCS} must be implemented in evaluateResidual.F90 because it does not include a linear operation on $\\hat{\\Phi}_1$. \nThe other terms will be implemented in populateMatrix.F90.\\\\\n\n\\noindent When implementing the Jacobian terms, we note that \n\\begin{equation}\n  \\label{eq:QNJacobianf1}\n\\textcolor{MidnightBlue}{\n  \\frac{\\delta \\hat{R}_{QN}}{\\delta \\hat{f}_{s 1}} = 2\\pi Z_s \\left(\\frac{\\hat{T}_s}{\\hat{m}_s}\\right)^{3/2} \\int_0^{\\infty} dx \\, x^2 \\int_{-1}^1 d\\xi},\n\\end{equation}\n\\begin{equation}\n  \\label{eq:QNJacobianLambda}\n\\textcolor{MidnightBlue}{\n  \\frac{\\delta \\hat{R}_{QN}}{\\delta \\lambda} = 1},\n\\end{equation}\nwhich means that these two terms are the same as the corresponding terms in the residual and are thus implemented in populateMatrix.F90.\nMoreover,\n\\begin{equation}\n  \\label{eq:QNJacobianPhi1}\n\\textcolor{JungleGreen}{\n  \\frac{\\delta \\hat{R}_{QN}}{\\delta \\hat{\\Phi}_1} = -\n\\sum_s  \\frac{Z_s^2 \\alpha}{\\hat{T}_s} \\hat{n}_{s0} \\exp \\left(- \\frac{Z_s \\alpha \\hat{\\Phi}_1}{\\hat{T}_s}  \\right)}\n\\end{equation}\nwill also be implemented in populateMatrix.F90 when 'whichMatrix==0' or 'whichMatrix==1'. \n\\\\\n\n\\noindent Note that, since the distribution function in SFINCS is stored as an expansion in Legendre polynomials in $\\xi$\n\\[\n\\hat{f}_{s 1}\\left(\\theta, \\zeta, x, \\xi\\right) = \\sum_{l=0}^{N_l} \\hat{f}_{s 1}^{\\left(l\\right)}\\left(\\theta, \\zeta, x\\right) P_l \\left(\\xi\\right),\n\\]\nand using that\n\\[\n\\int_{-1}^1 P_m\\left(\\xi\\right) P_n\\left(\\xi\\right) = \\frac{2}{2n + 1} \\delta_{m,n}\n\\]\nthe integration over $\\xi$ in Eq.~\\ref{eq:QuasineutralitySFINCS} becomes\n\\begin{equation}\n  \\label{eq:xiIntegration}\n  \\int_{-1}^1 d\\xi \\, f_{s 1} = \\int_{-1}^1 d\\xi \\, \\left(\\sum_{l=0}^{N_l} \\hat{f}_{s 1}^{\\left(l\\right)}\\left(\\theta, \\zeta, x\\right) P_l \\left(\\xi\\right)\\right) \\cdot P_0 \\left(\\xi\\right) = 2 \\cdot  \\hat{f}_{s 1}^{\\left(0\\right)}\\left(\\theta, \\zeta, x\\right).\n\\end{equation}\n\n\\paragraph*{\\textbf{Files to change:}}\n\\begin{verbatim}\nevaluateResidual.F90\npopulateMatrix.F90\nvalidateInput.F90\n\\end{verbatim}\n\n\\subsubsection*{EUTERPE quasi-neutrality equation, quasineutralityOption = 2}\nFor the EUTERPE equations, the code must be run with \nan adiabatic species and only one kinetic species (the first) is considered in the quasi-neutrality equation. \nWe need to make sure that the input densities fulfill quasi-neutrality:\n\\begin{equation}\n  \\label{eq:QuasiNeutralityInputFull}\n   Z_i \\hat{n}_{i} + Z_a \\hat{n}_{a} = 0\n\\end{equation}\n(here species $i$ would be the first kinetic species and $a$ the adiabatic).\\\\\nAgain we use \n\\begin{equation}\nn_s = n_{s 0} \\left(\\psi\\right) \\, \\exp \\left(- q_s \\Phi_1 / T_s \\right) + n_{s 1},\n\\label{eq:DensityParts2}\n\\end{equation}\n\\begin{equation}\n\\sum_s Z_s n_s = 0,\n\\label{eq:Quasineutrality2}\n\\end{equation}\nbut here we Taylor expand the exponential to $1^{\\mathrm{st}}$ order and write\n\\begin{multline}\n\\label{eq:QuasineutralityExpanded}\n%\\Rightarrow \\;\\;\\; \n0 \\simeq \\sum_s Z_s \\left[n_{s 0} \\left(1 - q_s \\Phi_1 / T_s \\right) + n_{s 1}\\right] \\;\\;\\; \\Leftrightarrow \\\\\n\\sum_s Z_s \\left[n_{s 0} + n_{s 1}\\right] = \\sum_s \\frac{Z_s^2 e}{T_s} \\Phi_1 n_{s 0} .\n\\end{multline}\n%Since $n_{s 0} \\left(\\psi\\right)$ is obtained by integrating the Maxwellian $f_{M s}$ over velocity space we must have \nFrom the condition of quasi-neutral input we know that\n\\[\n\\sum_s Z_s n_{s 0} = 0,\n\\]\nwhich yields \n\\begin{equation}\n\\sum_s Z_s n_{s 1} - \\Phi_1 \\sum_s \\frac{Z_s^2 e}{T_s} n_{s 0}  = 0.\n\\label{eq:Quasineutrality2}\n\\end{equation}\nWith kinetic ions, adiabatic electrons ($n_{a 1} = 0$) and neglecting other ion species we obtain \n\\begin{equation}\n\\Phi_1 = \\frac{T_a}{Z_a^2 e} \\left[\\frac{Z_i^2 T_a}{Z_a^2 T_i} n_{i 0} + n_{a 0}\\right]^{-1} Z_i n_{i 1}.\n\\label{eq:Phi1}\n\\end{equation}\n%\n%\\subsection*{Implementation in SFINCS}\n%For a first benchmark, we want to implement the same equations as EUTERPE in SFINCS. \\\\\n%\\remark{This is not a very generic quasi-neutrality equation so it is possible that we might want to change it in SFINCS later.} \\\\\n%In the code we add an adiabatic species which only enters into the quasi-neutrality equation, and neglect its collisional impact on the kinetic species (the effect of ion-electron collisions is small compared to ion-ion collisions). \n%Moreover, we will only consider the first of the kinetic species in quasi-neutrality and neglect the rest. \n%This is implemented by modifying the LHS of the row corresponding to quasi-neutrality in the block-matrix structure of Matt's ISHW poster, adding the adiabatic term to the $\\Phi_1$-column and removing all kinetic species except the first. \\\\\n% \\remark{It feels a bit weird to remove species from quasi-neutrality, even if the impurity density is small. Does this mean that we should removed the check that the input densities are quasi-neutral and instead check that $n_{i 0} \\left(\\psi\\right) = n_{e 0} \\left(\\psi\\right)$ in the input?}\\\\\nThe equation we will implement in SFINCS is thus \n\\begin{equation}\nZ_i n_{i 1} - \\Phi_1 \\left[ \\frac{Z_i^2 e}{T_i} n_{i 0} + \\frac{Z_a^2 e}{T_a} n_{a 0}\\right] = 0.\n\\label{eq:QuasineutralityIonElectrons}\n\\end{equation}\nWe note that\n\\begin{multline}\nn_s = n_{s 0} \\left(\\psi\\right) \\, \\exp \\left(- q_s \\Phi_1 / T_s \\right) + n_{s 1} = \\int d^3 v f_{Ms} \\exp \\left(- q_s \\Phi_1 / T_s \\right) + \\int d^3 v f_{1 s} = \\\\ = \nd^3 v f_{0 s} + d^3 v f_{1 s}.\n\\label{eq:distributionToDensity}\n\\end{multline}\nThe velocity integration is SFINCS is done in $\\left(x, \\xi\\right) = \\left(v / v_s, v_\\| / v\\right)$, and \n\\begin{equation}\n\\int d^3 v = 2 \\pi v_{s}^3 \\int_{0}^{\\infty} dx\\, x^2 \\int_{-1}^{1} d\\xi\n\\label{eq:VelocityIntegration2}\n\\end{equation}\n(note that $v_{s}^2 = 2 T_s/m_s$ differs from Jose's notation $v_{\\mathrm{th}}^2 = T/m$). \nUsing SFINCS normalizations $n_s = \\bar{n}  \\hat{n}_s$, $T_s = \\bar{T}  \\hat{T}_s$, $v_s / \\bar{v} = \\sqrt{\\hat{T}_s / \\hat{m}_s}$, \n$f_s = \\bar{n} \\hat{f}_s / \\bar{v}^3$, \nwe find \n\\begin{equation}\n\\hat{n}_s = 2 \\pi \\left(\\hat{T}_s / \\hat{m}_s\\right)^{3/2} \\int_{0}^{\\infty} dx\\, x^2 \\int_{-1}^{1} d\\xi \\hat{f}_s.\n\\label{eq:VelocityIntegrationSFINCS}\n\\end{equation}\nAlso using $\\Phi_1 = \\bar{\\Phi} \\hat{\\Phi}_1$ and $\\alpha = e \\bar{\\Phi} / \\bar{T}$ we can write Eq.~\\ref{eq:QuasineutralityIonElectrons} \n\\begin{equation}\nZ_i \\hat{n}_{i 1} - \\alpha \\hat{\\Phi}_1 \\left[ \\frac{Z_i^2}{\\hat{T}_i} \\hat{n}_{i 0} + \\frac{Z_a^2}{\\hat{T}_a} \\hat{n}_{a 0}\\right] = 0\n\\label{eq:QuasineutralityIonElectronsSFINCS}\n\\end{equation}\nand finally obtain the residual \n\\begin{equation}\n\\hat{R}_{QN}^{\\mathrm{EUTERPE}}\\left(\\hat{f}_{i 1}, \\hat{\\Phi}_1, \\lambda\\right) =\n\\left[2 \\pi Z_i \\left(\\hat{T}_i / \\hat{m}_i\\right)^{3/2} \\int_{0}^{\\infty} dx\\, x^2 \\int_{-1}^{1} d\\xi \\hat{f}_{i 1}\\right]\n- \\alpha \\hat{\\Phi}_1 \\left[ \\frac{Z_i^2}{\\hat{T}_i} \\hat{n}_{i 0} + \\frac{Z_a^2}{\\hat{T}_a} \\hat{n}_{a 0}\\right] \\, + \\, \\lambda = 0.\n\\label{eq:QuasineutralityIonElectronsSFINCS2}\n\\end{equation}\n%This is the equation we will implement in the code, but adding a $\\lambda$ to make the system square.\\\\ \n% \\remark{Is the $2\\pi$ factor correct in Eq.~\\ref{eq:QuasineutralityIonElectronsSFINCS2}? It is not in the former implementation of quasi-neutrality, but in that situation it could be divided away.}\nSince the residual has a linear operator dependence on all unknown variables, both the Jacobian and the residual can be implemented in populateMatrix.F90 with the same equations.\n\n\\paragraph*{\\textbf{Files to change:}}\n\\begin{verbatim}\npopulateMatrix.F90\nvalidateInput.F90\n\\end{verbatim}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\newpage\n\n\\subsection*{Additional changes}\nDecide which output fluxes should be possible to obtain, i.e. which combinations of \n\\begin{equation}\n  \\label{eq:OutputFluxes}\n  \\langle \\int d^3 v \\, f \\bm{v} \\cdot \\na X \\rangle,\n\\end{equation}\nshould be possible? \nHere $f$ can be $f_0$, $f_1$ or $f_0 + f_1$. \n$\\bm{v}$ can be $\\bm{v}_E$, $\\bm{v}_m$ or $\\bm{v}_E + \\bm{v}_m$. \n$X$ can be any of the radial coordinates, $r$, $r_N$, $\\psi$ or $\\psi_N$. \\\\\n\n\\noindent Allow for the output fluxes in SI units.\\\\\n\n\\noindent In all output flux quantities the substitution\n\\[\n\\textcolor{red}{\nf_M \\rightarrow f_0 = f_M \\exp \\left(- q \\Phi_1 / T \\right)}\n\\]\nmust be made. \n\\paragraph*{\\textbf{Files to change:}}\n\\begin{verbatim}\ndiagnostics.F90\n\\end{verbatim}\n\n\n\\newpage\n%\\appendix\n\\titleformat{\\section}{\\large\\bfseries}{\\appendixname~\\thesection .}{0.5em}{}\n\n\\begin{appendices}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Check of Matt's former implementation of $\\displaystyle \\frac{Z e}{T} f_M v_\\| \\na_\\| \\Phi_1$}\n\\textbf{This section is only to compare to what has already been implemented in SFINCS, to see that we understand the normalizations.}\\\\\n\\\\\nLooking at Matt's ISHW poster, since $\\Phi_1$ is an unknown this term is in the LHS of the square block matrix system. \nThe term is accessed by ``rowIndex = BLOCK\\_F'' and ``colIndex = BLOCK\\_QN''. \nWe use\n\\[\n\\na_\\| \\Phi_1 = \\bm{b} \\cdot \\na \\Phi_1 = \\frac{1}{B} \\left[ B^{\\theta} \\frac{\\p \\Phi_1}{\\p \\theta} + B^{\\zeta} \\frac{\\p \\Phi_1}{\\p \\zeta} \\right] = \n\\frac{\\bar{\\Phi}}{\\hat{B} \\bar{R}} \\left[ \\hat{B}^{\\theta} \\frac{\\p \\hat{\\Phi}_1}{\\p \\theta} + \\hat{B}^{\\zeta} \\frac{\\p \\hat{\\Phi}_1}{\\p \\zeta} \\right], \n\\]\n\\[\nf_M = n_0\\left(\\psi\\right) \\frac{m^{3/2}}{\\left(2 \\pi T\\right)^{3/2}} \\exp \\left[- \\frac{v^2}{v_{s}^2}\\right] = \n\\hat{n} \\bar{n} \\frac{\\hat{m}^{3/2}}{\\left(2 \\pi \\hat{T}\\right)^{3/2}} \\left(\\frac{\\bar{m}}{\\bar{T}}\\right)^{3/2} \\exp \\left[- x^2\\right],\n\\]\n$v_\\| = v_s x \\xi = v_s x P_1 = x P_1 \\sqrt{2 \\hat{T} / \\hat{m}} \\sqrt{\\bar{T} / \\bar{m}} $ and $x = v / v_s$. \nWith $\\alpha = e \\bar{\\Phi} / \\bar{T}$ we obtain \n\\begin{multline}\n\\frac{Z e}{T} f_M v_\\| \\na_\\| \\Phi_1 = \\frac{Z e}{\\hat{T} \\bar{T}} \\, \\hat{n} \\bar{n} \\frac{\\hat{m}^{3/2}}{\\left(2 \\pi \\hat{T}\\right)^{3/2}} \\left(\\frac{\\bar{m}}{\\bar{T}}\\right)^{3/2} \\exp \\left[- x^2\\right] \\, x P_1 \\sqrt{2 \\hat{T} / \\hat{m}} \\sqrt{\\bar{T} / \\bar{m}} \\, \\frac{\\bar{\\Phi}}{\\hat{B} \\bar{R}} \\left[ \\hat{B}^{\\theta} \\frac{\\p \\hat{\\Phi}_1}{\\p \\theta} + \\hat{B}^{\\zeta} \\frac{\\p \\hat{\\Phi}_1}{\\p \\zeta} \\right] = \\\\ =\n \\frac{Z \\alpha}{2\\pi^{3/2} } x P_1  \\exp \\left[- x^2\\right] \\, \\frac{\\hat{n} \\hat{m}}{\\hat{B} \\hat{T}^2 }  \\, \\frac{\\bar{n} \\bar{m}}{\\bar{R} \\bar{T}} \\left[ \\hat{B}^{\\theta} \\frac{\\p }{\\p \\theta} + \\hat{B}^{\\zeta} \\frac{\\p }{\\p \\zeta} \\right] \\hat{\\Phi}_1.\n\\label{eq:TermNaParallelPhi1}\n\\end{multline}\n\n%\\noindent\\textcolor{red}{\n%Questions:\\\\\n%\\begin{itemize}\n%\t\\item In the code you name a quantity ``dfMdx''. I don't see the reason for doing this since the expression doesn't contain the derivative of the Maxwellian. However, because of the $x$ it will turn out to be the same.\n%\t\\item Looking in the code and comparing to what I get there seems to be a factor $1/2$ discrepancy. Can you see where it is? It seems to be because a factor $2 x$ pops out when taking the derivative of the Maxwellian.\n%\t\\item In the code I can simply neglect the bar-quantities, right?\n%\t\\item Since this is a linear term in the unknowns, I suppose it gives the same contribution to the residual matrix as to the Jacobian matrix. Is it correct understood that when I calculate the residual matrix I will substitute the term as it is, whereas when I calculate the Jacobian matrix I will have to take the derivative with respect to $\\Phi_1$ (in this case when there is no $f_1$ in the term)? E.g. would a $\\Phi_1^2$-term be $\\Phi_1^2$ in the residual but $2 \\Phi_1$ in the Jacobian?\n%\\end{itemize}\n%}\n\n\\noindent In SFINCS the kinetic equation is made dimensionless by multiplying with\n\\[\n\\frac{\\bar{v}^3 \\bar{R}}{\\bar{n} \\bar{v}} = \\frac{2 \\bar{T} \\bar{R}}{\\bar{m} \\bar{n}},\n\\]\nwhich implies that the RHS of Eq.~\\ref{eq:TermNaParallelPhi1} becomes\n\\begin{equation}\n \\frac{Z \\alpha}{\\pi^{3/2} } x P_1  \\exp \\left[- x^2\\right] \\, \\frac{\\hat{n} \\hat{m}}{\\hat{B} \\hat{T}^2 }  \\,  \\left[ \\hat{B}^{\\theta} \\frac{\\p }{\\p \\theta} + \\hat{B}^{\\zeta} \\frac{\\p }{\\p \\zeta} \\right] \\hat{\\Phi}_1\n\\label{eq:TermNaParallelPhi1SFINCS}\n\\end{equation}\nin the implementation.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\\newpage\n% \\section{Temporary page}\n% \\subsection*{Implementation of $\\displaystyle f_0 \\frac{q}{T} \\na \\Phi_0 \\cdot \\bm{v}_{E1}$}\n% \\begin{multline}\n% \\left(f_0 \\frac{q}{T} \\na \\Phi_0 \\cdot \\bm{v}_{E1}\\right)_{\\mathrm{SFINCS}} = \\\\ =\n% \\frac{Z \\alpha^2 \\Delta}{2 \\pi^{3/2}} \\frac{\\hat{n} \\hat{m}^{3/2} \\hat{D}}{\\hat{T}^{5/2} \\hat{B}^2 \\hat{\\psi}_a} \\frac{\\p \\hat{\\Phi}_0}{\\p \\psi_N} \n% \\exp\\left(-x^2\\right) \\exp \\left(- \\frac{Z \\alpha \\hat{\\Phi}_1}{\\hat{T}}\\right) \\left[\\hat{B}_{\\theta} \\frac{\\p}{\\p \\zeta} - \\hat{B}_{\\zeta} \\frac{\\p}{\\p \\theta}\\right] \\hat{\\Phi}_1\n% \\label{eq:RHSphi1term1}\n% \\end{multline}\n\n% \\subsection*{Implementation of $\\displaystyle f_0 \\frac{q}{T} \\Phi_1 \\frac{\\na T}{T} \\cdot \\bm{v}_d$}\n% \\begin{multline}\n% \\left(f_0 \\frac{q}{T} \\Phi_1 \\frac{\\na T}{T} \\cdot \\bm{v}_d\\right)_{\\mathrm{SFINCS}} = \\\\ =\n% \\frac{\\alpha \\Delta}{3 \\pi^{3/2}} \\frac{\\hat{n} \\hat{m}^{3/2} \\hat{D}}{\\hat{T}^{5/2} \\hat{B}^3 \\hat{\\psi}_a} \\hat{\\Phi}_1 \\frac{\\p \\hat{T}}{\\p \\psi_N}\n% x^2 \\left(P_2\\left(\\xi\\right) + 2\\right)\n% \\exp\\left(-x^2\\right) \\exp \\left(- \\frac{Z \\alpha \\hat{\\Phi}_1}{\\hat{T}}\\right) \\left[\\hat{B}_{\\theta} \\frac{\\p \\hat{B}}{\\p \\zeta} - \\hat{B}_{\\zeta} \\frac{\\p \\hat{B}}{\\p \\theta}\\right] \n% \\label{eq:RHSphi1term2}\n% \\end{multline}\n\n% \\subsection*{Implementation of $\\displaystyle f_0 \\frac{q}{T} \\Phi_1 \\frac{\\na T}{T} \\cdot \\bm{v}_{E1}$}\n% \\begin{multline}\n% \\left(f_0 \\frac{q}{T} \\Phi_1 \\frac{\\na T}{T} \\cdot \\bm{v}_{E1}\\right)_{\\mathrm{SFINCS}} = \\\\ =\n% \\frac{Z \\alpha^2 \\Delta}{2 \\pi^{3/2}} \\frac{\\hat{n} \\hat{m}^{3/2} \\hat{D}}{\\hat{T}^{7/2} \\hat{B}^2 \\hat{\\psi}_a} \\frac{\\p \\hat{T}}{\\p \\psi_N} \\hat{\\Phi}_1\n% \\exp\\left(-x^2\\right) \\exp \\left(- \\frac{Z \\alpha \\hat{\\Phi}_1}{\\hat{T}}\\right) \\left[\\hat{B}_{\\theta} \\frac{\\p}{\\p \\zeta} - \\hat{B}_{\\zeta} \\frac{\\p}{\\p \\theta}\\right] \\hat{\\Phi}_1\n% \\label{eq:RHSphi1term3}\n% \\end{multline}\n \\end{appendices}\n \\newpage\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\begin{thebibliography}{99}\n\n\\bibitem{regana} J.~M.~Garc\\'{\\i}a-Rega\\~{n}a, R.~Kleiber, C.~D.~Beidler, Y.~Turkin, H.~Maa{\\ss}berg  \nand P.~Helander, \n\\href{http://dx.doi.org/10.1088/0741-3335/55/7/074008}{\\em Plasma Phys.~Control.~Fusion} {\\bf 55} (2013) 074008.\n\n\\bibitem{reganaArxiv} J.~M.~Garc\\'{\\i}a-Rega\\~{n}a, C.~D.~Beidler, Y.~Turkin, R.~Kleiber, P.~Helander, H.~Maa{\\ss}berg, J. A. Alonso and J. L. Velasco,  \n\\href{http://arxiv.org/abs/1501.03967}{\\em arXiv:1501.03967} (2015).\n\n\\bibitem{landremanSFINCS} Landreman~M, Smith~H~M, Moll\\'en~A and Helander~P 2014\n \\href{http://dx.doi.org/10.1063/1.4870077}{\\em Phys. Plasmas} {\\bf 21} 042503\n \n\\bibitem{SFINCStechnicalDoc} M.~Landreman, {\\em Technical Documentation for version 3 of SFINCS} (2014).\n\n%\\bibitem{simakov} A.~N.~Simakov, P.~Helander,\n%  {\\em Phys. Plasmas} {\\bf 16}, 042503 (2009).\n  \n%\\bibitem{nonAxis} P.~Helander, Theory of plasma confinement in non-axisymmetric magnetic fields (2013).\n\n%\\bibitem{MH} L.~Råde and B.~Westergren, Mathematics Handbook for Science and Engineering, $5^{\\mathrm{th}}$ edition, 2004. %\\vspace{-5mm}\n\n%\\bibitem{Abra} M.~Abramowitz and I.~A.~Stegun, Handbook of Mathematical Functions, $10^{\\mathrm{th}}$ printing, 1972.\n\n\\end{thebibliography}\n\n\\end{document}", "meta": {"hexsha": "57f78f2b379bad7933301160970eacdd40d215ae", "size": 50472, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/Phi1_implementation_2016-01.tex", "max_stars_repo_name": "amollen/sfincs", "max_stars_repo_head_hexsha": "a529954fd36330e1b5c816612943f39829f3542f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2017-10-13T15:15:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:56:20.000Z", "max_issues_repo_path": "doc/Phi1_implementation_2016-01.tex", "max_issues_repo_name": "amollen/sfincs", "max_issues_repo_head_hexsha": "a529954fd36330e1b5c816612943f39829f3542f", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-01-02T09:04:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-28T09:53:21.000Z", "max_forks_repo_path": "doc/Phi1_implementation_2016-01.tex", "max_forks_repo_name": "amollen/sfincs", "max_forks_repo_head_hexsha": "a529954fd36330e1b5c816612943f39829f3542f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2015-03-19T14:30:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T14:37:14.000Z", "avg_line_length": 55.4028540066, "max_line_length": 494, "alphanum_fraction": 0.6347083531, "num_tokens": 20330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.34904287667217504}}
{"text": "A common operational approach that water utilities use to address water quality concerns is flushing, which \r\nis the purging of water from the distribution network via a fire hydrant or blow-off port. \r\nMany utilities flush water mains following maintenance work \r\nor in response to customer complaints. Flushing can remove the sources \r\nof poor water quality (e.g., pipe corrosion, bio-film microorganisms), as well \r\nas loose or suspended material that has accumulated in low-flow portions or \r\ndead-ends of the distribution system. It is a response option that can be undertaken \r\nrelatively quickly after a contamination incident, and it can be made more efficient through \r\nthe careful selection of where to implement flushing activities. This chapter describes \r\nthe \\code{flushing} subcommand in WST that assists in the identification of effective \r\nhydrant locations to flush in order to remove contaminated water and the valves to close \r\nin order to direct the contaminated water towards the hydrants. \r\n\r\nA flowchart representation of the \\code{flushing} subcommand is shown in Figure \\ref{fig:flushing-flowchart}. \r\nThe \\code{flushing} subcommand employs an iterative process that combines contaminant transport, impact assessment \r\nand optimization. The optimization process identifies a set of flushing activities \r\nthat are simulated in the contaminant transport process and evaluated \r\nbased upon the impact assessment process. Since the \\code{flushing} subcommand relies \r\non the \\code{tevasim} and \\code{sim2Impact} subcommands, their required input \r\nis also required for the \\code{flushing} subcommand. In addition, the sensor network \r\ndesign used to detect the contamination incident(s) and the flushing characteristics \r\nare required inputs. The utility network model is defined by a EPANET 2.00.12 INP file, \r\nwhile the rest of the input can be specified in the \\code{flushing} WST configuration file.\r\n\r\n\\begin{figure}[h]\r\n  \\centering\r\n  \\includegraphics[scale=0.75]{graphics/flushing_flowchart.pdf}\r\n  \\caption{Flushing response simulation flowchart.}\r\n  \\label{fig:flushing-flowchart}\r\n\\end{figure}\r\n\r\n\\section{Flushing Formulation}\\label{flushing_formulations}\r\nThe flushing problem formulation can be summarized \r\nas selecting a set of hydrant locations to flush and valves to close \r\nthat minimizes the average impact of all contamination incidents \r\ngiven a set of potential hydrant locations to flush and valves to close. \r\nThe mathematical formulation can be written as follows:\r\n\\begin{align}\r\n\\textrm{  minimize } \\qquad &\\dfrac{1}{A} \\sum_{a \\in {A}} d_{a,\\max} \\label{eqn:flushing} \\\\\r\n\\textrm{subject to } \\qquad &\\sum_{h\\in H}y_{h} \\leq H_{\\max} \\label{eq:flushing_2} \\\\\r\n&\\sum_{v\\in V}y_{v} \\leq V_{\\max} \\label{eq:flushing_3} \\\\  \r\n&y_{h} \\in \\{0,1\\} &&\\forall h\\in H \\label{eq:flushing_4} \\\\\r\n&y_{v} \\in \\{0,1\\} &&\\forall v\\in V \\label{eq:flushing_5}\r\n\\end{align}\r\nwhere $A$ represents a set of contamination incidents, \r\n$d_{a,\\max}$ defines the maximum impact of the contamination incident $a$, \r\n$H$ represents the set of potential hydrant locations,\r\n$y_h$ is a binary variable which is 1 if node $h$ is selected as a flushing location, \r\n$H_{\\max}$ is the maximum number of hydrant locations,\r\n$V$ represents the set of potential valve locations,\r\n$y_v$ is a binary variable which is 1 if node $v$ is selected as a valving location and \r\n$V_{\\max}$ is the maximum number of valve locations. The maximum impact of a contamination\r\nincident, $d_{a,\\max}$, is the total impact across the entire network at the end of the simulation \r\nassuming that the contaminant was not detected by a sensor, and no interventions to reduce \r\nimpacts were implemented. This value is found in the -1 entry of the impact file. \r\n\r\nFor this problem, hydrants are assumed to be located at any user-defined nodes in the network. \r\nIn addition, valves are assumed to be located on any user-defined pipes in the network.  \r\n\r\n\\section{Flushing Solvers}\\label{flushing_solvers}\r\nThe flushing problem is solved through an iterative optimization process which \r\nselects different sets of hydrant and valve locations and evaluates their effectiveness\r\nin minimizing the impact of a set of contamination incidents. Two optimization \r\nmethods, an evolutionary algorithm and a network solver, are available in WST to solve this problem. \r\nEach solver is explained in more detail in the following subsections. \r\n\r\n\\subsection{Evolutionary Algorithm}\\label{coliny_ea}\r\nThe evolutionary algorithm (EA) included with DAKOTA, Coliny EA, is used in the \r\noptimization routine for the \\code{flushing} subcommand. \r\nAdditional information on DAKOTA/Coliny solvers can be found at \r\n\\url{http://dakota.sandia.gov/docs/dakota/5.2/html-ref/index.html}\r\nand in the DAKOTA user manual \\citep{DakotaUserManual}.  \r\nThe random number generator used in Coliny EA is platform dependent.  \r\nThis can result in slight variations in the solution.\r\n\r\nTo design an EA, the parameter space for the optimization problem \r\nis first encoded into a string of numbers. This encoded \r\nrepresentation of the problem is called a genetic string, where each \r\nelement of the genetic string represents one parameter. \r\nWhen the EA is used with the \\code{flushing} subcommand, the parameter space is defined by the number \r\nof flushing and valve closure locations. Each location is assigned a sequential \r\ninteger that represents a feasible location within the EPANET network. The final EA solution \r\nis reported based on the EPANET node/pipe IDs.\r\n\r\nThe EA has several solver options that define how the EA evolves. These options can be set in the \r\n\\code{[solver][options]} sections of the \\code{flushing} WST configuration file and are specific to the Coliny EA solver. \r\nThe EA evolves an initial genetic strings of size \\code{[population\\_size]} \r\nthat is set based on \\code{[initialization\\_type]} using the following steps:\r\n\\begin{enumerate}\r\n\\item Evaluation: Evaluate the solution for each genetic string. This involves function \r\ncalls to the \\code{tevasim} and \\code{sim2Impact} subcommands for each string to define the impact value.  \r\n\\item Breeding: Select two members of the population based on fitness. The \r\nprobability of selection is based on \\code{[fitness\\_type]}.  \r\n\\item Crossover: Crossover two members based on \\code{[crossover\\_type]} and \\code{[crossover\\_rate]}.\r\n\\item Mutation: Mutate the two members based on \\code{[mutation\\_type]} and \\code{[mutation\\_rate]}.\r\n\\item Steps 2-4 are repeated until the entire population has been changed.\r\n\\item Replacement: After a new population is created, the old population is \r\nreplaced by the current population while keeping the highest ranked string \r\n(elitist = 1 replacement option).\r\n\\end{enumerate}\r\nSteps 1-6 are repeated until \\code{[max\\_iterations]} or \\code{[max\\_function\\_evaluations]} criteria is met. \r\n\r\n\\subsection{Network Solver}\\label{coliny_statemachine}\r\n\r\nThe network solver used in WST is a network-constrained, derivative-free local search optimization algorithm. \r\nIt is a discrete analog-to-pattern search. The allowable moves are to adjacent nodes (or pipes), rather than moves in the \r\ncontinuous space. This approach provides local refinement of candidate solutions. The valid moves include\r\nremoving a node (or pipe) location and replacing it with one anywhere in the network. Two forms of the network solver can be \r\nused: with and without initial starting points. The initial starting points are node (or pipe) locations in the network\r\nin which the algorithm should begin its local search. If these points are not supplied to the algorithm, \r\nthen it reduces to a greedy placement algorithm. Convergence is met when no remaining moves improve the solution.\r\n\r\n\\subsection{Flushing Optimization for Large Problems}\r\n\r\nThe iterative optimization process used for flushing requires numerous \r\nsimulations of the network hydraulics and water quality. Computational run time depends on several factors, including \r\nthe size of the network model, \r\nthe number of possible contamination incidents, \r\nthe number of feasible flushing locations \r\nand the solver options. For the network solver,the computational run time also depends on the network model\r\ngeometry surrounding the local search region. For large flushing optimization problems, several techniques can be used to \r\ndecrease the computational run time. These options include running multiple instances of the underlying \r\nsimulation in parallel, setting a stop time criteria and skeletonizing the network model.  \r\n\r\n\\subsubsection{Parallelization}\r\n\r\nThe Dakota coliny\\_ea and StateMachineLS solvers both include an option to set \r\nthe number of threads used to perform the simulations.   \r\nThis option is specified in \\code{[solver][threads]}, as shown below. It should be \r\nset to the number of threads that are available for the simulation. The default value is 1.  \r\nIf an integer greater than 1 is specified, Dakota will run that many threads.\r\nThe expected efficiency of parallelization is nearly linear with the number of \r\nthreads (up to the number of processor cores in the computer).\r\n\r\n\\begin{unknownListing}\r\nsolver:\r\n  type: coliny_ea \r\n  threads: 2\r\n\\end{unknownListing}\r\n\r\n\\subsubsection{Stop time criteria}\r\n\r\nIf a solution needs to be identified within a certain amount of time, a simulation stop time \r\ncriteria can be defined. This option causes the solver to terminate after a \r\nspecified time, even if the underlying algorithm has not converged to an optimal solution.  \r\nThe stop time criteria is included with both the Dakota coliny\\_ea and \r\nStateMachineLS solvers, and it is specified in \\code{[solver][options][misc\\_options]}, as \r\nshown below. The max\\_time has to be given in seconds. As the optimization \r\nalgorithms only check the elapsed time once per major iteration, the actual \r\nsolver run time will be slightly longer than the specified maximum run time.  \r\nWhen the optimization process is cut off prematurely, the best solution \r\nobtained so far is reported to the user.\r\n\r\n\\begin{unknownListing}\r\nsolver:\r\n  type: StateMachineLS  \r\n  options: \r\n    misc_options: \"'max_time=10'\"\r\n\\end{unknownListing}\r\n\r\n\\subsubsection{Skeletonization}\r\n\r\nTo reduce the size of the network model, possible contamination incidents and the number of \r\nfeasible flushing locations, the user can skeletonize the problem and evaluate \r\nthe results on the full network model. WST includes a utility script, spotSkeleton,  \r\nthat can be used to skeletonize network models (See Executable Files Section ~\\ref{skelExecutable}).  \r\nNetwork models are skeletonized based on a pipe diameter threshold. The executable, spotSkeleton,  \r\ncreates a new EPANET input (inp) file and a related map file.  \r\nThe map file associates the nodes in the skeletonized network model (upscaled nodes)  \r\nto the nodes in the original network model (downscaled nodes). When  \r\nworking with a skeletonized network model, other aspects of the flushing problem also  \r\nneed to upscaled based on the skeletonization map. These include: the injection location(s)  \r\nand strength of the contamination incident(s), the population at each node, the sensor  \r\nplacement, the feasible flushing locations and the initial points for the optimization  \r\nsolver. For example, if Nodes 1, 2, 3 and 4 in the original network model are  \r\nrepresented by Node 2 in the skeletonized network model, then a sensor placed at  \r\nNode 4 in the original network model should be placed at Node 2 in the skeletonized  \r\nnetwork model. \r\n\r\nAfter flushing optimization is run on the skeletonized network model, the  \r\nsolution can then be evaluated or refined using the original network model.  \r\nTo evaluate the current solution, the locations on the skeletonized network \r\nshould be listed as the only feasible flushing locations  \r\nin the original network model and the EVALUATE solver option should be used (See Example ~\\ref{flushing_ex3}).   \r\nTo refine the current solution, downscale the locations on the skeletonized network\r\nand use those original network nodes as the only feasible flushing locations  \r\nin a second optimization. In this refinment, the solver type and  \r\nsolver options can be different for the first and second optimization.\r\n\r\n\\section{\\code{flushing} Subcommand}\r\n\r\nThe \\code{flushing} subcommand is executed using the following command line:\r\n\\begin{unknownListing}\r\nwst flushing <configfile> \r\n\\end{unknownListing}\r\nwhere \\code{configfile} is a WST configuration file in the YAML format. \r\n\r\nThe \\code{---help} option prints information about this subcommand, such as usage,\r\narguments and a brief description:\r\n\\begin{unknownListing}\r\nwst flushing --help\r\n\\end{unknownListing}\r\n\r\n\\subsection{Configuration File}\r\n\r\nThe \\code{flushing} subcommand generates a template configuration file using the following command line:\r\n\r\n\\begin{unknownListing}\r\nwst flushing --template <configfile>\r\n\\end{unknownListing}\r\n\r\nThe \\code{flushing} template configuration file is shown in Figure \\ref{fig:flushing_template}.  \r\nBrief descriptions of the options are included in the template after the \\# sign.  \r\n\r\n\\begin{figure}[p!]\r\n  \\unknownInputListing{examples/flushing_config.yml}{}{1}{50}\r\n  \\caption{The \\code{flushing} configuration template file.}\r\n  \\label{fig:flushing_template}\r\n\\end{figure}\r\n\r\n\\subsection{Configuration Options}\r\n\r\nFull descriptions of the WST configuration options used by the \\code{flushing} subcommand are listed below.\r\n\\input{examples/flushing_config}\r\n\r\nIn addition to these standard WST configuration options, the solver block can define \r\nan evaluation option. To evaluate the flushing response without solving the \r\noptimization problem, the solver type can be set as EVALUATE. This option allows a \r\nset of flushing locations to be evaluated against a different contamination \r\nscenario than the one for which it was designed. \r\n\r\nThe solver block can also define specific options for the optimization solver. \r\nThe solver options should be modified according to the specific optimization problem. \r\nIf the options are not set in the solver block, then the default values for these options are used. \r\nThe two solvers available in the \\code{flushing} subcommand each have their own options. \r\nThe EA solver has numerous options which can be defined. Additional information on the options available\r\nfor the EA solver can found in the DAKOTA user manual \\citep{DakotaUserManual}. \r\nAn example of the EA solver options are listed below.\r\n\r\n\\begin{unknownListing}\r\nsolver:\r\n  type: coliny_ea\r\n  options: \r\n    crossover_rate: 0.8\r\n    crossover_type: uniform\r\n    fitness_type: linear_rank\r\n    initialization_type: unique_random\r\n    max_function_evaluations: 30000\r\n    max_iterations: 1000\r\n    mutation_rate: 1\r\n    mutation_type: offset_uniform\r\n    population_size: 50\r\n    seed: 11011011\r\n\\end{unknownListing}\r\n\r\nThe network solver has two options that can be set in the solver block of the configuration file. \r\n\\begin{unknownListing}\r\nsolver:  \r\n  type: StateMachineLS\r\n  options:\r\n    verbosity: 2\r\n    max_fcn_evaluations: 0\r\n\\end{unknownListing}\r\n\r\n\\subsection{Subcommand Output}\r\nThe \\code{flushing} subcommand creates a YAML file called <output prefix>flushing\\_output.yml \r\nthat contains an optimized set of node locations (EPANET node IDs) to flush, \r\nan optimized set of pipe locations (EPANET pipe IDs) to close,\r\nthe final impact metric, the run date and CPU time. \r\nThe log file called <output prefix>flushing\\_output.log contains basic debugging information.\r\nA visualization YAML configuration file named <output prefix>flushing\\_output\\_vis.yml is also created.\r\nThe \\code{visualization} subcommand is automatically run using this YAML file.\r\n\r\n\\section{Flushing Response Examples}\\label{flushing_example}\r\nTo demonstrate the two different solvers available in the \\code{flushing} subcommand, \r\ntwo examples are presented. Both examples have the same characteristics in terms \r\nof the contamination scenario and flushing parameters. EPANET Example Network 3 (Net3.inp)\r\nis the network used and the contamination scenario is an hour long injection at \r\nnode 101 beginning at hour 3 in the simulation. A maximum of three hydrants can be flushed \r\nfor a duration of eight hours at a rate 800 gal/min. The option to close pipes/valves was \r\nnot included in these analyses. The impact metric being minimized is population exposed (PE). \r\nIn addition, the third and forth examples are provided to demonstrate the evaluate and stop time\r\ncriteria options, respectively.\r\n\r\n\\subsection{Example 1}\r\n\r\nThe first example uses the EA solver (coliny\\_ea) with the parallization option enabled \r\nand the configuration file, flushing\\_ex1.yml, is shown in Figure \\ref{fig:flushing_ex1}. This example\r\nhas the \\code{[solver][threads]} option set to 2 threads. Please note: \r\nif the computer used to execute the example only has one thread, change the \\code{[solver][threads]} \r\noption to 1 instead of 2.\r\n\r\n\\begin{figure}[h]\r\n  \\unknownInputListing{../../examples/flushing_ex1.yml}{}{1}{55}\r\n  \\caption{The \\code{flushing} configuration file for example 1.}\r\n  \\label{fig:flushing_ex1}\r\n\\end{figure}\r\n\r\nThe example can be executed using the following command line:\r\n\r\n\\begin{unknownListing}\r\nwst flushing flushing_ex1.yml\r\n\\end{unknownListing}\r\n\r\nThe YAML output file, Net3flushing\\_output.yml, for example 1 \r\nis shown in Figure \\ref{fig:flushing_ex1_yml}. The EA selected to \r\nflush nodes 113, 191 and 197 for a PE impact value of 5292. The CPU time \r\nwas approximately 6 minutes using 2 threads. \r\nSince the random number generator used in the EA solver is platform dependent,   \r\nthe solution can be slightly different if the example is executed on a computer with Windows.\r\n\r\n\\begin{figure}[h]\r\n  \\unknownInputListing{examples/flushing/flushing_ex1_output.yml}{}{1}{11}\r\n  \\caption{The \\code{flushing} YAML output file for example 1.}\r\n  \\label{fig:flushing_ex1_yml}\r\n\\end{figure}\r\n\r\n% \\FloatBarrier \r\n\\subsection{Example 2}\r\n\r\nThe second example uses the network solver (StateMachineLS) \r\nwithout initial points and the configuration file, flushing\\_ex2.yml, \r\nis shown in Figure \\ref{fig:flushing_ex2}. \r\n\r\n\\begin{figure}[h]\r\n  \\unknownInputListing{../../examples/flushing_ex2.yml}{}{1}{45}\r\n  \\caption{The \\code{flushing} configuration file for example 2.}\r\n  \\label{fig:flushing_ex2}\r\n\\end{figure}\r\n\r\nThe example can be executed using the following command line:\r\n\r\n\\begin{unknownListing}\r\nwst flushing flushing_ex2.yml\r\n\\end{unknownListing}\r\n\r\nThe YAML output file, Net3flushing\\_output.yml, for example 2 is shown \r\nin Figure \\ref{fig:flushing_ex2_yml}. The network solver selected to \r\nflush nodes 101, 103 and 109 for a PE impact metric of 4919. The CPU time \r\nwas approximately 2 minutes.\r\n\r\n\\begin{figure}[h]\r\n  \\unknownInputListing{examples/flushing/flushing_ex2_output.yml}{}{1}{11}\r\n  \\caption{The \\code{flushing} YAML output file for example 2.}\r\n  \\label{fig:flushing_ex2_yml}\r\n\\end{figure}\r\n\r\nExamining the output files from the two examples shows that the optimization\r\nsolvers identified different solutions. As EAs are not guaranteed to find the \r\noptimal solution, these results are not unexpected. In addition, the CPU times \r\nto obtain the solutions are different. The EA solution took about 6 minutes \r\nto obtained using 2 threads, while the network solver solution was achieved in approximately 2 minutes.\r\n\r\n\\subsection{Example 3}\\label{flushing_ex3}\r\n\r\nThe third example uses the evaluate option and the configuration \r\nfile, flushing\\_ex3.yml, is shown in Figure \\ref{fig:flushing_ex3}. \r\nIn this example, the same contamination scenario is used but only two \r\n(2) flushing locations are evaluated in terms of reducing the PE impact \r\nmetric. The flushing locations being evaluated are nodes 101 and 127. \r\n\r\n\\begin{figure}[h]\r\n  \\unknownInputListing{../../examples/flushing_ex3.yml}{}{1}{44}\r\n  \\caption{The \\code{flushing} configuration file for example 3.}\r\n  \\label{fig:flushing_ex3}\r\n\\end{figure}\r\n\r\nThe example can be executed using the following command line:\r\n\r\n\\begin{unknownListing}\r\nwst flushing flushing_ex3.yml\r\n\\end{unknownListing}\r\n\r\nThe YAML output file, Net3flushing\\_output.yml, for example 3 is shown \r\nin Figure \\ref{fig:flushing_ex3_yml}. These two flushing locations \r\nresulted in a PE impact metric of 10,759. Compared to the results from \r\nexample 2, the PE impact metric is much larger since only two flushing \r\nlocations are used instead of three. The evaluate option can be used to compare \r\nthe impact metrics obtained from various flushing location combinations. \r\n\r\n\\begin{figure}[h]\r\n  \\unknownInputListing{examples/flushing/flushing_ex3_output.yml}{}{1}{11}\r\n  \\caption{The \\code{flushing} YAML output file for example 3.}\r\n  \\label{fig:flushing_ex3_yml}\r\n\\end{figure}\r\n\r\n\\subsection{Example 4}\r\n\r\nThe fourth example demonstrates the stop time option and uses almost the same configuration file as example 2. \r\nThe configuration file, flushing\\_ex4.yml, is shown in Figure \\ref{fig:flushing_ex4}, in which \r\nthe stop criteria option is enabled using the \\code{[solver][options][misc\\_options]} option set to \"'max\\_time=30'\".\r\n\r\n\\begin{figure}[h]\r\n  \\unknownInputListing{../../examples/flushing_ex4.yml}{}{1}{46}\r\n  \\caption{The \\code{flushing} configuration file for example 4.}\r\n  \\label{fig:flushing_ex4}\r\n\\end{figure}\r\n\r\nThe example can be executed using the following command line:\r\n\r\n\\begin{unknownListing}\r\nwst flushing flushing_ex4.yml\r\n\\end{unknownListing}\r\n\r\nThe YAML output file, Net3flushing\\_output.yml, for example 4 \r\nis shown in Figure \\ref{fig:flushing_ex4_yml}. The network solver selected to \r\nflush node 105 for a PE impact value of 9676. The CPU time was 45 seconds, \r\nwhich is greater than the stop time criteria since it is only checked periodically. \r\nThe flushing solution was different than the solution obtained from example 2, \r\nsince the stop time option was not used and it executed the optimization process to completion. \r\n\r\n\\begin{figure}[h]\r\n  \\unknownInputListing{examples/flushing/flushing_ex4_output.yml}{}{1}{11}\r\n  \\caption{The \\code{flushing} YAML output file for example 4.}\r\n  \\label{fig:flushing_ex4_yml}\r\n\\end{figure}\r\n\r\n", "meta": {"hexsha": "3f59b8c9cd823369f2c717b3e507a4a2602622c2", "size": 22194, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/wst/flushing.tex", "max_stars_repo_name": "USEPA/Water-Security-Toolkit", "max_stars_repo_head_hexsha": "6b6b68e0e1b3dcc8023b453ab48a64f7fd740feb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-06-10T18:04:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-05T18:11:40.000Z", "max_issues_repo_path": "doc/wst/flushing.tex", "max_issues_repo_name": "USEPA/Water-Security-Toolkit", "max_issues_repo_head_hexsha": "6b6b68e0e1b3dcc8023b453ab48a64f7fd740feb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/wst/flushing.tex", "max_forks_repo_name": "USEPA/Water-Security-Toolkit", "max_forks_repo_head_hexsha": "6b6b68e0e1b3dcc8023b453ab48a64f7fd740feb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-09-24T19:04:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-05T18:11:43.000Z", "avg_line_length": 53.0956937799, "max_line_length": 126, "alphanum_fraction": 0.77579526, "num_tokens": 5157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.34904287667217504}}
{"text": "\n\\part{Outline of the AXFI Data Model}\n\\vspace{.5em}\n\\section{Types of Image Annotations}\n\\p{The most fundamental kinds of image annotations \nare geometric primitives such as points, lines, \nand polygons.  Many other forms of annotations \nare possible, however, mostly supplemental \ndata which is associated with these primitives \nor, in some cases, with the image as a whole.  \nIn general, \\AXFI{} classifies annotations into \nthe following groups:\n\n\\begin{description}\n\\item[Geometric Primitives]  These annotations \ndelineate spatial/geometric regions in zero, one, \nor two dimensions (or potentially higher dimensions \nwhen working in non-\\TwoD{} contexts).  At a minimum, \n\\AXFI{} data should support points, lines, \npolygons, polylines (considered a superkind of \npolygons where a polygon is a closed polyline), circles, \nand ellipses.  Additionally, \\AXFI{} recognizes \ngeneric \\q{closed} and \\q{open} \\textit{curves}, which \nare nonlinear one-dimensional regions (or boundaries \nof two-dimensional regions) that are neither \nelliptical or circular arcs.  Depending on \ncontext, \\AXFI{} can be extended to provide \nmore detailed subkinds of curves generated \nby different sorts of mathematical equations, \nalong with notations for the formulae \n(e.g., b-splines) that generate a particular \ncurve.\\footnote{In formal statements, \nthis and other \\sAXFI{} documentation will \nuse the term \\q{kind,} as well as \\q{superkind} \nand \\q{subkind,} to indicate groups of values/entities \nidentified via a classification.  Vocabulary \nbased on \\q{kind} is preferred to \\q{type} or \n\\q{class} because of the distinct meanings these\nlatter terms have in computational contexts \nwhich are also discussed in reference to \\sAXFI{}.}  \nMore information about encoding \nellipse data as well as other sorts of \ncurves is outlined below (page~\\lpageref{ph:curves}).  \n\nA variation on the polygon/polygon-line alternative \nare polygon-lines demarcating spatial regions \nwhose boundaries extend to one or more sides/corners \nof the image (e.g., a \\q{quadrant} is defined \nvia one central point with line segments \nparallel to and implicitly \nextended to the edges).  These poly-lines \nmay not explicitly represent the overall image \nboundary as part of their own boundary.  \nConceptually, treating the image-border itself \nas a different \\textit{sort} of boundary than \nthose explicitly notated may be more accurate \nthan eliding these distinctions.  This \napplies also to segment boundaries.  For instance, \nthe sand/ocean border in a beach scene represents \na physical discontinuity between two different \nmaterial substances, and so it records an \nobservable detail of the depicted scene.  \nOn the other hand, the edge of the sand-region \nat the bottom of the image is not a physical \nboundary, but an artifact of the camera position; \nwe assume the beach itself extends further than \nwhat the camera captures.  All told, then, \nin addition to polygons (or curves or segment-boundaries) \nbeing \\textit{open} or \\textit{closed}, \\AXFI{} \nrecognizes a third form of closure dubbed \n\\q{incomplete,} meaning that a spatial region is \ngeometrically closed by the edge of the image but \nthat this closure has no observational or semantic \nsignificance.  \\lAXFI{} allows a notation that \na spatial region is \\q{closed by fiat} when the closure \nresults from the intrusion of the global image boundary.  \nA polygonal line may be closed by fiat when it does \nnot explicitly include lines along the global boundary, \nbut forms a closed polygon when such lines are \nincluded in practice; the result is called a \n\\textit{fiat polygon} (similarly an annotation \ncan be classified as a \\textit{fiat curve} or \n\\textit{fiat segment}).\n   \n\n\\item[Segments and Regions]  A \\textit{segment} is \nconsidered to be, canonically, an integral \nsubimage with a semantically precise \nseparation of \\q{foreground} from \\q{background.}  \nThere may be vagueness or approximation \nin how the segment is precisely individuated \nfrom its surroundings, but these ambiguities \nare considered to be practical limitations \ndue to limited computer power, limiting pixel \nresolution, and so forth.  A \\textit{region} \nor \\textit{region of interest} is similar to a \nsegment, but defined more loosely; regions \ncan have vague descriptors, and spatially \ndisconnected parts of an image could be treated \nas parts of one same region.  In a photograph \nof a flock of birds, for example, there may be \nmultiple segments, each outlining one single bird.  \nHowever, the flock as a whole may be outlined \nby one \\textit{region}, which could (without \nbeing deemed approximative) include some of the \nbackground sky.  A \\textit{segment} can be seen \nas subkind of \\textit{region} with stricter \ngranular and topological requirements. \n\nA \\textit{partition} of an image is a segmentation \nwhich exhaustively classifies every point into \none or another segment.  A \\textit{selective} \nsegmentation, unlike a complete partition, only \nisolates certain segments or regions of \ninterests.  \\lAXFI{} adopts these terms \nas parameters that can characterize \nsegmentation processes, and by extension the \nresulting segments/regions. \n\n\\item[Locations]  In \\AXFI{}, \\textit{locations} \nare considered to be designations of areas \nwithin an image (of varying dimensions) which \nare significant by virtue of their directional, \nmorphological, or topological relations to \nthe rest of the image, rather than by virtue \nof their intrinsic shape.  Conceptually, \na \\textit{location} is in many cases similar \nto a \\textit{point}, but \\AXFI{} does not require \nlocations to be zero-dimensional.  A location \nmay be designated by a small disk, or even a\nregion/segment.  The distinguishing feature \nof locations is that their spatial shape or extent \nare not semantically significant; instead, \nwhat is important about locations is their \nposition in the image and how this position \nrelates to surrounding image content.  For \ninstance, a location might be the point/position \nwhere two roads intersect, or it could \nbe the leftmost point on the segment-boundary of \na car's fender or a bird's wings, or the \ngeometric center of a car's body or a bird's torso.\n\n\\lAXFI{} distinguishes location-annotations from \nsecondary annotations used to identify locations \n(insofar as these may be visually distinct).  For \ninstance, a position may be modeled as a single \npoint, but visually conveyed by an arrow, or by \na circle hovering above the relevant point.\n\n\\item[Focal Points]  The concept of \\textit{focal \npoints} integrates locations and geometric primitives \nfor certain analytic tasks.  In general, focal points \nare important for positional rather than morphological \nregions, similar to locations.  However, focal points \nmay function more like segments or geometric objects \nwhen used as part of an analytic objective.  For \ninstance, points embodying the center of a car's body \nor a bird's torso could be used to count the number \nof birds or cars appearing in a photograph.  \nIn this case the concept of \\q{geometric center} has \nno meaningful morphological properties, so it \nis analogous to a location.  On the other hand, the \ncenter may be treated as a proxy for, or a most \nsignificant component of, a segment or region; in this \nsense the point is \\textit{part of} a segment.  \nThis mereological aspect makes focal points \nact conceptually more like geometric primitives than \nlike locations.  In short, the classification \n\\textit{focal point} is available for spatial \nobjects which behave somewhere between locations \nand regions/points, and particularly when they \nare used in some proxying or indicative relation \nto other regions (e.g. for counting).  \n   \n\\item[Secondary Images]  In some contexts, such \nas segmentation, image-transforms are used to \nconvey image-processing operations, in contrast \nto geometric-style annotations that can be \ndefined via vertex coordinates.  A crisp \nsegment can be defined via a two-toned image \nwith the same dimensions as the annotated \nimage, but with only two logical colors \n(colors are called \\q{logical} insofar as the \nrelevant detail is how the colors compare to \none another, irregardless of the optical colors \nused to render them\\footnote{In \\sQt{}, for instance, \nthe \\textbf{QColorConstants::Color0} and \n\\textbf{QColorConstants::Color1} color values \nare considered to be special \\q{colors} \n(i.e., \\textbf{QColor} instances) which define \nthe foreground and background of a two-toned \nimage; they are not formally assigned to a \nvisual color, like black or white.}).  \nA \\q{fuzzy} segment can likewise be defined \nvia a greyscale image (anything which \nis pure-background becoming either pure white, \nor pure transparent, depending on context).  \nSecondary images can be used to denote annotations \nwhich are too granular to be summarized by \nany mathematical expression.  In these cases, \nthe actual annotation data should identify the \nsecondary image (e.g., via a file path) and \nexplain how it relates to the primary \n(or \\q{ground}) image, whereas the secondary \nfile itself fills in the annotation details.      \n\nSecondary images may be derived from ground \nimages merely to present annotations, but they \nmay also be intermediate analysands which are \nthemselves annotated.  In the latter case, \nannotations on secondary images are usually \nmeaningful also as annotations on ground \nimages, so the interrelations between both \nimages should be notated in the annotation data.\n\n\\item[Proscriptive Annotations]  \\lAXFI{} \nallows for the designation of certain annotations \nas \\q{proscriptive} when they do not \nformally delineate a geometric object, but \nindirectly express such an object's shape \nor how it may be derived.  A canonical \nexample is the use of color --- perhaps \ncolor-enhanced secondary images --- to \ndesignate segments or regions of interest.  \nFor instance, one common segmentation technique \nuses color simplification; smoothing out color \npatches can facilitate image partitioning \nby reinforcing the boundaries between different \nregions.  With sufficient color manipulation, \nimage-segments can potentially be described \nchromatically: a region may for instance \nbe identified as \\q{the area all of whose \npixels display a red channel above} some \nthreshold.  \\lAXFI{} data should therefore \nallow such indirect designations of \nsegments (and spatial/geometric regions in \ngeneral) to be encoded as annotations.\n\nThe concept of proscriptive annotations is not \nonly chromatic --- one can imagine other scenarios \nwhere morphological features, such as symmetries, \nmay be employed to similar effect.  In describing \na chess board, for instance, a set of image-regions \n(each square on the board) can be derived \nvia translational transforms of an initial \ntwo-segment kernel (one black square and one white).  \nThis representation is possible because of \ntranslational symmetries in the underlying image.  \nSuch geometric transforms and symmetries can \nsometimes be used to \\q{generate} meaningful \nimage segments, so they should be notated \nin \\AXFI{} data when appropriate.  \n\n\\item[Semantic Labels]  Some annotations supply data \nabout other annotations (what \\AIM{} calls \n\\q{Annotation on Annotation} as opposed to \n\\q{Annotation on Image}).  In general, we \ncan supply a label, description, or semantic \nclassification indicating what an image segment \nor region is \\q{about}, i.e., what it \\q{depicts} \n(a bird, a flock of birds, a car, a traffic \njam, and so forth).  Such meta-annotation may be \nseen as a semantic postlude to an imaging  \nprocess, but it may also be seen as providing further \ndetail about the process itself.  For instance, \nsuppose segmentation isolates a bird from the \nsky: the epilogue to this operation is an ability \n(for a human user or a computer algorithm) to \nclassify the segment as \\q{bird.}  However, we \ncan also say that the given fact of the segment \ncapturing the optics of a bird (with its apparent \nanatomical outline and coloration) is what \nallowed the segmentation to be possible in the \nfirst place.  Therefore, the label \\q{bird} \nserves both to utilize the segmentation for \nfurther analytic/classificatory purposes and \nalso, potentially, to characterize the \ninner workings or effectiveness of \nachieving the desired processing objective.  \nIt should be kept in mind, in short, that \nlabel annotations are not exclusively \nintended to be used for practical labeling \nin the contexts of tasks such as subject-marking \nimages in corpora; labeling could also \nbe used to notate how semantic properties \nof the image make segmentation (and other \nprocessing objectives) more or less \nfeasible, or computationally intensive/error-prone. \n\nThe semantics of labels themselves is outside \nthe scope of \\AXFI{}.  \\lAXFI{} makes no effort \nto proscibe what sorts of terms are useful \nas labels (\\q{bird,} \\q{car,} \\q{ocean,} \n\\q{tumor,} etc.), or whether labels are \nsimple strings/words or have internal structure \nof their own.  \\lAXFI{} does, however, \nmake the following minimal stipulations about \nlabels.  First, \\AXFI{} distinguishes \n\\q{mass,} \\q{count,} and \\q{plural} label \ntargets --- e.g., \\textit{ocean}, \\textit{one bird}, \n\\textit{two birds}.  These distinctions are \ndirectly relevant to how segments are bounded and \ncounted; for instance, labeling a body of water \nas \\textit{a lake} (e.g. on a satellite image where \nthe lake's full shore is visible) versus \\textit{ocean} \n(continuing to the horizon) implies different \ndesiderata for how the labeled region spatially extends \nin relation to the surrounding image.  Secondly, \nwith respect to semantic labels, \\AXFI{} recommends \nthat applications and libraries enable \nlabels to be typed values --- instances of \napplication-specific data types --- as well \nas simple character strings (like \\q{bird.})  \nThis is consistent with \\AXFI{}'s general \napproach to application integration and \ntype systems, to be discussed further in \nPart II. \n\nIn addition to labels being second-order annotations \n--- assertions attached to an image segment, \nfor example, or any other image feature deemed \nsemantically relevant in some context --- labels \nmay be applied to the image as a whole.  In this\ncontext labels would be an example of \n\\textit{metadata} annotations (discussed next), \nwhich apply to the image itself \nrather than any proper part. \n\n%\\item[Data Transformations]    \n\n\\item[Image Metadata]   This category \nof annotation concerns any information \n\\q{about} an image which is apart from \nthe specific image content.  Such details could encompass \ncomputational/encoding details such \nas color depth, pixel dimensions, and image \nfile format; or acquisition details \nsuch as the make and settings of the camera \nwhose photograph yields the current image.  \nIn theory, any information prerequisite to \ndisplaying an image may potentially \nbe relevant to how annotations are \nused and interpreted.  Therefore, \n\\AXFI{} should support representations of \nimage metadata where such information is needed \nto fully specify annotation data; the metadata \nwould then, typically, be considered an \nannotation on the entire image.  It is \noutside the scope of \\AXFI{} to present \nimage-related data which is applicable  \nto the sharing or rendering of images but \nnot, in a particular context, important to \nannotations themselves --- unlike \\DICOM{}, \nfor instance, which is designed as a \nstandard for ensuring that images are correctly \nrendered and therefore includes detailed \nspecifications of image formats and \nprerequisites, \\AXFI{} introduces \nimage metadata only where such information \ncan be considered intrinsic to the \nspecific objectives and operations of image \nannotation.  \n\n\\item[Acquisition Context]  Among the class of \nannotations which apply to the image as a whole, \n\\AXFI{} recognizes a distinct kind of annotation \ncovering what \\AIM{} calls the \\q{context,} \nor the purpose and concrete goal which compels \nusers to initiate image-processing operations.  \nIn general, some of this contextual data \nshould be preserved as a supplement to \nthe overall information generated by image-processing \noperations.  Often image processing itself is only \none stage in a multi-faceted scientific workflow, \nand contextual information which exists prior to \nthe image-annotation step may still be important \nfor subsequent steps.  For example, clinical data \nwhich motivates a radiographic study should remain \nlinked to images and annotations which result from \nthat study; this is why \\DICOMSR{} includes \nclinical as well as imaging data.  \n%More details about \\AXFI{} context descriptions are provided \n%below (section ?). \n\\end{description}\n\nThis outline covers the different kinds \nof annotation data recognized by \\AXFI{}.  \nThe following section will fill in some \nmissing details by addressing other \nsorts of information, apart from annotations \nthemselves, which might be included in an \n\\AXFI{} data package.}\n\n", "meta": {"hexsha": "bfe4dce314a05e3b37598f29a27a02c46746c041", "size": 16985, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "extra/papers/axfi/axfi/axfi-s1.tex", "max_stars_repo_name": "scignscape/PGVM", "max_stars_repo_head_hexsha": "e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "extra/papers/axfi/axfi/axfi-s1.tex", "max_issues_repo_name": "scignscape/PGVM", "max_issues_repo_head_hexsha": "e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "extra/papers/axfi/axfi/axfi-s1.tex", "max_forks_repo_name": "scignscape/PGVM", "max_forks_repo_head_hexsha": "e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.1091370558, "max_line_length": 62, "alphanum_fraction": 0.7823373565, "num_tokens": 3906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.34904286260507245}}
{"text": "\\section{Sliding Game}\nOur metric for algorithmic performance involves running A* on the sliding game (see the Youtube video for a demonstration). The sliding game is a particularly convenient search problem for two reasons: the state representation is small and the state space is very large. It blows up exponentially with respect to the puzzle dimensions. This is particularly important since our goal was to measure the effectiveness of a parallel A* algorithm, and the expansive state space would decrease potential overhead.\n\\newline\\newline\n\\begin{tabular}{ |p{3cm}||p{3cm}|p{3cm}|p{3cm}|  }\n\\hline\n\\multicolumn{4}{|c|}{Sliding Game Sequential Execution times} \\\\\n\\hline\nBoard Size& Runtime (ns)&Runtime (ms)& Runtime (s)\\\\\n\\hline\n2x3 & 35880 & 0 & 0\\\\\n3x3 & 84711 & 0 & 0\\\\\n3x4 & 258638033 & 259 & 0\\\\\n4x4 & 171623957677 & 171624 & 172\\\\\n\\hline\n\\end{tabular}\n\\newline\n\\begin{figure}[h]\n    \\includegraphics[scale=0.5]{figures/4x4.png}\n    \\caption{The puzzle grid used for the 4x4 measure}\n    \\label{fig:gastar_ds}\n\\end{figure}\n\\newline\nThe object of the game is to order the tiles in increasing numerical order. The 0 tile represents an empty tile where adjacent tiles can \"slide\" to. Thus, every turn can result in 4 more possible states (exponential). The graph below is a visual representation of the above runtimes in log scale.\n\n\\begin{tikzpicture}[scale=0.91]\n    \\begin{axis}[\n        xlabel=$area$,\n        ylabel=$time(ns)$,\n        ymode=log\n                ]\n    \\addplot[mark=*,blue] plot coordinates {\n        (6,35880)\n        (9,84711)\n        (12,258638033)\n        (16,171623957677)\n    };\n    \\addlegendentry{Runtime}\n   \n    \\end{axis}\n    \\node[above,font=\\large\\bfseries] at (current bounding box.north) {Sequential Execution times (log scale)};\n\\end{tikzpicture}\n\n\\section{Evaluating Performance}\nFor this problem, we evaluated our implementations by checking the wall time of the implementations. We found this to be appropriate for the serial algorithm given that we were not able to properly evaluate speedup for the GA* GPU method.\n\n\\section{Scaling the Problem Space}\nConsidering our sequential performance in the graph above, we see that the line is roughly linear. This supports our hypothesis that as the number of cells grow, the runtime grows roughly exponentially. In particular, we see that because most nodes on the frontier have 3 or 4 neighbors, the number of states being added as we go further from the initial state increases exponentially. Due to the nature of the problem, a small change in workload could result in dramatically larger runtime.\n\n\\section{Limitations of our Approach}\nThe main source of issues with our CUDA implementation came from our hash map. Our implementation of the hash map involves a table and two hash functions where the second can search for new locations in the table for a node if another element collides with it per the first hash function. Although this simplification allows us to not need sychronization in this section, it means that we need a very large hash table. If the hash table is small compared to the number of states, it is possible that an element has collisions with both the hash functions. In this case, the hash map will \\textit{lose information} that could potentially be important for the final path.\\newline\\newline\nAnother limitation of our approach was the amount of global memory that we allocate in this method. We use it for the large array \\verb|S| as well as the hash table. If we scale up the hash table size in order to reduce the likelihood of collisions, we will increase the global memory allocated. In the GPU, global memory is far less efficient to update than shared memory. \\textbf{As a result, the global memory brought upon by the hash table would likely be our main bottleneck in the CUDA implementation.}\n\n\\section{Changing the Hardware}\nAs we have discovered through this project, a GPU implementation of A* is not too pragmatic. In particular, the memory constraint of GPUs especially for search problems of this magnitude is quite restrictive. In contrast, using MPI would alleviate this. \\textbf{MPI is not restricted by a single device and can be used across a network of devices, thus relaxing the space constraints}. Furthermore, MPI is a more task oriented system whereas CUDA is more data oriented, which is more suitable for search problems.", "meta": {"hexsha": "35ac1f2d990ce2f365099813e4826721096ea414", "size": 4377, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "latex_files/Chapters/Results.tex", "max_stars_repo_name": "parallel-search/a-star", "max_stars_repo_head_hexsha": "0d8f940d9826b8abac5944c65845cb8e96f63f1e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "latex_files/Chapters/Results.tex", "max_issues_repo_name": "parallel-search/a-star", "max_issues_repo_head_hexsha": "0d8f940d9826b8abac5944c65845cb8e96f63f1e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "latex_files/Chapters/Results.tex", "max_forks_repo_name": "parallel-search/a-star", "max_forks_repo_head_hexsha": "0d8f940d9826b8abac5944c65845cb8e96f63f1e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 81.0555555556, "max_line_length": 685, "alphanum_fraction": 0.7669636737, "num_tokens": 1033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6926419958239131, "lm_q1q2_score": 0.3490265756632474}}
{"text": "\\section{\u001b$@4v2?%b%G%j%s%05!G=\u001b(J}\n\n\\subsection{\u001b$@4v2?%b%G%j%s%0$N4pK\\5!G=\u001b(J}\n\n\u001b$@K\\@a$G=R$Y$k5!G=$KBP1~$9$k%=!<%9%U%!%$%k$O!\"\u001b(J\\ $geopack.l$\\ \u001b$@$G$\"$k!#\u001b(J\n\n\\subsubsection{\u001b$@4pK\\=hM}4X?t\u001b(J}\n\n\\begin{description}\n\\item[vplus {\\em vertices}]\\hfill\\\\\nvertices\u001b$@$O\u001b(J3\u001b$@<!85%U%m!<%H%Y%/%?$N%j%9%H!#A4\u001b(Jvertices\u001b$@$NOB$r5a$a$k!#\u001b(J\n\\item[vector-mean {\\em vertices}]\\hfill\\\\\n3\u001b$@<!85%U%m!<%H%Y%/%?$N%j%9%H\u001b(Jvertices\u001b$@$N=E?4$r5a$a$k!#\u001b(J\n\\item[triangle {\\em a b c \\&optional (normal \\#f(0 0 1))}]\\hfill\\\\\na,b,c \u001b$@$O\u001b(J3\u001b$@<!85%U%m!<%H%Y%/%?$G$\"$j!\"\u001b(J3\u001b$@3Q7A$,7A@.$5$l$k!#\u001b(Jtriangle\u001b$@$O$3$N\u001b(J3\u001b$@3Q\u001b(J\n\u001b$@7A$NLL@Q$N\u001b(J2\u001b$@G\\$KEv$?$kNL$r5a$a$k!#\u001b(Jnormal\u001b$@$O!\"$3$N\u001b(J3\u001b$@E@$,:\\$C$F$$$kJ?LL$N@55,\u001b(J\n\u001b$@2=$5$l$?K!@~%Y%/%H%k$rI=$9!#K!@~$N8~$-$K$7$?$,$C$F!\"\u001b(Jtriangle\u001b$@$O@5!\"$^$?$OIi\u001b(J\n\u001b$@$NCM$H$J$k!#\u001b(Ja,b,c \u001b$@$,H?;~7W2s$j$KJB$s$G$$$k;~!\"\u001b(Jtriangle\u001b$@$O@5$G$\"$k!#\u001b(Ja,b,c \u001b$@$,\u001b(J\n\u001b$@;~7W2s$j$KJB$s$G$$$l$PIi$G$\"$k!#$^$?!\"\u001b(Jtriangle\u001b$@$,@5$G$\"$l$P!\"\u001b(Jc \u001b$@$OD>@~\u001b(Jab\u001b$@$N:8\u001b(J\n\u001b$@B&$K$\"$j!\"Ii$G$\"$l$PD>@~\u001b(Jab\u001b$@$N1&B&$K$\"$k$3$H$,$o$+$k!#\u001b(J\n\\item[triangle-normal {\\em a b c}]\\hfill\\\\\n\u001b$@H?;~7W2s$j$KJB$s$@\u001b(J3\u001b$@E@\u001b(Ja,b,c \u001b$@$N:\\$kJ?LL$N@55,2=$5$l$?K!@~%Y%/%?$r5a$a$k!#\u001b(J\n\\item[vector-angle {\\em v1 v2 normal}]\\hfill\\\\\n2\u001b$@$D$NJ}8~%Y%/%?\u001b(Jv1,v2 \u001b$@$N$J$93QEY!J%i%8%\"%s!K$r5a$a$k!#\u001b(Jv1, v2, normal\u001b$@$O$$$E$l\u001b(J\n\u001b$@$bA00J$F@55,2=$5$l$F$$$kI,MW$,$\"$k!#\u001b(J\n\\item[face-normal-vector {\\em vertices \\&optional rotatep}]\\hfill\\\\\n1\u001b$@J?LL>e$N\u001b(J3\u001b$@<!85%U%m!<%H%Y%/%?$N%j%9%H\u001b(Jvertices\u001b$@$+$i@55,2=$5$l$?K!@~%Y%/%?$r\u001b(J\n\u001b$@5a$a$k!#\u001b(Jvertices\u001b$@$N:G=i$NMWAG$H:G8e$NMWAG$,F10l$NE@$rI=$9;~!\"\u001b(Jrotatep \u001b$@$r\u001b(Jnil\n\u001b$@$K$7$F8F$V!#\u001b(Jrotatep!=nil\u001b$@$G$\"$l$P!\"\u001b(Jvertices\u001b$@$N:G=i$NMWAG$r:G8e$K%\"%Z%s%I$7$F\u001b(J\n\u001b$@K!@~%Y%/%?$r7W;;$9$k!#\u001b(J\n\\item[farthest {\\em p points}]\\hfill\\\\\np \u001b$@$O%U%m!<%H%Y%/%?!\"\u001b(Jpoints\u001b$@$O%U%m!<%H%Y%/%?$N%j%9%H$G$\"$k!#\u001b(Jpoints\u001b$@$NCf$+$i!\"\u001b(J\np \u001b$@$+$i:G$b1s$$E@$rC5$9!#\u001b(J\n\\item[farthest-pair {\\em points}]\\hfill\\\\\npoints\u001b$@$NCf$+$i!\"8_$$$K:G$b3V$?$C$?E@BP$rC5$9!#\u001b(J\n\\item[maxindex {\\em fv}]\\hfill\\\\\n3\u001b$@<!85%U%m!<%H%Y%/%?\u001b(Jfv\u001b$@$N\u001b(J3\u001b$@$D$NMWAG$N$&$A!\"@dBPCM$N:G$bBg$-$$MWAG$N%$%s%G%C\u001b(J\n\u001b$@%/%9\u001b(J(0,1,2) \u001b$@$r5a$a$k!#\u001b(J\n\\item[random-vector {\\em \\&optional (range 1.0)}]\\hfill\\\\\n3\u001b$@<!856u4V$N\u001b(Jrange \u001b$@$NHO0OFb$G0lMM$KJ,I[$7$?:BI8$r:n@.$9$k!#\u001b(J\n\\item[random-normalized-vector ()]\\hfill\\\\\n\u001b$@@55,2=$5$l$?%i%s%@%`%Y%/%?$r5a$a$k!#\u001b(J(note:\u001b$@6K:BI8$rMQ$$$F7W;;$9$Y$-$G$\"$k!K\u001b(J\n\\item[random-vectors {\\em n range}]\\hfill\\\\\n-range/2<x,y,z<range/2\u001b$@$N6u4V$K0lMM$KJ,I[$7$?\u001b(Jn\u001b$@8D$N%i%s%@%`%Y%/%?$r5a$a$k!#\u001b(J\n\\end{description}\n\n\\subsubsection{\u001b$@4v2?%b%G%k$N$?$a$N%/%i%9\u001b(J}\n\n\u001b$@K\\@a$G$O!\"4v2?%b%G%j%s%0$H$=$l$K4p$E$/=hM}$r9T$J$&$?$a$N%/%i%9$K$D$$$F=R$Y$k!#\u001b(J\n\\\\ [2.0cm]\n{\\jLarge surrounding-box}\n\\\\ [0.5cm]\n\n\\begin{description}\n\n\\item[{\\jlarge \\bf description}]\\hspace{1cm}\n\\begin{description}\n\\item[] \u001b$@M?$($i$l$?$9$Y$F$N#3<!85$NE@$,$=$NCf$K4^$^$l!\"\u001b(J\n\u001b$@%(%C%8$,\u001b(Jx,y,z \u001b$@<4$KJ?9T$G$\"$k$h$&$J:G>.$ND>J}BN$N%/%i%9!#\u001b(J\n\u001b$@43>D8!::$NA0=hM}Ey$KMQ$$$k!#\u001b(J\n\\end{description}\n\n\\item[{\\jlarge \\bf super class}]\\hspace{1cm}\n\\begin{description}\n\\item[object] ()\n\\end{description}\n\n\\item[{\\jlarge \\bf slots}]\\hspace{1cm}\n\\begin{description}\n\\item{minpoint}\n\\item{maxpoint}\n\\end{description}\n\n\\item[{\\jlarge \\bf methods}]\\hspace{1cm}\n\\begin{description}\n\\item[:inner (point)] point \u001b$@$,$3$N\u001b(Jbox \u001b$@Fb$K4^$^$l$k;~\u001b(Jt,\u001b$@$=$&$G$J$$$H$-\u001b(Jnil \u001b$@!#\u001b(J\n\\item[:grow (rate)]\n\u001b$@$?$H$($P\u001b(Jrate=0.01 \u001b$@$N$H$-!\"\u001b(Jbox \u001b$@$r8=:_$NBg$-$5$+$i\u001b(J1\\%\u001b$@$U$/$i$^$;$k!#\u001b(J\n\\item[:volume ()] \u001b$@$3$N\u001b(Jbox \u001b$@$NBN@Q!#\u001b(J\n\\item[:vectors (vlist)]\nfloatvector \u001b$@$N%j%9%H\u001b(Jvlist \u001b$@$+$i!\"\u001b(Jbox \u001b$@$N\u001b(Jminpoint, maxpoint \u001b$@$r@_Dj$9$k!#\u001b(J\n\\item[:vectors2 (v1 v2)]\n2\u001b$@$D$N\u001b(Jfloatvector,v1,v2 \u001b$@$+$i\u001b(Jminpoint,maxpoint \u001b$@$r@_Dj$9$k!#\u001b(J\n\\end{description}\n\n\\end{description}\n\n\\vfill\n\\pagebreak\n{\\jLarge line}\n\\\\ [0.5cm]\n\\begin{description}\n\n\\item[{\\jlarge \\bf description}]\\hspace{1cm}\n\\begin{description}\n\\item[] \u001b$@D>@~$N%/%i%9!#\u001b(J\n\\end{description}\n\n\\item[{\\jlarge \\bf super class}]\\hspace{1cm}\n\\begin{description}\n\\item[object] ()\n\\end{description}\n\n\\item[{\\jlarge \\bf slots}]\\hspace{1cm}\n\\begin{description}\n\\item[pvert] \u001b$@DL2a$9$kE@!#%5%V%/%i%9\u001b(Jedge\u001b$@$G$O!\"%(%C%8$N;OE@!#\u001b(J\n\\item[nvert] \u001b$@DL2a$9$kE@!#%5%V%/%i%9\u001b(Jedeg\u001b$@$G$O!\"%(%C%8$N=*E@!#\u001b(J\n\\end{description}\n\n\\item[{\\jlarge \\bf methods}]\\hspace{1cm}\n\\begin{description}\n\\item[:vertices ()] pvert \u001b$@$H\u001b(Jnvert \u001b$@$N%j%9%H!#\u001b(J\n\\item[:point (parameter)] pvert \u001b$@$r\u001b(J0.0,nvert \u001b$@$r\u001b(J1.0 \u001b$@$KBP1~$5$;$?$H$-$N\u001b(J\n\u001b$@%Q%i%a%?I=8=$+$i@~J,>e$NE@$N:BI8$r5a$a$k!#$9$J$o$A!\"\u001b(J\n$pvert=(x_{p},y_{p},z_{p})$, $nvert=(x_{n},y_{n},z_{n})$\\ \u001b$@$H$7!\"\u001b(J\n\u001b$@$3$N\u001b(J2\u001b$@E@$rDL$kD>@~$r!\"\u001b(J\n\n\\begin{equation}\n\\left(\n\\begin{array}{c}\nx \\\\ y \\\\ z \\\\ 1\n\\end{array} \\right)=\\left(\n\\begin{array}{cc}\n(1-t) & t\n\\end{array} \\right) \\left(\n\\begin{array}{cc}\nx_{p} & x_{n} \\\\\ny_{p} & y_{n} \\\\\nz_{p} & z_{n} \\\\\n1 & 1\n\\end{array} \\right)\n\\end{equation}\n\u001b$@$HI=$7$?$H$-!\"\u001b(J\\ $t$\\ \u001b$@$rM?$($l$P:BI8\u001b(J\\ $(x,y,z)$\\ \u001b$@$rJV$9!#\u001b(J\n\\item[:parameter (point)] :point\u001b$@$N5U$GE@$N:BI8$+$i%Q%i%a%?$r5a$a$k!#\u001b(J\n\\item[:box ()]\n\\item[:boxtest (box)]\n:box\u001b$@$O$3$N%(%C%8$,4^$^$l$k\u001b(Jsurrounding-box \u001b$@$r:n@.$9$k!#\u001b(J:boxtest\u001b$@$O$^$:<+J,\u001b(J\n\u001b$@$N\u001b(Jsurrounding-box \u001b$@$r:n@.$7!\"B>$N\u001b(Jbox \u001b$@$H$N43>D$r8!::$9$k!#\u001b(J\n\\item[:foot(point)]\n\u001b$@E@\u001b(J\\ $point=(x_{1},y_{1},z_{1})$\\ \u001b$@$+$i$3$ND>@~$K2<$m$7$??b@~$NB-$N%Q%i%a!<%?\u001b(J\n\\ $t$\\ \u001b$@$rJV$9!#$3$l$O!\"\u001b(J\n\\begin{equation}\nt=\\frac{(x_{n}-x_{p})(x_{1}-x_{p})+(y_{n}-y_{p})(y_{1}-y_{p})\n+(z_{n}-z_{p})(z_{1}-z_{p})}\n{(x_{n}-x_{p})^{2}+(y_{n}-y_{p})^{2}+(z_{n}-z_{p})^{2}}\n\\end{equation}\n\u001b$@$K$h$jM?$($i$l$k!#!J\u001b(JRef.\u001b$@LpLn7rB@O:Cx!\"?^7A$H<0!\"\u001b(Jp.178\u001b$@!\"9VCL<R!K\u001b(J\n\\item[:distance(point)]\n\u001b$@E@\u001b(Jpoint\u001b$@$+$i$3$ND>@~$^$G$N5wN%$rJV$9!#$3$l$O!\"\u001b(Jpoint\u001b$@$+$i$3$ND>@~$K2<$m$7$?\u001b(J\n\u001b$@?b@~$NB-$H\u001b(Jpoint\u001b$@$N5wN%$+$i5a$a$F$$$k!#\u001b(J\n\\item[:common-perpendicular(l)]\n\u001b$@D>@~\u001b(J\\ $l$\\ \u001b$@$H$N6&DL?b@~$r5a$a$k!#JV$9CM$O!\"\u001b(J2\u001b$@D>@~$H$N8rE@$N%j%9%H\u001b(J\n\u001b$@$G$\"$k!#\u001b(J2\u001b$@D>@~$,J?9T$N$H$-$O!\"\u001b(Jparallel\u001b$@$rJV$9!#$3$l$O!\"0J2<$NMM$K5a$a$F$$$k!#\u001b(J\n2\u001b$@D>@~$,7PM3$9$k\u001b(J2\u001b$@E@$r$=$l$>$l\u001b(J\\ $(x_{11},y_{11},z_{11})$\\ \n$(x_{12},y_{12},z_{12})$, $(x_{21},y_{21},z_{21})$\\ $(x_{22},y_{22},z_{22})$\n\\ \u001b$@$H$7!\"$3$N\u001b(J2\u001b$@D>@~$N6&DL?b@~\u001b(J\n\u001b$@$H$N8rE@$r\u001b(J\\ $(x_{31},y_{31},z_{31})$\\ $(x_{32},y_{32},z_{32})$\\ \u001b$@$H$9$k$H!\"\u001b(J\n\\begin{equation}\n(x_{12}-x_{11}\\ y_{12}-y_{11}\\ z_{12}-z_{11})^{T}\n(x_{32}-x_{31}\\ y_{32}-y_{32}\\ z_{32}-z_{31})=0 \\label{eq:suityoku1}\n\\end{equation}\n\\begin{equation}\n(x_{22}-x_{21}\\ y_{22}-y_{21}\\ z_{22}-z_{21})^{T}\n(x_{32}-x_{31}\\ y_{32}-y_{32}\\ z_{32}-z_{31})=0 \\label{eq:suityoku2}\n\\end{equation}\n\\begin{equation}\n\\left(\n\\begin{array}{c}\nx_{31} \\\\ y_{31} \\\\ z_{31} \\\\ 1\n\\end{array} \\right)=\\left(\n\\begin{array}{cc}\n(1-t_{1}) & t_{1}\n\\end{array} \\right) \\left(\n\\begin{array}{cc}\nx_{11} & x_{12} \\\\\ny_{11} & y_{12} \\\\\nz_{11} & z_{12} \\\\\n1 & 1\n\\end{array} \\right)\n\\label{eq:online1}\n\\end{equation}\n\\begin{equation}\n\\left(\n\\begin{array}{c}\nx_{32} \\\\ y_{32} \\\\ z_{32} \\\\ 1\n\\end{array} \\right)=\\left(\n\\begin{array}{cc}\n(1-t_{2}) & t_{2}\n\\end{array} \\right) \\left(\n\\begin{array}{cc}\nx_{21} & x_{22} \\\\\ny_{21} & y_{22} \\\\\nz_{21} & z_{22} \\\\\n1 & 1\n\\end{array} \\right)\n\\label{eq:online2}\n\\end{equation}\n\u001b$@$,@.N)$9$k!#\u001b(J\\ $X_{ij}=(x_{ij},y_{ij},z_{ij})^{T}$\\ \u001b$@$H$*$-!\"\u001b(J\n(\\ref{eq:suityoku1}),(\\ref{eq:suityoku2})\u001b$@<0$K\u001b(J\n(\\ref{eq:online1}),(\\ref{eq:online2})\u001b$@<0$rBeF~$9$k$H!\"\u001b(J\n\\begin{displaymath}\n(X_{12}-X_{11})^{T}(X_{12}-X_{11})t_{1}-(X_{12}-X_{11})^{T}(X_{22}-X_{21})t_{2}\n=(X_{12}-X_{11})^{T}(X_{21}-X_{11})\n\\end{displaymath}\n\\begin{displaymath}\n(X_{12}-X_{11})^{T}(X_{22}-X_{21})t_{1}-(X_{22}-X_{21})^{T}(X_{22}-X_{21})t_{2}\n=(X_{22}-X_{21})^{T}(X_{21}-X_{11})\n\\end{displaymath}\n\u001b$@$H$J$j!\"$3$l$+$i\u001b(J\\ $t_{1},t_{2}$\\ \u001b$@$r5a$a!\"$=$l$i$r\u001b(J(\\ref{eq:online1}),\n(\\ref{eq:online2})\u001b$@$KBeF~$9$k$3$H$K$h$j!\"6&DL?b@~$H$N\u001b(J2\u001b$@8rE@$,5a$^$k!#\u001b(J\n\u001b$@!J\u001b(JRef.\u001b$@LpLn7rB@O:Cx!\"?^7A$H<0!\"\u001b(Jp.178\u001b$@!\"9VCL<R!K\u001b(J\n\\item[:init (\\&key :pvertex :nvertex)]\n\\end{description}\n\n\\end{description}\n\\vfill\n\\pagebreak\n{\\jLarge edge}\n\\\\ [0.5cm]\n\\begin{description}\n\n\\item[{\\jlarge \\bf description}]\\hspace{1cm}\n\\begin{description}\n\\item[] 2\u001b$@$D$ND:E@\u001b(Jpvert \u001b$@$+$i\u001b(Jnvert \u001b$@$K8~$+$&%(%C%8$N%/%i%9!#\u001b(Jwing\u001b$@>pJs$r4^$^$J$$!#\u001b(J\n\\end{description}\n\n\\item[{\\jlarge \\bf super class}]\\hspace{1cm}\n\\begin{description}\n\\item[line] (pvert nvert)\n\\end{description}\n\n\\item[{\\jlarge \\bf slots}]\\hspace{1cm}\n\\begin{description}\n\\item[pface] \u001b$@%(%C%8$N:8B&$NLL\u001b(J\n\\item[nface] \u001b$@%(%C%8$N1&B&$NLL\u001b(J\n\\item[(angle float)] pface \u001b$@$H\u001b(Jnface \u001b$@$,$J$93QEY\u001b(J\n\\end{description}\n% picture= edge.tex\n% \\begin{figure}\n\\begin{minipage}[b]{16cm}\n\\begin{picture}( 391, 320)\n\\large\\tt\n\\put( 203.4, 152.8){nface}\n\\put( 102.2, 152.8){pface}\n\\put( 152.8,  51.6){pvert}\n\\put( 152.8, 253.9){nvert}\n\\thicklines\n\\put( 168.6, 101.2){\\line( 1,-1){  84.3}}\n\\put( 168.6, 101.2){\\line(-1,-1){  84.3}}\n\\put( 168.6, 101.2){\\vector( 0, 1){ 118.0}}\n\\put( 168.6, 219.2){\\line( 1, 1){  84.3}}\n\\put(  84.3, 303.5){\\line( 1,-1){  84.3}}\n\\end{picture}\n\\end{minipage}\n% \\end{figure}\n\n\\item[{\\jlarge \\bf methods}]\\hspace{1cm}\n\\begin{description}\n\\item[:pvertex (f)]\n\\item[:nvertex (f)] f \u001b$@$O\u001b(Jpface \u001b$@$^$?$O\u001b(Jnface \u001b$@!#\u001b(Jf \u001b$@$K$H$C$F$N\u001b(Jpvert,nvert \u001b$@$r5a$a$k!#\u001b(J\n\\item[:pface ()] pface\u001b$@$rJV$9!#\u001b(J\n\\item[:nface ()] nface \u001b$@$rJV$9!#\u001b(J\n\\item[:binormal (f)]\nf \u001b$@$O\u001b(Jpface \u001b$@$^$?$O\u001b(Jnface \u001b$@!#\u001b(Jf\u001b$@$NK!@~$H$3$N%(%C%8$NN>J}$KD>8r$9$k@55,2=$5$l$?J}8~%Y\u001b(J\n\u001b$@%/%?$r7W;;$9$k!#\u001b(J\n\\item[:angle ()] angle\n\\item[:set-angle ()] \u001b$@LL4V$N3QEY!J\u001b(J2\u001b$@LL3Q!K$r7W;;$7$F\u001b(Jangle \u001b$@$KF~$l$k!#\u001b(J\n\\item[:invert ()] \u001b$@%(%C%8$NJ}8~$r5UE>$5$;$k!#$9$J$o$A!\"\u001b(Jpface \u001b$@$H\u001b(Jnface \u001b$@$r\u001b(J\n\u001b$@8r49$9$k!#\u001b(J\n\\item[:set-face (pv nv f)] pvert,nvert \u001b$@$KBP1~$9$k\u001b(Jpface \u001b$@$^$?$O\u001b(Jnface \u001b$@$r\u001b(J\n\u001b$@%;%C%H$9$k!#\u001b(J\n\\item[:distance (point)] \u001b$@E@\u001b(Jpoint\u001b$@$H!\"\u001b(Jedge\u001b$@>e$N:G6aE@$H$N5wN%$r5a$a$k!#\u001b(J\npoint\u001b$@$+$i$3$N\u001b(Jedge\u001b$@$K2<$m$7$??b@~$NB-$,$3$N\u001b(Jedge\u001b$@>e$K>h$k$H$-$O$=$NB-$H$N5wN%!\"\u001b(J\n\u001b$@$=$&$G$J$$$H$-$O!\"6a$$J}$NC<E@$H$N5wN%$G$\"$k!#\u001b(J\n\\item[:init (\\&key :pface :nface :pvertex :nvertex)]\n\\end{description}\n\n\\end{description}\n\n\\vfill\n\\pagebreak\n{\\jLarge plane}\n\\\\ [0.5cm]\n\n\\begin{description}\n\n\\item[{\\jlarge \\bf description}]\\hspace{1cm}\n\\begin{description}\n\\item[] \u001b$@6-3&$N$J$$J?LL$N%/%i%9\u001b(J\n\\end{description}\n\n\\item[{\\jlarge \\bf super class}]\\hspace{1cm}\n\\begin{description}\n\\item[object] ()\n\\end{description}\n\n\\item[{\\jlarge \\bf slots}]\\hspace{1cm}\n\\begin{description}\n\\item[(normal :type floatvector)] \n\\item[(distance :type float) )]\n\\end{description}\n\n\\item[{\\jlarge \\bf methods}]\\hspace{1cm}\n\\begin{description}\n\\item[:normal ()] normal\n\\item[:distance (point)] point\u001b$@$H$3$NJ?LL$N5wN%$r7W;;$9$k!#\u001b(J\n\\item[:intersection (pv nv)]\n2\u001b$@E@\u001b(Jpv,nv \u001b$@$K$h$C$FI=8=$5$l$kD>@~$H$3$NJ?LL$H$N8rE@$r%Q%i%a!<%?$GJV$9!#\u001b(J\n\u001b$@$9$J$o$A!\"\u001b(J$pvert=(x_{p},y_{p},z_{p})$,\\ $nvert=(x_{n},y_{n},z_{n})$\\ \n\u001b$@$H$7!\"$3$N\u001b(J2\u001b$@E@$rDL$kD>@~$r!\"\u001b(J\n\n\\begin{equation}\n\\left(\n\\begin{array}{c}\nx \\\\ y \\\\ z \\\\ 1\n\\end{array} \\right)=\\left(\n\\begin{array}{cc}\n(1-t) & t\n\\end{array} \\right) \\left(\n\\begin{array}{cc}\nx_{p} & x_{n} \\\\\ny_{p} & y_{n} \\\\\nz_{p} & z_{n} \\\\\n1 & 1\n\\end{array} \\right)\n\\end{equation}\n\u001b$@$H$*$$$?$H$-!\"J?LL\u001b(J\n\n\\begin{equation}\n\\left(\n\\begin{array}{cccc}\na & b & c & d\n\\end{array} \\right) \\left(\n\\begin{array}{c}\nx \\\\ y \\\\ z \\\\ 1\n\\end{array} \\right) = 0\n\\end{equation}\n\u001b$@$H$N8rE@$K$*$1$k%Q%i%a!<%?\u001b(J\\ $t$\\ \u001b$@$NCM!\"\u001b(J\n\n\\begin{equation}\nt=\\frac{ax_{p}+by_{p}+cz_{p}+d}{(ax_{p}+by_{p}+cz_{p})-(ax_{n}+by_{n}+cz_{n})}\n\\end{equation}\n\u001b$@$rJV$9!#\u001b(J\n\\item[:foot (point)]\n\u001b$@E@\u001b(J\\ $point=(x_{1},y_{1},z_{1})$\\ \u001b$@$+$iJ?LL\u001b(J\\ $ax+by+cz+d=0$\\ \u001b$@$K9_$m$7$??b@~$NB-\u001b(J\n\\ $(x_{0},y_{0},z_{0})$\\ \u001b$@$r5a$a$k!#$3$l$O!\"\u001b(J\n\\begin{equation}\n\\left(\n\\begin{array}{c}\nx_{0} \\\\ y_{0} \\\\ z_{0}\n\\end{array}\n\\right) = \\left(\n\\begin{array}{c}\nx_{1} \\\\ y_{1} \\\\ z_{1}\n\\end{array}\n\\right) + t \\left(\n\\begin{array}{c}\na \\\\ b \\\\ c\n\\end{array}\n\\right)\n\\end{equation}\n\u001b$@$H$*$-!\"$3$l$r\u001b(J\\ $ax_{0}+by_{0}+cz_{0}+d=0$\\ \u001b$@$KBeF~$7$F!\"\u001b(J\n\\begin{equation}\nt=-\\frac{ax_{1}+by_{1}+cz_{1}+d}{a^{2}+b^{2}+c^{2}}\n\\end{equation}\n\u001b$@$H%Q%i%a!<%?\u001b(J\\ $t$\\ \u001b$@$NCM$r5a$a$k$3$H$K$h$jF@$i$l$k!#\u001b(J\n\\item[:intersect-edge (edge)]\nedge\u001b$@$H$N8rE@$N%Q%i%a!<%?$H:BI8$r%j%9%H$K$7$FJV$9!#\u001b(J\n\n\\item[:init (normal apoint)]\n\u001b$@K!@~$,\u001b(Jnormal\u001b$@$G!\"E@\u001b(Japoint\u001b$@$rDL$k$h$&$JJ?LL$rDj5A$9$k!#\u001b(J\n\\end{description}\n\n\\end{description}\n\\vfill\n\\pagebreak\n{\\jLarge closed-region}\n\\\\ [0.5cm]\n\\begin{description}\n\n\\item[{\\jlarge \\bf description}]\\hspace{1cm}\n\\begin{description}\n\\item[] \u001b$@%(%C%8$K$h$C$F0O$^$l$?J?LL$NNN0h$N%/%i%9\u001b(J\n\u001b$@LL$O4pK\\E*$KJ?LLJ}Dx<0$H%(%C%8$r0O$`%(%C%8!\"D:E@$N%k!<%W$GI=8=$5$l$k!#\u001b(J\n\u001b$@J?LLJ}Dx<0$O\u001b(Jplane \u001b$@$KJ];}$5$l!\"\u001b(Jclosed-region \u001b$@$O%k!<%W$rJ];}$9$k!#\u001b(J\nedges \u001b$@$H\u001b(Jvertices\u001b$@$OLL$rJ*BN$N30It$+$i\u001b(J\n\u001b$@D/$a$?;~!\"H?;~7W2s$j$KJB$V$h$&$J%j%9%H$G$\"$k!#JL$N8@$$J}$G$O!\"\u001b(Jedges,\nvertices\u001b$@$N=g$K%k!<%W$rIA$/$h$&$K$M$8$r2s$9$H$M$8$,?J$`J}8~$,J*BN$N30It$9\u001b(J\n\u001b$@$J$o$ALL$NK!@~J}8~$G$\"$k!#$3$N%k!<%W$K$h$C$F%(%C%8!\"D:E@$r$?$I$k$3$H$,$G$-$k\u001b(J\n\u001b$@$N$G!\"\u001b(Jedge\u001b$@$K$O%&%#%s%0>pJs$rJ];}$7$J$$!#\u001b(J\n\\end{description}\n\n\\item[{\\jlarge \\bf super class}]\\hspace{1cm}\n\\begin{description}\n\\item[plane] ((normal :type floatvector) (distance :type float))\n\\end{description}\n\n\\item[{\\jlarge \\bf slots}]\\hspace{1cm}\n\\begin{description}\n\\item[convexp] \u001b$@FLB?3Q7A$N$H$-\u001b(JT\n\\item[edges] \u001b$@LL$NFbIt$,%(%C%8$N:8B&$K$J$k$h$&$KJB$Y$?%(%C%8$N%j%9%H\u001b(J\n\\item[vertices] \u001b$@LL$NFbIt$,%(%C%8$N:8B&$K$J$k$h$&$KJB$Y$?D:E@$N%j%9%H!#\u001b(J\n$v_{1},v_{2},\\cdots,v_{n},v_{1})$\\ \u001b$@$H:G8e$K@hF,$NMWAG$,:F$S8=$l$k$3$H$KCm0U!#\u001b(J\n\\item[(model-normal :type floatvector)]\n\\item[(model-distance :type float))]\n\\end{description}\n\n\\item[{\\jlarge \\bf methods}]\\hspace{1cm}\n\\begin{description}\n\\item[:box ()] \u001b$@$3$NJDNN0h$r4^$`\u001b(Jsurrounding-box \u001b$@$r:n@.$9$k!#\u001b(J\n\\item[:boxtest (box)]\n\\item[:edges ()] edges\n\\item[:vertices ()] vertices\n\\item[:insidep (point)]\npoint \u001b$@$,$3$NJDNN0hFb$K$\"$k$H$-\u001b(Jinside, \u001b$@30It$N;~\u001b(Joutside,\u001b$@6-3&>e$N;~\u001b(Jborder.\n\u001b$@FLB?3Q7A$N$H$-!\"E@$,$9$Y$F$N%(%C%8$N:8B&$K$\"$k$+$I$&$+$rD4$Y$k!#FL$G$J$$\u001b(J\n\u001b$@$H$-$OE@$,JU$r8+9~$`3QEY$NAmOB$r7W;;$7!\"\u001b(J2\u001b$@&P$N$H$-FbIt!\"\u001b(J0\u001b$@$N$H$-30It$HH=\u001b(J\n\u001b$@Dj$7$F$$$k!#\u001b(J\n\\item[:intersect-point-vector (point vnorm)]\n\u001b$@E@\u001b(Jpoint \u001b$@$+$i@55,2=%Y%/%?\u001b(Jvnorm \u001b$@$NJ}8~$K8~$+$&H>D>@~$H$N8r:9$r5a$a$k!#\u001b(J\n\u001b$@H>D>@~$HJDNN0h$,J?9T$N$H$-$O!\"7k2L$O\u001b(Jparallel\u001b$@$K$J$k!#\u001b(J\nvnorm\u001b$@$NJ}8~$HJDNN0h$NK!@~%Y%/%?$NFb@Q$,@5!JIi!K$N$H$-$O!\"\u001b(Jpoint\u001b$@$,JDNN0h\u001b(J\n\u001b$@$+$i8+$FK!@~%Y%/%?$N8~$/B&!JH?BPB&!K$K$\"$l$P!\"H>D>@~$HJDNN0h$O8r$o$i$J$$\u001b(J\n\u001b$@$N$G!\"7k2L$O\u001b(Joutside\u001b$@$K$J$k!#5U$K!\"H>D>@~$HJDNN0h$,8r$o$k$H$-$O!\"$=$N8rE@$K\u001b(J\n\u001b$@BP$7$F!\"\u001b(J:insidep\u001b$@$N7k2L\u001b(J(inside, outside, border) \u001b$@$rJV$9!#\u001b(J\n\u001b$@!J?^\u001b(J\\ref{fig:intersect-point}\\ \u001b$@;2>H!K\u001b(J\n% picture = intersect-point.tex\n\\begin{figure}\n\\begin{minipage}[b]{16cm}\n\\begin{picture}( 388, 287)(20,0)\n\\Large\\tt\n\\put(  17.0,  12.0){p= -(ax+by+cz+d)/dnm  \u001b$@J,;R$OE@$NJDNN0h$+$i$N5wN%!#\u001b(J\np\u001b$@$,@5$J$i8r$o$k!#\u001b(J}\n\\put(  14.5,  45.7){dnm= au+by+cw dnm\u001b$@$,@5$J$iH>D>@~$HJDNN0h$NK!@~%Y%/%?$O\u001b(J\n\u001b$@F1$88~$-\u001b(J}\n\\put( 119.0, 113.1){ax+by+cz+d=0}\n\\put( 216.0, 198.3){(a,b,c)}\n\\put( 123.3, 232.0){(u,v,w)}\n\\put( 237.9, 253.1){(x,y,z)}\n\\thicklines\n\\put( 223.4, 255.5){\\vector(-3,-2){  42.2}}\n\\put( 231.9, 263.9){\\line(-1,-1){  16.9}}\n\\put( 215.0, 263.9){\\line( 1,-1){  16.9}}\n\\put( 198.1, 145.9){\\vector( 0, 1){  67.5}}\n\\put(  97.0, 112.1){\\line( 5,-2){  84.3}}\n\\put( 265.6, 129.0){\\line(-2, 3){  33.7}}\n\\put( 265.6, 129.0){\\line(-5,-3){  84.3}}\n\\put( 147.6, 196.5){\\line( 5,-1){  84.3}}\n\\put( 147.6, 145.9){\\line(-3,-2){  50.6}}\n\\put( 147.6, 196.5){\\line( 0,-1){  50.6}}\n\\end{picture}\n\\end{minipage}\n\\label{fig:intersect-point}\n\\end{figure}\n\\item[:intersect-line (p1 p2)]\n\u001b$@@~J,\u001b(Jp1-p2 \u001b$@$H$N8r:9$r5a$a$k!#8r:9$,$J$$$H$-\u001b(Jnil,\u001b$@8r:9$9$k;~!\"8rE@$N%Q%i%a%?\u001b(J\n\u001b$@$H8rE@$N:BI8$N%j%9%H$rJV$9!#\u001b(J\n\\item[:intersect-edge (e)]\n\u001b$@%(%C%8$H$N8rE@!#7k2L$O\u001b(J:intersect-line \u001b$@$HF1$8!#\u001b(J\n\\item[:intersect-face (fac)]\n\u001b$@LL\u001b(Jfac \u001b$@$H$3$NLL$H$N8r:9!#\u001b(Jt \u001b$@$^$?$O\u001b(Jnil \u001b$@!#\u001b(J\n\\item[:transform-normal (trans)]\ntrans \u001b$@$O%/%i%9\u001b(Jcoordinates \u001b$@$N%$%s%9%?%s%9$G$\"$j!\":BI8JQ49$rI=$9!#K!@~%Y%/%?\u001b(J\n\u001b$@$rJQ49$9$k!#\u001b(J\n\\item[:reset-normal ()]\nvertices\u001b$@$+$i\u001b(Jnormal\u001b$@$*$h$S\u001b(Jdistance\u001b$@$r7W;;$9$k!#\u001b(J\n\\item[:invert ()] \u001b$@$3$NLL$NFb!\"30$rH?E>$9$k!#\u001b(J\n\\item[:area ()] \u001b$@$3$NJDNN0h$NLL@Q$r7W;;$9$k!#\u001b(J\n\\item[:volume (point)] point\u001b$@$H$3$NJDNN0h$G:n$i$l$k?mBP$NBN@Q\u001b(J\n\\item[:centroid ()] \u001b$@$3$NJDNN0h$N=E?40LCV\u001b(J\n\\item[:perimeter] \u001b$@<~0OD9\u001b(J\n\\item[:init (\\&key :vertices :edges :normal :distance)]\n\\end{description}\n\n\\end{description}\n\\vfill\n\\pagebreak\n{\\jLarge face}\n\\\\ [0.5cm]\n\\begin{description}\n\n\\item[{\\jlarge \\bf description}]\\hspace{1cm}\n\\begin{description}\n\\item[] \u001b$@B?LLBN$NLL$N%/%i%9!#\u001b(J \n\\end{description}\n\n\\item[{\\jlarge \\bf super class}]\\hspace{1cm}\n\\begin{description}\n\\item[closed-region] (convexp edges vertices)\n\\end{description}\n\n\\item[{\\jlarge \\bf slots}]\\hspace{1cm}\n\\begin{description}\n\\item[holes] \u001b$@LL$K6u$$$?7j!#\u001b(J\n\\item[pbody] \u001b$@$3$NLL$,:n@.$5$l$?\u001b(Jprimitive\\ body\u001b$@$X$N%]%$%s%?!#\u001b(J\n\\item[type] \u001b$@LL$N%?%$%W\u001b(J\n\\end{description}\n\n\\item[{\\jlarge \\bf methods}]\\hspace{1cm}\n\\begin{description}\n\\item[:all-edges]\n\\item[:all-vertices] \u001b$@$3$NLL>e$NA4$F$N%(%C%8!&D:E@!\"A4$F$NFbIt%k!<%W$rJV$9!#\u001b(J\n\\item[:insidep {\\em point}]\n\\item[:area] \u001b$@LL@Q$r5a$a$k!#\u001b(J\n\\item[:centroid {\\em \\&optional reference-point}] \u001b$@LL$N=E?4$r5a$a$k!#\u001b(J\n\u001b$@7j$b9MN8$9$k!#\u001b(J\n\\item[:invert]\n\\item[:enter-hole {\\em hole}] \u001b$@7j$rEPO?$9$k!#\u001b(J\n\\item[:init {\\em \\&key :normal :distance :edges :vertices :holes}]\n\\end{description}\n\n\\end{description}\n\\vfill\n\\pagebreak\n{\\jLarge hole}\n\\\\ [0.5cm]\n\\begin{description}\n\n\\item[{\\jlarge \\bf description}]\\hspace{1cm}\n\\begin{description}\n\\item[] \u001b$@7j$N%/%i%9!#\u001b(J \n\\end{description}\n\n\\item[{\\jlarge \\bf super class}]\\hspace{1cm}\n\\begin{description}\n\\item[closed-region] (convexp edges vertices)\n\\end{description}\n\n\\item[{\\jlarge \\bf slots}]\\hspace{1cm}\n\\begin{description}\n\\item[myface] \u001b$@7j$,B0$9$k\u001b(Jface\u001b$@%*%V%8%'%/%H\u001b(J\n\\end{description}\n\n\\item[{\\jlarge \\bf methods}]\\hspace{1cm}\n\\begin{description}\n\\item[:face]\n\\item[:enter-face {\\em face}]\n\\item[:init {\\em \\&key :normal :distance :edges :vertices :face}]\n\\end{description}\n\n\\end{description}\n\\vfill\n\\pagebreak\n{\\jLarge body}\n\\\\ [0.5cm]\n\\begin{description}\n\n\\item[{\\jlarge \\bf description}]\\hspace{1cm}\n\\begin{description}\n\\item[] \u001b$@B?LLBN$N%/%i%9!#\u001b(J\n\\end{description}\n\n\\item[{\\jlarge \\bf super class}]\\hspace{1cm}\n\\begin{description}\n\\item[cascaded-coords] (parent descendants worldcoords manager)\n\\end{description}\n\n\\item[{\\jlarge \\bf slots}]\\hspace{1cm}\n\\begin{description}\n\\item[faces] \u001b$@LL$N%j%9%H!#\u001b(J\n\\item[edges] \u001b$@%(%C%8$N%j%9%H!#\u001b(J\n\\item[vertices] \u001b$@D:E@$N%j%9%H!#\u001b(J\n\\item[model-vertices] \u001b$@D:E@$N%j%9%H!#\u001b(J:translate \u001b$@Ey$GF0$+$7$F$bITJQ!#\u001b(J\n\\item[box]\n\\item[convexp] \u001b$@FLB?3Q7A$N$H$-\u001b(JT\n\\item[evertedp]\n\\item[csg] body\u001b$@$N7A>u$,JQ99$5$l$?MzNr$r<($9\u001b(JCSG\u001b$@>pJs!#\u001b(J\n\\end{description}\n\n\\item[{\\jlarge \\bf methods}]\\hspace{1cm}\n\\begin{description}\n\\item[:newcoords {\\em rot pos}]\n\\item[:vertices]\n\\item[:faces]\n\\item[:edges]\n\\item[:box]\n\\item[:volume {\\em \\&optional (reference-point \\#f(0 0 0))}] \u001b$@BN@Q7W;;\u001b(J\n\\item[:centroid {\\em \\&optional (reference-point \\#f(0 0 0))}] \u001b$@=E?47W;;\u001b(J\n\\item[:possibly-interfering-faces {\\em box}] \u001b$@43>D$7$F$$$k2DG=@-$N$\"$kLL$r\u001b(J\nbox\u001b$@%F%9%H$GC5$9!#\u001b(J\n\\item[:common-box {\\em body}]\n\u001b$@<+J,<+?H$H\u001b(Jbody\u001b$@$H$N:G>.6&DLH\"$rJV$9!#\u001b(J\n\\item[:insidep {\\em point}]\n\\item[:intersect-face {\\em face}]\n\\item[:intersectp {\\em body}] \u001b$@<+J,<+?H$H\u001b(Jbody \u001b$@$H$N43>D%A%'%C%/$r$9$k!#\u001b(Jt\u001b$@$N$H$-\u001b(J\n\u001b$@43>D$,$\"$k!#\u001b(J\n\\item[:evert] body\u001b$@$NN\"I=$rH?E>$5$;$k!#\u001b(J\n\\item[:init {\\em \\&key :faces :edges :vertices}] :init\u001b$@$K$h$C$F:n@.$5$l$?\u001b(J\nbody\u001b$@$O!\"\u001b(J*bodies*\u001b$@%j%9%H$K\u001b(Jpush\u001b$@$5$l$k!#\u001b(J\n\\item[:translate-vertices {\\em vector}]\n\u001b$@:BI87O$H$OFHN)$K!\"D:E@!J\u001b(Jmodel-vertices\u001b$@!K$N0LCV$r0\\F0$9$k!#\u001b(J\n\\item[:rotate-vertices {\\em radian axis}]\n\u001b$@F1MM$K!\"D:E@$N0LCV$r\u001b(Jaxis \u001b$@<4!J\u001b(J:x,:y or :z\u001b$@!K$^$o$j$K2sE>$9$k!#\u001b(J\n\\item[:magnify {\\em scale}]\n\\item[:csg {\\em \\&optional newcsg}] csg\u001b$@>pJs$rJV$9!#\u001b(Jnewcsg\u001b$@$,$\"$l$P!\"\u001b(Jcsg\u001b$@$NCM\u001b(J\n\u001b$@$r99?7$7$F!\"?7$7$$CM$rJV$9!#\u001b(J\n\\end{description}\n\n\\end{description}\n\n\\clearpage\n\\subsection{\u001b$@AGN)BN$N:n@.\u001b(J}\n\n\\begin{description}\n\\item[make-plane {\\em :normal :point :distance}]\n\\item[make-prism {\\em bottom-vertices sweep \\&key name color}]\\hfill\\\\\n\u001b$@ClBN$N@8@.!#ClBN$H$O!\"\u001b(J\\ $2\\frac{1}{2}$\\ \u001b$@J*BN$N$3$H!#\u001b(J\nbottom-vertices \u001b$@$ODlLL$ND:E@\u001b(J\\ $V_{1},V_{2},\\cdots,V_{n}$\\ \n\u001b$@$N%j%9%H!#\u001b(J\\ $V_{1},V_{2},\\cdots,V_{n}$\\ \u001b$@$O!\"$3$N=g$KDlLL$r30$+$i8+$F\u001b(J\n\u001b$@H?;~7W2s$j$K2s$k!#\u001b(Jsweep \u001b$@$O!\"A]0z%Y%/%?!JNc$($P!\"\u001b(J\\#f(0 0 50)\u001b$@!K$^$?$O\u001b(J\n\u001b$@C1$KClBN$N9b$5!#:BI886E@$O!\"%o!<%k%I$N\u001b(J\\#f(0 0 0)\u001b$@!#\u001b(J\n\n% picture = make-prism.tex\n\\begin{figure}[h]\n\\begin{picture}( 286, 236)\n\\thicklines\n\\put(  21.9, 158.5){\\line( 0,-1){  84.3}}\n\\put(  21.9, 158.5){\\line( 1, 1){  50.6}}\n\\put(  72.5, 209.1){\\line( 5, 1){  84.3}}\n\\put( 156.8, 226.0){\\line( 1,-1){  50.6}}\n\\put(  21.9, 158.5){\\line( 4,-3){  67.5}}\n\\put(  89.4, 107.9){\\line( 2, 3){  33.7}}\n\\put( 123.1, 158.5){\\line( 5, 1){  84.3}}\n\\put(  89.4, 107.9){\\line( 0,-1){  84.3}}\n\\put( 123.1, 158.5){\\line( 0,-1){  84.3}}\n\\put( 207.4, 175.4){\\line( 0,-1){  84.3}}\n\\thinlines\n\\put(  72.5, 209.1){\\line( 0,-1){ 101.2}}\n\\put( 156.8, 226.0){\\line( 0,-1){ 101.2}}\n\\put( 156.8, 124.8){\\line(-5,-1){  84.3}}\n\\put(  72.5, 107.9){\\line(-3,-2){  50.6}}\n\\put( 156.8, 124.8){\\line( 3,-2){  50.6}}\n\\thicklines\n\\put(  21.9,  74.2){\\line( 4,-3){  67.5}}\n\\put( 123.1,  74.2){\\line(-2,-3){  33.7}}\n\\put( 207.4,  91.1){\\line(-5,-1){  84.3}}\n\\large\\tt\n\\put( 208.4,  75.2){V1}\n\\put( 124.1,  58.3){V2}\n\\put(  90.4,   7.7){V3}\n\\put(   6.1,  58.3){V4}\n\\put( 141.0, 108.9){Vm}\n\\put( 248.9, 127.5){sweep}\n\\put( 231.0,  92.7){\\vector( 0, 1){  84.3}}\n\\put(  21.9, 158.5){\\line( 0,-1){  84.3}}\n\\put(  21.9, 158.5){\\line( 1, 1){  50.6}}\n\\put(  72.5, 209.1){\\line( 5, 1){  84.3}}\n\\put( 156.8, 226.0){\\line( 1,-1){  50.6}}\n\\put(  21.9, 158.5){\\line( 4,-3){  67.5}}\n\\put(  89.4, 107.9){\\line( 2, 3){  33.7}}\n\\put( 123.1, 158.5){\\line( 5, 1){  84.3}}\n\\put(  89.4, 107.9){\\line( 0,-1){  84.3}}\n\\put( 123.1, 158.5){\\line( 0,-1){  84.3}}\n\\put( 207.4, 175.4){\\line( 0,-1){  84.3}}\n\\thinlines\n\\put(  72.5, 209.1){\\line( 0,-1){ 101.2}}\n\\put( 156.8, 226.0){\\line( 0,-1){ 101.2}}\n\\put( 156.8, 124.8){\\line(-5,-1){  84.3}}\n\\put(  72.5, 107.9){\\line(-3,-2){  50.6}}\n\\put( 156.8, 124.8){\\line( 3,-2){  50.6}}\n\\thicklines\n\\put(  21.9,  74.2){\\line( 4,-3){  67.5}}\n\\put( 123.1,  74.2){\\line(-2,-3){  33.7}}\n\\put( 207.4,  91.1){\\line(-5,-1){  84.3}}\n\\put( 208.4,  75.2){V1}\n\\put( 124.1,  58.3){V2}\n\\put(  90.4,   7.7){V3}\n\\put(   6.1,  58.3){V4}\n\\put( 141.0, 108.9){Vm}\n\\put( 248.9, 127.5){sweep}\n\\put( 231.0,  92.7){\\vector( 0, 1){  84.3}}\n\\end{picture}\n\\caption{make-prism}\n\\end{figure}\n\\item[make-cylinder {\\em radius height \\&key segments name color}]\\hfill\\\\\n\u001b$@1_Cl$N@8@.!#\u001b(Jradius \u001b$@$ODlLL$NH>7B!#\u001b(Jheight \u001b$@$O9b$5!#\u001b(Jsegment\u001b$@?t$N\u001b(Jdefault\u001b$@$O!\"\u001b(J12\u001b$@!#\u001b(J\n\u001b$@:BI886E@$O!\"DlLL$NCf?4!#\u001b(J\n\n% picture = make-cylinder.tex\n\\begin{figure}[h]\n\\begin{picture}( 388, 236)\n\\thicklines\n\\put( 185.5,  50.6){\\vector(-1,-1){  16.9}}\n\\put( 185.5,  50.6){\\vector( 0, 1){  16.9}}\n\\large\\tt\n\\put( 321.4, 119.0){height}\n\\put( 303.5,  50.6){\\vector( 0, 1){ 134.9}}\n\\put( 237.1,  17.9){radius}\n\\put( 185.5,  50.6){\\vector( 1, 0){  33.7}}\n\\thinlines\n\\put( 134.9,  67.5){\\line(-1,-1){  16.9}}\n\\thicklines\n\\put( 118.0, 168.6){\\line( 0,-1){ 134.9}}\n\\thinlines\n\\put( 219.2,  84.3){\\line(-1, 0){  50.6}}\n\\put( 168.6,  84.3){\\line(-2,-1){  33.7}}\n\\put( 219.2, 219.2){\\line( 0,-1){ 134.9}}\n\\thicklines\n\\put( 252.9, 185.5){\\line( 0,-1){ 134.9}}\n\\put( 236.1,  33.7){\\line( 0, 1){ 134.9}}\n\\put( 202.4,  16.9){\\line( 0, 1){ 134.9}}\n\\put( 252.9,  50.6){\\line(-1,-1){  16.9}}\n\\put( 202.4,  16.9){\\line( 2, 1){  33.7}}\n\\put( 151.8,  16.9){\\line( 1, 0){  50.6}}\n\\put( 118.0,  33.7){\\line( 2,-1){  33.7}}\n\\thinlines\n\\put( 134.9, 202.4){\\line( 0,-1){ 134.9}}\n\\thicklines\n\\put( 151.8,  16.9){\\line( 0, 1){ 134.9}}\n\\thinlines\n\\put( 168.6, 219.2){\\line( 0,-1){ 134.9}}\n\\thicklines\n\\put( 134.9, 202.4){\\line(-1,-1){  16.9}}\n\\put( 168.6, 219.2){\\line(-2,-1){  33.7}}\n\\put( 219.2, 219.2){\\line(-1, 0){  50.6}}\n\\put( 252.9, 202.4){\\line(-2, 1){  33.7}}\n\\put( 252.9, 185.5){\\line( 0, 1){  16.9}}\n\\put( 252.9, 185.5){\\line(-1,-1){  16.9}}\n\\put( 202.4, 151.8){\\line( 2, 1){  33.7}}\n\\put( 202.4, 151.8){\\line(-1, 0){  50.6}}\n\\put( 151.8, 151.8){\\line(-2, 1){  33.7}}\n\\put( 118.0, 185.5){\\line( 0,-1){  16.9}}\n\\thinlines\n\\put( 252.9,  67.5){\\line(-2, 1){  33.7}}\n\\thicklines\n\\put( 185.5,  50.6){\\line( 3,-1){  50.6}}\n\\end{picture}\n\\caption{make-cylinder}\n\\end{figure}\n\\item[make-cube {\\em xsize ysize zsize \\&key name color}]\\hfill\\\\\n\u001b$@D>J}BN$N@8@.!#\u001b(Jxsize,ysize,zsize \u001b$@$O$=$l$>$l\u001b(J3\u001b$@JU$ND9$5!#:BI886E@$O!\"\u001b(J\n\u001b$@=E?4$K0lCW!#\u001b(J\n\\begin{figure}[h]\n\\begin{picture}( 304, 152)\n\\large\\tt\n\\put( 253.9, 102.2){zsize}\n\\put( 135.9,  17.9){ysize}\n\\put( 237.1,  51.6){xsize}\n\\put( 168.6,  84.3){\\vector( 1, 0){  33.7}}\n\\put( 168.6,  84.3){\\vector(-1,-1){  16.9}}\n\\put( 168.6,  84.3){\\vector( 0, 1){  33.7}}\n\\put( 134.9,  67.5){\\line( 1, 0){ 101.2}}\n\\put( 134.9,  67.5){\\line(-1,-1){  33.7}}\n\\put( 134.9, 134.9){\\line( 0,-1){  67.5}}\n\\thicklines\n\\put( 101.2,  33.7){\\line( 1, 0){ 101.2}}\n\\put( 236.1,  67.5){\\line(-1,-1){  33.7}}\n\\put( 236.1, 134.9){\\line( 0,-1){  67.5}}\n\\put( 236.1, 134.9){\\line(-1,-1){  33.7}}\n\\put( 202.4, 101.2){\\line( 0,-1){  67.5}}\n\\put( 101.2, 101.2){\\line( 1, 0){ 101.2}}\n\\put( 134.9, 134.9){\\line( 1, 0){ 101.2}}\n\\put( 101.2, 101.2){\\line( 1, 1){  33.7}}\n\\put( 101.2, 101.2){\\line( 0,-1){  67.5}}\n\\end{picture}\n\\caption{make-cube}\n\\end{figure}\n\\item[make-cone {\\em top bottom-vertices \\&key name color}]\\hfill\\\\\n\u001b$@B?3Q?m$N@8@.!#\u001b(Jtop \u001b$@$O!\"D:E@$N:BI8!#\u001b(Jbottom-vertices \u001b$@$O!\"\u001b(Jmake-prism \u001b$@$N9`;2>H!#\u001b(J\n\\begin{figure}[h]\n\\begin{picture}( 320, 169)\n\\small\\tt\n\\put( 186.5, 136.2){top}\n\\put( 237.1,  51.9){=bottom}\n\\put( 102.2,  51.9){V4}\n\\put( 135.9,  18.2){V3}\n\\put( 186.5,  18.2){V2}\n\\put( 220.2,  51.9){V1}\n\\put( 185.5,  67.5){\\line( 1,-1){  16.9}}\n\\put( 151.8,  67.5){\\line( 1, 0){  33.7}}\n\\put( 151.8,  67.5){\\line(-1,-1){  16.9}}\n\\put( 168.6, 134.9){\\line( 1,-4){  16.9}}\n\\put( 168.6, 134.9){\\line(-1,-4){  16.9}}\n\\put( 151.8,  33.7){\\line(-1, 1){  16.9}}\n\\put( 185.5,  33.7){\\line(-1, 0){  33.7}}\n\\put( 202.4,  50.6){\\line(-1,-1){  16.9}}\n\\put( 168.6, 134.9){\\line( 2,-5){  33.7}}\n\\put( 168.6, 134.9){\\line( 1,-6){  16.9}}\n\\put( 168.6, 134.9){\\line(-1,-6){  16.9}}\n\\put( 134.9,  50.6){\\line( 2, 5){  33.7}}\n\\end{picture}\n\\caption{make-cone}\n\\end{figure}\n\\clearpage\n\\item[make-solid-of-revolution {\\em points \\&key (segments 16) name key}]\n\\hfill\\\\\n\u001b$@2sE>BN$N@8@.!#\u001b(J\\ $points=(V_{1},V_{2},\\cdots,V_{n})$\\ \u001b$@$r@\\B3$7$?@^@~$r\u001b(J\nz \u001b$@<42s$j$K2sE>$7$?J*BN$r@8@.$9$k!#\u001b(Jpoints\u001b$@$N\u001b(Jy\u001b$@:BI8$O#0$K$7$F$*$/$3$H!#\u001b(J\n% picture = make-revolution\n\\begin{figure}[h]\n\\begin{picture}( 219, 169)\n\\put(  67.5,  33.7){\\line( 1, 0){  50.6}}\n\\small\\tt\n\\put( 135.9,  35.1){V5}\n\\put( 152.8,  51.9){V4}\n\\put( 152.8,  85.7){V3}\n\\put( 135.9, 119.4){V2}\n\\put( 119.0, 136.2){V1}\n\\put(  67.5, 134.9){\\line( 1, 0){  33.7}}\n\\thicklines\n\\put( 134.9,  50.6){\\line(-1,-1){  16.9}}\n\\put( 134.9,  84.3){\\line( 0,-1){  33.7}}\n\\put( 118.0, 101.2){\\line( 1,-1){  16.9}}\n\\put( 118.0, 118.0){\\line( 0,-1){  16.9}}\n\\put( 101.2, 134.9){\\line( 1,-1){  16.9}}\n\\put(  16.9,  67.5){\\vector( 1, 0){ 185.5}}\n\\put(  67.5,  16.9){\\vector( 0, 1){ 134.9}}\n\\end{picture}\n\\caption{make-solid-of-revolution}\n\\end{figure}\n\\item[convex-hull-3d {\\em vertices}]\\hfill\\\\\n\u001b$@D:E@Ns$+$iFLJq$r:n@.$9$k!#\u001b(J\n\\item[make-torus {\\em points \\&key (segments 16) name color}]\n\\item[make-icosahedron] {\\em \\&optional radius}]\n\\item[make-dodecahedraon {\\em \\&optional radius}]\n\\item[make-gdome]\n\\end{description}\n\\subsection{\u001b$@J*BN4V$N=89g1i;;\u001b(J}\n\n\u001b$@=89g1i;;$K$O!\"OB\u001b(J(union)\u001b$@!\"@Q\u001b(J(intersection)\u001b$@!\":9\u001b(J(difference)\u001b$@!\"$*$h$S\u001b(J\n\u001b$@J?LL$K$h$kJ,N%\u001b(J(cut)\u001b$@$,$\"$k!#$3$l$i$r<B9T$9$k4X?t$O!\"\u001b(J\n\n\\begin{description}\n\\item[cut-body {\\em abody plane}] abody\u001b$@$r\u001b(Jplane\u001b$@$G@ZCG$7$?$H$-$N\u001b(J\n\u001b$@@ZCGLL$r\u001b(Jface\u001b$@$H$7$F:n@.$7JV$9!#\u001b(J\n\\item[body+ {\\em body1 \\&rest more-bodies}]\\hfill\n\\item[body* {\\em body1 \\&rest more-bodies}]\\hfill\n\\item[body- {\\em body1 \\&rest more-bodies}]\\hfill\n\\item[body/ {\\em body cutting-plane}]\\hfill\n\\end{description}\n\u001b$@$G!\"$$$E$l$b4X?t\u001b(J\\ $compose-body$\\ \u001b$@$r8F$S=P$9!#$3$l$i$N7W;;$N2aDx$G$O!\"\u001b(J\n\u001b$@85$NJ*BN$K$O2?$i$NJQ99$b2C$($J$$!#=>$C$F!\"9g@.$,ESCf$G<:GT$7$?$H$7$F$b\u001b(J\n\u001b$@85$NJ*BN$O2?$N1F6A$b<u$1$J$$!#$3$NJ}K!$r:N$C$?7k2L$H$7$F!\"Hs>o$KJ#;($J\u001b(J\n\u001b$@J*BN$HC1=c$JJ*BN$NOB$r$H$k$h$&$J>l9g$K$O!\"A4BN$NJ#@=$,:n$jD>$5$l$k$3$H\u001b(J\n\u001b$@$+$i=hM}$K;~4V$,$+$+$k!#\u001b(J\n\n\u001b$@8=:_$N%P!<%8%g%s$G$O!\"=89g1i;;$r;\\$9\u001b(J2\u001b$@J*BN$N$$$E$l$+$NLL$I$&$7$,F10l\u001b(J\n\u001b$@J?LL>e$K:\\$C$F$$$k!\"$\"$k$$$O!\"Hs>o$K6a$$MM$J>l9g$K$O!\"=89g1i;;$,=PMh$J$$!#\u001b(J\n\\clearpage\n\\subsection{\u001b$@J*BN4V$N@\\?($K$h$k94B+$NF3=P\u001b(J}\n\n\\subsubsection{\u001b$@%\"%k%4%j%:%`$N35MW\u001b(J}\n\u001b$@J*BN$,<+M36u4V$K$\"$k$H$9$k$H!\"$=$NJ*BN$K$OG$0U$NHy>.JQ0L$,2DG=$G$\"$k$,!\"\u001b(J\n\u001b$@B>$NJ*BN$KBP$7$FNO$rH/@8$9$k$3$H$O=PMh$J$$!#\u001b(J\n\u001b$@5U$K!\"J*BN$,==J,=E$$J*BN$K8GDj$5$l$F$$$k>l9g$O!\"$=$NJ*BN$OJQ0L$9$k$3$H$O\u001b(J\n\u001b$@=PMh$J$$$,!\"8GDj$7$F$$$kJ*BN$KBP$7$FG$0U$NNO$rH/@8$9$k$3$H$,2DG=$G$\"$k!#\u001b(J\n\u001b$@$3$NN>6KC<$N4V$N>uBV$H$7$F!\"N>B&94B+$5$l$?J*BN$N>l9g$r9M$($k$H!\"\u001b(J\n\u001b$@94B+>r7o$OHy>.JQ0L$HNO$K4X$9$kF1<!J}Dx<0$K$J$j!\"\u001b(J\n\u001b$@$=$N2r$G$\"$k5v$5$l$kHy>.JQ0L$N=89g$HH/@82DG=$JNO$N=89g$OD>8rJd6u4V$K$J$k!#\u001b(J\n\u001b$@$^$?!\"J*BN$,JRB&94B+$5$l$F$$$k>l9g$O!\"J*BN$KBP$9$k94B+>r7o$OF1<!ITEy<0$K$J$j!\"\u001b(J\n\u001b$@5v$5$l$kHy>.JQ0L$HH/@82DG=$JNO$N=89g$OAPBPFLB?LL?m$K$J$k!#\u001b(J\n\n\u001b$@K\\@a$G$O!\"$3$l$iJRB&94B+$dN>B&94B+$r6hJL$9$k$3$H$J$/!\"\u001b(J\n\u001b$@G$0U$N7A>u$NB?LLBN$,B>$NB?LLBN$KG$0U$N>uBV$G@\\?($7$F$$$k>l9g$K!\"\u001b(J\n\u001b$@$=$NEy2A94B+E@$N0LCV$H!\"3F!9$NE@$K$*$1$k94B+>r7o$r5a$a$k%W%m%0%i%`\u001b(J\n\u001b$@$K$D$$$F@bL@$9$k!#\u001b(J\n\u001b$@%H%C%W%l%Y%k$N$_;H$&IaDL$N%f!<%6!<$O!\"\u001b(Jc-body\u001b$@$N@bL@$N$_FI$a$P==J,$G$\"$k!#\u001b(J\n\u001b$@$3$l$i$N%W%m%0%i%`$r;H$&$?$a$K$O!\"\u001b(J\n$eus/llib/model2const.l$\\ \u001b$@$r%m!<%I$9$kI,MW$,$\"$k!#\u001b(J\n\u001b$@%W%m%0%i%`$NA4BN9=B$$r\u001b(JFig.\\ref{fig:constraint-program}\u001b$@$K<($9!#\u001b(J\n\n\\begin{figure}[h]\n\\begin{center}\n\\epsfile{file=fig-program.ps,width=8cm}\n\\end{center}\n\\caption{Structure of the Algorithm}\n\\label{fig:constraint-program}\n\\end{figure}\n\\vfill\n\\clearpage\n\\subsubsection{\u001b$@%$%s%W%j%a%s%F!<%7%g%s\u001b(J}\n\\vspace{1.0cm}\n{\\jLarge c-body}\n\\\\ [0.5cm]\n\\begin{description}\n\n\\item[{\\jlarge \\bf description}]\\hspace{1cm}\n\\begin{description}\n\\item[] \u001b$@94B+>r7o$r3JG<$9$k%9%m%C%H$rDI2C$7$?\u001b(Jbody\u001b$@$N%5%V%/%i%9\u001b(J\n\\end{description}\n\n\\item[{\\jlarge \\bf super class}]\\hspace{1cm}\n\\begin{description}\n\\item[body] ()\n\\end{description}\n\n\\item[{\\jlarge \\bf slots}]\\hspace{1cm}\n\\begin{description}\n\\item[constraint] \u001b$@Ey2A94B+E@$H94B+>r7o\u001b(J\n\\end{description}\n\n\\item {\\jlarge \\bf methods}\n\\\\ [0.5cm]\n{\\bf :constraint (b)} self\u001b$@$H\u001b(Jb\u001b$@$NEy2A94B+E@$H94B+%Y%/%H%k$r5a$a$k\u001b(J \n\\begin{enumerate}\n\\item {\\bf if}\\ self\u001b$@$HB?LLBN\u001b(Jb\u001b$@$N3F!9$N6K>.H\"$,43>D$7$J$$\u001b(J\\ {\\bf then}\n\\begin{description}\n\\item self\u001b$@$OB?LLBN\u001b(Jb\u001b$@$H@\\?($7$F$$$J$$\u001b(J\n\\item \u001b$@%\"%k%4%j%:%`=*N;\u001b(J\n\\end{description}\n\\item {\\bf if} b\u001b$@$+$i<u$1$k94B+$r4{$K5a$a$F$$$k\u001b(J {\\bf then} return constraint\n\\item mycontact\\ $\\leftarrow$\\ (send self {\\bf :contact-vertices} b)\\ $+$\\ \n(send self {\\bf :contact-edges} b)\n\\item hiscontact\\ $\\leftarrow$\\ (send b {\\bf :contact-vertices} self)\\ $+$\\ \n(send b {\\bf :contact-edges} self)\n\\item constraint $\\leftarrow$ constraint $+$\n{\\bf contact-to-constraint}\\ (mycontact\\ hisconstact)\n\\item return constraint\n\\end{enumerate}\n{\\bf :contact (b)} self\u001b$@$H\u001b(Jb\u001b$@$N@\\?($NEy2A94B+E@$rJV$9!#\u001b(J\n\\begin{enumerate}\n\\item {\\bf if} b\u001b$@$+$i<u$1$k94B+$r4{$K5a$a$F$$$k\u001b(J {\\bf then} \nreturn \u001b$@Ey2A94B+E@\u001b(J\n\\item constraint $\\leftarrow$ constraint $+$ (send self {\\bf :constraint} b)\n\\item return b\u001b$@$+$i<u$1$k94B+$NEy2A94B+E@$N0LCV$N%j%9%H\u001b(J\n\\end{enumerate}\n{\\bf :draw-constraint (\\&optional b (arrow-length 30.0))}\nb\u001b$@$+$i<u$1$k94B+>r7o$rLp0u$G2hLL$KI=<($9$k!#\u001b(J\nb\u001b$@$r;XDj$7$J$$$H!\"$3$l$^$G$K5a$a$?94B+$rA4$FI=<($9$k!#\u001b(J\n\u001b$@Lp0u$ND9$5$r\u001b(Jarrow-length\u001b$@$G;XDj$9$k$3$H$b=PMh$k!#\u001b(J\n\\vfill\n\\clearpage\n{\\bf :contact-vertices (b)} b\u001b$@$K@\\?($7$F$$$k\u001b(Jself\u001b$@$ND:E@!\"\u001b(J\n\u001b$@BP1~$9$k\u001b(Jb\u001b$@$N@\\?(LL!\"FL=89g$NOB=89g$GI=8=$7$?\u001b(Jself\u001b$@$N6aK5$r5a$a$k\u001b(J\n\\begin{enumerate}\n\\item cbox\\ $\\leftarrow$\\ self\u001b$@$HB?LLBN\u001b(Jb\u001b$@$N3F!9$N6K>.H\"$N6&DL=89g\u001b(J\n\\item {\\bf if}\\ cbox\u001b$@$,6u=89g\u001b(J\\ {\\bf then}\n\\begin{description}\n\\item self\u001b$@$OB?LLBN\u001b(Jb\u001b$@$H@\\?($7$F$$$J$$\u001b(J\n\\item \u001b$@%\"%k%4%j%:%`=*N;\u001b(J\n\\end{description}\n\\item myvertices\\ $\\leftarrow$\\ cbox\u001b$@$K4^$^$l$k\u001b(Jself\u001b$@$ND:E@$N%j%9%H\u001b(J\n\\item hisfaces\\ $\\leftarrow$\\ cbox\u001b$@$K4^$^$l$k\u001b(Jb\u001b$@$NLL$N%j%9%H\u001b(J\n\\item {\\bf for\\ each}\\ v\\ $\\leftarrow$\\ myvertices\u001b$@$NA4$F$NMWAG\u001b(J\n\\begin{description}\n\\item {\\bf if}\\ v\u001b$@$,!\"\u001b(Jhisfaces\u001b$@$N$I$l$+$K@\\?($7$F$$$k\u001b(J\\ {\\bf then}\nconp\\ $\\leftarrow$\\ conp\\ $+$\\ (self\u001b$@$N@\\?(D:E@\u001b(Jv\\ \\ b\u001b$@$N@\\?(LL$N0l$D\u001b(J)\n\\end{description}\n\\item {\\bf for\\ each}\\ p\\ $\\leftarrow$\\ conp\u001b$@$NA4$F$NMWAG\u001b(J\n\\begin{description}\n\\item p\\ $\\leftarrow$\\ (self\u001b$@$N@\\?(D:E@\u001b(J\\ \\ b\u001b$@$N@\\?(LL$N0l$D\u001b(J\n\\ \\ self\u001b$@$N@\\?(D:E@$rC<E@$H$9$kNG$N%j%9%H\u001b(J)\n\\end{description}\n\\item {\\bf for\\ each}\\ p\\ $\\leftarrow$\\ conp\u001b$@$NA4$F$NMWAG\u001b(J\n\\begin{description}\n\\item (send p {\\bf :to-convex})\n\\end{description}\n\\item return\\ conp\n\\end{enumerate}\n\\begin{itemize}\n\\item \u001b$@%9%F%C%W#6$O!\"\u001b(Jself\u001b$@$N@\\?(D:E@$K!\"$=$l$,:\\$k\u001b(Jself\u001b$@$NNG$X$N%P%C%/%]%$%s%?\u001b(J\n\u001b$@$rIU$1$F$$$k!#\u001b(J\n\\item \u001b$@%9%F%C%W#7$O!\"\u001b(Jself\u001b$@$N6aK5$,FL$G$J$$>l9g$K!\"$=$l$rFL=89g$NOB=89g$K\u001b(J\n\u001b$@JQ49$7$F$$$k!#\u001b(J\n\\end{itemize}\n{\\bf :contact-edges (b)} b\u001b$@$K@\\?($7$F$$$k\u001b(Jself\u001b$@$NNG$NFbE@!\"\u001b(J\n\u001b$@BP1~$9$k\u001b(Jb\u001b$@$N@\\?(LL!\"FL=89g$NOB=89g$GI=8=$7$?\u001b(Jself\u001b$@$N6aK5$r5a$a$k\u001b(J\n\\begin{enumerate}\n\\item cbox\\ $\\leftarrow$\\ self\u001b$@$HB?LLBN\u001b(Jb\u001b$@$N3F!9$N6K>.H\"$N6&DL=89g\u001b(J\n\\item {\\bf if}\\ cbox\u001b$@$,6u=89g\u001b(J\\ {\\bf then}\n\\begin{description}\n\\item self\u001b$@$OB?LLBN\u001b(Jb\u001b$@$H@\\?($7$F$$$J$$\u001b(J\n\\item \u001b$@%\"%k%4%j%:%`=*N;\u001b(J\n\\end{description}\n\\item myedges\\ $\\leftarrow$\\ cbox\u001b$@$K4^$^$l$k\u001b(Jself\u001b$@$NNG$N%j%9%H\u001b(J\n\\item hisfaces\\ $\\leftarrow$\\ cbox\u001b$@$K4^$^$l$k\u001b(Jb\u001b$@$NLL$N%j%9%H\u001b(J\n\\item {\\bf for\\ each}\\  e\\ $\\leftarrow$\\ myedges\u001b$@$NA4$F$NMWAG\u001b(J\n\\begin{description}\n\\item {\\bf for\\ each}\\ f\\ hisfaces\u001b$@$NA4$F$NMWAG\u001b(J\n\\begin{description}\n\\item {\\bf if} e\u001b$@$,J?9T$G$J$$LL\u001b(Jf\u001b$@$N$I$l$+$NNG$H@\\?($7$F$$$k!\"$+$D!\"\u001b(J\n\u001b$@@\\?(E@$,\u001b(Jconp\u001b$@$NMWAG$G$O$J$$\u001b(J\\ {\\bf then}\n\\begin{description}\n\\item {\\bf if}\\ e\u001b$@$N\u001b(J2\u001b$@LL3Q$NJ?LL3Q$,\u001b(J\\ $\\pi$\\ \u001b$@$h$j>.$5$$\u001b(J\\ {\\bf then}\n\\begin{description}\n\\item conp\\ $\\leftarrow$\\ conp\\ $+$\\ \n(\u001b$@@\\?($7$F$$$k\u001b(Jself\u001b$@$NNG>e$NE@\u001b(J\\ \\ b\u001b$@$N@\\?(LL$N0l$D\u001b(J\\ \\ ((\u001b$@@\\?($7$F$$$k\u001b(Jself\u001b$@$NNG\u001b(J)))\n\\end{description}\n\\item {\\bf else}\n\\begin{description}\n\\item conp\\ $\\leftarrow$\\ conp\\ $+$\\ \n(\u001b$@@\\?($7$F$$$k\u001b(Jself\u001b$@$NNG>e$NE@\u001b(J\\ \\ b\u001b$@$N@\\?(LL$N0l$D\u001b(J\n\\ \\ ((\u001b$@@\\?($7$F$$$k\u001b(Jself\u001b$@$NNG$N\u001b(Jp\u001b$@LL\u001b(J)\\ (\u001b$@@\\?($7$F$$$k\u001b(Jself\u001b$@$NNG$N\u001b(Jn\u001b$@LL\u001b(J)))\n\\end{description}\n\\end{description}\n\\end{description}\n\\end{description}\n\\item return\\ conp\n\\end{enumerate}\n\n\\end{description}\n\\vfill\n\\clearpage\n{\\Large surrounding-box}\n\\\\ [0.5cm]\n{\\jlarge \\bf methods}\n\\begin{description}\n\\item[{\\bf :contact(box)}]\nself\u001b$@$H\u001b(Jbox\u001b$@$,@\\?($7$F$$$k$+$I$&$+$r%A%'%C%/$9$k!#@\\?($7$F$$$k>l9g$O!\"\u001b(J\n\u001b$@N><T$N6&DLH\"$r!\"$7$F$$$J$$>l9g$O\u001b(Jnil\u001b$@$rJV$9!#\u001b(J\n\\begin{enumerate}\n\\item clearance\\ $\\leftarrow$\\ \u001b$@Hy>.%Y%/%H%k\u001b(J\n\\item v1\\ $\\leftarrow$\\ (max\\ self\u001b$@$N:G>.E@\u001b(J\\ box\u001b$@$N:G>.E@\u001b(J)\\ $-\\ clearance$\n\\item v2\\ \\ $\\leftarrow$\\ (min\\ self\u001b$@$N:GBgE@\u001b(J\\ box\u001b$@$N:G>.E@\u001b(J)\\ $+\\ clearance$\n\\item {\\bf if}\\ v1\u001b$@$,\u001b(Jv2\u001b$@$h$j>.$5$$\u001b(J\\ {\\bf then}\n\\begin{description}\n\\item return\\ v1\u001b$@$r:G>.E@!\"\u001b(Jv2\u001b$@$r:GBgE@$H$9$kH\"\u001b(J\n\\item {\\bf else}\\ return\\ nil\n\\end{description}\n\\end{enumerate}\n\\end{description}\n\\vfill\n\\clearpage\n{\\Large edge}\n\\\\ [0.5cm]\n{\\jlarge \\bf methods}\n\\\\ [0.5cm]\n{\\bf :boxcontact(box)}self\u001b$@$,\u001b(Jbox\u001b$@$H@\\?($7$F$$$k$+$I$&$+$r%A%'%C%/$9$k!#\u001b(J\n\u001b$@@\\?($7$F$$$k$H$-$ON><T$N6&DLH\"$r!\"$7$F$$$J$$$H$-$O\u001b(Jnil\u001b$@$rJV$9!#\u001b(J\n\\begin{enumerate}\n\\item return\\ (send\\ box\\ {\\bf :contact}\\ self\u001b$@$r4^$`:G>.H\"\u001b(J)\n\\end{enumerate}\n{\\bf :neighborpoints(point)}self\u001b$@$N6aK5$rI=$9<!$N#3E@$N%j%9%H$rJV$9!#\u001b(J\nself\u001b$@>e$NE@$G\u001b(Jpoint\u001b$@$H$O0[$J$kE@!\"\u001b(Jself\u001b$@$N\u001b(Jpface\u001b$@>e$NE@!\"\u001b(Jself\u001b$@$N\u001b(Jnface\u001b$@>e$NE@!#\u001b(J\n\\begin{enumerate}\n\\item p1\\ $\\leftarrow$\\ (send\\ self\\ {\\bf :anothervertex}\\ point)\n\\item p2\\ \\ $\\leftarrow$\\ $point\\ +\\ pface$\u001b$@$NK!@~%Y%/%H%k\u001b(J\\ $\\times\\ \n(pvert\\ -\\ nvert)$\n\\item p3\\ \\ $\\leftarrow$\\ $point\\ +\\ nface$\u001b$@$NK!@~%Y%/%H%k\u001b(J\\ $\\times\\ \n(nvert\\ -\\ pvert)$\n\\item return\\ (p1\\ p2\\ p3)\n\\end{enumerate}\n{\\bf :contact(e)}self\u001b$@$NFbE@$HNG\u001b(Je\u001b$@$H$N@\\?(E@$r5a$a$k!#\u001b(J\n\u001b$@@\\?($7$F$$$J$$>l9g$O!\"\u001b(Jnil\u001b$@$rJV$9!#\u001b(J\n\\begin{enumerate}\n\\item {\\bf if}\\ self\u001b$@$H\u001b(Je\u001b$@$,3F!9:\\$k#2D>@~$,J?9T\u001b(J\\ {\\bf then}\\ return\\ nil\n\\begin{description}\n\\item p1\\ $\\leftarrow$\\ self\u001b$@$H\u001b(Je\u001b$@$,3F!9:\\$k#2D>@~$N6&DL?b@~$N!\"\u001b(Jself\u001b$@B&$NB-\u001b(J\n\\item p2\\ $\\leftarrow$\\ self\u001b$@$H\u001b(Je\u001b$@$,3F!9:\\$k#2D>@~$N6&DL?b@~$N!\"\u001b(Je\u001b$@B&$NB-\u001b(J\n\\item {\\bf if}\\ p1\u001b$@$H\u001b(Jp2\u001b$@$N5wN%$,Hy>.CM$h$j>.$5$$!\"\u001b(J\np1\u001b$@$,\u001b(Jself\u001b$@$NN>C<E@$h$jHy>.5wN%0J>eFbB&!\"$+$D!\"\u001b(J\\\\\np2\u001b$@$,\u001b(Je\u001b$@$NN>C<E@$h$jHy>.5wN%0J>e30B&$G$O$J$$\u001b(J\n\\ {\\bf then}\\ return\\ p1\n\\end{description}\n\\end{enumerate}\n\\begin{itemize}\n\\item self\u001b$@$H\u001b(Je\u001b$@$,=E$J$k>l9g$O!\"\u001b(Jself\u001b$@$OI,$:B>$NNG$H8r:9$9$k$N$G!\"\u001b(J\n\u001b$@@\\?(E@$r=P$9I,MW$O$J$$!#\u001b(J\n\\item p1\u001b$@$H\u001b(Jself\u001b$@$NN>C<E@$N5wN%$,Hy>.5wN%0J2<$N>l9g$O!\"\u001b(J\nself\u001b$@$ND:E@$HNG\u001b(Je\u001b$@$N@\\?($KAjEv$9$k$N$G!\"@\\?(E@$r=P$9I,MW$O$J$$!#\u001b(J\n\\item p2\u001b$@$,NG\u001b(Je\u001b$@$NHy>.5wN%L$K~30B&$N>l9g$r4^$a$J$$$H!\"\u001b(J\n\u001b$@?tCM7W;;8m:9$G@\\?(E@$,5a$^$i$J$$$3$H$,$\"$k!#\u001b(J\n\\end{itemize}\n{\\bf :anothervertex(point)}point\u001b$@$HF10lE@$G$O$J$$\u001b(Jself\u001b$@$rC<E@$rJV$9!#\u001b(J\n\\begin{enumerate}\n\\item {\\bf if}\\ pvert\u001b$@$H\u001b(Jpoint\u001b$@$N5wN%$,Hy>.5wN%$h$jBg$-$$\u001b(J\\ {\\bf then}\\ \n\\begin{description}\n\\item return\\ pvert\n\\item {\\bf else}\\ nvert\n\\end{description}\n\\end{enumerate}\n\\vfill\n\\clearpage\n{\\Large plane}\\\\\n\\\\ [0.5cm]\n{\\jlarge \\bf methods}\n\\\\ [0.5cm]\n{\\bf :separation(mypoints\\ hispoints)}\n\u001b$@LL\u001b(Jself\u001b$@$,\u001b(Jmypoints\u001b$@$H\u001b(Jhispoints\u001b$@$NJ,N%LL$K$J$k$+$I$&$+$r%A%'%C%/$9$k!#\u001b(J\n\u001b$@J,N%LL$K$J$k>l9g$O!\"\u001b(Jmypoints\u001b$@B&$K8~$/MM$KId9g$r9g$o$;$?!\"\u001b(Jself\u001b$@$N\u001b(J\n\u001b$@K!@~%Y%/%H%k$rJV$9!#J,N%LL$K$J$i$J$$>l9g$O!\"\u001b(Jnil\u001b$@$rJV$9\u001b(J\n\\begin{enumerate}\n\\item {\\bf if}\\ mypoints\u001b$@$NA4$F$NE@$N\u001b(Jself\u001b$@$+$i$N5wN%$,F1Id9g\u001b(J\\ {\\bf then}\n\\begin{description}\n\\item sign\\ $\\leftarrow$\\ \u001b$@5wN%$NId9g\u001b(J\n\\item {\\bf if}\\ hispoints\u001b$@$NA4$F$NE@$N\u001b(Jself\u001b$@$+$i$N5wN%$,F1Id9g\u001b(J\\ {\\bf then}\n\\begin{description}\n\\item return\\ sign\\ $\\times$\\ self\u001b$@$NK!@~%Y%/%H%k\u001b(J\n\\end{description}\n\\end{description}\n\\item return\\ nil\n\\end{enumerate}\n\\vspace{2.0cm}\n{\\Large closed-region}\\\\\n\\\\ [0.5cm]\n{\\jlarge \\bf methods}\n\\\\ [0.5cm]\n{\\bf :boxcontact(box)}self\u001b$@$,\u001b(Jbox\u001b$@$H@\\?($7$F$$$k$+$I$&$+$r%A%'%C%/$9$k!#\u001b(J\n\u001b$@@\\?($7$F$$$k$H$-$ON><T$N6&DLH\"$r!\"$7$F$$$J$$$H$-$O\u001b(Jnil\u001b$@$rJV$9!#\u001b(J\n\\begin{enumerate}\n\\item return\\ (send\\ box\\ {\\bf :contact}\\ self\u001b$@$r4^$`:G>.H\"\u001b(J)\n\\end{enumerate}\n{\\bf :contactp(p)}\u001b$@E@\u001b(Jp\u001b$@$,\u001b(Jself\u001b$@$K@\\?($7$F$$$k$+$I$&$+$r%A%'%C%/$9$k!#\u001b(J\n\u001b$@@\\?($7$F$$$k$H$-$O\u001b(Jinside\u001b$@!\"6-3&>e$N$H$-$O\u001b(Jborder\u001b$@!\"@\\?($7$F$$$J$$$H$-$O\u001b(J\noutside\u001b$@$rJV$9!#\u001b(J\n\\begin{enumerate}\n\\item d\\ $\\leftarrow$\\ p\u001b$@$H\u001b(Jself\u001b$@$H$N5wN%\u001b(J\n\\item {\\bf if}\\ d\u001b$@$,Hy>.CM$h$jBg$-$$\u001b(J\\ {\\bf then}\\ return\\ outside\n\\item {\\bf else}\n\\begin{description}\n\\item point\\ $\\leftarrow$\\ p\u001b$@$+$i\u001b(Jself\u001b$@$X9_$m$7$??b@~$NB-\u001b(J\n\\item {\\bf for each} e $\\leftarrow$ self\u001b$@$N\u001b(Jedges\n\\begin{description}\n\\item {\\bf if} (send e {\\bf :distance} point)\u001b$@$,Hy>.CM$h$j>.$5$$\u001b(J\n{\\bf then} return border\n\\end{description}\n\\item return\\ (send\\ self\\ {\\bf :insidep}\\ ip)\n\\end{description}\n\\end{enumerate}\n\\vfill\n\\clearpage\n{\\Large face}\\\\\n\\\\ [0.5cm]\n{\\jlarge \\bf methods}\n\\\\ [0.5cm]\n{\\bf :contactp(p)}\u001b$@E@\u001b(Jp\u001b$@$,\u001b(Jself\u001b$@$K@\\?($7$F$$$k$+$I$&$+$r%A%'%C%/$9$k!#\u001b(J\n\u001b$@@\\?($7$F$$$k$H$-$O\u001b(Jinside\u001b$@!\"6-3&>e$N$H$-$O\u001b(Jborder\u001b$@!\"@\\?($7$F$$$J$$$H$-$O\u001b(J\noutside\u001b$@$rJV$9!#\u001b(J\n\\begin{enumerate}\n\\item result $\\leftarrow$ (send-super {\\bf :contactp} p)\n\\item {\\bf if} result\u001b$@$,\u001b(Jinside\u001b$@$G$O$J$$\u001b(J {\\bf then} return result\n\\item {\\bf for each} h $\\leftarrow$ self\u001b$@$N\u001b(Jholes\n\\begin{description}\n\\item result $\\leftarrow$ (send h {\\bf :contactp} p)\n\\item {\\bf if} result\u001b$@$,\u001b(Jinside {\\bf then} return outside\n\\item {\\bf if} result\u001b$@$,\u001b(Jborder {\\bf then} return border\n\\item return inside\n\\end{description}\n\\end{enumerate} \n{\\bf :contact-edge(e1)}\u001b$@NG\u001b(Je1\u001b$@$H\u001b(Jself\u001b$@$,J?9T$G$J$$$H$-!\"\u001b(J\ne1\u001b$@$H\u001b(Jself\u001b$@$N$I$l$+$NNG$H$N@\\?(E@$rJV$9\u001b(J\n\\begin{enumerate}\n\\item {\\bf if}\\ e1\u001b$@$H\u001b(Jself\u001b$@$,J?9T\u001b(J\\ {\\bf then}\\ return\\ nil\n\\item {\\bf for\\ each}\\ e2\\ $\\leftarrow$\\ self\u001b$@$N\u001b(Jedges\n\\begin{description}\n\\item foot\\ $\\leftarrow$\\ (send\\ e1\\ {\\bf :contact}\\ e2)\n\\item {\\bf if}\\ foot\u001b$@$,\u001b(Jnil\u001b$@$G$J$$\u001b(J\\ {\\bf then}\\ return\\ foot \n\\end{description}\n\\end{enumerate}\n\\vfill\n\\clearpage\n{\\jLarge constrained-point}\n\\\\ [0.5cm]\n\\begin{description}\n\\item[{\\jlarge \\bf description}]\\hspace{1cm}\n\\begin{description}\n\\item[] \u001b$@Ho94B+E@$N%/%i%9\u001b(J\n\\end{description}\n\n\\item[{\\jlarge \\bf super class}]\\hspace{1cm}\n\\begin{description}\n\\item[object] ()\n\\end{description}\n\n\\item[{\\jlarge \\bf slots}]\\hspace{1cm}\n\\begin{description}\n\\item[myvertex] \u001b$@Ho94B+E@$N:BI8\u001b(J\n\\item[hisface] \u001b$@Ho94B+E@$K$*$1$k94B+J*BN$NLL$N0l$D\u001b(J\n\\item[myneighborhood] \u001b$@Ho94B+E@$K$*$1$k<+J,$N6aK5\u001b(J\n\\end{description}\n\n\\end{description}\n{\\jlarge \\bf methods}\\\\\n\\begin{description}\n\\item[:to-convex\\ ()] self\u001b$@$N6aK5$rFL6aK5$NOB$KJ,2r$9$k\u001b(J \n\\begin{enumerate}\n\\item count\\ $\\leftarrow$\\ self\u001b$@$N6aK5$N\u001b(Jor-edge\u001b$@$N?t\u001b(J\n\\item {\\bf if}\\ count=0\\ {\\bf then}\n\\begin{description}\n\\item self\u001b$@$N6aK5\u001b(J\\ $\\leftarrow$\\ \n(vertex\\ hisface\\ ((myedge11\\ and\\ myedge12\\ $\\cdots$)))\n\\end{description}\n{\\bf else}\n\\begin{description}\n\\item {\\bf if}\\ count=1\\ {\\bf then}\n\\begin{description}\n\\item (send\\ self\\ {\\bf :divide1}\\ or-edge)\n\\end{description}\n\\item {\\bf else}\n\\begin{description}\n\\item (send\\ self\\ {\\bf :dividen}\\ or-edge)\n\\end{description}\n\\end{description}\n\\end{enumerate}\n\\item[:divide1\\ (or-edge)] or-edge\u001b$@$,0l$D$@$1$\"$k\u001b(Jself\u001b$@$N6aK5$r\u001b(Jor-edge\u001b$@$N\u001b(J\np-face\u001b$@$H\u001b(Jn-face\u001b$@$N3F!9$G@ZCG$7$?FL6aK5$r5a$a!\"$=$l$i$N%j%9%H$G\u001b(J\n{\\bf myneighborhood}\u001b$@%9%m%C%H$r<!$N7A$KCV49$9$k!#\u001b(J\\\\\n((myedge11\\ and\\ myedge12\\ $\\cdots$)\\ or\\ (myedge21\\ and\\ myedge22\\ $\\cdots$))\n\\\\\n\\begin{enumerate}\n\\item {\\bf for\\ each}\\ or-edge-face\\ $\\leftarrow$\\ or-edge\u001b$@$N\u001b(Jp-face\u001b$@$H\u001b(Jn-face\n\\begin{description}\n\\item eset\\ $\\leftarrow$\\ or-edge-face\u001b$@$N30$K=P$J$$!\"6aK5$N\u001b(Jand-edge\u001b$@$N%j%9%H\u001b(J\n\\item flist\\ $\\leftarrow$\\ or-edge-face\u001b$@$N30$K=P$J$$!\"6aK5$N\u001b(Jface\u001b$@$N%j%9%H\u001b(J\n\\item {\\bf if}\\ flist\u001b$@$NMWAG?t$,\u001b(J2\u001b$@$h$jB?$$\u001b(J\\ {\\bf then}\n\\begin{description}\n\\item ip\\ $\\leftarrow$\\ or-edge-face\u001b$@$K@ZCG$5$l$?LL$NNG$G!\"\u001b(Jself\u001b$@$N\u001b(Jmyvertex\u001b$@$r\u001b(J\n\u001b$@C<E@$K$7$J$$NG$H\u001b(Jor-edge-face\u001b$@$N8rE@\u001b(J\n\\item {\\bf if}\\ ip\u001b$@$HNY$N\u001b(Jand-edge\u001b$@$H$N5wN%$,>/$7$O$\"$k\u001b(J\\ {\\bf then}\n\\begin{description}\n\\item self\u001b$@$N\u001b(Jmyvertex\u001b$@$H\u001b(Jip\u001b$@$rN>C<E@$H$9$kNG$r\u001b(Jeset\u001b$@$KDI2C$9$k\u001b(J\n\\end{description}\n\\end{description}\n\\item esets\\ $\\leftarrow$\\ esets\\ $+$\\ eset\n\\end{description}\n\\item {\\bf myneighborhood}\\ $\\leftarrow$\\ esets\n\\end{enumerate}\n\\item[:dividen\\ (or-edge)] or-edge\u001b$@$,\u001b(J2\u001b$@$D0J>e$\"$k6aK5$rFL6aK5$KJ,3d$7!\"\u001b(J\n\u001b$@$=$l$i$N%j%9%H$G\u001b(J{\\bf myneighborhood}\u001b$@%9%m%C%H$r<!$N7A$KCV49$9$k!#\u001b(J\\\\\n((myedge11\\ and myedge12$\\cdots$)\\ or\\ (myedge21\\ and\\ myedge22$\\cdots$)\n\\ $\\cdots$\\ (face1)\\ or\\ (face2)\\ $\\cdots$))\\\\\n\n\\begin{enumerate}\n\\item elist\\ $\\leftarrow$\\ \u001b$@6aK5$rI=$9\u001b(Jedge\u001b$@$N%j%9%H$+$i%9%?!<%H\u001b(J\n\u001b$@$N\u001b(Jor-edge\u001b$@$r=|$$$?%j%9%H\u001b(J\n\\item flist\\ $\\leftarrow$\\ (\u001b$@%9%?!<%H$N\u001b(Jor-edge\u001b$@$N0lJ}$NLL\u001b(J)\n\\item {\\bf while}\\ elist\u001b$@$,6u%j%9%H$G$J$$\u001b(J\\ {\\bf do}\n\\begin{description}\n\\item ee\\ $\\leftarrow$\\ flist\u001b$@$N@hF,MWAG$NLL$X$N%P%C%/%]%$%s%?$N$D$$$?NG\u001b(J\n\\item anotherface\\ $\\leftarrow$\\ ee\u001b$@$NH?BPB&$NLL\u001b(J\n\\item {\\bf if}\\ ee\u001b$@$,\u001b(Jand-edge\\ {\\bf then}\n\\begin{description}\n\\item flist\\ $\\leftarrow$\\ flist\\ $+$\\ anotherface\n\\item eset\\ $\\leftarrow$\\ eset\\ $+$\\ ee\n\\end{description}\n\\item {\\bf else}\\ ;\\ ee\u001b$@$,\u001b(Jor-edge\u001b$@$N>l9g\u001b(J\n\\begin{description}\n\\item {\\bf if}\\ eset\u001b$@$KNG$,4^$^$l$k\u001b(J\\ {\\bf then}\n\\begin{description}\n\\item {\\bf if}\\ flist\u001b$@$NMWAG?t$,\u001b(J2\u001b$@$h$jB?$$\u001b(J\\ {\\bf then}\n\\begin{description}\n\\item n-point\\ $\\leftarrow$\\ flist\u001b$@$N@hF,$H:G8e$NMWAG$NLL$N8r@~>e\u001b(J\n\u001b$@$K$\"$j!\"6aK5$N6-3&LL>e$K$\"$kE@\u001b(J\n\\item eset\\ $\\leftarrow$\\ eset\\ $+$\\ \u001b$@@\\?(E@$H\u001b(Jn-point\u001b$@$rC<E@$H$7!\"\u001b(Jflist\u001b$@$N\u001b(J\n\u001b$@@hF,$H:G8e$NLL$K%P%C%/%]%$%s%?$r;}$C$?NG\u001b(J\n\\end{description}\n\\item esets\\ $\\leftarrow$\\ esets + eset\n\\end{description}\n\\item {\\bf else}\n\\begin{description}\n\\item esets\\ $\\leftarrow$\\ esets\\ $+$\\ flist\n\\end{description}\n\\item eset\\ $\\leftarrow$\\ \u001b$@6u%j%9%H\u001b(J\n\\item flist\\ $\\leftarrow$\\ anotherface\n\\end{description}\n\\item elist\\ $\\leftarrow$\\ elist\\ $-$\\ ee\n\\end{description}\n\\item {\\bf if}\\ eset\u001b$@$KNG$,4^$^$l$k\u001b(J\\ {\\bf then}\n\\begin{description}\n\\item esets\\ $\\leftarrow$\\ esets\\ $+$\\ eset\n\\item {\\bf else}\n\\begin{description}\n\\item esets\\ $\\leftarrow$\\ esets\\ $+$\\ flist\n\\end{description}\n\\end{description}\n\\item {\\bf myneighborhood}\\ $\\leftarrow$\\ esets\n\\end{enumerate}\n\\vfill\n\\clearpage\n\\item[:analyse-contact(hispoint)]\n\u001b$@<+J,$N@\\?(E@$H$=$N6aK5$rI=$9\u001b(Jself\u001b$@$HAj<j$N@\\?(E@$H$=$N6aK5$rI=$9\u001b(Jhispoint\n\u001b$@$+$i!\"<+J,$KBP$9$k@\\?(>r7o$r5a$a$k\u001b(J\n\\begin{enumerate}\n\\item {\\bf for\\ each}\\ $(mine,his)$\\ $\\leftarrow$\\ self\u001b$@$N9=@.MWAG$NFL6aK5$H\u001b(J\nhispoint\u001b$@$N9=@.MWAG$NFL6aK5$NA4$F$NAH9g$;\u001b(J\n\\begin{description}\n\\item {\\bf if}\\ mine\u001b$@$,LL\u001b(J\\ {\\bf then}\\ and-cond\\ $\\leftarrow$\\ \nand-cond\\ $+$\\ {\\bf face-contact}(mine\\ -1.0)\n\\end{description}\n\\begin{description}\n\\item {\\bf if}\\ his\u001b$@$,LL\u001b(J\\ {\\bf then}\\ and-cond\\ $\\leftarrow$\\ \nand-cond\\ $+$\\ {\\bf face-contact}(his\\ 1.0)\n\\end{description}\n\\begin{description}\n\\item {\\bf if}\\ \u001b$@NG$HNG$N@\\?(\u001b(J\\ {\\bf then}\\ and-cond\\ $\\leftarrow$\\ \nand-cond\\ $+$\\ {\\bf edge-edge-contact}(\u001b$@@\\?(E@\u001b(J\\ mine\\ his)\n\\item {\\bf if}\\ \u001b$@NG$HD:E@$N@\\?(\u001b(J\\ {\\bf then}\\ and-cond\\ $\\leftarrow$\\ \nand-cond\\ $+$\\ {\\bf edge-vertex-contact}(\u001b$@@\\?(E@\u001b(J\\ mine\\ his)\n\\item {\\bf if}\\ \u001b$@D:E@$HNG$N@\\?(\u001b(J\\ {\\bf then}\\ and-cond\\ $\\leftarrow$\\ \nand-cond\\ $+$\\ {\\bf edge-vertex-contact}(\u001b$@@\\?(E@\u001b(J\\ his\\ mine)\u001b$@$N$=$l$>$l$N\u001b(J\n\u001b$@MWAG$NId9g$rH?E>$7$?%j%9%H\u001b(J\n\\item {\\bf if}\\ \u001b$@D:E@$HD:E@$N@\\?(\u001b(J\\ {\\bf then}\\ and-cond\\ $\\leftarrow$\\ \nand-cond\\ $+$\\ {\\bf vertex-vertex-contact}(\u001b$@@\\?(E@\u001b(J\\ mine\\ his)\n\\end{description}\n\\item return\\ (\u001b$@@\\?(E@\u001b(J\\ and-cond)\n\\end{enumerate}\n\\begin{itemize}\n\\item \u001b$@%9%F%C%W#3$G\u001b(Jand-cond\u001b$@$KDI2C$9$k$N$O!\"DI2C$5$l$kMWAG$,\u001b(Jand-cond\u001b$@$K\u001b(J\n\u001b$@4^$^$l$F$$$J$$$H$-$N$_!#\u001b(J\n\\end{itemize}\n\\end{description}\n\\vspace{2.0cm}\n{\\bf :draw-constraint} {\\em \\&optional (length 30.0)}\\\\\n\u001b$@$3$NE@$K$*$1$k94B+$rLp0u$G2hLL$KI=<($9$k!#\u001b(J\n\u001b$@Lp0u$ND9$5$r\u001b(Jlength\u001b$@$G;XDj$9$k$3$H$b=PMh$k!#\u001b(J\n\\vfill\n\\clearpage\n{\\large \\bf \u001b$@4X?t\u001b(J}\n\\vspace{1.0cm}\\\\\n{\\bf contact-to-constraint(mycontact\\ hiscontact)}\\\\\n\u001b$@Aj<j$K@\\?($7$F$$$k<+J,$ND:E@$HNG>e$NE@$N%j%9%H\u001b(Jmycontact\u001b$@$H\u001b(J\n\u001b$@<+J,$K@\\?($7$F$$$kAj<j$ND:E@$HNG>e$NE@$N%j%9%H\u001b(Jhiscontact\u001b$@$+$i!\"\u001b(J\n\u001b$@<+J,$,<u$1$k94B+>r7o$r5a$a$k4X?t\u001b(J\\\\\n{\\bf return}\\ =\\ {\\bf ((\u001b$@@\\?(E@\u001b(J\\ \\ (($f_{11}\\ or\\ f_{12}\\ \\cdots$)\\ and\\ \n($f_{21}\\ or\\ f_{22}\\ \\cdots$)\\ $\\cdots$))\\ $\\cdots$)}\n\\begin{enumerate}\n\\item {\\bf while}\\ mycontact\u001b$@$,6u%j%9%H$G$J$$\u001b(J\\ {\\bf do}\n\\begin{description}\n\\item point\\ $\\leftarrow$\\ mycontact\u001b$@$NMWAG$N0l$D\u001b(J\n\\item {\\bf if}\\ point\u001b$@$HF1$8E@$,\u001b(Jhiscontact\u001b$@$NMWAG$K$\"$k\u001b(J\\ {\\bf then}\n\\begin{description}\n\\item anotherpoint\\ $\\leftarrow$\\ \u001b$@BP1~$9$kE@$H$=$N6aK5\u001b(J\n\\item constraints\\ $\\leftarrow$\\ constraints\\ $+$\\ (send\\ point\\ \n{\\bf :analyse-contact}\\ anotherpoint)\n\\item hiscontact\\ $\\leftarrow$\\ hiscontact\\ $-$\\ another-point\n\\end{description}\n\\item {\\bf else}\n\\begin{description}\n\\item constraints\\ $\\leftarrow$\\ constraints\\ $+$\\ \n(point\\ ((\u001b$@<+J,$ND:E@$,@\\?($7$F$$$kAj<j$NLL$NK!@~%Y%/%H%k\u001b(J)))\n\\end{description}\n\\item mycontact\\ $\\leftarrow$\\ mycontact\\ $-$\\ point\n\\end{description}\n\\item {\\bf while}\\ hiscontact\u001b$@$,6u%j%9%H$G$J$$\u001b(J\\ {\\bf do}\n\\begin{description}\n\\item point\\ $\\leftarrow$\\ hiscontact\u001b$@$NMWAG$N0l$D\u001b(J\n\\item constraints\\ $\\leftarrow$\\ constraints\\ $+$\\ \n(point\\ ((\u001b$@Aj<j$ND:E@$,@\\?($7$F$$$k<+J,$NLL$NK!@~%Y%/%H%k$N5U8~$-$N%Y%/%H%k\u001b(J)))\n\\item hiscontact\\ $\\leftarrow$\\ hiscontact\\ $-$\\ point\n\\end{description}\n\\item return\\ constraints\n\\end{enumerate}\n{\\bf face-contact\\ (face\\ sign)}\n\u001b$@LL\u001b(Jface\u001b$@$K$h$k94B+>r7o$r5a$a$k!#\u001b(Jface\u001b$@$,<+?H$NLL$N$H$-$O\u001b(Jsign\u001b$@$O\u001b(J\\ $-1.0$\\ \u001b$@!\"\u001b(J\n\u001b$@Aj<j$NLL$N$H$-$O\u001b(J\\ $1.0$\u001b$@!#\u001b(J\n\\begin{enumerate}\n\\item return\\ (list\\ face\u001b$@$NK!@~%Y%/%H%k\u001b(J\\ $\\times$\\ sign)\n\\end{enumerate}\n{\\bf edge-edge-contact\\ (point\\ myedge\\ hisedge)}\n\u001b$@@\\?(E@\u001b(Jpoint\u001b$@$K$*$1$k<+J,$N6aK5$rI=$9NG\u001b(Jmyedge\u001b$@$HAj<j$N6aK5$r\u001b(J\n\u001b$@I=$9NG\u001b(Jhisedge\u001b$@$+$i!\"$3$N@\\?(E@$K$h$k94B+>r7o$r5a$a$k\u001b(J\n\\begin{enumerate}\n\\item mypoints\\ $\\leftarrow$\\ (send\\ myedge\\ {\\bf :neighborpoints}\\ point)\n\\item hispoints\\ $\\leftarrow$\\ (send\\ hisedge\\ {\\bf :neighborpoints}\\ point)\n\\item {\\bf if} myedge\u001b$@$H\u001b(Jhisedge\u001b$@$,J?9T\u001b(J {\\bf then} return nil\n\\item s-plane\\ $\\leftarrow$\\ myedge\u001b$@$H\u001b(Jhisedge\u001b$@$r4^$`LL\u001b(J\n\\item return\\ (\\ (send\\ s-plane\\ {\\bf :separation}\\ mypoints\\ hispoints)\\ )\n\\end{enumerate}\n\\vfill\n\\clearpage\n{\\bf edge-vertex-contact\\ (point\\ myedge\\ hisvertex)}\n\u001b$@@\\?(E@\u001b(Jpoint\u001b$@$K$*$1$k<+J,$N6aK5$rI=$9NG\u001b(Jmyedge\u001b$@$HAj<j$N6aK5$r\u001b(J\n\u001b$@I=$9D:E@\u001b(Jhisvertex\u001b$@$+$i!\"$3$N@\\?(E@$K$h$k94B+>r7o$r5a$a$k\u001b(J\n\\begin{enumerate}\n\\item mypoints\\ $\\leftarrow$\\ (send\\ myedge\\ {\\bf :neighborpoints}\\ point)\n\\item hispoints\\ $\\leftarrow$\\ hisvertex\u001b$@$N:\\$C$F$$$kNG$NH?BPB&$ND:E@$N%j%9%H\u001b(J\n\\item {\\bf for\\ each}\\ f\\ $\\leftarrow$\\ myedge\u001b$@$N:\\$k#2$D$NLL\u001b(J\n\\begin{description}\n\\item c-vector\\ $\\leftarrow$\\ (send f\\ {\\bf :separation}\\ mypoints\\ hispoints)\n\\item {\\bf if}\\ c-vector\u001b$@$,\u001b(Jnil\u001b$@$G$J$$\u001b(J\\ {\\bf then}\\ \nor-cond\\ $\\leftarrow$\\ or-cond\\ $+$\\ c-vector\n\\end{description}\n\\item {\\bf for\\ each}\\ $p1,p2$\\ $\\leftarrow$\\ myedge\u001b$@>e$NE@!\"\u001b(Jhispoints\u001b$@$N\u001b(J\n\u001b$@Cf$+$i0[$J$k#2E@$NAH9g$;\u001b(J\n\\begin{description}\n\\item s-plane\\ $\\leftarrow$\\ $point,p1,p2$\\ \u001b$@$N#3E@$N:\\$kLL\u001b(J\n\\item c-vector\\ $\\leftarrow$\\ \n(send s-plane\\ {\\bf :separation}\\ mypoints\\ hispoints)\n\\item {\\bf if}\\ c-vector\u001b$@$,\u001b(Jnil\u001b$@$G$J$$\u001b(J\\ {\\bf then}\\ \nor-cond\\ $\\leftarrow$\\ or-cond\\ $+$\\ c-vector\n\\end{description}\n\\item return\\ or-cond\n\\end{enumerate}\n{\\bf vertex-vertex-contact\\ (point\\ myvertex\\ hisvertex)}\n\u001b$@@\\?(E@\u001b(Jpoint\u001b$@$K$*$1$k<+J,$N6aK5$rI=$9D:E@\u001b(Jmyvertex\u001b$@$HAj<j$N6aK5$r\u001b(J\n\u001b$@I=$9D:E@\u001b(Jhisvertex\u001b$@$+$i!\"$3$N@\\?(E@$K$h$k94B+>r7o$r5a$a$k\u001b(J\n\\begin{enumerate}\n\\item mypoints\\ $\\leftarrow$\\ myvertex\u001b$@$N:\\$C$F$$$kNG$NH?BPB&$ND:E@$N%j%9%H\u001b(J\n\\item hispoints\\ $\\leftarrow$\\ hisvertex\u001b$@$N:\\$C$F$$$kNG$NH?BPB&$ND:E@$N%j%9%H\u001b(J\n\\item bothpoints\\ $\\leftarrow$\\ myvertex\u001b$@$H\u001b(Jhisvertex\u001b$@$N=EJ#$r=|$$$?OB=89g\u001b(J\n\\item {\\bf for\\ each}\\ $p1,p2$\\ $\\leftarrow$\\ bothpoint\n\u001b$@$NCf$+$i0[$J$k#2E@$NAH9g$;\u001b(J\n\\begin{description}\n\\item s-plane\\ $\\leftarrow$\\ $point,p1,p2$\\ \u001b$@$N#3E@$N:\\$kLL\u001b(J\n\\item c-vector\\ $\\leftarrow$\\ \n(send s-plane\\ {\\bf :separation}\\ mypoints\\ hispoints)\n\\item {\\bf if}\\ c-vector\u001b$@$,\u001b(Jnil\u001b$@$G$J$$\u001b(J\\ {\\bf then}\\ \nor-cond\\ $\\leftarrow$\\ or-cond\\ $+$\\ c-vector\n\\end{description}\n\\item return\\ or-cond\n\\end{enumerate}\n\\vfill\n\\clearpage\n\\subsubsection{\u001b$@7W;;Nc\u001b(J}\n\u001b$@K\\%W%m%0%i%`$K$h$C$F!\"Ey2A94B+E@$N0LCV$H!\"3F!9$NE@$K$*$1$k94B+>r7o$r\u001b(J\n\u001b$@5a$a$?Nc$r<!$K<($9!#\u001b(J\nFig.\\ref{fig:bilateral}\u001b$@$ON>B&94B+$NNc!\"\u001b(J\nFig.\\ref{fig:unilateral}\u001b$@$OJRB&94B+$NNc$G$\"$k!#\u001b(J\n\\begin{figure}[h]\n\\begin{center}\n\\epsfile{file=fig-bilateral.ps,width=15cm}\n\\end{center}\n\\caption{Bilateral constraint}\n\\label{fig:bilateral}\n\\end{figure}\n\\begin{verbatim}\n(setq x (make-cube 200 200 100))\n(setq y (make-cube 100 100 300))\n(setq ana (body- x y))\n(send y :constraint ana)\n(hidd y ana)\n(send y :draw-constraint)\n\\end{verbatim}\n\\vfill\n\\clearpage\n\\begin{figure}[h]\n\\begin{center}\n\\epsfile{file=fig-unilateral.ps,width=15cm}\n\\end{center}\n\\caption{Unilateral constraint}\n\\label{fig:unilateral}\n\\end{figure}\n\\begin{verbatim}\n(setq x (make-prism '(#f(-80 0 -50) #f(-80 -25 0) #f(-80 -100 0)\n\t\t      #f(-80 -100 25) #f(-80 100 25) #f(-80 100 0)\n\t\t      #f(-80 25 0))\n\t\t    #f(160 0 0)))\n(setq mizo (make-prism '(#f(-100 0 -50) #f(-100 25 0) #f(-100 100 0)\n\t\t\t #f(-100 100 -100) #f(-100 -100 -100) #f(-100 -100 0)\n\t\t\t #f(-100 -25 0))\n\t\t       #f(200 0 0)))\n(send x :constraint mizo)\n(hidd x mizo)\n(send x :draw-constraint mizo 20.0)\n\\end{verbatim}\n\\vfill\n\\clearpage\nFig.\\ref{fig:peg-in-hole}\u001b$@$O!\"7j$K$Z%0$rF~$l$k:n6HCf$N94B+>uBV$NNc$G$\"$k!#\u001b(J\n\\begin{figure}[h]\n\\epsfile{file=fig-peg-in-hole1.ps,width=8cm}\n\\epsfile{file=fig-peg-in-hole2.ps,width=8cm}\n\\epsfile{file=fig-peg-in-hole3.ps,width=8cm}\n\\epsfile{file=fig-peg-in-hole4.ps,width=8cm}\n\\caption{Peg in a hole}\n\\label{fig:peg-in-hole}\n\\end{figure}\n\\subsubsection{\u001b$@J88%\u001b(J}\n\u001b$@K\\@a$NFbMF$O!\"<!$NO@J8$K$h$C$F$$$k!#\u001b(J\n\u001b$@K\\@a$N%W%m%0%i%`$rMQ$$$F3X2qEy$GH/I=$5$l$k:]$O!\"\u001b(J\n\u001b$@$4;2>H2<$5$kMM$*4j$$$7$^$9!#\u001b(J\n\\begin{itemize}\n\\item \u001b$@HfN1@nGn5W!\">>0f=S9@!\"9b@%T\"9n!\"\u001b(J\n\u001b$@B?LLBN4V$N@\\?($K$h$k94B+>r7o$r4v2?%b%G%k$+$iF3=P$9$k0lHLE*$J%\"%k%4%j%:%`!\"\u001b(J\n\u001b$@F|K\\%m%\\%C%H3X2q;o!\"#94,!\"#49f!\"#1#9#9#1!#\u001b(J\n\\end{itemize}\n\\vfill\n\\clearpage\n\\subsection{\u001b$@J*BN4V$N@\\?($K$h$k94B+$N2r@O\u001b(J}\n\n\\subsubsection{\u001b$@%\"%k%4%j%:%`$N35MW\u001b(J}\n\u001b$@A0@a$G=R$Y$?MM$K!\"Ho94B+J*BN$H94B+J*BN$N7A>u$OB?LLBN!\"\u001b(J\n\u001b$@N><T$N4V$KK`;$$OF/$+$J$$$H2>Dj$9$k$H!\"Ho94B+J*BN$KBP$9$k94B+>r7o$O0lHL$K!\"\u001b(J\n\\begin{equation}\n\\bigcap_{k=1}^{L} \\bigcap_{i=1}^{N(k)}\\ \\bigcup_{j=1}^{M(k,i)}\\ \nF_{kij}^{T}J_{k}\\left(\n\\begin{array}{c}\n\\Delta X \\\\ \\Omega\n\\end{array}\n\\right)\\geq 0\n\\label{eq:ippannokosoku}\n\\end{equation}\n\u001b$@$GM?$($i$l$k!#$3$3$K!\"\u001b(J$L$\u001b$@$OEy2A94B+E@$N?t!\"\u001b(J\n$N(k)$\u001b$@$O3FEy2A94B+E@$K$*$1$kO@M}@Q>r7o$N?t!\"\u001b(J$M(k,i)$\u001b$@$OO@M}OB>r7o$N?t$G$\"$k!#\u001b(J\n\u001b$@$^$?!\"\u001b(J$F_{kij}:3\\times 1$\u001b$@$O94B+K!@~%Y%/%H%k!\"\u001b(J\n$J_{k}:3\\times 6$\u001b$@$O!\"J*BN:BI87O$GI=$5$l$?Hy>.JQ0L\u001b(J$\\Delta X$\u001b$@!&2sE>\u001b(J$\\Omega$\u001b$@$r\u001b(J\n\u001b$@Ey2A94B+E@$r86E@$H$9$k:BI87O$GI=$5$l$?Hy>.JQ0L\u001b(J$\\Delta X_{k}$\n\u001b$@$KJQ49$9$k%d%3%S9TNs$G$\"$k!#\u001b(J\n\u001b$@J,G[B'$rMQ$$$FO@M}OB$rA0$K=P$9$H!\"\u001b(J(\\ref{eq:ippannokosoku})\u001b$@<0$O!\"\u001b(J\n\\begin{equation}\n\\bigcup_{p=1}^{Q}\\ C_{p}\\ \\left(\n\\begin{array}{c}\n\\Delta X \\\\ \\Omega\n\\end{array}\n\\right)\\geq 0\n\\label{eq:matrix-form}\n\\end{equation}\n\u001b$@$H$$$&7A$K$+$1$k!#$3$3$K!\"\u001b(J$Q=\\Pi_{k,i}M(k,i)$\u001b$@!\"\u001b(J\n$C_{p}:n\\times 6$ \u001b$@$O\u001b(J$F_{kij}^{T}J_{k}$\u001b$@$r9T%Y%/%H%k$H$9$k9TNs$G$\"$k!#\u001b(J\n$n$\u001b$@$O\u001b(J$p$\u001b$@$K0MB8$7$F7h$^$k?t$G$\"$k$,!\"$3$3$G$O4JC1$N$?$aC1$K\u001b(J$n$\u001b$@$H5-$7$?!#\u001b(J\n(\\ref{eq:ippannokosoku})\u001b$@<0$N2r$O!\"3F!9$N!\"\u001b(J\n\\begin{equation}\nC_{p}\\ \\left(\n\\begin{array}{c}\n\\Delta X \\\\ \\Omega\n\\end{array}\n\\right)\\geq 0\n\\label{eq:each-matrix-form}\n\\end{equation}\n\u001b$@$H$$$&O\"N)@~7AITEy<0$N2r$NOB=89g$K$J$k!#\u001b(J\n(\\ref{eq:each-matrix-form})\u001b$@<0$N2r$OFLB?LL?m$K$J$k$,!\"\u001b(J\n\u001b$@2r$r5a$a$k$N$KI,MW$J7W;;NL$O\u001b(J$r=rank\\ C_{p}$\u001b$@$K0MB8$9$k!#\u001b(J\n\u001b$@$=$3$G!\"$^$:9TNs\u001b(J$C_{p}$\u001b$@$r!\"\u001b(J\n\\begin{equation}\nC_{p}=\\ \\left(\n\\begin{array}{cc}\nU_{1} & U_{2}\n\\end{array}\n\\right) \\left(\n\\begin{array}{cc}\nD_{rr} & O \\\\\nO & O\n\\end{array}\n\\right) \\left(\n\\begin{array}{c}\nV_{1}^{T} \\\\\nV_{2}^{T}\n\\end{array}\n\\right)\n\\label{eq:svd}\n\\end{equation}\n\u001b$@$HFC0[CMJ,2r$9$k$3$H$K$h$j!\"\u001b(J$C_{p}$\u001b$@$NNm6u4V$rJ,N%$9$k!#\u001b(J\n\u001b$@$3$3$K!\"\u001b(J$U_{1}:n\\times r$\u001b$@!\"\u001b(J$U_{2}:n\\times (6-r)$\u001b$@!\"\u001b(J\n$V_{1}:6\\times r$\u001b$@!\"\u001b(J$V_{2}:6\\times (6-r)$\u001b$@$OD>8r9TNs!\"\u001b(J\n$D_{rr}:r\\times r$\u001b$@$OBP3Q9TNs$G$\"$k!#\u001b(J\n(\\ref{eq:each-matrix-form})\u001b$@<0$N2r$O!\"\u001b(J$C_{p}$\u001b$@$NNm6u4V$H!\"\u001b(J\n$V_{1}$\u001b$@$NNs%Y%/%H%k$GD%$i$l$k\u001b(J$r$\u001b$@<!85@~7AItJ,6u4V$K$*$1$k2r$ND>OB$K$J$k!#\u001b(J\n\u001b$@8e<T$O!\"\u001b(J\n\\begin{equation}\nU_{1}D_{rr}V_{1}^{T}V_{1}W_{r}\n=U_{1}D_{rr}W_{r}\\stackrel{\\rm def}{=}\n\\left(\n\\begin{array}{c}\nH_{1}^{T} \\\\ \\vdots \\\\ H_{n}^{T}\n\\end{array}\n\\right) W_{r}\n\\geq O\n\\label{eq:pointed-cone}\n\\end{equation}\n\u001b$@$J$kO\"N)@~7AITEy<0$N2r\u001b(J$W_{r}$\u001b$@$G$\"$k!#\u001b(J\n$rank\\ U_{1}D_{rr}=r$\u001b$@$G$\"$k$N$G!\"$3$N2r$O86E@$r!VD:E@!W$H$9$kFLB?LL?m$K$J$j!\"\u001b(J\n\\begin{equation}\nW_{r}=\\left(\n\\begin{array}{ccc}\nE_{1} & \\cdots & E_{m}\n\\end{array}\n\\right) \\left(\n\\begin{array}{c}\n\\epsilon_{1} \\\\ \\vdots \\\\ \\epsilon_{m}\n\\end{array}\n\\right)\n\\label{eq:pointed-cone-solution}\n\\end{equation}\n\u001b$@$H$$$&HsIi#1<!7k9g$GI=8=$5$l$k!#\u001b(J\n\u001b$@$3$3$K!\"\u001b(J$E_{j}:r\\times 1$ \u001b$@$OFLB?LL?m$NB&JU$NJ}8~$rI=$9%Y%/%H%k!\"\u001b(J\n$\\epsilon_{j}$\u001b$@$OHsIi$N%9%+%i!<!\"\u001b(J$m$\u001b$@$OB&JU$N?t$G$\"$k!#\u001b(J\n\u001b$@:G=*E*$J\u001b(J(\\ref{eq:each-matrix-form})\u001b$@<0$N2r$O!\"\u001b(J$C_{p}$\u001b$@$NNm6u4V$NMWAG$r2C$($F!\"\u001b(J\n\\begin{equation}\n\\left(\n\\begin{array}{c}\n\\Delta X \\\\ \\Omega\n\\end{array}\n\\right) =V_{1} \\left(\n\\begin{array}{ccc}\nE_{1} & \\cdots & E_{m}\n\\end{array}\n\\right) \\left(\n\\begin{array}{c}\n\\epsilon_{1} \\\\ \\vdots \\\\ \\epsilon_{m}\n\\end{array}\n\\right) + \\left(\n\\begin{array}{cc}\nV_{2} & -V_{2}\n\\end{array}\n\\right) \\left(\n\\begin{array}{c}\n\\epsilon_{m+1} \\\\ \\vdots \\\\ \\epsilon_{m+2(6-r)}\n\\end{array}\n\\right)\n\\label{eq:finalsolution}\n\\end{equation}\n\u001b$@$HI=$5$l$k!#\u001b(J\n$V_{1}E_{j}$\u001b$@$O94B+>uBV$rJQ2=$5$;$kHy>.JQ0L$KBP1~$7!\"\u001b(J\n$V_{2}$\u001b$@$OA4$F$NEy2A94B+E@$H$N@\\?(>uBV$r0];}$9$kHy>.JQ0L$KBP1~$9$k!#\u001b(J\n\u001b$@$3$N<0$O!\"@\\?($K$h$j94B+$r<u$1$?J*BN$K5v$5$l$kG$0U$NHy>.JQ0L$,!\"\u001b(J\n$m+2(6-r)$\u001b$@8D$NHy>.JQ0L$NHsIi#1<!7k9g$GI=$5$l$k$3$H$r<($7$F$$$k!#\u001b(J\n\u001b$@$3$l$O:G>.$N?t$N4pDl$G$\"$k!#\u001b(J\n\u001b$@$3$N$H$-!\"Ho94B+J*BN$,94B+J*BN$KBP$7$F\u001b(J\n\u001b$@H/@82DG=$JNO\u001b(J$F$\u001b$@!\"%H%k%/\u001b(J$T$\u001b$@$N=89g$O!\"\u001b(J\n(\\ref{eq:finalsolution})\u001b$@<0$NAPBPFLB?LL?m$G!\"\u001b(J\n\\begin{equation}\n\\left(\n\\begin{array}{ccc}\nV_{1}(E_{1}\\ \\cdots\\ E_{m}) & V_{2} &  -V_{2}\n\\end{array}\n\\right)^{T}\n\\left(\n\\begin{array}{c}\nF \\\\ T\n\\end{array}\n\\right) \\leq 0\n\\label{eq:force}\n\\end{equation}\n\u001b$@$J$kO\"N)ITEy<0$N2r$K$J$k!#\u001b(J\n\n\u001b$@K\\@a$G$O!\"\u001b(Jc-body\u001b$@$N%a%=%C%I\u001b(J$:constraint$\u001b$@$G5a$a$?\u001b(J(\\ref{eq:ippannokosoku})\u001b$@<0\u001b(J\n\u001b$@$+$i2r$G$\"$k\u001b(J(\\ref{eq:finalsolution})\u001b$@<0$r5a$a$k%W%m%0%i%`!\"\u001b(J\n(\\ref{eq:force})\u001b$@<0$N2r$r5a$a$k%W%m%0%i%`$r@bL@$9$k!#\u001b(J\n\u001b$@$3$l$i$N%W%m%0%i%`$r;H$&$?$a$K$O!\"\u001b(J\n$eus/llib/solve-inequalities.l$\\ \u001b$@$r%m!<%I$9$kI,MW$,$\"$k!#\u001b(J\n\u001b$@K\\%\"%k%4%j%:%`$N<gMWItJ,$O\u001b(J$C$\u001b$@$G%$%s%W%j%a%s%H$5$l$F$*$j!\"\u001b(J\n$Euslisp$\u001b$@$NB>8@8l%$%s%?!<%U%'%$%9$rMQ$$$F%j%s%/$7$F$$$k!#\u001b(J\n$C$\u001b$@$NItJ,$O\u001b(J$eus/cone$\u001b$@$H$$$&\u001b(Jdirectory\u001b$@$K$\"$j!\"\u001b(J\n\\begin{verbatim}\n % cd eus/cone\n % make cone\n % make install\n\\end{verbatim}\n\u001b$@$r<B9T$9$k$3$H$K$h$C$F!\"%i%$%V%i%j!<$,:n$i$l$k!#\u001b(J\n\u001b$@%j%s%/$9$k:]$K$O\u001b(J$convexconeref.o$\u001b$@$H$$$&%*%V%8%'%/%H%U%!%$%k$,\u001b(J\n\u001b$@2?=h$+$KI,MW$G$\"$k!#>\\:Y$O!\"\u001b(Jeus/llib/solve-inequalities.l\\ \u001b$@$r;2>H$5$l$?$$!#\u001b(J\n\n\u001b$@%$%s%W%j%a%s%F!<%7%g%s>e$N@)Ls$+$i!\"Ey2A94B+>r7o$N?t$O:GBg#3#2$H$J$C$F$$$k!#\u001b(J\n\\vfill\n\\clearpage\n\\subsubsection{\u001b$@%$%s%W%j%a%s%F!<%7%g%s\u001b(J}\n\\vspace{1.0cm}\n{\\jLarge c-body}\n\\\\ [0.5cm]\n\\begin{description}\n\n\\item[{\\jlarge \\bf description}]\\hspace{1cm}\n\\begin{description}\n\\item[] \u001b$@94B+>r7o$r3JG<$9$k%9%m%C%H$rDI2C$7$?\u001b(Jbody\u001b$@$N%5%V%/%i%9\u001b(J\n\\end{description}\n\n\\item[{\\jlarge \\bf super class}]\\hspace{1cm}\n\\begin{description}\n\\item[body] ()\n\\end{description}\n\n\\item[{\\jlarge \\bf slots}]\\hspace{1cm}\n\\begin{description}\n\\item[motion] \u001b$@5v$5$l$kHy>.JQ0L\u001b(J\n\\item[force] \u001b$@H/@82DG=$JNO\u001b(J\n\\end{description}\n\n\\item {\\jlarge \\bf methods}\n\\\\ [0.5cm]\n\\begin{description}\n\\item[:motion ()] self\u001b$@$KBP$9$k94B+>r7o$r2r$$$F!\"5v$5$l$kHy>.JQ0L$r5a$a$k!#\u001b(J\n\\item[:force ()] self\u001b$@$K5v$5$l$kHy>.JQ0L$+$i!\"H/@82DG=$JNO$r5a$a$k!#\u001b(J\n\\item[:draw-motion (b)] self\u001b$@$H\u001b(Jb\u001b$@$,@\\?($7$F$$$k$H$-$K!\"\u001b(Jself\u001b$@$K5v$5$l$kHy>.JQ0L\u001b(J\n\u001b$@$rI=<($9$k!#\u001b(J\n\\end{description}\n\\end{description}\n\\vfill\n\\clearpage\n\\subsubsection{\u001b$@7W;;Nc\u001b(J}\n\u001b$@K\\%W%m%0%i%`$K$h$C$F!\"\u001b(J(\\ref{eq:finalsolution})\u001b$@<0$G\u001b(J\n\u001b$@I=$5$l$k2r$r5a$a$?Nc$r0J2<$K<($9!#\u001b(J\n\nFig.\\ref{fig:trigonalprism}\u001b$@$K!\"#33QCl$,%F!<%V%k$N>e$K:\\$C$F$$$kNc$r<($9!#\u001b(J\n\u001b$@$3$N>l9g!\"2r$O<!<0$GI=$5$l$k!#\u001b(J\n\\begin{equation}\n\\left(\n\\begin{array}{c}\n\\Delta X \\\\ \\Omega\n\\end{array}\n\\right) = \\left(\n\\begin{array}{ccc}\n0.0 & 0.0 & 0.0 \\\\\n0.0 & 0.0 & 0.0 \\\\\n2.31 & 6.00 & 2.31 \\\\\n-.0308 & 0.08 & -.0308 \\\\\n.0923 & 0.0 & -0.923 \\\\\n0.0 & 0.0 & 0.0\n\\end{array}\n\\right) \\left(\n\\begin{array}{c}\n\\epsilon_{1} \\\\ \\epsilon_{2} \\\\ \\epsilon_{3}\n\\end{array}\n\\right) + \\left(\n\\begin{array}{cccccc}\n-10. & 10. & 0.0 & 0.0 & 0.0 & 0.0 \\\\\n0.0 & 0.0 & -10. & 10. & 0.0 & 0.0 \\\\\n0.0 & 0.0 & 0.0 & 0.0 & 0.0 & 0.0 \\\\\n0.0 & 0.0 & 0.0 & 0.0 & 0.0 & 0.0 \\\\\n0.0 & 0.0 & 0.0 & 0.0 & 0.0 & 0.0 \\\\\n0.0 & 0.0 & 0.0 & 0.0 & 0.1 & -0.1\n\\end{array}\n\\right) \\left(\n\\begin{array}{c}\n\\epsilon_{4} \\\\ \\epsilon_{5} \\\\ \\epsilon_{6} \\\\\n\\epsilon_{7} \\\\ \\epsilon_{8} \\\\ \\epsilon_{9}\n\\end{array}\n\\right)\n\\end{equation}\n\u001b$@?^$K<($7$F$\"$k$N$O!\"94B+>r7o!\"N%C&F0:n$N0l$D!\"94B+$r0];}$9$kJB?J$H2sE>$G$\"$k!#\u001b(J\n\\begin{figure}[h]\n\\begin{center}\n\\epsfile{file=fig-onthetable-0.ps,width=7cm}\n\\epsfile{file=fig-onthetable-m1.ps,width=7cm}\\\\\n\\epsfile{file=fig-onthetable-mt.ps,width=7cm}\n\\epsfile{file=fig-onthetable-mr.ps,width=7cm}\n\\end{center}\n\\caption{Possible motions of a trigonal prism}\n\\label{fig:trigonalprism}\n\\end{figure}\n\\vfill\n\\clearpage\nFig.\\ref{fig:peg-in-a-hole}\u001b$@$K3QCl$,7j$KF~$C$F$$$kNc$r<($9!#\u001b(J\n\u001b$@$3$N>l9g!\"2r$O<!<0$GI=$5$l$k!#\u001b(J\n\\begin{equation}\n\\left(\n\\begin{array}{c}\n\\Delta X \\\\ \\Omega\n\\end{array}\n\\right) = \\left(\n\\begin{array}{ccc}\n0.0 & 0.0 & 0.0 \\\\\n3.87 & -8.66 & -3.87 \\\\\n2.24 & 5.0 & -2.24 \\\\\n.0894 & 0.0 & -.0894 \\\\\n0.0 & 0.0 & 0.0 \\\\\n0.0 & 0.0 & 0.0\n\\end{array}\n\\right) \\left(\n\\begin{array}{c}\n\\epsilon_{1} \\\\ \\epsilon_{2} \\\\ \\epsilon_{3}\n\\end{array}\n\\right)\n\\end{equation}\n\u001b$@$3$NNc$G$O!\"94B+>uBV$rJQ$($J$$F0:n$OB8:_$;$:!\"\u001b(J\n\u001b$@G$0U$NF0:n$O?^$K<($7$?MM$J#3$D$NF0:n$+$i@8@.$5$l$k!#\u001b(J\n\\begin{figure}[h]\n\\begin{center}\n\\epsfile{file=fig-peg-naname-0.ps,width=7cm}\n\\epsfile{file=fig-peg-naname-m1.ps,width=7cm}\\\\\n\\epsfile{file=fig-peg-naname-m2.ps,width=7cm}\n\\epsfile{file=fig-peg-naname-m3.ps,width=7cm}\n\\end{center}\n\\caption{Possible motions of a peg in a hole}\n\\label{fig:peg-in-a-hole}\n\\end{figure}\n\\vfill\n\\clearpage\n\\subsubsection{\u001b$@J88%\u001b(J}\n\u001b$@K\\@a$NFbMF$O!\"<!$NO@J8$K$h$C$F$$$k!#\u001b(J\n\u001b$@K\\@a$N%W%m%0%i%`$rMQ$$$F3X2qEy$GH/I=$5$l$k:]$O!\"\u001b(J\n\u001b$@$4;2>H2<$5$kMM$*4j$$$7$^$9!#\u001b(J\n\\begin{itemize}\n\\item \u001b$@HfN1@nGn5W!\">>0f=S9@!\"9b@%T\"9n!\"\u001b(J\n\u001b$@B?LLBN4V$N@\\?($K$h$k94B+>r7o$N9bB.2rK!$H$=$NN%C&F0:n7W2h$X$N1~MQ!\"\u001b(J\n\u001b$@F|K\\%m%\\%C%H3X2q;o!\"7G:\\M=Dj!#\u001b(J\n\\end{itemize}\n", "meta": {"hexsha": "5a2e8bcf148979fbe00743e660eaffd37e7b63db", "size": 62139, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/hirukawa/geometry.tex", "max_stars_repo_name": "snozawa/EusLisp", "max_stars_repo_head_hexsha": "021843b48ffcd029fcb6113d5022c703b6ce45fb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 50, "max_stars_repo_stars_event_min_datetime": "2015-02-16T23:07:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T02:43:01.000Z", "max_issues_repo_path": "doc/hirukawa/geometry.tex", "max_issues_repo_name": "snozawa/EusLisp", "max_issues_repo_head_hexsha": "021843b48ffcd029fcb6113d5022c703b6ce45fb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 286, "max_issues_repo_issues_event_min_datetime": "2015-01-04T02:47:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T16:38:43.000Z", "max_forks_repo_path": "doc/hirukawa/geometry.tex", "max_forks_repo_name": "snozawa/EusLisp", "max_forks_repo_head_hexsha": "021843b48ffcd029fcb6113d5022c703b6ce45fb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 39, "max_forks_repo_forks_event_min_datetime": "2015-01-03T05:06:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T05:10:54.000Z", "avg_line_length": 35.3866742597, "max_line_length": 110, "alphanum_fraction": 0.5554804551, "num_tokens": 34627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3490265692690928}}
{"text": "\n\\documentclass[Thesis.tex]{subfiles}\n\\begin{document}\n\\chapter{Variational Monte Carlo}\n\\label{chp:variational-monte-carlo}\n\n\\glsresetall\n\n\\Gls{vmc} is a method for obtaining the ground state wave function of\na quantum mechanical system, and it constitutes the framework for all the calculations we\nperform in this thesis. As this method is of great significance to us, this chapter is\ndevoted to all relevant definitions, derivations and technical details required for a\nsuccessful study of the systems of interest.\n\n\\section{The Variational Principle}\n\nThe fundamental principle that enables \\gls{vmc} is the observation that the wave function that\ndescribes the ground state of a system, is the wave function which produces the lowest\nexpectation value of the energy. Read this statement a couple of times and it almost seems\nlike a circular definition, because we define the ground state as the state with the\nlowest energy. Still, this simple observation is what allows us a way to go forward.\n\nLet's formalize the above statement.\n\n\\begin{theorem}[Variational Principle]\\label{thm:variational-principle}\n    Suppose a time-independent Hamiltonian, $\\hat H$, an associated set of eigenvalues,\n    $E_0\\leq E_1\\leq\\dots$ and\n    a set of orthonormal eigenvectors, $\\{\\ket{\\phi_n}\\}$ spanning the associated\n    Hilbert space, such that the \\acrlong{tise} is satisfied,\n\n    \\begin{align}\n        \\hat H\\ket{\\phi_n} = E_n\\ket{\\phi_n}.\n    \\end{align}\n    For any arbitrary $\\ket\\psi$ in the Hilbert space, the expectation value of $\\hat H$\n    for this wave function must satisfy\n    \\begin{align}\n        \\expval{\\hat H}&\\defeq \\expval{\\hat H}{\\psi} \\geq E_0,\n    \\end{align}\n    where $E_0$ is the exact ground state energy, with equality if and only if\n    $\\ket\\psi=\\ket\\phi_0$.\n\\end{theorem}\n\\begin{proof}\n    Because $\\{\\ket{\\phi_n}\\}$ constitutes a complete orthonormal basis of the Hilbert\n    space, we can expand $\\ket\\psi$ as\n    \\begin{align}\n        \\ket\\psi = \\sum_n c_n\\ket{\\phi_n} \\qq{with} \\sum_n \\abs{c_n}^2 = 1.\n    \\end{align}\n    We then have\n    \\begin{align}\n        \\expval{\\hat H}{\\psi} &= \\qty(\\sum_m c^*_m\\bra{\\phi_m})\\hat H\\qty(\\sum_n\n        c_n\\ket{\\phi_n})\\\\\n        &= \\sum_n\\sum_m c_m^*c_n\\bra{\\phi_m}\\hat H\\ket{\\phi_n}\\\\\n        &= \\sum_n\\sum_m c_m^*c_nE_n\\bra{\\phi_m}\\ket{\\phi_n}\\\\\n        &= \\sum_n\\sum_m c_m^*c_nE_n\\delta_{mn}\\\\\n        &= \\sum_n \\abs{c_n}^2 E_n\\\\\n        &\\geq\\sum_n \\abs{c_n}^2 E_0 = E_0.\n    \\end{align}\n    It is clear that the equality only occurs when $c_n = \\delta_{0n}$, which implies\n    $\\ket\\psi=\\ket{\\phi_0}$.\n\\end{proof}\n\nIf we require the test wave function $\\ket\\psi$ to be orthogonal to $\\ket{\\phi_0}$, then\nthe above derivation results in a similar condition for determining the first excited\nstate. By applying the same reasoning iteratively, the same can be said about any higher\nenergy state. So in principle, we can use the variational principle to first find the\nground state, then find an orthogonal state that gives the first excited energy, then find\na state orthogonal to both that gives the second excited energy etc. We will not pursue\nany excited states in this thesis, but it is useful to know that we could in principle\nextend our results if need be.\n\n\\section{The Variational Monte Carlo Algorithm}\n\nRooted in the variational principle, the general approach to finding a good estimate of\nthe ground state goes as follows:\n\n\\begin{enumerate}\n    \\item Define the Hamiltonian of interest, $\\hat H$\n    \\item Propose a trial wave function $\\ket{\\vb \\alpha}$ dependent on some free parameters\n        $\\vb \\alpha=\\qty(\\alpha_1, \\alpha_2,\\dots, \\alpha_m)$\n    \\item Return the best possible wave function $\\ket{\\vb\\alpha}$ such that $\\expval{\\hat\n        H}{\\vb\\alpha}$ is minimized w.r.t the parameters $\\vb \\alpha$.\n\\end{enumerate}\nThe first step is trivial, as we shall assume that the Hamiltonians we want to examine are\ngiven in advance.\\footnote{Clearly, deriving/defining Hamiltonians that accurately describe a given\nsystem is not a trivial task in general, and might require great levels of theoretical\nwork and/or experimental data analysis. But from our perspective, this work has already\nbeen done.}\n\nThe second and third points are where we will spend our efforts, and so we devote extra\nattention to these two points in particular.\n\n\n\\section{The Trial Wave Function}\n\nCritical to the outcome of a \\gls{vmc} calculation is the quality of the proposed trail wave\nfunction. In order to have stable and sensible results we should also take care that the\nwave function obeys the requirements stated in\n\\cref{sec:requirements-of-wave-functions}. Beyond these basic assertions, it is\nimperative that the functional form of the proposed wave function is capable of expressing\nthe true underlying ground state, or at least a good approximation of it. As an example,\ntake the simple case of the idealized one-dimensional harmonic oscillator presented in\n\\cref{sec:simple-non-inter-HO}, with the ground state expressed as\n\\begin{align}\n    \\phi_0(x) \\propto \\exp(- \\frac{1}{2} x^2).\n\\end{align}\nIf we proposed a trial wave function on a form\n\\begin{align}\n    \\psi(x; \\alpha)\\propto \\exp(- \\alpha x^2),\n\\end{align}\nwe could expect \\gls{vmc} to produce the exact ground state after optimizing $\\alpha$. The above\nis a good trial wave function because its functional form contains the exact state.\n\nSuppose now we proposed something different, maybe because of a lack of theoretical\nunderstanding. For the sake of example, say we chose this visually similar\nfunction:\\footnote{Visually similar in the sense that plotting them both yield similar bell\nshaped curves, not in terms of their algebra.}\n\\begin{align}\n    \\psi(x; \\alpha)\\propto \\frac{1}{1 + \\alpha x^2}.\n\\end{align}\nNo matter how we tune the $\\alpha$ parameter here, we will never achieve the lowest\nground state energy, simply because the ground state is not possible to express within this\nfunctional form. We can now only hope to get approximations, acting as upper bounds on the\nground state energy.\n\n\\subsection{Slater-Jastrow: Standard Approach}\n\\label{sec:slater-jastrow}\n\nIn order to come up with good trail wave functions we have a standard approach which often\nserves us well. Typically we are considering a system of many interacting particles in\nsome external potential (e.g. the quantum dots system). In such cases the typical approach\nis to build a trial wave function as a product of a single-particle part, $S$, and a correlation\npart, $J$. The two are referred to as the \\emph{Slater} factor and the\n\\emph{Jastrow} factor, respectively:\n\n\\begin{align}\n    \\psi = S\\cdot J.\n\\end{align}\n\n\\subsubsection*{Slater Factor}\n\nThe idea behind the decomposition above is that we put all the physical insight we have into these\ntwo components individually. For the single particle part we include what we can deduce\nabout the system if we idealize it in some way. Typically that involves looking at the\nstates when there is only one particle, or considering some simplified interaction between\nall of them (e.g. Hartree-Fock approximation). The basis functions we obtain from such an\nanalysis are then placed in a determinant/permanent structure so as to fix the symmetry\nrequirements of fermions/bosons, respectively. This factor is then the Slater\nfactor~\\cite{Slater-1929,Dirac-1926}.\n\n\nFor clarity, we present a couple of different Slater forms. We consider the two-dimensional\nquantum dots system from \\cref{sec:quantum-dots-theory} for $N$ particles. We\ndenote the position of particle $i$ by $\\vb x_i=(x_i, y_i)$. Let $\\vb\\Phi$ be a matrix defined by $\\Phi_{i,j}\n\\defeq \\phi_{i}(\\vb x_j)$, where the $\\phi_i$ is part of the set of orbitals\n$\\{\\phi_{0,0}, \\phi_{1,0},\\phi_{0,1}, \\phi_{1,1},\\dots\\}$, as defined in\n\\cref{eq:ho-single-particle-orbitals}. Lastly, let $\\vb \\Phi^{(M)}$ denote the\nresulting matrix with $M$ rows, one for each of the $M$ lowest energy orbitals. Finally,\nif the particles are fermions we define the Slater factor as:\\footnote{Spin considerations not mentioned here, as they will not be important for the particular systems we will investigate. In general though, the structure of the Slater factor needs to account for spin in a well defined way.}\n\n\\begin{align}\n    S(\\vb X)_\\text{fermions} \\defeq \\text{determinant}\\qty(\\vb\\Phi^{(M)}).\n\\end{align}\nDue to the properties of the determinant, this has the anti-symmetry required for\nfermions.\n\nIn the case of bosons, we could just change the above to\n\\begin{align}\n    S(\\vb X)_\\text{bosons} \\defeq \\text{permanent}\\qty(\\vb\\Phi^{(M)}).\n\\end{align}\nHowever, there are far less computationally expensive ways to get a \\emph{symmetric}\nresult, as required for bosons. A simple product of single particle ground states is\nsufficient in this case.\n\\begin{align}\n    S(\\vb X)_\\text{bosons} \\defeq \\prod_{i}^N \\phi_{0,0}(\\vb x_i).\n\\end{align}\n\nThe general structure is constant across different systems, changing only the basis\nfunctions we use to express the matrix elements.\n\nIn some cases, however, we will struggle to find basis functions that describe a meaningful\nportion of the system's behaviour in this way. In such challenging cases, the Slater factor\ncould be reduced to only being responsible for supplying the correct symmetry. In the case\nof bosons, that would mean the complete removal of the Slater factor from the trial wave\nfunction. We will see this when looking further into the liquid helium system.\n\n\n\n\\subsubsection*{Jastrow Factor}\n\nAnything not covered by this analysis is meant to be accounted for in the correlation\nterm, $J$. This is typically a function on the following generalized form, commonly called a Jastrow\nfactor~\\cite{Jastrow-1955}:\n\\begin{align}\n    J(\\vb X) &= \\exp(\\sum_{i < j} U(r_{ij})),\n\\end{align}\nwhere $U(r_{ij})$ is some function dependent on the inter-particle distance only. Note that by\nconvention the Slater factor has the correct symmetry, so the correlation factor should\nalways be symmetrical in order to maintain the same total symmetry.\n\nAny variational parameters $\\vb \\alpha$ are typically introduced as part of the Jastrow\nfactor. The Slater factor represents everything we are sure should be included\nfrom a theoretical approach, while the Jastrow term should ideally account for all our ignorance.\nIt is therefore typically expressed with a few free parameters.\n\nAgain, for the sake of clarity, we state an example of a Jastrow factor. One of the most\ncommonly used is the Pade-Jastrow factor~\\cite{Drummond-Towler-Needs-2008}:\n\\begin{align}\n    J(\\vb X) = \\prod_{i < j} \\exp(\\frac{\\alpha r_{ij}}{1 + \\beta r_{ij} } ).\n\\end{align}\nHere $\\beta$ is the only variational parameter, and $\\alpha$ is fixed depending on the\ndimensionality and spin of the particles. More complicated versions exist, containing\nhigher order polynomials of $r_{ij}$ in the exponential. This particular form\nwill prove to be a very good choice for the quantum dots system.\n\n\n\n\n\\section{Optimization}\n\nAt this point, we have a Hamiltonian $\\hat H$ defining our system of interest,\nand we have proposed a trial wave function $\\ket{\\vb\\alpha}$ based on the\ntheoretical intuition we have. The wave function has by design some free\nparameters $\\vb\\alpha$ which we now want to pin down to their optimal values.\n\nFrom the variational principle (\\cref{thm:variational-principle}), we know\nthat the best set of parameters are those that minimize the expected energy,\n$\\expval{\\hat H}{\\vb\\alpha}$. As such, a natural place to start would be to\ndetermine an efficient way to evaluate the energy.\n\n\\subsection{Local Energy}\n\nDenote the trial wave function as $\\psi_{\\vb\\alpha}(\\vb X)$, where $\\vb\\alpha$\nare the variational parameters and $\\vX=(\\vx_1\\  \\vx_2\\ \\dots\\ \\vx_n)^T$ is the\nmatrix of all the degrees of freedom for each particle (e.g. position\ncoordinates). The expectation value for the energy of the system is:\n\n\\begin{align}\n    \\expval{\\hat H} &= \\frac{\\expval{\\hat H}{\\vb\\alpha}}{\\braket{\\vb\\alpha}}\\\\\n    &= \\frac{\\int \\dd{\\vb X} \\psialpha^*\\hat H\\psialpha}{\\int\\dd{\\vX}\\abs{\\psialpha}^2}.\n    % &= \\int\\dd{\\vX} P(\\vX,\\valpha)E_L(\\vX,\\valpha),\n\\end{align}\n%\nWe now restructure this integral a bit. Remembering the interpretation of\nthe wave function as a \\gls{pdf}, we can write the \\emph{probability\ndensity} for a given system configuration $\\vX$ as:\n\n\\begin{align}\n    P_{\\psi_{\\vb{\\alpha}}}(\\vX) \\defeq \\frac{\\abs{\\psialpha}^2}{\\int\\dd{\\vX}\\abs{\\psialpha}^2},\\label{eq:wavefunc-probability-density-def}\n\\end{align}\nwhere we account for the possibility of $\\psialpha$ not being normalized to unity. Further, we define a quantity we will call the \\emph{local energy},\n\\begin{align}\n    E_L &\\defeq \\frac{1}{\\psialpha} \\hat H\\psialpha.\\label{eq:local-energy-def}\n\\end{align}\nThe reason for these definitions is that now we can write the energy expectation as follows:\n\n\\begin{align}\n    \\expval{\\hat H} &= \\int\\dd{\\vX} P_{\\psi_{\\valpha}} (\\vX) E_L(\\vX).\n\\end{align}\nWhy is this better? Because this is simply the weighted average of the local\nenergy, something which has a straightforward discrete formulation:\n\\begin{align}\\label{eq:vmc-local-energy-formulation}\n    \\expval{\\hat H} &= \\lim_{N\\rightarrow \\infty} \\frac{1}{N} \\sum_{i = 1}^N E_L(\\vX_i)\n    \\qq{where} \\vb X_i\\disteq P_{\\psi_{\\valpha}}.\n\\end{align}\nSo, if we can sample $\\vX$ from the distribution described by our trial wave\nfunction, we simply need to evaluate the local energy for a sufficiently large\nnumber of configurations  to obtain a good estimate of the expectation value of\nthe Hamiltonian. How exactly to do the sampling is a rather involved topic, and\nwill be handled in \\cref{chp:monte-carlo}.\n\n\\subsection{Updating Parameters}\n\nNow that we can evaluate the energy, the function to minimize, we could in\nprinciple start optimizing our parameters. If the parameters are few and\ndiscrete we could simply evaluate the energy for all of them and pick the one\nwhich gives the best result. However, this approach will quickly become\nintractable for even a modest number of parameters, and more intelligent\nmethods should be pursued.\n\nPerhaps the most common optimization strategy relies on computing the gradient\nof the energy w.r.t. $\\valpha$, and then change $\\valpha$ in the opposite\ndirection of this. After all, a gradient by definition points in the direction\nof steepest (local) ascent, so going the other way will be the direction of steepest\ndescent. How exactly to make these changes is a topic of its own, and discussed in depth in \\cref{chp:machine-learning}, but the simplest implementation is as follows:\n\n\\begin{align}\n    \\valpha^{(i+1)} = \\valpha^{(i)} - \\eta \\grad_{\\valpha}{\\expval{\\hat H}},\n\\end{align}\nfor a suitably chosen hyperparameter $\\eta\\in\\mathbb{R}$, typically $\\eta\\ll 1$.\nThis says that the updated parameters $\\valpha^{(i+1)}$ are equal to the\nprevious ones, $\\valpha^{(i)}$, minus a small step in the direction of the\ngradient of $\\expval{\\hat H}$ w.r.t. each parameter. After a sufficient number\nof iterations, we hope that the parameters converge to their optimal values.\n\nThis raises another question, namely how to compute\n$\\grad_{\\valpha}{\\expval{\\hat H}}$. Using the basic properties of derivatives we get (temporarily omitting the subscript on $\\psialpha$):\n\\begin{align}\n    \\grad_{\\valpha}\\expval{\\hat H} &= \\grad_{\\valpha}\\qty( \\frac{\\int\\dd{\\vX}\\psi^*\\hat H\\psi}{\\int\\dd{\\vX}\\abs{\\psi}^2})\\\\\n    &= \\frac{\\int\\dd{\\vX} \\abs{\\psi}^2 \\qty[ \\int\\dd{\\vX}\n    \\grad_{\\valpha}(\\psi^*)\\hat H\\psi +\n    \\psi^*\\hat H\\grad_{\\valpha}(\\psi)\n    ]}{\\qty(\\int\\dd{\\vX}\\abs{\\psi}^2)^2}\\\\\n    &\\quad{ }\\ -\n    \\frac{\\qty(\\int\\dd{\\vX}\\psi^*\\hat\n    H\\psi)\\qty(\\int\\dd{\\vX}\\grad_{\\valpha}(\\abs{\\psi}^2))}{\\qty(\\int\\dd{\\vX}\\abs{\\psi}^2)^2} \\\\\n    &= \\expval{\\frac{\\grad_{\\valpha}(\\psi^*)\\hat H\\psi + \\psi^*\\hat H\\grad_{\\valpha}(\\psi)}{\\abs{\\psi}^2}}\n    - \\expval{\\hat H}\\expval{\\frac{\\grad_{\\valpha}\\abs{\\psi}^2}{\\abs{\\psi}^2}},\n\\end{align}\nwhere we have used the fact that $\\hat H$ does not depend on $\\valpha$ in any way.\n\nTo further simplify this, we use the trick $\\flatfrac{\\grad(f)}{f}=\\grad(\\ln\nf)$, as well as the hermiticity of $\\hat H$:\n\\begin{align}\n    \\grad_{\\valpha}\\expval{\\hat H}\n    &= \\expval{\\frac{\\grad_{\\valpha}(\\psi^*)\\hat H\\psi + \\grad_{\\valpha}(\\psi)(\\hat H\\psi)^*}{\\abs{\\psi}^2}}\n    - \\expval{\\hat H}\\expval{\\frac{\\grad_{\\valpha}\\abs{\\psi}^2}{\\abs{\\psi}^2}}\\\\\n    &= \\expval{\\grad_{\\valpha}(\\ln \\psi^*) E_L + \\grad_{\\valpha}(\\ln\\psi)E_L^*}\n    - 2\\expval{\\hat H}\\expval{\\grad_{\\valpha}{\\ln\\abs{\\psi}}}.\n\\end{align}\nAt this point, we are going to explicitly assume that the wave function is\nreal. We are not going to propose any complex trial wave functions in this\nthesis, so this assumption will be valid for our purposes. The final expression then becomes (using $\\expval{\\hat H}=\\expval{E_L}$):\n\n\\begin{align}\n    \\grad_{\\valpha}\\expval{\\hat H}\n    &= 2\\qty[\\expval{\\grad_{\\valpha}(\\ln \\psi) E_L}\n    - \\expval{E_L}\\expval{\\grad_{\\valpha}{\\ln\\abs{\\psi}}}].\n    \\label{eq:local-energy-gradient-alpha}\n\\end{align}\nComputationally we already know how to evaluate $\\expval{E_L}$, and we employ a completely analogous approach for the two other expectation values.\nWith this final piece of the puzzle we have everything we need in order to perform a \\gls{vmc} calculation for the ground state of a system.\n\n\\end{document}\n", "meta": {"hexsha": "a6487aef298ffc32b64245964187c750e37995db", "size": 17314, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "writing/VariationalMonteCarlo.tex", "max_stars_repo_name": "johanere/qflow", "max_stars_repo_head_hexsha": "5453cd5c3230ad7f082adf9ec1aea63ab0a4312a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-07-24T21:46:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-11T18:18:24.000Z", "max_issues_repo_path": "writing/VariationalMonteCarlo.tex", "max_issues_repo_name": "johanere/qflow", "max_issues_repo_head_hexsha": "5453cd5c3230ad7f082adf9ec1aea63ab0a4312a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2019-02-19T10:49:26.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-18T09:42:13.000Z", "max_forks_repo_path": "writing/VariationalMonteCarlo.tex", "max_forks_repo_name": "bsamseth/FYS4411", "max_forks_repo_head_hexsha": "72b879e7978364498c48fc855b5df676c205f211", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-11-04T15:17:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-03T16:37:38.000Z", "avg_line_length": 51.8383233533, "max_line_length": 292, "alphanum_fraction": 0.7365138039, "num_tokens": 4843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.3490265660720155}}
{"text": "\\documentclass[review]{elsarticle}\n\n% Packages and macros go here\n\\usepackage{amsfonts}\n\\usepackage{amsmath}\n\\usepackage{lineno,hyperref}\n\\modulolinenumbers[5]\n\\usepackage{graphicx}\n\\usepackage{epstopdf}\n\\usepackage{algorithmic}\n\\usepackage{subcaption}\n\\captionsetup{font=small}\n\\captionsetup[sub]{font=footnotesize}\n\\usepackage{nicefrac}\n\\usepackage{units}\n\\usepackage[acronyms]{glossaries}\n\n\\journal{Elsevier}\n\n% \\title{Data recovery in computational fluid dynamics through deep image priors}\n% \\author[main]{M.~T.~Henry de Frahan\\corref{cor1}}\n% \\ead{marc.henrydefrahan@nrel.gov}\n% \\author[main]{R.~W.~Grout}\n% \\ead{ray.grout@nrel.gov}\n% \\cortext[cor1]{Corresponding author}\n% \\address[main]{High Performance Algorithms and Complex Fluids, Computational Science Center, National Renewable Energy Laboratory, 15013 Denver W Pkwy, ESIF301, Golden, CO 80401, USA}\n\n%% `Elsevier LaTeX' style\n%\\bibliographystyle{elsarticle-num}\n\\bibliographystyle{elsarticle-num-names}\n\\makeatletter\n\\providecommand{\\doi}[1]{%\n  \\begingroup\n  \\let\\bibinfo\\@secondoftwo\n  \\urlstyle{rm}%\n  \\href{http://dx.doi.org/#1}{%\n    doi:\\discretionary{}{}{}%\n    \\nolinkurl{#1}%\n  }%\n  \\endgroup\n}\n\\makeatother\n\n%=================================================================================\n% Abbreviations\n\\newacronym{dns}{DNS}{direct numerical simulations}\n\\newacronym{cfd}{CFD}{computational fluid dynamics}\n\\newacronym{pod}{POD}{proper orthogonal decomposition}\n\\newacronym{gpr}{GPR}{Gaussian process regression}\n\\newacronym{gp}{GP}{Gaussian processes}\n\\newacronym{gpu}{GPU}{graphics processing unit}\n\\makeglossaries\n\\glsdisablehyper\n\n\\begin{document}\n\\begin{frontmatter}\n\n\\title{Data recovery in computational fluid dynamics through deep image priors}\n\n\\author[main]{M.~T.~Henry de Frahan\\corref{cor1}}\n\\ead{marc.henrydefrahan@nrel.gov}\n\n\\author[main]{R.~W.~Grout}\n\\ead{ray.grout@nrel.gov}\n\n\\cortext[cor1]{Corresponding author}\n\n\\address[main]{High Performance Algorithms and Complex Fluids, Computational Science Center, National Renewable Energy Laboratory, 15013 Denver W Pkwy, ESIF301, Golden, CO 80401, USA}\n\n\\begin{abstract}\n\n  One of the challenges encountered by computational simulations at\n  exascale is the reliability of simulations in the face of hardware\n  and software faults. These faults, expected to increase with the\n  complexity of the computational systems, will lead to the loss of\n  simulation data and simulation failure and are currently addressed\n  through a checkpoint-restart paradigm. Focusing specifically on\n  \\gls{cfd} simulations, this work proposes a method that uses a deep\n  convolutional neural network to recover simulation data. This data\n  recovery method (i) is agnostic to the flow configuration and\n  geometry, (ii) does not require extensive training data, and (iii) is\n  accurate for very different physical flows. Results indicate that\n  the use of deep image priors for data recovery is more accurate than\n  standard recovery techniques, such as the \\gls{gpr}, also known as\n  Kriging. Data recovery is performed for two canonical fluid flows:\n  laminar flow around a cylinder and homogeneous isotropic\n  turbulence. For data recovery of the laminar flow around a cylinder,\n  results indicate similar performance between the proposed method and\n  \\gls{gpr} across a wide range of mask sizes. For homogeneous\n  isotropic turbulence, data recovery through the deep convolutional\n  neural network exhibits an error in relevant turbulent quantities\n  approximately three times smaller than that for the\n  \\gls{gpr}. Forward simulations using recovered data illustrate that\n  the enstrophy decay is captured within $10\\%$ using the deep\n  convolutional neural network approach. Although demonstrated\n  specifically for data recovery of fluid flows, this technique can be\n  used in a wide range of applications, including particle image\n  velocimetry, visualization, and computational simulations of\n  physical processes beyond the Navier-Stokes equations.\n\n\\end{abstract}\n\n\\begin{keyword}\ndata recovery \\sep fault tolerance \\sep Gaussian process regression \\sep deep convolutional neural network \\sep computational fluid dynamics\n\\end{keyword}\n\n\\end{frontmatter}\n\n\\glsresetall\n\n\\section{Introduction}\nAs modern computational efforts reach exascale, hardware and software\nfaults will increasingly cause difficulty in completing\nsimulations~\\cite{Brown2010}. Current research in hardware systems and\nsoftware frameworks~\\cite{Gropp2004, Hoemmen2011, Teranishi2014,\n  Cappello2014, Gamell2015, Grout2017} continues to develop techniques\nto detect and anticipate system failures; however, assuming that a\nfault has been detected and signaled, the data loss from these\nfailures will require data recovery processes~\\cite{Lee2015}. This\nwork addresses this challenge. Current computational codes rely\non a checkpoint and restart paradigm to recover from faults, requiring\neither significant memory consumption for frequent checkpoints or\nlarge resimulation efforts. The ability to recover the missing data\nwithout resorting to data checkpoints has the potential to increase\nsimulation resilience.\n\nIn the context of \\gls{cfd}, data recovery has been explored using a\nvariety of machine learning approaches. Gappy \\gls{pod} has shown\nparticular success in reconstructing missing\ndata~\\cite{Everson1995,Tan2003,Venturi2004}. This approach relies on\ncombining \\gls{pod} with least-squares estimates~\\cite{Yates1933,\n  Little2002} and data from \\acrlong{dns} snapshots. Venturi and\nKarniadakis~\\cite{Venturi2004} expanded on the methods proposed by\nEverson and Sirovich~\\cite{Everson1995} and used this technique to\nreconstruct missing data of unsteady flow past a cylinder. Other\napproaches rely on \\gls{gpr}, often referred to as Kriging in\ngeophysics, which is a a reconstruction technique that uses the mean and\ncovariance of the \\acrlong{gp} prior. The prior's covariance is determined\nby a kernel whose hyperparameters are optimized using training\ndata. Gunes et al.~\\cite{Gunes2006} compare \\gls{pod}-based and\n\\gls{gpr}-based solution reconstruction and show that \\gls{gpr}\ninterpolations are particularly effective for unsteady flows\n(including instability regions), whereas \\gls{pod}-based methods are\nadvantageous when the temporal resolution is high. In addition to\nthese methods, Lee et al.~\\cite{Lee2015} proposed a ``resimulation''\nmethod in which the missing data region is resimulated using\nappropriate initial and boundary conditions. This new method is\nevaluated for lid-driven cavity flows and flows past a cylinder at low\nReynolds numbers. Lee et al.~\\cite{Lee2017} combined the gap-tooth\nalgorithm, previously developed for dynamic systems~\\cite{Gear2003},\nmultiresolution information fusion, and auxiliary data to construct a\ngeneral framework for fault-tolerant \\gls{cfd}. The method is\ndemonstrated to work well for simulations of the heat equation and\nlid-driven cavity flow.\n\nRecently, the deep learning community has been proposing methods for\ndata recovery in the field of inverse image reconstruction problems,\nwhich include denoising, inpainting, and\nsuper-resolution,~\\cite{Goodfellow2014,Burger2012,Dosovitskiy2015,Lefkimmiatis2016,Ledig2017,Tai2017,Lai2017}. Deep\nconvolutional neural networks, particularly generative adversarial\nnetworks, have been very successful at solving this class of\nproblems~\\cite{Goodfellow2014}. Inpainting is of particular relevance\nto our objective of reconstructing flow solutions. The objective of\ninpainting is to fill in missing portions of a damaged image such that\nthe result is indistinguishable from the original image. Various\ngenerative adversarial neural networks have been proposed for image\ninpainting with notable\nsuccess~\\cite{Yeh2016,Denton2016,Pathak2016,Li2017a,Sasaki2017}. Generally\nspeaking, these approaches have relied on training deep neural\nnetworks with an extensive and large data set of images such that the\nnetwork learns image priors that it can use in other\nconfigurations. The deep learning methodology used in this work was\nfirst developed by Ulyanov et al.~\\cite{Ulyanov2017} for various\ninverse image reconstruction problems, including inpainting. In\ncontrast with previous image reconstruction solution with deep neural\nnetworks, Ulyanov et al.~\\cite{Ulyanov2017} showed that ``contrary to\nthe belief that learning is necessary for building good image priors,\na great deal of image statistics are captured by the structure of a\nconvolutional image generator independent of learning.''  Instead of\ntraining the neural networks with a large database of images, the\nauthors use untrained neural networks to fit single degraded images,\nusing the network weights as parameters for solving the image\nreconstruction problem.\n\nIn this work, we use deep convolutional neural networks, such as those\nproposed by Ulyanov et al.~\\cite{Ulyanov2017}, for spatial reconstruction of the flow\nsolution for simulations wherein some type of fault led to loss of\ndata, e.g.,\\,processor failure. In contrast to gappy\n\\gls{pod}~\\cite{Venturi2004}, we assume that the current gappy data are\nthe only available data for the reconstruction procedure. This\nassumption is relevant to large simulations where it is\ncomputationally expensive to reload data residing on the file system\nand the reconstruction process is restricted to data already in\nmemory. One advantage of using deep convolutional neural networks is\nthat this approach avoids eigenmode decompositions for solution\nreconstruction, which could restrict the applicability or translation of\nthe method to new configurations. As illustrated in this work, the\nmethod proposed here is not specific to the flow configuration and\ndoes not require multiple training data samples.\n\nThis paper is organized as follows. In Section\\,\\ref{sec:formulation}, we\npresent the problem formulation and define the objective function for\nthe data recovery problem. In Section\\,\\ref{sec:nn}, we detail the\narchitecture of the deep convolutional neural network used to perform\nthe data recovery process for fluid flows. In Section\\,\\ref{sec:results}, we\npresent our results by evaluating the neural network's ability to\nperform data recovery for two canonical flows: laminar flow past a\ncylinder, Section\\,\\ref{sec:cylinder}, and homogeneous isotropic turbulence,\nSection\\,\\ref{sec:hit}. These results are compared with data recovery\nperformed through \\gls{gpr}. Finally, conclusions and future work are\npresented in Section\\,\\ref{sec:ccl}.\n\n\\section{Problem formulation}\\label{sec:formulation}\n\nIn this work, we evaluate the performance of deep convolutional neural\nnetworks for data recovery in \\gls{cfd}. Deep convolutional neural\nnetworks have shown particular success for solving the image\nreconstruction problem~\\cite{Goodfellow2014}. Image reconstruction is\nanalogous to data recovery because they share a similar objective to\nprovide synthetic data that closely match the missing data. The\nimage reconstruction problem can be cast as an optimization problem:\n\\begin{align}\n  \\min_x{E(x;x_0) + R(x)}\n\\end{align}\nwhere $x$ is the original image that needs to be recovered, $x_0$ is\nthe corrupted image, $E(x;x_0)$ is the task-dependent data term, and\n$R(x)$ is the image prior. In the case of inpainting, the\ntask-dependent data term is:\n\\begin{align}\n  E(x;x_0) = || (x-x_0) \\circ m||^2\n\\end{align}\nwhere $\\circ$ is the Hadamart product, $m \\in \\{0,1\\}^{h\\times w}$\nrepresents the binary mask, and $h$ and $w$ are the image height and\nwidth. The image prior is usually captured through the training of\nconvolutional neural networks using a large image database. In the\napproach proposed by Ulyanov et al.~\\cite{Ulyanov2017}, $R(x)$ is replaced by a\nparameterization such that the optimization problem becomes:\n\\begin{align}\n  \\min_\\theta{E(f_\\theta(z); x_0)} \\label{equ:loss}\n\\end{align}\nwhere $f$ represents the convolutional neural network with parameters\n$\\theta$ that is initialized randomly, and $z$ is a fixed input. The\nfixed input for the neural network can take many forms but is usually\nchosen to be random uniform noise or smoothly varying data.\nNote that the neural network input is \\textit{fixed}. Given a\ndeteriorated image, the neural network effectively learns, by\nbackpropagation and network parameter tuning, the encoding necessary\nto map the fixed input to an output, i.e.,\\,the \\textit{recovered}\nimage, which minimizes the loss function,~Equation\\,\\ref{equ:loss}.\n\nWe emphasize that physical constraints are not explicitly included in\nthe data recovery process. This has the advantage of enabling a\nreconstruction technique that does not depend on the physical nature\nof the problem. Higher fidelity can be achieved, however, by\nincorporating physical constraints, as suggested in~\\cite{Raissi2017,\n  Sirignano2018}. The work presented here focuses on two-dimensional\nreconstruction, though there is no inherent methodological limitation\nto reconstructing three-dimensional data directly.\n\n\\section{Neural network architecture}\\label{sec:nn}\n\nThe network chosen for this work is a convolutional neural network\nthat exhibits an encoder-decoder architecture with approximately 2\nmillion tunable parameters and no skip connections,\nFigure\\,\\ref{fig:encoder_decoder}. This architecture enables the\nnetwork to encode the input in the latent space and then decode the\nlatent space representation into the reconstructed image. The\nnonlinear activation function used in the network is LeakyReLU\n\\cite{He2015}. Downsampling was performed through simple striding in\nthe convolution procedure, Figure\\,\\ref{fig:downsample}, and\nupsampling was done through nearest-neighbor upsampling,\nFigure\\,\\ref{fig:upsample}. The number of filters in the downsampling\nand upsampling layers, $n_f$, was kept fixed at 128, and the kernel\nsize, $k$, was fixed at 3. Experiments showed that using a fixed\nsmoothly varying input $z$ for the neural network imposes a smoothness\nprior, which is beneficial for data recovery for fluid flows. The\noptimization process was performed using Adam~\\cite{Kingma2014}. The\nimplementation was done in PyTorch~\\cite{Paszke2017}, and the learning\nprocess was computed on a Tesla V100 \\acrlong{gpu}. The number of\niterations for all the experiments was 2000, thereby reducing\nthe loss function by three orders of magnitude.\n\n\\begin{figure}[!tbp]%\n  \\centering%\n  \\begin{subfigure}[t]{1\\textwidth}%\n    \\includegraphics[width=\\textwidth]{./figs/encoder_decoder.pdf}%\n    \\caption{Encoder-decoder architecture.}\\label{fig:encoder_decoder}%\n  \\end{subfigure}\\\\[0.3cm]%\n  \\begin{subfigure}[b]{0.33\\textwidth}%\n    \\includegraphics[width=0.92\\textwidth]{./figs/downsample.pdf}%\n    \\caption{Downsampling unit.}\\label{fig:downsample}%\n  \\end{subfigure}%\n  \\hfill%\n  \\begin{subfigure}[b]{0.33\\textwidth}%\n    \\includegraphics[width=\\textwidth]{./figs/upsample.pdf}%\n    \\caption{Upsampling unit.}\\label{fig:upsample}%\n  \\end{subfigure}%\n  \\hfill%\n  \\begin{subfigure}[b]{0.15\\textwidth}%\n    \\includegraphics[width=\\textwidth]{./figs/legend.pdf}%\n    \\vspace*{0.4cm}%\n    \\caption{Legend.}\\label{fig:legend}%\n  \\end{subfigure}%\n  \\caption{Deep convolutional neural network used for data recovery.}\\label{fig:arch}%\n\\end{figure}%\n\n\\section{Results}\\label{sec:results}\n\nTo demonstrate the efficacy of using deep neural networks for data\nrecovery, we investigate two types of flows: laminar flow over a\ncylinder for data recovery of large flow scales and homogeneous\nisotropic turbulence for data recovery of flows spanning a wide range\nof scales. We compare the deep convolutional neural network results\nwith \\gls{gpr}. The sample points used to train the \\gls{gpr} are\nlocated in the region surrounding the mask with a depth of 10 cells,\nsimilar to~\\cite{Lee2015}. Beyond a depth of 10 cells surrounding\nthe masked regions, training the regressor becomes computationally\nintractable because the \\gls{gpr} complexity is $\\mathcal{O}(n^3)$, where\n$n$ is the number of training points. A radial basis function is used\nas the \\gls{gpr} kernel.\n\n\\subsection{Laminar flow around a cylinder}\\label{sec:cylinder}\nThe first numerical tests of the data recovery process are performed\nfor the laminar flow around a cylinder ($Re = 200$). The simulation is\nperformed using Nalu-Wind, a low Mach Navier-Stokes solver leveraging\nthe Trilinos\nlibraries\\footnote{\\url{https://github.com/Exawind/nalu-wind}}; and the\n$t=234\\,\\unit{s}$ snapshot is used for the numerical tests, at which\ntime the vortices behind the cylinder were fully developed. Masks\nsimulating data loss because of processor failure are generated in the\ncylinder wake. To capture typical domain decomposition methods for\nstructured grids, the masks are square boxes and vary in size\ndepending on the number of processors used for the simulation. The\nmask box length, $L_m$, ranged from $0.5D$ to $5D$, where $D$ is the\ncylinder diameter, and the masks are located at 40 random locations in\nthe cylinder wake, leading to 240 unique masks to be applied to the\nsimulation data. For the reconstruction process, reflection padding is\nused for the boundary conditions.\n\nAn example reconstruction is presented in\nFigure\\,\\ref{fig:illustrated_cyl} for $L_m=2D$, where the deep\nconvolutional neural network presents a slightly better reconstructed\nvelocity field than \\gls{gpr}. Specifically, the partially masked\nvortex is more accurately reconstructed using the deep convolutional\nneural network. The average $L_2$ error norm for the velocity fields\nas a function of $L_m$ is presented in\nFigure\\,\\ref{fig:cyl_error}. Both reconstruction techniques, \\gls{gpr}\nand the deep convolutional neural network, present similar error\nprofiles. At higher $L_m$ the neural network performs slightly better\nthan \\gls{gpr} for the $x$-direction velocity, whereas it performs\nsimilarly for all other lengths. Given the structured nature of the\nflow field, it is unsurprising that \\gls{gpr} performs well at\nmoderate mask sizes, given previously published\nresults~\\cite{Gunes2006}.\n\n\\begin{figure}[!tbp]%\n  \\centering%\n  \\begin{subfigure}[t]{0.45\\textwidth}%\n    \\includegraphics[width=\\textwidth]{./figs/cyl_umag0.png}%\n    \\caption{Original data.}\\label{fig:cyl_umag0}%\n  \\end{subfigure}%\n  \\hfill%\n  \\begin{subfigure}[t]{0.45\\textwidth}%\n    \\includegraphics[width=\\textwidth]{./figs/cyl_umag0_masked.png}%\n    \\caption{Deteriorated data.}\\label{fig:cyl_umag0_masked}%\n  \\end{subfigure}\\\\%\n  \\begin{subfigure}[t]{0.45\\textwidth}%\n    \\includegraphics[width=\\textwidth]{./figs/cyl_umagr.png}%\n    \\caption{Deep convolutional neural network.}\\label{fig:cyl_umagr}%\n  \\end{subfigure}%\n  \\hfill%\n  \\begin{subfigure}[t]{0.45\\textwidth}%\n    \\includegraphics[width=\\textwidth]{./figs/cyl_umagi.png}%\n    \\caption{\\gls{gpr}.}\\label{fig:cyl_umagi}%\n  \\end{subfigure}%\n  \\caption{Velocity magnitude for laminar flow around a cylinder where the mask box length is twice the cylinder diameter, $L_m=2D$.}\\label{fig:illustrated_cyl}%\n\\end{figure}%\n\n\\begin{figure}[!tbp]%\n  \\centering%\n  \\begin{subfigure}[t]{0.48\\textwidth}%\n    \\includegraphics[width=\\textwidth]{./figs/cyl_error_u.png}%\n    \\caption{$x$-direction velocity.}\\label{fig:cyl_error_u}%\n  \\end{subfigure}%\n  \\hfill%\n  \\begin{subfigure}[t]{0.48\\textwidth}%\n    \\includegraphics[width=\\textwidth]{./figs/cyl_error_v.png}%\n    \\caption{$y$-direction velocity.}\\label{fig:cyl_error_v}%\n  \\end{subfigure}%\n  \\caption{Average $L_2$ error norm as a function of mask box length,\n    $L_m$, for laminar flow past a cylinder ($Re=200$). Red squares:\n    deep convolutional neural network; green diamonds:\n    \\gls{gpr}.}\\label{fig:cyl_error}%\n\\end{figure}%\n\n\n\\subsection{Homogeneous isotropic turbulence}\\label{sec:hit}\n\nFor these numerical tests, we use two-dimensional slices of\nhomogeneous isotropic turbulence with a Taylor microscale Reynolds\nnumber $Re_\\lambda= \\nicefrac{\\rho_0 u' \\lambda}{\\mu}=133$, where\n$\\rho_0$ is the reference density,\n$u' = \\sqrt{\\nicefrac{\\overline{u_i u_i}}{3}}$ is the initial mean\nfluctuating velocity,\n$\\lambda = \\nicefrac{\\overline{u_1^2}}{\\overline{\\left(\\frac{\\partial\n        u_1}{\\partial x_1}\\right)^2}}$ is the Taylor microscale, and\n$\\mu$ is the dynamic viscosity; a turbulent Mach number\n$M_t = \\nicefrac{u_0}{c_s} = 0.1$, where $c_s$ is the speed of sound;\nand a Prandtl number $Pr = \\nicefrac{\\mu c_p}{k} = 0.71$, where $c_p$\nis the heat capacity at constant pressure, and $k$ is the thermal\nconductivity. The reference temperature and pressure are 300~K and 1\natmosphere and the ideal gas equation of state is used to relate the\nthermodynamic quantities. The domain ranges from $[0,2\\pi]$ with\nperiodic boundary conditions. In this work, we use\nPeleC\\footnote{\\url{https://github.com/AMReX-Combustion/PeleC}}, an\nexplicit compressible Navier-Stokes flow solver based on the AMReX\nlibrary\\footnote{\\url{https://amrex-codes.github.io}}, to demonstrate\nthe data recovery process. For the reconstruction process, periodic,\ni.e.,\\,wrapped, padding was used for the boundary conditions.\n\nInitial two-dimensional data slices are generated by slicing in each\ndirection a numerical simulation of homogeneous isotropic turbulence\nat a resolution of 64 cells in each direction, leading to 192 unique\nslices. The velocities in each direction are assigned an input channel\nfor the neural network. Masks simulating data loss because of processor\nfailure are generated independently, following typical domain\ndecomposition. We explore two different parameters associated with the\nmask generation process. The first is the total percentage of missing\ndata, $f$, ranging from $6.25\\%$ to $25\\%$. The second is the length\nscale associated with each block of missing data, $L_m$, ranging from\n$3.125\\%$ to $50\\%$ of the domain length, or $0.74\\lambda$ to\n$11.87\\lambda$. For each pair of parameters $f$ and $L_m$, we randomly\ngenerate ten different masks, resulting in 130 unique masks. These are\nrandomly applied to 100 initial slices, resulting in 1300 slices\nrequiring reconstruction. For each of these deteriorated slices, the\nneural network parameters are tuned to optimize the reconstruction\nloss function, Equation\\,(\\ref{equ:loss}). The data from the resulting\nrecovered slice are then used for comparison with the original\nslice. The data recovery process is illustrated for one slice in\nFigure\\,\\ref{fig:illustrated_hit}.\n\n\\begin{figure}[!tbp]%\n  \\centering%\n  \\begin{subfigure}[t]{0.32\\textwidth}%\n    \\includegraphics[width=\\textwidth]{./figs/umag0.png}%\n    \\caption{Original.}\\label{fig:original}%\n  \\end{subfigure}%\n  \\hfill%\n  \\begin{subfigure}[t]{0.32\\textwidth}%\n    \\includegraphics[width=\\textwidth]{./figs/umag0_masked.png}%\n    \\caption{Deteriorated.}\\label{fig:masked}%\n  \\end{subfigure}%\n  \\hfill%\n  \\begin{subfigure}[t]{0.32\\textwidth}%\n    \\includegraphics[width=\\textwidth]{./figs/umagr.png}%\n    \\caption{Recovered.}\\label{fig:result}%\n  \\end{subfigure}%\n  \\caption{Velocity magnitude in homogeneous isotropic turbulence\n    illustrating the data recovery process, where 25\\% of the original\n    data is missing and the length scale associated to each missing\n    block is 6.25\\% of the domain\n    ($1.5\\lambda$).}\\label{fig:illustrated_hit}%\n\\end{figure}%\n\nThe average error in $u'$ and $\\lambda$ for all the reconstructions is\napproximately three times larger for the \\gls{gpr} process compared to\nthe deep convolutional neural network. For all the slices, individual\nenergy spectra are calculated for the original data and the data\nrecovered through the deep convolutional neural network and\n\\gls{gpr}. The average energy spectrum is presented in\nFigure\\,\\ref{fig:spectra}. The average error from the \\gls{gpr}\nreconstruction increases at high wavenumbers, indicating that it not\nable to accurately capture the smallest scales of turbulence,\nFigure\\,\\ref{fig:error_spectra}. This behavior is not exhibited with\nthe deep neural network reconstruction, and the error increases\nslightly as a function of wavenumber.\n\n\\begin{figure}[!tbp]%\n  \\centering%\n  \\begin{subfigure}[t]{0.48\\textwidth}%\n    \\includegraphics[width=\\textwidth]{./figs/spectra.png}%\n    \\caption{Average energy spectrum.}\\label{fig:spectra}%\n  \\end{subfigure}%\n  \\hfill%\n  \\begin{subfigure}[t]{0.48\\textwidth}%\n    \\includegraphics[width=\\textwidth]{./figs/error_spectra.png}%\n    \\caption{Normalized error, $e_{E_k} = \\frac{|E^h_k - E_k|}{E_k}$.}\\label{fig:error_spectra}%\n  \\end{subfigure}%\n  \\caption{Energy spectrum and error as a function of wavenumber $k$. Solid red: original data; dashed green: deep convolutional neural network; dot-dashed blue: \\gls{gpr}.}\\label{fig:spec}%\n\\end{figure}%\n\nVelocities in slices of the original and recovered data are used as\ninitial conditions for two-dimensional decay simulations. In these\nsimulations performed in PeleC, the initial conditions for the\nvelocity fields are taken from the (i) original data, (ii)\nrecovered data from the deep convolutional neural network, and (iii)\nrecovered data from the \\gls{gpr}. The final time for the simulations\nis $5\\tau$, where $\\tau =\n\\nicefrac{\\lambda}{u'}$. Figure\\,\\ref{fig:hit_enstrophy} illustrates\nthe decay of normalized enstrophy,\n$\\omega = \\frac{\\lambda^2}{u'^2 V}\\int_V \\left( \\nabla \\times u\n\\right)^2 \\mathrm{d}V$, for simulations where $f=25\\%$ and\n$L_m \\in [0.74\\lambda, 11.87\\lambda]$, or $3.125\\%$ to $50\\%$ of the\ndomain length. \\gls{gpr} reconstruction exhibits a significantly\ndifferent enstrophy decay from the original data,\nFigure\\,\\ref{fig:enstrophy_gp}. For the deep convolutional neural\nnetwork, the enstrophy decay is well captured at all mask sizes, with\nslightly less accuracy for large $L_m$,\nFigure\\,\\ref{fig:enstrophy_dl}. Across the range of mask sizes, the\nnormalized error at $t=1\\tau$ in kinetic energy and enstrophy is less than\n10\\% for the deep convolutional neural network and around 20\\% for the\n\\gls{gpr} reconstruction. These differences in reconstruction\nprocedures are attributed to the deep convolutional neural network's\nability to preserve the energy spectra and accurately represent all\nthe length scales.\n\n\\begin{figure}[!tbp]%\n  \\centering%\n  \\begin{subfigure}[t]{0.48\\textwidth}%\n    \\includegraphics[width=\\textwidth]{./figs/enstrophy_result.png}%\n    \\caption{Deep convolutional neural network.}\\label{fig:enstrophy_dl}%\n  \\end{subfigure}%\n  \\hfill%\n  \\begin{subfigure}[t]{0.48\\textwidth}%\n    \\includegraphics[width=\\textwidth]{./figs/enstrophy_interp.png}%\n    \\caption{\\gls{gpr}.}\\label{fig:enstrophy_gp}%\n  \\end{subfigure}%\n  \\caption{Normalized enstrophy as a function of time where 25\\% of\n    the original data is missing. Solid black: original data; solid\n    red: $L_m=0.74\\lambda$; dashed green: $L_m=1.48\\lambda$;\n    dot-dashed blue: $L_m=2.97\\lambda$; dotted orange:\n    $L_m=5.94\\lambda$; dot-dot-dashed purple:\n    $L_m=11.87\\lambda$.}\\label{fig:hit_enstrophy}%\n\\end{figure}%\n\n\n\\section{Conclusion}\\label{sec:ccl}\n\nThis work evaluated the use of deep convolutional neural networks for\ndata recovery of fluid flows in the context of data loss because of\nhardware or software faults. The method proposed here leverages an\nencoder-decoder deep convolutional neural network to transform a fixed\ninput to a recovered output using only deteriorated data and\neschewing a training database. Comparisons were performed with\n\\acrlong{gpr}, a standard data recovery algorithm often referred to as\nKriging. Data recovery was performed on two different canonical flow\nconfigurations: laminar flow around a cylinder and homogeneous\nisotropic turbulence. For data recovery of the laminar flow around a\ncylinder, results indicate similar performance between the proposed\nmethod and \\gls{gpr} across a wide range of mask sizes. For homogeneous\nisotropic turbulence, data recovery through the deep convolutional\nneural network exhibits an error in relevant turbulent quantities\napproximately three times smaller than that for the \\gls{gpr}. Forward\nsimulations using recovered data illustrate that the enstrophy decay\nis accurately captured using the deep convolutional neural network\napproach.\n\nWe emphasize that the work presented here is not necessarily beholden\nto the specific inpainting technique used. The deep learning community\nhas developed many different methods for image inpainting that can be\nused for data recovery, and it is expected that state-of-the-art\nmethodologies would perform comparably well. Rather, the use of deep\nimage priors as first proposed by Ulyanov et al.~\\cite{Ulyanov2017}\nand investigated here provides a convenient framework to perform data\nrecovery of fluid flows because it does not require pretraining the neural\nnetwork to construct image priors for different flows. It is therefore\nagnostic to the specific flow configuration, and the same framework can\nbe used for very different flows. This technique, however, does\nnecessitate the solution of an optimization problem for each data\nrecovery task. Future work will investigate alleviating this through\npartial pretraining, transfer learning, and perceptual loss\nfunctions.\n\nThis work --- including data sets, demonstration notebooks, analysis\nscripts, and figures --- can be publicly accessed at the project's GitHub\npage.\\footnote{\\url{https://github.com/NREL/deep-image-prior-cfd}} Traditional\nmachine learning algorithms were implemented through\nscikit-learn~\\cite{Pedregosa2011} and the deep learning algorithms\nthrough PyTorch~\\cite{Paszke2017}.\n\n\\section*{Acknowledgments}\nThis work was authored by the National Renewable Energy Laboratory, operated by Alliance for Sustainable Energy, LLC, for the U.S. Department of Energy (DOE) under Contract No. DE-AC36-08GO28308. Funding provided by U.S. Department of Energy Office of Science and National Nuclear Security Administration. The views expressed in the article do not necessarily represent the views of the DOE or the U.S. Government. The U.S. Government retains and the publisher, by accepting the article for publication, acknowledges that the U.S. Government retains a nonexclusive, paid-up, irrevocable, worldwide license to publish or reproduce the published form of this work, or allow others to do so, for U.S. Government purposes.\n\nThis research was supported by the Exascale Computing Project (ECP), Project Number: 17-SC-20-SC, a collaborative effort of two DOE organizations -- the Office of Science and the National Nuclear Security Administration -- responsible for the planning and preparation of a capable exascale ecosystem -- including software, applications, hardware, advanced system engineering, and early testbed platforms -- to support the nation's exascale computing imperative.\n\n\\section*{References}\n\\bibliography{library}\n\n\\end{document}", "meta": {"hexsha": "8f1f31728e92e5733a7d9fad66c0fe4c78c0a514", "size": 30605, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/report.tex", "max_stars_repo_name": "NREL/deep-image-prior-cfd", "max_stars_repo_head_hexsha": "85a86ac10bef070b1a973d2a6569849583e08d79", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-02-06T20:55:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-06T02:43:38.000Z", "max_issues_repo_path": "paper/report.tex", "max_issues_repo_name": "NREL/deep-image-prior-cfd", "max_issues_repo_head_hexsha": "85a86ac10bef070b1a973d2a6569849583e08d79", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/report.tex", "max_forks_repo_name": "NREL/deep-image-prior-cfd", "max_forks_repo_head_hexsha": "85a86ac10bef070b1a973d2a6569849583e08d79", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-20T10:29:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-24T21:55:41.000Z", "avg_line_length": 51.960950764, "max_line_length": 718, "alphanum_fraction": 0.7848064042, "num_tokens": 7914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.34901492743438106}}
{"text": "\\XtoCBlock{Sin3Gen}\r\n\\label{block:Sin3Gen}\r\n\\begin{figure}[H]\\includegraphics{Sin3Gen}\\end{figure} \r\n\r\n\\begin{XtoCtabular}{Inports}\r\nA & Amplitude\\tabularnewline\r\n\\hline\r\nf & Frequency\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n\r\n\\begin{XtoCtabular}{Outports}\r\nu & Sine wave output phase u\\tabularnewline\r\n\\hline\r\nv & Sine wave output phase v\\tabularnewline\r\n\\hline\r\nw & Sine wave output phase w\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n\\begin{XtoCtabular}{Mask Parameters}\r\nfmax & Maximum Frequency in Hz\\tabularnewline\r\n\\hline\r\nOffset & Offset\\tabularnewline\r\n\\hline\r\nts\\_fact & Multiplication factor of base sampling time (in integer format)\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n\\subsubsection*{Description:}\r\nGeneration of a 3 sine waves with amplitude (A) and frequency (f).\r\n\n% include optional documentation file\r\n\\InputIfFileExists{\\XcHomePath/Library/General/Doc/Sin3Gen_Info.tex}{\\vspace{1ex}}{}\r\n\r\n\\subsubsection*{Implementations:}\r\n\\begin{tabular}{l l}\r\n\\textbf{FiP8} & 8 Bit Fixed Point Implementation\\tabularnewline\r\n\\textbf{FiP16} & 16 Bit Fixed Point Implementation\\tabularnewline\r\n\\textbf{FiP32} & 32 Bit Fixed Point Implementation\\tabularnewline\r\n\\textbf{Float32} & 32 Bit Floating Point Implementation\\tabularnewline\r\n\\textbf{Float64} & 64 Bit Floating Point Implementation\\tabularnewline\r\n\\end{tabular}\r\n\r\n\\XtoCImplementation{FiP8}\r\n\\index{Block ID!432}\r\n\\nopagebreak[0]\r\n% Implementation details\r\n\\begin{tabular}{l l}\r\n\\textbf{Name} & FiP8 \\tabularnewline\r\n\\textbf{ID} & 432 \\tabularnewline\r\n\\textbf{Revision} & 1.0 \\tabularnewline\r\n\\textbf{C filename} & Sin3Gen\\_FiP8.c \\tabularnewline\r\n\\textbf{H filename} & Sin3Gen\\_FiP8.h \\tabularnewline\r\n\\end{tabular}\r\n\\vspace{1ex}\r\n\r\n8 Bit Fixed Point Implementation\r\n\r\n\\begin{XtoCtabular}{Controller Parameters}\r\ndelta\\_phi & Angle increment\\tabularnewline\r\n\\hline\r\noffset & Amplitude offset\\tabularnewline\r\n\\hline\r\nphi & Current angle\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n% Implementation data structure\r\n\\XtoCDataStruct{Data Structure:}\r\n\\begin{lstlisting}\r\ntypedef struct {\r\n     uint16        ID;\r\n     int8          *A;\r\n     int8          *f;\r\n     int8          u;\r\n     int8          v;\r\n     int8          w;\r\n     int8          delta_phi;\r\n     int8          offset;\r\n     int8          phi;\r\n} SIN3GEN_FIP8;\r\n\\end{lstlisting}\r\n\r\n\\ifdefined \\AddTestReports\r\n\\InputIfFileExists{\\XcHomePath/Library/General/Doc/Test_Sin3Gen_FiP8.tex}{}{}\r\n\\fi\r\n\\XtoCImplementation{FiP16}\r\n\\index{Block ID!433}\r\n\\nopagebreak[0]\r\n% Implementation details\r\n\\begin{tabular}{l l}\r\n\\textbf{Name} & FiP16 \\tabularnewline\r\n\\textbf{ID} & 433 \\tabularnewline\r\n\\textbf{Revision} & 1.0 \\tabularnewline\r\n\\textbf{C filename} & Sin3Gen\\_FiP16.c \\tabularnewline\r\n\\textbf{H filename} & Sin3Gen\\_FiP16.h \\tabularnewline\r\n\\end{tabular}\r\n\\vspace{1ex}\r\n\r\n16 Bit Fixed Point Implementation\r\n\r\n\\begin{XtoCtabular}{Controller Parameters}\r\ndelta\\_phi & Angle increment\\tabularnewline\r\n\\hline\r\noffset & Amplitude offset\\tabularnewline\r\n\\hline\r\nphi & Current angle\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n% Implementation data structure\r\n\\XtoCDataStruct{Data Structure:}\r\n\\begin{lstlisting}\r\ntypedef struct {\r\n     uint16        ID;\r\n     int16         *A;\r\n     int16         *f;\r\n     int16         u;\r\n     int16         v;\r\n     int16         w;\r\n     int16         delta_phi;\r\n     int16         offset;\r\n     int16         phi;\r\n} SIN3GEN_FIP16;\r\n\\end{lstlisting}\r\n\r\n\\ifdefined \\AddTestReports\r\n\\InputIfFileExists{\\XcHomePath/Library/General/Doc/Test_Sin3Gen_FiP16.tex}{}{}\r\n\\fi\r\n\\XtoCImplementation{FiP32}\r\n\\index{Block ID!434}\r\n\\nopagebreak[0]\r\n% Implementation details\r\n\\begin{tabular}{l l}\r\n\\textbf{Name} & FiP32 \\tabularnewline\r\n\\textbf{ID} & 434 \\tabularnewline\r\n\\textbf{Revision} & 1.0 \\tabularnewline\r\n\\textbf{C filename} & Sin3Gen\\_FiP32.c \\tabularnewline\r\n\\textbf{H filename} & Sin3Gen\\_FiP32.h \\tabularnewline\r\n\\end{tabular}\r\n\\vspace{1ex}\r\n\r\n32 Bit Fixed Point Implementation\r\n\r\n\\begin{XtoCtabular}{Controller Parameters}\r\ndelta\\_phi & Angle increment\\tabularnewline\r\n\\hline\r\noffset & Amplitude offset\\tabularnewline\r\n\\hline\r\nphi & Current angle\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n% Implementation data structure\r\n\\XtoCDataStruct{Data Structure:}\r\n\\begin{lstlisting}\r\ntypedef struct {\r\n     uint16        ID;\r\n     int32         *A;\r\n     int32         *f;\r\n     int32         u;\r\n     int32         v;\r\n     int32         w;\r\n     int32         delta_phi;\r\n     int32         offset;\r\n     int32         phi;\r\n} SIN3GEN_FIP32;\r\n\\end{lstlisting}\r\n\r\n\\ifdefined \\AddTestReports\r\n\\InputIfFileExists{\\XcHomePath/Library/General/Doc/Test_Sin3Gen_FiP32.tex}{}{}\r\n\\fi\r\n\\XtoCImplementation{Float32}\r\n\\index{Block ID!435}\r\n\\nopagebreak[0]\r\n% Implementation details\r\n\\begin{tabular}{l l}\r\n\\textbf{Name} & Float32 \\tabularnewline\r\n\\textbf{ID} & 435 \\tabularnewline\r\n\\textbf{Revision} & 0.1 \\tabularnewline\r\n\\textbf{C filename} & Sin3Gen\\_Float32.c \\tabularnewline\r\n\\textbf{H filename} & Sin3Gen\\_Float32.h \\tabularnewline\r\n\\end{tabular}\r\n\\vspace{1ex}\r\n\r\n32 Bit Floating Point Implementation\r\n\r\n\\begin{XtoCtabular}{Controller Parameters}\r\ndelta\\_phi & Angle increment\\tabularnewline\r\n\\hline\r\noffset & Amplitude offset\\tabularnewline\r\n\\hline\r\nphi & Current angle\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n% Implementation data structure\r\n\\XtoCDataStruct{Data Structure:}\r\n\\begin{lstlisting}\r\ntypedef struct {\r\n     uint16        ID;\r\n     float32       *A;\r\n     float32       *f;\r\n     float32       u;\r\n     float32       v;\r\n     float32       w;\r\n     float32       delta_phi;\r\n     float32       offset;\r\n     float32       phi;\r\n} SIN3GEN_FLOAT32;\r\n\\end{lstlisting}\r\n\r\n\\ifdefined \\AddTestReports\r\n\\InputIfFileExists{\\XcHomePath/Library/General/Doc/Test_Sin3Gen_Float32.tex}{}{}\r\n\\fi\r\n\\XtoCImplementation{Float64}\r\n\\index{Block ID!436}\r\n\\nopagebreak[0]\r\n% Implementation details\r\n\\begin{tabular}{l l}\r\n\\textbf{Name} & Float64 \\tabularnewline\r\n\\textbf{ID} & 436 \\tabularnewline\r\n\\textbf{Revision} & 0.1 \\tabularnewline\r\n\\textbf{C filename} & Sin3Gen\\_Float64.c \\tabularnewline\r\n\\textbf{H filename} & Sin3Gen\\_Float64.h \\tabularnewline\r\n\\end{tabular}\r\n\\vspace{1ex}\r\n\r\n64 Bit Floating Point Implementation\r\n\r\n\\begin{XtoCtabular}{Controller Parameters}\r\ndelta\\_phi & Angle increment\\tabularnewline\r\n\\hline\r\noffset & Amplitude offset\\tabularnewline\r\n\\hline\r\nphi & Current angle\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n% Implementation data structure\r\n\\XtoCDataStruct{Data Structure:}\r\n\\begin{lstlisting}\r\ntypedef struct {\r\n     uint16        ID;\r\n     float64       *A;\r\n     float64       *f;\r\n     float64       u;\r\n     float64       v;\r\n     float64       w;\r\n     float64       delta_phi;\r\n     float64       offset;\r\n     float64       phi;\r\n} SIN3GEN_FLOAT64;\r\n\\end{lstlisting}\r\n\r\n\\ifdefined \\AddTestReports\r\n\\InputIfFileExists{\\XcHomePath/Library/General/Doc/Test_Sin3Gen_Float64.tex}{}{}\r\n\\fi\r\n", "meta": {"hexsha": "430e016fad940d82610595d72fd13c493bc3d96c", "size": 6878, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Library/General/Doc/Sin3Gen.tex", "max_stars_repo_name": "AlexisTM/X2C", "max_stars_repo_head_hexsha": "31f39b598afe271a7fd46ef1ee9e06c410b1120c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Library/General/Doc/Sin3Gen.tex", "max_issues_repo_name": "AlexisTM/X2C", "max_issues_repo_head_hexsha": "31f39b598afe271a7fd46ef1ee9e06c410b1120c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Library/General/Doc/Sin3Gen.tex", "max_forks_repo_name": "AlexisTM/X2C", "max_forks_repo_head_hexsha": "31f39b598afe271a7fd46ef1ee9e06c410b1120c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3524904215, "max_line_length": 90, "alphanum_fraction": 0.6930793835, "num_tokens": 2099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926666143434, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3490149273557987}}
{"text": "\\section{Conclusion}\\label{sec:conclusion}\n\nPrice response functions provide quantitative information on the deviation from\nMarkovian behavior. They measure price changes resulting from execution of\nmarket orders. We used these functions in big data analysis for spot foreign\nexchange markets. Such a study was, to the best of our knowledge, never done\nbefore.\n\nWe analyzed price response functions in spot foreign exchange markets for\ndifferent years and different time scales. We used trade time scale and\nphysical time scale to compute the price response functions for the seven major\nforeign exchange pairs for three different years. These major pairs are highly\nrelevant in the dynamics of the market. The use of different time scales and\ncalendar years in the work had the intention to display the different behaviors\nthe price response function could take when the time parameters differ.\n\nThe price response functions were analyzed according to the time scales. On\ntrade time scale, the signals were noisier. For both time scales we observe\nthat the signal for all the pairs increases to a maximum and then starts to\nslowly decrease. However, for the year 2008 the shape of the signals is not as\nwell defined as in the other years. The increase-decrease behavior observed in\nthe spot foreign exchange market was also reported in correlated financial\nmarkets \\cite{my_paper_response_financial,Wang_2016_avg}. These results show\nthat the price response functions conserve their behavior in different years\nand in different markets. The shape of the price\nresponse functions is qualitatively explained considering an initial increase\ncaused by the autocorrelated transaction flow. To assure diffusive prices,\nprice response flattens due to market liquidity adapting to the flow in the\ninitial increase.\n\nOn both scales, the more liquid pairs have a smaller price response function\ncompared with the non-liquid pairs. As the liquid pairs have more trades during\nthe market time, the impact of each trade is reduced. Comparing years and\nscales, the price response signal is stronger in past than in recent years. As\nalgorithmic trading has gained great relevance, the quantity of trades has\ngrown in recent years, and in consequence, the impact in the response has\ndecreased.\n\nFinally, we checked the pip bid-ask spread impact in price response functions\nfor three different years. We used 46 foreign exchange pairs and grouped them\ndepending on the conditions of the corresponding year analyzed. We employ the\nyear average pip bid-ask spread of every pair for each year. For all the year\nand time scales, the price response function signals were stronger for the\ngroups of pairs with larger pip bid-ask spreads and weaker for the group of\npairs with smaller bid-ask spreads. For the average of the price response\nfunctions, it was only possible to see the increase-maximum-decrease behavior\nin the year 2015 in both scales, and in the year 2019 on trade time scale.\nHence, the noise in the cross and exotic pairs due to the lack of trading\ncompared with the majors seems stronger. A general average price response\nbehavior for each year and time scale was spotted for the groups, suggesting a\nmarket effect on the foreign exchange pairs in each year.\n\nComparing the response functions in stock and spot currency exchange markets\nfrom a more general viewpoint, we find a remarkable similarity. It triggers the\nconclusion that the order book mechanism generates in a rather robust fashion\nthe observed universal features in these two similar, yet different subsystems\nwithin the financial system.", "meta": {"hexsha": "b90bbfe7996beb0321fe8ceb3d86757bf64be699", "size": 3598, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/forex_response_spread_paper/sections/09_conclusion.tex", "max_stars_repo_name": "juanhenao21/forex", "max_stars_repo_head_hexsha": "251ccccfc9a49f546db5e325ea6b594ff035d97f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-01T07:22:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-01T07:22:34.000Z", "max_issues_repo_path": "paper/forex_response_spread_paper/sections/09_conclusion.tex", "max_issues_repo_name": "juanhenao21/forex", "max_issues_repo_head_hexsha": "251ccccfc9a49f546db5e325ea6b594ff035d97f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2020-03-17T09:30:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-27T08:43:29.000Z", "max_forks_repo_path": "paper/forex_response_spread_paper/sections/09_conclusion.tex", "max_forks_repo_name": "juanhenao21/forex", "max_forks_repo_head_hexsha": "251ccccfc9a49f546db5e325ea6b594ff035d97f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 63.1228070175, "max_line_length": 79, "alphanum_fraction": 0.8224013341, "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.3490149188820786}}
{"text": "\\section{User Guide}\nThis section contains descriptions of how the gravity effector code works and includes descriptions of and notes on variables. It should be helpful to users who wish to use the gravity effector module.\n\n\\subsection{Code Diagram}\nThe diagram in Fig. \\ref{img:codeFlow} demonstrates the basic iterative logic of the gravity effector module. There is extensive additional code that deals with things from the messaging system to transforming the spacecraft position from one frame to another. In general, the inputs shown must be given for each gravity body to be considered. There are, however, convenience functions which add the standard values of these inputs for common celestial bodies. An example is simIncludeGravbody.createEarth() in the test\\_scenarioOrbitManeuver.py tutorial.\n\nAfter the inputs are given for each gravity body, the computeGravityInertial() method calculates the $0^{\\textrm{th}}$ degree gravity term for each body and its effects on the spacecraft. If useSphericalHarmParams is True for a given body, then computeField() is called to calculate higher degree spherical harmonics terms for that body.\n\n\\begin{figure}[H]\n\t\\centering \\includegraphics[height=1.0\\textwidth, keepaspectratio]{Figures/codeFlow.pdf}\n\t\\caption{A pseudo-code diagram demonstrating the flow of inputs and outputs in the gravity effector module.}\n\t\\label{img:codeFlow}\n\\end{figure}\n\n\\subsection{Variable Definition and Code Description}\nThe variables in Table \\ref{tabular:vars} are available for user input. Variables used by the module but not available to the user are not mentioned here. Variables with default settings do not necessarily need to be changed by the user, but may be.\n\\begin{table}[H]\n\t\\caption{Definition and Explanation of Variables Used.}\n\t\\label{tab:errortol}\n\t\\centering \\fontsize{10}{10}\\selectfont\n\t\\begin{tabular}{ | m{3cm}| m{3cm} | m{3cm} | m{6cm} |} % Column formatting, \n\t\t\\hline\n\t\t\\textbf{Variable}   \t\t\t\t\t\t\t& \\textbf{LaTeX Equivalent} \t&\t\t\\textbf{Variable Type} & \\textbf{Notes}\t\t\t  \\\\ \\hline\n\t\tspherHarm.maxDeg\t\t\t\t\t&$l_{\\text{max}}$\t\t \t  & double & Default setting: 0\"inertial\\_state number of degree to use when calculating gravity effects using sperical harmonics.\\\\ \\hline\n\t\tradEquator\t\t\t   & $R_{\\mathrm{ref}}^{l}$\t\t\t& double & [m] Default setting: 0.0. \tThis is the reference radius of the gravity body.\\\\ \\hline\n\t\tmuBody\t\t\t\t\t& $\\mu$ \t\t& double & [m3/s2] Default setting: 0.0f. This is the gravitational parameter of the body. Required Input to get any non-zero values out of the code.\\\\ \\hline\n\t\tisCentralBody & N/A & bool & Default setting: False. Determines whether the body in question is the central body and if initial spacecraft position and velocity are determined as relative or inertial.\\\\ \\hline\n\t\tisDisplayBody & N/A & bool & Default setting: False. Determines whether the body in question is the focus of the visualization\\\\ \\hline\n\t\tephemTime & N/A & double & [s] Default setting: 0. The ephemeris time for the body in question \\\\ \\hline\n\t\tephIntTime & N/A & double & [s] Default setting: 0. Required Input. The integration time associated with the ephem data. \\\\ \\hline\n\t\tbodyInMsgName & N/A & string & Required Input. The name of the message with gravity body data in the body frame. \\\\ \\hline\n\t\toutputMsgName & N/A & string & Required Input. The name of the message containing ephemeris information in display frame \\\\ \\hline\n\t\tplanetEphemName & N/A & string & Required Input. An ephemeris name for the planet (user-named). \\\\ \\hline\n\t\t\\label{tabular:vars}\n\t\\end{tabular}\n\\end{table}\n\n\\subsection{Using Central Bodies and Relative Dynamics}\n\\subsubsection{Using Central Bodies}\nIn simulations with multiple planetary bodies, using dynamics relative to a central body can improve accuracy. Generally, this is the right thing to do rather than using an absolute coordinate set. If a user has a gravBody called \\verb|earth|, the central body flag should be set to True.\n\\verb|earth.isCentralBody = True|\t\nThe dynamics will then take care of themselves, but the user needs to be careful to input initial position and velocity values as \\textit{relative to} the central body. This can be input from a set of Keplerian orbital elements using \\verb|orbitalMotion.elem2rv| as in\\\\ \\verb|Basilisk/tests/scenarios/scenarioBasicOrbit.py|. \n\nThe user should be aware that if spacecraft position and velocity are read back from a message log or plotted that the absolute position and velocity will be returned. It will take additional work to convert the outputs back to a relative form by subtracting out the central body positions and velocities. No rotation will be needed, though.\nIt is critical that the relative position and velocities are given in a frame which is linearly translated but \\textbf{not rotated} from the simulation inertial frame. There is no handling of rotated relative frames within the dynamics. The orbital element to position and velocity conversion in the section below can be used for relative dynamics inputs, as well.\n\n\\subsubsection{Not Using Central Bodies}\nIf no planets are designated as central bodies, an absolute initial position and velocity must be given. Again, \\verb|orbitalMotion.elem2rv| can be used if the orbital elements are given in a frame not rotated from the simulation inertial frame. However, now, the initial position and velocity of the central body must be accounted for. These can be retrieved from spice via the planetStates utility:\\\\\\\\\n\\verb|oe = om.ClassicElements()|\\\\\n\\verb|oe.a = orbit_a * 1000 #m, orbit semi-major axis|\\\\\n\\verb|oe.e = orbit_e #eccentricity|\\\\\n\\verb|oe.i = radians(orbit_i) #inclination, radians.|\\\\\n\\verb|oe.Omega = radians(orbit_O) # orbit RAA, radians|\\\\\n\\verb|oe.omega = radians(orbit_o) #orbit argument of periapsis, radians|\\\\\n\\verb|oe.f = radians(orbit_f) # orbit true anomaly, radians|\\\\\n\\verb|r_sc_E, v_sc_E = om.elem2rv(muEarth, oe) #get xyz coordinates from keplerian elements|\\\\\\\\\n\\verb|ephemerides = spice_interface.SpiceInterface()|\\\\\n\\verb|ephemerides.ModelTag = \"SpiceInterfaceData\"|\\\\\n\\verb|ephemerides.SPICEDataPath = splitPath[0] + '../supportData/EphemerisData/'|\\\\\n\\verb|ephemerides.outputBufferCount = 2|\\\\\n\\verb|ephemerides.planetNames = spice_interface.StringVector([\"earth\", \"sun\"])|\\\\\n\\verb|ephemerides.UTCCalInit = simStart #pick a UTC string|\\\\\n\\verb|earthPos_N, earthVel_N = planetStates.planetPositionVelocity('EARTH', simStart)|\\\\\n\\verb|r_sc_N = array(r_sc_E).flatten() + array(earthPos_N).flatten()|\\\\\n\\verb|v_sc_N = array(v_sc_E).flatten() + array(earthVel_N).flatten()|\\\\\n\\verb|scObject.hub.r_CN_NInit = array(r_sc_N)|\\\\\n\\verb|scObject.hub.v_CN_NInit = array(v_sc_N)|\\\\\\\\\nOf course, if a user has initial positions and velocities directly, those should be used. See scenarioCentralBody.py for a working example.\\\\\n\n\\subsubsection{Reference Frames}\nAn understanding of spice reference frames will help to explain the code above. The spice inertial frame is the ICRF. The ICRF is coplaner with the Earth's equator. Generally, the Earth Centered Inertial system one would give Keplerian elements in is aligned with ICRF. ICRF is referred to within spice as \"j2000\" for legacy reasons and because the J2000 system is only rotated from the ICRF by a few milliarcseconds.\n\n", "meta": {"hexsha": "2792376cca7b13e0311f20b11143de66eb23249f", "size": 7244, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/simulation/dynamics/gravityEffector/_Documentation/secUserGuide.tex", "max_stars_repo_name": "ian-cooke/basilisk_mag", "max_stars_repo_head_hexsha": "a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/simulation/dynamics/gravityEffector/_Documentation/secUserGuide.tex", "max_issues_repo_name": "ian-cooke/basilisk_mag", "max_issues_repo_head_hexsha": "a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-03-13T20:52:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-13T20:52:22.000Z", "max_forks_repo_path": "src/simulation/dynamics/gravityEffector/_Documentation/secUserGuide.tex", "max_forks_repo_name": "ian-cooke/basilisk_mag", "max_forks_repo_head_hexsha": "a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 99.2328767123, "max_line_length": 555, "alphanum_fraction": 0.7715350635, "num_tokens": 1865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.3490149188820786}}
{"text": "\\documentclass[10pt]{asme2ej}\n\n% Edited as https://www.overleaf.com/project/5f8228e5060d380001e71b21\n\n\\usepackage{epsfig} %% for loading postscript figures\n\\usepackage{placeins}\n\\usepackage[all]{xy}\n\\usepackage{dsserif}\n\\usepackage{listings}\n\\usepackage{xcolor}\n\\definecolor{codegreen}{rgb}{0,0.6,0}\n\\definecolor{codegray}{rgb}{0.5,0.5,0.5}\n\\definecolor{codepurple}{rgb}{0.58,0,0.82}\n\\definecolor{backcolour}{rgb}{0.95,0.95,0.92}\n\\lstdefinestyle{mystyle}{\n    backgroundcolor=\\color{backcolour},   \n    commentstyle=\\color{codegreen},\n    keywordstyle=\\color{magenta},\n    numberstyle=\\tiny\\color{codegray},\n    stringstyle=\\color{codepurple},\n    basicstyle=\\ttfamily\\footnotesize,\n    breakatwhitespace=false,         \n    breaklines=true,                 \n    captionpos=b,                    \n    keepspaces=true,                 \n    numbers=left,                    \n    numbersep=5pt,                  \n    showspaces=false,                \n    showstringspaces=false,\n    showtabs=false,                  \n    tabsize=2\n}\n\n\\lstset{style=mystyle}\n\n\\newcommand{\\catname}[1]{\\textbf{#1}}\n\\newcommand{\\Set}{\\catname{Set}}\n\\newcommand{\\Rel}{\\catname{Rel}}\n\n%% The class has several options\n%  onecolumn/twocolumn - format for one or two columns per page\n%  10pt/11pt/12pt - use 10, 11, or 12 point font\n%  oneside/twoside - format for oneside/twosided printing\n%  final/draft - format for final/draft copy\n%  cleanfoot - take out copyright info in footer leave page number\n%  cleanhead - take out the conference banner on the title page\n%  titlepage/notitlepage - put in titlepage or leave out titlepage\n%  \n%% The default is oneside, onecolumn, 10pt, final\n\n\n\\title{Intuitionistic Logic Implemented in Scala\\\\\nSubmitted for Publication at SAI Computing Conference, London, 2021}\n\n%%% first author\n\\author{Vlad Patryshev}\t\n\n\n\n\\begin{document}\n\\UseRawInputEncoding\n\n\\maketitle    \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{abstract}\n{\\it \nAn implementation of intuitionistic (Grothendieck topos-based, for a finite site) is described, with a variety of examples. \n\nThis paper demonstrates how non-Boolean logic can be implemented, to enable using all the power of Intuitionism. For that, a library was developed that works with topos logic. Sample code shows the logic for a variety of sites. \n}\n\\end{abstract}\n\n\\section{Introduction}\n\n In this paper I present a Scala implementation of topos logic (that is, an intuitionistic logic). Intuitionism includes all kinds of fuzzy and temporal logic (see TLA+). Having a code package modeling Intuitionism, one can experiment with different kinds of fuzziness and different shape s of time flow. The toposes used are Grothendieck toposes, and the sites are finite. \n \n Two categories (toposes) are chosen over which Grothendieck toposes are built. These categories are $Set$ and $Setf$, that is, a category of all (available in the code) sets, and the category of all finite sets available in the code. Since Scala does not exactly implement sets as are defined in set theories, a couple of new classes are introduced to resolve this issue.\n\nThis paper demonstrates how non-Boolean logic can be implemented, to enable using all the power of Intuitionism. For that, a library was developed that works with topos logic. Sample code shows the logic for a variety of sites.\nThe code is located at \n\\verb+https://github.com/vpatryshev/Categories+.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Non-Boolean Logic}\nLet us first introduce the idea of non-Booleanness, in a strict mathematical sense of the term. \n\n\\subsection{The Meaning of Non-Booleanness}\n\nTraditionally, as soon as we switch from the complicated logic of the real world into the realm of formal software design, we assume that just two outcomes are possible for any statement: it is either true or false. \nThis is not a feature of mathematical discourse but rather an interesting feature of the modern way of thinking. \nIn real life, we admit that there are more possibilities: something we may not know today, we may learn tomorrow. \nWe may assume something to be true with a certain probability. \nSimilarly, in science we may not know the answer, and the answer may be something we don't expect - like with the case of Continuum Hypothesis.\n\nIn intuitionistic logic, the double negation law does not have to hold. If it does, the logic is Boolean. Here we will show a way to eliminate the double negation law while keeping the remaining rules and axioms that don't depend on double negation.\nOf course, if the double negation law is included, we still have an intuitionistic logic that is also Boolean.\n\nAlso a logic may have more than two logical constants, but that does not make it non-Boolean. \nThe double negation rule may still be applicable in such a logic.\n\n\\subsubsection{Example 1. Boolean Logic, but not 2-Valued}\n\nConsider bytes and their operations: bitwise conjunction, bitwise disjunction, and negation. There are 256 different values, but we know\nthat double negation in this bitwise logic is an identity. \nSo, this 256-valued logic is Boolean.\\\\\n\n\\subsection{Dropping Booleanness}\n\nRemove the rule stating that either $P$ or $\\neg P$ is true.\nFormally, that $\\vdash P \\lor \\neg P$. Once we remove this rule, \nwe cannot apply it anymore in general settings, although it may still work in some cases.\n\nWe immediately bump into a problem: this rule was used to define\nimplication: $P\\ \\rightarrow\\ Q\\ \\equiv\\ \\neg\\ P\\ \\lor\\ Q$. \nWe must define implication differently. Here's a reasonable alternative solution:\n\n$$(P \\land Q)\\vdash R \\equiv P \\vdash ( Q \\rightarrow R)$$\n\nInformally, saying that $R$ can be deduced from a conjunction $P\\land Q$\nis the same as saying that we can deduce the implication $Q\\rightarrow R$ from $P$. \nImagine $Q$ is $\\top$. Then, from the formula\nabove, it follows that $Q\\rightarrow R$ is the same as R. On the other hand,\nif $Q$ is closer to the bottom, the situation may change. \nFor example, if $Q$ is “below” $R$, the implication $Q\\rightarrow R$ is true.\nWe can interpret the implication defined this way as the level of dependency of $R$ on $Q$.\\\\\n\nAs you see, we can define implication via conjunction, and negation is not involved.\\\\\n\nDoes this remind you currying? Given a function $f(P,Q):R$, we\ntransform it to a function $f_c(P): Q \\rightarrow R$.\\\\\n\nNow that implication is defined, we can define negation as\n$\\neg P = P\\rightarrow \\bot$. Its properties make it\nsimilar to classical negation, but the double negation law is not generally applicable anymore. Assume we use the definition above. \nIn the table below, we list some properties that are valid for this definition.\n\\FloatBarrier\n\\begin{table}[!htbp]\n\\begin{center}\n\\label{table_Sample_Statements}\n\\begin{tabular}{c l l}\n& & \\\\ \n\\hline\nStatement & Meaning \\\\\n\\hline\n$P \\land \\neg P \\vdash \\bot$ & Negation of $P$ is incompatible with $P$.\\\\\n  $\\neg \\neg \\neg P \\vdash \\neg P$ & Triple negation is the same as single negation.\\\\\n  $P \\vdash \\neg \\neg P$ & Double negation of $P$ is weaker than $P$.\\\\\n  $\\neg P \\lor \\neg Q \\vdash \\neg (P \\land Q)$ &  If not $P$ or not $Q$, then we can’t have both $P$ and $Q$\\\\\n  $\\neg (P \\lor Q) \\vdash \\neg P \\land \\neg Q$ &  If disjunction of $P$ and $Q$ is not true, then neither $P$ nor $Q$ is true.\\\\\n  $\\neg P \\land \\neg Q \\vdash \\neg (P \\lor Q)$ & If neither $P$ nor $Q$ is true, their disjunction is not true.\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\end{table}\n\nSome properties do not apply in this kind of logic:\n\\begin{table}[!htbp]\n\\begin{center}\n\\label{table_Sample_Wrong_Statements}\n\\begin{tabular}{c l l}\n& & \\\\ \n\\hline\nWrong Statement & What’s wrong with it? \\\\\n\\hline\n$\\neg \\neg P \\vdash P$   &                     Negation of negation of $P$ is not strong enough to give us $P$.\\\\\n\n  $\\neg (P \\land Q) \\vdash \\neg P\\lor \\neg Q$ &   Even if we can’t have both at the same time,\n  this does not mean that one of them is always wrong.\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\end{table}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Example 2. Three Logical Values (“Ternary Logic”)}\n\nStart with three logical values, $\\top$, $\\bot$, and $?$. Define operations for them:\n\n\\begin{center}\n\\begin{tabular}{ |c|c|c| }\n\\hline\n$\\textbf{x}$ & $\\textbf{\\neg x}$ & $\\textbf{\\neg \\neg x}$ \\\\\n\\hline\n$\\top$ & $\\bot$ & $\\top$ \\\\\n$?$    & $\\bot$ & $\\top$ \\\\\n$\\bot$ & $\\top$ & $\\bot$ \\\\\n  \\hline\n\\end{tabular}\n\\end{center}\n\n\\begin{center}\n\\begin{tabular}{ |c|c|c|c|c| }\n\\hline\n$\\textbf{x}$ & $\\textbf{y}$ & ${\\textbf{x} {\\land} \\textbf{y}}$  & $\\textbf{x} \\lor \\textbf{y}$ & $\\textbf{x} \\rightarrow \\textbf{y}$   \\\\\n\\hline\n$\\top$ & $\\top$ & $\\top$ & $\\top$ & $\\top$ \\\\\n$\\top$ &   $?$ &    $?$ &  $\\top$ & $?$ \\\\\n$\\top$ & $\\bot$ & $\\bot$ & $\\top$ & $\\bot$ \\\\\n $?$ &  $\\top$ &   $?$ &  $\\top$ & $\\top$ \\\\\n $?$ &    $?$ &    $?$ &    $?$ & $\\top$ \\\\\n $?$ &  $\\bot$ & $\\bot$ &   $?$ & $\\bot$ \\\\\n$\\bot$ & $\\top$ & $\\bot$ & $\\top$ & $\\top$ \\\\\n$\\bot$ &   $?$ &  $\\bot$ &   $?$ & $\\top$ \\\\\n$\\bot$ & $\\bot$ & $\\bot$ & $\\bot$ & $\\top$ \\\\\n  \\hline\n\\end{tabular}\n\\end{center}\n\nThis is the simplest intuitionistic logic, and it is a good tool for testing our statements.\n\nThe value ‘?,’ or ‘unknown,’ is somewhere between ‘truth’ $\\top$ and ‘false’ $\\bot$.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Example 3. Infinite Number of Logical Values}\n\nTake $[0,1]$, the set of all real numbers between $0$ and $1$, including\n$0$ and $1$. We can turn it into logic by defining:\n\n-   $\\bot = 0$\n\n-   $\\top =1$\n\n-   $a \\land b = glb(a,b)$\n\n-   $a \\lor b = lub(a,b)$\n\nIn this example, implication is defined, as always, via the equivalence:\n$(x~\\land~y)~\\leq~z~\\equiv~x~\\leq~(y~\\rightarrow~z)$. \n\n\nWe consider the following two cases separately:\n \n\nFirst, when $y\\leq z$, \n$(x~\\land~y)~\\leq~z$ is always true, for any $x$. Hence $y~\\rightarrow~z$\ncannot be smaller than any $x$, that is, it must be the top element, $1$.\n\n\nIn the opposite case, when $y$ is bigger than $z$ (we are talking about numbers),\n$( x \\land y \\leq z) \\equiv ( x \\leq z )$, so now we will have \n$x~\\leq~z~\\equiv~x~\\leq~(y~\\rightarrow~z)$, which means that $y~\\rightarrow~z~=~z$.\n\nRemember that we defined negation, $\\neg x$, as $x\\rightarrow 0$, and we have\n$\\neg x\\ \\equiv\\ if\\ (x = 0)\\ 1\\ else\\ 0$. You can also check whether double\nnegation maps $0$ to $0$ and any non-zero value to $1$.\n\nIn this example, we started with a set of values that was popular in \"fuzzy logic,\" and we were able to build\na pretty sound logic, except that it could not be made Boolean: double negation is not an identity.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Sets and Categories}\n \\\\\n \n\\subsection{Sets}\n \\\\\nScala programming language uses a pretty loose notion of sets; they have too many methods (like \\verb+head()+), and functions are not defined as \"special sets of pairs\", as they are defined in ZFC. So we had to introduce a special class for working with sets. Class $BigSet$ is the most general class defining sets; it does not even have to be enumerable.\n\n\\begin{lstlisting}[language=Scala]\nabstract class BigSet[T] extends Set[T] {\n override def size: Int = Sets.InfiniteSize\n...\n\\end{lstlisting}\n\nThis abstract \"container\" covers all possible sets.\nRemember, sets are not typed (in a set theory).\n\n\\begin{lstlisting}[language=Scala]\nobject Sets {                                     \n type set = Set[Any]\n\n implicit class untype[T](s: Set[T]) {\n   def untyped: set = s.asInstanceOf[set]\n }\n\n def isFinite(s: Set[_]) Boolean = s.size != InfiniteSize\n val Empty: set = Set.empty[Any]\n val Unit: set = Set(Empty)\n val FiniteSets = BigSet.comprehension(isFinite)\n ...\n\\end{lstlisting}\n\nWe can now define non-enumerable sets (thus banning all those Scala/Java methods that enumerate):\n\n\\begin{lstlisting}[language=Scala]\ntrait NonEnumerableSet[T] extends Set[T] {\n  private def notEnumerable = throw Stone(...)\n  override def isEmpty: Boolean = notEnumerable\n  def iterator: Iterator[T] = notEnumerable\n  override def toArray[S >: T : ClassTag] = notEnumerable\n}\n\\end{lstlisting}\n\nThese classes will be used to properly define Grothendieck toposes over sites.\n\n\n\\section{Categories}\n\nBefore defining \\verb+Category+, let's define \\verb+Graph+:\n\n\\begin{lstlisting}[language=Scala]\ntrait Graph { graph =>\n  type Node\n  type Arrow\n  def nodes: Set[Node]\n  def arrows: Set[Arrow]\n  def d0(f: Arrow): Node\n  def d1(f: Arrow): Node\n...\n\\end{lstlisting}\n\n\\verb+trait Graph+ implements a pretty big number of useful methods, but what's important is that it specifies \\verb+Node+s, \\verb+Arrow+s, and their relationships.\\\\\n\nHaving a type of \\verb+Graph+s, we can define a \\verb`Category` in Scala like this:\n\n\\begin{lstlisting}[language=Scala]\nabstract class Category(override val name: String) extends Graph {\n  type Obj = Node\n  def id(o: Obj): Arrow\n  def m(f: Arrow, g: Arrow): Option[Arrow]  // composition\n  \n  lazy val op: Category = {\n    val src = this\n    new Category(s\"~$name\") {\n      override def id(o: Obj): Arrow = src.id(o)\n      override def m(f: Arrow, g: Arrow) = src.m(f, g)\n    }\n  }\n\\end{lstlisting}\n\nNote that composition of arrows is a partial function lifted to \\verb+Option+.\\\\\n\nA category does not necessarily have to be finite: here is an example of an infinite one:\n\n\\begin{lstlisting}[language=Scala]\nobject N extends BigSet[BigInt] with EnumerableSet[BigInt] {\n  override def iterator: Iterator[BigInt] = new Iterator[BigInt] {...}\n  override def contains(n: BigInt): Boolean = n >= 0\n}\nobject PoSet {\n  lazy val ofNaturalNumbers: PoSet[BigInt] = new PoSet(N, comparator) {...}\n}\nlazy val NaturalNumbers: Category = fromPoset(\"N\", PoSet.ofNaturalNumbers)\n\\end{lstlisting}\n\nWe should never attempt to materialize such a category. \\\\\n\nThat was a countable category; we can even build an uncountable one:\n\n\\begin{lstlisting}[language=Scala]\nclass SetCategory(objects: BigSet[Set[Any]])\n  extends Category(name=\"Sets\", graphOfSets(objects)) {\n  type Node = set\n  type Arrow = SetFunction\n\n  override def d0(f: SetFunction): set = f.d0\n  override def d1(f: SetFunction): set = f.d1\n  override def m(f: Arrow, g: Arrow): Option[Arrow] = f compose g\n  override def id(s: set): SetFunction = SetFunction.id(s)\n  override def toString: String = \"Category of All Sets\"\n...\nobject Setf extends SetCategory(FiniteSets) {\n  override def toString: String = \"Category of Finite Sets\"\n}\n\\end{lstlisting}\n\nBut what is \\verb+SetFunction+?\n\n\\begin{lstlisting}[language=Scala]\ncase class SetFunction(\n  override val tag: String,\n  override val d0: set,\n  override val d1: set,\n  mapping: Any => Any) extends SetMorphism { self =>\n...\ndef compose(g: SetFunction): Option[SetFunction] =\n  if (d1 == g.d0) {\n    Some(new SetFunction(newTag, d0, g.d1, (x: Any) => g(self(x))))\n  } else None\n\\end{lstlisting}\n\n\\subsection{Samples of Categories}\nBelow are some example of categories, built using these tools:\n\n\\FloatBarrier\n\\begin{table}[!htbp]\n\\begin{center}\n\\label{table_Sample_Categories}\n\\begin{tabular}{|c|c|l|}\n\\hline\n$\\mathbb{ 0 }$ & & \n\\begin{lstlisting}[language=Scala]\nval _0_ : Cat = segment(0) \n\\end{lstlisting}\n\\\\\n\\hline\n$\\mathbb{ 1 } $ & • & \n\\begin{lstlisting}[language=Scala]\nval _1_ : Cat = segment(1) \n\\end{lstlisting}\n\\\\\n\\hline\n$\\mathbb{1}+\\mathbb{1}$ & • • & \n\\begin{lstlisting}[language=Scala]\nval _1plus1_ : Cat = discrete(Set(\"a\", \"b\")) \n\\end{lstlisting}\n\\\\\n\\hline\n$\\mathbb{2}$ & \n\\xymatrix{0 \\ar[r] & 1}\n& \n\\begin{lstlisting}[language=Scala]\nval _2_ : Cat = segment(2) \n\\end{lstlisting}\n\\\\\n\\hline\n$\\mathbb{3}$ & \n\\xymatrix{&1 \\ar[dr] \\\\\n0 \\ar[ur] \\ar[rr] && 2  }\n& \n\\begin{lstlisting}[language=Scala]\nval _3_ : Cat = segment(3) \n\\end{lstlisting}\n\\\\\n\\hline\n$\\mathbb{4}$ & \n\\xymatrix{\n&1 \\ar[drr] \\ar[r] & 2 \\ar[dr]\\\\\n0 \\ar[ur] \\ar[urr] \\ar[rrr] &&& 3\n}\n& \n\\begin{lstlisting}[language=Scala]\nval _4_ : Cat = segment(4) \n\\end{lstlisting}\n\\\\\n\\hline\n$ParallelPair$ & \n\\xymatrix{\n0 \\ar@<2pt>[r]^a \\ar@<-2pt>[r]_b & 1\n}\n& \n\\begin{lstlisting}[language=Scala]\ncategory\"ParallelPair:({0,1}, {a:0->1, b:0->1})\"\n\\end{lstlisting}\n\\\\\n\\hline\n$Pullback$ & \n\\xymatrix{\n& b \\ar[d]^{bd} \\\\\nc \\ar[r]_{cd} & d\n}\n& \n\\begin{lstlisting}[language=Scala]\ncategory\"Pullback:({b,c,d}, {bd:b->d, cd:c->d})\" \n\\end{lstlisting}\n\\\\\n\\hline\n$Square$ & \n\\xymatrix{\na \\ar[d]_{ac} \\ar[r]^{ab} \\ar[dr]|{ad} & b \\ar[d]^{bd} \\\\\nc \\ar[r]_{cd} & d\n}\n& \n\\begin{lstlisting}[language=Scala]\ncategory\"Square:({a,b,c,d},\n{ab:a->b, ac:a->c, bd:b->d, cd:c->d, ad:a->d},\n{bd o ab = ad,cd o ac = ad})\"\n\\end{lstlisting}\n\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\end{table}\n\n\\subsection{Functors and Natural Transformations}\n\nDefinitions are trivial:\n\n\\begin{lstlisting}[language=Scala]\nabstract class Functor(\n  val d0: Category, val d1: Category\n) extends Morphism {\n  def objectsMapping(x: d0.Obj): d1.Obj\n  def arrowsMapping(a: d0.Arrow): d1.Arrow\n  def compose(next: Functor): Option[Functor] = {\n    if (this.d1 != next.d0) None else Some { //...\n\\end{lstlisting}\n\n\n\\begin{lstlisting}[language=Scala]\nabstract class NaturalTransformation\n  extends Morphism[Functor, Functor] {\n\n\n  val domain: Category = d0.d0\n  val codomain: Category = d1.d1 // == d0.d1\n\n  def transformPerObject(x: domain.Obj): codomain.Arrow\n\\end{lstlisting}\n\nIn the picture, you see a natural transformation for category \"Pullback\":\n\n\\xymatrix{\n& F[b] \\ar[d] \\ar@{.>}[drr] \\\\\nF[c] \\ar[r] \\ar@{.>}[drr] & F[d] \\ar@{.>}[drr] && G[b]  \\ar[d]\\\\\n&&G[c] \\ar[r] &G[d]\n}\n\n\\section{Copresheaves (aka Diagrams)}\n\n\\subsection{Definition}\nA $Copresheaf$, also known as $Diagram$, of category \\catname{C} in category \\catname{D} is a functor from \\catname{C} to \\catname{D}.\n\nWe will, further on, be dealing with copresheaves in \\Set, and call them $diagrams$.\n\n\\begin{lstlisting}[language=Scala]\nabstract class Diagram(val domain: Category)\n  extends Functor(tag, topos.domain, Setf) { diagram =>\n\n  def isElementOf(other: Diagram): Boolean =\n    d0.objects.forall { o => other(o) contains (this(o)) }\n\n  def isContainedIn(other: Diagram): Boolean =\n    d0.objects.forall { o => this(o) subsetOf other(o) }\n\\end{lstlisting}\n\n\\subsection{Example 5, Diagrams over $\\mathbb{N}$}\nA functor $\\mathbb{N} \\rightarrow \\textbf{Sets}$ consists of sets $F[i]$ and functions $F[i]$→$F[i+1]$. (Other functions are compositions of these).\nThese diagrams model discreet “time flow” : discrete, \\cite{lamp}. \nThat’s the basic type of TLA+ book.\n\n\\xymatrix{\nF[0] \\ar[r] &F[1] \\ar[r] &F[2] \\ar[r] &{...}\n}\\\\\n\nBelow is a table of some shapes of time that we encounter in practice.\n\n\\FloatBarrier\n\n\\begin{table}[!htbp]\n\\begin{center}\n\\label{table_Sample_Diagram Categories}\n\\begin{tabular}{|c|l|}\n%\\hline\n%$\\textbf{Site}$ & $\\textbf{Concept}$ \\\\\n\\hline\n\\xymatrix{\nF[0] \\ar[r] &F[1] \\ar[r] &F[2] \\ar[r] &{...}\n} & TLA+ \\\\\n\\hline\n$\\bullet$ & Just sets\\\\\n\\hline\n\\xymatrix{0 \\ar[r] & 1}\n& Single transition (today and tomorrow)\n\\\\\n\\hline\n\\xymatrix{\n& b \\ar[d]^{bd} \\\\\nc \\ar[r]_{cd} & d\n}\n& Git Merge\n\\\\\n\\hline\n\\xymatrix{\na \\ar[d]_{ac} \\ar[r]^{ab} \\ar[dr]|{ad} & b \\ar[d]^{bd} \\\\\nc \\ar[r]_{cd} & d\n}\n& Eventual Consistency\n\\\\\n\\hline\n\\xymatrix{\n{Feb1} \\ar[r] & {Feb 2} \\ar@(ur,ul)[]_{6:00} \\ar[r] & {Feb 3}\n}\n& Groundhog day\n\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\end{table}\n\n\\FloatBarrier\n\n\\section{Logic in Grothedieck Topos}\n\nNow that we have a category of diagrams (it's a Grothendieck topos), we can dive deeper and build logic in it. We will be using points of objects to illustrate logic. Generally speaking, a Grothendieck topos is not well-pointed, though.\n\n\\subsection{Point of a Diagram}\nA point is any arrow \\xymatrix{1 \\ar[r] & D}, where $1$ is a terminal object of the category of diagrams.\n\n\\begin{lstlisting}[language=Scala]\nclass Point(val tag: Any, val mapping: Any => Any)\n\\end{lstlisting}\n\n\\subsection{Subobject Classifier}\nThis is a special object in a category of diagrams contains all the logic of a topos; we just have to discover it.\n\n\\xymatrix{&A \\ar@{>->}[d]_f \\ar[r] & 1 \\ar@{>->}[d]^{true} \\\\\n&B \\ar[r]_{\\chi_f} & \\Omega\n}\n\nHow can we build it? \n\n$\\Omega(x) \\equiv hom(hx, \\Omega)$ - by Yoneda lemma \n\n$hom(hx, \\Omega)  \\equiv {p \\subset hx}$ - by definition of $\\Omega$, see above.\n\n\\begin{lstlisting}[language=Scala]\ncase class Representable(x: domain.Obj)\n  extends Diagram(s\"hom($x, _)\", domain)\n//...\n\nobject Omega extends Diagram(\"Omega\", this, domain) {\n  val False: Point = points.head named \"false\"\n  val True: Point = points.last named \"true\"\n  val conjunction: DiagramArrow = ... // OmegaxOmega(x) => Omega(x)\n  val disjunction: DiagramArrow = ... // ΩxΩ(x) => Omega(x)\nal implication: DiagramArrow = ... // ΩxΩ(x) => Omega(x)\n  ...\n}\nval OmegaxOmega = product2(Omega, Omega)\n\nval DiagonalOfOmega: DiagramArrow =\n    buildArrow(\"Diagonal\", Omega, OmegaxOmega, _ => (s: Any) => (s, s)\n\n\\end{lstlisting}\n\n\\subsubsection{How to Build Conjunction in $\\Omega$}\n\n\\xymatrix{\n&1 \\ar@{>->}[d]_{(true,true)} \\ar[rr] && 1 \\ar@{>->}[d]^{true} \\\\\n& \\Omega\\times\\Omega \\ar[rr]_{\\land} && \\Omega\n}\n\n\\subsubsection{How to Build Implication in $\\Omega$}\n\nStart with building a subobject $\\Omega_1$ defining a partial order on $\\Omega$:\n\n\\xymatrix{\n\\Omega_1 \\ar@{>->}[r] & \\Omega\\times\\Omega \\ar@<1ex>[r]^{∧} \\ar@<-1ex>[r]_{p_1}\n& \\Omega\n}\n\nNow, implication is the arrow that classifies $\\Omega_1$:\n\n\\xymatrix{\n \\Omega_1 \\ar[d] \\ar[rr] && 1 \\ar[d]^{true}  \\\\\n \\Omega \\times \\Omega \\ar[rr]_{implication} && \\Omega\n}\n\n\\begin{lstlisting}[language=Scala]\nlazy val implication: DiagramArrow = {\n  val inclusion: DiagramArrow = inclusionOf(Omega_1) in OmegaxOmega iHope\n\n  classifies(inclusion, \"=>\")\n}\n\\end{lstlisting}\n\n\\subsection{Predicate Logic}\n\nFirst, what is a predicate in a topos? It's just any arrow\n$D\\ \\rightarrow\\ \\Omega$.\\\\\n\nLogical operations on $\\Omega$ provide operations on predicates:\n\n\\begin{lstlisting}[language=Scala]\ntrait Predicate extends DiagramArrow { p: DiagramArrow =>\n  val d0: Diagram\n  val d1: Diagram = Omega\n  def and(q: Predicate): Predicate = binaryOp(q, \"&\", Omega.conjunction)\n  def or(q: Predicate): Predicate = binaryOp(q, \"|\", Omega.disjunction)\n  def ==>(q: Predicate): Predicate = binaryOp(q, \"=>\", Omega.implication)\n  ...\n}\n\ndef not(p: Predicate): Predicate = p ==> FalsePredicate\n\\end{lstlisting}\n\n\nAs an example, here's a test case from a unittest for this code:\n\n\\begin{lstlisting}[language=Scala]\ndef check(c: Category): MatchResult[Any] = {\n val topos = new CategoryOfDiagrams(c)\n import topos._\n\n  for { p <- Omega.points map (_.asPredicate) } {\n    (True  ==> p)    === p\n    (False ==> p)    === True\n    (p     ==> p)    === True\n    (p     ==> True) === True\n    not(not(not(p))) === not(p)\n\n    for { q <- Omega.points map (_.asPredicate)\n          r <- Omega.points map (_.asPredicate) } {\n        (p and q ==> r) === (p ==> (q ==> r))\n      }\n    }\n}\n\\end{lstlisting}\n\n\n\n\n\\xymatrix{}\n\n\\begin{lstlisting}[language=Scala]\n\\end{lstlisting}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Conclusion}\nNeither Scala nor Java was designed to deal with problems like these: typeless sets, categories, infinite collections. \nAlso, the higher order type system in Scala 2 is not very convenient for\nthe problems like the ones I encountered implementing categories and toposes; dependent types would make more sense.\nThere's a hope that Scala 3 will help dealing with it properly.\nStrangely, implementing it in Haskell was even more challenging.\n\nIn addition to intuitionistic logic, Lawvere topologies can be implemented based on this package; and the implementation is now available in the same repository.\nUsing an older version of this software, we managed to enumerate all Lawvere topologies over finite sets.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% The bibliography is stored in an external database file\n% in the BibTeX format (file_name.bib).  The bibliography is\n% created by the following command and it will appear in this\n% position in the document. You may, of course, create your\n% own bibliography by using the bibliography environment as in\n%\n% \\begin{thebibliography}{12}\n% ...\n% \\bibitem{itemreference} D. E. Knudsen.\n% {\\em 1966 World Bnus Almanac.}\n% {Permafrost Press, Novosibirsk.}\n% ...\n% \\end{thebibliography}\n\n% Here's where you specify the bibliography style file.\n% The full file name for the bibliography style file \n% used for an ASME paper is asmems4.bst.\n\\bibliographystyle{asmems4}\n\n% Here's where you specify the bibliography database file.\n% The full file name of the bibliography database for this\n% article is asme2e.bib. The name for your database is up\n% to you.\n\\bibliography{london2021}\n\n\\cite{bartosz, pierce, tt, sheaves, brief, nlab1, repo, ctgd}\n\n\\end{document}\n", "meta": {"hexsha": "6c9f8d2f36eeb66d7088cc8531333d420780fd21", "size": 24731, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "talks/London2021/london2021.tex", "max_stars_repo_name": "vpatryshev/wowiki", "max_stars_repo_head_hexsha": "1af64e2fc2aca94c763fb2fe02ef21857d7c5ed3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2020-06-20T20:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T06:46:03.000Z", "max_issues_repo_path": "talks/London2021/london2021.tex", "max_issues_repo_name": "vpatryshev/wowiki", "max_issues_repo_head_hexsha": "1af64e2fc2aca94c763fb2fe02ef21857d7c5ed3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "talks/London2021/london2021.tex", "max_forks_repo_name": "vpatryshev/wowiki", "max_forks_repo_head_hexsha": "1af64e2fc2aca94c763fb2fe02ef21857d7c5ed3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-11T00:55:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-11T00:55:47.000Z", "avg_line_length": 33.0628342246, "max_line_length": 374, "alphanum_fraction": 0.6746188994, "num_tokens": 7355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3490149188820786}}
{"text": "\\documentclass[]{AVSSimReportMemo}\n\\usepackage{AVS}\n\\usepackage{colortbl}\n\n\\newcommand{\\ModuleName}{inertial3D}\n\\newcommand{\\subject}{Guidance Module to Perform an Inertially Fixed Pointing}\n\\newcommand{\\status}{Initial Version}\n\\newcommand{\\preparer}{M. Cols}\n\\newcommand{\\summary}{Generate the reference attitude trajectory for a general 3D inertial pointing.  A corrected body frame will align with the desired reference frame.     }\n\n\n\\begin{document}\n\n\n\\makeCover\n\n\n%\n%\tenter the revision documentation here\n%\tto add more lines, copy the table entry and the \\hline, and paste after the current entry.\n%\n\\pagestyle{empty}\n{\\renewcommand{\\arraystretch}{2}\n\\noindent\n\\begin{longtable}{|p{0.5in}|p{4.5in}|p{1.14in}|}\n\\hline\n{\\bfseries Rev}: & {\\bfseries Change Description} & {\\bfseries By} \\\\\n\\hline\nDraft & initial copy & M. Cols \\\\\n\\hline\n\n\\end{longtable}\n}\n\n\\newpage\n\\setcounter{page}{1}\n\\pagestyle{fancy}\n\n\\tableofcontents\n~\\\\ \\hrule ~\\\\\n\n\\section{Module Input and Output}\nTable \\ref{tab:inputTable} shows the input Configuration Data of the module Inertial 3D Point.\n\\begin{table}[h!]\n\t\\centering\n\t\\caption{Input Configuration Data}\n\t\\begin{tabular}{|l|l|l|p{3in}|}\n\t\t\\hline\n\t\t\\rowcolor{BrickRed}\n\t\t\\textcolor{white}{Name} & \\textcolor{white}{Type} & \n\t\t\\textcolor{white}{Length} & \n\t\t\\textcolor{white}{Description}  \\\\ \\hline\n\t\t$\\sigma_{R_0/N}$ & double [] & 3 & \n\t\tMRP attitude set of the desired reference frame with respect to the inertial frame . \\\\ \\hline\n\t\\end{tabular}\n\t\\label{tab:inputTable}\n\\end{table}\n\nTable \\ref{tab:outputTable} shows the Attitude Reference output message of the module Inertial 3D Point.\n\\begin{table}[h!]\n\t\\centering\n\t\\caption{Output Attitude Reference Message}\n\t\\begin{tabular}{|l|l|l|p{3in}|}\n\t\t\\hline\n\t\t\\rowcolor{BrickRed}\n\t\t\\textcolor{white}{Name} & \\textcolor{white}{Type} & \n\t\t\\textcolor{white}{Length} & \n\t\t\\textcolor{white}{Description}  \\\\ \\hline\n\t\t$\\sigma_{R/N}$ & double [] & 3 & \n\t\tMRP attitude set of the reference frame with respect to the inertial frame. \\\\ \\hline\n\t\t$\\leftexp{N} \\omega_{R/N}$ & double [] & 3 & \n\t\tAngular rate vector of the reference frame with respect to the inertial expressed in inertial frame components. \\\\ \\hline\n\t\t$\\leftexp{N} {\\dot{\\omega}_{R/N}}$ & double [] & 3 & \n\t\tAngular acceleration vector of the reference frame with respect to the inertial expressed in inertial frame components. \\\\ \\hline\n\t\\end{tabular}\n\t\\label{tab:outputTable}\n\\end{table}\n\\newpage\n\n\\section{Introduction}\nThis technical note discusses the guidance mathematics to compute a reference frame $\\mathcal{R}$ that is aligned the with an inertially fixed  frame  $\\mathcal{R}_0$, as shown in Figure~\\ref{fig:Fig1}.\n\\begin{figure}[htb]\n\t\\centerline{\n\t\\includegraphics{Figures/Fig3}\n\t}\n\t\\caption{Illustration of the input inertially fixed frame $\\mathcal{R}_{0}:\\{ \\hat e_{1}, \\hat e_{2}, \\hat e_{3} \\}$, the generated reference frame $\\mathcal{R}: \\{ \\hat r_{1}, \\hat r_{2}, \\hat r_{3}\\}$ and the inertial frame $\\mathcal{N}:\\{ \\hat{\\bm n}_{1}, \\hat{\\bm n}_{2}, \\hat{\\bm n}_{3} \\}$}\n\t\\label{fig:Fig1}\n\\end{figure}\n\n\\section{Reference Frame Generation}\nThe modules requires the desired reference orientation in terms of the MRP set $\\bm{\\sigma}_{R_{0}N}$. This input is only set once and does not have to be changed.\nLet us designate $\\mathcal{R}$ as the output generated reference frame. Since the fixed-pointing is inertial:\n\\begin{equation}\n\t\\bm{\\sigma}_{RN} = \\bm{\\sigma}_{R_{0}N}\n\\end{equation}\n\\begin{equation}\n\t\\bm{\\omega}_{RN} = \\dot{\\bm{\\omega}}_{RN} = 0\n\\end{equation}\n\n\\bibliographystyle{unsrt}\n\\bibliography{references}\n\n\\end{document}\n", "meta": {"hexsha": "13e893078602d216558669b9ff07b414be63c89c", "size": 3598, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/fswAlgorithms/attGuidance/inertial3D/_Documentation/AVS-Sim-Inertial3D-2016-01-15.tex", "max_stars_repo_name": "ian-cooke/basilisk_mag", "max_stars_repo_head_hexsha": "a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fswAlgorithms/attGuidance/inertial3D/_Documentation/AVS-Sim-Inertial3D-2016-01-15.tex", "max_issues_repo_name": "ian-cooke/basilisk_mag", "max_issues_repo_head_hexsha": "a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-03-13T20:52:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-13T20:52:22.000Z", "max_forks_repo_path": "src/fswAlgorithms/attGuidance/inertial3D/_Documentation/AVS-Sim-Inertial3D-2016-01-15.tex", "max_forks_repo_name": "ian-cooke/basilisk_mag", "max_forks_repo_head_hexsha": "a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5961538462, "max_line_length": 297, "alphanum_fraction": 0.7156753752, "num_tokens": 1154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.34897373067887094}}
{"text": "\\documentclass{article}\n\\usepackage{graphicx}\n\\usepackage{titletoc}\n\\usepackage{titlesec}\n\\usepackage{geometry} \n\\usepackage{fontspec, xunicode, xltxtra}\n\\usepackage{float}\n\\usepackage{cite}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{listings}\n\\usepackage{titletoc}\n\\usepackage{bm}\n\\usepackage{multirow}\n\n\\geometry{left=3cm,right=3cm,top=3cm,bottom=3cm}\n\\DeclareMathOperator*{\\argmin}{argmin}\n\\DeclareMathOperator*{\\argmax}{argmax}\n\\DeclareMathOperator*{\\var}{var}\n\\DeclareMathOperator*{\\expec}{E}\n\n\\begin{document}\n\\title{\\textsf{Course Project for Pattern Recognition}}\n\\author{Fan JIN\\quad (2015011506)}\n\\maketitle\n\n\\tableofcontents\n\\clearpage\n\n\\section{Introduction and Preprocessing}\n{\n    Here is a glance at the datasets. \n    Columns with only one unique value are removed, as they have no effect as observations.\n    The training set is roughly 9 times as much size as the testing set.\n\n    \\begin{table}[!hbp]\n        \\centering\n        \\begin{tabular}{|c|c|c|c|}\n        \\hline\n        File & sample size (nrow) & number of features (ncol) & number features in effect \\\\\n        \\hline\n        2ctrainX.txt & 2298 & 25133 & 17951 \\\\\n        \\hline\n        2ctestX.txt & 256 & 25133 & 17951 \\\\\n        \\hline\n        10ctrainX.txt & 16074 & 25133 & 24307 \\\\\n        \\hline\n        10ctestX.txt & 1787 & 25133 & 24307 \\\\\n        \\hline\n        \\end{tabular}\n        \\caption{Shape of datasets}\n    \\end{table}\n\n    \\begin{itemize}\n        \\item For two-category classification, the response ``2ctrainY.txt'' takes values 1 and 2.\n        \\item For ten-category one, the response ``10ctrainY.txt'' takes values ranging from 1 to 10.\n    \\end{itemize}\n}\n\n\\section{Two-category classification}\n{\n    \\subsection{Feature selection}\n    {\n        Feature selection is neccesary in this case, for we have much more features than data points, referred to as the ``large p, small n'' problem.\n\n        Methods of feature selection include:\n        \\begin{itemize}\n            \\item Non-wrapping: Fisher-based\n            \\item Non-wrapping: Correlation-based\n            \\item Non-wrapping: Entropy-based\n            \\item Non-wrapping: Statistical t-distribution\n            \\item Non-wrapping: Principal Component Analysis (PCA)\n            \\item Wrapping: Foreward-backward recursive\n            \\item Stochastic: Genetic algorithm\n        \\end{itemize}\n\n        Here we use non-wrapping methods for feature selection. We chose Fisher-based and PCA.\n\n        \\subsubsection{Fisher criterion}\n        {\n            The fisher criterion is defined as \n            $$F = \\frac{(\\mu_1 - \\mu_2)^2}{s_1^2 + s_2^2},$$\n            where $\\mu_1$, $\\mu_2$ are the means of two categories, and $s_1^2$, $s_2^2$ are the varainces, in terms of some feature.\n\n            The larger the Fisher criterion, the more significant the feature is. We select 2000 features with the largest Fisher criteria. \n        }\n\n        \\subsubsection{the PCA}\n        {\n            The Principal Component Analysis performs eigendecomposition to the correlation matrix of the data points, and retains the components with principal eigenvalues.\n\n            We retain 99\\% of total variance in raw data, which gives $2202$ features in total. \n        }\n    }\n\n    \\subsection{Classifier}\n    {\n        \\subsubsection{Linear SVM}\n        {\n            The support vector machine, or SVM, is a powerful method for both classification and regression, particularly in case of ``large p, small n''.\n\n            It is crucial to choose a kernel that balances between prediction accuracy and overfitting aversion. \n            We tried linear, quadratic, and RBF kernels. The linear kernel turns out the best.\n        }\n\n        \\subsubsection{Fully connected NN}\n        {\n            The neural network has advantages over the linear SVM in case of nonlinearity. \n\n            Since we have only limited data points, we cannot train a deep network. \n            We took a simple perceptron network, which has one hidden layer with 1500 nodes. \n            We tuned the hidden layer size, and $1000$ proves the best hyperparameter.\n        }\n    }\n\n    \\subsection{Experiments}\n    {\n        \\begin{table}[!hbp]\n            \\centering\n            \\begin{tabular}{|c|c|c|c|c|c|c|c|}\n            \\hline\n            Dim. Reduction & Classifier & \\multicolumn{5}{|c|}{5-fold cross validation} & Avg. Accuracy \\\\\n            \\hline\n            Fisher & Linear SVM & 0.9848 & 0.9934 & 0.9869 & 0.9869 & 0.9956 & 0.9896 \\\\\n            \\hline\n            PCA & Linear SVM & 0.9544 & 0.9434 & 0.9629 & 0.9586 & 0.9498 & 0.9539 \\\\\n            \\hline\n            Fisher & FC NN & 0.9891 & 0.9978 & 0.9891 & 1.0000 & 0.9956 & 0.9943 \\\\\n            \\hline\n            PCA & FC NN & 0.8828 & 0.8652 & 0.8823 & 0.9019 & 0.8758 & 0.8816 \\\\\n            \\hline\n            \\end{tabular}\n            \\caption{Comparison}\n        \\end{table}\n\n        The Fisher criterion has better performance in dimensionality reduction, compared with the PCA. \n\n        It is worth noting that the neural network does not always perform better than the SVM. \n        It does when we use Fisher criterion for dimensionality reduction, while it does not when the PCA is used. \n        This could be explained by the weak performance of the PCA, as it performs a linear transformation on the raw data.\n        The data might not be normally distributed, and thus the correlation matrix fails to identify all the principal components.\n\n        We tuned the hyperparamters, and found the best network size is around 1000. This attains high accuracy while avoiding overfitting.\n\n        \\begin{table}[!hbp]\n            \\centering\n            \\begin{tabular}{|c|c|c|c|c|c|c|}\n            \\hline\n            Size of hidden layer & \\multicolumn{5}{|c|}{5-fold cross validation} & Avg. Accuracy \\\\\n            \\hline\n            200 & 0.9934 & 0.9978 & 0.9934 & 0.9847 & 0.9934 & 0.9925 \\\\\n            \\hline\n            500 & 0.9891 & 0.9978 & 0.9891 & 1.0000 & 0.9934 & 0.9939 \\\\\n            \\hline\n            1000 & 0.9891 & 0.9978 & 0.9891 & 1.0000 & 0.9956 & 0.9943 \\\\\n            \\hline\n            1500 & 0.9891 & 0.9978 & 0.9891 & 1.0000 & 0.9956 & 0.9943 \\\\\n            \\hline\n            \\end{tabular}\n            \\caption{Finding the proper network size}\n        \\end{table}\n    }\n\n    \\subsection{Prediction}\n    {\n        Since it has the highest accuracy in 5-fold cross validation, the fully connected NN with Fisher-based dimensionality reduction is chosen for prediction. \n        The prediction is stored in ``2ctestY.txt'' in the root directory.\n    }\n}\n\n\\section{Ten-category classification}\n{\n    \\subsection{Feature selection}\n    {\n        The dataset is too large for SVD (singular value decomposition), so it would be diffucult to perform full PCA on it.\n        We tried using ``arpack'' instead, but the script ran out of memory on a GPU server. \n\n        Considering this, only Fisher criterion was used in this task.\n        We chose 2000 features out of 24307, and trained the reduced dataset using SVM and FCNN.\n    }\n\n    \\subsection{Experiments}\n    {\n        \\begin{table}[!hbp]\n            \\centering\n            \\begin{tabular}{|c|c|c|c|c|c|c|c|}\n            \\hline\n            Dim. Reduction & Classifier & \\multicolumn{5}{|c|}{5-fold cross validation} & Avg. Accuracy \\\\\n            \\hline\n            Fisher & Linear SVM & 0.9916 & 0.9878 & 0.9850 & 0.9903 & 0.9875 & 0.9884 \\\\\n            \\hline\n            Fisher & FC NN & 0.9891 & 0.9950 & 0.9937 & 0.9925 & 0.9934 & 0.9927 \\\\\n            \\hline\n            \\end{tabular}\n            \\caption{Comparison}\n        \\end{table}\n\n        The fully connected NN attains higher accuracy as the linear SVM does. \n\n        \\begin{table}[!hbp]\n            \\centering\n            \\begin{tabular}{|c|c|c|c|c|c|c|}\n            \\hline\n            Size of hidden layer & \\multicolumn{5}{|c|}{5-fold cross validation} & Avg. Accuracy \\\\\n            \\hline\n            200 & 0.9934 & 0.9925 & 0.9875 & 0.9940 & 0.9931 & 0.9921 \\\\\n            \\hline\n            500 & 0.9546 & 0.9928 & 0.9931 & 0.9934 & 0.9866 & 0.9841 \\\\\n            \\hline\n            1000 & 0.9953 & 0.9944 & 0.9944 & 0.9937 & 0.9937 & 0.9943 \\\\\n            \\hline\n            1500 & 0.9959 & 0.9940 & 0.9944 & 0.9947 & 0.9940 & 0.9946 \\\\\n            \\hline\n            \\end{tabular}\n            \\caption{Finding the proper network size}\n        \\end{table}\n\n        The optimal hyperparameter for the hidden layer size is around 1000. \n\n        Compared with two-category classification, the ten-category one attains slightly lower accuracy in training and cross validation.\n\n    }\n\n    \\subsection{Prediction}\n    {\n        Since it has the highest accuracy in 5-fold cross validation, the fully connected NN with Fisher-based dimensionality reduction is chosen for prediction. \n        The prediction is stored in ``10ctestY.txt'' in the root directory.\n    }\n}\n\n\\section{Visualization and Clustering}\n{\n    \\subsection{PCA}\n    {\n        \\begin{figure}[H]\n            \\centering\n            \\includegraphics[width = 1\\linewidth]{./src3/pca.png}\n            \\caption{Dimensionality reduction using PCA}\n        \\end{figure}\n    }\n\n    \\subsection{t-SNE}\n    {\n        \\begin{figure}[H]\n            \\centering\n            \\includegraphics[width = 1\\linewidth]{./src3/tsne.png}\n            \\caption{Dimensionality reduction using t-SNE}\n        \\end{figure}\n    }\n\n    \\subsection{Clustering based on t-SNE}\n    {\n        It is astouding to find the result of PCA, although with good linearity, does not split up all the 10 categories in the 2d space.\n        Only one category is distributed away from others. In comparison, the t-SNE works fine. We will use t-SNE for clustering.\n\n        Since the number of categories is known, k-means seems a good choice. We fix $k=10$. \n        The birch clustering algorithm is also tested. The Birch algorithm turns out better than K-means.\n\n        \\begin{table}[!hbp]\n            \\centering\n            \\begin{tabular}{|c|c|}\n            \\hline\n            Method & Accuracy \\\\\n            \\hline\n            K-means & 0.6926 \\\\\n            \\hline\n            Birch & 0.7343 \\\\\n            \\hline\n            \\end{tabular}\n            \\caption{Comparison}\n        \\end{table}\n\n        \\begin{figure}[H]\n            \\centering\n            \\includegraphics[width = 0.9\\linewidth]{./src3/kmeans.png}\n            \\includegraphics[width = 0.9\\linewidth]{./src3/birch.png}\n            \\caption{K-means (top); Birch (bottom)}\n        \\end{figure}\n    }\n}\n\n\\section{Source Code}\n{\n    \\subsection{Root directory}\n    {\n        \\begin{itemize}\n            \\item ``2ctestY.txt'': Two-category prediction. Use this file for evaluation.\n            \\item ``10ctestY.txt'': Ten-category prediction. Use this file for evaluation.\n            \\item ``report.pdf'': Project report.\n        \\end{itemize}\n    }\n\n    \\subsection{``data1'' directory}\n    {\n        \\begin{itemize}\n            \\item ``2ctrainX.txt'': Raw dataset.\n            \\item ``2ctrainY.txt'': Raw dataset.\n            \\item ``2ctestY.txt'': Raw dataset.\n            \\item ``data1.npz'': Preprocessed file. (invalid columns removed)\n        \\end{itemize}\n    }\n\n    \\subsection{``data2'' directory}\n    {\n        \\begin{itemize}\n            \\item ``10ctrainX.txt'': Raw dataset.\n            \\item ``10ctrainY.txt'': Raw dataset.\n            \\item ``10ctestY.txt'': Raw dataset.\n            \\item ``data2.npz'': Preprocessed file. (invalid columns removed)\n        \\end{itemize}\n    }\n\n    \\subsection{``src1'' directory}\n    {\n        \\begin{itemize}\n            \\item ``preproc.py'': Preprocessing, removing identical columns.\n            \\item ``feature\\_selection'': Feature selection, generating ``fisher\\_2000.npz'' and ``pca\\_99.npz''.\n            \\item ``SVM.py'': Training a SVM and use it for prediction.\n            \\item ``FCNN'': Training a fully connected NN and use it for prediction.\n        \\end{itemize}\n    }\n\n    \\subsection{``src2'' directory}\n    {\n        \\begin{itemize}\n            \\item ``preproc.py'': Preprocessing, removing identical columns.\n            \\item ``feature\\_selection'': Feature selection, generating ``fisher\\_2000.npz''.\n            \\item ``SVM.py'': Training a SVM and use it for prediction.\n            \\item ``FCNN'': Training a fully connected NN and use it for prediction.\n        \\end{itemize}\n    }\n\n    \\subsection{``src3'' directory}\n    {\n        \\begin{itemize}\n            \\item ``pca.py'': Dimensionality reduction by PCA, generating ``pca.npz''.\n            \\item ``tsne.py'': Dimensionality reduction by t-SNE, generating ``tsne.npz''.\n            \\item ``visualization'': Visualization after loading ``pca.pna'' and ``tsne.npz''. \n            \\item ``kmeans.py'': Clustering by K-means.\n            \\item ``birch.py'': Clustering by Birch.\n        \\end{itemize}\n    }\n}\n\n\\clearpage\n\\end{document}\n    ", "meta": {"hexsha": "e8c69c5c8067481ba2b5ace2b0f27005885f991e", "size": 12942, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Project/report.tex", "max_stars_repo_name": "kingium/PatternRecognitionForUndergrads", "max_stars_repo_head_hexsha": "5cd08f3a260fae4a7edaf71599433e93484863b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Project/report.tex", "max_issues_repo_name": "kingium/PatternRecognitionForUndergrads", "max_issues_repo_head_hexsha": "5cd08f3a260fae4a7edaf71599433e93484863b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Project/report.tex", "max_forks_repo_name": "kingium/PatternRecognitionForUndergrads", "max_forks_repo_head_hexsha": "5cd08f3a260fae4a7edaf71599433e93484863b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2968299712, "max_line_length": 173, "alphanum_fraction": 0.6004481533, "num_tokens": 3580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.3489737222844969}}
{"text": "\\documentclass{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage{pgfplotstable}\n\\pgfplotsset{compat=1.15}\n\\usepackage{fancyvrb}\n\n\\title{}\n\\author{}\n\\date{}\n\n\\begin{document}\n\n\\maketitle\n\n\\section{Introduction}\n\nUsing our DenseNet-BC we have approximately $634k$ 32FP-ops and $626k$ FP32-params. This gives us a score of approximately (rounding up) $0.078$ in total, where for the ops, we obtain $0.06$ as our score, and for the parameters, we obtain $0.018$ as our score.\n\nTo test a pre-trained network and check the score, just run profile.py. To train a network, just run train.py and then re-run profile.py.  \n\nWe describe our methods and computations in the following:\n\n\\section{Data Augmentation}\n\\label{data_aug}\n\nWe first use standard Data augmentation such as flip and random crop. In addition, we propose to add other different data augmentations. We use CutMix with $\\alpha = 1$ for all training dataset, and we drop $64$ pixels randomly for each input training image. \n\n\\section{Architecture}\n\nWe use a DenseNet-BC architecture with $K = 8$, depth $D = 196$ and reduction $R = 0.5$. \n\n\\section{Computing the Number of Parameters}\n\nTo get the number of parameters of the DenseNet-BC architecture, we compute the number of parameters of each layer (or each Bottleneck layer that contains 2 Batch norm layers, 2 Convolutional layers and 2 Relu), as described in Table~\\ref{table:params}\n\n\\begin{table}[h]\n    \\centering\n    \\begin{tabular}{c|c}\n    Layer     & Number of parameters  \\\\\n    \\hline\n    Convolution     &      $F_{in}F_{out}S_c^2$ \\\\\n    \\hline\n    Batch norm & $4F_{in}$ \\\\\n    \\hline\n    $Bottleneck_i$ & $ 4[F_{in} + K(4 + F_{in} + i + K(1 + i)]$\\\\\n    \\hline\n    Linear & $F_{in}F_{out}$\\\\\n    \\hline\n    Transition & $F_{in}(4 + RF_{in})$ \\\\\n    \\hline\n    \\end{tabular}\n    \\caption{The number of parameters for each layer. Note that $F_{in}$ represents the number of input feature maps, $F_{out}$ represents the number of output feature maps, $S_c^2$ represents the kernel size of a convolutional operation, $i$ represents the depth of the bottleneck inside a block that contains $\\frac{D-4}{6}$ bottleneck layers.}\n    \\label{table:params}\n\\end{table}\n\n\\section{Computing the Number of Operations}\n\nto get the number of operations required to process one input through the  DenseNet-BC network, we compute the number of operations of each layer (or each Bottleneck layer that contains 2 Batch norm layers, 2 Convolutional layers and 2 Relu), as described in Table~\\ref{table:Flops}\n\n\n\\begin{table}[h]\n    \\centering\n    \\begin{tabular}{c|c}\n    Layer     & Number of operations  \\\\\n    \\hline\n    Convolution     &  $[\\frac{F_{in}F_{out}S_c^2}{2} + (F_{in}S_c^2 -1)F_{out}]P $ \\\\\n    \\hline\n    Batch norm & $3F_{in}P$ \\\\\n    \\hline\n    Relu & $F_{in}P$\\\\\n    \\hline\n    Average pooling & $S_p^2PF_{in} $ \\\\\n    \\hline\n    Linear & $1.5F_{in}F_{out}$ \\\\\n    \\hline\n    Transition & $4F_{in}P + [\\frac{F_{in}F_{out}S_c^2}{2} + (F_{in}S_c^2 -1)F_{out}]P + S_p^2PF_{out}$ \\\\\n    \\hline\n    $Bottleneck_i$ & Batch norm1 + Relu1 + Batch norm2 + Relu2 + Conv1 + Conv2\\\\\n    & Batch norm1 = $3P(F_{in} + iK)$\\\\\n    & Relu1 = $P(F_{in} + iK)$\\\\\n    & Batch norm2 = $12P_{in}K$\\\\\n    & Relu2 = $4P_{in}K$\\\\\n    & Conv1 = $P[\\frac{(F_{in} + iK)4K}{2} + (F_{in} + ik -1)4K]$\\\\\n    & Conv2 = $[\\frac{36K^2}{2} + (36K-1)K]P$\\\\\n    \\hline\n    \n    \\hline\n    \n    \\hline\n    \\end{tabular}\n    \\caption{The number of operations for each layer. Note that $F_{in}$ represents the number of input feature maps, $F_{out}$ represents the number of output feature maps, $S_c^2$ represents the kernel size of a convolutional operation, $S_p^2$ represents the kernel size of an average pooling operation, $i$ represents the depth of the bottleneck inside a block that contains $\\frac{D-4}{6}$ bottleneck layers, $P$ represents the number of pixels of an input feature map.}\n    \\label{table:Flops}\n\\end{table}\n\n\\section{Training procedure}\n\nWe train the network with the data augmentation described on Section~\\ref{data_aug} for 200 epochs, using a batch size of 32 and a softmax temperature of 6. Our learning rate starts at 0.1 and is divided by 10 at epochs 100 and 150. We then fine-tune the network by training it for an extra 5 epochs without data-augmentation. \n\n\\newpage\n\n\\input{architecture.tex}\n\n\n\\end{document} \n", "meta": {"hexsha": "7267d44ccf07c9fe1b7c217a9283d7f7fabd1215", "size": 4329, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Report/main.tex", "max_stars_repo_name": "cadurosar/Micronet", "max_stars_repo_head_hexsha": "b57df0aa765f5b503cd02f6bd367f61cbf7d1dbe", "max_stars_repo_licenses": ["ECL-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-08-08T18:42:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-04T02:38:49.000Z", "max_issues_repo_path": "Report/main.tex", "max_issues_repo_name": "cadurosar/Micronet", "max_issues_repo_head_hexsha": "b57df0aa765f5b503cd02f6bd367f61cbf7d1dbe", "max_issues_repo_licenses": ["ECL-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Report/main.tex", "max_forks_repo_name": "cadurosar/Micronet", "max_forks_repo_head_hexsha": "b57df0aa765f5b503cd02f6bd367f61cbf7d1dbe", "max_forks_repo_licenses": ["ECL-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-06-06T17:06:31.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-06T17:06:31.000Z", "avg_line_length": 41.2285714286, "max_line_length": 475, "alphanum_fraction": 0.6853776854, "num_tokens": 1358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.34897371365441227}}
{"text": "\\newcommand{\\createRUpd}[4]{\\fun{createRUpd}~\\var{#1}~\\var{#2}~\\var{#3}~\\var{#4}}\n\\newcommand{\\mkApparentPerformance}[3]{\\fun{mkApparentPerformance}~{#1}~\\var{#2}~\\var{#3}}\n\\newcommand{\\Q}{\\ensuremath{\\mathbb{Q}}}\n\\newcommand{\\ActiveSlotCoeff}{\\mathsf{ActiveSlotCoeff}}\n\\newcommand{\\EpochState}{\\type{EpochState}}\n\\newcommand{\\BlocksMade}{\\type{BlocksMade}}\n\\newcommand{\\RewardUpdate}{\\type{RewardUpdate}}\n\\newcommand{\\PrtclState}{\\type{PrtclState}}\n\\newcommand{\\PrtclEnv}{\\type{PrtclEnv}}\n\\newcommand{\\PoolDistr}{\\type{PoolDistr}}\n\\newcommand{\\bheader}[1]{\\fun{bheader}~\\var{#1}}\n\n\\section{Removal of the Overlay Schedule}\n\nThe overlay schedule was only used during the early days of the Shelley ledger, and can be safely removed. First, the protocol parameter $\\var{d}$ is removed, and any functions that use it are reduced to the case $\\var{d} = 0$. The function $\\fun{mkApparentPerformance}$ is reduced to one of its branches, and its first argument is dropped. It is only used in the definition of $\\fun{rewardOnePool}$, which needs to be adjusted accordingly.\n\n\\begin{figure}[htb]\n    \\begin{align*}\n      & \\fun{mkApparentPerformance} \\in \\unitInterval \\to \\N \\to \\N \\to \\Q \\\\\n      & \\mkApparentPerformance{\\sigma}{n}{\\overline{N}} = \\frac{\\beta}{\\sigma} \\\\\n      & ~~~\\where \\\\\n      & ~~~~~~~\\beta = \\frac{n}{\\max(1, \\overline{N})} \\\\\n  \\end{align*}\n  \\caption{Function used in the Reward Calculation}\n  \\label{fig:functions:rewards}\n\\end{figure}\n\nThe function $\\fun{createRUpd}$ is adjusted by simplifying $\\eta$.\n\n\\begin{figure}[htb]\n  \\emph{Calculation to create a reward update}\n  %\n  \\begin{align*}\n    & \\fun{createRUpd} \\in \\N \\to \\BlocksMade \\to \\EpochState \\to \\Coin \\to \\RewardUpdate \\\\\n    & \\createRUpd{slotsPerEpoch}{b}{es}{total} = \\left(\n      \\Delta t_1,-~\\Delta r_1+\\Delta r_2,~\\var{rs},~-\\var{feeSS}\\right) \\\\\n    & ~~~\\where \\\\\n    & ~~~~~~~\\dotsb \\\\\n    & ~~~~~~~\\eta =\n        \\frac{blocksMade}{\\floor{{slotsPerEpoch} \\cdot \\ActiveSlotCoeff}} \\\\\n    & ~~~~~~~\\dotsb\n  \\end{align*}\n\n  \\caption{Reward Update Creation}\n  \\label{fig:functions:reward-update-creation}\n\\end{figure}\n\n$\\fun{incrBlocks}$ gets the same treatment as $\\fun{mkApparentPerformance}$. Its invocation in $\\mathsf{BBODY}$ needs to be adjusted as well.\n\n\\begin{figure}\n  \\begin{align*}\n      & \\fun{incrBlocks} \\in \\KeyHash_{pool} \\to\n          \\BlocksMade \\to \\BlocksMade \\\\\n      & \\fun{incrBlocks}~\\var{hk}~\\var{b} =\n        \\begin{cases}\n          b\\cup\\{\\var{hk}\\mapsto 1\\} & \\text{if }\\var{hk}\\notin\\dom{b} \\\\\n          b\\unionoverrideRight\\{\\var{hk}\\mapsto n+1\\} & \\text{if }\\var{hk}\\mapsto n\\in b \\\\\n        \\end{cases}\n  \\end{align*}\n\\end{figure}\n\n\\newpage\nFinally, the $\\mathsf{PRTCL}$ STS needs to be adjusted. To retire the $\\mathsf{OVERLAY}$ STS, we inline the definition of its 'decentralized' case and drop all the unnecessary variables from its environment. It is invoked in $\\mathsf{CHAIN}$, which needs to be adjusted accordingly.\n\n\\begin{figure}\n  \\emph{Protocol environments}\n  \\begin{equation*}\n    \\PrtclEnv =\n    \\left(\n      \\begin{array}{r@{~\\in~}lr}\n        \\var{pd} & \\PoolDistr & \\text{pool stake distribution} \\\\\n        \\eta_0 & \\Seed & \\text{epoch nonce} \\\\\n      \\end{array}\n    \\right)\n  \\end{equation*}\n  \\caption{Protocol transition-system types}\n  \\label{fig:ts-types:prtcl}\n\\end{figure}\n\n\\begin{figure}[ht]\n  \\begin{equation}\\label{eq:prtcl}\n    \\inference[PRTCL]\n    {\n      \\var{bhb}\\leteq\\bheader{bh} &\n      \\eta\\leteq\\fun{bnonce}~(\\bhbody{bhb})\n      \\\\~\\\\\n      {\n        \\eta\n        \\vdash\n        {\\left(\\begin{array}{c}\n        \\eta_v \\\\\n        \\eta_c \\\\\n        \\end{array}\\right)}\n        \\trans{\\hyperref[fig:rules:update-nonce]{updn}}{\\var{slot}}\n        {\\left(\\begin{array}{c}\n        \\eta_v' \\\\\n        \\eta_c' \\\\\n        \\end{array}\\right)}\n    }\\\\~\\\\\n      {\n        \\vdash\\var{cs}\\trans{\\hyperref[fig:rules:ocert]{ocert}}{\\var{bh}}\\var{cs'}\n      }\n      \\\\~\\\\\n      \\fun{praosVrfChecks}~\\eta_0~\\var{pd}~\\ActiveSlotCoeff~\\var{bhb}\n    }\n    {\n      {\\begin{array}{c}\n         \\var{pd} \\\\\n         \\eta_0 \\\\\n       \\end{array}}\n      \\vdash\n      {\\left(\\begin{array}{c}\n            \\var{cs} \\\\\n            \\eta_v \\\\\n            \\eta_c \\\\\n      \\end{array}\\right)}\n      \\trans{prtcl}{\\var{bh}}\n      {\\left(\\begin{array}{c}\n            \\varUpdate{cs'} \\\\\n            \\varUpdate{\\eta_v'} \\\\\n            \\varUpdate{\\eta_c'} \\\\\n      \\end{array}\\right)}\n    }\n  \\end{equation}\n  \\caption{Protocol rules}\n  \\label{fig:rules:prtcl}\n\\end{figure}", "meta": {"hexsha": "d4925d8ce5c7be4919e78901833a94aefa878518", "size": 4495, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "eras/babbage/formal-spec/remove-overlay.tex", "max_stars_repo_name": "MELD-labs/cardano-ledger", "max_stars_repo_head_hexsha": "9c3b4737b13b30f71529e76c5330f403165e28a6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "eras/babbage/formal-spec/remove-overlay.tex", "max_issues_repo_name": "MELD-labs/cardano-ledger", "max_issues_repo_head_hexsha": "9c3b4737b13b30f71529e76c5330f403165e28a6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eras/babbage/formal-spec/remove-overlay.tex", "max_forks_repo_name": "MELD-labs/cardano-ledger", "max_forks_repo_head_hexsha": "9c3b4737b13b30f71529e76c5330f403165e28a6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-14T16:56:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T16:56:46.000Z", "avg_line_length": 35.3937007874, "max_line_length": 440, "alphanum_fraction": 0.6100111235, "num_tokens": 1502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.3489708056480584}}
{"text": "\\chapter{Overhung}\n\t\\section{Introduction}\n\t\tOverhung rotors are widely used in industrial turbo-machines. For certain gas turbines, gyroscopic effects of the disks may almost double the critical speeds of the rotor systems, compared to normal mechanical vibration systems. In addition, the asymmetry of the bearing stiffness will bring more complication to a rotor system. Even though there are many established publications about how to theoretically model an overhung rotor with anisotropic bearings (\\cite{Genta}-\\cite{Ishida},\\cite{Dimarogonas}), very few papers compared the theoretical models with experimental results. Ishida al etc.\\cite{Ishida} derived a sophisticated mathematical model to theoretically investigate the nonstationary vibration of a flexible rotor with nonlinear spring parameters during acceleration. They employed an asymptotic method to compute the first approximate solution to vibration response. Then, they calculated the amplitude variation curves of each oscillation component using complex-FFT. Furthermore, they inspected how each nonlinear component in polar format affected dynamic vibration. They proposed a unique signal processing method called complex-FFT where the rotor whirling plane is coincident with the complex plane. The whirling direction of the rotor can be judged by filtering the vibration signals at different frequencies using complex-FFT method. However, the complex-FFT doesn’t provide instrumentation phase angle information and full spectrum cascaded plots.\n\t\t\\par\n\t\tGunter etc. (\\cite{Gunter}, \\cite{Gunter 93}) performed investigations about the forward and backward modes of overhung rotors through theoretical models and Finite Element Analysis. Like the majority of the publications, they use FFT to analyze their simulation results. In 1993, Southwick, Goldman, and Muszynska (\\cite{Goldman}-\\cite{Southwick 94}) introduced the new powerful “full spectrum” plot in rotating machinery vibration and rotor dynamics. Since then, Bently Nevada Corporation has installed full spectrum cascade plots in all of their major machinery data acquisition software package entitled as ADRE system. Compared to “traditional (half) spectrum” FFT plot, full spectrum can extract more significant diagnostic information from the original signals generated by X, Y transducers, this allows engineers to determine whether the vibration response is forward or backward with respect to rotational direction of the shaft. As a powerful tool for interpreting the vibration signals of rotating machinery, the full spectrum plots display the correlation between the vibration signals from the X and Y transducers. Based on reference (\\cite{Bently}-\\cite{Southwick 94}), Bently Nevada of GE Energy builds a multi-channel signal processing and data acquisition system, the ADRE Sxp Software and the 408 DSPi (Dynamic Signal Processing Instrument) respectively. Unlike any other data acquisition systems, ADRE 408 SDPi is an extremely versatile system designed for real-time highly parallel signal processing and presentation. Cascade full spectrum plots are embedded into all ADRE software which are installed on the majority of turbo-machines in industry.\n\t\t\\par\n\t\tMuszynska (1996) \\cite{Muszynska 96} methodically investigated the dynamic behaviors of a vertically configured overhung imbalanced rotor supported by flexible anisotropic bearings by theory and experiments. She concluded that the interaction of imbalance and shaft bow causes the synchronous forced precession of the rotor to be forward or backward. Furthermore, she investigated the situation in which the mid-span rotor sections precess one way, while the outboard disk precesses the other. The phenomenon is partly attributed to the relationship between the unbalances in terms of their relative direction. Ishida et al. (2008) \\cite{Ishida 2008} theoretically investigated internal resonances near both the primary and the gravity critical speeds for a rotor system of an asymmetric shaft supported at both ends and a disk installed in the middle; nonlinearities of the system induced by bearing clearances were thoroughly explored. Nagasaka et al. (2008) \\cite{Nagasaka} did further research by studying internal resonance between the forward and backward whirl modes near both the primary and the secondary critical speeds for a simply-supported rotor system with  asymmetric shaft. Based on above research, Nandakumar et al. (2010) \\cite{Nandakumar} extended their research to an overhung rotor with substantial gyroscopic effects and relatively large lateral vibration using the method of multiple scales (MMS). The authors derived the theoretical nonlinear equations of motion for an asymmetrical overhung rotor running near its gravity critical speed. The authors examined how gyroscopic effects contribute on maximum resonant amplitudes, which disclose some interesting phenomena induced solely by nonlinearities of the system.\n\t\t\\par \n\t\tYim et al. (2012) \\cite{Yim} studied the dynamic response of a flexible shaft with a disk subjected to axial forces for two overhung rotor systems using transfer matrix method. They concluded that, under the force load, the gyroscopic effect not only increases the critical axial force, but also changes the instability type from divergence to flutter. Ma et al. (2015) \\cite{Ma}experimentally investigated the vibration response of an overhung rotor under sudden unbalance excitation due to the blade loss and quantitatively assessed the impact effect. The effect of the sudden unbalance is tested in both the subcritical state and the supercritical state. The results demonstrate that the response of the system to sudden imbalance contains frequencies from the impact response as well as frequencies due to rotational speed. A flexible rotor was shown to excite more from sudden imbalance than a more rigid rotor. Ma et al. (2015) \\cite{Ma, H} presents a finite element model of the oil film instability of an overhung rotor with both parallel and angular misalignments including the gyroscopic effect. Oil film bearings are simulated using a non-linear oil-film force model, assuming short-length bearings. The validity of the model is verified by comparison to experimental results in published literature. Results show that misalignment of the coupling can delay the first mode of vibration and even reduce its amplitude.\n\t\t\\par \n\t\tUnfortunately, to the best of the authors’ knowledge, there are no publications about how to actually generate the cascade full spectrums directly from either X, Y transducers or simulation results. If we successfully solve this problem, we can predict what will happen in experiments from theoretical models. In this research, we will solve the following 4 problems. 1. We construct 3D full spectrum cascade plots using complex FFT through MATLAB programing. 2. We use tracking windows to filter the transducer data to nX components of rotor speed when the rotor starts up or runs down. 3. We experimentally compare our results with ADRE data. The results are directly comparable and the MATLAB plots, using our method, provide opportunity of further post processing full spectrum data. 4. Theoretical results of overhung rotor are converted into 3D full spectrum plots which will be compared with experimental data. The results presented in this paper match with experiments with confidence. More importantly, effects of different components of the theory are able to be determined. This allows for better diagnoses of real rotor systems. Stiffness of the bearings is determined by comparing theoretical natural frequencies to natural frequencies determined by experimentation. Using a Bode plot for each $xz$ and $yz$ plane, Figure \\ref{fig:Figure_14}, the natural frequency of the experimental apparatus is determined for each plane. The equations of motion \\ref{math:1}, with disregard for forcing and moment equations on the right hand side, are coupled with the total stiffness matrix \\ref{math:10} to provide a system of equations that is dependent only on time, speed and the unknown bearing stiffness parameters. This system of equations is used to solve for the natural frequencies in terms of the speed and the bearing stiffness using the eigenvalue problem. Different values of bearing stiffness are chosen in each plane and a Campbell diagram is used to solve for the natural frequency as a function of speed. Values of stiffness are iterated until the theoretical and experimental natural frequencies match.\\par\n\t\tSkew angle is determined by comparing theoretical and experimental angular displacement vibrations. Deducing the angular displacement from experiment is not easy to do, as transducers are observing the vibration of the shaft and not the angle of the disk. A method for determining the angle was employed in which displacements from two sets of transducers is compared. \\par\n\t\tTo the best of the authors’ knowledge, there are no papers which provide direct comparison between theoretical models and experimental results using full spectrum analysis. Experimental work sometimes uses full spectrum but most often it uses half spectrum. Analytical work that reports full spectrum does not correlate phase angel to instrument measurement.\n\t\t\\par\n\t\\section{Theoretical Model}\n\t\tThe theoretical model used to simulate the experimental apparatus is depicted in Figures \\ref{fig:Figure_1} and \\ref{fig:Figure_2}. Equations of motion \\ref{math:1} are determined using conservation of momentum and a dynamic analysis of the disk mass and inertial changes. The forcing functions on the right hand side of \\ref{math:1} include forces due to acceleration of the shaft so that the simulation can include change in speed of the shaft and gyroscopic effects, such as a start-up or run-down. Moment equations are presented as pertaining to the change in angular momentum of the disk (\\cite{Genta}, \\cite{Muszynska},\\cite{Gunter 93}).\\par\n\t\t\\begin{equation}\n\t\t\t\\centering\n\t\t\t\\includegraphics[scale=0.25]{./figures/Images/Math_1}\n\t\t\t\\label{math:1}\n\t\t\t\\centering\n\t\t\\end{equation}\n\t\t\\begin{figure}[h]\n\t\t\t\n\t\t\t\\begin{subfigure}[b]{.5\\textwidth}\n \t\t\t\t\\centering\n \t\t\t\t \\includegraphics[width=.75\\linewidth]{./figures/Images/Figure_1a}\n \t\t\t\t \\caption{Displacements, rotations, forces and moments}\n \t\t\t\t \\label{fig:Figure_1a}\n \t\t\t\t \\centering\n\t\t\t\\end{subfigure}%\n\t\t\t\\begin{subfigure}[b]{.5\\textwidth}\n  \t\t\t\t\\centering\n  \t\t\t\t\\includegraphics[width=.75\\linewidth]{./figures/Images/Figure_1b}\n  \t\t\t\t\\caption{Depiction of skew angle $\\chi$}\n  \t\t\t\t\\label{fig:Figure_1b}\n  \t\t\t\t\\centering\n\t\t\t\\end{subfigure}\n\t\t\t\\caption{Experimental apparatus mathematical representation}\n\t\t\t\\label{fig:Figure_1}\n\t\t\t\n\t\t\\end{figure}\n\t\t\\begin{figure}[h]\n\t\t\t\\centering\n\t\t\t\\includegraphics[scale=.25]{./figures/Images/Figure_2}\n\t\t\t\\caption{Diagram showing important parameters}\n\t\t\t\\label{fig:Figure_2}\n\t\t\t\\centering\n\t\t\\end{figure}\n\t\tThe total stiffness constants of the system are determined from geometry and properties of the rotor bearings, and divided into two main contributions from the bending of the shaft and the suspension of the bearings. These two contributions are considered independent to solve for each contribution and then are combined in series to determine the total stiffness.\\par\n\t\tCase (A) Flexible shaft with rigid bearings. Flexible Influence coefficients method in the general form of \\ref{math:2} is used to derive flexibility matrix  which can be applied in both $xz$ and $yz$ plane, respectively. Since the shaft is considered to be isotropic, the matrix is identical for the xz and the $yz$ plane (\\cite{Ishida},\\cite{Dimarogonas}).\\par\n\t\t\\begin{equation}\n\t\t\t\\centering\n\t\t\t\\includegraphics[scale=.25]{./figures/Images/Math_2}\n\t\t\t\\label{math:2}\n\t\t\t\\centering\n\t\t\\end{equation}\n\t\t\\begin{equation}\n\t\t\t\\centering\n\t\t\t\\includegraphics[scale=.25]{./figures/Images/Math_3}\n\t\t\t\\label{math:3}\n\t\t\t\\centering\n\t\t\\end{equation}\n\t\tCase (B) Rigid shaft with flexible bearing. The stiffness matrix is derived in the general form of \\ref{math:4} using stiffness influence coefficients method.\\par\n\t\t\\begin{equation}\n\t\t\t\\centering\n\t\t\t\\includegraphics[scale=.25]{./figures/Images/Math_4}\n\t\t\t\\label{math:4}\n\t\t\t\\centering\n\t\t\\end{equation}\n\t\t\\begin{equation}\n\t\t\t\\centering\n\t\t\t\\includegraphics[scale=.25]{./figures/Images/Math_5}\n\t\t\t\\label{math:5}\n\t\t\t\\centering\n\t\t\\end{equation}\n\t\tIn order to combine the bearing stiffness with the shaft stiffness, both are added as flexibility matrices.\\par\n\t\t\\begin{equation}\n\t\t\t\\centering\n\t\t\t\\includegraphics[scale=.25]{./figures/Images/Math_6}\n\t\t\t\\label{math:6}\n\t\t\t\\centering\n\t\t\\end{equation}\n\t\tApply to $xz$ and $yz$ plane, respectively to account for anisotropy of bearing stiffness for different planes.\\par\n\t\t\\begin{equation}\n\t\t\t\\centering\n\t\t\t\\includegraphics[scale=.25]{./figures/Images/Math_7}\n\t\t\t\\label{math:7}\n\t\t\t\\centering\n\t\t\\end{equation}\n\t\t\\begin{equation}\n\t\t\t\\centering\n\t\t\t\\includegraphics[scale=.25]{./figures/Images/Math_8}\n\t\t\t\\label{math:8}\n\t\t\t\\centering\n\t\t\\end{equation}\n\t\tTotal flexibility matrices in $xz$ and $yz$ plane are:\\par\n\t\t\\begin{equation}\n\t\t\t\\centering\n\t\t\t\\includegraphics[scale=.25]{./figures/Images/Math_9}\n\t\t\t\\label{math:9}\n\t\t\t\\centering\n\t\t\\end{equation}\n\t\tTotal stiffness matrices are shown in \\ref{math:10}, which are applied in equations of motion \\ref{math:1}.\\par\n\t\t\\begin{equation}\n\t\t\t\\centering\n\t\t\t\\includegraphics[scale=.25]{./figures/Images/Math_10}\n\t\t\t\\label{math:10}\n\t\t\t\\centering\n\t\t\\end{equation}\n\t\t\t\n\t\\section{Experimental apparatus}\n\t\tOur experimental apparatus consists of the GE (Formally Bently Nevada) RK4 rotor kit, the ADRE 408 Dspi Data asset condition monitoring equipment, and a laptop with the ADRE sxp software (Figure \\ref{fig:Figure_3}). Four eddy current displacement transducers are used to measure the vibration of the shaft. The ADRE 408, when coupled with ADRE sxp, is capable of providing real-time signal processing from the rotor system in meaningful figures.\\par\n\t\t\\begin{figure}[H]\n\t\t\t\\begin{subfigure}[b]{.5\\textwidth}\n\t\t\t\t\\centering\n\t\t\t\t\\includegraphics[width=.95\\linewidth]{./figures/Images/Figure_3.jpg}\n\t\t\t\t\\caption{Schematic of rotor geometry}\n\t\t\t\t\\label{fig:Figure_3a}\n\t\t\t\t\\centering\n\t\t\t\\end{subfigure} %\n\t\t\t\\begin{subfigure}[b]{.5\\textwidth}\n\t\t\t\t\\centering\n\t\t\t\t\\includegraphics[width=.95\\linewidth]{./figures/Images/Figure_3b.jpg}\n\t\t\t\t\\caption{Overview of apparatus}\n\t\t\t\t\\label{fig:Figure_3b}\n\t\t\t\t\\centering\n\t\t\t\\end{subfigure}\n\t\t\t\\caption{Experimental apparatus}\n\t\t\t\\label{fig:Figure_3}\n\t\t\\end{figure}\n\t\t\\begin{table}[H]\n\t\t\t\\centering\n\t\t\t\\caption{Rotor parameters}\n\t\t\t\\includegraphics[scale=.25]{./figures/Images/Table_1}\n\t\t\t\\label{tab:Table_1}\n\t\t\t\\centering\n\t\t\\end{table}\n\t\\section{Identify the bearing stiffness parameters from experimental data}\n\t\tWith the experimental data we were able to identify the natural frequency in the horizontal and vertical directions from the Bode plot of each horizontal and vertical transducer. From the theoretical equations of motion, the eigenvalue problem can be used to solve for the natural frequencies of the system. Since the system includes gyroscopic moments that depend on the rotational speed of the rotor, the natural frequency is a function of the speed of the rotor. The Campbell Diagram is a plot of the natural frequency as it changes with the increasing speed of the rotor. This diagram can be used to tune the bearing stiffness. The parameters that affect the natural frequency that are not evident from the description of the system is the stiffness of the bearings in each $xz$ and $yz$ plane. To solve for the stiffness values, a Campbell Diagram is created for each value of stiffness until the point at which the natural frequency line intersects the rotor speed line is the same value as the experimental natural frequency. An example of a Campbell diagram can be seen in Figure \\ref{fig:Figure_4}. The Campbell diagram gives a good depiction of how the natural frequency changes with speed and how negative natural frequencies decrease in frequency, while the positive natural frequency increases. The stiffness of the bearings was determined to be about 91000 N/m in the xz plane and about 120000 N/m in the $yz$ plane.\\par \n\t\t\\begin{figure}[H]\n\t\t\t\\centering\n\t\t\t\\includegraphics[scale=.75]{./figures/Images/Figure_4}\n\t\t\t\\caption{Example Campbell diagram}\n\t\t\t\\label{fig:Figure_4}\n\t\t\\end{figure}\n\t\tTo further understand the effect that stiffness anisotropy has on the system, Figure \\ref{fig:Figure_5} and \\ref{fig:Figure_6}  display a cascade of amplitude plots with changing stiffness anisotropy between the horizontal and vertical planes. Viewing the theoretical data in this way allows for comparison of the two natural frequencies to experimental values just as the Campbell Diagram does. In addition, the cascaded plots depict how the shape of the amplitude plots change with varying anisotropy. Figure \\ref{fig:Figure_5}  uses the amplitude of positive and negative frequencies to display the effect of anisotropy. The interaction between the first and second natural frequencies can be seen as the two get closer to one another. Negative whirling is dominant only between the two natural frequencies. When the two natural frequencies coincide, there is a highly circular positive whirl orbit. Experimental amplitude plots are used in conjunction with Figure \\ref{fig:Figure_5}  \\& \\ref{fig:Figure_6}  to choose the correct anisotropy at which the characteristic shape matches.\\par \n\t\tThe skew angle, $\\chi$, and the eccentricity, $\\varepsilon$, are determined next by independent methods. Eccentricity can be determined by simulating the theoretical model under varying eccentricities until the magnitude of the vibration is equivalent to that of the experimental results. The value was determined to be $9\\e{-4}  m$. The skew angle can be quantified using a similar technique. But the skew angle is closely related to the amplitude of vibration in the two orthogonal directions, $x$ and $y$, as well as the disk tilting angles, $\\theta_x$ and $\\theta_y$. In order to measure the tilting angles in the experiment, there were two sets of orthogonal transducers. One before the disk on the shaft and the other after the disk. This displacement between the two sets of transducers allows for an approximation of the angles of tilt. Assuming no bending of the shaft, the angle is deduced from a pivot about Bearing B, with the angle being equal to the inverse tangent of the ratio of difference in displacement between the transducers, and the distance between the transducers. Then the simulation is run with varying values of $\\chi$ to match the amplitude of angles and displacements to the experiment. The value was determined to be 0.09 radians.\\par \n\t\t\\begin{figure}[H]\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=.75\\linewidth]{./figures/Images/Figure_5}\n\t\t\t\\caption{3D cascading plot demonstrating the impact of stiffness anisotropy on positive/negative frequencies}\n\t\t\t\\label{fig:Figure_5}\n\t\t\\end{figure}\n\t\t\\begin{figure}[H]\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=.75\\linewidth]{./figures/Images/Figure_6}\n\t\t\t\\caption{3D cascading plot demonstrating the impact of stiffness anisotropy on horizontal/vertical frequencies}\n\t\t\t\\label{fig:Figure_6}\n\t\t\\end{figure}\n\n\t\\section{Produce full spectrum plots from orthogonal transducers }\n\t\tThe purpose of this work was to produce figures that represent vibration amplitude data from theoretical models in a way that is comparable to figures produced by the ADRE Sxp software. This allows the analysis of theoretical models with confidence in the representation of the data with figures such as the Bode plot, the Cascade plot, and full spectrum plots. The major achievement in producing the figures was obtaining phase lag angles between two signals. Another achievement was producing spectrum plots with both positive and negative frequencies (Full Spectrum plots).\\par \n\t\tFull spectrum plots are more complete in displaying the information contained in a Fourier Transform. In the frequency domain, negative frequencies pertain to vibration of the rotor that is precessing in the opposite rotational direction than that of the rotor rotational direction. The full spectrum plot is produced by first coupling the orthogonal transducer signals into a complex signal and then performing a Fourier transform. The transform on the complex data results in frequency information both negative and positive.\\par \n\t\tNegative frequencies tell a lot about the system, especially when they are greater than their positive counterpart. When the negative frequency vibration is greater in amplitude, the precession is said to be in the “reverse” direction. This can be vital information in diagnosing a problem in a real rotor system. In the case explored here it can be a sign of both, strong gyroscopic moments, as well as anisotropy of the stiffness from the shaft or the bearings. Another example is the rub in a fluid film bearing which manifests itself as a negative precession at twice the running speed of the rotor. This problem would be more difficult to diagnose without the knowledge of negative frequencies.\\par \n\t\tIn order to verify that the MATLAB code of our method would produce accurate frequency data, the Fast Fourier Transform, or FFT, of a steady state signal was compared to the FFT produced by the ADRE 408 with ADRE Sxp software. Both the amplitude and frequency of positive and negative frequency components was verified by comparison as demonstrated by the comparison of Figure \\ref{fig:Figure_7}  and \\ref{fig:Figure_8} .\\par \n\t\t\\begin{figure}[H]\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=.6\\linewidth]{./figures/Images/Figure_7}\n\t\t\t\\caption{Full Spectrum plot produced with the ADRE sxp software}\n\t\t\t\\label{fig:Figure_7}\n\t\t\\end{figure}\n\t\t\\begin{figure}[H]\t\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=.6\\linewidth]{./figures/Images/Figure_8}\n\t\t\t\\caption{Full Spectrum plot produced with using our method}\n\t\t\t\\label{fig:Figure_8}\n\t\t\\end{figure}\n\t\\section{Produce Bode plots from orthogonal transducers }\n\t\tThe process for producing phase lag angles begins with segmenting the data into windows of a fixed number of samples. This is because most rotordynamic data comes in the form of a “start-up” or a “run-down”. In both of these scenarios, the rotational speed of the rotor is continuously changing, as demonstrated by Figure \\ref{fig:Figure_9a}. This change deters capturing both time and frequency information. Segmenting the data provides small windows on which analysis can be performed as if the signal was a constant frequency within the window, as demonstrated in Figure \\ref{fig:Figure_9b}. For a segment of data in which the frequency is not changing, a Fourier Transform can be applied to obtain the frequency spectrum of the signal. In this frequency domain provided by the Fourier Transform, the phase angle of each frequency can be obtained as well as the amplitude of vibration of each frequency. In order to calculate the phase lag from one signal to another, this phase angle is compared for the same frequency of each signal in the same window in time. This process is done for each window through the entire length of data producing a phase angle for each window.\\par \n\t\tThe Bode plot is ubiquitous in rotating machinery diagnostics and can be used to characterize a system fairly thoroughly. Phase angle is a vital part of the bode plot and can shed light on many phenomenon One of the main goals in this paper is to demonstrate the ability to produce accurate phase lag information from two signals. As seen in the Bode plot of Figure \\ref{fig:Figure_10} , the MATLAB code based on complex FFT strategy produces phase lag information nearly identical to the phase lag information produced with the ADRE system using the same transducer data.\\par \n\t\t\\begin{figure}[H]\n\t\t\t\\begin{subfigure}[b]{.5\\linewidth}\t\n\t\t\t\t\\centering\n\t\t\t\t\\includegraphics[width=1\\textwidth]{./figures/Images/Figure_9a}\n\t\t\t\t\\caption{Rotational speed change over time}\n\t\t\t\t\\label{fig:Figure_9a}\n\t\t\t\\end{subfigure}\n\t\t\t\\begin{subfigure}[b]{.5\\linewidth}\n\t\t\t\t\\centering\n\t\t\t\t\\includegraphics[width=1\\textwidth]{./figures/Images/Figure_9b}\n\t\t\t\t\\caption{Rotational speed change over a window in time}\n\t\t\t\t\\label{fig:Figure_9b}\n\t\t\t\\end{subfigure}\n\t\t\t\\caption{Steady-state approximation demonstration}\n\t\t\t\\label{fig:Figure_9}\n\t\t\\end{figure}\n\t\tThis ability to produce phase lag information from any transducer data allows accurate comparison of theoretical and experimental data. The MATLAB code that produces these plots also allows the ability of tuning the resolution of the phase and amplitude information, gaining accuracy in either time or frequency. The phase lag calculation accuracy is determined by the number of cycles analyzed in each window, so the larger the window, the better the phase information. But, as the window gets larger, the accuracy of speed is diminished.\\par \n\t\t\\begin{figure}[H]\t\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=.75\\linewidth]{./figures/Images/Figure_10}\n\t\t\t\\caption{Bode plot for verification of the phase angle technique}\n\t\t\t\\label{fig:Figure_10}\n\t\t\\end{figure}\n\t\\section{Theoretical and experimental comparison}\n\t\tThe comparison of experiment and theoretical model developed in this research were performed. The geometric and other parameters of the rotor kit are shown in table 1.\\par \n\t\t\\begin{figure}[H]\t\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=.75\\linewidth]{./figures/Images/Figure_11}\n\t\t\t\\caption{Experimental Cascade plot directly produced by the ADRE sxp software}\n\t\t\t\\label{fig:Figure_11}\n\t\t\\end{figure}\n\t\t\\begin{figure}[H]\t\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=.75\\linewidth]{./figures/Images/Figure_12}\n\t\t\t\\caption{Re-constructed 3D experimental full-spectrum cascade plot using our strategy}\n\t\t\t\\label{fig:Figure_12}\n\t\t\\end{figure}\n\t\t\\begin{figure}[H]\t\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=.75\\linewidth]{./figures/Images/Figure_13}\n\t\t\t\\caption{3D theoretical full-spectrum cascade plot using our strategy}\n\t\t\t\\label{fig:Figure_13}\n\t\t\\end{figure}\n\t\tThe full-spectrum cascade plot is a vital tool for analysis in rotating machinery. The cascade plot depicts how the vibrations change with time. With the addition of the full spectrum in these cascade plots, the negative frequencies provide insight for diagnostics of certain rotor issues, such as misalignment of disk axis with the rotor axis. Just as with the FFT and Bode plots, the cascade plot produced with our MATLAB code using complex FFT strategy is compared with the cascade produced with the ADRE software to validate the method. From figure \\ref{fig:Figure_11}, \\ref{fig:Figure_12} and \\ref{fig:Figure_13}, we can see the results are similar and good enough to validate our full-spectrum strategy through experiment. Furthermore, MATLAB has the ability to display data in three dimensions as shown in the figures (\\cite{Southwick},\\cite{Southwick 94},\\cite{Dimarogonas}). With proper tuning of window size and sampling frequency, the cascade plot can display a host of rotordynamic phenomenon.\\par \n\t\t\\begin{figure}[H]\t\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=1\\linewidth]{./figures/Images/Figure_14}\n\t\t\t\\caption{Bode plot, Experimental vs. Theoretical}\n\t\t\t\\label{fig:Figure_14}\n\t\t\\end{figure}\n\t\tThe Bode plot of Figure \\ref{fig:Figure_14} compares the startup amplitude and phase angle of the theoretical model and the experiment. Because both the experimental and the theoretical results were processed using our strategy with the same MATLAB code to produce these plots, comparisons can be confidently drawn. The phase angles are of a phase lag from the X transducer and from the Y transducer. The two transducers are 270 positive degrees apart around the shaft.\\par \n\t\t\\begin{figure}[H]\t\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=1\\linewidth]{./figures/Images/Figure_15}\n\t\t\t\\caption{Positive/Negative frequency comparison, Experimental vs. Theoretical}\n\t\t\t\\label{fig:Figure_15}\n\t\t\\end{figure}\n\t\tObserving the comparison of positive and negative frequencies as done in Figure \\ref{fig:Figure_15} allows the detection of backward or forward whirl. When the negative frequency amplitude is greater than that of the positive frequency, the whirl is “backward”. Backward whirl describes the phenomenon of precession of the shaft vibration rotating opposite to the rotation of the shaft. Comparison to the typical horizontal vs. vertical amplitude plot shows that the crossover from positive to negative whirl occurs when either the horizontal or vertical vibration amplitudes drop.\\par \n\t\t\\begin{figure}[H]\n\t\t\t\\begin{subfigure}[b]{.5\\linewidth}\t\n\t\t\t\t\\centering\n\t\t\t\t\\includegraphics[width=.75\\textwidth]{./figures/Images/Figure_16a}\n\t\t\t\t\\caption{Experimental 1333 RPM orbit}\n\t\t\t\t\\label{fig:Figure_16a}\n\t\t\t\\end{subfigure}\n\t\t\t\\begin{subfigure}[b]{.5\\linewidth}\n\t\t\t\t\\centering\n\t\t\t\t\\includegraphics[width=.75\\textwidth]{./figures/Images/Figure_16b}\n\t\t\t\t\\caption{Experimental 1433 RPM orbit}\n\t\t\t\t\\label{fig:Figure_16b}\n\t\t\t\\end{subfigure}\n\t\t\t\\begin{subfigure}[b]{.5\\linewidth}\n\t\t\t\t\\centering\n\t\t\t\t\\includegraphics[width=.75\\textwidth]{./figures/Images/Figure_16c}\n\t\t\t\t\\caption{Theoretical 1358 RPM orbit}\n\t\t\t\t\\label{fig:Figure_16c}\n\t\t\t\\end{subfigure}\n\t\t\t\\begin{subfigure}[b]{.5\\linewidth}\n\t\t\t\t\\centering\n\t\t\t\t\\includegraphics[width=.75\\textwidth]{./figures/Images/Figure_16d}\n\t\t\t\t\\caption{Theoretical 1428 RPM orbit}\n\t\t\t\t\\label{fig:Figure_16d}\n\t\t\t\\end{subfigure}\n\t\t\t\\caption{Orbit plots fo filtered experimental data compared to theoretical predictions at similar speeds}\n\t\t\t\\label{fig:Figure_16}\n\t\t\\end{figure}\n\t\tOrbit plots of Figure \\ref{fig:Figure_16} are created using experimental and theoretical data. The orbits of experimental data contain the key-phasor dot to mark the beginning of a rotation from a fixed location on the shaft. This allows the determination of the orbit rotation direction. For all of the orbit plots, the shaft was rotating in the counter-clockwise direction. Therefore, an orbit in the clockwise direction is in the “reverse” direction. Experimental data was filtered using a tracking filter for the orbit plots. Since a once per turn reference is unavailable for theoretical data, the orbits are plotted with a reference dot at the maximum $x$ value for that orbit.\\par \n\t\t\\begin{figure}[H]\t\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=1\\linewidth]{./figures/Images/Figure_17}\n\t\t\t\\caption{Experimental 3D Orbit plot produced by our strategy}\n\t\t\t\\label{fig:Figure_17}\n\t\t\\end{figure}\n\t\t\\begin{figure}[H]\t\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=1\\linewidth]{./figures/Images/Figure_18}\n\t\t\t\\caption{Theoretical 3D Orbit plot}\n\t\t\t\\label{fig:Figure_18}\n\t\t\\end{figure}\n\t\tOrbit plots are cascaded in increasing rotational speed in the 3D orbit plots of Figures \\ref{fig:Figure_17} and \\ref{fig:Figure_18}. This cascade of orbits gives a sense of how the natural frequencies are physically manifested in these startups. This 3D orbit plot lends a more intuitive representation of the data and at the same time, important characteristics such as phase lag, amplitudes and reverse precession can be discerned from the plot. This plot was also useful in comparing the theoretical model to the experimental data, because it demonstrates magnitude as well as general shape of the response of the entire orbit in one plot. Also Figure \\ref{fig:Figure_17} and \\ref{fig:Figure_18} makes clear the effect of gyroscopic moments, as the shape of the elliptical orbits during peak amplitude vibrations are bent. The ADRE Sxp software does not produce this plot.\\par \n\t\\section{Discussion and conclusions}\n\t\t3D cascade plots (Figures \\ref{fig:Figure_12}, \\ref{fig:Figure_13}) produced using our complex FFT strategy clearly display the full vibration spectrum and complement those produced with the ADRE Sxp software (Figure \\ref{fig:Figure_11}). Both the theoretical model and the experimental results display a sudden dip in amplitude of positive frequencies between the two natural frequencies (Figures \\ref{fig:Figure_12},\\ref{fig:Figure_13}). This dip is coupled with an increase in negative frequencies, resulting in reverse orbits for a period in time. These negative orbits can be seen in Figure \\ref{fig:Figure_16}. The theoretical model suggested a strong influence from the relative phase angle of the skew to the eccentricity. Some values of phase difference offered completely positive orbits through the natural frequency, while others offered highly negative orbits. This is the greatest contribution from the skew angle, as without the consideration of it, the amount of negative to positive vibration could not be easily altered in the theoretical model.\\par \n\t\tIn this paper, the dynamic behavior of a flexible shaft with an overhung disk has been studied by employing full spectrum analysis. Anisotropic bearing stiffness and the effect of gyroscopic moments are considered in our classic theoretical model. Some of the parameters which are difficult to directly measure are estimated by combination of theoretical calculation and experimental results. Full spectrum analysis is applied to the system to reveal some interesting backward whirl vibration phenomena due to the interaction of anisotropy of the stiffness of the bearings, flexibility of the shaft and gyroscopic effect. Phenomena such as these cannot be disclosed by traditional half spectrum FFT. 3D cascade full spectrum plots from theoretical model are compared to those from experiments. Our full spectrum cascade plots using complex FFT strategy capture more detail in the vibration response of the system than the typical cascade plots. Filtered orbit plots with the key-phasor dots at different speed demonstrate forward and backward whirls. Methods for identifying the eccentricity and skew angle of the disk are presented. Also, the effect of the skew angle is determined by comparison of experiment and theory. The skew angle is determined by comparing theoretical angular amplitudes to experimental angular amplitudes. Bearing stiffness is determined through a method of matching theoretical and experimental natural frequencies. Consideration of the gyroscopic moments introduces speed as another dependent variable in the equation for natural frequency, making the process of matching an iterative one.\\par \n\t\\section{Acknowledgments}\n\t\tThe authors acknowledge the Donald E. Bently Center for Engineering Innovation at California Polytechnic State University San Luis Obispo for support of this work.\\par ", "meta": {"hexsha": "e0a8ebd1481078859ea94577d61e108f1d252266", "size": 34402, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/Overhung.tex", "max_stars_repo_name": "cameron1320/Cameron", "max_stars_repo_head_hexsha": "276144ab299ab00f102f3f3cc0869261a13e0059", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/Overhung.tex", "max_issues_repo_name": "cameron1320/Cameron", "max_issues_repo_head_hexsha": "276144ab299ab00f102f3f3cc0869261a13e0059", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/Overhung.tex", "max_forks_repo_name": "cameron1320/Cameron", "max_forks_repo_head_hexsha": "276144ab299ab00f102f3f3cc0869261a13e0059", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 120.2867132867, "max_line_length": 2128, "alphanum_fraction": 0.7935003779, "num_tokens": 7968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7090191214879992, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3489707995955746}}
{"text": "\\documentclass[journal = jacsat,manuscript = note]{achemso}\n\n%% The graphicx package provides the includegraphics command.\n%\\usepackage{graphicx}\n%\\usepackage[hidelinks]{hyperref}\n%\\usepackage{authblk}\n\\usepackage{natbib}\n%\\usepackage[backend=bibtex]{biblatex}\n\\usepackage[T1]{fontenc} % Use modern font encodings\n%% The amssymb package provides various useful mathematical symbols\n\\usepackage{amssymb}\n\n\\usepackage{amsmath}\n\n%% The lineno packages adds line numbers. Start line numbering with\n%% \\begin{linenumbers}, end it with \\end{linenumbers}. Or switch it on\n%% for the whole article with \\linenumbers after \\end{frontmatter}.\n%\\usepackage{lineno}\n\n%\\bibliographystyle{plain}\n%\\addbibresource{plasmid_replication.bib}\n\n\\title{How to model DNA replication in stochastic models of synthetic gene circuits (and why)}\n\n\\author{Samuel E. Clamons}\n\\author{Richard M. Murray}\n\\email{murray@cds.caltech.edu}\n\\affiliation{Caltech, Pasadena, CA, United States}\n\n%\\keywords{Keyword1, Keyword2, Keyword3}\n\n\\begin{document}\n\n\n\\begin{abstract}\nBiocircuit modeling sometimes requires explicit tracking of a self-replicating DNA species. The most obvious, straightforward way to model a replicating DNA is structurally unstable and leads to pathological model behavior. We describe a simple, stable replication mechanism with good model behavior and show how to derive it from a mechanistic model of ColE1 replication. \n\\end{abstract}\n\n\\section{Introduction}\n\nAlthough most synthetic biocircuits use DNA, models of synthetic biocircuits typically do not explicitly describe the dynamics of those DNA species. For example, the original repressilator model tracked mRNA and protein species, but not DNA \\cite{elowitz2000}, and the model for the first genetic toggle switch simply tracked ``repressor 1'' and ``repressor 2'' \\cite{gardner2000}. For many circuits under many modeling assumptions, it is sufficient to assume that all DNA species are held at a fixed concentration by the cell, by means of mysterious machinery whose details are irrelevant to understanding the circuit.\n\nIn some cases, however, it is useful or necessary to explicitly represent DNA as a dynamic species. Some circuits, for example, use DNA in different states as a dynamic component or readout (for example, integrase-based state machines \\cite{roquet2016}). Explicit representation of DNA can also be useful when DNA binding is slow relative to the other circuit processes (for example, CRISPR-based transcription factor networks under some conditions \\cite{Jones2017}). Stochastic models, in particular, are often most naturally expressed using explicit DNA species.\n\nExplicitly-modeled DNA often requires some mechanism of replication -- again particularly in stochastic models. Unfortunately, the obvious replication implementation $\\mathit{DNA} \\to \\mathit{DNA} + \\mathit{DNA}$ is a trap that leads to pathological circuit behavior. \n\n\\section{Trivially-replicating plasmids have no well-defined copy number}\n\nAn obvious way to model replication of a DNA species is the straightforward \n\n$$\\mathit{DNA} \\overset{\\alpha}{\\to} \\mathit{DNA} + \\mathit{DNA}$$\n\n\\noindent shown visually in Figure \\ref{fig:models_and_traces}A. We refer to this mechanism as ``trivial self-replication''. Although trivial replication is intuitively appealing, we strongly recommend against its use. \n\nAdding a dilution reaction $\\mathit{DNA} \\overset{\\gamma}{\\to} \\emptyset$, trivially self-replicating DNA has dynamics\n\n$$\\frac{d\\mathit{DNA}}{dt} = (\\alpha - \\gamma) \\mathit{DNA}$$\n\nNotice that at steady state, we have $\\alpha - \\gamma = 0$, \\emph{independent of DNA concentration}. In other words, the only finite, non-zero steady state of the trivial replication mechanism occurs when production is precisely balanced by dilution. If production is slightly faster than dilution, then the DNA's concentration will explode unphysically (and unbiologically) to infinity. Conversely, if dilution is slightly faster than production, $\\mathit{DNA}$ will always fall to zero concentration and die out. Such a steady state is structurally unstable\n\nIn a deterministic model of a trivially-replicating plasmid, production and dilution \\emph{can} be balanced perfectly, giving a nominally constant concentration of DNA, but this mechanism of replication rejects no disturbances--any addition or removal of DNA will remain permanently uncorrected.\n\nStochastic simulations of trivially-replicating DNA cannot even achieve this level of marginal stability. Stochastic simulation is, by its nature, noisy; a stochastically simulated, trivially replicating DNA will random walk in copy number until, practically speaking, it either dies out by wandering to zero or explodes to a concentration too large to simulate (see Figure \\ref{fig:models_and_traces}A).\n\n\\section{Zero-order replication recovers good steady-state properties}\n\nThe trivial replication mechanism is unstable because it has both production and degradation of DNA depend linearly on the concentration of DNA itself. A simple way to add stability to the replication model is to remove that dependence by conditioning replication on a ``dummy replication trigger'' produced at a constant rate (shown diagramatically in Figure \\ref{fig:models_and_traces}B):\n\n\\begin{align*}\n\t\\emptyset &\\overset{\\alpha}{\\to} R\\\\\n\t\\mathit{DNA} + R &\\overset{k}{\\to} \\mathit{DNA} + \\mathit{DNA}.\\\\\n\\end{align*}\n\n\\begin{figure}\n\\centering\n\\includegraphics[scale=.75]{figures/models_and_traces.png}\n\\caption{\\textbf{A)} The trivial replication mechanism, in which DNA spontaneously self-replicates. This mechanism is unstable and produces random-walking DNA concentrations. \\textbf{B)} The dummy-triggered replication mechanism, in which replication is triggered by a dummy molecule produced at a constant rate. This mechanism, coupled to dilution, is stable and rejects disturbances.}\n\\label{fig:models_and_traces}\n\\end{figure}\n\nThis mechanism has ODE dynamics\n\n\\begin{align*}\n\\frac{dR}{dt} &= \\alpha - kR*\\mathit{DNA}\\\\\n\\frac{d\\mathit{DNA}}{dt} &= kR*\\mathit{DNA} - \\gamma \\mathit{DNA}\n\\end{align*}\n\nAt steady state, $R = \\frac{\\alpha}{k*\\mathit{DNA}}$, which cancels out $\\mathit{DNA}$ in $\\mathit{DNA}$'s production term and gives $\\mathit{DNA} = \\frac{\\alpha}{\\gamma}$. This steady state is stable. As long as $k$ is fast relative to other replication dynamics ($\\alpha$ and $\\gamma$), the dummy-triggered replication mechanism emulates zero-order replication of DNA.\n\nBecause dummy-triggered replication leads to a stable steady state concentration of DNA, as shown in Figure \\ref{fig:models_and_traces}B, we recommend it over the trivial replication mechanism.\n\n\\section{Biological models of plasmid replication approximately reduce to zero-order replication}\\label{sec:reduction}\n\nDummy-triggered replication is not meant to accurately describe a real biological processes. Real cells do not control replication using consumable molecules like $R$. The critical property of the dummy-triggered replication mechanism is not its realism, but its ability to achieve the (biologically important!) property of having a defined, stable steady state.\n\nNevertheless, under a few relatively mild assumptions, at least one real-world DNA replication mechanism can be reduced to a zero-order replication mechanism equivalent to the dummy-triggered replication mechanism, . \n\nConsider the ColE1 plasmid replication system, first crystallized mathematically by Brendel \\& Perelson in 1993, shown on the left in Figure \\ref{fig:bp_diagram} \\cite{Brendel1993}. We use ColE1 as an example because it has a particularly simple and well-understood replication mechanism.\n\n\\begin{figure}[h]\n\\centering\n\\includegraphics[scale=.4]{figures/bp_diagram.pdf}\n\\caption{A mechanistic model of ColE1 (left), which can be conceptually approximated by a simplified ColE1 model (middle), which under fast RNA dynamics reduces zero-order replication equivalent to that of the dummy-triggered replication model (right).}\n\\label{fig:bp_diagram}\n\\end{figure}\n\nAlthough the details of the Brendel \\& Perelson model are a bit messy, they implement a straightforward logic:\n\n\\begin{itemize}\n\t\\item $\\mathit{DNA}$ produces an RNA species $RI$. More $\\mathit{DNA}$ leads to more $RI$. \n\t\\item Occasionally, $\\mathit{DNA}$ will spontaneously enter a primed state from which it can replicate. (Biologically, the plasmid produces an RNA primer $RNAII$ which can initiate replication.)\n\t\\item $RI$ can react with a replication-primed $\\mathit{DNA}$, un-priming it and destroying the $RI$. ($RI$ binds to $RII$ to form an inert complex that is removed by RNases.)\n\t\\item If not stopped by an $RI$, a primed $\\mathit{DNA}$ can spontaneously replicate into two non-primed $\\mathit{DNA}$. (DNA polymerase initiates replication using $RII$ as a primer.)\n\\end{itemize}\n\nWe can represent this logic more clearly with a three-species reduction of the Brendel \\& Perelson model, shown in the middle in Figure \\ref{fig:bp_diagram}, consisting of ``unprimed'' $\\mathit{DNA}$, ``primed'' $\\mathit{DNA}_p$, and feedback RNA $R$. \n\nWe can further simplify the three-species model by assuming that RNA transcription and degradation are fast compared to other replication dynamics. This should be a reasonable assumption, as both $RNAI$ and $RNAII$ have estimated half-lives of $\\approx 2$ minutes \\cite{Brendel1993}, while the plasmid's doubling time is roughly one \\emph{E. coli} cell generation time, or at least $\\approx 20$ minutes. Under this assumption, the three-species reduced ColE1 model can be approximated with one of two different single-species models, depending on the relative magnitudes of rate parameters $k_p$ and $k_{rep}$. With $k_{rep}\\gg k_p$, total DNA replication rate becomes constant with sufficiently large copy number; when $k_p\\gg k_{rep}$, replication rate is always constant. With the right parameterization, we have arrived back at a simple zero-order replication mechanism. \n\nSee supplemental notebook ``simple\\_bp\\_model\\_reduction.ipynb'' for derivations. \n\n\\section{Acknowledgments}\n\nThe authors thank John Marken and Andrew Halleran for insightful discussions and thoughtful editing. \n\n\\section{Supporting Information}\n\nFor more information and worked examples using the models described here, see our supplementary IPython notebooks at [GITHUB URL]. All notebooks use the BioSCRAPE modeling package to simulate systems with replicating DNA using both standard Gillespie stochastic simulation algorithm (SSA)\\cite{Gillespie1977} and a lineage-bjjased simulation algorithm incorporating cell growth and division.\n\nSee supplementary notebook ``model\\_comparison\\_and\\_fitting.ipynb'' for:\n\n\\begin{itemize}\n\t\\item Full descriptions of the trivial, dummy-triggered replication, full ColE1, and three-species ColE1 models.\n\t\\item Examples of replicating DNA using each of the models with the BioSCRAPE simulation package, \n\t\\item Replication of Figure \\ref{fig:models_and_traces}.\n\t\\item Comparison of model output to empirically-measured plasmid copy numbers taken from \\cite{Shao2021}, including parameter inference. \n\\end{itemize}\n\nSee supplementary notebook ``simple\\_bp\\_model\\_reduction.ipynb'' for:\n\n\\begin{itemize}\n\t\\item Derivations of the reductions made in section \\ref{sec:reduction}.\n\t\\item Random-parameter simulations evaluating the accuracy of reductions to the three-species reduced ColE1 replication model.\n\t\\item Parameter conditions for stability of the three-species reduced ColE1 model.\n\\end{itemize}\n\nSee supplementary notebook ``CRISPRlator.ipynb'' for:\n\n\\begin{itemize}\n\t\\item Worked examples of a 5-node CRISPRi-based repressilator \\cite{Clamons2017, Javier2020} implemented on a plasmid using each of the trivial, dummy-triggered replication, full ColE1, and three-species reduced ColE1 models.\n\t\\item Simulations showing synchronization of the CRISPRlator across many generations of growing and dividing cells, and dependence of that synchronization on circuit copy number, using the dummy-triggered replication model.\n\\end{itemize}\n\nSee supplementary notebook ``temporal\\_logic\\_gate.ipynb'' for:\n\n\\begin{itemize}\n\t\\item Worked examples of a population-based DNA integrase circuit capable of sensing the order of and time between arrival of two signals \\cite{hsiao2016}.\n\t\\item Demonstration of the same circuit moved to a single cell bearing the circuit on a 30 or 100 copy number plasmid (instead of in many cells bearing a single genomic copy) using dummy-triggered replication.\n\\end{itemize}\n\n\\bibliography{plasmid_replication.bib}\n\n\\end{document}\n", "meta": {"hexsha": "9613436ec90e7b7527f46095f8f7ba77479a305a", "size": 12543, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "working_copy_Clamons_plasmid_replication.tex", "max_stars_repo_name": "sclamons/plasmid_replication_modeling", "max_stars_repo_head_hexsha": "6a88ba6520e6761edb907f61623da38e7dbe3116", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "working_copy_Clamons_plasmid_replication.tex", "max_issues_repo_name": "sclamons/plasmid_replication_modeling", "max_issues_repo_head_hexsha": "6a88ba6520e6761edb907f61623da38e7dbe3116", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "working_copy_Clamons_plasmid_replication.tex", "max_forks_repo_name": "sclamons/plasmid_replication_modeling", "max_forks_repo_head_hexsha": "6a88ba6520e6761edb907f61623da38e7dbe3116", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 76.4817073171, "max_line_length": 875, "alphanum_fraction": 0.7946264849, "num_tokens": 2971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.34889134820669665}}
{"text": "\\documentclass[12pt]{article}\t\t\n%========================================================\n\\usepackage{setspace} \t\n\\usepackage{graphicx}\n\\usepackage[margin=1in]{geometry}      \n\\usepackage{hyperref}\n\\usepackage{xcolor}\n\\hypersetup{\n   colorlinks,\n   linkcolor={red!50!black},\n   citecolor={blue!50!black},\n   urlcolor={blue!80!black}\n}\t\t\n\\usepackage{natbib} \t\n\\usepackage{float}\t\t\t\n\\usepackage{amsmath}\t\n\\usepackage{amssymb}\t \t\t\t\n\\usepackage{bm}\t\t\t\t\t\t\n\\usepackage{booktabs}\n\\usepackage{dcolumn}\n\\usepackage{pdflscape}\n\\usepackage{afterpage}\n\\usepackage[hang,flushmargin]{footmisc} \n\\setlength\\parindent{0pt}\t\n%========================================================\n\\newcommand{\\X}{\\mathbf{X}}\n\\newcommand{\\x}{\\mathbf{x}}\n\\newcommand{\\z}{\\mathbf{z}}\n\\newcommand{\\Y}{\\mathbf{Y}}\n\\newcommand{\\K}{\\mathbf{K}}\n\\renewcommand{\\k}{\\mathbf{k}}\n\\newcommand{\\bc}{\\mathbf{c}}\n\\renewcommand{\\r}{\\right}\n\\renewcommand{\\l}{\\left}\n\\newcommand{\\bomega}{\\bm{\\omega}}\n\\newcommand{\\bpsi}{\\bm{\\psi}}\n\\newcommand{\\bbeta}{\\bm{\\beta}}\n\\newcommand{\\balpha}{\\bm{\\alpha}}\n\\newcommand{\\bphi}{\\bm{\\phi}}\n\\newcommand{\\btheta}{\\bm{\\theta}}\n\\newcommand{\\dist}{\\buildrel\\rm d\\over\\sim}\n\\newcommand{\\ind}{\\stackrel{\\rm indep.}{\\sim}}\n\\newcommand{\\ud}{\\mathrm{d}}\n\\newcommand{\\iid}{\\stackrel{\\rm i.i.d.}{\\sim}}\n\\newcommand{\\logit}{{\\rm logit}}\n\\newcommand{\\cA}{\\mathcal{A}}\n\\newcommand{\\E}{\\mathbb{E}}\n\\newcommand{\\V}{\\mathbb{V}}\n\\newcommand{\\cJ}{\\mathcal{J}}\n\\newcommand{\\bone}{\\mathbf{1}}\n\\newcommand{\\var}{{\\rm Var}}\n\\newcommand{\\cov}{{\\rm Cov}}\n\\DeclareMathOperator*{\\argmin}{\\arg\\!\\min}\n\\DeclareMathSizes{10}{12}{10}{10}\n%========================================================\n\\begin{document}\n\n\\title{Predicting Foreign Fighter Flows to Syria Using Machine Learning: An Introduction to Kernel Regularized Hurdle Negative Binomial\\thanks{The authors are listed in alphabetical order, and contributed equally. We thank Bryce Dietrich, Chad Hazlett, Jeff Lewis, David Rapoport, Art Stein, and Barbara Walter for their feedback. We also benefited from comments at the UCLA Comparative Politics Reading Group, and the 2016 Midwestern Political Science Association Conference. The usual disclaimer applies. For replication material and our companion software---still in its developmental phase in \\texttt{R}---see \\href{https://github.com/lukesonnet/foreign_fighters}{https://github.com/lukesonnet/foreign\\_fighters}.}}\n\n\\author{George Derpanopoulos\\thanks{PhD Student, Dept. Political Science, UCLA. Email: \\href{mailto:gderpa@ucla.edu}{\\tt gderpa@ucla.edu}} \\and Luke Sonnet\\thanks{PhD Student, Dept. Political Science, UCLA. Email: \\href{mailto:luke.sonnet@gmail.com}{\\tt luke.sonnet@gmail.com}}}\n\n\t\\maketitle\n%=========================================================\n\t\\thispagestyle{empty} \n\t\\singlespacing\n\n\\begin{abstract}\t\nWhy have some countries counted hundreds of their citizens fleeing to fight in Syria, while other countries' citizens have remained bystanders? There are three methodological challenges to answering this question. First, there may be two groups of countries: one at no risk of ``supplying'' foreign fighters and another supplying some positive amount. Second, there is no clear theory to specify the functional forms linking features to foreign fighter supply. Third, existing models perform poorly out of sample or yield output that is not amenable to social-scientific interpretations. To solve these challenges, we augment a hurdle negative binomial model with two machine learning tools. Namely, we allow our features to affect the response non-parametrically by using kernel functions that represent expansions of the data. Furthermore, we add regularization terms that penalize complexity to mitigate overfitting. Our approach combines the strengths of predictive and confirmatory models: it performs similarly to state-of-the-art machine learning algorithms in prediction while providing substantively interpretable output.  Applying our model to data on 163 countries, we find that populous, developed countries, with a large Sunni population and proximity to Syria supply more fighters. These results lend themselves to viewing foreign fighter supply as largely driven by structural forces.\n\\end{abstract}\n\n%=========================================================\n\t\\newpage\n\t\\setcounter{page}{1} \t\t\t\n\t\\onehalfspacing\n\n\\section{Introduction}\n\nThe ongoing Syrian Civil War has been named ``the world's largest humanitarian crisis since WWII'' \\citep[p. 1]{ECHO2015}. 230,000 dead, 850,000 injured, 4 million refugees, and 7.5 million internally displaced; these are some conservative estimates of the conflict's cost.\\footnote{All figures are the most recent estimates that could be found as of June 2015 \\citep{UNOCHA2015}.} An integral component of the conflict are the multiple rebel groups involved, like Islamic State, Jabhat al-Nusra, and the Free Syrian Army. Although rebel manpower is hard to estimate, there is consensus that a significant portion of it comes from foreign fighters \\citep{Byman2015}, ``non-state actors involved in military activity in a foreign country'' \\citep[p. 1]{Hegghammer2013}. Moreover, with an estimated 21,000 foreigners from 50 countries fighting in Syria \\citep{Neumann2015}, foreign fighter supply has reached a historical high \\citep{Hegghammer2013a}. \\\\\n\nNaturally, policy-makers are asking themselves what draws their voters to participate in a foreign conflict. Common concerns were best expressed by Britain's Prime Minister, David Cameron: ``one of the most disturbing aspects is how this conflict is sucking in our own young people, from modern, prosperous societies''. So far, public discourse has addressed these concerns by focusing on individual fighters' motivations. This has been complemented by an emerging case-study literature based on returning fighter interviews \\citep{Stenersen2011, Weggemans2014, Nilsson2015}. As a result, a popular conception of foreign fighters has emerged; that of young Muslims from poor urban environments, with ``deep-seated feelings of marginalization and exclusion'' \\citep[p. 2]{Noor2014}.  \\\\\n\nWhether the inferences of this literature are accurate and generalizable is an open question. Before settling it, though, policy-makers might want to know what the role of \\textit{country-level} features is in individual fighters' calculus. In particular, we might ask to what extent can foreign fighter supply be attributed to \\textit{policy}, which is under the control of government, versus countries' \\textit{structural features}, which are sticky. To date, there is no study addressing these questions. However, the ongoing nature of the conflict, its spillovers into the region, and the continuing flow of fighters throughout the globe call for a systematic analysis of the evidence. We take a first step in that direction, thereby responding to the recommendations of policy reports, that ``strategies would benefit immensely from more evidence-based research'' \\citep[p. 17]{GCCS2014}. \\\\\n\nAn analysis of the predictors of foreign fighter supply is hindered by two classes of problems: data availability and modeling challenges. In this study, we focus on overcoming the difficulties in modeling this process. Namely, our approach addresses four sets of issues, relating to our priors about the country-level mechanism generating foreign fighter supply, the nascent state of the literature, and our dual interest in prediction as well as inference and interpretability. \\\\ \n\nFirst, our theory-motivated prior that foreign fighter supply is a two-component process---some function of countries' features should predict \\textit{whether} they supply any foreign fighters and, if so, another function should predict \\textit{how many} fighters they supply. This is motivated by qualitative evidence that supplying at least one fighter alters supply dynamics within a country; radicalization and recruitment networks form, along with policies to contain them, and a different mechanism takes over the ``scaling-up\" of supply. Such a theoretical structure suggests that a two-component mixture model is appropriate, with one component predicting assignment to supplier countries (binary response), and a second component predicting the number of fighters supplied (count response left-truncated at $1$). This directs us to the familiar hurdle model \\citep{Mullahy1986}. In addition, the count nature of the response and its large variation urge us to further refine our specification to the hurdle negative binomial model.  \\\\\n\nAs with any mixture model, we can allow different features, or different functions of the same features, to enter each component. However, this brings us to a second modeling challenge: there is little theory on how a country's features combine to affect foreign fighter supply, let alone how this should vary between the model's components. The assumption behind most regression models is that the systematic component of a unit's response is a linear function of its features \\citep{King1989a}. When models are specified using vague theoretical priors, though, parametric assumptions are hard to justify \\citep{Ho2007}. Instead, model-fitting could greatly benefit from a flexible semi-parametric approach. Semi-parametric and non-parametric models are not uncommon, yet existing models do not allow us to impose the theoretically-motivated structure of the hurdle model. \\\\\n\nAnother downside of many non-/semi-parametric models is that they overfit the data, thereby yielding poor out-of-sample predictions -- a third challenge to address. This can be addressed by machine learning algorithms that penalize complexity, like LASSO and Random Forest. Regularizations based methods like the LASSO or Ridge regression use $k$-fold cross-validation to tune penalty, or regularization parameters in order to strike a better balance on the bias-variance tradeoff than classical estimators. Unfortunately, though, semi-parametric regularized models give way to a fourth challenge: they do not produce quantities of interest familiar to social scientists, like marginal effects and confidence intervals. In fact, demanding such quantities of interest requires sacrificing flexible model-fitting---for example, output from ridge regression is interpreted like that of GLMs, but the model assumes that the features affect the response linearly.  \\\\\n\nIn short, we seek an algorithm that combines attractive features from multiple approaches: the intuitive structure of the hurdle model, the agnosticism of non-parametric models on how the features combine to affect the response, the good out-of-sample performance of regularized algorithms, and the interpretability of standard regression models. We bridge the generalized linear model and machine learning literatures to arrive at such an algorithm, the Kernel Regularized Hurdle Negative Binomial (KRHNB). Specifically, we derive our estimator by applying kernel expansion and regularization to a hurdle negative binomial, then develop companion software to compute parameter estimates that minimize prediction error, produce pointwise marginal effects, and get bootstrapped estimates of uncertainty. \\\\\n\nOur procedure consists of several simple steps. We begin by assuming the data is generated by a two-component mixture model: a logit predicting whether a positive count is observed and a negative binomial (left-truncated at $1$) predicting the conditional count. Then we form the sample log-likelihood function and add a regularization term (using an $L_2$ norm), thereby arriving at our target function---the penalized log-likelihood. To move away from a fully parametric form, we expand our feature matrix into a higher-dimensional space; in our application we use an infinite-dimensional space corresponding to all possible expansions of the data (e.g. polynomial, logarithmic, exponential, multiplicative). This makes our target function linear in the \\textit{mapping} of the features, instead of the features themselves. We then show that the features enter the minimum of the target function solely through inner products and thus can be substituted by positive semi-definite kernels, like the Gaussian kernel. This is known as Mercer's Theorem and enables numerical optimization of the target function. \\\\\n\nPredicted responses are derived by substituting our estimates into the hurdle negative binomial's conditional expectation function (CEF). Pointwise marginal effects for feature $j$ are computed using numerical derivation of the CEF with respect to feature $j$. Averaging these effects for each feature gives us its average pointwise marginal effect. Finally, redrawing $1,000$ samples from our data with replacement and repeating the above computations gives us non-parametric bootstrapped estimates of uncertainty---a distribution of average pointwise marginal effects for each feature. All relevant computations are performed with our companion software, written in the \\texttt{R} language.\t\\\\\n\nKRHNB has two attractive properties over the standard hurdle negative binomial. First, regularization penalizes complexity, thereby striking a better balance on the bias-variance tradeoff. Thus, our procedure is less prone to overfitting the training data and better predicts test data. Second, feature expansion implicitly allows our features to affect the systematic component of the response through any functional form. This is particularly valuable in this context; the absence of theories of country-level foreign fighter supply should deter us from making strong parametric assumptions. Nevertheless, one might ask: does our method improve over other machine learning models? After all, there are other algorithms that penalize complexity, some of which impose less structure on the data.   \\\\\n\nTo answer this question, we compare our method to three popular machine learning algorithms and find that it performs better or comparably to all of them. Using a cross-section of 163 countries, and an array of 27 demographic, economic, geographic, and political features, we compute the leave-one-out cross-validation root mean square error and the mean absolute error. Higher mean absolute error rates are produced by all 3 of our benchmark models: Kernel Regularized Least Squares (KRLS) \\citep{Hainmueller2013}, KRLS truncated at 0, and a Random Forest. Only Random Forest outperforms KRHNB with respect to root mean squared error and this is largely due to its relative success in predicting a few large outliers. \\\\\n\nHaving established the merits of our approach -- theoretical motivation, flexibility, predictive power, and interpretability -- we apply it to our data, in an effort to contribute to the literature on foreign fighters. Substantively, we find that structural features dominate in predicting foreign fighter supply: populous, developed countries, that are close to Syria, and have a high concentration of Sunnis supply more fighters. Some features that respond to government policy more easily also matter: internet usage, refugee intake, government regulation of religion, and government favoritism of a particular religion positively predict foreign fighter supply. Our method also lends itself to the discovery of interesting heterogeneity in the predictive effect of our features. We find that the positive relationships of refugee intake and government regulation of religion with foreign fighter supply stem from European and Muslim-majority countries, respectively. Throughout this paper, we refer to effects in the sense of partial derivatives; we do not make causal claims.\t\\\\\n\nTo the limited extent that our research design allows us to inform policy, the implications of our findings for constraining foreign fighter flows are grim: little can be done and what can be done is costly. This is because the strongest and most accurate predictors of foreign fighter supply are structural features, while the cost of altering policies that predict supply might exceed the benefit of curbing it; in European countries, reducing refugee intake would arguably alienate the median voter, while in Muslim-majority countries, liberal government policies towards religion might be resisted. Furthermore, the relationships uncovered by this analysis say little about the general equilibrium effects of a large shift in government policy.    \\\\\n\nThe remainder of this study proceeds as follows. Section \\ref{sec:background} provides background information on the Syrian Civil War and foreign fighters. Section \\ref{sec:theory} reviews the emerging literature on foreign fighter supply and synthesizes a theoretical framework to analyze the data. Section \\ref{sec:hurdles} outlines some obstacles to empirical modeling in this setting, and motivates our method. Section \\ref{sec:krhnb} presents the theory and mechanics of KRHNB. Section \\ref{sec:computation} covers issues related to modeling choices and computation. Section \\ref{sec:comparison} compares our predictions to those of other models. Section \\ref{sec:results} displays the substantive findings of our analysis and provides possible substantive interpretations. Finally, Section \\ref{sec:conclusion} summarizes, underlines the limitations of our approach, and suggests directions for future research. \n\n%=========================================================\n\\section{Foreign Fighters in Syria}\t\\label{sec:background}\n\nForeign fighters are not a novel fighting technology. They have existed since at least the Greek War of Independence in the 1820s, have participated in different types of conflicts (ethnic, political, religious), and in several regions of the world (Europe, Asia, Latin America, Africa) \\citep{Malet2010}. However, the scale of foreign fighter presence in Syria is unprecedented. Conservative estimates place it around $21,000$, far exceeding supply to conflicts in the past 40 years, like those of Afghanistan, Bosnia, or Somalia \\citep{Hegghammer2011}. Already, confirmed cases of foreign fighters have been noted in $50$ countries \\citep{Neumann2015} -- their supply is mapped in Figure \\ref{fig:ff_map}. \\\\\n\n\\begin{figure}\n\t\\centering\n\t\\includegraphics[width = \\linewidth]{tabs_figs/worldMap_edited.pdf}\n\t\\caption{Global Distribution of Foreign Fighter Supply, Through 2014 \\citep{Neumann2015}}\t\\label{fig:ff_map} \n\\end{figure}\n\nThe scale of the foreign fighter phenomenon has raised a number of concerns in both Syria and supplier countries. Regarding the conflict itself, there is concern that foreign fighters may swing outcomes. Indeed, there is anecdotal evidence that insurgencies with foreign fighters are more successful \\citep{Hegghammer2011, Malet2010}. Moreover, the Syrian case is complicated by the presence of multiple organizations with competing ideologies. On the one hand, groups like the Free Syrian Army (FSA) promise a secular, democratic and pro-Western government upon toppling Assad. On the contrary, groups like Islamic State (IS) strive to replace the Ba'athist regime with an Islamic caliphate. To the extent that both of these opposing camps are continuously strengthened by foreign fighters, it is unlikely that either will prevail. Hence, even if insurgents succeed in defeating the state, factional conflict will make a ceasefire unlikely.\\footnote{The dynamics are complicated further if we consider Hezbollah and other Shia or pro-government militias' support of Assad.} \t\\\\\n\nJust as many concerns have been raised in the countries where foreign fighters originate. Despite some governments taking an active stance on the conflict, they do not condone their citizens' participation, even if it is in support of an organization allied with their government (e.g. FSA).\\footnote{In order to deter their citizens from joining the conflict, some governments have passed legislation to revoke returning fighters' citizenship (e.g. Australia, Britain, Canada, USA). See \\href{http://news.nationalpost.com/news/canada/canadian-government-revoking-passports-of-citizens-trying-to-join-extremist-groups}{http://news.nationalpost.com/news/canada/canadian-government-revoking-passports-of-citizens-trying-to-join-extremist-groups}.} More problematic is the case of foreign jihadis, since a coalition of numerous countries has declared war on groups like IS, yet some jihadis are citizens of these countries. A prominent example is ``Jihadi John'', a British citizen---and IS fighter---that was bombed by air strikes funded through his taxes. Cases like this have troubled Western governments, whose citizens comprise an estimated $20\\%$ of foreign fighters in the conflict.\\footnote{This estimate is based on the data we employ \\citep{Neumann2015}. In this case, the West is defined as non-Muslim-majority countries.} \\\\\n\nIn addition to shaking the liberal-democratic foundations of these countries, the greatest concern relates to the ``veteran effect'': the risk of returning fighters carrying-out terror attacks in their home country \\citep{Hegghammer2013}. Veterans' training, experience in combat and access to networks of fighters makes them prime candidates for terrorist recruiting, with \\cite{Hegghammer2011} claiming that ``most transnational jihadi groups today are by-products of foreign fighter mobilizations'' (p. 53). Naturally, policy-makers are worried that their citizens can participate in foreign conflicts and then import violence to their home country.\t\\\\\n\nA similar pattern holds in the literature. Few studies ask what causes one to become a foreign fighter, while virtually none focuses on country-level features. Crucially, ignoring these features impedes our ability to prevent foreign fighter flows in future conflicts. Admittedly, the Syrian conflict is well underway, and thus the most efficient way to minimize its costs is to contain its spillovers. In future cases, though, given that prevention is cheaper than treatment, a more efficient strategy is to identify potential supplier countries. This will also benefit countries on the receiving end; negotiation is always preferable to conflict, but the potential inflow of fighters makes conflict more likely.   \\\\\n\nThis study takes the first step towards predicting country-level foreign fighter flows. Before proceeding, though, in the next section we briefly review the emerging literature on foreign fighters and synthesize it into a broad theoretical framework. We do not put forth an argument for how foreign fighter flows take shape at the country level, let alone the individual level. We simply impose the minimum theoretical structure necessary to later enable a substantive interpretation of our findings. \n\n%=========================================================\n\\section{Predictors of Foreign Fighter Supply}\t\\label{sec:theory}\n\nThe literature on foreign fighters is still in its nascent stage, yet combines insights from a range of disciplines: political science, history, sociology, public policy, security, and counter-terrorism studies. A comprehensive review of this work is beyond our scope, and instead we focus on studies that touch on the determinants of foreign fighter supply. Unfortunately, we are aware of only one study that explores \\textit{country}-level predictors \\citep{Hewitt2009}; remaining studies and policy reports tackle the question at the individual level.\t\\\\ \n\nCrucially, although we extract the covariates that feature in this literature to synthesize a framework for country-level explanations of foreign fighter supply, we do not claim to \\textit{test} the theories posited in the literature. To make that claim would be to commit an ecological fallacy, since existing theories are about individuals, while our data covers countries. We merely borrow from individual-level theories to motivate our search for predictors at the country level. Similarly, we do not present every possible channel through which country features might operate on foreign fighter supply, as our research design does not have the power to adjudicate between competing mechanisms.\\footnote{Many of the potential mechanisms we review come from the transnational terrorism literature. For a discussion of the distinction between foreign fighting and other forms of violence, see \\cite{Hegghammer2011}.}\t\t\\\\\n\nWe divide country-level explanations of foreign fighter supply into two broad camps: structural vs. policy-related. The former involve features of a country that are ``sticky'', and respond very slowly to policy or shocks (e.g. geography, demography, development level).\\footnote{\\cite{Jackson2012} define a ``sticky'' variable as ``[a] highly autoregressive process that is slow to adapt to changes\" (p. 163). They add that ``[in] many policy areas, the influence of interest groups, the security of incumbents, the number of veto players, and bureaucratic inertia are likely to produce high values of $\\rho$ [the autocorrelation index] in any model of the policy processes'' (p. 163).} Policy-related explanations, on the other hand, point to country features that are either the direct output of government decisions (e.g. discrimination laws), or an outcome that is significantly influenced by government (e.g. respect for human rights). Although, policy and structure are interrelated---structure constrains policy, while policy can alter structure in the long-run---we adhere to this simplistic yet powerful classification for the sake of conceptual clarity.\t\\\\\n\nNumerous structural variables have figured in popular conceptions of foreign fighter-prone countries. Proximity to the conflict zone, because it decreases the travel cost incurred by fighters, along with spillovers of the conflict.\\footnote{Distance has also been used to explain the unprecedented \\textit{aggregate} flow of fighters to Syria, due to the conflict's proximity to Europe \\citep{Hegghammer2011}.} Population, since a positive (unconditional) probability of any individual becoming a foreign fighter implies that larger countries should have a higher supply. Urbanicity and population density, via the notion that radicalization networks operate more easily in urban centers and densely inhabited areas \\citep{Gibbs1989}. A right-skewed age distribution and large male population share, on account of rebel groups' preference for young male recruits.\\footnote{Nevertheless, it is worth noting that the Syrian foreign fighter movement is the first with such a high participation of females (see \\href{http://www.theguardian.com/world/2014/sep/29/schoolgirl-jihadis-female-islamists-leaving-home-join-isis-iraq-syria}{http://www.theguardian.com/world/2014/sep/29/schoolgirl-jihadis-female-islamists-leaving-home-join-isis-iraq-syria}).} The share of the country's population that identifies with a particular party in the conflict, by virtue of common nationality, ethnicity, or religion. This operates both on the supply side, with members of the diaspora having a steak in the conflict on account of their shared identity with some rebel group, and on the demand side, with recruiters manipulating the salience of identities to construct a sense of moral obligation to fight \\citep{Malet2010}.\\footnote{\\cite{Malet2015} qualifies this by arguing that shared ethnicity is not as strong of a motivating factor as shared religion.} Development, via the findings of \\cite{Hewitt2009} that more developed countries supplied more foreign fighters to Iraq.\\footnote{The authors do not offer an interpretation of their findings. However, they do review the more conventional view expressed by \\cite{Lewis2004} and \\cite{Gerges2009}; that Islamic radicalism is owed to a lack of modernization in Muslim-majority countries. Clearly, this explanation is problematic when applied to the case of Syria, as it cannot account for the large supply share held by the developed world.} Unemployment, particularly among the young and males, because they decrease the opportunity cost of participating in conflict vis-\\'a-vis recruiters' preference for that target group \\citep{RAN2014}. Homicide rates, given the notion that individuals raised in violent environments might export that violence to different theaters, especially if different forms of violence are substitutable.\t\\\\\n\nAn equally large number of policy variables has been associated with foreign fighter supply. Poor human and civil rights, repression, and censorship, due to their association with authoritarianism. Scholars have argued that aspects of liberal democracy alleviate grievances that lead to terrorism \\citep{Crenshaw1981}, but also that they decrease the cost of organizing terrorist acts and the punishment for carrying them out \\citep{Schmid1992}.\\footnote{For a review of a similar debate on the role of regime-type in terrorism, see \\cite{Chenoweth2013}.} Discriminative policies against minorities that share an identity with some party in the conflict, as they create grievances that have been argued to fuel terrorism \\citep{Piazza2011, Sageman2008}. The number of migrants and refugees, via two channels; first, their own radicalization, if they originate from countries that have a stake in the conflict (e.g. Muslim refugees and migrants in France), and second, their effect on citizens of the host country that are prone to radicalization (e.g. French citizens of Moroccan origin). Lastly, internet penetration, as most foreign fighter recruitment occurs online \\citep{Hegghammer2011}.\t\n\n%=========================================================\n\\section{Hurdles to Predicting Foreign Fighter Supply}\t\\label{sec:hurdles}\n\nAny empirical investigation of the correlates of foreign fighter supply encounters two central difficulties. The first relates to data availability, as foreign fighter supply is poorly measured. Naturally, foreign fighters do not report their participation in conflict, especially in supplier countries where returning fighters face punishment.\\footnote{Increasingly, fighters are using social media to publicize their activities. This has allowed more fine-grained measures of foreign fighter supply to develop, but not to the extent where we can use them in our analysis.} As such, any data on foreign fighter supply remains an estimate and is subject to non-random missingness and measurement error. Nevertheless, it is our conviction that the (nascent) literature on this question can gain enough from analyzing this data to warrant a full investigation. Thus, we will treat these estimates as our response variable (Section \\ref{sec:results}) and delegate improved data-collection to future work. \\\\\n\nWe instead focus on the second difficulty, which relates to prediction, inference, and interpretability. In particular, our approach is motivated by a desire to address four issues. First, we believe that foreign fighter supply at the country level can be theorized as a two-component process. \\textit{Whether} a country supplies any foreign fighters can be thought of as one component of the process; \\textit{how many} fighters it supplies can be thought of as another component. In other words, using an analogy of countries as firms and foreign fighter supply as a firm choice, one mechanism should determine which countries become suppliers of fighters and another mechanism should determine how much they scale-up their supply by. This is justified if different supply dynamics take over once a country ``decides'' to become a supplier.\\footnote{The use of ``once\" here does not imply a temporal dimension, since our model does not take account of time---in the statistical setup, the two decisions (whether to supply, how much to supply) are simultaneous.} Indeed, anecdotal evidence suggests that after radicalization and recruitment networks form, along with the policies to contain them, the mechanism underlying foreign fighter supply changes; incentives and costs for prospective fighters are fundamentally altered by the existence of previous fighters \\citep{Felter2007, Klausen2015}.\t\\\\\n\nAs such, we require a model that allows us to make a conceptual distinction between the two components of foreign fighter supply. The model should allow a country's features to differentially affect whether it becomes a supplier or not and how many fighters it supplies. More precisely, we allow for the possibility that there are different functional forms that govern the relationship between the features and the two components of the model. For example, security policies might have a small effect on whether aggrieved citizens decide to form a foreign fighter movement, but they may have a large effect on whether additional citizens join that movement---it may deter them from undertaking the potential legal costs of becoming a fighter. It is also possible that some features influence whether any foreign fighters are supplied, while having no effect on how many are supplied.\t\\\\\n\nThe above points us to the familiar hurdle model of \\cite{Mullahy1986}, a two-part mixture model combining a binary component with a truncated count component.\\footnote{The hurdle model was introduced to political science by \\cite{King1989} and \\cite{King1989a}. However, to the best of the authors' knowledge, its only application to a political science question is \\cite{Marschall2010}, which fits a Poisson process to the count component. For a comparison and application of the hurdle versus its more popular counterpart---the zero-inflated model---directed at a political science audience, see \\cite{Zorn1998}. Virtually all political science studies that employ the zero-inflated negative binomial do so to model terrorism (e.g. \\cite{Li2005}, \\cite{Burgoon2006}, and \\cite{Wilson2013}), or politically violent events more generally (e.g. \\cite{Bagozzi2015}). Note that zero-inflation is also used in other processes of discrete random variables, generating models like the zero-inflated ordered probit \\citep{Bagozzi2015a}, the middle-inflated ordered probit \\citep{Bagozzi2012}, and the baseline-inflated multinomial logit \\citep{Bagozzi2015b, Bagozzi2015c}.} Applied to the question of foreign fighter supply, the former predicts which countries are suppliers and the latter the number of fighters supplied by each country. Crucially, different features can enter each component and even if the same features are entered different marginal effects are returned. Thus, the hurdle model can handle both conceptual distinctions drawn above. Moreover, it closely follows our prior about the two-component structure of foreign fighter supply at the country level.\t\\\\\n\nTo adapt the hurdle model to the question of foreign fighter supply, appropriate statistical processes must be chosen for each component. For the binary component, the choice does not matter greatly, with the logit being the standard.\\footnote{For a theoretical overview of count models, see \\cite{Cameron2013}. For an applied overview in the context of the \\texttt{R}  language, see \\cite{Zeileis2007}.} As for the count component, the choice of process should depend on the distribution of foreign fighter supply across supplier countries. A common feature of count data is over-dispersion---the variance of the distribution exceeding its mean.\\footnote{See \\cite{Cox1983} for an early discussion of problems created by over-dispersion in count models.} Indeed, as Figure \\ref{fig:ff_map} shows, this is the case with foreign fighter data---some countries supply only a handful of fighters (e.g. New Zealand), while others supply thousands (e.g. Tunisia). Since this pattern cannot arise under the canonical Poisson process, estimates from a Poisson hurdle will suffer from high variance. A popular fix to this problem is to instead fit a negative binomial distribution to the count component. This restores the good statistical properties that the Poisson process holds under no over-dispersion \\citep{Lawless1987}. \t\\\\\n\nAn altogether different concern with our empirical setting is the absence of a theory to guide functional form selection. Still at its nascent stage, the literature is very far from specifying the correct function through which country features affect foreign fighter supply. That is, even if there was consensus that the count of foreign fighters from each country is a function of, say, its poverty and unemployment rates, there would be no consensus on whether that function is linear, exponential, logarithmic, or of any other form. This is made worse by the two-component nature of our model, as the danger of misspecification is doubled. The assumption behind most regression models, not just the linear one, is that the systematic component of the response is a linear function of its features \\cite{King1989a}. However, when models are specified using vague theoretical priors, parametric assumptions may be unwarranted \\citep{Ho2007}. \t\\\\\n\nInstead, model-fitting could greatly benefit from a flexible nonparametric approach. Nonparametric models are not new to political science, but their application has been relatively limited.\\footnote{We were unable to find a single review of nonparametric methods in a political science journal or textbook. This stands in contrast to related disciplines, like economics, where nonparametric estimators are more widely employed.} We argue that our discipline has a lot to gain from drawing a closer connection between the theories posited and the functions fit to the data. It is rarely the case that our theories are developed enough to accurately test them using assumptions as strong as those of GLMs. Therefore, to conduct fairer investigations of the validity of our hypotheses, we must relax the narrow confines of parametric models. \t\t\\\\\n\nOne form-free way to include a set of features in the systematic component of the response is to map them into a high-dimensional space, such as a high order polynomial expansion of the data or even more complicated expansions. Yet, such an expansion of the features into a regression model often will make computation unfeasible. Therefore, we need a way to \\textit{implicitly} consider higher-order expansions of the features, without actually computing them. This is possible if the expanded feature matrix enters our likelihood function only as an inner product; the inner product can be substituted with an appropriate kernel matrix of the features (see next section), via Mercer's Theorem. As such, kernels allow us to consider a high-dimensional function space, thereby fitting the CEF of the hurdle negative binomial much more flexibly than its classical counterpart. In our case, we use the Gaussian kernel which corresponds to an infinite-dimensional mapping of the data, allowing for very flexible functions. \t\\\\\n\nA third issue that our approach seeks to address is overfitting---the danger of producing predictions that generalize poorly to other samples. This danger is particularly grave in settings where the data-generating process is under-theorized, as is the case with foreign fighter supply. The researcher can embark on a quest to find the best-fitting model, trying numerous different specifications in order to minimize an appropriate metric, such as mean squared error. That model, in turn, may fit the available data very well, but may not fit other samples well. Overfitting becomes even more worrisome in under-theorized settings when coupled with nonparametric methods. Algorithms such as local polynomial regression and kernel regression fit complex surfaces through the training data, but make large prediction errors when applied to test data \\citep{Mroz1999}.\\footnote{Kernel regression does not necessarily involve regularization, and thus should not be confused with kernel \\textit{regularized} regression models like KRLS and KRHNB.} In other words, their emphasis is on minimizing bias in the given sample, as opposed to generating predictions generalizable to withheld samples.\t\t\\\\\n\nTo strike a better balance on the bias-variance tradeoff, we employ regularization and cross-validation. These are standard tools in machine learning methods that penalize complexity to improve out-of-sample prediction. Regularized algorithms based on the $L_2$ penalty, such as ridge regression \\citep{Hoerl1970}, shrink the coefficients of features that do not significantly improve prediction, while others based on the $L_1$ penalty, like Lasso \\citep{Tibshirani1996}, perform well in high-dimensional settings where feature selection is desired. Cross-validation, in turn, enables the optimal tuning of the regularization parameter, especially when there are few data points in the training set. Regularization and cross-validation have spurred the development of numerous algorithms. However, until recently these tools had not been used alongside kernel expansion.\\footnote{\\cite{Zhu2005} introduce kernel logistic regression, \\cite{Shim2011} and \\cite{Shim2012} apply kernel regularization to Poisson regression, and \\cite{Hainmueller2013} present kernel regularized least squares.} This might not seem important, given that nonparametric model fitting and regularization can both be accommodated without using kernels (e.g. Random Forest). \t\\\\\n\nAvoiding kernels, though, gives rise to our fourth issue: interpretability and inference. Many machine learning methods produce output that social scientists are not accustomed to analyzing.\\footnote{For a relatively comprehensive review of interpretability issues in machine learning methods, see pp. 9-12 of \\cite{Hainmueller2013}.} For example, familiar quantities of interest, such as marginal effects and confidence intervals, are absent from algorithms like Random Forest. Similarly, other regularized algorithms, like ridge regression, do produce familiar output, but make strong parametric assumptions---namely, that the response is a linear function of the features, as in OLS.\\footnote{\\cite{Hainmueller2013} note that applying kernel expansion (with a Gaussian kernel) and regularization (with an $L_2$ norm) to a least squares problem produces an \\textit{infinite-dimensional} ridge regression model. This should be contrasted to standard ridge regression (without kernel expansion), which solves a $P$-dimensional linear problem and, hence, produces a parametric fit.} In short, kernel expansion vis-\\'a-vis regularization and cross-validation aggregates the benefits of all aforementioned models: fitting a flexible solution surface, penalizing complexity, and communicating output to social scientists. \t\t\\\\\n\nBefore presenting the mechanics of our approach, we note that machine learning methods are not new to political science. Although already in \\cite{Beck1998} and \\cite{Beck2000} efforts were made to import some of these ideas to the discipline, limitations to computing power contained their expansion. Recently, though, this containment has ceased: \\cite{Kenkel2013} introduce \\texttt{polywog}, a model that fuses basis regression with regularization, cross-validation, and bootstrapping; \\cite{Hill2014} and \\cite{Muchlinski2016} use Random Forests to model state repression and civil war onset, respectively; \\cite{Wilson2015} use KRLS as a robustness check in modeling expropriation risk in autocracies; \\cite{Green2012} and \\cite{Montgomery2015} apply Bayesian Additive Regression Trees to survey experiment data and election fraud measures, respectively; \\cite{Montgomery2015a}, \\cite{Fariss2015}, and \\cite{Jones2015} discuss possible contributions of machine learning to political science.\\footnote{These studies by no means constitute the universe of political science papers employing machine learning tools.} In the following section, we develop a method that we hope will contribute to the growing use of machine learning in political science.\\footnote{For alternative ways of motivating and deriving kernel regularized models, we refer the reader to the simple and intuitive expositions in \\cite{Hainmueller2013} and their supplementary appendix. In what follows, we only take one possible approach to the derivation, in order to expose the mechanics of our method.}\n\n%=========================================================\n\\section{The Model}\t\t\\label{sec:krhnb}\n\nIn this section we construct the likelihood for the hurdle negative binomial model, reparameterize our model in an infinite-dimensional space, demonstrate that our features only enter our penalized likelihood via inner products, and then use Mercer's theorem to rewrite the problem using Gaussian kernels rendering optimization feasible.\t\t\\\\\n\nAssume $y_i$ is a count ($y_i \\in \\{0,1,\\dots,\\infty\\}$). We begin with the general formulation of the two-component density of the hurdle model \\citep{Mullahy1986}, which combines a zero-hurdle component, right-censored at $y_i=1$, with a positive count component, left-truncated at $y_i$=1:\\footnote{For the original formulation of the hurdle model---albeit not for count variables---see \\cite{Cragg1971}. Throughout, positive counts refer to \\textit{strictly} positive counts.}\n\n\\begin{align}\n  p(y_i) = \\begin{cases}\n             p_0(y_i = 0) \\quad &\\text{if } y_i = 0 \\\\\n             \\frac{p_1(y_i)}{1 - p_1(y_i = 0)} (1 - p_0(y_i = 0)) \\quad &\\text{if } y_i \\geq 1\n           \\end{cases}\n\\end{align} \n\nAny binomial model (e.g. probit) or right-censored count model (e.g. Poisson) can be chosen for the zero hurdle component. We follow the literature in opting for the computationally simple logit. Similarly, any count model can be chosen for the positive count component. We opt for the negative binomial, because it allows us to account for over-dispersion---as we will see, a characteristic of our response variable. Before providing the likelihood for $y_i$, we note the following useful densities:\n%\n\\begin{align}\n  p_0(y_i = 0) &= \\frac{1}{1 + \\exp(\\alpha_0 + \\x^\\top_i \\balpha)} \\label{eq:dens0} \\\\\n  p_1(y_i) &= \\frac{\\Gamma (\\zeta + y_i) \\l( \\frac{\\zeta}{\\zeta + \\exp(\\beta_0 + \\x^\\top_i \\bbeta)} \\r)^\\zeta  \\l( \\frac{\\exp(\\beta_0 + \\x^\\top_i \\bbeta)}{\\zeta + \\exp(\\beta_0 + \\x^\\top_i \\bbeta)} \\r)^{y_i}}{\\Gamma(1 + y_i) \\Gamma(\\zeta)} \\label{eq:densmu} \\\\\n  1 - p_1(y_i = 0) &= 1 -  \\l( \\frac{\\zeta}{\\zeta + \\exp(\\beta_0 + \\x^\\top_i \\bbeta)} \\r)^\\zeta \\label{eq:denstrunc} \n\\end{align} \n\nThe first density is the likelihood of observing a zero outcome, where $\\x_i$ is a length-$P$ vector of features for observation $i$, $\\balpha$ is the parameter vector for the binary component, $\\alpha_0$ is an intercept, and  $\\alpha_0 + \\x^\\top_i\\balpha$ is the linear predictor. \\\\\n\nThe second density is that of the standard negative binomial, where $\\bbeta$ is the parameter vector for the count component, $\\beta_0$ is an intercept for the count component, $\\zeta$ is the overdispersion parameter\\footnote{For completeness, we note the following properties of the negative binomial density: $\\E[y_i|\\x_i, \\bbeta] = \\exp(\\beta_0 + \\x^\\top_i\\bbeta + \\epsilon_i) = \\exp(\\beta_0 + \\x^\\top_i\\bbeta) \\exp(\\epsilon_i) = \\mu_i h_i$, where $h_i \\sim \\Gamma(\\zeta,\\zeta)$, \\; $\\E[h_i]= \\zeta/\\zeta = 1$, and $V[h_i]=1/\\zeta$. Thus, after conditioning on $\\zeta$, we obtain $\\E[y_i | \\x_i, \\bbeta, \\zeta] = \\mu_i$, as in the Poisson, and $Var[y_i | \\x_i, \\bbeta, \\zeta] = \\mu_i(1+\\mu_i/\\zeta)$, which tends to the Poisson's variance as $\\zeta \\rightarrow \\infty$.}, and $\\Gamma(\\cdot)$ is the gamma function.\\footnote{Note that $\\Gamma(n)=(n-1)!$, where $n$ is a positive integer.} The hurdle model allows us to specify each component as a function of different country features---say, $\\x_i$ for the binary component and $\\z_i$ for the count. This choice can be motivated from a substantive perspective; if theory dictates that different country features affect the likelihood of a country being a supplier (binary component), versus its likelihood of supplying a certain number of fighters conditional on being a supplier (truncated count component), including different features in each component is appropriate. However, given the nascent state of the literature on foreign fighters, we do not feel justified in making that choice, and assume that the same set of features ($\\x_i$) affects both likelihoods. Furthermore, because we allow for very flexible functional forms in both components and penalize complexity, including irrelevant variables will not cause overfitting or induce misspecification bias.\\footnote{Of course, if a feature truly has no relationship to one component of the model, including it will reduce the efficiency of our estimator. Knowing this a priori is very difficult and a benefit to regularized, flexible methods such as KRHNB is the ability to include many features and allowing the estimator to learn the appropriate features and functional form.}\t\\\\\n\nThe third density is simply the complement of the negative binomial density evaluated at zero. This term plays a crucial role in the hurdle model, since a zero count \\textit{cannot} arise from the count component, which is left-truncated at unity--hence the ``hurdle\". As such, in the formula for the density of a positive count we scale the binomial density by $1 - p_1(y_i = 0)$. This is the key difference between the hurdle and the zero-inflated model; the latter allows for zero counts to arise from \\textit{both} components.\\footnote{A case for using the hurdle is also made by \\cite{Porter2012}, but with respect to terrorism data.} We opt for the hurdle model not just because it is theoretically appropriate, as explained in Section \\ref{sec:hurdles}, but also because it is computationally more straightforward; the likelihood function is perfectly separable with respect to the two components and hence each parameter vector can be fit by independently maximizing the respective component.\\footnote{This is not the case with the zero-inflated model, whereby a mixing of zeros occurs under the two components. The computational advantage of the hurdle over the zero-inflated model becomes even larger when the \\textit{same} set of features is used in both components, as we do in our specification. This is because the mixing of zeros from the two components hinders identification of the two sets of coefficients for the features.} \t\\\\\n\nNow we can form the likelihood for observation $i$:\n\n\\begin{align}\n \\label{eq:likelihood}\n\\begin{split}\n  L_i(\\cdot) &= \\l[ p_0(y_i = 0) \\r]^{1 - d_i} \\l[ \\frac{p_1(y_i)}{1 - p_1(y_ i = 0)} (1 - p_0(y_i = 0)) \\r]^{d_i}\n  \\\\ d_i &= \\begin{cases}\n                               0 \\text{ if } y_i = 0 \\\\\n                               1 \\text{ if } y_i \\geq 1\n                             \\end{cases}\n\\end{split}\n\\end{align} \n\nWe use the densities in Equations~\\ref{eq:dens0}, \\ref{eq:densmu}, and \\ref{eq:denstrunc} to form the joint (sample) likelihood for $N$ observations. Taking the log, we arrive at the sample log-likelihood.\\footnote{See Appendix~\\ref{app:deriv} for the intermediate steps.} Where $\\btheta = (\\alpha_0, \\balpha^\\top, \\beta_0, \\bbeta^\\top, \\zeta)^\\top$ and $\\mathcal{D} = (\\Y, \\X)$,\n\n\\begin{align}\n  \\ell_N(\\btheta | \\mathcal{D}) &= \\begin{aligned}[t]\n    \\sum^N_{i=1} & - \\log \\l(1 + \\exp(\\alpha_0 + \\x^\\top_i \\balpha) \\r) +  d_i \\Bigg[ \\log \\Gamma( \\zeta + y_i ) + \\zeta \\log \\zeta \\\\\n    &- (\\zeta + y_i) \\log \\l( \\zeta + \\exp(\\beta_0 + \\x^\\top_i \\bbeta) \\r) + y_i(\\beta_0 + \\x^\\top_i \\bbeta) + (\\alpha_0 + \\x^\\top_i \\balpha) \\\\\n    & - \\log \\Gamma (1 + y_i) - \\log \\Gamma (\\zeta) - \\log \\l( 1 - \\l( \\frac{\\zeta}{\\zeta + \\exp(\\beta_0 + \\x^\\top_i \\bbeta)} \\r)^\\zeta \\r) \\Bigg]\n  \\end{aligned} \\label{eq:sampll}\n\\end{align} \n\nNote that $\\alpha_0$ and $\\beta_0$ are intercept terms. At this stage, we reparameterize the log-likelihood, by substituting the linear predictor functions $\\alpha_0 + \\x_i^\\top\\balpha$ and $\\beta_0 + \\x_i^\\top\\bbeta$ with $\\psi_0 + \\bphi(\\x_i)^\\top\\bpsi$ and $\\omega_0 + \\bphi(\\x_i)^\\top\\bomega$, respectively, functions linear in $\\bphi(\\x_i)^\\top$, a mapping of the features. That is, the feature space $\\X \\in \\mathbb{R}^P$ is expanded onto a higher-dimensional space $\\mathbb{R}^{P'}$, where $P<<P' $, and the parameter vectors $\\balpha, \\; \\bbeta \\in \\mathbb{R}^P$ are accordingly substituted with $\\bpsi, \\; \\bomega \\in \\mathbb{R}^{P'}$. Where $\\btheta_{\\bphi} = (\\psi_0, \\bpsi^\\top, \\omega_0, \\bomega^\\top, \\zeta)^\\top$ and $\\mathcal{D} = (\\Y, \\X)$,\n\n\\begin{align}\n\\label{eq:finalll}\n  \\ell_N(\\btheta_{\\bphi} | \\mathcal{D}) &= \\begin{aligned}[t]\n    \\sum^N_{i=1} & - \\log \\l(1 + \\exp(\\psi_0 + \\bphi(\\x_i)^\\top \\bpsi) \\r) +  d_i \\Bigg[ \\log \\Gamma( \\zeta + y_i ) + \\zeta \\log \\zeta \\\\\n    & - (\\zeta + y_i) \\log \\l( \\zeta + \\exp(\\omega_0 + \\bphi(\\x_i)^\\top \\bomega) \\r) + y_i(\\omega_0 + \\bphi(\\x_i)^\\top \\bomega) \\\\\n    & + (\\psi_0 + \\bphi(\\x_i)^\\top \\bpsi) - \\log \\Gamma (1 + y_i) - \\log \\Gamma (\\zeta) \\\\\n    & - \\log \\l( 1 - \\l( \\frac{\\zeta}{\\zeta + \\exp(\\omega_0 + \\bphi(\\x_i)^\\top \\bomega)} \\r)^\\zeta \\r) \\Bigg]\n  \\end{aligned}\n\\end{align} \n\nAgain, $\\psi_0$ and $\\omega_0$ are unregularized intercept terms; for example, $\\bpsi$ is defined as $\\bpsi = \\begin{bmatrix} \\psi_1 & \\psi_2 & \\dots \\end{bmatrix}^\\top$ and does not include $\\psi_0$. Next, we take the negative of the log-likelihood, Equation~\\ref{eq:finalll}, turning our exercise into a minimization problem. In addition, we add $||\\bpsi||^2$ and $||\\bomega||^2$, each of which is the square of the $L_2$ norm in our expanded feature space.\\footnote{The choice of the $L_2$ norm can be motivated from a Bayesian perspective. As in \\cite{Hainmueller2013}, it can be shown that the parameter estimates that maximize our target function---the penalized log-likelihood with an $L_2$ norm (Equation \\ref{eqn:target})---are the Maximum a Posteriori estimates of the hurdle negative binomial posterior, when a Normal prior is chosen for the parameters of the features. For a general treatment of the correspondence between Bayesian inference and regularization, see \\cite{Kimeldorf1970}.} These norms are multiplied by $\\lambda_\\psi, \\; \\lambda_\\omega \\in \\mathbb{R}^+$, tuning parameters that govern the tradeoff between fit and complexity for the coefficients on the features in each component. In sum, the norms and the regularization parameters are penalties that ensure that smoother functional forms are favored, thereby protecting against overfitting. The penalized log-likelihood arises as our target function:\n\n\\begin{align}\t\\label{eqn:target}\n  R_N (\\btheta_{\\bphi}, \\lambda_\\psi, \\lambda_\\omega | \\mathcal{D}) =\n    - \\ell_N(\\btheta_{\\bphi} | \\mathcal{D}) + \\lambda_\\psi ||\\bpsi||^2 + \\lambda_\\omega ||\\bomega||^2\n\\end{align} \n\nNext, we solve the First Order Condition (FOC) for each parameter vector, in order to demonstrate our use of Mercer's Theorem to reduce our problem from a potentially infinite-dimensional one to a tractable function. The details of this derivation can be found in Appendix~\\ref{app:deriv}. In both FOCs, many of the terms reduce to a scalar, which we can label $c^\\psi_i$ and $c^\\omega_i$. As such, we rewrite our FOC solutions for $\\bpsi$ and $\\bomega$ as:\\footnote{Alternatively, this can be directly shown by invoking the Representer Theorem \\citep{Kimeldorf1971}.}\n\n\\begin{align}\n  \\bpsi^* = \\sum^N_{i=1} c^\\psi_i \\bphi(\\x_i) \\\\\n  \\bomega^* = \\sum^N_{i=1} c^\\omega_i \\bphi(\\x_i) \n\\end{align} \n\nNow we substitute the solutions for $\\bpsi$ and $\\bomega$ back into the target function. Where $\\btheta_{\\bc} = (c^{\\psi}_0, {\\bc^\\psi}^\\top, c^{\\omega}_0, {\\bc^\\omega}^\\top, \\zeta)^\\top$ and $\\mathcal{D} = (\\Y, \\X)$,\n\\begin{equation}\n  R_N (\\btheta_{\\bc}, \\lambda_\\psi, \\lambda_\\omega | \\mathcal{D}) \\\\= \\begin{aligned}[t]\n    - \\sum^N_{i=1} & \\Bigg( - \\log \\l(1 + \\exp(c^\\psi_0 + \\bphi(\\x_i)^\\top \\sum^N_{j=1} c^\\psi_j \\bphi(\\x_j)) \\r) \\\\\n    & + d_i \\Bigg[ \\log \\Gamma( \\zeta + y_i ) + \\zeta \\log \\zeta - \\log \\Gamma (1 + y_i) - \\log \\Gamma (\\zeta) \\\\\n      & - (\\zeta + y_i) \\log \\l( \\zeta + \\exp(c^\\omega_0 + \\bphi(\\x_i)^\\top \\sum^N_{j=1} c^\\omega_j \\bphi(\\x_j)) \\r) \\\\\n      & + y_i\\l(c^\\omega_0 + \\bphi(\\x_i)^\\top \\sum^N_{j=1} c^\\psi_j \\bphi(\\x_j)\\r) + \\l(c^\\psi_0 + \\bphi(\\x_i)^\\top\\sum^N_{j=1} c^\\psi_j \\bphi(\\x_j) \\r)\\\\\n      & - \\log \\l( 1 - \\l( \\frac{\\zeta}{\\zeta + \\exp(c^\\omega_0 + \\bphi(\\x_i)^\\top \\sum^N_{j=1} c^\\omega_j \\bphi(\\x_j))} \\r)^\\zeta \\r) \\Bigg] \\Bigg) \\\\\n    & + \\lambda_\\psi \\langle \\sum^N_{i=1} c^\\psi_i \\bphi(\\x_i), \\sum^N_{i=1} c^\\psi_i \\bphi(\\x_i)\\rangle + \\lambda_\\omega \\langle \\sum^N_{i=1} c^\\omega_i \\bphi(\\x_i), \\sum^N_{i=1} c^\\omega_i \\bphi(\\x_i)\\rangle\n    \\end{aligned}\n\\end{equation} \n\nNoting that $\\sum^N_{j=1} c^m_j \\bphi(\\x_i)^\\top \\bphi(\\x_j) = \\sum^N_{j=1} c^m_j \\langle\\langle \\bphi(\\x_i), \\bphi(\\x_j) \\rangle\\rangle \\; , \\; m \\in \\{\\psi,\\omega\\}$, it becomes obvious that the expanded features enter our target function only as inner products. Mercer's Theorem, allows us to replace these inner products with any positive semi-definite kernel, $k(\\x_i,\\x_j)$.\\footnote{That is, Mercer's Theorem holds that, for any positive semi-definite kernel $k(\\cdot,\\cdot)$, there exists a mapping $\\bphi(\\cdot)$ that projects $\\x_i$ into a higher-dimensional vector $\\bphi(\\x_i)$ such that $ k(\\x_i,\\x_j)=\\langle \\bphi(\\x_i), \\bphi(\\x_j) \\rangle \\; , \\; \\forall i, \\; j$. Hence, this is also known as the ``kernel trick\", or kernel substitution.} Crucially, this means that we do not actually have to expand our features onto the higher-dimensional space that they are allowed to span via $\\bphi(\\cdot)$, but merely pass them through kernels. Although any positive semi-definite kernel suffices for performing kernel substitution, we opt for the Gaussian, due to its well-known properties.\\footnote{For any two data points $\\x_i, \\; \\x_j \\in \\mathbb{R}^P$, the Gaussian kernel-based distance is $k(\\x_i,\\x_j) = \\exp \\l( -\\frac{||\\x_i-\\x_j||^2}{\\sigma^2} \\r)$, where $\\sigma^2$ is the kernel bandwidth. We follow \\cite{Hainmueller2013} in setting $\\sigma^2 = P$, where $P$ is the number of features. This provides good performance and allows for differentiation among observations. For a review of kernel-based machine learning methods, see \\cite{Scholkopf2002}. For a critique of the use of Gaussian kernels in KRLS with small samples, see \\cite{Braga2015}.} Namely, $\\bphi(\\cdot)$ will be infinite-dimensional. A way to think about this infinite-dimensional vector is to imagine that it contains all possible combinations and functions of the original features. For example, it contains $\\x^{(1)}$, $\\x^{(1)} \\x^{(2)}$, $\\sqrt(|\\x^{(3)}|)$, $\\mathbf{1}\\{(\\x^{(1)} > 0)\\}$ and so on and so forth, where $\\x^{(j)}$ is the $j$th feature.\t\\\\\n\nThus, letting $\\bc^m = \\begin{bmatrix} c^m_1 & c^m_2 & \\dots & c^m_N\\end{bmatrix}$ where $N$ is the number of observations and $m$ represents either the first or second components, $\\psi$ or $\\omega$, letting $\\K$ be the kernel matrix of our sample, and letting $\\k_i$ be the $i$th column of $\\K$, we can rewrite our target function as:\n\n\\begin{align}\t\\label{eqn:targetFinal}\n  R_N (\\btheta_{\\bc}, \\lambda_\\psi, \\lambda_\\omega | \\Y, \\K) &= \\begin{aligned}[t]\n    - \\sum^N_{i=1} & \\Bigg( - \\log \\l(1 + \\exp({c^\\psi_0 + \\bc^\\psi}^\\top \\k_i) \\r) +  d_i \\Bigg[ \\log \\Gamma( \\zeta + y_i ) + \\zeta \\log \\zeta \\\\\n      & - (\\zeta + y_i) \\log \\l( \\zeta + \\exp({c^\\omega_0 + \\bc^\\omega}^\\top \\k_i) \\r) + y_i (c^\\omega_0 + {\\bc^\\omega}^\\top\\k_i) \\\\\n      & + (c^\\psi_0 + {\\bc^\\psi}^\\top \\k_i) - \\log \\Gamma (1 + y_i) - \\log \\Gamma (\\zeta) \\\\\n      & - \\log \\l( 1 - \\l( \\frac{\\zeta}{\\zeta + \\exp({\\bc^\\omega}^\\top \\k_i)} \\r)^\\zeta \\r) \\Bigg] \\Bigg) \\\\\n      & + \\lambda_\\psi {\\bc^\\psi}^\\top \\K \\bc^\\psi + \\lambda_\\omega {\\bc^\\omega}^\\top \\K \\bc^\\omega\n    \\end{aligned}\n\\end{align} \n\nThe resulting optimization problem does not have a closed-form solution. Therefore, we minimize the above with respect to $\\{ c^\\psi_0, \\bc^\\psi, c^\\omega_0, \\bc^\\omega, \\; \\zeta \\}$ through numerical optimization.\t\\\\ \n\nTo summarize, we receive estimates for $\\bc^\\psi$ and $\\bc^\\omega$, which act as a kind of weight for each observation $i$ in the two CEFs (describing the mean of the hurdle and the truncated count components, respectively). For example, our estimate of the probability of sending no foreign fighters, the probability in the logit component, is estimated as $$p_0(y_i = 0) = \\frac{1}{1 + \\exp(\\hat{c^\\psi_0} + {\\hat{\\bc^\\psi}}^\\top \\k_i)}$$\n\nAs a result, directly interpreting the estimated coefficients $\\hat{\\bc^\\psi}$ and $\\hat{\\bc^\\omega}$ can be very difficult for two reasons: they influence the outcome through non-linear transformations like the logistic function and are acting on $\\k_i$ instead of $\\x_i$, our features of interest. Therefore, in Section~\\ref{sec:pwmfx} we take the partial derivatives of the CEF for the outcome $y_i$ with respect to our columns of $\\X$ so that we can interpret our results using our input features.\n\n%=========================================================\n\\section{Computation \\& Quantities of Interest}\t\\label{sec:computation}\n\n%=======================\n\\subsection{Optimization}\t \n\t\nThere are three main difficulties with fitting this model. First, there is minor sensitivity to starting values in the numerical optimization. Using the BFGS algorithm limits this problem dramatically, and the sensitivity only arises when using implausible starting values.\\footnote{Implausible here means uniformly positive or negative starting values. They are implausible because the data have been scaled, thus the coefficients will generally be distributed around $0$.} However, this sensitivity could be guarded against by doing a grid search over some set of starting values. \\\\\n\nThis solution is difficult to implement because of the second problem with fitting this model numerically---speed. While we supply the analytic gradient of our target function to the BFGS algorithm, these functions are quite complicated and high-dimensional. We numerically optimize with starting values for all coefficients $\\bc = \\mathbf{0}$ and $\\zeta = 1$. From some rudimentary grid searches, this starting value has succeeded in finding the best minimum using our data and makes intuitive sense; setting $\\bc = \\mathbf{0}$ means our initial estimate of the CEF is simply the sample average over the entire feature space.\\footnote{In some instances, the algorithm gets stuck in local minima. In particular, it sometimes estimates $\\zeta < 0.0001$, which results in estimates of $y_i$ that are too large by $3$ or $4$ orders of magnitude. However, because the performance is so poor, it fails to find a way to improve it. For now, we forcibly prevent $\\zeta$ from reaching such implausibly small numbers to avoid this shortcoming of the BFGS algorithm.}\t\\\\\n\nThird, selecting the appropriate regularization parameters ($\\lambda_\\psi$, $\\lambda_\\omega$) can be difficult, as there are two parameters. (This also slows-down optimization.) The traditional approach is to use cross-validation (CV) \\citep{Stone1974} to select parameters that minimize the cross-validation RMSE \\citep{Friedman2001}. We advocate and implement in our software $k$-fold cross validation and a grid search over the two regularization parameters. For the application to foreign fighter supply, we select regularization parameters after several manual grid searches.\n\n%=======================\n\\subsection{Pointwise Marginal Effects}\n\\label{sec:pwmfx}\nThe CEF for test observation $i$ is:\n\n\\begin{align}\n  \\E[y_i|\\k_i] &= p_0(y_i=0)*0 + (1-p_0(y_i=0))*\\E[\\hat{Y}_i | \\hat{Y}_i > 0] \\notag \\\\\n  & =  ( 1-p_0(y_i=0) ) \\frac{\\mu_i}{1-p_1(y_i=0)} \\notag \\\\\n  \\widehat{\\E[y_i|\\k_i]} &= \\frac{\\exp(\\hat{c^\\psi_0} + \\hat{\\bc^\\psi}^\\top \\k_i)}{1 + \\exp(\\hat{c^\\psi_0} + \\hat{\\bc^\\psi}^\\top \\k_i)} \\frac{\\exp(\\hat{c^\\omega}_0 + \\hat{\\bc^\\omega}^\\top \\k_i)}{\\l( 1 - \\l( \\frac{\\hat{\\zeta}}{\\hat{\\zeta} + \\exp(\\hat{c^\\omega_0} + \\hat{\\bc^\\omega}^\\top \\k_i)} \\r)^{\\hat{\\zeta}} \\r)}\n\\end{align} \n\nwhere $\\mu_i$ is the mean component of the negative binomial distribution, and $\\{c^m_0, \\hat{\\bc^m}\\}, \\; m \\in \\{\\psi,\\omega\\}$ are the intercepts and coefficient vectors along with $\\hat{\\zeta}$ that minimize our target function (Equation~\\ref{eqn:targetFinal}).\t\\\\\n\nUsing this formula, we obtain a quantity of interest analogous to marginal effects in GLMs. We use numerical differentiation to take the partial derivative of $\\widehat{\\E[y_i|\\k_i]}$ with respect to each feature $\\x^{(j)}$ and evaluate it at each observation.\\footnote{Remember that $\\k_i$ is a function of the input features.} Because our CEF is non-linear, these pointwise marginal effects will vary over the feature space and provide rich detail about the shape of the CEF. Indeed, wherever an observation lives in the feature space, we will have an estimate of the slope of the CEF with respect to each feature.  \\\\\n\nThis allows for us to summarize average effects and estimate heterogeneous treatment effects. For example, we can display the range of pointwise marginal effects across the training values of $\\x^{(j)}$ for feature $j$ as a histogram (see Section \\ref{sec:results}).  Alternatively, one can focus on the mean of this distribution, the sample-average pointwise marginal effect of $\\x^{(j)}$, which would be analogous to the marginal effect produced by a linear model. Yet another alternative is to report the pointwise marginal effect for the ``typical\" training point---an observation with mean/median/modal values of the features. This approach is subject to the usual limitations.\\footnote{See \\cite{Gelman2006} for different approaches to summarizing predictive effects.} Our companion software allows the user to choose the effects reported. \t\\\\  \n\n%=======================\n\\subsection{Estimating Uncertainty of Sample-Average Pointwise Marginal Effects}\t\n\nAs noted in Section \\ref{sec:krhnb}, there is no closed-form solution to our optimization problem (Equation \\ref{eqn:targetFinal}). Consequently, obtaining an analytical estimate of the uncertainty of our predictions is not straightforward and we opt for a computational one.\\footnote{For one analytical approach in the context of a penalized zero-inflated negative binomial, see \\cite{Wang2014}. It is based on the sandwich estimator, whose consistency when applied to non-concave penalized likelihood problems was demonstrated in \\cite{Fan2001}.} Namely, we obtain non-parametric bootstrapped estimates of our pointwise marginal effects \\citep{Efron1979}.\\footnote{\\cite{Kenkel2013} also follow a bootstrapping approach to obtain a measure of uncertainty for their pointwise marginal effects. For an application and extension of the bootstrap to the zero-inflated negative binomial, see \\cite{Garay2011}.} This involves treating our training set as the population and repeatedly resampling from it (with replacement) to calculate sample-average pointwise marginal effects. Crucially, we hold the regularization parameters fixed across the resampled training sets and only re-fit the remaining parameters ($\\bc$ and $\\zeta$). This economizes greatly on computational time, as we do not have to execute the full optimization routine on every bootstrapped sample. However, it will result in smaller estimates of uncertainty as the variability in the regularization parameter is not incorporated \\citep{Tibshirani1996}. The resulting estimates provide a distribution of marginal effects, which can be graphed as a histogram, or summarized numerically to create a bootstrapped percentile interval.\\footnote{Our companion software provides a range of summary statistics for the bootstrapped estimates of these effects.}\n\n%=========================================================\n\\section{Performance Relative to Other Models}\t\\label{sec:comparison}\n\nBeyond getting purchase on the causes of foreign fighter supply, we are also interested in benchmarking the performance of our method against other machine learning techniques. In order to do this, we take a leave-one-out cross-validation approach: we train our method and four competing methods on all but one observation and then predict the foreign fighter supply to the withheld observation, repeating this for every observation. We take these out-of-sample predictions for each observation and their true values and calculate the root mean squared (RMSPE) and mean absolute prediction error (MAPE) of our estimated outcomes. The first method we benchmark against is KRLS. The rationale behind this choice is simple: if we cannot perform similarly or better to the method we are adding complexity to, then there is no reason for this extension beyond the ability to interpret the two components of the hurdle model. The second method is KRLS with predicted values truncated at $0$, which will uniformly improve the performance of KRLS, but will completely impair its interpretability. The third method is a random forest \\citep{Breiman2001} with $500$ trees, and the number of parameters available at each node set to $5$ -- roughly the square root of the total number of features ($27$). The last method is standard OLS, where the predictors enter as a simple linear function. \\\\\n\n\n\\begin{table}[!h] \\centering \n\t\\caption{Comparing Prediction Error} \n\t\\label{tab:compare} \n\t\\begin{tabular}{ll rr}\n\t\t\\\\ [-1.9ex]\n\t\t\\toprule\n\t\tData & Method & \\multicolumn{1}{c}{CV RMSPE} & \\multicolumn{1}{c}{CV MAPE} \\\\\n\t\t\\midrule\n\t\tForeign Fighters & KRHNB & 282.52 & \\textbf{107.91} \\\\\n\t\t& KRLS & 288.28 & 141.59 \\\\\n\t\t& KRLS (0-truncated) & 285.36 & 129.79 \\\\\n\t\t& Random Forest & \\textbf{278.08} & 131.60 \\\\\n\t\t& OLS & 299.88 & 182.86 \\\\\n\t\t\\midrule\n\t\t{\\bf \\cite{Burgoon2006}} & KRHNB & 5.81 & \\textbf{2.67} \\\\\n\t\t& KRLS & 5.71 & 2.72 \\\\\n\t\t& KRLS (0-truncated) & 5.71 & 2.71 \\\\\n\t\t& Random Forest & \\textbf{5.60} & 2.68 \\\\\n\t\t& OLS & 6.49 & 2.94 \\\\\n\t\t\\bottomrule\n\t\\end{tabular}\n\t\\begin{flushleft} \\footnotesize \\textit{Notes}: Bold denotes the lowest prediction error. We use leave-one-out CV error for the foreign fighters dataset and 5-fold CV error for the Burgoon dataset, as it is much larger. Therefore, while the prediction errors for the Foreign Fighters dataset are fixed, the 5-fold CV error for the Burgoon data might vary depending on how the folds are constructed. Other results produce the same rankings. \\end{flushleft}\n\\end{table}\n\nThe results of this leave-one-out cross-validation approach are presented in the upper half of Table~\\ref{tab:compare}. KRHNB beats all other methods using MAPE and loses only to random forest on RMSPE. The source for this discrepancy can be seen easily if all of the predicted outcomes are plotted against the observed outcomes. Figure~\\ref{fig:predictions} plots the observed number of foreign fighters on the $x$-axis, and the predicted number on the $y$-axis. The key advantage that random forest has over KRHNB is that it far outperforms it when predicting the largest value, Tunisia. However, all of these methods struggle to predict countries with high levels of foreign fighter supply, presumably because the predictors that explain the difference between supplying $200$ and $2,000$ fighters are not in our data. KRHNB performs well with respect to MAPE, because for values of $y$ between $0$ and $200$, KRHNB does quite well, while KRLS and Random Forests are more likely to predict values that are too large. This can be seen more clearly when we zoom in to the predictions for outcomes less than $150$ -- the right panel of Figure~\\ref{fig:predictions}. \t\\\\\n\nTherefore, KRHNB is good at predicting whether there are any supplied foreign fighters. This means the first component is making good predictions, while the second component has little power, and most values are predicted near the mean. MAPE is much larger for random forest than KRHNB, which exhibits better fit at lower levels of foreign fighter supply. Thus, it appears that the added structure in the form of the hurdle improves fit over models that do not assume much structure, such as KRLS or random forests. However, that lack of structure does allow some improved prediction for high levels of foreign fighter supply. Nonetheless, all these methods do quite poorly in the tail of the data, indicating a lack of explanatory power for many variables, or the fundamental unpredictability that describes observations living in tails of distributions. \\\\\n\nAs an additional evaluation of our method, we replicate \\cite{Burgoon2006}, who uses a zero-inflated negative binomial model to predict cross-national time variation in terrorist attacks. As shown in the lower half of Table~\\ref{tab:compare}, we observe a similar pattern of performance on this data; KRHNB minimizes MAPE, but performs worse on RMPSE. \\\\\n\n\\begin{figure}[!htb]\n\t\\centering\n\t\\includegraphics[width=0.95\\linewidth]{tabs_figs/predictJoin.pdf}\n\t\\caption{Leave-one-out CV Predictions}\t\\label{fig:predictions} \n\t\\begin{flushleft} \\footnotesize \\textit{Notes}: Black line is where perfect predictions would lie ($Y = \\hat{Y}$). The left panel is the full dataset, while the right panel zooms in to where $Y < 150$. The values of $Y$ are jittered because of the clustering at 0. \\end{flushleft}\n\\end{figure}\n\n%=========================================================\n\\section{Results \\& Discussion}\t\\label{sec:results} \t\n\n\\subsection{Data}\n\nTo uncover predictors of foreign fighter supply, we build a design matrix of $27$ geographic, demographic, economic, and political variables for $163$ countries. All of these features have been measured prior to 2014, although issues of endogeneity are beyond the scope of this paper. Furthermore, there is some (though very little) missingness, because we aggregate over several years (where applicable) to get as complete a dataset as possible. There is some remaining missingness, which we address by taking the mean over $1,000$ datasets, imputed using Amelia II \\citep{Honaker2011}.\\footnote{This algorithm relies on the assumption that the data are missing at random, which is almost certainly invalid. However, no feature has more than $4$ missing observations, save for the measure of how many refugees are in a country (missing $10$ observations). Furthermore, only 0.7\\% of the data are missing.} In the Appendix Table~\\ref{tab:appeffectslist}, we report full results with list-wise deletion, leaving us with $147$ observations. The results are largely the same.\t\t\\\\\n\n\\begin{table}[!h]\n\t\\footnotesize\n\t\\centering\n\t\\caption{Description of Features} \t\\label{tab:data}\n\\begin{tabular}{lrrrrrl}\n\t\\\\ [-1.9ex] \\toprule\n\t& Mean & Std. Dev. & Min. & Median & Max. & Source\\\\ \n\t\\midrule\n\tForeign Fighter Supply & 114.08 & 332.34 & 0.00 & 0.00 & 2250.00 & ICSR \\citep{Neumann2015}\\\\ \n\tContiguous & 0.04 & 0.20 & 0.00 & 0.00 & 1.00 & CEPII \\\\ \n\tEurope & 0.21 & 0.41 & 0.00 & 0.00 & 1.00 & Hand Coded\\\\ \n\tDistance (km) & 5251.69 & 3743.59 & 85.94 & 4363.00 & 15630.00 & CEPII \\\\ \n\tLog Population & 16.23 & 1.51 & 13.20 & 16.15 & 21.03 & World Bank WDI \\\\ \n\tLog Pop. Density & 4.19 & 1.40 & 0.60 & 4.30 & 8.95 & World Bank WDI\\\\ \n\tYouth Bulge (15-24 pct) & 17.06 & 3.68 & 9.60 & 18.10 & 23.10 & World Bank WDI \\\\ \n\tSunni Pct & 25.45 & 35.33 & 0.07 & 5.07 & 99.40 & Pew \\\\ \n\tShia Pct & 2.61 & 10.82 & 0.00 & 0.06 & 92.22 & Pew \\\\ \n\tReligious Frac. & 0.43 & 0.24 & 0.00 & 0.44 & 0.86 & \\cite{Fearon2003a} \\\\ \n\tGovt. Reg. Religion & 2.78 & 3.24 & 0.00 & 1.39 & 10.00 & ARDA \\\\ \n\tGovt. Fav. Religion & 4.50 & 3.18 & 0.00 & 4.73 &  10.00 & ARDA \\\\ \n\tSoc. Reg. Religion & 4.22 & 3.58 & 0.00 & 3.67 & 10.00 & Freedom House \\\\ \n\tFreedom House Pol. Rights & 3.63 & 2.11 & 1.00 & 3.00 & 7.00 & Freedom House  \\\\ \n\tMigrants as Pct of Pop & 7.87 & 12.06 & 0.05 & 2.94 & 74.61 & World Bank WDI\\\\ \n\tLog Refugees in Country & 8.50 & 3.04 & 0.00 & 8.85 & 14.30 & UNHCR \\\\ \n\tLog Refugees from Country & 7.35 & 2.92 & 0.00 & 7.18 & 14.75 & World Bank WDI \\\\ \n\tLog GDP pc, PPP & 9.10 & 1.24 & 6.37 & 9.26 & 11.76 & World Bank WDI \\\\ \n\tLife Expectancy & 69.89 & 9.48 & 45.55 & 72.27 & 83.83 & World Bank WDI\\\\ \n\tMale LFP & 79.42 & 7.03 & 48.40 & 79.80 & 95.90 & World Bank WDI \\\\ \n\tYouth Unemployment & 18.33 & 12.58 & 0.70 & 14.80 & 60.40 & World Bank WDI \\\\ \n\tInternet User per 100 & 40.01 & 29.46 & 0.00 & 39.20 & 95.05 & World Bank WDI \\\\ \n\tLog Homicides Per 100k & 1.46 & 1.20 & -1.61 & 1.57 & 4.50 & World Bank WDI \\\\ \n\t\\bottomrule\n\\end{tabular}\n\\begin{flushleft} \\footnotesize \\textit{Notes:} CEPII is the Centre d'\\'{E}tudes Prospectives et d'Informations Internationales \\citep{Mayer2011}. ARDA is the Association of Religion Data Archives \\citep{Finke2010}. The Pew data can be found at in a report by \\cite{Grim2012}. The Freedom House data are from \\cite{Teorell2013}. The UNHCR data can be found at \\href{http://popstats.unhcr.org/en/time\\_series}{http://popstats.unhcr.org/en/time\\_series} and are different from the World Bank summary of refugees in asylum because we exclude internally displaced persons. \\end{flushleft}\n\\end{table}\n\n\nThe full list of features can be found in Table~\\ref{tab:data}. We have data for all $163$ countries\\footnote{We exclude Macao and Puerto Rico as well. They had high rates of missingness due to many organizations not collecting data on these polities.} with populations above $500,000$ except for Syria and Iraq, where our outcome is not measured. Foreign fighter data come from the ICSR Report of 1/25/2015 \\citep{Neumann2015}, which estimates the number of all foreign fighters through the end of 2014. The estimates are either a single value, or a range. If there is a range, we take its mean, and round to the nearest integer.\\footnote{ICSR also lack data from the West Bank and Gaza. In the interest of maximizing our sample size, we split the count for Israel and assign half of those sent from Israel to the West Bank and Gaza. Table~\\ref{tab:appeffectslist} presents the results were we instead drop the West Bank and Gaza from our analysis, as well as other countries that have missingness. The results are substantively similar.} \\\\\n\n\\subsection{Main Results}\n\nWe fit KRHNB on the full data set, with $\\lambda_{\\psi}$ and $\\lambda_{\\omega}$ selected by a grid-search using leave-one-out cross validation. We use the Gaussian kernel to transform our data so that we are essentially working in an infinite-dimensional expansion of the design matrix and thus considering an infinite variety of complex functional forms. Following this optimization, we analyze the marginal effects of each feature on country-level foreign fighter supply in two ways. The first way is presented in Figure~\\ref{fig:booteffects}, which contains the sample-average marginal effect and bootstrapped confidence intervals, for both the binary and count components, as well as the two components jointly. Note that the confidence intervals are constructed using the empirical 2.5th percentile and 97.5th percentile of the bootstrapped distribution of marginal effects.\\footnote{This is sometimes known as the percentile interval, or the percentile bootstrap.} The exact results and confidence intervals for the sample-average marginal effects are presented in Table~\\ref{tab:appeffects} of the Appendix. The bootstrapped intervals are skewed away from 0 for many sample-average marginal effects in the foreign fighters application, indicating that several outliers and the complex target function may prevent the bootstrapped percentile interval from achieving nominal coverage. \\\\\n\n\\afterpage{\n\\begin{landscape}\n\\begin{figure} [!p]\n\t\\centering\n\t\\includegraphics[scale=0.9]{tabs_figs/bootEffects.pdf}\n\t\\caption{Sample-Average Pointwise Marginal Effects}\t\t\\label{fig:booteffects} \n\t\\begin{flushleft}\n\t\\footnotesize \\textit{Notes}: Pointwise marginal effects are computed numerically. All continuous features are scaled to have standard deviation of one. Dichotomous variables for Europe and Contiguous are not pointwise marginal effects, but first differences between the two values. Higher Freedom House scores indicate ``less freedom\". The outcome variable is foreign fighter supply for the first column, the probability of sending any fighters in the hurdle logit component in the second column, and the mean of the truncated negative binomial component in the third column. As a result, note that the scaling of the $x$ axes varies. \\end{flushleft}\n\\end{figure}\n\\end{landscape}\n}\n\nThe leftmost panel of Figure~\\ref{fig:booteffects} contains the estimated sample-average pointwise marginal effects for the combined model. Consistent with our usage throughout the paper, effects here mean the marginal effects our model produces, not causal effects. Furthermore, our features are scaled to have standard deviation of one so effects can be interpreted in standardized units. Most effects are near zero, showing that there is little predictive power for many of the features. Nonetheless, the bootstrapped 95 percentile intervals around seven of the features do not include 0. \\\\\n\nSubstantively, it appears that the two strongest predictors are population, and the percent of the country's population that is Sunni.\\footnote{The point estimate for contiguity is quite large, although the low number of foreign fighters from Iran, a contiguous state to Iraq, is a source of the large heterogeneity in these marginal effects.} The effect of population is not surprising, as a positive (unconditional) probability of any individual becoming a foreign fighter implies that larger countries should have a higher supply. Similarly, Sunni population share intuitively predicts participation in the conflict, as it captures the strength of identification with the opposition; virtually all groups fighting the Assad regime are Sunni. Thus, more Sunnis in a given country means that more people feel they have a steak in the conflict and recruiters can more easily manipulate the salience of Sunnis' religious identity to construct a sense of obligation to fight. Also unsurprising is the strong negative effect of distance to the conflict; increased travel costs should deter potential fighters at the margin, while dissociation from the conflict should increase with distance. Another noteworthy effect is that on life expectancy, which positively predicts foreign fighter supply. Although this seems troubling, it is in line with popular conceptions of supplier countries as developed, as well as the findings of \\cite{Hewitt2009} that more developed countries supplied more foreign fighters during Iraq's insurgency. Also consistent with conventional wisdom is the positive effect of internet usage; foreign fighters can be recruited online \\citep{Hegghammer2011}, thus countries with deeper internet penetration allow recruiters to cast their net more widely. There also is a positive relationship between government regulation of religion and foreign fighter supply, something we discuss further below. Finally, a puzzling finding is the positive effect of refugee presence. Below we show that this effect originates in European countries, hence we defer its interpretation for now. \t\t \\\\\n\nMore can be learned by disaggregating the effects into the hurdle and count components of our model. The central panel of Figure~\\ref{fig:booteffects} contains the estimated sample-average pointwise marginal effects of standardized variables in the hurdle component. These effects can be interpreted as changes in the probability that a country passes the hurdle of no supply and sends some foreign fighters. The results are quite similar to the left panel, indicating that our features are better at predicting whether or not any foreign fighters are supplied (binary component), rather than how many are supplied (count component). Six of the seven predictors that are distinguishable from zero in the combined model remain so here, and their ranking in terms of substantive significance is also similar. Sunni population share, population, and refugee presence are still the three strongest predictors, again followed by internet penetration, distance to the conflict, and life expectancy. Government regulation of religion is not distinguishable from zero in this component. In addition, there are two new results worth noting. First, GDP per capita has a positive effect. This is consistent with the positive effect of life expectancy, popular conceptions regarding foreign fighters as originating in the developed world, and prior findings on Iraq \\citep{Hewitt2009}. Second, migrant population share also has a positive effect. Yet, we hesitate to interpret this, as the effect is reversed in the count component. \t\\\\\n\nThe rightmost panel contains the estimated sample-average pointwise marginal effects of standardized variables in the count component. Only five features are clearly driving prediction of the count of foreign fighter supply. As in the combined model and hurdle component, population and Sunni population share have a positive effect distinguishable from zero. However, in contrast to the hurdle component, the effect of migrant population share is negative. Clearly, the opposite direction of the migrant effect in the two components accounts for its null effect in the combined model. Another difference from previous results is that government regulation of religion and government favoritism of religion are positive predictors.\\footnote{These indices reflect how much the government respects freedom of religion, and whether it funds and supports one religion in particular \\citep{Grim2006}.} This means that, among supplier countries, those that do not respect freedom of religion and/or fund a particular religion send more foreign fighters. Further inspection of these effects reveals that they are due to Sunni-majority countries, hence we interpret them later.\t\\\\\n\n\\subsection{Effect Heterogeneity}\n\nOur method allows for a rich exploration of marginal effect heterogeneity, by providing pointwise estimates of marginal effects for each feature. To demonstrate some of KRHNB's strength in learning from the data, Figure~\\ref{fig:histeffects} plots the distribution of pointwise marginal effects for four features. Most of the effects are near zero, indicating that much of the estimated CEF is flat across the support of the features. However, a clear difference can be seen between a feature that appears to have little to no relationship to foreign fighter supply (homicides, bottom left), and one that has a systematic relationship (Sunni population share, bottom right). Heterogeneity in the pointwise marginal effects can itself provide a lot of information about certain features of interest. Furthermore, by plotting or regressing the pointwise marginal effects on the features, we can see whether there appear to be interaction effects, or non-linear relationships \\citep{Hainmueller2013}. \\\\\n\n\\begin{figure}[!h]\n\t\\centering\n\t\\includegraphics[scale=.85]{tabs_figs/histeffects.pdf}\n\t\\caption{Distribution of Pointwise Marginal Effects}\t\\label{fig:histeffects} \n\\end{figure}\n\nIn Figure~\\ref{fig:hetplot1}, we demonstrate how the pointwise marginal effects differ for countries within and outside of Europe. While internet usage has uniformly positive effects in Europe, in the rest of the world its marginal effect is clustered around zero. This could suggest that radicalization and recruiting happens mostly online in European countries, but through non-digital means in other countries (e.g. personal networks, mosques). The plot can also shed light on the puzzling result on refugee presence, as it suggests that refugee presence is associated with larger foreign fighter supply only in Western countries. A possible interpretation is that refugees' predicament -- persecution, poverty, loss of family members -- exacerbates feelings of injustice among citizens of the host country that are already at high risk of becoming foreign fighters (e.g. young Sunni unemployed males in urban centers).\\footnote{We believe it is unlikely that the positive effect of refugee presence means that refugees are more likely to fight in Syria, since there is no anecdotal evidence of refugees from Western countries becoming foreign fighters. We also note that our refugee measure predates the large influx of refugees from Syria into Europe; this rules-out the explanation that Syrians are seeking refuge in Europe, only to return to Syria as fighters.} The latter might view their participation in the Syrian conflict as a chance to address the conditions that resulted in refugees' predicament. Radicalization might be especially strong for citizens of the host country with a shared religion or ethnicity with the refugees, the more so if the refugees fled countries with similar conditions to those that sparked the Syrian conflict. This applies to refugees from a number of countries that repressed Islam(ists) -- for example, Algeria, Bosnia, Egypt, Iraq, Libya, Russia, and Tunisia  -- much like the Assad regime did in Syria.\t \\\\\n\n\\begin{figure}[!h]\n\t\\centering\n\t\\includegraphics[scale=.85]{tabs_figs/hetplot1.pdf}\n\t\\caption{Effects Inside and Outside Europe}\t\\label{fig:hetplot1} \n\\end{figure}\n\nThis discussion provides an opportunity to return to the effect of government regulation of religion. As previewed above, intervention in religious affairs has a positive effect on foreign fighter supply in the model's count component. Figure~\\ref{fig:hetplot2} reveals an interesting heterogeneity in this effect, by plotting the pointwise marginal effect of government regulation of religion by countries' Sunni population share with a simple LOWESS smoother.\\footnote{To see the full picture of possible interaction effects, see Appendix~\\ref{fig:interactplot} which presents an overview of heterogeneous effects.} As the Sunni share of the population increases the effect of government regulation of religion becomes stronger and more precise. That is, only in Sunni-majority supplier countries does religious intervention consistently predict a larger supply of foreign fighters. Given that virtually all foreign fighters are Sunni, this is consistent with a view of illiberal religious policies as radicalizing the population in Sunni-majority countries. This radicalization, in turn, might map onto foreign fighter supply through two possible mechanisms. One is that repressing (Sunni) Islam in countries where it is popular can create deep-seated grievances. Since the Assad regime also fought Islam, repressed Sunnis from the Muslim world might see Syria as a battleground for addressing their grievances. This could be the case in Tunisia, an overwhelmingly Sunni country that repressed Islamists until 2011, and has by far the largest per capita supply of foreign fighters. The second mechanism is that government repression of some religions or sects to benefit the official state religion might lead to exporting this attitude abroad. Thus, Sunnis from countries that enforce the dominance of Sunni Islam might consider it their duty to defend that religion wherever it is threatened, as in Syria. This could be the case of Saudi Arabia, which was founded on the radical Wahhabi (Sunni) interpretation of Islam, and has the second largest supply of foreign fighters.\t\\\\\n\nThese possible explanations are raised by our model because it is able to uncover non-linear and interactive relationships without relying on the a priori specification of complex functional forms and without overfitting. Therefore, our model provides fodder for future work that should causally identify the mechanisms that may lead from government intervention in religion to the generation of foreign fighters.\t \\\\\n\n\\begin{figure}[!h]\n\t\\centering\n\t\\includegraphics[scale=.85]{tabs_figs/hetplotGovtRegSunni.pdf}\n\t\\caption{Effects of Government Regulation of Religion by Sunni Population Share}\t\\label{fig:hetplot2} \n\\end{figure}\n\nOverall, it seems that, while structural features dominate the hurdle component (distance, population, Sunni population share, life expectancy, GDP), policy variables mostly drive variation in the count component (government regulation of religion, government favoritism of a religion, migrant population share). Therefore, a tentative conclusion is that policy-makers cannot do much to prevent a foreign fighter network from emerging in their country, but, once it emerges, they can affect its size. Nevertheless, inspecting the effect of our features on the combined model, it is clear that structural features dominate in explaining foreign fighter supply, thereby limiting room for policy intervention.\n\n%=========================================================\n\\section{Conclusion}\t\\label{sec:conclusion}\n\n``The best way to reduce a foreign fighter returnee problem is to never have them go in the first place\" \\citep[p. 15]{Byman2015a}. Our analysis helps identify country features that are associated with higher foreign fighter supply. Substantively, our results suggest that countries' structural features play a larger role in shaping supply than their policies --- four of the strongest and most accurate predictors of supply are population, the share of the population that is Sunni, distance to Syria, and life expectancy. Some of these features cannot be altered by policy-makers, while others can, albeit at a slow pace and high cost. Moreover, with the exception of internet usage, all of the features that do respond to government policies -- refugee intake, regulation of religion, and favoritism of a particular religion -- are central to some countries' political culture. For example, French voters consistently prefer liberal policies towards refugees, while most Saudi citizens are likely to value state protection of Sunni Islam, and regulation of other religions. Therefore, policy-makers in such countries will hesitate to change these policies, unless the cost of doing so is less than that imposed by their foreign fighter supply. This might be unlikely, even for countries facing a high supply, like France and Saudi Arabia. In short, to the extent that our research design allows us to offer any policy recommendations, it is unclear whether policy-makers can feasibly curtail foreign fighter supply.\t\\\\\n\nOur approach is hindered by three limitations. On the empirical side, there is the inherent difficulty of measuring country-level foreign fighter supply. Fighters do not always publicize their participation in a conflict, not least because of fears of legal repercussions upon returning home. In addition, due to the nascent state of the literature, we lack a compass in our search for meaningful predictors to include in our specifications. Although we have carefully collected data on an array of economic, political, social, and demographic country features, there are many variables we have excluded from our specifications that may matter to foreign fighter supply. Future theoretical work will hopefully yield insights that can update our search for more informative predictors.\t\t\\\\\n\nOur second limitation is that our algorithm is computationally expensive. This is owed to three factors. First, our complex optimization problem (Equation \\ref{eqn:targetFinal}) involves a large number of parameters (2$n$ + 3), and requires evaluating derivatives of the Gamma function. Second, our process for selecting the regularization parameters ($\\lambda_\\psi$, $\\lambda_\\omega$), involves a grid search and leave-one-out cross validation. Third, the difficulties of deriving an analytical estimate of uncertainty for our quantities of interest force us to resort to the bootstrap, which involves repeatedly refitting the model to resampled datasets. One of the authors is also working on lowering the dimensionality of a related problem to improve speed and provide estimates of uncertainty that avoid the bootstrap.\t\\\\ \n\nOn the theoretical side, a limitation of our framework is that it ignores psychological, ideological, and organization factors that figure prominently in the terrorism literature. This is inevitable, given that such factors are only observable at the individual- or group-level, while our analysis is at the country-level. In theory, one could collect data on confirmed fighters and match them to non-fighters, in an effort to identify individual-level predictors of their decision to go to Syria. Indeed, several recent papers based on interviews of a small sample of returning fighters focus on individual features, albeit through a purely descriptive qualitative approach \\citep{Stenersen2011, Weggemans2014, Nilsson2015}. Expanding this dataset and applying classification models, such as Random Forest, is a promising avenue for future empirical research.\t\\\\\n\nIn future work, we would like to generalize the model to allow for different parameterizations of the two components. For example, if we use the procedure to model individual choice, one may want to fit a probit to the binary component, motivated by a theory that the stochastic term is normally distributed. Similarly, if there is no over-dispersion in the truncated count, we may want to make efficiency gains by fitting a Poisson.\\footnote{\\cite{Zorn1998} notes that in the hurdle model over dispersion can be largely accounted for by the binary component, and thus a Poisson model may suffice for the count component.} Yet another extension is to allow for different features to enter each component. This is appropriate for questions where the theory guiding model specification is more developed. Nonetheless, with flexible estimators it is likely better to include as many relevant features as possible into the two components. \n\nBroader extensions of our method would involve applying it to different political science questions. KRHNB can be used to predict any count processes that might have a hurdle structure, ranging from the number of terrorist attacks perpetrated in each country (e.g. \\cite{Burgoon2006}) to the number of bills passed by female legislatures in Congress (e.g. \\cite{Volden2013}). Moreover, by abandoning the hurdle structure and applying kernel regularization to different classes of GLMs (e.g. binary choice), the range of political science processes that can be modeled becomes infinite. We hope that our study will motivate political methodologists to take up this task.\t\n\n%========================================================\n\\bibliography{ff}\t\t\\bibliographystyle{chicago}\n%========================================================\n\\newpage\n\\appendix\n\\setcounter{table}{0}\n\\renewcommand{\\thetable}{A\\arabic{table}}\n\\setcounter{figure}{0}\n\\renewcommand{\\thefigure}{A\\arabic{figure}}\n\\setcounter{equation}{0}\n\\renewcommand{\\theequation}{\\Alph{section}.\\arabic{equation}}\n%========================================================\n%========================================================\n\\section{Results Table and Heterogeneous Effects}\t\\label{app:tables}\n\n\\subsection{Full Results}\n\nThis section contains two tables that have the sample-average pointwise marginal effects for two different datasets. Table~\\ref{tab:appeffects} contains the same information as Figure~\\ref{fig:booteffects} and represents the results from our main specification where we impute missing values and divide foreign fighter supply between Israel and the West Bank. \\\\\n\n\\begin{table}[!p]\n\t\\footnotesize\n\t\\centering\n\t\\caption{Average Marginal Effects on Foreign Fighter Supply} \t\\label{tab:appeffects}\n\t\\begin{tabular}{l ccc}\n\t\t\\toprule\n\t\tVariable & \\multicolumn{1}{c}{Both Components} & \\multicolumn{1}{c}{Hurdle} & \\multicolumn{1}{c}{Count} \\\\ \n\t\t\\midrule\nLife Expectancy & 8.64 & 0.02 & 6.87 \\\\ \n& [2.88, 22.87] & [0.02, 0.07] & [-2.59, 21.3] \\\\ \nContiguous & 68.3 & 0.1 & 87.89 \\\\ \n& [-117.95, 243] & [-0.16, 0.38] & [-151.81, 307.67] \\\\ \nDistance (km) & -6.99 & -0.02 & -4.36 \\\\ \n& [-23.87, -0.51] & [-0.08, -0.01] & [-21.98, 15.74] \\\\ \nInternet User per 100 & 9.48 & 0.02 & 9.37 \\\\ \n& [3.23, 36.21] & [0.01, 0.08] & [-4.11, 37.57] \\\\ \nMigrants as Pct of Pop & -3.84 & 0.02 & -20.19 \\\\ \n& [-20.76, 5.71] & [0.01, 0.08] & [-52.31, -7.87] \\\\ \nMale LFP & -6.52 & 0 & -12.23 \\\\ \n& [-26.61, 3.66] & [-0.03, 0.03] & [-46.65, 4.27] \\\\ \nYouth Unemployment & 2.73 & 0.01 & -0.12 \\\\ \n& [-9.21, 14.96] & [-0.01, 0.06] & [-29.94, 17.65] \\\\ \nFreedom House Civ. Lib. & -0.12 & 0 & -1.66 \\\\ \n& [-4.01, 12.74] & [-0.01, 0.03] & [-12.41, 15.97] \\\\ \nFreedom House Pol. Rights & 2.06 & 0.01 & -2 \\\\ \n& [-9.17, 15] & [0, 0.05] & [-23.41, 16.69] \\\\ \nSunni Pct & 15.17 & 0.05 & 12.7 \\\\ \n& [8.06, 41.84] & [0.02, 0.11] & [3.92, 38.71] \\\\ \nShia Pct & 0.19 & 0.02 & -8.48 \\\\ \n& [-11.1, 14.41] & [-0.01, 0.05] & [-25.07, 13.32] \\\\ \nGovt. Reg. Religion & 7.3 & -0.01 & 21.84 \\\\ \n& [0.34, 30.97] & [-0.02, 0.03] & [5.75, 52.54] \\\\ \nGovt. Fav. Religion & 4.45 & -0.01 & 19.11 \\\\ \n& [-3.94, 22.98] & [-0.05, 0.03] & [2.04, 46.65] \\\\ \nSoc. Reg. Religion & 3.96 & 0 & 10.8 \\\\ \n& [-5.36, 20.46] & [-0.02, 0.06] & [-12.12, 32.33] \\\\ \nYouth Bulge (15-24 pct) & -4.66 & -0.01 & -5.6 \\\\ \n& [-13.42, 9.51] & [-0.05, 0] & [-15.88, 23.18] \\\\ \nReligious Frac. & -3.8 & 0.01 & -12.71 \\\\ \n& [-22.42, 5.73] & [-0.03, 0.04] & [-38.91, 3.54] \\\\ \nLog Homicides Per 100k & -0.69 & 0 & -2.9 \\\\ \n& [-16.45, 7.97] & [-0.05, 0.01] & [-19.46, 20.01] \\\\ \nLog Pop. Density & -4.85 & -0.02 & -1.93 \\\\ \n& [-26.92, 3.47] & [-0.07, 0] & [-30.98, 15.26] \\\\ \nLog Population & 18.24 & 0.03 & 27.37 \\\\ \n& [7.31, 47.54] & [0.01, 0.08] & [13.14, 70.14] \\\\ \nLog GDP pc, PPP & 3.67 & 0.01 & 6.38 \\\\ \n& [-0.75, 20.31] & [0, 0.05] & [-7.99, 22.69] \\\\ \nLog Refugees in Country & 9.42 & 0.04 & 5.35 \\\\ \n& [1.4, 32.18] & [0.02, 0.09] & [-8.18, 36.92] \\\\ \nLog Refugees from Country & 0.55 & 0 & -1.34 \\\\ \n& [-10.9, 10.77] & [-0.03, 0.03] & [-18.47, 21.29] \\\\ \nEurope & -11.37 & -0.01 & -19.29 \\\\ \n& [-48.52, 29.19] & [-0.08, 0.09] & [-84.71, 55.31] \\\\ \n\\midrule\nN & 163 & & \\\\\n\t\t\\bottomrule\n\t\\end{tabular}\n\t\\\\ \\footnotesize \\textit{Notes}: The point estimates are the simple mean of pointwise marginal effects over the full data. The first column has the joint effect on the outcome of the full hurdle negative binomial model, while the second and third columns represent the effect on the probability of any fighters in the hurdle and the mean of the negative binomial distribution in the count component. In brackets are the 2.5th and 97.5th percentiles of the 1000 bootstrapped sample-average pointwise marginal effects. \n\\end{table}\n\nTable~\\ref{tab:appeffectslist} contains the same results, but instead on a dataset where listwise deletion is used to remove observations with missing values. Furthermore, the West Bank and Gaza observation has been dropped rather than manually imputed. The results are very similar. The only substantive difference is that the percentile interval now includes 0 for the number of refugees in the country, although the effect is still strictly positive in the hurdle component.\n\n\\begin{table}[!p]\n\t\\footnotesize\n\t\\centering\n\t\\caption{Average Marginal Effects on Foreign Fighter Supply in Listwise Deleted Dataset} \t\\label{tab:appeffectslist}\n\t\\begin{tabular}{l ccc}\n\t\t\\toprule\n\t\tVariable & \\multicolumn{1}{c}{Both Components} & \\multicolumn{1}{c}{Hurdle} & \\multicolumn{1}{c}{Count} \\\\ \n\t\t\\midrule\nLife Expectancy & 15.24 & 0.04 & 12.01 \\\\ \n& [2.71, 35.62] & [0.01, 0.06] & [-9.94, 33.48] \\\\ \nContiguous & 78.05 & 0.14 & 82.55 \\\\ \n& [-91.57, 266.88] & [-0.15, 0.34] & [-138.82, 304.3] \\\\ \nDistance (km) & -8.6 & -0.04 & 0.75 \\\\ \n& [-27.97, 4.96] & [-0.06, -0.01] & [-25.44, 35.02] \\\\ \nInternet User per 100 & 21.87 & 0.04 & 25.45 \\\\ \n& [4.38, 55.05] & [0.02, 0.07] & [-4.6, 65.7] \\\\ \nMigrants as Pct of Pop & -8.87 & 0.03 & -31.1 \\\\ \n& [-23.49, 8.55] & [0.01, 0.07] & [-67.27, -2.6] \\\\ \nMale LFP & -16.44 & 0 & -30.12 \\\\ \n& [-44.22, 0.94] & [-0.02, 0.03] & [-83.99, -1.16] \\\\ \nYouth Unemployment & 1.53 & 0.01 & -6.74 \\\\ \n& [-18.73, 18.49] & [-0.02, 0.05] & [-46.98, 25.33] \\\\ \nFreedom House Civ. Lib. & -2.27 & 0.01 & -8.71 \\\\ \n& [-7.19, 16.65] & [-0.01, 0.03] & [-20.98, 18.74] \\\\ \nFreedom House Pol. Rights & 0.65 & 0.03 & -11.18 \\\\ \n& [-17.51, 15.42] & [0, 0.04] & [-41.82, 15.94] \\\\ \nSunni Pct & 26.57 & 0.07 & 23.85 \\\\ \n& [7.78, 52.81] & [0.03, 0.09] & [0.43, 54.28] \\\\ \nShia Pct & -2.72 & 0.01 & -12.77 \\\\ \n& [-13.12, 15.71] & [-0.01, 0.04] & [-31.06, 19.03] \\\\ \nGovt. Reg. Religion & 14.75 & -0.01 & 34.68 \\\\ \n& [1.06, 43.85] & [-0.02, 0.03] & [3.94, 80.33] \\\\ \nGovt. Fav. Religion & 5.75 & -0.02 & 23.54 \\\\ \n& [-3.81, 31.51] & [-0.03, 0.03] & [-5.12, 67.13] \\\\ \nSoc. Reg. Religion & 8.3 & 0.01 & 13.15 \\\\ \n& [-4.82, 28.08] & [-0.01, 0.05] & [-13.39, 45.4] \\\\ \nYouth Bulge (15-24 pct) & -4.01 & -0.02 & -4.19 \\\\ \n& [-16.44, 15.04] & [-0.04, 0.01] & [-20.9, 34.81] \\\\ \nReligious Frac. & -6.56 & 0 & -16.27 \\\\ \n& [-32.4, 6.5] & [-0.03, 0.03] & [-58.49, 6.34] \\\\ \nLog Homicides Per 100k & 2.82 & 0 & 3.57 \\\\ \n& [-17.66, 16.3] & [-0.05, 0.01] & [-23.4, 40.09] \\\\ \nLog Pop. Density & -7.92 & -0.02 & -5.83 \\\\ \n& [-33.61, 6.05] & [-0.05, 0.01] & [-46.81, 20.93] \\\\ \nLog Population & 31.27 & 0.05 & 46.34 \\\\ \n& [7.58, 71.29] & [0, 0.06] & [14.38, 109.16] \\\\ \nLog GDP pc, PPP & 7.48 & 0.01 & 11.16 \\\\ \n& [-0.77, 30.97] & [0.01, 0.05] & [-11.26, 37.61] \\\\ \nLog Refugees in Country & 13.62 & 0.04 & 15.12 \\\\ \n& [-0.21, 47.45] & [0.01, 0.08] & [-9.63, 63.35] \\\\ \nLog Refugees from Country & -0.22 & -0.01 & 5.31 \\\\ \n& [-11.83, 19.31] & [-0.04, 0.01] & [-10.72, 47.96] \\\\ \nEurope & -11.1 & 0.01 & -25.47 \\\\ \n& [-71, 46.84] & [-0.08, 0.09] & [-135.44, 97.85] \\\\ \n\\midrule\nN & 147 & & \\\\\n\t\t\\bottomrule\n\t\\end{tabular}\n\t\\\\ \\footnotesize \\textit{Notes}: The point estimates are the simple mean of pointwise marginal effects over the full data. The first column has the joint effect on the outcome of the full hurdle negative binomial model, while the second and third columns represent the effect on the probability of any fighters in the hurdle and the mean of the negative binomial distribution in the count component. In brackets are the 2.5th and 97.5th percentiles of the 1000 bootstrapped sample-average pointwise marginal effects. \n\\end{table}\n\n\\subsection{Heterogeneous Effects}\n\nBecause we able to compute pointwise marginal effects, it is possible to explore these effects to see how they vary in different parts of the feature space. One way to do this is simply to plot the pointwise marginal effects with respect to one variable by some other variable to see an interaction effect. A more robust way to explore these effects is to regress the pointwise marginal effects of some feature and all of the features in the data. This way, we can uncover the conditional interaction or non-linearity of our features. Of course, the pointwise marginal effects can themselves be modeled using flexible models or visualized using partial residual plots.  \\\\ \n\nA way to summarize all of these interaction effects is to regress the pointwise marginal effects for each feature on the full set of features. To be precise, we estimate a regression of the following form\n$$ \\frac{\\partial\\E[y_i|\\x_i]}{\\partial x^{(j)}_i} = \\bm{\\gamma}^\\top \\x_i,$$\nwhere $x^{(j)}_i$ is the $i$th observation of the $j$th feature. We do this for all features $j$. The coefficients in $\\bm{\\gamma}$ are analogous to interaction terms ($\\gamma_i \\; \\forall \\; i \\neq j$) or quadratic terms ($\\gamma_j$). Thus if we are predicting the pointwise marginal effects of life expectancy on foreign fighter supply and we estimate a large positive $\\gamma_i$ on, for example, the percent of the population that is Sunni, we then conclude that the marginal effect of life expectancy is much greater in heavily Sunni countries. Figure~\\ref{fig:interactplot} contains the results of these regressions for all features, demonstrating how the variables interact. Large blue dots indicate the two have a positive interaction effect while large red dots indicate the two have a negative interaction effect.\n\n\\begin{figure}[!h]\n\t\\centering\n\t\\includegraphics[scale=.85]{tabs_figs/interactPlot.pdf}\n\t\\caption{Interaction Effects}\t\\label{fig:interactplot}\n\t\\begin{flushleft} \\footnotesize \\textit{Notes}: Each cell is the coefficient from of a regression of one set of pointwise marginal effects on the rest of the data. A blue cell means that the two have a positive interaction while a red cell means the two have a negative interaction.\t\\end{flushleft}\n\\end{figure}\n\n%========================================================\n%========================================================\n\\section{Target Function Derivation}\t\\label{app:deriv}\n\n\\subsection{Sample Log-Likelihood}\n\nThe likelihood for observation $i$ in Equation~\\ref{eq:likelihood} can be written more explicitly with respect to the densities in Equations~\\ref{eq:dens0}, \\ref{eq:densmu}, and \\ref{eq:denstrunc}. Where $\\btheta = (\\alpha_0, \\balpha^\\top, \\beta_0, \\bbeta^\\top, \\zeta)^\\top$,\n\n\\begin{align}\n  L_i(\\btheta | y_i, \\x_i) &= \\l[ p_0(y_i = 0) \\r]^{1 - d_i} \\l[ \\frac{p_1(y_i)}{1 - p_1(y_ i = 0)} (1 - p_0(y_i = 0)) \\r]^{d_i}\n  \\quad \\text{;} \\quad d_i = \\begin{cases}\n  0 \\text{ if } y_i = 0 \\\\\n  1 \\text{ if } y_i \\geq 1\n  \\end{cases}  \\notag \\\\\n  &= \\l[ \\frac{1}{1 + \\exp(\\alpha_0 + \\x^\\top_i \\balpha)} \\r]^{1 - d_i} \\\\\n  &\\times \\l[ \\frac{\\Gamma (\\zeta + y_i) \\l( \\frac{\\zeta}{\\zeta + \\exp(\\beta_0 + \\x^\\top_i \\bbeta)} \\r)^\\zeta  \\l( \\frac{\\exp(\\beta_0 + \\x^\\top_i \\bbeta)}{\\zeta + \\exp(\\beta_0 + \\x^\\top_i \\bbeta)} \\r)^{y_i}}{\\Gamma(1 + y_i) \\Gamma(\\zeta) \\l( 1 -  \\l( \\frac{\\zeta}{\\zeta + \\exp(\\beta_0 + \\x^\\top_i \\bbeta)} \\r)^\\zeta \\r)} \\frac{\\exp(\\alpha_0 + \\x^\\top_i \\balpha)}{1 + \\exp(\\alpha_0 + \\x^\\top_i \\balpha)} \\r]^{d_i}\n\\end{align}\n\nNext we derive the sample log-likelihood in Equation~\\ref{eq:sampll}:\n\n\\begin{align}\n\\ell_N(\\btheta | \\Y, \\X) &= \\begin{aligned}[t]\n\\sum^N_{i=1} &(1 - d_i) \\l[ \\log 1 - \\log \\l( 1 + \\exp(\\alpha_0 + \\x^\\top_i \\balpha) \\r) \\r] + d_i \\Bigg[ \\log \\Gamma( \\zeta + y_i ) \\\\\n& + \\zeta \\log \\zeta - \\zeta \\log \\l( \\zeta + \\exp(\\beta_0 + \\x^\\top_i \\bbeta) \\r) + y_i (\\beta_0 + \\x^\\top_i \\bbeta) \\\\\n& - y_i \\log \\l( \\zeta + \\exp(\\beta_0 + \\x^\\top_i \\bbeta) \\r) - \\log \\Gamma (1 + y_i) - \\log \\Gamma (\\zeta) \\\\\n&- \\log \\l(1 - \\l( \\frac{\\zeta}{\\zeta + \\exp(\\beta_0 + \\x^\\top_i \\bbeta)} \\r)^\\zeta \\r) + (\\alpha_0 + \\x^\\top_i \\balpha) \\\\\n& - \\log \\l(1 + \\exp(\\alpha_0 + \\x^\\top_i \\balpha) \\r) \\Bigg]\n\\end{aligned} \\notag \\\\\n &= \\begin{aligned}[t]\n  \\sum^N_{i=1} & - \\log \\l(1 + \\exp(\\alpha_0 + \\x^\\top_i \\balpha) \\r) +  d_i \\Bigg[ \\log \\Gamma( \\zeta + y_i ) + \\zeta \\log \\zeta \\\\\n  &- (\\zeta + y_i) \\log \\l( \\zeta + \\exp(\\beta_0 + \\x^\\top_i \\bbeta) \\r) + y_i(\\beta_0 + \\x^\\top_i \\bbeta) + (\\alpha_0 + \\x^\\top_i \\balpha) \\\\\n  & - \\log \\Gamma (1 + y_i) - \\log \\Gamma (\\zeta) - \\log \\l( 1 - \\l( \\frac{\\zeta}{\\zeta + \\exp(\\beta_0 + \\x^\\top_i \\bbeta)} \\r)^\\zeta \\r) \\Bigg]\n  \\end{aligned}\n\\end{align} \n\n\\subsection{Using Mercer's Theorem}\n\nGiven Equation~\\ref{eqn:target}, we solve the First Order Condition (FOC) for each parameter vector in order to demonstrate our ability to use Mercer's Theorem to reduce our problem from a potentially infinite-dimensional one to a more tractable function. Where $\\btheta_{\\bphi} = (\\psi_0, \\bpsi^\\top, \\omega_0, \\bomega^\\top, \\zeta)^\\top$,\n\n\\begin{align}\n\\frac{\\partial R_N (\\btheta_{\\bphi}, \\lambda_\\psi, \\lambda_\\omega | \\Y, \\X)}{\\partial \\bpsi} &= 0 \\notag \\\\\n0 &= -\\sum^N_{i=1} \\Bigg( - \\frac{\\bphi(\\x_i)^\\top \\exp \\l( \\psi_0 + \\bphi(\\x_i)^\\top \\bpsi \\r)}{1 + \\exp \\l( \\psi_0 + \\bphi(\\x_i)^\\top \\bpsi \\r)} + d_i \\bphi(\\x_i)^\\top \\Bigg) + 2 \\lambda_\\psi \\bpsi \\notag \\\\\n\\bpsi &= \\sum^N_{i=1} \\Bigg\\{ \\frac{1}{2 \\lambda_\\psi} \\Bigg( - \\frac{\\exp \\l( \\psi_0 + \\bphi(\\x_i)^\\top \\bpsi \\r)}{1 + \\exp \\l( \\psi_0 + \\bphi(\\x_i)^\\top \\bpsi \\r)} + d_i \\Bigg) \\Bigg\\} \\bphi(\\x_i)\n\\end{align}\n\n\\begin{align}\n\\frac{\\partial R_N (\\btheta_{\\bphi}, \\lambda_\\psi, \\lambda_\\omega | \\Y, \\X)}{\\partial \\bomega} &= 0 \\notag \\\\\n0 &= \\begin{aligned}[t]\n- & \\sum^N_{i=1} d_i \\Bigg[ - \\frac{(\\zeta + y_i) \\bphi(\\x_i)^\\top \\exp \\l( \\omega_0 + \\bphi(\\x_i)^\\top \\bomega \\r)}{\\zeta + \\exp \\l( \\omega_0 + \\bphi(\\x_i)^\\top \\bomega \\r)} + y_i \\bphi(\\x_i)^\\top \\notag \\\\\n& - \\frac{-\\zeta \\l( \\frac{\\zeta}{\\zeta + \\exp \\l( \\omega_0 + \\bphi(\\x_i)^\\top \\bomega \\r)} \\r)^{\\zeta - 1} \\l( \\frac{- \\zeta \\bphi(\\x_i)^\\top \\exp \\l(\\omega_0 + \\bphi(\\x_i)^\\top \\bomega \\r)}{\\l( \\zeta + \\exp \\l( \\omega_0 + \\bphi(\\x_i)^\\top \\bomega \\r) \\r)^2} \\r)}{1 - \\l( \\frac{\\zeta}{\\zeta + \\exp \\l(\\omega_0 + \\bphi(\\x_i)^\\top \\bomega \\r)} \\r)^\\zeta} \\Bigg] \\Bigg) \\\\\n&+ 2 \\lambda_\\omega \\bomega \n\\end{aligned} \\\\ \\notag \\\\\n\\bomega &= \\begin{aligned}[t]\n\\sum^N_{i=1} & \\Bigg\\{ \\frac{1}{2 \\lambda_\\omega} d_i \\Bigg[ - \\frac{(\\zeta + y_i) \\exp \\l( \\omega_0 + \\bphi(\\x_i)^\\top \\bomega \\r)}{\\zeta + \\exp \\l( \\omega_0 + \\bphi(\\x_i)^\\top \\bomega \\r)} + y_i  \\\\\n& - \\frac{\\zeta \\l( \\frac{\\zeta}{\\zeta + \\exp \\l( \\omega_0 + \\bphi(\\x_i)^\\top \\bomega \\r)} \\r)^{\\zeta - 1} \\l( \\frac{\\zeta \\exp \\l(\\omega_0 + \\bphi(\\x_i)^\\top \\bomega \\r)}{\\l( \\zeta + \\exp \\l( \\omega_0 + \\bphi(\\x_i)^\\top \\bomega \\r) \\r)^2} \\r)}{1 - \\l( \\frac{\\zeta}{\\zeta + \\exp \\l(\\omega_0 + \\bphi(\\x_i)^\\top \\bomega \\r)} \\r)^\\zeta} \\Bigg] \\Bigg\\}  \\bphi(\\x_i)\n\\end{aligned}\n\\end{align} \n\nNote that in both FOCs, the terms inside $\\{\\}$ form a scalar, which we label $c^\\psi_i$ and $c^\\omega_i$. As such, we rewrite our solutions for $\\bpsi$ and $\\bomega$ like we did in the main body of the paper:\n\n\\begin{align}\n\\bpsi^* = \\sum^N_{i=1} c^\\psi_i \\bphi(\\x_i) \\\\\n\\bomega^* = \\sum^N_{i=1} c^\\omega_i \\bphi(\\x_i) \n\\end{align} \n\nWe use these solutions to rewrite Equation~\\ref{eqn:target} as Equation~\\ref{eqn:targetFinal}, our final target function.\n\n\\end{document}\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: t\n%%% End:", "meta": {"hexsha": "9c6d4692cd2a6ad05305ad307f24347cb36474f9", "size": 113123, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/derpanopoulos_sonnet_ff.tex", "max_stars_repo_name": "lukesonnet/foreign_fighters", "max_stars_repo_head_hexsha": "88c1bfbde87b8e95c4858301d0a3e870ac59d0c3", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-12-27T12:50:03.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-27T12:50:03.000Z", "max_issues_repo_path": "tex/derpanopoulos_sonnet_ff.tex", "max_issues_repo_name": "lukesonnet/foreign_fighters", "max_issues_repo_head_hexsha": "88c1bfbde87b8e95c4858301d0a3e870ac59d0c3", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/derpanopoulos_sonnet_ff.tex", "max_forks_repo_name": "lukesonnet/foreign_fighters", "max_forks_repo_head_hexsha": "88c1bfbde87b8e95c4858301d0a3e870ac59d0c3", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 161.8354792561, "max_line_length": 2775, "alphanum_fraction": 0.7524287722, "num_tokens": 29204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.3488913482066966}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n\\chapter{Higher-Rank Polymorphism with the Application Mode}\n\\label{chap:BiDirectional}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n\nWe have seen in \\Cref{sec:DK} that bidirectional type checking is a useful and\nversatile tool for type checking and type inference. In traditional\nbidirectional type-checking, type information flows from functions to arguments\n(e.g., \\rref{dk-in-app} in \\Cref{sec:DK:declarative}). In this section, we\npresent a novel variant of bidirectional type checking where the type\ninformation flows from arguments to functions. This variant retains the\ninference mode, but adds a so-called \\textit{\\mode} mode. Such design can remove\nannotations that basic bidirectional type checking cannot, and is useful when\ntype information from arguments is required to type-check the functions being\napplied.\n\nWe illustrate our novel design of bidirectional type-checking using System \\ap,\na lambda calculus with implicit higher-rank polymorphism. This section first\npresents the declarative, syntax-directed type system of System \\ap\nin \\Cref{sec:AP:declarative}. The interesting aspects about the new type system\nare: 1) the typing rules, which employ a combination of the inference mode and\nthe \\textit{\\mode} mode; 2) the novel subtyping relation under an application\ncontext. Later, we prove our type system is type-safe by a type-directed\ntranslation to System F in \\Cref{sec:AP:translation}. An algorithmic type system\nis discussed in \\Cref{sec:AP:algorithm}.\n\n\n\n\\input{Gen/BiDirectional/introduction}\n\\input{Gen/BiDirectional/typesystem}\n\\input{Gen/BiDirectional/translation}\n\\input{Gen/BiDirectional/algorithm}\n\\input{Gen/BiDirectional/discussion}\n\n\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: \"../Thesis\"\n%%% org-ref-default-bibliography: \"../Thesis.bib\"\n%%% End:", "meta": {"hexsha": "6258a8f70c049d1abe8288f8fe19021f387434f4", "size": 1901, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Sources/BiDirectional.tex", "max_stars_repo_name": "xnning/Dissertation", "max_stars_repo_head_hexsha": "bcdca568b3e89ba9cc0e4e9858a34e7c008a4ebb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-09-07T00:43:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T23:07:52.000Z", "max_issues_repo_path": "Sources/BiDirectional.tex", "max_issues_repo_name": "xnning/Dissertation", "max_issues_repo_head_hexsha": "bcdca568b3e89ba9cc0e4e9858a34e7c008a4ebb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sources/BiDirectional.tex", "max_forks_repo_name": "xnning/Dissertation", "max_forks_repo_head_hexsha": "bcdca568b3e89ba9cc0e4e9858a34e7c008a4ebb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-15T08:46:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T08:46:35.000Z", "avg_line_length": 46.3658536585, "max_line_length": 80, "alphanum_fraction": 0.7317201473, "num_tokens": 433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883592602049, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.34889134820669654}}
{"text": "\\documentclass[a0]{tumposter}\n\n\\usepackage[english]{babel}\n\n\\usepackage{blindtext}\n\n\\usepackage{multicol}\n\\usepackage{amsmath}\n\\usepackage{graphicx}\n\n% for printing fontsizes\n\\usepackage{printlen}\n\\uselengthunit{mm}\n\n\\input{preamble.tex}\n\n\\usepackage[utf8]{inputenc}\n\n\\title{\n\tEarly Classification for Agricultural Monitoring \\\\ from Satellite Time Series\n\t}\n\t\n\\author{\n\tMarc Rußwurm,\\footnotemark[1] Romain Tavenard,\\footnotemark[2] Sébastien Lefèvre,\\footnotemark[2] Marco Körner\\footnotemark[1]\n\t}\n\n\\header{\n\tRemote Sensing Technology \\\\\n\tTUM Department of Civil, Geo and Environmental Engineering \\\\\n\tTechnical University of Munich\n\t}\n\t\n\\begin{document}\n\\maketitle\n\n\\renewcommand{\\subsection}[1]{\\textbf{#1}}\n\n\\begin{minipage}[t]{.65\\textwidth}\n\t\n\t\\section{Objective}\n\t\n\t\n\t\\begin{tikzpicture}[scale=16.8]\n\t\\node[label={[name=sat,text height=1.5ex,text depth=.25ex]Satellite Data}, anchor=north](x) at (-1,0){$\\M{X} = (\\V{x}_0, \\V{x}_1, \\dots , \\V{x}_T)$};\n\t\\node[below=of x, label={[yshift=1.3em, xshift=1.8em, font=\\tiny, text=white]below:ESA Sentinel 2 Satellite}](s2){\\includegraphics[width=11cm]{images/sentinel2}};\n\t\n\t\n\t\\node[below=0em of s2, text width=11cm](eqbox){\n\t\t\\small\n\t\t\\begin{itemize}\n\t\t\t\\item collected at regular temporal intervals of 2-3 days\n\t\t\t\\item measurements of 13 spectral bands\n\t\t\t\\item data available globalls\n\t\t\\end{itemize} \n\t};\n\t\n\t\\node[label={[name=cm,text height=1.5ex,text depth=.25ex]{Early} {Classification} Model}, anchor=north](f) at (0,0){ $\\yhat_t, {\\deltat} = f(\\xuptot)$};\n\t\\node[below=0em of f, text width=13cm, font=\\small](info){\n\t\t\\begin{description}\n\t\t\n\t\t\\item[$\\xuptot$] observation until $t$  \\\\\n\t\t\\item[$\\yhat_t$] class prediction scores \\\\\n\t\t\\item[$\\deltat$] probability of stopping.\n\t\t\n\t\t\\end{description}\n\t\t\n\t};\n%\t\\node[below=of f](example){\\input{images/example.tikz}};\n\t\\node[circle, below=of info, text width=11cm, fill=tumbluedark, text=white](example){Classifying a \\\\ satellite time series \\\\ {\\color{tumbluelight}\\textbf{accurately}} \\color{white} as {\\color{ecolor}\\textbf{early}} \\color{white} as possible};\n\t\n\t\n\t\\node[label={[name=ctm,text height=1.5ex,text depth=.25ex]Crop Type Labels}, anchor=north](y) at (1,0){\n\t\t$\\V{y} = \\small (y_\\text{corn}, y_\\text{barley}, \\dots) \\in \\mathbb{R}^{13}$\n\t};\n\t\\node[below=of y, label=below:crop type labels](labels){\\includegraphics[width=11cm]{images/parcels}};\n\t\\node[below=of labels, text width=11cm](lbls){\n\t\t\\small\n\t\t\\begin{itemize}\\setlength\\itemsep{.1em}\n\t\t\\item European Common Agricultural Policy (CAP)\n\t\t\\item collected yearly in entire Europe\n%\t\t\\item slowly made publicly available\n%\t\t\\item today, gathered on a national basis\n%\t\t\\item in future harmonized within Europe's INSPIRE directive\n\t\t\\end{itemize}\n\t};\n\t\n\t\\draw[very thick, -{Stealth[scale=.5]}, tumblue] (x) -- (f);\n\t\\draw[very thick, -{Stealth[scale=.5]}, tumblue] (f) -- (y);\n\t\n\t\\coordinate(bottomleftcolumn) at (example.south -| s2);\n\t\\coordinate(bottomrightcolumn) at (example.south -| lbls);\n\t\n\t\\scoped[on background layer]\n\t{\n\t\t\\node[fit=(ctm)(lbls)(bottomrightcolumn), fill=tumbluelight!20, inner sep=1em, rounded corners]{};\n\t\t\\node[fit=(f)(example)(cm), fill=tumorange!20, inner sep=1em, rounded corners]{};\n\t\t\\node[fit=(sat)(eqbox)(bottomleftcolumn), fill=tumbluelight!20, inner sep=1em, rounded corners]{};\n\t}\t\n\t\n\t\\end{tikzpicture}\n\t\n\t\n\t\\section{Method}\n\t\n\tBased on previous work (Rußwurm et al., 2019) applied to crop type mapping from remote sensing data.\n\t\n\t%A network output to indicate a probability of stopping $\\deltat$\n\t\n\t\\begin{minipage}[t]{.49\\textwidth}\n\t\t\\subsection{Mechanism}\n\t\t\n\t\t\\input{images/backprop_stopping_rule.tikz}\n\t\t\\backpropstoppingrulefull\n\t\t\n%\t\\begin{tikzpicture}\n%\t\t\\node[fill=tumbluelight!20, rounded corners](a) at (0,0){\n%\t\t\t\t\t\t\\input{images/backprop_stopping_rule.tikz}\n%\t\t\t\t\t\t\\backpropstoppingrulefull\n%\t\t\t\t\t};\n%\t\t\\node[right=of a]{\\input{images/qualitative_example.tikz}};\n%\t\\end{tikzpicture}\n%\t\\vspace{-10em}\n\n%\tprobability of not having classified before (known at training time)\n%\t$$P(t) = \\deltat \\cdot \\prod_{\\tau=0}^{t-1} 1 - p_\\tau$$\n\n\t\n\n\t\\end{minipage}\n\t\\begin{minipage}[t]{.49\\textwidth}\n\t\t\n\t\n\t\\subsection{Loss function}\n\t\n\tcomposite loss function\n\t$$\\mathcal{L}(\\V{x}, \\V{y}) = \\sum_{t=0}^T P(t;\\deltauptot) \\mathcal{L}_t(\\xuptot, \\V{y})$$\n\t\n\t\n\tA Loss function including accuracy and earliness\n\t\n\t\\begin{tikzpicture}[node distance=-.5em, draw=tumbluelight, rounded corners]\n\t\n\t%\t\\node(allloss){$\\mathcal{L}(\\V{x}, \\V{y}) = \\sum_{t=0}^T P(t;\\deltauptot) \\mathcal{L}_t(\\xuptot, \\V{y})$};\n\t%\t\n\t\\node(loss){$\\mathcal{L}_t(\\xuptot, \\V{y})$};\n\t\\node[right=of loss](equals){$=$};\n\t\\node[right=of equals, fill=accuracycolor!20, rounded corners, label={[font=\\small]Classification Loss}](classificationloss){$\\alpha \\mathcal{L}_c (\\xuptot, \\V{y})$};\n\t\\node[right=of classificationloss](minus){$-$};\n\t\\node[right=of minus, fill=earlinesscolor!20, rounded corners, label={[font=\\small]Earliness Reward}](earlinessreward){$(1 - \\alpha)\\mathcal{R}_e(t, \\ycorrect_t)$};\n\t\n\t\\node[below=1em of classificationloss, text width=10cm, xshift=-4em](clossexp){$\\mathcal{L}_c = -\\log(\\ycorrect_t)$ \\\\\n\t\t\\vspace{.5em} \n\t\t\\tiny\n\t\tcross entropy loss for accurate classifications \\par};\n\t\n\t\\node[below=1em of earlinessreward, text width=13cm, xshift=-2em](erewardexp){$\\mathcal{R}_e(t, \\ycorrect_t) = \\ycorrect_t \\left(1 - \\frac{t}{T}\\right)$ \\\\\n\t\t\\vspace{.5em}\n\t\t\\tiny\n\t\treduces loss for earlier classifications $1-\\frac{t}{T}$ if the correct class $\\ycorrect_t$ has been predicted \\par};\n\t\n\t\\draw[thick] (classificationloss) -- (clossexp);\n\t\\draw[thick] (earlinessreward) -- (erewardexp);\n\t\\end{tikzpicture}\n\t\n\t\n\t\\end{minipage}\n\n\t{\\tiny \n\tRußwurm, M., Lefèvre, S., Courty, N., Emonet, R., Körner, M., and Tavenard, R. End-to-end learning for early classification of time series. arXiv preprint arXiv:1901.10681, 2019.\n\t\\par\n\t}\n\n\t\\vspace{-1em}\n\t\\section{Application}\n\t\n\t\\begin{minipage}[t]{.5\\textwidth}\n\t\\subsection{Agriculture}\n\t\n\t\\small\n\t\n\t\\vspace{1em}\n\t\n\t\t\\textbf{Early Crop Detection}\n\t\t\\begin{itemize}\n\t\t\t\\item early assessment of cultivated crops\n\t\t\t\\item basis for early crop yield estimation\n\t\t\\end{itemize}\n\t\t\\vspace{.3em}\n\t\t\n\t\t\\textbf{Extraction of Crop Phenology}\n\t\t\\begin{itemize}\n\t\t\t\\item extraction of vegetation specific events \n\t\t\t\\item monitoring time of classification\n\t\t\t\\item regional or temporal variations\n\t\t\\end{itemize}\n\t\t\\vspace{.3em}\n\t\t\n\t\t\\textbf{Generalization}\n\t\t\\begin{itemize}\n\t\t\t\\item end-to-end trainable\n\t\t\t\\item no region-specific expert knowledge\n\t\t\t\\item applicable globally\n\t\t\\end{itemize}\n\t\n\t\\end{minipage}\n\t\\begin{minipage}[t]{.49\\textwidth}\n\t\\subsection{Dataset and Area of Interest} \\par\n\t\\begin{minipage}{.6\\textwidth}\n\t\t\\small\n\t\t\\vspace{1em}\n\t\tHollfeld region Bavaria\n\t\t\\begin{itemize}\n\t\t\t\\item 49k field parcels\n\t\t\t\\item 6 main crop types\n\t\t\t\\item covering 40km by 30 km\n\t\t\t\\item central Germany\n\t\t\\end{itemize}\n\t\t\n\t\t\\vspace{1em}\n\t\n\t\t\\tiny Challenge: Class imbalance \\par\n\t\t\\input{images/partition_histograms.tikz}\n%\t\t\\vspace{-4em}\\includegraphics[width=.3\\textwidth]{images/holl.pdf}\n\t\\end{minipage}\n\t\\begin{minipage}{.35\\textwidth}\n%\t\t\\input{images/partition_histograms.tikz}\n\t\t\\tiny {\\color{tumblue}regions with labels} and \\\\ {\\color{tumorange} location of dataset. \\par} \\par\n\t\t\\includegraphics[width=.9\\textwidth]{images/oberfrankenineurope.pdf}\n\t\t \n\t\t \\tiny partition in {\\color{traincolor} train}, {\\color{validcolor} validation}, and {\\color{evalcolor} evaluation} \\par\n\t\t\\includegraphics[width=.9\\textwidth]{images/holl.pdf}\n\t\\end{minipage}\n\t\n\t\\end{minipage}\n\n\\end{minipage}\n\\hfill\n\\begin{minipage}[t]{.32\\textwidth}\n\t\\section{Results}\n\t\n\t\\subsection{Qualitative Example} \\par\n\t{\\footnotesize Single example showing reflectance data $\\M{x}$ and predictions $\\yhat$ along with the stopping time $\\tstop \\sim \\text{Ber}(\\deltat)$. \\par}\n\t\n\t\\vspace{.5em}\n\t\\input{images/example.tikz}\n\t\\vspace{-.5em}\n\t\n\t\\subsection{Losses during Training} \\par\n\t{\\footnotesize The combined loss $L_t$, as well as earliness $L_e$ and accuracy $L_e$ losses during training. \\par}\n\n\t\\vspace{.5em}\t\n\t\\input{images/loss-accuracyplots.tikz}\n\t\\vspace{-1em}\n\n\t\\subsection{Stopping Condition Parameterization} \\par\n\t{\\footnotesize Stopping times throughout the training grouped by crop category. The parameterization of early classification is learned for different crop types at different times during training. \\par}\n\t\n\t\\input{images/trainingstoppingclasses.tikz}\n\t\n\t\\subsection{Balancing Earliness and Accuracy} \\par\n\t{\\footnotesize Evaluting the effect of the trade-off parameter $\\alpha$ on the accuracy and earliness ($\\tstop$). Runs repeated three times to evaluated the sability of the results. \\par}\n\t\n\t\\begin{table}\n\t\t\n\t\t\\scriptsize\n\t\t\\hspace{0em}\\begin{tabular}{lcccccc}\n\t\t\t\\toprule\\small\n\t\t\t\\textbf{$\\alpha$} & accuracy & $\\meantstop$  & precision & recall & $f_1$ & $\\kappa$ \\\\\n\t\t\t\\cmidrule(lr){0-0}\\cmidrule(lr){1-1}\\cmidrule(lr){2-2}\\cmidrule(lr){3-3}\\cmidrule(lr){4-4}\\cmidrule(lr){5-5}\\cmidrule(lr){6-6}\\cmidrule(lr){7-7}\n\t\t\t.0 & .25 $\\pm$ .22 & .10 $\\pm$ .17 & .19 $\\pm$ .20 & .25 $\\pm$ .17 & .16 $\\pm$ .20 & .12 $\\pm$ .19 \\\\\n\t\t\t.2 & .81 $\\pm$ .03 & .40 $\\pm$ .02 & .70 $\\pm$ .01 & .74 $\\pm$ .01 & .71 $\\pm$ .01 & .71 $\\pm$ .04 \\\\\n\t\t\t.4 & .80 $\\pm$ .09 & .47 $\\pm$ .03 & .71 $\\pm$ .02 & .74 $\\pm$ .01 & .71 $\\pm$ .02 & .71 $\\pm$ .10 \\\\\n\t\t\t.6 & .85 $\\pm$ .02 & .88 $\\pm$ .07 & .73 $\\pm$ .04 & .74 $\\pm$ .03 & .73 $\\pm$ .03 & .77 $\\pm$ .03 \\\\\n\t\t\t.8 & .84 $\\pm$ .01 & .93 $\\pm$ .05 & .72 $\\pm$ .02 & .75 $\\pm$ .01 & .73 $\\pm$ .02 & .76 $\\pm$ .02 \\\\\n\t\t\t1.0 & .83 $\\pm$ .03 & 1.00 $\\pm$ .00 & .72 $\\pm$ .03 & .75 $\\pm$ .01 & .72 $\\pm$ .03 & .75 $\\pm$ .04 \\\\\n\t\t\t\\bottomrule\n\t\t\\end{tabular}\n\t\n\t\n\t\t%\t\\caption{Varying the weighting factor $\\alpha$ for \\emph{early reward} loss formulation (\\cref{sec:earlynessreward}).}\n\t\t%\t\\label{tab:alpha}\n\t\t\n\t\\end{table}\n\t\n\t\n\t\\subsection{Extracting Vegetation Characteristics} \\par\n\t\n\t{\\footnotesize Stopping time per crop category reveals characteristic variations in type of vegetation confirmed by date of harvest (\\druschdatum) from local authorities. \\par} \n\t\\vspace{.5em}\n\t\\input{images/classboxplots.tikz}\n\t\n\\end{minipage}\n\n%\\frame{\n\\begin{footer}\n\t\\begin{minipage}{.15\\textwidth}\n\t\t\\textbf{ICML Workshop}\\\\\n\t\t\\includegraphics[width=5cm]{images/AI4SG}\n\t\\end{minipage}\n\t\\begin{minipage}{.275\\textwidth}\n\t\t\\textbf{Technical University of Munich}\\footnotemark[1]\\\\\n\t\tTUM Department of Civil, Geo and Env. \\\\\n\t\tRemote Sensing Technology \\\\\n\t\tArcisstr. 21, 80333 Munich, Germany\n\t\\end{minipage}\n\t\\begin{minipage}{.275\\textwidth}\n\t\t\\textbf{IRISA-Obelix}\\footnotemark[2]\\\\\n\t\tUniversité Bretagne Sud \\\\\n\t\tIRISA, UMR 6074 CNRS \\\\\n\t\tCampus de Tohannic, 56000 Vannes, France\n\t\t\n\t\\end{minipage}\n\t\\begin{minipage}{.2\\textwidth}\n\t\t\\textbf{Data \\& Code} \\\\\n\t\t%\t\t\\vspace{1em}\n\t\t{github.com/rtavenar/early\\_rnn} \\\\\n\t\t{twitter.com/MarcCoru} \\\\\n\t\twww.lmf.bgu.tum.de/vision\n\t\\end{minipage}\n\t\\begin{minipage}{.05\\textwidth}\n\t\t\\hfill\\includegraphics[width=5cm]{images/qr-code}\\\\\n\t\t\n\t\\end{minipage}\n\n\t\n\\end{footer}\n%}\n\n\\end{document}", "meta": {"hexsha": "2cf5b6b868faf8afddda497cb8744909682ccd63", "size": 10995, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "main.tex", "max_stars_repo_name": "MarcCoru/ICML19_AI4SG_Poster", "max_stars_repo_head_hexsha": "f55efb0c4286b9b28cd1716e9bd31e400c237b71", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.tex", "max_issues_repo_name": "MarcCoru/ICML19_AI4SG_Poster", "max_issues_repo_head_hexsha": "f55efb0c4286b9b28cd1716e9bd31e400c237b71", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.tex", "max_forks_repo_name": "MarcCoru/ICML19_AI4SG_Poster", "max_forks_repo_head_hexsha": "f55efb0c4286b9b28cd1716e9bd31e400c237b71", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4194528875, "max_line_length": 245, "alphanum_fraction": 0.6866757617, "num_tokens": 3933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.34876783486490925}}
{"text": "\\chapter{Discussion}\n\\label{chapter:conclusion}\n\n    %% TODO\n    %% - SimGrid suppose que les consommations réseau et cpu sont linéaires\n    %%   et indépendantes. Ce n'est pas si simple. Tension entre\n    %%   mesurer/injecter et modéliser/prédire.\n    %% - Ça marche mais niveau d'expertise encore assez démentiel\n    %% - Résolution/automatisation de pas mal de choses en terme de\n    %%   modélisation de plate-forme mais il y a encore beaucoup de\n    %%   travail. LibSimBLAS ?\n\n    \\section{Contribution}%\n\n        This thesis has contributed to the improvement of experimental reproducibility in high performance computing.\n\n        In Part~\\ref{part:prediction}, we described a method for predicting the performance of MPI applications through\n        simulation. Using Simgrid/SMPI simulator, we managed to emulate the High Performance Linpack benchmark at scale\n        by applying only a few modifications to its source code. We compared several computation and communication\n        models and showed the importance of modeling both the temporal and spatial variability of the platform. In a\n        thorough comparison of the simulations with real executions, we show that the prediction error remains very low,\n        only a few percent, thereby demonstrating the faithfulness of this approach. Several sensibility analyses are\n        then performed to quantify the effect of platform variability and showcase an important use case of simulation.\n\n        The lessons learned during this work are then presented in Part~\\ref{part:experiment}. We start by describing the\n        experiment engine we developed and that was used throughout this thesis. Then, we present an in-depth report of\n        the many experimental biases we faced, including very unsettling phenomenons we did not anticipate. While some\n        of these biases can be desirable if they are also occurring in the simulated application, most of them had to be\n        suppressed through randomization. Finally, we showcase the performance non-regression test we implemented. While\n        not a statistical novelty, they allowed us to detect many changes on Grid'5000 platform that affected\n        significantly the performance and could harm experiments if gone unnoticed. We believe the HPC community could\n        greatly benefit of such tests.\n\n    \\section{Trusting our predictions}%\n    \\label{sec:prediction_trust}\n\n        Unlike mathematical theorems or algorithms, the correctness of a model like those of Part~\\ref{part:prediction}\n        cannot be formally proven. The only sound method for validating its faithfulness is to thoroughly try to break\n        it, by comparing predictions to reality while methodically changing the configurations. As presented in\n        Chapter~\\ref{chapter:prediction:validation}, we did cover an extensive range of configurations in our\n        validation. Before managing to systematically obtain accurate predictions, we stumbled on many problems which\n        caused our predictions to be unrealistic. We had to investigate, understand and overcome these multiple\n        obstacles, as reported in Part~\\ref{part:experiment}.\n\n        A few weeks before the defense of this thesis, we decided to repeat the whole simulation study from scratch on\n        another Grid'5000 cluster named \\gros, using 60 of its nodes. This cluster has different nodes (one Intel Xeon\n        Gold 5220 processor per node with \\NSI{96}{\\giga\\byte} of memory), a different network (with\n        \\NSI{25}{\\giga\\bit/\\second} Ethernet) and we used a more recent version of OpenBLAS (resulting in the use of\n        AVX512 instructions by the \\dgemm function instead of AVX2). Over the course of a weekend, we calibrated the\n        platform by measuring the \\dgemm and MPI durations. Then, we performed real and simulated HPL executions. At\n        first, the predicted performance was too low by one order of magnitude. This was due to a mistake we made: we\n        computed the linear regression of the \\dgemm model using all the terms of the polynomial, even those of degree\n        one (\\ie \\(M\\), \\(N\\) and \\(K\\)) which were not statistically significant. This resulted in an overfitted model\n        with spurious predictions.  After fixing this issue by only considering the significant terms, we obtained\n        extremely accurate predictions of HPL performance for various matrix sizes (see\n        Figure~\\ref{fig:conclusion:gros_study}).\n\n        \\begin{figure}[htpb]\n            \\centering\n            \\includegraphics[width=\\linewidth]{img/conclusion/validation_gros.pdf}\n            \\caption{HPL performance: prediction vs. reality for various matrix ranks, using 60 nodes of the \\gros\n            cluster.}%\n            \\label{fig:conclusion:gros_study}\n        \\end{figure}\n\n        Similarly to what we observed in Chapter~\\ref{chapter:prediction:validation}, the predictions are more accurate\n        with a complex \\dgemm model (\\ie heterogeneous, stochastic and polynomial)  than with a simpler model (\\ie\n        homogeneous, deterministic and linear). However, the simpler model still makes reasonably low prediction errors\n        here as the \\gros cluster has less variability than the \\dahu cluster.\n\n        This small additional study demonstrates clearly the level of trust we can now have in our model, but also its\n        fragility, as seemingly inoffensive changes in the approach can lead to widely inaccurate predictions.\n\n    \\section{Future work}%\n\n        Besides the next steps already discussed in Chapter~\\ref{chapter:prediction:conclusion} and\n        Section~\\ref{sec:test:conclusion}, there also remains a unification work. By going a step further in the\n        automation, we could use the data produced by the non-regression tests to generate new model instances for\n        Simgrid. It would then be possible to make new simulations with a platform model that reflects the latest\n        changes of the real platform. Then, by implementing the same statistical test on the performance predicted by\n        the simulation, we should be able to detect whether a platform change has affected the application\n        performance and quantify this effect. A minor performance drop of the computation kernels could be amplified by\n        the synchronization phases of the application and become very concerning at a larger scale. Conversely, it could\n        also be attenuated by the global noise and go completely unnoticed.\n\n        We believe that our predictions could be extremely valuable to the whole life cycle of supercomputers:\n        \\begin{description}\n            \\item[Design] Using simulations, manufacturers could apply co-design techniques to construct the most\n                performant machines for a given set of target applications and within a given budget. This could help\n                achieve more faithful results than the current techniques relying on less accurate simulations or even\n                guesswork.\n            \\item[Development] Simulations could also largely benefit software developers. Both debugging and tuning the\n                application are more convenient and less expensive in simulation than in reality, especially if large\n                scale runs are required.\n            \\item[Maintenance] Whenever the platform employees need to perform some maintenance, there is a\n                non-negligible risk of affecting the machine performance, as we illustrated in\n                Chapter~\\ref{chapter:experiment:tests}. To verify that the performance did not change, the usual method\n                is to perform large-scale runs of a benchmark such as HPL, which can largely lengthen the maintenance\n                duration. A more convenient alternative would be to (1) carry small but carefully designed performance\n                tests as those described in Chapter~\\ref{chapter:experiment:tests} to check if there is anything\n                obviously wrong, and (2) perform large-scale simulations with the updated model and compare the new\n                predictions with the previous ones.\n        \\end{description}\n", "meta": {"hexsha": "6471f6903fdd7f380a40e6beacf089b4de7a6bff", "size": 8148, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapter_conclusion.tex", "max_stars_repo_name": "Ezibenroc/thesis", "max_stars_repo_head_hexsha": "62c239406d5979f1c9aabf180c8232ce2f2b1ee7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapter_conclusion.tex", "max_issues_repo_name": "Ezibenroc/thesis", "max_issues_repo_head_hexsha": "62c239406d5979f1c9aabf180c8232ce2f2b1ee7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter_conclusion.tex", "max_forks_repo_name": "Ezibenroc/thesis", "max_forks_repo_head_hexsha": "62c239406d5979f1c9aabf180c8232ce2f2b1ee7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 78.3461538462, "max_line_length": 121, "alphanum_fraction": 0.7357633775, "num_tokens": 1650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.34876782663137174}}
{"text": "\\documentclass{report}\n\\usepackage[utf8]{inputenc}\n\\usepackage{amsmath,mathpazo,siunitx,xparse,tikz,enumitem,fancyhdr,pgfplots}\n\n%%Needed to properly display graphs\n\\pgfplotsset{width=10cm,compat=1.9}\n\n\\pagestyle{fancy}\n\\fancyhf{}\n\\lhead{Steven Glasford}\n\\chead{Homework 2}\n\\rhead{Page \\thepage}\n\n\\title{Homework 2}\n\\author{Steven Glasford}\n\\date{\\parbox{\\linewidth}{\\centering%\n    %%Adds the last compiled date\n    \\today\\endgraf\\medskip\n    Math-451-M001}}\n\n%%Creates a new symbol for plus and minus together\n\\newcommand{\\rpm}{\\sbox0{$1$}\\sbox2{$\\scriptstyle\\pm$}\n  \\raise\\dimexpr(\\ht0-\\ht2)/2\\relax\\box2 }\n\n%%Creates a nice format for displaying the steps taken  \n\\newlist{steps}{enumerate}{1}\n\\setlist[steps, 1]{label = Step \\arabic*:}\n\n\\ExplSyntaxOn\n%%new command to round numbers\n\\newcommand*{\\prlen}[1]{%\n   % round to 1 digit:\n    \\pgfmathparse{round(10)/10.0}%\n    %\\pgfkeys{/pgf/number format/precision=1}\n    %\\pgfmathresult\n    \\pgfmathprintnumber[fixed, precision=2]{\\pgfmathresult}\n}\n\\ExplSyntaxOff\n\n\n\\begin{document}\n%% adds the title to the document\n\\maketitle\n%% adds the table of contents to the document\n\\tableofcontents\n\n%%Add everything about the first problem here\n\\chapter{Hydro-Turbine Optimization}\n\\section{Introduction}\nA paper company in Maine operates a hydroelectric generating station on the Penobscot River. Water is piped through from a dam to the power station. The rate at which the water flows through the pipe varies, depending on external conditions. The power station has three different hydroelectric turbine, each with a known (and unique) power function that gives the amount of electric generated as a function of the water flow arriving at the turbine. The incoming water can be apportioned in different volumes to each turbine, so the goal is to determine how to distribute water among the turbines to give the maximum total energy production for any rate of flow. Using experimental evidence and Bernoulli's equation, the following quadratic models were determined for the power output of each turbine, along with the allowable flows of operation:\n\\begin{align*}\n    KW_1 &= (-18.89+0.1277Q_1-\\num{4.08e-5}Q_1^2)(170-\\num{1.6e-6}Q_T^2)\\\\\n    KW_2 &= (-24.5+0.1358Q_2-\\num{4.69e-5}Q_2^2)(170-\\num{1.6e-6}Q_T^2)\\\\\n    KW_3 &= (-27.02+0.1380Q_3-\\num{3.84e-5}Q_3^2)(170-\\num{1.6e-6}Q_T^2)\n\\end{align*}\n$$250 \\leq Q_1 \\leq 1110, 250 \\leq Q_2 \\leq 1110, 250 \\leq Q_3 \\leq 1225$$\nwhere\n\n$Q_i = $ flow through turbine $i$ in cubic feet per second\n\n$KW_i = $ power generated by turbine $i$ in kilowatts\n\n$Q_T = $ total flow through the station in cubic feet per second\n\n\n\\section{Presentation of the Model}\n\\subsection{Objective}\n\\hspace{10mm} The objective of this problem is to determine the flow through each turbine needed to create the maximum amount of power.\n\\subsection{Variables and Constants}\n\n\\begin{center}\n\\begin{tabular}{c c c}\n$KW_i$ &$=$ & power generated by turbine $i$ in kilowatts.\\\\\n$Q_i$ & $=$ & flow through turbine $i$ in cubic feet per second.\\\\\n$Q_T$ & $=$ & total flow through the station in cubic feet per second.\\\\\n$P$ & $=$ & total power generated.\n\n\\end{tabular}\n\\end{center}\n\n\n\\subsection{Assumptions}\n\\begin{align*}\n    KW_1 &= (-18.89+0.1277Q_1-\\num{4.08e-5}Q_1^2)(170-\\num{1.6e-6}Q_T^2)\\\\\n    KW_2 &= (-24.5+0.1358Q_2-\\num{4.69e-5}Q_2^2)(170-\\num{1.6e-6}Q_T^2)\\\\\n    KW_3 &= (-27.02+0.1380Q_3-\\num{3.84e-5}Q_3^2)(170-\\num{1.6e-6}Q_T^2)\n\\end{align*}\n\\begin{align*}\n    250 &\\leq Q_1 \\leq 1110\\\\\n    250 &\\leq Q_2 \\leq 1110\\\\\n    250 &\\leq Q_3 \\leq 1225\n\\end{align*}\n$$Q_T=Q_1+Q_2+Q_3$$\n$$P = KW_1+KW_2+KW_3$$\n\n\\section{Solving the Model}\nWe will be using Lagrange Multipliers to find the values for the individual flow (as functions of $Q_T$) that maximize the total energy production $KW_1+KW_2+KW_3$ subject to the constraints $Q_1+Q_2+Q_3=Q_T$ and the domain restrictions on each $Q_i$.\n\nBut first we must find the objective function, which is the function we are trying to optimize. In this case it is the function $P$.\n$$P = KW_1+KW_2+KW_3$$\nThen we must populate this function using the data we are concerned about, we are not concerned with the optimum power generated with respect to the total power outputs of each individual turbine, instead we want to optimize with respect to the flow rates to each individual turbine. This makes the power function look more like this\n\n\\begin{multiline}\n$P = (-18.89+0.1277Q_1-\\num{4.08e-5}Q_1^2)(170-\\num{1.6e-6}Q_T^2) + (-24.5+0.1358Q_2-\\num{4.69e-5}Q_2^2)(170-\\num{1.6e-6}Q_T^2) + (-27.02+0.1380Q_3-\\num{3.84e-5}Q_3^2)(170-\\num{1.6e-6}Q_T^2)$\n\\end{multiline}\n\nLagrange Multipliers have the form:\n$$\\nabla f = \\lambda \\nabla g,$$\n\nwhere $f$ is our objective function and $g$ is the constraint equation. In this problem our constraint equation is $$Q_T = Q_1 + Q_2 + Q_3$$ and $$f = P,$$ but before we continue we must replace the all of the $Q_T$ in the objective equation with the variable $Q_1, Q_2, Q_3$ which isn't difficult since the constraint equation already does this step for us.\n\n\\vspace{5mm}\n\n\\begin{tabular}{c c}\n$P =& (-18.89+0.1277Q_1-\\num{4.08e-5}Q_1^2)(170-\\num{1.6e-6}* \\\\ \n&(Q_T)^2)+ (-24.5+0.1358Q_2-\\num{4.69e-5}Q_2^2)* \\\\ \n&(170-\\num{1.6e-6}(Q_T)^2) \\\\\n&+ (-27.02+0.1380Q_3-\\num{3.84e-5}Q_3^2)*\\\\\n&(170-\\num{1.6e-6}(Q_T)^2)$\n\\end{tabular}\n\n%(170-w^2/625000)*(-(51*x^2)/1250000+(1277*x)/10000-1889/100)+(170-w^2/625000)*(-(3*z^2)/78125+(69*z)/500-1351/50)+(170-w^2/625000)*(-(469*y^2)/10000000+(679*y)/5000-49/2)\n\n\\vspace{5mm}\n\nWe shall try to find the extrema for P the old fashion way, by simply finding the gradient of P, then setting the gradient to 0 and finding min and maxes. To make our lives easier we will assume that $Q_T$ is a constant, which will end up making life much, much easier in the long run.\n$$\\nabla P = \\left\\langle\\frac{\\partial P}{\\partial Q_1},\\frac{\\partial P}{\\partial Q_2},\\frac{\\partial P}{\\partial Q_3}\\right\\rangle$$\n\nNow we must find the partials:\n\n$$\\frac{\\partial P}{\\partial Q_1} = \\dfrac{\\left(Q_T^2-106250000\\right)\\left(102Q_1-159625\\right)}{781250000000}$$\n\n$$\\frac{\\partial P}{\\partial Q_2}=\\dfrac{7\\left(Q_T^2-106250000\\right)\\left(67Q_2-97000\\right)}{3125000000000}$$\n\n$$\\frac{\\partial P}{\\partial Q_3} = \\dfrac{3\\left(Q_T^2-106250000\\right)\\left(8Q_3-14375\\right)}{195312500000}$$\n\n\\vspace{5mm}\n\nThe roots of P:\n$$\\nabla P = \\left\\langle \\dfrac{159625}{102},\\dfrac{97000}{67},\\dfrac{14375}{8}\\right\\rangle$$\nOr more approximately:\n$$\\nabla P \\approx \\left\\langle1564.95098,1447.76119,1796.875\\right\\rangle$$\n\nHowever, this extrema is outside our bounds for all of the variables so we cannot use this method of finding the gradient and the roots of the gradient. So we must now use Lagrange multipliers. \n\n\n\n\\vspace{5mm}\nLagrange multipliers are in the form $$\\nabla f = \\lambda \\nabla g,$$ where $f$ is our objective equation ($P$) and $g$ ($Q_T$) is out constraint equation and $\\lambda$ is our Lagrange multiplier. \n\nWe have already found $\\nabla P$ so we must now find the gradient of $Q_T$ The gradient of $Q_T$ \n$$\\nabla Q_T = \\left\\langle\\frac{\\partial Q_T}{\\partial Q_1},\\frac{\\partial Q_T}{\\partial Q_2},\\frac{\\partial Q_T}{\\partial Q_3}\\right\\rangle$$ which boils down to $$\\nabla Q_T = \\left\\langle1,1,1\\right\\rangle$$\n\nNow we can set the two equations equal to each other:\n\n$$\\frac{\\partial P}{\\partial Q_1} = \\dfrac{\\left(Q_T^2-106250000\\right)\\left(102Q_1-159625\\right)}{781250000000}=\\lambda$$\n$$\\frac{\\partial P}{\\partial Q_2}=\\dfrac{7\\left(Q_T^2-106250000\\right)\\left(67Q_2-97000\\right)}{3125000000000}=\\lambda$$\n$$\\frac{\\partial P}{\\partial Q_3} = \\dfrac{3\\left(Q_T^2-106250000\\right)\\left(8Q_3-14375\\right)}{195312500000} = \\lambda$$\n\nand $$Q_T=Q_1+Q_2+Q_3$$\n\nNow we want to solve for $\\lambda$\n\n$$Q_1 = \\frac{15925Q_T+781250000000\\lambda -1692031250000}{102Q_T-10837500000}$$\n$$Q_2 = \\frac{679000Q_T + 3125000000000\\lambda - 72143750000000}{469Q_T^2-49831250000}$$\n$$Q_3 = \\frac{43125Q_t^2+195312500000\\lambda - 4582031250000}{24Q_T^2-2550000000}$$\n\nPut these equations into the original $Q_T$ equation and solve for $\\lambda$\n\n$$\\lambda = \\frac{7\\left(2733Q_T-92963275\\right)\\left(Q_T^2-106250000\\right)}{4297851562500000}$$\n\nPlugging $\\lambda$ back into the original $Q_i$ equations and then simplifying we get:\n\n$$Q_1 = \\frac{7501Q_T}{22005}-\\frac{26500495}{26406}$$\n\n$$Q_2=\\frac{2176Q_T}{7335}+\\frac{1931560}{4401}$$\n\n$$Q_3=\\frac{7973Q_T}{22005}+\\frac{14911135}{26406}$$\n\nNow we graph the function between the bounds of each variable and try to find some intersection points between the $Q_i$ functions:\n\n\\begin{tikzpicture}\n        \\begin{axis}[\n            axis lines = left,\n            ylabel = Flow,\n        ]\n        \n        \\addplot[\n            domain=225:1225,\n            samples=100,\n            color=green,\n        ]{abs(-.3408770734*x+1003.57854276)};\n        \\addlegendentry{$\\left|Q_1\\right|$}\n        \\addplot [\n            domain=225:1225,\n            samples=100,\n            color=red,\n        ]{(.29665985003)*x+438.8911611};\n        \\addlegendentry{$Q_2$}\n        \n        \\addplot[\n            domain=225:1225,\n            samples=100,\n            color=blue,\n        ]{(.36232674392)*x+564.687381656};\n        \\addlegendentry{$Q_3$}\n        \n        \\end{axis}\n    \\end{tikzpicture}\n    \n %   Then the optimized version of this model should be at $$790.827$$ $$Q_2=701.653$$ $$Q_3=746.24$$ for a total power generation of 16622.69864 Kilowatts.\n    \n  %  But then I started to think about it. Logically if you have a turbine, that turbine should generate the most amount of power when it is doing the most amount of work, which would logically place the max value at the max boundary for each individual turbine, which means the max values should be at $$Q_1=1110$$ $$Q_1=1110$$ $$Q_3=1225$$ and if you put those values into the calculator you get an even higher value than you would get from the the other values. In particular you get a total power generation of 23155.92823 kilowatts, which is obviously greater than 16622.69864, so this is a bigger maximum, and a very obvious maximum.\n\n%$$Q_1 = -z-y \\pm %2500\\cdot\\sqrt{17}$$\n\n%and\n%$$Q_1 = \\dfrac{\\sqrt{2}\\sqrt{-19584Q_3^2+70380000Q_3-23919Q_2^2+69258000Q_2+15051181250} \\pm 319250}{204}$$\n\n%$$Q_2 = -Q_3-Q_1 \\pm 2500\\cdot\\sqrt{17}$$\n%and \n%$$Q_2 = \\dfrac{2\\cdot\\sqrt{14}\\sqrt{-3216Q_3^2+11557500Q_3-3417Q_1^2+10694875Q_1+2336037500} \\pm 679000}{469}$$\n\n%$$Q_3 = -Q_2-Q_1 \\pm 2500\\cdot\\sqrt{17}$$\n%and\n%$$Q_3 = \\dfrac{\\sqrt{6}\\sqrt{-469Q_2^2+1358000Q_2-408Q_1^2+1277000Q_1+535743750}\\pm 86250}{48}$$\n\n%As you may have noticed, each axis has a root something with $\\pm 2500\\cdot\\sqrt{17}$, these would be nice to use if they pass all of the constraints of the problem, however, they fail $Q_T=Q_1+Q_2+Q_3$ since you can rearrange any of those equations to be in the form $$\\pm 2500\\cdot\\sqrt{17} = Q_1 + Q_2 + Q_3$$ So these equations cannot be used if you consider that $750 \\leq Q_T \\leq 3445$, which are the combined bounds of $Q_1,Q_2,Q_3$ and $\\pm 2500\\cdot\\sqrt{17}$ is far from being in that bound.\n\n%%$$P = (-18.89+0.1277Q_1-\\num{4.08e-5}Q_1^2)(170-\\num{1.6e-6}Q_T^2) + (-24.5+0.1358Q_2-\\num{4.69e-5}Q_2^2)(170-\\num{1.6e-6}Q_T^2) + (-27.02+0.1380Q_3-\\num{3.84e-5}Q_3^2)(170-\\num{1.6e-6}Q_T^2)$$\n\n%%$$P = (-18.89+0.1277x-4.08*10^-5*x^2)(170-1.6*10^-6*(x+y+z)^2) + (-24.5+0.1358y-4.69*10^-5*y^2)(170-1.6*10^-6*(x+y+z)^2) + (-27.02+0.1380z-3.84*10^-5*z^2)(170-1.6*10^-6*(x+y+z)^2)$$\n\n%\\section{Discussion of Results}\n%\\subsection{Verification}\n%To verify that this is in fact the optimal flow rate to each turbine we will try some nearby distributions.\n\n%If we try the points (1110,1110,1224), (1109,1110,1225), (1110,1109,1225), (1109,1109,1224) which are all points a little less than the max we get the following distributions\n\n%\\begin{center}\n%\\begin{tabular}{c c}\n%     $P(1110,1110,1224)=$& 23150.97440\\\\\n%%     $P(1109,1110,1225)=$& 23157.57594\\\\\n%     $P(1110,1109,1225)=$& 23152.82133\\\\\n%     $P(1109,1109,1224)=$& 23149.51208\n%\\end{tabular}\n%\\end{center}\n\n%all of these points are less than the max, making the (1110,1110,1225) a max\n\n\\section{More Information}\n\n\\subsection{Turbine Distribution for a Predetermined Max Flow Rate}\nIf the incoming flow never goes beyond 2500 cubic feet per second, the flow must be distributed accordingly to maximize the power generated. As shown in the graph, $Q_2$ maxes at 701.653 and $Q_3$ at 74.24, we then allow the remaining water to flow through $Q_1$ this will result in the max for the situation.\n\n\n\\subsection{More Information}\n\n\\hspace{10mm} \\emph{Turbines to be used if only two are allowed to operate}\n\n\nIf we were to have 1500 cubic feet per second, I would recommend using the $Q_2$ and $Q_3$ due to these ones generating the most amount of power individually.\n\n\\subsection{Recomendation of When the Flow Rate is Near the Hypothetical Maximum Flow Rate of Each Turbine}\n\nIf there was an incoming flow rate of 3400 cubic feet per second I would recommend allowing the maximum allowed flow through both $Q_2$ and $Q_3$, and then allowing the rest of the water to go through $Q_1$, this would generate the greatest amount of power for the situation.\n\n\\section{Conclusion}\nOverall, the best point for the water distribution is when $Q_1 \\approx 790.827$, $Q_2 \\approx 701.53$ and $Q_3 = 24.24$ for $\\approx$ of 16622.984 kilowatts.\n\n\n\\vspace{5mm}\n\n\\hspace{5mm} Let's say that the company discovers that it is sometimes advantageous to only use two turbines, and the incoming flow is 1500 cubic feet per second, the company should use the turbine x and turbine y to generate the most power\n\\vspace{5mm}\n\n\\hspace{5mm} If the incoming flow is 3400 cubic feet per second, the company should take the following action.\n\n\n%%Add everything about the second problem here\n\\chapter{Advertising Budget Analysis for a Personal Computer Manufacturer}\n\\section{Introduction}\n\\emph{This is a problem can be found on page 52 number 6 of \\textit{Mathematical Modeling, Fourth Edition} by Mark M. Meerschaert.}\n\n\\vspace{5mm}\nA manufacturer of personal computers currently sells 10,000 units per month of a basic model. The cost of manufacture is \\$700/unit, and the wholesale price is \\$950. During the last quarter the manufacturer lowered the price \\$100 in a few test markets, and the result was a 50\\% increase in sales. The company has been advertising its product nationwide at a cost of \\$50,000 per month. The advertising agency claims that increasing the advertising budget by \\$10,000/month would result in a sales increase of 200 units/month. Management has agreed to consider an increase in the advertising budget to no more than \\$100,000/month.\n\n\\section{Presentation of the Model}\n\\subsection{Objective}\nWill try to find a price and the advertising budget size that will maximize the total revenue for this manufacturing company.\n\n\\subsection{Variables and Constants}\n\\begin{tabular}{c c}\n    $R= $ & revenue (\\$)\\\\\n    $P= $ & profit (\\$)\\\\\n    $C= $ & costs (\\$)\\\\\n    $U= $ & units of personal computers\\\\\n    $B= $ & advertising budget (\\$/month)\\\\\n    $S= $ & selling wholesale price per unit\\\\\n    $D = $& price drop\\\\\n    $B_i = $& budget increase\\\\\n    $C_m=700=$ & cost to manufacture per unit (in dollars)  \\\\\n    $B_0=50000=$ & initial advertising budget size\\\\\n    $B_m=100000=$ & max advertising budget\\\\\n    $U_0 = 10000=$ & initial number of units sold\\\\\n    $S_0 = 950=$ &initial wholesale price\n\\end{tabular}\n\n\\subsection{Assumptions}\n\\begin{center}\n\\begin{tabular}{c}\n    $P=R-C$   \\\\\n    $p=S_0-D$\\\\\n    $R = UP$\\\\\n    $C= B + C_m*U$\\\\\n    $B = B_0 + B_i$\\\\\n    $U=U_0+(950-S)*50 + \\frac{b-B_0}{U_0}*200$\\\\\n    $B_0 \\leq B \\leq B_m$\\\\\n    $700\\leq P \\leq 950$\n    \n\\end{tabular}\n\\end{center}\n\n\\emph{objective:} Maximize Profits\n\n%Notice how the equation for $U$ has two main components, the next component is the increase of sets sold as the budget for advertising increases which is a linear component since for every dollar increase the number of sets grows at a known amount, in this case by 200. Then there is a quadratic function with very interesting, seemingly random coefficients. This part of the equation was found using a calculator doing linear regressions on the points:\n%\\begin{center}\n%\\begin{tabular}{c}\n %   (950,10000)\\\\\n  %  (850,15000)\\\\\n   % (750,22500)\n%\\end{tabular}\n%\\end{center}\n\n%I chose those points due to the 50\\% increase of sets purchased as a \\$100 decrease in price. I then put these points into the calculator to find a regression between all of them. I could have chosen to use a more exact regression and more points (this would also reduce the overall amount of error in the model, however I felt that this regressed version might be easier to have a calculator use later on in the problem. I chose to do a quadratic regression because the correlation between the points and the function is 1. I could have used a cubic or quadratic regression with added points, however I felt that those would have added too much complexity.\n\n\\section{Solution to Model}\nIn order to proceed we need to obtain our objective function\n\n%We will model this as a constrained optimization problem, and solve it using the method of Lagrange multipliers.\n\n%First we must make a uniform objective equation, which uses the variables $B$ and $S$:\n\n$$P=R-C$$\n\n$$\\left(10000+(950-p)50+\\frac{B-50000}{10000}\\cdot200\\right)p-\\left(B-\\left(10000+(950-p)50+\\frac{B-50000}{10000}\\cdot200\\right)700\\right)$$\n\nwhich reduces to: $$P=\\left(10000+(950-p)50+\\frac{B-50000}{10000}\\cdot 200\\right)(p-700)-B$$\n\nWithout showing it, we have determined that this problem cannot be solved by setting the gradient to zero and solving for the roots, doing that just gives us values outside our bounds. So we shall use Lagrange Multipliers\n\n$$\\nabla P = \\left\\langle-100p+91500+.01B,.02p-15\\right\\rangle$$\n\nWe solve using Lagrange by $$\\nabla f = \\lambda \\nabla g$$\n\nwhere $\\nabla f$ is our objective equation (which is $P$) and $\\nabla g$ is our constraint value: \n\n$$-100p+91500+.02B = 0$$\n$$.02p-15 = \\lambda$$\n\nSolving this for when $B$ is at a minimum (10000) \n\n$$p=935$$\n$$\\lambda = 3.7$$\nand\n$$P = 261250$$\n\nSolving for when $B$ is at a maximum we get \n\n$$B = 100000$$\n$$P(950,10000) = 2650000$$\n\n\n\n\n\\section{Sensitivity Analysis}\n%This is part 2 of the original problem\nWe will now determine the sensitivity of the decision variables (price and advertising) to price elasticity.\n\nWe will assume that $e$ is our price elasticity, we then obtain an equation $$P(p,B,e) = (10000 +e(950-p) + .02(B-50000))(p-700)-B$$\n\nNow we take the corresponding partials from the equation above:\n\n\\begin{center}\n    \\begin{tabular}\n    $\\dfrac{\\partial P}{\\partial p}=-e(p-700)+9000+100e(950-p)+.02a$\\\\\n    $\\dfrac{\\partial P}{\\partial B}=.02p-15$\n    \\end{tabular}\n\\end{center}\n\nNow we use Lagrange Multipliers method to obtain the equation:\n$$\\frac{\\partial P}{\\partial p} = 0$$\n$$\\frac{\\partial P}{\\partial B}=\\lambda$$\n\nby using $B=100000$ we get the values of $p$ and $\\lambda$:\n\n$$P = \\dfrac{275(3D+20)}{e}$$\n$$\\lambda = \\frac{1}{2}\\left(\\dfrac{3e+220}{e}\\right)$$\n\nEvaluating when $p=935$, $B=100000$ (our max point), $e=50$ \n$$S(p,e) = \\dfrac{dp}{de}\\cdot \\dfrac{e}{p}=-.12$$\n\n$$S(B,e)=\\dfrac{dB}{de}\\cdot \\dfrac{e}{p}$$\n\nWhat this means is that a 10\\% increase in the price elasticity the company would notice a 1.2\\% decrease in price but that the advertising budget would not be affected.\n\n\\vspace{5mm}\n%This is part 3 of the original book problem\n\\emph{The advertising agency estimates that the company will gain 200 new sales each time the advertising budget is increased by \\$10,000 per month. The sensitivity analysis is the following:}\n\nThis new assumption gives us the following equations:\n\n$E = $ estimate of new sales per \\$10,000 increase\n\n\\begin{center}\n    \\begin{tabular}{c}\n        $P(p,B,E)=(10000+50(950-p) + \\dfrac{E}{10000}(B-50000))(p-700)-B$\\\\\n        $\\dfrac{\\partial P}{\\partial p}=-100p+91500+\\dfrac{E}{10000}(B-50000)$\\\\\n        $\\dfrac{\\partial P}{\\partial B} = \\dfrac{E}{10000}(p-700)-1$\n    \\end{tabular}\n\\end{center}\n\nBy once again using the Lagrange multiplier method, we set the first partial to zero, and the second to 1; this gives us the following:\n\n$$p = .25 +.05E$$\n$$B=100000$$\n$$\\lambda = \\dfrac{9E}{400}+\\dfrac{E^2}{20000}-1$$\n\nUsing the max point $p=935$ and $B=100000$ as well as using the point $E=200$ we obtain:\n\n$$S(p,e)=\\dfrac{dp}{de}\\cdot \\dfrac{e}{p}=-.12$$\n\n$$S(B,e)=\\dfrac{dB}{de}\\cdot \\dfrac{e}{B}=0$$\n\nWhat this means is that when a 10\\% increase in the price elasticity would result in a 1.2\\% decrease in the profit, and the advertising budget would remain.\n\n\\section{Conclusion}\n%need to describe what \\lambda is. This is part 4 of the original problem\nIn conclusion, the best price to sell the units are at \\$935 and the best size for the advertising budget is \\$100000, this would give the company a total profit of about \\$2650000.\n\nWith or without the price elasticity we discovered that a 10\\% increase in price would result in a 1.2\\% decrease in price, with no affect on the advertising budget.\n\n\n\\end{document}", "meta": {"hexsha": "9931fe5034b2eb93da81c27611b9a8b6df23c460", "size": 21025, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "HW2.tex", "max_stars_repo_name": "stevenglasford/MATH451SDSMT", "max_stars_repo_head_hexsha": "c0fa475cb08a40debda6c106e8ddf8b44dab1060", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW2.tex", "max_issues_repo_name": "stevenglasford/MATH451SDSMT", "max_issues_repo_head_hexsha": "c0fa475cb08a40debda6c106e8ddf8b44dab1060", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW2.tex", "max_forks_repo_name": "stevenglasford/MATH451SDSMT", "max_forks_repo_head_hexsha": "c0fa475cb08a40debda6c106e8ddf8b44dab1060", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.3536036036, "max_line_length": 846, "alphanum_fraction": 0.7076337693, "num_tokens": 7042, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.3487603565866375}}
{"text": "% !TeX spellcheck = en_US\n% !TeX root = DynELA.tex\n%\n% LaTeX source file of DynELA FEM Code\n%\n% (c) by Olivier Pantalé 2020\n%\n\\chapter{Theory}\n\n\\startcontents[chapters]\n\\printmyminitoc[1]\\LETTRINE{T}he \\DynELA~is an Explicit FEM code written in \\Cpp~using a Python's interface for creating the Finite Element Models. \n\n\\section{Introduction}\n\n\\begin{tcolorbox}[width=0.95\\textwidth,myTab,tabularx={l||C|C|C|C|C},title=Homogeneous system of units in mechanics]%,boxrule=0.5pt]\n              & Dimension        & SI (MKS)   & SI (mm-s)  & SI (mm-kg)  & SI (mm-kg-s) \\\\\\hline\\hline\nLength        & $L$              & $m$        & $mm$       & $mm$        & $mm$        \\\\\\hline\nWeight        & $M$              & $kg$       & $T$        & $kg$        & $kg$        \\\\\\hline\nTime          & $T$              & $s$        & $s$        & $ms$        & $s$         \\\\\\hline\nStress        & $ML^{-1}T^{-2}$  & $Pa$       & $MPa$      & $GPa$       & $kPa$       \\\\\\hline\nForce         & $MLT^{-2}$       & $N$        & $N$        & $kN$        & $mN$        \\\\\\hline\nEnergy        & $ML^{2}T^{-2}$   & $J$        & $mJ$       & $J$         & $MJ$        \\\\\\hline\nDensity       & $ML^{-3}$        & $kg/m^{3}$ & $T/mm^{3}$ & $kg/mm^{3}$ & $kg/mm^{3}$ \\\\\\hline\nSpeed         & $LT^{-1}$        & $m/s$      & $mm/s$     & $mm/ms$     & $mm/s$      \\\\\\hline\nAngular speed & $T^{-1}$         & $s^{-1}$   & $s^{-1}$   & $ms^{-1}$   & $s^{-1}$    \\\\\\hline\nAcceleration  & $LT^{-2}$        & $m/s^{2}$  & $mm/s^{2}$ & $mm/ms^{2}$ & $mm/s^{2}$  \\\\\\hline\nCouple        & $ML^{2}T^{-2}$   & $N.m$      & $N.mm$     & $kN.mm$     & $mN.mm$\n\\end{tcolorbox}\n", "meta": {"hexsha": "1cda20a9edb5d7abaf98ea2c9e3d60d359f67488", "size": 1638, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Documentation/Theory-Introduction.tex", "max_stars_repo_name": "pantale/DynELA-v.-4.0", "max_stars_repo_head_hexsha": "2c366859b68df6243a1e128a7839e4fb23888820", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-12-14T20:12:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T14:47:50.000Z", "max_issues_repo_path": "Documentation/Theory-Introduction.tex", "max_issues_repo_name": "pantale/DynELA-v.-4.0", "max_issues_repo_head_hexsha": "2c366859b68df6243a1e128a7839e4fb23888820", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Documentation/Theory-Introduction.tex", "max_forks_repo_name": "pantale/DynELA-v.-4.0", "max_forks_repo_head_hexsha": "2c366859b68df6243a1e128a7839e4fb23888820", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.4827586207, "max_line_length": 148, "alphanum_fraction": 0.4145299145, "num_tokens": 629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3487603565866375}}
{"text": "\\section{FRP}\n\nThe most common solution for the construction of reactive systems in an imperative setting are call-back frameworks, embedded into a loop.\nThe call-backs are either used to query the state of variables, or to change them.\nThis imperative approach is well suited for rapid prototyping of small systems.\nHowever, tracing behaviors over time quickly becomes unmanageably complex for larger systems.\n\nFunctional Reactive Programming instead introduces a concrete abstraction of time that allows the programmer to safely manipulate time-varying values. \nThe key abstraction is given by a \\textit{signal}, providing the programmer with a simple type interface:\n\n\\begin{lstlisting}\n  type Signal a = Time -> a\n\\end{lstlisting}\n\nFor example, the type \\texttt{Signal Image} represents a video, while \\texttt{Signal Steer} captures a steering wheel operated over time.\nTo better understand how our library works, we now introduce the basic concepts and terminology from FRP.\n\n\\subsection{Arrowized FRP}\n\nThere are many types of FRP based on different abstractions from type theory.\nExpressive abstractions, such as monads, allow for complex manipulation of signal flows~\\cite{van2014monadic}. \nHowever, for most applications they are far too expressive.\nWe instead focus on an FRP library, Yampa, which uses the arrow abstraction, or so called Arrowized FRP~\\cite{hudak2003arrows}.\nArrows generally run faster and with little need for manual optimization~\\cite{yallop2016causal}, but are fundamentally less expressive than a monadic FRP~\\cite{lindley2011idioms}.\nThis more restrictive language is in fact a benefit, as it makes it harder for the programmer to introduce errors.\nAs we will see in the sequel, Yampa is still powerful enough to write complex controllers to drive an autonomous vehicle, or even to communicate with other vehicles.\nAt the same time, the syntax is clear and accessible enough to make for an easy introduction to the FRP paradigm.\n\nAlong with signals, Yampa also introduces the abstraction of a \\textit{signal function (SF)}.\nThis is a transformer from one signal to another.\n\n\\begin{lstlisting}\n  type SF a b = Signal a -> Signal b\n\\end{lstlisting}\n\n\\noindent Using the previous signals, imagine a type for a steering function, which operates based on a video stream, such as\n\n\\begin{lstlisting}\n  turn :: SF Image Steer\n\\end{lstlisting}\n\n\\noindent This function processes video and uses it to decide how to steer.\nWe omit an implementation, as the details of the data transformation are not relevant to the structure of the FRP code.\n\nHaskell provides special syntax for Arrowized FRP, which mimics the structure of control flow charts.\nThe syntax provides a composition environment, in which the programmer just manages the composition of arrow functions.\nInputs are read in from the right hand side, and piped to the left hand side (\\texttt{output <- function -< input}).\nA demonstration is given in Listing~\\ref{lst:arrows}.\n\nThe example introduces \n%\n\\begin{lstlisting}\n  avoid :: (Image, Steer) -> Steer\n\\end{lstlisting}\n%\na pure function that adjusts the basic steering plan based on the image to avoid any obstacles.\nIn Listing~\\ref{lst:arrows}, this \\texttt{avoid} function is lifted to the signal level using:\n%\n\\begin{lstlisting}\n  arr :: (a -> b) -> SF a b\n\\end{lstlisting}\n%\nThe function \\texttt{turn} is already on the signal level (has an SF type). Hence, we do not need to lift it.\n\n\\begin{lstlisting}[float,floatplacement=h!,caption=Basic Arrowized FRP syntax,label=lst:arrows]\nmyDriver :: SF Image Steer\nmyDriver = proc image -> do\n  basicSteer    <-     turn  -< image\n  adjustedSteer <- arr avoid -< (image, basicSteer)\n  returnA -< adjustedSteer\n\\end{lstlisting}\n\n\n\\subsection{Stateful FRP}\n\nTo avoid obstacles on the road, we might write an \\texttt{avoid2} function as shown in Listing~\\ref{lst:loop}, which requires two images to calculate the adjusted steering command. \nFor this, we need a mechanism to maintain state between each processing step.\nTwo images would be necessary to filter noise in the image, or calculates the velocity of an approaching obstacle.\nTo implement it, we use an abstraction called \\texttt{ArrowLoop} to  save the previous state of the image for the next processing step.\nThe syntax is presented in Listing~\\ref{lst:loop}.\nIntuitively, \\texttt{ArrowLoop} gives us a recursive computation, as also indicated by the \\texttt{rec} keyword\\footnote{We elide the technical details for the purposes of this presentation and refer the interested reader to~\\cite{paterson2001icfp}.}.\n\n\n\\begin{lstlisting}[float,caption=Using ArrowLoop to send feedback,label=lst:loop]\nmyDriver :: SF Image Steer\nmyDriver = proc image -> do\n  rec\n    oldI          <- iPre null  -< image\n    basicSteer    <-      turn  -< image\n    adjustedSteer <- arr avoid2 -< (image, oldI, basicSteer)\n  returnA -< adjustedSteer\n\\end{lstlisting}\n\nThe predefined function \\texttt{iPre} takes an initial state, in our case an empty image, and saves images for one time step, each time it is processed.\nThis way, we create a feedback loop that is then used in the updated \\texttt{avoid} function.\nAt the same time, the \\texttt{rec} keyword is used to denote a section of arrow code with  mutual dependencies\\footnote{Without the keyword, there is an unresolvable dependency loop.}.\n\n\n\n \n", "meta": {"hexsha": "fc777ce0faf7b5ac237bac750dcde723933def2d", "size": 5330, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/SCAV17/secs/FRP.tex", "max_stars_repo_name": "santolucito/Haskell-TORCS", "max_stars_repo_head_hexsha": "95eef93f7089bbe95f0f28fa21f0f636d7ffc39f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-03-08T14:58:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-14T16:49:06.000Z", "max_issues_repo_path": "paper/SCAV17/secs/FRP.tex", "max_issues_repo_name": "santolucito/Haskell-TORCS", "max_issues_repo_head_hexsha": "95eef93f7089bbe95f0f28fa21f0f636d7ffc39f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/SCAV17/secs/FRP.tex", "max_forks_repo_name": "santolucito/Haskell-TORCS", "max_forks_repo_head_hexsha": "95eef93f7089bbe95f0f28fa21f0f636d7ffc39f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.7722772277, "max_line_length": 251, "alphanum_fraction": 0.7782363977, "num_tokens": 1271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3487603489660664}}
{"text": "\\documentclass[lang=en,mode=geye,device=normal,color=blue,14pt]{elegantnote}\n\\usepackage{amsmath,amssymb}\n\\usepackage{bbm}\n\\usepackage{tcolorbox}\n\\usepackage{graphicx}\n\\usepackage{booktabs}\n \\usepackage{subfigure}\n\n\\DeclareMathOperator*{\\E}{\\mathbb{E}}\n\\DeclareMathOperator*{\\1}{\\mathbbm{1}}\n\\DeclareMathOperator*{\\R}{\\mathbbm{R}}\n\\DeclareMathOperator*{\\argmax}{arg\\,max}\n\\DeclareMathOperator*{\\argmin}{arg\\,min}\n\n\\title{Note: Reinforcement Learning - An Introduction}\n\n%\\author{Yanqing Wu}\n%\\institute{Viwistar Robotics}\n\n% \\version{0.1.0}\n%\\date{\\today}\n\n\\begin{document}\n\\maketitle\n\n\\setlength{\\parindent}{0pt}\n\n\\newpage\n\n\\section{Chap 1: Introduction}\n\\subsection{Reinforcement Learning}\n\nRL is learning what to do, so as to maximize a numerical reward signal.\n\nRL means taking optimal action with \\textbf{long term} results or \\textbf{cumulative rewards} in mind.\n\nTwo most important distinguishing features of RL: trial-and-error search and delayed reward.\n\nRL methods generally incorporate 3 aspects: sensation, action and goal.\n\n\\begin{definition}\n\\textbf{Supervised Learning} is learning from a training set of labeled examples provided by a knowledgable external supervisor.\n\\end{definition}\n\n\\begin{itemize}\n\t\\item Example: a description of a situation\n\t\\item Label: a specification of the correct action the system should take in a situation, which is often to identify a category to which the situation belongs\n\t\\item Object of Supervised Learning: for the system to extrapolate (generalize) its responses s.t. it acts correctly in unseen situations\n\t\\item Con: inadequate for learning from \\textit{interaction}, because it is (often) impractical to obtain examples of desired behavior that are both correct and representative of all the situations in which the agent has to act\n\\end{itemize}\n\n\\begin{definition}\n\\textbf{Unsupervised Learning} is about finding structure hidden in collections of unlabeled data.\n\\end{definition}\nRL is trying to maximize a reward signal, while Unsupervised Learning is trying to find hidden structure.\n\nKey feature 1: the exploration-exploitation dilemma is one of RL's challenges.\nExploitation: to obtain reward from experienced.\nExploration: to find better actions.\n\nKey feature 2: RL explicitly considers the whole problem of a goal-directed agent interacting with an uncertain environment.\n\n\\subsection{Examples}\n\\subsection{Elements of RL}\n\nFour main subelements of a RL system: a \\textit{policy}, a \\textit{reward signal}, a \\textit{value function}, and a \\textit{model} of the environment.\n\n\\begin{definition}\n\\textbf{Policy}, defines the learning agent's way of behaving at a given time.\n\\end{definition}\n\nA policy is a mapping from perceived states of the environment, to actions to be taken, when in those states.\nA policy may be a simple function or a lookup table, or complex computation (e.g. a search process).\nPolicies may be stochastic, specifying probabilities for each action.\n\n\\begin{definition}\n\\textbf{Reward signal}, defines the goal of a RL problem.\n\\end{definition}\n\nOn each timestep, the environment sends a single number (i.e. \\textit{reward}) to the RL agent. The agent's only objective is to maximize the total reward it receives over the long run.\n\n\\begin{definition}\n\\textbf{Value function}, specifies what is good in the long run.\n\\end{definition}\n\nThe \\textit{value} of a state is the total amount of reward an agent can expect to acumulate over the future, starting from that state.\n\n!! \\textit{Rewards} determine the immediate desirability of states, \\textit{values} determines the long-term desirability of states.\n\nState Value function = Expected Return = Discounted sum of all rewards\n\n\\begin{definition}\n\\textbf{Model}, mimics the behavior of the environment.\n\\end{definition}\n\nThe model defines the reward function and transition probabilities. Models are used for \\textit{planning}.\nModel-based methods: use models and planning to solve RL problems.\nModel-free methods: explicitly trial-and-error learner (almost the opposite of planning).\n\nModern RL spans the spectrum from low-level, trial-and-error learning to high-level, deliberative planning.\n\n\\subsection{Limitations and Scope}\n\\subsection{An Extended Example: Tic-Tac-Toe}\nMinimax algorithm \\cite{wiki_minimax} (from game theory).\n\nClassical optimization methods are for sequential decision problems (e.g. dynamic programming). We need to estimate an approximate opponent model so to use dynamic programming; in such case, this is similar to RL methods.\n\nDuring playing, we need to adjust the values of the states as to make more accuracte estimates of the probabilities of winning. The current value of the earlier state is updated to be closer to the value of the later state. This can be done by moving the earlier state's value a fraction of the way toward the value of the later state.\n\n\\begin{equation}\nV(S_t) \\leftarrow V(S_t) + \\alpha[V(S_{t+1}) - V(S_t)]\n\\end{equation}\n\n$S_t$, the state before a move.\n$S_{t+1}$, the state after the move.\n$V(S_t)$, the update to the estimated value of $S_t$.\n$\\alpha$, step-size parameter, a small positive fraction, influences the rate of learning.\n\nThis update rule is an example of a temporal-difference (TD) learning method. TD means the changes are based on a difference between estimates at two consecutive times.\n\nIf $\\alpha$ is reduced properly over time, then this method converges (for any fixed opponent, it converges to the true probabilities of winning for each state); if $\\alpha$ is not reduced to zero over time, then the agent ``also plays well against opponents that slowly change their way of playing'' (?). My understanding is that, there must have some slow changes, whether the parameter or the opponent model.\n\n\\textbf{Evolutionary methods vs. Value Function methods.} Evolutionary methods ignores what happens during the games, and only the final outcome of each game is used (e.g. all of its behavior in a winning game is given credit). In contrast, value function methods evaluate individual states.\n\nIn this example, learning started with no prior knowledge except the rules of the game. In reality, prior information can be incorporated into RL in many ways for efficient learning.\nRL can be used when we have access to true state, or where some states are hidden, or when different states appear to be the same to the learner.\n\nThe player need a model of the game to see the result states in response to actions. While model-free systems cannot know how their environments will change in response to actions.\nModel-free methods are building blocks for model-based methods.\nSometimes, it is difficult to construct an accurate environment model, thus model-based methods cannot be used in such cases.\n\n\\subsection{Summary}\n\nRL is a computational approach to understanding and automating goal-directed learning and decision making.\nIt is distinguished from other computational approaches by its emphasis on learning by an agent from direct \\textbf{interaction} with its environment, without requiring exemplary supervision or complete models of the environment.\n\nRL uses the formal framework of Markov decision processes (MDP) to defined the interaction between a learning agent and its environment in terms of states, actions, and rewards.\n\nThe concepts of value and value function are key to most of the RL methods in this book.\nThe authors believe that value functions are critical for efficient search in policy space.\nThe use of value functions distinguishes RL methods from evolutionary methods.\n\n\\subsection{Early History of RL}\n\nThree threads: \n1. learning by trial and error, originated in the psychology of animal learning. Time from 1850s to early 1980s' revival of RL;\n2. optimal control problem and its solution using value functions and dynamic programming. This thread did not involve learning;\n3. temporal-difference methods.\nThese 3 threads came together in late 1980s.\nThe TD and optimal control threads were fully brought together in 1989 with Chris Watkin's development of Q-learning.\n\nThe essential idea of trial-and-error learning: `the drive to achieve some result from the environment, to control the environment toward desired ends and away from undesired ends.'\n\nTD learning methods are driven by the difference between temporally successive estimates of the same quantity.\n\nThe authors developed a method for using TD learning + trial-and-error learning, known as the \\textit{actor-critic architecture}.\n\n\\newpage\n\\textbf{Part I: Tabular Solution Methods}\n\nAlgorithms in this part are described in simplest forms: the state space and action space are small enough for the approximate value functions to be represented as arrays/tables.\nIn this case, the methods can (often) find exact solutions (i.e. optimal value function and optimal policy).\nAlgorithms in next part can only find approximate solutions but can be applied to much larger problems.\n\n\\textbf{Bandit problems}, RL problem with only a single state. Chap 2 describes general problem formulation (finite MDP) and its main ideas (including Bellman equations and value functions).\n\nThree fundamental classes of methods for solving MDP problems: dynamic programming, Monte Carlo methods and TD learning.\n\\begin{itemize}\n\\item DP: well developed, but require a complete and accurate model of the environment\n\\item MC: no model needed, but not good for incremental computation\n\\item TD: no model needed and fully incremental, but are complex\n\\end{itemize}\n\n\\newpage\n\\section{Chap. 2 Multi-armed Bandits}\n\\begin{itemize}\n\\item Evaluative: feedback depends solely on the taken action\n\\item Instructive: feedback is independent of the taken action\n\\item Nonassociative setting: no learning involved in more than one situation; no need to associate different actions with different situations/states\n\\item Associative setting: the best action depends on the situation\n\\end{itemize}\n\n\\subsection{A k-armed Bandit Problem}\n\n\\textit{k-armed bandit problem}:\nYou choose one option (action) from \\textit{k} different options (actions). The probability of choosing each option (action) is stationary. For each choice, you receive a (probably distinct) numerical reward. Your objective is to maximize the expected total reward over \\textit{j} option selections (time steps).\n\nFor now, let us define that\n\\begin{itemize}\n\\item \\textit{Value}: the expected/mean reward of a taken action\n\\item $A_t$: action selected on time step $t$\n\\item $R_t$: corresponding reward of $A_t$\n\\item $q_{*}(a)$:  $q_{*}(a) \\doteq \\E[R_t|A_t=a]$. The (true) value of an arbitrary action $a$ (i.e. the expected reward given $a$ is selected)\n\\item $Q_t(a)$: the \\textit{estimated} value of action $a$ at time step $t$.\n\\end{itemize}\n\nIf we know each action values, then solving the \\textit{k}-armed bandit problem would be always select the action with highest $value$.\nIf we don't know the action values, then we can estimate them.\nOur goal is to have $Q_t(a)$ to be as close to $q_*(a)$ as possible.\n\n\\begin{definition}\n\\textbf{Greedy actions}, action(s) with highest \\textbf{estimated} value.\n\\end{definition}\n\\textit{exploiting}: select greedy action(s).\n\\textit{exploring}: select non-greedy action(s). Exploration may improve the estimate value of non-greedy actions.\n\n\\subsection{Action-value Methods}\n\n\\begin{definition}\n\\textbf{Action-value Methods}, or Q function, methods for estimating the values of actions, and using the estimates to select actions.\n\\end{definition}\n\n`Q' means the \\textbf{quality} of an action.\n\nLet see a simple action-value method: \\textit{sample-average method}, in which action-value is the mean reward for an action.\n\n$$ Q_t(a) \\doteq \\frac{\\sum_{i=1}^{t-1}R_i \\cdot \\1_{A_{i=a}}}{\\sum_{i=1}^{t-1}\\1_{A_{i=a}}}$$\n\n\\begin{itemize}\n\t\\item $\\1$: return 1 if predicate is true, otherwise 0\n\t\\item in the case when denominator is 0 (which makes the fraction mathematically undefined), $Q_t(a)$ is set as default value (e.g. 0)\n\t\\item in the case when denominator $\\rightarrow \\infty$, by the Law of Large Numbers, $Q_t(a)$ converges to $q_*(a)$\n\\end{itemize}\n\n\\begin{definition}\n\\textbf{Greedy action selection}, If there are more than one greedy action, select one of them arbitrarily.\n$$ A_t \\doteq \\argmax_{a} Q_t(a) $$\n\\end{definition}\n\n\\begin{definition}\n\\textbf{$\\varepsilon$-greedy action selection} with probability $\\varepsilon$, select an action randomly; with probability $1-\\varepsilon$, select a greedy action\n\\end{definition}\n\n\\subsection{The 10-armed Testbed}\n\nFor Exercise 2.2, note that we should first convert the sequence of actions and rewards to $Q_t(a)$, then we can decide whether the selection is greedy or exploration based on the definition of $\\varepsilon$-greedy action selection.\n\n\\subsection{Incremental Implementation}\n\nRecall that estimated action value $Q_n$, using sample-average method, is calculated as:\n$$ Q_n \\doteq \\frac{R_1 + \\cdots + R_{n-1}}{n-1} $$\n\nWe don't want to waste memory and computational resource for each new reward.\nIntuitively, to save memory, we can simplify the equation by first reconstruct the previous estimated action value $Q_{n-1}$ and then evaluate $Q_n$ with the new reward $R_n$.\nTherefore,\n$$ Q_{n+1} = \\frac{Q_n \\cdot (n-1) + R_n}{n} = \\frac{Q_n \\cdot n - Q_n + R_n}{n} = Q_n + \\frac{1}{n}[R_n - Q_n] $$\n\nThe form $Q_{n+1} = Q_n + \\frac{1}{n}[R_n - Q_n]$ is an important form occurs in this book. The general form is\n$$ NewEstimate \\leftarrow OldEstiamt + StepSize\\underbrace{[Target - OldEstimate]}_{error} $$\n\n% \\begin{tcolorbox}[width=\\textwidth,colback={grey},title={A simple bandit algorithm},colbacktitle=black,coltitle=white]}\n\\begin{tcolorbox}[width=\\textwidth,title={A simple bandit algorithm}]\n\t\\begin{align*}\n\t   & \\text{Initialize, for a = 1 to }k: \\\\\n\t   & \\quad Q(a) \\leftarrow 0 \\\\\n\t   & \\quad N(a) \\leftarrow 0 \\\\\n\t   & \\text{Loop forever: }\\\\\n\t   & \\quad A \\leftarrow \\left\\{\n\t    \\begin{array}{ll}\n\t        \\argmax_x Q(a) & \\text{with prob. } 1 - \\varepsilon \\text{ (breaking ties randomly) }\\\\\n\t        \\text{a random action} & \\text{with prob. } \\varepsilon\n\t    \\end{array}\n\t\\right. \\\\\n\t   & \\quad R \\leftarrow bandit(A) \\\\\n\t   & \\quad N(A) \\leftarrow N(A) + 1 \\\\\n\t   & \\quad Q(A) \\leftarrow Q(A) + \\frac{1}{N(A)}[R-Q(A)]\n\t\\end{align*}\n\\end{tcolorbox}\n\n\\subsection{Tacking a Nonstationary Problem}\n\nIn previous section, the reward probability distribution is stationary (i.e. doesn't change over time).\nFor nonstatoinary cases, let say we give more weight to recent rewards than to `long-past' rewards; for doing so, one popular way is to use a constant $\\alpha$ (step size).\n\nNot all choices of $\\alpha_n(a)$ guarantee convergence.\nIn \\textit{stochastic approximation theory}, two conditions required to assure convergence ``with probability 1''\\footnote{i.e. \\textit{almost sure}. No distinction between `sure' and `almost sure' in finite sample space, but becomes important in infinite sample space. see \\url{https://en.wikipedia.org/wiki/Almost_surely}}:\n\n$$ \\sum_{n=1}^\\infty \\alpha_n(a) = \\infty $$\n$$ \\sum_{n=1}^\\infty \\alpha_n^2(a) < \\infty $$\n\nThe 1st condition is required to guarantee that the steps are large enough to eventually overcome any initial conditions or random fluctuations.\nThe 2nd condition is required to guarantee that the steps eventually become small enough to assure convergence.\n\nTherefore, in sample-average method, $\\alpha_n(a) = \\frac{1}{n}$ converages, but a constant step-size parameter $\\alpha_n(a)=\\alpha$ does not converge.\n\nNote that sequences of $\\alpha$ that meet the conditions often converge very slowly and often need considerable tunning.\nThese sequences of $\\alpha$ often used in theoretical work, and are seldom used in real-world application.\n\n\\subsection{Optimistic Initial Values}\n\nHigher (more optimistic) initial values may result in better performance. More optimistic initial values ($Q_i(a)$) encourages more exploration.\nThis may only work well on stationary problems; as in nonstationary problems, the drive for exploration is inherently temporary.\n\n\\subsection{Upper-Confidence-Bound Action Selection}\n\nIn $\\varepsilon$-greedy action selection, it is not ideal to just randomly select actions; instead, we want to select among the non-greedy actions according to their potential for actually being optimal. Such taking into account both (1) how close their estimates are to being maximal, and (2) the uncertainties in those estimates.\n\n\\begin{definition}\nUpper-Confidence-Bound (UCB) Action Selection\n\n\\[\nA_t \\doteq \\argmax_a \\bigg[ Q_t(a) + c\\sqrt{\\frac{\\text{ln }t}{N_t(a)}} \\bigg]\n\\]\n\\end{definition}\n$N_t(a)$, denotes the number of times that action $a$ has been selected prior to time $t$. If $N_t(a)=0$, then $a$ is considered to be a maximizing action.\n$c$, $c > 0$ (confidence level) controls the degree of exploration\n\nThe idea of UCB action selection is that the square-root term is a measure of the uncertainty/variance in the estimate of $a$'s value.\nEach time $a$ is selected, the uncertainty is (presumably) reduced as $N_t(a)$ increments.\nEach time a non-$a$ is selected, $t$ increments but $N_t(a)$ doesn't, thus the uncertainty estimate increases.\nAll actions will eventually be selected, but actions with lower value estimates or that have been frequently selected, will be selected with decreasing frequency over time.\n\nUCB is useful in bandit problems, but is (usually) not practical in general RL settings. It is difficult to deal with (1) nonstationary problems, and (2) large state spaces.\n\n\\subsection{Gradient Bandit Algorithms}\nWe have considered methods that (1) estimate actions values; (2) select actions based on estimations.\nWe now consider a new approach for action selection: learning a numerical \\textit{preference} for each action \\textit{a}, which we denote $H_t(a) \\in \\R$.\nThe larger the preference, the more often that action is taken, but the preference has no interpretation regarding rewards.\nOnly the \\textbf{relative} preference of one action over another is important.\nThe action probabilities is determined by \\textit{soft-max distribution}.\n\n\\[\nP(A_t=a) \\doteq \\frac{e^{H_t(a)}}{\\sum_{b=1}^k e^{H_t(b)}} \\doteq \\pi_t(a)\n\\]\n\n$\\pi_t(a)$ is the probability of taking action $a$ at time $t$. The initial probability are the same for all actions.\n\nThere is a natural learning algorithm in this setting based on the idea of stochastic gradient descent.\nThis is based on updating the preference values as such, after taking action $A_t$ and obtaining reward $R_t$\n\n$$ H_{t+1}(A_t)\\doteq H_t(A_t) + \\alpha (R_t - \\overline{R_t})(1-\\pi_t(A_t)) $$\n\n$$ H_{t+1}(a) \\doteq H_t(a) - \\alpha(R_t - \\overline{R_t})\\pi_t(a)\\quad\\text{for all }a\\neq sA_t $$\n\n$\\overline{R_t} \\in \\R $ is the average of the rewards up to but not including time $t$ (with $\\overline{R_1} = R_1$)\n\nIf the reward is higher than the baseline $\\overline{R_t}$, then the probability of taking $A_t$ in the future is increased; and if the reward is below baseline, then the probability is decreased.\nThe non-selected actions move in the opposite direction.\n\nThe above update scheme is equivalent to \\textbf{stochastic gradient ascent} with bath size 1.\n\n\\subsection{Associative Search (Contextual Bandits)}\n\nFor now, we have only considered nonassociative tasks, that is, tasks in which there is no need to associate different actions with different situations.\nHowever, in the general RL task, there is more than one situation (state?), and the goal is to learn a policy, i.e., a mapping from states to optimal actions given the state.\n\nSuppose when a bandit task is selected for you, you are given some distinctive clue about its identity (but not its action values). For instance, if screen=red (actual reward is hidden from you), select arm 1; if screen=green, select arm 2... This is an example of an associative search task, it involves both trial-and-error learning to search for the best actions, and association of these actions with the situations in which they are best. This task is now called \\textit{contextual bandits} in the literature.\n\nIn this setting, we still don't have actions affecting the next situation as well as the reward. This will add another layer of complexity and lead us to full RL problems.\n\n\\begin{itemize}\n\\item (level 1) $k$-armed bandit problem: select one of $k$ actions that have fixed probabilities. For each selected action, a reward is given. The goal is to maximize the total reward after $j$ selections.\n\\item (level 2) associative search task (contextual bandits): Same as $k$-armed bandit problem, the action affects only the immediate reward. Unlike $k$-armed bandits problem, what situations/state you are facing are told and it involves learning a policy.\n\\item (level 3) full RL problem: On top of associative search task, actions affect next situation and reward.\n\\end{itemize}\n\n\\subsection{Summary}\n\nThis chapter presented several ways to balance exploration and exploitation:\n\n\\begin{itemize}\n\\item $\\varepsilon$-greedy methods choose randomly among actions a small fraction of the time to encourage exploration\n\\item UCB methods choose deterministically but favouring actions with uncertain estimates\n\\item Gradient methods don't estimate action values, but preferences, and choose actions probabilistically according to the preferences\n\\item Optimistic initialization sets optimistic initial $Q$ values in order to encourage a very active exploration in the initial phase, leading to a fast convergence with no bias\n\\end{itemize}\n\nThere is no method among the above that is best. Common ways to assess performance of these kind of algorithms are through graphs:\n\\begin{itemize}\n\\item learning curve: shows the performance of an algorithm vs. iterations for a certain parameter setting\n\\item parameter studies: summarize each algorithm by the average reward over the first 1000 steps, and show such a value for various parameter settings and algorithms.\n\\end{itemize}\n\nOne should also consider the sensitivity to parameter setting, that is an indication of \\textbf{robustness}.\n\nDespite the simplicity of methods presented in this chapter, they can be considered state of the art. More sophisticated methods usually impose additional complexity and assumptions.\n\nAnother approach to balancing exploration and exploitation in $k$-armed bandit problems is to compute a special kind of action value called \\textit{Gittins index}, which is an instance of Bayesian methods. This assume a known initial distribution over the (stationary) action values and then update the distribution exactly after each step.\nIn general, the update computations are complex, but for \\textit{conjugate priors} they are easy.\nOne way to select the best action at each time step is based on posterior probability.\nThis method, sometimes called posterior sampling or Thompson sampling.\n\n\\newpage\n\\section{Finite Markov Decision Processes}\n\n\\begin{definition}\nfinite Markov Decision Processes, involves evaluative feedback (as in bandits) and associative settings (choosing different actions in different situations)\n\\end{definition}\n\nMDPs are a classical formalization of \\textit{sequential} decision making, where actions influence both immediate rewards and subsequent situations/states (thus influence future rewards as well).\nMDPs involves delayed reward. MDPs need to consider trade-off between immediate reward and delayed reward.\n\nIn bandit problems, we estimated the value $q_{*}(a)$ of each action $a$.\n\nIn MDPs, we estimate $q_{*}(s,a)$ (value of each action $a$ in each state $s$), or $v_{*}(s)$ (value of each state given optimal action selections).\n\nMDPs are an ideal form of the RL problem where precise theoretical statements can be made.\nKey elements of RL's mathematical structure: returns, value functions, and Bellman equations.\n\n\\subsection{The Agent-Environment Interface}\n\n\\begin{itemize}\n\\item agent: learner and decision maker\n\\item environment: everything outside the agent, and which agent interacts with\n\\end{itemize}\n\n\\begin{figure}[!h]\n  \\includegraphics[width=\\linewidth]{MDP_interface.PNG}\n  \\caption{The agent-environment interaction in a MDP}\n  \\label{fig:MDP_interface}\n\\end{figure}\n\nAt each time step $t$, the agent receives some representation of the environment's $state$, $S_t$, and on the state selects an $action$, $A_t$. One time step later, the agent receives reward $R_{t+1}$ as a result of the action, and find itself in a new state $S_{t+1}$. The trajectory/sequence is:\n\n$$ S_0, A_0, R_1, S_1, A_1, R_2, S_2, A_2, R_3, \\cdots $$\n\nIn a \\textit{finite} MDP, the state sets, action sets and reward sets are finite.\n\nFollowing defines the \\textit{dynamics} of the MDP.\n\n$$ p(s', r| s, a) \\doteq P(S_t = s', R_t = r | S_{t-1} = s, A_{t-1} = a) $$\n$$ \\sum_{s' \\in \\mathcal{S}} \\sum_{r \\in \\mathcal{R}} p(s',r|s,a) = 1, \\forall s \\in \\mathcal{S}, a \\in \\mathcal{A}(s) $$\n\n$p$ specifies a probability distribution for each choice of $s$ and $a$.\nThe probability of each possible value for $S_t$ and $R_t$ depends on the immediately preceding state and action, $S_{t-1}$ and $A_{t-1}$ (note not including earlier states and actions).\n\n\\begin{definition}\nMarkov property\\footnote{Markov property refers to the memoryless property of a stochastic process}, the future only depends on the current state, not the history.\n\\end{definition}\n\n\\begin{definition}\nstate-transition probabilities,\n$$ p(s'|s,a) \\doteq P(S_t=s'|S_{t-1}=s, A_{t-1}=a) = \\sum_{r\\in \\mathcal{R}} p(s',r|s,a) $$\n\\end{definition}\nWe can express state transition probabilities in an Matrix as shown in Figure \\ref{fig:state-trans-prob-eg}. Each row in the matrix represents the probability from moving from our original or starting state to any successor state. Sum of each row is equal to 1.\n\\begin{figure}[h!]\n  \\includegraphics[width=\\linewidth]{state_transition_probability_example.jpg}\n  \\caption{An example of state transition probability.}\n  \\label{fig:state-trans-prob-eg}\n\\end{figure}\n\n\\begin{definition}\nexpected rewards for state-action pairs\n\n$$ r(s,a) \\doteq \\E [R_t | S_{t-1}=s, A_{t-1}=a] = \\sum_{r\\in \\mathcal{R}} \\sum_{s\\in \\mathcal{S}} p(s',r|s,a) $$\n\\end{definition}\n\n\\begin{definition}\nexpected rewards for state-action-nextState,\n\n$$ r(s,a,s') \\doteq \\E [R_t | S_{t-1}=s, A_{t-1}=a, S_t=s'] = \\sum_{r \\in \\mathcal{R}} r \\frac{p(s',r|s,a)}{p(s'|s,a)} $$\n\\end{definition}\n\n\n\\paragraph{agent-environment}\nThe agent-environment boundary represents the lit of the agent's absolute control, not of its knowledge. Anything that cannot be changed by the agent.\n\nAny problem of learning goal-directed behavior can be reduced to 3 signals passing back and forth between an agent and its environment:\n\\begin{itemize}\n\\item action: the choice made by the agent\n\\item the basis on which the choice is made\n\\item the agent's goal\n\\end{itemize}\n\n\\begin{example}\nBioreactor,\n\n\\begin{itemize}\n\\item actions (vector): target temperatures, target sitrring rates\n\\item states (vector): sensory readings, ingredients input, target chemical\n\\item rewards (number): production rate of useful chemical (target)\n\\end{itemize}\n\n\\end{example}\n\n\\begin{example}\nRobotic Arm (pick-and-place task)\n\n\\begin{itemize}\n\\item actions: voltages applied to each joint motor\n\\item states: readings of joint angles and velocities\n\\item rewards: +1 for successfully object pick-and-place; small negative reward at each time step (punish jerkiness motion)\n\\end{itemize}\n\\end{example}\n\n\n\\subsection{Goals and Rewards}\n In RL, thr purpose/goal of the agent is to maximize \\textit{cumulative reward in the long run}.\n It is important that the set-up rewards indicate what we truly want accomplished.\n In particular, rewards are not the place to tell/impart agent prior knowledge about \\textit{how} to achieve our goal.\n For example, in a chess game, the agent should only be reward for winning, instead of achieving subgoals like taking opponent's pieces.\n Better places for imparting this kind of prior knowledge in (1) initial policy; or (2) initial value function.\n \n The reward signal is a way of imparting to the agent \\textit{what} you want achieved, not \\textit{how} you want it achieved.\n\n\\subsection{Returns and Episodes}\n\nA RL agent's goal is to maximize the cumulative reward it receives in the long run.\nIn general, we seek to maximize the \\textit{expected return} $G_t$.\n\n$$ G_t \\doteq R_{t+1} + R_{t+2} + \\cdots + R_T $$\n\nwhere $T$ is a final time step.\n\nThe final time step marks the end of a subsequences.\n\n\\begin{definition}\nEpisode, a subsequence of the agent-environment interaction. Each episode ends in \\textbf{terminal state}, followed by a \\textbf{reset} to a standard starting state or to a \\textbf{sample} from a standard distribution of starting states. The next episode begins independently of how the previous one ended.\n\\end{definition}\n\nThe set of all nonterminal states, $\\mathcal{S}$. All states and the terminal state, $\\mathcal{S^+}$.\n\n\\begin{definition}\nEpisodic tasks, tasks with episodes that with terminal state.\n\\end{definition}\n\n\\begin{definition}\ncontinuing tasks, tasks without terminal state.\n\\end{definition}\n\nThis task uses discounted rewards to deal with $T=\\infty$.\n\n\\begin{definition}\ndiscounted rewards $G_t$. discount rate, $0 \\leq \\gamma \\leq 1$\n\n$$ G_t \\doteq R_{t+1} + \\gamma R_{t+2} + \\gamma^2 R_{t+3} + \\cdots = \\sum_{k=0}^{\\infty} \\gamma^k R_{t+k+1} $$\n\\end{definition}\n\nThe discount rate determines the present value of future rewards. As long as the reward sequence {$R_k$} is bounded, the infinite sum $G_t$ has a finite value.\nIf $\\gamma \\rightarrow 0$, the agent is myopic; if $\\gamma \\rightarrow 1$, the agent is farsighted.\n\nIf the reward is constant $R$, then we have the \\textit{geometric series}\n\n$$ G_t = \\sum_{k=0}^{\\infty} R\\gamma^k = R\\frac{1}{1-\\gamma} $$\n\nNote that the returns at successive time steps are related to each other (which is important for RL):\n\n$$ G_t \\doteq R_{t+1} + \\gamma R_{t+2} + \\gamma^2 R_{t+3} + \\cdots = R_{t+1} + \\gamma G_{t+1} $$\n\n\\begin{example} pole-balancing\n\\begin{itemize}\n\\item terimnal state: if the pole falls past a given angle from vertical or if the cart runs off the track\n\\item starting state: pole reset to vertical\n\\item reward (episodic): +1 for each time step before falling\n\\item reward (continuing): -1 on each falling, 0 for all other times\n\\end{itemize}\n\\end{example}\n\n\n\\begin{figure}[!h]\n  \\includegraphics[width=\\linewidth]{MDP_pole.PNG}\n  \\label{fig:MDP_pole}\n\\end{figure}\n\n\n\n\\subsection{Unified Notation for Episodic and Continuing Tasks}\n\nWe use $S_{t,i}$ to represents state at time $t$ of episode $i$ (same for $A_{t,i}$, $R_{t,i}$, etc).\nIn practice, we dropped the $i$ as we normally don't have to distinguish between different episodes.\nSo, now $S_t$ refers to $S_{t,i}$.\n\nWe use an $absorbing state$ to replace the terminate state. The absorbing state transits to itself and have reward = 0.\nThis way, we can have the same formula of $G_t$ for episodic and continuing tasks.\n\n\\subsection{Policies and Value Functions}\n\nValue functions (either V or Q) are \\textbf{always} conditional on some policy $\\pi$. Sometimes in literature we leave off the $\\pi$ or $*$ and just refer to $V$ and $Q$, because it’s implicit in the context, but ultimately, every value function is always with respect to some policies.\n\n\\begin{definition}\nThere are two value functions:\n\\begin{itemize}\n\\item value functions of states, or V, estimate how much expected return it is received for the agent to be in a given state;\n\\item value functions of state-action pairs, or Q, estimate how much expected return it is received to perform a given action in a given state.\n\\end{itemize}\n\\end{definition}\n\n\\begin{definition}\npolicy, $\\pi(A_t=a|S_t=s)$, a mapping from states to probabilities of selecting each action\n\\end{definition}\n\nExpectation of $R_{t+1}$ in terms of $\\pi$ and the four-argument function $p$:\n\\[\n\\E\\left[R_{t+1} \\middle|S_{t}\\right] = \\sum_{a \\in \\mathcal{A}} \\pi\\left(a \\middle| S_t\\right) \\cdot r(S_t, a) = \\sum_{a \\in \\mathcal{A}} \\pi\\left(a \\middle| S_t\\right) \\cdot \\sum_{r \\in \\mathcal{R}} r \\sum_{s' \\in \\mathcal{S}} p\\left(s', r \\middle| S_t, a\\right)\n\\]\nMy word explanation: the expectation of reward given current state $S_t$= the total sum of the probability of perform action $a$ at state $s$ $\\cdot$ the reward $r$ $\\cdot$ the probability of getting reward $r$ (when performs action $a$ at state $s$) (?)\n\n\\begin{definition}\nstate-value function for policy $\\pi$, (value function of a state $s$ under a policy $\\pi$), $v_{\\pi}(s)$, is the expected return when starting in $s$ and following $\\pi$ thereafter. For MDPs:\n\n$$ v_\\pi(s) \\doteq \\E_\\pi[G_t | S_t = s] = \\E_\\pi [ \\sum_{k=0}^{\\infty} \\gamma^k R_{t+k+1} | S_t = s], \\forall s \\in \\mathcal{S} $$\n\\end{definition}\n\n\\begin{definition}\naction-value function for policy $\\pi$, (value of taking action $a$ in state $s$ under a policy $\\pi$), $q_\\pi(s,a)$, as the expected return starting from $s$, taking the action $a$, and \\textbf{then} following policy $\\pi$:\n\n$$ q_\\pi(s,a) \\doteq \\E_\\pi [G_t | S_t = s, A_t = a] = \\E_\\pi [\\sum_{k=0}^{\\infty} \\gamma^k R_{t+k+1} | S_t = s, A_t = a] $$\n\\end{definition}\n\nThe main difference between $Q$ and $V$ then, is the $Q$-value lets you play a hypothetical of potentially taking a different action in the first time step than what the policy might prescribe and then following the policy from the state the agent winds up in.\n\\newline\n\nEquation of $v_\\pi$ in terms of $q_\\pi$ and $\\pi$:\n$$ v_\\pi(s) = \\sum_a \\pi(a|s)q_\\pi(s,a) $$\n\nMy word explanation: the value function is the total sum of probability of choosing action $a$ at state $s$ $\\times$ the action-value of taking each action.\n\\newline\nEquation of $v_\\pi$ in terms of $\\pi$ and $p$:\n\\begin{align*}\nv_\\pi(s) & \\doteq \\E_\\pi[G_t | S_t = s]\\\\\n& = \\E_\\pi[R_{t+1} + \\gamma G_{t+1} | S_t = s]\\\\\n& = \\sum_a \\pi(a|s) \\sum_{s'}\\sum_r p(s',r|s,a) [r+ \\gamma \\E_\\pi[G_{t+1} | S_{t+1}=s']]\\\\\n& = \\sum_a \\pi(a|s) \\sum_{s',r} p(s',r|s,a) [r+ \\gamma v_\\pi(s')]\n\\end{align*}\n\nEquation of $q_\\pi$ in terms of $v_\\pi$ and the four argument $p$\n$$ q_\\pi(s,a) = \\sum_{s', r} p(s',r|s,a) \\underbrace{ [r+\\gamma v_\\pi(s')] }_{G_t?} $$\n\n\\begin{definition}\nMonte Carlo methods, estimation methods that involve averaging over many random samples of actual returns.\n\\end{definition}\n\nFor example, an agent follows policy $\\pi$; and for each state $s$, the agent maintains an average of the actual returns which have followed that state, then the average converges to the state's value $v_\\pi(s)$. (Recall the Law of Large Numbers, or sample-average method in Chapter 2).\nFor another example, if separate averages are kept for each action taken in each state, then these averages will similarly converge to the action values $q_\\pi(s,a)$.\n\n\\begin{definition}\nBellman equation for $v_\\pi$:\n\n$$ v_\\pi = \\sum_a \\pi(a|s) \\sum_{s',r} p(s',r|s,a) [r+ \\gamma v_\\pi(s')] $$\n\\end{definition}\n\nIt expresses a relationship between the value of a state and the values of its successor states.\n\n\\begin{figure}[!h]\n  \\centering\n  \\includegraphics[]{MDP_backup.PNG}\n  \\caption{Backup diagram for $v_\\pi$}\n  \\label{fig:MDP_backup}\n\\end{figure}\nNote that in backup diagram, the nodes do not necessarily represent distinct states (e.g. a state might be its own successor).\n\nThe value function $v_\\pi$ is the unique solution to its Bellman equation (??). My understanding is that since $v_\\pi$ is the only solution, meaning that $v_\\pi$ must converge to a point?\n\n\\begin{definition}\nBellman equation for $q_\\pi$:\n\n$$ q_\\pi(s,a) \\doteq \\E_\\pi [G_t | S_t = s, A_t = a] = \\sum_{s',r} p(s',r|s,a)[r+\\gamma \\sum_{a'} \\pi(a'|s')q_\\pi (s',a')] $$\n\\end{definition}\n\n\\begin{figure}[!h]\n  \\centering\n  \\includegraphics[]{MDP_backup_Qpi.PNG}\n  \\caption{Backup diagram for $q_\\pi$}\n  \\label{fig:MDP_backup_qpi}\n\\end{figure}\n\n\\begin{figure}[!h]\n    \\centering\n    \\subfigure[]{\\includegraphics[width=\\textwidth]{MDP_1.PNG}}\n    \\subfigure[]{\\includegraphics[width=\\textwidth]{MDP_2.PNG}}\n    \\caption{ (a) $ v_\\pi(s)=\\sum_a \\pi(a|s)q_\\pi(s,a) $ (b) $ q_\\pi(s,a)=\\sum_{s',r}p(s',r|s,a)[r+\\gamma v_\\pi(s')] $ }\n    \\label{fig:MDPMDP}\n\\end{figure}\nThe value of a state depends on the values of the actions possible in that state and on how likely each action is to be taken under the current policy.\n\n\\subsection{Optimal Policies and Optimal Value Functions}\n\nSolving a RL means finding a policy that achieves a lot of reward over the long run.\n\n\\begin{definition}\noptimal policy, $\\pi_*$\n\n$$ \\pi_* \\geq \\pi' \\iff v_\\pi(s) \\geq v_{\\pi'}(s), \\quad \\forall s \\in \\mathcal{S} $$\n\\end{definition}\n\n\\begin{definition}\noptimal state-value function, $v_*$\n\n$$ v_*(s) \\doteq \\max_\\pi v_\\pi(s), \\quad \\forall s \\in \\mathcal{S} $$\n\\end{definition}\n\n\\begin{definition}\noptimal action-value function, $q_*$\n\n$$ q_*(s) \\doteq \\max_\\pi q_\\pi(s,a), \\quad \\forall s \\in \\mathcal{s}, a \\in \\mathcal{A} $$\n\\end{definition}\n\nWe can write $q_*$ in terms of $v_*$:\n\n$$ q_*(s,a) = \\E [R_{t+1} + \\gamma v_* (S_{t+1}) | S_t = s, A_t = a] $$\n\n\\begin{definition}\nBellman optimality equation for $v_*$,\n\\begin{align*}\nv_*(s) & = \\max_{a\\in\\mathcal{A}}(s) q_{\\pi_*} (s,a) \\\\\n& = \\max_a \\E [R_{t+1} + \\gamma v_* (S_{t+1}) | S_t = s, A_t = a] \\\\\n& = \\max_a \\sum_{s',r} p(s',r|s,a)[r+\\gamma v_*(s')]\n\\end{align*}\n\\end{definition}\n\n\\begin{definition}\nBellman optimality equatoin for $q_*$,\n\\begin{align*}\nq_*(s,a) & = \\E [R_{t+1} + \\gamma \\max_{a'} q_*(S_{t+1}, a') | S_t = s, A_t = a] \\\\\n& = \\sum_{s',r} p(s',r|s,a)[r+\\gamma \\max_{a'} q_*(s',a')]\n\\end{align*}\n\\end{definition}\n\n\\begin{figure}[!h]\n  \\centering\n  \\includegraphics[]{MDP_optimal.PNG}\n  \\caption{Backup diagram for $v_*$ and $q_*$}\n  \\label{fig:MDP_optimal}\n\\end{figure}\n\nExplicitly solving the Bellman optimality equation provides one route to finding $\\pi_*$, and thus to solving the RL problem.\nHowever, this solution is rarely useful. It needs an exhaustive search, looking ahead at all possibilities, computing their probabilities of occurrence and their desirabilities in terms of expected rewards.\nThis solution relies on at least 3 assumptions:\n\\begin{itemize}\n\\item the dynamics of the environment are accurately known\n\\item computational resources are sufficient\n\\item the states have the Markov property\n\\end{itemize}\n\nIn RL, one typically has to settle for approximate solutions. Many RL methods can be taken as approximately solving the Bellman optimality equation.\n\n\\paragraph{Exercise} Consider the contining MDP shown, the only decision to be made is in the top state with two actions (left, right).\nFind optimal policy when $\\gamma$ = 0.9.\n\n\\begin{figure}[!h]\n  \\centering\n  \\includegraphics[]{ex3-22.PNG}\n  \\label{fig:ex3-22}\n\\end{figure}\n\nRecall the definition of $v_\\pi(s)$ and $q_\\pi(s)$, we get\n\n\\begin{itemize}\n\\item Left Policy\n\\begin{itemize}\n\\item $ v(s_0) = 1 + 0.9\\cdot v(s_L) $\n\\item $ v(s_L) = 0 + 0.9\\cdot v(s_0) $\n\\item $ v(s_R) = 2 + 0.9\\cdot v(s_0) $\n\\end{itemize}\n\\item Right Policy\n\\begin{itemize}\n\\item $ v(s_0) = 0 + 0.9\\cdot v(s_R) $\n\\item $ v(s_L) = 0 + 0.9\\cdot v(s_0) $\n\\item $ v(s_R) = 2 + 0.9\\cdot v(s_0) $\n\\end{itemize}\n\\end{itemize}\nSolving above we find that all state values of Right Policy is greater than all state values of Left Policy. Thus, `right' is the optimal policy for $\\gamma$ = 0.9.\n\nIt is important to note that if we take `left' action in $s_0$, then policy $\\pi$ would never take us to state $s_R$ (same for `right' and $s_L$); however, due to the definition of $\\pi_*$, we must evaluate the value function for all states, even ones that would not be visited under a policy we are evaluating.\n\n\\subsection{Optimality and Approximation}\n\nIt is difficult to reach optimal solutions due to constraints from computational resource and memory. We can often approximate the optimal solutions.\n\n\\subsection{Summary}\n\n\\begin{itemize}\n\\item RL is about learning from interaction how to behave in order to achieve a goal.\n\\item RL \\textit{agent} and its \\textit{environment} interact over a sequence of discrete time steps.\n\\item \\textit{actions}: choices made by the agent, \\textit{states}: the basis for making the choices, \\textit{rewards}: basis for evaluating the choices.\n\\item everything inside agent is known and controllable; environment is incompletely controllable, and are partialily known\n\\item a \\textit{policy} is a stochastic rule that the agent selects actions as a function of states\n\\item agent's objective is to maximize reward it receives in the long run\n\\item when RL setup with agent, environment, states, actions, rewards, policy and formulated with well-defined transition probabilities it constitutes a Markov decision process (MDP)\n\\item a finite MDP is an MDP with finite state sets, action sets and reward sets.\n\\item \\textit{return} is the function of future rewards that the agent seeks to maximize (in expected value)\n\\item undiscounted formulation is appropriate for \\textit{episodic tasks}\n\\item discounted formulation is appropriate for \\textit{\\textbf{tabular} continuing tasks} (but not for approximate continuing tasks; see chap 10.3-4)\n\\item \\textit{value functions} $v_\\pi$ (state) and $q_\\pi$ (state-action pair) are the expected return from that state/state-action under policy $\\pi$\n\\item \\textit{optimal value functions} $v_*$ and $q_*$ are the largest expected return by any policy\n\\item A policy whose value functions are optimal is an optimal policy\n\\item !! A MDP can have many optimal policies, but can have only one unique optimal value function ($v_*$ and $q_*$)\n\\item Any policy that is \\textit{greedy} w.r.t $v_*$ and $q_*$ must be $\\pi_*$\n\\item The Bellman optimality equations are special consistency conditions that the optimal value functions must satisfy\n\\item In RL most cases, their optimal solutions cannot be found but must be approximated in some way.\n\\end{itemize}\n\n\\newpage\n\\section{Dynamic Programming}\n\nIn RL, DP refers to a collection of algorithms that can be used to compute optimal policies $\\pi_*$ given a perfect model of the environment as a Markov decision process (MDP).\nDP itself cannot be useful in RL due to its computational cost and requirement of a perfect model, but DP provides an essential foundation for the understanding of other algorithms.\nOther algorithms can be treated as attempts to achieve much the same effect as DP, only with less computation and without assuming a perfect model of the environment.\n\nStarting with this chapter, we assume the environment is a finite MDP (i.e. $S$, $A$, $R$ are finite and dynamics are given by a set of probabilities $p(s',r|s,a)$).\nA common way of obtaining approximate solutions for tasks with continuous states and actions is to quantize the state and action spaces and then apply finite-state DP methods.\nIn this chapter we show how DP can be used to compute the value functions defined in Chapter 3. As shown in Chapter 3, we can obtain $\\pi_*$ once we have found $v_*$ or $q_*$, which satisfy the Bellman optimality equations:\n\n\\begin{align*}\nv_*(s) & = \\max_a \\E [R_{t+1} + \\gamma v_*(S_{t+1}) | S_t = s, A_t = a] \\\\\n& = \\max_a \\sum_{s',r} p(s',r|s,a)[r + \\gamma v_*(s')]\n\\end{align*}\n\n\\begin{align*}\nq_*(s,a) & = \\E [R_{t+1} + \\gamma \\max_{a'} q_*(S_{t+1},a') | S_t = s, A_t = a] \\\\\n& = \\sum_{s',r} p(s',r|s,a)[r+\\gamma \\max_{a'} q_*(s',a')]\n\\end{align*}\n\n\\subsection{Policy Evaluation (Prediction)}\n\\begin{definition}\npolicy evaluation, compute the state-value function $v_\\pi$ for an arbitrary policy $\\pi$\n\\end{definition}\n\nPolicy evaluation is also called prediction problem.\n\nRecall that $\\forall s \\in \\mathcal{S}$,\n\n\\begin{align*}\nv_\\pi(s) & \\doteq \\E_\\pi [G_t | S_t = s] \\\\\n& = \\E_\\pi [R_{t+1} + \\gamma G_{t+1} | S_t = s] \\\\\n& = \\E_\\pi [R_{t+1} + \\gamma v_\\pi (S_{t+1}) | S_t = s] \\\\\n& = \\sum_a \\pi (a|s) \\sum_{s',r} p(s',r|s,a) [r+\\gamma v_\\pi (s')]\n\\end{align*}\n\nIf the environment's dynamics are completely known, then the last equation is a sysnteim of $|\\mathcal{S}|$ simultaneous linear equations.\nFor this case, iterative solution methods are most suitable. Consider a sequence of approximate value functions $v_0$, $v_1$, $v_2$, $\\cdots$, each mapping $\\mathcal{S^+}$ to $\\R$.\nThe initial approximation, $v_0$, is chosen arbitrarily, and each successive approximation is obtained by using the Bellman equation $v_\\pi$ as an update rule ($\\forall s$):\n\n\\begin{align*}\nv_{k+1} & \\doteq \\E_\\pi [R_{t+1} + \\gamma v_k (S_{t+1}) | S_t = s] \\\\\n& = \\sum_a \\pi (a|s) \\sum_{s',r} p(s',r|s,a)[r+\\gamma v_k (s')]\n\\end{align*}\n\nWe see that $v_k$ = $v_\\pi$ is a fixed point for this update rule as $k \\rightarrow \\infty$, $v_k$ converages to $v_\\pi$. This algorithm is called \\textit{iterative policy evaluation}.\nThe update is called \\textit{expected update}. It is called \\textit{expected} because the updates are based on an expectation over all possible next states rather than on a sample next state.\n\nIn this algorithm, we use one array and update values in place.\n\\begin{tcolorbox}[width=\\textwidth,title={Iterative Policy Evaluation, for estimating $V \\approx v_\\pi$}]\nInput $\\pi$ (the policy to be evaluated); $\\theta > 0$ threshold determining accuracy of estimation.\nInitialize $V(s)$ arbitrarily, for $s \\in \\mathcal{S}$, and $V$ to 0.\n\nLoop:\n\\begin{align*}\n&\\quad\\Delta \\leftarrow 0 \\\\\n&\\quad\\text{Loop for each } s \\in \\mathcal{S} \\\\\n&\\quad\\quad v \\leftarrow V(s) \\\\\n&\\quad\\quad V(s) \\leftarrow \\sum_a \\pi (a|s) \\sum_{s',r} p(s',r|s,a)[r + \\gamma V(s')] \\\\\n&\\quad\\quad \\Delta \\leftarrow \\text{max}(\\Delta, |v-V(s)|) \\\\\n&\\text{until } \\Delta < \\theta\n\\end{align*}\n\\end{tcolorbox}\n\n\nPolicy evaluation of $q_\\pi$:\n\n\\begin{align*}\nq_\\pi(s,a) & \\doteq \\E_\\pi [G_t | S_t = s, A_t = a] \\\\\n& = \\E_\\pi [R_{t+1} + \\gamma G_{t+1} | S_t = s, A_t = a] \\\\\n& = \\E_\\pi [R_{t+1} + \\gamma \\sum_{s',a'} q_\\pi (s',a') | S_t = s, A_t = a] \\\\\n& = \\sum_{s',r} p(s',r|s,a) [ r+ \\gamma \\sum_{a'} \\pi(a'|s')q_\\pi(s',a')]\n\\end{align*}\n\n\\begin{align*}\nq_{k+1}(s,a) & \\doteq \\E_\\pi [R_{t+1} + \\gamma G_{t+1} | S_t = s, A_t = a] \\\\\n& = \\sum_{s',r} p(s',r|s,a)[r+\\gamma \\sum_{a'} \\pi (a'|s')q_k(s',a')]\n\\end{align*}\n\n\\subsection{Policy Improvement}\n\n\\begin{definition}\npolicy improvement theorem. Let $\\pi$ and $\\pi'$ be any pair of deterministic policies, where $\\pi'$ is idential to $\\pi$ except $\\pi'(s) = a \\neq \\pi(s)$, s.t. $\\forall s \\in \\mathcal{S}$,\n\n$$ q_\\pi (s,\\pi'(s)) \\geq v_\\pi(s) $$\n\nThen the policy $\\pi'$ must be btter (or as good as) than $\\pi$. That is, it must obtain greater or equal expected return from all states $s \\in \\mathcal{S}$\n\n$$ v_{\\pi'}(s) \\geq v_\\pi (s) $$\n\\end{definition}\n\n\\begin{definition}\npolicy improvement, the process of making a new policy $\\pi'$ that improves on an original policy $\\pi$, by making it greedy w.r.t the value function of $\\pi$.\n\\end{definition}\n \nIf there are ties in policy improvement steps, each maximizing action can be given a portion of the probability of being selected in the new greedy policy.\n\n\\subsection{Policy Iteration}\n\nIt is trivial to see that we can ultimately reach an optimal policy through iterative improving policies and value functions \\footnote{In large-scale reinforcement learning problems, it is typically impractical to run either of these steps to convergence, and instead the value function and policy are optimized jointly. By Soft Actor-Critic: Off-Policy Maximum Entropy Deep Reinforcement Learning with a Stochastic Actor}.\n\n\\begin{definition}\npolicy iteration, the way of finding an optimal policy.\n\n$$\\pi_0 \\xrightarrow{E} v_{\\pi_0} \\xrightarrow{I} \\pi' \\xrightarrow{E} v_{\\pi'} \\xrightarrow{I} \\pi'' \\xrightarrow{E} \\cdots \\xrightarrow{I} \\pi_* \\xrightarrow{E} v_* $$\n\\end{definition}\n\n\\begin{tcolorbox}[width=\\textwidth,title={Policy Iteration (using iterative policy evaluation) for estimating $\\pi \\approx \\pi_*$}]\n1. Initialization\n\n$\\quad V(s) \\in\\R$ and $\\pi(s) \\in A(s)$ arbitrarily $\\forall s \\in \\mathcal{S}$; $V(terminal) \\doteq 0$\n\n2. Policy Evaluation\n\\begin{align*}\n&\\text{Loop:}\\\\\n&\\quad\\Delta \\leftarrow 0\\\\\n&\\quad\\text{Loop for each } s \\in \\mathcal{S}\\\\\n&\\quad\\quad v \\leftarrow V(s)\\\\\n&\\quad\\quad V(s) \\leftarrow \\sum_a \\pi (a|s) \\sum_{s',r} p(s',r|s,a)[r + \\gamma V(s')]\\\\\n&\\quad\\quad \\Delta \\leftarrow \\text{max}(\\Delta, |v-V(s)|)\\\\\n&\\text{until } \\Delta < \\theta\n\\end{align*}\n\n3. Policy Improvement\n\\begin{align*}\n&policyStable \\leftarrow true\\\\\n&\\text{For each } s \\in \\mathcal{S}\\\\\n&\\quad oldAction \\leftarrow \\pi(s)\\\\\n&\\quad \\pi(s) \\leftarrow \\argmax_a \\sum_{s',r} p(s',r|s,a)[r+\\gamma V(s')]\\\\\n&\\quad \\text{If } oldAction \\notin \\{a_i\\} \\text{, which is the all equal best solutions from $\\pi(s)$}\\\\\n& \\quad \\text{then } policyStable \\leftarrow false\\\\\n&\\text{If } policyStable \\text{, then stop and return } V \\approx v_* \\text{ and } \\pi \\approx \\pi_*\\text{; else go to 2}\t\n\\end{align*}\n\\end{tcolorbox}\n\n\\begin{tcolorbox}[width=\\textwidth,title={Policy Iteration (using iterative policy evaluation) for estimating $\\pi \\approx \\pi_*$}]\n1. Initialization\n\n$\\quad Q(s,a) \\in\\R$ and $\\pi(s) \\in A(s)$ arbitrarily $\\forall s \\in \\mathcal{S}, a \\in \\mathcal{A}$\n\n2. Policy Evaluation\n\\begin{align*}\n&\\text{Loop:}\\\\\n&\\quad\\Delta \\leftarrow 0\\\\\n&\\quad\\text{Loop for each } s \\in \\mathcal{S}, a \\in \\mathcal{A}\\\\\n&\\quad\\quad q \\leftarrow Q(s,a)\\\\\n&\\quad\\quad Q(s,a) \\leftarrow \\sum_{s',r} p(s',r|s,a)[r + \\gamma \\sum_{a'}\\pi(a'|s')Q(s',a')]\\\\\n&\\quad\\quad \\Delta \\leftarrow \\text{max}(\\Delta, |q-Q(s,a)|)\\\\\n&\\text{until } \\Delta < \\theta\n\\end{align*}\n\n3. Policy Improvement\n\\begin{align*}\n&policyStable \\leftarrow true\\\\\n&\\text{For each } s \\in \\mathcal{S}, a \\in \\mathcal{A}\\\\\n&\\quad oldAction \\leftarrow \\pi(s)\\\\\n&\\quad \\pi(s) \\leftarrow \\argmax_a Q(s,a)\\\\\n&\\quad \\text{If } oldAction \\notin \\{a_i\\} \\text{, which is the all equal best solutions from $\\pi(s)$}\\\\\n& \\quad \\text{then } policyStable \\leftarrow false\\\\\n&\\text{If } policyStable \\text{, then stop and return } Q \\approx q_* \\text{ and } \\pi \\approx \\pi_*\\text{; else go to 2}\t\n\\end{align*}\n\\end{tcolorbox}\n\n\n\\begin{definition}\n$\\varepsilon$-soft, the probability of selecting each action in each state, is at least $\\frac{\\varepsilon}{A(s)}$\n\\end{definition}\n\n\\subsection{Value Iteration}\n\nThe policy evaluation of policy iteration requires multiple sweeps through the state set and convergence occurs only in the limit.\nWe want to truncate policy evaluation without losing the convergence guarantees of policy iteration. One of the technique is value iteration.\n\n\\begin{definition}\nvalue iteration, stop policy evaluation after one sweep (one update after each state).\n\n\\begin{align*}\nv_{k+1}(s) & \\doteq max_a \\E [R_{t+1}+\\gamma v_k(S_{t+1})|S_t = s, A_t = a]\\\\\n& = max_a \\sum_{s',r} p(s',r|s,a)[r+\\gamma v_k (s')], \\forall s \\in \\mathcal{S}\n\\end{align*}\n\\end{definition}\n\n\n\n\n\n\n\n\n\n\n\\newpage\n\\section{Some Notes}\n\n\n% Please add the following required packages to your document preamble:\n\\begin{table}[]\n\\begin{tabular}{@{}ll@{}}\n\\toprule\non-policy                       & off-policy                                                                                                                  \\\\ \\midrule\nAgent can pick actions          & Agent can't pick actions                                                                                                    \\\\\nmost obvious setup :)           & \\begin{tabular}[c]{@{}l@{}}learning with exploration\\\\ playing without exploration\\end{tabular}                             \\\\\nAgent always follows own policy & \\begin{tabular}[c]{@{}l@{}}Learning from expert (expert is imperfect)\\\\ Learning from sessions (recorded data)\\end{tabular} \\\\ \\bottomrule\n\\end{tabular}\n\\end{table}\n\n% Please add the following required packages to your document preamble:\n% \\usepackage{booktabs}\n\\begin{table}[]\n\\begin{tabular}{@{}lll@{}}\n\\toprule\n             & on-policy                                                                                                                                   & off-policy                                                                          \\\\ \\midrule\nvalue based  & \\begin{tabular}[c]{@{}l@{}}Monte Carlo Learning\\\\ TD(0)\\\\ SARSA\\\\ Expected SARSA\\\\ n-Step TD/SARSA\\\\ TD(\\textbackslash{}lamda)\\end{tabular} & \\begin{tabular}[c]{@{}l@{}}Q-Learning\\\\ DQN\\\\ Double DQN\\\\ Dueling DQN\\end{tabular} \\\\\npolicy based & \\begin{tabular}[c]{@{}l@{}}REINFORCE\\\\ REINFORCE with Advantage\\end{tabular}                                                                &                                                                                     \\\\\nactor-critic & \\begin{tabular}[c]{@{}l@{}}A3C\\\\ A2C\\\\ TRPO\\\\ PPO\\end{tabular}                                                                              & \\begin{tabular}[c]{@{}l@{}}DDPG\\\\ TD3\\\\ SAC\\\\ IMPALA\\end{tabular}                   \\\\ \\bottomrule\n\\end{tabular}\n\\end{table}\n\n\n\\subsection{Gradient Descent vs. Gradient Ascent}\n\nThe gradient of a continuous function $f$ = the vector that contains the partial derivatives $\\frac{\\partial f(p)}{\\partial x_i}$ computed at that point $p$.\nThe gradient is finite and defined if and only if all partial derivatives are also defined and finite.\nThe gradient formula:\n\n$$ \\nabla f(x) = [\\frac{\\partial f(p)}{\\partial x_1}, \\frac{\\partial f(p)}{\\partial x_2}, \\cdots, \\frac{\\partial f(p)}{\\partial x_{|x|}}]^T $$\n\nWhen using the gradient for optimization, we can either conduct gradient descent or gradient ascent.\n\n\\paragraph{Gradient Descent}\nGradient Descent is an iterative process through which we optimize the parameters of a ML model. It's particularly used in NN, but also in logistic regression and support vector machines (SVM). It is the most typical method for iterative minimization of a cost function. Its major limitation consists of its guaranteed convergence to a local, not necesarily global, minimum.\n\nA hyperparameter (i.e. pre-defined parameter) $\\alpha$ (learning rate), allows the fine-tuning of the process of decent. In particular, we may descent to a global minimum.\nThe gradient is calculated with respect to a vector of parameters for the model, typically the weight $w$. In NN, the process of applying gradient descent to the weight matrix is called backpropagation of the error.\n\nBackpropagation uses the sign of the gradient to determine whether the weights should increase or decrease. The sign of the gradient allows us to direction of the closet minimum to the cost function. For a given $\\alpha$, we iteratively optimize the vector $w$ by computing\n$$ w_{n+1} = w_n - \\alpha \\nabla_w f(w) $$\nAt step $n$, the weights of the NN are all modified by the product of the hyperparameter $\\alpha$ times the gradient of the cost function, computed with those weights.\nIf the gradient is positive, then we decrease the weights; if the gradient is negative, then we increase the weights.\n\n\\paragraph{Gradient Ascent}\nGradient ascent works in the same manner as gradient descent. The only difference is that gradient ascent maximize functions (instead of minimization).\n$$ w_{n+1} = w_n + \\alpha \\nabla_w f(w) $$\n\nGradient descent works on \\textbf{convex functions}, while gradient ascent works on \\textbf{concave functions}.\n\n\\paragraph{Summary}\n\\begin{itemize}\n\\item The gradient is the vector containing all partial derivatives of a function in a point\n\\item We can apply gradient descent on a convex function, and gradient ascent on a concave function\n\\item Gradient descent finds the nearest minimum of a function, gradient ascent finds the nearest maximum\n\\item We can use either form of optimization for the same problem if we can flip the objective function.\n\\end{itemize}\n\n\\paragraph{Gradient vs. Derivative}\n\n\\begin{itemize}\n\\item A directional derivative = a slope in an arbitrary specified direction.\n\\item A directional derivative is a rate of change of a function in any given direction.\n\\end{itemize}\n\n\\begin{itemize}\n\\item Gradient = a vector with slope of the function along each of the coordinate axes.\n\\item Gradient indicates the direction of \\textbf{greatest} change of a funciton of more than one variable.\n\\item Gradient vector can be interpreted as the `direction and rate of fastest increase'.\n\\end{itemize}\n\n\\paragraph{Differential vs. Derivative}\n\\begin{itemize}\n\\item Differential is a subfield of calculus that refers to infinitesimal difference in some varying quantity\n\\item Differential represents an equation that contains a function and one or more derivatives of that function\n\\item The function which represents the relationsihp between the dependent and the independent variables is unknown\n\\end{itemize}\n\n\\begin{itemize}\n\\item The derivative of a function is the rate of change of the output value with respect to its input value\n\\item Derivative represent the instantaneous change in the dependent variable with respect to its independent variable\n\\item The function which represents the relationship between the variables is known\n\\end{itemize}\n\n\n\\paragraph{Loss/Cost/Objective function}\n\n\\begin{itemize}\n\\item \\textbf{Loss function} is usually a function defined on a data point, prediction and label, and measures the penalty. For example: square loss in linear regression, hinge loss in SVM, 01 loss in theoretical analysis\n\\item \\textbf{Cost function} is usually more general. It might be a sum of loss functions over all training set plus some model complexity penalty. For example: MSE and SVM cost function\n\\item \\textbf{Objective function} is the most general term for any function that you optimize during training. For example, a probability of generating training set in maximum likelihood approach is a well defined objective function, but it is not a loss function nor cost function\n\\end{itemize}\n\nWe may say that, a loss function is a part of cost function which is a type of an objective function.\n\nFrom wikipedia, in mathematical optimization and decision theory, a loss function or cost function (sometimes also called an error function) is a function that maps an event or values of one or more variables onto a real number intuitively representing some \"cost\" associated with the event. An optimization problem seeks to minimize a loss function. An objective function is either a loss function or its opposite (in specific domains, variously called a reward function, a profit function, a utility function, a fitness function, etc.), in which case it is to be maximized.\n\n\\paragraph{Surrogate vs. Approximation}\n\nI think surrogate and approximation can be used interchangeably.\n\nSurrogate loss function is used when the original loss function is inconvenient for calculation.\n\n\n\\bibliography{references.bib}\n\n\\end{document}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "3eb9d82302e17ee7af7fa983ef76b9e8bf9b7157", "size": 58361, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "sutton_barto_notes.tex", "max_stars_repo_name": "pwyq/Notes", "max_stars_repo_head_hexsha": "242169f301c0c425633f4357260ec7c67d63c18e", "max_stars_repo_licenses": ["LPPL-1.3c"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sutton_barto_notes.tex", "max_issues_repo_name": "pwyq/Notes", "max_issues_repo_head_hexsha": "242169f301c0c425633f4357260ec7c67d63c18e", "max_issues_repo_licenses": ["LPPL-1.3c"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sutton_barto_notes.tex", "max_forks_repo_name": "pwyq/Notes", "max_forks_repo_head_hexsha": "242169f301c0c425633f4357260ec7c67d63c18e", "max_forks_repo_licenses": ["LPPL-1.3c"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.9111514053, "max_line_length": 575, "alphanum_fraction": 0.7325611282, "num_tokens": 15796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.34876034896606634}}
{"text": "\\documentclass{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage{hyperref}\n\\usepackage{amsmath}\n\\usepackage{graphics}\n\\usepackage{graphicx}\n\\usepackage{float}\n\\graphicspath{ {images/} }\n\\title{Starlings Murmuration Simulation}\n\\author{Sankalan Pal Chowdhury, Shreshth Tuli}\n\\date{April 2018}\n\n\\begin{document}\n\n\\maketitle\n\n\\section{Introduction}\nStarlings are a species of small birds that show tendency to migrate in flocks. These flocks are called murmurations and can contain thousands of starlings. Due to their small size and coordinated movements, they can often put up very beautiful displays while moving. In this project, we try to mathematically model this behavior of theirs and run a Computer Simulation of the same\n\\section{Modeling the Starling}\nWe seek to model each bird as an individual agent which reacts to its surroundings in order to determine its flying direction. In the most simple model, its environment consists only of other birds. The bird must therefore negotiate three types of constraints in order to determine its flying direction: External forces, Internal forces and Personal limitations.\n\\subsection{External Forces}\nExternal forces are the forces of mother nature which the bird act on the bird. We assume that the bird does not need to spend energy to generate these forces, and also cannot have any direct control over them. While there are many such forces, we seek to model only the major ones(this selection is similar to what is done for modeling airplanes):\n\\begin{itemize}\n    \\item \\textbf{Gravity:} Gravity is perhaps the simplest yet most significant force to model. The concept of flight is fascinating essentially since it seems to overcome gravity.\n    \\item \\textbf{Buoyancy:} Buoyancy may not be too important in air, but it is extremely easy to adjust within gravity. It can become significant for birds with very low density, so it cannot harm to model it.\n    \\item \\textbf{Lift:} The  lift force is the main contributor towards overcoming gravity. In fact the bird can maintain its altitude only if the sum of Lift and Buoyancy is same as Gravity.\n    \\item \\textbf{Drag:} The drag force arises due to air resistance which tries to prevent the motion of any body traveling through a fluid. But for this force, the bird could keep flying without applying any effort.\n\\end{itemize}\nBirds, unlike airplanes can flap their wings in order to generate upward force. This force is more like a buoyant force, but needs the bird to spend energy to get it and can also control its magnitude to some extent. Modeling this requires a deep insight of the anatomy of the starlings which is beyond the scope of the model designers, therefore, we do not include it here.\n\\subsection{Internal Forces}\nOnce the external forces have been decided, the bird may decide to fly in a certain direction. It is somewhat misleading to call this decision a force, these are actually factors based on which the bird decides what kind of force to apply on itself(actually the bird applies the force on the environment and it gets it force by Newtons Third Law). These, however are all vector quantities and it is rather intuitive to consider them as components of the net force that the bird applies. \n\nIn the current model, we consider three forces, which are commonly used to simulate \\href{https://en.wikipedia.org/wiki/Flocking_(behavior)}{flocking behaviour}:\n\\begin{itemize}\n    \\item \\textbf{Cohesion:} The cohesive force is the attractive force that a bird experiences towards other members of the flock. It ensures that the flock stays together and does not start moving in random directions.\n\\begin{figure}[h]\n\\centering\n\\includegraphics[width=10cm]{cohesion600}\n\\end{figure}\n\\item \\textbf{Separation:} The separative force acts opposite to the cohesive force and ensures that the birds keep a minimum distance between them and don't start colliding with each other\n\\begin{figure}[h]\n\\centering\n\\includegraphics[width=10cm]{separation600}\n\\end{figure}\n    \\item \\textbf{Alignment:} This force tries to coordinate the direction of motion of the entire flock. Each bird has the urge to fly in the same direction as its neighbors.\n\\end{itemize}\n\\begin{figure}[h]\n\\centering\n\\includegraphics[width=10cm]{alignment600}\n\\end{figure}\n\nThe above mentioned factors present a somewhat idealistic view of how a certain bird desires to fly. However, there are other factors effecting how the bird really flies.\n\nTo start off, a bird is not likely to know about another bird which is flying right behind it. In fact, it can only see those birds which are in its \\textbf{field of view}, ie the maximum angle from its line of motion which it can see. This is actually quit large for birds since they have eyes on the sides of their heads. Further, two birds which are far off from each other are less likely to affect each other than two birds that are close by. This phenomenon is modeled by the (near)\\textbf{sightedness} of the bird. Finally, some birds may be more \\textbf{adventurous} than others, giving them urges to fly off in random directions rather than those specified by the above forces.\n\nFinally, a bird can apply only a limited amount of force, in which it would try to overcome the External forces and move in its desired direction. This limit would be determined both by an overall \\textbf{maximum acceleration} and the individual \\textbf{strength} of the bird.\n\\section{Mathematical Formulation}\nTo begin our mathematical formulation, we need to first fix a coordinate system. We fix the origin at the flock centroid(this is beneficial for bounding box creation during implementation) and the y axis upwards. The x and z axis are arbitrarily chosen since the system has cylindrical symmetry.\n\nThe mathematical values of the external forces are more or less standard and do not require much explanation\n\\begin{center}\n\n    $$\\vec{F_{gravity}}=\\rho_{bird}V\\vec{g}$$\n    $$\\vec{F_{buoyancy}}=-\\rho_{air}V\\vec{g}$$\n    $$\\vec{F_{lift}}=C_{lift}\\rho_{air}\\vec{v}^2W\\hat{j}$$\n    $$\\vec{F_{drag}}=-\\frac{1}{2} C_{drag}\\vec{v}^2A\\hat{v}$$\n    $$\\vec{F_{external}}=\\vec{F_{gravity}}+\\vec{F_{buoyancy}}+\\vec{F_{lift}}+\\vec{F_{drag}}$$\n\n    $$\\rho_{bird},\\rho_{air} \\text{ are the densities of the bird and air,}$$\n    $$C_{lift}, C_{drag} \\text{ are the lift and drag coefficients,}$$\n    $$g \\text{ is the acceleration due to gravity }=0\\hat{i}-9.8\\hat{j}+0\\hat{k}$$\n    $$W, A \\text{ are wing area and cross sectional area respectively,}$$\n    $$\\vec{v} \\text{ is the current velocity of the bird,}$$\n    $$V \\text{ is the volume of the bird}$$\n \n\\end{center}\n\nThe internal forces are more involved. To begin with, field of view simply filters out the birds which are beyond the specified angle, so all statements made hereafter are w.r.t. the rest of the birds.\n\n\\subsection{Internal Forces}\nTwo different approaches are possible to deal with the sightedness issue. One is to say that only a fixed number of nearest neighbors affect the bird. This partially relies on the fact that the bird would not want to over complicate its life and would approximate the world by a fixed number of birds around it. However, the evidence for this is quite empirical and needs to be judge in light of the fact that the number of birds in a certain region around the bird is held more or less constant by the Cohesion and separation forces. This also does not account for the chance that the bird might look at a very distant bird and adjust itself according to it.\n\nThe other view is to limit the distance till which a bird can see. This seems more logical, except for the fact that there is unlikely to be a hard boundary at a given distance. Therefore, we choose an exponential decay function to model the sightedness of the birds:\n\\begin{center}\n$$W_i=e^{-sd_i}$$\n\\[\n    d_i \\text{ is the distance to the } i^{th} \\text{ bird}\n    s \\text{is the sightedness of the bird}\n\\]\n\\end{center}\nAt this point, it may seem strange that a bird would look at like a thousand other birds before deciding which direction to move, which is clearly illogical. One way of explaining this would be that the bird looks at only a certain number of birds at each moment, and the quantity mentioned here is the over time expectation of looking at each bird.\n\nThis done, we can move on to the three forces. We calculate for each bird separately(call this the target bird and then aggregate to get the net forces.\n\nIt is intuitive to keep Alignment proportional to the velocity of the target bird. As for Separation and Cohesion, they should logically be proportional to the inverse of the distance between the two birds(Actually, cohesion can be constant, allowing for the sightedness to take care of the distance factor. Ignoring this fact is more of a personal intuition). Also, the separation force needs to grow faster that the cohesion force, as we want to prevent collisions. We chose to take the simplest expressions that satisfy these constraints.\n\\begin{center}\n$$\\vec{F_{cohesion,i}}=\\frac{C_{coh}}{d_i} \\hat{d_i}$$\n$$\\vec{F_{separation,i}}=-\\frac{C_{sep}}{d_i^2} \\hat{d_i}$$\n$$\\vec{F_{align,i}}=C_{ali}\\vec{v_{i}}$$\n\n$$\\hat{d_i} \\text{ is the unit vector towards the } i^{th} \\text{ bird }$$\n$$\\vec{v_{targ}} \\text{ is the velocity of } i^{th} \\text{ bird }$$\n$$C_{coh},C_{sep},C_{ali} \\text{ are respective coefficients}$$ \n\\end{center}\n\nOnce these forces are calculated due to each bird, we need to aggregate them to get net internal force. Aggregation can be done in many ways, but the two most common ways are summation and averaging. Summation is good for aggregating quantities that are likely to add up destructively. This is clearly true for the separation force. Averaging, on the other hand, make sense for quantities that would add up constructively, like the alignment force. Cohesion force can go either way, but it is somewhat safer to consider averaging since a zero is less dangerous than an infinity. The Weights assigned to the different birds is taken care of here.\n\n\\begin{center}\n    $$\\vec{F_{cohesion}}=\\frac{\\sum_iW_i\\vec{F_{cohesion,i}}}{\\sum_iW_i}$$\n    $$\\vec{F_{alignment}}=\\frac{\\sum_iW_i\\vec{F_{alignment,i}}}{\\sum_iW_i}$$\n     $$\\vec{F_{separation}}=\\sum_iW_i\\vec{F_{separation,i}}$$\n\\end{center}\n\nFinally, we need to add the adventure component to these forces to calculate the net internal force on the bird. Now, while an adventurous bird may not want to align itself with the other birds or get attracted to them, it will certainly not want to collide with other birds. Therefore, the random component will only replace the alignment and cohesion forces and not the separation force.\n\\begin{center}\n    $$\\vec{F_{internal}}=\\vec{F_{separation}}+\\frac{1000-Adv}{1000}(\\vec{F_{cohesion}}+ \\vec{F_{alignment}})+\\frac{Adv}{1000}\\vec{R}$$\n    \n    $$Adv \\in \\{0,...,1000\\} \\text{ is the adventurousness parameter }$$\n    $$\\vec{R} \\text{ is a suitable random vector(suitability depends on range of magnitudes)}$$\n\\end{center}\n\\subsection{Putting it Together}\nNow that we have both the external and internal force vectors, we need to put them together to calculate the acceleration, velocity and power of the bird. It is here that we need to take into account the maximum force that the bird can apply is limited.\n\nIf the bird was an inanimate object, it would simply drift in the direction of the external force. What the bird really does is try its best to change this to its desired direction of flight as much as possible. This difference is simply given by $\\vec{v_{diff}}=\\vec{v}+\\vec{F_{external}}-\\vec{F_{internal}}$. Since we can only take discrete time, the desired acceleration is $\\vec{a_{desired}}=\\vec{v_{diff}}/P$ where P is the clock period. The magnitude of  $\\vec{a_{desired}}$ needs to be bounded by a $a_{bound}=a_{max} \\times strength$ where $a_{max}$ is the global maximum acceleration and strength is a property of the bird.\\newline\n\nThe bounding mechanism itself is somewhat non trivial. The naive way of doing it would be to cut off any value higher that the required bound. But that would be very unrealistic as in a real scenario, the bird would start facing difficulty gradually till it reaches a point where it can no longer fly faster. \nA good function to approximate this is the $tanh$ function, which has derivative of 1 around zero, but is bounded by 1 on the positive side. However, its derivative never falls to 0 for any finite parameter.\n\nOnce the bounding is done, we can calculate Power easily using laws of physics.\n\\begin{center}\n    $$\\vec{a_{final}}=tanh(\\frac{|\\vec{a_{desired}}|}{a_{bound}})\\frac{a_{bound}}{|\\vec{a_{desired}}|}\\vec{a_{desired}}$$\n    $$\\vec{v_{final}}=\\vec{v}+\\vec{v}+\\vec{F_{external}}-\\vec{a_{final}}$$\n    $$Power=m\\vec{a_{final}}.\\vec{v_{final}}$$\n\\end{center}\nPosition and Energy follow trivially.\n\n\n\\pagebreak\n\\section{Implementation}\nHaving designed the model, we attempt to implement it on a computer. The aim of this part is to 1) Be able to visualize the murmurations of the starlings on a computer screen, and 2) approximate some statistics about these murmurations.\n\nThe implementation needs to proceed in two parts. First, we look at what kinds of deviations must be made from the original model in order to be able to simulate it. Second, we choose a framework to implement the design. Both of these are dependent on the characteristics of the model and/or the constraints set by the programming environment.\n\\subsection{Deviations from the Model}\nOne of the major issues we need to deal with here is the fact that in real life, Starlings are free to move anywhere in the open sky. However, our simulation only lets us look at the starlings from a fixed viewpoint, and there is little point in having the murmurations happening out of the visible region. There are multiple options to solve this:\n\\begin{itemize}\n    \\item \\textbf{Moving the Viewpoint:} This approach tries to approximate the real motions of the birds as best as possible, by moving the viewpoint automatically along with the birds. The main advantage of this is the model does not need to be tampered with. However, there can be scenarios in which the motion of the view point would cancel out the motion of the birds, making them appear to be static. Also, the flock may split into two, leading to issues on deciding the viewpoint. Alternatively, the shifting of viewpoint can be left upto the user, but that is probably not very user friendly.\n    \\item \\textbf{A Circular World:} To give the feeling of an infinite space, we can make the edges of the view wrap around to the opposite edge. This also would require minimal changes to the model, but its physical effect can hardly be explained. Also, it is not logical anyway to let the $-y$ direction extend to infinity.\n    \\item \\textbf{Adding Imaginary Force}: To prevent the birds from escaping into infinity, we can define a potential like field that forces the birds to remain in a specified region, beyond which this field becomes too large. This can represent pressure zones or simply unfamiliar territory for the birds. However, if not tuned properly, such a field can cause the birds to actually divert to infinity.\n    \\item \\textbf{Limiting Position Directly:} This would be similar to what was done for limiting the maximum acceleration, forcing the birds to stay in a fixed region. The chief downsides of this is the lack of a physical explanation and the fact that the birds might all want to escape in one direction, but get restricted by this force, making them appear as if they are all at the same point.\n\\end{itemize}\nIn our current implementation, we choose to go with a combination of the last two approaches, which tend to cancel out some of each others negative points. For the force field, we choose a force that is zero in some region around the origin and then grows as the square root of distance from origin. This choice is kind of empirical, with comparisons performed over multiple regularized polynomial fields. The modified set of equations are given below:\n\\begin{center}\n    $$\\vec{v_{positional}}=-\\vec{P} * max(\\sqrt{\\frac{|\\vec{P}|}{P_{max}}}-\\sqrt{5},0)$$\n    $$\\vec{v_{diff}}=\\vec{v}+\\vec{F_{external}}-\\vec{F_{internal}}-\\vec{v_{positional}}$$\n    $$\\vec{P_{final}}=tanh(\\frac{|\\vec{P_{desired}}|}{20*P_{max}})\\frac{20*P_{max}}{|\\vec{P_{desired}}|}\\vec{P_{desired}}$$\n    P \\text{represents position of the bird, no subscript means current position}\n\\end{center}\nThe other equations remain unchanged.\nApart from this, it turns out that the exponential sightedness model can sometimes become too much to calculate(it needs to be done O($n^2$) times in each time step, where n is the number of birds). We therefore keep an alternative of using a constant viewing range(ie a step function). In the same vein, all the other internal forces are also made toggle-able. \n\n\\subsection{Frameworks and Design Decisions}\nWhile it has not been stated previously, some decisions are implicit to our model:\n\\begin{itemize}\n    \\item Since every starling has been modeled as an entity, and \\textbf{Object Oriented Paradigm} is necessary to implement these.\n    \\item there is a stochastic dimension to this simulation. Every calculation therefore need to be performed on a clock edge.\n    \\item Interaction between different birds is purely observational, so the all the computations are parallelisable. This makes our program fit for multi-threading.\n\\end{itemize}\n\\subsubsection{The Clock}\nWhile it is clear that a clock needs to be used, there are actually multiple options on how the clock gets used. The simplest way to go about it is to use a \\textbf{real clock} which calculates the position and updates the display in real time. In such a setting, there would be a trade off between the frequency of the clock and the number of birds. The advantage, however is that no storage needs to be done in order to create a realistic display.\n\nThe alternative to this approach is to use a \\textbf{logical clock} which can proceed at much slower pace than the actual clock, which only influences the display. This means that we can slow down the Logical clock arbitrarily, allowing us to simulate as many birds as we like(well, kind of). In such an approach, the user cannot dynamically set parameters or visualize what the current setting looks like. The main problem here though, is the fact that the positions of each bird needs to be saved into a file, and this file can get huge. \n\nSuppose we store the position and velocity of each bird at each instant as vectors of single precision floats. If we use a 50 hz clock for 2000 birds for 10 minutes we end up with $50*6*1000*30*32=1.152 Gb$ of data. Note that this data would not make any sense to a human, and if we want to use a text file, the file size blows up even more. Another consideration here is that the display of the birds itself takes up significant computational power, and that needs to be done on a real clock anyway. \n\nTherefore, we choose to stick to a real clock\n\\subsubsection{Order of Computation with Multi-threading}\nWhen talking of objects, the ideal model is that all instances of an object run their computation concurrently. This would also be closest to the real world. \n\nIn a real programming paradigm, however, to run everything concurrently is not possible(unless we have as many logical cores as birds). The closest we can get is to give each bird its own thread, but that would mean a huge number of context switches, and therefore huge slowdown. Intuitively, since the steps taken by each bird in each tick of the clock would be rather small, imposing a fixed order should not harm the model too much. \n\nIn our implementation, we use 4 threads(this number can be increased depending on how many cores are available) and within each thread, we provide two options: In one, we impose a fixed order of execution amongst the birds, while in the other, we randomize within each thread. For the non-random approach, a simple segregation scheme is used viz that from the vector of birds thread $t$ gets birds which have index $i$ such that $i\\,\\%\\,4\\,=\\,t$. Order between the threads is always random, as long as at least 4 cores are available. So there are two levels of randomization that this approach provides:\n\\begin{enumerate}\n\\item The inherent scheduler of the operating system and the seemingly random distribution of load on the physical cores, randomize the order in which the computation is done for each bird.\n\\item An array of numbers 1 to flock size is shuffled and divided into 4 sub-arrays. Each thread gets a sub-array and uses it's values as indices for execution of the computation, thus making it random.\n\\end{enumerate}\n\nAlthough the approach used still does not allow concurrent calculation for each bird (which is a limitation of the hardware) but provides the best way to model the system with finite logical cores.\n\\begin{figure}[H]\n\\centering\n\\includegraphics[width=10cm]{Flock_threading}\n\\caption{Multi-threading flowchart with randomization}\n\\end{figure}\n\n\n\\subsubsection{Selected tools}\nThe calculation is implemented in \\textbf{C++} because it is perhaps one of the most widely used, rapidly evolving and fastest language for Object Oriented Programming. The display part is done in \\textbf{OpenGL} which is said to be the \\textit{industry standard for high performance graphics}. Other platforms like $Unity$ and other similar physics engines have not been used as they do not allow tuning at the root level even though they allow users to model the problem much more easily.\n\\section{Evaluation and Parameter Tuning}\nOnce we have implemented our design, we need to tune the hyper-parameters in order to get realistic displays. But before that, we need to have some metrics to evaluate the performance.\n\\subsection{Metrics for Correctness}\nIn the age of big data and machine learning, one is always talking of differentiable and convex cost functions. Luckily or unluckily, these things have not yet invaded the lives of the starlings, so we need to have heuristic measures of correctness.\n\nThe best judgment is obviously given by visualization of the simulation, to judge whether it is realistic or not. However, is is normally better to have a more quantitative measures. Following are some such possibilities:\n\\begin{itemize}\n\t\\item The most important correctness indicator is the \\textbf{visual effect} created by the starlings when in motion. A low number of birds may not give such an effect so relaxation should be for starlings when they are less than say 100.\n    \\item The starlings have a diet consisting fruits and insects. Based on this, we can estimate how much Energy they can actually spend in flying. Thereafter, we can check if the \\textbf{Average Energy} and the \\textbf{Maximum Energy} spent by the starling is around this value or not\n    \\item Based on the energy consumption in a finite time like 10 minutes, the amount of \\textbf{food intake} should be less than the typical food intake of a starling in a day which is around 10g. Such measurements are from online sources like \\href{https://www.tandfonline.com/doi/pdf/10.1080/00063657309476384}{this}.\n    \\item The starlings can withstand only so much \\textbf{force} on themselves. If it becomes too high, the will probably get squashed. \n    \\item \\textbf{Collisions} never take place in the real setting, so even if two birds get too close, we should rethink our model. \n    \\item The starlings can not apply a large amount of power while in motion, so the parameters \\textbf{Average Power} and \\textbf{Maximum Power} should be in an acceptable range.\n\\end{itemize}\nBeyond these, there are things like maximum velocity and acceleration, but that have already been accounted for explicitly in our model, so it makes little sense in measuring them. Finally, we should also see what is the maximum number of birds that we are able to simulate, as that is definitely a measure of performance.\n\n\\pagebreak\n\n\\subsection{Tuning the Hyper-parameters}\n\nTuning the hyper-parameters is crucial for a more realistic simulation. Although, these parameters can be determined by complex calculations and analysis of the birds anatomical structure and the cognitive model. This becomes much more complicated when such functions are to be mapped for discrete time. A not so precise but more effective approach would be to augment the model parameters by brute-force and intelligent guesses based on the metrics of correctness as discussed earlier. This approach leads to errors in the model, but the deviation from realism is also because of modeling constraints as discussed. These approximations and relaxations allow us to take such a decision for parameter tuning. \\\\\nFor the internal forces, the parameter tuning has been based on a intuitive notion of prioritizing the various forces: separation, alignment and cohesion. As separation must dominate at lower distances and cohesion at higher, it is important that the constants used for cohesion are higher than that of separation but the dependence with distance must rise faster in the latter case. For realistic simulation, it is also important to give some randomness to the forces considering that these random forces do not dominate over the systematic ones used in the model. As these forces are based on a factor that exponentially decays or as a step function with distance, there constants must be considering the distances as well. \\\\\nFor the external forces including lift, drag, buoyancy and lift some physical aspects need to be investigated. The cross section area and the drag coefficient in the real scenario change dynamically but for the ease of implementation and their somewhat low effect on the model have been neglected. It is important to observe that the drag force depends on the airflow around the bird. A turbulent airflow is expected most of the times due to the flock around it. Thus, we use a drag coefficient somewhat in between but more the side of that for turbulent air. The decision as to how much the air is turbulent or laminar is based on quantitative data of the Reynolds number on the internet as on \\href{https://aip.scitation.org/doi/abs/10.1063/1.4807064}{\"this\"}  link, and empirical observations. \n\n\\section{Conclusion}\nIn this project we have been able to approximately simulate the murmurations of starlings and also calculate some essential parameters of the motion. The fact that our outputs actually look realistic is definitely evidence in favour of the fact that the real model of flight is somewhat similar to the one that we have defined. This is therefore also a step towards understanding the behavior of starlings.\n\nFinally, our model contains a lot of hyper parameters, thus a lot of flexibility. In future, should someone be able to track the actual motion of starlings, the birds can also be made \\textit{Reinforcement Learning} agents.\n\\end{document}\n\n", "meta": {"hexsha": "db8f403c46a7796145ce3110b240a9b0c32d47e0", "size": 26906, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/main.tex", "max_stars_repo_name": "shreshthtuli/FlockSim", "max_stars_repo_head_hexsha": "4576f75c2fe61dc61311e8c582cb9c072e6a64a1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-05-06T14:28:44.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-06T14:28:44.000Z", "max_issues_repo_path": "doc/main.tex", "max_issues_repo_name": "shreshthtuli/FlockSim", "max_issues_repo_head_hexsha": "4576f75c2fe61dc61311e8c582cb9c072e6a64a1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/main.tex", "max_forks_repo_name": "shreshthtuli/FlockSim", "max_forks_repo_head_hexsha": "4576f75c2fe61dc61311e8c582cb9c072e6a64a1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 118.5286343612, "max_line_length": 797, "alphanum_fraction": 0.7801233926, "num_tokens": 6237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.3487603396242106}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\section{Physics beyond the Standard Model}\n\n\\marginpar{Sunday\\\\ 2020-7-5, \\\\ compiled \\\\ \\today}\n\nA Grand Unified Theory would unify strong, electromagnetic and weak interactions. \n\nThe electromagnetic and weak interactions were unified into a \\(SU(2)_L \\times U(1)_Y\\) theory, where the coupling constants for the two groups, \\(g_2 \\) and \\(g_1 \\), are pretty close. \nThe strong coupling, \\(g_s\\), is instead quite far from these.\n\nAll of these are running couplings: we have \n%\n\\begin{align} \\label{eq:first-order-running-coupling}\n\\dv{\\alpha _i}{\\log q^2} = b_i \\alpha_{i} + \\mathcal{O}(\\alpha_{i}^3)\n\\,,\n\\end{align}\n%\n\\todo[inline]{what's up with the \\(q^2\\)?}\nwhere \\(b_i\\) is given by: \n%\n\\begin{align}\nb_i = - \\frac{1}{4 \\pi } \\qty[ \\frac{11}{3} C(G_i) - \\sum _{f} \\frac{4}{3} T(R)_f]\n\\,,\n\\end{align}\n%\nwhere we are neglecting the contributions from scalars, and where the Casimirs in the \\(SU(N)\\) case are \\(C(SU(N)) = N\\) and \\(T(R)_{SU(N)} = 1/2\\).\n\nSo, if we label electromagnetism, weak and strong interactions with the numbers 1, 2 and 3 we find \n%\n\\begin{align}\nb_3 &= - \\frac{1}{4 \\pi } \\qty[ \\frac{11}{3} \\times 3 - \\frac{4}{3} \\qty( \\frac{1}{2} + \\frac{1}{2}) n _{\\text{fermion generations}}] \\\\\nb_2 &= - \\frac{1}{4 \\pi } \\qty[ \\frac{11}{3} \\times 2 - \\frac{4}{3} \\frac{1}{2}  4 \\frac{1}{2} n _{\\text{fermion generations}} ] \\\\\nb_1 &= - \\frac{1}{4 \\pi } \\qty[ 0  - \\frac{20}{9} n _{\\text{fermion generations}} ]\n\\,.\n\\end{align}\n\n\\todo[inline]{The calculation is not super clear: what are we counting exactly for each interaction? Are the fermions not the same?}\n\nBy integrating \\eqref{eq:first-order-running-coupling} we get the \\textbf{Renormalization Group Equations}: \n%\n\\boxalign{\n\\begin{align}\n\\frac{1}{\\alpha_{i} (q^2)} = \\frac{1}{\\alpha_{i} (M_X^2)} + b_i \\log \\qty( \\frac{M_X^2}{q^2})\n\\,.\n\\end{align}}\n\nCould we find a scale such that the three couplings become equal?\nIf it exists, such a scale would be called the \\textbf{Grand Unified Theory} Energy scale. \n\nSo, we have three equations for the values of the three couplings: \nwe can input two of the low-energy couplings and predict the GUT scale \\(M _{\\text{GUT}} \\sim \\SI{e15}{GeV}\\), the GUT coupling \\(\\alpha _{\\text{GUT}}\\), and one low energy parameter.\n\nOne possible prediction is \\(\\sin^2\\theta_{w} = e^2 / g^2\\), where \\(\\theta_{w}\\) is the weak mixing angle. \n\nThis kind of works: the three couplings come close but do not reach simultaneous equality.\nA key piece of the puzzle is the fact that the way the running coupling changes depends on the \\emph{particle content} at each energy from the electroweak scale \\(M_W \\sim \\SI{200}{GeV}\\) and the GUT scale. \n\nThe thing we try to do is to embed our gauge group into some larger symmetry group: \n%\n\\begin{align}\nSU(3)_c \\otimes SU(2)_L \\otimes U(1)_Y \\subset G _{\\text{GUT}}\n\\,.\n\\end{align}\n\nFor example, we could have \\(G _{\\text{GUT}} = SU(5)\\). This group has \\(5^2 - 1 = 24\\) generators, 12 of which are the known ones, and 12 of which would be new ones.\n\nWhat would be the charges of such a boson with respect to the known symmetries? Let us work with electric charge instead oh hypercharge directly. Then, we would have 6 bosons \\(X^{\\mu }\\) with charges \\(3, 2, 4/3\\) respectively with respect to \\(SU(3)_c\\), \\(SU(2)_L\\) and \\(U(1) _{\\text{em}}\\); and 6 bosons \\(Y^{\\mu } \\) with charges \\(3, 2, 1/3\\). \n\nThese would mediate baryon- and lepton-number violating interactions, such as \\(d_L + e^{+} \\to X^{\\mu } \\to u_L + u^{c}_{L}\\).\nThis kind of interaction would allow a process like the decay of a proton \\(p\\) into a positron and a pion: \\(p \\to e^{+} + \\pi^{0}\\). \n\nThe decay rate of this process is  \\(\\Gamma \\propto M_X^{4} / m_p^{5}\\), so the lifetime of a proton would be \n%\n\\begin{align}\n\\tau_{p} \\sim \\frac{M_X^{4}}{\\alpha^2 m_p^{5}} \\sim \\SI{5e32}{yr}\n\\,,\n\\end{align}\n%\n\\todo[inline]{not what he writes, but his formulas are dimensionally inconsistent as well so I don't know}\n\nbut our experimental bounds are already higher, at \\(\\tau_{p} \\gtrsim \\SI{e33}{yr}\\). \nThe way this theory would work is by introducing a new Higgs-like field, whose VEV would be of the order of \\(M _{\\text{GUT}}\\). \n\nSo, there are two phase transitions: one at \\(E \\sim T \\sim M _{\\text{GUT}}\\), from the big symmetry group \\(G\\) to \\(G _{\\text{SM}}\\), and then one around \\(M_W\\), from \\(G _{\\text{SM}}\\) to \\(SU(3)_c \\times U(1) _{\\text{em}}\\).\n\n\\subsection{GUTs and neutrino mass}\n\nIn the Standard Model we only have \\(\\nu_{L}\\) in an isospin doublet with \\(e_L\\), and no \\(\\nu_{R}\\). \nSo, a neutrino mass term could only be written as \n%\n\\begin{align}\n\\nu_{L}^{\\alpha } \\nu_{L}^{\\beta } \\epsilon_{\\alpha \\beta }\n\\,,\n\\end{align}\n%\nwhere \\(\\alpha \\) and \\(\\beta \\) are Lorentz indices. \nLorentz transformations \\(\\Lambda \\in SO(1, 3)\\) are locally isomorphic to \\(SU(2)_L \\times SU(2)_R\\) acting on the left- and right-handed components of a spinor. Note that this \\(SU(2)\\) is \\emph{not} the isospin \\(SU(2)_L\\): it is, instead, a different way to write our Lorentz transformation. \n\nThe issue is with the way that the term \\(\\nu_{L}^{\\alpha } \\nu_{L}^{\\beta } \\epsilon_{\\alpha \\beta } \\) transforms under an \\(SU(2)_L\\) transformation: \\(\\nu_L \\) has \\(T_3 = + 1/2\\), while \\(e_L\\) has \\(T_3 = - 1/2\\). So, \\(\\nu_{L } \\nu_{L}\\) has \\(T_3 = +1\\): a component of a  triplet! \n\nIf we define \\(L = (\\nu , e)_L\\) we can write a term like \\(L^{i} L^{j} \\Delta^{ij}\\), where \\(i\\) and \\(j\\) are \\(SU(2)_L\\) gauge indices, and \\(\\Delta \\) is an \\(SU(2)_L\\) triplet, which without loss of generality can be taken to be symmetric. \n\nHowever, in the SM we only have a Higgs scalar doublet: we cannot write a term like \\(LLH\\); we could write \\(LHLH\\), which would have dimension 5: we would need to introduce a new energy scale \\(M\\), so that after SSB the term looked like \n%\n\\begin{align}\n\\frac{L \\expval{H} L \\expval{H}}{M} \\implies m_\\nu \\sim \\frac{\\expval{H}^2}{M} \\sim \\frac{v^2}{M}\n\\,.\n\\end{align}\n\nIn order to comply with the bounds we have for the neutrino masses, we would need \\(M \\gg v \\sim M_W \\sim \\SI{100}{GeV}\\).\n\nAdding to the Standard Model an operator of dimension larger than 4 coming from physics above the electroweak scale makes the SM an \\emph{effective} field theory. \nWe could have \\(M\\) be the GUT scale (which would work: \\(v^2 / M _{\\text{GUT}} \\sim \\SI{10}{meV}\\)). \n\nThis would allow us to embed the SM symmetry into a parity-conserving Lagrangian, which becomes P-breaking only at low energies.\n\n\\subsubsection{Pati-Salam theory: \\(SO(10)\\)}\n\nFor example, if \\(G _{\\text{GUT}}\\) was \\(SO(10)\\) (Pati-Salam theory) we would have the subgroup \\(SU(4) \\times SU(2)_L \\times SU(2)_R\\). \n\nIn this theory, all fermions of a generation (both left and right for all: up and down quarks (three each, for color charge), electrons, neutrinos) are different components in a spinor which has dimension 16. \n\nIn this theory, the scalar coupling to the right-handed neutrino is in the form \n%\n\\begin{align}\n\\nu_{R}^{\\alpha , i} \\nu_{R}^{\\beta, j } \\epsilon_{\\alpha \\beta } \\Delta^{ij}_{R}\n\\,,\n\\end{align}\n%\nwhere \\(ij\\) are \\(SU(2)_R\\) indices, and \\(\\alpha \\beta \\) are Lorentz indices.\nThis is a Majorana mass term for the right-handed neutrino.\nNow, the VEV \\(\\expval{\\Delta_{R}}\\) will be approximately at the GUT energy scale.\n\nThen, electroweak symmetry breaking provides the Dirac term \\(\\overline{\\nu}_{L} \\nu_{R} \\expval{H}\\) at \\(\\expval{H} \\sim \\SI{100}{GeV}\\). \n\\todo[inline]{Recall how}\n\nThe neutrino mass matrix then reads \n%\n\\begin{align}\n\\left[\\begin{array}{cc}\n0 & v \\\\ \nv & V _{\\text{GUT}}\n\\end{array}\\right]\n\\,,\n\\end{align}\n%\nwhere the vector space is \\((L, R)\\). \nThe light neutrino mass eigenstate is then mostly \\(m_{\\nu_{L}} \\sim v^2 / V _{\\text{GUT}}\\) while the other one is mostly \\(m_{\\nu_{R}} sim\n V _{\\text{GUT}}\\). \n \nThis simultaneously explains the lightness of the observed neutrinos and  the fact that we have only observed left-handed ones in the weak interactions we tested. \n\n\\subsubsection{Baryon and lepton number conservation}\n\nIn the SM, baryon and lepton number conservation are ``accidental'' (not imposed from on high) symmetries.  \n\nIn general GUTs, they are violated in couplings of new super-heavy gauge bosons with fermions.\nSo, the new bosons interact both with leptons and quarks. \nHowever, in many GUTs the combination \\(B - L\\) is conserved. \n\nThis is not the case, for example, in \\(SO(10)\\): the term \\(\\nu_{R} \\nu_{R} \\) has \\(\\Delta L = 2\\) and \\(\\Delta B = 0\\). \n\n\\subsection{The gauge hierarchy problem}\n\nEven in low (electroweak-scale and lower) energy processes we can have GUT superheavy virtual particles appearing. These should be accounted for in the loop integrals. \n\nThe situation is different for fermions and gauge bosons on one side, versus the scalar Higgs field. \n\nFermions and gauge bosons only acquire mass after SSB: so, if we draw a diagram representing the interaction between the fermion field and the Higgs field, we must have a Higgs line as well as two fermion lines. For the gauge bosons the thing is the same, but we need two Higgs lines as well as two vector boson lines, in order to contract their Lorentz indices. \n\nSo, loop corrections will build on this diagram, but they cannot change the incoming lines:\ntherefore, their mass terms will always be proportional to \\(v\\), and never to \\(M _{\\text{GUT}}\\). \n\nThere is no such SSB protection for the mass of the Higgs boson, which already has a mass term \\(\\mu^2 \\abs{\\phi}^2\\) before SSB: GUT loop corrections can indeed affect it. \n\nLet us describe the way these perturb the mass like \\(\\mu^2 = \\mu_0^2 + \\delta \\mu^2\\). If \\(\\mu_0\\) is at the electroweak scale while \\(\\delta \\mu\\) is at the GUT scale, this breaks everything!\n\nThe VEV of our Higgs would be at the GUT scale, even though at tree level it might start off at the electroweak scale. \nThere are two ways to solve this problem: \none is to fine-tune the parameters in the Lagrangian to cancel the radiative corrections to \\(\\mathscr{L} _{\\text{Higgs}}\\). \n\nThe alternative is to introduce a cutoff scale for the corrections: this can either be achieved by supersymmetry which is broken around \\SI{100}{GeV} to \\SI{1}{TeV}, or by the introduction of new spacetime dimensions.\n\n\\subsubsection{Supersymmetry}\n\nThe idea of SUSY is to introduce a symmetry transformation mapping bosons to fermions: each SM particle would have a SUSY partner with a different spin. \n\nThese are characterized by their funny names.\n\\begin{figure}\n\\centering\n\\begin{tabular}{cc}\nSM particle & SUSY partner\\\\\n\\hline\nelectron \\(e^{-}\\), spin \\(1/2\\) & selectron \\(\\widetilde{e}^{-}\\), spin \\(0\\) \\\\\n\\(W^{\\mu }\\) boson, spin \\(1\\) & \\(W\\)-ino \\(\\widetilde{W}\\), spin \\(1/2\\) \\\\\nHiggs boson \\(H\\), spin \\(1\\) & Higgsino \\(\\widetilde{H}\\), spin \\(1/2\\) \\\\\nneutrino \\(\\nu \\), spin \\(1/2\\) & sneutrino \\(\\widetilde{\\nu }\\), spin \\(0\\) \\\\\nphoton \\(\\gamma  \\), spin \\(1\\) & photino \\(\\widetilde{\\gamma  }\\), spin \\(1/2\\) \\\\\ngraviton, spin \\(2\\) & gravitino, spin \\(3/2\\) \n\\end{tabular}\n\\label{tab:supersymmetric-partners}\n\\caption{Supersymmetric partners.}\n\\end{figure}\n\nIf we start off with \\(\\mu_0^2 \\phi^2\\) at the correct scale, we are done: the correction \\(\\delta \\mu^2\\) vanishes for a SUSY theory, since the contributions for a fermion loop for the Higgs self-interaction diagram precisely cancel with the sfermion loops. \n\nThis works as long as SUSY is broken around the \\SI{}{TeV}, so that the electroweak breaking scale are protected (they do not vanish like the other ones). \n\nIf SUSY is an exact symmetry, then we expect the masses of the particles and of their SUSY partners to be equal. \nIf, instead, it is broken around the electroweak scale we may have \\(m_{\\widetilde{f}}  - m_f \\sim M_W\\).\n\nThe important thing is then that this predicts that the SUSY partners are not very much more massive than the normal particles; and they have not been found at LHC. \n\nAs we go to higher energies in the search for new particles without finding SUSY ones we get ever stricter bounds on the SUSY breaking scale.\n\nSUSY is a discrete symmetry, an \\(R\\)-parity such that fermions have \\(R = +1\\) while bosons have \\(R = -1\\). \nThis being a symmetry means that the lightest SUSY particle cannot decay: it cannot turn into SM particles since they have a different \\(R\\), and it cannot turn into heavier SUSY particles by energy conservation. \n\nIn the Supersymmetric SM the Grand Unification works well: the couplings meet at \\(M _{\\text{GUT}}^{\\text{SUSY}} \\approx \\SI{e16}{GeV}\\). \nThis is also within our bounds for the proton lifetime.\n\nThe lightest neutralino is a good WIMP-like DM candidate. \n\n\\subsubsection{Extra dimensions}\n\nThe idea here is to suppose that our 1+3-dimensional spacetime is embedded into a higher-dimensional one, for example a 1+4-dimensional one. \nThen, suppose that only gravity ``feels'' this extra dimension: then, if would be very weak in comparison to the other interactions. \n\n\\todo[inline]{REALLY not clear what this means formally}\n\nThis way, instead of having the gravitational interaction be weak because of \\(M_P\\) being very large we could have \\(M_P\\) at the electroweak scale with \\(G_N\\) being still small; most of the gravitational flux lines could be flowing in these new spatial directions.  \n\nIn these theories, every ordinary SM particle is accompanied by many more with the same quantum numbers but increasing mass --- the Kaluza-Klein modes.\nThe lightest KK mode might be a DM candidate!\n\n\\end{document}\n\n", "meta": {"hexsha": "def4d1d7eb793059a564569dbfc5f173e5e12f47", "size": 13524, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ap_second_semester/astroparticle_physics/may26.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "ap_second_semester/astroparticle_physics/may26.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ap_second_semester/astroparticle_physics/may26.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 56.35, "max_line_length": 363, "alphanum_fraction": 0.7020851819, "num_tokens": 4134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.3486032395372771}}
{"text": "\\documentclass[./standalone.tex]{subfiles}\n%\\documentclass[../../../CR/pac.tex]{subfiles}\n\n\\begin{document}\n\t\n\t%% =======================================\n\t\\section{Algorithms}\n\tFor this labwork I have implemented 2 metaheuristics algorithms. The first one being the steepest hill algorithm with restarts and the second one being the tabu algorithm. \\\\\n\t\n\t\\subsection{Steepest Hill with restarts}\n\nBelow is the steepest hill algorithm without restarts. We won't detail here the auxiliary functions such as the \\textit{getDistance} method from the TSP class or the \\textit{debugSteepestRun} which only allows a few debugging prints. Furthermore some methods will be detailed in the section \\ref{neighb}. \n\t\\begin{lstlisting}[style=Java, caption={Source code of the steepest hill algorithm without restarts}]\npublic static int[] run(City[] cities, int[] citySequence, int maxMoves){\n\tint[] tmpCitySeq, res = citySequence;\n\tint nbMoves = 0; boolean stop = false;\n\t\n\t//Not essential to the algorithm but checks coherence of the algorithm:\n\tSystem.out.println(\"Random initial city sequence is: \");\n\tSystem.out.print(\"[ \");\n\tfor(int cityID : citySequence) System.out.print(cityID + \" \");\n\tSystem.out.println(\"]\");\n\t\n\t//Essential to the algorithm:\n\twhile(!stop && nbMoves < maxMoves){\n\t\ttmpCitySeq = bestNeighb(cities, res);\n\t\t\n\t\tif(TSP.getDistance(cities, tmpCitySeq) < TSP.getDistance(cities, res))\n\t\tres = tmpCitySeq;\n\t\telse\n\t\tstop = true;\n\t\t\n\t\tnbMoves++;\n\t}\n\t\n\t//Not essential to the algorithm but checks coherence of the algorithm:\n\tdebugSteepestRun(nbMoves, res);\n\treturn res;\n}\n\t\\end{lstlisting}\nThe steepest hill algorithm consists in always choosing the best neighbor and always going towards a better solution. If a better solution can't be found then the algorithm stops. The number of moves acts as a fail-safe for this algorithm (eg. if it's always possible to go up). This is actually the whole meaning of the loop quoted above from line 12 to 21. The restart version just adds another while loop over this algorithm and compares the best solutions found at each iteration between themselves to select only the best solution over the best solutions. This is a strategy to get out of local optimums.\n\n\\newpage\n\t\\subsection{Tabu}\n\\begin{lstlisting}[style=Java, caption={Source code of the tabu algorithm}]\npublic static int[] run(City[] cities, int[] citySequence, int maxMoves, int tabuSize){\n\tLinkedList<int []> tabu = new LinkedList<>();\n\tint[] tmpBestCitySeq = null, bestNonTabuNeighb, currentCitySeq = citySequence;\n\tint nbMoves = 0; boolean stop = false;\n\t\n\twhile(nbMoves < maxMoves && !stop){\n\t  bestNonTabuNeighb = bestNonTabuNeighb(tabu, cities, currentCitySeq);\n\t\tif(bestNonTabuNeighb == null)\n\t\tstop = true;\n\t\telse{\n\t\t\taddTabu(currentCitySeq, tabu, tabuSize);\n\t\t\tcurrentCitySeq = bestNonTabuNeighb;\n\t\t\t\n\t\t\tif(isBetterNeighb(cities, currentCitySeq, tmpBestCitySeq))\n\t\t\ttmpBestCitySeq = currentCitySeq;\n\t\t\t\n\t\t\tnbMoves++;\n\t\t}\n\t}\n\t\n\t//Not essential to the algorithm but checks coherence of the algorithm:\n\tdebugTabu(nbMoves, currentCitySeq, tabu);\n\treturn tmpBestCitySeq;\n}\n\\end{lstlisting}\nThe steepest hill algorithm uses the random restarts strategy to get out of local optimums. The tabu algorithm on the other hand uses another philosophy: it allows itself to not always pick up a better solution. But it does always pick up the best possible neighbor around (or the least worse). In order to not backtrack and get caught in an infinite loop of backtracking back and forth to the local optimum it uses a tabu list in which already explored solutions are stored so that they are not explored again (as long as the tabu list, implemented as a FIFO, doesn't overflow in which case we drop the most ancient step). The longest the tabu list, the more freedom we give to our tabu execution to roam around the local optimum hoping to find a better local optimum. Again, as with the steepest hill, the while loop reflects this metaheuristics concept (from line 6 to line 17).\\\\\n\n\\underline{NB:} If no non tabu neighbour is found then in order to avoid a \\textit{null} value as the \\textit{currentCitySeq} (cf. line 12) we stop the algorithm and return the best solution found so far. This is the meaning of lines 8 to 9 above.\n\n\n\t%% =======================================\n\t\\newpage\n\t\\section{Neighbours and Neighbourdhoods}\n\t\\label{neighb}\n\n\t\\begin{lstlisting}[style=Java, caption={Source code of the neighbourhood generation in the Tabu class}]\npublic static LinkedList<int[]> genNeighbourhood(int[] citySeq){\n\tint nbCities = citySeq.length;\n\tLinkedList<int[]> res = new LinkedList<>();\n\t\n\tfor(int i = 0; i < nbCities; i++) {\n\t\tfor (int j = i + 1; j < nbCities; j++) {\n\t\t\tint[] tmp = new int[nbCities];\n\t\t\tswap(citySeq, i, j);\n\t\t\tSystem.arraycopy(citySeq, 0, tmp, 0, nbCities);\n\t\t\tres.add(tmp);\n\t\t\tswap(citySeq, i, j);\n\t\t}\n\t}\n\treturn res;\n}\t\t\n\t\\end{lstlisting}\nWhile this piece of code comes from the TSP class it is actually very similar to the \\textit{bestNeighb} static method found in the SteepestHill class. This stems from the fact that the said method kills two birds in one stone by generating the whole neighborhood of a give solution while selecting the best neighbor.\\\\\n\nWhat the above function shows is that \\underline{in the context of the TSP problem}, a neighborhood consists in the swapping of two cities from one initial sequence of cities. We can generate all the possible neighbors by generating all the possible swaps with one value then by generating all the possible swaps of the other values without including the swaps with the value already computed. Here we do this in ascending order: we generate all the possible swaps from the first city then we do this with the second city excluding the first city, etc.\\\\\n\t\n\t\n\t%% =======================================\n\t\\newpage\n\t\\section{Instances and results}\n\t\n\t\\subsection{tsp5.txt instance}\n\t\n\t\\subsubsection{Steepest Hill algorithm with restarts}\n\t\\begin{lstlisting}[style=Java, caption={Bash output of the execution of the steepest hill algorithm on the tsp5.txt instance}]\nchuxclub @ CRex2 ~/projects/wip/2021_m1csa_algo_metaheuristics (dev)\n$ java -jar tsp.jar res/tsp5.txt steepest\n\nInput maxMoves: 10\nInput maxTrials: 3\n\n######### TESTING STEEPEST HILL ALGORITHM (with restarts) ########## \n>>> INITIAL SEQUENCE OF CITIES: \n===================================================== \nVector #DataStructures.Vector@3567135c has length: 5\nVector #DataStructures.Vector@3567135c contains: \n3     4     5     2     1 \n===================================================== \nDistance: 202.72643264132455 km\n\n>>> STEEPEST HILL ALGORITHM EXECUTION (with restarts): \nTrial #1 :\nRandom initial city sequence is: \n[ 1 2 3 5 4 ]\n2 moves required to reach the following solution:\n[ 1 2 4 5 3 ]\n\nTrial #2 :\nRandom initial city sequence is: \n[ 4 2 3 5 1 ]\n3 moves required to reach the following solution:\n[ 1 2 4 5 3 ]\n\nTrial #3 :\nRandom initial city sequence is: \n[ 2 3 1 5 4 ]\n3 moves required to reach the following solution:\n[ 1 3 2 4 5 ]\n\n>>> BEST SEQUENCE OF CITIES : \n===================================================== \nVector #DataStructures.Vector@54a097cc has length: 5\nVector #DataStructures.Vector@54a097cc contains: \n1     2     4     5     3 \n===================================================== \nDistance: 194.04052963659356 km\n####################################################################\n\t\\end{lstlisting}\nWith 10 maximum moves and 3 maximum trials the best solution was reached in a fraction of a second.\n\n\\newpage\n\\subsubsection{Tabu algorithm}\n\\begin{lstlisting}[style=Java, caption={Bash output of the execution of the tabu algorithm on the tsp5.txt instance}]\nchuxclub @ CRex2 ~/projects/wip/2021_m1csa_algo_metaheuristics (dev)\n$ java -jar tsp.jar res/tsp5.txt tabu\n\nInput maxMoves: 10\nInput tabuSize: 5\n\n############################# TESTING TABU ALGORITHM ########################### \n>>> INITIAL SEQUENCE OF CITIES: \n===================================================== \nVector #DataStructures.Vector@3567135c has length: 5\nVector #DataStructures.Vector@3567135c contains: \n4     1     5     2     3 \n===================================================== \nDistance: 258.8852276594047 km\n\n>>> TABU ALGORITHM EXECUTION: \nNumber of moves used to reach last solution: 10\nLast solution reached: [ 4 2 5 3 1 ]\nCity sequences in tabu list: \n[ 3 5 4 2 1 ]\n[ 3 5 2 4 1 ]\n[ 3 4 2 5 1 ]\n[ 5 4 2 3 1 ]\n[ 2 4 5 3 1 ]\n\n>>> BEST SEQUENCE OF CITIES: \n===================================================== \nVector #DataStructures.Vector@3551a94 has length: 5\nVector #DataStructures.Vector@3551a94 contains: \n3     5     4     2     1 \n===================================================== \nDistance: 194.04052963659356 km\n################################################################################ \t\n\\end{lstlisting}\nAs with the steepest hill algorithm above, here with 10 maximum moves and a tabu list size of 5 the best solution was reached in a fraction of a second.\\\\\n\nOn the tsp5.txt we have two possible best solutions as shown above: 3     5     4     2     1  and  1     2     4     5     3  with a distance of 194.04052963659356 km. We notice that one solution is the inverted version of the other solution which trivially means that the same distance is traveled whether we do the traveling salesman circuit in one way or the other.\\\\\n\n\t\\newpage\n\t\\subsection{tsp101.txt instance}\nGiven the amount of cities (101 of them) I couldn't find no best local optimum despite the algorithm used and the amount of moves/trials/tabu size involved. But I managed once to go down to around 994km with the tabu algorithm with 1000 moves and tabu list size of 500. Recently, the steepest hill algorithm provided a solution with 1023.92 km of traveled distance with 400 moves and 100 trials.  So we can conclude that both of these algorithms find more or less the same solutions. One algorithm take more memory space (the tabu algorithm) while the other seems to take more computing time (the steepest hill algorithm) meaning that the choice of one or the other algorithm depends on the application they are used for.\\\\\n\nWe also notice that the time to find local optimums given the parameters mentioned above usually spanned from 15s to 30s.\\\\\n\n\\end{document}", "meta": {"hexsha": "58088b70beee0354df0fbcbc9f38e0a84a98e849", "size": 10248, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/report/content.tex", "max_stars_repo_name": "florian-legendre/2021_m1csa_algo_metaheuristics", "max_stars_repo_head_hexsha": "95e7bc6cf63aa2c009daad1a0de22206e327d58b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/report/content.tex", "max_issues_repo_name": "florian-legendre/2021_m1csa_algo_metaheuristics", "max_issues_repo_head_hexsha": "95e7bc6cf63aa2c009daad1a0de22206e327d58b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/report/content.tex", "max_forks_repo_name": "florian-legendre/2021_m1csa_algo_metaheuristics", "max_forks_repo_head_hexsha": "95e7bc6cf63aa2c009daad1a0de22206e327d58b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.4827586207, "max_line_length": 883, "alphanum_fraction": 0.6941842311, "num_tokens": 2607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.34860323067900834}}
{"text": "\\documentclass[runningheads,a4paper]{llncs}\r\n\r\n\\usepackage{amssymb}\r\n\\setcounter{tocdepth}{3}\r\n\\usepackage{graphicx}\r\n\r\n%%%%%%%%%ADDED PACKAGES%%%%%%%%%%\r\n\\usepackage{amsmath}\r\n\\usepackage{graphicx}\r\n\\usepackage{booktabs}\r\n\\usepackage[caption=false]{subfig}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n\\usepackage{url}\r\n\\urldef{\\mailsa}\\path||\r\n\\urldef{\\mailsb}\\path||\r\n\\urldef{\\mailsc}\\path|simon.andermatt@unibas.ch|    \r\n\\newcommand{\\keywords}[1]{\\par\\addvspace\\baselineskip\r\n\\noindent\\keywordname\\enspace\\ignorespaces#1}\r\n\r\n\r\n\\DeclareMathOperator*{\\argmax}{arg\\,max}\r\n\\begin{document}\r\n\r\n\\mainmatter  % start of an individual contribution\r\n\r\n% first the title is needed\r\n\\title{Multi-Dimensional Gated Recurrent Units\\\\\r\nfor the Segmentation of Biomedical 3D-Data}\r\n\r\n% a short form should be given in case it is too long for the running head\r\n\\titlerunning{Multi-Dimensional GRU for the Segmentation of Biomedical Data}\r\n\r\n% the name(s) of the author(s) follow(s) next\r\n%\r\n% NB: Chinese authors should write their first names(s) in front of\r\n% their surnames. This ensures that the names appear correctly in\r\n% the running heads and the author index.\r\n%\r\n\\author{Simon Andermatt \\and Simon Pezold \\and Philippe Cattin}\r\n% index{Andermatt, Simon}\r\n% index{Pezold, Simon}\r\n% index{Cattin, Philippe}\r\n%\r\n\\authorrunning{Multi-Dimensional GRU for the Segmentation of Biomedical Data}\r\n\r\n% the affiliations are given next; don't give your e-mail address\r\n% unless you accept that it will be published\r\n\\institute{Department of Biomedical Engineering, \r\nUniversity of Basel,\r\nSwitzerland\r\n\\mailsc\\\\\r\n}\r\n\r\n%\r\n% NB: a more complex sample for affiliations and the mapping to the\r\n% corresponding authors can be found in the file \"llncs.dem\"\r\n% (search for the string \"\\mainmatter\" where a contribution starts).\r\n% \"llncs.dem\" accompanies the document class \"llncs.cls\".\r\n%\r\n\r\n\\toctitle{Multi-Dimensional Gated Recurrent Units for the Segmentation of Volumetric Biomedical Data}\r\n\\tocauthor{Simon Andermatt}\r\n\\maketitle\r\n\r\n\r\n\\begin{abstract}\r\nWe present a supervised deep learning method to automatically segment 3D volumes of biomedical image data. The presented method takes advantage of a neural network with the main layers consisting of multi-dimensional gated recurrent units. We apply an on-the-fly data augmentation technique which allows for accurate estimations without the need for either a huge amount of training data or advanced data pre- or postprocessing. We show that our method performs amongst the leading techniques on a popular brain segmentation challenge dataset in terms of speed, accuracy and memory efficiency. We describe in detail advantages over a similar method which uses the well-established long~short-term~memory.\r\n\r\n\\keywords{deep learning, GRU, multi-dimensional RNN, segmentation}\r\n\\end{abstract}\r\n\r\n\r\n\\section{Introduction}\r\nWith the rapid advancements of imaging technologies, their ubiquitous availability and dropping prices, vast amounts of data are collected. This is particularly true for medical imaging. Accurate segmentation and delineation of e.g. pathologies in this medical data, however, pose real challenges as this is still mainly a manual process. In late phase drug studies with thousands of patients, multiple 3d datasets with different MR sequences are often collected per patient. If quantitative analysis of the immense amount of data is required, the time that has to be spent on the data by trained experts is enormous. A successful automated segmentation technique would decrease manual work to a minimum, cutting the costs and time spent on developing new treatments.\r\n\r\nAutomatic segmentation of biomedical volumetric data is, however, a challenging problem due to its high dimensionality, imaging noise, artifacts and other factors. Recent advances in the field of deep learning, especially the enabling effect of modern GPUs along with the advent of general purpose GPU computing, led to a revival of convolutional neural networks~\\cite{krizhevsky_imagenet_2012}. These feed-forward networks show great promise, but need a large number of layers to solve a difficult task accurately. A recurrent neural network (RNN), in contrast, can become arbitrarily deep due to its additional temporal dimension. Each timestep computed in an RNN corresponds roughly to one layer in a feed-forward network, with the weights in one RNN being the same for each timestep. This property allows defining substantially more complexity very elegantly without the need for a huge number of layers or parameters.\r\n\r\nThe multi-dimensional Long Short-Term Memory (MD-LSTM) proposed by Stollenga et al.~\\cite{stollenga_parallel_2015}, called \\textit{PyraMiD-LSTM}, applied these insights to the Long Short-Term Memory (LSTM)~\\cite{hochreiter1997long}. It defines two LSTMs for each spatial dimension, using said spatial dimension as temporal dimension. The first one processes the data along that dimension, the second one in the opposite direction. In order to make full use of the spatial information, not only the direct predecessor along the temporal direction is taken into account, but also its local neighborhood. This can be neatly expressed using convolutions. \r\n\r\nA relatively new RNN called Gated Recurrent Unit (GRU)~\\cite{cho_learning_2014} grew popular in recent years and became a strong competitor for the LSTM. It can be seen as a simplified version of the LSTM, which uses an update gate instead of a forget and input gate and combines the hidden and cell state~\\cite{olah_understanding_2015}. It has been shown that it performs comparably to the LSTM in the task of sequence modeling~\\cite{chung_empirical_2014}. Another study suggests that GRU and LSTM report similar performance on selected tasks~\\cite{greff_lstm:_2015}. An empirical search among more than 10\\,000 RNN architectures showed that on the selected tasks, although not the best performing RNN on every task, the GRU outperformed the standard LSTM architecture~\\cite{jozefowicz_empirical_2015}.\r\nA larger time dimension in an RNN can mean that larger time dependencies can be represented. The lower memory requirement of the GRU means that larger volumes can be fed into the network and larger networks can be designed for the same volume size.\r\n\r\nFor all these reasons, a modification of the GRU to be able to process volumetric data seems compelling. We propose the multi-dimensional GRU (MD-GRU), which is capable of accurate segmentation of 3d data. We hint at the theoretical memory savings compared to the MD-LSTM and show that the performance of MD-GRU is comparable if not superior. Furthermore, we show that its convergence rate, computation time and combination of fewer gates favor the MD-GRU. We apply our method on a popular brain segmentation challenge dataset, achieving a score among the top 3 best performing methods. \r\n\r\n\\section{Methods}\r\n\\subsection{Data}\r\n\\begin{figure}\r\n \\centering\r\n \\begin{minipage}{.24\\textwidth}\r\n \\includegraphics[width=.99\\linewidth]{./images/t1.png}\r\n \\end{minipage}\r\n  \\begin{minipage}{.24\\textwidth}\r\n \\includegraphics[width=.99\\linewidth]{./images/t1-ir.png}\r\n  \\end{minipage}\r\n  \\begin{minipage}{.24\\textwidth}\r\n \\includegraphics[width=.99\\linewidth]{./images/t2-flair.png}\r\n  \\end{minipage}\r\n  \r\n   \\begin{minipage}{.24\\textwidth}\r\n \\includegraphics[width=.99\\linewidth]{./images/t1-gs.png}\r\n \\end{minipage}\r\n  \\begin{minipage}{.24\\textwidth}\r\n \\includegraphics[width=.99\\linewidth]{./images/t1-ir-gs.png}\r\n  \\end{minipage}\r\n  \\begin{minipage}{.24\\textwidth}\r\n \\includegraphics[width=.99\\linewidth]{./images/t2-flair-gs.png}\r\n  \\end{minipage}\r\n  \\caption{Slice 19 of the 5th training sample. \\emph{Top row (left to right):} T1, T1\\_IR and T2\\_FLAIR. \\emph{Bottom row:} respective highpass filtered versions.}\r\n  \\label{data}\r\n\\end{figure}\r\nWe used the publicly available MrBrainS~\\cite{mendrik2015mrbrains} challenge dataset, which was one of the datasets used to evaluate the PyraMiD-LSTM. The MrBrainS challenge data consists of 5 labeled samples and 15 testing samples, where each sample has a T1 weighted, T1 inversion recovery and a FLAIR scan. The additional high-resolution T1 scan was not used, as the labeling was performed on the low resolution data. The training data contained two different label maps, one for training and one for testing. The training map consists of classes for cortical gray matter (GM), basal ganglia, white matter (WM), WM lesions, cerebrospinal fluid (CSF), ventricles, cerebellum, brainstem and background. The testing map only defines classes for GM, WM and CSF, the respective classes of the training map are merged. Brainstem and cerebellum are not included in the evaluation and do therefore not appear labeled in the testing map.\r\n\r\n\r\n\\subsection{Convolutional Gated Recurrent Unit}\\label{reordering}\r\n\r\n\r\nThe standard GRU as proposed in~\\cite{cho_learning_2014} is defined as\r\n\\begin{align}\r\n r^j &= \\sigma([W_r x]^j + [U_r h_{t-1}]^j),\\\\\r\n z^j &= \\sigma([W_z x]^j + [U_z h_{t-1}]^j),\\\\\r\n \\tilde{h}^j_t &= \\phi([Wx]^j + [U(r \\odot h_{t-1})]^j),\\\\\r\n h^j_{t} &= z^j\\odot h^j_{t-1} + (1-z^j)\\odot \\tilde{h}^j_{t},\r\n\\end{align}\r\nwhere $x$ is the input data, $r^j$ is the reset gate, $z^j$ is the update gate of the hidden unit $j$ and the activation is performed in $h^j$. The operator $\\odot$ represents an elementwise multiplication. The functions $\\sigma(\\cdot)$ and $\\phi(\\cdot)$ stand for the logistic function and the hyperbolic tangent. $W$ and $U$ are the weight matrices for the current input and last step's output data respectively. Along the lines of Stollenga et al.~\\cite{stollenga_parallel_2015}, we adapt these equations to be able to process 3D volumes and introduce our convolutional GRU (C-GRU):\r\n\\begin{align}\\label{eq:cgru1}\r\n r^j &= \\sigma \\left( \\sum\\limits_i^I (x^i*w_r^{i,j}) + \\sum\\limits_k^J ( h_{t-1}^k*u_r^{k,j} ) +b^j_r\\right),\\\\\\label{eq:cgru2}\r\n z^j &= \\sigma \\left( \\sum\\limits_i^I (x^i*w_z^{i,j}) + \\sum\\limits_k^J ( h_{t-1}^k*u_z^{k,j} ) +b^j_z\\right),\\\\\\label{eq:cgru3}\r\n \\tilde{h}^j_t &= \\phi \\left( \\sum\\limits_i^I (x^i*w^{i,j}) + r^j \\odot \\sum\\limits_k^J ( h_{t-1}^k * u^{k,j} ) +b^j\\right),\\\\\r\n  h^j_{t} &= z^j\\odot h^j_{t-1} + (1-z^j)\\odot\\tilde{h}^j_{t},\r\n\\end{align}\r\nwhere $*$ represents a convolution. Compared to the vanilla GRU, we introduced slight changes. We decided to use a bias $b$ on each gate. We factored $r^j$ out of the convolution operation between $u$ and $h_{t-1}$. This change was motivated by the fact that an additional convolution would require $r$ to have twice the support it needs now because of the chained convolution. Moreover, we reorder the data for each C-RNN such that the two spatial dimensions are closest to memory, and the temporal dimension is ordered according to the temporal direction, as explained in the next paragraph. We motivated that decision with faster possible processing speeds on the GPU, since all convolutions now require data that lies close in memory. The computations of one C-GRU are visualized as a computational graph in Fig.~\\ref{fig:network}a.\r\n\r\nThe MD-GRU consists of two times $D$ C-GRUs, where $D$ is the dimensionality of the image data and we need one C-GRU for each of the two directions. We set the input data of channel $i$ as $x^i \\in \\mathbb{R}^{S_1\\times \\cdots\\times S_D}$. For each spatial dimension $d$, we create the copies $x^{i,d,-1}, x^{i,d,+1} \\in \\mathbb{R}^{S_d\\times S_1\\times \\cdots\\times S_D}$ of $x$ and apply the following data transformations:\r\n\\begin{align}\r\n x^{i,d,+1}(s_d, s_1, \\dots, s_{D}) &= x^i(s_1, \\dots, s_d,\\dots, s_{D}),\\\\\r\n x^{i,d,-1}(S_d-s_d, s_1, \\dots, s_{D}) &= x^i(s_1,\\dots , s_d,\\dots, s_{D}),\r\n\\end{align}\r\nwhere $s_d$ is the index of the assigned dimension of the C-GRU and $S_d$ is the size of dimension $d$. The inverse operation is applied to $h^{j,d,+1},h^{j,d,-1} \\in \\mathbb{R}^{S_d\\times S_1\\times \\cdots\\times S_D}$ to gather the final output $h^j$:\r\n\\begin{align}\r\nh^j(s_1,\\dots, s_{D}) &= \\sum\\limits_{d=1}^D \\left ( h^{j,d,+1}(s_d, s_1, \\dots, s_{D}) + h^{j,d,-1}(S_d-s_d, s_1, \\dots, s_{D}) \\right ).\r\n\\end{align}\r\n\r\nFigure~\\ref{fig:network}b details this process for the MD-GRU. We apply the same technique for our implementation of the MD-LSTM.\r\n\\subsection{Experiments}\r\n\\subsubsection{Network}\r\nWe model our network similar to~\\cite{stollenga_parallel_2015}. We include three multi-dimensional RNN (MD-RNN) layers of 16, 32 and 64 channels which are connected with pixelwise fully connected hidden layers of 25 and 45 channels respectively, each followed by a hyperbolic tangent activation function. The last MD-RNN is attached to a pixelwise fully connected layer with $c$ channels, the same number as classes in the data. We estimate the probabilities for each class using a softmax in the last layer and consequently choose the multinomial logistic loss for the training of our network. Figure~\\ref{fig:network}c shows our network setup for the case of MD-GRU.\r\n\r\n\r\n\\begin{figure}\r\n \\centering\r\n \\subfloat[][C-GRU]{\r\n          \\includegraphics[width=0.35\\textwidth]{images/cgrunotitle3.pdf}\r\n }\\qquad\r\n \\subfloat[][MD-GRU]{\r\n          \\includegraphics[width=0.48\\textwidth]{images/mdgrunotitle2.pdf}\r\n }\\quad\r\n \r\n  \\subfloat[][Network Architecture]{\r\n          \\includegraphics[width=0.99\\textwidth]{images/network.pdf}\r\n }\r\n \\caption{(a) Directed graph denoting the computations in one C-GRU. The variables $x^{d,o}$, $h^{d,o}$ with $o \\in \\{-1,+1\\}$ represent the input and output data across all $I$ and $J$ channels respectively. The $\\circledast$ operator denotes here the sum per channel $j$ over the convolutions with each channel $i$ or $k$, as used in equations (\\ref{eq:cgru1})--(\\ref{eq:cgru3}). (b) Proposed arrangement of 6 C-GRUs in a MD-GRU for three-dimensional data. (c) Setup of our network.} \\label{fig:network}\r\n\\end{figure}\r\n\r\n\r\n\\subsubsection{Setting}\\label{setting}\r\nAll experiments were calculated on an NVIDIA GTX Titan X GPU with 12 GB global memory. Our implementation of MD-LSTM and MD-GRU relied on the fast convolution routines provided by NVIDIA's cuDNN~\\cite{chetlur_cudnn:_2014}. For other layers, the already available implementations of the CAFFE\\footnote{version 1.0.0-rc3, commit 9c46289} framework~\\cite{jia2014caffe} were used.\r\n\r\n\\subsubsection{Preprocessing}\r\nFor all volumes, unsharp masking was done using a Gaussian smoothed image ($\\sigma=5$~voxels) which was then subtracted from the original images to produce highpass filtered volumes. The original images and the highpass filtered images were normalized to $\\sigma=1$ and $\\mu=0$, assuming normally distributed values. In this way we followed a procedure similar to~\\cite{stollenga_parallel_2015}, but omitted the histogram equalization. Figure \\ref{data} shows the original and preprocessed data for training sample 5 at slice 19.\r\n\r\n\\subsubsection{Data augmentation}\r\nIn the training stage, at each iteration, a random location in the training data was selected and a deformation field was generated and applied to the subvolumes, which were then fed into the network. We used a procedure similar to~\\cite{ronneberger_u-net:_2015}, but made the grid size dependent on the data. We did not use random deformations in the feasibility study mentioned in Sec.~\\ref{feasibilitystudylabel}. For the testing phase, no deformations were applied.\r\n\r\n\\subsubsection{Training}\r\nIn three training steps we iteratively increase the subvolume size from $64\\times64\\times8$~voxels to $128\\times128\\times12$ and finally to $200\\times200\\times15$, keeping the third dimension smaller to account for the anisotropic MR volume resolution. We relied on AdaDelta~\\cite{zeiler_adadelta_2012} to omit the manual tuning of a learning rate. For the challenge, we additionally used DropConnect~\\cite{icml2013_wan13} of 0.5 on the input connections of each C-GRU to prevent overfitting. Training took around two days.\r\n\r\n\r\n\\subsubsection{Testing}\r\nIn the testing phase, we divided the volume into a grid of equally sized subvolumes of $120\\times120\\times8$, which were padded by 50, 50 and 4 voxels respectively on all sides of the volume. The padding was later used to stitch the results together using a Gaussian ($\\mu=0$, $\\sigma=(10,10,0.8)$) to produce interpolation weights, since the borders contain starting artifacts from the individual RNNs and do not contain adequate results. Since we trained for nine classes, but only four classes were needed for the final evaluation, we simply combined the binary labels for the CSF with the ventricles, the cortical GM with the basal ganglia and the WM with the WM lesions. Everything else was considered background. Testing one volume of the MRBrainS data required 32 iterations, which needed around two minutes.\r\n\r\n\r\n\\section{Results}\r\n\r\n\\subsection{Feasibility Study}\r\n\\label{feasibilitystudylabel}\r\n\\begin{table}\r\n\\caption{Feasibility study. Dice coefficients in percent for gray and white matter (GM/WM), cerebrospinal fluid (CSF) and intracranial volume (ICV).}% The case with more memory was only trained until iteration 28000}\r\n\\begin{center}\r\n\\begin{tabular}{lllll}\\toprule\r\n× & GM & WM & CSF & ICV\\\\ \\midrule\r\nMD-LSTM  & \\textbf{88.09}  & 90.08 & 82.62  & 97.56 \\\\ \r\nMD-GRU & 87.88 & \\textbf{90.15 } & \\textbf{83.19} & \\textbf{97.73 }\\\\ \\bottomrule\r\n\\end{tabular}\r\n\\label{feasibilityquantitative}\r\n\\end{center}\r\n\\end{table}\r\n\r\n\\begin{figure}\r\n \\centering\r\n \\begin{minipage}{.24\\textwidth}\r\n \\includegraphics[width=.98\\linewidth]{./images/lstmfeas_new_new.png}\r\n \\end{minipage}\r\n  \\begin{minipage}{.24\\textwidth}\r\n \\includegraphics[width=.98\\linewidth]{./images/grusfeas_new_new.png}\r\n  \\end{minipage}\r\n  \\begin{minipage}{.24\\textwidth}\r\n \\includegraphics[width=.98\\linewidth]{./images/Traindata5atslice19-Testlabel.png}\r\n  \\end{minipage}\r\n  \r\n  \\begin{minipage}{0.80\\textwidth}\r\n    \\includegraphics[width=.9\\linewidth]{./images/convergence_rate_new10000_mediumlines_withtitle6.pdf}\r\n  \\end{minipage}\r\n  \\caption{Feasibility study. \\emph{Top row:} slice 19 of the 5th training volume used for the evaluation. The images from left to right represent the results of the MD-LSTM, the MD-GRU and the manual labeling. \\emph{Bottom row:} convergence rates for the feasibility study of both MD-GRU and MD-LSTM.}\r\n\\label{feasibilityqualitative}\r\n\r\n\\end{figure}\r\nTo point out differences between the MD-GRU and the MD-LSTM, we ran the same setup with the multi-dimensional RNN layers either being an MD-GRU or an MD-LSTM. We used the first four volumes in the training set of the MrBrainS challenge and trained both networks for 3\\,000 iterations on the largest possible resolution which was feasible for both (limited to $192\\times192\\times14$ by our MD-LSTM implementation). On average, one training iteration for MD-GRU and MD-LSTM took 9.1 and 12.8 seconds, respectively. The Dice coefficients for CSF, GM, WM and ICV between the computed segmentation of the 5th training volume and the provided reference segmentation are shown in Table~\\ref{feasibilityquantitative} for both the MD-GRU and MD-LSTM. Slice 19 of the computed segmentations and the reference segmentation are displayed in Fig.~\\ref{feasibilityqualitative} together with a plot of a running average of 100 iterations of the loss function for each iteration of the training procedure.\r\n\r\n\r\n\\subsection{MD-GRU on MRBrainS}\r\nIn our attempt to beat the highscore of the MRBrainS challenge, we used our described data augmentation method. Each subvolume was deformed randomly throughout all three training phases. We used all provided low resolution volumes and their highpass filtered versions. Table~\\ref{mrbrainsres} lists our performance according to the Dice coefficients, 95th-percentile  of the Hausdorff distance and average volume difference of the GM, WM, CSF and ICV. Nine measures were relevant for the final evaluation: Dice, modified Hausdorff distance and average volume distance in each of the categories GM, WM and CSF. The sum of the ranks in these nine categories is used as the performance score and determines the final rank. \r\nFigure~\\ref{visualresultschallenge} shows the computed segmentation at slice 19 of samples 5, 10 and 15 of the test data. \r\n\\begin{table}\r\n\\begin{center}\r\n \\caption{MrBrainS challenge. Results of the six best performing methods for GM, WM, CSF and ICV of all three used metrics (Dice, 95th-percentile of the Hausdorff distance (HD) and average volume difference (AVD)). A bold number means best out of these six. The results reflect the state on August 12, 2016.}\r\n\\label{mrbrainsres}\r\n \\scriptsize\r\n\\begin{tabular}{l c rcl rcl rcl rcl rcl}\r\n\\toprule\r\nTeam name &  Rank &\\multicolumn{3}{c}{GM} & \\multicolumn{3}{c}{WM} & \\multicolumn{3}{c}{CSF} &  \\multicolumn{3}{c}{ICV}\\\\%\\hline\\hline\r\n×& × & Dice & HD & AVD & Dice & HD & AVD & Dice & HD & AVD & Dice & HD & AVD \\\\\\midrule\r\nCU\\_DL2  & \\textbf{1}& \\textbf{86.15} & \\textbf{1.45} & 6.60 & \\textbf{89.46} & \\textbf{1.94} & 6.05 & \\textbf{84.25}& 2.19 & 7.69 &  98.10 & 2.75 & 1.54\\\\\r\nCU\\_DL& 2  & 86.12 & 1.47 & 6.42 & 89.39 & \\textbf{1.94} & \\textbf{5.84} & 83.96 & 2.28 & 7.44 &  97.99 & 3.16 & 1.83 \\\\\r\nMD-GRU [proposed] & 3 & 85.40 & 1.55 & \\textbf{6.09} & 88.98 & 2.02 & 7.69 & 84.13 & 2.17 & 7.44 & \\textbf{98.15} & \\textbf{2.37} & 0.86\\\\\r\nPyraMiD-LSTM2 & 4 & 84.89 & 1.67 & 6.35 & 88.53 & 2.07 & 5.93 & 83.05 & 2.30 & 7.17 &  98.04 & 2.86 & \\textbf{0.69}\\\\\r\nFBI/LMB Freiburg~\\cite{cicek_3d_2016}& 5 & 85.44 & 1.58 & 6.60 & 88.86 & 1.95 & 6.47 & 83.47 & 2.22 & 8.63 &  97.98 & 2.51 & 1.06\\\\\r\nIDSIA~\\cite{stollenga_parallel_2015} & 6 & 84.82 & 1.70 & 6.77 & 88.33 & 2.08 & 7.05& 83.72 & \\textbf{2.14} & \\textbf{7.09}& \\textbf{98.15} & 2.44 & 0.95\\\\\\bottomrule\r\n\\end{tabular}\r\n\\end{center}\r\n \\label{resultschallenge}\r\n\\end{table}\r\n\r\n\\begin{figure}\r\n \\centering\r\n \\begin{minipage}{.24\\textwidth}\r\n \\includegraphics[width=.99\\linewidth]{./images/sl19-v5-test-challres_new.png}\r\n \\end{minipage}\r\n  \\begin{minipage}{.24\\textwidth}\r\n \\includegraphics[width=.99\\linewidth]{./images/sl19-v5-test-t1.png}\r\n  \\end{minipage}\r\n  \\begin{minipage}{.24\\textwidth}\r\n \\includegraphics[width=.99\\linewidth]{./images/sl19-v5-test-t1-ir.png}\r\n  \\end{minipage}\r\n  \\begin{minipage}{.24\\textwidth}\r\n \\includegraphics[width=.99\\linewidth]{./images/sl19-v5-test-t2-flair.png}\r\n  \\end{minipage}\r\n  \r\n  \\vspace{0.3em}\r\n   \\begin{minipage}{.24\\textwidth}\r\n \\includegraphics[width=.99\\linewidth]{./images/sl19-v10-test-challres_new.png}\r\n \\end{minipage}\r\n  \\begin{minipage}{.24\\textwidth}\r\n \\includegraphics[width=.99\\linewidth]{./images/sl19-v10-test-t1.png}\r\n  \\end{minipage}\r\n  \\begin{minipage}{.24\\textwidth}\r\n \\includegraphics[width=.99\\linewidth]{./images/sl19-v10-test-t1-ir.png}\r\n  \\end{minipage}\r\n  \\begin{minipage}{.24\\textwidth}\r\n \\includegraphics[width=.99\\linewidth]{./images/sl19-v10-test-t2-flair.png}\r\n  \\end{minipage}\r\n  \r\n  \\vspace{0.3em}\r\n   \\begin{minipage}{.24\\textwidth}\r\n \\includegraphics[width=.99\\linewidth]{./images/sl19-v15-test-challres_new.png}\r\n \\end{minipage}\r\n  \\begin{minipage}{.24\\textwidth}\r\n \\includegraphics[width=.99\\linewidth]{./images/sl19-v15-test-t1.png}\r\n  \\end{minipage}\r\n  \\begin{minipage}{.24\\textwidth}\r\n \\includegraphics[width=.99\\linewidth]{./images/sl19-v15-test-t1-ir.png}\r\n  \\end{minipage}\r\n  \\begin{minipage}{.24\\textwidth}\r\n \\includegraphics[width=.99\\linewidth]{./images/sl19-v15-test-t2-flair.png}\r\n  \\end{minipage}\r\n  \\caption{MrBrainS challenge. \\emph{Rows (top to bottom):} 5th, 10th and 15th test sample. \\emph{Columns (left to right):} slice 19 of our segmentation results, T1, T1\\_IR and T2\\_FLAIR.}\r\n   \\label{visualresultschallenge}\r\n\r\n\\end{figure}\r\n\r\n\r\n\r\n\\section{Discussion}\r\n\r\nThe feasibility study has shown that MD-GRU has great potential for the segmentation of volumetric images, since it achieved comparable results to the MD-LSTM in less time with the same settings. \r\n\r\nUsing deformation as a data augmentation strategy and DropConnect for regularization in the challenge, we ranked 3rd out of 37. Unfortunately, none of the results in the top five of the challenge highscore are published so far. The 4th and 6th entries are both incarnations of the already discussed MD-LSTM, where only the latter was described in~\\cite{stollenga_parallel_2015} and the former likely contains unpublished improvements to their method. In contrast to \\cite{stollenga_parallel_2015}, we did not omit the original T1\\_IR images. Yet some obvious misclassifications could be traced back to strong bias field artifacts in the T1\\_IR images. Given the small training size, using the T1\\_IR images leads to apparent fitting to the bias field. Furthermore, we were not able to replicate the training volume size of Stollenga et al.~\\cite{stollenga_parallel_2015} due to a higher memory requirement of our implementation, since we decided to copy the input and output data for each RNN layer, as detailed in Sec.~\\ref{reordering}. This has to be kept in mind when comparing the two approaches. Relationships between areas that are located at a certain distance in the data could therefore not be modeled in our network, where~\\cite{stollenga_parallel_2015} was able to use the full spatial context in two dimensions as well as a larger third dimension. In their last training step more than half of the data was covered while we could only fit a bit more than a fifth in our memory. \r\n\r\nThe contribution on rank five was computed using the 3D U-Net~\\cite{cicek_3d_2016}. It consists of a hierarchical convolutional neural network with shortcut connections, which is trained using various on-the-fly data augmentation techniques, including the deformation strategy used in this paper. The challenge results and corresponding adaptations of the algorithm to fit the challenge data are, however, not yet published. We believe that data augmentation is key for successful applications to problems with such a small training size. \r\n\r\n\r\n \\subsubsection{Conclusion}\r\n With the MD-GRU, we combined the enormous expressive power of RNNs with a highly beneficial data augmentation strategy, resulting in a powerful supervised automatic segmentation technique. With a memory-savvy implementation that omits the initial reordering of the data, results surpassing the state of the art should be possible with MD-GRU.\r\n\r\n\r\n\r\n\\bibliographystyle{splncs03}\r\n\\bibliography{manuallib}\r\n\\end{document}\r\n", "meta": {"hexsha": "c23059ca1926fb28d6750fedd370742ddf7699b7", "size": 26276, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "dlmiapaper/paper34.tex", "max_stars_repo_name": "zubata88/dlmia16", "max_stars_repo_head_hexsha": "096fc18c40b20ed3c719851faf9773f95d1058fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dlmiapaper/paper34.tex", "max_issues_repo_name": "zubata88/dlmia16", "max_issues_repo_head_hexsha": "096fc18c40b20ed3c719851faf9773f95d1058fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dlmiapaper/paper34.tex", "max_forks_repo_name": "zubata88/dlmia16", "max_forks_repo_head_hexsha": "096fc18c40b20ed3c719851faf9773f95d1058fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 84.7612903226, "max_line_length": 1491, "alphanum_fraction": 0.7551758258, "num_tokens": 7324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.3485389718040475}}
{"text": "\\section{Static Obstacle Avoidance}\n\\label{chap:StaticObstacleAvoidance}\nFor the static obstacle avoidance task, the controller must drive the vehicle in order to avoid collision with any still obstacle detected by a set of sensors mounted on the vehicle.\\\\\nBefore implementing the algorithm for obstacle avoidance, we have made a set of assumptions with the aim of simplifying this task:\n\\begin{itemize}\n    \\item we have a set of sensor able to determine the position of the obstacle and to place it on the reference map, but the detection is performed only when the distance from the obstacle is less than 200 $m$;\n    \\item it is always possible to avoid the obstacle by moving to the left lane;\n    \\item the obstacle is never placed at less than 200 $m$ from the starting point, therefore it is always possible to avoid it without violating the zones (described below); \n    \\item dimensions of the obstacle are not relevant.\n\\end{itemize}\nTo be sure that the controller tries to avoid obstacles, we have decided to implement the avoidance algorithm by giving to the controller a set of constraints on the output, in order to define a \\textit{``forbidden zone\"}, as described in subsection \\ref{sec:Safety_distance}.\\\\\nTo be precise, we have defined 5 zones nearby each obstacle:\n\\begin{itemize}\n    \\item \\textbf{Zone 1}: the obstacle is detected, but the vehicle is still too far from it, so it stays in its lane;\n    \\item \\textbf{Zone 2}: the vehicle is close enough to the obstacle to start the overtaking maneuver, so it can start the lane change;\n    \\item \\textbf{Zone 3}: the vehicle is in the left lane, in the so called \\textit{``Safe Zone\"};\n    \\item \\textbf{Zone 4}: the obstacle is passed and the vehicle can come back to the right lane;\n    \\item \\textbf{Zone 5}: the vehicle is in its lane and the obstacle has been already passed, so we are in the same condition of no obstacle detected.\n\\end{itemize}\nThese zones are defined, starting from the obstacle position, in the following way:\n\\begin{itemize}\n    \\item \\textbf{Zone 1} starts when the obstacle is detected, so when the distance between the vehicle and the obstacle is less than 200 $m$, as specified in the assumptions made at the start of this section;\n    \\item \\textbf{Zone 2} starts 40 meters before the Zone 3. We have decided to define this zone in this way to be symmetric with respect to Zone 4, where the other lane change maneuver is performed;\n    \\item \\textbf{Zone 3} is defined to be compliant with the Safety Distance described in \\ref{sec:Safety_distance}, according to equation \\ref{eq:safetyDistance}: $SafetyDistance [m] = \\left(\\frac{v[\\sfrac{km}{h}]}{10}\\right)^2$, so it is proportional to the square of the speed. Zone 3 ends 10 meters after the obstacle, to be compliant with the requirement n° 4 in section \\ref{System_Requirements};\n    \\item \\textbf{Zone 4} is defined to be compliant with requirement n° 4 in Section \\ref{System_Requirements}, so it starts 10 meters after the obstacle and ends 50 meters after it, resulting in a space of 40 meters for the re-entering maneuver, thus it is symmetric with respect to the maneuver performed in Zone 2 as previously stated;\n    \\item \\textbf{Zone 5} starts right after Zone 4 and it is kept until the distance from the obstacle becomes greater then 200 $m$.\n\\end{itemize}\nThe distance of 200 $m$ from the obstacle is evaluated as the Euclidean distance between the vehicle and the obstacle, while the other distances involved in the definition of the zones are evaluated as projection on the reference path, and assuming constant speed, they result in fixed points on the reference map.\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=1\\textwidth]{Figures/Zones.png}\n    \\caption{Zones defined for obstacle avoidance}\n      \\label{fig:Zones}\n\\end{figure}\nIn Figure \\ref{fig:Zones} the aforementioned zones are depicted on a straight line scenario with a reference speed of 100 $km/h$.\\\\\\\\\nIn Zones 1 and 5, as previously said, the obstacle is too far from the vehicle to be a problem, so no procedure is applied to the controller.\\\\\\\\\nIn Zone 2, the yellow one in the figure, the vehicle should pass in the left lane. To do so, we have defined two points, represented in the figure respectively with a green circle, which is called the \\textbf{\\textit{Detection Point}}, and a red circle that is the \\textbf{\\textit{Safe Point}}.\nThe latter is defined as the projection on the left lane of the point in the reference trajectory at a distance equal to the safety distance. \\\\To let the controller move on the path defined by these two points, we have exploited the \\textit{Custom Constraint} of the MPC block in Simulink.\\\\\\\\\nAs briefly explained in Section \\ref{chap:Controller}, the linear combination of inputs and states can be set as constraints for the controller. To accomplish our task, we have defined 2 constraints on the \\textit{x} and \\textit{y} states, which result in two lines representing an upper and a lower bound for the vehicle position during the overtaking maneuver. Looking at the example in Figure \\ref{fig:Zones}, the lower bound becomes the border of the polygon defined by Zones 2, 3 and 4, while the upper bound is the left limit of the road, that is to say the left border of the left lane (straight line $y=6$ in Figure \\ref{fig:Zones}).\\\\\nFor what concerns the lower bound for constraints in Zone 2, it is completely defined by the line passing from the two aforementioned points (\\textit{Detection Point} and \\textit{Safe Point}) .\\\\\\\\\nIn Zone 3, the vehicle should stay in the left lane. To define constraints in this zone, we have set as lower bound the projection of the reference trajectory on the left lane instead of the straight line connecting points from the start (red circle) to the end (blue cross), since the former method allows to track both straight and curved paths. One limitation of the \\textit{linear} constraints is that they can only define \\textit{linear} relation between states, thus when the path is curved, we have to approximate it to a straight line, but this can cause errors because the controller tries to satisfy the constraint for all the timesteps in the prediction horizon, so resulting in a reduced or increased distance with respect to the points in the reference map. To limit this effect, we have inserted a correction factor to the constraint generated.\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=1\\textwidth]{Figures/ConstraintCorrection.png}\n    \\caption{Constraints generated in a curved path with 300 $m$ radius at 50 $km/h$, with and without the correction factor}\n      \\label{fig:CorrectionConstraint}\n\\end{figure}\nIn Figure \\ref{fig:CorrectionConstraint} a case where the reference road is a left curve with 300 meters radius is represented. The dashed red line is the projection of the road approximated with the slope of the reference point where the controller is called, while the green dashed line is the projection evaluated with the correction factor. As it can be seen, the original projection \"collapses\" on the reference path before the corrected one does, resulting in a reduction of the distance from the reference during the predicted horizon and a consequent reduction of distance between the trajectory and starting lane, occupied by the obstacle.\\\\\nThis corrected constraint is evaluated according to the following procedure:\n\\begin{enumerate}\n    \\item an approximation of the \\textit{curvature} of the road is evaluated as the mean value of the reference angle in the prediction horizon: $curvature = \\frac{\\sum_{i=0}^{p}\\theta_i-\\theta_0}{p}$;\n    \\item the correction factor is: $416\\cdot\\frac{|curvature|}{V}$, where the coefficient 416 has been found empirically by simulations;\n    \\item the \\textit{CorrectedSlope} is given by the road slope ($tan(\\theta_r)$) plus the correction factor;\n    \\item the intercept for the constraint line is given by:\\\\\n    $CorrectedIntercept = y_r + Lw/cos(\\theta_r) - CorrectedSlope\\times x_r$\\\\\n    where $x_r$, $y_r$, and $\\theta_r$ are the reference trajectory values at the first timestep of the prediction horizon, and $Lw$ is the lane width;\n    \\item the constraint is applied as $y > CorrectedSlope\\times x + CorrectedIntercept$.\n\\end{enumerate}\nObviously, when the reference path is straight, the correction function becomes 0 and the constraint is the simple projection of the road.\\\\\\\\\nIn Zone 4, the situation is analogous to the one in Zone 2, with the only difference that here we are \\textit{``relaxing\"} the constraints, allowing the vehicle to come back to its original position on the right lane. The bounds here are defined by the blue cross point, called \\textbf{\\textit{End Point}} and the yellow diamond point, called \\textbf{\\textit{Entry Point}} (Figure \\ref{fig:Zones}).\\\\\nTo define these bounds in a suitable form for the controller, we have transposed the information in a matrix form, describing two line equations:\n\\begin{equation}\n    y > m_{lower}x + q_{lower}\n\\end{equation}\n\\begin{equation}\n    y < m_{upper}x + q_{upper}\n\\end{equation}\nwhere $m$ is the slope of the constraint and $q$ is the intercept of the constraint.\nThe slope of the constraint can be evaluated by calculating the tangent of the road orientation when we are considering the upper bound of the Zone 3, while it is evaluated as the slope between the points defined above in Zones 2 and 4.\\\\\nThe intercept is given by the projection of the reference trajectory, on the left lane center line for Zone 3 and on the left road limit for the upper bound, or it is evaluated by inverting the line equation in the changing lane maneuvers.\\\\\nTo let our algorithm work on all the quadrants, we make a check of the reference trajectory orientation and we adapt the constraint generation to the case we are in. This check projects the constraints on the $x$ axis rather than $y$ if the road inclination is closer to the vertical line in the X-Y plane, moreover it defines which are the relations between the bounds and the reference trajectory, intended as \\textit{``lower than\"} or \\textit{``greater than\"}, according to the direction of the vehicle and its left.\n\\subsection{Multiple obstacles avoidance}\nThe procedure described until now shows how the controller sets constraints when an obstacle is detected, but when multiple obstacles are present, things can become harder.\\\\\nIf two obstacles are very far one from the other, at least 400 $m$, they can be treated as single obstacles in sequence, but if they are close, a new definition of the zones is needed. In detail, we have decided to control the position of the next obstacle when we reach the \\textit{End Point} of the previous. In this case, we can decide whether to come back in the right lane or to stay in the left lane and continue the overtaking maneuver. The procedure follows the rules below:\n\\begin{itemize}\n    \\item if the next obstacle is more than 400 $m$ far from the previous one, it is treated as an independent single obstacle;\n    \\item if the next obstacle is in the range 400 $m$ and 210 $m$ from the previous obstacle, it is not detected when the vehicle is in the \\textit{End Point} of the previous obstacle. Here the vehicle simply comes back to the right lane and when the next obstacle is detected, it is treated as a single one;\n    \\item if the next obstacle is closer than 210 $m$ from the previous one, it is detected when the vehicle is in the \\textit{End Point} of the latter, so here a decision is taken:\n    \\begin{enumerate}\n        \\item the next \\textit{Detection Point} is after the previous \\textit{Entry Point} $\\xrightarrow{}$ the vehicle reenters in the right lane and starts the new overtaking maneuver when it reaches the next \\textit{Detection Point};\n        \\item the next \\textit{Detection Point} is before the previous \\textit{Entry Point} $\\xrightarrow{}$ the vehicle stays in the left lane and sets as target the next obstacle, so then it repeats this procedure when the next \\textit{End Point} is reached.\n    \\end{enumerate}\n\\end{itemize}\nTo implement this control strategy in the simulation environment, we have used a counter on the obstacles, which takes into account if an obstacle has already been passed and in that case the detection algorithm neglects it, considering the next obstacle.\\\\\nIn real-world scenarios, a counter is not a feasible solution since it is impossible to know how many obstacles will be detected during a trip, but advanced navigation and sensor systems can detect and classify obstacles, and then can understand whether they have been passed or not, so our assumption is justified.\n\n", "meta": {"hexsha": "668bc9c5feb371dcdef968d7cb41b9ce0f81151f", "size": 12646, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Documentation/Report/Chapters/9-StaticObstacleAvoidance.tex", "max_stars_repo_name": "meltinglab/dynamic-obstacle-avoidance", "max_stars_repo_head_hexsha": "2290754436864a817851c71803d5275445cbcdb1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-05-24T07:00:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-19T16:44:04.000Z", "max_issues_repo_path": "Documentation/Report/Chapters/9-StaticObstacleAvoidance.tex", "max_issues_repo_name": "meltinglab/dynamic-obstacle-avoidance", "max_issues_repo_head_hexsha": "2290754436864a817851c71803d5275445cbcdb1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Documentation/Report/Chapters/9-StaticObstacleAvoidance.tex", "max_forks_repo_name": "meltinglab/dynamic-obstacle-avoidance", "max_forks_repo_head_hexsha": "2290754436864a817851c71803d5275445cbcdb1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-04-20T19:24:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T17:58:16.000Z", "avg_line_length": 145.3563218391, "max_line_length": 858, "alphanum_fraction": 0.7753439823, "num_tokens": 2942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.3485389718040475}}
{"text": "\\section{object.size() and Strings}\n\n\\subsection{Comparison to object.size()}\n\n\\R contains a handy tool for telling you how big an already allocated \nobject is, namely the \\code{object.size()} function from the \\code{utils} \npackage.  The functions in this package are essentially an extension of that \nfunction for unallocated, dense objects, provided your objects are numeric (more \non this later).\n\nSo say we have the vector \\code{x <- 1.0}.  This should be using 8 bytes to \nstore that \\code{1.0} as a double, right?  Well\\dots\n\\begin{lstlisting}[language=rr]\nobject.size(1.0)\n## 48 bytes\n\\end{lstlisting}\n\nSo where is all that extra space coming from?  Simply put, \\R objects \nare more than just their data.  They contain a great deal of very useful \nmetadata, which is where all the nice abstraction comes from.  Whenever you \ncreate a vector, \\R keeps track of, for example, its length.  If you \ndo not appreciate this convenience, go learn \\proglang{C} and then get back to \nme.  \n\nFor vectors, this overhead is 40 bytes, regardless of the type of data.   \nMatrices, unsurprisingly cost more, clocking in at 200 bytes overhead.  It is \nworth noting that this overhead does not scale; it is on a per-object basis.  So \nwe don't need 40 bytes for each element of a vector when just 8 would do (in the \ncase of double precision values).  We need 40 plus 8 per element:\n\\begin{lstlisting}[language=rr]\n# 2 elements\n40+8*2\n## [1] 56\nobject.size(rnorm(2))\n## 56 bytes\n\n# 100.000 elements\n40+1e5*8\n## [1] 800040\nobject.size(rnorm(1e5))\n## 800040 bytes\n\\end{lstlisting}\n\nThe story is slightly more complicated for integer data (and a lot more \ncomplicated for strings; see the following section).  On my machine (and \nprobably yours, but not necessarily), \\code{int}s costs 4 bytes.  However, \n\\R does some aggressive allocation:\n\\begin{lstlisting}[language=rr]\nobject.size(1L:3L)\n## 56 bytes\nobject.size(1L:4L)\n## 56 bytes\n\\end{lstlisting}\nHere we see \\R allocating more bytes than it needs for integer vectors \nsometimes, choosing to allocate in 16 byte chunks rather than 8 byte chunks.\n\nThe \\pkg{memuse} package does not adjust for this overhead, because it \nhonestly just doesn't matter.  This overhead is really paltry, and when you \nthink about all the abstraction it buys you, it's a hell of a bargain.  If you \nhave a million R objects stored, you're wasting less than one MiB ($1024^2$ \nbytes); so you would need a billion objects to use just about a GiB ($1024^3$ \nbytes) on overhead.  And if you're doing that kind of silly shit, my advice \nwould be to learn how to properly use data structures.\n\nAll that said, the main \\code{memuse()} (\\code{mu()} for short) function\nwill offer a better version of \\code{object.size()}.  In previous \nversion, the package overwrote the default functionality, but as of\npackage version 3.0.0, that is no longer the case. \n\nThe \\code{object.size()} function returns an object of class \n\\code{object_size}, which is a not-so-useful S3 class provided by core \n\\R.  If you instead use \\code{memuse()}, then you will get a much more useful\n\\code{memuse} object.  So revisiting the code above:\n\\begin{lstlisting}[language=rr]\nmemuse(rnorm(1e5))\n## 781.289 KiB\n\\end{lstlisting}\n\n\n\n\\subsection{Strings}\n\nString objects have been avoided up until this point because they are much more \ndifficult to describe in general, unless they have a great deal of regularity \nimposed on them.  In \\R, strings by default are allocated to use 56 \nbytes (not counting overhead), unless they need more.  I'm not sure why this \nvalue was chosen, but 56 byte strings will allow for the storage of 7 chars \n(like \\code{a} but not \\code{aa}).  Each char costs 1 byte, so there's some fat \noverhead for the strings here, and almost certainly an additional byte held out \nfor the null terminator.  So for example, recall that a vector allocates 40 \nbytes of overhead, so the vector string \\code{letters} should use $56\\times 26 + \n40$ bytes.  We can easily verify that this is the case:\n\\begin{lstlisting}[language=rr]\n56*26+40\n## [1] 1496\nmemuse(letters)\n## 1.461 KiB\n\\end{lstlisting}\n\nIf you have a string with more than 7 chars, \\R will allocate extra \nspace in 8-16 byte blocks.  After the initial 8 byte allocation (7 chars $+$ \nnull terminator), if you need more you get an additional 8 bytes (in reality \nthis is probably a contiguous 16 byte allocation; I have not bothered to check). \n Beyond that, storage is allocate in 16 byte blocks for each string.  For \nexample:\n\\begin{lstlisting}[language=rr]\nmemuse(c(paste(rep(\"a\", 7), collapse=\"\"), \"a\")) \n## 152 B\n\n  memuse(c(paste(rep(\"a\", 7+1), collapse=\"\"), \"a\")) \n## 160 B\n\n  memuse(c(paste(rep(\"a\", 7+8+1), collapse=\"\"), \"a\")) \n## 176 B\n\n  memuse(c(paste(rep(\"a\", 7+8+16+1), collapse=\"\"), \"a\")) \n## 192 B\n\\end{lstlisting}\n\nIf you have a vector of strings with them of varying lengths, the allocation of \nindividual elements is handled on a case-by-case basis.  Consider the \nfollowing:\n\\begin{lstlisting}[language=rr]\n  memuse(c(paste(rep(\"a\", 7+8+16+1), collapse=\"\"), \"a\")) \n## 192 B\n\\end{lstlisting}\n\nThis object (the vector of 2 elements with first element \n``aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'' and second element ``a'') is using 40 \nbytes for the vector, $56+8+16+16$ bytes for the first element, and 56 bytes for \nthe second.\n\nFor all of these reasons, and given the fact that I almost never (ever) deal \nwith character data, I have not bothered to make any attempt to extend, for \nexample, \\code{howmany()} or \\code{howbig()}, to incorporate strings.  Deal \nwith it, nerd.\n", "meta": {"hexsha": "0b39c42b613459e26649dfe35c43bf532e174f7a", "size": 5555, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "vignettes/include/05-other.tex", "max_stars_repo_name": "cran/memuse", "max_stars_repo_head_hexsha": "22d4e53c0b1a7f9731256d0cd2c791cf8a9d1165", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 34, "max_stars_repo_stars_event_min_datetime": "2015-05-15T17:15:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T14:03:29.000Z", "max_issues_repo_path": "vignettes/include/05-other.tex", "max_issues_repo_name": "cran/memuse", "max_issues_repo_head_hexsha": "22d4e53c0b1a7f9731256d0cd2c791cf8a9d1165", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2016-09-16T08:01:25.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:08:37.000Z", "max_forks_repo_path": "vignettes/include/05-other.tex", "max_forks_repo_name": "cran/memuse", "max_forks_repo_head_hexsha": "22d4e53c0b1a7f9731256d0cd2c791cf8a9d1165", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-19T09:09:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-19T09:09:30.000Z", "avg_line_length": 40.5474452555, "max_line_length": 81, "alphanum_fraction": 0.7364536454, "num_tokens": 1549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.34853896456110484}}
{"text": "\\documentclass[11pt,a4paper,oneside]{report}             % Single-side\n\n\\usepackage{t1enc}\n\\usepackage[utf8]{inputenc}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{enumerate}\n\\usepackage{graphics}\n\\usepackage{listings}\n\\usepackage{color}\n\\usepackage{fancyvrb}\n\\usepackage{anysize}\n\\usepackage{setspace}\n\\usepackage[center]{caption}\n\n\\usepackage{titlesec}\n\t\\titleformat{\\chapter}[hang] \n\t{\\normalfont\\huge\\bfseries}{\\chaptertitlename\\ \\thechapter:}{1em}{} \n\n\\usepackage[hidelinks]{hyperref}\n\\usepackage{textcomp}\n\\usepackage{graphicx}\n\\usepackage{svg}\n\n\\onehalfspacing\n\n\\def\\doubleunderline#1{\\underline{\\underline{#1}}}\n\\def\\dul#1{\\doubleunderline{#1}}\n\\def\\ul#1{\\underline{#1}}\n\\newcommand{\\vect}[2]{\\begin{bmatrix} #1 \\\\ #2 \\end{bmatrix}}\n\\setcounter{MaxMatrixCols}{20}\n\n\\begin{document}\n\n% Title page ==================================================================================\n\\begin{titlepage}\n\\begin{center}\n{\\huge Fast decoding of systematic Golay-24 code } \\\\\n\\vspace{0.5cm}\n{\\small Description of the algorithm used on board the SMOG-P, ATL-1 and SMOG-1 satellites } \\\\\n{\\large Timur Kristóf } \\\\\n\n\\vfill\n{\\large \\today}\n\\end{center}\n\\end{titlepage}\n\n\\chapter{Introduction}\n\nThe Golay forward error correction code was invented by Marcel Golay in 1949. Its most well-known\nuse was onboard the NASA Voyager satellites where they used the Golay(24, 12, 8) code. These days\nwe know codes with much better error correction capabilities, but the Golay code is still a good\nchoice in applications where the size of each packet is small and/or the available hardware\nresources are too modest, so there is no chance to use more complicated coding schemes.\n\nThe topic of this study is the \\emph{systematic Golay(24, 12, 8)} code, called \\emph{Golay-24} for short.\nThe aim is to present a new algorithm which can quickly and efficiently\ndecode this coding scheme even on machines with limited compute capabilities,\nsuch as embedded systems.\n\nThis study not only presents the algorithm but also proves its correctness.\n\nThe algorithm presented here is a \\emph{hard-decision} algorithm, since most of the embedded hardware\nthat I've worked with make a hard decision about the received bits, so the aim was to make decoding\nefficient on this class of hardware.\nFurther research needs to be done to determine if the ideas presented here can be utilized in soft-decision algorithms.\n\n\\section{Definitions}\n\n\\doubleunderline{A} is the Golay matrix.\n\n\\[\n    \\doubleunderline{A} = \n    \\begin{bmatrix}\n            1 & 0 & 0 & 1 & 1 & 1 & 1 & 1 & 0 & 0 & 0 & 1 \\\\\n            0 & 1 & 0 & 0 & 1 & 1 & 1 & 1 & 1 & 0 & 1 & 0 \\\\\n            0 & 0 & 1 & 0 & 0 & 1 & 1 & 1 & 1 & 1 & 0 & 1 \\\\\n            1 & 0 & 0 & 1 & 0 & 0 & 1 & 1 & 1 & 1 & 1 & 0 \\\\\n            1 & 1 & 0 & 0 & 1 & 0 & 0 & 1 & 1 & 1 & 0 & 1 \\\\\n            1 & 1 & 1 & 0 & 0 & 1 & 0 & 0 & 1 & 1 & 1 & 0 \\\\\n            1 & 1 & 1 & 1 & 0 & 0 & 1 & 0 & 0 & 1 & 0 & 1 \\\\\n            1 & 1 & 1 & 1 & 1 & 0 & 0 & 1 & 0 & 0 & 1 & 0 \\\\\n            0 & 1 & 1 & 1 & 1 & 1 & 0 & 0 & 1 & 0 & 0 & 1 \\\\\n            0 & 0 & 1 & 1 & 1 & 1 & 1 & 0 & 0 & 1 & 1 & 0 \\\\\n            0 & 1 & 0 & 1 & 0 & 1 & 0 & 1 & 0 & 1 & 1 & 1 \\\\\n            1 & 0 & 1 & 0 & 1 & 0 & 1 & 0 & 1 & 0 & 1 & 1\n    \\end{bmatrix}\n\\]\n\n\\doubleunderline{G} is the generator matrix of the systematic Golay(24, 12, 8) code.\n\n\\[\n    \\doubleunderline{G} =\n    \\begin{bmatrix}\n        \\doubleunderline{I} \\\\\n        \\doubleunderline{A}\n    \\end{bmatrix}\n\\]\n\nIf \\underline{m} is the message (which we want to encode), and the parity vector is \\underline{p},\nthen the encoded code word is \\underline{x}.\nThe Hamming weight of the code word is $w\\{\\ul{x}\\} = w\\{\\ul{m}\\} + w\\{\\ul{p}\\}$.\n\n\\[\n    \\underline{x} = \\begin{bmatrix}\n        \\underline{m} \\\\\n        \\underline{p}\n    \\end{bmatrix} = \\doubleunderline{G} \\cdot \\underline{m} = \\begin{bmatrix}\n        \\doubleunderline{I} \\\\\n        \\doubleunderline{A}\n    \\end{bmatrix} \\cdot \\underline{m} = \\begin{bmatrix}\n        \\doubleunderline{I} \\cdot \\underline{m} \\\\\n        \\doubleunderline{A} \\cdot \\underline{m}\n    \\end{bmatrix} = \\begin{bmatrix}\n        \\underline{m} \\\\\n        \\doubleunderline{A} \\cdot \\underline{m}\n    \\end{bmatrix}\n\\]\n\nIf the \\underline{x} code word is transmitted through a noisy channel, the received word might\ncontain errors. The error vector is \\underline{e} (the error vector in the received message \nis $\\underline{e}_m$ and the error vector in the received parity is $\\underline{e}_p$)\nand the received word is \\underline{r}.\n\n\\[\n    \\ul{r} = \\ul{x} + \\ul{e} = \\vect{\\ul{r}_m}{\\ul{r}_p} = \\vect{\\ul{m} + \\ul{e}_m}{\\ul{p} + \\ul{e}_p}\n\\]\n\nThe Golay-24 code is capable of correcting 3 or fewer\nbit errors, and detecting 4 bit errors. So the cases we care about the most are when $w\\{\\ul{e}\\} \\leq 3$\nor $w\\{\\ul{e}\\} = 4$.\n\n\\chapter{Algorithm}\n\nThis chapter presents the decoding algorithm. We will make the assumption that $w\\{\\ul{e}\\} \\leq 4$,\nso the received vector contains at most 4 bit errors. This is reasonable because the Golay(24, 12, 8)\ncode is only capable to correct at most 3 bit errors, and detect 4 bit errors. Since the minimal\nHamming distance between each code word is 8, in case of 4 bit errors it is possible to create the\nreceived vector from multiple different code words, therefore it is not possible to tell which was\nthe original.\n\n\\section{Basics}\n\nFirst a few basic considerations are presented on which the algorithm is based.\n\n\\subsubsection{Inverse and transpose of the Golay matrix}\n\nThe \\dul{A} Golay matrix is its own inverse and transpose.\n\n\\[\n    \\dul{A}^T = \\dul{A}\n\\]\n\\[\n    \\dul{A}^{-1} = \\dul{A}\n\\]\n\nConsequences:\n\\begin{itemize}\n    \\item \\dul{A} is an invertable linear transformation, so if $\\ul{p} = \\dul{A} \\cdot \\ul{m}$, then\n          $\\dul{A} \\cdot \\ul{p} = \\dul{A} \\cdot \\dul{A} \\cdot \\ul{m} = \\dul{A} \\cdot \\dul{A}^{-1} \\cdot \\ul{m} = \\ul{m}$.\n          In other words, the message can be restored from the parity vector.\n    \\item We only need to store the \\dul{A} matrix in memory, and we don't need to ever invert or transpose it.\n\\end{itemize}\n\n\\subsubsection{Parity of messages with 1 Hamming weight}\n\nIf $\\ul{m} = \\ul{I}_{i}$, then $\\ul{p} = \\dul{A} \\cdot \\ul{m} = \\dul{A} \\cdot \\ul{I}_{i} = \\ul{A}_{i}$.\nSo if the message is the same as the $i$th row of the identity matrix $\\dul{I}$, then the parity vector is the\nsame as the $i$-th row of the Golay matrix $\\dul{A}$.\n\nConsequences:\n\\begin{itemize}\n    \\item When changing a single bit at $\\ul{I}_{i}$ in the message, the equivalent change to the parity is $\\ul{A}_{i}$.\n    \\item When changing a single bit at $\\ul{I}_{i}$ in the parity, the equivalent change to the message is $\\ul{A}_{i}$.\n\\end{itemize}\n\n\\subsubsection{Hamming weight of code words from non-zero Hamming weight messages}\n\nIf $\\ul{m} \\neq \\ul{0}$, then $w\\{ \\ul{x} \\} = w\\{ \\ul{m} \\} + w\\{ \\ul{p} \\} \\geq 8$.\n\nProof:\nWe already know that the Hamming distance between every possible code word is at least 8.\n(Not proven here, but it's a well-known fact about the Golay code.)\nThe $\\ul{m} = \\ul{0}$ message is encoded to the code word $\\ul{x} = \\ul{0}$, so\nthe minimal Hamming distance of every possible code word can only be at least 8 if\nin case of $\\ul{m} \\neq \\ul{0}$ the $w\\{ \\ul{x} \\} \\geq 8$, otherwise there\nwould be a code word $\\ul{x}$ whose Hamming distance from the $\\ul{0}$ code word is less than 8.\n\nConsequence:\n\\begin{itemize}\n    \\item $\\forall \\ul{m} \\neq \\ul{0} : w\\{ \\dul{A} \\cdot \\ul{m} \\} \\geq 8$\n\\end{itemize}\n\n\\subsubsection{Lemma 1.}\n\nIf $w\\{\\ul{e}\\} \\leq 4$ and $w\\{\\dul{A} \\cdot \\ul {r_m} + \\ul{r}_p\\} \\leq 3$,\nthen $w\\{\\ul{e}_m\\} = 0$ (which is equivalent to $\\ul{e}_m = \\ul{0}$).\nSo, assuming 4 or fewer bit errors, if we calculate the parity from the received message, and\nthe Hamming distance between the calculated parity and the received parity is less than\nor equal to 3, then the received message is error-free.\n\nProof:\n\nLet's suppose that the statement is false, and $\\ul{e}_m \\neq \\ul{0}$.\nThe given expression looks like:\n\n\\[\n    \\dul{A} \\cdot \\ul{r}_m + \\ul{r}_p =\n    \\dul{A} \\cdot ( \\ul{m} + \\ul{e}_m ) + ( \\ul{p} + \\ul{e}_p ) =\n    \\dul{A} \\cdot \\ul{m} + \\dul{A} \\cdot \\ul{e}_m + \\dul{A} \\cdot \\ul{m} + \\ul{e}_p =\n    \\dul{A} \\cdot \\ul{e}_m + \\ul{e}_p\n\\]\n\nConsider the code word generated from $\\ul{e}_m$. The minimum Hamming distance between every possible code word is 8, therefore\nin case of $\\forall \\ul{e}_m \\neq \\ul{0}$ the following is true:\n$w\\{ \\ul{e}_m \\} +  w\\{ \\dul{A} \\cdot \\ul{e}_m \\} \\geq 8$.\n(See \"Hamming weight of code words from non-zero Hamming weight messages\" above.)\n\nLet's define $w\\{ \\ul{e}_m \\} = N$, then because $w\\{ \\ul{e} \\} \\leq 4$ the following\nwill also be true: $w\\{ \\ul{e}_p \\} \\leq 4 - N$.\nSo, $w\\{ \\dul{A} \\cdot \\ul{e}_m \\} \\geq 8 - N$.\n\nSo according the above, we get this:\n\\[\n    w\\{ \\dul{A} \\cdot \\ul{e}_m + \\ul{e}_p \\} \\geq (8 - N) - (4 - N) = 4\n\\]\n\nWhat we got is that when $\\ul{e}_m \\neq \\ul{0}$, then\n$w\\{ \\dul{A} \\cdot \\ul{e}_m + \\ul{e}_p \\} \\geq 4$ which is a contradiction, because\nwe started with the condition that it's $\\leq 3$.\n\nSo we can conclude that the statement is true, and $\\ul{e}_m = \\ul{0}$.\n\n\\subsubsection{Lemma 2.}\n\nIf $2 \\leq w\\{\\ul{e}\\} \\leq 4$ and $w\\{\\dul{A} \\cdot \\ul{r}_m + \\ul{A}_i + \\ul{r}_p\\} \\leq 2$,\nthen $\\ul{e}_m = \\ul{I}_i$. So if we assume the number of errors to be at least 2 but at most 4,\nand we correct a 1-bit error $\\ul{e}_{m, i} = \\ul{I}_i$ in the received message, then we calculate\nthe parity of the corrected message, and the Hamming distance between the calculated parity and\nthe received parity is less than or equal to 2, then the received message contains exactly 1 error,\nand that error is the $i$th row of the identity matrix, which is what was corrected.\n\nProof.\n\nConsider the $\\ul{r}_2 = \\vect{\\ul{r}_{m,2}}{\\ul{r}_{p,2}} = \\vect{\\ul{r}_m + \\ul{I}_i}{\\ul{r}_p}$ received word.\n\nBecause of Lemma 1, we know that\nif $w\\{ \\dul{A} \\cdot \\ul{r}_{m,2} + \\ul{r}_{p,2} \\} \\leq 3$, then $\\ul{e}_{m,2} = \\ul{0}$.\n\nThe above formula of $\\ul{r}_2$ yields the following result:\n\n\\[\n    \\dul{A} \\cdot \\ul{r}_{m,2} + \\ul{r}_{p,2} =\n    \\dul{A} \\cdot ( \\ul{r}_m + \\ul{I}_i ) + \\ul{r}_p =\n    \\dul{A} \\cdot \\ul{r}_m + \\dul{A} \\cdot \\ul{I}_i + \\ul{r}_p =\n    \\dul{A} \\cdot \\ul{r}_m + \\ul{A}_i + \\ul{r}_p\n\\]\n\nThe above conditions contain $w \\{ \\dul{A} \\cdot \\ul{r}_m + \\ul{A}_i + \\ul{r}_p \\} \\leq 2$,\nso for the received word $\\ul{r}_2$ the following is true: $\\ul{e}_{m,2} = \\ul{0}$.\n\nSince $\\ul{r}$ only differs from $\\ul{r}_2$ by only 1 message bit, the error of the parity is\n$\\ul{e}_p = \\ul{e}_{p,2}$. The differing message bit is at $\\ul{I}_i$.\nSo if $\\ul{e}_{m,2} = \\ul{0}$, then $\\ul{e}_m = \\ul{I}_i$.\n\n\\subsubsection{Lemma 3.}\n\nSame as Lemma 1, but the other way around:\n\nIf $w\\{\\ul{e}\\} \\leq 4$ and $w\\{\\dul{A} \\cdot \\ul {r_p} + \\ul{r}_m\\} \\leq 3$,\nthen $w\\{\\ul{e}_p\\} = 0$  (which is equivalent to $\\ul{e}_p = \\ul{0}$).\nSo, if we calculate the message from the received parity, and\nthe Hamming distance between the calculated message and the received message is less than\nor equal to 3, then the received parity is error-free. (And the received message is\n$\\dul{A} \\cdot \\ul {r_p}$.)\n\nThis can be proved in the exact same way as Lemma 1.\n\n\\subsubsection{Lemma 4.}\n\nSame as Lemma 2, but the other way around:\n\nIf $2 \\leq w\\{\\ul{e}\\} \\leq 4$ and $w\\{\\dul{A} \\cdot \\ul{r}_p + \\ul{A}_i + \\ul{r}_m\\} \\leq 2$,\nthen $\\ul{e}_p = \\ul{I}_i$. So if we assume the number of errors to be at least 2 but at most 4,\nand we correct a 1-bit error $\\ul{e}_{p, i} = \\ul{I}_i$ in the received parity, then we calculate\nthe message of the corrected parity, and the Hamming distance between the calculated message and\nthe received message is less than or equal to 2, then the received parity contains exactly 1 error,\nand that error is the $i$th row of the identity matrix, which is what we corrected.\n\nThis can be proved in the exact same way as Lemma 2.\n\n\\section{Steps of the algorithm}\n\n\\subsubsection{Step 1.}\n\nConsider the $\\ul{r}$ received vector.\nSplit $\\ul{r}$ into received message and received parity:\n\n\\[\n    \\ul{r} = \\vect{\\ul{r}_m}{\\ul{r}_p}\n\\]\n\n\\subsubsection{Step 2.}\n\nCalculate the parity of the received message part: $\\ul{p}_2 = \\dul{A} \\cdot \\ul{r}_m$.\n\n\\subsubsection{Step 3.}\n\nIf $\\ul{p}_2 = \\dul{A} \\cdot \\ul{r}_m = \\ul{p}$ then the received word contains no error, so we're done.\n\n\\subsubsection{Step 4.}\n\nWhen the received message is error-free but the parity contains $w\\{\\ul{e}_p\\} \\leq 3$ errors, then according to\n\\emph{Lemma 1} we can tell this by looking at the Hamming distance between the received parity $\\ul{r}_p$ and\nthe calculated parity $\\ul{p}_2$ which is $d = w\\{\\ul{r}_p + \\ul{p}_2\\}$.\n\nIf $d \\leq 3$ then the received message is error-free, and only the received parity contained at most 3 errors.\n\n\\subsubsection{Step 5.}\n\nCalculate the message from the received parity, which will be $\\ul{m_2} = \\dul{A} \\cdot \\ul{r}_p$.\n\n\\subsubsection{Step 6.}\n\nWhen the received parity is error-free but the received message has $w\\{\\ul{e}_m\\} \\leq 3$ errors, then according to\n\\emph{Lemma 2} we can tell this by looking at the Hamming distance between the received message $\\ul{r}_m$\nand the calculated message $\\ul{m_2}$ which is $d = w\\{\\ul{r}_m + \\ul{m_2}\\}$.\n\nIf $d \\leq 3$ then the received parity is error-free, and only the received message contained at most 3 errors.\nSo the decoded message is $\\ul{m_2}$.\n\n\\subsubsection{Step 7.}\n\nSo far, the algorithm has covered every possible 1-bit error and all the 2 and 3-bit errors which were\nlimited to only the message or the parity. Let's now deal with the case where the received message contains 1 error,\nand the received parity contains 1 or 2 errors.\n\nFor $\\forall i : 1 \\leq i \\leq 12, \\ul{e}_m = \\ul{I}_i$ cases, let's look at the possible 1-bit errors of the\nreceived message, and correct them in the following manner:\n\n\\[\n    \\ul{r}_{corr, i} = \\vect{\\ul{r}_{m, corr, i}}{\\ul{r}_{p, corr, i}} = \\vect{\\ul{r}_m + \\ul{I}_i}{\\ul{r}_p + \\ul{A}_i}\n\\]\n\nLet's also calculate the parity of the corrected message:\n\n\\[\n    \\ul{p}_{i} = \\dul{A} \\cdot \\ul{r}_{m, corr, i}\n\\]\n\nThere are 12 possible corrections, the right one is the case when:\n\n\\[\n    w\\{\\ul{p}_{i} + \\ul{r}_{p, corr, i}\\} \\leq 2\n\\]\n\nThanks to \\emph{Lemma 2}, whichever $\\ul{r}_{corr, i}$ satisfies the above formula, the correspoding $\\ul{r}_{m, corr, i}$ will be\nthe decoded message.\n\n\\subsubsection{Step 8.}\n\nLet's deal with the cases when the received parity has 1 error, and the received message has 1 or 2 errors.\n\nFor $\\forall i : 1 \\leq i \\leq 12, \\ul{e}_p = \\ul{I}_i$ cases, let's look at the possible 1-bit errors of the\nreceived parity, and correct them in the following manner:\n\n\\[\n    \\ul{r}_{corr, i} = \\vect{\\ul{r}_{m, corr, i}}{\\ul{r}_{p, corr, i}} = \\vect{\\ul{r}_m + \\ul{A}_i}{\\ul{r}_p + \\ul{I}_i}\n\\]\n\nLet's calculate the message from the corrected parity:\n\n\\[\n    \\ul{m}_{i} = \\dul{A} \\cdot \\ul{r}_{p, corr, i}\n\\]\n\nThere are 12 possible corrections, the right one is the case when:\n\n\\[\n    w\\{\\ul{m}_{i} + \\ul{r}_{m, corr, i}\\} \\leq 2\n\\]\n\nThanks to \\emph{Lemma 4}, whichever $\\ul{r}_{corr, i}$ satisfies the above formula, the corresponding $\\ul{m}_{i}$  will be\nthe decoded message.\n\n\\subsubsection{Step 9.}\n\nIf the algorithm reached this point, it means that we've already covered all possible 1, 2 and 3 bit errors.\nSo we've detected a 4-bit error which we can't correct.\n\n\\end{document}\n\n\n", "meta": {"hexsha": "5410616b9118617258ff78c1c04c3766b57f8a6a", "size": 15437, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "proof/golay-fast-proof.tex", "max_stars_repo_name": "Venemo/golay-fast", "max_stars_repo_head_hexsha": "bb9e8145edcb8265acab6cda1d91dee599d36dd2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-13T12:53:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-13T12:53:38.000Z", "max_issues_repo_path": "proof/golay-fast-proof.tex", "max_issues_repo_name": "Venemo/golay-fast", "max_issues_repo_head_hexsha": "bb9e8145edcb8265acab6cda1d91dee599d36dd2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "proof/golay-fast-proof.tex", "max_forks_repo_name": "Venemo/golay-fast", "max_forks_repo_head_hexsha": "bb9e8145edcb8265acab6cda1d91dee599d36dd2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.1802030457, "max_line_length": 130, "alphanum_fraction": 0.6488955108, "num_tokens": 5440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.34853896093963344}}
{"text": "\\subsection{Solvent Accessible Surface}\\index{SAS|ff}\r\n\\index{Solvent Accessible Surface|ff}\r\nThe solvent accessible surface is a continuous surface of the molecule which\r\ncan be reached by the center of charge of a solvent molecule.  The calculation \r\nof the SAS is carried out as follows:\r\n\r\n\\begin{itemize} \r\n\\item Each atom is assigned a van der Waals' radius.  VdW radii used in COSMO\r\nare given in Table~\\ref{vdw}.\r\n\\begin{table}\r\n\\caption{\\label{vdw} Van der Waals radii (\\AA ) used in COSMO}\r\n\\begin{center}\r\n\\begin{tabular}{llllllllllllll}\r\n\\hline\r\n I  & R    & II & R    &III& R    &IV & R    & V & R    &VI & R    &VII& R \\\\\r\n\\hline\r\n H  & 1.08 & \\\\\r\n Li & 1.80 &    &      &   &      & C & 1.53 & N & 1.48 & O & 1.36 & F & 1.30\\\\\r\n Na & 2.30 &    &      & Al& 2.05 & Si& 2.10 & P & 1.75 & S & 1.70 & Cl& 1.65\\\\\r\n K  & 2.80 & Ca & 2.75 &   &      &   &      &   &      &   &      &Br & 1.80\\\\\r\n    &      &    &      &   &      &   &      &   &      &   &      &I  &  2.05\\\\\r\n\\hline\r\n\\end{tabular}\r\n\\end{center}\r\n\\end{table}\r\n\r\n\\item To each radius is added a distance equal to the radius of the solvent. By\r\ndefault, this is 1.0\\AA, but may be changed by the user using \r\n\\comp{RSOLV=$n.nn$}. This gives the distance from the nucleus to the center of\r\na solvent molecule.\r\n\\item A set of points is generated on this surface. These points produce a\r\nbasic grid.\r\n\\item All points which are inside the surface of any other atom are excluded.\r\n\\item The remaining points are moved towards the center of the atom.  The\r\ndistance moved is equal to the distance of the center of charge of the solvent\r\nmolecule from the center of the solvent molecule.  By default, this distance is\r\nset to \\comp{RSOLV}, but may be set explicitly by keyword \\comp{RSOLV=$n.nn$}.\r\n\\item Each of the remaining points represents a small area of the solvent\r\naccessible surface.  The total SAS is calculated from the number of points.\r\n\\end{itemize}\r\n\r\nFrom this definition of the SAS we see that the SAS of each atom is a  surface\r\nof radius equal to the van der Waals' radius plus the radius of the solvent\r\nmolecule minus the distance of the center of charge of the solvent molecule to\r\nthe center of the solvent molecule.  In other words, the radius is the VdW\r\nradius plus the distance from the surface of the solvent molecule to the center\r\nof charge of the solvent molecule.  By default, this extra distance is zero.\r\nOnly that part of the atom surface which can be touched by the solvent molecule\r\nis used.  This means that only those atoms on the surface of the molecule can\r\ncontribute to the SAS.  Of those atoms  that are on the surface of the molecule\r\nthere will be parts of the surface which cannot be reached by the solvent\r\nbecause the solvent molecule is too bulky.\r\n", "meta": {"hexsha": "846247794801869f3c6a25970f35b7484384de26", "size": 2770, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "manuals/MOPAC2000_manual/sas.tex", "max_stars_repo_name": "openmopac/MOPAC-archive", "max_stars_repo_head_hexsha": "01510e44246de34a991529297a10bcf831336038", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-16T20:53:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T20:54:11.000Z", "max_issues_repo_path": "manuals/MOPAC2000_manual/sas.tex", "max_issues_repo_name": "openmopac/MOPAC-archive", "max_issues_repo_head_hexsha": "01510e44246de34a991529297a10bcf831336038", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "manuals/MOPAC2000_manual/sas.tex", "max_forks_repo_name": "openmopac/MOPAC-archive", "max_forks_repo_head_hexsha": "01510e44246de34a991529297a10bcf831336038", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.2641509434, "max_line_length": 81, "alphanum_fraction": 0.6815884477, "num_tokens": 794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.34844248313045645}}
{"text": "\\chapter{Generation of Band Structures}\r\n\\section{Program BZ}\r\n\\subsection{Description} \\index{BZ!description of}\r\nUnlike molecules, whose eigenvalue spectrum consists of infinitely sharp lines\r\n(Kronecker-$\\delta$ type), the eigenvalues of solids form bands.  These bands\r\nare conventionally represented by Brillouin Zones (BZ).  For a polymer, the BZ\r\nconsists of a line, for a layer structure, a surface, and for a solid, a\r\nthree-dimensional shape.  The dimensions of the BZ are inverse distance: if two\r\npolymers have unit cells of 10 and 8 \\AA, then the ratio of their unit cell\r\ntranslation vectors is 1.25:1, and the ratio of their BZ's is 1:1.25.\r\n\r\nAlthough MOPAC can generate all the information necessary  to generate\r\nband-structures, for ease of use this job is given to a special program called\r\nBZ. \\  MOPAC is designed to run in batch mode, but drawing band-structures is\r\nan interactive operation.\r\n\r\nBefore BZ can be run, a MOPAC calculation must first be run in order to\r\ngenerate the data needed by BZ. \\  Most of this data is invisible to the user,\r\nbut the user must supply to MOPAC one or two data which BZ will use.  These\r\ndata are:\r\n\r\n\\begin{description}\r\n\\item[\\comp{MERS=($n_1$,$n_2$,$n_3$)}]~\\\\\r\n(See Chapter~\\ref{makpol:mers}  and Section~\\ref{mopac:mers})  BZ needs to know how\r\nthe Fock matrix is organized, and  \\comp{MERS} gives the number of unit cells\r\nin each direction.  MOPAC uses the keyword \\comp{MERS} as the prompt to write\r\nout a file for use by BZ.  Within MOPAC, \\comp{MERS} has no other use.\r\n\\index{MERS}\r\n\\item[\\comp{BCC} \\normalfont{(optional)}]~\\\\\r\nLike \\comp{MERS}, \\comp{BCC} is not used by MOPAC. \\comp{BCC} (see\r\nChapter~\\ref{makpol:bcc})  indicates that the system is Body-Centered-Cubic; in\r\nother words, that every odd unit cell is missing.  If the keyword \\comp{BCC} is\r\npresent, MOPAC informs BZ that the system is Body-Centered-Cubic.\r\n\\end{description}\r\n\r\n\r\nBZ is an interactive utility program.  It can perform three types of\r\ncalculation:\r\n\\begin{itemize}\r\n\\item  Points in $k$-space are to be studied.\r\n\\item  Lines in $k$-space are to be drawn.\r\n\\item  Surfaces in $k$-space are to be drawn.\r\n\\end{itemize}\r\n\r\n\\subsection{Data input for BZ}\\index{Data! for BZ}\r\nOnce the MOPAC calculation has been completed, the band structure can be\r\ngenerated. The instruction to generate band structures is:\r\n\r\n\\comp{bz $<$filename$>$}\r\n\r\nwhere \\comp{$<$filename$>$} is the name of the file. This must be the same as\r\nthat used for the MOPAC calculation.\r\n\r\nWhen BZ starts, it invites the user to specify the type\r\nof calculation to be performed. The allowed types are:\r\n\\begin{description}\r\n\\item[0] Points in $k$-space are to be studied.\r\n\\item[1] Lines in $k$-space are to be drawn.\r\n\\item[2] Surfaces in $k$-space are to be drawn.\r\n\\end{description}\r\n\r\nInstead of supplying data at the prompt, a data set can be supplied, using the\r\n command:\r\n\r\n\\comp{bz $<$filename$>$ $<$filename2$>$}\r\n\r\nA second file, called \\comp{$<$filename2$>$.bz}, must exist.  This file will\r\ncontain the data that would otherwise be supplied by the prompt.\r\n\r\n\\index{Help! with BZ}\r\nIn addition, the user is invited to enter the number `3' to request help. Help\r\ndescribes diagnostic key-words which allow an interested user to follow the\r\ncalculation.\r\n\r\nSome of the operations in BZ are very sensitive to perturbations in the Fock\r\nmatrix, specifically any perturbations which lower the symmetry.  The first\r\nthing BZ does, therefore, is to restore symmetry.  To do this, BZ reads in a\r\nlist of symmetry operations and symmetrizes the Fock matrix.\r\n\r\nAt the present time, the user must supply all operations of the group.\r\nEventually this will be done automatically by the program, but for now the job\r\nof defining symmetry is given to the user.\r\n\r\n\\subsubsection{Structure of $<$filename$>$.ops}\r\n\\index{Space group!operations}\r\nThis file holds the definitions of the symmetry operations for the space-group.\r\nThe format is `free format' - one or more spaces are treated as one space. The\r\nfirst line should contain one of the following two words: ``Cartesian'' or\r\n``Crystallographic''.  If ``Cartesian'' is selected, then the rotation axis is\r\nrelative to the Cartesian coordinates of the atoms; if ``Crystallographic'' is\r\nselected, then the rotation axis is relative to the crystal coordinates of the\r\natoms.  (In practice, ``Cartesian'' is {\\em much} easier to use.)\r\n\r\nEach operation is defined by one line and is composed of 12 data.\r\nIn order, these data are:\r\n\\begin{enumerate}\r\n\\item A `1' or `0'.  `1' if the operation is composed of the inversion operation times\r\na rotation, `0' if the operation is a pure rotation.\r\n\\item The non-primitive translations.  These are given as their reciprocals, thus\r\na (0.5,0.5,0.0) translation would be entered as `2~2~0'. The absence of\r\na non-primitive translation is indicated by a zero. (three numbers)\r\n\\item The rotation expressed as a fraction of a circle.\r\n\\item The axis about which the operation is performed. Units are\r\nCartesian coordinates, or, if ``Crystallographic'' is selected, the crystal\r\ncoordinates. (three numbers)\r\n\\item The center about which the operation is performed. Units are\r\nCartesian coordinates, in Angstroms. (three numbers)\r\n\\item A text string describing the operation.\r\n\\end{enumerate}\r\n\r\nThe operations list is terminated by an operation which has a `2' for the\r\ninversion option.\r\n\r\nExamples of these operations are illustrated in Table~\\ref{sgo}\r\nby the 10 classes of operation for the O$_h$ group in O$_h^7$.\r\n\r\n\r\nThe Fock matrix will be symmetrized if, and only if, every operation of\r\nthe group is represented once.  For O$_h$, this would involve a total of 49\r\nlines, 48 for the operations of O$_h$, and one line to terminate the operations\r\nfile.\r\n\r\n% 24 lines, including this one\r\n\\begin{table}\r\n\\caption{\\label{sgo}\r\n Space-Group Operations of O$_h^7$}\r\n\\index{oh7@{$O_h^7$}|ff}\r\n\\begin{center}\r\n\\begin{tabular}{lllllllrrrll}\\\\ \\hline\r\ni& \\multicolumn{3}{c}{N.P.T}  & Rotation & \\multicolumn{3}{c}{Axis of Rotation} &\r\n \\multicolumn{3}{c}{Center of Operation}& Name\\\\ \\hline\r\n0& 0& 0& 0& 0.0     &  0.0&0.0 &1.0 &  0.0& 0.0& 0.0 &  Identity  \\\\\r\n0& 0& 0& 0& 0.3333  &  1.0&1.0 &1.0 &  0.0& 0.0& 0.0 &  C$_3$  \\\\\r\n0& 0& 0& 0& 0.5     &  1.0&0.0 &0.0 &  0.0& 0.0& 0.0 &  C$_2$=C$_4^2$  \\\\\r\n0& 2& 2& 2& 0.5     &  1.0&0.0 &-1.0 & 0.0& 0.0& 0.0 &  C$_2$  \\\\\r\n0& 2& 2& 2& 0.25    &  0.0&0.0 &1.0 &  0.0& 0.0& 0.0 &  C$_4$  \\\\\r\n1& 2& 2& 2& 0.0     &  0.0&0.0 &1.0 &  0.0& 0.0& 0.0 &  Inversion  \\\\\r\n1& 0& 0& 0& 0.25    &  0.0&0.0 &1.0 &  0.0& 0.0& 0.0 &  S$_4$  \\\\\r\n1& 0& 0& 0& 0.5     &  1.0&1.0 &0.0 &  0.0& 0.0& 0.0 &  $\\sigma_d$  \\\\\r\n1& 2& 2& 2& 0.333333&  1.0&1.0 &1.0 &  0.0& 0.0& 0.0 &  S$_6$  \\\\\r\n1& 2& 2& 2& 0.5     &  0.0&0.0 &1.0 &  0.0& 0.0& 0.0 &  $\\sigma_h$  \\\\\r\n2& 0& 0& 0& 0.0     &  0.0&0.0 &1.0 &  0.0& 0.0& 0.0 &  End  \\\\ \\hline\r\n\\end{tabular}\r\n\r\nN.P.T.: Non-Primitive Translation \\end{center}\r\n\\end{table}\r\n\r\n\\subsection{Calculating Points in $k$-space}\r\n\\index{ksp@{$k$-space}!calculating points in}\r\n\r\nA point in $k$-space is specified by one number for a polymer, two\r\nnumbers for a layer system, and three numbers for a solid.   All symmetry\r\npoints and lines for diamond are shown in Table~\\ref{sod} and Figure~\\ref{oh7}.\r\n% 21 lines, including this one\r\n\\begin{figure}\r\n\\begin{makeimage}\r\n\\end{makeimage}\r\n% \\setlength{\\unitlength}{0.1cm}\r\n\\begin{center}\r\n% \\begin{picture}(100,100)\r\n% \\put(62,47){$\\Gamma$}\r\n% \\put(106,42){X}\r\n% \\put(108,68){W}\r\n% \\put(107.5,58){$\\longleftarrow$Z}\r\n% \\put(96.5,54){S$\\longrightarrow$}\r\n% \\put(84,44){$\\Delta$}\r\n% \\put(100.2,59.5){U}\r\n% \\put(76,71){L}\r\n% \\put(92,71){Q}\r\n% \\put(56,80){K}\r\n% \\put(61,63){$\\Sigma$}\r\n% \\put(69,59){$\\Lambda$}\r\n% %\\put(14,38){\\psfig{figure=oh7.ps}}\r\n% \\put(14,38){\\includegraphics{oh7}}\r\n% \\end{picture}\r\n\\includegraphics{oh7}\r\n\\end{center}\r\n\\caption{\\label{oh7}Brillouin zone for Diamond}\r\n\\end{figure}\r\nA ``random'' point is indicated by the number 0.123.  (Note: 0.377 = 0.500 -\r\n0.123)\r\n\r\nThese high-symmetry points have associated subgroup symmetries, thus $\\Gamma $\r\nhas the symmetry O$_h$, $\\Lambda $ has the symmetry C$_{3v}$, and X has the\r\nsymmetry D$_{4h}$.\r\n\r\n\\subsubsection{Little Groups}\\index{Little groups|(}\r\nThe symmetry operations supplied in \\comp{ $<$filename$>$.ops} are used to\r\ngenerate a little group of the space group.  A ``little group'' is the\r\nsub-group of the space-group at a specific point in $k$-space.  There are too\r\nmany little groups to allow all the irreducible representations to be labeled.\r\nIn addition, there is no generally-accepted convention for describing them.\r\nBecause of this, the little group is given as a group-table.  Thus the little\r\ngroup for $\\Gamma$ would have the form shown in Table~\\ref{lgd}.\r\n\r\n% 22 lines, including this line\r\n\\begin{table}\r\n\\begin{center}\r\n\\caption{\\label{sod} Symmetry Points in $k$-space for Diamond}\r\n\\begin{tabular}{lllcc} \\\\ \\hline\r\n\\multicolumn{3}{c}{Point} & Little Group* & Symbol\\\\ \\hline\r\n  0.000& 0.000& 0.000  & O$_h$ &  $\\Gamma$\\\\\r\n  0.500& 0.000& 0.000  & (D$_{4h}$)&X\\\\\r\n  0.500& 0.250& 0.000  & (C$_{2v}$)&W\\\\\r\n  0.500& 0.125& 0.125  & (C$_{2v}$)&U\\\\\r\n  0.375& 0.375& 0.000  & (C$_{2v}$)&K\\\\\r\n  0.250& 0.250& 0.250  & D$_{3d}$ &L\\\\\r\n  0.123& 0.000& 0.000  & C$_{4v}$ &$\\Delta $\\\\\r\n  0.500& 0.123& 0.000  & (C$_{2v}$) &Z\\\\\r\n  0.500& 0.045& 0.045  & (C$_{2v}$)&S\\\\\r\n  0.123& 0.123& 0.000  & C$_{2v}$ &$\\Sigma $\\\\\r\n  0.123& 0.250& 0.377  &  C$_{2}$ &Q\\\\\r\n  0.123& 0.123& 0.123  & C$_{3v}$ &$\\Lambda $\\\\ \\hline\r\n\\end{tabular}\r\n\r\n* Point groups in parentheses only approximate little groups.\\end{center}\\end{table}\r\n\\begin{table}\r\n\\begin{center}\r\n\\caption{\\label{lgd} Little Group for $\\Gamma$ for Diamond}\r\n\\begin{tabular}{lrrrrrrrrrrrr}\\\\ \\hline\r\nLevel & Energy & $\\Gamma$ & E & C$_3$ & C$_2$=C$_4^2$ & C$_2$ & C$_4$\r\n & I & S$_4$ & $\\sigma_d$ & S$_6$\r\n&$\\sigma_h$ \\\\ \\hline\r\n  1& -58.0408& 1& 1& 1& 1& 1 &1&1&1&1&1&1 \\\\\r\n  2&  -9.4687& 2& 3& 0&-1& 1&-1&3&-1&1&0&-1 \\\\\r\n  3&   0.9807& 3& 3& 0&-1&-1&1&-3&-1&1&0&1 \\\\\r\n  4&   4.1933& 4& 1& 1& 1&-1&-1&-1&1&1&-1&-1\\\\ \\hline\r\n\\end{tabular}\\end{center} \\end{table}\r\n\r\nFrom this we see that there are four different irreducible representations: 1,\r\n2, 3, and 4. These representations can be equated with those of the O$_h$\r\npoint-group, so 1 and 4, being non-degenerate, become $a$, while 2 and 3, being\r\n3-fold degenerate, become $t$. So far we have ($a$, $t$, $t$, $a$).  The effect\r\nof inversion on the eigenfunctions allows us to assign {\\em gerade} and  {\\em\r\nungerade}, thus ($a_g$, $t_g$, $t_u$, $a_u$), while C$_4$ resolves the\r\n``1''-``2'' nature of the representations: ($a_{1g}$, $t_{2g}$, $t_{1u}$,\r\n$a_{2u}$).\r\n\r\nInspection of the eigenvectors reveals, as expected, that the two\r\n$a$ representations can be identified with the $s$ atomic orbitals, and the two\r\n$t$ representations, with the six $p$ atomic orbitals.\r\n\r\nFor points other than $\\Gamma$, the little groups become complex. Consider a\r\npoint on $\\Delta$, the line connecting $\\Gamma$ and X, or (0,0,0) and\r\n(1/2,0,0). The little group for (0.123,0,0) has the form shown in\r\nTable~\\ref{dig}.\r\n\\begin{table}\r\n\\begin{center}\r\n\\caption{\\label{dig} Little Group for $\\Delta$ for Diamond}\r\n \\index{Diamond!little group|(}\r\n\\begin{tabular}{lrlrrrrr} \\\\ \\hline\r\nLevel&Energy&$\\Gamma$&E &C$_2$=C$_4^2$ &C$_4$&$\\sigma_d$\r\n&$\\sigma_h$  \\\\  \\hline\r\n  1& -54.2893 &1 & 1& 1& $\\theta$    &   1& $\\theta$   \\\\\r\n  2& -10.2758 &2 & 2&-2& 0           &   0& 0              \\\\\r\n  3& -10.1336 &3 & 1& 1&-$\\theta$    &   1& -$\\theta$   \\\\\r\n  4&   0.9087 &1 & 1& 1& $\\theta$    &   1& $\\theta$   \\\\\r\n  5&   1.5003 &2 & 2&-2& 0           &   0& 0  \\\\\r\n  6&   3.7878 &3 & 1& 1&-$\\theta$    &   1& -$\\theta$  \\\\ \\hline\r\n\\end{tabular}\\end{center}\\end{table}\r\nHere $\\theta$ = $e^{-ik/2\\pi}$.\r\n\r\n\r\nAs is seen, complications arise for those operations which involve\r\n\\index{Characters!complex}\\index{Complex characters} non-primitive\r\ntranslations,\\index{Translations!non-primitive} \\index{Non-primitive\r\ntranslations} e.g.\\  C$_{4}$ and $\\sigma_h$, when points other than $\\Gamma$ are\r\nstudied. The complex phase-factor can cause interpretation of the group\r\ncharacters to be difficult.  One option is to correct for the phase-factor by\r\nmultiplying the character by $e^{ik/2\\pi}$. This would make the little group\r\nfor $\\Delta$ easier to read (Table~\\ref{mdig}).\r\n\r\n\\begin{table}\r\n\\begin{center}\r\n\\caption{\\label{mdig} Modified Little Group for $\\Delta$ for Diamond}\r\n\\begin{tabular}{lrlrrrrr} \\\\ \\hline\r\nLevel&Energy&$\\Gamma$&E &C$_2$=C$_4^2$ &C$_4$&$\\sigma_d$\r\n&$\\sigma_h$  \\\\ \\hline\r\n  1& -54.2893 &1 & 1& 1& 1     &   1& 1    \\\\\r\n  2& -10.2758 &2 & 2&-2& 0     &   0& 0              \\\\\r\n  3& -10.1336 &3 & 1& 1&-1     &   1& -1    \\\\\r\n  4&   0.9087 &1 & 1& 1& 1     &   1& 1    \\\\\r\n  5&   1.5003 &2 & 2&-2& 0     &   0& 0  \\\\\r\n  6&   3.7878 &3 & 1& 1&-1     &   1& -1   \\\\ \\hline\r\n\\end{tabular}\\end{center}\\end{table}\r\n\r\nHowever, for some little groups, this procedure may cause complications. Thus,\r\nat $L$, the inversion operation becomes sensitive to the point chosen, e.g.\r\n(0.25,0.25,0.25) will give a different character for the $I$ operation than\r\n(0.25,0.25,-0.25).\r\n\r\nA third option is to assume that the lowest-lying level represents the totally\r\nsymmetric representation.  (Note: this is different from transforming as the\r\ntotally symmetric representation.  Only one point, the $\\Gamma$-point, can ever\r\ncontain a totally symmetric representation.) By making that assumption, all\r\ncharacters can be related to those of the  lowest-lying level.\r\n\r\nUsers are given key-words which select these alternatives to the basic\r\ncharacter tables when the $k$-point is specified.  The key-words are:\r\n\r\n\\begin{description}\r\n\\index{One! use in BZ}\\index{BZ!use of ``one''}\r\n\\item[\\comp{one}] Assume the lowest energy level is totally symmetric.  All operations\r\ninvolving non-primitive translations are then multiplied by a (complex) factor\r\nwhich will make the lowest energy level totally symmetric. Example: \\comp{0.123 0 0 one}.\r\n\r\n\\index{Byk! use in BZ}\\index{BZ!use of ``byk''}\r\n\\item[\\comp{byk}] Multiply all operations which involve non-primitive translations by\r\na phase factor (``byk''---``multiply by k'')  which depends on the current value\r\nof $k$. Example: \\comp{0.123 0 0 byk}.\r\n\\end{description}\r\n\r\nUsing the points option, assignment of the symmetry of lines and points in\r\n$k$-space becomes very easy.\r\n\r\n\\subsection{Lines in $k$-space}\r\n\r\nA line  in $k$-space is specified by two numbers for a polymer, four numbers\r\nfor a layer system, and six numbers for a solid.  The number of points\r\ncalculated for each line is proportional to the length of the line in\r\n$k$-space. For a line of length 1.0, for example $\\Gamma$ to $\\Gamma$, 300\r\npoints would be calculated. \\index{Walks in\r\n$k$-space}\\index{ksp@{$k$-space}!walks} The data needed to specify a\r\nband-structure `walk' from $\\Gamma $ to X to  W to L to $\\Gamma $ is given in\r\nTable~\\ref{walk}, and for diamond, the band-structure for this `walk' is given\r\nin Figure~\\ref{walk-pic}.\r\n\r\n\\begin{table}\r\n\\begin{center}\r\n\\caption{\\label{walk}A ``Walk'' in $k$-Space ($\\Gamma $ to X to W to L to $\\Gamma $)}\r\n\\begin{tabular}{ccccccccc} \\\\ \\hline\r\nStart && Stop&\\multicolumn{3}{c}{Start} & \\multicolumn{3}{c}{Stop} \\\\ \\hline\r\n$\\Gamma$&-&X & 0.000& 0.000& 0.000& 0.500& 0.000& 0.000  \\\\\r\nX       &-&W        & 0.500& 0.000& 0.000& 0.500& 0.250& 0.000  \\\\\r\nW       &-&L        & 0.500& 0.250& 0.000& 0.250& 0.250& 0.250  \\\\\r\nL       &-&$\\Gamma$ & 0.250& 0.250& 0.250& 0.000& 0.000& 0.000  \\\\ \\hline\r\n\\end{tabular}\r\n\\end{center}\r\n\\end{table}\r\n\\begin{figure}\r\n\\begin{makeimage}\r\n\\end{makeimage}\r\n\\begin{center}\r\n\\includegraphics{diamondbs}\r\n\\end{center}\r\n\\caption{\\label{walk-pic}Band structure for Diamond}\r\n\\label{pbt}\r\n\\end{figure}\r\n\\index{Little groups|)}\r\n\\index{Diamond!little group|)}\r\n\r\n\r\n\\subsection{Surfaces in $k$-space}\r\n\\index{ksp@{$k$-space}!surfaces in}\\index{Surfaces in $k$-space} A surface is\r\ndefined by seven data.  Three numbers are used to specify the center of the\r\nsurface, three are used to define a perpendicular, and one number is used to\r\ndefine the length of an edge.\r\n\r\nFor example, to generate the hexagonal face of the Brillouin Zone for diamond,\r\nthe specification would be (0.25 0.25 0.25 1 1 1 0.7071), the center of the\r\nplot being (0.25 0.25 0.25), and (1 1 1) defining the direction.\r\n\r\nTwo dimensional surfaces use 80 points in each direction, and an interpolation\r\nprocedure is used to double this number to 160 points in each direction.  The\r\nlength of a side in a two-dimensional plot is defined by the user at\r\nrun-time.\r\n\r\nThe cost of generating the surface is quite large.  Because of this, the data\r\nare stored on disk, once they are generated.\r\n\r\nThe user is prompted for input.\r\n\r\n\\subsection{Files used by BZ}\r\n\\index{Files used by BZ}\\index{BZ!files used by}\r\nBZ uses the following files:\r\n\\begin{description}\r\n\\item[\\comp{ $<$filename$>$.ops}] a symmetry file.\r\n\\item[\\comp{ $<$filename$>$.brz}] a Fock matrix file made by MOPAC.\r\n\\end{description}\r\n\r\nThe file \\comp{$<$filename$>$.brz} {\\em must} exist.  The file\r\n\\comp{$<$filename$>$.ops}\r\n{\\em should}, but does not have to, exist.    If \\comp{$<$filename$>$.ops} is\r\nwritten,  the first two lines should look like this:\r\n\\begin{verbatim}\r\n0 0 0 0 0.0       0.0       0.0       1.0  0.0 0.0 0.0  'Identity'\r\n2 0 0 0 0.0       0.0       0.0       0.0  0.0 0.0 0.0  'Terminus'\r\n\\end{verbatim}\r\nMore lines can be added, as needed,  to define the other symmetry operations.\r\n", "meta": {"hexsha": "cbbbee87557473ab83db4b5cb604e7e4c22a516a", "size": 17540, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "manuals/MOPAC2000_manual/bz.tex", "max_stars_repo_name": "openmopac/MOPAC-archive", "max_stars_repo_head_hexsha": "01510e44246de34a991529297a10bcf831336038", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-16T20:53:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T20:54:11.000Z", "max_issues_repo_path": "manuals/MOPAC2000_manual/bz.tex", "max_issues_repo_name": "openmopac/MOPAC-archive", "max_issues_repo_head_hexsha": "01510e44246de34a991529297a10bcf831336038", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "manuals/MOPAC2000_manual/bz.tex", "max_forks_repo_name": "openmopac/MOPAC-archive", "max_forks_repo_head_hexsha": "01510e44246de34a991529297a10bcf831336038", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.9743589744, "max_line_length": 90, "alphanum_fraction": 0.6677879133, "num_tokens": 6109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.34844247767154934}}
{"text": "% !TEX encoding = UTF-8\n% !TEX program = pdflatex\n% !TEX spellcheck = en_US\n% !TEX root = roma-demo.tex\n\n\n\\section{Introduction}\n\n\\subsection{Original problem}\n\n\\begin{frame}[t]{Code Example}\n\t\\begin{lstlisting}[language=C++, caption=Multiplication example]\n\t\tbyte mult(byte in_1, byte in_2){\n\t\t\tbyte mask, result, piv;\n\t\t\tmask = 0x01;\n\t\t\tresult = 0x00;\n\t\t\tpiv = in_1;\t\n\t\t\tfor(int i=0; i<8; i++){\n\t\t\t\tif(in_2 & mask) result^=piv;\n\t\t\t\tmask = mask << 1;\n\t\t\t\tpiv = xtime(piv);\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\t\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}[t]{Assumptions}\n\n\tLet us consider the usual linear regression model defined as: \\[y = \\beta_*^t \\mathbf{x} + \\epsilon \\text{ with }\\]\n\t\n\t\\begin{enumerate}[i.]\n\t\t\\item $\\mathbf{x} \\in \\mathbb{R}^p$ a vector of random variables normally called the input vector.\n\t\t\\item $\\epsilon \\in \\mathbb{R}$ the random noise defined as a Gaussian random variable with expectation zero and variance $\\sigma^2$, this is, $\\epsilon \\sim \\mathcal{N}(\\mu=0,\\,\\sigma^{2})$\n\t\t\\item $y \\in \\mathbb{R}$ a random variable that depends linearly on $\\mathbf{x}$.\n\t\t\\item $\\beta_* \\in \\mathbb{R}^p$ is the optimal model.\n\t\\end{enumerate} \n\n\\end{frame}\n\n\\begin{frame}[t]{Problem Formulation}\n\t\n\tThe problems we need to solve to estimate $\\beta_*$ are written as follow:\n\t\n\t\\begin{mini!}|s|[2]<b>\n\t\t{\\beta, e}{ f(e)+ \\lambda g(\\beta)}{}{P(s, \\lambda) \\quad}\n\t\t\\addConstraint{e}{= \\mathbf{y} - X \\beta \\quad \\label{const:c1ex1}}{e \\in \\mathbb{R}^m, \\beta \\in \\mathbb{R}^p }\n\t\t\\addConstraint{h(\\beta)}{\\leq s}{ s \\in \\mathbb{R}, s \\geq 0}\n\t\t\\addConstraint{\\mathbf{L}\\leq }{A\\beta \\leq \\mathbf{U}}{\\mathbf{L,U} \\in \\mathbb{R}^m, A \\in \\mathbb{R}^{q x p}}\n\t\\end{mini!}\n\n\\end{frame}\n\n\\begin{frame}[t]{Examples}\n\t\\begin{itemize}\n\t\n\t\\item $f$ is the error function. Examples: $f(\\mathbf{e}) = {\\| \\mathbf{e} \\|}_1$ y $f(\\mathbf{e}) =\\frac{1}{2} {\\| \\mathbf{e} \\|}^2_2$, among others.\n\t\n\t\\item $h$ and $g$ are the complexity functions of the model. Examples: $g(\\mathbf{\\beta}) = {\\| \\mathbf{\\beta} \\|}_1$ y $g(\\mathbf{\\beta}) = {\\| \\mathbf{\\beta} \\|}^2_2$, $h(\\mathbf{\\beta}) = {\\| \\mathbf{\\beta} \\|}_1$ y $h(\\beta) = {\\| \\beta \\|}_0 = \\vert \\lbrace j: \\beta_j \\neq 0,\\;\\;j \\in [n] \\rbrace \\vert$, among  others. \n\t\n\t\\item  $A$,$\\mathbf{L}$ and $\\mathbf{U}$ allow the modelling of linear constraints over the regressors.\n\n\t\\end{itemize}\n\\end{frame}\n\n\\subsection{The Holistic Regression Problem}\n\n\\begin{frame}[t]{The Holistic Regression problem}\n\\[(R(\\lambda,s))\\;\\;\\underset{\\beta,\\mathbf{e},\\mathbf{z}}{min}\\;\\;f(\\mathbf{e}) + \\lambda g(\\beta)\\;\\;s.t.\\]\n\\[\\mathbf{y} - X \\beta = \\mathbf{e}\\]\n\\[h(\\beta) \\leq s\\]\n\\[\\mathbf{L} \\leq A\\beta \\leq \\mathbf{U}\\]\n\\[(\\beta,\\mathbf{z}) \\in H\\]\n\\[\\beta \\in \\mathbb{R}^n,\\;\\;\\mathbf{e} \\in \\mathbb{R}^m,\\;\\;\\mathbf{z} \\in {\\lbrace 0,1 \\rbrace}^n\\]\n\t\n\t\\begin{itemize}\n\t\t\\item The structure of $R(\\lambda,s)$ is too general, so the algorithms designed for $P(s, \\lambda)$ cannot be used (Specially because $H$).\n\t\t\\item For the usual optins of $f$,$g$,$h$ and for $H$ defined as affine equations and inequations in $(\\beta,\\mathbf{z})$ $R(\\lambda,s)$ is as (0-1-MICQP).\n\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}[t]{Huber Function $\\rho_\\gamma(s)$}\n\t\\begin{center}\n\t\t$\\rho_\\gamma(s) =\n\t\t\\begin{cases}\n\t\t\\frac{1}{2} s^2  & 0 \\leq  s  \\leq \\gamma\\\\\n\t\t\\gamma  s - \\frac{1}{2} \\gamma^2  &  s \\geq \\gamma\n\t\t\\end{cases}\n\t\t$\n\t\t\n\t\t\\vspace{0.3cm}\n\t\t\n\t\t\\resizebox{0.58\\textwidth}{!}{\n\t\t\t\\begin{tikzpicture}\n\t\t\t\\begin{axis}[\n\t\t\txlabel=$s$,\n\t\t\tylabel={$\\rho_\\gamma(s)$},\n\t\t\tlegend pos=north west\n\t\t\t]\n\t\t\t% p_2(x)\n\t\t\t\\addplot[green, ultra thick, domain=0:3]{0.5*x^2};\n\t\t\t\\addlegendentry{$\\gamma=3$}\n\t\t\t\\addplot[blue, ultra thick, domain=0:2]{0.5*x^2};\n\t\t\t\\addlegendentry{$\\gamma=2$}\n\t\t\t\\addplot[red, ultra thick, domain=0:0.5]{0.5*x^2};\n\t\t\t\\addlegendentry{$\\gamma=0.5$}\n\t\t\t\n\t\t\t\\addplot[green, ultra thick, domain=3:6]{3*abs(x)-0.5*(3)^2};\n\t\t\t\n\t\t\t\\addplot[blue, ultra thick, domain=2:6]{2*abs(x)-0.5*(2)^2};\n\t\t\t\n\t\t\t\\addplot[red, ultra thick, domain=0.5:6]{0.5*abs(x)-0.5*(0.5)^2};\n\t\t\t\n\t\t\t\\end{axis}\n\t\t\t\\end{tikzpicture}\n\t\t}\n\t\\end{center}\n\\end{frame}\n\n\\begin{frame}[t]{The $\\epsilon$-insensitive Huber Function $g_\\gamma^\\epsilon(t)$}\n\t\\begin{center}\n\t\t\n\t\t$f^{\\epsilon}_\\gamma(\\mathbf{e}) = \\underset{i \\in [m]}{\\sum} g^{\\epsilon}_\\gamma(\\bar{\\mathbf{e}}_i)$ with: \\\\\n\t\t\n\t\t$g^{\\epsilon}_\\gamma(t) = \\left\\{\\begin{array}{lcc} 0 & si & \\vert t \\vert \\leq \\epsilon\\\\\\rho_\\gamma(\\vert t \\vert - \\epsilon)   & si & \\vert t \\vert \\geq \\epsilon\\\\\n\t\t\\end{array}\n\t\t\\right.$\n\t\\end{center}\n\t\n\\end{frame}\n\n\\section{The study case}\n\n\\begin{frame}[t]{Study case}\n\t\n\t\\[(R(\\lambda,k))\\;\\;\\underset{\\beta,\\mathbf{e},\\mathbf{z}}{min}\\;\\;f^\\epsilon_\\gamma (\\mathbf{e}) + \\lambda {\\parallel \\beta \\parallel}_1\\;\\;s.t.\\;\\;(1)\\]\n\t\\[\\mathbf{y} - X \\beta = \\mathbf{e}\\;\\;(2)\\]\n\t\\[\\mbox{If}\\;\\;\\mathbf{z}_j = 1\\;\\;\\mbox{then}\\;\\;\\beta_j = 0\\;\\;\\forall j \\in [n]\\;\\;(3)\\]\n\t\\[Co(\\mathbf{z})\\leq k\\;\\;(4)\\]\n\t\\[\\underset{j \\in J1_i}{\\sum} \\mathbf{z}_j \\leq 1\\;\\;\\forall i \\in [n_1]\\;\\;(5)\\]\n\t\\[\\underset{j \\in J2_i}{\\sum} \\mathbf{z}_j = 1\\;\\;\\forall i \\in [n_2]\\;\\;(6)\\]\n\t\\[\\mathbf{z}_{j_1} = \\mathbf{z}_{j_2}\\;\\;\\forall j_1,j_2 \\in B_i\\;\\;\\forall i \\in [n_B]\\;\\;(7)\\]\n\t\\[\\beta_j \\geq 0\\;\\;\\forall j \\in J^+,\\;\\;\\beta_j \\leq 0\\;\\;\\forall j \\in J^-\\;\\;(8)\\]\n\n\\end{frame}\n\n\\begin{frame}[t]{Study case (II)}\n\t\n\t\\[(R(\\lambda,k))\\;\\;\\underset{\\beta,\\mathbf{e},\\mathbf{z}}{min}\\;\\;f^\\epsilon_\\gamma (\\mathbf{e}) + \\lambda {\\parallel \\beta \\parallel}_1\\;\\;s.t.\\;\\;(1)\\]\n\t\\[ \\cdots \\]\n\t\\[\\mathbf{z}_{j_1} + \\mathbf{z}_{j_2} \\leq 1\\;\\;\\forall (j_1,j_2) \\in Jc\\;\\;(9)\\]\n\\[\\beta \\in \\mathbb{R}^n,\\;\\;\\mathbf{e} \\in \\mathbb{R}^m,\\;\\;\\mathbf{z} \\in {\\lbrace 0,1 \\rbrace}^n\\;\\;(10)\\]\n\n\t\n\\end{frame}\n\n\\section{Roadmap}\n\n\n\\begin{frame}[t]{Road}\n\\textbf{Objective:} Find a set of solutions with values close to the optimal, this is {\\it a path of Approximate Solutions} \n\n\\begin{enumerate}\n\t\\item Formulation of $ R(\\lambda, k)$.\n\t\\item Obtaining valid values for BigM values. \n\t\tBigMs too big $\\implies$ numerical problems, inefficiency of algorithms. \n\t\tBigMs too small $ ~ implies $ good solutions removed. \n\t\t\\item {\\it Local Holistic Searches}: Distances, Neighborhoods and Complexity function are presented on $\\mathbf{z}$, which we will call Holistic, that adapt naturally to the case study, to obtain solutions locally optimal.\n\t\t\\item Algorithms for the construction of the Approximate Solutions \tPath combining (2.) and (3.)\n\\end{enumerate}\n\\end{frame}\n", "meta": {"hexsha": "3f30e8e5c199136244fa89631c7684e87f1a5b6f", "size": 6449, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "presentation/1_introduction/regression.tex", "max_stars_repo_name": "belgrades/aes", "max_stars_repo_head_hexsha": "ebd1fbf36acd8e3a787ebc0cd68f83e3784d2979", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-14T12:34:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T12:34:37.000Z", "max_issues_repo_path": "presentation/1_introduction/regression.tex", "max_issues_repo_name": "belgrades/aes", "max_issues_repo_head_hexsha": "ebd1fbf36acd8e3a787ebc0cd68f83e3784d2979", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "presentation/1_introduction/regression.tex", "max_forks_repo_name": "belgrades/aes", "max_forks_repo_head_hexsha": "ebd1fbf36acd8e3a787ebc0cd68f83e3784d2979", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2774566474, "max_line_length": 327, "alphanum_fraction": 0.6146689409, "num_tokens": 2566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199008363969, "lm_q2_score": 0.6757646140788308, "lm_q1q2_score": 0.34843768330007274}}
{"text": "\\section{UTxO}\n\\label{sec:utxo}\n\n\\begin{figure*}[htb]\n  \\emph{Functions}\n  %\n  \\begin{align*}\n    & \\fun{isNonNativeScriptAddress} \\in \\Tx \\to \\Addr \\to \\Bool \\\\\n    & \\fun{isNonNativeScriptAddress}~tx~a = \\\\\n      &\\quad\\begin{cases}\n        s \\in \\ScriptNonNative & a \\in \\AddrScr \\land \\fun{validatorHash}~a \\mapsto s \\in \\fun{txscripts} (\\fun{txwits}~tx) \\\\\n        \\False & \\text{otherwise}\n      \\end{cases}\n                 \\nextdef\n    & \\fun{totExunits} \\in \\Tx \\to \\ExUnits \\\\\n    & \\fun{totExunits}~\\var{tx} = \\sum_{\\wcard \\mapsto (\\wcard, eu) \\in \\fun{txrdmrs}~(\\fun{txwits}~tx)} eu\n    \\nextdef\n    & \\fun{feesOK} \\in \\PParams \\to \\Tx \\to \\UTxO \\to \\Bool  \\\\\n    & \\fun{feesOK}~\\var{pp}~tx~utxo~= \\\\\n    &~~      \\minfee{pp}~{tx} \\leq \\txfee{txb} \\wedge (\\fun{totExunits}~tx \\neq (0, 0) \\Rightarrow \\\\\n    &~~~~~~((\\forall (a, \\wcard, \\_) \\in \\fun{range}~(\\fun{txinputs_{fee}}~{txb} \\restrictdom \\var{utxo}), \\neg \\fun{isNonNativeScriptAddress}~tx~a) \\\\\n    &~~~~~~\\wedge~ \\fun{adaOnly}~\\var{balance} \\\\\n    &~~~~~~      \\wedge~ \\var{balance} \\geq \\txfee{txb})) \\\\\n    &~~      \\where \\\\\n    & ~~~~~~~ \\var{txb}~=~\\txbody{tx} \\\\\n    & ~~~~~~~ \\var{balance}~=~\\fun{ubalance}~(\\fun{txinputs_{fee}}~{txb} \\restrictdom \\var{utxo})\n    \\nextdef\n    & \\fun{txins} \\in \\TxBody \\to \\powerset{\\TxId \\times \\Ix} \\\\\n    & \\fun{txins} ~\\var{txb} = \\fun{txinputs}~txb \\cup \\fun{txinputs_{fee}}~txb\n    \\nextdef\n    & \\fun{txscriptfee} \\in \\Prices \\to \\ExUnits \\to \\Coin \\\\\n    & \\fun{txscriptfee}~(pr_{mem}, pr_{steps})~ (\\var{mem, steps})\n    = \\var{pr_{mem}}*\\var{mem} + \\var{pr_{steps}}*\\var{steps}\n    \\nextdef\n    &\\fun{minfee} \\in \\PParams \\to \\Tx \\to \\Coin \\\\\n    &\\fun{minfee}~\\var{pp}~\\var{tx} = \\\\\n    &~~(\\fun{a}~\\var{pp}) \\cdot \\fun{txSize}~\\var{tx} + (\\fun{b}~\\var{pp}) +\n    \\hldiff{\\fun{txscriptfee}~(\\fun{prices}~{pp})~(\\fun{totExunits}~(\\fun{txbody}~{tx}))}\n  \\end{align*}\n  \\caption{Functions related to fees}\n  \\label{fig:functions:utxo}\n\\end{figure*}\n\nWe have added or changed several functions that deal with fees as shown in Figure \\ref{fig:functions:utxo}.\n\n\\begin{itemize}\n  \\item $\\fun{isNonNativeScriptAddress}$ is a predicate that checks\n  whether an address is used as a script address with a non-native\n  script.\n  \\item $\\fun{totExunits}$ calculates the total $\\ExUnits$ in a transaction by summing\n  the per-script units stored in the indexed redeemer structure\n  \\item The predicate $\\fun{feesOK}$ checks whether the transaction is\n  paying the necessary fees, and that it does it correctly. That is, it checks that:\n  \\begin{enumerate}[label=({\\roman*})]\n    \\item the fee amount that the transaction states it is paying suffices to cover\n    the minimum fee that the transaction is obligated to pay; and if the transaction uses non-native scripts, that\n    \\item the fee-marked inputs do not belong to non-native script addresses;\n    \\item all the fee-marked inputs contain strictly Ada and no other kinds of token; and\n    \\item the fee-marked inputs are sufficient to cover the fee amount that is stated\n    in the transaction.\n  \\end{enumerate}\n  \\item The function $\\fun{txins}$ returns the UTxO keys of transaction inputs.\n  \\item $\\fun{txscriptfee}$ calculates the fee that a transaction must pay for script\n  execution based on the amount of $\\ExUnits$ it has budgeted, and the prices in the current protocol parameters\n  for each component of $\\ExUnits$.\n  \\item The minimum fee calculation, $\\fun{minfee}$, includes the script\n  fees that the transaction is obligated to pay in order to run its scripts.\n\\end{itemize}\n\nNote that when creating a transaction, the wallet is responsible for\ndetermining the fees. Thus, it also has to execute the non-native scripts\nand include the fees for their execution.\n\n\\subsection{Combining Scripts with Their Inputs}\n\\label{sec:scripts-inputs}\n\nFigure~\\ref{fig:functions:script1} shows the functions that are needed to\nretrieve all the data that is relevant to Plutus script validation.\nThese include:\n\n\\begin{itemize}\n\\item $\\Time$ is the system time\n\\item\n  $\\ScriptPurpose$ is a sum type of all parts of a transaction that may\n  require a script witness to validate. Note that this contains the data\n  (eg. a certificate $c \\in \\fun{txcerts}~{txb}$,\n  or a transaction input $tin \\in \\fun{txcerts}~{txb}$) of the item being validated,\n  not just a tag indicating the type.\n\\item\n  $\\fun{indexof}$ is a helper function that finds the index of a given certificate, value, input, or\n  withdrawal in a list, finite map, or set of such objects.\n  It assumes there is some ordering on each of these structures.\n\\item\n  $\\fun{indexedRdmrs}$ indexes the pair of a redeemer and an $\\ExUnits$ value\n  for a given script by its script purpose (eg. the input, or certificate, etc.)\n\\end{itemize}\n\n\n\\begin{figure}[htb]\n  \\emph{Abstract types}\n  %\n  \\begin{equation*}\n    \\begin{array}{r@{~\\in~}l@{}lr}\n      \\var{tm}\n      & \\Time\n      & \\text{System time}\n    \\end{array}\n  \\end{equation*}\n  %\n  \\emph{Derived types}\n  %\n  \\begin{equation*}\n    \\begin{array}{r@{~\\in~}l@{\\qquad=\\qquad}lr}\n      \\var{sp}\n      & \\ScriptPurpose\n      & \\PolicyID \\uniondistinct \\UTxOIn \\uniondistinct \\AddrRWD \\uniondistinct \\DCert\n%      & \\text{item the script is validated for}\n    \\end{array}\n  \\end{equation*}\n  %\n  \\emph{Abstract functions}\n  \\begin{align*}\n    &\\fun{indexof} \\in \\DCert \\to \\seqof{\\DCert} \\to \\Ix\\\\\n    &\\fun{indexof} \\in \\AddrRWD \\to \\Wdrl \\to \\Ix\\\\\n    &\\fun{indexof} \\in \\UTxOIn \\to \\powerset{\\TxIn} \\to \\Ix\\\\\n    &\\fun{indexof} \\in \\PolicyID \\to \\Value \\to \\Ix\n  \\end{align*}\n  %\n  \\emph{Indexing functions}\n  \\begin{align*}\n    &\\fun{indexedRdmrs} \\in \\Tx \\to \\ScriptPurpose \\to (\\seqof{\\Data}~\\times~\\ExUnits)\\\\\n    &\\fun{indexedRdmrs}~tx~sp =\n      \\begin{cases}\n        ([], \\var{eu}) & rdptr \\mapsto (\\Nothing, \\var{eu}) \\in \\fun{txrdmrs}~(\\fun{txwits}~{tx}) \\} \\\\\n        ([d], \\var{eu}) & rdptr \\mapsto (\\var{d}, \\var{eu}) \\in \\fun{txrdmrs}~(\\fun{txwits}~{tx}) \\} \\\\\n        \\Nothing & \\text{otherwise}\n      \\end{cases} \\\\\n    & ~~\\where \\\\\n    & ~~\\quad \\var{txb} = \\txbody{tx} \\\\\n    & ~~\\quad \\var{rdptr} = \\begin{cases}\n        (\\mathsf{certTag},\\fun{indexof}~\\var{sp}~(\\fun{txcerts}~{txb}))   & \\var{sp}~\\in~\\DCert \\\\\n        (\\mathsf{wdrlTag},\\fun{indexof}~\\var{sp}~(\\fun{txwdrls}~{txb}))   & \\var{sp}~\\in~\\AddrRWD \\\\\n        (\\mathsf{mintTag},\\fun{indexof}~\\var{sp}~(\\fun{mint}~{txb}))    & \\var{sp}~\\in~\\PolicyID \\\\\n        (\\mathsf{inputTag},\\fun{indexof}~\\var{sp}~(\\fun{txinputs}~{txb})) & \\var{sp}~\\in~\\UTxOIn\n      \\end{cases}\n  \\end{align*}\n  \\caption{Indexing script and data objects}\n  \\label{fig:functions:script1}\n\\end{figure}\n\n\n\\subsection{Plutus Script Validation}\nFigure~\\ref{fig:defs:functions-valid} shows the abstract functions that are used for script validation.\n\n\\begin{itemize}\n\\item $\\fun{slotToTime}$ translates a slot number to system time if possible.\nIf it is not possible to do this translation, $\\Nothing$ is returned.\nThe reason it may not be possible to translate is that the slot number\nis too far in the future for the system to accurately\npredict the exact time to which it refers.\n\n\\item $\\fun{txInfo}$ summarizes all the necessary transaction and chain state info\n  that needs to be passed to the script interpreter. The $\\Language$ argument\n  is required because different languages have different expectations of the\n  format and contents of the summary $\\Data$ term.\n  It has a $\\UTxO$ as its argument to recover the full information of the inputs of the transaction,\n  but only the inputs of the transaction are provided to scripts. For details, see~\\ref{sec:txinfo}\n\n\\item\n  $\\fun{valContext}$ constructs the \\emph{validation context}. A validation context is\n  a $\\Data$ term which encodes both the summary of the transaction and ledger information\n  (this is supplied by the $\\fun{txInfo}$ summarization function), and the script purpose.\n\n\\item\n  $\\fun{runPLCScript}$ validates Plutus scripts. It takes the following\n  arguments:\n  \\begin{itemize}\n  \\item A cost model, that is used to calculate the $\\ExUnits$ that are needed for script execution;\n  \\item A script to execute;\n  \\item A list of terms of type $\\Data$ that will be passed to the script; and\n  \\item the execution unit budget.\n  \\end{itemize}\n  It outputs the validation result.\n  Note that script execution stops if the full budget has been spent before validation is complete.\n  It is left abstract because it is implemented as part of the native script interpreter, not the ledger.\n  The interpreter called depends on the language of the script.\n\\end{itemize}\n\n\n\\textbf{Slot to time translation.}\nOne of the inputs to scripts is the transaction validity interval (recall here that\nthey do not actually see the current slot number). The length of a\nslot may change in a future era. In this case, for a script written in a previous\nera, if we were to pass the transaction validity interval expressed as slot numbers,\nwe get that\n\n\\begin{itemize}\n  \\item the script logic is expressed in terms of slot numbers\n  which likely assume the slot length of the era in which it was created\n  \\item the slot numbers in the validity interval of the transaction are used\n  assuming slot length of the current era\n\\end{itemize}\n\nTherefore, the slot numbers inside the contract and the slot numbers in the transaction\nmap differently onto points in time. The ledger does not have access to data (or conversion functions)\nthat is needed to convert transaction validity interval slots numbers to slots numbers\nthat correspond to the contracts world view. To address this, we decided to pass\nnon-native contracts (in all languages and all eras) the system time instead of slot numbers.\nThe conversion function is implemented by consensus (see~\\cite{shelley_consensus}),\nwhich has the information to do this correctly for\n\n\\begin{itemize}\n  \\item all slots prior to the current slot\n  \\item a number of slots after the current slot (this number is determined by\n  the consensus's forecast window)\n\\end{itemize}\n\n\\textbf{Validation context construction.}\n  As additional non-native scripting languages become supported in the future, scripts of different\n  languages may expect different (or differently structured) transaction and ledger data summary.\n  The $\\fun{txInfo}$ function will be implemented differently\n  for each new language. So, the construction is\n  dependent on both the language of the script being validated and the ledger/transaction structure\n  of the current era.\n\n  In order to ensure that running scripts of all script languages is supported indefinitely across\n  future eras, the $\\fun{txInfo}$ function must be total.\n  Recall here that while \\emph{running} all scripts must be supported across\n  all future ledger changes,\n  it is not a requirement that every script must \\emph{validate} within the context of some transaction.\n\n  The $\\fun{txInfo}$ output is computed once for the whole transaction. The output of the function\n  $\\fun{valContext}$ is computed separately for each script purpose.\n  The script purpose is passed to it\n  to allow the script to reference itself via its hash, and to be aware of what it is validating.\n\n\\textbf{Know your contract arguments.}\n  A Plutus validator script may receive either a list of three terms of type $\\Data$, in case it validates the spending of script outputs\n  or two terms (redeemer and context, with no datum), for all other uses.\n  Script authors must keep this in mind when writing scripts, since the ledger call to the interpreter is oblivious to what\n  arguments are required.\n\n\\begin{figure*}[htb]\n  \\emph{Abstract Script Validation Functions}\n  %\n  \\begin{align*}\n     &\\fun{slotToTime} \\in \\Slot \\to \\Time^? \\\\\n     &\\text{Translate slot number to system time or fail} \\\\~\\\\\n     &\\fun{txInfo} \\in \\Language \\to \\UTxO \\to \\Tx \\to \\Data \\\\\n     &\\text{Summarizes transaction data} \\\\~\\\\\n     &\\fun{valContext} \\in \\Data \\to \\ScriptPurpose \\to \\Data \\\\\n     &\\text{Pairs transaction data with a script purpose} \\\\~\\\\\n     &\\fun{runPLCScript} \\in \\CostMod \\to\\ScriptPlutus \\to\n    \\seqof{\\Data} \\to \\ExUnits \\to \\IsValidating \\\\\n     &\\text{Validate a Plutus script, taking resource limits into account}\n  \\end{align*}\n  %\n  \\emph{Notation}\n  %\n  \\begin{align*}\n    \\llbracket \\var{script_v} \\rrbracket_{\\var{cm},\\var{exunits}}~\\var{d}\n    &=& \\fun{runPLCScript} ~{cm}~\\var{script_v}~\\var{d}~\\var{exunits}\n  \\end{align*}\n  \\caption{Script Validation, cont.}\n  \\label{fig:defs:functions-valid}\n\\end{figure*}\n\nFigure \\ref{fig:functions:script2} contains the functions used to\nmatch scripts with their corresponding inputs and pass them to the\nevaluator.\n\n\\begin{itemize}\n  \\item $\\fun{getData}$ looks for a datum associated with a given script purpose. Note that\n  only an $\\TxIn$-type script purpose can result in finding an associated datum hash.\n  In no datum is found, an empty list is returned. A list containing the found datum\n  is returned otherwise.\n\n  \\item $\\fun{collectNNScriptInputs}$ builds a list of scripts, paired with their\n  inputs. Specifically, each tuple in the list contains :\n\n  \\begin{itemize}\n  \\item the script;\n\n  \\item the validation context, built by the $\\fun{valContext}$ function using\n  the transaction summary built by $\\fun{txInfo}$, together with the current item being validated;\n\n  \\item the hash of the required datum, if any (returned by the $\\fun{getData}$ function,\n  wrapped in a list type instead of a $\\Data^?$ type).\n\n  \\item a pair, returned by the $\\fun{indexedRdmrs}$ function, of\n  \\begin{itemize}\n    \\item a list of $\\Data$, containing exactly one or zero elements (this\n    is not checked here, however, see~\\ref{fig:functions:script1}). This list\n    contains the optional redeemer if there is one.\n    \\item an $\\ExUnits$ value, which is mandatory for all scripts\n  \\end{itemize}\n\n  \\item $\\fun{evalScripts}$ evaluates a whole list of scripts paired with all their\n  inputs by calling the native script validator function, $\\fun{runPLCScript}$\n\n  \\item $\\fun{runNativeScript}$ replaces the $\\fun{validateScript}$ function,\n  to diffentiate running native and non-native scripts. The definition is the\n  same as in the ShelleyMA specification.\n\\end{itemize}\n\nNote that no ``checks'' are performed within these functions.\nMissing validators, missing inputs, incorrect hashes, the wrong type of script etc,\nare caught during the application of the UTXOW rule (before these functions are ever applied).\n%\n\n\\end{itemize}\n\n\\begin{figure}[htb]\n  \\begin{align*}\n    & \\fun{getData} \\in \\Tx \\to \\UTxO \\to \\ScriptPurpose \\to \\seqof{\\Data} \\\\\n    & \\fun{getData}~{tx}~{utxo}~{sp}~=~\n      \\begin{cases}\n        [\\var{d}] & \\var{sp} \\mapsto (\\_, \\_, h_d) \\in \\var{utxo}, \\var{h_d}\\mapsto \\var{d} \\in \\fun{txdats}~(\\fun{txwits}~tx) \\\\\n        \\epsilon  & \\text{otherwise}\n      \\end{cases}\n    \\nextdef\n    & \\fun{collectNNScriptInputs} \\in \\PParams \\to \\Tx \\to \\UTxO \\to \\seqof{(\\ScriptNonNative \\times \\seqof{\\Data} \\times \\ExUnits \\times \\CostMod)} \\\\\n    & \\fun{collectNNScriptInputs} ~\\var{pp}~\\var{tx}~ \\var{utxo} ~=~ \\\\\n    & ~~\\fun{toList} \\{ (\\var{script}, (\\fun{valContext}~\\var{txinfo}~\\var{sp}~++~ \\fun{getData}~tx~utxo~sp~++~\\var{d}), \\var{eu}, \\var{cm}) \\mid \\\\\n    & ~~~~(\\var{sp}, \\var{scriptHash}) \\in \\fun{scriptsNeeded}~{utxo}~{tx}, \\\\\n    & ~~~~\\var{scriptHash}\\mapsto \\var{script}\\in \\fun{txscripts}~(\\fun{txwits}~tx), \\\\\n    & ~~~~(\\var{d}, \\var{eu}) := \\fun{indexedRdmrs}~tx~sp, \\\\\n    & ~~~~\\fun{language}~{script} \\mapsto \\var{cm} \\in \\fun{costmdls}~{pp} \\} \\\\\n    & \\where \\\\\n    & ~~~~~~~ \\var{txinfo}~=~\\fun{txInfo}~(\\fun{language}~{script})~\\var{utxo}~\\var{tx} \\\\\n    \\nextdef\n    & \\fun{evalScripts} \\in \\seqof{(\\ScriptNonNative \\times \\seqof{\\Data} \\times \\ExUnits \\times \\CostMod)} \\to \\IsValidating \\\\\n    & \\fun{evalScripts}~\\epsilon = \\True \\\\\n    & \\fun{evalScripts}~((\\var{sc}, \\var{d}, \\var{eu}, \\var{cm});\\Gamma) =\n      \\llbracket sc \\rrbracket_{cm,\\var{eu}} d \\land \\fun{evalScripts}~\\Gamma\n    \\nextdef\n    &\\fun{runNativeScript} \\in\\ScriptNative \\to \\Tx \\to \\IsValidating\n  \\end{align*}\n  \\caption{Scripts and their arguments}\n  \\label{fig:functions:script2}\n\\end{figure}\n\n\\subsection{Two-Phase Transaction Validation for Non-Native Scripts}\n\\label{sec:two-phase}\n\nTransactions are validated in two phases:\nthe first phase consists of every aspect of transaction validation apart from executing the non-native scripts; and\nthe second phase involves actually executing those scripts.\nThis ensures that users pay for the computational resources that are needed to validate non-native scripts, even\nif script validation fails. %\nIn order to handle script execution, an additional transition system is used, called UTXOS.\nIt performs the appropriate UTxO state changes, based on the\nvalue of the $\\IsValidating$ tag, which it checks using the $\\fun{evalScripts}$ function.\n\nIn general, there is no way to check \\emph{a-priori} that the budget that has been supplied is sufficient for the transaction.\nThis can only be done by actually running the scripts. From the perspective of the ledger, there is no difference\nbetween a script that exhausts the $\\ExUnits$ budget during validation, and one that fails to validate.\nIf a transaction contains a failing script, the only change to the ledger that is made\nis to collect all inputs that have been marked for fees.\n\nIt is always in the interest of the slot leader to have the new block validate,\nand for it to contain only valid transactions. This motivates the\nslot leader to:\n\n\\begin{enumerate}\n  \\item Correctly apply the $\\IsValidating$ tag;\n  \\item Include all transactions that validate within the block,\n  \\textit{even when there is a 2nd step script validation failure};\n  \\item Exclude any transactions that are invalid in some way \\textit{other than 2nd step script validation failure}.\n\\end{enumerate}\n\nOne important reason for adding the validation tag\nto a transaction is that re-applying blocks will not require repeat\nexecution of scripts in the transactions inside a block, which would increase execution costs.\nIn fact, when replaying\nblocks, all the witnessing information can be thrown away.\n\n\\subsection{The UTXOS transition system}\n\\label{sec:utxo-state-trans}\n\nWe have defined a separate transition system, UTXOS, to represent the two distinct\nUTxO state changes: i) when all the scripts in a transaction validating; and\nii) when at least one fails to validate. Its transition types\nare identical to the UTXO transition (Figure\n\\ref{fig:ts-types:utxo-scripts}).\n\n\\begin{figure}[htb]\n  \\emph{State transitions}\n  \\begin{equation*}\n    \\_ \\vdash\n    \\var{\\_} \\trans{utxos}{\\_} \\var{\\_}\n    \\subseteq \\powerset (\\UTxOEnv \\times \\UTxOState \\times \\Tx \\times \\UTxOState)\n  \\end{equation*}\n  %\n  \\caption{UTxO script state update types}\n  \\label{fig:ts-types:utxo-scripts}\n\\end{figure}\n\nThere are two rules, corresponding to the two possible state changes of the\nUTxO state in the UTXOS transition system (Figure~\\ref{fig:rules:utxo-state-upd}).\n%\nIn both cases, the $\\fun{evalScripts}$ function is called upon to verify that the $\\IsValidating$\ntag has been applied correctly. The function $\\fun{collectNNScriptInputs}$ is used to build\nthe inputs $\\var{sLst}$ for the $\\fun{evalScripts}$ function.\n%\nThe first rule\napplies when the validation tag is $\\True$.\nIn this case, the states of the UTxO, fee\n  and deposit pots, and updates are updated exactly as in the current Shelley\n  ledger spec.\n%\n  The second rule\n  applies when the validation tag is $\\False$.\n  In this case, the UTxO state changes as follows:\n\n  \\begin{enumerate}\n    \\item All the\n    UTxO entries corresponding to the transaction inputs selected for covering\n    fees are removed;\n\n    \\item The sum total of the value of the marked UTxO entries\n    is added to the fee pot.\n  \\end{enumerate}\n\n\n\\begin{figure}[htb]\n  \\begin{equation}\n    \\inference[Scripts-Yes]\n    {\n    \\var{txb}\\leteq\\txbody{tx} &\n    \\var{sLst} := \\fun{collectNNScriptInputs}~\\var{pp}~\\var{tx}~\\var{utxo}\n    \\\\\n    ~\n    \\\\\n    \\fun{txvaltag}~\\var{tx} = \\fun{evalScripts}~\\var{sLst} = \\True\n    \\\\~\\\\\n    {\n      \\begin{array}{r}\n        \\var{slot} \\\\\n        \\var{pp} \\\\\n        \\var{genDelegs} \\\\\n      \\end{array}\n    }\n    \\vdash \\var{pup} \\trans{\\hyperref[fig:rules:update]{ppup}}{\\fun{txup}~\\var{tx}} \\var{pup'}\n    \\\\~\\\\\n    \\var{refunded} \\leteq \\keyRefunds{pp}{txb}\n    \\\\\n    \\var{depositChange} \\leteq\n      (\\deposits{pp}~{poolParams}~{(\\txcerts{txb})}) - \\var{refunded}\n    }\n    {\n    \\begin{array}{l}\n      \\var{slot}\\\\\n      \\var{pp}\\\\\n      \\var{poolParams}\\\\\n      \\var{genDelegs}\\\\\n    \\end{array}\n      \\vdash\n      \\left(\n      \\begin{array}{r}\n        \\var{utxo} \\\\\n        \\var{deposits} \\\\\n        \\var{fees} \\\\\n        \\var{pup} \\\\\n      \\end{array}\n      \\right)\n      \\trans{utxos}{tx}\n      \\left(\n      \\begin{array}{r}\n        \\varUpdate{\\var{(\\txins{txb} \\subtractdom \\var{utxo}) \\cup \\outs{slot}~{txb}}}  \\\\\n        \\varUpdate{\\var{deposits} + \\var{depositChange}} \\\\\n        \\varUpdate{\\var{fees} + \\txfee{txb}} \\\\\n        \\varUpdate{\\var{pup'}} \\\\\n      \\end{array}\n      \\right) \\\\\n    }\n  \\end{equation}\n  \\begin{equation}\n    \\inference[Scripts-No]\n    {\n    \\var{txb}\\leteq\\txbody{tx} &\n    \\var{sLst} := \\fun{collectNNScriptInputs}~\\var{pp}~\\var{tx}~\\var{utxo}\n    \\\\\n    ~\n    \\\\\n    \\fun{txvaltag}~\\var{tx} = \\fun{evalScripts}~\\var{sLst} = \\False\n    }\n    {\n    \\begin{array}{l}\n      \\var{slot}\\\\\n      \\var{pp}\\\\\n      \\var{poolParams}\\\\\n      \\var{genDelegs}\\\\\n    \\end{array}\n      \\vdash\n      \\left(\n      \\begin{array}{r}\n        \\var{utxo} \\\\\n        \\var{deposits} \\\\\n        \\var{fees} \\\\\n        \\var{pup} \\\\\n      \\end{array}\n      \\right)\n      \\trans{utxos}{tx}\n      \\left(\n      \\begin{array}{r}\n        \\varUpdate{\\var{\\fun{txinputs_{fee}}~{txb} \\subtractdom \\var{utxo}}}  \\\\\n        \\var{deposits} \\\\\n        \\varUpdate{\\var{fees} + \\fun{ubalance}~(\\fun{txinputs_{fee}}~{txb}\\restrictdom \\var{utxo})} \\\\\n        \\var{pup} \\\\\n      \\end{array}\n      \\right)\n    }\n  \\end{equation}\n  \\caption{State update rules}\n  \\label{fig:rules:utxo-state-upd}\n\\end{figure}\n\nFigure \\ref{fig:rules:utxo-shelley} shows the $\\type{UTxO-inductive}$\ntransition rule for the UTXO transition type.\nThis rule has the following changes:\n\n\\begin{enumerate}\n  \\item The transaction pays fees correctly, as defined above;\n\n  \\item The end of the transaction validity interval is translatable into\n  system time (ie. within the consensus's forecast window). This is checked\n  by $\\fun{slotToTime}$, which returns $\\Nothing$ if the end slot is outside.\n  Note that we do not need to check that the start slot can be converted to\n  time, because all pasts slots can be converted into time correctly.\n\n  \\item $\\fun{adaPerUTxOWord}$ is now a protocol parameter explicitly, the\n  $\\fun{utxoEntrySize}$ calculation is defined differently than for ShelleyMA\n  (see Section~\\ref{sec:value-size})\n\n  \\item $\\fun{maxValSize}$ is now also a protocol parameter (not a constant).\n  It represents a size (in bytes) of the total transaction\n  size that the size of a $\\Value$ in an output can be. Otherwise, this check is\n  the same as in ShelleyMA.\n\n \\item The execution unit budget for a transaction is within the maximum\n  permitted number of units for a transaction;\n\n  \\item The UTXOS state transition is valid (this is the transition that runs the\n  non-native scripts)\n\\end{enumerate}\n\nThe resulting state transition is defined entirely by the application of the\nUTXOS rule.\n\n\\begin{figure}[htb]\n  \\begin{equation}\\label{eq:utxo-inductive-shelley}\n    \\inference[UTxO-inductive]\n    {\n      \\var{txb}\\leteq\\txbody{tx} &\n      \\fun{ininterval}~\\var{slot}~(\\fun{txvldt}~{tx}) \\\\\n      \\hldiff{\\var{(\\wcard, i_f)}\\leteq\\fun{txvldt}~{tx}} & \\hldiff{\\fun{slotToTime}~i_f \\neq \\Nothing} \\\\\n      \\txins{txb} \\neq \\emptyset\n      & \\hldiff{\\fun{feesOK}~pp~tx~utxo}\n      & \\txins{txb} \\subseteq \\dom \\var{utxo}\n      \\\\\n      \\consumed{pp}{utxo}{txb} = ~\\produced{pp}{poolParams}~{txb}\n      \\\\~\\\\\n      \\mathsf{adaID}\\notin \\supp {\\fun{mint}~tx} \\\\~\\\\\n      \\forall txout \\in \\txouts{txb}, \\\\\n      \\fun{getValue}~txout \\geq \\fun{inject}~(\\hldiff{\\fun{utxoEntrySize}~{txout} * \\fun{adaPerUTxOWord}~pp)} \\\\~\n      \\\\\n      \\forall txout \\in \\txouts{txb},\\\\\n      \\hldiff{\\fun{serSize}~(\\fun{getValue}~txout) ~\\leq ~ (\\fun{maxTxSize}~pp) * (\\fun{maxValSize}~pp)} \\\\~\n      \\\\\n      \\forall (\\wcard\\mapsto (a,~\\wcard)) \\in \\txouts{txb}, \\fun{netId}~a = \\NetworkId\n      \\\\\n      \\forall (a\\mapsto\\wcard) \\in \\txwdrls{txb}, \\fun{netId}~a = \\NetworkId\n      \\\\\n      \\fun{txsize}~{tx}\\leq\\fun{maxTxSize}~\\var{pp} \\\\\n      \\hldiff{\\fun{totExunits}~{tx} \\leq \\fun{maxTxExUnits}~{pp}}\n      \\\\\n      ~\n      \\\\\n      \\hldiff{{\n        \\begin{array}{c}\n          \\var{slot}\\\\\n          \\var{pp}\\\\\n          \\var{poolParams}\\\\\n          \\var{genDelegs}\\\\\n        \\end{array}\n      }\n      \\vdash\n      {\n        \\left(\n          \\begin{array}{r}\n            \\var{utxo} \\\\\n            \\var{deposits} \\\\\n            \\var{fees} \\\\\n            \\var{pup}\\\\\n          \\end{array}\n        \\right)\n      }\n      \\trans{utxos}{\\var{tx}}\n      {\n        \\left(\n          \\begin{array}{r}\n            \\var{utxo'} \\\\\n            \\var{deposits'} \\\\\n            \\var{fees'} \\\\\n            \\var{pup'}\\\\\n          \\end{array}\n        \\right)\n      }\n    }}\n    {\n      \\begin{array}{l}\n        \\var{slot}\\\\\n        \\var{pp}\\\\\n        \\var{poolParams}\\\\\n        \\var{genDelegs}\\\\\n      \\end{array}\n      \\vdash\n      \\left(\n      \\begin{array}{r}\n        \\var{utxo} \\\\\n        \\var{deposits} \\\\\n        \\var{fees} \\\\\n        \\var{pup}\\\\\n      \\end{array}\n      \\right)\n      \\trans{utxo}{tx}\n      \\left(\n      \\begin{array}{r}\n        \\varUpdate{\\var{utxo'}}  \\\\\n        \\varUpdate{\\var{deposits'}} \\\\\n        \\varUpdate{\\var{fees'}} \\\\\n        \\varUpdate{\\var{pup'}}\\\\\n      \\end{array}\n      \\right)\n    }\n  \\end{equation}\n  \\caption{UTxO inference rules}\n  \\label{fig:rules:utxo-shelley}\n\\end{figure}\n\n\\subsection{Witnessing}\n\\label{sec:wits}\n\nBecause of two-phase transaction validation, non-native script validation is not part of phase one of transaction witnessing\n(it is done in phase 2, once the rest of the transaction is validated).\nHowever, native script validation does remain part of transaction witnessing.\nWhen witnessing a transaction in phase one, we therefore need to validate only the native scripts.\n\nWe construct the following helper functions :\n\n\\begin{itemize}\n  \\item $\\fun{scriptsNeeded}$ assembles the all the $\\ScriptPurpose$ terms\n  for validation of every transaction action that requires script validation,\n  paired with the hashes of corresponding the witnessing scripts.\n  This function collects hashes of both native and non-native scripts.\n\n  \\item $\\fun{checkRedeemers}$ returns $\\True$ if, for the given script purpose,\n  whenever the script it points to is non-native, the transaction contains an associated entry\n  in the indexed redeemers structure.\n  Recall that redeemers are optional to include, so there may be a $\\Nothing$ in place of\n  a redeemer. Execution units are mandatory for all scripts, so each script purpose\n  should have an associated entry specifying the $\\ExUnits$ value.\n\n  \\item $\\fun{languages}$ returns the set of (non-native) script languages\n  of all the scripts included in the transaction\n\\end{itemize}\n\n\\begin{figure}[htb]\n  \\begin{align*}\n    & \\hspace{-1cm}\\fun{scriptsNeeded} \\in \\UTxO \\to \\Tx \\to \\powerset (\\ScriptPurpose \\times \\ScriptHash) \\\\\n    & \\hspace{-1cm}\\fun{scriptsNeeded}~\\var{utxo}~\\var{tx} = \\\\\n    & ~~\\{ (\\var{i}, \\fun{validatorHash}~a) \\mid i \\mapsto (a, \\wcard, \\wcard) \\in \\var{utxo},\n      i\\in\\fun{txinsScript}~{(\\fun{txins~\\var{txb}})}~{utxo}\\} \\\\\n    \\cup & ~~\\{ (\\var{a}, \\fun{stakeCred_{r}}~\\var{a}) \\mid a \\in \\dom (\\AddrRWDScr\n           \\restrictdom \\fun{txwdrls}~\\var{txb}) \\} \\\\\n    \\cup & ~~\\{ (\\var{cert}, \\var{c}) \\mid \\var{cert} \\in (\\DCertDeleg \\cup \\DCertDeRegKey)\\cap\\fun{txcerts}~(\\txbody{tx}), \\\\\n    & ~~~~~~\\var{c} \\in \\cwitness{cert} \\cap \\AddrScr\\} \\\\\n      \\cup & ~~\\{ (\\var{pid}, \\var{pid}) \\mid \\var{pid} \\in \\supp~(\\fun{mint}~\\var{txb}) \\} \\\\\n    & \\where \\\\\n    & ~~~~~~~ \\var{txb}~=~\\txbody{tx}\n    \\nextdef\n    & \\hspace{-1cm}\\fun{checkRedeemers} \\in \\Tx \\to \\UTxO \\to (\\ScriptPurpose \\times \\ScriptHash) \\to \\Bool \\\\\n    & \\hspace{-1cm}\\fun{checkRedeemers}~\\var{tx}~\\var{utxo}~(\\var{sp},\\var{h})~=~ \\forall s, (h\\mapsto s) \\in \\fun{txscripts}~(\\fun{txwits}~tx),\\\\\n    & (s \\in \\ScriptNonNative~\\Rightarrow \\fun{indexedRdmrs}~tx~sp \\neq \\Nothing) \\\\\n    \\nextdef\n    & \\hspace{-1cm}\\fun{languages} \\in \\TxWitness \\to \\powerset{\\Language} \\\\\n    & \\hspace{-1cm}\\fun{languages}~\\var{txw}~=~\n      \\{\\fun{language}~s \\mid s \\in \\range (\\fun{txscripts}~{txw}) \\cap \\ScriptNonNative\\}\n  \\end{align*}\n  \\caption{UTXOW helper functions}\n  \\label{fig:functions-witnesses}\n\\end{figure}\n\nWe have made the following changes and additions to the UTXOW preconditions:\n\n\\begin{itemize}\n\n\\item All the native scripts in the transaction validate;\n\n\\item The transaction contains exactly those scripts that are required for witnessing and no\nadditional ones;\n\n    \\item The datums included in the witnesses are exactly those that are required for validating;\n\n    \\item For every item that needs to be validated by a non-native script, the transaction contains\n      an entry in the indexed redeemer structure (ie. the execution units for it are specified);\n\n    \\item The signatures of the keys whose hashes are specified in the\n    $\\fun{reqSignerHashes}$ field in a transaction\n    have all indeed signed it;\n\n    \\item\n    The hash of the subset of protocol parameter values that have been included in the transaction body is the same as\n    the hash of the same subset of protocol parameters that are currently contained in the ledger;\n\n    \\item A check that ensures that the list of scripts paired with their input data (context, datum and redeemer)\n    has the same number of elements as the set of scripts needed for each script purpose. Note that the same\n    script may appear more than once in both the list and the set, as it can be used for different purposes, and therefore\n    run separately for each, with different input data. Note also that by construction, the output of\n    the $\\fun{collectNNScriptInputs}$ function should have exactly the same collection of scripts as\n    the $\\fun{scriptsNeeded}$ function output - this check is in place to catch discrepancies in this construction.\n    \\begin{note}\n      Note that $\\fun{collectNNScriptInputs}$ is called twice, here and in UTXO. We need to avoid this.\n      ALSO we need to audit the $\\fun{wppHash}$ function\n    \\end{note}\n\\end{itemize}\n\nIf these conditions are all satisfied, then the resulting UTxO state change is fully determined\nby the UTXO transition (the application of which is also part of the conditions).\n\n\\begin{figure}[htb]\n  \\emph{State transitions}\n  \\begin{equation*}\n    \\_ \\vdash\n    \\var{\\_} \\trans{utxow}{\\_} \\var{\\_}\n    \\subseteq \\powerset (\\UTxOEnv \\times \\UTxOState \\times \\Tx \\times \\UTxOState)\n  \\end{equation*}\n  %\n  \\caption{UTxO with witnesses state update types}\n  \\label{fig:ts-types:utxo-witness}\n\\end{figure}\n\n\\begin{figure}\n  \\begin{equation}\n    \\label{eq:utxo-witness-inductive-alonzo}\n    \\inference[UTxO-witG]\n    {\n      \\var{txb}\\leteq\\txbody{tx} &\n      \\var{txw}\\leteq\\fun{txwits}~{tx} \\\\\n      (utxo, \\wcard, \\wcard, \\wcard) \\leteq \\var{utxoSt} \\\\\n      \\var{witsKeyHashes} \\leteq \\{\\fun{hashKey}~\\var{vk} \\vert \\var{vk} \\in\n      \\dom (\\txwitsVKey{txw}) \\}\\\\~\\\\\n      \\hldiff{\\forall \\var{s} \\in \\range (\\fun{txscripts}~{txw}) \\cap \\ScriptNative,\n      \\fun{runNativeScript}~\\var{s}~\\var{tx}}\\\\~\\\\\n      \\hldiff{\\{ s \\mid (\\_, s) \\in \\fun{scriptsNeeded}~\\var{utxo}~\\var{tx}\\} = \\dom (\\fun{txscripts}~{txw})} \\\\\n      \\hldiff{\\{ h \\mid (\\_ \\mapsto (a, \\_, h)) \\in \\txins{txb} \\restrictdom \\var{utxo}, \\fun{isNonNativeScriptAddress}~{tx}~{a}\\} =} \\\\\n      \\hldiff{\\dom (\\fun{txdats}~{txw})} \\\\\n      \\hldiff{\\forall sph \\in \\fun{scriptsNeeded}~\\var{utxo}~\\var{tx},~ \\fun{checkRedeemers}~tx~utxo~sph}\n      \\\\~\\\\\n      \\forall \\var{vk} \\mapsto \\sigma \\in \\txwitsVKey{txw},\n      \\mathcal{V}_{\\var{vk}}{\\serialised{txbodyHash}}_{\\sigma} \\\\\n      \\hldiff{\\fun{witsVKeyNeeded}~{utxo}~{tx}~{genDelegs} \\cup \\fun{reqSignerHashes}~txb \\subseteq \\var{witsKeyHashes}}\n      \\\\~\\\\\n      genSig \\leteq\n      \\left\\{\n        \\fun{hashKey}~gkey \\vert gkey \\in\\dom{genDelegs}\n      \\right\\}\n      \\cap\n      \\var{witsKeyHashes}\n      \\\\\n      \\left\\{\n        c\\in\\txcerts{txb}~\\cap\\DCertMir\n      \\right\\} \\neq\\emptyset \\implies \\vert genSig\\vert \\geq \\Quorum \\wedge\n      \\fun{d}~\\var{pp} > 0\n      \\\\~\\\\\n      \\var{adh}\\leteq\\fun{txADhash}~\\var{txb}\n      &\n      \\var{ad}\\leteq\\fun{txAD}~\\var{tx}\n      \\\\\n      (\\var{adh}=\\Nothing \\land \\var{ad}=\\Nothing)\n      \\lor\n      (\\var{adh}=\\fun{hashAD}~\\var{ad})\n      \\\\~\\\\\n      \\hldiff{\\fun{wppHash}~{txb}~=~\\fun{hashWitnessPPData}~\\var{pp}~(\\fun{languages}~{txw})~(\\fun{txrdmrs}~{txw})}\n      \\\\~\\\\\n      \\hldiff{\\|~\\fun{scriptsNeeded}~\\var{utxo}~\\var{tx}~\\|~=~\\|~\\fun{collectNNScriptInputs} ~\\var{pp}~\\var{tx}~ \\var{utxo}~\\|}\n      \\\\~\\\\\n      {\n        \\begin{array}{r}\n          \\var{slot}\\\\\n          \\var{pp}\\\\\n          \\var{poolParams}\\\\\n          \\var{genDelegs}\\\\\n        \\end{array}\n      }\n      \\vdash \\var{utxoSt} \\trans{\\hyperref[fig:rules:utxo-shelley]{utxo}}{tx}\n      \\var{utxoSt'}\\\\\n    }\n    {\n      \\begin{array}{r}\n        \\var{slot}\\\\\n        \\var{pp}\\\\\n        \\var{poolParams}\\\\\n        \\var{genDelegs}\\\\\n      \\end{array}\n      \\vdash \\var{utxoSt} \\trans{utxow}{tx} \\varUpdate{\\var{utxoSt'}}\n    }\n  \\end{equation}\n  \\caption{UTxO with witnesses inference rules for Tx}\n  \\label{fig:rules:utxow-alonzo}\n\\end{figure}\n", "meta": {"hexsha": "2f404488f58841f4b3ea6bec4f419c26f4d2b48e", "size": 33759, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "alonzo/formal-spec/utxo.tex", "max_stars_repo_name": "goolord/cardano-ledger-specs", "max_stars_repo_head_hexsha": "03a01f9ceece4ebe49fcd4f42fe94e5024dfcadd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "alonzo/formal-spec/utxo.tex", "max_issues_repo_name": "goolord/cardano-ledger-specs", "max_issues_repo_head_hexsha": "03a01f9ceece4ebe49fcd4f42fe94e5024dfcadd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "alonzo/formal-spec/utxo.tex", "max_forks_repo_name": "goolord/cardano-ledger-specs", "max_forks_repo_head_hexsha": "03a01f9ceece4ebe49fcd4f42fe94e5024dfcadd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.5239852399, "max_line_length": 151, "alphanum_fraction": 0.6660742321, "num_tokens": 10541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.3484076423105946}}
{"text": "\\documentclass[11pt]{article}\n%============Macros==================%\n% you don't need to change anything. start editing from main body.\n\\usepackage{amsmath,amsfonts,amssymb,amsthm, cancel, float, enumitem}\n\\usepackage{qcircuit}\n\\usepackage[margin=1in]{geometry}\n%--------------Cosmetic----------------%\n\\usepackage{mathtools}\n\\usepackage{hyperref}\n\\usepackage{fullpage}\n\\usepackage{microtype}\n\\usepackage{xspace}\n\\usepackage[svgnames]{xcolor}\n\\usepackage[sc]{mathpazo}\n\\usepackage{enumitem}\n\\setlist[enumerate]{itemsep=1pt,topsep=2pt}\n\\setlist[itemize]{itemsep=1pt,topsep=2pt}\n%--------------Header------------------%\n\\def\\course{CS 410/510 Introduction to Quantum Computing}\n\\def\\term{Portland State U, Spring 2017}\n\\def\\prof{Lecturer: Fang Song}\n\\newcommand{\\handout}[5]{\n   \\renewcommand{\\thepage}{\\arabic{page}}\n   \\begin{center}\n   \\framebox{\n      \\vbox{\n    \\hbox to 5.78in { \\hfill \\large{\\course} \\hfill }\n       \\vspace{2mm}\n       \\hbox to 6in { {\\Large \\hfill #5  \\hfill} }\n       \\vspace{2mm}\n       \\hbox to 6in { \\term \\hfill \\emph{#2}}\n       \\hbox to 6in { {#3 \\hfill \\emph{#4}}}\n      }\n   }\n   \\end{center}\n   \\vspace*{4mm}\n}\n\\newcommand{\\lecture}[4]{\\handout{#1}{#2}{#3}{#4}{{Lecture #1}}}\n\n\\def\\complex{\\mathbb{C}}\n\\def\\real{\\mathbb{R}}\n\\def\\natural{\\mathbb{N}}\n\\def\\integer{\\mathbb{Z}}\n\n\\newcommand{\\norm}[1]{\\left\\lVert#1\\right\\rVert}\n\\newcommand{\\snorm}[1]{\\lVert#1\\rVert}\n\\newcommand{\\abs}[1]{\\left\\lvert #1 \\right\\rvert}\n\\newcommand{\\ceil}[1]{\\left\\lceil #1 \\right\\rceil}\n\\newcommand{\\floor}[1]{\\left\\lfloor #1 \\right\\rfloor}\n\\newcommand{\\set}[1]{\\left\\{ #1 \\right\\}}\n\\newcommand{\\vecb}[1]{\\boldsymbol{\\vec{#1}}}\n\\newcommand{\\conj}[1]{\\overline{#1}}\n\\newcommand{\\op}[2]{#1#2#1^\\dag}\n\n\\newcommand{\\tr}{\\operatorname{Tr}}\n\\newcommand{\\se}{\\operatorname{H}}\n\\newcommand{\\vne}{\\operatorname{S}}\n\\newcommand{\\e}{\\operatorname{E}}\n\\newcommand{\\rank}{\\operatorname{rank}}\n\\renewcommand{\\det}{\\operatorname{Det}}\n\n\\newcommand{\\bra}[1]{\\langle #1 \\rvert}\n\\newcommand{\\ket}[1]{\\lvert #1 \\rangle}\n\\newcommand{\\bret}[2]{\\langle{#1}|{#2}\\rangle}\n\\newcommand{\\kret}[2]{\\ket{#1}\\bra{#2}}\n\\newcommand{\\kera}[1]{\\kret{#1}{#1}}\n\\newcommand{\\Example}[1]{{\\bf Example #1}:}\n\n\\def\\X{\\mathcal{X}}\n\\def\\Y{\\mathcal{Y}}\n\\def\\Z{\\mathcal{Z}}\n\\def\\W{\\mathcal{W}}\n\\def\\A{\\mathcal{A}}\n\\def\\B{\\mathcal{B}}\n\\def\\V{\\mathcal{V}}\n\\def\\U{\\mathcal{U}}\n\\def\\C{\\mathcal{C}}\n\\def\\D{\\mathcal{D}}\n\\def\\E{\\mathcal{E}}\n\\def\\F{\\mathcal{F}}\n\\def\\M{\\mathcal{M}}\n\\def\\R{\\mathcal{R}}\n\\def\\P{\\mathcal{P}}\n\\def\\Q{\\mathcal{Q}}\n\\def\\S{\\mathcal{S}}\n\\def\\T{\\mathcal{T}}\n\\def\\K{\\mathcal{K}}\n\\def\\L{\\mathcal{L}}\n\n\\def\\fill{   \\hfill}\n\n%=============Main Doc=================%\n\\begin{document}\n%-----Specs: change accordingly--------%\n\\def\\lecdate{May 16, 2017} % put lecture date here\n\\def\\scribe{Scribe: Enis K. Inan} % put your name here\n\\def\\lecnum{13} % change the lecture number\n\n\\lecture{\\lecnum}{\\lecdate}{\\prof}{\\scribe}%\n\n\\begin{center}\n{\\textsc{Version: \\today}}  \n\\end{center}\n\n\n\\noindent Last lecture we introduced the density operator, which made it easier for us to describe general quantum states. We will briefly review it before proceeding any further. In the old notation, we only had pure states of the form $\\ket{\\psi} = \\alpha \\ket{0} + \\beta \\ket{1}$ where $\\alpha, \\beta \\in \\complex$ and $\\abs{\\alpha}^2 + \\abs{\\beta}^2 = 1$. With our new framework, a pure state is expressed as $\\kera{\\psi}$ where for our example,\n\\begin{equation*}\n\\kera{\\psi} = \\left(\\begin{array}{cc}\n\\alpha\\conj{\\alpha} & \\alpha\\conj{\\beta} \\\\\n\\conj{\\alpha}\\beta & \\beta\\conj{\\beta}\n\\end{array}\n\\right) = \\left(\\begin{array}{cc}\n\\abs{\\alpha}^2 & \\alpha\\conj{\\beta} \\\\\n\\conj{\\alpha}\\beta & \\abs{\\beta}^2\n\\end{array}\n\\right)\n\\end{equation*}\nThe expressive power of this notation is apparent when we have general quantum states. Specifically, imagine we have a register $X$ that could be in one of the quantum states $\\ket{\\psi_1}, \\dots, \\ket{\\psi_k}$ with a probability distribution $p_1, \\dots, p_k$ where $p_i$ is the probability that $X$ is in state $\\ket{\\psi_i}$. With our new notation, we expressed our ``knowledge'' of $X$ as a density matrix $\\rho$ where\n\\begin{equation*}\n\\rho = \\sum_{i} p_i \\kera{\\psi_i}\n\\end{equation*}\nIntuitively, $\\rho$ corresponds to a weighted average of each state. There were also several important properties associated with density matrices:\n\\begin{enumerate}\n\t\\item $\\tr{(\\rho)} = 1$\n\t\n\t\\item $\\rho$ is positive semidefinite.\n\\end{enumerate}\nProperty 2 will be important later in this lecture, so keep it in the back of your head for now.\n\n\\fill\n\n\\noindent In our old notation, the physically allowable operations on $\\ket{\\psi}$ were unitary operations $U$ -- the state $\\ket{\\psi'} = U\\ket{\\psi}$ is the resulting state after applying the unitary $U$ on $\\ket{\\psi}$. In our new notation, $\\rho' = U\\rho U^\\dag$ corresponds to applying the unitary $U$ on the general quantum state described by $\\rho$ -- the result is $\\rho'$.\n\n%==============================%\n\\section{General (Physically Admissible) Quantum Operations}\n%==============================%\nThe density matrix formalism does not limit us to just unitary operations. Specifically, any \\emph{physically admissible operation} $\\Phi$ is a series of matrices $A_1, A_2, \\dots, A_k$ where $A_{i_{jk}} \\in \\complex$ and\n\\begin{equation} \\label{eq:phya:completeness}\n\\sum_{i} A^\\dag_iA_i = I \n\\end{equation}\n\\begin{equation} \\label{eq:phya:app}\n\\Phi(\\rho) = \\sum_{i} \\op{A_i}{\\rho}\n\\end{equation}\nNote that each $A_i$ in $\\Phi$ does \\emph{not} have to be a square matrix, and that unitary matrices $U$ are a special case of $\\Phi$ with $k = 1$.\n\n\\noindent Applying $\\Phi$ to $\\rho$ yields another density matrix, just like how applying unitary $U$ to $\\ket{\\psi}$ resulted in another valid quantum state. In fact, $\\Phi$ is also known as a completely positive trace preserving (CPTP) operator, which is just jargon for an operation that preserves a matrix's trace and semi-positive definitiveness. Another way to think of $\\Phi$ is as follows. Let $\\X$ and $\\Y$ denote spaces describing $m$ and $n$ qubits, respectively, and let $\\L(\\X, \\Y)$ be the set of all linear mappings from $\\X$ to $\\Y$. Let $\\D(\\X)$ be the set of all density matrices in $\\X$; define $\\D(\\Y)$ in a similar manner. Then $\\Phi : \\D(\\X) \\rightarrow \\D(\\Y)$ or, informally, $\\Phi$ is the set of all density matrix mappings from $\\X$ to $\\Y$.\n\n\\fill  \n\n\\noindent \\Example{1} Here we investigate decoherence as a physically admissible operation, which is when a quantum system interacts with some environmental noise and loses its quantumness (i.e. gets measured). Note that the operation used in this example is equivalent to measurement in the standard basis $\\set{\\ket{0}, \\ket{1}}$. Here we have $A_0 = \\kera{0}$ and $A_1 = \\kera{1}$ so that\n\\begin{equation*}\n\\Phi(\\rho) = \\op{A_0}{\\rho} + \\op{A_1}{\\rho}\n\\end{equation*}\nFirs we check if $A_0$ and $A_1$ are valid, i.e. that they satisfy Eqn. \\ref{eq:phya:completeness}:\n\\begin{align*}\n\\sum_{i} A^\\dag_iA_i\n&= A^\\dag_0A_0 + A^\\dag_1A_1 \\\\\n&= \\ket{0}\\bret{0}{0}\\bra{0} + \\ket{1}\\bret{1}{1}\\bra{1} \\\\\n&= \\kera{0} + \\kera{1} \\\\\n&= I\n\\end{align*}\nwhich they do. Now assume that $\\rho=\\kera{\\psi}$ where $\\ket{\\psi} = \\alpha\\ket{0} + \\beta\\ket{1}$, i.e. that $\\rho$ corresponds to a pure state. We have,\n\\begin{align*}\n\\Phi(\\kera{\\psi}) \n&= \\op{A_0}{\\kera{\\psi}} + \\op{A_1}{\\kera{\\psi}} \\\\\n&= \\kera{0}\\kera{\\psi}\\kera{0} + \\kera{1}\\kera{\\psi}\\kera{1} \\\\\n&= \\left(\\begin{array}{cc}\n1 & 0 \\\\\n0 & 0\n\\end{array}\\right)\n\\left(\\begin{array}{cc}\n\\abs{\\alpha}^2 & \\alpha\\conj{\\beta} \\\\\n\\conj{\\alpha}\\beta & \\abs{\\beta}^2\n\\end{array}\n\\right)\n\\left(\\begin{array}{cc}\n1 & 0 \\\\\n0 & 0\n\\end{array}\\right) + \\left(\\begin{array}{cc}\n0 & 0 \\\\\n0 & 1\n\\end{array}\\right)\n\\left(\\begin{array}{cc}\n\\abs{\\alpha}^2 & \\alpha\\conj{\\beta} \\\\\n\\conj{\\alpha}\\beta & \\abs{\\beta}^2\n\\end{array}\n\\right)\n\\left(\\begin{array}{cc}\n0 & 0 \\\\\n0 & 1\n\\end{array}\\right) \\\\\n&= \\left(\\begin{array}{cc}\n\\abs{\\alpha}^2 & 0 \\\\\n0 & \\abs{\\beta}^2\n\\end{array}\n\\right) \\\\\n&= \\abs{\\alpha}^2\\kera{0} + \\abs{\\beta}^2\\kera{1}\n\\end{align*}\nwhich is exactly what we get by doing a measurement on the standard basis! To see why, the last line shows that we can think of $\\Phi(\\kera{\\psi})$ as representing the general quantum state where we have an $\\abs{\\alpha}^2$ chance of being in $\\ket{0}$ and a $\\abs{\\beta}^2$ chance of being in $\\ket{1}$. This is the definition of measurement in the standard basis.\n\n\\fill\n\n\\noindent Another important operation is the partial trace. Imagine that we have an $m + n$ qubit-state, e.g. $\\ket{\\psi} = \\sum_{x \\in \\set{0, 1}^m}\\sum_{y \\in \\set{0, 1}^n} \\alpha_{xy}\\ket{x}\\ket{y}$. We want to examine the resulting state after we discard either $x$ or $y$. For our old notation, this is easy -- for $\\ket{\\psi}$, we can just remove $\\ket{x}$ or $\\ket{y}$. But in our new notation of density matrices, it is not as obvious. Let $\\X$ and $\\Y$ be the spaces describing $\\ket{x}$ and $\\ket{y}$, respectively, and assume without any loss of generality that we want to remove $\\ket{y}$. Then what we want is an operation $\\Phi: \\D(\\X \\otimes \\Y) \\rightarrow \\D(\\X)$ -- this is the partial trace, denoted as $\\tr_y$ for our specific case to explicitly indicate that we want to discard $\\ket{y}$.\n\n\\fill\n  \n\\noindent Let's examine what $\\tr_y$ would look like when $\\X$ and $\\Y$ both describe 1-qubit each -- i.e., when we have a two-qubit state and we want to discard the second qubit. We have $\\Phi$ be the matrices:\n\\begin{equation*}\n\\begin{split}\nA_0 &= I_x \\otimes \\bra{0}_y = \\left(\\begin{array}{cccc}\n1 & 0 & 0 & 0 \\\\\n0 & 0 & 1 & 0\n\\end{array}\\right) \\\\\nA_1 &= I_x \\otimes \\bra{1}_y = \\left(\\begin{array}{cccc}\n0 & 1 & 0 & 0 \\\\\n0 & 0 & 0 & 1\n\\end{array}\\right)\n\\end{split}\n\\end{equation*}\nNote that $A_0$ and $A_1$ are $2 \\times 4$ matrices -- $I_x$ is the $2 \\times 2$ identity matrix. We first check that $A_0$ and $A_1$ satisfy Eqn. \\ref{eq:phya:completeness}:\n\\begin{align*}\n\\sum_{i} A^\\dag_iA_i\n&= A^\\dag_0A_0 + A^\\dag_1A_1 \\\\\n&= (I_x \\otimes \\ket{0}_y)(I_x \\otimes \\bra{0}_y)\n+  (I_x \\otimes \\ket{1}_y)(I_x \\otimes \\bra{1}_y) \\\\\n&= (I_x \\otimes \\kera{0}_y) + (I_x \\otimes \\kera{1}_y) \\\\\n&= I_x \\otimes (\\kera{0}_y + \\kera{1}_y) \\\\\n&= I_x \\otimes I_y = I_{xy}\n\\end{align*}\nNow let's do an example calculation using $\\Phi$.\n\n\\fill\n\n\\noindent \\Example{2} Let $\\rho = \\kera{0} \\otimes \\kera{1}$. Intuitively, we should get $\\kera{0}$ back after applying $\\Phi$. Let's see if this is indeed the case.\n\\begin{align*}\n\\Phi(\\rho)\n&= \\op{A_0}{\\rho} + \\op{A_1}{\\rho} \\\\\n&= (I_x \\otimes \\bra{0}_y)(\\kera{0} \\otimes \\kera{1})(I_x \\otimes \\ket{0}_y)\n+  (I_x \\otimes \\bra{1}_y)(\\kera{0} \\otimes \\kera{1})(I_x \\otimes \\ket{1}_y) \\\\\n&= \\cancelto{0}{(\\kera{0} \\otimes \\bret{0}{1}\\bra{1})}(I_x \\otimes \\ket{0}_y)\n+  (\\kera{0} \\otimes \\bret{1}{1}\\bra{1})(I_x \\otimes \\ket{1}_y) \\\\\n&= (\\kera{0} \\otimes \\bra{1})(I_x \\otimes \\ket{1}_y) \\\\\n&= \\kera{0}\n\\end{align*}\nwhich is exactly what we expected. In the general case, e.g. when we have $\\rho' = \\rho \\otimes \\ket{0}$, then $\\Phi(\\rho') = \\rho$ which is consistent with the physical meaning of $\\tr_y$ -- take away $y$ and only look at $x$. We can think of it as ``tracing out $y$'', which is where the name ``partial trace'' comes from.\n\n\\fill\n\n\\noindent Now what if the qubits $x$ and $y$ are entangled? What do we get after we apply $\\tr_y$? We will use $\\ket{\\phi^+} = \\frac{1}{\\sqrt{2}}(\\ket{00} + \\ket{11})_{xy}$ as our example.\n\n\\fill\n\n\\noindent \\Example{3} $\\tr_y(\\kera{\\phi^+}) = \\frac{1}{2}\\kera{0} + \\frac{1}{2}\\kera{1} = \\frac{1}{2}I$ which can be verified by brute-force computation using $\\Phi$, like we did in Example 2. So we see that we get a \\emph{maximally mixed state}, i.e. a density matrix where the pure states form an orthonormal basis and each state has a probability $1/n$ of occurring, where $n$ is the dimension of the matrix. Here, $n = 2$. In fact, it can be shown that $\\tr_y$ for \\emph{any} Bell state is $\\frac{1}{2}I$. Here's why this makes sense. In a Bell state, when we measure the second register, we \\emph{collapse} the resulting state to either just $\\ket{0}$ with probability $1/2$, or just $\\ket{1}$ with probability $1/2$ -- exactly our maximally mixed state. For example in $\\ket{\\phi^+}$, if we measure a $1$ in the second register, then the state collapses to $\\ket{1}_x$; otherwise, it collapses to $\\ket{0}_x$.\n\n\\fill\n\n\\noindent The next operation we will consider is an extension of Example 1. Instead of constraining the measurement to a specific basis, e.g. the standard basis, let's generalize it. Imagine that $\\Gamma$ represents the set of all possible outcomes resulting from our measurement and, for an $a \\in \\Gamma$, $M_a$ is the matrix ``capturing'' an outcome $a$. For example in Example 1, $\\Gamma = \\set{0, 1}$, and $M_0 = \\kera{0}$, $M_1 = \\kera{1}$. Then if\n\\begin{equation*}\n\\sum_{a \\in \\Gamma} M^\\dag_aM_a = I\n\\end{equation*}\nthen the set of matrices $M = \\set{M_a \\: | \\: a \\in \\Gamma}$ form a physically admissible operation $\\Phi$, i.e. $\\Phi$ is a valid measurement. Let's take an outcome $a$ and its measurement matrix $M_a$ where $M_a$ is a projecter ($M^2_a = M_a$). Then $\\tr(M_a\\rho M^\\dag_a)$ is the probability that we will observe outcome $a$ when we measure the quantum system described by $\\rho$. In Example 1, $\\tr(M_0\\rho M^\\dag_0) = \\abs{\\alpha}^2$, which is exactly the probability of measuring a $0$. Now assume that we did measure $a$. Then our state would collapse to\n\\begin{equation*}\n\\frac{M_a\\rho M^\\dag_a}{\\tr(M_a\\rho M^\\dag_a)}\n\\end{equation*}\nwhich makes sense. If $M_a$ is the measurement matrix ``capturing'' an outcome $a$ then when we see $a$, we should only have $M_a\\rho M^\\dag_a$ left in our summation for $\\Phi(\\rho)$. However $M_a\\rho M^\\dag_a$ may not be a valid density matrix, so we need to normalize its trace back down to $1$ -- this is what the $\\tr(M_a\\rho M^\\dag_a)$ in the denominator does. This corresponds to what we do in the pure state case, which is to keep only parts of the state that contain the measured outcome in its qubits ($M_a\\rho M^\\dag_a$ here), then normalize that part (divide by $\\tr(M_a\\rho M^\\dag_a)$).\n\n\\fill\n\n\\noindent The above is known as a Von-Neumann measurement. Another way to think about measurement is through positive operator valued measurements (POVMs) which are the most general class of quantum measurements. In a POVM, we do not care about the resulting state after the measurement; only the probability of a specific outcome $a$. Above, we determined this to be $\\tr(M_a\\rho M^\\dag_a)$. Using a nice property of the trace, $\\tr(AB) = \\tr(BA)$, we see that $\\tr(M_a\\rho M^\\dag_a) = \\tr(M^\\dag_aM_a \\rho ) = \\tr(E_a \\rho)$ where $E_a = M^\\dag_aM_a$. Given that $\\tr(E_a \\rho)$ is the probability that we will see outcome $a$, we can think of $E_a$ as a ``probability'' matrix for outcome $a$ that we multiply with $\\rho$ to obtain the probability that we measure $a$. Then note that the completeness condition, i.e. Eqn. \\ref{eq:phya:completeness}, can be restated as $\\sum_{a} E_a = 1$ -- intuitively, this is like $\\sum_{i} p_i = 1$ for a probability distribution. So POVM is a generalization of measurement, but in a different flavor.\n\n\\fill\n\n\\noindent It would appear on the surface that a physically admissible operator $\\Phi$ is more powerful than a unitary $U$ because $U$ is just $\\Phi$ with $k = 1$, i.e. $\\Phi$ has more matrices that we're applying on $\\rho$. Surprisingly according to Stinespring's Dilation Theorem, this is not the case - unitaries and physically admissible operators are \\emph{equally} powerful. Proving this result is beyond the scope of this class, but the basic idea is that we can simulate any circuit implementing $\\Phi$ with a corresponding unitary circuit using some ancilla bits as input to the latter. At a high-level, the diagram looks like the following: \n\\includegraphics[scale = 0.7]{phisim}\n%NOTE: Don't know how to draw the above as a circuit, spent too much time trying to figure it out.\n\n\\noindent \\Example{4} As an example, let's simulate $\\Phi$ as described in Example 1. The following circuit will do the trick:\n\n\\centerline{\n\\Qcircuit @C=1em @R=0.75em {\n\t\\lstick{\\ket{0}}   & \\targ & \\qw & \\qw \\\\\n\t\\lstick{\\alpha\\ket{0}+\\beta\\ket{1}} & \\ctrl{-1} & \\qw & \\rstick{\\rho' = \\Phi(\\rho)}  \n}\n}\n\n\\fill\n\n\\noindent so we see that we've introduced an extra ancillary bit and applied the CNOT gate to do the measurement, discarding the ancilla at the end.\n\n%==============================%\n\\section{Quantum Information Theory}\n%==============================%\nSo far we talked about the no-cloning theorem (1), distinguishing between two quantum states (2), entanglement (3), and the density matrix formalistm (4). An example of (2) was given in HW. 1 Problem 4. Here Alice and Bob are physically separated, each given one of the qubits of some 2-qubit state; the 2-qubit state is either State I or State II. The problem asked us to devise a strategy they could use to distinguish whether they're sharing State I or State II given that they are allowed to make only local measurements and communicate across a classical channel. An example of (3) was quantum teleportation where we showed that through entanglement, Alice can transmit a 1-qubit state to Bob.\n\n\\fill\n\n\\noindent In both classical and quantum information theory, we have three important issues that we would like to consider. These are:\n\\begin{enumerate}[start=0]\n\\item What is the information comprised of? What is its source? How do we measure the \\emph{amount} of information that's being transmitted?\n\t\\begin{itemize}\n\t\t\\item In the classical world, the source is a random variable $X$. We measure the amount of information using the Shannon entropy, $\\se(X)$.\n\t\t\n\t\t\\item In the quantum world, the source is a mixed state $\\rho$. We measure the amount of information using the Von Neumann entropy, $\\vne(\\rho)$.\n\t\\end{itemize}\n\n\\item How do we transmit information over a noiseless channel? To put another way, if we store the information on a physical device, then what is the optimal compression that's possible for storing this information source?\n\t\\begin{itemize}\n\t\t\\item Given an $m$-bit source, if we want to represent it using only $\\alpha\\bullet m$ bits where $\\alpha < 1$, then Shannon's noiseless source coding theorem says that we can only do so iff $\\alpha \\geq H(X)$\n\t\t\n\t\t\\item Given a density matrix $\\rho$ on $m$-qubits, if we want to represent it using only $\\alpha\\bullet m$ qubits where $\\alpha < 1$, then Schumacher's noiseless quantum source coding theorem says that we can only do so iff $\\alpha \\geq S(\\rho)$.\n\t\\end{itemize}\n\n\\item How do we transmit information over a noisy channel?\n\t\\begin{itemize}\n\t\t\\item We can do so using error correction codes, ECC.\n\t\t\n\t\t\\item We can do so using quantum error correction codes, QECC.\n\t\\end{itemize}\n\\end{enumerate}\n\n\\fill\n\n\\noindent Imagine that we have a classical source churning out $m$-bit binary strings that are being transmitted on a quantum channel. The information transfer can be summarized by the following steps for a given $n$-bit binary string $x$:\n\\begin{enumerate}\n\\item The classical source churns out $x$\n\n\\item Some kind of process encodes $x$ as a $\\alpha\\bullet n$ qubit quantum source $\\rho_x$, where $\\alpha \\leq 1$.\n\n\\item $\\rho_x$ is transmitted across the quantum channel.\n\n\\item $\\rho_x$ is decoded at the end to get back $x$.\n\\end{enumerate}\nThe question here is whether we can use a shorter quantum message to transmit our classical message, i.e. if we can find an $\\alpha < 1$. Unfortunately, we're stuck with $\\alpha = 1$ due to Holevo's theorem, which states that it is impossible to communicate more than $n$ bits of classical information when transmitting $n$ qubits.\n\n%==============================%\n\\section{Entropy}\n%==============================%\n\n\\subsection{Shannon Entropy}\nWe think of information as some kind of a message but, as counter-intuitive as it might be, a message may not necessarily contain any ``information''. For example, if all participating parties know the exact contents of the message that's being transmitted, then anybody who opens to read the message does not gain any new ``information'' -- they already know what to expect! So really, it is better to think of ``information'' as the \\emph{amount of uncertainty} that's present in a message. The more uncertainty we have in our message, the more ``information'' it contains. For example, an e-mailed job offer would tell you a lot of information because, in general, there are a lot of factors that determine whether you will get the job or not and hence, a lot of uncertainty on whether you will get said job.\n\n\\fill\n\n\\noindent In physics, entropy is a quantity used to capture the amount of uncertainty in a given system. Similarly, the \\emph{Shannon Entropy} quantifies the amount of uncertainty in a given piece of information -- that is why we use the term entropy. Mathematically it is defined as follows. Say we have a source that outputs a random variable $X \\in \\set{0, 1}^m$ with probability $p_x$. Then we define the Shannon Entropy $\\se(x)$ as:\n\\begin{equation} \\label{eq:def-se}\n\\se(X) = -\\sum_{x} p_x \\lg{p_x}\n\\end{equation}\nwhere we define $0\\lg{0} = 1$.\n\n\\fill\n\n\\noindent \\Example{5} Let $X \\in \\set{0, 1}$ where $p_0 = 0$ and $p_1 = 1$. Note that there is no uncertainty involved in $X$ -- we know that our source will always transmit a $1$. Thus we expect that $\\se(X) = 0$. Doing the calculation:\n\\begin{align*}\n\\se(X) \n&= -\\sum_{x} p_x \\lg{p_x} \\\\\n&= -1\\lg{1} \\\\\n&= 0 \n\\end{align*}\n\n\\fill\n\n\\noindent \\Example{6} Let $X \\in \\set{0, 1}$ where $p_0 = p_1 = 1/2$, i.e. $X$ corresponds to a fair coin. Then we see that:\n\\begin{align*}\n\\se(X) \n&= -\\sum_{x} p_x \\lg{p_x} \\\\\n&= -\\left(\n\\frac{1}{2}\\lg{\\frac{1}{2}} + \\frac{1}{2}\\lg{\\frac{1}{2}}\n\\right) \\\\\n&= -(-\\frac{1}{2} + -\\frac{1}{2}) \\\\\n&= 1\n\\end{align*}\nwhich is exactly 1-bit of information. This is the mathematical definition of a bit.\n\n\\fill\n\n\\noindent Generalizing Example 6, if we have $X \\in \\set{0, 1}^m$ and $H(X) = m$, then this corresponds to $m$ fair coins each with 1-bit of information for a total of $m$-bits of information. Note that the Shannon Entropy is non-negative, bounded by the size of %NOTE: I didn't quite hear this part in lecture, so couldn't record it.\nIt also works well in a syntactic sense in that we can take many independent and identically distributed random variables %NOTE: Didn't hear this part in lecture too, I think it was glazed over.\n\n\\subsection{Von Neumann Entropy}\nImagine that we have an $m$-qubit space $\\X$, and a source that outputs $k$ pure states with probability $p_k$ for each. Then our source is summarized by the density matrix $\\rho_x = \\sum_{i} p_i \\kera{\\psi_i}$. First, note that the quantum source subsumes the classical source as any classical source with $X \\in \\{0, 1\\}^m$ and associated probability $p_x$ is just the densitry matrix $\\rho' = \\sum_{x \\in \\set{0, 1}^m} p_x \\kera{x}$. %NOTE: In class, we had a density matrix with density matrices p1, p2, ..., pm along its diagonals as being the one that summarizes a classical source. I don't understand why this is the case. The previous sentence makes more sense to me so I included that instead. If it is incorrect, then I apologize.\nLet us try to come up with a way to describe the amount of information contained in the density matrix, i.e. its entropy. At a glance, it might seem like we could use $\\se$ defined above. Letting $\\e(\\rho_x)$ denote the entropy quantity of $\\rho_x$, we get:\n\\begin{equation*}\n\\e(\\rho_x) = -\\sum_{i} p_i \\lg{p_i}\n\\end{equation*} \nHowever this definition does not work because two different quantum sources can have the same entropy -- entropy is meant to be unique. For example, the quantum source $S_1$ that outputs $\\ket{0}$ with probability $1/2$ and $\\ket{1}$ with probability $1/2$ is certainly different than the quantum source $S_2$ that outputs $\\ket{0}$ with probability $1/2$ and $\\ket{+}$ with probability $1/2$ -- the density matrices are not the same! However the probabilities of all the possible pure states in each source are the same, so $\\e(S_1) = \\e(S_2)$. The intuition is that in the quantum world, we have different bases that we can output our information in such as the standard and Hadamard bases. Further, there is no requirement that the pure states outputted by our source be orthogonal or even form an orthonormal basis -- $S_2$ is an example of one such source. In the classical world, however, everything is in binary -- all our possible sources will output information that's the same representation, so it is enough to just examine the probabilities. But the Shannon Entropy is too limited in the quantum world because we have sources that output different kinds of pure states together.\n\n\\fill\n\n\\noindent Fortunately, there is a way we can resolve our problem and that is by using the spectral decomposition. Because $\\rho$ is positive semi-definite, it has a unique decomposition under the eigenbasis which is:\n\\begin{equation*}\n\\rho = \\sum_{i = 0}^{d-1} \\lambda_i \\kera{\\psi_i}\n\\end{equation*}\nwhere $d$ is the dimension of $\\rho$'s space, $\\lambda_i$ is an eigenvalue, and $\\ket{\\psi_i}$ is an eigenvector such that $\\rho\\ket{\\psi_i} = \\lambda_i \\ket{\\psi_i}$ and $\\bret{\\psi_i}{\\psi_j} = \\delta_{ij}$. Note that $\\lambda_i \\geq 0$. Because $\\tr(\\rho) = 1$, we see that $\\sum_{i} \\lambda_i = 1$ so the eigenvalues form a valid probability distribution. Then we define the Von-Neumann entropy $\\vne$ as:\n\\begin{equation} \\label{eq:def-vne}\n\\vne(\\rho) = -\\sum_{i = 0}^{d-1} \\lambda_i \\lg{\\lambda_i}\n\\end{equation}\n\n\\fill\n\n\\noindent \\Example{7} Consider the source summarized by $\\rho = \\kera{0}$, i.e. a source that always outputs the pure state $\\ket{0}$. We would expect that $\\vne(\\rho) = 0$ since there is no uncertainty in what state we get. This is indeed the case, as $\\vne(\\rho) = -1\\lg{1} = 0$, i.e. $\\lambda = 1$ is the only eigenvalue of $\\rho$.\n\n\\fill\n\n\\noindent \\Example{8} Consider a fair coin, i.e. the source where $\\rho = \\frac{1}{2}\\kera{0} + \\frac{1}{2}\\kera{1}$. Here, $\\vne(\\rho) = 1$ which matches the corresponding classical case. In fact, if we have a mixed state on $n$-qubits where $\\rho = \\frac{1}{2^n}I$, then $\\vne(\\rho) = n$.\n\n\\end{document}", "meta": {"hexsha": "3524de594ed70b33dff76d4329df2257ee1f9fa4", "size": 26253, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "teaching/s17_4510_qc/170516_ei_lec13.tex", "max_stars_repo_name": "fangsonghub/fangsonghub.github.io", "max_stars_repo_head_hexsha": "31a42b297a4644b307b97acd293d9111e567f5c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "teaching/s17_4510_qc/170516_ei_lec13.tex", "max_issues_repo_name": "fangsonghub/fangsonghub.github.io", "max_issues_repo_head_hexsha": "31a42b297a4644b307b97acd293d9111e567f5c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-05-06T23:19:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-06T23:19:12.000Z", "max_forks_repo_path": "teaching/s17_4510_qc/170516_ei_lec13.tex", "max_forks_repo_name": "fangsonghub/fangsonghub.github.io", "max_forks_repo_head_hexsha": "31a42b297a4644b307b97acd293d9111e567f5c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 64.6625615764, "max_line_length": 1190, "alphanum_fraction": 0.6931017408, "num_tokens": 8255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.34839763850849137}}
{"text": "%\n% vecmat3.tex - LaTeX documentation source for vecmat3.h version 2.3.1: \n%               Fast 3d vector and matrix classes using expression templates\n%\n% Copyright (c) 2007-2013  Ramses van Zon\n%\n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, including without limitation the rights\n% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n% copies of the Software, and to permit persons to whom the Software is\n% furnished to do so, subject to the following conditions:\n%\n% The above copyright notice and this permission notice shall be included in\n% all copies or substantial portions of the Software.\n%\n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n% THE SOFTWARE.\n%\n\n\\documentclass[12pt,twoside]{article}\n\n\\usepackage{a4wide,fancyhdr,mathptm,charter,color}\n%\\usepackage[colorlinks]{hyperref}\n\n\\pagestyle{fancy}\n\\renewcommand{\\sectionmark}[1]{\\markright{#1}}\n\\fancyhf{}\n\\fancyhead[LE,RO]{\\bfseries\\thepage}\n\\fancyhead[LO]{\\bfseries \\hfill\\rightmark\\hfill}\n\\fancyhead[RE]{\\hfill\\bfseries\\rightmark \\hfill}\n\\fancyfoot[L]{\\textit{vecmat3} v2.3.1}\n\\fancyfoot[R]{\\hfill{\\color{white}.}\\hfill Ramses van Zon\\hfill May 15, 2013}\n\\renewcommand{\\headrulewidth}{0.5pt}\n\\renewcommand{\\footrulewidth}{0pt}\n\\addtolength{\\headheight}{2.5pt}\n\\fancypagestyle{plain}{\\fancyhead{}\\renewcommand{\\headrulewidth}{0pt}}\n\n\n\\newcommand{\\Vector}{{Vector}}\n\\newcommand{\\Matrix}{{Matrix}}\n\\newcommand{\\cxx}{C\\texttt{++}}\n\\newcommand{\\TT}{{\\tt<}T{\\tt>}}\n\n\\begin{document}\n\n\\setlength{\\parskip}{1mm}\n\n\\title{User Documentation for the  \\emph{vecmat3}\\\\\\Vector\\ and\n  \\Matrix\\ classes\\\\(version 2.3.1)}\n\n\\author{Ramses van Zon\\footnote{vanzonr@gmail.com}}\n\n\\date{May 15, 2013}\n\n\\maketitle\n\\begin{abstract}\nThis document describes how to use the \\cxx\\ \\Vector\\ and\n\\Matrix\\ classes defined in the header file vecmat3.h. These classes\noffer a very convenient notation for three dimensional vector and\nmatrix algebra by using overloaded operators.  Furthermore, they are\nconstructed to be numerically efficient through the internal use of\nexpression templates, without interfering at the user level.  As a\nresult, one can convert mathematical matrix-vector expressions\nstraightforwardly into the corresponding \\cxx\\ expression without\nhaving to worry about incurring an efficiency penalty.\n\\end{abstract}\n\n\\newpage\n\n\\renewcommand{\\contentsname}{\\vspace{-13mm}}\\markright{Contents}\n\\tableofcontents\n\n\\newpage\n\n\\section{Introduction}\nVectors and matrices are used frequently in scientific computation (as\nwell as in modeling, games and movie rendering).  Unfortunately, no\nbuilt-in support for matrices and vectors exists in \\cxx.  In\nprinciple, expressions involving matrices and vectors, such as\n\\[\n\\vec a=\\vec b+\\mathsf M \\cdot \\vec c\n\\]\n(with $\\vec a$, $\\vec b$ and $\\vec c$ vectors and $\\mathsf M$ a\nmatrix) can be implemented in \\cxx\\\nsuch that they strongly resemble their mathematical notations, e.g.\n\\begin{quote}\n\\tt\nVector a,b;\n\nMatrix M;\n\nVector c = a + M*b;\n\\end{quote}\nThe technique used to accomplish such notational convenience is\noperator overloading, whose straightforward implementation comes with\na high computational cost due to the creation of temporary\nobjects.\n\nA more efficient implementation is possible by using \\emph{expression\ntemplates}.  Efficient matrix-vector implementations are somewhat of a\nby-product of \\cxx\\ templates, and this shows in the awkward and\ncomplicated notation needed for general matrix-vector\nmanipulations. In addition, the \\cxx\\ standard is somewhat quirky on\nwhat is and is not allowed when using templates.\n\nThese notational issues probably explain why there are far fewer\ntemplate-based implementations of matrices and vectors available.\nThis is especially problematic for small vectors and matrices of fixed\nsize, for instance three-dimensional ones. These allow additional\nefficiency gains over general-size vectors and matrices (because loops\nover indices can be replaced by explicit sums in the implementation).\nTwo known implementations are the \\texttt{TinyVector} and \\texttt{\nTinyMatrix} classes of \\texttt{Blitz++} and the ones by the same name of\n\\texttt{tvmet}. The former is not very developed, i.e., many operations\nthat one would like to have are not present, and indeed, the latter is\naimed at fixing that. Still, \\texttt{tvmet} lacks some functionality that\nbuilt-in types do have, for instance, \\texttt{TinyVector<3,double> v =\na+b;} is not possible.\n\nThis is where \\emph{vecmat3} comes in. It defines very efficient\nthree dimensional vector and matrix manipulations.  The aim is to be\nable to use these vectors and matrices as if they were built-in types,\nwith which the same kind of expressions can be formed as can with\nbuilt-in types without worrying about template techniques, but also without\nsubstantial losses compared to hard-coded element-by-element\ntechniques.\n\n\\emph{vecmat3} uses expression templates and operator\noverloading. The restrictions of vecmat3 at present are that the\nelements of the vectors and matrices have to be of a single type,\nwhich is \\texttt{double} by default, and that only three-dimensional\nquantities are supported (as the name suggests).\n\n\\section*{Change history}\n\\subsection*{Changes in version 2}\n\nThe main difference between the first version of vecmat3 and the\nsecond is that the matrices and vectors no longer need to be all of\none type in a single application.  In addition to the standard Vector\nand Matrix classes of type \\texttt{DOUBLE} (which defaults to double)\nas in version 1, in version 2 one also has three-dimensional\nstructures of any type \\texttt{T} at one's disposal. To be more\nprecise:\n\\begin{itemize}\n\\item \\texttt{vecmat3::Vector\\TT{}} and \\texttt{vecmat3::Matrix\\TT{}} are\n  three-dimensional vector and matrix classes whose elements are of\n  type \\texttt{T}. \n\n  For example, one can define a 3x3 matrix of integers as\\ \\ \n  \\texttt{vecmat3::Matrix<int>~m;}\n\\item This notation reflects two changes in the code: \n\\begin{itemize}\n\\item Almost all of the \\texttt{vecmat3} code is now contained in its own\n  namespace called \\texttt{vecmat3}. \n\\item The type is a template argument.\n\\end{itemize}\n\\item In version 2 the standard Vector and Matrix classes are simply\n  typedef'ed as equivalent to \\texttt{vecmat3::Vector<DOUBLE>} and\n  \\texttt{vecmat3::Vector<DOUBLE>}, whereas in version 1 they were the\n  only vectors and matrices available.\n\\item The typedef's of Vector and Matrix will be omitted if the\n  compiler flag \\texttt{NOVECMAT3DEF} is defined.\n\\end{itemize}\n\n\\subsection*{Changes between version 2 and version 2.3}\n\n(Versions 2.1 and 2.2 were internal development stages.)\n\n\\begin{itemize}\n\\item Most functionality remained the same as in version 2, except that square bracket support has been added. See Section \\ref{bracketsnowtoo}.\n\n\\item The header file now also enforces inlining the template functions for\nthe GNU (tested version 4.4.0) and the Intel compilers (tested\nversions 11 and 12), even when no optimization is used.  \n\n\\item A major improvement of version 2.3 is that the library is now\ncompatible with IBM's xlC compiler, which had trouble with some\ntemplate constructions in versions 1 and 2. While I'm on the\nsubject, one should compile with \\texttt{-O4} when using the IBM\ncompilers with vecmat3 in order to get all inlining done properly (in\nthe latest version, xlC 11, the options \\texttt{-O2 -qinline=level=6} suffice).\n\\end{itemize}\n\n\\subsection*{Changes between version 2.3 and version 2.3.1}\n\nVersion 2.3.1 comes with an open-source license (MIT). Here is the\ntext of the license:\n\\begin{verbatim}\nCopyright (c) 2007-2013 Ramses van Zon\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\\end{verbatim}\n\n\\section{Installation}\n\nTo use this header-only library, one merely needs to copy the header\nfile vecmat3.h to the directory of the source files that include it,\nor to a default directory where the compiler will look for header\nfiles (e.g. /usr/local/include).\n\nThe \\emph{vecmat3} library has been tested with the GNU g++ compiler version\n4.4 and up, the Intel C++ compiler version 11 and up and IBM's XL C++\ncompiler version 10 and up.\n\n\n\\section{Using the \\Vector\\ and \\Matrix\\ classes}\n\\label{use}\n\n\\subsection{Classes}\n\n\\emph{vecmat3} provides two general template classes within the\nnamespace \\texttt{vecmat3}:\n\n\\begin{quote}\\tt\n  template<typename T> vecmat3::Vector;\n\n  template<typename T> vecmat3::Matrix;\n\\end{quote}\nThe template parameter T determines the type of the vector and\nmatrix elements. Thus, for a vector of integers one uses the type\n\\texttt{vecmat3::Vector<int>}, while for a matrix of doubles one would\nuse \\texttt{vecmat3::Matrix<double>}.\n\nSince applications often need only one type of vector, a default\nvector type a and default matrix type are defined outside the\n\\texttt{vecmat3} namespace, as follows\n\\begin{quote}\\tt\n\ntypedef vecmat3::Vector<DOUBLE> Vector;\n\ntypedef vecmat3::Matrix<DOUBLE> Matrix;\n\\end{quote}\nHere, DOUBLE is a predefined macro that should contain the type of the\nelements of the default vectors and matrices. Thus, \\texttt{Vector v;}\ndefines a vector with elements of type DOUBLE.\n\nThe type DOUBLE can be defined in three ways: \n\\begin{enumerate}\n\\item One can write an\n\\texttt{\\#define DOUBLE <something>} before including the\n\\texttt{vecmat3.h} header, with \\texttt{<something>} replaced by the\ndesired type (e.g.\\ \\texttt{float} or \\texttt{double});\n\\item One can give a command line argument to the compiler to define\n  DOUBLE to be \\texttt{<something>} (e.g.\\ \\texttt{-DDOUBLE=float} for\n  g++);\n\\item One can do nothing, which makes \\texttt{DOUBLE} default to\n\\texttt{double}.\n\\end{enumerate}\n\nThe definition of DOUBLE and the type definition of Vector and Matrix\nin the global namespace does pollute the global namespace, and in many\ncases is not wanted. These definitions are omitted if \\texttt{NOVECMAT3DEF} is defined.\n\n\\subsection{Header file}\n\nTo use \\emph{vecmat3}, the following general procedure should be\nfollowed: \n\n\\begin{itemize}\n  \\item If the elements of the vectors and matrices are to have a\n  different type than \\texttt{double}, first \\texttt{\\#define} their type as\n  \\texttt{DOUBLE}, e.g.\n  \\begin{quote}\n    \\tt \\#define DOUBLE float\n  \\end{quote}\n  The type of the elements of a vector or matrix will be referred to\n  as the ``value type'' in this documentation.\n  \\item Include the header file vecmat3.h:\n  \\begin{quote}\n    \\tt \\#include \"vecmat3.h\"\n  \\end{quote}\n\n  \\item The class \\Vector\\ and the class \\Matrix\\ are now\n  defined and instances these classes can be declared as follows:\n    \\begin{quote}\\tt\n      Vector a;\n\n      Matrix R;\n    \\end{quote}\n    \\item One can explicitly use any other value type\n      than DOUBLE type, e.g.\n    \\begin{quote}\\tt\n      vecmat3::Vector<int> a;\n\n      vecmat3::Matrix<int> R;\n    \\end{quote}\n    If vectors and matrices of a specific value type are used a lot in an\n    application, it may be useful to typedef them to a shorter\n    notation, e.g.\n    \\begin{quote}\\tt\n      typedef vecmat3::Vector<int> intVector;\n\n      typedef vecmat3::Matrix<int> intMatrix;\n\n      intVector b;\n\n      intMatrix S;\n    \\end{quote}\n  \\item Alternatively, one can have no default global \\Vector\\ and \\Matrix\\ class defined, and use only the namespace vecmat3, e.g.\n    \\begin{quote}\\tt\n      \\#define NOVECMAT3DEF\n\n      \\#include \"vecmat3.h\"      \n\n      vecmat3::Vector<double> a;\n\n      vecmat3::Matrix<double> R;\n    \\end{quote}\n\n      \\item In the above examples, the elements of the vectors and\n        matrices are unspecified, and likely contain garbage. In the\n        next section, it will be explained how to initialize these\n        elements of these\n        classes.\n    \\item Note that currently, operations between matrices and vectors\n      of different value types are not supported, even when mathematically\n      this would make sense (such as for \\texttt{int} and\n      \\texttt{double}). \n      \\item However, it is possible to assign any kind of number to an\n        element of any value type, as long as a (standard)\n        conversion to that type is known to the c++ compiler.  Thus,\n        one may, for instance, assign an integer to an element of a\n        vector, or one may multiply a vector by 2 (i.e., one may write\n        \\texttt{2*v} instead of being\n        forced to write \\texttt{2.0*v} or \\texttt{2.0f*v}).\n\\end{itemize}\n\n\n\\subsection{Initialization methods}\n\nThere are four ways to initialize a \\Vector\\ or \\Matrix, which we will\ndiscuss by example.  In describing the initialization methods, the\ndefault Vector and Matrix types will be used; the arbitrary type\nversions \\texttt{vecmat3::Vector\\TT{}} and\n\\texttt{vecmat3::Matrix\\TT{}} have the same functionality.\n\n\\subsubsection{Initialization through constructor parameters}\n  Example:\n    \\begin{quote}\\tt\n         Vector a(1.1, 3.0, -4.3);\n\n         Matrix R(1, 2, 3,\n \n\\ \\ \\ \\ \\ \\ \\ \\ \\ 4, 5, 6,\n\n\\ \\ \\ \\ \\ \\ \\ \\ \\ 7, 8, 9);\n    \\end{quote}\n    defines a \\Vector\\ \\texttt a and \\Matrix\\ \\texttt R with specified\n    elements. Note that the first set of three elements given to\n    \\texttt R comprise the top row of \\texttt R, the second set of\n    three the middle row and the last set of three the bottom row.\n\n    If fewer than three or nine (for \\Vector\\ and \\Matrix,\n    respectively) number are given, the unspecified elements are set\n    to zero. Thus, one can define a zero \\Vector\\ and \\Matrix\\ simply by\n    \\begin{quote}\\tt\n         Vector a(0);\n\n         Matrix R(0);\n    \\end{quote}\n\n  \\subsubsection{Initialization through assignment}\n  Example:\n    \\begin{quote}\\tt\n         Vector b = a;\n\n         Matrix S = R;\n    \\end{quote}\n    defines a \\Vector\\ \\texttt b with the same elements as \\texttt a,\n    and a \\Matrix\\ \\texttt S with the elements~as~\\texttt R. \n\n    The right hand sides may also be an expression involving \\Vector's\n    and Matrices. The allowed expressions are explained in\n    sections \\ref{operations} and \\ref{expressions}.\n%\\newpage\n  \\subsubsection{Initialization through a comma separated list}\n  Example:\n    \\begin{quote}  \\tt\n         Vector a;\n\n\t a = 1.1, 3.0, -4.3;\n\n         Matrix R;\n\n\t R = 1, 2, 3, \n\n     \\ \\ \\ \\ 4, 5, 6, \n\n     \\ \\ \\ \\ 7, 8, 9;\n    \\end{quote}  \n    Note: this is the standard construction for \\texttt{Blitz++} and\n    \\texttt{tvmet}, and is achieved though an overloaded comma\n    operator. Not everybody likes overloading the comma operator,\n    because it may confuse the user (more than the above methods), and\n    it is somewhat less efficient than the method in 3.2.1.\n\n    Furthermore, it is  not possible to use this method in\n    the declaration, i.e., one cannot write \\texttt{Vector\n    a=1.1,3.0,-4.3;} since \\cxx\\ would consider this a\n    declaration of 3.0 and -4.3 as being of type \\Vector.\n    \n    If not enough elements are given in the list, the remaining\n    elements are set to zero. Thus, one can write\n    \\begin{quote}\\tt\n         b = 1;\n    \\end{quote}\n    to get the vector (1,0,0), and \n    \\begin{quote}\\tt\n         R = 2;\n    \\end{quote}\n    to get the matrix $\\left(\\begin{array}{ccc}2&0&0\\\\0&0&0\\\\0&0&0\\end{array}\\right)$.\n\n  \\subsubsection{Initialization through member functions}\n  Example:\n    \\begin{quote}\\tt\n         Vector a;\n\n\t a.zero();\n\n         Matrix R;\n\n\t R.zero();\n    \\end{quote}\n    also define a \\Vector\\ and \\Matrix, respectively, with zero\n    elements.\n    \n\\noindent\n    For a \\Matrix, there also is a member function {\\tt one()} to turn\n    it into an identity matrix:\n    \\begin{quote}\\tt\n         Matrix S;\n\n\t S.one();\n    \\end{quote}\n    Furthermore, one can initialize a \\Matrix\\ also per row or column, e.g.\n    \\begin{quote}\\tt\n      R.setRow(0,a);\n\n      R.setRow(1,Vector(0,2,0));\n\n      R.setRow(2,Vector(0,2,-1));\n\n      S.setColumn(0,a);\n\n      S.setColumn(1,Vector(0,2,0));\n\n      S.setColumn(2,Vector(0,2,-1));\n    \\end{quote}  \n    Note that rows and columns are numbered from 0 to 2.\n\n\n \\subsubsection{Arrays}\n     Example:\n    \\begin{quote}\\tt\n         Vector a[3];\n\n         Matrix S[3];\n    \\end{quote}\n    Defines arrays of three Vectors and Matrices which are\n    non-initialized. One can initialize these arrays as follows\n    \\begin{quote}\\tt\n         Vector a[3] = \\{ Vector(1,2,3), Vector(3,4,5), Vector(5,6,7) \\};\n\n         Matrix S[3] = \\{ Matrix(0), Matrix(1,2,3,4,5,6,7,8,9), Matrix(2) \\} ;\n    \\end{quote}\n\n\\subsection{Accessing the elements}\n\\label{bracketsnowtoo}\n\nThere are three ways to assess the elements of Vectors and Matrices:\n\n\\begin{enumerate}\n\n\\item Basic elements of Vectors and Matrices are generally accessible using the\nparenthesis notation, i.e., the elements of a  \\Vector\\ \\texttt a are\n\\texttt{a(0)}, \\texttt{a(1)} and \\texttt{a(2)}, while those of a\n\\Matrix\\ \\texttt R are \\texttt{R(0,0)}, \\texttt{R(0,1)}, \\dots\n\\texttt{R(2,2)}.\n\n\\item Bracket notation can also be used, \n i.e., the elements of a  \\Vector\\ \\texttt a are\n\\texttt{a[0]}, \\texttt{a[1]} and \\texttt{a[2]}, while those of a\n\\Matrix\\ \\texttt R are \\texttt{R[0][0]}, \\texttt{R[0][1]}, \\dots\n\\texttt{R[2][2]}. Note the double brackets for matrix element access.\nThis way, Vector and Matrix objects act as if they are of type \\texttt{T[3]} and \\texttt{T[3][3]}, respectively. Accessing the matrix elements in this way may be moderately slower than the parenthesis method (depending on the compiler).\n\n\\item Another way to access the elements is though the class members\nthemselves, i.e., \\texttt x, \\texttt y and \\texttt z for \\Vector, and\n\\texttt{xx}, \\texttt{xy}, \\texttt{xz}, \\texttt{yx}, \\texttt{yy},\n\\texttt{yz}, \\texttt{zx}, \\texttt{zy} and \\texttt{zz} for Matrix. This is\npotentially  more efficient, but cannot be used for expressions, i.e.,\n\\texttt{(A+B).xx} is not possible, unless one writes \\texttt{Matrix(A+B).xx}.\n\\end{enumerate}\nFurthermore, the rows and columns of a Matrix can be used as if they\nwere vectors as follows\n\\begin{quote}\\tt\n  Vector v = R.row(1);\n\n  Vector w = R.column(2);\n\\end{quote}\n\n\n\\subsection{Operators}\n\\label{operations}\n\n\nThe available algebraic operators for the Vector and Matrix classes\nare summarized in table 1, in which '\\Vector\\TT' stands for\n'\\texttt{const Vector\\TT\\&}' or a \\Vector-valued expression, and '\\Matrix\\TT'\nstands for '\\texttt{const Matrix\\TT\\&}' or a Matrix\\TT-valued expression.\n\nIn addition, \\texttt{<<} operators are defined for output of Vectors\nand Matrices to \\texttt{ostream}s, such that\n\\begin{quote}\\tt\n  Vector a(1,2,3);\n\n  std::cout << a << endl;\n\\end{quote}\nwould print the numbers 1, 2 and 3 with just a space in between.\n\\begin{quote}\\tt\n  Matrix<T> M(1,2,3,4,5,6,7,8,9);\n\n  std::cout << M << endl;\n\\end{quote}\nwould print a newline, the numbers 1, 2 and 3, another newline, the\nnumbers 4, 5 and 6, another newline, the numbers 7, 8 and 9 and\nfinally another newline.\n\n\\begin{table}[t]\\small\n\\begin{center}\n\\begin{tabular}{|rcl|c|c|rcl|}\n\\hline\n \\multicolumn{3}{|c|}{\\bf form} & \\bf description & \\bf example & \\multicolumn{3}{c|}{\\bf mathematically}\\\\\\hline\\hline\n%\n&\\texttt{\\textcolor{red}-}\n&\\texttt{Vector<T>}  \n& negative \n& \\tt c = -a; \n& $\\quad \\vec c$&=&$-\\vec a$\\\\\n%\n\\texttt{Vector<T>}\n&\\textcolor{red}{\\texttt +}\n&\\texttt{Vector<T>} \n& add \n& \\tt c = a + b; \n& $\\quad \\vec c$&=&$\\vec a +\\vec b$\\\\\n%\n\\texttt{Vector<T>}\n&\\textcolor{red}{\\texttt -}\n&\\texttt{Vector<T>} \n& subtract\n& \\tt c = a - b;\n& $\\quad \\vec c$&=&$\\vec a -\\vec b$\\\\\n%\n\\texttt{T}\n&\\textcolor{red}{\\texttt *}\n&\\texttt{Vector<T>} \n& multiply with scalar \n& \\tt c = d * a; \n& $\\quad \\vec c$&=&$d\\,\\vec a$\\\\\n%\n\\texttt{Vector<T>}\n&\\textcolor{red}{\\texttt *} \n&\\texttt{T} \n& multiply with scalar \n& \\tt c = a * d; \n& $\\quad \\vec c$&=&$\\vec a\\, d$\\\\\n%\n\\texttt{Vector<T>}\n&\\textcolor{red}{\\texttt /}\n&\\texttt{T} \n& divide by scalar \n& \\tt c = a / d; \n& $\\quad \\vec c$&=&$\\vec a / d$\\\\\n%\n\\texttt{Vector<T>} \n&\\textcolor{red}{\\texttt \\^{}} \n&\\texttt{Vector<T>} \n& cross/outer product$^\\dagger$\n& \\tt c = a \\^{} b; \n& $\\quad \\vec c$&=&$\\vec a \\times \\vec b$\\\\\n%\n\\texttt{Vector<T>}\n&\\textcolor{red}{\\texttt *}\n&\\texttt{Vector<T>} \n& dot/inner product$^\\ddagger$\n& \\tt d = a * b; \n& $\\quad d$&=&$\\vec a \\cdot \\vec b$\\\\\n%\n\\ \\textcolor{red}( \\texttt{Vector<T>} \n&\\textcolor{red}{\\texttt |}\n& \\texttt{Vector<T>} \\textcolor{red})\n& dot/inner product$^\\ddagger$\n& \\tt d = (a|b); \n& $\\quad d$&=&$\\vec a \\cdot \\vec b$\\\\\n%\n\\hline\n%\n&\\texttt{\\textcolor{red}-}\n&\\texttt{Matrix<T>}  \n& negative \n& \\tt T = -S; \n& $\\quad \\mathsf T$&=&$-\\mathsf S$\\\\\n%\n\\texttt{Matrix<T>}\n&\\textcolor{red}{\\texttt +}\n&\\texttt{Matrix<T>} \n& add \n& \\tt T = S + R; \n& $\\quad \\mathsf T$&=&$\\mathsf S +\\mathsf R$\\\\\n%\n\\texttt{Matrix<T>}\n&\\textcolor{red}{\\texttt -}\n&\\texttt{Matrix<T>} \n& subtract\n& \\tt T = S - R;\n& $\\quad \\mathsf T$&=&$\\mathsf S -\\mathsf R$\\\\\n%\n\\texttt{T}\n&\\textcolor{red}{\\texttt *}\n&\\texttt{Matrix<T>} \n& multiply with scalar \n& \\tt T = d * S; \n& $\\quad \\mathsf T$&=&$d\\,\\mathsf S$\\\\\n%\n\\texttt{Matrix<T>} \n&\\textcolor{red}{\\texttt *} \n&\\texttt{T} \n& multiply with scalar \n& \\tt T = S * d; \n& $\\quad \\mathsf T$&=&$\\mathsf S\\, d$\\\\\n%\n\\texttt{Matrix<T>} \n&\\textcolor{red}{\\texttt /} \n&\\texttt{T} \n& divide by scalar \n& \\tt T = S / d; \n& $\\quad \\mathsf T$&=&$\\mathsf S / d$\\\\\n%\n\\texttt{Matrix<T>}\n&\\textcolor{red}{\\texttt *}\n&\\texttt{Matrix<T>} \n& matrix-matrix product\n& \\tt T = S * R; \n& $\\quad \\mathsf T$&=&$\\mathsf S\\,\\mathsf R$\\\\\n%\n\\texttt{Matrix<T>}\n&\\textcolor{red}{\\texttt *} \n&\\texttt{Vector<T>} \n& matrix-vector product\n& \\tt c = S * a; \n& $\\quad \\vec c$&=&$\\mathsf S \\, \\vec a$\\\\\n%\n\\hline\n%\n\\texttt{Vector<T>}\n&\\textcolor{red}{\\texttt{+=}}\n&\\texttt{Vector<T>} \n& add \n& \\tt c += b; \n& $\\quad \\vec c$&=&$\\vec c +\\vec b$\\\\\n%\n \\texttt{Vector<T>}\n&\\texttt{\\textcolor{red}{-=}}\n&\\texttt{Vector<T>} \n& subtract \n& \\tt c -= b; \n& $\\quad \\vec c$&=&$\\vec c -\\vec b$\\\\\n%\n\\texttt{Vector<T>}\n&\\texttt{\\textcolor{red}{*=}}\n&\\texttt{T} \n& multiply by scalar\n& \\tt c *= d; \n& $\\quad \\vec c$&=&$d\\,\\vec c$\\\\\n%\n\\texttt{Vector<T>}\n&\\texttt{\\textcolor{red}{/=}}\n&\\texttt{T} \n& divide by scalar\n& \\tt c /= d; \n& $\\quad \\vec c$&=&$\\vec c/d$\\\\\n%\n\\texttt{Matrix<T>}\n&\\texttt{\\textcolor{red}{+=}}\n&\\texttt{ Matrix<T>} \n& add \n& \\tt T += R; \n& $\\quad \\mathsf T$&=&$\\mathsf T +\\mathsf R$\\\\\n%\n \\texttt{Matrix<T>}\n&\\texttt{\\textcolor{red}{-=}}\n&\\texttt{ Matrix<T>} \n& subtract \n& \\tt T -= R; \n& $\\quad \\mathsf T$&=&$\\mathsf T -\\mathsf R$\\\\\n%\n\\texttt{Matrix<T>}&\n\\texttt{\\textcolor{red}{*=}}\n&\\texttt{T} \n& multiply by scalar\n& \\tt T *= d; \n& $\\quad \\mathsf T$&=&$d\\,\\mathsf T$\\\\\n%\n \\texttt{Matrix<T>}\n&\\texttt{\\textcolor{red}{/=}}\n&\\texttt{T} \n& divide by scalar\n& \\tt T /= d; \n& $\\quad \\mathsf T$&=&$\\mathsf T/d$\\\\\n\\hline\n\\multicolumn{6}{l}{\n$^\\dagger$ The \\texttt \\^{} operator has rather low precedence, so\noften one has to write \\texttt{(a\\^{}b)}.\n}\\\\\\multicolumn{6}{l}{\n$^\\ddagger$ Two operators are provided for the dot product, which do\nthe exact same thing. \n}\n\\end{tabular}\n\\end{center}\n\\caption{Operators available for matrices and\n  vectors with elements of type \\texttt{T}. }\n\\end{table}\n\n\n\n\\subsection{Member functions}\n\nFor any \\Vector, or \\Vector-valued expression, or for any \\Matrix, or\n\\Matrix-valued expression, the following properties are available as\nmember functions. Note that below, {\\tt T} stands for the typename of the template, while {\\tt Vector\\TT{}} and {\\tt Matrix\\TT{}} stand for {\\tt vecmat3::Vector\\TT{}} and {\\tt vecmat3::Matrix\\TT{}}, respectively.  The examples all use {\\tt T=DOUBLE}.\n\n\\subsubsection{T nrm2()}\n\nThis returns the sum of the squares of the elements, which is its norm\nsquared. E.g., with {\\tt T=DOUBLE},\n\\begin{quote} \\tt\n  Vector a(1,2,3.316625);\n\n  Matrix R(1,2,0,\n\n\\ \\ \\ \\ \\ \\ \\ \\ \\ 2,0,2\n\t   \n\\ \\ \\ \\ \\ \\ \\ \\\t\\ 1,1,1);\n\n  DOUBLE d1 = a.nrm2(); // will be equal to 16.0000014\n\n  DOUBLE d2 = R.nrm2(); // will be equal to 16\n\\end{quote}\n\n\\subsubsection{T nrm()}\n\nThis returns the norm of a \\Vector\\ or \\Matrix, e.g., with {\\tt T=DOUBLE},\n\\begin{quote} \\tt\n  DOUBLE d3 = a.nrm(); // will be equal to 4.00000017\n\n  DOUBLE d4 = R.nrm(); // will be equal to 4\n\\end{quote}\n\n\\noindent\nThe following properties are for Matrices only:\n\n\\subsubsection{T tr()}\n\nThis returns the trace of a \\Matrix, i.e., the sum of its diagonal\nelements. E.g., with {\\tt T=DOUBLE},\n\\begin{quote} \\tt\n  DOUBLE d5 = R.tr(); // will be equal to 2\n\\end{quote}\n\n\\subsubsection{T det()}\n\nThis returns the determinant of a \\Matrix, e.g., with {\\tt T=DOUBLE},\n\\begin{quote} \\tt\n  DOUBLE d6 = R.det(); // will be equal to -2\n\\end{quote}\n\n\\subsubsection{Vector\\TT{} row(int i)}\nThis returns the ith row of a \\Matrix.\n\n\\subsubsection{Vector\\TT{} column(int j)}\n\nThis returns the jth column of a \\Matrix.\n\n\\pagebreak[3]\n\\subsection{Non-member functions}\n\nIn the definition of the following non-member functions, the specified\nreturn type are effective ones. E.g. a return type of Matrix may\nreturn a Matrix-Expression when this is more efficient. In any case, it\ncan be treated as a Matrix in virtually all ways. Likewise, if an\nargument is of Matrix type, a Matrix expression is also allowed.\n\n\\subsubsection{Matrix\\TT{} Transpose(const Matrix\\TT{} \\& M)}\n\nReturns the transpose of the argument, which is a \\Matrix, e.g.\n\\begin{quote}\\tt\n  Matrix S = Transpose(R);\n\\end{quote}\n\n\\subsubsection{Matrix\\TT{} Inverse(const Matrix\\TT{} \\& M)}\n\nReturns the inverse of the argument, which is a \\Matrix, e.g.\n\\begin{quote}\\tt\n  Matrix S = Inverse(R);\n\\end{quote}\n\n\\subsubsection{Matrix\\TT{} Rodrigues(const Vector\\TT{} \\& v)}\n\nReturns the \\Matrix-valued rotation matrix for a rotation along the\naxis given by the direction of the \\Vector\\ argument, with the angle\nequal to the norm of that \\Vector, e.g.\n\\begin{quote}\\tt\n  Matrix S = Rodrigues(a);\n\\end{quote}\n\n\n\\subsubsection{Matrix\\TT{} Dyadic(const Vector\\TT{} \\& a, const Vector\\TT{} \\& b)}\n\nReturns the \\Matrix-valued dyadic product of two arguments which are\n\\Vector s, e.g.\n\\begin{quote}\\tt\n  Matrix S = Dyadic(a,b);\n\\end{quote}\n\n\n\\subsubsection{Vector\\TT{} MTVmult(const Matrix\\TT{} \\& M, const Vector\\TT{} \\& v)}\n\nThis simply returns Transpose(Matrix)*Vector. \n\n\\subsubsection{T dist(const Vector\\TT{} \\& a, const Vector\\TT{} \\& b)}\n\nReturns the length of the difference vector between a and b. This is a\nremnant of earlier versions of the \\Vector and \\Matrix classes, and\nbarely if at all more efficient than \\texttt{(a-b).nrm()}.\n\n\\subsubsection{T dist2(const Vector\\TT{} \\& a, const Vector\\TT{} \\& b)}\n\nReturns the square length of the difference vector between a and\nb. This is a remnant of earlier versions of the Vector and Matrix\nclasses, and barely if at all more efficient than \\texttt{(a-b).nrm2()}.  \n\n\\subsubsection{T distwithshift(const Vector\\TT{}\\&a,const Vector\\TT{}\\&b,const Vector\\TT{}\\&s)}\n\nReturns the length of the difference vector between a and b shifted by\ns. This is a remnant of earlier versions of the vector and Matrix\nclasses, and barely if at all more efficient than \\texttt{(a+s-b).nrm()}.\n\n\n\\vspace{1cm}\\pagebreak[3]\nFinally, because the notation \\texttt{a*b} and \\texttt{a\\^{}b} for dot and\ncross product may be confusing, the following equivalent alternatives\nare defined:\n\\nopagebreak\n\\subsubsection{T dotProduct(const Vector\\TT{} \\& a, const Vector\\TT{} \\& b)}\n\nReturns the DOUBLE which is the dot, or inner, product of the two\n\\Vector\\ arguments.  It is by definition equal to\n\\texttt{(\\texttt{Vector}|\\texttt{Vector})}.\nExample, with {\\tt T=DOUBLE}:\n\\begin{quote}\\tt\n  DOUBLE d = dotProduct(a,b);\n\\end{quote}\n\n\\subsubsection{Vector\\TT{} crossProduct(const Vector\\TT{} \\& a, const Vector\\TT{} \\& b)}\n\nReturns the \\Vector\\ which is the cross, or outer, product of the two\n\\Vector\\ arguments.  It is by definition equal to\n\\texttt{(\\texttt{Vector}\\^{}\\texttt{Vector})}.\nExample:\n\\begin{quote}\\tt\n  Vector c = crossProduct(a,b);\n\\end{quote}\n\n\n\\section{Expressions}\n\\label{expressions}\n\nUsing the above elementary operations and functions, complex\nexpressions can be constructed just as for built-in type such as\n\\texttt{double}. To be more specific, for all operator expressions in table 1\non page 8, the arguments can be expressions themselves.\n\nFor example, one can write,\n\\begin{quote}\\tt\n  Vector r[2] = \\{ Vector(1,4,5), Vector(2,3,4) \\};\n\n  Vector v[2] = \\{ Vector(1,0,0), Vector(-1,0,0) \\};\n\n  Vector s(7,1,0);\n\n  Matrix A(1,0,0,0,1,0,0,-1,0);\n\n  DOUBLE t =  (r[0]+2*A*(s\\^{}r[1]) ) | (v[1]-v[0]);\n\n  // alternatively:\n\n  //DOUBLE t =  dotProduct(r[0]+2*A*crossProduct(s,r[1]), v[1]-v[0]);\n\\end{quote}\n\nInternally, the expressions are not computed directly via temporaries,\nbut are computed only upon assignment. As a result, the definitions of\nthese operators and functions in vecmat3.h is not as simple as\ne.g. \\texttt{Vector operator+(Vector\\&,Vector\\&)}.  For that reason,\nabove we used \\texttt{Vector} and \\texttt{Matrix} wherever a\n\\Vector/\\Matrix\\ or a \\Vector/\\Matrix\\ expression can occur. Never\nmind the implementation though, things work as expected.\n\n\\newpage\n\\renewcommand{\\refname}{Background references}\n\\begin{thebibliography}{9}\n\\bibitem{Lippmann}  \nT. Veldhuizen, \\emph{Expression Templates} C++ Report, Vol. 7 No. 5 June\n1995, pp. 26-31. See also\nhttp://ubiety.uwaterloo.ca/\\~{}tveldhui/papers/Expression-Templates/exprtmpl.html.\\\\\nReprinted in:\nS. B. Lippmann (ed.) \\emph{C++ Gems} (Cambridge\n  University Press, 1998).\n\\bibitem{VandevoordeJosuttis} D.\\ Vandevoorde and N.\\ M.\\ Josuttis,\n  \\emph{C++ Templates: The Complete Guide} (Addison-Wesley, Boston,\n  2002).\n\\bibitem{blitz} http://www.oonumerics.org/blitz\n\\bibitem{tvmet} http://tvmet.sourceforge.net\n\\end{thebibliography}\n\\addcontentsline{toc}{section}{\\refname}\n\n\n\n\\end{document}\n", "meta": {"hexsha": "f23f378e014e60d82ec5ff1b02b8307c94ab263f", "size": 31011, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "vecmat3.tex", "max_stars_repo_name": "vanzonr/vecmat3", "max_stars_repo_head_hexsha": "b1c9671854f95418bd6a4c46dc6be6816ca43fff", "max_stars_repo_licenses": ["Intel", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vecmat3.tex", "max_issues_repo_name": "vanzonr/vecmat3", "max_issues_repo_head_hexsha": "b1c9671854f95418bd6a4c46dc6be6816ca43fff", "max_issues_repo_licenses": ["Intel", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vecmat3.tex", "max_forks_repo_name": "vanzonr/vecmat3", "max_forks_repo_head_hexsha": "b1c9671854f95418bd6a4c46dc6be6816ca43fff", "max_forks_repo_licenses": ["Intel", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5745798319, "max_line_length": 250, "alphanum_fraction": 0.702395924, "num_tokens": 9294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.34839763850849137}}
{"text": "\\section{Introduction}\n\\label{sec:introduction}\n\nFull bayesian inference for most neural network is intractable due to the model's nonlinearity causing the true posterior distribution to be highly complex. This has led to the use of variational methods which attempt to approximate the posterior. With regard to bayesian variational inference; this paper addresses the general issue of prior selection to reduce the sensitivity BNNs have toward such initializations and the high variance that arises in the gradients when employing Monte Carlo approximation techniques.\n\nThe authors list their contributions as:\n\\begin{itemize}\n\t\\item Development of a deterministic procedure for propagating uncertain activations through neural networks with uncertain weights and ReLU or Heaviside activation functions.\n\t\\item Development of an EB method for principled tuning of weight priors during BNN training.\n\t\\item Experimental results showing the accuracy and efficiency of our method and applicability to heteroscedastic and homoscedastic regression on real datasets.\n\\end{itemize}    \n \n", "meta": {"hexsha": "dc51f690608c2e82ce85279a5e47dc21d8690809", "size": 1082, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "_notes/paper-summary/DVI-2019-05-23/tex/Introduction.tex", "max_stars_repo_name": "ibrahimkakbar/ibrahimkakbar.github.io", "max_stars_repo_head_hexsha": "5e6b0ea67f5e5f8f3a7bb4394095ea7f7992673a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_notes/paper-summary/DVI-2019-05-23/tex/Introduction.tex", "max_issues_repo_name": "ibrahimkakbar/ibrahimkakbar.github.io", "max_issues_repo_head_hexsha": "5e6b0ea67f5e5f8f3a7bb4394095ea7f7992673a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_notes/paper-summary/DVI-2019-05-23/tex/Introduction.tex", "max_forks_repo_name": "ibrahimkakbar/ibrahimkakbar.github.io", "max_forks_repo_head_hexsha": "5e6b0ea67f5e5f8f3a7bb4394095ea7f7992673a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 83.2307692308, "max_line_length": 520, "alphanum_fraction": 0.8327171904, "num_tokens": 207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.34839763850849137}}
{"text": "\\documentclass[10pt]{article}\n\\usepackage[margin=1in]{geometry}\n\n\\input{global_macros}\n\\input{macros}\n\n% Enable (uncolored) cross-reference hyperlinks\n% Should always be last package loaded.\n% See: https://tex.stackexchange.com/questions/103123/links-do-not-lead-to-right-pages\n\\usepackage[colorlinks=false]{hyperref}\n\\begin{document}\n  \\begin{center}\n    {\\Large \\textbf{Text Classification under Negative Covariate Shift}}\n\n    \\vspace{6pt}{\\large Project Proposal}\n\n    \\vspace{6pt}Zayd Hammoudeh\n  \\end{center}\n\n  Consider the task of binary (supervised) classification.  Each sample is a tuple of feature vector~${\\X \\in \\domain}$ and label~${\\y \\in \\lbls}$.  Samples are generated from unknown, joint probability distribution~$\\joint$.  Given hypothesis class~${\\hypoCls=\\setbuild{\\dec}{\\func{\\dec}{\\domain}{\\real}}}$ and loss function~$\\func{\\loss}{\\real \\times \\lbls}{\\real}$, the ideal classifier is:\n\n  \\begin{equation}\\label{eq:IdealClassifier}\n    \\dec\\opt = \\argmin_{\\dec \\in \\hypoCls} \\mathbb{E}_{(\\X, \\y) \\sim \\joint} \\sbrack{\\fLoss{\\fDec{\\X}, \\y}}\\text{.}\n  \\end{equation}\n\n  Since $\\joint$~is unknown, Eq.~\\eqref{eq:IdealClassifier} cannot be determined exactly.  \\textit{Empirical risk minimization}, defined in Eq.~\\eqref{eq:ERM}, is used in practice for selection of the optimal learner,~${\\dec\\opt}$. Observe that the true expected loss is replaced with an empirical estimate using i.i.d.\\ training set~${\\train \\sim \\joint}$.\n\n  \\begin{equation}\\label{eq:ERM}\n    \\dec\\opt = \\argmin_{\\dec \\in \\hypoCls} \\sum_{(\\X_i,\\y_i) \\in \\train} \\fLoss{\\fDec{\\X_i}, \\y_i}\n  \\end{equation}\n\n  There are many real-world applications where $\\train$~is not an i.i.d.\\ sample. For example, given a huge (unlabeled) news corpus, a particular user may only be interested in a single topic,~$\\interest$.  There are numerous irrelevant news topics,~${\\irrel_1,\\ldots,\\irrel_n}$ where~$n$ is huge.  This user could label a few relevant articles she manually found as positive~($\\pCls$). She could also label any irrelevant articles she encountered negative. Such an ad-hoc labeling mechanism generally induces \\textit{covariate shift} (i.e.,~train and test marginal distributions) for the negative class. For instance, the user may fail to label documents from each negative topic~$\\irrel_i$. Similarly, the training set's negative topic prior probabilities will not match the corresponding true priors. Constructing a classifier given negative covariate shift is know as \\textit{positive, unlabeled, biased negative} (PUbN)~\\textit{learning}.\n\n  There are three common approaches to PUbN learning:\n\n  \\begin{enumerate}\n    \\item Supervised (PN -- Positive-Negative) Learning: Ignores the bias in the negative training examples.  Serves as a baseline of comparison and quantifies the effect of any correction.\n\n    \\item Positive\\-/Unlabeled (PU) Learning: Premised on the idea that using the biased negative training examples can be inherently deleterious.  It constructs a binary classifier strictly using the positive examples and the residual unlabeled corpus.  An example where this approach was used is~\\cite{Li:2010}.\n\n    \\item Positive, Unlabeled, biased Negative (PUbN) Learning: Constructs a classifier using some \\textit{a~priori} knowledge of the negative training set's bias.  Similar to~\\cite{Hsieh:2019}, this project assumes knowledge of the negative training sets prior probabilities.\n  \\end{enumerate}\n\n  \\paragraph{Goal} This project will explore negative covariate shift's effect on news topic classification.  The experiments in this section are inspired by Fei \\&~Liu~\\cite{Fei:2015} and Hsieh\\etal~\\cite{Hsieh:2019}.\n\n  \\paragraph{Experimental Setup} This project will use the 20~newsgroups dataset~\\cite{20Newsgroups}.  The dataset statistics are shown in Table~\\ref{tab:DatasetComparison}.  We will use the latest (cleaned) version of the dataset published by Jason Rennie where duplicate and empty documents were removed.\n\n  \\begin{table}[b]\n    \\centering\n    \\caption{Dataset statistics for 20~Newsgroups}\\label{tab:DatasetComparison}\n    \\begin{tabular}{|c|c|c|}\n      \\hline\n      \\#~Classes     & 20                     \\\\\\hline\n      Train Size     & 13,180                 \\\\\\hline\n      Test Size      & 5,648                  \\\\\\hline\n      Test Set Prior & Nearly uniform         \\\\\\hline\n    \\end{tabular}\n  \\end{table}\n\n\n  When constructing the experimental datasets, one topic will be selected as the positive class and all remaining~(19) topics will form joint form the negative class.  The experiments will be divided into three categories:\n\n  \\begin{itemize}\n    \\item \\textit{In-Training}: All negative subclasses (${\\irrel_1,\\ldots,\\irrel_n}$) are present in both the training and test sets.  The only difference is their train/test marginal distributions.\n\n    \\item \\textit{Out-of-Training}: Some negative subclasses are only present in the test set. Beside that difference, the train and test marginal distributions are identical.\n\n    \\item \\textit{Combined}: Synthesis of in-training and out-of-training.  Bias includes missing training set subclasses and a marginal distribution shifts  Most challenging case.\n  \\end{itemize}\n\n  \\noindent\n  This procedure will be repeated with different topics as the positive class to ensure as representative of an experiment set as possible.\n\n  \\paragraph{Implementation Plan} The PN, PU, and PUbN implementations will share the same standard neural network architecture implemented in PyTorch.  There will be an embedding of some kind (at minimum a word embedding but potentially also character as well), a bidirectional (possibly stacked) RNN, and an output feed forward.\n\n  Where the three learning classes differ is the risk estimator used in gradient descent training.  PN~will use standard logistic loss.  PU~will use the nnPU risk estimator by Kiryo\\etal\\ in~\\cite{Kiryo:2017}.  PUbN will use~\\cite{Hsieh:2019}'s risk estimator.\n\n  \\bibliographystyle{ieeetr}\n  \\bibliography{bib/ref.bib}\n\\end{document}\n", "meta": {"hexsha": "c0f835d9c965996d36c65c44bb2e54f8018496b2", "size": 5997, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "project/proposal/proposal.tex", "max_stars_repo_name": "ZaydH/cis510_nlp", "max_stars_repo_head_hexsha": "e1e039ca9f228051f6a3682b3ee71665e4d693d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "project/proposal/proposal.tex", "max_issues_repo_name": "ZaydH/cis510_nlp", "max_issues_repo_head_hexsha": "e1e039ca9f228051f6a3682b3ee71665e4d693d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project/proposal/proposal.tex", "max_forks_repo_name": "ZaydH/cis510_nlp", "max_forks_repo_head_hexsha": "e1e039ca9f228051f6a3682b3ee71665e4d693d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-03-25T07:33:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T14:21:20.000Z", "avg_line_length": 74.037037037, "max_line_length": 943, "alphanum_fraction": 0.7470401868, "num_tokens": 1567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6113819591324418, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.34839763043840377}}
{"text": "\\mainsection{Advanced Protocols}\nThis section details the protocols needed to perform complex\nfunctionalities on LSSS style secret shared values in MAMBA.\nAs well as the documentation here further, details can be\nfound at\n\\begin{center}\n  \\verb+$(HOME)/Documentation/Compiler_Documentation/index.html+\n\\end{center}\nunder the heading \\verb+Files+.\n\nThe protocols break the ``arithmetic circuit'' model of computation,\nas they make heavy use of pre-processed data and the ability\nto $\\Open$ shared values.\nIn particular we assume three lists of pre-processed data:\n\\[ \\MList, \\quad \\SList, \\quad \\BList. \\]\nAn entry on the $\\MList$ is of the form\n$(\\sshare{a}, \\sshare{b}, \\sshare{c})$ where $c=a \\cdot b \\pmod{p}$,\nan entry on the $\\SList$ is of the form\n$(\\sshare{a}, \\sshare{b})$ where $b=a^2 \\pmod{p}$,\nwhilst an entry on the $\\BList$ is of the form\n$\\sshare{b}$ where $b \\in \\{0,1\\}$.\nWe also assume a function $\\Random()$ which can generate\na random secret sharing (this can be implemented by just taking\nthe first element from a multiplication triple).\nWe add and multiply secret shared elements in what follows\nusing the notation\n\\[ \\sshare{a+b} \\asn \\sshare{a}+\\sshare{b}, \\quad\n  \\sshare{a\\cdot b} \\asn \\sshare{a} \\cdot \\sshare{b}.\n\\]\n\nThe protocols in this chapter allow us to do more advanced operations,\nwithout resorting to using full blown arithmetic circuits.\nWe describe here what we have implemented as a form of\ndocumentation, both for us and for others.\nMany of the protocol ideas can be found in the five\ndocuments\n\\begin{itemize}\n  \\item Unconditionally Secure Constant-Rounds\n        Multi-party Computation for Equality, Comparison, Bits and Exponentiation.\n          {\\em TCC 2006}, \\cite{DFKNT06}.\n  \\item Improved Primitives for Secure Multiparty Integer Computation.\n          {\\em SCN 2010}, \\cite{CH10}.\n  \\item D9.2 of the EU project {\\em secureSCM}, \\cite{SSCM}.\n  \\item Secure Computation with Fixed-Point Numbers {\\em FC 2010} \\cite{CS10}.\n  \\item Secure Computation on Floating Point Numbers {\\em NDSS 2013} \\cite{ABZS13}.\n\\end{itemize}\nMany of the protocols operating on integers make use of a statistical security\nparameter $\\kappa$.\nIf the integer being operated on is $k$ bits long, then we often require $(k+\\kappa)<\\log_2 p$.\nFor ease of implementation of the protocols we recommend $k$ is\nalways a power of two, and we assume this in the write up below.\nIf this is not the case, obvious tweaks can be made to the protocols.\n\nDue to experience with the SPDZ system we prefer logarithmic\nround protocols over constant round protocols, it appears that in\npractice the logarithmic round protocols outperform the constant\nround ones.\nThe MAMBA compiler can execute non-constant round protocols, by\nflicking a compile time switch. But here we only document\nlogarithmic round protocols.\n\n\\msubsection{Basic Protocols}\n\n\\msubsubsection{$\\mathsf{Inv}(\\sshare{x})$:}\nThis produces a share $\\sshare{z}$ of $1/x \\pmod{p}$, with an\n$\\abort$ if $x=0$.\n\\begin{enumerate}\n  \\item $\\sshare{a} \\asn \\Random()$.\n  \\item $\\sshare{y} \\asn \\sshare{a} \\cdot \\sshare{x}$.\n  \\item $y \\asn \\Open(\\sshare{y})$.\n  \\item If $y=0$ then $\\abort$.\n  \\item $t \\asn 1/y \\pmod{p}$.\n  \\item $\\sshare{z} \\asn t \\cdot \\sshare{a}$.\n  \\item Return $\\sshare{z}$.\n\\end{enumerate}\n\\paragraph{MAMBA Example:} To obtain the inverse of a \\verb|sint| or a \\verb|cint| can be done as follows:\n\\begin{lstlisting}[language={python}]\nd = sint(5)\nd_inv =  AdvInteger.Inv(d)\nprint_ln(\"inverse is correct if 1: %s\", (d*d_inv).reveal())\n\\end{lstlisting}\n\n\\msubsubsection{$\\mathsf{Ran}_p^*()$:}\nThis produces a random sharing of a value $x$ and its inverse $1/x$.\nThis is faster than generating $x$, and then performing the above operaton.\n\\begin{enumerate}\n  \\item Take a triple $(\\sshare{a},\\sshare{b},\\sshare{c})$ from $\\MList$.\n  \\item $c \\asn \\Open(\\sshare{c})$.\n  \\item If $c=0$ then return to the first step.\n  \\item $\\sshare{a^{-1}} \\asn c^{-1} \\cdot \\sshare{b}$.\n  \\item Output $(\\sshare{a},\\sshare{a^{-1}})$.\n\\end{enumerate}\nThis function does not exist ``as is'' in the MAMBA language, as it\nis used in place within the python compiler. Thus it is only here\nfor documentation reasons.\n\n\\msubsubsection{$\\mathsf{PreMult}(\\sshare{a_1},\\ldots,\\sshare{a_t},T)$:}\nThis computes the prefix multiplication, i.e. the values\n\\[ \\sshare{a_{i_0,i_1}} = \\bsshare{\\prod_{i=i_0}^{i_1} a_i} \\]\nwhere $(i_0,i_1) \\in T$ and $1 \\le i_0 \\le i_1 \\le t$.\n\\begin{enumerate}\n  \\item For $i \\in [0,\\ldots,t]$ do.\n        \\begin{enumerate}\n          \\item $(\\sshare{b_i},\\sshare{b_i^{-1}}) \\asn \\mathsf{Ran}_p^*()$.\n        \\end{enumerate}\n  \\item For $i \\in [0,\\ldots,t]$ do.\n        \\begin{enumerate}\n          \\item $\\sshare{t} \\asn \\sshare{b_{i-1}} \\cdot \\sshare{a_i}$.\n          \\item $\\sshare{d_i} \\asn \\sshare{t} \\cdot \\sshare{b_i^{-1}}$.\n          \\item $d_i \\asn \\Open(\\sshare{d_i})$.\n        \\end{enumerate}\n  \\item For $(i_0,i_1) \\in T$\n        \\begin{enumerate}\n          \\item $d_{i_0,i_1} \\asn \\prod_{i=i_0}^{i_1} d_i$.\n          \\item $\\sshare{a_{i_0,i_1}} \\asn d_{i_0,i_1} \\cdot\n                  \\sshare{b_{i_0-1}^{-1}} \\cdot \\sshare{b_{i_1}}$.\n        \\end{enumerate}\n\\end{enumerate}\nAgain, this function does not exist ``as is'' in the MAMBA language, as it\nis used in place within the python compiler. Thus it is only here\nfor documentation reasons.\n\n\n\n\\msubsection{Bit Oriented Operations}\nThese operations refer exclusively to how to perform bit oriented operations on top of\n$\\modp$ data-types. It is not related to the \\verb|sbit| type.\n\n\\msubsubsection{$\\mathsf{OR}(\\sshare{a},\\sshare{b})$:}\nThis computes the logical OR of two input shared bits:\n\\begin{enumerate}\n  \\item Return $\\sshare{a}+\\sshare{b}-\\sshare{a} \\cdot \\sshare{b}$.\n\\end{enumerate}\n\\paragraph{MAMBA Example:} To obtain the \\verb|or| of two \\verb|sint| or \\verb|cint| numbers you can:\n\\begin{lstlisting}[language={python}]\na= sint(1)\nb= sint(0)\nprint_ln(\"or is correct if 1: %s\", (a or b).reveal())\nprint_ln(\"or is correct if 1: %s\", AdvInteger.or_op(a, b).reveal())\n\\end{lstlisting}\n\n\\msubsubsection{$\\mathsf{XOR}(\\sshare{a},\\sshare{b})$:}\nThis computes the logical XOR of two input shared bits:\n\\begin{enumerate}\n  \\item Return $\\sshare{a}+\\sshare{b}-2 \\cdot \\sshare{a} \\cdot \\sshare{b}$.\n\\end{enumerate}\n\\paragraph{MAMBA Example:} To obtain the \\verb|xor| of two \\verb|sint| or \\verb|cint| numbers you can:\n\\begin{lstlisting}[language={python}]\na= sint(1)\nb= sint(0)\nprint_ln(\"or is correct if 1: %s\", AdvInteger.xor_op(a, b).reveal())\n\\end{lstlisting}\n\n\\iffalse\n  \\note{Nigel}{Does not seem to be used anywhere}\n  \\msubsubsection{$\\mathsf{Symm}(f,\\sshare{a_1},\\ldots,\\sshare{a_t})$:}\n  This takes a symmetric boolean function $f$ on $t$ binary inputs\n  and evaluates it at the points $\\sshare{a_1},\\ldots,\\sshare{a_t}$,\n  where we assume $a_i \\in \\{0,1\\}$.\n  We first pre-process the function $f$ so that we can write\n  \\[ f(x_1,\\ldots,x_t) = \\phi(1+\\sum_{i=1}^t x_i), \\]\n  where the inner sum is over the integers and\n  $\\phi:{1,2,\\ldots,t+1} \\longrightarrow \\{0,1\\}$.\n  We then write\n  \\[ \\phi(X) = \\sum_{i=0}^t \\alpha_i \\cdot X^i \\pmod{p} \\]\n  using Lagrange interpolation.\n  So for example if we have $f(X_1,X_2)=X_1^2+X_1 \\cdot X_2+X_2^2+1$\n  then $\\phi$ is the function which maps\n  $1 \\longrightarrow 1$, $2 \\longrightarrow 0$, $3 \\longrightarrow 0$.\n  In which case $\\phi(X)=X^2/2-5 \\cdot X/2+3$.\n\n  To compute this function we have the algorithm\n  \\begin{enumerate}\n    \\item $\\sshare{a} \\asn 1+ \\sum_{i=1}^t \\sshare{a_i}$.\n    \\item $(\\sshare{a},\\sshare{a^2},\\ldots,\\sshare{a^t})\n            \\asn \\mathsf{PreMult}(\\sshare{a},\\ldots,\\sshare{a},\n            \\{(1,1),\\ldots,(1,t)\\})$.\n    \\item $\\sshare{f(a_1,\\ldots,a_t)}\n            \\asn \\sum_{i=0}^t \\alpha_i \\cdot \\sshare{a^i}$.\n  \\end{enumerate}\n\\fi\n\n\\msubsubsection{$\\mathsf{KOp}(\\odot,\\sshare{a_1},\\ldots,\\sshare{a_k},k)$:}\nThis computes the operation $\\sshare{p}= \\bigodot_{i=1}^k \\sshare{a_i}$\ngiven a binary operator $\\odot$.\n\\begin{enumerate}\n  \\item If $k>1$ then (assuming $k$ is even, if not pad)\n        \\begin{enumerate}\n          \\item $\\sshare{t_1} \\asn \\mathsf{KOp}(\\odot, \\sshare{a_{k/2}},\\ldots,\\sshare{a_{k/2}},k/2)$.\n          \\item $\\sshare{t_2} \\asn \\mathsf{KOp}(\\odot, \\sshare{a_{k/2+1}},\\ldots,\\sshare{a_k},k/2)$.\n          \\item Return $\\sshare{t_1} \\odot \\sshare{t_2}$.\n        \\end{enumerate}\n  \\item Else\n        \\begin{enumerate}\n          \\item $\\sshare{p} \\asn \\sshare{a_1}$.\n        \\end{enumerate}\n  \\item Return $\\sshare{p}$.\n\\end{enumerate}\n\n\\paragraph{MAMBA Example:} Note that we basically want to achieve a construction capable to call any function in an iterative fashion reducing computation time. In this sense a call to the function could be perform in the following way:\n\\begin{lstlisting}[language={python}]\n# addition\ndef addition(a, b):\n    return a + b\n\nar=[1]*16\n# (k is exctracted from ar directly on the implementation)\nprint_ln(\"KOpL is correct if 32: %s\", (AdvInteger.KOpL(addition,ar)).reveal())\n\\end{lstlisting}\nThis runs in logarithmic rounds.\n\n\\msubsubsection{$\\mathsf{PreOp}(\\odot,\\sshare{a_1},\\ldots,\\sshare{a_k},k)$:}\nThis computes the prefix operator $\\sshare{p_j} = \\odot_{i=1}^j \\sshare{a_i}$,\nfor $1 \\le j \\le k$.\n\\begin{enumerate}\n  \\item For $i \\in [1,\\ldots, \\log_2 k]$ do\n        \\begin{enumerate}\n          \\item For $j \\in [1,\\ldots,k/2^i]$ do\n                \\begin{enumerate}\n                  \\item $y \\asn 2^{i-1}+j\\cdot 2^i$.\n                  \\item For $z \\in [1,\\ldots,2^{i-1}]$ do\n                        \\begin{enumerate}\n                          \\item $\\sshare{a_{y+z}} \\asn \\sshare{a_y} \\odot \\sshare{a_{y+z}}$.\n                        \\end{enumerate}\n                \\end{enumerate}\n        \\end{enumerate}\n  \\item Return $(\\sshare{a_1},\\ldots,\\sshare{a_k})$.\n\\end{enumerate}\n\n\\paragraph{MAMBA Example:} Similarly, we basically want to achieve a construction capable to call any function in an iterative fashion reducing computation time. In this case, however, we return all the list of intermediate values. The function call could be performed in the following way:\n\\begin{lstlisting}[language={python}]\ndef addition(a, b):\n    return a + b\n\ndef addition_triple(a, b, c):\n\t# c is a boolean parameter\n    return a + b\n\ne = sint(2)\n\nar = [e]*16\n# k is stracted from ar.\nprint_ln(\"PreOpL is correct if 32: %s\", (AdvInteger.PreOpL(addition_triple,ar))[15].reveal())\nprint_ln(\"PreOpN is correct if 32: %s\", (AdvInteger.PreOpN(addition,ar))[15].reveal())\n\\end{lstlisting}\nNote that both methods are implementations of the functionality with slightly different  communication and round complexity.\nWith the \\verb+PreOpL+ function corresponding to the pseudo-code above.\n\n\\msubsubsection{$\\mathsf{Sum\\mhyphen Bits}(\\sshare{x}_B)$:}\nThis outputs a shared integer $x$ in the range\n$[0,\\ldots,2^k)$ with $2^k<p$ given the input $k$ bits\n$\\sshare{x}_B$ making up its binary representation.\n\\begin{enumerate}\n  \\item $\\sshare{x} \\asn \\sum_{i=0}^{k-1} 2^i \\cdot \\sshare{x_i}$.\n  \\item Output $\\sshare{x}$.\n\\end{enumerate}\nTo ease notation in what follows we will write\n$\\sshare{x}_B = \\{\\sshare{x_i}\\}_{i=0}^{k-1}$.\n\n\\paragraph{MAMBA Example:}  We can reconstruct a number from its bits as follows:\n\\begin{lstlisting}[language={python}]\na = [sint(0)]*program.bit_length\n# k is taken from a\nprint_ln(\"sum_bits is correct if 0: %s\", AdvInteger.SumBits(a, program.bit_length).reveal())\n\\end{lstlisting}\n\n\\msubsubsection{$\\mathsf{PRandInt}(k)$:}\nThis generates a random secret integer $r$ in the range $[0,\\ldots,2^k-1]$.\nIn the pseudo-code below we let $[\\BList]\\star k$ denote taking\n$k$ bits from $\\BList$.\n\\begin{enumerate}\n  \\item $\\sshare{r}_B \\asn [\\BList]\\star k$.\n  \\item $\\sshare{r} \\asn \\mathsf{Sum\\mhyphen Bits}(\\sshare{r}_B)$.\n  \\item Return $\\sshare{r}$.\n\\end{enumerate}\n\\paragraph{MAMBA Example:}  We obtain the value as follows:\n\\begin{lstlisting}[language={python}]\n# x is the returned value\nx = sint()\n\n# k are parameters\nk = 5\nAdvInteger.PRandInt(x, k)\n\\end{lstlisting}\n\n\\msubsubsection{$\\mathsf{PRandM}(k,m,\\kappa)$:}\nThis generates two random shares $r' \\in [0,\\ldots,2^{k+\\kappa-m}-1]$\nand $r \\in [0,\\ldots,2^m-1]$, along with the shares the bits of $r$.\n\\begin{enumerate}\n  \\item $\\sshare{r}_B \\asn [\\BList]\\star m$.\n  \\item $\\sshare{r} \\asn \\mathsf{Sum\\mhyphen Bits}(\\sshare{r}_B)$.\n  \\item $\\sshare{r'} \\asn \\mathsf{PRandInt}(k+\\kappa-m)$.\n  \\item Return $\\sshare{r'}, \\sshare{r}, \\sshare{r}_B$.\n\\end{enumerate}\n\\paragraph{MAMBA Example:}  We obtain the randomness and its bits as follows:\n\\begin{lstlisting}[language={python}]\n\n# x, y,z are returned values\nx = sint()\ny = sint()\nyB = [sint() for i in range(3)]\n\n# k, m, kappa are parameters\nk = 5\nm = 3\nkappa = 7\nAdvInteger.PRandM(x, y, yB, k, m, kappa)\n\\end{lstlisting}\n\n\\msubsubsection{$\\mathsf{CarryOut}(\\sshare{a}_B,\\sshare{b}_B,k)$:}\nThis protocol computes the carry-out of a binary addition of\ntwo $k$ bit shared values, when presented via shared bits.\nThe protocol can easily be adapted to the case when either\nthe bits of $a$, or the bits of $b$, are given in the clear.\nWe give a logarithmic round version, which requires $\\log k$\nrounds of interaction.\nIt requires a sub-routine $\\mathsf{CarryOutAux}$ which we\ngive below.\n\\begin{enumerate}\n  \\item For $i \\in [0,\\ldots,k-1]$ do\n        \\begin{enumerate}\n          \\item $\\sshare{d_i}_B \\asn (\\mathsf{XOR}(\\sshare{a_i},\\sshare{b_i}),\n                  \\sshare{a_i}\\cdot \\sshare{b_i})$.\n                  [Note, $\\sshare{d_i}_B$ is a set of two shared bits, one being the XOR\n                    of $a_i$ and $b_i$, whilst the other the AND].\n        \\end{enumerate}\n  \\item $\\sshare{d}_B \\asn \\mathsf{CarryOutAux}(\\sshare{d_{k-1}}_B,\\ldots,\\sshare{d_0}_B,k)$.\n  \\item $(\\sshare{p},\\sshare{g}) \\asn \\sshare{d}_B$.\n  \\item Return $\\sshare{g}$.\n\\end{enumerate}\n\\paragraph{MAMBA Example:}  The carry out operation is executed as follows:\n\\begin{lstlisting}[language={python}]\nres = sint() # last carry bit in addition of a and b\na = [cint(i) for i in [1,0]] # array of clear bits\nb = [sint(i) for i in [0,1]] # array of secret bits (same length as a)\nc = 0 # initial carry-in bit\nAdvInteger.CarryOut(res, a, b, c)\n\\end{lstlisting}\n\n\\msubsubsection{$\\mathsf{CarryOutAux}(\\sshare{d_k}_B,\\ldots,\\sshare{d_1}_B,k)$:}\nThis function uses the $\\circ$ operator for carry propagation on two\nbit inputs which is defined as\n\\[  \\circ:  \\left\\{ \\begin{array}{ccc}\n    \\{0,1\\}^2 \\times \\{0,1\\}^2 & \\longrightarrow & \\{0,1\\} \\\\\n    (p_2,g_2) \\circ (p_1,g_1)  & \\longmapsto     &\n    (p_1 \\wedge p_2, g_2 \\vee (p_2 \\wedge g_1))\n  \\end{array} \\right.\n\\]\nThis is computed using arithmetic operations (i.e. where the values are\nheld as bits modulo $p$) as $(p,g) = (p_2,g_2) \\circ (p_1,g_1)$ via\n\\begin{align*}\n  p & = p_1 \\cdot p_2,       \\\\\n  g & = g_2 + p_2 \\cdot g_1.\n\\end{align*}\nGiven this operation the function $\\mathsf{CarryOutAux}$ is defined by,\nwhich is just a specialisation of the protocol $\\mathsf{KOp}$ above,\n\\begin{enumerate}\n  \\item If $k>1$ then\n        \\begin{enumerate}\n          \\item For $i \\in [1,\\ldots,k/2]$ do\n                \\begin{enumerate}\n                  \\item $\\sshare{u_i}_B \\asn \\sshare{d_{2\\cdot i}}_B \\circ \\sshare{d_{2 \\cdot i-1}}_B$.\n                \\end{enumerate}\n          \\item $\\sshare{d}_B \\asn \\mathsf{CarryOutAux}(\\sshare{u_{k/2}}_B,\\ldots,\\sshare{u_1}_B,k/2)$.\n        \\end{enumerate}\n  \\item Else\n        \\begin{enumerate}\n          \\item $\\sshare{d}_B \\asn \\sshare{d_1}_B$.\n        \\end{enumerate}\n  \\item Return $\\sshare{d}_B$.\n\\end{enumerate}\n\\paragraph{MAMBA Example:} This method is thought as a subroutine for \\verb|CarryOut| and should not be used outside that context. the code is invoked in the following way:\n\\begin{lstlisting}[language={python}]\nkappa = 16\nx = [cint(i) for i in [1,0]]\nres = sint()\nAdvInteger.CarryOutAux(res, x)\n\\end{lstlisting}\n\n\n\\msubsubsection{$\\mathsf{BitAdd}((\\sshare{a_{k-1}},\\ldots,\\sshare{a_0}), (\\sshare{b_{k-1}},\\ldots,\\sshare{b_0}),k)$:}\n  This function also makes use of the operator $\\circ$.\n  The inputs are shared bits. The case where one set of inputs is in the clear\n  is obviously more simple, and we do not detail this here.\n  \\begin{enumerate}\n    \\item For $i \\in [0,\\ldots,k-1]$ do\n          \\begin{enumerate}\n            \\item $\\sshare{d_i}_B \\asn (\\mathsf{XOR}(\\sshare{a_i}, \\sshare{b_i}),\n                    \\sshare{a_i}\\cdot \\sshare{b_i})$.\n          \\end{enumerate}\n    \\item $\\sshare{c_{k-1},t_{k-1}},\\ldots,\\sshare{c_0,t_0}  \\asn \\mathsf{PreOp}(\\circ,\\sshare{d_{k-1}}_B,\\ldots,\\sshare{d_0}_B,k)$.\n    \\item $\\sshare{s_0} \\asn \\mathsf{XOR}(\\sshare{a_0}, \\sshare{a_1})$.\n    \\item For $i \\in [1,\\ldots,k-1]$ do\n          \\begin{enumerate}\n            \\item $\\sshare{s_i} \\asn \\sshare{a_i}+\\sshare{b_i}+\\sshare{c_{i-1}}-2\\cdot \\sshare{c_i}$.\n          \\end{enumerate}\n    \\item $\\sshare{s_k} \\asn \\sshare{c_{k-1}}$.\n    \\item Return $(\\sshare{s_k},\\ldots,\\sshare{s_0})$.\n  \\end{enumerate}\n  There is also a variant (requiring less operations) which does an increment\n  by one, i.e. $x \\asn x+1$.\n\n  \\paragraph{MAMBA Example:} The addition of two numbers expressed in bits, can be performed as follows:\n  \\begin{lstlisting}[language={python}]\na_bits = [sint(i) for i in [0,1,0,1,1]]\nb_bits = [sint(i) for i in [0,1,0,1,1]]\n# k is extracted from the array size\nb = AdvInteger.BitAdd(a_bits, b_bits)\nc = AdvInteger.BitIncrement(a_bits)\n\\end{lstlisting}\n\n  \\msubsubsection{$\\mathsf{BitLTFull}(\\sshare{a}_B,\\sshare{b}_B,k)$:}\n  This computes the sharing of the bit $a<b$, where both $a$ and $b$ are\n  assumed to be $k$ bit values presented in bit format, with\n$a=\\sum_{i=0}^{k-1} a_i \\cdot 2^i$ and\n$b=\\sum_{i=0}^{k-1} b_i \\cdot 2^i$.\n  The method used is from \\cite{DFKNT06}.\n  \\paragraph{MAMBA Example:} Comparing two secret shared numbers decomposed in bits can be achieved as follows:\n  \\begin{lstlisting}[language={python}]\nx = [sint(i) for i in [0,1,1]]\ny = [sint(i) for i in [1,0,1]]\nz = sint()\nkappa = 16\n# k can be extracted from the array size\n# in this case the bit that is the answer is contained in z\nAdvInteger.BitLTFull(z, x, y)\n\\end{lstlisting}\n\n  \\msubsubsection{$\\mathsf{BitLT}(a,\\sshare{b}_B,k)$:}\n  This computes the sharing of the bit $a<b$, where $a$ is a public value.\n  Both $a$ and $b$ are assumed to be $k$ bit values, with\n$a=\\sum_{i=0}^{k-1} a_i \\cdot 2^i$ and\n$b=\\sum_{i=0}^{k-1} b_i \\cdot 2^i$.\n  \\begin{enumerate}\n    \\item For $i \\in [0,\\ldots,k-1]$\n          \\begin{enumerate}\n            \\item $\\sshare{b_i'}\\asn 1-\\sshare{b_i}$.\n          \\end{enumerate}\n    \\item $\\sshare{s} \\asn 1-\n            \\mathsf{CarryOut}((a_{k-1},\\ldots,a_0),\\sshare{b'}_B)$.\n    \\item Return $\\sshare{s}$.\n  \\end{enumerate}\n  \\paragraph{MAMBA Example:} Comparing an open register with a secret shared number decomposed in bits can be achieved as follows:\n  \\begin{lstlisting}[language={python}]\nx = cint(5)\ny = [sint(i) for i in [1,0,1]]\nz = sint()\nkappa = 16\n# k can be extracted from the array size\n# in this case the bit that is the answer is contained in z\nAdvInteger.BitLT(z, x, y, kappa)\n\\end{lstlisting}\n\n\n  \\msubsubsection{$\\mathsf{BitDecFull}(\\sshare{a})$:}\n  This produces the bit-decomposition of the shared value $a$ with\n  respect to the prime \\verb+program.P+.\n  The method used is the one from \\cite{DBLP:conf/pkc/NishideO07},\n  and thus it does not depend on any statistical security gap.\n  The next version is more efficient variant, but only\n  gives statistical security guarantees, and does not\n  work for all $a \\in [0,\\ldots,p)$ is given.\n  When \\verb+program.P+ is larger than $64$-bit the\n  method from \\cite{DFKNT06} is used; not because it is\n  faster but purely because SCALE is not so adapt at doing\n  the other method for large primes.\n  This routine has a side-effect of writing to memory locations in the\n  \\verb+sint+ memory in the first $0,\\ldots,\\log_2 p$ locations.\n  \\paragraph{MAMBA Example:} A secret shared value can be decomposed into bits as shown in the following snippet:\n  \\begin{lstlisting}[language={python}]\nx = cint(23)\nbits = AdvInteger.BitDecFull(a)\nfor i in range(program.P.bit_length()):\n  print_str('%s',bits[i].reveal())\n\\end{lstlisting}\n\n\n  \\msubsubsection{$\\mathsf{BitDec}(\\sshare{a},k,m, \\kappa)$:}\n  This outputs the $m$ least significant bits in the $2$'s complement\n  representation of $a \\in \\Zk$.\n  It requires a statistical security `gap' of $\\kappa$.\n  \\begin{enumerate}\n    \\item $\\sshare{r'}, \\sshare{r}, \\sshare{r}_B \\asn \\mathsf{PRandM}(k,m,\\kappa)$.\n    \\item $c \\asn \\Open(\\sshare{a}+2^k+2^{k+\\kappa}-\\sshare{r}-2^m \\cdot \\sshare{r'})$.\n    \\item $(\\sshare{a_{m-1}},\\ldots,\\sshare{a_0}) \\asn\n            \\mathsf{BitAdd}(c,(\\sshare{r_{m-1}},\\ldots,\\sshare{r_0}))$.\n    \\item Return $(\\sshare{a_{m-1}},\\ldots,\\sshare{a_0})$.\n  \\end{enumerate}\n  \\paragraph{MAMBA Example:} A secret shared value can be decomposed into bits as shown in the following snippet:\n  \\begin{lstlisting}[language={python}]\na = sint(23)\nk = 5\nm = 5\nkappa = 20\n# where b is bit array of type sint\nb = AdvInteger.BitDec(a, k, m, kappa)\n# you can also vall via (where it selects m=k)\nb = a.bit_decompose(k, kappa)\n\\end{lstlisting}\n\n  \\msubsection{Arithmetic with Signed Integers}\n  In this section we define basic arithmetic on signed integers.\n  We define $\\Zk$ as the set of integers $\\{x \\in \\Z: -2^{k-1} \\le x \\le 2^{k-1}-1\\}$,\n  which we embed into $\\F_p$ via the map $x \\mapsto x \\pmod{p}$.\n  Most algorithms require a statistical security gap of $\\kappa$.\n\n\n  \\msubsubsection{$\\mathsf{Mod2m}(\\sshare{a_{prime}}, \\sshare{a},k,m, \\kappa, \\signed)$:}\n  Given $a \\in \\Zk$, $m \\in [1,\\ldots,k-1]$ this outputs $a' = a \\pmod{2^m}$\n  when $\\signed=\\true$.\n  When $\\signed=\\false$ it can take as input a value in $[0,\\ldots,2^k-1]$.\n  Use this protocol when $m>1$, for $m=1$ use $\\mathsf{Mod2}$ below.\n  \\begin{enumerate}\n    \\item $\\sshare{r'}, \\sshare{r}, \\sshare{r}_B \\asn \\mathsf{PRandM}(k,m,\\kappa)$.\n    \\item $c \\asn \\Open(\\sshare{a}+\\signed \\cdot 2^{k-1}+\\sshare{r}+2^m \\cdot \\sshare{r'})$.\n    \\item $c'\\asn c \\pmod{2^m}$.\n    \\item $\\sshare{u} \\asn \\mathsf{BitLT}(c',(\\sshare{r_{m-1}},\\ldots,\\sshare{r_0}),m)$.\n    \\item $\\sshare{a'} \\asn c'-\\sshare{r}+2^m \\cdot \\sshare{u}$.\n    \\item Return $\\sshare{a'}$.\n  \\end{enumerate}\n\n  \\paragraph{MAMBA Example:} The \\verb|mod| to a power of $2$ of a secret shared integer register can be obtain as follows:\n  \\begin{lstlisting}[language={python}]\na_prime = sint(0) # a % 2 ^ m\na = sint(100)\nk = 16 # bit length of a\nm = 2 # the power of two, i..e we want  ( a mod 2^m )\nkappa = 8\nsigned = True # True/False\n\n# where a is a register of type sint\nr_dprime, r_prime, c, c_prime, u, t, c2k1 = \\\n    AdvInteger.Mod2m(a_prime, a, k, m, kappa, signed)\n\\end{lstlisting}\n\n\n  \\msubsubsection{$\\mathsf{Mod2}(\\sshare{a},k, \\kappa, \\signed)$:}\n  \\begin{enumerate}\n    \\item $\\sshare{r'}, \\sshare{r}, \\sshare{r_0} \\asn \\mathsf{PRandM}(k,1,\\kappa)$.\n    \\item $c \\asn \\Open(\\sshare{a}+\\signed \\cdot 2^{k-1}+\\sshare{r}+2 \\cdot \\sshare{r'})$.\n    \\item $\\sshare{a_0} \\asn c_0+\\sshare{r_0}-2 \\cdot c_0 \\cdot \\sshare{r_0}$.\n    \\item Return $\\sshare{a_0}$.\n  \\end{enumerate}\n\n  \\paragraph{MAMBA Example:} You obtain the modulo two of a number as follows:\n  \\begin{lstlisting}[language={python}]\na = sint(1)\na_0 = sint()\nk = 1\nkappa = 8\nsigned = False\n# y stores the result of X % 2\nAdvInteger.Mod2(a_0, A, k, kappa, signed)\n\\end{lstlisting}\n\n  \\msubsubsection{Addition, Multiplication in $\\Zk$}\n  Addition and multiplication $\\odot$ of two elements $\\sshare{a}, \\sshare{b}$\n  to obtain $\\sshare{c}$, where $a,b,c \\in \\Zk$ is then easy to define\n  by performing\n  \\begin{enumerate}\n    \\item $\\sshare{d} \\asn \\sshare{a} \\odot \\sshare{b}$.\n    \\item $\\sshare{c} \\asn \\mathsf{Mod2m}(\\sshare{d},k',k)$,\n          where $k'=k+1$ is $\\odot=+$ and $k'=2\\cdot k$ if $\\odot=\\cdot$.\n    \\item Return $\\sshare{c}$.\n  \\end{enumerate}\n  These functions are not directly callable from MAMBA, they are\n  included here purely for documentation reasons.\n\n  \\msubsubsection{$\\mathsf{Pow2}(\\sshare{a},k, \\kappa)$:}\n  This computes $\\sshare{2^a}$ where $a \\in [0,\\ldots,k)$\n  \\begin{enumerate}\n    \\item $m \\asn \\ceil{\\log_2 k}$.\n    \\item $\\sshare{a_{m-1}},\\ldots,\\sshare{a_0} \\asn \\mathsf{BitDec}(\\sshare{a},m,m)$.\n    \\item For $i\\in [0,\\ldots,m-1]$ do\n          \\begin{enumerate}\n            \\item $\\sshare{v_i} \\asn 2^{2^i} \\cdot \\sshare{a_i}+1-\\sshare{a_i}$.\n          \\end{enumerate}\n    \\item $\\sshare{x_0},\\ldots,\\sshare{x_{m-1}}\n            \\asn \\ \\mathsf{PreMult}(\\sshare{v_0},\\ldots,\\sshare{v_{m-1}}, \\{(1,1),\\ldots,(1,m)\\})$\n    \\item Return $\\sshare{x_{m-1}}$.\n  \\end{enumerate}\n  \\paragraph{MAMBA Example:} You can obtain the value of two raised to a secret shared number as follows:\n  \\begin{lstlisting}[language={python}]\na = sint(23)\nl = 32\nkappa = 20\n# y stores the result of 2^23\ny = AdvInteger.Pow2(a, l, kappa)\n\\end{lstlisting}\n\n  \\msubsubsection{$\\mathsf{B2U}(\\sshare{a},k, \\kappa)$:}\n  This converts the integer $a \\in [0,\\ldots,k)$ into unary form.\n  It outputs $k$ bits, of which the last $a$ bits are zero to one,\n  with the others set to zero.\n  \\begin{enumerate}\n    \\item $\\sshare{2^a} \\asn \\mathsf{Pow2}(\\sshare{a},k)$.\n    \\item $\\sshare{r'}, \\sshare{r}, \\sshare{r}_B \\asn \\mathsf{PRandM}(k,k,\\kappa)$.\n    \\item $c \\asn \\Open(\\sshare{2^a}+\\sshare{r}+2^k \\cdot \\sshare{r'})$.\n    \\item Let $c_{k-1},\\ldots,c_0$ be the bits of $c$.\n    \\item For $i \\in [0,\\ldots,k=1]$ do\n          \\begin{enumerate}\n            \\item $\\sshare{x_i} \\asn c_i+\\sshare{r_i}-2 \\cdot c_i \\cdot \\sshare{r_i}$.\n          \\end{enumerate}\n    \\item $\\sshare{y_{k-1}},\\ldots,\\sshare{y_0} \\asn \\mathsf{PreOp}(\\mathsf{OR},\\sshare{x_{k-1}},\\ldots,\\sshare{x_0},k)$.\n    \\item For $i \\in [0,\\ldots,k=1]$ do\n          \\begin{enumerate}\n            \\item $\\sshare{a_i} \\asn 1-\\sshare{y_i}$.\n          \\end{enumerate}\n    \\item Return $\\sshare{a_0},\\ldots,\\sshare{a_{k-1}}$.\n  \\end{enumerate}\n  Note, in the function $\\mathsf{Oblivious\\_Trunc}$ below we also require the\n  value $\\sshare{2^a}$ to be returned so as to avoid recomputing it.\n\n  \\paragraph{MAMBA Example:} You can transform a number into its unary form as follows:\n  \\begin{lstlisting}[language={python}]\na = sint(3)\nl=5\nkappa=20\nb,c = AdvInteger.B2U(a, l, kappa)\n\\end{lstlisting}\n\n\n  \\msubsubsection{$\\mathsf{TruncPr}(\\sshare{a},k,m, \\kappa)$:}\n  An approximate truncation algorithm which is faster than\n  a fully accurate Trunc.\n  Given $a \\in \\Zk$, $m \\in [1,\\ldots,k-1]$\n  this outputs $\\floor{a/2^m}+u$ where $u$ is a random\n  (and unknown) bit.\n  It gives the actual correct nearest integer with\n  probability $1-\\alpha$, where $\\alpha$ is the distance\n  between $a/2^m$ and that integer.\n  \\begin{enumerate}\n    \\item $\\sshare{r'}, \\sshare{r}, \\sshare{r}_B \\asn \\mathsf{PRandM}(k,m,\\kappa)$.\n    \\item $c \\asn \\Open(\\sshare{a}+2^{k-1}+\\sshare{r}+2^m \\cdot \\sshare{r'})$.\n    \\item $c'\\asn c \\pmod{2^m}$.\n    \\item $t \\asn 1/2^m \\pmod{p}$.\n    \\item $\\sshare{d} \\asn t \\cdot (\\sshare{a}-c'+\\sshare{r})$.\n    \\item Return $\\sshare{d}$.\n  \\end{enumerate}\n  \\paragraph{MAMBA Example:} A secret shared fractional register can be approximately truncated as follows:\n  \\begin{lstlisting}[language={python}]\na = sint(23)\nk = 5\nm = 3\nkappa = 20\n# where b is a register of type sint\nb=AdvInteger.TruncPr(a, k, m, kappa)\n\\end{lstlisting}\n\n  \\msubsubsection{$\\mathsf{Trunc}(\\sshare{a},k,m, \\kappa, \\signed)$:}\n  An exact version of $\\mathsf{Trunc}$ above, it computes the value\n$(a-a \\mod{2^m})/2^m$, where the $\\mod$ operator here produces a positive value.\n  \\begin{enumerate}\n    \\item $\\sshare{a'} \\asn \\mathsf{Mod2m}(\\sshare{a},k,m, \\kappa, \\signed)$.\n    \\item $t \\asn 1/2^m \\pmod{p}$.\n    \\item $\\sshare{d} \\asn t \\cdot (\\sshare{a}-\\sshare{a'})$.\n    \\item Return $\\sshare{d}$.\n  \\end{enumerate}\n  Below we will give a version of $\\mathsf{Trunc}$ in which $m$ is kept secret shared.\n\n  \\paragraph{MAMBA Example:} You truncate a number as follows:\n  \\begin{lstlisting}[language={python}]\n# a = sint(23)\n# k = 5\n# m = 3\n# kappa = 20\n# where a is a register of type sint\na= AdvInteger.Trunc(a, k, m, kappa)\n\\end{lstlisting}\n  There is also an exact version of $\\mathsf{Trunc}$ called $\\mathsf{TruncRoundNearest}$\n  which rounds the value $a/2^m$ to the nearest integer.\n  This is called as\n  \\begin{lstlisting}[language={python}]\na= AdvInteger.TruncRoundNearest(a, k, m, kappa)\n\\end{lstlisting}\n\n\n  \\msubsubsection{$\\mathsf{Oblivious\\_Trunc}(\\sshare{a},k,\\sshare{m}, \\kappa)$:}\n  This does the same operation as $\\mathsf{Trunc}$ above, but $m$ is now secret shared, but guaranteed to be in the range $[0,\\ldots,k)$.\n  \\begin{enumerate}\n    \\item $\\sshare{x_0},\\ldots,\\sshare{x_{k-1}}, \\sshare{2^m} \\asn \\mathsf{B2U}(\\sshare{m},k)$.\n    \\item $\\sshare{2^{-m}} \\asn \\mathsf{Inv}(\\sshare{2^m})$.\n    \\item $\\sshare{r''}, \\sshare{r}, \\sshare{r}_B \\asn \\mathsf{PRandM}(k,k,\\kappa)$.\n    \\item $\\sshare{r'} \\asn \\sum_{i=0}^{k-1} 2^i \\cdot \\sshare{x_i} \\cdot \\sshare{r_i}$\n    \\item $c \\asn \\Open(\\sshare{a}+\\sshare{r''} \\cdot 2^{K} +\\sshare{r})$.\n    \\item For $i \\in [1,\\ldots,k=1]$ do $c_i' \\asn c \\pmod{2^i}$.\n    \\item $\\sshare{c''} \\asn \\sum_{i=1}^{k-1} c_i' \\cdot (\\sshare{x_{i-1}}-\\sshare{x_i})$.\n    \\item $\\sshare{d} \\asn \\mathsf{LT}(\\sshare{c''},\\sshare{r'},k)$.\n    \\item $\\sshare{b} \\asn (\\sshare{a}-\\sshare{c''}+\\sshare{r'}) \\cdot \\sshare{2^{-m}} - \\sshare{d}$.\n    \\item Return $\\sshare{b}$.\n  \\end{enumerate}\n\n  \\paragraph{MAMBA Example:} You truncate a number as follows:\n  \\begin{lstlisting}[language={python}]\na = sint(23)\nk = 5\nm = sint(3)\nkappa = 20\n# where a is a register of type sint\nb= AdvInteger.Oblivious_Trunc(a, k, m, kappa)\n\\end{lstlisting}\n\n  \\iffalse\n    \\note{Nigel}{Does not seem to be used anywhere}\n    \\msubsubsection{$\\mathsf{Mod}(\\sshare{a},k,x)$:}\n    Given $a \\in \\Zk$ and public $x \\in [1,\\ldots,2^{k-1}-1]$\n    this computes $\\sshare{a \\pmod{x}}$.\n    \\begin{enumerate}\n      \\item $m \\asn \\ceil{\\log_2 x }$.\n      \\item $\\sshare{r'}, \\sshare{r}, \\sshare{r}_B \\asn \\mathsf{PRandM}(k,m,\\kappa)$.\n      \\item $c \\asn \\Open(\\sshare{a}+2^{k-1}+\\sshare{r}+x \\cdot \\sshare{r'})$.\n      \\item $c' \\asn c \\pmod{x}$.\n      \\item $\\sshare{v} \\asn 1 -\\mathsf{BitLT}(\\sshare{r}_B,x)$.\n      \\item $\\sshare{u} \\asn \\mathsf{LTZ}(c' - \\sshare{r} + x \\cdot \\sshare{v},m)$.\n      \\item $\\sshare{a'} \\asn c' - \\sshare{r} + x \\cdot ( \\sshare{v}+\\sshare{u})$.\n      \\item Return $\\sshare{a'}$.\n    \\end{enumerate}\n  \\fi\n\n  \\msubsubsection{$\\mathsf{LTZ}(\\sshare{a},k, \\kappa)$:}\n  Given $a \\in \\Zk$ this tests whether $a<0$ or not,\n  resulting in a shared bit.\n  \\begin{enumerate}\n    \\item $\\sshare{s} \\asn - \\mathsf{Trunc}(\\sshare{a},k,k-1)$.\n  \\end{enumerate}\n\n  \\paragraph{MAMBA Example:} You determine whether a number is less than zero as follows:\n  \\begin{lstlisting}[language={python}]\na = sint(1)\nb = sint()\nk=80\nkappa=40\n# b stores the result of x < 0\nAdvInteger.LTZ(b, a, k, kappa)\n\\end{lstlisting}\n  Like many commands in this section this can be abbreviated to\n  \\begin{lstlisting}[language={python}]\nb=a<0\n\\end{lstlisting}\n  In which case the default value of $\\kappa=40$ is chosen\n  (when using a $128$-bit prime modulus), this default value can be\n  altered by using the command\n  \\begin{lstlisting}[language={python}]\nprogram.security = 100\n\\end{lstlisting}\n  The default value of $k=64$ is used in this setting, and\n  this can be altered by executing\n  \\begin{lstlisting}[language={python}]\nprogram.bit_length = 40\n\\end{lstlisting}\n  The requirement is that $k+\\kappa$ must be less than the bit length\n  of the prime $p$.\n\n\n  \\msubsubsection{$\\mathsf{EQZ}(\\sshare{a},k, \\kappa)$:}\n  Given $a \\in \\Zk$ this tests whether $a=0$ or not,\n  resulting in a shared bit.\n  \\begin{enumerate}\n    \\item $\\sshare{r'}, \\sshare{r}, \\sshare{r}_B \\asn \\mathsf{PRandM}(k,k,\\kappa)$.\n    \\item $c \\asn \\Open(\\sshare{a}+2^{k-1}+2^k \\cdot \\sshare{r'}+\\sshare{r})$.\n    \\item Let $c_{k-1},\\ldots,c_0$ be the bits of $c$.\n    \\item For $i \\in [0,\\ldots,k-1]$ do\n          \\begin{enumerate}\n            \\item $\\sshare{d_i} \\asn c_i+\\sshare{r_i}-2 \\cdot c_i \\cdot \\sshare{r_i}$.\n          \\end{enumerate}\n    \\item $\\sshare{z} \\asn 1- \\mathsf{KOp}(\\mathsf{OR},\\sshare{d_{k-1}},\\ldots,\\sshare{d_0},k)$.\n    \\item Return $\\sshare{z}$.\n  \\end{enumerate}\n\n  \\paragraph{MAMBA Example:} You determine whether a number is equal to zero as follows:\n  \\begin{lstlisting}[language={python}]\na = sint(1)\nb = sint()\nk = 80\nkappa = 40\n# b stores the result of x == 0\nAdvInteger.EQZ(b, a, k, kappa)\n\\end{lstlisting}\n\n\n  \\msubsubsection{Comparison Operators:}\n  We can now define the basic comparison operators on shared\n  representations from $\\Zk$.\n  \\begin{center}\n    \\begin{tabular}{|lll|}\n      \\hline\n      Operator & Protocol Name                        & Construction                            \\\\\n      \\hline\n      $a>0$    & $\\mathsf{GTZ(\\sshare{a})}$           & $\\mathsf{LTZ}(-\\sshare{a})$             \\\\\n      $a\\le0$  & $\\mathsf{LEZ(\\sshare{a})}$           & $1-\\mathsf{LTZ}(-\\sshare{a})$           \\\\\n      $a\\ge0$  & $\\mathsf{GEZ(\\sshare{a})}$           & $1-\\mathsf{LTZ}(\\sshare{a})$            \\\\\n      $a=b$    & $\\mathsf{EQ(\\sshare{a},\\sshare{b})}$ & $\\mathsf{EQZ}(\\sshare{a}-\\sshare{b})$   \\\\\n      $a<b$    & $\\mathsf{LT(\\sshare{a,\\sshare{b}})}$ & $\\mathsf{LTZ}(\\sshare{a}-\\sshare{b})$   \\\\\n      $a>b$    & $\\mathsf{GT(\\sshare{a,\\sshare{b}})}$ & $\\mathsf{LTZ}(\\sshare{b}-\\sshare{a})$   \\\\\n      $a\\le b$ & $\\mathsf{LE(\\sshare{a,\\sshare{b}})}$ & $1-\\mathsf{LTZ}(\\sshare{b}-\\sshare{a})$ \\\\\n      $a\\ge b$ & $\\mathsf{GE(\\sshare{a,\\sshare{b}})}$ & $1-\\mathsf{LTZ}(\\sshare{a}-\\sshare{b})$ \\\\\n      \\hline\n    \\end{tabular}\n  \\end{center}\n\n\n  \\iffalse\n    ### NPS: This does not seem to be defined, or used\n    \\msubsubsection{$\\mathsf{Mod2m}(a_{prime}, \\sshare{a},k,\\sshare{m}, \\kappa)$:}\n    This does the same operation as $\\mathsf{Mod2m}$ above, but $m$ is now secret shared.\n    \\begin{enumerate}\n      \\item $\\sshare{x_0},\\ldots,\\sshare{x_{k-1}}, \\sshare{2^m} \\asn \\mathsf{B2U}(\\sshare{m},k)$.\n      \\item $\\sshare{2^{-m}} \\asn \\mathsf{Inv}(\\sshare{2^m})$.\n      \\item $\\sshare{r''}, \\sshare{r}, \\sshare{r}_B \\asn \\mathsf{PRandM}(k,k,\\kappa)$.\n      \\item $\\sshare{r'} \\asn \\sum_{i=0}^{k-1} 2^i \\cdot \\sshare{x_i} \\cdot \\sshare{r_i}$\n      \\item $c \\asn \\Open(\\sshare{a}+\\sshare{r''}+\\sshare{r})$.\n      \\item For $i \\in [1,\\ldots,k=1]$ do $c_i' \\asn c \\pmod{2^i}$.\n      \\item $\\sshare{c''} \\asn \\sum_{i=1}^{k-1} c_i' \\cdot (\\sshare{x_{i-1}}-\\sshare{x_i})$.\n      \\item $\\sshare{d} \\asn \\mathsf{LT}(\\sshare{c''},\\sshare{r'},k)$.\n      \\item $\\sshare{b} \\asn \\sshare{c''}-\\sshare{r'}+\\sshare{2^m} \\cdot \\sshare{d}$.\n      \\item Return $\\sshare{b}$.\n    \\end{enumerate}\n  \\fi\n\n  \\paragraph{MAMBA Example:} The \\verb|mod| to a secret shared power of $2$ of a secret shared integer register can be obtain as follows:\n  \\begin{lstlisting}[language={python}]\na_prime = param_a_prime # a % 2^m\na sint(2137)\nk = 16\nm = sint(2)\nkappa = 8\nsigned = True # True/False, describes a\n\n# where sb is a register of type sint\nr_dprime, r_prime, c, c_prime, u, t, c2k1 = \\\n    comparison.Mod2m(a_prime, a, k, m, kappa, signed)\n\\end{lstlisting}\n\n\n  \\msubsection{Arithmetic with Fixed Point Numbers}\n  In this section we define basic arithmetic on fixed\n  point numbers.\n  We mainly follow the algorithms given in\n  \\begin{itemize}\n    \\item Secure Computation with Fixed-Point Numbers {\\em FC 2010} \\cite{CS10}.\n  \\end{itemize}\n  We define $\\Qk{f}$ as the set of rational numbers\n$\\{x \\in \\Q: x = \\overline{x} \\cdot 2^{-f}, \\overline{x} \\in \\Zk\\}$.\n  We represent $x \\in \\Q$ as the integer $x \\cdot 2^f = \\overline{x} \\in \\Zk$,\n  which is then represented in $\\F_p$ via the mapping used above.\n  Thus $x \\in \\Q$ is in the range $[-2^e,2^e-2^{-f}]$\n  where $e=k-f$.\n  As we are working with fixed point numbers we assume that the\n  parameters $f$ and $k$ are public.\n  For our following algorithms to work (in particular fixed point\n  multiplication and division) we require that\n$f<k$ and $2 \\cdot k + \\kappa < \\log_2 p$.\n  By abuse of notation we write $\\sshare{a}$ to mean $\\sshare{\\overline{a}}$,\n  i.e. the secret sharing of the fixed point number $a$,\n  is actually the secret sharing of the integer representative\n$\\overline{a}$.\n\n  \\iffalse\n    %NPS Does not seem to be used anywhere\n    \\msubsubsection{$\\mathsf{Scale}(\\sshare{a},k,f_1,f_2)$:}\n    Sometimes we want to scale the input fixed point number $a$\n    from $\\Qk{f_1}$ to $\\Qk{f_2}$.\n    \\begin{enumerate}\n      \\item $m \\asn f_2-f_1$.\n      \\item If $m\\ge 0$ then $\\sshare{a'} \\asn 2^m \\cdot \\sshare{a}$.\n      \\item Else $\\sshare{a'} \\asn \\mathsf{TruncPr}(\\sshare{a},k,-m)$.\n      \\item Return $\\sshare{a'}$.\n    \\end{enumerate}\n    This is not directly callable from MAMBA it is here purely\n    for documentation reasons.\n  \\fi\n\n  \\msubsubsection{$\\mathsf{FxEQZ}, \\mathsf{FxLTZ}, \\mathsf{FxEQ}, \\mathsf{FxLT}$, etc:}\n  All of the comparison operators for integers given above carry\n  over to fixed point numbers (if the inputs have the same $f$-values).\n\n  \\msubsubsection{$\\mathsf{FxAbs}(\\sshare{a},k,f)$}\n  \\begin{enumerate}\n    \\item $\\sshare{s} \\asn \\mathsf{LTZ}(\\sshare{a})$.\n    \\item $\\sshare{a} \\asn (1-2\\cdot \\sshare{s}) \\cdot \\sshare{a}$.\n    \\item Return $\\sshare{a}$.\n  \\end{enumerate}\n\n  \\paragraph{MAMBA Example:} To obtain the absolute value of a number as follows:\n  \\begin{lstlisting}[language={python}]\nb = -1.5\nsb = sfix(b)\n\n# k and f are extracted from b\n# returns unsigned b and receives signed b\nub = FixedPt.abs_fx(sb)\n\\end{lstlisting}\n\n  \\msubsubsection{$\\mathsf{FxFloor}(\\sshare{a},k,f)$}\n  \\begin{enumerate}\n    \\item $\\sshare{s} \\asn \\mathsf{Trunc}(\\sshare{a}, k-f, f, \\kappa)$.\n    \\item Return $\\sshare{s}$.\n  \\end{enumerate}\n\n  \\paragraph{MAMBA Example:} To obtain the floor of an \\verb+sfix+ value\n  as an \\verb+sfix+value\n  \\begin{lstlisting}[language={python}]\nb = -1.5\nsb = sfix(b)\n\nub = FixedPt.floor_fx(sb)\n\\end{lstlisting}\n\n  \\msubsubsection{$\\mathsf{FxNeg}(\\sshare{a},k,f)$}\n  \\begin{enumerate}\n    \\item Return $-\\sshare{a}$.\n  \\end{enumerate}\n  \\paragraph{MAMBA Example:} To obtain the original value times $-1$ as follows:\n  \\begin{lstlisting}[language={python}]\nb = -1.5\nsb = sfix(b)\n# k and f are extracted from b\n# returns the value of signed b times -1.\nnb = -sb\n\\end{lstlisting}\n  \\msubsubsection{$\\mathsf{FxAdd}(\\sshare{a},\\sshare{b},k,f)$:}\n  Given $a, b \\in \\Qk{f}$ this is just the integer addition algorithm for elements\n  in $\\Zk$ given above\n  \\begin{enumerate}\n    \\item $\\sshare{c} \\asn \\sshare{a} + \\sshare{b}$.\n    \\item Return $\\sshare{c}$.\n  \\end{enumerate}\n  Obviously from $\\mathsf{FxNeg}$ and $\\mathsf{FxAdd}$ we can define $\\mathsf{FxSub}$.\n  Note that, if the sum overflows then the resulting value will be\n  invalid.\n  \\paragraph{MAMBA Example:} To obtain the addition of two fixed point secret shared values you can do as follows:\n  \\begin{lstlisting}[language={python}]\na = sfix(3.5)\nb = sfix(1.5)\n# k and f are extracted from b or a\n#returns secret shared 5\na_plus_b = a+b\n\\end{lstlisting}\n  \\msubsubsection{$\\mathsf{FxMult}(\\sshare{a},\\sshare{b},k,f)$:}\n  Given $a, b \\in \\Qk{f}$ this requires integer multiplication followed\n  by a suitable truncation.\n  \\begin{enumerate}\n    \\item $\\sshare{d} \\asn \\sshare{a} \\cdot \\sshare{b}$.\n    \\item $\\sshare{c} \\asn \\mathsf{TrunkPR}(\\sshare{d},2 \\cdot k,f)$.\n    \\item Return $\\sshare{c}$.\n  \\end{enumerate}\n  \\paragraph{MAMBA Example:} To obtain the multiplication of two fixed point secret shared values you can do as follows:\n  \\begin{lstlisting}[language={python}]\na = sfix(3.5)\nb = sfix(1.5)\n# k and f are extracted from b or a\n#returns secret shared 5.25\na_mult_b = a*b\n\\end{lstlisting}\n\n  \\msubsubsection{$\\mathsf{FxDiv}(\\sshare{a},b,k,f)$:}\n  We first give division for when $a, b \\in \\Qk{f}$ and $b$ is in the clear.\n  \\begin{enumerate}\n    \\item Compute $x \\in \\Qk{f}$ such that $x \\approx 1/b$.\n    \\item $\\sshare{y} \\asn \\mathsf{TruncPr}(\\overline{x} \\cdot \\sshare{a},k,f)$.\n    \\item Return $\\sshare{y}$.\n  \\end{enumerate}\n\n  \\paragraph{MAMBA Example:} To divide two fixed point values (where only one is secret shared) you can do as follows:\n  \\begin{lstlisting}[language={python}]\na = sfix(3.5)\nb = 1.5\n# k and f are extracted from b\n#returns secret shared 2.333333\na_div_b = a/b\n\\end{lstlisting}\n  \\msubsubsection{$\\mathsf{FxDiv}(\\sshare{a},\\sshare{b},k,f)$:}\n  This operation is more complex and we use method of Goldschmidt, which\n  is recommended by Catrina et. al.\n  The following routine makes use of the two subroutines which follow\n  \\begin{enumerate}\n    \\item $\\theta \\asn \\ceil{\\log_2 (k/3.5)}$.\n    \\item $\\overline{\\alpha} \\asn 2^{2 \\cdot f}$.\n          Note that $\\overline{\\alpha}$ is the integer representative of $1.0$ in $\\Qk{2\\cdot f}$.\n    \\item $\\sshare{w} \\asn \\mathsf{AppRcr}(\\sshare{b},k,f)$.\n    \\item $\\sshare{x} \\asn \\overline{\\alpha} - \\sshare{b}\\cdot \\sshare{w}$.\n    \\item $\\sshare{y} \\asn \\sshare{a}\\cdot \\sshare{w}$.\n    \\item $\\sshare{y} \\asn \\mathsf{TruncPr}(\\sshare{y},2\\cdot k,f)$.\n    \\item For $i \\in [1,\\ldots,\\theta-1]$ do\n          \\begin{enumerate}\n            \\item $\\sshare{y} \\asn \\sshare{y} \\cdot (\\overline{\\alpha}+\\sshare{x})$.\n            \\item $\\sshare{x} \\asn \\sshare{x}^2$.\n            \\item $\\sshare{y} \\asn \\mathsf{TruncPr}(\\sshare{y},2\\cdot k,2 \\cdot f)$.\n            \\item $\\sshare{x} \\asn \\mathsf{TruncPr}(\\sshare{x},2\\cdot k,2 \\cdot f)$.\n          \\end{enumerate}\n    \\item $\\sshare{y} \\asn \\sshare{y} \\cdot (\\overline{\\alpha}+\\sshare{x})$.\n    \\item $\\sshare{y} \\asn \\mathsf{TruncPr}(\\sshare{y},2\\cdot k,2 \\cdot f)$.\n    \\item Return $\\sshare{y}$.\n  \\end{enumerate}\n  \\paragraph{MAMBA Example:} To obtain the division of two fixed point values that are secret shared, you can do as follows:\n  \\begin{lstlisting}[language={python}]\na = sfix(3.5)\nb = 1.5\n# k and f are extracted from b\n#returns secret shared 2.333333\na_div_b = a/b\n\\end{lstlisting}\n\n  \\msubsubsection{$\\mathsf{AppRcr}(\\sshare{b},k,f)$:}\n  \\begin{enumerate}\n    \\item $\\overline{\\alpha} \\asn 2.9142 \\cdot 2^k$.\n          Note that $\\overline{\\alpha}$ is the integer representative of $2.9142$ in $\\Qk{f}$.\n    \\item $(\\sshare{c},\\sshare{v}) \\asn \\mathsf{Norm}(\\sshare{b},k,f)$.\n    \\item $\\sshare{d} \\asn \\overline{\\alpha} - 2 \\cdot \\sshare{c}$.\n    \\item $\\sshare{w} \\asn \\sshare{d} \\cdot \\sshare{v}$.\n    \\item $\\sshare{w} \\asn \\mathsf{TruncPr}(\\sshare{w},2 \\cdot k,2 \\cdot (k-f))$.\n    \\item Return $\\sshare{w}$.\n  \\end{enumerate}\n  This is not mean to be called from MAMBA; but\n  if you insist it is\n  \\begin{lstlisting}[language={python}]\na = sfix(3.5)\nb = FixedPt.AppRcr(a, k, f, kappa)\n\\end{lstlisting}\n\n  \\msubsubsection{$\\mathsf{Norm}(\\sshare{b},k,f):$}\n  This returns the value $c$ such that $2^{k-1} \\le c <2^k$\n  and $v'$ such that $b \\cdot v' = c$,\n  and if $2^{m-1} \\le |b| <2^m$ then $v'= \\pm 2^{k-m}$.\n  \\begin{enumerate}\n    \\item $\\sshare{s} \\asn 1-2 \\cdot \\mathsf{LTZ}(\\sshare{b},k)$.\n    \\item $\\sshare{x} \\asn \\sshare{s} \\cdot \\sshare{b}$.\n    \\item $\\sshare{x_{k-1}},\\ldots,\\sshare{x_0} \\asn \\mathsf{BitDec}(\\sshare{x},k,k)$.\n    \\item $\\sshare{y_{k-1}},\\ldots,\\sshare{y_0} \\asn \\mathsf{PreOp}(\\mathsf{OR},\\sshare{x_{k-1}},\\ldots,\\sshare{x_0},k)$.\n    \\item For $i \\in [0,\\ldots,k-2]$ do\n          \\begin{enumerate}\n            \\item $\\sshare{z_i} \\asn \\sshare{y_i}-\\sshare{y_{i+1}}$.\n          \\end{enumerate}\n    \\item $\\sshare{z_{k-1}} \\asn \\sshare{y_{k-1}}$.\n    \\item $\\sshare{v} \\asn \\sum_{i=0}^{k-1} 2^{k-i-1} \\cdot \\sshare{z_i}$.\n    \\item $\\sshare{c} \\asn \\sshare{x} \\cdot \\sshare{v}$.\n    \\item $\\sshare{v'} \\asn \\sshare{s} \\cdot \\sshare{v}$.\n    \\item Return $(\\sshare{c}, \\sshare{v'})$.\n  \\end{enumerate}\n  \\paragraph{MAMBA Example:} To obtain the norm of a secret shared fix point register you can do as follows:\n  \\begin{lstlisting}[language={python}]\nkappa = 40\nb = sfix(1.5)\n#returns the norm\nc, v = FixedPt.Norm(b, b.k, b.f, kappa, True)\n\\end{lstlisting}\n\n  \\msubsubsection{$\\mathsf{NormSQ}(\\sshare{b},k):$}\n  As above, but now we assume $b \\ge 0$, and we also\n  output shares of $m$ and $w$ such that $w=2^{m/2}$\n  if $m$ is even and $2^{(m-1)/2}$ if $m$ is odd.\n  This algorithm is used in the Fixed Point sqrt routine later.\n  Furthermore $v = 2^{k-m}$. Note that we have introduced some adaptations from the original paper:\n  \\begin{enumerate}\n    \\item $z \\asn \\mathsf{MSB}(\\sshare{b},k,f)$.\n    \\item $\\sshare{v} \\asn \\sum_{i=0}^{k-1} 2^{k-i-1} \\cdot \\sshare{z_i}$.\n    \\item $\\sshare{c} \\asn \\sshare{b} \\cdot \\sshare{v}$.\n    \\item $\\sshare{m} \\asn \\sum_{i=0}^{k-1} (i+1) \\cdot \\sshare{z_i}$.\n    \\item For $i \\in [1,\\ldots,k/2)$ do\n          \\begin{enumerate}\n            \\item $\\sshare{w_i}=\\sshare{z_{2\\cdot i-1}}+\\sshare{z_{2\\cdot i}}$.\n          \\end{enumerate}\n    \\item $\\sshare{w} \\asn \\sum_{i=1}^{k/2-1} 2^i \\cdot \\sshare{w_i}$.\n    \\item Return $\\sshare{c}, \\sshare{v}, \\sshare{m}, \\sshare{w}$.\n  \\end{enumerate}\n\n  \\msubsubsection{$\\mathsf{SimplifiedNormSQ}(\\sshare{b},k):$}\n  Same as above, but in this case we only return $w$, together with a $\\{0,1\\}$ bit signaling whether $m$ is odd.\n  This algorithm is used in the Fixed Point sqrt routine later.\n\n  \\begin{enumerate}\n    \\item $z \\asn \\mathsf{MSB}(\\sshare{b},k,f)$.\n\n    \\item $\\sshare{m} \\asn \\sum_{i=0}^{k-1} (i+1) \\cdot \\sshare{z_i}$.\n    \\item For $i \\in [0,\\ldots,k-1]$ do\n          \\begin{enumerate}\n            \\item If $(i \\quad \\% \\quad 2 == 0)$:\n                  \\begin{enumerate}\n                    \\item $\\sshare{m_{odd}} \\asn m_{odd} + \\sshare{z_{i}}$\n                  \\end{enumerate}\n          \\end{enumerate}\n    \\item For $i \\in [1,\\ldots,k/2)$ do\n          \\begin{enumerate}\n            \\item $\\sshare{w_i}=\\sshare{z_{2\\cdot i-1}}+\\sshare{z_{2\\cdot i}}$.\n          \\end{enumerate}\n    \\item $\\sshare{w} \\asn \\sum_{i=1}^{k/2-1} 2^i \\cdot \\sshare{w_i}$.\n\n    \\item Return $\\sshare{m_{odd}}, \\sshare{w}$.\n  \\end{enumerate}\n\n  \\msubsubsection{$\\mathsf{MSB}(\\sshare{b},k):$}\n  Returns index array $\\sshare{z}$ of size $k$, such that it holds a $1$ in the position of the most significative bit of $\\sshare{b}$ and $\\sshare{0}$ otherwise. This function is used internally in \\verb|NormSQ| and \\verb|SimplifiedNormSQ|.\n  \\begin{enumerate}\n\n    \\item $\\sshare{s} \\asn 1-2 \\cdot \\mathsf{LTZ}(\\sshare{b},k)$.\n    \\item $\\sshare{x} \\asn \\sshare{s} \\cdot \\sshare{b}$.\n    \\item $\\sshare{x_{k-1}},\\ldots,\\sshare{x_0} \\asn \\mathsf{BitDec}(\\sshare{x},k,k)$.\n    \\item $\\sshare{y_{k-1}},\\ldots,\\sshare{y_0} \\asn \\mathsf{PreOp}(\\mathsf{OR},\\sshare{x_{k-1}},\\ldots,\\sshare{x_0},k)$.\n    \\item For $i \\in [0,\\ldots,k-1]$ do\n          \\begin{enumerate}\n            \\item $\\sshare{z_i} \\asn \\sshare{y_i}-\\sshare{y_{i+1}}$.\n          \\end{enumerate}\n    \\item $\\sshare{z_{k-1}} \\asn \\sshare{y_{k-1}}$.\n    \\item Return $\\sshare{z}$.\n  \\end{enumerate}\n\n\n  \\msubsection{Arithmetic with Floating Point Numbers}\n\n  For floating point numbers we utilize the methods described in\n  \\begin{itemize}\n    \\item Secure Computation on Floating Point Numbers {\\em NDSS 2013} \\cite{ABZS13}.\n  \\end{itemize}\n  However we make explicit use of an error flag which we carry throughout\n  a computation, as detailed in previous sections.\n  The processing of overflow and underflow detection is expensive,\n  and thus we enable the user to turn this off via\n  means of a compile time flag \\verb+fdflag+ by passing the option\n  \\verb+-f+ or \\verb+--fdflag+ when using \\verb|compile.py|.\n  This can also be turned on/off within a program by assigning\n  to the variable \\verb+program.fdflag+.\n  The error flag is still needed however to catch other forms of errors\n  in computations (such as division by zero, taking square roots of\n  negative numbers etc).\n  Thus setting \\verb+fdflag+ equal to $\\false$\n  does not necessarily result in $\\err$ always equaling zero.\n\n  Floating point numbers are defined by two global, public integer parameters\n$(\\ell,k)$ which define the size of the mantissa and the exponent respectively.\n  Each floating point number is represented as a five tuple $(v,p,z,s,\\err)$, where\n  \\begin{itemize}\n    \\item $v \\in [2^{\\ell-1},2^\\ell)$ is an $\\ell+1$-bit significand with it's most\n          significant bit always set to one.\n    \\item $p \\in \\Zk$ is the signed exponent.\n    \\item $z$ is a bit to define whether the number is zero or not.\n    \\item $s$ is a sign bit (equal to zero if non-negative).\n    \\item $\\err$ is the error flag (equal to zero if no error has occurred, it holds a non-zero value otherwise).\n  \\end{itemize}\n  Thus assuming $\\err=0$ this tuple represents the value\n  \\[ u=(1- 2 \\cdot s) \\cdot (1-z) \\cdot v \\cdot 2^p. \\]\n  We adopt the conventions that when $u=0$ we also have $z=1, v=0$ and $p=0$,\n  and when $\\err \\ne 0$ then the values of $v,p,z$ and $s$ are meaningless.\n\n  The standard arithmetic operations of addition, multiplication and\n  comparison (plus others) are then implemented in MAMBA for this datatype using\n  operator overloading. The precise algorithms which are executed\n  are detailed below.\n\n  \\msubsubsection{$\\mathsf{FlowDetect}(\\sshare{p})$:}\n  \\begin{enumerate}\n    \\item If $\\mathsf{fdflag}$ then\n          \\begin{enumerate}\n            \\item $\\sshare{s} \\asn -2 \\cdot (\\sshare {p} < 0) + 1$.\n                  %\\item $\\sshare{of} \\asn \\mathsf{GT}(\\sshare{p},2^{k-1}-1,k+1)$.\n                  %\\item $\\sshare{uf} \\asn \\mathsf{LT}(\\sshare{p},-2^{k-1}-1,k+1)$.\n            \\item $\\sshare{\\err} \\asn \\mathsf{GT}(\\sshare{p} \\cdot \\sshare{s},2^{k-1}-1,k+1)$.\n                  %\\sshare{of} + \\sshare{uf}.\n          \\end{enumerate}\n    \\item Return $\\sshare{\\err}$.\n  \\end{enumerate}\n\n  \\msubsubsection{$\\mathsf{FLNeg}((\\sshare{v},\\sshare{p},\\sshare{z},\\sshare{s},\\sshare{\\err}))$:}\n\\begin{enumerate}\n  \\item $\\sshare{s} \\asn 1-\\sshare{s}$.\n  \\item Return $(\\sshare{v},\\sshare{p},\\sshare{z},\\sshare{s},\\sshare{\\err})$\n\\end{enumerate}\n\n\\msubsubsection{$\\mathsf{FLAbs}((\\sshare{v},\\sshare{p},\\sshare{z},\\sshare{s},\\sshare{\\err}))$:}\n  \\begin{enumerate}\n    \\item $\\sshare{s} \\asn 0$.\n    \\item Return $(\\sshare{v},\\sshare{p},\\sshare{z},\\sshare{s},\\sshare{\\err})$\n  \\end{enumerate}\n  Obviously from $\\mathsf{FLNeg}$ and $\\mathsf{FLAdd}$ we can define $\\mathsf{FLSub}$.\n\n  \\msubsubsection{$\\mathsf{FLMult}(\n(\\sshare{v_1},\\sshare{p_1},\\sshare{z_1},\\sshare{s_1},\\sshare{\\err_1}),\n(\\sshare{v_2},\\sshare{p_2},\\sshare{z_2},\\sshare{s_2},\\sshare{\\err_2}))$:}\nFor floating point operations multiplication is much easier than addition, so we deal with\nthis first.\n\\begin{enumerate}\n  \\item $\\sshare{v} \\asn \\sshare{v_1} \\cdot \\sshare{v_2}$.\n  \\item $\\sshare{v} \\asn \\mathsf{Trunc}(\\sshare{v},2 \\cdot \\ell, \\ell-1)$.\n  \\item $\\sshare{b} \\asn \\mathsf{LT}(\\sshare{v},2^\\ell,\\ell+1)$.\n  \\item $\\sshare{v'} \\asn \\sshare{v}+\\sshare{b} \\cdot \\sshare{v}$.\n  \\item $\\sshare{v} \\asn \\mathsf{Trunc}(\\sshare{v'}, \\ell+1, 1)$.\n  \\item $\\sshare{z} \\asn \\mathsf{OR}(\\sshare{z_1},\\sshare{z_2})$.\n  \\item $\\sshare{s} \\asn \\mathsf{XOR}(\\sshare{s_1},\\sshare{s_2})$.\n  \\item $\\sshare{p} \\asn (\\sshare{p_1}+\\sshare{p_2}+\\ell-\\sshare{b}) \\cdot (1-\\sshare{z})$.\n  \\item $\\sshare{\\err} \\asn \\sshare{\\err_1} + \\sshare{\\err_2} + \\mathsf{FlowDetect}(\\sshare{p})$.\n  \\item Return $(\\sshare{v},\\sshare{p},\\sshare{z},\\sshare{s},\\sshare{\\err})$.\n\\end{enumerate}\n\n\n\\msubsubsection{$\\mathsf{FLAdd}(\n  (\\sshare{v_1},\\sshare{p_1},\\sshare{z_1},\\sshare{s_1},\\sshare{\\err_1}),\n  (\\sshare{v_2},\\sshare{p_2},\\sshare{z_2},\\sshare{s_2},\\sshare{\\err_2}))$:}\n  \\begin{enumerate}\n    \\item $\\sshare{a} \\asn \\mathsf{LT}(\\sshare{p_1},\\sshare{p_2},k)$.\n    \\item $\\sshare{b} \\asn \\mathsf{EQ}(\\sshare{p_1},\\sshare{p_2},k)$.\n    \\item $\\sshare{c} \\asn \\mathsf{LT}(\\sshare{v_1},\\sshare{v_2},k)$.\n    \\item $\\sshare{p_{\\max}} \\asn \\sshare{a} \\cdot \\sshare{p_2} + (1-\\sshare{a}) \\cdot \\sshare{p_1}$.\n    \\item $\\sshare{p_{\\min}} \\asn (1-\\sshare{a}) \\cdot  \\sshare{p_2} + \\sshare{a} \\cdot \\sshare{p_1}$.\n    \\item $\\sshare{a \\cdot b} \\asn \\sshare{a} \\cdot \\sshare{b}$.\n    \\item $\\sshare{b \\cdot c} \\asn \\sshare{b} \\cdot \\sshare{c}$.\n    \\item $\\sshare{v_{\\max}} \\asn\n            (\\sshare{a \\cdot b}-\\sshare{a}-\\sshare{b \\cdot c}) \\cdot (\\sshare{v_1}-\\sshare{v_2})\n            + \\sshare{v_1}$.\n    \\item $\\sshare{v_{\\min}} \\asn\n            (\\sshare{a \\cdot b}-\\sshare{a}-\\sshare{b \\cdot c}) \\cdot (\\sshare{v_2}-\\sshare{v_1})\n            + \\sshare{v_2}$.\n    \\item $\\sshare{s_3} \\asn \\mathsf{XOR}(\\sshare{s_1},\\sshare{s_2})$.\n    \\item $\\sshare{d} \\asn \\mathsf{LT}(\\ell, \\sshare{p_{\\max}}-\\sshare{p_{\\min}}, k)$.\n    \\item $\\sshare{2^\\Delta} \\asn \\mathsf{Pow2}((1-\\sshare{d}) \\cdot (\\sshare{p_{\\max}}-\\sshare{p_{\\min}),\\ell+1)$.\n    \\item $\\sshare{v_3} \\asn 2 \\cdot (\\sshare{v_{\\max}}-\\sshare{s_3})+1$.\n    \\item $\\sshare{v_4} \\asn \\sshare{v_{\\max}} \\cdot \\sshare{2^\\Delta}+(1-2 \\cdot \\sshare{s_3}) \\cdot \\sshare{v_{\\min}}$.\n    \\item $\\sshare{v} \\asn (\\sshare{d} \\cdot \\sshare{v_3}+(1-\\sshare{d}) \\cdot \\sshare{v_4})\n            \\cdot 2^\\ell \\cdot \\mathsf{Inv}(\\sshare{2^\\Delta}})$.\n    \\item $\\sshare{v} \\asn \\mathsf{Trunc}(\\sshare{v},2 \\cdot \\ell+1,\\ell-1)$.\n    \\item $\\sshare{u_{\\ell+1}},\\ldots,\\sshare{u_0} \\asn \\mathsf{BitDec}(\\sshare{v},\\ell+2,\\ell+2)$.\n    \\item $\\sshare{h_0},\\ldots,\\sshare{h_{\\ell+1}} \\asn \\mathsf{PreOp}(\\mathsf{OR},\\sshare{u_{\\ell+1}},\\ldots,\\sshare{u_0},k)$.\n    \\item $\\sshare{p_0} \\asn \\ell+2-\\sum_{i=0}^{\\ell+1} \\sshare{h_i}$.\n    \\item $\\sshare{2^{p_0}} \\asn 1+ \\sum_{i=0}^{\\ell+1} 2^i \\cdot (1-\\sshare{h_i})$.\n    \\item $\\sshare{v} \\asn \\mathsf{Trunc}(\\sshare{2^{p_0}} \\cdot \\sshare{v},\\ell+2,2)$.\n    \\item $\\sshare{p} \\asn \\sshare{p_{\\max}}-\\sshare{p_0}+1-\\sshare{d}$.\n    \\item $\\sshare{z_1 \\cdot z_2} \\asn \\sshare{z_1} \\cdot \\sshare{z_2}$.\n    \\item $\\sshare{v} \\asn (1-\\sshare{z_1}-\\sshare{z_2} +\\sshare{z_1 \\cdot z_2}) \\cdot \\sshare{v}\n            + \\sshare{z_1} \\cdot \\sshare{v_2} + \\sshare{z_2} \\cdot \\sshare{v_1}$.\n    \\item $\\sshare{z} \\asn \\mathsf{EQZ}(\\sshare{v},\\ell)$.\n    \\item $\\sshare{p} \\asn (1-\\sshare{z_1}-\\sshare{z_2}+\\sshare{z_1 \\cdot z_2}) \\cdot \\sshare{p}\n            + \\sshare{z_1} \\cdot \\sshare{p_2}\n            + \\sshare{z_2} \\cdot \\sshare{p_1}) \\cdot (1-\\sshare{z})$.\n    \\item $\\sshare{s} \\asn (\\sshare{a}-\\sshare{a \\cdot b}) \\cdot \\sshare{s_2}\n            + (1-\\sshare{a}-\\sshare{b}+\\sshare{a \\cdot b}) \\cdot \\sshare{s_1})\n            + \\sshare{b \\cdot c} \\cdot \\sshare{s_2}\n            + (\\sshare{b}-\\sshare{b \\cdot c}) \\cdot \\sshare{s_1})$.\n    \\item $\\sshare{s} \\asn (1-\\sshare{z_1}-\\sshare{z_2}+\\sshare{z_1 \\cdot z_2}) \\cdot \\sshare{s}\n            + (\\sshare{z_2}-\\sshare{z_1 \\cdot z_2}) \\cdot \\sshare{s_1}\n            + (\\sshare{z_1}-\\sshare{z_1 \\cdot z_2}) \\cdot \\sshare{s_2}$.\n    \\item $\\sshare{\\err} \\asn \\sshare{\\err_1} + \\sshare{\\err_2} + \\mathsf{FlowDetect}(\\sshare{p})$.\n    \\item $\\sshare{\\err} \\asn \\sshare{\\err} + \\mathsf{FlowDetect}(\\sshare{p})$.\n    \\item Return $(\\sshare{v},\\sshare{p},\\sshare{z},\\sshare{s},\\sshare{\\err})$.\n  \\end{enumerate}\n\n  \\msubsubsection{$\\mathsf{SDiv}(\\sshare{a},\\sshare{b},\\ell)$:}\n  \\begin{enumerate}\n    \\item $\\theta \\asn \\ceil{\\log_{2} \\ell}$.\n    \\item $\\sshare{x} \\asn \\sshare{b}$.\n    \\item $\\sshare{y} \\asn \\sshare{a}$.\n    \\item For $i \\in [1,\\ldots,\\theta-1]$ do\n          \\begin{enumerate}\n            \\item $\\sshare{y} \\asn \\sshare{y} \\cdot (2^{\\ell+1}-\\sshare{x})$.\n            \\item $\\sshare{y} \\asn \\mathsf{TruncPr}(\\sshare{y},2\\cdot \\ell+1,\\ell)$.\n            \\item $\\sshare{x} \\asn \\sshare{x} \\cdot (2^{\\ell+1}-\\sshare{x})$.\n            \\item $\\sshare{x} \\asn \\mathsf{TruncPr}(\\sshare{x},2\\cdot \\ell+1,\\ell)$.\n          \\end{enumerate}\n    \\item $\\sshare{y} \\asn \\sshare{y} \\cdot (2^{\\ell+1}-\\sshare{x})$.\n    \\item $\\sshare{y} \\asn \\mathsf{TruncPr}(\\sshare{y},2\\cdot \\ell+1,\\ell)$.\n    \\item Return $\\sshare{y}$.\n  \\end{enumerate}\n\n  \\msubsubsection{$\\mathsf{FLDiv}(\n(\\sshare{v_1},\\sshare{p_1},\\sshare{z_1},\\sshare{s_1},\\sshare{\\err_1}),\n(\\sshare{v_2},\\sshare{p_2},\\sshare{z_2},\\sshare{s_2},\\sshare{\\err_2}))$:}\n\\begin{enumerate}\n  \\item $\\sshare{v} \\asn \\mathsf{SDiv}(\\sshare{v_1},\\sshare{v_2}+\\sshare{z_2},\\ell)$.\n  \\item $\\sshare{b} \\asn \\mathsf{LT}(\\sshare{v},2^\\ell,\\ell+1)$.\n  \\item $\\sshare{v'} \\asn \\sshare{v}+\\sshare{b} \\cdot \\sshare{v}$.\n  \\item $\\sshare{v} \\asn \\mathsf{Trunc}(\\sshare{v'}, \\ell+1, 1)$.\n  \\item $\\sshare{z} \\asn \\sshare{z_1}$.\n  \\item $\\sshare{s} \\mathsf{XOR}(\\sshare{s_1},\\sshare{s_2})$.\n  \\item $\\sshare{p} \\asn (\\sshare{p_1}-\\sshare{p_2}-\\ell+1-\\sshare{b}) \\cdot (1-\\sshare{z})$.\n  \\item $\\sshare{\\err} \\asn \\sshare{\\err_1} + \\sshare{\\err_2}$.\n  \\item $\\sshare{\\err} \\asn \\sshare{\\err} + \\sshare{z_2}$.\n  \\item $\\sshare{\\err} \\asn \\sshare{\\err} + \\mathsf{FlowDetect}(\\sshare{p})$.\n  \\item Return $(\\sshare{v},\\sshare{p},\\sshare{z},\\sshare{s},\\sshare{\\err})$.\n\\end{enumerate}\n\n\n\\msubsubsection{$\\mathsf{FLLTZ}((\\sshare{v},\\sshare{p},\\sshare{z},\\sshare{s},\\sshare{\\err}))$:}\n  \\begin{enumerate}\n    \\item Return $\\sshare{s} \\cdot (1-\\sshare{z}) \\cdot \\mathsf{EQZ}(\\sshare{\\err}, k)$.\n  \\end{enumerate}\n\n  \\msubsubsection{$\\mathsf{FLEQZ}((\\sshare{v},\\sshare{p},\\sshare{z},\\sshare{s},\\sshare{\\err}))$:}\n\\begin{enumerate}\n  \\item Return $\\sshare{z} \\cdot \\mathsf{EQZ}(\\sshare{\\err}, k)$.\n\\end{enumerate}\n\n\\msubsubsection{$\\mathsf{FLGTZ}((\\sshare{v},\\sshare{p},\\sshare{z},\\sshare{s},\\sshare{\\err}))$:}\n  \\begin{enumerate}\n    \\item Return $(1-\\sshare{s}) \\cdot (1-\\sshare{z}) \\mathsf{EQZ}(\\sshare{\\err}, k)$.\n  \\end{enumerate}\n\n  \\msubsubsection{$\\mathsf{FLLEZ}((\\sshare{v},\\sshare{p},\\sshare{z},\\sshare{s},\\sshare{\\err}))$:}\n\\begin{enumerate}\n  \\item Return $\\sshare{s} \\cdot (1 - \\mathsf{EQZ}(\\sshare{\\err}, k))$.\n\\end{enumerate}\n\n\\msubsubsection{$\\mathsf{FLGEZ}((\\sshare{v},\\sshare{p},\\sshare{z},\\sshare{s},\\sshare{\\err}))$:}\n  \\begin{enumerate}\n    \\item Return $(1-\\sshare{s}) \\cdot \\mathsf{EQZ}(\\sshare{\\err}, k)$.\n  \\end{enumerate}\n\n  \\msubsubsection{$\\mathsf{FLEQ}(\n(\\sshare{v_1},\\sshare{p_1},\\sshare{z_1},\\sshare{s_1},\\sshare{\\err_1}),\n(\\sshare{v_2},\\sshare{p_2},\\sshare{z_2},\\sshare{s_2},\\sshare{\\err_2}))$:}\n\\begin{enumerate}\n  \\item $\\sshare{b_1} \\asn \\mathsf{EQ}(\\sshare{v_1},\\sshare{v_2},\\ell)$.\n  \\item $\\sshare{b_2} \\asn \\mathsf{EQ}(\\sshare{p_1},\\sshare{p_2},k)$.\n  \\item $\\sshare{b_3} \\asn \\sshare{z_1} \\cdot \\sshare{z_2}$.\n  \\item $\\sshare{b_4} \\asn \\sshare{s_1} \\cdot \\sshare{s_2}$.\n  \\item $\\sshare{t} \\asn \\sshare{err_1} + \\sshare{err_2}$.\n  \\item $\\sshare{t} \\asn (\\mathsf{EQZ}(\\sshare{t}, k)$.\n  \\item Return $(\\sshare{b_1} \\cdot \\sshare{b_2} \\cdot \\sshare{b_3} \\cdot (1 - \\sshare{b_4}) + \\sshare{b_4}) \\cdot \\sshare{t}$.\n\\end{enumerate}\n\n\\msubsubsection{$\\mathsf{FLLT}(\n  (\\sshare{v_1},\\sshare{p_1},\\sshare{z_1},\\sshare{s_1},\\sshare{\\err_1}),\n  (\\sshare{v_2},\\sshare{p_2},\\sshare{z_2},\\sshare{s_2},\\sshare{\\err_2}))$:}\n  \\begin{enumerate}\n    \\item $\\sshare{a} \\asn \\mathsf{LT}(\\sshare{p_1},\\sshare{p_2},k)$.\n    \\item $\\sshare{c} \\asn \\mathsf{EQ}(\\sshare{p_1},\\sshare{p_2},k)$.\n    \\item $\\sshare{d} \\asn \\mathsf{LT}((1-2\\cdot \\sshare{s_1}) \\cdot \\sshare{v_1},\n            (1-2\\cdot \\sshare{s_2}) \\cdot \\sshare{v_2},\\ell+1)$.\n    \\item $\\sshare{a \\cdot c} \\asn \\sshare{a}\\cdot \\sshare{c}$.\n    \\item $\\sshare{c \\cdot d} \\asn \\sshare{c}\\cdot \\sshare{d}$.\n    \\item $\\sshare{b^+} \\asn \\sshare{c \\cdot d}+(\\sshare{a}-\\sshare{a \\cdot c})$.\n    \\item $\\sshare{b^-} \\asn \\sshare{c \\cdot d}+(1-\\sshare{c}-\\sshare{a}+\\sshare{a \\cdot c})$.\n    \\item $\\sshare{z_1 \\cdot z_2} \\asn \\sshare{z_1}\\cdot \\sshare{z_2}$.\n    \\item $\\sshare{s_1 \\cdot s_2} \\asn \\sshare{s_1}\\cdot \\sshare{s_2}$.\n    \\item $\\sshare{b} \\asn \\sshare{z_1 \\cdot z_2} \\cdot (\\sshare{s_2}-1-\\sshare{s_1 \\cdot s_2})\n            + \\sshare{s_1 \\cdot s_2} \\cdot (\\sshare{z_1}+\\sshare{z_2}-1)\n            + \\sshare{z_1}\\cdot (1-\\sshare{s1}-\\sshare{s_2})\n            + \\sshare{s_1}$.\n    \\item $\\sshare{t} \\asn \\sshare{err_1} + \\sshare{err_2}$.\n    \\item $\\sshare{t} \\asn \\mathsf{EQZ}(\\sshare{t}, k)$.\n    \\item $\\sshare{b} \\asn \\sshare{b}+\n            (1-\\sshare{z_1}-\\sshare{z_2}+\\sshare{z_1 \\cdot z_2} \\cdot\n            ((1-\\sshare{s_1}-\\sshare{s_2}+\\sshare{s_1 \\cdot s_2}) \\cdot \\sshare{b^+}\n            +\\sshare{s_1 \\cdot s_2} \\cdot \\sshare{b^-}) \\cdot \\sshare{t}$.\n    \\item Return $\\sshare{b}$.\n  \\end{enumerate}\n\n\n  \\msubsubsection{$\\mathsf{FLGT}(\n(\\sshare{v_1},\\sshare{p_1},\\sshare{z_1},\\sshare{s_1},\\sshare{\\err_1}),\n(\\sshare{v_2},\\sshare{p_2},\\sshare{z_2},\\sshare{s_2},\\sshare{\\err_2}))$:}\n\\begin{enumerate}\n  \\item $\\sshare{v_r}, \\sshare{p_r}, \\sshare{z_r}, \\sshare{s_r}, \\sshare{err_r} \\asn\n          \\mathsf{FLAdd}(\n          (\\sshare{v_2},\\sshare{p_2},\\sshare{z_2},1 -\\sshare{s_2},\\sshare{\\err_2}),\n          (\\sshare{v_1},\\sshare{p_1},\\sshare{z_1},\\sshare{s_1},\\sshare{\\err_1}))$.\n  \\item Return $\\mathsf{FLLTZ}(\\sshare{v_r}, \\sshare{p_r}, \\sshare{z_r}, \\sshare{s_r}, \\sshare{err_r})$.\n\\end{enumerate}\n\n\\msubsubsection{$\\mathsf{FLLET}(\n  (\\sshare{v_1},\\sshare{p_1},\\sshare{z_1},\\sshare{s_1},\\sshare{\\err_1}),\n  (\\sshare{v_2},\\sshare{p_2},\\sshare{z_2},\\sshare{s_2},\\sshare{\\err_2}))$:}\n  \\begin{enumerate}\n    \\item $\\sshare{b} \\asn \\mathsf{FLGT}(\n            (\\sshare{v_1},\\sshare{p_1},\\sshare{z_1},\\sshare{s_1},\\sshare{\\err_1}),\n            (\\sshare{v_2},\\sshare{p_2},\\sshare{z_2},\\sshare{s_2},\\sshare{\\err_2}))$.\n          %\\item $\\sshare{b_2} \\asn \\mathsf{FLEQ}(\n          %        (\\sshare{v_1},\\sshare{p_1},\\sshare{z_1},\\sshare{s_1},\\sshare{\\err_1}),\n          %        (\\sshare{v_2},\\sshare{p_2},\\sshare{z_2},\\sshare{s_2},\\sshare{\\err_2}))$.\n    \\item Return $1 - \\sshare{b}$%$\\mathsf{OR}(\\sshare{b_1},\\sshare{b_2})$.\n  \\end{enumerate}\n\n  \\msubsubsection{$\\mathsf{FLGET}(\n(\\sshare{v_1},\\sshare{p_1},\\sshare{z_1},\\sshare{s_1},\\sshare{\\err_1}),\n(\\sshare{v_2},\\sshare{p_2},\\sshare{z_2},\\sshare{s_2},\\sshare{\\err_2}))$:}\n\\begin{enumerate}\n  \\item $\\sshare{b} \\asn \\mathsf{FLLT}(\n          (\\sshare{v_1},\\sshare{p_1},\\sshare{z_1},\\sshare{s_1},\\sshare{\\err_1}),\n          (\\sshare{v_2},\\sshare{p_2},\\sshare{z_2},\\sshare{s_2},\\sshare{\\err_2}))$.\n        %\\item $\\sshare{b_2} \\asn \\mathsf{FLEQ}(\n        %        (\\sshare{v_1},\\sshare{p_1},\\sshare{z_1},\\sshare{s_1},\\sshare{\\err_1}),\n        %        (\\sshare{v_2},\\sshare{p_2},\\sshare{z_2},\\sshare{s_2},\\sshare{\\err_2}))$.\n  \\item Return $1 - \\sshare{b}$%$\\mathsf{OR}(\\sshare{b_1},\\sshare{b_2})$.\n\\end{enumerate}\n\n\\msubsection{Conversion Routines}\n\n\\msubsubsection{$\\mathsf{FLRound}((\\sshare{v_1},\\sshare{p_1},\\sshare{z_1},\\sshare{s_1},\\sshare{\\err_1},\\mathsf{mode})$:}\n  This, depending on $\\mathsf{mode}$, computes either the floating point\n  representation of the floor (if $\\mathsf{mode}=0$) or the ceiling (if $\\mathsf{mode}=1$)\n  of the input floating point number.\n  \\begin{enumerate}\n    \\item $\\sshare{a} \\asn \\mathsf{LTZ}(\\sshare{p_1},k)$.\n    \\item $\\sshare{b} \\asn \\mathsf{LT}(\\sshare{p_1},-\\ell+1,k)$.\n    \\item $\\sshare{a \\cdot b} \\asn \\sshare{a} \\cdot \\sshare{b}$.\n    \\item $\\sshare{v_2},\\sshare{2^{-p_1}} \\asn \\mathsf{Oblivious\\_Trunc}(\\sshare{v_1},\\ell,(\\sshare{a \\cdot b}-\\sshare{a}) \\cdot \\sshare{p_1})$.\n            [Note, we save the computation of $\\sshare{2^{-p_1}}$ which this routine computes when $0 \\le p_1 < -\\ell$, otherwise the returned share is of $2^0$.]\n    \\item $\\sshare{c} \\asn \\mathsf{EQZ}(\\sshare{v_2},\\ell)$.\n    \\item $\\sshare{v} \\asn \\sshare{v_1}-\\sshare{v_2}+(1-\\sshare{c}) \\cdot \\sshare{2^{-p_1}}\n            \\cdot \\mathsf{XOR}(\\mathsf{mode},\\sshare{s_1})$.\n    \\item $\\sshare{d} \\asn \\mathsf{EQ}(\\sshare{v},2^\\ell,\\ell+1)$.\n    \\item $\\sshare{v} \\asn 2^{\\ell-1} \\cdot \\sshare{d} + (1-\\sshare{d}) \\cdot \\sshare{v}$.\n    \\item $\\sshare{v} \\asn (\\sshare{a}-\\sshare{a \\cdot b}) \\cdot \\sshare{v}\n            + \\sshare{a \\cdot b} \\cdot (\\mathsf{mode}-\\sshare{s_1})\n            + (1-\\sshare{a}) \\cdot \\sshare{v_1}$.\n    \\item $\\sshare{s} \\asn (1-\\sshare{b} \\cdot \\mathsf{mode}) \\cdot \\sshare{s_1}$.\n    \\item $\\sshare{z} \\asn \\mathsf{OR}(\\mathsf{EQZ}(\\sshare{v},\\ell),\\sshare{z_1})$.\n    \\item $\\sshare{v} \\asn \\sshare{v} \\cdot (1-\\sshare{z})$.\n    \\item $\\sshare{p} \\asn (\\sshare{p_1}+\\sshare{d} \\cdot (\\sshare{a}-\\sshare{a \\cdot b})) \\cdot (1-\\sshare{z})$.\n    \\item $\\sshare{\\err} \\asn \\sshare{\\err_1}$.\n    \\item Return $(\\sshare{v},\\sshare{p},\\sshare{z},\\sshare{s},\\sshare{\\err})$.\n  \\end{enumerate}\n\n  \\paragraph{MAMBA Example:} To round a \\verb|sfloat| value we could invoke the function as follows:\n  \\begin{lstlisting}[language={python}]\nfrom Compiler import floatingpoint\nx = sfloat(5.5)\nmode = 0\n# v, p, z, s, err are extracted from x\n# retunrs the floor of x\ny = floatingpoint.FLRound(x,mode)\n\\end{lstlisting}\n  When \\verb+mode=2+ then we get the ceil operation.\n\n\n  \\msubsubsection{$\\mathsf{Int2Fx}(\\sshare{a},k,f)$:}\n  Given an integer $a \\in \\Zk$ this gives the equivalent integer $b$\n  in $\\Qk{f}$, namely $\\overline{b}=a \\cdot 2^f$.\n  Note this means, to ensure correctness, that $|a|\\le 2^{k-f}$.\n  \\begin{enumerate}\n    \\item Return $2^f \\cdot \\sshare{a}$.\n  \\end{enumerate}\n\n  \\paragraph{MAMBA Example:} To cast an \\verb|int| or \\verb|sint| register into a \\verb|sfix| one, you could execute the following:\n  \\begin{lstlisting}[language={python}]\nx = sfix(5.5)\n# k, f are extracted from x\ny = sfix.load_sint(x)\n\\end{lstlisting}\n\n  \\msubsubsection{$\\mathsf{Int2FL}(\\sshare{a},\\gamma,\\ell)$:}\n  We assume $a \\in \\Zgam$, this could loose precision if $\\gamma-1>\\ell$.\n  \\begin{enumerate}\n    \\item $\\lambda \\asn \\gamma-1$.\n    \\item $\\sshare{s} \\asn \\mathsf{LTZ}(\\sshare{a},\\gamma)$.\n    \\item $\\sshare{z} \\asn \\mathsf{EQZ}(\\sshare{a},\\gamma)$.\n    \\item $\\sshare{a} \\asn (1- 2 \\cdot \\sshare{s}) \\cdot \\sshare{a}$.\n    \\item $\\sshare{a_{\\lambda-1}},\\ldots,\\sshare{a_0}\n            \\asn \\mathsf{BitDec}(\\sshare{a},\\lambda,\\lambda)$.\n    \\item $\\sshare{b_0},\\ldots,\\sshare{b_{\\lambda-1}} \\asn\n            \\mathsf{PreOp}(\\mathsf{OR},\\sshare{a_{\\lambda-1}},\\ldots,\\sshare{a_0},\\gamma)$.\n    \\item $\\sshare{v} \\asn \\sshare{a} \\cdot\n            ( 1+\\sum_{i=0}^{\\lambda-1} 2^i \\cdot (1-\\sshare{b_i}))$.\n    \\item $\\sshare{p} \\asn - (\\lambda-\\sum_{i=0}^{\\lambda-1} \\sshare{b_i})$.\n    \\item If $(\\gamma-1)>\\ell$ then\n          \\begin{enumerate}\n            \\item $\\sshare{v} \\asn \\mathsf{Trunc}(\\sshare{v},\\gamma-1,\\gamma-\\ell-1)$.\n          \\end{enumerate}\n    \\item Else\n          \\begin{enumerate}\n            \\item $\\sshare{v} \\asn 2^{\\ell-\\gamma+1} \\cdot \\sshare{v}$.\n          \\end{enumerate}\n    \\item $\\sshare{p} \\asn (\\sshare{p}+\\gamma-1-\\ell) \\cdot (1-\\sshare{z})$.\n    \\item $\\sshare{\\err} \\asn 0$.\n    \\item Return $(\\sshare{v},\\sshare{p},\\sshare{z},\\sshare{s},\\sshare{\\err})$.\n  \\end{enumerate}\n\n  \\paragraph{MAMBA Example:} To cast an \\verb|int| or \\verb|sint| register into a \\verb|sfloat| one, you could execute the following:\n  \\begin{lstlisting}[language={python}]\nx = sfloat(5.5)\n# gamma and l are extracted from the system\ny = sfloat(x)\n\\end{lstlisting}\n\n\n  \\msubsubsection{$\\mathsf{Fx2Int}(\\sshare{a},k,f)$:}\n  Given a value $a \\in \\Qk{f}$ this gives the integer\n$\\floor{\\overline{a}/2^f}$.\n  \\begin{enumerate}\n    \\item Return $\\mathsf{Trunc}(\\sshare{a},k,f)$.\n  \\end{enumerate}\n\n  \\paragraph{MAMBA Example:} To extract the integral component of a \\verb|sfix| register, which is then encapsulated on a \\verb|sint| register,\n  and taking into account what is currently implemented, you could execute the following:\n  \\begin{lstlisting}[language={python}]\nx = sifx(5.5)\n# y stores 5 in a sint register\ny = AdvInteger.Trunc(x.v, x.k, x.f, x.kappa)\n\\end{lstlisting}\n  \\msubsubsection{$\\mathsf{FxFloor}(\\sshare{a},k,f)$:}\n  Given a value $a \\in \\Qk{f}$ this does the same, but\n  gives the result as a fixed point value.\n  \\begin{enumerate}\n    \\item Return $2^f \\cdot \\mathsf{Trunc}(\\sshare{a},k,f)$.\n  \\end{enumerate}\n  \\paragraph{MAMBA Example:} To floor an \\verb|sfix| register, you could execute the following:\n  \\begin{lstlisting}[language={python}]\nfrom Compiler import mpc_math\nx = sifx(5.5)\n# k and f are extracted from x\n# y stores 5 in a sfix register\ny = mpc_math.floor_fx(x)\n\\end{lstlisting}\n\n  \\msubsubsection{$\\mathsf{Fx2FL}(\\sshare{g},\\gamma,f,\\ell,k)$:}\n  Converts $g \\in \\Qk{f}$ into a floating point number\n  \\begin{enumerate}\n    \\item ($\\sshare{v},\\sshare{p},\\sshare{z},\\sshare{s},\\sshare{\\err})\n            \\asn \\mathsf{Int2FL}(\\sshare{g},\\gamma,\\ell)$.\n    \\item $\\sshare{p} \\asn (\\sshare{p}-f) \\cdot (1-\\sshare{z})$.\n    \\item Return $(\\sshare{v},\\sshare{p},\\sshare{z},\\sshare{s},\\sshare{\\err})$.\n  \\end{enumerate}\n  \\paragraph{MAMBA Example:} To cast from \\verb|sfix| to \\verb|sfloat|, you could execute the following:\n  \\begin{lstlisting}[language={python}]\n# stores 5.5 on a sfloat register\nx = sfloat(sfix(5.5))\n\\end{lstlisting}\n\n  \\iffalse\n    % this seems not to be used elsewhere\n    \\msubsubsection{$\\mathsf{FL2Int}((\\sshare{v},\\sshare{p},\\sshare{z},\\sshare{s},\\sshare{\\err}),\\ell,k,\\gamma)$:}\n      Note the two calls to $\\mathsf{Mod2m}$ below can be combined into\n      one, as can the two calls to $\\mathsf{Pow2}$.\n      The output here is in $\\Zgam$.\n    \\begin{enumerate}\n      \\item $\\sshare{v'},\\sshare{p'},\\sshare{z'},\\sshare{s'},\\sshare{\\err'}\n              \\asn \\mathsf{FLRound}(\\sshare{v},\\sshare{p},\\sshare{z},\\sshare{s},\\sshare{\\err},\\mathsf{2})$.\n      \\item $\\sshare{a} \\asn \\mathsf{LT}(\\sshare{p'},\\gamma-1,k)$.\n      \\item $\\sshare{b} \\asn \\mathsf{LT}(\\gamma-\\ell-1,\\sshare{p'},k)$.\n      \\item $\\sshare{c} \\asn \\mathsf{LTZ}(\\sshare{p'},k)$.\n      \\item $\\sshare{b \\cdot c} \\asn \\sshare{b} \\cdot \\sshare{c}$.\n      \\item $\\sshare{m} \\asn \\sshare{a}\\cdot (\\sshare{b} -\\sshare{b \\cdot c})\n              \\cdot (\\gamma-1-\\sshare{p'})$.\n      \\item $\\sshare{u} \\asn \\mathsf{Mod2m}(\\sshare{v'},\\ell,\\sshare{m})$.\n      \\item $\\sshare{v'} \\asn (\\sshare{b} -\\sshare{b \\cdot c}) \\cdot ( \\sshare{u}-\\sshare{v'}) +\\sshare{v'}$\n      \\item $\\sshare{2^{-p'}} \\asn \\mathsf{Pow2}(-\\sshare{c} \\cdot \\sshare{p'},\\ell)$.\n      \\item $\\sshare{2^{p'}} \\asn \\mathsf{Inv}(\\sshare{2^{-p'}})$.\n      \\item $\\sshare{v'} \\asn (\\sshare{c} \\cdot \\sshare{2^{p'}}+1-\\sshare{c})\n              \\cdot \\sshare{v'}$.\n      \\item $\\sshare{w} \\asn \\mathsf{Mod2m}(\\sshare{v'},\\ell,\n              \\sshare{b \\cdot c}\\cdot(\\gamma-1))$.\n      \\item $\\sshare{v'} \\asn \\sshare{b \\cdot c} \\cdot (\\sshare{w}-\\sshare{v'}) +\\sshare{v'}$.\n      \\item $\\sshare{2^{p'}} \\asn \\mathsf{Pow2}(\\sshare{a} \\cdot (1-\\sshare{c})\n              \\cdot \\sshare{p'},\\gamma-1)$.\n      \\item $\\sshare{g} \\asn (1-\\sshare{z'}) \\cdot (1-2 \\cdot \\sshare{s'})\n              \\cdot \\sshare{2^{p'}} \\cdot \\sshare{a}\n              \\cdot \\sshare{v'}$.\n      \\item Return $\\sshare{g}$.\n    \\end{enumerate}\n    \\paragraph{MAMBA Example:} To extract the integral component of a \\verb|sfloat| input,\n    given the current implementation, you could execute the following:\n    \\begin{lstlisting}[language={python}]\nfrom Compiler import floatingpoint\n# v, p, z, s, err are extracted from x and l, k, gamma are system parameters\nx = sfloat(5.5)\n# retunrs the floor of x\ny = floatingpoint.FLRound(x,0)\n\\end{lstlisting}\n  \\fi\n\n  \\msubsubsection{$\\mathsf{FL2Fx}((\\sshare{v},\\sshare{p},\\sshare{z},\\sshare{s},\\sshare{\\err}),\\ell,k,\\gamma,f)$:}\n\\begin{enumerate}\n  \\item $\\sshare{b} \\asn \\mathsf{LT}(\\sshare{p},2^{k-1}-f,k)$.\n  \\item $\\sshare{g} \\asn \\mathsf{FL2Int}((\\sshare{v},\\sshare{p}+f,\\sshare{z},\n          \\sshare{s},\\sshare{\\err}),\\ell,k,\\gamma)$.\n  \\item Return $\\sshare{g} \\cdot \\sshare{b}$.\n\\end{enumerate}\n\\paragraph{MAMBA Example:} To cast an \\verb|sfloat| register into a \\verb|sfix| one, you could execute the following:\n\\begin{lstlisting}[language={python}]\n# stores 5.5 on a sfix register\n# v, p, z, s, err are extracted from x and l, k, gamma are system parameters\nx = sfix(sfloat(5.5))\n\\end{lstlisting}\n\n\\msubsection{SQRT Functions}\n\\todo{These functions are only currently supported in their fixed point versions.}\nThe original description of the protocols for the fixed point square root algorithm are included in:\n\\begin{itemize}\n  \\item Secure Distributed Computation of the Square Root and Applications, {\\em ISPEC 2012}\n        \\cite{Liedel12}.\n\\end{itemize}\nThe floating point variant is in\n\\begin{itemize}\n  \\item Secure Computation on Floating Point Numbers {\\em NDSS 2013} \\cite{ABZS13}.\\todo{This is not currently implemented}\n\\end{itemize}\nAdditionally, we provide a simplified implementation for the Square Root on fixed point variables, that is appropriate for inputs of any size. We make use Liedel's protocol, when the input's size makes it possible, as we explain later in this section.\nBoth algorithms makes use of two constants\n\\[ \\alpha = -0.8099868542, \\quad \\beta  =  1.787727479.  \\]\nThese are the solutions of the system of equations\n\\begin{align*}\n  E(x)                       & = \\frac{\\alpha \\cdot x+\\beta-\\frac{1}{\\sqrt{x}}}{\\frac{1}{\\sqrt{x}}}, \\\\\n  M                          & = \\frac{\\sqrt{3}}{3} \\cdot \\sqrt{\\frac{-\\beta}{\\alpha}}\n  \\cdot \\left(\\frac{2}{3} \\cdot\\beta\n  -\\frac{\\sqrt{3}}{\\sqrt{\\frac{-\\beta}{\\alpha}}}\n  \\right),                                                                                           \\\\\n  E\\left( \\frac{1}{2}\\right) & = E(1) = -M.\n\\end{align*}\n\n\\msubsubsection{$\\mathsf{ParamFxSqrt}(\\sshare{x},k,f)$:}\nThis algorithm uses the sub-algorithm $\\mathsf{LinAppSQ}$ defined below, note that \\verb|LinAppSQ| returns an scaled $1/\\sqrt{x} \\cdot 2^{f}$.\nThe algorithm only works when $3 \\cdot k -2 \\cdot f$ is less than the system precision, which is by default equal to $20$.\nIn a future release we will extend the sqrt function to cope with other input ranges.\n\\begin{enumerate}\n  \\item $\\theta \\asn \\ceil{\\log_2 (k/5.4)}$.\n  \\item $\\sshare{y_0} \\asn \\mathsf{LinAppSQ}(\\sshare{x},k,f)$.\n  \\item $\\sshare{y_0} \\asn \\sshare{y_0} \\cdot 1/2^{f}$.\n  \\item $\\sshare{g_0} \\asn \\sshare{y_0} \\cdot \\sshare{x}$.\n  \\item $\\sshare{g_0} \\asn \\sshare{y_0} \\cdot 1/2^{f}$.\n        %\\item $\\sshare{g_0} \\asn \\mathsf{TruncPr}(\\sshare{g_0},k,f)$.\n        %\\item $\\sshare{h_0} \\asn \\mathsf{FxDiv}(\\sshare{g_0},2,k,f)$.\n  \\item $\\sshare{g_0} \\asn \\sshare{y_0} \\cdot 1/2$.\n  \\item $\\sshare{gh_0} \\asn \\sshare{g_0} \\cdot \\sshare{h_0}$.\n        %\\item $\\sshare{gh} \\asn \\mathsf{TruncPr}(\\sshare{gh},k,f)$.\n  \\item $\\sshare{g} \\asn \\sshare{g_0}$.\n  \\item $\\sshare{h} \\asn \\sshare{h_0}$.\n  \\item $\\sshare{gh} \\asn \\sshare{gh_0}$.\n  \\item For $i \\in[1,\\ldots,\\theta-2]$ do\n        \\begin{enumerate}\n          \\item $\\sshare{r} \\asn 3/2-\\sshare{gh}$.\n          \\item $\\sshare{g} \\asn \\sshare{g} \\cdot \\sshare{r}$.\n          \\item $\\sshare{h} \\asn \\sshare{h} \\cdot \\sshare{r}$.\n                %\\item $\\sshare{g} \\asn \\mathsf{TruncPr}(\\sshare{g},k,f)$.\n                %\\item $\\sshare{h} \\asn sf{TruncPr}(\\sshare{h},k,f)$.\n          \\item $\\sshare{gh} \\asn \\sshare{g} \\cdot \\sshare{h}$.\n                %\\item $\\sshare{gh} \\asn \\mathsf{TruncPr}(\\sshare{gh},k,f)$.\n        \\end{enumerate}\n  \\item $\\sshare{r} \\asn 3/2-\\sshare{gh}$.\n  \\item $\\sshare{h} \\asn \\sshare{h} \\cdot \\sshare{r}$.\n        %\\item $\\sshare{h} \\asn \\mathsf{TruncPr}(\\sshare{h},k,f)$.\n  \\item $\\sshare{H} \\asn 4 \\cdot (\\sshare{h}^2)$.\n  \\item $\\sshare{H} \\asn \\sshare{H}\\cdot \\sshare{x}$.\n  \\item $\\sshare{H} \\asn (3) - \\sshare{H}$.\n  \\item $\\sshare{H} \\asn \\sshare{h} \\cdot \\sshare{H}$.\n  \\item $\\sshare{g} \\asn \\sshare{H} \\cdot \\sshare{x}$.\n        %\\item $\\sshare{g} \\asn \\mathsf{FxDiv}(\\sshare{g},2,k,f)$.\n        %\\item $\\sshare{g} \\asn \\mathsf{TruncPr}(\\sshare{g},4 \\cdot k,4 \\cdot f)$.\n  \\item Return $\\sshare{g}$.\n\\end{enumerate}\n\n\\msubsubsection{$\\mathsf{SimplifiedFxSqrt}(\\sshare{x}, k, f)$:}\nThis algorithm uses the sub-algorithm $\\mathsf{NormSQ}$ defined above. Among the values it returns, we base our approximation by directly using $w =2^{m/2}$. From that point it approximates the  value of $\\sqrt{x}$ by calculating $\\frac{x}{2^{m/2}}$. To avoid any loss of precision, we reuse \\verb|sfix| instantiation process.\nThe algorithm work on the precision of the system and can solve values on any range. Its behaviour is still experimental. The function is designed in such a way that there is no restriction on the size $f$.\n\\begin{enumerate}\n  \\item $\\theta \\asn \\max{(\\ceil{\\log_2(k)},6)}$.\n  \\item $\\sshare{m_{odd}}, \\sshare{w} \\asn \\mathsf{SimplifiedNormSQ}(\\sshare{x},k)$.\n  \\item $\\sshare{m_{odd}} \\asn (1 - 2 \\cdot \\sshare{m_{odd}}) \\cdot (f \\quad \\% \\quad 2)$.\n  \\item $\\sshare{w} \\asn (2 \\cdot \\sshare{w} -\\sshare{w}) \\cdot (1 - \\sshare{m_{odd}}) \\cdot (f \\quad \\% \\quad 2) + \\sshare{w}$.\n  \\item $\\sshare{w} \\asn sfix( \\sshare{w} \\cdot 2 ^{\\frac{f - f \\quad \\% \\quad 2}{2}})$.\n  \\item $\\sshare{w} \\asn (\\sqrt{2}\\cdot \\sshare{w} - \\sshare{w})\\cdot \\sshare{m_{odd}} + \\sshare{w}$.\n  \\item $\\sshare{y_0} \\asn \\frac{1}{\\sshare{w}} $.\n  \\item $\\sshare{g_0} \\asn \\sshare{y_0} \\cdot \\sshare{x}$.\n  \\item $\\sshare{g_0} \\asn \\sshare{y_0} \\cdot 1/2$.\n  \\item $\\sshare{gh_0} \\asn \\sshare{g_0} \\cdot \\sshare{h_0}$.\n  \\item $\\sshare{g} \\asn \\sshare{g_0}$.\n  \\item $\\sshare{h} \\asn \\sshare{h_0}$.\n  \\item $\\sshare{gh} \\asn \\sshare{gh_0}$.\n  \\item For $i \\in[1,\\ldots,\\theta-2]$ do\n        \\begin{enumerate}\n          \\item $\\sshare{r} \\asn 3/2-\\sshare{gh}$.\n          \\item $\\sshare{g} \\asn \\sshare{g} \\cdot \\sshare{r}$.\n          \\item $\\sshare{h} \\asn \\sshare{h} \\cdot \\sshare{r}$.\n                %\\item $\\sshare{g} \\asn \\mathsf{TruncPr}(\\sshare{g},k,f)$.\n                %\\item $\\sshare{h} \\asn sf{TruncPr}(\\sshare{h},k,f)$.\n          \\item $\\sshare{gh} \\asn \\sshare{g} \\cdot \\sshare{h}$.\n                %\\item $\\sshare{gh} \\asn \\mathsf{TruncPr}(\\sshare{gh},k,f)$.\n        \\end{enumerate}\n  \\item $\\sshare{r} \\asn 3/2-\\sshare{gh}$.\n  \\item $\\sshare{h} \\asn \\sshare{h} \\cdot \\sshare{r}$.\n        %\\item $\\sshare{h} \\asn \\mathsf{TruncPr}(\\sshare{h},k,f)$.\n  \\item $\\sshare{H} \\asn 4 \\cdot (\\sshare{h}^2)$.\n  \\item $\\sshare{H} \\asn \\sshare{H}\\cdot \\sshare{x}$.\n  \\item $\\sshare{H} \\asn (3) - \\sshare{H}$.\n  \\item $\\sshare{H} \\asn \\sshare{h} \\cdot \\sshare{H}$.\n  \\item $\\sshare{g} \\asn \\sshare{H} \\cdot \\sshare{x}$.\n        %\\item $\\sshare{g} \\asn \\mathsf{FxDiv}(\\sshare{g},2,k,f)$.\n        %\\item $\\sshare{g} \\asn \\mathsf{TruncPr}(\\sshare{g},4 \\cdot k,4 \\cdot f)$.\n  \\item Return $\\sshare{g}$.\n\\end{enumerate}\n\n\\msubsubsection{$\\mathsf{FxSqrt}(\\sshare{x}, k \\asn \\mathtt{sfix.k}, f \\asn \\mathtt{sfix.f})$:}\nOur \\verb|FxSqrt| functionality returns the square root of any fixed point input. It receives an input value $\\sshare{x}$, from which it calculates the square root, and optional parameters regarding its bit-length and bit-wise precision. The functionality is going to make use of our \\verb|SimplifiedFxSqrt| process by default, and the somewhat more efficient Liedel's method instead when the $3 \\cdot k - 2 \\cdot f < \\mathtt{sfix.f}$ bound, provided by his paper, is met.\n\n\\begin{enumerate}\n  \\item if $(3 \\cdot k - 2 \\cdot f >= \\mathtt{sfix.f})$:\n        \\begin{enumerate}\n          \\item Return $\\mathsf{SimplifiedFxSqrt}(\\sshare{x}, k, f)$.\n        \\end{enumerate}\n  \\item else:\n        \\begin{enumerate}\n          \\item $\\sshare{x} \\asn Trunc(\\sshare{x} \\cdot 2^{f}, sfix.k, sfix.k-sfix.f)$\n          \\item Return $\\mathsf{ParamFxSqrt}(\\sshare{x}, k, f)$.\n        \\end{enumerate}\n\\end{enumerate}\n\n\\paragraph{MAMBA Example:} To obtain the \\verb|sqrt| of any value, you could execute the following:\n\\begin{lstlisting}[language={python}]\nfrom Compiler import mpc_math\nk = 5\nf = 2\n\nx = sfix(6.25)\ny = sfix(144)\nz = sfix (257.5)\n\n# returns the sqrt of the number, i.e. 2.5\n# inputs have to be expressed such that:\n# x * 2^f \\in Z_q\n# and 3*k -2*f < sfix.f (system precision)\n# by default system precision is 20 bits.\na = mpc_math.sqrt(x, k, f)\n\n# when you don't specify k and f, the system uses\n# the default sfix values, and hence the simplified\n# version for any value range, at the cost of an\n# additional division call.\n\nb = mpc_math.sqrt(y)\nc = mpc_math.sqrt(z)\n\n\\end{lstlisting}\n\n\\msubsubsection{$\\mathsf{LinAppSQ}(\\sshare{b},k,f)$:}\nWe based this section on the contents of the original paper, \\cite{Liedel12}.\nHowever we corrected the typos from the original work, the result is as follows:\n\\begin{enumerate}\n  \\item $\\alpha \\asn (-0.8099868542) \\cdot 2^k$.\n  \\item $\\beta \\asn (1.787727479) \\cdot 2^{2\\cdot k}$.\n  \\item $(\\sshare{c},\\sshare{v},\\sshare{m},\\sshare{W}) \\asn \\mathsf{NormSQ}(\\sshare{b},k,f)$.\n  \\item $\\sshare{w} \\asn \\alpha \\cdot \\sshare{c}+\\beta$.\n  \\item $\\sshare{m} \\asn \\mathsf{Mod2}(\\sshare{m},\\ceil{\\log_2 k})$.\n  \\item $\\sshare{w} \\asn \\sshare{w} \\cdot \\sshare{W} \\cdot \\sshare{v}$.\n  \\item $\\sshare{w} \\asn \\mathsf{FxDiv}(\\sshare{w},2^{f/2},w.k,w.f)$.\n  \\item $\\sshare{w} \\asn \\mathsf{FxDiv}(\\sshare{w},2^{3 \\cdot k - 2 \\cdot f},w.k,w.f)$.\n        %\\item $\\sshare{w} \\asn \\mathsf{TruncPr}(\\sshare{w},3\\cdot k, 3 \\cdot k - 2 \\cdot f)$.\n  \\item $\\sshare{w} \\asn (1-\\sshare{m}) \\cdot \\sshare{w} \\cdot 2^f\n          +(\\sqrt{2} \\cdot 2^f) \\cdot \\sshare{m}\\cdot \\sshare{w}$.\n  \\item Return $\\sshare{w}$ % \\asn \\mathsf{TruncPr}(\\sshare{w},k,f)$.\n\\end{enumerate}\n\n\n\\msubsubsection{$\\mathsf{FLSqrt}((\\sshare{v_1},\\sshare{p_1},\\sshare{z_1},\\sshare{s_1},\\sshare{\\err_1}))$:}\n  Below we let $\\ell_0$ denote the lsb of $\\ell$,\n$(v_\\alpha,p_\\alpha,z_\\alpha,s_\\alpha)$\n  (resp.  $(v_\\beta,p_\\beta,z_\\beta,s_\\beta)$)\n  denote the floating point representation of the constant $\\alpha$ (resp. $\\beta$)\n  given above,\n  and $v_{\\sqrt{2}}$ and $p_{\\sqrt{2}}$ represent the $\\ell$-bit significand and exponent of\n$\\sqrt{2}$ in floating point representation.\n  \\begin{enumerate}\n    \\item $\\sshare{b} \\asn \\mathsf{BitDec}(\\sshare{p_1},\\ell,1)$.\n    \\item $\\sshare{c} \\asn \\mathsf{XOR}(\\sshare{b},\\ell_0)$.\n    \\item $\\sshare{p} \\asn 2^{-1} \\cdot (\\sshare{p_1}-\\sshare{b})\n            +\\floor{\\ell/2}+\\mathsf{OR}(\\sshare{b},\\ell_0)$.\n    \\item $(\\sshare{v_2},\\sshare{p_2},\\sshare{z_2},\\sshare{s_2},\\sshare{\\err_2})\n            \\asn \\mathsf{FLMult}((\\sshare{v_1},-\\ell,0,0,0),(v_\\alpha,p_\\alpha,z_\\alpha,s_\\alpha,0))$.\n    \\item $(\\sshare{v_0},\\sshare{p_0},\\sshare{z_0},\\sshare{s_0},\\sshare{\\err_0})\n            \\asn \\mathsf{FLAdd}((\\sshare{v_2},\\sshare{p_2},\\sshare{z_2},\\sshare{s_2},\\sshare{\\err_2}),(v_\\beta,p_\\beta,z_\\beta,s_\\beta,0))$.\n    \\item $(\\sshare{v_g},\\sshare{p_g},\\sshare{z_g},\\sshare{s_g},\\sshare{\\err_g})\n            \\asn \\mathsf{FLMult}((\\sshare{v_1},-\\ell,0,0,0),(\\sshare{v_0},\\sshare{p_0},\\sshare{z_0},\\sshare{s_0},\\sshare{\\err_0}))$.\n    \\item  $(\\sshare{v_h},\\sshare{p_h},\\sshare{z_h},\\sshare{s_h},\\sshare{\\err_h})\n            \\asn   (\\sshare{v_0},\\sshare{p_0}-1,\\sshare{z_0},\\sshare{s_0},\\sshare{\\err_0})$.\n    \\item For $i \\in [1,\\ldots,\\ceil{\\ell/5.4}-1]$ do\n          \\begin{enumerate}\n            \\item $(\\sshare{v_2},\\sshare{p_2},\\sshare{z_2},\\sshare{s_2},\\sshare{\\err_2})\n                    \\asn \\mathsf{FLMult}(\n                    (\\sshare{v_g},\\sshare{p_g},\\sshare{z_g},\\sshare{s_g},\\sshare{\\err_g}),\n                    (\\sshare{v_h},\\sshare{p_h},\\sshare{z_h},\\sshare{s_h},\\sshare{\\err_h})\n                    )$.\n            \\item $(\\sshare{v_2},\\sshare{p_2},\\sshare{z_2},\\sshare{s_2},\\sshare{\\err_2})\n                    \\asn \\mathsf{FLSub}(\n                    (3 \\cdot 2^{\\ell-2},-(\\ell-1),0,0,0),\n                    (\\sshare{v_2},\\sshare{p_2},\\sshare{z_2},\\sshare{s_2},\\sshare{\\err_2})\n                    )$.\n            \\item $(\\sshare{v_g},\\sshare{p_g},\\sshare{z_g},\\sshare{s_g},\\sshare{\\err_g})\n                    \\asn \\mathsf{FLMult}(\n                    (\\sshare{v_g},\\sshare{p_g},\\sshare{z_g},\\sshare{s_g},\\sshare{\\err_g}),\n                    (\\sshare{v_2},\\sshare{p_2},\\sshare{z_2},\\sshare{s_2},\\sshare{\\err_2})\n                    )$.\n            \\item $(\\sshare{v_h},\\sshare{p_h},\\sshare{z_h},\\sshare{s_h},\\sshare{\\err_h})\n                    \\asn \\mathsf{FLMult}(\n                    (\\sshare{v_h},\\sshare{p_h},\\sshare{z_h},\\sshare{s_h},\\sshare{\\err_h}),\n                    (\\sshare{v_2},\\sshare{p_2},\\sshare{z_2},\\sshare{s_2},\\sshare{\\err_2})\n                    )$.\n          \\end{enumerate}\n    \\item $(\\sshare{v_{h^2}},\\sshare{p_{h^2}},\\sshare{z_{h^2}},\\sshare{s_{h^2}},\\sshare{\\err_{h^2}})\n            \\asn \\mathsf{FLMult}(\n            (\\sshare{v_h},\\sshare{p_h},\\sshare{z_h},\\sshare{s_h},\\sshare{\\err_h}),\n            (\\sshare{v_h},\\sshare{p_h},\\sshare{z_h},\\sshare{s_h},\\sshare{\\err_h})\n            )$.\n    \\item $(\\sshare{v_2},\\sshare{p_2},\\sshare{z_2},\\sshare{s_2},\\sshare{\\err_2})\n            \\asn \\mathsf{FLMult}(\n            (\\sshare{v_1},-\\ell,0,0,0),\n            (\\sshare{v_{h^2}},\\sshare{p_{h^2}},\\sshare{z_{h^2}},\\sshare{s_{h^2}},\\sshare{\\err_{h^2}})$.\n    \\item $(\\sshare{v_2},\\sshare{p_2},\\sshare{z_2},\\sshare{s_2},\\sshare{\\err_2})\n            \\asn \\mathsf{FLSub}(\n            (3 \\cdot 2^{\\ell-2},-(\\ell-1),0,0,0),\n            (\\sshare{v_2},\\sshare{p_2}+1,\\sshare{z_2},\\sshare{s_2},\\sshare{\\err_2})\n            )$.\n    \\item $(\\sshare{v_h},\\sshare{p_h},\\sshare{z_h},\\sshare{s_h},\\sshare{\\err_h})\n            \\asn \\mathsf{FLMult}(\n            (\\sshare{v_h},\\sshare{p_h},\\sshare{z_h},\\sshare{s_h},\\sshare{\\err_h}),\n            (\\sshare{v_2},\\sshare{p_2},\\sshare{z_2},\\sshare{s_2},\\sshare{\\err_2})\n            )$.\n    \\item $(\\sshare{v_2},\\sshare{p_2},\\sshare{z_2},\\sshare{s_2},\\sshare{\\err_2})\n            \\asn \\mathsf{FLMult}(\n            (\\sshare{v_1},-\\ell,0,0,0),\n            (\\sshare{v_h},\\sshare{p_h}+1,\\sshare{z_h},\\sshare{s_h},\\sshare{\\err_h})\n            )$.\n    \\item $(\\sshare{v_2},\\sshare{p_2},\\sshare{z_2},\\sshare{s_2},\\sshare{\\err_2})\n            \\asn \\mathsf{FLMult}(\n            (\\sshare{v_2},\\sshare{p_2},\\sshare{z_2},\\sshare{s_2},\\sshare{\\err_2})\n            (2^{\\ell-1} \\cdot (1-\\sshare{c}) + v_{\\sqrt{2}} \\cdot \\sshare{c},\n            -(1-\\sshare{c}) \\cdot (\\ell-1)+p_{\\sqrt{2}} \\cdot \\sshare{c},0,0,0)$.\n    \\item $\\sshare{p} \\asn (\\sshare{p_2}+\\sshare{p}) \\cdot (1-\\sshare{z_1})$.\n    \\item $\\sshare{v} \\asn \\sshare{v_2} \\cdot (1-\\sshare{z_1})$.\n    \\item $\\sshare{\\err} \\asn \\mathsf{OR}(\\sshare{\\err_2},\\sshare{s_1})$.\n    \\item Return $(\\sshare{v},\\sshare{p},\\sshare{z_1},\\sshare{s_1},\\sshare{\\err})$.\n  \\end{enumerate}\n  \\todo{Have we picked up $\\err$ correctly here?}\n\n  \\msubsection{EXP and LOG Functions}\n  \\todo{These functions are only currently supported in their fixed point versions.}\n\n  A secure fixed point exponentiation and logarithm algorithm is not found anywhere, so\n  this is our own one derived from the identities in the book.\n  \\begin{itemize}\n    \\item {\\em Computer Approximations} by Hart from 1968 \\cite{Hart:1978:CA:540084}.\n  \\end{itemize}\n  The floating point variants are in\n  \\begin{itemize}\n    \\item Secure Computation on Floating Point Numbers {\\em NDSS 2013} \\cite{ABZS13}.\n  \\end{itemize}\n  Once we have defined $\\mathsf{FxExp2}$ and $\\mathsf{FxLog2}$\n  (resp. $\\mathsf{FLExp2}$ and $\\mathsf{FLLog2}$) we can\n  define the following functions from the usual identities\n  for non-secret values of the base $b$:\n  \\begin{align*}\n    \\log_b x & = (\\log_b 2) \\cdot \\mathsf{Log2}(x),       \\\\\n    x^y      & = \\mathsf{Exp2}(y \\cdot \\mathsf{Log2}(x)), \\\\\n    \\exp   x & = \\mathsf{Exp2}(x \\cdot \\log_2 e),         \\\\\n  \\end{align*}\n  Note, that the functions on these section require specific \\verb|sfloat| parametrization, in accordance to the algorithms in this section. They support secret shared \\verb|sfix| $x$ ad $y$, as well as public floating point or integer inputs.  We can define these operations as follows:\n\n  \\msubsubsection{$\\mathsf{FxExp2}(\\sshare{a},k,f)$:}\n  This algorithm computes $2^a$ as a fixed point calculation.\n  First takes the integer and fractional part of the input\n$|a/2^f|$, which we denote by $b$ and $c$.\n  We then compute $d=2^b$, which will clearly overflow\n  if $b>k-f$, but we ignore this error (if the user is stupid\n  enough to put in garbage, they get garbage out).\n  We then compute $e=2^c$, as $0 \\le c \\le 1$ via the\n  polynomial the following polynomial\\footnote{Note polynomial\n    $P_{1045}(X)$ from Hart \\cite{Hart:1978:CA:540084} is incorrect\n    and does not give an accurate result}.\n  %with coefficients\n  %\\begin{center}\n  %\\begin{tabular}{|c|c|l|}\n  %\\hline\n  %0 & 1  & +.10000 00077 44302 1686 \\\\\n  %1 & 0  & +.69314 71804 26163 82779 5756 \\\\\n  %2 & 0  & +.24022 65107 10170 64605 384 \\\\\n  %3 & -1 & +.55504 06862 04663 79157 744 \\\\\n  %4 & -2 & +.96183 41225 88046 23749 77 \\\\\n  %5 & -2 & +.13327 30359 28143 78193 29 \\\\\n  %6 & -3 & +.15510 74605 90052 57397 8 \\\\\n  %7 & -4 & +.14197 84739 97656 06711 \\\\\n  %8 & -5 & +.18633 47724 13796 7076 \\\\\n  %\\hline\n  %\\end{tabular}\n  %\\end{center}\n  %which gives a relative error of at most $10^{-12.11}$\n  %if computed exactly.\n  %The table should be read as line $(i,a,b)$ giving\n  %the $i$th coefficient of the polynomial being\n  %$b \\cdot 10^a$.\n  Our polynomial (which we produced using a Chebyshev approximation)\n  is of degree nine and has coefficients given by\n  \\begin{center}\n    \\begin{tabular}{|c|l|}\n      \\hline\n      0 & 0.99999999999998151058451       \\\\\n      1 & 0.69314718056364205693851       \\\\\n      2 & 0.24022650683729748257646       \\\\\n      3 & 0.0555041102193305250618        \\\\\n      4 & 0.0096181190501642860210497     \\\\\n      5 & 0.0013333931011014250476911     \\\\\n      6 & 0.00015395144945146697380844    \\\\\n      7 & 0.000015368748541192116946474   \\\\\n      8 & 0.0000012256971722926501833228  \\\\\n      9 & 0.00000014433329807023165258784 \\\\\n      \\hline\n    \\end{tabular}\n  \\end{center}\n  Given $d$ and $e$ one can now compute\n$2^{|a|}=2^{b+c}=2^b \\cdot 2^c=d \\cdot e$,\n  and the final dealing with the sign of $a$ can\n  be done by an inversion.\n  We denote by $\\mathsf{FxPol}(P_{1045},\\sshare{x},k,f)$ the evaluation\n  of the polynomial $P_{1045}$ on the fixed point input $\\sshare{x}$\n  where $x \\in \\Qk{f}$. This is done by Horner's rule.\n  \\begin{enumerate}\n    \\item $\\sshare{s}=\\mathsf{FxLTZ}(\\sshare{a})$.\n    \\item $\\sshare{a} \\asn (1-2 \\cdot \\sshare{s}) \\cdot \\sshare{a}$.\n    \\item $\\sshare{b} \\asn \\mathsf{Fx2Int}(\\sshare{a},k,f)$.\n    \\item $\\sshare{c} \\asn \\sshare{a}-\\mathsf{Int2Fx}(\\sshare{b},k,f)$.\n    \\item $\\sshare{d} \\asn \\mathsf{Int2Fx}(\\mathsf{Pow2}(\\sshare{b},k),k,f)$. [This will produce an invalid result if $b$ is too big, in which case the result cannot be held in an Fx in any case]\n    \\item $\\sshare{e} \\asn \\mathsf{FxPol}(P_{1045},\\sshare{c},k,f)$.\n    \\item $\\sshare{g} \\asn \\mathsf{FxMult}(\\sshare{d},\\sshare{e},k,f)$.\n    \\item $\\sshare{g^{-1}} \\asn \\mathsf{FxDiv}(2^f,\\sshare{g},k,f)$.\n    \\item $\\sshare{a} \\asn (1-\\sshare{s}) \\cdot g+ \\sshare{s} \\cdot \\sshare{g^{-1}}$.\n    \\item Return $\\sshare{a}$.\n  \\end{enumerate}\n  The above works, but we have found a little numerical\n  instability due to the division operation.\n  \\paragraph{MAMBA Example:} To obtain $2^y$ where $y$ is secret shared you could run the following:\n  \\begin{lstlisting}[language={python}]\nfrom Compiler import mpc_math\nsfloat.vlen = 15   # Length of mantissa in bits\nsfloat.plen = 10   # Length of exponent in bits\nsfloat.kappa = 4  # Statistical security parameter for floats\n\ny =sfix(4)\n\n# returns 2^4\n# extracts k and f from y\nexp2_y=mpc_math.exp2_fx(sfix(y))\n\\end{lstlisting}\n\n  \\msubsubsection{$\\mathsf{FLExp2}((\\sshare{v_1},\\sshare{p_1},\\sshare{z_1},\\sshare{s_1},\\sshare{\\err_1}))$:}\nThis method assumes that $k \\le \\ell$.\nWe do not support a method if $k > \\ell$, and so if this happens\nwe will signal an error.\n\\begin{enumerate}\n  \\item If $k>\\ell$ then $\\err_1 \\asn 1$.\n  \\item $\\max \\asn \\ceil{\\log_2(2^{k-1}-1+\\ell)-\\ell+1}$.\n  \\item $\\sshare{a} \\asn \\mathsf{LT}(\\sshare{p_1},\\max,k)$.\n  \\item $\\sshare{b} \\asn \\mathsf{LT}(\\sshare{p_1},-\\ell+1,k)$.\n  \\item $\\sshare{c} \\asn \\mathsf{LT}(\\sshare{p_1},-2 \\cdot \\ell+1,k)$.\n  \\item $\\sshare{(1-c) \\cdot a} \\asn (1-\\sshare{c}) \\cdot \\sshare{a}$.\n  \\item $\\sshare{p_2} \\asn -\\sshare{(1-c) \\cdot a} \\cdot (\\sshare{b} \\cdot \\ell +\\sshare{p_1})$.\n  \\item $\\sshare{x},\\sshare{2^{p_2}} \\asn \\mathsf{Trunc}(\\sshare{v_1},\\ell,\\sshare{p_2})$.\n  \\item $\\sshare{y} \\asn \\sshare{v_1}-\\sshare{x} \\cdot \\sshare{2^{p_2}}$.\n  \\item $\\sshare{d} \\asn \\mathsf{EQZ}(\\sshare{y},\\ell)$.\n  \\item $\\sshare{b \\cdot s_1} \\asn \\sshare{b} \\cdot \\sshare{s_1}$.\n  \\item $\\sshare{(1-d) \\cdot s_1} \\asn (1-\\sshare{d}) \\cdot \\sshare{s_1}$.\n  \\item $\\sshare{x} \\asn (1-\\sshare{b \\cdot s_1})\n          \\cdot (\\sshare{x}-\\sshare{(1-d)\\cdot s_1})\n          +\\sshare{b \\cdot s_1} \\cdot(2^\\ell-1+\\sshare{d}-\\sshare{x})$.\n  \\item $\\sshare{y} \\asn \\sshare{(1-d) \\cdot s_1} \\cdot (\\sshare{2^{p_2}}-\\sshare{y})\n          + (1-\\sshare{s_1})\\cdot \\sshare{y}$.\n  \\item $\\sshare{w} \\asn \\sshare{(1-c) \\cdot a} \\cdot\n          ((1-\\sshare{b}) \\cdot\\sshare{x}+\\sshare{b \\cdot s_1})\n          \\cdot (1-2\\cdot \\sshare{s_1})-\\sshare{c} \\cdot \\sshare{s_1}$.\n  \\item $\\sshare{u} \\asn \\sshare{(1-c) \\cdot a}\n          \\cdot (\\sshare{b} \\cdot \\sshare{x}\n          +(1-\\sshare{b}) \\cdot 2^\\ell \\cdot \\mathsf{Inv}(\\sshare{2^{p_2}})\n          \\cdot \\sshare{y})\n          +(2^\\ell-1)\\cdot \\sshare{c} \\sshare{s_1}$.\n  \\item $\\sshare{u_\\ell},\\ldots,\\sshare{u_1} \\asn \\mathsf{BitDec}(\\sshare{u},\\ell,\\ell)$.\n  \\item For $i \\in [1,\\ldots,\\ell]$ do\n        \\begin{enumerate}\n          \\item~ [In this loop $(cv_i,cp_i,0,0)$ represents the floating point number $2^{2^{-i}}$].\n          \\item $\\sshare{a_i} \\asn 2^{\\ell-1} \\cdot (1-\\sshare{u_i})+cv_i \\cdot \\sshare{u_i}$.\n          \\item $\\sshare{b_i} \\asn -(\\ell-1) \\cdot (1-\\sshare{u_i})+cp_i \\cdot \\sshare{u_i}$.\n        \\end{enumerate}\n  \\item $(\\sshare{v_u},\\sshare{p_i},0,0)\n          \\asn \\mathsf{FLProd}((\\sshare{a_1},\\sshare{b_1},0,0), \\ldots,\n          (\\sshare{a_\\ell},\\sshare{b_\\ell},0,0))$.\n          [This implements a product of $\\ell$ floating point values, which is\n            performed via a binary tree style method.]\n  \\item $\\sshare{p} \\asn \\sshare{a} \\cdot (\\sshare{w}+\\sshare{p_u})\n          +2^{k-1}\\cdot (1-\\sshare{a}) \\cdot (1-2 \\sshare{s_1})$.\n  \\item $\\sshare{v} \\asn 2^{\\ell-1} \\cdot \\sshare{z_1}+(1-\\sshare{z_1}) \\cdot \\sshare{v_u}$.\n  \\item $\\sshare{p} \\asn -\\sshare{z_1} \\cdot (\\ell-1)\n          +(1-\\sshare{z_1}) \\cdot \\sshare{p}$.\n  \\item $\\sshare{\\err} \\asn \\sshare{\\err_1} +  \\mathsf{FlowDetect}(\\sshare{p})$\n  \\item Return $(\\sshare{v},\\sshare{p},0,0,\\sshare{\\err})$.\n\\end{enumerate}\n\n\\msubsubsection{$\\mathsf{FxLog2}(\\sshare{a},k,f)$:}\nWe first map $a$ to a value $v$ in the interval $[1/2,1]$ by essentially\nconverting to a floating point number.\nSo we a have $a=(v/2^k) \\cdot 2^p$ where $v, p \\in \\Zk$,\nand $v/2^k \\in [1/2,1]$.\nThus we have\n$\\log_2 a = p+\\log_2 (v/2^k)$, and we then treat $v$ as a fixed\npoint number and apply the Pade approximation $P_{2524}/Q_{2524}$\nfrom Hart's book \\cite{Hart:1978:CA:540084},\nwhich produces an {\\em absolute} error of $10^{-8.32}$.\nWe denote by $\\mathsf{FxPade}(P_{2524},Q_{2524},\\sshare{x},k,f)$ the evaluation\nof the rational function $P_{2524}/Q_{2524}$ on the fixed point input $\\sshare{x}$\nwhere $x \\in \\Qk{f}$.\nThe Pade approximation is given be the rational function defined\nby the following table\n\\begin{center}\n  \\begin{tabular}{|c|c|c|l|}\n    \\hline\n    P & 0 & 1 & -.20546 66719 51 \\\\\n    P & 1 & 1 & -.88626 59939 1  \\\\\n    P & 2 & 1 & +.61058 51990 15 \\\\\n    P & 3 & 1 & +.48114 74609 89 \\\\\n    Q & 0 & 0 & +.35355 34252 77 \\\\\n    Q & 1 & 1 & +.45451 70876 29 \\\\\n    Q & 2 & 1 & +.64278 42090 29 \\\\\n    Q & 3 & 1 & +.1              \\\\\n    \\hline\n  \\end{tabular}\n\\end{center}\n\n\\begin{enumerate}\n  \\item $(\\sshare{v},\\sshare{p},\\sshare{z},\\sshare{s},\\sshare{\\err})\n          \\asn \\mathsf{Fx2FL}(\\mathsf{a},k,f,k,k)$.\n  \\item $\\sshare{a} \\asn \\mathsf{FxPade}(P_{2524},Q_{2524},\\sshare{v},k,k)$.\n  \\item $\\sshare{a} \\asn \\sshare{a}+\\sshare{p} + f$.\n  \\item $\\sshare{a} \\asn \\sshare{a} \\cdot (1-\\sshare{z}) \\cdot (1-\\sshare{s}) \\cdot (1-\\cdot \\sshare{\\err})$.\n  \\item Return $\\sshare{a}$.\n\\end{enumerate}\n\n\\paragraph{MAMBA Example:} To obtain \\verb|log2|$(x)$ where $y$ is secret shared you could run the following:\n\\begin{lstlisting}[language={python}]\nfrom Compiler import mpc_math\nsfloat.vlen = 15   # Length of mantissa in bits\nsfloat.plen = 10   # Length of exponent in bits\nsfloat.kappa = 4  # Statistical security parameter for floats\n\nx =sfix(4)\n# extracts k and f from y\n# returns log_2(4)\nlog2_x=mpc_math.log2_fx(sfix(x))\n\\end{lstlisting}\nNote, internally \\verb+log2_fx+ uses a polynomial to approximate the logarithm, but it uses the \\verb+sfloat+ arithmetic to do this.\nThus, you need to set up \\verb+sfloat+ and \\verb+sfix+ correctly for this to work.\nIn particular if you look deep inside the code there is the following cryptic remark in relation to \\verb+log2_fx+...\n\\begin{verbatim}\n     # Note that sfloat and sfix sizes have to be parametrized correctly,\n     # such that sfix k > sfix.f >= sfloat vlen. This is not the case by default.\n\\end{verbatim}\n\n\n\\msubsubsection{$\\mathsf{FLLog2}((\\sshare{v_1},\\sshare{p_1},\\sshare{z_1},\\sshare{s_1},\\sshare{\\err_1}))$:}\n  In the following algorithm $(cv_i,cp_i,0,0)$ represents the floating point\n  constant $(2 \\cdot \\log_2 e)/(2 \\cdot i+1)$.\n  \\begin{enumerate}\n    \\item $M \\asn \\ceil{ \\ell/(2 \\cdot \\log_2 3)-1/2}$.\n    \\item $(\\sshare{v_2},\\sshare{p_2},0,0,0) \\asn \\mathsf{FLSub}((2^{\\ell-1},-(\\ell-1),0,0,0),(\\sshare{v_1},-\\ell,0,0,0))$.\n    \\item $(\\sshare{v_3},\\sshare{p_3},0,0,0) \\asn \\mathsf{FLAdd}((2^{\\ell-1},-(\\ell-1),0,0,0),(\\sshare{v_1},-\\ell,0,0,0))$.\n    \\item $(\\sshare{v_y},\\sshare{p_y},0,0,0) \\asn \\mathsf{FLDiv}((\\sshare{v_2},\\sshare{p_2},0,0,0),(\\sshare{v_3},\\sshare{p_3},0,0,0))$.\n    \\item $(\\sshare{v_{y^2}},\\sshare{p_{y^2}},0,0,0) \\asn \\mathsf{FLMult}((\\sshare{v_y},\\sshare{p_y},0,0,0),(\\sshare{v_y},\\sshare{p_y},0,0,0))$.\n    \\item $(\\sshare{v},\\sshare{p},0,0,0) \\asn  \\mathsf{FLMult}((\\sshare{v_y},\\sshare{p_y},0,0),(cv_0,cp_0,0,0))$.\n    \\item For $i \\in[1,\\ldots,M]$ do\n          \\begin{enumerate}\n            \\item $(\\sshare{v_y},\\sshare{p_y},0,0,0) \\asn \\mathsf{FLMult}((\\sshare{v_y},\\sshare{p_y},0,0,0),(\\sshare{v_{y^2}},\\sshare{p_{y^2}},0,0,0))$.\n            \\item $(\\sshare{v_2},\\sshare{p_2},0,0,0) \\asn \\mathsf{FLMult}((\\sshare{v_y},\\sshare{p_y},0,0,0),(cv_i,cp_i,0,0,0))$.\n            \\item $(\\sshare{v},\\sshare{p},0,0,0) \\asn \\mathsf{FLAdd}((\\sshare{v},\\sshare{p},0,0,0),(\\sshare{v_2},\\sshare{p_2},0,0,0))$.\n          \\end{enumerate}\n    \\item $(\\sshare{v_2},\\sshare{p_2},\\sshare{z_2},\\sshare{s_2},\\sshare{\\err_2}) \\asn \\mathsf{Int2FL}(\\ell,-\\sshare{p},\\ell,\\ell)$.\n    \\item $(\\sshare{v},\\sshare{p},\\sshare{z},\\sshare{s},\\sshare{\\err}) \\asn \\mathsf{FLSub}((\\sshare{v_2},\\sshare{p_2},\\sshare{z_2},\\sshare{s_2},\\sshare{\\err_2}),(\\sshare{v},\\sshare{p},0,0,0))$.\n    \\item $\\sshare{a} \\asn \\mathsf{EQ}(\\sshare{p_1},-(\\ell-1),k)$.\n    \\item $\\sshare{b} \\asn \\mathsf{EQ}(\\sshare{v_1},2^{\\ell-1},\\ell)$.\n    \\item $\\sshare{z} \\asn \\sshare{a} \\cdot \\sshare{b}$.\n    \\item $\\sshare{v} \\asn \\sshare{v} \\cdot(1-\\sshare{z})$.\n    \\item $\\sshare{\\err} \\asn \\mathsf{OR}(\\sshare{\\err},\\sshare{\\err_1})$.\n    \\item $\\sshare{\\err} \\asn \\mathsf{OR}(\\mathsf{OR}(\\sshare{z_1},\\sshare{s_1}),\\err)$.\n    \\item $\\sshare{p} \\asn \\sshare{p} \\cdot(1-\\sshare{z})$.\n    \\item Return $(\\sshare{v},\\sshare{p},\\sshare{z_1},\\sshare{s_1},\\sshare{\\err})$.\n  \\end{enumerate}\n\n\n  \\msubsection{Trigonometic Functions}\n  All three basic trigonometric functions support inputs of either\n  fixed point or floating point precision.\n  With the output type being equal to the input type.\n  The computation of $\\sin(x)$ and $\\cos(x)$ are performed\n  using polnoymial approximations, with the computation of $\\tan(x)$\n  done via $\\sin(x)/\\cos(x)$.\n  The basic idea for $\\sin(x)$ and $\\cos(x)$ is to first reduce\n  the argument $x$ into the range $[0,\\ldots,2 \\pi)$, so\n  as to obtain a new argument (which we call $y$)\n  We then compute a bit $b_1$ to test as to whether\n$y \\in [0,\\pi)$ or $[\\pi,2 \\pi)$ (with $0$ being\n  the former).\n  We then reduce $y$ to $z$ by reducing it into the range\n$[0,\\pi)$, and compute a bit $b_2$ which says whether\n$z$ is in the range $[0,\\pi/2)$ or $[\\pi/2,\\pi)$.\n  We finally reduce $z$ into the range $[0,\\pi/2)$ resulting\n  in $w$.\n  Then a polynomial is used to compute\n$\\sin(w)$ or $\\cos(w)$, which means\n  we need to now {\\em scale} $w$ into the range $[0,1)$\n  to obtain $v$.\n  %We then derive the final result using the following\n  %identities:\n  %\\begin{align*}\n  %\t\\sin(x) &= \\sin(y) = (1-2 \\cdot b_1) \\cdot \\sin(z), %\\\\\n  %\t\\cos(x) &= \\cos(y) = (1-2 \\cdot b_1) \\cdot \\cos(z), %\\\\\n  %\t\\sin(z) &= (1-b_2) \\cdot \\sin(w) + b_2\\cdot \\cos(w), %\\\\\n  %\t\\cos(z) &= (1-b_2) \\cdot \\cos(w) - b_2\\cdot \\sin(w).\n  %\\end{align*}\n  For the polynomial approximations to the basic functions in\n  the range $[0,\\pi/2)$, where the argument is given as $w = v \\cdot \\pi/2$\n  we use the following approximations from Hart's book \\cite{Hart:1978:CA:540084}\n  \\begin{align*}\n    \\sin(w) & = v \\cdot P_{3307}(v^2), \\\\\n    \\cos(w) & = P_{3508}(v^2).\n  \\end{align*}\n  Where we have\n  \\begin{center}\n    \\begin{tabular}{|c||c|l||c|l|}\n      \\hline\n         & \\multicolumn{2}{c||}{$P_{3307}$} & \\multicolumn{2}{c|}{$P_{3508}$}                                                 \\\\\n      \\hline\n      0  & 1                                & +.15707 96326 79489 66192 31314 989 & 0   & +.99999 99999 99999 99999 99914 771 \\\\\n      1  & 0                                & -.64596 40975 06246 25365 51665 255 & 0   & -.49999 99999 99999 99999 91637 437 \\\\\n      2  & -1                               & +.79692 62624 61670 45105 15876 375 & -1  & +.41666 66666 66666 66653 10411 988 \\\\\n      3  & -2                               & -.46817 54135 31868 79164 48035 89  & -2  & -.13888 88888 88888 88031 01864 15  \\\\\n      4  & -3                               & +.16044 11847 87358 59304 30385 5   & -4  & +.24801 58730 15870 23300 45157     \\\\\n      5  & -5                               & -.35988 43235 20707 78156 5727      & -6  & -.27557 31922 39332 25642 1489      \\\\\n      6  & -7                               & +.56921 72920 65732 73962 4         & -8  & +.20876 75698 16541 25915 59        \\\\\n      7  & -9                               & -.66880 34884 92042 33722           & -10 & -.11470 74512 67755 43239 4         \\\\\n      8  & -11                              & +.60669 10560 85201 792             & -13 & +.47794 54394 06649 917             \\\\\n      9  & -13                              & -.43752 95071 18174 8               & -15 & -.15612 26342 88277 81              \\\\\n      10 & -15                              & +.25002 85418 9303                  & -18 & +.39912 65450 7924                  \\\\\n      \\hline\n    \\end{tabular}\n  \\end{center}\n  NOTE: Polynomial tables are described by the monomial number, the degree of the approximation $p$ and its significand $s$. The coefficient of the $i$th monomial can be obtained by multiplying the significand by $10^{p_{i}}$ as follows: $s_{i} \\cdot 10^{p_{i}}$.\n\n  \\msubsubsection{$\\mathsf{F\\star TrigSub}(\\sshare{x})$:}\n  \\begin{enumerate}\n\n    \\item $\\sshare{f} \\asn \\mathsf{F\\star Mult}(\\sshare{x},(1 /(2 \\cdot \\pi))$\n    \\item $\\sshare{f} \\asn \\mathsf{F\\star Floor}(\\sshare{f})$.\n    \\item $\\sshare{y} \\asn \\mathsf{F\\star Mult}(\\sshare{f},(2 \\cdot \\pi ))$.\n    \\item $\\sshare{y} \\asn \\mathsf{F\\star Add}(\\sshare{x},-\\sshare{y})$.\n    \\item $\\sshare{b_1} \\asn \\mathsf{F\\star GE}(\\sshare{y},(\\pi))$.\n    \\item $\\sshare{f} \\asn \\mathsf{F\\star Add}(2 \\cdot \\pi,-\\sshare{y})$\n    \\item $w \\asn \\mathsf{F\\star Choose}(\\sshare{f},\\sshare{y}, \\sshare{b_1})$.\n    \\item $\\sshare{b_2} \\asn \\mathsf{F\\star GE}(\\sshare{2},(\\pi / 2))$.\n    \\item $\\sshare{f} \\asn \\mathsf{F\\star Add}( \\pi,-\\sshare{w})$\n    \\item $w \\asn \\mathsf{F\\star Choose}(\\sshare{f},\\sshare{w}, \\sshare{b_2})$.\n    \\item Return $(\\sshare{w},\\sshare{b_1},\\sshare{b_2})$.\n\n  \\end{enumerate}\n\n  \\paragraph{MAMBA Example:} To reduce the angle you could execute the following (note that this function call is meant to be used internally):\n  \\begin{lstlisting}[language={python}]\nfrom Compiler import mpc_math\nx = sfix(4) # sfloat(4)\n# returns an angle in the [0,pi/2) interval in w and flags b1 and b2.\nw, b1, b2 = mpc_math.sTrigSub_fx(x)\n\\end{lstlisting}\n\n  \\msubsubsection{$\\mathsf{F\\star Sin}(\\sshare{x})$}\n  We present these routines as generic routines given the specific helper subroutine above;\n  we assume an obvious overloading/translation of arguments.\n  We let $\\mathsf{F\\star Choose}(\\sshare{x},\\sshare{y},\\sshare{b})$, for a\n  shared bit $b$, denote an operation which produces $\\sshare{x}$ if $\\sshare{b}=1$\n  and $\\sshare{y}$ otherwise\n  This is easily obtained by securely multiplying each component share\n  of the data representing $\\sshare{x}$ etc by $\\sshare{b}$.\n  So for fixed point representations this becomes, irrespective of the\n  values $k$ and $f$,\n  \\begin{enumerate}\n    \\item $\\sshare{a} \\asn \\sshare{b}\\cdot \\sshare{x}+(1-\\sshare{b}) \\cdot \\sshare{y}$\n  \\end{enumerate}\n  For floating point representations this becomes\n  \\begin{enumerate}\n    \\item $\\sshare{w}, \\sshare{b_1}, \\sshare{b_2} \\asn \\mathsf{F\\star TrigSub}(\\sshare{x})$\n    \\item $\\sshare{v} \\asn \\sshare{w} \\cdot (1/(\\pi/2))$.\n    \\item $\\sshare{b} \\asn \\mathsf{F\\star Choose}(\\sshare{-1},\\sshare{1}, \\sshare{b_1})$.\n    \\item $\\sshare{\\sin(v)} \\asn \\sshare{v} \\cdot \\mathsf{F\\star Pol}(P_{3307},\\sshare{v^2})$.\n    \\item Return $(\\sshare{b} \\cdot \\sshare{\\sin(v)})$.\n  \\end{enumerate}\n  %\n  %Given this we can now compute $\\sin(x)$ in the following lines:\n  %\\begin{enumerate}\n  %\\item $(\\sshare{\\sin(w)},\\sshare{\\cos(w)},\\sshare{b_1},\\sshare{b_2}) \\asn \\mathsf{F\\star TrigSub}(\\sshare{x})$.\n  %\\item $\\sshare{\\sin(z)} \\asn \\mathsf{F\\star Choose}(\\sshare{\\sin(w)},\\sshare{\\cos(w)},1-\\sshare{b_2})$.\n  %\\item $\\sshare{-\\sin(z)} \\asn \\mathsf{F\\star Neg}(\\sshare{\\sin(z)}$.\n  %\\item $\\sshare{\\sin(x)} \\asn \\mathsf{F\\star Choose}(\\sshare{\\sin(z)},\\sshare{-\\sin(z)},1-\\sshare{b_1})$.\n  %\\item Return $\\sshare{\\sin(x)}$.\n  %\\end{enumerate}\n\n  \\paragraph{MAMBA Example:} To obtain the \\verb|sin| of any value, you could execute the following:\n  \\begin{lstlisting}[language={python}]\nfrom Compiler import mpc_math\nx = sfix(4) # sfloat(4)\n# returns the sin of a number of any interval\ny = mpc_math.sin(x)\n\\end{lstlisting}\n\n  \\msubsubsection{$\\mathsf{F\\star Cos}(\\sshare{x})$}\n  Likewise this becomes\n  \\begin{enumerate}\n\n    \\item $\\sshare{w}, \\sshare{b_1}, \\sshare{b_2} \\asn \\mathsf{F\\star TrigSub}(\\sshare{x})$\n    \\item $\\sshare{v} \\asn \\sshare{w}$.\n    \\item $\\sshare{b} \\asn \\mathsf{F\\star Choose}(\\sshare{-1},\\sshare{1}, \\sshare{b_2})$.\n    \\item $\\sshare{\\cos(v)} \\asn  \\mathsf{F\\star Pol}(P_{3308},\\sshare{v^2})$.\n    \\item Return $(\\sshare{b} \\cdot \\sshare{\\cos(v)})$.\n\n  \\end{enumerate}\n\n  \\paragraph{MAMBA Example:} To obtain the \\verb|sin| of any value, you could execute the following:\n  \\begin{lstlisting}[language={python}]\nfrom Compiler import mpc_math\nx = sfix(4) # sfloat(4)\n# returns the cos of an angle on any interval\ny = mpc_math.cos(x)\n\\end{lstlisting}\n\n  \\msubsubsection{$\\mathsf{F\\star Tan}(\\sshare{x})$}\n  Likewise this becomes\n  \\begin{enumerate}\n\n    \\item $(\\sshare{w},\\sshare{b_1},\\sshare{b_2}) \\asn \\mathsf{F\\star TrigSub}(\\sshare{x})$.\n    \\item $\\sshare{v} \\asn \\sshare{w} \\cdot (1/(\\pi/2))$.\n    \\item $\\sshare{b} \\asn \\mathsf{F\\star Choose}(\\sshare{-1},\\sshare{1}, \\sshare{b_1})$.\n    \\item $\\sshare{\\sin(v)} \\asn \\sshare{v} \\cdot \\mathsf{F\\star Pol}(P_{3307},\\sshare{v^2})$.\n    \\item $\\sshare{\\sin(x)} \\asn (\\sshare{b} \\cdot \\sshare{\\sin(v)})$.\n    \\item $\\sshare{v} \\asn \\sshare{w}$.\n    \\item $\\sshare{b} \\asn \\mathsf{F\\star Choose}(\\sshare{-1},\\sshare{1}, \\sshare{b_2})$.\n    \\item $\\sshare{\\cos(v)} \\asn  \\mathsf{F\\star Pol}(P_{3308},\\sshare{v^2})$.\n    \\item $\\sshare{\\sin(x)} \\asn (\\sshare{b} \\cdot \\sshare{\\cos(v)})$.\n    \\item $\\sshare{\\tan(x)} \\asn \\mathsf{F\\star Div}(\\sshare{\\sin(x)},\\sshare{\\cos(x)})$.\n    \\item Return $\\sshare{\\tan(x)}$.\n  \\end{enumerate}\n\n  \\paragraph{MAMBA Example:} To obtain the \\verb|tan| of any value, you could execute the following:\n  \\begin{lstlisting}[language={python}]\nfrom Compiler import mpc_math\nx = sfix(4) # sfloat(4)\n# returns the tan of an angle on any interval\ny = mpc_math.tan(x)\n\\end{lstlisting}\n\n  \\msubsection{Inverse Trigonometric Functions}\n  \\todo{Given that SCALE-MAMBA currently only supports square root operations for sfix inputs,\n    inverse trigonometric functions are restricted to sfix inputs.}\n  To obtain  $\\arcsin$ and $\\arccos$ one makes use of the formula:\n  \\begin{align*}\n    \\arcsin (x) & = \\arctan \\left( \\frac{x}{\\sqrt{1-x^2}} \\right), \\\\\n    \\arccos (x) & = \\frac{\\pi}{2} - \\arcsin (x).\n  \\end{align*}\n  Note, that $\\arcsin$ and $\\arccos$ are only defined when\n$|x|\\le 1$.\n  The value of $\\arctan(x)$ is however defined for all real $x$.\n  For $\\arctan(x)$ we first reduce to positive values of $x$ by using the formula\n  \\[ \\arctan(-x) = - \\arctan(x). \\]\n  We then reduce to the interval $[0,1)$ using the formula\n  \\[ \\arctan(x) = \\frac{\\pi}{2} - \\arctan\\left(\\frac{1}{x} \\right). \\]\n  The final approximation to $\\arctan(x)$ for $x \\in [0,1)$\n  is obtained using the Pade approximation $P_{5102}/Q_{5102}$\nfrom Hart's book \\cite{Hart:1978:CA:540084}.\nWhere the polynomials are represented as in our earlier\ndescriptions.\n\\begin{center}\n  \\begin{tabular}{|c||c|l||c|l|}\n    \\hline\n      & \\multicolumn{2}{c||}{$P_{5102}$} & \\multicolumn{2}{c|}{$Q_{5102}$}                                               \\\\\n    \\hline\n    0 & 5                                & +.21514 05962 60244 19331 93254 468 & 5 & +.21514 05962 60244 19331 93298 234 \\\\\n    1 & 5                                & +.73597 43380 28844 42408 14980 706 & 5 & +.80768 78701 15592 48851 76713 209 \\\\\n    2 & 6                                & +.10027 25618 30630 27849 70511 863 & 6 & +.12289 26789 09278 47762 98743 322 \\\\\n    3 & 5                                & +.69439 29750 03225 23370 59765 503 & 5 & +.97323 20349 05355 56802 60434 387 \\\\\n    4 & 5                                & +.25858 09739 71909 90257 16567 793 & 5 & +.42868 57652 04640 80931 84006 664 \\\\\n    5 & 4                                & +.50386 39185 50126 65579 37791 19  & 5 & +.10401 13491 56689 00570 05103 878 \\\\\n    6 & 3                                & +.46015 88804 63535 14711 61727 227 & 4 & +.12897 50569 11611 09714 11459 55  \\\\\n    7 & 2                                & +.15087 67735 87003 09877 17455 528 & 2 & +.68519 37831 01896 80131 14024 294 \\\\\n    8 & -1                               & +.75230 52818 75762 84445 10729 539 & 1 & +.1                                 \\\\\n    \\hline\n  \\end{tabular}\n\\end{center}\n\nThe following protocol for \\verb|arcsin| implements the formulas from before.\nThe protocol and its implementation, make use of our secure implementation of Square Root.\nThis method is implemented, and it is used to derive \\verb|arccos|.\n\n\\msubsubsection{$\\mathsf{F\\star ArcSin}(\\sshare{x})$}\n\\begin{enumerate}\n  \\item $\\sshare{x^2} \\asn \\mathsf{F\\star Mult}(\\sshare{x},\\sshare{x})$.\n  \\item $\\sshare{-x^2} \\asn \\mathsf{F\\star Neg}(\\sshare{x^2})$.\n  \\item $\\sshare{1-x^2} \\asn \\mathsf{F\\star Add}(1,\\sshare{-x^2})$.\n  \\item $\\sshare{\\sqrt{1-x^2}} \\asn \\mathsf{F\\star Sqrt}(1,\\sshare{1-x^2})$.\n  \\item $\\sshare{v} \\asn \\mathsf{F\\star Div}(\\sshare{x},\\sshare{\\sqrt{1-x^2}})$.\n  \\item $\\sshare{y} \\asn \\mathsf{F\\star ArcTan}(\\sshare{v})$.\n  \\item If $\\star=\\mathsf{L}$\n        \\begin{enumerate}\n          \\item $\\sshare{|x|} \\asn \\mathsf{FLAbs}(\\sshare{x})$.\n          \\item $\\sshare{y_\\err} \\asn \\mathsf{FLGT}(\\sshare{|x|},1.0)$.\n        \\end{enumerate}\n  \\item Return $\\sshare{y}$.\n\\end{enumerate}\n\n\n\\paragraph{MAMBA Example:} To obtain the \\verb|arcSin| on the  (-1,1) interval, you could execute the following:\n\\begin{lstlisting}[language={python}]\nfrom Compiler import mpc_math\nx =sfix(0.5)\n# returns the tan of an angle on any interval\ny = mpc_math.asin(x)\n\\end{lstlisting}\n\n\n\\msubsubsection{$\\mathsf{F\\star ArcCos}(\\sshare{x})$}\n\\begin{enumerate}\n  \\item $\\sshare{y} \\asn \\mathsf{F\\star ArcSin}(\\sshare{x})$.\n  \\item $\\sshare{-y} \\asn \\mathsf{F\\star Neg}(\\sshare{y})$.\n  \\item $\\sshare{\\pi/2-y} \\asn \\mathsf{F\\star Add}(\\pi/2,\\sshare{-y})$.\n  \\item Return $\\sshare{y}$.\n\\end{enumerate}\n\n\\paragraph{MAMBA Example:} To obtain the \\verb|arcCos| of any value on the (-1,1) interval, you could execute the following:\n\\begin{lstlisting}[language={python}]\nfrom Compiler import mpc_math\nx =sfix(0.5)\n# returns the tan of an angle on any interval\ny = mpc_math.acos(x)\n\\end{lstlisting}\n\n\\msubsubsection{$\\mathsf{F\\star ArcTan}(\\sshare{x})$}\n\\begin{enumerate}\n  \\item $\\sshare{s} \\asn \\mathsf{F\\star LTZ}(\\sshare{z})$.\n  \\item $\\sshare{|x|} \\asn \\mathsf{F\\star Abs}(\\sshare{x})$.\n  \\item $\\sshare{b} \\asn \\mathsf{F\\star GT}(\\sshare{|x|},1.0)$.\n  \\item $\\sshare{v} \\asn \\mathsf{F\\star Div}(1,\\sshare{|x|})$.\n  \\item $\\sshare{v} \\asn \\mathsf{F\\star Choose}(\\sshare{|x|},\\sshare{v},1-\\sshare{b})$.\n  \\item $\\sshare{v^2} \\asn \\mathsf{F\\star Mul}(\\sshare{v},\\sshare{v})$.\n  \\item $\\sshare{y} \\asn \\mathsf{FxPade}(P_{5102},Q_{5102},\\sshare{v^2})$.\n  \\item $\\sshare{y} \\asn \\mathsf{F\\star Mul}(\\sshare{v},\\sshare{y})$.\n  \\item $\\sshare{\\pi/2-y} \\asn \\mathsf{F\\star Sub}(\\pi/2,\\sshare{y})$.\n  \\item $\\sshare{y} \\asn \\mathsf{F\\star Choose}(\\sshare{y},\\sshare{\\pi/2-y},1-\\sshare{b})$.\n  \\item $\\sshare{-y} \\asn \\mathsf{F\\star Neg}(\\sshare{y})$.\n  \\item $\\sshare{y} \\asn \\mathsf{F\\star Choose}(\\sshare{y},\\sshare{-y},1-\\sshare{s})$.\n  \\item Return $\\sshare{y}$.\n\\end{enumerate}\n\n\\paragraph{MAMBA Example:} To obtain the \\verb|arcTan| of any value, you could execute the following:\n\\begin{lstlisting}[language={python}]\nfrom Compiler import mpc_math\nx =sfix(0.5)\n# returns the tan of an angle on any interval\ny = mpc_math.atan(x)\n\\end{lstlisting}\n", "meta": {"hexsha": "cfc10db92a738f4bf5c8284e6ff92a6d97d6bfd6", "size": 113083, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Documentation/Advanced.tex", "max_stars_repo_name": "karannewatia/SCALE-MAMBA", "max_stars_repo_head_hexsha": "467b33a6c80050789204ea3ee3b5cf0113354f85", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-26T06:10:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T06:10:49.000Z", "max_issues_repo_path": "Documentation/Advanced.tex", "max_issues_repo_name": "karannewatia/SCALE-MAMBA", "max_issues_repo_head_hexsha": "467b33a6c80050789204ea3ee3b5cf0113354f85", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Documentation/Advanced.tex", "max_forks_repo_name": "karannewatia/SCALE-MAMBA", "max_forks_repo_head_hexsha": "467b33a6c80050789204ea3ee3b5cf0113354f85", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.305425032, "max_line_length": 472, "alphanum_fraction": 0.6211455303, "num_tokens": 43652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.3483901964460228}}
{"text": "\\section{Introduction}\n\nMeasurements of anomalies in potential fields, like gravity disturbances and\ntotal-field magnetic anomalies, are widely used in geophysical exploration for\ntheir low cost of acquisition.\nThese data can be surveyed using ground, airborne, shipborne, or satellite\nsystems.\nDuring ground surveys, the data are often gathered following irregular paths or\nnetworks along the surface of the terrain, leading to highly variable\nelevations in mountainous regions.\nAirborne and satellite surveys gather data along flight lines, producing\nclosely spaced measurements along almost straight lines but with larger spacing\nbetween adjacent lines.\nMeasurement height can also change because of the vertical movement of the\naircraft.\nProcessing of the data often involves interpolation onto a regular grid at\nconstant height, both to improve visualization for interpretation purposes as\nwell as to prepare the data for further processing and modelling (e.g.,\nreduction-to-the-pole, derivative calculations, upward continuation, Euler\ndeconvolution).\n\nSeveral methods exist in the literature for interpolation in two dimensions,\nfor example continuous curvature splines in tension \\citep{smith1990},\nbi-harmonic (thin-plate) splines \\citep{sandwell1987}, and kriging\n\\citep{hansen1993}.\nThese general-purpose methods have limitations when it comes to interpolating\npotential field data, namely\n(i)~they are not able to take into account the variable height of the\nobservation points and\n(ii)~the interpolating functions are not necessarily harmonic, which\nis the underlying assumption behind many processing techniques\n(e.g., upward continuation and vertical derivatives).\n\nA widely used method for interpolating gravity and magnetic data\nis the equivalent sources technique (also known as equivalent layer, radial\nbasis functions, or Green's functions interpolation).\nFirst introduced by \\citet{dampney1969}, the method consists in fitting a model\nof finite elementary sources to the data and using this model to predict new\ndata values.\nBesides interpolation, equivalent sources have been used for\nreduction-to-the-pole of magnetic data\n\\citep{silva1986, nakatsuka2006, guspi2009}, upward\ncontinuation \\citep{emilia1973, li2010}, joint processing of gravity gradient\ndata \\citep{barnes2011}, modelling the lithospheric magnetic field\n\\citep{kother2015}, recovering the magnetic induction vector from\ntotal-field magnetic anomalies \\citep{li2020}, and more.\n\nIt is also worth mentioning the least-squares collocation method\n(LSC), which is widely used in geodesy\n\\citep[][and references therein]{tscherning2015}.\nLCS is often applied to combine and interpolate different linear functionals of\nthe disturbing gravity potential (gravity anomalies, gravity disturbances,\ndeflections of the vertical, geoid height, et cetera).\nLike equivalent sources, collocation also requires the solution of a large\nlinear system of the order of the number of observed data.\nAs such, it's practical application suffers from the same computational\nchallenges.\n\nMany variants of the equivalent sources technique have been proposed, often\nattempting to obtain faster or more accurate solutions.\nThe key factors that vary between them are: (i) the type of source, (ii)\nthe location of the sources, and (iii) the solution strategy.\n\nThe most commonly used type of source is a point mass for gravity or dipole for\nmagnetics \\citep[e.g.,~][]{vonfrese1981, silva1986, mendonca1994,\nsiqueira2017}.\nHowever, right-rectangular prisms \\citep[e.g.,][]{barnes2011, jirigalatu2019,\nli2020} and tesseroids \\citep{bouman2016} have also been used successfully.\nIn fact, even point sources with a simple inverse distance function, instead of\nactual gravity or magnetic fields, can be used as\nequivalent sources \\citep{cordell1992}.\n\nThe location of sources often follows one of two strategies.\nThe most common approach is to distribute sources on a regular grid at a\nconstant depth \\citep[e.g.,~][]{leao1989, barnes2011, oliveira2013}.\nAlternatively, sources can be placed beneath each data point\n\\citep[e.g.,~][]{cordell1992, siqueira2017}.\nSome recent work by \\citet{li2020} places the sources in two overlapping layers\nat different depths.\n\nThe coefficients of the equivalent source model are often estimated through\ndamped least-squares.\nThis imposes a heavy computational load when the number of data points is\nlarge (e.g., airborne and satellite surveys).\nTo reduce the computational load, \\citet{mendonca1994} built the solution\niteratively by incorporating one data point at a time using the ``equivalent\ndata concept''.\n\\citet{leao1989} processed the input data using a moving window, only fitting the\ndata inside the window and predicting observations at its center.\n\\citet{li2010} and \\citet{barnes2011} apply different operations to generate a\nsparse representation of the sensitive matrix (respectively, wavelet\ncompression and quadtree discretization), which significantly improves the\nspeed of the least-squares solution.\n\\citet{oliveira2013} parametrized the equivalent layer as a piecewise bivariate\npolynomial function, reducing the number of parameters in the solution.\n\\citet{siqueira2017} developed an iterative solution in which the sensitivity\nmatrix is transformed into a diagonal matrix with constant terms through the\n``excess mass criterion''.\n\\citet{jirigalatu2019} applied the Gauss-FFT method to speed up the forward\nmodelling operations and solved the least-squares problem using steepest\ndescent to avoid calculating the Hessian matrix and solving linear systems.\n\nMany of the existing methods solve under-determined problems, requiring a much\nlarger number of equivalent sources than the number of data points.\nSome achieve greater efficiency by restricting their applications\nto specific data types \\citep{siqueira2017},\ninterpolating only on regular grids \\citep{leao1989},\nor requiring already gridded data \\citep{takahashi2020},\nto name a few.\nFurthermore, many of the optimizations proposed are also complex to implement\nin a computer program, limiting their wider adoption.\n\nIn the present study,\nwe propose two strategies for reducing the computational load of\nthe equivalent sources technique:\n\n\\begin{enumerate}\n    \\item Reduce the number of equivalent sources for oversampled surveys\n      through a \\emph{block-averaging} strategy while maintaining the quality\n      of the solution.\n    \\item Fit the equivalent source model iteratively along overlapping windows\n      using a \\emph{gradient boosting} algorithm \\citep{friedman2001}.\n\\end{enumerate}\n\nThe first strategy consists in dividing the survey area into horizontal blocks\nand assigning a single source to each block, located at the median horizontal\nlocation of the data points.\nFor airborne, shipborne, and satellite surveys, which are oversampled along\ntracks, this can greatly reduce the size of the inverse problem while retaining\nthe same quality of interpolation.\n\nThe gradient boosting algorithm allows us to fit the equivalent source model\niteratively by operating on individual overlapping windows.\nAs a result, our method solves several much smaller least-squares problems\ninstead of a large one.\nThis has some similarities with the strategy used by \\citet{leao1989} but\nwithout the requirement for sources and predictions to be on regular grids.\n\nThrough tests on synthetic data, we show that:\n(i)~the \\emph{block-averaged} sources are able to achieve the same accuracy as\nother traditional equivalent source layouts while using a fraction of the\nnumber of sources, and\n(ii)~the \\emph{gradient boosting} algorithm greatly reduces the computational\nmemory required to fit very large datasets without sacrificing prediction\naccuracy.\nFinally, a combination of both strategies is used to process a collection of\napproximately 1.7 million ground gravity data measurements from Australia.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Methodology}\n\n\\subsection{The equivalent sources technique}\n\nWe will follow the ``generalized equivalent sources'' of \\citet{cordell1992}\nand assume that any harmonic function $d(\\mathbf{p})$ can be approximated by a\nsum of $M$ discrete point source effects\n\n\\begin{equation}\n    d(\\mathbf{p})\n    =\n    \\sum\\limits_{j=1}^{M} \\frac{c_j}{\\left\\lVert \\mathbf{p} - \\mathbf{q}_j\n    \\right\\rVert} \\ ,\n    \\label{eq:eql-forward}\n\\end{equation}\n\n\\noindent in which\n$\\mathbf{p}$ and $\\mathbf{q}_j$ are, respectively, the position vectors in a 3D\nCartesian space of data and sources,\n$c_j$ is a scalar coefficient related to the point source located at\n$\\mathbf{q}_j$,\nand $\\lVert \\cdot \\rVert$ represents the $\\text{L}_2$ norm.\nThe horizontal and vertical distribution of sources is discussed in\nsection~\\ref{sec:source_distribution}.\n\nIn case we have values of the harmonic function at $N$ discrete points\n$\\{\\mathbf{p}_1\\ \\mathbf{p}_2\\ \\ldots\\ \\mathbf{p}_N\\}$,\nwe can write a set of $N$ equations of the form\n\n\\begin{equation}\n    d_i\n    =\n    \\sum\\limits_{j=1}^{M} \\frac{c_j}{\\left\\lVert \\mathbf{p}_i - \\mathbf{q}_j\n    \\right\\rVert}\n    \\quad \\forall i=1,2,\\ldots,N\n    \\ ,\n    \\label{eq:forward-sum}\n\\end{equation}\n\n\\noindent where $d_i$ is the calculated value at point $\\mathbf{p}_i$.\nThese equations can also be expressed in matrix form as\n\n\\begin{equation}\n    \\mathbf{d} = \\mathbf{A} \\mathbf{c} \\ ,\n    \\label{eq:linear-problem}\n\\end{equation}\n\n\\noindent where $\\mathbf{d}$ is a column vector containing the $N$ predicted\nvalues at the observation points,\n$\\mathbf{c}$ is a column vector containing the $M$ coefficients $c_j$,\nand $\\mathbf{A}$ is the $N \\times M$ Jacobian matrix,\nwhose elements are\n\n\\begin{equation}\n    a_{ij} = \\frac{1}{\\left\\lVert\\mathbf{p}_i - \\mathbf{q}_j\\right\\rVert}\n\\end{equation}\n\nFor a given set of $N$ observed data $\\mathbf{d}^o$,\nwe can find a least-squares solution to\nEq.~\\ref{eq:linear-problem} and obtain the values of\n$\\mathbf{c}$ that best fit the observations.\nThese coefficients can, in turn, be used to predict the value of the harmonic\nfunction at any other point outside of the sources by evaluating\nEq.~\\ref{eq:eql-forward}.\nGridding and upward continuation can thus be achieved by predicting values on\npoints that fall on a regular grid or at different heights, respectively.\n\n\n\\subsection{Damped least-squares solution}\n\\label{sec:eql_inversion}\n\nWe can obtain the values of the source coefficients $\\mathbf{c}$ that best\nfit the observed field values $\\mathbf{d}^o$ by minimizing the goal function\n\n\\begin{equation}\n    \\phi(\\mathbf{c}) =\n    \\left[\\mathbf{d}^o - \\mathbf{A}\\mathbf{c}\\right]\\trans\n    \\mathbf{W}\n    \\left[\\mathbf{d}^o - \\mathbf{A}\\mathbf{c}\\right]\n    + \\lambda_d\\ \\mathbf{c}\\trans\\mathbf{c}\n    \\ ,\n    \\label{eq:misfit-unscaled}\n\\end{equation}\n\n\\noindent where\n$\\mathbf{W}$ is a $N \\times N$ diagonal matrix of data weights and\n$\\lambda_d$ is a positive \\emph{damping} parameter with the same units as the\nJacobian matrix elements.\nThe second term on the right-hand side of Eq.~\\ref{eq:misfit-unscaled} is the\nzeroth-order Tikhonov regularization \\citep{tikhonov1977}, also known as a\ndamping regularization, that is used to stabilize the solution.\n\nThe damping parameter controls the amount of regularization that will be\napplied.\nAn overly large value would generate a smooth solution that fails to reproduce\nthe high frequency components of the data, while an overly small value would\nresult in over-fitting, thus failing to produce realistic interpolation results\n\\citep{martinez2016}.\nThe range of acceptable values for the damping parameter $\\lambda_d$ will\ndepend on the values of the Jacobian matrix $\\mathbf{A}$ and the coefficients.\nConsequently, this range will vary (often dramatically) between datasets,\nmaking it difficult to choose an appropriate value in practice.\n\nTo solve this issue, we first scale the Jacobian matrix so that its elements\nare dimensionless and each column has unit variance.\nWe define a diagonal matrix $\\mathbf{S}$\n\n\\begin{equation}\n    \\mathbf{S} =\n    \\begin{bmatrix}\n      \\sigma_1 & 0 & \\cdots &0 \\\\\n      0 & \\sigma_2 & \\cdots &0 \\\\\n      \\vdots & \\vdots & \\ddots & \\vdots \\\\\n      0  & 0 & \\cdots & \\sigma_M\n    \\end{bmatrix}_{M \\times M}\n    ,\n\\end{equation}\n\n\\noindent in which $\\sigma_j$ is the standard deviation of the $j$-th column of\n$\\mathbf{A}$.\nWe then write the forward problem in Eq.~\\ref{eq:linear-problem} as\n\n\\begin{equation}\n    \\mathbf{d}\n    =\n    \\mathbf{A} \\mathbf{S}\\inv \\mathbf{S} \\mathbf{c}\n    =\n    \\left[\n        \\mathbf{A} \\mathbf{S}\\inv\n    \\right]\n    \\left[\n        \\mathbf{S} \\mathbf{c}\n    \\right]\n    =\n    \\mathbf{B} \\mathbf{m}\n\\end{equation}\n\n\\noindent where $\\mathbf{B} = \\mathbf{A} \\mathbf{S}\\inv$ is the scaled and\ndimensionless Jacobian matrix\nand $\\mathbf{m} = \\mathbf{S} \\mathbf{c}$ is a vector containing scaled\ncoefficients with the same units as the data.\n\nThe goal function defined in Eq.~\\ref{eq:misfit-unscaled} can be\nrewritten as\n\n\\begin{equation}\n    \\phi(\\mathbf{m}) =\n    \\left[\\mathbf{d}^o - \\mathbf{B}\\mathbf{m}\\right]\\trans\n    \\mathbf{W}\n    \\left[\\mathbf{d}^o - \\mathbf{B}\\mathbf{m}\\right]\n    + \\lambda\\ \\mathbf{m}\\trans\\mathbf{m}\n    \\ ,\n    \\label{eq:misfit}\n\\end{equation}\n\n\\noindent where $\\lambda$ is a \\emph{dimensionless} damping parameter and\nregularization is applied on the scaled coefficients $\\mathbf{m}$ instead of\n$\\mathbf{c}$.\nUsing a dimensionless damping parameter allows us to narrow the range of values\nof $\\lambda$ that would generate the most accurate predictions, irrespective\nof the dataset and its units.\nFrom experience, we recommend searching for suitable $\\lambda$ values between\n$10^{-6}$ and $10^{4}$ varying by order-of-magnitude.\nThe choice of the damping and other hyper-parameters, like the source depth,\ncould be done through well-established statistical methods, such as\ncross-validation.\n\nThe vector of scaled coefficients $\\hat{\\mathbf{m}}$ that minimizes the goal\nfunction can be found by solving the \\emph{normal equation system}\n\\citep{menke1989}\n\n\\begin{equation}\n    \\left[\n      \\mathbf{B}\\trans \\mathbf{W} \\mathbf{B} + \\lambda \\mathbf{I}\n    \\right]\n    \\hat{\\mathbf{m}} =\n    \\mathbf{B}\\trans\\mathbf{W}\n    \\mathbf{d}^o.\n    \\label{eq:least_squares_solution}\n\\end{equation}\n\nOnce the scaled coefficients are obtained, the estimated unscaled coefficients\n$\\hat{\\mathbf{c}}$ can be calculated by removing the scaling factor\n\n\\begin{equation}\n    \\hat{\\mathbf{c}} = \\mathbf{S}\\inv \\hat{\\mathbf{m}} \\ .\n\\end{equation}\n\n\\noindent The forward modeling operations used to perform predictions\n(e.g., for interpolation and upward continuation) are left unchanged by\nusing vector $\\hat{\\mathbf{c}}$ instead of $\\hat{\\mathbf{m}}$.\n\n\n\\subsection{Gradient boosting}\n\nGradient boosting was first introduced by \\citet{friedman2001, friedman2002} as\na method for fitting additive parametric models of the form\n\n\\begin{equation}\n    d = \\sum_{k=1}^K \\alpha_k f(\\mathbf{c}_k),\n\\end{equation}\n\n\\noindent where $\\alpha_k$ is a scalar coefficient called the \\emph{step-size}\nand $f$ is a function of the parameter vector $\\mathbf{c}_k$.\nFor linear problems, these additive models can be written as the matrix\nequation\n\n\\begin{equation}\n    \\mathbf{d} = \\sum_{k=1}^K \\mathbf{A}_k \\mathbf{c}_k \\ .\n    \\label{eq:gb-linear-model}\n\\end{equation}\n\n\\noindent Because of the linearity of the $f(\\mathbf{c}_k)$ functions, the\n$\\alpha_k$ step-size parameters can be incorporated into the parameter vector\n$\\mathbf{c}_k$.\n\nWe can transform our equivalent source problem in\nEq.~\\ref{eq:linear-problem} into an additive model by following these\nsteps:\n\n\\begin{enumerate}\n  \\item Define a set of $M$ equivalent sources distributed throughout the\n    survey area (see section \\ref{sec:source_distribution} for details).\n  \\item Define a set of $K$ overlapping windows of equal size that cover the\n    survey area.\n  \\item Create $K$ separate sets of equivalent sources, one for each window.\n    Each set will be formed by the portion of the original $M$ sources that\n    fall inside the respective window.\n    Since the windows overlap, the total number of sources from all sets will\n    be greater than $M$.\n  \\item Define vector $\\mathbf{c}_k$ as the $M_k$ coefficients of the\n    equivalent sources of the $k$-th window.\n  \\item Define matrix $\\mathbf{A}_k$ as the $N \\times M_k$ Jacobian matrix\n    between the sources in the $k$-th window and all $N$ data points of the\n    survey.\n  \\item Model the predicted data as a superposition of the effects of the $K$\n    separate sets of equivalent sources (i.e., Eq.~\\ref{eq:gb-linear-model}).\n\\end{enumerate}\n\nThe gradient boosting algorithm works by fitting each component of the\nadditive model, one at a time, to the residuals of the previous component.\n\\citet{friedman2001} demonstrates that this corresponds to a steepest-descent\noptimization in the so-called ``function space''.\nThe adaptation of the gradient boosting method to find the damped least-squares\nsolutions for the $K$ parameter vectors $\\mathbf{c}_k$ in\nEq.~\\ref{eq:gb-linear-model} is presented in\nAlgorithm~\\ref{alg:gradient_boosting}.\n\n\\begin{algorithm}[!h]\n  \\DontPrintSemicolon\n  \\setstretch{1.5}\n  Define the residual vector $\\mathbf{r}_{0} = \\mathbf{d}^o$ \\;\n  \\For{ $k = 1$ \\KwTo $K$ }{\n\n\n    Calculate the $N \\times M_k$ Jacobian matrix $\\mathbf{A}_k$\n    \\;\n\n    $\\mathbf{B}_k = \\mathbf{A}_k \\mathbf{S}_k\\inv$\n    \\nllabel{alg:scale}\n    \\;\n\n    $\n     \\hat{\\mathbf{m}}_k = \\left[\\mathbf{B}_k\\trans \\mathbf{W}_k \\mathbf{B}_k +\n     \\lambda \\mathbf{I} \\right]\\inv \\mathbf{B}_k\\trans \\mathbf{W}_k\n     \\mathbf{r}_{k-1}\n    $\n    \\nllabel{alg:fit}\n    \\;\n\n    $\\hat{\\mathbf{c}}_k = \\mathbf{S}_k\\inv \\hat{\\mathbf{m}}_k$\n    \\nllabel{alg:unscale}\n    \\;\n\n    $\\mathbf{d}_k = \\mathbf{A}_k \\hat{\\mathbf{c}}_k$\n    \\nllabel{alg:predicted}\n    \\;\n\n    $\\mathbf{r}_k = \\mathbf{r}_{k - 1} - \\mathbf{d}_k$\n    \\nllabel{alg:residual}\n    \\;\n  }\n  \\BlankLine\n  \\setstretch{1}\n  \\caption{Gradient boosting solution for damped least-squares regression.}\n  \\label{alg:gradient_boosting}\n\\end{algorithm}\n\nAfter all $\\mathbf{c}_k$ coefficients vectors are estimated, we can predict the\neffect of the additive equivalent source model on any point through the\nsummation\n\n\\begin{equation}\n    d(\\mathbf{p}) =\n    \\sum\\limits_{k=1}^K \\sum\\limits_{j=1}^{M_k}\n    \\frac{{c_k}_j}{\\left\\lVert \\mathbf{p} - {\\mathbf{q}_k}_j \\right\\rVert}\n    \\ ,\n    \\label{eq:eql-forward-gb}\n\\end{equation}\n\n\\noindent\nin which ${c_k}_j$ is the $j$-th element of the $\\mathbf{c}_k$ vector and the\n${\\mathbf{q}_k}_j$ is the position vector of the $j$-th source of the $k$-th\nwindow.\n\nTo improve the convergence of the algorithm, \\citet{friedman2002} suggests\nintroducing randomness into the fitting process. We achieve this by randomizing\nthe order in which the $K$ windows are used in the gradient boosting algorithm.\nSection~\\ref{sec:gb_interpolation} explores the effect of randomization in the\nconvergence rate of the algorithm and the accuracy of the interpolation.\n\nThe $\\mathbf{A}_k$ matrices have only $N \\times M_k$ elements\n(where $M_k$ is the number sources on the $k-$th window), which can be\nconsiderably smaller than the $N \\times M$ elements of $\\mathbf{A}$.\nTherefore, the gradient boosting method allows us to fit\nequivalent source models that would produce Jacobian matrices that are larger\nthan the available computer memory.\nFurthermore, we can increase or decrease the size of the overlapping windows as\nneeded depending on the number of sources in the model and the available\ncomputer memory.\n\nWe can improve the efficiency of the algorithm further by:\n\n\\begin{enumerate}\n  \\item Using only the $N_k$ data points that fall within the $k$-th window for\n    fitting the sources (steps \\ref{alg:scale} and \\ref{alg:fit} of\n    algorithm~\\ref{alg:gradient_boosting}).\n    By doing so, we can replace the $N \\times M_k$ Jacobian matrix $\\mathbf{A}_k$\n    with the smaller $N_k \\times M_k$ matrix $\\tilde{\\mathbf{A}}_k$.\n    We still use all $N$ data points when calculating the predicted data and\n    residuals (steps \\ref{alg:predicted} and \\ref{alg:residual} of\n    algorithm~\\ref{alg:gradient_boosting}).\n  \\item The forward modeling operation performed in step \\ref{alg:predicted}\n    can be done by a summation (Eq.~\\ref{eq:forward-sum}) instead of a\n    matrix-vector product, which allows us to avoid computing and storing the\n    larger $N \\times M_k$ matrix $\\mathbf{A}_k$ at any point.\n\\end{enumerate}\n\nAlgorithm~\\ref{alg:gradient_boosting_window} is the final\n\\textit{gradient-boosted equivalent sources algorithm} which incorporates these\nchanges.\nFigure~\\ref{fig:gradient-boosting-schematics} shows a sketch of the algorithm\nsteps applied a set of observation points that simulate a ground survey and\nlocating one source below each data point.\n\n\\begin{algorithm}[!h]\n  \\DontPrintSemicolon\n  \\setstretch{1.5}\n  Define the residual vector $\\mathbf{r}_{0} = \\mathbf{d}^o$ \\;\n  \\For{ $k = 1$ \\KwTo $K$ }{\n\n    Select weights $\\tilde{\\mathbf{W}}_k$ and residuals\n    $\\tilde{\\mathbf{r}}_{k - 1}$ for data points inside the $k$-th window\n    \\;\n\n    Calculate Jacobian matrix $\\tilde{\\mathbf{A}}_k$ with data points and\n    sources inside the $k$-th window\n    \\;\n\n    $\\mathbf{B}_k = \\tilde{\\mathbf{A}}_k \\mathbf{S}_k\\inv$\n    \\;\n\n    $\n     \\hat{\\mathbf{m}}_k = \\left[\n     \\mathbf{B}_k\\trans \\tilde{\\mathbf{W}}_k \\mathbf{B}_k +\n     \\lambda \\mathbf{I} \\right]\\inv \\mathbf{B}_k\\trans \\tilde{\\mathbf{W}}_k\n     \\tilde{\\mathbf{r}}_{k-1}\n    $\n    \\;\n\n    $\\hat{\\mathbf{c}}_k = \\mathbf{S}_k\\inv \\hat{\\mathbf{m}}_k$\n    \\;\n\n    Calculate $ \\mathbf{d}_k $, where\n    $\n    {d_k}_i\n    =\n    \\sum\\limits_{j=1}^{M_k} \\dfrac{{c_k}_j}{\\left\\lVert \\mathbf{p}_i -\n        {\\mathbf{q}_k}_j\n    \\right\\rVert}\n    \\quad \\forall\\ i=1\\ \\text{to}\\ N\n    $\n    \\;\n\n    $\\mathbf{r}_k = \\mathbf{r}_{k - 1} - \\mathbf{d}_k$\n    \\;\n  }\n  \\BlankLine\n  \\setstretch{1}\n  \\caption{Gradient-boosted equivalent sources algorithm.}\n  \\label{alg:gradient_boosting_window}\n\\end{algorithm}\n\n\\begin{figure*}[tb]\n    \\centering\n    \\includegraphics[width=\\linewidth]{figs/gradient-boosting-schematics.pdf}\n    \\caption{\n        Sketch of the gradient-boosted equivalent source algorithm.\n        Data points are represented by blue upwards-facing triangles,\n        equivalent sources by orange dots, data residuals by red downwards-facing\n        triangles, and the current window by black dashed lines.\n        The algorithm starts by selecting the data and sources\n        inside the first window and estimating the source coefficients\n        using the selected data points.\n        Then, the effect of the estimated sources is predicted on all data\n        points and used to calculate the residuals.\n        Another window is used to select residuals and sources and\n        estimate the coefficients using the selected residuals instead of the\n        original data.\n        Again, the effect of the estimated sources is predicted on all data points\n        and the residuals are updated.\n        These steps are repeated for every window in a randomized order.\n    }\n    \\label{fig:gradient-boosting-schematics}\n\\end{figure*}\n\nIt is worth noting that two sets of equivalent sources obtained through two\nadjacent overlapping windows have some portion of the sources on the same\nlocations, specifically the ones that fall on the intersection between the two\nwindows.\nWe can interpret this as the gradient-boosting algorithm fitting the source\ncoefficients multiple times: one time for every window that covers each source.\nThis fact can be exploited in order to save computer memory.\nInstead of storing all of the $\\mathbf{c}_k$ vectors\n(Eq.~\\ref{eq:gb-linear-model}), we can initialize a single $\\mathbf{c}$ vector\nwith zeros, where each element represents the coefficient of each one of the\noriginal $M$ sources.\nAfter each iteration of the gradient-boosting algorithm, we add the estimated\ncoefficients $\\hat{\\mathbf{c}}_k$ to the corresponding elements of vector\n$\\mathbf{c}$.\nBecause the forward modelling function is linear, we can safely compute the\nresulting field through Eq.~\\ref{eq:eql-forward} instead of\nEq.~\\ref{eq:eql-forward-gb}.\nThis way, the memory needed to store the entire set of estimated coefficients\nis limited to a single vector of $M$ elements.\n\nOur gradient boosting algorithm for overlapping windows is similar to the\n``bootstrap inversion'' used in \\citet{vonfrese1988}, which also iteratively\nfits portions of an equivalent source model to the data residuals.\nThe key differences are that in our method:\n(i)~the sources in the overlapping portions of the windows are fitted more than\nonce, allowing the algorithm to self-correct for poor solutions to any given\nwindow;\n(ii)~we use only data points within the window when fitting, what enables the\nuse of larger datasets.\n\n\n\n\\subsection{Location of sources}\n\\label{sec:source_distribution}\n\nThe ideal number of sources and their locations, both horizontally and\nvertically, has been debated since the inception of the equivalent sources\ntechnique with \\citet{dampney1969}.\nThe choices made regarding these parameters can play an important role on the\naccuracy of the predictions and the computational resources needed to estimate\nthe source coefficients.\nAn ideal distribution of sources should simultaneously be able to reproduce the\nmeasured data on the survey points, make accurate predictions on non-surveyed\nlocations, and minimize the required computational resources.\n\nA large number of evenly distributed sources along the survey region are\ncapable of reproducing the observed data.\nNevertheless, the computational load can be prohibitive and such\nunderdetermined problems are prone to overfitting the data, leading to poor\npredictive power when interpolating and extrapolating.\nOn the other hand, using few sources will reduce the computational requirements\nbut the model may be incapable of reproducing the full spectral content of the\nmeasured data.\n\nParticular survey characteristics also play a role in the choice of equivalent\nsource distribution.\nIn a ground survey, observations are usually located along irregular paths and\nscattered points.\nThe coverage of the survey region is often uneven, leaving large areas without\nany observation.\nOn the other hand, observations from airborne surveys are located along almost\nstraight and closely spaced flight lines.\nMeasurements are usually taken at a high temporal frequency, leading to\nobservation points along the flight lines that are several times closer to each\nother than the flight line spacing.\nThis creates a bias in the sampling, which can cause aliasing artifacts in\ngridded products.\n\n\\subsubsection{Horizontal source layouts}\n\n\\begin{figure*}[tb]\n    \\includegraphics[width=\\linewidth]{figs/source-layouts-schematics.pdf}\n    \\caption{\n        Sketch of different horizontal layouts for equivalent source models.\n        Blue points represent the locations of observations and orange points\n        represent the locations of equivalent sources according to different\n        layout strategies.\n        (a)~Set of \\SourceLayoutsSchematicsObservations{} observation points\n        that simulate a ground survey.\n        (b)~Location of the \\SourceLayoutsSchematicsSourceBelowData{} sources\n        obtained through the \\emph{sources below data} layout.\n        (c)~Location of the \\SourceLayoutsSchematicsGridSources{} sources\n        obtained through the \\emph{regular grid} layout.\n        (d)~Location of the \\SourceLayoutsSchematicsBlockAveragedSources{}\n        sources obtained through the \\emph{block-averaged sources} layout.\n        Grey dashed lines represent the spatial blocks within which the median\n        observation location is calculated.\n    }\n    \\label{fig:source_layouts}\n\\end{figure*}\n\nThe most widely used layouts for distributing equivalent sources horizontally\nare:\n\n\\begin{enumerate}\n  \\item\n    \\emph{Sources below data points}: one equivalent source is placed at the\n    horizontal location of each data point (Fig.~\\ref{fig:source_layouts}b).\n    Therefore, the number of sources is equal to the number of observations\n    ($M=N$).\n  \\item\n    \\emph{Regular grid}: a homogeneous distribution of point sources below the\n    survey region (Fig.~\\ref{fig:source_layouts}c). A padding region is often\n    added to help reduce edge effects. In practice, it often leads to\n    underdetermined problems since a large number of sources is required\n    ($M>N$).\n\\end{enumerate}\n\nFor ground surveys, the \\emph{regular grid} layout needs a sufficiently\nsmall grid spacing to be able to fit the observed data.\nThis creates an unnecessarily large number of sources in areas where no\nobservations exist.\nIn contrast, the \\emph{sources below data} layout is more likely to accurately\nfit the observed data with many fewer sources, reducing the computational load.\nBut when applied to airborne surveys, the \\emph{sources below data} layout may\nplace an undesirably large number of sources along the flight paths.\nThis could lead to aliasing effects on the predicted values, such as the\nstripes parallel to flight lines that are often observed when gridding airborne\nmagnetic data.\nThe \\emph{regular grid} layout can avoid this effect by evenly\ndistributing sources and using a continuous source layer (e.g.,\nright-rectangular prisms or tesseroids).\n\nWe propose a new way of distributing equivalent sources horizontally that could\nsimultaneously reduce the computational load and mitigate some of the drawbacks\nof existing layouts.\nIn the \\emph{block-averaged sources} layout,\npoint sources are placed in the average\nposition of data points that fall within specified spatial blocks\n(Fig.~\\ref{fig:source_layouts}d).\nThis is done by:\n\n\\begin{enumerate}\n    \\item Dividing the survey region into rectangular blocks of equal size.\n    \\item \\label{item:median-position} Computing the median horizontal position\n        of the observation points that fall inside each block. Blocks without\n        any observation point are omitted.\n    \\item Assign one point source to each of the median horizontal positions\n      calculated in step \\ref{item:median-position}.\n\\end{enumerate}\n\nThe number of sources created by this new layout will be less than the number\nof observations if the block size is chosen appropriately (i.e., making sure\nthat blocks are large enough to contain more than a single data point).\nThe overdetermined problem that arises from this layout has a lower\ncomputational load and is less prone to overfitting the data since the model\ncomplexity is lower.\nMoreover, the block averaging process can balance the spacing between sources\nalong a flight line and between adjacent lines, helping to reduce aliasing\neffects in the generated grids.\nIn Section~\\ref{sec:synthetic_distributions}, we demonstrate through tests on\nsynthetic data that the block-averaged sources layout is able to interpolate\nwith comparable accuracy to other layouts while using a fraction of the\nequivalent sources.\n\n\n\\subsubsection{Depth of sources}\n\n\\begin{figure*}[tb]\n    \\includegraphics[width=\\linewidth]{figs/depth_types.pdf}\n    \\caption{\n        Examples of different strategies for assigning depths to equivalent\n        sources.\n        Here we assign one source for each\n        observation point, located at the same horizontal coordinates as the\n        data points.\n        Source depths are\n        (a)~a \\emph{constant depth} at a chosen vertical coordinate,\n        (b)~a \\emph{relative depth} determined by uniformly shifting downward\n        the vertical coordinate of data points,\n        and\n        (c)~a \\emph{variable depth} determined by shifting the vertical\n        coordinates of the observation points by an amount proportional to the\n        average distance to neighbouring sources.\n        The distance between data points and their respective sources (a)\n        depends on observation height, (b) is constant, and (c) is proportional\n        to the horizontal distribution of sources.\n        Notice how the closely spaced sources in the middle of the profile (c)\n        are shallower than their counterparts in (b).\n    }\n    \\label{fig:depth_types}\n\\end{figure*}\n\nIt is widely known from potential theory that the depth of a point source\ninfluences the wavelength of the observed field at the surface.\nThis makes the source depth a key parameter affecting the outcome of\ninterpolation and other operations done with equivalent sources.\nSeveral different strategies for assigning the depths of equivalent sources\nhave been proposed in the literature.\nHere, we will highlight the following (Fig.~\\ref{fig:depth_types}):\n\n\\begin{enumerate}\n  \\item\n    \\emph{Constant depth}:\n    The simplest option is to locate all sources at the same depth\n    (Fig.~\\ref{fig:depth_types}a).\n    If the measurements were taken at significantly different altitudes, some\n    measurements will be more distant to the sources than others,\n    which may create problems for reproducing short wavelengths in high\n    altitude points.\n \\item\n    \\emph{Relative depth}:\n    The depths of sources are determined by shifting the vertical coordinate of\n    data points downward by a fixed amount (Fig.~\\ref{fig:depth_types}b).\n    The sources will not all be at the same vertical coordinate, but they will\n    all be at the same vertical distance from the observation points.\n \\item\n    \\emph{Variable depth}:\n    The depths of sources are proportional to the horizontal distance to the\n    nearest neighbouring data points or sources (Fig.~\\ref{fig:depth_types}c).\n    Different variations of this strategy have been proposed before, for\n    example \\citet{cordell1992}, \\citet{guspi2004}, and \\citet{guspi2009}.\n    The rationale for this strategy is that if a survey has data points\n    clustered in some areas, we may\n    want the sources below those areas to be shallower in order to preserve the\n    shorter wavelengths that can be measured.\n\\end{enumerate}\n\nOur approach to the \\emph{variable depth} strategy will be:\n\n\\begin{equation}\n  z = z_{obs} + \\Delta z + \\alpha h,\n  \\label{eq:variable_depth}\n\\end{equation}\n\n\\noindent\nin which $z$ is the vertical coordinate (positive downwards) of an equivalent\nsource,\n$\\Delta z$ is a relative depth shift that is the same for all sources,\n$\\alpha$ is an dimensionless depth factor,\n$h$ is the median horizontal distance to the $k$ nearest neighbouring sources,\nand\n$z_{obs}$ is a vertical observation coordinate that will depend on the\nhorizontal layout strategy.\nFor \\emph{sources below data}, it is the vertical coordinate of the data point\ncorresponding to the given source.\nFor \\emph{regular grid}, it can be interpolated from the vertical coordinates\nof all data points.\nFinally, for \\emph{block-averaged sources} it will be the median vertical\ncoordinate of the data within the corresponding block.\n\nIn Section~\\ref{sec:synthetic_distributions}, we test the effectiveness each of\nthese strategies on synthetic data.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Tests on synthetic data}\n\n\\begin{figure*}[tb]\n    \\includegraphics[width=\\linewidth]{figs/synthetic-survey-layouts.pdf}\n    \\caption{\n        Observation heights and gravity values for the synthetic ground (a-b)\n        and airborne (c-d) surveys.\n        Heights are given in meters above the zero height plane.\n        The synthetic gravity data are contaminated with pseudo-random Gaussian\n        noise with zero mean and \\SurveyNoise{} standard deviation.\n    }\n    \\label{fig:synthetic-layouts}\n\\end{figure*}\n\n\\begin{figure}[tb]\n    \\includegraphics[width=\\linewidth]{figs/target-grid.pdf}\n    \\caption{\n        Pseudo-color map of the target grid of synthetic gravity data. The grid\n        is composed of \\TargetEastingSize{}$\\times$\\TargetNorthingSize{} points\n        with a spacing of \\TargetSpacing{}. The grid height is \\TargetHeight{}\n        above the zero height plane.\n    }\n    \\label{fig:synthetic-target}\n\\end{figure}\n\nWe have used synthetic gravity datasets to test the interpolation accuracy of\nthe difference horizontal and vertical source distribution strategies as well\nas the gradient-boosted equivalent sources method.\nTo generate the data, we created a model of \\NPrisms{} right-rectangular\nprisms,\ndistributed in a \\ModelEasting{}$\\times$\\ModelNorthing{} area with depths\nvarying between \\ModelDepth{} and zero.\nThe density contrast of prisms ranges from \\ModelMinDensity{} to\n\\ModelMaxDensity{}.\nThe model includes prisms of different shapes, sizes, and depths to create\ngravity disturbances with a variety of wavelengths.\n\nWe created two synthetic datasets from the model, one simulating a ground\nsurvey and another an airborne acquisition (Fig.~\\ref{fig:synthetic-layouts}).\nTo create the synthetic ground survey, we selected measurement positions from a\nportion of a public domain gravity dataset for Southern Africa, available\nthrough the NOAA National Centers for Environmental Information (NCEI).\nFor the synthetic airborne survey, we used a portion of the Great Britain\nAeromagnetic Survey acquired by Hunting Geology and Geophysics Ltd and Canadian\nAeroservices Ltd between 1955 and 1965 and made publicly available by the\nBritish Geological Survey (BGS).\nIn both cases, we rescaled the horizontal coordinates of each survey portion to\nspan an area of \\SurveyEasting{}$\\times$\\SurveyNorthing{}, matching the model\ndimensions.\nThe ground survey contains \\GroundSurveyPoints{} observations distributed at\nheights between \\GroundSurveyMinHeight{} and \\GroundSurveyMaxHeight{}\n(Fig.~\\ref{fig:synthetic-layouts}a).\nThe airborne survey has \\AirborneSurveyPoints{} observations at heights between\n\\AirborneSurveyMinHeight{} and \\AirborneSurveyMaxHeight{}\n(Fig.~\\ref{fig:synthetic-layouts}c).\n\nThe vertical component of the gravitational acceleration generated by the\nmodel was computed  using the method of \\citet{nagy2000, nagy2002}\nwith recent modifications by \\citet{fukushima2020},\nas implemented in the open-source software Harmonica \\citep{harmonica2020}.\nWe generated a \\emph{target grid} of\n\\TargetEastingSize{}$\\times$\\TargetNorthingSize{} points with a spacing of\n\\TargetSpacing{} and located \\TargetHeight{} above the zero height plane\n(Fig.~\\ref{fig:synthetic-target}) to serve as a reference when calculating the\ninterpolation error.\nWe then generated synthetic ground (Fig.~\\ref{fig:synthetic-layouts}b) and\nairborne (Fig.~\\ref{fig:synthetic-layouts}d) data to which we added\npseudo-random Gaussian noise with zero mean and \\SurveyNoise{} standard\ndeviation.\n\n\n\\subsection{Source distribution strategies}\n\\label{sec:synthetic_distributions}\n\n\\begin{figure*}[p]\n    \\includegraphics[width=\\linewidth]{figs/ground_survey_differences.pdf}\n    \\caption{\n        Pseudo-color maps of the differences between the target grid and the\n        interpolated synthetic ground survey data produced by each source\n        distribution strategy.\n        The black dots represent the horizontal location of the synthetic data\n        points. The RMS error and total number of equivalent sources is\n        reported for each strategy at the top of the respective maps.\n    }\n    \\label{fig:ground-survey-differences}\n\\end{figure*}\n\n\\begin{figure*}[p]\n    \\includegraphics[width=\\linewidth]{figs/airborne_survey_differences.pdf}\n    \\caption{\n        Pseudo-color maps of the differences between the target grid and the\n        interpolated synthetic airborne survey data produced by each source\n        distribution strategy.\n        The black dots represent the horizontal location of the synthetic data\n        points. The RMS error and total number of equivalent sources is\n        reported for each strategy at the top of the respective maps.\n    }\n    \\label{fig:airborne-survey-differences}\n\\end{figure*}\n\nWe investigated the effect on interpolation accuracy of different strategies\nfor distributing the equivalent sources horizontally and vertically.\nTo do this, we used the damped least-squares solution described in\nSection~\\ref{sec:eql_inversion} (without gradient boosting) to interpolate the\nsynthetic datasets (Fig.~\\ref{fig:synthetic-layouts}) and compared the results\nagainst the target grid (Fig.~\\ref{fig:synthetic-target}).\nThis process was repeated for each combination of horizontal layout\n(\\emph{sources below data} and \\emph{block-averaged sources}) and depth type\n(\\emph{constant}, \\emph{relative}, and \\emph{variable}) and for regular grid\nsources with a constant depth, totalling 7 different combinations.\n\nEach source distribution strategy requires certain hyper-parameters to be\nchosen in order to build the set of point sources.\nFor example, using a constant depth needs the definition of the depth and using\nblock-averaged sources requires the definition of the block size.\nThe predictive capabilities of the equivalent sources depend on the choice of\nthese hyper-parameters.\nTo ensure that our comparisons are fair, we perform an exhaustive search over\ncombinations of hyper-parameter values (including the damping parameter from\nEq.~\\ref{eq:misfit}) to obtain the best prediction that can be achieved by each\nsource distribution strategy.\nHere, the best prediction is defined as the one that minimizes the root\nmean-square error (RMS) between interpolated values and the target grid\n(Fig.~\\ref{fig:synthetic-target}).\nThe parameter values used in these searches and the one producing the smallest\nRMS error are outlined in Tables~\\ref{tab:parameters-ground-survey}\nand~\\ref{tab:parameters-airborne-survey}.\n\nFig.~\\ref{fig:ground-survey-differences}\nand~\\ref{fig:airborne-survey-differences} show the differences between the\ntarget grid and the best prediction achieved by each source distribution\nstrategy for the ground and airborne synthetic surveys, respectively.\nFor the synthetic ground survey, the horizontal layouts produced similar RMS\nvalues of approximately 0.8\\mGal{} regardless of the depth type, with the\nexception of the regular grid layout which produced a larger RMS of\n\\BestGroundGridSourcesConstantDepthRms{}\\mGal{}.\nThe differences between the target grid and the interpolated values are larger\nin regions of poor data coverage.\nEdge effects are present for all strategies but are noticeably smaller for the\ncombination of block-averaged sources with a variable depth based on the\nnearest neighbour distance.\nFor the synthetic airborne survey, all strategies (including the regular grid)\nproduced similar RMS errors of approximately 0.3\\mGal{}.\nThe maps of the differences between the target grid and interpolation results\nare visually indistinguishable from each other.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\subsection{Window size and overlap in gradient boosting}\n\\label{sec:window_size_and_overlap}\n\nWe assessed the trade-offs in interpolation accuracy and computation time of\nthe gradient-boosted equivalent sources algorithm as a function of the two key\ncontrolling factors: the window size and the amount of overlap between adjacent\nwindows.\nThe comparisons were performed against a regular least-squares solution\n(Eq.~\\ref{eq:least_squares_solution}) using the synthetic airborne data\n(Fig.~\\ref{fig:synthetic-layouts}c-d).\nTo avoid biasing the results, we used the same locations of equivalent sources\nfor both the regular and gradient-boosted interpolations, namely\nblock-averaged sources with a block size of\n\\BestAirborneBlockAveragedSourcesRelativeDepthSpacing\\m{} and a\nrelative depth of\n\\BestAirborneBlockAveragedSourcesRelativeDepthDepth\\m{}.\n\n\\subsubsection{Window size}\n\\label{sec:window_size}\n\nThe size of the windows controls the size of the Jacobian matrices\n$\\tilde{\\mathbf{A}}_k$ by limiting the number of data points and equivalent\nsources used in each step of the gradient-boosting algorithm\n(Alg.~\\ref{alg:gradient_boosting_window}).\nThus, using smaller windows will reduce the total amount of computer memory\nrequired to estimate the source coefficients.\nNevertheless, smaller windows may produce less accurate interpolations by\nfailing to achieve the global minimum of the goal function in\nEq.~\\ref{eq:misfit}.\nThe window size might also impact the computation time in non-intuitive ways\nsince smaller windows generate smaller least-squares problems but also require\nmore gradient-boosting iterations.\n\nWe calculated the interpolation RMS error (between the interpolated grid and\nthe target grid in Fig.~\\ref{fig:synthetic-target}) and computation time for a\nfixed window overlap of 50\\% and several window sizes.\nTo avoid any biases introduced by the shuffling of windows, the calculations\nwere repeated using different seeds for the pseudo-random number generator used\nin the shuffling.\nFig.~\\ref{fig:gradient-boosted-comparison}a shows the RMS error and\nFig.~\\ref{fig:gradient-boosted-comparison}c shows the computation time\nrequired for estimating the source coefficients, both as functions of\nthe window size.\n\n\\begin{figure*}[tb]\n    \\includegraphics[width=\\linewidth]{figs/gradient-boosted-comparisons.pdf}\n    \\caption{\n        Interpolation RMS error (a-b) and relative computation time (c-d) for\n        regular least-squares equivalent sources (orange dashed lines) and\n        gradient-boosted equivalent sources (blue dots and error bars).\n        Window overlap is given as a percentage of the window size (an overlap\n        of 50\\% means that two adjacent windows share an area half of the size\n        of the entire window).\n        For gradient-boosting, the RMS errors and computation times are the\n        means (error bars are 1 standard deviation) of results using different\n        seeds for the pseudo-random number generator.\n        Computation time is the ratio between the time required to estimate the\n        source coefficients for the gradient-boosted and the regular equivalent\n        sources.\n}\n    \\label{fig:gradient-boosted-comparison}\n\\end{figure*}\n\nThese results show that the interpolation error for gradient-boosting is\ngenerally larger than the error for regular equivalent sources.\nThe error decreases asymptotically to within $\\sim 40\\%$ of the regular\nequivalent sources for windows with an area greater than $\\sim 10\\%$ of the\nsurvey area.\nThe computation time similarly decreases with window size, with the\ngradient-boosting being generally faster than the regular equivalent sources\nfor windows with an area greater than $\\sim 5\\%$ of the survey area.\nAs the window size increases, both RMS error and computation time appear to\nstabilize to nearly constant levels.\n\n\\subsubsection{Window overlap}\n\nThe amount of overlap between adjacent windows plays an important role in the\nperformance of the gradient-boosted equivalent sources.\nIt controls the number of iterations and how many times a particular source is\nused in the least-squares fitting process.\nThe experiments in the previous section showed that 50\\% overlap was\nsufficient to achieve acceptable interpolation accuracy.\nHowever, we studied separately the impacts of the amount of window overlap on\nboth accuracy and computation time.\n\nWe performed a similar experiment to the one in section~\\ref{sec:window_size}\nbut this time kept the window size fixed to \\BoostOverlappingWindowSize{} and\nvaried the amount of overlap from 0\\% to 95\\% with a step size of 5\\%.\nAll other experimental procedures remained unchanged.\nFig.~\\ref{fig:gradient-boosted-comparison}b shows the RMS error and\nFig.~\\ref{fig:gradient-boosted-comparison}d shows the computation time\nrequired for estimating the source coefficients, both as functions of\nthe window overlap.\n\nOur results show that the interpolation RMS error decreases with the amount of\noverlap, reaching the same accuracy as the regular equivalent sources at\napproximately 90\\% overlap.\nOn the other hand, the computation time increases with the amount of overlap,\nbecoming larger than that of the regular equivalent sources for overlaps\ngreater than 70\\%.\nThis is expected since increasing the overlap adds iterations to the gradient\nboosting algorithm without decreasing the individual least-squares problem\nsizes to compensate.\n\n\n\\subsection{\n    Interpolation with gradient boosting\n}\n\\label{sec:gb_interpolation}\n\nFinally, we applied the gradient-boosted equivalent sources to interpolate the\nsynthetic airborne survey (Fig.~\\ref{fig:synthetic-layouts}).\nAs previously, we used the block-averaged sources layout with a block size of\n\\EqlBoostAirborneSpacing{}.\nBased on the results from section \\ref{sec:window_size_and_overlap}, we adopted\na window overlap of 50\\% and a window size of \\EqlBoostAirborneWindowSize{}.\n\nWe estimated the relative depth of the sources and the damping parameter by\ncomparing the predictions against the values of the target grid.\nThe search explored \\emph{depth} values between \\EqlBoostAirborneMinDepth{} and\n\\EqlBoostAirborneMaxDepth{} and \\emph{damping} values between\n\\EqlBoostAirborneMinDamping{} and \\EqlBoostAirborneMaxDamping{} by steps of one\norder of magnitude.\nThe most accurate predictions achieved a RMS error of\n\\EqlBoostAirborneRmsScore{} with a depth of \\EqlBoostAirborneDepth{} and\na damping of \\EqlBoostAirborneDamping{}.\nIt is worth noting that the RMS error achieved by the gradient-boosted\nequivalent sources is comparable to the ones obtained by the regular equivalent\nsources in Section \\ref{sec:synthetic_distributions}.\nTo highlight the importance of randomizing the order of windows in the\ngradient-boosting iterations, we preformed the interpolation once more using\nthe same values of \\emph{damping} and \\emph{depth} but this time iterating over\nwindows in sequential order (South to North, West to East).\n\n\\begin{figure}[tb]\n    \\includegraphics[width=\\linewidth]{figs/eql-boost-airborne.pdf}\n    \\caption{\n        Interpolation error for gradient-boosted equivalent sources using\n        randomized (a) and sequential (b) window order.\n        (a and b)~Pseudo-color maps of the differences between the target grid\n        and the interpolated synthetic airborne survey data.\n        The color scale has been cropped to the same range as\n        Fig.~\\ref{fig:airborne-survey-differences}.\n        (c)~Root-mean squared error after each iteration of the\n        gradient-boosting algorithm.\n}\n\\label{fig:eql-boost-airborne}\n\\end{figure}\n\nFigs.~\\ref{fig:eql-boost-airborne}a-b show the differences between the target\ngrid and the interpolation results for windows in randomized and sequential\norder, respectively.\nThe differences for randomized windows resemble those for regular least-squares\nequivalent sources seen in Figs.~\\ref{fig:ground-survey-differences} and\n\\ref{fig:airborne-survey-differences}.\nOn the other hand, the differences for sequential windows show a clear\ntrend of large negative differences in the South decreasing towards the North.\nThis trend is correlated with the order in which windows are executed, with\ndifferences decreasing in absolute value towards the end of the algorithm.\nFig.~\\ref{fig:eql-boost-airborne}c shows the RMS error of the fitting process\nafter each iteration for both window orders, clearly indicating that\na randomized window order leads to faster convergence of the algorithm.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Gridding gravity data from Australia}\n\n\\begin{figure*}[p]\n    \\includegraphics[width=\\linewidth]{figs/australia.png}\n    \\caption{\n      Pseudo-color maps of observed (a and c) and\n      interpolated (b and d) gravity disturbance of Australia.\n      The observed values in a and c are plotted as colored circles.\n      The red rectangle marks the boundaries of the highlight maps in c\n      and d.\n      Observations are part of a compilation by \\citet{wynne2018} of\n      over 1.7 million ground gravity measurements.\n      Interpolated values were obtained through gradient-boosted equivalent\n      sources and calculated on a regular grid at \\AustraliaEqlGridHeight{}\n      over the WGS84 ellipsoid.\n    }\n    \\label{fig:australia}\n\\end{figure*}\n\nThis section will demonstrate how gradient-boosted equivalent sources can be\nused to interpolate large datasets onto regular grids at uniform height.\nFor this purpose, we selected an open-access compilation of ground gravity\nsurveys over Australia made by \\citet{wynne2018} and filtered and referenced to\nthe WGS84 ellipsoid by \\citet{australia_compilation}.\nIt contains over 1.7 million data points and covers most of the Australian\nterritory at variable point spacings.\nOur goal is to create a 1~arc-minute resolution grid of gravity disturbances at\na constant geometric height of \\AustraliaEqlGridHeight{} (the largest height of\nobservations).\n\nWe computed the gravity disturbance by removing the normal gravity of\nthe WGS84 ellipsoid from the observed gravity data (Fig.~\\ref{fig:australia}).\nHere, normal gravity was computed at each observation point through the\nclosed-form formula of \\citet{ligotze2001} using the Boule software\n\\citep{boule2020}.\nFinally, we converted the observations to planar Cartesian coordinates by\napplying a Mercator projection.\n\nWe start the interpolation process by defining a set of block-averaged sources\nusing a block size of 1.8\\km{}, resulting in a total of\n\\AustraliaEqlNSources{}~point sources.\nThe block size was chosen to match the desired resolution of the final grid\n(1~arc-minute is approximately 1.8\\km{} at the equator).\nBased on the results obtained in Section~\\ref{sec:synthetic_distributions}, we\nhave chosen to use the \\emph{relative depth} strategy.\nThe window overlap was once again fixed at 50\\%.\nTo determine the size of the windows, we calculated the amount of computer memory\nneeded to store the largest Jacobian matrix for different values of window size\n(Fig.~\\ref{fig:australia-memory-cv-error}a).\nWe have chosen a size of \\AustraliaEqlWindowSize{} in order to limit the\namount of memory needed to under 16~Gigabytes.\n\n\\begin{figure}[tbh!]\n    \\makeatletter%\n    \\if@twocolumn%\n        \\includegraphics[width=\\linewidth]{figs/australia-memory-cv-error.pdf}\n    \\else% \\@twocolumnfalse\n        \\centering\n        \\includegraphics[width=0.6\\linewidth]{figs/australia-memory-cv-error.pdf}\n    \\fi\n    \\makeatother\n    \\caption{\n        (a) Amount of computer memory needed to store the largest Jacobian\n        matrix for different window sizes. Our implementation uses double\n        precision floating point numbers (64 bits) for the Jacobian.\n        (b) Root-mean square error against the observed data after each\n        iteration of the gradient-boosting algorithm.\n        (c) K-Fold cross-validation root-mean square errors obtained for each\n        pair of damping and depth parameters. The orange star highlights the\n        minimum.\n    }\n    \\label{fig:australia-memory-cv-error}\n\\end{figure}\n\nWe determined the depth of the sources and the damping parameter by applying\nK-Fold cross-validation through the scikit-learn library \\citep{sklearn2011}.\nThe method randomly divides the original data into $k$ sets (folds), fits the\nmodel using only data from $k - 1$ folds, and validates the model by comparing\nits predictions against the one remaining fold.\nThis process is carried out once for each one of the $k$ folds, leading to\nan estimated mean cross-validation RMS error for the model.\nTo speed up the computation, we only performed the cross-validation on a subset\nof the data corresponding to an area of\n\\AustraliaSmallAreaEastingSize{}$\\times$\\AustraliaSmallAreaNorthingSize{}\ncontaining \\AustraliaSmallAreaNPoints{} points.\nWe ran the cross-validation repeatedly for combinations of \\emph{depth},\nranging from \\AustraliaDepthMin{} to \\AustraliaDepthMax{},\nand \\emph{damping}, from \\AustraliaDampingMin{} to \\AustraliaDampingMax{} in\nsteps of one order of magnitude.\nFigure \\ref{fig:australia-memory-cv-error}c shows the resulting\ncross-validation RMS errors and highlights the minimum value of\n\\AustraliaEqlRmsScore{}, which corresponds to a relative depth of\n\\AustraliaEqlDepth{} and a damping equal to \\AustraliaEqlDamping{}.\n\nFinally, we proceeded to estimate the source coefficients using the entire\ndataset and the parameters previously determined.\nThe estimated source coefficients were then used to predict the values of the\ngravity disturbance on a regular grid of\n\\AustraliaEqlGridNLongitude{}$\\times$\\AustraliaEqlGridNLatitude{} points at\n\\AustraliaEqlGridHeight{} above the ellipsoid.\nOn a modest workstation with 16 cores and 16~Gigabytes of RAM,\nestimating the \\AustraliaEqlNSources{} coefficients with gradient-boosting took\n$\\sim 1.3$~hours and the prediction step took $\\sim 18$~minutes.\n\nFig.~\\ref{fig:australia} shows the original data distribution and the\ninterpolated grid.\nGrid points that are further than 50\\km{} from the nearest data point are\nmasked to avoid unrealistic extrapolations.\nFig.~\\ref{fig:australia-memory-cv-error}b shows the RMS error against the\nobserved data after each iteration of the algorithm.\nFig.~\\ref{fig:australia-residuals} shows the difference between the observed\nand predicted gravity disturbances.\nThe inset figure shows a histogram of these residuals, which are approximately\nnormally distributed around zero.\n\n\\begin{figure}[tb]\n    \\includegraphics[width=\\linewidth]{figs/australia-residuals.png}\n    \\caption{\n        Residuals. Differences between the gravity disturbance data from\n        Australia and the predicted values by the estimated equivalent sources\n        on the same observation points. The color map has been truncated to\n        improve the visualization around the largest portion of residual\n        values. The inset plot shows a histogram of the residuals.\n    }\n    \\label{fig:australia-residuals}\n\\end{figure}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Discussion}\n\n\\subsection{Location of sources}\n\nThe results of our tests on synthetic data\n(Figs.~\\ref{fig:ground-survey-differences}\nand~\\ref{fig:airborne-survey-differences}) show that there are no significant\ndifferences in interpolation accuracy between source distribution strategies,\nboth in terms of the interpolation RMS errors and from visual inspection of the\ndifference maps.\nTherefore, we conclude that all source distribution strategies are able to\nproduce comparable interpolations.\nNevertheless, the \\emph{block-averaged sources} strategy makes use of fewer\nsources when compared with other strategies, which reduces the computational\nload of estimating the sources coefficients and forward modelling.\nTo ensure that the interpolation is able to reproduce the high frequencies in\nthe data, the block size used in the averaging should be chosen to match the\ndesired grid resolution.\n\nThe choice of source depth strategy does not appear to significantly impact the\ninterpolation RMS error.\nIn the particular case of a sparse ground survey with block-averaged sources,\nthe use of a variable depth visibly reduced edge effects and artifacts in areas\nof poor data coverage.\nAt a first glance, the choice of a depth strategy would not seem to impact\nthe computation time.\nHowever, when searching for the set of hyper-parameters that produce the most\naccurate interpolation (e.g., through cross-validation), one must solve the\ninverse problem once for every possible combination of parameters.\nA depth strategy like the \\emph{variable depth} requires a higher number of\nhyper-parameters (depth shift $\\Delta z$, depth factor $\\alpha$, and the number\nof nearest neighbours $k$ from Eq.~\\ref{eq:variable_depth}) than other\nstrategies which only require a single parameter.\nHaving more parameters means increasing the dimensions of the parameter space\nand thus increasing the number of possible combinations.\nThus, we recommend using a \\emph{constant depth} or a \\emph{relative depth}\nwhen processing large datasets in order to minimize computation time.\n\n\\subsection{Gradient boosting}\n\nFrom Fig.~\\ref{fig:gradient-boosted-comparison}a\nand~\\ref{fig:gradient-boosted-comparison}c, we can see that the\ngradient-boosted equivalent sources produce slightly less accurate\ninterpolation results but are able to achieve smaller computation times than\nregular equivalent sources.\nThe reduction of the accuracy might be due to the gradient boosting algorithm\nfailing to converge to the global minimum of the goal function.\nAs the windows increase in size, interpolation error decreases because more data\npoints are included into the least-squares fitting of the source coefficients.\nAt the same time, the fitting process becomes faster because of a reduction in\nthe number of iterations.\nOur results indicate that it is desirable to maximize the window size,\nwhich can be done up to the point that the Jacobian matrices still fit within\nthe available computer memory.\n\nThe results shown in Figs.~\\ref{fig:gradient-boosted-comparison}b\nand~\\ref{fig:gradient-boosted-comparison}d indicate that using\nwindow overlap values between 40\\% and 70\\% strike a balance between\naccuracy and computation time.\nThis corroborates our initial choice of 50\\% overlap, which is good enough for\nproducing accurate predictions in reasonable times.\n\nFinally, the results in Fig.~\\ref{fig:eql-boost-airborne} highlight the\nimportance of randomizing the order in which the overlapping windows are\niterated.\nRunning the gradient boosting algorithm sequentially produces less accurate\npredictions and decreases the convergence rate of the method.\n\n\\subsection{Australia gravity data}\n\nThe application of the gradient-boosted equivalent sources to the Australian\ngravity dataset demonstrates that the method is able to interpolate and\nupward-continue large datasets in a reasonable amount of time using only modest\ncomputational resources.\nThe resulting grid (Fig.~\\ref{fig:australia}) preserves the high resolution of\nthe original data while avoiding aliasing artifacts due to the block averaging\nof the source locations.\nSome parts of the grid are smoother and have lower amplitudes than the original\ndata (e.g., some southwestern parts), which is expected from the upward\ncontinuation that was performed to have the grid at a constant height.\nFrom the cross-validation analysis on a subset of the data, we estimate that\nthe interpolation error is approximately \\AustraliaEqlRmsScore{}.\n\nThe largest residuals in Fig.~\\ref{fig:australia-residuals} are located in\nregions with high-amplitude short-wavelength features in the observed data.\nThis is expected since the method involves some degree of smoothing because of\nthe use of damping and the source depths.\nThere are also low-amplitude long-wavelength residual signals that seem to\ncoincide with some of the windows of the gradient-boosting method.\nA possible cause of these features is inability of the equivalent-sources\nwithin a window to adequately fit the long-wavelength components of the data.\nWe note, however, that all of these long-wavelength residuals are smaller than\n1\\mGal{} in amplitude and do not represent a significant source of errors.\n\nThe elongated valley around the minimum of the cross-validation RMS errors\n(Fig.~\\ref{fig:australia-memory-cv-error}c) shows that there is ambiguity in\nthe choice of damping and source depths.\nOne could choose a large damping with a small depth or a small damping with a\nlarge depth to achieve roughly the same interpolation result.\nThis is expected since both parameters control the smoothness of the\ninterpolation.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Conclusions}\n\nThe equivalent source technique has been proven to be well suited for\ninterpolating gravity disturbances and magnetic anomalies.\nThe two main reasons that make it to stand out from other 2D interpolation\nmethods is the fact that the equivalent sources take into account the height of\nthe observations and that the interpolated values will always be harmonic\nfunctions.\nThe main challenge of using equivalent sources in practice is the high\ncomputational load of estimating the coefficients of the equivalent sources,\nspecially the computer memory needed to store the Jacobian matrix.\n\nWe present two strategies that could be simultaneously applied to interpolate\ndatasets with millions of points on modest hardware:\nblock-averaging source locations, which reduces the number of equivalent\nsources needed for the interpolation,\nand the gradient-boosted equivalent source algorithm, which breaks down the\ninverse problem into smaller sets of equivalent sources defined by overlapping\nwindows.\nBoth methods were tested against synthetic datasets in order to compare their\naccuracy and how they perform in terms of computational efficiency.\n\nOur results show that the block-averaged sources reduce the computational\nload needed to estimate source coefficients in comparison to two traditional\nstrategies (placing sources below data points or on regular grids).\nWe also show that this reduction of the number of sources does not affect\nthe accuracy of the predictions.\nThe use of block-averaged sources may also prevent aliasing of the interpolated\nvalues, specially when the observations are unevenly sampled (e.g., airborne\nand shipborne surveys).\nSpecial attention must be payed when choosing the size of the blocks for\naveraging.\nAs a thumb rule, we recommend choosing a size approximately equal to\nthe resolution of the regular grid where the values will be interpolated.\n\nTests that compared strategies for the vertical location of the\nsources showed that any one of the three strategies tested\n(\\emph{constant depth}, \\emph{relative depth} and \\emph{variable depth})\nproduces comparable accuracy of interpolation.\nNevertheless, we are more prone to recommending either the \\emph{constant\ndepth} or the \\emph{relative depth} for most applications because they involve\nless hyper-parameters that would need to be configured before the actual\ninterpolation.\n\nGradient-boosted equivalent sources were shown to heavily reduce the computer\nmemory needed to estimate source coefficients, making it possible to\ninterpolate large datasets with millions of points that would otherwise produce\nJacobian matrices larger than the available memory.\nThe interpolations obtained though this new method achieve close to the same\naccuracy than the regular equivalent sources, while reducing the computation\ntime by approximately a factor of three.\nWe also show that an overlap of 50\\% between adjacent windows achieves a good\ncompromise between accuracy and computation time.\nThe size of the overlapping windows should be chosen as the maximum value\npossible that creates Jacobian matrices that still fit into computer memory.\nMoreover, randomizing the order in which the windows are iterated increases the\nconvergence rate of the algorithm and is essential to producing accurate\npredictions.\n\nThe gradient-boosting method can be used in conjunction with any horizontal\nsource layout, depth strategy, or source type (e.g., point sources, prisms,\ntesseroids) because it does not rely on assumptions about the sources.\nFuture research should investigate the application of gradient boosting to\nother equivalent source methods.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Data and code availability}\n\nThe Python source code used to produce all results and figures presented here\nis available at\n\\url{https://doi.org/10.6084/m9.figshare.13604360} and\n\\url{https://github.com/compgeolab/eql-gradient-boosted}\nunder the BSD 3-clause open-source license.\n\nThe gradient-boosted equivalent sources implementation is based on the\nequivalent source code in the Harmonica library \\citep{harmonica2020}.\nOther software used in this study includes:\nPooch \\citep{pooch2020} for downloading and caching datasets,\nVerde \\citep{verde2018} for block reductions and coordinate manipulations,\nBoule \\citep{boule2020} for normal gravity calculations,\nxarray \\citep{xarray2017} and Numpy \\citep{numpy2020} for handling\nmultidimensional arrays and numerical computations,\nNumba \\citep{numba2015} for just-in-time compilation and parallelization,\nscikit-learn \\citep{sklearn2011} for cross-validation,\nMatplotlib \\citep{matplotlib2007} and PyGMT \\citep{pygmt2020} for generating\nthe figures and maps,\nand the Jupyter notebook programming environment \\citep{jupyter2016}.\nHarmonica, Boule, Pooch, and Verde are part of the Fatiando a Terra project\n\\citep{fatiando2013}.\n\nAll datasets used are open-access and publicly available.\nThe synthetic surveys were generated using\na public domain gravity dataset for Southern Africa distributed by the\nNOAA NCEI (\\url{https://www.ngdc.noaa.gov/mgg/gravity/gravity.html})\nand the Great Britain Aeromagnetic\nSurvey distributed by the\nBritish Geological Survey (BGS) under an Open Government License\n(\\url{https://www.bgs.ac.uk/products/geophysics/aeromagneticRegional.html}).\nThe shaded relief in Fig.~\\ref{fig:australia} is the SRTM15+ dataset by\n\\citet{tozer2019}.\nThe Australian ground gravity\ndata is based on a compilation distributed by Geoscience Australia under a\nCreative Commons Attribution 4.0 International Licence \\citep{wynne2018}  which\nwas filtered and referenced to the WGS84 ellipsoid by\n\\citet{australia_compilation} and is distributed under the same license\n(\\url{https://doi.org/10.6084/m9.figshare.13643837}).\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Acknowledgements}\n\nWe are indebted to the developers and maintainers of the open-source software\nwithout which this work would not have been possible.\nWe would also like to thank Editor Frederik Simons, Assistant Editor Fern\nStorey, and two anonymous reviewers for their constructive comments.\nS.R. Soler is supported by a scholarship from CONICET, Argentina.\nThis work contains British Geological Survey materials ©~UKRI.\nS.R. Soler and L. Uieda jointly developed the initial idea, analysed the\nresults, and wrote the paper. S.R. Soler produced all results and developed the\nsoftware implementation with the assistance of L. Uieda.\n", "meta": {"hexsha": "140180c851c0c3ab98d5f86a260e935d08caa6e1", "size": 69945, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "manuscript/content.tex", "max_stars_repo_name": "compgeolab/eql-gradient-boosted", "max_stars_repo_head_hexsha": "759a0c6f34e92d83551b14c8dfaeae2a8be1e949", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2021-02-25T18:03:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T22:47:37.000Z", "max_issues_repo_path": "manuscript/content.tex", "max_issues_repo_name": "compgeolab/eql-gradient-boosted", "max_issues_repo_head_hexsha": "759a0c6f34e92d83551b14c8dfaeae2a8be1e949", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 24, "max_issues_repo_issues_event_min_datetime": "2021-02-25T15:21:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T10:29:33.000Z", "max_forks_repo_path": "manuscript/content.tex", "max_forks_repo_name": "compgeolab/eql-gradient-boosted", "max_forks_repo_head_hexsha": "759a0c6f34e92d83551b14c8dfaeae2a8be1e949", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-07-27T15:55:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-17T07:26:42.000Z", "avg_line_length": 47.1327493261, "max_line_length": 82, "alphanum_fraction": 0.7715490743, "num_tokens": 16558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.34833327806942005}}
{"text": "\\documentclass[a4paper]{article}\n\\usepackage{fullpage}\n\\usepackage{listings} %--- For including MATLAB code ---%\n    \\usepackage{color} %red, green, blue, yellow, cyan, magenta, black, white\n    \\definecolor{mygreen}{RGB}{28,172,0} % color values Red, Green, Blue\n    \\definecolor{mylilas}{RGB}{170,55,241}\n    \\lstset{language=Matlab,%\n    basicstyle=\\footnotesize\\ttfamily,\n    breaklines=true,%\n    morekeywords={matlab2tikz},\n    keywordstyle=\\color{blue},%\n    morekeywords=[2]{1}, keywordstyle=[2]{\\color{black}},\n    identifierstyle=\\color{black},%\n    stringstyle=\\color{mylilas},\n    commentstyle=\\color{mygreen},%\n    showstringspaces=false,%without this there will be a symbol in the places where there is a space\n    numbers=left,%\n    numberstyle={\\tiny \\color{black}},% size of the numbers\n    numbersep=9pt, % this defines how far the numbers are from the text\n    emph=[1]{for,end,break},emphstyle=[1]\\color{red}, %some words to emphasise\n    %emph=[2]{word1,word2}, emphstyle=[2]{style},    \n   }\n%---End MATLAB code inclusion package ---%\n\n\\author{Ryan Day}\n\\title{Optimization Homework \\#4}\n\\begin{document}\n    \\maketitle\n    \\section{Truss Optimization}\n\n    \\subsection{Scaling}\n    Scaling the constraints is useful. I scaled it by dividing the constraints by $10^{2}$. This reduced the number of function calls by more than half when I implemented it. \n    I tried to make the constraints the same order of magnitude as the design functions.\n    The design variables are all around the same order of magnitude, so I don't see the use of scaling there.\n    \n    \\subsection{Matlab Code implementation}\n    The matlab code is included in appendix \\ref{appendix.trussCode}.\n    I used a function that took in x, then perturbed the function with a step depending on a type input (forward, central, or complex), and then calculated the gradient and constraints gradient.\n    It was not too hard to implement this function. \n    I simply added it to the end of obj and con in order to get the derivatvies.\n    However, I had to make one change in order to get the complex function to work.\n    This change was changing the inequality constraint from using the abs function to taking the square root of the value squared.\n    This did the same thing as abs but could be used with complex variables.\n    \n    \\subsection{Expected Errors of the derivatives}\n    I expected the errors of the derivative to be greatest for the forward, then central, then complex. \n    The merits of the forward method is it is only takes one function call per derivative. \n    Central method is slightly more accurate, but takes twice as many function calls.\n    Both central and forward methods have subtractive error which makes it so you can't have the step size be too small.\n    The complex step method does not have this subtractive error which makes it so you can have an extremely small step size, but then you have to make sure your function can handle complex numbers.\n    In addition to this, the computations of the complex step can take longer than the forward step because of the included complex numbers.\n    \n    I figured out the optimal perturbation of forward and central methods by comparing it to the complex step derivative.\n    I checked compared the estimated derivatives from the first iteration between the complex step with a step size of $10^{-30}$. \n    I knew the complex derivative would be pretty accurate because it has no subtractive error, so you can make the step size extremely small. \n    $10^{-8}$ turned out to be the ideal step size for forward and central. It had an error for forward on the order of $10^{-6}$ which was fine.\n    When I tried at 1e-9 there was an error in the gradient of forward of $10^{-4}$ which was too much. \n    For some reason the central wasn't converging when I scaled it, so that is why it was so much slower than the other functions.\n    \n    \\subsection{Table and stopping criteria}\n    \\begin{center}\n    \\begin{tabular}[h]{c c c c c}\n        & \\# Function calls & \\# Iterations & Avg Time execution& Final Objective value \\\\\n        No Derivatives supplied&287&12&0.420 &1.5932e+03\\\\\n        Forward method&309&12&0.415 & 1.5932e+03\\\\\n        Central method&4621&5&1.114 & 1.5932e+03\\\\ \n        Complex method&287&12&0.510  &   1.5932e+03 \n    \\end{tabular}\n\\end{center}\n\nThe execution time was fastest by just a little bit with the forward method. It barely beat out the fmincon with no supplied derivatives.\nThe forward method and complex method had the same number of function calls as expected since they both call the objective function just once to calculate derivatives. \nThe complex method took longer than the forward method because it had to deal with complex numbers. \nThe central method took about twice as many function calls and so took a lot longer than any other method. \nHowever, it had about half the iterations, because it goes in a more accurate direction with .\n\n\\textbf{Stopping Criterion for no derivatives supplied: }\n\nOptimization completed: The relative first-order optimality measure, 5.312214e-07,\nis less than options.OptimalityTolerance = 1.000000e-06, and the relative maximum constraint\nviolation, 0.000000e+00, is less than options.ConstraintTolerance = 1.000000e-06.\n\n\\textbf{Stopping Criterion for other methods:}\n\n\\textbf{Forward:}\n\nOptimization stopped because the relative changes in all elements of x are\nless than options.StepTolerance = 1.000000e-10, and the relative maximum constraint\nviolation, 0.000000e+00, is less than options.ConstraintTolerance = 1.000000e-06.\n\n\\textbf{Central:}\n\nOptimization completed: The relative first-order optimality measure, 7.486241e-07,\nis less than options.OptimalityTolerance = 1.000000e-06, and the relative maximum constraint\nviolation, 0.000000e+00, is less than options.ConstraintTolerance = 1.000000e-06.\n\n\\textbf{Complex:}\n\nOptimization completed: The relative first-order optimality measure, 3.928371e-08,\nis less than options.OptimalityTolerance = 1.000000e-06, and the relative maximum constraint\nviolation, 0.000000e+00, is less than options.ConstraintTolerance = 1.000000e-06.\n\n\\textbf{Commentary:}\nThe stopping criterion for forward and without supplying derivatives was that the x inputs had very small changes, signalling that there was an optimum. \nFor the complex and central step, the function output met the optimality measure. \nBecause I only looked at 5 significant digits for the optimum, these measures didn't affect the optimum at all.\n\n\\section{Automatic Differentiation}\n\\subsection{How does this method work?}\nI define the values to be of the valder class. \nAny other function that has a valder variable as part of its calculation will then take the valder variable  into account and then operator overloading is used to compute derivatives for the original valder functions.\nIn this way you can get derivatives without having to change your code much.\n\\subsection{How is AD different from other numerical methods?}\nAD is different because it solves the derivatives analytically using lookup functions and operator overloading instead of numerically approximating the value.\n\\subsection{Matlab Code}\nAD code is found in appendix \\ref{appendix.adcode}\n\\appendix\n\\section{Truss Optimization}\n\\label{appendix.trussCode}\n\\lstinputlisting[language=matlab]{../OptimizeTruss/OptimizeTruss.m} \n\\section{Automatic differentiation}\n\\lstinputlisting[language=matlab]{../AutomaticDifferentiation/optimize_spring.m} \n\\label{appendix.adcode}\n\\end{document}\nxopt =\n\n  Columns 1 through 5\n\n    6.3535    0.1016    6.4508    4.0730    0.1028\n\n  Columns 6 through 10\n\n    0.1016    5.4464    5.2882    6.0309    0.1039\n\n\nfopt =\n\n   1.4775e+03", "meta": {"hexsha": "3754b4e329df77a6dd49f68693df6d0e3819bb49", "size": 7699, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Hw4/Hw4Writeup/main.tex", "max_stars_repo_name": "rddq/OptimizationME570", "max_stars_repo_head_hexsha": "159f0117d8d9b15e1cc4f1ff64375a7645f62681", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-09-10T03:44:49.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-10T03:44:49.000Z", "max_issues_repo_path": "Hw4/Hw4Writeup/main.tex", "max_issues_repo_name": "rddq/OptimizationME570", "max_issues_repo_head_hexsha": "159f0117d8d9b15e1cc4f1ff64375a7645f62681", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Hw4/Hw4Writeup/main.tex", "max_forks_repo_name": "rddq/OptimizationME570", "max_forks_repo_head_hexsha": "159f0117d8d9b15e1cc4f1ff64375a7645f62681", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.7898550725, "max_line_length": 217, "alphanum_fraction": 0.7573710872, "num_tokens": 1941, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.34833327154901456}}
{"text": "In the figures below we can see the surface plots of the horizontal velocity $u$, vertical velocity $v$ and mass fraction $Y$, for different values of $t$. They are all obtained using $M=256$, $N=128$ and $CFL=0.8$. Below the contour plots, and using the same parameters, we have the curve plots of the probe measurements together with the performance parameter $R$ $vs$ time. To finish, we have the $GCI$-analysis of the quantities required by the problem. At the very end, the same $GCI$-analysis will be performed to the steady state solution.\n\n\\begin{figure}[H]\n\\centering     %%% not \\center\n\\hspace*{\\fill}\n\\subfigure[$t=1$ s.]{\\includegraphics[scale=0.55]{u_11.eps}}\n\\hfill\n\\subfigure[$t=2$ s.]{\\includegraphics[scale=0.55]{u_12.eps}}\n\\hspace*{\\fill}\n\n\\hspace*{\\fill}\n\\subfigure[$t=3$ s.]{\\includegraphics[scale=0.55]{u_13.eps}}\n\\hfill\n\\subfigure[$t=5$ s.]{\\includegraphics[scale=0.55]{u_14.eps}}\n\\hspace*{\\fill}\n\n\\hspace*{\\fill}\n\\subfigure[$t=7$ s.]{\\includegraphics[scale=0.55]{u_15.eps}}\n\\hfill\n\\subfigure[$t=10$ s.]{\\includegraphics[scale=0.55]{u_16.eps}}\n\\hspace*{\\fill}\n\\caption{Profiles of horizontal velocity $u$ for $M=256$, $N=128$ and $CFL=0.8$.}\n\\end{figure}\n\n\\begin{figure}[H]\n\\centering     %%% not \\center\n\\hspace*{\\fill}\n\\subfigure[$t=1$ s.]{\\includegraphics[scale=0.55]{v_21.eps}}\n\\hfill\n\\subfigure[$t=2$ s.]{\\includegraphics[scale=0.55]{v_22.eps}}\n\\hspace*{\\fill}\n\n\\hspace*{\\fill}\n\\subfigure[$t=3$ s.]{\\includegraphics[scale=0.55]{v_23.eps}}\n\\hfill\n\\subfigure[$t=5$ s.]{\\includegraphics[scale=0.55]{v_24.eps}}\n\\hspace*{\\fill}\n\n\\hspace*{\\fill}\n\\subfigure[$t=7$ s.]{\\includegraphics[scale=0.55]{v_25.eps}}\n\\hfill\n\\subfigure[$t=10$ s.]{\\includegraphics[scale=0.55]{v_26.eps}}\n\\hspace*{\\fill}\n\\caption{Profiles of the vertical velocity $v$ for $M=256$, $N=128$ and $CFL=0.8$.}\n\\end{figure}\n\n\\begin{figure}[H]\n\\centering     %%% not \\center\n\\hspace*{\\fill}\n\\subfigure[$t=1$ s.]{\\includegraphics[scale=0.55]{Y_31.eps}}\n\\hfill\n\\subfigure[$t=2$ s.]{\\includegraphics[scale=0.55]{Y_32.eps}}\n\\hspace*{\\fill}\n\n\\hspace*{\\fill}\n\\subfigure[$t=3$ s.]{\\includegraphics[scale=0.55]{Y_33.eps}}\n\\hfill\n\\subfigure[$t=5$ s.]{\\includegraphics[scale=0.55]{Y_34.eps}}\n\\hspace*{\\fill}\n\n\\hspace*{\\fill}\n\\subfigure[$t=7$ s.]{\\includegraphics[scale=0.55]{Y_35.eps}}\n\\hfill\n\\subfigure[$t=10$ s.]{\\includegraphics[scale=0.55]{Y_36.eps}}\n\\hspace*{\\fill}\n\\caption{Profiles of the mass fraction $Y$ for $M=256$, $N=128$ and $CFL=0.8$.}\n\\end{figure}\n\n\\begin{figure}[H]\n\\centering     %%% not \\center\n\\hspace*{\\fill}\n\\subfigure[Probe 1.]{\\includegraphics[scale=0.55]{probeu.eps}}\n\\hfill\n\\subfigure[Probe 2.]{\\includegraphics[scale=0.55]{probev.eps}}\n\\hspace*{\\fill}\n\n\\hspace*{\\fill}\n\\subfigure[Probe 3.]{\\includegraphics[scale=0.55]{probeY.eps}}\n\\hfill\n\\subfigure[Performance parameter.]{\\includegraphics[scale=0.55]{Rplot.eps}}\n\\hspace*{\\fill}\n\\caption{Probe curves and performance parameter with time for $M=256$, $N=128$ and $CFL=0.8$.}\n\\end{figure}\n\n\\subsection*{GCI analysis for u at t=5}\n\nThe GCI analysis details are shown in the tables below. Note that \n\\begin{align*}\n\\beta=\\frac{GCI_{12}}{GCI_{23}}r^p,\n\\end{align*}\nand $u_{h=0}$ is obtained by Richardson extrapolation. We can see that $\\beta\\in[0.95,1.05]$ which implies that we are in the asymptotic range of convergence, and for the last mesh we have a $GCI_{12}$ value less than $0.02\\%$, the requested accuracy.\n\\begin{table}[H]\n\\centering\n\\begin{tabular}{|c|c|c|}\n%\\hline\n%\\multicolumn{3}{|c|}{Datos}\\\\\nM & N & $u(1,0.5)$ \\\\\n\\hline\n$16$ & $8$ & $1.543690071443089$ \\\\\n$32$ & $16$ & $   1.335416609160283$ \\\\\n$64$ & $32$ & $   1.322019032777453$ \\\\\n$128$ & $64$ & $   1.319745850662477$ \\\\\n$256$ & $128$ & $   1.319205904441201$ \\\\\n$512$ & $256$ & $   1.319067860936907$ \\\\\n\\end{tabular}\n\\caption{GCI analysis data.}\n\\end{table}\n\n\\begin{figure}[H]\n\\centering     %%% not \\center\n\\includegraphics[scale=0.55]{ut5.png}\n\\caption{GCI analysis results for the probe 1 measurement.}\n\\end{figure}\n\n\\subsection*{GCI analysis for v at t=5}\n\nWe can see that $\\beta\\in[0.95,1.05]$ which implies that we are in the asymptotic range of convergence, and for the last mesh we have a $GCI_{12}$ value less than $0.02\\%$, the requested accuracy.\n\n\\begin{table}[H]\n\\centering\n\\begin{tabular}{|c|c|c|}\n%\\hline\n%\\multicolumn{3}{|c|}{Datos}\\\\\nM & N & $v(1,1.5)$ \\\\\n\\hline\n$16$ & $8$ & $  -0.757061737618705$ \\\\\n$32$ & $16$ & $  -0.625718980721275$ \\\\\n$64$ & $32$ & $  -0.622907528189143$ \\\\\n$128$ & $64$ & $  -0.622804506934971$ \\\\\n$256$ & $128$ & $  -0.622781023934629$ \\\\\n$512$ & $256$ & $\t-0.622773391772338$ \\\\\n\\end{tabular}\n\\caption{GCI analysis data.}\n\\end{table}\n\n\\begin{figure}[H]\n\\centering     %%% not \\center\n\\includegraphics[scale=0.55]{vt5.png}\n\\caption{GCI analysis results for the probe 2 measurement.}\n\\end{figure}\n\n\\subsection*{GCI analysis for Y at t=5}\n\nWe can see that $\\beta\\in[0.95,1.05]$ which implies that we are in the asymptotic range of convergence, and for the last mesh we have a $GCI_{12}$ value less than $0.4\\%$, the requested accuracy.\n\n\\begin{table}[H]\n\\centering\n\\begin{tabular}{|c|c|c|}\n%\\hline\n%\\multicolumn{3}{|c|}{Datos}\\\\\nM & N & $Y(2,0.5)$ \\\\\n\\hline\n$16$ & $8$ & $   0.582656635075406$ \\\\\n$32$ & $16$ & $   0.588540399303644$ \\\\\n$64$ & $32$ & $   0.591682314985302$ \\\\\n$128$ & $64$ & $   0.594958713346013$ \\\\\n$256$ & $128$ & $   0.596429634107325$ \\\\\n$512$ & $256$ & $   0.597084423776656$ \\\\\n\\end{tabular}\n\\caption{GCI analysis data.}\n\\end{table}\n\n\\begin{figure}[H]\n\\centering     %%% not \\center\n\\includegraphics[scale=0.55]{Yt5.png}\n\\caption{GCI analysis results for the probe 3 measurement.}\n\\end{figure}\n\n\\subsection*{GCI analysis for R at t=5}\n\nWe can see that $\\beta\\in[0.95,1.05]$ which implies that we are in the asymptotic range of convergence, and for the last mesh we have a $GCI_{12}$ value less than $0.5\\%$, the requested accuracy.\n\n\\begin{table}[H]\n\\centering\n\\begin{tabular}{|c|c|c|}\n%\\hline\n%\\multicolumn{3}{|c|}{Datos}\\\\\nM & N & $v(1,1.5)$ \\\\\n\\hline\n$16$ & $8$ & $   0.168352427538196$ \\\\\n$32$ & $16$ & $   0.162648932748133$ \\\\\n$64$ & $32$ & $   0.161109373859052$ \\\\\n$128$ & $64$ & $   0.160690350976423$ \\\\\n$256$ & $128$ & $   0.160521007689289$ \\\\\n$512$ & $256$ & $   0.160443010433551$ \\\\\n\\end{tabular}\n\\caption{GCI analysis data.}\n\\end{table}\n\n\\begin{figure}[H]\n\\centering     %%% not \\center\n\\includegraphics[scale=0.55]{Rt5.png}\n\\caption{GCI analysis results for the parameter $R$.}\n\\end{figure}\n\n\\subsection*{Steady state results}\nI ran the simulation using $M=256$ and $N=128$ up to a $t=30$ to reach the steady state solution of the problem. In the following tables are the results obtained, with the GCI analysis.\n\n\\begin{figure}[H]\n\\centering     %%% not \\center\n\\includegraphics[scale=0.55]{ut30.png}\n\\caption{GCI analysis results for the probe 1 measurement.}\n\\end{figure}\n\n\\begin{figure}[H]\n\\centering     %%% not \\center\n\\includegraphics[scale=0.55]{vt30.png}\n\\caption{GCI analysis results for the probe 2 measurement.}\n\\end{figure}\n\n\\begin{figure}[H]\n\\centering     %%% not \\center\n\\includegraphics[scale=0.55]{Yt30.png}\n\\caption{GCI analysis results for the probe 3 measurement.}\n\\end{figure}\n\n\\begin{figure}[H]\n\\centering     %%% not \\center\n\\includegraphics[scale=0.55]{Rt30.png}\n\\caption{GCI analysis results for the parameter $R$.}\n\\end{figure}", "meta": {"hexsha": "2651baf69ee09a3369207b5306ab9384e1c110ce", "size": 7262, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Year_1/CFD/Homework_10/Latex/Results.tex", "max_stars_repo_name": "fjcasti1/Courses", "max_stars_repo_head_hexsha": "12ab3e86a4a44270877e09715eeab713da45519d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Year_1/CFD/Homework_10/Latex/Results.tex", "max_issues_repo_name": "fjcasti1/Courses", "max_issues_repo_head_hexsha": "12ab3e86a4a44270877e09715eeab713da45519d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Year_1/CFD/Homework_10/Latex/Results.tex", "max_forks_repo_name": "fjcasti1/Courses", "max_forks_repo_head_hexsha": "12ab3e86a4a44270877e09715eeab713da45519d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8597285068, "max_line_length": 546, "alphanum_fraction": 0.6724042963, "num_tokens": 2722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.3483332715490145}}
{"text": "%\\documentclass[notes]{beamer}       % print frame + notes\n% \\documentclass[notes=only]{beamer}   % only notes\n\\documentclass{beamer}  \n\n\\usepackage{wrapfig}\n\\usepackage{amsmath,amssymb}\n%\\usepackage[dvipsname]{xcolor}\n\\usepackage{tikz}\n\\usepackage{tikz-cd}\n\\usepackage{graphicx}\n\n\\usetikzlibrary{shapes.geometric,shadows,knots}\n\n\\tikzset{pics/.cd,\nopencube/.style args={#1/#2/#3}{code={\n\\coordinate (O) at (0,0,0);\n\\coordinate (A) at (0,#2,0);\n\\coordinate (B) at (0,#2,#3);\n\\coordinate (C) at (0,0,#3);\n\\coordinate (D) at (#1,0,0);\n\\coordinate (E) at (#1,#2,0);\n\\coordinate (F) at (#1,#2,#3);\n\\coordinate (G) at (#1,0,#3);\n%% Background\n\\draw[black,dotted] (O) -- (A);\n\\draw[black,dotted] (O) -- (C);\n\\draw[black,dotted] (O) -- (D);\n% Forground\n\\draw[black,dashed] (A) -- (E) -- (F) -- (B) -- cycle;\n\\draw[black,dashed] (E) -- (D) -- (G) -- (C) -- (B);\n\\draw[black,dashed] (F) -- (G);\n\n%\\draw[black,dashed, blue] (O) -- (A) -- (E) -- (D) -- cycle;\n%\\draw[black,dashed] (O) -- (A) -- (B) -- (C) -- cycle;\n%\\draw[black,dashed] (D) -- (E) -- (F) -- (G) -- cycle;\n%\\draw[black,dashed] (C) -- (B) -- (F) -- (G) -- cycle;\n%\\draw[black,dashed] (A) -- (B) -- (F) -- (E) -- cycle;\n\n}}}\n\n\\tikzset{pics/.cd,\nlinecube/.style args={#1/#2/#3/#4}{code={\n\\coordinate (OO) at (0,0,0);\n\\coordinate (AA) at (0,#2,0);\n\\coordinate (BB) at (0,#2,#3);\n\\coordinate (CC) at (0,0,#3);\n\\coordinate (DD) at (#1,0,0);\n\\coordinate (EE) at (#1,#2,0);\n\\coordinate (FF) at (#1,#2,#3);\n\n\\coordinate (GG) at (#1,0,#3);\n%% Background\n\\draw[black,dashed] (OO) -- (AA);\n\\draw[black,dashed] (OO) -- (CC);\n\\draw[black,dashed] (OO) -- (DD);\n\n\\node at (0.5*#1,0.5*#2,0.5*#3) {#4};\n\n% Foreground\n\\draw[black] (AA) -- (EE) -- (FF) -- (BB) -- cycle;\n\\draw[black] (EE) -- (DD) -- (GG) -- (CC) -- (BB);\n\\draw[black] (FF) -- (GG);\n\n%\\draw[black,dashed, blue] (O) -- (A) -- (E) -- (D) -- cycle;\n%\\draw[black,dashed] (O) -- (A) -- (B) -- (C) -- cycle;\n%\\draw[black,dashed] (D) -- (E) -- (F) -- (G) -- cycle;\n%\\draw[black,dashed] (C) -- (B) -- (F) -- (G) -- cycle;\n%\\draw[black,dashed] (A) -- (B) -- (F) -- (E) -- cycle;\n\n}}}\n\n\n\\tikzset{pics/.cd,\nshadedcube/.style args={#1/#2/#3/#4/#5}{code={\n\\coordinate (O) at (0,0,0);\n\\coordinate (A) at (0,#2,0);\n\\coordinate (B) at (0,#2,#3);\n\\coordinate (C) at (0,0,#3);\n\\coordinate (D) at (#1,0,0);\n\\coordinate (E) at (#1,#2,0);\n\\coordinate (F) at (#1,#2,#3);\n\\coordinate (G) at (#1,0,#3);\n\\draw[black,fill=#4!80] (O) -- (C) -- (G) -- (D) -- cycle;\n\\draw[black,fill=#4!30] (O) -- (A) -- (E) -- (D) -- cycle;\n\\draw[black,fill=#4!10] (O) -- (A) -- (B) -- (C) -- cycle;\n\\draw[black,fill=#4!20,opacity=0.8] (D) -- (E) -- (F) -- (G) -- cycle;\n\\draw[black,fill=#4!20,opacity=0.6] (C) -- (B) -- (F) -- (G) -- cycle;\n\\draw[black,fill=#4!20,opacity=0.8] (A) -- (B) -- (F) -- (E) -- cycle;\n\\node at (0.5*#1,0.5*#2,0.5*#3) {#5};\n}}}\n\\tikzset{pics/.cd,\ngridcube/.style args={#1/#2/#3/#4/#5/#6/#7}{code={\n\\coordinate (O) at (0,0,0);\n\\coordinate (A) at (0,#2,0);\n\\coordinate (B) at (0,#2,#3);\n\\coordinate (C) at (0,0,#3);\n\\coordinate (D) at (#1,0,0);\n\\coordinate (E) at (#1,#2,0);\n\\coordinate (F) at (#1,#2,#3);\n\\coordinate (G) at (#1,0,#3);\n\n% Foreground\n\\draw[fill=#7!20] (A) -- (E) -- (F) -- (B) -- cycle;\n\\draw[fill=#7!40] (E) -- (F) -- (G) -- (D) -- cycle;\n\\draw[fill=#7!30] (B) -- (F) -- (G) -- (C) -- cycle;\n%\\draw[black] (E) -- (D) -- (G) -- (C) -- (B);\n%\\draw[black] (F) -- (G);\n\n% lines\n\\foreach \\ll in {1,...,#4} {\n    \\draw[black] (#1/#4*\\ll,#2,0) -- (#1/#4*\\ll,#2,#3) -- (#1/#4*\\ll,0,#3);\n}\n\\foreach \\ll in {1,...,#5} {\n    \\draw[black] (0,#2/#5*\\ll,#3) -- (#1, #2/#5*\\ll,#3) -- (#1,#2/#5*\\ll,0);\n}\n\\foreach \\ll in {1,...,#6} {\n    \\draw[black] (0,#2,#3/#6*\\ll) -- (#1,#2,#3/#6*\\ll) -- (#1,0,#3/#6*\\ll);\n}\n\n}}}\n\n%\\pgfmathsetmacro{\\xx}{0.5}\n\n\\mode<presentation>\n% \\setbeameroption{hide notes}\n{\n  %\\usetheme{Madrid}\n  \\usetheme{metropolis}\n% CSU COLORS\n  \\definecolor{csugreen}{HTML}{1C674F}\n  \\definecolor{csugold}{HTML}{B78E00}\n    \\definecolor{csured}{HTML}{E02F11}\n\n  \\definecolor{greenmain}{HTML}{00AF64}\n  \\definecolor{brick}{rgb}{.85,.1,.2}\n  \\colorlet{greenstruct}{greenmain!87.5!black}\n  \\usecolortheme[named=csugreen]{structure}\n  % Change this in order to make the presentation look\n  % different. Works just like a powerpoint template. \n  % Have your RA mess around until it looks nice.\n  \\setbeamercovered{dynamic}\n\n  \\useinnertheme{rectangles}\n  \n %Other colors.\n\n%   \\definecolor{bluemain}{HTML}{0B61A4}\n%   \\definecolor{orangemain}{HTML}{AA6600}\n%   \\definecolor{redmain}{HTML}{E02F11}\n%   \\definecolor{redlight}{HTML}{FF9B73}\n%   \\definecolor{orangelight}{HTML}{FFC373}\n%   \\definecolor{cmugray}{RGB}{104,104,104}\n%   \\definecolor{cmulightgray}{RGB}{238,238,238}\n%   \\setbeamercolor{block body}{bg=cmulightgray}\n%   \\setbeamercolor{talktitle}{bg=csugreen,fg=white}\n%   \\setbeamercolor{block title alerted}{bg=csugold}\n%   \\setbeamercolor{block body alerted}{bg=orangelight}\n\n}\n\\renewcommand{\\footnoterule}{}\n\\renewcommand{\\hat}[1]{\\widehat{#1}}\n\\newcommand{\\sourcenum}[3]{$^{\\textcolor{bluemain} #1}$\\let\\thefootnote\\relax\n  \\footnotetext{\\begin{flush#2}\\textcolor{bluemain}\n      {\\tiny $^{#1}$ #3}\\end{flush#2}}} \n\\newcommand{\\source}[2]{\\let\\thefootnote\\relax\\footnotetext{\\begin{flush#1}\n      \\textcolor{bluemain}{\\tiny Source: #2}\\end{flush#1}}}  \n\n\n\\DeclareMathOperator{\\Span}{Span}\n\\DeclareMathOperator{\\Pres}{Pres}\n\\DeclareMathOperator{\\End}{End}\n\\newcommand{\\bmto}{\\rightarrowtail}\n\n\\usepackage{wasysym} \n\\newcommand{\\den}[1]{\\Leftcircle\\hspace*{-1mm}#1\\hspace*{-1mm} \\Rightcircle}\n\\usepackage{listings}\n\n\\begin{document}\n\n\\title{Group isomorphism is nearly-linear time for most\norders\\\\ {\\small IEEE Foundations On Computer Science FOCS 2021}}\n\\author{Heiko Dietrich\\\\ Monash University, Australia\\\\[10pt] James B. Wilson (presenting)\\\\ Colorado State University, USA}\n\\date{February 8, 2022}\n\n\\maketitle\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Motivation}\n\n\\begin{frame}[containsverbatim,fragile]{Outward Facing Motive: honest data types}\nWhere in this... \\\\\n\\begin{center}\n\\begin{tikzpicture}\n\\visible<2->{\n    \\node at (0,0) {\\includegraphics[height=0.25\\textheight]{algo.jpg}};\n};\n\\visible<3->{\n\\node[rotate=30,drop shadow] at (1,1) {\\includegraphics[height=0.25\\textheight]{OIP.jpg}};\n};\n\\visible<4->{\n\\node[rotate=-30,drop shadow] at (3,0.5) {\\includegraphics[height=0.25\\textheight]{stack.png}};\n};\n\\end{tikzpicture}\n\\end{center}\n\\visible<5->{\n...do we send people to get help making this... \n\n\\includegraphics{equals.png}\n% \\begin{lstlisting}[mathescape=true,language=Java,basicstyle=\\ttfamily,commentstyle=\\color{csugreen},keywordstyle=\\color{blue}]\n% boolean equals(Object that) {\n%     // <this> can transform into <that>?\n% }\n% \\end{lstlisting}\n};\n\\end{frame}\n\n\n\\begin{frame}{Why groups(oids)?}\n\\begin{itemize}\n    \\item \\textbf{Transitive}$\\to$ \\textbf{Partial Multiplication}\n    \\begin{align*}\n    trans_{xyz}:& (x\\equiv y) \\wedge (y\\equiv z) \\Rightarrow (x\\equiv z)\\\\\n    *:& Eq \\times Eq \\dashrightarrow Eq\n    \\end{align*}\n\\pause\n\n\\item  \\textbf{Reflexive}$\\to$ \\textbf{Identity}\n    \\begin{align*}\n    refl_x&: x \\Rightarrow  (x\\equiv x)\\\\\n    trans_{xxy} &:(x\\equiv x)\\wedge (x\\equiv y) \\Rightarrow (x\\equiv y)\\\\\n    \\hline\n    Identity &: refl*evidence  = evidence\n    \\end{align*}\n\n    \n    \\item  \\textbf{Symmetric}$\\to$ \\textbf{Inverse}\n    \\begin{align*}\n    sym_{xy}&:(x\\equiv y)\\Rightarrow (y\\equiv x)\\\\\n    trans_{xyx} &: (x\\equiv y) \\wedge (x\\equiv y)  \\Rightarrow (x\\equiv x)\\\\\n    \\hline\n    Inverses & : evidence * (evidence)^{-1}  = refl\n    \\end{align*}\n\\end{itemize}\n\\end{frame}\n    \n\\begin{frame}{Anatomy of hard equality}\n    \\centering\n\\begin{tikzpicture}[yscale=0.85]\n\\node at (0,0.5) {$L$};\n\\node (L) at (0,0) {\n    \\begin{tikzpicture}[scale=0.5]\n        \\foreach \\brk in {0,1,2} {\n        \\begin{scope}[rotate=\\brk * 240]\n            \\node[knot crossing, transform shape, inner sep=3pt] (k\\brk) at (0,-1) {};\n        \\end{scope}\n        }\n        \\foreach \\brk in {0,1,2} {\n            \\pgfmathparse{int(Mod(\\brk - 1,3))}\n            \\edef\\brl{\\pgfmathresult}\n            \\draw[thick,blue] (k\\brk) .. controls (k\\brk.4 north east) and (k\\brl.4 north west) .. (k\\brl.center);\n            \\draw[thick,blue] (k\\brk.center) .. controls (k\\brk.16 south east) and (k\\brl.16 south west) .. (k\\brl);\n        }\n    \\end{tikzpicture}\n};\n\n\\node at (1.5,0.5) {$\\overset{?}{\\cong}$};\n\\node at (3,0.5) {$R$};\n\\node (R) at (3,0) {\n    \\begin{tikzpicture}[scale=0.5]\n        \\foreach \\brk in {0,1,2} {\n        \\begin{scope}[rotate=\\brk * 120]\n            \\node[knot crossing, transform shape, inner sep=3pt] (k\\brk) at (0,-1) {};\n        \\end{scope}\n        }\n        \\foreach \\brk in {0,1,2} {\n            \\pgfmathparse{int(Mod(\\brk - 1,3))}\n            \\edef\\brl{\\pgfmathresult}\n            \\draw[thick,red] (k\\brk) .. controls (k\\brk.4 north west) and (k\\brl.4 north east) .. (k\\brl.center);\n            \\draw[thick,red] (k\\brk.center) .. controls (k\\brk.16 south west) and (k\\brl.16 south east) .. (k\\brl);\n        }\n    \\end{tikzpicture}\n};\n\n\\visible<2->{\n\\node (pL) at (-0.5,-3) {$\\pi_1(L)=\\langle x,y\\mid x^2=y^3\\rangle$};\n\\node (pR) at (4.5,-3) {$\\pi_1(R)=\\langle x,y\\mid x^2=y^{-3}\\rangle$};\n\\node[text width=4cm] at (7,-0.5) {Relax category until automorphisms computable.};\n\\draw[->,thick] (L) to (pL);\n\\draw[->,thick] (R) to (pR);\n};\n\n\\visible<3->{\n\\node (apL) at (0,-5) {$\\mathrm{Aut}_{\\chi}\\pi_1(L)$};\n\\node (apR) at (3,-5) {$\\mathrm{Aut}_{\\chi}\\pi_1(R)$};\n\\draw[->,thick] (pL) to[bend right=30] (apL);\n\\draw[->,thick] (pR) to[bend left=30] (apR);\n\\node at (2,-3) {$\\overset{?}{\\cong}$};\n\\draw[->,thick,dashed] (apL) to[bend right=30] (0.5,-7);\n\\draw[->,thick,dashed] (apR) to[bend left=30] (2.5,-7);\n\\node[color=red] at (1.5,-5) {$\\not{\\cong}_{\\chi}$};\n\\node[text width=4cm] at (7,-5.5) {Recursively refine comparing automorphisms\n with incrementally stricter properties. {\\color{red} E.g. respect crossing number $\\chi$?}};\n};\n\\end{tikzpicture}\n\n\\end{frame}\n\n\\begin{frame}{Inward facing Motive: equalivance surveys complexity}\n\\centering\n\\begin{tikzpicture}\n\n\\fill[rounded corners, black!20] (0,5.5) rectangle (11,4.5);\n\\node[text width=2cm] at (9.5,5) {Undecideable};\n\\node[text width=3cm] at (2,5) {\\textbf{FPGroupIso}\\\\ Adjan, Rabin `50's};\n\n\n\\fill[rounded corners,red!30] (0,4) rectangle (11,3);\n\\node[text width=2cm] at (10,3.5) {$\\Sigma_3^P$};\n\\node[text width=5cm] at (3,3.5) {\\textbf{PlaneGroupIso}\\\\ Dietrich et.al. STACS`21};\n\n\\fill[rounded corners,red!20] (0,3) rectangle (11,2);\n\\node[text width=2cm] at (10,2.5) {$\\Sigma_2^P$};\n\\node[text width=5cm] at (3,2.5) {\\textbf{BlackBoxGroupIso}\\\\ Babai-Szemer\\'edi FOCS`84};\n\\node[text width=5cm] at (8,2.5) {\\textbf{MatroidIso}};\n\n\\fill[rounded corners,red!10] (0,2) rectangle (11,1);\n\\node[text width=2cm] at (10,1.5) {$\\Sigma_1^P=NP$};\n\\node[text width=5cm] at (3,1.5) {\\textbf{PermGroupIso}\\\\ Luks DIMACS};\n\n\n\\fill[rounded corners,brown!20] (0,1) rectangle (11,0);\n\\node[text width=2cm] at (9,0.5) {${\\tiny DTIME}(2^{\\log^c n})$};\n\\node[text width=5cm] at (3,0.5) {\\textbf{TableGroupIso}\\\\ Tarjan};\n\\node[text width=5cm] at (8,0.5) {\\textbf{GraphIso}\\\\ Babai};\n\n\\fill[rounded corners,csugreen!20] (0,-.5) rectangle (11,-1.5);\n\\node[text width=2cm] at (9,-1) {${\\tiny DTIME}(n^2\\log^c n)$};\n\\node[text width=7cm] at (4,-1) {\\textbf{TableGroupIsoAbel}\\\\ Kavitha (nearly-linear in RAM model)};\n\n\\fill[rounded corners,csugreen!30] (0,-1.5) rectangle (11,-2.5);\n\\node[text width=2cm] at (9,-2) {${\\tiny DTIME}(n\\log^c n)$};\n\\node[text width=7cm] at (4,-2) {\\textbf{TableGroupIsoMostOrders, IsGroup}\\\\ {\\color{red}This Talk}};\n\n\n\\end{tikzpicture}\n\n\\end{frame}\n\n\\begin{frame}{Schreier-Sims}\n\n    \\begin{block}{Problem: Transport}\n    \\begin{description}\n        \\item[Given:] A set $\\Omega$, allowed permutations $X$, $\\omega,\\omega'\\in\\Omega$\n        \\item[Return:] decide if a string $g$ over $X$ maps $\\omega$ to $\\omega'$, \n        written $\\omega^{g}=\\omega'$, and give all such $g$.\\footnote{Give words $W$ over $X$\n        so that $\\omega^h=\\omega'$ implies $h=wg$ for a string $w$ over $W$.}\n    \\end{description}\n    \\end{block}\n\\end{frame}\n\n\n\n\\begin{frame}[fragile]{String Isomorphism}\n\\begin{center}\n    ``Eighth'' == ``HeigHt''\n\\end{center}\n%Cycle right by 1 and replace $h$ with $H$.\n\\pause\n\\begin{block}{String Isomorphism}\n\\noindent\n\\begin{minipage}{0.6\\textwidth}\n\\noindent\n\\begin{itemize}\n\\item {\\color{csugreen}\\textbf{Given}} strings $s,t:I\\to \\Sigma$\nallowed permutations $G=\\langle g_k\\rangle\\leq \\mathrm{Sym}_{I}$, \n$H=\\langle h_k\\rangle\\leq \\mathrm{Sym}_{\\Sigma}$\n\\item {\\color{csugreen}\\textbf{Return}} strings $g=g_{a_1}\\cdots g_{a_u}$ \nand $h=h_{b_1}\\cdots h_{b_v}$ where $h(s_{i})=t_{g(i)}$; or prove impossible.\n\\end{itemize}\n\\end{minipage}\n\\begin{minipage}{0.3\\textwidth}\n\\begin{tikzcd}\n    & I \\arrow[d,\"g\"]\\arrow[r, \"s\"] \n        & \\Sigma\\arrow[d,\"h\"] &\\\\ \n    & I\\arrow[r,\"t\"] & \\Sigma & \n\\end{tikzcd}\n\\end{minipage}\n\\end{block}\n\\pause\n\n\\textbf{Theorem.} (Babai 2016+) If $\\Sigma$ fixed, \\textsc{StringIso} \nis in Quasipolynomial $n^{O((\\log n)^c)}$-time.\n\\vfill\n(\\textsc{GraphIso}$\\leq_P$ \\textsc{StringIso})\n\n\\end{frame}\n\n\\begin{frame}{Snapshot of solving a hard isomorphism problem}\n\\centering\n\\begin{tikzpicture}\n\\visible<1->{\n\\node[fill=csugreen!20,text width=3cm] (math) at (0,5) {\\textbf{Math Facts}};\n\\node[fill=blue!20,text width=3cm] (SS) at (0,-2) {\\textbf{Schreier-Sims} `65};\n\\draw[-,dashed] (SS) to[bend right=30] (math);\n};\n\n\\visible<2->{\n\\node[fill=green!20,text width=3cm] (exp) at (0,3) {\\textbf{Exponential}\\\\ Babai-Luks STOC83};\n\\node[fill=blue!20,text width=3.5cm] (BV) at (0,0) {\\textbf{Bounded Valence}\\\\ Luks `82};\n\\node[shade, left color=blue!30, right color=red!30,text width=3cm] (color) at (4,0) {Color Refinement\\\\ Weisfeiler-Leman, Babai-Erd\\H{o}s-Selkow,$\\ldots$ 70-80's};\n\\draw[-] (exp) -- (color);\n\\draw[-] (exp) -- (BV);\n\\draw[-,dashed] (BV) to[bend right=30] (math);\n\\draw[-,dotted] (BV) -- (SS);\n\n};\n\n\\visible<3->{\n\\node[fill=red!20,text width=3cm] (CFI) at (8,-1) {\\textbf{Exceptional}\\\\ Cai-F\\\"urer-Immerman FOCS 89};\n\n\\draw[-,dashed] (CFI) to[bend right=30] (math);\n};\n\n\\visible<4>{\n\\node[fill=green!20,text width=3cm] (quasi) at (5,5) {\\textbf{Split-or-Johnson}\\\\ Babai STOC 16+};\n\n\\node[fill=red!20,text width=3cm] (Johnson) at (8,2) {\\textbf{Johnson Graphs}\\\\ Babai STOC 16+\\\\};\n\\draw[-,dotted] (Johnson) -- (CFI);\n\n\\draw[-] (quasi) -- (color);\n\\draw[-] (quasi) -- (BV);\n\\draw[-] (quasi) -- (Johnson);\n\\draw[-] (quasi) -- (CFI);\n\\draw[-,dashed] (quasi) -- (math);\n};\n\\end{tikzpicture}\n\n\\end{frame}\n\n%========================================================\n\\section{Isomorphism of Tables}\n\n\\begin{frame}[fragile]{Code Equivalence}\n\n\\[\\begin{array}{|cc|}\n    \\hline \nL & i \\\\ v & e \\\\\n\\hline\n\\end{array}\n== \n\\begin{array}{|cc|}\n    \\hline \nE & v \\\\ i & l \\\\\n\\hline\n\\end{array}\\]\n\\begin{block}{Code Equivalence\\footnote{Non-linear twisted, with variable alphabet.}}\n\\begin{minipage}{0.6\\textwidth}\n\\begin{itemize}\n    \\item {\\color{csugreen}\\textbf{Given}} $s,t:I\\times J\\to \\Sigma$, \n    (generators for) permutations \n    $R\\leq \\mathrm{Sym}_{I}$, \n    $C\\leq \\mathrm{Sym}_J$, \n    \\& $V\\leq \\mathrm{Sym}_{\\Sigma}$ \n    \\item {\\color{csugreen}\\textbf{Return}}  $\\sigma\\in R$, $\\tau\\in C$, $\\mu\\in V$,\n    \\[\\mu(s_{ij}) = t_{\\sigma(i)\\tau(j)}\\] \n\\end{itemize}\n\\end{minipage}\n\\hfill\n\\begin{minipage}{0.3\\textwidth}\n    \\begin{tikzcd}\n        I \\arrow[d,\"\\sigma\"] &[-\\dimexpr\\pgfmatrixcolumnsep+0.6em\\relax]\n        \\times &[-\\dimexpr\\pgfmatrixcolumnsep+0.6em\\relax] J \\arrow[d,\"\\tau\"]\n        \\arrow[r,\"s\"] & \\Sigma\\arrow[d,\"\\mu\"]\\\\\n        I &[-\\dimexpr\\pgfmatrixcolumnsep+0.6em\\relax]\n        \\times &[-\\dimexpr\\pgfmatrixcolumnsep+0.6em\\relax] J \n        \\arrow[r,\"t\"] & \\Sigma\n    \\end{tikzcd}\n\\end{minipage}\n\n\\end{block}\n\nBabai-Codenotti-Grochow-Qiao $2^{O(n)}$-time bound for constant alphabet $\\Sigma$ (SODA `11) \\\\\nBuilds on Luks $2^{O(n)}$-hypergraph isomorphism, FOCS `99.\n\n\\end{frame}\n\n\n\\begin{frame}[fragile]{Algebra Isomorphism}\n\n\\[\\begin{array}{|ccccc|}\n    \\hline \n1 & 2 & 3 & 4 & 5\\\\\n2 & 3 & 4 & 5 & 1\\\\\n3 & 4 & 5 & 1 & 2\\\\\n4 & 5 & 1 & 2 & 3\\\\\n5 & 1 & 2 & 3 & 4\\\\\n\\hline\n\\end{array}\n== \n\\begin{array}{|ccccc|}\n    \\hline \n1 & 2 & 3 & 4 & 5\\\\\n2 & 4 & 1 & 5 & 3\\\\\n3 & 1 & 5 & 2 & 4\\\\\n4 & 5 & 2 & 3 & 1\\\\\n5 & 3 & 4 & 1 & 2\\\\\n\\hline\n\\end{array}\\]\n\\begin{block}{Algebra Isomorphism}\n\\begin{minipage}{0.6\\textwidth}\n\\begin{itemize}\n    \\item {\\color{csugreen}\\textbf{Given}} $s,t:I\\times I\\to I$, \n    (generators for) permutations \n    $G\\leq \\mathrm{Sym}_I$, \n    \\item {\\color{csugreen}\\textbf{Return}}  $\\sigma\\in G$,\n    \\[\\sigma(s_{ij}) = t_{\\sigma(i)\\sigma(j)}\\] \n\\end{itemize}\n\\end{minipage}\n\\hfill\n\\begin{minipage}{0.3\\textwidth}\n    \\begin{tikzcd}\n        I\\arrow[d,\"\\sigma\"] &[-\\dimexpr\\pgfmatrixcolumnsep+0.6em\\relax]\n        \\times &[-\\dimexpr\\pgfmatrixcolumnsep+0.6em\\relax] I \\arrow[d,\"\\sigma\"]\n        \\arrow[r,\"s\"] & I\\arrow[d,\"\\sigma\"]\\\\\n        I &[-\\dimexpr\\pgfmatrixcolumnsep+0.6em\\relax]\n        \\times &[-\\dimexpr\\pgfmatrixcolumnsep+0.6em\\relax] I\n        \\arrow[r,\"t\"] & I\n    \\end{tikzcd}\n\\end{minipage}\n\n\\end{block}\n\n\\end{frame}\n\n\\begin{frame}{Group Isomorphism Strategy}\n\n\\centering\n\\begin{tikzpicture}\n\\visible<1->{\n\\node[fill=csugreen!20,text width=3cm] (math) at (5,5) {\\textbf{Math Facts}};\n\\node[fill=blue!20,text width=3.5cm] (gt) at (0,-2) {\\textbf{Generator Test}\\\\ Tarjan, Miller STOC78};\n\\draw[-,dashed] (gt) to[bend right=30] (math);\n};\n\n\\visible<2->{\n\\node[fill=csugreen!20,text width=3cm] (data) at (0,5) {\\textbf{Data Types}};\n\\node[fill=blue!20,text width=2cm] (abel) at (0,3) {\\textbf{(Nearly) Abelian}\\\\ Kavitha `07, LeGall};\n\\node[fill=blue!20,text width=3.5cm] (ss) at (0,0) {\\textbf{Semisimplicty}\\\\ Babai-Codenotti-Qiao ICALP `11};\n\\node[fill=red!20,text width=3cm] (AT) at (8,2) {\\textbf{Adjoint Tensor}\\\\ Lewis-W. `12};\n\n\\draw[-,dashed] (abel) to[bend right=30] (math);\n\\draw[-,dashed] (ss) to[bend right=30] (math);\n\\draw[-,dashed] (abel) to[bend right=30] (data);\n\\draw[-,dashed] (ss) to[bend right=30] (data);\n\n\\draw[-,dashed] (AT) to[bend left=30] (math);\n\n};\n\n\n\\visible<3->{\n    \\node[fill=red!20,text width=3cm] (TG) at (8,4) {\\textbf{Tame Genus}\\\\ Brooksbank-Maglione-W. `16};    \n\\node[fill=brown!20,text width=3cm] (BQ) at (4,3) {\\textbf{AbelTower}\\\\Babai-Qiao};\n\\node[fill=brown!20,text width=3cm] (GQ) at (4,1.5) {\\textbf{Extensions}\\\\Grochow-Qiao};\n\n    \\node[shade, left color=blue!30, right color=red!30,text width=3cm] (color) at (4,-2) {\\textbf{Tensor Individualization}\\\\Li-Qiao FOCS17};\n    \\node[shade, left color=blue!30, right color=red!30,text width=3cm] (cube) at (4,0) {\\textbf{Cube free}\\\\ Dietrich-W. JoA 19};\n    \n\\node[fill=red!20,text width=3cm] (W) at (8,0) {\\textbf{Exceptional}\\\\ W. ToC 19};\n\\node[fill=red!20,text width=3cm] (BS) at (8,-2) {\\textbf{Exceptional}\\\\ Brachter-Schweitzer LICS20};\n%\\draw[-,dashed] (color) to[bend right=30] (data);\n\n%\\draw[-,dashed] (cube) to[bend right=30] (data);\n% \\draw[-,dashed] (W) to[bend left=30] (math);\n% \\draw[-,dashed] (TG) to[bend right=30] (math);\n\\draw[->] (AT) to (color);\n\\draw[->] (AT) to (TG);\n\\draw[->] (AT) to (W);\n\\draw[->] (ss) to (BQ);\n\\draw[->] (ss) to (GQ);\n\\draw[->] (abel) to (BQ);\n\\draw[->] (abel) to (GQ);\n};\n\n\\end{tikzpicture}\n\n    \n\\end{frame}\n\n\\section{Group Isomorphism of most orders}\n\n\\begin{frame}{Divide and conquer}\n\nIsomorphism of $G=A\\times B$, i.e.\n\\[(a,b)(\\tilde{a},\\tilde{b}) = (a\\tilde{a},b\\tilde{b})\\] reduces to isomorphism\nof $A$ and $B$ in parallel.\\footnote{Technical detail: decompose maximally and\nadjust non-unique decompositions by Krull-Schmidt; see W. 2008.}\n\\pause\n\nIsomorphism of $G=A\\ltimes_{\\theta} B$, i.e.\n\\[(a,b)(\\tilde{a},\\tilde{b})=(a\\tilde{a},\\theta(\\tilde{a})(b)\\tilde{b})\\]\nreduces to isomorphism of $A$ and $B$\nsequentially, plus adjusting $\\theta$.\\footnote{Lemma~2.1}\n\n\\end{frame}\n\n% \\begin{frame}{Factorization}\n% $|A|=p_1^{e_1}\\cdots p_{\\ell}^{e_{\\ell}}$\n\n% \\begin{block}{Fact}\n%     $A$ abelian implies $A=P_1\\times \\cdots \\times P_{\\ell}$ with $|P_i|=p_i^{e_i}$.\n% \\end{block}\n\n% \\begin{block}{Fact}\n%     $A$ a ring implies $A=P_1\\times \\cdots \\times P_{\\ell}$ with $|P_i|=p_i^{e_i}$.\n% \\end{block}\n\n% \\begin{block}{Fact}\n%     $A$ Lie algebra implies $A=P_1\\times \\cdots \\times P_{\\ell}$ with $|P_i|=p_i^{e_i}$.\n% \\end{block}\n\n\n% \\begin{block}{Almost fact}\n%     $A$ a group then $A$ comes close to \n%     $P_1\\times \\cdots \\times P_{\\ell}$ with $|P_i|=p_i^{e_i}$.\n% \\end{block}\n\n% \\end{frame}\n\n\n\\begin{frame}{Division Graph: Erd\\H{o}s-P\\'{a}lfy}\n\nFactor $n$ into a \\emph{graph} $\\Gamma(n)$.  \\\\\nEdge $(p_i^{e_i},p_j^{e_j})$\nwhere $p_i|p_j^k-1$ for some $k\\leq e_j$, \\& symmetrically.  \n\n\\begin{block}{Erd\\H{o}s-P\\'{a}lfy, 1999}\n    A group $G$ of order $n$ factors as \n\\[N_1\\times \\cdots \\times N_{\\ell},\\] \n$|N_i|=n_i$, order of connected component $i$ in $\\Gamma(n)$.\n\\end{block}\n\n\\pause\n\n\\begin{block}{Example $n=1785$}\n\\begin{center}\n\\begin{tikzpicture}\n\\node[circle,draw] (3) at (0,0) {$3$};\n\\node[circle,draw] (5) at (1,0) {$5$};\n\\node[circle,draw] (7) at (0,1) {$7$};\n\\node[circle,draw] (17) at (1,1) {$17$};\n\n\\draw[-,thick] (3) to (7);\n\n\\node at (6,1) {$|G|=n\\Rightarrow N_{3\\cdot 7}\\times N_5\\times N_{17}$};\n\\end{tikzpicture}\n\\end{center}\n\\end{block}\n\n\n\\end{frame}\n    \n\\begin{frame}{Extending implications}\n\nFactor $n$ into a \\emph{direct hypergraph} $\\mathcal{H}(n)$.  (i) \\emph{Oriented}\nErd\\H{o}s-P\\'{a}lfy \\emph{hyper-}edges, (ii) exceptions for \nfinite nonabelian simple groups.\n\n\\begin{block}{Proposition}\n    A group $G$ of order $n$ factors as \n\\[N_0\\ltimes (N_1\\ltimes \\cdots \\ltimes N_{\\ell}),\\] \n$|N_i|=n_i$, where $n_i$ is order of interconnected components of $\\mathcal{H}(n)$. \n\\end{block}\n\n\\pause\n\\begin{block}{Example $n=5,810,340$}\n\\begin{tikzpicture}\n\\node[circle,draw] (2) at (0,-1) {$2^2$};\n\\node[circle,draw] (3) at (0,1) {$3$};\n\\node[circle,draw] (5) at (-1.5,0) {$5$};\n\\node[circle,draw] (179) at (2,1) {$179$};\n\\node[circle,draw] (547) at (2,-1) {$547$};\n\n\\draw[->,thick] (2) to[bend right=30]  (3);\n\\draw[->,thick] (2) to[bend left=30]  (5);\n\\draw[->,thick] (2) to[bend right=20] (179);\n\\draw[->,thick] (2) to[bend right=20] (547);\n\n\\draw[->,thick] (5) to (-0.5,0) to[bend right=30] (3);\n\\draw[->,thick] (-0.5,0) to[bend left=30] (2);\n\n\\draw[->,thick] (3) to[bend left=30] (2);\n\n\n\\node at (6,1) {$|G|=n\\Rightarrow N_{60}\\ltimes (N_{179}\\times N_{547})$};\n\n\\end{tikzpicture}\n\\end{block}\n\n\n\\end{frame}\n\n\\begin{frame}{Most Orders}\n\n\\begin{center}\n\\begin{tikzpicture}\n\n\\fill[color=black!20,rounded corners] (-2.5,2) rectangle (1,-2);\n\\fill[color=blue!20,rounded corners] (1,2) rectangle (7,-2);\n\n\\node[circle,draw] (2) at (0,-1) {$p_1^{e_1}$};\n\\node[circle,draw] (3) at (0,1) {$p_2^{e_2}$};\n\\node[circle,draw] (5) at (-1.5,0) {$p_m^{e_{m}}$};\n\\node[circle,draw] (179) at (3,1) {$p_{m+1}$};\n\\node[circle,draw] (547) at (3,-1) {$p_{\\ell}$};\n\\node[circle,draw] (1949) at (4,0.5) {$p_{k}$};\n\\node[circle,draw] (7893) at (5,-0.5) {$p_{j}$};\n\n\n\n\\draw[->,thick] (2) to[bend right=30]  (3);\n\\draw[->,thick] (2) to[bend left=30]  (5);\n\\draw[->,thick] (2) to[bend right=20] (179);\n\\draw[->,thick] (2) to[bend right=20] (547);\n\n\\draw[->,thick] (5) to (-0.5,0) to[bend right=30] (3);\n\\draw[->,thick] (-0.5,0) to[bend left=30] (2);\n\n\\draw[->,thick] (3) to[bend left=30] (2);\n\n\\draw[->,thick] (3) to[bend right=20] (7893);\n\n\\visible<2->{\n\\node[color=red] at (-1,2.25) {Hard Group Theory};\n\\node[color=red] at (4,2.25) {Hard Number Theory};\n};\n\n\\visible<3->{\n\\node[color=csugreen] at (-1,-2.25) {Tiny Numbers};\n\\node[color=csugreen] at (4,-2.25) {Cyclic Groups};\n\\node at (2.5,-4) {$G=H\\ltimes (\\mathbb{Z}_{p_{m+1}}\\times\\cdots \\times \\mathbb{Z}_{p_{\\ell}})$};\n};\n\n\n\\end{tikzpicture}    \n\\end{center}\n\n\\end{frame}\n\n% \\begin{frame}{}\n% \\begin{itemize}\n%     \\item Factor $n=ab$ where prime $p|n$, $p\\geq\\log \\log n$ and not exceptional\\footnote{primes strongly connected or involved in identifying a nonabelian simple group} then $p|b$;\n%     otherwise $p|a$.\n    \n%     \\item Factor $G=H\\ltimes_{\\theta} B$ with prime divisors $p>\\log \\log n$ dividing\n%     $|B|$ but not $|H|$ (unless exceptional divisor of finite simple groups).\n%     Likewise decompose $\\tilde{G}=\\tilde{H}\\ltimes_{\\tilde{\\theta}} \\tilde{B}$.\n\n%     \\item Brute-force decide $H\\cong \\tilde{H}$.\n%     \\item Canonical isomorphism $B\\cong \\mathbb{Z}_b\\cong \\tilde{B}$ by Group Theory.\n%     \\item Adjust $\\theta$ to match $\\tilde{\\theta}$ if possible.\n\n% \\end{itemize}\n% \\end{frame}\n\n\n%==============================================================================\n\\section{Is it a Group Table?}\n\n\\begin{frame}{Promise-to-decision}\n\nA great many computational algebra are analyzed as \\textbf{promise problems}\nnot \\textbf{decision problems}.\n\nIdentity testing is needed to remove the promise; unsolvable in general (word problem), \nbut on tables at least brute-force.\n\\pause\n\n\\begin{block}{Theorem Rajagopalan-Schulman, 2000}\n    Given $*:[n]\\times [n]\\to [n]$, test associativity (and other identities) in\n    nearly-linear time $\\tilde{O}(n^2)$ in RAM model (constant time ops and\n    memory access). Also can test if a group.\n\\end{block}\n\n\\end{frame}\n\n\\begin{frame}{RAM-to-TM}\n\nAt larger scales Turing Machine (TM) model better match to computations \nthat are communication bounded (typical in practice).\n\nRAM $\\to$ TM at most a quadratic blow-up.\n\\begin{block}{Corollary}\nNearly Quadratic-time $\\tilde{O}(n^4)$ on multi-tape Turing Machine (TM).\n\\end{block}\n\n\\pause\n\\begin{block}{Theorem Dietrich-W.}\n    Given $*:[n]\\times [n]\\to [n]$,\n    test if a group in time nearly-linear time\n    $\\tilde{O}(n^2)$ on deterministic multi-tape TM.\n    % \\footnote{One tape of input length $\\ell\\in O(n^2)$,\n    % and another of length $O(\\sqrt{\\ell})$.}\n\\end{block}\n\n\\end{frame}\n\n% \\begin{frame}{IsGroup Sketch}\n% \\tikzset{\n% mybox/.style={\n%     inner sep=0pt,\n%     text width=5mm,\n%     text height=5mm,\n%     align=center,\n%     }\n% }\n% \\begin{tikzpicture}\n% \\node[fill=blue!0, label=center:1,mybox] at  ( 0mm, -0mm) {};\n% \\node[fill=blue!20,label=center:2,mybox] at  ( 5mm, -0mm) {};\n% \\node[fill=blue!20,label=center:3,mybox] at  (10mm, -0mm) {};\n% \\node[fill=blue!30,label=center:4,mybox] at  (15mm, -0mm) {};\n% \\node[fill=blue!40,label=center:5,mybox] at  (20mm, -0mm) {};\n% %\n% \\node[fill=blue!10,label=center:2,mybox] at  ( 0mm, -5mm) {};\n% \\node[fill=blue!30,label=center:4,mybox] at  ( 5mm, -5mm) {};\n% \\node[fill=blue!0, label=center:1,mybox] at  (10mm, -5mm) {};\n% \\node[fill=blue!40,label=center:5,mybox] at  (15mm, -5mm) {};\n% \\node[fill=blue!20,label=center:3,mybox] at  (20mm, -5mm) {};\n% %\n% \\node[fill=blue!20,label=center:3,mybox] at  ( 0mm,-10mm) {};\n% \\node[fill=blue!40,label=center:5,mybox] at  ( 5mm,-10mm) {};\n% \\node[fill=blue!30,label=center:4,mybox] at  (10mm,-10mm) {};\n% \\node[fill=blue!10,label=center:2,mybox] at  (15mm,-10mm) {};\n% \\node[fill=blue!0, label=center:1,mybox] at  (20mm,-10mm) {};\n% %\n% \\node[fill=blue!30,label=center:4,mybox] at  ( 0mm,-15mm) {};\n% \\node[fill=blue!0, label=center:1,mybox] at  ( 5mm,-15mm) {};\n% \\node[fill=blue!40,label=center:5,mybox] at  (10mm,-15mm) {};\n% \\node[fill=blue!20,label=center:3,mybox] at  (15mm,-15mm) {};\n% \\node[fill=blue!10,label=center:2,mybox] at  (20mm,-15mm) {};\n% %\n% \\node[fill=blue!40,label=center:5,mybox] at  ( 0mm,-20mm) {};\n% \\node[fill=blue!20,label=center:3,mybox] at  ( 5mm,-20mm) {};\n% \\node[fill=blue!10,label=center:2,mybox] at  (10mm,-20mm) {};\n% \\node[fill=blue!0, label=center:1,mybox] at  (15mm,-20mm) {};\n% \\node[fill=blue!30,label=center:4,mybox] at  (20mm,-20mm) {};\n% \\end{tikzpicture}\n\n% \\end{frame}\n\n\n\\begin{frame}{IsGroup}\n\n\\begin{tikzpicture}\n    \\node at (0,0) {$\n        \\begin{array}{|c|ccccc|}\n        \\hline\n        \\bullet & 1 & 2 & 3 & 4 & 5\\\\\n        \\hline\n        1 & 1 & 2 & 3 & 4 & 5\\\\\n        2 & 2 & 1 & 4 & 5 & 3\\\\\n        3 & 3 & 5 & 1 & 2 & 4\\\\\n        4 & 4 & 3 & 5 & 1 & 2\\\\\n        5 & 5 & 4 & 2 & 3 & 1\\\\\n        \\hline\n        \\end{array}   \n    $};\n    \\visible<2->{\n    \\node at (6,0) {$\n        \\rho(2)  = \n        \\begin{array}{|ccccc|}\n        \\hline\n            1 & 2 & 3 & 4 & 5 \\\\\n        \\hline \n            2 & 1 & 4 & 5 & 3 \\\\\n        \\hline \\end{array}    \n        =\n        (1,2)(3,5,4)\n    $};\n    };\n    \\visible<3->{\n    \\node at (0,-3) {\\begin{tikzpicture}\n        \\node[circle,draw] (1) at (0,0) {1};\n        \\node[circle,draw] (2) at (2,0) {2};\n        \\draw[->,thick] (1) to[bend left=30] (2);\n        \\draw[->,thick] (2) to[bend left=30] (1);\n    \\end{tikzpicture}};\n    \\node at (0,-4.5) {$G_{1}=\\langle (354)\\rangle$};\n    };\n    \\visible<4->{\n    \\node at (3,-3) {\\begin{tikzpicture}\n        \\node[circle,draw] (3) at (-1,0) {3};\n        \\node[circle,draw] (4) at (0.5,0.7) {5};\n        \\node[circle,draw] (5) at (0.5,-0.7) {4};\n\n        \\draw[->,thick] (3) to[bend left=30] (4);\n        \\draw[->,thick] (4) to[bend left=30] (5);\n        \\draw[->,thick] (5) to[bend left=30] (3);\n    \\end{tikzpicture}};\n    \\node at (3,-4.5) {$G_{13}=\\{1\\}$};\n    };\n    \\visible<5>{\n    \\node[text width=4cm] at (8,-3) {$|G|=[G:G_1][G_1:G_{13}]$\\\\ $~=2\\cdot 3=6$.\\\\  Should be 5,\\\\ not a group.};\n    };\n\\end{tikzpicture}\n\n\\end{frame}\n\n    \n\\begin{frame}{IsGroup}\n    \\begin{tikzpicture}\n        \\node at (0,0) {$\n        \\begin{array}{|c|ccccc|}\n        \\hline\n        * & 1 & 2 & 3 & 4 & 5 \\\\\n        \\hline \n        1 & 1 & 2 & 3 & 4 & 5 \\\\ \n        2 & 2 & 4 & 1 & 5 & 3 \\\\\n        3 & 3 & 5 & 4 & 2 & 1 \\\\\n        4 & 4 & 1 & 5 & 3 & 2 \\\\\n        5 & 5 & 3 & 2 & 1 & 4 \\\\\n        \\hline \\end{array}    \n        $};\n        \\visible<2->{\n        \\node at (6,0) {$\n            \\rho(2)  = \n            \\begin{array}{|ccccc|}\n            \\hline\n                1 & 2 & 3 & 4 & 5 \\\\\n            \\hline \n                2 & 4 & 1 & 5 & 3 \\\\\n            \\hline \\end{array}    \n            =\n            (1,2,4,5,3)\n        $};\n        };\n        \\visible<3->{\n        \\node at (0,-3) {\\begin{tikzpicture}\n            \\node[circle,draw] (1) at (1,0) {1};\n            \\node[circle,draw] (2) at (0.3,0.8) {2};\n            \\node[circle,draw] (3) at (-0.6,0.5) {3};\n            \\node[circle,draw] (4) at (-0.6,-0.5) {4};\n            \\node[circle,draw] (5) at (0.3,-0.8) {5};\n\n            \\draw[->,thick] (1) to[bend right=30] (2);\n            \\draw[->,thick] (2) to[bend left=30] (4);\n            \\draw[->,thick] (4) to[bend right=30] (5);\n            \\draw[->,thick] (5) to[bend right=30] (3);\n            \\draw[->,thick] (3) to[bend right=30] (1);\n        \\end{tikzpicture}};\n        \\node at (0,-4.5) {$|G|=[G:G_{1}|=5$};\n        };\n        \\visible<4>{\n        \\node[text width=4cm] at (7,-3) {$\n        \\begin{array}{|c|ccccc|}\n        \\hline\n        * & 1 & 2 & 3 & 4 & 5 \\\\\n        \\hline \n        \\rho(2)^0 & 1 & 2 & 3 & 4 & 5 \\\\ \n        \\rho(2)^1 & 2 & 4 & 1 & 5 & 3 \\\\\n        \\rho(2)^2 & 4 & 5 & 2 & 3 & 1 \\\\\n        \\hline \\end{array}    \n        $\\\\\n\n        $\\rho(2)^2=45231\\neq T_4=41532$\\\\ Not a group.};\n        };\n    \\end{tikzpicture}\n\\end{frame}\n\n% \\begin{frame}{IsGroup}\n%     \\begin{tikzpicture}\n%         \\node at (0,0) {$\n%         \\begin{array}{|c|ccccc|}\n%         \\hline\n%         * & 1 & 2 & 3 & 4 & 5 \\\\\n%         \\hline \n%         1 & 1 & 2 & 3 & 4 & 5 \\\\ \n%         2 & 2 & 4 & 1 & 5 & 3 \\\\\n%         3 & 4 & 5 & 4 & 2 & 1 \\\\\n%         4 & 4 & 1 & 5 & 3 & 2 \\\\\n%         5 & 5 & 3 & 2 & 1 & 4 \\\\\n%         \\hline \\end{array}    \n%         $};\n%         \\visible<2->{\n%         \\node at (6,0) {$\n%             \\rho(2)  = \n%             \\begin{array}{|ccccc|}\n%             \\hline\n%                 1 & 2 & 3 & 4 & 5 \\\\\n%             \\hline \n%                 2 & 4 & 1 & 5 & 3 \\\\\n%             \\hline \\end{array}    \n%             =\n%             (1,2,4,5,3)\n%         $};\n%         };\n%         \\visible<3->{\n%         \\node at (0,-3) {\\begin{tikzpicture}\n%             \\node[circle,draw] (1) at (1,0) {1};\n%             \\node[circle,draw] (2) at (0.3,0.8) {2};\n%             \\node[circle,draw] (3) at (-0.6,0.5) {3};\n%             \\node[circle,draw] (4) at (-0.6,-0.5) {4};\n%             \\node[circle,draw] (5) at (0.3,-0.8) {5};\n\n%             \\draw[->,thick] (1) to[bend right=30] (2);\n%             \\draw[->,thick] (2) to[bend left=30] (4);\n%             \\draw[->,thick] (4) to[bend right=30] (5);\n%             \\draw[->,thick] (5) to[bend right=30] (3);\n%             \\draw[->,thick] (3) to[bend right=30] (1);\n%         \\end{tikzpicture}};\n%         \\node at (0,-4.5) {$|G|=[G:G_{1}|=5$};\n%         };\n%         \\visible<4>{\n%         \\node[text width=4cm] at (7,-3) {$\n%         \\begin{array}{|c|ccccc|}\n%         \\hline\n%         * & 1 & 2 & 3 & 4 & 5 \\\\\n%         \\hline \n%         \\rho(2)^0 & 1 & 2 & 3 & 4 & 5 \\\\ \n%         \\rho(2)^1 & 2 & 4 & 1 & 5 & 3 \\\\\n%         \\rho(2)^2 & 4 & 5 & 2 & 3 & 1 \\\\\n%         \\hline \\end{array}    \n%         $\\\\\n\n%         $\\rho(2)^2=45231\\neq T_4=41532$\\\\ Not a group.};\n%         };\n%     \\end{tikzpicture}\n% \\end{frame}\n\n% \\begin{frame}{IsGroup Generalizing}\n\n% \\begin{block}{Main idea}\n% \\begin{itemize}\n%     \\item Map putative generator $S$ into efficient representation of class, e.g. permutations.\n%     \\item Explore representation to efficiently reproduce table\n%     \\item Compare tables.\n% \\end{itemize}\n% \\end{block}\n\n% \\begin{block}{Question:}\n% Do other classes of tables permit this representation approach?\n% \\end{block}\n\n\n% \\end{frame}\n\n\\section{Summary}\n\n\\begin{frame}{Summary}\n\n\\begin{block}{IsGroup nearly linear time}\n    From $\\tilde{O}(n^4)$ to $\\tilde{O}(n^2)$: \n    Promise-to-decision by transferring group to permutation model.\n\\end{block}\n\n\\begin{block}{GroupIso most orders nearly linear time}\n    From $n^{O(\\log n)}$ to $\\tilde{O}(n^2)$: \n    Split group into\n    \\begin{center} \n        hard group $\\ltimes$ hard numbers \n        = tiny numbers $\\ltimes$ cyclic groups.\n    \\end{center}\n    Then standard divide-and-conquer.\n\\end{block}\n\n\\rule{\\textwidth}{1pt}\n{\\tiny Thanks to: Newton Institute (Cambridge, UK) \nEPSRC Grant Number EP/R014604/1, Australian Research Council grant\nDP190100317, and Simons Foundation Grant 636189.}\n\\end{frame}\n\n% \\begin{frame}{}\n\n% \\begin{block}{Theorem.}\n% A positive density of positive integers $n$ has $\\Gamma(n)$ such \n% that the \n% \\end{block}\n\n% \\end{frame}\n\n% \\begin{frame}{Most integers factor like this}\n\n    \n% \\begin{tikzpicture}\n% \\node[circle,draw] (3) at (0,0) {$3$};\n% \\node[circle,draw] (31) at (1,1) {$31$};\n% \\node[circle,draw] (137) at (1,-1) {$137$};\n% \\node[circle,draw] (379) at (2,-1) {$379$};\n% \\node[circle,draw] (1949) at (3,0) {$1949$};\n\n% \\draw[->,thick] (3) to[bend left=30] (0,0.5) to[bend right=30] (31);\n% \\draw[->,thick] (3) to[bend left=30] (0,0.5) to[bend right=30] (31);\n% % \\draw[->,thick] (0,0.5) to[bend left=30] (5);\n% % \\draw[->,thick] (0,0.5) to[bend right=20] (541);\n\n% % \\draw[->,thick] (5) to[bend right=30] (-0.25,-0.5) to[bend right=30] (3);\n% % \\draw[->,thick] (-0.25,-0.5) to[bend left=30] (2);\n\n% % \\draw[->,thick] (3) to[bend right=30] (2);\n\n\n% % \\node at (6,1) {$|G|=n\\Rightarrow N_{60}\\ltimes N_{541}$};\n\n% \\end{tikzpicture}\n    \n% \\end{frame}\n\n\\end{document}", "meta": {"hexsha": "e3bed3426c3215f48de88141c3f718789a48379c", "size": 34982, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "FOCS21/FOCS.tex", "max_stars_repo_name": "algeboy/talks", "max_stars_repo_head_hexsha": "0787c45eb8d69ac4bbf5e23a35b9f83d910b5d73", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FOCS21/FOCS.tex", "max_issues_repo_name": "algeboy/talks", "max_issues_repo_head_hexsha": "0787c45eb8d69ac4bbf5e23a35b9f83d910b5d73", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FOCS21/FOCS.tex", "max_forks_repo_name": "algeboy/talks", "max_forks_repo_head_hexsha": "0787c45eb8d69ac4bbf5e23a35b9f83d910b5d73", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5722021661, "max_line_length": 184, "alphanum_fraction": 0.5724086673, "num_tokens": 14102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792046, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.3483332650286089}}
{"text": "\\documentclass[12pt]{cdblatex}\n\\usepackage{exercises}\n\\usepackage{fancyhdr}\n\\usepackage{footer}\n\n\\begin{document}\n\n% --------------------------------------------------------------------------------------------\n\\section*{Exercise 1.6 Multiple {\\tt SortOrder} lists}\n\n\\begin{cadabra}\n   {D,C,B,A}::SortOrder.  # first SortOrder list\n\n   foo := A B C D .       # cdb(ex-0106.101,foo)\n\n   sort_product (foo)     # cdb(ex-0106.102,foo)\n\n   {V,U}::SortOrder.      # second SortOrder list, all entries distinct from first list\n\n   foo := U V A B C D .   # cdb(ex-0106.201,foo)\n\n   sort_product (foo)     # cdb(ex-0106.202,foo)\n\n   {A,B,C,D}::SortOrder.  # all entries in this list appear in the\n                          # first SortOrder so they will be effectively ignored\n\n   foo := U V D C B A .   # cdb(ex-0106.301,foo)\n\n   sort_product (foo)     # cdb(ex-0106.302,foo)\n\\end{cadabra}\n\n% \\clearpage\n\n\\begin{dgroup*}[spread=2pt]\n   \\Dmath*{\\cdb*{ex-0106.101}}\n   \\Dmath*{\\cdb*{ex-0106.102}}\n\\end{dgroup*}\n\n\\begin{dgroup*}[spread=2pt]\n   \\Dmath*{\\cdb*{ex-0106.201}}\n   \\Dmath*{\\cdb*{ex-0106.202}}\n\\end{dgroup*}\n\n\\begin{dgroup*}[spread=2pt]\n   \\Dmath*{\\cdb*{ex-0106.301}}\n   \\Dmath*{\\cdb*{ex-0106.302}}\n\\end{dgroup*}\n\n\\end{document}\n", "meta": {"hexsha": "dda1fb06b5bb06ceaf5038e91276fa4eee01619f", "size": 1227, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "source/cadabra/exercises/ex-0106.tex", "max_stars_repo_name": "leo-brewin/cadabra-tutorial", "max_stars_repo_head_hexsha": "5b428ae158b5346315ab6c975dee9de933e5c3d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2019-12-20T07:49:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T22:55:47.000Z", "max_issues_repo_path": "source/cadabra/exercises/ex-0106.tex", "max_issues_repo_name": "leo-brewin/cadabra-tutorial", "max_issues_repo_head_hexsha": "5b428ae158b5346315ab6c975dee9de933e5c3d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/cadabra/exercises/ex-0106.tex", "max_forks_repo_name": "leo-brewin/cadabra-tutorial", "max_forks_repo_head_hexsha": "5b428ae158b5346315ab6c975dee9de933e5c3d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-22T13:52:19.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-22T13:52:19.000Z", "avg_line_length": 24.54, "max_line_length": 94, "alphanum_fraction": 0.5729421353, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.3482894268451717}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\marginpar{Friday\\\\ 2020-3-27, \\\\ compiled \\\\ \\today}\n\nWe can always decompose a Hermitian matrix in a basis: if \\(M = M ^\\dag\\) then \\(M = r_{\\mu } \\hat{\\Gamma}_{\\mu } \\).\nIf we choose the matrices so that \\(\\Tr [\\hat{\\Gamma}_{\\mu } \\hat{\\Gamma}_{\\nu }] = \\delta_{\\mu \\nu }\\), we can use the Euclidean scalar product. \n\n\\section{Bell nonlocality}\n\nWe will follow some of  \\cite[]{brunnerBellNonlocality2014}. \n\nWhen first encountering QM, people usually think in terms of statistics. \n\nLet us make an explicit example for a hidden variable theory. \n\nLet us suppose we have a qubit which is described by the density matrix \n%\n\\begin{align}\n\\rho = \\frac{1}{2} \\qty(\\mathbb{1} + \\vec{s} \\cdot \\vec{\\sigma})\n\\,,\n\\end{align}\n%\nwhere \\(\\vec{s}\\) is a unit vector in the Bloch sphere. \nNow, we can measure spins: our observables are in the form \\(\\hat{A} = \\vec{a} \\cdot \\vec{\\sigma}\\), which means we are measuring the spin in the direction of the unit vector \\(\\vec{a}\\). \n\nThe expectation value is \n%\n\\begin{align}\n\\expval{\\hat{A}} = \\Tr (\\hat{A} \\rho ) = \\vec{a} \\cdot \\vec{s}\n= \\cos \\theta  = (+1) \\mathbb{P} (+1) + (-1) \\mathbb{P}(-1)\n\\,,\n\\end{align}\n%\nwhere \\(\\theta \\) is the angle between \\(\\vec{a}\\) and \\(\\vec{s}\\). \n\nIs the output of the measurement prescribed by some hidden variable \\(\\lambda \\)?\n\nIf so, we would need to describe the state with the pair \\((\\rho , \\lambda )\\). Then, if \\(A(\\lambda )\\) is the function associating a value of \\(\\lambda \\) to its outcome we will have \n%\n\\begin{align}\n\\expval{\\hat{A}} = \\int \\dd{\\mu_{\\rho }(\\lambda )} A(\\lambda )\n\\,.\n\\end{align}\n\nIn principle \\(A(\\lambda )\\) would also depend on \\(\\rho \\), but we can rescale the measure on the space so that it doesn't. \n\nSuppose \\(\\vec{\\lambda}\\) is defined on the hemisphere \\(\\vec{\\lambda} \\cdot \\vec{s} \\geq 0 \\) and \\(\\abs{\\vec{\\lambda}} =1\\).\nThen, \\(\\dd{\\mu_{\\rho }(\\lambda )}\\) is a uniform density function defined there, and it is zero otherwise. \n\nLet us define the unit vector \\(\\vec{a}'\\) so that \n%\n\\begin{align}\nA(\\lambda ) = \\sign(\\vec{\\lambda } \\cdot \\vec{a}')\n\\,,\n\\end{align}\n%\nand so that \\(\\vec{a}'\\) is in the plane defined by \\(\\vec{s}\\) and \\(\\vec{a} \\) and the angle between \\(\\vec{s}\\) and \\(\\vec{a}'\\) is \\(\\theta'\\), defined by \n%\n\\begin{align}\n1 - \\frac{2 \\theta'}{\\pi } = \\cos  \\theta \n\\,.\n\\end{align}\n\nWith this, we have a statistical model which describes quantum mechanics. \n\nThe problem comes along when we consider Bell inequalities, which deal with multiple systems. \n\nThen, in the Hidden Variable theory we will have \n%\n\\begin{align}\n\\expval{\\hat{A} \\otimes \\hat{B}} = \\int \\dd{\\mu_{\\rho } (\\lambda )} F(\\lambda )\n\\,,\n\\end{align}\n%\nbut if we assume we have locality then (as shown in Phys Rev 47, 777 (1935), the EPR paper) we must impose that there can be no causal link between events which are spacelike-separated. \nSo, under a Local Hidden Variable model we must have that the events are independent: so we must write \n%\n\\begin{align}\n\\expval{\\hat{A} \\otimes \\hat{B}} = \\int \\dd{\\mu_{\\rho } (\\lambda )} A(\\lambda ) B(\\lambda )\n\\,.\n\\end{align}\n\nReality means determinism: if we have reality and we fix \\(\\lambda \\) then the result of the measurement is also fixed. \n\nWhat Bell did was to probe that this kind of expression is incompatible with the prediction of QM: if we consider the operator \n%\n\\begin{align} \nS =\n\\expval{\\hat{A} \\otimes \\hat{B}}+\n\\expval{\\hat{A} \\otimes \\hat{B}'} +\n\\expval{\\hat{A}' \\otimes \\hat{B}} -\n\\expval{\\hat{A}' \\otimes \\hat{B}'} \n\\,,\n\\end{align}\n%\nwhere \\(\\hat{A}'\\) and \\(\\hat{B}'\\) are two different observables Alice and Bob can choose to measure randomly, and which both have eigenvalues \\(\\pm 1\\). Then, we have that its expectation value is \n%\n\\begin{align}\n\\int \\dd{\\mu (\\lambda )} \\qty[A (B + B') + A' (B - B')] \n\\,,\n\\end{align}\n%\nand this is upper-bounded by 2. \nIf we do an experiment, and measure a value which is greater than 2, then we have falsified LHV theory. \nQuantum Mechanics tells us we can indeed go beyond 2. \nIf we choose \\(\\vec{a}\\) and \\(\\vec{a}'\\) at right angles to each other, \\(\\vec{b} \\) and \\(\\vec{b}'\\) likewise, with an angle of \\(\\pi /4\\) between them, then it can be shown that if the state \\(\\rho \\) is a singlet then \n%\n\\begin{align}\n\\expval{(\\vec{a} \\cdot \\vec{\\sigma}) \\otimes (\\vec{a} \\cdot \\vec{\\sigma})} = - \\vec{a} \\cdot \\vec{b} \n\\,,\n\\end{align}\n%\nso if \\(\\vec{a} = \\vec{b} \\) we have perfect anticorrelation. So we get \n%\n\\begin{align}\n\\expval{\\abs{S}} = \\abs{- \\frac{1}{\\sqrt{2}} - \\frac{1}{\\sqrt{2}} - \\frac{1}{\\sqrt{2}} - \\frac{1}{\\sqrt{2}} } = 2 \\sqrt{2} \\approx 2.8  > 2\n\\,.\n\\end{align}\n\nSo, we either reject determinism or we reject locality. \n\nIn the orthodox interpretation of QM the theory is simply nondeterministic. \n\nThis is wonderful theoretically, but there are loopholes. \nOnly in 2015 the experiment was done in a loophole-free way. \n\n\\subsection{Loopholes}\n\n\\subsubsection{Freedom of choice}\n\nIn the experiment we discussed before Alice and Bob could choose in a random way between the two measurements. This is important since if the measurements are predetermined then that is a hidden variable. \nIf the measurements are fixed then we can describe the statistics with a hidden variable theory. \n\n\\subsubsection{Locality}\n\nThe choice of the measurement basis must be done late enough so that the events are still spacelike separated. \nSo, we should choose the measurement basis so that the photons have almost arrived when we decide. \n\n\\subsubsection{Detection loophole}\n\nPhotons are not revealed efficiently: they are lost in detection, so we may reveal only a small fraction of the total photons. \n\n\\subsubsection{Superdeterminism}\n\nIt has not been possible yet to exclude that all of nature is completely predetermined. \n\nWhen we write the correlation between two operators, we write something like \n%\n\\begin{align}\n\\expval{A \\otimes B} = \\sum _{ij} ij \\mathbb{P}_{AB} (ij)\n\\,,\n\\end{align}\n%\nbut we have that \\(\\mathbb{P} (a, b) + \\mathbb{P} (\\overline{a}, b) = \\mathbb{P}(b)\\). \nThen, we can find that \n%\n\\begin{align}\n\\expval{A \\otimes B} = 4 \\mathbb{P}(a, b) - 2 P_A(a) -2 P_B(b) +1\n\\,,\n\\end{align}\n%\nwhich is useful since it contains only positive results. \nThis allows us to write \n%\n\\begin{align}\nS_{CHSH} = 4S_{CH} + 2\n\\qquad \\text{where} \\qquad\nS_{CH} = \\mathbb{P}(a, b) \n+ \\mathbb{P} (a', b) \n+ \\mathbb{P} (a, b') \n- \\mathbb{P}(a) - \\mathbb{P}(b)\n\\,,\n\\end{align}\n%\nand \\(S_{CHSH}\\leq 2\\) is equivalent to \\(S_{CH} \\leq 0\\). The advantage is that we do not need to normalize for the total number of events: we can write this directly as \n%\n\\begin{align}\nN(a, b) \n+ N (a', b) \n+ N (a, b') \n- N(a) - N(b)\n\\leq 0\n\\,,\n\\end{align}\n%\nso we have no issue with lost photons. \n\nIf the efficiency is \\(\\eta \\) for each channel, then experimentally we will measure \n%\n\\begin{align}\nS_{CH}^{\\text{exp}} = \\eta^2 \\qty[\\mathbb{P}(a, b) \n+ \\mathbb{P} (a', b) \n+ \\mathbb{P} (a, b') ]\n- \\eta \\qty[\\mathbb{P}(a) + \\mathbb{P}(b)]\n\\,,\n\\end{align}\n%\nwhere the term multiplying \\(\\eta^2\\) is precisely \\(S_{CHSH}+ \\mathbb{P}(a) + \\mathbb{P}(b)\\). If we want to violate the inequalities, we must have \\(S_{CH}^{\\text{exp}} > 0\\): the minimum efficiency is \n%\n\\begin{align}\n\\eta_{*} = \\frac{\\mathbb{P}_{A}(a) + \\mathbb{P}_{B}(b)}{S^{Q}_{CH} + P_{A}(a) + P_{B}(b)}\n\\,,\n\\end{align}\n%\nand if we use maximally entangled singlet states we have \\(\\eta_{*} \\approx 2 \\qty(\\sqrt{2}-1) \\approx \\SI{83}{\\percent}\\). \n\nThis is combined efficiency: an emitted photon must have a \\(\\geq \\SI{83}{\\percent}\\) probability of being revealed. \n\nThe detectors used had less efficiency than this: actually, if we have a state like \\(\\cos \\theta \\ket{00} + \\sin \\theta \\ket{11 }\\) we have a lower \\(\\eta_{*}\\): the best thing is in the limit of \\(\\theta \\rightarrow 0\\), so we will need \\(\\eta_{*} \\approx 2/3 \\approx \\SI{67}{\\percent}\\). \n\nIf we do not have this efficiency, we must make a \\emph{fair sampling assumption}: the photons we do measure are a representative sample of all the photons. \n\nThere were three works published in 2015 which did this: \n\\begin{enumerate}\n  \\item Nature 526, 682\n  \\item PRL 115, 250401\n  \\item PRL 115, 250402\n\\end{enumerate}\n\nIn the works in PRL they used photons, while the work in Nature used electron spins, entangling them with entanglement swapping. \nThe experiment using electrons did not have the detection loophole, but they are very much subject to the locality loophole. \n\nWe can further extend Bell inequalities in multipartite systems. \n\nIf we have three systems, we can measure (denoting \\(\\sigma_{x} = X\\) and so on)\n%\n\\begin{align}\nM_1 &= X_{a} X_{b} X_{c} \\\\\nM_2 &= - Y_{a} Y_{b} X_{c} \\\\\nM_3 &= - Y_{a} X_{b} Y_{c} \\\\\nM_4 &= - Y_{a} Y_{b} Y_{c}\n\\,,\n\\end{align}\n%\nand one can see that \\(M_1 M_2 M_3 = - M_4 \\), so classically if we assume we can write the expectation value as \n%\n\\begin{align}\n\\int \\dd{\\mu } A(\\lambda ) B(\\lambda ) C(\\lambda )\n\\,,\n\\end{align}\n%\nand we can violate these with the GHZ state: \n%\n\\begin{align}\n\\ket{\\text{GHZ}} = \\frac{1}{\\sqrt{2}} \\qty(\\ket{000} + \\ket{111})\n\\,,\n\\end{align}\n%\nand we can see that \n%\n\\begin{align}\n\\expval{M_i} = +1\n\\,,\n\\end{align}\n%\nfor each of these. We can write this as an inequality with \\(M_1 + M_2 + M_3 + M_4 \\leq 2\\). \n\nThe nice thing is that we can do this with perfect correlations, while in CHSH we do not have perfect correlations. \n\nOne could actually see that this can be generalized to \\(N\\) qubits: as we increase the dimension, the violation increases exponentially: \n%\n\\begin{align}\n\\frac{\\beta_{Q}}{\\beta_{c}} \\sim 2^{N}\n\\,,\n\\end{align}\n%\nwhere \\(\\beta \\) is the value we obtain for the inequality. \n\nNo one has yet done a loophole-free measurement with three subsystems, but loophole-wrought measurements have indeed been done. \n\nWe can also improve the violation s increasing the dimensionality of two systems, that is, using Q-dits.\n\nOften ``quantum nonlocality'' is discussed, but this is imprecise: we cannot really prove that quantum mechanics is nonlocal, we can only say that it either is  nonlocal or nondeterministic. \n\n\\end{document}\n", "meta": {"hexsha": "9f0674d8f956186d2c8078a55571f16d8824c138", "size": 10109, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "quantum_optics/mar27.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "quantum_optics/mar27.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "quantum_optics/mar27.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 36.4945848375, "max_line_length": 291, "alphanum_fraction": 0.6762291028, "num_tokens": 3250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.6654105587468141, "lm_q1q2_score": 0.3482894268451717}}
{"text": "%\\documentclass[12pt]{article}\n\\documentclass[12pt,landscape]{article}\n\n\n\\include{preamble}\n\n\\newcommand{\\instr}{\\small Your answer will consist of a lowercase string (e.g. \\texttt{aebgd}) where the order of the letters does not matter. \\normalsize}\n\n\\title{Math 368 / 621 Fall \\the\\year{} \\\\ Final Examination}\n\\author{Professor Adam Kapelner}\n\n\\date{Wednesday, December 14, \\the\\year{}}\n\n\\begin{document}\n\\maketitle\n\n%\\noindent Full Name \\line(1,0){410}\n\n\\thispagestyle{empty}\n\n\\section*{Code of Academic Integrity}\n\n\\footnotesize\nSince the college is an academic community, its fundamental purpose is the pursuit of knowledge. Essential to the success of this educational mission is a commitment to the principles of academic integrity. Every member of the college community is responsible for upholding the highest standards of honesty at all times. Students, as members of the community, are also responsible for adhering to the principles and spirit of the following Code of Academic Integrity.\n\nActivities that have the effect or intention of interfering with education, pursuit of knowledge, or fair evaluation of a student's performance are prohibited. Examples of such activities include but are not limited to the following definitions:\n\n\\paragraph{Cheating} Using or attempting to use unauthorized assistance, material, or study aids in examinations or other academic work or preventing, or attempting to prevent, another from using authorized assistance, material, or study aids. Example: using an unauthorized cheat sheet in a quiz or exam, altering a graded exam and resubmitting it for a better grade, etc.\n\\\\\n\n\\noindent By taking this exam, you acknowledge and agree to uphold this Code of Academic Integrity. \\\\\n\n%\\begin{center}\n%\\line(1,0){250} ~~~ \\line(1,0){100}\\\\\n%~~~~~~~~~~~~~~~~~~~~~signature~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ date\n%\\end{center}\n\n\\normalsize\n\n\\section*{Instructions}\n\nThis exam is 105 minutes (variable time per question) and closed-book. You are allowed \\textbf{three} pages (front and back) of a \\qu{cheat sheet}, blank scrap paper and a graphing calculator. Please read the questions carefully. No food is allowed, only drinks. %If the question reads \\qu{compute,} this means the solution will be a number otherwise you can leave the answer in \\textit{any} widely accepted mathematical notation which could be resolved to an exact or approximate number with the use of a computer. I advise you to skip problems marked \\qu{[Extra Credit]} until you have finished the other questions on the exam, then loop back and plug in all the holes. I also advise you to use pencil. The exam is 100 points total plus extra credit. Partial credit will be granted for incomplete answers on most of the questions. \\fbox{Box} in your final answers. Good luck!\n\n\\pagebreak\n\n\\problem\\timedsection{14} Let $X_1, X_2, \\ldots$ be a sequence of independent rv's distributed as Deg$(\\mu / n^2)$. Let $T_n := X_1 + X_2 + \\ldots + X_n$.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{18} \n\n\\begin{enumerate}[(a)]\n\\item $X_1$ has no PMF\n\\item $X_1$ has no CDF\n\\item $X_1$ is zero with probability one\n\\item The convolution of $X_1$ and $X_2$ is also degenerate\n\\item The expectation of $X_1$ is $\\mu$\n\\item The variance of $X_1$ is $\\mu^2$\n\\item $\\prob{X_1 \\geq \\mu} \\leq 0$\n\\item The chf of $X_1$ is $\\mu$\n\\item The chf of $X_1$ is $e^{it\\mu}$\n\\item The chf of $X_1$ is $\\in \\mathbb{L}^1$\n\\item The chf of $X_1$ evaluated at 0 is 1\n\\item The mgf of $X_1$ does not exist for some values of $t$ or $\\mu$\n\\item $X_n \\convd 0$\n\\item $X_n \\convp 0$\n\\item $X_n \\convLp{1} 0$\n\\item $X_n$ converges to zero in mean square\n\\item $T_n \\convd 0$\n\\item $T_n$ does not converge in probability.\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\problem\\timedsection{7} Let $\\X \\sim$ Multinomial$(n, \\bv{p})$ and $\\phi_{\\X}(\\bv{t}) = \\tothepow{p_1 e^{i t_1} + p_2 e^{i t_2} + \\ldots + p_K e^{i t_K}}{n}$.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{9} \n\n\\begin{enumerate}[(a)]\n\\item $\\onevec^\\top \\bv{p}$ = 1\n\\item $\\dime{\\X} = K$\n\\item $\\Xoneton$ are independent\n\\item $\\Xoneton$ are identically distributed\n\\item $X_3 \\sim \\binomial{n}{p_3}$\n\\item The chf for $X_3$ is $\\phi_{\\X}\\parens{\\bracks{t_1~t_2~0~t_4~\\ldots~t_K}^\\top}$\n\\item The chf for $X_3$ is $\\phi_{\\X}\\parens{\\bracks{~0~0~t~0~\\ldots~0}^\\top}$\n\\item The chf for $X_3$ is $\\tothepow{p_3 e^{i t} + p_4 e^{i t} \\ldots + p_K e^{i t_K}}{n}$\n\\item The chf for $X_3$ is $\\tothepow{1 + p_3 e^{i t}  - p_3 }{n}$\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\problem\\timedsection{9} Let $X_1, X_2, \\ldots$ be a sequence of iid rv's with mean $\\mu$ and variance $\\sigsq$ finite.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{13} \n\n\\begin{enumerate}[(a)]\n\\item $\\Xbar_n$ is exactly normally distributed\n\\item $\\Xbar_n$ is approximately normally distributed\n\\item The expectation of $\\Xbar_n$ is exactly $\\mu$\n\\item The expectation of $\\Xbar_n$ is approximately $\\mu$\n\\item The variance of $\\Xbar_n$ is exactly $\\sigsq / n$\n\\item The variance of $\\Xbar_n$ is approximately $\\sigsq / n$\n\\item $\\Xbar_n \\convd \\mu$\n\\item $\\Xbar_n \\convp \\mu$\n\\item $Z_n := \\frac{\\Xbar_n - \\mu}{\\sigma / \\sqrt{n}} \\convd \\mu$\n\\item $Z_n := \\frac{\\Xbar_n - \\mu}{\\sigma / \\sqrt{n}} \\convp \\mu$\n\\item $Z_n := \\frac{\\Xbar_n - \\mu}{\\sigma / \\sqrt{n}} \\convd \\oneoversqrt{2\\pi}e^{-z^2/2}$\n\\item Regardless of whether (h) is true or not, it is the main result of the \\qu{central limit theorem}\n\\item Regardless of whether (k) is true or not, it is the main result of the \\qu{central limit theorem}\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\problem\\timedsection{19} Let $X \\sim \\chisq{k}$ and $Y~|~X = x \\sim \\uniform{0}{x}$. For this problem, you may need the following fact from Math 241: for $U \\sim \\uniform{a}{b}$,  $\\var{U} = (b-a)^2 / 12$ and the following fact from this class: for $G \\sim \\gammanot{\\alpha}{\\beta}$, $\\var{G} = \\alpha / \\beta^2$.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{19} \n\n\\begin{enumerate}[(a)]\n\\item $X$ and $Y$ are independent\n\\item $X \\sim \\gammanot{k/2}{1/2}$\n\\item The rv $Y$ is a compound distribution\n\\item The rv $Y$ has one parameter\n\\item $f^{old}_{X,Y}(x,y) = \\oneover{2^k \\Gammaf{k / 2}}x^{k/2 - 2} e^{-x/2}$\n\\item $f^{old}_{X,Y}(x,y) = \\oneover{2^k \\Gammaf{k / 2}}x^{k/2 - 1} y^{-1} e^{-x/2}$\n\\item $f_{X,Y}(x,y)$ is always defined\n\\item $f_{X|Y}(x,y)$ is always defined\n\\item $f_{Y|X}(y,x)$ cannot be computed given the information you have\n\\item The support of the rv $Y$ is all real numbers\n\\item The support of the rv $Y$ is all positive real numbers\n\\item The expectation of $Y$ can be computed via $\\int_\\reals y \\int_\\reals f_{X,Y}(x,y) dx dy$  \n\\item The expectation of $Y$ is $x/2$\n\\item The expectation of $Y$ is $k/2$\n\\item The expectation of $Y$ is $\\sqrt{\\pi}$\n\\item The variance of $Y$ is $k^2 / 12$ \n\\item The variance of $Y~|~X$ is $X^2 / 12$ \n\\item The variance of $Y$ is $(8k + k^2) / 12$ \n\\item The variance of $Y$ cannot be computed given the information you have\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\problem\\timedsection{18} Let $X \\sim T_k$, $U = X^2$, $Y = \\mu + \\sigma X$ and $V = \\mu + \\sigma  U$ where $\\mu \\in \\reals$, $\\sigma > 0$.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{16} \n\n\\begin{enumerate}[(a)]\n\\item $X$ and $V$ are independent\n\\item $f^{old}_X(x) = f_X(x) = \\frac{\\Gammaf{(k+1) / 2}}{\\sqrt{k\\pi} \\Gammaf{k/2}} \\tothepow{1 + x^2 / k}{-(k+1) / 2}$\n\\item $\\support{U} = [0, \\infty)$\n\\item $\\support{V} = [0, \\infty)$\n\\item $\\expe{X} = \\mu$\n\\item $\\expe{Y} = \\mu$\n\\item $\\expe{U} = \\mu$\n\\item $\\expe{V} = \\mu$\n\\item $Y / V \\sim $ Cauchy$(\\mu,\\sigma)$\n\\item $\\var{Y} = \\sigsq$\n\\item $f^{old}_Y(y) = f_Y(y) = \\frac{\\Gammaf{(k+1) / 2}}{\\sigma\\sqrt{k\\pi} \\Gammaf{k/2}} \\tothepow{1 + (y - \\mu)^2 / (k\\sigsq)}{-(k+1) / 2}$\n\\item $f^{old}_Y(y) = f_Y(y) = \\mu + \\sigma  \\frac{\\Gammaf{(k+1) / 2}}{\\sqrt{k\\pi} \\Gammaf{k/2}} \\tothepow{1 + y^2 / k}{-(k+1) / 2}$\n\\item $U \\sim F_{1,k}$\n\\item $V \\sim F_{\\sigma,k}$ if $\\mu=0$\n\\item $f^{old}_U(u) = \\frac{(1 + u / k)^{-(k+1) / 2}}{B(1/2, k/2) \\sqrt{ku} }$\n\\item $f^{old}_V(v) = \\frac{(1 + v / (k\\sigma))^{-(k+1) / 2}}{B(1/2, k/2) \\sqrt{k\\sigma v}}$ if $\\mu=0$\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\problem\\timedsection{9} Let $\\Xoneton \\iid \\normnot{\\mu}{\\sigsq}$ where $\\mu$ and $\\sigsq$ are finite and let $\\Xbar = \\oneover{n} \\sum X_i$ and $S^2 = \\oneover{n - 1} \\sum (X_i - \\Xbar)^2$. Let $Z_1 = (X_1 - \\mu)/\\sigma, Z_2 = (X_2 - \\mu)/\\sigma,\\ldots, Z_n = (X_n - \\mu)/\\sigma$. Let $\\Z = \\bracks{Z_1~Z_2 ~\\ldots~ Z_n}^\\top$.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{11} \n\n\\begin{enumerate}[(a)]\n\\item $\\Xbar \\sim \\normnot{\\mu}{\\sigsq / n}$\n\\item $\\Xbar \\sim \\normnot{\\mu}{\\sigsq}$\n\\item $S^2 \\sim \\chisq{n-1}$\n\\item $S^2 \\sim \\gammanot{\\frac{n-1}{2}}{\\frac{n-1}{2\\sigsq}}$\n\\item $\\Xbar$ and $S^2$ are independent\n\\item $\\bar{Z}$ and $S^2$ are independent\n\\item There exists a matrix $A$ where $S^2 = \\Z A \\Z^\\top$.\n\\item There exists a matrix $A$ where $S^2 = \\Z^\\top A \\Z$.\n\\item If $\\Z^\\top \\Z = \\Z^\\top B_1 \\Z + \\Z^\\top B_2 \\Z + \\ldots + \\Z^\\top B_k\\Z$, then $ \\Z^\\top B_1 \\Z$ is chi-squared distributed\n\\item If (e) is assumed, then Cochran's theorem can be proven\n\\item If $a>0$, then $\\prob{Z_1 > a} < \\half$.\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\problem\\timedsection{19} Let $\\X \\sim \\multnormnot{n}{\\muvec}{\\Sigma}$ where $\\Sigma$ is full rank, $A \\in \\reals^{m \\times n}$,  $\\bv{b} \\in \\reals^m$ and $\\Y = A\\X + \\bv{b}$. Let $\\mu_i$ denote the $i$th entry in $\\muvec$ and let $\\Sigma_{i,j}$ denote the entry on the $i$th row and $j$th column of matrix $\\Sigma$.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{17} \n\n\\begin{enumerate}[(a)]\n\\item $\\expe{\\X} = \\muvec$\n\\item $\\X - \\muvec$ is a standard multivariate normal rv\n\\item The kernel of the PDF of $\\X$ is $e^{\\x^\\top \\Sigma^{-1} \\muvec - \\x^\\top \\Sigma^{-1} \\x / 2}$\n\\item $\\displaystyle\\argmax_{\\x \\in \\reals^n}\\braces{f_{\\X}(\\x)} = \\muvec$\n\\item $\\phi_{\\X}(\\bv{t}) = e^{i\\bv{t}^\\top \\muvec - \\bv{t}^\\top \\Sigma \\bv{t} / 2}$\n\\item $\\phi_{\\Y}(\\bv{t}) = e^{i\\bv{t} \\bv{b}} \\phi_{\\X}(A^\\top\\bv{t})$\n\\item $\\int_0^\\infty \\int_0^\\infty f_{\\X}(x_1,x_2) dx_1 dx_2 = 1$ if $n=2$\n\\item $X_1$ and $X_2$ would be independent if $\\muvec = \\zerovec$\n\\item $X_1$ and $X_2$ could be independent regardless of the value of $\\muvec$\n\\item $\\var{\\X + \\bv{b}} = \\Sigma\\bv{b}$ if $n=m$\n\\item $A\\X \\sim \\multnormnot{n}{\\muvec}{A\\Sigma}$\n\\item $X_3 + X_7$ is normally distributed\n\\item $X_3 / X_7$ is Cauchy distributed\n\\item $\\twovec{X_3}{X_7} \\sim \\multnormnot{2}{\\twovec{\\mu_3}{\\mu_7}}{\\twobytwomat{\\Sigma_{3,3}}{\\Sigma_{3,7}}{\\Sigma_{3,7}}{\\Sigma_{7,7}}}$\n\\item $\\var{X_1 + X_2} = \\Sigma_{1,1} + \\Sigma_{2,2} + \\Sigma_{1,2} + \\Sigma_{2,1}$\n\\item $\\X^\\top \\X \\sim \\chisq{n}$\n\\item $(\\Y - A\\muvec - \\bv{b})^\\top \\inverse{A \\Sigma A^\\top} (\\Y - A\\muvec - \\bv{b})$ is always chi-squared distributed\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\problem\\timedsection{10} Let $X, Y \\iid \\chisq{k}$ where $\\mu$ and $\\sigsq$ are finite and $a>0$.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{10} \n\n\\begin{enumerate}[(a)]\n\\item $\\prob{X > a} \\leq k / a$\n\\item $\\prob{2^X > a} \\leq \\expe{2^X} / a$\n\\item $\\prob{2^X > a} \\leq 2^k / a$\n\\item $Q[X, 1/e] \\leq ek$\n\\item $\\prob{X > b} \\leq \\var{X} / (b-k)^2$ if $b \\geq 2k$\n\\item $\\expe{\\natlog{X}} \\geq \\natlog{\\expe{X}}$\n\\item $\\expe{\\natlog{X}} \\leq \\natlog{\\expe{X}}$\n\\item If $a$ was large, the Chernoff bound for $\\prob{X > a}$ would be tighter (smaller) than the Markov bound for $\\prob{X > a}$\n\\item $\\corr{X}{Y} \\in \\bracks{-1,1}$\n\\item Computing the Cauchy-Schwartz upper bound is the most information you can provide about $\\expe{XY}$.\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\end{document}%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n", "meta": {"hexsha": "c667e6e8756fdb0ba2fcc675b511a5dae9c3a7f1", "size": 12611, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "exams/final/final.tex", "max_stars_repo_name": "kapelner/QC_Math_621_Fall_2020", "max_stars_repo_head_hexsha": "f71dc4901d46c4aaaea3ef4795a22046e754bb11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-08-25T01:46:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T01:21:21.000Z", "max_issues_repo_path": "exams/final/final.tex", "max_issues_repo_name": "kapelner/QC_Math_621_Fall_2020", "max_issues_repo_head_hexsha": "f71dc4901d46c4aaaea3ef4795a22046e754bb11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exams/final/final.tex", "max_forks_repo_name": "kapelner/QC_Math_621_Fall_2020", "max_forks_repo_head_hexsha": "f71dc4901d46c4aaaea3ef4795a22046e754bb11", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-09-02T18:47:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-17T19:42:31.000Z", "avg_line_length": 48.3180076628, "max_line_length": 877, "alphanum_fraction": 0.614225676, "num_tokens": 4548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.3482894169515366}}
{"text": "%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Template for a conference paper, prepared for the\n%% Food and Resource Economics Department - IFAS\n%% UNIVERSITY OF FLORIDA\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Version 1.0 // November 2019\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Ariel Soto-Caro\n%%  - asotocaro@ufl.edu\n%%  - arielsotocaro@gmail.com\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\documentclass[10pt]{article}\n\\usepackage{format}\n\n\\usepackage{amsthm}\n\\theoremstyle{plain}\n\\newtheorem{theorem}{Theorem}[section]\n\\newtheorem{corollary}{Corollary}[theorem]\n\\newtheorem{lemma}[theorem]{Lemma}\n\n\\usepackage[ruled,vlined]{algorithm2e}\n\\newcommand{\\bigslant}[2]{{\\raisebox{.2em}{$#1$}\\left/\\raisebox{-.2em}{$#2$}\\right.}}\n\n\\usepackage{enumitem}\n\\setlist[itemize,1]{label=\\textbullet}\n\\setlist[itemize,2]{label=$\\circ$}\n\\setlist[itemize,3]{label=$\\ast$}\n\n%% ===============================================\n%% Setting the line spacing (3 options: only pick one)\n% \\doublespacing\n% \\singlespacing\n\\onehalfspacing\n%% ===============================================\n\n\\setlength{\\droptitle}{-5em} %% Don't touch\n\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SET THE TITLE\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% TITLE:\n\\title{Random Trees and Effective Resistance}\n\n% AUTHORS:\n\\author{Kishlaya Jaiswal\\\\% Name author\n    % \\href{mailto:kishlaya.j@gmail.com}{\\texttt{kishlaya.j@gmail.com}} %% Email author 1 \n% \\and Second Author\\\\% Name author\n%     \\href{mailto:secondauthor@ufl.edu}{\\texttt{secondauthor@ufl.edu}} %% Email author 2\n% \\and Third Author\\\\% Name author\n%     \\href{mailto:thirdauthor@ufl.edu}{\\texttt{thirdauthor@ufl.edu}}%% Email author 3\n%\\and Forth Author\\\\% Name author\n%    \\href{mailto:forthuthor@ufl.edu}{\\texttt{forthuthor@ufl.edu}}%% Email author 4\n    }\n    \n% DATE:\n\\date{\\today}\n\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{document}\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% ABSTRACT\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n{\\setstretch{.8}\n\\maketitle\n% %%%%%%%%%%%%%%%%%%\n\\begin{abstract}\n% CONTENT OF ABS HERE--------------------------------------\n\nWe look at a graph as an electric network to present a simple proof for the well known relation between effective resistance of an edge and the chances of that edge being in a uniformly random spanning tree.\n\n% END CONTENT ABS------------------------------------------\n\\noindent\n\\textit{\\textbf{Advisor: }%\nSamir Datta} \\\\ %% <-- Keywords HERE!\n\n\\end{abstract}\n}\n\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% BODY OF THE DOCUMENT\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n% % --------------------\n\\section{Introduction}\n% % --------------------\n\nLet $G=(V,E)$ be a given undirected graph. Sampling a uniformly random spanning tree $T$ is a well-studied problem and the question we ask is: given an edge $e \\in E$, what are the chances that a random spanning tree has this edge $e$.\n\nWe consider an electric circuit where each edge in $G$ is replaced with a resistor of $1 \\Omega$. To setup a potential difference, we supply external current $i_{ext}$ at nodes; then potential $p$ at each node is given by: $i_{ext} = Lp$ where $L$ denotes the Laplacian of the graph.\n\n\\textsl{Effective resistance} of an edge $e=(a,b)$, denoted by $R_{\\text{eff}}(e)$, is defined as potential difference across $e$ when a unit current is inducted at $a$ and taken out at $b$.\n\nSo we consider the particular vector $i_{ext} = x_e$ where $x_e(a) = 1$, $x_e(b) = -1$ and $x_e(c) = 0$ for all $c \\neq a,b$. Since $x_e \\perp \\textbf{1}$, we know that a solution for $p$ exists and can be given by $p = L^{\\dag}x_e$ where $L^{\\dag}$ denotes the psuedo-inverse of $L$. Therefore, potential difference between $a$ and $b$ is $p(a) - p(b) = x_e^T p = x_e^T L^{\\dag} x_e$ and so $R_{\\text{eff}}(e) = p(a)-p(b) = x_e^T L^{\\dag} x_e$\n\nIt turns out that:\n$$\\mathbb{P}[e \\in T] = R_{\\text{eff}}(e)$$\n\nGiven these values $\\mathbb{P}(e \\in T)$, we can use them to sample a random spanning tree as follows~\\cite{GUENOCHE1983214}:\n\n% \\begin{algorithm}[H]\n% \\SetAlgoLined\n% $T = \\{\\}$, $G_0 = G$ \\\\\n% Let $e_1, \\ldots, e_m$ be some ordering on the edges \\\\\n% \\For{$i\\gets1$ \\KwTo $m$}{\n%     Let $p$ be the probability that $e_i$ is in a random spanning tree of $G_{i-1}$ \\\\\n%     Flip a biased coin whose chance of heads is $p$ \\\\\n%     \\eIf{heads}{\n%         $T = T \\cup \\{e_i\\}$ \\\\\n%         % $G_i = G_{i-1} / \\{e_i\\}$\n%         $G_i = \\bigslant{G_{i-1}}{\\{e_i\\}}$\n%     }{\n%         $G_i = G_{i-1} \\setminus \\{e_i\\}$\n%     }\n% }\n% Return $T$\n% \\caption{Sampling a uniformly random spanning tree}\n% \\end{algorithm}\n\n\\begin{algorithm}[H]\n\\SetAlgoLined\n$T = \\{\\}$ \\\\\n\\For{$e \\in E$}{\n    Let $p$ be the probability that $e$ is in a random spanning tree of $G$ \\\\\n    Flip a biased coin whose chance of heads is $p$ \\\\\n    \\eIf{heads}{\n        $T = T \\cup \\{e\\}$ \\\\\n        % $G_i = G_{i-1} / \\{e_i\\}$\n        $G = \\bigslant{G}{\\{e\\}}$ (contract $e$)\n    }{\n        $G = G \\setminus \\{e\\}$ (delete $e$)\n    }\n}\nReturn $T$\n\\caption{Sampling a uniformly random spanning tree}\n\\end{algorithm}\n\n\\medskip\n\nBut directly calculating these probabilities require enumerating all spanning trees (hard), whereas computing $R_{\\text{eff}}(e)$ only involves multiplying vectors (easy).\n\nThe proof we discuss here is from ~\\cite{appralgo}. In what follows, we shall assume that the graph is connected (if the graph is not connected then no spanning tree exists).\n\n% % --------------------\n\\section{Matrix Tree Theorem}\n% % --------------------\n\nMatrix Tree Theorem~\\cite{godsil2001algebraic} counts the number of spanning trees of $G$ in terms of the Laplacian of the graph. That is, let $0 < \\lambda_1 \\leq \\cdots \\lambda_n$ be the eigen values of $L$, then \n$$\\# \\text{spanning trees of } G = \\frac1n \\lambda_1 \\ldots \\lambda_n$$\n\nWe define $$\\bar{L} = L + \\frac1n J$$\n$\\bar{L} \\textbf{1} = \\textbf{1}$ and for any other eigenvector $v$ (of $L$) of non-zero eigenvalue, since $v \\perp \\textbf{1}$, $v$ is also an eigenvector of $\\bar{L}$ with same eigenvalue. Hence $\\{1, \\lambda_1, \\ldots, \\lambda_n\\}$ are the eigenvalues of $\\bar{L}$ and so we can re-state the Matrix Tree Theorem as:\n$$\\# \\text{spanning trees of } G = \\frac1n \\det(\\bar{L})$$\n\n% % --------------------\n\\section{Main Result}\n% % --------------------\n\n\\begin{lemma}\nGiven a positive-definite symmetric matrix $M \\in \\mathbb{R}^{n \\times n}$ and $x \\in \\mathbb{R}^n$\n$$\\det(M + x x^T) = \\det(M) (1 + x^T M^{-1} x)$$\n\\end{lemma}\n\n\\begin{proof}\nSince $M$ is positive-definite symmetric, there exists a unique positive-definite symmetric matrix $M^{1/2}$ such that $(M^{1/2})^2 = M$\n\\begin{align*}\n    \\det(M + x x^T) &= \\det \\left(M^{1/2} (I + M^{-1/2} x x^T M^{-1/2}) M^{1/2} \\right) \\\\\n    &= \\det(M) \\det(I + M^{-1/2} x x^T M^{-1/2}) \\\\\n    &= \\det(M) \\det(I + yy^T) \\\\\n\\end{align*}\nwhere $y = M^{-1/2} x$. Notice that solutions of $y^Tv = 0$ gives $n-1$ eigenvectors of $I + yy^T$ with eigenvalue $1$ and from trace computation we get the last eigenvalue is $1 + y^Ty$. Hence $\\det(I + yy^T) = 1 + y^Ty = 1 + x^T M^{-1} x$ and we are done.\n\\end{proof}\n\nSince $G$ is connected, $\\bar{L}$ is a positive definite symmetric matrix and $\\det(\\bar{L}) > 0$. We also note that Laplacian of $G - \\{e\\}$ is simply $L - x_e x_e^T$. Therefore, $\\# \\text{spanning trees of } G$ not containing $e = \\# \\text{spanning trees of } G \\setminus \\{e\\} = \\frac1n \\det(\\bar{L} - x_e x_e^T)$.  Finally we have,\n\n\\begin{align*}\n    \\mathbb{P}[e \\in T] &= 1 - \\mathbb{P}[e \\not \\in T] \\\\\n    &= 1 - \\frac{\\det(\\bar{L} - x_e x_e^T)}{\\det(\\bar{L})} \\\\ \n    &= 1 - \\frac{\\det(\\bar{L}) (1 - x_e^T \\bar{L}^{-1} x_e)}{\\det(\\bar{L})} \\\\\n    &= x_e^T \\bar{L}^{-1} x_e \\\\\n    &= x_e^T L^{\\dag} x_e\n\\end{align*}\nas $L = \\bar{L}$ when restricted to the subspace perpendicular to $\\textbf{1}$. Thus, $\\mathbb{P}[e \\in T] = x_e^T L^{\\dag} x_e = R_{\\text{eff}}(e)$ \\qed\n\n% % --------------------\n\\section{Further Extensions}\n% % --------------------\n\nWe can further extend this result by asking the probability of $F \\subseteq T$ where $F$ is any subset of edges. In this case~\\cite{burton1993} showed that $\\mathbb{P}[F \\subseteq T] = \\det(Y_F)$ where $Y$ is a $E \\times E$ matrix such that $Y(e,f) = x_e^T L^{\\dag}x_f$. This can be easily proved by inducting on size of $F$ and using Cauchy-Binet formula (note that the base case $|F|=1$ is what we have proved above).\n\nWhen $G$ is weighted undirected graph, in which case resistance of each edge is inverse of it's weight then we have $\\mathbb{P}[e \\in T] = w(e)R_{\\text{eff}}(e)$ where $T$ is sampled with probability proportional to $\\prod_{e \\in T} w(e)$. The proof is similar with the modification that we work with the weighted Laplacian and use Matrix Tree theorem for weighted graphs.\n\n\n\\printbibliography\n\n\\end{document}\n", "meta": {"hexsha": "e47f0ce393f73c4535c3d23c1ffdcdcf1cb55b7a", "size": 9250, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "spectral_graph_theory/Random_Trees_and_Effective_Resistance/main.tex", "max_stars_repo_name": "kishlaya/assignments", "max_stars_repo_head_hexsha": "1aa76e32d7e5059499a93359cb52118ccbf07028", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-11-17T09:28:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-14T17:40:34.000Z", "max_issues_repo_path": "spectral_graph_theory/Random_Trees_and_Effective_Resistance/main.tex", "max_issues_repo_name": "kishlaya/assignments", "max_issues_repo_head_hexsha": "1aa76e32d7e5059499a93359cb52118ccbf07028", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spectral_graph_theory/Random_Trees_and_Effective_Resistance/main.tex", "max_forks_repo_name": "kishlaya/assignments", "max_forks_repo_head_hexsha": "1aa76e32d7e5059499a93359cb52118ccbf07028", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.5665024631, "max_line_length": 444, "alphanum_fraction": 0.5607567568, "num_tokens": 2858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381667555713, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.34828905627616163}}
{"text": "\\chapter{Review of terms and existing solutions}\n\n\\startrelatedwork\n\nFor now the automation of different problems like community search in social networks is very relevant and progress from day to day. There are different methods for finding communities in the whole network \\cite{Newman04, Newman06, Fortunato10, Cui13} and also for finding a dense community containing all selected vertices in the network \\cite{Faloutsos06, Wiener15, Huang15, Barbieri15}. There are even algorithms for splitting selected vertices into several communities \\cite{Akoglu13} (DOT2DOT algorithm). However, almost all of these algorithms don't support noise in the query and find non-optimal subgraphs on such queries. Precisely this problem we are going to solve in this work, suggesting the new algorithm that will effectively find the needed subgraph even if there is some noise in the query.\n\n\\section{Terms and definitions}\n\n\\subsection{Graph terms}\n\nIn this chapter we will write down all non-common terms and definitions that may be helpful for the further reading.\n\n\nUnder \\textbf{$N_G(v)$} we will understand the set of the neighbors of vertex $v$ in graph $G$, i.e. the set of the vertices that are directly connected to $v$ by edge: $N_G(v) = \\{u | (v, u) \\in E(G)\\}$. If graph $G$ can be obviously recognized from the context, we can write just $N(v)$.\n\n\\textbf{$G[V]$} is called \\textbf{originated subgraph} of the graph $G$ by the set of vertices $V$ if $G[V] := (V, E[G, V])$, where $E[G, V]$~--- the subset of the set of edges of $G$, both ends of which are contained in $V$, i.e. $E[G, V] = E(G) \\cap (V \\times V)$.\n\n\\textbf{k-truss} of the graph $G$ is the subgraph $G' \\subseteq G$ containing the maximal possible number of vertices, such that for each edge $(v, u)$ the number of vertices $w$, such that edges $(w, v)$ and $(w, u)$ exists in $G'$ is at least $k$. In other words, $k-truss$ is the maximal by size subgraph $G'$, for each of which edge $(v, u)$, the $|N_{G'}(v) \\cap N_{G'}(u)| >= k$ is true.\n\n\\textbf{k-core} of the graph $G$ is called the maximal by the number of vertices subgraph $G' \\subseteq G$, so that the degree of each of its vertices is at least $k$. For the fixed $k$, by $C_k$ we will denote \\textit{$k$-core}, namely the set of the connected components of which it consists. So, $C_k = \\{H_i\\}$, where $H_i$ is the $i$-th connected component, where the degree of each vertex is at least $k$. The number $k$ we will call the \\textbf{order} of \\textit{k-core}.\n\nBy \\boldmath$\\mu(G)$\\unboldmath we will denote the minimal degree of the vertices $G$, i.e. $\\mu(G) = \\min_{v \\in V(G)} deg(v)$.\n\n\\textbf{Core decomposition} is the set of \\textit{k-core} for all possible $k$: $C = \\{C_k\\}_{k=1}^{k=k^*}$. We also need to clarify that from the definition of the \\textit{k-core} you can see that $C_1 \\supseteq C_2 \\supseteq C_3 \\ldots \\supseteq C_{k^*}$ (where $k^*$ is the maximal possible $k$ in core decomposition).\n\n\\textbf{Сore index} for the vertex $v$ is called the minimal by the size \\textit{k-core} which includes $v$, i.e. \\textit{k-core} with the maximal $k$: $c(v) = \\max(k \\in [0..k^*] | v \\in C_k)$.\n\n\\textbf{$\\gamma$-quasi-clique} of the graph $G$ is called any such subgraph $G' \\subseteq G$ that it is <<dense enough>>, i.e. $\\frac{2 \\cdot |E(G')|}{|V(G')| \\cdot (|V(G')| - 1)} \\ge \\gamma$.\n\n\\subsection{Social networks}\n\n\\textbf{The community} or \\textbf{The community in social network} is called the set of vertices of the social network $G$, where all vertices are united by some property or attribute. For example, <<the community of rock lovers>> or <<the community of Apple shareholders>>.\n\n\\textbf{The social clique} or \\textbf{clique} we will call the set of people in social network, where everyone \"knows\" (i.e. is connected by edge) each other, in other words when between any pair of distinct people there is an edge in social network.\n\n\\textbf{Social pseudoclique} or \\textbf{pseudoclique} we will call the set of people, where it is not required that each pair of distinct people is connected by edge, but this set is still densely connected. The estimation, how dense the pseudoclique is connected depends on the type of the pseudoclique and will be discussed later in the work, but in all definitions the biggest role plays the number of edges in subgraph in comparison with the number of pairs of vertices ($\\frac{2 \\cdot |E(G)|}{|V(G)| \\cdot (|V(G)| - 1)}$).\n\n\\textbf{Free-rider effect} is called the effect, appearing during the obtaining the answer for the given problem (finding the dense community in social network), when the final or intermediate answer contains unnecessary subgraphs~--- subgraphs which can be deleted without violation the optimality of the answer. Thereby, we can make the answer smaller which is one of ours main goals.\n\n\\subsection{Useful abbreviations}\n\n\\textbf{RW}~--- Random Walks. The main idea of this method is based on moving from one vertex to the neighbor one with probability proportional to the edge weight.\n\n\\textbf{RWR}~--- Random Walks with Restarts. The idea is similar to the RW, but in this case the probability to move to the initial vertex (from which we've started) from the current one exists as well.\n\n\\textbf{Smart-ST}~--- Smart Spanning Trees. The heuristic for Steiner Tree problem, which is used in Gionis et al. article \\cite{Gionis15}.\n\n\\textbf{CSP}~--- Community Search Problem. This is the problem for finding the community in the social network which contains all the selected vertices.\n\n\\textbf{NCSP}~--- Noising Community Search Problem. This is the problem for finding the community in the social network which contains most of the selected vertices, but not necessary all (not including the noise).\n\n\\section{Overview}\n\nThe problem that we're analyzing in the work is formulated as follows: given a graph $G$ and a set of selected vertices $Q \\subset V(G)$, the goal is to solve community search problem~--- to find the community which contains most of the vertices from $Q$, but not necessary all of them. Sometimes we will call vertices from $Q$ <<query vertices>>, <<query>> or <<vertices from query>>.\n\n\\subsection{Initial solutions}\n\n\\begin{enumerate}\n  \\item The community search problem by the given selected vertices is researched during a long time. Even in 2004 Faloutsos et al. \\cite{Faloutsos04} suggested the algorithms for finding the dense community by $2$ selected vertices in network ($|Q| = 2$). The algorithm shows that metrics like <<the shortest path>> and <<max flow>> between two given vertices are not optimal. Instead of them, the initial graph is considered as the electric network and <<the current delivered between vertices>> metric is used~--- setting voltage \\texttt{+1} on the first vertex-query and \\texttt{0} on the second one, we find subgraph which delivers the maximal current between vertices from query. The provided metrics works only for $|Q| = 2$, but this algorithm was the foundation in research of the community search problem. After that many authors were working on optimization for this article and were quite successful.\n\n  \\item Authors of the second article that was taken for consideration \\textbf{Faloutsos06} suggest the metric function based on \\textit{random walks with restarts} (RWR) used on the weighted graph. They consider $r(i, j)$~--- the probability that starting in vertex $i$-th query vertex $q_i$ we will end in vertex $j$ using RWR, where on each step we move to the neighbor by edge vertex with probability proportional the edge weight. Also we introduce $r(Q, j)$ which is equal to the sum of $r(i, j)$ for each query vertices: $r(Q, j) = \\sum_{i = 1}^{i = |Q|}\\; r(i, j)$. The dense metric is considered as $g(H) = \\sum_{j \\in H}\\; r(Q, j)$. This method has shown quite good results compared to the previous article, because expanded the number of query vertices from $2$ to any number from $2$ to $|V(G)|$. Also, it introduced new ability of finding the subgraph containing not all vertices, but at least $k$ of them ($k$ is a parameter which is given as input). This operation was called $K\\_softAND$ and was successfully implemented in the article. Further algorithms were expanding this idea, were applying other metrics and improved the results of this algorithm, but the problem of finding the community containing not necessary all query vertices, but only a part of them (our problem), almost wasn't optimized.\n\n  \\item Authors of the third article \\cite{Wiener15} suggest to use \\textit{Wiener index} as the metric for subgraph density. This metric is equal to the pairwise sum of the shortest distances between vertices from the query. Authors are trying to solve the issue of obtaining too large graph as the result of processing the query if query vertices are placed in several communities and are weakly connected between each other. To solve this issue, authors suggest to add some <<important vertices>> to the query which will connect communities, even if not very dense. Results has shown that this method works several times better than previous methods \\cite{Faloutsos06, Sozio10} and almost the same as the methods that based on \\textit{Steiner tree problem}. Unfortunately, the article doesn't consider more late methods based on \\textit{Steiner tree problem} which significantly improved the old results, which make this method less priority comparing to them.\n  \n\\end{enumerate}\n\n\\subsection{Finding optimal pseudocliques}\n\nThe most part of all algorithms for solving the described problem are the algorithms based on the finding optimal pseudocliques with some additional heuristics. There are a lot of different pseudocliques the were considered in different articles: for example, \\textit{k-core} \\cite{Barbieri15}, \\textit{k-truss} \\cite{Huang15}, \\textit{$\\gamma$-quasi-clique} \\cite{Zhu11} or just algorithms that maximizes the edge density in the resulting subgraph \\cite{Wu15} which is almost a definition of a pseudoclique. For each of these pseudocliques the algorithms are evolving and becoming better, optimizing the previous results using new heuristics. Comparing the results of the algorithms that use different pseudocliques is quite hard and unlikely will give visible results because of the difference of the metrics that are being optimized~--- the result strongly depend on the initial graph and the queries on it. In some cases one pseudoclique will obtain results better than others, but in other cases it will work worse, so actually it's worth to compare some common performance metrics, but unfortunately it doesn't give us the whole understanding of the optimality or non-optimality of the algorithms.\n\nLet's consider several newest algorithms for the most popular pseudocliques:\n\n\\begin{enumerate}\n  \\item X. Huang et al. \\cite{Huang15} choose \\textit{k-truss} pseudoclique. However, just finding the optimal \\textit{k-truss} (i.e. \\textit{k-truss} with the maximal $k$ containing all query vertices in it) is not an optimal solution, and also it is an already solved problem (even with polynomial solution). That's why the authors of the article suggest to find \\textit{k-truss} with maximal $k$ and minimal subgraph diameter, which, as they show in their article, is a NP-hard problem. However, this idea pretends to show good results, so authors made a research trying to understand how close the answer found by polynomial time may be to the theoretically optimal answer. It turned out that this problem couldn't be solved with accuracy better than in $(2 - \\varepsilon)$ times worse for each $\\varepsilon > 0$ (under the accuracy we understand the length of the diameter in the final answer). However, authors suggested the heuristic algorithm which in the worst case makes exactly $2$ times error, which shows that their algorithm is optimal for the provided problem. The algorithm is based on building the supposed maximal $\\textit{k-truss}$ with the followed iterative deleting vertices which doesn't make the answer worse and make the diameter smaller. The results obtained in this article are really good comparing to the previous articles \\cite{Sozio10, Wu15}, however, even despite of proved optimality for the provided algorithm, it is not optimal for the initial problem (finding the dense subgraph by the given query vertices), because authors found the optimal solution only for the problem provided \\textit{by themselves}.\n\n  \n  \\item N. Barbieri et al. \\cite{Barbieri15} is using \\textit{k-core} pseudoclique. However, even here simple finding the optimal \\textit{k-core} (i.e. \\textit{k-core} with maximal $k$ which contains all query vertices in it) is not an optimal solution, and also this problem is already solved by polynomial time \\cite{Sozio10}. That's why the authors of the article apply some heuristics targeted for minimizing the size of the resulting subgraph without loosing its optimality. These heuristics allow to reduce the problem to finding the answer in component $H^* \\subset G$, and besides it is guaranteed that all possible optimal answers for the initial problem are lying in $H^*$. After that authors bring some heuristics for minimizing the obtained subgraph $H^*$. The main statement described by the authors is not new, but it looks quite interesting for the further researches because it adds more information to the initial problem without loosing any solutions. The results of this article shows that provided method really works better and faster than previous ones \\cite{Sozio10, Cui14}. Based on all the above information, it was decided to take this article as the baseline and try to improve it, especially to expand it to our problem (finding the community containing not necessary all selected vertices).\n\\end{enumerate}\n\n\\subsection{Other methods}\n\nAs we already saw earlier, optimizing functions may be quite different. In the previous part we were considering pseudocliques, and here we're going to consider several other popular optimizing functions.\n\n\\begin{enumerate}\n  \\item L. Akoglu et al. \\cite{Akoglu13} slightly change the initial problem~--- they try to find subgraph that unites not all the vertices in the query, but their groups. Actually the idea is based on splitting the query into groups and building the answer for each of the groups separately, so that in each groups the vertices are densely connects and are united by some common property. But between each other the groups may be connected not very densely. This corresponds to the splitting the query into several communities. The results of the article has shown that this method solves the problem provided by authors quite good, but however as we said before, this problem differs from ours and it's hard to compare it's results with ours. However, we still are going to compare this solution with ours, because this solution supports finding community not for all selected vertices. \n\n  \\item A. Gionis et al. \\cite{Gionis15} in their article consider \\textit{linear local discrepancy} metric which is equal to the weighted difference of the number of query vertices in the resulting subgraph and the number of remaining vertices. More formally, $g(C) = \\alpha p_C - n_C$, where $p_C = |Q \\cap V(C)|$ and $n_C = |V(C) \\setminus Q|$. The algorithm that maximized this function based on the \\textit{Steiner tree problem} and \\textit{Smart-ST}s. The distinguishing feature of this algorithm is the ability of solving the problem using \\textit{local access model}, i.e. the model where we don't know the whole graph (or it is too big to save it in RAM), and API allows us only to make queries for accessing all vertex neighbors~--- $get-neighbors$ method. This model allows to solve the problem optimally even on very big social networks, such as \\textit{Twitter} or \\textit{Facebook}. Based on the definition, the resulting subgraph may not contain all vertices from query, which coincides with our research. Unfortunately, the provided metric doesn't fit our problem very good~--- it doesn't take into consideration edge density of the resulting subgraph, it looks only the ratio of the vertices. Also it's possible that the answer will contain too few vertices from the initial query~--- it also doesn't work for us.\n\\end{enumerate}\n\n\\section{Final requirements for our work}\n\nLet's sum up everything described above. Most of the current solutions solves CSP quite optimal~--- each of the solutions uses it's own metric and obtains quite good results. However, as we can see, solutions for NCSP (which includes noise into consideration) are quite rare, despite it is more useful problem in real life. We've noted consideration of NCSP problem in articles C. Faloutsos \\& H. Tong \\textbf{[3]} and A. Gionis et al. \\cite{Gionis15}, however the last problem is not based on solving NCSP (but solves it at the same time). So, the goal of our article will be to build the algorithm that focuses on NCSP solving and obtains better results than the current ones. Here are some requirements for our algorithm:\n\n\\begin{itemize}\n    \\item The algorithm should obtain better results than the current ones \\cite{Faloutsos06, Gionis15, Barbieri15};\n    \\item The algorithm should be quite optimal, ideally not loosing the competition with other algorithms in terms of working time;\n    \\item It would be an advantage to support backwards compatibility~--- if the user wants to find subgraph that contains \\textit{all} query vertices, it should be possible to be done.\n\\end{itemize}\n", "meta": {"hexsha": "57e66feb81723481eaae1124e83dd5cb00755d74", "size": 17452, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "pdf/articles/article-1/chapters-eng/chapter1.tex", "max_stars_repo_name": "DimaPhil/master-thesis", "max_stars_repo_head_hexsha": "a7a398fc91ee2d274f37dfeaa8e6264904f84e6d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pdf/articles/article-1/chapters-eng/chapter1.tex", "max_issues_repo_name": "DimaPhil/master-thesis", "max_issues_repo_head_hexsha": "a7a398fc91ee2d274f37dfeaa8e6264904f84e6d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pdf/articles/article-1/chapters-eng/chapter1.tex", "max_forks_repo_name": "DimaPhil/master-thesis", "max_forks_repo_head_hexsha": "a7a398fc91ee2d274f37dfeaa8e6264904f84e6d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 176.2828282828, "max_line_length": 1641, "alphanum_fraction": 0.7707999083, "num_tokens": 4164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.3482890393314951}}
{"text": "\\chapter{The object classifier}\\label{chap:univalent}\n\nIn this chapter we establish notation, and we highlight the basic results concerning fiberwise transformations and fiberwise equivalences, which we will use for the descent theorems \\cref{thm:descent,thm:rcoeq_cartesian}. Of particular importance are the following theorems:\n\\begin{enumerate}\n\\item The Fundamental Theorem of Identity Types (\\cref{thm:id_fundamental}), which establishes that a type family $B$ over $A$ with $b:B(a)$ for a given $a:A$ is fiberwise equivalent to the identity type $a=x$ if and only if its total space is contractible. This result appears in \\cite{hottbook} as Theorem 5.8.2, which contains other equivalent conditions as well.\n\\item \\cref{thm:pb_fibequiv}, in which we establish that for any fiberwise map\n\\begin{equation*}\ng:\\prd{x:A}P(x)\\to Q(f(x)),\n\\end{equation*}\nthe commuting square\n\\begin{equation*}\n\\begin{tikzcd}[column sep=large]\n\\sm{x:A}P(x) \\arrow[r,\"{\\total[f]{g}}\"] \\arrow[d,swap,\"\\proj 1\"] & \\sm{y:B}Q(y) \\arrow[d,\"\\proj 1\"] \\\\\nA \\arrow[r,swap,\"f\"] & B,\n\\end{tikzcd}\n\\end{equation*}\nwhere $\\total[f]{g}$ is defined as $\\lam{(x,p)}(f(x),g(x,y))$, is a pullback square if and only if $g$ is a fiberwise equivalence\\index{fiberwise equivalence}. As a consequence, we obtain that a commuting square\n\\begin{equation*}\n\\begin{tikzcd}\nA \\arrow[d,swap,\"f\"] \\arrow[r] & B \\arrow[d,\"g\"] \\\\\nX \\arrow[r,swap,\"h\"] & Y\n\\end{tikzcd}\n\\end{equation*}\nis a pullback square if and only if the induced fiberwise transformation\n\\begin{equation*}\n\\prd{x:X} \\fib{f}{x}\\to\\fib{g}{h(x)}\n\\end{equation*}\nis a fiberwise equivalence. Our main reference \\cite{hottbook} does not present many results of homotopy pullbacks, although the material we present about homotopy pullbacks is surely well-known. The connection between pullbacks and fiberwise equivalences has an important role in the descent theorem\\index{descent} in \\cref{chap:descent}, which is why we devote a section to this result.\n\\item \\cref{thm:classifier}, in which we establish that the universe is an object classifier. This result appears in \\cite{RijkeSpitters} as Theorem 2.31, and in \\cite{hottbook} as Theorem 4.8.4\n\\end{enumerate}\n\n\\section{Notation and preliminary results}\n\nWe work in Martin-L\\\"of dependent type theory with $\\Pi$-types, $\\Sigma$-types and cartesian products, coproducts $A+B$ equipped with $\\inl:A\\to A+B$ and $\\inr:B\\to A+B$ for any two types $A$ and $B$, an empty type $\\emptyt$, a unit type $\\unit$ equipped with $\\ttt:\\unit$, a type $\\bool$ of booleans equipped with $\\btrue,\\bfalse:\\bool$, a type $\\N$ of natural numbers equipped with $0:\\N$ and $\\suc:\\N\\to\\N$, and identity types. \n\n\\begin{rmk}\nAs usual, we write $\\idfunc[A]:A\\to A$ for the \\define{identity function} $\\lam{x}x$ on $A$, and we write $g\\circ f:A\\to C$ for the \\define{composite function} $\\lam{x}g(f(x))$ of $f:A\\to B$ and $g:B\\to C$. For any two types $A$ and $B$, and any $b:B$, we write\n\\begin{equation*}\n\\const_b : A\\to B\n\\end{equation*}\nfor the \\define{constant function} $\\lam{x}b$. Sometimes we also write $\\lam{\\nameless}b$ for the constant function.\n\nIn the case of $\\Sigma$-types, the empty type $\\emptyt$, and the unit type, we use the following notation to define functions by pattern-matching:\n\\begin{align*}\n\\lam{(x,y)}f(x,y) & : \\prd{t:\\sm{x:A}B(x)} P(t) \\\\\n\\lam{\\ttt}y & : \\prd{t:\\unit}P(t).\n\\end{align*}\nFor instance, the first and second projection maps \n\\begin{align*}\n\\proj 1 & : (\\sm{x:A}B(x))\\to A \\\\\n\\proj 2 & : \\prd{p:\\sm{x:A}B(x)}B(\\proj 1)\n\\end{align*}\nare defined as $\\proj 1\\defeq \\lam{(x,y)}x$ and $\\proj 2\\defeq\\lam{(x,y)}y$.\nWe use similar notation for definitions by iterated pattern-matching. For instance, given a dependent function $f:\\prd{x:A}{y:B(x)}{z:C(x,y)} P((x,y),z)$ we obtain the function\n\\begin{equation*}\n\\lam{((x,y),z)} f(x,y,z): \\prd{t:\\sm{s:\\sm{x:A}B(x)}C(s)}P(t).\n\\end{equation*}\n\\end{rmk}\n\nGiven a type $A$ in context $\\Gamma$, the \\define{identity type} of $A$ at $a:A$ is the inductive type family \n\\begin{equation*}\n\\Gamma,x:A\\vdash a =_A x~\\mathrm{type}\n\\end{equation*}\nwith constructor\n\\begin{equation*}\n\\Gamma \\vdash \\refl{a} : a=_A a.\n\\end{equation*}\nThe induction principle for the identity type of $A$ at $a$ asserts that for any type family\n\\begin{equation*}\n\\Gamma,x:A,\\alpha: a=_A x\\vdash P(x,\\alpha)~\\mathrm{type}\n\\end{equation*}\nthere is a term\n\\begin{equation*}\n\\ind{a=} : P(a,\\refl{a})\\to \\prd{x:A}{\\alpha:a=_A x}P(x,\\alpha)\n\\end{equation*}\nin context $\\Gamma$, satisfying the computation rule\n\\begin{equation*}\n\\ind{a=}(p,a,\\refl{a})\\jdeq p.\n\\end{equation*}\n\nA term of type $a=_A x$ is also called an \\define{identification} of $a$ with $x$, or a \\define{path} from $a$ to $x$.\nThe induction principle for identity types is sometimes called \\define{identification elimination} or \\define{path induction}. Occasionally, we also write $\\idtypevar{A}$ for the identity type on $A$. \n\nMoreover, we assume that there is a universe $\\UU$ with a universal family $\\mathrm{El}$ over $\\UU$, that is closed under the type forming operations. For example, there is a map\n\\begin{equation*}\n\\check{\\idtypevar{}}:\\prd{A:\\UU}\\mathrm{El}(A)\\to\\mathrm{El}(A)\\to\\UU\n\\end{equation*}\nsatisfying\n\\begin{equation*}\n\\mathrm{El}(\\check{\\idtypevar{}}(A,x,y))\\jdeq (x=_{\\mathrm{El}(A)} y),\n\\end{equation*}\nestablishing that the universe is closed under identity types.\n\nGiven a type $A$ the \\define{concatenation} operation\n\\begin{equation*}\n\\concat : \\prd{x,y,z:A} (\\id{x}{y})\\to(\\id{y}{z})\\to (\\id{x}{z})\n\\end{equation*}\nis defined by $\\concat(\\refl{x},q)\\defeq q$. We will usually write $\\ct{p}{q}$ for $\\concat(p,q)$. \nThe concatenation operation satisfies the unit laws\n\\begin{align*}\n\\leftunit(p) & : \\ct{\\refl{x}}{p}=p \\\\\n\\rightunit(p) & : \\ct{p}{\\refl{y}}=p.\n\\end{align*}\n\nThe \\define{inverse operation} \n\\begin{equation*}\n\\invfunc:\\prd{x,y:A} (x=y)\\to (y=x)\n\\end{equation*}\nis defined by $\\invfunc(\\refl{x})\\defeq\\refl{x}$. We will usually write $p^{-1}$ for $\\invfunc(p)$.\nThe inverse operation satisfies the inverse laws\n\\begin{align*}\n\\leftinv(p) & : \\ct{p^{-1}}{p} = \\refl{y} \\\\\n\\rightinv(p) & : \\ct{p}{p^{-1}} = \\refl{x}.\n\\end{align*}\n\nThe \\define{associativity operation}, which assigns to each $p:x=y$, $q:y=z$, and $r:z=w$ the \\define{associator}\n\\begin{equation*}\n\\assoc(p,q,r) : \\ct{(\\ct{p}{q})}{r}=\\ct{p}{(\\ct{q}{r})}\n\\end{equation*}\nis defined by $\\assoc(\\refl{x},q,r)\\defeq \\refl{\\ct{q}{r}}$.\n\nGiven a map $f:A\\to B$, the \\define{action on paths} of $f$ is an operation\n\\begin{equation*}\n\\apfunc{f} : \\prd{x,y:A} (\\id{x}{y})\\to(\\id{f(x)}{f(y)})\n\\end{equation*}\ndefined by $\\ap{f}{\\refl{x}}\\defeq\\refl{f(x)}$. \nMoreover, there are operations\n\\begin{align*}\n\\apid_A & : \\prd{x,y:A}{p:\\id{x}{y}} \\id{p}{\\ap{\\idfunc[A]}{p}} \\\\\n\\apcomp(f,g) & : \\prd{x,y:A}{p:\\id{x}{y}} \\id{\\ap{g}{\\ap{f}{p}}}{\\ap{g\\circ f}{p}}\n\\end{align*}\ndefined by $\\apid_A(\\refl{x})\\defeq \\refl{\\refl{x}}$ and $\\apcomp(f,g,\\refl{x})\\jdeq \\refl{\\refl{g(f(x))}}$, respectively.\nIt can be shown easily that the action on paths of a map preserves the groupoid operations, and that the groupoid laws are also preserved.\n\n\\begin{defn}\nLet $A$ be a type, and let $B$ be a type family over $A$. The \\define{transport} operation\n\\begin{equation*}\n\\tr_B:\\prd{x,y:A} (\\id{x}{y})\\to (B(x)\\to B(y))\n\\end{equation*}\nis defined by $\\tr_B(\\refl{x}) \\defeq \\idfunc[B(x)]$. \n\\end{defn}\n\n\\begin{defn}\\label{defn:apd}\nGiven a dependent function $f:\\prd{a:A}B(a)$ and a path $p:\\id{x}{y}$ in $A$, the \\define{dependent action on paths}\n\\begin{equation*}\n\\apdfunc{f} : \\prd{x,y:A}{p:x=y}\\id{\\tr_B(p,f(x))}{f(y)}\n\\end{equation*}\nis defined by $\\apd{f}{\\refl{x}}\\defeq \\refl{f(x)}$.\n\\end{defn}\n\n\\begin{defn}\nLet $f,g:\\prd{x:A}P(x)$ be two dependent functions. The type $f\\htpy g$ of \\define{homotopies}\\index{homotopy|textbf} from $f$ to $g$ is defined as\n\\begin{equation*}\nf\\htpy g \\defeq \\prd{x:A} f(x)=g(x).\n\\end{equation*}\n\\end{defn}\n\nCommutativity of diagrams is stated using homotopies. For instance, a triangle\n\\begin{equation*}\n\\begin{tikzcd}[column sep=tiny]\nA \\arrow[dr,swap,\"f\"] \\arrow[rr,\"h\"] & & B \\arrow[dl,\"g\"] \\\\\n& X\n\\end{tikzcd}\n\\end{equation*}\nis said to commute if it comes equipped with a homotopy $H:f\\htpy g\\circ h$, and a square\n\\begin{equation*}\n\\begin{tikzcd}\nA \\arrow[d,\"i\"'] \\arrow[r,\"g\"] & X \\arrow[d,\"f\"] \\\\\nB \\arrow[r,swap,\"h\"] & Y\n\\end{tikzcd}\n\\end{equation*}\nis said to commute if it comes equipped with a homotopy $H:h\\circ i\\htpy f\\circ g$. \n\nThe reflexivity, inverse, and concatenation operations on homotopies are defined pointwise.\nWe will write $H^{-1}$ for $\\lam{x}H(x)^{-1}$, and $\\ct{H}{K}$ for $\\lam{x}\\ct{H(x)}{K(x)}$.\nThese operations satisfy the groupoid laws (phrased appropriately as homotopies). Apart from the groupoid operations and their laws, we will occasionally need \\emph{whiskering} operations and the naturality of homotopies.\n\n\\begin{defn}\\label{defn:htpy_whisering}\nWe define the following \\define{whiskering}\\index{homotopy!whiskering operations|textbf}\\index{whiskering operations!of homotopies|textbf} operations on homotopies:\n\\begin{enumerate}\n\\item Suppose $H:f\\htpy g$ for two functions $f,g:A\\to B$, and let $h:B\\to C$. We define\n\\begin{equation*}\nh\\cdot H\\defeq \\lam{x}\\ap{h}{H(x)}:h\\circ f\\htpy h\\circ g.\n\\end{equation*}\n\\item Suppose $f:A\\to B$ and $H:g\\htpy h$ for two functions $g,h:B\\to C$. We define\n\\begin{equation*}\nH\\cdot f\\defeq\\lam{x}H(f(x)):h\\circ f\\htpy g\\circ f.\n\\end{equation*}\n\\end{enumerate}\n\\end{defn}\n\nWe will frequently make use of commuting cubes. The commutativity of a cube is stated using the whiskering operations on homotopies.\n\n\\begin{defn}\\label{defn:cube}\nA \\define{commuting cube}\\index{commuting cube|textbf}\n\\begin{equation*}\n\\begin{tikzcd}\n& A_{111} \\arrow[dl] \\arrow[dr] \\arrow[d] \\\\\nA_{110} \\arrow[d] & A_{101} \\arrow[dl] \\arrow[dr] & A_{011} \\arrow[dl,crossing over] \\arrow[d] \\\\\nA_{100} \\arrow[dr] & A_{010} \\arrow[d] \\arrow[from=ul,crossing over] & A_{001} \\arrow[dl] \\\\\n& A_{000},\n\\end{tikzcd}\n\\end{equation*}\nconsists of \n\\begin{enumerate}\n\\item types\n\\begin{equation*}\nA_{111},A_{110},A_{101},A_{011},A_{100},A_{010},A_{001},A_{000},\n\\end{equation*}\n\\item \\begin{samepage}%\nmaps\n\\begin{align*}\nf_{11\\check{1}} & : A_{111}\\to A_{110} & f_{\\check{1}01} & : A_{101}\\to A_{001} \\\\\nf_{1\\check{1}1} & : A_{111}\\to A_{101} & f_{01\\check{1}} & : A_{011}\\to A_{010} \\\\\nf_{\\check{1}11} & : A_{111}\\to A_{011} & f_{0\\check{1}1} & : A_{011}\\to A_{001} \\\\\nf_{1\\check{1}0} & : A_{110}\\to A_{100} & f_{\\check{1}00} & : A_{100}\\to A_{000} \\\\\nf_{\\check{1}10} & : A_{110}\\to A_{010} & f_{0\\check{1}0} & : A_{010}\\to A_{000} \\\\\nf_{10\\check{1}} & : A_{101}\\to A_{100} & f_{00\\check{1}} & : A_{001}\\to A_{000},\n\\end{align*}\n\\end{samepage}%\n\\item homotopies\n\\begin{align*}\nH_{1\\check{1}\\check{1}} & : f_{1\\check{1}0}\\circ f_{11\\check{1}} \\htpy f_{10\\check{1}}\\circ f_{1\\check{1}1} & H_{0\\check{1}\\check{1}} & : f_{0\\check{1}0}\\circ f_{01\\check{1}} \\htpy f_{00\\check{1}}\\circ f_{0\\check{1}1} \\\\\nH_{\\check{1}1\\check{1}} & : f_{\\check{1}10}\\circ f_{11\\check{1}} \\htpy f_{01\\check{1}}\\circ f_{\\check{1}11} & H_{\\check{1}0\\check{1}} & : f_{\\check{1}00}\\circ f_{10\\check{1}} \\htpy f_{00\\check{1}}\\circ f_{\\check{1}01} \\\\\nH_{\\check{1}\\check{1}1} & : f_{\\check{1}01}\\circ f_{1\\check{1}1} \\htpy f_{0\\check{1}1}\\circ f_{\\check{1}11} & H_{\\check{1}\\check{1}0} & : f_{\\check{1}00}\\circ f_{1\\check{1}0} \\htpy f_{0\\check{1}0}\\circ f_{\\check{1}10},\n\\end{align*}\n\\item and a homotopy \n\\begin{align*}\nC & : \\ct{(f_{\\check{1}00}\\cdot H_{1\\check{1}\\check{1}})}{(\\ct{(H_{\\check{1}0\\check{1}}\\cdot f_{1\\check{1}1})}{(f_{00\\check{1}}\\cdot H_{\\check{1}\\check{1}1})})} \\\\\n& \\qquad \\htpy \\ct{(H_{\\check{1}\\check{1}0}\\cdot f_{11\\check{1}})}{(\\ct{(f_{0\\check{1}0}\\cdot H_{\\check{1}1\\check{1}})}{(H_{0\\check{1}\\check{1}}\\cdot f_{\\check{1}11})})}\n\\end{align*}\nfilling the cube.\n\\end{enumerate}\n\\end{defn}\n\n\\begin{defn}\nLet $f:A\\to B$ be a function. We say that $f$ has a \\define{section}\\index{section!of a map|textbf} if there is a term of type\\index{sec(f)@{$\\sections(f)$}|textbf}\n\\begin{equation*}\n\\sections(f) \\defeq \\sm{g:B\\to A} f\\circ g\\htpy \\idfunc[B].\n\\end{equation*}\nDually, we say that $f$ has a \\define{retraction}\\index{retraction} if there is a term of type\\index{retr(f)@{$\\retractions(f)$}|textbf}\n\\begin{equation*}\n\\retractions(f) \\defeq \\sm{h:B\\to A} h\\circ f\\htpy \\idfunc[A].\n\\end{equation*}\nIf $f$ has a retraction, we also say that $A$ is a \\define{retract}\\index{retract!of a type} of $B$.\n\\end{defn}\n\n\\begin{defn}\nWe say that a function $f:A\\to B$ is an \\define{equivalence}\\index{equivalence|textbf}\\index{bi-invertible map|see {equivalence}} if it has both a section and a retraction, i.e.~if it comes equipped with a term of type\\index{is_equiv@{$\\isequiv$}|textbf}\n\\begin{equation*}\n\\isequiv(f)\\defeq\\sections(f)\\times\\retractions(f).\n\\end{equation*}\nWe will write $\\eqv{A}{B}$\\index{equiv@{$\\eqv{A}{B}$}|textbf} for the type $\\sm{f:A\\to B}\\isequiv(f)$.\n\\end{defn}\n\nClearly, if $f$ is \\define{invertible}\\index{invertible map} in the sense that it comes equipped with a function $g:B\\to A$ such that $f\\circ g\\htpy\\idfunc[B]$ and $g\\circ f\\htpy\\idfunc[A]$, then $f$ is an equivalence. We write\\index{has_inverse@{$\\hasinverse$}|textbf}\n\\begin{equation*}\n\\hasinverse(f)\\defeq\\sm{g:B\\to A} (f\\circ g\\htpy \\idfunc[B])\\times (g\\circ f\\htpy\\idfunc[A]).\n\\end{equation*}\nThe section of an equivalence is also a retraction (and vice versa), so we define the \\define{inverse} of an equivalence to be its section. It follows immediately that the inverse of any equivalence is again an equivalence.\\index{equivalence!invertibility of} The identity function $\\idfunc[A]$ on a type $A$ is an equivalence since it is its own section and its own retraction.\n\nIt is straightforward to show that for any two functions $f,g:A\\to B$, we have\n\\begin{equation*}\n(f\\htpy g)\\to (\\isequiv(f)\\leftrightarrow\\isequiv(g)).\n\\end{equation*}\nGiven a commuting triangle\n\\begin{equation*}\n\\begin{tikzcd}[column sep=tiny]\nA \\arrow[rr,\"h\"] \\arrow[dr,swap,\"f\"] & & B \\arrow[dl,\"g\"] \\\\\n& X.\n\\end{tikzcd}\n\\end{equation*}\nwith $H:f\\htpy g\\circ h$, we have:\n\\begin{enumerate}\n\\item If the map $h$ has a section, then $f$ has a section if and only if $g$ has a section.\n\\item If the map $g$ has a retraction, then $f$ has a retraction if and only if $h$ has a retraction.\n\\item (The \\define{3-for-2 property} for equivalences.) If any two of the functions\n\\begin{equation*}\nf,\\qquad g,\\qquad h\n\\end{equation*}\nare equivalences, then so is the third.\n\\end{enumerate}\n\nIn the following theorem we characterize the identity type of a $\\Sigma$-type as a $\\Sigma$-type of identity types.\n\n\n\\begin{prp}[Theorem 2.7.2 of \\cite{hottbook}]\\label{thm:eq_sigma}\nLet $B$ be a type family over $A$, let $s:\\sm{x:A}B(x)$, and consider the dependent function\\index{pair_eq@{$\\paireq$}|textbf}\n\\begin{equation*}\n\\paireq_s:\\prd{t:\\sm{x:A}B(x)} (s=t)\\to \\sm{\\alpha:\\proj 1(s)=\\proj 1(t)} \\tr_B(\\alpha,\\proj 2(s))=\\proj 2(t)\n\\end{equation*}\ndefined by $\\paireq_s(\\refl{s}) \\defeq (\\refl{\\proj 1(s)},\\refl{\\proj 2(s)})$. Then $\\paireq_{s,t}$ is an equivalence for every $t:\\sm{x:A}B(x)$.\\index{Sigma type@{$\\Sigma$-type}!identity types of|textit}\\index{identity type!of a Sigma-type@{of a $\\Sigma$-type}|textit}\n\\end{prp}\n\nWe include the proof mainly to introduce some more notation.\n\n\\begin{proof}\nThe maps in the converse direction\\index{eq_pair@{$\\eqpair$}}\n\\begin{equation*}\n\\eqpair_{s,t} : \\Big(\\sm{p:\\proj 1(s)=\\proj 1(t)}\\id{\\tr_B(p,\\proj 2(s))}{\\proj 2(t)}\\Big)\\to(\\id{s}{t})\n\\end{equation*}\nis defined by\n\\begin{equation*}\n\\eqpair_{(x,y),(x',y')}(\\refl{x},\\refl{y})\\defeq \\refl{(x,y)}.\n\\end{equation*}\nThe proofs that the function $\\eqpair_{s,t}$ is indeed an inverse of $\\paireq_{s,t}$ are also by induction.\n\\end{proof}\n\n\\begin{defn}\nWe say that a type $A$ is \\define{contractible}\\index{contractible!type|textbf} if there is a term of type\n\\begin{equation*}\n\\iscontr(A) \\defeq \\sm{c:A}\\prd{x:A}c=x.\n\\end{equation*}\nGiven a term $(c,C):\\iscontr(A)$, we call $c:A$ the \\define{center of contraction}\\index{center of contraction|textbf} of $A$, and we call $C:\\prd{x:A}a=x$ the \\define{contraction}\\index{contraction} of $A$.\n\\end{defn}\n\nSuppose $A$ is a contractible type with center of contraction $c$ and contraction $C$. Then the type of $C$ is (judgmentally) equal to the type\n\\begin{equation*}\n\\const_c\\htpy\\idfunc[A].\n\\end{equation*}\nIn other words, the contraction $C$ is a \\emph{homotopy} from the constant function to the identity function.\n\n\\begin{defn}\nConsider a type $A$ with a base point $a:A$. We say that $A$ satisfies \\define{singleton induction}\\index{singleton induction|textbf} if for every type family $B$ over $A$, the map\n\\begin{equation*}\n\\evpt:\\Big(\\prd{x:A}B(x)\\Big)\\to B(a)\n\\end{equation*}\ngiven by $f\\mapsto f(a)$ has a section.\n\\end{defn}\n\n\\begin{prp}\\label{thm:contractible}\nA type $A$ is contractible if and only if it satisfies singleton induction.\n\\end{prp}\n\n\\begin{eg}\nBy definition the unit type\\index{unit type!contractibility} $\\unit$ satisfies singleton induction, so it is contractible.\n\\end{eg}\n\n\\begin{rmk}\nFor any family $P:\\Big(\\sm{x:A}B(x)\\Big)\\to\\UU$ there is a map\n\\begin{equation*}\n\\evpair : \\Big(\\prd{t:\\sm{x:A}B(x)}P(t)\\Big)\\to \\prd{x:A}{y:B(x)}P(x,y)\n\\end{equation*}\nthat evaluates $f:\\prd{t:\\sm{x:A}B(x)}P(t)$ at pairs $(x,y)$. In other words, $\\evpair$ is defined by $\\lam{f}{x}{y}f(x,y)$. By the induction principle for $\\Sigma$-types, this map has a section. It is easy to show that $\\evpair$ is in fact an equivalence. \n\nSimilarly, there is a map\n\\begin{equation*}\n\\evrefl : \\Big(\\prd{x:A}{p:a=x}B(x,p)\\Big)\\to B(a,\\refl{a})\n\\end{equation*}\ngiven by $\\lam{f}f(a,\\refl{a})$, for any type family $B:\\prd{x:A} (a=x)\\to\\UU$. By path induction, this map has a section, and again it is easy to show that this map is in fact an equivalence. \n\\end{rmk}\n\n\\begin{prp}[Lemma 3.11.8 in \\cite{hottbook}]\\label{thm:total_path}\nFor any $x:A$, the type\n\\begin{equation*}\n\\sm{y:A}x=y\n\\end{equation*}\nis contractible.\\index{identity type!contractibility of total space|textit}\n\\end{prp}\n\n\\begin{proof}\nWe have the term $(x,\\refl{x}):\\sm{y:A}x=y$, and both maps in the composite\n\\begin{equation*}\n\\begin{tikzcd}[column sep=large]\n\\prd{t:\\sm{y:A}x=y}B(t) \\arrow[r,\"\\evpair\"] & \\prd{y:A}{p:x=y}B((y,p)) \\arrow[r,\"\\evrefl\"] & B((x,\\refl{x}))\n\\end{tikzcd}\n\\end{equation*}\nhave sections, so the composite has a section. The composite is $\\evpt$, so we see that the asserted type satisfies singleton induction.\n\\end{proof}\n\n\\begin{defn}\nLet $f:A\\to B$ be a function, and let $b:B$. The \\define{fiber}\\index{fiber|textbf}\\index{homotopy fiber|see {fiber}} of $f$ at $b$ is defined to be the type\n\\begin{equation*}\n\\fib{f}{b}\\defeq\\sm{a:A}f(a)=b.\n\\end{equation*}\n\\end{defn}\n\n\\begin{eg}[Lemma 4.8.1 of \\cite{hottbook}]\\label{eg:fib_proj}\nConsider a type family $B$ over $A$. Then the map\n\\begin{equation*}\nB(a)\\to \\fib{\\proj 1}{a}\n\\end{equation*}\ngiven by $b\\mapsto ((a,b),\\refl{a})$ is an equivalence. In other words, the fibers of the projection function $\\proj 1 : \\big(\\sm{x:A}B(x)\\big)\\to A$ are just the fibers of the family $B$.\n\\end{eg}\n\n\\begin{defn}\nWe say that a function $f:A\\to B$ is \\define{contractible}\\index{contractible!map|textbf} if there is a term of type\n\\begin{equation*}\n\\iscontr(f)\\defeq\\prd{b:B}\\iscontr(\\fib{f}{b}).\n\\end{equation*}\n\\end{defn}\n\nWe cite Chapter 4 of \\cite{hottbook} for the following result, although it is well-known that it can be proven directly and without the use of function extensionality.\n\n\\begin{prp}[Chapter 4 in \\cite{hottbook}]\\label{thm:contr_equiv}\nA function is an equivalence if and only if it is contractible.\\index{contractible!map!is an equivalence|textit}\n\\end{prp}\n\n\\section{The Fundamental Theorem of Identity Types}\nConsider a family\n\\begin{equation*}\nf : \\prd{x:A}B(x)\\to C(x)\n\\end{equation*}\nof maps. Such $f$ is also called a \\define{fiberwise map} or \\define{fiberwise transformation}.\n\n\\begin{defn}[Definition 4.7.5 of \\cite{hottbook}]\nWe define the map\n\\begin{equation*}\n\\total{f}:\\sm{x:A}B(x)\\to\\sm{x:A}C(x).\n\\end{equation*}\nby $\\lam{(x,y)}(x,f(x,y))$.\n\\end{defn}\n\n\\begin{lem}[Theorem 4.7.6 of \\cite{hottbook}]\\label{lem:fib_total}\nFor any fiberwise transformation $f:\\prd{x:A}B(x)\\to C(x)$, and any $a:A$ and $c:C(a)$, there is an equivalence\n\\begin{equation*}\n\\eqv{\\fib{f(a)}{c}}{\\fib{\\total{f}}{\\pairr{a,c}}}.\n\\end{equation*}\n\\end{lem}\n\n\\begin{eg}\nThere are equivalences\n\\begin{equation*}\n\\eqv{\\fib{(\\apfunc{f})_{x,y}}{q}}{\\fib{\\delta_f}{(x,y,q)}}\n\\end{equation*}\nfor any $q:f(x)=f(y)$, because the triangle\n\\begin{equation*}\n\\begin{tikzcd}[column sep=-1em]\nA \\arrow[rr,\"{\\lam{x}(x,x,\\refl{x})}\"] \\arrow[dr,swap,\"\\delta_f\"] & & \\sm{x,y:A}x=y \\arrow[dl,\"\\total{\\total{\\apfunc{f}}}\"] \\\\\n\\phantom{\\sm{x,y:A}x=y} & \\sm{x,y:A}f(x)=f(y)\n\\end{tikzcd}\n\\end{equation*}\ncommutes, and the top map is an equivalence.\n\\end{eg}\n\n\\begin{prp}[Theorem 4.7.7 of \\cite{hottbook}]\\label{thm:fib_equiv}\nLet $f:\\prd{x:A}B(x)\\to C(x)$ be a fiberwise transformation. The following are logically equivalent:\n\\begin{enumerate}\n\\item For each $x:A$, the map $f_x:B(x)\\to C(x)$ is an equivalence. In this case we say that $f$ is a \\define{fiberwise equivalence}.\n\\item The map $\\total{f}:\\sm{x:A}B(x)\\to\\sm{x:A}C(x)$ is an equivalence.\n\\end{enumerate}\n\\end{prp}\n\nThe following theorem is the key to many results about identity types, which we will use instead of the \\emph{encode-decode method}\\index{encode-decode method} of \\cite{LicataShulman}. We refer to it as the \\define{Fundamental Theorem of Identity Types}.\n\n\\begin{thm}[Theorem 5.8.2 of \\cite{hottbook}]\\label{thm:id_fundamental}\nLet $A$ be a type with $a:A$, and let $B$ be a type family over $A$ with $b:B(a)$.\nThen  the following are logically equivalent:\n\\begin{enumerate}\n\\item The canonical family of maps\n\\begin{equation*}\n\\ind{a{=}}(b):\\prd{x:A} (a=x)\\to B(x)\n\\end{equation*}\nis a fiberwise equivalence.\n\\item The total space\n\\begin{equation*}\n\\sm{x:A}B(x)\n\\end{equation*}\nis contractible.\n\\end{enumerate}\n\\end{thm}\n\n\\begin{proof}\nBy \\autoref{thm:fib_equiv} it follows that the fiberwise transformation $\\ind{a{=}}(b)$ is a fiberwise equivalence if and only if it induces an equivalence\n\\begin{equation*}\n\\eqv{\\Big(\\sm{x:A}a=x\\Big)}{\\Big(\\sm{x:A}B(x)\\Big)}\n\\end{equation*}\non total spaces. We have that $\\sm{x:A}a=x$ is contractible. Now it follows by the 3-for-2 property of equivalences, applied in the case\n\\begin{equation*}\n\\begin{tikzcd}\n\\sm{x:A}a=x \\arrow[rr,\"\\total{\\ind{a{=}}(b)}\"] \\arrow[dr,swap,\"\\eqvsym\"] & & \\sm{x:A}B(x) \\arrow[dl] \\\\\n& \\unit & \\phantom{\\sm{x:A}a=x}\n\\end{tikzcd}\n\\end{equation*}\nthat $\\total{\\ind{a{=}}(b)}$ is an equivalence if and only if $\\sm{x:A}B(x)$ is contractible.\n\\end{proof}\n\nObserve that in the proof of \\cref{thm:id_fundamental} we haven't used the actual definition of the fiberwise transformation. Indeed, for any fiberwise transformation\n\\begin{equation*}\nf:\\prd{x:A}(a=x)\\to B(x)\n\\end{equation*}\nwe have that $f$ is a fiberwise equivalence if and only if the total space of $B$ is contractible.\n\nSince retracts of contractible types are again contractible, it follows that the only retract of the identity type is the identity type itself:\n\n\\begin{cor}\\label{cor:id_fundamental_retr}\nLet $a:A$, and let $B$ be a type family over $A$. If each $B(x)$ is a retract of $\\id{a}{x}$, then $B(x)$ is equivalent to $\\id{a}{x}$ for every $x:A$.\n\\end{cor}\n\nAs a first application of the fundamental theorem we give a quick new proof that equivalences are embeddings. The proof of the corresponding theorem in \\cite{hottbook} is more involved.\n\n\\begin{defn}\nAn \\define{embedding}\\index{embedding|textbf} is a map $f:A\\to B$ satisfying the property that\n\\begin{equation*}\n\\apfunc{f}:(\\id{x}{y})\\to(\\id{f(x)}{f(y)})\n\\end{equation*}\nis an equivalence for every $x,y:A$. We write $\\isemb(f)$ for the type of witnesses that $f$ is an embedding.\n\\end{defn}\n\n\\begin{prp}[Theorem 2.11.1 in \\cite{hottbook}]\n\\label{cor:emb_equiv} \nAny equivalence is an embedding.\\index{embedding!equivalences are embeddings|textit}\\index{equivalence!is an embedding|textit}\n\\end{prp}\n\n\\begin{proof}\nLet $e:\\eqv{A}{B}$ be an equivalence, and let $x:A$. By \\autoref{thm:id_fundamental} it follows that\n\\begin{equation*}\n\\apfunc{e} : (\\id{x}{y})\\to (\\id{e(x)}{e(y)})\n\\end{equation*}\nis an equivalence for every $y:A$ if and only if the total space\n\\begin{equation*}\n\\sm{y:A}e(x)=e(y)\n\\end{equation*}\nis contractible for every $y:A$. Now observe that $\\sm{y:A}e(x)=e(y)$ is equivalent to the fiber $\\fib{e}{e(x)}$, which is contractible by \\cref{thm:contr_equiv}.\n\\end{proof}\n\n\\begin{defn}\nA type $A$ is said to be a \\define{proposition} if there is a term of type\n\\begin{equation*}\n\\isprop(A)\\defeq\\prd{x,y:A}\\iscontr(x=y).\n\\end{equation*}\nFurthermore, we write $\\prop\\defeq\\sm{X:\\UU}\\isprop(X)$ for the type of all small propositions.\n\\end{defn}\n\nWe will often use either of the following characterizations of propositions.\n\n\\begin{lem}[Lemma 3.11.10 and Exercise 3.5 of \\cite{hottbook}]\\label{lem:prop_char}\nFor any type $A$ the following are equivalent:\n\\begin{enumerate}\n\\item $A$ is a proposition.\n\\item $A$ is \\define{proof irrelevant} in the sense that $\\prd{x,y:A}x=y$.\n\\item $A\\to\\iscontr(A)$. \n\\end{enumerate}\n\\end{lem}\n\n\\begin{eg}\\label{eg:prop_contr}\nAny contractible type is a proposition. The empty type is a proposition by a direct application of the induction principle of the empty type. Furthermore, any retract of a proposition is again a proposition. In particular, propositions are closed under equivalences.\n\\end{eg}\n\n\\begin{lem}\\label{lem:id_fib}\nConsider a function $f:A\\to B$, and let $(a,p),(a',p'):\\fib{f}{b}$ for some $b:B$. Then the canonical map\n\\begin{equation*}\n((a,p)=(a',p'))\\to \\fib{\\apfunc{f}}{\\ct{p}{p'^{-1}}}\n\\end{equation*}\nis an equivalence.\n\\end{lem}\n\n\\begin{proof}\nBy \\cref{thm:fib_equiv} it suffices to show that the type\n\\begin{equation*}\n\\sm{y:A}{q:f(y)=b}{p:\\proj 1(s)=y} \\ap{f}{p}=\\ct{\\proj 2(s)}{q^{-1}}\n\\end{equation*}\nis contractible, which is immediate by two applications of \\cref{thm:total_path}.\n\\end{proof}\n\n\\begin{prp}[Lemma 7.6.2 of \\cite{hottbook}]\\label{thm:prop_emb}\nA map is an embedding if and only if its fibers are propositions.\n\\end{prp}\n\n\\begin{proof}\nIf $f$ is an embedding, then the fibers of $\\apfunc{f}$ are contractible by \\cref{thm:contr_equiv}. Thus it follows by \\cref{lem:id_fib} that the fibers of $f$ are propositions.\n\nConversely, if the fibers of $f$ are propositions, then we have by \\cref{lem:id_fib} an equivalence\n\\begin{equation*}\n\\eqv{((x,p)=(y,\\refl{f(y)}))}{\\fib{\\apfunc{f}}{p}}\n\\end{equation*}\nfor any $p:f(x)=f(y)$, which shows that the fibers of $\\apfunc{f}$ are contractible. Thus $f$ is an embedding by \\cref{thm:contr_equiv}.\n\\end{proof}\n\n\\begin{defn}\nA type family $B$ over $A$ is said to be a \\define{subtype} of $A$ if for each $x:A$ the type $B(x)$ is a proposition.\n\\end{defn}\n\n\\begin{cor}\\label{thm:subtype}\nA type family $B$ over $A$ is a subtype if and only if the projection map\n\\begin{equation*}\n\\proj 1 : \\Big(\\sm{x:A}B(x)\\Big)\\to A\n\\end{equation*}\nis an embedding.\n\\end{cor}\n\n\\begin{proof}\nImmediate by \\cref{eg:fib_proj,thm:prop_emb}.\n\\end{proof}\n\n\\section{Function extensionality}\n\\begin{prp}[Theorem 4.9.5 of \\cite{hottbook}]\\label{thm:funext_wkfunext}\nThe following are equivalent:\n\\begin{enumerate}\n\\item The \\define{function extensionality principle}\\index{function extensionality}: For every type family $B$ over $A$, and any two dependent functions $f,g:\\prd{x:A}B(x)$, the canonical map\\index{htpy_eq@{$\\htpyeq$}|textbf}\n\\begin{equation*}\n\\htpyeq(f,g) : (\\id{f}{g})\\to (f\\htpy g)\n\\end{equation*}\nby path induction (sending $\\refl{f}$ to $\\lam{x}\\refl{f(x)}$) is an equivalence. We will write $\\eqhtpy$\\index{eq_htpy@{$\\eqhtpy$}} for its inverse.\n\\item The \\define{weak function extensionality principle}\\index{weak function extensionality} holds: For every type family $B$ over $A$ one has\\index{contractible!weak function extensionality}\n\\begin{equation*}\n\\Big(\\prd{x:A}\\iscontr(B(x))\\Big)\\to\\iscontr\\Big(\\prd{x:A}B(x)\\Big).\n\\end{equation*}\n\\end{enumerate}\n\\end{prp}\n\nFrom now on we will assume that function extensionality holds.\n\n\\begin{cor}[Theorem 7.1.9 of \\cite{hottbook}]\\label{thm:prop_pi}\nFor any type family $B$ over $A$ one has\n\\begin{equation*}\n\\Big(\\prd{x:A}\\isprop(B(x))\\Big)\\to \\isprop\\Big(\\prd{x:A}B(x)\\Big).\n\\end{equation*}\nIn particular, if $B$ is a proposition, then $A\\to B$ is a proposition for any type $A$.\n\\end{cor}\n\nWe show in this section that a map $f:A\\to B$ is an equivalence if and only if for any type family $P$ over $B$, the precomposition map\n\\begin{equation*}\n\\blank\\circ f: \\Big(\\prd{y:B}P(y)\\Big)\\to\\Big(\\prd{x:A}P(f(x))\\Big)\n\\end{equation*}\nis an equivalence. \nIn the proof we use the notion of \\emph{path-split} maps, which was introduced in \\cite{RijkeShulmanSpitters}.\n\n\\begin{defn}\nWe say that a map $f:A\\to B$ is \\define{path-split}\\index{path-split|textbf} if $f$ has a section, and for each $x,y:A$ the map\n\\begin{equation*}\n\\apfunc{f}(x,y):(x=y)\\to (f(x)=f(y))\n\\end{equation*}\nalso has a section. We write $\\pathsplit(f)$\\index{path_split(f)@{$\\pathsplit(f)$}|textbf} for the type\n\\begin{equation*}\n\\sections(f)\\times\\prd{x,y:A}\\sections(\\apfunc{f}(x,y)).\n\\end{equation*}\n\\end{defn}\n\nWe will also use the notion of \\emph{half-adjoint equivalences}, which were introduced in \\cite{hottbook}.\n\n\\begin{defn}[Definition 4.2.1 of \\cite{hottbook}]\nWe say that a map $f:A\\to B$ is a \\define{half-adjoint equivalence}\\index{half-adjoint equivalence|textbf}, in the sense that there are\n\\begin{align*}\ng & : B \\to A\\\\\nG & : f\\circ g \\htpy \\idfunc[B] \\\\\nH & : g\\circ f \\htpy \\idfunc[A] \\\\\nK & : G\\cdot f \\htpy f\\cdot H.\n\\end{align*}\nWe write $\\halfadj(f)$\\index{half_adj(f)@{$\\halfadj(f)$}|textbf} for the type of such quadruples $(g,G,H,K)$.\n\\end{defn}\n\nFurthermore, we will need `type theoretic choice'. \n\n\\begin{prp}[Theorem 2.15.7 of \\cite{hottbook}]\\label{thm:choice}\nLet $C(x,y)$ be a type in context $\\Gamma,x:A,y:B(x)$. Then the map\n\\begin{equation*}\n\\varphi:\\Big(\\prd{x:A}\\sm{y:B(x)}C(x,y)\\Big)\\to \\Big(\\sm{f:\\prd{x:A}B(x)}\\prd{x:A}C(x,f(x))\\Big)\n\\end{equation*}\ngiven by $\\lam{h}(\\lam{x}\\proj 1(h(x)),\\lam{x}\\proj 2(h(x)))$ is an equivalence.\n\\end{prp}\n\n\\begin{cor}\nFor type $A$ and any type family $C$ over $B$, the map\n\\begin{equation*}\n\\Big(\\sm{f:A\\to B} \\prd{x:A}C(f(x))\\Big)\\to\\Big(A\\to\\sm{y:B}C(x)\\Big)\n\\end{equation*}\ngiven by $\\lam{(f,g)}{x}(f(x),g(x))$ is an equivalence.\n\\end{cor}\n\n\\begin{prp}\\label{prp:equiv_precomp}\nFor any map $f:A\\to B$, the following are equivalent:\n\\begin{enumerate}\n\\item $f$ is an equivalence.\n\\item $f$ is path-split.\n\\item $f$ is a half-adjoint equivalence.\n\\item For any type family $P$ over $B$ the map\n\\begin{equation*}\n\\Big(\\prd{y:B}P(y)\\Big)\\to\\Big(\\prd{x:A}P(f(x))\\Big)\n\\end{equation*}\ngiven by $s\\mapsto s\\circ f$ is an equivalence.\n\\item For any type $X$ the map\n\\begin{equation*}\n(B\\to X)\\to (A\\to X)\n\\end{equation*}\ngiven by $g\\mapsto g\\circ f$ is an equivalence. \n\\end{enumerate}\n\\end{prp}\n\n\\begin{proof}\nTo see that (i) implies (ii) we note that any equivalence has a section, and its action on paths is an equivalence by \\cref{cor:emb_equiv} so again it has a section.\n\nTo show that (ii) implies (iii), assume that $f$ is path-split. Thus we have $(g,G):\\sections(f)$, and the assumption that $\\apfunc{f}:(x=y)\\to (f(x)=f(y))$ has a section for every $x,y:A$ gives us a term of type\n\\begin{equation*}\n\\prd{x:A}\\fib{\\apfunc{f}}{G(f(x))}.\n\\end{equation*}\nBy \\cref{thm:choice} this type is equivalent to\n\\begin{equation*}\n\\sm{H:\\prd{x:A}g(f(x))=x}\\prd{x:A}G(f(x))=\\ap{f}{H(x)},\n\\end{equation*}\nso we obtain $H:g\\circ f\\htpy \\idfunc[A]$ and $K:G\\cdot f\\htpy f\\cdot H$, showing that $f$ is a half-adjoint equivalence.\n\nTo show that (iii) implies (iv), suppose that $f$ comes equipped with $(g,G,H,K)$ witnessing that $f$ is a half-adjoint equivalence. Then we define the inverse of $\\blank\\circ f$ to be the map\n\\begin{equation*}\n\\varphi:\\Big(\\prd{x:A}P(f(x))\\Big)\\to\\Big(\\prd{y:B}P(y)\\Big)\n\\end{equation*}\ngiven by $s\\mapsto \\lam{y}\\tr_P(G(y),sg(y))$. \n\nTo see that $\\varphi$ is a section of $\\blank\\circ f$, let $s:\\prd{x:A}P(f(x))$. By function extensionality it suffices to construct a homotopy $\\varphi(s)\\circ f\\htpy s$. In other words, we have to show that\n\\begin{equation*}\n\\tr_P(G(f(x)),s(g(f(x)))=s(x)\n\\end{equation*}\nfor any $x:A$. Now we use the additional homotopy $K$ from our assumption that $f$ is a half-adjoint equivalence. Since we have $K(x):G(f(x))=\\ap{f}{H(x)}$ it suffices to show that\n\\begin{equation*}\n\\tr_P(\\ap{f}{H(x)},sgf(x))=s(x).\n\\end{equation*}\nA simple path-induction argument yields that\n\\begin{equation*}\n\\tr_P(\\ap{f}{p})\\htpy \\tr_{P\\circ f}(p)\n\\end{equation*}\nfor any path $p:x=y$ in $A$, so it suffices to construct an identification\n\\begin{equation*}\n\\tr_{P\\circ f}(H(x),sgf(x))=s(x).\n\\end{equation*}\nWe have such an identification by $\\apd{H(x)}{s}$.\n\nTo see that $\\varphi$ is a retraction of $\\blank\\circ f$, let $s:\\prd{y:B}P(y)$. By function extensionality it suffices to construct a homotopy $\\varphi(s\\circ f)\\htpy s$. In other words, we have to show that\n\\begin{equation*}\n\\tr_P(G(y),sfg(y))=s(y)\n\\end{equation*}\nfor any $y:B$. We have such an identification by $\\apd{G(y)}{s}$. This completes the proof that (iii) implies (iv).\n\nNote that (v) is an immediate consequence of (iv), since we can just choose $P$ to be the constant family $X$.\n\nIt remains to show that (v) implies (i). Suppose that\n\\begin{equation*}\n\\blank\\circ f:(B\\to X)\\to (A\\to X)\n\\end{equation*}\nis an equivalence for every type $X$. Then its fibers are contractible by \\cref{thm:contr_equiv}. In particular, choosing $X\\jdeq A$ we see that the fiber\n\\begin{equation*}\n\\fib{\\blank\\circ f}{\\idfunc[A]}\\jdeq \\sm{h:B\\to A}h\\circ f=\\idfunc[A]\n\\end{equation*}\nis contractible. Thus we obtain a function $h:B\\to A$ and a homotopy $H:h\\circ f\\htpy\\idfunc[A]$ showing that $h$ is a retraction of $f$. We will show that $h$ is also a section of $f$. To see this, we use that the fiber\n\\begin{equation*}\n\\fib{\\blank\\circ f}{f}\\jdeq \\sm{i:B\\to B} i\\circ f=f\n\\end{equation*}\nis contractible (choosing $X\\jdeq B$). \nOf course we have $(\\idfunc[B],\\refl{f})$ in this fiber. However we claim that there also is an identification $p:(f\\circ h)\\circ f=f$, showing that $(f\\circ h,p)$ is in this fiber, because\n\\begin{align*}\n(f\\circ h)\\circ f & \\jdeq f\\circ (h\\circ f) \\\\\n& = f\\circ \\idfunc[A] \\\\\n& \\jdeq f\n\\end{align*}\nNow we conclude by the contractibility of the fiber that there is an identification $(\\idfunc[B],\\refl{f})=(f\\circ h,p)$. In particular we obtain that $\\idfunc[B]=f\\circ h$, showing that $h$ is a section of $f$.\n\\end{proof}\n\n\\section{Homotopy pullbacks}\n\\subsection{Cartesian squares}\n\nRecall that a square\n\\begin{equation*}\n\\begin{tikzcd}\nC \\arrow[r,\"q\"] \\arrow[d,swap,\"p\"] & B \\arrow[d,\"g\"] \\\\\nA \\arrow[r,swap,\"g\"] & X\n\\end{tikzcd}\n\\end{equation*}\nis said to \\define{commute}\\index{commuting square|textbf} if there is a homotopy $H:f\\circ p\\htpy g\\circ q$. \n\n\\begin{defn}\\label{defn:cospan}\nA \\define{cospan}\\index{cospan|textbf} consists of three types $A$, $X$, and $B$, and maps $f:A\\to X$ and $g:B\\to X$. Given a type $C$, a \\define{cone}\\index{cone!on a cospan|textbf} on the cospan $A \\stackrel{f}{\\rightarrow} X \\stackrel{g}{\\leftarrow} B$ with \\define{vertex} $C$\\index{vertex!of a cone|textbf} consists of maps $p:C\\to A$, $q:C\\to B$ and a homotopy $H:f\\circ p\\htpy g\\circ q$ witnessing that the square\n\\begin{equation*}\n\\begin{tikzcd}\nC \\arrow[r,\"q\"] \\arrow[d,swap,\"p\"] & B \\arrow[d,\"g\"] \\\\\nA \\arrow[r,swap,\"f\"] & X\n\\end{tikzcd}\n\\end{equation*}\ncommutes. We write\\index{cone(C)@{$\\cone(\\blank)$}|textbf}\n\\begin{equation*}\n\\cone(C)\\defeq \\sm{p:C\\to A}{q:C\\to B}f\\circ p\\htpy g\\circ q\n\\end{equation*}\nfor the type of cones with vertex $C$.\n\\end{defn}\n\nGiven a cone with vertex $C$ on a span $A\\stackrel{f}{\\rightarrow} X \\stackrel{g}{\\leftarrow} B$ and a map $h:C'\\to C$, we construct a new cone with vertex $C'$ in the following definition.\n\n\\begin{defn}\nFor any cone $(p,q,H)$ with vertex $C$ and any type $C'$, we define a map\\index{cone map@{$\\conemap$}|textbf}\n\\begin{equation*}\n\\conemap(p,q,H):(C'\\to C)\\to\\cone(C')\n\\end{equation*}\nby $h\\mapsto (p\\circ h,q\\circ h,H\\cdot h)$. \n\\end{defn}\n\n\\begin{defn}\nWe say that a commuting square\n\\begin{equation*}\n\\begin{tikzcd}\nC \\arrow[r,\"q\"] \\arrow[d,swap,\"p\"] & B \\arrow[d,\"g\"] \\\\\nA \\arrow[r,swap,\"f\"] & X\n\\end{tikzcd}\n\\end{equation*}\nwith $H:f\\circ p\\htpy g\\circ q$ is a \\define{pullback square}\\index{pullback square|textbf}, or that it is \\define{cartesian}\\index{cartesian square|textbf}, if it satisfies the \\define{universal property} of pullbacks\\index{universal property!of pullbacks}, which asserts that the map\n\\begin{equation*}\n\\conemap(p,q,H):(C'\\to C)\\to\\cone(C')\n\\end{equation*}\nis an equivalence for every type $C'$. \n\\end{defn}\n\nWe often indicate the universal property with a diagram as follows:\n\\begin{equation*}\n\\begin{tikzcd}\nC' \\arrow[drr,bend left=15,\"{q'}\"] \\arrow[dr,densely dotted,\"h\"] \\arrow[ddr,bend right=15,swap,\"{p'}\"] \\\\\n& C \\arrow[r,\"q\"] \\arrow[d,swap,\"p\"] & B \\arrow[d,\"g\"] \\\\\n& A \\arrow[r,swap,\"f\"] & X\n\\end{tikzcd}\n\\end{equation*}\nsince the universal property states that for every cone $(p',q',H')$ with vertex $C'$, the type of pairs $(h,\\alpha)$ consisting of $h:C'\\to C$ equipped with $\\alpha:\\conemap((p,q,H),h)=(p',q',H')$ is contractible by \\cref{thm:contr_equiv}.\n\n\n\\begin{prp}\\label{thm:pullback_up}\nConsider a commuting square\n\\begin{equation*}\n\\begin{tikzcd}\nC \\arrow[r,\"q\"] \\arrow[d,swap,\"p\"] & B \\arrow[d,\"g\"] \\\\\nA \\arrow[r,swap,\"f\"] & X\n\\end{tikzcd}\n\\end{equation*}\nwith $H:f\\circ p\\htpy g\\circ q$\nThen the following are equivalent:\\index{universal property!of pullbacks (characterization)|textit}\n\\begin{enumerate}\n\\item The square is a pullback square.\n\\item For every type $C'$ and every cone $(p',q',H')$ with vertex $C'$, the type of quadruples $(h,K,L,M)$ consisting of\n\\begin{align*}\nh & : C'\\to C \\\\\nK & : p\\circ h \\htpy p' \\\\\nL & : q\\circ h \\htpy q' \\\\\nM & : \\ct{(H\\cdot h)}{(g\\cdot L)} \\htpy \\ct{(f\\cdot K)}{H'}\n\\end{align*}\nis contractible.\n\\end{enumerate}\n\\end{prp}\n\n\\begin{rmk}\nThe homotopy $M$ in \\cref{thm:pullback_up} witnesses that the square\n\\begin{equation*}\n\\begin{tikzcd}\nf\\circ p\\circ h \\arrow[r,\"f\\cdot K\"] \\arrow[d,swap,\"H\\cdot h\"] & f\\circ p' \\arrow[d,\"{H'}\"] \\\\\ng\\circ q\\circ h \\arrow[r,swap,\"g\\cdot L\"] & g\\circ q'\n\\end{tikzcd}\n\\end{equation*}\nof homotopies commutes.\n\\end{rmk}\n\n\\subsection{The unique existence of pullbacks}\n\n\\begin{defn}\nLet $f:A\\to X$ and $B\\to X$ be maps. Then we define\n\\begin{align*}\nA\\times_X B & \\defeq \\sm{x:A}{y:B}f(x)=g(y) \\\\\n\\pi_1 & \\defeq \\proj 1 & & : A\\times_X B\\to A \\\\\n\\pi_2 & \\defeq \\proj 1\\circ\\proj 2 & & : A\\times_X B\\to B\\\\\n\\pi_3 & \\defeq \\proj 2\\circ\\proj 2 & & : f\\circ \\pi_1 \\htpy g\\circ\\pi_2.\n\\end{align*}\nThe type $A\\times_X B$ is called the \\define{canonical pullback}\\index{canonical pullback|textbf} of $f$ and $g$.\n\\end{defn}\n\nNote that $A\\times_X B$ depends on $f$ and $g$, although this dependency is not visible in the notation.\n\n\\begin{prp}[Exercise 2.11 of \\cite{hottbook}]\nGiven maps $f:A\\to X$ and $g:B\\to X$, the commuting square\\index{canonical pullback|textit}\n\\begin{equation*}\n\\begin{tikzcd}\nA\\times_X B \\arrow[r,\"\\pi_2\"] \\arrow[d,swap,\"\\pi_1\"] & B \\arrow[d,\"g\"] \\\\\nA \\arrow[r,swap,\"f\"] & X,\n\\end{tikzcd}\n\\end{equation*}\nis a pullback square.\n\\end{prp}\n\nIn the following lemma we establish the uniqueness of pullbacks up to equivalence via a \\emph{3-for-2 property} for pullbacks.\n\n\\begin{lem}\\label{lem:pb_3for2}\\index{pullback!3-for-2 property|textit}\\index{3-for-2 property!of pullbacks|textit}%\nConsider the squares\n\\begin{equation*}\n\\begin{tikzcd}\nC \\arrow[r,\"q\"] \\arrow[d,swap,\"p\"] & B \\arrow[d,\"g\"] & {C'} \\arrow[r,\"{q'}\"] \\arrow[d,swap,\"{p'}\"] & B \\arrow[d,\"g\"] \\\\\nA \\arrow[r,swap,\"f\"] & X & A \\arrow[r,swap,\"f\"] & X\n\\end{tikzcd}\n\\end{equation*}\nwith homotopies $H:f\\circ p \\htpy g\\circ q$ and $H':f\\circ p'\\htpy g\\circ q'$.\nFurthermore, suppose we have a map $h:C'\\to C$ equipped with\n\\begin{align*}\nK & : p\\circ h \\htpy p' \\\\\nL & : q\\circ h \\htpy q' \\\\\nM & : \\ct{(H\\cdot h)}{(g\\cdot L)} \\htpy \\ct{(f\\cdot K)}{H'}.\n\\end{align*}\nIf any two of the following three properties hold, so does the third:\n\\begin{samepage}%\n\\begin{enumerate}\n\\item $C$ is a pullback.\n\\item $C'$ is a pullback.\n\\item $h$ is an equivalence.\n\\end{enumerate}%\n\\end{samepage}%\n\\end{lem}\n\n\\begin{proof}\nThe type of triples $(K,L,M)$ is equivalent to the type of identifications\n\\begin{equation*}\n\\conemap((p,q,H),h)=(p',q',H').\n\\end{equation*}\nLet $D$ be a type, and let $k:D\\to C'$ be a map. We observe that\n\\begin{align*}\n\\conemap((p,q,H),(h\\circ k)) & \\jdeq (p\\circ (h\\circ k),q\\circ (h\\circ k),H\\circ (h\\circ k)) \\\\\n& \\jdeq ((p\\circ h)\\circ k,(q\\circ h)\\circ k, (H\\circ h)\\circ k) \\\\\n& \\jdeq \\conemap(\\conemap((p,q,H),h),k) \\\\\n& = \\conemap((p',q',H'),k).\n\\end{align*}\nThus we see that the triangle \n\\begin{equation*}\n\\begin{tikzcd}[column sep=-1em]\n(D\\to C') \\arrow[rr,\"{h\\circ \\blank}\"] \\arrow[dr,swap,\"{\\conemap(p',q',H')}\"] & & (D\\to C) \\arrow[dl,\"{\\conemap(p,q,H)}\"] \\\\\n& \\cone(D) & \\phantom{(D\\to C')}\n\\end{tikzcd}\n\\end{equation*}\ncommutes. Therefore it follows from the 3-for-2 property of equivalences that if any two of the following properties hold, then so does the third:\n\\begin{enumerate}\n\\item The map $\\conemap(p,q,H):(D\\to C)\\to \\cone(D)$ is an equivalence,\n\\item The map $\\conemap(p',q',H'):(D\\to C')\\to \\cone(D)$ is an equivalence,\n\\item The map $h\\circ\\blank : (D\\to C')\\to (D\\to C)$ is an equivalence.\n\\end{enumerate}\nThus the 3-for-2 property for pullbacks follows from the fact that $h$ is an equivalence if and only if $h\\circ\\blank : (D\\to C')\\to (D\\to C)$ is an equivalence for any type $D$.\n\\end{proof}\n\n\n\\begin{defn}\nGiven a commuting square\n\\begin{equation*}\n\\begin{tikzcd}\nC \\arrow[r,\"q\"] \\arrow[d,swap,\"p\"] & B \\arrow[d,\"g\"] \\\\\nA \\arrow[r,swap,\"f\"] & X\n\\end{tikzcd}\n\\end{equation*}\nwith $H:f\\circ p \\htpy g \\circ q$, we define the \\define{gap map}\\index{gap map|textbf}\\index{pullback!gap map|textbf}\n\\begin{equation*}\n\\gap(p,q,H):C \\to A\\times_X B\n\\end{equation*}\nby $\\lam{z}(p(z),q(z),H(z))$. Furthermore, we will write\\index{is_pullback@{$\\ispullback$}|textbf}\n\\begin{equation*}\n\\ispullback(f,g,H)\\defeq \\isequiv(\\gap(p,q,H)).\n\\end{equation*}\n\\end{defn}\n\n\\begin{prp}\\label{thm:is_pullback}\nConsider a commuting square\n\\begin{equation*}\n\\begin{tikzcd}\nC \\arrow[r,\"q\"] \\arrow[d,swap,\"p\"] & B \\arrow[d,\"g\"] \\\\\nA \\arrow[r,swap,\"f\"] & X\n\\end{tikzcd}\n\\end{equation*}\nwith $H:f\\circ p \\htpy g \\circ q$. The following are equivalent:\n\\begin{enumerate}\n\\item The square is a pullback square\n\\item There is a term of type\n\\begin{equation*}\n\\ispullback(p,q,H)\\defeq \\isequiv(\\gap(p,q,H)).\n\\end{equation*}\n\\end{enumerate}\n\\end{prp}\n\n\\begin{proof}\nNote that there are homotopies\n\\begin{align*}\nK & : \\pi_1\\circ \\gap(p,q,H) \\htpy p \\\\\nL & : \\pi_2\\circ \\gap(p,q,H) \\htpy q \\\\\nM & : \\ct{(\\pi_3\\cdot \\gap(p,q,H))}{(g\\cdot L)} \\htpy \\ct{(f\\cdot K)}{H}.\n\\end{align*}\ngiven by \n\\begin{align*}\nK & \\defeq \\lam{z}\\refl{p(z)} \\\\\nL & \\defeq \\lam{z}\\refl{q(z)} \\\\\nM & \\defeq \\lam{z}\\ct{\\rightunit(H(z))}{\\leftunit(H(z))^{-1}}.\n\\end{align*}\nTherefore the claim follows by \\cref{lem:pb_3for2}.\n\\end{proof}\n\n\\subsection{Fiberwise equivalences}\n\n\\begin{prp}\\label{thm:pb_fibequiv}\nLet $f:A\\to B$, and let $g:\\prd{a:A}P(a)\\to Q(f(a))$ be a fiberwise transformation\\index{fiberwise transformation|textit}. The following are equivalent:\n\\begin{enumerate}\n\\item The commuting square\n\\begin{equation*}\n\\begin{tikzcd}[column sep=large]\n\\sm{a:A}P(a) \\arrow[r,\"{\\total[f]{g}}\"] \\arrow[d,swap,\"\\proj 1\"] & \\sm{b:B}Q(b) \\arrow[d,\"\\proj 1\"] \\\\\nA \\arrow[r,swap,\"f\"] & B\n\\end{tikzcd}\n\\end{equation*}\nis a pullback square.\n\\item $g$ is a fiberwise equivalence.\\index{fiberwise equivalence|textit}\n\\end{enumerate}\n\\end{prp}\n\n\\begin{proof}\nThe gap map factors as follows\n\\begin{equation*}\n\\begin{tikzcd}[column sep=-2em]\n\\sm{x:A}P(x) \\arrow[dr,swap,\"\\total{g}\"] \\arrow[rr,\"\\gap\"] & & A \\times_B \\Big(\\sm{y:B}Q(y)\\Big) \\\\\n\\phantom{A \\times_B \\Big(\\sm{y:B}Q(y)\\Big)} & \\sm{x:A}Q(f(x)) \\arrow[ur,swap,\"{\\gap'\\,\\defeq\\,\\lam{(x,q)}(x,(f(x),q),\\refl{f(x)})}\"]\n\\end{tikzcd}\n\\end{equation*}\nSince $\\gap'$ is an equivalence, it follows by \\cref{thm:fib_equiv} that the gap map is an equivalence if and only if $g$ is a fiberwise equivalence.\n\\end{proof}\n\n\\begin{lem}\nConsider a commuting square\n\\begin{equation*}\n\\begin{tikzcd}\nC \\arrow[r,\"q\"] \\arrow[d,swap,\"p\"] & B \\arrow[d,\"g\"] \\\\\nA \\arrow[r,swap,\"f\"] & X\n\\end{tikzcd}\n\\end{equation*}\nwith $H:f\\circ p\\htpy g\\circ q$, and consider the fiberwise transformation\n\\begin{equation*}\n\\fibf{(f,q,H)} : \\prd{a:A} \\fib{p}{a}\\to \\fib{g}{f(a)}\n\\end{equation*}\ngiven by $\\lam{a}{(c,u)}(q(c),\\ct{H(c)^{-1}}{\\ap{f}{u}})$. Then there is an equivalence\n\\begin{equation*}\n\\eqv{\\fib{\\gap(p,q,H)}{(a,b,\\alpha)}}{\\fib{\\fibf{(f,q,H)}(a)}{(b,\\alpha^{-1})}}\n\\end{equation*}\n\\end{lem}\n\n\\begin{proof}\nTo obtain an equivalence of the desired type we simply concatenate known equivalences:\n\\begin{align*}\n\\fib{h}{(a,b,\\alpha)} & \\jdeq \\sm{z:C} (p(z),q(z),H(z))=(a,b,\\alpha) \\\\\n& \\eqvsym \\sm{z:C}{u:p(z)=a}{v:q(z)=b}\\ct{H(z)}{\\ap{g}{v}}=\\ct{\\ap{f}{u}}{\\alpha} \\\\\n& \\eqvsym \\sm{(z,u):\\fib{p}{a}}{v:q(z)=b} \\ct{H(z)^{-1}}{\\ap{f}{u}}=\\ct{\\ap{g}{v}}{\\alpha^{-1}} \\\\\n& \\eqvsym \\fib{\\varphi(a)}{(b,\\alpha^{-1})}\\qedhere\n\\end{align*}\n\\end{proof}\n\n\\begin{cor}\\label{cor:pb_fibequiv}\nConsider a commuting square\n\\begin{equation*}\n\\begin{tikzcd}\nC \\arrow[r,\"q\"] \\arrow[d,swap,\"p\"] & B \\arrow[d,\"g\"] \\\\\nA \\arrow[r,swap,\"f\"] & X\n\\end{tikzcd}\n\\end{equation*}\nwith $H:f\\circ p\\htpy g\\circ q$. The following are equivalent:\n\\begin{enumerate}\n\\item The square is a pullback square.\\index{pullback square!characterized by fiberwise equivalence|textit}\n\\item The induced map on fibers\n\\begin{equation*}\n\\fibf{(p,q,H)}:\\prd{x:A}\\fib{p}{x}\\to \\fib{g}{f(x)}\n\\end{equation*}\nis a fiberwise equivalence.\n\\end{enumerate}\n\\end{cor}\n\n\\begin{cor}\\label{cor:pb_equiv}\nConsider a commuting square\n\\begin{equation*}\n\\begin{tikzcd}\nC \\arrow[r,\"q\"] \\arrow[d,swap,\"p\"] & B \\arrow[d,\"g\"] \\\\\nA \\arrow[r,swap,\"f\"] & X.\n\\end{tikzcd}\n\\end{equation*}\nand suppose that $g$ is an equivalence. Then the following are equivalent:\n\\begin{enumerate}\n\\item The square is a pullback square.\n\\item The map $p:C\\to A$ is an equivalence.\\index{equivalence!pullback of|textit}\n\\end{enumerate}\n\\end{cor}\n\n\\begin{proof}\nIf the square is a pullback square, then by \\cref{thm:pb_fibequiv} the fibers of $p$ are equivalent to the fibers of $g$, which are contractible by \\cref{thm:contr_equiv}. Thus it follows that $p$ is a contractible map, and hence that $p$ is an equivalence.\n\nIf $p$ is an equivalence, then by \\cref{thm:contr_equiv} both $\\fib{p}{x}$ and $\\fib{g}{f(x)}$ are contractible for any $x:X$. It follows that the induced map $\\fib{p}{x}\\to\\fib{g}{f(x)}$ is an equivalence. Thus we apply \\cref{cor:pb_fibequiv} to conclude that the square is a pullback.\n\\end{proof}\n\n\\section{The univalence axiom}\n\nThe univalence axiom characterizes the identity type of the universe. It is considered to be an \\emph{extensionality principle}\\index{extensionality principle!types} for types. In the following theorem we introduce the univalence axiom and give two more equivalent ways of stating this.\n\n\\begin{prp}\\label{thm:univalence}\nThe following are equivalent:\n\\begin{enumerate}\n\\item The \\define{univalence axiom}\\index{univalence axiom|textbf}: for any $A:\\UU$ the map\\index{equiv_eq@{$\\equiveq$}|textbf}\n\\begin{equation*}\n\\equiveq\\defeq \\ind{A=}(\\idfunc[A]) : \\prd{B:\\UU} (\\id{A}{B})\\to(\\eqv{A}{B}).\n\\end{equation*}\nis a fiberwise equivalence.\\index{identity type!universe} If this is the case, we write\n$\\eqequiv$\\index{eq equiv@{$\\eqequiv$}|textbf}\nfor the inverse of $\\equiveq$.\n\\item The type\n\\begin{equation*}\n\\sm{B:\\UU}\\eqv{A}{B}\n\\end{equation*}\nis contractible for each $A:\\UU$.\n\\item The principle of \\define{equivalence induction}\\index{equivalence induction}\\index{induction principle!for equivalences}: for every $A:\\UU$ and for every type family\n\\begin{equation*}\nP:\\prd{B:\\UU} (\\eqv{A}{B})\\to \\type,\n\\end{equation*}\nthe map\n\\begin{equation*}\n\\Big(\\prd{B:\\UU}{e:\\eqv{A}{B}}P(B,e)\\Big)\\to P(A,\\idfunc[A])\n\\end{equation*}\ngiven by $f\\mapsto f(A,\\idfunc[A])$ has a section.\\qedhere\n\\end{enumerate}\n\\end{prp}\n\nIt is a trivial observation, but nevertheless of fundamental importance, that by the univalence axiom the identity types of $\\UU$ are equivalent to types in $\\UU$, because it provides an equivalence $\\eqv{(A=B)}{(\\eqv{A}{B})}$, and the type $\\eqv{A}{B}$ is in $\\UU$ for any $A,B:\\UU$. Since the identity types of $\\UU$ are equivalent to types in $\\UU$, we also say that the universe is \\emph{locally small}.\n\n\\begin{defn}\\label{defn:ess_small}\n\\begin{enumerate}\n\\item A type $A$ is said to be \\define{essentially small}\\index{essentially small!type|textbf} if there is a type $X:\\UU$ and an equivalence $\\eqv{A}{X}$. We write\\index{ess_small(A)@{$\\esssmall(A)$}|textbf}\n\\begin{equation*}\n\\esssmall(A)\\defeq\\sm{X:\\UU}\\eqv{A}{X}.\n\\end{equation*}\n\\item A map $f:A\\to B$ is said to be \\define{essentially small}\\index{essentially small!map|textbf} if for each $b:B$ the fiber $\\fib{f}{b}$ is essentially small.\nWe write\\index{ess_small(f)@{$\\esssmall(f)$}|textbf}\n\\begin{equation*}\n\\esssmall(f)\\defeq\\prd{b:B}\\esssmall(\\fib{f}{b}).\n\\end{equation*}\n\\item A type $A$ is said to be \\define{locally small}\\index{locally small!type} if for every $x,y:A$ the identity type $x=y$ is essentially small.\nWe write\\index{loc_small(A)@{$\\locsmall(A)$}|textbf}\n\\begin{equation*}\n\\locsmall(A)\\defeq \\prd{x,y:A}\\esssmall(x=y).\n\\end{equation*}\n\\item Similarly, a map $f:A\\to X$ is said to be \\define{locally small} if $\\delta_f:A\\to A\\times_X A$ is essentially small.\n\\end{enumerate}\n\\end{defn}\n\n\\begin{lem}\\label{lem:isprop_ess_small}\nThe type $\\esssmall(X)$ is a proposition for any type $X$.\\index{essentially small!is a proposition|textit}\n\\end{lem}\n\n\\begin{proof}\nLet $X$ be a type. Our goal is to show that the type\n\\begin{equation*}\n\\sm{Y:\\UU}\\eqv{X}{Y}\n\\end{equation*}\nis a proposition. Suppose there is a type $X':\\UU$ and an equivalence $e:\\eqv{X}{X'}$, then the map\n\\begin{equation*}\n(\\eqv{X}{Y})\\to (\\eqv{X'}{Y})\n\\end{equation*}\ngiven by precomposing with $e^{-1}$ is an equivalence. This induces an equivalence on total spaces\n\\begin{equation*}\n\\eqv{\\Big(\\sm{Y:\\UU}\\eqv{X}{Y}\\Big)}{\\Big(\\sm{Y:\\UU}\\eqv{X'}{Y}\\Big)}\n\\end{equation*}\nHowever, the codomain of this equivalence is contractible by \\cref{thm:univalence}. Thus it follows that the asserted type is a proposition.\n\\end{proof}\n\n\\begin{cor}\nFor each function $f:A\\to B$, the type $\\esssmall(f)$ is a proposition, and for each type $X$ the type $\\locsmall(X)$ is a proposition.\n\\end{cor}\n\n\\begin{proof}\nThis follows from the fact that propositions are closed under dependent products, established in \\cref{thm:prop_pi}.\n\\end{proof}\n\n\\begin{rmk}\nThe property of essentially smallness is preserved by $\\Pi$, $\\Sigma$, and $\\mathsf{Id}$. Of course, any contractible type is essentially small, and so is any small type. The property of essentially smallness is preserved by $\\Sigma$ and $\\mathsf{Id}$, and the exponent $X^A$ of a locally small type $X$ by an essentially small type $A$ is again locally small. Furthermore, any proposition is locally small, and any universe is locally small with respect to itself. \n\\end{rmk}\n\n\\begin{defn}\nConsider two functions $f:A\\to X$ and $g:B\\to X$. We define the type \n\\begin{equation*}\n\\hom_X(f,g)\\defeq \\sm{h:A\\to B} f\\htpy g\\circ h.\n\\end{equation*}\n\\end{defn}\n\nIn other words, the type $\\hom_X(f,g)$ is the type of functions $h:A\\to B$ equipped with a homotopy witnessing that the triangle\n\\begin{equation*}\n\\begin{tikzcd}[column sep=tiny]\nA \\arrow[dr,swap,\"f\"] \\arrow[rr,\"h\"] & & B \\arrow[dl,\"g\"] \\\\\n& X\n\\end{tikzcd}\n\\end{equation*}\n\n\\begin{lem}\nLet $P$ and $Q$ be two type families over $X$, and write $\\proj 1^P$ and $\\proj 1^Q$ for their first projections, respectively. Then the map\n\\begin{equation*}\n\\tottriangle:\\Big(\\prd{x:X} P(x)\\to Q(x)\\Big)\\to \\hom_X(\\proj 1^P,\\proj 1^Q)\n\\end{equation*}\ngiven by $\\tottriangle(f)\\defeq (\\total{f},\\lam{(x,y)}\\refl{x})$, is an equivalence.\n\\end{lem}\n\n\\begin{cor}\\label{cor:fib_triangle}\nFor any two maps $f:A\\to X$ and $g:B\\to X$, the map\n\\begin{equation*}\n\\fibtriangle : \\hom_X(f,g) \\to \\prd{x:X}\\fib{f}{x}\\to \\fib{g}{x}\n\\end{equation*}\ngiven by $\\lam{(h,H)}{x}{(a,p)}(h(a),\\ct{H(a)^{-1}}{p})$ is an equivalence.\n\\end{cor}\n\n\\begin{thm}\\label{thm:fam_proj}\nFor any small type $A:\\UU$ there is an equivalence\n\\begin{equation*}\n\\eqv{(A\\to \\UU)}{\\Big(\\sm{X:\\UU} X\\to A\\Big)}.\n\\end{equation*}\n\\end{thm}\n\n\\begin{proof}\nNote that we have the function\n\\begin{equation*}\n\\varphi :\\lam{B} \\Big(\\sm{x:A}B(x),\\proj 1\\Big) : (A\\to \\UU)\\to \\Big(\\sm{X:\\UU}X\\to A\\Big).\n\\end{equation*}\nThe fiber of this map at $(X,f)$ is by univalence and function extensionality equivalent to the type\n\\begin{equation*}\n\\sm{B:A\\to \\UU}{e:\\eqv{(\\sm{x:A}B(x))}{X}} \\proj 1\\htpy f\\circ e.\n\\end{equation*}\nBy \\cref{cor:fib_triangle} this type is equivalent to the type\n\\begin{equation*}\n\\sm{B:A\\to \\UU}\\prd{a:A} \\eqv{B(a)}{\\fib{f}{a}},\n\\end{equation*}\nand by `type theoretic choice', which was established in \\cref{thm:choice}, this type is equivalent to\n\\begin{equation*}\n\\prd{a:A}\\sm{X:\\UU}\\eqv{X}{\\fib{f}{a}}.\n\\end{equation*}\nWe conclude that the fiber of $\\varphi$ at $(X,f)$ is equivalent to the type $\\esssmall(f)$. However, since $f:X\\to A$ is a map between small types it is essentially small. Moreover, since being essentially small is a proposition by \\cref{lem:isprop_ess_small}, it follows that $\\fib{\\varphi}{(X,f)}$ is contractible for every $f:X\\to A$. In other words, $\\varphi$ is a contractible map, and therefore it is an equivalence.\n\\end{proof}\n\n\\begin{rmk}\nThe inverse of the map\n\\begin{equation*}\n\\varphi : (A\\to \\UU)\\to \\Big(\\sm{X:\\UU}X\\to A\\Big).\n\\end{equation*}\nconstructed in \\cref{thm:fam_proj} is the map $(X,f)\\mapsto \\fibf{f}$.\n\\end{rmk}\n\n\\section{The object classifier}\n\n\\begin{defn}\nLet $p:E\\to B$ and $p':E'\\to B'$ be maps. A morphism from $p'$ to $p$ is a triple $(f,g,H)$ consisting of maps $f:B'\\to B$ and $g:E'\\to E$ and a homotophy $H:f\\circ p'\\htpy p\\circ g$ witnessing that the square\n\\begin{equation}\\label{eq:morphism_arrow}\n\\begin{tikzcd}\nE' \\arrow[r,\"g\"] \\arrow[d,swap,\"p'\"] & E \\arrow[d,\"p\"] \\\\\nB' \\arrow[r,\"f\"] & B\n\\end{tikzcd}\n\\end{equation}\ncommutes. We write $\\mathsf{hom}(p',p)$ for the type of such triples $(f,g,H)$, and sometimes we write $\\mathsf{hom}_f(p',p)$ for the type of pairs $(g,H)$. A morphism $(f,g,H)$ is said to be \\define{cartesian} if the square in \\cref{eq:morphism_arrow} is cartesian. We write $\\mathsf{cart}(p',p)$ for the type of cartesian morphisms from $p'$ to $p$, and we write $\\mathsf{cart}_f(p',p)$ for the type of triples $(g,H,t)$ for the type of triples, where $t:\\ispullback(p',g,H)$.  \n\\end{defn}\n\n\\begin{defn}\\label{defn:object_classifier}\nA morphism $p:E\\to B$ is said to be an \\define{object classifier} if the type $\\mathsf{cart}(p',p)$ is a proposition for each $p':E'\\to B'$. If $p:E\\to B$ is an object classifier, we also write \n\\begin{equation*}\n\\mathsf{is\\usc{}classified}(p')\\defeq \\mathsf{hom}(p',p).\n\\end{equation*}\n\\end{defn}\n\nOur goal in this section is to show that a univalent universe is an object classifier. \n\n\\begin{prp}\\label{thm:pb_fibequiv_complete}\nLet $\\alpha:I\\to J$ be a map, and let $A:I\\to\\UU$ and $B:J\\to\\UU$ be type families.\nThen the map\n\\begin{equation*}\n\\Big(\\prd{i:I}A_i\\to B_{\\alpha(i)}\\Big) \\to \\mathsf{hom}_\\alpha(\\proj 1^A,\\proj 1^B)\n\\end{equation*}\ngiven by $\\lam{f}(\\total[\\alpha]{f},\\lam{(x,y)}\\refl{x})$ is an equivalence. Furthermore, the map\n\\begin{equation*}\n\\Big(\\prd{i:I}A_i\\eqvsym B_{\\alpha(i)}\\Big) \\to \\mathsf{cart}_\\alpha(\\proj 1^A,\\proj 1^B)\n\\end{equation*}\ngiven by $\\lam{e}(\\total[\\alpha]{e},\\lam{(x,y)}\\refl{x},t)$ where $t$ is the term constructed in \\cref{thm:pb_fibequiv}, is an equivalence. \n\\end{prp}\n\n\\begin{proof}\nWe have the equivalences\n\\begin{align*}\n\\prd{i:I}A_i\\to B_{\\alpha(i)} & \\eqvsym \\prd{i:I}{a:A_i}\\sm{j:J}{\\gamma : \\alpha(i)=j} B_j \\\\\n& \\eqvsym \\prd{i:I}{a:A_i}\\sm{j:J}{b:B_j}\\alpha(i)=j \\\\\n& \\eqvsym \\prd{(i,a):\\sm{i:I}A_i}\\sm{(j,b):\\sm{j:J}B_j}\\alpha(i)=j \\\\\n& \\eqvsym \\sm{f:\\big(\\sm{i:I}A_i\\big)\\to\\big(\\sm{j:J}B_j\\big)}\\alpha\\circ \\proj 1^A\\htpy \\proj 1^B\\circ f \\\\\n& \\jdeq \\mathsf{hom}_\\alpha(\\proj 1^A,\\proj 1^B).\n\\end{align*}\nIt is easy to check that this composite is the asserted map. The second claim follows from \\cref{thm:pb_fibequiv}.\n\\end{proof}\n\n\\begin{cor}\\label{cor:sq_fib}\nConsider a diagram of the form\n\\begin{equation*}\n\\begin{tikzcd}\nA \\arrow[d,swap,\"f\"] & B \\arrow[d,\"g\"] \\\\\nI \\arrow[r,swap,\"\\alpha\"] & J.\n\\end{tikzcd}\n\\end{equation*}\nThen the map\n\\begin{equation*}\n\\mathsf{hom}_\\alpha(f,g)\\to \\Big(\\prd{i:I}\\fib{f}{i}\\to\\fib{g}{\\alpha(i)}\\Big)\n\\end{equation*}\ngiven by $\\lam{(h,H)}{i}{(a,p)}(h(a),\\ct{H(a)^{-1}}{\\ap{\\alpha}{p}})$ is an equivalence.\n\\end{cor}\n\n\\begin{thm}\\label{thm:classifier}\nLet $f:A\\to B$ be a map, and let $\\UU$ be a univalent universe with universal family $\\mathrm{El}$ over $\\UU$. Then there is an equivalence\n\\begin{equation*}\n\\eqv{\\esssmall(f)}{\\mathsf{cart}(f,\\proj 1^{\\mathrm{El}})}.\n\\end{equation*}\nIn particular, the type $\\mathsf{cart}(f,\\proj 1^{\\mathrm{El}})$ is a proposition for each map $f$, so the universe is an object classifier in the sense of \\cref{defn:object_classifier}.\n\\end{thm}\n\n\\begin{proof}\nFrom \\cref{cor:sq_fib} we obtain that the type of pairs $(\\tilde{F},H)$ is equivalent to the type of fiberwise transformations\n\\begin{equation*}\n\\prd{b:B}\\fib{f}{b}\\to F(b).\n\\end{equation*}\nBy \\cref{cor:pb_fibequiv} the square is a pullback square if and only if the induced map\n\\begin{equation*}\n\\prd{b:B}\\fib{f}{b}\\to F(b)\n\\end{equation*}\nis a fiberwise equivalence. Thus the data $(F,\\tilde{F},H,pb)$ is equivalent to the type of pairs $(F,e)$ where $e$ is a fiberwise equivalence from $\\fibf{f}$ to $F$. By \\cref{thm:choice} the type of pairs $(F,e)$ is equivalent to the type $\\esssmall(f)$. \n\\end{proof}\n\n\\begin{rmk}\nFor any type $A$ (not necessarily small), and any $B:A\\to \\UU$, the square\\index{Sigma-type@{$\\Sigma$-type}!as pullback of universal family|textit}\n\\begin{equation*}\n\\begin{tikzcd}[column sep=6em]\n\\sm{x:A}B(x) \\arrow[d,swap,\"\\proj 1\"] \\arrow[r,\"{\\lam{(x,y)}(B(x),y)}\"] & \\sm{X:\\UU}X \\arrow[d,\"\\proj 1\"] \\\\\nA \\arrow[r,swap,\"B\"] & \\UU\n\\end{tikzcd}\n\\end{equation*}\nis a pullback square. Therefore it follows that for any family $B:A\\to\\UU$ of small types, the projection map $\\proj 1:\\sm{x:A}B(x)\\to A$ is an essentially small map.\nTo see that the claim is a direct consequence of \\cref{thm:pb_fibequiv} we write the asserted square in its rudimentary form:\n\\begin{equation*}\n\\begin{tikzcd}[column sep=6em]\n\\sm{x:A}\\mathrm{El}(B(x)) \\arrow[d,swap,\"\\proj 1\"] \\arrow[r,\"{\\lam{(x,y)}(B(x),y)}\"] & \\sm{X:\\UU}\\mathrm{El}(X) \\arrow[d,\"\\proj 1\"] \\\\\nA \\arrow[r,swap,\"B\"] & \\UU.\n\\end{tikzcd}\n\\end{equation*}\n\\end{rmk}\n\nIn the following theorem we show that a type is locally small if and only if its diagonal is classified by $\\UU$.\n\n\\begin{thm}\nLet $A$ be a type. The following are equivalent:\n\\begin{enumerate}\n\\item $A$ is locally small.\\index{locally small|textit}\n\\item The diagonal $\\delta_A : A\\to A\\times A$ is classified by $\\UU$.\\index{diagonal!of a type|textit}\n\\end{enumerate}\n\\end{thm}\n\n\\begin{proof}\nThe identity type $x=y$ is the fiber of $\\delta_A$ at $(x,y):A\\times A$. Therefore it follows that $A$ is locally small if and only if the diagonal $\\delta_A$ is essentially small.\nNow the result follows from \\cref{thm:classifier}.\n\\end{proof}\n", "meta": {"hexsha": "4125c93ce81d2ef607348948d926dcf6e4f1ee5d", "size": 59494, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "univalent.tex", "max_stars_repo_name": "EgbertRijke/dissertation", "max_stars_repo_head_hexsha": "f2c087ba8983205d3dd336bbc194be5b7218c2c5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-07-06T10:37:12.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-06T10:37:12.000Z", "max_issues_repo_path": "univalent.tex", "max_issues_repo_name": "EgbertRijke/dissertation", "max_issues_repo_head_hexsha": "f2c087ba8983205d3dd336bbc194be5b7218c2c5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "univalent.tex", "max_forks_repo_name": "EgbertRijke/dissertation", "max_forks_repo_head_hexsha": "f2c087ba8983205d3dd336bbc194be5b7218c2c5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.431665422, "max_line_length": 480, "alphanum_fraction": 0.682589841, "num_tokens": 21682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.6370307875894138, "lm_q1q2_score": 0.34828903556393925}}
{"text": "\\section{Protocol Parameters}\n\\label{sec:protocol-parameters}\n\n\\subsection{Updatable Protocol Parameters}\n\\label{sec:updatable-protocol-parameters}\n\nThe Shelley protocol parameters are listed in Figure~\\ref{fig:defs:protocol-parameters}.\nSome of the Shelley protocol parameters are common to the Byron era,\nspecifically, the common ones are $\\var{a}$, $\\var{b}$, $\\var{maxTxSize}$, and\n$\\var{maxHeaderSize}$ (see the document~\\cite{byron_ledger_spec}).\n\nThe type $\\Ppm$ represents the names of the protocol parameters,\nand $\\mathsf{T_{ppm}}$ is the type of the protocol parameter $\\var{ppm}$.\nThe type $\\PParams$ is a finite map containing all the Shelley parameters,\nindexed by their names.\nWe will explain the significance of each parameter as it comes up in\nthe calculations used in transition rules.\nThe type $\\PParamsUpdate$ is similar to $\\PParams$, but is\na partial mapping of the protocol parameters. It is used in the update\nsystem explained in Section~\\ref{sec:update}.\n\nThe type $\\Coin$ is defined as an alias for the integers.\nNegative values will not be allowed in UTxO outputs or reward accounts,\nand $\\Z$ is only chosen over $\\N$ for its additive inverses.\n\nSome helper functions are defined in Figure~\\ref{fig:defs:protocol-parameters-helpers}.\nThe $\\fun{minfee}$ function calculates the minimum fee that must be paid by a transaction.\nThis value depends on the protocol parameters and the size of the transaction.\n\nTwo time related types are introduced, $\\Epoch$ and $\\type{Duration}$.\nA $\\type{Duration}$ is the difference between two slots, as given by $\\slotminus{}{}$.\n\nLastly, there are two functions, $\\fun{epoch}$ and $\\fun{firstSlot}$ for converting\nbetween epochs and slots and one function $\\fun{kesPeriod}$ for getting the cycle of a slot.\nNote that $\\Slot$ is an abstract type, while the constants are integers.\nWe use multiplication and division symbols on these distinct types\nwithout being explicit about the types and conversion.\n\n\\begin{figure*}[htb]\n  \\emph{Abstract types}\n  %\n  \\begin{equation*}\n    \\begin{array}{r@{~\\in~}lr}\n      \\var{p} & \\Ppm & \\text{protocol parameter}\\\\\n      \\var{dur} & \\Duration & \\text{difference between slots}\\\\\n      \\var{epoch} & \\Epoch & \\text{epoch} \\\\\n      \\var{kesPeriod} & \\KESPeriod & \\text{KES period} \\\\\n    \\end{array}\n  \\end{equation*}\n  %\n  \\emph{Derived types}\n  %\n  \\begin{equation*}\n    \\begin{array}{r@{~\\in~}l@{\\qquad=\\qquad}lr}\n      \\var{pp}\n      & \\PParams\n      & \\Ppm \\to \\mathsf{T_{ppm}}\n      & \\text{protocol parameters}\n      \\\\\n      \\var{ppup}\n      & \\PParamsUpdate\n      & \\Ppm \\mapsto \\mathsf{T_{ppm}}\n      & \\text{protocol parameter update}\n      \\\\\n      \\var{coin}\n      & \\Coin\n      & \\Z\n      & \\text{unit of value}\n      \\\\\n      \\var{pv}\n      & \\ProtVer\n      & \\N\\times\\N\n      & \\text{protocol version}\n    \\end{array}\n  \\end{equation*}\n  %\n  \\emph{Protocol Parameters}\n  %\n  \\begin{equation*}\n      \\begin{array}{r@{~\\in~}lr}\n        \\var{a} \\mapsto \\Z & \\PParams & \\text{min fee factor}\\\\\n        \\var{b} \\mapsto \\Z & \\PParams & \\text{min fee constant}\\\\\n        \\var{maxBlockSize} \\mapsto \\N & \\PParams & \\text{max block body size}\\\\\n        \\var{maxTxSize} \\mapsto \\N & \\PParams & \\text{max transaction size}\\\\\n        \\var{maxHeaderSize} \\mapsto \\N & \\PParams & \\text{max block header size}\\\\\n        \\var{keyDecayRate} \\mapsto \\nonnegReals & \\PParams & \\text{stake credential decay rate}\\\\\n        \\var{poolDeposit} \\mapsto \\Coin & \\PParams & \\text{stake pool deposit}\\\\\n        \\var{E_{max}} \\mapsto \\Epoch & \\PParams & \\text{epoch bound on pool retirement}\\\\\n        \\var{n_{opt}} \\mapsto \\Npos & \\PParams & \\text{desired number of pools}\\\\\n        \\var{a_0} \\mapsto \\posReals & \\PParams & \\text{pool influence}\\\\\n        \\tau \\mapsto \\unitInterval & \\PParams & \\text{treasury expansion}\\\\\n        \\rho \\mapsto \\unitInterval & \\PParams & \\text{monetary expansion}\\\\\n        \\var{d} \\mapsto \\{0,~0.1,~0.2,~\\ldots,~1\\} & \\PParams & \\text{decentralization parameter}\\\\\n        \\var{extraEntropy} \\mapsto \\Seed & \\PParams & \\text{extra entropy}\\\\\n        \\var{pv} \\mapsto \\ProtVer & \\PParams & \\text{protocol version}\\\\\n        \\var{minUTxOValue} \\mapsto \\Coin & \\PParams & \\text{minimum allowed value of a new \\TxOut}\\\\\n        \\var{minPoolCost} \\mapsto \\Coin & \\PParams & \\text{minimum allowed stake pool cost}\\\\\n      \\end{array}\n  \\end{equation*}\n  %\n  \\emph{Accessor Functions}\n  %\n  \\begin{center}\n    \\fun{a},\n    \\fun{b},\n    \\fun{maxBlockSize},\n    \\fun{maxTxSize},\n    \\fun{maxHeaderSize},\n    \\fun{keyDeposit},\n    \\fun{poolDeposit},\n    \\fun{emax},\n    \\fun{nopt},\n    \\fun{influence},\n    \\fun{tau},\n    \\fun{rho},\n    \\fun{d},\n    \\fun{extraEntropy},\n    \\fun{pv},\n    \\fun{minUTxOValue},\n    \\fun{minPoolCost}\n  \\end{center}\n  %\n  \\emph{Abstract Functions}\n  %\n  \\begin{equation*}\n    \\begin{array}{r@{~\\in~}lr}\n      (\\slotminus{}{}) & \\Slot \\to \\Slot \\to \\Duration\n                       & \\text{duration between slots}\n    \\end{array}\n  \\end{equation*}\n  %\n  \\caption{Definitions Used in Protocol Parameters}\n  \\label{fig:defs:protocol-parameters}\n\\end{figure*}\n\n\\subsection{Global Constants}\n\\label{sec:global-constants}\n\nIn additon to the updatable protocol parameters defined in\nSection~\\ref{sec:updatable-protocol-parameters},\nthere are ten parameters which cannot be changed by the update\nsystem in Section~\\ref{sec:update}.\nWe call these the global constants, as changing these values can only\nbe done by updating the software, i.e. a soft or a hard fork.\nFor the software update mechanism, see Section~\\ref{sec:software-updates}.\n\nThe constants $\\SlotsPerEpoch$ and $\\SlotsPerKESPeriod$\nrepresent the number of slots in an epoch/KES period (for a brief explanation\nof a KES period, see Section \\ref{sec:crypto-primitives-shelley}).\nThe constants $\\StabilityWindow$ and $\\RandomnessStabilisationWindow$ concern the chain stability.\nThe maximum number of time a KES key can be evolved before a pool operator\nmust create a new operational certificate is given by $\\MaxKESEvo$.\n\\textbf{Note that if } $\\MaxKESEvo$\n\\textbf{is changed, the KES signature format may have to change as well.}\n\nThe constant $\\Quorum$ determines the quorum amount needed for votes on the\nprotocol parameter updates and the application version updates.\n\nThe constant $\\MaxMajorPV$ provides a mechanism for halting outdated nodes.\nOnce the major component of the protocol version in the protocol parameters\nexceeds this value, every subsequent block is invalid.\nSee Figures~\\ref{fig:funcs:chain-helper} and~\\ref{fig:rules:chain}.\n\nThe constant $\\MaxLovelaceSupply$ gives the total number of lovelace in the system,\nwhich is used in the reward calculation.\nIt is always equal to the sum of the values in the UTxO, plus the sum of the\nvalues in the reward accounts, plus the deposit pot, plus the fee pot,\nplus the treasury and the reserves.\n\nThe constant $\\ActiveSlotCoeff$ is the value $f$ from the\nPraos paper \\cite{ouroboros_praos}.\n\nLastly, $\\NetworkId$ determines what network, either mainnet or testnet, is expected.\nThis value will also appear inside every address, and transactions\ncontaining addresses with an unexpected network ID are rejected.\n\n\\begin{figure*}[htb]\n  \\emph{Global Constants}\n  %\n  \\begin{equation*}\n    \\begin{array}{r@{~\\in~}lr}\n      \\SlotsPerEpoch & \\N & \\text{- slots per epoch} \\\\\n      \\SlotsPerKESPeriod & \\N & \\text{- slots per KES period} \\\\\n      \\StabilityWindow & \\Duration &\n      \\begin{array}{r}\n        \\text{- window size for chain growth} \\\\\n        \\text{guarantees, see}\\text{ in \\cite{ouroboros_praos}}\n      \\end{array} \\\\\n      \\RandomnessStabilisationWindow & \\Duration &\n      \\begin{array}{r}\n        \\text{- duration needed for epoch}\\\\\n        \\text{nonce stabilization}\\\\\n      \\end{array} \\\\\n      \\MaxKESEvo & \\N & \\text{- maximum KES key evolutions}\\\\\n      \\Quorum & \\N & \\text{- quorum for update system votes}\\\\\n      \\MaxMajorPV & \\N & \\text{- all blocks are invalid after this value}\\\\\n      \\MaxLovelaceSupply & \\Coin & \\text{- total lovelace in the system}\\\\\n      \\ActiveSlotCoeff & (0, 1] & \\text{ - }f\\text{ in \\cite{ouroboros_praos}}\\\\\n      \\NetworkId & \\Network & \\text{- the network, mainnet or testnet}\\\\\n    \\end{array}\n  \\end{equation*}\n  %\n  \\caption{Global Constants}\n  \\label{fig:defs:global-constants}\n\\end{figure*}\n\n\\begin{figure*}[htb]\n  \\emph{Helper Functions}\n  %\n  \\begin{align*}\n    \\fun{minfee} & \\in \\PParams \\to \\Tx \\to \\Coin & \\text{minimum fee}\\\\\n    \\fun{minfee} & ~\\var{pp}~\\var{tx} =\n    (\\fun{a}~\\var{pp}) \\cdot \\fun{txSize}~\\var{tx} + (\\fun{b}~\\var{pp})\n    \\\\\n    \\\\\n    \\fun{epoch} & \\in ~ \\Slot \\to \\Epoch & \\text{epoch of a slot}\n    \\\\\n    \\fun{epoch} & ~\\var{slot} = \\var{slot}~/~\\SlotsPerEpoch\n    \\\\\n    \\\\\n    \\fun{firstSlot} & \\in ~ \\Epoch \\to \\Slot\n               & \\text{first slot of an epoch}\n    \\\\\n    \\fun{firstSlot} & ~\\var{e} = \\var{e}~\\cdot~\\SlotsPerEpoch\n    \\\\\n    \\\\\n    \\fun{kesPeriod} & \\in ~ \\Slot \\to \\KESPeriod & \\text{KES period of a slot}\n    \\\\\n    \\fun{kesPeriod} & ~\\var{slot} = \\var{slot}~/~\\SlotsPerKESPeriod\n  \\end{align*}\n  %\n  \\caption{Helper functions for the Protocol Parameters}\n  \\label{fig:defs:protocol-parameters-helpers}\n\\end{figure*}\n\n\\clearpage\n", "meta": {"hexsha": "776c72b80ce4c7560b1b7c9a89453cfa862a2261", "size": 9202, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "shelley/chain-and-ledger/formal-spec/protocol-parameters.tex", "max_stars_repo_name": "ConsultD/cardano-ledger-specs", "max_stars_repo_head_hexsha": "76365a530d064c9c74fbc93e6c4f751ee18004c3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "shelley/chain-and-ledger/formal-spec/protocol-parameters.tex", "max_issues_repo_name": "ConsultD/cardano-ledger-specs", "max_issues_repo_head_hexsha": "76365a530d064c9c74fbc93e6c4f751ee18004c3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "shelley/chain-and-ledger/formal-spec/protocol-parameters.tex", "max_forks_repo_name": "ConsultD/cardano-ledger-specs", "max_forks_repo_head_hexsha": "76365a530d064c9c74fbc93e6c4f751ee18004c3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8270042194, "max_line_length": 100, "alphanum_fraction": 0.6689850033, "num_tokens": 2756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.34825182247274916}}
{"text": "\\section{Power Reactor Terminology}\n\\begin{labeling}\n    \\item [\\underline{Coolant}:] Material used to remove heat from core, to\n        heat water, to push a turbine, etc.\n    \\item [\\underline{Steam or Coolant Loops}:] Number of heat transfer mechanisms.\n        Must be at least 1.\n    \\item [\\underline{Moderator}:] Material that slows down neutrons. Not all\n        reactors are moderated. Sometimes this is the same as the coolant. Typically\n        low-Z materials.\n    \\item [\\underline{Neutron Energies}:]\n        \\begin{labeling}\n            \\item [\\underline{Fast}:] At or near fission neutron birth energies $> 1$ MeV\n            \\item [\\underline{Epithermal}:] Neutrons in the process of slowing down\n                $[10^{-5}, 1)$ MeV.\n            \\item [\\underline{Thermal}:] Neutrons in thermal equilibrium with the moderator,\n                $< 10^{-5}$ MeV. Maxwellian distribution\n                % FIXME Add image of maxwell distribution for linaer and log.\n        \\end{labeling}\n    \\item [\\underline{Fuel Production}:]\n        \\begin{labeling}\n            \\item [\\underline{Burner}:] If destroies more atomes of fuel at discharge.\n            \\item [\\underline{Breeder}:] If creates more atoms of fuel at discharge\n        \\end{labeling}\n\\end{labeling}\n\n% FIXME Add single loop core image\n% FIXME Add two loop core image\n\n\\section{Neutron Multiplication}\nReactors are controlled by how many neutron are in teh core at any given time.\nThis is because neutrons cause fission, which releases energy and more neutrons.\n\n\\section{Prompt Neutron Multiplication}\n``Prompt'' means that neutrons born in a given generation are destroyed or lost before the\nnext generation, i.e. instantly.\n\nChange in \\# neutrons = Sources - Losses\n\nSymbolically,\n\\[ \\frac{dN}{dt} = \\nu \\Sigma_f\\phi - \\Sigma_a\\phi -DB^2\\phi \\]\n\nLet's go through this term-by-term.\n\nNote: The book uses $\\Phi$ for $\\phi$\n\n\\section{Difussion Theory Terms}\n\\begin{labeling}\n    \\item [$N$:] Neutron density [n/cm$^3$]\n    \\item [$t$:] Time [sec]\n    \\item [$\\nu$:] Number of neutrons born per fission, 2 - 5 typically [unitless]\n    \\item [$\\Sigma_f$:] macroscopic fission cross section, [1/cm]\n    \\item [$\\phi$:] neutron flux, [n/cm$^2$ s]\n    \\item [$\\Sigma_a$:] Macroscopic absorption cross-section\n    \\item [$D$:] Diffission coefficient, [cm], related to neutron mean free path\n        $\\lambda_{\\mathrm{tr}}$ by\n        \\[ D = \\frac{\\lambda_{\\mathrm{tr}}}{3} = \\frac{1}{3\\Sigma_{\\mathrm{tr}}} = \\frac{1}{3\\Sigma_s(1 -\\frac{2}{3A})} \\]\n    \\item [$B$:] Buckling [1/cm]\n        \\begin{itemize}\n            \\item \\mathbf{Geometric Buckling} $B_g$ depends on the shape of the core, see table 4-2.\n            \\item \\mathbf{Material Buckling} $B_m$'s is derived from the criticality constraint\n                such that $B_m^2 = \\frac{\\nu\\Sigma_f - \\Sigma_a}{D}$ for critical systems.\n        \\end{itemize}\n\\end{labeling}\n\nSo, $\\frac{dN}{dt}$ is the growth rate.\n\n$\\nu\\Sigma_f\\phi$ is the rate of neutron birth.\n\n$\\Sigma_a\\phi$ is the rate at which neutrons are destroyed.\n\n$DB^2\\phi$ is the \\textit{Leakage}, or the rate at which neutrons leave the system entirely.\n\n\\underline{On the board:}  Units for each term. Ensure that they are the same.\n", "meta": {"hexsha": "285a536b09bcb88057093c823a8e69c650034dbd", "size": 3226, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "notes/n03.tex", "max_stars_repo_name": "scopatz/rxps", "max_stars_repo_head_hexsha": "bef0045f12215ebe0ac15f9e944047eaefb0ec36", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notes/n03.tex", "max_issues_repo_name": "scopatz/rxps", "max_issues_repo_head_hexsha": "bef0045f12215ebe0ac15f9e944047eaefb0ec36", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notes/n03.tex", "max_forks_repo_name": "scopatz/rxps", "max_forks_repo_head_hexsha": "bef0045f12215ebe0ac15f9e944047eaefb0ec36", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.5945945946, "max_line_length": 122, "alphanum_fraction": 0.6602603844, "num_tokens": 912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961016, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.34815112699611533}}
{"text": "\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%\n\\documentclass[12pt]{amsart}\n\\usepackage{amssymb, amstext, amscd, amsmath}\n% \\usepackage[notcite,notref]{showkeys}\n% \\input{amsmacros2e}\n% %%%%%%%%%%%%%%%%%%%%%%% begin macros\n%%%%%%%%%%%%%%%%%%%%%%\n%\n%      Cites in bold rather than roman.\n\\makeatletter\n\\def\\@cite#1#2{{\\m@th\\upshape\\bfseries%\n[{#1\\if@tempswa{\\m@th\\upshape\\mdseries, #2}\\fi}]}}\n\\makeatother\n%\n% Change first-level `enumerate' numbering\n%style from arabic to roman numeral.\n%\n\\renewcommand{\\labelenumi}{(\\roman{enumi}) }\n%\n%     normal style theorems,\n%numbered within the section\n\\theoremstyle{plain}\n\\newtheorem{thm}{Theorem}[section]\n\\newtheorem{cor}[thm]{Corollary}\n\\newtheorem{prop}[thm]{Proposition}\n\\newtheorem{lem}[thm]{Lemma}\n%\n%      Theorem style with roman text, numbered within section\n\\theoremstyle{definition}\n\\newtheorem{rem}[thm]{Remark}\n\\newtheorem{defn}[thm]{Definition}\n\\newtheorem{note}[thm]{Note}\n\\newtheorem{eg}[thm]{Example}\n%\n\\newcommand{\\Prf}{\\noindent\\textbf{Proof.\\ }}\n\\newcommand{\\bx}{\\hfill$\\blacksquare$\\medbreak}\n\\newcommand{\\upbx}{\\vspace{-2.5\\baselineskip}\\newline\\hbox{}%\n\\hfill$\\blacksquare$\\newline\\medbreak}\n\\newcommand{\\eqbx}[1]{\\medbreak\\hfill\\(\\displaystyle #1\\)\\bx}\n% for proofs ending in a one line equation\n%      Useful shortforms\n\\newcommand{\\BH}{{\\B(\\H)}}\n\\newcommand{\\bsl}{\\setminus}\n\\newcommand{\\ca}{\\mathrm{C}^*}\n\\newcommand{\\cstar}{\\mathrm{C}^*}\n\\newcommand{\\cenv}{\\mathrm{C}^*_{\\text{env}}}\n\\newcommand{\\rip}{\\rangle}\n\\newcommand{\\ol}{\\overline}\n\\newcommand{\\td}{\\widetilde}\n\\newcommand{\\wh}{\\widehat}\n\\newcommand{\\sot}{\\textsc{sot}}\n\\newcommand{\\wot}{\\textsc{wot}}\n\\newcommand{\\wotclos}[1]{\\ol{#1}^{\\textsc{wot}}}\n\n%      Blackboard bold letters\n\\newcommand{\\bbA}{{\\mathbb{A}}}\n\\newcommand{\\bbB}{{\\mathbb{B}}}\n\\newcommand{\\bbC}{{\\mathbb{C}}}\n\\newcommand{\\bbF}{{\\mathbb{F}}}\n\\newcommand{\\bbI}{{\\mathbb{I}}}\n\\newcommand{\\bbD}{{\\mathbb{D}}}\n\\newcommand{\\bbN}{{\\mathbb{N}}}\n\\newcommand{\\bbQ}{{\\mathbb{Q}}}\n\\newcommand{\\bbR}{{\\mathbb{R}}}\n\\newcommand{\\bbT}{{\\mathbb{T}}}\n\\newcommand{\\bbZ}{{\\mathbb{Z}}}\n\n%      Capital script letters\n  \\newcommand{\\A}{{\\mathcal{A}}}\n  \\newcommand{\\B}{{\\mathcal{B}}}\n  \\newcommand{\\C}{{\\mathcal{C}}}\n  \\newcommand{\\D}{{\\mathcal{D}}}\n  \\newcommand{\\E}{{\\mathcal{E}}}\n  \\newcommand{\\F}{{\\mathcal{F}}}\n  \\newcommand{\\G}{{\\mathcal{G}}}\n\\renewcommand{\\H}{{\\mathcal{H}}}\n  \\newcommand{\\I}{{\\mathcal{I}}}\n  \\newcommand{\\J}{{\\mathcal{J}}}\n  \\newcommand{\\K}{{\\mathcal{K}}}\n\\renewcommand{\\L}{{\\mathcal{L}}}\n  \\newcommand{\\M}{{\\mathcal{M}}}\n  \\newcommand{\\N}{{\\mathcal{N}}}\n\\renewcommand{\\O}{{\\mathcal{O}}}\n\\renewcommand{\\P}{{\\mathcal{P}}}\n  \\newcommand{\\Q}{{\\mathcal{Q}}}\n  \\newcommand{\\R}{{\\mathcal{R}}}\n%\\renewcommand{\\S}{{\\mathcal{S}}}\n  \\newcommand{\\T}{{\\mathcal{T}}}\n  \\newcommand{\\U}{{\\mathcal{U}}}\n  \\newcommand{\\V}{{\\mathcal{V}}}\n  \\newcommand{\\W}{{\\mathcal{W}}}\n  \\newcommand{\\X}{{\\mathcal{X}}}\n  \\newcommand{\\Y}{{\\mathcal{Y}}}\n  \\newcommand{\\Z}{{\\mathcal{Z}}}\n\n%Greek Letters\n\\newcommand{\\eps}{\\varepsilon}\n%\\renewcommand{\\phi}{\\varphi}\n\n%Gothic letters\n\\newcommand{\\fA}{{\\mathfrak{A}}}\n\\newcommand{\\germA}{{\\mathfrak{A}}}\n\\newcommand{\\germB}{{\\mathfrak{B}}}\n\\newcommand{\\fB}{{\\mathfrak{B}}}\n\\newcommand{\\fC}{{\\mathfrak{C}}}\n\\newcommand{\\fD}{{\\mathfrak{D}}}\n\\newcommand{\\fE}{{\\mathfrak{E}}}\n\\newcommand{\\fF}{{\\mathfrak{F}}}\n\\newcommand{\\fG}{{\\mathfrak{G}}}\n\\newcommand{\\fH}{{\\mathfrak{H}}}\n\\newcommand{\\fI}{{\\mathfrak{I}}}\n\\newcommand{\\fJ}{{\\mathfrak{J}}}\n\\newcommand{\\fK}{{\\mathfrak{K}}}\n\\newcommand{\\fL}{{\\mathfrak{L}}}\n\\newcommand{\\fM}{{\\mathfrak{M}}}\n\\newcommand{\\fN}{{\\mathfrak{N}}}\n\\newcommand{\\fO}{{\\mathfrak{O}}}\n\\newcommand{\\fP}{{\\mathfrak{P}}}\n\\newcommand{\\fQ}{{\\mathfrak{Q}}}\n\\newcommand{\\fR}{{\\mathfrak{R}}}\n\\newcommand{\\fS}{{\\mathfrak{S}}}\n\\newcommand{\\fT}{{\\mathfrak{T}}}\n\\newcommand{\\fU}{{\\mathfrak{U}}}\n\\newcommand{\\fV}{{\\mathfrak{V}}}\n\\newcommand{\\fW}{{\\mathfrak{W}}}\n\\newcommand{\\fX}{{\\mathfrak{X}}}\n\\newcommand{\\fY}{{\\mathfrak{Y}}}\n\\newcommand{\\fZ}{{\\mathfrak{Z}}}\n\n%Roman letters for math\n\\newcommand{\\rN}{\\mathrm{N}}\n\n%      Text used in equations\n\\newcommand{\\foral}{\\text{ for all }}\n\\newcommand{\\qand}{\\quad\\text{and}\\quad}\n\\newcommand{\\qif}{\\quad\\text{if}\\quad}\n\\newcommand{\\qfor}{\\quad\\text{for}\\quad}\n\\newcommand{\\qforal}{\\quad\\text{for all}\\quad}\n\\newcommand{\\qforsome}{\\quad\\text{for some}\\quad}\n\\newcommand{\\qwhere}{\\quad\\text{where}\\quad}\n\n%Operators\n\\newcommand{\\ad}{\\operatorname{ad}}\n\\newcommand{\\Alg}{\\operatorname{Alg}}\n\\newcommand{\\alg}{\\operatorname{alg}}\n\\newcommand{\\ball}{\\operatorname{ball}}\n\\newcommand{\\dirlim}{\\varinjlim}\n\\newcommand{\\dist}{\\operatorname{dist}}\n\\newcommand{\\dom}{\\operatorname{Dom}}\n\\newcommand{\\frRep}{\\operatorname{Rep}_{\\operatorname{fr}}}\n\\newcommand{\\Id}{\\operatorname{Id}}\n\\newcommand{\\LL}{\\operatorname{L}}\n\\newcommand{\\Lat}{\\operatorname{Lat}}\n\\newcommand{\\nil}{\\operatorname{nil}}\n\\newcommand{\\PI}{\\operatorname{PI}}\n\\newcommand{\\Prim}{\\operatorname{Prim}}\n\\newcommand{\\rad}{\\operatorname{rad}}\n\\newcommand{\\ran}{\\operatorname{Ran}}\n\\renewcommand{\\dom}{\\operatorname{Dom}}\n\\newcommand{\\rank}{\\operatorname{rank}}\n\\newcommand{\\spn}{\\operatorname{span}}\n\\newcommand{\\sumoplus}{\\operatornamewithlimits{\\sum\\oplus}}\n\\newcommand{\\supr}{\\operatorname{sup}}\n\\newcommand{\\Spec}{\\operatorname{Spec}}\n\\newcommand{\\rep}{\\operatorname{rep}}\n\\newcommand{\\ba}{\\backslash}\n\\newcommand{\\om}{\\omega}\n\\newcommand{\\trace}{\\operatorname{trace}}\n\n\n%Commands specific to this paper\n\\def\\bra#1{\\langle #1|}\n\\def\\ket#1{|#1 \\rangle}\n\\def\\one{{\\mathchoice{\\rm 1\\mskip-4mu l}{\\rm 1\\mskip-4mu l}{\\rm 1\\mskip-4.5mu l}{\\rm\n1\\mskip-5mu l}}}\n\\newcommand{\\fgeeplus}{\\bbF^+\\!(G)}\n\\newcommand{\\fgeeplusnot}{\\bbF_+^+\\!(G)}\n\\newcommand{\\inftree}{\\tau_G}\n\\newcommand{\\Lg}{{\\mathfrak{L}}_G}\n\\newcommand{\\Rg}{{\\mathfrak{R}}_G}\n\\newcommand{\\fixed}{\\B(\\K)^\\Phi}\n\\newcommand{\\sumin}{\\sum_{i=1}^n}\n\\newcommand{\\ai}{A_i}\n\\newcommand{\\si}{S_i}\n\\newcommand{\\aistar}{A_i^*}\n\\newcommand{\\sistar}{S_i^*}\n\\newcommand{\\cp}{\\Phi}\n\\newcommand{\\bofk}{\\B(\\K)}\n\\newcommand{\\bofh}{\\B(\\H)}\n\\newcommand{\\rowt}{(T_e)_{e\\in E(G)}}\n\\newcommand{\\rows}{(S_e)_{e\\in E(G)}}\n\\newcommand{\\rowl}{(L_e)_{e\\in E(G)}}\n\\newcommand{\\fnplus}{{\\bbF}_n^+}\n\\newcommand{\\mulam}{\\nu_{\\lambda,i}}\n\\newcommand{\\nulam}{\\nu_{\\lambda,i}}\n\\newcommand{\\ank}{\\fA (n_k)}\n\\newcommand{\\flgee}{\\fL_G}\n\\newcommand{\\frgee}{\\fR_G}\n\\newcommand{\\alphuw}{\\alpha_w^u}\n\\newcommand{\\alphvw}{\\alpha_w^v}\n\\newcommand{\\fomg}{\\bbF_\\omega(G)}\n\\newcommand{\\fomgk}{\\bbF_{\\omega(G)}^{k}}\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%% end of macros\n%%%%%%%%%%%%%%%%%%%\n\n\\begin{document}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%\n\\title[]{A unified framework for graph algebras and quantum causal histories}\n%\\thanks{}\n%\n%\n\\author[D.W. Kribs]{David~W.~Kribs}\n%\n\\address{Department of Mathematics and Statistics, University of\nGuelph, Guelph, Ontario, Canada  N1G 2W1} \\address{Institute for\nQuantum Computing, University of Waterloo, Waterloo, ON, CANADA\nN2L 3G1} \\address{Perimeter Institute for Theoretical Physics, 31\nCaroline St. N., Waterloo, ON, CANADA N2L 2Y5}\n%\n%\n\\begin{abstract}\nWe present a mathematical framework that unifies the quantum\ncausal history formalism from theoretical high energy physics and\nthe directed graph operator framework from the theory of operator\nalgebras. The approach involves completely positive maps and\ndirected graphs and leads naturally to a new class of operator\nalgebras.\n\\end{abstract}\n\n\\thanks{2000 {\\it  Mathematics Subject Classification.} 46L05, 47L75, 81P68, 83C45.}\n\\thanks{{\\it Key words and phrases.} directed graph, completely positive\nmap, partial isometry, quantum operation,  quantum causal\nhistory.}\n%\\date{November, 2004.}\n\\maketitle\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Introduction}   \\label{S:intro}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\nIn this paper we present a new operator theoretic framework that\nprovides a unified approach for recent studies in theoretical high\nenergy physics and contemporary operator algebra theory. More\nspecifically, this approach involves completely positive maps and\ndirected graphs, and includes the quantum causal history formalism\nfrom recent work towards a quantum theory of gravity on the one\nhand and the graph-operator framework from the theory of directed\ngraph operator algebras on the other. We also define a new class\nof operator algebras that is naturally defined through this\napproach.\n\nThe basic physical properties that a quantum theory of gravity\nmust satisfy motivated F. Markopoulou to invent a formalism called\n``Quantum Causal Histories'' \\cite{HMS,M02,M00C,M00B,M00A}. A\nsecondary goal of this paper is to introduce this formalism to the\nbroader mathematical community. Fundamental examples include\ncausal evolutions of spin networks \\cite{Gupta,MS97} and quantum\ncomputers \\cite{M00C}. The basic definitions have been refined\nthrough a series of papers and now a clean mathematical definition\nis emerging \\cite{HMS}. Mathematically, and somewhat roughly\nspeaking at this point, a {\\it quantum causal history} (QCH) is\ngiven by a directed graph with a finite-dimensional Hilbert space\nfor each vertex and a quantum operation associated with each\ndirected edge. The vertex spaces correspond to events, or\nobservables, within a local history and the quantum operations\nindicate causal links between pairs of related events. As\ndescribed below, the QCH framework incorporates further structure\nmotivated by the characterization of evolution within quantum\nsystems.\n\nOn the other hand, Cuntz and Krieger \\cite{CK} were motivated by a\nproblem in dynamical systems to initiate the study of operator\nalgebras associated with directed graphs. Over the past two\ndecades the study of directed graph operator algebras and related\ntopics has taken on a life of its own and now, it is fair to say,\nplays a central role in the modern theory of operator algebras. We\nmention the articles \\cite{BP} -- \\cite{Spi} as entrance points\ninto the extensive literature on the subject.\n\nIn $\\S~2$ we recall some basic properties of completely positive\nmaps and quantum operations. We define the ``CP -- directed graph\nframework'' and associated $\\ca$-algebras in $\\S~3$, and show how\ngraph algebras fit into the framework. In $\\S~4$ we discuss in\nsome detail the QCH formalism, draw a connection with quantum\ncomputing, and prove a theorem for the QCH $\\ca$-algebras.\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Completely Positive Maps}   \\label{S:cpmaps}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nGiven a Hilbert space $\\H$ we let $\\B(\\H)$ be the set of bounded\noperators that act on $\\H$. A {\\it completely positive} (CP) map\nis a linear map $\\Phi : \\B(\\H_1)\\rightarrow\\B(\\H_2)$ such that the\n``ampliated'' maps\n\\[\n \\one_k \\otimes \\Phi : \\M_k \\otimes \\B(\\H_1) \\longrightarrow\n\\M_k \\otimes \\B(\\H_2)\n\\]\nare positive for $k\\geq 1$. (Here $\\M_k$ denotes the set of\n$k\\times k$ complex matrices and $\\one_k$ denotes the identity\noperator, the ``maximally mixed state'', inside $\\M_k$.) For basic\nmathematical properties of CP maps see \\cite{Paulsentext2} and\nphysical motivations see \\cite{Kraustext}.\n\nA fundamental technical device in the study of CP maps is the {\\it\noperator-sum representation} given by the theorem of Choi\n\\cite{Choi} and Kraus \\cite{Kraus}. For every CP map $\\Phi$ on\nfinite-dimensional space, there is a set of {\\it noise operators}\n(or {\\it errors}) $\\{A_i\\}\\subseteq \\B(\\H_1,\\H_2)$ such that\n\\begin{eqnarray}\\label{opsum}\n\\Phi(\\rho) &=& \\sum_i A_i\\, \\rho\\, A_i^* \\quad\\forall\n\\rho\\in\\B(\\H_1).\n\\end{eqnarray}\nThe map is {\\it unital} if also $\\sum_i A_i A_i^* = \\one_{\\H_2}$.\nIt is always possible to choose a family of noise operators with\ncardinality at most $\\dim(\\H_1)\\dim(\\H_2)$. On infinite\ndimensional space not all CP maps have such a form, and when they\ndo the sum in (\\ref{opsum}) converges in the strong operator\ntopology. For brevity, we assume all the CP maps considered here\nhave a representation as in (\\ref{opsum}).\n%The family $\\{A_i\\}$ can be chosen with cardinality\n%$|\\{A_i\\}|\\leq \\dim(\\H_1) \\dim(\\H_2)$ and is of course non-unique.\n%(However, the algebra generated by the $A_i$ is strictly an\n%artifact of $\\Phi$, it is independent of the choice of noise\n%operators \\cite{Kchannel}.)\n\nA {\\it quantum operation} (or {\\it quantum evolution}, or {\\it\nquantum channel}) is a CP map $\\Phi : \\B(\\H_1)\\rightarrow\\B(\\H_2)$\nthat is also trace preserving. When $\\Phi$ is represented as in\n(\\ref{opsum}), trace preservation is equivalent to the identity\n\\begin{eqnarray}\\label{tracepreserve}\n \\sum_i A_i^*  A_i = \\one_{\\H_1}.\n\\end{eqnarray}\nThus, a quantum operation $\\Phi$ is a map that satisfies\n(\\ref{opsum}) and (\\ref{tracepreserve}) for some set of operators\n$\\{A_i\\}$. Equivalently, a quantum operation is a CP map such that\nits associated {\\it dual map}, denoted by $\\Phi^\\dagger:\n\\B(\\H_2)\\rightarrow\\B(\\H_1)$, is unital. (Recall that the dual map\nfor a map $\\Phi$ is defined via the equation\n$\\trace(\\rho\\,\\Phi^\\dagger(\\sigma)) =\n\\trace(\\Phi(\\rho)\\,\\sigma)$.)\n\nThe ideal physical examples of quantum operations are {\\it unitary\nmaps}  as they characterize evolution of states within a closed\nquantum system. Such a map is of the form $\\Phi(\\rho) = U \\rho\\,\nU^*$ for some unitary operator $U$. When evolution occurs in an\nopen system (i.e., when the system of interest is exposed to an\nexternal environment) quantum operations have the more general\nform given by (\\ref{opsum}) and (\\ref{tracepreserve}). See\n\\cite{Ksurvey} for further discussions and references.\n\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{The CP -- Directed Graph Framework}   \\label{S:cpgraph}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\nLet $E=(E^0,E^1,r,s)$ be a (countable) directed graph with\nvertices $x\\in E^0$, directed edges $e\\in E^1$ and range and\nsource maps $r,s: E^1\\rightarrow E^0$ giving the initial ($s(e)$)\nand final ($r(e)$) vertices of an edge $e$.  When $e\\in E^1$\nsatisfies $s(e)=x$ and $r(e)=y$, we shall write $e=(x,y)$.\n\nSuppose we have a Hilbert space $\\{\\H(x):x\\in E^0\\}$ for each\nvertex and a family of CP maps $\\Psi=\\{\\Phi_e:e\\in E^1\\}$ with\ndomains and ranges that satisfy\n\\[\n(\\dagger)\\left\\{\n\\begin{array}{lll}\n(i) & \\dom(\\Phi_e) = \\B(\\H(s(e))) & \\mbox{$\\forall\\, e \\in E^1$} \\\\\n(ii) & \\ran(\\Phi_e) \\subseteq \\B(\\H(r(e))) & \\mbox{$\\forall\\, e\\in\nE^1$}\n\\end{array}\\right.\n\\]\n\nGiven such a family of spaces and maps, define the Hilbert space\n$\\H = \\oplus_{x\\in E^0} \\H(x)$ and let $P_x$ be the projection of\n$\\H$ onto $\\H(x)$.\n\n\\begin{defn}\nGiven a directed graph $E$, let $\\{\\H(x):x\\in E^0\\}$ be Hilbert\nspaces and let $\\Psi=\\{\\Phi_e: e\\in E^1\\}$ be a family of CP maps\nthat satisfy $(\\dagger)$. Suppose $\\Phi_e = \\{A_{e,i}:i\\in\\I_e\\}$\nis an operator-sum representation of $\\Phi_e$ for each $e\\in E^1$.\nWe can naturally regard the $A_{e,i}$ as operators acting on $\\H$.\nDefine $\\fA_\\Psi$ to be the $\\ca$-algebra generated by all\noperators $A_{e,i}$ and vertex projections $P_x$; so that,\n\\[\n\\fA_\\Psi = \\ca \\big( \\{ P_x, A_{e,i} : x\\in E^0,\\, e\\in E^1, \\,\ni\\in\\I_e\\}\\big).\n\\]\n\\end{defn}\n\nThe choice of noise operators that represent a given CP map in\n(\\ref{opsum}) is of course not unique. However, as our notation\nsuggests the algebras $\\fA_\\Psi$ are independent of these choices.\n\n\\begin{prop}\nLet $E$ be a directed graph and let $\\Psi= \\{\\Phi_e:e\\in E^1\\}$ be\na family of CP maps that satisfy $(\\dagger)$. Then the algebra\n$\\fA_\\Psi$ is independent of the choice of operators $\\{A_{e,i}\\}$\nthat represent the maps $\\Phi_e$ as in (\\ref{opsum}).\n\\end{prop}\n\n\\Prf Suppose that $\\{A_{e,i}\\}_i$ and $\\{A_{e,j}^\\prime\\}_j$\nrepresent $\\Phi_e$ via  equation (\\ref{opsum}). By possibly\nincluding zero operators we may assume the cardinality of these\ntwo sets is the same. Then from the structure theory for CP maps,\nthere is a scalar unitary matrix $U=(u_{ij})$ such that\n\\[\nA_{e,i} = \\sum_j u_{ij} A_{e,j}^\\prime \\quad \\forall i.\n\\]\nIt follows that the algebras generated by\n$\\{P_x,A_{e,i}\\}_{x,e,i}$ and $\\{P_x,A_{e,j}^\\prime\\}_{x,e,j}$\ncoincide, and the result follows.\n \\bx\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Graph Algebras}\\label{sS:graphalg}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nWe now discuss one of the motivating special cases for this\nframework. Let $E=(E^0,E^1,r,s)$ be a directed graph. Consider\nfamilies of operators $\\{P_x,S_e: x\\in E^0, e\\in E^1\\}$, where the\n$P_x$ are projections and the $S_e$ are partial isometries (or\nequivalently, unitary operators restricted to a subspace), that\nact on the same Hilbert space and satisfy:\n\\[\n(\\ddagger)\\left\\{\n\\begin{array}{lll}\n(i) & S_{e}^{*}S_e = P_{s(e)} & \\mbox{$\\forall\\, e \\in E^1$} \\\\\n(ii) & S_{e}S_e^* \\leq P_{r(e)} & \\mbox{$\\forall\\, e\\in E^1$}\n\\end{array}\\right.\n\\]\nThen the structure of $E$ determines the relations satisfied by\n$\\{P_x,S_e\\}$ in the sense that the initial projection for each\n$S_e$ is equal to the projection for the source vertex of $e$ and\nthe range projection for each $S_e$ is supported on the projection\nfor the range vertex of $e$.\n\nThe relations $(\\ddagger)$ provide the fundamental base case for\ninvestigations into operator algebras associated with directed\ngraphs. In the most general context, a {\\it graph algebra} is an\noperator algebra generated by a family $\\{S_e,P_x\\}$. There are a\nnumber of refinements and generalizations of the formulation\n$(\\ddagger)$. In many instances the $S_e$ are assumed to have\nmutually orthogonal ranges. The projections $P_x$ are typically\nassumed to have mutually orthogonal ranges as well, or sometimes\njust mutually commuting ranges. There are also topological graph\ngeneralizations wherein the vertices and edges are locally compact\nspaces and the range and source maps are continuous maps. However,\nin every setting the motivating case is the same: A Hilbert space\n$\\H(x)$ associated with every vertex $x$ in $E$ and for every\ndirected edge $e=(x,y)$ a partial isometry $S_e$ that maps from\n$\\H(x)$ to $\\H(y)$.\n\nIf $\\{S_e,P_x\\}$ satisfy $(\\ddagger)$, observe that for each\n$e=(x,y)$ the operator $S_e$ defines a unitary from\n$\\H(x)=P_{x}\\H$ into $\\H(y)=P_{y}\\H$ and a unitary CP map\n$\\Phi_e:\\B(\\H(x))\\rightarrow\\B(\\H(y))$ via\n\\[\n\\Phi_e(\\rho) = S_e^\\prime\\, \\rho\\, (S_e^\\prime)^* \\qwhere\nS_e^\\prime = S_e|_{\\H(x)}.\n\\]\nThus the corresponding algebra $\\fA_\\Psi$ defines a graph algebra,\nand so graph algebras form a subclass of the algebras $\\fA_\\Psi$.\n\n\n\n\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{The Quantum Causal History Formalism}   \\label{S:qch}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\nThe mathematical formalism for QCH's has undergone a series of\nrefinements since being introduced in \\cite{M00B}. The\npresentation below is most closely related to the recent\nformulation of Hawkins, Markopoulou and Sahlmann \\cite{HMS}. The\nnomenclature we use is slightly different than \\cite{HMS}, we do\nthis to mesh with the graph algebra terminology. We shall focus on\nthe mathematical aspects and touch on the physical motivations for\nvarious constraints.\n\nTo define a QCH then, we begin with a graph $E=(E^0,E^1,r,s)$,\nwhich may also be interpreted as a partial order when there are no\nloops. This graph represents a causal set wherein the vertices\ncorrespond to a set of local events in the universe and vertices\nlinked by directed edges indicate causal relations between events.\nFrom the postulates of quantum mechanics, events are represented\nby density operators on Hilbert space. Recent work in string\ntheory and loop quantum gravity (see \\cite{M02}) suggests that any\nfinite region of space should contain a finite amount of\ninformation. Thus, each of the event spaces is assumed to be\nfinite-dimensional. Since causality can be interpreted as\ntransferring information from one event to another and because, by\ndefinition, a QCH describes local causality at the quantum level,\na causal relation given by a directed edge $e=(x,y)\\in E^1$\ncorresponds to a quantum operation $\\Phi(x,y) : \\B(\\H(x))\n\\rightarrow \\B(\\H(y))$ between event spaces.\n\nThus, at its mathematical core, a QCH consists of a directed\ngraph, with a finite-dimensional Hilbert space for each vertex,\nand a quantum operation for each directed edge. There are further\nconstraints within a QCH and we discuss them now briefly.\n\nFirst some terminology. Given $x,y\\in E^0$ write $x\\leq y$ when\n$x$ precedes $y$ as an event. In this case there is a\nfuture-directed curve from $x$ to $y$ and this is represented by a\ndirected edge $e=(x,y)\\in E^1$. If $x\\leq y$ or $y\\leq x$ then $x$\nand $y$ are {\\it related} and otherwise they are {\\it spacelike\nseparated} and we use $x\\sim y$ to denote this.  A path in $E$\ncorresponds to a {\\it future-directed path} through the events in\nthe history. Such a path is {\\it future (past) inextendible} if\nthere is no event in $E$ which is in the future (past) of the\nentire path. Loops in $E$ correspond to {\\it closed timelike\ncurves}. From the finiteness assumption discussed above, $E$ is\n{\\it locally finite} in the sense that for any $x,y\\in E^0$ there\nare at most finitely many $z\\in E^0$ such that $x\\leq z \\leq y$.\nGiven $x,y\\in E^0$, there is also  no generality lost in assuming\nthere is at most one edge $e=(x,y)$ in $E$ from $x$ to $y$. (If\n$s(e)=x=s(f)$ and $r(e)=y=r(f)$ then the operations associated\nwith these edges could be combined to form a single operation that\nencodes the relevant causal structure from event $x$ to event\n$y$.)\n\nAn {\\it acausal set} $\\xi\\subseteq E^0$ is defined by the property\nthat $x\\sim y$ whenever $x,y\\in\\xi$. Such a set is a {\\it complete\nfuture} for an event $x$ if $\\xi$ intersects any future\ninextendible future-directed path that starts at $x$. A {\\it\ncomplete past} is defined analogously. The composite state space\nfor $x\\sim y$ (the physical existence of which is guaranteed by\nquantum mechanics) is $\\H(\\{x,y\\}) = \\H(x) \\otimes \\H(y)$ and more\ngenerally $\\H(\\xi) = \\otimes_{x\\in\\xi} \\H(x)$. For $x\\in E^0$\nwrite $\\A(x)$ for the matrix algebra $\\B(\\H(x))$ and similarly\ndefine $\\A(\\xi)=\\otimes_{x\\in\\xi}\\A(x)$ for a set $\\xi\\subseteq\nE^0$. Given an acausal set $\\xi$ and an event $x\\in \\xi$, there is\na natural unital embedding $\\iota_x: \\A(x)\\hookrightarrow\\A(\\xi)$\nand we shall write $\\A(x)\\subseteq\\A(\\xi)$.\n\nIf $\\xi$ and $\\zeta$ are acausal sets such that $\\xi$ is a\ncomplete past for $\\zeta$ and $\\zeta$ is a complete future for\n$\\xi$, then we write $\\xi \\preceq \\zeta$ and say that\n$(\\xi,\\zeta)$ form a {\\it complete pair}. Such a pair represents\nan evolution in a closed quantum system, hence woven into the\nfabric of the QCH there should be a unitary operator\n$U(\\xi,\\zeta): \\H(\\xi) \\rightarrow \\H(\\zeta)$. Such an operator\ndetermines a unitary map (an isomorphism) $\\Phi(\\xi,\\zeta):\n\\A(\\xi)\\rightarrow\\A(\\zeta)$ via\n\\[\n\\Phi(\\xi,\\zeta)(\\rho) = U(\\xi,\\zeta)\\, \\rho\\, U(\\xi,\\zeta)^*\n\\quad\\forall \\,\\rho\\in\\A(\\xi).\n\\]\nNote the restriction of $\\Phi(\\xi,\\zeta)$ (respectively\n$\\Phi(\\xi,\\zeta)^\\dagger$) to $\\A(x)\\subseteq\\A(\\xi)$ for\n$x\\in\\xi$ (respectively $\\A(z)\\subseteq\\A(\\zeta)$ for $z\\in\\zeta$)\nis a $\\ast$-homomorphism. This gives the structure of a QCH at the\nglobal level, but does not indicate how the isomorphisms\n$\\Phi(\\xi,\\zeta)$ should depend on the individual causal relations\nbetween events in $\\xi$ and $\\zeta$. This is the role played by\nthe operations $\\Phi(x,y)$ on individual edges.\n\nWe now give a precise mathematical definition of a QCH. We note\nthat the maps in the definition below have directions reversed\nfrom the presentation in \\cite{HMS}. Here we take the dual\napproach so the ``directions'' of the maps are in line with the\ngraph structure. Recall that if $\\iota_A: \\A_1\\rightarrow\\A_2$ and\n$\\iota_B: \\B_1\\rightarrow\\B_2$ are $\\ast$-monomorphisms and $\\Psi:\n\\A_2\\rightarrow\\B_2$ is a map, then the {\\it reduction} of $\\Psi$\nto $\\A_1\\mapsto\\B_1$ is the map $\\Phi = \\iota_B^\\dagger \\circ \\Psi\n\\circ i_A$.\n\n\\begin{defn}\nA {\\it quantum causal history} consists of a directed graph $E$\nwith a Hilbert space $\\{\\H(x): x\\in E^0\\}$ for each event and a\nquantum operation $\\Phi (x,y) : \\A(x)\\rightarrow\\A(y)$ for each\npair of related events $x\\leq y$ such that the following axioms\nare satisfied:\n\n$(i)$ (Extension) For all $y\\in E^0$ and $\\zeta\\subseteq E^0$ a\ncomplete future of $y$, there is a homomorphism $\\Phi_F(y,\\zeta) :\n\\A(y)\\rightarrow\\A(\\zeta)$ such that $\\Phi_F(y,\\zeta)^\\dagger$ is\na quantum operation and for all $z\\in\\zeta$, the reduction of\n$\\Phi_F(y,\\zeta)^\\dagger$ to $\\A(z)$ is $\\Phi(y,z)^\\dagger$.\nLikewise, for all $y\\in E^0$ and $\\xi\\subseteq E^0$ a complete\npast of $y$, there is a quantum operation\n$\\Phi_P(\\xi,y):\\A(\\xi)\\rightarrow\\A(y)$ such that\n$\\Phi_P(\\xi,y)^\\dagger$ is a homomorphism and for all $x\\in\\xi$\nthe reduction of $\\Phi_P(\\xi,y)^\\dagger$ to $\\A(x)$ is\n$\\Phi(x,y)^\\dagger$.\n\n$(ii)$ (Spacelike Commutativity)  If $x\\sim y\\in E^0$ and\n$\\zeta\\subseteq E^0$ is a complete future of $x$ and $y$, then the\nimages of $\\Phi_F(x,\\zeta)$ and $\\Phi_F(y,\\zeta)$ commute inside\n$\\A(\\zeta)$.  Likewise, if $y\\sim z \\in E^0$ and $\\xi\\subseteq\nE^0$ is a complete past of $y$ and $z$, then the images of\n$\\Phi_P(\\xi,y)^\\dagger$ and $\\Phi_P(\\xi,z)^\\dagger$ commute inside\n$\\A(\\xi)$.\n\n$(iii)$ (Composition) If $\\zeta\\subseteq E^0$ is a complete future\nof $x$ and a complete past of $y$, then $\\Phi(x,y) =\n\\Phi_P(\\zeta,y)\\circ\\Phi_F(x,\\zeta)$.\n\\end{defn}\n\n%\\begin{rem}\n%With the QCH formalism and the DGO framework in hand, the overlap\n%between the two is now evident. Each partial isometry $S_e$ in a\n%DGO family acts on  $\\H = \\oplus_{x\\in E^0} \\H(x)$, but it only\n%acts non-trivially on the vertex space $\\H(s(e))$ where it acts as\n%a unitary from $\\H(s(e))$ into $\\H(r(e))$. As such, $S_e$\n%determines a unitary map with initial observable space $\\H(s(e))$\n%and final observable space supported on $\\H(r(e))$. Thus, when a\n%DGO family satisfies the further constraints discussed above, the\n%resulting construct may be interpreted as a QCH. Hence certain DGO\n%families define QCH's and vice versa. It is conceivable that the\n%overlap could expand, and further connections come to light, as\n%both the QCH and DGO frameworks undergo refinements.\n%\\end{rem}\n\nIf $\\xi\\preceq\\zeta$ form a complete pair within a given QCH, it\nis proved in \\cite{HMS} that there is a unique unitary map\n$\\Phi(\\xi,\\zeta):\\A(\\xi)\\rightarrow\\A(\\zeta)$ such that the\nreduction of $\\Phi(\\xi,\\zeta)$ to $\\A(x)\\mapsto\\A(y)$  is\n$\\Phi(x,y)$ for all $x\\in\\xi$ and $y\\in\\zeta$. Thus the\nisomorphisms $\\Phi(\\xi,\\zeta)$ discussed above may be built up\nfrom the individual edge maps $\\Phi(x,y)$ and hence the edge maps\nare the fundamental building blocks for a QCH.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{eg}\\label{S:qcomp}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n({\\bf Quantum Computers}) As discussed in \\cite{M00C}, the basic\nmodel for a quantum computer fits into the QCH formalism.\nSpecifically, each quantum algorithm may be interpreted as a QCH\nvia its ``circuit-gate'' presentation. (See \\cite{Ksurvey} for a\nbrief mathematical introduction to quantum algorithms and\nreferences.) The QCH for a given algorithm has vertex spaces all\nequal to $\\bbC^2$. The directed edges correspond to the choice of\nunitary gates within the algorithm and the vertex spaces encode\nthe intermediate states of the quantum bits of information (the\n`qubits'). The structure of the associated directed graph is the\nsame as the circuit-gate diagram, with the circuits labelled as\nvertices and the gates labelled as directed edges.\n\\end{eg}\n\nWe finish by proving that the algebras $\\fA_\\Psi$ associated with\nQCH's are familiar objects from operator theory. For basic\nproperties of AF-algebras we point the reader to the text\n\\cite{byeg}.\n\n\\begin{thm}\\label{qchopalg}\nLet $\\fA_\\Psi$ be the $\\ca$-algebra associated with a given\nquantum causal history. Then $\\fA_\\Psi$ is an AF-algebra.\n\\end{thm}\n\n\\Prf It is enough to prove that every finite set of elements of\n$\\fA_\\Psi$ can be approximated by elements lying in a\nfinite-dimensional subalgebra. But elements of the form $A =\nA_1\\cdots A_n$, where each $A_k=A_{e,i}$ or $A_k = A_{e,i}^*$ for\nsome $e$ and $i$, span a dense subspace of $\\fA_\\Psi$. (Note that\nthe vertex projections are obtained via equation\n(\\ref{tracepreserve}).) Hence it is enough to show that each\nfinite set of such elements lies in a finite-dimensional\nsubalgebra. Suppose $\\F$ is such a set. Note that each $A_{e,i}$\nbelongs to $\\B(\\H(x),\\H(y))$ for some $x,y\\in E^0$, and so the\nsame is true for every $A_{e,i}^*$ and all elements $A\\in\\F$.\nThus, as $\\dim\\H(x)<\\infty$ for all $x\\in E^0$, it follows that\nthe algebra generated by $\\F$ is a finite-dimensional algebra\nwhich is also a subalgebra of $\\fA_\\Psi$, and the result follows.\n\\bx\n\n\\begin{rem}\nWhile graph algebras and quantum causal histories provided the\ninitial impetus for the CP -- directed graph framework presented\nhere, it is evident that this structure admits other\npossibilities. Indeed, there are many CP maps that are neither\nunitary maps nor quantum operations, and presumably the\n$\\ca$-algebras $\\fA_\\Psi$ would go beyond the graph algebra and\nQCH subclasses in general. We have also not considered here the\nvarious possibilities for non-selfadjoint algebras defined by this\nframework. We plan to undertake investigations of these algebras\nelsewhere and hope this paper motivates others to do the same.\n\\end{rem}\n\n\n\n\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\\section{Conclusion}   \\label{S:conclusion}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n%We have illustrated a connection between the quantum causal\n%history formalism from quantum gravity and the directed graph\n%operator framework from operator algebras. This motivates a number\n%of new problems and possible avenues of research. For instance,\n%this connection begs the question as to whether there is a\n%physical interpretation of graph algebras within a quantum theory\n%of gravity. On the other hand, a natural mathematical\n%generalization of the graph-operator framework would be to allow\n%quantum operations (or even completely positive maps) instead of\n%only partial isometries on the directed edges and to consider the\n%corresponding operator algebras. Further, Example~\\ref{S:qcomp}\n%suggests an enticing link between graph algebras and quantum\n%computing. We plan to undertake these investigations elsewhere and\n%we hope this paper motivates others to do the same.\n\n\n\n\n\n\n\n\\vspace{0.05in}\n\n\n{\\noindent}{\\it Acknowledgements.}\n%I am grateful to the referee\n%for helpful suggestions.\nI would like to thank Fotini Markopoulou\nfor enlightening conversations and Eli Hawkins for helpful\ncomments on an early draft. I am also grateful to colleagues at\nthe Institute for Quantum Computing and the Perimeter Institute\nfor interesting discussions. This work was partially supported by\nan NSERC grant.\n\n\n\\begin{thebibliography}{99}\n\n\n\\bibitem{HMS} E. Hawkins, F. Markopoulou, H. Sahlmann,\n\\textit{Evolution in quantum causal histories}, Class. Quant.\nGrav. {\\bf 20} (2003), 3839.\n\n\\bibitem{M02} F. Markopoulou,\n\\textit{Planck-scale models of the universe}, invited contribution\nto ``Science \\& Ultimate Reality: From Quantum to Cosmos\n(Explorations Celebrating the Vision of John Archibald Wheeler,''\narxiv.org/gr-qc/0210086.\n\n\\bibitem{M00C} F. Markopoulou,\n\\textit{An insider's guide to quantum causal histories}, Nucl.\nPhys. Proc. Suppl. {\\bf 88} (2000), 308-313.\n\n\\bibitem{M00B} F. Markopoulou,\n\\textit{Quantum causal histories}, Class. Quant. Grav. {\\bf 17}\n(2000), 2059-2072.\n\n\\bibitem{M00A} F. Markopoulou,\n\\textit{The internal description of a causal set: What the\nuniverse looks like from the inside}, Commun. Math. Phys. {\\bf\n211} (2000), 559-583.\n\n\\bibitem{Gupta} S. Gupta,\n\\textit{Causality in spin foam models}, Phys. Rev. D {\\bf 61}\n(2000), 064014.\n\n\\bibitem{MS98} F. Markopoulou, L. Smolin,\n\\textit{Quantum geometry with intrinsic local causality}, Phys.\nRev. D {\\bf 58} (1998), 084032.\n\n\\bibitem{MS97} F. Markopoulou, L. Smolin,\n\\textit{Causal evolution of spin networks}, Nucl. Phys. B {\\bf\n508} (1997), 409-430.\n\n\\bibitem{CK} J. Cuntz, W. Krieger,\n\\textit{A class of $\\ca$-algebras and topological Markov chains,}\nInvent. Math. \\textbf{56} (1980), 251-268.\n\n\\bibitem{BP} T. Bates, D. Pask,\n\\textit{Flow equivalence of graph algebras}, Ergod. Theory \\& Dyn.\nSys. {\\bf 24} (2004), 367-382.\n\n\\bibitem{BPRS} T. Bates, D. Pask, I. Raeburn, W. Szymanski,\n\\textit{The $\\ca$-algebras of row-finite graphs}, New York J.\nMath. {\\bf 6} (2000), 307-324.\n\n\\bibitem{BJKR} O. Bratteli, P.E.T. Jorgensen, K.H. Kim, F. Roush,\n\\textit{Decidability of the isomorphism problem for stationary\nAF-algebras}, Ergod. Theory \\& Dyn. Sys. {\\bf 21} (2001),\n1625-1655.\n\n\\bibitem{Bre} B. Brenken,\n\\textit{$\\ca$-algebras of infinite graphs and Cuntz-Krieger\nalgebras}, Can. Math. Bull. {\\bf 45} (2002), 321-336.\n\n\\bibitem{DK} K.R. Davidson, E. Katsoulis,\n\\textit{Nest representations of directed graph algebras},\narxiv.org/math.OA/0410449.\n\n\\bibitem{DKP} K.R. Davidson, E. Katsoulis, D.R. Pitts,\n\\textit{The structure of free semigroup algebras}, J. Reine Angew.\nMath. {\\bf 533} (2001), 99-125.\n\n\\bibitem{Dun} B. Duncan,\n\\textit{Universal operator algebras of directed graphs}, Houston\nJ. Math., to appear.\n\n\\bibitem{ELQ} R. Exel, M. Laca, J. Quigg,\n\\textit{Partial dynamical systems and $\\ca$-algebras generated by\npartial isometries}, J. Operator Theory {\\bf 47} (2002), 169-186.\n\n\\bibitem{EL} R. Exel, M. Laca,\n\\textit{Cuntz-Krieger algebras for infinite matrices}, J. Reine\nAngew. Math. \\textbf{512} (1999), 119-172.\n\n\\bibitem{FR} N. Fowler, I. Raeburn,\n\\textit{The Toeplitz algebra of a Hilbert bimodule}, Indiana Univ.\nMath. J. \\textbf{48} (1999), 155--181.\n\n%\\bibitem{FMR} N. Fowler, P. Muhly, I. Raeburn,\n%\\textit{Representations of Cuntz-Pimsner algebras}, Indiana Univ.\n%Math. J. \\textbf{52}, 2003, 569-605.\n\n\\bibitem{HPP} A. Hopenwasser, J.R. Peters, S.C. Power,\n\\textit{Subalgebras of graph $\\ca$-algebras},\narxiv.org/math.OA/0409075.\n\n\\bibitem{aHR} A. an Huef, I. Raeburn,\n\\textit{The ideal structure of Cuntz-Krieger algebras}, Ergod.\nTheory \\& Dyn. Sys. {\\bf 17} (1997), 611-624.\n\n\\bibitem{JP} F. Jaeck, S.C. Power,\n\\textit{Hyper-reflexivity of free semigroupoid algebras},\narxiv.org/math.OA/0311201.\n\n\\bibitem{JK2} M.T. Jury, D.W. Kribs,\n\\textit{Partially isometric dilations of noncommuting $n$-tuples\nof operators}, Proc. Amer. Math. Soc. {\\bf 133} (2005), 213-222.\n\n%\\bibitem{JK1} M.T. Jury, D.W. Kribs,\n%\\textit{Ideal structure in free semigroupoid algebras from\n%directed graphs}, J. Operator Theory, to appear.\n\n\\bibitem{KQR} S. Kaliszewski, J. Quigg, I. Raeburn,\n\\textit{Skew products and crossed products by coactions}, J.\nOperator Theory \\textbf{46} (2001), 411-433.\n\n\\bibitem{KK} E. Katsoulis, D.W. Kribs,\n\\textit{Isomorphisms of algebras associated with directed graphs},\nMath. Ann. {\\bf 330} (2004), 709-728.\n\n\\bibitem{Kat} T. Katsura,\n\\textit{A class of $\\ca$-algebras generalizing both graph algebras\nand homeomorphism $\\ca$-algebras. I. Fundamental results}, Trans.\nAmer. Math. Soc. {\\bf 356} (2004), 4287-4322.\n\n\\bibitem{KS} D.W. Kribs, B. Solel,\n\\textit{A class of limit algebras associated with directed\ngraphs}, arxiv.org/math.OA/0411379.\n\n\\bibitem{KP04} D.W. Kribs, S.C. Power,\n\\textit{The $H^\\infty$ algebras of higher rank graphs},\narxiv.org/math.OA/0409432.\n\n\\bibitem{KP} D.W. Kribs, S.C. Power,\n\\textit{Free semigroupoid algebras}, J. Ramanujan Math. Soc. {\\bf\n19} (2004), 117-159.\n\n%\\bibitem{KP2} D.W. Kribs, S.C. Power,\n%\\textit{Partly free algebras}, Operator Theory: Advances and\n%Applications, Birkhauser-Verlag Basel/Switzerland, {\\bf 149}\n%(2004), 381-393.\n\n%\\bibitem{Kchannel} D.W. Kribs,\n%\\textit{Quantum channels, wavelets, dilations, and representations\n%of $\\O_n$}, Proc. Edin. Math. Soc., {\\bf 46} (2003), 421-433.\n\n%\\bibitem{KPR} A. Kumjian, D. Pask, I. Raeburn,\n%\\textit{Cuntz-Krieger algebras of directed graphs},\n%Pacific J. Math. \\textbf{184}, 1998, 161--174.\n\n\\bibitem{KumP1}  A. Kumjian, D. Pask,\n\\textit{Higher rank graph $\\ca$-algebras}, New York J. Math.\n\\textbf{6} (2000), 1-20.\n\n\\bibitem{KumP2}  A. Kumjian, D. Pask, I. Raeburn, J. Renault,\n\\textit{Graphs, groupoids, and Cuntz-Krieger algebras}, J. Funct.\nAnal. \\textbf{144} (1997), 505--541.\n\n\n\n\n\n%\\bibitem{Mu} P.S. Muhly,\n%\\textit{A finite dimensional introduction to operator algebra},\n%A. Katavolos (ed.), Operator Algebras and\n%Application, Kluwer Academic Publishers, 1997, 313--354.\n\n\\bibitem{MT} P.S. Muhly, M. Tomforde, \\textit{Topological\nquivers}, arxiv.org/math.OA/0312109.\n\n\\bibitem{MS1} P.S. Muhly, B. Solel,\n\\textit{Tensor algebras, induced representations, and the Wold\ndecomposition}, Can. J. Math. {\\bf 51} (1999), 850--880.\n\n\\bibitem{MS2} P.S. Muhly, B. Solel,\n\\textit{Tensor algebras over $\\ca$-correspondences:\nrepresentations, dilations and $\\ca$-envelopes} J. Funct. Anal.\n\\textbf{158} (1998), 389--457.\n\n%\\bibitem{Pim}M. Pimsner,\n%\\textit{A class of $C\\sp *$-algebras generalizing both\n%Cuntz-Krieger algebras and crossed products by $\\bbZ$}, Free\n%probability theory (Waterloo, ON, 1995), 189--212, Fields Inst.\n%Commun., \\textbf{12}, Amer. Math. Soc., Providence, RI, 1997.\n\n\\bibitem{Rcbms} I. Raeburn,\nCBMS conference on `graph $\\ca$-algebras' notes, in preparation,\n2004.\n\n\\bibitem{RST} I. Raeburn, A. Sims, T. Yeend,\n\\textit{Higher-rank graphs and their $\\ca$-algebras}, Proc.\nEdinburgh Math. Soc. {\\bf 46} (2003), 99-115.\n\n%\\bibitem{Sol} B. Solel,\n%\\textit{You can see the arrows in a quiver operator algebra},\n%e-print arxiv math.OA/0309420, preprint, 2003.\n\n\\bibitem{Spi} J. Spielberg,\n\\textit{A functorial approach to the $\\ca$-algebras of a graph},\nInternat. J. Math. {\\bf 13} (2002), 245-277.\n\n\n\\bibitem{Paulsentext2} V. Paulsen,\n\\textit{Completely bounded maps and operator algebras,} Cambridge\nUniversity Press, Cambridge, United Kingdom, 2002.\n\n\\bibitem{Kraustext} K. Kraus,\n\\textit{States, Effects and Operations: Fundamental Notions of\nQuantum Theory,} Lecture Notes in Physics, vol. 190, Berlin:\nSpringer-Verlag, 1983.\n\n\\bibitem{Choi} M.D. Choi,\n\\textit{Completely positive linear maps on complex matrices,} Lin.\n\\ Alg.\\ Appl. \\ \\textbf{10} (1975), 285-290.\n\n\\bibitem{Kraus} K. Kraus,\n\\textit{General state changes in quantum theory,} Ann. \\ Physics \\\n\\textbf{64} (1971), 311-335.\n\n\\bibitem{Ksurvey} D.W. Kribs,\n\\textit{A quantum computing primer for operator theorists}, Lin.\nAlg. Appl., to appear.\n\n\\bibitem{byeg} K.R. Davidson,\n\\textit{$\\ca$-algebras by example}, Fields Institute Monographs,\n{\\bf 6}, Amer. Math. Soc., Providence, 1996.\n\n\\end{thebibliography}\n\n\\end{document}\n", "meta": {"hexsha": "d3e05abafa7efda1e58a468fc9b9d2df43bfe1be", "size": 38714, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "benchmark/src/test-data/0501/math0501087/math0501087.tex", "max_stars_repo_name": "e-sim/pdf-text-extraction-benchmark", "max_stars_repo_head_hexsha": "42eede9867e5795a6fc040b0a7ce92da3ddd3120", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-08-23T19:07:01.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-23T19:07:01.000Z", "max_issues_repo_path": "benchmark/src/test-data/0501/math0501087/math0501087.tex", "max_issues_repo_name": "e-sim/pdf-text-extraction-benchmark", "max_issues_repo_head_hexsha": "42eede9867e5795a6fc040b0a7ce92da3ddd3120", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmark/src/test-data/0501/math0501087/math0501087.tex", "max_forks_repo_name": "e-sim/pdf-text-extraction-benchmark", "max_forks_repo_head_hexsha": "42eede9867e5795a6fc040b0a7ce92da3ddd3120", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2239108409, "max_line_length": 84, "alphanum_fraction": 0.6996952007, "num_tokens": 12491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3481511269961152}}
{"text": "\\title{Lattice methods and the nuclear few- and many-body problem}\n\\author{Dean Lee}\n\\institute{Dean Lee \\at  Department of Physics, \nNorth Carolina State University, Raleigh, NC 27695,  USA, \\email{dean\\_lee@ncsu.edu}}\n\\maketitle\n\n\\abstract{This chapter builds upon the review of lattice methods and effective\nfield theory of the previous chapter. We begin with a brief overview of lattice calculations using chiral effective field theory and some recent applications.  We then describe several methods for computing scattering on the lattice.  After that we focus on the main goal, explaining the theory and algorithms\nrelevant to lattice simulations of nuclear\nfew- and many-body systems.  We discuss the exact equivalence\nof four different lattice formalisms, the Grassmann path integral, transfer matrix operator, Grassmann path\nintegral with auxiliary fields, and transfer matrix operator with auxiliary\nfields.  Along with our analysis we include several coding examples and a number of exercises for the calculations of few- and many-body systems at leading order in chiral effective field theory.}\n\n\n\\section{Introduction}\nThis chapter builds upon the general overview of lattice methods for effective field theory of the previous chapter. We discuss the theory and algorithms used in lattice simulations of nuclear\nfew and many body systems.  We show the exact equivalence of the Grassmann path integral, transfer matrix operator, Grassmann path\nintegral with auxiliary fields, and transfer matrix operator with auxiliary\nfields.  Along with our analysis we include several coding examples and a number of exercises for the calculations of few- and many-body systems at leading order in chiral effective field theory.\n\n\nEffective field theory (EFT) provides a theoretical framework for organizing low-energy\ninteractions in powers of particle\nmomenta. \\ Chiral\neffective field theory   applies this framework to the low-energy interactions of protons and neutrons while explicitly including the interactions of pions \\cite{Weinberg:1990rz,Weinberg:1991um,Ordonez:1992xp,Ordonez:1993tn,vanKolck:1994yi,Epelbaum:1998hg,Epelbaum:1998ka,Bedaque:2002mn,Epelbaum:2008ga}.\nPions are qualitatively different from other mesons since they become massless in the limit of massless quarks, thereby producing long-range exchange interactions. The low-energy expansion of chiral EFT is organized\nin powers of $Q$, where $Q$ denotes the typical momentum of the nucleons as well as explicit factors of the pion mass. \\ The most important interactions are called\nleading order (LO) or $O(Q^{0})$. \\ The next most important contributions\nare \nnext-to-leading order (NLO) or $O(Q^{2})$. \\ The terms after this are\nnext-to-next-to-leading order (NNLO) or $O(Q^{3})$, and so on. \n\nLattice EFT refers generally to lattice simulations based upon the framework of effective\nfield theory.  There are a few reviews in the literature which discuss current methods used\nin lattice effective field theory \\cite{Lee:2008fa,Drut:2012a} as well as the discussion in the previous chapter of this volume. Many different phenomena can be studied\nin\nlattice EFT using the same lattice action. \\ In principle all systematic\nerrors are introduced up front when defining the low-energy effective theory,\nas opposed to the particular computational scheme used to calculate\nobservables. \\ \n\nLattice EFT has been aided by efficient lattice methods developed for lattice QCD and condensed matter applications. \\ The methods include\nMarkov Chain Monte Carlo techniques, auxiliary fields\n\\cite{Hubbard:1959ub,Stratonovich:1958}, pseudofermion methods\n\\cite{Weingarten:1980hx}, and non-local updating schemes such as the hybrid Monte\nCarlo algorithm\\cite{Scalettar:1986uy,Gottlieb:1987mq,Duane:1987de}. \\ Lattice EFT\nwas\nfirst used in studies of infinite nuclear matter \\cite{Muller:1999cp} and\ninfinite neutron matter with and without explicit pions\n\\cite{Lee:2004si,Lee:2004qd,Lee:2005is,Lee:2005it}. \\ The method has also been used\nto\nstudy light nuclei in pionless EFT \\cite{Borasoy:2005yc} and chiral EFT at\nleading order \\cite{Borasoy:2006qn}. There have been further studies of neutron matter \n\\cite{Borasoy:2007vi,Borasoy:2007vk,Wlazlowski:2014jna} and light nuclei \\cite{Epelbaum:2009zs,Epelbaum:2009pd}, and there have been several applications to nuclear structure and nuclear clustering \\cite{Epelbaum:2011md,Epelbaum:2012qn,Epelbaum:2012iu,Lahde:2013uqa,Epelbaum:2013paa,Elhatisari:2016owd} as well as recent work on nuclear scattering and reactions~\\cite{Rupak:2013aue,Rupak:2014xza,Elhatisari:2015iga}.\n\n\\section{Recent Applications}\n\n\nWe review here several recent applications of lattice effective field theory to nuclear systems. In Ref.~\\cite{Epelbaum:2013paa},\nthe first {\\it ab initio} evidence is presented for a tetrahedral alpha-cluster structure\nof the ground state of $^{16}$O. The first excited $0^+$ state of $^{16}$O is found to be a planar or square arrangement of alpha clusters.  The evidence for these geometric arrangements come from the strong overlap between nuclear states and initial state configurations with these alpha-cluster geometries. \n\n\nIn Table~\\ref{oxygen1} we presented the energies of the low-lying even parity states of oxygen-16.  The columns labeled ``LO(2N)'' and ``NNLO(2N)'' show\nthe energies at each order using the two-nucleon force only. The column labeled\n``+3N'' also includes the 3NF, which first appears \nat NNLO. The column ``+4N$_\\mathrm{eff}$'' includes an ``effective''\n4N force, and the column ``Exp'' gives\nthe empirical energies.  This ``effective'' 4N force was introduced in Ref.~\\cite{Lahde:2013uqa} as a proxy  measure of unknown systematic errors responsible for overbinding in lattice chiral effective field theory calculations with increasing numbers of nucleons.  This tendency towards overbinding has also been noted in other nuclear structure calculations \\cite{Ekstrom:2015rta,Hagen:2015yea}. \n\\begin{table}[h]\n\\centering\n\\caption{Lattice results and experimental energies for the lowest even-parity\nstates of $^{16}$O in MeV. \nThe errors include statistical\nMonte Carlo errors and \nuncertainties due to the extrapolation to infinite Euclidean time. \n\\label{oxygen1}}\n\\vspace{.5cm}\n\\begin{tabular}{c | r | r r r | r}\n$J_n^p$ & \\multicolumn{1}{c |}{LO (2N)} & \\multicolumn{1}{c}{NNLO (2N)} \n& \\multicolumn{1}{c}{+3N} & \\multicolumn{1}{c |}{+4N$_\\mathrm{eff}$} & \\multicolumn{1}{c}{Exp}\n  \\\\ \\hline\\hline\n$0^+_1$ & $-147.3(5)$ & $-121.4(5)$ & $-138.8(5)$ & $-131.3(5)$ & $-127.62$\n\\\\\n$0^+_2$ & $-145(2)$ & $-116(2)$ & $-136(2)$ & $-123(2)$ & $-121.57$ \\\\\n$2^+_1$ & $-145(2)$ & $-116(2)$ & $-136(2)$ & $-123(2)$ & $-120.70$\n\\end{tabular}\n\\end{table}\n\nIn order to understand the source of this overbinding, the problem was revisited again in Ref.~\\cite{Elhatisari:2016owd}.  In that work numerical evidence from {\\it ab initio} lattice simulations showed that the problem appears related to the fact that the nuclear forces reside near a quantum phase transition. Using lattice effective field theory, Monte Carlo simulations were performed for systems with up to twenty nucleons. For even and equal numbers of protons and neutrons, a first-order transition was found at zero temperature from a Bose-condensed gas of alpha particles to a nuclear liquid. Whether one has an alpha-particle gas or nuclear liquid is determined by the strength of the alpha-alpha interactions, and the alpha-alpha interactions depend on the strength and locality of the nucleon-nucleon interactions. This insight is useful in improving calculations of nuclear structure and important astrophysical reactions involving alpha capture on nuclei.  These findings also provide a tool to probe the structure of alpha cluster states such as the Hoyle state responsible for the production of carbon in red giant stars and point to a connection between nuclear states and the universal physics of bosons at large scattering length.\n\nProcesses such as the scattering of alpha particles,\nthe triple-alpha reaction, and\nalpha capture play an important role in stellar nucleosynthesis.  In\nparticular, alpha capture on carbon determines the ratio of carbon to oxygen\nduring helium burning and impacts the following carbon, neon, oxygen,\nand silicon burning stages.  In these\nreactions the elastic scattering of alpha particles\nand alpha-like nuclei (nuclei with even and equal numbers of protons\nand neutrons) are important for understanding background and resonant\nscattering contributions.  In Ref.~\\cite{Elhatisari:2015iga}\nthe first {\\it ab initio}\ncalculations of the scattering of two alpha particles were performed using a technique called the adiabatic projection method.  These\ncalculations represent a significant algorithmic improvement since the calculations presented in\n Ref.~\\cite{Elhatisari:2015iga}\nscale roughly quadratically with the number of nucleons and opens a gateway to scattering and reactions involving heavier nuclei. \\\\ \n\n\n\n\n\n\\section{Scattering on the lattice}\n\nAt any given order in the chiral EFT expansion, there will be short-range interaction coefficients which depend on the chosen regularization of the large-momentum divergences.  On the lattice this regularization is provided by the lattice spacing, unless some additional regularization\nis applied to the lattice interactions.\nIn order to set the values of the short-range two-nucleon interaction\ncoefficients, we make a comparison of nucleon-nucleon scattering on\nthe lattice with experimental scattering data.  The extension to three-nucleon\ninteraction coefficients is also required at NNLO, and that procedure\non the lattice has been discussed in Ref.~\\cite{Epelbaum:2009zs}\n\n\nAs discussed in the previous chapter, L\\\"{u}scher \\cite{Luscher:1985dn,Luscher:1986pf,Luscher:1991ux} has shown that the finite-volume energy levels for a two-body system in a periodic cubic box are related to the infinite-volume scattering matrix. \\ While the method is very useful\nat low momenta, it can become less accurate at higher momenta and higher orbital angular momenta. \\ Also spin-orbit\ncoupling and partial-wave mixing are difficult to measure accurately using\nL\\\"{u}scher's method due to scattering artifacts produced by the\ncubic periodic boundary. \\ An alternative approach has been developed to measure\nphase shifts for particles on the lattice using a spherical wall boundary \\cite{Borasoy:2007vy,Carlson:1984}.\n\\ \n\nIn this approach, a hard spherical wall boundary is imposed on the relative separation between\nthe two particles.  This wall is placed at some chosen  radius $R_{\\text{wall}}$, and it removes copies of the interactions produced by the periodic lattice.\n\\ Working in the center-of-mass frame, we solve the time-independent Schr{\\\"o}dinger equation as a function of the relative separation between the particles and compute spherical standing waves which vanish at $r=R_{\\text{wall}}$.\nAt values of $r$ beyond the range of the interaction, the spherical standing\nwaves can be written as a superposition of products of spherical harmonics\nand spherical Bessel functions,\\begin{equation}\n\\left[  \\cos\\delta_{\\ell}\\cdot j_{\\ell}(kr)-\\sin\\delta_{\\ell}\\cdot y_{\\ell}(kr)\\right]\nY_{\\ell,\\ell_{z}}(\\theta,\\phi). \\label{wavefunction}%\n\\end{equation}\nHere $k$ is the relative momentum between the scattering particles,\nand $\\delta_{\\ell}$ is the phase shift for partial wave $\\ell$. \\ We can extract\n$k$ from the energy of the standing wave, and the phase shift $\\delta_{\\ell}$\nis determined by setting the wave function in Eq.~(\\ref{wavefunction}) to\nzero at the wall boundary.\n\nWhen the total intrinsic spin of the two nucleons is nonzero,\nspin-orbit coupling generates mixing between partial waves. $\\ $In this case\nthe standing wave at the wall boundary is decomposed into spherical harmonics\nand coupled-channel equations are solved to extract the phase shifts and\nmixing angles.  The spherical wall method\nwas used to calculate phase shifts and mixing angle for low-energy nucleon-nucleon\nscattering \\cite{Borasoy:2007vi}.\nRecently the spherical wall approach has been improved\nin accuracy and computational efficiency \\cite{Lu:2015riz}.\nIn the improved approach one projects onto spherical harmonics\n$Y_{\\ell,\\ell_z}$ with angular momentum quantum numbers $\\ell,\\ell_z$.  In this manner one constructs radial position states for a given partial wave,\n\\begin{equation}\n|r\\rangle^{\\ell,\\ell_z} = \\sum_{{\\bf r'}}Y_{\\ell,\\ell_z}({\\bf\\hat{r}'})\\delta_{r,|{\\bf r'}|}|{\\bf r'} \\rangle.\n\\end{equation} We require that $r$ is less than half the box length $L/2$.\n Using this technique we are essentially constructing a radial position basis for each partial wave. \n\nIt is also useful to introduce auxiliary potentials in the region lying just in front\nof the spherical wall boundary \\cite{Lu:2015riz}. The auxiliary potential\nis a spherical attractive well that is positioned in front\nof the spherical wall boundary.  We can tune to any scattering energy by\nadjusting the depth of the well. For systems with partial wave mixing due\nto spin-orbit coupling, we also include a Hermitian but imaginary off-diagonal\nauxiliary potential\nfor the two coupled channels.  This breaks time reversal\nsymmetry, and the resulting standing wave solutions now have both real and imaginary\nparts that are linearly independent.  From the real and imaginary solutions\none can determine the scattering phase shifts and mixing angle at any\ngiven value of the scattering energy.\n\nThis spherical wall approach has been used together with a technique called the adiabatic projection method to study nuclear scattering and reactions on the lattice.  The adiabiatic projection method \\cite{Pine:2013zja,Elhatisari:2014lka,Elhatisari:2015iga,Rokash:2015hra,Elhatisari:2016owd} is a general framework that produces a low-energy effective theory for\nclusters of particles which becomes exact in the limit of large projection\ntime.\nFor the case of two-cluster scattering, we consider a set of two cluster states\n$|{\\bf R}\\rangle$ labeled by the spatial separation vector {\\bf R}. The initial\nwave\nfunctions are wave packets which, for large $|{\\bf R}|$, factorize into a\nproduct of two\nindividual clusters,\n%\n\\begin{equation}\n|{\\bf R}\\rangle=\\sum_{{\\bf r}} |{\\bf r}+{\\bf R}\\rangle_1\\otimes|{\\bf r}\\rangle_2.\n\\label{eqn:single_clusters}\n\\end{equation}\n%\nThe summation over $\\bf {r}$ is required to produce states with \ntotal momentum equal to zero. We bin the initial cluster states together\naccording to radial distance and angular momentum. In this manner, we form\nradial \nposition states with projected angular momentum quantum numbers, which we\nlabel $|R\\rangle^{\\ell,\\ell_z}$. \n\nThe next step is to multiply by powers of the transfer matrix in order to\nform ``dressed'' cluster\nstates. This produces states that approximately span the set of low-energy cluster-cluster scattering\nstates in our periodic box. We discuss the transfer matrix formalism in detail later in this chapter. After $n_t$ time steps, we have the dressed cluster\nstates \n%\n\\begin{equation}\n\\vert R\\rangle^{\\ell,\\ell_z}_{n_t} = M^{n_t}|R\\rangle^{\\ell,\\ell_z}.\n\\end{equation}\n%\nThese dressed cluster states are then used to compute matrix\nelements of the transfer matrix $M$,\n%\n\\begin{equation}\n\\left[M_{n_t}\\right]^{\\ell,\\ell_z}_{R',R} =\\ ^{\\ell,\\ell_z}_{\\!\\!\\!\\!\\!\\quad{n_t}}\\langle\nR'\\vert M \\vert R\\rangle^{\\ell,\\ell_z}_{n_t}.\n\\label{Hmatrix}\n\\end{equation}\n%\nSince such states are not orthogonal, we also compute a norm\nmatrix\n% \n\\begin{equation}\n\\left[N_{n_t}\\right]^{\\ell,\\ell_z}_{R',R} =\\ ^{\\ell,\\ell_z}_{\\!\\!\\!\\!\\!\\quad{n_t}}\\langle\nR'\\vert R\\rangle^{\\ell,\\ell_z}_{n_t}. \n\\label{eqn:norm}\n\\end{equation}\n%\nThe ``radial adiabatic transfer matrix'' is defined as the matrix product\n%\n\\begin{equation}\n\\left[ {M^a_{n_t}} \\right]^{\\ell,\\ell_z}_{R',R} = \n\\left[N_{n_t}^{-\\frac{1}{2}}M_{n_t}\nN_{n_t}^{-\\frac{1}{2}} \\right]^{\\ell,\\ell_z}_{R',R},\n\\label{eqn:Adiabatic-Hamiltonian}\n\\end{equation}\n%\nand the scattering phase shifts can then be determined from the standing waves\nof the radial adiabatic transfer matrix.  \n\n\\section{Lattice formalisms}\n\nThroughout our discussion of the lattice formalism we use dimensionless\nparameters and operators corresponding with physical values times\nthe\nappropriate power of the spatial lattice spacing $a$. In our notation the\nthree-component integer vector ${\\bf n}$ labels the lattice sites of a\nthree-dimensional periodic lattice with dimensions $L^{3}$. The spatial\nlattice unit vectors are denoted \n$\\mathbf{\\hat{l}}$ = $\\mathbf{\\hat{1}}$,\n$\\mathbf{\\hat{2}}$, $\\mathbf{\\hat{3}}$.\nWe use $n_t$ to label lattice steps in the temporal direction, and $L_{t}$\ndenotes the total number of lattice time steps. \\ The temporal lattice spacing\nis given by $a_{t}$, and $\\alpha_{t}=a_{t}/a$ is the ratio of the temporal\nto\nspatial lattice spacing. \\ We also define $h=\\alpha_{t}/(2m)$, where $m$\nis\nthe nucleon mass in lattice units. In Fig.~\\ref{formalism} we show a diagram\nof the four different but exactly equivalent lattice formulations that we\ndiscuss, the Grassmann path integral, transfer matrix operator, Grassmann\npath integral with auxiliary fields, and transfer matrix operator with auxiliary\nfields.\n\n\\begin{figure}\n[pb]\n\\begin{center}\n\\includegraphics[width=3in\n]%\n{Chapter6-figures/formalism.png}%\n\\caption{A schematic diagram of the different lattice formulations, namely, the Grassmann path integral, transfer matrix operator, Grassmann\npath integral with auxiliary fields, and transfer matrix operator with auxiliary\nfields.}%\n\\label{formalism}%\n\\end{center}\n\\end{figure}\n%EndExpansion\n\n\\subsection{Grassmann path integral}\n\nWe define the lattice action starting from the lattice Grassmann path integral\naction without auxiliary fields.\n\\ This\nis the simplest formulation in which to derive the lattice Feynman rules.\n We let $c$ and $c^*$ be anticommuting Grassmann fields for the nucleons.\n\\ In our notation $c$ is a column vector composed of the spin-isospin nucleon\ndegrees of freedom $c_i$, while $c^*$ is a row vector of the components\n$c^*_i$.  The Grassmann fields are periodic with respect to\nthe spatial extent of the $L^{3}$ lattice,%\n\\begin{equation}\nc_i({\\bf n}+L\\hat{1},n_t)=c_i({\\bf n}+L\\hat{2},n_t)=c_i({\\bf n}+L\\hat{3},n_t)=c_i({\\bf n},n_t),\n\\end{equation}%\n\\begin{equation}\nc_i^{\\ast}({\\bf n}+L\\hat{1},n_t)=c_i^{\\ast}({\\bf n}+L\\hat{2}%\n,n_t)=c_i^{\\ast}({\\bf n}+L\\hat{3},n_t)=c_i^{\\ast}({\\bf n},n_t),\n\\end{equation}\nand antiperiodic along the temporal direction,%\n\\begin{equation}\nc_i({\\bf n},n_t+L_{t})=-c_i({\\bf n},n_t),\n\\end{equation}%\n\\begin{equation}\nc_i^{\\ast}({\\bf n},n_t+L_{t})=-c_i^{\\ast}({\\bf n},n_t).\n\\end{equation}\nWe write $DcDc^{\\ast}$ as shorthand for the integral measure,%\n\\begin{equation}\nDcDc^{\\ast}=\\prod_{{\\bf n},n_t,i}dc_{i}({\\bf n}%\n,n_t)dc_{i}^{\\ast}({\\bf n},n_t).\n\\end{equation}\nWe use the usual convention for Grassmann integration,%\n\\begin{equation}\n\\int dc_{i}({\\bf n},n_t)=\\int dc_{i}^{\\ast}({\\bf n},n_t)=0\\text{,}%\n\\end{equation}%\n\\begin{equation}\n\\int dc_{i}({\\bf n},n_t)c_{i}({\\bf n},n_t)=\\int dc_{i}^{\\ast}(\\vec\n{n},n_t)c_{i}^{\\ast}({\\bf n},n_t)=1\\text{ \\ (no sum on }i\\text{)}.\n\\end{equation}\nWe consider the Grassmann path integral%\n\\begin{equation}\n\\mathcal{Z}=\\int DcDc^{\\ast}\\exp\\left[  -S\\left(c^{\\ast},c\\right)  \\right]\n, \\label{defining_Z}%\n\\end{equation}\nwhere the lattice action can be broken into a free part and interacting part,\n\\begin{equation}\nS(c^*,c)=S_{\\text{free}}(c^{\\ast},c)+S_\\text{int}(c^{\\ast},c).\n\\label{path_nonaux}%\n\\end{equation}\nThe free part is the free non-relativistic nucleon action, which is \n\\begin{align}\nS_{\\text{free}}(c^{\\ast},c)  &  =\\sum_{{\\bf n},n_t\n}  c_{}^{\\ast}({\\bf n},n_t) \\left[ c({\\bf n},n_t+1)-c({\\bf n},n_t)\\right]\n+\\alpha_t \\sum_{n_t} K^{(n_t)}(c^*,c),\n\\end{align}\nwhere\n\\begin{align}\nK^{(n_t)}(c^*,c) =\\sum_{k=0,1,2,\\cdots} (-1)^k \\frac{w_k}{2m} \\sum_{{\\bf\nn},{\\bf \\hat{l}}} c^{\\ast}({\\bf n},n_t) \\left[ c({\\bf n}+k{\\bf\\hat{l}},n_t)\n+ c({\\bf n}-k{\\bf \\hat{l}},n_t)\\right], \n\\end{align}\nand the hopping coefficients $w_k$ correspond to a hopping parameter expansion\nof the squared momentum,\n\\begin{align}\nP^2({\\bf p})=2\\sum_{k=0,1,2,\\cdots}\\sum_{l=1,2,3}%\n(-1)^{k}w_{k}\\cos\\left(kp_{l}\\right).\n\\end{align}\nThe hopping coefficients are chosen to match the continuum  relation \n\\begin{align}\nP^2({\\bf p})={\\bf p}^2,\n\\end{align}\nup to some chosen level of lattice discretization error.  The hopping coefficients\n$w_k$ for a few different lattice actions are shown in Table~\\ref{hopping_coeff}.\n\n\\begin{table}[tbh]\n\\caption{Hopping coefficients $w_k$ for several lattice actions}%\n\\label{hopping_coeff}%\n\\begin{center}\n\\begin{tabular}{p{2cm}p{3cm}p{3cm}p{3cm}}\n\\hline\\noalign{\\smallskip}\ncoefficient& standard & $O(a^{2})$-improved & $O(a^{4})$-improved \\\\\n\\noalign{\\smallskip}\\svhline\\noalign{\\smallskip}\n$w_{0}$ & $1$ & $5/4$ & $49/36$\\\\\n$w_{1}$ & $1$ & $4/3$ & $3/2$\\\\\n$w_{2}$ & $0$ & $1/12$ & $3/20$\\\\\n$w_{3}$ & $0$ & $0$ & $1/90$\\\\\n\\noalign{\\smallskip}\\hline\\noalign{\\smallskip}\n\\end{tabular}\n\\end{center}\n\\end{table}\n\n\n\\subsection{Transfer matrix operator}\n\n\nLet $a_{i}({\\bf n})$ and\n$a_{i}^{\\dagger}({\\bf n})$ denote fermion annihilation and creation operators\nfor the nucleon component $i$ at lattice site ${\\bf n}$.  The shorthand $a_{}({\\bf\nn})$ represents a column vector of nucleon components $a_{i}({\\bf n})$, and\n$a^{\\dagger}({\\bf n})$ represents a row vector of components $a^{\\dagger}_{i}({\\bf\nn})$.  We can write any Grassmann path\nintegral with instantaneous interactions as the trace of a product of\noperators using the identity \\cite{Creutz:1988wv,Creutz:1999zy}%\n\\begin{align}\n&  {\\rm Tr}\\left\\{  \\colon F_{L_{t}-1}\\left[  a_{}^{\\dagger}({\\bf n}^{\\prime}),a({\\bf\nn})\\right]  \\colon\\times\\cdots\\times\\colon\nF_{0}\\left[  a_{}^{\\dagger}({\\bf n}^{\\prime}),a({\\bf n})\\right]\n\\colon\\right\\} \\nonumber\\\\\n&  =\\int DcDc^{\\ast}\\exp\\left\\{  \\sum_{n_t=0}^{L_{t}-1}\\sum_{{\\bf n},i}%\nc_{i}^{\\ast}({\\bf n},n_t)\\left[  c_{i}({\\bf n},n_t)-c_{i}({\\bf n}%\n,n_t+1)\\right]  \\right\\} \\nonumber\\\\\n&  \\qquad\\qquad\\qquad\\times\\prod_{n_t=0}^{L_{t}-1}F_{n_t}\\left[\nc_{}^{\\ast}({\\bf n}^{\\prime},n_t),c({\\bf n},n_t)\\right]\n ,\n\\label{correspondence}%\n\\end{align}\nwhere $c_{i}({\\bf n},L_{t})=-c_{i}({\\bf n},0)$.\n\nLet us define the free non-relativistic lattice Hamiltonian\n\\begin{equation}\nH_{\\rm free}(a^{\\dagger},a) =\\sum_{k=0,1,2,\\cdots} (-1)^k \\frac{w_k}{2m}\n\\sum_{{\\bf n},{\\bf \\hat{l}}} a^{\\dagger}({\\bf n}) \\left[ a({\\bf n}+k{\\bf\\hat{l}})\n+ a({\\bf n}-k{\\bf \\hat{l}})\\right].\n\\end{equation}\nWe write the interaction term as $H_{\\rm int}(a^{\\dagger},a)$, so that our\ntotal Hamiltonian is\n\\begin{equation}\nH(a^{\\dagger},a) = H_{\\rm free}(a^{\\dagger},a) + H_{\\rm int}(a^{\\dagger},a).\n\\end{equation}Using the correspondence Eq.~(\\ref{correspondence}), we can\nrewrite the path\nintegral $\\mathcal{Z}$ defined in Eq.~(\\ref{defining_Z}) as a transfer-matrix\npartition function,%\n\\begin{equation}\n\\mathcal{Z}={\\rm Tr}\\left(  M^{L_{t}}\\right)  ,\n\\end{equation}\nwhere $M$ is the normal-ordered transfer matrix operator%\n\\begin{equation}\nM=:\\exp\\left[  -H(a^{\\dagger},a)\\alpha_{t}\\right]  :. \\label{transfer_noaux}%\n\\end{equation}\nRoughly speaking, the transfer matrix operator is the exponential of the\nHamiltonian operator over one Euclidean lattice time step.\n\\ In order to satisfy the identity Eq.~(\\ref{correspondence}), the exact\ndefinition of the transfer matrix is the normal-ordered exponential as defined\nin Eq.~(\\ref{transfer_noaux}).\n\nIn this transfer matrix formalism, one can do simulations of nucleons using Monte Carlo, and this would essentially be a lattice version of diffusion or Green's function Monte Carlo \\cite{Carlson:2014vla}.  Visually one can view the nucleons as interacting with each other while diffusing in space with each time step, as indicated in Fig.~\\ref{worldlines}.  At leading order in chiral effective field theory, the\ninteractions include two independent $S$-wave contact interactions and the exchange of pions.  We discuss these interactions in detail in the following.\n\\begin{figure}[ptb]%\n\\centering\n\\sidecaption\n\\includegraphics[\nheight=7.00cm\n]%\n{Chapter6-figures/worldlines.png}%\n\\caption{A sketch showing nucleons which evolve with each time step.  At leading order in chiral effective field theory, the interactions include\ntwo contact\ninteractions and the exchange of pions.}%\n\\label{worldlines}%\n\\end{figure}\n\n\n\\subsection{Grassmann path integral with auxiliary field}\n\nWe assume that there exists an integral relation that allows us to write\n$\\exp\\left[-S_{\\rm int}(c^*,c)\\right]$ as an integral over auxiliary fields.\n The purpose of the auxiliary field transformation is to decouple the interactions\namong the nucleons.  Instead the interactions will be between the nucleons\nand the auxiliary fields.  \n\nWe illustrate using the interactions that appear at leading order in\nchiral effective field theory.  For pedagogical purposes we discuss the simplest possible implementation of the leading order action on the lattice.  We first consider a zero-range contact interaction\nwhich is independent of\nnucleon spin and isospin.\nThe action has the form \n\\begin{equation}\nS^{C}_\\text{int}(c^{\\ast},c) = \\alpha_{t}\\frac{C}{2} \\sum_{{\\bf n},n_t} \\left[c^{\\ast}({\\bf\nn},n_t)c({\\bf n},n_t)\\right]^2.\n\\end{equation}\nWe can write this as\n\\begin{equation}\n\\exp\\left[-S^C_{\\rm int}(c^*,c)\\right] = \\int Ds \\; \\exp\\left[-S_{ss}(s)\n- S_{s}(c^*,c,s)\\right]\n\\label{aux}\n\\end{equation}\nfor auxiliary field $s({\\bf n},n_t)$, \nwhere\n\\begin{align}\nS_{ss}(s) = \\frac{1}{2} & \\sum_{{\\bf n},n_t} s^{2}({\\bf n},n_t),\n \\\\\nS_{s}(c^*,c,s) =  \\sqrt{-C\\alpha_{t}} & \\sum_{{\\bf n},n_t} s({\\bf n},n_t)c^{\\ast}({\\bf\nn},n_t)c({\\bf n},n_t).  \n\\end{align}\nIn our definition of the integration measure $Ds$, we include a factor of\n$1/\\sqrt{2\\pi}$ for each degree of freedom.\n\nNext we consider an isospin-dependent contact interaction \n\\begin{equation}\nS^{C'}_\\text{int}(c^{\\ast},c) = \\alpha_{t}\\frac{C'}{2} \\sum_{{\\bf n},n_t,I}\n\\left[c^{\\ast}({\\bf\nn},n_t)\\tau_I c({\\bf n},n_t)\\right]^2,\n\\end{equation}\nwhere $\\tau_I$ for $I=1,2,3$ are the Pauli matrices in isospin space.  Then\nwe can use\n\\begin{equation}\n\\exp\\left[-S^{C'}_{\\rm int}(c^*,c)\\right] = \\int \\prod_I Ds_I \\exp\\left[-S_{s_Is_I}(s_I)\n- S_{s_I}(c^*,c,s_{I})\\right]\n\\label{aux2}\n\\end{equation}\nfor auxiliary fields $s_I({\\bf n},n_t)$ where\n\\begin{align}\nS_{s_Is_I}(s_I)=\\frac{1}{2} & \\sum_{{\\bf n},n_t,I} s_I^{2}({\\bf n},n_t),\n\\\\\nS_{s_I}(c^*,c,s_{I}) = \\sqrt{-C'\\alpha_{t}} & \\sum_{{\\bf n},n_t,I} s_{I}({\\bf\nn},n_t)c^{\\ast}({\\bf\nn},n_t)\\tau_Ic({\\bf n},n_t).  \n\\end{align}\n\nFinally we work with the one-pion exchange potential (OPEP).  In this case\nthe pion acts much like the auxiliary fields.  However there are also spatial\ncorrelations in the quadratic part of the pion action and a gradient coupling\nbetween the pions and nucleons.\n The one-pion exchange interaction on the lattice can written as\n\\begin{equation}\n\\exp\\left[-S^{\\rm OPEP}_{\\rm int}(c^*,c)\\right] = \\int \\prod_I D\\pi_I\n\\exp\\left[-S_{\\pi_I\\pi_I}(\\pi_I) - S_{\\pi_I}(c^*,c,\\pi_{I})\\right].\n\\end{equation}\nThe free pion action is\n\\begin{align}\nS_{\\pi_I\\pi_I}(\\pi_I)= & \\frac{1}{2}\\alpha_{t}m^2_{\\pi} \\sum_{{\\bf n},n_t,I}\\pi^2_{I}({\\bf\nn},n_t) \\\\\n& +\\frac{1}{2}\\alpha_{t}%\n\\sum_{k=0,1,2,\\cdots}(-1)^k w_k \\sum_{{\\bf n},n_t,I,{\\bf \\hat{l}}} \\pi_{I}({\\bf\nn},n_t)\n\\left[ \\pi_{I}({\\bf n}+k{\\bf \\hat{l}},n_t) + \\pi_{I}({\\bf n}-k{\\bf \\hat{l}},n_t)\n\\right],\n\\end{align}\nwith the coefficient $w_k$ as defined in Table~\\ref{hopping_coeff} and $m_{\\pi}$ is the pion mass.  At leading order we do not\nconsider any isospin-breaking effects.  The pion coupling to the nucleon is\\begin{align}\nS_{\\pi_I}(c^*,c,\\pi_{I}) = \\frac{g_A \\alpha_t}{2 f_{\\pi}} \\sum_{{\\bf n},n_t,l,I}\n\\Delta_k \\pi_{I}({\\bf\nn},n_t)c^{\\ast}({\\bf\nn},n_t)\\sigma_k\\tau_Ic({\\bf n},n_t),  \n\\end{align}\nwhere $\\sigma_l$ for $l=1,2,3$ are the Pauli matrices in spin space and \n\\begin{equation}\n\\Delta_l \\pi_{I}({\\bf\nn},n_t)=\\frac{1}{2}\\sum_{k=1,2,\\cdots} (-1)^{k-1} o_k \\left[  \\pi_{I}({\\bf\nn}+k{\\bf \\hat{l}},n_t) - \\pi_{I}({\\bf\nn}-k{\\bf \\hat{l}},n_t)\\right],\n\\end{equation}\nwith coefficients $o_k$ corresponding to a hopping parameter expansion of the\nmomentum,\n\\begin{align}\nP(p_l)=\\sum_{k=1,2,\\cdots}%\n(-1)^{k-1} o_{k}\\sin\\left(kp_{l}\\right).\n\\end{align}\nHere\n$g_A$ is the axial-vector coupling constant, and $f_{\\pi}$ is the pion\ndecay constant.  The hopping coefficients can be chosen to match the continuum result\n\\begin{equation}\nP(p_l)= p_l.\n\\end{equation}\nThe hopping coefficients $o_k$ for a few different lattice actions are shown\nin Table~\\ref{hopping_coeff_2}.\n\\begin{table}[tbh]\n\\caption{Hopping coefficients $o_k$ for several lattice actions.}%\n\\begin{center}\n\\label{hopping_coeff_2}%\n\n\\begin{tabular}{p{2cm}p{3cm}p{3cm}p{3cm}}\n\\hline\\noalign{\\smallskip}\ncoefficient& standard & $O(a^{2})$-improved & $O(a^{4})$-improved \\\\\n\\noalign{\\smallskip}\\svhline\\noalign{\\smallskip}\n$o_{1}$ & $1$ & $4/3$ & $3/2$\\\\\n$o_{2}$ & $0$ & $1/6$ & $3/10$\\\\\n$o_{3}$ & $0$ & $0$ & $1/30$ \\\\\n\\noalign{\\smallskip}\\hline\\noalign{\\smallskip}\n\\end{tabular}\n\\end{center}\n\\end{table}\n\n\\subsection{Transfer matrix operator with auxiliary field}\nUsing the equivalence in Eq.~(\\ref{correspondence}), we can write $\\mathcal{Z}$\nas the trace of a product of transfer matrix operators which depend on the\nauxiliary field,\n\\begin{equation}\n\\mathcal{Z} = \\int Ds \\prod_I \\left(Ds_I D\\pi_I\\right) \\; \n\\exp{\\left[-S_{ss}(s)\n-S_{s_Is_I}(s_I)\n-S_{\\pi_I\\pi_I}(\\pi_I)\\right]}\n {\\rm Tr}\\left\\{ M^{(L_t-1)}\\cdots M^{(0)}\\right\\}.\n\\end{equation}\nThe transfer matrix at time step $n_t$ is given by\n\\begin{equation}\nM^{(n_t)}=\\colon\\exp\\left[ -H^{(n_t)}(a^{\\dagger},a,s,s_I,\\pi_I)\\alpha_{t}\n\\right]\n\\colon,\n\\end{equation}\nwhere\n\\begin{equation}\nH^{(n_t)}(a^{\\dagger},a,s,s_I,\\pi_I)\\alpha_{t}=H_{\\text{free}}(a^{\\dagger},a)\\alpha_{t}+S^{(n_t)}_s(a^{\\dagger},a,s)+S^{(n_t)}_{s_I}(a^{\\dagger},a,s_{I})+S^{(n_t)}_{\\pi_I}(a^{\\dagger},a,\\pi_{I}),\n\\end{equation}\nand\n\\begin{equation}\nS^{(n_t)}_{s}(a^{\\dagger},a,s) =  \\sqrt{-C\\alpha_{t}} \\sum_{\\bf n} s({\\bf\nn},n_t)a^{\\dagger}({\\bf\nn})a({\\bf n}),  \n\\end{equation}\n\\begin{equation}\nS^{(n_t)}_{s_I}(a^{\\dagger},a,s_{I}) = \\sqrt{-C'\\alpha_{t}} \\sum_{{\\bf n},I}\ns_{I}({\\bf\nn},n_t)a^{\\dagger}({\\bf\nn})\\tau_Ia({\\bf n}),\n\\end{equation}\n\\begin{equation}\nS^{(n_t)}_{\\pi_I}(a^{\\dagger},a,\\pi_{I}) = \\frac{g_A \\alpha_t}{2 f_{\\pi}}\n\\sum_{{\\bf n},k,I}\n\\Delta_k \\pi_{I}({\\bf\nn},n_t)a^{\\dagger}({\\bf\nn})\\sigma_k\\tau_I a({\\bf n}).\n\\end{equation}\n\n\\section{Projection Monte Carlo}\nLet us consider a system with $A$ nucleons.  We can create a general single-nucleon\nstate using \ncreation operators acting on the vacuum with coefficient function $f({\\bf\nn})$. We write $f({\\bf n})$ as a column vector in the space of nucleon spin and isospin components, and the single-nucleon\nstate can be written as\\begin{equation}\n\\left| f \\right> = \\sum_{\\bf n}a^{\\dagger}({\\bf n})f({\\bf n}) \\left| 0 \\right>.\n\\end{equation}\nFor our projection Monte Carlo calculation we take our A-body initial\nstate\nto be a Slater determinant of single nucleon states,\n\\begin{equation}\n\\left| f_1,\\cdots ,f_A \\right> =   \\left[\\sum_{\\bf n}a^{\\dagger}({\\bf n})f_1({\\bf\nn}) \\right] \\cdots \\left[\\sum_{\\bf n}a^{\\dagger}({\\bf n})f_A({\\bf n}) \\right]\n\\left| 0 \\right>.\n\\end{equation} We use the same construction for the $A$-body final state.\n\nFor the purposes of coding the projection Monte Carlo calculation, it is\nconvenient to view the identical nucleons as having a hidden index $j=1,\\cdots\n,A$ that makes all of the nucleons distinguishable.  If we antisymmetrize\nall physical states over this extra index then all physical observables are\nexactly recovered.   So our initial state $\\left| f_1,\\cdots ,f_A \\right>$\nbecomes\n\\begin{align}\n \\frac{1}{\\sqrt{A!}} & \\sum_{P}   \\left[\\sum_{\\bf n}a^{\\dagger}_{[P(1)]}({\\bf n})f_1({\\bf\nn}) \\right] \\cdots \\left[\\sum_{\\bf n}a^{\\dagger}_{[P(A)]}({\\bf n})f_A({\\bf\nn}) \\right]\n\\left| 0 \\right> \\nonumber \\\\\n & =\\frac{1}{\\sqrt{A!}} \\sum_{P'} {\\rm sgn}(P') \\left[\\sum_{\\bf n}a^{\\dagger}_{[1]}({\\bf\nn})f_{P'(1)}({\\bf\nn}) \\right] \\cdots \\left[\\sum_{\\bf n}a^{\\dagger}_{[A]}({\\bf n})f_{P'(A)}({\\bf\nn}) \\right]\n\\left| 0 \\right>,\n\\end{align}\nwhere the summations are over all permutations $P$, and ${\\rm sgn}$ is\nthe sign of the permutation.\nWith these hidden indices our normal-ordered auxiliary-field transfer matrix\n$M^{(n_t)}$  becomes \n\\begin{equation}\n\\left[1-H^{(n_t)}(a_{[1]}^{\\dagger},a_{[1]},s,s_I,\\pi_I)\\alpha_{t}\\right]\n\\cdots \\left[1-H^{(n_t)}(a^{\\dagger}_{[A]},a_{[A]},s,s_I,\\pi_I)\\alpha_{t}\\right]\n\\end{equation}\nWe see that the higher-order powers of the exponential vanish due to normal ordering.\n\nIn the projection Monte Carlo calculation we compute the amplitude\n\\begin{equation}\nZ(n_t) = \\left< f_1,\\cdots ,f_A \\right|  M^{(n_t-1)} \\cdots M^{(0)} \\left|\nf_1,\\cdots ,f_A \\right>\n\\end{equation}\nfor $n_t=L_t$ and $n_t=L_t-1$.  In the limit of large $L_t$ the amplitudes will be dominated\nby the state with the lowest energy $E_0$ and nonzero overlap with $\\left|\nf_1,\\cdots ,f_A \\right>$.  In this limit the ratio $Z(n_t)/Z(n_t-1)$\nwill converge to $\\exp(-E_0 \\alpha_t)$ from above.\n\nEach nucleon evolves as a\nparticle in a fluctuating background of auxiliary fields and pion\nfields. \\  The original interactions are reproduced after integrating over\nthe fluctuating auxiliary\nand pion fields. For a simulation with $A$ nucleons, the amplitude for\na given configuration of pion and auxiliary fields is proportional to the\ndeterminant of an $A\\times A$ matrix ${\\bf M}$. \\ The\nentries of ${\\bf M}_{ij}$ are single nucleon worldline amplitudes for a nucleon\nstarting at state $\\left| f_j \\right> $ at $t=0$ and ending at state $\\left|\nf_i \\right> $ at $t=t_{f}=L_t\\alpha_t$. This is shown in Fig. \\ref{hsworldlines}.\n\n\\begin{figure}[ptb]%\n\\centering\n\\sidecaption\n\\includegraphics[\nheight=7.00cm\n]\n{Chapter6-figures/HSworldlines.png}%\n\\caption{A sketch showing the worldline for a single nucleon with a background\nof pion fields and\nauxiliary fields.}%\n\\label{hsworldlines}%\n\\end{figure}\n\nIn the following we show sample code \\ref{label_1} in the Fortran programming language which calculates the \nauxiliary-field transfer matrix multiplications on the left starting from the \nsingle-nucleon initial states.  We show only the terms which arise from \nthe free-nucleon transfer matrix and the auxiliary field $s$.  \n\n\\begin{lstlisting}[language=Fortran,caption=Sample code calculating \nthe auxiliary-field transfer matrix multiplications on the left starting from the single-nucleon initial states,label={label_1}]\nDO nt = nt1+1, nt2     \n  DO np = 0,num-1        \n    DO nz = 0,L-1; DO ny = 0,L-1; DO nx = 0,L-1; DO ni = 0,1; DO ns = 0,1\n              \n     zvecs(nx,ny,nz,nt,ns,ni,np) = zvecs(nx,ny,nz,nt-1,ns,ni,np) &\n        * (1.D0-6.D0*w0_N*h+CDSQRT(-c0*atovera*(1.D0,0.D0))*s(nx,ny,nz,nt-1))\n              \n      zvecs(nx,ny,nz,nt,ns,ni,np) = zvecs(nx,ny,nz,nt,ns,ni,np) &\n        + w1_N*h*zvecs(MOD(nx+1,L),ny,nz,nt-1,ns,ni,np) &\n        + w1_N*h*zvecs(MOD(nx-1+L,L),ny,nz,nt-1,ns,ni,np) &\n        + w1_N*h*zvecs(nx,MOD(ny+1,L),nz,nt-1,ns,ni,np) &\n        + w1_N*h*zvecs(nx,MOD(ny-1+L,L),nz,nt-1,ns,ni,np) &\n        + w1_N*h*zvecs(nx,ny,MOD(nz+1,L),nt-1,ns,ni,np) &\n        + w1_N*h*zvecs(nx,ny,MOD(nz-1+L,L),nt-1,ns,ni,np)\n              \n      IF (improveN >= 1) THEN                 \n        zvecs(nx,ny,nz,nt,ns,ni,np) = zvecs(nx,ny,nz,nt,ns,ni,np) & \n          - w2_N*h*zvecs(MOD(nx+2,L),ny,nz,nt-1,ns,ni,np) &\n          - w2_N*h*zvecs(MOD(nx-2+L,L),ny,nz,nt-1,ns,ni,np) &\n          - w2_N*h*zvecs(nx,MOD(ny+2,L),nz,nt-1,ns,ni,np) &\n          - w2_N*h*zvecs(nx,MOD(ny-2+L,L),nz,nt-1,ns,ni,np) &\n          - w2_N*h*zvecs(nx,ny,MOD(nz+2,L),nt-1,ns,ni,np) &\n          - w2_N*h*zvecs(nx,ny,MOD(nz-2+L,L),nt-1,ns,ni,np)\n      END IF\n              \n      IF (improveN == 2) THEN\n        zvecs(nx,ny,nz,nt,ns,ni,np) = zvecs(nx,ny,nz,nt,ns,ni,np) &\n          + w3_N*h*zvecs(MOD(nx+3,L),ny,nz,nt-1,ns,ni,np) &\n          + w3_N*h*zvecs(MOD(nx-3+L,L),ny,nz,nt-1,ns,ni,np) &\n          + w3_N*h*zvecs(nx,MOD(ny+3,L),nz,nt-1,ns,ni,np) &\n          + w3_N*h*zvecs(nx,MOD(ny-3+L,L),nz,nt-1,ns,ni,np) &           \n          + w3_N*h*zvecs(nx,ny,MOD(nz+3,L),nt-1,ns,ni,np) &\n          + w3_N*h*zvecs(nx,ny,MOD(nz-3+L,L),nt-1,ns,ni,np)\n      END IF\n              \n    END DO; END DO; END DO; END DO; END DO\n  END DO\nEND DO\n\n\\end{lstlisting}\n\n\nSimilarly, we now show sample code \\ref{label_2} which calculates \nthe auxiliary-field transfer matrix multiplications on the right starting from \nthe single-nucleon final states.  Again we present only the terms arising from the free-nucleon transfer matrix and the auxiliary field $s$.  \n\n\\begin{lstlisting}[language=Fortran,caption=Sample code calculating \nthe auxiliary-field transfer matrix multiplications on the right starting\nfrom the single-nucleon final states,label={label_2}]\nDO nt = nt2,nt1+1,-1\n  DO np = 0,num-1   \n    DO nz = 0,L-1; DO ny = 0,L-1; DO nx = 0,L-1; DO ni = 0,1; DO ns = 0,1\n               \n      zdualvecs(nx,ny,nz,nt-1,ns,ni,np) &\n        = zdualvecs(nx,ny,nz,nt,ns,ni,np) &\n        * (1.D0-6.D0*w0_N*h+CDSQRT(-c0*atovera*(1.D0,0.D0))*s(nx,ny,nz,nt-1))\n               \n      zdualvecs(nx,ny,nz,nt-1,ns,ni,np) &\n        = zdualvecs(nx,ny,nz,nt-1,ns,ni,np) & \n        + w1_N*h*zdualvecs(MOD(nx+1,L),ny,nz,nt,ns,ni,np) &\n        + w1_N*h*zdualvecs(MOD(nx-1+L,L),ny,nz,nt,ns,ni,np) &\n        + w1_N*h*zdualvecs(nx,MOD(ny+1,L),nz,nt,ns,ni,np) &\n        + w1_N*h*zdualvecs(nx,MOD(ny-1+L,L),nz,nt,ns,ni,np) &\n        + w1_N*h*zdualvecs(nx,ny,MOD(nz+1,L),nt,ns,ni,np) &\n        + w1_N*h*zdualvecs(nx,ny,MOD(nz-1+L,L),nt,ns,ni,np) \n               \n      IF (improveN >= 1) THEN\n        zdualvecs(nx,ny,nz,nt-1,ns,ni,np) &\n          = zdualvecs(nx,ny,nz,nt-1,ns,ni,np) &\n          - w2_N*h*zdualvecs(MOD(nx+2,L),ny,nz,nt,ns,ni,np) &\n          - w2_N*h*zdualvecs(MOD(nx-2+L,L),ny,nz,nt,ns,ni,np) &\n          - w2_N*h*zdualvecs(nx,MOD(ny+2,L),nz,nt,ns,ni,np) &\n          - w2_N*h*zdualvecs(nx,MOD(ny-2+L,L),nz,nt,ns,ni,np) &\n          - w2_N*h*zdualvecs(nx,ny,MOD(nz+2,L),nt,ns,ni,np) &\n          - w2_N*h*zdualvecs(nx,ny,MOD(nz-2+L,L),nt,ns,ni,np) \n      END IF\n               \n      IF (improveN == 2) THEN\n        zdualvecs(nx,ny,nz,nt-1,ns,ni,np) &\n        = zdualvecs(nx,ny,nz,nt-1,ns,ni,np) &\n        + w3_N*h*zdualvecs(MOD(nx+3,L),ny,nz,nt,ns,ni,np) &\n        + w3_N*h*zdualvecs(MOD(nx-3+L,L),ny,nz,nt,ns,ni,np) &\n        + w3_N*h*zdualvecs(nx,MOD(ny+3,L),nz,nt,ns,ni,np) &\n        + w3_N*h*zdualvecs(nx,MOD(ny-3+L,L),nz,nt,ns,ni,np) &\n        + w3_N*h*zdualvecs(nx,ny,MOD(nz+3,L),nt,ns,ni,np) &\n        + w3_N*h*zdualvecs(nx,ny,MOD(nz-3+L,L),nt,ns,ni,np) \n      END IF\n               \n    END DO; END DO\n  END DO; END DO; END DO\nEND DO\n\n\\end{lstlisting}\n\nIn the following we show sample code \\ref{label_3} where these transfer matrix product multiplications are called as subroutines and used to compute the determinant and inverse of the matrix of single-nucleon amplitudes {\\bf M}.  \n\n\\begin{lstlisting}[language=Fortran,caption=Sample code where transfer matrix product multiplications are called and used to compute the determinant and inverse of the matrix of single-nucleon\namplitudes.,label={label_3}]\nCALL getzvecs(s,sI,zvecs,zwave,Lt,0,pion,ztau2x2,n_f)            \nCALL getzdualvecs(s,sI,zdualvecs,zdualwave,Lt,0,pion,ztau2x2,n_f)\nCALL getinvcorr(zvecs,zdualvecs,zldeter,zcorrmatrix,zcorrinv,Lt)\n\naldeterabs = DBLE(zldeter)\nzdeterphase = CDEXP((0.D0,1.D0)*DIMAG(zldeter))\nact = bose - aldeterabs\n\\end{lstlisting}\n\n\\section{Importance sampling}\n\nWe do importance sampling according to the positive measure \n\\begin{equation}\n|Z(L_t)|\\exp{\\left[-S_{ss}(s)\n-S_{s_Is_I}(s_I)\n-S_{\\pi_I\\pi_I}(\\pi_I)\\right]},\n\\end{equation} \nand use hybrid Monte Carlo to do global updates of the auxiliary and pion\nfields. The hybrid Monte Carlo~(HMC) algorithm\n\\cite{Scalettar:1986uy,Gottlieb:1987mq,Duane:1987de} is efficient in quickly generating decorrelated configurations for\neach\nauxiliary and pion field.  Here we describe the\nupdating algorithm for the $s$ field. The updating of the $s_I$ and $\\pi_I$\nfields proceed in a very similar fashion.  In\ngeneral terms, the HMC algorithm can be described by means of a probability\nweight $P(s)$\n\\begin{equation}\nP(s)\\propto\\exp[-V(s)],\n\\end{equation}\nwhere $V(s)$ is in general a non-local function of the field $s({{\\bf n}%\n,n_t}),$ and a molecular dynamics~(MD) Hamiltonian,\n\\begin{equation}\n\\quad\\quad H(s,p)\\equiv\\frac{1}{2}\\sum_{{\\bf n},n_t%\n}\\left[p_s({{\\bf n},n_t})\\right]  ^{2}+V(s).\n\\end{equation}\nClassical Hamiltonian dynamics is introduced by defining\nthe\nmomentum $p_s({{\\bf n},n_t})$ conjugate to $s({{\\bf n},n_t})$.\n\nGiven an arbitrary initial configuration $s^{0}({{\\bf n},n_t})$, the\nconjugate momentum is chosen from a random Gaussian distribution according\nto\n\\begin{equation}\nP[p_s^{0}({\\bf n},n_t)]\\propto\\exp\\left\\{  -\\frac{1}{2}\\left[  p_s^{0}({\\bf\nn},n_t)\\right]  ^{2}\\right\\}  , \\label{Gdistr}%\n\\end{equation}\nafter which the Hamiltonian equations of motion are integrated numerically\nwith a small but nonzero step size $\\varepsilon_{\\mathrm{step}}$.  This method begins\nwith a\n\\textquotedblleft half-step\\textquotedblright\\ forward in the conjugate\nmomentum,\n\\begin{equation}\n\\tilde{p}_s^{0}({\\bf n},n_t)=p_s^{0}({\\bf n},n_t)-\\frac{\\varepsilon\n_{\\mathrm{step}}}{2}\\left[  \\frac{\\partial V(s)}{\\partial s({\\bf n},n_t%\n)}\\right]  _{s=s^{0}},\n\\end{equation}\nfollowed by repeated updates of $s$ and $\\tilde{p}_s$ according to\n\\begin{equation}\ns^{i+1}({\\bf n},n_t)=s^{i}({\\bf n},n_t)+\\varepsilon_{\\mathrm{step}}%\n\\tilde{p}^{i}_s({\\bf n},n_t),\\quad\\quad\\tilde{p}^{i+1}_s({\\bf n},n_t%\n)=\\tilde{p}^{i}_s({\\bf n},n_t)-\\varepsilon_{\\mathrm{step}}\\left[\n\\frac{\\partial V(s)}{\\partial s({\\bf n},n_t)}\\right]  _{s=s^{i+1}},\n\\end{equation}\nfor a specified number of steps $N_{\\mathrm{step}}$. This is followed by an additional half-step\nbackward in $\\tilde{p}_s$  given by\n\\begin{equation}\np_s^{N_{\\mathrm{step}}}({\\bf n},n_t)=\\tilde{p}_s^{N_{\\mathrm{step}}}(\\vec\n{n},n_t)+\\frac{\\varepsilon_{\\mathrm{step}}}{2}\\left[  \\frac{\\partial\nV(s)}{\\partial s({\\bf n},n_t)}\\right]  _{s=s^{0}}.\n\\end{equation}\n\nFor algorithmic efficiency the length of such an MD \\textquotedblleft trajectory\\textquotedblright%\n\\ should be taken large enough to ensure decorrelation between\nsuccessive configurations of the auxiliary field. The evolved configuration\nis\nthen subjected to a \\textquotedblleft Metropolis test\\textquotedblright%\n\\ against a random number $r\\in\\lbrack0,1)$.  The new configuration is accepted if\n\\begin{equation}\nr<\\exp\\left[  -H(s^{N_{\\mathrm{step}}},p^{N_{\\rm step }}_s)+H(s^{0}%\n,p_s^{0})\\right]  .\n\\end{equation}\nIt\nshould be noted that although $H$ is in principle conserved in the MD\nevolution, the truncation error of the leapfrog method introduces a systematic\nerror. The Metropolis test eliminates the need for extrapolation in\n$\\varepsilon_{\\mathrm{step}}$. \n\nIn our case $\\exp[-V(s)]$ has the form \n\\begin{equation}\n|Z(L_t)|\\exp{\\left[-S_{ss}(s)\n-S_{s_Is_I}(s_I)\n-S_{\\pi_I\\pi_I}(\\pi_I)\\right]},\n\\end{equation} \nwhere $Z(L_t)$ is the determinant\nof an $A\\times A$ matrix of single-nucleon amplitudes {\\bf M}.  The derivative of\n$V_{}$ is then computed using%\n\\begin{align}\n\\frac{\\partial V_{}(s)}{\\partial s({\\bf n},n_t)}  &  =\\frac{\\partial\nS_{ss}(s)}{\\partial s({\\bf n},n_t)}- \\frac{\\partial {\\rm Re} \\left[\n\\ln \\left( \\det\\mathbf{M} \\right) \\right]}{\\partial s(\\vec\n{n},n_t)} \\nonumber\\\\\n  &  =\\frac{\\partial\nS_{ss}(s)}{\\partial s({\\bf n},n_t)}- {\\rm Re} \\left[ \\frac{1}{\\det\\mathbf{M}}\\sum\n_{k,l}\\frac{\\partial\\det\\mathbf{M}}{\\partial \\mathbf{M}\n_{kl}}\\frac{\\partial  \\mathbf{M}_{kl}}{\\partial s(\\vec\n{n},n_t)} \\right] \\nonumber\\\\\n&  =\\frac{\\partial S_{ss}(s)}{\\partial s({\\bf n},n_t)}- {\\rm Re} \\left[\n\\sum_{k,l}\n\\mathbf{M}^{-1}  _{lk}\\frac{\\partial  \\mathbf{M}\n_{kl}}{\\partial s({\\bf n},n_t)} \\right].\n\\end{align}\n\nIn the following we show sample code \\ref{label_4} calculating the\nquadratic part of the action due to the auxiliary fields and pion fields,\n\\begin{equation}\n\\frac{1}{2}\\sum_{{\\bf n},n_t}\\left[p_s({{\\bf n},n_t})\\right]^{2}+\\frac{1}{2}\\sum_{{\\bf n},n_t,I}\\left[  p_{s_I}({{\\bf n},n_t})\\right]^{2}+\\frac{1}{2}\\sum_{{\\bf n},n_t,I}\\left[p_{\\pi_I}({{\\bf n},n_t})\\right]^{2}+S_{ss}(s) + S_{s_Is_I}(s_I) + S_{\\pi_I\\pi_I}(\\pi_I).\n\\end{equation}\nIn the code we have found it convenient to rescale the pion field by a factor of $\\sqrt{q_{\\pi}}$ where \n\\begin{equation}\nq_{\\pi}=\\alpha_{t} \\left( m_{\\pi}^2 + 6w_0 \\right).\n\\end{equation}\n\n\\begin{lstlisting}[language=Fortran,caption=Sample code calculating the\nquadratic part of the action due to the auxiliary fields and pion fields.,label={label_4}]\nbose = 0.D0\nDO nt = 0,Lt-1\n  DO nz = 0,L-1; DO ny = 0,L-1; DO nx = 0,L-1\n    bose = bose &\n      + s(nx,ny,nz,nt)**2.D0/2.D0 &\n      + p_s(nx,ny,nz,nt)**2.D0/2.D0\n    DO iso = 1,3\n      bose = bose &\n        + sI(nx,ny,nz,nt,iso)**2.D0/2.D0 &\n        + p_sI(nx,ny,nz,nt,iso)**2.D0/2.D0 &\n        + pion(nx,ny,nz,nt,iso)**2.D0/2.D0 &\n        + atovera/qpi3*pion(nx,ny,nz,nt,iso)*( &\n        - w1_P*pion(MOD(nx+1,L),ny,nz,nt,iso) &\n        - w1_P*pion(nx,MOD(ny+1,L),nz,nt,iso) &\n        - w1_P*pion(nx,ny,MOD(nz+1,L),nt,iso) &\n        + w2_P*pion(MOD(nx+2,L),ny,nz,nt,iso) &\n        + w2_P*pion(nx,MOD(ny+2,L),nz,nt,iso) &\n        + w2_P*pion(nx,ny,MOD(nz+2,L),nt,iso) &\n        - w3_P*pion(MOD(nx+3,L),ny,nz,nt,iso) &\n        - w3_P*pion(nx,MOD(ny+3,L),nz,nt,iso) &\n        - w3_P*pion(nx,ny,MOD(nz+3,L),nt,iso)) &\n        + p_pion(nx,ny,nz,nt,iso)**2.D0/2.D0\n    END DO\n  END DO; END DO; END DO\nEND DO\n\n\\end{lstlisting}     \n\nIn following we show sample code \\ref{label_5} which calculates \n\\begin{equation}\n\\left[  \\frac{\\partial V(s)}{\\partial s({\\bf n},n_t%\n)}\\right]  _{s=s^{0}}\n\\end{equation}\nand uses it to compute the\n half-step\\ forward in the conjugate\nmomentum,\n\\begin{equation}\n\\tilde{p}_s^{0}({\\bf n},n_t)=p_s^{0}({\\bf n},n_t)-\\frac{\\varepsilon\n_{\\mathrm{step}}}{2}\\left[  \\frac{\\partial V(s)}{\\partial s({\\bf n},n_t%\n)}\\right]  _{s=s^{0}}.\n\\end{equation}\n\n\\begin{lstlisting}[language=Fortran,caption=Sample code computing derivative with respect to the auxiliary field and half-step forward in the conjugate momentum.,label={label_5}]\n\nDO npart1 = 0,n_f-1; DO npart2 = 0,n_f-1\n  zdcorrmatrix(npart2,npart1) = 0.D0\n  DO ni = 0,1; DO ns = 0,1\n    zdcorrmatrix(npart2,npart1) = &\n      zdcorrmatrix(npart2,npart1) + &\n      zdualvecs(nx,ny,nz,nt+1,ns,ni,npart2) &\n      *zvecs(nx,ny,nz,nt,ns,ni,npart1) &\n      *CDSQRT(-c0*atovera*(1.D0,0.D0))/L**3\n  END DO; END DO\nEND DO; END DO\n           \ndVds(nx,ny,nz,nt) = s(nx,ny,nz,nt) \n\nDO npart1 = 0,n_f-1; DO npart2 = 0,n_f-1\n  dVds(nx,ny,nz,nt) = dVds(nx,ny,nz,nt) &\n    - DBLE(zdcorrmatrix(npart2,npart1) &\n    *zcorrinv(npart1,npart2))\nEND DO; END DO\n                 \np_sHMC(nx,ny,nz,nt,0) = &\n  p_s(nx,ny,nz,nt) - 0.5D0*eHMC*dVds(nx,ny,nz,nt)\n  \n\\end{lstlisting}\n\nIn following code \\ref{label_6} we show an example code which performs  the Metropolis test%\n\\ against a random number $r\\in\\lbrack0,1)$, with the new configuration being accepted if\n\\begin{equation}\nr<\\exp\\left[  -H(s^{N_{\\mathrm{step}}},p^{N_{\\rm step }}_s)+H(s^{0}%\n,p_s^{0})\\right].\n\\end{equation}\n\n\\begin{lstlisting}[language=Fortran,caption=Sample code which performs  the Metropolis acceptance test,label={label_6}]\nIF (ntrial .eq. 1 .or. grnd() .lt. DEXP(-actnew+act)) THEN\n\n  accept = accept + 1.\n\n  DO nt = 0,Lt-1\n    DO nz = 0,L-1; DO ny = 0,L-1; DO nx = 0,L-1      \n      s(nx,ny,nz,nt) = snew(nx,ny,nz,nt)\n    END DO; END DO; END DO\n  END DO\n  \n  DO nt = 0,Lt-1\n    DO nz = 0,L-1; DO ny = 0,L-1; DO nx = 0,L-1      \n      DO iso = 1,3\n        sI(nx,ny,nz,nt,iso) = sInew(nx,ny,nz,nt,iso)\n        pion(nx,ny,nz,nt,iso) = pionnew(nx,ny,nz,nt,iso)\n      END DO\n    END DO; END DO; END DO\n  END DO\n  \n  aldeterabs = aldeternewabs\n  zdeterphase = zdeternewphase\n            \nEND IF\n\\end{lstlisting}\n\nAlthough the Monte Carlo importance sampling uses only the absolute value of the amplitude, the complex phase\nof the amplitude is treated as an observable and is collected  with each\nconfiguration of the auxiliary and pion fields.\n\n\\section{Exercises}\n\n\\begin{prob}\n\\label{prob6.1}\nWrite a lattice hybrid Monte Carlo code which performs updates of the lattice action according to only the quadratic part of the action due to the auxiliary fields and pions,\n\\begin{equation}\n\\frac{1}{2}\\sum_{{\\bf n},n_t}\\left[p_s({{\\bf n},n_t})\\right]^{2}+\\frac{1}{2}\\sum_{{\\bf\nn},n_t,I}\\left[  p_{s_I}({{\\bf n},n_t})\\right]^{2}+\\frac{1}{2}\\sum_{{\\bf\nn},n_t,I}\\left[p_{\\pi_I}({{\\bf n},n_t})\\right]^{2}+S_{ss}(s) + S_{s_Is_I}(s_I)\n+ S_{\\pi_I\\pi_I}(\\pi_I).\n\\end{equation} \nVerify that the change in the action produced by the hybrid Monte Carlo update is scaling quadratically in the step size, $\\varepsilon_{\\mathrm{step}}$, in the limit $\\varepsilon_{\\mathrm{step}} \\rightarrow 0$ with $N_{\\rm step}\\varepsilon_{\\mathrm{step}}$ held fixed. \n\\end{prob} \n\n\\begin{prob}\n\\label{prob6.2}\nWrite a function or subroutine that generates initial/final single-nucleon states on the lattice corresponding to a Slater-determinant state with one neutron spin-up and one neutron spin-down, both with zero momentum. \\end{prob} \n\n\\begin{prob}\n\\label{prob6.3}\nWrite a function or subroutine that generates initial/final single-nucleon\nstates on the lattice corresponding to a Slater-determinant state with one proton spin-up and one neutron spin-up, both with zero momentum.\\end{prob}\n\n\\begin{prob}\n\\label{prob6.4}\nWrite a function or subroutine that generates initial/final single-nucleon\nstates on the lattice corresponding to a Slater-determinant state of four\nnucleons --- proton spin-up, proton spin-down, neutron spin-up, and neutron\nspin-down --- each with zero momentum. \\end{prob}\n\n\\begin{prob}\n\\label{prob6.5}\nWrite a function or subroutine that extends the sample code \\ref{label_1}  to repeatedly multiply the auxiliary-field transfer matrix on the left starting from the initial single-nucleon wave functions.  Include the contributions from the auxiliary fields $s$ and $s_I$ as well as the pion\n field $\\pi_I$.  \n\\end{prob}\n\n\\begin{prob}\n\\label{prob6.6}\nWrite a function or subroutine that extends the sample code \\ref{label_2}  to\nrepeatedly multiply the auxiliary-field transfer matrix on the right starting from the final\nsingle-nucleon wave functions.  Include the contributions from the auxiliary\nfields $s$ and $s_I$ as well as the pion\n field $\\pi_I$.  \n\\end{prob}\n\n\\begin{prob}\n\\label{prob6.7}\nUse the Slater-determinant states constructed in Probs.~\\ref{prob6.2}, \\ref{prob6.3}, \\ref{prob6.4} as initial and final states.  In each case apply the functions or subroutines written in Prob.~\\ref{prob6.5} and Prob.~\\ref{prob6.6} with all coupling constants set to zero.  Verify that in each case the initial/final state is the ground state of the non-interacting system with energy equal to zero.\n\\end{prob}\n\n\\begin{prob}\n\\label{prob6.8}\nUse the Slater-determinant states constructed in Probs.~\\ref{prob6.2}, \\ref{prob6.3},\n\\ref{prob6.4} as initial and final states.  Using the functions or subroutines written in Prob.~\\ref{prob6.5} and Prob.~\\ref{prob6.6}, extend the sample code  \\ref{label_5} to compute the derivatives of $V(s)$ with respect to $s({\\bf n},n_t)$, $s_I({\\bf n},n_t)$, and $\\pi_I({\\bf n},n_t)$.\n\\end{prob}\n\n\\begin{prob}\n\\label{prob6.9}\nTake the code you have written for Prob.~\\ref{prob6.8} and complete the remaining steps needed to do hybrid Monte Carlo updates for $s$, $s_I$, and $\\pi_I$. Verify that the change in the action produced by the hybrid Monte Carlo update\nis scaling quadratically in $\\varepsilon_{\\mathrm{step}}$ in the limit\n$\\varepsilon_{\\mathrm{step}} \\rightarrow 0$ with $N_{\\rm step}\\varepsilon_{\\mathrm{step}}$\nheld fixed.\n\\end{prob}   \n\n\\begin{prob}\n\\label{prob6.10}\nTake the code you have written for Prob.~\\ref{prob6.9} and complete the remaining\nsteps needed to calculate the energy of the ground state by computing the ratio of the amplitudes $Z(L_t)/Z(L_t-1)$.\n\\end{prob}\n\n\\section{Codes and Benchmarks}\n\nComplete verisons of the codes discussed in this chapter and developed in the exercises can be found online via \\href{https://github.com/ManyBodyPhysics/LectureNotesPhysics/tree/master/Programs/Chapter6-programs}{this link}.  In order to run the codes, one must first copy the corresponding initial/final wavefunctions (waveinit\\_1S0.f90, waveinit\\_3S1.f90, or waveinit\\_He4.f90) into the file waveinit.f90 used by the main program nuclei.f90. The number of nucleons is controlled by the parameter n\\_f in input.f90 and must correspond to the number of nucleons in waveinit.f90.  \n\nAs an example we show the beginning of the input file input.f90 for a two nucleon state with spatial lattice spacing $a = 1/(100\\;{\\rm MeV})$, temporal lattice spacing $a_t = 1/(150\\;{\\rm MeV})$, box size $L = 4a$, and Euclidean time extent $L_t = 6a_t$.  We use an $O(a^{4})$-improved lattice action for the nucleon hopping coefficients, $O(a^{0})$-improved lattice action for the pion hopping coefficients, and $O(a^{0})$-improved lattice action for the pion-nucleon coupling. The coefficient of the $^1S_0$ contact interaction is tuned to the physical $^1S_0$ $n-p$ scattering length and is $-5.615\\times 10^{-5}\\;{\\rm MeV}^{-2}$.  The coefficient of the $^3S_1$ contact interaction is tuned to the deuteron binding energy at infinite volume and is $-6.543\\times 10^{-5}\\;{\\rm MeV}^{-2}$.\n\n\\begin{lstlisting}[language=Fortran,caption=Parameter declarations at the beginning of the file input.f90.]\n  parameter(n_f = 2)\n  parameter(L = 4)\n  parameter(Lt = 6)\n  parameter(cutoff = 100.D0, temporalcutoff = 150.D0)\n  parameter(improveN = 2)\n  parameter(improveP = 0)\n  parameter(improveD = 0)\n  parameter(c1S0_phys = -5.615D-5)\n  parameter(c3S1_phys = -6.543D-5)\n \n\\end{lstlisting}\n\nUsing these values for the parameters of the lattice action, we now present some benchmark values which can be used to test the nuclear lattice simulations in the two-nucleon system.  The values presented in these benchmarks are computed using exact calculations of the two-nucleon transfer matrix.  They provide a useful independent check that there are no errors in the Monte Carlo simulations.  In Table~\\ref{1S0} we show the energies for the $^1S_0$ spin combination\nof two nucleons.  The initial state is one\nneutron spin-up and one neutron spin-down, both at zero momentum, for $L=4a$\nand various values of\n$L_t$.  The energies are extracted by computing the\nratio of amplitudes $Z(L_t)/Z(L_t-1)$ and setting equal to $\\exp(-E\\alpha_t)$.  \n\n\\begin{table}[tbh]\n\\caption{Benchmark energies for the $^1S_0$ spin combination\nof two nucleons.  The initial state is one\nneutron spin-up and one neutron spin-down, both at zero momentum, for $L=4a$\nand various values of $L_t$.}%\n\\begin{center}\n\\begin{tabular}{p{1.5cm}p{1.5cm}}\n\\hline\\noalign{\\smallskip}\n$L_t$ & ${\\rm energy (MeV)}$ \\\\\n\\noalign{\\smallskip}\\svhline\\noalign{\\smallskip}\n$2$ & $-1.0915$  \\\\\n$4$ & $-1.3987$  \\\\\n$6$ & $-1.6209$  \\\\\n$8$ & $-1.7929$  \\\\ \n$10$ & $-1.9296$  \\\\\n$12$ & $-2.0398$   \\\\\n$14$ & $-2.1291$   \\\\\n$16$ & $-2.2018$   \\\\\n$18$ & $-2.2610$  \\\\\n$20$ & $-2.3094$ \\\\\n\\noalign{\\smallskip}\n\\hline\\noalign{\\smallskip}\n\\end{tabular}\n\\end{center}\n\\label{1S0}%\n\\end{table}\n\nWe show the energies for the $^3S_1$ spin combination\nof two nucleons in Table~\\ref{3S1}.  The initial state is one\nproton spin-up and one neutron spin-up, both at zero momentum, for $L=4a$\nand various values of\n$L_t$.  The energies are extracted by computing the\nratio of amplitudes $Z(L_t)/Z(L_t-1)$ and setting equal to $\\exp(-E\\alpha_t)$. \n\n\n\\begin{table}[tbh]\n\\caption{Benchmark energies for the $^3S_1$ spin combination\nof two nucleons.  The initial state is one\nproton spin-up and one neutron spin-up, both at zero momentum, for $L=4a$\nand various values of\n$L_t$.}%\n\\begin{center}\n\\begin{tabular}{p{1.5cm}p{1.5cm}}\n\\hline\\noalign{\\smallskip}\n$L_t$ & ${\\rm energy (MeV)}$ \\\\\n\\noalign{\\smallskip}\\svhline\\noalign{\\smallskip}\n$2$ & $-1.4446 $  \\\\\n$4$ & $-2.0400$  \\\\\n$6$ & $-2.4774$  \\\\\n$8$ & $-2.8331$  \\\\ \n$10$ & $-3.1341$  \\\\\n$12$ & $-3.3925$   \\\\\n$14$ & $-3.6151$   \\\\\n$16$ & $-3.8069 $   \\\\\n$18$ & $-3.9718$  \\\\\n$20$ & $-4.1132$ \\\\\n\\noalign{\\smallskip}\\hline\\noalign{\\smallskip}\n\\end{tabular}\n\\end{center}\n\\label{3S1}%\n\\end{table}\n\n\n\\begin{acknowledgement}\nThe author is grateful for discussions with Amy Nicholson and Morten\nHjorth-Jensen.  He is also greatly indebted to his collaborators Jose\nAlarc{\\'o}n, Dechuan Du, Serdar Elhatisari, Evgeny Epelbaum, Nico\nKlein, Hermann Krebs, Timo L{\\\"a}hde, Ning Li, Bing-nan Lu, Thomas\nLuu, Ulf-G. Mei{\\ss}ner, Alexander Rokash, and Gautam Rupak.  Partial\nfinancial support provided by the U.S. Department of Energy\n(DE-FG02-03ER41260).  Computational resources were provided by the\nJ\\\"{u}lich Supercomputing Centre.\n\\end{acknowledgement}\n\n\\bibliographystyle{spphys} \n\\bibliography{lnp}\n", "meta": {"hexsha": "2efc64d23a295ff27f16e8987f9324038b543203", "size": 56834, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/src/chapter6.tex", "max_stars_repo_name": "cpmoca/LectureNotesPhysics", "max_stars_repo_head_hexsha": "8e9f8c5d7f163ea10b14002850f7c79acc4513df", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2016-11-22T09:42:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T01:33:46.000Z", "max_issues_repo_path": "doc/src/chapter6.tex", "max_issues_repo_name": "cpmoca/LectureNotesPhysics", "max_issues_repo_head_hexsha": "8e9f8c5d7f163ea10b14002850f7c79acc4513df", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/src/chapter6.tex", "max_forks_repo_name": "cpmoca/LectureNotesPhysics", "max_forks_repo_head_hexsha": "8e9f8c5d7f163ea10b14002850f7c79acc4513df", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 25, "max_forks_repo_forks_event_min_datetime": "2016-05-24T22:54:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T00:08:19.000Z", "avg_line_length": 48.1644067797, "max_line_length": 1249, "alphanum_fraction": 0.7071647253, "num_tokens": 18923, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3481511269961152}}
{"text": "\\chapter{Bundle Adjustment}\n\\label{ch:bundle_adjustment}\n\n\\definecolor{lgray}{gray}{0.95}\n\nSatellite position and orientation errors have a direct effect on the\naccuracy of digital elevation models produced by the Stereo Pipeline.\nIf they're not corrected, these uncertainties will result in\nsystematic errors in the overall position and slope of the \\ac{DEM}.  Severe\ndistortions can occur as well, resulting in twisted or ``taco shaped''\n\\acp{DEM}, though in most cases these effects are quite subtle and hard to\ndetect.\n\nThe Stereo Pipeline includes a powerful suite of tools for correcting\ncamera position and orientation errors using a process called\n\\emph{bundle adjustment}. Bundle adjustment is the process of\nsimultaneously adjusting the properties of many cameras and the 3D\nlocations of the objects they see in order to minimize the error\nbetween the estimated, back-projected pixel location of the 3D\nobjects and their actual measured location in the captured images.\n\nThat complex process can be boiled down to this simple idea: bundle\nadjustment ensures that observations in multiple different images of a\nsingle ground feature are self-consistent. If they are not consistent,\nthen the position and orientation of the cameras as well as the 3D\nposition of the feature must be adjusted until they are.  This\noptimization is carried out along with thousands (or more) of similar\nconstraints involving many different features observed in other\nimages.  Bundle adjustment is very powerful and versatile: it can\noperate on just two overlapping images, or on thousands.\n\n\\begin{figure}[bt]\n  \\centering\n  \\includegraphics[width=8cm]{images/ba_orig}\n  \\includegraphics[width=8cm]{images/ba_adjusted}\n  \\caption{Bundle adjustment is illustrated here using a color-mapped,\n    hill-shaded DEM mosaic from Apollo 15 Orbit 33 imagery. (a)\n    Prior to bundle adjustment, large discontinuities can exist between\n    overlapping DEMs made from different images. (b) After bundle\n    adjustment, DEM alignment errors are minimized, and no longer visible.}\n  \\label{fig:bundle_adjustment}\n\\end{figure}\n\nBundle adjustment can also take advantage of \\acp{GCP}, which are\n3D locations of features that are known a priori (often by measuring\nthem by hand in another existing \\ac{DEM}). \\acp{GCP} can improve the internal\nconsistency of your \\ac{DEM} or align your \\ac{DEM} to an existing data\nproduct. Finally, even though bundle adjustment calculates the\nlocations of the 3D objects it views, only the final properties of\nthe cameras are recorded for use by the Ames Stereo Pipeline. Those\nproperties can be loaded into the \\texttt{stereo} program which\nuses its own method for triangulating 3D feature locations.\n\nWhen using the Stereo Pipeline, bundle adjustment is an optional step\nbetween the capture of images and the creation of \\acp{DEM}. The bundle\nadjustment process described below should be completed prior to\nrunning the \\texttt{stereo} command.\n\nAlthough bundle adjustment is not a required step for generating\n\\acp{DEM}, it is {\\em highly recommended} for users who plan to\ncreate \\acp{DEM} for scientific analysis and publication.  Incorporating\nbundle adjustment into the stereo work flow not only results in\n\\acp{DEM} that are more internally consistent, it is also the correct\nway to co-register your \\acp{DEM} with other existing data sets and\ngeodetic control networks.\n\nAt the moment however, Bundle Adjustment does not automatically work\nagainst outside DEMs from sources such as laser altimeters. Hand\npicked \\acp{GCP} are the only way for \\acp{ASP} to register to those\ntypes of sources.\n\n\\subsection{A deeper understanding}\n\nIn bundle adjustment the position and orientation of each camera\nstation are determined jointly with the 3D position of a set of image\ntie-points points chosen in the overlapping regions between\nimages. Tie points, like they sound, tie individual camera images\ntogether. Their physical manifestation would be a rock or small crater\nthan can be observed across multiple images.\n\nTie-points can be automatically extracted using Vision Workbench's\nInterest Point module or through a number of outside methods such as\nthe famous SURF\\citep{surf08}. Creating a tie point is a three step\nprocess. First, all images are processed for their natural {\\it\n  'interesting'} points. In most algorithms, an interest point is\ndefined as a place where image gradients accumulate together into a\npeak. These interesting points are then described by the texture that\nsurrounds them. Finally the described interesting points are matched\nacross the multiple images. A single matched pair of interest points\nis now a tie point to use in bundle adjustment. In application, there\nis also a little filtering of the tie points with RANSAC\n\\citep{fischler81}.\n\n\\begin{figure}[b!]\n  \\begin{center}\n  \\includegraphics[trim=20mm 20mm 20mm 15mm,clip,width=6in]{images/ba_feature_observation.pdf}\n  \\end{center}\n  \\caption{ A feature observation in bundle adjustment, from \\citet{moore09} }\n  \\label{fig:ba_feature}\n\\end{figure}\n\nOur bundle adjustment approach follows the method described\nin~\\cite{triggs00} and determines the best camera parameters that\nminimize the projection error given by ${\\bf \\epsilon} =\n\\sum_k\\sum_j(I_k-I(C_j, X_k))^2$ where $I_k$ are the tie points on the\nimage plane, $C_j$ are the camera parameters, and $X_k$ are the 3D\npositions associated with features $I_k$. $I(C_j, X_k)$ is an image\nformation model (i.e. forward projection) for a given camera and 3D\npoint. To recap, it projects the 3D point, $X_k$, into the camera with\nparameters $C_j$. This produces a predicted image location for the 3D\npoint that is compared against the observed location, $I_k$. We reduce\nthis error with the Levenberg-Marquardt algorithm (LMA). Speed is\nimproved by using sparse methods as described in \\citet{hartley04}.\n\nEven though the arithmetic for bundle adjustment sounds clever. There\nare faults with the base implementation. Imagine a case where all\ncameras and 3D points were collapsed into a single point. If you\nevaluate the above cost function, you'll find that the error is indeed\nzero. Sadly, this is not the correct solution if the images were taken\nfrom orbit. Another example is if a translation was applied equally to\nall 3D points and camera locations. This again would not effect the\ncost function. This fault comes from bundle adjustment's inability to\ncontrol scale and translation of the solution. It will correct\ngeometric shape of the problem. Yet it can not guarantee that solution\nwill have correct scale and translation.\n\nWe attempt to fix this problem by adding two additional cost functions\nto bundle adjustment. First of which is ${\\bf \\epsilon} =\n\\sum_j(C_j^{initial}-C_j)^2$. This constrains camera parameters to\nstay relatively close to their initial values. Second, a small handful\nof 3D ground control points can be chosen by hand and added to the\nerror metric as ${\\bf \\epsilon} = \\sum_k(X_k^{gcp}-X_k)^2$ to\nconstrain these points to known locations in the planetary coordinate\nframe. A physical example of a ground control point could be the\nlocation of a lander that has a well known location. In the cost\nfunctions discussed above, errors are weighted by the inverse\ncovariance of the measurement that gave rise to the constraint.\n\nLike other iterative optimization methods, there are several\nconditions that will cause bundle adjustment to terminate.  When\nupdates to parameters become insignificantly small or when the error,\n${\\bf \\epsilon}$, becomes insignificantly small, then the algorithm\nhas converged and the result is most likely as good as it will get.\nHowever, the algorithm will also terminate when the number of\niterations becomes too large, in which case bundle adjustment may or\nmay not have finished refining the parameters of the cameras.\n\n\\section{Performing bundle adjustment with isis\\_adjust}\n\nFirst off, let it be known that USGS's \\ac{ISIS} has its own bundle\nadjustment software called \\texttt{jigsaw}. It has a long history and\nis supported by a team of skilled developers. Despite this, Ames\nStereo Pipeline provides an alternative called \\texttt{isis\\_adjust}\nthat has its own benefits.\n\nLike \\texttt{jigsaw}, the \\texttt{isis\\_adjust} program is designed to\nperform bundle adjustment on images supported by \\ac{ISIS} 3\nsoftware package.  The \\texttt{isis\\_adjust} program does not\ndiscriminate based on camera type.  It can perform bundle adjustment\non images from line-scan imagers like \\ac{MOC}, \\ac{LROC} NAC,\n\\ac{HiRISE}, and the \\ac{CTX}. The \\texttt{isis\\_adjust} program can\nalso perform bundle adjustment on traditional frame cameras\n(e.g. Apollo Metric Camera). Theoretically it should also work with\npush-frame imagers like the \\ac{THEMIS} VIS, and \\ac{LROC} WAC, though\nthis is untested.\n\nThe \\texttt{isis\\_adjust} program works by first converting all\npixel measurements in an image to measurements defined on the ideal\nfocal plane using millimeters and the \\ac{ET}. The \\ac{ET} is the\nabsolute second at which that pixel measurement was recorded on the\ncamera.  For a frame camera, all of the pixels are captured at the\nsame time so the \\ac{ET} will be identical for all measurements on\nthe image.  For pushbroom, pushframe, or other cameras which build\nup their `image' over time, different parts of the image will have\ndifferent ET values.  For example, on a MOC image between the first\nand last line about 5 seconds of \\ac{ET} will have elapsed.\n\nWhen \\texttt{isis\\_adjust} calculates the partial derivatives of the\nforward projection of a point, it uses an ideal pinhole camera model.\nThe properties of this model are defined as properties of the subject\ncamera at the specified \\ac{ET} for the current measure plus the\ncorrection function, $f(t)$, that \\texttt{isis\\_adjust} is solving\nfor.  Many forms of $f(t)$ could be used; the only limit is the\nnumber of parameters in the equations. Some initial work hints that\nanything greater than a second order polynomial becomes an ill-posed\nproblem, but we hope to investigate this further in the future.\n\nOur \\texttt{isis\\_adjust} implements multiple bundle adjustment\nalgorithms which can be selected from the command line. It implements\nthe standard sparse algorithm that can be found in literature. It also\nimplements our research work into robust cost functions. This allows\nthe algorithm to ignore measurements that it thinks to be outliers.\n\nFinally, \\texttt{isis\\_adjust} stores its solution for a camera as a\ndelta that can be added to the camera's original SPICE in a separate\nfile. Those files have the extension \\texttt{*.isis\\_adjust}. This is\nless than ideal and one feature that we value in \\ac{ISIS}'s\n\\texttt{jigsaw}. Their software overwrites the SPICE information in\nthe cube file. This means that \\texttt{jigsaw} results can be used in\nother \\ac{ISIS} programs like \\texttt{cam2map}. This is not the case\nwith \\texttt{isis\\_adjust}'s results.\n\n\\subsection{Options}\n\nThe following is a listing and explanation of the options that can be\ngiven to \\texttt{isis\\_adjust} on the command line. These options are\nnot required.\n\n\\begin{description}\n\n\\item[\\texttt{-\\/-cnet|-c \\textit{control-network-file}}] \\hfill \\\\\n  \\emph{Optional.} This option will force {\\tt isis\\_adjust} to\n  use a pre-built built control network. This control network can\n  either be in the \\ac{USGS} \\ac{ISIS} ``cnet'' format or in the binary Vision\n  Workbench format.\n\n  If no control network is supplied using this option, {\\tt\n    isis\\_adjust} will look for match files in the current working\n  directory with base filenames that match the input images.  The\n  \\texttt{isis\\_adjust} program will then create its own control\n  network file and save it as \\texttt{isis\\_adjust.cnet}.\n\n\\item[\\texttt{-\\/-cost-function L1|L2|Cauchy|Huber|PseudoHuber(=L2)} ] \\hfill \\\\\n  Sets the cost function used for bundle adjustment. Default is \\texttt{L2}\n  which is the normal squared error. The full list of available options\n  are:\n\n  \\begin{description}\n    \\item[L1] Proportional Error\n    \\item[L2] Squared Error and Default Option.\n    \\item[Cauchy]\n    \\item[Huber]\n    \\item[PseudoHuber]\n  \\end{description}\n\n  The options towards the end of the list are robust cost functions\n  that deal better with non-ideal data that has outliers. These robust\n  cost functions are performed by post-weighting the original errors yet\n  still using equations derived for squared error.\n\n\\item[\\texttt{-\\/-bundle-adjuster Ref|Sparse|RobustRef|RobustSparse|RobustSparseKGCP(=Sparse)}] \\hfill \\\\\n  Sets the bundle adjustment code to be used. The standard to use is\n  \\texttt{Sparse}, which is a traditional squared error derived method that\n  utilizes sparse matrices to obtain speed. Here are the complete list\n  of options:\n\n  \\begin{description}\n    \\item[Ref] Reference implementation that doesn't use sparse methods.\n    \\item[Sparse] Default implementation.\n    \\item[RobustRef]\n    \\item[RobustSparse]\n    \\item[RobustSparseKGCP]\n  \\end{description}\n\n  The ending methods are experimental student-t derived bundle\n  adjustment algorithms. Using the experimental robust algorithm\n  overrides the {\\tt cost-function} option. The last two bundle\n  adjustment algorithms are still experimental and are a work in\n  progress.\n\n\\item[\\texttt{-\\/-disable-camera-const}] \\hfill \\\\\n  \\emph{Optional.} This disables the camera constraint error. Useful\n  for debugging and just exploring what are the effects of this cost\n  function.\n\n\\item[\\texttt{-\\/-disable-gcp-const}] \\hfill \\\\\n  \\emph{Optional.} This disables the \\ac{GCP} constraint error even\n  if \\acp{GCP} are provided. Useful for debugging and just exploring\n  what the effects are of \\acp{GCP}.\n\n\\item[\\texttt{-\\/-gcp-scalar \\textit{multiplier(=1)}}] \\hfill \\\\\n  \\emph{Optional.} Sets the multiplier that is used to adjust the\n  sigma (or uncertainty) of the \\aclp{GCP}. The sigmas of\n  \\aclp{GCP} are defined in the \\ac{GCP} data file, so this\n  option is useful when debugging for universally scaling \\ac{GCP} sigmas\n  up or down.\n\n\\item[\\texttt{-\\/-lambda|-l \\textit{float}}] \\hfill \\\\\n  \\emph{Optional.} This sets the starting value for $\\lambda$: the\n  parameter in the Levenberg Marquardt (LMA) optimization algorithm\n  that selects between Gauss-Newton optimization and gradient\n  descent. This parameter evolves over time on its own, but this\n  argument can be used to override its initial value. \\emph{This is an\n  advanced setting, not recommended for normal use.}\n\n\\item[\\texttt{-\\/-min-matches \\textit{integer(=5)}}] \\hfill \\\\\n  Set the minimum number of tie-points that are required between a\n  pair of images for them to be included in the control network. This\n  option is useful for eliminating tie-points from image pairs that\n  have only a handful of poor or erroneous matches.\n\n\\item[\\texttt{-\\/-max-iterations \\textit{integer(=25)}}] \\hfill \\\\\n  Sets the maximum number of iterations for bundle adjustment. The\n  number of required iterations will vary by problem size, so this\n  parameter allows the user to decide how much time they're willing\n  to dedicate to the correction of the data.  We have found that 20\n  iterations suffices for small problems with 10 or fewer images, and\n  tens or hundreds of iterations may be required for problems with\n  hundreds or thousands of images.\n\n\\item[\\texttt{-\\/-poly-order \\textit{integer(=0)}}] \\hfill \\\\\n  \\emph{Optional.} Sets the order of the polynomial that is used for\n  adjustment. Using zero means only apply offset to the camera\n  parameters that are not time dependent. That setting is recommend\n  for frame cameras. Linescan imagers should using either a first\n  order polynomial or a second order. Increasing this number too high can\n  lead to a problem that is ill-defined and would prevent the algorithm\n  from converging on a solution. \\emph{Initial work suggest that anything\n    beyond a 2nd order polynomial would be ill-defined. 3rd order may\n    work with a good dose of ground control points.}\n\n\\item[\\texttt{-\\/-position-sigma \\textit{float(=100)}}] \\hfill \\\\\n  Sets the sigma (or uncertainty) of the spacecraft position in\n  units of meters.\n\n\\item[\\texttt{-\\/-pose-sigma \\textit{float(=0.1)}}] \\hfill \\\\\n  Sets the sigma (or uncertainty) of the spacecraft pose in units\n  of radians.\n\n\\item[\\texttt{-\\/-report-level|-r \\textit{integer(=10)}}] \\hfill \\\\\n  \\emph{Optional.} Sets the report level for the final bundle\n  adjustment report.  This report is saved as\n  \\texttt{isis\\_adjust.report}. Report levels available are:\n\n  \\begin{description}\n    \\item[0   - CommandLine Error and Final report]\n    \\item[10  - CommandLine Iteration Error (default)]\n    \\item[20  - Write Report file]\n    \\item[25  - \\textnormal{\\emph{In development}}]\n    \\item[30  - Write Stereo Triangulation Error]\n    \\item[35  - \\textnormal{\\emph{In development}}]\n    \\item[100 - Debug, Write Error Vectors (big human readable)]\n    \\item[110 - Debug, Write Jacobian Matrix (massive human readable)]\n  \\end{description}\n\n\\item[\\texttt{-\\/-robust-threshold \\textit{float(=10)}}] \\hfill \\\\\n  Sets the robust threshold; an additional parameter specifically for\n  the \\texttt{PseudoHuber}, \\texttt{Huber}, and \\texttt{Cauchy} arguments to the   \\texttt{-\\/-cost-function} option.\n\n\\item[\\texttt{-\\/-save-iteration-data|-s}] \\hfill \\\\\n  \\emph{Optional.} Use to write {\\tt bundlevis} visualization files.\n\n\\item[\\texttt{-\\/-seed-with-previous}] \\hfill \\\\\n  \\emph{Optional.} Loads up the previous {\\tt isis\\_adjust} session's\n  adjustment file and uses them as a starting point for this session.\n\n\\item[\\texttt{-\\/-write-isis-cnet-also}] \\hfill \\\\\n  \\emph{Optional.} Write an \\ac{ISIS} \\ac{PVL} style control network file to\n  \\texttt{isis\\_adjust.net}. The output file is very large compared to\n  the binary output, \\texttt{isis\\_adjust.cnet}, but is human readable\n  and compatible with the \\ac{ISIS} 3 \\texttt{qnet} tool.\n\n\\item[\\texttt{-\\/-write-kml [0|1(=0)]}] \\hfill \\\\\n  \\emph{Optional.} Providing this option with a zero will have the\n  program write a \\ac{KML} file showing the location of all the \\acp{GCP}\n  and be colored according to their final error. Providing this\n  option with a one will have this perform as before, but also have it\n  write all of the 3D point estimates. This is useful for debugging and\n  for having a quick visualization of where stress points might exist in\n  a bundle adjustment problem when there are many cameras.\n\n\\item[\\texttt{-\\/-help|-h}] \\hfill \\\\\n  Provides a shortened list of the above.\n\n\\end{description}\n\n\\section{Visualizing bundle adjustment with bundlevis}\n\nThe \\texttt{bundlevis} program is used to visualize the process of\nbundle adjustment. It will show an animated, fully interactive 3D\nscene containing all the 3D points and cameras across all iterations\nof bundle adjustment.  This tool is used to quickly determine if\nbundle adjustment was successful.  If something does go wrong,\n\\texttt{bundlevis} can be a powerful debugging tool for identifying\nthe problem.\n\n\\begin{figure}[b!]\n  \\begin{center}\n  \\includegraphics[width=5in]{images/bundlevis_apollo.png}\n  \\end{center}\n  \\caption{ A screenshot of \\texttt{bundlevis} visualizing the bundle\n    adjustment of imagery from the Apollo 15 Metric Camera (orbit\n    33). }\n  \\label{fig:bundlevis}\n\\end{figure}\n\nOnce \\texttt{bundlevis} has loaded the data from a bundle adjustment run,\nthe user can click on and inspect the position of 3D points that are\nin purple and play back the iterations using the keyboard. Double\nclicking on a camera will cause lines to be drawn to each point viewed\nby the camera. Clicking on a 3D point causes lines to be drawn to all\ncameras that view the point.\n\nBundle adjustment can fail in a variety of different ways, but users\nshould be aware of two common failure modes.  The first is segmentation;\nwhere tie points will split into two or more distinct groups,\nproducing cliffs between or clumps among points. This is usually\ncaused by insufficient matches between a pair of images in your\ncontrol network.  You may need to choose some tie-points between\nthese images by hand or add additional images that overlap with the\nproblem area.\n\nThe second common sign of a failure is a point cloud explosion (the\nresulting terrain looks unrecognizably noisy). This most often results\nfrom a high number of outlying, bad tie-point measurements that the\nbundle adjustment algorithm can't recover from. These bad constraints\ncan be removed by hand or mitigated using one of the robust cost modes\n(e.g. by using the \\texttt{-\\/-cost-function} argument for\n\\texttt{isis\\_adjust}).\n\n\\subsection{Options}\n\nThe following is a listing and explanation of the options\nthat can be given to \\texttt{bundlevis} from the command line.\n\n\\begin{description}\n\n\\item[\\texttt{-\\/-camera-iteration-file|-c \\textit{bundlevis-camera-iteration-file}}] \\hfill \\\\\n  \\emph{Optional.} Supply a camera iteration file that was produced by\n       \\texttt{isis\\_adjust}.  \\texttt{bundlevis} will only draw cameras\n       if you supply a camera iteration file.\n\n\\item[\\texttt{-\\/-points-iteration-file|-p \\textit{bundlevis-point-iteration-file}}] \\hfill \\\\\n  \\emph{Optional.} Supply a point iteration file that was produced by\n       \\texttt{isis\\_adjust}.  \\texttt{bundlevis} will only draw 3D points\n       if you supply a point iteration file.\n\n\\item[\\texttt{-\\/-control-network-file|-n \\textit{Vision-Workbench-binary-control-network-file}}] \\hfill \\\\\n  \\emph{Optional.} Supply a control network file that was produced by\n       {\\tt isis\\_adjust}.  This allows {\\tt bundlevis} to show the\n       relationship between points and cameras when used in\n       conjunction with \\texttt{-\\/-camera-iteration-file} and\n       \\texttt{-\\/-points-iteration-file}.\n\n\\item[\\texttt{-\\/-additional-pnt-files \\textit{bundlevis-point-iteration-files}}] \\hfill \\\\\n  \\emph{Optional.} Supply additional points to be animated alongside\n  the camera and 3D points.  The files given must be in the same\n  format as a \\texttt{bundlevis} point iteration file and have the same number\n  of iterations.\n\n\\item[\\texttt{-\\/-fullscreen}] \\hfill \\\\\n  \\emph{Optional.} Displays \\texttt{bundlevis} using the entire screen;\n  otherwise the program loads in a window. \\emph{The fullscreen option\n    does not work correctly with dual screen systems.}\n\n\\item[\\texttt{-\\/-stereo}] \\hfill \\\\\n  \\emph{Optional.} Render the 3D scene in red/blue anaglyph mode.\n\n\\item[\\texttt{-\\/-show-moon}] \\hfill \\\\\n  \\emph{Optional.} Draws a wireframe sphere with a radius of 1737.3~km\n  that represents the Moon.\n\n\\item[\\texttt{-\\/-show-mars}] \\hfill \\\\\n  \\emph{Optional.} Draws a wireframe sphere with a radius of 3397~km\n  that represents Mars.\n\n\\item[\\texttt{-\\/-show-earth}] \\hfill \\\\\n  \\emph{Optional.} Draws a wireframe sphere that represents the Earth.\n\n\\end{description}\n\n\\subsection{Controls}\n\nOnce \\texttt{bundlevis} is running, there are several controls that\ncan be used to interface with the program. There are the playback\ncontrols, jump-to-frame controls, and the mouse.\n\n\\paragraph{Playback Controls}\n\nPlayback controls are similar to those in the popular Winamp program;\narranged on the keyboard like the controls on a tape deck.\n\n\\newenvironment{myindentpar}[1]\n               {\\begin{list}{}\n                   {\\setlength{\\leftmargin}{#1}}\n                 \\item[]\n               }\n               {\\end{list}}\n\n\\begin{myindentpar}{3cm}\n\\begin{description}\n  \\item[Z] Step back one iteration\n  \\item[X] Play\n  \\item[C] Pause\n  \\item[V] Stop \\emph{(which is the same as Pause except that\n    bundlevis goes back to iteration 0)}\n  \\item[B] Step forward one iteration\n\\end{description}\n\\end{myindentpar}\n\n\\paragraph{Jump-to-Frame Controls}\nJump-to-Frame controls are the numbers \\textbf{1-9} along the top of\nthe keyboard. Pressing \\textbf{1} will display the very first\niteration. Pressing \\textbf{9} will display the very last\niteration. Pressing \\textbf{2} through \\textbf{8} will display\niterations that are somewhere in between based on the value of the\nnumber. Finally, pressing \\textbf{0} will cause \\texttt{bundlevis} to\ndisplay the points at their very last iteration with an additional\ntail pointing back to the starting position of the points in the first\niteration.\n\n\\paragraph{Mouse}\nThe mouse is used to move around the model, and has the same controls\nfound in many 3D environments (e.g. \\texttt{osgviewer}). Moving the\nmouse with the \\textbf{left mouse button} held down will cause the\nmodel to rotate.  Moving with the \\textbf{right mouse button} pressed\nwill zoom, and moving with the \\textbf{middle mouse button} will\ntranslate. Alternatively for systems where the mouse is\nbutton-challenged, \\textbf{option + mouse} is translation and\n\\textbf{command + mouse} is zoom.\n\nDouble clicking with the mouse on a point or camera will allow the\nuser to query entities in the model.  A double click will cause the\npoint number and camera number to be printed to the terminal. The\nnumber identifier for a given camera or point will also appear when\nthe viewer is zoomed in on that entity.\n\n\\section{Examples of Use}\n\\label{sec:ba_example}\n\n\\subsection{Processing Mars Orbital Camera}\n\nWhat follows is an example of bundle adjustment using two \\ac{MOC}\nimages of the south Cydonia region. We use images M10/00254 and\nR09/01059. These images are available from NASA's \\ac{PDS} (the\n\\ac{ISIS} \\texttt{mocproc} program will operate on either the IMQ\nor IMG format files, we use the \\texttt{.imq} below in the example).\nFor reference, the following \\ac{ISIS} commands are how to convert\nthe \\ac{MOC} images to \\ac{ISIS} cubes.\n\n\\begin{verbatim}\n  ISIS 3> mocproc from= m1000254.imq to= m1000254.cub mapping=no\n  ISIS 3> mocproc from= r0901059.imq to= r0901059.cub mapping=no\n\\end{verbatim}\n\nYou will note that the resulting images are not map projected. Bundle\nadjustment requires the ability to project arbitrary 3D points into\nthe camera frame. The process of map projecting an image dissociates\nthe camera model from the image. Map projecting can be perceived as\nthe generation of a new infinitely large camera sensor that is\nperfectly parallel to the surface of its subject ( and thus spherical\n). That makes it extremely hard to project a random point into\nthe camera's original model. The math would follow the transformation from\nprojection into the camera frame, then projected back down to surface\nthat ISIS uses, then finally up into the infinitely large sensor. The\n\\texttt{isis\\_adjust} program does not support this.\n\nAt this point, we need to automatically generate tie-points between\nthese two images. This can be done using the \\texttt{ipfind} and\n\\texttt{ipmatch} utilities. These tools do not reliably (currently)\nwork with photometrically calibrated images, so we must first convert\nthese images to a standard format using the \\ac{ISIS} program\n\\texttt{isis2std} or \\texttt{gdal\\_translate}. The utility\n\\texttt{gdal\\_translate} is the preferred option as it is able to\nproduce lossless compressed images.\n\n\\begin{verbatim}\n  ISIS 3> isis2std from= m1000254.cub to= m1000254.tif format=TIFF\n  ISIS 3> isis2std from= r0901059.cub to= r0901059.tif format=TIFF\n\\end{verbatim}\n\nor ...\n\n\\begin{verbatim}\n  ISIS 3> gdal_translate -of GTiff -scale -ot Byte\n              -co COMPRESS=LZW -co TILED=yes m1000254.cub m1000254.tif\n  ISIS 3> gdal_translate -of GTiff -scale -ot Byte\n              -co COMPRESS=LZW -co TILED=yes r0901059.cub r0901059.tif\n\\end{verbatim}\n\nHere is how to process those newly created TIFF files for tie-points\nusing the Interest Point Module tools from Vision Workbench.\n\n\\begin{verbatim}\n  > ipfind  m1000254.tif r0901059.tif -g 1.2\n  > ipmatch m1000254.tif r0901059.tif -d -r homography -i 30\n\\end{verbatim}\n\n\\begin{center}\n\\fcolorbox{black}{lgray}{ \\begin{minipage}{5.5in}\n\n    Be aware that the tie-point tools available in Vision Workbench do\n    not always produce enough matches for bundle adjustment. An\n    alternative would be to use outside code such as SURF. We have\n    included a patch at the end of the book that converts SURF output\n    to a Vision Workbench style match file. In extreme cases, users\n    can be forced to make measurements themselves. This can be\n    performed with \\ac{ISIS}'s \\texttt{qnet} progam.  \\\\ \\\\ For this\n    example we found that \\texttt{ipfind} and \\texttt{ipmatch} work\n    great. Expect to find approximately 100 matched points. Your\n    results will be slightly different due to the random nature of\n    RANSAC.\n\n\\end{minipage}}\n\\end{center}\n\nFinally it is time to start bundle adjustment. There are many options\nthat can be used at this stage.  We have chosen those required to\ncreate visualization data for \\texttt{bundlevis}.  We have also set\nthe maximum iterations to 100 and chose the option to create a\ndetailed report file of \\texttt{isis\\_adjust}'s results.\n\n\\begin{verbatim}\n  ISIS 3> isis_adjust *.cub -s --max 30 -r 50\n\\end{verbatim}\n\nBefore you hit enter, notice that we are not feeding the interest\npoint match files to \\texttt{isis\\_adjust}. Instead, we only provide\nthe camera files. During run time, the program will see that it\ndoesn't have any image measurements in the form of a control\nnetwork. In that case it will attempt to build its own by searching\nthe current working directory for \\texttt{*.match} files.\n\nNow you have permission to run \\texttt{isis\\_adjust}. You'll see the\ncommand will produce considerable debugging output and will place many\noutput files in the current working directory. If you look through the\noutput in the terminal or alternatively in the output report file,\n\\texttt{isis\\_adjust.report}, you'll see that the problem did not\nconverge but reduced most of the error in the first 40 iterations\n(again, your results may vary slightly). The lack of convergence is\nworrisome and a few (like 3) ground control points would probably help\nconsiderably.  Notice that the error improved only slightly after\nthose first 40 iterations, but the shape of the pointcloud and the\ncamera paths changed considerably. This untwisting of the cameras can\nbe seen next in \\texttt{bundlevis}.\n\nVisualizing all of the data that was exported for \\texttt{bundlevis}\ncan be carried out as follows:\n\n\\begin{verbatim}\n  > bundlevis -p iterPointsParam.txt -c iterCameraParam.txt \\\n              -n isis_adjust.cnet\n\\end{verbatim}\n\nPress escape to exit out of \\texttt{bundlevis} when finished.  You may\nalso want to try viewing the data with a wire-frame of Mars to give\nsome perspective. Note, you will have to zoom in very far since the\nsize of a MOC frame is quite small relative to the size of Mars!\n\n\\begin{verbatim}\n  > bundlevis -p iterPointsParam.txt -c iterCameraParam.txt \\\n              -n isis_adjust.cnet --show-mars\n\\end{verbatim}\n\nProducing a DEM using the newly created corrections is the same as\ncovered in the Tutorial on page \\pageref{ch:tutorial}, with one small\ndifference: \\texttt{stereo} needs to know of the existence of the\ncorrection files, \\texttt{m1000254.isis\\_adjust} and\n\\texttt{r0901059.isis\\_adjust}.\n\n\\begin{verbatim}\n  ISIS 3> stereo m1000254.cub r0901059.cub m1000254.isis_adjust \\\n                 r0901059.isis_adjust MOC_RESULTS/M1000254_R0901059\n\\end{verbatim}\n\nThe two new arguments (\\texttt{*.isis\\_adjust}) provide\n\\texttt{stereo} with the necessary corrections. When providing outside\ncamera models for images, they are always the 3rd and 4th argument for\n\\texttt{stereo}. This is also how \\texttt{stereo} can be made to\noperate on images from standard consumer cameras.\n\n\\subsection{Processing with Ground Control Points}\n\nGround control point files describe a single point in the world\nthat is seen by 1 or more cameras. How they are measured in the\nfirst place is up to the user. We use a manual process of comparing\neach image to a respected map projected image and then recording\nthe latitude, longitude, and altitude of the point(s). The maps to\nregister against can be anything, but it is recommended to register\nagainst a product with a high amount of cartographic stability and\naccuracy.  For terrestrial work, we would use a \\ac{USGS} product\nthat can provide imagery that is registered to LIDAR height\nmeasurements.\n\nUnlike match files, ground control points must specifically be given\nto \\texttt{isis\\_adjust} from the command line, but in no particular\norder. Ground control point files are written with the extension\n\\texttt{.gcp}. Below is an example of a ground control point file that\nwas created to control a series of Apollo Metric Camera images from\nseveral Apollo 15 orbits.\n\n\\begin{verbatim}\n    -52.8452 27.2561 1735999 300 300 500\n    sub4-AS15-M-2086.cub     210.9   3565.0\n    sub4-AS15-M-2087.cub     1476.9  3579.0\n    sub4-AS15-M-2088.cub     2798.9  3586.8\n    sub4-AS15-M-2089.cub     4133.5  3588.6\n    sub4-AS15-M-2344.cub     906.9   3874.8\n    sub4-AS15-M-2345.cub     2204.2  3913.9\n    sub4-AS15-M-2482.cub     939.8   4348.0\n    sub4-AS15-M-2483.cub     2282.0  4340.7\n    sub4-AS15-M-2484.cub     3642.1  4330.9\n\\end{verbatim}\n\nThe first line of a \\texttt{.gcp} file is like a header line and\nis different from the remaining lines.  The first line defines the\nworld location of the ground control point, and the rest of the\nlines define the image locations of the ground control points. Here\nare what the columns mean for the first line.\n\n\\begin{myindentpar}{2cm}\n\\begin{description}\n  \\item[Column 1:] Longitude in degrees\n  \\item[Column 2:] Latitude in degrees\n  \\item[Column 3:] Radius in meters\n  \\item[Column 4:] Sigma (or uncertainty) in meters for Local X axis\n  \\item[Column 5:] Sigma (or uncertainty) in meters for Local Y axis\n  \\item[Column 6:] Sigma (or uncertainty) in meters for Local Z axis\n\\end{description}\n\\end{myindentpar}\n\nThe other lines describe where this \\ac{GCP} is found in each image:\n\n\\begin{myindentpar}{2cm}\n\\begin{description}\n  \\item[Column 1:] Image name\n  \\item[Column 2:] Sample (X) image measurement\n  \\item[Column 3:] Line (Y) image measurement\n\\end{description}\n\\end{myindentpar}\n\nMake a {\\tt .gcp} file for every ground control point, then be sure\nto feed them as an input to {\\tt isis\\_adjust}. Remember that you\ncan scale the sigma of all ground control points by using the {\\tt\n-\\/-gcp-scalar} flag. This can save time by allowing you to make\nadjustments without needing to edit all of the files individually.\n\n\\subsection{Sharing Data with ISIS 3's qnet program}\n\n\\ac{ISIS} contains a program called \\texttt{qnet} whose purpose is\nto create and edit \\ac{ISIS} style control network files. To share\na control network with \\texttt{qnet}, you will need to save our\ncontrol network in the \\ac{ISIS} format. If bundle adjustment has\nalready been performed once and if we want to simply convert the\ncontrol network for use in \\texttt{qnet}, you can use this command\nto save an \\ac{ISIS} style control network:\n\n\\begin{verbatim}\n  ISIS 3> isis_adjust -c isis_adjust.cnet --write-isis-cnet-also *.cub\n\\end{verbatim}\n\nOtherwise if this is the first time performing bundle adjustment and a\ncontrol network does not already exist, use:\n\n\\begin{verbatim}\n  ISIS 3> isis_adjust --write-isis-cnet-also *.cub\n\\end{verbatim}\n\nThere should now be an \\texttt{isis\\_adjust.net} file in the project's\ndirectory. It will be quite a bit larger than the other control\nnetwork file since it is stored as ASCII text, but it can be read\nand edited with a text editor. Before starting \\texttt{qnet}, there\nis one additional preparation that must be performed. \\ac{ISIS}'s\n\\texttt{qnet} requires a text file listing of all the cubes used\nby the control network. Here's how to create one:\n\n\\begin{verbatim}\n  > ls *.cub > list_of_cubes.lis\n\\end{verbatim}\n\nNow, start up \\texttt{qnet} without any command line arguments. Click\nFile$\\rightarrow$Open. It will first ask for the list of cubes. Refer\nit to the newly created \\texttt{list\\_of\\_cubes.lis}. Next it will ask for\nthe control network. Give it \\texttt{isis\\_adjust.net}.\n\n\\begin{center}\n\\fcolorbox{black}{lgray}{ \\begin{minipage}{5.5in}\n\n    At this time \\texttt{qnet} does not work with the Apollo Metric\n    Camera's cube files. When loading the text file listing of cubes\n    it will issue an error about invalid serial numbers for the listed\n    cube files.  % (03/11/09)\n\n\\end{minipage}}\n\\end{center}\n\nWhen finished, save the new control network file. Here's how to use\nthe new control network in \\texttt{isis\\_adjust}:\n\n\\begin{verbatim}\n  ISIS 3> isis_adjust -c the_new_control_network.net *.cub\n\\end{verbatim}\n\nTake note that to distinguish \\ac{ISIS} style control network files\nfrom Stereo Pipeline style control network files is by the file\nextension. \\ac{ISIS} control networks have the extension of\n\\texttt{.net} and can be read with a text editor. Stereo Pipeline's\ncontrol networks have the extension \\texttt{.cnet} and are binary\nformat files.\n", "meta": {"hexsha": "1d208c138057f7b77aa461f55f952930eff3cc02", "size": 36743, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/book/bundle_adjustment.tex", "max_stars_repo_name": "nasa/StereoPipeline", "max_stars_repo_head_hexsha": "8b9c0bcab258c41d10cb2973d97722765072a7bf", "max_stars_repo_licenses": ["NASA-1.3"], "max_stars_count": 29, "max_stars_repo_stars_event_min_datetime": "2015-05-06T01:28:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T22:55:29.000Z", "max_issues_repo_path": "docs/book/bundle_adjustment.tex", "max_issues_repo_name": "imagineagents/StereoPipeline", "max_issues_repo_head_hexsha": "8b9c0bcab258c41d10cb2973d97722765072a7bf", "max_issues_repo_licenses": ["NASA-1.3"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/book/bundle_adjustment.tex", "max_forks_repo_name": "imagineagents/StereoPipeline", "max_forks_repo_head_hexsha": "8b9c0bcab258c41d10cb2973d97722765072a7bf", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2015-01-15T04:20:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-10T01:31:17.000Z", "avg_line_length": 46.5101265823, "max_line_length": 117, "alphanum_fraction": 0.765941812, "num_tokens": 9509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.3481511269961152}}
{"text": "\\documentclass{article}\n\\usepackage[a4paper, left=25.4mm, top=25.4mm, right=25.4mm, bottom=25.4mm]{geometry}\n\\usepackage[shortlabels]{enumitem}\n\\usepackage{adjustbox}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{amsthm}\n\\usepackage{authoraftertitle}\n\\usepackage{blindtext}\n\\usepackage{booktabs}\n\\usepackage{bussproofs}\n\\usepackage{cancel}\n\\usepackage{color}\n\\usepackage{fancyhdr}\n\\usepackage{graphicx}\n\\usepackage{latexsym}\n\\usepackage{listings}\n\\usepackage{multicol}\n\\usepackage{newpxtext}\n%\\usepackage{newpxmath}\n\\usepackage{subcaption}\n\\usepackage{textcomp}\n\\usepackage{textgreek}\n\\usepackage{vwcol}\n\\newcommand\\tab[1]{\\hspace*{#1}}\n\\newcommand\\lowermidtilde{\\raisebox{-0.8ex}{\\textasciitilde}}\n\\newcommand\\midtilde{\\raisebox{-0.6ex}{\\textasciitilde}}\n\\newcommand{\\partfarrow}{\\rightharpoonup}\n\\newcommand{\\partf}{\\rightharpoonup\\!\\!\\!\\!\\!\\!\\!\\!\\!\\raisebox{2.5pt}{$\\rightharpoonup$}}\n\\renewcommand{\\thesubsection}{\\arabic{subsection}}\n\\renewcommand{\\headrulewidth}{0pt}\n\\renewcommand{\\ttdefault}{pcr}\n\\renewcommand{\\sfdefault}{lmss}\n\\renewcommand\\qedsymbol{Q.E.D.}\n\\definecolor{gray}{rgb}{0.5,0.5,0.5}\n\\lstset{\n    basicstyle=\\ttfamily,\n    commentstyle=\\color{gray}\\ttfamily,\n    keywordstyle=\\ttfamily\\bfseries,\n    columns=flexible,\n    numbers=left,\n    numberstyle=\\tiny,\n    firstnumber=0,\n    showstringspaces=false,\n}\n\\setlist{  \n    listparindent=\\parindent,\n    align=parleft,\n}\n\n\\author{Victor Zhao\\\\xz398@cam.ac.uk}\n\n\\begin{document}\n\\centering\n\\section*{Types\\\\CST Part II Paper 8 \\& 9}\n\\MyAuthor\n\n\\justifying\n\n\\subsection{Simply-Typed $\\lambda$-Calculus}\n\n\\subsection*{Syntax}\n\n\\hspace{-1em}\n\\begin{tabular}{lccl}\nTypes   & $T$ & $::=$ & $1\\ |\\ 0\\ |\\ T_1\\times T_2\\ |\\ T_1+T_2\\ |\\ T_1\\to T_2$\\\\[0.5em]\nTerms   & $e$ & $::=$ & $x\\ |\\ \\langle\\rangle\\ |\\ \\langle e_1,e_2\\rangle\\ |\\ \\textsf{fst }e\\ |\\ \\textsf{snd }e\\ |\\ \\textsf{L }e\\ |\\ \\textsf{R }e\\ |\\ \\textsf{case}(e,\\textsf{L }x\\to e_1,\\textsf{R }y\\to e_2)$\\\\ \n        & {}  & $|$   & $\\lambda x:T.\\ e\\ |\\ e_1\\ e_2\\ |\\ \\textsf{abort}$\\\\[0.5em]\nValues  & $v$ & $::=$ & $\\langle\\rangle\\ |\\ \\langle v_1,v_2\\rangle\\ |\\ \\lambda x:T.\\ e\\ |\\ \\textsf{L }v\\ |\\ \\textsf{R }v$\\\\[0.5em] \nContexts & $\\Gamma$ & $::=$ & $\\cdot\\ |\\ \\Gamma,x:T$\n\\end{tabular} \n\n\\subsection*{Typing rules}\n\n(\\textsc{I}: introduction rule, \\textsc{E}: elimination rule, \\textsc{Hyp}: hypothesis)\n\\medbreak\n\\noindent\n\\AxiomC{{\\color{white} $\\langle\\rangle$}} % placeholder\n\\RightLabel{\\textsc{1I}}\n\\UnaryInfC{$\\Gamma\\vdash\\langle\\rangle:1$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{$\\Gamma\\vdash e_1:T_1$}\n\\AxiomC{$\\Gamma\\vdash e_2:T_2$}\n\\RightLabel{\\textsc{$\\times$I}}\n\\BinaryInfC{$\\Gamma\\vdash\\langle e_1, e_2\\rangle:1$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{$\\Gamma\\vdash e:T_1\\times T_2$} \n\\RightLabel{\\textsc{$\\times$E$_1$}}\n\\UnaryInfC{$\\Gamma\\vdash\\textsf{fst }e:T_1$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{$\\Gamma\\vdash e:T_1\\times T_2$} \n\\RightLabel{\\textsc{$\\times$E$_2$}}\n\\UnaryInfC{$\\Gamma\\vdash\\textsf{snd }e:T_2$}\n\\DisplayProof\\bigbreak %========================================================\n\\noindent\n\\AxiomC{$x:T\\in\\Gamma$} \n\\RightLabel{\\textsc{Hyp}}\n\\UnaryInfC{$\\Gamma\\vdash x:T$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{$\\Gamma,x:T\\vdash e:T'$} \n\\RightLabel{\\textsc{$\\to$I}}\n\\UnaryInfC{$\\Gamma\\vdash\\lambda x:T.\\ e:T\\to T'$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{$\\Gamma\\vdash e_1:T\\to T'$}\n\\AxiomC{$\\Gamma\\vdash e_2:T$}\n\\RightLabel{\\textsc{$\\to$E}}\n\\BinaryInfC{$\\Gamma\\vdash e_1\\ e_2:T'$}\n\\DisplayProof\\bigbreak %========================================================\n\\noindent\n\\AxiomC{$\\Gamma\\vdash e:T_1$} \n\\RightLabel{\\textsc{$+$I$_1$}}\n\\UnaryInfC{$\\Gamma\\vdash\\textsf{L }e:T_1+T_2$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{$\\Gamma\\vdash e:T_2$} \n\\RightLabel{\\textsc{$+$I$_2$}}\n\\UnaryInfC{$\\Gamma\\vdash\\textsf{R }e:T_1+T_2$}\n\\DisplayProof\\bigbreak %========================================================\n\\noindent\n\\AxiomC{$\\Gamma\\vdash e:T_1+T_2$}\n\\AxiomC{$\\Gamma,x:X\\vdash e_1:T$}\n\\AxiomC{$\\Gamma,x:X\\vdash e_2:T$}\n\\RightLabel{\\textsc{$+$E}}\n\\TrinaryInfC{$\\Gamma\\vdash\\textsf{case}(e,\\textsf{L }x\\to e_1,\\textsf{R }y\\to e_2):T$}\n\\DisplayProof\\bigbreak %========================================================\n\\noindent\n(No introduction for 0)$\\qquad$\n\\AxiomC{$\\Gamma\\vdash e:0$} \n\\RightLabel{\\textsc{0E}}\n\\UnaryInfC{$\\Gamma\\vdash\\textsf{abort }e:T$}\n\\DisplayProof\n\n\\subsection*{Operational semantics}\n\n(No rule for unit)$\\qquad$\n\\AxiomC{$e_1\\leadsto e_1'$}\n\\RightLabel{\\textsc{Pair1}}\n\\UnaryInfC{$\\langle e_1,e_2\\rangle\\leadsto\\langle e_1',e_2\\rangle$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{$e_2\\leadsto e_2'$}\n\\RightLabel{\\textsc{Pair2}}\n\\UnaryInfC{$\\langle v,e_2\\rangle\\leadsto\\langle v,e_2'\\rangle$}\n\\DisplayProof\\bigbreak %========================================================\n\\noindent\n\\AxiomC{{\\color{white} $\\langle\\rangle$}} % placeholder\n\\RightLabel{\\textsc{Proj1}}\n\\UnaryInfC{$\\textsf{fst }\\langle v_1,v_2\\rangle\\leadsto v_1$}\n\\DisplayProof$\\quad$ %==========================================================\n\\AxiomC{{\\color{white} $\\langle\\rangle$}} % placeholder\n\\RightLabel{\\textsc{Proj2}}\n\\UnaryInfC{$\\textsf{snd }\\langle v_1,v_2\\rangle\\leadsto v_2$}\n\\DisplayProof$\\quad$ %==========================================================\n\\AxiomC{$e\\leadsto e'$} \n\\RightLabel{\\textsc{Proj3}}\n\\UnaryInfC{$\\textsf{fst }e\\leadsto\\textsf{fst }e'$}\n\\DisplayProof$\\quad$ %==========================================================\n\\AxiomC{$e\\leadsto e'$} \n\\RightLabel{\\textsc{Proj4}}\n\\UnaryInfC{$\\textsf{snd }e\\leadsto\\textsf{snd }e'$}\n\\DisplayProof\\bigbreak %========================================================\n\\noindent\n\\AxiomC{$e\\leadsto e'$} \n\\RightLabel{\\textsc{Sum1}}\n\\UnaryInfC{$\\textsf{L }e\\leadsto\\textsf{L }e'$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{$e\\leadsto e'$} \n\\RightLabel{\\textsc{Sum2}}\n\\UnaryInfC{$\\textsf{R }e\\leadsto\\textsf{R }e'$}\n\\DisplayProof\\bigbreak %========================================================\n\\noindent\n\\AxiomC{$e\\leadsto e'$} \n\\RightLabel{\\textsc{Case1}}\n\\UnaryInfC{$\\textsf{case}(e,\\textsf{L }x\\to e_1,\\textsf{R }y\\to e_2)\\leadsto\\textsf{case}(e',\\textsf{L }x\\to e_1,\\textsf{R }y\\to e_2)$}\n\\DisplayProof\\bigbreak %========================================================\n\\noindent\n\\AxiomC{{\\color{white} $[]$}} %placeholder\n\\RightLabel{\\textsc{Case2}}\n\\UnaryInfC{$\\textsf{case}(\\textsf{L }v,\\textsf{L }x\\to e_1,\\textsf{R }y\\to e_2)\\leadsto[v/x]e_1$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{{\\color{white} $[]$}} %placeholder\n\\RightLabel{\\textsc{Case3}}\n\\UnaryInfC{$\\textsf{case}(\\textsf{R }v,\\textsf{L }x\\to e_1,\\textsf{R }y\\to e_2)\\leadsto[v/y]e_2$}\n\\DisplayProof\\bigbreak %========================================================\n\\noindent\n\\AxiomC{$e_1\\leadsto e_1'$}\n\\RightLabel{\\textsc{App1}}\n\\UnaryInfC{$e_1\\ e_2\\leadsto e_1'\\ e_2$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{$e_2\\leadsto e_2'$}\n\\RightLabel{\\textsc{App2}}\n\\UnaryInfC{$v\\ e_2\\leadsto v\\ e_2'$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{{\\color{white} $[]$}} %placeholder\n\\RightLabel{\\textsc{Fn}}\n\\UnaryInfC{$(\\lambda x:T.\\ e)\\ v\\leadsto[v/x]e$}\n\\DisplayProof\\bigbreak %========================================================\n\\noindent\n\\AxiomC{$e\\leadsto e'$} \n\\RightLabel{\\textsc{Abort}}\n\\UnaryInfC{$\\textsf{abort }e\\leadsto\\textsf{abort }e'$}\n\\DisplayProof\\newpage %=========================================================\n\n\\subsection{Polymorphic $\\lambda$-Calculus (System F)}\n\n\\subsection*{Syntax}\n\n\\hspace{-1em}\n\\begin{tabular}{lccl}\nTypes   & $T$ & $::=$ & $\\alpha\\ |\\ T_1\\to T_2\\ |\\ \\forall\\alpha.\\ T\\ |\\ \\exists\\alpha.\\ T$\\\\[0.5em]\nTerms   & $e$ & $::=$ & $x\\ |\\ \\lambda x:T.\\ e\\ |\\ e_1\\ e_2\\ |\\ \\Lambda\\alpha.\\ e\\ |\\ e\\ T\\ |\\ \\textsf{pack}_{\\alpha_\\text{abs}.T_\\text{sig}}(T_\\text{conc},e_\\text{impl})$\\\\\n{}      & {}  &  $|$  & $\\textsf{let pack}(\\alpha,x)=e_\\text{impl}\\textsf{ in }e_\\text{use}$\\\\[0.5em]\nValues  & $v$ & $::=$ & $\\lambda x:T.\\ e\\ |\\ \\Lambda\\alpha.\\ e\\ |\\ \\textsf{pack}_{\\alpha_\\text{abs}.T_\\text{sig}}(T_\\text{conc},v_\\text{impl})$\\\\[0.5em] \nType Contexts & $\\Theta$ & $::=$ & $\\cdot\\ |\\ \\Theta,\\alpha$\\\\[0.5em] \nTerm Contexts & $\\Gamma$ & $::=$ & $\\cdot\\ |\\ \\Gamma,x:T$\n\\end{tabular} \n\n\\subsection*{Well-formedness of types}\n\n\\vspace{0.5em}\n\\AxiomC{$\\alpha\\in\\Theta$} \n\\UnaryInfC{$\\Theta\\vdash\\alpha\\textsf{ type}$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{$\\Theta\\vdash T_1\\textsf{ type}$} \n\\AxiomC{$\\Theta\\vdash T_2\\textsf{ type}$} \n\\BinaryInfC{$\\Theta\\vdash T_1\\to T_2\\textsf{ type}$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{$\\Theta,\\alpha\\vdash T\\textsf{ type}$} \n\\UnaryInfC{$\\Theta\\vdash\\forall\\alpha.\\ T\\textsf{ type}$}\n\\DisplayProof\n\n\\subsection*{Well-formedness of term contexts}\n\n\\vspace{0.5em}\n\\AxiomC{{\\color{white} $\\Theta\\vdash\\Gamma$}} %placeholder \n\\UnaryInfC{$\\Theta\\vdash\\cdot\\textsf{ ctx}$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{$\\Theta\\vdash\\Gamma\\textsf{ ctx}$} \n\\AxiomC{$\\Theta\\vdash T\\textsf{ type}$} \n\\BinaryInfC{$\\Theta\\vdash\\Gamma,x:T\\textsf{ ctx}$}\n\\DisplayProof\n\n\\subsection*{Typing rules}\n\n\\vspace{0.5em}\n\\AxiomC{$x:T\\in\\Gamma$} \n\\RightLabel{\\textsc{Hyp}}\n\\UnaryInfC{$\\Theta;\\Gamma\\vdash x:T$}\n\\DisplayProof$\\qquad$ %==========================================================\n\\AxiomC{$\\Theta\\vdash T\\textsf{ type}$} \n\\AxiomC{$\\Theta;\\Gamma,x:T\\vdash e:T'$} \n\\RightLabel{\\textsc{$\\to$I}}\n\\BinaryInfC{$\\Theta;\\Gamma\\vdash\\lambda x:T.\\ e:T\\to T'$}\n\\DisplayProof\\bigbreak %========================================================\n\\noindent\n\\AxiomC{$\\Theta;\\Gamma\\vdash e_1:T\\to T'$}\n\\AxiomC{$\\Theta;\\Gamma\\vdash e_2:T$}\n\\RightLabel{\\textsc{$\\to$E}}\n\\BinaryInfC{$\\Theta;\\Gamma\\vdash e_1\\ e_2:T'$}\n\\DisplayProof\\bigbreak %========================================================\n\\noindent\n\\AxiomC{$\\Theta,\\alpha;\\Gamma\\vdash e:T$} \n\\RightLabel{\\textsc{$\\forall$I}}\n\\UnaryInfC{$\\Theta;\\Gamma\\vdash\\Lambda\\alpha.\\ e:\\forall\\alpha.\\ T$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{$\\Theta;\\Gamma\\vdash e:\\forall\\alpha.\\ T'$}\n\\AxiomC{$\\Theta\\vdash T\\textsf{ type}$}\n\\RightLabel{\\textsc{$\\forall$E}}\n\\BinaryInfC{$\\Theta;\\Gamma\\vdash e\\ T:[T/\\alpha]T'$}\n\\DisplayProof\\bigbreak %========================================================\n\\noindent\n\\AxiomC{$\\Theta,\\alpha_\\text{abs}\\vdash T_\\text{sig}\\textsf{ type}$} \n\\AxiomC{$\\Theta\\vdash T_\\text{conc}\\textsf{ type}$}\n\\AxiomC{$\\Theta;\\Gamma\\vdash e_\\text{impl}:[T_\\text{conc}/\\alpha_\\text{abs}]T_\\text{sig}$} \n\\RightLabel{\\textsc{$\\exists$I}}\n\\TrinaryInfC{$\\Theta;\\Gamma\\vdash\\textsf{pack}_{\\alpha_\\text{abs}.T_\\text{sig}}(T_\\text{conc},e_\\text{impl}):\\exists\\alpha_\\text{abs}.\\ T_\\text{sig}$}\n\\DisplayProof\\bigbreak %========================================================\n\\noindent\n\\AxiomC{$\\Theta;\\Gamma\\vdash e_\\text{impl}:\\exists\\alpha_\\text{abs}.\\ T_\\text{sig}$} \n\\AxiomC{$\\Theta,\\alpha;\\Gamma,x:[\\alpha_\\text{abs}/\\alpha]T_\\text{sig}\\vdash e_\\text{use}:T_\\text{use}$}\n\\AxiomC{$\\Theta\\vdash T_\\text{use}\\textsf{ type}$} \n\\RightLabel{\\textsc{$\\exists$E}}\n\\TrinaryInfC{$\\Theta;\\Gamma\\vdash\\textsf{let pack}(\\alpha,x)=e_\\text{impl}\\textsf{ in }e_\\text{use}:T_\\text{use}$}\n\\DisplayProof\n\n\\subsection*{Operational semantics}\n\n(\\textsc{Cong}: congruence rule, \\textsc{Eval}: evaluation rule)\n\\medbreak\n\\noindent\n\\AxiomC{$e_1\\leadsto e_1'$}\n\\RightLabel{\\textsc{CongFun}}\n\\UnaryInfC{$e_1\\ e_2\\leadsto e_1'\\ e_2$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{$e_2\\leadsto e_2'$}\n\\RightLabel{\\textsc{CongFunArg}}\n\\UnaryInfC{$v\\ e_2\\leadsto v\\ e_2'$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{{\\color{white} $[]$}} %placeholder\n\\RightLabel{\\textsc{FunEval}}\n\\UnaryInfC{$(\\lambda x:T.\\ e)\\ v\\leadsto[v/x]e$}\n\\DisplayProof\\bigbreak %========================================================\n\\noindent\n\\AxiomC{$e\\leadsto e'$}\n\\RightLabel{\\textsc{CongForall}}\n\\UnaryInfC{$e\\ T\\leadsto e'\\ T$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{{\\color{white} $[]$}} %placeholder\n\\RightLabel{\\textsc{ForallEval}}\n\\UnaryInfC{$(\\Lambda\\alpha.\\ e)\\ T\\leadsto[T/\\alpha]e$}\n\\DisplayProof\\bigbreak %========================================================\n\\noindent\n\\AxiomC{$e_\\text{impl}\\leadsto e'_\\text{impl}$}\n\\RightLabel{\\textsc{CongExists}}\n\\UnaryInfC{$\\textsf{pack}_{\\alpha_\\text{abs}.T_\\text{sig}}(T_\\text{conc},e_\\text{impl})\\leadsto\\textsf{pack}_{\\alpha_\\text{abs}.T_\\text{sig}}(T_\\text{conc},e'_\\text{impl})$}\n\\DisplayProof\\bigbreak %========================================================\n\\noindent\n\\AxiomC{$e_\\text{impl}\\leadsto e'_\\text{impl}$}\n\\RightLabel{\\textsc{CongExistsUnpack}}\n\\UnaryInfC{$\\textsf{let pack}(\\alpha,x)=e_\\text{impl}\\textsf{ in }e_\\text{use}\\leadsto\\textsf{let pack}(\\alpha,x)=e'_\\text{impl}\\textsf{ in }e_\\text{use}$}\n\\DisplayProof\\bigbreak %========================================================\n\\noindent\n\\AxiomC{{\\color{white} $[]$}} %placeholder\n\\RightLabel{\\textsc{ExistsEval}}\n\\UnaryInfC{$\\textsf{let pack}(\\alpha,x)=\\textsf{pack}_{\\alpha_\\text{abs}.T_\\text{sig}}(T_\\text{conc},v_\\text{impl})\\textsf{ in }e_\\text{use}\\leadsto [T_\\text{conc}/\\alpha,v_\\text{impl}/x]e_\\text{use}$}\n\\DisplayProof\n\n\\subsection*{Church encodings}\n\n\\subsubsection*{Pairs}\n\n\\hspace{-1em}\n\\begin{tabular}{lcl}\n$T_1\\times T_2$ & \\hspace{-0.5em}$\\triangleq$ & \\hspace{-0.5em}$\\forall\\alpha.\\ (T_1\\to T_2\\to\\alpha)\\to\\alpha$\\\\[0.5em]\n$\\langle e_1,e_2\\rangle$ & \\hspace{-0.5em}$\\triangleq$ & \\hspace{-0.5em}$\\Lambda\\alpha.\\ \\lambda k:T_1\\to T_2\\to\\alpha.\\ k\\ e\\ e'$\\\\[0.5em]\n\\textsf{fst }$e$ & \\hspace{-0.5em}$\\triangleq$ & \\hspace{-0.5em}$e\\ T_1\\ (\\lambda x:T_1.\\ \\lambda y:T_2.\\ x)$\\\\[0.5em]\n\\textsf{snd }$e$ & \\hspace{-0.5em}$\\triangleq$ & \\hspace{-0.5em}$e\\ T_2\\ (\\lambda x:T_1.\\ \\lambda y:T_2.\\ y)$\n\\end{tabular}\n\n\\subsubsection*{Sums}\n\n\\hspace{-1em}\n\\begin{tabular}{lcl}\n$T_1+T_2$ & \\hspace{-0.5em}$\\triangleq$ & \\hspace{-0.5em}$\\forall\\alpha.\\ (T_1\\to\\alpha)\\to(T_2\\to\\alpha)\\to\\alpha$\\\\[0.5em]\n\\textsf{L }$e$ & \\hspace{-0.5em}$\\triangleq$ & \\hspace{-0.5em}$\\Lambda\\alpha.\\ \\lambda f:T_1\\to\\alpha.\\ \\lambda g:T_2\\to\\alpha.\\ f\\ e$\\\\[0.5em]\n\\textsf{R }$e$ & \\hspace{-0.5em}$\\triangleq$ & \\hspace{-0.5em}$\\Lambda\\alpha.\\ \\lambda f:T_1\\to\\alpha.\\ \\lambda g:T_2\\to\\alpha.\\ g\\ e$\\\\[0.5em]\n\\end{tabular}\\\\\n$\\textsf{case}(e,\\textsf{L }x\\to e_1,\\textsf{R }y\\to e_2):T\\ \\triangleq\\ e\\ T\\ (\\lambda x:T_1\\to T.\\ e_1)\\ (\\lambda y:T_2\\to T.\\ e_2)$\n\n\\subsubsection*{Existential types}\n\n$\\exists\\alpha.\\ T_\\text{sig}\\ \\triangleq\\ \\forall\\beta.\\ (\\forall\\alpha.\\ T_\\text{sig}\\to\\beta)\\to\\beta$\\medbreak\n\\noindent\n$\\textsf{pack}_{\\alpha_\\text{abs}.T_\\text{sig}}(T_\\text{conc},e_\\text{impl})\\ \\triangleq\\ \\Lambda\\beta.\\ \\lambda k:\\forall\\alpha_\\text{abs}.\\ T_\\text{sig}\\to\\beta.\\ k\\ T_\\text{conc}\\ e_\\text{impl}$\\medbreak\n\\noindent\n$\\textsf{let pack}(\\alpha,x)=e_\\text{impl}\\textsf{ in }e_\\text{use}:T_\\text{use}\\ \\triangleq\\ e_\\text{impl}\\ T_\\text{use}\\ (\\Lambda\\alpha.\\ \\lambda x:T_\\text{sig}.\\ e_\\text{use})$\n\n\\subsubsection*{Booleans}\n\n\\hspace{-1em}\n\\begin{tabular}{lcl}\n\\textsf{bool} & \\hspace{-0.5em}$\\triangleq$ & \\hspace{-0.5em}$\\forall\\alpha.\\ \\alpha\\to\\alpha\\to\\alpha$\\\\[0.5em]\n\\textsf{True} & \\hspace{-0.5em}$\\triangleq$ & \\hspace{-0.5em}$\\Lambda\\alpha.\\ \\lambda x:\\alpha.\\ \\lambda y:\\alpha.\\ x$\\\\[0.5em]\n\\textsf{False} & \\hspace{-0.5em}$\\triangleq$ & \\hspace{-0.5em}$\\Lambda\\alpha.\\ \\lambda x:\\alpha.\\ \\lambda y:\\alpha.\\ y$\\\\[0.5em]\n\\end{tabular}\\\\\n\\textsf{if }$e$\\textsf{ then }$e_1$\\textsf{ else }$e_2:T\\ \\triangleq\\ e\\ T\\ e_1\\ e_2$\n\n\\subsubsection*{Natural numbers}\n\n\\hspace{-1em}\n\\begin{tabular}{lcl}\n$\\mathbb{N}$ & \\hspace{-0.5em}$\\triangleq$ & \\hspace{-0.5em}$\\forall\\alpha.\\ \\alpha\\to(\\alpha\\to\\alpha)\\to\\alpha$\\\\[0.5em]\n\\textsf{zero} & \\hspace{-0.5em}$\\triangleq$ & \\hspace{-0.5em}$\\Lambda\\alpha.\\ \\lambda z:\\alpha.\\ \\lambda s:\\alpha\\to\\alpha.\\ z$\\\\[0.5em]\n\\textsf{succ}$(e)$ & \\hspace{-0.5em}$\\triangleq$ & \\hspace{-0.5em}$\\Lambda\\alpha.\\ \\lambda z:\\alpha.\\ \\lambda s:\\alpha\\to\\alpha.\\ s\\ (e\\ \\alpha\\ z\\ s)$\\\\[0.5em]\n\\end{tabular}\\\\\n$\\textsf{iter}(e,\\textsf{zero}\\to e_\\textsf{z},\\textsf{succ}(x)\\to e_\\textsf{s}):T\\ \\triangleq\\ e\\ T\\ e_\\textsf{z}\\ (\\lambda x:T.\\ e_\\textsf{s})$\n\n\\subsubsection*{Lists}\n\n\\hspace{-1em}\n\\begin{tabular}{lcl}\n\\textsf{list }$T$ & \\hspace{-0.5em}$\\triangleq$ & \\hspace{-0.5em}$\\forall\\alpha.\\ \\alpha\\to(T\\to\\alpha\\to\\alpha)\\to\\alpha$\\\\[0.5em]\n$[]$ & \\hspace{-0.5em}$\\triangleq$ & \\hspace{-0.5em}$\\Lambda\\alpha.\\ \\lambda n:\\alpha.\\ \\lambda c:T\\to\\alpha\\to\\alpha.\\ n$\\\\[0.5em]\n$e::e'$ & \\hspace{-0.5em}$\\triangleq$ & \\hspace{-0.5em}$\\Lambda\\alpha.\\ \\lambda n:\\alpha.\\ \\lambda c:T\\to\\alpha\\to\\alpha.\\ c\\ e\\ (e'\\ \\alpha\\ n\\ c)$\\\\[0.5em]\n\\end{tabular}\\\\\n$\\textsf{fold}(e,[]\\to e_\\textsf{n},x::r\\to e_\\textsf{c}):T'\\ \\triangleq\\ e\\ T'\\ e_\\textsf{n}\\ (\\lambda x:T.\\ \\lambda r:T'.\\ e_\\textsf{c})$\n\n\\newpage\n\n\\subsection{Monadic $\\lambda$-Calculus for State}\n\n\\subsection*{Syntax}\n\n\\hspace{-1em}\n\\begin{tabular}{lccl}\nTypes          & $T$ & $::=$ & $1\\ |\\ \\mathbb{N}\\ |\\ T_1\\to T_2\\ |\\ \\textsf{ref }T\\ |\\ \\textsf{M }T$\\\\[0.5em]\nPure Terms     & $e$ & $::=$ & $\\langle\\rangle\\ |\\ n\\ |\\ \\lambda x:T.\\ e\\ |\\ e_1\\ e_2\\ |\\ l\\ |\\ \\{t\\}$\\\\[0.5em]\nImpure Terms   & $t$ & $::=$ & $\\textsf{new }e\\ |\\ !e\\ |\\ e:=e'\\ |\\ \\textsf{let }x=e;t\\ |\\ \\textsf{return }e$\\\\[0.5em]\nValues         & $v$ & $::=$ & $\\langle\\rangle\\ |\\ n\\ |\\ \\lambda x:T.\\ e\\ |\\ l\\ |\\ \\{t\\}$\\\\[0.5em]\nStores         & $\\sigma$ & $::=$ & $\\cdot\\ |\\ \\sigma,l:v$\\\\[0.5em]\nContexts       & $\\Gamma$ & $::=$ & $\\cdot\\ |\\ \\Gamma,x:T$\\\\[0.5em]\nStore Typings  & $\\Sigma$ & $::=$ & $\\cdot\\ |\\ \\Sigma,l:T$ \n\\end{tabular} \n\n\\subsection*{Typing rules}\n\n\\subsubsection*{Pure terms}\n\n\\vspace{0.5em}\n\\AxiomC{$x:T\\in\\Gamma$} \n\\RightLabel{\\textsc{Hyp}}\n\\UnaryInfC{$\\Sigma;\\Gamma\\vdash x:T$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{{\\color{white} $\\langle\\rangle$}} % placeholder\n\\RightLabel{\\textsc{1I}}\n\\UnaryInfC{$\\Sigma;\\Gamma\\vdash\\langle\\rangle:1$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{{\\color{white} $\\langle\\rangle$}} % placeholder\n\\RightLabel{\\textsc{$\\mathbb{N}$I}}\n\\UnaryInfC{$\\Sigma;\\Gamma\\vdash n:\\mathbb{N}$}\n\\DisplayProof\\bigbreak %========================================================\n\\noindent\n\\AxiomC{$\\Sigma;\\Gamma,x:T\\vdash e:T'$} \n\\RightLabel{\\textsc{$\\to$I}}\n\\UnaryInfC{$\\Sigma;\\Gamma\\vdash\\lambda x:T.\\ e:T\\to T'$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{$\\Sigma;\\Gamma\\vdash e_1:T\\to T'$}\n\\AxiomC{$\\Sigma;\\Gamma\\vdash e_2:T$}\n\\RightLabel{\\textsc{$\\to$E}}\n\\BinaryInfC{$\\Sigma;\\Gamma\\vdash e_1\\ e_2:T'$}\n\\DisplayProof\\bigbreak %========================================================\n\\noindent\n\\AxiomC{$l:T\\in\\Sigma$} \n\\RightLabel{\\textsc{RefBar}}\n\\UnaryInfC{$\\Sigma;\\Gamma\\vdash l:\\textsf{ref }T$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{$\\Sigma;\\Gamma\\vdash t\\div T$} \n\\RightLabel{\\textsc{MI}}\n\\UnaryInfC{$\\Sigma;\\Gamma\\vdash \\{t\\}:\\textsf{M }T$}\n\\DisplayProof\n\n\\subsubsection*{Impure terms}\n\n\\vspace{0.5em}\n\\AxiomC{$\\Sigma;\\Gamma\\vdash e:T$} \n\\RightLabel{\\textsc{RefI}}\n\\UnaryInfC{$\\Sigma;\\Gamma\\vdash \\textsf{new }e\\div\\textsf{ref }T$}\n\\DisplayProof$\\quad$ %==========================================================\n\\AxiomC{$\\Sigma;\\Gamma\\vdash e:\\textsf{ref }T$} \n\\RightLabel{\\textsc{RefGet}}\n\\UnaryInfC{$\\Sigma;\\Gamma\\vdash !e\\div T$}\n\\DisplayProof$\\quad$ %==========================================================\n\\AxiomC{$\\Sigma;\\Gamma\\vdash e:\\textsf{ref }T$}\n\\AxiomC{$\\Sigma;\\Gamma\\vdash e':T$}\n\\RightLabel{\\textsc{RefSet}}\n\\BinaryInfC{$\\Sigma;\\Gamma\\vdash e:=e'\\div 1$}\n\\DisplayProof\\bigbreak %========================================================\n\\noindent\n\\AxiomC{$\\Sigma;\\Gamma\\vdash e:T$} \n\\RightLabel{\\textsc{MRet}}\n\\UnaryInfC{$\\Sigma;\\Gamma\\vdash \\textsf{return }e\\div T$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{$\\Sigma;\\Gamma\\vdash e:\\textsf{M }T$}\n\\AxiomC{$\\Sigma;\\Gamma,x:T\\vdash t\\div T'$}\n\\RightLabel{\\textsc{MLet}}\n\\BinaryInfC{$\\Sigma;\\Gamma\\vdash \\textsf{let }x=e;t\\div T'$}\n\\DisplayProof\n\n\\subsubsection*{Store and configuration}\n\n\\vspace{0.5em}\n\\AxiomC{{\\color{white} $\\Sigma\\vdash\\cdot$}} %placeholder \n\\RightLabel{\\textsc{StoreNil}}\n\\UnaryInfC{$\\Sigma\\vdash\\cdot:\\cdot$}\n\\DisplayProof$\\quad$ %==========================================================\n\\AxiomC{$\\Sigma\\vdash\\sigma':\\Sigma'$} \n\\AxiomC{$\\Sigma;\\cdot\\vdash v:T$} \n\\RightLabel{\\textsc{StoreCons}}\n\\BinaryInfC{$\\Sigma\\vdash(\\sigma',l:v):(\\Sigma',l:T)$}\n\\DisplayProof$\\quad$ %==========================================================\n\\AxiomC{$\\Sigma\\vdash\\sigma:\\Sigma$} \n\\AxiomC{$\\Sigma;\\cdot\\vdash t\\div T$} \n\\RightLabel{\\textsc{ConfigOK}}\n\\BinaryInfC{$\\langle\\sigma;t\\rangle:\\langle\\Sigma;T\\rangle$}\n\\DisplayProof\n\n\\subsection*{Operational semantics}\n\n\\subsubsection*{Pure terms}\n\n\\vspace{0.5em}\n\\AxiomC{$e_1\\leadsto e_1'$}\n\\UnaryInfC{$e_1\\ e_2\\leadsto e_1'\\ e_2$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{$e_2\\leadsto e_2'$}\n\\UnaryInfC{$v\\ e_2\\leadsto v\\ e_2'$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{{\\color{white} $[]$}} %placeholder\n\\UnaryInfC{$(\\lambda x:T.\\ e)\\ v\\leadsto[v/x]e$}\n\\DisplayProof\n\n\\subsubsection*{Impure terms}\n\n\\vspace{0.5em}\n\\AxiomC{$e\\leadsto e'$}\n\\UnaryInfC{$\\langle\\sigma;\\textsf{new }e\\rangle\\leadsto\\langle\\sigma;\\textsf{new }e'\\rangle$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{$l\\notin\\text{dom}(\\sigma)$}\n\\UnaryInfC{$\\langle\\sigma;\\textsf{new }v\\rangle\\leadsto\\langle(\\sigma,l:v);\\textsf{return }l\\rangle$}\n\\DisplayProof\\bigbreak %========================================================\n\\noindent\n\\AxiomC{$e\\leadsto e'$}\n\\UnaryInfC{$\\langle\\sigma;!e\\rangle\\leadsto\\langle\\sigma;!e'\\rangle$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{$l:v\\in\\text{dom}(\\sigma)$}\n\\UnaryInfC{$\\langle\\sigma;!l\\rangle\\leadsto\\langle\\sigma;\\textsf{return }v\\rangle$}\n\\DisplayProof\\bigbreak %========================================================\n\\noindent\n\\AxiomC{$e_1\\leadsto e_1'$}\n\\UnaryInfC{$\\langle\\sigma;e_1:=e_2\\rangle\\leadsto\\langle\\sigma;e_1':=e_2\\rangle$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{$e_2\\leadsto e_2'$}\n\\UnaryInfC{$\\langle\\sigma;v:=e_2\\rangle\\leadsto\\langle\\sigma;v:=e_2'\\rangle$}\n\\DisplayProof\\bigbreak %========================================================\n\\noindent\n\\AxiomC{{\\color{white} $\\langle\\rangle$}} %placeholder\n\\UnaryInfC{$\\langle(\\sigma,l:v,\\sigma');l:=v\\rangle\\leadsto\\langle(\\sigma,l:v',\\sigma');\\textsf{return }\\langle\\rangle\\rangle$}\n\\DisplayProof\\bigbreak %========================================================\n\\noindent\n\\AxiomC{$e\\leadsto e'$}\n\\UnaryInfC{$\\langle\\sigma;\\textsf{return }e\\rangle\\leadsto\\langle\\sigma;\\textsf{return }e'\\rangle$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{$e\\leadsto e'$}\n\\UnaryInfC{$\\langle\\sigma;\\textsf{let }x=e;t\\rangle\\leadsto\\langle\\sigma;\\textsf{let }x=e';t\\rangle$}\n\\DisplayProof\\bigbreak %========================================================\n\\noindent\n\\AxiomC{{\\color{white} $\\langle\\rangle$}} %placeholder\n\\UnaryInfC{$\\langle\\sigma;\\textsf{let }x=\\{\\textsf{return v}\\};t\\rangle\\leadsto\\langle\\sigma;[v/x]t\\rangle$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{$\\langle\\sigma;t_1\\rangle\\leadsto\\langle\\sigma';t_1'\\rangle$}\n\\UnaryInfC{$\\langle\\sigma;\\textsf{let }x=\\{t_1\\};t_2\\rangle\\leadsto\\langle\\sigma';\\textsf{let }x=\\{t_1'\\};t_2\\rangle$}\n\\DisplayProof\\bigbreak %========================================================\n\n\\subsection{Monadic $\\lambda$-Calculus for I/O}\n\n\\subsection*{Syntax}\n\n\\hspace{-1em}\n\\begin{tabular}{lccl}\nTypes          & $T$ & $::=$ & $1\\ |\\ \\mathbb{N}\\ |\\ T_1\\to T_2\\ |\\ \\textsf{M}_\\textsf{IO}\\ T$\\\\[0.5em]\nPure Terms     & $e$ & $::=$ & $\\langle\\rangle\\ |\\ n\\ |\\ \\lambda x:T.\\ e\\ |\\ e_1\\ e_2\\ |\\ l\\ |\\ \\{t\\}$\\\\[0.5em]\nImpure Terms   & $t$ & $::=$ & $\\textsf{print }e\\ |\\ \\textsf{let }x=e;t\\ |\\ \\textsf{return }e$\\\\[0.5em]\nValues         & $v$ & $::=$ & $\\langle\\rangle\\ |\\ n\\ |\\ \\lambda x:T.\\ e\\ |\\ \\{t\\}$\\\\[0.5em]\nOutput Tokens  & $\\omega$ & $::=$ & $\\cdot\\ |\\ n::\\omega$\\\\[0.5em]\nContexts       & $\\Gamma$ & $::=$ & $\\cdot\\ |\\ \\Gamma,x:T$\n\\end{tabular} \n\n\\subsection*{Typing rules}\n\n\\subsubsection*{Pure terms}\n\n\\vspace{0.5em}\n\\AxiomC{$x:T\\in\\Gamma$} \n\\RightLabel{\\textsc{Hyp}}\n\\UnaryInfC{$\\Gamma\\vdash x:T$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{{\\color{white} $\\langle\\rangle$}} % placeholder\n\\RightLabel{\\textsc{1I}}\n\\UnaryInfC{$\\Gamma\\vdash\\langle\\rangle:1$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{{\\color{white} $\\langle\\rangle$}} % placeholder\n\\RightLabel{\\textsc{$\\mathbb{N}$I}}\n\\UnaryInfC{$\\Gamma\\vdash n:\\mathbb{N}$}\n\\DisplayProof\\bigbreak %========================================================\n\\noindent\n\\AxiomC{$\\Gamma,x:T\\vdash e:T'$} \n\\RightLabel{\\textsc{$\\to$I}}\n\\UnaryInfC{$\\Gamma\\vdash\\lambda x:T.\\ e:T\\to T'$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{$\\Gamma\\vdash e_1:T\\to T'$}\n\\AxiomC{$\\Gamma\\vdash e_2:T$}\n\\RightLabel{\\textsc{$\\to$E}}\n\\BinaryInfC{$\\Gamma\\vdash e_1\\ e_2:T'$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{$\\Gamma\\vdash t\\div T$}\n\\RightLabel{\\textsc{MI}}\n\\UnaryInfC{$\\Gamma\\vdash \\{t\\}:\\textsf{M}_\\textsf{IO}\\ T$}\n\\DisplayProof\n\n\\subsubsection*{Impure terms}\n\n\\vspace{0.5em}\n\\AxiomC{$\\Gamma\\vdash e:\\mathbb{N}$} \n\\RightLabel{\\textsc{MPrint}}\n\\UnaryInfC{$\\Gamma\\vdash \\textsf{print }e\\div 1$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{$\\Gamma\\vdash e:T$} \n\\RightLabel{\\textsc{MRet}}\n\\UnaryInfC{$\\Gamma\\vdash \\textsf{return }e\\div T$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{$\\Gamma\\vdash e:\\textsf{M}_\\textsf{IO}\\ T$}\n\\AxiomC{$\\Gamma,x:T\\vdash t\\div T'$}\n\\RightLabel{\\textsc{MLet}}\n\\BinaryInfC{$\\Gamma\\vdash \\textsf{let }x=e;t\\div T'$}\n\\DisplayProof\n\n\\subsection*{Operational semantics}\n\n\\subsubsection*{Pure terms}\n\n\\vspace{0.5em}\n\\AxiomC{$e_1\\leadsto e_1'$}\n\\UnaryInfC{$e_1\\ e_2\\leadsto e_1'\\ e_2$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{$e_2\\leadsto e_2'$}\n\\UnaryInfC{$v\\ e_2\\leadsto v\\ e_2'$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{{\\color{white} $[]$}} %placeholder\n\\UnaryInfC{$(\\lambda x:T.\\ e)\\ v\\leadsto[v/x]e$}\n\\DisplayProof\n\n\\subsubsection*{Impure terms}\n\n\\vspace{0.5em}\n\\AxiomC{$e\\leadsto e'$}\n\\UnaryInfC{$\\langle\\omega;\\textsf{print }e\\rangle\\leadsto\\langle\\omega;\\textsf{print }e'\\rangle$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{{\\color{white} $\\langle\\rangle$}} %placeholder\n\\UnaryInfC{$\\langle\\omega;\\textsf{print }n\\rangle\\leadsto\\langle(n::\\omega);\\textsf{return }\\langle\\rangle\\rangle$}\n\\DisplayProof\\bigbreak %========================================================\n\\noindent\n\\AxiomC{$e\\leadsto e'$}\n\\UnaryInfC{$\\langle\\omega;\\textsf{return }e\\rangle\\leadsto\\langle\\omega;\\textsf{return }e'\\rangle$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{$e\\leadsto e'$}\n\\UnaryInfC{$\\langle\\omega;\\textsf{let }x=e;t\\rangle\\leadsto\\langle\\omega;\\textsf{let }x=e';t\\rangle$}\n\\DisplayProof\\bigbreak %========================================================\n\\noindent\n\\AxiomC{{\\color{white} $\\langle\\rangle$}} %placeholder\n\\UnaryInfC{$\\langle\\omega;\\textsf{let }x=\\{\\textsf{return v}\\};t\\rangle\\leadsto\\langle\\omega;[v/x]t\\rangle$}\n\\DisplayProof$\\qquad$ %=========================================================\n\\AxiomC{$\\langle\\omega;t_1\\rangle\\leadsto\\langle\\omega';t_1'\\rangle$}\n\\UnaryInfC{$\\langle\\omega;\\textsf{let }x=\\{t_1\\};t_2\\rangle\\leadsto\\langle\\omega';\\textsf{let }x=\\{t_1'\\};t_2\\rangle$}\n\\DisplayProof\\newpage %=========================================================\n\n\\end{document}\n", "meta": {"hexsha": "3b993cace876689c4c117ec469e3c668ec27caf1", "size": 28783, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Types Cheat Sheet.tex", "max_stars_repo_name": "VictorZXY/cst-part-ii-types-cheat-sheet", "max_stars_repo_head_hexsha": "62d5b1a5c8477f0c1a0b61d3e9adf662c70015de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Types Cheat Sheet.tex", "max_issues_repo_name": "VictorZXY/cst-part-ii-types-cheat-sheet", "max_issues_repo_head_hexsha": "62d5b1a5c8477f0c1a0b61d3e9adf662c70015de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Types Cheat Sheet.tex", "max_forks_repo_name": "VictorZXY/cst-part-ii-types-cheat-sheet", "max_forks_repo_head_hexsha": "62d5b1a5c8477f0c1a0b61d3e9adf662c70015de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.6248062016, "max_line_length": 209, "alphanum_fraction": 0.5638397665, "num_tokens": 10337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.3481511269961152}}
{"text": "\\documentclass[../PHYS306Notes.tex]{subfiles}\n\n\\begin{document}\n\\section{Lecture 6}\n\\subsection{Lecture Notes - Charged Particles in EM Fields}\n\\subsubsection{Newton's Law in the presence of EM fields}\nNewton says:\n\\[m\\ddot{\\v{r}} = q(\\v{E} + \\dot{\\v{r}}\\times \\v{B})\\] for an electric field $\\v{E}$ and magnetic field $\\v{B}$. This is just the sum of the Coloumb force and Lorentz force.\n\n\\subsubsection{Scalar and Vector Potentials}\nWe will now apply the ideas of vector potential (for the magnetic field) from PHYS 301 to this situation. Recall that we defined the vector potential $\\v{A}$ as \\[\\v{B} = \\curl{\\v{A}}\\].\nWe also recall Faraday's Law, which states (combined with the definition of the potential above) that:\n\\[\\curl{\\v{E}} = -\\dpd{\\v{B}}{t} = -\\dpd{\\curl{\\v{A}}}{t}\\]\nInterchanging the order of taking the curl and taking the time derivative, we see that:\n\\[\\curl{\\left(\\v{E} + \\dpd{\\v{A}}{t}\\right)} = \\v{0}\\]\nSo there exists a scalar potential $V$ such that:\n\\[-\\grad{V} = \\v{E} + \\dpd{\\v{A}}{t}\\]\nWhich comes from the fact that a curl of a gradient is zero. We can rewrite this to say that:\n\\[\\v{E} = -\\grad{V} - \\dpd{\\v{A}}{t}\\]\nNow, we construct $\\LL$ such that we get the Lorentz Force. Generalize $U = qV$ to get:\n\\[U' = qV - q\\dot{\\v{r}}\\cdot\\v{A}\\]\nAnd we use $\\LL' = T - U'$ as our Lagrangian.\n\nNext week Monday, we will look at symmetry properties of the Lagrangian and how we can use this to derive conservation laws. On Wednesday we will look at the method of using Lagrange multipliers for constrained systems. On Friday we will review damped oscillators before moving into a discussion of coupled oscillators.\n\n\n\\end{document}", "meta": {"hexsha": "625cfe37dab5219ba2de9ad412e77be6619e4755", "size": 1658, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Lecture-6/Lecture-Notes-6.tex", "max_stars_repo_name": "RioWeil/PHYS306-notes", "max_stars_repo_head_hexsha": "9394a8cd986722b6fdcb57c8846c6b0d52c23188", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lecture-6/Lecture-Notes-6.tex", "max_issues_repo_name": "RioWeil/PHYS306-notes", "max_issues_repo_head_hexsha": "9394a8cd986722b6fdcb57c8846c6b0d52c23188", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lecture-6/Lecture-Notes-6.tex", "max_forks_repo_name": "RioWeil/PHYS306-notes", "max_forks_repo_head_hexsha": "9394a8cd986722b6fdcb57c8846c6b0d52c23188", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 61.4074074074, "max_line_length": 319, "alphanum_fraction": 0.6996381182, "num_tokens": 519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961013, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.34815112699611517}}
{"text": "\\documentclass{llncs}\n\\usepackage[dvips,final]{graphics}\n\\usepackage{amsmath}\n\\usepackage{times}\n%\n%\n%\n\\begin{document}\n\\mainmatter\n\n%\n\\title{An Image Inpainting Technique based on the Fast Marching Method}\n\\titlerunning{An Image Inpainting Technique}\n\\author{Alexandru Telea}\n\n\\authorrunning{Alexandru Telea}\n\\tocauthor{Alexandru Telea (Eindhoven University of Technology)}\n\n\\institute{Department of Mathematics and Computer Science,\\\\\nEindhoven University of Technology, \\\\\nDen Dolech 2,Eindhoven 5600 MB, The Netherlands, \\\\\n\\email{alext@win.tue.nl},\n\\texttt{http://www.win.tue.nl/$\\sim$alext}}\n%\n%\n\\maketitle\n%\n%\n\\begin{abstract} \n% \n  Digital inpainting provides a means for reconstruction of small\ndamaged portions of an image. Although the inpainting basics are\nstraightforward, most inpainting techniques published in\nthe literature are complex to understand and implement.\nWe present here a new algorithm for digital inpainting based on the fast\nmarching method for level set applications. Our algorithm is very\nsimple to implement, is fast, and produces nearly identical results as\nmore complex, and usually slower, known methods. Source code is available online.\n\\end{abstract}\n%\n%\n\\section{Introduction}\n%\n%\n Digital inpainting, the technique of reconstructing small damaged portions\nof an image, has received considerable attention in the last years.\nDigital inpainting serves a wide range of\napplications, such as removing text and logos from still images or videos, reconstructing\nscans of deteriorated images by removing scratches or stains, or creating\nartistic effects.\n Most inpainting methods work as follows. First, the\nimage regions to be inpainted are selected, usually in a\nmanual way. Next, color information is propagated inwards from the region\nboundaries, i.e. the known image information is used to fill-in the missing areas. \nIn order to produce a perceptually plausible reconstruction, an inpainting\ntechnique should attempt to continue the \n\\textit{isophotes} (lines of equal gray value) as smoothly as possible inside the\nreconstructed region. In other words, the missing region should be inpainted\nsuch that the inpainted gray value and gradient extrapolate\nthe gray value and gradient outside this region. \n  \nSeveral inpainting methods are based on the above ideas.\nIn \\cite{bertalmio1,bertalmio2}, the image smoothness\ninformation, estimated by the image Laplacian, is propagated along the\nisophotes directions, estimated by the image gradient rotated with 90\ndegrees. The \\textit{Total Variational} (TV) model~\\cite{chan} uses an\nEuler-Lagrange equation coupled with anisotropic diffusion to maintain the\nisophotes' directions. The \\textit{Curvature-Driven Diffusion} (CCD)\nmodel~\\cite{chan2} enhances the TV method to drive diffusion along the isophotes' directions\nand thus allows inpainting thicker regions. All above methods essentially \nsolve a partial differential equation (PDE) that describes\nthe color propagation inside the missing region, subject to various\nheuristics that attempt to preserve the\nisophotes' directions. Preserving isophotes is, however desirable, never\nperfectly attained in practice. The main problem is that both isophote\nestimation and information propagation are subject to numerical diffusion.\nDiffusion is desirable as it stabilizes the PDEs to be solved, but leads\ninevitably to a cetain amount of blurring of the inpainted area.\n\nA second type of methods~\\cite{oliveira}\nrepeatedly convolves a simple 3x3 filter over the missing regions to\ndiffuse known image information to the missing pixels.\n  \nHowever impressive, the above methods have several drawbacks that preclude\ntheir direct use in practice. The PDE-based methods require implementing non-trivial iterative numerical\nmethods and techniques, such as anisotropic diffusion and multiresolution schemes \\cite{bertalmio1}.\nLittle or no information is given on practical implementation details such as various thresholds or\ndiscretization methods, although some steps are mentioned as numerically unstable.\nMoreover, such methods are quite slow, e.g. a few minutes for the relatively\nsmall inpainting region shown in Fig.~\\ref{fig:example3}.\nIn contrast, the convolution-based method described in~\\cite{oliveira} \nis simple to implement and fast. However, this method has no provisions for\npreserving the isophotes' directions.\nHigh-gradient image areas must be manually selected before inpainting and\nseparately treated in order not to be blurred. \n\n  We propose a new inpainting algorithm based on propagating an image smoothness estimator along the\nimage gradient, similarly to~\\cite{bertalmio1}. We estimate the image\nsmoothness as a weighted average over a known image neighborhood of the pixel to\ninpaint. We treat the missing regions as level sets and use\nthe fast marching method (FMM) described in~\\cite{sethian} to propagate the\nimage information. Our approach has several advantages:\n\\begin{itemize}\n  \\item it is very simple to implement (the complete pseudocode is given here).\n  \\item it is considerably faster than other inpainting methods\n       --- processing an 800x600 image (Fig.~\\ref{fig:example3}) takes under 3 seconds on a 800 MHz PC.\n  \\item it produces very similar results as compared to the other methods.\n  \\item it can easily be customized to use different local inpainting strategies.\n\\end{itemize}\n%\n%\n In Section~\\ref{sec:method}, we describe our method. Section~\\ref{sec:discussion}\npresents several results, details our method's advantages and limitations\nin comparison to other methods, and discusses possible enhancements. Source\ncode of a sample method implementation is available online at the address\nlisted at the end of the paper.\n%\n%\n\t\\begin{figure}[h] \\centering\n\t\\resizebox{1.0\\textwidth}{!}{\\includegraphics{EPS/example3.eps}}\n\t\\caption{800x600 image inpainted in under 3 seconds}\n\t\\label{fig:example3} \n        \\end{figure} \n%\n%   \n%\n%\n\\section{Method}\n\\label{sec:method}\n%\nThis section describes our inpainting method. First,\nwe introduce the mathematical model we base our inpainting\non (Sec.~\\ref{sec:model}). Next, we describe how the missing regions are\ninpainted using the FMM (Sec.~\\ref{sec:fmm}). Finally, we detail the\nimplementation of inpainting one point on the missing region's boundary\n(Sec.~\\ref{sec:inp_function}).\n%\n\\subsection{Mathematical model}\n\\label{sec:model}\n%\n To explain our method, consider Fig.~\\ref{fig:method}, in which one must\ninpaint the point $p$ situated on the boundary $\\partial\\Omega$ of the\nregion to inpaint $\\Omega$. Take a small neighborhood $B_{\\varepsilon}(p)$\nof size $\\varepsilon$ of the known image around $p$\n(Fig.~\\ref{fig:method}~a). As described in~\\cite{bertalmio1,oliveira,chan},\nthe inpainting of $p$ should be determined by the values\nof the known image points close to $p$, i.e. in $B_{\\varepsilon}(p)$. \nWe first consider gray value images, color images being a natural extension (see Sec.~\\ref{sec:implem}).\n%\n\t\\begin{figure}[h] \\centering\n\t\\resizebox{0.65\\textwidth}{!}{\\includegraphics{EPS/method.eps}}\n\t\\caption{The inpainting principle}\n\t\\label{fig:method} \n        \\end{figure} \n%\nFor $\\varepsilon$ small enough, we consider a first order approximation $I_q(p)$\nof the image in point $p$, given the image $I(q)$ and gradient $\\nabla I(q)$\nvalues of point $q$ (Fig~\\ref{fig:method}~b):\n%\n%\n\\begin{equation}\n   I_q(p) = I(q) + \\nabla I(q) (p-q)\n\\label{eqn:linear}\n\\end{equation}\n%\n%\nNext, we inpaint point $p$ as function of all points $q$ in\n$B_{\\varepsilon}(p)$ by summing the estimates of all points $q$, \nweighted by a normalized weighting function $w(p,q)$:\n%\n%\n\\begin{equation}\n  I(p) = \\frac{\\sum_{q \\in B_{\\varepsilon}(p)} w(p,q) [I(q) + \\nabla I(q) (p-q)]}\n              {\\sum_{q \\in B_{\\varepsilon}(p)} w(p,q)}\n\\label{eqn:sum}\n\\end{equation}\n%\n%\nThe weighting function $w(p,q)$, detailed in Sec.~\\ref{sec:inp_function}, \nis designed such that the inpainting of $p$ propagates the gray value as well \nas the sharp details of the image over $B_{\\varepsilon}(p)$. \n%\n\\subsection{Adding inpainting to the FMM}\n\\label{sec:fmm}\n%\n%\n Section~\\ref{sec:model} explained how to inpaint\na point on the unknown region's boundary $\\partial\\Omega$ as a function of\nknown image pixels only. To inpaint the whole $\\Omega$, we iteratively apply\niteratively apply Equation~\\ref{eqn:sum} to all the discrete pixels of\n$\\partial\\Omega$, in increasing distance from $\\partial\\Omega$'s initial\nposition $\\partial\\Omega_i$, and advance the boundary inside $\\Omega$ until the whole\nregions has been inpainted (see pseudocode in Fig.~\\ref{fig:pseudo}). \nInpainting points in increasing\ndistance order from $\\partial\\Omega_i$ ensures that areas closest to known\nimage points are filled in first, thus mimicking manual inpainting\ntechniques~\\cite{bertalmio1,bertalmio2}. \n%\n\t\\begin{figure}[h] \\centering\n\t\\resizebox{0.45\\textwidth}{!}{\\includegraphics{EPS/pseudo.eps}}\n\t\\caption{Inpainting algorithm}\n\t\\label{fig:pseudo} \n        \\end{figure} \n%\n\nImplementing the above requires thus a method that propagates\n$\\partial\\Omega$ into $\\Omega$ by advancing the pixels of $\\partial\\Omega$\nin order of their distance to the initial boundary $\\partial\\Omega_i$. \nFor this, we use the fast marching method (FMM) developed by Sethian et al.\n\\cite{sethian}. In brief, the FMM is an algorithm that solves the Eikonal equation:\n%\n%\n\\begin{equation}\n   |\\nabla T| = 1 \\mbox{~~~~~on $\\Omega$,~~~~~with $T=0$ on $\\partial\\Omega$}\n\\label{eqn:eikonal}\n\\end{equation}\n%\nThe solution $T$ of Eqn.~\\ref{eqn:eikonal} is the distance map of the $\\Omega$ pixels to the boundary\n$\\partial\\Omega$. The level sets, or isolines, of $T$ \nare exactly the successive boundaries $\\partial\\Omega$ of the shrinking\n$\\Omega$ that we need for inpainting. The normal $N$ to\n$\\partial\\Omega$, also needed for inpainting, is exactly $\\nabla T$. The FMM\nguarantees that pixels of $\\partial\\Omega$ are always processed in\nincreasing order of their distance-to-boundary $T$~\\cite{fmm_book}, i.e.\nthat we always inpaint the closest pixels to the known image area first. \n\nWe prefer the FMM over other 'distance transform' (DT) methods that compute the distance map $T$ to a boundary $\\partial\\Omega$\n(e.g.~\\cite{chamfer1,chamfer2,roerdinck}). The FMM's main advantage is that it\n\\textit{explicit} maintains the narrowband that\nseparates the known from the unknown image area \\textit{and} specifies which is the next pixel to\ninpaint. Other DT methods compute the distance map $T$ but do not maintain an\nexplicit narrowband. Adding a narrowband structure to these method would\ncomplicate their implementation, whereas the FMM provides this structure by\ndefault.\n\nTo explain in detail our use of the FMM  --- and since the FMM is not\nstraightforward to implement from the reference\nliterature~\\cite{sethian,fmm_book} --- we provide next its complete pseudocode. \n  The FMM maintains a so-called \\textit{narrow band} of pixels, which is\nexactly our inpainting boundary $\\partial\\Omega$. For every image pixel, we store\nits value $T$, its image gray value $I$ (both represented as floating-point\nvalues),  and a flag $f$ that may have three values:\n\\begin{itemize}\n  \\item\\textit{BAND}: the pixel belongs to the narrow band. Its $T$ value\n  undergoes update.\n  \\item\\textit{KNOWN}: the pixel is outside $\\partial\\Omega$, in the known\n  image area. Its $T$ and $I$ values are known.\n  \\item\\textit{INSIDE}: the pixel is inside $\\partial\\Omega$, in the region to inpaint. Its $T$\n  and $I$ values are not yet known.\n\\end{itemize}\n%\n%\n  The FMM has an initialization and propagation phase, as follows.\nFirst, we set $T$ to zero on and outside the boundary\n$\\partial\\Omega$ of the region to inpaint and to some large value (in practice $10^6$)\ninside, and initialize $f$ over the whole image as explained\nabove. All $BAND$ points are inserted in a heap \\texttt{NarrowBand}\nsorted in ascending order of their $T$ values. \nNext, we propagate the $T$, $f$, and $I$ values using the code\nshown in Fig.~\\ref{fig:fmm_code}.\n%\n\t\\begin{figure}[h] \\centering\n\t\\resizebox{0.75\\textwidth}{!}{\\includegraphics{EPS/code.eps}}\n\t\\caption{Fast marching method used for inpainting}\n\t\\label{fig:fmm_code} \n        \\end{figure} \n%\n%\nStep 1 extracts the $BAND$ point with the smallest $T$. Step 2 marches\nthe boundary inwards by adding new points to it. Step 3 performs the\ninpainting (see Sec.~\\ref{sec:inp_function}). Step 4 propagates the value\n$T$ of point $(i,j)$ to its neighbors $(k,l)$ by solving the finite difference discretization of\nEqn.~\\ref{eqn:eikonal} given by:\n%\n\\begin{equation}\n  \\mbox{max}(D^{-x}T,-D^{+x}T,0)^2+\\mbox{max}(D^{-y}T,-D^{+y}T,0)^2 = 1\n\\label{eqn:quad}\n\\end{equation}\n%\nwhere $D^{-x}T(i,j) = T(i,j)-T(i-1,j)$ and $D^{+x}T(i,j) = T(i+1,j)-T(i,j)$\nand similarly for $y$. Following the upwind idea of Sethian~\\cite{sethian},\nwe solve Eqn.~\\ref{eqn:quad} for $(k,l)$'s four quadrants and retain\nthe smallest solution. Finally, step 5 (re)inserts $(k,l)$\nwith its new $T$ in the heap.\n\n%\n%\n\\subsection{Inpainting one point}   \n\\label{sec:inp_function}\n%\n%\nWe consider now how to inpaint a newly discovered point $(k,l)$, as function of the\n$KNOWN$ points around it, following the idea described in Sec.~\\ref{sec:model}\n(step 3 in Fig.~\\ref{fig:fmm_code}, detailed in Fig.~\\ref{fig:inpaint_code})).\n%\n\t\\begin{figure}[h] \\centering\n\t\\resizebox{0.7\\textwidth}{!}{\\includegraphics{EPS/inpaint_code.eps}}\n\t\\caption{Inpainting one point}\n\t\\label{fig:inpaint_code} \n        \\end{figure} \n%\nWe iterate over the $KNOWN$ points in the neighborhood $B_{\\varepsilon}$ of\nthe current point $(i,j)$ and compute $I(i,j)$ following\nEqn.~\\ref{eqn:sum}. The image gradient $\\nabla I$ (\\texttt{gradI} in the\ncode) is estimated by central differences. As stated in Sec.~\\ref{sec:model}, the design of the\nweighting function $w(p,q)$ is crucial to propagate the sharp image details and the smooth\nzones as such into the inpainted zone. We design $w(p,q) = dir(p,q) \\cdot\ndst(p,q) \\cdot lev(p,q)$ as a product of three factors:\n%\n%\n%\\begin{equation}\n%  w(p,q)=dir(p,q) \\cdot dst(p,q) \\cdot lev(p,q)\n%\\end{equation}\n%\n%\n\\begin{eqnarray*}\n  dir(p,q) &=& \\frac{p-q}{||p-q||} \\cdot N(p)\\\\\n  dst(p,q) &=& \\frac{d_0^2}{||p-q||^2} \\\\\n  lev(p,q) &=& \\frac{T_0}{1+|T(p)-T(q)|}  \n\\end{eqnarray*}\n%\n%\nThe \\textit{directional} component $dir(p,q)$ ensures that the\ncontribution of the pixels close to the normal direction\n$N=\\nabla T$ (\\texttt{gradT} in the code), i.e. close to the\nFMM's information propagation direction, is higher than for those further from\n$N$. The \\textit{geometric distance} component $dst(p,q)$ decreases the\ncontribution of the pixels geometrically farther from $p$.  \nThe \\textit{level set} distance\ncomponent $lev(p,q)$ ensures that pixels close to the contour\nthrough $p$ contribute more than further pixels. Both $dst$ and $lev$ are\nrelative with respect to the reference distances $d_0$ and $T_0$. In practice, we set\n$d_0$ and $T_0$ to the inter-pixel distance, i.e. to 1.\nOverall, the above factors model the manual inpainting heuristics~\\cite{bertalmio1} that\ndescribe how to paint a point by strokes bringing color from a small region\naround it.\n\nFor $\\varepsilon$ up to about\n6 pixels, i.e. when inpainting thin regions, $dst$ and $lev$ have\na weak effect. For thicker regions to inpaint, such as\nFig.~\\ref{fig:example2}~d where we used an $\\varepsilon$ of 12 pixels, \nusing $dst$ and $lev$ provides better\nresults than using $dir$ alone. The above is clearly visible in\nFig.~\\ref{fig:ellipse}, on a test image taken from~\\cite{bertalmio1},  where\nthe missing ring shaped region is over 30 pixels thick.\nFigure~\\ref{fig:ellipse}~c shows, on an image detail, the effect of $dir$ alone. The results are\nsomewhat less blurry when $dir$ and $dst$ (Fig.~\\ref{fig:ellipse}~d) or\n$dir$ and $lev$ (Fig.~\\ref{fig:ellipse}~e) are used together. The inpainting\nis visually the best when all three components are used (Fig.~\\ref{fig:ellipse}~f).\n%\n%\n\t\\begin{figure}[h] \\centering\n\t\\resizebox{0.81\\textwidth}{!}{\\includegraphics{EPS/ellipse.eps}}\n\t\\caption{Thick region to inpaint (a) and result (b). Effect of weighting functions: \n         direction (c), direction and geometric distance (d), direction and level set distance (e),\n         direction, geometric, and level set distance (f)}\n\t\\label{fig:ellipse} \n        \\end{figure} \n%\n%\n%\n%\n\\subsection{Implementation details}\n\\label{sec:implem}\n%\n%\n  Several implementation details are important. First, we compute the\nboundary normal $N=\\nabla T$ by numerical derivation of the field $T$\ncomputed by the FMM. Derivating $T$ on the fly as it is computed by the\nFMM is unstable, since we are not guaranteed that a large enough\nneighborhood around the current point contains only $KNOWN$ points.\nWe first run the FMM outside the initial inpainting boundary\n$\\partial\\Omega$ and obtain the distance field $T_{out}$. Since we use only\nthose points closer to $\\partial\\Omega$ than $\\varepsilon$, we run the FMM\noutside $\\partial\\Omega$ only until we reach $T > \\varepsilon$. This\nrestricts the FMM computations to a band of thickness $\\varepsilon$ around\n$\\partial\\Omega$, thus speeding up the process. Next, we run the FMM\ninside $\\partial\\Omega$ and obtain $T_{in}$. The field $T$ over the whole\nimage is given by:\n%\n\\begin{equation}\nT(p) = \\left\\{\n      \\begin{array}{rcl}\n      &T_{in}&(p)~~~\\mbox{if}~p \\in \\Omega\\\\\n      -&T_{out}&(p)~~~\\mbox{if}~p \\notin \\Omega.\n\\end{array}\n\\right.\n\\end{equation}\n%\nNext, we smooth $T$ by a 3x3 tent filter, and then compute $\\nabla T$ by\ncentral differences. \n\n  The value of $\\varepsilon$ giving the size of $B$ usually ranges from 3 to 10\npixels. This corresponds with the 'thickness' of the regions to inpaint,\nwhich is usually less than 15 pixels. Higher values blur the sharp details\nto be reconstructed by inpainting, although they are useful when inpainting\nthicker regions. \n\n  The test \\texttt{f(k,l)!=OUTSIDE} in Fig.~\\ref{fig:inpaint_code} that\nrestricts $B_{\\varepsilon}$ to the known image points can be changed to\n\\texttt{f(k,l)==KNOWN}. The results are visually identical, as\n$B_{\\varepsilon}$ contains very few $BAND$ pixels. However, one would use the second test\nif the initial $\\partial\\Omega$ corresponds to unknown image pixels.\n\nThe \\texttt{NarrowBand} sorted heap (Sec.~\\ref{sec:fmm}) is straightforwardly implemented using\nthe C++ STL \\texttt{multimap} container~\\cite{stl}. Finally, for color (RGB) images we apply the presented \nmethod separately for each color channel.\n%\n\\section{Discussion}\n\\label{sec:discussion}\n%\n%\n   We have compared our inpainting method with the methods presented\nby Bertalmio et al. in~\\cite{bertalmio1} and Oliveira et al. in~\\cite{oliveira}, further denoted by\nBSCB and OBMC, by running it on the same input images (see Figures~\\ref{fig:example1}\nand~\\ref{fig:example2}~a-c). For BSCB we used the implementation publicly available\nat~\\cite{implem}, whereas we reimplemented OBMC ourselves. \nOur method produced visually nearly identical results with BSCB. Compare, for example, the\ninpaintings in Fig.~\\ref{fig:example1}~c,d (Fig.~\\ref{fig:example1}~e,f in\ndetail) and Fig.~\\ref{fig:example2}~b,c (Fig.~\\ref{fig:example2}~g,h in detail).\nIn contrast, the results of OBMC (shown in~\\cite{oliveira}) \nwere visibly more blurry for regions thicker than 6 pixels. \n%\n\t\\begin{figure}[h] \\centering\n\t\\resizebox{1.05\\textwidth}{!}{\\includegraphics{EPS/example1.eps}}\n\t\\caption{Lincoln 'cracked photo' inpainting}\n\t\\label{fig:example1} \n        \\end{figure} \n%\n%   \n  The running time for our method was in all cases much lower than for\nBSCB. Our C++ implementation took under 3 seconds on an 800 MHz PC for a 800x600\ncolor image with about 15\\% pixels to inpaint (Fig.~\\ref{fig:example3}).\nOn the same input, the original BSCB method, published in~\\cite{bertalmio1}, is reported to take under 5 minutes on a\n300 MHz PC. The BSCB implementation we used~\\cite{implem}, which is\nhowever mentioned to be unoptimized by its authors, took between 2.5 and 3 minutes on the 800\nMHz PC, depending on its various parameter settings.\nIn contrast, OBMC takes in all cases about the same time as our method.\nThe above matches the fact that both OBMC and our method are linear\nin the inpainted region's size. \n\nThe main limitation of our method (applicable to the methods BSCB and\nOBMC mentioned here too) is the blurring produced when inpainting\nregions thicker than 10-15 pixels, especially visible when sharp isophotes\nintersect the region's boundary almost tangentially. See for example the\ninpainting in Fig.~\\ref{fig:example2}~d,e (in\ndetail in Fig.~\\ref{fig:example2}~i,j). The above is caused by the linear\nand local character of our method. Techniques using an explicit nonlinear\nand/or global image model, such as the TV~\\cite{chan} and the CDD~\\cite{chan2} methods,\nachieve better results, at the cost of considerably more complex implementations.\n%\n\t\\begin{figure}[h] \\centering\n\t\\resizebox{1.05\\textwidth}{!}{\\includegraphics{EPS/example2.eps}}\n\t\\caption{Inpainting examples. Damaged photo (a), inpainting by method BSCB (b), \n         our method (c), and close-ups (f,g,h).\n         Damaged photo (d), distance-weighted inpainting (e), and close-ups (i,j)}.\n\t\\label{fig:example2} \n        \\end{figure} \n\nOverall, the presented inpainting method is simple to implement (our complete C++ code is \nabout 500 lines), is fast, and easy to customize for different inpainting strategies.\nWe plan to extend the method by developing new inpainting functions that\nare better able to preserve the isophotes' directions. One such way is to\nintegrate anisotropic diffusion, e.g. following~\\cite{bertalmio1}, in the FMM boundary\nevolution in order to reduce the blurring for inpainting thick regions. A\nsecond extension would be to modulate the evolution speed of the FMM, now\nequal to 1, by the image anisotropy, i.e. let inpainting 'work more' on the\nhigh detail areas than on the smooth regions.\n%\n%\n\\section*{Acknowledgements}\n%\n  We are indebted to prof. J. J. van Wijk from the Department of\nMathematics and Computer Science of the Eindhoven University of Tehcnology\nfor his numerous suggestions on how to improve this paper.\n%\n\\section*{Web Information}\n%\n  Source code of a sample C++ implementation of the inpainting method\ndescribed here is available at\\\\\n\\texttt{http://www.acm.org/jgt/papers/Telea03.html}\n%\n%\n%\n%-------------------------------------------------------------------------------\n%\n\\begin{thebibliography}{13}\n%\n\\bibitem {bertalmio1}\n   {\\sc M. Bertalmio, G. Sapiro, V. Caselles, and C. Ballester},\n   {\\em Image Inpainting}, Proc. SIGGRAPH 2000, ACM Press, pp. 417-424.\n\\bibitem {bertalmio2}\n   {\\sc M. Bertalmio, A. L. Bertozzi, and G. Sapiro},\n   {\\em Navier-Stokes, Fluid Dynamics, and Image and Video Inpainting},\n   Proc. ICCV 2001, IEEE CS Press, vol. 1, pp. 1335-1362.\n\\bibitem{chamfer1}\n   {\\sc G. Borgefors},\n   {\\em Distance transformations in arbitrary images},\n   Comp. Vision, Graphics, and Image Proc., 27(3), pp. 321-345, 1984.\n\\bibitem{chamfer2}\n   {\\sc G. Borgefors},\n   {\\em Distance transformations in digital images},\n   Comp. Vision, Graphics, and Image Proc., 34(3), pp. 344-371, 1986.\n\\bibitem {oliveira}\n   {\\sc M. Oliveira, B. Bowen, R. McKenna, and Y.-S. Chang},\n   {\\em Fast Digital Image Inpainting},\n   Proc. VIIP 2001 (Marbella, Spain), pp. 261-266.\n\\bibitem {chan}\n   {\\sc T. Chan, J. Shen}, \n   {\\em Mathematical Models for Local Deterministic Inpaintings},\n   Tech. report CAM 00-11, Image Processing Research Group, UCLA, 2000.\n\\bibitem {chan2}\n   {\\sc T. Chan, J. Shen},\n   {\\em Non-texture Inpainting by Curvature-Driven Diffusions (CDD)},\n   Tech. report CAM 00-35, Image Processing Research Group, UCLA, 2000.\n\\bibitem{roerdinck}\n   {\\sc A. Meijster, J. Roerdink, W. Hesselink},\n   {\\em A general algorithm for computing distance transforms in linear time},\n   Math. Morph. and its Appls. to Image and Signal Proc., pp. 331--340, Kluwer, 2000.\n\\bibitem {fmm_book}\n   {\\sc J. A. Sethian},\n   {\\em Level Set Methods and Fast Marching Methods},\n   Cambridge Univ. Press, 2nd edition, 1999.\n\\bibitem {sethian}\n   {\\sc J. A. Sethian},\n   {\\em A Fast Marching Level Set Method for Monotonically Advancing Fronts},\n   Proc. Nat. Acad. Sci. vol. 93, nr. 4, pp. 1591-1595, 1996. \n\\bibitem{implem}\n   {\\sc W. Yung, A. J. Shankar},\n   {\\em Image Inpainting Implementation Software}, \\texttt{www.bantha.org/$\\sim$aj/inpainting}\n\\bibitem{stl}\n  {\\sc D. R. Musser, A. Saini},\n  {\\em STL Tutorial and Reference Guide: C++\n   Programming with the Standard Template Library},\n  Addison-Wesley Professional Computing Series, 1996.\n   \n\n\\end{thebibliography}\n\n\n%-------------------------------------------------------------------------------\n%\n%\n%\n%\n\\end{document}\n%\n\n", "meta": {"hexsha": "859fc89760d32ac84cf7cb2c753410c3b7732060", "size": 24704, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Volume_09/Number_1/Telea2004/sources/pres.tex", "max_stars_repo_name": "kyeonghopark/jgt-code", "max_stars_repo_head_hexsha": "08bbcc298e12582e32cb56a52e70344c57689d73", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 415, "max_stars_repo_stars_event_min_datetime": "2015-10-24T17:37:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T04:09:07.000Z", "max_issues_repo_path": "Volume_09/Number_1/Telea2004/sources/pres.tex", "max_issues_repo_name": "kyeonghopark/jgt-code", "max_issues_repo_head_hexsha": "08bbcc298e12582e32cb56a52e70344c57689d73", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2016-01-15T13:23:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-27T01:49:50.000Z", "max_forks_repo_path": "Volume_09/Number_1/Telea2004/sources/pres.tex", "max_forks_repo_name": "kyeonghopark/jgt-code", "max_forks_repo_head_hexsha": "08bbcc298e12582e32cb56a52e70344c57689d73", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 77, "max_forks_repo_forks_event_min_datetime": "2015-10-24T22:36:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T01:03:54.000Z", "avg_line_length": 44.9981785064, "max_line_length": 127, "alphanum_fraction": 0.7420660622, "num_tokens": 7000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878414043816, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.34815111900864}}
{"text": "\\documentclass[12]{scrartcl}\n\\usepackage{amssymb,amsmath,gensymb,dsfont,calc,multicol,fullpage}\n\\makeatletter\n\\newcommand\\Aboxed[1]{\n   \\@Aboxed#1\\ENDDNE}\n\\def\\@Aboxed#1&#2\\ENDDNE{%\n   &\n   \\settowidth\\@tempdima{$\\displaystyle#1{}$}\n   \\setlength\\@tempdima{\\@tempdima+\\fboxsep+\\fboxrule}\n   \\kern-\\@tempdima\n   \\boxed{#1#2}\n}\n\\makeatother\n\n\\begin{document}\n\n\\title{Homework 26, Section 4.9: 1, 2, 6, 7, 12, 18}\n\\author{Alex Gordon}\n\\date{\\today}\n\\maketitle\n\\section*{Homework}\n\\subsection*{1. A)}\n\\ \\ N  \\ M \\\\\n$\\begin{bmatrix}  .7 & .6 \\\\ .3 & .4  \\end{bmatrix} $ News and Music\n\\subsection*{1. B)}\n$\\begin{bmatrix}  1\\\\ 0  \\end{bmatrix} $\n\\subsection*{1. C)}\nApproximately 33%\n\\subsection*{2. A)}\n1, 2, and 3 respectively at the tops and it goes to 1, 2, and 3 on the side respectively. \n$\\begin{bmatrix}  .6 & .2 & .2 \\\\ .2 & .6 & .2 \\\\ .2 & .2 & .6  \\end{bmatrix} $\n\\subsection*{2. B)}\nApproximately .28\n\\subsection*{6.}\n$\\begin{bmatrix}  4/7 \\\\ 3/7  \\end{bmatrix} $ is the steady state vector. \n\\subsection*{7.}\n$\\begin{bmatrix}  1/4 \\\\ 1/2 \\\\ 1/4  \\end{bmatrix} $  is the steady state vector. \n\\subsection*{12.}\nEach food will be preferred equally, because $\\begin{bmatrix}  1/3 \\\\ 1/3 \\\\ 1/3  \\end{bmatrix} $ of the equal numbers in the steady state vector. \n\\subsection*{18.}\nIf alpha = beta = 0, then $\\begin{bmatrix}  1\\\\ 0  \\end{bmatrix} $ and $\\begin{bmatrix}  0\\\\ 1  \\end{bmatrix} $ are the steady state vectors. If it is not 0, then it should equal $\\frac{1}{\\alpha + \\beta} \\begin{bmatrix}  \\beta \\\\ \\alpha  \\end{bmatrix}$\n\n\n\\end{document}", "meta": {"hexsha": "341dd6116e68340e4d555c32dbce20cc497cef0b", "size": 1554, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "LinearAlgebra/Homework26.tex", "max_stars_repo_name": "alexggordon/latex", "max_stars_repo_head_hexsha": "7dd945f33490e6585e26cff39d9cf6ad8f582a0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LinearAlgebra/Homework26.tex", "max_issues_repo_name": "alexggordon/latex", "max_issues_repo_head_hexsha": "7dd945f33490e6585e26cff39d9cf6ad8f582a0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LinearAlgebra/Homework26.tex", "max_forks_repo_name": "alexggordon/latex", "max_forks_repo_head_hexsha": "7dd945f33490e6585e26cff39d9cf6ad8f582a0e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3181818182, "max_line_length": 253, "alphanum_fraction": 0.6473616474, "num_tokens": 633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.34815111799038173}}
{"text": "\\section{Results}\n\\label{section:results}\n\nIn order to demonstrate the performance of our method, we conducted three sets\nof tests.\nIn the first we simulated observables from a set of stellar parameters for a\nfew hundred stars using the MIST stellar evolution models and the\ngyrochronology model of equation \\ref{eqn:gyro}.\nThe ages predicted with our model were compared to the true parameters used to\ngenerate the data.\nIn the second we tested our model by measuring the ages of individual stars in\nthe NGC 6819 open cluster, and in the third we tested our model on \\kepler\\\nasteroseismic stars.\n\n\\subsection{Test 1: simulated stars}\nFor the first test we drew masses, ages, bulk metallicities, distances and\nextinctions at random for 1000 stars from the following uniform distributions:\n\\begin{eqnarray}\n& \\mathrm{EEP} \\sim U(198, 480) \\\\\n% & M \\sim U(0.5, 1.5)~[M_\\odot] \\\\\n& t \\sim U(0.5, 14)\\mathrm{~[Gyr]} \\\\\n& [Fe/H] \\sim U(-0.2, 0.2) \\\\\n& D \\sim U(10, 1000)~\\mathrm{[pc]} \\\\\n& A_V \\sim U(0, 0.1).\n\\end{eqnarray}\n\\teff, \\logg, \\fhat, parallax, and apparent magnitudes $B$, $V$, $J$, $H$, $K$,\n\\gaia\\ $G$, $G_{BP}$ and $G_{RP}$ were generated from these\nstellar parameters using the MIST stellar evolution models.\nWe added a small amount of noise to the `observed' stellar properties in order\nto reflect optimistic observational uncertainties for isochrone-dating.\nWe added Gaussian noise with a standard deviation of 25 K to \\teff, 0.01 dex\nto \\feh\\ and \\logg, and 10 mmags to $B$, $V$, $J$, $H$, and $K$ magnitudes.\nThese are just one choice of uncertainties that we could have adopted and are\nextremely optimistic.\nThe uncertainties on predicted ages {\\it will} depend strongly on all\nobservational uncertainties, however, since this analysis is designed to show\nthe relative improvement in stellar age precision when {\\it rotation periods}\nare included, we chose to use best-case spectroscopic parameters.\nThe noise added to Gaia $G$-band photometry ranged from\n0.3 mmag for stars brighter than 13th magnitude, to 10 mmag for stars\naround 20th magnitude \\citep{evans2017, brown2018}.\nNoise added to \\gaia\\ $G_{BP}$ and $G_{RP}$ bands ranged from 2 mmag for stars\nbrighter than 13th magnitude to 200 mmag for stars fainter than 17th.\nUnphysical combinations of stellar parameters were discarded, resulting in a\nfinal sample size of 841 simulated stars.\nFigure \\ref{fig:CMD_age} shows the position of these stars on an HRD\n(with \\logg\\ on the y-axis instead of luminosity to improve the visibility of\nthe MS), colored by their age.\nRotation periods for these stars were generated using the gyrochronology\nrelation described in equation \\ref{eqn:gyro}.\nWe added 5\\% Gaussian noise to all stellar rotation periods to represent\nrealistic measurement uncertainties of 5\\%.\nThe median uncertainty on rotation periods calculated from \\kepler\\ light\ncurves, provided in the \\citet{mcquillan2014} catalog is 1\\%.\nHowever, the \\citet{aigrain2015} injection and recovery study showed that true\nrotation period uncertainties are often slightly larger than this, and noise\ndistribution of rotation periods can be highly non-Gaussian\n\\citep[\\eg][]{aigrain2015, angus2018}.\n\\begin{figure}\n  \\caption{\n      The simulated star sample plotted on an HRD, colored by age\n    (top panel) and rotation period (bottom panel).\n    HRD positions were calculated using MIST isochrones via the {\\tt\n    isochrones.py} {\\it Python} package and rotation periods were generated\n    using equation \\ref{eqn:gyro}.\n    This figure was generated in a Jupyter notebook available at\n    \\url{https://github.com/RuthAngus/stardate/blob/master/paper/code/Simulate_data.ipynb}\n}\n  \\centering\n    \\includegraphics[width=1\\textwidth]{simulated_CMD}\n\\label{fig:CMD_age}\n\\end{figure}\nFigure \\ref{fig:rotation_model} shows the rotation periods of 841\nstars generated from the gyrochronology model.\n\\begin{figure}\n  \\caption{\nData simulated from the rotation period model.\n    Late F, GK and early M dwarfs (stars with 0.56 $<$ \\gcolor\\ $<$ 2.7 follow\n    the Praesepe-calibrated gyrochronology relation (dashed gray lines), with\n    the exception of old, slowly\n    rotating stars with large Rossby numbers whose rotation periods are fixed\n    at 2$\\times$ their convective overturn time.\n    The rotation periods of early F (\\gcolor $<$ 0.56), late M dwarfs (\\gcolor\n    $<$ 2.7) and subgiants (EEP $\\gtrsim$ 420) were generated\n    from a log-normal distribution with standard deviation given by equation\n    \\ref{eqn:gyro}.\n% The top panel shows the rotation periods vs. B-V colors of simulated stars,\nThe top panel shows the rotation periods vs. \\gcolor\\ colors of simulated stars,\n    colored by their age and the bottom panel shows the same stars colored\n    by their equivalent evolutionary phase (EEP).\n    % 9, 11, and 13 (rotation periods rise with age).\n    The gray lines describe the mean gyrochronology model at ages 1,\n    3, 5, 7, 9, 11, and 13 (rotation periods rise with age).\n    This figure was generated in a Jupyter Notebook, available at\n    \\url{https://github.com/RuthAngus/stardate/blob/master/paper/code/Simulate_data.ipynb}\n}\n  \\centering\n    \\includegraphics[width=1.\\textwidth]{rotation_model_praesepe}\n\\label{fig:rotation_model}\n\\end{figure}\n\nWe took two approaches to inferring the ages of these simulated stars:\nfirstly using isochrone fitting {\\it only}, and secondly using isochrone\nfitting {\\it combined with} a gyrochronology model (\\sd).\nSince the posterior PDFs of stars are often multimodal, we found that the\nchoice of initial positions of the {\\tt emcee} walkers influenced the final\noutcome because walkers occasionally got stuck in local minima.\nWe found that the following set of initial parameters worked well, though not\nperfectly: EEP = 330, $t = 9.56$ Gyr, $[M/H] = -0.05$, $D = 269$ pc and $A_V =\n0.0$\\footnote{These are the default initial parameters provided in \\sd.}.\nFigure \\ref{fig:simulation_results} shows the results of combining\ngyrochronology with isochrone fitting for the simulated sample.\nThe stars' true ages are plotted against their predicted ages, with ages\ninferred with gyrochronology and isochrone fitting\nin color, and ages inferred using isochrone fitting only plotted in light\ngrey.\nThe different panels show the results for different types of stars: FGK\ndwarfs that are still undergoing magnetic braking, FGK dwarfs that have ceased\nmagnetic braking (their Rossby number is around 2), M dwarfs, and evolved\nstars.\nThe selection criteria for these groups are in the panel headings.\nThe FGK dwarfs with low Rossby numbers showed the largest improvement: the\nmedian age precision for this group (defined as the standard deviation of the\nposterior as a percentage of the median age) was 8\\% when using a combination\nof isochrones and gyrochronology, and 22\\% using isochrone fitting alone.\nThis equates to an almost 3$\\times$ improvement in age precision.\nThe age RMS of this group was 0.8 Gyr using isochrones and gyrochronology, and\n2 Gyr using isochrones only.\nDespite the fact that stars with Rossby numbers of 2 have stopped spinning\ndown and their rotation periods no longer evolve with age, the ages of these\nstars can still be relatively precisely constrained with isochrone fitting.\nThe median age precision for stars with large Rossby numbers was 11\\% with\ngyrochronology and isochrone fitting, and 13\\% with isochrone fitting only.\n% This is because their rotation periods are still directly related to their\n% age, but also {\\it indirectly} related to their age via EEP and metallicity,\n% as shown in equation \\ref{eqn:gyro}.\n% When including rotation periods to infer the ages of stars with large Rossby\n% numbers, age precision improves from 21\\% to 11\\% and the age RMS improves\n% from 2.5 to 0.9 Gyr.\n% Age precision also increases for F dwarfs when incorporating their rotation\n% periods, even though they are not directly related to their ages.\n% This is because rotation period relates to color via the variance model in\n% equation \\ref{eqn:gyro}.\nThe precision of M dwarf ages did improve overall when their rotation periods\nwere included, but this improvement was entirely driven by the early M dwarfs.\nThe precision of this group improved overall from 33\\% to 22\\% and RMS from\n5.4 Gyr to 4.6 Gyr.\nThe precision of ages inferred for evolved stars changed very little when\nrotation periods were included in the inference process.\nThis is because the variance of the rotation-age relation was inflated by a\nlarge amount in the gyrochronology model (equation \\ref{eqn:gyro}), making\nrotation periods almost entirely uninformative for this group.\nThe median age precision of subgiants from both gyrochronology and isochrone\nfitting and isochrone fitting alone was 7\\%.\n\n\\begin{figure}\n  \\caption{\nThe true vs. predicted ages of simulated stars.\n    Ages calculated by combining gyrochronology\n    and isochrone fitting with \\sd\\ are shown in color and ages calculated with\n    isochrone fitting only are shown in gray.\nThe different panels show the results for stars\n    with \\gcolor\\ $<$ 2.2 (FGK dwarfs) that are still braking magnetically\n    ($Ro < 2$), stars with \\gcolor\\ $<$ 2.2 that have stopped braking\n    magnetically ($Ro \\geq 2$),\n    stars with 2.2 $<$ \\gcolor\\ (M dwarfs), and evolved stars (EEP $>$ 420).\nGyrochronology is highly effective for FGK stars and ages inferred with both\n    gyrochronology and isochrone fitting are more accurate and precise than\n    ages inferred via isochrone fitting only for this group.\nNeither gyrochronology nor isochrone fitting can provide precise ages for\n    M dwarfs, so the ages of these stars are imprecise regardless of\n    age-dating method.\n    This figure was generated in a Jupyter Notebook available at\n    \\url{https://github.com/RuthAngus/stardate/blob/master/paper/code/Results_plots.ipynb}.\n}\n  \\centering\n    \\includegraphics[width=1\\textwidth]{simulation_results}\n\\label{fig:simulation_results}\n\\end{figure}\n\nAn important caveat associated with these results is that they strongly depend\non the uncertainties adopted for all observables used in the analysis: \\teff,\n\\feh, \\logg, $G$, $G_BP$, $G_RP$, $J$, $H$, $K$, $B$, $V$, and rotation\nperiod.\nChanging the uncertainties on these observables will affect the uncertainties\non inferred ages in different ways.\nThis demonstration is not intended to reflect the typical age uncertainties\nthat will result for all stars in reality, it merely exemplifies the increase\nin stellar age precision that results from one specific choice of\nuncertainties.\nNeedless to say, estimating the uncertainties on observables accurately can be\nas important as accurately measuring the observables themselves.\n\n% Figure \\ref{fig:all_iso_gyr} shows the inferred vs. true ages of all simulated\n% stars, colored by their \\gaia\\ \\gcolor\\ age.\n% The ages of FGK stars (\\gcolor\\ $<$ 2.2) were more precisely recovered with\n% gyrochronology and isochrone fitting than with isochrone fitting alone.\n% In both cases M dwarfs ages were not precisely recovered.\n% \\begin{figure}\n%   \\caption{\n%       Inferred vs. true ages for all simulated stars using isochrones plus\n%       gyrochronology via the \\sd\\ code (left) and isochrones only (right).\n%       Stellar ages are colored by \\gaia\\ \\gcolor\\ color.\n%       The ages of FGK stars (\\gcolor\\ $<$ 2.2)\n%       were more precisely recovered with \\sd\\ than with isochrones only.\n%       In both cases M dwarfs ages were not precisely recovered.\n%       Points in the lower right of the left panel are either M dwarfs or\n%       evolved (EEP $>$ 400).\n%       In both panels, the ages of FGK stars were slightly underestimated.\n% }\n%   \\centering\n%     \\includegraphics[width=1\\textwidth]{all_iso_gyro}\n% \\label{fig:all_iso_gyro}\n% \\end{figure}\n\n% Figure \\ref{fig:eep} shows the inferred equivalent evolutionary phase (EEP)\n% for the simulated star sample.\n% EEP is a dimensionless number that describes evolutionary stage and, combined\n% with age and metallicity, determines stellar mass.\n% An interesting result of inferring stellar properties with both isochrones\n% {\\it and} rotation periods is an increase in EEP precision, .\n% The reason for this is partly that EEP and age are correlated, so shrinking\n% the age posterior also shrinks the EEP posterior, and partly because rotation\n% period is a function of HRD position.\n% As shown in equation \\ref{eqn:gyro}, rotation period does not just depend on\n% color and age, but also on EEP and [Fe/H].\n% \\begin{figure}\n%   \\caption{\n%     Inferred EEP for the simulated star sample with isochrones plus\n%     gyrochronology (left panel) and isochrone fitting only (right panel).\n%     Rotation periods provide information about position on the HRD via\n% equation \\ref{eqn:gyro} and therefore improve all stellar parameters, not\n% just age.\n%     This figure was generated in a Jupyter Notebook available at\n%     \\url{https://github.com/RuthAngus/stardate/blob/master/paper/code/Results_plots.ipynb}.\n% }\n%   \\centering\n%     \\includegraphics[width=1\\textwidth]{eep}\n% \\label{fig:eep}\n% \\end{figure}\n% In general, the posterior PDFs of stellar properties, inferred using\n% isochrones or stellar evolution models, are multimodal.\n% The stars with under-predicted EEP in both panels of figure \\ref{fig:eep} are\n% slightly evolved, with EEPs $>$ 400.\n% These slightly evolved stars have two high probability modes: one at their\n% true EEP and age values, and another at a lower EEP and corresponding lower\n% age.\n% In other words, these are subgiants being mistaken for dwarfs.\n% Rotation periods do not carry information for subgiants, so including the\n% rotation periods in the analysis of these stars doesn't break the degeneracy,\n% and this is why stars with under-predicted EEPs are present in both panels.\n% Stars with over-predicted EEPs in the right-hand panel of figure \\ref{fig:eep}\n% are usually dwarfs being confused for subgiants.\n% The rotation periods of dwarfs are informative, so when the rotation periods\n% are included in the analysis for these stars, the degeneracy is broken, the\n% amplitude of the secondary mode is reduced, and their EEP is correctly\n% inferred.\n\n% Figure \\ref{fig:precision} shows the simulated stars on an HRD, with\n% points colored by the precision of their predicted ages\n% (defined as the standard deviation of the age\n% posterior PDF, as a percentage of the median age).\n% The top panel shows the precision of ages calculated using both gyrochronology\n% and isochrone fitting via \\sd\\ and the bottom panel shows the precision of\n% ages calculated with isochrone fitting only.\n% Although these are empirical uncertainties, calculated via MCMC which only\n% approximates the age posterior PDFs, they nevertheless show that combining\n% gyrochronology and isochrone fitting improves age precision on the MS,\n% particularly at low masses.\n% \\begin{figure}\n%   \\caption{\n% Simulated stars on an HRD, colored by their relative age precision\n%     using gyrochronology and isochrone fitting via \\sd\\ (top panel) and\n%     isochrone fitting only (bottom panel).\n% Combining gyrochronology with isochrone fitting significantly improves stellar\n%     age precision on the MS.\n% Isochrone fitting provides precise ages for hot stars and subgiants and the\n%     rotation periods of these stars are relatively uninformative, so\n%     gyrochronology does not significantly improve their age precision.\n% The ages of late M dwarfs are highly imprecise because their ages are not well\n%     determined by either their rotation periods or their position on the HRD\n%     or CMD.\n%     This figure was generated in a Jupyter Notebook available at\n%     \\url{https://github.com/RuthAngus/stardate/blob/master/paper/code/Results_plots.ipynb}.\n% }\n%   \\centering\n%     \\includegraphics[width=1\\textwidth]{precision_plot}\n% \\label{fig:precision}\n% \\end{figure}\n\nThis simulation experiment was designed to show the theoretical improvement in\nage precision when gyrochronology is incorporated into isochrone fitting.\nHowever, it does not demonstrate the accuracy of this method because the test\ndata were simulated from the same model used to infer ages.\nThe results of this experiment are therefore extremely accurate by design.\nWhen applying this method to real data, the results will only be accurate if\nthe model is accurate.\nIn other words, \\sd, like any age-dating method, provides model-dependent\nages.\nStellar ages calculated with \\sd\\ depend on both the accuracy of the MIST\nmodels {\\it and} the accuracy of the gyrochronology model (equation\n\\ref{eqn:gyro}).\nIn order to test the accuracy of \\sd, we applied it to real data, as described\nin the following section.\n\n\\subsection{Test 2: Open clusters}\nIn order to test our model on real stars with known ages, we selected a sample\nof stars in the 2.5 Gyr NGC 6819 cluster.\nWe compiled \\kepler-based rotation periods \\citep{meibom2015}, \\Gaia\\\nphotometry and \\gaia\\ parallaxes for members of the NGC 6819 cluster.\nFigure \\ref{fig:NGC6819} shows the period-color relation of this\ncluster and figure \\ref{fig:NGC6819_results} shows the results of inferring\nthe ages of individual cluster members using a combination of gyrochronology\nand isochrone fitting (via \\sd) and isochrone fitting alone.\nThe ages of F stars in this cluster (\\gcolor\\ $\\sim$ 5.5-6.5) were relatively\nprecisely constrained by isochrone fitting alone because, at 2.5 Gyr, they are\napproaching the MS turnoff.\nFor these hot stars, ages inferred with gyrochronology and isochrones were\nsimilar to ages inferred with isochrones and similarly precise, showing that\nisochrones provide a lot of age information for these stars and rotation\nperiods do not add significantly more information.\nThe G and early K stars in this cluster (\\gcolor\\ $\\lesssim$ .65) were not\nprecisely recovered from isochrone fitting alone -- the isochrone-only age\nposteriors tend towards the prior which is a uniform distribution between 0\nand 13.8 Gyrs.\nThe median age of stars in the cluster was 4.27 $\\pm$ 0.48 Gyr when only\nisochrone fitting was used.\nIn contrast, including gyrochronology when inferring the ages of G and K stars\nin this cluster significantly improved age precision.\nThe median age of stars in this cluster was 2.63 $\\pm$ 0.16 Gyr when ages were\ninferred with a combination of isochrone fitting and gyrochronology, using the\nnewly calibrated Praesepe-based gyrochronology model.\nThe previously-calibrated \\citet{angus2015} model resulted in a median stellar\nage of 2.66 $\\pm$ 0.21 Gyr, which is still consistent with the established\ncluster age of 2.5 Gyr.\nThe median age of stars in the cluster using uncorrected photometry was\nslightly underestimated at 1.86 $\\pm$ 0.22 Gyr.\nThis suggests that, despite the fact that V-band extinction is marginalized\nover during the inference process, correcting for extinction {\\it before} ages\nare estimated will reduce bias introduced by dust.\n\n\\begin{figure}\n  \\caption{\n    The \\kepler-based rotation periods of members of the 2.5 Gyr NGC 6819 open\n    cluster.\n    The raw \\gcolor\\ colors are shown in red and the dust-corrected colors are\n    shown in black.\n    The dashed line shows a gyrochronology model that was fit to the Praesepe\n    cluster and the Sun in this work, interpolated to 2.5 Gyrs.\n    The solid blue line shows a previously calibrated gyrochronology model\n    \\citep{angus2015}.\n    This figure was generated in a Jupyter Notebook available at:\n    \\url{https://github.com/RuthAngus/stardate/blob/master/paper/code/NGC6819.ipynb}\n  }\n  \\centering\n    \\includegraphics[width=1\\textwidth]{NGC6819}\n\\label{fig:NGC6819}\n\\end{figure}\n\n\\begin{figure}\n  \\caption{\n    The inferred ages of members of the NGC 6819 open cluster as a function of\n    their \\gcolor\\ color.\n    Ages of stars inferred using a combination of isochrone fitting and\n    gyrochronology (Praesepe and Sun calibration) with dereddened \\gaia\\ $G$,\n    $G_{BP}$, and $G_{RP}$ photometry (black circles) and uncorrected, raw,\n    photometry (red squares).\n    % Black circles and red squares show the ages of stars inferred using a\n    % combination of isochrone fitting and gyrochronology, with a gyrochronology\n    % relation that was calibrated to Praesepe and the Sun.  Black circles show\n    % ages inferred with dereddened \\gaia\\ $G$, $G_{BP}$ and\n    % $G_{RP}$ photometry and red squares show ages inferred with uncorrected,\n    % raw, photometry.\n    Even though V-band extinction is marginalized over in the inference\n    process, reddening can still bias ages.\n    Blue triangles, pointing up, show ages inferred using isochrone fitting\n    and gyrochronology, with the \\citet{angus2015} gyrochronology model.\n    Orange triangles, pointing down, show ages inferred using isochrone\n    fitting only.\n    The ages of F stars (stars bluer than 0.7) were precisely constrained by\n    isochrones and including gyrochronology makes little difference to their\n    inferred ages.\n    The age precision of G and K dwarfs (stars redder than 0.7) was improved\n    by including gyrochronology.\n    The median age of stars inferred using the gyrochronology model\n    calibrated to Praesepe and the Sun (black circles) was 2.65 $\\pm$ 0.13\n    which is consistent with the established cluster age (2.5 Gyr).\n    This figure was generated in a Jupyter Notebook available at:\n    \\url{https://github.com/RuthAngus/stardate/blob/master/paper/code/NGC6819.ipynb}\n}\n  \\centering\n    \\includegraphics[width=1\\textwidth]{NGC6819_results}\n\\label{fig:NGC6819_results}\n\\end{figure}\n\nWe found that 5\\% rotation period uncertainties resulted in the most accurate\nages for NGC 6819.\nThe uncertainties on the measured rotation periods, provided in\n\\citet{meibom2015} and shown in figure \\ref{fig:NGC6819}, were likely\nunderestimated for some stars.\nUnderestimated rotation period uncertainties can result in inaccurate age\nestimates.\nThis raises the question: how should uncertainties on rotation periods be\nestimated?\nThe likelihood is weighted by the inverse variance, so uncertainties on the\nrotation period control the relative information provided by gyrochronology,\nisochrones, and the prior.\nIf rotation period uncertainties are either too large or too small, the\nresulting age estimate will be imprecise and/or inaccurate.\nIt is difficult to measure uncertainties on rotation periods directly:\nstandard techniques such as Lomb-Scargle periodograms and autocorrelation\nfunctions do not provide them.\n% In general, formal rotation period uncertainties should probably be calculated\n% empirically via simulations as in the \\citet{aigrain2015} study.\n\\racomment{Ideally, rotation period uncertainties should capture {\\it both} the\nmeasurement precision, {\\it and} the physical uncertainty introduced by the\nlatitudinal movement of star spots on the surface of a differentially rotating\nstar.\nFor example, \\citet{donahue1996} demonstrated that the seasonal variation in\nmeasurements of G and K star rotation periods is a function of period, $\\Delta\n\\mathrm{P_{rot}} \\propto \\mathrm{P_{rot}}^{1.3\\pm0.1}$.\nThis variation is presumably caused by a latitudinal drift in the dominant\nactive regions, which traces the stellar cycle over several years, in\ncombination with latitudinal differential rotation.\nThis suggests that latitudinal spot drifting does not significantly\naffect stellar rotation periods when stars are young, for example the scatter\nof rotation periods about the mean gyrochronology model in Praesepe is only\naround 5\\%.\nHowever it is likely that this effect will become more important at older\nages.\n% The impact of this phenomenon on gyrochronology remain to be seen, and an\n% in-depth study is warranted.\nA thorough exploration of how rotation period uncertainties, from both\nmeasurement uncertainty and physical variation, affect stellar ages via\ngyrochronology is key to understanding the power of gyrochronology as an\nage-dating method.\nFor now, we leave this exploration for a future study.}\n\n\\subsection{Test 3: Kepler asteroseismic stars}\n\\racomment{In order to test our method in the regime where both isochrone\nfitting and gyrochronology become important, we recovered the ages of the 21\nasteroseismic stars analysed in \\citet{vansaders2016}.\nThese 21 stars were observed in \\kepler's short cadence mode and are a mixture\nof dwarfs and subgiants.\nTheir asteroseismic ages were calculated from the analysis of the frequencies\nof individual oscillation modes \\citep{mathur2012, metcalfe2014,\nsilvaaguirre2015, ceillier2016}, and their rotation periods from their\n\\kepler\\ light curves \\citep{garcia2014}.\nWe crossmatched these stars with the \\Gaia\\ catalog to obtain parallaxes and\napparant magnitudes in the \\Gaia\\ G, $\\mathrm{G_{BP}}$ and $\\mathrm{G_{RP}}$\nband passes.\nWe also added J, H and K 2MASS magnitudes from the Kepler input catalog\n\\citep{brown2011},\n% asteroseismic parameters $\\Delta_\\nu$ and $\\nu_{\\mathrm{max}}$ from\n% \\citet{ceillier2017} and \\citet{serenelli2017},\nand used spectroscopic effective temperatures, spectroscopic metallicities and\nrotation periods reported in table 1 of \\citet{vansaders2016}.\nThe \\gaia\\ photometry is extremely precise, and we found that artificially\ninflating the uncertainties on \\gaia\\ apparent magnitudes by a factor of 10\nsubstantially improved the quality of fit, both in terms of MCMC convergence\nand agreement with asteroseismic age measurements.\nIn figure \\ref{fig:astero} we show the ages of these 21 stars inferred using\nisochrone fitting and gyrochronology, against their asteroseismic ages,\ncalculated using the Asteroseismic Modeling Portal (AMP) \\citep{metcalfe2009,\nmetcalfe2012, metcalfe2014}.\nIn this figure, the colored symbols show ages inferred using a combination of\ngyrochronology and isochrone fitting, implemented with the \\sd\\ {\\it Python}\npackage.\nThe black and grey triangles show ages inferred from gyrochronology only,\nwhere the mass and color of the stars were not inferred, but fixed to be the\nasteroseismic mass and the \\gaia\\ \\gcolor\\ color.\nThese gyrochronal ages were calculated with age as the only free parameter,\nwithout marginalizing over stellar mass, \\gcolor\\ color or extinction.\nAs a result, these gyrochronal ages are {\\it not the same} as the ages given\nby the maximum of the gyrochronal likelihood function used in the combined\nage model, they simply represent an approximation to the gyrochronal age.\nGrey triangles are shown for stars where gyrochronology is not applicable\nbecause the stars are either too metal poor, too metal rich, or too evolved.\nBlack triangles are shown for stars where gyrochronology {\\it is} applicable.\nThe white circles show ages inferred from isochrones only.\nDashed lines connect the three different age measurements for the same\nstars.\n}\n\n\\racomment{\nAlthough the ages of all 21 stars shown in figure \\ref{fig:astero} were\ninferred with a joint isochronal and gyrochronal model, most (all but 8) were\neither too evolved, too metal poor, or too metal rich for gyrochronology to\ncontribute any information to the ages.\nThese metal poor/rich or evolved stars lie in a regime where the variance on\ntheir rotation period was artificially inflated because the gyrochronology\nrelations are not thoroughly understood or well calibrated.\nThe rotation periods of the remaining eight stars {\\it did} contribute to\ntheir inferred ages to some degree, however isochrones still dominated the age\ninformation for some of them because these stars are relatively old and/or\nrelatively hot.\n% Isochrones are information-rich for these hot and old stars, and this is\n% exactly where gyrochronology is at its most information-poor.\n}\n\n\\racomment{\nIn general, there is relatively poor agreement between the asteroseismic ages\nand the ages inferred using \\sd.\nMuch of this discrepancy is driven by differences in the isochronal ages,\nwhich is likely attributable to differences between the MIST stellar evolution\nmodels and those used in the AMP analysis: a combination of the Aarhus stellar\nevolution code \\citep[ASTEC][]{christensen-dalsgaard2008a} and the adiabatic\npulsation code \\citep[ADIPLS][]{christensen-dalsgaard2008b}.\nWe compared non-rotating, Solar-metallicity MIST isochrones for middle-aged\nstars with Solar-metallicity BaSTI isochrones \\citep{pietrinferni2004,\nhidalgo2018} and found that, for stars between 4 and 8 Gyrs, in the same\neffective temperature range as the asteroseismic stars, the age discrepancy\nbetween the two sets of models can be as large as 1-2 billion years.\nThe MIST isochrones lie above the BaSTI isochrones on the HR diagram, leading\nto a systematic underprediction of ages.\n}\n\n\\racomment{\nThe gyrochronal ages, where gyrochronology is applicable, do not show\nexcellent agreement with the asteroseismic ages either.\nThe four hot stars to the left in figure \\ref{fig:astero} are rotating more\nslowly than predicted by the Praesepe-based gyrochronology models, and as a\nresult their gyro-ages are older than their asteroseismic ones.\nFor these hot stars, two out of four have ages that are still consistent, or\nclose to consistent, with their asteroseismic ages.\nThe third star from the left is an anomalously slow rotator for its age and\nmass and \\citet{vansaders2016} also found this star to be surprisingly slowly\nrotating.\nIn contrast, the star with a black triangle symbol (indicating that\ngyrochronology is applicable) furthest to the right is {\\it rapidly} rotating\nfor its mass and age, even when weakened braking is taken into account.\n% Both stars are around Solar mass (1.06 \\pm 0.02 and 1.0 \\pm 0.03 M$_\\odot$\n% from left to right) and have asteroseismic ages older than the Sun (6.82 \\pm\n% 0.28 and 7.28 \\pm 0.51 Gyr from left to right), and yet both rotate more\n% rapidly than the Sun (23.2 \\pm 7.4).\nThis star is around Solar mass (1.0 $\\pm$ 0.03 M$_\\odot$) and has an\nasteroseismic age older than the Sun (7.28 $\\pm$ 0.51 Gyr), yet rotates with a\nperiod of only 19.8 $\\pm$ 1.3 days.\nThis is KIC 9098294, a single-lined spectroscopic binary with an orbital\nperiod of around 20 days (Latham, private communication).\nIt is the only clear SB1 in the \\citet{vansaders2016} sample, although some\nothers do have binary companions with long orbital periods, for which tidal\ninteractions are not expected to be strong.\n}\n\n\\begin{figure}\n    \\caption{ A comparison of stellar ages inferred using\n    asteroseismic modeling with ages inferred using a combination of isochrone\n    fitting and gyrochronology.\nColored circles show ages inferred using isochrone fitting and gyrochronology\ncombined via the \\sd\\ software package.\nBlack triangles show the ages of all stars inferred via gyrochronology only\n    and white circles show ages inferred via isochrone-fitting only.\n% This plot shows that, for the majority of stars in this sample, isochrone\n%     fitting dominates the age information and gyrochronology only contributes\n%     significantly for two or three stars.\n% This is a consequence of many of these stars being hot old, extremely metal\n%     rich, extremely metal poor, or evolved.\n  }\n  \\centering\n    \\includegraphics[width=1.2\\textwidth]{asteroseismic_results_nosdss_gaia}\n\\label{fig:astero}\n\\end{figure}\n", "meta": {"hexsha": "ed449b1c0392845dda109208e47e5adc058cfc03", "size": 31084, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/results.tex", "max_stars_repo_name": "john-livingston/stardate", "max_stars_repo_head_hexsha": "5c0d45c1e2eb9ec5b6c57aeacbcb301304065bbc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-02-19T13:46:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-31T23:46:36.000Z", "max_issues_repo_path": "paper/results.tex", "max_issues_repo_name": "john-livingston/stardate", "max_issues_repo_head_hexsha": "5c0d45c1e2eb9ec5b6c57aeacbcb301304065bbc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-02-21T21:37:05.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-09T10:38:15.000Z", "max_forks_repo_path": "paper/results.tex", "max_forks_repo_name": "john-livingston/stardate", "max_forks_repo_head_hexsha": "5c0d45c1e2eb9ec5b6c57aeacbcb301304065bbc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2019-02-11T02:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T22:16:53.000Z", "avg_line_length": 55.1134751773, "max_line_length": 93, "alphanum_fraction": 0.7804658345, "num_tokens": 7811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3479791562105448}}
{"text": "%!TEX root = ../PhD_thesis__Lilian_Besson\n\n% ----------------------------------------------------------------------\n\\chapter{Improving Spectrum Usage of IoT Networks with Selfish MAB Learning}\n\\label{chapter:4}\n\n\\graphicspath{{2-Chapters/4-Chapter/Images/}}\n\n\n\\abstractStartChapter{}%\n%\nAfter detailing in Part~\\ref{part:Introduction} the MAB model, we now come back to our main question of interest.\nIn this chapter, we focus on wireless networks following the hypotheses common to present and future Internet of Things (IoT) networks exposed in Chapter~\\ref{chapter:1}.\nOur goal is to show that the IoT devices can automatically learn to increase their battery life and their successful transmission rates, without changing anything on the IoT standard side.\n%\nWe propose two models of IoT networks, composed of many independent IoT end-devices, that can use low-cost Reinforcement Learning (RL) algorithms in order to learn how to improve their spectrum access.\n%\nDecentralized RL for IoT lets the devices use acknowledgements sent back by their Base Station as a reward, instead of sensing feedback like for OSA.\nWe consider many independent ``dynamic'' devices, each communicating with a small probability at every instant.\nSimulations show that dynamic devices can greatly improve their spectrum efficiency,\nby using MAB algorithms like \\UCB.\n% in the case of a non-uniform distribution of the static devices in the channels\nWe also developed a proof-of-concept using USRP platforms, for a real-world validation of this approach.\n% Numerical simulations justify the interest of the approach,\n%  of the advantage of using MAB algorithms for the first model.\n%\n% On a simple example, we present in Section~\\ref{sec:4:gnuradio} a demonstration that implements and validates the proposed approach, using real wireless radio hardware.\n% The first model\n% % without retransmission of packets,\n% is interesting for its simplicity,\n% and because considering no retransmission can improve the battery life of IoT devices, at the cost of a lower Quality of Service (QoS).\n%\nIn a second step, we consider a second model where a dynamic device has to (try to) retransmit a message, in case of a failed first transmission, up-to a fixed number of retransmissions.\nWe compare heuristics based on \\UCB, and simulations confirm that the non-naive heuristics also significantly improve the network efficiency.\n% Interestingly, the simplest heuristic is found to be the most efficient one, as its simplicity implies a faster learning and convergence time.\n%\n% The second model is more interesting if the main target is an improvement of the QoS, rather than a longer battery life.\n\n\\minitocStartChapter{}\n\n% ----------------------------------------------------------------------------\n% \\section{Motivations for Selfish MAB Learning for IoT Networks}\n\\section{Introduction and motivations for MAB learning for IoT Networks}\n\\label{sec:4:motivations}\n% ----------------------------------------------------------------------\n\nAfter the first chapters that presented the model of MAB, we go back to the initial problems studied in this thesis, and thus we focus on Internet of Things (IoT) networks.\n%\nAs explained in the introduction in Chapter~\\ref{chapter:1},\nunlicensed bands are more and more used and considered for mobile and LAN (Local Area Network) and for Internet of Things communication standards.\n%  (Wi-Fi, LTE-U), (IoT) standards for short-range (ZigBee, Z-Wave, Bluetooth) and long-range (LoRaWAN, SIGFOX, Ingenu, Weightless) communications \\cite{Centenaro16}.\nThis heavy use of unlicensed bands, in particular with the expected exponential growth of the number of IoT devices, will cause performance drop, due to radio collisions that could even compromise IoT promises.\n\nEfficient Medium Access Control (MAC) policies allow devices to avoid interfering traffic and can significantly reduce the spectrum contention problem in unlicensed bands.\nAs end-devices battery life is a key constraint of IoT networks,\nand as IoT networks are decentralized, because the devices initiate transmissions,\nthis leads to IoT protocols using as low signaling overhead as possible and simple ALOHA-based mechanisms.\n%\nIn this chapter, we analyze the performance of Multi-Armed Bandits (MAB) algorithms, that could be used in combination with a time-frequency slotted ALOHA-based protocol.\nWe highlight that even without changing anything on the level of IoT standards, our proposal is just an add-on capability that can be used on a unit-per-unit basis.\nWe consider the \\UCB \\cite{Auer02}, and the Thompson-Sampling (TS) algorithms \\cite{Thompson33,AgrawalGoyal11,\nKaufmann12Thompson}, for the first model. For the demonstration as well as for the second model, without loss of generality, we preferred to focus on heuristics based on the simplest algorithm (\\ie, \\UCB), to give a clear presentation of the different ideas explored to solve the problem of learning in order to retransmit efficiently.\n\n% As detailed in Chapter~\\ref{chapter:1},\n% MAB learning has already been proposed in Cognitive Radio (CR) \\cite{Mitola99,Haykin05}, and in particular, for sensing-based Dynamic Spectrum Access (DSA) in licensed bands \\cite{Jouini10}.\n% For example,\n% proof-of-concepts like \\cite{kumar2016two} have proven the capability of such approaches on real radio signals for OSA,\n% and \\cite{Maghsudi16} shows how MAB learning can be applied for small cell management in licensed 5G networks.\n% Some analysis on real radio measurements made for HF ionospheric channels have also proven that solutions based on MAB learning is appropriate and solves efficiently this kind of decision-making problems on real-world wireless signals \\cite{Melian15}.\n% Recent works show that stationary MAB algorithms work well to solve reinforcement learning models that represent accurately real-world radio problems.\n% Recently, TS and \\UCB{} algorithms have been used for improving the spectrum access in (unlicensed) Wi-Fi networks, for instance by \\cite{Toldov16} or \\cite{Wilhelmi19collaborative,Wilhelmi19potential}.\n% % However, even with only one dynamic user using the learning algorithm, the background traffic or the traffic of the other devices is never really stationary or \\iid{}.\n\nWe present in Section~\\ref{sec:4:firstModel} how the MAB algorithms can be used in a unlicensed but frequency- and time-slotted IoT network.\nSeveral devices are using bandit algorithms, and the assumptions made by the stochastic bandit algorithms are not satisfied: as several agents learn simultaneously and their activation processes are random, their behavior is not stationary.\nAs far as we know, we provide the first practical study to confirm robustness of the use of stochastic bandit algorithms for decision making in IoT networks with a large number of intelligent devices in the network, which makes the environment ``strongly not stationary''.\nThis specific context makes it very hard to give mathematical proofs of convergence and of efficiency of bandit algorithms (that is why we relax the hypothesis and only consider up-to $M \\leq K$ players in Chapter~\\ref{chapter:5}).\nWe then validate the model with a hardware implementation on real radio signals, detailed in Section~\\ref{sec:4:gnuradio}.\n%\nWe conclude this chapter by presenting in Section~\\ref{sec:4:retransmissions} an extension of this model to take into account another aspect of the ALOHA protocol, that is the possibility for dynamic devices to retransmit their packets if the \\emph{Ack} was not received.\n\n\n\\paragraph{Publications.}\n%\nThis chapter is mainly based on our articles \\cite{Bonnefoi17,Besson2018ICT,Besson2019WCNC,Bonnefoi2019WCNC,MoyBesson2019,MoyBesson2019Annales}.\n\n\n% ----------------------------------------------------------------------------\n\\section[Selfish learning for many dynamic devices in an IoT network]{Selfish learning for many dynamic devices with low activation probabilities in an IoT network}\n\\label{sec:4:firstModel}\n% ----------------------------------------------------------------------\n\n% - ``Multi-Armed Bandit Learning in IoT Networks and non-stationary settings'', see https://hal.inria.fr/hal-01575419\n\n\\input{2-Chapters/4-Chapter/CrownCom_17/IoT_slotted.tex}\n\n\n\\newpage  % WARNING ?\n% ----------------------------------------------------------------------------\n% \\section{Test-bed implementation of the first model for real-world validation}\n\\section{Proof-of-concept of our model for real-world validation}\n\\label{sec:4:gnuradio}\n% ----------------------------------------------------------------------\n\n% - ``MALIN: Multi-Arm bandit Learning for Iot Networks with GRC: A TestBed Implementation and Demonstration that Learning Helps'', demo at ICT, and the companion paper ``GNU Radio Implementation of MALIN: \"Multi-Armed bandits Learning for Internet-of-things Network\"'', see https://hal.inria.fr/hal-02006825\n\n\\input{2-Chapters/4-Chapter/IEEE_WCNC_2019__DemoICT/IEEE_WCNC_2019__DemoICT.tex}\n\n\n\n\\newpage  % WARNING ?\n% ----------------------------------------------------------------------------\n\\section{Extending the model to account for retransmissions}\n\\label{sec:4:retransmissions}\n% ----------------------------------------------------------------------\n\n% - ``Upper-Confidence Bound for Channel Selection in LPWA Networks with Retransmissions'', see \\texttt{https://perso.crans.org/besson/articles/BMBM\\_\\_IEEE\\_WCNC\\_2019.pdf}\n\n\\input{2-Chapters/4-Chapter/IEEE_WCNC__2019__Paper__BMBM/IEEE_WCNC__2019__Paper__BMBM.tex}\n\n\n\\newpage  % WARNING ?\n% ----------------------------------------------------------------------------\n\\section{Conclusion -- Towards theoretical guarantees}\n% \\section{Conclusion}\n\\label{sec:4:conclusion}\n% ----------------------------------------------------------------------\n\n% % We give in this section conclusions about the two models presented above, one for long-life IoT devices (without retransmission) and for improved QoS devices (\\ie, with retransmissions), and about our demonstration, as well as directions of future works, some of which are currently being studied by researchers of our team.\n\n% % \\subsection*{Conclusions}\n\n% % ----------------------------------------------------------------------\n% % \\paragraph{Summary of the first model.}\n% \\label{sub:41:conclusion}\n\n% In Section~\\ref{sec:4:firstModel}, we proposed an evaluation of the performance of MAB learning algorithms in IoT networks,\n% with a focus on the convergence of algorithms, in terms of successful transmission rates, when the proportion of intelligent dynamic devices changes.\n% Concretely, increasing this probability allows to insert more devices in the same network, while maintaining a good Quality of Service.\n% Similarly, if the number of devices remain constant, increasing the successful transmission rate directly extends the IoT devices battery life, as they suffer less from failed transmissions.\n% We show that \\UCB{} and TS have near-optimal performance, even when their underlying \\iid{} assumption (see Chapter~\\ref{chapter:2}) is violated by the presence of many ``intelligent'' end-devices which follow a random activation process.\n% %\n% This is both surprising and encouraging, it shows that applying bandit algorithms tailored for a stochastic model is still useful in broader settings.\n% The fully \\emph{decentralized} application of classic stochastic MAB algorithms are almost as efficient as the best possible centralized policy in this setting, after a short learning period, even though the dynamic devices \\emph{cannot} communicate with each other, and \\emph{do not} know the system parameters.\n\n\n% % ----------------------------------------------------------------------\n% % \\paragraph{Conclusions taken from the demonstration.}\n% \\label{sub:42:conclusionFromDemonstration}\n\n% We presented in Section~\\ref{sec:4:gnuradio} a demonstration, showed in $2018$ at the ICT conference \\cite{Besson2018ICT}, and further detailed in the companion paper \\cite{Besson2019WCNC}.\n% We gave all the necessary details on both the PHY and the MAC layer, as well as details on the User Interface developed for the demo.\n% Results obtained in practice were discussed, to highlight the interest of using learning algorithms for radio online optimization problem, and especially multi-armed bandit learning algorithms.\n% %\n% By using such low-cost algorithms, we demonstrated empirically that a dynamically re-configurable device can learn on its own to favor a certain channel, if the environment traffic is not uniform between the $K$ different channels, by using the acknowledgement (\\Ack) feedback sent from the base station.\n\n\n% % ----------------------------------------------------------------------\n% % \\paragraph{Conclusion about this second model.}\n% \\label{sub:43:conclusion}\n\n% In Section~\\ref{sec:4:retransmissions}, we presented an extension of our model of LPWA networks based on an ALOHA protocol, slotted both in time and frequency.\n% % , in which dynamic IoT devices can again use machine learning algorithms, to improve their Packet Loss Ratio (PLR) when accessing the network.\n% If the priority is the Quality of Service, for instance with renewable energy capabilities, this second model is more appropriate.\n% The main novelty of this model is to address the packet retransmissions upon radio collision, by using a Multi-Armed Bandit framework.\n% We presented and evaluated several heuristics that try to learn how to transmit and retransmit in a smarter way, by using the \\UCB{} algorithm for channel selection for first transmission, and different proposals based on \\UCB{} for the retransmissions upon collisions.\n% %\n% We showed that incorporating learning for the transmission is needed to achieve optimal performance, with significant gain in terms of successful transmission rate in networks with a large number of devices (up-to $30\\%$ in the example network).\n% Our simulations show that each of our proposed heuristic outperforms a naive random access scheme.\n% Surprisingly, the main take-away message is that a simple \\UCB{} learning approach, that retransmit in the same channel, turns out to perform as well as more complicated heuristics.\n\n\n% % ----------------------------------------------------------------------\n% \\subsection*{Future works}\n% \\label{sub:4:futureWorks}\n\n% % Future works related to this chapter include the following directions.\n\n\n% % \\paragraph{Possible extensions of the first model.}\n\n% The first model presented in Section~\\ref{sec:4:firstModel} could easily be generalized with two probabilities $p_S$ and $p_D$, if static and dynamic devices have different transmission pattern, and less easily with one probability per device. Also, other emission pattern could be considered, instead of a Bernoulli process for each user.\n% In this whole Chapter~\\ref{chapter:4}, we prefer to consider that all devices have the same activation probability, to keep the notation as simple as possible.\n% %\n% Moreover, for sake of simplicity we supposed that all devices use the same standard.\n% Future works could consider more realistic interference scenarios and IoT networks, with, \\eg, non-slotted time, more than one base station etc.\n\n% Another extension could be to not have a Bernoulli process (or any random process), but a fixed rate of transmission, \\eg, one transmission a day.\n% So additionally to deciding the channel for communication (\\ie, \\emph{where} to communicate), each device has to also decide \\emph{when} to communicate.\n% % This is another direction of research, that we will investigate in the future.\n% However, this clearly leads to a much larger action space, as there are many time slots in one day (for example), and thus we believe that as soon as the action space becomes too large in this extension, the simple MAB-based learning approach could be no longer appropriate.\n% It is well-known in the MAB literature that the larger the action space, the slower is the convergence speed of any stationary MAB algorithms.\n% It could be interesting to study the possible application of \\emph{contextual} MAB \\cite{Li10,Luo18} or structured MAB \\cite{Combes17} models and algorithms for this extension.\n\n% % We will investigate this behavior in order to understand it better theoretically.\n% % We will also experiment more with adversarial algorithms, to confirm that they work less efficiently than stochastic bandit algorithms in our non-stochastic setting.\n\n% % \\paragraph{Extensions of the demonstration.}\n\n% Possible future extensions of our demonstration include the following points.\n% We could consider more dynamic devices (\\eg, $100$) but it would either cost more in terms of equipment, or in terms of software engineering to simulation more devices with the same card.\n% We could also implement a real-world IoT communication protocol (like the LoRaWAN standard), which we prefer not to do as it would cost a significant effort of development.\n% Finally, we could also study the interference in case of other gateways located nearby, and this could be done without needing a lot of new hardware (using one extra USRP card to simulate another gateway).\n% %\n% % Pub pour notre autre article\n% % We are also interested in studying the possible gain of using a learning step when the transmission model follows ALOHA-like retransmissions, and this is presented in the next Section~\\ref{sec:4:retransmissions}.\n\n\n% % \\paragraph{Possible extensions for the second model.}\n\n% Finally, the utility and impact of the proposed approaches for LPWA networks motivates us to address several subjects as future works. Among them, the non-stationarity of the channel occupancy caused by the learning policy employed by the IoT devices.\n% %\n% For that end, modifications of MAB algorithms have been proposed, such as Sliding-Window-\\UCB{} or Discounted-\\UCB{} \\cite{Garivier11UCBDiscount}\n% or more recently M-\\UCB{} \\cite{CaoZhenKvetonXie18},\n% or more recently GLR-\\UCB{} \\cite{Besson2019GLRT} which is presented in Chapter~\\ref{chapter:6},\n% that nevertheless have not been explored for the targeted problem.\n% Chapter~\\ref{chapter:6} is focusing on this direction, but we did not have enough time to explore the possible applications of MAB policies designed for non-stationary problems to the model with retransmissions presented in this Chapter.\n\n% In order to validate our results in a realistic experimental setting and not only with simulations, future works include a hardware implementation of the analyzed models to complete our demonstration \\cite{Besson2019WCNC}.\n% Note that Julio César Mango-Vasquez is currently working on this direction, for the EPHYL project, in collaboration with Carlos Faouzi Bader at IETR and CentraleSupélec campus of Rennes.\n% % and Christophe Moy at IETR and University Rennes 1.\n% %\n% A hardware demonstrator could be also benefit to study other settings by removing some hypotheses, for instance by studying a similar model in non-slotted time.\n\n\n% \\subsection*{Summary of this chapter}\n\nWe focused in this chapter on models of IoT networks, and we proposed to use classical stationary multi-armed bandit learning algorithms implemented in a selfish and decentralized manner by each of the dynamic devices in the IoT network.\nWe presented two models of wireless IoT networks, without relying on the feedback provided by spectrum sensing, and inspired by the ALOHA protocol. We proposed two versions, with or without retransmissions of up-link packages in case of collisions.\n% In both cases, we try to model the existing standards, like the LoRa standard, and we demonstrated the efficiency of the proposed MAB-based approach in both numerical simulations and empirical measurements on real wireless radio signals.\n%\nWe conclude that this learning-based approach is efficient, as it allows the IoT devices to automatically and independently increase their successful transmission rates.\n\nIt is also quite surprising that stochastic MAB algorithms can be of any use in such non-stationary applications.\nUnfortunately, it turned out to be of extreme difficulty to analyze analytically the considered model with thousands of independent devices, all communicating and learning in their own (random) time scales.\nThat is why we focus on two different simplifications of this model in the next chapters, for which we are able to provide a rigorous theoretical analysis.\n% %\n% We can also highlight that the two models we studied are complementary:\n% the first model (without retransmission of packets), is interesting for its simplicity, and focused on improving the battery life of IoT devices,\n% % , at the cost of a lower Quality of Service (QoS),\n% %\n% while the second model is more interesting if the main target is an improvement of the Quality of Service (QoS).\n% % , rather than a longer battery life.\n\n\n\\paragraph{Multi-Players MAB.}\n%\nOn the one hand, we are actually able to analyze a simpler model, if we assume to have at most $M \\leq K$ devices with a transmission probability of $p=1$.\nInstead of the experiment-driven direction pursued in this chapter, another possibility is to consider a \\emph{multi-players MAB} model to describe our problem.\n%\nThe main difference between the two models is the fact that in Chapter~\\ref{chapter:4}, $M \\gg K$ devices transmit their messages at every time step, by following a random activation process (with a fixed transmission probability $p < 1$).\nIf static and dynamic devices that have to transmit at a fixed time are denoted \\emph{active devices},\nthen their random activation patter makes the number of active devices an (unpredictable) random variable.\nAnalyzing multi-players MAB models under this hypothesis is much harder, and is left as a future work.\n%\nWe study the case of $M \\leq K$ devices learning independently to play a $K$-armed bandit in the next Chapter~\\ref{chapter:5}.\n\n% In that case, the static and dynamic devices effect is decoupled, and arms only model the availability of the channels in the absence of dynamic devices: they are \\iid{} with mean $\\mu_i = 1 - p S_i$.\n% Moreover, dynamic devices are usually assumed to be able to \\emph{sense} a channel before sending \\cite{Zhao10}, and so communicate only if no static device is detected on the channel.\n% The smart devices try to learn the arms with highest means, while coordinating to choose different arms, \\ie, avoid collisions in their choice, in a decentralized manner.\n% However, in this model it is assumed that the multiple agents can know that they experienced a collision with another agent, which is non-realistic for our problem at stake, as our model of smart device cannot do sensing nor differentiate collisions between smart and non-smart devices.\n\n\n\\paragraph{Non-stationary MAB.}\n%\nOn the other hand, while it is hard to analyze the models of this chapter because of the unpredictable behaviors of the IoT devices' activation patterns and the evolving number of active devices, we are also able to analyze a simpler model, if we focus on a single player accessing a network which is assumed to be \\emph{piece-wise stationary},\nthat are bandit problems which are stationary on ``long enough'' intervals, of unknown locations and lengths.\n%\nWe then study this second direction in Chapter~\\ref{chapter:6}.\n\n\n\\newpage\n% ----------------------------------------------------------------------------\n\\section{Appendix}\n\\label{sec:4:appendix}\n\n\\subsection{Proof of Proposition~\\ref{prop:41:Lagrangian}}\n\\label{sec:4:proofLagrangian}\n% ----------------------------------------------------------------------------\n\n% We include here a missing proof from Section~\\ref{sec:4:firstModel}.\n\n\\input{2-Chapters/4-Chapter/CrownCom_17/IoT_slotted_appendix.tex}\n\n\n\\newpage\n\\subsection{Illustration of the GNU Radio Companion Flowcharts}\n\\label{sec:4:IllustrationFlowcharts}\n% ----------------------------------------------------------------------------\n\n\\input{2-Chapters/4-Chapter/IEEE_WCNC_2019__DemoICT/IEEE_WCNC_2019__DemoICT_appendix.tex}\n", "meta": {"hexsha": "9ca8ff915f511f66072090065ae7222e9b8f6535", "size": 23996, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "2-Chapters/4-Chapter/chapter4.tex", "max_stars_repo_name": "Naereen/phd-thesis", "max_stars_repo_head_hexsha": "0fa93ca0d738771f4215bc4aeb66157f2026ba00", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-11-18T12:22:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T19:29:48.000Z", "max_issues_repo_path": "2-Chapters/4-Chapter/chapter4.tex", "max_issues_repo_name": "Naereen/phd-thesis", "max_issues_repo_head_hexsha": "0fa93ca0d738771f4215bc4aeb66157f2026ba00", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-11-18T09:19:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-08T14:13:08.000Z", "max_forks_repo_path": "2-Chapters/4-Chapter/chapter4.tex", "max_forks_repo_name": "Naereen/phd-thesis", "max_forks_repo_head_hexsha": "0fa93ca0d738771f4215bc4aeb66157f2026ba00", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-05-28T20:56:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-13T11:11:57.000Z", "avg_line_length": 82.1780821918, "max_line_length": 344, "alphanum_fraction": 0.7519586598, "num_tokens": 5095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3478862186402445}}
{"text": "\\chapter{Mass Relations and Stoichiometry}\n\\section{Atomic Mass}\nTo determine the weight of an atom, scientists developed a small unit at which\nsuch quantities may be measured.  This unit is know as the AMU, or\n\\textit{atomic mass unit}.\n\n12 AMUs are defined as the weight of one atom of the Carbon-12 isotope.  That is\nto say that $1amu$ is exactly the weight of 1/12th of one atom of Carbon-12.\n\n\\subsection{Masses of Elements}\nHowever, the numbers on the periodic table are not so round?  Why might this be?\nWell, since we are accounting for isotopes, we must apply a weighted average to\nall naturally occuring isotopes.  For example:\n\n\\begin{table}[h]\n\\begin{tabular}{lll}\n\\hline\n          & Abundance & \\textit{Mass (amu)} \\\\ \\hline\noxygen-16 & 99.762\\%  & 15.994              \\\\\noxygen-17 & 0.038\\%   & 16.999              \\\\\noxygen-18 & 0.200\\%   & 17.999\n\\end{tabular}\n\\end{table}\n\nThe calculation for the relative \\textit{amu} of Oxygen is as follows:\n$(0.99762*15.994) + (0.00038*16.999) + (0.00200*17.999) = 15.9994amu$\n\n\\section{The Mole}\nAvagadro's Number (or $N_A$) is thought of a quantity, usually of atoms.  The\nnumber of that quantity is $6.022e23$.  Therefore, since this is a quantity, the\nunit is $anything/mole$.\n\n\\subsection{Molar Mass}\n\\subsubsection{Of Elements}\nTo calculate the molar mass of an element: simply look to the periodic table!\nIn the upper-left of the element box, you will find the relative molar mass of\nthe element.  That is to say, the \\textit{amu} of an element is the weight in\ngrams of one mole of that element.  For example, $1.008mol$ of \\ce{H} weighs\n\\ce{1g}.\n\n\\subsubsection{Of Compounds}\nSimply put, the molar mass of a compound is the sum of all its parts, multiplied\nindividiually by each of the relative quantities.\n\n\\section{Percent Composition}\n\\textbf{Percent composition} of an element is the percent by mass of itself\nwithin a compound.  For example, the molar mass of \\ce{Cu2S} is 159.2.  The mass\namount of \\ce{Cu}\n\n\\subsection{Empirical Formulae}\nAn \\textit{emperical formula} consists of the sumbols for the elements combined\nin a compound, with subscripts showing the smallest whole-number mole ratio of\nthe different atoms in the compound.\n\nFor example, the emperical formula \\ce{P2O5} might lead to a chemical formula of\n\\ce{P4O10}, or similarily, the emp. formula \\ce{C3H6O} may lead to the formula\n\\ce{C6H18O2}.\n\n\\subsubsection{Calculating}\nTo calculate an emperical formula, you must first start with the percentages of\nan atom or the mass of the atom present.  Once these are determined, you may\nthen convert to moles, and simplify the ratio by dividing by the smallest amount\nand rounding.  If you cannot round cleanly, multiple the whole ratio by a\nfactor.\n\nThe steps for calculating this emperical formula follow below:\n\n\\begin{enumerate}\n  \\item Assume $100g$s was sampled, unless given other measurements.\n  \\item Convert the grams to moles, unless given moles.\n  \\item Simplify the ratio of moles by dividing by the smallest term.\n  \\item Multiply by factors to arrive at cleaner ratios, if not already clean.\n\\end{enumerate}\n\n\\section{Stoichiometry}\nStoichiometry involves the mass relationships between reactants and products in\na chemical reaction.  IT allows you to determine the amount of additional\nreactants or products given the chemical equation and just one amount.\n\nStoichiometry relies on the ratios of moles between different compounds in a\nchemical reaction.  Consider the following reaction: \\ce{Al2(SO4)3 + 3Ca(OH)2 ->\n2Al(OH)3 + 3CaSO4}.  It has the following mass relations:\n\n\\begin{frame}\n  \\centering\n  {\\huge $\\frac{1mol \\ce{Al2(SO4)3}}{3mol \\ce{Ca(OH)2}}$, $\\frac{1mol\n  \\ce{Al2(SO4)3}}{2mol \\ce{Al(OH)3}}$, $\\frac{1mol \\ce{Al2(SO4)3}}{3mol\n  \\ce{CaSO4}}$}\n\\end{frame}\n\nTo work with these mass relations, you can convert from mass $\\rightarrow$ molar\nmass $\\rightarrow$ moles $\\rightarrow$ mole-to-mole ratio $\\rightarrow$ moles\n$\\rightarrow$ molar mass $\\rightarrow$ mass.\n\n\\subsection{Limiting Reagent}\nSometimes when doing stoichometry, one reagent appears in a limiting amount such\nthat you cannot fully complete the reaction.  These substances are known as\n\\textit{limiting reagents}.  The substances that is not completely used up in a\nreaction is referred to as an \\textit{excess reagent (reactant)}.\n\nTo determine the limiting reagent, just do the reaction with both against one of\nthe products and figure out which makes \\textit{less}.  The excess reagent will\nbe what is left over.  To determine the quantity of the excess reagent, use the\nquantity of the limiting reagent that you originally plugged in and wire that\nthrough.\n\n\\subsubsection{Percent Yield Calculations}\nSometimes, you are given an amount of which is supposed to occur (via\nstoichiometry) and an amount that you actually produced.  To calculate this, you\nuse the following:\n\n{\\huge $100 * \\frac{actual}{theoretical}$}\n", "meta": {"hexsha": "5b4595b11ab3246114462eb307600bf65a742fb6", "size": 4893, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "2015/chemistry/sections/stoichiometry.tex", "max_stars_repo_name": "ttaylorr/midterms", "max_stars_repo_head_hexsha": "fdde0fd1a66eb5242d0dfa04a5201c3ab6d6b7eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-01-06T06:55:26.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-06T06:55:26.000Z", "max_issues_repo_path": "2015/chemistry/sections/stoichiometry.tex", "max_issues_repo_name": "ttaylorr/midterms", "max_issues_repo_head_hexsha": "fdde0fd1a66eb5242d0dfa04a5201c3ab6d6b7eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2015/chemistry/sections/stoichiometry.tex", "max_forks_repo_name": "ttaylorr/midterms", "max_forks_repo_head_hexsha": "fdde0fd1a66eb5242d0dfa04a5201c3ab6d6b7eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.3008849558, "max_line_length": 80, "alphanum_fraction": 0.7572041692, "num_tokens": 1369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.34786381905871405}}
{"text": "\\documentclass[a4paper]{article}\n%\\usepackage[ngerman]{babel}\n\\usepackage[T1]{fontenc}\n\\usepackage[utf8]{inputenc}\n\\usepackage{textcomp}\n\\usepackage{geometry}\n\\geometry{ left=2cm, right=2cm, top=2cm, bottom=3cm, bindingoffset=5mm}\n\\usepackage{graphicx}\n\\usepackage{xcolor}\n\\usepackage{hyperref}\n\\usepackage{longtable}\n\\usepackage{amstext}\n\\usepackage{array}\n\\usepackage{amsmath}\n\\newcolumntype{L}{>{$}l<{$}}\n\\usepackage{tabularx, ragged2e}\n\\usepackage{helvet}\n\\renewcommand{\\familydefault}{\\sfdefault}\n\\usepackage{lastpage}\n\\usepackage{todonotes}\n\\usepackage{titlesec}\n\\titleformat*{\\section}{\\large\\bfseries}\n\\usepackage{listings}\n\\usepackage{color}\n\n\\usepackage{tikz}\n%\\newcommand{\\tikzmark}[2]{\\tikz[overlay, remember picture] \\node[inner sep=0pt, outer sep=0pt, anchor=base] (#1) {#2};}\n\\usetikzlibrary{tikzmark}\n\n\n\\definecolor{mygreen}{rgb}{0.18, 0.545, 0.341}\n\\definecolor{mygray}{rgb}{0.5,0.5,0.5}\n\\definecolor{myblue}{rgb}{0.53,0.61,0.85}\n\n\\lstset{\n keywordstyle=\\color{mygreen},\n commentstyle=\\color{mygray},\n numbers=left,\n numbersep=5pt, \n numberstyle=\\scriptsize\\color{mygray}\n }\n\n\\usepackage{amsmath,amssymb}\n\n\\DeclareRobustCommand{\\bbone}{\\text{\\usefont{U}{bbold}{m}{n}1}}\n\n\\DeclareMathOperator{\\EX}{\\mathbb{E}}% expected value\n\n\\date{}\n\\author{}\n\\usepackage{fancyhdr}\n\\pagestyle{fancy}\n\\fancyhf{}\n\\fancyhead[R]{Felix Burk\\\\ Pascal Huszár}\n\\fancyhead[L]{Reinforcment Learning \\\\ Summer Term 2021 }\n\\fancyfoot[R]{page \\thepage \\text{ }/ \\pageref*{LastPage}}\n%\\fancyfoot[LE]{Seite \\thepage \\text{ }von \\pageref{LastPage}}\n\\renewcommand{\\headrulewidth}{0.5pt}\n\n\\usepackage{amsmath}\n\\DeclareMathOperator*{\\argmax}{arg\\,max}\n\\DeclareMathOperator*{\\argmin}{arg\\,min}\n\n\n\\title{\\textbf{Exercise 09}}\n\n\\begin{document}\n\t\\maketitle \n\t\\thispagestyle{fancy}\n\t\n    \\section*{Task 1 - REINFORCE on the Cart-Pole}\n    \\subsection*{a)}\n    $\\frac{\\delta}{\\delta \\theta_a}\\frac{se^{s*\\theta_a^T+s*\\theta_b^T)}}{(e^{\\theta_a^T*s}+e^{\\theta_b^T*s})^2}$\n \t\\subsection*{b)}\n \t$\\pi(a|s,\\theta) = \\frac{e^{\\theta_a^T*s}}{e^{\\theta_b^T*s}+e^{\\theta_c^T*s}}$ where $b,c$ are all possible actions and $a \\in \\{b,c\\}$ \\\\\n \t$\\nabla_\\theta log(\\pi_\\theta(s,a)) = \\nabla_\\theta log(\\frac{e^{\\theta_a^T*s}}{e^{\\theta_b^T*s}+e^{\\theta_c^T*s}})$ \\\\\n \t$= \\nabla_\\theta log(e^{\\theta_a^T*s})-\\nabla_\\theta log(e^{\\theta_b^T*s}+e^{\\theta_c^T*s})$ \\\\\n \t$= \\nabla_\\theta \\theta_a^T*s*log(e)-\\nabla_\\theta log(e^{\\theta_b^T*s}+e^{\\theta_c^T*s})$ \\\\\n \t$= s -\\nabla_\\theta log(e^{\\theta_b^T*s}+e^{\\theta_c^T*s})$\n \t$= s -\\frac{\\nabla_\\theta log(e^{\\theta_b^T*s}+e^{\\theta_c^T*s})}{e^{\\theta_b^T*s}+e^{\\theta_c^T*s}}$ \\\\\n \t$= s - \\frac{e^{\\theta_b^T*s}}{e^{\\theta_b^T*s}+e^{\\theta_c^T*s}}$ \n \t$= \\frac{e^{\\theta_c^T*s}*s}{e^{\\theta_b^T*s}+e^{\\theta_c^T*s}}$\n \t$= \\frac{1}{1+e^{\\theta_c^T*s}}*s$ \\\\\n \tFor the case $a=c$, $a=b$ is equivalent.\n\n\n\\end{document}", "meta": {"hexsha": "92bef9ea13d64a8332ae7a60ead0b770b78470f3", "size": 2829, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ex09-pg/ex09.tex", "max_stars_repo_name": "FlxB2/rl-course", "max_stars_repo_head_hexsha": "0db6632fbb2e9f90977b5b3422494279477cb8a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ex09-pg/ex09.tex", "max_issues_repo_name": "FlxB2/rl-course", "max_issues_repo_head_hexsha": "0db6632fbb2e9f90977b5b3422494279477cb8a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ex09-pg/ex09.tex", "max_forks_repo_name": "FlxB2/rl-course", "max_forks_repo_head_hexsha": "0db6632fbb2e9f90977b5b3422494279477cb8a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5172413793, "max_line_length": 140, "alphanum_fraction": 0.6783315659, "num_tokens": 1153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.34786381905871405}}
{"text": "\\chapter{Course Introduction}\n\\label{cha:intro}\n\n\\sloppy\n%\\lecture{1 --- Wednesday, February 19th}\n%{Spring 2020}{Rasmus Kyng}{Course Introduction}\n\n\\section{Overview}\n This course will take us quite deep into modern approaches to\n graph algorithms using convex optimization techniques.\n%\n By studying convex optimization through the lens of graph algorithms,\n we'll try to develop an understanding of fundamental\n phenomena in optimization.\n %\n Much of our time will be devoted to flow problems on graphs.\n We will not only be studying these problems for their own sake,\n but also because they often provide a useful setting for thinking more broadly about optimization.\n\n The course will cover some traditional discrete approaches to various graph\n problems, especially flow problems, and then contrast these approaches\n with modern, asymptotically faster methods based on combining convex\n optimization with spectral and combinatorial graph theory.\n\n\\section{Electrical Flows and Voltages - a Graph Problem from Middle School?}\n\nWe will dive right into graph problems by considering how electrical\ncurrent moves through a network of resistors.\n\nFirst, let us recall some middle school physics.\nIf some of these things don't make sense two you, don't worry, in less\nthan paragraph from here, we'll be make to safely doing math.\n\nRecall that a typical battery that buy from Migros has two\nendpoints, and produces what is called a \\emph{voltage\n  difference} between these endpoints.\n\nOne end of the battery will have a positive charge (I think that means an excess of\npositrons\\footnote{I'm joking, of course! Try Wikipedia if you want to know\nmore. However, you will not need it for this class.}), and the other a\nnegative charge.\nIf we connect the two endpoints with a wire, then a current will flow\nfrom one end of the battery to the other in an attempt to even out\nthis imbalance of charge.\n\n\\begin{figure}[H]\n  \\centering\n  \\includegraphics[width=0.5\\linewidth]{fig/lecture1_battery9volts.png}\n  \\captionof{figure}{A 9 volts battery with a wire attached.}\n  \\label{fig:battery-volt}\n\\end{figure}\n\nWe can also imagine a kind of battery that tries to send a certain\namount of current the wires between its endpoints, e.g. 1 unit of charge per\nunit of time.\nThis will be a little more convenient to work with, so let us focus on\nthat case.\n\n\\begin{figure}[H]\n  \\centering\n  \\includegraphics[width=0.5\\linewidth]{fig/lecture1_battery1ampere.png}\n  \\captionof{figure}{A 1 ampere battery with a wire attached.}\n  \\label{fig:battery-current}\n\\end{figure}\n\nA \\emph{resistor} is a piece of wire that connects two\npoints $u$ and $v$, and is completely described by a single number $r$\ncalled its \\emph{resistance}.\n\nIf the voltage difference between the endpoints of the resistor is\n$x$, and the resistance is $r$ then this will create a flow of charge per unit of time of $f = x / r$.\nThis is called Ohm's Law.\n\n\\begin{figure}[H]\n  \\centering\n  \\includegraphics[width=0.5\\linewidth]{fig/lecture1_ohmslawx-vs-f.png}\n  \\captionof{figure}{Ohm's Law for a resistor with resistance $r = 1$.}\n  \\label{fig:ohmslaw}\n\\end{figure}\n\nSuppose we set up a bunch of wires that route electricity from our\ncurrent source $s$ to our current sink $t$ in some pattern:\n\n\\begin{figure}[H]\n  \\centering\n  \\includegraphics[width=0.5\\linewidth]{fig/lecture1_graphpath.png}\n  \\captionof{figure}{A path of two resistors.}\n  \\label{fig:graphpath}\n\\end{figure}\n\nWe have one unit of charge flowing out of $s$ per unit of time, and\none unit coming into $t$.\nBecause charge is conserved, the current flowing into any other point\n$u$ must equal the amount flowing out of it.\nThis is called Kirchoff's Current Law.\n\nTo send one unit of current from $s$ to $t$, we must be sending it\nfirst form $s$ to $u$ and then from $u$ to $t$.\nSo the current on edge $(s,u)$ is 1 and the current on $(u,t)$ is 1.\nBy Ohm's Law, the voltage difference must also be 1 across each of the two\nwires.\nThus if the voltage is $x$ at $s$, it must be $x+1$ at $u$ and $x+2$\nat $t$. What is $x$? It turns out it doesn't matter: We only care\nabout the differences. So let us set $x = 0$.\n\n\\begin{figure}[H]\n  \\centering\n  \\includegraphics[width=0.5\\linewidth]{fig/lecture1_graphpath-labelled.png}\n  \\captionof{figure}{A path of two resistors.}\n  \\label{fig:graphpathlabelled}\n\\end{figure}\n\n\nLet us try one more example:\n\n\\begin{figure}[H]\n  \\centering\n  \\includegraphics[width=0.5\\linewidth]{fig/lecture1_graphtriangle.png}\n  \\captionof{figure}{A network with three resistors.}\n  \\label{fig:graphtriangle}\n\\end{figure}\n\nHow much flow will go directly from $s$ to $t$ and how much via $u$?\n\nWell, we know what the net current flowing into and out of each vertex\nmust be, and we can use to set up some equations.\nLet us say the voltage at $s$ is $x_s$, at $u$ is $x_u$ and at $t$ is $x_t$.\n\\begin{tight_itemize}\n\\item Net current at $s$:   $-1 = (x_s-x_t) + (x_s-x_u)$\n\\item  Net current at $u$:   $\\phantom{-}0 = (x_u-x_s) + (x_u-x_t)$\n\\item Net current at  $t$:\\,   $\\phantom{-}1 = (x_t-x_s)+(x_t-x_u)$\n\\end{tight_itemize}\nThe following is a solution: $x_s = 0$, $x_u = \\frac{1}{3}$, $x_t\n= \\frac{2}{3}$.\nAnd as before, we can shift all the voltages by some constant $x$ and\nget another solution $a = x+0$, $x_u = x+\\frac{1}{3}$, $x_t\n= x+\\frac{2}{3}$. You might want to convince yourself that these are the only solutions.\n\n\\paragraph{Electrical flows in general graphs.}\nDo we know enough to calculate the electrical flow in some other\nnetwork of resistors?\nTo answer this, let us think about the network\nas a graph.\nConsider a undirected graph $G = (V,E)$ with $\\abs{V} = n$ vertices and\n$\\abs{E} = m$ edges, and let us assume $G$ is connected.\nLet's associate a resistance\n$\\rr(e) > 0$ with every edge $e \\in E$.\n\nTo keep track of the direction of the flow on each edge, it will be\nuseful to assign an arbitrary direction to every edge. So let's do\nthat, but remember that this is just a bookkeeping tool that helps\nus track where flow is going.\n\nA \\emph{flow} in the graph is a vector $\\ff: \\R^E$.\n%\nThe \\emph{net flow} of $\\ff$ at a vertex $u \\in V$ is defined as\n$\\sum_{v \\to u} \\ff(v,u) - \\sum_{u  \\to v} \\ff(u,v).$\n% As a second accounting trick, we can define $\\ff(v,u) \\defeq\n% -\\ff(u,v)$,\n% and then write the net flow as $\\sum_{(u,v)\\in E} \\ff(u,v)$.\n\nWe say a flow routes the demands $\\dd \\in \\R^V$ if the net flow at\nevery vertex $v$ is $\\dd(v)$.\n\nWe can assign a voltage to every vertex $\\xx \\in R^V$.\nOhm's Law says that the electrical flow induced by these voltages will\nbe $\\ff(u,v) = \\frac{1}{\\rr(u,v)} (\\xx(u) - \\xx(v))$.\n\nSay we want to route unit of current from vertex $s \\in V$ to vertex\n$t \\in V$.\nAs before, we can write an equation for every vertex saying that the\nvoltage differences must produce the desired net current:\n\\begin{tight_itemize}\n\\item Net current at $s$:\n  $\\phantom{----,,,}-1 = \\sum_{(s,v)} \\frac{1}{\\rr(s,v)} (\\xx(s) - \\xx(v))$\n\\item Net current at $u \\in V\\setminus\\setof{s,t}$:\n  $\\phantom{..} 0 = \\sum_{(u,v)} \\frac{1}{\\rr(u,v)} (\\xx(u) - \\xx(v))$\n\\item Net current at  $t$:  $\\phantom{------,} 1=\\sum_{(t,v)} \\frac{1}{\\rr(t,v)} (\\xx(t) - \\xx(v))$\n\\end{tight_itemize}\nThis gives us $n$ constraints, exactly as many as we have voltage\nvariables.\nHowever we have to be a little careful when trying to conclude that a\nsolution exists, yielding voltages $\\xx$ that gives induce an\nelectrical flow routing the desired demand.\n\n\nYou will prove in the exercises (Week 1, Exercise 3) that a solution $\\xx$ exists. The proof requires two\nimportant observations: Firstly that the graph is connected, and\nsecondly that summed over all vertices, the net demand is zero,\ni.e. as much flow is coming into the network as is leaving it.\n\n\\paragraph{The incidence matrix and the Laplacian matrix.}\nTo have a more compact notation for net flow constraints, we also\nintroduce the \\emph{edge-vertex incidence matrix} of the graph,\n$\\BB \\in \\R^{V \\times E}$.\n\\[\n  \\BB(v,e) =\n  \\begin{cases}\n    1 & \\text{ if } e = (u,v) \\\\\n    -1 &\\text{ if } e = (v,u) \\\\\n    0 &\\text{ o.w.}\n  \\end{cases}\n\\]\n%\nNow we can express the net flow constraint that $\\ff$ routes $\\dd$ by\n\\[\n  \\BB \\ff = \\dd\n  .\n\\]\nThis is also called a conservation constraint. In our examples so far,\nwe have $\\dd(s) = -1$, $\\dd(t) = 1$ and $\\dd(u) = 0$ for all $u\\in V\\setminus\\setof{s,t}$.\n\nIf we let $\\RR = \\diag_{e \\in E} \\rr(e)$\nthen Ohm's law tells us that $\\ff = \\RR^{-1}\\BB^{\\trp} \\xx$.\nPutting these observations together, we have $\\BB \\RR^{-1}\\BB^{\\trp}\n\\xx= \\dd$.\nThe voltages $\\xx$ that induce $\\ff$ must solve this system of linear\nequations, and we can use that to compute both $\\xx$ and $\\ff$.\nIt is exactly the same linear\nequation as the one we considered earlier.\nWe can show a that for a connected graph, a solution $\\xx$\nexists if and only if the\nflow into the graph equals the net flow out, which we can express as\n$\\sum_{v} \\dd(v) = 0$ or $\\vecone^\\trp \\dd = 0$.\nYou will show this as part of Exercise 3.\nThis also implies that an electrical flow routing\n$\\dd$ exists if and only if the net\nflow into the graph equals the net flow out, which we can express as\n$\\vecone^\\trp \\dd = 0$.\n\n\nThe matrix $\\BB \\RR^{-1}\\BB^{\\trp}$ is called the \\emph{Laplacian} of\nthe graph and is usually denoted by $\\LL$.\n\n\\paragraph{An optimization problem in disguise.}\nSo far, we have looked at electrical voltages and flows as arising\nfrom a set of linear equations -- and it might not be apparent that\nthis has anything to do with optimization.\nBut transporting current through a resistor requires energy, which will be\ndissipated as heat by the resistor (i.e. it will get hot!).\nIf we send a current of $f$ across a resistor with a potential drop of\n$x$, then the amount of energy spent per unit of time by the resistor will be\n$f \\cdot x$. This is called Joule's Law.\nApplying Ohm's law to a resistor with resistance $r$,\nwe can also express this energy per unit of time\nas $f \\cdot x = x^2 / r = r \\cdot f ^2$.\nSince we aren't bothering with units, we will even forget about time,\nand refer to these quantities as ``energy'', even though a physicist\nwould call them ``power''.\n\n\\begin{figure}[H]\n  \\centering\n  \\includegraphics[width=0.6\\linewidth]{fig/lecture1_flow-vs-energy.png}\n  \\captionof{figure}{Energy has a function of flow in a resistor with\n    resistance $r = 1$.}\n  \\label{fig:flow-vs-energy}\n\\end{figure}\n\nNow, another interesting question would seem to be: If we want to find\na flow routing a certain demand $\\dd$, how should have flow behave in\norder to minimize the the electrical energy spent routing the flow?\nWe can phrase this as an optimization problem:\n\\begin{align*}\n  \\min_{\\ff \\in \\R^E} & \\sum_e \\rr(e) \\ff(e)^2\n  \\\\\n  \\textrm{s.t. } & \\BB \\ff = \\dd .\n\\end{align*}\nWe call this problem \\emph{electrical energy-minimizing flow}.\nIt turns out, that the flow $\\ff^*$ that minimizes the electrical\nenergy among all flows that satisfy $\\BB \\ff = \\dd$ is precisely the\nelectrical flow.\n\n\\paragraph{A pair of problems.}\nWhat about our voltages, can we also get them from some optimization\nproblem?\n%\nWell, we can work backwards from the fact that our voltages solve the\nequation $\\LL \\xx = \\dd$.\n%\nConsider the function $c(\\xx) = \\frac{1}{2} \\xx^{\\trp} \\LL \\xx -\n\\xx^{\\trp}\\dd$.\nWe should ask ourselves some questions about this function $c : \\R^V\n\\to \\R$. Is it continuous and continuously differentiable? The answer to this is\nyes, and that is not hard to see.\nDoes the function have a minimum?\nThis is maybe not immediately clear, but the minimum does indeed exist.\n\nWhen this is minimized, the derivative of $c(\\xx)$ with respect to each coordinate of $\\xx$\nmust be zero. This condition yields exactly the system of linear\nequations $\\LL \\xx = \\dd$.\nYou will confirm this in Exercise 4.\n\nBased on our derivative condition for the optimum, we can also express the electrical voltages as the solution to\nan optimization problem, namely\n\\begin{align*}\n\\min_{\\xx \\in \\R^V} & \\frac{1}{2} \\xx^{\\trp} \\LL \\xx -\n\\xx^{\\trp}\\dd\n\\end{align*}\nAs you are probably aware, having the derivative of each coordinate equal zero is not a\nsufficient condition for being at the optimum of a\nfunction\\footnote{Consider the function in one variable $c(x) =\n  x^3$.}.\nIt is also interesting to know whether \\emph{all} solutions to $\\LL\n\\xx = \\dd$ are in fact minimizers of $c$. The answer is\nyes, and will see some very general tools for proving statements like\nthis in Chapter~\\ref{sec:cvopt}.\n% Although, we have not yet proven the electrical flow minimizes\n% electrical energy $\\sum_e \\rr(e) \\ff(e)^2$, I have promised you that\n% this is true.\n% Let us denote the electrical flow and voltages by $\\fftil$ and $\\xxtil$,\n% and recall that $\\fftil = \\RR^{-1} \\BB ^\\trp \\xxtil$.\n% Based on this, we can make an interesting observation:\n% \\[\n%   \\sum_e \\rr(e) \\ff(e)^2\n%   =\n%   \\ff^{\\trp} \\RR \\ff\n%   =\n  % \\]\n  % \\frac{1}{2} \\xxtil^{\\trp} \\LL \\xxtil - \\xxtil^{\\trp}\\dd\n  % =\n\nAltogether, we can see that routing electrical current through a\nnetwork of resistors leads to a \\emph{pair} of optimization problems,\nlet's call them $\\ff^*$ and $\\xx^*$,\nand that the solutions to the two problems are related, in our case\nthrough the equation $\\ff^* = \\RR^{-1}\\BB^{\\trp} \\xx^*$.\nIn Exercise 5, you will explore this relationship more.\n\\\\\n\nThis turns out to be an instance of a much broader phenomenon, known\nas Lagrangian duality, which allows us to learn a lot about many\noptimization problems by studying two related pairs of problems.\n\n\\paragraph{Solving $\\LL \\xx = \\dd$.}\nGiven a graph $G$ with resistances for the edges, and some net flow\nvector $\\dd$, how quickly can we compute $\\xx$?\n%\nBroadly speaking, there are two very different families of algorithms\nwe could use to try to solve this problem.\n\nEither, we could solve the linear equation using something like\n\\emph{Gaussian Elimination} to compute an exact solution.\n\nAlternatively,\nwe could start with a guess at a solution, e.g. $\\xx_0\n= \\veczero$, and then we could try to make a change to $\\xx_0$ to reach\na new point $\\xx_1$ with a lower value of $c(\\xx) = \\frac{1}{2} \\xx^{\\trp} \\LL \\xx -\n\\xx^{\\trp}\\dd$, i.e. $c(\\xx_1) < c(\\xx_0)$.\nIf we repeat a process like that for enough steps, say $t$, hopefully we\neventually reach $\\xx_t$ with $c(\\xx_t)$ close to $c(\\xx^*)$, where\n$\\xx^*$ is a minimizer of $c(\\xx)$ and hence $\\LL \\xx^* = \\dd$.\nNow, we also need to make sure that $c(\\xx_t) \\approx c(\\xx^*)$\nimplies that $\\LL \\xx_t \\approx \\dd$ in some useful sense.\n\nOne of the most basic algorithms in this framework of ``guess and adjust''\nis called \\emph{Gradient Descent}, which we will study in two weeks.\nThe rough idea is the following: if we make a very small step from $\\xx$ to\n$\\xx + \\ddelta$, then a multivariate Taylor expansion suggests that\n$c(\\xx + \\ddelta) - c(\\xx) \\approx \\sum_{v \\in V} \\ddelta(v)\n\\frac{\\partial c(\\xx)}{\\partial\\xx(v)} $.\n\nIf we are dealing with smooth convex function,\nthis quantity is negative if we let $\\ddelta(v) = -\\epsilon \\cdot \\frac{\\partial\n  c(\\xx)}{\\partial\\xx(v)}$ for some small enough $\\epsilon$ so the\napproximation holds well.\nSo we should be able to make progress by taking a small step in this\ndirection.\nThat's Gradient Descent!\nThe name comes from the vector of partial\nderivatives, which is called the gradient.\n% But first we need to become familiar with some basic terminology about\n% optimization and some convex geometry.\n% As we will see later in this course, understanding electrical problems\n% from an optimization perspective is crucial to developing fast\n% algorithms.\n\nAs we will see later in this course, understanding electrical problems\nfrom an optimization perspective is crucial to developing fast\nalgorithms for computing electrical flows and voltages, but to do very\nwell, we also need to borrow some ideas from Gaussian Elimination.\n\nWhat running times do different approaches get?\n\\begin{enumerate}\n\\item Using Gaussian Elimination, we can find $\\xx$ s.t. $\\LL \\xx =\n  \\dd$ in $O(n^3)$ time and with asymptotically faster algorithms based on matrix\n  multiplication, we can bring this down to roughly $O(n^{2.372})$.\n\\item Meanwhile Gradient Descent will get a running time of $O(n^3m)$\n  or so -- at least this is a what a simple analysis suggests.\n\\item However, we can do much better: By combining ideas from both\n  algorithms, and a bit more,\n  we can get $\\xx$ up to very high\n  accuracy in time $O(m \\log^c n)$ where $c$ is some small constant.\n  % This type of result was orignally shown by Spielman and Teng in a\n  % breakthrough result in 2004.\n\\end{enumerate}\n\n\n\\section{Convex Optimization}\n\nRecall our plot in Figure~\\ref{fig:flow-vs-energy} of the energy required to\nroute a flow $f$ across a resistor with resistance $r$, which was\n$\\energy(f) = r\\cdot f^2$.\n%\nWe see that the function has a special structure: the graph of the function sits\nbelow the line joining any two points $(f, \\energy(f))$ and $(g,\\energy(g))$.\nA function $\\energy : \\R \\to \\R$ that has this property is said to be convex.\n\nFigure~\\ref{fig:flow-vs-energy-convex} shows the energy as a function of flow, along with two\npoints $(f, \\energy(f))$ and $(g,\\energy(g))$. We see the function sits below the\nline segment between these points.\n\n\\begin{figure}[H]\n  \\centering\n  \\includegraphics[width=0.6\\linewidth]{fig/lecture1_flow-vs-energy-convex.png}\n  \\captionof{figure}{Energy has a function of flow in a resistor with\n    resistance $r = 1$. The function is convex.}\n  \\label{fig:flow-vs-energy-convex}\n\\end{figure}\nWe can also interpret this condition as saying that for all $\\theta \\in [0,1]$\n\\[\n  \\energy(\\theta f + (1-\\theta)g) \\leq \\theta \\energy(f) +\n  (1-\\theta) \\energy(g)\n  .\n  \\]\nThis immediately generalizes to functions $\\energy:\\R^m \\to \\R$.\n\nA \\emph{convex set} is a subset of $S \\subseteq \\R^m$ s.t.\nif $\\ff, \\gg \\in S$ then for all $\\theta \\in [0,1]$ we have\n$\\theta \\ff + (1-\\theta) \\gg \\in S$.\n\nFigure~\\ref{fig:convex_sets} shows some examples of sets that are and\naren't convex.\n\n\\begin{figure}[t]\n\\begin{centering}\n                \\includegraphics[trim = 0mm 0mm 0mm 0mm, height=60mm]{fig/lec1_convex_sets.pdf}\n                 \\caption{A depiction of convex and non-convex sets.  The sets $A$ and $B$ are convex since the straight line between any two points inside them is also in the set.  The set $C$ is not convex.}\\label{fig:convex_sets}\n                 \\end{centering}\n\\end{figure}\n\n\nConvex functions and convex sets are central to optimization,\nbecause for most problems of minimization a convex function over a\nconvex set, we can develop fast algorithms \\footnote{\n There are some convex optimization problems that are NP-hard.\n  That said, polynomial time algorithms exist for almost any convex\n  problem you can come up with.\n  The most general polynomial time algorithm for convex optimization\n  is probably the\n  \\href{https://en.wikipedia.org/wiki/Ellipsoid_method}{Ellipsoid Method}.\n}.\n\n\nSo why convex functions and convex sets?\nOne important reason is that\nfor a convex function defined over a convex feasible set,\nany local minimum is also a global minimum,\nand this fact makes searching for an optimal solution\ncomputationally easier.\nIn fact, this is closely related to why Gradient Descent works well\non many convex functions.\n\n\nNotice that the set $\\setof{ \\ff: \\BB \\ff = \\dd}$ is convex, i.e. the\nset of all flows that route a fixed demand $\\dd$ is convex.\nIt is also easy to verify that $\\energy(\\ff) = \\sum_e \\rr(e) \\ff(e)^2$\nis a convex function, and hence finding an electrical flow is an\ninstance of convex minmization:\n\n\n\n\\section{More Graph Optimization Problems}\n\n\\paragraph{Maximum flow.}\nAgain, let $G=(V,E)$ be an undirected, connected graph with $n$\nvertices and $m$ edges.\nSuppose we want to find a flow\n$\\ff \\in \\R^E$ that routes $\\dd$, but instead of trying to minimize\nelectrical energy, we try to pick an $\\ff$ that minimizes the largest\namount of flow on any edge, i.e. $\\max_e \\abs{\\ff_e}$  -- which we\nalso denote by $\\norm{\\ff}_{\\infty}$.\nWe can write this problem as\n\\begin{align*}\n\\min_{\\ff \\in \\R^E } & \\norm{\\ff}_{\\infty} \\\\\n\\textrm{s.t. } & \\BB \\ff = \\dd\n\\end{align*}\nThis problem is known as the Minimum Congested Flow Problem\\footnote{This\n  version is called undirected, because the graph is undirected, and\n  \\emph{uncapacitated} because we are aiming for the same\n  bound on the flow on all edges.}.\nIt is equivalent to the more famous Maximum Flow Problem.\n\nThe behavior of this kind of flow is very different than electrical\nflow. Consider the question of whether a certain demand can be routed\n$\\norm{\\ff}_{\\infty} \\leq 1$.\nImagine sending goods from a source $s$ to a destination $t$ using a\nnetwork of train lines that all have the\nsame capacity and asking whether the network is able to route the\ngoods at the rate you want: This boils down to whether routing exists\nwith $\\norm{\\ff}_{\\infty} \\leq 1$, if we set it up right.\n\nWe have a very fast, convex optimization-based algorithm for Minimum Congested Flow:\nIn $m \\epsilon^{-1} \\log^{O(1)} n$ time, we can find a flow $\\fftil$\ns.t. $\\BB \\fftil = \\dd$ and $\\norm{\\fftil}_{\\infty} \\leq\n(1+\\epsilon)\\norm{\\ff^*}_{\\infty}$, where $\\ff^*$ is an optimal solution, i.e. an\nactual minimum congestion flow routing $\\dd$.\n\nBut what if we want $\\epsilon$ to be very small, e.g. $1/m$? Then this running\ntime isn't so good anymore.\nBut, in this case, we can use another algorithm, that finds an optimal\nflow $\\ff^*$ \\emph{exactly}, in time\\footnote{And there's even a paper on arXiv.org that brings this further\n  down to $m^{11/8} \\log^{O(1)} n$.} $m^{10/7} \\log^{O(1)} n $.\n\nJust as the electrical flow problem had a dual voltage problem, so\nmaximum flow has a dual voltage problem, which is know as the\n$s$-$t$ minimum cut problem.\n\n\\paragraph{Maximum flow, with directions and capacities.}\nWe can make the maximum flow problem harder by introducing directed\nedges: To do so, we allow edges in both directions to exist between a\nvertex to exist, and we require that that flow on a directed edge is\nalways non-negative. So now $G=(V,E)$ is a directed graph.\nWe can also make the problem harder by introducing capacities.\nWe define a capacity vector $\\cc \\in \\R^E \\geq \\veczero$ and try to minimize $\\norm{\\CC^{-1} \\ff}_{\\infty}$, where $\\CC =\n\\diag_{e \\in E}\\cc(e)$.\nThen our problem becomes\n\\begin{align*}\n\\min_{\\ff \\in \\R^E } & \\norm{\\CC^{-1} \\ff}_{\\infty} \\\\\n  \\textrm{s.t. } &  \\BB \\ff = \\dd\\\\\n                     &  \\ff \\geq \\veczero.\n\\end{align*}\nFor this capacitated, directed maximum flow problem, our best\nalgorithms run in about $O( m \\sqrt{n} )$ time\\footnote{Provided the\n  capacities are integers satisfying a condition like $\\cc \\leq n^{100} \\vecone$.}, even if we are willing to\naccept fairly low accuracy solution.\nIf the capacities are allowed to be exponentially large, the best\nrunning time we can get is $O(m n)$.\nFor this problem, we do not yet know how to improve over classical\ncombinatorial algorithms using convex optimization.\n\n\\paragraph{Multi-commodity flow.}\nWe can make the even harder still, by simultaneously trying to route\nto types of flow (imagine pipes with Coke and Pepsi).\nOur problem now looks like\n\\begin{align*}\n\\min_{\\ff_1, \\ff_2 \\in \\R^E } & \\norm{\\CC^{-1} (\\ff_1 + \\ff_2)}_{\\infty} \\\\\n  \\textrm{s.t. } &  \\BB \\ff_1 = \\dd_1 \\\\\n                              & \\BB \\ff_2 = \\dd_2\\\\\n                     &  \\ff_1, \\ff_2 \\geq \\veczero.\n\\end{align*}\nSolving this problem to high accuracy is essentially as hard as\nsolving a general linear program! We should see later in the course\nhow to make this statement precise.\n\nIf we in the above problem additionally require that our flows must be\ninteger valued, i.e. $\\ff_1, \\ff_2 \\in \\N_{0}$, then the problem becomes NP-complete.\n\n\\paragraph{Random walks in a graph.}\nGoogle famously uses\\footnote{At least they did at some point.} the\nPageRank problem to help decide how to rank their search results.\nThis problem essentially boils down to computing the \\emph{stable\ndistribution} of a random walk on a graph.\nSuppose $G=(V,E)$ is a directed graph where each edge outgoing edge\n$(v,u)$, which we will define as going from $u$ to $v$, has a\ntransition probability $p_{(v,u)} > 0$ s.t. $\\sum_{z \\leftarrow u}\np_{(z,u)} = 1$.\nWe can take a step of a random walk on the vertex set by starting at some vertex\n$u_0 = u$, and then randomly picking one of it the outgoing edges\n$(v,u)$ with probability $p_{(v,u)}$  and move to\nthe chosen vertex $u_1 = v$.  Repeating this procedure, to take a step from\nthe next vertex $u_1$, gives us a\n\\emph{random walk} in the graph, a sequence of vertices $u_0, u_1, u_2\n\\ldots, u_k$.\n\nWe let $\\PP \\in \\R^{V \\times V}$ be the matrix of transition\nprobabilities given by\n\\[\n  \\PP_{vu} =\n  \\begin{cases}\n    p_{(v,u)} & \\text{ for } (u,v) \\in E \\\\\n    0 & \\text{ o.w.}\n  \\end{cases}\n\\]\n\nAny probability distribution over the vertices can be specified by a vector\n$\\pp \\in \\R^V$ where $\\pp \\geq\n\\veczero$ and $\\sum_v \\pp(v) = 1$.\nWe say that probability distribution $\\ppi$ on the vertices is a \\emph{stable distribution} of the random walk\nif $\\ppi = \\PP \\ppi$.\nA strongly connected graph always has exactly one stable distribution.\n\nHow quickly can we compute the stable distribution of a general random\nwalk? Under some mild conditions on the stable\ndistribution\\footnote{Roughly something like $\\max_{v} 1/\\ppi(v) \\leq n^{100}$.}, we can find\na high accuracy approximation of $\\ppi$ in time $O(m \\log^cn )$ for\nsome constant $c$.\n\nThis problem does not easily fit in a framework of convex\noptimization, but nonetheless, our fastest algorithms for it use ideas\nfrom convex optimization.\n\n\\section*{Topics in this Course}\nIn this course, we will try to address the following questions.\n\\begin{enumerate}\n\\item What are the fundamental tools of fast convex optimization?\n\\item What are some problems we can solve quickly on graphs using optimization?\n\\item What can graphs teach us about convex optimization?\n\\item What algorithm design techniques are good for getting algorithms\n  that quickly find a crude approximate solution? And what techniques\n  are best when we need to get a highly accurate answer?\n\\item What is special about flow problems?\n\\end{enumerate}\n\n% \\pagebreak\n% \\section{Exercises}\n\n% NEW\n% \\begin{enumerate}\n% \\item sub-level set of a convex function is a convex set (show).\n% \\item is it true that a function whose sub-level sets are all convex\n%   is necessarily convex?\n% \\item \\todo{exercise A}\n%   \\begin{itemize}\n%   \\item kernel of the Laplacian\n%   \\item show that solutions (voltage and flow) exist when\n%     graph is connected and $\\dd^\\trp \\vecone = 0$.\n%   \\item prove matrix symmetric, consider quadratic form,\n%     show positive semi-definite.\n%   \\end{itemize}\n% \\item \\todo{exercise B}\n%     define gradient. do the voltage gradient computation\n% \\item \\todo{exercise C: more duality}\n% {\\color{olive}\n%   \\\\\n% Recall $\\ff^* = \\RR^{-1}\\BB^{\\trp} \\xx^*$ and $\\BB \\ff^* = \\dd$,\n% we can conclude\n% $(\\ff^* )^\\trp R \\ff^*  = (\\ff^* )^\\trp \\BB^\\trp \\xx^* = \\dd^\\trp \\xx^* = (\\xx^*)^\\trp \\LL\n% \\xx^*$\n% (Maybe don't directly point this out to students!)\n\n% now we can see that\n% \\begin{align*}\n% \\max_{\\xx \\in \\R^V} \\xx^{\\trp}\\dd - \\frac{1}{2} \\xx^{\\trp} \\LL \\xx\n%   &=\n% \\min_{\\ff \\in \\R^E} \\frac{1}{2}\\sum_e \\rr(e) \\ff(e)^2 \\\\\n%   & \\qquad \\textrm{ s.t. }\n%   \\BB \\ff = \\dd\n% .\n% \\end{align*}\n\n% Maybe also point out to students that the stuff they have proved can\n% easily be generalized a larger class of quadratic problems.\n% }\n% \\item GRADED? gaussian elimination for Laplacians is closed ?\n% \\end{enumerate}\n\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: \"agao21_script\"\n%%% TeX-engine: luatex\n%%% End:\n", "meta": {"hexsha": "80d3bfecf1ff9708575d975201ab9b4d46856ddd", "size": 27649, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "agao21_script/lecture1_mod.tex", "max_stars_repo_name": "csssaz/agao21_script", "max_stars_repo_head_hexsha": "51044f4775e5e20d2c5fc5c0d035363e5beb66be", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-15T09:04:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T05:39:09.000Z", "max_issues_repo_path": "agao21_script/lecture1_mod.tex", "max_issues_repo_name": "csssaz/agao21_script", "max_issues_repo_head_hexsha": "51044f4775e5e20d2c5fc5c0d035363e5beb66be", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "agao21_script/lecture1_mod.tex", "max_forks_repo_name": "csssaz/agao21_script", "max_forks_repo_head_hexsha": "51044f4775e5e20d2c5fc5c0d035363e5beb66be", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-03-11T12:35:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T06:04:51.000Z", "avg_line_length": 41.7028657617, "max_line_length": 232, "alphanum_fraction": 0.714456219, "num_tokens": 7985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.34777769092573024}}
{"text": "\\documentclass[12pt]{amsart}\n\\usepackage[margin=0.5in]{geometry} \n  % see geometry.pdf on how to lay out the page. There's lots.\n\\usepackage{bsymb}\n\\usepackage{../unitb}\n\\usepackage{calculational}\n\\usepackage{ulem}\n\\usepackage{hyperref}\n\n\\newcommand{\\REQ}{\\text{REQ}}\n\n\\begin{document}\n  % \\input{main9/machine_m0.tex}\n\\begin{machine}{m0}\n\n  \\newset{\\REQ}\n\nWe need a variable to keep track of all the requests to mutate the\ndata structure.\n\n  \\[ \\variable{ req,req_0 : \\set [\\REQ] } \\]\n\n... and new events:\n% % \\hide{\n  \\newevent{req}{req}\n  \\newevent{handle}{handle}\n  % \\newevent{req}{req\\_b} \n  % \\newevent{handle}{handle\\_b} \n\n\\[\\param{req}{r : \\REQ }\\]\n\\with{sets}\n\\begin{align*}\n  & \\evguard{req}{grd0}{ \\neg r \\in req }  \\\\\n  & \\evbcmeq{req}{act0}{ req }{ req \\bunion \\{ r \\} } \\\\\n  & \\evbcmeq{req}{act1}{ req_0 }{ req } \n\\end{align*}\n\\[\\param{handle}{r : \\REQ }\\]\n\\begin{align*}\n  \\evguard{handle}{grd0}{ r \\in req }  \\\\\n  \\evbcmeq{handle}{act0}{ req }{ req \\setminus \\{ r \\} } \\\\\n  \\evbcmeq{handle}{act1}{ req_0 }{ req }\n\\end{align*}\n\n% \\section{Requirements}\n%   \\dummy{ R : \\set[\\REQ] }\n\\begin{align*}\n  \\constraint{co0}{ req_0' = req \\1\\lor (req_0' = req_0 \\1\\land req' = req) }\n\\end{align*}\n\\begin{align*}\n  & \\progress{prog0}\n    { \\neg req = \\emptyset }\n    { \\neg req_0 \\subseteq req }\n \\refine{prog0}{ensure}{handle}{ using \\ref{handle} }\n  & \\progress{prog1}\n    { V = req}\n    { req \\subset V \n      \\1\\lor req = \\emptyset \\1\\lor \\neg req \\subseteq req_0}\n \\refine{prog1}{ensure}{handle}{ using \\ref{handle} }\n\\end{align*}\n\\begin{align*}\n  \\dummy{ R,V : \\set [\\REQ] } \\\\\n  \\cschedule{handle}{m0:sch0}{ \\neg req = \\emptyset } \\\\\n  \\initialization{m0:in0}{ req = \\emptyset }\n\\end{align*}\n\\end{machine}\n\n% \\input{main9/machine_m1}\n\\begin{machine}{m1}\n  \\refines{m0}\n\\[ \\indices{handle}{ b : \\Bool } \\]\n\\[ \\dummy{ b : \\Bool } \\]\n\\[ \\variable{ ch : \\Bool } \\]\n\\begin{align*}\n  & \\cschedule{handle}{m1:sch0}{ b = ch } \\\\\n  & \\witness{handle}{b}{b = ch} \\\\\n  & \\progress{m1:prog1}{ b = ch }{ b = ch }\n\\end{align*}\n\\replace{handle}{m1:sch0}{m1:prog1}\n  \\begin{liveness}{m1:prog1}\n    \\progstep{\\true}{req = \\emptyset \\1\\lor \\neg req \\subseteq req_0}\n      {induction}{}{ \\var{req}{down}{\\emptyset} }\n  \\begin{flatstep}\n    \\progstep\n      {V = req}\n      {req \\subset V\n        \\1\\lor req = \\emptyset \\1\\lor \\neg req \\subseteq req_0}\n      {discharge}{}{}\n      \\begin{step}\n        \\trstep{handle}{ \\index{b}{ \\true }  }\n          { req = V \\1\\land \\neg req = \\emptyset  }\n        \\safstep\n          { V = req }\n          { req \\subset V \\1\\lor \\neg req \\subseteq req_0 }\n          {}\n      \\end{step}\n  \\end{flatstep}\n  \\end{liveness}\n\\end{machine}\n\n% % \\input{main9/machine_m2}\n% \\begin{machine}{m2}\n%   \\refines{m0}\n\n% We now partitial $req$ into requests for operation A ($reqA$) and\n% requests for operation B ($reqB$).\n\n% \\[ \\variable{ reqA, reqB : \\set [\\REQ] } \\]\n% \\begin{align*}\n%   \\invariant{m1:inv0}{ reqA \\bunion reqB = req } \\\\\n%   \\invariant{m1:inv1}{ reqA \\binter reqB = req } \n% \\end{align*}\n% And consequ\n% \\begin{align*}\n%   \\initialization{m1:in0}{ reqA = \\emptyset \\land reqB = \\emptyset }\n% \\end{align*}\n% \\end{machine}\n\n\\end{document}\n", "meta": {"hexsha": "0d72475262e41cba8ffd441eee69516f7eac5552", "size": 3171, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Tests/lock-free deque/main9.tex", "max_stars_repo_name": "literate-unitb/literate-unitb", "max_stars_repo_head_hexsha": "0d843456dc103bb09babc5b12855435d2e10f534", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-07-27T11:05:56.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-20T14:53:33.000Z", "max_issues_repo_path": "Tests/lock-free deque/main9.tex", "max_issues_repo_name": "unitb/literate-unitb", "max_issues_repo_head_hexsha": "0d843456dc103bb09babc5b12855435d2e10f534", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32, "max_issues_repo_issues_event_min_datetime": "2017-06-25T03:53:02.000Z", "max_issues_repo_issues_event_max_datetime": "2017-06-25T04:28:38.000Z", "max_forks_repo_path": "Tests/lock-free deque/main9.tex", "max_forks_repo_name": "literate-unitb/literate-unitb", "max_forks_repo_head_hexsha": "0d843456dc103bb09babc5b12855435d2e10f534", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6470588235, "max_line_length": 77, "alphanum_fraction": 0.5935036266, "num_tokens": 1206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3477776834764115}}
{"text": "\\title          {\\TeX\\ macros for proof boxes}\n\\author         {Paul Taylor}\n\n\\documentclass{article}\n\\usepackage{boxproof}\n\\usepackage{a4wide}\n\\usepackage{daymonthyear}\n\n\\def\\meta#1{\\mbox{$\\langle\\hbox{#1}\\rangle$}}\n\\def\\macrowitharg#1#2{{\\tt\\string#1\\bra\\meta{#2}\\ket}}\n\n{\\escapechar-1 \\xdef\\bra{\\string\\{}\\xdef\\ket{\\string\\}}}\n\n\\def\\intro#1{{#1}{\\cal I}}\n\\def\\elim#1{{#1}{\\cal E}}\n\n\\showboxbreadth 999\n\\showboxdepth 999\n\\tracingoutput 1\n\n\n\\let\\imp\\to\n\\def\\elim#1{{{#1}{\\cal E}}}\n\\def\\intro#1{{{#1}{\\cal I}}}\n\\def\\lt{<}\n\\def\\eqdef{=}\n\\def\\eps{\\mathrel{\\epsilon}}\n\\def\\biimplies{\\leftrightarrow}\n\\def\\flt#1{\\mathrel{{#1}^\\flat}}\n\\def\\setof#1{{\\left\\{{#1}\\right\\}}}\n\\let\\implies\\to\n\\def\\KK{{\\mathsf K}}\n\\let\\squashmuskip\\relax\n\n%=======================================================================\n\\begin{document}\n\\maketitle\n\n\\section{Introduction}\nThe proof\n\\begin{proofbox}\n  \\(\\\"1\"\\:\\alpha\\leftrightarrow\\psi(x,\\top)\\=\\\\\n        \\:\\Some\\beta.\\psi(x,\\beta)\\=\\mathsf{total}\\\\\n    \\[\\exists\\beta\\kern-1em\\:\\psi(x,\\beta)\\\\\n      \\(\\:\\beta\\=\\\\\n        \\:\\beta=\\top\\=(*)\\\\\n        \\:\\psi(x,\\!\\top)\\=\\mathsf{subs}\\\\\n        \\:\\alpha\\=\\elim\\leftrightarrow(\\ref{1})\\\\\n      \\*\\:\\alpha\\=\\\\\n        \\:\\psi(x,\\!\\top)\\=\\elim\\leftrightarrow(\\ref{1})\\\\\n        \\:\\beta=\\top\\=\\mathsf{func}\\\\\n        \\:\\beta\\=(*)\\\\\n      \\)\\:\\alpha=\\beta\\=\\intro\\leftrightarrow\\\\\n        \\:\\psi(x,\\alpha)\\=\\mathsf{subs}\\\\\n    \\]  \\:\\psi(x,\\alpha)\\=\\elim\\exists\\\\\n    \\*  \\:\\psi(x,\\alpha)\\=\\\\\n      \\(\\:\\alpha\\=\\\\\n        \\:\\alpha=\\top\\=(*)\\\\\n        \\:\\phi(x,\\!\\top)\\=\\mathsf{subs}\\\\\n      \\*\\:\\psi(x,\\!\\top)\\=\\\\\n        \\:\\alpha=\\top\\=\\mathsf{func}\\\\\n        \\:\\alpha\\=(*)\\\\\n      \\)\\:\\alpha\\leftrightarrow\\psi(x,\\!\\top)\\=\\intro\\leftrightarrow\\\\\n    \\)  \\:\\psi(x,\\alpha)\\leftrightarrow(\\alpha\\leftrightarrow\\psi(x,\\!\\top))\n          \\=\\intro\\leftrightarrow\\\\\n\\end{proofbox}\n is produced by\n\\begin{verbatim}\n\\begin{proofbox}\n  \\(\\\"1\"\\:\\alpha\\leftrightarrow\\psi(x,\\top)\\\\\n        \\:\\Some\\beta.\\psi(x,\\beta)                      \\=\\mathsf{total}\\\\\n    \\[\\exists\\beta\\kern-1em\\:\\psi(x,\\beta)\\\\\n      \\(\\:\\beta\\\\\n        \\:\\beta=\\top                                    \\=(*)\\\\\n        \\:\\psi(x,\\!\\top)                                \\=\\mathsf{subs}\\\\\n        \\:\\alpha                         \\=\\elim\\leftrightarrow(\\ref{1})\\\\\n      \\*\\:\\alpha\\\\\n        \\:\\psi(x,\\!\\top)                 \\=\\elim\\leftrightarrow(\\ref{1})\\\\\n        \\:\\beta=\\top                                     \\=\\mathsf{func}\\\\\n        \\:\\beta\\=(*)\\\\\n      \\)\\:\\alpha=\\beta                           \\=\\intro\\leftrightarrow\\\\\n        \\:\\psi(x,\\alpha)                                 \\=\\mathsf{subs}\\\\\n    \\]  \\:\\psi(x,\\alpha)                                  \\=\\elim\\exists\\\\\n    \\*  \\:\\psi(x,\\alpha)\\\\\n      \\(\\:\\alpha\\\\\n        \\:\\alpha=\\top                                   \\=(*)\\\\\n        \\:\\phi(x,\\!\\top)                                \\=\\mathsf{subs}\\\\\n      \\*\\:\\psi(x,\\!\\top)\\\\\n        \\:\\alpha=\\top                                   \\=\\mathsf{func}\\\\\n        \\:\\alpha                                        \\=(*)\\\\\n      \\)\\:\\alpha\\leftrightarrow\\psi(x,\\!\\top)   \\=\\intro\\leftrightarrow\\\\\n    \\)  \\:\\psi(x,\\alpha)\\leftrightarrow\n          (\\alpha\\leftrightarrow\\psi(x,\\!\\top)) \\=\\intro\\leftrightarrow\\\\\n\\end{proofbox}\n\\end{verbatim}\n\n  Syntax as follows:\n  each line is of the form\n  \\begin{center}\n     \\meta{variables}\n     \\meta{name}\n     \\verb/\\:/ \\meta{formula}\n     \\verb/\\=/ \\meta{reason}\n     \\verb/\\-/ \\meta{use}\n     \\verb/\\\\/\n  \\end{center}\n  where\n  \\begin{itemize}\n  \\item \\meta{variables} is something like ``$x,y$'' ---\n    it's for variables declared at the beginning of $\\intro\\forall$- and\n    $\\elim\\exists$-boxes.\n  \\item \\meta{name} is a command \\verb/\\label{fred}/ which\n    defines \\verb/fred/ to be the label text, which may be used anywhere\n    as \\verb/\\ref{fred}/ --- see {\\em The \\LaTeX book.}\n    Local labels are also available, using \\macrowitharg\\lbl{name}\n    or \\verb/\\\"/\\meta{name}\\verb/\"/; these obey the scoping rules of\n    the boxes.\n    You may also refer to the previous line as \\verb/\\ref{-}/.\n  \\item \\meta{formula} is the proposition being asserted.\n  \\item \\meta{reason} is \\verb/\\intro\\land(\\ref{john},\\ref{mary})/\n         or \\verb/\\elim\\forall(\\ref{jim})/.\n  \\item \\meta{use} is provided for linear logic, to record the step\n         which uses this one. How this accords with theory I don't yet know.\n  \\end{itemize}\n  Note that the parts are separated by \\verb/\\:/, \\verb/\\=/ and \\verb/\\\\/;\n  these correspond to\n  \\begin{center}\n     {\\bf let } \\meta{name} = \\meta{expression} : \\meta{type}\n  \\end{center}\n  in a declarative language.\n  The \\verb/\\:/, \\verb/\\=/ and \\verb/\\-/ fields are optional and may occur\n  in any order. If any of them is repeated the last is taken.\n  If none of them is present the \\meta{variables} field is also ignored.\n\n  Proof {\\em boxes\\/} are ``wrapped up'' as follows:\n  \\begin{itemize}\n  \\item the whole proof in \\verb/\\begin{proofbox}/...\\verb/\\end{proofbox}/;\n  \\item single-column boxes ($\\intro\\forall$, $\\intro\\imp$, $\\elim\\exists$),\n      in \\verb/\\[/...\\verb/\\]/.\n  \\item multiple-column boxes are of two kinds:\n    \\begin{itemize}\n     \\item separate ($\\intro\\land$) boxes: \\verb/\\(/...\\verb/\\*/...\\verb/\\)/.\n     \\item stuck together ($\\elim\\lor$) boxes:\n        \\verb/\\(/...\\verb/\\+/...\\verb/\\)/.\n    \\end{itemize}\n  \\end{itemize}\n  You may put more than two columns in \\verb/\\(/...\\verb/\\)/ and even mix\n  the \\verb/\\+/ and \\verb/\\*/ separators.\n\n  The whole proof is enclosed in \\verb/\\proofbox/...\\verb/\\endproofbox/\n  or \\verb/\\begin{proofbox}/...\\verb/\\end{proofbox}/, but the \\LaTeX\\\n  environment form {\\em must not\\/} be used for nested boxes.\n\n  If the proof occurs in paragraph mode (ie in vertical or\n  unrestricted horizontal mode) then it is set as a display, using the\n  full width of the page. Otherwise it uses only the required width.\n\n  A lot of the internals are potentially configurable, but there is not\n  yet a user interface suitable for doing this. This will be provided\n  in the next version.\n\n\n%=======================================================================\n\\section{Redefinable macros}\n WARNING: most of these commands will be hidden and replaced with\n optional arguments to \\verb/\\proofbox/ in a future version.\n Do not rely on them.\n\n We provide three different ways of numbering the lines of the proof:\n \\begin{itemize}\n \\item \\verb/\\runningproofline/: a global running sequence (default),\n \n \\item \\verb/\\nestedproofline/: a hierarchical system with dots,\n\n \\item \\verb/\\nestedproofline/: a fully hierarchical system which\n also includes the column number\n (\\verb/\\proof@columns/) as a letter (ASCII quote plus number).\n\n \\end{itemize}\n \\verb/\\theproofline/ is the default.\n\n The macro \\verb/\\proofboxmakelabel#1/ is used to print the line label.\n We only put it in the leftmost box.\n It is printed in small non-ranging Arabic numerals\n ({\\the\\scriptfont1 0123456789}).\n Right-justify it in \\verb/\\prooflinenowidth/ if it will fit,\n otherwise let it stick out on the right, {\\em i.e.}~left-justify it.\n\n Kill the numbers altogether with \\verb/\\proofboxnonumbers/.\n\n How to make the left column of the proof box:\n use the variables field, a space if necessary and the line label.\n\n How to make the middle column of the proof box:\n left justify the formula field.\n\n How to make the right column of the proof box:\n use the reason and use fields.\n\n\n Make the four edges of a rectangular box and the separator\n between \\verb/\\+/ columns.\n\n\n Use dotted lines: \\verb/\\dottedproofbox/.\n\n Leave the boxes open at the bottom: \\verb/\\openproofbox/\n\n%=======================================================================\n\\section{Miscellaneous logical notations}\n\nThese macros are now in my \\texttt{logicsym.sty}\n\n Print the names of the introduction and elimination rules, for example:\n  \\begin{quote}\n     \\verb/\\elim\\forall/ $\\elim\\forall$ \\qquad\n     \\verb/\\intro\\land/ $\\intro\\land$ \\qquad\n  \\end{quote}\n Recall that in \\TeX\\ the logical connectives and quantifiers are called\n  \\begin{center}\n    \\verb/\\lor/ $\\lor$\\quad\n    \\verb/\\land/ $\\land$\\quad\n    \\verb/\\lnot/ $\\lnot$\\quad\n    \\verb/\\forall/ $\\forall$\\quad\n    \\verb/\\exists/ $\\exists$\n  \\end{center}\n The following provide macros for the \\verb/\\implies/ {\\em relation\\/}\n and for the binary {\\em operation\\/} which yields the abstract\n \\verb/\\implic/ation between formulae.\n The point is that \\TeX\\ spaces them and breaks the lines differently:\n  \\begin{center}\n    \\verb/A\\implies B/ $A\\implies B$\\quad{\\em versus\\/}\\quad\n    \\verb/A\\implic B/ $A\\implic B$\n  \\end{center}\n There are forward and reverse, single and Double versions.\n\n Handle the spacing after a variable (and optionally its type)\n bound by a quantifier symbol. For example\n  \\begin{quote}\n    \\verb/\\All x:X. \\phi(x)/\\quad prints as\\quad $\\All x:X.\\phi(x)$\\quad\n     instead of\\quad $\\forall x:X.\\phi(x)$\n  \\end{quote}\n We provide some commonly used forms; \\verb/\\iota/ ($\\iota$) is Russell's\n description operator and should really be inverted.\n There are several notations for substitution.\n After writing $a[x:=b]$ throughout my book I~thought I~might change to\n $[b/x]^*a$.\n This macro reads the source in the first form and prints in the second.\n If you use it you can, like me, defer the decision about\n which notation to use until the final stages, doing\n \\begin{quote}\n    \\verb/\\renewcommand{\\Subst}{\\plainsubstitution}/\n \\end{quote}\n if you finally decide on making substitution act on the right.\n This is already an improvement on the literal text, because it\n automatically enlarges the brackets according to the text inside.\n \\verb/\\Subst/ itself is (following my book)\n defined in terms of the action of a context morphism (\\verb/\\CtxtMor/)\n on a term. Again you can do\n \\begin{quote}\n    \\verb/\\renewcommand{\\CtxtMor}{\\plaincontextmorphism}/\n \\end{quote}\n for something simpler.\n This macro interprets its argument as a comma-separated list\n of items in the form $x:=b$, which it switches to $b/x$.\n The simple versions.\n\n%=======================================================================\n\\section{Some very easy logic exercises}\n\nThe following examples are taken from Krysia Broda's\n{\\em Solutions to Problems~5\\/} (KB-Logic-B1-90) and took me a little\nunder an hour to type in.\n\npage 1: (a)\n\n\\begin{proofbox}\n   \\: P\\land Q \\\\\n   \\: P         \\= \\elim\\land\\\\\n\\end{proofbox}\n\n\\begin{proofbox}\n   \\lbl{1}\\: P \\\\\n   \\[\n      \\: Q \\\\\n      \\: P \\= (\\ref{1}) \\\\\n   \\]\n   \\: Q\\to P \\= \\intro\\to \\\\\n\\end{proofbox}\n\n\npage 2: (c)\n\n\\begin{proofbox}\n   \\lbl{2}\\: P\\\\\n   \\[\n      \\lbl{3}\\: Q\\\\\n      \\: P\\land Q\\= \\intro\\land(\\ref{2},\\ref{3}) \\\\\n   \\]\n   \\: Q\\to(P\\land Q) \\= \\intro\\to \\\\\n\\end{proofbox}\n\n(g)\n\n\\begin{proofbox}\n   \\lbl{6}\\: P\\to(Q\\to R)\\\\\n   \\[\n      \\lbl{4}\\: P\\to Q\\\\\n      \\[\n         \\lbl{5}\\: P\\\\\n         \\lbl{8}\\: Q \\= \\elim\\to(\\ref{4},\\ref{5})\\\\\n         \\lbl{7}\\: Q\\to R \\= \\elim\\to(\\ref{6},\\ref{5})\\\\\n         \\: R \\= \\elim\\to(\\ref{7},\\ref{8})\\\\\n      \\]\n      \\: P\\to R \\= \\intro\\to \\\\\n   \\]\n   \\: (P\\to Q)\\to(P\\to R) \\= \\intro\\to \\\\\n\\end{proofbox}\n\npage 3: (h)\n\n\\begin{proofbox}\n   \\lbl{10}\\: P\\to(Q\\to R)\\\\\n   \\[\n      \\lbl{9}\\: P\\land Q\\\\\n      \\lbl{11}\\: P \\= \\elim\\land1(\\ref{9})\\\\\n      \\lbl{12}\\: Q\\to R \\= \\elim\\to(\\ref{10},\\ref{11})\\\\\n      \\lbl{13}\\: Q \\=\\elim\\land2(\\ref{9})\\\\\n      \\: R \\=\\elim\\to(\\ref{12},\\ref{13})\\\\\n   \\]\n      \\: P\\land Q\\to R \\= \\intro\\to \\\\\n\\end{proofbox}\n\n(i)\n\n\\begin{proofbox}\n   \\lbl{16}\\: P\\land Q\\to R \\\\\n   \\[\n      \\lbl{14}\\: P \\\\\n      \\[\n         \\lbl{15}\\: Q \\\\\n         \\lbl{17}\\: P\\land Q \\= \\intro\\land(\\ref{14},\\ref{15})\\\\\n         \\: R \\= \\elim\\to(\\ref{16},\\ref{17})\n      \\]\n      \\: Q\\to R \\= \\intro\\to \\\\\n   \\]\n   \\: P\\to(Q\\to R) \\= \\intro\\to \\\\\n\\end{proofbox}\n\n(j)\n\n\\begin{proofbox}\n   \\lbl{18}\\: P\\to Q\\\\\n   \\lbl{20}\\: \\lnot Q\\\\\n   \\[\n      \\lbl{19}\\: P \\\\\n      \\lbl{21}\\: Q \\= \\elim\\to(\\ref{18},\\ref{19})\\\\\n      \\: \\bot \\= \\elim\\lnot(\\ref{20},\\ref{21})\\\\\n   \\]\n   \\: \\lnot P \\= \\intro\\lnot \\\\\n\\end{proofbox}\n\npage 5: (k)\n\n\\begin{proofbox}\n   \\lbl{22}\\: \\lnot P\\\\\n   \\[\n      \\lbl{23}\\: P\\\\\n      \\[\n         \\: \\lnot Q\\\\\n         \\: \\lnot P \\land P \\= \\intro\\land(\\ref{22},\\ref{23})\\\\\n         \\: \\bot \\= \\elim\\lnot(\\ref{22},\\ref{23})\\\\\n      \\]\n      \\: \\lnot\\lnot Q \\= \\intro\\lnot\\\\\n      \\: Q \\= \\lnot\\lnot\\\\\n   \\]\n   \\: P\\to Q \\= \\intro\\to \\\\\n\\end{proofbox}\n\npage 8: (o)\n\n\\begin{proofbox}\n   \\lbl{24}\\: P\\to Q \\\\\n   \\[\n      \\lbl{26}\\: \\lnot Q \\\\\n      \\[\n         \\lbl{25}\\: P \\\\\n         \\lbl{27}\\: Q \\= \\elim\\to(\\ref{24},\\ref{25})\\\\\n         \\: \\bot \\= \\elim\\lnot(\\ref{26},\\ref{27})\\\\\n      \\]\n      \\: \\lnot P \\= \\intro\\lnot\\\\\n   \\]\n   \\: \\lnot Q\\to \\lnot P \\= \\intro\\to \\\\\n\\end{proofbox}\n\n(p) The $\\lnot\\lnot$ rule is unnecessary!\n\n\\begin{proofbox}\n   \\lbl{28}\\: P\\to Q \\\\\n   \\[\n      \\: \\lnot\\lnot P\\\\\n      \\lbl{29}\\: P \\= \\lnot\\lnot\\\\\n      \\[\n         \\lbl{31}\\: \\lnot Q \\\\\n         \\lbl{30}\\: Q \\= \\elim\\to(\\ref{28},\\ref{29})\\\\\n         \\: Q\\land\\lnot Q \\= \\intro\\land(\\ref{30},\\ref{31})\\\\\n         \\: \\bot \\= \\elim\\lnot\\\\\n      \\]\n      \\: \\lnot\\lnot Q \\= \\intro\\lnot\\\\\n   \\]\n   \\: \\lnot\\lnot P\\to\\lnot\\lnot Q \\= \\intro\\to \\\\\n\\end{proofbox}\n\n%=======================================================================\n\\section{Some more exercises}\n\n\\begin{proofbox}\n   \\: P\\lor\\lnot P \\\\\n   \\(\n      \\: P \\\\\n      \\: Q\\to P \\=\\hbox{by (e)}\\\\\n      \\: (P\\to Q)\\lor(Q\\to P) \\= \\intro\\lor \\\\\n   \\+\n      \\: \\lnot P\\\\\n      \\: P\\to Q \\=\\hbox{by (k)}\\\\\n      \\: (P\\to Q)\\lor(P\\to Q) \\= \\intro\\lor \\\\\n   \\)\n   \\: (P\\to Q)\\lor(P\\to Q) \\= \\elim\\lor \\\\\n\\end{proofbox}\n\n\n\n\\begin{proofbox}\n   \\lbl{35}\\: P\\lor Q \\\\\n   \\[\n      \\lbl{30}\\: (\\lnot P)\\land(\\lnot Q) \\\\\n      \\(\n         \\lbl{31} \\: P \\\\\n         \\lbl{32} \\: \\lnot P \\=\\elim\\land1(\\ref{30})\\\\\n         \\: \\bot \\= \\elim\\lnot(\\ref{32},\\ref{31})\\\\\n      \\+\n         \\lbl{33} \\: Q \\\\\n         \\lbl{34} \\: \\lnot Q \\= \\elim\\land2(\\ref{30})\\\\\n         \\: \\bot \\= \\elim\\lnot(\\ref{33},\\ref{34})\\\\\n      \\)\n      \\: \\bot \\= \\elim\\lor(\\ref{35})\\\\\n   \\]\n   \\: \\lnot((\\lnot P)\\land(\\lnot Q)) \\= \\intro\\lnot \\\\\n\\end{proofbox}\n\n\n\\begin{proofbox}\n\\lbl{51} x \\: \\forall x'.x'<x\\to p(x')\\\\\n   \\(\n       \\lbl{52}\\: x=a \\\\\n       \\(\n          \\: a=c \\\\\n               \\: b<x \\=\\hbox{subst}(\\ref{50})\\\\\n               \\: p(b) \\= \\elim\\forall(\\ref{51})\\\\\n               \\: b\\neq b \\= \\elim\\land\\\\\n               \\: \\bot \\= \\hbox{refl}\\\\\n       \\+\n          \\: c<a \\\\\n               \\: c<x \\=\\hbox{subst}(\\ref{52})\\\\\n               \\: p(c) \\= \\elim\\forall(\\ref{51})\\\\\n               \\: c\\neq c \\= \\elim\\land\\\\\n               \\: \\bot \\\\\n       \\)\n               \\: \\bot \\= \\elim\\lor(\\ref{53})\\\\\n   \\*\n       \\(\n           \\[\n               \\: x=b \\\\\n                  \\: a<x \\\\\n                  \\: p(a) \\= \\elim\\forall\\\\\n                  \\: a\\neq a\\\\\n                  \\: \\bot \\\\\n           \\] \\: x\\neq b \\= \\intro\\lnot \\\\\n       \\*\n           \\[\n              \\: x=c \\\\\n                  \\: b<x \\\\\n                  \\: p(b) \\= \\elim\\forall\\\\\n                  \\: b\\neq b\\\\\n                  \\: \\bot\n           \\] \\: x\\neq c \\= \\intro\\lnot \\\\\n       \\)\n   \\)\n   \\: x\\neq a \\land x\\neq b \\land x\\neq c \\= \\intro\\land\\\\\n   \\: p(x) \\= \\hbox{def} \\\\\n\\end{proofbox}\n\n\\begin{proofbox}\n   \\: a<b \\\\\n   \\lbl{40}\\= b<c \\\\\n   \\: a<c \\lor (a=c \\lor c<a) \\\\\n   \\(\n       \\lbl{43}\\: a=c \\lor c<a \\\\\n       \\: p(x)\\equiv(x\\neq a\\land (x\\neq b \\land x\\neq c))\\=\\hbox{def}\\\\\n       \\[\n          \\lbl{41} x \\: \\forall x'.x'<x\\to p(x')\\\\\n          \\(\n              \\lbl{42}\\: x=a \\\\\n            \\(\n               \\: a=c \\\\\n               \\: b<x \\=\\hbox{subst}(\\ref{40})\\\\\n               \\: p(b) \\= \\elim\\forall(\\ref{41})\\\\\n               \\: b\\neq b \\= \\elim\\land\\\\\n               \\: \\bot \\= \\hbox{refl}\\\\\n            \\+\n               \\: c<a \\\\\n               \\: c<x \\=\\hbox{subst}(\\ref{42})\\\\\n               \\: p(c) \\= \\elim\\forall(\\ref{41})\\\\\n               \\: c\\neq c \\= \\elim\\land\\\\\n               \\: \\bot \\\\\n            \\)\n            \\: \\bot \\= \\elim\\lor(\\ref{43})\\\\\n         \\*\n            \\(\n               \\[\n                  \\: x=b \\\\\n                  \\: a<x \\\\\n                  \\: p(a) \\= \\elim\\forall\\\\\n                  \\: a\\neq a\\\\\n                  \\: \\bot \\\\\n               \\]\n               \\: x\\neq b \\= \\intro\\lnot \\\\\n            \\*\n               \\[\n                  \\: x=c \\\\\n                  \\: b<x \\\\\n                  \\: p(b) \\= \\elim\\forall\\\\\n                  \\: b\\neq b\\\\\n                  \\: \\bot \\\\\n               \\]\n               \\: x\\neq c \\= \\intro\\lnot \\\\\n            \\)\n       \\)\n       \\: x\\neq a \\land x\\neq b \\land x\\neq c \\= \\intro\\land\\\\\n       \\: p(x) \\= \\hbox{def}\\\\\n    \\]\n    \\: \\forall x.(\\forall x'.x'<x\\to p(x'))\\to p(x) \\= \\intro\\forall\\\\\n   \\: p(a) \\= \\elim\\forall\\\\\n   \\: a\\neq a \\= \\elim\\land\\\\\n   \\: \\bot\\\\\n   \\: a<c \\= \\elim\\bot \\\\\n\\+\n   \\: a<c \\\\\n\\)\n\\: a<c \\= \\elim\\lor\\\\\n\\end{proofbox}\n\n%=======================================================================\n\\section{Krysia Broda's dragons exercise}\n\n\\def\\happy#1{{{\\mathsf{happy}}(#1)}}\n\\def\\child#1#2{{{\\mathsf{child}}(#1,#2)}}\n\\def\\fly#1{{{\\mathsf{fly}}(#1)}}\n\\def\\dragon#1{{{\\mathsf{dragon}}(#1)}}\n\\def\\green#1{{{\\mathsf{green}}(#1)}}\n\\def\\parent#1#2{{{\\mathsf{parent}}(#1,#2)}}\n\n\\def\\all{\\forall}\n\\def\\some{\\exists}\n\\def\\imp{\\Rightarrow}\n\\def\\impby{\\Leftarrow}\n\n\\advance\\proofboxmargin-3em\n\n\\begin{proofbox}\n\\lbl{happy}\\:\\all x.\\happy x\\impby[\\all y.\\child y x\\imp\\fly y]\n        \\land\\dragon x\\\\\n\\lbl{fly}\\:\\all x.\\green x \\land \\dragon x \\imp \\fly x\\\\\n\\lbl{green}\\:\\all x.[\\some y.\\parent y x \\land \\green y]\\imp\\green x\\\\\n\\lbl{dragon}\\:\\all z.\\all x.\\child x z \\land \\dragon z \\imp \\dragon x\\\\\n\\lbl{parent}\\:\\all x.\\all y.\\parent x y \\impby \\child y x\\\\\n\\[\\all x_0\\lbl{Dragon}\\:\\dragon{x_0}\\\\\n        \\lbl{Green}\\:\\green{x_0}\\\\\n        \\[\\all y_0\\lbl{child}\\:\\child {y_0}{x_0}\\\\\n                \\(      \\lbl{Parent}\\:\\parent{x_0}{y_0}\n                                \\=\\elim\\all(\\ref{parent})\\\\\n                        \\:\\parent{x_0}{y_0} \\land\\green{x_0}\n                                \\=\\intro\\land(\\ref{Green})\\\\\n\\lbl{greenish}  \\:\\some z.\\parent z {y_0} \\land \\green z\n                                \\=\\intro\\some(z:=x_0)\\\\\n                        \\:\\green{y_0}\\=\\elim\\all(\\ref{green},x:=y_0)\\\\\n                \\*\n                        \\:\\dragon{y_0}\\=\\elim\\all(\\ref{dragon},x:=y_0,\n                                z:=x_0,\\ref{Dragon})\\\\\n                \\)\\lbl{greendragon}\\:\\green{y_0}\\land\\dragon{y_0}\n                                \\=\\intro\\land\\\\\n                \\:\\fly{y_0}\\=\\elim\\all(\\ref{fly},x:=y_0,\\ref{greendragon})\\\\\n        \\]\\lbl{taught}\\:\\all y.\\child y{x_0}\\imp\\fly y\\=\\intro\\all\\\\\n        \\:\\happy x\\=\\elim\\all(\\ref{happy},\\ref{taught},\\ref{Dragon})\\\\\n\\]\\:\\all x.\\happy x \\impby \\green x \\impby \\dragon x\\=\\intro\\all\\\\\n\\end{proofbox}\n\\noindent\nWhere the previous deduction is a premise of a rule, the reference is omitted.\nWhere the substitution is of the same letter (possibly with a subscript) it\nis omitted, except for the $\\alpha$-conversion (change of bound variable name)\nin line~\\ref{greenish}.\n\n%=======================================================================\n\\section{Proof boxes from my book}\n\n$$\\proofboxformulawidth=18em\\relax\n\\begin{proofbox}\n\\[\\forall x:\\lbl{ind box hyp}\\:\\forall x'.x'\\prec x\\imp\\phi(x')\n   \\=\\mbox{induction hypothesis}\\\\\n\\:\\vdots\\\\\n\\lbl{ind box pred}\\:u\\prec x\\=\\mbox{various terms $u$}\\\\\n\\:\\phi(u)\\=\\elim\\forall(\\ref{ind box hyp},\\ref{ind box pred})\\\\\n\\:\\vdots\\\\\n\\:\\phi(x)\\=\\mbox{the property}\\\\\n\\]\\:\\forall x.(\\forall x'.x'\\prec x\\imp\\phi(x'))\\imp\\phi(x)\\=\\intro\\forall\\\\\n\\:\\forall x.\\phi(x)\\=\\mbox{$\\prec$-induction for $\\phi$}\\\\\n\\end{proofbox}$$\n$$\\begin{proofbox}\n\\lbl{ind eg 0}\\:\\phi(0)\\=z\\\\\n\\lbl{ind eg s}\\:\\forall n.\\phi(n)\\imp\\phi(n+1)\\=s\\\\\n\\lbl{ind eg 1-}\\:\\phi(0)\\imp\\phi(1)\\=\\elim\\forall(\\ref{ind eg s})\\\\\n\\lbl{ind eg 1}\\:\\phi(1)\\=\\elim\\imp(\\ref{ind eg 1-},\\ref{ind eg 0})\\\\\n\\lbl{ind eg 2-}\\:\\phi(1)\\imp\\phi(2)\\=\\elim\\forall(\\ref{ind eg s})\\\\\n\\lbl{ind eg 2}\\:\\phi(2)\\=\\elim\\imp(\\ref{ind eg 2-},\\ref{ind eg 1})\\\\\n\\lbl{ind eg 3-}\\:\\phi(2)\\imp\\phi(3)\\=\\elim\\forall(\\ref{ind eg s})\\\\\n\\lbl{ind eg 3}\\:\\phi(3)\\=\\elim\\imp(\\ref{ind eg 3-},\\ref{ind eg 2})\\\\\n\\end{proofbox}$$\n$$\\begin{proofbox}\n\\lbl{mrwf1}\\:\\forall x.(\\forall x'.x'\\lt x\\imp\\phi(x'))\\imp\\phi(x)\n\\=\\mbox{hypothesis}\\\\\n\\lbl{mrwf4}\\:\\psi(y)\\eqdef\\forall x.(fx=y)\\imp\\phi(x)\\=\\mbox{definition}\\\\\n\\[\\forall y:\\lbl{mrwf2}\\:\\forall y'.y'\\prec y\\imp\\psi(y') \\\\\n   \\[\\forall x:\\lbl{mrwf3}\\:fx=y\\\\\n      \\[\\forall x':\\:x'\\lt x\\\\\n          \\:fx'\\prec y\\=\\hbox{monotonicity}\\\\\n          \\:\\psi(fx')\\=\\elim\\forall(\\ref{mrwf2})\\\\\n          \\:\\phi(x')\\=\\elim\\forall(\\hbox{def }\\ref{mrwf4},\\ref{mrwf3})\\\\\n      \\]\n      \\:\\forall x'.x'\\lt x\\imp\\phi(x')\\=\\intro\\forall\\\\\n      \\:\\phi(x)\\=\\elim\\forall(\\ref{mrwf1})\\\\\n   \\]\n   \\:\\forall x.(fx=y)\\imp\\phi(x)\\=\\intro\\forall\\\\\n  \\:\\psi(y)\\=\\hbox{def}(\\ref{mrwf4})\\\\\n\\]\n\\:\\forall y.(\\forall y'.y'\\prec y\\imp\\psi(y'))\\imp\\psi(y)\\=\\intro\\forall\\\\\n\\:\\forall y.\\psi(y)\\=(Y,{\\prec})\\hbox{-induction}\\\\\n\\end{proofbox}$$\n$$\\begin{proofbox}\n\\lbl{qwf1}\\:\\forall y.[\\forall y'.y'\\eps y\\imp\\phi(y')]\\imp\\phi(y)\\\\\n\\[\\lbl{qwf2}\\forall x:\\:\\forall x'.x'\\prec x\\imp\\phi(fx')\\\\\n\\[\\forall y':\\:y'\\eps fx\\\\\n\\lbl{qwf3}\\:\\exists x'.x'\\prec x\\land y'=fx'\n\\=\\hbox{surj on pred}\\\\\n\\[\\exists x':\\:x'\\prec x\\\\\n\\:y'=fx'\\\\\n\\:\\phi(fx')\\=\\elim\\forall(\\ref{qwf2})\\\\\n\\:\\phi(y')\\=\\hbox{substitution}\\\\\n\\]\\:\\phi(y')\\=\\elim\\exists(\\ref{qwf3})\\\\\n\\]\\:\\forall y'.y'\\eps fx\\imp\\phi(y')\\=\\intro\\forall\\\\\n\\:\\phi(fx)\\=\\elim\\forall(\\ref{qwf1},y:=fx)\\\\\n\\]\\:\\forall x.[\\forall x'.x'\\prec x\\imp\\phi(fx')]\\imp\\phi(fx)\\=\\intro\\forall\\\\\n\\end{proofbox}$$\n$$\\begin{proofbox}\n\\lbl{trwf1}\\:\\forall x_2,x.[x_2\\ll x \\biimplies\nx_2\\prec x \\lor \\exists x_1. x_2\\ll x_1\\prec x]\\\\\n\\lbl{trwf2}\\:\\forall x.[\\forall x'.x'\\prec x\\imp\\phi(x')]\\imp\\phi(x)\n\\=\\mbox{hypothesis}\\\\\n\\lbl{trwf3}\\:\\psi(x)\\eqdef\\forall x_2.x_2\\ll x\\imp\\phi(x_2)\n\\=\\mbox{definition}\\\\\n\\lbl{trwf4}\\:\\forall x.\\psi(x)\\imp\\phi(x)\n\\=\\intro\\forall(\\elim\\forall(\\ref{trwf2},\\ref{trwf3}))\\\\\n\\(\\:\\phi(x)\\\\\n\\:\\forall x_2.x_2\\ll x\\imp\\phi(x_2)\\\\\n\\[\\forall x_1:\\:x_2\\ll x_1\\\\\n\\:x_2\\ll x\\\\\n\\:\\phi(x_2)\\\\\n\\:\\forall x_2.x_2\\ll x\\imp\\phi(x_2)\\\\\n\\:\\psi(x_1)\\\\\n\\]\\:\\forall x_1.x_1\\prec x\\imp\\psi(x_1)\\\\\n\\+\\lbl{trwf5}\\forall x:\\:\\forall x_1.x_1\\prec x\\imp\\psi(x_1)\\\\\n\\[\\forall x_2:\\:x_2\\ll x\\\\\n\\lbl{trwf7}\\:x_2\\prec x_1\\lor\\exists x_1.x_2\\ll x_1\\prec x\n\\=\\elim\\forall(\\ref{trwf1})\\\\\n\\(\\:x_2\\prec x_1\\\\\n\\:\\psi(x_2)\\=\\elim\\forall(\\ref{trwf5})\\\\\n\\:\\phi(x_2)\\=\\elim\\forall(\\ref{trwf4})\\\\\n\\+\\exists x_1:\\:x_2\\ll x_1\\prec x\\\\\n\\:\\psi(x_1)\\=\\elim\\forall(\\ref{trwf5})\\\\\n\\:\\phi(x_2)\\=\\elim\\forall(\\ref{trwf3},x:=x_1)\\\\ \n\\)\\:\\phi(x_2)\\=\\elim{\\exists{\\lor}}(\\ref{trwf7})\\\\\n\\]\\:\\forall x_2.x_2\\ll x\\imp\\phi(x_2)\\=\\intro\\forall\\\\\n\\:\\psi(x)\\=\\hbox{def}(\\ref{trwf3})\\\\\n\\)\\:\\forall x.[\\forall x_1.x_1\\prec x\\imp\\psi(x_1)]\\biimplies\\psi(x)\n\\=\\intro{\\forall{\\biimplies}}\\hfill\\\\\n\\end{proofbox}$$\n$$\\begin{proofbox}\n\\:\\forall U.[\\forall V.V\\flt\\prec U\\imp\\phi(V)]\\biimplies\\phi(U)\\\\\n\\:\\phi(\\emptyset)\\\\\n\\[\\forall x,U:\\:\\phi(U)\\\\\n\\lbl{fltindxhyp}\\:\n        [\\forall y.y\\prec x\\imp[\\forall V.\\phi(V)\\imp\\phi(V\\cup\\setof y)]]\\\\\n\\[\\forall V_0:\\:V_0\\flt\\prec U\\\\\n\\:\\phi(V_0)\\=\\mbox{premise}\\\\\n\\:\\emptyset\\flt\\prec\\setof x\\imp\\phi(V_0)\\\\\n\\[\\forall y,V_1:\\:V_1\\flt\\prec x\\\\\n\\lbl{fltindV0V1}\\:\\phi(V_0\\cup V_1)\\\\\n\\lbl{fltindy<x}\\:y\\prec x\\\\\n\\:\\phi(V_0\\cup V_1\\cup\\setof y)\n        \\=\\elim\\forall(\\ref{fltindxhyp},\\ref{fltindy<x},V:=V_0\\cup V_1,\n        \\ref{fltindV0V1})\\\\\n\\]\n\\:\\forall y,V_1.V_1\\flt\\prec x\\land y\\prec x\\land\\phi(V_0\\cup V_1)\n        \\imp\\phi(V_0\\cup V_1\\cup\\setof y)\\=\\intro\\forall\\\\\n\\:\\forall V_1.V_1\\flt\\prec\\setof x\\imp\\phi(V_0\\cup V_1)\n        \\=\\mbox{$\\KK$-induction}\\\\\n\\]\n\\:\\forall V_0,V_1.V_0\\flt\\prec U\\land V_1\\flt\\prec\\setof x\n        \\imp\\phi(V_0\\cup V_1)\\=\\intro\\forall\\\\\n\\:\\forall V.V\\flt\\prec U\\cup\\setof x\\imp\\phi(V)\\=\\mbox{Lemma}\\\\\n\\:\\phi(U\\cup\\setof x)\\=\\mbox{premise}\\\\\n\\]\n\\:\\forall x.[\\forall y.y\\prec x\\imp[\\forall V.\\phi(V)\\imp\\phi(V\\cup\\setof y)]]\n        \\imp[\\forall U.\\phi(U)\\imp\\phi(U\\cup\\setof x)]\\=\\intro\\forall\\\\\n\\:\\forall x.[\\forall U.\\phi(U)\\imp\\phi(U\\cup\\setof x)]\n        \\=\\mbox{$\\prec$-induction}\\\\\n\\:\\forall U.\\phi(U)\\=\\mbox{$\\KK$-induction}\\\\\n\\end{proofbox}$$\n$$\\proofboxnonumbers\\proofboxformulawidth=4em\n\\begin{array}{cc}\n\\begin{proofbox}\\[\\qquad\\:\\phi\\=\\qquad\\\\\\:\\vdots\\\\\\:\\psi\\\\\\]\n\\:\\phi\\imp\\psi\\=\\intro\\imp\\end{proofbox}&\n\\begin{proofbox}\\[\\forall x':\\\\\\:\\vdots\\=\\qquad\\\\\\:\\phi(x')\\\\\\]\n\\:\\forall x.\\phi(x)\\=\\intro\\forall\\end{proofbox}\\\\\n\\begin{proofbox}\\qquad\\:\\phi\\lor\\psi\\\\\n\\(\\qquad\\:\\phi\\=\\qquad\\\\\\:\\vdots\\\\\\:\\alpha\\\\\n\\+\\:\\psi\\=\\qquad\\\\\\:\\vdots\\\\\\:\\alpha\\\\\\)\n\\:\\alpha\\=\\elim\\lor\\end{proofbox}&\n\\begin{proofbox}\\:\\exists x.\\phi(x)\\\\\n\\[\\exists x':\\:\\phi(x')\\=\\qquad\\\\\\:\\vdots\\\\\\:\\alpha\\\\\\]\n\\:\\alpha\\=\\elim\\exists\\end{proofbox}\n\\end{array}$$\n$$\\proofboxformulawidth=30em \\begin{proofbox}\n\\(\\:\\alpha\\biimplies\\psi(x,\\top)\\\\\n\\:\\exists\\beta.\\psi(x,\\beta)\\=\\mathsf{total}\\\\\n\\[\\exists\\beta:\\:\\psi(x,\\beta)\\\\\n\\(\\:\\beta\\\\\n\\:\\beta=\\top\\\\\n\\:\\psi(x,\\top)\\=\\mathsf{subs}\\\\\n\\:\\alpha\\=\\elim\\biimplies\\\\\n\\*\\:\\alpha\\\\\n\\:\\psi(x,\\top)\\=\\elim\\biimplies\\\\\n\\:\\beta=\\top\\=\\mathsf{func}\\\\\n\\:\\beta\\\\\n\\)\\:\\alpha=\\beta\\=\\intro\\biimplies\\\\\n\\:\\psi(x,\\alpha)\\=\\mathsf{subs}\\\\\n\\]\\:\\psi(x,\\alpha)\\=\\elim\\exists\\\\\n\\*\n\\:\\psi(x,\\alpha)\\\\\n\\(\\:\\alpha\\\\\n\\:\\alpha=\\top\\\\\n\\:\\phi(x,\\top)\\=\\mathsf{subs}\\\\\n\\*\\:\\psi(x,\\top)\\\\\n\\:\\alpha=\\top\\=\\mathsf{func}\\\\\n\\:\\alpha\\\\\n\\)\n\\:\\alpha\\biimplies\\psi(x,\\top)\\=\\intro\\biimplies\\\\\n\\)\\:\\psi(x,\\alpha)\\biimplies(\\alpha\\biimplies\\psi(x,\\top))\\=\\intro\\biimplies\\\\\n\\end{proofbox}$$\n$$\\proofboxformulawidth=7em \\proofboxmargin=2em\n\\begin{proofbox}\n\\[\\lbl{pnn0h}\\:\\alpha\\\\\n\\lbl{pnn0r}\\:\\alpha\\imp\\alpha\\\\\n\\:\\alpha\\=\\qquad\\quad(\\ref{pnn0h})\\\\\n\\]\\:\\alpha\\imp(\\alpha\\imp\\alpha)\\imp\\alpha\\=\\intro\\forall\\\\\n\\proofboxnonumbers\\:(0)\\\\\n\\end{proofbox}\n\\hskip 0pt minus3em\\relax\n\\begin{proofbox}\n\\[\\lbl{pnn1h}\\:\\alpha\\\\\n\\lbl{pnn1r}\\:\\alpha\\imp\\alpha\\\\\n\\:\\alpha\\=\\elim\\imp(\\ref{pnn1r},\\ref{pnn1h})\\\\\n\\]\\:\\alpha\\imp(\\alpha\\imp\\alpha)\\imp\\alpha\\=\\intro\\forall\\\\\n\\proofboxnonumbers\\:(1)\\\\\n\\end{proofbox}\n\\hskip 0pt minus3em\\relax\n\\begin{proofbox}\n\\[\\lbl{pnn2h}\\:\\alpha\\\\\n\\lbl{pnn2r}\\:\\alpha\\imp\\alpha\\\\\n\\lbl{pnn21}\\:\\alpha\\=\\elim\\imp(\\ref{pnn2r},\\ref{pnn2h})\\\\\n\\:\\alpha\\=\\elim\\imp(\\ref{pnn2r},\\ref{pnn21})\\\\\n\\]\\:\\alpha\\imp(\\alpha\\imp\\alpha)\\imp\\alpha\\=\\intro\\forall\\\\\n\\proofboxnonumbers\\:(2)\\\\\n\\end{proofbox}\n%  \\hskip 0pt minus3em\\relax\n%  \\begin{proofbox}\n%  \\[\\lbl{pnn3h}\\:\\alpha\\\\\n%  \\lbl{pnn3r}\\:\\alpha\\imp\\alpha\\\\\n%  \\lbl{pnn31}\\:\\alpha\\=\\elim\\imp(\\ref{pnn3r},\\ref{pnn3h})\\\\\n%  \\lbl{pnn32}\\:\\alpha\\=\\elim\\imp(\\ref{pnn3r},\\ref{pnn31})\\\\\n%  \\:\\alpha\\=\\elim\\imp(\\ref{pnn1r},\\ref{pnn32})\\\\\n%  \\]\\:\\alpha\\imp(\\alpha\\imp\\alpha)\\imp\\alpha\\=\\intro\\forall\\\\\n%  \\proofboxnonumbers\\:(3)\\\\\n%\\end{proofbox}%Overfull \\hbox (17.42128pt too wide) detected\n$$\n$$\\vbox{\\proofboxformulawidth=12em \\relax\n\\begin{proofbox}\n\\lbl{pthora1}\\:\\phi\\land\\psi\\\\\n\\[\\lbl{pthora2}\\forall\\alpha:\\:\\phi\\implies(\\psi\\implies\\alpha)\\\\\n\\lbl{pthora3}\\:\\phi\\=\\elim{{\\land}1}(\\ref{pthora1})\\\\\n\\lbl{pthora4}\\:\\psi\\implies\\alpha\n\\=\\elim\\implies(\\ref{pthora2},\\ref{pthora3})\\\\\n\\lbl{pthora5}\\:\\psi\\=\\elim{{\\land}2}(\\ref{pthora1})\\\\\n\\lbl{pthora6}\\:\\alpha\n\\=\\elim\\implies(\\ref{pthora4},\\ref{pthora5})\\\\\n\\]\\:\\forall\\alpha.(\\phi\\implies(\\psi\\implies\\alpha))\\implies\\alpha\n\\=\\intro{\\forall{\\implies}}\\\\\n\\end{proofbox}}\n\\kern6em\n%\n% Underfull \\hbox (badness 10000) in paragraph\n% Overfull \\hbox (282.68869pt too wide) detected\n%\n\\vbox{\\baselineskip=\\proofboxbaselineskip\\relax\n$p_1:\\phi\\times\\psi$\\\\\n$p_2:\\phi\\to(\\psi\\to\\alpha)$\\\\\n$p_3=\\pi_1(p_1):\\phi$\\\\\n$p_4=p_2(p_3):\\psi\\to\\alpha$\\\\\n$p_5=\\pi_2(p_1):\\psi$\\\\\n$p_6=p_4(p_5):\\alpha$\\\\\n$p_7=\\lambda\\alpha.\\lambda p_2.p_6\n%  =\\lambda\\alpha\\lambda p_2.p_2(\\pi_1(p_1))(\\pi_2(p_1))\n%  :\\Pi\\alpha.(\\phi\\to(\\psi\\to\\alpha))\\to\\alpha\n$\\\\}$$\n\n%=======================================================================\n\\section{From my JSL paper}\n\n%--------------------------------------------------------------------------\n%                 save the proof box so that we can find out its height\n\\setbox9=\\vbox{%\n\\proofboxbaselineskip=1.42em\n%\n%  parameters for version 1:\n   \\proofboxmargin=80pt\n   \\proofboxformulawidth=\\hsize\n   \\advance\\proofboxformulawidth-2\\proofboxmargin\n\\iffalse\n   \\def\\isX{:X}%\n   \\def\\isPfX{:\\finpower(X)}%\n\\else\n   \\def\\isX{}\\def\\isPfX{}%\n\\fi\n%\n\\begin{proofbox}%%*** WARNING: the names of the labels dont match their numbers\n\\lbl{fltwf1}\\:\\All U.[\\All V.V\\flt\\prec U\\Implies\\phi(V)]\n\\biimplies\\phi(U)\\\\\n%\\lbl{fltwf2}\\:\\All V.V\\flt\\prec\\emptyset\\Implies\\bot\n%   \\=\\mbox{def}({\\flt\\prec})\\\\\n\\lbl{fltwf3}\\:\\phi(\\emptyset)\n    \\=\\elim\\forall(\\ref{fltwf1},\\mbox{def}({\\flt\\prec}))\\\\ %\\ref{fltwf2})\\\\\n\\lbl{fltwf4}\\:\\psi(x)\\eqdef\\forall U.\\phi(U)\\Implies\\phi(U\\cup\\setof x)\\\\\n\\[\\lbl{fltwf5}\\lbl{fltindxhyp}\\forall x\\isX\n   \\:\\forall y.y\\prec x\\Implies\\psi(y)\\\\\n%\\:[\\forall y.y\\prec x\\Implies[\\All V.\\phi(V)\\Implies\\phi(V\\cup\\setof y)]]\\\\\n\\[\\lbl{fltwf8}\\forall V_0\\isPfX\n\\lbl{fltwf10}\\:\\phi(V_0)\\\\\n\\lbl{fltwf9}\\:\\theta(W)\\eqdef W\\flt\\prec\\setof x\\Implies\\phi(V_0\\cup W)\\\\\n\\lbl{fltwf11}\\:\\theta(\\emptyset)\n   \\=\\mbox{def}(\\ref{fltwf9},\\ref{fltwf10})\\\\\n\\[\\forall W\\isPfX\n   \\:\\theta(W)\\\\\n  \\forall y\\isX\\lbl{fltwf13}\\: W\\flt\\prec\\setof x\\Implies\\phi(V_0\\cup W)\n   \\=\\mbox{def}(\\ref{fltwf9})\\\\\n\\[\\lbl{fltwf14}\\:W\\cup\\setof y\\flt\\prec\\setof x\n   \\equiv W\\flt\\prec\\setof x\\land y\\prec x\\\\\n%\\lbl{fltwf15}\\:W\\flt\\prec\\setof x\\=\\ref{fltwf14},\\hbox{def}({\\flt\\prec})\\\\\n\\lbl{fltwf16}\\:\\phi(V_0\\cup W)\\=\\elim\\Implies(\\ref{fltwf13},\\ref{fltwf14})\\\\\n%\\lbl{fltwf17}\\:y\\prec x\\=\\ref{fltwf14},\\hbox{def}({\\flt\\prec})\\\\\n\\lbl{fltwf18}\\:\\psi(y)\\equiv\\forall V.\\phi(V)\\Implies\\phi(V\\cup\\setof y)\n\\=\\elim\\forall(\\ref{fltwf5},\\ref{fltwf14}),\\mbox{def}(\\ref{fltwf4})\\\\\n\\:\\phi(V_0\\cup W\\cup\\setof y)\\=\\elim\\forall(\\ref{fltwf18},\\ref{fltwf16})\\\\\n\\]\n\\:W\\cup\\setof y\\flt\\prec\\setof x\\Implies\\phi(V_0\\cup W\\cup\\setof y)\n   \\=\\intro\\Implies\\\\\n\\:\\theta(W\\cup\\setof y)\\=\\mbox{def}(\\ref{fltwf9})\\\\\n\\]\n\\:\\theta(\\emptyset)\\land\n     \\forall y.\\All W.\\big[\\theta(W)\\Implies\\theta(W\\cup\\setof y)\\big]\n     \\=\\intro\\land(\\ref{fltwf11},\\intro\\forall)\\\\\n\\:\\forall W.\\theta(W)\\=\\mbox{$\\KK$-induction for }\\theta\\\\\n\\:\\All W.W\\flt\\prec\\setof x\\Implies\\phi(V_0\\cup W)\\=\\mbox{def}(\\ref{fltwf9})\\\\\n\\]\n%\\:\\All V_0.V_0\\flt\\prec U\\Implies\\All W.\\theta(W)\\=\\intro\\forall\\\\\n\\lbl{fltwf24}\\:\\squashmuskip\n\\All V_0.\\phi(V_0)\\Implies\n      \\big(\\All W.W\\flt\\prec\\setof x\\Implies\\phi(V_0\\cup W)\\big)\n        \\=\\intro\\forall\\\\    %\\mbox{Currying, def(\\ref{fltwf9})}\\\\\n\\[\\lbl{fltwf6}\\forall U\\isPfX\n   \\:\\phi(U)\\\\\n%   \\:V_0\\flt\\prec U \\=\\elim\\forall(\\ref{fltwf1},\\ref{fltwf6},\\ref{fltwf8})\\\\\n\\lbl{fltwfa}\\:U=\\emptyset\\lor U\\neq\\emptyset\n   \\=\\hbox{Proposition~\\ref{free semil}}\\\\\n\\lbl{fltwfb}\\:\n   U=\\emptyset\\Implies\\All W.W\\flt\\prec(U\\cup\\setof x)\\Implies\\phi(W)\n   \\=\\elim\\forall(\\ref{fltwf24},V_0=\\emptyset,\\ref{fltwf3})\\\\\n\\[\\lbl{fltwfe}\\forall V_0\\isPfX\\:V_0\\flt\\prec U\\\\\n\\lbl{fltwff}\\forall W\\isPfX\\:W\\flt\\prec\\setof x\\\\\n\\label{fltwfg}\\:\\phi(V_0)\n   \\=\\elim{\\forall{\\Impliedby}}(\\ref{fltwf1},\\ref{fltwf6},\\ref{fltwfe})\\\\\n\\lbl{fltwfh}\\:\\phi(V_0\\cup W)\n   \\=\\elim\\forall(\\ref{fltwf24},\\ref{fltwfg},\\ref{fltwff})\\\\\n\\]\\:\\All V_0,W.V_0\\flt\\prec U\\land W\\flt\\prec\\setof x\\Implies\\phi(V_0\\cup W)\n  \\=\\intro\\forall\\\\\n\\lbl{fltwfk}\\:\n   U\\neq\\emptyset\\Implies\\forall V.V\\flt\\prec(U\\cup\\setof x)\\Implies\\phi(V)\n  \\=\\hbox{Lemma \\ref{flt power distr}}\\\\\n\\lbl{fltwf27}\\:\\forall V.V\\flt\\prec(U\\cup\\setof x)\\Implies\\phi(V)\n        \\=\\elim\\lor(\\ref{fltwfa},\\ref{fltwfb},\\ref{fltwfk})\\\\\n\\:\\phi(U\\cup\\setof x)\\=\\elim\\forall(\\ref{fltwf1},\\ref{fltwf27})\\\\\n\\]\\lbl{fltwf29}\n\\:\\forall U.\\phi(U)\\Implies\\phi(U\\cup\\setof x)\\equiv\\psi(x)\n        \\=\\intro\\forall,\\hbox{def}(\\ref{fltwf4})\\\\\n\\]\n\\:\\forall x.[\\All y.y\\prec x\\Implies\\psi(y)]\\Implies\\psi(x)\\=\\intro\\forall\\\\\n\\lbl{fltwf32}\\:\\forall x.\\psi(x)\\=\\mbox{$\\prec$-induction for }\\psi\\\\\n\\:\\phi(\\emptyset)\\land\\All x.\\All U.\n        \\big[\\phi(U)\\Implies\\phi(U\\cup\\setof x)\\big]\n        \\=\\intro\\land(\\ref{fltwf3},\\mbox{def}(\\ref{fltwf4},\\ref{fltwf32}))\\\\\n\\:\\All U.\\phi(U)\\=\\mbox{$\\KK$-induction for }\\phi      \\\\%\\;\\hfill\\qedsymbol\\\\\n\\end{proofbox}%\n}% end of \\setbox9=\\vbox\n\n\\box9\n\n%=======================================================================\n\n\\nocite{*}\n\\bibliographystyle{plain}\n%\\bibliography{boxuser}\n\n\\begin{thebibliography}{1}\n\n\\bibitem{VickersSJ:reasprog}\nK.~Broda, S.~Eisenbach, H.~Khoshnevisan, and Steven Vickers.\n\\newblock {\\em Reasoned Programming}.\n\\newblock International Series in Computer Science. Prentice Hall, 1994.\n\n\\bibitem{TaylorP:intso}\nPaul Taylor.\n\\newblock Intuitionistic sets and ordinals.\n\\newblock {\\em Journal of Symbolic Logic}, 61:705--744, 1996.\n\n\\bibitem{TaylorP:prafm}\nPaul Taylor.\n\\newblock {\\em Practical Foundations of Mathematics}.\n\\newblock Number~59 in Cambridge Studies in Advanced Mathematics. Cambridge\n  University Press, 1999.\n\n\\end{thebibliography}\n\n\n%=======================================================================\n\n\\end{document}\n\n\n", "meta": {"hexsha": "c7c460ec046f14df0ab285edc30cd0d42b0c8a1a", "size": 32896, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Course/CSLogic/boxuser.tex", "max_stars_repo_name": "AixMoon/LearnigRepo", "max_stars_repo_head_hexsha": "ee98fb352735e2b4f97304847b6c0311bc30195e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2020-05-02T20:06:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-24T10:01:29.000Z", "max_issues_repo_path": "Course/CSLogic/boxuser.tex", "max_issues_repo_name": "AixMoon/LearnigRepo", "max_issues_repo_head_hexsha": "ee98fb352735e2b4f97304847b6c0311bc30195e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Course/CSLogic/boxuser.tex", "max_forks_repo_name": "AixMoon/LearnigRepo", "max_forks_repo_head_hexsha": "ee98fb352735e2b4f97304847b6c0311bc30195e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-06-04T04:29:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-15T08:15:01.000Z", "avg_line_length": 34.0186142709, "max_line_length": 79, "alphanum_fraction": 0.5483037451, "num_tokens": 12488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.3477776834764115}}
{"text": "\\documentclass[11pt]{article}\n\\usepackage{xcolor}\n\\usepackage{bbm}\n\\usepackage{amsmath}\n\\usepackage{hyperref}\n\\DeclareMathOperator*{\\argmin}{arg\\,min}\n\\hypersetup{\n    colorlinks=true,\n    linkcolor=blue,\n    filecolor=magenta,      \n    urlcolor=violet,\n}\n\\newcommand{\\numpy}{{\\tt numpy}}    % tt font for numpy\n\n\\topmargin -.5in\n\\textheight 9in\n\\oddsidemargin -.25in\n\\evensidemargin -.25in\n\\textwidth 7in\n\n\\begin{document}\n\n% ========== Edit your name here\n\\title{SAILON Evaluation Metrics: Rigorously Defined}\n\\author{Sam Showalter}\n\\maketitle\n\n\\medskip\n\\section{Experimental Setup}\n\nThe SAILON evaluation system is abstractly defined as follows. \\textit{A priori}, a number of trials $T$ is defined, where each trial $t \\in T$ contains a single batch $b$ of $n$ samples. The total number of samples across the entire evaluation is denoted $Tn = N$. \n\nEach sample $\\mathbf{x}$ is a video of one of $k$ possible actions, or an action unseen during training time as denoted the $k + 1$ novel class. These samples are independently fed through a network and novelty detection system, considered jointly in this setup as $f_\\theta(.)$. In this setting, the output for any sample $\\mathbf{x_i}$ fed through $f_\\theta(.)$ is a scalar label $y_{\\theta i} \\in \\{0,1, ... k, k+1\\}$ where $k + 1$ represents a novel input sample.\n\nIn addition, there is a third metric set \\textit{a-priori} on the trials of the evaluation. At an unspecified trial $t_a \\in T$, the presence of novel instances begins and will remain for all subsequent trials. Before trial $t_a$, no novel samples are present, though the model $f_\\theta(.)$ can at any time predict $y_{\\theta i} = k + 1$. \n\nThe evaluation is run sequentially in a batch-wise fashion over trials. Accordingly, $\\mathbf{x}_{ti}$ represents the $i^{th}$ sample of the $t^{th}$ batch, and $y_{ti}$ represents the corresponding label. In addition, a baseline model $f_\\phi(.)$, whose predictions are denoted $\\hat{y}_{\\phi ti} \\in \\{0, 1, ... , k\\}$, cannot predict novelty and is often referred to as the \\textbf{baseline model}. All evaluation metrics are determined based on the relationship of predicted labels $\\hat{y}_{\\theta ti}$ to the ground-truth labels $y_{ti}$ of the evaluation and to the baseline predictions $\\hat{y}_{\\phi ti}$.\n\nImplicitly, if a given trial $t$ at least one sample in its batch $b_t$ was predicted to be novel ($\\hat{y}_{\\theta ti} = 1$), the trial itself is tagged with binary label 1 for its batch $\\hat{l}_t = 1$, signifying the agent believes novelty has started. After the first trial possessing novelty occurs, all future trials will be given a novelty label = 1 regardless of the predictions in its batch. The ground truth labels across trials is denoted $l_t$\n\n\n\\section{Trial-based Evaluation Metrics: Detection Performance}%\n\\label{sec:trial_based_evaluation_metrics}\n\nFirst, trial-based evaluation metrics are evaluated, with an optimal performance defined as predicting novelty for the first time in batch $b_{ta}$ belonging to trial $t_a \\in T$. Failure modes in terms of false positives and false negatives are defined as follows, where $t$ represents the $t^{th}$ trial and $\\hat{l}_t$ represents the binary label defining if any samples in batch $b_t$ were classified as novel.\n\n\\begin{equation}\n    \\begin{aligned}\n      TP &= \\hat{l}_t = l_t \\\\\n      FP &= \\hat{l}_t > l_t \\\\\n      FN &= \\hat{l}_t < l_t\n    \\end{aligned}\n\\end{equation}\n\nThese metrics are then utilized to generate slightly more sophisticated evaluation metrics across trials, including:\n\n\\begin{equation}\n    \\begin{aligned}\n      \\text{Correctly Detected Trials (CDT)} &= \\sum^{T}_{t = 1} \\mathbbm{1}( (FP_{t} = 1) \\ \\& \\ (TP_t >= 1)) \\\\\n      \\text{Trial Failures} &= (t_a - \\argmin_t(l_t = 1)) \\\\\n      \\text{False Positive Trial \\%} &= \\frac{FP}{T} \\\\\n      \\text{False Negative Trial \\%} &= \\frac{FN}{T}\n    \\end{aligned}\n\\end{equation} \n\nIn summary, the primary goal of this family of evaluation metrics is to minimize the number of false positives. This is far more important to PAR than the other metrics. Trial Failures exclusive looks at how many trials too early you declared novelty.\n\n\\section{Sample-based Evaluation Metrics: Reaction Performance}%\n\\label{sec:sample_based_evaluation_metrics_reaction_performance}\n\nThe next family of evaluation metrics concerns sample-based evaluation metrics. These metrics conducted over batches (unless specified otherwise) and then averaged. The evaluation metrics are defined below.\n\n\n\\begin{equation}\n    \\begin{aligned}\n      FP &= (\\hat{y}_{\\theta ti} = k+1) \\ \\& \\ (y_{ti} \\neq k+1)) \\\\\n      FN &= (\\hat{y}_{\\theta ti} \\neq k+1) \\ \\& \\ (y_{ti} = k+1))\n    \\end{aligned}\n\\end{equation}\n\nThese can be computed in any way, but in particular there are several metrics that compare these FP, FN values in the pre- and post-novelty regime. The formulas are the same for the baseline model, but $\\theta$ is replaced by $\\phi$.\n\n\\begin{equation}\n    \\begin{aligned}\n      \\text{Accuracy} &= \\frac{1}{T} \\sum^{T}_{t=1} \\frac{1}{n} \\sum^{n}_{i=1} \\mathbbm{1}(\\hat{y}_{\\theta ti} = y_{ti}) \\\\\n      \\text{Baseline Accuracy} &= \\frac{1}{T} \\sum^{T}_{t=1} \\frac{1}{n} \\sum^{n}_{i=1} \\mathbbm{1}(\\hat{y}_{\\phi ti} = y_{ti}) \\\\\n    \\end{aligned}\n\\end{equation}\n\nPer trial asymptotic performance is defined as the ``measure in the change in accuracy over post-novelty rounds''. No notation or formulae of any kind accompany this statement. However, some additional metrics include:\n\n\\begin{equation}\n    \\begin{aligned}\n      \\text{Novelty Response Performance (NRP)} &= \\frac{( \\text{Accuracy} | t \\geq t_a)}{( \\text{Accuracy} | t < t_a)}  \\\\\n      \\text{Overall Performance Task Improvement (OPTI)} &= \\frac{( \\text{Accuracy} | t \\geq t_a)}{( \\text{Baseline Accuracy} | t \\geq t_a)} \\\\\n      \\text{Asymptotic Performance Task Improvement (APTI)} &= \\frac{( \\text{Accuracy per Trial} | t \\geq t_a)}{( \\text{Baseline Accuracy per trial} | t \\geq t_a)} \\\\\n      \\text{Area Under Activity Monitor Operating Characteristic (AUAMOC)} &= \\text{AUROC of TP and FP}\n    \\end{aligned}\n\\end{equation}\n\nIn words, \\textbf{NRP} is the ratio of the average batch accuracy in batches after novelty over the average batch accuracy in batches before novelty - we want this as high as possible. \\textbf{OPTI} is the ratio of post-novelty accuracy in our model over post-novelty accuracy of the baseline. We also want this to be as high as possible. \\textbf{APTI} is a more granular \\textbf{OPTI} that makes use of per-trial differences. \\textbf{AUAMOC} is a simple AUROC curve plotted for global TP and FP, \\textbf{threshold based on anomaly score} \n\n\n\\section{Oustanding items}%\n\\label{sec:oustanding_items}\n\n\\begin{enumerate}\n  \\item Top-k classification with anomaly score not a probability - how do they intend to do this?\n\\end{enumerate}\n\n\n\n\\end{document}\n", "meta": {"hexsha": "2bac9add388b21bfe770639a35ae87466540fd4b", "size": 6841, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "summaries/summ_1/eval_mets.tex", "max_stars_repo_name": "SamShowalter/CS272-NLP", "max_stars_repo_head_hexsha": "6914064018fbcd416c2f9b24ee105319d02b3cb2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "summaries/summ_1/eval_mets.tex", "max_issues_repo_name": "SamShowalter/CS272-NLP", "max_issues_repo_head_hexsha": "6914064018fbcd416c2f9b24ee105319d02b3cb2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "summaries/summ_1/eval_mets.tex", "max_forks_repo_name": "SamShowalter/CS272-NLP", "max_forks_repo_head_hexsha": "6914064018fbcd416c2f9b24ee105319d02b3cb2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 60.0087719298, "max_line_length": 614, "alphanum_fraction": 0.7159771963, "num_tokens": 1900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3477776760270927}}
{"text": "\\chapter{Background}\n\\label{ch:02-background}\n\nWe can make human language manageable to computers by using a sort of different methods and techniques. This is the bread and butter of any NLP researcher. Here, following the NLP community, we will focus only in the techniques derived from the machine learning field. In this chapter, we will present some abstract machine learning models follow by some applications in NLP. \n\n\\section{Machine Learning}\n\n\\textit{Machine learning} is the branch of computer science that deals with programs that can improve with experience (i. e., learn). Machine learning is divided into three main subareas: \\textit{supervised learning}, \\textit{reinforcement learning} and \\textit{unsupervised learning}.\n\nWe will work with supervised learning only. In this setting, we assume that the process of interest is defined by an unknown function $g:X\\rightarrow Y$. We try to approximate $g$ by changing the parameters of a function $f$ through an optimization process. The optimization is done by defining an \\textit{error function} that evaluates how well $f$ approximates $g$ in the part of $g$ that we have access: the training data $D = \\{(\\vect{x}^{(1)}, \\vect{y}^{(1)}), \\dots ,(\\vect{x}^{(N)}, \\vect{y}^{(N)})\\}$ (where $g(\\vect{x}^{(i)})=\\vect{y}^{(i)}$).\n\n\n$f$ can be a function from any family of models. One family that is having a lot of success for language tasks is the \\textit{neural network} family.\n\n\\section{Neural Networks}\n\nA neural network is a non-linear function $f(\\vect{x}; \\vect{\\theta})$. It is defined by a collection of parameters $\\vect{\\theta}$ and a collection of non-linear transformations. It is usual to represent $f$ as a compositions of functions:\n\n\\begin{align}\nf(\\vect{x}; \\vect{\\theta}) &= f^{(2)}(f^{(1)}(\\vect{x}; \\vect{W}_1, \\vect{b}_1); \\vect{W}_2, \\vect{b}_2)\\\\\n&= softmax(\\vect{W}_2 (\\sigma(\\vect{W}_1\\vect{x} + \\vect{b}_1)) + \\vect{b}_2)\n\\end{align}\n\n\nThe output of these intermediary functions are referred as \\textit{layers}. So in the example above, $\\vect{x}$ (the output of the identity function) is the \\textit{input layer}, $f^{(1)}(\\vect{x}; \\vect{W}_1, \\vect{b}_1)$ is the \\textit{hidden layer} and $f^{(2)}(f^{(1)}(\\vect{x}; \\vect{W}_1, \\vect{b}_1); \\vect{W}_2, \\vect{b}_2)$ is the \\textit{output layer}. Since each layer is a vector, we normally speak about the \\textit{dimension} of a layer. For historical reasons we also say that each entry on a layer is a \\textit{node} or a \\textit{neuron}.  Models with a large number of hidden layers are called \\textit{deep models}, for this reason the name \\textit{deep learning} is used.  \n\n\\par A neural network is a function approximator: it can approximate any Borel measurable function from one finite dimensional space to another with any desired nonzero amount of error. This theoretical result is know as the \\textit{universal approximation theorem} \\cite{Cybenko}. Without entering in the theoretical concepts, it suffice to note that the family of Borel mensurable functions include all continuous functions on a closed and bounded subset of $\\mathbb{R}^n$.\n\n\n\nDifferent deep learning architectures are used in NLP: \\textit{convolutional architectures} have a good performance in tasks were it is required to find a linguistic indicator regardless of its position (e.g., document classification, short-text categorization, sentiment classification, etc); high quality word embeddings can be achieved with models that are a kind of \\textit{feedforward neural network} \\cite{Mikolov23}. But for a variety of works in natural language we want to capture regularities and similarities in a text structure. That is way \\textit{recurrent} and \\textit{recursive} models have been widely used in the field. Here we are focused on generative models and since recurrent models have been producing very strong results for language modeling \\cite{goldberg15}, we will concentrate on them.\n\n\n\\section{Recurrent Neural Network}\n\\label{sec:RNN}\n\n\n\\textit{Recurrent neural network} (RNN) is a family of neural network specialized in sequential data $\\vect{x}^{(1)}, \\dots, \\vect{x}^{(\\tau)}$. As a neural network, a RNN is a parametrized function that we use to approximate one hidden function from the data. What makes RNN unique is a recurrent definition of one of its hidden layer:\n\n\\begin{equation}\n\\vect{h}^{(t)} = g(\\vect{h}^{(t-1)}, \\vect{x}^{(t)}; \\vect{\\theta})\n\\end{equation}\n\n$\\vect{h}^{(t)}$ is called \\textit{state}, \\textit{hidden state}, or \\textit{cell}.\n\n\n\\par This recurrent equation can be unfolded for a finite number of steps $\\tau$. For example, when $\\tau =3$:\n\n\\begin{align}\n\\vect{h}^{(3)}& = g(\\vect{h}^{(2)}, \\vect{x}^{(3)}; \\vect{\\theta})\\\\\n & = g(g(\\vect{h}^{(1)}, \\vect{x}^{(2)}; \\vect{\\theta}), \\vect{x}^{(3)}; \\vect{\\theta})\\\\\n & = g(g(g(\\vect{h}^{(0)}, \\vect{x}^{(1)}; \\vect{\\theta}), \\vect{x}^{(2)}; \\vect{\\theta}), \\vect{x}^{(3)}; \\vect{\\theta})\\\\\n\\end{align}\n\nUsing a concrete example consider the following classification model define by the equations:\n\n\\begin{equation}\nf(\\vect{x}^{(t)}, \\vect{h}^{(t-1)}; \\vect{V}, \\vect{W}, \\vect{U}, \\vect{c}, \\vect{b}) = \\vect{\\hat{y}}^{(t)}\n\\end{equation}\n \\vspace{0.2cm}\n\\begin{equation}\n\\vect{\\hat{y}}^{(t)} = softmax(\\vect{V} \\vect{h}^{(t)} + \\vect{c})\n\\end{equation}\n\\vspace{0.2cm}\n \\begin{equation}\n\\vect{h}^{(t)} = g(\\vect{h}^{(t-1)}, \\vect{x}^{(t)}; \\vect{W},\\vect{U}, \\vect{b})\n\\end{equation}\n\\vspace{0.2cm}\n\\begin{equation}\n\\vect{h}^{(t)} = \\sigma(\\vect{W} \\vect{h}^{(t-1)} + \\vect{U} \\vect{x}^{(t)} + \\vect{b})\n\\end{equation}\n\n\nThis kind of model can create an output $\\vect{\\hat{y}}^{(t)}$ at each time $t$, or the model can produce a single output $\\vect{\\hat{y}}$ after processing an entire input sequence. This choice depends on the learning problem that is being modeled.\n\n\nWith the model's prediction at hand, we can use a loss function (like cross entropy for the classification problem) and apply the back-propagation algorithm to optimize the model. These models look complex, but it quite straightforward to compute the gradients \\cite[p.~374]{DeepLearningbook}.\n\nAlthough this kind of deep learning model is very useful, it presents a severe flaw. When computing the gradients there is a lot of repeated matrix multiplication using the recurrent weight matrix (in the example above, the matrix $\\vect{W}$). Depending on some configurations of this matrix \\textit{the gradients may vanish or explode exponentially with respect to the number of time steps}.\n\nThus, handing long-term dependencies became a problem when using RNNs. Different solutions were proposed, the most effective results came from some modifications of this model. We will present the two most famous modifications: \\textit{the gated recurrent unit} and \\textit{the long short-term memory}. \n\n\n\\section{Gated Recurrent Unit}\n\\label{sec:GRU}\n\nTo capture long-term dependencies on a RNN  the authors of the paper \\cite{ChungGCB14}  proposed a new architecture called \\textit{gated recurrent unit} (GRU). This model was constructed to make each hidden state  $\\vect{h}^{(t)}$ to adaptively capture dependencies of different time steps. It work as follows, at each step $t$ one candidate for hidden state is formed:\n\n\\begin{equation}\n\\vect{\\widetilde{h}}^{(t)} = tahn(\\vect{W} (\\vect{h}^{(t-1)} \\odot  \\vect{r}^{(t)}) + \\vect{U} \\vect{x}^{(t)} + \\vect{b})\n\\end{equation}\n\nwhere $\\vect{r}^{(t)}$ is a vector with values in $[0, 1]$ called a \\textit{reset gate}, i.e.,  a vector that at each entry outputs the probability of reseting the  corresponding entry in the previous hidden state $\\vect{h}^{(t-1)}$. Together with $\\vect{r}^{(t)}$ we define an \\textit{update gate}, $\\vect{u}^{(t)}$. It is also a vector with values in $[0, 1]$. Intuitively we can say that this vector decides how much on each dimension we will use the candidate update. Both $\\vect{r}^{(t)}$ and $\\vect{u}^{(t)}$ are defined by $\\vect{h}^{(t-1)}$ and $\\vect{x}^{(t)}$; they also have specific parameters:\n\n\\begin{equation}\n\\vect{r}^{(t)} = \\sigma(\\vect{W}_{r} \\vect{h}^{(t-1)} + \\vect{U}_{r} \\vect{x}^{(t)} + \\vect{b}_{r})\n\\end{equation}\n\n\n\\begin{equation}\n\\vect{u}^{(t)} = \\sigma(\\vect{W}_{u} \\vect{h}^{(t-1)} + \\vect{U}_{u} \\vect{x}^{(t)} + \\vect{b}_{u})\n\\end{equation}\n\nAt the end the new hidden state $\\vect{h}^{(t)}$ is defined by the recurrence:\n\n\\begin{equation}\n\\vect{h}^{(t)} = \\vect{u}^{(t)} \\odot \\vect{\\widetilde{h}}^{(t)} + (1 - \\vect{u}^{(t)}) \\odot \\vect{h}^{(t-1)} \n\\end{equation}\n\nNote that the new hidden state combines the candidate hidden state $\\vect{\\widetilde{h}}^{(t)}$ with the past hidden state $\\vect{h}^{(t-1)}$ using both $\\vect{r}^{(t)}$ and $\\vect{u}^{(t)}$ to adaptively copy and forget information.\n\n\\section{Long Short-Term Memory}\n\\label{sec:LSTM}\n\n\\textit{Long short-term memory} (LSTM) is one of the most applied versions of the RNN family of models. Historically it was developed before the GRU model, but conceptually we can think in the LSTM as an expansion of the model presented in the last session. Because of notation differences they can look different. LSTM is also based on parametrized gates; in this case three: the \\textit{forget gate}, $\\vect{f}^{(t)}$, the \\textit{input gate}, $\\vect{i}^{(t)}$, and the \\textit{output gate}, $\\vect{o}^{(t)}$. The gates are defined only by $\\vect{h}^{(t-1)}$ and $\\vect{x}^{(t)}$ with specific parameters:\n\n\n\\begin{equation}\n\\vect{f}^{(t)} = \\sigma(\\vect{W}_{f} \\vect{h}^{(t-1)} + \\vect{U}_{f} \\vect{x}^{(t)} + \\vect{b}_{f})\n\\end{equation}\n\n\\begin{equation}\n\\vect{i}^{(t)} = \\sigma(\\vect{W}_{i} \\vect{h}^{(t-1)} + \\vect{U}_{i} \\vect{x}^{(t)} + \\vect{b}_{i})\n\\end{equation}\n\n\\begin{equation}\n\\vect{o}^{(t)} = \\sigma(\\vect{W}_{o} \\vect{h}^{(t-1)} + \\vect{U}_{o} \\vect{x}^{(t)} + \\vect{b}_{o})\n\\end{equation}\n\nIntuitively $\\vect{f}^{(t)}$ should control how much informative will be discarded, $\\vect{i}^{(t)}$ controls how much information will be updated, and $\\vect{o}^{(t)}$ controls how munch each component should be outputted. A candidate cell, $\\tilde{\\vect{c}}^{(t)}$ is formed:\n\n\\begin{equation}\n\\tilde{\\vect{c}}^{(t)} = tahn(\\vect{W} \\vect{h}^{(t-1)} + \\vect{U} \\vect{x}^{(t)} + \\vect{b})\n\\end{equation}\n\nAnd a new cell $\\vect{c}^{(t)}$ is formed by forgetting some information of the previous cell $\\tilde{\\vect{c}}^{(t-1)}$ and by adding new values from $\\tilde{\\vect{c}}^{(t)}$ (scaled by the input gate)\n\n\\begin{equation}\n\\vect{c}^{(t)} = \\vect{f}^{(t)} \\odot \\vect{c}^{(t-1)} + \\vect{i}^{(t)} \\odot \\tilde{\\vect{c}}^{(t)}\n\\end{equation}\n\nThe new hidden state, $\\vect{h}^{(t)}$, is formed by filtering $\\vect{c}^{(t)}$:\n\n\\begin{equation}\n\\vect{h}^{(t)} = \\vect{o}^{(t)} \\odot tanh(\\vect{c}^{(t)})\n\\end{equation}\n\nUntil now we have presented general deep learning theory, now we will focus on the specificities of these models applied to natural language problems.\n\n\n\\section{Language model}\n\nWe call \\textit{language model} a probability distribution over sequences of tokens in a natural language.\n\n\\[\nP(x_1,x_2,x_3,x_4) = p\n\\]\n\nThis model is used for different NLP tasks such as speech recognition, machine translation, text auto-completion, spell correction, question answering, summarization and many others.\n\nThe classical approach to a language model was to use the chain rule of probability and a Markovian assumption, i.e., for a specific $n$ we assume that:\n\n\\begin{equation}\nP(x_1, \\dots, x_T) = \\prod_{t=1}^{T} P(x_t \\vert x_1, \\dots, x_{t-1}) = \\prod_{t=1}^{T} P(x_{t} \\vert x_{t - (n+1)}, \\dots, x_{t-1})\n\\end{equation} \n\n\nThis gave raise to models based on $n$-gram statistics. The choice of $n$ yields different models; for example, the \n\\textit{unigram} language model ($n=1$) is defined as: \n\\begin{equation}\nP_{uni}(x_1, x_2, x_3, x_4) = P(x_1)P(x_2)P(x_3)P(x_4)\n\\end{equation}\n\nwhere $P(x_i) = count(x_i)$ and $count$ is a function that counts tokens occurrence in a corpus.\\\\\n\nSimilarly the \\textit{bigram} language model ($n=2$) is defined as: \n\\begin{equation}\nP_{bi}(x_1,x_2,x_3,x_4) = P(x_1)P(x_2\\vert x_1)P(x_3\\vert x_2)P(x_4\\vert x_3)\n\\end{equation} \nwhere\n\\begin{equation}\nP(x_i\\vert x_j) = \\frac{count(x_i, x_j)}{count(x_j)}\n\\end{equation} \n\nWith these basic statistics we can already define useful language models. It is observed that higher $n$-grams yields better performance. This comes with a price though, higher $n$-grams requires great amounts of memory \\cite{Heafield}. For this motive $n$-grams based language models that are trained on large corpora uses at most $5$-grams. \n\nSince \\cite{Mikolov11} the landscape has change, instead of using one approach that is specific for the language domain, we can use a general model for sequential data prediction, a RNN. The RNN's ability to deal with unrestricted size sequence input permits to abandon the $n$-gram model's restricted context assumption.\n\nTo understand the language model task as a machine learning task, some details should be clear. \n\nFirst, the learning task is to estimate the probability distribution \n\n\\begin{equation}\n\\label{languagedistri}\nP(x_{n} = \\text{word}_{j^{*}} | x_{1}, \\dots ,x_{n-1})\n\\end{equation}\n\nfor any $(n-1)$-sequence of words $x_{1}, \\dots ,x_{n-1}$.\n\n\nSecond, the function $f$ being used to approximate \\ref{languagedistri} is trained on a corpus in the following way: each word $x_t$ of the corpus will be used as input to $f$ (in the form of an one-hot vector), and the immediate subsequent word, say $x_{t+1}$, will be used as a target. The training is done by minimizing the cross entropy loss between the model's output and the probability distribution given by the target.\n\nOne example is in order. Suppose our corpus $\\corpus$ is compose only by the lines below:\n\n\\begin{quote}\nYes, here we go again, give you more, nothing lesser\\\\\nBack on the mic is the anti-depressor\\\\\nAd-Rock, the pressure, yes, we need this\\\\\nThe best is yet to come, and yes, believe this\\\\\n\\end{quote}\n\n\nFrom this corpus we can construct a vocabulary list $\\Vocab$ as follows: after preprocessing the text we create a list of the most frequent words (in this case we can take all words) with the size $V$ (here $V=27$). Hence, we can treat each word in the text either by an index referring to the word position on $\\Vocab$ or as a one-hot vector that codifies this index (e.g., \"the\" would be identified with $0$, \"yes\" with $1$, \"we\" with $2$, and so on).\n\nThen, the dataset is the collection of words \n\\[\nD = \\{(<eos>, \\text{Yes}), (\\text{Yes}, \\text{here}), (\\text{here}, \\text{we}),\\dots,(\\text{believe}, \\text{this}), (\\text{this}, <eos>)\\}\n\\]\nwhere $<eos>$ is the \"end of sentence\" token (also a member of $\\Vocab$).\n\nA simple recurrent language model $f(\\vect{x}^{(t)}, \\vect{\\theta})$ is defined by the following equations:\n\n\\begin{equation}\n\\vect{e}^{(t)} = \\vect{E}\\vect{x}^{(t)}\n\\end{equation}\n\\vspace{0.2cm}\n\\begin{equation}\n\\vect{h}^{(t)} = \\sigma(\\vect{W}\\vect{h}^{(t-1)}+ \\vect{U}\\vect{e}^{(t)}+ \\vect{b})\n\\end{equation}\n\\vspace{0.2cm}\n\\begin{equation}\nf(\\vect{x}^{(t)}, \\vect{\\theta}) = \\vect{\\hat{y}}^{(t)} = softmax(\\vect{V}\\vect{h}^{(t)} + \\vect{c})\n\\end{equation}\n\nwhere $\\vect{E} \\in \\mathbb{R}^{d,V}$ is the matrix of word embeddings, $\\vect{x}^{(t)} \\in \\mathbb{R}^{V}$ is one-hot word vector at time step $t$, $\\vect{y}^{(t)} \\in \\mathbb{R}^{V}$ is the ground truth at time step $t$ (also a one-hot word vector) and $d$ is the size of the word embeddings.\n\nFor each word $x_t$ let $j_t$ be the index of the subsequent word, so at each time $t$ the point-wise loss is:\n\n\\begin{align}\n\\label{lossCE}\nL^{(t)}(\\vect{\\theta}) &= CrossEntropy(\\vect{y}^{(t)},\\vect{\\hat{y}}^{(t)})\\\\\n    &= - \\log({\\vect{\\hat{y}}^{(t)}}_{j_t})\\\\\n        &= - \\log P(x_{t+1} = \\text{word}_{j_t}|x_{1}, \\dots, x_{t})\\\\\n        &= - \\log P(x_{t+1}|x_{1}, \\dots, x_{t})\n\\end{align}\n\nThe loss $L$ is the mean of all point-wise losses\n\n\\begin{equation}\nL(\\vect{\\theta})=\\frac{1}{T}\\sum_{t=1}^{T}L^{(t)}(\\vect{\\theta})\n\\end{equation}\n\nWith the loss function defined, we apply some optimization algorithm like \\textit{stochastic gradient descent} to choose the optimal parameters for the language model:\n\n\\begin{equation}\n\\vect{\\theta}^{*} = \\argmin_{\\vect{\\theta}} L(\\vect{\\theta})\n\\end{equation}\n\nBecause of the historical connections with information theory, the \\textit{perplexity} ($PP$) metric is often used to evaluate a language model. This metric can be thought as the weighted average branching factor of a language.\n\nGiven $\\corpus = x_1, x_2, \\dots, x_T$, we define the perplexity of $\\corpus$ ($PP(\\corpus)$) as:\n\n\\begin{align}\nPP(\\corpus) &= P(x_1, x_2, \\dots, x_T)^{-\\frac{1}{T}}\\\\\n      &= \\sqrt[T]{\\frac{1}{P(x_1, x_2, \\dots, x_T)}}\\\\\n      &= \\sqrt[T]{\\prod_{i=1}^{T}\\frac{1}{P(x_i \\vert x_1,\\dots, x_{i-1})}}\n\\end{align}\n\nUsing \\ref{lossCE} we can relate cross entropy loss and perplexity:\n\n\\begin{align}\n        L(\\vect{\\theta}) &=\\frac{1}{T} \\sum_{t=1}^{T} L^{(t)}(\\vect{\\theta})\\\\\n          &=\\frac{1}{T} \\sum_{t=1}^{T} - \\log P(x_{t+1}|x_{1}, \\dots, x_{t})\\\\\n          &=\\frac{1}{T} \\sum_{t=1}^{T} \\log ((\\frac{1}{P(x_{t+1}|x_{1}, \\dots, x_{t})})\\\\\n          &= \\log\\left( \\sqrt[T]{\\prod_{i=1}^{T}\\frac{1}{P(x_i \\vert x_1,\\dots, x_{i-1})}} \\right)\\\\\n          &= \\log(PP(\\corpus))\n\\end{align}\n\nHence,\n\n\\begin{equation}\n2^{L(\\vect{\\theta})} = PP(\\corpus)\n\\end{equation}\n\nThus, by finding the parameters that minimize the cross entropy error we are also minimizing the perplexity of the language model. \n\n\\section{Sequence-to-Sequence}\n\\label{sec:Seq2seq}\n\nThere is one powerful application of RNN based language model. The authors from \\cite{Sustskever} used two RNNs to create an end-to-end translation model that is now know as \\textit{the encoder-decoder} or \\textit{the sequence-to-sequence} (seq2seq) architecture. This architecture is define as follows: let $\\vect{x}^{(1)}, \\dots, \\vect{x}^{(n)}$ be a source sentence in the one-hot representation,  let $\\vect{y}^{(1)}, \\dots, \\vect{y}^{(m)}$ be the target sentence also in the one-hot format. $f_{enc}$ (the \\textit{encoder}) is a RNN with the sole purpose of creating a vector representation of input language's sequences. $f_{dec}$ (the \\textit{decoder}) is a language model for the target language. These models are trained together mapping source sentences to target sentences.\n\nFor example, suppose the training pair $(\\vect{x}^{(1)}, \\dots, \\vect{x}^{(n)}, \\vect{y}^{(1)}, \\dots, \\vect{y}^{(m)})$ is (\"Nas tardes de fazenda há muito azul demais\", \"In the farm’s afternoons there is too much blue\"). Here we want the model to translate one Portuguese sentence to an English one. We first encode the Portuguese sentence in the vector $\\vect{s}$, i.e.,\n\n\\begin{equation}\n\\vect{s} = f_{enc}(\\vect{x}^{(n)}, \\vect{h}^{(n-1)})\n\\end{equation}\n\nThen using the control English sentence as a target, at each time $t$ we compute the cross entropy error between the decoder prediction $f_{dec}(\\vect{y}^{(t)}, \\vect{\\tilde{h}}^{(t-1)})$ and the target $\\vect{y}^{(t+1)}$ ($\\vect{y}^{(0)}$ is the $<eos>$ token). The decoder uses the vector representation of the source sentence $\\vect{s}$ as an initial hidden state (i.e., $\\vect{\\tilde{h}}^{(0)} = \\vect{s}$). The goal of this model is to to approximate the probability distribution over the tokens from the target language given the sentence of the source language, i.e.,\n\n\\begin{equation}\n\\vect{\\tilde{h}}^{(t)} = f_{dec}(\\vect{y}^{(t)}, \\vect{\\tilde{h}}^{(t-1)})\n\\end{equation}\n\n\\begin{equation}\n\\label{decpred}\np(y_t | y_1, \\dots, y_{t-1}, x_1, \\dots, x_{n}) = softmax(\\vect{W}_{s}  \\vect{\\tilde{h}}^{(t)} + \\vect{b}_s)\n\\end{equation}\n\nOne limitation of this architecture is that the source sentence, in some cases, has more features than the decoder embedding $\\vect{s}$ can properly summarize. To address that some attention mechanisms were introduced.\n\n\\section{Attention}\n\\label{sec:Attention}\n\nThe attention-based models are models built on top of the seq2seq architecture. The encoding part continues the same as before, but now at each time $t$ a context vector $\\vect{c}^{(t)}$ is defined to capture relevant source-side information to help the prediction of the current target word $\\vect{y}^{(t)}$. Once $\\vect{c}^{(t)}$ is constructed the attention hidden state is defined as:   \n\n\\begin{equation}\n\\vect{\\tilde{h}}^{(t)} = tahn(\\vect{W}_c[\\vect{c}^{(t)};\\vect{h}^{(t)}])\n\\end{equation}\n\nWith the attention hidden state defined, the model's prediction is the same as the one defined in \\ref{decpred}.\n\nThe core of this technique is the definition of $\\vect{c}^{(t)}$. There are different strategies available, here we will focus only on one: \\textit{global attention}.\n\nLet $\\vect{a} \\in \\mathbb{R}^{m,n}$. We will use this matrix as an alignment matrix, i.e., at the end of the training $\\vect{a}_{ts}$ should reflect the probability of the source representation $\\vect{h}^{(s)}$ be relevant for the output $\\hat{y}^{(t)}$. We define $\\vect{a}_{ts}$ as\n\n\n\\begin{equation}\n\\vect{a}_{ts} = \\frac{exp(score(\\vect{\\tilde{h}}_t,\\vect{h}_s))}{\\sum_j exp(score(\\vect{\\tilde{h}}_t,\\vect{h}_j))}\n\\end{equation}\n\nWhere $score$ is a content-based function that can have different implementations: \n\n\\begin{equation}\nscore(\\vect{\\tilde{h}}_t,\\vect{h}_s) = \\begin{cases}\n\\vect{\\tilde{h}}_t ^{\\top}\\vect{h}_s\\\\\n\\vect{\\tilde{h}}_t ^{\\top}\\vect{W}_a \\vect{h}_s\\\\\n\\vect{v}_a ^{\\top}tahn(\\vect{W}_a[\\vect{\\tilde{h}}_t;\\vect{h}_s])\\\\\n\\end{cases}\n\\end{equation}\n\nAt the end, a global context vector $\\vect{c}^{(t)}$ is computed as the weighted average, according to $\\vect{a}_t$ over all source states:\n\n\\begin{equation}\n\\vect{c}^{(t)} = \\sum_{s} \\vect{a}_{ts}\\vect{h}^{(s)}\n\\end{equation}\n\n\n\n", "meta": {"hexsha": "c9d1d8a38f1e9a7bee255501fa1df70b9d4dd285", "size": 21572, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/chapters/ch02-background.tex", "max_stars_repo_name": "felipessalvatore/quali", "max_stars_repo_head_hexsha": "500dc69a10ccd0320cc90c8c51dc13bb8097584e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/chapters/ch02-background.tex", "max_issues_repo_name": "felipessalvatore/quali", "max_issues_repo_head_hexsha": "500dc69a10ccd0320cc90c8c51dc13bb8097584e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chapters/ch02-background.tex", "max_forks_repo_name": "felipessalvatore/quali", "max_forks_repo_head_hexsha": "500dc69a10ccd0320cc90c8c51dc13bb8097584e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 61.8108882521, "max_line_length": 815, "alphanum_fraction": 0.6913128129, "num_tokens": 6812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629465, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.34754702457537057}}
{"text": "\\section{Learning Motion Primitive using Kinesthetic Demonstrations}\n\\label{sec:Learning motion primitive}\nThe main idea of the work is to infer the relevant set of features,\nwhich describe the demonstrated motion primitive.\nBased on the learnt relevant features, during the execution phase \nthe robot tries to predict the goal of the motion primitive, starting \nfrom a new initial condition.\n\nThe demonstrations consist of recording two  states of the world\ncalled as the start state and the end state.\nSo each demonstrations have 2 snapshots of the world in the initial state and the final state.\nBased on these snapshots we try to infer the intent of the demonstrations. \n\nThe motion primitive in our representation consist of pre-conditions and the post-conditions.\nThe execution of each motion primitive depends on the features used to explain it.\nEach motion primitive is defined by a set of features which are a subset of the complete feature space, \nwhich are also relevant for the robot to execute the respective motion primitive.\n\n\\subsection{Features}\nFeatures are the basic building block, which are used to describe a motion primitive.\nA Feature $f$ can be defined as any quantitative parameter of the world $W$.\nFor example the pose of the robot, color of the box, distance between box and robot,\ndisplacement of the tooltip in time.\n\nFeatures are broadly classified into :\n\\begin{enumerate}\n    \\item features describing object properties $f(O)$\n    \\begin{enumerate}\n        \\item features describing robot properties $f(O_r)$ (eg : pose of the robot)\n        \\item features describing environment properties $f(O_e)$(eg: color of the box)\n    \\end{enumerate}\n    \\item features describing relation between object properties $g(O_1, O_2)$\n    \\begin{enumerate}\n        \\item relation between  different objects $g(O_1, O_2)$ (eg : distance between box and robot)\n        \\item relation between same object in time $g(O_{1i}, O_{1f}) $(eg : displacement of tooltip)\n    \\end{enumerate}\n\\end{enumerate}\n\n\nThus the collection of featues can be defined as \n\\begin{equation}\n    \\begin{aligned}\n    F &= f(O) + g(O_1 , O_2) \\\\\n      &= (f(O_r) + f(O_e))  +  (g(O_1, O_2) + g(O_{1i}, O_{1f}))\n    \\end{aligned}\n\\end{equation}\n\nAs explained in section \\ref{sec:Proposed motion primitive}\nthe proposed motion primitive is defined using pre and post conditions of the features.\n\\begin{equation}\n    \\begin{aligned}\n    & \\text{Motion primitive} := (f_s, f_e ) \\\\\n    & where  \\nonumber \\\\ \n    &    f_s = \\text{features in start of demonstrations} \\nonumber\\\\\n    &    f_e = \\text{features in end of demonstrations} \\nonumber\n    \\end{aligned}\n\\end{equation}\n\n\n\n\\subsection{Modelling Motion Primitive}\n\nThe learning problem can be considered as a supervised learning problem, where \nthe model has to learn from the set of demonstrations to predict the output\n$f_e$ when a new input $f_s$ is provided as explained in figure \\ref{model}.\n\\begin{figure}[htp]\n\\centering\n\\includegraphics[scale=0.40]{images/model.png}\n\\caption{Model of motion primitive}\n\\label{model}\n\\end{figure}\n\nWhen the number of training set is limited,learning on\n all the features of the world is not a feasible solutions.\n The approach taken here is to find the relevant features on which the \nlearning can be made most effectively.\nThe prespective adopted in finding the relevant features is that in multiple\ndemonstrations of the same action, some features will share similar values \nin all the demonstrations. Since we are demonstrating a single action\nthere has to be consistency in some features of the action.\nWe need to identify these consistent features and these become the relevant\nfeatures. The consistency increases the relevance of the feature to\nsucessfully predict from new unseen start states.\n\nWe will consider a bivariate probability density function $\\phi_i$  by\nconsidering 2 variables, the value of a feature in start of demonstration and\nits value at the end of the demonstration.\n\nLet $s_i$ be the $i^{th}$ feature of $f_s$, \nand $e_i$ be the $i^{th}$ feature of $f_e$, \\\\\nThe bivariate distribution is given by :\n\\begin{equation}\n    \\phi_i(s_i , r_i) = \\eta_i I_i ( \\lfloor s_i \\rfloor, \\lfloor e_i \\rfloor)\n\\end{equation}\nwhere operator $\\lfloor .  \\rfloor$ is  a quantization operator, that returns the bin unit in \nthe histogram $I_i$, that corresponds to the feature.\n\nThe bi-variate distribution is an appropriate criteria to comment on the\nrelevance of the feature. Using the distribution we can conclude on the\nconvergence of the feature. A feature which has converged, the final values\nwill lie on a straight line in the distribution. If all the final values lie on\na straight line it ensures that whatever maybe the initial value the end values\nalways remain constant. The constant value in all the demonstration concludes\nthat the corresponding feature is relevant with respect to the intent of the\nmotion primitive.\nThis is explained in the figure \\ref{fig:feature distribution}. Higher the\ndegree of convergence, higher the relevance of the feature for the motion\nprimitive.\n\\begin{figure}\n    \\centering\n    \\begin{subfigure}[b]{0.4\\textwidth}\n        \\includegraphics[scale=0.5]{images/arm_joint_1JoinPDF.png} \n        \\caption{Distribution of the feature describing arm joint 1.}\n        \\label{sub fig 1}\n    \\end{subfigure}\n    \\begin{subfigure}[b]{0.4\\textwidth}\n        \\includegraphics[scale=0.5]{images/d_linear_m0_gripperJoinPDF.png} \n        \\caption{Distribution of feature describing distance of object 0 and tooltip. }\n        \\label{sub fig 2}\n    \\end{subfigure}\n    \\caption[Bivariate distribution of features]{An example of bivariate\n        distributions of two features for the \\textit{move} arm relative to object motion\n        primitive.The x-axis is the end values of demonstration while the \n        y-axis is the start value of the demonstration. The dots are the \n        feature values across 12 demonstrations.\n        Based on the distribution in \\ref{sub fig 1}, we can say that\n        there is no certaininty in the end values. This \n        results in lower relvance to the motion primitive . Based on the\n        distribution in \\ref{sub fig 2},we can say that the end states are\n        more concentrated.This ensures that for any value in the start state\n        we are sure that the end values always remain same.\n        This results in a higher relevance with respect to the motion\n    primitive.}\\label{fig:feature distribution}\n\\end{figure}\n\nTo calculate this relevance in the distribution, we use two different \nmeasuring  methods. 1) Entropy 2) Conditional entropy.\nWe compute the \nentropy $H_i$ and conditional entropy $CH_i$ of the bi-variate distribution $\\phi_i(s_i, r_i)$.\n\nEntropy of a discrete random variable is given by,\n\\begin{equation}\n    H(X) = - \\sum P(X) \\log P(X)\n\\end{equation}\n\n\nFor a pair of discrete random variables X and Y, which are co related \nconditional entropy of X given Y $h(X|Y)$ is given by :\n\\begin{equation}\n    H(X|Y) =  - \\sum _{k = -K}^{K} p_X(x|y) p_Y(y|x) \\log \\frac{p_Y(y|x)}{p_X(x|y) p_Y(y|x)}\n\\end{equation}\n\n\nBased on the entropy or conditional entropy we define the model relevance of a motion primitive.\n\\begin{equation}\n    p(f | \\theta ) = \\prod_i e^{-E_i}\n\\end{equation}\nwhere $\\theta$ is the set of all $\\phi$, and $E_i$ can be $H_i$ or $CH_i$\n\n\n\n\\subsection{Expert knowledge base}\nIn our work we create the knowledge base based on expert knowledge of the tasks being performed.\nAn individual subset of feature space $F$ is called as a template $t$. $t_i \\subset F $ .\nFor example the template $t_1$ contains all the features describing the joint angles of the robot, template $t_2$ contains features which describes \ndistance of tooltip to manipulated object.\n\nA collection of the templates is called as a knowledge base $K$.\n\n\n$K = t_1 \\and t_2 \\ldots t_n $\n\n\n\\begin{figure}[htp]\n\\centering\n\\includegraphics[scale=0.50]{images/feature_space.png}\n\\caption[Feature space venn diagram]{Relation between feature space F, knowledge base K and the templates t}\n\\label{}\n\\end{figure}\nThus for each template $t_i$ we have created a low dimension subset of the feature space $F$.\nOur aim is not to find minimum set of features but to find relevant set of features which can describe an action.\n\n\nThe novelty in our approach is the representation of the expert knowledge base.\nThe knowledge base has been structured using the effect metrics. \nThe templates in the knowledge base are organised on the basis of the effect metrics.\nThe structured nature of the knowledge base helps in determining the relevant features with\nless number of demonstrations.\n\\subsubsection{Effect Metrics}\nEffects are defined as changes to the robot-world relationship and/or to positions, orientations\nand states of external objects and robot \\cite{alissandrakis_action_2006}\n\nIn this work we only consider changes to the robot-world relationship and changes to positions, orientations and states of the robot. Based on the orientation and position of the \nrobot in environment 2 types of effect metrics can be used, \\textit{position} and \\textit{orientation}\n\n\\begin{figure}[htp]\n\\centering\n\\includegraphics[scale=0.70]{images/position_effect_metrics.png}\n\\caption[Position effect metrics]{Position effect metrics.\n To measure the change in the relation of change in positions between \nrobot and environment objects \n\\textit{relative displacement, absolute position, relative position and mirror position}\n effect metrics can be used. First row shows the demonstration and\n their resulting effects. The second rows represents the\n corresponding object (in different workspace ) how it needs to be\n moved (from dashed to solid outline) by an imitator to match the \ncorresponding effects according to the metric. The grey triangle\n are superimposed to show the relative position of the objects are \nthe same in final state. \\cite{alissandrakis_action_2006} }\n\\label{position effect metrics}\n\\end{figure}\n\\begin{figure}[htp]\n\\centering\n\\includegraphics[scale=0.70]{images/angular_effect_metrics.png}\n\\caption[Orientation effect metrics]{Orientation effect metrics.  To measure the change in the relation of change in orientation between robot and environment objects \\textit{relative rotation, absolute orientation, relative orientation and mirror rotation} effect metrics can be used.First row shows the demonstration and their resulting effects. The second rows represents the corresponding object (in different workspace) how it needs to be moved. (from dashed to solid outline) by an imitator to match the corresponding effects according to the metric. The guide lines are superimposed to show the relative orientation of the objects are the same in final state. \\cite{ alissandrakis_action_2006}}\n\\label{orientation effect metrics}\n\\end{figure}\n\nThe different position metrics are \n\\begin{itemize}\n\t\\item relative displacement\n\t\\item absolute position\n\t\\item relative position\n\t\\item mirror position\n\\end{itemize}\n\nthe different orientation metrics are \n\\begin{itemize}\n\t\\item relative rotation\n\t\\item absolute orientation\n\t\\item relative orientation\n\t\\item mirror rotation\n\\end{itemize}\n\nDepending on the effect metric the same demonstration can be interpreted as different. \nThe example in figure \\ref{effect metrics} explains this.\n\\begin{figure}[htp]\n\\centering\n\\includegraphics[scale=0.8]{images/effect_position.png}\n\\caption[Effect metrics in imitation]{The figure illustrates three examples\n of the imitation based on a single demonstration. The left box is the\n demonstrated action. The right box is the possible final state based on\n the position metrics used. The grey triangles are superimposed to show\n the relative distance is maintained \\cite{alissandrakis_action_2006}}\n\\label{effect metrics}\n\\end{figure}\n\nBased on the effect metrics the knowledge base is organized in different templates which describe an action.\nThe templates developed in this work are categorized based on the effect metrics.\n\n\\subsection{Selecting template from the knowledge base}\nFor computing the relevance, we use a 3 stage procedure:\n\\begin{enumerate}\n    \\item Comparing mean of start value and end value of the feature. $\\rightarrow$ To determine that the feature has changed.\n            (This was used because features which were not changed in demonstration also have low entropy. So to remove these features this condition \n            check was introduced.)\n    \\item Comparing the standard deviation of start value and end value of the featue $\\rightarrow$ To determing the feature shows convergence in information.\n            (This was used because there were features which changed and had low entropy but they were divergent in nature. So to remove the effect of \n            these features this condition check was introduced as explained in figure \\ref{fig:box plot})\n    \\item Calculating the entropy/conditional entropy of the final value of features whose values have changed.\n\\end{enumerate}\n\n\\begin{algorithm}[H]\n \\KwData{\\\\ $f_s$ : start value of the features \\\\\n         $f_e$ : end value of the features\\\\\n        K : knowledge base }\n \\KwResult{\\\\ relevance $L$ of each Template }\n R=0\\;\n \\For{each template $t$ in K}{\n    \\For{each feature $f$ in $t$ }{\n  read start values $s$ of feature $f$ from $f_s$\\;\n  read end values $e$ of featue $f$ from $f_e$\\;\n  \\If{mean(s) equals mean(e)}{\n       $ R += 1$\\;\n   }\n   \\If{standard deviation(s) is less or equal to standard deviation(e)}{\n       $ R += 1$\\;\n   }\n    $R += \\text{entropy(e)} or\\text{ conditional entropy}(e|s)$\\;\n  }\n }\n \\caption{Algorithm for computing relevance of the templates in knowledge base}\n\\end{algorithm}\n\n\\begin{figure}\n    \\centering\n    \\begin{subfigure}[b]{0.3\\textwidth}\n        \\includegraphics[scale=0.25]{images/boxplot_same_mean.png} \n        \\caption{}\n        \\label{sub box 1}\n    \\end{subfigure}\n    \\begin{subfigure}[b]{0.3\\textwidth}\n        \\includegraphics[scale=0.25]{images/boxplot_noconvergence.png} \n        \\caption{}\n        \\label{sub box 2}\n    \\end{subfigure}\n    \\begin{subfigure}[b]{0.3\\textwidth}\n        \\includegraphics[scale=0.25]{images/boxplot_converged.png} \n        \\caption{}\n        \\label{sub box 3}\n    \\end{subfigure}\n    \\caption[Box plot of features]{Box plots of features. Each figure has 2 box plots.\nPlot I is of the start value of the feature while plot F is of the end value\nof the feature. Figure \\ref{sub box 1} is box plot of a featue whose mean values \nhave not changed for both start and end values of the feature .\nFigure \\ref{sub box 2} is the box plot of a feature whose mean value \nhas changed but the final values has not converged. \nFigure \\ref{sub box 3} is the box plot of a feature whose mean value \nhas changed and the final values have converged.} \\label{fig:box plot}\n\\end{figure}\n\n\nFor each $t_i \\in K $, we compute a score $\\beta_i$ that combines model fitting and the number of \nfeatures in the template.\n\\begin{equation}\n    \\beta_i = -2 \\log (p (f | \\theta_i)) - \\alpha_i L_i\n\\end{equation}\nwhere $\\theta_i$ are the distributions related to the features of $t_i$\nand $L_i$ is the number of features in the template.\nThe first term of equation  computes relevance and the second term, weighted by $\\alpha$, encourages the usage of templates\nconsisting of a large number of features $L_i$ .\n\n\nThe most relevant template $T^*$ is selected as :\n\\begin{equation}\n    T^* = \\operatornamewithlimits{argmin}_i (\\beta_i)\n\\end{equation}\n", "meta": {"hexsha": "f91b19288cff1b49b648e3bb41210fa3e3dcdb20", "size": 15465, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/rnd_report_tex/Content.tex", "max_stars_repo_name": "deebuls/RecommenderSystemInRobotics", "max_stars_repo_head_hexsha": "2badd51dc0f196374a9195e346d85354b1e2e108", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tex/rnd_report_tex/Content.tex", "max_issues_repo_name": "deebuls/RecommenderSystemInRobotics", "max_issues_repo_head_hexsha": "2badd51dc0f196374a9195e346d85354b1e2e108", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2015-04-10T16:33:27.000Z", "max_issues_repo_issues_event_max_datetime": "2015-04-19T09:30:04.000Z", "max_forks_repo_path": "tex/rnd_report_tex/Content.tex", "max_forks_repo_name": "deebuls/RecommenderSystemInRobotics", "max_forks_repo_head_hexsha": "2badd51dc0f196374a9195e346d85354b1e2e108", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.1493902439, "max_line_length": 701, "alphanum_fraction": 0.7523440026, "num_tokens": 3742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791786991753931, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3475470179294239}}
{"text": "\n% \\documentclass[draft,11pt]{article}\n\\chapter{Solving Laplacian\n  Linear Equations}\n\n%\\allowdisplaybreaks\n\n%%% For this lecture\n%\\newcommand\\symset{S}\n%\\newcommand\\psdset{S_+}\n%\\newcommand\\pdset{S_{++}}\n\n%\\newcommand\\symsetn{\\symset^n}\n%\\newcommand\\psdsetn{\\psdset^n}\n%\\newcommand\\pdsetn{\\pdset^n}\n\n\n%\\newcommand{\\vcliq}[2]{\\textsc{Clique}\\!\\left({#1,#2}\\right)}\n%\\newcommand{\\vstar}[2]{\\textsc{Star}\\!\\left({#1,#2}\\right)}\n\n%%% added by Hongjie\n%\\newcommand{\\Hongjie}[1]{{\\color{red} Hongjie: #1}}\n%\\newcommand{\\vcliqsp}[2]{\\textsc{CliqueSample}\\!\\left({#1,#2}\\right)}\n\n%%% layout and code\n%\\usepackage[vlined, ruled]{algorithm2e}\n%\\usepackage{float}\n\n%\\begin{document}\n\\sloppy\n%\\lecture{9 --- Wednesday, April 22nd}\n%{Spring 2020}{Rasmus Kyng, Scribe: Hongjie Chen}{Solving Laplacian\n%  Linear Equations}\n\n% \\todo{introduce stopped martingale}\n\n% \\todo{remarks, Tropp and Matrix Freedman and things to know}\n\n% \\paragraph{outline}\n% \\begin{itemize}\n% \\item objective\n% \\item precond\n% \\item algo\n% \\item martingale\n% \\item mat conc\n% \\end{itemize}\n\n\n\n\\section{Solving Linear Equations Approximately}\n\nGiven a Laplacian $\\LL$ of a connected graph and a demand vector\n$\\dd \\perp \\vecone$, we want to find $\\xx^*$ solving the linear equation\n$\\LL \\xx^* = \\dd$.\nWe are going to focus on fast algorithms for finding approximate (but\nhighly accurate) solutions.\n\nThis means we need a notion of an approximate solution.\nSince our definition is not special to Laplacians, we state it more\ngenerally for positive semi-definite matrices.\n\\begin{definition}\n  Given PSD matrix $\\MM$ and $\\dd \\in \\ker(\\MM)^{\\perp}$, let\n  $\\MM \\xx^* = \\dd$.\n  We say that $\\xxtil$ is an $\\epsilon$-approximate solution to the\n  linear equation $\\MM \\xx = \\dd$ if\n  \\[\n    \\norm{\\xxtil - \\xx^*}_{\\MM}^2 \\leq \\epsilon \\norm{\\xx^*}_{\\MM}^2.\n  \\]\n\\end{definition}\n\n\\begin{remark}\n  The requirement $\\dd \\in \\ker(\\MM)^{\\perp}$ can be removed,\n   but this is not important for us.\n \\end{remark}\n\n\\begin{theorem}[Spielman and Teng (2004) \\cite{st04}]\nGiven a Laplacian $\\LL$ of a weighted undirected graph $G = (V,E,\\ww)$\nwith $\\abs{E}=m$ and $\\abs{V} = n$ and a demand vector $\\dd \\in \\R^V$,\nwe can find $\\xxtil$ that is an $\\epsilon$-approximate solution to\n$\\LL \\xx = \\dd$, using an algorithm that takes time\n$O(m \\log^c n \\log(1/\\epsilon))$ for some fixed constant $c$ and succeeds with probability $1 - 1/n^{10}$.\n\\end{theorem}\nIn the original algorithm of Spielman and Teng, the exponent on the\nlog in the running time was $c \\approx 70$.\n\nToday, we are going to see a simpler algorithm. But first, we'll look\nat one of the key tools behind all algorithms for solving Laplacian\nlinear equations quickly.\n\n\n\\section{Preconditioning and\nApproximate Gaussian Elimination}\nRecall our definition of two positive semi-definite matrices being\napproximately equal.\n\\begin{definition}[Spectral approximation]\n  Given $\\AA, \\BB \\in \\psdsetn$, we say that\n  \\[\n    \\AA \\approx_{K} \\BB\n    \\text{ if and only if }\n    \\frac{1}{1+ K} \\AA \\preceq \\BB \\preceq (1+ K) \\AA.\n    \\]\n\\end{definition}\nSuppose we have a positive definite matrix $\\MM \\in \\pdsetn$ and want to\nsolve a linear equation $\\MM \\xx =\\dd$.\nWe can do this using gradient descent or accelerated gradient\ndescent, as we covered in Graded Homework 1.\nBut if we have access to an easy-to-invert matrix that happens to also\nbe a good spectral approximation of $\\MM$, then we can use this to\nspeed up the (accelerated) gradient descent algorithm.\nAn example of this would be that we have a factorization\n$\\matlow\\matlow^{\\trp} \\approx_{K} \\MM$, where $\\matlow$ is\nlower triangular and sparse, which means we can invert it quickly.\n\nThe following lemma, which you will prove in Problem Set 6, makes this\npreconditioning precise.\n\\begin{lemma}\n  \\label{lem:cholprecond}\n  Given a matrix $\\MM \\in \\pdsetn$, a vector $\\dd$ and a decomposition $\\MM\n  \\approx_{K} \\matlow\\matlow^{\\trp}$,\n  we can find $\\xxtil$ that $\\epsilon$-approximately solves $\\MM \\xx =\n  \\dd$, using\n$O( (1+ K)\\log(K/\\epsilon)(T_{\\text{matvec}} + T_{\\text{sol}} + n) ) $ time.\n\\begin{itemize}\n\\item $T_{\\text{matvec}}$ denotes the time required to compute $\\MM\n  \\zz$ given a vector $\\zz$, i.e.  a ``matrix-vector multiplication''.\n\\item  $T_{\\text{sol}}$ denotes the time required to compute\n  $\\matlow^{-1}\\zz$ or $(\\matlow^{\\trp})^{-1}\\zz$ given a vector\n  $\\zz$.\n\\end{itemize}\n\\end{lemma}\n\\paragraph{Dealing with pseudo-inverses.}\nWhen our matrices have a null space, preconditioning becomes slightly\nmore complicated, but as long as it is easy to project to the\ncomplement of the null space, there's no real issue. The following\ndescribes precisely what we need (but you can ignore the null-space\nissue when first reading these notes without losing anything\nsignificant).\n\\begin{lemma}\n  \\label{lem:cholprecondpinv}\n  Given a matrix $\\MM \\in \\psdsetn$, a vector $\\dd \\in \\ker(\\MM)^{\\perp}$ and a decomposition $\\MM\n  \\approx_{K} \\matlow\\calDD\\matlow^{\\trp}$, where $\\matlow$ is invertible,\n  we can find $\\xxtil$ that $\\epsilon$-approximately solves $\\MM \\xx =\n  \\dd$, using\n${O( (1+ K)\\log(K/\\epsilon)(T_{\\text{matvec}} + T_{\\text{sol}} +\nT_{\\text{proj}} + n) ) }$ time.\n\\begin{itemize}\n\\item $T_{\\text{matvec}}$ denotes the time required to compute $\\MM\n  \\zz$ given a vector $\\zz$, i.e.  a ``matrix-vector multiplication''.\n\\item  $T_{\\text{sol}}$ denotes the time required to compute\n  $\\matlow^{-1}\\zz$ and $(\\matlow^{\\trp})^{-1}\\zz$ and $\\calDD^{+}\\zz$ given a vector\n  $\\zz$.\n\\item $T_{\\text{proj}}$ denotes the time required to compute\n  $\\proj_{\\MM} \\zz$ given a vector $\\zz$.\n\\end{itemize}\n\\end{lemma}\n\n\\begin{theorem}[Kyng and Sachdeva (2015) \\cite{ks16}]\n  \\label{thm:apxgauss}\nGiven a Laplacian $\\LL$ of a weighted undirected graph $G = (V,E,\\ww)$\nwith $\\abs{E}=M$ and $\\abs{V} = n$,\nwe can find a decomposition\n$\\matlow\\matlow^{\\trp} \\approx_{0.5} \\LL $, such that\n$\\matlow$ has number of non-zeroes $\\nnz(\\matlow) = O(m \\log^3 n)$,\nwith probability at least $1 - 3/n^{5}$.\nin time  $O(m \\log^3 n)$.\n\\end{theorem}\nWe can combine Theorem~\\ref{thm:apxgauss} with\nLemma~\\ref{lem:cholprecondpinv} to get a fast algorithm for solving\nLaplacian linear equations.\n% ...\n% \\begin{corollary}\n%   Given a decomposition $\\matlow\\matlow^{\\trp} \\approx_{0.5} \\LL $,\n% \\end{corollary}\n\\begin{corollary}\n  \\label{cor:precondsolver}\n  Given a Laplacian $\\LL$ of a weighted undirected graph $G = (V,E,\\ww)$\nwith $\\abs{E}=m$ and $\\abs{V} = n$ and a demand vector $\\dd \\in \\R^V$,\nwe can find $\\xxtil$ that is an $\\epsilon$-approximate solution to\n$\\LL \\xx = \\dd$, using an algorithm that takes time $O(m \\log^3 n\n\\log(1/\\epsilon))$ and succeeds with probability $1 - 1/n^{10}$.\n\\end{corollary}\n\\begin{proof}[Proof sketch]\n\n  First we need to get a factorization that confirms to\n  Lemma~\\ref{lem:cholprecondpinv}.\n  The decomposition $\\matlow\\matlow^{\\trp}$ provided by\n  Theorem~\\ref{thm:apxgauss} can be rewritten as\n  $\\matlow\\matlow^{\\trp} = \\matlowtil \\calDD (\\matlowtil)^{\\trp}$\n  where\n$\\matlowtil$ is equal to $\\matlow$ except $\\matlow(n,n) = 1$\nand we let $\\calDD$ be the identity matrix, except $\\calDD (n,n)\n= 0$.\nThis ensures $\\calDD^{\\pinv} = \\calDD$ and that $\\matlowtil$ is\ninvertible and lower triagular with  $O(m \\log^3 n)$ non-zeros.\nWe note that the inverse of an invertible lower or upper triangular\n  matrix with $N$ non-zeros can be applied in time $O(N)$ given an\n  adjacency list representation of the matrix.\n  Finally, as $\\ker(\\matlow\\matlow^{\\trp}) = \\Span\\setof{\\vecone}$,\nwe have $\\proj_{ \\matlowtil \\calDD (\\matlowtil)^{\\trp}}\n= \\II -\\frac{1}{n} \\vecone \\vecone^{\\trp}$, and this projection matrix can be\napplied in $O(n)$ time.\nAltogether, this means that $T_{\\text{matvec}} + T_{\\text{sol}} +\nT_{\\text{proj}} = O(n)$, which suffices to complete the proof.\n\\end{proof}\n\n\\section{Approximate Gaussian Elimination Algorithm}\nRecall \\emph{Gaussian Elimination / Cholesky decomposition} of a graph Laplacian $\\LL$.\nWe will use $\\AA(:,i)$ to denote the the $i$th\ncolumn of a matrix $\\AA$.\nWe can write the algorithm as\n% \\begin{algorithm}[h]\n%   \\begin{algorithmic}\n%  \\For{$i = 1$ to $i = n-1$}\n%   \\State $\\ll_i = \\frac{1}{\\sqrt{\\SS_{i-1}(i,i)}} \\SS_{i-1}(:,i)$\n%   \\State  $\\SS_{i} = \\SS_{i-1} - \\ll_i \\ll_i^{\\trp}.$\n%   \\EndFor\n%   \\State $\\ll_n = \\veczero_{n \\times 1}$\n%   \\State $\\matlow=\\begin{bmatrix} \\ll_1 \\cdots \\ll_n \\end{bmatrix}$\n% \\end{algorithmic}\n% \\end{algorithm}\n\n\\begin{algorithm}[H]\n\\label{alg:ge}\n\\caption{Gaussian Elimination / Cholesky Decomposition}\n\\KwIn{Graph Laplacian $\\LL$}\n\\KwOut{Lower triangular $\\matlow$ s.t. $\\matlow\\matlow^{\\trp} = \\LL$}\nLet $\\SS_0 = \\LL$ \\;\n \\For{$i = 1$ to $i = n-1$}{\n$\\ll_i = \\frac{1}{\\sqrt{\\SS_{i-1}(i,i)}} \\SS_{i-1}(:,i)$\\;\n$\\SS_{i} = \\SS_{i-1} - \\ll_i \\ll_i^{\\trp}.$\\\n}\n$\\ll_n = \\veczero_{n \\times 1}$\\;\n\\Return{$\\matlow=\\begin{bmatrix} \\ll_1 \\cdots \\ll_n \\end{bmatrix}$}\\;\n\\end{algorithm}\n% Now, for $i = 1$ to $i = n-1$ we define\n% \\begin{align*}\n%   \\ll_i &= \\frac{1}{\\sqrt{\\SS_{i-1}(i,i)}} \\SS_{i-1}(:,i), \\\\\n%   \\SS_{i} &= \\SS_{i-1} - \\ll_i \\ll_i^{\\trp}.\n% \\end{align*}\n% Finally, we let $\\ll_n = \\veczero_{n \\times 1}$. It follows that\n% $\\matlow=\\begin{bmatrix} \\ll_1 \\cdots \\ll_n \\end{bmatrix}$ is lower\n% triangular and $\\LL=\\matlow\\matlow^\\trp$.\nWe want to introduce some notation that will help us describe and\nanalyze a faster version of Gaussian elimination -- one that uses sampling\nto create a sparse approximation of the decomposition.\n\nConsider a Laplacian $\\SS$ of a graph $H$ and a vertex $v$ of $H$.\nWe define $\\vstar{v}{\\SS}$ to be the Laplacian of the subgraph of $H$\nconsisting of edges incident on $v$.\nWe define\n\\[\n\\vcliq{v}{\\SS} = \\vstar{v}{\\SS} - \\frac{1}{\\SS(v,v)} \\SS(:,v)  \\SS(:,v)^{\\trp}\n\\]\nFor example, suppose\n\\[\n  \\LL =\n\\left(\n\\begin{array}{ccc}\nW & -\\aa^\\trp \\\\\n-\\aa& \\diag(\\aa) + \\LL_{-1}\n\\end{array} \\right)\n\\]\nThen\n\\[\n\\vstar{1}{\\LL}\n=\n\\left(\n\\begin{array}{ccc}\nW & -\\aa^\\trp \\\\\n-\\aa& \\diag(\\aa)\n\\end{array} \\right)\n\\text{ and }\n\\vcliq{1}{\\LL}\n=\n\\left(\n\\begin{array}{ccc}\n0 &  \\veczero \\\\\n\\veczero & \\diag(\\aa) - \\frac{1}{W} \\aa \\aa^\\trp\n\\end{array} \\right)\n\\]\nwhich is illustrated in Figure \\ref{fig:schurclique}.\n%\n\\begin{figure}[H]\n  \\centering\n  \\includegraphics[width=1\n  \\textwidth]{fig/lecture7_schur-clique.jpeg}\n  \\caption{Gaussian Elimination:\n    $\\vcliq{1}{\\LL} = \\vstar{1}{\\LL} - \\frac{1}{\\LL(1,1)} \\LL(:,1)\n    \\LL(:,1)^{\\trp}$.}\n      \\label{fig:schurclique}\n    \\end{figure}\nIn Chapter~\\ref{cha:ge}, we proved that $\\vcliq{v}{\\SS}$ is a graph Laplacian --\nit follows from the proof of Claim~\\ref{clm:optimgaussclosed} in that chapter.\nThus we have that following.\n \\begin{claim}\n\\label{clm:optimgaussclosedagain}\nIf $\\SS$ is the Laplacian of a connected graph, then\n$\\vcliq{v}{\\SS}$ is a graph Laplacian.\n% \\begin{enumerate}\n% \\item $\\vcliq{v}{\\SS}$ is a graph Laplacian.\n% \\item\n% \\end{enumerate}\n\\end{claim}\n\nNote that in Algorithm~\\ref{alg:ge}, we have  $\\ll_i\\ll_i^\\trp = \\vstar{v_i}{\\SS_{i-1}}-\\vcliq{v_i}{\\SS_{i-1}}$. The update rule can be rewritten as\n\\[ \\SS_{i} = \\SS_{i-1} - \\vstar{v_i}{\\SS_{i-1}} +\n  \\vcliq{v_i}{\\SS_{i-1}}, \\]\n\nThis also provides way to understand why\nGaussian Elimination is slow in some cases.\nAt each step, one vertex is eliminated, but a clique is added to the\nsubgraph on the remaining vertices, making the graph denser.\nAnd at the $i$th step, computing $\\vstar{v_i}{\\SS_{i-1}}$\ntakes around $\\deg(v_i)$ time, but computing $\\vcliq{v_i}{\\SS_{i-1}}$\nrequires around $\\deg(v_i)^2$ time.\nIn order to speed up Gaussian\nElimination, the algorithmic idea of \\cite{ks16}\n%\\cite{?}\n is to plug in a sparser appproximate of the intended clique instead\n of the entire one.\n\nThe following procedure $\\vcliqsp{v}{\\SS}$ produces a sparse\napproximation of $\\textsc{clique}(v,\\SS)$.\nLet $V$ be the vertex set of the graph associated with $\\SS$ and $E$\nthe edge set.\nWe define $\\bb_{i,j} \\in \\R^V$ to be the vector with\n\\[\n  \\bb_{i,j}(i) = 1\n  \\text{ and }\n  \\bb_{i,j}(j) = -1\n  \\text{ and }\n  \\bb_{i,j}(k) = 0\n  \\text{ for }\n  k \\neq i,j.\n\\]\nGiven weights $\\ww \\in \\R^E$ and a vertex $v \\in V$,\nwe let\n\\[\n  \\ww_v = \\sum_{(u,v) \\in E} \\ww(u,v)\n  .\n  \\]\n\\begin{algorithm}[H]\n\\label{alg:cliquesamp}\n\\caption{$\\vcliqsp{v}{\\SS}$}\n\\KwIn{Graph Laplacian $\\SS \\in \\R^{V \\times V}$, of a graph with edge\n  weights $\\ww$, and vertex $v \\in V$}\n\\KwOut{$\\YY_v \\in \\R^{V \\times V}$ sparse approximation of\n  $\\textsc{clique}(v,\\SS)$  }\n $\\YY_v   \\gets  \\matzero_{n \\times n} $\\;\n \\ForEach{Multiedge $e\n   = (v,i)$ from $v$ to a neighbor $i$}{\n    Randomly pick a neighbor $j$ of $v$ with probability $\\frac{\\ww(j,v)}{\\ww_v}$\\;\n    If $i \\neq j$, let $\\YY_v   \\gets \\YY_v + \\frac{\\ww(i,v)\\ww(j,v)}{\\ww(i,v)+\\ww(j,v)} \\bb_{i,j}\\bb_{i,j}^\\trp$\\;\n}\n\\Return{$\\YY_v$}\\;\n\\end{algorithm}\n% Let $\\YY_v = \\matzero_{n \\times n}$. For each neighbor $i$ of $v$, randomly pick a neighbor $j$ of $v$ with probability $\\frac{\\ww(j,v)}{\\ww_v}$ where $\\ww_v = \\sum_{u \\sim v} \\ww(u,v)$ is the sum of weights of edges incident to $v$. If $i\\neq j$, then draw an edge with weight $\\ww(i,v)\\ww(j,v)/(\\ww(i,v)+\\ww(j,v))$ between $i$ and $j$, i.e. update $\\YY_v$ by\n% \\[ \\YY_v \\gets \\YY_v + \\frac{\\ww(i,v)\\ww(j,v)}{\\ww(i,v)+\\ww(j,v)} \\bb_{i,j}\\bb_{i,j}^\\trp. \\]\n%\n\\begin{remark}\n  We can implement each sampling of a neighbor $j$ in $O(1)$ time\n  using a classical algorithm known as Walker's method (also known as the Alias\n  method or Vose's method).\n  This algorithm requires an additional $O(\\deg_{\\SS}(v))$ time to\n  initialize a data structure used for sampling.\n  Overall, this means the total time for $O(\\deg_{\\SS}(v))$ samples is still $O(\\deg_{\\SS}(v))$.\n\\end{remark}\n\n% %TODO this paragraph sometimes causes horizontal \"badness\" failure\n% In what sense does $\\vcliqsp{v}{\\SS}$ produce a sparse approximation\n% of the clique $\\vcliq{v}{\\SS}$ created by Gaussian elimination?\n% This is a crucial question, and the next lemma gives part of the\n% answer: Namely that the output in expectation equals the clique.\n\\begin{lemma}\\label{lem:cliquesample_expectation}\n  $\\E{\\YY_v} = \\vcliq{v}{\\SS}$.\n\\end{lemma}\n\\begin{proof}\n  Let $\\CC=\\vcliq{v}{\\SS}$. Observe that both $\\E{\\YY_v}$ and $\\CC$ are Laplacians. Thus it suffices to verify $\\Ex{\\YY_v(i,j)}=\\CC(i,j)$ for $i\\neq j$.\n  \\[ \\CC(i,j) = -\\frac{\\ww(i,v)\\ww(j,v)}{\\ww_v}, \\]\n  \\[ \\Ex{\\YY_v(i,j)} = -\\frac{\\ww(i,v)\\ww(j,v)}{\\ww(i,v)+\\ww(j,v)} \\left( \\frac{\\ww(j,v)}{\\ww_v} + \\frac{\\ww(i,v)}{\\ww_v} \\right) = -\\frac{\\ww(i,v)\\ww(j,v)}{\\ww_v} = \\CC(i,j). \\]\n\\end{proof}\n\\begin{remark}\n  Lemma \\ref{lem:cliquesample_expectation} shows that $\\vcliqsp{v}{\\LL}$ produces the original $\\vcliq{v}{\\LL}$ in expectation.\n\\end{remark}\n\nNow, we define \\emph{Approximate Gaussian Elimination}.\n% Let $\\SS_0 = \\LL$. Generate a radom permutation $\\pi$ on $[n]$. For $i = 1$ to $i = n-1$ we define\n% \\begin{align*}\n%   \\ll_i &= \\frac{1}{\\sqrt{\\SS_{i-1}(\\pi(i),\\pi(i))}} \\SS_{i-1}(:,\\pi(i)), \\\\\n%   \\SS_{i} &= \\SS_{i-1} - \\vstar{\\pi(i)}{\\SS_{i-1}} + \\vcliqsp{\\pi(i)}{\\SS_{i-1}}.\n              %   \\end{align*}\n\n\\begin{algorithm}[H]\n\\label{alg:apxge}\n\\caption{Approximate Gaussian Elimination / Cholesky Decomposition}\n\\KwIn{Graph Laplacian $\\LL$}\n\\KwOut{Lower triangular\\footnote{$\\matlow$ is not actually lower\n    triangular. However, if we let $\\PP_\\pi$ be the permutation matrix\n    corresponding to $\\pi$, then $\\PP_\\pi \\matlow$ is lower\n    triangular. Knowing the ordering that achieves this is enough to\n    let us implement forward and backward substitution for solving\n    linear equations in $\\matlow$ and $\\matlow^\\trp$.}\n  $\\matlow$ as\n  given in Theorem~\\ref{thm:apxgauss}}\nLet $\\SS_0 = \\LL$\\;\nGenerate a random permutation $\\pi$ on $[n]$\\;\n\\For{$i = 1$ to $i = n-1$}{\n$\\ll_i = \\frac{1}{\\sqrt{\\SS_{i-1}(\\pi(i),\\pi(i))}} \\SS_{i-1}(:,\\pi(i)) $\\;\n$\\SS_{i} = \\SS_{i-1} - \\vstar{\\pi(i)}{\\SS_{i-1}} + \\vcliqsp{\\pi(i)}{\\SS_{i-1}}$\\\n}\n$\\ll_n = \\veczero_{n \\times 1}$\\;\n\\Return{$\\matlow=\\begin{bmatrix} \\ll_1 \\cdots \\ll_n \\end{bmatrix}$ and\n$\\pi$}\\;\n\\end{algorithm}\n% $\\PP_\\pi$ be the permutation matrix corresponding to $\\pi$. It follows that $\\matlow =\n% \\PP_\\pi \\begin{bmatrix} \\ll_1 \\cdots \\ll_n \\end{bmatrix}$ is lower\n% triangular and $\\LL=\\matlow\\matlow^\\trp$.\nNote that if we replace\n$\\vcliqsp{\\pi(i)}{\\SS_{i-1}}$ by $\\vcliq{\\pi(i)}{\\SS_{i-1}}$ at each\nstep, then we can recover Gaussian Elimination, but with a random\nelimination order.\n\n\\section{Analyzing Approximate Gaussian Elimination}\n\nIn this Section, we're going to analyze Approximate Gaussian\nElimination, and see why it works.\n\nUltimately, the main challenge in proving Theorem~\\ref{thm:apxgauss}\nwill be to prove for the output $\\matlow$\nof Algorithm~\\ref{alg:apxge} that with high probability\n\\begin{equation}\n  \\label{eq:relerrgoal}\n0.5 \\LL\n\\preceq\n\\matlow \\matlow^{\\trp}\n\\preceq 1.5 \\LL\n.\n\\end{equation}\nWe can reduce this to proving that with high probability\n\\begin{equation}\n\\label{eq:spectralnormgoal}\n \\norm{\\LL^{+/2} (\\matlow \\matlow^{\\trp} -  \\LL) \\LL^{+/2}} \\leq 0.5\n\\end{equation}\nUltimately, the proof is going to have a lot in common with our proof\nof Matrix Bernstein in Chapter~\\ref{cha:randmat}.\nOverall, the lesson there was that when we have a sum of independent,\nzero-mean random matrices, we can show that the sum is likely to have\nsmall spectral norm if the spectral norm of each random matrix is\nsmall, and the matrix-valued variance is also small.\n\nThus, to replicate the proof, we need control over\n\\begin{enumerate}\n\\item The \\emph{sample norms}.\n\\item The \\emph{sample variance}.\n\n\\end{enumerate}\n\nBut, there is seemlingly another major obstacle: We are trying to\nanalyze a process where the samples are far from independent.\nEach time we sample edges, we add new edges to the remaining graph,\nwhich we will the later sample again. This creates a lot of\ndependencies between the samples, which we have to handle.\n\nHowever, it turns out that independence is more than what is needed to\nprove concentration. Instead, it suffices to have a sequence of random\nvariables such that each is mean-zero in expectation, conditional on\nthe previous ones. This is called a martingale difference sequence.\nWe'll now learn about those.\n\n\\subsection{Normalization, a.k.a. Isotropic Position}\n\nSince our analysis requires frequently measuring matrices after right\nand left-multiplication by $\\LL^{\\pinv/2}$, we reintroduce the\n``normalizing map'' $\\Phi : \\R^{n\\times n} \\to\n\\R^{n\\times n} $\ndefined by\n\\[\n  \\Phi(\\AA) = \\LL^{\\pinv/2}\\AA\\LL^{\\pinv/2}.\n  \\]\nWe previously saw this in Chapter~\\ref{cha:randmat}.\n\n\\subsection{Martingales}\n\nA scalar martingale is a sequence of random variables $Z_0, \\ldots,\nZ_k$, such that\n\\begin{align}\n\\label{eq:martingale}\n  \\E{Z_i \\mid Z_0, \\ldots, Z_{i-1}} = Z_{i-1}\n.\n\\end{align}\nThat is, conditional on the outcome of all the previous random\nvariables, the expectation of $Z_{i}$ equals $Z_{i-1}$.\nIf we unravel the sequence of conditional expectations, we\nget that \\emph{without conditioning}\n$\\E{Z_k}=\\E{Z_0}$.\n\nTypically, we use martingales to show a statement along like  ``$Z_k$\nis concentrated around $\\E{Z_k}$''.\n\nWe can also think of a martingale in terms of the sequence of changes\nin the $Z_i$ variables.\nLet $X_i = Z_i - Z_{i-1}$.\nThe sequence of $X_i$s is called a martingale difference sequence.\nWe can now state the martingale condition as\n\\[\n  \\E{X_i \\mid Z_0, \\ldots, Z_{i-1}} = 0\n.\n\\]\nAnd because $Z_0$ and $X_{1}, \\ldots, X_{i-1}$ completely determine\n$Z_1,  \\ldots, Z_{i-1}$, we could also write\nthe martingale condition equivalently as\n\\[\n  \\E{X_i \\mid Z_0, X_1, \\ldots, X_{i-1}} = 0\n  .\n\\]\nCrucially, we can write\n\\[\nZ_k = Z_0 + \\sum_{i=1}^k Z_i - Z_{i-1} = Z_0 + \\sum_{i=1}^k X_i\n\\]\nand when we are trying to prove concentration, the martingale difference property\nof the $X_i$'s is often ``as good as'' independence, meaning that\n$\\sum_{i=1}^k X_i$ concentrates similarly to a sum of independent\nrandom variables.\n\n\n\n\n\\paragraph{Matrix-valued martingales.}\nWe can also define matrix-valued martingales.\nIn this case, we replace the martingalue condition of\nEquation~\\eqref{eq:martingale}, with the condition that the whole matrix\nstays the same in expectation.\nFor example, we could have a sequence of random matrices $\\ZZ_0, \\ldots,\n\\ZZ_k \\in \\R^{n \\times n}$, such that\n\\begin{align}\n\\label{eq:matmartingale}\n  \\E{\\ZZ_i \\mid \\ZZ_0, \\ldots, \\ZZ_{i-1}} = \\ZZ_{i-1}\n.\n\\end{align}\n\\begin{lemma}\\label{lem:ApxGE_martingale}\n  Let $\\LL_i = \\SS_i + \\sum_{j=1}^i \\ll_j\\ll_j^\\trp$ for $i=1,...,n$ and $\\LL_0=\\SS_0=\\LL$. Then\n  \\[ \\E{\\LL_i | \\text{all random variables before } \\vcliqsp{\\pi(i)}{\\SS_{i-1}} } = \\LL_{i-1}. \\]\n\\end{lemma}\n\\begin{proof}\n  Let's only consider $i=1$ here as other cases are similar.\n  \\[ \\LL_0 = \\LL = \\ll_1\\ll_1^\\trp + \\vcliq{v}{\\LL} + \\LL_{-1} \\]\n  \\begin{align*}\n    \\LL_1 &= \\ll_1\\ll_1^\\trp + \\vcliqsp{v}{\\LL} + \\LL_{-1} \\\\\n    \\E{\\LL_1 | \\pi(1)}\n    &= \\ll_1\\ll_1^\\trp + \\E{\\vcliqsp{v}{\\LL}|\\pi(1)} + \\LL_{-1} \\\\\n    &= \\ll_1\\ll_1^\\trp + \\vcliq{v}{\\LL} + \\LL_{-1} \\\\\n    &= \\LL_0\n  \\end{align*}\n  where we used Lemma~\\ref{lem:cliquesample_expectation} to get\n  $\\E{\\vcliqsp{v}{\\LL}|\\pi(1)}  = \\vcliq{v}{\\LL} $.\n\\end{proof}\n\\begin{remark}\n  $\\sum_{j=1}^i \\ll_j\\ll_j^\\trp$ can be treated as what has already been eliminated by (Approximate) Gaussian Elimination, while $\\SS_i$ is what still left or going to be eliminated.\n  In Approximate Gaussian Elimination, $\\LL_n=\\sum_{i=1}^n\\ll_i\\ll_i^\\trp$ and our goal is to show that $\\LL_n\\approx_K\\LL$.\n  Note that $\\LL_i$ is always equal to the original Laplacian $\\LL$ for all $i$ in Gaussian Elimination.\n  Lemma \\ref{lem:ApxGE_martingale} demonstrates that $\\LL_0,\\LL_1,...,\\LL_n$ forms a matrix martingale.\n\\end{remark}\n\nUltimately, our plan is to use this matrix martingale structure to show\nthat ``$\\LL_n$ is concentrated around $\\LL$'' in some appropriate\nsense.\nMore precisely, the spectral approximation we would like to show can\nbe established by showing that  ``$\\Phi(\\LL_n)$ is concentrated around $\\Phi(\\LL)$''\n\n\\subsection{Martingale Difference Sequence as Edge-Samples}\nWe start by taking a slightly different view of the observations we\nused to prove Lemma~\\ref{lem:ApxGE_martingale}.\nRecall that $\\LL_i = \\SS_i + \\sum_{j=1}^i \\ll_j\\ll_j^\\trp$,\nand  $\\LL_{i-1} = \\SS_{i-1} + \\sum_{j=1}^{i-1} \\ll_j\\ll_j^\\trp$\nand\n\\[\n  \\SS_{i} = \\SS_{i-1} - \\vstar{\\pi(i)}{\\SS_{i-1}} +\n  \\vcliqsp{\\pi(i)}{\\SS_{i-1}}\n . \\]\nPutting these together, we get\n\\begin{align}\n  \\LL_i - \\LL_{i-1}\n  &=\n  \\ll_i\\ll_i^\\trp\n  +\n  \\vcliqsp{\\pi(i)}{\\SS_{i-1}}\n  -\n    \\vstar{\\pi(i)}{\\SS_{i-1}}\n     \\nonumber\n  \\\\\n    \\label{eq:apxgaussdiffseq}\n  &=\n  \\vcliqsp{\\pi(i)}{\\SS_{i-1}}\n  -\n    \\vcliq{\\pi(i)}{\\SS_{i-1}}\n\\\\\n  &=\n  \\vcliqsp{\\pi(i)}{\\SS_{i-1}}\n  -\n    \\E{\\vcliqsp{\\pi(i)}{\\SS_{i-1}} \\mid \\text{preceding samples}}\n \\tag*{by Lemma~\\ref{lem:cliquesample_expectation}.}\n\\end{align}\nIn particular, recall that by Lemma~\\ref{lem:cliquesample_expectation},\nconditional on the randomness before\nthe call to $\\vcliqsp{\\pi(i)}{\\SS_{i-1}}$, we\nhave\n\\[\n\\E{\\vcliqsp{\\pi(i)}{\\SS_{i-1}} \\mid \\text{preceding samples}}= \\vcliq{\\pi(i)}{\\SS_{i-1}}\n\\]\nAdopting the notation of Lemma~\\ref{lem:cliquesample_expectation}\nwe write\n\\[\n  \\YY_{\\pi(i)} = \\vcliqsp{\\pi(i)}{\\SS_{i-1}}\n\\]\nand we further introduce notation each multi-edge sample for\n$e \\in \\vstar{\\pi(i)}{\\SS_{i-1}}$, as $\\YY_{\\pi(i),e}$, denoting the random\nedge Laplacian sampled when the algorithm is processing multi-edge\n$e$.\nThus, conditional on preceding samples, we have\n\n\\begin{equation}\n  \\label{eq:cliquesamplesum}\n  \\YY_{\\pi(i)} = \\sum_{e \\in\n    \\vstar{\\pi(i)}{\\SS_{i-1}}}\\YY_{\\pi(i),e}\n\\end{equation}\nNote that even the number of multi-edges in\n$\\vstar{\\pi(i)}{\\SS_{i-1}}$ depends on the preceding samples.\nWe also want to associate zero-mean variables with each edge.\nConditional on preceding samples, we also define\n\\[\n  \\XX_{i,e} = \\Phi\\left( \\YY_{\\pi(i),e} - \\E{\\YY_{\\pi(i),e}} \\right)\n  \\text{ and }\n  \\XX_{i} = \\sum_{e \\in\n    \\vstar{\\pi(i)}{\\SS_{i-1}}}\\XX_{i,e}\n\\]\nand combining this with Equations~\\eqref{eq:apxgaussdiffseq} and \\eqref{eq:cliquesamplesum}\n\\[\n  \\XX_{i}\n  = \\Phi(\\YY_{\\pi(i)} - \\E{\\YY_{\\pi(i)}})\n  = \\Phi(\\LL_i - \\LL_{i-1})\n\\]\nAltogether, we can write\n\\[\n  \\Phi\\left(  \\LL_n -\\LL \\right)\n  =\n    \\sum_{i=1}^n \\Phi(\\LL_i - \\LL_{i-1})\n  =\n  \\sum_{i=1}^n \\XX_i\n  =\n  \\sum_{i=1}^n \\sum_{e \\in\n    \\vstar{\\pi(i)}{\\SS_{i-1}}}\\XX_{i,e}\n\\]\nNote that the $\\XX_{i,e}$ variables form a martingale difference\nsequence, because the linearity of $\\Phi$ ensures they are zero-mean\nconditional on preceding randomness.\n\n\\subsection{Stopped Martingales}\nUnfortunately, directly analyzing the concentration properties of\nthe $\\LL_i$ martingale that we just introduced turns out to be\ndifficult.\nThe reason is that we're trying to prove some very delicate\nmultiplicative error guarantees.\nAnd, if we analyze $\\LL_i$, we find that the multiplicative error is\nnot easy to control, \\emph{after it's already gotten big}.\nBut that's not really what we care about anyway: We want to say it\nnever gets big in the first place, with high probability.\nSo we need to introduce another martingale, that lets us ignore the\nbad case when the error has already gotten too big.\nAt the same time, we also need to make sure that statements about our\nnew martingale can help us prove guarantees about  $\\LL_i$.\nFortunately, we can achieve both at once.\nThe technique we use is related to the much broader topic of\nmartingale \\emph{stopping times}, which we only scratch the surface of\nhere. We're also going to be quite informal about it, in the interest\nof brevity.\nLecture notes by Tropp \\cite{tropp19} give a more formal introduction for\nthose who are interested.\n\n\n\nWe define the stopped martingale sequence $\\LLtil_i$ by\n\\begin{equation}\n  \\label{eq:stoppedmartingale}\n  \\LLtil_i\n  =\n  \\begin{cases}\n    \\LL_i & \\text{ if for all } j < i \\text{ we have }\n       \\LL_i \\preceq 1.5 \\LL\n       \\\\\n    \\LL_{j^*} & \\text{ for } j^* \\text{ being the least $j$ such that }  \\LL_{j} \\not\\preceq 1.5 \\LL\n  \\end{cases}\n\\end{equation}\n\n\n\nFigure~\\ref{fig:stopmart} shows the $\\LLtil_i$ martingale getting\nstuck at the first time $\\LL_{j^*} \\not\\preceq 1.5 \\LL$.\n\\begin{figure}[H]\n  \\centering\n  \\includegraphics[width=1\n  \\textwidth]{fig/lec9_stoppedmartingale.png}\n  \\caption{Gaussian Elimination\n    :\n    $\\vcliq{1}{\\LL} = \\vstar{1}{\\LL} - \\frac{1}{\\LL(1,1)} \\LL(:,1)\n    \\LL(:,1)^{\\trp}$.}\n      \\label{fig:stopmart}\n    \\end{figure}\n\nWe state the following without proof:\n\\begin{claim}\n\\noindent\n  \\begin{enumerate}\n  \\item The sequence $\\setof{\\LLtil_i}$ for $i = 0, \\ldots, n$ is a\n    martingale.\n  \\item $\\norm{\\LL^{+/2} (\\LLtil_i -  \\LL) \\LL^{+/2}} \\leq 0.5$\n    implies $\\norm{\\LL^{+/2} (\\LL_i -  \\LL) \\LL^{+/2}} \\leq 0.5$\n  \\end{enumerate}\n\\end{claim}\nThe martingale property also implies that the unconditional\nexpectation satisfies $\\E{\\LLtil_n} = \\LL$.\nThe proof of the claim is easy to sketch: For Part 1, each difference is\nzero-mean if the condition has not been violated, and is identically\nzero (and hence zero-mean) if it has been violated.\nFor Part 2, if the martingale $\\setof{\\LLtil_i}$ has stopped,\nthen $\\norm{\\LL^{+/2}\n  (\\LLtil_i -  \\LL) \\LL^{+/2}} \\leq 0.5$ is false, and the implication\nis vacuosly true.\nIf, on the other hand, the martingale has not stopped, the\nquantities are equal, because $\\LLtil_i  = \\LL_i$, and again it's easy\nto see the implication holds.\n\nThus, ultimately, our strategy is goin to be to show that\n$\\norm{\\LL^{+/2} (\\LLtil_i -  \\LL) \\LL^{+/2}} \\leq 0.5$\nwith high probability.\nExpressed using the normalizing map $\\Phi(\\cdot)$,\nour goal is to show that with high probability\n\\[\n  \\norm{\\Phi(\\LLtil_n -  \\LL)} \\leq 0.5.\n\\]\n\n\\paragraph{Stopped martingale difference sequence.}\nIn order to prove the spectral norm bound, we want to express the\n$\\setof{\\LLtil_i}$ martingale in terms of a sequence of martingale\ndifferences.\nTo this end, we define\n$\\XXtil_i = \\Phi(\\LLtil_i -  \\LLtil_{i-1})$.\nThis ensures that\n\\begin{equation}\n  \\label{eq:stoppedmartingale}\n  \\XXtil_i\n  =\n  \\begin{cases}\n    \\XX_i& \\text{ if for all } j < i \\text{ we have }\n       \\LL_i \\preceq 1.5 \\LL\n       \\\\\n    \\matzero & \\text{ otherwise }\n  \\end{cases}\n\\end{equation}\nWhenever the modified martingale $\\XXtil_i$ has not yet stopped, we\nalso introduce individual modified edge samples $\\XXtil_{i,e} =\n\\XX_{i,e}$.\nIf the martingale \\emph{has} stopped, i.e. $\\XXtil_i = \\matzero$,\nthen we can take these edge samples $\\XXtil_{i,e}$\nto be zero.\nWe can now write\n\\[\n  \\Phi\\left(  \\LLtil_n -\\LL \\right)\n  =\n    \\sum_{i=1}^n \\Phi(\\LLtil_i - \\LLtil_{i-1})\n  =\n  \\sum_{i=1}^n \\XXtil_i\n  =\n  \\sum_{i=1}^n \\sum_{e \\in\n    \\vstar{\\pi(i)}{\\SS_{i-1}}}\\XXtil_{i,e}\n  .\n\\]\nThus, we can see that Equation~\\eqref{eq:spectralnormgoal} is implied by\n\\begin{equation}\n  \\label{eq:zeromeanspectralnormgoal}\n  \\norm{\\sum_{i=1}^n \\XXtil_i} \\leq 0.5.\n\\end{equation}\n\n\\subsection{Sample Norm Control}\nIn this Subsection, we're going to see that the norms of each\nmulti-edge sample is controlled throughout the algorithm.\n\\begin{lemma}\\label{lem:cliquesample_bounded_norm}\n  Given two Laplacians $\\LL$ and $\\SS$ on the same vertex\n  set.\\footnote{$\\LL$ can be regarded as the original Laplacian we\n    care about, while $\\SS$ can be regarded as some intermediate\n    Laplacian appearing during Approximate Gaussian Elimination.} If\n  each multiedge $e$ of $\\vstar{v}{\\SS}$ has bounded norm in the following sense,\n  \\[ \\norm{\\LL^{\\pinv/2}\\ww_{\\SS}(e)\\bb_e\\bb_e^{\\trp}\\LL^{\\pinv/2}} \\leq R, \\]\n  then each possible sampled multiedge $e'$ of $\\vcliqsp{v}{\\SS}$ also satisfies\n  \\[ \\norm{\\LL^{\\pinv/2}\\ww_{\\mathrm{new}}(e')\\bb_{e'}\\bb_{e'}^{\\trp}\\LL^{\\pinv/2}} \\leq R. \\]\n\\end{lemma}\n\\begin{proof}\n  Let $\\ww=\\ww_{\\SS}$ for simplicity. Consider a sampled edge between $i$ and $j$ with weight $\\ww_{\\mathrm{new}}(i,j) = \\ww(i,v)\\ww(j,v)/(\\ww(i,v)+\\ww(j,v))$.\n  \\begin{align*}\n    \\norm{\\LL^{\\pinv/2} \\ww_{\\mathrm{new}}(i,j) \\bb_{ij}\\bb_{ij}^{\\trp}\\LL^{\\pinv/2}}\n    &= \\ww_{\\mathrm{new}}(i,j) \\norm{\\LL^{\\pinv/2} \\bb_{ij}\\bb_{ij}^{\\trp}\\LL^{\\pinv/2}} \\\\\n    &= \\ww_{\\mathrm{new}}(i,j) \\norm{ \\LL^{\\pinv/2}\\bb_{ij} }^2 \\\\\n    &\\leq \\ww_{\\mathrm{new}}(i,j) \\left( \\norm{\\LL^{\\pinv/2}\\bb_{iv}}^2 + \\norm{\\LL^{\\pinv/2}\\bb_{jv}}^2 \\right) \\\\\n    &= \\frac{\\ww(j,v)}{\\ww(i,v)+\\ww(j,v)} \\norm{\\LL^{\\pinv/2} \\ww(i,v)\\bb_{iv}\\bb_{iv}^{\\trp}\\LL^{\\pinv/2}} + \\\\\n    & ~\\quad \\frac{\\ww(i,v)}{\\ww(i,v)+\\ww(j,v)} \\norm{\\LL^{\\pinv/2} \\ww(j,v)\\bb_{jv}\\bb_{jv}^{\\trp}\\LL^{\\pinv/2}} \\\\\n    &\\leq \\frac{\\ww(j,v)}{\\ww(i,v)+\\ww(j,v)} R + \\frac{\\ww(i,v)}{\\ww(i,v)+\\ww(j,v)} R \\\\\n    &= R\n  \\end{align*}\n  The first inequality uses the triangle inequality of effective\n  resistance in $\\LL$, in that effective resistance is a distance as\n  we proved in Chapter~\\ref{cha:pinver}. The second inequality just uses the conditions of this lemma.\n\\end{proof}\n\\begin{remark}\n  Lemma \\ref{lem:cliquesample_bounded_norm} only requires that each single multiedge has small norm instead of that the sum of all edges between a pair of vertices have small norm. And this lemma tells us, after sampling, each multiedge in the new graph still satisfies the bounded norm condition.\n\\end{remark}\nFrom the Lemma, we can conclude that each edge sample $\\YY_{\\pi(i),e}$\nsatisfies\n$\\norm{\\Phi(\\YY_{\\pi(i),e})} \\leq R$\nprovided the assumptions of the\nLemma hold. Let's record this observation as a Lemma.\n\\begin{lemma}\n  If for all $e \\in \\vstar{v}{\\SS_i}$,\n  \\[\n    \\norm{\\Phi(\\ww_{\\SS_i }(e)\\bb_{e} \\bb_{e}^{\\trp})}\n    \\leq\n    R\n    .\n  \\]\n  then all $e \\in \\vstar{\\pi(i)}{\\SS_i}$,\n  \\[\n    \\norm{\\Phi(\\YY_{\\pi(i),e})} \\leq R\n .\n  \\]\n\\end{lemma}\n\n\\paragraph{Preprocessing by multi-edge splitting.}\nIn the original graph of Laplacian $\\LL$ of graph $G = (V,E,\\ww)$, we\nhave for each edge $\\hat{e}$ that\n\\[\n  \\ww(\\hat{e}) \\bb_{\\hat{e}}\\bb_{\\hat{e}}^{\\trp} \\preceq \\sum_e \\ww(e) \\bb_{e}\\bb_{e}^{\\trp}= \\LL\n\\]\nThis also implies that\n\\[\n  \\norm{\\LL^{\\pinv/2}  \\ww(\\hat{e})  \\bb_{\\hat{e}}\\bb_{\\hat{e}}^{\\trp} \\LL^{\\pinv/2} }\\leq 1.\n\\]\nNow, that means that if we split every original edge $e$ of the graph\ninto $K$ multi-edges $e_1, \\ldots e_K$, with a fraction $1/K$ of the\nweight, we get a new graph $G' = (V, E', \\ww')$ such that\n\\begin{claim}\n  \\label{clm:edgesplit}\n  \\noindent\n  \\begin{enumerate}\n  \\item $G'$ and $G$ have the same graph Laplacian.\n  \\item $\\abs{E'} = K\\abs{E}$\n  \\item For every multi-edge in $G'$\n    \\[\n      \\norm{\\LL^{\\pinv/2} \\ww'(e) \\bb_{e}\\bb_{e}^{\\trp} \\LL^{\\pinv/2}\n      }\\leq 1/K.\n    \\]\n  \\end{enumerate}\n\\end{claim}\nBefore we run Approximate Gaussian Elimination, we are going to do\nthis multi-edge splitting to ensure we have control over multi-edge\nsample norms.\n%\nCombined with Lemma~\\ref{lem:cliquesample_bounded_norm} immediately\nestablishes the next lemma, because we start off with all multi-edges\nhaving bounded norm and only produce multi-edges with bounded norm.\n\\begin{lemma}\n  \\label{lem:edgesampnorm}\n  When Algorithm~\\ref{alg:apxge} is run on the (multi-edge) Laplacian of $G'$,\n  arising from splitting edges of $G$ into $K$ multi-edges, the every\n  edge sample $\\YY_{\\pi(i),e}$ satisfies\n  \\[\n    \\norm{\\Phi(\\YY_{\\pi(i),e})} \\leq 1/K\n .\n  \\]\n\\end{lemma}\nAs we will see later $K = 200 \\log^2 n$ suffices.\n\n\\subsection{Random Matrix Concentration from Trace Exponentials}\nLet us recall how matrix-valued variances come into the picture when\nproving concentration following the strategy from Matrix Bernstein in\nChapter~\\ref{cha:randmat}.\n\nFor some matrix-valued random variable $\\XX \\in \\symsetn$,\nwe'd like to show $\\Pr[ \\norm{\\XX} \\leq 0.5 ]$.\nUsing Markov's inequality, and some observations about matrix\nexponentials and traces, we saw that for all $\\theta > 0$,\n\\begin{equation}\n  \\label{eq:masterprob}\n  \\Pr[ \\norm{\\XX} \\geq 0.5 ]\n  \\leq\n  \\exp(-0.5\\theta ) \\left(\\E{\\trace{ \\exp\\left(\\theta \\XX\\right)}}\n  +\n  \\E{\\trace{ \\exp\\left(-\\theta \\XX\\right)}}\n  \\right)\n  .\n\\end{equation}\nWe then want to bound $\\E{\\trace{ \\exp\\left(\\theta \\XX\\right)}}$\nusing Lieb's theorem.\nWe can handle $\\E{\\trace{ \\exp\\left(-\\theta \\XX\\right)}}$ similarly.\n\\begin{theorem}[Lieb]\n  \\label{thm:Lieb}\n  Let $f:S^n_{++}\\to\\R$ be a matrix function given by\n  \\[ f(\\AA) = \\trace{\\exp\\left(\\HH+\\log(\\AA)\\right)} \\]\n  for some $\\HH\\in S^n$. Then $-f$ is convex (i.e. $f$ is concave).\n\\end{theorem}\nAs observed by Tropp, this is useful for proving matrix concentration statements.\nCombined with Jensen's inequality, it gives that for a random matrix\n$\\XX \\in \\symsetn $ and a fixed $\\HH \\in \\symsetn$\n\\[\n  \\E{\\trace{ \\exp\\left(\\HH+\\XX\\right)}}\n    \\leq\n    \\trace{ \\exp\\left(\\HH+\\log(\\E{\\exp(\\XX)})\\right)}\n  .\n\\]\nThe next crucial step was to show that it suffices to obtain an upper\nbound on the matrix $\\E{\\exp(\\XX)}$ w.r.t the Loewner order.\nUsing the following three lemmas, this conclusion is an immediate\ncorollary.\n\\begin{lemma}\\label{lem:trexpmono}\n  If $\\AA\\preceq\\BB$, then $\\trace{\\exp(\\AA)}\\leq\\trace{\\exp(\\BB)}$.\n  % i.e. $\\ZZ \\mapsto \\trace{\\exp(\\ZZ)}$ is monotone increasing.\n\\end{lemma}\n\\begin{lemma}\\label{lem:logmono}\n  If $0\\prec\\AA\\preceq\\BB$, then $\\log(\\AA)\\preceq\\log(\\BB)$.\n\\end{lemma}\n\\begin{lemma}\\label{lem:ineq_log}\n  $\\log(\\II+\\AA) \\preceq \\AA$ for $\\AA\\succ-\\II$.\n\\end{lemma}\n%\n\\begin{corollary}\n  \\label{cor:trexpub}\n  For a random matrix\n  $\\XX \\in \\symsetn $ and a fixed $\\HH \\in \\symsetn$,\n  if $\\E{\\exp(\\XX)} \\preceq \\II + \\UU$ where $\\UU \\succ -\\II$, then\n\\[\n  \\E{\\trace{ \\exp\\left(\\HH+\\XX\\right)}}\n    \\leq\n    \\trace{ \\exp\\left(\\HH+\\UU\\right)}\n  .\n\\]\n\\end{corollary}\n\n% \\begin{corollary}\\label{cor:trexpmono}\n%   If $\\AA\\preceq\\BB$, then $\\trace{\\exp(\\AA)}\\leq\\trace{\\exp(\\BB)}$,\n%   i.e. $\\XX \\mapsto \\trace{\\exp(\\XX)}$ is monotone increasing.\n% \\end{corollary}\n% \\begin{lemma}\\label{lem:logmono}\n%   If $0\\prec\\AA\\preceq\\BB$, then $\\log(\\AA)\\preceq\\log(\\BB)$.\n% \\end{lemma}\n\n\\subsection{Mean-Exponential Bounds from Variance Bounds}\nTo use Corollary~\\ref{cor:trexpub}, we need to construct useful upper\nbounds on $\\E{\\exp(\\XX)}$.\nThis can be done, starting from the following lemma.\n\\begin{lemma}\\label{lem:ineq_exp}\n  $\\exp(\\AA) \\preceq \\II + \\AA + \\AA^2$ for $\\|\\AA\\|\\leq1$.\n\\end{lemma}\nIf $\\XX$ is zero-mean and $\\norm{\\XX} \\leq 1$,\nthis means that $\\E{\\exp(\\XX)} \\preceq \\II + \\E{\\XX^2}$,\nwhich is how we end up wanting to bound the matrix-valued variance $\\E{\\XX^2}$.\nIn the rest of this Subsection, we're going to see the matrix-valued variance of the stopped\nmartingale is bounded throughout the algorithm.\n\nFirstly, we note that for a single edge sample $\\XXtil_{i,e}$,\nby Lemma~\\ref{lem:edgesampnorm}, we have that\n\\[\n  \\norm{\\XXtil_{i,e}} \\leq\n  \\norm{\\Phi\\left( \\YY_{\\pi(i),e} - \\E{\\YY_{\\pi(i),e}} \\right)}\n    \\leq 1/K,\n\\]\nusing that $\\norm{\\AA-\\BB} \\leq \\max( \\norm{\\AA}, \\norm{\\BB} )$, for\n$\\AA, \\BB \\succeq \\matzero$, and $\\norm{\\E{\\AA}} \\leq \\E{\\norm{\\AA}}$\nby Jensen's inequality.\n\nThus, if $0 < \\theta \\leq K$, we have that\n\\begin{align}\n  \\label{eq:edgelogexp}\n  \\E{ \\exp(\\theta \\XXtil_{i,e}) \\mid \\text{preceding samples} }\n  &\\preceq\n      \\II +\n    \\E{(\\theta \\XXtil_{i,e})^2 \\mid \\text{preceding samples} }\n  \\\\ \\nonumber   &\\preceq\n        \\II +\n    \\frac{1}{K}\\theta^2\\cdot\n    \\E{\\Phi(\\YY_{\\pi(i),e}) \\mid \\text{preceding samples} }\n\\end{align}\n% \\begin{lemma}\n%   \\label{lem:edgelogexp}\n%   \\[\n%     \\log \\Ex{\\XX_{v_i,d_i-1}}\\exp(\\theta\\XX_{v_i,d_i}) \\preceq\n%     \\theta^2 R \\cdot\n%     \\Ex{\\XX_{v_i,d_i-1}}\\Phi(\\YY_{v_i,d_i})\n%   \\]\n% \\end{lemma}\n\n\n\n\\subsection{The Overall Mean-Trace-Exponential Bound}\n\nWe will use $\\Ex{(<i)} $ to denote expectation over variables preceding the\n$i$th elimination step.\nWe are going to refrain from explicitly writing out conditioning in\nour expectations, but any \\emph{inner} expectation that appears inside another\n\\emph{outer} expectation should be taken as conditional on the outer\nexpectation.\nWe are going to use $d_i$ to denote the multi-edge degree of vertex\n$\\pi(i)$ in $\\SS_{i-1}$. This is exactly the number of edge samples in\nthe $i$th elimination.\nNote that there is no elimination at step $n$ (the algorithm is\nalready finished). As a notational convenience, let's write $\\hat{n} =\nn-1$.\nWith all that in mind, we bound the mean-trace-exponential for some\nparameter\n$0 <\\theta \\leq 0.5/\\sqrt{K}$\n\\begin{align}\n    \\label{eq:fulltrexpub1}\n&  \\Ex{}\\trace{\\exp(\\theta\\sum_{i = 1}^{\\hat{n}}\\XXtil_{i} )}\n  \\\\ \\nonumber\n&  = \\Ex{(<\\hat{n})} \\Ex{\\pi(\\hat{n})} \\Ex{\\XXtil_{\\hat{n},1}} \\cdots \\Ex{\\XXtil_{\\hat{n},d_{\\hat{n}}-1}}  \\Ex{\\XXtil_{\\hat{n},d_{\\hat{n}}}}\n   \\tr\\exp\\left( \\underbrace{\\sum_{i = 1}^{\\hat{n}-1}\\theta\\XXtil_{i}\n     + \\sum_{e =1}^{d_{\\hat{n}}-1}\\theta\\XXtil_{\\hat{n},e}}_{\\HH}\n    +\\theta \\XXtil_{\\hat{n},d_{\\hat{n}}} \\right)\n   \\tag*{$\\XXtil_{\\hat{n},1} \\ldots, \\XXtil_{\\hat{n},d_{\\hat{n}}}$  are independent\n    conditional on $(<\\hat{n}), \\pi(\\hat{n})$\n  }\n\\\\  \\nonumber\n&  \\leq \\Ex{(<\\hat{n})} \\Ex{\\pi(\\hat{n})} \\Ex{\\XXtil_{\\hat{n},1}} \\cdots \\Ex{\\XXtil_{\\hat{n},d_{\\hat{n}}-1}}\n   \\tr\\exp\\left(\\sum_{i = 1}^{\\hat{n}-1}\\theta\\XXtil_{i}\n     +  \\sum_{e =1}^{d_{\\hat{n}}-1}\\theta\\XXtil_{\\hat{n},e}\n    +  \\frac{1}{K}\\theta^2\\cdot\n    \\Ex{\\XXtil_{\\hat{n},d_{\\hat{n}}}}{\\Phi(\\YY_{\\pi(\\hat{n}), d_{\\hat{n}}})}\n  \\right)\n  \\tag*{By Equation~\\eqref{eq:edgelogexp} and Corollary~\\ref{cor:trexpub}\n  .\n  }\n  \\\\ \\nonumber\n&  \\vdots\n \\tag*{ Repeat for each multi-edge sample $\\XXtil_{\\hat{n},1} \\ldots,\n       \\XXtil_{\\hat{n},d_{\\hat{n}}-1}$ }\n\\\\  \\nonumber\n&  \\leq  \\Ex{(<\\hat{n})} \\Ex{\\pi(\\hat{n})}\n   \\tr\\exp\\left(\\sum_{i = 1}^{\\hat{n}-1}\\theta\\XXtil_{i}\n     +  \\sum_{e =1}^{d_{\\hat{n}} }\n     \\frac{1}{K}\\theta^2\\cdot\n    \\Ex{\\XXtil_{\\hat{n},e}}{\\Phi(\\YY_{\\pi(\\hat{n}), e})}\n     \\right)\n \\\\  \\nonumber\n&  = \\Ex{(<\\hat{n})} \\Ex{\\pi(\\hat{n})}\n   \\tr\\exp\\left(\\sum_{i = 1}^{\\hat{n}-1}\\theta\\XXtil_{i}\n     +\n     \\frac{1}{K}\\theta^2\\Phi(\\vcliq{\\pi(\\hat{n})}{\\SS_{\\hat{n}-1}})\n  \\right)\n\\end{align}\nTo further bound the this quantity, we now need to deal with the\nrandom choice of $\\pi(\\hat{n})$.\nWe'll be able to use this to bound the trace-exponential in a very\nstrong way.\nFrom a random matrix perspective, it's the following few\nsteps that give the analysis it's surprising strength.\n\nWe can treat\n$\\frac{1}{K}\\theta^2\\Phi(\\vcliq{\\pi(\\hat{n})}{\\SS_{\\hat{n}-1}})$ as a random\nmatrix.\nIt is not zero-mean, but we can still bound the trace-exponential\nusing Corollary~\\ref{cor:trexpub}.\n\nWe can also bound the expected matrix exponential in\nthat case, using a simple corollary of Lemma~\\ref{lem:ineq_exp}.\n\\begin{corollary}\\label{cor:ineq_exp_cher}\n  $\\exp(\\AA) \\preceq \\II + (1+R)\\AA $\n  for $\\matzero \\preceq \\AA$ with $\\norm{\\AA} \\leq R \\leq 1$.\n\\end{corollary}\n\\begin{proof}\n  The conclusion follows after observing that for $\\matzero \\preceq \\AA$ with $\\norm{\\AA} \\leq R$,\n  we have $\\AA^2 \\preceq R \\AA$.\n  We can see this by considering the spectral decomposition of $\\AA$\n  and dealing with each eigenvalue separately.\n\\end{proof}\n\nNext, we need a simple structural observation about the cliques\ncreated by elimination:\n\\begin{claim}\n  \\label{clm:cliquevsstar}\n  \\[\n    \\vcliq{\\pi(i)}{\\SS_i} \\preceq \\vstar{\\pi(i)}{\\SS_i} \\preceq \\SS_i\n  \\]\n\\end{claim}\n\\begin{proof}\n  The first inequality is immediate from\n  $\n     \\vcliq{\\pi(i)}{\\SS_i} \\preceq   \\vcliq{\\pi(i)}{\\SS_i} + \\ll_i\\ll_i^\\trp\n     =\n     \\vstar{\\pi(i)}{\\SS_i}\n   $\n   .\n   The latter inequality $\\vstar{\\pi(i)}{\\SS_i} \\preceq \\SS_i$\n  follows from the star being a subgraph of the whole Laplacian $\\SS_i$.\n\\end{proof}\n\nNext we make use of the fact that $\\XXtil_{i}$ is from the\ndifference sequence of the \\emph{stopped} martingale.\nThis means we can assume\n\\[\n  \\SS_{i} \\preceq 1.5 \\LL,\n\\]\nsince\notherwise $\\XXtil_{i} = \\matzero$ and we get an even better\nbound on the trace-exponential.\nTo make this formal, in Equation~\\eqref{eq:fulltrexpub1},\nwe ought to do a case analysis that also includes\nthe case $\\XXtil_{i} = \\matzero$ when the martingale has\nstopped, but we omit this.\n\nThus we can conclude by Claim~\\ref{clm:cliquevsstar} that\n\\[\n  \\norm{\\Phi(\\vcliq{\\pi(i)}{\\SS_{i}})} \\leq 1.5.\n\\]\n\nBy our assumption $0 <\\theta \\leq 0.5/\\sqrt{K}$, we have\n$\\norm{\\frac{1}{K}\\theta^2\\Phi(\\vcliq{\\pi(i)}{\\SS_{i-1}})}\n\\leq 1$, so that by Corollary~\\ref{cor:ineq_exp_cher},\n\\begin{align}\n  \\Ex{\\pi(i)}\n  \\exp\\left(\\\n     \\frac{1}{K}\\theta^2\\Phi(\\vcliq{\\pi(i)}{\\SS_{i-1}})\n  \\right)\n  &\\preceq\n  \\II\n  +\n  \\frac{2}{K} \\theta^2\\Ex{\\pi(i)}\n    \\Phi(\\vcliq{\\pi(i)}{\\SS_{i-1}})\n  \\\\\n  &\\preceq\n  \\II\n  +\n  \\frac{2}{K} \\theta^2\\Ex{\\pi(i)}\n  \\Phi(\\vstar{\\pi(i)}{\\SS_{i-1}})\n  \\tag*{by Claim~\\ref{clm:cliquevsstar}.}\n\\end{align}\nNext we observe that, because every multi-edge appears in exactly two\nstars, and $\\pi(i)$ is chosen uniformly at random among the $n+1-i$\nvertices that $\\SS_{i-1}$ is supported on, we have\n\\[\n  \\Ex{\\pi(i)}\n  \\vstar{\\pi(i)}{\\SS_{i-1}}\n  =\n  2\\frac{1}{n+1-i}\\SS_{i-1}\n  .\n\\]\nAnd, since we assume $\\SS_{i} \\preceq 1.5 \\LL$, we further get\n\\[\n  \\Ex{\\pi(i)}\n  \\exp\\left(\\\n     \\frac{1}{K}\\theta^2\\Phi(\\vcliq{\\pi(i)}{\\SS_{i-1}})\n  \\right)\n  \\preceq\n  \\II\n  +\n  \\frac{6\\theta^2}{K(n+1-i)}\\II\n  .\n\\]\nWe can combine this with Equation~\\eqref{eq:fulltrexpub1} and\nCorollary~\\ref{cor:trexpub} to get\n\\begin{align*}\n  &  \\Ex{}\\trace{\\exp(\\theta\\sum_{i = 1}^{\\hat{n}}\\XXtil_{i} )}\n     \\\\*  \\nonumber\n  &  \\leq\n    \\Ex{(<\\hat{n})} \\Ex{\\pi(\\hat{n})}\n   \\tr\\exp\\left(\\sum_{i = 1}^{\\hat{n}-1}\\theta\\XXtil_{i}\n     +\n     \\frac{1}{K}\\theta^2\\Phi(\\vcliq{\\pi(\\hat{n})}{\\SS_{\\hat{n}-1}})\n    \\right)\n\\\\  \\nonumber\n  &  \\leq\n    \\Ex{(<\\hat{n})}\n   \\tr\\exp\\left(\\sum_{i = 1}^{\\hat{n}-1}\\theta\\XXtil_{i}\n     +\n    \\frac{6\\theta^2}{K(n+1-i)}\\II\n  \\right)\n\\end{align*}\nAnd by repeating this analysis for each term $\\XXtil_{i}$, we get\n\\begin{align*}\n \\Ex{}\\trace{\\exp(\\theta\\sum_{i = 1}^{\\hat{n}}\\XXtil_{i} )}\n&\\leq\n   \\tr\\exp\\left(\\sum_{i = 1}^{\\hat{n}}\n    \\frac{6\\theta^2}{K(n+1-i)}\\II\n    \\right)\n\\\\\n  &\\leq\n\\tr\\exp\\left(\n    \\frac{7\\theta^2\\log(n)}{K}\\II\n    \\right)\n\\\\\n  &=\n    n\\exp\\left(\n    \\frac{7\\theta^2\\log(n)}{K}\n    \\right)\n\\end{align*}\nThen, by choosing $K = 200 \\log^2 n$ and $\\theta = 0.5 \\sqrt{K}$,\nwe get\n\\[\n\\exp(-0.5 \\theta ) \\Ex{}\\trace{\\exp(\\theta\\sum_{i =\n    1}^{\\hat{n}}\\XXtil_{i} )}\n\\leq\n\\exp(-0.5 \\theta )\n n\\exp\\left(\n    \\frac{7\\theta^2\\log(n)}{K}\n  \\right)\n  \\leq\n  1/n^5.\n\\]\n$\\Ex{}\\trace{\\exp(-\\theta\\sum_{i =\n    1}^{\\hat{n}}\\XXtil_{i} )}$ can be bounded by an identical\nargument, so that Equation~\\eqref{eq:masterprob} gives\n\\[\n  \\Pr\\left[ \\norm{\n\\sum_{i =\n    1}^{\\hat{n}}\\XXtil_{i}\n  } \\geq 0.5 \\right] \\leq 2/n^5.\n  \\]\nThus we have established $\\norm{\n\\sum_{i =\n    1}^{\\hat{n}}\\XXtil_{i}\n  } \\leq 0.5 $ with high probability\n  (Equation~\\eqref{eq:zeromeanspectralnormgoal}), and this in turn\n  implies Equation~\\eqref{eq:spectralnormgoal}, and finally\n  Equation~\\eqref{eq:relerrgoal}:\n  \\[\n0.5 \\LL\n\\preceq\n\\matlow \\matlow^{\\trp}\n\\preceq 1.5 \\LL\n.\n\\]\n\nNow, all that's left to note is that the running time is linear in the\nmulti-edge degree of the vertex being eliminated in each iteration (and\nthis also bounds the number of non-zero entries being created in\n$\\matlow$).\nThe total number of multi-edges left in the remaining graph stays\nconstant at $K m = O(m\\log^2 n)$.\nThus the expected degree in the $i$th elimination is $K m/(n+i-1)$,\nbecause the remaining number of vertices is $n+i-1$.\nHence the total running time and total number of non-zero entries\ncreated can both be bounded as\n\\[\n  Km\\sum_i 1/(n+i-1) = O(m\\log^3 n)\n  .\n  \\]\nWe can further prove that the bound $O(m\\log^3 n)$ on running time and\nnumber of non-zeros in $\\LL$ holds with high probability\n(e.g. $1-1/n^5$).\nTo show this, we essentially need a scalar Chernoff bound, in except\nthe degrees are in fact not independent, and so we need a scalar\nmartingale concentration result, e.g. Azuma's Inequality.\nThis way, we complete the proof of Theorem~\\ref{thm:apxgauss}.\n\\FloatBarrier\n\n% \\todo{reenable lecture}\n%\\bibliographystyle{alpha}\n%\\bibliography{refs}\n\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: \"agao21_script\"\n%%% TeX-engine: luatex\n%%% End:", "meta": {"hexsha": "014ce4a2738d9bef9ed091ca547fc08e27582a6b", "size": 45824, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "agao21_script/lecture9_mod.tex", "max_stars_repo_name": "csssaz/agao21_script", "max_stars_repo_head_hexsha": "51044f4775e5e20d2c5fc5c0d035363e5beb66be", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-15T09:04:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T05:39:09.000Z", "max_issues_repo_path": "agao21_script/lecture9_mod.tex", "max_issues_repo_name": "csssaz/agao21_script", "max_issues_repo_head_hexsha": "51044f4775e5e20d2c5fc5c0d035363e5beb66be", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "agao21_script/lecture9_mod.tex", "max_forks_repo_name": "csssaz/agao21_script", "max_forks_repo_head_hexsha": "51044f4775e5e20d2c5fc5c0d035363e5beb66be", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-03-11T12:35:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T06:04:51.000Z", "avg_line_length": 36.0818897638, "max_line_length": 362, "alphanum_fraction": 0.6598507332, "num_tokens": 16569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.3475470146064504}}
{"text": "\\documentclass[11pt]{article}\n\n\n% preamble\n\\usepackage[margin=1in]{geometry}\n\\usepackage{palatino}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{mathpazo}\n\\usepackage{setspace}\n\\usepackage{float}\n\\usepackage{enumitem}  % control the indentation value of an enumerate environment\n\\usepackage{hyperref}\n\\usepackage{siunitx}\n\\sisetup{\n  round-mode = places,\n  round-precision = 2,\n}\n\n\\usepackage[backend=bibtex,style=ieee]{biblatex}\n\\bibliography{advanced_algorithms}\n\n\\usepackage[type={CC}, modifier={by-nc-sa}, version={3.0},]{doclicense}  % license\n\n\\usepackage{algpseudocode}  % pseudocode block\n\\usepackage{algorithm}  % pseudocode block\n\n\\usepackage{pgf,tikz,pgfplots}  % draw mathematics graphs\n\\pgfplotsset{compat=1.15}\n\\usepackage{mathrsfs}\n\\usetikzlibrary{arrows}\n% \\pagestyle{empty}  % suppress subsequent page numbers\n\\renewcommand{\\figurename}{\\hspace{-12mm}Example}  % override default figure caption title\n\n\\title{Exercises for Advanced Algorithms}\n\\author{Solution by: \\href{mailto:neo-mashiro@hotmail.com}{Wentao Lu}}\n\\date{}\n\n\n% document\n\\begin{document}\n  \\newcommand{\\solution}{\\noindent \\textbf{\\textsc{Solution:}} \\dotfill \\vspace{2mm}}  % solution title\n  \\definecolor{ffqqqq}{rgb}{1,0,0}  % node color in hypercube\n  \\definecolor{qqqqff}{rgb}{0,0,1}  % node color in hypercube\n\n  \\maketitle\n  \\pagenumbering{arabic}\n\n  % \\rule[raise]{width}{height}\n  \\noindent \\hspace{\\fill} Models of computation \\rule[0mm]{20mm}{2mm} (20\\%)\\\\\n  \\hspace*{\\fill} NP-complete \\rule[0mm]{55mm}{2mm} (55\\%)\\\\\n  \\hspace*{\\fill} Approximation algorithms \\rule[0mm]{40mm}{2mm} (40\\%)\\\\\n  \\hspace*{\\fill} Linear programming \\rule[0mm]{30mm}{2mm} (30\\%)\\\\\n  \\hspace*{\\fill} Computational geometry \\rule[0mm]{30mm}{2mm} (30\\%)\\\\\n  \\hspace*{\\fill} Parallel models and algorithms \\rule[0mm]{40mm}{2mm} (40\\%)\n\n  \\section{NP-complete}\n    Provide a proof of NP-completeness for the two-machine scheduling problem by formulating a reduction from the knapsack problem and state its corresponding optimization problem.\n    \\begin{itemize}[leftmargin=*]\n      \\item \\textsc{Two-machine scheduling:} Given the execution time $a_1, a_2 \\dots, a_n$ of $n$ independent tasks and a deadline $D$, is it possible to schedule the $n$ tasks on two identical machines in a non-preemptive fashion (meaning that once a task starts executing it must run to completion) such that all the task complete by the deadline $D$.\n      \\item \\textsc{Knapsack:} Given $n$ objects with volumes $v_i$ and prices $s_i$, \\(1 \\le i \\le n\\), a knapsack of volume $V$, and a constant $S > 0$, is there a subset $N' \\subseteq \\{1, \\dots, n\\}$ such that $\\Sigma_{i \\in N'} v_i < V$ (the objects in $N'$ can be placed in the knapsack) and $\\Sigma_{i \\in N'} s_i \\geq S$ (their price exceeds the given limit $S$)?\n    \\end{itemize}\n\n    \\solution\\\\\n    The complete proof consists of two steps. Given any candidate solution (purported certificate) of this problem which divides the $n$ independent tasks into two bins, we can easily compute the total execution time of tasks in each bin, and then check if both of them $\\leq D$. Since the solution can be verified in linear time, by definition\\autocite[1049]{Cormen09} it is an NP problem.\\\\\n\n    After Stephen Cook proved 3-SAT to be the first known NP-complete problem in 1971\\autocite{Cook71}, the next year Richard Karp further proved that another 21 common computational problems are all NP-complete\\autocite{Karp72}, one of which is the knapsack problem. To prove NP-hardness, we will show that the knapsack problem is reducible to the two-machine scheduling problem.\\\\\n\n    For every instance of the knapsack problem, construct $n + 2$ independent tasks with execution time $\\{a_1, \\dots, a_{n+2}\\}$ and a deadline $D = \\Sigma_{i=1}^{n} a_i + 2$. Let\n    \\begin{align*}\n      a_i     &= v_i + s_i \\,,\\, 1 \\le i \\le n\\\\\n      a_{n+1} &= \\Sigma_{i \\in P} v_i + \\Sigma_{i \\in P} s_i + 2\\\\\n      a_{n+2} &= \\Sigma_{i=1}^{n} a_i - \\Sigma_{i \\in P} v_i - \\Sigma_{i \\in P} s_i + 2\n    \\end{align*}\n\n    where $P$ denotes the set of items placed in the knapsack. It is evident that this mapping takes polynomial time in the size of input. Now let's prove that this translation is indeed a reduction.\\\\\n\n    $\\Rightarrow$ First, suppose that the knapsack problem has a true instance, which means there is indeed a subset of items $P \\subseteq \\{1, \\dots, n\\}$ such that\n    \\begin{align*}\n      \\Sigma_{i \\in P} v_i &< V\\\\\n      \\Sigma_{i \\in P} s_i &\\geq S\n    \\end{align*}\n\n    Let\n    \\begin{align*}\n      M_1 &= \\{a_i \\mid i \\in P\\} \\cup \\{a_{n+2}\\}\\\\\n      M_2 &= \\{a_i \\mid i \\notin P\\} \\cup \\{a_{n+1}\\}\n    \\end{align*}\n\n    Then we have\n    \\begin{align}\n      \\text{the sum of } M_1 &= \\Sigma_{i \\in P} v_i + \\Sigma_{i \\in P} s_i + \\Sigma_{i=1}^{n} a_i - \\Sigma_{i \\in P} v_i - \\Sigma_{i \\in P} s_i + 2 = \\Sigma_{i=1}^{n} a_i + 2\\\\\n      \\text{the sum of } M_2 &= \\Sigma_{i=1}^{n} a_i - \\Sigma_{i \\in P} v_i - \\Sigma_{i \\in P} s_i + \\Sigma_{i \\in P} v_i + \\Sigma_{i \\in P} s_i + 2 = \\Sigma_{i=1}^{n} a_i + 2\n    \\end{align}\n\n    From (1) and (2), it's clear that we have $M_1=M_2=D$, also notice that $M_1 \\cup M_2 $ is the set of all tasks, therefore we have found a feasible schedule for two identical machines.\\\\\n\n    $\\Leftarrow$ Conversely, suppose that the translated two-machine scheduling problem has a true instance, so the set of $n + 2$ independent tasks can be divided into two subsets, which can be scheduled on two machines $M_1$ and $M_2$, respectively, by the deadline $D = \\Sigma_{i=1}^{n} a_i + 2$.\\\\\n\n    Since execution time must be nonnegative, and notice that $a_{n+1} + a_{n+2} = \\Sigma_{i=1}^{n} a_i + 4>D$, this means $a_{n+1}$ and $a_{n+2}$ must not be executed on the same machine. Without loss of generality, assume that $a_{n+2}$ is scheduled on $M_2$, then the execution time of the rest of the tasks scheduled on $M_2$ must sum up to\n    \\begin{align*}\n      D - a_{n+2} = \\Sigma_{i=1}^{n} a_i + 2 - a_{n+2} = \\Sigma_{i \\in P} v_i + \\Sigma_{i \\in P} s_i\n    \\end{align*}\n\n    As per our reduction assumption, it imples that this subset $P \\subseteq \\{1, \\dots, n\\}$ has the property\n    \\begin{align*}\n      \\Sigma_{i \\in P} v_i &< V\\\\\n      \\Sigma_{i \\in P} s_i &\\geq S\n    \\end{align*}\n\n    Thus, it makes a true instance of the knapsack problem as well.\\\\\n\n    Now we have \\textsc{Knapsack} $\\leq_p$ \\textsc{Two-machine scheduling}, which implies that the two-machine scheduling problem is at least as hard as the knapsack. This completes our proof that two-machine scheduling is also NP-complete.\\\\\n\n    The optimization variant of this is the so-called \\textit{makespan} problem, in our case with two machines denoted by $P2||C_{max}$\\autocite{Schuurman00}, which can be stated as: Given the execution time $a_1, a_2 \\dots, a_n$ of $n$ independent tasks, find a way to schedule the $n$ tasks on two identical parallel machines in a non-preemptive fashion, so as to minimize the maximum task completion time. In other words, we would like to do our best to equally assign the $n$ tasks to both machines, such that the total execution time on the machine that finishes last is minimized. This variant is NP-hard.\\autocite{Karp72}\n\n  \\section{Approximate Maximum Clique}\n    Let $G = (V,E)$ be an undirected graph. For integer $k \\geq 1$ define $G^{(k)} = (V^{(k)}, E^{(k)})$ such that $V^{(k)} = \\{(v_1, v_2, \\dots, v_k) | v_i \\in V, 1 \\leq i \\leq k\\}$ and $((v_1, v_2, \\dots, v_k), (w_1 ,w_2 ,\\dots ,w_k)) \\in E^{(k)}$ iff either $(v_i, w_i) \\in E$ or $v_i = w_i$ for all $1 \\leq i \\leq k$.\n    \\begin{enumerate}[leftmargin=*]\n      \\item Prove $|C^{(k)}| = |C|^k$, where $C^{(k)}$ and $C$ are the maximum cliques of $G^{(k)}$ and $G$, respectively.\n      \\item Argue that the existence of an approximation algorithm for finding the maximum clique with a constant approximation ratio implies the existence of a polynomial-time approximation scheme for finding the maximum clique.\n    \\end{enumerate}\n\n    \\solution\n    \\begin{enumerate}[leftmargin=*, topsep=0pt]\n      \\item Let $V' = \\{(v_1, v_2, \\dots, v_k) | v_i \\in C, 1 \\leq i \\leq k\\} \\subseteq V^{(k)}$, where $C$ is the maximum clique of $G$, so every pair of vertices $(v_i, v_j)$ is adjacent, clearly $V'$ is a clique of $G^{(k)}$. Since each element $v_i$ in the $k$-tuple $(v_1, v_2, \\dots, v_k)$ comes from $C$, the size of $V'$ is $|C|^k$. Therefore, the size of the maximum clique of $G^{(k)}$ is at least $|C|^k$. We will prove by induction that this is indeed the size of the maximum clique.\n\n      In the base case, when $k = 1$, $G^{(1)} = G$, we have $|C^{(1)}| = |C|^1$. Now suppose that $|C^{(k)}| = |C|^k$ is true for $1 \\leq i \\leq k$. Let $C^{(k+1)} = \\{(p_i, v_1, v_2, \\dots, v_k)\\}$ where $p_i$ is some vertex in $G$.\n\n      Since the adjacency condition of $(v_1, v_2, \\dots, v_k)$ and $(w_1, w_2, \\dots, w_k)$ only requires the adjacency of $v_i$ and $w_i$, the choice of vertices at index $i$ is independent of vertices at any other index. Hence, if we remove the prefix vertex $p_i$ from every tuple in $C^{(k+1)}$, the remaining $k$-tuples must form a maximum clique of $G^{(k)}$, otherwise we can always do better. By induction hypothesis, it has size $|C|^k$.\n\n      In order to make $C^{(k+1)}$ a clique of $G^{(k+1)}$, we must choose a set of prefixes $\\{p_i\\} \\subseteq V$ such that every pair of vertices $(p_i, p_j)$ is connected by an edge. Moreover, to make it a maximum clique, we also want to maximize the number of prefixes we choose. In other words, we are trying to find a maximum set of mutually adjacent vertices from $G$ and prepend them to every $k$-tuple in $C^{(k)}$, so we should choose the set of prefix vertices $\\{p_i\\} = C$. Therefore, the size of $C^{(k+1)}$ is $|C|^k \\times |C| = |C|^{k+1}$.\n\n      \\item Given a $c$-approximation algorithm for finding the maximum clique, we can apply it on $G^{(k)}$ and obtain a clique of size $n$, while the true maximum clique of $G^{(k)}$ has size $|C|^k$.\n\n      By definition of an approximation ratio, $|C|^k/n \\leq c$, so we have $|C|/n^{1/k} \\leq c^{1/k}$. For any $\\varepsilon > 0$, we can choose a positive integer $k > \\log_{1+\\varepsilon}{c}$, then $|C|/n \\leq |C|/n^{1/k} \\leq c^{1/k} < 1 + \\varepsilon$. Since it is polynomial in the size of input, so we have a polynomial-time approximation scheme for finding the maximum clique.\n    \\end{enumerate}\n\n  \\section{Linear Inequality Feasibility}\n    Given a set of $m$ linear inequalities over $n$ variables, the linear inequality feasibility problem asks whether there exists a set of the instances that satisfies all the linear inequalities simultaneously.\n    \\begin{enumerate}[leftmargin=*]\n      \\item Prove that we can use an algorithm for linear programming to solve linear inequality feasibility problems. The number of variables and constraints used in the linear programming problem must be polynomial in $n$ and $m$.\n      \\item Prove that we can use an algorithm for the linear inequality feasibility problem to solve linear programming problems. The number of variables and linear inequalities must be polynomial in the number of variables and constraints of the linear program.\n    \\end{enumerate}\n\n    \\solution\n    \\begin{enumerate}[leftmargin=*, topsep=0pt]\n      \\item Given a set of linear inequalities, we can simply formulate the equality feasibility problem as a linear program. First, we can set the objective function to be a constant such as 0 because there's nothing to maximize or minimize in this case. Next, we need to transform those linear inequalities into their slack form, and then apply the simplex algorithm. If the linear program returns a feasible solution, it implies that all the linear inequalities can be satisfied at the same time. Otherwise, those linear inequalities are not feasible. The variables and constraints in the linear program are exactly the same as in the equality feasibility problem so they are polynomial in $n$ and $m$.\n\n      \\item Given a linear program in standard form, we want to maximize the objective function $\\Sigma_{j=1}^{n} c_jx_j$ with $n$ variables, subject to $m$ constraints $\\Sigma_{j=1}^{n} a_{ij}x_j \\leq b_i, 1 \\leq i \\leq m$. Suppose we have an algorithm for the linear inequality feasibility problem, then we can apply it on the $m$ constraints of the linear program. If the algorithm fails to find a solution for the linear inequality feasibility problem, it means that those inequalities can not be satisfied, so the linear program should return infeasible. If the algorithm does find an assignment of the $n$ variables that satisfies all the linear inequalities, then the linear program is also feasible.\n\n      In order to solve the linear program and maximize the objective function, in each step we first calculate the value of our objective function using the assignment values returned by that algorithm, then we update the linear program by introducing a new constraint. For example, if the algorithm finds an assignment $\\overline{x}$ which gives an objective function value of $\\Sigma_{j=1}^{n} c_jx_j = k$, we will add another constraint $\\Sigma_{j=1}^{n} c_jx_j > k$ to the original linear program. As long as this updated linear program is feasible, it must be equivalent to the original linear program because both the objective function and all other constraints are not affected. If we iteratively run this step, we are getting closer to the optimal solution. We will repeat this step until the algorithm detects that the updated constraints are not feasible anymore, in which case we stop and return the last calculated objective function value as the optimal solution.\n\n      Whenever the algorithm returns a feasible assignment so that all constraints are satisfied, it represents a point that's somewhere in the simplex. The basic idea is to update that point until it reaches a local maximum, which is also a global maximum because the simplex is convex. Since we are only adding 1 more constraint in each step, we can optimistically assume that the number of linear inequalities is polynomial in the number of constraints. If that's not true, we can modify the constraint to be $\\Sigma_{j=1}^{n} c_jx_j > k + \\alpha$, where $\\alpha$ is a reasonable step size to choose in different trials. Unless the original linear program has an unbounded solution, we will eventually converge to an optimal solution.\n    \\end{enumerate}\n\n  \\section{Ghostbusters and Ghosts}\n    A group of $n$ ghostbusters is battling $n$ ghosts. Each buster carries a proton pack, which shoots a stream at a ghost, eradicating it. A stream goes in a straight line and terminates when it hits the ghost. The ghostbusters decide upon the following strategy: They will pair off with the ghosts, forming $n$ ghostbuster-ghost pairs, and then simultaneously each ghostbuster will shoot a stream at his chosen ghost. As we all know, it is \\textit{very} dangerous to let streams cross, and so the busters must choose pairings for which no streams will cross. Assume that the position of each buster and each ghost is a fixed point in the plane and that no three positions are colinear.\n    \\begin{enumerate}[leftmargin=*]\n      \\item Argue that there exists a line passing through one Ghostbuster and one ghost such that the number of Ghostbusters on one side of the line equals the number of ghosts on the same side. Describe how to find such a line in $O(n \\log n)$ time.\n      \\item Give an $O(n^2 \\log n)$-time algorithm to pair Ghostbusters with ghosts such that no streams cross.\n    \\end{enumerate}\n\n    \\solution\n    \\begin{figure}[H]\n      \\centering\n      \\begin{tikzpicture}\n        \\draw[black, dotted, thick]\n        (-0.5,0) -- (5.5,0)\n        (0,-0.5) -- (0,3.5);\n        \\draw[->](0,0) -- (5,1);\n        \\draw[->](0,0) -- (4,2);\n        \\draw[->](0,0) -- (5,2);\n        \\draw[->](0,0) -- (3,3);\n        \\draw[->](0,0) -- (3,2);\n        \\draw[->](0,0) -- (1,2);\n        \\draw[color=black] (-0.25,-0.25) node {$P_0$};\n        \\draw (5,1) node;\n        \\draw (4,2) node;\n        \\draw (5,2) node;\n        \\draw (3,3) node;\n        \\draw (3,2) node;\n        \\draw (1,2) node;\n        \\draw [fill=black] (5,1) circle (1.0pt);\n        \\draw [fill=black] (4,2) circle (1.0pt);\n        \\draw [fill=black] (5,2) circle (1.0pt);\n        \\draw [fill=black] (3,3) circle (1.0pt);\n        \\draw [fill=black] (3,2) circle (1.0pt);\n        \\draw [fill=black] (1,2) circle (1.0pt);\n        \\draw [fill=ffqqqq] (0,0) circle (1.5pt);\n      \\end{tikzpicture}\n      \\caption{Graham Scan}\n    \\end{figure}\n\n    \\begin{enumerate}[leftmargin=*, topsep=0pt]\n      \\item First we pick the leftmost bottom point $P_0$ as the origin. For the remaining points, we can easily sort them by polar angle in counterclockwise order. Concretely, the cross product $(P_1 - P_0) \\times (P_2 - P_0)$ gives us a comparison relationship between any two points $P_1$ and $P_2$, which can be applied to any comparison-based sorting algorithm such as merge sort.\n\n      Given the sorted points by polar angle with respect to $P_0$, we then visit them one by one in this order, and count the number of ghostbusters and ghosts along the way. We would stop at a point $P_k$ when the following two conditions are met:\n\n      \\begin{itemize}[leftmargin=*, topsep=0pt]\n          \\item Either $P_0$ is a ghostbuster and $P_k$ is a ghost, or $P_0$ is a ghost and $P_k$ is a ghostbuster.\n          \\item The number of ghostbusters and ghosts visited so far are equal (including $P_0$ and $P_k$).\n      \\end{itemize}\n\n      It follows that the line passing through $P_0$ and $P_k$ is the solution. Since the number of ghostbusters and ghosts are equal, we are guaranteed to find such a line. It takes $O(n\\log n)$ to sort and $O(n)$ to scan, so the running time is $O(n\\log n)$ in total.\n\n      \\item Now we have paired one ghostbuster with one ghost in $O(n\\log n)$ time, applying this algorithm recursively on both sides of this line will pair all the ghostbusters with ghosts.\n\n      That is, for the subset of points on each side, we choose the origin with the minimum coordinate, sort the remaining points on this side and then scan through them until we find a new line. During each recursion step, work done on one side of the line is independent from the other, so that no lines will ever cross. We need to find $n$ lines, so this divide-and-conquer approach runs in $O(n^2\\log n)$ time.\n    \\end{enumerate}\n\n  \\section{Divide and Conquer Prefix Computations}\n    We use again divide and conquer method to perform prefix computation (with $\\circ$ as binary operator) on a sequence $S$ of size $n$. This time the running time will be $O(\\log \\log n)$ time using $O(n/\\log \\log n)$ processors. This algorithm would be optimal, faster than the one mentioned in the book, but also using more processors. To obtain such an algorithm we proceed as follows:\n\n    \\begin{enumerate}[leftmargin=*]\n      \\item[a] Divide the sequence $S$ into $n^{1/2}$ subsequences of size $n^{1/2}$ each. Perform prefix computation on each sequence recursively using $n^{1/2}$ processors. Let the result of the computation on the $i$-th sequence be $s(i,1), s(i,2), \\dots, s(i,n^{1/2})$.\n      \\item[b] Perform a prefix computation on the sequence $s(1,n^{1/2}), s(2,n^{1/2}), \\dots, s(n^{1/2}-1,n^{1/2})$ using $n$ processors. Let the result of this computation be $s^\\prime(1,n^{1/2}), s^\\prime(2,n^{1/2}), \\dots, s^\\prime(n^{1/2}-1,n^{1/2})$.\n      \\item[c] For all $1 \\leq i < n^{1/2}$ use the binary operator $\\circ$ to combine $s^\\prime(i,n^{1/2})$ with all the elements of $s(i+1,1),s(i+1,2),\\dots,s(i+1,n^{1/2})$ using $n^{1/2}$ processors per subsequence.\n    \\end{enumerate}\n\n    \\begin{enumerate}[leftmargin=*]\n      \\item Show that the algorithm described above uses $n$ processors to run in $O(\\log \\log n)$ time.\n      \\item \\label{l} Show how the number of processors can be reduced to $O(n/\\log \\log n)$ while maintaining the $O(\\log \\log n)$ running time, thus achieving the optimal cost $O(n)$.\n      \\item Discuss the implications of the result obtained in Question \\ref{l} on related computations such as array packing.\n    \\end{enumerate}\n\n    \\solution\n    \\begin{enumerate}[leftmargin=*, topsep=0pt]\n      \\item In step 1 we recursively perform prefix computation on each subsequence of size $n^{1/2}$ using $n^{1/2}$ processors. Suppose our recursive algorithm on the entire sequence $S$ has running time $t(n)$, then the recursion call on each subsequence takes $t(n^{1/2})$. Since this is done in parallel, this step takes $t(n^{1/2})$.\n\n      In step 2, the sequence $s(1,n^{1/2}), s(2,n^{1/2}), \\dots, s(n^{1/2}-1,n^{1/2})$ contains every last element of a subsequence except the first one, so there are only $n^{1/2}-1$ elements, but we have $n$ processors available. We can take advantage of all of them by letting $n^{1/2}$ processors work on each element simultaneously, that is, for some element $s(i,n^{1/2})$, we use $n^{1/2}$ processors in parallel to perform binary operations on $s(i,n^{1/2})$ with all other elements $s(j,n^{1/2})$, where $j \\neq i, 1 \\leq j \\leq n^{1/2}-1$. Since we have $n$ processors so that all elements can update in parallel, this step takes $O(1)$. However, this does not work for all binary operations, in fact, the binary operation must be both associative and commutative, such as addition, multiplication and union, but not concatenation because concurrent writes would mess up the order. Besides, this speed up is possible only with the Combining CRCW PRAM model such that concurrent reads and writes can be effectively reconciled.\n\n      In step 3, for each subsequence we use $n^{1/2}$ processors to combine its elements with the last element in the preceding subsequence. Each element can be mapped to a processor, so this single operation is done in parallel, this step takes $O(1)$ time.\n\n      Now combining these results we have $t(n) = t(n^{1/2}) + O(1)$. To derive the running time from this equation, we substitute $n$ with $e^m$, so $t(e^m) = t(e^{m/2}) + O(1)$. Let $s(m) = t(e^m)$, then $s(m) = s(m/2) + O(1)$. According to the Master's Theorem, this implies that\n      \\begin{equation*}\n        s(m) = O(\\log m) \\hspace{3mm} \\Rightarrow \\hspace{3mm} t(n) = t(e^m) = s(m) = O(\\log m) = O(\\log \\log n)\n      \\end{equation*}\n\n      \\item If we want to reduce the number of processors to $O(n/\\log \\log n)$, the previous partition will not work, we need a new partition. Besides, we want to follow the previous three steps, but need to make some modifications.\n\n      In concrete, we will divide $S$ into $n/\\log \\log n$ subsequences or groups, each group has size $\\log \\log n$. Since the number of groups is equal to the number of processors, each group can only have one processor, so in step 1, prefix computation must be executed sequentially within each group, while all groups do this in parallel. Hence, this step takes $O(\\log \\log n)$.\n\n      In step 2, the sequence will be $s(1,\\log \\log n), s(2,\\log \\log n), \\dots, s(n/\\log \\log n-1,\\log \\log n)$ because we only have $n/\\log \\log n$ groups, processors and last elements. To perform prefix computation on this sequence, we will adopt the algorithm in Question 1. As we have shown in Question 1, that algorithm runs in $O(\\log \\log n)$ time on $n$ elements using $n$ processors, so here with $n/\\log \\log n$ elements and processors, it will take $O(\\log \\log(n/\\log \\log n))$ time to run. By removing the trivial terms, we have\n      \\begin{equation*}\n        O(\\log \\log(n/\\log \\log n)) = O(\\log(\\log n-\\log(\\log \\log n))) = O(\\log \\log n)\n      \\end{equation*}\n\n      In step 3, for the same reason as in step 1, the combining operation has to be executed sequentially for each group due to the lack of processors. As a result, each group takes $O(\\log \\log n)$ to run, while different groups run in parallel with each other. This step takes $O(\\log \\log n)$.\n\n      In summation, the total running time is $3 \\times O(\\log \\log n) = O(\\log \\log n)$ which is identical to the previous one, but the cost is optimal as we are now using less than $n$ processors.\n\n      \\item The result obtained in Question 2 has several implications.\n\n      We have seen that it is possible to devise an optimal parallel algorithm that takes a suboptimal algorithm as an intermediate step. The divide and conquer approach allows us to divide a problem into many subproblems which can be solved in parallel, and the way we partition the data can sometimes make a difference. In addition, different PRAM models may lead to different optimal algorithms to solve the same problem, we are free to choose among them depending on the scenario. This gives us a lot more flexibility from a practical perspective since the number of processors and hardware is often fixed in real world. For example, compared to the other optimal algorithm discussed in the class notes, this one is also optimal but much faster, so it can be very useful if we are strict on the running time and have sufficient processors that support CRCW PRAM models. It has also proved the possibility of applications being highly scalable based on commutative binary operations such as prefix sum. For example, the array packing problem uses addition as the underlying binary operation, so that as long as the hardware requirement is satisfied, it can easily scale up to boost performance, especially when the input array size is huge.\n    \\end{enumerate}\n\n  \\section{Descending in a Hypercube}\n    Let $N = 2^g$ data be stored in the processors of a hypercube, one value per processor (so that the value $x_i$ is stored in $P_i$, $0 \\leq i < N$). A technique with wide applicability to hypercube algorithms is called \\textsc{Descend} and consists of $g$ iterations. During the $j$-th iteration a basic binary operation \\textsc{Operation}$(P_i, P_l)$ is performed on data in cores whose indices differ by $2^j$. Here is the pseudocode for this process, with $i_{g-1}i_{g-2}\\dots i_{1}i_{0}$ the binary representation of index $i$:\n\n    \\newpage\n\n    \\begin{algorithm}\n      % \\renewcommand\\thealgorithm{}  % suppress the caption number\n      \\caption{\\textsc{Descend}}\n      \\label{ad}\n      \\begin{algorithmic}[1]\n        \\For{$j \\leftarrow g - 1$ \\textbf{to} $0$} \\Comment{iterate over each bit}\n          \\For{$i \\leftarrow 0$ \\textbf{to} $2^{g}-1$} \\Comment{iterate over each core}\n            \\If{$i_j = 0$}  \\textsc{Operation}$(P_i, P_{i+2^j})$\n              \\hspace{2mm}\\raisebox{.5\\baselineskip}[0pt][0pt]{$\\left.\\rule{0pt}{1.0\\baselineskip}\\right\\}\\ \\mbox{in parallel}$} \\Comment{operate on adjacent cores}\n      \\end{algorithmic}\n    \\end{algorithm}\n\n    \\noindent If \\textsc{Operation} requires constant time then \\textsc{Descend} runs in $O(\\log N)$ time. The dual to \\textsc{Descend} is \\textsc{Ascend}, in which $j$ in the outer loop varies from $0$ to $g-1$.\n\n    \\begin{enumerate}[leftmargin=*]\n      \\item Show how \\textsc{Descend} can be used to obtain an algorithm that computes the sum of all the values $x_i$ and places the result in $P_0$.\n      \\item Use either \\textsc{Ascend} or \\textsc{Descend} to broadcast the datum held by some processor $P_k$ to all the other processors.\n      \\item Suggest other problems that can be solved using these paradigms.\n    \\end{enumerate}\n\n    \\solution\\\\\n    If two integers differ by $2^k$, then in their binary representation, all bits must be the same except the $k$-th bit where they differ by 1. That is, in the $j$-th iteration of the \\textsc{Descend} algorithm, the binary operation is applied on any pair of processors whose indices differ only at the $j$-th bit. A bit can be either 0 or 1, only 2 possible values. Therefore, in each iteration, all processors are divided into halves by some bit, one half will exchange data with the other half via the binary operation. After $g$ iterations, we would have divided the set of processors bit by bit in every possible way, so that every processor has talked to all the other processors exactly once, either directly or indirectly.\n\n    \\begin{enumerate}[leftmargin=*]\n      \\item[1.] Since the addition operation is commutative, it doesn't matter if we loop from the highest bit or the lowest bit, so we don't mind whether the \\textsc{Descend} or \\textsc{Ascend} algorithm is being used. In order to place the final result in $P_0$ whose index is a bunch of zeros in binary format, during the $j$-th step we must store the sum of $P_i$ and $P_{i+2^j}$ into $P_i$ because $i_j=0$. Then after $g$ iterations, the value in each processor will be added exactly once to $P_0$. So we define\n      \\begin{enumerate}\n          \\item[] \\textsc{Operation}($P_i$, $P_{i+2^j}$) to be \\fbox{$P_i$ = $P_i$ + $P_{i+2^j}$}\n      \\end{enumerate}\n      As an example, we can graphically illustrate how it works in a 3 dimensional hypercube. In the figure below, processors $P_0,P_1,\\dots,P_7$ correspond to the 8 corner vertices of the cube, which are represented in their binary format as $(0,0,0),(0,0,1),\\dots,(1,1,1)$. For simplicity, suppose that initially each processor has value $x_i=1$, so we expect $P_0$ to be 8 in the end.\n\n      In the first iteration the algorithm looks at the highest bit, which is 0 for vertices on the left side and 1 for vertices on the right side. So as to perform the binary operation, values on the right side are added to those on the left. Vertices whose values have been updated are colored blue. Likewise, the second round looks at the middle bit, so values on the upper side are added to those on the lower side, and so forth. When the algorithm finishes, $P_0(0,0,0)$ has been involved in all iterations and colored blue for three times, hence it has the sum of all values and we color it red. In the end, we managed to compute the sum of 8 numbers in merely 3 steps.\n    \\end{enumerate}\n\n    % tex code generated by GeoGebra\n    \\begin{figure}[H]\n      \\centering\n      \\begin{tikzpicture}[line cap=round,line join=round,>=triangle 45,x=1cm,y=1cm]\n      \\clip(-1,-8.5) rectangle (16,6.6);\n      \\draw [line width=0.4pt] (3.5,-7.5)-- (5.5,-5.5);\n      \\draw [line width=0.4pt] (7.5,-7.5)-- (9.5,-5.5);\n      \\draw [line width=0.4pt] (3.5,-3.5)-- (5.5,-1.5);\n      \\draw [line width=0.4pt] (7.5,-3.5)-- (9.5,-1.5);\n      \\draw [line width=0.4pt] (0,0)-- (2,2);\n      \\draw [line width=0.4pt] (4,0)-- (6,2);\n      \\draw [line width=0.4pt] (0,4)-- (2,6);\n      \\draw [line width=0.4pt] (4,4)-- (6,6);\n      \\draw [line width=0.4pt] (8,0)-- (10,2);\n      \\draw [line width=0.4pt] (12,0)-- (14,2);\n      \\draw [line width=0.4pt] (8,4)-- (10,6);\n      \\draw [line width=0.4pt] (12,4)-- (14,6);\n      \\draw (0.7150220913107512,-0.25439503619441556) node[anchor=north west] {(a) right to left};\n      \\draw (8.676730486008838,-0.216132368148914) node[anchor=north west] {(b) top to bottom};\n      \\draw (4.332842415316643,-7.715615305067217) node[anchor=north west] {(c) back to front};\n      \\draw [line width=0.4pt] (0,4)-- (4,4);\n      \\draw [line width=0.4pt] (2,6)-- (6,6);\n      \\draw [line width=0.4pt] (0,0)-- (4,0);\n      \\draw [line width=0.4pt] (2,2)-- (6,2);\n      \\draw [line width=0.4pt] (0,4)-- (0,0);\n      \\draw [line width=0.4pt] (2,2)-- (2,6);\n      \\draw [line width=0.4pt] (6,2)-- (6,6);\n      \\draw [line width=0.4pt] (4,4)-- (4,0);\n      \\draw [line width=0.4pt] (14,6)-- (14,2);\n      \\draw [line width=0.4pt] (8,4)-- (12,4);\n      \\draw [line width=0.4pt] (10,6)-- (14,6);\n      \\draw [line width=0.4pt] (8,0)-- (12,0);\n      \\draw [line width=0.4pt] (10,2)-- (14,2);\n      \\draw [line width=0.4pt] (8,4)-- (8,0);\n      \\draw [line width=0.4pt] (12,0)-- (12,4);\n      \\draw [line width=0.4pt] (10,6)-- (10,2);\n      \\draw [line width=0.4pt] (5.5,-1.5)-- (9.5,-1.5);\n      \\draw [line width=0.4pt] (3.5,-3.5)-- (7.5,-3.5);\n      \\draw [line width=0.4pt] (9.5,-5.5)-- (9.5,-1.5);\n      \\draw [line width=0.4pt] (7.5,-7.5)-- (3.5,-7.5);\n      \\draw [line width=0.4pt] (5.5,-5.5)-- (5.5,-1.5);\n      \\draw [line width=0.4pt] (3.5,-3.5)-- (3.5,-7.5);\n      \\draw [line width=0.4pt] (9.5,-5.5)-- (5.5,-5.5);\n      \\draw [line width=0.4pt] (7.5,-3.5)-- (7.5,-7.5);\n      \\draw [->,line width=0.4pt,dash pattern=on 1pt off 1pt] (3.5,2.9) -- (0.5,2.9);\n      \\draw [->,line width=0.4pt,dash pattern=on 1pt off 1pt] (9.622754360465116,3.5725472383720938) -- (9.622754360465116,0.5725472383720931);\n      \\draw [->,line width=0.4pt,dash pattern=on 1pt off 1pt] (7,-3) -- (5,-5);\n      \\begin{scriptsize}\n      \\draw [fill=ffqqqq] (3.5,-7.5) circle (2.5pt);\n      \\draw[color=ffqqqq] (4.59499263622975,-7.193846949327817) node {(0,0,0) = 8};\n      \\draw [fill=qqqqff] (7.5,-7.5) circle (2.5pt);\n      \\draw[color=qqqqff] (8.100883652430046+0.5,-7.093846949327817-0.1) node {(1,0,0) = 4};\n      \\draw [fill=qqqqff] (7.5,-3.5) circle (2.5pt);\n      \\draw[color=qqqqff] (8.100883652430046+0.5,-3.0953981385729055-0.1) node {(1,1,0) = 2};\n      \\draw [fill=qqqqff] (3.5,-3.5) circle (2.5pt);\n      \\draw[color=qqqqff] (4.09499263622975+0.5,-3.0953981385729055-0.1) node {(0,1,0) = 4};\n      \\draw [fill=black] (5.5,-5.5) circle (2.5pt);\n      \\draw[color=black] (6.0979381443298974+0.2,-5.085056876938985-0.1) node {(0,0,1) = 4};\n      \\draw [fill=black] (9.5,-5.5) circle (2.5pt);\n      \\draw[color=black] (10.103829160530191+0.2,-5.085056876938985-0.1) node {(1,0,1) = 2};\n      \\draw [fill=black] (9.5,-1.5) circle (2.5pt);\n      \\draw[color=black] (10.103829160530191+0.2,-1.0866080661840742-0.1) node {(1,1,1) = 1};\n      \\draw [fill=black] (5.5,-1.5) circle (2.5pt);\n      \\draw[color=black] (6.0979381443298974+0.2,-1.0866080661840742-0.1) node {(0,1,1) = 2};\n      \\draw [fill=qqqqff] (0,0) circle (2.5pt);\n      \\draw[color=qqqqff] (1.1023564064801179,0.30563598759048614) node {(0,0,0) = 2};\n      \\draw [fill=black] (4,0) circle (2.5pt);\n      \\draw[color=black] (4.595729013254787+0.5,0.40563598759048614-0.1) node {(1,0,0) = 1};\n      \\draw [fill=black] (4,4) circle (2.5pt);\n      \\draw[color=black] (4.595729013254787+0.5,4.404084798345398-0.1) node {(1,1,0) = 1};\n      \\draw [fill=qqqqff] (0,4) circle (2.5pt);\n      \\draw[color=qqqqff] (0.6023564064801179+0.5,4.404084798345398-0.1) node {(0,1,0) = 2};\n      \\draw [fill=qqqqff] (2,2) circle (2.5pt);\n      \\draw[color=qqqqff] (2.6053019145802656+0.2,2.4144260599793173-0.1) node {(0,0,1) = 2};\n      \\draw [fill=black] (6,2) circle (2.5pt);\n      \\draw[color=black] (6.598674521354934+0.2,2.4144260599793173-0.1) node {(1,0,1) = 1};\n      \\draw [fill=black] (6,6) circle (2.5pt);\n      \\draw[color=black] (6.598674521354934+0.2,6.412874870734228-0.1) node {(1,1,1) = 1};\n      \\draw [fill=qqqqff] (2,6) circle (2.5pt);\n      \\draw[color=qqqqff] (2.6053019145802656+0.2,6.412874870734228-0.1) node {(0,1,1) = 2};\n      \\draw [fill=qqqqff] (8,0) circle (2.5pt);\n      \\draw[color=qqqqff] (9.10162002945508,0.30563598759048614) node {(0,0,0) = 4};\n      \\draw [fill=qqqqff] (12,0) circle (2.5pt);\n      \\draw[color=qqqqff] (12.59499263622975+0.5,0.40563598759048614-0.1) node {(1,0,0) = 2};\n      \\draw [fill=black] (12,4) circle (2.5pt);\n      \\draw[color=black] (12.59499263622975+0.5,4.404084798345398-0.1) node {(1,1,0) = 1};\n      \\draw [fill=black] (8,4) circle (2.5pt);\n      \\draw[color=black] (8.60162002945508+0.5,4.404084798345398-0.1) node {(0,1,0) = 2};\n      \\draw [fill=qqqqff] (10,2) circle (2.5pt);\n      \\draw[color=qqqqff] (10.604565537555228+0.2,2.4144260599793173-0.1) node {(0,0,1) = 4};\n      \\draw [fill=qqqqff] (14,2) circle (2.5pt);\n      \\draw[color=qqqqff] (14.597938144329897+0.2,2.4144260599793173-0.1) node {(1,0,1) = 2};\n      \\draw [fill=black] (14,6) circle (2.5pt);\n      \\draw[color=black] (14.597938144329897+0.2,6.412874870734228-0.1) node {(1,1,1) = 1};\n      \\draw [fill=black] (10,6) circle (2.5pt);\n      \\draw[color=black] (10.604565537555228+0.2,6.412874870734228-0.1) node {(0,1,1) = 2};\n      \\end{scriptsize}\n      \\end{tikzpicture}\n      \\vspace{-9mm}\n      \\caption{Parallel sum in a 3-hypercube}\n    \\end{figure}\n\n    \\begin{enumerate}[leftmargin=*]\n      \\item[2.] No matter which bit we start from, the \\textsc{Descend} or \\textsc{Ascend} algorithm always divides the processors by a different dimension in each round, then the binary operation is performed on pairs of processors, one from each group. Suppose that we use the \\textsc{Ascend} algorithm that loops from the $0$-th bit, further assume that $P_k$ has the datum set $\\{x\\}$ while other processors have no data ($\\emptyset$) initially. In order to broadcast, we can simply define\n      \\begin{enumerate}\n          \\item[] \\textsc{Operation}($P_i$, $P_{i+2^j}$) to be \\fbox{$P_i \\bigcup P_{i+2^j}$}\n      \\end{enumerate}\n\n      In the first round, $P_k$ sends $\\{x\\}$ to its counterpart $\\bar{P_{k}}$ in the other group via the binary operation, this implies that $P_k$ and $\\bar{P_{k}}$ can only differ by 1 at the $0$-th bit. On the other hand, the rest of the processors are empty, so the binary operation has no effect on them. When this round finishes, now 2 processors know about $\\{x\\}$. In the second round, we have a new partition of processors. Since $P_k$ and $\\bar{P_{k}}$ differs only at the $0$-th bit but now we have divided the processors by another bit, they cannot be counterparts this time or in any future rounds. Hence, they will both have a new counterpart who can receive the datum $\\{x\\}$. When this round finishes, now 4 processors know about $\\{x\\}$, and so forth...\n\n      Given that any two processors can be counterparts in only one round, we will always have new pairs of counterparts in each round. As a result, after the $j$-th iteration, $2^j$ processors will know about $\\{x\\}$, and finally the datum will be propagated across the entire interconnection network.\n\n      \\item[3.] The \\textsc{Descend} and \\textsc{Ascend} paradigm can be a powerful tool in many scenarios.\n\n      If the binary operation is set intersection and each processor has a set, we can find the common values and remove duplicates. If the binary operation is set union, we can also find all distinct values or aggregate the data. For other binary operations such as the max()/min() function or multiplication, we can compute the maximum, minimum and product of numbers in an array or other data structures. It is also possible to use logical gates in parallel, where each processor handles a condition that is either true or false. For instance, we can check if the constraints of a linear program are violated, or if an interpretation of the 3-SAT formula is satisfiable.\n    \\end{enumerate}\n\n  \\vspace{8mm}\n  \\printbibliography\n\n  \\vfill\n  \\doclicenseThis\n\n\\end{document}\n", "meta": {"hexsha": "e6fc1cd99badf5686c18f5f15f15ef37b1b605c8", "size": 38570, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "misc/advanced_algorithms.tex", "max_stars_repo_name": "neo-mashiro/BU", "max_stars_repo_head_hexsha": "2d2e789342ada0da6c1676e93d7d4e4839bdd6ef", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "misc/advanced_algorithms.tex", "max_issues_repo_name": "neo-mashiro/BU", "max_issues_repo_head_hexsha": "2d2e789342ada0da6c1676e93d7d4e4839bdd6ef", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-09-25T14:29:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-25T14:29:00.000Z", "max_forks_repo_path": "misc/advanced_algorithms.tex", "max_forks_repo_name": "neo-mashiro/DOC", "max_forks_repo_head_hexsha": "2d2e789342ada0da6c1676e93d7d4e4839bdd6ef", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 91.8333333333, "max_line_length": 1243, "alphanum_fraction": 0.6852735286, "num_tokens": 12112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.34754701460645027}}
{"text": "\n\n% ==================\n%\n% =-------------------\n\\section{Simulation of the Multidomain Model}\\label{sec:solver_multidomain_model}\n\nThe multidomain model is an alternative to the fiber based electrophysiology model discussed in the last section.\nAs introduced in \\cref{sec:multidomain_model}, it does not explicitly resolve muscle fibers, but considers activity in the muscle domain in a homogenized view.\nOn every point in the 3D muscle mesh, separate values $V_m^k$ of the transmembrane potential exist for every MU $k \\in \\{1,\\dots,N_\\text{MU}\\}$, in addition to the value $\\phi_e$ for the extracellular electric potential. \nThe computational domain considers the muscle volume $\\Omega_M$ and the body domain $\\Omega_B$, which represents  adipose tissue on top of the muscle.\nTo solve the multidomain model, a large linear system has to be solved in every timestep, as described in \\cref{sec:discretization_body_domain}.\n\nIn the following, \\cref{sec:multidomain_components} discusses the model setup for a scenario with four MUs. \\Cref{sec:multidomain_simulation_emg} demonstrates a larger simulation scenario with 25 MUs, which can be used to simulate surface EMG signals. We discuss differences between the multidomain approach and the fiber based electrophysiology model in \\cref{sec:multidomain_differences}.\n\n\\subsection{Components of the Computational Model}\\label{sec:multidomain_components}\n\nIn the following, we consider a multidomain simulation with muscle and body fat domains and four MUs. We use a muscle mesh with $16 \\times 16 \\times 74 = \\num{18944}$ elements and linear finite element ansatz functions and a fat mesh with $32 \\times 4 \\times 74 = \\num{9472}$ elements, which are partitioned to 128 subdomains for 128 processes. \n\nThe scenario uses the following electric conduction tensors $\\bfsigma_i$ and $\\bfsigma_e$ for the intra-cellular domain and the extracellular domain, respectively:\n\\begin{align}\\label{eq:multidomain_isotropic_e}\n  \\bfsigma_i &= \\mat{\n  8.93 & 0 & 0\\\\\n  0& 0& 0\\\\\n  0& 0& 0}\\SI{}{\\milli\\siemens\\per\\centi\\meter}, &  \\bfsigma_e &= \\mat{6.7 & 0 & 0\\\\\n        0& 6.7& 0\\\\\n        0& 0& 6.7}\\SI{}{\\milli\\siemens\\per\\centi\\meter}.\n\\end{align}\n%\nIn this scenario, we use the subcellular model of Hodgkin and Huxley \\cite{Hodgkin1952} and solve it using Heun's method. We discretize the multidomain equations using the Crank-Nicolson scheme with $\\theta=\\frac12$.\nWe solve the resulting linear system of equations by a GMRES solver with the parallel incomplete LU factorization preconditioner \\emph{Euclid} \\cite{euclid} from the HYPRE package \\cite{falgout2002hypre}. A tight residual norm tolerance of \\num{1e-15} is used in the abortion criterion of the GMRES solver. Such a low tolerance is required, as, for higher tolerances, spurious artificial stimulations can be observed. Timestep widths of $\\dt_\\text{0D}=\\dt_\\text{multidomain}=\\dt_\\text{splitting}=\\SI{1e-3}{\\ms}$ are used. \nThe computation for a simulation end time of $t_\\text{end}=\\SI{20}{\\ms}$ in this scenario takes approximately \\SI{27}{\\min}.\n\n%MU  0 around fiber 864, fr_max: 0.050, stddev: 0.10, r: 40.0 μm, Cm: 0.6 uF/cm^2, tstart: 0.000 s, f: 24.000 Hz\n%MU  1 around fiber 343, fr_max: 0.061, stddev: 0.12, r: 40.7 μm, Cm: 0.6 uF/cm^2, tstart: 0.010 s, f: 22.937 Hz\n%MU  2 around fiber 265, fr_max: 0.072, stddev: 0.14, r: 41.3 μm, Cm: 0.6 uF/cm^2, tstart: 0.020 s, f: 21.895 Hz\n\n%scenario_name: 4mus,  n_subdomains: 4 1 32,  n_ranks: 128,  end_time: 20\n%dt_0D:           1e-03    multidomain solver:         1000 it. of gmres (10000 it. of gmres), lumped mass matrix: False, initial guess: previous solution\n%dt_multidomain:  1e-03    multidomain preconditioner: euclid (euclid), symmetric precond.: True\n%dt_splitting:    1e-03    theta: 1.0, solver tolerances, abs: 1e-15, rel: 1e-15\n%fiber_file:              /data/scratch/sgs/maierbn/opendihu/examples/electrophysiology/input/left_biceps_brachii_33x33fibers.bin\n%fat_mesh_file:           /data/scratch/sgs/maierbn/opendihu/examples/electrophysiology/input/left_biceps_brachii_33x33fibers.bin_fat.bin\n%cellml_file:             /data/scratch/sgs/maierbn/opendihu/examples/electrophysiology/input/hodgkin_huxley_1952.c\n%firing_times_file:       /data/scratch/sgs/maierbn/opendihu/examples/electrophysiology/input/MU_firing_times_always.txt\n%********************************************************************************\n%128 ranks, partitioning: x4 x y1 x z32\n  %sampling 3D mesh with stride 2 x 2 x 20\n    %linear 3D mesh    nodes global: 17 x 17 x 75 = 21675, local: 4 x 17 x 3 = 204\n    %linear 3D mesh elements global: 16 x 16 x 74 = 18944, local: 4 x 16 x 3 = 192\n    %fat mesh, n points total:    12375 (33 x 5 x 75), (per process: 4 x 5 x 3 = 60)\n       \nIn the multidomain model, we have to specify which point in the 3D mesh belongs to which MU to which extent. This is achieved by the relative occupancy factors $f_r^{k}$ for MU $k$.\nIn our implementation, the occupancy factors are computed by Python code in the settings file of the simulation.\nThe location of a MU in the 3D domain is specified by choosing a 1D muscle fiber, which is considered to be the center of the MU territory. This is possible, as the nodes in the structured 3D mesh can also be interpreted as a set of adjacent 1D fibers.\n\nFor every MU $k$, the occupancy factors $f_r^k(x,y,z)$ in every muscle cross-section with fixed $z$ coordinate are defined by a radial function $f(|(x,y)^\\top|/d(z))$, which reaches a configurable maximum value at the location of the specified fiber. The argument of the radial function is scaled by the diameter $d(z)$ of the muscle at the considered cross-section. The factor $f_r^k(x,y,z)$ is constant in longitudinal direction of the muscle ($z$ axis). Before the simulation, all factors $f_r^k$ are scaled, such that the maximum of their sum is equal to one:%\n\\begin{align*}\n  \\max\\limits_{(x,y,z)\\in\\Omega_M} \\sum_{k=1}^{N_\\text{MU}} f_r^k(x,y,z) = 1.\n\\end{align*}\n\n% multidomain fr factors\n\\begin{figure}\n  \\centering%\n  \\begin{subfigure}[t]{0.23\\textwidth}%\n    \\centering%\n    \\includegraphics[width=\\textwidth]{images/results/application/multidomain_fr0_cropped.png}%\n    \\caption{$f_r^1$}%\n    \\label{fig:fr0}%\n  \\end{subfigure}\n  \\,\n  \\begin{subfigure}[t]{0.23\\textwidth}%\n    \\centering%\n    \\includegraphics[width=\\textwidth]{images/results/application/multidomain_fr1_cropped.png}%\n    \\caption{$f_r^2$}%\n    \\label{fig:fr1}%\n  \\end{subfigure}\n  \\,\n  \\begin{subfigure}[t]{0.23\\textwidth}%\n    \\centering%\n    \\includegraphics[width=\\textwidth]{images/results/application/multidomain_fr2_cropped.png}%\n    \\caption{$f_r^3$}%\n    \\label{fig:fr2}%\n  \\end{subfigure}\n  \\,\n  \\begin{subfigure}[t]{0.23\\textwidth}%\n    \\centering%\n    \\includegraphics[width=\\textwidth]{images/results/application/multidomain_fr3_cropped.png}%\n    \\caption{$f_r^4$}%\n    \\label{fig:fr3}%\n  \\end{subfigure}\n  \\caption{Simulation of electrophysiology with the multidomain model: Value of the occupancy factors $f_r^k$ for MUs 1 to 4. The color coding encodes the maximum value by red color and the decreasing value along the radius by increased transparency and the color transition to blue color. The locations where the factor vanishes, $f_r^k=0$, correspond to full transparency.}%\n  \\label{fig:multidomain_fr}%\n\\end{figure}%\n\n\\Cref{fig:multidomain_fr} shows the MU occupancy factors for the four MUs in the considered example scenario. It can be seen that the individual MU territories only occupy a small fraction of the muscle domain and are centered around fibers in longitudinal direction of the muscle.\n\nResults of the simulation at $t=\\SI{14}{\\ms}$ are given in \\cref{fig:multidomain_4mus}. In the considered scenario, the first and second MU are stimulated at $t=\\SI{0}{\\ms}$ and $t=\\SI{10}{\\ms}$, respectively. At the time of the displayed images, MUs 3 and 4 have not yet been stimulated. \n\nUpon stimulation, we prescribe the membrane voltage $V_m$ for one timestep as $\\SI{20}{\\milli\\volt}$ at the stimulated nodes in the mesh of the respective MU. In this scenario, the stimulated nodes are located in the middle of the muscle in longitudinal direction in three adjacent cross-sectional layers of mesh elements.\n\nThe upper two images in \\cref{fig:multidomain_4mus} show the locations of the propagated action potential fronts at $t=\\SI{14}{\\ms}$ for MU 1 and MU 2, given by the values of $V_m^k$. While the action potentials span the entire cross-section of the muscle domain, they contribute to the EMG value scaled by their locally varying occupancy factor $f_r^k$.\n\n% multidomain Vm MUs\n\\begin{figure}\n  \\centering%\n  \\includegraphics[width=\\textwidth]{images/results/application/multidomain_4mus_mu1.png}\\\\[4mm]\n  \\includegraphics[width=\\textwidth]{images/results/application/multidomain_4mus_mu2.png}\\\\[4mm]\n  \\includegraphics[width=\\textwidth]{images/results/application/multidomain_4mus_mu3.png}\\\\[4mm]\n  \\includegraphics[width=\\textwidth]{images/results/application/multidomain_4mus_mu4.png}%\n  \\caption{Simulation of electrophysiology with the multidomain model: Transmembrane potential $V_m^k$ of MUs 1 to 4 at $t=\\SI{14}{\\ms}$.}%\n  \\label{fig:multidomain_4mus}%\n\\end{figure}%\n\nAs the $V_m^k$ values of all MUs $k\\in \\{1,\\dots,N_\\text{MU}\\}$ are strongly coupled, the active MUs, MU 1 and MU 2, influence the $V_m^k$ scalar fields of the inactive MUs, MU 3 and MU 4. The lower two images in \\cref{fig:multidomain_4mus} show the computational domain of the muscle with several layers of 3D elements removed. \nIt can be seen that, at some regions in the interior of the domain, the values of $V_m^3$ and $V_m^4$ correspond to the negated value of $V_m^2$ with a smaller absolute value. Note the different color scales for $V_m^1$, $V_m^3$ and $V_m^4$ in these images.\n\n\\Cref{fig:multidomain_4mus_body} shows the values of the extracellular potential $\\phi_e$ on the muscle domain. The contributions from the two active MUs can be seen. \n\\Cref{fig:multidomain_4mus_phi_e_points} gives an impression of the used mesh and shows the value of $\\phi_e$ for all nodes. It can be seen that the $\\phi_e$ values span a larger value range in the interior of the domain than on the boundary, as previously shown in \\cref{fig:multidomain_4mus_body}. Correspondingly, the color coding in \\cref{fig:multidomain_4mus_phi_e_points} uses a larger range than in \\cref{fig:multidomain_4mus_body}.\n\n\\Cref{fig:multidomain_4mus_emg} shows the EMG values $\\phi_b$ on the surface of the body domain mesh. The effect of the body domain is revealed by comparing the electric potential on the boundary of the muscle mesh in \\cref{fig:multidomain_4mus_body} with the values in \\cref{fig:multidomain_4mus_emg}. The signals get locally smoothed by the fat layer.\n\n\n% multidomain phi_e\n\\begin{figure}\n  \\centering%\n  \\begin{subfigure}[t]{\\textwidth}%\n    \\centering%\n    \\includegraphics[width=\\textwidth]{images/results/application/multidomain_4mus_body.png}%\n    \\caption{Extracellular potential $\\phi_e$ on the surface of the muscle domain.}%\n    \\label{fig:multidomain_4mus_body}%\n  \\end{subfigure} \\\\\n  \\begin{subfigure}[t]{\\textwidth}%\n    \\centering%\n    \\includegraphics[width=\\textwidth]{images/results/application/multidomain_4mus_phi_e_points.png}%\n    \\caption{Extracellular potential $\\phi_e$ at points of the 3D muscle mesh.}%\n    \\label{fig:multidomain_4mus_phi_e_points}%\n  \\end{subfigure} \\\\\n  \\begin{subfigure}[t]{\\textwidth}%\n    \\centering%\n    \\includegraphics[width=\\textwidth]{images/results/application/multidomain_4mus_emg.png}%\n    \\caption{EMG signal $\\phi_b$ on the surface of the body fat domain. The comparison with (a) shows the effect of the fat layer.}%\n    \\label{fig:multidomain_4mus_emg}%\n  \\end{subfigure}\n  \\caption{Simulation of electrophysiology with the multidomain model: Simulation results at $t=\\SI{14}{\\ms}$ for a scenario with 4 MUs.}%\n  \\label{fig:multidomain_4mus_2}%\n\\end{figure}%\n\n\n\n\\subsection{Simulation of EMG Signals}\\label{sec:multidomain_simulation_emg}\n\nIn the second scenario, we simulate a higher number of 25 MUs. The MUs are activated at random times within the first \\SI{20}{\\ms}. We use a mesh with $12 \\times 12 \\times 74 = \\num{10656}$ elements in the muscle domain and $24 \\times 4 \\times 74 = 7104$ elements in the body domain. Compared to the mesh in the previous scenario, the spatial resolution in radial direction is chosen slightly coarser, to speed up the computation.\nThe other model parameters, discretization schemes and solvers are chosen as before.\n\nIn this scenario, the stimulated nodes are no longer located in the middle of the muscle, but randomly varied by up to \\SI{10}{\\percent} of the muscle length using a uniform distribution. This approach to model the neuromuscular junctions is analog to the approach in \\cref{sec:simfiber_mu} for the fiber based electrophysiology. \n\\Cref{fig:multidomain_25mus_snapshot} shows the membrane voltage $V_m^1$ of MU 1 shortly after the MU has been activated. Because of the different locations of the stimulated points, no uniform action potential \\say{front} as in \\cref{fig:multidomain_4mus} is seen. Instead, a characteristic 2D MU action potential forms. \n\nThe spike of the depolarized membrane voltage at every stimulated point propagates along the fiber direction and additionally diffuses in  transverse direction. This yields the cone-like structures of lower $V_m$ values as  seen in \\cref{fig:multidomain_25mus_snapshot}. The origin of the transverse propagation is the electric conduction in the extracellular space, which is governed by the isotropic conduction tensor $\\bfsigma_e$ in \\cref{eq:multidomain_isotropic_e}. This isotropic conduction is strongly coupled to the directed action potential propagation within every MU compartment.\n\nThe resulting EMG values $\\phi_e$ on the muscle boundary and $\\phi_b$ on the skin surface are given in \\cref{fig:multidomain_25mus2_emg} and \\cref{fig:multidomain_25mus2_body}, respectively. The fat layer again smooths out the signal, as observed in the last section and in \\cref{sec:simfiber_fat} for the fiber based electrophysiology model.\n\nThe two blue vertical stripes in \\cref{fig:multidomain_25mus2_emg} with lower $\\phi_e$ values correspond to the action potentials of multiple MUs at the respective location. It can be seen that the resulting EMG signal varies more in longitudinal direction than in transverse direction. This can be explained by the wide MU territories in this scenario.\n\n% multidomain Vm MU\n% multidomain phi_e\n\\begin{figure}\n  \\centering%\n  \\begin{subfigure}[t]{\\textwidth}%\n    \\centering%\n    \\includegraphics[width=11cm]{images/results/application/multidomain_25mus_snapshot.png}%\n    \\caption{Transmembrane voltage $V_m^1$ of the first MU.}%\n    \\label{fig:multidomain_25mus_snapshot}%\n  \\end{subfigure} \\\\[4mm]\n  \\begin{subfigure}[t]{\\textwidth}%\n    \\centering%\n    \\includegraphics[width=12cm]{images/results/application/multidomain_25mus2_emg.png}%\n    \\caption{Extracellular potential $\\phi_e$ at the surface of the 3D muscle mesh.}%\n    \\label{fig:multidomain_25mus2_emg}%\n  \\end{subfigure} \\\\[4mm]\n  \\begin{subfigure}[t]{\\textwidth}%\n    \\centering%\n    \\includegraphics[width=12cm]{images/results/application/multidomain_25mus2_body.png}%\n    \\caption{EMG signal $\\phi_b$ at the surface of the body fat domain.}%\n    \\label{fig:multidomain_25mus2_body}%\n  \\end{subfigure}\n  \\caption{Simulation of electrophysiology with the multidomain model: Simulation results at $t=\\SI{20}{\\ms}$ for a scenario with 25 MUs.}%\n  \\label{fig:multidomain_25mus2}%\n\\end{figure}%\n\n\n\\subsection{Comparison of the Fiber Based Electrophysiology Model and the Multidomain Model}\\label{sec:multidomain_differences}\n\nEMG signals on the upper arm can be simulated by both the fiber based electrophysiology model, as demonstrated in \\cref{sec:results_fiber_based_electrophysiology} and by the multidomain model, as shown in the previous sections. The two approaches have several similarities and differences.\n\nBoth model approaches have in common that they are based on biophysical principles. They both involve a detailed subcellular model, which describes the biochemical processes on the muscle fiber membranes. The subcellular model is solved at discrete points in the 3D domain and the model instances are coupled to a description of electric volume conduction in the muscle domain and the body fat layer.  Both the fiber based approach and the multidomain model are, thus, multi-scale descriptions. \n\nBoth models also resolve the physiological structure of muscle activity given by multiple MUs. Action potential propagation is computed separately for different MUs. In a comprehensive simulation of the neuromuscular system, motor neuron models can be coupled to drive the activation of the MUs.\n\nThe two domains of the electrically active muscle tissue and the passive layer of skin and adipose tissue are also considered in both modeling approaches. In the fiber based approach, electric volume conduction is described by the 3D bidomain equation \\cref{eq:bidomain1} for the muscle domain and a strongly coupled 3D Laplace equation \\cref{eq:body} for the body domain.\nThe multidomain approach for electric volume conduction generalizes the bidomain model and yields the bidomain equation as a special case, if only one MU is considered. The Laplace equation for the body domain is coupled in the same way as in the fiber based model. In summary, both approaches are very similar regarding the 3D electric conduction part.\n\nThe major difference between the models is, that the multidomain approach considers only 3D domains, whereas the fiber based approach resolves individual 1D muscle fibers. Another difference lies in the coupling between the model components. For the fiber based approach, action potential propagation on the 1D fibers is unidirectionally coupled to the 3D volume conduction part of the model. In the multidomain model, all components are bidirectionally coupled. This allows, e.g., to simulate externally applied stimulations by active electrodes on the skin surface. The effects of the external currents on the electric potentials in the 3D muscle volume and down to the 0D subcellular behavior can only be described accurately by the multidomain approach.\n\nThe difference in coupling between the action potential propagation model part and the electric volume conduction in the extracellular space can also be seen in the computed EMG signals. A comparison of EMG simulations using the fiber based model, e.g., \\cref{fig:emg273529b}, and the multidomain model, e.g., \\cref{fig:multidomain_25mus2_emg}, shows that the multidomain approach yields less sharp artifacts in the 2D EMG signal on the muscle surface than the fiber based method. In the fiber based model, the action potentials of individual fibers are visible in the signal. In the multidomain simulations, the regions of similar activity are more clustered in the resulting EMG signals.\n\nOther differences between the two model approaches exist in terms of the computational performance properties of their solvers. In the fiber based approach, action potential propagation can be computed independently for all muscle fibers, which enables large speedups by parallelization and makes large problem sizes with realistic numbers of muscle fibers feasible. For example, \\cref{sec:effects_of_the_mesh_width_emg} presents the simulation of \\num{270000} muscle fibers with \\num{27000} compute cores.\nIn the multidomain approach, on the other hand, a large linear system of equations has to be solved in every timesteps. This can also be parallelized, but requires communication between the involved processes, which limits the parallel scalability for large problem sizes.\n\nIn the multidomain model, the computational effort increases, in good approximation, linearly with both the number of MUs and the number of nodes in the mesh. In the fiber based approach, the amount of computational work mainly corresponds to the number of fibers, not to the number of MUs. \nThe 3D problem and, thus, the mesh width of the 3D mesh, typically plays a minor role in the total runtime for the fiber based approach, as the 3D problem is only solved according to the desired EMG sampling frequency. In the multidomain approach, no separate timestep widths can be chosen for the computations of the extracellular and body domain electric potentials, $\\phi_e$ and $\\phi_b$, as they are computed as a solution of the same linear system of equations.\n\nFor example, the computation of \\SI{24}{\\ms} of the multidomain scenario in \\cref{sec:multidomain_simulation_emg} with 25 MUs and 126 processes has a runtime of approximately $\\SI{106}{\\min}$. The fiber based approach with the same 3D mesh and the same parallel partitioning with 126 processes has a total runtime of \\SI{6}{\\s} for 169 fibers or \\SI{20}{\\s} for 1369 fibers. A scenario with 169 fibers leads to a fiber spacing that corresponds to the 3D mesh width in the compared multidomain scenario. The speedup between the models in this case is approximately \\num{1000}.\nNote that only the computation of the fiber based approach is highly optimized in this work, and a better performance of the multidomain solver could be achieved in future work. However, the structural properties of the models facilitate highly parallel simulations only for the fiber based approach.\n\nAs a result, if the simplifications of a unidirectional coupling of the extracellular potential $\\phi_e$ from the muscle fibers to the 3D volume can be tolerated, the fiber based approach should be used, as it exhibits significantly lower runtimes. The fiber based approach is (considering the current implementation) the only possible choice for scenarios with at least two of the three requirements (i) long simulation time spans in the range of seconds, (ii) large number of MUs in the range of multiple dozens, and (iii) finely resolved 3D meshes in the range of several $\\num{1e6}$ degrees of freedom.\n \nThe multidomain approach, on the other hand, can describe phenomena that are not accurately captured by the fiber based model, as described earlier.\nMoreover, the multidomain model is potentially easier to handle for more irregular geometries, where only a structured 3D mesh and no physiologically oriented fibers are given. Another advantage of the multidomain approach is its ability to fine tune the MU territories. \nThe multidomain model can also possibly simulate a given MU distribution with the same accuracy with less 3D points than the fiber based approach. However, investigations in this direction are subject of future research.\nIf large runtimes are not an issue, the multidomain approach can be used to yield more physically accurate results than the fiber based approach, ultimately advancing the means to describe the neuromuscular system as detailed and accurately as possible.\n\n\n% common\n%   biophysically based, MUs, subcellular models\n%   3D bidomain in both\n\n% differences\n%   coupling uni->bi\n%   computation\n\n\n% fibers and multidomain\n%\\begin{figure}[H]\n%  \\centering%\n%  \\begin{subfigure}[t]{0.48\\textwidth}%\n%    \\centering%\n%    \\includegraphics[width=\\textwidth]{images/results/application/2_multidomain.png}%\n%    \\caption{Multidomain}%\n%    \\label{fig:2_multidomain}%\n%  \\end{subfigure}\n%  \\quad\n%  \\begin{subfigure}[t]{0.48\\textwidth}%\n%    \\centering%\n%    \\includegraphics[width=\\textwidth]{images/results/application/2_fibers.png}%\n%    \\caption{Fibers}%\n%    \\label{fig:2_fibers}%\n%  \\end{subfigure}   \n%  \\caption{Fibers and Multidomain}%\n%  \\label{fig:multidomain_fibers}%\n%\\end{figure}%\n\n\n\\begin{reproduce_no_break}\n  The two simulations in this section with 4 and 25 MUs, respectively, which are visualized in \\cref{fig:multidomain_4mus,fig:multidomain_4mus_2,fig:multidomain_25mus2}, can be executed by the following commands:\n  \\begin{lstlisting}[columns=fullflexible,breaklines=true,postbreak=\\mbox{\\textcolor{gray}{$\\hookrightarrow$}\\space}]\n    cd $\\$$OPENDIHU_HOME/examples/electrophysiology/multidomain/multidomain_with_fat/build_release\n    mpirun -n 128 multidomain_with_fat ../settings_multidomain_with_fat.py 4mus.py --n_subdomains 8 1 16\n    mpirun -n 126 ./multidomain_with_fat_emg ../settings_multidomain_with_fat.py all_active.py --n_subdomains 6 1 21\n  \\end{lstlisting}\n  For other available numbers of processes, the subdomains at the end of the commands have to be adjusted.\n\\end{reproduce_no_break}\n\n% ----------------\n%\n% =================\n\n%-----\n% ==================\n%\n% =-------------------\n%-----\n\n\\section{Simulation of Coupled Electrophysiology and Solid Mechanics}\\label{sec:coupled_electrophysiology_and_solid_mechanics}\n\nSimulating muscle contraction with a detailed model, which accurately describes motor recruitment,\nyields the basis for new insights into the neuromuscular orchestration of processes that lead to muscle force generation.\n\nWe couple the two model approaches for electrophysiology, the fiber based model presented in \\cref{sec:results_fiber_based_electrophysiology} and the multidomain model presented in \\cref{sec:solver_multidomain_model}, with a solid mechanics model. \nIn \\cref{sec:solver_solid_mechanics}, we demonstrated the solver for nonlinear hyperelasticity models in simulations of the passive behavior of muscle tissue. The current section aims at simulating active muscle contraction.\n\n\\Cref{sec:fiber_based_contraction} couples the fiber based electrophysiology model with a model of muscle contraction. \\Cref{sec:prestress_contraction} discusses an algorithm to add prestress to the description. \\Cref{sec:multidomain_contraction} demonstrates the coupling of the multidomain model with the model of muscle contraction. \\Cref{sec:volume_coupling_contraction} and \\cref{sec:surface_coupling_contraction} describe simulations using the numerical coupling library preCICE.\n\n\\subsection{Fiber Based Electrophysiology and Muscle Contraction}\\label{sec:fiber_based_contraction}\n%-----\n\nWe begin with coupling the fiber based electrophysiology solver with the solid mechanics model to simulate muscle contraction as a result of the activation of muscle fibers.\nWe use the subcellular model of Shorten et al. \\cite{Shorten2007}. It computes the microscopic activation parameter $\\gamma \\in [0,1]$, which is related to the concentration of attached cross-bridges in the sarcomeres. The parameter $\\gamma$ is mapped and homogenized from the 0D subcellular points to $\\bar{\\gamma}$ on the 3D mesh. In the macroscopic 3D mechanics description, the factor is multiplied with a maximum active stress parameter $S_\\text{max,active}$ and a force-velocity characteristic $f_l(\\lambda_f)$, as described in \\cref{sec:material_nonlinear_model}.\nThe 3D mechanics model updates the geometry of the 3D domain and transfers the fiber stretch value $\\lambda_f$ and the contraction velocity $\\dot{\\lambda}_f$ back to the subcellular model.\n\nIn this scenario, we aim to simulate a rapid and strong contraction of the biceps muscle.\nThe scenario contains 169 fibers, which are associated with 15 MUs. This association is generated by method 1 in \\cref{sec:method1_assignment}. All MUs are subsequently activated in a ramp in the first $\\SI{1.4}{\\s}$. \n\nThe muscle geometry is fixed at its lower end and no external forces are considered in this scenario. The dynamic formulation with the transversely isotropic Mooney-Rivlin material is used, as described in \\cref{sec:material_nonlinear_model}.\nThe 3D muscle mesh contains $2 \\times 3 \\times 18 = 108$ elements with quadratic finite element ansatz functions and 1295 nodes in total and is  partitioned into subdomains for four processes. Time step widths of $\\dt_\\text{0D} = \\dt_\\text{1D} = \\dt_\\text{splitting} = \\SI{1e-4}{\\ms}$ and $\\dt_\\text{3D}=\\SI{1}{\\ms}$ are used. The used numerical solvers and other settings of the electrophysiology and contraction models are equal to the described scenarios in \\cref{sec:simfiber_mu,sec:effects_of_the_mesh_width_emg} and \\cref{sec:comparison_linear_nonlinear}.\n\n% normal muscle contraction\n%0/4 : This is opendihu 1.2, built Apr 16 2021, C++ 201402, GCC 10.2.0, current time: 2021/4/17 19:56:16, hostname: ipvs-epyc1, n ranks: 4\n%0/4 : Open MPI v3.1.6, package: Open MPI maierbn@ipvs-epyc1 Distribution, ident: 3.1.6, repo rev: v3.1.6, Mar 18, 2020\n%0/4 : File \"../settings_biceps_contraction.py\" loaded.\n%0/4 : ---------------------------------------- begin python output ----------------------------------------\n%Loading variables from \"15mus.py\".\n%scenario_name: 15mus,  n_subdomains: 2 1 2,  n_ranks: 4,  end_time: 4000.0\n%dt_0D:           1e-04, diffusion_solver_type:      cg\n%dt_1D:           1e-04, potential_flow_solver_type: gmres\n%dt_splitting:    1e-04, emg_solver_type:            cg, emg_initial_guess_nonzero: False\n%dt_3D:           1e+00, paraview_output: True\n%output_timestep: 1e+00  stimulation_frequency: 0.1 1/ms = 100.0 Hz\n%fast_monodomain_solver_optimizations: True, use_analytic_jacobian: True, use_vc: True\n%fiber_file:              ../../../../input/left_biceps_brachii_13x13fibers.bin\n%fat_mesh_file:           ../../../../input/left_biceps_brachii_13x13fibers.bin_fat.bin\n%cellml_file:             ../../../../input/new_slow_TK_2014_12_08.c\n%fiber_distribution_file: ../../../../input/MU_fibre_distribution_15MUs_13x13fibers.txt\n%firing_times_file:       ../../../../input/MU_firing_times_always.txt\n%********************************************************************************\n%prefactor: sigma_eff/(Am*Cm) = 0.0132 = 3.828 / (500.0*0.58)\n%diffusion solver type: cg\n%n fibers:              169 (13 x 13), sampled by stride 2 x 2\n%n points per fiber:    1481, sampled by stride 40\n%4 ranks, partitioning: x2 x y1 x z2\n%13 x 13 = 169 fibers, per partition: 6 x 12 = 72\n%per fiber: 1D mesh    nodes global: 1481, local: 760\n  %sampling 3D mesh with stride 2 x 2 x 40 \n %quadratic 3D mesh    nodes global: 5 x 7 x 37 = 1295, local: 2 x 7 x 18 = 252\n %quadratic 3D mesh elements global: 2 x 3 x 18 = 108, local: 1 x 3 x 9 = 27\n%number of degrees of freedom:\n                    %1D fiber:       1481  (per process: 760)\n            %0D-1D monodomain:      82936  (per process: 42560)\n %all fibers 0D-1D monodomain:   14016184  (per process: 3064320)\n                 %3D bidomain:       1295  (per process: 252)\n                       %total:   14017479  (per process: 3064572)\n\n% contraction fibers\n\\begin{figure}\n  \\centering%\n  \\begin{subfigure}[t]{0.3\\textwidth}%\n    \\centering%\n    \\includegraphics[height=9cm]{images/results/application/contraction_fibers_044.png}%\n    \\caption{}%\n    \\label{fig:contraction_fibers_044}%\n  \\end{subfigure} \\,\n  \\begin{subfigure}[t]{0.18\\textwidth}%\n    \\centering%\n    \\includegraphics[height=9cm]{images/results/application/contraction_fibers_844b.png}%\n    \\caption{}%\n    \\label{fig:contraction_fibers_844b}%\n  \\end{subfigure}\\,\n  \\begin{subfigure}[t]{0.25\\textwidth}%\n    \\centering%\n    \\includegraphics[height=9cm]{images/results/application/contraction_fibers_1684b.png}%\n    \\caption{}%\n    \\label{fig:contraction_fibers_1684b}%\n  \\end{subfigure}\\,\n  \\begin{subfigure}[t]{0.2\\textwidth}%\n    \\centering%\n    \\includegraphics[height=9cm]{images/results/application/contraction_fibers_2084b.png}%\n    \\caption{}%\n    \\label{fig:contraction_fibers_2084b}%\n  \\end{subfigure}\n  \\caption{Simulation of fiber based electrophysiology and muscle contraction: Activation of the muscle fibers and overall deformation at various timesteps.}%\n  \\label{fig:contraction_fibers_1}%\n\\end{figure}%\n\n\\Cref{fig:contraction_fibers_1} shows the fibers of the contracting muscle at four different timesteps between $t=\\SI{44}{\\ms}$ and $t=\\SI{2.084}{\\s}$. The fibers are colored according to the resulting activation parameter $\\gamma$, which is a measure for the generated force on the sarcomere level. Between $t=\\SI{44}{\\ms}$ and $t=\\SI{844}{\\ms}$, shown in \\cref{fig:contraction_fibers_044,fig:contraction_fibers_844b}, the smallest MUs are activated, which, in this example, are mainly located on the left-hand side. As a consequence, the muscle domain initially bends slightly to the left. As more MUs become active at $t=\\SI{1684}{\\ms}$, depicted in \\cref{fig:contraction_fibers_1684b}, the deformation increases and the bending direction is reversed. However, the fibers on the left-hand side still exhibit the highest $\\gamma$ value, as they have been stimulated most often at that time.\nAt $t=\\SI{1684}{\\ms}$, visualized in \\cref{fig:contraction_fibers_2084b}, almost all fibers have a $\\gamma$ value close to one, corresponding to full activation.\n\n% contracted state\n\\begin{figure}\n  \\centering%\n  \\begin{subfigure}[t]{0.31\\textwidth}%\n    \\centering%\n    \\includegraphics[height=77mm]{images/results/application/contraction_fibers.png}%\n    \\caption{Action potentials given by the membrane voltage $V_m$ (in millivolts) on the muscle fibers.}%\n    \\label{fig:contraction_fibers}%\n  \\end{subfigure}\\,\n  \\begin{subfigure}[t]{0.31\\textwidth}%\n    \\centering%\n    \\includegraphics[height=8cm]{images/results/application/contraction_lambda.png}%\n    \\caption{Stretch parameter $\\lambda$ of the deformed 3D muscle domain (red mesh) in comparison to the reference configuration (yellow mesh).}%\n    \\label{fig:contraction_lambda}%\n  \\end{subfigure}\n  \\begin{subfigure}[t]{0.31\\textwidth}%\n    \\centering%\n    \\includegraphics[height=8cm]{images/results/application/contraction_active_stress.png}%\n    \\caption{Value of the active second Piola-Kirchhoff stress.}%\n    \\label{fig:contraction_active_stress}%\n  \\end{subfigure}\n  \\caption{Simulation of fiber based electrophysiology and muscle contraction: Simulation results at $t=\\SI{2084}{\\ms}$.}%\n  \\label{fig:contraction_at_end}%\n\\end{figure}%\n\n\\Cref{fig:contraction_at_end} shows several variables at the simulation end time of $t=\\SI{2084}{\\ms}$. \\Cref{fig:contraction_fibers} visualizes the transmembrane voltage $V_m$ on the muscle fibers. Action potentials can be seen on almost all fibers, as the whole muscle is activated at this time. \\Cref{fig:contraction_lambda} shows a comparison between the reference configuration given by the yellow mesh and the current configuration given by the red mesh. The muscle domain is colored according to the stretch $\\lambda$, which has a nearly constant value of $\\lambda \\approx \\SI{85}{\\percent}$ at the end time of this scenario. A similar visualization is given in \\cref{fig:contraction_active_stress} for the active stress in the muscle.\n\nBecause of the high level of activation and the corresponding active stress distribution in the muscle, our mechanics solver only converges up to the shown simulation time of \\SI{2084}{\\ms} in this scenario. The aim of the scenario is to simulate the contraction of a fully activated muscle. Other scenarios, where the activation is applied more slowly, allow for a convergence of the mechanics solver during longer simulation time spans.\n\nThe presented scenario showed that a fully activated biceps muscle contracted to about \\SI{85}{\\percent} of its original length. However, in reality, larger contractions are possible. In the shown scenario, the muscle was initially in a stress-free configuration. More realistic scenarios can incorporate pretension forces, where the undeformed reference configuration is subject to a constant stress level in the muscle's direction of the line of action. This is considered in the next scenario.\n\n% muscle contraction\n%\\begin{figure}\n%  \\centering%\n%  \\includegraphics[width=0.5\\textwidth]{images/results/application/neuromuscular_muscle_contraction_traction.png}%\n % \\caption{contraction traction}%\n%  \\label{fig:neuromuscular_muscle_contraction_traction}%\n%\\end{figure}%\n\n\\begin{reproduce}\n  The simulation in this section can be run as follows:\n  \\begin{lstlisting}[columns=fullflexible,breaklines=true,postbreak=\\mbox{\\textcolor{gray}{$\\hookrightarrow$}\\space}]\n    cd $\\$$OPENDIHU_HOME/examples/electrophysiology/fibers/fibers_contraction/no_precice/build_release\n    mpirun -n 4 ./biceps_contraction ../settings_biceps_contraction.py ramp.py\n  \\end{lstlisting}\n\\end{reproduce}\n\n\\subsection{Simulation of Prestress}\\label{sec:prestress_contraction}\n% compressing muscle by external force does not work -> need activation \n\nTo obtain more realistic ranges of muscle contraction, a nonzero, constant prestress can be considered in the undeformed configuration of the muscle. \nIn our solid mechanics formulation, the reference configuration always has zero stress. Thus, we need to construct a separate, first reference configuration of a shorter muscle geometry. We stretch it to the original muscle length by applying external forces. The resulting, second configuration resembles the original muscle geometry and has the desired prestress characteristics.\n\nThe detailed steps of this algorithm are visualized in \\cref{fig:neuromuscular_prestretch} and are described in the following.\nWe begin with the given geometry of the muscle with body fat layer, which is shown as black wireframe mesh in \\cref{fig:neuromuscular_prestretch_1}. In a first static simulation step, a constant active stress $\\alpha_\\text{pre}\\,S_\\text{max,active}$ is prescribed in the entire muscle volume. The resulting muscle deformation is computed, using the usual nonlinear hyperelastic muscle material. $S_\\text{max,active}$ refers to the maximum active stress value as used in the mechanics model description in \\cref{eq:active_stress_term}. The result of this first step is a shortened muscle with the same volume as the original geometry. \\Cref{fig:neuromuscular_prestretch} shows the result by the yellow volume for $\\alpha_\\text{pre}=0.3$. It can be seen that the length of the muscle has shortened by approximately \\SI{13}{\\percent}.\n\nIn the second step, we reuse the computed deformed geometry of the first step as new stress-free reference configuration and re-extend it by applying a constant surface load $F_\\text{pre}$ pointing to the bottom on the lower face in the setting of \\cref{fig:neuromuscular_prestretch}. The value of $F_\\text{pre}$ corresponding to $\\alpha_\\text{pre}$ has to be estimated by numerical experiments.\n\nThis step is again solved as a static problem. The result is a similar muscle geometry as the original one, and contains prestress according to the applied force. The muscle volume is exactly preserved due to the incompressible material formulation. \\Cref{fig:neuromuscular_prestretch_2} shows the starting point for the second step by the black wireframe mesh and the resulting geometry for a total applied force of $F_\\text{pre}=\\SI{30}{\\newton}$ by the red volume. The comparison of the original, black mesh in \\cref{fig:neuromuscular_prestretch_1} with the red volume in \\cref{fig:neuromuscular_prestretch_2} shows a good match of the geometry.\nFor the subsequent dynamic simulations of, e.g., muscle contraction, the surface load has to be constantly applied. It corresponds to the tendon forces and the loads of the musculoskeletal system acting on the muscle.\n\nThe active stress parameter $\\alpha_\\text{pre}$ and the corresponding preload force $F_\\text{pre}$ can be chosen according to the desired amount of prestress. However, the higher these values are chosen, the more difficult is it for the nonlinear solid mechanics solvers to converge to a solution. Especially for irregular or large mechanics meshes, a lower stress factor of, e.g., $\\alpha_\\text{pre}=0.1$ has to be chosen. To improve convergence, we apply the load in the second step of the algorithm incrementally by several load steps. In addition, reducing the number of unknowns and increasing the mesh width in the mechanics problem can help, as this improves the conditioning of the problem. \n \n% contracted state\n\\begin{figure}\n  \\centering%\n  \\hfill\n  \\begin{subfigure}[t]{0.48\\textwidth}%\n    \\centering%\n    \\includegraphics[height=12cm]{images/results/application/neuromuscular_prestretch_1.png}%\n    \\caption{In the first step, the original mesh (black wireframe) is contracted by an artificial active stress $\\alpha_\\text{pre}\\,S_\\text{max,active}$ to yield a shortened muscle (yellow mesh).}%\n    \\label{fig:neuromuscular_prestretch_1}%\n  \\end{subfigure}\\hfill\n  \\begin{subfigure}[t]{0.48\\textwidth}%\n    \\centering%\n    \\includegraphics[height=12cm]{images/results/application/neuromuscular_prestretch_2.png}%\n    \\caption{In the second step, the mesh is extended again by an external surface load. The black wireframe corresponds to the yellow volume in (a), the red volume is the resulting geometry.}%\n    \\label{fig:neuromuscular_prestretch_2}%\n  \\end{subfigure}\n  \\hfill\n  \\caption{Simulation of biceps muscle geometry with prestress: The two steps of the algorithm to generate a reference geometry with prestress, shown with the geometry of the tendons for reference.}%\n  \\label{fig:neuromuscular_prestretch}%\n\\end{figure}%\n\n\n\\subsection{Coupling of the Multidomain Model and Solid Mechanics Model with Prestress}\\label{sec:multidomain_contraction}\n\nIn the following, we present a scenario that uses the prestress algorithm of the last section and couples the multidomain and mechanics models to simulate surface EMG signals on the skin surface over a contracting muscle.\n\nWe choose $\\alpha_\\text{pre}=0.1$ and apply the prestretch force $F_\\text{pre}=\\SI{10}{\\newton}$ in three load steps. The multidomain model considers 5 MUs with stimulation frequencies between \\SI{7}{\\hertz} and \\SI{24}{\\hertz} and a 3D mesh of $8 \\times 8 \\times 28 = 1792$ elements. We execute the simulation with four processes. All other parameters and settings of the multidomain model and the solid mechanics model that are not explicitly mentioned in the following are chosen the same as in \\cref{sec:multidomain_components} and \\cref{sec:comparison_linear_nonlinear}.\n\nFor the discretization of the mechanics model, we use a coarser mesh than for the multidomain model. Furthermore, we use quadratic elements instead of linear elements. The Python implementation of the settings script of this example contains functionality to create the mechanics mesh by subsampling the multidomain mesh with specified factors. In the current scenario, we set these factors for the $x$, $y$ and $z$ directions to 0.7, 0.7, and 0.3, respectively. As a result, we get meshes with $5 \\times 7 \\times 9 = 315$ elements for the muscle and $5 \\times 1 \\times 4 = 20$  elements for the body fat domain. \\Cref{fig:multidomain_prestretch5} visualizes all meshes used in this scenario: The orange muscle mesh and the red body mesh are used for the multidomain model, and the yellow mesh is used for the solid mechanics model.\n\n\n% multidomain prestretch\n\\begin{figure}\n  \\centering%\n  \\hfill\n  \\begin{subfigure}[t]{0.31\\textwidth}%\n    \\centering%\n    \\includegraphics[height=87mm]{images/results/application/multidomain_prestretch5.png}%\n    \\caption{Multidomain meshes of the muscle domain (orange), body fat domain (red) and the coarser mesh used for the solid mechanics model (yellow).}%\n    \\label{fig:multidomain_prestretch5}%\n  \\end{subfigure}\n  \\begin{subfigure}[t]{0.31\\textwidth}%\n    \\centering%\n    \\includegraphics[height=95mm]{images/results/application/multidomain_prestretch6.png}%\n    \\caption{Reference configuration (yellow mesh) and current configuration of the muscle colored according to the distribution of the second Piola-Kirchhoff stress.}%\n    \\label{fig:multidomain_prestretch6}%\n  \\end{subfigure}\\qquad\n  \\begin{subfigure}[t]{0.31\\textwidth}%\n    \\centering%\n    \\includegraphics[height=87mm]{images/results/application/multidomain_prestretch2.png}%\n    \\caption{Electric potential $\\phi_b$ in the body domain (green color scale, in millivolts) and active stress in the interior of the muscle (blue-red color scale, in \\SI{}{\\newton\\per\\centi\\meter\\squared}).}%\n    \\label{fig:multidomain_prestretch2}%\n  \\end{subfigure}\n  \\hfill\n  \\caption{Simulation of muscle contraction based on the multidomain model with prestressed muscle geometry: Used meshes and simulation results at $t=\\SI{920}{\\ms}$ of a scenario of the multidomain electrophysiology model coupled to the solid mechanics model.}%\n  \\label{fig:multidomain_prestretch}%\n\\end{figure}%\n\n\\Cref{fig:multidomain_prestretch6,fig:multidomain_prestretch2} depict results of the simulation at time $t=\\SI{920}{\\milli\\second}$. \n\\Cref{fig:multidomain_prestretch6} shows the reference geometry by the yellow wireframe after applying the prestress. The muscle is colored according to the value of the second Piola-Kirchhoff stress. During this dynamic simulation, the muscle bends elastically slightly to the left and right, as it is only fixed at its bottom in \\cref{fig:multidomain_prestretch}. This explains the stress distribution at the snapshot for $t=\\SI{920}{\\milli\\second}$ in \\cref{fig:multidomain_prestretch6}, where higher stresses occur on the right-hand side.\n\n\\Cref{fig:multidomain_prestretch2} shows the electric potential $\\phi_b$ of the body domain by the green color scale on the left of the image. The visible part of the fat layer shows two action potentials, visualized by the two dark green stripes.\n\nMoreover, \\cref{fig:multidomain_prestretch2} displays the total active stress  $\\bfS_\\text{active}$ in the interior of the muscle by the color scale that ranges from blue to red color. In the multidomain model, $\\bfS_\\text{active}$ is calculated as a weighted sum over the contributions $\\bfS_\\text{active}^k$ of the MU compartments, scaled by the occupancy factors $f_r^k$ (cf. \\cref{sec:multidomain_model}):\n\\begin{align*}\n  \\bfS_\\text{active} = \\sum\\limits_{k=1}^{N_\\text{MU}} f_r^k\\,\\bfS_\\text{active}^k.\n\\end{align*}\nThe muscle domain in \\cref{fig:multidomain_prestretch2} is cut open, such that interior distribution at the cut plane can be seen. The image shows two regions of higher active stress, which run vertically through the muscle, given by red color. They are a result on the location of the MUs in this scenario. The legend shows that the active stress inside the muscle is below $\\SI{0.4}{\\newton\\per\\centi\\meter\\squared}$, while the maximum active stress parameter is chosen as $S_\\text{max,active}=\\SI{7.3}{\\newton\\per\\centi\\meter\\squared}$. This low activation level is a result of the chosen MU recruitment. As a result, the muscle only slightly contracts, as can be seen in \\cref{fig:multidomain_prestretch6}.\n\nIn summary, both the fiber based electrophysiology model and the multidomain model can be coupled with the nonlinear solid mechanics model to simulate muscle contraction, as presented in \\cref{sec:fiber_based_contraction} and in this section. \nThe computational efficiency considerations discussed in the comparison of the fiber based and multidomain approaches in \\cref{sec:multidomain_differences} also apply to coupled simulations with muscle contraction. For longer simulation times, the fiber based approach in \\cref{sec:fiber_based_contraction} is, therefore, favored.\n\n%0/4 : This is opendihu 1.2, built Apr 17 2021, C++ 201402, GCC 10.2.0, current time: 2021/4/18 17:13:03, hostname: ipvs-epyc1, n ranks: 4            \n%0/4 : Open MPI v3.1.6, package: Open MPI maierbn@ipvs-epyc1 Distribution, ident: 3.1.6, repo rev: v3.1.6, Mar 18, 2020\n%0/4 : File \"../settings_multidomain_prestretch.py\" loaded.                                     \n%0/4 : ---------------------------------------- begin python output ----------------------------------------                                                                                   \n%Loading variables from \"multidomain.py\".                                                                                                                                                      \n%scenario_name: multidomain,  n_subdomains: 2 1 2,  n_ranks: 4,  end_time: 4000.0                                                                                                              \n%dt_0D:           1e-03    multidomain solver:         gmres, lumped mass matrix: False                                                                                                        \n%dt_multidomain:  1e-03    multidomain preconditioner: euclid, symmetric precond.: True\n%dt_splitting:    1e-03    theta: 1.0, solver tolerances, abs: 1e-15, rel: 1e-15\n%dt_elasticity:   1e+00    elasticity solver: lu, preconditioner: none\n%fiber_file:              /data/scratch/sgs/maierbn/opendihu/examples/electrophysiology/input/left_biceps_brachii_9x9fibers.bin\n%fat_mesh_file:           /data/scratch/sgs/maierbn/opendihu/examples/electrophysiology/input/left_biceps_brachii_9x9fibers.bin_fat.bin\n%cellml_file:             /data/scratch/sgs/maierbn/opendihu/examples/electrophysiology/input/hodgkin_huxley-razumova.cellml\n%firing_times_file:       /data/scratch/sgs/maierbn/opendihu/examples/electrophysiology/input/MU_firing_times_always.txt\n%********************************************************************************\n%4 ranks, partitioning: x2 x y1 x z2\n  %sampling 3D mesh with stride 1 x 1 x 50 \n    %linear 3D mesh    nodes global: 9 x 9 x 29 = 2349, local: 4 x 9 x 14 = 504\n    %linear 3D mesh elements global: 8 x 8 x 28 = 1792, local: 4 x 8 x 14 = 448\n %quadratic 3D mesh    nodes global: 9 x 9 x 29 = 2349, local: 4 x 9 x 14 = 504\n %quadratic 3D mesh elements global: 4 x 4 x 14 = 224, local: 2 x 4 x 7 = 56\n    %fat mesh, n points total:    2465 (17 x 5 x 29), (per process: 4 x 5 x 14 = 280)\n   %sub-sampling 3D elasticity mesh with factors 0.7, 0.7, 0.3 \n   %elasticity quadratic 3D meshes:\n   %muscle:             nodes global: 5 x 7 x 9 = 315, local: 2 x 7 x 4 = 56\n          %quadratic elements global: 2 x 3 x 4 = 24, local: 1 x 1 x 2 = 2\n   %fat and skin layer: nodes global: 11 x 3 x 9 = 297, local: 2 x 3 x 4 = 24\n          %quadratic elements global: 5 x 1 x 4 = 20, local: 1 x 1 x 2 = 2\n\n%Debugging output about compartment firing: Taking input from file \"/data/scratch/sgs/maierbn/opendihu/examples/electrophysiology/input/MU_firing_times_always.txt\"\n%First stimulation times\n    %Time  MU compartments\n    %0.00   0 [0]\n    %0.00   1 [1]\n    %0.00   2 [2]\n    %0.00   3 [3]\n%stimulated MUs: 4, not stimulated MUs: 0\n%duration of assembling this list: 0.000 s\n\n%Load relative factors, f_r, from file \"compartments_relative_factors.left_biceps_brachii_9x9fibers.bin.5_mus_stride_1x1x50_partitioning_2x1x2\"\n%MU 0, maximum fr: 0.1999999999999993\n%MU 1, maximum fr: 0.4426237526712864\n%MU 2, maximum fr: 0.6900999803960008\n%MU 3, maximum fr: 0.9425257326752092\n%MU 4, maximum fr: 1.1999999999999993\n\n\n\n% prestretch\n%\\begin{figure}\n%  \\centering%\n%  \\includegraphics[width=0.5\\textwidth]{images/results/application/fibers_muscle_contraction_quantities.png}%\n%  \\caption{prestretch}%\n%  \\label{fig:prestrech1b}%\n%\\end{figure}%\n\n\\begin{reproduce_no_break}\n  The simulation can be run with the following commands. Instead of four processes also other numbers are possible. A lot of parameters can be fine-tuned in the \\code{../variables/multidomain.py} settings file.\n  \\begin{lstlisting}[columns=fullflexible,breaklines=true,postbreak=\\mbox{\\textcolor{gray}{$\\hookrightarrow$}\\space}]\n    cd $\\$$OPENDIHU_HOME/examples/electrophysiology/multidomain/multidomain_prestretch/build_release\n    mpirun -n 4 ./multidomain_prestretch ../settings_multidomain_prestretch.py multidomain.py\n  \\end{lstlisting}\n\\end{reproduce_no_break}\n\n% --------\n%\n% f==============\n\n% ==================\n%\n% =-------------------\n%-----\n\\subsection{Coupling of Solid Mechanics Models using the Software preCICE}\\label{sec:volume_coupling_contraction}\n\nOne problem of multi-scale simulations with solid mechanics models is the limited amount of parallelism, \nif a coarse mechanics mesh with a low number of elements is chosen. The domain can only be partitioned into as many subdomains as there are elements in the 3D mechanics mesh. While this is not an issue for small scale simulations like the ones shown in the previous sections, it prohibits exploitation of High Performance Computing resources, e.g., if numerous muscle fibers are considered as in \\cref{sec:effects_of_the_mesh_width_emg}.\n\nThe reason for the limited parallelism lies in the partitioning scheme, where every node in the 3D domain corresponds to the subdomain of exactly one process, regardless of the mesh. OpenDiHu does not allow to partition, e.g., the finely resolved 1D muscle fiber meshes differently than the coarse 3D mechanics mesh. However, this restriction can be circumvented by using multiple OpenDiHu programs with different partitioning schemes and by performing the data transfer between the meshes using an external coupling software.\n\nWe provide support for the black-box coupling library preCICE \\cite{precice}. This open source library allows mapping data between different meshes, can communicate values between subdomains that reside on different processors, and implements implicit numerical coupling schemes with quasi-Newton methods. The implementation is known to scale well on small-scale clusters and supercomputers.\nThe preCICE library targets a minimally-invasive approach, where the user application implements a preCICE adapter. Multiple, potentially different solver codes can be coupled numerically and compute individual model parts of a joint multi-physics simulation. Moreover, preCICE has an active and growing community where experiences and codes are shared, and open source adapters are available for several popular solvers.\n\nThis makes the library suited for our use case. We provide two different types of preCICE adapters in OpenDiHu, one for surface coupling of 2D meshes and one for volume coupling of 3D meshes. These adapters integrate with the structure of nested solvers and can be positioned anywhere in the solver tree (cf. \\cref{fig:solver_tree_multidomain_spindles}). The meshes and variables that are exposed to preCICE can be configured in the settings file.\n\nIn the current section, we show how to use the volume coupling adapter to resolve the initially stated issue of limited scalability for coupled simulations with electrophysiology and mechanics models. Subsequently, the next section presents a simulation that uses surface coupling. Details can also be found in \\cite{hlrs2021}.\n\nWe simulate muscle contraction and surface EMG of the biceps muscle using the fiber based electrophysiology model. To fully exploit the  capabilities of an 18-core Intel Core i9-10980XE processor, we compute the electrophysiology model using 16 processes and the mechanics model using 2 processes. The data mapping between the differently partitioned 3D meshes is performed by preCICE.\n\n\\Cref{fig:precice_muscle_force} shows the structure of the simulation components with the used meshes and the exchanged variables in this simulation. Two different OpenDiHu programs are executed at the same time, given by the gray boxes. The program corresponding to the left box solves the electric conduction problem, given by the bidomain equation \\cref{eq:bidomain1} on the 3D domain and the action potential propagation model, given by the monodomain equation \\cref{eq:monodomain} on a large number of 1D muscle fiber meshes. \nThe 3D and the 1D mesh in this program are partitioned into 16 subdomains for the 16 processes.\n\n\\Cref{fig:precice_muscle_force} visualizes the meshes and their partitioning to the different processes by the colored inset images. It can be seen that the fibers meshes and the 3D mesh used in the OpenDiHu program in the left box have corresponding subdomains.\n\nThe second OpenDiHu program visualized by the right box in \\cref{fig:precice_muscle_force} only solves the solid mechanics problem using a coarse 3D mesh. The mesh of this problem is partitioned to two processes, as shown by the image. \n\nThe three model parts are numerically coupled and need to exchange several variables. The action potential propagation model, shown at the lower left of \\cref{fig:precice_muscle_force}, computes the transmembrane voltage $V_m$ and the activation parameter $\\gamma$ and maps them from the 0D points on the fibers to the 3D mesh using the mapping scheme described in \\cref{sec:data_mapping_between_meshes}. The activation parameter $\\gamma$ is needed in the solid mechanics model. It is transferred between the two OpenDiHu programs using the functionality of preCICE. After the solid mechanics solver has computed a new deformation of the coarse solid mechanics mesh, preCICE maps the node positions to the finer 3D mesh in the left program. The geometries of the 3D and 1D meshes in the left program are updated accordingly.\nThe preCICE couplings in this example use serial explicit coupling and radial basis functions for the data mapping.\n\n% precice coupling scheme\n\\begin{figure}\n  \\centering%\n  \\def\\svgwidth{0.9\\textwidth}\n  \\input{images/results/application/precice_scheme1.pdf_tex}%\n  \\caption{Simulation of muscle contraction: Structure of a coupled simulation with the coupling library preCICE on 18 processes, consisting of the two independent OpenDiHu programs indicated by the gray boxes. The program in the left box solves the electric conduction model using the shown 3D mesh and the action potential propagation model using the shown 1D fiber meshes. Both meshes are partitioned to 16 subdomains as shown by the colors. The program in the right box solves the mechanics problem on a coarse 3D mesh, which is partitioned into 2 subdomains. The arrows between the models indicate the exchanged variables. The coupling within the left gray box is implemented in OpenDiHu, the coupling between the gray boxes is realized using preCICE.}%\n  \\label{fig:precice_scheme1}%\n\\end{figure}\n\nThe presented scheme in \\cref{fig:precice_scheme1} allows us to simulate muscle contraction and surface EMG signals. The volume coupling with preCICE is configured between the two 3D meshes. Even for scenarios where EMG signals are not of interest and only the muscle contraction resulting from the activated muscle fibers should be simulated, the presented approach can be used.\n\nAn alternative approach, where preCICE instead couples directly between the fiber meshes and the solid mechanics 3D mesh is also implemented. This approach neither includes the electric conduction model nor the fine 3D mesh for the left program.\nHowever, the mapping between the solid mechanics mesh and the set of 1D fiber meshes is more costly than the mapping between the two 3D meshes, as the fibers contain more data points in total than the 3D mesh of the electric conduction problem. A quantitative analysis of this effect is subject to work in progress.\n\nApart from ensuring better parallel scalability, the OpenDiHu model setup using preCICE also allows to exchange the solid mechanics solver by a different solver code, e.g., a commercial solver. The black-box approach of preCICE allows to exchange the mechanics solver without any changes to the electrophysiology simulation, contributing to the extensibility goal of combining modular model components.\n\n\\begin{reproduce_no_break}\n  The two programs with preCICE coupling can be used as follows. Note that the compilation of preCICE has to be enabled in the \\code{user-variables.scons.py} configuration file for the \\code{scons} build system in the \\code{$\\$$OPENDIHU_HOME} directory.\n  \\begin{lstlisting}[columns=fullflexible,breaklines=true,postbreak=\\mbox{\\textcolor{gray}{$\\hookrightarrow$}\\space}]\n    cd $\\$$OPENDIHU_HOME/examples/electrophysiology/fibers/fibers_contraction/with_precice_volume_coupling/build_release\n    mpirun -n 2 ./muscle_contraction ../settings_muscle_contraction.py ramp.py\n    mpirun -n 16 ./fibers_with_3d ../settings_fibers_with_3d.py ramp.py\n  \\end{lstlisting}\n\\end{reproduce_no_break}\n\n%-----\n\\subsection{Simulation of a Muscle-Tendon Complex using Surface Coupling with preCICE}\\label{sec:surface_coupling_contraction}\n\nIn all previously presented simulations of muscle contraction, the biceps muscle was considered in isolation. In the following, we present a  physiologically more correct scenario that includes a 3D description of the tendon mechanics.\nThe simulation consists of four individual solvers in OpenDiHu for the distal tendon, the two proximal tendons, and the muscle belly.\nThe coupling library preCICE is used to numerically couple the parts.\n\nAn advantage of simulations of an entire muscle-tendon complex is their more realistic line of action of the muscle force, compared with a model of the muscle belly without tendons. The goal of the simulation described in this section is to predict the progression of the total muscle force as  result of MU recruitment.\n\nFor the simulation of the muscle contraction part, we couple the fiber based electrophysiology model with the nonlinear solid mechanics model as described in \\cref{sec:fiber_based_contraction}. The electrophysiology part of the muscle uses the subcellular model of Shorten et al. \\cite{Shorten2007}. \nThe solid mechanics description of the three tendons uses the hyperelastic Saint-Venant Kirchhoff material, which is the extension of the linear elastic formulation given in \\cref{sec:material_linear_model} to the geometrically nonlinear regime.\nThe proximal tendons are fixed at their insertion points to the skeletal system. We apply corresponding Dirichlet boundary conditions. At the lower end of the distal tendon, a downwards pulling force is applied. We gradually increase the value of this force in the corresponding Neumann boundary conditions from zero up to the maximum value \\SI{100}{\\newton} during the first \\SI{100}{\\ms} of the simulation.\n\nThe muscle fibers are associated with 10 MUs and activated in a ramp during the first $\\SI{1.8}{\\s}$. After each MU has been activated for the first time, it fires with a MU specific frequency between \\SI{7.66}{\\hertz} and \\SI{23.92}{\\hertz} plus a random jitter value of \\SI{10}{\\percent}. This setup replicates the progressive recruitment scenario in \\cite{Klotz2020}.\n\nThe four simulation programs are connected using an implicit Neumann-Dirichlet multi-coupling scheme in preCICE with a constant relaxation factor of 0.5. At the interfaces between the muscle and the tendons, the implicit numerical coupling ensures continuity for the displacements, velocities and stresses.\nThe tendon solvers send their computed displacement and velocity values to the muscle model, where the corresponding Dirichlet boundary conditions are applied. The muscle model computes traction forces by integrating the stress values over the surface and sends the values to the tendon models, where corresponding Neumann boundary conditions are applied. \n\nWe configure preCICE to use Gaussian radial basis functions for the consistent mapping of the variables between the surface meshes of the muscle and the tendons. \nAn error threshold of $\\eps=0.1$ for the coupled displacement values is used to terminate the implicit coupling scheme. As a consequence, the scheme requires approximately two iterations per timestep on average to reach the error threshold. The coupling step is repeated with a timestep width of $\\dt_\\text{coupling} = \\SI{1}{\\ms}$.\n\nWe simulate two scenarios of this model. The first scenario considers a high spatial resolution of 1089 muscle fibers and a simulation time of approximately \\SI{1}{\\s}, while the second scenario considers only 81 fibers but a longer simulation time span of \\SI{10}{\\s}. \n\nIn the first scenario, we use a 3D mesh with $9\\times 9 \\times 21=1701$ nodes, which are partitioned into 160 subdomains.\nThe meshes of the three tendons each consists of 125 nodes and are each partitioned to four subdomains. We run the computation using 172 processes on four compute nodes of the supercomputer Hawk at the High Performance Computing Center Stuttgart. The hardware is described in more detail in  \\cref{sec:effects_of_the_mesh_width_emg}. The simulation time span of $\\SI{1}{\\s}$ has a runtime of approximately $\\SI{7}{\\hour}$ $\\SI{20}{\\minute}$.\n\n\\Cref{fig:precice_muscle_force} presents the simulation results of this scenario at the simulation time $t=\\SI{1.05}{\\s}$. \\Cref{fig:precice_activated_muscles_1} shows the muscle fibers, which are attached to the tendons at both ends. Several action potentials can be seen on the fibers. \\Cref{fig:precice_activated_muscles_2} displays the distribution of active stresses in the 3D mesh at the same simulation time. One vertical red line of higher active stress values can be seen at the foreside of the muscle belly, which corresponds to a region of higher muscle activity. This muscle activity results from a MU that is activated early on in the simulation scenario. A corresponding active fiber at that location can also be identified in \\cref{fig:precice_activated_muscles_1}.\n\\Cref{fig:precice_activated_muscles_3} visualizes the parallel partitioning of the 3D domains of muscle and tendons into 160 subdomains for the muscle mesh and 4 subdomains for each of the three tendon meshes.\n\n% contracted state\n\\begin{figure}\n  \\centering%\n  \\begin{subfigure}[t]{0.34\\textwidth}%\n    \\centering%\n    \\includegraphics[height=97mm]{images/results/application/precice_activated_muscles1.png}%\n    \\caption{Muscle fibers colored by the value of the transmembrane potential $V_m$.}%\n    \\label{fig:precice_activated_muscles_1}%\n  \\end{subfigure}\\,\n  \\begin{subfigure}[t]{0.28\\textwidth}%\n    \\centering%\n    \\includegraphics[height=97mm]{images/results/application/precice_activated_muscles2.png}%\n    \\caption{Active stress in the 3D muscle mesh.}%\n    \\label{fig:precice_activated_muscles_2}%\n  \\end{subfigure}\n  \\begin{subfigure}[t]{0.28\\textwidth}%\n    \\centering%\n    \\includegraphics[height=97mm]{images/results/application/precice_activated_muscles3.png}%\n    \\caption{Parallel partitioning scheme.}%\n    \\label{fig:precice_activated_muscles_3}%\n  \\end{subfigure}\n  \\caption{Simulation of a muscle-tendon complex. Muscle and tendon geometries of the scenario with 1089 muscle fibers, embedded in the skeletal system comprising the ulna bone (lower end) and humerus bone (upper end), result of the simulation at $t=\\SI{1.05}{\\s}$.}%\n  \\label{fig:precice_muscle_force}%\n\\end{figure}%\n\nThe second scenario uses a coarser 3D mesh with 525 nodes and a parallel partitioning into eight subdomains. We simulate the resulting muscle force, measured at the top insertion point of the proximal tendons, over a longer time period of \\SI{10}{\\s}. \\Cref{fig:precice_muscle_force0} shows the resulting relative force progression over time. The plot shows the total force as a moving average function over $\\SI{0.1}{\\s}$. It can be seen that the force initially increases, as more and more MUs get activated. A short delay between the onset of the last MU at $\\SI{1.8}{\\s}$ and the maximum force at \\SI{2.39}{\\s} can be seen. The muscle force exhibits large oscillations during the period of high muscle activation. They result from the lower firing frequencies of the later activated, large MUs and their higher contribution to the overall activity, compared to the smaller MUs. \n\n% muscle force\n\\begin{figure}\n  \\centering%\n  \\includegraphics[width=0.7\\textwidth]{images/results/application/precice_muscle_force.pdf}%\n  \\caption{Simulation of muscle force in a muscle-tendon complex. Resulting relative muscle force of the biceps muscle with attached tendons using the second scenario with 81 muscle fibers.}%\n  \\label{fig:precice_muscle_force0}%\n\\end{figure}\n\n\\Cref{fig:precice_muscle_force0} also shows that the generated muscle force rapidly decreases after the maximum is reached. This is a result from muscle fatigue, which is described by the Shorten subcellular model. The observed decrease to below \\SI{60}{\\percent} after \\SI{10}{\\s} can also be found in experimental studies of healthy subjects, e.g., in \\cite{Enoka2008}. \n\nIn conclusion, several biophysical simulation scenarios of MU activity induced muscle contraction have been presented in the previous sections. OpenDiHu allowed us to couple the computationally efficient fiber based electrophysiology description with the solid mechanics model of muscle deformation, as well as the biophysically more accurate multidomain model. An algorithm to include prestresses was presented and the coupling software preCICE was used to numerically couple individual parts of the multi-scale model. \n\nThe last presented scenario simulated the generated force of a muscle-tendon complex for a simulation time span of \\SI{10}{\\s}. \nIt can be used in the future to test hypotheses on the influence of various processes along the pathway from MU recruitment over muscle activation to force generation and macroscopic deformation. The simulated force progression related to the maximum voluntary contraction force is a macroscopic quantity, which can be easily measured in in vivo studies. Thus, a connection between the simulation domain and the experimental domain is given, and the microscopic subcellular processes in the muscle fibers are linked to a quantifiable outcome that can be compared with experiments.\n\n\\begin{reproduce_no_break}\n  The simulations in this section were carried out on the supercomputer Hawk in Stuttgart. The job scripts can be found in the repository at \\\\ \\href{https://github.com/dihu-stuttgart/performance}{github.com/dihu-stuttgart/performance} in the directory \\code{opendihu/15_precice_biceps/with_electrophysiology}. To run similar simulations on other computers, run commands that are similar to the following (adjust the numbers of processes):\n  \\begin{lstlisting}[columns=fullflexible,breaklines=true,postbreak=\\mbox{\\textcolor{gray}{$\\hookrightarrow$}\\space}]\n    cd $\\$$OPENDIHU_HOME/examples/electrophysiology/fibers/fibers_contraction/with_tendons_precice/multiple_tendons_with_electrophysiology\n    mpirun -n 1 muscle_electrophysiology_precice settings_muscle.py ramp.py\n    mpirun -n 1 tendon_linear_precice_dynamic settings_tendon_bottom.py\n    mpirun -n 1 tendon_linear_precice_dynamic settings_tendon_top_a.py\n    mpirun -n 1 tendon_linear_precice_dynamic settings_tendon_top_b.py\n  \\end{lstlisting}\n\\end{reproduce_no_break}\n\n", "meta": {"hexsha": "21a890a2e3a45ee70b47a3cc25805dbcccca6a25", "size": 69918, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "document/08_results_1b.tex", "max_stars_repo_name": "maierbn/phd_thesis_source", "max_stars_repo_head_hexsha": "babee64f01f15d93cb75140eb8c8424883b33c6c", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-05T19:00:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-05T19:00:04.000Z", "max_issues_repo_path": "document/08_results_1b.tex", "max_issues_repo_name": "maierbn/phd_thesis_source", "max_issues_repo_head_hexsha": "babee64f01f15d93cb75140eb8c8424883b33c6c", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "document/08_results_1b.tex", "max_forks_repo_name": "maierbn/phd_thesis_source", "max_forks_repo_head_hexsha": "babee64f01f15d93cb75140eb8c8424883b33c6c", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 98.8939179632, "max_line_length": 892, "alphanum_fraction": 0.7705168912, "num_tokens": 18138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.34754701128347687}}
{"text": "\\section*{Exercise 20.3-2}\n\\subsection*{Modify vEB trees to support keys that have associated satellite data}\n\nFor both of the keys in the vEB(2) trees (meaning leaves), which are not summaries, we define an additional field, holding the associated satellite data.\n\\\\\nFurthermore, we also define this new field for every $min$ in the (entire) tree, that is not a summary, since the elements stored in $min$ does not appear in the clusters.\n\\\\\nThis way, the new field holds the associated satellite data for every key in the entire tree, but it will not affect running time, since the satellite data are found together with the keys.", "meta": {"hexsha": "0efcbd6b04f5762b4d8476fc320412b02cf290c2", "size": 632, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Uge3/Ex.20.3-2.tex", "max_stars_repo_name": "pdebesc/AADS", "max_stars_repo_head_hexsha": "a26e24d18adee973d3ce88bdfd96d857ec472fdf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Uge3/Ex.20.3-2.tex", "max_issues_repo_name": "pdebesc/AADS", "max_issues_repo_head_hexsha": "a26e24d18adee973d3ce88bdfd96d857ec472fdf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Uge3/Ex.20.3-2.tex", "max_forks_repo_name": "pdebesc/AADS", "max_forks_repo_head_hexsha": "a26e24d18adee973d3ce88bdfd96d857ec472fdf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 79.0, "max_line_length": 189, "alphanum_fraction": 0.7768987342, "num_tokens": 147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.347535856635085}}
{"text": "%# -*- coding: utf-8-unix -*-\n% !TEX program = xelatex\n% !TEX root = ../thesis.tex\n% !TEX encoding = UTF-8 Unicode\n\n\\chapter{Procedures for evaluating the state of networks}\n\\label{appendixA}\n\\begin{algorithm}[H]\n\t\\caption{Algorithm for evaluating the state of networks}\n\t\\label{algo:evaluating}\n\t\\begin{algorithmic} \n\t\t\\State  \\bf{INPUT : Two-layer Network G(V, E), interval (m, n), repeat\\_number} \\normalfont \\\\\n\t\t\\Comment{In this study, The number of nodes(V/2) on each layer is $2048$, The number of edges is different according to network structures, and the interval of both parameters is $m = n = 40$}\n\t\t\\State  \\bf{OUTPUT : array Average\\_States} \\normalfont \n\t\t\\Comment{Array for Average States according to all parameters}\n\t\t\\State N = len(V), P = linspace(0, 1, m), V = linspace(0, 1, n), M = len(P), N = len(V)\n\t\t\\State set array Average\\_States[M][N]\n\t\t\\State set temp\\_Array[i]\n\t\t\\ForEach {$p \\in \\mathcal P $}\n\t\t\t\\ForEach {$v \\in \\mathcal V $}\n\t\t\t\t\\For{$i$ to repeat\\_number}  \n\t\t\t\t\\Comment{In this work, simulations are repeated 100times for average values}\n\t\t\t\t\t\\State \\Call{Doing\\_Interacting\\_Dynamics}{G(V,E), p, v}\n\t\t\t\t\t\\State temp\\_Array = GET\\_STATE(G(V,E))\n\t\t\t\t\t\\Comment{The summation of all nodes' states }\n\t\t\t\t\\EndFor\n\t\t\t\t\\State Average\\_States[p][v] = SUM(temp\\_Array)/repeat\\_number\n\t\t\t\\EndFor\n\t\t\\EndFor\n\t\t\\State \\Return {array Average\\_States[M][N]}\\\\\n\t\t\n\t\t\\Function {Doing\\_Interacting\\_Dynamics}{G(V,E), p, v}\n\t\t    \\For{$i$ to $100$steps}\n\t\t    \\Comment{100 steps for opinion evolutions}\n\t\t\t\t\\State \\Call{Doing\\_layer\\_A\\_dynamics}{G(V, E), p, sequential}\n\t\t\t\t\\State \\Call{Doing\\_layer\\_B\\_dynamics}{G(V,E), v}\n\t\t\t\\EndFor\n\t\t\t\\State \\Return {G(V, E)}\n\t\t\\EndFunction\n\t\t\\Comment{In this function, the updating rule are assumed as O(o, o) $\\to$ D(o), other updating rules are presented in Appendix \\ref{appendixC}}\n\t\\end{algorithmic}\n\\end{algorithm}\n\n\n\\chapter{Procedures for two-layer network dynamics}\n\\label{appendixB}\n\\begin{breakablealgorithm}\n\t\\caption{Algorithm for layer A dynamics}\n\t\\label{algo:layer A}\n\t\\begin{algorithmic} \n\t\\Function {Doing\\_layer\\_A\\_dynamics}{G(V, E), p, sequential}\n\t\t\\State in\\_edge\\_list = GET\\_INTERNAL\\_EDGE\\_LIST(G(V,E))\n\t\t\\State ex\\_edge\\_list = GET\\_EXTERNAL\\_EDGE\\_LIST(G(V,E))\\\\\n\t\t\\Comment{List of links between two nodes such as (i, j)}\n\t\t\\ForEach {edge $\\in$ in\\_edge\\_list}\n\t\t    \\State (a, b) = \\Call{Two\\_Node\\_Change}{edge[0], edge[1]}\n\t\t    \\State G(V, E)[edge[0]][state] = a\n\t\t    \\State G(V, E)[edge[1]][state] = b\n\t\t\\EndFor  \n\t\t\\ForEach {edge $\\in$ ex\\_edge\\_list}\n\t\t\t\\State a = \\Call{One\\_Node\\_Change}{edge[0], edges[1]}\n\t\t\t\\State G(V, E)[edge[0]][state] = a \n\t\t\\EndFor\n\t\t\\State \\Return {G(V, E)}    \n\t\\EndFunction\n\t\t\n\t\\Function{One\\_Node\\_Change}{edge[0], edges[1], G(V, E)}\n\t    \\Comment{In the case that the state of only one node is changed when two nodes interact: external edges, simultaneous updating rules}\t\n\t\t\\If {edge[0][state] * edge[1][state] > 0}\n\t\t\t\\State node\\_state(a, b) = {Persuasion\\_Process}{edge[0], edge[1]}\n\t\t\t\\State a = node\\_state(a, b)[0]\n\t\t\\EndIf\n\t\t\\If {edge[0][state] * edge[1][state] < 0}\n\t\t\t\\If {edge[0] * edge[1] = -1}\n\t\t\t\t\\If {random z > (1-p)/2}   \n\t\t\t\t\t\\Comment{0<z<1}\n\t\t\t\t\t\\State a = node\\_state(+1, +1)[0]\n\t\t\t\t\\Else\n\t\t\t\t\t\\State a = node\\_state(-1, -1)[0]\n\t\t\t\t\\EndIf\n\t\t\t\\Else\n\t\t\t\t\\State node\\_state(a, b) = \\Call{Compromise\\_Process}{edge[0], edge[1]}\n\t\t\t\t\\State a = node\\_state(a, b)[0]\n\t\t\t\\EndIf\n\t\t\\EndIf\n\t\t\\State \\Return{a}\n\t\\EndFunction\n\n\t\\Function{Two\\_Node\\_Change}{edge[0], edge[1]}\n\t\\Comment{In the case that the state of two nodes are changed when two nodes interact: internal edges, sequential updating rules}\t\n\t\t\\If {edge[0][state] * edge[1][state] > 0}\n\t\t\t\\State node\\_state(a, b) = \\Call{Persuasion\\_Process}{edge[0], edge[1]}\n\t\t\\EndIf\n\t\t\\If {edge[0][state] * edge[1][state] < 0}\n\t\t\t\\If {edge[0][state] * edge[1][state] = -1}\n\t\t\t\t\\If {random z > (1-p)/2}   \n\t\t\t\t\\Comment{0<z<1}\n\t\t\t\t\t\\State  node\\_state(+1, +1)\n\t\t\t\t\\Else\n\t\t\t\t\t\\State node\\_state(-1, -1)\n\t\t\t\t\\EndIf\n\t\t\t\\Else\n\t\t\t\t\\State node\\_state(a, b) = \\Call{Compromise\\_Process}{edge[0], edge[1]}\n\t\t\t\\EndIf\n\t\t\\EndIf\t\n\t\t\\State \\Return{node\\_state(a, b)}  \n\t\\EndFunction\n\t\n\t\\Function {Persuasion\\_Process}{edge[0], edge[1]}\n\t\\Comment{The states of nodes become extreme}\n\t\t\\If {edge[0]>0 and edge[1]>0}\n\t\t\t\\State node\\_state(a, b) = (\\Call{move\\_right}{edge[0]}, \\Call{move\\_right}{edge[1]})\n\t\t\\EndIf\n\t\t\\If {edge[0]<0 and edge[1]<0}\n\t\t\t\\State node\\_state(a, b) = (\\Call{move\\_left}{edge[0]}, \\Call{move\\_left}{edge[1]})\n\t\t\\EndIf\n\t\t\\State \\Return {node\\_state(a, b)}\n\t\\EndFunction\n\t\n\t\\Function {Compromise\\_Process}{edge[0], edge[1]}\n\t\\Comment{The states of nodes become moderate}\n\t\t\\If {edge[0]>0 and edge[1]<0}\n\t\t\t\\State node\\_state(a, b) = (\\Call{move\\_left}{edge[0]}, \\Call{move\\_right}{edge[1]})\n\t\t\\EndIf\n\t\t\\If {edge[0]<0 and edge[1]>0}\n\t\t\t\\State node\\_state(a, b) = (\\Call{move\\_right}{edge[0]}, \\Call{move\\_left}{edge[1]})\n\t\t\\EndIf\n\t\t\\State \\Return {node\\_state(a, b)}\n\t\\EndFunction\n\t\t\n\t\\Function {move\\_left}{a}\n\t\\Comment{the state of a node is changed into -1 or unchanged}\n\t\t\\State set Min = -2\n\t\t\\If {a = Min}\n\t\t\t\\State a = a\n\t\t\\Else\n\t\t\t\\State a = a - 1\n\t\t\\EndIf\n\t\t\\State \\Return {a}\n\t\\EndFunction\n\t\n\t\\Function {move\\_right}{a}\n\t\\Comment{the state of a node is changed into +1 or unchanged}\n\t\t\\State set Max = +2\n\t\t\\If {a = Max}\n\t\t\t\\State a = a\n\t\t\\Else\n\t\t\t\\State a = a + 1\n\t\t\\EndIf\n\t\t\\State \\Return {a}\n\t\\EndFunction\n\t\\end{algorithmic}\n\\end{breakablealgorithm}\n\n\\begin{algorithm}[H]\n\t\\caption{Algorithm for layer B dynamics}\n\t\\label{algo:layer B}\n\t\\begin{algorithmic} \n\t\t\\State set A = [for node i in layer A]\n\t\t\\State set B = [for node j in layer B]\n\t\t\\Function {Doing\\_layer\\_B\\_dynamics}{G(V,E), v, sequential}\n\t\t\t\\State same = 0\n\t\t\t\\State opposite = 0\n\t\t\t\\ForEach {node\\_i $\\in \\mathcal B $}\n\t\t\t\t\\State neighbor\\_list = GET\\_NEIGHBOR\\_NODES(node\\_i)\n\t\t\t\t\\ForEach{node\\_j $\\in$ neighbor\\_list}\n\t\t\t\t\t\\If {node\\_i * node\\_j > 0}\n\t\t\t\t\t\t\\State same += 1\n\t\t\t\t\t\t\\Comment {the number of the same orientation node}\n\t\t\t\t\t\\Else\n\t\t\t\t\t\t\\State opposite += 1\n\t\t\t\t\t\t\\Comment {the number of the opposite orientation node}\n\t\t\t\t\t\\EndIf\n\t\t\t\t\\EndFor\n\t\t\t\t\\If {opposite = 0}\n\t\t\t\t\t\\State prob = 0\n\t\t\t\t\\Else\n\t\t\t\t\t\\If {v = 0}\n\t\t\t\t\t\t\\State prob = 1\n\t\t\t\t\t\\Else\n\t\t\t\t\t\t\\State prob = ${{opposite / len(neighbor\\_list)}^{1 / v}} {\\cdot} {len(neighbor\\_list) / opposite}$\n\t\t\t\t\t\\EndIf\n\t\t\t\t\\EndIf\n\t\t\t\t\\If {prob < random z}\n\t\t\t\t\t\\State G(V, E)[node\\_i][state] = -G(V, E)[node\\_i][state]\n\t\t\t\t\\EndIf\n\t\t\t\\EndFor\n\t\t\t\\State \\Return G(V, E)\n\t\t\\EndFunction\n\t\\end{algorithmic}\n\\end{algorithm}\n\n\\chapter{Procedures for applying updating rules on a two-layer network}\n\\label{appendixC}\n\\begin{breakablealgorithm}\n\t\\caption{Updating rules of the layers' order}\n\t\\label{layers_order}\n\t\\begin{algorithmic} \n\t\t\\Function{Layer\\_Order}{layer\\_order}\n\t\t\t\\State set A = [for node i in layer A]\n\t\t\t\\State set B = [for node j in layer B]\n\t\t\t\\If {layer\\_order = sequential order}\n\t\t\t\t\\If{Layer A $\\to$ Layer B}\n\t\t\t\t\t\\State \\Call{Doing\\_layer\\_A\\_dynamics}{G(V, E), p}\n                \t\\State \\Call{Doing\\_layer\\_B\\_dynamics}{G(V, E), v}\n            \t\\EndIf\n\t\t\t\t\\If{Layer A $\\leftarrow$ Layer B}\n\t\t\t    \t\\State \\Call{Doing\\_layer\\_B\\_dynamics}{G(V, E), v}\n\t\t\t   \t\t\\State \\Call{Doing\\_layer\\_A\\_dynamics}{G(V, E), p}\n\t\t\t\t\\EndIf\n\t\t\t\\EndIf\n\t\t\t\\If{layer\\_order = simultaneous order}\n\t\t\t\t\\State copy\\_G(V, E) = DEEPCOPY(G(V, E))\n\t\t\t\t\\State A\\_G(V, E) = \\Call{Doing\\_layer\\_A\\_dynamics}{copy\\_G(V, E), p}\n\t\t\t\t\\State B\\_G(V, E) = \\Call{Doing\\_layer\\_B\\_dynamics}{copy\\_G(V, E), v}\n\t\t\t\t\\ForEach {node\\_i $\\in \\mathcal A $}\n\t\t\t\t\t\\State G(V, E)[node\\_i][state] =  A\\_G(V, E)[node\\_i][state]\n\t\t\t\t\\EndFor\n\t\t\t\t\\ForEach {node\\_j $\\in \\mathcal B $}\n\t\t\t\t\t\\State G(V, E)[node\\_j][state] =  B\\_G(V, E)[node\\_j][state]\n\t\t\t\t\\EndFor\n\t\t\t\\EndIf\n\t\t\t\\If{layer\\_order = random order} \n\t\t\t\t\\State node\\_i = CHOOSE\\_ONE\\_NODE(V)\n\t\t\t\t\\If{node\\_i $\\in \\mathcal A $}\n\t\t\t\t\t\\State \\Call{Doing\\_layer\\_A\\_dynamics}{copy\\_G(V, E), p}\n\t\t\t\t\\EndIf\n\t\t\t\t\\If{node\\_i $\\in \\mathcal B $}\n\t\t\t\t\t\\State \\Call{Doing\\_layer\\_B\\_dynamics}{copy\\_G(V, E), v}\n\t\t\t\t\\EndIf\n\t\t\t\\EndIf\n\t\t\\EndFunction\n\t\\end{algorithmic}\n\\end{breakablealgorithm}\n\n\n\\begin{breakablealgorithm}\n\t\\caption{Updating rules of the nodes' order}\n\t\\label{nodes_order}\n\t\\begin{algorithmic} \n\t\t\\State in\\_edge\\_list = GET\\_INTERNAL\\_EDGE\\_LIST(G(V,E))\n\t\t\\State ex\\_edge\\_list = GET\\_EXTERNAL\\_EDGE\\_LIST(G(V,E))\\\\\n\t\t\\Comment{List of links between two nodes such as (i, j)}\n\t\t\\If {sequential order}\n\t\t\t\\ForEach {edge $\\in$ in\\_edge\\_list}\n\t\t\t\\Comment{internal edges}\n\t\t\t\t\\If {edge$\\in$ Layer A}\n\t\t\t\t\\Comment{When the layer A includes the edge}\n\t\t\t\t\t\\State (a, b) = \\Call{Two\\_Node\\_Change}{edge[0], edge[1], G(V, E)}\n\t\t\t\t\t\\State G(V, E)[edge[0]][state] = a\n\t\t\t\t\t\\State G(V, E)[edge[1]][state] = b\n\t\t\t\t\\EndIf\n\t\t\t\t\\If {edge$\\in$ Layer B}\n\t\t\t\t\\Comment{When the layer B includes the edge}\n\t\t\t\t\t\\State \\Call{Doing\\_layer\\_B\\_dynamics}{G(V, E), v, sequential}\n\t\t\t\t\\EndIf\n\t\t\t\\EndFor  \n\t\t\t\\ForEach {edge $\\in$ ex\\_edge\\_list}\n\t\t\t\\Comment{external edge}\n\t\t\t\t\\State \\Call{One\\_Node\\_Change}{edge[0], edges[1], G(V, E)}\n\t\t\t\t\\State G(V, E)[edge[0]][state] = a\n\t\t\t\\EndFor\n\t\t\t\\State \\Return {G(V, E)}\n\t\t\\EndIf\n\t\t\\If {simultaneous order}\n\t\t\tcopy\\_G(V, E) = DEEPCOPY(G(V, E))\n\t\t\t\\ForEach {edge $\\in$ in\\_edge\\_list}\n\t\t\t\t\\If {edge$\\in$ Layer A}\n\t\t\t\t\t\\State previous\\_state = copy\\_G(V, E)\n\t\t\t\t\t\\State a = \\Call{One\\_Node\\_Change}{edge[0], edge[1], copy\\_G(V, E)}\n\t\t\t\t\t\\State G(V, E)[edge[0]][state] = a\n\t\t\t\t\t\\State copy\\_G(V, E) = previous\\_state\n\t\t\t\t\\EndIf\n\t\t\t\t\\If {edge$\\in$ Layer B}\n\t\t\t\t\t\\State previous\\_state = copy\\_G(V, E)\n\t\t\t\t\t\\State G(V, E)[edge[0][state]\n\t\t\t\t\t\\State = \\Call{Doing\\_layer\\_B\\_dynamics}{copy\\_G(V, E), v, sequential}[edge[0]][state]\n\t\t\t\t\t\\State G(V, E)[edge[1][state]\n\t\t\t\t\t\\State = \\Call{Doing\\_layer\\_B\\_dynamics}{copy\\_G(V, E), v, sequential}[edge[1]][state]\n\t\t\t\t\t\\State copy\\_G(V, E) = previous\\_state\n\t\t\t\t\\EndIf\n\t\t\t\\EndFor  \n\t\t\t\t\\ForEach {edge $\\in$ ex\\_edge\\_list}\n\t\t\t\t\t\\State a = \\Call{One\\_Node\\_Change}{edge[0], edges[1], copy\\_G(V, E)}\n\t\t\t\t\t\\State G(V, E)[edge[0]][state] = a\n\t\t\t\t\\EndFor\n\t\t\t\t\\State \\Return {G(V, E)}\n\t\t\\EndIf\n\t\t\\If {random order}\n\t\t\t\\While{len(edge\\_list) = 0}\n\t\t\t\t\\State SELECT edge IN edge\\_list\n\t\t\t\t\\Comment{select an edge among the edge lists until all edges are selected}\n\t\t\t\t\\If {edge $\\in$ in\\_edge\\_list}\n\t\t\t\t\t\\If {edge$\\in$ Layer A}\t\n\t\t\t\t\t\t\\State (a, b) = \\Call{Two\\_Node\\_Change}{edge[0], edge[1], G(V, E)}\n\t\t\t\t\t\t\\State G(V, E)[edge[0]][state] = a\n\t\t\t\t\t\t\\State G(V, E)[edge[1]][state] = b\n\t\t\t\t\t\\EndIf\n\t\t\t\t\t\\If {edge$\\in$ Layer B}\t\n\t\t\t\t\t\t\\State \\Call{Doing\\_layer\\_B\\_dynamics}{G(V, E), v, sequential}\n\t\t\t\t\t\\EndIf\n\t\t\t\t\\EndIf\n\t\t\t\t\\If {edge $\\in$ ex\\_edge\\_list}\n\t\t\t\t\t\\State a = \\Call{One\\_Node\\_Change}{edge[0], edges[1], G(V, E)}\n\t\t\t\t\t\\State G(V, E)[edge[0]][state] = a\n\t\t\t\t\\EndIf\n\t\t\t\\EndWhile\n\t\t\t\\State \\Return {G(V, E)}\n\t\t\\EndIf\n\t\\end{algorithmic}\n\\end{breakablealgorithm}\n\n\n\\begin{breakablealgorithm}\n\t\\caption{Updating rules of the edges' order(Simultaneous)}\n\t\\label{edges_order}\n\t\\begin{algorithmic} \n\t\t\\ForEach {node i $ \\in \\mathcal V $}\n\t\t\t\\State (a, b, c) = \\Call{Calculate\\_Prob}{G(V, E), p, node i}\n\t\t\t\\State set random z\n\t\t\t\\Comment{0 < z < 1}\n\t\t\t\\If {z > a + b}\n\t\t\t\t\\State s = COMPROMISE\\_FUNC(node i)\n\t\t\t\t\\Comment {the state of node i becomes moderate, the state of node i is returned}\n\t\t\t\\EndIf\n\t\t\t\\If {z < a}\n\t\t\t\t\\State s = UNCHANGE(node i)\n\t\t\t\t\\Comment {the state of node i is unchanged, the state of node i is returned}\n\t\t\t\\EndIf\n\t\t\t\\If {z > a and z < a + b}\n\t\t\t \t\\State s = PERSUASION\\_FUNC(node i)\n\t\t\t \t\\Comment {the state of node i becomes extreme, the state of node i is returned}\n\t\t\t\\EndIf\n\t\t\t\\State G(V, E)[node i][state] = s\n\t\t\\EndFor\n\t\t\\State \\Return {G(V, E)}\n\t\t\n\t\t\\Function{Calculate\\_Prob}{G(V, E), p, node i}\n\t\t\t\\State same = GET\\_SAME\\_ORIENTATION\\_NUM(node i)\n\t\t\t\\State opposite = GET\\_OPPOSITE\\_ORIENTATION\\_NUM(node i)\n\t\t\t\\For{$n$ to same}\n\t\t\t\t\\For{$m$ to opposite}\n\t\t\t\t\t\\State n\\_combi = $_{same} C_n$\n\t\t\t\t\t\\State m\\_combi = $_{opposite} C_m$\n\t\t\t\t\t\\If {$n = m$}\n\t\t\t\t\t\t\\State $unchange += {p^{n+opposite-m}} * {(1 - p)^{same-n+m}} * n\\_combi * m\\_combi$\n\t\t\t\t\t\\EndIf\n\t\t\t\t\t\\If{$n > m$}\n\t\t\t\t\t\t\\State $persuasion += {p^{n+opposite-m}} * {(1 - p)^{same-n+m}} * n\\_combi * m\\_combi$\n\t\t\t\t\t\\EndIf\n\t\t\t\t\t\\If{$n < m$}\n\t\t\t\t\t\t\\State $compromise += {p^{n+opposite-m}} * {(1 - p)^{same-n+m}} * n\\_combi * m\\_combi$\n\t\t\t\t\t\\EndIf\n\t\t\t\t\\EndFor\n\t\t\t\\EndFor\n\t\t\t\\State \\Return {unchange, persuasion, compromise}\n\t\t\\EndFunction\t\t\t\n\t\\end{algorithmic}\n\\end{breakablealgorithm}\n\n\n\n\\chapter{Selecting keynodes by single and multiple indicators}\n\\label{appendixD}\n\\begin{algorithm}[!htb]\n\t\\caption{Algorithm for ranking by single and multiple indicators}\n\t\\label{algo:keynodes}\n\t\\begin{algorithmic} %每行显示行号\n\t\t\\State  \\bf{INPUT : Network G(V, E), selected\\_layer, parameters $(p, v)$, indicators} \\normalfont \n\t\t\\State  \\bf{OUTPUT : array critical\\_nodes\\_order} \\normalfont \n        \\State set N = len(V), M = len(indicators)\n\t\t\\State set array node\\_centrality[N][M]\n\t\t\\State set array node\\_rank[N][M]\n\t\t\\State set array temp[N]\n\t\t\\State set array critical\\_nodes\\_order[N]\n\t\t\\State node\\_centrality = Calculate\\_Centrality(G(V, E), selected\\_layer)\n\t\t\\State node\\_rank = Get\\_Rank(node\\_centrality)\n        \\ForEach {$i \\in \\mathcal V $}\n            \\For{$m \\gets 0$ to $M-1$}\n\t\t\t\t\\State temp[i] += node\\_rank[i][m]\n\t\t \t\\EndFor\n\t\t\\EndFor\n        \\ForEach {$i \\in \\mathcal V $}\n\t\t\t\\State critical nodes order.append(temp.index(min(temp)))\n\t\t\t\\State temp[temp.index(min(temp))] = $2*N$ or $\\inf$\n\t\t\\EndFor\n\t\t\\State \\Return array critical\\_nodes\\_order[N]\n\t\\end{algorithmic}\n\\end{algorithm}\n", "meta": {"hexsha": "f57d52e57a893993a0bfdfc044d5e9ba092354f9", "size": 13587, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/app_code.tex", "max_stars_repo_name": "leighsix/thesisgit", "max_stars_repo_head_hexsha": "77d3c41a7c045c656d2e28dc4e5cfea418632d62", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tex/app_code.tex", "max_issues_repo_name": "leighsix/thesisgit", "max_issues_repo_head_hexsha": "77d3c41a7c045c656d2e28dc4e5cfea418632d62", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-09-21T09:57:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-19T19:06:17.000Z", "max_forks_repo_path": "tex/app_code.tex", "max_forks_repo_name": "leighsix/thesisgit", "max_forks_repo_head_hexsha": "77d3c41a7c045c656d2e28dc4e5cfea418632d62", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8384615385, "max_line_length": 194, "alphanum_fraction": 0.6214764113, "num_tokens": 5064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.34734535367853997}}
{"text": "\\chapter{parReset}\n\n\\section{Introduction}\n\nA linearized process may have parameters that are initialized, changed and used, and subsequently ignored until they are initialized again.\nParameters that often follow this pattern are \\emph{control flow parameters}.\n\nDuring the period in between the last change or use of a parameter and its subsequent initialization, a parameter could have different values.\nThese values contribute to the size of the state space of the process \\emph{without} adding any new behavior!\nIt may therefore be advantageous to detect from which moment the value of a parameter is no longer used and set it to a default value instead.\n\n\\section{Algorithm}\n\nThe algorithm is a generalization of an existing algorithm \\cite{van2009state}.\nIt consists of two phases, a preparation phase and an iteration phase.\n\n\\subsection{Preparation phase}\n\nConsider all possible pairs of summands of the LPE (including symmetric pairs).\nOf a given summand pair $(s, t)$, let $t$ be a \\emph{successor} of $s$ if $s$ contains a recursive process instantiation and if the following equation is satisfiable:\n\\begin{align*}\nc_s \\land {c_t}[p \\rightarrow v_s(p) \\;|\\; p \\in P]\n\\end{align*}\n\nwhere\n\n\\begin{itemize}\n\\item $c_s$ and $c_t$ are the guards of summands $s$ and $t$, respectively;\n\\item $P$ is the set of all process parameters;\n\\item $v_s$ is a function that yields the expression that summand $s$ assigns to a given process parameter in its recursive process instantiation.\n\\end{itemize}\n\nDuring the preparation phase, we determine all successors of each summand of the LPE.\nThis gives an overapproximation of the control flow graph of the LPE.\n\n\\subsection{Iteration phase}\n\nThis phase follows these steps:\n\n\\begin{enumerate}\n\n\\item For each summand $s$, create a set $R_s$ that contains all process parameters.\nThis means that, initially, we assume that all process parameters are used by one or more of the successors of $s$.\n\n\\item For each summand $s$, set the value of $R_s$ to $\\bigcup\\limits_{t \\in S_s}^{} r(t)$ where $S_s$ is the set of all successors of $s$ (as determined during the previous phase) and where $r$ is the function\n\\begin{align*}\nr(t) = \\left( \\text{vars}(c_t) \\cup \\bigcup\\limits_{x \\in R_t}^{} \\text{vars}(v_t(x)) \\right) \\setminus C_t\n\\end{align*}\n\nwhere\n\n\\begin{itemize}\n\\item $\\text{vars}(c_t)$ gives the free variables in $c_t$, the guard of summand $t$;\n\\item $v_t$ is a function that yields the expression that summand $t$ assigns to a given process parameter in its recursive process instantiation;\n\\item $\\text{vars}(v_t)$ gives the free variables in $v_t$;\n\\item $C_t$ is the set of the communication variables used by summand $t$.\n\\end{itemize}\n\n\\item Repeat the previous step until the new value of $R_s$ is the same as before for all summands $s$.\n\n\\item For each summand $s$ with $R_s \\subset P$, choose some $\\rho = [x \\rightarrow h_x \\;|\\; x \\in P \\setminus R_s]$ so that $({c_s} \\land {c_t}[p \\rightarrow v_s(p) \\;|\\; p \\in P])[\\rho]$ is unsatisfiable for all $t \\notin S_s$, where\n\n\\begin{itemize}\n\\item $P$ is the set of all process parameters of the LPE;\n\\item $h_x$ is a closed expression of the same sort as $x$;\n\\item $c_s$ and $c_t$ are the guards of summands $s$ and $t$, respectively.\n\\end{itemize}\n\nFor each process parameter $x \\in P \\setminus R_s$, change the recursive process instantiation of $s$ so that $x$ is assigned $v_s(x)[\\rho]$.\nNote that the choice of $\\rho$ ensures that the set of summands that are successors of $s$ can only decrease.\n\nIn practice, it is expensive to generate a suitable $\\rho$, and only the initial values of the parameters in $P \\setminus R_s$ are tried (that is, $\\rho = [x \\rightarrow v_0(x) \\;|\\; x \\in P \\setminus R_s]$).\nIf this does not satisfy the further requirements, the summand is left unchanged.\n\n\\end{enumerate}\n\n\\section{Example}\n\nConsider the following LPE:\n\n\\begin{lstlisting}\n//Process definition:\nPROCDEF example[A :: Int, B](x, y :: Int)\n  = A ? i [[x==0]] >-> example[A, B](1, i)\n  + A ? i [[x==1 && i==y]] >-> example[A, B](2, y)\n  + B [[x==2]] >-> example[A, B](3, y)\n  + B [[x==3]] >-> example[A, B](0, y)\n  ;\n\n//Initialization:\nexample[A, B](0, 0);\n\\end{lstlisting}\n\nFinding the successors of each summand is easy: each summand has exactly one successor, namely the next one, except in case of the fourth summand, where the first summand is the successor.\n\nIt is also obvious that $x$ will always be in $R_s$ for each summand $s$, because each summand uses $x$ in its guard.\n\nProcess parameter $y$ will always be in $R_{s_1}$, where $s_1$ is the first summand, because $y$ is used in the guard of $s_1$'s successor (the second summand).\nAfter a few iterations, however, $y$ is removed from $R_{s_2}$ to $R_{s_4}$.\nThis means that $y$ is assigned a default value in the corresponding summands.\nDepending on the mood of the SMT solver, this could give\n\n\\begin{lstlisting}\n//Process definition:\nPROCDEF example[A :: Int, B](x, y :: Int)\n  = A ? i [[x==0]] >-> example[A, B](1, i)\n  + A ? i [[x==1 && i==y]] >-> example[A, B](2, 0)\n  + B [[x==2]] >-> example[A, B](3, 0)\n  + B [[x==3]] >-> example[A, B](0, 0)\n  ;\n\n//Initialization:\nexample[A, B](0, 0);\n\\end{lstlisting}\n\n\n\n\n", "meta": {"hexsha": "be1461c62a55b456b4d46a732d9531f2c99bc77b", "size": 5197, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "_tex/lpeopsDoc/parReset.tex", "max_stars_repo_name": "Sercammus/TxsLpeOps", "max_stars_repo_head_hexsha": "3354f2762cf195e571f4c05040ec500165969359", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_tex/lpeopsDoc/parReset.tex", "max_issues_repo_name": "Sercammus/TxsLpeOps", "max_issues_repo_head_hexsha": "3354f2762cf195e571f4c05040ec500165969359", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_tex/lpeopsDoc/parReset.tex", "max_forks_repo_name": "Sercammus/TxsLpeOps", "max_forks_repo_head_hexsha": "3354f2762cf195e571f4c05040ec500165969359", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.6722689076, "max_line_length": 236, "alphanum_fraction": 0.7119492015, "num_tokens": 1506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.34734535367853997}}
{"text": "\\documentclass[12pt]{article}\n\\usepackage{lipsum}\n\\usepackage{authblk}\n\\usepackage{fancyhdr}\n\n\\usepackage{amssymb}\n\\usepackage{amsmath}\n\n\\usepackage[english]{babel}\n\\usepackage{tikz}\n\\usetikzlibrary{positioning}\n\\usepackage[colorlinks=true,\n            urlcolor=blue,\n            linkcolor=black,\n            citecolor=black]{hyperref}\n\\usepackage[doublespacing]{setspace}\n\\usepackage{geometry}\n  \\geometry{\n    a4paper,\n    right=25mm,\n    left=25mm,\n    bottom=25mm,\n    top=25mm\n  }\n\n\\usepackage{amsmath}\n\\usepackage{listings}\n\n\\pagestyle{fancy}\n\\setlength{\\headheight}{15pt}\n\n\\usepackage{algpseudocode}\n\\usepackage{algorithm}\n\n%\\usepackage{cite}\n\\usepackage[nottoc,numbib]{tocbibind}\n\\usepackage{natbib}\n\n\\usepackage{../presentation/colordef}\n\\usepackage{../presentation/lvblisting}\n\n\\usepackage{wrapfig}\n\\usepackage{booktabs}\n%\\raggedbottom\n\\usepackage{tikz}\n\\usetikzlibrary{shapes.geometric, arrows}\n\n\\tikzstyle{io} = [trapezium, trapezium left angle=70,\n                  trapezium right angle=110, minimum width=3cm,\n                  minimum height=0.5cm, text centered,\n                  draw=black, fill=blue!30]\n\\tikzstyle{process} = [rectangle, minimum width=3cm,\n                       minimum height=0.5cm, text centered,\n                       draw=black, fill=orange!30]\n\\tikzstyle{decision} = [rectangle, minimum width=3cm,\n                        minimum height=0.5cm, text centered,\n                        draw=black, fill=green!30]\n\\tikzstyle{algo} = [circle, minimum width=0.5cm, draw=black, fill=orange!30]\n\\tikzstyle{arrow} = [thick,->,>=stealth]\n\n\\renewenvironment{abstract}{%\n\n\\begin{center}\n\\begin{minipage}{0.9\\textwidth}\n\\rule{\\textwidth}{1pt}}\n{\\par\\noindent\\rule{\\textwidth}{1pt}\n\\end{minipage}\n\\end{center}}\n\n\\begin{document}\n\n\\title{Numerical Methods for solving Eigenvalue-Problems}\n\\author{Thomas Siskos}\n\\date{}\n\n\\begin{titlepage}\n  \\begin{center}\n\n  \\includegraphics[scale=1.25]{../presentation/hulogo.pdf} \\par\n  {\\scshape\\LARGE Humboldt Universit{\\\"a}t zu Berlin \\par}\n\n  {\\scshape\\Large Seminar Paper\\par}\n\n  {\\huge\\bfseries Numerical Methods for solving Eigenvalue-Problems\\par}\n\n\\vspace{1cm}\n\n  {\\Large\\itshape Thomas Siskos (580726)\\par}\n\n  {\\Large\\scshape Numerical Introductory Course\\par}\n\n  \\vfill\n  Supervised by: \\par\n  {\\Large Prof. Dr. Brenda L{\\'o}pez Cabrera \\par}\n  \\vfill\n  {\\large \\today\\par}\n  \\end{center}\n\n\\end{titlepage}\n\n\\tableofcontents\n\\newpage\n\\listofalgorithms\n\\listoffigures\n\\listoftables\n\\newpage\n\n\\section{Motivation}\n\n\\begin{singlespacing}\n\\begin{abstract}\n\\centerline{\\textbf{Abstract}} \\\\\n\\small\nEigenvalues and eigenvectors are often the solution to multidimensional optimization problems, however computing them by hand for anything but trivial matrices is most of the time infeasible or inpractical. To this extend we would like to deploy an automated procedure which yields the correct eigenvectors and eigenvalues. We demonstrate the relevance of eigenvalues and eigenvectors by revising two applications from statistics, Principal Component Analysis and Fisher's Linear Discriminant Analysis, which we follow up by investigating four algorithms suited for eigenvalue problems. Finally we provide a compound solution that takes advantage of each algorithm's strengths.\n\\end{abstract}\n\\vspace{3mm}\n\\end{singlespacing}\n\nFor many statistical applications eigenvectors provide a formidable solution. Be it dimensionality reduction in terms of a Principal Component Analysis or classification by Fisher's Linear Discriminant Analysis, both come in the guise of optimization problems. But what are eigenvalues and eigenvectors?\n\nIf $A$ is an $n \\times n$ matrix, $v$ is a non-zero vector and $\\lambda$ is a scalar, such that\n\n\\begin{equation}\n\\label{eigenvalue-def}\nAv = \\lambda v\n\\end{equation}\n\nthen $v$ is called an \\textit{eigenvector} and $\\lambda$ is called an \\textit{eigenvalue} of the matrix $A$.\nAn eigenvalue of A is a root of the characteristic equation,\n\n\\begin{equation}\n\\label{eigenvalue-solve}\ndet\\left(A - \\lambda I \\right) = 0.\n\\end{equation}\n\nEach \\textit{eigenvalue} is associated with an \\textit{eigenvector}. Geometrically speaking, we require a vector which, when multiplied by matrix $A$, will not get rotated but only elongated by the \\textit{eigenvalue} $\\lambda$ \\citep[p. 13]{NME}.\n\nWhen confronted with a high-dimensional data matrix $X \\in \\mathbb{R}^{n \\times m}$ an analyst often wishes to find a lower-dimensional representation, while conserving as much of the data's structure as possible. One way of achieving this goal is to choose a standardized linear combination of features that aim to maximize the variance of the projection $\\delta^{\\prime} X$. We can formalize this as\n\n\\begin{equation}\n\t\\label{pca_obj}\n    \tmax\\ \\delta^{\\prime} Var \\left(X\\right) \\delta \\;\\; s.t. \\;\\; \\sum \\delta_i^2 = 1.\n\\end{equation}\n\nThe solution to this optimization problem is given by\n\\begin{equation}\n\\label{pca_sol}\n\tY = \\Gamma^{\\prime} \\left(X - \\mu\\right)\n\\end{equation}\n\nwhere $Y \\in \\mathbb{R}^{n \\times m}$ is the matrix of rotations,\n\t  $\\Gamma \\in \\mathbb{R}^{m \\times m}$ is the matrix of eigenvectors,\n\t  $\\mu \\in \\mathbb{R}^m$ is the vector of sample means \\citep[p. 234]{MVA}.\n\nA second use for Eigenvalues lies in Fisher's Linear Discriminant Analysis for classification problems. In this setting we would like to find the rotation that is best suited to separate the classes. To this effect we try to maximize the between-class-variance while simoultaneously trying to minimize the within-class variance. This is equivalent to maximizing the so called Rayleigh-coefficient\n\n\\begin{equation}\n\\label{LDA}\nmax J = \\frac{J_b(w)}{J_w(w)} = \\frac{w^{\\prime} S_{b} w}{w^{\\prime} S_{w} w}.\n\\end{equation}\n\nThe between and within class variance matrices are defined as $S_b = \\sum\\limits_{c=1}^{C}(\\mu_c - \\mu)(\\mu_c - \\mu)^{\\prime}$ and $S_w = \\sum\\limits_{c=1}^{C}\\sum\\limits_{i \\in c}(x_i - \\mu_c)(x_i - \\mu_c)^{\\prime}$. The solution to this maximization problem is given by\n\\begin{equation}\nS_B^{\\frac{1}{2}} S_W^{-1} S_B^{\\frac{1}{2}} v = \\lambda v,\n\\end{equation}\n\nwhich again is an eigenvalue problem of a square, symmetric matrix and can be readily computed \\citep[p. 219]{duda}.\n\nIn the following we will try to extract the eigenvalues of matrices by reformulating any complicated eigenvalue problem into a straightforward one by diagonalizing the matrix in question, without altering the eigenvalues we would like to compute. In section two we provide the mathematical tools, which allow us to do so. We follow these justifications by proposing two main algorithms for computing eigenvalues, first the Jacobi-Method for symmetric matrices, then the QR-Method for arbitrary square matrices in section 3. Additionally, for the QR-Method we define two extensions which try to increase the initial QR-algorithm's speed.\nFor all algorithms we provide implementations in the \\texttt{Python}-programming-language, all plots have been produced with the \\texttt{matplotlib}-module and the custom algorithms rely solely on modules from \\texttt{Python}'s \\texttt{scipy} environment for scientific computing \\citep{python, matplotlib, scipy}. All scripts are available \\href{https://github.com/thsis/NIS18}{online}. In section 4 we will analyse the implemented routines by critically reflecting upon the accuracy of the obtained results as well as their efficiency. In the final section we provide a final algorithm which combines the strengths of the defined procedures by chosing the algorithm that is most fit for the underlying problem.\n% ==============================================================================\n\\section{Similarity Transformations}\n\nIn general we want to reformulate the eigenvalue problem of a complicated matrix into an eigenvalue problem of a simple matrix, which yields the same eigenvalues. Simple matrices in our case will be diagonal matrices, since with them it is possible to identify their eigenvalues as entries on the main diagonal. A transformation that conserves the eigenvalues of a matrix is called a \\textit{similarity transformation}.\n\nTwo $n \\times n$ matrices $A$ and $B$ are called \\textit{similar} if there exists an invertible matrix $P$ such that\n\n\\begin{equation}\n\\label{similarity}\nA = P^{-1} B P.\n\\end{equation}\n\nIt is obvious that the similarity relationship is commutative as well as transitive. If $A$ and $B$ are similar, it holds that\n\n\\begin{align*}\nB - \\lambda I &= P^{-1} B P - \\lambda P^{-1} I P \\notag \\\\\n              &= A - \\lambda I.\n\\end{align*}\n\n Hence $A$ and $B$ have the same eigenvalues. This fact also follows immediately from the transitivity of the similarity relationship and the fact that a matrix is similar to the diagonal matrix formed from its eigenvalues, as stated in the spectral-decomposition. Important types of similarity transformations are based around orthogonal matrices. If $Q$ is orthogonal and\n\n$$ A = Q^{\\prime} B Q, $$\n\n$A$ and $B$ are called \\textit{orthogonally similar} \\citep{NLA}. We will use \\textit{orthogonal similarity transformations} to diagonalize matrices we wish to know the eigenvalues of. For our custom implementations we will make use of Givens-Rotations and Householder Reflectors (for a detailed discussion consider the appendix).\n\n% ==============================================================================\n\\section{Algorithms}\n% ------------------------------------------------------------------------------\n\\subsection{Jacobi Method}\n\nThe \\textit{Jacobi-Method} for computing the eigenvalues of a symmetric matrix $A \\in \\mathbb{R}^{n \\times n}$ deploys a sequence of orthogonal similarity transformations that eventually results in\n$$ A = P \\Lambda P^{-1} \\Leftrightarrow \\Lambda = P^{-1} A P,$$\n\nwhere $\\Lambda$ is diagonal and $P$ consists of a sequence of matrix multiplications $P = \\prod\\limits_{k=1}^{K} V_{p_k, q_k}(\\theta_k)$ and $V_{p_k, q_k}(\\theta_k)$ is a matrix that performs a Givens-Rotation. Such a rotation is performed by an identity matrix with four of its elements replaced, such that\n\\small\n\\begin{equation}\n\\label{givens_rotator}\nV_{pq}(\\theta) = \\begin{bmatrix}\n                      1 \\\\\n                        & \\ddots \\\\\n                        &        & \\cos\\theta    &        & \\sin\\theta  \\\\\n                        &        &               & \\ddots     \\\\\n                        &        & -\\sin\\theta   &        & \\cos\\theta   \\\\\n                        &        &               &        &            &  \\ddots \\\\\n                        &        &               &        &            &         & 1 \\\\\n                 \\end{bmatrix}\n\\end{equation}\n\\normalsize\n\\newpage\nThe \\textit{Jacobi iteration} is defined as\n\n\\begin{equation}\nA^{(k)} = V^{\\prime}_{p_k, q_k}(\\theta_k) A^{(k-1)} V_{p_k, q_k}(\\theta_k),\n\\end{equation}\n\nwhere $p_k, q_k$ and $\\theta_k$ are chosen such that $A^{(k)}$ resembles more a diagonal matrix than $A^{(k-1)}$. Specifically they will be chosen as to reduce the sum of squares of the off-diagonal elements. Also, note that $A^{(k)}$ and $A^{(k-1)}$ are similar, since $V^{\\prime}_{p_k, q_k}(\\theta_k)$ is an orthogonal matrix for every step $k$. The benefit of matrices as in (\\ref{givens_rotator}) is, that it is easy to choose an angle $\\theta_k$ in order to introduce a zero in a single multiplication step. Here we use the rotations in the context of a similarity transformation, so it is a little more complicated.\n\nWe require that $a_{pq}^{(k)} = 0$, this implies\n\\begin{equation}\n\\label{theta-troubles}\na^{(k-1)}_{pq} (\\cos^2\\theta - \\sin^2\\theta) + \\left( a^{(k-1)}_{pp} - a^{(k-1)}_{qq} \\right) \\cos\\theta \\sin\\theta = 0.\n\\end{equation}\nWe can use the trigonometric identities\n\\begin{align*}\n\\cos(2\\theta) &= \\cos^2 \\theta \\sin^2 \\theta \\\\\n\\sin(2\\theta) &= 2 \\cos\\theta \\sin\\theta,\n\\end{align*}\n\nin (\\ref{theta-troubles}) we have\n$$\\tan(2\\theta) = \\frac{2a^{(k-1)}_{pq}}{a^{(k-1)}_{pp} - a^{(k-1)}_{qq}}.$$\n\nFrom this we can retrieve the angle and obtain the rotation matrix in each iteration \\citep[p. 128]{NLA}.\n\nThe algorithm converges if the off-diagonal elements are sufficiently small. The best index pair at a given iteration is the pair $(p, q)$ that satisfies\n\n\\[\n|a^{(k-1)}_{pq}| = \\mathop{\\max_{i<j}} |a^{(k-1)}_{ij}|.\n\\]\n\nIf this choice is made, the Jacobi Method can be shown to converge \\citep[p. 128]{NLA}.\n\n\\begin{figure}[H]\n\\begin{center}\n\\caption{\\href {https://github.com/thsis/NIS18/tree/master/media/plots}{Progress Jacobi-Method}  \\protect\\includegraphics[scale=0.05]{qletlogo.pdf}}\n  \\label{j-plot}\n  \\includegraphics[scale=0.6]{../media/plots/jacobi.png}\n\\end{center}\n\\end{figure}\n\n\nFigure \\ref{j-plot} visualizes the progress of the \\textit{Jacobi}-method on a symmetric $5 \\times 5$ matrix. As we can see, in the first iteration the element $a_{43}$ is eliminated. In the subsequent operations the \\textit{Jacobi}-method continues to eliminate any non-zero entries on the off-diagonal until the algorithm convergences after 10 iterations.\n\n\\begin{algorithm}\n\\caption{\\href {https://github.com/thsis/NIS18/blob/master/algorithms/eigen.py}{\\texttt{jacobi}}  \\protect\\includegraphics[scale=0.05]{qletlogo.pdf}}\n\n\\label{j-algo}\n\\begin{algorithmic}[1]\n  \\Require symmetric matrix $A$\n  \\Ensure $0 < precision < 1$\n  \\Statex \\textbf{initialize: } $L \\gets A$; $U \\gets I$; $L_{max} \\gets 1$\n  \\While{$L_{max} > precision$}\n    \\State Find indices $i$, $j$ of largest value in lower triangle of $abs(L)$\n        \\State $L_{max} \\gets L_{i,j}$\n            \\State $\\theta \\gets \\frac{1}{2}\\cdot \\arctan(\\frac{2A_{i, j}}{A_{i, i}-A_{j, j}})$\n    \\State $V \\gets I$\n    \\State $V_{i, i}, V_{j, j} \\gets \\cos \\theta$; $V_{i, j}, V_{j, i} \\gets -\\sin \\theta,\\; \\sin \\theta$\n    \\State $A \\gets V^{\\prime} A V$; $U \\gets UV$\n\n  \\EndWhile\\\\\n  \\Return $diag(A),\\; U$\n\\end{algorithmic}\n\\end{algorithm}\n\n% ------------------------------------------------------------------------------\n\\subsection{QR-Method}\n\nThe most widely used algorithm to extract eigenvalues is the so called \\textit{QR}-method. The most important advantage of the \\textit{QR}-method over the \\textit{Jacobi}-method is that it can be applied to non-symmetric matrices. Note however, that it is simpler for symmetric matrices, since the eigenvalues are real-valued.\n\nThe \\textit{QR}-method to extract the eigenvalues of a square matrix $A \\in \\mathbb{R}^{n \\times n}$ is performed by first computing the titular \\textit{QR} decomposition of $A$.\n\n\\begin{equation}\n\\label{qr_a}\nA = QR,\n\\end{equation}\n\nwhere $Q$ is an orthogonal and $R$ is an upper triangular matrix. Then define the \\textit{QR} iteration as\n\n\\begin{equation}\n\\label{qr-method}\n  A^k = Q_{k-1}^{\\prime} A_{k-1} Q_{k-1} = R_{k-1}Q_{k-1}\n\\end{equation}\n\nNote hereby that all matrices in the sequence $\\{A_k\\}$ share the same eigenvalues, since this procedure is a similarity transformation due to $Q$'s orthogonality \\citep[p. 121]{NME}. Additionally, for practical applications it is preferable to compute the \\textit{QR}-iteration in the way shown at the rightmost part of equation (\\ref{qr-method}). Although, mathematically, each statement is exactly identical there is a non-negligible difference due to computational imperfections and limited machine precision. The reason is that the computation of $Q_{k-1}^{\\prime} A_{k-1} Q_{k-1}$, obviously, requires two matrix multiplications whereas the result of $R_{k-1}Q_{k-1}$ can be readily obtained by one. When combining multiple steps over a long sequence of \\textit{QR} iterations the additional computations lead to additional rounding errors, which can have an influence on the accuracy of the obtained results. Besides, less computations lead of course to a faster procedure in general.\n\n\\begin{figure}\n\\begin{center}\n\\label{qrm1-plot}\n\\caption{\\href {https://github.com/thsis/NIS18/tree/master/media/plots}{Progress basic QR-Method}  \\protect\\includegraphics[scale=0.05]{qletlogo.pdf}}\n  \\includegraphics[scale=0.6]{../media/plots/qrm1.png}\n\\end{center}\n\\end{figure}\n\nFigure \\ref{qrm1-plot} visualizes the progress of the basic \\textit{QR}-method on the same $5 \\times 5$ matrix as in Figure \\ref{j-plot}. Compared to the \\textit{Jacobi}-method it does not explicitly pick a single element that will be eliminated per iteration. Instead, the \\textit{QR}-method extracts the eigenvalues by a process that is called \\textit{chasing}. By that we mean that alternating steps are being performed, which create non-zero eintries in positions $(i+2, i)$, $(i+3, i)$ and $(i+3, i+1)$ and restore them to zero, as the nonzero entries are moved farther down the matrix \\citep[p. 130]{NLA}. We can also see that compared to the \\textit{Jacobi}-Method, so far, the \\textit{QR}-algorithm lacks in speed. Where the \\textit{Jacobi}-method was almost done diagonalizing the matrix in iteration 10, the basic \\textit{QR}-algorithm still had multiple non-zero entries left. Thus we would like to make minor improvements on the algorithm's efficiency.\n\\begin{algorithm}\n\\caption{\\href {https://github.com/thsis/NIS18/blob/master/algorithms/eigen.py}{\\texttt{QRM1}}  \\protect\\includegraphics[scale=0.05]{qletlogo.pdf}}\n\\label{qr1-meth}\n  \\begin{algorithmic}[1]\n    \\Require square matrix $A$\n    \\Statex \\textbf{initialize: } $conv \\gets False$\n    \\While{not $conv$}\n      \\State $Q, R \\gets$ QR-Factorization of $A$\n      \\State $A \\gets RQ$\n      \\If{$A$ is diagonal}\n        \\State $conv \\gets \\texttt{True}$\n      \\EndIf\n    \\EndWhile\\\\\n    \\Return $diag\\left(A\\right),\\; Q$\n  \\end{algorithmic}\n\\end{algorithm}\n\n\n\\subsubsection{Hessenberg Variant}\n\nIn order to speed up the \\textit{QR}-method it is advisable to transform the matrix to its upper \\textit{Hessenberg} form. A matrix $A$ is of upper \\textit{Hessenberg} form if it is upper triangular except for the first subdiagonal, which may be non-zero. In particular $a_{ij} = 0\\; \\forall i > j + 1$:\n\\small\n$$\n\\begin{bmatrix}\nX & X & X  & \\dots &  X & X\\\\\nX & X & X &  \\dots &  X & X\\\\\n0 & X & X &  \\dots &  X & X\\\\\n0 & 0 & X &  \\dots &  X & X \\\\\n\\vdots &  \\vdots & & \\ddots  & \\vdots  & \\vdots\\\\\n0 & 0 & 0 &  \\dots &  X & X \\\\\n\\end{bmatrix}$$\n\\normalsize\nA matrix can be reduced to \\textit{Hessenberg} form in a finite number of similarity transformations using Householder transformations or Givens rotations. For symmetric matrices the transformation into a \\textit{Hessenberg}-form results in a tridiagonal matrix. But even for non-symmetric matrices, the \\textit{Hessenberg}-form allows a large saving in subsequent computations. After the transformation we can deploy the previously defined \\textit{QR}-method \\citep[p. 130]{NLA}.\n\n\\begin{figure}\n\\centering\n\\caption{\\href {https://github.com/thsis/NIS18/tree/master/media/plots}{Progress Hessenberg-QR-Method}  \\protect\\includegraphics[scale=0.05]{qletlogo.pdf}}\n  \\label{qr2-plot}\n  \\includegraphics[scale=0.6]{../media/plots/qrm2.png}\n\\end{figure}\n\nFigure \\ref{qr2-plot} visualizes the progress of the \\textit{Hessenberg} variant of the \\textit{QR}-method. In order to make it comparable to the previous algorithms the same $5 \\times 5$-dimensional matrix is being evaluated. We can readily see, that the transformation to \\textit{Hessenberg}-form results in a tridiagonal matrix. This facilitates computations and explains the vastly improved resulting matrix after 10 iterations compared to the basic \\textit{QR}-method. However, it still does not match the progress of the \\textit{Jacobi}-method after the same number of iterations.\n\n\n\\begin{algorithm}\n\\caption{\\href {https://github.com/thsis/NIS18/blob/master/algorithms/eigen.py}{\\texttt{QRM2}}  \\protect\\includegraphics[scale=0.05]{qletlogo.pdf}}\n\\label{qr2-meth}\n\\begin{algorithmic}[1]\n  \\Require square matrix $A$\n  \\State $A \\gets \\texttt{hessenberg(}A\\texttt{)}$\n  \\State continue with: \\Call {QRM1} A\n\\end{algorithmic}\n\\end{algorithm}\n\n\\subsubsection{Accelerated Variant}\n\nWe could already improve the \\textit{QR}-method and cut down on computational cost. However, we still cannot match the results of the \\textit{Jacobi} method. To this effect we present one additional adjustment on the \\textit{QR}-method that aims to improve convergence speed. The general idea is, that we deliberately create an additional zero entry on the main diagonal by subtracting a scalar on each element, perform the \\textit{QR}-iteration and finally undo the subtraction. In particular, we define\n\n\\begin{equation}\n\\label{qrm3-prop}\nT^{m} = \\begin{bmatrix}\n\n\\alpha^{m}_1 & \\beta^{m}_1  & 0            & 0            & \\dots            & 0                                  \\\\\n\\beta^{m}_1  & \\alpha^{m}_2 & \\beta^{m}_2                                                                         \\\\\n0            & \\beta^{m}_2  & \\alpha^{m}_3 & \\beta^{m}_3  &                  & \\vdots                             \\\\\n             &              & \\ddots       & \\ddots       & \\ddots                                                \\\\\n             &              &              &              & \\beta^{m}_{n-2}  & \\alpha^{m}_{n-1} & \\beta^{m}_{n-1} \\\\\n0            &              &              &              &                  & \\beta^{m}_{n-1}  & \\alpha^{m}_n    \\\\\n\n\\end{bmatrix}\n\\end{equation}\n\n\n\\begin{align*}\nT^{m}       &= T - t _{n, n} I \\\\\nT^{m}       &= QR \\\\\nT^{m+1}     &= T^{m} + t _{n, n} I\n\\end{align*}\n\nAfter this we can define the accelerated iteration step as\n\\begin{align}\n\\label{qrm3}\nR_m &= Q^{\\prime}_m\\left(T^m - \\alpha_n^{m}I\\right) \\\\\nT^{m+1} &= Q^{\\prime}_m\\left(T^m - \\alpha_n^{m}I\\right)Q_m + \\alpha_n^{m}I \\\\\n        &= Q^{\\prime}_m T^m Q_m\n\\end{align}\n\nAgain $T^{m+1}$ is similar to $T^m$.\n\n\\begin{figure}[H]\n\\centering\n\\caption{\\href {https://github.com/thsis/NIS18/tree/master/media/plots}{Progress Accelerated QR-Method}  \\protect\\includegraphics[scale=0.05]{qletlogo.pdf}}\n  \\label{qr3-plot}\n  \\includegraphics[scale=0.6]{../media/plots/qrm3.png}\n\\end{figure}\n\nFigure \\ref{qr3-plot} visualizes the progress of the accelerated \\textit{QR}-method. For comparability, the matrix used, is the same $5 \\times 5$ matrix as before. Most notably is, that the accelerated method still performs worse than the \\textit{Jacobi} method. So far results seem similar compared to the \\textit{Hessenberg} variant of the \\textit{QR}-method. The case can be made that the accelerated method performs considerably better than the basic \\textit{QR}-method and slightly better than the \\textit{Hessenberg} variant after 10 iterations. Howbeit, this claim warrants further analysis.\n\n\\begin{algorithm}\n\\begin{algorithmic}[1]\n\\caption{\\href {https://github.com/thsis/NIS18/blob/master/algorithms/eigen.py}{\\texttt{QRM3}}  \\protect\\includegraphics[scale=0.05]{qletlogo.pdf}}\n\n\\Require square matrix $A \\in \\mathbb{R}^{p \\times p}$\n\\State $T \\gets \\texttt{hessenberg}(A),\\ conv \\gets False$\n\\While{not $conv$}\n    \\State $Q, R \\gets$ QR-Factorization of $T - t_{p-1, p-1} I$\n    \\State $T \\gets RQ + t_{p-1, p-1}I$\n    \\If{$T$ is diagonal}\n        \\State $conv \\gets True$\n    \\EndIf\n\\EndWhile\\\\\n\\Return $diag\\left(T\\right),\\; Q$\n\\end{algorithmic}\n\\end{algorithm}\n\n% ==============================================================================\n\\section{Analysis}\n\nIn order to test the quality of our implemented algorithms we will follow a two pronged approach. First, we will scrutinize the quality of the obtained results. Once we can be sure that the implemented routines are reliable or, to be more precise, under which conditions our routines are reliable we can analyze their convergence behavior and compare the efficiency accross algorithms in terms of computational cost.\n% ------------------------------------------------------------------------------\n\\subsection{Accuracy}\n\nIf we wish to investigate the accuracy of our algorithms, we first need to define what we mean by that. We set up an environment of unit tests that compare the absolute difference between the vector of true eigenvalues of a matrix and the vector of computed eigenvalues by our custom algorithms. If any element of this $L_1$-norm is larger than a threshold of $10^{-5}$ we consider the test as failed. In order to obtain matrices with known eigenvalues we will reverse the spectral decomposition, which states that every square, symmetric matrix $A \\in \\mathbb{R}^{m \\times m}$ can be written as\n\\begin{equation}\n\\label{spectral-decomp}\nA = \\Gamma \\Lambda \\Gamma^{\\prime} = \\sum\\limits_{j=1}^m \\lambda_j \\gamma_j \\gamma^{\\prime}_j,\n\\end{equation}\nwhere $\\Lambda = diag(\\lambda_1, \\dots, \\lambda_m)$ is a diagonal matrix with the eigenvalues of $A$ on its main diagonal and where $\\Gamma=(\\gamma_1, \\dots, \\gamma_m)$ is the matrix containing the associated eigenvectors \\citep{MVA}. This means we can draw a random vector of eigenvalues $\\lambda_{true}$ and a random orthogonal matrix to construct a test matrix $A_{test}$ \\citep{lapack}. Once the matrix $A_{test}$ is initialized, we can plug it into the eigenvalue-routine we wish to test.\n\n\n\\begin{table}[b]\n\\centering\n\\caption{\\href {https://github.com/thsis/NIS18/tree/master/tests/tests_eigen.py}{Failed unit tests accross matrix-sizes}  \\protect\\includegraphics[scale=0.05]{qletlogo.pdf}}\n\\label{acc-res}\n\\scriptsize\n\\begin{tabular}{ccrrrrr}\n\\toprule\nAlgorithm & Maximum number & \\multicolumn{5}{c}{Dimension}\\\\\n\\cline{3-7}\n          & of iterations &    3 &    4 &    5 &     6 &     7 \\\\\n\\toprule\n\\bottomrule\n\\textit{Jacobi} & - &    0 &    0 &    0 &     0 &     0 \\\\\n\\textit{QRM1}   & 10 &  785 &  952 &  994 &   999 &  1000 \\\\\n                & 100 &  110 &  224 &  349 &   474 &   565 \\\\\n                & 1000 &    7 &   16 &   33 &    38 &    45 \\\\\n                & 10000 &    1 &    1 &    1 &     1 &     3 \\\\\n                & 100000 &    0 &    0 &    0 &     0 &     0 \\\\\n\\textit{QRM2}   & 10 &  826 &  975 &  997 &  1000 &  1000 \\\\\n                & 100 &  111 &  191 &  360 &   467 &   602 \\\\\n                & 1000 &    9 &   16 &   22 &    35 &    58 \\\\\n                & 10000 &    0 &    0 &    3 &     2 &     0 \\\\\n                & 100000 &    0 &    0 &    0 &     0 &     0 \\\\\n\\textit{QRM3}   & 10 &  251 &  616 &  896 &   983 &   997 \\\\\n                & 100 &   29 &   52 &  116 &   222 &   311 \\\\\n                & 1000 &    6 &    2 &    8 &    19 &    21 \\\\\n                & 10000 &    0 &    0 &    1 &     1 &     3 \\\\\n                & 100000 &    0 &    0 &    0 &     0 &     0 \\\\\n\\bottomrule\n\\end{tabular}\n\\normalsize\n\\end{table}\n\n\nThe number of failures out of 1000 unit tests on matrices of different dimensions are catalogued in Table \\ref{acc-res}. Most notably, we see that the \\textit{Jacobi}-method outperforms any of the \\textit{QR}-methods in terms of accuracy. This is mostly due to its convergence criterion being defined differently than the convergence criterion of the \\textit{QR}-methods. Simply put, the \\textit{Jacobi}-method will always converge in this setup. Also keep in mind, that since the \\textit{Jacobi}-method is only allowed for symmetric matrices, it essentially eliminates two non-zero off-diagonal elements at once. Comparing only the \\textit{QR}-methods amongst each other one can clearly see, that the quality of the obtained results increases, the more willing an analyst is to wait. Convergence is slower for the \\textit{QR}-methods and a premature stop leads to poor eigenvalues. One the other hand, if the \\textit{QR}-methods converge, they unanimously pass all tests. It would therefore be possible to always achieve an arbitrary grade of precision by allowing for a higher number of iterations. For the highest possible accuracy one can set the maximum number of iterations to infinity.\n\n% ------------------------------------------------------------------------------\n\\subsection{Efficiency}\n\n\n\\begin{figure}[b]\n\\centering\n\\caption{\\href {https://github.com/thsis/NIS18/blob/master/tests/tests_eigen.py}{Unit-tests: Iterations}  \\protect\\includegraphics[scale=0.05]{qletlogo.pdf}}\n  \\label{algo_efficiency}\n  \\includegraphics[width=\\textwidth, height=6.5cm]{../media/plots/iterations_boxplot.png}\n\\end{figure}\n\nNow that we can be confident that each of the routines is able to offer accurate results we are interested in which method is most appropriate for which kind of matrix. Especially, we are interested in convergence speed. Figure \\ref{algo_efficiency} shows the distribution of steps performed before the algorithms reached convergence or their maximum allowed number of iterations. Again, the \\textit{Jacobi}-method outperforms every \\textit{QR}-method. For matrices of small dimensions, i.e. eleven or less, the accelerated \\textit{QR}-method outperforms the other \\textit{QR}-methods. However, for larger matrices the \\textit{Hessenberg} variant seems to be slightly more appropriate, since the accelerated method tends to have a wider range of needed steps. Additionally, the accelerated method's distribution has a wider tail whenever the dimension of the test matrices is larger than eleven. This means that high waiting times, operating on the same matrix, are more likely to occur using the \\textit{accelerated} variant compared to the \\textit{Hessenberg} variant or even the basic variant. This can only mean that the supplementary additions and subtractions of the accelerated method provide a questionable aid. In some cases they do seem to help for small matrices, however when confronted with larger matrices the cost of the additions and subtractions outweighs the benefit of the facilitated \\textit{QR}-step. Surprisingly, there seems to be no striking difference between the distributions of the basic and the \\textit{Hessenberg} variants. Looking closely, the only effect of performing a \\textit{Hessenberg} transformation prior to running a \\textit{QR}-algorithm on a test matrix is to mitigate outliers in terms of computation steps needed before convergence. And even that is true, only for large matrices. This can only mean that the cost of computing the \\textit{Hessenberg}-form of the matrix is roughly as high as the reduction of steps needed before convergence is reached.\n\n% ==============================================================================\n\\section{Conclusion}\n\\begin{figure}\n\\centering\n\\caption{\\href {https://github.com/thsis/NIS18/tree/master/algorithms/eigen.py}{Decision process of the final eigenvalue routine}  \\protect\\includegraphics[scale=0.05]{qletlogo.pdf}}\n\\begin{tikzpicture}\n\\node (in1) [io] {Input: matrix A};\n\\node (dec_sym) [decision, below of=in1, yshift=-0.25cm] {Is A symmetric?};\n\\node (algo1) [algo, below of=dec_sym, xshift=-2cm, yshift=-0.5cm] {\\texttt{Jacobi}};\n\\node (dec_small) [decision, below of=dec_sym, xshift=2cm, yshift=-0.5cm] {rows of A $\\leq$ 11?};\n\\node (algo2) [algo, below of=dec_small, xshift=-1cm, yshift=-0.5cm] {\\texttt{QRM3}};\n\\node (algo3) [algo, below of=dec_small, xshift=1cm, yshift=-0.5cm] {\\texttt{QRM2}};\n\n\\draw [arrow] (in1) -- (dec_sym);\n\\draw [arrow] (dec_sym) -- node[anchor=east] {yes} (algo1);\n\\draw [arrow] (dec_sym) -- node[anchor=west] {no} (dec_small);\n\\draw [arrow] (dec_small) -- node[anchor=east] {yes} (algo2);\n\\draw [arrow] (dec_small) -- node[anchor=west] {no} (algo3);\n\\end{tikzpicture}\n\\end{figure}\n\nFinally, we would like to present a compound solution which combines the strengths of all presented algorithms and automatically picks the procedure that fits best to the problem. For obvious reasons, it is best to chose the \\textit{Jacobi}-method, whenever applicable. That is, when the input-matrix is symmetric. Whenever the matrix is not symmetric, a second decision based on the matrix' size will determine which \\textit{QR}-method will be used. If the matrix' dimension is smaller than eleven it will chose the accelerated \\textit{QR} method. Otherwise, the \\textit{Hessenberg} variant of the \\textit{QR}-method will be deployed.\n\nWe have thus demonstrated the practical importance of eigenvalues in the context of Principal Component Analysis and Fisher's Linear Discriminant Analysis. For computing the eigenvalues we have shown various numerical procedures. We examinated the \\textit{Jacobi}- and the \\textit{QR}-method, as well as a selection of simple improvements towards the basic \\textit{QR}-method. We have shown that the implemented routines can achieve an arbitrary grade of precision and provided a guided procedure for when to use which of the provided algorithms.\n\n\n% ==============================================================================\n\\newpage\n\\section{Appendix}\n\\subsection{Householder-Reflections}\n\nOur goal is to diagonalize a matrix in order to programmatically extract its eigenvalues. In section 2 we have seen that there exist such transformations that conserve the eigenvalues of a given matrix. However, we require transformations that, additionally, eliminate non-zero entries on the off-diagonal elements of a particular matrix. A greedy technique, that eliminates all but the first elements of a vector is proposed in the form of Householder-Reflections.\n\nLet $u$ and $v$ be orthonormal vectors and let $x$ be a vector in the space spanned by $u$ and $v$, such that\n$$x = c_1 u + c_2 + v$$\nfor some scalars $c_1$ and $c_2$. The vector\n$$\\tilde{x}=-c_1 u + c_2 v$$\nis a \\textit{reflection} of x through the line difined by the vector u. Now consider the matrix\n\n\\begin{equation}\nP = I - 2 uu^{\\prime}.\n\\end{equation}\nNote that\n\\begin{align*}\nPx &= c_1 u + c_2 v - 2c_1 uuu^{\\prime} - 2 c_2 v uu^{\\prime} \\\\\n   &= c_1 u + c_2 v - 2c_1 u^{\\prime}uu - 2 c_2 u^{\\prime} v u \\\\\n   &= -c_1 u + c_2 v\\\\\n   &= \\hat{x}.\n\\end{align*}\n\nThe matrix $P$ is called a reflector. The usefulness of Householder-Reflections stems from the fact that it is easy to transform a vector of the form\n\n$$x = (x_1, x_2, \\dots, x_n)$$\n\ninto a vector\n$$\\hat{x} = (\\hat{x}_1, 0, \\dots, 0).$$\n\nIf $Qx = \\hat{x}$, then $||x||_2 = ||\\hat{x}||_2$ and thus $\\hat{x_1} = \\pm ||x||_2$, since it is the only non-zero entry. To construct the reflector let\n\\begin{equation}\n\\label{house-con}\nv = (x_1 + sign(x_1)||x||_2, x2, \\dots, x_n)\n\\end{equation}\nand $u = \\frac{v}{||v||_2}$ \\citep{NLA}. We use the $sign$-function, which simply returns the sign of its argument in order to avoid the numerical problem known as \\textit{catastrophic cancellation}. It can occur when adding two very close, but different, floating point numbers of differing signs. In some unfortunate cases both of these numbers get represented by the same computer number and, because of their opposing signs cancel each other out. In our case this would mean, that we reflect the vector onto the origin. Fortunately, by making use of the \\textit{sign} function we can make sure that both summands will share the same sign, thus mitigating any concerns about catastrophic cancellation.\n\nWe use reflectors to compute the so called $QR$ factorization of an aribitrary square matrix $A \\in \\mathbb{R}^{n \\times n}$.\n\n\\begin{equation}\n\\label{QR-prop}\nA = QR\n\\end{equation}\n\nwhere $Q$ is orthogonal and $R$ is upper triangular. We use Householder transformations to reflect the $i^{th}$ column and produce zeros below the $(i, i)$ element. The QR-factorization of a matrix $A \\in \\mathbb{R}^5$ would therefore consist of five Householder-reflections with $Q=P_5 P_4 P_3 P_2 P_1$. The number of computations for the \\textit{QR} factorization in this fashion is $2n^3 / 3$ multiplications and $2n^3 / 3$ additions \\citep[p. 110]{NLA}.\n\\newpage\n% ------------------------------------------------------------------------------\n\\subsection{Givens-Rotations}\n\n\\begin{wrapfigure}[7]{r}{0.35\\textwidth}\n\\centering\n\\caption{\\href {https://github.com/thsis/NIS18/blob/master/media/plots}{Rotation of \\textit{x}}  \\protect\\includegraphics[scale=0.05]{qletlogo.pdf}}\n\\includegraphics[scale=0.5]{../media/plots/givens.png}\n\\end{wrapfigure}\n\nAnother way of forming the \\textit{QR}-factorization is by using orthogonal transformations which rotate a vector in a way such that a specific element becomes 0 and only one other element in the vector being changed. These transformations are called \\textit{Givens transformations, Givens Rotations} or \\textit{Jacobi transformations}\n\nUsing orthogonal transformations we can also rotate a vector in such a way that a specified element becomes 0 and only one other element in the vector is changed. The basic idea can be seen in a two-dimensional space. We wish to rotate the vector $x = (x_1, x_2)$ to $\\tilde{x} = (\\tilde{x_1}, 0)$ as with a reflector.\n\nIt is easy to see that the orthogonal matrix\n$$Q=\\begin{bmatrix}\n\\cos\\theta & \\sin\\theta \\\\\n-\\sin\\theta & \\cos\\theta\n\\end{bmatrix}$$\n\nperforms the desired rotation, if $\\cos\\theta = \\frac{x_1}{||x||_2}$ and $\\sin\\theta = \\frac{x_2}{||x||_2}$\n\nIn general, we can construct an orthogonal $matrix V_{pq}$, that will transform the vector $$x = (x_1,\\dots, x_p, \\dots x_q, \\dots, x_n)$$ to $$\\tilde{x} = (x_1,\\dots, \\tilde{x}_p, \\dots 0, \\dots, x_n)$$. The matrix that does this is\n\\scriptsize\n\\begin{equation}\n\\label{givens-rotation}\nV_{pq}(\\theta) = \\begin{bmatrix}\n                      1 \\\\\n                        & \\ddots \\\\\n                        &        & \\cos\\theta    &        & \\sin\\theta  \\\\\n                        &        &               & \\ddots     \\\\\n                        &        & -\\sin\\theta   &        & \\cos\\theta   \\\\\n                        &        &               &        &            &  \\ddots \\\\\n                        &        &               &        &            &         & 1 \\\\\n                 \\end{bmatrix}\n\\end{equation}\n\\normalsize\n\twhere $\\cos\\theta = \\frac{x_p}{||x||}$ and $\\sin\\theta = \\frac{x_q}{||x||}.$\n\nA rotation matrix is therefore the same as an identitiy matrix, in which we change four elements \\citep[p. 105]{NME}. We will use Givens rotations primarily in the Jacobi-Method.\n\\newpage\n\\subsection{Code}\n\\subsubsection{Eigenvalue Routines}\n  \\lstinputlisting[language=Python]{../algorithms/helpers.py}\n  \\lstinputlisting[language=Python]{../algorithms/eigen.py}\n  \\newpage\n\\subsubsection{Analysis: Figures}\n  \\lstinputlisting[language=Python]{../analysis/analysis.py}\n  \\newpage\n\\subsubsection{Analysis: Unit tests}\n  \\lstinputlisting[language=Python]{../tests/tests_eigen.py}\n  \\newpage\n% ==============================================================================\n\\bibliographystyle{apalike}\n\\bibliography{references}\n\n\\end{document}\n", "meta": {"hexsha": "3e798586c6f158a435d040758de0c57a7f5944fe", "size": 38217, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "term-paper/term-paper.tex", "max_stars_repo_name": "thsis/NIS18", "max_stars_repo_head_hexsha": "1f2a7be1ab209fa7c0a25cb8eace744336b07c1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "term-paper/term-paper.tex", "max_issues_repo_name": "thsis/NIS18", "max_issues_repo_head_hexsha": "1f2a7be1ab209fa7c0a25cb8eace744336b07c1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "term-paper/term-paper.tex", "max_forks_repo_name": "thsis/NIS18", "max_forks_repo_head_hexsha": "1f2a7be1ab209fa7c0a25cb8eace744336b07c1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 61.4421221865, "max_line_length": 1996, "alphanum_fraction": 0.6869456001, "num_tokens": 10665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.34734535367853997}}
{"text": "% Note on compiling: requires external programs dot (from the graphvix package\n% on Debian/Ubuntu) and dot2tex.\n% You need to pass the --shell-escape option to pdflatex\n% (or use the Makefile, which required latexmk).\n%\\documentclass[aspectratio=169,handout]{beamer}\n%\\documentclass[aspectratio=169,handout,hyphens]{beamer} % hyphens option for url package which beamer loads.\n\\documentclass[aspectratio=169,hyphens]{beamer} % hyphens option for url package which beamer loads.\n\n\\def\\UrlFont{\\small\\tt}\n\n\\usepackage{minted}\n\\usepackage{color}\n%\\usepackage[pgf,dot]{dot2texi}\n%\\usepackage{tikz}\n%\\usetikzlibrary{shapes,arrows}\n\n\\usetheme{Pittsburgh}\n\\usecolortheme{beaver}\n% \\useoutertheme{infolines}\n\n\\title{Constraint Programming in Haskell}\n\\subtitle{Melbourne Haskell Users Group}\n\\author{David Overton}\n\\date{29 October 2015}\n\n\\AtBeginSection[]\n{\n\t\\begin{frame}\n\t\t\\frametitle{Table of Contents}\n\t\t\\tableofcontents[currentsection]\n\t\\end{frame}\n}\n\n%\\lstnewenvironment{code}{\\lstset{language=Haskell,basicstyle=\\small}}{}\n\n\\newminted[code]{haskell}{fontsize=\\small}\n\\newmint[hask]{haskell}{fontsize=\\small}\n\\newminted{prolog}{fontsize=\\small}\n\n\\definecolor{mygreen}{rgb}{0,0.6,0}\n\\definecolor{mygrey}{rgb}{0.5,0.5,0.5}\n\\definecolor{mymauve}{rgb}{0.58,0,0.82}\n\n\\newtheorem{observation}[theorem]{Observation}\n\n\\newcommand\\myheading[1]{%\n  \\par\\bigskip\n  {\\large\\color{blue}#1}\\par\\smallskip}\n\\begin{document}\n\n\\frame{\\titlepage}\n\n\\section{Constraint programming}\n\n\\begin{frame}\n    \\frametitle{Constraint programming}\n    Constraint programming is a declarative programming paradigm for solving constraint satisfaction problems.\n    \\pause\n    \\begin{itemize}\n        \\item A set of \\emph{constraint variables} over a \\emph{domain}, e.g. Booleans, integers, reals, finite domain.\n    \\pause\n        \\item A set of \\emph{constraints} between those variables.\n    \\pause\n        \\item A \\emph{solver} to find solutions to the constraints, i.e. assignments of variables to values in the domain such that all constraints are satisfied.\n    \\end{itemize}\n    \\pause\n    Applications: planning, scheduling, resource allocation, computer graphics, digital circuit design, programming language analysis, \\ldots\n\\end{frame}\n\n\\section{Constraint logic programming}\n\n\\begin{frame}\n    \\frametitle{Constraint logic programming}\n    \\begin{itemize}\n        \\item Constraint programming and logic programming work well together.\n    \\pause\n        \\item Many Prolog implementations have built in constraint solvers.\n    \\pause\n        \\item Basic idea:\n            \\begin{itemize}\n                \\item add constraints to the constraint store\n    \\pause\n                \\item constraint solver works behind the scenes to propagate constraints\n    \\pause\n                \\item use Prolog's backtracking search mechanism to generate solutions\n    \\pause\n            \\end{itemize}\n        \\item Advantages over pure logic programming:\n            \\begin{itemize}\n                \\item ``constrain-and-generate'' rather than ``generate-and-test''\n    \\pause\n                \\item constraint solver can greatly reduce the search space required compared to Prolog's built-in depth-first-search\n    \\pause\n                \\item much more powerful than relying on just unification and backtracking\n            \\end{itemize}\n    \\end{itemize}\n\\end{frame}\n\n\\section{Finite domain constraints}\n\n\\begin{frame}[fragile]\n    \\frametitle{Finite domain constraints}\n\\begin{itemize}\n    \\item One of the most widely used varieties of constraint solver.\n        \\pause\n    \\item Variables range over a finite domain of integers.\n        \\pause\n    \\item Simple equality and inequality constraints: $=$, $\\neq$, $<$, $>$, $\\leq$, $\\geq$\n        \\pause\n    \\item Also simple arithmetic expressions: $+$, $-$, $\\times$, \\texttt{abs}\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}[fragile]\n    \\frametitle{Arc consistency}\nSolver uses an \\emph{arc consistency algorithm}, e.g.\\ AC-3\n\\begin{itemize}\n    \\item Constraint store holds the set of constraints to be checked.\n        \\pause\n    \\item For each constraint, the domains of the variables involved are checked to\n        ensure they are consistent with the contraint.\n        \\pause\n    \\item Any values in the domains that break consistency are removed.\n        \\pause\n    \\item If the domain of a variable changes then all other constraints involving that variable are\n        rechecked.\n\\end{itemize}\n\\pause\n\\begin{example}\n\\begin{displaymath}\n    \\begin{array}{c}\n    x \\in \\{1, 2, 3\\} ~~\\land~~ y \\in \\{1, 2, 3\\} \\\\\n    \\pause\n    \\textrm{add constraint~} x < y \\\\\n    \\pause\n    \\Rightarrow ~~~ x \\in \\{1, 2\\} ~~\\land~~ y \\in \\{2, 3\\} \\\\\n    \\pause\n    \\textrm{add constraint~} y = 2 \\\\\n    \\pause\n        \\Rightarrow ~~~ x \\in \\{1\\} ~~\\land~~ y \\in \\{2\\}\n    \\end{array}\n\\end{displaymath}\n\\end{example}\n\\end{frame}\n\n\\begin{frame}[fragile]\n    \\frametitle{Example: $n$ queens in SWI-Prolog}\n\n\\begin{columns}[t]\n\\column[c]{0.35\\paperwidth}\n\\begin{minted}[fontsize=\\small]{prolog}\nn_queens(N, Qs) :-\n        length(Qs, N),\n        Qs ins 1..N,\n        safe_queens(Qs).\n\nsafe_queens([]).\nsafe_queens([Q|Qs]) :-\n    safe_queen(Qs, Q, 1),\n    safe_queens(Qs).\n\nsafe_queen([], _, _).\nsafe_queen([Q|Qs], Q0, D0) :-\n        Q0 #\\= Q,\n        abs(Q0 - Q) #\\= D0,\n        D1 #= D0 + 1,\n        safe_queen(Qs, Q0, D1).\n\\end{minted}\n\\column[c]{0.5\\paperwidth}\n\\includegraphics[width=0.45\\paperwidth]{8queens.png}\n\\end{columns}\n\\end{frame}\n\n\\section{Constraint programming in Haskell}\n\n\\subsection{Basic equality and inequality}\n\n\\begin{frame}[fragile]\n    \\frametitle{Constraint programming in Haskell}\nHow can we do something similar in Haskell?\\pause{}\n\\textbf{Use a monad!}\n\\end{frame}\n\n\\begin{frame}[fragile]\n    \\frametitle{Example: $n$ queens in SWI-Prolog and Haskell}\n\n\\begin{columns}[t]\n\\column[t]{0.33\\paperwidth}\n\\begin{minted}[fontsize=\\footnotesize]{prolog}\nn_queens(N, Qs) :-\n        length(Qs, N),\n        Qs ins 1..N,\n        safe_queens(Qs).\n\nsafe_queens([]).\nsafe_queens([Q|Qs]) :-\n    safe_queen(Qs, Q, 1),\n    safe_queens(Qs).\n\nsafe_queen([], _, _).\nsafe_queen([Q|Qs], Q0, D0) :-\n        Q0 #\\= Q,\n        abs(Q0 - Q) #\\= D0,\n        D1 #= D0 + 1,\n        safe_queen(Qs, Q0, D1).\n\\end{minted}\n\\pause\n\\column[t]{0.59\\paperwidth}\n\\begin{minted}[fontsize=\\footnotesize]{haskell}\nnQueens :: Int -> FD [FDExpr]\nnQueens n = do\n    qs <- news n (1, n)\n    safeQueens qs\n    return qs\n\nsafeQueens :: [FDExpr] -> FDConstraint\nsafeQueens [] = return ()\nsafeQueens (q : qs) = do\n    safeQueen qs q 1\n    safeQueens qs\n\nsafeQueen :: [FDExpr] -> FDExpr -> FDExpr -> FDConstraint\nsafeQueen [] _ _ = return ()\nsafeQueen (q : qs) q0 d0 = do\n   q0 #\\= q \n   abs (q0 - q) #\\= d0\n   safeQueen qs q0 (d0 + 1)\n\\end{minted}\n\\end{columns}\n\\end{frame}\n\\begin{frame}[fragile]\n\\begin{itemize}\n    \\item List monad provides backtracking / search / multiple solutions.\n        \\pause\n    \\item Wrap it in a state monad transformer to keep track of the constraint store.\n        \\pause\n\\end{itemize}\n\\begin{code}\ntype FD a = StateT FDState [] a\n\\end{code}\n\\pause\n\\begin{code}\ntype FDConstraint = FD ()\n\\end{code}\n\\pause\n\\begin{code}\n-- Run the monad to obtain a list of solutions.\nrunFD :: FD a -> [a]\nrunFD fd = evalStateT fd initState\n\\end{code}\n\\end{frame}\n\n\\begin{frame}[fragile]\n\\begin{code}\nnewtype FDVar = FDVar { _unwrapFDVar :: Int } deriving (Ord, Eq)\n\ntype VarSupply = FDVar\n\ndata Domain\n    = Set IntSet\n    | Range Int Int\n\ndata VarInfo = VarInfo { _delayedConstraints :: !FDConstraint\n                       , _domain :: !Domain }\n\ntype VarMap = Map FDVar VarInfo\n\ndata FDState = FDState { _varSupply :: !VarSupply, _varMap :: !VarMap }\n\ninitState :: FDState\ninitState = FDState { _varSupply = FDVar 0, _varMap = Map.empty }\n\\end{code}\n\\end{frame}\n\n\\begin{frame}[fragile]\n\\begin{code}\nnewVar :: ToDomain a => a -> FD FDVar\nnewVar d = do\n    v <- use varSupply\n    varSupply . unwrapFDVar += 1\n    let vi = initVarInfo & domain .~ toDomain d\n    varMap . at v ?= vi\n    return v\n\nnewVars :: ToDomain a => Int -> a -> FD [FDVar]\nnewVars n d = replicateM n (newVar d)\n\\end{code}\n\\end{frame}\n\n\\begin{frame}[fragile]\n\\begin{code}\n-- Look up the current domain of a variable.\nlookup :: FDVar -> FD Domain\nlookup x =\n    use $ varMap . ix x . domain\n\n-- Update the domain of a variable and fire all delayed constraints\n-- associated with that variable.\nupdate :: FDVar -> Domain -> FDConstraint\nupdate x i = do\n    vi <- use $ varMap . ix x\n    varMap . ix x . domain .= i\n    vi ^. delayedConstraints\n\n-- Add a new constraint for a variable to the constraint store.\naddConstraint :: FDVar -> FDConstraint -> FDConstraint\naddConstraint x constraint =\n    varMap . ix x . delayedConstraints %= (>> constraint)\n\\end{code}\n\\end{frame}\n\n\\begin{frame}[fragile]\n\\begin{code}\n-- Useful helper function for adding binary constraints between FDVars.\ntype BinaryConstraint = FDVar -> FDVar -> FDConstraint\naddBinaryConstraint :: BinaryConstraint -> BinaryConstraint\naddBinaryConstraint f x y = do\n    let constraint  = f x y\n    constraint\n    addConstraint x constraint\n    addConstraint y constraint\n\n-- Constrain two variables to have the same value.\nsame :: FDVar -> FDVar -> FDConstraint\nsame = addBinaryConstraint $ \\x y -> do\n    xv <- lookup x\n    yv <- lookup y\n    let i = xv `intersection` yv\n    guard $ not $ Domain.null i\n    when (i /= xv) $ update x i\n    when (i /= yv) $ update y i\n\\end{code}\n\\end{frame}\n\n\\begin{frame}[fragile]\n\\begin{code}\n-- Constrain two variables to have different values.\ndifferent :: FDVar -> FDVar -> FDConstraint\ndifferent = addBinaryConstraint $ \\x y -> do\n    xv <- lookup x\n    yv <- lookup y\n    guard $ not (isSingleton xv) || not (isSingleton yv) || xv /= yv\n    when (isSingleton xv && xv `isSubsetOf` yv) $\n        update y (yv `difference` xv)\n    when (isSingleton yv && yv `isSubsetOf` xv) $\n        update x (xv `difference` yv)\n\n-- Constrain a list of variables to all have different values.\nvarsAllDifferent :: [FDVar] -> FDConstraint\nvarsAllDifferent (x:xs) = do\n    mapM_ (different x) xs\n    varsAllDifferent xs\nvarsAllDifferent _ = return ()\n\\end{code}\n\\end{frame}\n\n\\begin{frame}[fragile]\n    \\frametitle{Labelling}\n\\emph{Labelling} is used to obtain valid solutions for a set of variables.\nThe embedded list monad allows us to search for and return all possible solutions.\n\\begin{code}\n-- Label variables using a depth-first left-to-right search.\nvarsLabelling :: [FDVar] -> FD [Int]\nvarsLabelling = mapM label where\n    label var = do\n        vals <- lookup var\n        val <- lift $ elems vals\n        var `hasValue` val\n        return val\n\\end{code}\n\\end{frame}\n\n\\begin{frame}[fragile]\nWe now have enough to solve Sudoku!\n\\begin{code}\nsudoku :: [Int] -> [[Int]]\nsudoku puzzle = runFD $ do\n    vars <- newVars 81 (1, 9)\n    zipWithM_ (\\x n -> when (n > 0) (x `hasValue` n)) vars puzzle\n    mapM_ varsAllDifferent (rows vars)\n    mapM_ varsAllDifferent (columns vars)\n    mapM_ varsAllDifferent (boxes vars)\n    varsLabelling vars\n\nrows, columns, boxes :: [a] -> [[a]]\nrows = chunk 9\ncolumns = transpose . rows\nboxes = concat . map (map concat . transpose) . chunk 3 . chunk 3 . chunk 3\n\nchunk :: Int -> [a] -> [[a]]\nchunk _ [] = []\nchunk n xs = ys : chunk n zs where\n    (ys, zs) = splitAt n xs\n\\end{code}\n\\end{frame}\n\n\\subsection{Arithmetic expressions}\n\n\\begin{frame}[fragile]\n    \\frametitle{Arithemtic expressions}\n    \\begin{itemize}\n        \\item So far we have seen how to declare contraint variables and define simple equality constraints\n            between them.\n            \\pause\n        \\item We also want to be able to write constraints involving simple arithmetic expressions.\n    \\end{itemize}\n\\end{frame}\n\\begin{frame}[fragile]\n    \\begin{code}\ndata FDExpr\n    = Int !Int\n    | Var !FDVar\n    | Plus !FDExpr !FDExpr\n    | Minus !FDExpr !FDExpr\n    | Times !FDExpr !FDExpr\n    | Negate !FDExpr\n    | Abs !FDExpr\n    | Signum !FDExpr\n    \\end{code}\n\\pause\n    \\begin{code}\n\n-- Num instance allows us to use the usual arithmetic operators\n-- and integer literals\ninstance Num FDExpr where\n    (+) = Plus\n    (-) = Minus\n    (*) = Times\n    negate = Negate\n    abs = Abs\n    signum = Signum\n    fromInteger = Int . fromInteger\n    \\end{code}\n\\end{frame}\n\n\\begin{frame}[fragile]\n    \\begin{code}\n-- Define new variables and return as expressions\nnew :: ToDomain a => a -> FD FDExpr\nnew d = newVar d <&> Var\n\nnews :: ToDomain a => Int -> a -> FD [FDExpr]\nnews n d = replicateM n $ new d\n    \\end{code}\n    \\pause\n    \\begin{code}\n\n-- Interpret an FDExpr and return an FDVar representing it\ninterpret :: FDExpr -> FD FDVar\ninterpret (Var v) = return v\ninterpret (Int i) = newVar [i]\ninterpret (Plus e0 e1) = interpretBinary (+) e0 e1\ninterpret (Minus e0 e1) = interpretBinary (-) e0 e1\ninterpret (Times e0 e1) = interpretBinary (*) e0 e1\ninterpret (Negate e) = interpretUnary negate e\ninterpret (Abs e) = interpretUnary abs e\ninterpret (Signum e) = interpretUnary signum e\n    \\end{code}\n\\end{frame}\n\n\\begin{frame}[fragile]\n    \\begin{minted}[fontsize=\\footnotesize]{haskell}\ninterpretBinary :: (Int -> Int -> Int) -> FDExpr -> FDExpr -> FD FDVar\ninterpretBinary op e0 e1 = do\n    v0 <- interpret e0\n    v1 <- interpret e1\n    d0 <- lookup v0\n    d1 <- lookup v1\n    v <- newVar [n0 `op` n1 | n0 <- elems d0, n1 <- elems d1]\n    let pc  = constrainBinary (\\n n0 n1 -> n == n0 `op` n1) v v0 v1\n        nc0 = constrainBinary (\\n0 n n1 -> n == n0 `op` n1) v0 v v1\n        nc1 = constrainBinary (\\n1 n n0 -> n == n0 `op` n1) v1 v v0\n    addConstraint v0 $ pc >> nc1\n    addConstraint v1 $ pc >> nc0\n    addConstraint v  $ nc0 >> nc1\n    return v\n\nconstrainBinary :: (Int -> Int -> Int -> Bool) -> FDVar -> FDVar -> FDVar -> FDConstraint\nconstrainBinary pred v v0 v1 = do\n    d <- lookup v\n    d0 <- lookup v0\n    d1 <- lookup v1\n    let d' = toDomain [n | n <- elems d, n0 <- elems d0, n1 <- elems d1, pred n n0 n1]\n    guard $ not $ Domain.null d'\n    when (d' /= d) $ update v d'\n    \\end{minted}\n\\end{frame}\n\n\\begin{frame}[fragile]\n    \\begin{code}\ninfix 4 #\\=\n(#\\=) :: FDExpr -> FDExpr -> FDConstraint\na #\\= b = do\n    v0 <- interpret a\n    v1 <- interpret b\n    v0 `different` v1\n\nallDifferent :: [FDExpr] -> FDConstraint\nallDifferent = varsAllDifferent <=< mapM interpret\n\nlabelling :: [FDExpr] -> FD [Int]\nlabelling = varsLabelling <=< mapM interpret\n    \\end{code}\n\\end{frame}\n\n\\begin{frame}[fragile]\n    \\frametitle{Example: $n$ queens in SWI-Prolog and Haskell}\n\n\\begin{columns}[t]\n\\column[t]{0.33\\paperwidth}\n\\begin{minted}[fontsize=\\footnotesize]{prolog}\nn_queens(N, Qs) :-\n        length(Qs, N),\n        Qs ins 1..N,\n        safe_queens(Qs).\n\nsafe_queens([]).\nsafe_queens([Q|Qs]) :-\n    safe_queen(Qs, Q, 1),\n    safe_queens(Qs).\n\nsafe_queen([], _, _).\nsafe_queen([Q|Qs], Q0, D0) :-\n        Q0 #\\= Q,\n        abs(Q0 - Q) #\\= D0,\n        D1 #= D0 + 1,\n        safe_queen(Qs, Q0, D1).\n\\end{minted}\n\\pause\n\\column[t]{0.59\\paperwidth}\n\\begin{minted}[fontsize=\\footnotesize]{haskell}\nnQueens :: Int -> FD [FDExpr]\nnQueens n = do\n    qs <- news n (1, n)\n    safeQueens qs\n    return qs\n\nsafeQueens :: [FDExpr] -> FDConstraint\nsafeQueens [] = return ()\nsafeQueens (q : qs) = do\n    safeQueen qs q 1\n    safeQueens qs\n\nsafeQueen :: [FDExpr] -> FDExpr -> FDExpr -> FDConstraint\nsafeQueen [] _ _ = return ()\nsafeQueen (q : qs) q0 d0 = do\n   q0 #\\= q \n   abs (q0 - q) #\\= d0\n   safeQueen qs q0 (d0 + 1)\n\\end{minted}\n\\end{columns}\n\\end{frame}\n\\begin{frame}[fragile]\n    \\begin{verbatim}\n        SEND\n     +  MORE\n     -------\n       MONEY\n    \\end{verbatim}\n\n    \\begin{code}\nsendMoreMoney = runFD $ do\n    vars@[s, e, n, d, m, o, r, y] <- news 8 (0, 9)\n    s #\\= 0\n    m #\\= 0\n    allDifferent vars\n\n    1000 * s + 100 * e + 10 * n + d\n       + 1000 * m + 100 * o + 10 * r + e\n       #== 10000 * m + 1000 * o + 100 * n + 10 * e + y\n\n    labelling vars\n    \\end{code}\n\\end{frame}\n\n\\section{Conclusion}\n\\begin{frame}\n    \\frametitle{Consclusion}\n    \\begin{itemize}\n        \\item Haskell can do constraint logic programming -- all you need is monads.\n            \\pause\n        \\item Advantages of Haskell\n            \\begin{itemize}\n                    \\pause\n                \\item Awesomeness of Haskell.\n                    \\pause\n                \\item Type safety.\n                    \\pause\n                \\item Leverage libraries, such as monad combinators, in a very natural way.\n                    \\pause\n            \\end{itemize}\n        \\item Disadvantages\n            \\begin{itemize}\n                    \\pause\n                \\item Not full Prolog, e.g. missing unification between terms, multi-moded predicates.\n                    \\pause\n                \\item Some Prolog implementations have very powerful and efficient built-in solvers, which Haskell can't use.\n            \\end{itemize}\n    \\end{itemize}\n    \\pause\n    Github repository: \\url{https://github.com/dmoverton/finite-domain}\n\\end{frame}\n\\end{document}\n", "meta": {"hexsha": "a11e94e2634738803dbfb958a95fd148cbfd5a00", "size": 16900, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "mhug-talk/constraints.tex", "max_stars_repo_name": "dmoverton/finite-domain", "max_stars_repo_head_hexsha": "ae4afe755c1c1880d1283b9fdae90c1dc4a03f10", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2016-08-07T21:57:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-22T21:37:31.000Z", "max_issues_repo_path": "mhug-talk/constraints.tex", "max_issues_repo_name": "dmoverton/finite-domain", "max_issues_repo_head_hexsha": "ae4afe755c1c1880d1283b9fdae90c1dc4a03f10", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2016-12-07T01:46:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-02T07:21:00.000Z", "max_forks_repo_path": "mhug-talk/constraints.tex", "max_forks_repo_name": "dmoverton/finite-domain", "max_forks_repo_head_hexsha": "ae4afe755c1c1880d1283b9fdae90c1dc4a03f10", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2015-10-29T11:16:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-03T21:59:24.000Z", "avg_line_length": 27.9801324503, "max_line_length": 162, "alphanum_fraction": 0.6447337278, "num_tokens": 5160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.34734535046232556}}
{"text": "\\documentclass[12pt]{article}\n\\input{physics1}\n\\begin{document}\n\n\\section*{NYU Physics I---Problem Set 9}\n\nDue Thursday 2018 November 08 at the beginning of lecture.\n\n\\paragraph{\\problemname~\\theproblem}\\refstepcounter{problem}%\nWhat is the pressure gradient (units of $\\Pa\\,\\m^{-1}$) in air at sea level at STP?\nWhat is the pressure gradient in water?\nWhat is the pressure gradient in liquid mercury?\nWhat would be the pressure gradient in rock, if we treated the rock like a fluid?\n\nCompute the ratio of the pressure gradient in mecury to the pressure gradient\nin water. How does this ratio compare to the ratio of $33\\,\\ft$ to $760\\,\\mm$?\nWhy did I ask that?\n\n\\paragraph{\\problemname~\\theproblem}\\refstepcounter{problem}%\nIn a bungy jump, the bungy cord has a rest (unstretched) length of\n$\\ell_0 = 5\\,\\m$, and has a spring constant $k$ such that it stretches\nby 1~m for every 400~N of force.\n\n\\textsl{(a)} If an adult of mass $M=80\\,\\kg$ jumps off of a very tall\nbridge at time $t=0$ with this bungy cord attached between her or\nhimself and also the bridge, to what maximum distance $h_\\mathrm{max}$\nbelow the bridge will he or she fall?  (You might use energy\nconservation). Give your answer in terms of the symbols $M$, $\\ell_0$,\n$k$, and $g$ as well as numerically. That is, we want the numerical\nand symbolic answers both.\n\n\\textsl{(b)} What is the maximum tension $T$ in the bungy? Again, give\nboth answers.\n\n\\textsl{(c)} If you stiffen the cord (increase $k$), but keep\nthe natural length and adult's mass fixed, do you increase or decrease the maximum\ntension?\n\n\\textsl{(d)} What acceleration $a$ does the adult feel at the maximum\nextension of the bungy (that is, at the bottom)? Again, give your\nanswer both symbolically (in terms of the same symbols) and numerically.\n\n\\paragraph{\\problemname~\\theproblem:}\\refstepcounter{problem}%\nHere we consider the construction and tuning of a standard grand piano.\nEach string of the piano has a mass $M$, a length $L$, and a tension $T$.\n\n\\textsl{(a)} Use dimensional analysis to estimate the natural angular\nfrequency $\\omega$ of a piano string with these properties. That is,\nwhat combination has units of frequency?\n\n\\textsl{(b)} Look up the natural frequency of a guitar or piano string\nin its lowest harmonic. You might have to look up ``standing wave'' or\nsomething like that, and you might also have to look up ``transverse\nwave speed'' in a string. A string fixed at both ends (like a piano\nstring) is different from an open organ pipe! How does what you find\nin your research compare to what you found in part \\textsl{(a)}?\n\n\\textsl{(c)} Look inside a piano at or near middle C. Roughly what are\nthe diameters of the strings? And what are the lengths of the strings?\nUse these quantities and the density of steel to estimate the masses\nof the strings.\n\n\\textsl{(d)} Given what you know about the piano---the number of keys,\nthe number of strings per key (which isn't one for most keys), and the\nrange of frequencies and string lengths, estimate \\emph{very roughly}\nthe total force compressing a piano frame, in Newtons. That is,\nestimate the total of all the tension forces. Do you understand why\npiano frames and harps are so heavy?\n\n\\paragraph{Problem~\\theproblem:}\\refstepcounter{problem}%\nEverything submerged in the Earth's atmosphere is subject to a buoyant\nforce from the air.  In the following, use a sensible (reasonably\naccurate) measure of the density of air at STP.\n\n\\textsl{(a)} When you measure your weight on a standard bathroom\nscale, you are measuring the \\emph{normal force} between yourself and\nthe floor.  This normal force opposes the \\emph{combination} of\ngravity and buoyancy.  What is the correction to your weight coming\nfrom buoyancy, roughly?  Express it as a \\emph{fraction} of the\ngravitational force.  Is this correction positive or negative---that\nis, does it increase or decrease the weight measured by the scale?\n\n\\textsl{(b)} Look up the ``volume'' of the Goodyear blimp model GZ-22.\nImagine that it is floating in an air atmosphere at STP, and that the\ngas inside the blimp is \\emph{also} at STP.  What is the approximate\nbuoyant force on the blimp if it is filled with helium?  What about if\nit were filled with hydrogen (molecular hydrogen)?  Compare these\nnumbers with the gross weight and capacity of the blimp.\n\n\\textsl{(c)} Will the buoyant force increase, decrease, or stay the\nsame as you decrease the temperature?\nAssume that the blimp contents are always at the same pressure as the\nexterior air (and therefore the volume of the blimp must change).\n\n\\paragraph{Extra Problem (will not be graded for credit):}%\nA child of mass $m$ sits exactly on top of a hemispherical mound of\nfrictionless ice of radius $R$.  If the child is displaced a tiny (ie,\nsmall relative to $R$) horizontal distance $x$ from the top of the\nmound of ice, what is the $x$-component $F_x$ of the net force on the\nchild?  Write down the differential equation relating the $x(t)$ to\nits second derivative (with respect to time).  Use the small-angle\napproximation to get rid of trigonometric functions! What functions\n$x(t)$ solve your equation?  Try to be as general as possible.\n\\emph{Hint: Try exponentials!}.\n\n\\paragraph{Extra Problem (will not be graded for credit):}%\nLook up the Youngs modulus for steel, and estimate the spring\npotential energy stored in the middle C string, using what you figured\nout in the piano problem. Now estimate the total mechanical energy\nstored in the tuned piano!\n\n\\end{document}\n", "meta": {"hexsha": "e49981cca0e6dd6ae09d802d090730d26fad6986", "size": 5496, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/physics1_ps09.tex", "max_stars_repo_name": "davidwhogg/Physics1", "max_stars_repo_head_hexsha": "6723ce2a5088f17b13d3cd6b64c24f67b70e3bda", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-11-13T03:48:56.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-13T03:48:56.000Z", "max_issues_repo_path": "tex/physics1_ps09.tex", "max_issues_repo_name": "davidwhogg/Physics1", "max_issues_repo_head_hexsha": "6723ce2a5088f17b13d3cd6b64c24f67b70e3bda", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2016-10-07T19:48:57.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-29T22:47:25.000Z", "max_forks_repo_path": "tex/physics1_ps09.tex", "max_forks_repo_name": "davidwhogg/Physics1", "max_forks_repo_head_hexsha": "6723ce2a5088f17b13d3cd6b64c24f67b70e3bda", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.6371681416, "max_line_length": 83, "alphanum_fraction": 0.7641921397, "num_tokens": 1422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.34734535046232545}}
{"text": "\\documentclass[10pt,twocolumn]{article}\n\\usepackage{cite}\n\\usepackage{amsmath,amssymb,amsfonts,amsthm}\n\\usepackage{multicol}\n\\setlength{\\columnsep}{0.75cm}\n\\usepackage{caption}\n\\usepackage{graphicx}\n\\usepackage{csquotes}\n\\usepackage{todonotes}\n\n\\def\\BibTeX{{\\rm B\\kern-.05em{\\sc i\\kern-.025em b}\\kern-.08em\n    T\\kern-.1667em\\lower.7ex\\hbox{E}\\kern-.125emX}}\n\\usepackage{hyperref}\n\\usepackage[margin=1.75cm]{geometry}\n\\usepackage[hpos=0.72\\paperwidth,vpos=0.97\\paperheight,angle=0,scale=0.8]{draftwatermark}\n\\SetWatermarkText{Preprint}\n\\SetWatermarkLightness{0.5}\n\\SetWatermarkText{Preprint of preliminary work}\n\n\\newtheorem{theorem}{Theorem}[section]\n\\newtheorem{corollary}{Corollary}[theorem]\n\\newtheorem{lemma}[theorem]{Lemma}\n\n\n\\title{Optimally Reliable \\& Cheap Payment Flows on the Lightning Network}\n\n\n\\author{Rene Pickhardt \\& Stefan Richter\\thanks{The authors have contributed to this work in equal measure. The order merely reflects the fact that this line of research was initiated by Rene Pickhardt.}}\n\\begin{document} \n\\maketitle\n\n\n\n\n\n\n \n\\begin{abstract}\n  Today, payment paths in Bitcoin's Lightning Network are found by searching for shortest paths on the fee graph.\n  We enhance this approach in two\n  dimensions. Firstly, we take into account the probability of a payment\n  actually being possible due to the unknown balance distributions in the\n  channels. Secondly, we use minimum cost flows as a proper generalization of\n  shortest paths to multi-part payments (MPP).\n\n  In particular we show that under plausible assumptions about the balance\n  distributions we can find the most likely MPP for any given set of senders, recipients and amounts by solving for a (generalized) integer\n  minimum cost flow with a separable and convex cost function. Polynomial time\n  exact algorithms as well as approximations are known for this optimization\n  problem.\n  \n\n  We present a round-based algorithm of min-cost flow computations for\n  delivering large payment amounts over the Lightning Network. This algorithm\n  works by updating the probability distributions with the information gained\n  from both successful and unsuccessful paths on prior rounds. In all our\n  experiments a single digit number of rounds sufficed to deliver payments \n  of sizes that were close to the total local balance of the sender.\n  Early experiments indicate that our approach increases the size of payments that can be reliably delivered by several orders of magnitude compared to the current state of the art.\n\n  We observe that finding the cheapest multi-part payments is an NP-hard problem\n  considering the current fee structure and propose dropping the base fee to make\n  it a linear min-cost flow problem. Finally, we discuss possibilities for\n  maximizing the probability while at the same time minimizing the fees of a\n  flow. While this turns out to be a hard problem in general as well --- even in\n  the single path case --- it appears to be surprisingly tractable in practice.\n  \n\\end{abstract}\n\n%==========================================================================\n\\section{Introduction}\nThe Lightning Network is a payment channel network using source-based onion routing to deliver payments from senders to recipients.\nA necessary condition for a single onion package to be delivered successfully is that the onion follows a path with sufficient liquidity.\nIn this context sufficient liquidity does not just mean that the publicly known channel capacities of the channels on the path between sender and recipient are larger than the payment amount. Rather, every node along the path has to own enough of the channel capacity as their local balance to be able to forward the amount to the next hop.\nAs broadcasting the balance values would hinder the scalability of the Lightning Network they are generally kept private and thus unknown to other nodes.\nCurrently the sender node mitigates this uncertainty by entering a trial-and-error loop for delivering payments.\nHowever, past experiments have demonstrated that payments are often failing, in particular when the amounts to be delivered are increasing\\cite{DBLP:journals/corr/abs-1911-09432,DBLP:journals/corr/abs-2006-14358,lange2021impact, pickhardt2021security}.\n\nCurrent implementations largely find candidate paths for the trial-and-error-loop by solving\nshortest path problems or generalizations like $k$-shortest paths on the\nweighted channel graph, where the weights correspond to the routing fees charged by nodes forwarding a payment along a channel.\\footnote{We also observe a combination of the fee function with features like a penalty for longer CLTV values, prior experiences of using the channel and a bias against smaller channels.}\nThat approach tries to find the cheapest payment path for the sender but does not systematically factor in success probabilities. As a consequence, the payment loop might try a large number of cheapest but unreliable paths before timing out instead of using slightly more expensive but vastly more reliable paths. It also does not produce an optimal split of the payment into multiple paths.\n\nSoftware implementations of the Lightning Network protocol have mainly focused on three strategies for handling the uncertainty of sending a payment.\n\\begin{enumerate}\n\\item Incentivizing the path finding algorithm to favor larger channels.\\footnote{\\url{https://lists.ozlabs.org/pipermail/c-lightning/2021-May/000203.html}}%clightning dev\n\\item Ad-hoc splitting of large payment amounts into smaller ones after failed attempts using a technique called multi-part payments (MPP).\n\\item Using provenance scores of nodes and channels and other data collected during operation of a node to estimate which nodes and channels might be reliable.\n\\end{enumerate}\n\nIn this work we are developing a general technique that is achieving the effects of these rather ad-hoc techniques in a systematic fashion.\nThis text largely builds upon and extends prior research which pointed out that\nthe uncertainty of channel balance values can be mathematically modeled to\narrive at a probabilistic path finding scheme\\cite{pickhardt2021security}. While\nthis earlier work demonstrated a significant reduction in failed attempts while\ndelivering payments it still mostly kept the perspective of a single path finding\nproblem.\n\nIt has long been a folklore view that delivering payments on the Lightning Network can be modeled as a network flow problem.\nIn what follows we show that the discovery of the most likely multi-path payment is equivalent to solving a (generalized) min-cost flow problem in which the negative logarithms of channel success probabilities are considered as the cost of using a channel.\nThe channel success probabilities are priors that have to be estimated, through sampling for example.\nUnder the assumption of an independent uniform balance distribution on each channel as the prior, finding the most probable multi-part payment for a given amount from a sender to a recipient can be usefully modeled as solving an integer min-cost flow problem with a separable convex cost function.\nWhile in general min-cost flow problems are complex\noptimization problems, the above mentioned subclass is known to have polynomial\ntime solutions with a runtime complexity of $O(m \\cdot \\log(U) \\cdot S(n,m))$\nwhere $n$ is the number of nodes, $m$ is the number of edges on the network, $U$\nis the amount to be delivered, and $S(n,m)$ is the time it takes to obtain a\nsolution to the single source shortest path problem\\cite{Minoux1986,ahuja1993network}. This\nis typically done using Dijkstra's Algorithm in time $O(m+n) \\cdot \\log(n)$, so\nthat we arrive at a total runtime of $O(\\log(U)\\cdot(m^2+mn)\\cdot\\log(n))$.\n\nIf the balance values were known, the decision if a payment between two nodes can be conducted could be arrived at by finding a max-flow / min-cut and comparing it to the amount that is to be delivered.\nGiven the uncertainty of channel balances, the decision problem is much harder to solve and still involves a trial-and-error loop.\nWe introduce a practical round-based algorithm that can either quickly deliver the payment or decide with a high probability that the min-cut is lower than the payment amount that is supposed to be delivered between sender and receiver.\nIt starts by creating the most likely MPP split as the solution of the min-cost flow problem and sending out the partial payments.\nThe algorithm reduces its uncertainty of the balance values by learning from the failures and successes.\nThis is done by updating the prior probabilities after the failing onions have returned.\nFinally it creates another candidate MPP for the residual amount by solving a min-cost flow on the updated graph.\n\n\\section{Payments as Integer Flows}\n\\label{flows}\nLet $G = (V,E)$ be a directed graph and $u: E \\longrightarrow \\mathbb{N}$ a function assigning capacity values to all edges in the graph.\nFor every node $v\\in V$ let $b_v \\in \\mathbb{Z}$ denote its \\emph{excess, supply or demand}.  Typically $b_v$ will be $0$ except for the source node $s$ (with supply $b_v>0$) and the destination $d$ (with demand $b_v<0$). We call a function $f: E \\longrightarrow \\mathbb{N}_{0}$ a \\emph{flow} if the following conditions hold:\n\\begin{enumerate}\n\\item \\textbf{capacity constraint}: For every edge $e \\in E$ we have: $$0 \\leq f(e) =: f_{e} \\leq u_{e} := u(e).$$\n\\item \\textbf{flow conservation}: For every node $i\\in V$ we have: $$\\sum_{(i,j)\\in E} f_{ij} - \\sum_{(j,i)\\in E} f_{ji} = b_i.$$\n\\end{enumerate}\n\n\\subsection{Flows on a Known Balance Graph}\nAssuming the balance values of every payment channel of the Lightning Network were publicly known, one could create a flow network called \\emph{balance graph} as follows:\nFor any given payment channel between two nodes $i$ and $j$ with capacity $u$ we know that the balance $u_j$ of node $j$ plus the balance $u_i$ of node $i$ must be equal to the capacity $u$.\nOn the balance graph we add two directed edges for the payment channel between the nodes $i,j$.\nFirst we add the edge $(i,j)$ with a capacity of $u(i,j) = u_i$ and then we add another edge in the opposing direction $j,i$ with a capacity of $u(j,i)=u_j$.\\footnote{In reality, channel reserves would need to be accounted for by lowering the capacities to the spendable balances.}\n\nObserve that in this balance graph, a set of payment paths from $s$ to $t$ determines a flow simply by summing up the amount sent through any edge.\\footnote{We abstract from the fact that the amount sent through a payment path diminishes along the path by the fees collected; we assume the total fees are included until the end. See Section~\\ref{generalized} for a discussion of the impact of this relaxation.}\nIn fact, the converse is also true: It is easy to see that any flow can be decomposed into paths from $s$ to $t$ and cycles in linear time~\\cite[p.~79ff]{ahuja1993network}.\nSince cycles do not change supply or demand at any node, we can safely ignore them.\nIn this way, we can represent any MPP split as a flow and vice versa.\nWe emphasize that the paths of the decomposed flow that lead to the MPP split do not need to be disjoint.\n\nGiven the balance values, we could decide the maximum possible amount that can be sent for any given node pair $s,t \\in V$ by computing the minimal $s$--$t$-cut.\nUsing, say, the Ford-Fulkerson algorithm\\cite{ford_fulkerson_1956} one could compute a max-flow and disect it into a series of paths.\nThese paths could then be used to construct several onions for a multi-part payment.\n\nIn a preliminary test we use two different prior distributions to generate two static balance graphs and check on each how often the min-cut between arbitrarily chosen pairs of sender and receiver is actually determined by the minimum of the local outbound capacity of the sender and the local inbound capacity of the recipient.\nIn Figure~\\ref{fig:mincut} we can see that for both of these distributions --- which have been observed on the entire Lightning Network and an active core subset, respectively --- in only about $5\\%$ of the payment pairs is the max-flow smaller than the maximum amount locally sendable by the payer and the maximum amount locally receivable by the target node.\n\\begin{figure}[htpb]\n  \\center\n  \\includegraphics[width=0.45\\textwidth]{img/maxFlowFraction.png}\n  \\caption{Showing the percentage of payment pairs where the maximal payable amount is actually lower than the upper bound given by the local balance known to both sender and recipient.}\n  \\label{fig:mincut}\n\\end{figure}\n\nThe fact that with publicly known balance values in $19$ out of $20$ payment pairs the amount that can be delivered is as high as the local limits of the payment pair is in stark contradiction to the currently observed and reported \\cite{DBLP:journals/corr/abs-1911-09432,DBLP:journals/corr/abs-2006-14358,lange2021impact, pickhardt2021security} success rates. In fact, these are declining heavily with amounts larger than $100,000$ satoshi (1 BTC = 100,000,000 sat) for which the delivery should be almost always possible.\nWe conjecture that this is due to the fact that in reality, the balance values are not publicly known.\nThis forces us to take the total channel capacities $u$ as capacities on our flow network in both directions.\nNote that finding a max-flow on this network is not sufficient for deciding if a payment can be made.\nHowever, we can generalize the flow model to the case of uncertain balance values and will return to this question in Section~\\ref{rounds}.\n\n\\subsection{Uncertainty Networks}\nEarlier research~\\cite{pickhardt2021security} has introduced a mathematical framework for handling uncertain balance values in payment channels with the goal of making path finding decisions that maximize the success probability of payment paths.\nWe recall that --- given a prior belief about the balance uncertainty via a probability distribution $P_e$ and a random variable $X_e$ ---  the channel success probability for a payment of size $f_e$ for a channel $e$ is expressed as $P_e(X_e\\geq f_e)$.\nWhereas in~\\cite{pickhardt2021security} the goal was maximizing the path success probabilities, here we aim to maximize the success probability for the entire flow. Assuming the channel balances to be independently distributed, this combined success probability is simply the product of all channel success probabilities:\n\n\\[\nP(f)=\\prod_{e\\in E}P_e\\left(X_{e} \\geq f_e\\right)\n\\]\n\nAny flow $f$ that maximizes the success probability $P(f)$ is also minimizing $-\\log\\left(P(f)\\right)$ and vice versa.\n%The following sentence is a mathematical beauty and it would be really sad to have it removed (: \nUsing the fact that the logarithm is a group homomorphism from the multiplicative group of positive real numbers to the additive group of real numbers we can write:\n\\[\n-\\log\\left(\\prod_{e\\in E}P_e(X_{e} \\geq f_e)\\right) = \\sum_{e\\in E}-\\log\\left(P_e(X_e \\geq f_e)\\right)\n\\]\nThe right hand side of the equation has the form of a separable cost function $C$ for the flow $f$ from the theory of min-cost flows:\n\\[\nC(f) := \\sum_{e\\in E}-\\log\\left(P_e(X_e \\geq f_e)\\right)\n\\]\nGiven fixed probability distributions for the channel balances, finding the most likely flow is therefore equivalent to finding a flow of minimum cost on this \\emph{uncertainty network}. Any such flow can then be disected into the most likely multi-path payment as in the previous section.\n\nIn general, finding optimal solutions to the min-cost flow problem with non-linear costs is NP-hard~\\cite{guisewite1990minimum}. Fortunately, in the special case of integer flows and capacities together with a separable convex cost function a polynomial algorithm has been introduced by~\\cite{Minoux1986}.\nSince our flows are integer-valued and the cost function is separable we need to understand when a cost function arising from channel success probabilities is convex in order to be able to apply such an algorithm.\nBecause the cost function $C$ is separable we can test convexity independently for any given channel $e$ and the resulting cost function $c_e(f_e):=-\\log\\left(P_e(X_e\\geq f_e)\\right)$\nAfter simplifying by assuming a flow value $x:=f(e)$ and defining $p(x):=P_e(X_x\\geq x)$ we get:\n\\[\nc_e(x)=-\\log(p(x))\n\\]\nAssuming this function is twice differentiable, it is convex iff its second derivative is be nonnegative on the entire domain.\nThe first derivative is:\n\\[\nc_e'(x) = -\\frac{p(x)'}{p(x)}\n\\]\nand the second derivative is:\n\\[\nc_e''(x) = \\frac{(p'(x))^2-p(x)p''(x)}{{p^2(x)}} \\geq 0\n\\]\nIn particular we see that the negative log probabilities result in a convex cost function iff the following inequality holds:\n\\[\n(p'(x))^2 \\geq p(x)p''(x)\n\\]\nIn the uniform case $p(x)=\\frac{u+1-x}{u+1}$ (cf.~\\cite{pickhardt2021security}) we have $p'(x)=\\frac{-1}{u+1}$ and $p''(x)=0$ demonstrating that the resulting cost function $c_e(x)$ is convex on its entire domain.\nThis indicates that the polynomial algorithm can be used to find the flow that minimizes:\n\\[\nC(f)=\\sum_{e\\in E}-\\log\\left(\\frac{u_{e}+1-f_e}{u_{e}+1}\\right)\n\\]\nThus the most probable multi-part split for delivering the amount $U$ can be found by solving a min-cost flow problem and disecting the flow into paths.\n\nWe do not explicitly handle fees in this model, but observe that if we can find a flow that includes an upper bound to the total fees, the real payment success probability will be at least as high as the one predicted by this model, since the transported amount is only falling along the paths and our probability function is monotonic.\n\n\\subsection{Maximizing Success Probabilities vs Minimizing Fees}\n\\label{fees}\nThe current routing fee function on the Lightning network is a separable cost function depending only on the flow across each channel.\nHowever, it is easy to see that the function is not convex at the transition between flow $0$ (cost $0$) and flow $1$ (cost base fee plus unit flow cost), whenever the base fee is larger than the proportional unit flow cost. In fact, a cost function of this form is often called a \\emph{concave fixed-charge cost} in the literature. Unfortunately, finding the flow that minimizes a cost function of this form is a strongly NP-hard problem as shown in~\\cite{guisewite1990minimum} by reduction from 3-SAT to a min-cost flow problem with only fixed-charge costs.\n\nOn the other hand, if the Lightning Network community were to drop the base fee, the separable cost function would become linear in the flow value of each arc.\nFinding an MPP split that minimizes routing fees could easily be done by solving the linear min-cost flow problem using any of a number of algorithms~\\cite{ahuja1993network}.\nHowever, we note that minimizing the routing fees alone tends to\nsaturate the full capacity of cheap channels. Such paths are highly improbable to succeed since they can only do so when the entire balance is on the right side of the channel (even ignoring channel reserves). In our opinion that makes optimizing purely for fees a poor choice in general. On the other hand, only maximizing the success probability might allow routing node operators and liquidity providers to game the algorithm and extract unlimited fees.\n\nSo in practice, it should be our goal to both minimize fees and maximize success probabilities.\nNaturally, these goals can be contradictory, since node operators\ncan and will choose fees freely. Two ways of expressing this goal might be\n\\begin{enumerate}\n\\item to minimize fees with a side constraint of achieving a certain minimal probability bound, or\n\\item to maximize success probability with a side constraint of staying below a certain maximal fee bound.\n\\end{enumerate}\n\nUnfortunately, both of these problems are weakly NP-hard via the following argument:\nFirst, observe that adding unit capacities to the problems and looking for a flow of size 1 makes them instances of the so-called constrained shortest-path problem.\nThen,~\\cite[p.~798]{ahuja1993network} shows that this subclass of constrained min-cost flow problems is already NP-hard by reduction from the Knapsack problem.\n\nFortunately, the picture is not quite as bleak as it looks on first sight.\nFirst, the reduction only implies weak NP-hardness, meaning that we could find a polynomial algorithm whenever $U=O(n^k)$ for some $k$.\nStrictly speaking, the flow size $U$ is always bounded by a constant in our applications, since the total number of bitcoin is limited. Looking into the theory of Lagrangian relaxation~\\cite[p.~598ff]{ahuja1993network} methods, however, gives us immediate practical results instead of just hope.\n\nIn fact, the two cases enumerated above collapse into one when we try to find bounds for them by applying a simple one-dimensional Lagrange multiplier, that is we try to minimize:\n\\[\n\\sum_{e\\in E}-\\log(\\frac{c_{e}+1-f_e}{c_{e}+1})+\\mu\\cdot f_e\\cdot fee(e)\n\\]\nthe linear combination of both costs, with a suitable multiplicative constant\n$\\mu$.\nBy calculating this combined min-cost flow (note that the linear combination of\nthe two cost functions remains convex), not only do we get a feasible flow of size $U$, but because of the \\emph{Lagrangian bounding principle}~\\cite[p. 605f]{ahuja1993network}, whatever total fee $x$ and success probability $p$ we achieve, we are guaranteed that this combination is optimal on both sides.\nThat is, there is no solution with cheaper total fees than $x$ and at least probability $p$, and there is no solution with higher success probability than $p$ that still only costs at most $x$.\nSo in case we are not satisfied with the parameters of the solution we got, finding an adequate solution is reduced to either increasing $\\mu$ and getting a potentially cheaper, but less probable solution, or decreasing $\\mu$ and receiving a more reliable but also more expensive solution.\n\n\\subsection{Generalized Flows with Losses}\n\\label{generalized}\nSo far we have ignored the fact that every node on every path takes some part of the payment as a fee, which means that the total amount of flow gets smaller towards the target.\nThis observation is best described by a slightly more general model called \\emph{generalized (minimum cost) flows with gains and losses}. In this formulation, the flow conservation condition for any node $i\\in V$ is changed to $$\\sum_{(i,j)\\in E} f_{ij} - \\sum_{(j,i)\\in E} \\gamma_{ji}f_{ji} = b_i.$$\nThus, when we send 1 unit of flow along an edge $(i,j)$, $\\gamma_{ij}$ units of flow arrive at node $j$. The edge multipliers $\\gamma_e$ are positive rational numbers\\footnote{In the Lightning Network, these correspond to the proportional part of the fee. Again, including the base fee makes solving the problem infeasible, which is why we propose abolishing it.} and the edges are called \\emph{gainy} ($\\gamma_e > 1$) or \\emph{lossy} ($\\gamma_e < 1$) accordingly.\nNotice that until now, this formulation still depends on us knowing the exact supply/demand amounts at the source and destination nodes. This is especially troubling here, because we cannot just use an upper bound to the supply as before: there might not be a solution that uses the corresponding exact amount of fees. Therefore we introduce a cost-free high-capacity gainy (say, $\\gamma_s=2$) self-loop at the source node and set the source excess to zero. This allows for introduction of an arbitrary amount of flow at the source. Then, we aim to minimize the convex cost function as before under the remaining flow and capacity constraints.\n\nThe generalized flow problem is clearly a proper generalization of the min-cost flow problem outlined above. Unfortunately, it also appears to be harder to solve. The algorithm that we implemented for the min-cost flow problem does not seem to carry over to this more general problem. We did find pointers to some approaches~\\cite{tsengbertsekas} that might be worth exploring. So far, we have been reluctant to invest too much effort in this direction, because in our application, the fees are generally expected to be a small fraction of the total flow.  Thus it is doubtful if the greater computational effort will be worth the slightly more favorable probability/fee result.\n\n\n\\section{Payment Algorithm}\n\\label{rounds}\nOnce we are able to efficiently compute minimum cost flows optimizing either for success probabilities, fees or both using the Lagrange relaxation we naturally arrive at a round-based payment algorithm that can be used by a node $s$ that wishes to send an amount $U$ to a destination $d$.\nFor now, we assume a Lagrange-style combination between channel success probabilities and the linear fee rate function, as we believe this achieves the most useful results.\n\nThe round-based algorithm is initialized by the sending node $s$ in the following way:\nIt starts by creating a new uncertainty network model $N$ of the Lightning Network which encodes the initial uncertainty and information $s$ is gaining about the balance distribution on the network during the rounds.\n%TODO: put back in? Thus the network will be updated during the process of delivering the payment during the following rounds.\nIn order to deliver the full amount, the node $s$ will have to solve a minimum cost flow problem, send out onions and update the uncertainty network based on the successes and failures of the onions in each of the rounds.\nThe uncertainty network $N$ consists of all the nodes that are on the same connected component as $s$ on the channel graph.\nThe edges of $N$ correspond to payment channels on the Lightning Network.\nIf $s$ has no further knowledge about the channels, a directed arc for both directions of each payment channel is added to the uncertainty network.\nThe capacities of the edges are set to the capacities of the payment channel (possibly deducting channel reserves).\n\nNotice for example that in the local channels of $s$ the balance values are known and there is no uncertainty.\nThus the capacity for those channels is set to the local balance value $u$ as this is the most that can currently be sent on those channels.\nThe probability is set to $1 = P(X\\geq a | X=u)$ for any amount $a$ between $0$ and $u$.\nThis results in a negative log probability of $0$ and thus makes it very cheap for the minimum cost flow computation to utilize the liquidity in this channel. In particular since the node $s$ also does not have to pay any fees to itself.\n\nSimilarly, the receiving destination node $d$ could tell the sending node about the state of its local channels and this knowledge could also be incorporated into the graph by creating edges with 0 log probabilities and decreased capacities.\\footnote{Communicating this information in invoices is currently not part of the protocol but routing hints in the invoices might be extended to encode such information.} In Figure~\\ref{fig:mincut} we have demonstrated that for about $95\\%$ of all payment pairs the amount that can be delivered through the network is actually limited by the local outbound capacity of the sender and the local inbound capacity of the receiving node which yields another motivation for this information to be shared.\n\nAfter the setup phase the round-based phase starts. Here the algorithm iterates over the following steps until either the entire amount is delivered or the minimum cost flows become too unlikely or cannot be computed for the residual amount, which means the minimum $s$--$d$-cut has been discovered.\\footnote{In such cases it seems reasonable that $s$ open a new payment channel with $d$ for at least the remainder amount.}\nThe round starts with $s$ computing a minimum cost flow for the amount $U$ to $d$ following the optimization goal.\nThe flow is then decomposed into paths and cycles. Note that cycles cannot appear in our application as long as we do not allow negative cost edges. If they appeared, they would indicate profitable rebalancing options that may or may not be reachable for $s$. Since negative fees are not allowed in the BOLT standards, we can safely ignore cycles for now.\n\nThe node then conducts a multi-part payment by concurrently sending out onions along the resulting paths.\nIn practice one has to chose a decomposition of the flow into paths that does not create more HTLCs on a remote channel than the HTLC limit encoded into the protocol permits.\nThis engineering challenge as well as others like the question of channel reserves are ignored here for simplicity of the presentation.\nDespite the fact that the most likely flow was used, some of the onions will not reach the target in most cases. So the sending node gathers information from the error codes of failed attempts as previously described in~\\cite{tikhomirov2020probing} as well as information from the paths that have not returned an error to update the probabilities as described in~\\cite{pickhardt2021security}.\nThis step decreases the uncertainty of the channel balances and is crucial for the improvement and different results in the next round which is why we explicitly explain how the knowledge is updated in several cases.\n\\begin{enumerate}\n\\item If an onion with the amount $h$ has not been returned, we assume it has arrived at the destination. Thus all channels across the path have now locked some liquidity into an HTLC.\\@ In our uncertainty network we thus reduce the capacity $u$ of each involved channel by the amount $h$ that was sent along that channel on that path. This changes our future success probabilities for the amount $a$ to be $P(X\\geq a+h|X\\geq h)$ which corresponds to a change from $\\frac{u+1-a}{u+1}$ to $\\frac{(u-h)+1-a}{(u-h)+1}$ in the uniform case. For any value of $a$ and positive $h$ the second fraction is smaller that the first one. This leads to lower probabilities which in turn yields higher costs to use those channels again in follow up rounds.\n\\item If an onion of size $h$ fails we learn the following new information:\n  \\begin{enumerate}\n  \\item On every channel up to the failed channel there has been sufficient liquidity to forward the amount $h$. In future rounds we can use the conditional probability $P(X\\geq a|X\\geq h)$. For $a<=h$ this term will be $1$, resulting in log costs of $0$. For $a>h$ the conditional probability is uniform again. It is important to notice that the conditional probability will again lead to a convex cost function.\n  \\item Assuming the failure code is related to liquidity issues for the failed channel we know that the amount $h$ was not available. Thus we are able to reduce the capacity to $h-1$ and change the probability for the future rounds from $\\frac{u+1-a}{u+1}$ to $\\frac{h-a}{h}$ in the uniform case, or $P(X\\geq a|X < h)$ in general. This probability decrease will result in higher costs for utilizing this channel.\n  \\item If on the other hand the failure code is related to an issue with the next hop, for example a downtime, the node can update its local view by temporarily removing the failed node with all its channels.\n  \\end{enumerate}\n\\end{enumerate}\n\nNote that both successful and failing onions would also allow us to update the knowledge about the balances in the reverse direction.\nOnce all the knowledge from the partial attempts of the round has been learned --- which is reflected by the update of the probabilities and cost functions --- the algorithm enters the next round.\nFirst, the sum of all failed onions is computed as the residual amount that still needs to be delivered.\nWe enter the next round with that amount on the updated uncertainty network by computing a new minimum cost flow to generate the next optimal MPP split.\n\n\n\\section{Example}\nLet us go through an example that illustrates why finding a min-cost flow is necessary instead of just adding optimal paths.\nIt also serves to better understand the round-based algorithm.\nIn order to simplify the example, we ignore fees and channel reserves and optimize purely for probability here.\nWe also hide the nonintuitive negative log probabilities by writing down the corresponding max-probable flow with probabilities as edge weights.\nFor the channel graph depicted in Figure~\\ref{fig:counterexample},\n\\begin{figure}[htpb]\n  \\center\n  \\includegraphics[width=0.45\\textwidth]{img/counterexample.png}\n  \\caption{Example Channel Graph on which the $2$-flow with maximal probability is not an extension of the $1$-flow from  $s$ to $d$ with maximal probability. The success probabilities for sending $i$ sat are depicted as $p_i$. The channels capacities are the bold numbers along the edges.}\n  \\label{fig:counterexample}\n\\end{figure}\nassuming uniform probability distributions we compute the following probabilities for the $1$-flows (paths delivering 1 sat):\n\\[\n\\begin{aligned}\np([s,A,B,d]) = & \\frac{2}{3}\\cdot\\frac{2}{3}\\cdot\\frac{4}{5}=\\frac{16}{45} &= 0.35\\overline{5} \\\\\np([s,X,Y,d]) = & \\frac{1}{2}\\cdot\\frac{7}{8}\\cdot\\frac{4}{5}=\\frac{28}{80} &= 0.35 \\\\\np([s,X,B,d]) = & \\frac{1}{2}\\cdot\\frac{9}{10}\\cdot\\frac{4}{5}=\\frac{36}{100} &= 0.36 \\\\\n\\end{aligned}\n\\]\n\nThis indicates that $s,X,B,d$ is the minimum cost $1$-flow.\nThe $(s,X)$ arc is obviously saturated so that a $2$-flow extending the $1$-flow would have to go via the $(s,A)$ arc.\nOne can easily compute the probability of the resulting $2$-flow $f^2$ if the next sat is also using the $(B,d)$ channel and being merged with the min-cost $1$-flow as\n\\[\np(f^2) = \\frac{1}{2}\\cdot \\frac{9}{10}\\cdot \\frac{2}{3}\\cdot \\frac{2}{3}\\cdot \\frac{3}{5} = \\frac{3}{25}=0.12\n\\]\n\nHowever if we look at the $2$-flow $g^2$ that sends $1$ sat along $s,A,B,d$ and $1$ along $s,X,Y,d$ we get $p(g^2)=\\frac{16}{45}\\cdot\\frac{28}{80} = 0.124\\overline{4}$\nwhich is also the min-cost $2$-flow in this graph.\nThis example shows that finding a min-cost flow cannot in general be done  by computing the most likely path for a single sat and extending it with the next most likely $1$-sat-paths.\\footnote{This simple $+1$-algorithm could actually be rescued so that it would be able to compute the min-cost flow. However both versions would also be quite slow as they would be linear in the amount that was to be sent --- which is exponential in the input size}\n\nExtending our example and assuming we want to send a total of 3 sat we start again by computing the min-cost flow $f^3$ which can be disected into two paths $l_1= s,X,Y,d$ with an amount of $1$ and another path $l_2=s,A,B,d$ with an amount of $2$.\nAfter sending out the onions we might have learned that the onion along $l_1$ has been successful, but the one with $2$ sat along $l_2$ has failed because $B$ did not have enough liquidity to forward the onion to $d$ on the $(B,d)$ channel.\nFor the second phase of the algorithm we now compute the min-cost flow on a graph where we know that we can deliver 2 sat with perfect certainty to $B$.\nThis updated uncertainty network is depicted in Figure~\\ref{fig:round2}\n\\begin{figure}[htpb]\n  \\center\n  \\includegraphics[width=0.45\\textwidth]{img/round2.png}\n\\caption{The uncertainty network of $s$ after HTLCs of value $1$ are locked in along the path $s,X,Y,d$ and a 2-sat onion along $s,A,B,d$ failed because of missing liquidity on the $B,d$ channel. Saturated edges are removed. The black labels on the edges depict the uncertainty range of the balance or a single number if the balance is known to $s$. The $p_i$ express the success probability for sending a further $i$ sat along an edge given the updated knowledge. }\n\n  \\label{fig:round2}\n\\end{figure}\n\nThe flow that sends the full residual amount of $2$ sat along $s,A,B,X,Y,d$ has a probability of $\\frac{8}{10}\\cdot\\frac{5}{7}\\cdot\\frac{1}{2}=0.286...$ while the flow that sends $1$ sat along the $B,d$ channel has a probability of $\\frac{1}{2}\\cdot\\frac{9}{10}\\cdot\\frac{6}{7}\\cdot\\frac{3}{4}=0.289...$ telling us that for the residual amount we should make another split payment sending one sat along each of the paths $q_1=s,A,B,d$ and $q_2=s,A,B,X,Y,d$.\n\nFinally, if the path $q_1$ locks in and $q_2$ returns an error at any of the channels $(B,X),(X,Y)$ or $(Y,d)$ we would know that we cannot deliver the full payment as the min-cut in the network on the balance graph had the value $2$.\nIf however $q_2$ and $q_1$ both lock in we have successfully delivered the payment.\nIf both $q_1$ and $q_2$ return an error we know the min-cut between $s$ and $d$ on the balance graph was $1$ (as that had been locked-in in the first round and no further HTLCs have locked in).\nFinally if $q_1$ returns an error and $q_2$ locks in we will have to enter the third round.\nIn the third round there is only 1 sat to be delivered on a single possible path $q_2$ which, given our knowledge, has a success probability of $\\frac{8}{9}\\cdot\\frac{5}{6}\\cdot\\frac{2}{3}=0.494\\ldots$\\footnote{the numerical similarity to the twitter account mentioned in the acknowledgements is completely coincidental as we used that graph even before we had the discussion with the individual.}.\n\n\n\\section{Anecdotal Lab Report}\n\\textbf{Disclaimer:} We stress that this document is a preprint. In particular this section cannot be considered a proper evaluation. For that we would also have to test the algorithms on the Lightning Network mainnet.\nIn addition to the fundamental complications arising through the base fee\\footnote{which should be easily avoidable at the moment by incorporating some buffer in the fee size, as long as it remains lightly used}, such a real-world test requires overcoming several engineering challenges that we did not have the time to address yet:\n\nA practical implementation needs to automatically answer questions that might arise in case of hanging HTLCs, if channels become inactive, or amounts reach HTLC limits of channels, for example.\nAlso the implementation of the min-cost flow solver would have to be engineered to have a much faster runtime than our experimental version so that it would actually be feasible to use it on the real Lightning Network.\nHowever we felt the need to share some preliminary research progress after some test results from our simulated setting indicated an improvement of reliability of several orders of magnitude over the currently reported statistics for payment delivery.\nIn particular, an anecdotal lab report --- while highly unusual --- seemed appropriate for this particular situation in order to inform the developer community as early as possible about the potential need for a protocol upgrade removing the base fee.\n\n\\subsection{Simulation}\nSince the computation with base fees is not feasible\\footnote{and the fees are also currently low enough to not impact the results too much}, we have ignored the base fees in all our computations.\nIn fact, we started experimenting by not even optimizing for low fees at all but just for high probabilities.\n\nWe took a recent snapshot from the channel graph of the Lightning Network that was observed via the gossip protocol on one of our long running mainnet nodes.\nWe then created a static balance graph instantiation of the simulated network by splitting the channel capacity into two balance values uniformly at random independently for each channel.\n\nWe created a Python-based min-cost solver following the algorithm described in~\\cite[p.~556ff]{ahuja1993network} and a Scala version later on that turned out to be faster by a factor of about $3$--$4$.\nWhile implementing this algorithm we made some mistakes early on that accidentally led to the discovery of a heuristic that, on our snapshot Lightning Network graph, reliably produced results with less than 1\\% deviation from the optimal cost in less than 1\\% of the runtime.\nBecause the exact algorithm takes more than 30 minutes even in the faster Scala implementation, the following results have been mostly obtained with this heuristic, which typically takes about 6 seconds to run in Scala. So it is notable that the optimal results would be even better, although negligibly so.\n\nWe picked a medium-sized Lightning node that got randomly assigned a local balance of $0.42$ BTC and tried to send $0.4$ BTC to another node $3$ hops distant using the round-based algorithm described in Section~\\ref{rounds}.\nThe remote node had a total capacity of roughly $1.5$ BTC and more than $0.4$ BTC inbound liquidity. \nAssuming no routing hints from the recipient we started the first round computing a flow that was disected into several hundred small paths.\nSending them out we where able to deliver almost $75\\%$ of the amount that we wanted to deliver at once.\nWe updated the graph with the insights from the successes and failures and started the second round for the residual amount of roughly $0.1$ BTC.\nIn this round the min-cost solver on the graph with less uncertainty suggested a split of about $100$ paths.\nAfter sending out the payments we observed that the residual amount was only about $0.009$ Bitcoin.\nIn the third round, again on the updated graph, the min-cost solver suggested to send about 15 concurrent payments, of which all but one where successful.\nWe entered the fourth and final round with an amount of $30,000$ sat ($0.0003$ BTC) remaining.\nOwing to the learned data, the heuristic of our min-cost solver sent the full amount on a single path with $8$ hops, because it had already gained enough certainty for all but one channel (of size 1 BTC) along that path that it could forward $30,000$ sat.\nThus with a $99.97\\%$ probability the $30,000$ sat path settled on the selected $8$ hops path and the payment was delivered in full.\nWhile sending out all the onions we tracked the total routing fees to be $814$ sat.\n\nWe also repeated the experiment with reduced initial uncertainty by assuming the recipient node had initially communicated to the sender on which channels it could receive what amounts in the invoice.\nIn this case and on the same graph the algorithm delivered the final payment in the third round already.\n\nWe repeated the experiment a couple of times with different amounts and different instantiations of the simulated balance graph, resulting in similar results with every run. We therefore believe it reasonable to expect that we would see very similar results on the actual Lightning Network even though the unknown balance graph of the mainnet is constantly changing (potentially making some of our learned knowledge invalid).\n\nWe also used the above combination of balance graph, source and destination node for some experiments with the Lagrangian relaxation. This time, we allowed multiple parallel channels between nodes, as they are actually observed in the Lightning Network. Also, instead of going through the rounds of the payment algorithm, we just looked at the results of a single min-cost flow calculation, with a payment amount of 9.2 million sat (0.092 BTC). In this setting\\footnote{without using any knowledge about the source's or the destinations' channels}, optimizing for reliability only ($\\mu=0$) yields a probability of $P=0.16$, with total fees of 697 sat (excluding base fees). On the other hand, choosing $\\mu=100$ means optimizing almost exclusively for fees. This brings the total fees down to $16$ sat, but, as expected from the arguments in Section~\\ref{fees}, the success probability drops to $P=1.1\\cdot10^{-11}$. Table~1 shows that when we lower $\\mu$ through multiple orders of magnitude, the success probability increases drastically, while the fees are only rising moderately. Unfortunately, we increasingly observed numerical instabilities while decreasing $\\mu$. This lead to our algorithm not terminating beyond $\\mu=0.01$.\n\n\n\\begin{table}\n\\begin{center}\n\\begin{tabular}[h]{l|l|r}\n  $\\mu$ & P & fee(sat) \\\\\n  \\hline\n  100  & $1.1\\cdot10^{-11}$ & 16 \\\\\n  10 & $2.3\\cdot 10^{-5}$ & 16 \\\\\n  1 & $0.0097$ & 18 \\\\\n  0.1 &  0.044 & 24 \\\\\n  0.01 & 0.056 & 28 \\\\\n  0  & 0.16 & 697\n\\end{tabular}\n\\caption{Results of varying $\\mu$ on a fixed payment pair}\n\\end{center}\n\\label{table:mu}\n\\end{table}\n\nAgain, all numbers are from the heuristic, but the exact algorithm performed nearly identically in all our samples, including the numerical instabilities.\n\n\\subsection{Source code}\nWe could not find any preexisting open source software implementing the solution of the integer minimum cost flow problem for arbitrary separable convex cost functions.\nWe therefore share the source code of the described algorithms and methods as well as the latex sources of this document with an open MIT license at: \\url{https://github.com/renepickhardt/mpp-splitter}.\nThis repository consists of Scala- and Python-based example implementations of the exact min-cost flow algorithm described in~\\cite[p.~556ff]{ahuja1993network} for a separable convex cost function.\nIt also includes a minimalistic simulation framework in Python to test the practicality of the round-based payment loop.\nThe Scala version includes example code to demonstrate the usage of the Lagrangian relaxation.\n\n\n\\section{Advanced Applications}\n\n\n\\subsection{Multiple Senders and/or Receivers}\n\nNotice that our definition of a flow in Section~\\ref{flows} allows for an arbitrary number of both sources and sinks, that is, nodes with non-zero excess. This means that while a min-cost flow calculation might be computationally expensive, it can result in an optimized flow for multiple payments and/or channel balancing efforts at the same time. With respect to the runtime of the algorithm we have implemented\\footnote{which relies on single source shortest path calculations}, a more complex flow will take longer to optimize in practice, even though it will still respect the same worst-case runtime bounds.\nWe expect that entities like Lightning Service Providers (LSP) or trampoline routers, who need to find paths for many payments, will find this aspect helpful.\nOne could imagine a permanently running min-cost flow calculation loop that keeps learning about the network and sending out remainder amounts as in Section~\\ref{rounds}, but can always add additional payments in the next round.\nIt bears mentioning that in such multi-purpose rounds, the minimum cost is always optimized globally, which could lead to some payments being cheaper at the expense of others.\nThis needs to be accounted for when, e.g., routing payments for multiple clients.\n\n\n\\subsection{Optimal Channel Rebalancing}\n\\label{rebalancing}\nIt is well-known in the community that routing nodes can contribute to the overall payment reliability in the Lightning Network by using various channel rebalancing techniques. A recent survey paper~\\cite{papadis2020blockchain} in particular describes channel rebalancing via off-chain circular onions. This can happen proactively or lazily at routing time via a technique called just in time routing (JIT-routing)\\cite{Pickhardt2019}. To our knowledge, rebalancing has so far only been considered one channel pair at a time.\nWe observe that a node $i$ might want to rebalance several channels at once by shifting excess balance from source channels to target channels where more liquidity would be demanded.\nIn the uncertainty network, we can then assign the supply for rebalancing to the channel partner nodes of the corresponding outbound supply channels and remove these edges from the graph.\nBecause we have to account for the fees on inbound channels, the construction is a little more involved for the channels that demand extra balance: For every incoming edge $(j,i)$ that demands a balance increase, we create a copy $(j,k)$\n(with the same capacity and cost function) leading to a new node $k$ that is assigned the demand.\nFinally, we can compute a multi-source-multi-sink min-cost flow in order to shift the liquidity and conduct a multi-channel rebalancing.\nAs rebalancing is rarely time critical, one might prefer a high value of $\\mu$ in the min-cost flow computation that favors low fees over a high success rate.\nA node might even decide to stop the rebalancing operation before all of the onions have been successfully delivered: it has just engaged into a cheap opportunity for rebalancing; if delivering the remaining amounts turns out to be too expensive in the next min-cost flow calculation, it might prefer to stay with this improved but not perfect balance according to its own rebalancing strategy.\n\nAt first sight, rebalancing seems most interesting for nodes that engage more in routing than sending or receiving payments.\nHowever, we want to stress that for LSPs who conduct several payments per second, it might be very reasonable to combine the rebalancing and payment aspect, and suggest two ideas.\nFirst, we recall the global uncertainty of a node is always decreasing while delivering payments, so learning this knowledge could help find opportunities for engaging in rebalancing operations.\nSecond, an LSP might aim to keep its channels balanced according to a certain strategy.\nInstead of allowing itself to use all channels for making a payment, an LSP could restrict itself only to the channels where it has too much liquidity and exclude other channels from the computation.\nThis min-cost flow might be more expensive and less likely, but it might increase the chances for the node to forward payments; potentially earning a fee and increasing its overall reliability for other nodes might make such a trade-off worthwhile.\n\n\n\\section{Limitations}\n\n\\begin{enumerate}\n\\item As discussed in Section~\\ref{fees}, the currently adopted base fees in the Lightning Network make computing a min-cost flow NP-hard whenever the cost function includes these fees. Thus we have inquired about the motivation for the inclusion of a base fee online and received a response from the developer who appears to be responsible for this decision.\\footnote{Rusty Russell's answer to the question: Why was the base\\_fee for the routing fee calculation of the Lightning Network included? \\url{https://bitcoin.stackexchange.com/a/107341/81940}}\nWe are under the impression that the base fee was a rather ad-hoc and arbitrary choice and is not of significant importance to the Lightning Network protocol.\nEven if it were too difficult to change the protocol we see clear incentives for node operators setting the base fee to zero:\nNodes who want to conduct path finding might ignore base fees in their path computation in the future and thus ignore channels with a non-zero base fee.\nFurthermore, we note that our approach favors channels with large capacity, whose operators might therefore be able to demand higher fees.\nWe conjecture that this will give rise to a more balanced fee market, which should be in the interest particularly of node operators who have invested significant liquidity.\n\\item We made the crucial assumption that channel balances are uniformly distributed. While this was confirmed by prior research~\\cite{pickhardt2021security}, the situation could evolve over time, making our priors less suitable.\nIf, say, we assumed a normal distribution, the negative log probabilities would not be convex on the entire domain and the min-cost flow problem might not be solvable in polynomial time.\nHowever, we note for future research that there are practical solutions\nfor this, like limiting the domain by limiting the allowed channel capacity. Moreover, in~\\cite{pickhardt2021security} it has also been shown in the single path case that adopting a rebalancing protocol which changed the prior to a normal distribution but computing paths with a uniform prior still performed well.\nIn fact, we conjecture that we cannot do better than assume uniformity unless we have knowledge of the parameters of the actual distribution.\n\\item While the min-cost flow problem admits a polynomial time solution in the case of a convex cost function (without base fees), it is still computationally intensive, with a runtime that is quadratic in the number of channels. Remember also that we might have to solve several of these problems per payment round in order to find a suitable Lagrange multiplier in the trade-off between reliability and fees.\nOur prototype implementation is currently not optimized for speed; on the full Lightning Network graph, running times can easily reach 30 minutes and more, depending on the degree of precision. However, we have achieved preliminary experimental results on a promising heuristic that seems to very favorably trade reductions in runtime for only a slight deterioration from the optimal solution of the minimum cost flows.\nUsing heuristics like this, algorithmic methods including approximation and parallelization, as well as optimized code, we estimate that on the currently public Lightning Network it should be feasible to achieve sub-second runtimes on commodity hardware.\nHowever, we feel that this research is still too early for publication.\n\\end{enumerate}\n\n\\section{Future work}\nBeyond the optimization steps required for practical usability and extensive tests on the actual Lightning Network that we have\nhinted at above, we see some additional directions for further research:\n\n\\begin{enumerate}\n\\item Recall from Section~\\ref{fees} that when optimizing for both fees and reliability one has to find a suitable value for $\\mu$. We hope that improving on the current Lightning Network user experience will be possible with some experimentation, user interface design, and drawing from the extensive literature on Lagrangian relaxation.\n\n\\item In the round-based payment algorithm described in \\ref{rounds}, the optimal delay spent waiting for further responses after the first failed onion has returned and before entering the next round with updated knowledge remains an open question. In our experiments and simulation we have assumed waiting for the status of all onions to be resolved. We defer investigation of this question to practical experimentation but point out that it does not appear too critical since we can always incorporate information that arrives too late for one round in any later ones. In the extreme case, for every returned onion a new round could be entered.\n\n\\item It is conceptionally straight forward to extend the probabilities with provenance scores from operating nodes on the Lightning Network.\nInstead of just looking at the channel balance distribution one could create a joint distribution from, e.g., estimating the nodes' uptime.\n\n\\item Large channels could become the equivalent to the autobahn and attract a lot of traffic. Given the limitations of concurrent payments on the Lightning Network, the need for congestion control mechanisms might arise.\n\n\\item The payment planning and execution algorithm accumulates knowledge about the actual channel success probability distributions. However, we know that in practice those distributions do not stay constant. In fact, they change with every payment that is conducted through a particular channel or via the rebalancing behavior of node operators.\nFurther research into the dynamics of the money flow through the Lightning Network will help estimate how long to rely on the knowledge gained from previous payment attempts. This knowledge can then be adequately discounted or forgotten in future rounds.\n\n\\item The promising idea of adding redundant liquidity during the path finding phase of MPP splits was introduced by~\\cite{DBLP:journals/corr/abs-1910-01834}. It would be very interesting to study if we could find optimal redundant overpayments so that we can expect to finish within one round of sending out multi-part payments with high probability.\n\n\\item  In spite of the arguments given in Section~\\ref{generalized} that led to prioritizing other aspects first, we still believe generalized flows to be an interesting future research direction, especially in light of multiple-source-multiple-sink applications (cf. Section~\\ref{rebalancing}). In this setting, constructions like the self-loop we described might allow for more flexibility: One can specify some sources and destinations with exact excess requirements as well as leave others open in order to give the optimization more leeway.\n\n\\end{enumerate}\n\n\\section{Acknowledgements}\nThis research was partially sponsored by the Norwegian University of Science and Technology (NTNU).\nWe want to thank David Karger and MIT open courseware for sharing a lecture series about min-cost flows\\footnote{\\url{https://www.youtube.com/playlist?list=PLaRKlIqjjguDXlnJWG2T7U52iHZl8Edrc}} that has been very useful for us in creating our reference implementation and understanding the theory of min-cost flows.\nWe are grateful to Ravindra Ahuja, Thomas Magnanti and James Orlin for their exceptional textbook~\\cite{ahuja1993network} which contains so much of the knowledge we have been adapting to our use case here.\nWe also thank Twitter user \\texttt{@four9four} for discussing our preliminary results after the Lightning hacksprint in April 2021.\nThanks to GB for polishing the graphics.\nWe thank Rene's co-authors Andreas M. Antonopoulos and Olaoluwa Osuntokun for accepting Rene's decision to temporarily prioritize this research over their Lightning Network book project.\nFinally our gratitude goes to Christian Decker with whom we had several discussions and who provided valuable feedback along the course of this research.\nIf you like the idea of decentralized and independent research and development of the Lightning Network feel free to support future work by contributing via \\url{https://donate.ln.rene-pickhardt.de}.\n\n\n\n\\bibliography{mppSplitting}\n\\bibliographystyle{plain}\n\n\\begin{appendix}\n  \\section{Twitter-based TL;DR}\n  While putting all together we actually shared the method and results in 6 Tweets:\n  \\\\\\\\\n\n    \\textbf{March 17th 2021}\\footnote{\\url{https://twitter.com/renepickhardt/status/1372169686251626499}} \\\\\n    Over the last year I have been making quite some discoveries about  \\#bitcoin Payment Pathfinding on the \\#LightningNetwork .\\\\A paper which introduces a probabilistic approach of modeling the uncertainty of remote channel balances is out and discussed on \\url{https://lists.linuxfoundation.org/pipermail/lightning-dev/2021-March/002984.html}\\\\\\\\\n  \n  \\textbf{April 22nd 2021}\\footnote{\\url{https://twitter.com/renepickhardt/status/1385144337907044352}} \\\\\n  Multipathfinding \n\\begin{enumerate}\n\\item capacities are integers (Satoshis)\n\\item channel success probabilities -log(1-x/c) are convex functions\n\\item Solving integer minimum cost flows with separable convex cost objective polynomially: \\url{https://link.springer.com/chapter/10.1007\\%2FBFb0121104}\n\\end{enumerate}\n  Kudos @stefanwouldgo 4 digging this out\n\\\\\\\\\n  \n  \\textbf{May 26th 2021}\\footnote{\\url{https://twitter.com/renepickhardt/status/1397559345139888137}}\\\\\n  most likely MPP-split to deliver 92 mBTC from my lightning node (03efc...) to (022c6...).\n  We split into 11 onions!\n\\begin{figure}[htpb]\n  \\center\n  \\includegraphics[width=0.45\\textwidth]{img/optflow.jpeg}\n  \\label{fig:optflow}\n\\end{figure}\\\\\nWith knowledge of my own balance \\& routing hints in the invoice the total likelihood to deliver all 11 onions is $64.84\\%$\nNote the 6 hop path with 4 WUMBO channels!\n\\\\\\\\\n\n\\textbf{June 6th 2021}\\footnote{\\url{https://twitter.com/renepickhardt/status/1401514950984712198}}\\\\\nCouldn't go to Miami so I coded up my algorithm!\\\\\\\\\nIn a simulated network with realistic balance values a node having 0.42 BTC could send 0.4 BTC to a remote node (that could receive up to 1.59 BTC) with no direct channel\\\\\\\\\nIt took just 4 attempts to deliver and 814 sat in fees\\\\\\\\\n\n\\textbf{June 8th 2021}\\footnote{\\url{https://twitter.com/renepickhardt/status/1402264479677693958}}\\\\\non other good news:\n\\begin{enumerate}\n\\item this yields another test vector for unit tests\n\\item the previous / non optimal algorithm might for other reasons (that go beyond a tweet) actually be better suitable for the lightning network after all\n\\item either way the issue seems fixable (:\n\\end{enumerate}\n\n  \\textbf{July 5th 2021}\\footnote{\\url{https://twitter.com/stefanwouldgo/status/1412158904008646660}}\\\\\n  Lightning Routing IS NP hard, though.\n\n  It's funny 'cause it's true.\n\n\n\n\\end{appendix}\n\\end {document}\n", "meta": {"hexsha": "f864a53267a49b5bcd0cdd6c74653ecd7e8bb673", "size": 59855, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/mppSplitting.tex", "max_stars_repo_name": "drmartinberger/mpp-splitter", "max_stars_repo_head_hexsha": "74b7634bb4c21e62c24865906a83fd391e4e06bf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paper/mppSplitting.tex", "max_issues_repo_name": "drmartinberger/mpp-splitter", "max_issues_repo_head_hexsha": "74b7634bb4c21e62c24865906a83fd391e4e06bf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/mppSplitting.tex", "max_forks_repo_name": "drmartinberger/mpp-splitter", "max_forks_repo_head_hexsha": "74b7634bb4c21e62c24865906a83fd391e4e06bf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 105.9380530973, "max_line_length": 1234, "alphanum_fraction": 0.7888229889, "num_tokens": 13550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.34722653010511845}}
{"text": "% Created 2019-08-27 mar 16:52\n\\documentclass[presentation,aspectratio=1610]{beamer}\n\\usepackage[utf8]{inputenc}\n\\usepackage[T1]{fontenc}\n\\usepackage{fixltx2e}\n\\usepackage{graphicx}\n\\usepackage{longtable}\n\\usepackage{float}\n\\usepackage{wrapfig}\n\\usepackage{rotating}\n\\usepackage[normalem]{ulem}\n\\usepackage{amsmath}\n\\usepackage{textcomp}\n\\usepackage{marvosym}\n\\usepackage{wasysym}\n\\usepackage{amssymb}\n\\usepackage{hyperref}\n\\tolerance=1000\n\\usepackage{khpreamble}\n\\usepackage{amssymb}\n\\DeclareMathOperator{\\shift}{q}\n\\DeclareMathOperator{\\diff}{p}\n\\usetheme{default}\n\\author{Kjartan Halvorsen}\n\\date{2018-01-19}\n\\title{Computerized Control - LTIs, impulse response, difference equations}\n\\hypersetup{\n  pdfkeywords={},\n  pdfsubject={},\n  pdfcreator={Emacs 25.3.50.2 (Org mode 8.2.10)}}\n\\begin{document}\n\n\\maketitle\n\n\n\\section{Intro: Discrete-time signals}\n\\label{sec-1}\n\n\\begin{frame}[label=sec-1-1]{The discrete causal linear time-invariant system}\n\\begin{center}\n\\begin{tikzpicture}[node distance=20mm, anchor=north]\n\\node[coordinate] (input) {};\n\\node[rectangle, draw, right of=input, inner sep=3mm] (lti) {g};\n\\node[coordinate, right of=lti] (output) {};\n\\draw[->] (input) -- node[near start, above] {$u(k)$}  (lti);\n\\draw[->] (lti) -- node[near end, above] {$y(k)$} (output);\n\\end{tikzpicture}\n\\end{center}\n\n\\[ y(k) = g \\ast u = \\sum_{n=0}^\\infty g(n) u(k-n) \\]\n\nIf input signal is a pulse (delta-function)\n\\begin{center}\n\\begin{tikzpicture}\n\\begin{axis}[\n  width=14cm,\n  height=2.5cm,\n  xlabel={$k$},\n  ylabel={$u(k)$},\n  xmin=-2.5,\n  xmax=10.5,\n]\n\n\\addplot+[black, ycomb, domain=-2:10, samples=13,variable=k] { (k==0)}; \n\n\\end{axis}\n\\end{tikzpicture}\n\\end{center}\n\n\\vspace*{-5mm}\n\\[ y(k) = \\sum_{n=0}^\\infty g(n) \\delta(k-n) = g(k) \\]\n\\end{frame}\n\n\\begin{frame}[label=sec-1-2]{Linearity, time invariance and the pulse response}\nThe input signal\n\n\\begin{center}\n\\begin{tikzpicture}\n\\small\n\\begin{axis}[\n  width=14cm,\n  height=3.5cm,\n  xlabel={$k$},\n  ylabel={$u(k)$},\n  xmin=-0.5,\n  xmax=10.5,\n  ytick = {-1, 0, 0.6, 2},\n]\n\n\\addplot+[black, ycomb, domain=-2:10, samples=13,variable=k] { 0.6*(k==0) + 2*(k==1) - 1*(k==2)}; \n\n\\end{axis}\n\\end{tikzpicture}\n\\end{center}\n\n\\vspace*{-5mm}\n\n\nCan be written \n\\[u(k) = 0.6\\delta(k) + 2\\delta(k-1) - \\delta(k-2) \\]\nSince the system's response to a pulse is given by $g(k)$, the output signal is\n\\[ y(k) = ?\\]\n\\end{frame}\n\n\\begin{frame}[label=sec-1-3]{Linearity, time invariance and the pulse response}\nThe input signal\n\n\\begin{center}\n\\begin{tikzpicture}\n\\small\n\\begin{axis}[\n  width=14cm,\n  height=3.5cm,\n  xlabel={$k$},\n  ylabel={$u(k)$},\n  xmin=-0.5,\n  xmax=10.5,\n  ytick = {-1, 0, 0.6, 2},\n]\n\n\\addplot+[black, ycomb, domain=-2:10, samples=13,variable=k] { 0.6*(k==0) + 2*(k==1) - 1*(k==2)}; \n\n\\end{axis}\n\\end{tikzpicture}\n\\end{center}\n\n\\vspace*{-5mm}\n\n\nCan be written \n\\[u(k) = 0.6\\delta(k) + 2\\delta(k-1) - \\delta(k-2) \\]\nSince the system's response to a pulse is given by $g(k)$, the output signal is\n\\[ y(k) = 0.6g(k) + 2g(k-1) - g(k-2) \\]\n\\end{frame}\n\n\n\\begin{frame}[label=sec-1-4]{The output of a causal, linear discrete-time system is a weighted sum of previous input}\n\\[ y(k) = g \\ast u = \\sum_{n=0}^\\infty g(n) u(k-n) \\]\nThe \\alert{weighting function} $g(k)$ is the \\alert{pulse response} of the system.\n\nWhat if the weighting function looks like this\n\n\\begin{center}\n\\begin{tikzpicture}\n\\small\n\\begin{axis}[\n  width=14cm,\n  height=3.5cm,\n  xlabel={$k$},\n  ylabel={$g(k)$},\n  xmin=-0.5,\n  xmax=10.5,\n  ytick = {0, 1},\n]\n\n\\addplot+[black, ycomb, domain=-2:10, samples=13,variable=k] { (k==4)}; \n\n\\end{axis}\n\\end{tikzpicture}\n\\end{center}\n\n\\[y(k) = \\]\n\\end{frame}\n\n\\begin{frame}[label=sec-1-5]{Exercise: Impulse response}\n\\end{frame}\n\n\n\n\\section{The shift operator}\n\\label{sec-2}\n\\begin{frame}[label=sec-2-1]{The shift operator}\n\\begin{itemize}\n\\item For difference equations the shift operator \\(\\shift\\) is very useful.\n\\item The shift operator is defined for double-infinite sequences $x_k$, i.e. the sequence $x_k$ must be infinitely long both for negative and positive $k$.\n\\item The operator shifts the sequence ahead one step:\n\\[ \\shift x_k = x_{k+1} \\]\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}[label=sec-2-2]{The difference equation is a representation of a discrete-time dynamical systems}\n\\begin{center}\n\\begin{tikzpicture}[node distance=25mm]\n\\node[rectangle, draw, minimum height=10mm, minimum width=14mm] (sys) {$G(\\shift)$};\n\\node[coordinate, left of=sys] (input) {};\n\\node[coordinate, right of=sys] (output) {};\n\n\\draw[->] (input) -- node [near start, above] {$u(k)$} (sys);\n\\draw[->] (sys) -- node [near end, above] {$y(k)$} (output);\n\n\\end{tikzpicture}\n\\end{center}\n\n\\[ y_{k+n} + a_1 y_{k+n-1} + \\cdots + a_n y_k =  b_0 u_{k+m} + b_1 u_{k+m-1} + \\cdots + b_m u_k \\]\n\n\\[ \\left( \\shift^n + a_1 \\shift^{n-1} + \\cdots + a_n \\right) y(k) = \\left( b_0 \\shift^m + b_1\\shift^{m-1} + \\cdots + b_m \\right)  u(k) \\]\n\n\\[ y(k) = \\frac{b_0 \\shift^m + b_1\\shift^{m-1} + \\cdots + b_m}{ \\shift^n + a_1 \\shift^{n-1} + \\cdots + a_n} u(k) = \\frac{B(\\shift)}{A(\\shift)} u(k) = G(\\shift) u(k) \\]\n\\end{frame}\n\n\\section{First order system and pulse response}\n\\label{sec-3}\n\n\\begin{frame}[label=sec-3-1]{First order systems}\n\\begin{center}\n\\begin{tikzpicture}[node distance=20mm, anchor=north]\n\\node[coordinate] (input) {};\n\\node[rectangle, draw, right of=input, inner sep=3mm] (lti) {$G(q)=\\frac{q-1}{q}$};\n\\node[coordinate, right of=lti] (output) {};\n\\draw[->] (input) -- node[near start, above] {$u(k)$}  (lti);\n\\draw[->] (lti) -- node[near end, above] {$y(k)$} (output);\n\\end{tikzpicture}\n\\end{center}\n\nThe system with pulse-transfer operator $G(q)=\\frac{q-1}{q}$ corresponds to the difference equation\n\\[ y(k) = G(q)u(k) \\Leftrightarrow y(k) = \\frac{q-1}{q} u(k) \\]\n\\[ y(k+1) = ?\\]\n\\end{frame}\n\n\\begin{frame}[label=sec-3-2]{First order systems}\n\\begin{center}\n\\begin{tikzpicture}[node distance=20mm, anchor=north]\n\\node[coordinate] (input) {};\n\\node[rectangle, draw, right of=input, inner sep=3mm] (lti) {$G(q)=\\frac{q-1}{q}$};\n\\node[coordinate, right of=lti] (output) {};\n\\draw[->] (input) -- node[near start, above] {$u(k)$}  (lti);\n\\draw[->] (lti) -- node[near end, above] {$y(k)$} (output);\n\\end{tikzpicture}\n\\end{center}\n\nThe system with pulse-transfer operator $G(q)=\\frac{q-1}{q}$ corresponds to the difference equation\n\\[ y(k) = G(q)u(k) \\Leftrightarrow y(k) = \\frac{q-1}{q} u(k) \\]\n\\[ y(k+1) = u(k+1)-u(k), \\quad \\text{i.e.~a discrete-time differentiator}\\]\n\\end{frame}\n\n\\begin{frame}[label=sec-3-3]{First order systems}\n\\begin{center}\n\\begin{tikzpicture}[node distance=20mm, anchor=north]\n\\node[coordinate] (input) {};\n\\node[rectangle, draw, right of=input, inner sep=3mm] (lti) {$G(q)=\\frac{q}{q-a}$};\n\\node[coordinate, right of=lti] (output) {};\n\\draw[->] (input) -- node[near start, above] {$u(k)$}  (lti);\n\\draw[->] (lti) -- node[near end, above] {$y(k)$} (output);\n\\end{tikzpicture}\n\\end{center}\n\nThe system with pulse-transfer operator $G(q)=\\frac{q}{q-a}$ corresponds to the difference equation\n\\[ y(k) = G(q)u(k) \\Leftrightarrow y(k) = \\frac{q}{q-a} u(k) \\]\n\\[ y(k+1) = ?\\]\n\\end{frame}\n\n\\begin{frame}[label=sec-3-4]{First order systems}\n\\begin{center}\n\\begin{tikzpicture}[node distance=20mm, anchor=north]\n\\node[coordinate] (input) {};\n\\node[rectangle, draw, right of=input, inner sep=3mm] (lti) {$G(q)=\\frac{q}{q-a}$};\n\\node[coordinate, right of=lti] (output) {};\n\\draw[->] (input) -- node[near start, above] {$u(k)$}  (lti);\n\\draw[->] (lti) -- node[near end, above] {$y(k)$} (output);\n\\end{tikzpicture}\n\\end{center}\n\nThe system with pulse-transfer operator $G(q)=\\frac{q}{q-a}$ corresponds to the difference equation\n\\[ y(k) = G(q)u(k) \\Leftrightarrow y(k) = \\frac{q}{q-a} u(k) \\]\n\\[ y(k+1) = ay(k) + u(k+1). \\quad \\text{If $a=1$, the system is a discrete-time integrator}\\]\n\\end{frame}\n\n\\begin{frame}[label=sec-3-5]{Pulse-response of a first order system}\n\\[ y(k+1) = ay(k) + u(k+1) \\]\n\\end{frame}\n\n\\begin{frame}[label=sec-3-6]{Pulse response of a first order system}\n\\[ y(k+1) = ay(k) + u(k+1) \\]\n\nPair the pulse response to each of the values of $a$\n\\[ \\text{I)}\\; a=1 \\qquad \\text{II)}\\; a=2 \\qquad \\text{III)}\\; a = 0.5 \\qquad \\text{IV)}\\; a=-0.9 \\]\n\n\\begin{tikzpicture}\n\\small\n\\begin{axis}[\nwidth=7cm,\nheight=2.5cm,\nxlabel={$k$},\nylabel={$g(k)$},\nxmin=-3.5,\nxmax=10.5,\nytick = {-1,0,1},\nymin = -1.2, ymax=1.2,\n]\n\\addplot+[black, ycomb, domain=-3:10, samples=14,variable=k] { (k>=0)*pow(1,k)};\n\\end{axis}\n\n\\begin{axis}[\nxshift=7cm,\nwidth=7cm,\nheight=2.5cm,\nxlabel={$k$},\nylabel={$g(k)$},\nxmin=-3.5,\nxmax=10.5,\nytick = {0},\nytick = {-1,0,1},\nymin = -1.2, ymax=1.2,\n]\n\\addplot+[black, ycomb, domain=-3:10, samples=14,variable=k] { (k>=0)*pow(-0.9,k)};\n\\end{axis}\n\n\\begin{axis}[\nxshift=0cm,\nyshift=-2.5cm,\nwidth=7cm,\nheight=2.5cm,\nxlabel={$k$},\nylabel={$g(k)$},\nxmin=-3.5,\nxmax=10.5,\nytick = {0},\nytick = {-1,0,8},\nymin = -0.2, ymax=8.2,\n]\n\\addplot+[black, ycomb, domain=-5:8, samples=14,variable=k] {  (k>=0)*pow(2,k) };\n\\end{axis}\n\n\\begin{axis}[\nxshift=7cm,\nyshift=-2.5cm,\nwidth=7cm,\nheight=2.5cm,\nxlabel={$k$},\nylabel={$g(k)$},\nxmin=-3.5,\nxmax=10.5,\nytick = {0},\nytick = {-1,0,1},\nymin = -1.2, ymax=1.2,\n]\n\\addplot+[black, ycomb, domain=-5:8, samples=14,variable=k] {  (k>=0)*pow(0.5,k)};\n\\end{axis}\n\n\n\\end{tikzpicture}\n\\end{frame}\n% Emacs 25.3.50.2 (Org mode 8.2.10)\n\\end{document}", "meta": {"hexsha": "224b9952be1d398d8f33971b57941e7ddbc0df22", "size": 9259, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "discrete-time-systems/slides/problem-solving-sampling-poles-etc.tex", "max_stars_repo_name": "kjartan-at-tec/mr2007-computerized-control", "max_stars_repo_head_hexsha": "16e35f5007f53870eaf344eea1165507505ab4aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-11-07T05:20:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-22T09:46:13.000Z", "max_issues_repo_path": "discrete-time-systems/slides/problem-solving-sampling-poles-etc.tex", "max_issues_repo_name": "kjartan-at-tec/mr2007-computerized-control", "max_issues_repo_head_hexsha": "16e35f5007f53870eaf344eea1165507505ab4aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-06-12T20:44:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-12T20:49:00.000Z", "max_forks_repo_path": "discrete-time-systems/slides/problem-solving-sampling-poles-etc.tex", "max_forks_repo_name": "kjartan-at-tec/mr2007-computerized-control", "max_forks_repo_head_hexsha": "16e35f5007f53870eaf344eea1165507505ab4aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-14T03:55:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-14T03:55:27.000Z", "avg_line_length": 26.9156976744, "max_line_length": 167, "alphanum_fraction": 0.641213954, "num_tokens": 3616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.34722653010511845}}
{"text": "\\section{delimited continuations}\n\\label{sec:cont-delim-cont}\nContinuatioins\nA conditional banch selects a continuation from the two possible\nfutures; rasing an exception discards. Traditional way to handle\ncontinuations explicitly in a program is to transform a program into\ncps style. Continuation captured by call/cc is the {\\bf whole} continuation\nthat includes all the future computation.. In practice, most of the\ncontinuations that we want to manipulate are only a part of\ncomputation. Such continuations are called {\\bf delimited continuations} or\n{\\bf partial continuations}.\n\n\n\\begin{enumerate}\n\\item cps transform \\\\\n  there are multiple ways to do cps transform, here are two.\n\n  \n  \\begin{bluetext}\n------------------------------------------\n   [x] --> x\n   [\\x. M] --> \\k . k (\\x . [M])\n   [M N] --> \\k. [M] (\\m . m [N] k)\n------------------------------------------\n\n\n------------------------------------------\n   [x] --> \\k . k x\n   [\\x. M] --> \\k. k (\\x.[M])\n   [M N] --> \\k. [M] (\\m . [N] (\\n. m n k))\n------------------------------------------\n\n\n[callcc (\\k. body)] = \\outk. (\\k. [body] outk) (\\v localk. outk v)\n   \n  \\end{bluetext}\n\n  \n\\item experiment\n\n\\begin{alternate}\n#load \"delimcc.cma\";;\n\\end{alternate}\n\\begin{alternate}\nDelimcc.shift;;\n- : 'a Delimcc.prompt -> (('b -> 'a) -> 'a) -> 'b = <fun>\n\\end{alternate}\n\n\\begin{bluetext}\nreset (fun () -> M ) --> push_prompt p (fun () -> M )\nshift (fun k -> M) --> shift p (fun k -> M )\n\\end{bluetext}\nin racket you should have \\textit{(require racket/control)}\nand then \\textit{(reset expr ...+)}\n\\textit{(shift id expr ...+)}\n\n\n\\begin{ocamlcode}\nmodule D = Delimcc\n(** set the prompt *)  \nlet p = D.new_prompt ()\nlet (reset,shift),abort  = D.(push_prompt &&& shift &&& abort ) p;;\nlet foo x = reset (fun () -> shift (fun cont -> if x = 1 then cont 10 else 20 ) + 100 )\n\\end{ocamlcode}\n\n\\begin{alternate}\nfoo 1 ;;\n- : int = 110\nfoo 2  ;;\n- : int = 20\n5 * reset (fun () -> shift (fun k -> 2 * 3 ) + 3 * 4 );;\n- : int = 30\nreset (fun () -> 3 + shift (fun k -> 5 * 2) ) - 1 ;;\n- : int = 9\n\\end{alternate}\n\\begin{bluetext}\nval p : '_a D.prompt = <abstr>\nval reset : (unit -> '_a) -> '_a = <fun>\nval shift : (('_a -> '_b) -> '_b) -> '_a = <fun>\nval abort : '_a -> 'b = <fun> \n\\end{bluetext}\n\n\\begin{ocamlcode}\nlet p = D.new_prompt ()\nlet (reset,shift),abort  = D.(push_prompt &&& shift &&& abort ) p;;\n\\end{ocamlcode}\n\n\\begin{alternate}\nreset (fun () -> if (shift (fun k -> k(2 = 3))) then \"hello\" else \"hi \") ^ \"world\";;\n- : string = \"hi world\"\nreset (fun () -> if (shift (fun k -> \"laji\")) then \"hello\" else \"hi \") ^ \"world\";;\n- : string = \"lajiworld\"\nreset (fun _ -> \"hah\");;\n- : string = \"hah\"\n\\end{alternate}\n\n\n\\begin{ocamlcode}\nlet make_operator () =  \n  let p = D.new_prompt () in \n  let (reset,shift),abort = D.(push_prompt &&& shift &&& abort) p in \n  p,reset,shift,abort\n\\end{ocamlcode}\n\nDelimited continuations seems not able to handle answer type polymorphism.\n\n\\begin{bluetext}\nexception Str of [`Found of int | `NotFound]  \n\\end{bluetext}\n\n\\begin{ocamlcode}\nlet times lst  = \n  let rec times_aux lst = match lst with \n    | [] -> 1 \n    | 0 :: xs -> shift (fun _ -> 0 )\n    | x :: xs -> begin \n      (* printf \"entering %d\\n\" x ; *)\n      let v = x * times_aux xs in \n      (* printf \"exiting %d\\n\" x ;  *)\n      v\n    end in \n  reset (fun () -> times_aux lst )\n\\end{ocamlcode}\n\nStore the continuation, the type system is not friendly to the\ncontinutations, but fortunately we have \\textit{side effects} at hand, we can\nstore it. (This is pretty hard in Haskell )\n\n\\begin{ocamlcode}\nlet p,reset,shift,abort = make_operator() in \n  let c = ref None in \n  begin \n   reset (fun () -> 3 + shift (fun k -> c:= Some k ;  0) - 1)  ; \n   Option.get (!c) 20 \n   end ;;\n          Characters 81-139:\n     reset (fun () -> 3 + shift (fun k -> c:= Some k ;  0) - 1)  ; \n     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n     Warning 10: this expression should have type unit.\n   \\end{ocamlcode}\n\\begin{ocamlcode}   \n- : int = 22\n\\end{ocamlcode}\n\\begin{ocamlcode}\nlet cont = \n  let p,reset,shift,abort = make_operator() in \n  let c = ref None in \n  let rec id lst = match lst with \n    | [] -> shift (fun k -> c:=Some k ; [] )\n    |x :: xs -> x :: id xs in \n  let xs = reset (fun () -> id [1;2;3;4]) in \n  xs, Option.get (!c);;\n\\end{ocamlcode}\n\\begin{ocamlcode}\nval cont : int list * (int list -> int list) = ([], <fun>)\n\\end{ocamlcode}\n\\begin{alternate}\n# let a,b = cont ;;\nval a : int list = []\n\nval b : int list -> int list = <fun>\n# b [];;\n- : int list = [1; 2; 3; 4]\n\\end{alternate}\n\n\n\n\\begin{ocamlcode}\ntype tree = Empty | Node of  tree * int  * tree \nlet walk_tree = \n  let cont = ref None in \n  let p,reset,shift,abort = make_operator() in \n  let yield n = shift (fun k -> cont := Some k; print_int n ) in \n  let rec walk2 tree = match tree with \n    |Empty -> ()\n    |Node (l,v,r) -> \n      walk2 l ;\n      yield v ; \n      walk2 r in \n  fun tree -> (reset (fun _ -> walk2 tree ), cont);;\n\\end{ocamlcode}\n\\begin{ocamlcode}\nval walk_tree : tree_t -> unit * ('_a -> unit) option Batteries.ref =\n\\end{ocamlcode}\n\n\\begin{alternate}\n# let _, cont = walk_tree tree1 ;;\n1val cont : ('_a -> unit) option Batteries.ref = {contents = Some <fun>}\n# Option.get !cont ();;\n2- : unit = ()\n# Option.get !cont ();;\n3- : unit = ()\n# Option.get !cont ();;\n- : unit = ()\n# Option.get !cont ();;\n- : unit = ()\n\\end{alternate}\n\nIt's quite straightforward to implement yield using delimited\ncontinuation, since each time shifting will escape the control, and you store the continuation, later it can be resumed.\n\n\n\\begin{bluetext}\n(** defer the continuation *)  \nshift (fun k -> fun () -> k \"hello\")\n\\end{bluetext}\n\nBy wrapping continuations, we can \\textbf{access the information outside} of the enclosing\nreset while staying within reset lexically.\n\nsuppose this type check\n\n\\begin{alternate}\n  let f x = reset (fun () -> shift (fun k -> fun () -> k \"hello\") ^ \"world\" ) x\n  f : unit -> string \n\\end{alternate}\n\n\\item Answer type modification (serious)\n  in the following context,\n  \\verb|reset (fun () -> [...] ^  \"word\" )|, the value returned by\n  reset appears to be a string. An answer type is a type of the enclosing\n  \\emph{reset}.\n\n\\item reorder delimited continuations \\\\\n  if we apply a continuation at the tail position, the captured computation is simply\n  resumed. If we apply a continuation at the non-tail position, we can perform\n  additional computation after resumed computation finishes.\n\n  Put differently, we can switch the execution order of the surrounding context.\n\n\\begin{ocamlcode}\nlet p,reset,shift,abort = make_operator () in\n    reset (fun () -> 1 + (shift (fun k -> 2 * k 3 )));;\n\\end{ocamlcode}\n\\begin{ocamlcode}\n- : int = 8    \n\\end{ocamlcode}\n\n\\begin{ocamlcode}\nlet p,reset,shift,abort = make_operator () in \n   let either a b = shift (fun k -> k a ; k b ) in \n   reset (fun () -> \n   let x = either  0  1 in \n   print_int x ; print_newline ());;\n \\end{ocamlcode}\n\\begin{ocamlcode} \n 0\n 1  \n\\end{ocamlcode}\n\\item useful links \\\\\n  \\href{http://blog.fitzell.ca/2009/01/seaside-partial-continuations.html}{sea\n    side} \\\\\n  \\href{http://pllab.is.ocha.ac.jp/~asai/cw2011tutorial/}{shift and\n    reset tutorial} \\\\\n  \\href{http://pllab.is.ocha.ac.jp/~asai/cw2011tutorial/main-e.pdf}{shift\n    reset tutorial} \\\\\n  \\href{http://docs.racket-lang.org/reference/cont.html#(part._.Classical_.Control_.Operators)}{racket\n    control operators} \\\\\n  \\href{http://okmij.org/ftp/continuations/caml-shift.pdf}{caml-shift-paper.pdf} \\\\\n  \\href{http://okmij.org/ftp/continuations/caml-shift-talk.pdf}{caml-shift-talk} \\\\\n\n\\end{enumerate}\n", "meta": {"hexsha": "f07d3d2d74b112f429bdd93f7de8e2376307b705", "size": 7622, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "library/delimcc.tex", "max_stars_repo_name": "mgttlinger/ocaml-book", "max_stars_repo_head_hexsha": "09a575b0d1fedfce565ecb9a0ae9cf0df37fdc75", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 142, "max_stars_repo_stars_event_min_datetime": "2015-01-12T16:45:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-15T00:47:37.000Z", "max_issues_repo_path": "library/delimcc.tex", "max_issues_repo_name": "mgttlinger/ocaml-book", "max_issues_repo_head_hexsha": "09a575b0d1fedfce565ecb9a0ae9cf0df37fdc75", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-10-09T13:53:43.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-03T04:15:48.000Z", "max_forks_repo_path": "library/delimcc.tex", "max_forks_repo_name": "mgttlinger/ocaml-book", "max_forks_repo_head_hexsha": "09a575b0d1fedfce565ecb9a0ae9cf0df37fdc75", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2015-02-10T18:12:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-21T06:57:32.000Z", "avg_line_length": 28.9809885932, "max_line_length": 120, "alphanum_fraction": 0.6078457098, "num_tokens": 2400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.3472265301051184}}
{"text": "\\documentclass[10pt,conference,compsocconf]{IEEEtran}\n\n\\usepackage{hyperref}\n\\usepackage{graphicx}\t% For figure environment\n\\usepackage{amssymb}\n\\usepackage{authblk}\n\\usepackage{color}\n\\usepackage{graphicx}\n\\graphicspath{ {images/} }\n\\usepackage[skip=2pt]{caption} % example skip set to 2pt\n\n\\title{Project 1 on Machine Learning team Yoor}\n\n\\author[1]{Sergei Volodin}\n\\author[1]{Baran Nama}\n\\author[1]{Omar Mehio}\n\\affil[1]{EPFL}\n\\affil[ ]{\\textit {\\{sergei.volodin,baran.nama,omar.mehio\\}@epfl.ch}}\n\n\\begin{document}\n\n\\maketitle\n\n\\begin{abstract}\nA classification dataset from the Large Hadron Collider simulations is being studied. First, the data is thoroughly explored using visual aids.\nAfter that, several basic Machine Learning methods are applied on preprocessed data.\nResults are evaluated using cross-validation.\nModel overview is given for each considered algorithm and the best model is chosen.\n\\end{abstract}\n\n\\section{Introduction}\nThe Higgs boson is a famous elementary particle which was first predicted in 1960s and then discovered in 2012 \\cite{higgs}. Its famousness is due to two facts, first being the collosal amount of effort put into construction of the Large Hadron Collider and conducting the ATLAS experiment and the second being the fact that the Higgs boson is considered to be connected to the fact that particles have a mass.\n\nThe ATLAS experiment consists of protons colliding at near-relative speed. After collision, the resulting particles sometimes contain the Higgs boson. Itself, it is not detectable by LHC. However, it is possible to detect the particles that it is decaying to.\n\nThe data being studied comprises of $N=250 000$ objects (train) each having 30 features: $\\{(x_i,y_i)\\}_{i=1}^N$, $x_i\\in\\mathbb{R}^D$, $D=30$. Each object represents a collision of a stream of protons. The data was not obtained during the ATLAS experiment, but rather from the simulation \\cite{data}. Features represent properties of detected particles. It is required to determine if the particles represent the Higgs boson. The dataset has two classes: signal (+1) and background (-1).\n\nThe following paper claims that it is possible to use simple methods, such as Linear and Logistic Regressions to classify the data. In the following sections, the data is thoroughly studied and then the model is chosen based on reasoning and cross-validation.\n\\section{Models and Methods}\n\\begin{table}[!htb]\n\t\\caption{Feature processing tricks and linear regression}\t\\label{tab:feature_proc}\n\t\\centering\\begin{tabular}{|lc|}\\hline\n\t\t{\\bf Feature trick added} & {\\bf Test accuracy}\\\\\\hline\n\t\tConstant feature & 0.745\\\\\n\t\tStandardization & 0.745\\\\\n\t\tImputation & 0.747\\\\\n\t\tBinarization & 0.747\\\\\n\t\tDegree 3 poly & 0.785\\\\\\hline\n\t\\end{tabular}\n\\end{table}\n\n\\begin{figure}[!htb]\n\t\\centering \\includegraphics[width=100px]{../src/analysis/xy_tr_imp}\n\t\\centering \\includegraphics[width=100px]{../src/analysis/hist_te_imp}\n\t\\centering \\includegraphics[width=100px]{../src/analysis/hist-scatter-tr-imp-0}\n\t\\centering \\includegraphics[width=110px]{../src/analysis/correlation}\n\t\\caption{Exploratory data analysis using charts}\n\t\\label{fig:data}\n\\end{figure}\n\nFirst, the exploratory data analysis shows that most of the features (except one) are real-valued (Figure \\ref{fig:data}, 1-2). Moreover, it can also be seen that the test distribution does not differ from the training one (Figure \\ref{fig:data}, 1-2). Scatter plots (Figure \\ref{fig:data}, 3) show dependencies between features.\nTo further explore linear interactions among our data, we computed the correlation matrix (Figure \\ref{fig:data}, 4).\nSome of the significant dependencies we observed include the relationship among following tuples ({\\tt DER\\_prodeta\\_jet\\_jet}, {\\tt DER\\_mass\\_jet\\_jet})  and ({\\tt PRI\\_jet\\_subleading\\_phi}, {\\tt DER\\_sum\\_pt}).\n\nEach of the respective tuples have a $-1$ and $+1$ correlation coefficient. This implies that for each column in the tuple we can eliminate the other element since we are able to deduce the same amount of knowledge from either one of them. In practice this didn't turn out to be efficient as our prediction with deducted features resulted in lower accuracy. \n\nTo begin with, a simple linear regression model is used on raw data (with a constant feature added), with 5-fold cross-validation to control overfitting. The results of each subsample are averaged to provide train and test accuracy. However, the model gives unsatisfying results on the hold-out dataset. As a means to deal with this issue, feature imputation and engineering is used: missing features are imputed with mean values (and ``missing value'' column is added), categorical features are binarized. Moreover, it has been discovered that some of the features represent particle's mass, momentum or energy. Using the fact that squaring these quantities would make linear combinations of them meaningful in terms of physics ($E^2=m^2+p^2$), we introduce the polynomial basis starting from the degree of 2. Table \\ref{tab:feature_proc} shows the respective effects of these tricks.\n\n\\begin{figure}[!htb]\n\t\\centering \\includegraphics[width=110px]{linear_5}\n\t\\centering \\includegraphics[width=110px]{ridge_accuracy_deg6}\n\t\\caption{Degree 6 basis, MSE and Accuracy metrics}\n\t\\label{fig:deg6}\n\\end{figure}\n\nApplying ridge regression, it might be seen that it does not overfit in terms of accuracy (but does in terms of MSE \\ref{fig:deg6}) on the dataset given even for the 6th degree, meaning that there is no significant difference between the test and the train accuracies. Applying it using different degrees, one obtains results shown in the Table \\ref{tab:degrees}.\n\n\\begin{table}[!htb]\n\t\\caption{Polynomial basis and linear regression, $\\lambda=0$}\t\\label{tab:degrees}\n\t\\centering\\begin{tabular}{|lcccc|}\\hline\n\t\t{\\bf Degree} & {\\bf Test accuracy} & {\\bf MSE Test} & {\\bf MSE Train} & {$\\lambda$ best}\\\\\n\t\t1 & 0.7470 & 0.3378 & 0.3377 & $10^{-6}$\\\\\n\t\t2 & 0.7737 & 0.3483 & 0.3158 & $10^{-2}$\\\\\t\t\n\t\t3 & 0.7850 & 0.3060 & 0.3040 & $10^{-4}$\\\\\n\t\t4 & 0.7937 & 0.3030 & 0.3010 & 0.0004\\\\\n\t\t5 & 0.7971 & 0.3050 & 0.3010 & 0.0006\\\\\\hline\n\t\\end{tabular}\n\\end{table}\n\nMoreover, as can be seen in the figures (Table \\ref{tab:degrees}), while train MSE is continuously decreasing because of over-fitting, there is no significant change in test error after third degree polynomial basis. Therefore, feature extraction using polynomial basis does not seem to work for higher degrees. Furthermore, the accuracy of the model in Kaggle is not as good as what we expected (below 0.8), so that we decided to switch to logistic regression since it uses a loss function tailored for the purpose of classification.\n\nTraining logistic regression with gradient descent on the dataset, we have found out that it is crucial to implement the Newton's method since gradient update rule is taking too much time. This is due to the fact that the final iterations are going with a small step size since setting the step size of gradient descent to a larger value resulted in a numerical overflow.\n\nMoreover, we discovered that the magnitude $\\gamma$ of the gradient step depends on the size of the dataset. Therefore, we tried using batched version of stochastic gradient descent for logistic regression as the optimizer to stabilize the size of the dataset the used for training. However, applying this batched version to the dataset was costly since working with a large matrix in numpy is faster than working with $k$ smaller matrices. Therefore, we used the standard Netwon algorithm and tuned the $\\gamma$ manually for the final model.\n\nThe Figure \\ref{fig:logreg} (1) shows logistic regression accuracy for different regularization parameters $\\lambda$. For this experiment, a constant number of iterations $20$ was chosen. The $\\gamma$ parameter equals $\\gamma=10^{-1}$. The chart indicates that the logistic regression does not overfit. Therefore, we have chosen the first in magnitude value of $\\lambda=2\\times 10^{-4}$ which allowed us to use $\\gamma=0.1$ without numerical overflows in loss. The figure \\ref{fig:logreg} (2) indicates the training schedule. Total number of $N=70$ iterations allowed us to bring the training error to 0. The solution has scored 0.82058 on Kaggle \\cite{kaggle} (first part of test).\n\nDespite the fact that the gradient at the final point was close to $0$ compared to the previous values, the value of the loss did not equal to $0$. Moreover, it can be seen that the train and test errors were similar. These two facts indicate that linear model has a high bias and low variance when applied to this dataset.\n\n\\begin{figure}[!htb]\n\t\\centering \\includegraphics[width=110px]{logistic_lambda_cv_netwon_nobatch}\n\t\\centering \\includegraphics[width=110px]{logistic_01}\n%\t\\centering \\includegraphics[width=200px]{logistic_02}\n\t\n\t\\caption{Degree 5 basis, Logistic regression accuracy}\n\t\\label{fig:logreg}\n\\end{figure}\n\n\\section{Results}\nWe have presented an application of linear, ridge and logistic regression to the dataset. The best model was the logistic one with best accuracy of 0.82 trained with Newton's method. All of the linear models do not overfit on the dataset even when using a polynomial basis.\n\\section{Discussion}\nDespite thorough analysis, our project lacks further consideration in the following directions. First, it can be seen that some of the features do not look like the Gaussian distribution. It might prove beneficial to split such features into two using a certain threshold. Moreover, it might be useful to apply bagging techniques, as well as to use more sophisticated nonlinear classifiers, such as neural networks.\n\\section{Summary}\nWe have shown that it is possible to detect the Higgs boson using linear methods and feature augmentation. Such a simple solution gives fairly good performance and places the team above average on the Kaggle submission. However, this approach is not optimal in terms of model selection, since a linear model seem to not capture all of the specifics of data since it produces high bias.\n\\begin{thebibliography}{99}\n\\bibitem{higgs} \\href{https://en.wikipedia.org/wiki/Higgs\\_boson}{en.wikipedia.org/wiki/Higgs\\_boson}\n\\bibitem{data} \\href{http://higgsml.lal.in2p3.fr/files/2014/04/documentation\\_v1.8.pdf}{Experiment and feature description}\n\\bibitem{kaggle} \\href{http://kaggle.com/c/epfml-higgs}{EPFL ML Project 1}\n\\end{thebibliography}\n\n\\end{document}\n", "meta": {"hexsha": "b925a4980ada09ad98efc6252d9ce12126d02b4e", "size": 10411, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/report.tex", "max_stars_repo_name": "EPFLMachineLearningTeamYoor/Project1", "max_stars_repo_head_hexsha": "a0558be0d1ff39424bcd33184fc4e3f64292f602", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "report/report.tex", "max_issues_repo_name": "EPFLMachineLearningTeamYoor/Project1", "max_issues_repo_head_hexsha": "a0558be0d1ff39424bcd33184fc4e3f64292f602", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/report.tex", "max_forks_repo_name": "EPFLMachineLearningTeamYoor/Project1", "max_forks_repo_head_hexsha": "a0558be0d1ff39424bcd33184fc4e3f64292f602", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 85.3360655738, "max_line_length": 885, "alphanum_fraction": 0.7778311401, "num_tokens": 2642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.34722652274188975}}
{"text": "\\lab{GeoPandas}{GeoPandas}\n\n\n\\objective{GeoPandas is a package designed to organize and manipulate geographic data, It combines the data manipulation tools of pandas with the geometric capabilities of the Shapely package. In this lab, we explore the basic data structures of GeoSeries and GeoDataFrames and their functionalities.}\n\n\n\\section*{Installation} %============================\nGeoPandas is a new package designed to combine the functionality of pandas with Shapely, a package used for geometric manipulation.\nUsing GeoPandas with geographic data is very useful as it allows the user to not only compare numerical data, but also geometric attributes.\nGeoPandas can be installed via \\li{pip}:\n\\begin{lstlisting}\n>>> pip install geopandas\n\\end{lstlisting}\nHowever, Geopandas can be notoriously difficult to install.\n%It is very finicky, which is likely a by-product of it still being in development\nThis is especially the case if the python environment is not carefully maintained.\nSome of its dependencies can also be very difficult to install on certain systems.\nBecause of this, using Colab for this lab is recommended; its environment is set up in a way that makes GeoPandas very easy to install.\nOtherwise, the GeoPandas documentation contains some additional options that can be used if installation difficulties occur: \\url{https://geopandas.org/install.html}.\n\n\\section*{GeoSeries} %============================\n\nA GeoSeries is a pandas Series where each entry is a set of geometric objects.\nThere are three classes of geometric objects inherited from the Shapely package:\n\\begin{enumerate}\n\\item Points / Multi-Points\n\\item Lines / Multi-Lines\n\\item Polygons / Multi-Polygons\n\\end{enumerate}\nA point is used to identify objects like coordinates, where there is one small instance of the object.\nA line could be used to describe objects such as roads.\nA polygon could be used to identify regions, such as a country.\nMultipoints, multilines, and multipolygons contain lists of points, lines, and polygons, respectively.\n\nSince each object in the GeoSeries is also a Shapely object, the GeoSeries inherits many methods and attributes of Shapely objects.\nSome of the key attributes and methods are listed in Table \\ref{shapely-methods}.\nThese attributes and methods can be used to calculate distances, find the sizes of countries, and determine whether coordinates are within country's boundaries.\nThe example below uses the attribute \\li{bounds} to find the maximum and minimum coordinates of Egypt in a built-in GeoDataFrame.\n\n\\begin{table}[ht]\n\\begin{center}\n\\begin{tabular}{c|c}\nMethod/Attribute & Description\\\\\n\\hline\n\\li{distance(other)}&returns minimum distance from GeoSeries to \\li{other}\\\\\n\\li{contains(other)}&returns \\li{True} if shape contains \\li{other}\\\\\n\\li{intersects(other)}&returns \\li{True} if shape intersects \\li{other}\\\\\n\\li{area}&returns shape area\\\\\n\\li{convex_hull}&returns convex shape around all points in the object\\\\\n\\li{bounds} &  returns the bounding x- and y-coordinates of the object\n\\end{tabular}\n\\end{center}\n\\caption{Attributes and Methods for GeoSeries}\n\\label{shapely-methods}\n\\end{table}\n\n\\begin{lstlisting}\n>>> import geopandas as gpd\n>>> world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))\n# Get GeoSeries for Egypt\n>>> egypt = world[world['name']=='Egypt']\n\n# Find bounds of Egypt\n>>> egypt.bounds\n         minx    miny         maxx      maxy\n47   24.70007    22.0     36.86623  31.58568\n\\end{lstlisting}\n\n\\section*{Creating GeoDataFrames} %============================\n\nThe main structure used in GeoPandas is a GeoDataFrame, which is similar to a pandas DataFrame.\nA GeoDataFrame has one special column called \\li{geometry}, which must be a GeoSeries.\nThis GeoSeries column is used when a spatial method, like \\li{distance()}, is used on the GeoDataFrame.\n\nA GeoDataFrame can be made from a pandas DataFrame.\nAt least one of the columns in the DataFrame should contain geometric information.\nThis column containing geometric information can be converted to a GeoSeries using the \\li{apply()} method.\nAt this point, the Pandas DataFrame can be cast as a GeoDataFrame.\nAssign which column will be the \\li{geometry} using either the \\li{geometry} keyword in the constructor or the \\li{set_geometry()} method afterwards.\n\n\\begin{lstlisting}\n>>> import pandas as pd\n>>> import geopandas as gpd\n>>> from shapely.geometry import Point, Polygon\n\n# Create a Pandas DataFrame\n>>> df = pd.DataFrame({'City': ['Seoul', 'Lima', 'Johannesburg'],\n...                   'Country': ['South Korea', 'Peru', 'South Africa'],\n...                   'Latitude': [37.57, -12.05, -26.20],\n...                   'Longitude': [126.98, -77.04, 28.04]})\n\n# Create geometry column\n>>> df['Coordinates'] = list(zip(df.Longitude, df.Latitude))\n\n# Make geometry column Shapely objects\n>>> df['Coordinates'] = df['Coordinates'].apply(Point)\n\n# Cast as GeoDataFrame\n>>> gdf = gpd.GeoDataFrame(df, geometry='Coordinates')\n\n# Equivalently, specify the geometry after construction\n# Note that set_geometry() returns a new GeoDataFrame\n>>> gdf = gpd.GeoDataFrame(df)\n>>> gdf = gdf.set_geometry('Coordinates')\n\n# Display the GeoDataFrame\n>>> gdf\n           City       Country  Latitude  Longitude                  Coordinates\n0         Seoul   South Korea     37.57     126.98   POINT (126.98000 37.57000)\n1          Lima          Peru    -12.05     -77.04  POINT (-77.04000 -12.05000)\n2  Johannesburg  South Africa    -26.20      28.04   POINT (28.04000 -26.20000)\n\n# Create a polygon with all three cities as points\n>>> city_polygon = Polygon(list(zip(df.Longitude, df.Latitude)))\n\\end{lstlisting}\n\nA \\li{GeoDataFrame} can also be made directly from a dictionary.\nIf the dictionary already contains geometric objects, the corresponding column can be directly set as the \\li{geometry} in the constructor.\nOtherwise, a column containing geometry data can be created as in the above example and then set as the \\li{geometry} with the \\li{set_geometry()} method.\n\n\\begin{lstlisting}\n# Both of these methods create the same GeoDataFrame as above\n# Directly create the GeoDataFrame from the dictionary\n>>> gdf = gpd.GeoDataFrame({'City': ['Seoul', 'Lima', 'Johannesburg'],\n...                   'Country': ['South Korea', 'Peru', 'South Africa'],\n...                   'Latitude': [37.57, -12.05, -26.20],\n...                   'Longitude': [126.98, -77.04, 28.04]})\n# Create geometry column and set as the geometry\n>>> gdf['Coordinates'] = list(zip(df.Longitude, df.Latitude))\n>>> gdf['Coordinates'] = df['Coordinates'].apply(Point)\n# inplace=True modifies gdf itself rather than returning a copy\n>>> gdf.set_geometry('Coordinates', inplace=True)\n\n# Equivalently, using a dictionary that already contains geometry objects\n>>> gdf = gpd.GeoDataFrame({'City': ['Seoul', 'Lima', 'Johannesburg'],\n...                   'Country': ['South Korea', 'Peru', 'South Africa'],\n...                   'Coordinates': [Point(126.98,37.57),\n...                       Point(-77.04,-12.05), Point(28.04,-12.05)]},\n...                   geometry='Coordinates')\n\\end{lstlisting}\n\n\\begin{info}\nLongitude is the angular measurement starting at the Prime Meridian, $0\\degree$, and going to $180\\degree$ to the east and $-180\\degree$ to the west.\nLatitude is the angle between the equatorial plane and the normal line at a given point; a point along the Equator has latitude $0$, the North Pole has latitude $+90\\degree$ or $90\\degree N$, and the South Pole has latitude $-90\\degree$ or $90\\degree S$.\n\\end{info}\n\n\\section*{Plotting GeoDataFrames} %============================\n\nInformation from a GeoDataFrame is plotted based on the geometry column.\nData points are displayed as geometry objects.\nThe following example plots the shapes in the \\li{world} GeoDataFrame.\n\n\\begin{lstlisting}\n# Plot world GeoDataFrame\n>>> world.plot()\n\\end{lstlisting}\n\n\\begin{figure}[H]\n\\begin{center}\n\\includegraphics[scale=.55]{figures/worldmap.pdf}\n\\end{center}\n\\label{world-map}\n\\caption{World map}\n\\end{figure}\n\nMultiple GeoDataFrames can be plotted at once.\nThis can be done by by setting one GeoDataFrame as the base of the plot and ensuring that each layer uses the same axes.\nIn the following example, the file \\li{airports.csv}, containing the coordinates of world airports, is loaded into a GeoDataFrame and plotted on top of the boundary of the \\li{world} GeoDataFrame.\n\n\\begin{lstlisting}\n# Set outline of world countries as base\n>>> fig,ax = plt.subplots(figsize=(10,7), ncols=1, nrows=1)\n>>> base = world.boundary.plot(edgecolor='black', ax=ax, linewidth=1)\n\n# Load airport data and convert to a GeoDataFrame\n>>> airports = pd.read_csv('airports.csv')\n>>> airports['Coordinates'] = list(zip(airports.Longitude, airports.Latitude))\n>>> airports['Coordinates'] = airports.Coordinates.apply(Point)\n>>> airports = gpd.GeoDataFrame(airports, geometry='Coordinates')\n\n# Plot airports on top of world map\n>>> airports.plot(ax=base, marker='o', color='green', markersize=1)\n>>> ax.set_xlabel('Longitude')\n>>> ax.set_ylabel('Latitude')\n>>> ax.set_title('World Airports')\n\\end{lstlisting}\n\n\\begin{figure}[H]\n\\begin{center}\n\\includegraphics[scale=.6]{figures/airports.pdf}\n\\end{center}\n\\label{airport-map}\n\\caption{Airport map}\n\\end{figure}\n\n\\begin{problem}\nRead in the file \\li{airports.csv} as a pandas DataFrame.\nCreate three convex hulls around the three sets of airports listed below.\nThis can be done by passing in lists of the airports' coordinates to a \\li{shapely.geometry.Polygon} object.\n\nCreate a new GeoDataFrame with these three Polygons as entries.\nPlot this GeoDataFrame on top of an outlined world map.\n\\begin{itemize} %These could also be listed by 4-character ICAO codes, but listing the names makes the problem more exciting/realistic. Probably.\n\t\\item Maio Airport, Scatsta Airport, Stokmarknes Skagen Airport, Bekily Airport, K. D. Matanzima Airport, RAF Ascension Island\n\t\\item Oiapoque Airport, Maio Airport, Zhezkazgan Airport, Walton Airport, RAF Ascension Island, Usiminas Airport, Piloto Osvaldo Marques Dias Airport\n\t\\item Zhezkazgan Airport, Khanty Mansiysk Airport, Novy Urengoy Airport, Kalay Airport, Biju Patnaik Airport, Walton Airport\n\\end{itemize}\n\\end{problem}\n\n\\section*{Working with GeoDataFrames} %============================\n\nAs previously mentioned, GeoDataFrames contain many of the functionalities of pandas DataFrames.\nFor example, to create a new column, define a new column name in the GeoDataFrame with the needed information for each GeoSeries.\n\n\\begin{lstlisting}\n# Create column in the world GeoDataFrame for gdp_per_capita\n>>> world['gdp_per_cap'] = world.gdp_md_est / world.pop_est\n\\end{lstlisting}\n\nGeoDataFrames can utilize many pandas functionalities, and they can also be parsed by geometric manipulations.\nFor example, a useful way to index GeoDataFrames is with the \\li{cx} indexer.\nThis splits the GeoDataFrame by the coordinates of each geometric object.\nIt is used by calling the method \\li{cx} on a GeoDataFrame, followed by a slicing argument, where the first element refers to the longitude and the second refers to latitude.\n\n\\begin{lstlisting}\n# Create a GeoDataFrame containing the northern hemisphere\n>>> north = world.cx[:, 0:]\n\n# Create a GeoDataFrame containing the southeastern hemisphere\n>>> south_east = world.cx[0:, :0]\n\\end{lstlisting}\n\nGeoSeries objects in a GeoDataFrame can also be dissolved, or merged, together into one GeoSeries based on their geometry data.\nFor example, all countries on one continent could be merged to create a GeoSeries containing the information of that continent.\nThe method designed for this is called \\li{dissolve}.\nIt receives two parameters, \\li{by} and \\li{aggfunc}.\n\\li{by} indicates which column to dissolve along, and \\li{aggfunc} tells how to combine the information in all other columns.\nThe default \\li{aggfunc} is \\li{first}, which returns the first application entry.\nIn the following example, we use \\li{sum} as the \\li{aggfunc} so that each continent is the combination of its countries.\n\n\\begin{lstlisting}\n>>> world = world[['continent', 'geometry', 'gdp_per_cap']]\n\n# Dissolve world GeoDataFrame by continent\n>>> continent = world.dissolve(by = 'continent', aggfunc='sum')\n\\end{lstlisting}\n\n\n\\section*{Projections and Coloring} %============================\n\nWhen plotting, GeoPandas uses the CRS (coordinate reference system) of a GeoDataFrame.\nThis reference system indicates how coordinates should be spaced on a plot.\nTwo of the most commonly used CRSs are EPSG:4326 and EPSG:3395.\nEPSG:4326 is the standard latitude-longitude projection used by GPS.\nEPSG:3395, also known as the Mercator projection, is the standard navigational projection.\n\nWhen creating a new GeoDataFrame, it is important to set the \\li{crs} attribute of the GeoDataFrame.\nThis allows any plots to be shown correctly.\nFurthermore, GeoDataFrames being layered need to have the same CRS.\nTo change the CRS, use the method \\li{to_crs()}.\n\n\\begin{lstlisting}\n# Check CRS of world GeoDataFrame\n>>> print(world.crs)\nepsg:4326\n\n# Change CRS of world to Mercator\n# inplace=True ensures that we modify world instead of returning a copy\n>>> world.to_crs(3395, inplace=True)\n>>> print(world.crs)\nepsg:3395\n\\end{lstlisting}\n\nGeoPandas accepts many different CRSs; a reference can be found at \\url{www.spatialreference.org}.\n% I think this is helpful information, but I'm not sure\nAdditionally, inspecting a given CRS object in the terminal without using \\li{print()} or \\li{str()} can be used to get additional information about a specific CRS:\\footnote{This can also be accomplished using \\li{print(repr(crs))}.}\n\\begin{lstlisting}[mathescape]\n>>> world.crs\n<Projected CRS: EPSG:3395>\nName: WGS 84 / World Mercator\nAxis Info [cartesian]:\n- E[east]: Easting (metre)\n- N[north]: Northing (metre)\nArea of Use:\n- name: World between 80$^\\circ$S and 84$^\\circ$N.\n- bounds: (-180.0, -80.0, 180.0, 84.0)\nCoordinate Operation:\n- name: World Mercator\n- method: Mercator (variant A)\nDatum: World Geodetic System 1984\n- Ellipsoid: WGS 84\n- Prime Meridian: Greenwich\n\\end{lstlisting}\n\nGeoDataFrames can also be plotted using the values in the the other attributes of the GeoSeries.\nThe map plots the color of each geometry object according to the value of the column selected.\nThis is done by passing in the parameter \\li{column} into the \\li{plot()} method.\n\n\\begin{lstlisting}\n>>> fig, ax = plt.subplots(1, figsize=(10,4))\n# Plot world based on gdp\n>>> world.plot(column='gdp_md_est', cmap='OrRd', legend=True,  ax=ax)\n>>> ax.set_title('World Map based on GDP')\n>>> ax.set_xlabel('Longitude')\n>>> ax.set_ylabel('Latitude')\n>>> plt.show()\n\\end{lstlisting}\n\n\\begin{figure}[H]\n\\begin{center}\n\\includegraphics[scale=.7]{figures/gdp.pdf}\n\\end{center}\n\\caption{World Map Based on GDP}\n\\label{figure:gdp_map}\n\\end{figure}\n\n\n\\begin{problem}\nThe file \\li{county_data.gpkg.zip} contains information about US counties.\\footnote{Source: \\url{http://www2.census.gov/geo/tiger/GENZ2016/shp/cb_2016_us_county_5m.zip}}\nAfter unzipping, use the command \\li{gpd.read_file('county_data.gpkg')} to create a GeoDataFrame of this information.\nEach county's shape is stored in the \\li{geometry} column.\nUse this to plot all US counties two times, first using the default CRS and then using EPSG:5071.\n\nNext, create a new GeoDataFrame that merges all counties within a single state.\nDrop regions with the following STATEFP codes: 02, 15, 60, 66, 69, 72, 78.\nPlot this GeoDataFrame to see an outline of all 48 contiguous states.\nEnsure a CRS  of EPSG:5071.\n\\label{problem:us_counties}\n\\end{problem}\n\\begin{info}\n\\li{.gpkg} files are actually structured as a directory that contains several files that each contain parts of the data.\nFor instance, \\li{county_data.gpkg} consists of the files \\li{county_data.cpg}, \\li{county_data.dbf}, \\li{county_data.prj}, \\li{county_data.shp}, and \\li{county_data.shx}.\nBe sure that these files are placed directly in the first level of folders, and not in further subdirectories.\\\\\nTo use this file in Google Colab, upload the zipped file and extract it with the following code:\n\\begin{lstlisting}\ncounty = files.upload()\n!unzip county_data.gpkg.zip\n\\end{lstlisting}\nIt then can be loaded:\n\\begin{lstlisting}\ncounty_df = gpd.read_file('county_data.gpkg')\n\\end{lstlisting}\n\\end{info}\n\n\\section*{Merging GeoDataFrames} %============================\n\nJust as multiple pandas DataFrames can be merged, multiple GeoDataFrames can be merged with attribute joins or spatial joins.\nAn attribute join is similar to a merge in pandas.\nIt combines two GeoDataFrames on a column (not the geometry column) and then combines the rest of the data into one GeoDataFrame.\n\n\\begin{lstlisting}\n>>> world = gpd.read_file(geopandas.datasets.get_path('naturalearth_lowres'))\n>>> cities = gpd.read_file(geopandas.datasets.get_path('naturalearth_cities'))\n\n# Create subsets of the world and cities GeoDataFrames\n>>> world = world[['continent', 'name', 'iso_a3']]\n>>> cities = cities[['name', 'iso_a3']]\n\n# Merge the GeoDataFrames on their iso_a3 code\n>>> countries = world.merge(cities, on='iso_a3')\n\\end{lstlisting}\n\nA spatial join merges two GeoDataFrames based on their geometry data.\nThe function used for this is \\li{sjoin}.\n\\li{sjoin} accepts two GeoDataFrames and then direction on how to merge.\nIt is imperative that two GeoDataFrames have the same CRS.\nIn the example below, we merge using an \\li{inner} join with the option \\li{intersects}.\nThe \\li{inner} join means that we will only use keys in the intersection of both geometry columns, and we will retain only the left geometry column.\n\\li{intersects} tells the GeoDataFrames to merge on GeoSeries that intersect each other.\nOther options include \\li{contains} and \\li{within}.\n\n\\begin{lstlisting}\n# Combine countries and cities on their geographic location\n>>> countries = gpd.sjoin(world, cities, how='inner', op='intersects')\n\\end{lstlisting}\n\n\\begin{problem}\nLoad in the file \\li{nytimes.csv}\\footnote{Source: \\url{https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv}} as a DataFrame.\nThis file includes county-level data for the cumulative cases and deaths of Covid-19 in the US, starting with the first case in Snohomish County, Washington, on January 21, 2020.\nBegin by converting the \\li{date} column into a \\li{DatetimeIndex}.\n\nNext, use county FIPS codes to merge your GeoDataFrame from Problem \\ref{problem:us_counties} with the DataFrame you just created.\nA FIPS code is a 5-digit unique identifier for geographic locations.\nIgnore rows in the Covid-19 DataFrame with unknown FIPS codes as well as all data from Hawaii and Alaska.\n\nNote that the \\li{fips} column of the Covid-19 DataFrame stores entries as floats, but the county GeoDataFrame stores FIPS codes as strings, with the first two digits in the \\li{STATEFP} column and the last three in the \\li{COUNTYFP} column.\n\nOnce you have completed the merge, plot the cases from March 21, 2020 on top of your state outline map from Problem \\ref{problem:us_counties}, using the CRS of EPSG:5071.\nFinally, print out the name of the county with the most cases on March 21, 2020 along with its case count.\n\\label{problem:merge_covid}\n\\end{problem}\n\n\\section*{Logarithmic Plotting Techniques} %============================\n\nThe color scheme of a graph can also help to communicate information clearly.\nA good list of available colormaps can be found at \\url{https://matplotlib.org/3.2.1/gallery/color/colormap_reference.html}.\nNote also that you can reverse any colormap by adding \\li{_r} to the end.\nThe following example demonstrates some plotting features, using country GDP as in Figure \\ref{figure:gdp_map}.\n\n\\begin{lstlisting}\n>>> fig, ax = plt.subplots(figsize=(15,7), ncols=1, nrows=1)\n>>> world.plot(column='gdp_md_est', cmap='plasma_r',\n...\t\t\tax=ax, legend=True, edgecolor='gray')\n\n# Add title and remove axis tick marks\n>>> ax.set_title('GDP on Linear Scale')\n>>> ax.set_yticks([])\n>>> ax.set_xticks([])\n>>> plt.show()\n\\end{lstlisting}\n\n\\begin{figure}[H]\n\\begin{center}\n\\includegraphics[scale=.75]{figures/world_linear.pdf}\n\\end{center}\n\\caption{World map showing country GDP}\n\\label{figure:linear_world}\n\\end{figure}\n\nSometimes data can be much more informative when plotted on a logarithmic scale.\nSee how the world map changes when we add a \\li{norm} argument in the code below.\nDepending on the purpose of the graph, Figure \\ref{figure:log_world} may be more informative than Figure \\ref{figure:linear_world}.\n\n\\begin{lstlisting}\n>>> from matplotlib.colors import LogNorm\n>>> from matplotlib.cm import ScalarMappable\n>>> fig, ax = plt.subplots(figsize=(15,6), ncols=1, nrows=1)\n\n# Set the norm using data bounds\n>>> data = world.gdp_md_est\n>>> norm = LogNorm(vmin=min(data), vmax=max(data))\n\n# Plot the graph using the norm\n>>> world.plot(column='gdp_md_est', cmap='plasma_r', ax=ax,\n...\t\t\tedgecolor='gray', norm=norm)\n\n# Create a custom colorbar\n>>> cbar = fig.colorbar(ScalarMappable(norm=norm, cmap='plasma_r'),\n...\t\t\tax=ax, orientation='horizontal', pad=0, label='GDP')\n\n>>> ax.set_title('Country Area on a Log Scale')\n>>> ax.set_yticks([])\n>>> ax.set_xticks([])\n>>> plt.show()\n\\end{lstlisting}\n\n\\begin{figure}[H]\n\\begin{center}\n\\includegraphics[scale=.65]{figures/world_log.pdf}\n\\end{center}\n\\caption{World map showing country GDP using a log scale}\n\\label{figure:log_world}\n\\end{figure}\n\n\\begin{problem}\nAs in Problem \\ref{problem:merge_covid}, plot your state outline map from Problem \\ref{problem:us_counties} on top of a map of the Covid-19 cases from March 21, 2020.\nThis time, however, use a log scale.\nUse EPSG:5071 for the CRS.\nPick a good colormap (the counties with the most cases should generally be darkest) and be sure to display a colorbar.\n\\end{problem}\n\n\\begin{problem}\nIn this problem, you will create an animation of the spread of Covid-19 through US counties from January 21, 2020 to June 21, 2020.\nUse a log scale and a good colormap, and be sure that you're using the same norm and colorbar for the whole animation.\nUse EPSG:5071 for the projection.\n\nAs a reminder, below is a summary of what you will need in order to animate this map.\nYou may also find it helpful to refer to the animation section included with the Volume 4 lab manual.\n\n%------------------------------------------- Is that ok to say?\n\\begin{enumerate}\n\t\\item Set up your figure and norm. Be sure to use the highest case count for your \\li{vmax} so that the scale remains uniform.\n\t\\item Write your \\li{update} function. This should plot the cases from a given day.\n\t\\item Set up your colorbar. Do this outside the \\li{update} function to avoid adding a new colorbar each day.\n\t\\item Create the animation and embed it.\n\\end{enumerate}\n\\end{problem}\n", "meta": {"hexsha": "3394f2b3103f71caf8365c937e7e1d756387ba24", "size": 22669, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "DataScienceEssentials/Pandas4/Pandas4.tex", "max_stars_repo_name": "chrismmuir/Labs-1", "max_stars_repo_head_hexsha": "13c23611b90d73b0c2c7d275bce9808f829009f2", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 190, "max_stars_repo_stars_event_min_datetime": "2015-07-17T01:57:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T19:16:19.000Z", "max_issues_repo_path": "DataScienceEssentials/Pandas4/Pandas4.tex", "max_issues_repo_name": "chrismmuir/Labs-1", "max_issues_repo_head_hexsha": "13c23611b90d73b0c2c7d275bce9808f829009f2", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": 184, "max_issues_repo_issues_event_min_datetime": "2015-07-16T17:56:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-06T23:47:14.000Z", "max_forks_repo_path": "DataScienceEssentials/Pandas4/Pandas4.tex", "max_forks_repo_name": "chrismmuir/Labs-1", "max_forks_repo_head_hexsha": "13c23611b90d73b0c2c7d275bce9808f829009f2", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 76, "max_forks_repo_forks_event_min_datetime": "2015-08-06T02:53:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-27T11:08:57.000Z", "avg_line_length": 47.4246861925, "max_line_length": 301, "alphanum_fraction": 0.7432617231, "num_tokens": 5739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.34719444064477467}}
{"text": "%!TEX root = thesis-kdyoung.tex\n\n\\chapter{Computational Experiments}\n\\label{chap:exp}\n\nAll experiments were run on a personal computer with\nan Intel i5 5575R CPU (four cores each with 2.8GHz clock speed) and 16GB of main memory.\nThe scripts for the MIPs and the primary script used \nto iterate through the Benders\ndecomposition algorithm was written in Python 3.4.\nWe employed Gurobi 7.0.2 as the solver\nused for all MIP formulations.\nAs mentioned previously, \\chuffed was the solver\nwe chose to solve all constraint programs with.\nMiniZinc version 2.1.2 was used to compile the models\ninto the \\chuffed FlatZinc format.\nUnless stated otherwise, all tests were run\nwith a time limit of 30 minutes (1800 seconds).\n\nWe chose to only test \\fsbf{2} and \\scbf{2} for the\ncomputational experiments of the previous work.\nThis is a result of our encoding of the \\ssbf{2} model\nreturning infeasible solutions in our preliminary tests.\nDue to time constraints we were unable to discern whether\nthe problem was our encoding of the model\nor if the \\ssbf{2} is ill-formed.\n\nWe now provide a brief outline of the computational\nresults reported in this chapter.\nFirst a description of the data used for testing\nis given in Section \\ref{sec:exp:data}.\nAs the MIPs presented in \\authciteb{Esmaeilbeigi2016}\nhave been untested, we investigate the best combination\nof valid inequalities to include for these models\nin Section \\ref{sec:exp:mip}.\nIn Section \\ref{sec:exp:cuts} we report on the best combination\nof Benders cuts to use for our decomposition.\nWe provide a detailed investigation into the best configuration\nof the CP sub-problem in Section \\ref{sec:exp:cp}.\nOnce the superior sub-problem formulation is determined, \nwe close in Section \\ref{sec:exp:benchmarkExp} of\nthis chapter by reporting on the results of our best\nsolution methodology on a set of benchmark instances.\n\n\\section{Data}\n\\label{sec:exp:data}\nThe primary dataset available for the \\sua{} is\nthe SBF generated by \\citeauthor{Scholl2013}\nHowever, this dataset was created for the type-1 case in\nparticular and so is not immediately applicable to\nthe \\sua{2}.\nThe SBF is divided into two halves, the SBF1 and SBF2, \nwhere each half consists of a total of 1076 instances.\nWe first provide a brief explanation of how SBF1\nwas generated.\n\nThe basis of the SBF1 are a set of 269 instances\nfor the \\sab{1} containing between 4 and 297 tasks.\nWhen creating instances for the \\sua{1}, the cycle time,\ntask times and precedence relations are all transferred from\nthe original instances.\nWe also require values of the forward and backward setup times \\ap \nso to create these the authors consider the average processing\ntime among all tasks, denoted $t_{av}$.\nIn practice the setup times are smaller than the execution time\nof a task, so a parameter $\\alpha$ is used when randomly generating\nthe setups.\nAn upper bound on the possible setup is defined as $\\alpha\\cdot t_{av}$\nwhere $\\alpha\\in\\{\\:0.25,\\:0.50,\\:0.75,\\:1.00\\:\\}$.\nFor example, when $\\alpha=1.00$, the largest possible setup time\nis 50\\% of the average task time.\nThe 269 input instances are duplicated for each $\\alpha$ value\nand so 1076 instances of \\sua{1} are generated for SBF1.\n\nThe SBF2 was generated in almost exactly the same way as SBF1.\nHowever in this case,\ncare was taken when randomly generating the setup times to ensure\nthat at least one optimal solution to the original \\sab{1} instance\nis still feasible in the new \\sua{1} instance.\nThis solution will necessarily be the optimal solution\nof the \\sua{2} as noted by \\citeauthor{Scholl2013}\nWhen storing the instance data, the authors also recorded the\noptimal number of stations for the original \\sab{1} instance.\n\nThe data we chose to run all our tests on was adapted from the SBF2\ndataset.\nAs the optimal solutions were recorded,\nwe could take the optimal number of stations as input\nand then solve for the cycle time.\nThis simple change allowed 1076 instances for testing our formulations.\n\\authciteb{Esmaeilbeigi2016} considered a subset of the SBF2 instances\nwhich they divided into 3 classes.\nWe considered the same subset of instances for the type-2 problem\nwhich are detailed in Table \\ref{tab:exp:dataSBF2}.\nIn this table we give the number of tasks, stations, precedence\nrelations and order strength of the precedence graph.\nIn total 396 instances were considered in our tests.\n\nThe order strength of an instance is a measure of its complexity\nwhere higher values correspond to more difficult instances.\nHowever, we note that in the extreme, when $OS=1$, there is only one \nprecedence-feasible task sequence and thus the problem becomes trivial.\n\n\\begin{table}[tpb]\n\t\\centering\n\t\\caption{Dataset summary}\n\t\\vspace{2mm}\n\t\\begin{tabular}{llrrrrr}\n\t\t\\toprule\n\t\tClass & Creator & \\#Inst. & $n$ & $m$ & $|E|$ & Order Strength $(OS)$ \\\\\n\t\t\\midrule\\midrule\n\t\t1 &  & 108 & 7-21 & 2-8 & 6-27 & \\\\[1mm]\n\t\t & {\\tt mertens}  & 6 & 7 & 2-6 & 6 & medium (52.40)\\\\\n\t\t  & {\\tt bowman8}  & 1 & 8 & 5 & 8 & high (75.00)\\\\\n\t\t  & {\\tt jaeschke} & 5 & 9 & 3-8 & 11 & high (83.33)\\\\\n\t\t  & {\\tt jackson}  & 6 & 11 & 3-8 & 13 & medium (58.18)\\\\\n\t\t  & {\\tt mansoor}  & 3 & 11 & 2-4 & 11 & medium (60.00)\\\\\n\t\t  & {\\tt mitchell} & 6 & 21 & 3-8 & 27 & high (70.95)\\\\\\midrule\n\t\t2 &  & 112 & 25-30 & 3-14 & 32-40 & \\\\[1mm]\n\t\t  & {\\tt roszieg} & 6 & 25 & 4-10 & 32 & high (71.67)\\\\\n\t\t  & {\\tt heskia}   & 6 & 28 & 3-8 & 40 & low (22.49)\\\\\n\t\t  & {\\tt buxey}    & 7 & 29 & 7-13 & 36 & medium (50.74)\\\\\n\t\t  & {\\tt sawyer30} & 9 & 30 & 5-14 & 32 & low (44.83)\\\\\\midrule\n\t\t3 &  & 176 & 32-58 & 3-31 & 38-82 & \\\\[1mm]\n\t\t  & {\\tt lutz1}   & 6 & 32 & 6-11 & 38 & high (83.47)\\\\\n\t\t  & {\\tt gunther}  & 7 & 35 & 7-14 & 43 & medium (59.50)\\\\\n\t\t  & {\\tt kilbrid}  & 10 & 45 & 3-10 & 62 & low (44.60)\\\\\n\t\t  & {\\tt hahn}     & 5 & 53 & 4-8 & 82 & high (83.82)\\\\\n\t\t  & {\\tt warnecke} & 16 & 58 & 14-31 & 70 & medium (59.10)\\\\\\midrule\n\t\tOverall & & 396 & 7-58 & 2-31 & 6-82 & \\\\\n\t\t\\bottomrule\n\t\\end{tabular}\n\t\\label{tab:exp:dataSBF2}\n\\end{table}\n\n% \\section{Preliminary Tests}\n% \\label{sec:exp:prelim}\n\n\\section{MIP Formulations}\n\\label{sec:exp:mip}\nWe first report on how the MIP formulations presented\nin Chapter \\ref{chap:mip} performed.\nIn Table \\ref{tab:exp:resultsFSBF} and \\ref{tab:exp:resultsSCBF} we give the results\nof \\fsbf{2} and \\scbf{2} respectively.\nEach is tested on each combination of the valid inequalities from\nSection \\ref{sec:mip:validIneqs} against\nall 3 classes of the subset\nof instances from SBF2.\nThe following datapoints are summarized for each test:\nthe number of nodes explored by \\gurobi's \\bab tree,\nthe average gap for all instances,\nthe number of instances where no feasible solution was found,\nthe fraction of instances found to optimality out of the whole class,\nthe percentage of optimal instances and finally\nthe average runtime taken by \\gurobi.\n\n\\begin{table}[tpb]\n\t\\caption{FSBF-2 formulations tested on classes 1,2 and 3}\n\t\\centering\n\t\\vspace{2mm}\n\t\\begin{tabular}{clrrrrrr}\n\t\t\\toprule\n\t\tClass & Ineqs. & \\#Nodes & \\%Gap & \\#No.s. & \\#Opt. & \\%Opt. & Rt.(s) \\\\\\midrule\\midrule\n\t\t1 & -- & 40,181 & 0.56 & 0 & 98/108 & 90.74 & 172.90 \\\\\n\t\t & (\\ref{eq:mip:valIneq1}) & 43,437 & 0.16 & 0 & \\bf{101}/108 & 93.52 & 166.57 \\\\\n\t\t & (\\ref{eq:mip:valIneq3}) & 50,987 & 1.14 & 0 & 84/108 & 77.78 & 628.47 \\\\\n\t\t & (\\ref{eq:mip:valIneq1}),(\\ref{eq:mip:valIneq3}) & 51,734 & 1.12 & 0 & 85/108 & 78.73 & 645.02 \\\\\\midrule\n\t\t2 & -- & 171,847 & 14.81 & 0 & 0/112 & 0.00 & 1801.08 \\\\\n\t\t & (\\ref{eq:mip:valIneq1}) & 168,899 & 13.76 & 0 & 0/112 & 0.00 & 1800.66 \\\\\n\t\t & (\\ref{eq:mip:valIneq3}) & 205,752 & 18.04 & 0 & 0/112 & 0.00 & 1801.52 \\\\\n\t\t & (\\ref{eq:mip:valIneq1}),(\\ref{eq:mip:valIneq3}) & 202,980 & 17.90 & 0 & 0/112 & 0.00 & 1801.27 \\\\\\midrule\n\t\t3 & -- & 48,927 & 19.75 & 9 & 7/176 & 3.98 & 1763.45 \\\\\n\t\t & (\\ref{eq:mip:valIneq1}) & 46,060 & 19.56 & 9 & 7/176 & 3.98 & 1759.67 \\\\\n\t\t & (\\ref{eq:mip:valIneq3}) & 62,845 & 25.64 & 16 & 0/176 & 0.00 & 1800.23 \\\\\n\t\t & (\\ref{eq:mip:valIneq1}),(\\ref{eq:mip:valIneq3}) & 63,002 & 24.72 & 15 & 0/176 & 0.00 & 1801.12 \\\\\n\t\t\\bottomrule\n\t\\end{tabular}\n\t\\label{tab:exp:resultsFSBF}\n\\end{table}\n\n\\begin{table}[tpb]\n\t\\caption{SCBF-2 formulations tested on classes 1,2 and 3}\n\t\\centering\n\t\\vspace{2mm}\n\t\\begin{tabular}{clrrrrrr}\n\t\t\\toprule\n\t\tClass & Ineqs. & \\#Nodes & \\%Gap & \\#No.s. & \\#Opt. & \\%Opt. & Rt.(s) \\\\\\midrule\\midrule\n\t\t1 & -- & 221,842 & 1.62 & 0 & \\bf{92}/108 & 86.11 & 374.88 \\\\\n\t\t & (\\ref{eq:mip:valIneq1}) & 244,811 & 1.97 & 0 & 84/108 & 77.78 & 403.17 \\\\\n\t\t & (\\ref{eq:mip:valIneq3}) & 238,515 & 1.75 & 0 & 86/108 & 76.93 & 377.05  \\\\\n\t\t & (\\ref{eq:mip:valIneq1}),(\\ref{eq:mip:valIneq3}) & 215,866 & 1.75 & 0 & 86/108 & 76.93 & 380.82  \\\\\\midrule\n\t\t2 & -- & 651,880 & 18.01 & 28 & 0/112 & 0.00 & 1800.33 \\\\\n\t\t & (\\ref{eq:mip:valIneq1}) & 701,617 & 19.75 & 31 & 0/112 & 0.00 & 1800.47 \\\\\n\t\t & (\\ref{eq:mip:valIneq3}) & 686,566 & 18.98 & 30 & 0/112 & 0.00 & 1801.03 \\\\\n\t\t & (\\ref{eq:mip:valIneq1}),(\\ref{eq:mip:valIneq3}) & 612,442 & 18.57 & 31 & 0/112 & 0.00 & 1800.99 \\\\\\midrule\n\t\t3 & -- & 301,055 & 10.09 & 109 & 0/176 & 0.00 & 1800.88 \\\\\n\t\t & (\\ref{eq:mip:valIneq1}) & 326,284 & 12.20 & 117 & 0/176 & 0.00 & 1801.00 \\\\\n\t\t & (\\ref{eq:mip:valIneq3}) & 324,878 & 12.15 & 112 & 0/176 & 0.00 & 1801.21 \\\\\n\t\t & (\\ref{eq:mip:valIneq1}),(\\ref{eq:mip:valIneq3}) & 319,908 & 12.06 & 117 & 0/176 & 0.00 & 1801.01 \\\\\n\t\t\\bottomrule\n\t\\end{tabular}\n\t\\label{tab:exp:resultsSCBF}\n\\end{table}\n\nBy inspecting the data we find that using the \nvalid inequality (\\ref{eq:mip:valIneq1})\nwithout (\\ref{eq:mip:valIneq3}) is the best \nformulation of \\fsbf{2}.\nAs for \\scbf{2}, we found that the best formulation\nwas when neither of the two valid inequalities were included in\nthe program.\n\nFor both the MIPs, optimality was proven for almost none of the instances of\nclass 2 and 3.\nAs a result, all the average runtime values are close\nto the time limit of 30 minutes.\nIn the case of \\scbf{2}, no feasible solution was found for 66.5\\% of the instances\nin class 3.\nEven for the smallest class of data, where there is no more\nthan 21 tasks, neither MIP was able to prove\noptimality for all instances.\nWe note that when calculating the gap value, we only average\nthe instances where a feasible solution was found.\nWith a 30 minute time limit, both MIPs could not achieve\nan average gap value less than 10\\% for class 2 and 3.\n\nHere we tested the full mixed-integer programming approach\non the smallest subset of instances of the SBF2.\nThe poor results we have found make it clear that these programs\nare unsatisfactory exact solution methods for tackling\nthe \\sua{2}.\n\n\\section{Cuts}\n\\label{sec:exp:cuts}\nThe cutting strategy used in the iteration of the Benders\nalgorithm can have a large impact on its overall performance.\nEven when either the master or sub-problem is exceptionally\ndifficult to solve, if the Benders cuts added to the master\nallow us to find optimality in very few iterations then the problem\ncan still be tractable.\n\n\\subsection{Nogood Cuts}\n\\label{sec:exp:NGcuts}\nIn the preliminary testing phase, we considered feasibility sub-problems\nusing the nogood cuts presented in Section \\ref{sec:bend:NGcuts} of the \nprevious chapter.\nThese results are briefly summarized in Table \\ref{tab:exp:resultsNGcut}.\nEven on the smallest class 1, the Benders\nalgorithm failed to prove optimality for 66 of the instances tested.\nDue to this, we felt that further investigation into the use\nof nogood cuts was not the most fruitful research direction. \nNote that we did not make use of the possible parallel computing capabilities\ndetailed earlier in Section \\ref{sec:bend:SPfeas},\nwhere the feasibility sub-problems could be run concurrently.\nThis potential avenue was not explored as the percentage of computation\ntime spent solving the sub-problems was dwarfed by the time spent solving\nthe master problem; as we will see in the coming results.\n\nFor all remaining experiments optimality sub-problems were used\nunless stated otherwise.\n\n\\begin{table}[tpb]\n\t\\caption{Benders algorithm tested on class 1 with nogood cuts}\n\t\\centering\n\t\\vspace{2mm}\n\t\\begin{tabular}{ccrrrr}\n\t\t\\toprule\n\t\tCuts & Class & \\#No sol. & \\#Opt. & \\%Opt. & Runtime(s) \\\\\\midrule\\midrule\n\t\t$\\mathcal{C}_{ng}$ & 1 & 66 & 42/108 & 38.89 & 1456.57 \\\\\n\t\t\\bottomrule\n\t\\end{tabular}\n\t\\label{tab:exp:resultsNGcut}\n\\end{table}\n\n\\subsection{Cutting Procedure}\n\\label{sec:exp:cuttngProcedure}\nIn Tables \\ref{tab:exp:resultsCutsClass1} and \\ref{tab:exp:resultsCutsClass2}\nwe provide the primary comparison of the possible cutting strategies\nthat we considered.\nThe first table compares the 9 possible cut combinations on the smallest\nclass of data (class 1).\nThe variation in the results of Table \\ref{tab:exp:resultsCutsClass1},\nmakes it difficult to discern a\nclear best cutting procedure.\nSo we further tested 6 cut combinations\non class 2 in the Table \\ref{tab:exp:resultsCutsClass2}.\nThe choice of solving technology for the sub-problems \nwill only effect the time taken to solve all scheduling problems\nbut not the cutting procedure.\nThus we arbitrarily chose to test all combinations of cuts using MIP\nsub-problems.\n\nThe two tables comparing the cut combinations contain\nthe following data:\naverage number of nodes explored by \\gurobi's\n\\bab tree (total combined between the \\rmp{} and sub-problems),\naverage number iterations of the Benders algorithm,\naverage number of cuts generated,\naverage Benders gap,\ntotal number of instances where no feasible solution was found,\npercentage of the instances proved optimal and\nthe average runtime of all instances.\n\nBy inspecting the results of Table \\ref{tab:exp:resultsCutsClass1}\nit is difficult to reason about which cutting strategy is superior\nas all instances were proved optimal for every combination.\nThese results immediately tell us that the Benders decomposition\nwe present here has outperformed the pure MIP formulations\npreviously presented by the literature.\nWe note that when the global bound in not enforced after\na globally feasible solution is found, the Benders gap\nremains substantially large and so it is difficult\nto measure the convergence of the Benders algorithm.\nThus for the remaining experiments we run, the global bound\nwill always be used unless stated otherwise.\nThe $3^{\\text{rd}}$ version of the inference cut ($\\mathcal{C}_{iii}$) appears to\nbe a key ingredient in the Benders algorithm terminating efficiently,\nbut to confirm this suspicion we test our solution\nmethodology on class 2.\n\n\\begin{table}[tpb]\n\t\\caption{Benders cutting strategies compared on class 1}\n\t\\centering\n\t\\vspace{2mm}\n\t\\begin{tabular}{cccccrrrrrrr}\n\t\t\\toprule\n\t\t\\multicolumn{5}{c}{Cuts and Bound}  &  &  &  &  &  &  &   \\\\\\cmidrule(rl){1-5}\n\t\t$\\mathcal{C}_{i}$ & $\\mathcal{C}_{ii}$ & $\\mathcal{C}_{iii}$ & $\\mathcal{C}_{l}$ & $\\mathcal{C}_{gb}$& \\#Nodes & \\#Its. & $|\\mathcal{C}|$ & \\%Gap & \\#No.s. & \\%Opt. & Rt.(s) \\\\\\midrule\\midrule\n\t\t\\checkmark &  &  &  &  & 4,718 & 18 & 35 & 0.00 & 0 & 100.00 & 5.8 \\\\\n\t\t & \\checkmark &  &  &  & 2,845 & 15 & 28 & 0.00 & 0 & 100.00 & 4.1 \\\\\n\t\t &  & \\checkmark &  &  & 170 & 4 & 8 & 0.00 & 0 & 100.00 & 1.1 \\\\\\midrule\n\t\t\\checkmark &  &  &  & \\checkmark & 3,790 & 16 & 32 & 0.00 & 0 & 100.00 & 2.9 \\\\\n\t\t & \\checkmark &  &  & \\checkmark & 2,064 & 12 & 26 & 0.00 & 0 & 100.00 & 1.9 \\\\\n\t\t &  & \\checkmark &  & \\checkmark & 128 & 3 & 9 & 0.00 & 0 & 100.00 & 0.4 \\\\\\midrule\n\t\t\\checkmark &  &  & \\checkmark & \\checkmark & 766 & 17 & 34 & 0.00 & 0 & 100.00 & 2.6 \\\\\n\t\t & \\checkmark &  & \\checkmark & \\checkmark & 896 & 17 & 34 & 0.00 & 0 & 100.00 & 2.8 \\\\\n\t\t &  & \\checkmark & \\checkmark & \\checkmark & 56 & 4 & 12 & 0.00 & 0 & 100.00 & 0.5 \\\\\n\t\t\\bottomrule\n\t\\end{tabular}\n\t\\label{tab:exp:resultsCutsClass1}\n\\end{table}\n\nIn Table \\ref{tab:exp:resultsCutsClass2} we can see that\nclass 2 proved more challenging for the Benders decomposition\nto solve the problem as in many cases optimality was\nproven for only $\\sim30\\%$ of the instances.\nThese results make it clear that $\\mathcal{C}_{iii}$\nis the strongest infer cut as it is able to\nsolve almost twice as many instances to optimality\nthat the other 2 infer cuts.\nFurther to this, it needed half as many iterations\nand similarly half as many cuts in total.\nFor the instances where the optimal solution was not found,\n$\\mathcal{C}_{iii}$ provided the lowest Benders gap values\nas well.\n\nWe must also examine whether including the logic cut, $\\mathcal{C}_{l}$,\nprovided a benefit.\nWhen considering the logic cut, a global bound on the cycle time is instituted\nas an upper bound on the load of each station's sub-problem,\npossibly leading to feasibility sub-problems, rather than optimality.\nThe logic cut was formulated to provide the \\rmp{} with detailed information\nabout the assignment variables whilst also reducing the time\nneeded to solve a sub-problem; however it also has a notable drawback.\nWhen a logic cut is generated by a sub-problem, that sub-problem\nhas not been solved to optimality.\nThis results in us not being able to generate an optimality cut for\nthis sub-problem, such as $\\mathcal{C}_{iii}$.\nThe results of Table \\ref{tab:exp:resultsCutsClass2} indicate\nthat on average, not being able to perform an infer cut has not outweighed the beneficial\ninformation provided by the logic cut.\n\n\\begin{table}[tpb]\n\t\\caption{Benders cutting strategies compared on class 2}\n\t\\centering\n\t\\vspace{2mm}\n\t\\begin{tabular}{cccccrrrrrrr}\n\t\t\\toprule\n\t\t\\multicolumn{5}{c}{Cuts and Bound}  &  &  &  &  &  &  &   \\\\\\cmidrule(rl){1-5}\n\t\t$\\mathcal{C}_{i}$ & $\\mathcal{C}_{ii}$ & $\\mathcal{C}_{iii}$ & $\\mathcal{C}_{l}$ & $\\mathcal{C}_{gb}$ & \\#Nodes & \\#Its. & $|\\mathcal{C}|$ & \\%Gap & \\#No.s. & \\%Opt. & Rt.(s) \\\\\\midrule\\midrule\n\t\t\\checkmark &  &  &  & \\checkmark & 1,522k & 99 & 396 & 11.63 & 1 & 31.25 & 1339.7 \\\\\n\t\t & \\checkmark &  &  & \\checkmark & 1,430k & 99 & 399 & 10.79 & 1 & 32.14 & 1348.5 \\\\\n\t\t &  & \\checkmark &  & \\checkmark & 1,024k & 47 & 196 & 8.42 & 1 & \\bf{60.71} & 959.9 \\\\\\midrule\n\t\t\\checkmark &  &  & \\checkmark & \\checkmark & 918k & 112 & 439 & 11.38 & 1 & 33.04 & 1318.4 \\\\\n\t\t & \\checkmark &  & \\checkmark & \\checkmark & 964k & 114 & 443 & 11.33 & 1 & 31.25 & 1342.3 \\\\\n\t\t &  & \\checkmark & \\checkmark & \\checkmark & 898k & 68 & 225 & 9.03 & 1 & 58.04 & 956.8 \\\\\n\t\t\\bottomrule\n\t\\end{tabular}\n\t\\label{tab:exp:resultsCutsClass2}\n\\end{table}\n\nHence, for all remaining experiments we used the infer cut $\\mathcal{C}_{iii}$\nin combination with the global bound $\\mathcal{C}_{gb}$ as the cutting\nprocedure, unless stated otherwise.\n\nWe mention here that combining different \ntypes of infer cuts together in a single cutting procedure\nwas not explored.\nThis is because every inference made by $\\mathcal{C}_{i}$ is \ncontained within $\\mathcal{C}_{ii}$ and every inference made by $\\mathcal{C}_{ii}$\nis similarly contained within $\\mathcal{C}_{iii}$.\nThus combining these infer cuts will not lead to a\nsubstantial reduction in runtime.\n\n\\section{CP Sub-Problem}\n\\label{sec:exp:cp}\nThe CP solver \\chuffed provides the\nuser with numerous input parameters to\ntailor the propagation and search procedure \nto the problem at hand.\nIn this section, we report on the comparisons\nbetween the model formulation\nand search strategies in order to find the best suited\nconfiguration for the \\sua{2} instances.\n\nAs we are only concerned with optimizing the sub-problems'\nsolving time, the runtime values we present here will\nonly average the time used by the CP model, \n\\ie excluding the runtime of the master problem.\nSimilarly, this also applies to the average number of nodes\nexplored by the CP sub-problems..\n\n% The upper bound cut reduces the space complexity of the sub-problems\n% very helpful for cp solver whose difficultly is very closely\n% related to the inference that can be done on the finite domains. \n\n\\subsection{Model Formulation}\n\\label{sec:exp:cpForm}\nTwo main types of CP models were considered, so we\nfirst check which of these is superior before moving\non to test other input parameters.\n$CP_1$ represents the model detailed in Section \\ref{sec:bend:cpModel}\nfrom the previous chapter.\n$CP_2$ represents the same model but with the additional decision\nvariable $\\sigma_{ij}$ and the \\cumu global constraint.\n\nIn Table \\ref{tab:exp:resultsCPmodel}, we compare these two models \nagainst each other on the class 1 and\nclass 2 instances where $\\alpha$ is fixed to $1.00$.\nThe search strategy used for these tests was simply the default\nsearch of \\chuffed.\nThese tests indicate that there is a reduction\nin sub-problem runtime when the \\cumu constraint\nis used in the CP formulation.\nFor all remaining experiments where CP sub-problems\nwere used, $CP_2$ was the formulation utilized\nunless stated otherwise.\n\n\\begin{table}[tpb]\n\t\\caption{CP formulations compared on classes 1 and 2 when $\\alpha=1.00$}\n\t\\centering\n\t\\vspace{2mm}\n\t\\begin{tabular}{ccrrrrrr}\n\t\t\\toprule\n\t\tClass & Model & \\#SP Nodes & \\%Gap & \\%Opt. & SP Runtime(s) \\\\\\midrule\\midrule\n\t\t1 & $CP_1$ & 32,755 & 0.00 & 100.00 & 3.83  \\\\\n\t\t & $CP_2$ & 29,225 & 0.00 & 100.00 & \\bf{2.84} \\\\\\midrule\n\t\t2 & $CP_1$ & 2,768,871 & 15.45 & 25.00 & 386.71 \\\\\n\t\t & $CP_2$ & 2,503,183 & 14.03 & 25.00 & \\bf{329.60} \\\\\n\t\t\\bottomrule\n\t\\end{tabular}\n\t\\label{tab:exp:resultsCPmodel}\n\\end{table}\n\n\\subsection{Search Strategy}\n\\label{sec:exp:cpSearch}\nEarlier in Section \\ref{sec:bend:cpForm}\nof the previous Chapter, we detailed a range of possible search procedures\nwhich could be employed when solving our constraint program.\nIn Table \\ref{tab:exp:resultsCPsearch} we present the results\nof testing the CP sub-problems on a selection of these procedures.\nThe names of the searches refer to the following procedures:\n{\\tt def} is the default search, {\\tt start} is the basic search on start time variables,\n{\\tt start\\_ff\\_Then\\_sigma} is a sequential search of start then $\\sigma$ variables. \nFour priority searches were considered which only differ by the variable selection\nstrategy used to choose the next sequential procedure.\n% ; these are \n% {\\tt priority\\_io} using {\\tt input\\_order} variable selection, \n% {\\tt priority\\_sm} using {\\tt smallest},\n% {\\tt priority\\_sml} using {\\tt smallest\\_largest} and\n% {\\tt priority\\_ff} using {\\tt first\\_fail}.\n\nFrom the results of Table \\ref{tab:exp:resultsCPsearch}, \nwe can immediately conclude that the default search\nis inferior to the search strategies we have tailored for\nthe \\sua{2}.\nAlthough, among the search procedures we devised, there\nis very little variations in the results.\nEach procedure was able to find the optimal solution\nfor the same number of instances,\nwhile the runtime was very similar.\nThe basic search {\\tt start} needed to explore the fewest\nnumber of nodes in the search tree, however the priority search\n{\\tt priority\\_ff} provided the best average runtime.\nFor all remaining tests where CP sub-problems\nwere utilized, the priority based search strategy using \nthe {\\tt first\\_fail} variable selection was used.\n\n\n\\begin{table}[tpb]\n\t\\caption{CP search strategies compared on class 2 when $\\alpha=1.00$}\n\t\\centering\n\t\\vspace{2mm}\n\t\\begin{tabular}{clrrrrrr}\n\t\t\\toprule\n\t\tClass & Search & \\#SP Nodes & \\%Gap & \\%Opt. & SP Runtime(s) \\\\\\midrule\\midrule\n\t\t2 & {\\tt default}\t\t\t& 2,503k & 14.03 & 25.00 & 329.60 \\\\\n\t\t & {\\tt start}\t\t\t\t& 1,884k & 8.97 & 42.86 & 246.57 \\\\\n\t\t & {\\tt start\\_ff\\_Then\\_sigma}\t& 2,391k & 9.69 & 42.86 & 254.23 \\\\\n\t\t & {\\tt priority\\_io}\t\t& 2,448k & 9.12 & 42.86 & 253.70 \\\\\n\t\t & {\\tt priority\\_sm}\t\t& 2,408k & 9.06 & 42.86 & 252.91 \\\\\n\t\t & {\\tt priority\\_sml}\t\t& 2,470k & 9.04 & 42.86 & 252.63 \\\\\n\t\t & {\\tt priority\\_ff}\t\t& 2,426k & 8.90 & 42.86 & \\bf{245.74} \\\\\n\t\t\\bottomrule\n\t\\end{tabular}\n\t\\label{tab:exp:resultsCPsearch}\n\\end{table}\n\n\\section{Benchmark Experiments}\n\\label{sec:exp:benchmarkExp}\nWe close this chapter by comparing the best\nconfiguration of our logic-based Benders decomposition\nagainst the results of the MIP formulations for all benchmark\ninstances from the subset of SBF2 we have used.\nBefore presenting this final result, we must first\ndecide on the best sub-problem formulation for our\nBenders decomposition.\n\nEarlier in Section \\ref{sec:lit:cpChuffed}, we gave a\nbrief description of the CP solver, \\chuffed, we chose to utilize when\ntackling the constraint programs we formulated.\nAs mentioned in that section, \\chuffed does not currently have\nthe ability to be run in parallel.\nThis handicap has hampered its ability to effectively compete\nwith \\gurobi, which can easily run in parallel on all four cores\nof the computer we used for testing.\n\nIn Table \\ref{tab:exp:resultsSPform} we present a comparison\nof our Benders decomposition algorithm tested on the class 2\ninstances when using MIP and CP sub-problems.\nThere are many more nodes explored when using CP sub-problems\ndue to the different search procedure of a CP solver\nwhen compared to a MIP solver.\nThe results of the two formulations are similar, but we can\nconclude that our best configuration of the CP model\nhas provided a reduction in runtime when compared to the MIP\nformulation.\n\n\\begin{table}[tpb]\n\t\\caption{MIP and CP sub-problem formulations compared on class 2}\n\t\\centering\n\t\\vspace{2mm}\n\t\\begin{tabular}{ccrrrrrr}\n\t\t\\toprule\n\t\tClass & Sub-Problem & \\#SP Nodes & \\%Gap & \\%Opt. & SP Runtime(s) \\\\\\midrule\\midrule\n\t\t2 & \\spmip{} & 630k & 8.42 & 60.71 & 173.05 \\\\\n\t\t & \\spcp{} & 2,489k & 8.21 & 61.61 & \\bf{165.26} \\\\\n\t\t\\bottomrule\n\t\\end{tabular}\n\t\\label{tab:exp:resultsSPform}\n\\end{table}\n\nNow using the best formulation of our Benders decomposition\nwe present the results of our final benchmark experiments \non all 3 classes from the subset of the SBF2 instances.\nThese results can be found in Table \\ref{tab:exp:resultsBestBenders}\nwhere we provide the average number of iterations,\ncuts, average gap, number optimal and runtime breakdown.\nThe instances from classes 2 and 3 proved to be more\nchallenging than the smaller instances from class 1.\nMost notably, the total runtime taken by\nthe Benders algorithm is almost entirely due to the complexity of the \\rmp{}.\n\nMore cuts are to be expected when the difficultly of the problem\nis increased, but we also mention that for the instances of class 3\nthere is also a larger number of stations.\nThis will lead to more cuts being made for every iteration of the algorithm.\n\n\\begin{table}[tpb]\n\t\\caption{Benchmark results of our final Benders decomposition}\n\t\\centering\n\t\\vspace{2mm}\n\t\\begin{tabular}{crrrrrr}\n\t\t\\toprule\n\t\tClass & \\#Its. & \\#Cuts. & \\%Gap & \\#Opt. & RMP.Runtime(s) & SP.Runtime(s) \\\\\\midrule\\midrule\n\t\t1 & 3 & 9 & 0.00 & 108/108 & 0.36 (87.95\\%) & 0.04 (10.98\\%) \\\\\n\t\t2 & 47 & 196 & 8.21 & 69/112 & 781.29 (82.33\\%) & 165.26 (17.42\\%) \\\\\n\t\t3 & 92 & 468 & 15.76 & 27/176 & 1462.01 (88.00\\%) & 173.63 (10.45\\%) \\\\\n\t\t\\bottomrule\n\t\\end{tabular}\n\t\\label{tab:exp:resultsBestBenders}\n\\end{table}\n\nTable \\ref{tab:exp:resultsBenchmark} compares how our final results perform\nwhen compared to the pure MIP formulations of the \\sua{2}.\nFor each class of instances our solution methodology beats the best formulation\nof the MIPs.\nIn the case of class 2 where the Benders decomposition could not prove optimality for\nall instances, the average Benders gap at termination is superior to\nthe best average gap found by \\gurobi when solving either \\fsbf{2} and \\scbf{2}.\nFor class 3, our algorithm could only find the optimal solution for 15.3\\% of the 176 instances.\nAlso the \\scbf{2} model returned superior average gap values for class 3, even though\nit was unable to find any optimal solutions.\nAlthough the gap value of \\scbf{2} for the class 3 instances\nmay be misleading, as it only calculated from\nthe 59 of 176 instances where a feasible solution was found.\n\n\\begin{table}[tpb]\n\t\\caption{Benders decomposition compared to pure MIP formulations}\n\t\\centering\n\t\\vspace{2mm}\n\t\\begin{tabular}{crrrrrrrr}\n\t\t\\toprule\n\t\t & \\multicolumn{4}{c}{Benders decomposition}  & \\multicolumn{2}{c}{\\fsbf{2}} & \\multicolumn{2}{c}{\\scbf{2}}  \\\\\n\t\t \\cmidrule(lr){2-5} \\cmidrule(lr){6-7} \\cmidrule(lr){8-9}\n\t\tClass & \\%Gap & \\#Opt. & \\%Opt. & Rt.(s) & \\%Gap & \\%Opt. & \\%Gap & \\%Opt. \\\\\\midrule\\midrule\n\t\t1 & 0.00 & 108/108 & 100.00 & 0.41 & 0.16 & 93.52 & 1.62 & 77.78 \\\\\n\t\t2 & 8.21 & 69/112 & 61.61 & 948.93 & 13.76 & 0.00 & 18.01 & 0.00 \\\\\n\t\t3 & 15.76 & 27/176 & 15.34 & 1661.93 & 19.56 & 3.98 & 10.09 & 0.00 \\\\\n\t\t\\bottomrule\n\t\\end{tabular}\n\t\\label{tab:exp:resultsBenchmark}\n\\end{table}\n\nOur results indicate that the \\sua{2} is a difficult problem to solve\nwhen the instance size becomes large.\nHowever, we can see from these results that decomposing the problem using a \nlogic-based Benders decomposition framework provides\nthe most optimal solutions when compared to the other available exact\nsolution procedures.\n\n% \\section{Summary}\n% \\label{sec:exp:summary}\n\n% blah\n", "meta": {"hexsha": "b69f29cb4ed5d42e780035be988058d5f941660c", "size": 28670, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Assembly Task Scheduling/sualbsp-2-master/thesis/chap_experiments.tex", "max_stars_repo_name": "BillChan226/ODA-Multi-Manipulator", "max_stars_repo_head_hexsha": "6863558a9fdb946fb16c67a7660172154274cfe0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assembly Task Scheduling/sualbsp-2-master/thesis/chap_experiments.tex", "max_issues_repo_name": "BillChan226/ODA-Multi-Manipulator", "max_issues_repo_head_hexsha": "6863558a9fdb946fb16c67a7660172154274cfe0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assembly Task Scheduling/sualbsp-2-master/thesis/chap_experiments.tex", "max_forks_repo_name": "BillChan226/ODA-Multi-Manipulator", "max_forks_repo_head_hexsha": "6863558a9fdb946fb16c67a7660172154274cfe0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.0786163522, "max_line_length": 195, "alphanum_fraction": 0.7138472271, "num_tokens": 9208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.6584174938590245, "lm_q1q2_score": 0.34719442379402826}}
{"text": "\\chapter{Shape-from-Shading}\n\\label{ch:sfs}\n\nASP provides a tool, named \\texttt{sfs}, that can improve the level of\ndetail of DEMs created by ASP or any other source using\n\\textit{shape-from-shading} (SfS). The tool takes as input one or more\ncamera images, a DEM at roughly the same resolution as the images, and\nreturns a refined DEM.\n\n\\texttt{sfs} works only with ISIS cub images. It has been tested\nthoroughly with Lunar LRO NAC datasets, and some experiments were done\nwith Mars HiRISE images and with pictures from Charon, Pluto's moon. As\nseen later in the text, it returns reasonable results on the Moon as far\nas $85^\\circ$ South.\n\nCurrently, \\texttt{sfs} is computationally expensive, and is practical\nonly for DEMs whose width and height are several thousand pixels. It can be \nsensitive to errors in the position and orientation of the cameras, the\naccuracy of the initial DEM, and to the value of the two weights it uses.\nYet, with some effort, it can work quite well. \n\nA tool named \\texttt{parallel\\_sfs} is provided (section \\ref{psfs}) \nthat parallelizes \\texttt{sfs} using multiple processes (optionally on\nmultiple machines) by splitting the input DEM into tiles with padding,\nrunning \\texttt{sfs} on each tile, and then blending the results. \n\nThe \\texttt{sfs} program can model position-dependent albedo, different\nexposure values for each camera, shadows in the input images, and regions\nin the DEM occluded from the Sun. It can refine the positions and orientations\nof the cameras.\n\nThe tool works by minimizing the cost function\n\\begin{equation}\\label{cost}\n%\\begin{multline}\\label{cost}\n\\int\\!\\! \\int \\! \\sum_k \\left[ I_k(\\phi)(x, y) - T_k A(x, y)\n R_k(\\phi)(x, y) \\right]^2\\,  \n% R_k(\\phi)(x, y) \\right]^2\\,  \\\\\n+ \\mu \\left\\|\\nabla^2 \\phi(x, y) \\right\\|^2  \n+ \\lambda  \\left[ \\phi(x, y) - \\phi_0(x, y) \\right]^2\n\\, dx\\, dy.\n\\end{equation}\n%\\end{multline}\n\nHere, $I_k(\\phi)(x, y)$ is the $k$-th camera image interpolated at\npixels obtained by projecting into the camera 3D points from the terrain\n$\\phi(x, y)$, $T_k$ is the $k$-th image exposure, $A(x, y)$ is the\nper-pixel albedo, $R_k(\\phi)(x, y)$ is the reflectance computed from the\nterrain for $k$-th image, $\\left\\|\\nabla^2 \\phi(x, y) \\right\\|^2 $ is the sum\nof squares of all second-order partial derivatives of $\\phi$, $\\mu > 0$\nis a smoothing term, and $\\lambda > 0$ determines how close we should\nstay to the input terrain $\\phi_0$ (smaller $\\mu$ will show more detail\nbut may introduce some artifacts, and smaller $\\lambda$ may allow for\nmore flexibility in optimization but the terrain may move too far from the input). \n\nWe use either the regular Lambertian reflectance model,\nor the Lunar-Lambertian model \\cite{mcewen1991photometric}, more specifically as given in\n\\cite{lohse2006derivation} (equations (3) and (4)).\nAlso supported is the Hapke model, \n\\cite{johnson2006spectrophotometric}, \\cite{fernando2013surface},\n\\cite{hapke2008bidirectional}, \\cite{hapke1993opposition}.\nCustom values for the coefficients of these models can be passed to the program.\n\n\\section{How to get good test imagery}\n\nWe obtain the images from\n\\url{http://wms.lroc.asu.edu/lroc/search} (we search for EDR images of\ntype NACL and NACR). \n\nA faster (but not as complete) interface is provided by\n\\url{http://ode.rsl.wustl.edu/moon/indexproductsearch.aspx}. The related\nsite\n\\url{http://ode.rsl.wustl.edu/moon/indextools.aspx?displaypage=lolardr}\ncan provide LOLA datasets which can be used as (sparse) ground truth.\n\nWe advise the following strategy for picking images. First choose a small\nlongitude-latitude window in which to perform a search for imagery. Pick\ntwo images that are very close in time and with a big amount of overlap\n(ideally they would have consecutive orbit numbers).\nThose can be passed to ASP's \\texttt{stereo} tool to create an initial DEM. Then, search for \nother images close to the center of the maximum overlap of the first\ntwo images. Pick one or more of those, ideally with different illumination\nconditions than the first two. Those (together with one of the first two images) can be used for SfS.\n\nTo locate the area of spatial overlap, the images can be map-projected (either\nwith \\texttt{cam2map} with a coarse resolution) or with\n\\texttt{mapproject}, using for example the LOLA DEM as the terrain to project onto, \nor the DEM obtained from running \\texttt{stereo} on those images. Then the images can be overlayed\nin \\texttt{stereo\\_gui}. A good sanity check is to examine the shadows in\nvarious images. If they point in different directions in the images and perhaps\nalso have different lengths, that means that illumination conditions are\ndifferent enough, which will help constrain the \\texttt{sfs} problem better.\n\n\\section{Running sfs at 1 meter/pixel using a single image}\n\nIn both this and the next sections we will work with LRO NAC images taken\nclose to the Lunar South Pole, at a latitude of $85^\\circ$ South (the tool was\ntested on equatorial regions as well). We will use four images,\nM139939938LE, M139946735RE, M173004270LE, and M122270273LE.\n\nWe first retrieve the data sets.\n\\begin{verbatim}\n  wget http://lroc.sese.asu.edu/data/LRO-L-LROC-2-EDR-V1.0/\\\nLROLRC_0005/DATA/SCI/2010267/NAC/M139939938LE.IMG\n  wget http://lroc.sese.asu.edu/data/LRO-L-LROC-2-EDR-V1.0/\\\nLROLRC_0005/DATA/SCI/2010267/NAC/M139946735RE.IMG\n  wget http://lroc.sese.asu.edu/data/LRO-L-LROC-2-EDR-V1.0/\\\nLROLRC_0009/DATA/SCI/2011284/NAC/M173004270LE.IMG\n  wget http://lroc.sese.asu.edu/data/LRO-L-LROC-2-EDR-V1.0/\\\nLROLRC_0002/DATA/MAP/2010062/NAC/M122270273LE.IMG\n\\end{verbatim}\n\nThen we convert them to ISIS cubes, initialize the SPICE kernels, and\nperform radiometric calibration and echo correction. Here are the steps, \nillustrated on the first image:\n\\begin{verbatim}  \n  lronac2isis from = M139939938LE.IMG     to = M139939938LE.cub\n  spiceinit from   = M139939938LE.cub\n  lronaccal from   = M139939938LE.cub     to = M139939938LE.cal.cub\n  lronacecho from  = M139939938LE.cal.cub to = M139939938LE.cal.echo.cub\n\\end{verbatim}\nWe rename, for simplicity, the obtained four processed datasets to\nA.cub, B.cub, C.cub, and D.cub.\n\nThe first step is to run stereo to create an initial guess DEM. We\npicked for this the first two of these images. These form a stereo pair,\nthat is, they have a reasonable baseline and sufficiently close times of\nacquisition (hence very similar illuminations). These conditions are\nnecessary to obtain a good stereo result.\n\\begin{verbatim}\nparallel_stereo --job-size-w 1024 --job-size-h 1024 A.cub B.cub    \\\n                --left-image-crop-win 0 7998 2728 2696             \\\n                --right-image-crop-win 0 9377 2733 2505            \\\n                --threads 16 --corr-seed-mode 1  --subpixel-mode 3 \\\n                run_full1/run\n\\end{verbatim}\nNext we create a DEM at 1 meter/pixel, which is about the resolution\nof the input images. We use the stereographic projection since this\ndataset is very close to the South Pole. Then we crop it to the region\nwe'd like to do SfS on.\n\\begin{verbatim}\n  point2dem -r moon --stereographic --proj-lon 0 \\\n    --proj-lat -90 run_full1/run-PC.tif\n  gdal_translate -projwin -15471.9 150986 -14986.7 150549  \\\n    run_full1/run-DEM.tif run_full1/run-crop-DEM.tif\n\\end{verbatim}\nThis creates a DEM of size $456 \\times 410$ pixels.\n\nThen we run \\texttt{sfs}:\n\\begin{verbatim}\n  sfs -i run_full1/run-crop-DEM.tif A.cub -o sfs_ref1/run           \\\n     --reflectance-type 1                                           \\\n    --smoothness-weight 0.08 --initial-dem-constraint-weight 0.0001 \\\n    --max-iterations 10 --use-approx-camera-models                  \\\n    --use-rpc-approximation --crop-input-images  \n\\end{verbatim}\n\nThe smoothness weight is a parameter that needs tuning. If it is too\nsmall, SfS will return noisy results, if it is too large, too much\ndetail will be blurred. Here we used the Lunar Lambertian model. The meaning of the other\n\\texttt{sfs} options can be looked up in section \\ref{sfs}.\n\nWe show the results of running this program in figure\n\\ref{fig:sfs1}. The left-most figure is the hill-shaded original DEM,\nwhich was obtained by running:\n\\begin{verbatim}\n  hillshade --azimuth 300 --elevation 20 run_full1/run-crop-DEM.tif \\\n    -o run_full1/run-crop-hill.tif \n\\end{verbatim}\nThe second image is the hill-shaded DEM obtained after running\n\\texttt{sfs} for 10 iterations.\n\nThe third image is, for comparison, the map-projection of A.cub onto the\noriginal DEM, obtained via the command:\n\\begin{verbatim}\n  mapproject --tr 1 run_full1/run-crop-DEM.tif A.cub A_map.tif --tile-size 128\n\\end{verbatim}\nThe forth image is the colored absolute difference between the original\nDEM and the SfS output, obtained by running:\n\\begin{verbatim}\n  geodiff --absolute sfs_ref1/run-DEM-final.tif run_full1/run-crop-DEM.tif\n  colormap --min 0 --max 2 --colormap-style binary-red-blue \\\n    run-DEM-final__run-crop-DEM-diff.tif\n\\end{verbatim}\n\\begin{figure}[h!]\n\\begin{center}\n\\includegraphics[width=7in]{images/sfs1.jpg}\n\\caption[sfs]{An illustration of \\texttt{sfs}. The images are, from\n  left to right, the original hill-shaded DEM, the hill-shaded DEM obtained\nfrom \\texttt{sfs}, the image A.cub map-projected onto the original DEM,\nand the absolute difference of the original and final DEM, where the brightest\nshade of red corresponds to a 2 meter height difference.}\n\\label{fig:sfs1}\n\\end{center}\n\\end{figure}\n\nIt can be seen that the optimized DEM provides a wealth of detail and\nlooks quite similar to the input image. It also did not diverge\nsignificantly from the input DEM. We will see in the next section that\nSfS is in fact able to make the refined DEM more accurate than the\ninitial guess (as compared to some known ground truth), though that is\nnot guaranteed, and most likely did not happen here where just one image\nwas used.\n\n\\section{SfS with multiple images in the presence of shadows}\n\nIn this section we will run \\texttt{sfs} with multiple images. We would\nlike to be able to see if SfS improves the accuracy of the DEM rather\nthan just adding detail to it. We evaluate this using the following\n(admittedly imperfect) approach. We resample the original images by a\nfactor of 10, run stereo with them, followed by SfS using the stereo\nresult as an initial guess and with the resampled images. As ground\ntruth, we create a DEM from the original images at 1 meter/pixel, which\nwe bring closer to the initial guess for SfS using\n\\texttt{pc\\_align}. We would like to know if running SfS brings us even\ncloser to this ``ground truth'' DEM.\n\nThe most significant challenge in running SfS with multiple images is\nthat shape-from-shading is highly sensitive to errors in camera position\nand orientation. The \\texttt{sfs} tool can improve these by floating\nthem during optimization and by using a coarse-to-fine scheme, where\nthe problem is first solved using subsampled images and terrain then\nit is successively refined.\n\nIf possible, it may still be desirable to bundle-adjust the cameras first\n(section \\ref{bundleadjust}). It is important to note that bundle adjustment may\nfail if the images have sufficiently different illumination, as it will\nnot be able to find matches among images. A solution to this is discussed\nin section \\ref{sfs-lola}.\n\nTo make bundle adjustment and stereo faster, we first crop the images,\nsuch as shown below (the crop parameters can be determined via\n\\texttt{stereo\\_gui}).\n\\begin{verbatim}\n  crop from = A.cub to = A_crop.cub sample = 1 line = 6644 nsamples = 2192 nlines = 4982\n  crop from = B.cub to = B_crop.cub sample = 1 line = 7013 nsamples = 2531 nlines = 7337\n  crop from = C.cub to = C_crop.cub sample = 1 line = 1 nsamples = 2531 nlines = 8305\n  crop from = D.cub to = D_crop.cub sample = 1 line = 1 nsamples = 2531 nlines = 2740\n\\end{verbatim}\nThen we bundle-adjust and run stereo\n\\begin{verbatim}\n  bundle_adjust A_crop.cub B_crop.cub C_crop.cub D_crop.cub    \\\n    --min-matches 1 -o run_ba/run\n  stereo A_crop.cub B_crop.cub run_full2/run --subpixel-mode 3 \\\n    --bundle-adjust-prefix run_ba/run\n\\end{verbatim}\n\nThis will result in a point cloud, \\verb#run_full2/run-PC.tif#, which will\nlead us to the ``ground truth'' DEM. As mentioned\nbefore, we'll in fact run SfS with images subsampled by a factor of\n10. Subsampling is done by running the ISIS \\texttt{reduce} command\n\\begin{verbatim}\n  for f in A B C D; do \n    reduce from = ${f}_crop.cub to = ${f}_crop_sub10.cub sscale = 10 lscale = 10\n  done\n\\end{verbatim}\n\nWe run bundle adjustment and stereo with the subsampled images using\ncommands analogous to the above:\n\\begin{verbatim}\n  bundle_adjust A_crop_sub10.cub B_crop_sub10.cub C_crop_sub10.cub D_crop_sub10.cub \\\n    --min-matches 1 -o run_ba_sub10/run --ip-per-tile 100000\n stereo A_crop_sub10.cub B_crop_sub10.cub run_sub10/run --subpixel-mode 3           \\\n   --bundle-adjust-prefix run_ba_sub10/run\n\\end{verbatim}\nWe'll obtain a point cloud named \\verb#run_sub10/run-PC.tif#.\n\nWe'll bring the ``ground truth'' point cloud closer to the initial guess\nfor SfS using \\texttt{pc\\_align}:\n\\begin{verbatim}\n  pc_align --max-displacement 200 run_full2/run-PC.tif run_sub10/run-PC.tif \\\n    -o run_full2/run --save-inv-transformed-reference-points\n\\end{verbatim}\nThis step is extremely important. Since we ran two bundle adjustment\nsteps, and both were without ground control points, the resulting clouds\nmay differ by a large translation, which we correct here. Hence we would like to \nmake the ``ground truth'' terrain aligned with the datasets on which we \nwill perform SfS. \n\nNext we create the ``ground truth'' DEM from the aligned high-resolution\npoint cloud, and crop it to a desired region:\n\\begin{verbatim}\n  point2dem -r moon --tr 10 --stereographic --proj-lon 0 --proj-lat -90 \\\n    run_full2/run-trans_reference.tif\n  gdal_translate -projwin -15540.7 151403 -14554.5 150473               \\\n    run_full2/run-trans_reference-DEM.tif run_full2/run-crop-DEM.tif\n\\end{verbatim}\nWe repeat the same steps for the initial guess for SfS:\n\\begin{verbatim}\n  point2dem -r moon --tr 10 --stereographic --proj-lon 0 --proj-lat -90 \\\n    run_sub10/run-PC.tif\n  gdal_translate -projwin -15540.7 151403 -14554.5 150473               \\\n    run_sub10/run-DEM.tif run_sub10/run-crop-DEM.tif\n\\end{verbatim}\nAfter this, we run \\texttt{sfs} itself. Since our dataset has many shadows, we found\nthat specifying the shadow thresholds for the tool improves the\nresults. The thresholds can be determined using \\texttt{stereo\\_gui}.\nThis can be done by turning on shadow-threshold mode from the GUI menu, \nand then clicking on a few points in the shadows.  Then the thresholded images\ncan be visualized/updated from the menu as well, and this process can be iterated.\n\\begin{verbatim}\n  sfs -i run_sub10/run-crop-DEM.tif A_crop_sub10.cub C_crop_sub10.cub \\\n    D_crop_sub10.cub -o sfs_sub10_ref1/run --threads 4                \\\n    --smoothness-weight 0.12 --initial-dem-constraint-weight 0.0001   \\\n    --reflectance-type 1 --float-exposure                             \\\n    --float-cameras --use-approx-camera-models                        \\\n    --max-iterations 10 --use-approx-camera-models                    \\\n    --use-rpc-approximation --crop-input-images                       \\\n    --bundle-adjust-prefix run_ba_sub10/run                           \\\n    --shadow-thresholds \"0.00162484 0.0012166 0.000781663\"\n\\end{verbatim}\nWe compare the initial guess to \\texttt{sfs} to the ``ground truth'' DEM\nobtained earlier and the same for the final refined DEM using\n\\texttt{geodiff} as in the previous section. Before SfS:\n\n\\begin{verbatim}\n  geodiff --absolute run_full2/run-crop-DEM.tif run_sub10/run-crop-DEM.tif\n  gdalinfo -stats run-crop-DEM__run-crop-DEM-diff.tif | grep Mean=  \n\\end{verbatim}\nand after SfS:\n\\begin{verbatim}\n  geodiff --absolute run_full2/run-crop-DEM.tif sfs_sub10_ref1/run-DEM-final.tif\n  gdalinfo -stats run-crop-DEM__run-DEM-final-diff.tif | grep Mean=\n\\end{verbatim}\n\nThe mean error goes from 2.64~m to 1.29~m, while the standard deviation\ndecreases from 2.50~m to 1.29~m. Visually the refined DEM looks more detailed\nas well as seen in figure \\ref{fig:sfs2}. The same experiment can be\nrepeated with the Lambertian reflectance model (reflectance-type 0), and\nthen it is seen that it performs a little worse. \n\nWe also show in this figure the first of the images used for SfS,\n\\verb#A_crop_sub10.cub#, map-projected upon the optimized DEM. Note that\nwe use the previously computed bundle-adjusted cameras when\nmap-projecting, otherwise the image will show as shifted from its true\nlocation:\n\\begin{verbatim}\n  mapproject sfs_sub10_ref1/run-DEM-final.tif A_crop_sub10.cub A_crop_sub10_map.tif \\\n    --bundle-adjust-prefix run_ba_sub10/run\n\\end{verbatim}\n\\begin{figure}[h!]\n\\begin{center}\n\\includegraphics[width=7in]{images/sfs2.jpg}\n\\caption[sfs]{An illustration of \\texttt{sfs}. The images are, from\n  left to right, the hill-shaded initial guess DEM for SfS, the hill-shaded DEM obtained\nfrom \\texttt{sfs}, the ``ground truth'' DEM, and the first of the\nimages used in SfS map-projected onto the optimized DEM.}\n\\label{fig:sfs2}\n\\end{center}\n\\end{figure}\n\n\\section{Dealing with large camera errors and LOLA comparison}\n\\label{sfs-lola}\n\nSfS is very sensitive to errors in camera positions and\norientations. These can be optimized as part of the problem, but if they\nare too far off, the solution will not be correct. In the previous\nsection we used bundle adjustment to correct these errors, and then we\npassed the adjusted cameras to \\texttt{sfs}. However, bundle adjustment may\noften fail, simply because the illumination conditions can be very\ndifferent among the images, and interest point matching may not succeed.\n\nThe option \\texttt{-\\/--coarse-levels \\it{int}} can be passed to\n\\texttt{sfs}, to solve for the terrain using a multi-resolution\napproach, first starting at a coarse level, where camera errors have\nless of an impact, and then jointly optimizing the cameras and\nthe terrain at ever increasing levels of resolution. Yet, this may still\nfail if the terrain does not have large and pronounced features on the\nscale bigger than the errors in the cameras.\n\nThe approach that we found to work all the time is to manually select\ninterest points in the images, as the human eye is much more skilled at\nidentifying a given landmark in multiple images, even when the lightning\nchanges drastically. Picking about 4 landmarks in each image is\nsufficient. Ideally they should be positioned far from each other, to\nimprove the accuracy.\n\nBelow is one example of how we manually select interest points, run SfS,\nand then how we compare to LOLA, which is an independently acquired\nsparse dataset of 3D points on the Moon. According to\n\\cite{smith2011results}, the LOLA accuracy is on the order of 1~m. To\nensure a meaningful comparison of stereo and SfS with LOLA, we resample\nthe LRO NAC images by a factor of 4, making them nominally 4\nm/pixel. This is not strictly necessary, the same exercise can be\nrepeated with the original images, but it is easier to see the\nimprovement due to SfS when comparing to LOLA when the images are\ncoarser than the LOLA error itself.\n\nWe work with the same images as before. To resample them, we do:\n\\begin{verbatim}\n  for f in A B C D; do \n    reduce from = ${f}_crop.cub to = ${f}_crop_sub4.cub sscale=4 lscale=4\n  done\n\\end{verbatim}\n\nWe run \\texttt{stereo} and \\texttt{point2dem} to get a first cut DEM. We don't do bundle\nadjustment at this stage yet. \n\\begin{verbatim}\n  stereo A_crop_sub4.cub B_crop_sub4.cub run_stereo_noba_sub4/run --subpixel-mode 3\n  point2dem --stereographic --proj-lon -5.7113451 --proj-lat -85.000351 \\\n    run_stereo_noba_sub4/run-PC.tif --tr 4 \n\\end{verbatim}\n\nWe would like now to manually pick interest points for the purpose of\ndoing bundle adjustment.  We found it it much easier to locate the landmarks if we \nfirst map-project the images, which brings them all into the same\nperspective. We then pick interest points in \\texttt{stereo\\_gui}, and then project\nthem back into the original cameras and do bundle adjustment. Here are\nthe steps:\n\\begin{verbatim}\n  for f in A B C D; do \n    mapproject --tr 4 run_stereo_noba_sub4/run-DEM.tif ${f}_crop_sub4.cub \\\n      ${f}_crop_sub4_v1.tif --tile-size 128\n  done\n  stereo_gui A_crop_sub4_v1.tif B_crop_sub4_v1.tif C_crop_sub4_v1.tif \\\n    D_crop_sub4_v1.tif run_ba_sub4/run\n\\end{verbatim}\nInterest points are selected by zooming and right-clicking with the\nmouse, one point at a time, from left to right, and then saving them. An\nillustration is shown in Figure \\ref{fig:sfs3}.\n\n\\begin{figure}[t!]\n\\begin{center}\n\\includegraphics[width=7in]{images/sfs3.jpg}\n\\caption[sfs]{An illustration of how interest points are picked manually for the purpose of bundle adjustment and then SfS.}\n\\label{fig:sfs3}\n\\end{center}\n\\end{figure}\n\nThen bundle adjustment happens:\n\\begin{verbatim}\n  P='A_crop_sub4_v1.tif B_crop_sub4_v1.tif' # to avoid long lines below\n  Q='C_crop_sub4_v1.tif D_crop_sub4_v1.tif run_stereo_noba_sub4/run-DEM.tif'\n  bundle_adjust A_crop_sub4.cub B_crop_sub4.cub C_crop_sub4.cub D_crop_sub4.cub  \\\n    -o run_ba_sub4/run --mapprojected-data  \"$P $Q\"                              \\\n    --min-matches 1\n\\end{verbatim}\n\nA good sanity check to ensure that at this stage cameras are aligned properly is to map-project\nusing the newly obtained camera adjustments and then overlay the obtained images in the GUI.\nThe features in all images should be perfectly on top of each other.\n\\begin{verbatim}\n  for f in A B C D; do \n    mapproject --tr 4 run_stereo_noba_sub4/run-DEM.tif ${f}_crop_sub4.cub  \\\n     ${f}_crop_sub4_v2.tif --tile-size 128 --bundle-adjust-prefix run_ba_sub4/run\n  done\n\\end{verbatim}\nThis will also show where the images overlap, and hence on what portion of the DEM we\ncan run SfS.\n\nThen we run stereo, followed by SfS. \n\\begin{verbatim}\n  stereo A_crop_sub4.cub B_crop_sub4.cub run_stereo_yesba_sub4/run             \\\n    --subpixel-mode 3 --bundle-adjust-prefix run_ba_sub4/run\n  point2dem --stereographic --proj-lon -5.7113451 --proj-lat -85.000351        \\\n    run_stereo_yesba_sub4/run-PC.tif --tr 4\n  gdal_translate -srcwin 138 347 273 506 run_stereo_yesba_sub4/run-DEM.tif     \\\n    run_stereo_yesba_sub4/run-crop1-DEM.tif \n  sfs -i run_stereo_yesba_sub4/run-crop1-DEM.tif A_crop_sub4.cub               \\\n    C_crop_sub4.cub D_crop_sub4.cub -o sfs_sub4_ref1_th_reg0.12_wt0.001/run    \\\n    --shadow-thresholds '0.00149055 0.00138248 0.000747531'                    \\\n    --threads 4 --smoothness-weight 0.12 --initial-dem-constraint-weight 0.001 \\\n    --reflectance-type 1 --float-exposure --float-cameras --max-iterations 20  \\\n    --use-approx-camera-models --use-rpc-approximation --crop-input-images     \\\n    --bundle-adjust-prefix run_ba_sub4/run\n\\end{verbatim}\n\nWe fetch the portion of the LOLA dataset around the current DEM from the\nsite described earlier, and save it as\n\\verb#RDR_354E355E_85p5S84SPointPerRow_csv_table.csv#. It is necessary\nto align our stereo DEM with this dataset to be able to compare\nthem. We choose to bring the LOLA dataset into the coordinate system\nof the DEM, using:\n\\begin{verbatim}\n  pc_align --max-displacement 280 run_stereo_yesba_sub4/run-DEM.tif             \\\n    RDR_354E355E_85p5S84SPointPerRow_csv_table.csv -o run_stereo_yesba_sub4/run \\\n    --save-transformed-source-points\n\\end{verbatim}\n\nThen we compare to the aligned LOLA dataset the input to SfS and its output:\n\\begin{verbatim}\n  geodiff --absolute -o beg --csv-format '1:lon 2:lat 3:radius_km' \\\n    run_stereo_yesba_sub4/run-crop1-DEM.tif run_stereo_yesba_sub4/run-trans_source.csv\n  geodiff --absolute -o end --csv-format '1:lon 2:lat 3:radius_km' \\\n    sfs_sub4_ref1_th_reg0.12_wt0.001/run-DEM-final.tif             \\\n    run_stereo_yesba_sub4/run-trans_source.csv\n\\end{verbatim}\n\nWe see that the mean error between the DEM and LOLA goes down, after SfS,\nfrom  1.14~m to 0.90~m, while the standard deviation decreases from\n 1.18~m to 1.06~m.\n\n\\section{Running SfS with an external initial guess DEM}\n\nSometimes it is convenient to run SfS with a DEM not created using ASP's\n\\texttt{stereo}. For example, for the Moon, the LOLA gridded DEM is\navailable. It is somewhat noisy and the nominal resolution is on the\norder of 10 m/pixel, but it is available even for permanently shadowed\nregions.\n\nThe main challenge in such a situation is that the images, such as\ncoming from LRO NAC, may not be aligned well to this external DEM and\namong themselves, and then SfS will fail. To get an initial alignment,\nwhat worked for us to coarsen both this DEM and the images to about 40\nmeters/pixel (using the ISIS \\texttt{reduce} command and\n\\texttt{dem\\_mosaic} with the options to blur and change the grid size),\nand then run SfS over a reasonably large area (say about $500 \\times\n500$ pixels) with pronounced terrain and where images have a lot of\noverlap with the option \\texttt{-\\/-float-all-cameras} (and of course\n\\texttt{-\\/-float-exposure}, and an appropriate \\texttt{-\\/-shadow-threshold}). \nThen, the SfS program will find\nadjustments to the cameras, writing them in the output directory. The\n\\texttt{mapproject} tool can be used to map-project the coarse images\nonto the input DEM using \\texttt{-\\/-bundle-adjust-prefix} pointing to\nthe \\texttt{sfs} output prefix. This should be used to verify that images\nare now aligned correctly, for example by overlaying them in\n\\texttt{stereo\\_gui}. If so, these adjustments can be used as input for\nSfS with images at finer levels of resolution (after appropriately renaming the\nadjustment files and using the \\texttt{-\\/-bundle-adjust-prefix} option of \\texttt{sfs}).\n\nHere, a higher value can be used for \\texttt{-\\/-initial-dem-constraint-weight}\nto ensure we cameras have more motivation to align to the terrain.\n\nWhen it comes to running SfS with many large high-resolution\nimages, one runs very fast into memory constraints. It is then necessary\nto parallelize the problem using \\texttt{parallel\\_sfs}, which will run\n\\texttt{sfs} on multiple tiles. Yet, the camera adjustments need to be\ndetermined before running this tool, and then kept fixed when this tool\nis run, as otherwise each single tile will optimize its cameras\nindependently, and as result there will be discontinuities at tile\nboundaries. \n\nIf the camera adjustments are determined by first running \\texttt{sfs}\non a clip representative of the entire terrain, far from that clip the\ncameras will start to disagree. For that reason, \\texttt{sfs} makes it\npossible to optimize the cameras on an entire collection of clips,\nchosen so they are reasonably spread out over the entire terrain, \nand that each camera image is covered by at least a handful of such clips.\nThe clips can be passed to \\texttt{sfs} as a quoted string via the \\texttt{-i} option. \nAs before, at the end the \\texttt{mapproject}\nprogram can be used to verify that the camera images mapprojected using the\nobtained camera adjustments are perfectly on top of each other, and if not,\nmore clips can be added to the joint optimization problem. When a good\nenough set of camera adjustments is obtained, \\texttt{parallel\\_sfs} can\nbe run as before. \n\n\\section{Insights for getting the most of SfS}\n\\label{sfs:insights}\n\nHere are a few suggestions we have found helpful when running \\texttt{sfs}:\n\n\\begin{itemize}{}\n\n\\item First determine the appropriate smoothing weight $\\mu$ by running a\nsmall clip, and using just one image. A value between 0.06 and 0.12 seems to work \nall the time with LRO NAC, even when the images are subsampled. The other weight, $\\lambda,$ can\nbe set to something small, like $0.0001.$ This can be increased to $0.001$ if noticing\nthat the output DEM strays too far. \n\n\\item As stated before, more images with more diverse illumination conditions\nresult in more accurate terrain. Ideally there should be at least 3 images, with the shadows\nbeing, respectively, on the left, right, and then perhaps missing or small. \n\n\\item Bundle-adjustment for multiple images is crucial, to eliminate\n  camera errors which will result in \\texttt{sfs} converging to a local\n  minimum. This is described in section \\ref{sfs-lola}.\n\n\\item Floating the albedo (option \\texttt{-\\/-float-albedo}) can\n  introduce instability and divergence, it should be avoided unless\n  obvious albedo variation is seen in the images.\n\n\\item Floating the DEM at the boundary (option\n  \\texttt{-\\/-float-dem-at-boundary}) is also suggested to be avoided.\n\n\\item Overall, the best strategy is to first use SfS for a single image\n  and not float any variables except the DEM being optimized, and then\n  gradually add images and float more variables and select whichever\n  approach seems to give better results.\n\n\\item If an input DEM is large, it may not be completely covered by a\nsingle set of imagery with various illumination conditions.  It should\nthen be broken up into smaller regions (with overlap), the SfS problem\ncan be solved on each region, and then every output terrain can be\ntransformed using \\texttt{pc\\_align} into LOLA's global coordinate\nsystem, where they can be mosaicked together using\n\\texttt{dem\\_mosaic}. Or, \\texttt{sfs} can be run not on one clip, but\non an entire collection of clips covering this area to get the\nadjustments, and then \\texttt{parallel\\_sfs} can be run as described in\nthe previous section. \n\n  The easier case is when at least the two images in the stereo pair\n  cover the entire terrain. Then, portions of this terrain can be used\n  as an initial guess for each SfS sub-problem (even as the other images\n  used for SfS change), the results can be mosaicked, and the alignment\n  to LOLA can happen just once, after mosaicking. This approach is\n  preferable, if feasible, as alignment to LOLA is more accurate if the\n  terrain to align is larger in extent.\n\n\\item The \\texttt{mapproject} program can be used to map-project each image\nonto the resulting SfS DEM (with the camera adjustments solved using\nSfS). These orthoimages can be mosaicked using \\texttt{dem\\_mosaic}. If the\n\\texttt{-\\/-max} option is used with this tool, it create a mosaic with\nthe most illuminated pixels from this image. If during SfS the camera\nadjustments were solved accurately, this mosaic should have little or no\nblur. An alterantive is to use the \\texttt{-\\/-block-max} option\nwhich will pick the most lit of the images per each block, with the latter\nbeing specified via \\texttt{-\\/-block-size}. \n\\end{itemize}\n", "meta": {"hexsha": "1673d673103dafb0995dae21db815621bf10a3f5", "size": 30437, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/book/sfs.tex", "max_stars_repo_name": "fenglang12345/asp20", "max_stars_repo_head_hexsha": "565894567b58ecb72385e7bb698e318a734bed5a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/book/sfs.tex", "max_issues_repo_name": "fenglang12345/asp20", "max_issues_repo_head_hexsha": "565894567b58ecb72385e7bb698e318a734bed5a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/book/sfs.tex", "max_forks_repo_name": "fenglang12345/asp20", "max_forks_repo_head_hexsha": "565894567b58ecb72385e7bb698e318a734bed5a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-04T14:34:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-04T14:34:23.000Z", "avg_line_length": 50.0608552632, "max_line_length": 124, "alphanum_fraction": 0.7573348227, "num_tokens": 8373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241911813151, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.34716737140727527}}
{"text": "\\section{Interpretation and Discussion of the Results}\n%In this section, first the challenges of the given problem are summarized and an ideal model to solve the problem is defined. Second, all properties of the ideal model are discussed with the relation to selected models and their performance. Last but not the least, conclusion is made on which of the three models is the best for classification of glass fragments.\n\n\\subsection{Classification Challenges and the Ideal Classifier}\nBuilding a good model to accurately predict glass fragments from a data set of $214$ data points turned out to be demanding. The core challenges were:\n\n%\\vspace{10pt}\n\\begin{enumerate}\n    \\item Little amount of data for 6-class classification problem\n    \\item Skewed class distribution \n    \\item Class overlap\n\\end{enumerate}\n%\\vspace{10pt}\n\nIn the light of the model being used in criminal investigation processes, an ideal model would be transparent in a way that the decision-making is comprehensible for humans. Furthermore, the model should be well-suited to tackle the challenges mentioned.\n\n\n%Before a discussion of particular models, it is important to highlight the main challenges of the given classification problem and based on it define ideal model. First, certain classes of glass, such as $1$, $2$ and $3$, had a large overlap given its similar features. This implies a need for a complex model capable of handling such overlap and still being able to generalize well. Second, distribution of classes within the training and test split of data was skewed. Thus, minority classes might be very hard to predict. This goes hand in hand with the size of the training data-set which was only 149 records. Therefore, optimal model should be able to learn even from a small training data-set. Last but not the least, since the output of the model might be used as part of crime analysis, ideal model should be also interpretable, i.e. it should be clear how it decides.\n\n\\subsection{Comparison of Model Performances}\nThe three models evaluated within this project can be ranked by their performance (measured by the expected out-of-sample accuracy) as follows:\n\n\\begin{enumerate}\n    \\item \\class{RandomForestClassifier()}\n    \\item \\class{NeuralNetworkClassifier()}\n    \\item \\class{DecisionTreeClassifier()}\n\\end{enumerate}\n\nLooking at the individual classification reports, all models were able to almost perfectly predict class $7$ which goes hand in hand with the findings from the EDA and Figure \\ref{pca}. In contrast, the prediction of the overlapping classes 1, 2 and 3 turned out to be generally challenging. In order to classify these classes correctly, the model needed to establish a complex decision boundary, that at the same time generalises well. The \\class{RandomForestClassifier()} did the best job at separating the classes 1 and 2 from each other (Table \\ref{random_forest_evaluation}), giving one indication of its overall good performance. The \\class{DecisionTreeClassifier()} struggled the most at separating the overlapping classes (Table \\ref{dt_evaluation}). \nAnother noticeable, common pattern from the classification reports is that the minority classes were generally more difficult to predict. That is reasonable, since a lack of training examples makes it difficult to learn class-specific properties.\n\n\\subsection{Interpretation of Model Performances}\nThe \\class{RandomForestClassifier()}, being an ensemble of a large number of, uncorrelated decision trees, as well as the \\class{NeuralNetworkClassifier()} are complex models, with longer training times, but more accurate predictions. This explains, why both models outperform the simpler \\class{DecisionTreeClassifier()}. \nThe fact that the \\class{RandomForestClassifier()} gives better results than the \\class{NeuralNetworkClassifier()} is probably due to the fact that neural networks usually need larger amounts of training data to give good results. In fact, neural networks perform best on complex classification problems with large amount of data to learn from. Since this classification problem is quite the opposite of that, the neural network is not performing as well as the \\class{RandomForestClassifier()}.\n\n%- 1. difference between high performant, but slow/ less performant, but fast\n%- 2. neural net not as good, because usually needs more data points\n\n%- 3. however, when choosing a model, dt might stil be intersting, since transparent model (main advantage not only speed, but also interpretability)\n\n\\begin{comment}\nFirst, all models were able to almost perfectly predict class $7$ which goes hand in hand with the findings from EDA and figure $2$ where even using only first two principal components, it was possible to see the clear separation of class $7$ from others. Second, more challenging proved to be a prediction of classes $1$ and $2$. In order to classify them correctly, the model needed to establish complex decision boundary. From this perspective, it was expected that \\class{DecisionTreeClassifier()} will perform the worst as it can only divide feature space with straight boundaries. This expectation was wrong as \\class{NeuralNetwork()} (both implementations) had similar results. One possible explanation is that \\class{NeuralNetwork()} got stuck in a local minimum during training and even advanced optimizer (Adam) did not help to overcome this. More interestingly, \\class{RandomForestClassifier()} performed way better than the other two models. Its core advantage is concealed in its ability to rely on a majority vote of a large and diverse set of \\class{DecisionTreeClassifier()} trained only on a subsample of original data. Thanks to this diversity, it is capable of fitting complex patterns but even more importantly generalize well. In other words, it is less likely to make an error due to small variation in data.\n\n\\subsection{Learning from a small data set}\nIn the given data-set, there were three minor classes, namely $3$, $5$ and $6$. From EDA (Figure 3), it was clear that it will be very hard to classify them correctly as they all overlapped with the other majority classes. This proved to be a problem especially for \\class{DecisionTreeClassifier()}. A good explanation can be found from its visualization and following the splits of class 3 for example. In majority of cases (3 out of 5), it ends being in a leaf node either with class 1 or 2 with which it has a large overlap. Further, the nodes are almost pure, thus the model has no further incentive to split it. In addition, since these classes have more records, they are also more likely to be predicted. Finally, compare to other two methods, \\class{NeuralNetwork()} is parametric and given the chosen architecture, it has a large number of parameters to be tuned. Therefore, it also needs a larger training data-set in order for it to work well. This might be a possible explanation why it outperformed by \\class{RandomForestClassifier()} for prediction of classes $1$ and $2$.\n\n%\\subsection{Interpretability}\n%\\class{DecisionTreeClassifier()}'s core advantage compare to the other two models is that its decision can be simply translated into just if-else statements. For example, can see that within its first two levels (root is level 1), it only uses first or second principal component to decide. This in fact makes sense as the first two components explain most of the variability of the given features and thus it is a good way to separate the classes. On the opposite site, trying to understand how a \\class{RandomForestClassifier()} decided is way more difficult and infeasible as it would require to go through all the 100 trees.\n\\end{comment}\n\n\\subsection{Conclusion}\nThe analysis has shown that a model chosen solely on the basis of best performance (\\class{RandomForestClassifier()}) has an expected out-of-sample performance of over 80\\%, which is a solid result given the challenges of the problem at hand. However, in the light of the model being used in assisting criminal investigations, transparency in the way decision are being made might be relevant, i.e. in court trials. Thus, if interpretability of the model is a core requirement for the final model, a  \\class{DecisionTreeClassifier()} should be considered.", "meta": {"hexsha": "422af1f19b83b7ad2c35b1b6a3b03f9f128997c2", "size": 8237, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/06_results_discussion.tex", "max_stars_repo_name": "jonas-mika/ml-project", "max_stars_repo_head_hexsha": "c052c33010033cd9fd596eb5ac4d270d1bf98ee3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "report/06_results_discussion.tex", "max_issues_repo_name": "jonas-mika/ml-project", "max_issues_repo_head_hexsha": "c052c33010033cd9fd596eb5ac4d270d1bf98ee3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/06_results_discussion.tex", "max_forks_repo_name": "jonas-mika/ml-project", "max_forks_repo_head_hexsha": "c052c33010033cd9fd596eb5ac4d270d1bf98ee3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-29T17:23:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-29T17:23:15.000Z", "avg_line_length": 158.4038461538, "max_line_length": 1330, "alphanum_fraction": 0.7983489134, "num_tokens": 1714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.6261241842048093, "lm_q1q2_score": 0.34716736753900884}}
{"text": "\\documentclass{article}\n\\usepackage[T1]{fontenc}%\n\\usepackage[utf8]{inputenc}%\n\\usepackage{lmodern}%\n\\usepackage{textcomp}%\n\\usepackage{lastpage}%\n\\input{common_symbols_and_format.tex}\n\n\n\\begin{document}\n\\logo\n\\rulename{Simple Moving Averages}\n\\tblofcontents\n\n\\ruledescription{\nThese representations have the position dependent on comparing two moving average windows one is short and the other is Long when the short window average length $\\averagelengthshort$ is greater than the long one average length $\\averagelengthlong$ so the model will go for the long position and when the short $\\averagelengthshort$ is less than the long one $\\averagelengthlong$, the position will be short}\n\\\\\n\n\\ruleparameters\n{Long Window size}{10}{This is the number of time steps over which exponential contributions are sourced}{$\\averagelengthlong$}\n{Short Window Size}{5}{This is the decay factor that reduces older contributions from the price series}{$\\averagelengthshort$}\n\\stoptable\n\\section{Equation}\n\\begin{equation}\n\\sum_{\\dummyiterator}^{\\averagelengthlong} \\price_{\\currenttime - \\dummyiterator} \\\\\n\\label{eq1}\n\\end{equation}\n\n\\begin{equation}\n\\sum_{\\dummyiterator}^{\\averagelengthshort} \\price_{\\currenttime - \\dummyiterator} \\\\\n\\label{eq2}\n\\end{equation}\n\n\\[ \\position_\\currenttime = \\begin{cases} \\mbox{1,} & \\mbox{if } equ.\\ref{eq2}>equ.\\ref{eq1} \\\\ \\mbox{0,} & \\mbox{if } equ.\\ref{eq1}>equ.\\ref{eq2} \\end{cases} \\]\n\n\n\\hspace{200mm}\n\nwhere $\\price_\\currenttime$ is the price at time $\\currenttime$,\n\n\\hspace{200mm}\n\\hspace{200mm}\n\n\\keyterms\n\\furtherlinks %The footer\n\\end{document}\n", "meta": {"hexsha": "9d27b534beb8292f8fe98a502959edc509627d94", "size": 1581, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/strategies/tex/SimpleMovingAverage.tex", "max_stars_repo_name": "SaurabhBansalInferstat/infertrade", "max_stars_repo_head_hexsha": "ee72d72cec54b2d29243f23dd0b6d9caf5dc49e8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-07T14:40:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-07T14:40:51.000Z", "max_issues_repo_path": "docs/strategies/tex/SimpleMovingAverage.tex", "max_issues_repo_name": "GirijaDas9/infertrade", "max_issues_repo_head_hexsha": "9245eaae202aea997e62d4eeb299f70516da35e0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/strategies/tex/SimpleMovingAverage.tex", "max_forks_repo_name": "GirijaDas9/infertrade", "max_forks_repo_head_hexsha": "9245eaae202aea997e62d4eeb299f70516da35e0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6382978723, "max_line_length": 408, "alphanum_fraction": 0.7621758381, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.6261241842048093, "lm_q1q2_score": 0.34716736753900884}}
{"text": "\\documentclass[a4paper, 11 pt, article, accentcolor=tud7b]{tudreport}\n\n\\usepackage[utf8]{inputenc}\n\\usepackage{amsmath}\n\\usepackage{placeins}\n\\usepackage{tabularx}\n\\usepackage{subcaption}\n\n\\title{CNuVS Exercise 9}\n\\author{Nils Rollshausen, Daniel Drodt}\n\\subtitle{Nils Rollshausen, Daniel Drodt}\n\n\\begin{document}\n\t\\maketitle\n\t\\section{TCP Congestion control}\n\t\\subsection*{a) Congestion control vs flow control}\n\tFlow control intends to protect the receiver from overload while congestion control protects the network. TCP specifically uses a window-based approach to congestion control.\n\t  \n\t\\subsection*{b) Congestion window}\n\tThe amount added to the congestion window with each ack is given as $inc = MSS \\cdot \\frac{MSS}{window}$. So, on the first acknowledgement, we increment the window by $1320 \\cdot \\frac{1320}{13200} = 132$ bytes to $13332$ bytes. On the second ack, we increment by $1320 \\cdot \\frac{1320}{13332} = 130.69$ byte to a new congestion window of $13462.69$ byte.\n\t\n\t\\subsection*{c) Slow start}\n\tAfter establishing a connection or pausing the connection when congestion is detected, it would take a long time for TCP to incrementally adjust the congestion window to its proper value. To speed this process up, the congestion window is increased exponentially (as opposed to linearly in the regular congestion avoidance phase) until the desired window size is reached (half the previous window if a packet loss has been detected) or a packet is lost.\n\t\n\t\\section{Three-Way-Handshake}\n\t\n\t\\subsection*{a) Handshake}\n\tThe three-way-handshake consists of the initiating party sending a SYN packet to the receiving party. The receiving party responds to the SYN request with a SYN-ACK packet acknowledging the receipt of the SYN request. Finally, the initiating party acknowledges the receipt of the SYN-ACK with an ACK packet.\n\t\n\t\\subsection*{b) TCP Segment}\n\t\n\tIn addition to the fields already given, the TCP header contains the following values:\n\t\n\t\\begin{table}[h]\n\t  \\centering\n\t  \\begin{tabular}{|l|l|}\n\t    \\hline\n\t    Source port & 0x076c \\\\ \\hline\n\t    Destination port & 0x07cd \\\\ \\hline\n\t    Data offset & 0x5 \\\\ \\hline\n\t    Checksum & 0x3c8f \\\\ \\hline\n\t  \\end{tabular}\n\t  \\caption{Remaining TCP header fields}\n\t\\end{table}\n\t\n\tThe application data is \\verb|0x4e6f 7274 6865 726e 204c 6967 6874 7300|. The checksum is calculated as the inverse two's-complement sum as follows: \n\t\n\t\\begin{align*}\n\t  0xFFFF - (&0x076c + 0x07cd + 0x0000 + 0x1337 + 0x0000 + 0x0000 \\\\\n\t            &+ 0x5020 + 0x5000 + 0x0000 + 0x0000 + 0x4e6f + 0x7274 \\\\\n\t            &+ 0x6865 + 0x726e + 0x204c + 0x6967 + 0x6874 + 0x7300) \\\\\n\t          = &0xFFFF - 0xC370 = 0x3C8F\n\t\\end{align*}\n\t\n\t\\newpage\n\t\n\t\\subsection*{c) TCP header fields}\n\t\n\t\\begin{table}[h]\n\t  \\centering\n\t  \\begin{tabularx}{\\linewidth}{|l|X|}\n\t    \\hline\n\t    Source port & The port from which the packet is sent \\\\ \\hline\n\t    Destination port & The port to which the packet is sent \\\\ \\hline\n\t    Sequence number & Sequence number of the packet, corresponds to bytes already sent \\\\ \\hline\n\t    Acknowledgement number & If the ACK flag is set, this acknowledges the receipt of all bytes up to the acknowledgement number \\\\ \\hline\n\t    Data offset & The length of the header in 32 bit words, used to determine where the payload starts \\\\ \\hline\n\t    Reserved & Reserved bits intended for future extensions of the protocol \\\\ \\hline\n\t    URG & Indicates that the Urgent Data Pointer field is valid and should be considered \\\\ \\hline\n\t    ACK & Indicates that the acknowledgement number is valid \\\\ \\hline\n\t    PSH & Indicated that received data should be pushed to the receiving process immediately \\\\ \\hline\n\t    RST & Resets the connection \\\\ \\hline\n\t    SYN & Indicates a connection request \\\\ \\hline\n\t    FIN & Indicates a connection termination \\\\ \\hline\n\t    Window Size & The amount of bytes the sender of the packet is currently willing to receive, starting at the value in the acknowledgement field \\\\ \\hline\n\t    Checksum & The 16bit twos-complement checksum over the entire packet \\\\ \\hline\n\t    Urgent Pointer & If URG is set, this indicates that the first n bytes from the message start are urgent \\\\ \\hline\n\t  \\end{tabularx}\n\t  \\caption{TCP header fields}\n\t\\end{table}\n\t\n\t\\subsection*{d) Retransmission}\n\t\\begin{figure}[h]\n    \\begin{subfigure}[b]{0.3\\textwidth}\n      \\includegraphics[width=\\textwidth]{retrans1.png}\n      \\caption{Lost ACK}\n      \\label{fig:1}\n    \\end{subfigure}\n    %\n    \\begin{subfigure}[b]{0.3\\textwidth}\n      \\includegraphics[width=\\textwidth]{retrans2.png}\n      \\caption{Premature Timeout}\n      \\label{fig:2}\n    \\end{subfigure}\n    %\n    \\begin{subfigure}[b]{0.3\\textwidth}\n      \\includegraphics[width=\\textwidth]{retrans3.png}\n      \\caption{Cumulative ACK}\n      \\label{fig:2}\n    \\end{subfigure}\n  \\end{figure}\n\tWhen an ACK packet is lost, the sender would, after a timeout, consider the packet whose acknowledgement got dropped to be lost and re-send it. The receiver recognizes the re-sent packet as a duplicate, discards it, and responds with an up-to-date acknowledgement.\n\t\n\t\\FloatBarrier\n\t\n\t\\section{RED, State Chart \\& Nagle}\n\t\n\t\\subsection*{a) Random Early Detection}\n\tRandom Early Detection is necessary for routers and other network equipment to signal to end nodes that they are running close to their maximum capacity. As the routers should be agnostic to the choice of transport protocol, there is no protocol-inherent mechanism for them to communicate their capacity. As a solution, routers communicate implicitly by randomly dropping packets when running close to maximum load to reduce the network load before actually running completely out of capacity, which would lead to heavy congestion.\n\t\n\t\\subsection*{TIME\\_WAIT and ESTABLISHED}\n\tThe TIME\\_WAIT state is used by the party terminating a connection to ensure that the other party was able to terminate the connection properly (i.e. it received the acknowledgement to its FIN). A duplicate received FIN in this state indicates that the previous ACK was lost and should be retransmitted. After a sufficient amount of time passes, it can be assumed that no such duplicate FIN will arrive and the remote party was able to terminate the connection. \\\\ \\medskip\n\tThe ESTABLISHED state is the normal state of a TCP connection in which both parties have established the connection and are able to send and receive data.\n\t\n\t\\subsection*{c) Nagle's Algorithm}\n\tNagle's Algorithm deals with the problem network congestion caused by acknowledging small amounts of data and thus creating very high network overhead for comparatively little data. It states that data should only be sent if either the amount of data to send is larger or equal to the maximum segment size or there is no unacknowledged data packet still in-flight to the receiver. Using this algorithm, non-full packets are only sent when it is assumed that the receiver is currently idle.\n\t\n\t\\end{document}\n", "meta": {"hexsha": "a4641b89e697ec966edbae00fc8e85ff5fdc9a95", "size": 6948, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ex9/ex9.tex", "max_stars_repo_name": "rec0de/CNuVS19", "max_stars_repo_head_hexsha": "52d07fe5c4380af707c63f718aa9533044224a3e", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ex9/ex9.tex", "max_issues_repo_name": "rec0de/CNuVS19", "max_issues_repo_head_hexsha": "52d07fe5c4380af707c63f718aa9533044224a3e", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ex9/ex9.tex", "max_forks_repo_name": "rec0de/CNuVS19", "max_forks_repo_head_hexsha": "52d07fe5c4380af707c63f718aa9533044224a3e", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 58.3865546218, "max_line_length": 532, "alphanum_fraction": 0.7443868739, "num_tokens": 1809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.6261241842048092, "lm_q1q2_score": 0.3471673675390088}}
{"text": "\\documentclass[11pt,a4paper]{article}\n\\usepackage[english]{babel}\n\\usepackage[utf8]{inputenc}\n\\usepackage{amsmath}\n\\usepackage{fourier}\n\\usepackage{yfonts}\n\\usepackage[hmargin=3cm,vmargin=2.4cm]{geometry}\n\\usepackage[colorlinks=true]{hyperref}\n\\usepackage{fancyhdr}\n\n\\pagestyle{fancy}\n\\fancyhead{}\n\\fancyhead[L]{\\href{https://www-ljk.imag.fr/membres/Pierre.Karpman/cry\\_eng2017\\_td\\_hf.pdf}{https://www-ljk.imag.fr/membres/Pierre.Karpman/cry\\_eng2017\\_td\\_hf.pdf}}\n\n\n\\DeclareMathOperator\\hash{\\mathcal{H}}\n\\DeclareMathOperator\\E{\\mathcal{E}}\n\\DeclareMathOperator\\comp{\\textswab{f}}\n\\DeclareMathOperator\\cat{\\mathrm{CAT}}\n\\DeclareMathOperator\\pmm{\\mathrm{PM}}\n\\DeclareMathOperator\\smm{\\mathrm{SM}}\n\\DeclareMathOperator\\sand{\\mathrm{SANDWICH}}\n\n\\title{Crypto Engineering (GBX9SY03)\\\\\nTD Hash functions}\n\\date{2017-10-18}\n\n\\begin{document}\n\n\\maketitle{}\n\n\\subsection*{Exercise 1: Multicollisions for Merkle-Damg\\aa rd hash functions}\nIn 2004, Joux showed a simple attack illustrating the fact that Merkle-Damg\\aa rd hash functions were not ``ideal''. This attack consists in computing a collision on many\n(more than two) messages, i.e. finding $m_0$, $m_1$, $\\ldots$, $m_q$ that all have the same hash, more efficiently than what is possible for a random oracle.\\\\\n\\emph{In this exercice, we can safely ignore padding issues.}\n\n\\paragraph{Q. 1:} We assume that the expected number of collisions in the elements of two lists $L_0$ and $L_1$ of random $n$-bit elements is $\\approx \\#L_0\\times\\#L_1/2^n$.\nLet $\\hash : \\{0,1\\}^* \\rightarrow \\{0,1\\}^n$ be a random oracle; what is the expected complexity of finding an $r$-collision for $\\hash$?\\\\\n{\\footnotesize Hint: try to find the optimal balance in the list sizes for the case $r = 3$, and generalize the formula.}\n\n\\paragraph{Q. 2:}  Recall the structure of a Merkle-Damg\\aa rd hash function\n$\\hash : \\{0,1\\}^* \\rightarrow \\{0,1\\}^n$ based on a compression function $\\comp : \\{0,1\\}^n \\times \\{0,1\\}^b \\rightarrow \\{0,1\\}^n$.\nLet $m$, $m'$ be two messages such that $|m| = |m'| = b$.\nExplicit the relation between $\\hash(m)$, $\\hash(m||m')$ and $\\comp$.\n\n\\paragraph{Q. 3} Take $\\hash$ as in Q.~2. Let $m_0$ and $m'_0$ be two one-block messages colliding through $\\hash$ (i.e. $h_0 :=\n\\hash(m_0) = \\comp(\\text{IV}, m_0) = \\hash(m'_0) = \\comp(\\text{IV}, m'_0)$). Assuming $\\comp$ is ideal, how efficiently can you compute a collision\n($m_1$, $m'_1$) for $\\comp(h_0, \\cdot)$? Once you know such a collision, how many messages colliding with $\\hash(m_0||m_1)$ can you easily (i.e. in\nconstant time) create? Conclude about the cost of\ncomputing a $2^r$-collision for $\\hash$ and why Merkle-Damg\\aa rd hash functions are not ideal.\n\n\\paragraph{Q. 4} The \\emph{concatenation combiner} is a simple construction taking two hash functions $\\hash_1$ and $\\hash_2$ and defined as\n$\\cat_{\\hash_1,\\hash_2}(m) := \\hash_1(m)||\\hash_2(m)$. Assuming $\\hash_1$ and $\\hash_2$ have an output size of $n$ bits and follow the Merkle-Damg\\aa rd construction,\nhow efficiently can you compute a collision for $\\cat_{\\hash_1, \\hash_2}$? Is it possible to significantly improve the collision-resistance of SHA-1 by using\n$\\cat_{\\text{SHA-1}, \\text{MD5}}$?\n\n\n\\subsection*{Exercise 2: Davies-Meyer fixed-points}\nIn this exercise, we will see one reason why \\emph{Merkle-Damg\\aa rd strengthening} (adding the length of a message in its padding) is necessary\nin some practical constructions.\n\n\\paragraph{Q. 1} Recall the ``Davies-Meyer'' construction of a compression function $\\comp$ from a block cipher~$\\E$.\n\n\\paragraph{Q. 2} Considering the feed-forward structure of Davies-Meyer, under what conditions would you obtain a fixed-point for such a compression function?\n\n\\paragraph{Q. 3} Show how to compute the (unique) fixed-point of $\\comp(\\cdot,m)$ for a fixed $m$. Given $h$, is it easy to find $m$ such that it is a fixed-point,\nif $\\E$ is an ideal block cipher?\n\n\\paragraph{Q. 4} A \\emph{semi-freestart collision attack} for a Merkle-Damg\\aa rd hash function $\\hash$ is a triple $(h, m, m')$ s.t. $\\hash_h(m) = \\hash_h(m')$,\nwhere $\\hash_h$ denotes the function $\\hash$ with its original IV replaced by $h$.\nShow how to use a fixed-point to efficiently mount such an attack for Davies-Meyer + Merkle-Damg\\aa rd, when strengthening is not used.\n\n\\paragraph{Note:} Fixed-points of the compression function can be useful to create the \\emph{expandable messages} used in second preimage attacks on Merkle-Damg\\aa rd.\n\n\n\\subsection*{Exercise 3: Meet-in-the-middle preimage attack on BRSS/PGV-13 + MD}\nBRSS/PGV-13 is an alternative to Davies-Meyer, defined as $\\comp(h,m) = \\E(m,h) \\oplus c$ for a cipher $\\E$ and with $c$ a constant.\nIt can be shown in the ideal cipher model that\na Merkle-Damg\\aa rd function with such a compression function is secure up to the birthday bound for both collision \\emph{and} preimage attacks (Black \\& al., 2010).\n\n\\paragraph{Q. 1} If $\\E$ is ideal, what is the complexity, given $h$ and $t$, of finding $m$ such that $\\comp(h, m) = t$? Conclude about the preimage security\nof $\\comp$ itself.\n\n\\paragraph{Q. 2} Show how to compute a two-block preimage for $\\hash$ with the above compression function, using a\nmeet-in-the-middle attack, and roughly evaluate its complexity (both time and memory).\n\n\\paragraph{Q. 3} Give a rough explanation of how the attack of Q.~2 is prevented when using a Davies-Meyer compression function.\n\n\\subsection*{Exercise 4: Hash-based message-authentication codes}\n\n\\paragraph{Q. 1} Recall the definition of a message-authentication code (MAC), existential forgery, and universal forgery.\n\n\n\\paragraph{Q. 2} Let us first assume that $\\hash$ is a random oracle. Explain (roughly) why the ``prefix-MAC'' construction\n$\\pmm_{\\hash}(k, m) := \\hash(k||m)$ is secure? Is there a difference with the ``suffix-MAC'' variant $\\smm_{\\hash}(k, m) := \\hash(m||k)$?\n\n\\paragraph{Q. 3} Now assume that $\\hash$ is a Merkle-Damg\\aa rd hash function. Suppose I know $m$ and its tag $t := \\pmm_{\\hash}(k, m)$,\nand that the size of $k$ is known. How easily can I compute another message and its corresponding tag under $\\pmm_{\\hash}(k, \\cdot)$? Is this\nMAC secure against existential forgery?\n\n\\paragraph{Q. 4} Still assuming that $\\hash$ is a Merkle-Damg\\aa rd function, show how collisions on $\\hash$ lead to an existential forgery attack\nof $\\smm_{\\hash}$. What is the expected complexity of this attack for an otherwise secure $\\hash$? Is this better than what you would expect for a ``good'' MAC?\n\n\\paragraph{Q. 5} Is it reasonable to instantiate prefix/suffix-MAC with SHA-3? With SHA-256? With SHA-512/256?\n\n\\paragraph{Note:} It can be proven (Yasuda, 2007) that, using appropriate padding rules, the ``Sandwich-MAC'' construction $\\sand_{\\hash}(k,m) := \\hash(k||p||m||p'||k)$\n(where $p$ and $p'$ denote padding) is secure, without requiring $\\hash$ to be a random oracle (in particular, it can be built with a Merkle-Damg\\aa rd construction).\n\n\\end{document}\n", "meta": {"hexsha": "9c29f5960f9573abb20c94224fd394fc132e6485", "size": 6927, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "CRY-M2-ENG/2017/TD/td_hf.tex", "max_stars_repo_name": "P1K/LectureNotes", "max_stars_repo_head_hexsha": "7a2a2e912afe9b1eff01430194761f4ae1bc65c5", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-10-18T06:00:24.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-18T06:00:24.000Z", "max_issues_repo_path": "CRY-M2-ENG/2017/TD/td_hf.tex", "max_issues_repo_name": "P1K/LectureNotes", "max_issues_repo_head_hexsha": "7a2a2e912afe9b1eff01430194761f4ae1bc65c5", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CRY-M2-ENG/2017/TD/td_hf.tex", "max_forks_repo_name": "P1K/LectureNotes", "max_forks_repo_head_hexsha": "7a2a2e912afe9b1eff01430194761f4ae1bc65c5", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 62.9727272727, "max_line_length": 173, "alphanum_fraction": 0.7278764256, "num_tokens": 2117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.34716736367074236}}
{"text": "\\documentclass[a4paper]{letter}\r\n\\usepackage{hyperref}\r\n\\usepackage{color}\r\n\r\n\\title{Tutorial in Computational Science using Visual Python}\r\n\r\n\\begin{document}\r\n\\definecolor{code}{cmyk}{1,0,1 ,.5}\r\n\r\n\r\n\r\n\\section{Introduction to Visual python: Simple motion}\r\nThe first section of the tutorial introduces you to programming in visual python by stepping \r\nthrough a program to display a ball bouncing around inside a box.  \r\nThis program will later be a modified to become a simulation of an ideal gas.\r\n\\subsection{Your First Program}\r\nStart IDLE by clicking on the snake icon on the panel at the bottom of your desktop. \r\nA window labeled 'Untitled' should appear. \r\nThis is the window in which you will type your program.\r\nType the following statements \r\n(You can select the text below and then paste it into IDLE using the middle mouse button.):\r\n{\\color{code}\r\n\\begin{verbatim}\r\nfrom visual import * # This instructs Python to use the Visual graphics module\r\n \r\nwallR = box(pos=vector(6,0,0),size=vector(0.2,4,4),color=color.green) \r\n#opens a window for displaying graphics and creates a thin green slab  \r\n#in it which we can refer to later as wallR\r\nball = sphere(pos=vector(-5,0,0), radius=0.5, color=color.red)\r\n#creates a red sphere and names it ball\r\n\\end{verbatim}}\r\nIDLE will colour different sections of the program to make it easier to read.\r\nFor example comment lines, which begin with the \\# symbol are red.\r\nThe functions {\\color{code}sphere} and {\\color{code}box} are 'constructors' for 3D objects. \r\nThe position of an object's centre is specified in three dimensions \r\nusing a vector.\r\n\r\nSave your program as 'firstprogram.py' by choosing 'save as' from the file menu.\r\n\r\n\\subsection{Running the Program}\r\nNow run your program by choosing 'Run program' from the 'Run' menu. \r\nWhen you run the program, two new windows appear. \r\nThere is a window titled 'VPython,' in which you should see a red sphere, \r\nand a window titled 'Output'. \r\n\r\nIn the VPython window, hold down the middle mouse button and move the mouse. \r\nYou should see that you are able to zoom into and out of the scene. \r\nNow try holding down the right mouse button . \r\nYou should find that you are able to rotate your view of the scene.   \r\n\r\nYou can stop the program by choosing 'Stop program' from the run menu.\r\n\r\n\\subsection{Objects and attributes}\r\nSphere and box are types of objects that visual python recognises and displays. \r\nThey have some attributes associated with them (such as \r\nposition({\\color{code}pos}), colour({\\color{code}color}) and \r\n{\\color{code}radius}) which can be set when you first define and name the object, \r\notherwise the default values will be used. \r\n\r\nYou can change the radius attribute of {\\color{code}ball} after it has been constructed \r\nwith the statement:\r\n{\\color{code}\\begin{verbatim}\r\nball.radius=0.5 \r\n\\end{verbatim}}\r\nYou can also add any new attributes you want to associate with the object, eg: \r\n{\\color{code}\\begin{verbatim}\r\nball.velocity=vector(2,.1,0) \r\n\\end{verbatim}}\r\n\r\n\\subsection{Moving Objects}\r\nTo move objects you will need a program loop that repeatedly updates the position. \r\nThis can be done with a while loop that repeats the indented lines of code following \r\nthe while statement, as long as the while condition remains true.\r\n\r\nAdd the following while loop to the bottom of your program to make the ball move according to the velocity you gave it earlier:\r\n{\\color{code}\\begin{verbatim}\r\ntimestep=0.05 \r\nball.velocity=vector(2,.1,0) \r\nwhile (1==1):\r\n    rate(20) \r\n    ball.pos=ball.pos + ball.velocity*timestep \r\n\\end{verbatim}}\r\nIn Python {\\small\\color{code}==} stands for 'is equal to' \r\nso the statement {\\small\\color{code}1==1} always has a value of true,\r\n and code inside the while loop will repeat forever. \r\nThe symbol {\\small\\color{code}=} is used for assignment, to set a new value for a variable. \r\n\r\nIn the above example the value of {\\color{code}ball.pos + ball.velocity*timestep} \r\nis calculated and then assigned as the new value for ball.pos. \r\nPython knows how to add vectors and how to multiply them by a scalar so you don't have \r\nto specify this element by element. \r\n\r\nThe rate statement specifies how many times each second the loop will be executed. \r\nIt allows you to control the animation speed so that the ball moves at the same speed \r\non faster computers.\r\n\r\nRun your program by choosing 'Run program' from the 'Run' menu.  \r\nYou should observe that the ball moves to the right. \r\nYou can change how fast either by changing the rate or the timestep. \r\n\r\n\\subsection{Making the ball bounce: Logical tests}\r\nTo make the ball bounce off the wall, we need to detect a collision between the ball and the wall. \r\nA simple approach is to compare the x coordinate of the ball to the x coordinate of the wall, \r\nand reverse the x component of the ball's velocity if the ball has moved too far to the right. \r\nThe components of vectors are attributes which can be referred to individually as .x, .y and .z.\r\nThe logical test we would use to detect a collision and reverse the velocity might look like: \r\n{\\color{code}\\begin{verbatim}\r\nif ball.x > wallR.x: \r\n    ball.velocity.x = -ball.velocity.x \r\n\\end{verbatim}}\r\nThe indented line after the if statement will be executed only if the \r\nlogical test in the previous line gives 'true' for the comparison. \r\nIf the result of the logical test is false \r\n(that is, if the x coordinate of the ball is not greater than the x coordinate of the wall), \r\nthe indented line will be skipped. \r\nSince we want this logical test to be performed every time the ball is moved, \r\nwe need to indent both of these lines so they are inside the while loop. \r\nYour program should now look like this: \r\n{\\color{code}\\begin{verbatim}\r\nfrom visual import * \r\n\r\n# create wall\r\nwallR = box(pos=vector(6,0,0), size=vector(0.2,4,4), color=color.green) \r\n#create a ball and define its velocity\r\nball = sphere(pos=vector(-5,0,0), radius=0.5, color=color.red) \r\nball.velocity = vector(2,.1,0) \r\n# set the timestep between position updates\r\ntimestep = 0.05 \r\nwhile (1==1): \r\n#the code within this while loop will be repeated 100 times per second\r\n    rate(100) \r\n    ball.pos = ball.pos + ball.velocity*timestep #move ball\r\n    if ball.pos.x > wallR.pos.x: #check for collision with wall\r\n        ball.velocity.x = -ball.velocity.x #reflect velocity at collision\r\n\\end{verbatim}}\r\nRun your program. \r\nYou should observe that the ball moves to the right, bounces off the wall,\r\nand then moves to the left, continuing off into space. \r\nNote that our test is not very sophisticated. \r\n{\\color{code}ball.x} is at the center of the ball \r\nand wallR.x is at the center of the wall so the ball penetrates the wall before it bounces. \r\n\r\nAdjust the position test so that the ball bounces when the edge of the balls reaches \r\nthe edge of the wall (ie when {\\color{code}ball.x + ball.radius == wallR.x-wallR.size.x/2}). \r\nFor a more realistic bounce you should reflect the position of the ball as well as its velocity. \r\nYou can add another wall at the left side of the display, and make the ball bounce off that wall also. \r\n\r\nYour program should now look something like the following: \r\n{\\color{code}\\begin{verbatim}\r\nfrom visual import * \r\n# create walls\r\nwallR = box(pos=vector(6,0,0), size=vector(0.2,4,4), color=color.green) \r\nwallL = box(pos=vector(-6,0,0), size=vector(0.2,4,4), color=color.green)\r\n# create a ball and define its velocity\r\nball = sphere(pos=vector(-5,0,0), radius=0.5, color=color.red)  \r\nball.velocity = vector(2,.1,0) \r\n# set the maximum and minimum position for the centre of the ball\r\nmax_xpos=wallR.pos.x-ball.radius-wallR.size.x/2 \r\nmin_xpos=wallL.pos.x+ball.radius+wallL.size.x/2 \r\n# set the timestep between position updates\r\ntimestep = 0.05 \r\n\r\nwhile (1==1): \r\n#the code within this while loop will be repeated 100 times per second\r\n    rate(100) \r\n    ball.pos = ball.pos + ball.velocity*timestep #move ball\r\n    if ball.x > max_xpos: #check for collision with right wall\r\n        ball.velocity.x = -ball.velocity.x #reflect velocity\r\n        ball.pos.x=2*max_xpos-ball.pos.x #reflect position\r\n    if ball.x < min_xpos: #check for collision with left wall\r\n        ball.velocity.x = -ball.velocity.x #reflect velocity\r\n        ball.pos.x=2*min_xpos-ball.pos.x #reflect position\r\n\\end{verbatim}}\r\nThis program makes a ball bounce backward and forward between two parallel walls. \r\nThe ball continues to bounce even when it has  passed the top of the walls. \r\n\r\nYou should be able to add and extend walls now so that the ball bounces inside a box. \r\nYou will want to have an invisible front wall so that you can see inside. \r\nPlay around with different starting positions and velocities for the ball, \r\nand sizes for the ball and box. \r\n\r\nIf you have trouble, or are short of time you can copy the example solution from the link below.\r\nThe next section is based on the solution to this exercise.\r\n%Example solution \\href{bounce2.py}{bounce2.py}\r\n%\\href{bounce2.html}{( html format )}\r\n\\href{bounce2.html}{ Example Solution }\r\n\r\n\\section{Simulating particle motion in a gas}\r\nIn this section you will extend the bouncing ball program so that it simulates the motion \r\nof atoms in a gas. \r\nThere will need to be many atoms in the box and they should bounce off each other as well\r\n as off the sides of the box.\r\nWe will need to set the initial distribution of atom positions and velocities, \r\nbut these distributions may evolve as the simulation progresses.\r\n\r\n\\subsection{Random numbers}\r\nYou can make the velocity of the ball different each time the program is run \r\nby using a random number generator. \r\nThe random number generator is not part of standard python and needs to be \r\nimported from the random module. \r\nThe random module contains random number generator for several different distributions. \r\nYou can import just a uniform distribution random number generator by inserting a line at \r\nthe beginning of the program (following the line {\\color{code}from visual import *}): \r\n{\\color{code}\\begin{verbatim}\r\nfrom random import uniform \r\n\\end{verbatim}}\r\nThe function {\\color{code}uniform(-1,1)} will give a random number between -1 and 1. \r\nYou can set a random ball velocity  by replacing the line setting the ball's velocity with: \r\n{\\color{code}\\begin{verbatim}\r\nmaxv=2. \r\nball.velocity=maxv*vector(uniform(-1,1),uniform(-1,1),uniform(-1,1))  \r\n\\end{verbatim}} \r\n\\subsection{Multiple balls: Using lists}\r\nTo simulate a gas we will need many particles inside the box. \r\nOne easy way of dealing with many particles is to put them into a list.\r\n \r\nReplace the section of code in which you created the ball \r\nand gave it velocity with the following code \r\n(it should be after the section defining the walls):\r\n{\\color{code}\\begin{verbatim}\r\nside=wallR.pos.x\r\nballradius=0.4\r\nthk=wallR.size.x\r\nmaxpos=side-thk/2-ballradius \r\nmaxv=2.0 \r\n\r\nball1=sphere(color=color.green,radius=ballradius) \r\nball1.pos=maxpos*vector(uniform(-1,1),uniform(-1,1),uniform(-1,1)) \r\nball1.velocity=maxv*vector(uniform(-1,1),uniform(-1,1),uniform(-1,1)) \r\n\r\nball2=sphere(color=color.green,radius=ballradius) \r\nball2.pos=maxpos*vector(uniform(-1,1),uniform(-1,1),uniform(-1,1)) \r\nball2.velocity=maxv*vector(uniform(-1,1),uniform(-1,1),uniform(-1,1)) \r\n\r\nball3=sphere(color=color.green,radius=ballradius) \r\nball3.pos=maxpos*vector(uniform(-1,1),uniform(-1,1),uniform(-1,1)) \r\nball3.velocity=maxv*vector(uniform(-1,1),uniform(-1,1),uniform(-1,1))\r\n\r\nballs=[ball1,ball2,ball3] \r\n\\end{verbatim}}\r\n\r\nThis gives a list containing three balls. Any type of object can go into a list. \r\nIn fact a list can be made up of several different types of object. \r\nIf you run the code now you will see three balls within the box but the section \r\nof code to move the ball no longer works.\r\n\r\nTo move all the balls in a list you use a {\\color{code}for} loop. \r\nIn python a {\\color{code}for} loop cycles through the elements of a list.\r\nThe loop to move all the balls in the list would look like:\r\n{\\color{code}\\begin{verbatim}\r\nwhile (1==1): \r\n    for ball in balls: \r\n        ball.pos = ball.pos + ball.velocity*timestep \r\n        if ball.pos.x > maxpos: \r\n            ball.velocity.x = -ball.velocity.x \r\n            ball.pos.x=2*maxpos-ball.pos.x \r\n                                   . . . \r\n\\end{verbatim}}\r\nThe code within the for loop is indented by two levels \r\nsince it is also inside the while loop (with code inside the if indented an additional level). \r\nYou can indent a whole section by selecting it and then choosing 'indent section' \r\nfrom the format menu.\r\n(Try running the program now to see three balls bouncing within your box)\r\n\r\nA for loop can also be used to set up the list of balls more efficiently. \r\nTo add each ball to the list {\\color{code}balls} use {\\color{code}balls.append(ball)}.\r\nThe construction of a for loop in python is slightly different from many \r\nother programming languages which cycle through a set of numbers. \r\nTo get the more usual counted for loop you use {\\color{code}range} to create a \r\nlist of integers between 0 and {\\color{code}no\\_particles-1}.\r\n\r\nRelplace the part of the code which created a list of three balls with this for loop \r\nwhich creates a list of ten balls. \r\nThe for loop which moves the balls in the list should still work perfectly.  \r\n{\\color{code}\\begin{verbatim}\r\nno_particles=10 \r\nside=wallR.pos.x\r\nballradius=0.4\r\nthk=wallR.size.x\r\nmaxpos=side-thk/2-ballradius \r\nmaxv=2.0 \r\nballs=[]\r\nfor i in range(no_particles): \r\n    ball=sphere(color=color.green,radius=ballradius) \r\n    ball.pos=maxpos*vector(uniform(-1,1),uniform(-1,1),uniform(-1,1)) \r\n    ball.velocity=maxv*vector(uniform(-1,1),uniform(-1,1),uniform(-1,1)) \r\n    balls.append(ball) \r\n\\end{verbatim}}\r\n\r\n\\subsection{Particle interactions}\r\nYou should now have a program that shows many particles bouncing around inside a box. \r\nAt the moment the balls are simply passing through each other \r\n(make the ball radius large to see this more clearly). \r\nFor this to be a realistic model of a gas the particles need to interact in some fashion. \r\n\r\nDifferent 'interaction potentials' could be used depending on the type of molecule making up \r\nthe gas. \r\nFor an ideal gas an appropriate interaction is 'hard sphere collisions' \r\n--- the balls bounce off each other the same way they bounce off the walls. \r\n\r\n\\subsubsection{Detecting a collision}\r\nAt each time step we need to check whether any particles have collided. \r\nFor each pair of particles we need to check whether the distance between \r\nthem is less than the sum of their radii. \r\nFor example add the following lines to the end of your program, \r\nafter you have updated the position of all the particles.  \r\nThe indentation should place it within the while loop but outside the other for loop.\r\n{\\color{code}\\begin{verbatim}\r\n    for ball in balls: \r\n        for otherball in balls:\r\n            if not ball == otherball:\r\n                distance=mag(otherball.pos-ball.pos) \r\n                if distance<(ball.radius+otherball.radius): \r\n                    print 'collision' , distance\r\n\\end{verbatim}}\r\n{\\color{code}mag} is a function that returns the size (magnitude) of a vector. \r\n\r\nRun your program.\r\nNotice that every time a pair of balls collide in the display window the word 'collision' \r\nis printed twice to the output window. \r\nThis is because the loop goes through every pair of balls twice. \r\nTo check each pair only once the second loop should only check against balls with \r\nhigher index than the first. To do this replace the collision detection code with: \r\n{\\color{code}\\begin{verbatim}\r\n    for i in range(no_particles): \r\n        for j in range(i+1,no_particles): \r\n            distance=mag(balls[i].pos-balls[j].pos) \r\n            if distance<(balls[i].radius+balls[j].radius): \r\n                print 'collision', distance \r\n\\end{verbatim}}\r\nNow when you run the program, 'collision' should be written once for each collision. \r\n  \r\n\\subsubsection{Exchanging momentum: more vector calculations}\r\nWhen two objects collide elastically (without losing energy) in one dimension they swap momentum. \r\nIf their masses are equal this means they should swap velocity. \r\nSince we are modelling the interaction between particles as hard spheres, \r\nwith no friction, the force at impact is only along the line joining the centres of the balls. \r\nThe balls exchange momentum in this direction, \r\nleaving the perpendicular velocity components unchanged. \r\nThe result is similar to the way billiard balls collide.\r\nThe section of code that detects a collision and swaps the velocity component of the two balls \r\nin the collision direction looks like:\r\n{\\color{code}\\begin{verbatim}\r\n    for i in arange(no_particles): \r\n        for j in arange(i+1,no_particles): \r\n            distance=mag(balls[i].pos-balls[j].pos) \r\n            if distance<(balls[i].radius+balls[j].radius): \r\n                direction=norm(balls[j].pos-balls[i].pos) \r\n                vi=dot(balls[i].velocity,direction) \r\n                vj=dot(balls[j].velocity,direction) \r\n                exchange=vj-vi \r\n                balls[i].velocity=balls[i].velocity+exchange*direction \r\n                balls[j].velocity=balls[j].velocity-exchange*direction \r\n\\end{verbatim}}\r\nThe function {\\color{code}norm} returns a vector with the same direction as the input \r\nbut with its magnitude normalised to one. \r\nThe function {\\color{code}dot} returns the dot product of the two input vectors, \r\nin this case the component of the ball's velocity that is in the collision direction. \r\n\r\nYou should now have a program that shows ten spheres bouncing around inside a box \r\nand bouncing off each other. \r\nYou might find that balls occasionally get stuck together, \r\nparticularly if three or more balls collide at the same time. \r\nThis problem is reduced by making the time step smaller. \r\nWe can also make the collisions more accurate, and stop balls sticking together, \r\nby adjusting the position of the balls after a collision, in much the same way we did \r\nfor collisions with the sides of the box. \r\n{\\color{code}\\begin{verbatim}\r\n                overlap=2*ballradius-distance \r\n                balls[i].pos=balls[i].pos - overlap*direction \r\n                balls[j].pos=balls[j].pos + overlap*direction \r\n\\end{verbatim}}\r\n%An example solution is at \\href{manybounce1.py}{manybounce1.py}\r\n% \\href{manybounce1.html}{(html version)}\r\n\\href{manybounce1.html}{Example solution} \r\n\r\n\\subsection{Program speed}\r\nThe program you have written shows a simple model of the behaviour of particles within a gas. \r\nPlay around with changing the number and size of particles and their average velocities. \r\nAs you add more particles the speed of the program slows down significantly. \r\nDoubling the number of particles may increase the time to run the program by four times. \r\nThis is because the number of steps to check for collisions increases as the square of the \r\nnumber of particles. \r\nMany computational science models which are based on interacting particles have this $N^2$ speed dependence.  \r\nModels with large numbers of particles need high speed computers and efficient programs. \r\n\r\nIncreasing the speed of a simulation program can make up a large part of the work of a \r\ncomputational scientist. \r\nTactics for improving the efficiency of a program include:\r\n\\begin{itemize}\r\n\\item{removing unneccessary calculations (eg the calculation of the distance between particles involves calculating a square root whch is quite slow. The comparison of particle separation for detecting collisions could be made just as easily with the square of the distance which is much quicker to calculate.)}\r\n\\item{Saving results of calculations instead of repeating them. }\r\n\\item{Using more efficient data constructions (eg the elements of lists in python are not necessarily all the same data type. This makes them flexible for many different programming tasks but the program takes longer to access this data. Python arrays have each element the same data type and are faster to work with.) }\r\n\\item{Improved mathematical algorithms which allow larger step sizes for the same accuracy.}\r\n\\item{Minimise the number of particles needed by the model}\r\n\\item{Include only the most important interactions.} \r\n\\end{itemize}\r\n\r\n%\\href{quickbounce1.py}{quickbounce1.py} is a faster version of the above example program.\r\n\\href{quickbounce1.html}{Here} is a faster version of the ideal gas simulation program.\r\n\r\n\\subsection{Extracting useful information}\r\nThe visualisation of a model can be useful in itself to get insight into its behaviour. \r\nBut the program might be more useful as a computational science 'experiment' if we \r\ncould extract from it predictions of gas behaviour that could be measured in a \r\nphysical experiment or were relevant in some real world application. \r\nAlternatively we could use the results to confirm some theory about ideal gasses. \r\n\r\nTo do either of these we need to extract the sort of information that can normally \r\nbe measured since you don't get to watch the particles of a real gas bouncing around.\r\n\r\nExamples of some measurements we could extract from our simulation:\r\n\\begin{itemize}\r\n\\item{measure how the pressure on the walls varies with gas temperature and density}\r\n\\item{distribution of particle velocities}\r\n\\item{collision frequency}\r\n\\end{itemize}\r\n\\section{Velocity distribution: using graphs}\r\nWe gave our particles a uniform inititial velocity distribution for each direction. \r\nA statistical analysis suggests that the 'most likely' velocity distribution for each \r\ncomponent will have more low energy particles and a long tail of high energy particles. \r\nDoes our gas evolve to this 'most likely' velocity distribution.\r\n\r\n\\subsection{Graphing in visual python}\r\nWe will need the graphing functions contained in the visual.graph module, so insert a line \r\nat the beginning of your program\r\n{\\color{code}\\begin{verbatim}\r\nfrom visual.graph import *\r\n\\end{verbatim}}\r\nSeveral types of graph are available. \r\nWe will use a histogram that displays how many particles fit into each velocity range. \r\nThis graph is set up before the main while loop with:\r\n{\\color{code}\\begin{verbatim}\r\ngraphwindow=gdisplay(xtitle='v_x',ytitle='N',ymax=no_particles/2)\r\nvelocity_dist=ghistogram(bins=arange(0,2*maxv,maxv/5))\r\n\\end{verbatim}}\r\nvelocity\\_dist defines a histogram with a set of ten velocity 'bins' into which the list of \r\nparticle velocities will be sorted. \r\nYou might want to adjust the number of bins depending on the number of particles in your gas. \r\nThe graph will be displayed in a new graphing window. \r\n\r\nTo plot the distribution of particle speeds in the x direction you would form a list and use \r\nthis list as data for the histogram\r\n{\\color{code}\\begin{verbatim}\r\nvlist=[]\r\nfor ball in balls:\r\n        vlist.append(abs(ball.velocity.x))\r\nvelocity_dist.plot(data=vlist)\r\n\\end{verbatim}}\r\nYou can put these lines within the while loop and see the velocity distribution evolve. \r\nUnless you have many particles in your gas the velocity distribution will jump around alot. \r\nYou can reduce this problem by averaging the distribution over time using:\r\n{\\color{code}\\begin{verbatim}\r\nvelocity_dist=ghistogram(bins=arange(0,2*maxv,maxv/5),accumulate=1,average=1)\r\n\\end{verbatim}}\r\n(You may find that displaying the graph slows down the simulation considerably. \r\nIf this is a problem, turn your while loop into a for loop so that it runs for a limited time \r\nand put all the graphing parts of the program after the loop finishes.)\r\n\r\nIf you are using the quick version of the code the velocity is stored as in varray, \r\nwhich can be fed directly to the histogram as:\r\n{\\color{code}\\begin{verbatim}\r\n     velocity_dist.plot(data=varray[:,0])\r\n\\end{verbatim}}\r\n\\subsection{Compare with expected result}\r\nThe expected 'most likely' velocity distribution can be plotted for comparison as a curve set \r\nup with:\r\n{\\color{code}\\begin{verbatim}\r\nexpected_distribution=gcurve(color=color.green)\r\n\\end{verbatim}}\r\nand then plotted point by point with:\r\n{\\color{code}\\begin{verbatim}\r\nfor vx in arange(0,2*maxv,maxv/20):\r\n        expected_distribution.plot(pos=(vx,.3*no_particles*exp(-vx**2/maxv**2*3/2)))\r\n\\end{verbatim}}\r\n(plot only once - so just before while loop. You may need to rescale this graph if you \r\nused a different number of velocity bins)\r\n\r\n% An example of graphing with the quick program is \r\n%\\href{quickbouncevdist.py}{quickbouncevdist.py}\r\n\\href{quickbouncevdist.html}{Here} is an example of graphing with the quick program.\r\n%An example of graphing with the slower program is\r\n%\\href{manybouncevdist.py}{manybouncevdist.py}\r\n\\href{manybouncevdist.html}{Here} is an example of graphing with the slower program.\r\n\r\nSome questions that you could use this program to investigate:\r\n\\begin{itemize}\r\n\\item {Is the initial velocity distribution different from the final velocity distribution?}\r\n\\item{Does the final velocity distribution match the expected result?}\r\n\\item{Does changing the initial velocity distribution effect the final distribution?}\r\n\\item{Consider the ways this simulation is different from a real gas. \r\nWhat changes might you need to make to model a real gas more closely? \r\nHow might this effect the behaviour of the simulation?}\r\n\\end{itemize}\r\n\\section{More complicated simulations}\r\nYou could extend this simulation to investigate more complex situations.\r\n\\begin{itemize}\r\n\\item{Mixing of two ideal gasses (diffusion)(eg look at \\href{quicktwogas.html}{quicktwogas})}\r\n\\item{Heat conduction}\r\n\\item{Other interaction potentials including some attraction may give phase change to \r\nsolid or liquid phases}\r\n\\item{Include effects of earth's gravity to get height variations in pressure and \r\ntemperature - or better simulation of liquid/gas interface}\r\n\\item{Velocity distribution when a gas includes molecules of different masses} \r\n\\item{Movable or elastic walls (eg look at \\href{quickbounce2.html}{quickbounce2})}\r\n\\end{itemize}\r\n%\\section{Other situations that can be modelled using similar techniques}\r\n%The technique of following individual particles, calculating their accelerations \r\n%due to their position and the position of other particles around them can be used \r\n%to simulate a wide variety of situations.\r\n%\\begin{itemize}\r\n%\\item{Molecular dynamics and computational chemistry can determine the \r\n%shape of molecules, their resonant frequencies and their potential reactions. \r\n%The most difficult part is to determine the interaction potentials which can depend on \r\n%relative positions of more than two particles, and also on angles between them.}\r\n%\\item{Gravitational interactions determine the orbits of planets in the solar system. \r\n%Precise calculations of these orbits determine whether the solar system is stable or chaotic, \r\n%whether orbits may change drastically at some future time, give clues as to how the solar \r\n%system form, and whether any asteroid is likely to hit the earth. \r\n%With large objects like planets their shape and rotation may need to be taken into account.}\r\n%\\item{Animal behaviour. Animals use the positions of other animals and objects around them to decide how they \r\n%should move in order to acheive their goals. The goals might include getting food, fleeing predators, staying \r\n%in a group and avoiding collisions. This simulations apply to people and traffic flow and can be used to design\r\n%adequate escape routes from burning buildings and sinking ships, road systems that minimise congestions, or to \r\n%suggest driving techniques that avoid collisions.}\r\n\r\n\\end{document} ", "meta": {"hexsha": "5643ea569d554a689594584adbb00e6e5a7cbceb", "size": 27544, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/simple.tex", "max_stars_repo_name": "stoiver/python_gas_tutorial", "max_stars_repo_head_hexsha": "0e931681507bb1f37ac662fca91e4e89c0893e73", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-04-14T22:29:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-23T17:08:31.000Z", "max_issues_repo_path": "tex/simple.tex", "max_issues_repo_name": "stoiver/python_gas_tutorial", "max_issues_repo_head_hexsha": "0e931681507bb1f37ac662fca91e4e89c0893e73", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/simple.tex", "max_forks_repo_name": "stoiver/python_gas_tutorial", "max_forks_repo_head_hexsha": "0e931681507bb1f37ac662fca91e4e89c0893e73", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-02-19T06:25:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-05T19:39:24.000Z", "avg_line_length": 52.265654649, "max_line_length": 321, "alphanum_fraction": 0.7482210282, "num_tokens": 6415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3467904168342855}}
{"text": "\\chapter{Applications I:  Pure Binary Arithmetic}\\label{arithchapter}\n\n[PLACEHOLDER]\n\n% [TODO I need to clean up this chapter. This paper this chapter is\n% based on presented the definitions in Prolog.  I've translated the\n% code to miniKanren, but much of the English still refers to Prolog's\n% SLD resolution strategy and incomplete, depth-first search.  I still\n% need to clean up this wording, since miniKanren uses a complete,\n% interleaving search strategy.  I also need to integrate the text from\n% the intro and conclusion sections into the rest of the chapter, and\n% the thesis intro and conclusion chapters, as appropriate]\n\n% %%% This could bite me when it comes to Slatex.  Better disable at end of this chapter.\n% %\\DefineShortVerb{\\|}\n\n% %\\begin{abstract}\n% We present \\emph{decidable} logic programs for addition, multiplication,\n% division with remainder, exponentiation, and logarithm with remainder over the\n% \\emph{unbounded} domain of natural numbers.  Our predicates represent\n% \\emph{relations} without mode restrictions or annotations.  They are\n% fully decidable under the common, Depth-First-Search-like, SLD resolution strategy of\n% Prolog, or under an interleaving refinement of DFS\\@, such as that used by miniKanren. We prove that\n% the evaluation of our arithmetic goals always terminates, given arguments \n% that share no logic variables. Further, the (possibly infinite) set of\n% solutions for a goal denotes exactly the\n% corresponding mathematical relation. (For SLD without interleaving, and for\n% some infinite solution sets, only half of the relation's domain may\n% be covered.) We define predicates to handle unary (for illustration)\n% and binary representations of natural numbers, and prove termination\n% and completeness of these predicates. Our predicates are written in pure miniKanren, without\n% \\scheme|conda|/\\scheme|condu|, \\scheme|varo|, \\scheme|project|, or other non-logical operators.  The purity and\n% minimalism of our approach allows us to declare arithmetic in other\n% logic systems, such as Haskell type classes.\n% %\\end{abstract}\n\n% %% \\begin{keywords}\n% %% declarative arithmetic, binary, logic programming, termination\n% %% \\end{keywords}\n\n\n% \\section{Introduction}\n\n% Logic programming is said to be programming with relations, but\n% arithmetic is often dealt with in a non-relational, restricted way.\n% For example, Prolog's built-in \\verb|is/2| predicate for evaluating\n% arithmetic expressions does not allow free (unbound) logic variables\n% in the expressions.  Whereas the goal \\verb|Z is 6*7|\n% succeeds, binding \\verb|42| to~\\verb|Z|, the related goal \\verb|42 is X*Y| is\n% considered erroneous because its multiplicands `are not sufficiently\n% instantiated.' Multiplication is not treated as a ternary relation\n% between multiplicands and the product because of mode restrictions on\n% the first two arguments.  Constraint logic programming (CLP) overcomes\n% this drawback to some extent~\\cite{apt03principles}; for example,\n% disjunctive Datalog~\\cite{Eiter:1997:DD} treats arithmetic\n% relationally.  Indeed, relational handling of arithmetic was one of\n% the motivations for CLP\\@.  Unfortunately, this flexibility has a\n% price: CLP restricts the\n% arithmetic domain to be finite and changes the evaluation mode\n% of the logic programming system away from Kowalski's `predicate as\n% function' model~\\cite{Kowalski74a}.\n\n% We present fully relational arithmetic on the \\emph{unbounded} domain\n% of binary natural numbers for conventional\n% (SLD~\\cite{lloyd:lp}, or SLD with\n% interleaving~\\cite{backtracking}) logic\n% programming systems.  We define predicates for addition,\n% multiplication, division with remainder, and logarithm with\n% remainder. These predicates express the remaining arithmetic\n% operations, including subtraction and exponentiation.  These so-called base\n% predicates have \\emph{no} mode restrictions or annotations \n% on their arguments, and are\n% implemented in a \\emph{pure} logic system without\n% \\scheme|conda|/\\scheme|condu|, \\scheme|varo|, \\scheme|project|, or negation. Furthermore,\n% each base predicate terminates under SLD evaluation (and re-evaluation, upon\n% backtracking), provided that the predicate's arguments share no\n% logic variables.  The stream of answers produced by (re-)evaluating\n% each arithmetic predicate under SLD with interleaving~\\cite{backtracking}\n% covers exactly the corresponding\n% mathematical relation; under SLD resolution and some infinite domains,\n% only half of the relation is covered.\n\n\n% In particular, we define the following decidable predicates:\n% %\n% \\begin{description}\n% \\item[\\scheme|addo|] such that \\scheme{(addo x y z)} can be used to add two numbers\n% \\scheme{x} and \\scheme{y} to get \\scheme{z}, to subtract \\scheme{x} or \\scheme{y} from \\scheme{z}, to decompose\n% \\scheme{z} into summands, or to compare two naturals. For example, \n% we can determine that the triple $(1,2,3)$ is in the ternary addition\n% relation%\n% \\footnote{We mean a relation that relates triples of numbers $(x,y,z)$\n% so that $x+y=z$.}\n% by\n% evaluating either the goal\n% \\scheme{(addo bn1 bn2 bn3)}%\n% \\footnote{\\bn{3} means the representation of the binary numeral 3, which in\n%   miniKanren is encoded as \\schemeresult{(l l)} (\\S\\ref{s:binary}).}\n% or the goal:\n\n% \\schemedisplayspace\n\n% \\begin{schemebox}\n% (exist (x y z)\n%   (addo x y z)\n%   (== bn1 x)\n%   (== bn2 y)\n%   (== bn3 z)).\n% \\end{schemebox}\n\n% By evaluating \\scheme{(addo x bn3 bn2)} we determine, also in finite\n% time, that the addition relation does \\emph{not} include\n% \\emph{any} triple $(n,3,2)$.\n\n% \\item[\\scheme|mulo|] such that \\scheme{(mulo x y z)} can be used, inter alia, to\n%   multiply \\scheme{x} and~\\scheme{y}, to factor~\\scheme{z},\n%   or to generate a stream of triples related\n%   by multiplication.\n\n% \\item[\\scheme|divo|] such that \\scheme{(divo n m q r)}\n% succeeds if and only if $n = m \\cdot q + r < m\\cdot(q+1)$.%\n% \\footnote{This equation implies that \\scheme{divo} fails when $m$ is\n%   \\bn0. Hence \\scheme{mulo} is not reducible to \\scheme{divo}. Besides,\n%   the former is simpler and is part of the implementation of the latter.}\n% For instance, the goal \\scheme{(divo bn1 bn0 q r)} to relate the \n% divisor zero to a non-zero dividend\n% fails instantly, without trying to enumerate all natural numbers.\n% The goal \\scheme{(divo bn5 m bn1 r)} finds all \n% numbers $m$ that divide 5, perhaps unevenly, \n% with a quotient of 1. These values are $5$, $4$, and $3$. Finally,\n% \\scheme{(divo bn5 m bn7 r)} fails in finite time rather than diverging.\n\n% \\item[\\scheme|logo|] such that \\scheme{(logo n b q r)} succeeds if\n% and only if $n = b^q + r < b^{q+1}$.\n% We can use \\scheme{logo} to perform exponentiation, find logarithms, \n% and find $n$-th roots.\n% \\end{description}\n% %\n% We prove that these base predicates are decidable and\n% that the arithmetic relations over natural numbers form their\n% universal model\n% \\begin{comment}\n% \\oleg{\\url{http://www.inf.ed.ac.uk/teaching/courses/fpls/note15.pdf}}\n% \\end{comment}\n% (see the\n% \\emph{faithfulness} property introduced in~\\S\\ref{s:unary}).\n\n\n% \\subsection{Challenges}\n\n% We require the predicates to be both effective and efficient.\n% First, the\n% evaluation of base arithmetic goals must terminate. Put\n% differently, it must be effectively computable whether a\n% tuple of naturals is included in or \\emph{excluded} from a\n% base arithmetic relation (addition, multiplication, division with\n% remainder, and logarithm with remainder).\n% Further, these computations must finish\n% without taking an exponential amount of time or space with respect to\n% the `search depth' (corresponding, in the case of binary numbers, \n% to the logarithm of the largest\n% number appearing in the computation). In other words, we wish to\n% maintain the efficiency of depth-first search (DFS) (or DFS with\n% interleaving \\cite{backtracking,kanrensite}) of the and-or tree expressing the\n% solution space of our base goals.\n\n% The main challenge in defining our predicates is that the domains of\n% natural numbers, and of arithmetic relations in general, are\n% infinite---enumerating them is not an option. \n% The incompleteness of DFS (used in SLD resolution) immediately\n% presents a problem. For example, assuming that \\scheme{geno} is a predicate\n% that generates all (ground) natural numbers in sequence, one may be\n% tempted to implement \\scheme{mulo} (separating the generation and testing for\n% clarity) as\n\n% \\schemedisplayspace\n% \\begin{schemedisplay}\n% (define mulo\n%   (lambda (x y z)\n%     (exist (a b c)\n%       (geno a)\n%       (== x a)\n%       (geno b)\n%       (== y b)\n%       (geno c)\n%       (== z c)\n%       (project (a b)\n%         (== (* a b) c)))))\n% \\end{schemedisplay}\n\n% In addition to its obvious inefficiency, \n% this implementation%\n% \\footnote{Bra{\\ss}el, Fischer, and Huch \\citep{numbers-Curry} describe the drawbacks of this\n% residuation-based approach in functional logic programming.}\n% often diverges under\n% DFS\\@. For example, evaluating \\scheme{(mulo x y 1)}\n% instantiates \\scheme{a} and \\scheme{b} to \\verb|0| and \\scheme{c} to \\verb|1|, causing the goal\n% \\scheme{(== (* a b) c)} to fail; after backtracking into \\scheme{(geno b)}, \\scheme{mulo}\n% keeps forever instantiating \\scheme{b} to\n% larger and larger positive numbers, each time resulting in failure of\n% the goal \\scheme{(== (* 0 b) 1)}.\n\n% One may attempt to fix this problem by using a complete search\n% strategy, such as breadth-first search (BFS) or iteratively-deepening\n% DFS\\@. Even ignoring efficiency concerns, this\n% implementation of \\scheme{mulo} is still unacceptable: a complete search strategy\n% will find a solution \\emph{if it exists}, but if no solution exists\n% the search will continue forever.  For example, although BFS finds the\n% instantiation of \\scheme{y} that satisfies \\mbox{\\scheme|(mulo 1 y 2)|}, the goal\n% \\mbox{\\scheme|(mulo 2 y 1)|} still diverges. Thus we must devise a termination\n% criterion for \\scheme{mulo}.\n\n% Devising a termination criterion may seem easy. For example, when\n% searching for \\scheme{x} and \\scheme{y} that satisfy the goal\n% \\scheme{(mulo x y 5)}, we\n% only need to examine \\scheme{x} and \\scheme{y} values up to~$5$---since\n% the search space is finite, the evaluation of the goal\n% certainly terminates.  The problem arises when determining whether the\n% third argument in a specific use of \\scheme{mulo} is instantiated to a\n% ground numeral.  This task is trivial if we use the `impure'\n% non-logical features provided by Prolog's reflection facilities, such\n% as the infamous \\verb|var/1| predicate. Even if \\verb|var/1| were absent from\n% Prolog, it could be emulated using cuts and negation. We\n% disavow such tools---we aim to implement our predicates in a pure\n% subset of Prolog, without cuts, reflection, or any way to distinguish\n% a logic variable. This aim for purity is a\n% challenge that in return makes our approach most\n% elucidating and extensible.\n\n% The final challenge is that the binary representation of a number\n% may not be structurally part of that of its successor.\n% For example, the binary numeral 111 (in decimal, 7)\n% is not structurally part of its successor 1000. This lack of\n% structural inclusion prevents straightforward structural recursion.\n\n\n% \\subsection{Termination and Solvability}\n\n% These challenges make the arithmetic predicates tricky to code.\n% It is not obvious that the resulting predicates have the\n% claimed properties, in particular, that they terminate in all\n% modes. We therefore devote much of the paper to proofs. A typical\n% termination theorem we prove assures that evaluating or re-evaluating\n% \\mbox{\\scheme|(addo x y z)|} terminates, provided that the terms initially associated\n% with \\scheme{x}, \\scheme{y}, and \\scheme{z} share no logic variables. Successive\n% re-evaluations of this goal recursively enumerate the stream of unique\n% triples $(x,y,z)$ of potentially non-ground terms whose denotation\n% (\\S\\ref{s:solution-sets-of-addition}) is the domain $\\set{(u,v,w) \\in x\\times\n% y\\times z : u+v=w}$.  Thus, membership and non-membership are\n% computable for base arithmetic relations.\n\n% We guarantee termination only for stand-alone base arithmetic goals but\n% not their conjunctions (see \\S\\ref{s:solution-set}). This\n% non-compositionality is expected, since conjunctions of arithmetic\n% goals can express Diophantine equations; were such conjunctions\n% guaranteed to terminate, we would be able to solve Hilbert's 10th\n% problem, which is undecidable~\\cite{hilbertstenth}.  We also do not\n% guarantee termination if the goal's arguments share variables.  Such a\n% goal can be expressed by conjoining a sharing-free base goal and\n% equalities.\n\n% We proceed as follows.\n% In~\\S\\ref{s:unary} we define addition and multiplication predicates\n% for a \\emph{unary} representation of natural numbers.  \n% We introduce solution sets, \\S\\ref{s:solution-set}, to carefully\n% establish termination for these predicates, laying a\n% foundation for our analysis of binary predicates.\n% In~\\S\\ref{s:binary} we introduce our representation of binary\n% numerals, and in \\S\\ref{s:addsub} and~\\S\\ref{s:mult}\n%  we define predicates for binary addition and\n% subtraction, and multiplication, respectively.\n% In~\\S\\ref{s:div-exp-log} we briefly describe our predicates \n% for binary division, exponentiation, and logarithm.  For lack of\n% space, we relegate our pure Prolog implementation of exponentiation,\n% logarithm, and non\\hyp interleaving binary multiplication to\n% the accompanying source\n% code,\\footnote{\\url{http://okmij.org/ftp/Prolog/Arithm/}}\n% along with additional proofs, tests, examples, and discussion.\n% We review related work in~\\S\\ref{s:related}, and\n% conclude in~\\S\\ref{s:conclusion}.\n% The full version of this\n% paper\\footnote{\\url{http://okmij.org/ftp/Prolog/Arithm/arithm.pdf}}\n% includes appendices outlining proofs of the properties of solution sets.\n% We have also implemented\n% declarative arithmetic as Haskell type-level relations (type classes)\n% \\cite{lightweight-resources}.\n\n\n% \\section{Predicates for Unary Arithmetic}\n% \\label{s:unary}\n\n% We begin with unary numerals.\n% Unary is simpler than binary, since every unary numeral is\n% structurally part of its successor, so we may use structural\n% recursion. However, membership and non-membership still need to\n% be decidable for the base arithmetic predicates, whose domains are\n% infinite however they are represented.\n% Hence, the unary case already presents our main challenges.\n% The unary case also lets us introduce and illustrate\n% most of our terminology in this section.\n\n% We represent unary numerals as lists of atoms \\schemeresult{u}: \\scheme{`()} denotes zero,\n% \\scheme{`(u)} denotes one, \\scheme{`(u u)} denotes two, etc.%\n% \\footnote{We could just as easily use a more common representation \n% $z$, $s(z)$, $s(s(z))$, etc. We chose lists for consistency with our\n%   binary representation.}  Throughout this section\n% we use the shorthand \\bn{n} to indicate our representation of\n% the number $n$---that is, the list of \\schemeresult{u}'s of length~$n$.\n\n% Although miniKanren is not statically typed, we assume an \n% implicit type of `unary numerals' and an implicit\n% typing of logic variables. For example, the implicit type of the term\n% \\scheme{`(u u . ,x)} is `unary numeral'; the logic variable \\scheme{x} has\n% the same type. The type predicate for unary numerals can be expressed\n% as a generator:\n\n% \\schemedisplayspace\n% \\begin{schemedisplay}\n% (define genuo\n%   (lambda-e (t)\n%     (`(()))\n%     (`((u . ,x)) (genuo x))))\n% \\end{schemedisplay}\n\n% \\noindent A term \\scheme{t} has the type of `unary numeral' if the goal \\scheme{(genuo t)}\n% succeeds.  When providing denotations for terms and goals we\n% use the implicit type of a logic variable to characterize the \n% variable's domain.\n\n% We can add unary numerals with a special case of the\n% \\scheme{appendo} predicate.\n\n% \\schemedisplayspace\n% \\begin{schemedisplay}\n% (define addo\n%   (lambda-e (n m s)\n%     (`(() ,x ,x))\n%     (`((u . ,x) ,y (u . ,z)) (addo x y z))))\n% \\end{schemedisplay}\n\n% \\noindent We can use \\scheme{addo} to add numerals: the goal\n% \\scheme{(addo bn1 bn2 x)} unifies \\scheme{x} with \\bn3.  We can also use \\scheme{addo} for\n% subtraction: both \\scheme{(addo x bn1 bn3)} and\n% \\scheme{(addo bn1 x bn3)} unify \\scheme{x} with \\bn2, and the evaluation of\n% \\scheme{(addo x bn3 bn1)} fails finitely. We can further use \\scheme{addo} to\n% decompose a number into its summands: for example, \\scheme{(addo x y bn3)}\n% has four solutions, in which \\scheme{x} and \\scheme{y} are unified in turn with\n% $\\bn0$ and $\\bn3$, $\\bn1$ and $\\bn2$, $\\bn2$ and $\\bn1$, and $\\bn3$\n% and $\\bn0$. Finally, passing three distinct uninstantiated logic\n% variables to \\scheme{addo} lets us enumerate the domain of addition over the\n% natural numbers.  The evaluation of the query \\scheme{(addo x y z)} in miniKanren yields an infinite set of solutions; here are the first three, assuming a {\\em depth-first} search strategy:\n\n% \\schemedisplayspace\n% \\begin{schemedisplay}\n% (run3 (q)\n%   (exist (x y z)\n%     (addo x y z)\n%     (== `(,x ,y ,z) q)))  $\\Rightarrow$ \n% \\end{schemedisplay}\n% \\nspace\n% \\begin{schemeresponse}\n% ((() _$_{_{0}}$ _$_{_{0}}$)\n%  ((u) _$_{_{0}}$ (u . _$_{_{0}}$))\n%  ((u u) _$_{_{0}}$ (u u . _$_{_{0}}$)))\n% \\end{schemeresponse}\n\n% \\noindent This stream of solutions represents the infinite addition\n% relation \\emph{in two different ways}. First, the goal produces an\n% infinite number of solutions; we can always re-evaluate the\n% goal to get another solution. Second, each solution represents\n% infinitely many triples, all members of\n% the addition relation. For example, the second solution\n% compactly represents the infinitely many triples of naturals $(x,y,z)$\n% for which $x$ is one and $z$ is the successor of $y$.  Each instantiation\n% of the free logic variable \\schemeresult|_$_{_{0}}$| to a member of its domain\n% (corresponding to its implicit type) yields a new triple of naturals\n% that is a member of the addition relation. We will make extensive use of\n% this compact representation of infinite domains when proving\n% termination properties of our predicates.\n\n% \\subsection{Solution Sets}\\label{s:solution-set}\n\n% To formulate propositions about \\scheme{addo} and other predicates, we\n% introduce the notion of \\emph{solution sets}, which accounts for the\n% search strategy used to run a logic program (unlike other procedural\n% notions of solutions).  We use miniKanren syntax.\n% We identify a bound logic variable with the term it is bound to,\n% so all variables are free for us, as for Lloyd \\cite{lloyd:lp}.\n% Our goals are all pure (contain no \\scheme|varo|, \\scheme|project|,\n% negation, or \\scheme|conda|/\\scheme|condu|).\n\n% We assume an \\emph{idempotent} notion of substitution\n% \\cite{FBaade01}: a substitution~$\\theta$\n% is a finite map $\\set{x_i=t_i}$ from logic variables~$x_i$ to\n% terms~$t_i$ such that no $t_j$ contains any~$x_i$.\n% \\begin{comment}\n% The finite set $\\set{x_i}$ is\n% the domain $\\dom\\theta$.\n% and the set of variables occurring in \n% $\\set{t_i}$ is the set $\\fv\\theta$ of free variables of $\\theta$.\n% \\end{comment}\n% We write the application of the substitution $\\theta$ to a term $t$ as\n% $t\\theta$; this application easily extends to tuples of\n% terms and sets of tuples.\n\n% \\begin{definition}[Conjunction of substitutions]\\label{defn:conjunction}\n% We define the \\emph{conjunction} $\\theta\\xi$ of two \n% substitutions $\\theta$ and $\\xi$ by treating them\n% as sets of equations $\\set{x_i = t_i}$: we combine both\n% sets (the result may contain two equations for the same $x_i$) and use\n% unification to solve the resulting equations\n% \\cite[\\S2.2.3]{FBaade01}. Our conjunction of substitutions is thus\n% commutative and associative.  Because of the unification our\n% conjunction is partial: if unification fails we call\n% the original substitutions contradictory.\n% \\end{definition}\n\n% \\begin{comment}\n% Notion of instantiatedness and instantiatedness tree from Mercury\n% documentation.\n% \\url{http://www.cs.mu.oz.au/research/mercury/information/doc-release/mercury_ref/Insts-modes-and-mode-definitions.html#Insts-modes-and-mode-definitions}\n% \\end{comment}\n\n% \\newcommand{\\bind}{\\star}\n% \\newcommand{\\plus}{\\oplus}\n% \\newcommand{\\equal}{=}\n% We can interpret a goal~$g$ as a function from a substitution\n% to a (finite or infinite) stream of substitutions.  Both SLD and\n% SLD-interleaving \\cite{backtracking} interpret (right-associative and non-commutative)\n% disjunction and conjunction by\n\n% \\hspace{2.9cm}\\scheme|(conde (g1) (g2))|$(\\theta) \\equal g_{_{1}}(\\theta) \\plus g_{_{2}}(\\theta)$,\n\n% \\hspace{3.2cm}\\scheme|(exist () g1 g2)|$(\\theta) \\equal g_{_{1}}(\\theta) \\bind g_{_{2}}$\n\n% % we use ; and , rather than \\land and \\lor for consistency with Prop 2\n% where the \\emph{bind} operation $\\bind$ is defined recursively by\n% \\begin{align*}\n%     \\boldleftparen \\boldrightparen                    &\\bind f \\equal \\boldleftparen \\boldrightparen, \\\\\n%     \\boldleftparen \\theta\\ \\centerdot\\ \\vec\\theta \\boldrightparen &\\bind f \\equal (f \\theta) \\plus (\\vec\\theta \\bind f).\n% \\end{align*}\n% The difference between SLD and SLD-interleaving is that $\\plus$ above is\n% defined as stream concatenation in SLD but stream \n% interleaving in SLD-interleaving.\n\n% \\begin{definition}[Solution sequence and set]\n%   Given an $n$-ary predicate \\scheme{g} and $n$ terms $t_1,\\ldots,t_n$ that may\n%   contain logic variables, a \\emph{solution}\n%   of a goal {\\rm \\scheme|(g t1 ... tn)|} is an $n$-tuple\n%   $(t^{\\prime}_1,\\ldots,t^{\\prime}_n)$ where each $t^{\\prime}_i$ instantiates $t_i$\n%   after the evaluation of the goal succeeds\n%   using SLD or SLD-interleaving strategy.\n%   A solution can be represented as $(t_1,\\ldots,t_n)\\theta$ for some\n%   substitution $\\theta$.\n%   A \\emph{solution sequence} is\n%   a sequence of solutions obtained by evaluating and\n%   successively re-evaluating a goal.\n%   The sequence is a \\emph{solution set} if no two of its members\n%   unify with each other.\n% \\end{definition}\n% A goal that fails has the empty solution set. A goal whose evaluation\n% or re-evaluation does not terminate does not have a solution\n% sequence.\n% In contrast, the goal \\mbox{\\scheme|(genuo x)|} does have a solution sequence (which\n% can be infinite)\n% because its evaluation and re-evaluation always terminates.\n% We assume SLD as the default solution strategy.\n% If we add the clause \\scheme{(addo x '() x)} as a well-meaning optimization ($x+0=x$)\n% after the first clause of \\scheme{addo} above, the solution sequence may not\n% necessarily be a solution set: for example, the goal \\scheme{(addo x y bn0)}\n% will have $(\\bn0,\\bn0,\\bn0)$ in duplicate.\n\n\n% The notion of solution sequence is constructive, `proof-theoretic,' to\n% be distinguished from a model of a logic program: each\n% solution has been actually \\emph{derived}, in finite time, from\n% the facts and rules at hand using the given solution strategy. A term\n% in a solution may contain free logic variables.  We can prove\n% the following properties of solution sets\n% (see Appendix~A of our full paper).\n\n% \\begin{comment}\n% \\oleg{define the monotonicity property: what happens with the solution\n%    sequence if we add one more clause to the definition of the goal,\n%    after the existing clauses. Note starvation: under SLD, solution set\n%    remains the same if it is already infinite.}\n% \\end{comment}\n\n% \\begin{proposition}\\label{p:ss-monotonicity}\n% If a goal {\\rm \\scheme|(g t1 ... tn)|} has a (finite or infinite) solution set \n% $\\set{ (t_1,\\ldots,t_n)\\theta_i }$\n% and $\\xi$ is a substitution that contradicts only finitely many \n% $\\theta_i$, then the goal \n% \\mbox{{\\rm \\scheme|(g t1$\\xi$ ... tn$\\xi$)|}} has a solution set\n% $\\set{ (t_1,\\ldots,t_n)({\\theta_i}\\xi) }$,\n% omitting the elements where $\\theta_i$ and $\\xi$ are contradictory.\n% \\end{proposition}\n\n% The solution set of a conjunction of goals \n% \\scheme{(g1 t11 ... t1n)} and \\scheme{(g2 t21 ... t2n)} is \n% (as in a natural database join)\n% the set of tuples $\\set{ (t_{11},\\ldots,t_{1n},t_{21},\\ldots,t_{2n}) }$\n% after the evaluation of the conjunction has succeeded.\n\n% \\begin{proposition}\\label{p:ss-conj-finite}\n% If the goals $g_1$ and $g_2$ have a finite solution set, \n% then the conjunction of $g_1$ and $g_2$ has a finite solution set.\n% \\end{proposition}\n% This proposition is a corollary of the previous proposition. It\n% does not generally hold if the solution set of one of the conjuncts is infinite. For example, \n\n% \\schemedisplayspace\n% \\begin{schemedisplay}\n% (define mfo\n%   (lambda-e (n m)\n%     (`(() (u . ,y)) (genuo y))\n%     (`((u . ,x) ,y) (mfo `(u . ,x) y))))\n% \\end{schemedisplay}\n\n% \\noindent The goal \\scheme{(mfo x y)}, with the variables \\scheme{x} and \\scheme{y} free, has the infinite solution set \n% $\\set{(\\bn0,\\bn{i}): i \\in \\mathbb{N}^+}$. However, the (left or right)\n% conjunction of this goal with \\mbox{\\scheme|(== x bn1)|} diverges and has no solution set.\n% Similarly, the conjunction of \\mbox{\\scheme|(mfo x y)|} with \\mbox{\\scheme|(== x y)|} has no solution set\n% either.\n% Prop.\\,\\ref{p:ss-monotonicity} applies to neither conjunction because \n% the substitutions $\\{x=\\bn1\\}$ and $\\{x=y\\}$ both\n% contradict infinitely many solution-set substitutions (in fact, all\n% of them).\n% The latter conjunction is equivalent to the goal\n% \\scheme{(mfo x x)}; such sharing of variables among the arguments of\n% a goal is lethal to the termination guarantees below (such as\n% Prop.\\,\\ref{p:add-unground}).\n\n% \\begin{proposition}\\label{p:ss-conj-infinite}\n% If a goal {\\rm \\scheme|(g1 t1 ... tn)|} has a finite solution set \n% $\\set{(t_1,\\ldots,t_n)\\theta_i}$ and the goal\n% \\mbox{{\\rm \\scheme|(g2 $t^{\\prime}_1$$\\theta_1$ ... $t^{\\prime}_m$$\\theta_1$)|}} has an infinite solution set\n% $\\set{(t_1^{\\prime}\\theta_1,\\ldots,t_m^{\\prime}\\theta_1)\\xi_j}$, then\n% the conjunction of $g_1$ and $g_2$ has the infinite solution set\n% $\\set{(t_1,\\ldots,t_n,t_1^{\\prime},\\ldots,t_m^{\\prime})\\penalty\\binoppenalty(\\theta_1\\xi_j)}$.\n% \\end{proposition}\n% This proposition describes the incompleteness of SLD\\@: its underlying\n% depth-first search becomes trapped exploring the leftmost \n% infinite branch of the search tree. However, using \n% the SLD-interleaving strategy, we can strengthen the proposition:\n\n% \\begin{proposition}\\label{p:ss-conj-interleaving}\n% If a goal\n% \\mbox{{\\rm \\scheme|(g1 t1 ... tn)|}} has a (finite or infinite) solution set \n% $\\set{(t_1,\\ldots,t_n)\\theta_i}$ and the goal\n% \\mbox{{\\rm \\scheme|(g2 $t^{\\prime}_1$$\\theta_i$ ... $t^{\\prime}_m$$\\theta_i$)|}} has a non-empty (finite or \n% infinite) solution set $\\set{(t_1^{\\prime}\\theta_i,\\ldots,t_m^{\\prime}\\theta_i)\\xi_{ij}}$\n% for each~$i$, then\n% the conjunction of $g_1$ and $g_2$ has the solution set\n% $\\set{ (t_1,\\ldots,t_n,t_1^{\\prime},\\ldots,t_m^{\\prime})(\\theta_i\\xi_{ij}) }$.\n% \\end{proposition}\n% The proof is based on the laws of fair conjunction and disjunction in\n% \\cite{backtracking}; details are given in\n% Appendix~B of our full paper.\n% We use analogous properties for disjunctions of goals.\n\n% \\subsection{Properties of Addition: Solution Sets of Addition}\\label{s:solution-sets-of-addition}\n\n% If $t$ is a term and $n$ is a natural number, then we write\n% \\mbox{\\scheme|`(u$^{n}$ . ,t)|} to mean \\mbox{\\scheme|`(u ... u . ,t)|} where \\mbox{\\scheme|`u ... `u|}\n% consists of $n$ occurrences of~\\scheme{`u}.\n\n% One can easily prove the following propositions:\n% \\begin{proposition}\\label{p:add-ground-XY}\n% The goal {\\rm \\scheme|(addo x y z)|}, where \\scheme{x} and \\scheme{y} are instantiated to ground\n% numerals and \\scheme{z} is free, has a singleton solution set\n% unifying \\scheme{z} with the\n% numeral that is the sum of those corresponding to \\scheme{x} and \\scheme{y}.\n% \\end{proposition}\n% That is, if the first two arguments of \\scheme{addo} are instantiated to\n% numerals, the goal is decidable and has one solution.\n% \\begin{proposition}\\label{p:add-ground-Z}\n% The goal {\\rm \\scheme|(addo x y z)|} where \\scheme{z} is instantiated to a ground numeral\n% has a finite solution set.\n% \\end{proposition}\n% The proof is an easy induction on the third argument.\n\n% \\begin{proposition}\\label{p:add-ground-X}\n% The goal {\\rm \\scheme|(addo x y z)|}, where \\scheme{x} is a ground numeral \\bn{n} and \\scheme{y} and \\scheme{z} are\n% free, has the singleton solution set\n% $\\{ (\\bn{n},g,${\\rm \\scheme|`(u$^n$ . ,g)|}$) \\}$ where \\scheme{g}\n% is a free logic variable.\n% \\end{proposition}\n% The proof is by induction on \\scheme{x}. The proposition easily extends to\n% the case where \\scheme{y} and \\scheme{z} are arbitrary terms, using\n% Prop.\\,\\ref{p:ss-monotonicity}. \n\n% \\begin{proposition}\\label{p:add-free}\n% The goal {\\rm \\scheme|(addo x y z)|}, where the arguments are distinct\n% free logic variables, has an infinite solution set\n% $\\{ (\\bn{n},g,${\\rm \\scheme|`(u$^n$ . ,g)|}$) : n\\in\\mathbb{N} \\}$ \n% where $g$ is a free logic variable. In each solution,\n% $x$ is unified to a ground numeral. \n% \\end{proposition}\n% The proof is by induction on $x$ and soundness of SLD resolution.\n\n% \\begin{definition}[Denotation of arithmetic solutions]\n% The \\emph{denotation} $\\denot\\cdot$ of an arithmetic term or solution set is defined as follows.\n% \\begin{align*}\n% \\denot {\\bn n} &= \\{n\\}\\\\\n% \\denot t &= \\set{\\, n \\in \\mathbb{N} : n \\ge m \\,} \\notag\\\\[-\\jot]\n% &\\qquad\\text{where $t$ is the non-ground term \\emph{$\\boldleftparen \\sfusymbol^m\\ \\centerdot\\ x\\boldrightparen$}} \\notag\\\\[-\\jot]\n% &\\qquad\\text{where $x$ is a free logic variable of the type of unary numerals}\\\\\n% \\denot{(t_1,\\ldots,t_n)} &= \\denot{t_1} \\times \\dotsb \\times \\denot{t_n} \\\\\n% \\denot S &= \\cup_{s \\in S}\\denot {s}\n% \\quad\\text{for a solution set $S$ (whose elements are all disjoint)}\n% \\end{align*}\n% \\end{definition}\n\n% \\noindent\n% The previous propositions along with Prop.\\,\\ref{p:ss-monotonicity} let\n% us prove:\n% \\begin{proposition}\\label{p:add-unground}\n% The goal {\\rm \\scheme|(addo x y z)|} where the arguments have no shared logic variables has\n% a solution set with \\scheme{x} always unified to a ground numeral. \n% The denotation of the solution set is\n% $\\set{(u,v,w) \\in \\denot{x} \\times \\denot{y} \\times \\denot{z} : u+v=w}$.\n% \\end{proposition}\n% The proof simply invokes Prop.\\,\\ref{p:add-ground-Z} or\n% Prop.\\,\\ref{p:add-ground-X} if $z$ or $x$ is ground.\n% If neither $z$ nor $x$ is ground, then the arguments of the goal,\n% since they share no logic variables,\n% contradict only finitely many solutions in the set of\n% Prop.\\,\\ref{p:add-free}, so we invoke Prop.\\,\\ref{p:ss-monotonicity}.\n\n\n% The proposition states that the predicate \\scheme{addo} is fully decidable:\n% for any arguments sharing no free variables, the predicate\n% decides if the denotation of these arguments is in the domain\n% of addition \\emph{or not}. Furthermore, for any subset of the domain\n% of addition of the form\n% $\\set{(u,v,w) \\in \\denot{x} \\times \\denot{y} \\times \\denot{z} : u+v=w}$,\n% there is a goal with exactly this denotation.\n% We call such a predicate \\emph{faithful}.\n\n\n% \\subsection{Multiplication}\\label{s:unary-mul}\n\n% Multiplication of unary numbers may seem as trivial as\n% addition. (We will be developing several versions of multiplication,\n% so we label the \\scheme{mulo} predicates with a numeric version  \n% to distinguish them.)\n\n% \\schemedisplayspace\n% \\begin{schemedisplay}\n% (define mul1o\n%   (lambda-e (n m p)\n%     (`(() __ ()))\n%     (`((u . ,x) ,y ,z)\n%      (exist (z1)\n%        (mul1o x y z1)\n%        (addo z1 y z)))))\n% \\end{schemedisplay}\n\n% \\noindent This predicate directly encodes the inductive definition of\n% multiplication: \\mbox{$0 \\cdot x = 0$,} $(x+1)\\cdot y = x\\cdot y + y$. Indeed, \n% the goal \\scheme{(mul1o bn3 bn2 x)} has the singleton solution set with $x$\n% unified with $\\bn6$. However, the goal \\scheme{(mul1o x bn2 bn6)}\n% diverges after producing the first solution, the goal\n% \\scheme{(mul1o x bn2 bn5)} diverges without producing anything, and\n% \\scheme{(mul1o x y bn6)} overflows the stack after producing three solutions.\n% % -- $x=\\bn1,y=\\bn6$, $x=\\bn2,y=\\bn3$, $x=\\bn3,y=\\bn2$ -- \n\n% The problem is left-recursion in the second clause: the goal\n% \\scheme{(mul1o x bn2 z)} with free $x$ and~$z$ requires evaluating\n% \\scheme{(mul1o x^ bn2 z^)} again with free \\scheme{x^} and~\\scheme{z^}. Reordering\n% goals in the body of the second clause eliminates left-recursion:\n\n% \\schemedisplayspace\n% \\begin{schemedisplay}\n% (define mul2o\n%   (lambda-e (n m p)\n%     (`(() __ ()))\n%     (`((u . ,x) ,y ,z)\n%      (exist (z1)\n%        (addo z1 y z)\n%        (mul2o x y z1)))))\n% \\end{schemedisplay}\n\n% \\noindent Now \\scheme{(mul2o x bn2 bn6)} has a singleton solution set and\n% \\scheme{(mul2o x bn2 bn5)} fails finitely.\n% However, whereas before\n% \\scheme{(mul1o bn3 bn2 x)} had a singleton solution set (with $x=\\bn6$), \n% this version \\scheme{mul2o} diverges after the\n% first solution, so the goal has no solution set.\n\n% Interestingly, simply swapping the arguments to \\scheme{addo} fixes the\n% problems.\n\n% \\schemedisplayspace\n% \\begin{schemedisplay}\n% (define mul3o\n%   (lambda-e (n m p)\n%     (`(() __ ()))\n%     (`((u . ,x) ,y ,z)\n%      (exist (z1)\n%        (addo y z1 z)\n%        (mul3o x y z1)))))\n% \\end{schemedisplay}\n\n% \\noindent Now \\mbox{\\scheme|(mul3o x bn2 bn6)|} and \\mbox{\\scheme|(mul3o bn3 bn2 x)|} both have singleton\n% solution sets, and \\mbox{\\scheme|(mul3o x bn2 bn5)|} fails finitely. \n% The reason is important. Evaluating\n% \\mbox{\\scheme|(mul2o bn3 bn2 z)|} requires evaluating\n% \\mbox{\\scheme|(addo z1 bn2 z)|} whereas evaluating\n% \\mbox{\\scheme|(mul3o bn3 bn2 z)|} requires evaluating\n% \\mbox{\\scheme|(addo bn2 z1 z)|}.\n% Although both addition goals denote the same relation, the former\n% has the infinite solution set\n% $\\set{ (\\bn0,\\bn2,\\bn2), \\penalty\\binoppenalty (\\bn1,\\bn2,\\bn3),\n%     \\penalty\\binoppenalty (\\bn2,\\bn2,\\bn4),\\ldots}$\n% whereas the latter has the singleton solution set\n% $\\{ (\\bn2,g,$\\scheme|`(u u . ,g)|$) \\}$ (Prop.\\,\\ref{p:add-ground-X}).\n% That makes all the difference, as we prove below.\n\n% However, \\scheme{mul3o} is not perfect. Evaluating\n% \\scheme{(mul3o x y bn6)} overflows the stack,\n% because it requires evaluating\n% \\mbox{\\scheme|(addo y z1 bn6)|}, which gives $z_1=\\bn6, y=\\bn0$ as one\n% solution.  This solution causes a recursive call\n% \\mbox{\\scheme|(mul3o x^ y bn6)|}, same as the original call. Thus we must treat\n% zero multiplicands separately,\n% taking care to avoid overlapping solutions so that the solution\n% sequence remains a solution set.\n\n% \\schemedisplayspace\n% \\begin{schemedisplay}\n% (define mulo\n%   (lambda-e (n m p)\n%     (`(() __ ()))\n%     (`((u . __) () ()))\n%     (`((u . ,x) (u . ,y) ,z)\n%      (exist (z1)\n%        (addo `(u . ,y) z1 z)\n%        (mulo x `(u . ,y) z1)))))\n% \\end{schemedisplay}\n\n% \\noindent This pattern of fixing one problem only to see another problem emerge\n% is quite common, which is why we need proofs.\n\n% \\begin{comment}\n% In conducting the proofs below, we will appeal to the size-change\n% termination principle (Jones et al, GPCE 2002) ``a program terminates\n% on all inputs if every valid infinite call sequence would, if\n% executed, cause an infinite decrease in some parameter values''\n% trivially extended to logic programs (exploration of search trees).\n% \\oleg{use that paper and a paper at FLOPS2006 for relevant literature\n%   on termination analysis of logic programs. Mention Mercury's\n%   termination checker.}\n% \\end{comment}\n\n% \\begin{proposition}\\label{p:mul-ground-XY}\n% The goal {\\rm \\scheme|(mulo x y z)|}, where $x$ and $y$ are instantiated to ground\n% numerals and $z$ is free, has the singleton solution set that\n% unifies $z$ with the\n% numeral that is the product of the numerals for $x$ and $y$.\n% \\end{proposition}\n% The proof is an induction on $x$ using Prop.\\,\\ref{p:ss-conj-finite}\n% and Prop.\\,\\ref{p:add-ground-X}.\n% \\begin{comment}\n% \\oleg{or should we appeal to the size-changing principle?}\n% That is, if the first two arguments of \\verb|mul/3| are instantiated to\n% numerals, the goal is decidable and has at most one solution.\n% \\end{comment}\n\n% \\begin{proposition}\\label{p:mul-ground-Z}\n% The goal {\\rm \\scheme|(mulo x y z)|}, where $z$ is instantiated to a ground numeral,\n% has a finite solution set.\n% \\end{proposition}\n% The proof depends on Prop.\\,\\ref{p:ss-conj-finite} and\n% Prop.\\,\\ref{p:add-ground-Z}:\n% each solution of\n% \\scheme{(addo `(u . ,y) z1 z)} instantiates\n% $z_1$ to a ground numeral smaller than the numeral for~$z$. \n% \\begin{comment}\n% The latter\n% fact follows from the soundness of addition.\n% \\end{comment}\n\n% \\begin{proposition}\\label{p:mul-ground-Y}\n% The goal {\\rm \\scheme|(mulo x y z)|}, where $y$ is instantiated to a positive \n% ground numeral \\bn{n} and $x$ and $z$ are free, has the solution set\n% $\\set{ (\\bn{i},\\bn{n},\\bn{i\\cdot n}) : i \\in \\mathbb{N} }$. If $y$ is \\bn0,\n% the solution set is finite: $\\{ (\\bn0,\\bn0,\\bn0), (${\\rm \\scheme|`(u . ,x)|}$,\\bn0,\\bn0) \\}$.\n% \\end{proposition}\n% The proof is by induction on $y$ and Prop.\\,\\ref{p:add-ground-X}.\n\n\n% \\begin{proposition}\\label{p:mul-unground-interleave}\n% Under the SLD-interleaving strategy,\n% the goal {\\rm \\scheme|(mulo x y z)|}, where the arguments share no logic variables,\n% has a solution set that denotes\n% $\\set{ (u,v,w) \\in \\denot{x} \\times \\denot{y} \\times \\denot{z} :\n% u\\cdot v=w}$.\n% \\end{proposition}\n% The proof depends on Props.\\,\\ref{p:add-unground}, \\ref{p:mul-ground-Y}\n% and~\\ref{p:ss-conj-interleaving}.\n% Thus under SLD with interleaving, our \\scheme{mulo} predicate is faithful\n% to the multiplication\n% relation on naturals.\n\n% Without interleaving, the goal \\scheme{(mulo x y z)} has the solution set:\n\n% $\\{ (\\bn0, g,\\bn0), (${\\rm \\scheme|`(u . ,g$^{\\prime}$)|}$,\\bn0,\\bn0), (\\bn1,\\bn1,\\bn1), (\\bn2,\\bn1,\\bn2),(\\bn3,\\bn1,\\bn3),\\ldots \\}$.\n\n% \\noindent The denotation of this solution set\n% obviously does not cover the entire\n% multiplication relation: the second argument gets `stuck' on~$1$.\n% Under SLD\\@, then, our predicate \\scheme{mulo} covers only an infinitesimal part of\n% the domain of multiplication. We can do better: we define\n% a predicate \\scheme{semimulo} that\n% has the \\emph{same} termination properties as \\scheme{mulo} but covers \\emph{half} of the\n% domain of multiplication, namely $y \\le x$, whichever arguments are instantiated.\n\n% We first define the predicate \\scheme{lesso}, corresponding to the less-than\n% relation.\n\n% \\schemedisplayspace\n% \\begin{schemedisplay}\n% (define lesso\n%   (lambda-e (n m)\n%     (`(() (__ . __)))\n%     (`((u . ,x) (u . ,y)) (lesso x y))))\n% \\end{schemedisplay}\n\n% \\noindent The \\scheme{semimulo} predicate is then as follows.\n\n% \\schemedisplayspace\n% \\begin{schemedisplay}\n% (define semimulo\n%   (lambda-e (n m p)\n%     (`(() __ ()))\n%     (`((u . __) () ()))\n%     (`((u . ,x) (u . ,y) ,z) (lesso x z) (lesso y `(u . ,x))\n%      (mulo `(u . ,x) `(u . ,y) z))))\n% \\end{schemedisplay}\n\n% \\begin{proposition}\n% The goal {\\rm \\scheme|(semimulo x y z)|}, where the arguments are free logic variables,\n% has a solution set that denotes\n% $\\set{ (u,v,w) \\in \\mathbb{N}^3: v \\le u,\\, u\\cdot v=w }$.\n% \\end{proposition}\n% The proof depends on the goal \\scheme{(lesso x z)}, which asserts the trivial inequality\n% $x < (x+1)\\cdot (y+1)$ for all $x,y \\in \\mathbb{N}$.\n% With free $x$ and $z$, the goal\n% \\scheme{(lesso x z)} has an infinite solution set whose solutions each\n% instantiate $x$ to a ground numeral.\n% The goal \\scheme{(lesso y `(u . ,x))}\n% then has a \\emph{finite} solution set that grounds $y$ as well.\n% The last goal has thus a singleton\n% solution set, by Prop.\\,\\ref{p:mul-ground-XY}.\n\n% These attempts to define decidable multiplication even for the\n% seemingly trivial unary case show the difficulties that become more\n% pronounced as we move to binary arithmetic. We rely on a\n% finite representation of infinite domains, precise instantiatedness\n% analysis, and reasoning about SLD using search trees.\n\n\n% \\section{Binary Numerals}\\label{s:binary}\n\n% We represent numerals as lists of binary digits in little-endian order\n% (least significant bit first), with zero represented as the empty\n% list.  A zero bit is denoted by \\schemeresult{o} (lower-case `oh') and a one bit is denoted\n% by \\schemeresult{l} (lower-case `el')---to distinguish a\n% number from its representation.  For example, the terms \\scheme{`()}, \\scheme{`(l)},\n% \\scheme{`(o l)}, \\scheme{`(l l)}, \\scheme{`(o o l)} represent $0$ through~$4$.\n% The last bit of\n% a positive numeral \\emph{must} be~\\schemeresult{l}. Our code below takes special\n% care to maintain this well-formedness condition.\n% It is trivial to convert\n% between this and Prolog's native representations of integers.\n\n% We often use the auxiliary one-clause\n% predicates \\scheme{zeroo}, \\scheme{poso}, and \\scheme{gtlo}:\n\n% \\schemedisplayspace\n% \\begin{schemedisplay}\n% (define zeroo\n%   (lambda-e (n)\n%     (`(()))))\n\n% (define poso\n%   (lambda-e (n)\n%     (`((__ . __)))))\n\n% (define gtlo\n%   (lambda-e (n)\n%     (`((__ __ . __)))))\n% \\end{schemedisplay}\n\n% \\noindent The goal \\scheme{(zeroo n)} succeeds if $n$ is zero. The goal \\scheme{(poso n)}\n% succeeds if $n$ is positive. The goal \\scheme{(gtlo n)} succeeds\n% if $n$ is at least two.\n\n% The predicate \\scheme{genbo} below expresses the\n% implicit type of binary numerals.\n\n% \\schemedisplayspace\n% \\begin{schemedisplay}\n% (define genbo\n%   (lambda-e (n)\n%     (`(()))\n%     (`((l . ,x)) (genbo x))\n%     (`((o . ,x)) (poso x) (genbo x))))\n% \\end{schemedisplay}\n\n% \\noindent The presence of \\scheme{(poso x)} in the last clause ensures that the last\n% bit of a positive numeral is~\\schemeresult{l}. The code below contains similar\n% guarding occurrences of \\scheme{poso}.\n\n% Recall that one challenge of binary arithmetic is that a numeral\n% is not structurally part of its\n% successor. However, such a notion of inclusion exists (with\n% the attendant induction principle) if we consider the `length' of a binary\n% number, i.e., the number of bits in its binary representation. \n% More precisely, the length~$\\norm{n}$ of a numeral~$n$\n% is $\\floor{\\log_2 n} + 1$ if $n>0$, and $0$ if $n=0$. We define \\scheme{lesslo} by\n\n% \\schemedisplayspace\n% \\begin{schemedisplay}\n% (define lesslo\n%   (lambda-e (n m)\n%     (`(() (__ . __)))\n%     (`((__ . ,x) (__ . ,y)) (lesslo x y))))\n% \\end{schemedisplay}\n\n% \\noindent It has the meaning and form of the unary \\scheme{lesso}\n% in~\\S\\ref{s:unary-mul}---and the same termination properties---but\n% compares the length of binary numbers rather their magnitude.\n\n% \\section{Addition and Subtraction}\\label{s:addsub}\n\n% % http://en.wikipedia.org/wiki/Adder_(electronics)\n\n% % full adder: one-bit adder\n% % what below is full_adder is nbit adder (multiple-bit) adder\n% % of the ripple-carry adder type\n\n% Our treatment of addition is inspired by hardware \n% full-adders and multi-bit adders, \n% as found in a digital computer's arithmetic logic\n% unit \\citep{hennessy-computer}.  A one-bit full-adder\n% \\mbox{\\scheme|(full1-addero cin a b s cout)|} relates two input bits $a,b$ and the incoming\n% carry bit $c_{\\mathrm{in}}$ with the sum bit~$s$ and the outgoing carry \n% bit $c_{\\mathrm{out}}$, according\n% to the equation $c_{\\mathrm{in}} + a + b = s + 2 c_{\\mathrm{out}}$. In miniKanren,\n% we define \\scheme{full1-addero} by enumerating eight facts:\n\n% \\schemedisplayspace\n% \\begin{schemedisplay}\n% (define full1-addero\n%   (lambda-e (cin a b s cout)\n%     (`(o o o o o))\n%     (`(o o l l o))\n%     (`(o l o l o))\n%     (`(o l l o l))\n%     (`(l o o l o))\n%     (`(l o l o l))\n%     (`(l l o o l))\n%     (`(l l l l l))))\n% \\end{schemedisplay}\n\n% The multi-bit adder \\mbox{\\scheme|(fulln-addero cin a b s)|} relates\n% the incoming carry bit \\scheme{cin} (either \\schemeresult|o| or \\schemeresult|l|), \n% two binary numbers $a,b$, and their sum~$s$, according to the equation $c_{\\mathrm{in}} + a + b = s$.\n% It is defined by recursively combining one-bit adders\n% as in a ripple-carry adder of digital logic,\n% only in our case, the summands' bitwidths need not be the same or limited.\n\n% \\schemedisplayspace\n% \\begin{schemedisplay}\n% (define fulln-addero\n%   (lambda-e (cin a b r)\n%     (`(o ,a () ,a))\n%     (`(o () ,b ,b) (poso b))\n%     (`(l ,a () ,r) (fulln-addero 'o a '(l) r))\n%     (`(l () ,b ,r) (poso b) (fulln-addero 'o '(l) b r))\n%     (`(,cin (l) (l) (,r1 ,r2)) (full1-addero cin 'l 'l r1 r2))\n%     (`(,cin (l) (,ba . ,bd) (,ra . ,rd)) (poso bd) (poso rd)\n%      (exist (cout)\n%        (full1-addero cin 'l ba ra cout)\n%        (fulln-addero cout '() bd rd)))\n%     (`(,cin ,a (l) ,r) (gtlo a) (gtlo r)\n%      (fulln-addero cin '(l) a r))\n%     (`(,cin (,aa . ,ad) (,ba . ,bd) (,ra . ,rd))\n%      (poso ad) (poso bd) (poso rd)\n%      (exist (cout)\n%        (full1-addero cin aa ba ra cout)\n%        (fulln-addero cout ad bd rd)))))\n% \\end{schemedisplay}\n\n% \\noindent The first four clauses above deal with the cases\n% of a summand being zero. The next three clauses handle\n% the cases of a summand being one. The last clause adds\n% numbers at least two bits wide. We take\n% care to keep clauses from overlapping, so the solution\n% sequence of a \\scheme{fulln-addero} goal is a solution set. The\n% splitting of the cases and the many occurrences of \\scheme{poso} are\n% necessary to keep all numerals in a solution `well-typed':\n% If logic variables in a solution are instantiated according to their \n% implicit types, we never see a list whose last element unifies with \\schemeresult{o}.\n% \\begin{comment}\n% i.e., satisfy the typing predicate \\verb|genb/1|. If free logic variables in a\n% solution are instantiated according to their implicit types, \n% all the numerals are well-formed---we never have a finite list \n% whose last element unifies with \\verb|o|.\n% \\end{comment}\n\n% This multi-bit adder expresses binary addition, subtraction, and\n% ordering:\n\n% \\schemedisplayspace\n% \\begin{schemedisplay}\n% (define addo\n%   (lambda (a b c)\n%     (fulln-addero 'o a b c)))\n\n% (define subo\n%   (lambda (a b c)\n%     (addo b c a)))\n\n% (define lesso\n%   (lambda (a b)\n%     (exist (x)\n%       (poso x)\n%       (addo a x b))))\n% \\end{schemedisplay}\n\n% \\begin{comment}\n% The latter says that the number $a$ is less than the number $b$ if\n% there exists a positive number $x$ that can be added to $a$ to produce\n% $b$.\n% \\end{comment}\n\n% Our predicate \\scheme{addo} for binary numerals satisfies\n% Prop.\\,\\ref{p:add-ground-XY} (by induction on \\mbox{$4 c_{\\mathrm{in}} + 3a + b$}) and\n% Prop.\\,\\ref{p:add-ground-Z}.\n% However, due to carry propagation (clauses 4 and 6 of \\scheme{fulln-addero}),\n% Prop.\\,\\ref{p:add-ground-X} and Prop.\\,\\ref{p:add-free} no longer\n% accurately describe the solution sets of binary \\scheme{addo}:\n% the goal \\mbox{\\scheme|(addo x y z)|}, with either $x$ or $y$ ground and the other\n% arguments being distinct free variables, has an infinite solution\n% set.\n\n% Prop.\\,\\ref{p:add-unground} holds (without $x$ being always\n% ground) only in the case of SLD with interleaving;\n% for SLD\\@, we can develop a binary addition\n% predicate that covers half of the domain of addition,\n% as in~\\S\\ref{s:unary-mul}.\n% The proofs begin by unrolling the recursion in clauses 3, 4,\n% and~7 of \\scheme{fulln-addero} (splitting cases for clauses 3 and~4),\n% so that \\scheme{fulln-addero} invokes itself recursively only for shorter\n% arguments.\n% \\begin{comment}\n% \\oleg{For the full proof, we need\n%   one more proposition about the interleaving, about adding\n%   to the disjunction.\n%   Actually, the proposition is as follows: limited completeness of\n%   SLD with interleaving: if a goal $\\mathtt{g}(\\vec t)$ has a \n%   (possibly infinite) solution set, and $\\mathtt{g}(\\vec t)\\theta$\n%   has a non-empty solution set, the solution set of the latter goal is\n%   included in the solution set of the former goal. That is not the\n%   full completeness since it does not address the divergence. That's\n%   why there is a premise that a goal must have a solution set to\n%   start with. To prove that the solution set exists, we can prove that\n%   given any particular `depth' the strategy will find a fact there.\n% }\n% \\end{comment}\n\n% \\section{Multiplication}\\label{s:mult}\n\n% Binary multiplication may seem an obvious generalization of unary\n% multiplication. The most complex case is to multiply an odd number by\n% a positive one, $(2n + 1) m = 2 (n m) + m$, because it\n% involves addition. One may think that the\n% approach in \\scheme{mulo} in~\\S\\ref{s:unary-mul} will work here. Alas, binary\n% addition does not satisfy Prop.\\,\\ref{p:add-ground-X}, so we must\n% turn to a much less obvious solution.\n\n% \\schemedisplayspace\n% \\begin{schemedisplay}\n% (define mulo\n%   (lambda-e (n m p)\n%     (`(() ,m ()))\n%     (`(,n () ()) (poso n))\n%     (`((l) ,m ,m) (poso m))\n%     (`((o . ,nd) ,m (o . ,pd)) (poso m) (poso nd) (poso pd) (mulo nd m pd))\n%     (`((l . ,nd) ,m ,p) (poso m) (poso nd) (gtlo p)\n%      (exist (p1)\n%        (lessl3o p1 p `(l . ,nd) m)\n%        (mulo nd m p1)\n%        (addo `(o . ,p1) m p)))))\n% \\end{schemedisplay}\n\n% \\noindent This solution relies on a seemingly contrived predicate \\scheme{lessl3o}:\n\n% \\schemedisplayspace\n% \\begin{schemedisplay}\n% (define lessl3o\n%   (lambda-e (p1 p n m)\n%     (`(() (__ . __) __ __))\n%     (`((__ . ,p1d) (__ . ,pd) () (__ . ,md)) (lessl3o p1d pd '() md))\n%     (`((__ . ,p1d) (__ . ,pd) (__ . ,nd) m) (lessl3o p1d pd nd m))))\n% \\end{schemedisplay}\n\n% \\noindent The goal \\mbox{\\scheme|(lessl3o p1 p n m)|} relates four numerals such that\n% \\mbox{$\\norm{p_1} < \\min(\\norm{p},\\penalty\\binoppenalty \\norm{n} + \\norm{m} + 1)$}.\n% As long as the arguments of the goal, \\emph{however instantiated}, \n% share no logic variables, the goal has a solution set. In any solution,\n% $p_1$ is a numeral whose bits may be free but whose length is fixed.\n% We call such numerals \\emph{L-instantiated}.\n% Moreover, whenever $p_1$, $p$, or both $n$ and $m$ are\n% L-instantiated, the solution set is finite.\n\n% In the code for binary \\scheme{mulo} above, \\scheme{lessl3o} occurs in a clause that is\n% selected when multiplying an odd number $2 n + 1$ (where $n>0$) by a positive\n% number~$m$ to yield~$p$. Under these conditions, clearly\n% $\\floor{\\log_2 n m}$ is less than both $\\floor{\\log_2 p}$\n% and $\\floor{\\log_2(2n+1)} + \\floor{\\log_2 m} + 2$, so the\n% constraint imposed by \\scheme{lessl3o} does not affect the declarative meaning\n% of \\scheme{mulo}.\n% The guarantee\n% of \\scheme{lessl3o} mentioned above lets us prove\n% Prop.\\,\\ref{p:mul-ground-XY} and Prop.\\,\\ref{p:mul-ground-Z} for binary\n% multiplication. For Prop.\\,\\ref{p:mul-ground-Z},\n% \\scheme{lessl3o} ensures that $p_1$ is L-instantiated,\n% so we can use induction to prove that \\mbox{\\scheme|(mulo n m p)|} with an\n% L-instantiated $p$ has a finite solution set. \n\n% The important role of \\scheme{lessl3o} can be informally explained as follows.\n% Given the goal \\mbox{\\scheme|(mulo x y z)|}, when $x$ and $y$ are instantiated but $z$\n% is free, or when $z$ is instantiated but $x$ and $y$ are free, the\n% search space is finite even though the free variables can be\n% instantiated an infinite number of ways: the length of the\n% product limits the lengths of the multiplicands, and vice versa.\n% The predicate \\scheme{lessl3o} enforces these limits, even\n% though our code cannot distinguish these two cases by\n% determining which arguments are instantiated.\n\n% The \\scheme{mulo} predicate also satisfies\n% Prop.\\,\\ref{p:mul-unground-interleave} (the proof again relies on the\n% properties of \\scheme{lessl3o}). As in the unary case, using SLD without\n% interleaving, we cannot cover the whole domain of natural\n% multiplication---but we can cover half of it. The technique is\n% essentially the same as explained for unary\n% multiplication.\n\n\n% \\section{Division, Exponentiation, and Logarithm}\\label{s:div-exp-log}\n\n% Our predicate for division with remainder\n% \\mbox{\\scheme|(divo n m q r)|} relates four natural\n% numbers such that $n = m \\cdot q + r < m\\cdot(q+1)$. The implementation is\n% quite complex so as to finitely fail as often as possible: for example, not only\n% when the divisor $m$ is zero, but also in the case\n% \\mbox{\\scheme|(divo `(o . ,x) '(o l) q '(l))|} with \\emph{free} $x$ and $q$, as\n% no even number divided by~$2$ gives the remainder~$1$.\n% Our algorithm is akin to long division as taught in elementary school, only\n% done right-to-left. At each step, we determine at\n% least one bit of the quotient in finite time.\n\n% First, we handle the easy case when the divisor~$m$ is\n% bigger than the dividend~$n$, so $q=0$ and $n=r$.\n\n% \\schemedisplayspace\n% \\begin{schemedisplay}\n% (define divo\n%   (lambda-e (n m q r)\n%     (`(,n ,m () ,r) (== n r) (lesso n m))\n%     ...))\n% \\end{schemedisplay}\n\n% \\noindent Otherwise, $q$ must be positive.\n% The second easy case is when $n$ is at least~$m$\n% and has the same length as~$m$.\n\n% \\schemedisplayspace\n% \\begin{schemedisplay}\n% (define divo\n%   (lambda-e (n m q r)\n%     ...\n%     (`(,n ,m (l) ,r) (samelo n m) (addo r m n) (lesso r m))\n%     ...))\n% \\end{schemedisplay}\n\n% \\noindent This code relies on the auxiliary predicate \\scheme{samelo}, which holds if its\n% two arguments are binary numerals with the same number of digits.\n\n% \\schemedisplayspace\n% \\begin{schemedisplay}\n% (define samelo\n%   (lambda-e (n m)\n%     (`(() ()))\n%     (`((__ . ,x) (__ . ,y)) (samelo x y))))\n% \\end{schemedisplay}\n\n% The main case of division is when $n$ has more digits than~$m$.\n% The key is to represent $n = m \\cdot q + r < m\\cdot(q+1)$ as the conjunction\n% of the two relations\n% \\begin{align*}\n% 2^{l+1}r_1 &= m q_2 + r - n_2\n% &&\\text{and}&\n% n_1 &= m q_1 + r_1\n% \\end{align*}\n% where\n% \\begin{align*}\n% n &= 2^{l+1} n_1 + n_2, & q &= 2^{l+1} q_1 + q_2, & l &= \\norm{r},\n% \\end{align*}\n% and $n_2$ and~$q_2$ are at most $l+1$ long.\n% Given $l$, then, we can decide the first\n% relation. Because $0 \\le r_1 < m$, we can invoke\n% \\mbox{\\scheme|(divo n1 m q1 r1)|} recursively to decide the second\n% relation. That gives us a convenient induction principle:\n% either $n_1$ is zero and so $q_1$ and $m q_2 + r - n_2$ are both zero,\n% or $n_1$ is positive and shorter than~$n$.  These two cases correspond\n% to the disjunction below.\n\n% \\schemedisplayspace\n% \\begin{schemedisplay}\n% (define divo\n%   (lambda-e (n m q r)\n%     ...\n%     (`(,n ,m ,q ,r) (lesslo m n) (lesso r m) (poso q)\n%      (exist (n1 n2 q1 q2 q2m q2md r1 rd)       \n%        (splito n r n1 n2)\n%        (splito q r q1 q2)\n%        (conde\n%          ((== '() n1)\n%           (== '() q1)\n%           (subo n2 r q2m)\n%           (mulo q2 m q2m))\n%          ((poso n1)\n%           (mulo q2 m q2m)\n%           (addo q2m r q2md)\n%           (subo q2md n2 rd)\n%           (splito rd r r1 '())\n%           (divo n1 m q1 r1)))))))\n% \\end{schemedisplay}\n\n% \\noindent The calls to \\scheme{lesslo} and \\scheme{lesso} at the beginning of this code\n% ensure that \\scheme{m} and then \\scheme{r} are both L-instantiated.\n% The code also relies on the predicate \\scheme{splito} to `split' a binary\n% numeral at a given length: The goal\n% \\mbox{\\scheme|(splito n r n1 n2)|} holds if \n% $n = 2^{l+1} n_1 + n_2$ where $l = \\norm{r}$ and $n_2 < 2^{l+1}$. The goal should be\n% invoked only when $r$ is L-instantiated, which is the case in the\n% \\scheme{divo} code above. The goal has a finite solution set, in which\n% $n_2$ is L-instantiated in every solution.\n\n% \\schemedisplayspace\n% \\begin{schemedisplay}\n% (define splito (n r n1 n2)\n%   (lambda-e\n%     (`(() __ () ()))\n%     (`((o ,b . ,n) () (,b . ,n) ()))\n%     (`((l . ,n) () ,n (l)))\n%     (`((o ,b . ,n) (__ . ,r) ,n1 ()) (splito `(,b . ,n) r n1 '()))\n%     (`((l . ,n) (__ . ,r) ,n1 (l)) (splito n r n1 '()))\n%     (`((,b . ,n) (__ . ,r) ,n1 (,b . ,n2)) (poso n2) (splito n r n1 n2))))\n% \\end{schemedisplay}\n\n% Our predicate\n% \\mbox{\\scheme|(logo n b q r)|}\n% relates four numbers such that\n% $n = b^q + r < b^{q+1}$, so it implements\n% exponentiation, logarithm, and\n% $n$-th root.\n% Our implementation uses an\n% upper bound on $r$, namely $r b < n (b-1)$, and upper and lower bounds on $q$,\n% namely $(\\norm{b}-1) q < \\norm{n}$ and $\\norm{n}-1 < \\norm{b} (q+1)$. These\n% bounds constrain the search just as \\scheme{lessl3o} does for\n% binary multiplication in~\\S\\ref{s:mult}. Because the base-$2$\n% case is so simple, we treat it separately.\n\n\n% \\section{Conclusions}\\label{s:conclusion}\n\n% [TODO Integrate this text into rest of chapter, and thesis conclusion,\n% as appropriate.]\n\n% In a pure logic programming system,\n% we have declared decidable arithmetic of unrestricted unary and\n% binary natural numbers: addition, multiplication, division with\n% remainder, exponentiation, and logarithm with remainder.\n% The declared relations have unlimited domain and\n% are free from any mode restrictions or annotations.  We have proven\n% that our arithmetic predicates are fully decidable and faithfully\n% represent the corresponding arithmetic relations.  Our technique can\n% be easily extended to full integers (i.e., a tuple of the sign and a\n% natural number).\n\n% The gist of our approach is to limit the search space by a\n% balancing act of computing \\emph{bidirectional} bounds from arguments of unknown\n% instantiatedness. For example, the key to decidable\n% multiplication is to limit the search using bounds that\n% the inputs place on each other, without\n% testing whether any input is instantiated. We\n% also rely on the ability to finitely represent infinite domains\n% using logic variables, so that goals with infinite denotations\n% may have only a finite solution set.\n% Our notion of solution sets and the associated proof techniques\n% are not specific to arithmetic and SLD\\@; rather, they appear\n% applicable to logic programming in other domains using a variety\n% of search strategies.\n\n% %\\UndefineShortVerb{\\|}\n\n% \\newpage\n\n% % [fix typography:  remove sfu, bind definition should use bold parens and dot]\n\n% % [should include expo and logo code.  Make sure logo code is the corrected code.]\n\n% % [need to test all of this]\n\n% % [I dumped the two proofs in the appendix--refer the reader to the published paper, or the full version on Oleg's site]\n\n% % [should I build up the definition of divo one function at a time?  Probably not as important if we use the lambda-e macro.]\n\n% % [need to discuss varo, project, conda, condu, somewhere, preferably before this chapter]\n\n% % [Careful with the use of 'we'.  Should refer to authors, not 'we', when referring to work I wasn't part of (for example, Ken and Oleg's arithmetic system using Haskell typeclasses).]\n\n% % [is it necessary or desirable to include all of the proofs?  Or can I point to the full paper?]\n\n% % [the *full* paper, with proof outlines, wasn't presented at FLOPS.  the full paper is on Oleg's website (see footnote)]\n\n% % [does this code include the fix for logo?]\n\n% % [check against canonical miniKanren arithmetic code]\n\n% % [can we write a relational quicksort program, like in Apt's paper?\n% % See page 3 of Apt's paper 'Declarative Programming in Prolog']\n\n% % \\noindent [also, can we write the trans relation w/out negation?  see\n% % page 15 of Apt's paper]\n\n% % [no constraints (other than equality constraints via unification).]\n\n% % [individual operations are decidable]\n\n% % Interesting examples (need to translate to chapter's conventions and names):\n\n% % factoring\n\n% % \\schemedisplayspace\n% % \\begin{schemedisplay}\n% % (run* (q)\n% %   (exist (x y)\n% %     (mulo x y '(o o l l))\n% %     (== `(,x ,y) q)))\n% % \\end{schemedisplay}\n% % \\begin{schemeresponse}\n% % (((l) (o o l l))\n% %  ((o o l l) (l))\n% %  ((o l) (o l l))\n% %  ((o o l) (l l))\n% %  ((l l) (o o l))\n% %  ((o l l) (o l)))\n% % \\end{schemeresponse}\n\n% % division\n\n% % \\schemedisplayspace\n% % \\begin{schemedisplay}\n% % (run* (t)\n% %   (exist (x q r)\n% %     (divo '(o l l) x q r)\n% %     (== `(,x ,q ,r) t)))\n% % \\end{schemedisplay}\n% % \\begin{schemeresponse}\n% % (((_.0 _.1 _.2 _.3 . _.4) () (o l l))\n% %  ((l l l) () (o l l))\n% %  ((o l l) (l) ())\n% %  ((l o l) (l) (l))\n% %  ((o o l) (l) (o l))\n% %  ((l) (o l l) ())\n% %  ((l l) (o l) ())\n% %  ((o l) (l l) ()))\n% % \\end{schemeresponse}\n", "meta": {"hexsha": "2ab54a09496537b677b366d9ce36e3e00c43b481", "size": 60254, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "oldarith.tex", "max_stars_repo_name": "holtzermann17/dissertation-single-spaced", "max_stars_repo_head_hexsha": "aca0e56a33916596c98709308342d9ccabd4718b", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 50, "max_stars_repo_stars_event_min_datetime": "2015-01-11T21:22:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T12:49:11.000Z", "max_issues_repo_path": "oldarith.tex", "max_issues_repo_name": "holtzermann17/dissertation-single-spaced", "max_issues_repo_head_hexsha": "aca0e56a33916596c98709308342d9ccabd4718b", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-08-08T18:10:18.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-09T02:33:25.000Z", "max_forks_repo_path": "oldarith.tex", "max_forks_repo_name": "holtzermann17/dissertation-single-spaced", "max_forks_repo_head_hexsha": "aca0e56a33916596c98709308342d9ccabd4718b", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-07-29T13:58:01.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-14T05:01:31.000Z", "avg_line_length": 43.4419610671, "max_line_length": 192, "alphanum_fraction": 0.6908752946, "num_tokens": 18277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3467904083364927}}
{"text": "\\chapter{How Cameras Work}\n\nLet's say it is a sunny day and you are standing in field a few meters\nfrom a cow. You use the camera on your phone to take a picture of the\ncow. How does that whole process work?\n\n\\section{The Light That Shines On the Cow}\n\nThe sun is a sphere of hot gas. About 70\\% of the gas is\nhydrogen. About 28\\% is helium. There's also a little carbon, nitroge,\nand oxygen.\n\nGradually, the sun is converting hydrogen into helium through a\nprocess known as ``nuclear fusion''. (We will talk more about nuclear\nfusion in a later chapter.) A lot of heat is created in this\nprocess. The heat makes the gases glow.\n\nHow does heat make things glow? The heat pushes the electrons into\nhigher orbitals.  When the fall back down to a lower orbital, they\nrelease a photon of energy, which travels away from the atam as an\nelectromagnetic wave.\n\nHeat isn't the only way to push the electrons into a higher\norbital. For example, a flourescent lightbulb is filled with gas.\nWhen we pass electricity through the gas, its electrons are moved to a\nhigher orbital.  When they fall, light is created.\n\nWhat is the frequency of the wave that the photon travels on?\nDepending on what orbital it falls from and how far it falls, the\nphoton created has different amounts of energy. The amount of energy\ndetermines the frequency of the electromagnetic wave.\n\n\\begin{mdframed}[style=important, frametitle={Formula for enegy of a photon}]\n\nIf you want to know the amount of energy $E$ in a photon, here is the formula:\n\n$$E = \\frac{h c}{\\lambda}$$\n\nwhere $c$ is the speed of light, $\\lambda$ is the wavelength of the\nelectromagnetic wave, and $h$ Planck's constant: $6.63 \\times 10^{-34} m^2 kg/s$\n\nFor example, a red laser light has a wavelength of about 630 nm. So the energy in each photon is:\n\n$$\\frac{(300 \\times 10^6) (6.63 \\times 10^{-34})}{630 \\times 10^{-9}} = 3.1 \\times 10^{-19} \\text{ joules}$$\n\n\\end{mdframed}\n\nIn the sun, there are several kinds of molecules and each has a few\ndifferent orbitals that the electrons can live in.  Thus, the light\ncoming from the sun is made up of electromagnetic waves of many\ndifferent frequencies.\n\nWe can see some of these frequencies as different colors, but some are\ninvisible to humans, for example ultraviolet and infrared.\n\n\\section{Light Hits the Cow}\n\nWhen these photons from the sun hit the cow, the hide and hairs of the\ncow will absorb some of the photons. These photons will become heat\nand make the cow feel warm.  Some of the photons will not be absorbed\n-- they will leave the cow.  When you say ``I see the cow,'' what you are\nreally saying is ``I see some photons that were not absorbed by the cow.''\n\nDifferent materials absorb different amounts of each wavelength. A\nplant, for example, absorbs large percentage of all blue and red\nphotons that hit it, but it absorbs only a small percentage of the\ngreen photons that hit it.  Thus we say ``That plant is green.''\n\nWhite things absorb very small percentages of photons of any visible\nwavelength.  Black things absorb very \\emph{large} percentages of\nphotons of any visible wavelength.\n\nBefore we go on, let's review: The sun creates photons that travel as\nelectromagnetic waves of assorted wavelengths to the cow.  Many of\nthose photons are absorbed, but some are not.  Some of those photons\nthat are not absorbed go into the lens of our camera.\n\n\\section{Pinhole camera}\n\nThe simplest cameras have no lenses. They are just a box.  The box has\na tiny hole that allows photons to enter.  The side of the box\nopposite the hole is flat and covered with film or some other\nphoto-sensitive material.\n\nThe photons entering the box continue in the same direction they were\ngoing when they passed through the hole.  Thus, the photons that\nentered from high, hit the back wall low.  The photons that came from\nthe left, hit the back wall on the right. Thus the image is projected\nonto the back wall rotated 180 degrees: What was up is down, what was\non the left is on the right.\n\nFIXME: picture here\n\n\\begin{Exercise}[title={Height of the image}, label=image_height]\n\nLet's say that that the pinhole is exactly the same height as the\nshoulder of the cow and that the shoulder is directly above one hoof.\nThan the pinhole, the shoulder, and the hoof form a right triangle.\n\nNow, let's say that the camera is being held perpendicular to the\nground.  Now, the pinhole, the image of the shoulder, and the image of\nthe hoof on the back wall of the camera also form a right triangle.\n\nThese two triangles are similar.\n\nThe shoulder is 2 meters from the hoof.  The cow is standing 3 meters\nfrom the camera.  The distance from the pinhole to the back wall of\nthe camera is 3 cm.  How tall is the image of the cow on the back wall\nof the camera?\n\n\\end{Exercise}\n\\begin{Answer}[ref=image_height]\n\nThe two triangles are similar, one is 2 m and 3m.  The other is $x$ cm and 3 cm.\n\nThe image of the cow is 2 cm tall.\n\n\\end{Answer}\n\n\\section{Lenses}\n\nQuick review: A photon leaves the sun in some random direction. It\ntravels 150 million km from the sun and hits a cow.  It is not\nabsorbed by the cow, and heads off in a new direction.  It passes\nthrough the pinhole and hits the back wall of the camera.  That seems\nincredibly improbable, right?\n\nIt actually is kind of improbable, especially if there isn't a lot of\nlight -- like you are taking the picture at dusk.  To increase the\nodds, we added a \\newterm{lens} to the camera.\n\nIf you focus a lens on a wall, and then you draw a dot on the\nwall. The lens is designed such that all the photons from the dot that\nhit the lens get redirected to the same spot on the back wall of the\ncamera -- regardless of which path it took to get to the lens.\n\nFIXME: illustration here\n\nNote that the image still gets flipped.  There is a \\newterm{ focal\npoint } that all the photons pass through.\n\nFIXME: illustration here\n\nThe distance from the lens to its focal point is called the lens's\n\\newterm{focal length}. Telephoto lenses, that let you take big\npictures of things that are far away, have long focal lengths.\nWide-angle lenses have short focal lengths.\n\n\\section{Sensors}\n\nThe camera on your phone has a sensor on the back wall of the\ncamera. The sensor is broken up into tiny rectangular regions called\npixels.  When you say a sensor is 6000 by 4000 pixels, we are saying\nthe sensor is a grid of 24,000,000 pixels: 6000 pixels wide and\n4000 pixels tall.\n\nEach pixel has three types of cavities that take in photos. One of the\ncavities measures the amount of short wavelength light, like blues and\nviolets. One of the cavities measures the long wavelength light, like\nreds and oranges. One of the cavities measures the intensity of\nwavelengths in the middle, like greens.\n\nThus, if your camera has a resolution of $6000 \\times 4000$, the image\nis 72,000,000 numbers: Every one of the 24,000,000 pixels yeilds three\nnumbers: intensity of long wavelength, mid wavelength, and long\nwavelength light. We call these numbers ``RGB'' for Red, Green, and\nBlue.\n\n\n\n", "meta": {"hexsha": "a4bc9fe893fb6c2028f1f76d63b56f34a274a916", "size": 6993, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Modules/Oscillations/camera-en_US.tex", "max_stars_repo_name": "hillegass/sequence", "max_stars_repo_head_hexsha": "b7b4896d804c49cbc93fe86a0d2fce531afbcc1f", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-06-13T17:19:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T00:43:44.000Z", "max_issues_repo_path": "Modules/Oscillations/camera-en_US.tex", "max_issues_repo_name": "hillegass/sequence", "max_issues_repo_head_hexsha": "b7b4896d804c49cbc93fe86a0d2fce531afbcc1f", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Modules/Oscillations/camera-en_US.tex", "max_forks_repo_name": "hillegass/sequence", "max_forks_repo_head_hexsha": "b7b4896d804c49cbc93fe86a0d2fce531afbcc1f", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-05T00:43:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T00:43:58.000Z", "avg_line_length": 40.8947368421, "max_line_length": 108, "alphanum_fraction": 0.7670527671, "num_tokens": 1749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3467903998386998}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\marginpar{Tuesday\\\\ 2020-4-21, \\\\ compiled \\\\ \\today}\n\nNow we have a dilemma: beauty versus pragmatism.\n\nHow do we provide a mass to the \\(W\\) vector boson?\n\n% We could introduce an \\(SU(2)\\) symmetry. \n\nAs we were discussing, we could add a mass term and write \n%\n\\begin{align}\n\\mathscr{L} = \\mathscr{L} _{\\text{Yang-Mills}} + M^2 W^{+}_{\\mu } W^{\\mu, -}\n\\,,\n\\end{align}\n%\nbut this term \\emph{brutally} breaks the symmetry.\nThis is explicit breaking of the symmetry. \n\nHowever, if we do not break the symmetry we cannot reproduce the data\\dots or can we?\n\n\\subsection{Spontaneous Symmetry Breaking}\n\nWe introduce \\textbf{Spontaneous Symmetry Breaking}. \nThis is a phenomenon which is not exclusive to HEP: it happens in ferromagnets, for example.\nThey start off (above the Curie temperature) with the spins pointing in uniformly distributed directions: the situation is symmetric.\nAs we cool them, at a certain stage all the spins align.\nWe cannot predict the direction along which they will align (since the initial state is symmetric), but once they do the symmetry is \\emph{spontaneously broken}.\n\nLet us take the standard approach (also done in the Theoretical Physics course \\cite[sec.\\ 5.2]{tissinoTheoreticalPhysicsNotes2020}) introduce the Lagrangian of a complex scalar field \\(\\phi \\): \n%\n\\begin{align}\n\\mathscr{L} = \\qty(\\partial^{\\mu  } \\phi^{*}(x)) \\qty(\\partial_{\\mu } \\phi (x)) \n\\underbrace{- \\mu^2 \\abs{\\phi (x)}^2\n- \\lambda^{4} \\abs{\\phi (x)}^{4}}_{- V(\\phi )}\n\\,,\n\\end{align}\n%\nand to find the ground state we can move to the Hamiltonian: \n%\n\\begin{align}\n\\mathscr{H} = \\pi(x) \\phi (x) - \\mathscr{L}\n\\,.\n\\end{align}\n\nThe parameter \\(\\lambda \\) must be \\(>0\\), while \\(\\mu^2\\) has no constraints.\n\nIt is a critical parameter: if \\(\\mu^2\\) is positive we are in the symmetric phase of the system, and the vacuum is only \\(\\phi = 0\\): the VEV is \\(\\bra{0} \\phi \\ket{0} = 0\\). \n\nIf, on the other hand, \\(\\mu^2\\) is negative we transition to a new phase which is not symmetric: the vacuum becomes a whole circle, whose VEV is \\(v = \\sqrt{- \\mu^2 / 2 \\lambda }\\). The whole region parametrized as \\(v e^{i \\theta }\\), with \\(\\theta \\in \\mathbb{R}\\), provides equivalent vacua:\na specific ground state is not symmetric under the whole symmetry of the Lagrangian.\n\nWhy do we only have terms in \\(\\phi^2\\) and \\(\\phi^{4}\\)? we basically constructed the simplest potential which has the properties we want.\n\nIf \\(\\mu^2>0\\) we can perturb around the state without the quartic term, which is described by the KG equation.\n\nIf, instead, we want to perturb around a vacuum in the \\(\\mu^2<0\\) case we need to distinguish two directions, since the Hessian of the potential has two different eigenvalues, one positive and one equal to zero. We parametrize \n%\n\\begin{align}\n\\phi = \\frac{1}{\\sqrt{2}} \\qty(v + \\sigma (x) + i\\eta (x))\n\\,,\n\\end{align}\n%\nwhere \\(\\sigma \\) and \\(\\eta \\) are both real. \n\nThe Lagrangian can then be rewritten as \n%\n\\begin{align}\n\\mathscr{L} = \\frac{1}{2} \\partial^{\\mu } \\sigma \\partial_{\\mu } \\sigma \n+ \\frac{1}{2} \\partial^{\\mu } \\eta \\partial_{\\mu } \\eta \n+ 2 \\lambda v^2 \\frac{1}{2} \\sigma^2 \n- \\frac{\\lambda}{4} \\qty(\\sigma^2 + \\eta^2)^2\n- \\lambda v \\sigma \\qty(\\sigma^2 + \\eta^2)\n\\,,\n\\end{align}\n%\nso we have two real fields, one massive  (\\(\\sigma \\)) and one massless (\\(\\eta \\)). The massless field is called a \\textbf{Goldstone boson}.\n\nIf we compute the VEV of \\(\\phi \\) in this configuration we get     \\(v / \\sqrt{2 }\\). \n\nIn general, the Golstone theorem states that for each broken symmetry generator we get a massless boson. \n\nIt seems that instead of solving the problem of our massless gauge bosons we have created another problem, predicting more massless particles; but in fact our two problems solve each other.\n\nWe must break a different symmetry, though: a gauge local symmetry, instead of a global one.\nIf we explicitly break a \\(U(1)\\) global symmetry, we have a Goldstone boson.\nIf we break a \\(U(1)\\) local symmetry, instead, we get a massless vector boson and a massless scalar.\nThis spontaneous breaking of local gauge symmetry is the \\textbf{Higgs mechanism}.\n\n\\subsubsection{SQED Higgs mechanism}\n\nWe will see this explicitly, with the breaking of the scalar-QED \\(U(1)\\) symmetry: let us consider a Lagrangian \n%\n\\begin{align}\n\\mathscr{L} = \\qty(\\DD^{\\mu } \\phi )^{*} \\DD_{\\mu } \\phi \n- \\mu^2 \\abs{\\phi}^2 - \\lambda \\abs{\\phi }^4\n- \\frac{1}{4} F^{\\mu \\nu } F_{\\mu \\nu }\n\\,,\n\\end{align}\n%\nwhere \\(\\DD_{\\mu } = \\partial_{\\mu } + iq A_{\\mu} \\).\nThis is similar to a Lagrangian describing a fermion, but we substitute it with a complex scalar field with charge \\(q\\). \n\nThis Lagrangian has a \\(U(1)\\) gauge symmetry, whose action is \n%\n\\begin{align}\n\\phi &\\to e^{-iq \\alpha (x)} \\phi \\\\\n\\phi^{*} &\\to e^{iq \\alpha (x)} \\phi^{*} \\\\\nA_{\\mu } &\\to A_{\\mu } + \\partial_{\\mu } \\alpha     \n\\,.\n\\end{align}\n\nIf \\(\\mu^2>0\\) we have no issues: the only minimum is the global one at \\(\\phi = A_{\\mu } = 0\\). This is the only configuration which is Lorentz invariant: any other vector would define a direction, breaking Lorentz symmetry. \n\nThe last point also holds if \\(\\mu^2 < 0\\); so the possible vacua are those defined as \\(\\phi = v e^{i \\theta } / \\sqrt{2}\\) and \\(A^{\\mu } = 0 \\).\nLet us perturb as we did before: if we define \n%\n\\begin{align}\n\\phi (x) = \\frac{1}{\\sqrt{2}} \\qty(v + \\sigma (x) + i \\eta (x))\n\\,,\n\\end{align}\n%\nthe Lagrangian can be rewritten as \n%\n\\begin{align}\n\\begin{split}\n\\mathscr{L} &= \\frac{1}{2} \\partial^{\\mu } \\sigma \\partial_{\\mu }\\sigma \n- \\frac{1}{2} (2 \\lambda v^2) \\sigma^2(x)  \n- \\frac{1}{4} F^{\\mu \\nu } F_{\\mu \\nu } \\\\\n&\\phantom{=}\\ \n+ \\frac{1}{2} (q v)^2 A_{\\mu } A^{\\mu }\n+ \\frac{1}{2} \\partial^{\\mu }\\eta \\partial_{\\mu } \\eta \n+ qv A^{\\mu } \\partial_{\\mu } \\eta \n+ \\text{higher-order interactions}   \n\\,.\n\\end{split}\n\\end{align}\n\nThis Lagrangian describes a real scalar \\(\\sigma \\) with mass \\(\\sqrt{2 \\lambda v^2}\\); a massless real scalar \\(\\eta \\); a massive vector boson and the interactions between them. \n\nLet us count degrees of freedom: we started with a complex scalar \\(\\phi \\) (2 dof) and a massless vector (2 dof); now we have two real scalars (1 dof each) and a massive vector (3 dof): we have gone from a total of four to a total of five! \nSo, there must be an unphysical field between these. \n\nIn fact, we can do a gauge transformation (going to the \\emph{unitary gauge}) so that \\(\\phi \\) is real everywhere: this removes the need for \\(\\eta \\). \nAfter this manipulation, the Lagrangian will read \n%\n\\begin{align}\n\\begin{split}\n\\mathscr{L} &= \\frac{1}{2} \\partial^{\\mu } \\sigma \\partial_{\\mu } \\sigma \n- \\frac{1}{2} (2 \\lambda v^2) \\sigma^2 \n- \\frac{1}{4} F_{\\mu \\nu } F^{\\mu \\nu } \\\\\n&\\phantom{=}\\ \n+ \\frac{1}{2} (qv)^2 A_{\\mu} A^{\\mu }  \n+ \\text{higher-order interactions}\n\\,,\n\\end{split}\n\\end{align}\n%\nso we are left with a massive scalar \\(\\sigma \\) (1 dof) and a massive vector \\(A_{\\mu } \\) (3 dof): the total is 4 again! \n\nIt is a ``transmutation'' of degrees of freedom: one dof has gone from the scalar to the vector making it massive. \n\nThis is the \\textbf{Higgs mechanism}.\n\n% The wonderful thing is that the two dof of the massless vector ad the single degree of freedom of the massless scalar couple to give a massive vector with three degrees of freedom.\n\n\n\\end{document}\n", "meta": {"hexsha": "a63600b400ae699dcc0902e52d605bf63a3ac347", "size": 7345, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ap_second_semester/astroparticle_physics/apr21.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "ap_second_semester/astroparticle_physics/apr21.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ap_second_semester/astroparticle_physics/apr21.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 42.9532163743, "max_line_length": 295, "alphanum_fraction": 0.6778761062, "num_tokens": 2321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3467903998386998}}
{"text": "\\documentclass[12pt]{cdblatex}\n\\usepackage{bssn-eqtns}\n\n\\begin{document}\n\n\\section*{PhysRevD.62.044034 equation (20)}\n\n\\begin{cadabra}\n   from shared import *\n   import cdblib\n\n   jsonfile = 'bssn-eqtns-20.json'\n   cdblib.create (jsonfile)\n\n   # --------------------------------------------------------------------------\n\n   DGiBarDt := \\partial_{t}{GammaBar^{i}}.                 # cdb(eq20.00,DGiBarDt)\n   DGiBarDt := - 2 ABar^{i j} \\partial_{j}{N}\n               + 2 N (  GammaBar^{i}_{j k} ABar^{k j}\n                      - (2/3) gBar^{i j} \\partial_{j}{trK}\n                      + 6 ABar^{i j} \\partial_{j}{\\phi}).  # cdb(eq20.01,DGiBarDt)\n\n   substitute   (DGiBarDt,defGammaBarU)                    # cdb(eq20.02,DGiBarDt)\n\n   distribute   (DGiBarDt)\n   DGiBarDt = product_sort (DGiBarDt)                      # cdb(eq20.03,DGiBarDt)\n\n   canonicalise (DGiBarDt)                                 # cdb(eq20.04,DGiBarDt)\n                                                           # cdb(eq20.99,DGiBarDt)\n\n   cdblib.put ('DGiBarDt',DGiBarDt,jsonfile)\n\\end{cadabra}\n\n\\begin{dgroup*}\n   \\begin{dmath*}\n      \\cdb{eq20.00} = \\Cdb*{eq20.01}\n                    = \\Cdb*{eq20.02}\n                    = \\Cdb*{eq20.03}\n   \\end{dmath*}\n\\end{dgroup*}\n\n\\end{document}\n", "meta": {"hexsha": "2bf4c71a0844053fbc22d3a5434ab9bfccec8813", "size": 1261, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "bssn/cadabra/bssn-eqtns-20.tex", "max_stars_repo_name": "leo-brewin/adm-bssn-numerical", "max_stars_repo_head_hexsha": "9e32c201272e9a41e7535475fe381e450b99b058", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-25T11:36:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T11:36:06.000Z", "max_issues_repo_path": "bssn/cadabra/bssn-eqtns-20.tex", "max_issues_repo_name": "leo-brewin/adm-bssn-numerical", "max_issues_repo_head_hexsha": "9e32c201272e9a41e7535475fe381e450b99b058", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bssn/cadabra/bssn-eqtns-20.tex", "max_forks_repo_name": "leo-brewin/adm-bssn-numerical", "max_forks_repo_head_hexsha": "9e32c201272e9a41e7535475fe381e450b99b058", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3255813953, "max_line_length": 82, "alphanum_fraction": 0.4829500397, "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032313, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.346769911690831}}
{"text": "\\documentclass[twoside]{MATH77}\n\\usepackage{multicol}\n\\usepackage[fleqn,reqno,centertags]{amsmath}\n\\begin{document}\n\\begmath 19.4  Converting Codes to Different Versions\n\n\\silentfootnote{$^\\copyright$1997 Calif. Inst. of Technology, \\thisyear \\ Math \\`a la Carte, Inc.}\n\n\\subsection{Purpose}\n\nThis program, {\\tt m77con}, converts codes from one version to another.\nIt is used to convert between different precisions, and to support the\nspecial comments used in some of the Fortran codes for input to a program\nthat converts programs from Fortran to C.  Support is provided for\nprecision greater than double for systems that support such a feature.\nSupport is provided for conversion between real programs and integer or\ncomplex versions of a program, and also partial double precision and\npartial quadruple precision.  Most MATH77 codes contain the comments only\nfor conversion between the single and double precision cases.  Although\ndesigned for use with MATH77 codes, {\\tt m77con} could be used in other\napplications that want a portable means to support multiple versions.  Any\nversion of a code can be used as input to {\\tt m77con} for the purpose of\ngetting another version.\n\n\\subsection{Usage}\n\n    One uses this program by creating a control file named {\\tt\nm77job}, and executing the program {\\tt m77con} from the command\nline.  The first part of this section describes the control file which\ndefines what version is desired.  The second part describes the\ncomments in the code which indicate how different versions are to be\nobtained.\n\n\\subsubsection{Transforming an Instrumented Code}\n\nIn the descriptions below, items in brackets are optional; $L_i$ is\nused for letters (frequently the first letter in the name of a\nprogram, which indicates the precision); and $T_i$ is used for\nletters associated with types. Types supported include: S, D, Q, I,\nC, Z, and W, which are used for Single precision, Double precision,\nQuadruple precision (or at least some  precision greater than\ndouble), Integer, Complex, double precision complex, and quadruple\nprecision complex respectively.\n\n``C...'' is a comment and can appear anywhere in the control file.  A\ncomment of the form ``C$>>$yyyy$-$mm$-$dd...'' is treated as a special\ncase.  It inserts a date stamp in the file being processed, which is\nused to track changes in MATH77 codes. Details on this can be found in\nthe code listing for {\\tt m77con}.\n\n``MAKE $L_{out}$ [with type $T_{out}$] [from $L_{in}$ [with type\n$T_{in}$]]'' is used to define a letter in the names of the output\nand input files and types associated with these files.  $L_{out}$ is\na letter used in output file names.  $T_{out}$ is the type for the\noutput file. If $T_{out}$ is not given it is assumed to be $L_{out}$\nif $L_{out}$ is an allowed type, is assumed to be S or D, for\n$L_{out}$ =  P or X respectively, and otherwise an error results.  (P\nis assumed to be used for partial double precision, and X for partial\nquadruple precision.)  $L_{in}$ and $T_{in}$ are defined as for\n$L_{out}$ and $T_{out}$, except they apply to input files.  If the\n``from'' clause is missing, $L_{in}$ is D, except when $L_{out}$ is\nD, in which case $L_{in}$ is S. The case of letters is not\nsignificant, except for $L_{out}$.  The case used for $L_{out}$\ndetermines the case used when substituting $L_{out}$ or $L_{in}$ into\na file name, and thus the case is significant on systems where case\nis significant in a file name.\n\n``$T$ Defined by: $L_{exp}$, {\\em keyword}, {\\em type\\_conv}, {\\em\nmach\\_const}\\/''\\newline\n``$T$ Defined by: {\\em keyword}, {\\em type\\_conv},\n{\\em conj}, {\\em imag\\_part}\\/''\\newline\nOne of these lines is needed only if the input or output code makes\nuse of a nonstandard type, namely, Q, Z, or W.  Note that W makes use\nof Q, and thus if it is used, Q must also be defined.  The first type\nof line is used to define real (as opposed to complex) types.  $L_{exp}$\nis the letter used to define the exponent part of floating point\nconstants, {\\em keyword} is the text used to declare a variable of\ntype $T$, {\\em type\\_conv} is the name of the function used for type\nconversion to type $T$, {\\em mach\\_const} is the name of the function\nused for getting machine constants, {\\em conj} and {\\em imag\\_part}\nare the functions used to conjugate or get the imaginary part of a\ncomplex expression, respectively.  The standard S, D, and C types are\ninitialized as if one had input:\\newline ``S Defined by: E, real,\nreal, r1mach'',\\newline ``D Defined by: D, double precision, dble,\nd1mach'', and \\newline ``C Defined by: complex, cmplx, conjg, aimag''\n\nNote that at most one embedded blank is allowed inside {\\em keyword},\nand if such a blank is desired it must be included on this line.\nInternally, `I' defines {\\em keyword} as ``integer'', and {\\em\ntype\\_conv} as ``int''.\n\n``VERIFY path'' if present will compare the lines of the result files\nwith lines in the files of the same name as the result files preceded\nby ``path'', and when lines are different, both lines will be printed.\nThe text in ``path'' is taken exactly as given, and is considered\nterminated by either a blank or an end of line.  This comparison is\nnot sensitive to changes in the special comment lines described in\nthe following subsection, or to differences in the number of\nblanks.\n\n``SET $A_1$, $A_2$, ... $A_n$'' is used to set values for the\nmetavariables defined by the assignments $A_i$.  These assignments, which\nsometimes are necessary to get the version of a code desired, and the\nmetavariables set by these assignments, are described in the following\nsubsection.  One can have any number of ``SET...'' lines.\n\n``STOP ...'' acts like an end of file, i.e. no more lines are read in\nthe control file.\n\n``FILE {\\em name}[[,] {\\em ext}]'' is used to specify the name of a file\nto be processed.  A ``?'' in name may be used to parameterize the name if\ndesired.  $L_{in}$ is substituted for the ``?'' (if any) and a file of\nthis name is processed as the input file.  Then $L_{out}$ is substituted\nfor ``?'' to obtain the name of the output file.  If the ``,~{\\em ext}\\/''\nis present and one of the first two characters in {\\em ext} is ``.'' this\nname is further modified by searching backward from the end of ``{\\em\nname}\\/'' looking for the first character in ``{\\em ext}\\/''.  When this\ncharacter is found, this character and the following characters in {\\em\nname} are replaced by ``{\\em ext}\\/''.  If the ``,~{\\em ext} is present\nand neither of the first two characters is a ``.'', {\\em ext} is used as\nthe name of the output file.  The input and output files can have the same\nname.  If the ``?'' is missing, there is no need to have had a ``MAKE...''\nline.  Any characters except ``,'' can appear in ``{\\em name}\\/'' or\n``{\\em ext}\\/'', as long as the results will serve as valid file names.\nExamples and Remarks, below, gives samples of FILE statements.\n\nProcessing a ``FILE...'' line involves carrying out conversions on\nthe specified input file and placing the result in the output file.\nIf a ``VERIFY...'' line is present, the output file will be compared\nwith the file specified there.  After processing a ``FILE ...'' line,\nthe next line from the control file, {\\tt m77job}, is read, and\nactions are taken as requested there.  All metavariables defined in\nprevious SET instructions become undefined if there is a new SET\ninstruction; otherwise the old values are kept.\n\n\\subsubsection{Instrumenting a Code}\n\nWe use the notation:\n\n\\begin{tabular}{l@{ }l@{ }ll}\n$L$,&$L_1$,&... $L_i$ & Letters\\newline\\\\\n$T$,&$T_1$,&... $T_i$ & Letters used to denote types\\newline\\\\\n$I$,&$I_1$,&... $I_i$ & Integer constants\\newline\\\\\n$V$,&$V_1$,&... $V_i$ & Metavariables\\newline\\\\\n$E$,&$E_1$,&... $E_i$ & Expressions\\newline\\\\\n$A$,&$A_1$,&... $A_i$ & Assignments\\newline\\\\\n\\end{tabular}\n\nThe types are: S, D, Q, I, C, Z, and W, which are used for Single\nprecision, Double precision, Quadruple precision (or at least some\nprecision greater than double), Integer, Complex, double precision\ncomplex, and quadruple precision complex respectively.  An ``$L$''\nequal to one of these letters is used for a code of the corresponding\ntype.  Other letters are used for mixtures of types.  In particular,\nP (Partial double) is used for a code that uses some D in a code that\nis primarily S (perhaps to save on storage), and X (eXtended) is used\nfor a code that is primarily in D, but uses some Q.  No other\nprecisions are supported.\n\nThere are integer, logical, and string metavariables and constants.\nAn integer constant is defined as in Fortran.  The logical constants\nare .T.\\, .F.\\, .U.\\, .D.\\, .S.\\, .I.\\, and .C.\\ Of course .T.\\ is\nalways true, and .F.\\ is false; .U.\\ is undefined (see below); .D.\\,\n.S.\\, and .I.\\ have a value of .T.\\ if the upper case of the letter\n$L_{out}$ in a MAKE command matches the letter between the dots, has a\nvalue of .F. if $L_{out}$ is defined but does not match, and otherwise\nhas the value .U.; and .C.\\ has the value .T.\\ if a version of the\ncode used as input to the Fortran to C converter is being generated,\nand is .F.  otherwise.  Initially .C.\\ =.F.; its value can be set to\n.T.\\ with the statement ``SET .C.'' in {\\tt m77job}, and can be reset\nto .F.\\ with the statement ``SET $\\sim $.C.''.  (With T=.T., F=.F.,\nand U=.U., we have, U$|$F=.U., U$|$T=.T., U\\&F=.F., U\\&T=.U., $\\sim\n$U=.U.  If U is on either side of a relational operator, the result is\n.U.)\n\nA string is defined as an arbitrary sequence of characters enclosed by\neither apostrophes ({\\tt '}), or quotes ({\\tt \"}), has the same form as a\nmetavariable (see below), or is .X., .Y., or .N.\\ \\ \\ .X.  gives the\nstring consisting of the letter used for floating point exponents in the\noutput, .Y.\\ gives the string consisting of the letter $T_{out}$, and\n.N.\\ gives the string consisting of the letter $L_{out}$.  If a\nlogical value of a string is required by the context, a string has the\nvalue .U.\n\nA metavariable is any number of nonoperators, not all of which are\ndigits, and not one of the letters ``TFUXN'' preceded and followed by\na ``.''.  Metavariables once defined remain defined until the end of\nthe file. Those metavariables defined in {\\tt m77job} remain defined\npast the end of file, until the next ``SET...'' line read in {\\tt\nm77job}. Note that metavariables appear only in ``C++...'' lines\nand in lines immediately following ``C++ Substitute for ...'' lines.\n\nExpressions may use the following operators, all of which have the same\nmeaning and precedence as their Fortran counterparts.\n\n\\begin{tabular}{ll}\nArithmetic:&        + \\hspace{8pt} $-$ \\hspace{8pt} * \\hspace{8pt} /\n \\hspace{8pt} **\\\\\nRelational:&        $<$ \\hspace{8pt} $>$ \\hspace{8pt} == \\hspace{8pt} /=\n \\hspace{8pt} $<=$ \\hspace{8pt} $>=$\\\\\nAlt. Relational:&         = \\hspace{8pt} $\\sim $=\\\\\nLogical:&           $|$ (or) \\hspace{8pt}  \\& (and) \\hspace{8pt} $\\sim $ (not)\\\\\nConcatenation:&     // \\\\\nGrouping letters:&  $\\{$ \\hspace{8pt}  $\\}$\\\\\nOther:&             ( \\hspace{8pt}  ) \\hspace{8pt} ,\\\\\n\\end{tabular}\n\nThe ``$\\{$'' and ``$\\}$'' are used to define a special operand.  If\nthe letter $L_{out}$ from the ``MAKE...'' line, see ``Transforming an\nInstrumented Code'' above, appears inside the \\{...\\}, then this\noperand has the value true, and otherwise has the value false.  The\nletters inside the \\{...\\} may optionally be separated by commas.\nThus \\{SP\\} is true if $L_{out}$ is either S or P, and is false\notherwise.\n\nWe recommend using ``=='' rather than ``='' in relational\nexpressions.  ``='' is allowed for compatibility with comments\nwritten for an earlier processor. The first ``='' in an assignment\nstatement is part of the assignment statement, not part of an\nexpression.\n\nAn expression can be formed as one would expect using the operators\nthat are available.  A diagnostic is given if one tries to mix types\nin a way that make no sense.  Integer and logical are converted to\nstrings when they appear as an operand of ``//''.\n\nAs assignment has the form: $V = E$, or simply $V$.  The latter form is\nequivalent to writing $V$=.T.\n\nThree kinds of comments in the source code initiate special processing by\nthe program.  (Not counting the ``C$<<$...'' comments which are used for\ndate stamps.) Those headed by ``C++'' are intended primarily to support\ndifferent versions of a program.  Those headed by ``C$--$'' are intended\nprimarily to support different precisions, which involves changing types in\nFortran statements.  Those headed by ``C\\%\\%'' are used to convert the\ncode to the form needed for the Fortran to C conversion program.  The\nactions for ``C++...'' lines precede other actions, and thus a ``C++...''\nline could result in turning off a ``C$--$...'' line.  Also, if there was\nno ``MAKE...'' line, type conversion is turned off, and ``C$--$...'' lines\nare simply treated like any other comments.  These comments allow either\ncase for the ``C'' and also allow an ``*'' in column one.\n\n``C++...'' lines have the form:\n\n\\begin{tabular}{@{}l@{ }l@{ }l}\n(1) & ``C++ & Code for $E$ is active''\\\\\n(2) & ``C++ & Code for $E$ is inactive''\\\\\n(3) & ``C++ & END''\\\\\n(4) & ``C++ & Of next $I$ lines, only the first $E$ are active''\\\\\n(5) & ``C++ & Default $A_1$, $A_2$, ... $A_i$'', or\\\\\n    & ``C++L & Default $A_1$, $A_2$, ... $A_i$'', or\\\\\n    & ``C++(E) & Default $A_1$, $A_2$, ... $A_i$''\\\\\n(6) & ``C++ & Current has A''\\\\\n(7) & ``C++ & Substitute for $V_1$, $V_2$, ... $V_i$ below''\\\\\n(8) & ``C++ & Replace $A_1$, $A_2$, ... $A_i$''\\\\\n(9) & ``C++ & [With first index $E_1$,]\\\\\n    &       & Save data by elements if $E_2$''\n\\end{tabular}\n\nA line of form (1) or (2) initiates a scope of applicability that is\nterminated by the next line of form (1), (2), or (3).  In either case\n(1) or (2), if $E$=.U., no change is made in this line or in the\nlines in its scope.\n\nIn the case of (1), if $E$=.T. there is no change.  If $E$=.F.,\nthe word ``active'' is changed to ``inactive'' and in the following\nscope, columns 1--71 are shifted to columns 2--72 and a C placed in\ncolumn 1.  An error message is printed if the original line was not\nblank in column 72.  (Only the first 72 characters of input lines are\nread.)\n\nIn the case of (2), if $E$=.F. there is no change.  If $E$=.T. the\nword ``inactive'' is replaced by ``active'' and in the following\nscope, columns 2--72 are copied to columns 1--71, and a blank placed\nin column 72.\n\nNo other ``C++...'' line may appear between a line of type (1) or (2)\nand the next line of type (1), (2), or (3).  No code changing action\ncan be active when the end of a Fortran program unit is reached.\n\nExamples from AMACH of lines of type (1), (2) and (3) are,\n\n\\begin{verbatim}\nc++ Code for SYS = IEEE is ACTIVE\n...\nc++ Code for SYS = AMDAHL is INACTIVE\nC ...\nc++   END\n\\end{verbatim}\n\nIn case (4), one must have $I$ (an integer constant) $>$ 0, and $E$\nmust have an integer value $ <= I$.  The following $I$ lines in the\ncode must be valid Fortran statements if column~1 is set to a blank\nand there must be $I$ lines preceding the last line of the Fortran\nprogram unit. This causes the action of storing a ` ' in column~1 of\nthe following $E$ lines, and then storing a `C' in column~1 for the\nremaining $I - E$ lines (neither shifts the line).\n\nAn example from DIVA of using this feature is (the first two lines\ngiven here are one line in the code):\n\n\\begin{verbatim}\nc++ Of next 23 lines, only the first\n                        KDIM+MAXORD are active\n      data B(1)  / 5.00000...0D-1 /\n      ...\n      data B(22) / 1.97628...5D-3 /\nC     data B(23) / 1.81159...2D-3 /\n\\end{verbatim}\n\nIn case (5) when no L or (E) is present each assignment, $A_i$, is\nexecuted if and only if the $V_i$ on the left of the ``='' in the $A_i$ is\nnot already defined.  (Recall that if $A_i$ does not contain an ``=''\nsign, it is as if it had the form ``$V_i$ = .T.''.)  $V_i$ may have been\ndefined either from a ``SET...'' line in {\\tt m77job} or from an\nearlier ``C++'' line.  When L is present, L must be a sequence of\nletters and the assignments will be processed as described for the\ncase when no L is present if and only if the current $L_{out}$ matches\none of the letters in L.  When (E) is present, the line is processed as\nabove if E is a logical expression with the value .T., else the line rest\nof the line is ignored.\n\nThe following example from DRDIVA illustrates defining a default\nvalue for NDIG of 4 for type of ``S'' or ``P'', and a default value for NDIG\nof 10 in other cases.  If NDIG has been set in {\\tt m77job}, then\nthe value set there will be used.\n\n\\begin{verbatim}\nc++SP Default NDIG = 4\nc++  Default NDIG = 10\n\\end{verbatim}\n\nIn case (6), the A must have an ``='' sign.  If the $V$ on the left\nside of the ``=''  in A is not defined this works just like a\n``C++ Default A'' line.  If $V$ is defined, then the text on the\nright of the ``='' is replaced by the current value of $V$.\n\nThe following line from AMACH shows that AMACH is currently\nconfigured for SYS = IEEE.  If SYS is not set in {\\tt m77job}, this\nvalue for SYS will continue to be used.  Otherwise the new value will\nreplace the {\\tt IEEE} on this line.\n\n{\\tt c++ CURRENT HAS SYS = IEEE}\n\nIn case (7), the following line is examined for each of the $V_i$'s in\nturn.  If such a metavariable name is found followed by an ``='' sign, and\nan integer value, the integer is replaced by the integer value of $V_i$.\nIf the ``='' sign is followed by a logical value, this value is replaced\nby the corresponding Fortran logical constant for $V_i$.  A type mismatch\nin either of these cases results in a diagnostic, with no change.  A\nvalue of .U. in this case is treated as a mismatch.\n\nThe following from DRDIVA illustrates using this feature.\n\n\\begin{verbatim}\nc++ Substitute for NDIG below\n      parameter (NDIG = 10)\n\\end{verbatim}\n\nIn case (8), the left side of each $A_i$ must be a constant character\nstring, i.e. either {\\tt '}xx...x{\\tt '} or {\\tt \"}xx...x{\\tt \"}, and\nthe right side, $E_i$,  must be an expression that evaluates to a\nstring value.  Occurrences (case of letters must match) of the\n``xx...x'' on the left of $A_i$ are replaced by the value for $E_i$.\nThe replacement is made on ``C++ Replace...'' lines, and other lines\nnot starting with ``C++''.  If this line precedes a ``C$--$...'' line\nof type (1), see below, then the replacement applies starting with\nthe first line of the file else it applies starting with the current\nline.\n\nThe following from DRDRAN illustrates this feature.\n\n\\begin{verbatim}\nc++S Default NDIG = 6\nc++  Default NDIG = 12\nc++  Replace \"f15.12\" = \"f\"//NDIG+3//\".\"//NDIG\n...\n      print'(7x,i7,'',''i5,10x,f15.12)',K...\n\\end{verbatim}\n\nCase (9) is intended primarily to avoid unnecessary mess in Fortran code\nthat would have too many continuation lines for a data statement in\nFortran when declared with a single array.  The C converter we are using\ngenerates much better code when such data statements are declared with a\nsingle array instead of a separate statement for each element.  $E_1$ must\nbe a integer expression, and $E_2$ must be logical.  If the part\ncontaining $E_1$ is missing the action is as if $E_1$ were present with a\nvalue of 1.  The data statement following this must contain exactly one\ndata item per line.  When $E_2$ = .T., the first line and every following\nline that is either a continuation line, or is a data statement for the\nsame name, is changed (if necessary) to be a data statement for a single\nelement of the array.  The index used for the array element is $E_1$ for\nthe first data statement and is incremented by one for the following\nstatements.  If $E_1$ is .F.  the first data statement line uses only the\narray name, and following lines that are either continuation lines, or\ndata statements for the same name are changed to be continue statements.\nThere is no limit on the number of continued lines.\n\nThe ``C$--$...'' lines have the form:\n\n\\begin{tabular}{@{}lll}\n(1) & ``C$-$$-$$L$ & Replaces ``?'': $V_1$, $V_2$, ...''\\\\\n(2) & ``C$-$$-$$T$ & (Type)Replaces ``?'': $V_1$, $V_2$, ...''\\\\\n(3) & ``C$-$$-$\\& & $v_1$, $v_2$, ...''\\\\\n(4) & ``C$-$$-T$ & Next line special: $S_1$, $S_2$, ...''\\\\\n(5) & ``C$-$$-$ & Begin mask code changes''\\\\\n(6) & ``C$-$$-$ & End mask code changes''\\\\\n\\end {tabular}\n\nAt most one of (1) or (2) can occur in a file, and all lines of type\n(3) must follow immediately after a (1) (2) or (3).  (No embedded\ncomments.) In case (1) $L$ denotes the value of $L_{out}$ for the\ncurrent version of the code.  (See the description of the ``MAKE...''\nline in Usage above.) If $L$ = $L_{out}$, then no names are changed.\nWhen $L=L_{in}$ the $L$ in this statement is replaced by $L_{out}$.\nEach of the $V_i$, or $v_i$, must be Fortran names with one of the\nletters replaced by a ``?''.  These names with the ``?''  replaced by\n$L_{in}$ are searched for and replaced as described below, starting\nat the beginning of the file.  A line of type (2) must follow\nimmediately after a line of type (1) or (3).  The action for this\nkind of line is similar to that for type (1),  but with $L$,\n$L_{out}$, and $L_{in}$, replaced by $T$, $T_{out}$, and $T_{in}$\nrespectively.\n\nThe following excerpt from DWCOMP illustrates lines of type (1) and\n(3).\n\n\\begin{verbatim}\nc--D replaces \"?\": ?WCOMP,?WATAN,...\nc--&   ?WSQRT,?WEXP,?WSIN,?WCOS,...\n\\end{verbatim}\n\nCase (4) is used to indicate either that something different from the\nstandard conversion is to be used on the next line, or that\nconversion to or from integer or one of the complex types is allowed.\nConversions to or from integer types occur only on lines so marked.\nFor a conversion to or from a code corresponding to the first letter\nof one of the pairs, (C, S), (Z, D), (W, Q), the conversion is done\nas if the second letter applied, except for lines marked in this\nmanner.  $T$ indicates the type to assume for the input on the\nfollowing line. The $T$ is replaced by the value used for the type of\nthe output on the next line.  The $S_i$ is either a single $L_i$, or\nan expression of the form $L_i$ $=>$ $T_i$. If $L_{out}$ is the same\nas any of these $L_i$, then the following line is treated as special\nbased on this $S_i$.  If there is no ``$=>$ $T_i$'' part then\npresumably $L_i$ is I, C, Z, or W, and the following line is\nmodifiable to suit these types.  If the ``$=>$ $T_i$'' part is\npresent, then the following line is to be converted as if the output\ntype were $T_i$.  If none of the $L_i$ match the $L_{out}$ from the\n``MAKE...'' line, the following line is treated just like any other\nline.\n\nThe following from DRDIVA illustrates specifying metavariables with a\nhigher than usual precision when $L_{out}$ is ``P'' or ``X''.  In all\nother cases the declaration here would be what one would expect\nfrom the letter specifying the precision.\n\n\\begin{verbatim}\nc--D Next line special: P=>D, X=>Q\n      double precision TSPECS(4), Y(IYDIM)...\n\\end{verbatim}\n\n?VECPR is one of the few codes in MATH77 which allows all the real\nprecisions, and also allows integer.  The first pair of lines below\nget converted to the second pair when DVECPR is converted to IVECPR.\n\n\\begin{verbatim}\nc--D Next line special: I\n      double precision  V(N)\n\nc--I Next line special: I\n      integer           V(N)\n\\end{verbatim}\n\nLines of type (5) and (6) mark the beginning and end, respectively,\nof a set of lines in which all code modifications due to ``C$--$''\ncommands will be inhibited.\n\nThe ``C\\%\\%'' lines are documented here so that those looking at the\nlibrary source will understand their purpose.  These lines only have a\nspecial meaning when they are not being treated in a special way for some\nother reason.  In particular, if a ``C++ END'' statement would be\nacceptable, then such lines are not treated in a special way.  When .C.\\ =\n.T., the ``C'' is deleted from column one in any sequence of consecutive\nlines containing ``C\\%\\%'', and a C is inserted at the start of the\nfirst line (one line only) that does not start in this way.  If .C.\\ =\n.F., and the lines are not being treated in a special way for some other\nreason, then consecutive lines starting with ``\\%\\%'' have a C inserted\nin column 1, and the next line has the character in column 1 deleted.\nThese lines provide a way of indicating changes required to get the code\nconverted to C, without using the ``C++'' mechanism, which makes the code\ndifficult to read when used frequently.\n\n\\subsection{Examples and Remarks}\n\nIf one wanted to get the partial double precision version of the\nintegration program DIVA, Chapter~14.1, one could set {\\tt m77job} to\nthe following for a unix machine.  (For a PC replace the {\\tt .f}\nwith {\\tt.for}.)\n\n{\\tt \\begin{tabbing}\n  MAKE p\\\\\n  FILE ?iva.f\\\\\n  FILE ?ivag.f \\\\\n  FILE ?ivadb.f\n\\end{tabbing}}\n\nTo convert {\\tt amach} for a VAX running UNIX, {\\tt m77job} would\ncontain the following to obtain the output file {\\tt amach.f} from\nthe input file {\\tt amach}.\n\n{\\tt \\begin{tabbing}\n  SET SYS = VAX\\\\\n  FILE amach.f\n\\end{tabbing}}\n\n\\subsection{Functional Description}\n\nThe program {\\tt m77con} converts between different versions of Fortran~77\nsource code that satisfy conventions used for MATH77.  It combines\nfunctionality from earlier programs: ``The Specializer''\n\\cite{Krogh:1974:ALS}, ``MARVEL'' \\cite{Lawson:1980:MAR}, and ``CHGTYP''\n\\cite{Lawson:1988:CHG}.\n\nThe code is processed a line at a time, first doing actions on\n``C++...'' lines, then for other lines doing the actions called for\nby ``C++...'' lines (except for replacing strings), then doing\nactions on ``C$-$$-$...'' lines, and then doing other replacements.\nProcessing restarts with the first line after initial processing of\n``C$-$$-$'' lines of types 1--3.\n\nExcept for strings defined by ``C++ Replace...'' lines, all\ncomparisons done by this code are case insensitive, all replacements\nare done in the same case as for the text found, and blanks are\nremoved before comparisons are made in the source code.\n\nLet ``in'' denote a string, keyword, variable name, or function name\nwe are searching for, and ``out'' denote the corresponding\nreplacement.  When conversion results in substitutions, if ``out'' is\nlonger than ``in'', characters to the right of ``in'' are shifted\nright to leave enough space to insert ``out''.  A diagnostic\nresults if in the process nonblank characters are shifted beyond\ncolumn 72 (and thus lost).  If ``out'' is shorter than ``in'', then\n``out'' is padded with blanks so as to occupy the same space as\n``in''.\n\nWhen type conversion is on (as it is if there is a ``MAKE...'' line\nin the control file), then all lines, except those with ``++'' or\n``$--$'' in columns 2 and 3, are examined in turn for the following:\n\nIf the ``in'' {\\em keyword} is found, it is replaced by the ``out''\n{\\em keyword}.\n\nThen ``in'' default function names for type conversion and getting\nmachine constants (see ``$T$ Defined by:...'' lines in Usage above)\nare searched for, and when found are replaced by the corresponding\nnames of the ``out'' functions.  When searching for names (here and\nbelow) they are only found if they are preceded and followed by a\nnonletter or nondigit. Function names which do not have ``mach'' as\ntheir last four letters are found only if followed by a `('.\n\nThen the $V_i$'s and $v_i$'s generated from the ``C$--$L...'',\n``C$--$T...'', and ``C$--$\\&'' lines are searched for.  When found,\n$L_{out}$ (or $T_{out}$ for names defined on ``C$--$T (Type)...''\nlines or ``C$--$\\&'' lines following such lines) replaces the letter\nin the position of the ``?'', preserving the case of the letter that\nwas there.\n\nThen, those strings defined by the ``C++ Replace...'' lines are\nsearched for and replaced if found.\n\nThen, floating point constants are converted.  These are assumed to\nconsist of (not a letter).(0 or more digits)(the letter used for\nfloating point constants in the current version)(an optional + or\n$-$)(a digit).  If such a string is found, the letter is replaced as\nspecified.\n\nWhether type conversion is on or not, lines consisting of only ``END'' are\nsearched for.  When found, {\\tt m77con} checks if there are any ``C++...''\nactions still active or if the processing is not in ``usual precision''\nmode.  In either of these cases a diagnostic is given and the processing\nreturns to normal mode.\n\n\\bibliography{math77}\n\\bibliographystyle{math77}\n\n\\subsection{Error Procedures and Restrictions}\n    The program prints a variety of error messages on the standard\noutput. An error in the control file causes the program to stop.  In\nmost cases of errors in the special comments of the files being\nprocessed, processing continues.  After 10 comparison errors in\na single file, no more comparison errors are printed for that file.\n\n\\subsection{Supporting Information}\n\nThe source language is ANSI Fortran~77.\n\nDesign and code due to F. T. Krogh, JPL, October~1994.  Multiple minor\nmodifications through April~1996.\n\n\\end{multicols}\n\\end{document}\n", "meta": {"hexsha": "c6682834bcfcb0e681d8fd1b8534b3770f7c24c3", "size": 28804, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/doctex/ch19-04.tex", "max_stars_repo_name": "jacobwilliams/math77", "max_stars_repo_head_hexsha": "b562d09e191e99eba8a5bedfec45acf7461203b1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2016-01-04T03:17:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-25T19:17:42.000Z", "max_issues_repo_path": "doc/doctex/ch19-04.tex", "max_issues_repo_name": "jacobwilliams/math77", "max_issues_repo_head_hexsha": "b562d09e191e99eba8a5bedfec45acf7461203b1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-01-17T02:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T16:04:58.000Z", "max_forks_repo_path": "doc/doctex/ch19-04.tex", "max_forks_repo_name": "jacobwilliams/math77", "max_forks_repo_head_hexsha": "b562d09e191e99eba8a5bedfec45acf7461203b1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-01-07T09:26:45.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-25T05:32:54.000Z", "avg_line_length": 47.767827529, "max_line_length": 98, "alphanum_fraction": 0.7046937925, "num_tokens": 8151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.34675854675216977}}
{"text": "% rubber: module xelatex\n\\documentclass[english,final,compress]{beamer}\n%\\usepackage[utf8]{inputenc}\n\\usepackage[T1]{fontenc}\n\\usepackage{fixltx2e}\n\\usepackage{graphicx}\n\\usepackage{longtable}\n\\usepackage{float}\n\\usepackage{wrapfig}\n\\usepackage{soul}\n\\usepackage{textcomp}\n\\usepackage{marvosym}\n\\usepackage{wasysym}\n\\usepackage{latexsym}\n\\usepackage{amssymb}\n\\usepackage{hyperref}\n\\tolerance=1000\n\\mode<beamer>{\\usetheme{Bonn}}\n\\usepackage{fontspec}\n\\defaultfontfeatures{Mapping=tex-text}\n\\usepackage{xunicode}\n\\usepackage{xltxtra}\n\\setmainfont[Scale=0.86,Mapping=tex-text]{News Gothic MT}\n\\setsansfont[Scale=0.86,Mapping=tex-text]{News Gothic MT}\n\\setmonofont[Scale=0.86,Mapping=tex-text]{Andale Mono}\n\\usepackage{polyglossia}\n\\setdefaultlanguage{english}\n\\usepackage[EU1]{fontenc}\n\\usepackage{listings}\n\\usepackage{color}\n\\usepackage{csquotes}\n\\usepackage{mdwtab}\n\\usepackage{booktabs}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{amstext}\n\\usepackage{amsthm}\n\\usepackage{listings}\n\\renewcommand\\maketitle{\\frame[plain]{\\titlepage}\\addtocounter{framenumber}{-1}}\n\\providecommand{\\alert}[1]{\\textbf{#1}}\n\n\\setbeamercolor{insult}{fg=black,bg=red!30}\n\\setbeamercolor{noinsult}{fg=black,bg=green!30}\n\\setbeamerfont*{myserif}{family=\\rmfamily,size=\\scriptsize}\n\n\\title{Tutorial Machine Learning in Python}\n\\author{Andreas M\\\"{u}ller, Hannes Schulz, Nenad Bire\\v sev and Sven \n    Behnke\\\\[5mm]\\includegraphics[width=.2\\linewidth]{style/Logo_UBo_h24_4c-crop}}\n\\date{GK Bionik Tutorial 2012}\n\\begin{document}\n\n\\maketitle\n\n\n\\lstset{%\n    basicstyle=\\small\\tt,\n    keywordstyle=\\color{beamer@bonnblue}\\bfseries, % style for keywords\n    numbers=none, % where to put the line-numbers\n    numberstyle=\\tiny, % the size of the fonts that are used for the line-numbers\n    showspaces=false, % show spaces adding particular underscores\n    showstringspaces=false, % underline spaces within strings\n    showtabs=false, % show tabs within strings adding particular underscores\n    tabsize=2, % sets default tabsize to 2 spaces\n    captionpos=b, % sets the caption-position to bottom\n    breaklines=true, % sets automatic line breaking\n    breakatwhitespace=false, \n}\n\\newcommand\\fenc{f_{\\mathrm{enc}}}\n\\newcommand\\fdec{f_{\\mathrm{dec}}}\n\\newcommand\\Wand{\\ensuremath{W_{\\mathbf{and}}}}\n\\newcommand\\Wor{\\ensuremath{W_{\\mathbf{or}}}}\n\\newcommand{\\w}[1]{\\ensuremath{\\mathbf{#1}}}\n\\newcommand\\loss{\\ell}\n\n\\frame[plain]{\\frametitle{Outline}\\tableofcontents\\addtocounter{framenumber}{-1}}\n\\section{Introduction to Python}\n\n%\\begin{frame}\n%    \\frametitle{Machine Learning Overview}\n%    \\begin{itemize}\n%        \\item Intro: Sven\n%        \\item Python: Hannes\n%        \\item Before Lunch: Unsupervised Learning (Hannes)\n%        \\item After Lunch: Supervised Learning (Nenad LinReg, Andy LogReg/kNN)\n%    \\end{itemize}\n%\\end{frame}\n\n\n\\begin{frame}\n    \\frametitle{A Short Introduction to Python}\n    \\begin{itemize}\n        \\item Please log in, using:\n            \\begin{description}\n                \\item[Username] \\alert{gkbionik}\n                \\item[Password] \\alert{tut0rial} (with a zero instead of the \n                    ``o''!)\n            \\end{description}\n    \\end{itemize}\n\\end{frame}\n\n\n\\section{Unsupervised Learning}\n\n\\subsection{PCA}\n\n\\input{pca.tex}\n\n\\subsection{k-Means}\n\n\\input{kmeans.tex}\n\n\\section{Supervised Learning}\n\n\n\\begin{frame}\n    \\frametitle{Supervised Learning -- General}\n    \\begin{itemize}\n\t\\item Task: Learn the function $ y = f(x) $ which predicts the output $y$ for the given input $x$, knowing the desired output\n        \\item Each example in data is a tuple of the input and desired output (target)\n    \\end{itemize}\n\\end{frame}\n\n\n\\begin{frame}\n    \\frametitle{Example: Supervised Learning}\n    \\begin{itemize}\n       \\item Input Data: 40 examples of persons (age, height, smoker). \n\t\\item Targets: Weight of the person (desired output)\n\t\\item Goal: Learn a function which predicts the weight for the new person\n\t\tknowing the age, height, nationality of person.\n\n    \\end{itemize}\n\\end{frame}\n\n\\begin{frame}\n    \\frametitle{Training / Test data}\n    \\begin{itemize}\n\t\\item Learning is done on the training data, for which we know the input and targets\n\t\\item To test if the model learned to predict the output, we use test data. \t\t\n    \\end{itemize}\n\\end{frame}\n\n\\subsection{Linear Regression}\n\n\\input{linreg.tex}\n\n\\subsection{Classification}\n\\begin{frame}\n    \\frametitle{Classification}\n    \\begin{itemize}\n        \\item Predict to which class a data point belongs.\n        \\item Training data are pairs $\\left( (x_0, y_0), \\cdots, (x_N, y_N)\n                \\right), x_i \\in \\mathbb{R}^n, y_i \\in \\{0, \\cdots, k\\}$\n        \\item Classical example: Spam / Ham.\n        \\item All classes known beforehand.\n        \\item Other examples: Digit recognition, cancer benign/malignant, \\ldots\n    \\end{itemize}\n\\end{frame}\n\n\\subsection{Logistic Regression}\n\n\\input{logreg.tex}\n\n\\subsection{$k$ Nearest Neighbors}\n\n\\input{knn.tex}\n\n\\end{document}\n", "meta": {"hexsha": "9e802b19e3cd2c615a4a1f447da497b6e7dd8239", "size": 4969, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "presentation/presentation.tex", "max_stars_repo_name": "wagglefoot/Target-Oxbridge-ML-workshop", "max_stars_repo_head_hexsha": "d2b547169c45f985f8f6e501c837921950565dee", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2015-01-28T15:12:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T17:29:54.000Z", "max_issues_repo_path": "presentation/presentation.tex", "max_issues_repo_name": "kbastani/tutorial_ml_gkbionics", "max_issues_repo_head_hexsha": "2317d3137cc463716b73932a70083aef70fd8eca", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "presentation/presentation.tex", "max_forks_repo_name": "kbastani/tutorial_ml_gkbionics", "max_forks_repo_head_hexsha": "2317d3137cc463716b73932a70083aef70fd8eca", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2015-08-15T08:13:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-11T19:58:53.000Z", "avg_line_length": 29.4023668639, "max_line_length": 126, "alphanum_fraction": 0.7166431878, "num_tokens": 1507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.3467585374639343}}
{"text": "\\documentclass[11pt, oneside]{article}   \t% use \"amsart\" instead of \"article\" for AMSLaTeX format\n\n\n% \\usepackage{draftwatermark}\n% \\SetWatermarkText{Draft}\n % \\SetWatermarkScale{5}\n% \\SetWatermarkLightness {0.85} \n% \\SetWatermarkColor[rgb]{0.7,0,0}\n\n\n\\usepackage{geometry}                \t\t% See geometry.pdf to learn the layout options. There are lots.\n\\geometry{letterpaper}                   \t\t% ... or a4paper or a5paper or ... \n%\\geometry{landscape}                \t\t% Activate for for rotated page geometry\n%\\usepackage[parfill]{parskip}    \t\t% Activate to begin paragraphs with an empty line rather than an indent\n\\usepackage{graphicx}\t\t\t\t% Use pdf, png, jpg, or eps� with pdflatex; use eps in DVI mode\n\t\t\t\t\t\t\t\t% TeX will automatically convert eps --> pdf in pdflatex\t\t\n\\usepackage{amssymb}\n\\usepackage{mathrsfs}\n\\usepackage{hyperref}\n\\usepackage{url}\n\\usepackage{authblk}\n\\usepackage{amsmath}\n\\usepackage{graphicx}\n\\usepackage{fixltx2e}\n\\usepackage{hyperref}\n\\usepackage{alltt}\n\\usepackage{color}\n\\usepackage{bigints}\n\n\\newcommand{\\argmax}{\\operatornamewithlimits{argmax}}\n\\newcommand{\\argmin}{\\operatornamewithlimits{argmin}}\n\n\n\\title{What is Rejection Sampling?}\n\\author{David Meyer \\\\ dmm@\\{1-4-5.net,uoregon.edu,brocade.com,...\\}}\n\n% \\date{September 30, 2015}\t\t\t\t\t\t\t% Activate to display a given date or no date\n\n\n\\begin{document}\n\\maketitle\n\n\\section{Introduction} \n\\label{sec:intro}\nSuppose that we want to sample from a distribution $f(x)$ that is difficult or impossible to sample from directly. Instead of trying to sample from $f(x)$, can we use a simpler distribution $q(x)$ from which sampling is easier? Perhaps, and the idea behind Rejection Sampling (aka Acceptance-rejection sampling) is to sample from $q(x)$ and apply some rejection/acceptance criterion such that the samples that are accepted are distributed according to $f(x)$.\n\n\\subsection{Envelope distribution and rejection criterion}\n\nIn order to be able to reject samples from $q(x)$ that aren't (approximately)   sampled from $ f(x)$, $q(x)$ must “cover” or envelop the distribution $f(x)$. This is generally done by choosing a constant $c > 1$ such that  $cq(x) > f(x)$, for all $x$. For this reason $cq(x)$ is often called the \\emph{envelope distribution}. A common criterion for accepting samples from $x \\sim q(x)$ is based on the ratio of the target distribution to that of the envelope distribution. The samples are accepted if\n\n\\begin{flalign}\n\\frac{f(x)}{cq(x)} > u\n\\end{flalign}\n\n\\noindent\nwhere $u \\sim Unif(0,1)$, and rejected otherwise. If the ratio is close to one, then $f(x) $ must have a large amount of probability mass around $x$ and that sample should  be more likely accepted. If the ratio is small, then it means that $f(x)$ has low probability mass around $x$ and we should be less likely to accept the sample. See Figure~\\ref{fig:rgr}.  I think...\n\n\n\n\\begin{figure}\n\\center{\\includegraphics[scale=0.75]{images/rejectionsamplingcriterion.png}}\n\\caption{Rejection Sampling with a Normal proposal distribution}\n\\label{fig:rgr}\n\\end{figure}\n\n\n\n\\end{document} \n\n", "meta": {"hexsha": "74a9932988436c4d7e558e0a56421df4fca6069a", "size": 3066, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "_my_stuff/papers/ml/rs/rs.tex", "max_stars_repo_name": "davidmeyer/davidmeyer.github.io", "max_stars_repo_head_hexsha": "14f01e0a50b9c643b5176a10c840f270b9da7bc1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_my_stuff/papers/ml/rs/rs.tex", "max_issues_repo_name": "davidmeyer/davidmeyer.github.io", "max_issues_repo_head_hexsha": "14f01e0a50b9c643b5176a10c840f270b9da7bc1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_my_stuff/papers/ml/rs/rs.tex", "max_forks_repo_name": "davidmeyer/davidmeyer.github.io", "max_forks_repo_head_hexsha": "14f01e0a50b9c643b5176a10c840f270b9da7bc1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.8, "max_line_length": 500, "alphanum_fraction": 0.7322243966, "num_tokens": 850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.3467585374639343}}
{"text": "\\chapter{The GNK value: A new solution}\n\\label{cha:new_solution}\n\nIn the previous chapter we introduced several different solution concepts, each stemming from different ethical principles and perspectives.\nIn this chapter we detail a new approach that combines some of the features of the solution concepts outlaid in the previous chapter.\nThe primary motivation for this new solution, is to attempt to distil the intuition behind the Nash bargaining solution concepts (per section \\ref{sec:solutions_bargaining}) into a description of total allocation that is suitable for arbitrary number of players - rather than just two.\nOur solution extends the work of others to the space of generalised non-cooperative games, which are then suitable for application in various electrical network contexts.\n\nOur solution relates to many of the concepts of the previous chapter: where we have a fundamentally coalitional scheme (per Coalitional Game Theory), that rewards based upon disagreement points (Bargaining Theory), which is partially informed by how much individual's participation influences the group's wellbeing (reminiscent of VCG), and attempts to describe normative trading between large numbers of participants (Marginalism).\n\nWe call our new solution concept the \\textit{Generalized Neyman and Kohlberg Value} or \\textit{GNK value} for short, and is computed and directly compared against other solutions concepts of the previous chapter in the context of electricity allocation.\nBy this comparison it is seen that the different solution concepts give different outcomes, and we discuss these differences in light of our ethical considerations (from Chapter \\ref{cha:background}).\n\nThe material from this chapter extends from work which was originally submitted to AAMAS, and was accepted as an extended abstract: \\\\\n\\-\\hspace{5mm}``The Generalized N\\&K Value: An Axiomatic Mechanism for Electricity Trading''\\\\ International Conference on Autonomous Agents and Multiagent Systems\\\\ (AAMAS) 2018 (accessible: \\href{ifaamas.org/Proceedings/aamas2018/pdfs/p1883.pdf}{ifaamas.org/Proceedings/aamas2018/pdfs/p1883.pdf})\n\nThis chapter consists of the following parts:\n\n\\begin{itemize}\n\\item\tIn sections \\ref{sec:prelude_gnk} and \\ref{the_value_def2}, we introduce and define the GNK value, relating it to historical roots and similar solution concepts.\n\\item\tIn section \\ref{more_involved}, we consider how the GNK value can be computed to derive financial and electrical outcomes on a DC electricity network, against LMP and VCG.\n\\item\tIn section \\ref{sec:features}, we point-by-point discuss the features GNK, LMP and VCG as they are expressed in the context of an example electricity network.\n%\\item\tin section \\ref{sec:scaling} we address the possible ways of remedying the GNK value for computation in larger network contexts, particularly via the use of sampling to approximate its value, and by the adoption of a proxy for the GNK inner optimisation (which we denote as the M-GNK).\n%\\item\tin section \\ref{sec:results_and_evaluation_of_GNK}, we detail computation and the efficiency of computation of the sampled M-GNK value for larger networks, and discuss its shortcommings for an example computed larger network.\n%\\item\tin section \\ref{sec:GNK_extensions_discussion} and the concluding section \\ref{sec:GNK_value_discussion}, we discuss possible extensions to the GNK concept and compare it point-by-point with ethical qualities.\n\\end{itemize}\n\nWe identify that the GNK value is difficult to compute for large numbers of players, and so in the next chapter \\ref{sec:scaling} we address and consider the GNK value at scale against ethical criteria.\n\n%\\begin{itemize}\n%\\item Derive the GNK value (section \\ref{the_value_def2})\n%\\item Apply it to DC networks (section \\ref{more_involved})\n%\\item We discuss some of its qualities (section \\ref{sec:features})\n%\\item Before discussing techniques to scale it (section \\ref{sec:scaling})\n%\\item Then evaluating it at scale (section \\ref{sec:results_and_evaluation_of_GNK})\n%\\item And then conclude with an ethical evaluation (section \\ref{sec:GNK_extensions_discussion})\n%\\end{itemize}\n\n\n%derive the GNK value (section \\ref{the_value_def2}) before applying it to DC networks (section \\ref{more_involved}), we discuss its qualities (section \\ref{sec:features}), before discussing techniques to scale it (section \\ref{sec:scaling}), before evaluating it at scale (section \\ref{sec:results_and_evaluation_of_GNK}) and concluding with ethical evaluation (section \\ref{sec:GNK_extensions_discussion})\n\n\n%Particularly:\n%\\begin{itemize}\n%\\item\tin sections \\ref{sec:prelude_gnk},\\ref{sec:introduction_gnk_sec},\\ref{the_value_def2}, We introduce and define the GNK value at a conceptual and mathematical level, relating it to historical roots and similar solution concepts.\n%\\item\tin sections \\ref{more_involved} we consider how the GNK value can be applied to derive financial and electrical transactions on a small example electricity network, and outlay the procedures for its computation alongside LMP and VCG in this context.\n%\\item\tin section \\ref{sec:features} we point-by-point discuss the features GNK, LMP and VCG as they are expressed in the context of the small example DC electricity network. particularly we pay attention to the fact that the GNK value is computationally difficult to compute for larger networks.\n%\\item\tin section \\ref{sec:scaling} we address the possible ways of remedying the GNK value for computation in larger network contexts, particularly via the use of sampling to approximate its value, and by the adoption of a proxy for the GNK inner optimisation (which we denote as the M-GNK).\n%\\item\tin section \\ref{sec:results_and_evaluation_of_GNK}, we detail computation and the efficiency of computation of the sampled M-GNK value for larger networks, and discuss its shortcommings for an example computed larger network.\n%\\item\tin section \\ref{sec:GNK_extensions_discussion} and the concluding section \\ref{sec:GNK_value_discussion}, we discuss possible extensions to the GNK concept and compare it point-by-point with ethical qualities.\n%\\end{itemize}\n\n%After this chapter, the next Chapter \\ref{chap:stratified_sampling_chapter} details our investigation into novel sampling methods which are which are used to scale the GNK value in section \\ref{sec:scaling}.\n\n\\section{Introduction to the GNK value}\\label{sec:prelude_gnk}\\label{sec:introduction_gnk_sec}\n\n\nHow should we model ideal competition? In the two player case, existing bargaining solutions (such as Nash's) seem rather difficult to surpass as they describe a singular and axiomatic outcome that is both cooperatively Pareto optimal and also accounts for anti-cooperative strategising.\n\nIn the context of Nash bargaining with endogenous disagreement point (per section \\ref{subsec:nash_bargaining_endogenous}), the disagreement point was interpreted as a unique point defined by a minimax equilibrium in the payoff-advantage of strategies.\nHowever there exists a problem extending this scheme directly to three or more players, as there may not exist a unique minimax equilibrium in payoff-advantages for strategies in a game of more than two players.\nThe question then is how to logically and consistently extend Nash's bargaining solution with endogenous disagreement point to an arbitrary number of players.\n\nWhile it may be possible to arbitrarily choose one of those possible minimax equilibria in a 3+ person game as the disagreement point, \ninstead we consider all the possible divisions of players between two groups and then consider all the two-player minimax payoff advantages between them. We then integrate this information via Shapley Value axioms to form a unique outcome, that does not depend on any arbitrary choice.\nIn this way our new solution allocates outcomes in proportion to the aggregate leverage that all the individuals - and groups of individuals - could hypothetically posses in bargaining for outcomes they desire.\nIn the following sections of this chapter (sections \\ref{the_value_def2} to \\ref{more_involved}) we give all the details of this process.% Particularly we note that this process of how to reasonably extend Nash's bargaining solution to multiple players has a history.\n\nThe fundamental idea behind our approach was first detailed by \\cite{values3}.\nSo far as we know, Harsanyi's solution concepts have never been applied to electricity networks, as there exists a particular problem in doing so, particularly that Harsanyi's solution concepts apply to non-cooperative games but cannot apply to generalised non-cooperative games.\nThe details of this problem and our novel remedy are given in following section \\ref{the_value_def3}.\n\nBut briefly, in electricity network contexts the mutual interactions of participants can be limited by the physical constraint of the network, for instance: network participants cannot simply draw or push power to/from the network without restraint, as doing so would lead to damage to the network.\nAnd these limitations on the space of possible mutual actions is best modelled by a generalised non-cooperative game, and unfortunately in the context of such a generalised game there is no unique minimax point between two players.\nOur principle and novel development in this chapter is the provision of a remedy, such that Harsanyi's solution can then be applied.\nThe remedy is to take the expected outcome on a coin-flip on who chooses actions first in the minimax strategies - and as we shall see - this turns out to be a unique value that satisfies all required properties, and thus leads to a coherent outcome.\n\nThe resulting outcome we call the \\textit{Generalized Neyman and Kohlberg Value} or the \\textit{GNK value} for short, \nas Harsanyi's solution was also axiomatically derived by \\cite{value2,KOHLBERG2018139}.\nThis solution concept is shown to apply for all transferable utility (TU) generalised non-cooperative games, and directly equivalent to the Nash bargaining with endogenous disagreement point under transferable utility (TU) between two players (such as per section \\ref{sec:nash_bargaining_exogenous}, as in the example in that section).\n\nThe GNK value is thus flexible enough to extend to many contexts, but we focus particularly on the specific case of allocating monetary payments over Optimal Power Flow (OPF) instances under the DC approximation - as we will explain.\n\nLet us derive the GNK value (in section \\ref{the_value_def2}) before giving details of its application to DC networks (in section \\ref{more_involved}), discussing it (section \\ref{sec:features}) and scaling it (section \\ref{sec:scaling}).\n\n\\section{Deriving the GNK value}\\label{the_value_def2}\n\nWe begin by presenting the axiomatic foundations of the GNK value, in a similar manner as \\cite{value2}'s exposition.\nWe begin by defining the GNK value to be the integration of \\emph{threat} values between possible coalitions; defined via Shapley Value axioms.\nWe then describe the \\emph{threat} or \\emph{advantage} of a coalition $v(S)$ in the context of a \\textit{generalized non-cooperative game} (which is our key point of novelty in the solution concept).\nAnd then we clarify how the GNK value relates to other prominent solution concepts in non-cooperative games.\n\n\\subsection{Axiomatic foundations and the \\textit{Value}}\\label{the_value_def}\n\n%There have been many attempts to answer the question of what cooperative outcome \\textit{should} occur in the context of a non-cooperative TU game.\n%One well known answer is the \\textit{Nash bargaining solution} between two players \\cite{nash2}, which Harsanyi extended to arbitrary numbers of players.\n%Building on this, Harsanyi's solution \\cite{values3} was derived from a simple set of axioms by Neyman and Kohlberg ~\\cite{value2}; \n%our axiomatic derivation of a value for games with generalized action spaces mirrors the steps in theirs.\n\nWe begin by considering \\cite{KOHLBERG2018139}'s \\textit{coalitional game of threats}, \nwhich is a coalitional game defined by a pair $\\langle N,v \\rangle$ in which:\n\\begin{itemize}\n\\item\t$N=\\{1,\\dots,n\\}$ is a finite set of \\textit{players} or \\textit{agents}, and\n\\item\t$v:2^N\\rightarrow \\mathbb{R}$ is a \\textit{characteristic function} with \n\\begin{equation}\nv(S)=-v(N\\setminus S) \\label{myeq2} \\quad \\forall S\\subseteq N.\n\\end{equation}\n\\end{itemize}\nThe intuition for \\eqref{myeq2} is that the characteristic function of this game is a measure of the strength of the bargaining position (the `threat' or `advantage') that a coalition, $S$, has over its complement, $N\\setminus S$.\nThis contrasts with classical cooperative game theory games, where the characteristic function $v(\\emptyset)=0$ and equation \\ref{myeq2} does not generally hold (see section \\ref{sec:cooperative_game_theory_part}).\n\nNeyman and Kohlberg's key result was to prove that if $\\mathbb{D}$ is the set of all such games, then there exists a unique mapping $\\varphi:\\mathbb{D}\\rightarrow\\mathbb{R}^n$ that satisfies the following four axioms:\n\n\\begin{itemize}\n\\item\t\\textbf{Efficiency}: $\\sum_i\\varphi(\\langle N,v\\rangle)_i = v(N)\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad~~\\refstepcounter{equation}(\\theequation)\\label{myeq}$\n\\item\t\\textbf{Symmetry}: If two players $i$ and $j$ are substitutes, such that if\\\\ $v(S\\cup i)=v(S\\cup j)~~\\forall S\\subseteq N\\setminus\\{i,j\\}$, then $\\varphi(\\langle N,v\\rangle)_i = \\varphi(\\langle N,v\\rangle)_j$\n\\item\t\\textbf{Null Player}: If a player $i$ is a null player (i.e.\\ $v(S\\cup i)=v(S)~~\\forall S\\subseteq N$) then $\\varphi(\\langle N,v\\rangle)_i=0$\n\\item\t\\textbf{Additivity}: for any $v_1$ and $v_2$, $\\varphi(\\langle N,v_1+v_2\\rangle)=\\varphi(\\langle N,v_1 \\rangle) + \\varphi(\\langle N,v_2\\rangle)$\n\\end{itemize}\n\nLetting agent $i$'s element of $\\varphi$ be denoted by $\\varphi_i$, this mapping is:\n\\begin{equation}\\label{da_value_eq} \n\\varphi_i(\\langle N,v\\rangle)\n= \\frac{1}{n}\\sum_{k=1}^n v_{i,k} \n= \\frac{1}{n}\\sum_{k=1}^n \\frac{1}{\\binom{n-1}{k-1}} \\sum_{\\substack{S:i\\in S \\\\ |S|=k}}v(S) \n\\end{equation}\nWhere $v_{i,k}$ is the average value of $v(S)$ for all coalitions of size $k$ that include $i$.\nThis mapping gives a distribution of the total surplus $v(N)$ among the players, and \\cite{KOHLBERG2018139} appropriately call this unique mapping the `Shapley Value' of the game of threats as it mirrors the classic \\textit{Shapley Value} of cooperative game theory.\n\nIndeed \\cite{KOHLBERG2018139} have shown that for any game of threats $\\langle N,v\\rangle$ there is a classic cooperative game $\\langle N,v'\\rangle$ where the two Shapley Values are the same.\nIt is possible to map a game of threats $v$ to a cooperative game $v'$ via relation:\n\\begin{equation}\\label{convert1}\nv'(S)=\\frac{1}{2}v(S)+\\frac{1}{2}v(N)\n\\end{equation}\n%Where the Shapley value is hence given by the classic expression:\n%\\begin{equation}\\label{eq:shapley_value}\n%    \\varphi_i(\\langle N,v\\rangle)= \\frac{1}{n}\\sum_{S\\subseteq N\\setminus\\{i\\}} \\binom{n-1}{|S|}^{-1} \\left(v'(S\\cup\\{i\\})-v'(S)\\right) \n%\\end{equation}\n%Which identifies the Shapley value of a player in a cooperative game as its average over marginal contributions; which we can similarly be expressed by averages over marginal contributions by player and size:\n%\\begin{equation}\\label{eq:shapley_value2}\n%\\hat{v}_{i,k} = \\frac{1}{\\binom{n-1}{k}}\\sum_{S\\subset N\\setminus \\{ i\\} , |S|=k} %\\frac{(n-|S|-1)!\\,|S|!}{(n-1)!}\n%(v'(S\\cup\\{i\\})-v'(S))\n%\\end{equation}\n%\\begin{equation}\\label{shap2} \\varphi_i(\\langle N,v\\rangle) = \\frac{1}{n}\\sum_{k=0}^{n-1}\\hat{v}_{i,k} \\end{equation}\n%These multiple formulations of the Shapley value will be useful to us in Section \\ref{} where we use these expressions in different methods of sampling the GNK value.\n\nA central question in \\cite{KOHLBERG2018139}'s coalitional game of threats, is what the `threat' of a coalition of players $v(S)$ should be (such as on an electricity network), and one way of considering this is in relation to the actions that the coalition could exert and their consequences (positive and negative) over other players; such as may be described in non-cooperative game theory.\n\n\\subsection{Defining threats in games with general action spaces}\\label{the_value_def3}\n\nIn this subsection we define the characteristic function $v(S)$, in the context of a \\textit{generalized non-cooperative game}.\nA generalised non-cooperative game is a game where the strategies available to one player may be restricted by the strategy choice of others.\nSuch games were introduced by \\cite{Debreu01101952} and the problem of finding equilibria in such games has been a topic of further research \\citep{Facchinei2007,fischer2014}.\n\nIn more detail, a generalised non-cooperative game consists of a triplet $G = \\langle N,A,u \\rangle$ in which:\n\\begin{itemize}\n\\item\t$N=\\{1,\\dots,n\\}$ is a finite set of players,\n\\item\t$A\\subseteq \\prod_{i\\in N}A^i$ is a set of all possible joint strategies, where $A^i$ denotes the set of strategies available to player $i\\in N$, and $A$ is a subset of their product space\n\\item\t$\\{u_i(a) : A\\rightarrow \\mathbb{R}\\}_{i\\in N}$ is a set of functions of each player's payoff/utility when joint strategy $a\\in A$ is executed.\n\\end{itemize}\n\nIn this context, we wish to describe the payoff `threat' or `advantage' $v(S)$ of a coalition $S\\subseteq N$ (letting $A^S=\\prod_{i\\in S}A^i$), taking into account the constraints that apply to the joint action space.  \nA key contribution in our research is the following construction of the coalitional game of threat's characteristic function. \nDenoting $(x,y)\\in A$ as a partition of a joint action between two coalitions $S$ and $N\\setminus S$, \nthe characteristic function for the game of threats with generalised action spaces is given by:\n\\begin{align}\n\\label{knvalue1}\nv(S) = &\n\\frac{1}{2}\\min_{\\substack{y\\in A^{N\\setminus S} \\\\ \\text{s.t.}\\exists x,(x,y)\\in A}} \n\\max_{\\substack{x\\in A^S \\\\ \\text{s.t.}(x,y)\\in A}}\n\t\\left(\\sum_{i\\in S} u_i(x,y) - \\sum_{i\\in N\\setminus S}u_i(x,y)\\right)\\nonumber\\\\\n+&\n\\frac{1}{2}\\max_{\\substack{x\\in A^S \\\\ \\text{s.t.}\\exists y,(x,y)\\in A}}\n\\min_{\\substack{y\\in A^{N\\setminus S} \\\\ \\text{s.t.}(x,y)\\in A}}\n\t\\left(\\sum_{i\\in S} u_i(x,y) - \\sum_{i\\in N\\setminus S} u_i(x,y) \\right)\n\\end{align}\n\nThe requisite condition $v(S)=-v(N\\setminus S)$, as given in~\\eqref{myeq2}, is immediately satisfied irrespective of the structure of strategy space $A$, insofar as the $\\max$ and $\\min$ terms are defined.\nThus, \\eqref{knvalue1} is a feasible representation of the competitive advantage (or threat) that a coalition has over its complement in a generalised strategy space.\nWith the characteristic function \\eqref{knvalue1}, the formulation of $\\varphi$ (per \\eqref{da_value_eq}) defines the GNK value.\nThis is a novel extension of existing work to the space of generalised games (see Section~\\ref{relating_to_the_old}).\n\n\\subsection{Understanding the GNK value}\\label{the_value_def4}\n\nIn the characteristic function~\\eqref{knvalue1}, the inner term:\n\\[\n\\sum_{i\\in S} u_i(x,y) - \\sum_{i\\in N\\setminus S} u_i(x,y)\n\\] \nis the sum of payoffs that the coalition $S$ receives, \nminus the sum of payoffs that the complement $N\\setminus S$ receives, \nunder the joint strategy $(x,y)\\in A$, we call this the \\textit{payoff advantage} to $S$.\n\nThe first line of $v(S)$ in~\\eqref{knvalue1} is half the payoff advantage achieved if, the players in $S$ collectively choose their strategies to maximise the payoff advantage knowing that the players in $N\\setminus S$ will subsequently choose their strategies to minimise it - and thus this dynamic constitutes a bilevel optimisation problem.\nThen the second line of~\\eqref{knvalue1} is an additional half of the payoff advantage achieved if the ordering of choice were reversed, with $N\\setminus S$ choosing first.\nIn this way, \\eqref{knvalue1} can be interpreted as the expectation of Nash equilibrium payoff advantage of $S$ over its complement under a fair coin-toss of who chooses their strategies first.\n\nIn this formulation $v(N) = \\max_{a\\in A} (\\sum_{i\\in N} u_i(a))$ is the maximum achievable sum of payoffs that the players can achieve, and the GNK value $\\varphi$, splits all of this amount between the players (by the efficiency axiom).\nThe allocation of utility that the GNK value allocates can be realised by having the players execute the strategies that achieve this maximal sum, and then enacting appropriate utility transfers between the players.\nIn this way the GNK value can be seen as a method of allocating a Pareto optimal outcome and budget-balanced payments between players, to attain utility proportional to their competitive advantages.\n\n\\subsection{Relation to other solution concepts}\\label{relating_to_the_old}\n\nThe GNK value is closely related to several other solution concepts, and even equivalent to them under certain conditions.\n\nMost immediately, the GNK value is identical to \\cite{value2}'s Value when the strategy space $A$ represents a mixed strategy game that is not generalised; that is when the strategy space, $A$, is an unconstrained combination of strategies for all agents (ie. $A = \\prod_{i\\in N}A^i$).\nTo see this, we observe that the two halves of \\eqref{knvalue1} are equal in the absence of joint action constraints (%proof in Appendix \\ref{appendix1}, or \nvia direct application of von Neumann's minimax theorem\\footnote{see Lemma 1 of \\cite{value2}}), \nand hence the characteristic value reduces to that used in Neyman and Kohlberg's original definition:\n\\begin{equation}\\label{knvalue2}v_o(S) = \\max_{x\\in A^S}\\min_{y\\in A^{N\\setminus S}} \\left(\\sum_{i\\in S} u_i(x,y) - \\sum_{i\\in N\\setminus S} u_i(x,y) \\right).\\end{equation}\n%\nThat is, Neyman and Kohlberg's Value is the formulation of $\\varphi$ (per \\eqref{da_value_eq}) \nwith $v_o(S)$ (per \\eqref{knvalue2}).\nUnfortunately Neyman and Kohlberg's Value cannot be directly applied to generalised games because the required condition $v_o(S)=-v_o(N\\setminus S)$ can fail to hold in that case. \n\nNeyman and Kohlberg's Value (and the GNK value) are also directly conceptually related to \\cite{values3}'s solution in this context,\nwhile in the 2-player context, it is identical to \\cite{kalai1,Kalai2010}'s \\textit{coco-value} in the context of complete information  \nand also identical to \\cite{nash2}'s bargaining solution in the context of transferable utility (see \\cite{value2}, or section \\ref{subsec:nash_bargaining_endogenous}).\nIt also shares a conceptual similarity with \\cite{aumann1961core}'s $\\alpha$ and $\\beta$ core solution concepts, and \\cite{1944}'s historic formulation :\n\\begin{equation}\\label{knvalue3}v_m(S) = \\max_{x\\in A^S}\\min_{y\\in A^{N\\setminus S}} \\sum_{i\\in S} u_i(x,y).\\end{equation}\nIn this way the GNK value can be seen as a conceptual continuation of historic solution concepts, and can be judged according to how well it derives outcomes in application contexts.\n\nAs a simple example demonstration, it is possible to see how the GNK value is identical to Nash bargaining in the context of transferable utility games (such as in the example matrix game \\ref{eq:example_game1} of section \\ref{subsec:nash_bargaining_endogenous}), we calculate all the terms $v(S)$ for coalitions of players $1$ and $2$, particularly:\n\n\\begin{align*}\nv(\\{1,2\\})=&\\max\\max\\begin{bmatrix}3 & -3\\\\ -3 & 3\\end{bmatrix}=3\\\\\nv(\\{1\\})=&\\frac{1}{2}\\min\\max\\begin{bmatrix}1 & 1\\\\ -1 & -1\\end{bmatrix}+\\frac{1}{2}\\max\\min\\begin{bmatrix}1 & -1\\\\ 1 & -1\\end{bmatrix}=1\\\\\nv(\\{2\\})=&\\frac{1}{2}\\min\\max\\begin{bmatrix}1 & -1\\\\ 1 & -1\\end{bmatrix}+\\frac{1}{2}\\max\\min\\begin{bmatrix}1 & 1\\\\ -1 & -1\\end{bmatrix}=-1\\\\\nv(\\emptyset)=&-\\max\\max\\begin{bmatrix}3 & -3\\\\ -3 & 3\\end{bmatrix}=-3\\\\\n\\end{align*}\nFrom this:\n$$ \\varphi_1(\\langle N,v\\rangle)=\\frac{1}{2}(v(\\{1,2\\})+v(\\{1\\}))=\\frac{1}{2}(3+1)=2 $$\n$$ \\varphi_2(\\langle N,v\\rangle)=\\frac{1}{2}(v(\\{1,2\\})+v(\\{2\\}))=\\frac{1}{2}(3-1)=1 $$\nWhich matches exactly the result in section \\ref{subsec:nash_bargaining_endogenous}. In section \\ref{subsec:nash_bargaining_endogenous} we considered that the minimax in the payoff advantage matrix (ie. $d$ in that section) was the nash equilibrium point of threat in bargaining between the players in choosing a subsequent point on the Pareto frontier (see Figure \\ref{fig:graph1_utilities}) that divides the maximum possible sum revenue (ie $s$ in that section).\nThe GNK value also directly encodes this same logic as $v(\\{1\\})=-v(\\{2\\})$ is the minimax in the payoff advantage between the player (in this ungeneralised game), and $v(\\{1,2\\})$ is the maximum sum revenue which is split. This result is the same as we would get by the \\textit{coco-value}, and working with Neyman and Kohlberg's value (equation \\ref{knvalue2}).\n\nIn the following section we describe the setup for an application and evaluation of the GNK value in the context of DC-approximated electrical networks.\n\n\\section{GNK value computation on DC powerflows}\\label{more_involved}\n\nBecause of its flexibility the GNK value has the potential to be used in a large range of different contexts,\nhowever in this section we focus solely on the development of a simple case --- the pricing of the immediate consumption and generation of power on a meshed network under DC approximation, where all participants have linear utilities over their own power.\nAlthough this construction simplifies away some key technical problems in power networks, it allows us to clarify the analysis of the GNK value and its features.\n\nIn this section, we consider the DC network model, discuss how to calculate the GNK value as well as LMP and VCG for it, before in the next section \\ref{sec:features} we discuss the features of these mechanisms with an example.\n\n\\subsection{Network model}\\label{sec:the_setup}\n\n\nWe begin by setting out the elements of an electricity network under DC approximation:\n\\begin{itemize}\n    \\item A set of buses $B$ with, for all $i\\in B$:\n    \\begin{itemize} \n        \\item Power consumption at each bus $p_i$, and \n        \\item A bus voltage phase-angle $\\theta_i$,\n    \\end{itemize}\n    \\item Lines $C\\subseteq B\\times B$, with, for all $(i,j)\\in C$: \n        \\begin{itemize} \n        \\item Line susceptance $b_{i,j}$, and \n        \\item Power flow $p_{i,j}$ (power from bus $i$ to $j$), with $p_{i,j}=-p_{j,i}$. \n    \\end{itemize}\n\\end{itemize}\nIn this context, the DC approximated powerflow constraints (per \\cite{Wang1}) are expressed as follows:\n\\begin{equation}\n\\label{dcopf1}\n\\begin{aligned}\n\\text{DC-powerflow} \\quad& \\\\\n\\text{Variables:} \\quad&  p_{i\\in B},\\ \\theta_{i\\in B},\\ p_{(i,j)\\in C} \\\\\n\\text{constraints:} \\quad& p_i^{l}\\le p_i \\le p_i^{u} \\\\\n&p_{i,j}^l \\le p_{i,j} \\le p_{i,j}^u \\\\\n&p_j = \\sum_{(i,j)\\in C}p_{i,j}\\\\\n&p_{i,j} = -b_{i,j}(\\theta_i - \\theta_j)\n\\end{aligned}\n\\end{equation}\nwhere $p_i^{l}$, $p_i^{u}$, $p_{i,j}^l$, $p_{i,j}^u$ are the upper and lower bounds on power consumption/generation and line limits, respectively.\n\nWe can eliminate redundant variables, such as $\\theta_i$ and $p_{i,j}$, and to ease presentation, and use the abstract functions $h_j$ and $g_k$ (for indices $j,k$) to represent the remaining linear functions:\n\n\\begin{equation}\n\\label{dcopf2}\n\\begin{aligned}\n\\text{DC-powerflow}\\\\\n\\text{Variables:}\\quad & p_{i\\in B} \\\\\n\\text{constraints:}\\quad & h_j(p_1,p_2,\\dots)=0\\quad \\forall j\\\\\n& g_k(p_1,p_2,\\dots)\\le 0 \\quad \\forall k\n\\end{aligned}\n\\end{equation}\n\nIn this DC powerflow network the participants on each bus are treated as players in a game.\nFor simplicity, we have one player per bus (i.e.~$N=B$), and the power consumption of that bus is the respective player's strategy space (i.e.\\ $A_i=[p_i^l,p_i^u]$).\nThen the DC constraints define the space of jointly executable strategies --- forming the generalised strategy space $A$.\n\nWe further assume that there is a linear utility (or payoff) associated with the power consumption of each player, denoted $u_i(p_i)$ for player $i$, which makes all the components of a generalised game.\\footnote{the Linear utility assumption simplifies the mathematics, as it makes the objective function linear, intuitively consumers should value consuming more power more, and generators cost producing more power more with some gradient.}\nWe now consider how to calculate the GNK value against LMP and VCG for such a generalised game.\n\n\n\n\n\n\n\\subsection{Computing the GNK value}\\label{subsec:gnk_compute1}\n\nThe GNK value is difficult to solve because of the bilevel structure of \\eqref{knvalue1} which must be computed for each of the possible coalitions of network participants.\nEven though we have modelled our example network with a set of linear utility functions and linear constraints (as given in section \\ref{sec:the_setup}), equation \\eqref{knvalue1} is still quite difficult to solve as it constitutes a linear bilevel program (LBP) which are a class of problems known by to be NP-hard. \\citep{DBLP:journals/tec/SinhaMD18,Ben-Ayed:1990:CDB} \n\nThere exist a range of techniques which can be used to solve LBPs, such as summarised by \\cite{DBLP:journals/tec/SinhaMD18,S.Dempe.Optimisations}.\nSome of the many methods include: vertex enumeration processes \\citep{Bialas:1984:TLP:2784019.2784026,Shi:2005:EKA:2641854.2642183,LIU1995644}; penalty method schemes \\citep{KleinertSchmidt2019,ONAL1993126,dempe_optimisation111};\ncutting plane approaches \\citep{cuttingplane1};\nbranch-and-bound/cut methods \\citep{SHI200551,Hansen:1992:NBR:141164.141181,Audet2007};\nand approximating algorithms \\citep{Pineda2018,rnnlbp1,genetic_algirthm_blp}.\n\nOne well known way of addressing LBPs involves converting the inner optimisation constraints into KKT conditions (introduced by \\cite{kuhn1951nonlinear}), and then converting the complementarity conditions into disjunctive constraints with binary variables - see \\cite{Fortuny-Amat1981,Pineda2018}.\nIn this way, a bilevel program is converted into a mixed integer linear program, which is then directly amenable to standard optimisation software.\nThis method was chosen, and the SCIP Optimisation Suite was employed to compute the GNK value for an example network as described in the next section \\ref{sec:example_network}.\n\nKKT conditions are a well known set of algebraic tests which imply that the function under consideration is locally optimal (maximal or alternatively minimal) with respect to its variables under a set of constraint functions (with some regularity assumptions on those functions).\nKKT are well documented, and extend the method of Lagrange multipliers.\n\nSpecifically for maximising an objective function $f(\\mathbf{x})$ subject to multiple constraints:\n\\begin{equation}\\label{eq:KKT_condition1} g_k(\\mathbf{x})\\le 0 \\end{equation}\n\\begin{equation}\\label{eq:KKT_condition2} h_j(\\mathbf{x})=0 \\end{equation}\nThen $\\mathbf{x}*$ is a local maximum if the following KKT conditions are true:\n\\begin{equation}\\label{eq:KKT_conditions3} \\nabla f(\\mathbf{x}*) - \\sum_k\\lambda_k\\nabla g_k(\\mathbf{x}*) - \\sum_j\\mu_k\\nabla h_k(\\mathbf{x}*) =0\\end{equation}\nand equations \\ref{eq:KKT_condition1} and \\ref{eq:KKT_condition2} hold for $\\mathbf{x}*$, and for all $i$ that $\\lambda_i\\ge 0$ and $\\lambda_ig_i(\\mathbf{x}*)=0$.\n\nBy KKT conditions, we can convert the DC powerflow constraints given by equations \\ref{dcopf2} into a set of equations for maximising an objective function $f(p_{i\\in B})$:\n\n\\begin{equation}\\forall i~~\\frac{\\partial f}{\\partial p_i}(p_{i\\in B})=\\sum_j\\mu_j\\frac{\\partial h_j}{\\partial p_i}(p_{i\\in B}) + \\sum_k\\lambda_k\\frac{\\partial g_k}{\\partial p_i}(p_{i\\in B})\\end{equation}\n\\begin{equation}\\forall j~~ h_j(p_{i\\in B})=0\\end{equation}\n\\begin{equation}\\forall k~~ g_k(p_{i\\in B})\\le 0\\end{equation}\n\\begin{equation}\\forall k~~ \\lambda_k \\ge 0\\end{equation}\n\\begin{equation}\\label{eq:complementarity_constraint_KKT}\\forall k~~ \\lambda_kg_k(p_{i\\in B}) = 0\\end{equation}\n\nHence the reformulation of our LBPs in equation \\ref{knvalue1} involves transforming the inner maximisation/minimisation constraints into KKT conditions.\nThe sets of variable values which satisfy the KKT conditions are called KKT points, if we denote the set of values of an maximised objective function $f(p_{i\\in B})$ at the KKT points as $\\mathcal{KKT}(f(p_{i\\in B}))$.\nThen reformulation of the inner part of \\eqref{knvalue1} to involve KKT conditions is as follows:\n\n\\begin{equation}\n\\label{kkt_optimization1}\n\\begin{aligned}\nv(S) =& \n \\frac{1}{2}\\max_{\\substack{p_i \\\\ i\\in S}}   \\min\\left[-\\mathcal{KKT}\\left(-\\sum_{i\\in S} u_i(x,y) + \\sum_{i\\in N\\setminus S}u_i(x,y)\\right)\\right] +\\\\\n&\\frac{1}{2}\\min_{\\substack{p_i \\\\ i\\notin S}}\\max\\left[\\mathcal{KKT}\\left(\\sum_{i\\in S} u_i(x,y) - \\sum_{i\\in N\\setminus S}u_i(x,y)\\right)\\right]\n\\end{aligned}\n\\end{equation}\n\n\nBy reformulating the inner maximisations/minimisations of \\eqref{knvalue1} in this way we replaced the inner minimisations/maximisations in the space $(x,y)\\in A$ with minimisations/maximisations over KKT points in the same space.%\\footnote{By doing this we tacitly we assume that $u_i(p_i)$ is continuously differentiable, and satisfy some regularity conditions.}\n\nAs the constraints under DC-approximation are linear and hence define a convex polygon,\n%if we assume that the functions $u_i(p_i)$ are concave then there is either: only ever a single KKT point for all sets of outer variables, or (if weakly-concave) then any of the KKT points will be equal to the global minima (maxima).\n%Hence the inner maximization (minimization) over the KKT points can be ignored.\nand as the functions $u_i(p_i)$ are linear (per the assumption of linear utility in section \\ref{sec:the_setup}), then there will only be a single maximum/minimum value of these inner minimisations/maximisations - which will be the global maximum/minimum value.\\footnote{as linear optimisation problem has a unique solution, although there may be multiple points which attain this maximum/minimum value}\nIn this way the inner maximisation (minimisation) over the KKT points can be ignored.\n\nIt was also realised that a binary reformulation of the complementary slackness conditions (equation \\ref{eq:complementarity_constraint_KKT}) would increase computational efficiency, and so we transformed these complementarity constraints into disjunctive binary constraints.\n\nSpecifically, for each complementary slackness condition $\\lambda_kg_k(p_{i\\in B}) = 0$ we introduced a binary variable $Z_k$ to indicate whether $\\lambda_k$ or $g_k(p_{i\\in B})$ was zero and then introduced large numbers $\\bar{\\lambda}_k$ and $ \\underline{g_k} $ such as to make the complementary slackness condition equivalent to: $(1-Z_k)\\bar{\\lambda}_k \\ge \\lambda_k \\ge 0$ and $\\underline{g_k}Z_k\\le g_k(p_{i\\in B})\\le 0$.\nWhere $\\bar{\\lambda}_k$ and $\\underline{g_k}$ are the estimated upper and lower bounds on the KKT multipliers and constraint functions respectively.\n\nthe resulting KKT conditions for maximising and objective function $f(p_{i\\in B})$ under this complementary slackness conditions are as follows:\n\n\\begin{equation}\\forall i~~\\frac{\\partial f}{\\partial p_i}(p_{i\\in B})=\\sum_j\\mu_j\\frac{\\partial h_j}{\\partial p_i}(p_{i\\in B}) + \\sum_k\\lambda_k\\frac{\\partial g_k}{\\partial p_i}(p_{i\\in B})\\end{equation}\n\\begin{equation}\\forall j~~ h_j(p_{i\\in B})=0\\end{equation}\n\\begin{equation}\\forall k~~ g_k(p_{i\\in B})\\le 0\\end{equation}\n\\begin{equation}\\forall k~~ (1-Z_k)\\bar{\\lambda}_k \\ge \\lambda_k \\ge 0\\end{equation}\n\\begin{equation}\\forall k~~ \\underline{g_k}Z_k\\le g_k(p_{i\\in B}) \\le 0\\end{equation}\n\nif we denote the set of values of an maximised objective function $f(p_{i\\in B})$ that satisfy these new KKT conditions $\\mathbb{KKT}(f(p_{i\\in B}))$.\nThen reformulation of the inner part of \\eqref{knvalue1} to involve KKT conditions is as follows:\n\nThe resulting reformulation is as follows:\n\n\\begin{equation}\n\\label{optimization_eq1}\n\\begin{aligned}\nv(S) =\n&\\frac{1}{2}\\max_{\\substack{p_i \\\\ i\\in S}}   \\left[-\\mathbb{KKT}\\left(-\\sum_{i\\in S} u_i(x,y) + \\sum_{i\\in N\\setminus S}u_i(x,y)\\right)\\right] +\\\\\n&\\frac{1}{2}\\min_{\\substack{p_i \\\\ i\\notin S}}\\left[\\mathbb{KKT}\\left(\\sum_{i\\in S} u_i(x,y) - \\sum_{i\\in N\\setminus S}u_i(x,y)\\right)\\right]\n\\end{aligned}\n\\end{equation}\n\nThis reformulation renders the LBP into a mixed integer program which is directly amenable for calculation by optimisation solvers, and the SCIP optimisation suite was used in our case.\n%Using the SCIP optimisation suite the GNK transfers were calculated for an example DC network in the next section \\ref{sec:example_network} particularly as shown in Figures \\ref{fig:1d} and \\ref{fig:1c} show the utility transfers and the post-transfer utilities under GNK.\n\n\n\\subsection{Computing the LMP transfers}\\label{subsec:LMP_compute1}\n\nComputing the Locational Marginal Price (LMP) transfers for DC electricity networks is a process described in various literature - such as by \\cite{lmp1,lmp2}.\n\nParticularly we consider optimising the sum of utility: $\\sum_{i\\in B} u_i(p_i)$ subject to the DC powerflow constraints in equations \\ref{dcopf1}.\nIn this context the power conservation constraints on each bus are the constraints $p_j = \\sum_{(i,j)\\in C}p_{i,j}$, and the lagrange multipliers associated with these constraints are the marginal prices for power on each of the respective busses.\nThis process is an application of the more general marginal price calculation procedure discussed previously in section \\ref{subsec:marginal_price_sketch}.\nWe utilised the SCIP optimisation suite\\footnote{development reported by \\cite{MaherFischerGallyetal.2017}}.\n\n\\subsection{Computing the VCG imputations}\\label{subsec:VCG_compute1}\n\nFrom section \\ref{sec:solutions_VCG} the VCG payment that a participant makes is the difference between the sum of other's utility at the social optimum point $x^*$, and the utility that others would have if the participant were not present and the optimisation were only over the remaining participants, as seen in equation \\ref{eq:VCG_payment_rule}.\n\nIn this way the socially optimum value $x^*$ needs to be computed, and then additionally an additional optimisation problem for each player - where we assume that the excluded participant has power zero $p_i=0$. Thus in our context, equation \\ref{eq:VCG_payment_rule} becomes:\n\\begin{equation}\\label{eq:VCG_calculation_DC} d_i=\\argmax_{\\sum_{j} u_j(p_j)}\\sum_{j\\ne i}u_j(p_j) - \\argmax_{\\sum_{j\\ne i} u_j(p_j), p_i=0}\\sum_{j\\ne i}u_j(p_j)\\end{equation}\n\nThe first term in this equation is the sum of utilities at the point which maximises the sum of utilities minus the player $i$.\nThe second term in this equation is the sum of other's utilities (ie. excluding player $i$) at the point which maximises the sum of other's utilities in the context that the players power is zero.\nThe first part of the equation is common to all player's contributions $d_i$, but the second negative part is unique for each.\nIn this way, if there are $n$ participants, there are $n+1$ comparable OPF optimisation problems which need to be solved to calculate VCG payments.\nThe SCIP optimisation suite was used solving these optimisation problems.\n\n\\subsection{Computing the Shapley Value imputations}\\label{subsec:Shap_compute1}\n\nFrom section \\ref{subsec:the_shapley_value} the Shapley Value utility imputations that a participant receives is the average marginal contribution that it adds to a characteristic function under ambiguity of the join ordering.\nIn this way we need to consider a characteristic function in the context of DC networks:\n\\begin{equation*}v_{shap}(S) = \\max\\sum_{j}u_j(p_j)~~~~\\text{s.t.}~~\\forall i\\notin S~~p_i=0\\end{equation*}\nThis characteristic function describes the utility that a coalition could achieve by themselves, absent any consumption/generation from those not in the coalition - it is one possible way of creating a characteristic function for DC networks.\n\nThe utilities under the Shapley Value (by efficiency axiom) sum to give the value of the grand coalition $v_{shap}(N)$ which occurs at the optimal operating point $x^*$.\nThus the Shapley Value can be implementing by enacting electrical outcomes described by $x^*$ and conducting budget balanced utility transfers between participants.\nTo calculate the Shapley Value imputations, the maximal sum of utilities under OPF for all the possible $2^n-1$ coalitions need computed, and the SCIP optimisation suite was used for these calculations.\n\n\n\n\n\\section{Some features of GNK, in context of an example}\\label{sec:features}\\label{sec:example_network}\n\nIn the previous section \\ref{more_involved} we detailed a procedure to calculate the financial payments and dispatched powers under the GNK value as well as LMP, VCG and Shapley Value, so that now we can compute and compare them with an example.\nIn this section we are thus able to witness and discuss the characteristics of the GNK value, in the context of an example 5-bus network shown in Figure \\ref{fig:example1}, with parameters given in Table~\\ref{tab:example1}.\nIn this example we calculate and subsequently consider the features of the GNK value against LMP, VCG and Shapley Value against parameter $p_1^l$ (the generator capacity in the network).\nThe results of these calculations of the financial payments are plotted against $p_1^l$ in Figures \\ref{fig:1d}, \\ref{fig:1f}, \\ref{fig:1h} and \\ref{fig:1j} for GNK, LMP, VCG and Shapley Value respectively. Which in addition to the utilities derived from power consumption/generation (Figure \\ref{fig:1b}) form the post payment utility imputations as Figures \\ref{fig:1c}, \\ref{fig:1e}, \\ref{fig:1g} and \\ref{fig:1i}.\n\n%For GNK, LMP and VCG, the power allocations and the utilities associated with these power allocations are plotted against $p_1^l$ (the generator capacity in the network) and are shown in Figures \\ref{fig:1a} and \\ref{fig:1b}.\n%And through subsequent pairs of figures we can see how the different mechanisms allocate payments and utilities in the context of constrained resources - Figures \\ref{fig:1c}, \\ref{fig:1d} for GNK, Figures \\ref{fig:1e}, \\ref{fig:1f} for LMP, Figures \\ref{fig:1g}, \\ref{fig:1h} for VCG.\n\n\n\\input{figs/Electro_table.tex}\n\n\n\n\n\\iffigures\n% \\input{graph0.tex}\n\\input{figs/GNK_graph1.tex}\n\\fi\n\nIn Figure~\\ref{fig:1a}, increasing the generator capacity from $0$ shows that power is initially consumed entirely by the consumer at bus 2, \nwho uses all $p_1^l$kW of power and values it at a rate of 1.9 units of utility. This continues until the power constraint on line (1,2) binds, at 70kW.\nThen the consumer at bus 3 begins to be supplied with power, who values it at a rate of 1.8 units of utility until its consumption is maximised at 100kW. \nThis dynamic is then repeated for the agent with the next-highest marginal utility for power (given by the utility function coefficients in Table~\\ref{tab:example1}), until the respective line constraints are also met.\n\nIn the interval of the first 70 units of generator capacity (ie. $p_1^l \\in [0,-70]$), the LMP price for this power, for both the generator at bus 1 and the consumer at bus 2, is given by its marginal value 1.9 (as the line constraint is not active). This corresponds to the slope of the black line in Figure~\\ref{fig:1f} (or \\ref{fig:1b}) over this interval. \nMore generally, the full set of the LMP transfers plotted in Figure~\\ref{fig:1f} are given by the Lagrange multiplier for power conservation in the OPF optimisation multiplied by the power consumed at that bus, and that as the generation capacity increases the marginal price of power changes, and the gradients of the lines change in discrete steps as the utility functions in the example network are linear.\n\nAdditionally, the VCG payments are plotted against $p_1^l$ in Figures \\ref{fig:1h} and resulting utilities in Figure \\ref{fig:1g}.\nThe VCG payments are similar to the LMP payments, except that instead of payment proportional to the marginal unit of electricity, each player is compensated at his/her marginal cost of their participation.\nVCG takes into account the marginal effect that each of the player's participation has upon each other at the social optimum\n\nIn contrast VCG and LMP, the GNK value takes into account the full bargaining position of each agent and also every possible coalition of agents when determining transfers, which are based on the utilities (or costs, in the case of the generator) of all agents in the system, and not just the marginal value of participation or electrical supply.\nThe GNK value is plotted against $p_1^l$ for our example in Figure~\\ref{fig:1c}, and the resulting transfers (GNK value less utility) are plotted in Figure~\\ref{fig:1d}.\n\nIn contrast to VCG, LMP and GNK, the Shapley Value exhibits character traits that are similar to LMP and VCG, particularly as the Shapley value is composed of many more marginal contributions than those ones inherent to VCG, which is in turn proportional to the marginalism inherent in LMP.\nFurthermore it has a superficial similarity to the GNK value as they both extend from the same axioms - either exhibited in section \\ref{the_value_def}, or by conversion to Shapley value by equation \\ref{convert1} thus having exactly the same axioms as in section \\ref{subsec:the_shapley_value}.\nThe Shapley Value results are plotted against $p_1^l$ for our example in Figure~\\ref{fig:1i}, and the resulting transfers (GNK value less utility) are plotted in Figure~\\ref{fig:1j}.\n\n\nFrom these graphs we can witness some of the qualities of the GNK value against LMP and VCG and the Shapley Value:\n\n% \\begin{itemize}\n% \\item GNK is continuous in the parameters of the network\n% \\end{itemize}\n\n\\subsubsection*{The GNK value, VCG and Shapley Value imputations are continuous in the parameters of the network}\nThe GNK value has some evident continuity properties, as can be seen from equation \\ref{knvalue1}, in which the minimax characteristic function, $v(S)$, always changes continuously with the utility functions $u$.\nThis continuity property is proven in the Appendix \\ref{appendix:continuity_of_GNK}, together with some associated monotonicity properties.\n%, and are generally continuous with continuous deformations of the strategy space $A$.\nThis continuity is similarly witnessed in VCG imputations, but notably not in the context of LMP payments.\n\nIt is seen that LMP features discontinuous changes in financial transfers and this can clearly be seen from the jagged edges in Figure \\ref{fig:1f}, where the payments received by generator 1 drop sharply with increasing generator capacity.\nThis happens because the change in generator capacity is changing the parameters of the network itself and its feasibility region, which yields discontinuous changes in network operating point, and thus marginal prices.\nThis dynamic under LMP might be seen to lead to a somewhat perverse incentive to produce less power than what is socially optimal, and in contrast, the utilities under the GNK value (Figure \\ref{fig:1c}), VCG (Figure \\ref{fig:1g}) and Shapley Value (Figure \\ref{fig:1i}) which feature no such drops or discontinuities.\nIn a power systems context under LMP, these discontinuities are known to occur precisely in the event of network \\emph{congestion}\nwhich is one known cause of the volatility experienced in electricity markets - see \\cite{RePEc:aen:journl:2006v27-02-a09}. \nIn contrast, the post-payment utilities under the GNK value and VCG are always continuous with network parameters.\n\n\n%In the electrical context, \n%$v(S)$ will change continuously when the utilities of the participants and/or the network constraint functions change continuously. \n%In these cases, because $v(S)$ will change continuously, the GNK value $\\varphi$ will also change continuously. \n\n% \\begin{itemize}\n% \\item the GNK value is always budget balanced\n% \\end{itemize}\n\\subsubsection*{The GNK and Shapley Value payments are always budget balanced}\nThe transactions under VCG are not necessarily budget-balanced and can yield a surplus or deficit, and transactions under LMP can yield a budget surplus (they are weakly budget balanced \\cite{Wu1996}[Fact 4]), whereas payments under the GNK value and Shapley Value are strongly budget-balanced and result in no surplus or deficit.\nThis is an outcome of the GNK value's axiomatic derivation, as given by equation \\eqref{myeq}, which is reflective of the Shapley Value axioms, per section \\ref{subsec:the_shapley_value}.\nUnder LMP, each participant is credited or debited at the effective rate of supply for their location but there is no guarantees that the total payments should add to zero.\nThis can be seen by inspecting the region $x>300$ in Figure~\\ref{fig:1f}, where generator 1 is credited $\\$56$ while the consumers are debited at $\\$133.0$, $\\$160.0$, $\\$119.0$, and $\\$64.0$ respectively, leading to a budget surplus of $\\$420$.\nThe surplus of $\\$420$ comes particularly from the existence of congestion in the example network which is well known to introduce so-called `congestion-rents'.\nAdditionally VCG payments are known not to be budget balanced generally and may yield a surplus or deficit depending on various conditions, as considered in section \\ref{sec:solutions_VCG}.\n\n\n%In a power systems context, budget-balancedness of payments is desirable in that any revenue/deficit collected is independent of the network operating conditions.\n\n% \\begin{itemize}\n% \\item the GNK value can offset those that do not receive/generate power\n% \\end{itemize}\n\\subsubsection*{The GNK value (but not VCG or LMP) can offset those that do not receive or generate power}\nThe GNK value can allocate payments between parties such that the consumers that receive power compensate those that are excluded from receiving it.\nThis can be seen from Figures \\ref{fig:1a} and \\ref{fig:1c} particularly in the region where $x<50$.\nIn this region there is only sufficient power to supply consumer 2 (who has the highest utility for that power) whereas consumers 3, 4 and 5 who would otherwise be in a position to receive that power are\ncompensated such as to be barely worse off (as can be seen from \\ref{fig:1c}).\n\nFor instance at $x=50$, generator 1 produces $50$kW which is consumed entirely by consumer 2; the utilities of the participants before transfers are: $-10, 95, 0, 0, 0$ respectively (which can be seen from Figure \\ref{fig:1b}).\nHowever under the GNK value, consumer 2 must pay both the generator and also the other consumers for its right-of-way to consumption.\n\nThe utilities after the transfers of the participants are: $0.5, 23.83, 21.33, 20.08, 19.25$ respectively (which can be seen from Figure \\ref{fig:1c}).\nIn a power systems context, this is likely to be seen as a desirable quality as it may correspond to people's intuitions about the fair allocation of resources.\nFor example, distribution network feeders that have a high penetration of PV systems have been identified by \\cite{feeder1} to experience voltage rise problems at \ntimes of high-supply/low-demand, particularly at the feeder extremities. \nIn these settings, the inverters of PV owners at the bottom are unable to inject their power into the network and also typically get no compensation for essentially a forced curtailment of their electricity generation.\n\nIn this context under LMP, curtailed generators that dont inject their power get no reward, and under VCG curtailed generators will only be allocated utility if their presence or absence would make a difference to the network operating point, which is not assured.\nUnder Shapley Value, it is witnessed that there is some rather small offset for those that do not receive power, though this is mostly determined by marginal coalitional considerations that exclude most other consumers.\n\n% \\begin{itemize}\n% \\item the GNK value is not incentive compatible\n% \\end{itemize}\n\\subsubsection*{The GNK value is not incentive compatible}\nUnlike VCG, the GNK value, LMP and Shapley Value are not \\emph{incentive compatible} in the sense that is often referred-to in Mechanism Design (see Section \\ref{sec:solutions_VCG}).\nSpecifically, the payments between parties are potentially subject to strategic manipulation if the agents are freely able to report their utility.\nIn the GNK value this can be seen in \\eqref{knvalue1}, or more easily in its reduced form, \\eqref{knvalue2}, where the payoff advantage of a coalition $v(S)$ is based on its reported utilities in minimax strategies which may not be actualised; the same consideration holds for the Shapley Value.\nBecause of this consideration, misreporting the utilities of these unactualised events may change the $v(S)$ and hence the GNK value itself.\nAdditionally, LMP is known not to be incentive compatible, and there is further work to understand exactly how consequential this would likely be - such as by \\cite{8054716}.\nIn section \\ref{sec:GNK_extensions_discussion} we continue discussion about this point.\n\n% \\begin{itemize}\n% \\item the GNK value is computationally difficult\n% \\end{itemize}\n\\subsubsection*{The GNK value and Shapley Value are computationally difficult}\nThe GNK value is more difficult than the Shapley Value, which is more difficult than VCG, which is more difficult than LMP, to compute.\nThis can be seen via \\eqref{da_value_eq} where calculating the GNK value exactly requires calculating $v(S)$ for all the $2^n-1$ possible coalitions $S$, and each calculation of $v(s)$ is an NP-hard bilevel optimisation problem.\nThe Shapley Value also requires calculating $v_{shape}(S)$ for all the $2^n-1$ possible coalitions $S$, but the calculation of $v_{shape}(S)$ is not necessarily NP-hard problem, as DC OPF problem can be a linear optimisation.\nConversely VCG calculation for $n$ agents requires $n+1$ OPF optimisations (which are potentially linear in the DC case) per equation \\ref{eq:VCG_calculation_DC}, where as LMP calculation requires exactly one OPF optimisation (as identified in section \\ref{subsec:LMP_compute1}).\n\nThe computational difficulty of the GNK value is reflected in a later Figure \\ref{fig:performance_graph2} where it is seen that even using sampling to approximate the GNK value to sufficient accuracy is witnessed to be a double-exponentially complex process. \n\n\n\\section{Summary}\n\nIn this Chapter we have introduced the GNK value from its axioms and we have considered its conceptual inheritance from other solution concepts.\nIn order to apply the GNK value to the pricing of immediate power generation and consumption in small DC networks we formally introduced the elements of the DC network and have detailed a computation methodology for the GNK value in that context.\nWe then compared the GNK against LMP, VCG and Shapley Value on a small example network to examine their features, particularly we identified that the GNK value has some nice budget-balance and continuity properties, however we also realised that the GNK is not incentive compatable and that it is difficult to calculate for larger electricity networks.\n\nIn the next chapter we consider the ways in which the computational difficultly of calculating the GNK value on larger networks can be ameliorated.\nThe two primary techniques to ameliorate this difficulty are principally by sampling, and also by the adoption of a proxy for the inner optimisations.\nWe discuss these to directions in the next chapter \\ref{sec:scaling} before actually applying these techniques for an application of GNK to larger network in section \\ref{sec:results_and_evaluation_of_GNK} where we discuss in section \\ref{sec:GNK_value_discussion}.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "37cbfabfe704c7429edadac43fe87de8fe8999d2", "size": 55408, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Thesis/chapters/new_solution.tex", "max_stars_repo_name": "Markopolo141/Thesis_code", "max_stars_repo_head_hexsha": "df7cffff8127641b0fed0309adf38cfc9372e618", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Thesis/chapters/new_solution.tex", "max_issues_repo_name": "Markopolo141/Thesis_code", "max_issues_repo_head_hexsha": "df7cffff8127641b0fed0309adf38cfc9372e618", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Thesis/chapters/new_solution.tex", "max_forks_repo_name": "Markopolo141/Thesis_code", "max_forks_repo_head_hexsha": "df7cffff8127641b0fed0309adf38cfc9372e618", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 97.3778558875, "max_line_length": 464, "alphanum_fraction": 0.7773787179, "num_tokens": 14440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3467585374639343}}
{"text": "% Features to discuss in depth:\nThis section gives a basic introduction of SymPy, and lists its features.\nA few features---assumptions, simplification, calculus, polynomials, printers,\nsolvers, and matrices---are core components of SymPy and are discussed in\ndepth. Many other features are discussed in depth in the supplementary\nmaterial.\n\n\\subsection{Basic Usage}\n\\label{sec:basic-usage}\n\\input{basic_usage.tex}\n\n\\subsection{List of Features}\n\nAlthough SymPy's extensive feature set cannot be covered in depth in this\npaper, bedrock areas, that is, those areas that are used throughout the\nlibrary, are discussed in their own\nsubsections below. Additionally, Table~\\ref{features-table} gives a compact listing\nof all major capabilities present in the SymPy codebase. This grants a\nsampling from the breadth of topics and application domains that SymPy\nservices. Unless stated otherwise, all features noted in\nTable~\\ref{features-table} are symbolic in nature. Numeric features are\ndiscussed in Section~\\ref{sec:numerics}.\n\n\\begin{longtable}[htbc]{>{\\raggedright}p{0.30\\linewidth}p{0.63\\linewidth}}\n\\caption{SymPy Features and Descriptions.\\label{features-table}}\\\\\n\\toprule\n\\textbf{Feature (submodules)} & \\textbf{Description} \\\\\n\\midrule\nCalculus (\\texttt{sympy.core}, \\texttt{sympy.calculus}, \\texttt{sympy.integrals}, \\texttt{sympy.series}) & Algorithms for computing derivatives, integrals, and limits.\\\\\n\nCategory Theory (\\texttt{sympy.categories}) & Representation of objects, morphisms, and diagrams. Tools\nfor drawing diagrams with Xy-pic~\\cite{rose1999xy}.\\\\\n\nCode Generation (\\texttt{sympy.printing}, \\texttt{sympy.codegen}) & Generation of compilable and executable code in a\nvariety of different programming languages from expressions directly. Target\nlanguages include C, Fortran, Julia, JavaScript,\nMathematica, MATLAB and Octave, Python, and Theano.\\\\\n\nCombinatorics \\& Group Theory (\\texttt{sympy.combinatorics}) & Permutations, combinations,\npartitions, subsets, various permutation groups (such as polyhedral, Rubik,\nsymmetric, and others), Gray codes~\\cite{Nijenhuis1978combinatorial},\nand Prufer sequences~\\cite{biggs1976graph}.\\\\\n\nConcrete Math (\\texttt{sympy.concrete}) & Summation, products, tools for determining whether summation\nand product expressions are convergent, absolutely convergent, hypergeometric,\nand for determining other properties; computation of Gosper's normal form~\\cite{Petkovsek1997AeqB} for two univariate polynomials.\\\\\n\nCryptography (\\texttt{sympy.crypto}) & Block and stream ciphers, including shift, Affine,\nsubstitution, Vigen\\`{e}re's, Hill's, bifid, RSA, Kid RSA,\nlinear-feedback shift registers, and Elgamal encryption.\\\\\n\nDifferential Geometry (\\texttt{sympy.diffgeom}) & Representations of manifolds, metrics, tensor\nproducts, and coordinate systems in Riemannian and pseudo-Riemannian\ngeometries~\\cite{sussman2013functional}.\\\\\n% TODO: Someone verify that this is a good summary of the diffgeom module\n\nGeometry (\\texttt{sympy.geometry}) & Representations of 2D geometrical entities, such as lines and\ncircles. Enables queries on these entities, such as asking the area of an\nellipse, checking for collinearity of a set of\npoints, or finding the intersection between objects.\\\\\n\nLie Algebras (\\texttt{sympy.liealgebras}) & Representations of Lie algebras and root systems.\\\\\n\nLogic (\\texttt{sympy.logic}) & Boolean expressions, equivalence testing, satisfiability, and normal\nforms.\\\\\n\nMatrices (\\texttt{sympy.matrices}) & Tools for creating matrices of symbols and expressions.\nBoth sparse and dense representations, as well as symbolic linear\nalgebraic operations (e.g., inversion and factorization), are\nsupported.\\\\\n\nMatrix Expressions (\\texttt{sympy.matrices.expressions}) & Matrices with symbolic dimensions (unspecified entries).\nBlock matrices.\\\\\n\nNumber Theory (\\texttt{sympy.ntheory}) & Prime number generation, primality testing, integer\nfactorization, continued fractions, Egyptian fractions, modular arithmetic,\nquadratic residues, partitions, binomial and multinomial coefficients,\nprime number tools, hexidecimal digits of $\\pi$, and integer factorization. \\\\\n\nPlotting (\\texttt{sympy.plotting}) & Hooks for visualizing expressions via matplotlib~\\cite{Hunter:2007}\nor as text drawings when lacking a graphical back-end. 2D function plotting,\n3D function\nplotting, and 2D implicit function plotting are supported.\\\\\n\nPolynomials (\\texttt{sympy.polys}) & Polynomial algebras over various coefficient domains.\nFunctionality ranges from simple operations (e.g., polynomial division) to\nadvanced computations (e.g., Gr\\\"obner bases~\\cite{Adams1994intro} and multivariate\nfactorization over algebraic number domains).\\\\\n\nPrinting (\\texttt{sympy.printing}) & Functions for printing SymPy expressions in the terminal with ASCII\nor Unicode characters and converting SymPy expressions to \\LaTeX{} and\nMathML.\\\\\n\nQuantum Mechanics (\\texttt{sympy.physics.quantum}) & Quantum states, bra--ket notation, operators, basis sets,\nrepresentations, tensor products, inner products, outer products, commutators,\nanticommutators, and specific quantum system implementations.\\\\\n\nSeries (\\texttt{sympy.series}) & Series expansion, sequences, and limits of sequences.\nThis includes Taylor, Laurent, and Puiseux series as well as special series, such\nas Fourier and formal power series.\\\\\n\nSets (\\texttt{sympy.sets}) & Representations of empty, finite, and infinite sets (including\nspecial sets such as the natural, integer, and complex numbers). Operations\non sets such as union, intersection, Cartesian product, and building sets from\nother sets are supported.\\\\\n\nSimplification (\\texttt{sympy.simplify}) & Functions for manipulating and simplifying expressions.\nIncludes algorithms for simplifying hypergeometric functions, trigonometric\nexpressions, rational functions, combinatorial functions, square root\ndenesting, and common subexpression elimination.\\\\\n\nSolvers (\\texttt{sympy.solvers}) & Functions for symbolically solving equations, systems\nof equations, both linear and non-linear, inequalities, ordinary differential\nequations, partial differential equations, Diophantine equations, and\nrecurrence relations.\\\\\n\nSpecial Functions (\\texttt{sympy.functions}) & Implementations of a number of well known special functions,\nincluding Dirac delta, Gamma, Beta, Gauss error functions, Fresnel integrals,\nExponential integrals, Logarithmic integrals, Trigonometric integrals, Bessel,\nHankel, Airy, B-spline, Riemann Zeta, Dirichlet eta, polylogarithm, Lerch\ntranscendent, hypergeometric, elliptic integrals, Mathieu, Jacobi polynomials,\nGegenbauer polynomial, Chebyshev polynomial, Legendre polynomial, Hermite\npolynomial, Laguerre polynomial, and\nspherical harmonic functions.\\\\\n\nStatistics (\\texttt{sympy.stats}) & Support for a random variable type as well as the ability to\ndeclare this variable from prebuilt distribution functions such as\nNormal, Exponential, Coin, Die, and other custom distributions~\\cite{rocklin2012symbolic}.\\\\\n\nTensors (\\texttt{sympy.tensor}) & Symbolic manipulation of indexed objects.\\\\\n\nVectors (\\texttt{sympy.vector}) & Basic operations on vectors and differential calculus with respect\nto 3D Cartesian coordinate systems.\\\\\n\\bottomrule\n\n\\end{longtable}\n\n%% Assumptions\n\\subsection{Assumptions}\n\\label{sec:assumptions}\n\\input{assumptions.tex}\n\n\\subsection{Simplification}\n\n\\input{simplification}\n\n\\subsection{Calculus}\n\\label{sec:calculus}\n\\input{calculus}\n\n\\subsection{Polynomials}\n\\input{polys}\n\n\\subsection{Printers}\n\n\\input{printers.tex}\n\n% Solvers (regular equations, maybe also mention other types of solvers like ODEs/recurrence/Diophantine)\n\\subsection{Solvers}\n\\input{solvers.tex}\n\n% Matrices (worth emphasizing that they are symbolic)\n\\subsection{Matrices}\n\n\\input{matrices}\n", "meta": {"hexsha": "21d8b6aeca7868d174758ba8902c602ee743aafa", "size": 7773, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "features.tex", "max_stars_repo_name": "ProgZone/sympy-paper", "max_stars_repo_head_hexsha": "b3b85809cc92d1fd588971f944abda9fa995a426", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 40, "max_stars_repo_stars_event_min_datetime": "2016-03-27T06:55:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-22T18:42:39.000Z", "max_issues_repo_path": "features.tex", "max_issues_repo_name": "ProgZone/sympy-paper", "max_issues_repo_head_hexsha": "b3b85809cc92d1fd588971f944abda9fa995a426", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 205, "max_issues_repo_issues_event_min_datetime": "2016-03-17T03:08:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-01T17:09:29.000Z", "max_forks_repo_path": "features.tex", "max_forks_repo_name": "ProgZone/sympy-paper", "max_forks_repo_head_hexsha": "b3b85809cc92d1fd588971f944abda9fa995a426", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 37, "max_forks_repo_forks_event_min_datetime": "2016-03-17T16:02:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-15T15:06:54.000Z", "avg_line_length": 46.8253012048, "max_line_length": 169, "alphanum_fraction": 0.8007204426, "num_tokens": 1929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.3467585374639343}}
{"text": "% Copyright 2021 Google LLC\n%\n% Use of this source code is governed by an MIT-style\n% license that can be found in the LICENSE file or at\n% https://opensource.org/licenses/MIT.\n\n%!BIB program = biber\n%!TeX program = lualatex\n%!TeX spellcheck = en-US\n\n\\documentclass[hctr2.tex]{subfiles}\n\\begin{document}\n\\section{Injectivity of H onto polynomials}\\label{injective}\nTo demonstrate injectivity, \nthe following algorithm recovers \\(T\\) and \\(M\\) given\na binary string \\(X\\) of length \\(\\abs{X} = n (1 + \\deg(H(T, M)))\\)\nrepresenting the coefficients of \nthe polynomial \\(H(T, M)\\) in binary form,\nstarting with the greatest nonzero power; thus\n\\(13\\hpoly^3\\) would encode as \\(1011 \\Concat 0^{4n -4}\\).\n\\begin{algorithmic}[1]\n    \\Procedure{GetTM}{$X$}\n    \\State \\textbf{assert} \\(\\abs{X} \\bmod n = 0\\)\n    \\State \\textbf{assert} \\(\\abs{X} \\geq 2n\\)\n    \\State \\textbf{assert} \\(X[\\abs{X} - n; n] = 0^n\\)\n    \\State \\(t \\gets \\fromint^{-1}_{n-1}(X[1;n-1])\\)\n    \\State \\textbf{assert} \\(t > 0\\)\n    \\State \\(t \\gets t-1\\)\n    \\State \\(w \\gets n(1 + \\ceil{t/n})\\)\n    \\If{\\(X[0; 1] = 0\\)}\n        \\State \\textbf{assert} \\(w + n \\leq \\abs{X}\\)\n        \\State \\(M \\gets X[w;\\abs{X}-w-n]\\)\n    \\Else\n        \\State \\textbf{assert} \\(w + 2n \\leq \\abs{X}\\)\n        \\State \\textbf{assert} \\(X[\\abs{X}-2n+1; n-1] \\neq 0^{n-1}\\)\n        \\State \\(i \\gets \\abs{X} - n - 1\\)\n        \\While{\\(X[i; 1] = 0\\)}\n            \\State \\(i \\gets i - 1\\)\n        \\EndWhile\n        \\State \\(M \\gets X[w;i - w]\\)\n    \\EndIf\n    \\State \\(T \\gets X[n;t]\\)\n    \\State \\textbf{return} \\(T, M\\)\n    \\EndProcedure\n\\end{algorithmic}\n\n\\end{document}\n", "meta": {"hexsha": "1e5b6e93b63a5e628011772f9951db1b53525d81", "size": 1615, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/injective.tex", "max_stars_repo_name": "google/hctr2", "max_stars_repo_head_hexsha": "1913bddafea9797108446d4284a1e3f8e43a1b5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2021-11-05T14:23:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T17:24:43.000Z", "max_issues_repo_path": "paper/injective.tex", "max_issues_repo_name": "google/hctr2", "max_issues_repo_head_hexsha": "1913bddafea9797108446d4284a1e3f8e43a1b5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2021-11-01T21:35:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T23:41:06.000Z", "max_forks_repo_path": "paper/injective.tex", "max_forks_repo_name": "google/hctr2", "max_forks_repo_head_hexsha": "1913bddafea9797108446d4284a1e3f8e43a1b5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-11-04T17:58:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T13:29:03.000Z", "avg_line_length": 33.6458333333, "max_line_length": 68, "alphanum_fraction": 0.5789473684, "num_tokens": 601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3467585298119606}}
{"text": "\\section{A simple multi-skill contact center}\n\\label{sec:SimpleMSK}\n\nThis section presents an example of a contact center with three\ncontact types, two\nagent groups, and three two-hours periods.  Contacts arrive\nfollowing a non-homogeneous Poisson process\nwith randomized arrival rate\n$B\\lambda_{k, p}$ for contact type~$k$ during period~$p$.\nAs in the previous section,\n$B$ is a gamma busyness factor with parameters\n$(\\alpha_0, \\alpha_0)$.\n\nWhen a contact arrives, an agent is selected from a group depending on\nthe contact type.  Contacts of type~0 can only be served by agents in\ngroup~0 while contacts of type~2 can only be served by agents in\ngroup~1.  Contacts of type~1 are served by agents in group~0, or\nin group~1 if no agent is free in group~0.\nFor contacts arriving during period~$p$,\nservice times are i.i.d.\\ exponential random variables with\nmean~$1/\\mu_p$.\nAgents in groups are not differentiated, and the total number of\nagents can change from periods to periods.\n\nA contact that cannot be served immediately is added to a waiting\nqueue corresponding to its type.  After a patience time, if service\nhas not started, the contact abandons.  For contacts arriving during\nperiod~$p$,\npatience times are i.i.d.\\ exponential variables with mean~$1/\\nu_p$.\n\nWe are interested in the overall service level defined\nby~(\\ref{eq:slab}), and the occupancy ratio\nof the first agent group defined by\n\\begin{equation}\no_i=\\frac{E\\left[\\int_0^{t_P} \\Nb[i](t)\\\n    dt\\right]}{E\\left[\\int_0^{t_P} (N_i(t)+\\Ng[i](t))\n    dt\\right]}\\label{eq:occi}\n\\end{equation}\nwhere $\\Nb[i](t)$ corresponds to the number of busy agents in\ngroup~$i$, $N_i(t)$ corresponds to the total number of agents in group~$i$,\nand $\\Ng[i](t)$ corresponds to the number of ghost agents in\ngroup~$i$, at time~$t$.\nWe also estimate $\\E[\\Sg[k, p](s)]$ for $k=0,\\ldots,K-1$ and\n$p=0,\\ldots,P-1$, the number of contacts meeting the service level\ntarget.\n\n\\subsection{Implementing the model}\n\nListing~\\ref{lst:SimpleMSK} presents the code implementing this\nmodel.\n\n\\lstinputlisting[\ncaption={A simple multi-skill contact center},%\nemph={main,simulateOneDay,MyContactFactory,MyContactMeasures},\nlabel=lst:SimpleMSK\n]\n{SimpleMSK.java}\n\nAs with previous examples, a class representing the simulator is\ndefined.  The \\texttt{main} method constructs the simulator, runs a\nsimulation, and prints some statistics.\n\nFields are declared for contact center's components, statistical\ncounters, etc.\nFor the number of served and\nabandoned contacts, simple integers are sufficient,\nbut a matrix is needed to get the number of contacts meeting service\nlevel target, for each contact type and main period.\n\nAs in previous examples, a constructor is responsible for creating all\narrival processes, agent groups, waiting queues, etc.\nThe period-change event has a preliminary period of length~0,\ntwo-hours main periods, and a wrap-up period with\nrandom length.\nFor each contact type, a factory and an arrival process are\nconstructed.  In contrast with the previous examples, the\nfactory requires the contact type identifier to be given as an\nargument.  In this example,\nall the arrival processes use the same period-change event to be\nnotified when a new period starts.  Some arrival processes could of\ncourse use different period-change events.\nConstructing the agent groups only\nrequires the period-change event for $N_i(t)$ to be automatically updated,\nand an array containing the number of agents for each period.\n\nService and patience times are generated using\nrandom variate generators adapted for multiple periods.  Such\ngenerators use a\nperiod-change event to determine the current period and select a\nperiod-specific generator to get random values.  The generic way to\nconstruct them is to create a random variate generator for each\nperiod and give the resulting array of generators, with a\nperiod-change event, to the\nconstructor of \\texttt{Multi\\-Period\\-Gen}.  For some distributions,\nincluding exponential,\nhelper methods such as \\texttt{create\\-Exponential}\nare available to construct the generators more\nconveniently.\n\nBecause each waiting queue and agent group is\nfunctionally identical, it is the task of the router to decide which contacts to\nsend to which agents or\nqueues, and from which queues contacts must be removed.\nFor the router to be constructed, a type-to-group map and a\ngroup-to-type map are needed.  The selected\n\\texttt{Single\\-FIFO\\-Queue\\-Router} class affects how these\nstructures are used.  Here, because we model a multi-skill contact\ncenter, the data structures for the routing policy become important\nand can greatly affect the performance of the contact center.\nThe choice of the subclass of \\texttt{Router} affects how\ncontacts interact with the center.\n\nThe \\texttt{simulate\\-One\\-Day} method must initialize several arrays\nof elements, including arrival processes, agent groups, and counters.\nThe same value of $B$ is used for every arrival process, because the\nbusyness is not specific to a contact type.\nAs in the previous example, the period-change event and the\narrival processes are started before the simulation starts.\n\nOne factory object has been constructed for each arrival\nprocess, the only difference between these objects being the value of\ntheir \\texttt{type} field.  This\navoids the necessity of one factory class for each contact type,\nwhich greatly improves scalability.\nThe factory constructs a contact of the\nappropriate type and generates a service and a patience times.\n\nWhen a contact of type~0 arrives, the router takes the element~0 of\nthe type-to-group map, which corresponds to an ordered list containing\nthe\nagent group~0 only.  Let $\\Nf[i](t)$ be the number of idle agents in\ngroup~$i$ available to serve contacts.\nIf $\\Nf[0](t)>0$, the contact is served\nimmediately.  Otherwise, it is added to waiting queue~0.  Contacts of\ntype~2 are treated similarly.  For contacts of type~1, the router\nobtains an ordered list containing~0 and~1.  If $\\Nf[0](t)>0$, the contact\nis served immediately by an agent in group~0.  Otherwise, it overflows\nto the next agent\ngroup in the list:  if $\\Nf[1](t)>0$, the contact is served by an\nagent in group~1.\nOtherwise, it is added at the end of the queue~1.\n\nWhen an agent within group~0 becomes free or is added, the router uses\nthe group-to-type map to obtain the ordered list $\\{1, 0\\}$.  The\nchosen\nrouter selects the queued contact with the longest waiting time rather\nthan using the order induced by the list.  If the waiting queues\naccessible for agents in group~0 contain no contact, the agent\nremains free until new arrivals occur.  Similar routing\nhappens for agents in group~1.  This is equivalent to managing a\nsingle FIFO queue by merging all\nper-type waiting queues, sorting contacts by increasing arrival\ntimes, and removing the first contact the free agent can serve.\n\nIf \\texttt{Queue\\-Priority\\-Router} was used as in previous examples,\nthe algorithm for agent selection would be the same, but waiting\nqueues would be scanned sequentially rather than considered as a\nsingle FIFO queue.  For example, if an agent in\ngroup~0 became free, the queue priority router would check for\ncontacts in queue~0 only when queue~1 is empty.\n\nEach contact exiting the system is notified to the registered\nexited-contact listener.  The \\texttt{blocked} method does nothing\nbecause\nthe capacity of the contact center is infinite; no contact is\nblocked.   When a contact leaves the queue without service, it is\ncounted as having abandoned.\nIf its waiting time is greater than or equal\nto $s$, a contact having abandoned after the acceptable waiting time\nis also counted.  When a\ncontact is served, a new service is counted.  If its waiting time is\nsmall enough, it is also counted as a contact meeting service level\ntarget.\n\nFor a contact to be counted in \\texttt{numGoodSLKP}, the main\nperiod of its arrival must be\ndetermined.  Arrivals occur in periods~$1,\\ldots,P$,\ncorresponding to main periods~$0,\\ldots,P-1$.\nIf the main period index, i.e., the period index minus one, is\nnegative or greater than or equal to~$P$,\nthe arrival occurred during the preliminary or\nwrap-up periods, and the event is ignored.  When the arrival occurs\nduring a main period, the appropriate element of the matrix is\nincremented.\n\n\\lstinputlisting[caption={Results of the program \\texttt{SimpleMSK}},%\nlabel=res:SimpleMSK,language={},float=htb,breaklines,prebreak={\\char92}\n ]{SimpleMSK.res}\n\nAfter the simulation stops, the \\texttt{stop} method of\n\\texttt{Period\\-Change\\-Event} is called,\ncomputed observations are added to collectors.\nTo keep the program simple, we estimate the occupancy ratio from\ntimes~0 to~$T$ rather than~$t_P$.  Getting the correct ratio would\nrequire the creation of a custom period-change listener to get\n$\\int_0^{t_P}\\Nb[0](t)\\ dt$ and $\\int_0^{t_P} (N_0(t)+\\Ng[0](t)) dt$ at\ntime~$t_P$, i.e., at the beginning of wrap-up period.\nThis will be done in a further example, in sections~\\ref{sec:occcor}\nand~\\ref{sec:Blend}.\nListing~\\ref{res:SimpleMSK} displays the results of the program when\nperforming 1000 independent runs.\n\n\n\\subsection{Adding a contact-by-contact trace}\n\nFor debugging or advanced statistical processing using tools such as\nSAS or R, it may be\nneeded to get a contact-by-contact trace of the simulation. This can be done\neasily by using observers, as shown in\nListing~\\ref{lst:SimpleMSKWithTrace}.\nThis example is a simplified version of the trace facility available\nin the generic simulator of call centers supporting blend and\nmulti-skill systems.\nIt shows how it is possible to extract information from a contact\nobject, and other parts of the simulator.\n\n\\lstinputlisting[\ncaption={Contact-by-contact trace added to the simple multi-skill contact\n  center example},%\nemph={main,simulateOneDay,ContactTrace},\nlabel=lst:SimpleMSKWithTrace\n]\n{SimpleMSKWithTrace.java}\n\nThis program behaves the same as the program in the preceding subsection,\nbut it creates a text file named \\texttt{contactTrace.log} with one line\nfor each processed contact, whether it has abandoned or was served.\nOne can then open the resulting (large) trace file with any text\neditor, or make a program to parse it.\nListing~\\ref{res:SimpleMSKWithTrace} displays ten lines of the trace\nproduced by the program.  We cannot display the full trace, because\nits size is 2MB, even though we have simulated only five days.\n\nThe trace contains the following fields:\n\\begin{description}\n\\item[Step] The index of the replication the contact arrived in.\n\\item[Type] The type of the contact.\n\\item[Period] The period the contact arrived in.\n\\item[ArvTime] The simulation time of the contact's arrival.\n\\item[QueueTime] The waiting time in queue of the contact.\n\\item[Outcome] The outcome of the contact, can be \\texttt{Served} or \\texttt{Abandoned}.\n\\item[Group] The group index of the agent who has served the contact, or\n  $-1$ for abandoned contacts.\n\\item[SrvTime] The service time of the contact, or \\texttt{NaN} for\n  unserved contacts.\n\\end{description}\n\n\\lstinputlisting[caption={Sample trace produced by the program \\texttt{SimpleMSKWithTrace}},%\nlabel=res:SimpleMSKWithTrace,language={},float=htb\n ]{SimpleMSKTrace.res}\n\nThe program defines a class named \\texttt{SimpleMSKWithTrace} which\nextends \\texttt{SimpleMSK} to inherit the simulation logic of the\nexample in the previous subsection, but it adds a new exited-contact\nlistener to the router for logging contacts.\nThis trace manager, which is initialized at the beginning of the\nsimulation, writes a trace entry to a file for any exiting contact.\nIt does not have any effect on how the contacts are managed by the\nsimulator.\n\nThe new subclass defines three fields: the trace manager, the output\ntrace file, and the current\nreplication number.\nThe first two fields are initialized by the constructor, which also\nattach the trace manager to the router, defined in the superclass\n\\texttt{Simple\\-MSK}.\nThis way, every contact processed by the router is broadcast to the contact\ntrace manager.\nMoreover, one could disable the contact-by-contact trace simply by unregistering\nthe trace manager from the router.\n\nThe last field is updated after each replication by an overridden\n\\texttt{simulate\\-One\\-Day} method, and is used when formatting trace\nentries.\n\nThe overridden \\texttt{simulate} method opens the trace file at\nthe beginning of the simulation, calls the \\texttt{simulate} method\nfrom the superclass to\nperform the simulation, and closes the trace at the end.\nWe put the call to \\texttt{close} into a\n\\texttt{finally} block that will be called even if an unexpected\nexception is thrown by the simulator.\nThis prevents any loss of information caused by an unflushed buffer.\n\nThe main part of the program is the\n\\texttt{Trace\\-Manager} inner class which is an exited-contact listener\nproducing the data written into the trace.\nA trace manager has an associated print writer used to format trace\nentries into the output file.\n\nLog lines are constructed by the \\texttt{dequeued} and \\texttt{served}\nmethods of \\texttt{Trace\\-Manager}, using the \\texttt{format} method\nof \\texttt{Print\\-Writer}.\nNote how the arrival time, the service time, the waiting time, the\ncontact type, etc.\\ can all be extracted from the \\texttt{Contact}\nobject.\nThe \\texttt{format} method fills a user-provided pattern\nby using the values given by the remaining arguments.  The print stream\ntakes the system's current locale and the line separator into account.\n\nArrival times and time durations are formatted with a fixed\nnumber \\texttt{timePrecision} of decimal digits of precision, which is\nset to 3 in this program.\nThis allows for a better visual formatting of the data in the plain\ntext file.\nOne could easily use another format, e.g., XML, or use JDBC to\nwrite data into a database instead of a file.\n\n\\subsection{Rerouting queued contacts}\n\nAgents may sometimes be allowed to serve some types of contacts only\nafter the contacts have waited for some time in queue.\nFor example, we can modify the model of this example to allow agents\nin group~1 to serve contacts of type~1 only after these contacts have\nwaited more than 12s.\nThis can be done by customizing the router as in\nListing~\\ref{lst:SimpleMSKWithRerouting} for \\emph{contact rerouting},\ni.e., the router can, after a delay elapses, reprocess a queued\ncontact for a new agent selection with different criteria.\nNote that the router in ContactCenters also supports \\emph{agent\n  rerouting} which is not covered in this example but\nworks in a way similar to contact rerouting:\nif an agent stays free after the end of a service for a certain delay,\nthe router can reprocess the agent to do a new contact selection, with\ndifferent criteria.\nOf course, agent rerouting requires the agent groups to keep track of\nindividual agents.\n\n\\lstinputlisting[\ncaption={Contact rerouting added to the simple multi-skill contact\n  center example},%\nemph={main,MyRouter},\nlabel=lst:SimpleMSKWithRerouting\n]\n{SimpleMSKWithRerouting.java}\n\nThe customized router, named \\texttt{My\\-Router}, extends the\n\\texttt{Single\\-FIFO\\-Queue\\-Router} used by the original example.\nAs a result, the agent and contact selections are performed the same\nway as in the original example, but we use a different type-to-group\nmap which allows incoming contacts of type~1 to be served by agents in\ngroup~0 only.\n\nContact rerouting works as follows.\nWhen a new contact is notified to the router, an agent is selected by\nthe \\texttt{select\\-Agent} methods which is given the new contact as\nits argument. This method must construct and return an end-service\nevent representing the served contact, or \\texttt{null} if the contact\ncannot be served.\nWhen the contact cannot be served, it is added into a waiting queue by\nthe \\texttt{select\\-Waiting\\-Queue} method of the router.\nIf the contact can be queued, the router obtains its initial\n\\emph{rerouting delay}, i.e., the time after which the queued contact\nis reprocessed if still in queue.\nIf this delay is negative, no rerouting happens, which is the default.\nWhen a positive rerouting delay elapses for a queued contact, the\nrouter passes this queued contact to a second \\texttt{select\\-Agent}\nmethod which accepts the dequeue event along with the number of\nreroutings done. For the first rerouting, this corresponds to 0.\nThis new method returns an end-service event or \\texttt{null}, exactly\nas the ordinary \\texttt{select\\-Agent} method.\nOf course, the scheme for agent selection implemented by this method\nshould differ from the scheme implemented by the ordinary\n\\texttt{select\\-Agent} method.\nIf the contact still cannot be served, it remains in queue, and a new\nrerouting delay is required.\nThe process continues until a negative delay is obtained, the contact\nis served, or abandons.\n\nThe initial rerouting delay is obtained\nusing \\texttt{get\\-Rerouting\\-Delay} with\n$-1$ as the number of preceding reroutings. By\ndefault, this method always returns $-1$, which results in no rerouting.\nIn our case, we return \\texttt{DELAY} if the number of reroutings done\nis $-1$, or $-1$ otherwise.\nThe \\texttt{select\\-Agent} method for rerouting applies the overflow\nrouting of the\noriginal example, which allows contacts of type~1 to be routed to\nagents in group~1 when no agent is available in group~0.\n\nWe also need to override contact selection in order to prevent an\nagent in group~1 to dequeue a contact of type~1 if its waiting time is\nsmaller than \\texttt{DELAY}.  We therefore override the\n\\texttt{select\\-Contact}\nmethod of \\texttt{Router}, which accepts an agent group containing the\nfree agents, and returns the dequeue event representing the\ncontact to serve.\nOur method scans the waiting queues accessible to the free agent, and\nrecords the waiting queue whose first contact has the smallest enqueue\ntime. However, if the free agent is in group~1, the method filters out\nqueue~1 if the first contact has a waiting time smaller than\n\\texttt{DELAY}.\nAfter the queue is selected, the first contact is removed, and\nreturned.  The contact is removed with dequeue type\n\\texttt{DEQUEUETYPE\\_BEGINSERVICE} which is used to represent the\nbeginning of the service for a queued contact.\n\nListing~ \\ref{res:SimpleMSKWithRerouting} shows that the modified\nprogram produces slightly different results: the number of contacts\nhaving abandoned is higher and the service level is smaller than with\nthe original model.  The simulator behaves as we would expect:\nsome contacts of type~0 have to wait 12s longer in queue before they\ncan be served, and some of them abandon while they were served in the\noriginal setting.\n\n\\lstinputlisting[caption={Results of \\texttt{SimpleMSKWithRerouting}},%\nlabel=res:SimpleMSKWithRerouting,language={},float=htb,breaklines,prebreak={\\char92}\n ]{SimpleMSKWithRerouting.res}\n", "meta": {"hexsha": "37aabafc605a3c2d8b67cb72edbe088505e9ef47", "size": 18757, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/examples/simplemsk.tex", "max_stars_repo_name": "umontreal-simul/contactcenters", "max_stars_repo_head_hexsha": "f5ddb4a0a4b30dbf436ac36e6d97facce2f3576d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/examples/simplemsk.tex", "max_issues_repo_name": "umontreal-simul/contactcenters", "max_issues_repo_head_hexsha": "f5ddb4a0a4b30dbf436ac36e6d97facce2f3576d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/examples/simplemsk.tex", "max_forks_repo_name": "umontreal-simul/contactcenters", "max_forks_repo_head_hexsha": "f5ddb4a0a4b30dbf436ac36e6d97facce2f3576d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.8606356968, "max_line_length": 93, "alphanum_fraction": 0.7889854454, "num_tokens": 4578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3467585298119606}}
{"text": "\\subsection{Bernstein inequalities}\\label{subsec:bernstein_inequalities}\n\n\\begin{definition}\\label{def:real_function_space_operators}\n  Consider the \\hyperref[def:function]{operator} \\( T: C([a, b]) \\to C([a, b]) \\).\n\n  \\begin{thmenum}\n    \\thmitem{def:real_function_space_operators/positive} If \\( f([a, b]) \\subseteq [0, \\infty) \\) implies \\( T(f)([a, b]) \\subseteq [0, \\infty) \\), we say that \\( T \\) is \\term{positive}.\n\n    \\thmitem{def:real_function_space_operators/monotone} If \\( f(x) \\leq g(x) \\) for all \\( x \\in [a, b] \\) implies \\( T(f)(x) \\leq T(g)(x) \\) for all \\( x \\in [a, b] \\), we say that \\( T \\) is \\term{monotone}.\n  \\end{thmenum}\n\\end{definition}\n\n\\begin{definition}\\label{def:periodic_function_space}\\mcite[44]{Николов2020Лекции}\n  We denote by \\( \\tilde{C}([a, b]) \\) the subspace of \\( C([a, b]) \\) consisting of all continuous functions in \\( [a, b] \\) which are periodic with minimal period \\( b - a \\).\n\\end{definition}\n\n\\begin{definition}\\label{def:approximation_error}\\mcite[44]{Николов2020Лекции}\n  We introduce two operators.\n\n  \\begin{thmenum}\n    \\thmitem{def:approximation_error/algebraic} The \\term{algebraic approximation error}\n    \\begin{balign*}\n      E_n: C([a, b]) \\to [0, \\infty] \\\\\n      E_n(f) \\coloneqq \\inf_{p \\in \\pi_n} \\norm{f - p}.\n    \\end{balign*}\n\n    \\thmitem{def:approximation_error/trigonometric} The \\term{trigonometric approximation error}\n    \\begin{balign*}\n      \\tilde{E}_n: C([a, b]) \\to [0, \\infty] \\\\\n      \\tilde{E}_n(f) \\coloneqq \\inf_{p \\in \\tau_n} \\norm{f - p}.\n    \\end{balign*}\n  \\end{thmenum}\n\\end{definition}\n\n\\begin{theorem}[Jackson's trigonometric theorem]\\label{thm:jacksons_trigonometric_theorem}\\mcite[47]{Николов2020Лекции}\n  For \\( f \\in \\tilde{C}[-\\pi, \\pi] \\) we have\n  \\begin{equation*}\n    \\tilde{E}_n(f) \\leq \\frac {6^{k+1}} {n^k} \\omega\\left(f^{(k)}, \\frac 1 n \\right).\n  \\end{equation*}\n\\end{theorem}\n\n\\begin{theorem}[Szego’s inequality]\\label{thm:szegos_trigonometric_inequality}\\mcite[55]{Николов2020Лекции}\n  For any nonnegative integer \\( n \\) and any \\( s \\in S_{\\tau_n} \\), we have\n  \\begin{equation}\\label{eq:thm:szegos_trigonometric_inequality}\n    [s'(\\theta)]^2 + n^2 s^2 (\\theta) \\leq n^2 \\quad\\forall \\theta \\in [-\\pi, \\pi].\n  \\end{equation}\n\\end{theorem}\n\\begin{proof}\n  Fix \\( n = 1, 2, \\ldots \\) and \\( \\alpha \\in [-1, 1] \\).\n\n  For brevity, denote \\( c(\\theta) \\coloneqq \\cos(n \\theta) \\). Let \\( \\theta_s \\) and \\( \\theta_c \\) be numbers in \\( [-\\pi, \\pi] \\) such that\n  \\begin{equation*}\n    s(\\theta_s) + c(\\theta_c) = \\alpha.\n  \\end{equation*}\n\n  We will show that\n  \\begin{equation}\\label{eq:thm:szegos_trigonometric_inequality/abs}\n    \\abs{s'(\\theta_s)} \\leq \\abs{c'(\\theta_c)}\n  \\end{equation}\n\n  This will, in turn, imply that\n  \\begin{equation*}\n    [s'(\\theta_s)]^2\n    \\leq\n    [c'(\\theta_c)]^2\n    =\n    n^2 [\\sin(n \\theta_c)]^2\n    \\reloset {\\ref{thm:trigonometric_identities/pythagorean_identity}}\n    =\n    n^2 [1 - \\cos(n \\theta_c)^2]\n    =\n    n^2 [1 - s(\\theta_s)]\n  \\end{equation*}\n  which is equivalent to \\eqref{eq:thm:szegos_trigonometric_inequality}.\n\n  Now we will prove \\eqref{eq:thm:szegos_trigonometric_inequality/abs}. If \\( \\theta_c \\) is a critical point of \\( c \\), i.e. if \\( r'(\\theta_c) = 0 \\), then \\( c'(\\theta_c) = s'(\\theta_s) \\) and \\eqref{eq:thm:szegos_trigonometric_inequality/abs} holds. Suppose that \\( \\theta_c \\) is not a critical point. Denote by\n  \\begin{equation*}\n    \\theta_n \\coloneqq \\tfrac k n \\pi, k = -n, -n+1, \\ldots, n-2, n-1.\n  \\end{equation*}\n  the extrema of \\( c(\\theta) \\) in \\( [-\\pi, \\pi) \\).\n\n  Define the auxiliary function\n  \\begin{equation*}\n    r(\\theta) \\coloneqq c(\\theta) - s(\\theta - \\theta_c + \\theta_s).\n  \\end{equation*}\n\n  We now have \\( r(\\theta_c) = c(\\theta_c) - s(\\theta_s) = 0 \\).\n\n  Furthermore, since \\( \\norm{s} = 1 \\), then \\( \\abs{s(\\theta)} \\leq 1 \\) for all \\( \\theta \\in [-\\pi, \\pi) \\). Therefore, \\( r(\\theta_k) \\leq 0 \\) for all odd \\( k \\) and \\( r(\\theta_k) \\geq 0 \\) for all even \\( k \\).\n\n  If \\( \\theta_c \\) coincides with any of the extrema \\( \\theta_k \\), then \\( r(\\theta_c) \\) holds trivially. Suppose that \\( \\theta_c \\) is between \\( \\theta_{k-1} \\) and \\( \\theta_k \\). Without loss of generality, assume that \\( k \\) is even.\n\n  By the intermediate value theorem, there exists a zero of \\( r \\) between \\( r(\\theta_c) \\) and \\( r(\\theta_k) \\). If \\( r(\\theta_c) < 0 \\), then \\( \\theta_c \\) is a local minimum and hence there exists a point \\( \\theta_{c'} \\) between \\( r(\\theta_{k-1}) \\) and \\( \\theta_c \\) such that \\( r(\\theta_{c'}) = r(\\theta_c) = 0 \\). But this would imply that \\( r \\) has more than \\( 2n \\) different roots in the interval \\( [-\\pi, \\pi) \\), which is a contradiction.\n\\end{proof}\n\n\\begin{corollary}[Bernstein's trigonometric inequality]\\label{thm:bernsteins_trigonometric_inequality}\\mcite[53]{Николов2020Лекции}\n  For any nonnegative integer \\( n \\) and any \\( s \\in \\tau_n \\) we have\n  \\begin{equation}\\label{eq:thm:bernsteins_trigonometric_inequality}\n    \\abs{s'(\\theta)} \\leq n \\norm{s} \\quad\\forall \\theta \\in [-\\pi, \\pi].\n  \\end{equation}\n\\end{corollary}\n\\begin{proof}\n  The case \\( n = 0 \\) is trivial. If \\( n > 0 \\), for any \\( s \\in \\tau_n \\), we can apply \\eqref{eq:thm:szegos_trigonometric_inequality} to \\( \\frac s {\\norm s} \\) to obtain\n  \\begin{equation}\n    [s'(\\theta)]^2 + n^2 s^2 (\\theta) \\leq \\norm{s}^2 n^2 \\quad\\forall \\theta \\in [-\\pi, \\pi].\n  \\end{equation}\n\n  \\eqref{eq:thm:bernsteins_trigonometric_inequality} follows directly.\n\\end{proof}\n\n\\begin{theorem}[Bernstein's trigonometric theorem]\\label{thm:bernsteins_trigonometric_theorem}\\mcite[55]{Николов2020Лекции}\n  Let \\( f \\in \\tilde(C)[-\\pi, \\pi] \\) and\n  \\begin{equation*}\n    \\tilde{E}_n(f) \\leq \\frac A {n^{k+\\alpha}} \\quad n = 0, 1, 2, \\ldots,\n  \\end{equation*}\n  where \\( A \\in \\BbbR \\) and \\( \\alpha \\in (0, 1) \\).\n\n  Then \\( f \\in C^{(k)}[-\\pi, \\pi] \\) and \\( f^{(k)} \\) is \\( \\alpha \\)-H\\\"older.\n\\end{theorem}\n\\begin{proof}\n  Since \\( \\tilde{E}_n(f) \\) is bounded by \\( \\frac A {n^{k+\\alpha}} \\) on a compact interval, there exists a sequence \\( \\{ s_k \\}_{k=0}^\\infty \\) such that\n  \\begin{equation*}\n    \\norm{f - s_n} \\leq A {n^{k+\\alpha}}.\n  \\end{equation*}\n\n  Define the sequence of polynomials\n  \\begin{equation*}\n    v_j \\coloneqq \\begin{cases}\n      s_1,                  &j = 0, \\\\\n      s_{2^j} - s_{2^{j-1}} &j > 0.\n    \\end{cases}\n  \\end{equation*}\n\n  It is now clear that\n  \\begin{equation*}\n    \\norm{f - \\sum_{j=0}^n v_j} \\xrightarrow[]{j \\to \\infty} 0\n  \\end{equation*}\n  because\n  \\begin{equation*}\n    \\abs{f(\\theta) - \\sum_{j=0}^n v_j (\\theta)}\n    =\n    \\abs{f(\\theta) - s_{2^n}(\\theta)}\n    \\leq\n    A {n^{k+\\alpha}}.\n  \\end{equation*}\n\n  For each term of the series, we have\n  \\begin{equation*}\n    \\abs{v_j(\\theta)}\n    \\leq\n    \\abs{f(\\theta) - s_{2^j}(\\theta)} + \\abs{f(\\theta) - s_{2^{j-1}}(\\theta)}\n    \\leq\n    \\frac A {2^{j(k + \\alpha)}} + \\frac A {2^{(j - 1) (k + \\alpha)}}.\n  \\end{equation*}\n\n  By setting \\( B \\coloneqq A (2^{k + \\alpha}) \\), we obtain\n  \\begin{equation*}\n    \\abs{v_j(\\theta)} \\leq \\frac B {2^{j(k + \\alpha)}}.\n  \\end{equation*}\n\n  By \\fullref{thm:bernsteins_trigonometric_inequality},\n  \\begin{equation*}\n    \\norm{v_j^{(r)}} \\leq 2^{jr} \\norm{v_j} \\leq \\frac B {2^{j(k - r + \\alpha)}}.\n  \\end{equation*}\n\n  Then\n  \\begin{equation*}\n    \\sum_{j=0}^\\infty v_j^{(r)} (\\theta)\n  \\end{equation*}\n  converges uniformly, therefore\n  \\begin{equation*}\n    f^{(r)}(\\theta) = \\sum_{j=0}^\\infty v_j^{(r)} (\\theta).\n  \\end{equation*}\n\\end{proof}\n\n\\begin{theorem}[Bernstein's algebraic inequality]\\label{thm:bernsteins_algebraic_inequality}\\mcite[59]{Николов2020Лекции}\n  For any nonnegative integer \\( n \\) and any \\( p \\in \\pi_n \\) and \\( x \\in (a, b) \\) we have\n  \\begin{equation*}\n    \\abs{p'(x)} \\leq n \\frac 1 {(b - a)(b - x)} \\norm{p}.\n  \\end{equation*}\n\\end{theorem}\n\n\\begin{theorem}[Bernstein's algebraic theorem]\\label{thm:bernsteins_algebraic_theorem}\\mcite[60]{Николов2020Лекции}\n  Let \\( f \\in C[a, b] \\) and\n  \\begin{equation*}\n    E_n(f) \\leq \\frac A {n^{k+\\alpha}} \\quad n = 0, 1, 2, \\ldots,\n  \\end{equation*}\n  where \\( A \\in \\BbbR \\) and \\( \\alpha \\in (0, 1) \\).\n\n  Then \\( f \\in C^{(k)}(a, b) \\) and \\( f^{(k)} \\) is \\( \\alpha \\)-H\\\"older in every \\( [a_1, b_1] \\) such that \\( a_1 > a \\) and \\( b_1 < b \\).\n\\end{theorem}\n", "meta": {"hexsha": "38ce11d78fc0252bf0563d4083b3960520d58a80", "size": 8300, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/bernstein_inequalities.tex", "max_stars_repo_name": "v--/anthology", "max_stars_repo_head_hexsha": "89a91b5182f187bc1aa37a2054762dd0078a7b56", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/bernstein_inequalities.tex", "max_issues_repo_name": "v--/anthology", "max_issues_repo_head_hexsha": "89a91b5182f187bc1aa37a2054762dd0078a7b56", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bernstein_inequalities.tex", "max_forks_repo_name": "v--/anthology", "max_forks_repo_head_hexsha": "89a91b5182f187bc1aa37a2054762dd0078a7b56", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.2291666667, "max_line_length": 463, "alphanum_fraction": 0.613373494, "num_tokens": 3239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.34675852817569885}}
{"text": "\n\n    \\filetitle{datdiff}{Number of periods between two dates with check for date frequency}{dates/datdiff}\n\n\t\\paragraph{Syntax}\\label{syntax}\n\n\\begin{verbatim}\nD = datdiff(D1,D2)\n\\end{verbatim}\n\n\\paragraph{Input arguments}\\label{input-arguments}\n\n\\begin{itemize}\n\\itemsep1pt\\parskip0pt\\parsep0pt\n\\item\n  \\texttt{D1}, \\texttt{D2} {[} numeric {]} - IRIS dates of vectors of\n  IRIS dates.\n\\end{itemize}\n\n\\paragraph{Output arguments}\\label{output-arguments}\n\n\\begin{itemize}\n\\itemsep1pt\\parskip0pt\\parsep0pt\n\\item\n  \\texttt{D} {[} numeric {]} - Number of periods between \\texttt{D1} and\n  \\texttt{D2}, positive for \\texttt{D1} greater than \\texttt{D2},\n  negative for \\texttt{D1} smaller than \\texttt{D2}, or NaN for dates of\n  different frequencies.\n\\end{itemize}\n\n\\paragraph{Description}\\label{description}\n\n\\paragraph{Example}\\label{example}\n\n\\begin{verbatim}\nd1 = mm(2010,12);\nd2 = mm(2011,12);\n\ndatdiff(d1,d2)\nans =\n   -12\n\ndatdiff(d2,d1)\nans =\n    12\n\nd3 = yy(2011);\ndatdiff(d1,d3)\nans =\n   NaN\n\\end{verbatim}\n\n\n", "meta": {"hexsha": "79f56736a7d6ef1c588141e53bfe7d7d44450afb", "size": 1015, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "-help/dates/datdiff.tex", "max_stars_repo_name": "OGResearch/IRIS-Toolbox-For-Octave", "max_stars_repo_head_hexsha": "682ea1960229dc701e446137623b120688953cef", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-12-06T13:38:38.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-06T13:38:38.000Z", "max_issues_repo_path": "-help/dates/datdiff.tex", "max_issues_repo_name": "OGResearch/IRIS-Toolbox-For-Octave", "max_issues_repo_head_hexsha": "682ea1960229dc701e446137623b120688953cef", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-03-28T08:13:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-02T10:40:25.000Z", "max_forks_repo_path": "-help/dates/datdiff.tex", "max_forks_repo_name": "OGResearch/IRIS-Toolbox-For-Octave", "max_forks_repo_head_hexsha": "682ea1960229dc701e446137623b120688953cef", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-17T07:06:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T07:06:39.000Z", "avg_line_length": 18.7962962963, "max_line_length": 105, "alphanum_fraction": 0.7133004926, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073507867328, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.34675852434971205}}
{"text": "\\documentclass[11pt]{article}\n\\usepackage{euler}\n\\usepackage{xltxtra}\n\\usepackage{amsmath}\n%\\usepackage{amssymb}\n\\usepackage[pdfborder={0 0 0}]{hyperref}\n\\usepackage{listings}\n%\\setmainfont[Mapping=tex-text]{Ubuntu}\n%{FreeSerif}\n%{DejaVu Serif}\n\n\\date{26th of June 2012}\n\\author{Lukas Prokop}\n\\title{Software paradigms exam 27.6.2011}\n\n% Definitions by Daniel Gruß\n% https://github.com/lava2/swp/blob/master/commands.tex\n% various operators\n\\DeclareMathOperator {\\id}{id}\n\\DeclareMathOperator*{\\ggt}{ggT}\n\\DeclareMathOperator*{\\kgv}{kgV}\n\\DeclareMathOperator {\\ord}{ord}\n\\DeclareMathOperator {\\fmod}{mod}\n\\DeclareMathOperator*{\\trace}{tr}\n\\DeclareMathOperator {\\nil}{nil}\n\\DeclareMathOperator*{\\supp}{Supp}\n\\DeclareMathOperator {\\lm}{lm}\n\\DeclareMathOperator {\\lt}{lt}\n\\DeclareMathOperator {\\lc}{lc}\n\\DeclareMathOperator*{\\rest}{rest}\n\\DeclareMathOperator*{\\tmult}{\\:{mult}\\:}\n\\DeclareMathOperator*{\\tplus}{\\:{plus}\\:}\n\\DeclareMathOperator*{\\tminus}{\\:{minus}\\:}\n\\DeclareMathOperator*{\\tnull}{\\:{null}\\:}\n\\DeclareMathOperator*{\\teins}{\\:{eins}\\:}\n\\DeclareMathOperator*{\\tif}{\\:{if}\\:}\n\\DeclareMathOperator*{\\telse}{\\:{else}\\:}\n\\DeclareMathOperator*{\\tthen}{\\:{then}\\:}\n\\DeclareMathOperator*{\\tlt}{\\:{lt?}\\:}\n\\DeclareMathOperator*{\\teq}{\\:{eq?}\\:}\n\\DeclareMathOperator*{\\tumult}{\\:\\u{mult}\\:}\n\\DeclareMathOperator*{\\tuplus}{\\:\\u{plus}\\:}\n\\DeclareMathOperator*{\\tuminus}{\\:\\u{minus}\\:}\n\\DeclareMathOperator*{\\tunull}{\\:\\u{null}\\:}\n\\DeclareMathOperator*{\\tueins}{\\:\\u{eins}\\:}\n\\DeclareMathOperator*{\\tuif}{\\:\\u{if}\\:}\n\\DeclareMathOperator*{\\tuelse}{\\:\\u{else}\\:}\n\\DeclareMathOperator*{\\tuthen}{\\:\\u{then}\\:}\n\\DeclareMathOperator*{\\tult}{\\:\\u{lt?}\\:}\n\\DeclareMathOperator*{\\tueq}{\\:\\u{eq?}\\:}\n\\DeclareMathOperator {\\End}{end}\n\\DeclareMathOperator*{\\rang}{rang}\n\\DeclareMathOperator*{\\dist}{d}\n\\DeclareMathOperator*{\\real}{Re}\n\\DeclareMathOperator*{\\imag}{Im}\n\\DeclareMathOperator*{\\sign}{sign}\n\\DeclareMathOperator*{\\weight}{weight}\n\n% graphics and sectioning\n\\newcommand{\\skizze}[1]{$ $ \\begin{center}\\includegraphics[scale = 0.33]{images/#1.png}\\end{center}}\n\\newcommand{\\mychapter}[1]{\\chapter{#1}}\n\\newcommand{\\mysection}[1]{\\section{#1}}\n\\newcommand{\\mysubsection}[1]{\\subsection{#1}}\n\\newcommand{\\separate}{\\begin{center}*\\:*\\:*\\end{center}}\n\n% definition and proof tools\n\\newcommand{\\proofdone}{\\hfill \\ensuremath{\\Box}}\n\\newcommand{\\mathdone}{\\tag*{\\ensuremath{\\Box}}}\n\n\\newcommand{\\defas}{\\mathrel{\\mathop:}=}\n\\newcommand{\\asdef}{=\\mathrel{\\mathop:}}\n\n\\newcommand{\\there}{``$\\Rightarrow$'' \\;}\n\\newcommand{\\back}{``$\\Leftarrow$'' \\;}\n\n\\newcommand{\\then}{\\: \\Rightarrow \\:}\n\\newcommand{\\ifonlyif}{\\: \\Leftrightarrow \\:}\n\\renewcommand{\\u}[1]{\\underline{#1}}\n\\newcommand{\\tu}[1]{\\text{\\underline{#1}}}\n\n\\newcommand{\\tobe}{\\overset{!}{=}}\n\\newcommand{\\isit}{\\overset{?}{=}}\n\n% referencing\n\\newcommand{\\tagstar}{\\tag*{$\\star$}}\n\\newcommand{\\refstar}{\\ensuremath{(\\star)}}\n\\newcommand{\\alrefstar}{\\tag*{(\\star)}}\n\\newcommand{\\tagstarn}[1]{\\tag*{$\\star_{#1}$}}\n\\newcommand{\\refstarn}[1]{\\ensuremath{(\\star_{#1})}}\n\\newcommand{\\alrefstarn}[1]{\\tag*{(\\star_{#1})}}\n\n% mathtext\n\\newcommand{\\sonst}{\\text{sonst}}\n\\newcommand{\\const}{\\mathrm{const}}\n\n% braces\n\\newcommand{\\abs}[1]{\\left\\lvert{#1}\\right\\rvert}\n\\newcommand{\\norm}[1]{\\left\\lVert{#1}\\right\\rVert}\n\\newcommand{\\angled}[1]{\\left\\langle{#1}\\right\\rangle}\n\\newcommand{\\tangled}[1]{\\langle{#1}\\rangle}\n\\newcommand{\\braced}[1]{\\left( {#1} \\right)}\n\\newcommand{\\sbraced}[1]{\\left\\{#1\\right\\}}\n\\newcommand{\\bbraced}[1]{\\left[#1\\right]}\n\n\\newcommand{\\bbinom}[2]{\\genfrac[]{0pt}{0}{#1}{#2}}\n\\newcommand{\\cbinom}[2]{\\genfrac{\\{}{\\}}{0pt}{0}{#1}{#2}}\n\\newcommand{\\ebinom}[2]{\\genfrac{}{}{0pt}{0}{#1}{#2}}\n\n\\newcommand{\\gausslo}[1]{\\left\\lfloor {#1} \\right\\rfloor}\n\\newcommand{\\gausshi}[1]{\\left\\lceil {#1} \\right\\rceil}\n\\newcommand{\\gaussround}[1]{\\left\\lfloor {#1} \\right\\rceil}\n\n% under/overlining\n\\newcommand{\\ov}[1]{\\overline{#1}}\n\\newcommand{\\un}[1]{\\underline{#1}}\n\\newcommand{\\vek}[1]{\\vec{#1}}\n\n% relations\n\\newcommand{\\sm}{\\setminus}\n\\newcommand{\\se}{\\subseteq}\n\\newcommand{\\nse}{\\nsubseteq}\n\\newcommand{\\sne}{\\nsubseteq}\n\\newcommand{\\ise}{\\supseteq}\n\\newcommand{\\nise}{\\nsupseteq}\n\\newcommand{\\sneq}{\\subsetneqq}\n\\newcommand{\\isneq}{\\supsetneqq}\n\n\\newcommand{\\subideal}{\\trianglelefteq}\n\\newcommand{\\isubideal}{\\trianglerighteq}\n\n\\newcommand{\\divs}{\\mathrel\\vert}\n\\newcommand{\\ndivs}{\\nmid}\n\\newcommand{\\iso}{\\simeq}\n\n\\newcommand{\\nequiv}{\\not\\equiv}\n\n% sets\n\\newcommand{\\N}{\\mathbb{N}}\n\\newcommand{\\Z}{\\mathbb{Z}}\n\\newcommand{\\Q}{\\mathbb{Q}}\n\\newcommand{\\R}{\\mathbb{R}}\n\\newcommand{\\C}{\\mathbb{C}}\n\\newcommand{\\F}{\\mathbb{F}}\n\\newcommand{\\K}{\\mathbb{K}}\n\\newcommand{\\primes}{\\mathbb{P}}\n\\newcommand{\\potenz}{\\mathcal{P}}\n\n\\newcommand{\\dotcup}{\\ensuremath{\\mathaccent\\cdot\\cup}}\n\n\\newcommand{\\prob}{\\mathbb{P}}\n\\newcommand{\\erw}{\\mathbb{E}}\n\\newcommand{\\variance}{\\mathbb{V}}\n\n% greek symbols\n\\newcommand{\\fee}{\\varphi}\n\\newcommand{\\eps}{\\varepsilon}\n\n% various tools\n\\newcommand{\\where}{\\mathrel\\big\\vert}\n\\newcommand{\\limited}{\\big\\vert}\n\n% complexity theory\n\\newcommand{\\ordn}{\\mathcal{O}}\n\\newcommand{\\oh}{\\mathcal{O}}\n\n% analysis\n\\newcommand{\\de}{\\, \\dd}\n\\newcommand{\\dd}{\\mathrm{d}}\n\n\\renewcommand{\\thesubsection}{\\arabic{subsection}}\n\\newcommand{\\rbr}[1]{\\left(#1\\right)}\n\\newcommand{\\ebr}[1]{\\left[#1\\right]}\n\\newcommand{\\sbr}[1]{\\left<#1\\right>}\n\\newcommand{\\gbr}[1]{\\left\\{#1\\right\\}}\n\\renewcommand{\\det}[1]{\\text{det}\\left(#1\\right)}\n\\renewcommand{\\u}[1]{\\underline{#1}}\n\\renewcommand{\\o}[1]{\\overline{#1}}\n\\renewcommand{\\b}[1]{\\textbf{#1}}\n\n\\newcommand{\\E}{\\mathbb{E}}\n\\renewcommand{\\P}{\\mathbb{P}}\n%\\newcommand{\\I}{\\mathbb{I}}\n\\newcommand{\\V}{\\mathbb{V}}\n\\newcommand{\\dx}{\\text{d}x}\n\\newcommand{\\D}{\\mathbb{D}}\n\\newcommand{\\kA}{\\mathcal{A}}\n\\newcommand{\\kC}{\\mathcal{C}}\n\\newcommand{\\kP}{\\mathcal{P}}\n\n\\newcommand{\\Lra}{\\:\\Leftrightarrow\\:}\n\\newcommand{\\lra}{\\:\\leftrightarrow\\:}\n\\newcommand{\\Ra}{\\:\\Rightarrow\\:}\n\\newcommand{\\ra}{\\:\\rightarrow\\:}\n\\newcommand{\\La}{\\:\\Leftarrow\\:}\n\\newcommand{\\la}{\\:\\leftarrow\\:}\n\n\\newcommand{\\limi}[1]{\\lim_{#1 \\rightarrow \\infty}}\n\\newcommand{\\mceil}[1]{\\left\\lceil #1 \\right\\rceil}\n\\newcommand{\\mfloor}[1]{\\left\\lfloor #1 \\right\\rfloor}\n\n\\DeclareMathOperator{\\ggT}{ggT}\n\\DeclareMathOperator{\\kgV}{kgV}\n\n\\DeclareMathOperator{\\RR}{R}\n\\DeclareMathOperator{\\notdivides}{\\nmid}\n\n\\newcommand{\\lng}[1]{\\mathcal{#1}}\n\\newcommand{\\kwu}[1]{\\text{\\:\\u{#1}\\:}}\n\\newcommand{\\kw}[1]{\\text{\\:{#1}\\:}}\n\\newcommand{\\I}[3]{I_{\\lng{#1}}\\left(#2,\\tu{#3}\\right)}\n\\newcommand{\\Iu}[3]{I_{\\lng{#1}}\\left(#2,#3\\right)}\n\n\\newcommand{\\twedge}{\\text{$\\wedge$}}\n\\newcommand{\\tforall}{\\text{$\\forall$}}\n\\newcommand{\\texists}{\\text{$\\exists$}}\n\\newcommand{\\tvee}{\\text{$\\vee$}}\n\\newcommand{\\tto}{\\text{$\\to$}}\n\\newcommand{\\tneg}{\\text{$\\neg$}}\n% End Definitions\n\n\\DeclareMathOperator*{\\s}{s}\n\\DeclareMathOperator*{\\binStack}{binStack}\n\\DeclareMathOperator*{\\add}{add}\n\\DeclareMathOperator*{\\len}{len}\n\\newcommand{\\Null}{\\text{null}}\n\\newcommand{\\set}[1]{\\left\\{#1\\right\\}}\n\n\\lstdefinelanguage{EXP}%\n  {keywords={if,then,else},%\n%   emph={plus,minus,mult,add0,add1,sub,build,rest,first,second,reverse,depth,max,nth,lt?,eq?,is0?,is1?,isEmpty?,atom?},\n   moreemph={null,eins,0,1,[]},% epsilon is missing\n   emphstyle=\\emph,\n   mathescape={true}%\n  }%\n\\newcommand{\\NE}{\\text{NE:}\\hspace{5pt}}\n\\newcommand{\\NR}{\\text{NR:}\\hspace{5pt}}\n\n\\begin{document}\n\\maketitle\n\\tableofcontents\n\\newpage\n%\n\\section{Exercise 1}\n%\n%\\begin{table}\n  \\begin{tabular}{lcccc}\n           &    S     &    A    &   B   &   C \\\\ \\hline\n    \\textsc{FIRST}  & $\\set{\\u{a}}$ & $\\set{\\u{a}}$ & $\\set{\\u{b}, \\u{c}, \\u{a}}$ & $\\set{\\u{c}, \\varepsilon}$ \\\\\n    \\textsc{FOLLOW} & $\\set{\\$}$ & $\\set{\\$, \\u{b}, \\u{c}, \\u{a}}$ & $\\set{\\$, \\u{b}, \\u{c}, \\u{a}}$ & $\\set{\\u{a}}$ \\\\\n  \\end{tabular}\n%\\end{table}\n%\n\\section{Exercise 2a}\n%\n%\\begin{table}\n  \\begin{tabular}{lcccc}\n      &    $\\u{a}$     &    $\\u{b}$    &   $\\u{c}$   &   \\$ \\\\\n  \\hline\n    S & $S \\to A$      & $S \\to A$     & $S \\to A$   & \\\\\n    A & $A \\to AB, A \\to \\u{a}$ &      &             & \\\\\n    B & $B \\to CA$     & $B \\to \\u{b}$ & $B \\to CA$  & \\\\\n    C & $C \\to \\varepsilon$ &          & $C \\to \\u{c}D, C \\to \\u{c}$ & \\\\\n    D &                & $D \\to \\u{b}$ & $D \\to \\u{c}$ & \\\\\n  \\end{tabular}\n%\\end{table}\n\n$(A, \\u{a})$ contains a left recursion.\n$(C, \\u{c})$ contains an ambiguity.\n%\n\\section{Exercise 2b}\n%\n\\begin{align*}\n  S &\\to IR \\\\\n  R &\\to CIR \\\\\n  R &\\to \\varepsilon \\\\[7pt]\n  I &\\to \\u{a}J \\\\\n  J &\\to \\u{b}J \\\\\n  J &\\to \\varepsilon \\\\[7pt]\n  C &\\to \\u{c}D \\\\\n  C &\\to \\varepsilon \\\\\n  D &\\to \\u{c} \\\\\n  D &\\to \\u{b} \\\\\n  D &\\to \\varepsilon\n\\end{align*}\n%\n%\\begin{table}\n \\begin{center}\n  \\begin{tabular}{lcccc}\n      & $\\u{a}$ & $\\u{b}$ & $\\u{c}$ & \\$ \\\\\n  \\hline\n    S & $S \\to IR$ &      &         &  \\\\\n    R & $R \\to CIR$ &     & $R \\to CIR$ & $R \\to \\epsilon$ \\\\\n    I & $I \\to \\u{a}J$ &  &         &  \\\\\n    J & $J \\to \\varepsilon$ & $J \\to \\u{b}J$ & $J \\to \\varepsilon$ & $J \\to \\varepsilon$ \\\\\n    C & $C \\to \\varepsilon$ & & $C \\to \\u{c}D$ & \\\\\n    D & $D \\to \\varepsilon$ & $D \\to \\u{b}$ & $D \\to \\u{c}$ & \\\\\n  \\end{tabular}\n \\end{center}\n%\\end{table}\n%\n\\section{Exercise 2c}\n%\n\\begin{center}\n \\begin{tabular}{lll}\n  \\textsc{Input}           & \\textsc{Stack}        & \\textsc{Comment} \\\\\n  $\\u{\\$abcbba}$           & $S$                   & $S \\to IR$ \\\\\n  $\\u{\\$abcbba}$           & $RI$                  & $I \\to \\u{a}J$ \\\\\n  $\\u{\\$abcbba}$           & $RJ\\u{a}$             & $J \\to \\u{b}J$ \\\\\n  $\\u{\\$abcbb}$            & $RJ\\u{b}$             & $J \\to \\u{b}J$ \\\\\n  $\\u{\\$abcb}$             & $RJ\\u{b}$             & $J \\to \\varepsilon$ \\\\\n  $\\u{\\$abc}$              & $R$                   & $R \\to CIR$ \\\\\n  $\\u{\\$abc}$              & $RIC$                 & $C \\to \\u{c}D$ \\\\\n  $\\u{\\$abc}$              & $RID\\u{c}$            & $D \\to \\u{b}$ \\\\\n  $\\u{\\$ab}$               & $RI\\u{b}$             & $I \\to \\u{a}J$ \\\\\n  $\\u{\\$a}$                & $RJ\\u{a}$             & $J \\to \\varepsilon$ \\\\\n  $\\u{\\$}$                 & $R$                   & $R \\to \\varepsilon$ \\\\\n  $\\u{\\$}$                 &                       & accepted \\\\\n \\end{tabular}\n\\end{center}\n%\n\\section{Exercise 3}\n%\n\\lstset{language=EXP}\n\\begin{lstlisting}\nfactorial(x) =\n  if eq?(x, 0) then eins\n  else if eq?(x, eins) then eins\n  else mult(factorial(minus(x, eins)), x)\n\\end{lstlisting}\n\nProof by complete induction.\n\n\\subsection{Induction hypothesis}\n\\[\n  \\forall \\omega, \\omega(\\u{x}) \\leq n, \\omega(\\u{x}) \\in ℕ:\n    I(\\delta, \\omega, \\u{factorial(x)}) = \\omega(\\u{x})!\n\\]\n\n\\subsection{Induction base 0}\n\\[\n  \\omega(\\u{x}) = 0\n\\] \\[\n  I(\\delta, \\omega, \\u{\\text{if eq?(x, 0) then eins else if eq?}}\\ldots)\n\\] \\[\n  \\NR I(\\delta, \\omega, \\u{\\text{eq?(x, 0)}})\n    = \\operatorname{eq?}(I(\\delta, \\omega, \\u{x}), I(\\delta, \\omega, \\u{0}))\n    = \\operatorname{eq?}(\\omega(\\u{x}), 0)\n    = T\n\\] \\[\n  I(\\delta, \\omega, \\u{\\text{eins}}) = 1 = 0!\n\\]\n\n\\subsection{Induction base 1}\n%\n\\[\n  \\omega(\\u{x}) = 1\n\\] \\[\n  I(\\delta, \\omega, \\u{\\text{if eq?(x, 0) then eins else if eq?}}\\ldots)\n\\] \\[\n  \\NR I(\\delta, \\omega, \\u{\\text{eq?(x, 0)}})\n    = \\operatorname{eq?}(I(\\delta, \\omega, \\u{x}), I(\\delta, \\omega, \\u{0}))\n    = \\operatorname{eq?}(\\omega(\\u{x}), 0)\n    = F\n\\] \\[\n  I(\\delta, \\omega, \\u{\\text{if eq?(x, 1) then eins else mult}}\\ldots)\n\\] \\[\n  \\NR I(\\delta, \\omega, \\u{\\text{eq?(x, eins)}})\n    = \\operatorname{eq?}(I(\\delta, \\omega, \\u{x}), I(\\delta, \\omega, \\u{\\text{eins}}))\n    = \\operatorname{eq?}(\\omega(\\u{x}), 1)\n    = T\n\\] \\[\n  I(\\delta, \\omega, \\u{\\text{eins}}\\ldots) = 1 = 1!\n\\]\n\n\\subsection{Induction step}\n%\n\\[\n  \\omega(\\u{x}) = n + 1 \\qquad n \\geq 2\n\\] \\[\n  I(\\delta, \\omega, \\u{\\text{if eq?(x, 0) then eins else if eq?}}\\ldots)\n\\] \\[\n  \\NR I(\\delta, \\omega, \\u{\\text{eq?(x, 0)}})\n    = \\operatorname{eq?}(I(\\delta, \\omega, \\u{x}), I(\\delta, \\omega, \\u{0}))\n    = \\operatorname{eq?}(\\omega(\\u{x}), 0)\n    = F\n\\] \\[\n  I(\\delta, \\omega, \\u{\\text{if eq?(x, 1) then eins else mult}}\\ldots)\n\\] \\[\n  \\NR I(\\delta, \\omega, \\u{\\text{eq?(x, eins)}})\n    = \\operatorname{eq?}(I(\\delta, \\omega, \\u{x}), I(\\delta, \\omega, \\u{\\text{eins}}))\n    = \\operatorname{eq?}(\\omega(\\u{x}), 1)\n    = F\n\\] \\[\n  I(\\delta, \\omega, \\u{\\text{mult(factorial(minus(x, eins)), x)}})\n    = \\operatorname{mult}(I(\\delta, \\omega, \\u{\\text{factorial(minus(x, eins))}}), I(\\delta, \\omega, \\u{x}))\n\\] \\[\n  \\NE \\omega'(\\u{x})\n    = I(\\delta, \\omega, \\u{\\text{minus(x, eins)}})\n    = \\operatorname{minus}(I(\\delta, \\omega, \\u{x}), I(\\delta, \\omega, \\u{\\text{eins}}))\n\\] \\[\n    = \\operatorname{minus}(\\omega(\\u{x}), 1)\n    = \\operatorname{minus}(n + 1, 1) = n\n\\] \\[\n  \\operatorname{mult}(n!, n+1) = (n+1)! \\qquad \\text{ corresponds to hypothesis}\n\\]\n\n%\n\\section{Exercise 4a}\n%\n\\lstset{language=prolog}\n\\begin{lstlisting}\nodd(binStack(V, R)) :- odd(R).\nodd(binStack(s(0), null)).\n\\end{lstlisting}\n%\n\\section{Exercise 4b}\n%\nTables~\\ref{tab:4b-def} and~\\ref{tab:4b-deriv}.\n\\begin{table}[h]\n  \\begin{tabular}{cl}\n    Q   & $\\neg \\len(\\binStack(0, \\binStack(0, \\binStack(0, \\Null))), \\s(\\s(\\s(0))))$ \\\\\n    C1  & $\\add(X, 0, X)$ \\\\\n    C2  & $\\add(X, \\s(Y), \\s(Z)) \\lor \\neg \\add(X, Y, Z)$ \\\\\n    C3  & $\\len(\\Null, 0)$ \\\\\n    C4  & $\\len(\\binStack(V, R), E) \\lor \\neg \\len(R, S) \\lor \\neg \\add(\\s(0), S, E)$\n  \\end{tabular}\n  \\caption{Rules of exercise 4b in logical notation}\n  \\label{tab:4b-def}\n\\end{table}\n%\n\\begin{table}[h]\n  \\begin{tabular}{cl}\n    Q   & $\\neg \\len(\\binStack(0, \\binStack(0, \\binStack(0, \\Null))), \\s(\\s(\\s(0))))$ \\\\\n    C4  & $\\len(\\binStack(V, R), E) \\lor \\neg \\len(R, S) \\lor \\neg \\add(\\s(0), S, E)$ \\\\\n    $\\Theta$ & $\\{ V = 0, R = \\binStack(0, \\binStack(0, null)), E = \\s(\\s(\\s(0))) \\}$ \\\\\n    R   & $\\neg \\len(\\binStack(0, \\binStack(0, \\Null)), S_1) \\lor \\neg \\add(\\s(0), S_1, \\s(\\s(\\s(0))))$ \\\\[10pt]%\n\n    C4  & $\\len(\\binStack(V, R), E) \\lor \\neg \\len(R, S) \\lor \\neg \\add(\\s(0), S, E)$ \\\\\n    $\\Theta$ & $\\{ V_2 = 0, R_2 = \\binStack(0, \\Null), E_2 = S_1 \\}$ \\\\\n    R   & $\\neg \\len(\\binStack(0, \\Null), S_2) \\lor \\neg \\add(\\s(0), S_2, S_1)\n           \\lor \\neg \\add(\\s(0), S_1, \\s(\\s(\\s(0))))$ \\\\[10pt]%\n\n    C3  & $\\len(\\Null, 0)$ \\\\\n    $\\Theta$ & $\\{ S_3 = 0 \\}$ \\\\\n    R   & $\\neg \\add(\\s(0), 0, S_2) \\lor \\neg \\add(\\s(0), S_2, S_1) \\lor \\neg \\add(\\s(0), S_1, \\s(\\s(\\s(0))))$ \\\\[10pt]%\n\n    C1  & $\\add(X, 0, X)$ \\\\\n    $\\Theta$ & $\\{ S_2 = \\s(0), X = S_2 \\}$ \\\\\n    R   & $\\neg \\add(\\s(0), \\s(0), S_1) \\lor \\neg \\add(\\s(0), S_1, \\s(\\s(\\s(0))))$ \\\\[10pt]%\n\n    C2  & $\\add(X, \\s(Y), \\s(Z)) \\lor \\neg \\add(X, Y, Z)$ \\\\\n    $\\Theta$ & $\\{ X_2 = \\s(0), Y_2 = 0, Z_2 = A, S_1 = \\s(A) \\}$ \\\\\n    R   & $\\neg \\add(\\s(0), 0, A) \\lor \\neg \\add(\\s(0), \\s(A), \\s(\\s(\\s(0))))$ \\\\[10pt]%\n\n    C1  & $\\add(X, 0, X)$ \\\\\n    $\\Theta$ & $\\{ X_3 = \\s(0), A = X_3 \\}$ \\\\\n    R   & $\\neg \\add(\\s(0), \\s(\\s(0)), \\s(\\s(\\s(0)))$ \\\\[10pt]%\n\n    C2  & $\\add(X, \\s(Y), \\s(Z)) \\lor \\neg \\add(X, Y, Z)$ \\\\\n    $\\Theta$ & $\\{ X_4 = \\s(0), Y_3 = \\s(0), Z_3 = \\s(\\s(0)) \\}$ \\\\\n    R   & $\\neg \\add(\\s(0), \\s(0), \\s(\\s(0)))$ \\\\[10pt]%\n\n    C2  & $\\add(X, \\s(Y), \\s(Z)) \\lor \\neg \\add(X, Y, Z)$ \\\\\n    $\\Theta$ & $\\{ X_5 = \\s(0), Y_4 = 0, Z_4 = \\s(0) \\}$ \\\\\n    R   & $\\neg \\add(\\s(0), 0, \\s(0))$ \\\\[10pt]%\n\n    C1  & $\\add(X, 0, X)$ \\\\\n    $\\Theta$ & $\\{ X_6 = \\s(0) \\}$ \\\\\n    R   & empty, query got successfully derivated. \\\\\n  \\end{tabular}\n  \\caption{Derivation of the query in exercise 4b}\n  \\label{tab:4b-deriv}\n\\end{table}\n%\n\\section{Exercise 5}\n%\n\\[\n  \\pi[\\text{add}](\\pi(a), \\pi(b)) = \\operatorname{add}(a, b)\n\\]\n%\n\\lstset{language=EXP}\n\\begin{lstlisting}\nadd(a, b) =\n  if eq?(mod(a, 2), 1) then\n    if eq?(mod(b, 2), 1) then\n      sub(add(a, b), 1)\n    else\n      if gt?(a, b) then\n        sub(a, b)\n      else\n        add(sub(b, a), 1)\n  else\n    if eq?(mod(b, 2), 1) then\n      if gt?(a, b) then\n        add(sub(a, b), 1)\n      else\n        sub(b, a)\n    else\n      add(a, b)\n\\end{lstlisting}\n\n\\begin{enumerate}\n  \\item Sign of first parameter is positive, second parameter the same\n  \\item Sign of first parameter is positive, second parameter is negative\n  \\item Sign of first parameter is negative, second parameter is positive\n  \\item Sign of first parameter is negative, second parameter the same\n\\end{enumerate}\n\n\\textbf{Case both parameters are positive:} \\\\\nIf both parameters are positive, the modulo value of both values by 2 is 1.\nTherefore the very last line of the function is evaluated. For decoded\nvalues the result is $a+b$, which equals to $\\pi(a) + \\pi(b)$ for encoded\nvalues as far as the sum of two even numbers is even (which represents\na positive number).\n\n\\end{document}\n", "meta": {"hexsha": "0fdafae0b8bc04d4e56cb11720a567c1e4007f14", "size": 16495, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "pub/swp_prev_exam.tex", "max_stars_repo_name": "meisterluk/tug_lp", "max_stars_repo_head_hexsha": "eaf7e0a9bfaa91400248f7231c6891531ee71275", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pub/swp_prev_exam.tex", "max_issues_repo_name": "meisterluk/tug_lp", "max_issues_repo_head_hexsha": "eaf7e0a9bfaa91400248f7231c6891531ee71275", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pub/swp_prev_exam.tex", "max_forks_repo_name": "meisterluk/tug_lp", "max_forks_repo_head_hexsha": "eaf7e0a9bfaa91400248f7231c6891531ee71275", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9052224371, "max_line_length": 120, "alphanum_fraction": 0.5624734768, "num_tokens": 6675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3467084396262222}}
{"text": "% from latexml\n\\documentclass{article}\n\\usepackage{xcolor}\n\\usepackage{cancel}\n\\usepackage{siunitx}\n\\usepackage{float}\n\\usepackage{multirow}\n\\usepackage{booktabs}\n\n\\DeclareSIQualifier\\polymer{pol}\n\\DeclareSIQualifier\\catalyst{cat}\n\\DeclareSIQualifier\\isotropic{i} %?\n\n\\DeclareSIUnit\\abbra{ a }\n\\DeclareSIUnit\\abbrb{ \\abbra }  % abbreviation\n\\DeclareSIUnit\\abbrc{ \\abbrb }  % abbreviation twice\n\\DeclareSIUnit\\abbrd{ \\abbre }  % before defined\n\\DeclareSIUnit\\abbre{ e }\n\n\\def\\mabbra{a}\n\\DeclareSIUnit\\mabbrb{\\mabbra}\n\n\\DeclareSIPrefix\\killer{\\kilo}{3}\n\n\\usepackage{amsmath}\n\\begin{document}\n{\n\\color{red}\nSome text \\\\\n\\SI{4}{\\metre\\per\\sievert} \\\\\nMore text \\\\\n\\SI[color = blue]{4}{\\metre\\per\\sievert} \\\\\nStill red here!\n\\numlist[color = blue]{1;2;3;4}\\\\\nStill red here!\\\\\n}\n\n\\si{m^2.s}\\\\\n\\si{\\mu m^2}\\\\\n\n\\SI{0.094}{\\pi . \\milli\\meter . \\milli\\radian}\\\\\n\n\\SI{0.094}{\\frac{1}{3} . \\milli\\meter . \\milli\\radian}\\\\\n\n\\SI{0.094}{\\pi \\per \\milli\\meter . \\milli\\radian\\tothe{3}}\\\\\n\\section{Numbers}\n\\subsection{General}\n%\\num{\\sqrt{2}}\\\\\n%\\num{{a word}}\\\\\n\\num{12345,67890}\\\\\n\\num{1+-2i}\\\\\n\\num{.3e45}\\\\\n\\num{1.654 x 2.34 x 3.430}\\\\\n\\num{\\pi}\\\\\n\\num{2\\pi}\\\\\n\\num{\\pi/3}\\\\\n\n\\num{123}\\\\\n\\num{1234}\\\\\n\\num{12345}\\\\\n\\num{0.123}\\\\\n\\num{0,1234}\\\\\n\\num{.12345}\\\\\n\\num{3.45d-4}\\\\\n\\num{-e10}\\\\\n\n\\num{123e4}\\\\\n%\\num{123e4(3)}\\\\\n\\num{123(3)e4}\\\\\n\n\\num{123\\pm2}\\\\\n\\num{123\\pm2i}\\\\\n\\num{123+234i}\\\\\n%\\num{123+234}\\\\\n%\\num{123e2+234e3i}\\\\\n\\num{123+234ie3}\\\\\n\\num{123(1)+234(1)ie3}\\\\\n%\\num{123e2(1)+234e3i(1)}\\\\\n%\\num{+234(1)ie3}\\\\              %comes out weird?\n\\num{+3i}\\\\\n\\num{+3ie4}\\\\\n\nPretty nonsensical stuff?\n\\num{1.\\pi e+3}\\\\\n\\def\\dig{1234}\\\\\n\\num{\\dig.\\dig}\\\\\n\\def\\odd{\\xi}\\\\\n\\def\\odder{\\odd}\\\\\n\\num[input-symbols=\\xi]{3\\xi}\\\\\n\\num[input-symbols=\\xi]{3\\odd}\\\\\n%\\num[input-symbols=\\odd]{3\\odd}\\\\\n\\num[input-symbols=\\odd, input-protect-tokens=\\odd]{3\\odd}\\\\\n\\num[input-symbols=\\odd, input-protect-tokens=\\odd]{3\\odder}\\\\\n\\num[input-symbols=\\odder, input-protect-tokens=\\odder]{3\\odder}\\\\\n%\\num[input-symbols=\\odder, input-protect-tokens=\\odd]{3\\odder}\\\\\n%\\num[input-symbols=\\odd, input-protect-tokens=\\odder]{3\\odder}\\\\\n\n\\num{1.23(1)}\\\\\n%\\num{1.23(0.01)}\n\\num{1.23\\pm0.01}\\\\\n%\\num{1.23(1.0)}\\\\\n%\\num{1.23(\\pm1)}\\\\\n\\num{1.23(\\pi)}\\\\\n\n\\subsection{Parsing numbers}\n\n\\subsubsection{input-digits, input-decimal-markers, input-signs, input-exponent-markers}\n\n\\subsubsection{input-symbols, input-ignore}\n\\subsubsection{input-comparators}\n\n\\num{< 10} \\\\\n%\\SI{>> 5}{\\metre} \\\\\n\\num{\\le 0.12}\\\\\n\n\\subsubsection{input-open-uncertainty, input-close-uncertainty, input-uncertainty-signs}\n\\num{9.99(9)}\\\\\n\\num{9.99 +- 0.09}\\\\\n\\num{9.99 \\pm 0.09}\\\\\n\\num{123 +- 4.5}\\\\\n\\num{12.3 +- 6}\\\\\n\n\\subsubsection{input-complex-roots}\n\\num{9.99 + 88.8i} \\\\\n\\num{9.99 + i88.8}\\\\\n\n\\subsubsection{input-protect-tokens}\n\n\\subsubsection{parse-numbers}\n\\num[parse-numbers = false]{\\sqrt{2}}\\\\\n\n\\subsection{Post-processing numbers}\n\\subsubsection{round-mode, round-precision}\n{\n\\num{1.23456} \\\\\n\\num{14.23} \\\\\n\\num{0.12345(9)} \\\\\n\\sisetup{\n  round-mode = places,\n  round-precision = 3\n}%\n\\num{1.23456} \\\\\n\\num{14.23} \\\\\n\\num{0.12345(9)} \\\\\n\\sisetup{\n  round-mode = figures,\n  round-precision = 3\n}%\n\\num{1.23456} \\\\\n\\num{14.23} \\\\\n\\num{0.12345(9)}\\\\\n}\n\\subsubsection{round-integer-to-decimal}\n{\n\\num[round-mode = figures]{1} \\\\\n\\num[round-mode = places]{1} \\\\\n\\sisetup{round-integer-to-decimal}\n\\num[round-mode = figures]{1} \\\\\n\\num[round-mode = places]{1}\\\\\n}\n\n\\subsubsection{round-minimum}\n{\n\\sisetup{round-mode = places}%\n\\num{0.0055} \\\\\n\\num{0.0045} \\\\\n\\sisetup{round-minimum = 0.01}%\n\\num{0.0055} \\\\\n\\num{0.0045}\\\\\n}\n\n\\subsubsection{round-half}\n{\n\\sisetup{round-mode = places, round-half = up}%\n\\num{0.055} \\\\\n\\num{0.045} \\\\\n\\sisetup{round-half = even}%\n\\num{0.055} \\\\\n\\num{0.045}\n}\n\n\\subsubsection{add-decimal-zero, add-integer-zero}\n{\n\\num{123.} \\\\\n\\num{456} \\\\\n\\num{.789} \\\\\n\\sisetup{\n  add-decimal-zero = false,\n  add-integer-zero = false,\n}%\n\\num{123.} \\\\\n\\num{456} \\\\\n\\num{.789}\\\\\n}\n\n\\subsubsection{minimum-integer-digits}\n\\num{123} \\\\\n\\num[minimum-integer-digits = 1]{123} \\\\\n\\num[minimum-integer-digits = 2]{123} \\\\\n\\num[minimum-integer-digits = 3]{123} \\\\\n\\num[minimum-integer-digits = 4]{123}\\\\\n\n\\subsubsection{explicit-sign, retain-explicit-sign}\n\\num{+345} \\\\\n\\num[retain-explicit-plus]{+345} \\\\\n\\num[explicit-sign = -]{345}\\\\\n\\num[explicit-sign = -]{+345}\\\\\n\n\\subsubsection{retain-unity-mantissa, retain-zero-exponent}\n\\num{1e4} \\\\\n\\num[retain-unity-mantissa = false]{1e4} \\\\\n\\num{444e0} \\\\\n\\num[retain-zero-exponent = true]{444e0}\\\\\n\n\\subsubsection{scientific-notation, fixed-exponent}\n{\n\\num{0.001}\\\\\n\\num{0.0100} \\\\\n\\num{1200}\\\\\n\\sisetup{scientific-notation = true}%\n\\num{0.001}\\\\\n\\num{0.0100} \\\\\n\\num{1200}\\\\\n\\sisetup{scientific-notation = engineering}%\n\\num{0.001}\\\\\n\\num{0.0100} \\\\\n\\num{1200}\\\\\n\\sisetup{\nfixed-exponent = 2,\nscientific-notation = fixed,\n}%\n\\num{0.001}\\\\\n\\num{0.0100} \\\\\n\\num{1200}\\\\\n}\n\n\\subsubsection{omit-uncertainty}\n\\num{0.01(2)} \\\\\n\\num[omit-uncertainty]{0.01(2)}\\\\\n\n\\subsection{Printing numbers}\n\\subsubsection{group-digits, group-four-digits,group-seperator}\n\\num{12345.67890}\\\\\n\\num[group-digits= false]{12345.67890}\\\\\n\\num[group-digits= decimal]{12345.67890} \\\\\n\\num[group-digits= integer]{12345.67890}\\\\\n\n\\num[group-digits= false]{12345.67890}\\\\\n\\num[group-digits= decimal]{12345.67890} \\\\\n\\num[group-digits= integer]{12345.67890}\\\\\n\n\\num{1234567890.1234567890}\\\\\n\\num[group-four-digits]{1234567890.1234567890}\\\\\n\n\\num{12345} \\\\\n\\num[group-separator = {,}]{12345} \\\\\n\\num[group-separator = \\text{~}]{12345}\\\\\n\n\\subsubsection{group-minimum-digits}\n\\num{1234} \\\\\n\\num[group-minimum-digits = 4]{1234} \\\\\n\\num{1234.5678} \\\\\n\\num[group-minimum-digits = 4]{1234.5678}\\\\\n\n\\subsubsection{output-complex-root,output-decimal-marker,copy-complex-root,copy-decimal-marker}\n\\num{1.23} \\\\\n\\num[output-decimal-marker = {,}]{1.23} \\\\\n\\num{1+2i} \\\\\n\\num[output-complex-root = \\text{\\ensuremath{i}}]{1+2i} \\\\\n\\num[output-complex-root = j]{1+2i} \\\\\n\\num[copy-complex-root]{1+2j} \\\\\n\\num[copy-decimal-marker]{555,555}\\\\\n\n\\subsubsection{complex-root-position}\n\\num{67-0.9i} \\\\\n\\num[complex-root-position = before-number]{67-0.9i} \\\\\n\\num[complex-root-position = after-number]{67-0.9i}\\\\\n\n\\subsubsection{exponent-base, exponent-product}\n\\num[exponent-product = \\times]{1e2} \\\\\n\\num[exponent-product = \\cdot]{1e2} \\\\\n\\num[exponent-base = 2]{1e2}\\\\\n\n\\subsubsection{output-exponent-marker}\n\\num[output-exponent-marker = \\text{e}]{1e2} \\\\\n\\num[output-exponent-marker = \\ensuremath{\\mathrm{E}}]{1e2}\\\\\n\n\\subsubsection{separate-uncertainty,uncertainty-separator,output-open-uncertainty,output-close-uncertain\nty}\n{\n\\num{1.234(5)} \\\\\n\\num{1.234\\pm 0.005} \\\\\n\\num[separate-uncertainty = true]{1.234(5)} \\\\\n\\num[separate-uncertainty = true]{1.234\\pm 0.005} \\\\\n\\sisetup{\n  output-open-uncertainty = [,\n  output-close-uncertainty = ],\n  uncertainty-separator= {\\,}\n}\n\\num{1.234(5)}\\\\\n}\n\\num{8.2(13)} \\\\\n\\num{8.2\\pm1.3} \\\\\n\\num[separate-uncertainty]{8.2(13)}\\\\\n\\num[separate-uncertainty]{8.2\\pm1.3} \\\\\n\n\\num{1.234(5) x \\pi} \\\\\n\\num[separate-uncertainty = true]{1.234(5) x \\pi} \\\\\n\n\\num{1.2 +- 0.001}\\\\\n\\num[separate-uncertainty]{1.2 +- 0.001}\\\\\n\n\\subsubsection{bracket-numbers, open-bracket, close-bracket}\n{\n\\num{1 e10} \\\\\n\\num{2i e10} \\\\\n\\num{1+2i e10} \\\\\n\\num[bracket-numbers = false]{1+2i e10} \\\\\n\\sisetup{\n  open-bracket = \\{,\n  close-bracket = \\},\n}\n\\num{1+2i e10}\\\\\n}\n\n\\subsubsection{negative-color}\n\\num{-15673} \\\\\n\\num[negative-color = red]{-15673}\n\n\\subsubsection{bracket-negative-numbers}\n\\num{-15673} \\\\\n\\num[bracket-negative-numbers]{-15673} \\\\\n%\\SI{-10}{\\metre} \\\\\n%\\SI[bracket-negative-numbers]{-10}{\\metre}\n\n\\subsection{Multi-part Numbers}\n\n\\subsubsection{input-product,input-quotient}\n\\num{1 x 2 x 3} \\\\\n\\num{1e4 x 2(3) x 3/4} \\\\\n\\num[input-product=*]{4 * 5 * 6} \\\\\n\\num{ 1 / 2e4 } \\\\\n\\num{ 1e2 / 3e4 }\\\\\n\n\\subsubsection{output-product, output-quotient}\n\\num[output-product = \\cdot]{4.87 x 5.321 x 6.90545} \\\\\n\\num[output-quotient = \\text{ div }]{1 / 2}\\\\\n\n\\subsubsection{quotient-mode}\n\\num{1 / 2e4} \\\\\n\\num[quotient-mode = fraction]{1 / 2e4}\\\\\n\n\\subsubsection{fraction-function}\n{\n\\sisetup{quotient-mode= fraction}\n\\num{1 / 1}\\\\\n\\num[fraction-function= \\dfrac]{1 / 2}\\\\\n%\\num[fraction-function= \\sfrac]{1 / 3}\\\\\n\\num[fraction-function= \\tfrac]{1 / 4}\\\\\n}\n\n\\subsection{Lists and ranges of numbers}\n\\subsubsection{list-final-separator,list-pair-separator,list-separator}\n\\numlist{0.1;0.2;0.3}\\\\\n\\numlist[list-separator = {; }]{0.1;0.2;0.3}\\\\\n\\numlist[list-final-separator = {, }]{0.1;0.2;0.3} \\\\\n\\numlist[\nlist-separator\n= { and },\nlist-final-separator = { and finally }\n]{0.1;0.2;0.3} \\\\\n\\numlist{0.1;0.2} \\\\\n\\numlist[list-pair-separator = {, and }]{0.1;0.2}\\\\\n\n\\subsection{range-phrase}\n\n\\numrange{5}{100} \\\\\n\\numrange[range-phrase = --]{5}{100}\\\\\n\n\\subsection{Angles}\n\\subsubsection{number-angle-product}\n\\ang{2.67} \\\\\n\\ang[number-angle-product = \\,]{2.67}\n\\subsubsection{arc-separator}\n\\ang{6;7;6.5} \\\\\n\\ang[arc-separator = \\,]{6;7;6.5}\n\\subsubsection{add-arc-degree-zero,add-arc-minute-zero,add-arc-second-zero}\n\\ang{-1;;} \\\\\n\\ang{;-2;} \\\\\n\\ang{;;-3} \\\\\n{\n\\sisetup{add-arc-degree-zero}\n\\ang{-1;;} \\\\\n\\ang{;-2;} \\\\\n\\ang{;;-3} \\\\\n}\n{\n\\sisetup{add-arc-minute-zero}\n\\ang{-1;;} \\\\\n\\ang{;-2;} \\\\\n\\ang{;;-3} \\\\\n}\n{\n\\sisetup{add-arc-second-zero}\n\\ang{-1;;} \\\\\n\\ang{;-2;} \\\\\n\\ang{;;-3}\\\\\n}\n\\ang[add-arc-minute-zero,add-arc-second-zero]{45.697}\\\\\n\n\\subsubsection{angle-symbol-over-decimal}\n\\ang{45.697} \\\\\n\\ang{6;7;6.5} \\\\\n\\ang[angle-symbol-over-decimal]{45.697} \\\\\n\\ang[angle-symbol-over-decimal]{6;7;6.5}\n\n% \\ang{10}\\\\\n% \\ang{12.3}\\\\\n% \\ang{4,5}\\\\\n% \\ang{1;2;3}\\\\\n% \\ang{;;1}\\\\\n% \\ang{+10;;}\\\\\n% \\ang{-0;1;}\\\\\n\n\n\\section{Units}\n\\def\\showunit#1{#1 & \\texttt{$\\backslash$#1} & \\si{\\csname#1\\endcsname}}\n\\begin{table}\n\\caption{SI base units}\n\\centering\n\\begin{tabular}{lll}\\hline\\hline\nUnit & Macro & Symbol \\\\\\hline\n\\showunit{ampere}\\\\\n\\showunit{candela}\\\\\n\\showunit{kelvin}\\\\\n\\showunit{kilogram}\\\\\n\\showunit{metre}\\\\\n\\showunit{mole}\\\\\n\\showunit{second}\\\\\n\\end{tabular}\n\\end{table}\n\n\\begin{table}\n\\caption{Coherent derived units}\n\\centering\n\\begin{tabular}{llllll}\\hline\\hline\nUnit & Macro & Symbol &\nUnit & Macro & Symbol \\\\\\hline\n\\showunit{becquerel}     & \\showunit{newton} \\\\\n\\showunit{degreeCelsius} & \\showunit{ohm} \\\\\n\\showunit{coulomb}       & \\showunit{pascal} \\\\\n\\showunit{farad}         & \\showunit{radian} \\\\\n\\showunit{gray}          & \\showunit{siemens} \\\\\n\\showunit{hertz}         & \\showunit{sievert} \\\\\n\\showunit{henry}         & \\showunit{steradian} \\\\\n\\showunit{joule}         & \\showunit{tesla} \\\\\n\\showunit{katal}         & \\showunit{volt} \\\\\n\\showunit{lumen}         & \\showunit{watt} \\\\\n\\showunit{lux}           & \\showunit{weber} \\\\\n\\end{tabular}\n\\end{table}\n\n\\begin{table}\n\\caption{Non-SI units}\n\\centering\n\\begin{tabular}{lll}\\hline\\hline\nUnit & Macro & Symbol \\\\\\hline\n\\showunit{day}\\\\\n\\showunit{degree}\\\\\n\\showunit{hectare}\\\\\n\\showunit{hour} \\\\\n\\showunit{litre}\\\\\n\\showunit{liter}\\\\\n\\showunit{arcminute}\\\\\n\\showunit{minute}\\\\\n\\showunit{arcsecond}\\\\\n\\showunit{tonne}\\\\\n\\end{tabular}\n\\end{table}\n\n\\begin{table}\n\\caption{Expermental Non-SI units}\n\\centering\n\\begin{tabular}{lll}\\hline\\hline\nUnit & Macro & Symbol \\\\\\hline\n\\showunit{astronomicalunit}\\\\\n\\showunit{atomicmassunit}\\\\\n\\showunit{bohr}\\\\\n\\showunit{clight}\\\\\n\\showunit{dalton}\\\\\n\\showunit{electronmass}\\\\\n\\showunit{electronvolt}\\\\\n\\showunit{elementarycharge}\\\\\n\\showunit{hartree}\\\\\n\\showunit{planckbar}\\\\\n\\end{tabular}\n\\end{table}\n\n\\begin{table}\n\\caption{Other non-SI units}\n\\centering\n\\begin{tabular}{lll}\\hline\\hline\nUnit & Macro & Symbol \\\\\\hline\n\\showunit{angstrom}\\\\\n\\showunit{bar}\\\\\n\\showunit{barn}\\\\\n\\showunit{bel}\\\\\n\\showunit{decibel}\\\\\n\\showunit{knot}\\\\\n\\showunit{mmHg}\\\\\n\\showunit{nauticalmile}\\\\\n\\showunit{neper}\\\\\n\\end{tabular}\n\\end{table}\n\n\\def\\showprefix#1{#1 & \\texttt{$\\backslash$#1} & \\si{\\csname#1\\endcsname} & \\si[prefixes-as-symbols=false]{\\csname#1\\endcsname}}\n\\begin{table}\n\\caption{Other non-SI units}\n\\centering\n\\begin{tabular}{llllllll}\\hline\\hline\nUnit & Macro & Symbol & Power\nUnit & Macro & Symbol & Power \\\\\\hline\n\\showprefix{yocto} & \\showprefix{deca}\\\\\n\\showprefix{zepto} & \\showprefix{hecto}\\\\\n\\showprefix{atto}  & \\showprefix{kilo}\\\\\n\\showprefix{femto} & \\showprefix{mega}\\\\\n\\showprefix{pico}  & \\showprefix{giga}\\\\\n\\showprefix{nano}  & \\showprefix{tera}\\\\\n\\showprefix{micro} & \\showprefix{peta}\\\\\n\\showprefix{milli} & \\showprefix{exa}\\\\\n\\showprefix{centi} & \\showprefix{zetta}\\\\\n\\showprefix{deci}  & \\showprefix{yotta}\\\\\n\\end{tabular}\n\\end{table}\n\n\n\\begin{table}\n\\caption{Abbreviated units}\n\\centering\n\\begin{tabular}{lll}\\hline\\hline\nUnit & Macro & Symbol \\\\\\hline\n\\showunit{fg}\\\\\n\\showunit{pg}\\\\\n\\showunit{ng}\\\\\n\\showunit{ug}\\\\\n\\showunit{mg}\\\\\n\\showunit{g}\\\\\n\\showunit{kg}\\\\\n\\showunit{amu}\\\\\\hline\n\\showunit{pm}\\\\\n\\showunit{nm}\\\\\n\\showunit{um}\\\\\n\\showunit{mm}\\\\\n\\showunit{cm}\\\\\n\\showunit{dm}\\\\\n\\showunit{m}\\\\\n\\showunit{km}\\\\\\hline\n\\showunit{as}\\\\\n\\showunit{fs}\\\\\n\\showunit{ps}\\\\\n\\showunit{ns}\\\\\n\\showunit{us}\\\\\n\\showunit{ms}\\\\\n\\showunit{s}\\\\\\hline\n\\showunit{fmol}\\\\\n\\showunit{pmol}\\\\\n\\showunit{nmol}\\\\\n\\showunit{umol}\\\\\n\\showunit{mmol}\\\\\n\\showunit{mol}\\\\\n\\showunit{kmol}\\\\\\hline\n\\showunit{pA}\\\\\n\\showunit{nA}\\\\\n\\showunit{uA}\\\\\n\\showunit{mA}\\\\\n\\showunit{A}\\\\\n\\showunit{kA}\\\\\\hline\n\\showunit{ul}\\\\\n\\showunit{ml}\\\\\n\\showunit{l}\\\\\n\\showunit{hl}\\\\\n\\showunit{uL}\\\\\n\\showunit{mL}\\\\\n\\showunit{L}\\\\\n\\showunit{hL}\\\\\\hline\n\\showunit{mHz}\\\\\n\\showunit{Hz}\\\\\n\\showunit{kHz}\\\\\n\\showunit{MHz}\\\\\n\\showunit{GHz}\\\\\n\\showunit{THz}\\\\\\hline\n\\showunit{mN}\\\\\n\\showunit{N}\\\\\n\\showunit{kN}\\\\\n\\showunit{MN}\\\\\\hline\n\\showunit{Pa}\\\\\n\\showunit{kPa}\\\\\n\\showunit{MPa}\\\\\n\\showunit{GPa}\\\\\\hline\n\\showunit{mohm}\\\\\n\\showunit{kohm}\\\\\n\\showunit{Mohm}\\\\\\hline\n\\showunit{pV}\\\\\n\\showunit{nV}\\\\\n\\showunit{uV}\\\\\n\\showunit{mV}\\\\\n\\showunit{V}\\\\\n\\showunit{kV}\\\\\\hline\n\\showunit{W}\\\\\n\\showunit{uW}\\\\\n\\showunit{mW}\\\\\n\\showunit{kW}\\\\\n\\showunit{MW}\\\\\n\\showunit{GW}\\\\\\hline\n\\showunit{J}\\\\\n\\showunit{kJ}\\\\\\hline\n\\showunit{eV}\\\\\n\\showunit{meV}\\\\\n\\showunit{keV}\\\\\n\\showunit{MeV}\\\\\n\\showunit{GeV}\\\\\n\\showunit{TeV}\\\\\\hline\n\\showunit{kWh}\\\\\\hline\n\\showunit{F}\\\\\n\\showunit{fF}\\\\\n\\showunit{pF}\\\\\\hline\n\\showunit{K}\\\\\\hline\n\\showunit{dB}\\\\\\hline\n\\end{tabular}\n\\end{table}\n\n\\begin{table}\n\\caption{Binary prefixes}\n\\centering\n\\begin{tabular}{llllllll}\\hline\\hline\nUnit & Macro & Symbol & Power \\\\\\hline\n\\showprefix{kibi} \\\\\n\\showprefix{mebi} \\\\\n\\showprefix{gibi} \\\\\n\\showprefix{tebi} \\\\\n\\showprefix{pebi} \\\\\n\\showprefix{exbi} \\\\\n\\showprefix{zebi} \\\\\n\\showprefix{yobi} \\\\\n\\end{tabular}\n\\end{table}\n\n%\\subsection{Creating Units}\n%\\subsection{Loading additional units}\n\n\\subsection{Using units}\n% Note that \\kilogram is defined as \\kilo\\gram, and acts sorta like a macro\n\\si{\\kilogram}\n\\si{\\kilo\\gram}\n% Not allowed.\n%\\si{\\kilo\\kilogram}\n%\\si{\\kilo\\kilo\\gram}\n{\n% and note that regular macros ARE expanded!\n\\def\\killermeater{\\kilo\\meter}\n\\si{\\killermeater}\n}\n{\n% BUT, it prefers its OWN definitions!\n\\def\\gram{Grr}\n\\si{\\kilo\\gram}\n}\n\n% However, it's happy with various indirect definitions.\n% Ie. units, prefixes (at least) act like regular macros within \\si.\n\\si{\\abbra}\\\\\n\\si{\\abbrb}\\\\\n\\si{\\abbrc}\\\\\n\\si{\\abbrd}\\\\\n\\si{\\abbre}\\\\\n\n\\si{\\mabbra}\\\\\n\\si{\\mabbrb}\\\\\n\n\\si{\\killer\\meter}\\\\\n\n% Where can highlight go?\n\\si{\\highlight{red}\\kilo\\gram\\metre\\per\\second} \\\\\n\\si{\\kilo\\highlight{red}\\gram\\metre\\per\\second} \\\\\n\\si{\\kilo\\gram\\highlight{red}\\metre\\per\\second} \\\\\n\\si{\\kilo\\gram\\metre\\highlight{red}\\per\\second} \\\\\n\\si{\\kilo\\gram\\metre\\per\\highlight{red}\\second} \\\\\n\n\\si{\\cancel\\kilo\\gram\\metre\\per\\second} \\\\\n\\si{\\kilo\\cancel\\gram\\metre\\per\\second} \\\\\n\\si{\\kilo\\gram\\cancel\\metre\\per\\second} \\\\\n\\si{\\kilo\\gram\\metre\\cancel\\per\\second} \\\\\n\\si{\\kilo\\gram\\metre\\per\\cancel\\second} \\\\\n\n\\subsubsection{forbid-literal-units, inter-unit-product}\n\\si{\\farad\\squared\\lumen\\candela} \\\\\n\\si[inter-unit-product = \\ensuremath{{}\\cdot{}}]\n{\\farad\\squared\\lumen\\candela}\\\\\n\n\\subsubsection{per-mode, per-symbol, bracket-unit-denominator}\n\\si{\\joule\\per\\mole\\per\\kelvin} \\\\\n\\si{\\metre\\per\\second\\squared} \\\\\n\\si[per-mode=fraction]{\\joule\\per\\mole\\per\\kelvin} \\\\\n\\si[per-mode=fraction]{\\joule\\raiseto{-1}\\mole\\per\\kelvin} \\\\\n\\si[per-mode=fraction]{\\metre\\per\\second\\squared}\\\\\n\\si{\\ampere\\per\\mole\\second} \\\\\n\\si[per-mode = reciprocal-positive-first]{\\ampere\\per\\mole\\second}\n\n{\n\\sisetup{per-mode = symbol}%\n\\si{\\joule\\per\\mole\\per\\kelvin} \\\\\n\\si{\\metre\\per\\second\\squared} \\\\\n\\si[per-symbol = \\text{~div~}]{\\joule\\per\\mole\\per\\kelvin} \\\\\n\\si[bracket-unit-denominator = false]{\\joule\\per\\mole\\per\\kelvin}\\\\\n}\n\\si[per-mode=repeated-symbol]{\\joule\\per\\mole\\per\\kelvin}\\\\\n{\n\\sisetup{per-mode = symbol-or-fraction}%\n\\( \\si{\\joule\\per\\mole\\per\\kelvin} \\)\n\\[ \\si{\\joule\\per\\mole\\per\\kelvin} \\]\n\\si{\\joule\\per\\mole\\per\\kelvin} \\\\\n\\(\n\\displaystyle\n\\si{\\joule\\per\\mole\\per\\kelvin}\n\\)\n\\[\n\\textstyle\n\\si{\\joule\\per\\mole\\per\\kelvin}\n\\]\n}\n\n\\subsubsection{sticky-per}\n\\si{\\pascal\\per\\gray\\henry} \\\\\n\\si[sticky-per]{\\pascal\\per\\gray\\henry}\\\\\n\n\\subsubsection{power-font}\n\\si{\\metre\\per\\second\\squared} \\\\\n\\si[power-font = unit]{\\metre\\per\\second\\squared}\\\\\n\n\\subsubsection{literal-superscript-as-power}\n\\si{m.s^{2}} \\\\\n\\si[literal-superscript-as-power = false]{m.s^{2}}\\\\\n\n\\subsubsection{qualifier-mode, qualifier-phrase}\n\\si{\\kilogram\\polymer\\squared\\per\\mole\\catalyst\\per\\hour} \\\\\n\\si[qualifier-mode = brackets]\n{\\kilogram\\polymer\\squared\\per\\mole\\catalyst\\per\\hour} \\\\\n\\si[qualifier-mode = subscript]\n{\\kilogram\\polymer\\squared\\per\\mole\\catalyst\\per\\hour} \\\\\n\\si[qualifier-mode = space]\n{\\kilogram\\polymer\\squared\\per\\mole\\catalyst\\per\\hour} \\\\\n\\si[qualifier-mode = text]\n{\\deci\\bel\\isotropic}\\\\\n\n\\si[qualifier-mode = phrase]\n{\\kilogram\\polymer\\squared\\per\\mole\\catalyst\\per\\hour} \\\\\n\\si[qualifier-mode = phrase, qualifier-phrase = { by }]\n{\\kilogram\\polymer\\squared\\per\\mole\\catalyst\\per\\hour} \\\\\n\n\\subsubsection{prefixes-as-symbols}\n\\si{\\milli\\litre\\per\\mole\\deci\\ampere} \\\\\n%%\\SI{10}{\\kilo\\gram\\squared\\deci\\second} \\\\\n\\si[prefixes-as-symbols=false]{\\milli\\litre\\per\\mole\\deci\\ampere}\\\\\n\\si[prefixes-as-symbols=false]{\\kilo\\gram\\squared\\deci\\second}\\\\\n\\si{\\mega\\gram\\squared\\deci\\second}\\\\\n\\si[prefixes-as-symbols=false]{\\mega\\gram\\squared\\deci\\second}\\\\\n\\si{\\micro\\gram\\squared\\deci\\second}\\\\\n\\si[prefixes-as-symbols=false]{\\micro\\gram\\squared\\deci\\second}\\\\\n\\si{\\per\\mega\\gram\\squared\\deci\\second}\\\\\n\\si[prefixes-as-symbols=false]{\\per\\mega\\gram\\squared\\deci\\second}\\\\\n\\si{\\per\\micro\\gram\\squared\\deci\\second}\\\\\n\\si[prefixes-as-symbols=false]{\\per\\micro\\gram\\squared\\deci\\second}\\\\\n%%\\SI[prefixes-as-symbols=false]{10}{\\kilo\\gram\\squared\\deci\\second}\\\\\n\n\\subsubsection{parse-units}\n%%\\SI{300}{\\MHz} \\\\\n%%\\SI[parse-units = false]{300}{\\MHz}\\\\\n\n\\subsection{Numbers with units}\n\\subsubsection{allow-number-unit-breaks}\n\\subsubsection{number-unit-product}\n\\SI{2.67}{\\farad} \\\\\n\\SI[number-unit-product = \\ ]{2.67}{\\farad} \\\\\n\\SI[number-unit-product = ]{2.67}{\\farad}\\\\\n\n\\subsubsection{multi-part-units}\n{\n\\sisetup{separate-uncertainty}%\n\\SI{12.3(4)}{\\kilo\\gram} \\\\\n\\SI[multi-part-units = brackets]{12.3(4)}{\\kilo\\gram} \\\\\n\\SI[multi-part-units = repeat]{12.3(4)}{\\kilo\\gram}\\\\\n\\SI[multi-part-units = single]{12.3(4)}{\\kilo\\gram}\\\\\n}\n\n{\n\\sisetup{separate-uncertainty,bracket-numbers = false}%\n\\num{1.234(5)e-4} \\\\\n\\SI{1.234(5)e-4}{\\metre}\\\\\n}\n\\subsubsection{product-units}\n\\SI{2 x 3 x 4}{\\metre} \\\\\n\\SI[product-units = brackets]{2 x 3 x 4}{\\metre}\\\\\n\\SI[product-units = brackets-power]{2 x 3 x 4}{\\metre}\\\\\n\\SI[product-units = power]{2 x 3 x 4}{\\metre}\\\\\n\\SI[product-units = repeat]{2 x 3 x 4}{\\metre}\\\\\n\\SI[product-units = single]{2 x 3 x 4}{\\metre}\\\\\n\n\\subsubsection{list-units,range-units}\n\\SIlist{2;4;6;8}{\\tesla} \\\\\n\\SIlist[list-units = brackets]{2;4;6;8}{\\tesla} \\\\\n\\SIlist[list-units = repeat]{2;4;6;8}{\\tesla} \\\\\n\\SIlist[list-units = single]{2;4;6;8}{\\tesla} \\\\\n\\SIrange{2}{4}{\\degreeCelsius} \\\\\n\\SIrange[range-units = brackets]{2}{4}{\\degreeCelsius} \\\\\n\\SIrange[range-units = repeat]{2}{4}{\\degreeCelsius} \\\\\n\\SIrange[range-units = single]{2}{4}{\\degreeCelsius}\\\\\n\n\\subsubsection{exponent-to-prefix}\n\\SI{1700}{\\g} \\\\\n\\SI{1.7e3}{\\g} \\\\\n{\n\\sisetup{exponent-to-prefix}%\n\\SI{1700}{\\g} \\\\\n\\SI{1.7e3}{\\g} \\\\\n}\n{\n\\sisetup{fixed-exponent = 3, scientific-notation = fixed}%\n\\SI{1700}{\\g} \\\\\n\\SI{1.7e3}{\\g}\\\\\n}\n\n\\subsubsection{just degree}\n\n\\si{\\degree}\n\n\\section{Tabular material}\n% \\begin{tabular}{S}\n% 2.3456 \\\\\n% \\end{tabular}\n% \\end{document}\n\n\n\\begin{table}[H]\n\\caption{Standard behaviour of the \\texttt{S} column type.}\n\\label{tab:S:standard}\n\\centering\n\\begin{tabular}{S}\n\\toprule\n{Some Values} \\\\\n\\midrule\n2.3456 \\\\\n34.2345 \\\\\n-6.7835 \\\\\n90.473 \\\\\n5642.5 \\\\\n1.2e3 \\\\\ne4 \\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n\n\n%\\end{document}\n\n\n\n\\begin{table}[H]\n\\caption{Detection of surrounding material in an \\texttt{S} column.}\n\\label{tab:S:extras}\n\\centering\n\\begin{tabular}{S[color=orange]}\n\\toprule\n{Some Values} \\\\\n\\midrule\n12.34 \\\\\n\\color{purple} 975,31 \\\\\n44.268 \\textsuperscript{\\emph{a}} \\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n\n\\begin{table}[H]\n\\caption{Controlling complex alignment with the tablenum macro.}\n\\label{tab:tablenum}\n\\centering\n\\begin{tabular}{lr}\n\\toprule\nHeading & Heading \\\\\n\\midrule\nInfo & More info \\\\\nInfo & More info \\\\\n\\multicolumn{2}{c}{\\tablenum[table-format = 4.4]{12,34}} \\\\\n\\multicolumn{2}{c}{\\tablenum[table-format = 4.4]{333.5567}} \\\\\n\\multicolumn{2}{c}{\\tablenum[table-format = 4.4]{4563.21}} \\\\\n\\bottomrule\n\\end{tabular}\n\\hfil\n\\begin{tabular}{lr}\n\\toprule\nHeading & Heading \\\\\n\\midrule\n\\multirow{2}*{\\tablenum{88,999}} & aaa \\\\\n& bbb \\\\\n\\multirow{2}*{\\tablenum{33,435}} & ccc \\\\\n& ddd \\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n\n\\begin{table}[H]\n\\centering\n\\caption{Units in tables.}\n\\label{tab:s:demo}\n\\begin{tabular}{s}\n\\toprule\n\\multicolumn{1}{c}{Unit} \\\\\n\\midrule\n\\metre\\squared\\per\\second \\\\\n\\pascal \\\\\nm.s^{-1} \\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n\n\\begin{table}[H]\n\\centering\n\\caption{The \\texttt{s} column processes everything.}\n\\label{tab:s:processing}\n\\sisetup{color = orange}\n\\begin{tabular}{ss}\n\\toprule\n{Unit}\n& \\multicolumn{1}{c}{Unit}\\\\\n\\midrule\n{\\si{m^3}} & \\multicolumn{1}{c}{\\si{m^3}} \\\\\n\\kilogram\n& \\kilogram \\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n\n\\subsubsection{table-parse-only}\n\\begin{table}[H]\n\\centering\n\\caption{Parsing without aligning in an \\texttt{S} column.}\n\\label{tab:S:parse}\n\\begin{tabular}{SS[table-parse-only]}\n\\toprule\n{Decimal-centred} &\n{Simple centring} \\\\\n\\midrule\n12.345 & 12.345 \\\\\n6,78   & 6,78   \\\\\n-88.8(9) & -88.8(9) \\\\\n4.5e3    & 4.5e3 \\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n\n\\subsubsection{table-number-alignment}\n\\begin{table}[H]\n\\caption{Aligning the \\texttt{S} column.}\n\\label{tab:S:align}\n\\centering\n\\sisetup{\ntable-figures-integer = 2,\ntable-figures-decimal = 4\n}\n\\begin{tabular}{\nS\nS[table-number-alignment = center]\nS[table-number-alignment = left]\nS[table-number-alignment = right]\n}\n\\toprule\n{Some Values} & {Some Values} & {Some Values} & {Some Values} \\\\\n\\midrule\n2.3456 & 2.3456 & 2.3456 & 2.3456\\\\\n34.2345 & 34.2345 & 34.2345 & 34.2345\\\\\n56.7835 & 56.7835& 56.7835 & 56.7835\\\\\n90.473 & 90.473 & 90.473 & 90.473\\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n\n\\subsubsection{table-figures-decimal, table-figures-exponent,table-figures-integer,table-figures-\nuncertainty}\n\n\\begin{table}[H]\n\\caption{Reserving space in \\texttt{S} columns.}\n\\label{tab:S:space}\n\\sisetup{\ntable-number-alignment = center,\ntable-figures-integer = 2\n}\n\\centering\n\\begin{tabular}{\nS\nS[table-number-alignment = right]\nS[table-figures-uncertainty = 1]\nS[separate-uncertainty, table-figures-uncertainty = 1]\nS[table-sign-mantissa]\nS[table-figures-exponent = 1]\n}\n\\toprule\n{Values}\n& {Values}\n& {Values}\n& {Values}\n& {Values}\n& {Values} \\\\\n\\midrule\n2.3 & 2.3 & 2.3(5) & 2.3(5) & 2.3 & 2.3e8\\\\\n34.23 & 34.23 & 34.23(4) & 34.23(4) & 34.23 & 34.23\\\\\n56.78 & 56.78 & 56.78(3) & 56.78(3) & -56.78 & 56.78e3\\\\\n3,76 & 3,76 & 3,76(2) & 3.76(2) & +-3.76 & e6\\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n\n\\subsubsection{table-comparator}\n\\begin{table}[H]\n\\caption{Reserving space for comparators in \\texttt{S} columns.}\n\\label{tab:S:comparators}\n\\sisetup{\ntable-number-alignment = center,\ntable-figures-integer = 2,\ntable-figures-decimal = 2,\ntable-figures-exponent = 2,\n}\n\\centering\n\\begin{tabular}{\nS\nS[table-comparator = true]}\n\\toprule\n{Values}\n& {Values} \\\\\n\\midrule\n2 .3  & < 2.3e8\\\\\n34.23 & = 34.23 \\\\\n56.78 & >= 56.78e3\\\\\n3,76  & \\gg e6 \\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n\n\\subsubsection{table-format}\n\\begin{table}[H]\n\\caption{Using the \\texttt{table-format} option.}\n\\label{tab:S:format}\n\\centering\n\\begin{tabular}{\nS\nS[table-format = 2.2]\nS[table-format = 2.2(1)]\nS[table-format = +2.2]\nS[table-format = 2.2e1]\n}\n\\toprule\n{Values}\n& {Values}\n& {Values}\n& {Values}\n& {Values} \\\\\n\\midrule\n2.3 & 2.3 & 2.3(5) & 2.3 & 2.3e8 \\\\\n34.23 & 34.23 & 34.23(4) & 34.23 & 34.23 \\\\\n56.78 & 56.78 & 56.78(3) & -56.78 & 56.78e3 \\\\\n3,76 & 3,76 & 3.76(2) & +-3.76 & e6 \\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n\n\n\\subsubsection{table-space-text-pre, table-space-text-post}\n\\begin{table}[H]\n\\caption{Text before and after numbers.}\n\\label{tab:S:ends}\n\\centering\n\\sisetup{\ntable-number-alignment = center,\ntable-figures-integer = 2,\ntable-figures-decimal = 4,\ntable-space-text-pre\n= now~,\ntable-space-text-post =\n\\textsuperscript{\\emph{a}}\n}\n\\begin{tabular}{S}\n\\toprule\n{Values} \\\\\n\\midrule\n2.3456 \\\\\n34.2345 \\textsuperscript{\\emph{a}}\\\\\n56.7835 \\\\\nnow~ 90.473 \\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n\n\\subsubsection{table-align-comparator, table-align-exponent, table-align-uncertainty}\n\\begin{table}[H]\n\\centering\n\\caption{The \\texttt{table-align-exponent} option}\n\\label{tab:align:exp}\n\\sisetup{table-format = 1.3e2, table-number-alignment = center}\n\\begin{tabular}{SS[table-align-exponent = false]}\n\\toprule\n{Header} & {Header} \\\\\n\\midrule\n1.2e3 & 1.2e3 \\\\\n1.234e56 & 1.234e56 \\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n\n\\begin{table}[H]\n\\centering\n\\caption{The \\texttt{table-align-uncertainty} option}\n\\label{tab:align:uncert}\n\\sisetup{\nseparate-uncertainty,\ntable-format = 1.3(1),\n}\n\\begin{tabular}{SS[table-align-uncertainty = false]}\n\\toprule\n{Header} & {Header} \\\\\n\\midrule\n1.2(1) & 1.2(3) \\\\\n1.234(5) & 1.234(5) \\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n\n\\begin{table}[H]\n\\centering\n\\caption{The \\texttt{table-align-comparator} option}\n\\label{tab:align:comp}\n\\sisetup{table-format = >2.2}\n\\begin{tabular}{SS[table-align-comparator = false]}\n\\toprule\n{Header} & {Header} \\\\\n\\midrule\n> 1.2 & > 1.2 \\\\\n< 12.34 & < 12.34 \\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n\n\\subsubsection{table-omit-exponent}\n\\begin{table}[H]\n\\centering\n\\caption{The \\texttt{table-omit-exponent} option}\n\\label{tab:exp:omit}\n\\begin{tabular}{\nS[table-format = 1.1e1]\nS[fixed-exponent = 3, table-format = 2.1, table-omit-exponent]\n}\n\\toprule\n{Header} & {Header / \\num{e3}} \\\\\n\\midrule\n1.2e3 & 1.2e3 \\\\\n3e2 & 3e2 \\\\\n1.0e4 & 1.0e4 \\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n\n\\subsubsection{table-align-text-pre,table-align-text-post}\n% \\begin{table}[H]\n% \\caption{Closing notes up to text.}\n% \\label{tab:S:notes}\n% \\newrobustcmd\\NoteMark[1]{%\n% \\textsuperscript{\\emph{#1}}%\n% }\n% \\centering\n% \\sisetup{\n% table-number-alignment = center,\n% table-figures-integer = 2,\n% table-figures-decimal = 4,\n% table-space-text-pre\n% = \\NoteMark{a}\n% }\n% \\begin{tabular}{\n% S\n% S[table-align-text-pre = false]\n% }\n% \\toprule\n% {Values}\n% & {Values} \\\\\n% \\midrule\n% 2.3456 &\n% 2.3456 \\\\\n% \\NoteMark{a} 4.234 & \\NoteMark{a} 4.234 \\\\\n% \\NoteMark{b}\n% .78\n% & \\NoteMark{b}\n% .78 \\\\\n% \\NoteMark{d} 88\n% & \\NoteMark{d} 88\n% \\\\\n% \\bottomrule\n% \\end{tabular}\n% \\hfil\n% \\sisetup{table-space-text-post = \\NoteMark{a}}\n% \\begin{tabular}{\n% S\n% S[table-align-text-post = false]\n% }\n% \\toprule\n% {Values}\n% & {Values} \\\\\n% \\midrule\n% 2.3456\n% & 2.3456 \\\\\n% 34.234 \\NoteMark{a} & 34.234 \\NoteMark{a} \\\\\n% 56.78\n% \\NoteMark{b} & 56.78 \\NoteMark{b} \\\\\n% 90.4\n% \\NoteMark{c} & 90.4\n% \\NoteMark{c} \\\\\n% 88\n% \\NoteMark{d} & 88\n% \\NoteMark{d} \\\\\n% \\bottomrule\n% \\end{tabular}\n% \\end{table}\n\n\\subsubsection{table-auto-round}\n\\begin{table}[H]\n\\centering\n\\caption{The \\texttt{table-auto-round} option.}\n\\label{tab:S:auto}\n\\sisetup{\ntable-number-alignment = center,\ntable-figures-integer = 1,\ntable-figures-decimal = 3\n}\n% Notice the overfull hbox which results with\n% the first column\n\\begin{tabular}{\nS\nS[table-auto-round]\n}\n\\toprule\n{Header} & {Header} \\\\\n\\midrule\n1.2 & 1.2 \\\\\n1.2345 & 1.2345 \\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n\n\\subsubsection{parse-numbers}\n\\begin{table}[H]\n\\caption{Aligning without parsing.}\n\\label{tab:S:nonparsed}\n\\sisetup{\nparse-numbers = false,\ntable-figures-integer = 2,\ntable-figures-decimal = 3\n}\n\\centering\n\\begin{tabular}{\nS\nS[table-number-alignment = center]\nS[table-number-alignment = right]\nS[table-number-alignment = left]\n}\n\\toprule\n{Some values}\n& {Some values}\n& {Some values}\n& {Some values} \\\\\n\\midrule\n2.35 &\n2.35 &\n2.35 &\n2.35 \\\\\n34.234 &\n34.234 &\n34.234 & 34.234 \\\\\n56.783 &\n56.783 &\n56.783 & 56.783 \\\\\n3,762 &\n3,762 &\n3,762 &\n3.762 \\\\\n\\sqrt{2} & \\sqrt{2} & \\sqrt{2} & \\sqrt{2} \\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n\n\\subsubsection{table-text-alignment}\n\\begin{table}[H]\n\\caption{Aligning text in \\texttt{S} columns.}\n\\label{tab:S:text}\n\\sisetup{\ntable-number-alignment = center,\ntable-figures-integer = 4,\ntable-figures-decimal = 4\n}\n\\centering\n\\begin{tabular}{\nS\nS[table-text-alignment = left]\nS[table-text-alignment = right]\n}\n\\toprule\n{Values}\n& {Values}\n& {Values} \\\\\n\\midrule\n992.435 & 992.435 & 992.435 \\\\\n7734.2344 & 7734.2344 & 7734.2344 \\\\\n56.7834 &\n56.7834 &\n56.7834 \\\\\n3,7462 &\n3,7462 &\n3,7462 \\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n\n\\subsubsection{table-unit-alignment}\n\\begin{table}[H]\n\\centering\n\\caption{Alignment options in \\texttt{s} columns.}\n\\label{tab:s:align}\n\\begin{tabular}\n{\ns[table-unit-alignment = right]\ns\ns[table-unit-alignment = left]\n}\n\\toprule\n{Right-aligned} &\n{Centred text} &\n{Left-aligned} \\\\\n\\midrule\n\\metre\\per\\second & \\metre\\per\\second & \\metre\\per\\second \\\\\n\\kilogram\n& \\kilogram\n& \\kilogram\n\\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n\n\\subsubsection{table-alignment}\n\n\\subsubsection{table-column-width}\n\\begin{table}[H]\n\\centering\n\\caption{Fixed-width columns.}\n\\label{tab:width:fixed}\n\\begin{tabular}\n{\ns\ns[table-column-width = 2 cm]\nS\nS[table-column-width = 2 cm]\n}\n\\toprule\n{Flexible} &\n{Fixed}\n&\n{Flexible} &\n{Fixed}\n\\\\\n\\midrule\n\\metre\\per\\second & \\metre\\per\\second & 1.23 & 1.23 \\\\\n\\kilogram\\candela & \\kilogram\\candela & 45.6 & 45.6 \\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n\n% \\begin{table}[H]\n% \\centering\n% \\caption{Right-aligning under a heading.}\n% \\label{tab:width:special}\n% \\settowidth\\mylength{Long header}\n% \\sisetup{\n% table-format\n% = 4\n% ,\n% table-number-alignment = center\n% ,\n% table-column-width\n% = \\mylength ,\n% input-decimal-markers =\n% ,\n% input-symbols\n% = .\n% ,\n% }\n% \\begin{tabular}{S}\n% \\toprule\n% {Long header} \\\\\n% \\midrule\n% 12.33 \\\\\n% 2\n% \\\\\n% 1234\n% \\\\\n% \\bottomrule\n% \\end{tabular}\n% \\end{table}\n\n\\end{document}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\\si{kg.m.s^{-1}}\\\\\n\\si{\\kilogram\\metre\\per\\second} \\\\\n\\si[per-mode=symbol]{\\kilogram\\metre\\per\\second} \\\\\n\\si[per-mode=symbol]{\\kilogram\\metre\\per\\ampere\\per\\second}\n\n\\numlist{10;20;30}\\\\\n\\SIlist{0.13;0.67;0.80}{\\milli\\metre} \\\\\n\\numrange{10}{20}\\\\\n\\SIrange{0.13}{0.67}{\\milli\\metre}\\\\\n\n\n\\numlist{10;30;50;70}\n\n\\numrange{10}{30}\n\n\n\\si{kg.m/s^2} \\\\\n\\si{g_{polymer}~mol_{cat}.s^{-1}}\n\n\\si{\\kilo\\gram\\metre\\per\\square\\second}\n\\si{\\gram\\per\\cubic\\centi\\metre}\n\\si{\\square\\volt\\cubic\\lumen\\per\\farad}\n\\si{\\metre\\squared\\per\\gray\\cubic\\lux}\n\\si{\\henry\\second}\n\n\\SI[mode=text]{1.23}{J.mol^{-1}.K^{-1}}\\\\\n\\SI{.23e7}{\\candela}\\\\\n\\SI[per-mode=symbol]{1.99}[\\$]{\\per\\kilogram}\\\\\n\\SI[per-mode=fraction]{1,345}{\\coulomb\\per\\mole}\\\\\n\n\\SIlist{10;30;45}{\\metre}\n\n\\si{\\square\\becquerel} \\\\\n\\si{\\joule\\squared\\per\\lumen} \\\\\n\\si{\\cubic\\lux\\volt\\tesla\\cubed}\n\n\\si{\\henry\\tothe{5}} \\\\\n\\si{\\raiseto{4.5}\\radian}\n\n\\si{\\joule\\per\\mole\\per\\kelvin} \\\\\n\\si{\\joule\\per\\mole\\kelvin} \\\\\n\\si{\\per\\henry\\tothe{5}} \\\\\n\\si{\\per\\square\\becquerel}\n\n\\si{\\kilogram\\of{metal}} \\\\\n\\SI[qualifier-mode = brackets]\n{0.1}{\\milli\\mole\\of{cat}\\per\\kilogram\\of{prod}}\n\n\\si[per-mode = fraction]\n{\\cancel\\kilogram\\metre\\per\\cancel\\kilogram\\per\\second} \\\\\n\\si{\\highlight{red}\\kilogram\\metre\\per\\second} \\\\\n\\si[unit-color = purple]\n{\\highlight{red}\\kilogram\\metre\\per\\second}\n\n\n\\si{\\kilo} \\\\\n\\si{\\micro} \\\\\n\\si[prefixes-as-symbols = false]{\\kilo}\n\n\\si{\\kilo\\gram\\micro} \\\\\n\\SI{10}{\\micro}\n\n\n\\begin{table}\n\\caption{Standard behaviour of the \\texttt{S} column type.}\n\\label{tab:S:standard}\n\\centering\n\\begin{tabular}{S}\n\\toprule\n{Some Values} \\\\\n\\midrule\n2.3456 \\\\\n34.2345 \\\\\n-6.7835 \\\\\n90.473 \\\\\n5642.5\n\\\\\n1.2e3 \\\\\ne4 \\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n\n\\begin{table}\n\\caption{Detection of surrounding material in an \\texttt{S}\ncolumn.}\n\\label{tab:S:extras}\n\\centering\n\\begin{tabular}{S[color=orange]}\n\\toprule\n{Some Values} \\\\\n\\midrule\n12.34 \\\\\n\\color{purple} 975,31 \\\\\n44.268 \\textsuperscript{\\emph{a}} \\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n\n\\begin{table}\n\\caption{Controlling complex alignment with the tablenum macro.}\n\\label{tab:tablenum}\n\\centering\n\\begin{tabular}{lr}\n\\toprule\nHeading & Heading \\\\\n\\midrule\nInfo & More info \\\\\nInfo & More info \\\\\n\\multicolumn{2}{c}{\\tablenum[table-format = 4.4]{12,34}}\n\\\\\n\\multicolumn{2}{c}{\\tablenum[table-format = 4.4]{333.5567}} \\\\\n\\multicolumn{2}{c}{\\tablenum[table-format = 4.4]{4563.21}}\n\\bottomrule\n\\end{tabular}\n\\hfil\n\\begin{tabular}{lr}\n\\toprule\nHeading & Heading \\\\\n\\midrule\n\\multirow{2}*{\\tablenum{88,999}} & aaa \\\\\n& bbb \\\\\n\\multirow{2}*{\\tablenum{33,435}} & ccc \\\\\n& ddd \\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n\n\\begin{table}\n\\centering\n\\caption{Units in tables.}\n\\label{tab:s:demo}\n\\begin{tabular}{s}\n\\toprule\n\\multicolumn{1}{c}{Unit} \\\\\n\\midrule\n\\metre\\squared\\per\\second \\\\\n\\pascal \\\\\nm.s^{-1} \\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n\n\n\\end{document}\n", "meta": {"hexsha": "6045338bed37403bfe44ec419ad4b13557fe307a", "size": 33610, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tests/integration/packages/siunitx.tex", "max_stars_repo_name": "kenjikun/engrafo", "max_stars_repo_head_hexsha": "2ac87e215daea32699aa7f888f0405936d2ef452", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 836, "max_stars_repo_stars_event_min_datetime": "2017-10-23T10:16:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T00:31:05.000Z", "max_issues_repo_path": "tests/integration/packages/siunitx.tex", "max_issues_repo_name": "kenjikun/engrafo", "max_issues_repo_head_hexsha": "2ac87e215daea32699aa7f888f0405936d2ef452", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 894, "max_issues_repo_issues_event_min_datetime": "2017-10-23T09:27:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T19:06:07.000Z", "max_forks_repo_path": "tests/integration/packages/siunitx.tex", "max_forks_repo_name": "kenjikun/engrafo", "max_forks_repo_head_hexsha": "2ac87e215daea32699aa7f888f0405936d2ef452", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 62, "max_forks_repo_forks_event_min_datetime": "2017-10-23T19:29:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T12:19:08.000Z", "avg_line_length": 21.39401655, "max_line_length": 128, "alphanum_fraction": 0.6673013984, "num_tokens": 13225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.34670843128633855}}
{"text": "\\section{Modules}\n\n\\begin{itemize}\n\t\n\t\\item Modules provide a way to store data structures and procedures\n\t\n\t\\item Example:\\\\\n\t\\gcl{0}{\\Module ~ UniqueNumberAllocator}\n\t\\gcl{1}{\\Export ~ Acquire, Reset}\n\t\\gcl{1}{\\Import ~ Choose}\n\t\\gcl{1}{}\n\t\\gcl{1}{\\Var ~ u : \\textbf{set} \\left[0, N\\right)}\n\t\\gcl{1}{}\n\t\\gcl{1}{\\Procedure ~ Acquire(\\Result ~ t) \\defeq}\n\t\\gcl{2}{Choose(\\left[0, N\\right) - $ u $, t); u := u \\cup \\left\\lbrace t \\right\\rbrace]}\n\t\\gcl{1}{}\n\t\\gcl{1}{\\Procedure ~ Reset() \\defeq u := \\left\\lbrace \\right\\rbrace}\n\t\\gcl{1}{}\n\t\\gcl{1}{\\Procedure ~ Choose(\\Value ~ s; \\Result ~ e) \\defeq e : [s \\ne \\left\\lbrace \\right\\rbrace, e \\in s]}\n\t\\gcl{1}{}\n\t\\gcl{1}{\\Initially ~ u = \\left\\lbrace \\right\\rbrace}\n\t$ \\End $\n\t\\item Syntax\n\t\n\t\\begin{itemize}\n\t\t\n\t\t\\item Modules are declared with $ \\Module $ and have a unique name\n\t\t\n\t\t\\item Module-level variables are declared in the $ \\Var $ clause and given a type\n\t\t\n\t\t\\item The initial condition of module variables is given the predicate in the $ \\Initially $ clause\n\t\t\n\t\t\\item Modules may define procedures which make use of its variables\n\t\t\n\t\t\\item Modules list which procedures are exported publicly with an $ \\Export $ clause (if there is no $ \\Export $ clause, all procedures are exported)\n\t\t\n\t\t\\item The variables and procedures of another module may be used if they are included in the $ \\Import $ clause\n\t\t\n\t\t\\begin{itemize}\n\t\t\t\n\t\t\t\\item Imported variables must be redeclared exactly as in their source module\n\t\t\t\n\t\t\t\\item Imported procedures must be redeclared: the original declaration must refine the redeclaration\n\t\t\t\n\t\t\t\\item Imported procedures cannot refer to the local variables of the module they are imported into\n\t\t\t\n\t\t\t\\item Circular import/export is not well defined\n\t\t\t\n\t\t\\end{itemize}\n\t\t\n\t\\end{itemize}\n\t\n\\end{itemize}\n\n\\subsection{Module Refinement}\n\n\\begin{itemize}\n\t\n\t\\item A module $ M' $ refines some module $ M $ with exported procedures $ E $, imported procedures $ I $ and initialisation condition $ init $ when\n\t\n\t\\begin{itemize}\n\t\t\n\t\t\\item $ M' $ has the same local and imported variables as $ M $\n\t\t\n\t\t\\item The exported procedures $ E' $ refine those in $ E $ (there may be more procedures in $ E' $, but not fewer)\n\t\t\n\t\t\\item The imported procedures $ I' $ refine those in $ I $ (there may be fewer procedures in $ I' $ but not more)\n\t\t\n\t\t\\item The initialisation $ init' $ is stronger than $ init $ -- i.e. $ init' \\entails init $\n\t\t\n\t\\end{itemize}\n\t\n\t\\item To refine modules with different variables, data refinement is required\n\t\n\\end{itemize}\n\n\\newpage\n\n\\subsection{Data Refinement}\n\n\\begin{itemize}\n\t\n\t\\item The local state of a module cannot be accessed from the outside, so it may be changed provided the difference cannot be detected by use of the exported procedures\n\t\n\t\\item Rule 1: \\textbf{Introducing new variables}\n\t\n\t\\begin{itemize}\n\t\t\n\t\t\\item Relationships between new and existing variables are maintained via a \\textbf{coupling invariant} $ CI $\n\t\t\n\t\t\\begin{itemize}\n\t\t\t\n\t\t\t\\item E.g. $ CI \\defeq p = q + r $\n\t\t\t\n\t\t\\end{itemize}\n\t\t\n\t\t\\item The initialisation $ init $ becomes $ init \\land CI $\n\t\t\n\t\t\\begin{itemize}\n\t\t\t\n\t\t\t\\item E.g. if initialisation was $ p = 1 $, it would become $ p = 1 \\land p = q + r $\n\t\t\t\n\t\t\\end{itemize}\n\t\t\n\t\t\\item Any specification $ w : [P, Q] $ becomes $ w, c : [P \\land CI, Q \\land CI] $ where $ c $ is the list of new variables\n\t\t\n\t\t\\begin{itemize}\n\t\t\t\n\t\t\t\\item E.g. $ p : [p > 0, p < p_0]  $ becomes $ p, q, r : [p > 0 \\land p = q + r, p < p_0 \\land p = q + r] $\n\t\t\t\n\t\t\\end{itemize}\n\t\t\n\t\t\\item Every assignment in the module $ w := E $ becomes $ w, c := E, F $ provided that $ CI \\entails CI[w, c \\backslash E, F] $\n\t\t\n\t\t\\begin{itemize}\n\t\t\t\n\t\t\t\\item E.g. $ p := p + 1 $ becomes $ p, q := p + 1, q + 1 $, or alternately $ p, r := p + 1, r + 1 $\n\t\t\t\n\t\t\\end{itemize}\n\t\t\n\t\t\\item Every guard in the module $ G $ becomes $ G' $ provided that $ CI \\entails (G \\iff G') $\n\t\t\n\t\t\\begin{itemize}\n\t\t\t\n\t\t\t\\item $ G' \\defeq CI \\land G $ is always suitable\n\t\t\t\n\t\t\t\\item E.g. the guard $ p > 0 $ could become $ p > 0 \\land p = q + r $, or alternately $ p = q +r \\implies p > 0 $\n\t\t\t\n\t\t\\end{itemize}\n\t\t\n\t\\end{itemize}\n\t\n\t\\item Rule 2: \\textbf{Removing an existing variable}\n\t\n\t\\begin{itemize}\n\t\t\n\t\t\\item Only \\textbf{auxiliary variables} may be removed, i.e. they must only appear in:\n\t\t\n\t\t\\begin{itemize}\n\t\t\t\n\t\t\t\\item Assignments\n\t\t\t\n\t\t\t\\item Specifications which modify only auxiliary variables\n\t\t\t\n\t\t\\end{itemize}\n\t\n\t\t\\item The initialisation $ init $ becomes $ \\exists a \\cdot init $ where $ a $ is the auxiliary variable\n\t\t\n\t\t\\begin{itemize}\n\t\t\t\n\t\t\t\\item The `one-point rule' may be used to remove the existential quantifier: $ \\exists x \\cdot P \\land x = n \\equiv P[x \\backslash n] $\n\t\t\t\n\t\t\t\\item E.g. given initialisation $ p = 1 \\land p = q + r $, it would become $ \\exists p \\cdot p = 1 \\land p = q + r \\equiv q + r = 1 $\n\t\t\t\n\t\t\\end{itemize}\n\t\n\t\t\\item All specifications $ w, a : [P, Q] $ become $ w : [\\exists a \\cdot P, \\forall a_0 \\cdot P[w, a \\backslash w_0, a_0] \\implies (\\exists a \\cdot Q)] $\n\t\t\n\t\t\\begin{itemize}\n\t\t\t\n\t\t\t\\item A similar one-point rule may be used to remove the universal quantifier:\\\\\n\t\t\t$~~~~ \\forall x \\cdot P \\land x = n \\implies Q \\equiv P[x \\backslash n] \\implies Q[x \\backslash n] $\n\t\t\t\n\t\t\t\\item E.g. $ p, q, r : [p > 0 \\land p = q + r, p < p_0 \\land p = q + r] $ can be refined to:\\\\\n\t\t\t\\form{q, r : [\\exists p \\cdot p > 0 \\land p = q + r, \\forall p_0 \\cdot p_0 > 0 \\land p_0 = q_0 + r_0 \\implies (\\exists p \\cdot p < p_0 \\land p = q + r)]}\n\t\t\t\\hint{\\refsto}{Apply $ \\exists $ one-point rule to pre and postconditions}\n\t\t\t\\form{q, r : [q + r > 0, \\forall p_0 \\cdot p_0 > 0 \\land p_0 = q_0 + r_0 \\implies q + r < p_0]}\n\t\t\t\\hint{\\refsto}{Apply $ \\forall $ one-point rule to postcondition}\n\t\t\t\\form{q, r : [q + r > 0, q_0 + r_0 > 0 \\implies q + r < q_0 + r_0]}\n\t\t\t\n\t\t\\end{itemize}\n\t\n\t\t\\item Any assignment $ w, a := E, F $ where $ E $ contains no variables from $ a $ can be replaced by $ w := E $\n\t\t\n\t\t\\begin{itemize}\n\t\t\t\n\t\t\t\\item E.g. $ p, q := p + 1, q + 1 $ can be replaced by $ q := q + 1 $\n\t\t\t\n\t\t\\end{itemize}\n\t\t\n\t\t\\item Normally the coupling invariant $ CI $ relates each concrete state to a unique abstract state (e.g. $ p = q + r $), in which case the following rule applies:\n\t\t\n\t\t\\begin{itemize}\n\t\t\t\n\t\t\t\\item Given abstract variables $ a $ and concrete variables $ c $, if $ CI \\defeq a = f(c) \\land P(c) $ then a guard $ G $ may be replaced by $ G[a \\backslash f(c)] \\land P(c)$, or simply by $ G[a \\backslash f(c)] $\n\t\t\t\n\t\t\t\\item E.g. $ p > 0 \\land p = q + r $ can be replaced by $ q + r > 0 \\land q + r = q + r \\equiv q + r > 0 $\n\t\t\t\n\t\t\\end{itemize}\n\t\t\n\t\\end{itemize}\n\t\n\\end{itemize}", "meta": {"hexsha": "661ebb325211adcd3083fce537032e0085c57f01", "size": 6651, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "CSSE3100/modules.tex", "max_stars_repo_name": "mcoot/CourseNotes", "max_stars_repo_head_hexsha": "c643f46e32cdf4c567bf73d4a23784c834278803", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CSSE3100/modules.tex", "max_issues_repo_name": "mcoot/CourseNotes", "max_issues_repo_head_hexsha": "c643f46e32cdf4c567bf73d4a23784c834278803", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CSSE3100/modules.tex", "max_forks_repo_name": "mcoot/CourseNotes", "max_forks_repo_head_hexsha": "c643f46e32cdf4c567bf73d4a23784c834278803", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4611398964, "max_line_length": 218, "alphanum_fraction": 0.6248684408, "num_tokens": 2242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331319177488, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3467084229464548}}
{"text": "%auto-ignore\n\\providecommand{\\MainFolder}{..}\n\\documentclass[\\MainFolder/Text.tex]{subfiles}\n\\begin{document}\n\n\\section{Homological perturbation lemma}\n\n\n\\begin{Remark}[Origin of $\\BV$-formalism in physics]\nin $\\BRST$ we have clasical fields $x$ and ghosts $c$ (and Lagrange multiplier $\\lambda$ and $\\bar{c}$ for gauge fixing)\nin $\\BV$-formalism add anti-fields and anti-ghosts\n$$ \\int_{V_0} \\Vol(G) \\int_{V_0/G} f(v) e^{S_{\\BRST}}$$\nHaving $S$, they use the \nresolution of the integration\n$$(V_{\\BV}\\coloneqq T^*[-1]V_{\\BRST},) \\rightarrow (V_{\\BRST},\\int,Q,\\Action_{\\BRST} =)\\rightarrow (V_0,\\int,\\Action_0)$$\n-and $\\Action_0$ gets written as $\\Action_{\\BRST} = \\Action_0 +  Q(\\Psi)$, where $\\Psi$ is a $Q$-exact term depending on $\\lambda$, $\\bar{c}$ and $c$ (and Faddeev Poppov determinant and gauge fixing) called the gauge fixing fermion. Now, eventhough $\\int_{V_0} e^{\\Action_0}$ does not exist, $\\int_V e^{\\Action_{\\BRST}}$ exists and does not depend $\\Psi$. To remove the choice completely, one considers the $\\BV$-formalism on odd cotangent bundle $V_{\\BV} = T^*[1] V_{0}$ with the canonical odd symplectic form, where there is a well-defined notion of integration over a Lagrangian subspace $L \\subset V_{\\BV}$ which does not depend on $L$ if  the integrand is $\\BV$-closed. The choice of $\\Psi$ then corresponds to the choice of $L$. Having $V_0 = \\Harm \\oplus C$ of ``harmonic'' and the rest and. This amounts \n$$ Z:  $$\n$\\BRST$ extends the space of fields \n$$ $$\n$$ \\int_V f(v) e^{\\Action(v)} $$\n\\end{Remark}\n\n\nIn \\cite{Doubek2018}, they consider multilinear operations $l_{kg}: V^{\\otimes k} \\rightarrow \\R$ for $k\\ge 1$, $g\\ge 0$ on an odd symplectic vector space~$V$ and write down an action $\\Action\\in \\Fun(V)$ similar to \\eqref{Eq:MyAction} with~$\\MC_{kg}$ replaced with~$l_{kg}^+$. Notice that whereas they have $l^+_{kg}(v,\\dotsc,v)$ for a ``field'' $v\\in V$, we have $\\MC_{kg}(v_1,\\dotsc,v_k)$ for a ``string of fields'' $v_1\\dotsb v_k\\in \\CycB(V)$. They consider the Schwarz's canonical $\\BV$-operator on $\\Fun(V)$ and show that $\\Action$ satisfies the quantum master equation if and only if $(l_{kg})$ satisfy the relation of a quantum $\\LInfty$-algebra. This is equivalent to the notion of a loop homotopy algebra from \\cite{Markl1997} and to string brackets in closed string field theory from \\cite{Zwiebach1992}.\n\nIn order to transform \\eqref{Eq:QME} and \\eqref{Eq:Twist} to the convention of \\cite{Doubek2018}, we make the substitutions $\\BVOp \\mapsto \\BVOp$ and $S \\mapsto S = \\hbar S$.\n\n\nA deformation retract \\eqref{Eq:DefRetr} induces a deformation retract\n\\begin{equation*}\n\\begin{tikzcd}\n\\bigl(\\CycC(V),\\OPQ_{110}\\bigr) \\arrow[loop left]{l}{K_\\CycC}\\arrow[shift left]{r}{P_\\CycC} & \\arrow[shift left]{l}{I_\\CycC} \\bigl(\\CycC(V'),\\OPQ_{110}'\\bigr),\n\\end{tikzcd}\n\\end{equation*}\nwhich further induces a deformation retract\n\\begin{equation*}\n\\begin{tikzcd}\n\\bigl(\\Fun(B(V)),\\hat{\\OPQ}_{110}\\bigr) \\arrow[loop left]{l}{K}\\arrow[shift left]{r}{P} & \\arrow[shift left]{l}{I} \\bigl(\\Fun(B(V')),\\hat{\\OPQ}_{110}'\\bigr).\n\\end{tikzcd}\n\\end{equation*}\nWe can take $P$ and $P$, resp.~$I$ and $I$ to be the natural extensions of $\\iota^*$, resp.~$\\pi^*$. In~\\cite{Doubek2018}, they write down formulas for $K_F$ given $K$ using a tensor trick due to Eilenberg Mac-Lane (the same method may apply to get $K$ from $\\Htp$ too). Note that any surjective quasi-isomorphism over $\\R$ is a deformation retract.\\ToDo[caption={injectiv qi},noline]{Are injective quasi-isomorphisms sections of deformatino retractions?} They idea of \\cite{Doubek2018} would be to view $\\BVOp$ and $\\BVOp^\\MC$ as perturbations of $\\{\\FreeAction,\\cdot\\} = \\hat{\\OPQ}_{110}$ and apply the Homological Perturbation Lemma from \\cite{Crainic2004} to obtain deformation retracts\n\\begin{equation*}\\begin{tikzcd}[execute at end picture={\n\\draw[->,dashed] (3.5,1.5) to[out=0,in=90] node[midway,right,xshift=.5cm]{$\\delta^{(1)} = \\BVOp_0$} (5,.75) to[out=-90,in=0] (3.5,0);\n\\draw[->,dashed] (3.5,1.5) to[out=0,in=0] node[pos=0.8,right,xshift=.3cm]{$\\delta^{(2)} = \\BVOp_0 + \\{\\IntAction,\\cdot\\}$} (3.5,-1.5);\n}]\n\\bigl(\\Fun(B(V)),\\hat{\\OPQ}_{110}\\bigr) \\arrow[loop left]{l}{K}\\arrow[shift left]{r}{P} & \\arrow[shift left]{l}{I} \\bigl(\\Fun(B(V')),\\hat{\\OPQ}_{110}'\\bigr) \\\\\n\\bigl(\\Fun(B(V)),\\BVOp \\bigr) \\arrow[loop left]{l}{K^{(1)}}\\arrow[shift left]{r}{P^{(1)}} & \\arrow[shift left]{l}{I^{(1)}} \\bigl(\\Fun(B(V')),\\BVOp^{(1)}\\bigr)\\\\\n\\bigl(\\Fun(B(V)),\\BVOp^\\MC \\bigr) \\arrow[loop left]{l}{K^{(2)}}\\arrow[shift left]{r}{P^{(2)}} & \\arrow[shift left]{l}{I^{(2)}} \\bigl(\\Fun(B(V')),\\BVOp^{(2)}\\bigr)\n\\end{tikzcd}\\end{equation*}\nwhere\n\\begin{align*} \n \\BVOp^{(i)} &= \\hat{\\OPQ}_{110}' + P(\\Id - \\delta^{(i)}K)^{-1}\\delta^{(i)} I = \\hat{\\OPQ}_{110}' + P \\delta^{(i)} I + P \\delta^{(i)} K \\delta^{(i)} I + \\dotsb  \\\\\n I^{(i)} &= I + K(\\Id - \\delta^{(i)}K)^{-1}\\delta^{(i)} I = I + K \\delta^{(i)} I + K \\delta^{(i)} K \\delta^{(i)} I + \\dotsb \\\\\n P^{(i)} &= P + P(\\Id-\\delta^{(i)}K)^{-1}\\delta^{(i)} K = P + P \\delta^{(i)} K + P \\delta^{(i)} K \\delta^{(i)} K + \\dotsb\\\\\n K^{(i)} &= K + K(\\Id-\\delta^{(i)}K)^{-1}\\delta^{(i)}K = K + K\\delta^{(i)} K + K \\delta^{(i)} K \\delta^{(i)} K + \\dotsb\n\\end{align*}\nThe prerequisite for this is ``smallness'' of $\\delta^{(i)}$, i.e., that $(\\Id - \\delta^{(i)} K)$ is invertible, plus another condition which guarantees $P(A K^2 A + A K + K A)I = 0$ where $A= (\\Id - \\delta K)\\delta$. In the case of a special deformation retract, it holds automatically.\n\nIn the special case of being the deformation retract onto the Hodge decomposition \n\n$$ \\BVOp^{(1)} = P\\BVOp_0 I,\\quad \\BVOp^{(2)}=\\BVOp^{(1)} + \\{W,\\cdot\\}^{(1)}\\quad\\text{and}\\quad P^{(2)}_{\\Fun} = Z $$\n\nand define the \\emph{effective action} \n$$W \\coloneqq \\log\\bigl(P'(e^{\\IntAction})\\bigr) \\in \\Fun(\\CycB(V'))$$\nand the \\emph{path integral}\n$$P^{(2)}_{\\Fun} \\coloneqq L_{\\bigl(P'(e^{\\IntAction})\\bigr)^{-1}} \\circ P'_{\\Fun} \\circ L_{P'(e^{\\IntAction})}: \\Fun(\\CycB(V)) \\rightarrow \\Fun(\\CycB(V')).$$\n\n\n\\begin{Question}\nCan one choose the data and apply the Lemma to get\n$$ \\BVOp^{(1)} = \\BVOp_0', \\quad W = \\Action_{\\HTP_* \\MC},\\quad P^{(1)} = e^\\HTP,\\quad P^{(2)}= e^{\\HTP^\\MC} $$\n\\end{Question}\n\n\nThe article of \\cite{Doubek2018} contains references of other authors on how to get the path integral.\n\nThe Chern-Simons is \n\\end{document}\n", "meta": {"hexsha": "105ee311ab82c853d86811985eb8fb220c2a87f2", "size": 6312, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Subfiles/BV_deRham.tex", "max_stars_repo_name": "p135246/phd-thesis", "max_stars_repo_head_hexsha": "0e124466a3d0ff988c012225400fadb0b170aa9e", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Subfiles/BV_deRham.tex", "max_issues_repo_name": "p135246/phd-thesis", "max_issues_repo_head_hexsha": "0e124466a3d0ff988c012225400fadb0b170aa9e", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Subfiles/BV_deRham.tex", "max_forks_repo_name": "p135246/phd-thesis", "max_forks_repo_head_hexsha": "0e124466a3d0ff988c012225400fadb0b170aa9e", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 79.8987341772, "max_line_length": 815, "alphanum_fraction": 0.6498732573, "num_tokens": 2366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102956, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3466676208393454}}
{"text": "\n\\subsection{Symmetric}\n\nWe have a document we want to be able to transfer on an insecure medium.\n\nWe use a key to encrypt the file, and a key to decrypt the file.\n\nWith symmetric encryption these are the same key.\n\n", "meta": {"hexsha": "6e1b6d804f781818022f7ecb246f06e1de627b60", "size": 216, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/pug/theory/statistics/encryptionModern/02-01-symmetric.tex", "max_stars_repo_name": "adamdboult/nodeHomePage", "max_stars_repo_head_hexsha": "266bfc6865bb8f6b1530499dde3aa6206bb09b93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pug/theory/statistics/encryptionModern/02-01-symmetric.tex", "max_issues_repo_name": "adamdboult/nodeHomePage", "max_issues_repo_head_hexsha": "266bfc6865bb8f6b1530499dde3aa6206bb09b93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-03-03T12:36:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-01T22:16:09.000Z", "max_forks_repo_path": "src/pug/theory/statistics/encryptionModern/02-01-symmetric.tex", "max_forks_repo_name": "adamdboult/nodeHomePage", "max_forks_repo_head_hexsha": "266bfc6865bb8f6b1530499dde3aa6206bb09b93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.6, "max_line_length": 72, "alphanum_fraction": 0.7638888889, "num_tokens": 49, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.3466676072981253}}
{"text": "\\chapter{Physical Background }\n\\label{chapter:Introduction}\n\\textit{In this chapter raise and explains the basis of  fundamental physics in semiconductor and quantum structures, implemented  to understand the results in this work.}\n\\vfill\n\\minitoc\n\\newpage\n\n\\lettrine[lines=3, lraise=.1, nindent=0mm, slope=0mm]{\\textbf{Q}}{uantum mechanics}  is basically electron behavior that exhibits many phenomena non explained by classical regime. Quantum structures (QS) are artificially systems conformed by semiconductors where electrons exhibit their quantum nature, this is a great platform to study and create quantum devices. Nowadays, the progress in creation of QS consist in precisely deposition of thin films, in which electrons show fundamentally new electrical and optical properties\\cite{sundram1991structures}. Most of these properties consist in quantum behavior  as the energy confinement, which is the principal interest to study the electron and their consequent interactions which generates analogous  hydrogen atom in semiconductors. Therefore, the interest to studying QS was increasing for many years ago and nowadays, those continue considering an excellent research area.  \n\nIn this chapter, it presents the fundamental concepts to describe the physical  phenomena resultant in this work, without intention to replicate concepts and models already explained in publications with major impact. Therefore, the purpose is to present an own interpretation to highlight the great obtained results.\n\n\\section{Semiconductor Bandstructure}\n\\label{sec:chapter-1-semiconductor}\n\\vspace{-10mm}\nTo starting with physical background to understand the QS, it has to start with understand the  band structure of semiconductors. The band structure describes the electron behavior in a solid, therefore, we will need to invoke the \\sch equation to describe it behavior. But, due inside a solid around $10^{23}$ valence electrons contribute to the bonding in each cubic centimeter, this results in a many-body complex problem\\cite{piprek2017handbook}, then the general hamiltonian for a solid has the form\\cite{alloul2010introduction,cardona2005fundamentals}: \n\n\\begin{equation}\n\\begin{split}\n\tH  =  &\\dfrac{1}{2M}\\sum\\limits_{i=1}^{N_{n}} \\bff{P}_{j}^{2} + \\dfrac{1}{2m_{0}} \\sum\\limits_{j=1}^{N_{e}} \\bff{p}_{j}^{2} + \\dfrac{Z^{2}}{2} \\sum\\limits_{i,j=1,i\\neq j}^{N_{n}} V_{c}\\left(\\bff{R}_{i}-\\bff{R}_{j}\\right)-Z\\sum\\limits_{i=1}^{N_{n}}\\sum\\limits_{j=1}^{N_{e}}V_{c}\\left(\\bff{r}_{j}-\\bff{R}_{i}\\right) \\\\\n\t   & + \\dfrac{1}{2} \\sum\\limits_{i,j=1,i\\neq j}^{N_{e}} V_{c} \\left(\\bff{r}_{i}-\\bff{r}_{j}\\right).\n\\end{split}\n\\label{eq:chapter-1-solid-hamiltonian}\n\\end{equation}\n\nWhere  $N_{n}$ is the number of atomic nuclei, $N_{e}$ is the number of electrons with mass $m_{0}$, asumming that the nuclei are the same mass it's consider  $M$ and charge $Z_{e}$. As is obviously, this Hamiltonian is so complicated, the sum of five terms which consists in : kinetic enrgies to electrons and nuclei, the nucleus-nucleus, nucleus-electron and electron-electron Coulomb interactions, also $\\bff{R}_{i}$ are the positions of the nuclei and $\\bff{r}_{j}$ are the position of the electrons, the operators $\\bff{P}$ and $\\bff{p}$ are momentum operators to nuclei and electrons respectively.  Finally, the consider of  Coulomb potential $V_{c}$\\cite{alloul2010introduction}.  \n\n\nFortunately, the QS are formed by crystalline materials, the Bloch theorem provide the most important tool to develop required equations. The Bloch theorem establish a periodic potential $U(\\rv)$ for electrons, this due the material is periodic (definition of crystal structure) and the \\sch equation it can describe in terms of single electron  as:  \n\n\n\\begin{equation}\n\t\\left[-\\dfrac{\\hbar^2}{2m_{0}}\\nabla^2 + U(\\rv)\\right]\\psi (r)=\\senergy\\psi(\\rv)\n\t\\label{eq:chapter-1-first-sch}\n\\end{equation}\n\nThe principal reason that the periodic potential in a crystal structure is highly important is their translational invariance concept and the consequent symmetry operations that are possible in a crystalline solid. The symmetry concept, as a  tool to understand solids, is discussed with major detail in the next chapter. In according to Bloch's theorem we can associate a wave vector $\\boldsymbol{k}$ with each energy state, $E_{n}(\\boldsymbol{k})$. Thus, it is useful to display the energies $E_{n}(\\bf{k})$ as a function of the wave vector $\\boldsymbol{k}$. This result also knowing as dispersion relation, but in general terms is the electron band structure of the given solid\\cite{piprek2017handbook}.   \n\nEven if, the calculation of electron band structure in solids are very complex by the distance between atoms that composes it's, and the Bloch's theorem provide the most important tool to reduce the problem to crystalline structures, exists several methods to  calculate the realistic bandstructure for semiconductors that are categorized in two groups: Atomistic methods\\footnote{In this category can include the ab initio methods, these are the most complex methods due to propose  solutions of the many-body problem} (Tight-binding, orthogonalized plane wave methods) and Perturbative methods ($\\boldsymbol{k}\\bigcdot \\boldsymbol{p}$)\\footnote{In fact, both TB and $\\boldsymbol{k}\\bigcdot \\boldsymbol{p}$ also consider in same kind, because both are \\emph{semi-empirical} methods due to they consider experimental parameters.}. \nThese two main categories with theirs respective methods have special characteristics which becomes in the reasons to choose them. The reasons have to do with to the described bandstructure, this mean, in case of Atomistic methods the entire bands  (valence and conduction) can describe, but in case of perturbative methods are reserve to near bandedge bandstructures. So, each of these methods can be chosen and enhanced as the system to study requires. \nWe won't enter  in discussion about of which of these methods are the best, the reasons are simple, each method is powerful, and we must be remembered that the complexity of solutions requires that these are solved by numerical techniques therefore this convert it to good approximations. \nThen, basically the electron behavior inside a semiconductor consist in solutions of the appropriate Schrödinger equation\\cite{boer2018semiconductor}.  \n\\subsection{Valence and Conduction Bands}\n\\label{subsec:chapter-1-valence-and-conduction-bands}\n\\vspace{-10mm}\nThe most important characteristic of semiconductors even we can call as the fingerprint of these, is their bands structure, this characteristic sort out the solids as insulators, metals, and semiconductors. \nThese are the reason of many mechanisms and phenomena by which study this structures. In general,  the bands of semiconductors composed by valence and conduction bands separated by a  region known as bandgap. \nThe bandgap, which is proportional to separation energy of valence and conduction bands also is called as forbidden region, this is because doesn't exist electron states, therefore this gap energy determine the electron conduction in a semiconductor and the difference they have with the insulators and metals as shows \\Cref{fig:subsubsection-1.1.1-solid-types}.  \n\n\\begin{figure}[h!]\n\t\\centering\n\t\\includegraphics[width=\\linewidth]{../figures/chapter-1/solid-sort/build/solid-sort}\n\t\\caption{Band energy diagram for insulators (left), semiconductors(center) and metals (right). The principal difference is the gap energy, for insulators this is longer than semiconductors, although in semiconductors gap energy depends on materials, finally in metals doesn't exist gap energy instead exist an overlap bands characterize these. Dashed line determine Fermi's level.  }\n\t\\label{fig:subsubsection-1.1.1-solid-types}\n\\end{figure}\n\nSo, the bandgap determines many characterizes and functionalities in semiconductors. The bandgap energy classifies semiconductors in direct and indirect semiconductors, but doesn't only depend on this energy, in reality the band structure is the liable for this. As before mentioned, it is so difficult to describe electrons behaviors over the solids due to the many body interactions that exists in its, and therefore the Scr\\\"odinger equation that's describe electrons behaviors is complicatedly to solve.  Fortunately, the semiconductor structures have a one of the most important characterize  and his has to do with their atomic structure,  that's periodically arrangement of atoms.\nThis periodicity is the key to propose solutions and describe the semiconductor band structure. \nStarting with describe bulk semiconductors, for example GaAs which consists in with the family III-V cube semiconductor so that their lattice structure consist in a two sublattices correspond to each atom which it conform as shows in \\Cref{fig:subsubsection-1.1.1-bulk-1}. For this case, when the atoms in two sublattice are diferent, the crystal structure is then called \\emph{zinc-blende}\\cite{vurgaftman2020bands}.\n\nTo calculate bandstructures of bulk semiconductors it's important to define specific symmetry direction, this mean that it's not possible to plot dispersion relation. For each three-dimensional wave vector $\\boldsymbol{k}$, then the plot energy as a function of $\\boldsymbol{k}$ is along of different high-symmetry directions\\cite{piprek2017handbook}.  \nIn this work the structures to study are composed of semiconductors III-V, being GaAs the bulk in each structure.  GaAs is a direct semiconductor so that the $\\left[001\\right]$ direction is the high-symetry direction then is denoted by $\\Gamma$ point (at $\\boldsymbol{k}=0$)\n\\begin{figure}[h!]\n\t\\centering\n\t\\includegraphics[width=\\linewidth]{../figures/chapter-1/bulk-1/build/bulk-1}\n\t\\caption{\n\t\t GaAs crystal lattice, where the each sublattice correspond of each atom species Ga and As. }\n\t\\label{fig:subsubsection-1.1.1-bulk-1}\n\\end{figure}\n\n\nAs before mentioned several times, it's very complex to compute the Schrödinger equation in the solids. The most ``exact'' compute is employed by DFT theory,  these calculations commonly are called atomistic even some  semiempirical models can consider as atomistic, but the semiemprical models are good approximations in comparison with the DFT theory. So, which is the reason to call ``exact'' solutions to the DFT results? The answer leads us to great discussion and  it's not intended to get into controversy,  but in general the DFT calculations have the capacity to calculate in terms of electrons interaction and the empirical methods are based in potential choice.\\\\\n \nWe will, don't into details about band calculations theories and models, but we will make a general reference to the importance in this work. The models more performed in semiconductor heterostructures as GaAs/AlGaAs are semiempirical, this is because DFT theory and their derived models are very limited to carried out in large structures, their electron interaction nature need high computational perform. So that in comparison with empirical models where the main role is the potential of semiconductor structures, this reduces computational reduce. So, the most models used in semiconductor band calculations are empirical models, these models are distinguished by low computational requires for this reason are considered like approximations. The importance to discuss these concepts will take relevance when we discuss the physics model proposed in this work. \n\n\\begin{figure}[h!]\\label{fig:subsubsection-1.1.1-GaAsbands-1}\n\t\\centering\n\t\\begin{subfigure}{\\textwidth}\n\t\\includegraphics[width=\\linewidth]{../figures/chapter-1/bands/build/bands01}\n\t\\phantomsubcaption\\label{subfig:subsubsection-1.1.1-GaAsbands-1-a)}\n\t\\phantomsubcaption\\label{subfig:subsubsection-1.1.1-GaAsbands-1-b)}\n\\end{subfigure}\n\t\\caption{Band structure of GaAs, \\subref{subfig:subsubsection-1.1.1-GaAsbands-1-a)} hows the zoom around of $\\Gamma$  to denote the direct band gap and the electrons energy  needed to jump from valence to conduction band. \\subref{subfig:subsubsection-1.1.1-GaAsbands-1-b)} denotes the two directions to dispersion of the bands corresponds to Brillouin zone: $\\Gamma\\to\\mathrm{X}$ and  $\\Gamma\\to\\mathrm{L}$.\\cite{fox2002optical}}\n\\end{figure}\n\nThe \\Cref{fig:subsubsection-1.1.1-GaAsbands-1} shows the results of calculations of TB model as discus it in \\cite{vogl1983asemiempirical} and the code was impmemented by R. Muller \\cite{rpmuller2017}. The model purposes by Vogl et al.  take into account small number of localized pseudo-orbitals and based the empirical parameters to substituted on TB Hamiltonian. \nThe importance to get bandstructure it's based  importance to study optical properties of solid structures, if it doesn't exist  band electrons it's like look a place without map, so, the band structure  far from being  a complex tool it's the key to get the information to investigate the optical properties. \n\nAs shown in \\Cref{subfig:subsubsection-1.1.1-GaAsbands-1-a)} the GaAs bandstructure shows that it's a direct semiconductor as a previously mentioned, this gives way to get electron transitions from VB to CB and the energy to success this it. In \\Cref{subfig:subsubsection-1.1.1-GaAsbands-1-b)} it's plotted, the band dispertion around $\\Gamma$ point, it's the most symmetry point.  It is well-known that the band dispersion increasing $\\boldsymbol{k}$ along two different directions of the Brillouin zone, from $\\boldsymbol{k}=(0,0,0)$ to X point $\\boldsymbol{k}=(2\\pi a_{L})(1,0,0)$ and L point $\\boldsymbol{k}=(2\\pi a_{L})(1,1,1)$.  So, these figures, are the typical representation of direct gap to III-V semiconductors around of  $\\boldsymbol{k}=0$, then, is obviously that the shape of dispersion is parabolic. For the GaAs bandstructure calculations shown in \\Cref{fig:subsubsection-1.1.1-GaAsbands-1} doesn't take into account the contribution of spin\\footnote{This spin contribution as called as split-off (so) hole band.}, therefore it's focus on three bands dispersion correspond to a single $s$-like conduction band and two $p$-like valence bands.  Is important to say that the characteristic curvature $E\\!\\!-\\!\\!\\boldsymbol{k}$ of dispersion bands corresponds to an electron ($e$) in case of positive curvature while the negative curvature correspond to holes states; heavy ($hh$) and light hole ($lh$) bands, so, this denotes that the transitions, are of dipole nature\\cite{fox2002optical,cardona2005fundamentals}. \n\\begin{figure}[h!]\n\t\\centering\n\t\t\\includegraphics[width=0.5\\linewidth]{../figures/chapter-1/bands/build/bands02}\n\t\\caption{Two typical transitions for GaAs near $\\boldsymbol{k}=0$. The first one correspond to the heavy-hole and second one to the light-hole. }\n\t\\label{fig:subsubsection-1.1.1-GaAsbands-2}\n\\end{figure}\nAll the above disputed is significant to refers of one of the most indispensable quantum mechanisms in solids, this is absorption. The electron absorption, specifically interband absorption, give way to a fundamental physical process that involves the principle of many basic studies of semiconductors, applications, and the importance to understand the electron behavior in a semiconductor structures disputed in this work. Then the \\Cref{fig:subsubsection-1.1.1-GaAsbands-2} schematizes the two typical transitions in GaAs bulk, this transitions are near to k=0, so that is called interband absorption. Is important to remark that the interband transitions are observed in all solids, but the mechanisms are different dependently of their bandstructure, for what,  being repetitive when mentioning that the bandstructure is the key to study solids. \n\nIn case of GaAs the interband tranisitions are called as direct transitions, this is because their bandstructure proofs GaAs is a direct Gap semiconductor.  This process is determined by quantum mechanical rate $W_{i\\to f}$ for exciting and electron in a initial quantum state $\\psi_{i}$ to final state $\\psi_{f}$ by absorption of a photon of angular frequency $\\omega$\\cite{fox2002optical}. As is very know, this is given by Fermi's golden rule. Later this is disputed according to highlight the model and results obtained. It has been mentioned that the direct transitions are of dipole nature, as before mentioned the CB is type $s$-like while the VB is $p$-like, then it've electric-dipole allowed transitions $p\\to s$. The excitation of electron in CB carries to leave an initial state unoccupied, this is called as a hole creation, then the electron in the final state and the hole is considered as \\textbf{electron-hole pair}. The next part subject this theme with major focus.\n\n\n\\subsection{Excitons}\n\\label{subsec:chapter-1-excitons}\n\\vspace{-10mm}\nThe importance to study bandstrcuture of semiconductors is very clear so far, so that could be said that absorption process is the source of optical properties of solids. It's due to this that the importance to study of semiconductors in the optoelectronics applications. But, this process give rise to formation of one of the most important excitations in the crystal structures. The photon absorption process carries to an electron is excited from CB to VB, this  generates an empty location in VB which has positive charge. This positive empty location called as hole, therefore the electron and hole have opposite charge then it's  to be expected that they are attracted, so, this creates a bound state called an exciton\\cite{leonard2017exciton}. \n\nFrom \\Cref{fig:subsubsection-1.1.1-GaAsbands-2} and \\Cref{fig:subsubsection-1.1.1-x-1}  is clearly that excitons are commonly presented in direct band gap semiconductors as GaAs, this was denoted by absorption experiments,  after mentioned in \\Cref{subsec:chapter-3-pl} this is the cause in photoluminiscence mechanism.\n\n\\begin{figure}[b]\n\t\\centering\n\t\\includegraphics[width=0.5\\linewidth]{../figures/chapter-1/exciton-1/build/x-1}\n\t\\caption{Qualitative scheme of exciton creation in GaAs as direct gap.}\n\t\\label{fig:subsubsection-1.1.1-x-1}\n\\end{figure}\n\n\\section{Semiconductor Low-Dimensional Structures}\n\\label{sec:chapter-1-low-dimensional-structures}\n\\vspace{-10mm} \nThe previous section engaged to explain the principles of semiconductors, this is the bandstructure, the importance of these is practically the fingerprint of all semiconductor, without bandstructure  the understanding of these would be improbable. The first approximations were based in  GaAs bulk, their cubic symmetry practically defines their nature and consequently the physical effects as excitons existence.  But, what happens  if joined several semiconductors with same symmetry and structural parameters? The bulk properties and physical properties are the same?. \nThe answers they are well-known, when two materials with relatively same structural parameters, as lattice constant can create a heterojunction, the union of several heterojunction make up a heterostructure.\\footnote{The samples studied in this work are heterostructures, for this reason, and by nomenclature it's we refer to that way.}\\\\*\n\\begin{figure}[h]\n\t\\centering\n\t\\includegraphics[width=0.65\\textwidth]{../figures/chapter-1/heterostructures/out/hs-01}\n\t\\caption{General scheme of GaAs/\\algaas heterostructure, at top show the scheme of atomic arranged of this heterjunction, the dashed lines are the matched between two dissimilar materials. In bottom shows the band-edge profile.}\n\t\\label{fig:subsection-1.2-heterostructure}\n\\end{figure}\nThe \\Cref{fig:subsection-1.2-heterostructure} is a general scheme of a heterostructure, in this case is presents three species of atoms Al, As, Ga. These atoms can   locate in columns III-V of the periodic table, hence its name of III-V semiconductors. The principal characteristic of these atoms is that it can create matched structures as GaAs, AlAs and ternary alloys as \\algaas with specific Al concentration. The matched semiconductors produce a material with new properties based principally in the difference of bandgap which involves the alloys. \\\\* \nAs can see in \\Cref{fig:subsection-1.2-heterostructure} it's consisting a GaAs/\\algaas heterostructure, these interface is well-matched due to the lattice parameters is relatively equals, therefore and thanks to powerful growth technics as MBE it's possible to get high-quality quantum structures. \n\nAlso, the heterostructure composed by two semiconductors with different band gaps generate a discontinuity in either the conduction or the valence band can be represented by a constant potential term\\cite{harrison2016quantum}.  The theory to treatment the electron behavior in these structures, is relatively simple if we consider the above. \nAlthough, in this chapter doesn't have intention to explore the theory of electron behavior in that, worth noting that  it get one-dimensional potential $V(z)$ to both bands, so the Schr\\\"odinger equation can solve simple. \n\n\n\n\\subsection{Quantum wells}\n\\label{subsection:chapter-1-quantum-wells}\n\\vspace{-10mm} \nDoubtless the creation or growth of heterostructures increased the interest in the study of quantum structures, the interactions, and physical behavior of light-matter they would not have been possible without these.  The major relevance is due the quantum confinement, the junction of semiconductors results in an interest quantum structures with specific dimensions. From 3D bulk the dimensions reduce to 2D,1D and 0D dimensional structures. Therefore each of that has interest properties and their correspond applications. The \\Cref{fig:subsection-1.2-heterostructures} schematics the low dimensional heterostructures from 3D bulk, the first low dimensional from 3D to 2D  is the Quantum Wells, then from 2D to 1D it have the Quantum Wires finally with 0D have the Quantum Dots.\n\\begin{figure}\n\t\\centering\n\t\\includegraphics[width=0.6\\textwidth]{../figures/chapter-1/heterostructures/out/lds-00}\n\t\\caption{Heterostructures from bulk (3D), to Quantum Wells (2D), Quantum Wires (1D) and Quantum Dots (0D).  }\n\t\\label{fig:subsection-1.2-heterostructures}\n\\end{figure}\nThe quantum confinement so is the principal reason to study that structures, the electron behavior which exhibits in it  should  can to help  understand  a great variety of quantum mechanical phenomena as electron interaction on a crystal. \nSuppose a heterostructure composed with a two semiconductor alloys as sandwich, this 2D quantum structure is called a Single Quantum Well (SQW). \\\\*\nThis dissimilar semiconductors in terms of their potential energy ($V(z)$) can be schematized as \\Cref{fig:subsection-1.2-single-quantum-well-scheme}. The Gap difference of \\algaas and GaAs is due to $x$ Al concentration in \\algaas therefore it obtains a one dimensional potential profile, with that can confinement electrons in a 2D plane along $z$ direction. \nAll of these carries to quantum mechanics formalism, the electron behavior should be obeyed these rules. If we have an electron closed in two potential barriers  an $L$ distance, the wave which describe it will be spatially confined.\nSo if we confined many electrons in these potential,  we have two important physical aspects: the first one is knowing as Pauli's exclusion principle, which as of its Fermion nature prevents carriers with the same spin occupying the same region in of space\\cite{harrison2016quantum,pauli1925zusammenhang}, the second one and one of the most relevant in the birth of the quantum mechanics; the Heisenberg's uncertainty principle. \nThat last, it can say  that is the consequence of quantum confinement due to the space reduction of the electrons is expected that momentum increases by an amount of the order $\\hbar/L$. Therefore, the energy of that confined particles increases, and it's referred to as confinement energy\\cite{cardona2005fundamentals}. \\\\*\n\\begin{figure}\n\t\\centering\n\t\\includegraphics[width=0.65\\textwidth]{../figures/chapter-1/heterostructures/out/qw1}\n\t\\caption{GaAs/\\algaas Single Quantum Well }\n\t\\label{fig:subsection-1.2-single-quantum-well-scheme}\n\\end{figure}\nThen the quantum confinement is our started point to understand the optical properties in QWs. As is referred in the figure, the uni-dimensional potential profile can well describe by top conduction- and bottom valence-bands, the band offset in these two of correspond gap energy between that, while Al concentration increases their bandgap and the band offset ($\\mathrm{Q_{c}}$ to CB and $\\mathrm{Q_{v}}$ to VB) also to.   \n\nIt's so clearly  that the QWs have the potential to presents amazing quantum properties, even if all of these are very important we focus on the optical properties, basically our interest is the light-matter interaction through its result mechanisms.  \n \n\\subsection{Preliminary approach of Quantum Confinement effect in QWs}\n\\label{subsection:chapter-1-preliminary-approach-of-quantum-confinment-effect-in-qws}\n\\vspace{-10mm} \nAs the title describes, here it will try to explain as the first  approach the quantum confinement effect in QWs. If  it starts with the  scoop, which it can be reduced the electrons space, then this mean that in reciprocal space it has two components $k_{x}$ and $k_{y}$. Then say in crystal symmetry properties to the case of GaAs/\\algaas QWs it's $\\Gamma$ the central point, as long as $x < 0.4$\\footnote{It will be explained in the next section, although it's due to the Gap go from direct to indirect, shortly the symmetry $\\Gamma\\to X$.} the bandstructure depends on confinement energ, so say which the bandstructure depends on confinement energy.  \nIn this case, the electronic properties in comparison with a bulk semiconductor properties can solve trough particle-in-a-box as textbook problem as first approach. Nevertheless, even if usually can solver without much mathematical formalism is very essential that it dedicates a chapter with their solution, this is because will employ a physical formalism exclusively to QWs structures. In general way, as it before mentioned the Schrödinger equation solution is the fundamental pillar to understand, where it's taken into account which  in a crystal the periodic potential is the key. Here are important remarks before to continue, when it has a heterostructure starting with the bulk model it's clearly that the system doesn't same, the Quantum Mechanics which is behind take into account the symmetry properties, then it can be developed a Hamiltonian  to understand that system.  In the next chapter will be explained details and the formalism both physical and mathematical to solve and discus it's. The model which give the tools to get the solutions is called as Effective Mass Approximation, thus their correspond Schrödinger equation is\\cite{harrison2016quantum,chuang1995physics,singh2003electronic,bastard1990wave,fox2002optical,davies1998physics}: \n\\begin{equation}\\label{eq:chapter-1-ema-schroedinger}\n\t-\\dfrac{\\hbar^{2}}{2m^{*}}\\dfrac{\\partial^{2}}{\\partial {z}^{2}}\\psi(z)+V(z)\\psi(z)=E\\psi(z),\n\\end{equation}\n\nwhere the $m^{*}$ is the effective mass in each material, and $V(z)$ is the potential profile got by heterostructure materials properties. Therefore, that differential equation can solve as in textbooks explained\\cite{de2014introduccion,griffiths2018introduction,sakurai1995modern,cohen2019quantum,chuang1995physics,harrison2016quantum,fox2002optical,bastard1990wave}. The idea is thinking as a one particle in a finite potential well, where is well important established the boundary conditions and solve the Schrödinger equation in each part of single QW, this means that need to create a potential function. Then it's can obtain the Eigenfunctions and their correspond Eigenenergies.\n\n\\begin{figure}\n\t\\begin{subfigure}{\\textwidth}\n\t\t\\centering\n\t\t\\includegraphics[width=0.65\\textwidth]{../figures/chapter-1/heterostructures/out/qw2}\n\t\t\\phantomsubcaption\\label{subfig:subsection-1.2-single-quantum-well-scheme2-a)}\n\t\t\\phantomsubcaption\\label{subfig:subsection-1.2-single-quantum-well-scheme2-b)}\n\t\\end{subfigure}\n\t\\caption{General scheme of typical Schrödinger's equation solutions to one-dimensional potential as \\subref{subfig:subsection-1.2-single-quantum-well-scheme2-a)} where the Eigenenergies of both electron and holes are denoted with same color depending on  $n$ value.\\subref{subfig:subsection-1.2-single-quantum-well-scheme2-b)} It's plot, of the subbands in  the same case of  \\subref{subfig:subsection-1.2-single-quantum-well-scheme2-a)} to both particles.  }\n\t\\label{fig:subsection-1.2-single-quantum-well-scheme2}\n\\end{figure}\n\nThe principal idea doesn't is reproducing something which is very well known, the objective of this part is established the scoop of the next chapter. Therefore,  before to continue, we will finish with to explain the dispersion in-plane of single QW. As in the QW the one-dimensional potential set up the 1D confinement, is important doesn't confuse which the QW is a 2D structure, but their confinement is along of $z$ direction  this mean 1D. Then, the particle can motion in the $x-y$ plane. By this reason, even if consider 3D Schrödinger equation and  the above is considered it obtain \\Cref{eq:chapter-1-ema-schroedinger}\ntherefore, the solutions in the one-dimensional potential produce discrete states of energy $E_{z}=E_{n}$\\cite{harrison2016quantum}, where $n$ is the energy level it which produce  subbands as shows in \\Cref{fig:subsection-1.2-single-quantum-well-scheme2}. In contrast, before it called as ``energy bands'' in the bulk case, now due to the quantum confinement gets subbands to both conduction- and valence bands.\n\nThese subbands are the result of the sum of $E_{z}$ and $E_{x,y}$, which are the 1D confinement energy and the in-plane momentum $k_{x,y}$ then\\cite{harrison2016quantum}:\n\\begin{equation}\\label{eqn:chapter-1-total-enery-ema-aprox}\t\t\n\tE = E_{n} + \\dfrac{\\hbar^{2}|\\boldsymbol{k}_{x,y}|^{2}}{2m^{*}}.\n\\end{equation}  \nFrom equation the effective mass  $m^*$ depends on particle, i.e the effective mass to electrons in CB and the holes in VB. So, the most relevant in the solutions is the energy $E_{n}$ (\\Cref{subfig:subsection-1.2-single-quantum-well-scheme2-a)})  is discrete, this is the quantum confinement in the low-dimensional heterostructures. \n\n\n\\section{Summary}\n\\vspace{-10mm} \nIn this chapter, was exposed the generalities of semiconductor band structure and low-dimensional heterostructures, highlighting or taking in major GaAs/\\algaas that's the semiconductors of major importance in this work. \nThe band structure interpretation  usually be so hard, and their calculations even more, but the impact and relevance in optical properties of semiconductors starts from that interpretation, from here arises the mathematical arsenal to right physical interpretation. Another significant concept which was treatment as first approach is the effective mass concept, even if, when solved, the bulk Hamiltonian it considers the mass as constant parameter or depending on semiconductor material, contrary  in low-dimensional structures have an important role.  \\\\*\n\nIn generally, the band structure of semiconductors is the key to understand quantum properties of solids, in this work the  relevant is the light-matter. Remember that light-mater interaction in solids can be studied by process resulting in it, as absorption, reflection, transmission, diffraction, scattering, and others\\cite{rivera2020light}.  Although, the light-matter interactions are fundamentally  quantum electrodynamical, also, can be studied in quantum way through before mentioned process. Firstly, is the photon absorption process can help to understand or calculate the fundamental parameter in semiconductors as is bandgap energy. \nThis parameter is the started point in the study of semiconductors, this is the start point in the map called bandstructure, if it ignores the gap value in the semiconductor to study it couldn't possibly get the principal optical properties of that. \\\\*\nThen, the bandstructure of semiconductors is the map to understand them, without these routes or fundamental parameters couldn't have quantum devices. \n \n", "meta": {"hexsha": "f3ed8950f34fe78d10b9938bcee85464f409f0f9", "size": 31980, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "phd-thesis/files/chapter-1-introduction.tex", "max_stars_repo_name": "lflmgroup/ruco-phd-project", "max_stars_repo_head_hexsha": "b26156508d1aff06825360470608abf8559b3388", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "phd-thesis/files/chapter-1-introduction.tex", "max_issues_repo_name": "lflmgroup/ruco-phd-project", "max_issues_repo_head_hexsha": "b26156508d1aff06825360470608abf8559b3388", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phd-thesis/files/chapter-1-introduction.tex", "max_forks_repo_name": "lflmgroup/ruco-phd-project", "max_forks_repo_head_hexsha": "b26156508d1aff06825360470608abf8559b3388", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 159.9, "max_line_length": 1529, "alphanum_fraction": 0.7967166979, "num_tokens": 7749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3466676072981252}}
{"text": "\\documentclass{article}\n\n\\title{FreeCat design document}\n\\author{Morgan Thomas}\n\n\\usepackage{amsmath}\n\\usepackage{amsfonts}\n\\usepackage{amssymb}\n\n\\begin{document}\n\n\\maketitle\n\nProgramming languages can usually be classified as typed or untyped. Untyped languages are usually relatively simple and flexible, but less capable of automatically finding errors in programs. Typed languages are usually more capable of automatically finding errors in programs, but this usually comes at the expense of flexibility and expressive capability. Expressive capability of typed languages can be increased, but this usually comes at the expense of increasing their complexity.\n\nFreeCat is a programming language, a system of logic and computer algebra, and an approach to type theory and the foundations of math. It aims to chart a new programming language design path, where the guiding hope is that we can have automatic error finding, language simplicity, flexibility, and expressive capability, all at the same time, all to a degree which is robust and state of the art. FreeCat is based on the hypothesis that we can do this by following a language design approach based on type theory, when we do not try to rule out logical inconsistency in the core type theory.\n\nBy definition, a system is logically inconsistent when it can prove that some statement is both true and false. In the case of type theory based programming languages such as FreeCat, this definition depends on the Curry-Howard correspondence, under which types are considered as statements, and values are considered as proofs of the statements which are their types. The statement that FreeCat is logically inconsistent means in other words that in FreeCat, for any type it is possible to construct a value inhabiting that type.\n\nProgramming languages to which FreeCat is similar include Haskell, PureScript, ML, Agda, Coq, Cayenne, and Idris. FreeCat follows a novel variant of a well-established type theory based approach to programming language design.\n\nWhat's novel (as far as I'm aware) about FreeCat is that it accepts the possibility of logical inconsistency, and it incorporates the assumption that logical inconsistency will be possible, starting from the design of the core type theory. In contrast, similar languages I'm aware of have mechanisms for ruling out inconsistency incorporated into the core type theory, even in cases where the final language is inconsistent. The motivation for designing FreeCat in this way is the hope that the resulting language will be significantly simpler and easier to understand, compared to alternatives, while also being more flexible and expressive.\n\nThis document describes FreeCat from a theoretical perspective. There are two main target audiences. First, programming language theorists who want to understand FreeCat's theoretical contributions. Second, people who want to understand the implementation of FreeCat, for example in order to contribute to it.\n\nFreeCat is an open source, non-profit project whose primary aim is to give people a new way to develop software. The hope is that FreeCat will help people reduce their costs for developing software, while achieving higher quality.\n\nA further, related aim of this project is to describe a new approach to understanding the foundations of math. The hope is that people will find this approach simpler, conceptually clearer, and capable of expressing more concepts, compared to alternatives. The capability to express more concepts comes from not imposing restrictions designed to prevent logical inconsistency. This approach is limited in scope to constructive math, and more specifically it is limited to countably infinite objects and (partial) computable functions. These limitations can probably be removed if one gives up the goal of being able to implement the system as a computer programming language.\n\nFreeCat doesn't aim to be the best approach to solving everybody's problem. For now the focus is on making it a good approach to solving some problems.\n\nThe current implementation of FreeCat can be considered the reference implementation in progress. This implementation provides the most complete definition and explanation of FreeCat. This implementation doesn't focus on performance optimization. The plan is to keep the reference implementation as simple as possible, optimizing for ease of human comprehension. Once the reference implementation is mature, it would provide a good basis for writing a performance-optimizing implementation.\n\nThe conception and justification of FreeCat is rooted in a holistic, interdisciplinary approach to technical analysis. This holistic methodology assumes that there are deep connections between fundamental problems in different technical disciplines. It assumes in essence that we can clarify our thinking about technical problems in general by developing theories which can systematize solutions to technical problems in general.\n\nThis design document aims to give a self-contained conceptual explanation of FreeCat. The Context section is not self-contained. The other sections should explain FreeCat in a self-contained way which does not require understanding of the Context section. It's hard to state exact prerequisites for reading this document, but practically necessary prerequisites include some familiarity with functional programming and programming language theory concepts.\n\nPrior experience in any of the following areas is helpful, but not necessarily required, for understanding this document: type theory, foundations of math, mathematical logic, philosophical logic, category theory, abstract/universal algebra, holistic analysis.\n\n\\section{Context}\n\nThis section gestures at some of the areas of thought which are closely related to FreeCat. The main aim is to give an idea of where FreeCat's intellectual DNA comes from. For people familiar with these fields, hopefully it will help to contextualize FreeCat. None of this section is necessary for understanding FreeCat. It aims to provide perspectives which are useful for understanding FreeCat and its motivations.\n\nTODO: sprinkle some citations\n\n\\subsection{Symbolic computation}\n\nSymbolic computation is one conceptual paradigm from which FreeCat is derived. A prototypical example of a symbolic computation system is Lisp. In Lisp, the most fundamental data structures are symbols and conses. These two simple data structures suffice for basic untyped symbolic computation. Typed symbolic computation languages include ML, Haskell, PureScript, and so forth. In these languages the notion of algebraic data types replaces the notions of symbols and conses.\n\nFreeCat is another typed symbolic computation language. The basic and only data structure is the (symbolic) expression. The simplest types of expressions are symbols and function applications. Constructors are functions with no reduction rules. Instead of algebraic data types, users are given the ability to declare symbols to have arbitrary types. They can use this feature to declare types, values belonging to types, and constructors.\n\n\\subsection{Type theory and set theory}\n\nType theory is a field of math and a way of describing the foundations of math. Type theory is closely related to set theory. Set theory is the study of sets. Sets are collections of objects: e.g., the set of all even integers, the set of all unicorns, the set of all sets.\n\nType theory is basically a theoretical approach to studying sets, which can be distinguished from classical set theory. Classical set theory, as exemplified by ZFC, was originally motivated in essence by the desire to provide theoretical foundations for math. Type theory today is most interesting for its applications to technology. Many computer programming languages and software verification systems are based closely on type theory. Examples include Haskell, ML, Coq, Agda, and Idris. The demonstrated applicability of type theory to technology distinguishes it from classical set theory. The reason for the distinction is that type theory has been formulated in such a way that computers can feasibly process it.\n\nThere are other interesting differences between type theory and classical set theory. In classical set theory, every object is an element of infinitely many sets, whereas in many versions of type theory (FreeCat included), every object is an element of at most one set (i.e. type).\n\nAlso, classical set theory includes the principle of extensionality, which states that if two sets have exactly the same elements, then they are the same set. Type theory frequently does not include the principle of extensionality. In most computer implementations of type theory, the principle of extensionality is not included, or it's trivially true because no two distinct sets have any elements in common.\n\nHere is a further important difference between type theory and classical set theory. Classical set theory is based on classical logic, most often first-order logic. The classical approach to logic and set theory defines logical rules of inference, such as those of first-order logic, and axioms about sets, such as those of ZFC. When combined they let you do math, once you've defined every mathematical concept in terms of sets. Type theory, on the other hand, simply defines rules for talking about types, and the rules of logic can be derived from these rules via the Curry-Howard isomorphism. Whereas classical set theory is founded on logic, type theory stands alone and can be used as a foundation for logic.\n\nIn short, type theory is a way of thinking about sets, which can form the basis of computer programming languages, which often relaxes or trivializes the principle of extensionality, and which unifies logic with set theory via the Curry-Howard isomorphism.\n\n\\subsection{Constructive math}\n\nConstructive math is a style of math in which one restricts one's attention to mathematical objects which can be constructed in some suitable sense. For example, if you are doing math which only pertains to a finite number of things which could fit in the universe, then in a robust sense the math you are doing is constructive.\n\nIntuitionism is a subfield or paradigm of constructive math. Speaking generally and simplistically, intuitionists think that math properly concerns objects which can be constructed mentally. Intuitionists think that if an object exists for the purposes of math, then we can mentally construct (conceptualize, visualize) the object to any desired degree of detail. Whether you agree or disagree with intuitionists, their idea of mental construction of mathematical objects provides an accessible way of thinking about constructive math.\n\nConstructive math does not necessarily restrict its attention to finite objects only. There are a wide variety of ways of understanding the notion of constructive math, and the widest variety is in the ways of understanding constructive math which assume that constructive math can study infinite things.\n\nThe varieties of type theory which are most relevant to technology are constructive type theories. What it means for a type theory to be constructive is a subtle question to which many answers are possible. For purposes of intuition, I lean on the intuitionist notion of mental construction. Constructive type theory, I'll say, is only concerned with objects which can be mentally constructed to any desired degree of detail, as well as realized in computer implementations. Roughly, constructive type theory (conceived this way) can talk about finite objects, countably infinite types, and infinite objects which can be described by means of (partial) computable functions. For example, constructive type theory can talk about the type of integers, and the type of (partial computable) functions from integers to integers.\n\nThe real numbers are an example of something constructive type theory can't talk about. There are uncountably many real numbers. If you had a computer with infinite memory and infinite computation time, such a computer could not represent and do arithmetic on all real numbers. That statement assumes the hypothetical infinite computer is built in something resembling a conventional manner: something like an infinitely large circuit board whose circuits are of uniform density. Actual computers have only finite memory and computation time. Uncountably infinite sets like the real numbers are far beyond what actual computers can fathom. Therefore they are beyond the realm of constructive type theory as I'm conceiving it.\n\n\\subsection{Inconsistent math}\n\nFreeCat is a system of inconsistent math. ``Inconsistent math'' refers to any style of math where contradictions can be true, or in other words where the same statement can be both true and false. Inconsistent math is a fairly obscure and unpopular subfield of math, which I believe is mostly studied and practiced by philosophers.\n\nInconsistent math is unpopular probably in large part because most people assume that it is absurd and impossible for any statement (or at least any statement of math) to be provably both true and false. FreeCat starts by rejecting that assumption, following other scholars including C.E. Mortensen, Mark Colyvan, Zach Weber, Graham Priest, Jc Beall, and David Ripley, to name a few.\n\n\\subsection{Functional programming}\n\nFreeCat is a functional programming language. Functional programming is a way of thinking about software engineering. It is a very broad topic which today has increasing importance to practical software engineers.\n\nFunctional programming languages can be classified as pure or impure. In pure functional languages, there is no notion of mutable state in the semantics of the core language. Pure functional languages ask the programmer to think about a world in which there is no change. Impure functional languages lack this property.\n\nFunctional programming languages can be classified as typed or untyped, depending on whether or not they have a type system as part of the semantics of the core language.\n\nFreeCat is a pure typed functional programming language. This puts it in the same class as programming languages including Agda, Cayenne, Coq, Haskell, Idris, and PureScript.\n\nAll of these languages are based on type theory. Type theory provides the underlying mathematical theories which are used to construct the languages mentioned in the previous paragraph. As far as I understand, in every case mentioned, the underlying type theories are constructive. This makes sense because constructive type theories can talk about what computers can talk about, whereas non-constructive type theories more or less by definition (depending on your definition) can talk about some things which computers can't talk about.\n\nMost of the type theory literature is concerned with logically consistent type theories. A logically consistent type theory is one in which it is not possible to prove that the same statement is both true and false. To prove a statement is in other words to construct an inhabitant of the type which is the statement under the Curry-Howard correspondence.\n\nPractical typed functional programming languages tend to be logically inconsistent. This means that in these languages it's possible to prove any statement, or in other words (under the Curry-Howard correspondence), for any type it's possible to construct a value inhabiting it. Haskell, Idris, PureScript, Agda, and Coq all have this property, either by the nature of the type system (as with Haskell), or by importing a module (as with PureScript), or in the case where you make assumptions which are logically inconsistent (as with Agda and Coq).\n\nThere are some good reasons to make a practical programming language inconsistent or potentially inconsistent. For example, a language is potentially inconsistent if you are able to tell the implementation to assume that something is true when you haven't proven it. One important reason to want this capability is to be able to compile a program which is missing a proof you don't yet understand how to construct or don't have time to construct.\n\nAnother reason to allow a programming language to be inconsistent is that the restrictions which type theorists impose to avoid logical inconsistency tend to prevent some ideas from being expressed.\n\nThere is an interesting disconnect here. Type theorists usually study consistent type theories. Designers of practical typed functional programming languages tend to construct inconsistent languages, and there seem to be some good reasons for that. Yet language designers who rely on type theory have tended to base their work on consistent type theories, even when the languages they design are inconsistent in the end. Arguably this leads to a worst of both worlds situation, where you have restrictions on what you can express which are intended to prevent inconsistency, but you also have the potential of inconsistency.\n\nFreeCat is based on the approach of rethinking type theory from the beginning with the assumption that it's not necessary to take steps to prevent the possibility of inconsistency. Of course it will be useful to have tools to try to discover inconsistency, or to rule out inconsistency in cases where this is practical and desirable. But FreeCat's core type theory doesn't contain restrictions designed to prevent paradoxes. This simplifies the core type theory and language design, and the hypothesis is that this will lead to substantial additional simplifications further down the road.\n\nThe previous statements locate FreeCat in the space of conceptual paradigms discussed so far. FreeCat is a pure typed functional programming language and an approach to the foundations of math. It is founded on a form of inconsistent constructive type theory.\n\n\\subsection{Category theory}\n\nCategory theory is a field of math with close connections to logic, type theory, and the foundations of math, among many other fields. Category theory is a valuable tool for interdisciplinary/holistic technical analysis. Category theory provides a useful perspective on the core concepts of FreeCat. FreeCat, in turn, provides a useful perspective on the core concepts of category theory.\n\nFreeCat has the core concepts of types and functions, which correspond to category theory's notions of objects and morphisms. All FreeCat constructions can be considered to occur in a category of all FreeCat types, within which it is possible to construct an infinite variety of categories.\n\nFrom this perspective, FreeCat defines a form of inconsistent constructive category theory. This form of category theory abandons the usual paradox-avoiding restrictions of category theory, with the consequence that categories such as the category of all categories and the category of all groups can be discussed.\n\n\\subsection{Abstract/universal algebra}\n\nAbstract algebra is a field of math which (basically) studies mathematical objects considered as sets of abstract objects with operations defined on them, with the sets and operations usually required to satisfy axioms.\n\nUniversal algebra is a field of math which tries to generalize the patterns of abstract algebra in the form of general theories of algebras and concepts which help in studying algebras.\n\nFreeCat is conceptually connected to abstract algebra and universal algebra. FreeCat provides a system for defining sets (types) and operations (functions) on them. FreeCat can be viewed as a general system for constructing algebras. As such, FreeCat provides a way of thinking about abstract/universal algebra, while abstract/universal algebra provides a way of thinking about FreeCat.\n\n\\section{Basic Concepts}\n\nThe most basic concept in FreeCat is the concept of an object. Everything FreeCat can talk about is an object. ``Object'' is the root node of FreeCat's conceptual taxonomy.\n\nTypes are a fundamental class of object. Every object is an instance of some type. There is a type called Type. Every type is an instance of Type. In particular, Type is an instance of itself.\n\nObjects in FreeCat are represented by expressions. For all practical purposes, in FreeCat, objects can be equated with expressions.\n\nFunctions are a fundamental class of object. A function maps objects of some type to objects of other types. The type of a function's output can be dependent on the object it receives as input. In other words, FreeCat is a dependently typed language.\n\nFunctions are defined by pattern matching equations. These equations express rules stating that expressions of given shapes can be replaced by other, dependent expressions. A function can have different equations defined for it in different contexts. A lambda expression can be thought of as having exactly one pattern matching equation.\n\nA constructor is a function which has no pattern matching equations defined. Whether a function is a constructor or not can be dependent on the context.\n\nFreeCat expressions are evaluated following the rule of eager evaluation, where subexpressions of an expression are completely evaluated, left to right, before performing any evaluation step on the outermost expression. Pattern matching definitions are tried in the order they were declared, with the first match being used.\n\nEvery expression has a type, which is intrinsic to it. The type is itself an expression, whose type is Type. The type of an expression of a specific form will depend on the context in which the expression originally occurs. A symbol name, such as ``foo'' or ``Type,'' may denote different symbols in different contexts. As such, syntactically identical expressions may be semantically different expressions.\n\nThere is a function digestExpr of type $\\text{Context} \\to \\text{RawExpr} \\to \\text{FreeCat Expr}$. (Here FreeCat denotes the FreeCat monad, which accounts for error handling and other issues.) A RawExpr or raw expression is the syntax of an expression without any contextual semantic interpretation applied to it. Given a context and a raw expression, digestExpr gives you an expression which is the interpretation of that raw expression in that context (or else it throws an error, etc.) This function, digestExpr, describes the one-to-many, context-dependent correspondence between syntactic or raw expressions, and semantic expressions, i.e. expressions.\n\nThere are the following kinds of expressions: symbols, applications, lambdas, and (dependent and non-dependent) function types.\n\nA context can be represented as a sequence of declarations. There are the following kinds of declarations: type declarations and equation declarations.\n\nType declarations assert that a given symbol has a given type. Whenever you have an expression denoting a type, you can declare a symbol to have that type, as long as you haven't previously declared a type for that symbol in the current context.\n\nEquation declarations, also called pattern matching definitions or reduction rules, assert that during evaluation, expressions following the left hand side pattern should be replaced by the right hand side expression. As usual, the right hand expression may be dependent on variables in the left hand pattern.\n\nPatterns are like expressions, but they're restricted to consist of symbols and applications. The first symbol in the pattern is called the lead symbol. An equation declaration's left hand pattern must have a lead symbol whose type has been declared previously.\n\n\\section{Syntax}\n\nTODO\n\n\\section{Semantics}\n\nSemantics is the study of meaning. Whereas the syntax of FreeCat tells you what FreeCat expressions and declarations look like, the semantics of FreeCat tells you how to interpret FreeCat expressions and declarations. Specifically, it gives you a computer-implementable theory of how to interpret FreeCat expressions and declarations.\n\nThis section gives a high level overview of the semantics of FreeCat. For a complete definition of the semantics of FreeCat, see the code, and in particular the file src/FreeCat/Core.hs.\n\nA context in FreeCat is represented by a sequence of declarations: type declarations and equation declarations.\n\nThere are basically two aspects to the semantics of FreeCat: the semantics of contexts, and the semantics of expressions. The semantics of contexts tells you how to interpret a representation of a context (i.e., a series of declarations). The semantics of expressions tells you how to interpret an expression relative to a context.\n\nThe semantics of contexts is basically characterized by a function digestContext of type $\\text{RawContext} \\to \\text{FreeCat Context}$. Here RawContext is the type of uninterpreted, syntactic sequences of declarations. Context is the type of contexts, and FreeCat is the FreeCat monad, which deals with error conditions and other things.\n\nThe semantics of expressions is basically characterized by two functions: digestExpr and evaluate.\n\ndigestExpr has type $\\text{Context} \\to \\text{RawExpr} \\to \\text{FreeCat Expr}$. It takes as input a context and an uninterpreted syntactic expression, i.e. a RawExpr. It produces as output an interpreted semantic expression, i.e. an Expr (or it throws an error, etc.)\n\nevaluate has type $\\text{Context} \\to \\text{Expr} \\to \\text{FreeCat Expr}$. It takes as input a context and an expression, and produces as output an expression. The output expression is produced from the input expression by repeatedly reducing all reducible subexpressions, in depth first left to right order, so that in the end there are no reducible subexpressions. A reducible subexpression is either a function application whose head (i.e., left-hand subexpression) is a lambda expression, or a function application matching the left hand pattern of some equation declaration in the current context.\n\nLet's now unpack the types Context and Expr and related types. Both of these types involve the type Symbol, which we'll look at first.\n\nA Symbol basically consists of the following data: its name (a string), its type (an Expr), its native context (the Context in which it first appeared), and its equations (a list of Equation objects representing equation declarations). Symbols are considered to be the same symbol when they have the same name and native context. However, different occurrences in different contexts of the same symbol may have different equations.\n\nAn Equation is of the form $a_1 : t_1, ..., a_n : t_n. p \\Rightarrow d$, where $a_1,...,a_n$ are symbols, $t_1,...,t_n$ are Expr of type Type, $p$ is a Pattern, and $d$ is an Expr. Each Equation is associated with a Context, called its evaluation context.\n\nTODO\n\n\\end{document}\n", "meta": {"hexsha": "f5bb6eb705ad631c29ed99fc22e1175aab08225b", "size": 26617, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/design-doc/design-doc.tex", "max_stars_repo_name": "morganthomas/freecat", "max_stars_repo_head_hexsha": "a608a22e44f01cb61db73adfd5aa96d26b8c51e6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-12-02T20:17:29.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-02T20:17:29.000Z", "max_issues_repo_path": "doc/design-doc/design-doc.tex", "max_issues_repo_name": "morganthomas/freecat", "max_issues_repo_head_hexsha": "a608a22e44f01cb61db73adfd5aa96d26b8c51e6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 37, "max_issues_repo_issues_event_min_datetime": "2017-12-02T18:10:06.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-24T17:34:46.000Z", "max_forks_repo_path": "doc/design-doc/design-doc.tex", "max_forks_repo_name": "morganthomas/freecat", "max_forks_repo_head_hexsha": "a608a22e44f01cb61db73adfd5aa96d26b8c51e6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 142.3368983957, "max_line_length": 823, "alphanum_fraction": 0.8167336665, "num_tokens": 5067, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.34663581577017116}}
{"text": "\\newcommand{\\TOMNetTrimap}{TOM-Net$^{\\text{+Trimap}}$\\xspace}\n\\newcommand{\\TOMNetBg}{TOM-Net$^{\\text{+Bg}}$\\xspace}\n\\chapter{Learning Transparent Object Matting}\n\\label{ch:tomnet}\n\n\\section{Introduction}\nImage matting refers to the process of extracting the foreground matte of an image by locating the region of the foreground object and estimating the opacity of each pixel inside the foreground region. The foreground object can then be composited onto a new background image using the \\emph{matting equation}~\\cite{smith1996blue} \n\\begin{equation}\n    \\label{eq:alphamatte}\n    C = F + (1-\\alpha)B,  \\quad \\alpha \\in [0, 1],\n\\end{equation}\nwhere $C$ denotes the composited color, $F$ the foreground color, $B$ the background color, and $\\alpha$ the opacity.\n\nImage matting has been widely used in image editing and film production. However, most of the existing methods are tailored for opaque objects, and cannot handle transparent objects whose appearance depends on how light is refracted from the background.\n\nTo model the effect of refraction, Zongker~\\etal~\\cite{zongker1999environment} introduced \\emph{environment matting} as \n\\begin{equation}\n    \\label{eq:em_general}\n    C = F + (1-\\alpha)B + \\Phi, \\quad \\alpha \\in [0, 1],\n\\end{equation}\nwhere $\\Phi$ is the contribution of environment light caused by refraction or reflection at the foreground object. Besides estimating the foreground shape, environment matting also describes how objects interact with the background. \n\n\\begin{figure}[t] \\centering\n    \\includegraphics[width=\\textwidth]{ch-tomnet/images/Method/Intro_network_intro_v3}\n    \\caption[Learning transparent object matting]{Learning transparent object matting. Given an image of a transparent object as input, our model can estimate the environment matte (consisting of an object mask, an attenuation mask, and a refractive flow field) in a feed-forward pass. The transparent object can then be composited onto new background images with the extracted matte.}\n    \\label{fig:intro}\n\\end{figure}\n\nMany efforts~\\cite{chuang2000environment,wexler2002image,peers2003wavelet,zhu2004frequency,duan2011flexible,duan2015compressive} have been devoted to improving the seminal work of~\\cite{zongker1999environment}. The resulting methods often require either a huge number of input images to achieve a higher accuracy, or the use of specially designed patterns to reduce the number of required images. They are in general all very computational expensive.\n\nIn this work, we focus on environment matting for transparent objects. It is highly ill-posed, if not impossible, to estimate an accurate environment matte for transparent objects from a single image with an arbitrary background. Given the huge solution space, there exist multiple objects and backgrounds which can produce the same refractive effect. In order to make the problem more tractable, we simplify our problem to estimating an environment matte that can produce visually realistic refractive effect from a single image, instead of estimating a highly accurate refractive flow. We define the environment matte in our model as a triplet consisting of an object mask, an attenuation mask, and a refractive flow field. Realistic refractive effect can then be obtained by compositing the transparent object onto new background images (see \\fref{fig:intro}). We then show that the performance of the proposed method can be improved when a trimap or a background image is available.\n\nInspired by the great successes of convolutional neural networks (CNNs) in high-level computer vision tasks, we propose a convolutional neural network, called TOM-Net, for simultaneous learning of an object mask, an attenuation mask, and a refractive flow field from a single image with an arbitrary background. The key contributions of this work can be summarized as follows:\n\n\\begin{itemize}\n  \\item We introduce a simple and efficient model for transparent object matting as simultaneous estimation of an object mask, an attenuation mask, and a refractive flow field.\n  \\item We propose a convolutional neural network, TOM-Net, to learn an environment matte of a transparent object from a single image. To the best of our knowledge, TOM-Net is the first CNN that is capable of learning transparent object matting.\n  \\item We create a large-scale synthetic dataset and a real dataset as a benchmark for learning transparent object matting. Our TOM-Net has produced promising results on both the synthetic and real datasets.\n  \\item We propose two additional convolutional neural networks, denoted as \\TOMNetTrimap and \\TOMNetBg, for handling the cases where a trimap or a background image is available, respectively.\n\\end{itemize}  \n\nPreliminary results of this chapter were published in~\\cite{chen2018tomnet,chen2019learning}.\nOur code, trained models, and datasets can be found at \\url{https://guanyingc.github.io/TOM-Net}.\n\n\\section{Related Work}\n\\label{sec:related_work}\nIn this section, we briefly review representative works on environment matting and recent works on CNN based image matting. \n\n\\paragraph{Environment matting}\n\\label{par:Environment Matting}\nZongker~\\etal~\\cite{zongker1999environment} introduced the concept of environment matting, and assumed each foreground pixel being originated from a single rectangular region of the background. They obtained the environment matte by identifying the corresponding background region for each foreground pixel using three monitors and multiple images. Chuang~\\etal~\\cite{chuang2000environment} extended~\\cite{zongker1999environment} in two different ways. First, they replaced the single rectangular supporting area for a foreground pixel with multiple 2D oriented Gaussian strips. This makes it possible for their method to model the effects of color dispersion, multiple mapping, and glossy reflection. Second, they simplified the environment matting equation by assuming the object being colorless and perfectly transparent. This allows them to achieve real time capture environment matting (RTCEM). The environment matte was then extracted with one image taken in front of a pre-designed pattern. However, RTCEM requires background images to segment the transparent objects, and depends on a time-consuming off-line processing. \n\nWexler~\\etal~\\cite{wexler2002image} introduced a probabilistic model based method which assumes each background point has a probability to make contribution towards the color of a certain foreground point. Their approach does not require pre-designed patterns during data acquisition, but it still needs multiple images and can only model thin transparent objects. Peers and Dutr{\\'e}~\\cite{peers2003wavelet} used a large number of wavelet basis backgrounds to obtain the environment matte, and their method can also model the effect of diffuse reflection. Based on the fact that a signal can be decomposed uniquely in the frequency domain, Zhu and Yang~\\cite{zhu2004frequency} proposed a frequency-based approach to extract an accurate environment matte. They used Fourier analysis to solve the decomposition problem. Both~\\cite{peers2003wavelet} and~\\cite{zhu2004frequency} require a large number of images to extract the matte (\\eg,~\\cite{peers2003wavelet} needs $2,400$ images and~\\cite{zhu2004frequency} needs $4,096$ images for an image of size $1024\\times 1024$), making them not very practical. Recently, compressive sensing theory has been applied to environment matting to reduce the number of images required. Duan~\\etal~\\cite{duan2011fast} applied this theory in  the spatial domain and Qian~\\etal~\\cite{qian2015frequency} applied it in the frequency domain. However, the number of images needed is still in the order of hundreds. In contrast, our work can estimate an environment matte from a single image in a fast feed-forward computation without the need for pre-designed patterns or additional background images.\n\n\\begin{sidewaystable}[htbp]\n    \\caption[Comparison of different environment matting methods]{Comparison of different environment matting methods. $k$ indicates the image size and mapping type stands for how a foreground point is composited by the point(s) in the background image.}\n    \\label{tab:related_work}\n    \\input{ch-tomnet/tables/comparisons}\n\\end{sidewaystable}\n\nYeung~\\etal~\\cite{yeung2011matting} proposed an interactive way to estimate an environment matte given an image containing a transparent object. Their method requires users to manually mark the foreground and background in the image, and models the refractive effect using a thin-plate-spline transformation. Their method does not produce an accurate environment matte, but instead a visually pleasing refractive effect. Our method shares the same spirit, but does not involve any human interaction. \n\n\\Tref{tab:related_work} shows a comparison of different environment matting methods. Compared with other methods, our method requires only a single image and can extract a matte in $0.5$ second without the need for any predefined backgrounds.\n\n\\paragraph{CNN based image matting}\nAlthough the potential of CNN on transparent object matting has not yet been explored, some existing work have adopted CNNs for solving the traditional image matting problem. Shen~\\etal~\\cite{shen2016deep} introduced a CNN for image matting of color portrait images. Cho~\\etal~\\cite{cho2016natural} proposed a network to predict a better alpha matte by taking the matting results of the traditional method and normalized color images as input. \nSome deep learning methods~\\cite{xu2017deep,zhang2019late,lu2019indices} have been introduced to estimate an alpha matte given an image and its trimap. \nHowever, none of these methods can be applied directly to the task of transparent object matting as object opacity alone is not sufficient to model the refractive effect. \n\n\\section{Matting Formulation}\n\\label{sec:formulation}\nAs a transparent object may have multiple optical properties (\\eg, color attenuation, translucency, and reflection), estimating an accurate environment matte for a generic transparent object from a single image is very challenging. \nFollowing the work of~\\cite{chuang2000environment}, we cast environment matting to a refractive flow estimation problem by assuming that each foreground pixel only originates from one point in the background due to refraction. Compared to the seminal work of~\\cite{zongker1999environment}, which models each foreground pixel as a linear combination of a patch in the background, our formulation is more tractable and can be easily encoded using a CNN.\n\nIn~\\cite{zongker1999environment}, the per-pixel environment matting is obtained through leveraging color information from multiple background images. Given a set of pre-designed background patterns, matting is formulated as\n\\begin{equation}\n    \\label{eq:em_origin}\n    C = F + (1-\\alpha)B + \\sum_{i=1}^{k} R_i \\mathcal{M}(\\mathbf{T}_i, \\mathbf{A}_i),\n\\end{equation}\nwhere $F$, $B$ and $\\alpha$ denote the ambient illumination, background color and opacity, respectively. The last term in \\eref{eq:em_origin} accounts for the environment light accumulated from $k$ pre-designed background images ($k=3$ in~\\cite{zongker1999environment}). $R_i$ is a factor describing the contribution of light emanating from the $i$-$th$ background image $\\mathbf{T}_i$. $\\mathcal{M}(\\mathbf{T}_i, \\mathbf{A}_i)$ denotes the average color of a rectangular region $\\mathbf{A}_i$ on the background image $\\mathbf{T}_i$. \n\nTo obtain an environment matte, the transparent object is placed in front of the monitor(s), and multiple pictures of the object are captured with the monitor(s) displaying different background patterns\\footnote{For an image of size $512\\times 512$, $18$ pictures and around $20$ minutes processing time are needed.}. \nGenerally, a surface point receives light from multiple directions, especially for a diffuse surface. When it comes to a perfectly transparent object, however, a surface point will only receive light from one direction as determined by the law of refraction. Consider a single background image as the only light source (\\ie, no ambient illumination), the problem can be modeled as\n\\begin{equation}\n    \\label{eq:em_simplify1}\n    C = (1-\\alpha)B + R \\mathcal{M}(\\mathbf{T}, P),\n\\end{equation}\nwhere $\\mathcal{M}(\\mathbf{T}, P)$ is a bilinear sampling operation at location $P$ on the background image $\\mathbf{T}$. Further, by assuming a colorless transparent object, $R$ becomes a  light attenuation index $\\rho$ (a scalar value). The formulation in \\eref{eq:em_simplify1} can be simplified to\n\\begin{equation}\n    \\label{eq:em_simplify2}\n    C = (1-\\alpha)B + \\rho \\mathcal{M}(\\mathbf{T}, P),\n\\end{equation}\nwhere $\\rho \\in [0, 1]$ denotes the attenuation index.\n\nHere, we use refractive flow to model the refractive effect of a transparent object. The refractive flow of a foreground pixel is defined as the offset between the foreground pixel and its refraction correspondence on the background image. \n\nWe further introduce a binary foreground mask to define the object region in the image. The matting equation can now be rewritten as\n\\begin{equation}\n    \\label{eq:em_simplify3}\n    C = (1 - m) B + m\\rho \\mathcal{M}(\\mathbf{T}, P),\n\\end{equation}\nwhere $m \\in\\{0, 1\\}$ denotes background ($m = 0$) or foreground ($m = 1$). The matte can then be estimated by solving $m$, $\\rho$ and $P$ for each pixel in the input image containing the transparent \nobject\\footnote{For an image with $n$ pixel, we have $7$ unknowns ($3$ for $B$, $2$ for $P$, $1$ for $m$, and $1$ for $\\rho$) for each pixel, resulting in a total of $7n$ unknowns.}.\n\n\n\\section{Learning Transparent Object Matting}\n\\label{sec:method}\nIn this section, we present a two-stage deep learning framework, called TOM-Net, for learning transparent object matting (see \\fref{fig:networkStructure}). The first stage, denoted as CoarseNet, is a multi-scale encoder-decoder network that takes a single image as input, and predicts an object mask, an attenuation mask, and a refractive flow field simultaneously. CoarseNet is capable of predicting a robust object mask. However, the estimated attenuation mask and refractive flow field lack local structural details. \nTo overcome this problem, we introduce the second stage of TOM-Net, denoted as RefineNet, to achieve a sharper attenuation mask and a more detailed refractive flow field. RefineNet is a residual network~\\cite{he2016deep} that takes both the input image and the output of CoarseNet as input. After training, our TOM-Net can predict an environment matte from a single image in a fast feed-forward pass.\n\n\\begin{figure}[tbp] \\centering\n    \\includegraphics[width=\\textwidth]{ch-tomnet/images/Method/TOMNet_framework.pdf}\n    \\caption[Network architecture of TOM-Net]{Network architecture of TOM-Net. The upper subnetwork is the CoarseNet and the bottom subnetwork is the RefineNet. (Cross-link and multi-scale outputs are not shown for simplicity.)} \\label{fig:networkStructure}\n\\end{figure}\n\n\\subsection{Encoder-Decoder for Coarse Prediction}\n\\label{sub:Encoder-decoder Net for Coarse Prediction}\nThe first stage of our TOM-Net (\\ie, CoarseNet) is based on mirror-link CNN introduced in~\\cite{shi2016learning}. Mirror-link CNN was proposed to learn non-Lambertian object intrinsic decomposition. Its output consists of an albedo map, a shading map, and a specular map. It shares a similar output structure with our transparent object matting task (\\ie, three output branches sharing the same spatial dimensionality). Therefore, it is reasonable for us to adapt mirror-link CNN for our CoarseNet. \n\nThe mirror-link CNN adapted for our CoarseNet consists of one shared encoder and three distinct decoders. The encoder contains six down-sampling convolutional blocks, leading to a down-sampling factor of $64$ in the bottleneck layer. Features in the encoder layers are connected to the decoder layers having the same spatial dimensions through skip connections~\\cite{ronneberger2015u}. Cross-links~\\cite{shi2016learning} are introduced to make different decoders share the same input in each layer, so that decoders can better utilize the correlation between different predictions.\n\nLearning with multi-scale loss has been proven to be helpful in dense prediction tasks (\\eg,~\\cite{eigen2014depth,fischer2015flownet}). Since we formulate the problem of transparent object matting as refractive flow estimation, which is a dense prediction task, we augment our mirror-link CNN with multi-scale loss similar to~\\cite{fischer2015flownet}. \nWe use four different scales in our model, where the first scale starts from the decoder features with a down-sampling factor of $8$ and the largest scale has the same spatial dimensions as the input.\n\nIn contrast to the recent two-stage framework for image matting~\\cite{xu2017deep}, our TOM-Net has a shared encoder and three parallel decoders to accommodate different outputs. Besides, we augment our CoarseNet with multi-scale loss and cross-link. Moreover, TOM-Net is trained from scratch while the encoder in~\\cite{xu2017deep} is initialized with the pre-trained VGG16.\n\n\\newcommand{\\mathL}{\\mathcal{L}}\n\\subsection{Loss Function for Coarse Stage}\n\\label{sub:Loss Function for CoarseNet}\nCoarseNet takes a single image as input and predicts the environment matte as a triplet consisting of an object mask, an attenuation mask, and a refractive flow field. The learning of CoarseNet is supervised by the ground-truth matte using an object \\textbf{m}ask \\textbf{s}egmentation loss $\\mathL_{ms}$, an \\textbf{a}ttenuation \\textbf{r}egression loss $\\mathL_{ar}$, and a refractive \\textbf{f}low \\textbf{r}egression loss $\\mathL_{fr}$. Besides, the predicted matte is expected to render an image as close to the input image as possible when applied to the ground-truth background based on \\eref{eq:em_simplify3}. Hence, in addition to the supervision of the matte, we also take \\textbf{i}mage \\textbf{r}econstruction loss $\\mathL_{ir}$ into account (bilinear sampling is implemented following~\\cite{jaderberg2015spatial}). Note that the ground-truth background is only used to calculate the reconstruction error during training but not needed during testing. CoarseNet can therefore be trained by minimizing \n\\begin{align}\n    \\mathL^c = \\alpha^c_{ms} \\mathL_{ms} + \\alpha^c_{ar} \\mathL_{ar} + \\alpha^c_{fr} \\mathL_{fr} + \\alpha^c_{ir} \\mathL_{ir},\n\\end{align}\nwhere \n$\\alpha^c_{ms}, \\alpha^c_{ar}, \\alpha^c_{fr}, \\alpha^c_{ir}$ are weights for the corresponding loss terms. \n\n\\paragraph{Object mask segmentation loss}\n\\label{par:Object Mask Classification Loss}\nObject mask segmentation is simply a spatial binary classification problem. The output of the object mask decoder has a dimension of $2\\times H\\times W$, where $H$ and $W$ denote the height and width of the input. We normalize the output with {\\em softmax} and compute the loss using the binary cross-entropy function\n\\begin{equation}\n    \\mathL_{ms} = -\\frac{1}{HW} \\sum_{ij} (\\tilde{M}_{ij}\\log(P_{ij}) + (1-\\tilde{M}_{ij}) \\log(1-P_{ij})),\n\\end{equation}\nwhere $\\tilde{M}_{ij} \\in \\{0,1\\}$ and $P_{ij}\\in [0,1]$ represent ground truth and normalized foreground probability of the pixel at $(i, j)$, respectively.\n\n\\paragraph{Attenuation regression loss} \nThe predicted attenuation mask has a dimension of  $1\\times H\\times W$. The value of this mask is in the range of $[0, 1]$, where $0$ indicates no light can pass and $1$ indicates the light will not be attenuated. \nWe adopt a mean square error (MSE) loss\n\\begin{equation}\n    \\mathL_{ar} = \\frac{1}{HW} \\sum_{ij} (A_{ij}-\\tilde{A}_{ij})^2,\n\\end{equation}\nwhere $A_{ij}$ is the predicted attenuation index and $\\tilde{A}_{ij}$ the ground truth at $(i, j)$.\n\\paragraph{Refractive flow regression loss}\n\\label{par:Disparity Smoothness Loss}\nThe predicted refractive flow field has a dimension of $2\\times H\\times W$, where we have one channel for the horizontal displacement and another for the vertical displacement. We normalize the refractive flow with $tanh$ activation and multiply it by the width of the input, such that the output is constrained in the range of $[-W, W]$.\nWe adopt an average end-point error (EPE) loss\n\\begin{equation}\n    \\mathL_{fr} = \\frac{1}{HW} \\sum_{ij} \\sqrt{(F^x_{ij}-\\tilde{F}^x_{ij})^2 + (F^y_{ij}-\\tilde{F}^y_{ij})^2},\n\\end{equation}\nwhere $(F^x, F^y)$ and $(\\tilde{F}^x, \\tilde{F}^y)$ denote the predicted flow and the ground truth, respectively.\n\n\\paragraph{Image reconstruction loss}\n\\label{par:Image Reconstruction Loss}\nWe use MSE loss to measure the dissimilarity between the reconstructed image and the input image. \nDenoting the reconstructed image by $I$ and the ground-truth image (\\ie, the input image) by $\\tilde{I}$, the reconstruction loss is given by\n\\begin{equation}\n    \\mathL_{ir} = \\frac{1}{HW} \\sum_{ij} \\Vert I_{ij}-\\tilde{I}_{ij}\\Vert_2^2.\n\\end{equation}\n\n\\paragraph{Implementation details}\n\\label{par:Implementation Details}\nIn all experiments, we empirically set $\\alpha^c_{ms}=0.1, \\alpha^c_{ar}=1, \\alpha^c_{fr}=0.01,$ and $\\alpha^c_{ir}=1$. The loss weights for different scales are $\\frac{1}{2^{(4 -\\text{s})}}$, where $s \\in\\{1,2,3,4\\}$ denotes the scale. %\nCoarseNet contains $8$ million parameters and it takes about $2.5$ days to train with Adam optimizer~\\cite{kingma2014adam} on a single NVIDIA Titan X Pascal GPU.  We first train the CoarseNet from scratch until convergence and then train the RefineNet. \n\n\\subsection{Residual Learning for Matte Refinement}\n\\label{par:Residual Learning for Matte Refinement}\nAs the attenuation mask and the refractive flow field predicted by the CoarseNet lack structural details, a refinement stage is needed to produce a detailed matte. Observing that residual learning is particularly suitable for tasks whose input and output are largely similar~\\cite{kim2016accurate,Nah_2017_CVPR}, we propose a residual network, denoted as RefineNet, to refine the matte predicted by the CoarseNet. \nSimilar strategy has also been successfully applied to progressively refine the estimated optical flow in~\\cite{ilg2017flownet}.\n\nWe concatenate the input image and the output of the CoarseNet to form the input of the RefineNet. As the object mask predicted by the CoarseNet is already plausible, the RefineNet only outputs an attenuation mask and a refractive flow field. The parameters of the CoarseNet are fixed when training the refinement stage. \n\n\\paragraph{Loss for the refinement stage}\n\\label{par:Loss for Refinement}\nThe overall loss for the refinement stage is\n\\begin{align}\n    \\mathL^r = \\alpha^r_{ar} \\mathL_{ar} + \\alpha^r_{fr} \\mathL_{fr} ,\n\\end{align}\nwhere $\\mathL_{ar}$ is the refinement attenuation regression loss, $\\mathL_{fr}$ the refinement flow regression loss,  and $\\alpha^r_{ar}$, $\\alpha^r_{fr}$ their weights. The definitions of these two losses are identical to those defined in the first stage. \nWe found that adding the image reconstruction loss in the refinement stage did reduce the image reconstruction error during training, but was not helpful in preserving sharp edges of the refractive flow field (\\eg, mouth of a glass). This could be explained by the fact that a lower image reconstruction loss does not guarantee a better refractive flow field. As the matte estimated by the CoarseNet has already achieved a small reconstruction error, simultaneously optimizing the flow regression loss and image reconstruction loss in the refinement stage may compromise the flow estimation.\nSince our goal in the refinement stage is to estimate a more detailed matte, we remove the image reconstruction loss to make our network focus on reducing the flow regression loss.\n\n\\paragraph{Implementation details}\n\\label{par:Implementation Details}\nWe set $\\alpha^r_{ar}=1$, $\\alpha^r_{fr}=1$ for the refinement. RefineNet contains $1$ million parameters and it takes about $2$ days to train with Adam optimizer on a single NVIDIA Titan X Pascal GPU. RefineNet is randomly initialized during training.\n\\subsection{Improvement with Trimap and Background Image}\n\\label{ssec:trimap}\nAs the problem of transparent object matting from a single image is highly ill-posed, we investigate how to reinforce our framework by utilizing additional information. \nIn particular, we consider the cases where a trimap or a background image is available.\nOur framework can be easily extended to make use of these additional information by taking the concatenation of the input image and the background image (or trimap) as input, while keeping the overall network architecture unchanged.\n\n\\paragraph{\\TOMNetTrimap}\nTrimap can provide a rough location of the transparent object to help the model better locate the transparent object. The trimap used in this work is a single channel image with $3$ different values, where values $0$, $1$, and $2$ indicate background, unknown, and foreground regions, respectively.  \nDuring training, we randomly generate trimaps based on the ground-truth object mask. We first perform random erosion and cropping on the object mask to form the known (rough) foreground region. The unknown region is then generated by subtracting the foreground region from a tight bounding box of the object mask, leaving the rest of the regions as the background region.\nThe variant model, denoted as \\TOMNetTrimap, takes both the input image and trimap as input, giving rise to an input channel number of $4$ in the first convolutional layer. \n\n\\paragraph{\\TOMNetBg}\nGiven the background image, the model can easily identify the accurate location of the transparent object based on the difference of the input and background images. Moreover, having access to the background image allows the model to better estimate the refractive flow field.\nThe variant model, denoted as \\TOMNetBg, takes both the input and background images as input, giving rise to an input channel number of $6$ in the first convolutional layer.\n\n\\TOMNetTrimap and \\TOMNetBg are trained with the same procedure as \\hbox{TOM-Net}.\nOur experimental results show that with the additional information, our framework can achieve better results on both synthetic and real dataset.\n\n\\section{Dataset for Learning and Evaluation}\n\\label{sec:dataset}\nCurrently there is no off-the-shelf dataset for transparent object matting. \nOne potential direction is to create a real dataset with ground-truth mattes (\\ie, object masks, attenuation masks, and refractive flow fields) for training. \nHowever, it is almost impossible for human to manually label the refractive flow field of the transparent object.\nOne may consider estimating the mattes using existing transparent object matting methods and using them as the ground truth for training.\nHowever, it is very difficult and tedious as traditional methods require a large number of images and/or a long processing time for each object. \nBesides, there is no publicly available code for transparent object matting.\nTo bypass this problem, we created a large-scale synthetic dataset using \\emph{POV-Ray}~\\cite{povray} to render images of synthetic transparent objects.\nBesides, we captured a real dataset for evaluation. We will show that our TOM-Net trained on the synthetic dataset can generalize well to real world objects, demonstrating its good transferability.\n\n\\subsection{Synthetic Dataset} \n\\label{sub:Synthetic Dataset}\n\n\\begin{figure}[tbp] \\centering\n    \\input{ch-tomnet/figures/syn_data_samples}\n    \\caption[Examples of synthetic data]{Examples of synthetic data. Top to bottom: examples of \\emph{Glass}, \\emph{Glass with Water}, \\emph{Lens} and \\emph{Complex}, respectively. First three columns: background image, rendered image, refractive flow visualization (sparse). Last three columns: ground-truth refractive flow field, object mask, attenuation mask.} \n    \\label{fig:syn_data_samples}\n\\end{figure}\n\nWe used a large number of background images and 3D models to render our training samples. We randomly changed the pose of the models, as well as the viewpoint and focal length of the camera in the rendering process to avoid overfitting to a fixed setting.\n\n\\paragraph{Background images}\n\\label{par:Backgrounds Images}\nWe employed two types of background images, namely scene images and synthetic patterns. For scene images, we randomly sampled images from the Microsoft COCO~\\cite{lin2014microsoft} dataset\\footnote{Other large-scale datasets like ImageNet~\\cite{deng2009imagenet} can also be used.}. The background images for the synthetic training set are sampled from COCO Train2014 and Test2015, while that for the synthetic test dataset are from COCO Val2014, giving rise to $100K$ scene images in total. \nFor synthetic patterns, we rendered $40K$ patterns of size $512\\times 512$ using \\emph{POV-Ray} built-in textures. \n\n\\begin{table} \\centering\n    \\caption[Statistics of our synthetic datasets]{Statistics of our synthetic datasets.}\n    \\label{tab:synth}\n    \\resizebox{0.7\\textwidth}{!}{\n    \\Large\n    \\begin{tabular}{l|*{4}{c}|c}\n        \\toprule\n        Type & \\emph{Glass} & \\emph{Glass with Water} & \\emph{Lens} & \\emph{Complex} & Total \\\\\n        \\midrule\n        Synthetic Train & $52K$ & $26K$ & $20K$ & $80K$ & $178K$\\\\\n        Synthetic Test   & $250$ & $250$ & $200$ & $200$ & $900$\\\\\n        \\bottomrule\n    \\end{tabular}\n    }\n\\end{table}\n\n\\paragraph{Transparent objects}\n\\label{par:Transparent Object}\nWe divided common transparent objects into four categories, namely \\emph{Glass}, \\emph{Glass with water}, \\emph{Lens}, and \\emph{Complex} shape (see \\fref{fig:syn_data_samples} for examples). We constructed parametric 3D models for the first three categories, and generated a large number of models using random parameters. For complex shapes, we constructed parametric 3D models for basic shapes like sweeping-spheres and squashed surface of revolution (SOR) parts, and composed a larger number of models using these basic shapes. We generated $178K$ 3D models in total, with each model assigned a random refractive index $\\lambda \\in [1.3, 1.5]$. The distribution of these models in four categories is shown in \\Tref{tab:synth}. \n\n\\paragraph{Ground-truth matte generation}\n\\label{par:Ground Truth Generation}\nWe obtained the ground-truth object mask of a model by rendering it in front of a black background image and setting its color to white. Similarly, we obtained the ground-truth attenuation mask of a model by simply rendering it in front of a white background image. Finally, we obtained the ground-truth refractive flow field (see \\fref{fig:syn_data_samples}) of a model by rendering it in front of a sequence of Gray-coded patterns. Technical details for the data rendering can be found at \\url{https://github.com/guanyingc/TOM-Net_Rendering}.\n\n\n\\paragraph{Data augmentation}\nTo improve the diversity of the training data and narrow the gap between real and synthetic data, extensive data augmentation was carried out on-the-fly. \nFor an image of size $512\\times 512$ with color intensity normalized to $[0, 1]$, we randomly performed color (brightness, contrast and saturation) augmentation (in a range of $[-0.2, 0.2]$), image scaling (in a range of $[0.875, 1.05]$), noise perturbation (in a range of $[-0.05, 0.05]$), and horizontal/vertical flipping. Besides, we also blurred the object boundary to make the synthetic data visually more natural. A patch with a size of $448\\times 448$ was then randomly cropped from an augmented image and used as input to train CoarseNet. To speed up the training and save memory, a smaller patch with a size of $384\\times 384$ was used to train RefineNet after the training of CoarseNet.\n\n\\begin{figure}[t] \\centering\n    \\makebox[0.16\\textwidth]{\\footnotesize \\emph{Glass}} \n    \\makebox[0.16\\textwidth]{\\footnotesize \\emph{Glass with Water}} \n    \\makebox[0.16\\textwidth]{\\footnotesize \\emph{Lens}} \n    \\makebox[0.16\\textwidth]{\\footnotesize \\emph{Complex}}\n    \\makebox[0.16\\textwidth]{\\footnotesize \\emph{Complex}}\n    \\\\\n    \\input{ch-tomnet/figures/real_data_samples}\n    \\caption[Sample images in real dataset]{Sample images in real dataset. The first row shows the background images and the second row shows the images of transparent objects.} \\label{fig:real_sample}\n\\end{figure}\n\n\\begin{table}[t] \\centering\n    \\caption[Statistics of our real dataset]{Statistics of our real dataset. The first and second rows show the number of objects and the number of backgrounds used during data acquisition, respectively. The last row shows the number of captured samples. Note that the category of \\emph{Glass with Water} are created by filling five of the glasses with different amount of water, and some backgrounds are shared between different shape categories.}\n    \\label{tab:real_data}\n    \\resizebox{0.6\\textwidth}{!}{\n    \\Large\n    \\begin{tabular}{l|*{4}{c}}\n        \\toprule\n        & \\emph{Glass} & \\emph{Glass with Water} & \\emph{Lens} & \\emph{Complex} \\\\% & Total \n        \\midrule                                    %\n        \\# Objects     & $7$   & ($5$ glasses used)  & $1$   & $6$      \\\\% & 14    \n        \\# Backgrounds & $60$  & $38$  & $4$   & $18$     \\\\% & 60    \n        \\midrule                                    %\n        \\# Samples     & $470$ & $103$ & $61$  & $242$    \\\\% & 876   \n        \\bottomrule\n    \\end{tabular}\n    }\n\\end{table}\n\\subsection{Real Dataset}\n\\label{sub:Real Dataset}\nTo validate the transferability of TOM-Net, we introduce a real dataset, which was captured using $14$ objects\\footnote{The objects consist of $7$ glasses, $1$ lens and $6$ complex objects. Glasses with water are implicitly included.} and $60$ background images, resulting in a dataset of $876$ images. Note that the background images for real data have not been used in the synthetic training or test dataset. The data distribution is summarized in \\Tref{tab:real_data}. During the data capturing process, the objects were placed under different poses, with the distances between the camera, object, and background uncontrolled. \\fref{fig:real_sample} shows some sample images from the real dataset.  Note that we do not have the ground-truth matte for the real dataset. We instead captured images of the backgrounds without the transparent objects to facilitate evaluation.\n\nFollowing previous works, the transparent objects were captured in front of a monitor displaying different background images.\nDue to the sampling problem, there may exist Moir\\'{e}-effect in the captured image.  We carefully adjusted the focal length and shutter speed to remove the Moir\\'{e}-effect during the data capturing.\n\n\\section{Experimental Results}\n\\label{sec:experiments}\nIn this section, we present experimental results and analysis.\nWe performed ablation study for TOM-Net, and evaluated our approach on both synthetic and real data.  For synthetic data, we evaluated end-point error (EPE) for refractive flow fields, intersection over union (IoU) for object masks, mean square error (MSE) for attenuation masks and image reconstruction results, respectively.  For real data, due to the absence of ground-truth matte, evaluation on the absolute error with respect to the ground truth is not possible. \nInstead, we reconstructed the input images using the estimated mattes and background images, and then evaluated the PSNR and SSIM metrics~\\cite{wang2004image} between each pair of input image (\\ie, photograph) and reconstructed image (\\ie, composite). In addition, a user study was conducted to validate the realism of TOM-Net composites.\n\nWe showcased an application of image editing of transparent object by manipulating the extracted matte, and analyzed typical failure cases. We also investigated how the performance of our method can be improved when a trimap or a background image is available.\n\n\\subsection{Ablation Study for Network Architecture}\n\\label{sub:Network Analysis}\n\n\\begin{table} \\centering\n    \\caption[Ablation study for TOM-Net]{Ablation study for TOM-Net. F, A, I, and M are short for flow, attenuation, image reconstruction, and object mask, respectively. (The first value for EPE is measured on the whole image and the second measured within the object region. A-MSE and I-MSE are computed on the whole image.)}\n    \\label{tab:self_compare}\n    \\input{ch-tomnet/tables/ablation_study}\n\\end{table}\n\nWe quantitatively analyzed different components of TOM-Net using synthetic dataset\\footnote{Complex shape is excluded in experiments here to speed up training.}. We first verified the effectiveness of \\emph{refractive flow regression loss} ($\\mathL^{c}_{fr}$), \\emph{cross-link}, \\emph{multi-scale loss} and \\emph{image reconstruction loss} ($\\mathL^{c}_{ir}$) in the coarse stage by removing each of them from \\emph{CoarseNet} during training. We then validated the effectiveness of \\emph{RefineNet} in recovering details of the refractive flow field.  RefineNet was evaluated by adding it to a trained CoarseNet and was trained while fixing the parameters of CoarseNet. \nFor comparison, we also included a naive baseline, denoted as \\emph{Background}, by considering a zero matte case (\\ie, whole image as object mask, no attenuation, and no refractive flow) where the reconstructed image is the same as the background image. The quantitative results are summarized in \\Tref{tab:self_compare} and the qualitative comparisons are shown in \\fref{fig:syn_ablation_study}.\nOverall, the baseline \\emph{Background} was outperformed by all TOM-Net variants with a large margin for all the evaluation metrics, which clearly shows that TOM-Net can successfully learn the matte. \n\n\\paragraph{Effectiveness of refractive flow regression loss} Comparing experiments with IDs 1 \\& 5 in \\Tref{tab:self_compare}, it can be clearly seen that the CoarseNet trained with the refractive flow regression loss significantly outperformed that without it in refractive flow estimation. This result indicates that image reconstruction loss alone is not enough to supervise the learning of refractive flow. \\fref{fig:syn_ablation_study} (a \\& e) qualitatively show that the refractive flow regression loss improved the performance of refractive flow estimation.\n\n\\begin{figure}[tbp] \\centering\n    \\input{ch-tomnet/figures/syn_ablation_study_larger}\n    \\caption[Qualitative comparison of different model variants]{Qualitative comparison of different model variants. The first row shows a sample of \\emph{Glass with Water} from the synthetic test dataset. The second and third rows show the estimated refractive flow fields and attenuation masks by different variants, respectively. (\\textbf{CNet} and \\textbf{RNet} are short for CoarseNet and RefineNet.)} \\label{fig:syn_ablation_study}\n\\end{figure}\n\n\\paragraph{Effectiveness of cross-link} Comparing experiments with IDs 2 \\& 5 in \\Tref{tab:self_compare}, we can see that augmenting the decoders of CoarseNet with cross-link helped improve the performance in all metrics, suggested that utilizing correlation is helpful for the matte estimation.\n\\fref{fig:syn_ablation_study} (b \\& e) qualitatively show the results without and with cross-link during training.\n\n\\paragraph{Effectiveness of multi-scale loss} Comparing experiments with IDs 3 \\& 5 in \\Tref{tab:self_compare}, we can see that multi-scale loss boosted performance of CoarsNet in all of the evaluation metrics, particularly the attenuation mask MSE (see \\fref{fig:syn_ablation_study} (c \\& e) for qualitative comparison).\n\n\\paragraph{Effectiveness of image reconstruction loss} Comparing experiments with IDs 4 \\& 5 in \\Tref{tab:self_compare}, we can see that adding image reconstruction loss in the coarse stage slightly improved the performance of refractive flow estimation and was very effective for reducing the image reconstruction error (see \\fref{fig:syn_ablation_study} (d \\& e) for qualitative comparison).\n\n\\begin{figure}[tbp] \\centering\n    \\input{ch-tomnet/figures/refine_vis}\n    \\caption[Visualization of the effectiveness of the refinement stage on real data]{Visualization of the effectiveness of the refinement stage on real data. After refinement, the refractive flow and attenuation mask have more clear structural details (\\eg, glass mouth).} \\label{fig:refine}\n\\end{figure}\n\n\\paragraph{Effectiveness of RefineNet}\nComparing experiments with IDs 5 \\& 6 in \\Tref{tab:self_compare}, we can clearly see that RefineNet can significantly improve the refractive flow estimation. \\fref{fig:syn_ablation_study} (e \\& f) and \\fref{fig:refine} show that RefineNet can infer sharp details on both the synthetic and real data based on the outputs of CoarseNet, demonstrating the effectiveness of the RefineNet. We also found that image reconstruction loss is not helpful for refractive flow estimation in the refinement stage (experiments with IDs 6 \\& 7 in \\Tref{tab:self_compare}). This is reasonable since the matte produced by CoarseNet already gives a small image reconstruction error, and further reducing the image reconstruction error does not guarantee a better refractive flow field. \n\n\\subsection{Evaluation on Synthetic Data}\n\\label{sub:Results on Synthetic data}\n\\begin{table*}[htbp] \\centering\n    \\caption[Quantitative results on the synthetic test dataset]{Quantitative results on the synthetic test dataset. (The first value for EPE is measured on the whole image and the second measured within the object region. A-MSE and I-MSE are computed on the whole image.)}\n    \\input{ch-tomnet/tables/syn_quant_larger}\n    \\label{tab:quant_synth}\n\\end{table*}\n\nQuantitative results for synthetic test dataset are presented in \\Tref{tab:quant_synth}. We compared TOM-Net against \\emph{Background} and CoarseNet. Here, to accelerate training convergence, we first trained CoarseNet from scratch using our synthetic dataset excluding the complex shape subset. The trained CoarseNet was then fine-tuned using the entire training set including complex shapes, followed by training of RefineNet on the entire training set with random initialization. Similar to previous experiments, TOM-Net outperformed \\emph{Background} by a large margin, and slightly outperformed CoarseNet in both EPE and MSE, which implies more local details can be learned by RefinedNet. \n\nThe average IoU for object mask estimation is $0.96$, indicates that TOM-Net can robustly segment the transparent object given only a single image as input.\nAlthough TOM-Net is not expected to learn highly accurate refractive flow, the average EPE errors ($2.7/18.6$)\\footnote{The first value is measured on the whole image and the second measured within the object region.} are very small compared with the size of the input image ($448\\times 448$). In this sense, our predicted flow is capable of producing visually plausible refractive effect. The errors of complex shape category are larger than that of others, because complex shapes contain more sharp regions that will induce more errors. \n\\Fref{fig:qual_synth} and \\Fref{fig:qual_synth2} show the qualitative results on five synthetic objects. The objects in the first four examples come from the test set where each example shows a specific object category. Although the background images and objects in the test set never appear in the training set, TOM-Net can still predict robust matte.\n The last row (\\ie, \\fref{fig:qual_synth2}~(e)) shows a sample of \\emph{complex dog}, which was rendered using a 3D dog model. The pleasing result on the \\emph{complex dog} demonstrates that our model can generalize well from simple shapes to complex shapes.\n\n\\Fref{fig:qual_synth} shows that the reconstructed images using the estimated mattes (column 2) are very close to the input images (column 2), which empirically verifies that our simplified matting equation \\eref{eq:em_simplify3} is sufficiently accurate for this problem.\n\n\\begin{figure}[htbp] \\centering\n    \\input{ch-tomnet/figures/syn_qual_larger}\n    \\caption[Qualitative results on synthetic data (part $1$)]{Qualitative results on synthetic data (part $1$). For each example, the first column shows the input image and background. The second column shows the reconstructed image and reconstruction error map. The last three columns show the ground truth matte and estimation. Quantitative results are shown below each example. Dark region in GT flow indicates no valid flow.} \\label{fig:qual_synth}\n\\end{figure}\n\n\\begin{figure}[htbp] \\centering\n    \\input{ch-tomnet/figures/syn_qual_larger2}\n    \\caption[Qualitative results on synthetic data (part $2$)]{Qualitative results on synthetic data (part $2$). For each example, the first column shows the input image and background. The second column shows the reconstructed image and reconstruction error map. The last three columns show the ground truth matte and estimation. Quantitative results are shown below each example. Dark region in GT flow indicates no valid flow.} \\label{fig:qual_synth2}\n\\end{figure}\n\n\\clearpage\n\\subsection{Evaluation on Real Data}\n\\label{sub:Results}\n\\begin{table}[htbp] \\centering\n    \\caption[Quantitative results on real data]{Quantitative results on real data. (Value the higher the better.)}\n    \\resizebox{0.9\\textwidth}{!}{ \n    \\huge\n    \\begin{tabular}{c|*{2}{c}|*{2}{c}|*{2}{c}|*{2}{c}|*{2}{c}}\n        \\toprule\n        \\multirow{2}{*}{} & \\multicolumn{2}{c}{\\emph{Glass}} \n                          & \\multicolumn{2}{c}{\\emph{Glass with Water}} \n                          & \\multicolumn{2}{c}{\\emph{Lens}} \n                          & \\multicolumn{2}{c}{\\emph{Complex}} \n                          & \\multicolumn{2}{c}{Avg} \\\\\n        & PSNR & SSIM  & PSNR & SSIM & PSNR & SSIM & PSNR & SSIM & PSNR & SSIM \\\\\n        \\midrule\n        Background    & 22.05 & 0.894 & 20.75 & 0.886 & 18.60 & 0.860 & 16.85 & 0.816 & 19.56 & 0.864 \\\\ \n        CoarseNet     & 25.09 & 0.921 & 23.53 & 0.911 & 21.13 & 0.895 & 17.89 & 0.835 & 21.91 & 0.891  \\\\ \n        TOM-Net        & 25.06 & 0.920 & 23.53 & 0.911 & 20.89 & 0.893 & 17.88 & 0.835 & 21.84 & 0.890 \\\\ \n        \\bottomrule\n    \\end{tabular}\n    }\n    \\label{tab:real_quant}\n\\end{table}\n\nWe evaluated TOM-Net on our captured real dataset, which consists of $876$ images of real objects. The results are shown in \\Tref{tab:real_quant}. The average PSNR and SSIM are above $21.0$ and $0.89$ respectively. The values are a bit lower for complex shapes, due to the opaque base of complex objects as well as the sharp regions of the objects that might induce large errors. After training, TOM-Net generalized well to common real transparent objects (see \\fref{fig:real_qualitative}). It is worth to note that during training, each sample contains only one object, while TOM-Net can predict reliable matte for images containing multiple objects (see \\fref{fig:real_qualitative} (c)), which indicates the transferability and robustness of TOM-Net.\n\n\\begin{figure}[htbp] \\centering\n    \\input{ch-tomnet/figures/real_qual}\n    \\caption[Qualitative results on real data]{Qualitative results on real data. The PSNR and SSIM between input photographs and reconstructed images are shown below each example. The last column shows the composites on novel backgrounds given the estimated matte.} \n    \\label{fig:real_qualitative}\n\\end{figure}\n\n\\paragraph{User study}\n\\label{par:User Study}\nRemember that our goal is to estimate an environment matte that can produce visually realistic refractive effect from the input image, instead of estimating the highly accurate refractive flow.\nA user study was carried out to validate the realism of TOM-Net composites. $69$ subjects participated in our user study. At the beginning, we showed each participant photographs of the transparent objects that will be seen during the user study. The objects consisted of $3$ different glasses, $1$ glass with water, $1$ lens, and $1$ complex shape. $40$ samples, including $20$ photographs\\footnote{glass $\\times$12, glass \\& water $\\times$4, lens $\\times$2, and complex shape $\\times$2.} and the corresponding $20$ TOM-Net composites, were then randomly presented to each subject. When showing each sample, we also showed the corresponding background image to the subject for reference. We provided $3$ options for each sample: (P) {\\em photograph}, (C) {\\em composite}, (N) {\\em not distinguishable}.\n\\Tref{tab:user_study} shows the statistics of the user study. The $69$ participants produced $1,380$ votes for the $20$ real photographs, and $1,380$ votes for the $20$ composites, respectively. The P:C:N ratios are $850:455:75$ and $827:482:71$ for photographs and composites respectively. The per-category ratios also follow a similar trend, indicating close chance of photographs and composites to be considered real, which further demonstrates TOM-Net can produce realistic matte. \n\n\\begin{table}[tbp] \\centering\n    \\caption[User study results]{User study results. P, C, and N are short for votes for photograph, composite, and not distinguishable.}\n    \\large\n    \\resizebox{0.8\\textwidth}{!}{\n        \\begin{tabular}{c|*{3}{c}|*{3}{c}|*{3}{c}|*{3}{c}|*{3}{c}}\n        \\toprule\n            \\multirow{2}{*}{}  & \\multicolumn{3}{c}{\\emph{Glass}} \n                               & \\multicolumn{3}{c}{\\emph{Glass with Water}} \n                               & \\multicolumn{3}{c}{\\emph{Lens}} \n                               & \\multicolumn{3}{c}{\\emph{Complex}}  \n                               & \\multicolumn{3}{c}{All}  \\\\\n                               & P & C & N & P & C & N & P & C & N & P & C & N & P & C & N \\\\ \\midrule\n        Photographs        & 522 & 275 & 31 & 163 & 97 & 16 & 74 & 48 & 16 & 91 & 35 & 12 & 850 & 455 & 75 \\\\\n        Composites    & 531 & 266 & 31 & 145 & 113 & 18 & 73 & 52 & 13 & 78 & 51 & 9 & 827 & 482 & 71 \\\\\n        \\bottomrule\n    \\end{tabular}\n    }\n    \\label{tab:user_study}\n\\end{table}\n\n\\begin{figure}[htbp] \\centering\n    \\includegraphics[width=0.8\\textwidth]{ch-tomnet/images/user_study/user_study_larger} \\\\\n    \\makebox[0.4\\textwidth]{\\footnotesize Photograph} \n    \\makebox[0.4\\textwidth]{\\footnotesize Composite} \n    \\caption[Comparison of the photograph and composite]{Comparison of the photograph and composite. The first row shows the predicted matte, which is estimated by taking the photograph as input to our method. The second row compares the photograph and composite. When looking at the photograph and composite simultaneously, users can easily spot some imperfections of the composites (mostly in the boundary region).}\n    \\label{fig:sup_user_study}\n\\end{figure}\n\nAlthough we stress that TOM-Net can produce visually realistic composites, the results are still less than perfect. When looking at the real image and our composite side-by-side, users can spot some imperfections of the composite (mostly in the boundary region, see \\fref{fig:sup_user_study}). Therefore, we did not include such a user study by showing the real image and our composite side-by-side. Otherwise, the result will be biased. In the future, we will strengthen our approach to produce more realistic composites, so that the real image and our composite are indistinguishable even when showing them side-by-side.\n\n\\subsection{Transparent Object Editing by Manipulating Environment Matte}\n\\label{sec:edit_flow}\n\n\\begin{figure}[htbp] \\centering\n    \\makebox[0.132\\textwidth]{\\scriptsize Background} \n    \\makebox[0.132\\textwidth]{\\scriptsize Input} \n    \\makebox[0.132\\textwidth]{\\scriptsize Rec. Image} \n    \\makebox[0.132\\textwidth]{\\scriptsize Rec. Error} \n    \\makebox[0.132\\textwidth]{\\scriptsize Refractive Flow} \n    \\makebox[0.132\\textwidth]{\\scriptsize Object Mask} \n    \\makebox[0.132\\textwidth]{\\scriptsize Attenuation Mask} \n    \\\\\n    \\input{ch-tomnet/figures/sup_editFlow_example}\n    \\makebox[\\textwidth]{\\footnotesize (a) An example result on \\emph{Glass with Water}. Reconstruction error: PSNR=25.69, SSIM=0.95}\n    \\\\\n    \\input{ch-tomnet/figures/sup_scaleFlow}\n    \\vspace{-0.2em}\\makebox[\\textwidth]{\\footnotesize (b) Rescaling the magnitude of the estimated refractive flow field.}\n    \\\\\n    \\vspace{0.4em}\n    \\input{ch-tomnet/figures/sup_editFlow} \n    \\makebox[\\textwidth]{\\footnotesize (c) Translate, rotate or rescale the environment matte.}\n    \\caption[Image editing by manipulating the predicted environment matte]{Various novel composites of a \\emph{Glass with Water} shape obtained by manipulating the predicted environment matte.} \\label{fig:sup_edit}\n\\end{figure}\n\nGiven a single image as input, our TOM-Net can estimate the environment matte as a triplet (consisting of an object mask, an attenuation mask, and a refractive flow field) in a fast feed-forward pass (see \\fref{fig:sup_edit} (a) for an example).\nNote that the goal of the proposed TOM-Net is to extract an environment matte that can produce realistic refractive effect from a single image, instead of estimating a highly accurate environment matte. \nThe reconstructed image in \\fref{fig:sup_edit} (a) looks realistic but does not have the same refractive effect as the original input, as the refractive effect of the estimated matte seems stronger. \nBy decreasing the magnitude of the estimated refractive flow field\\footnote{We simply multiply the refractive flow field by a scaling factor ($<1$).}, we can produce a similar refractive effect as the input image (see \\fref{fig:sup_edit} (b)). When the scaling factor becomes $0.6$, the reconstructed image achieved the lowest reconstruction error, with an improvement of $1.49$ and $0.01$ in PSNR and SSIM, respectively.\nApart from rescaling the magnitude of the refractive flow field to adjust the refractive effect of the object, more interesting composites can be obtained by translating, rotating and rescaling the environment matte (see \\fref{fig:sup_edit} (c)). \n\n\\subsection{Failure Cases}\n\\label{sec:Failure Cases}\n\n\\begin{figure}[htbp] \\centering\n    \\makebox[0.05\\textwidth]{\\footnotesize } \n    \\makebox[0.18\\textwidth]{\\footnotesize Input} \n    \\makebox[0.18\\textwidth]{\\footnotesize Refractive Flow} \n    \\makebox[0.18\\textwidth]{\\footnotesize Object Mask} \n    \\makebox[0.18\\textwidth]{\\footnotesize Attenuation Mask} \\\\\n    \\input{ch-tomnet/figures/sup_failure}\n    \\caption[Failure cases on real data]{Two failure cases on real data. In (a), our model fails to estimate the upper-part of the matte as there is no visual clue to find the object. In (b), the bottom part of the estimated matte is incomplete as the background image is heavily cluttered and the bottom part of the object is very dark.}\n    \\label{fig:sup_fail}\n\\end{figure}\n\nOur model can robustly estimate environment matte for different transparent objects in front of different backgrounds, however, when there is no visual clue for the objects or the image is too cluttered to separate the object from the background, our model may fail. \\Fref{fig:sup_fail} shows two failure cases of our model on real data. In \\fref{fig:sup_fail} (a), our model fails to extract the upper-part of the environment matte for the transparent glass due to the lack of visual clue. \nIn \\fref{fig:sup_fail} (b), although our model is still able to estimate a reasonable matte, the bottom part of the estimated matte is incomplete due to the very cluttered background. \n\n\n\\subsection{Improvement with Trimap and Background Image}\n\\begin{table*}[htbp] \\centering\n    \\caption[Quantitative comparison on the synthetic test dataset]{Quantitative comparison between TOM-Net, \\TOMNetTrimap and \\TOMNetBg on the synthetic test dataset.}\n    \\input{ch-tomnet/tables/syn_quant_trimap_bg_larger}\n    \\label{tab:stereo_quant_synth}\n\\end{table*}\n\n\\begin{table}[htbp] \\centering\n    \\caption[Quantitative comparison on real data]{Quantitative comparison between TOM-Net, \\TOMNetTrimap and \\TOMNetBg on real data.}\n    \\resizebox{0.8\\textwidth}{!}{ \n    \\huge\n    \\begin{tabular}{l|*{2}{c}|*{2}{c}|*{2}{c}|*{2}{c}|*{2}{c}}\n        \\toprule\n        \\multirow{2}{*}{} & \\multicolumn{2}{c}{\\emph{Glass}} \n                          & \\multicolumn{2}{c}{\\emph{Glass with Water}} \n                          & \\multicolumn{2}{c}{\\emph{Lens}} \n                          & \\multicolumn{2}{c}{\\emph{Complex}} \n                          & \\multicolumn{2}{c}{Average} \\\\\n        & PSNR & SSIM  & PSNR & SSIM & PSNR & SSIM & PSNR & SSIM & PSNR & SSIM \\\\\n        \\midrule\n        Background     & 22.05 & 0.894 & 20.75 & 0.886 & 18.60 & 0.860 & 16.85 & 0.816 & 19.56 & 0.864 \\\\ \n        TOM-Net        & 25.06 & 0.920 & 23.53 & 0.911 & 20.89 & 0.893 & 17.88 & 0.835 & 21.84 & 0.890 \\\\ \n        \\TOMNetTrimap & 25.48 & 0.924 & 23.77 & 0.914 & 23.98 & 0.913 & 20.88 & 0.868 & 23.53 & 0.905\\\\ \n\\TOMNetBg     & 26.10 & 0.931 & 24.58 & 0.922 & 25.52 & 0.924 & 22.23 & 0.884 &\\textbf{24.61} & \\textbf{0.915} \\\\ \n        \\bottomrule\n    \\end{tabular}\n    }\n    \\label{tab:real_quant_stereo}\n\\end{table}\n\n\\begin{figure*} \\centering\n    \\input{ch-tomnet/figures/qual_mono_trimap_stereo_larger}\n    \\caption[Qualitative comparison on real data]{Qualitative comparison between TOM-Net, \\TOMNetTrimap and \\TOMNetBg on real data.\n    For each testing object, the input to the model is shown on the first column, and the results of TOM-Net (up), \\TOMNetTrimap (middle) and \\TOMNetBg (bottom) are shown on the rest of the columns. Note that for \\TOMNetTrimap and \\TOMNetBg, we do not show the input image for simplicity. The PSNR and SSIM between input photographs and reconstructed images are shown right after the error maps.}\n    \\label{fig:qual_stereo_mono}\n\\end{figure*}\n\nAt test time, the input trimaps for \\TOMNetTrimap were generated in the same way adopted in the training (as described in \\Sref{ssec:trimap}), except that the foreground regions were obtained by performing erosion operation on the ground-truth object mask with a fixed (rather than a random) kernel size of $10$ pixels for evaluation.\n\\Tref{tab:stereo_quant_synth} shows the quantitative comparisons between TOM-Net, \\TOMNetTrimap and \\TOMNetBg on the synthetic test dataset. \nAs expected, with the access to the additional information, both \\TOMNetTrimap and \\TOMNetBg performed better than TOM-Net. Due to the fact that a background image contains more useful information than a trimap, \\TOMNetBg achieved the best results.\n\n\\Tref{tab:real_quant_stereo} presents the quantitative comparison on real data. Compared with TOM-Net, \\TOMNetTrimap and \\TOMNetBg achieved an improvement of $1.69$ and $2.77$ in average PSNR and an improvement of $0.015$ and $0.024$ in average SSIM, respectively. \n\\fref{fig:qual_stereo_mono} shows the qualitative comparison on real data, where the foreground region of the trimap was marked by the user. It can be seen that with the additional information, \\TOMNetTrimap and \\TOMNetBg can identify the transparent object from the cluttered background more accurately than TOM-Net and model the opaque base of the transparent object (\\fref{fig:qual_stereo_mono} (a)). As a result, the environment matte predicted by \\TOMNetTrimap and \\TOMNetBg can produce more realistic composites and achieve lower reconstruction errors, clearly demonstrating the effectiveness of our framework in handling cases where a trimap or a background image is available.\n\n\\section{Discussion}\n\\label{sec:discussion}\n\n\\begin{figure*}[t] \\centering\n    \\input{ch-tomnet/figures/limitation}\n    \\caption[Results on colored object and objects under natural illumination]{Qualitative results of TOM-Net on colored transparent object (first row) and objects under natural illuminations (last four rows).}\n    \\label{fig:limitation}\n\\end{figure*}\n\n\\subsection{Limitations}\nAlthough our method can produce plausible results for transparent object matting, there do exist limitations that require further study.\nFirst, our model assumes objects to be colorless so that the attenuation property of an object can be depicted as a scalar value $\\rho$ in our formulation. However, this is not applicable to colored transparent objects, as shown in see \\fref{fig:limitation}~(a). \nAlthough our method can estimate a reasonably good object mask and refractive flow field for the \\emph{Glass with Water}, the estimated attenuation mask cannot model the colored effect of the object.\n\nSecond, our model assumes a single planar background (following most of the previous works) as the only light source and simplifies the interaction between object and background image to a point-to-point (single) mapping. However, more complicated effects exist in the real world, such as specular highlights, translucency, multi-mapping (\\ie, refraction and reflection happen simultaneously at a surface point), and color dispersion (\\ie, different color components may have different supporting background regions). \n\\fref{fig:limitation}~(b)-(e) show four example results of TOM-Net on transparent objects under different types of natural illuminations. Regardless of the fact that TOM-Net can estimate a plausible object mask and refractive flow field, the composites do not look very realistic. \nThis is because our current formulation does not consider the more sophisticated refractive properties of a transparent object under natural illumination like complex interaction with environment light, specular highlight, Fresnel effect, and acoustic shadow.\n\n\\subsection{Colored Objects and Specular Highlights}\nHere we sketch the potential solutions to colored transparent objects as well as the cases when specular highlights appear on transparent objects. In \\Sref{sec:formulation}, we simplified matting equation as \\eref{eq:em_simplify3}.\nTo handle colored objects, the scalar attenuation index $\\rho$ should be expanded to a color attenuation 3-vector $R$, in which each value corresponds to an attenuation index for a specific color channel. The matting equation then becomes \n\\begin{equation}\n    \\label{eq:color_2}\n    C = (1 - m) B + mR \\circ \\mathcal{M}(\\mathbf{T}, P),\n\\end{equation}\nwhere $\\circ$ represents element-wise multiplication.\n\nConsider a white near point light source, we can simplify the specular highlight effect with a specular highlight component $S$, then the generalized matting equation can be written as\n\\begin{equation}\n    \\label{eq:color_2}\n    C = (1 - m) B + mR \\circ \\mathcal{M}(\\mathbf{T}, P) + S,\n\\end{equation}\nwhere $S$ is a 3-vector containing three identical values.\nThe problem of transparent object matting now becomes simultaneously estimating an object mask, a color attenuation mask, a refractive flow field, and a specular highlight mask from a single image, while more efforts are needed to implement them for practical use and we leave this as our future work.\n\n\\subsection{Difficulty in Comparison with Previous Works}\nCurrently, it is not trivial to have a fair comparison with existing methods. On one hand, applying our method on the data used in the previous methods is difficult. Most of the previous methods require multiple images of the transparent object captured in front of pre-designed patterns, which are not publicly available and lack enough textures for our method to estimate the refractive effect of the transparent object. \nThe single image based methods RTCEM~\\cite{chuang2000environment} and~\\cite{yeung2011matting} have additional requirements. In particular, RTCEM~\\cite{chuang2000environment} requires the object to be captured in front of a coded-pattern (also not publicly available), and the background image is needed to segment the foreground object. \n\\cite{yeung2011matting} requires human interaction to segment the foreground object and model the object's refractive effect with thin-plate-spline transformation. The data used in~\\cite{yeung2011matting} does not follow our assumption that the light comes from a single background image, thus it cannot be directly processed by our method.\nOn the other hand, there are no public implementations for the previous methods, and even if there were, those methods cannot be applied to our dataset which is created for single image transparent object matting.\n\nDifferent from the previous methods, our method aims to estimate the foreground mask, attenuation mask, and refractive flow field from a single natural image. Since our code and datasets have been made publicly available, it will ease the comparison for the future work. We believe our work can serve as a baseline and provide meaningful insight for future researches in this area.\n\n\\subsection{Generalization to Real Data}\n    As it is very difficult and time consuming to create a large scale real dataset for training, we use synthetic data for training and evaluate its performance on real data. \nIt is well-known that there is a domain gap between the synthetic and real data, and a model trained on synthetic data may not generalize well to real data.\nWe hypothesize that the reasons why our method works well on real data are as follows.\nFollowing previous works, the real transparent objects are captured in front of a monitor.\nUnder our assumption, the captured images and the rendered images are very similar. Moreover, extensive data augmentation is performed to close the gap between the synthetic and real data.\n\nTo further improve the generalization ability of our method on real data, we will explore the idea of exploiting real data for self-supervised training or fine-tuning in the future.\n\n\\subsection{Design of the Network Architecture}\nTo better recover the details of the refractive flow field and attenuation mask, we propose a two-stage network architecture for this problem. \nOur results show that RefineNet can effectively improve the results of CoarseNet.\nHowever, our two-stage network requires stepwise training (\\ie, we first trained CoarseNet until convergence and then trained RefineNet) which requires longer training time.\nAn interesting future direction is to develop a more efficient single-stage network that achieves comparable performance as the two-stage network. \n\n\\section{Conclusion}\n\\label{sec:conclusion}\nWe have introduced a simple and efficient model for transparent object matting, and proposed a CNN architecture, called TOM-Net, that takes a single image as input and predicts environment matte as an object mask, an attenuation mask, and a refractive flow field in a fast feed-forward pass. We created a large-scale synthetic dataset and a real dataset as a benchmark for learning transparent object matting. We have also shown that TOM-Net can perform better by incorporating a trimap or a background image in the input. Promising results have been achieved on both synthetic and real data, which clearly demonstrate the feasibility and effectiveness of the proposed approach. \n", "meta": {"hexsha": "528bdb814867b64e687c75d9af8a546145bbcef2", "size": 66390, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ch-tomnet/tomnet.tex", "max_stars_repo_name": "guanyingc/HKU-PhD-Thesis-LaTex", "max_stars_repo_head_hexsha": "b243a0517ed2e802f480d87925d110f15f030ff6", "max_stars_repo_licenses": ["Unlicense", "MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-06T01:05:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-06T01:05:00.000Z", "max_issues_repo_path": "ch-tomnet/tomnet.tex", "max_issues_repo_name": "guanyingc/HKU-PhD-Thesis-LaTex", "max_issues_repo_head_hexsha": "b243a0517ed2e802f480d87925d110f15f030ff6", "max_issues_repo_licenses": ["Unlicense", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch-tomnet/tomnet.tex", "max_forks_repo_name": "guanyingc/HKU-PhD-Thesis-LaTex", "max_forks_repo_head_hexsha": "b243a0517ed2e802f480d87925d110f15f030ff6", "max_forks_repo_licenses": ["Unlicense", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 111.5798319328, "max_line_length": 1629, "alphanum_fraction": 0.7713812321, "num_tokens": 16218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3466190405799409}}
{"text": "\\chapter{Solving the \\acrshort{ECP} and the \\acrshort{D-ECP}}\n\\label{ch:solving}\n\nWe now present some techniques for calculating exactly and approximating both\nthe \\acrshort{ECP} and the \\acrshort{D-ECP} (\\autoref{sub:the_problem_definition}).\n\n\\section{Exact Solutions}%\n\\label{sec:exact-solutions}\n\nWe start with our exact algorithms that are based on MIPs.\n\n\\subsection{A MIP Model for the \\acrshort{ECP}}%\n\\label{sub:a_mip_model_for_the_ecp}\n\nLet $G$ be an \\emph{interaction graph} for contents $\\mathcal{C} $ and\nthreads $T \\in \\mathcal{T}_{C}, \\; C \\in \\mathcal{C} $ for which we want to\nsolve the \\acrshort{ECP}. Fix\n$\\alpha \\in [0, 1]$. Let $\\mathcal{\\hat{C}} \\subseteq \\mathcal{C} $ be the\nset of controversial contents and $E_k$ the set\nof all edges of thread $T_k$ associated to a controversial content, i.e. $T_{k}\n\t\\in \\mathcal{T}_{C}, C \\in \\mathcal{\\hat{C}}$; let also $E^{+}_k $\nand $E^{-}_k $ be the set of positive and negative edges in $T_k$, respectively.\n\nThe following \\acrshort{MIP} model is able to solve the \\acrshort{ECP} on $G$\nfor values of $\\alpha \\leq 0.5$.\n\n\\begin{alignat}{3}\n\t\\label{eq:ecp-exact1}\n\t\\text{maximize}     &                                                 & \\sum_{ T_{k} \\in \\mathcal{T}_{C}, \\; C \\in\n\t\t\\mathcal{\\hat{C}} } \\big( \\sum^{}_{ij \\in E^{+}_k } x_{ij}\n\t^{k} - \\sum_{ij \\in E^{-}_k } x_{ij} ^{k} \\big)                                                                                                                                               \\\\\n\t\\label{eq:ecp-v1}\n\t\\text{subject to}   & \\quad                                           & x _{ij}^{k}  \\leq y_i                                               & \\quad \\forall ij \\in E_k                        \\\\\n\t\\label{eq:ecp-v2}\n\t                    &                                                 & x _{ij}^{k}  \\leq y_j                                               & \\quad \\forall ij \\in E_k                        \\\\\n\t\\label{eq:ecp-t1}\n\t                    &                                                 & x _{ij}^{k}  \\leq z_k                                               & \\quad \\forall ij \\in E_k                        \\\\\n\t\\label{eq:ecp-e1}\n\t                    &                                                 & x _{ij} ^{k} \\geq - 2 + y_i + y_j + z_k                             & \\quad \\forall ij \\in E_k                        \\\\\n\t\\label{eq:ecp-alpha-constraint1}\n\t                    &                                                 & \\sum^{}_{ij \\in E_k^{-} } x_{ij}^{k}  - \\alpha \\sum^{}_{ij \\in E_k}\n\tx_{ij} ^{k}  \\leq 0 & \\quad \\forall T_{k} \\in \\mathcal{T} _{C}, C \\in\n\t\\hat{\\mathcal{C}}                                                                                                                                                                             \\\\\n\t\\label{eq:ecp-vertex-def1}\n\t                    &                                                 & y _{i} \\in  \\{0, 1\\}                                                & \\quad \\forall i \\in V                           \\\\\n\t\\label{eq:ecp-edge-def1}\n\t                    &                                                 & 0 \\leq x _{ij} ^{k}  \\leq 1                                         & \\quad \\forall ij \\in E_k                        \\\\\n\t\\label{eq:ecp-thread-def1}\n\t                    &                                                 & 0 \\leq z _{k} \\leq 1                                                & \\quad \\forall T_{k} \\in \\mathcal{T} _{C}, C \\in\n\t\\hat{\\mathcal{C}}\n\\end{alignat}\n\nThe \\acrshort{MIP} model introduces variables $x$, $y$ and $z$.\n\\begin{itemize}\n\t\\item $y$ variables are associated to vertices\n\t      (\\autoref{eq:ecp-vertex-def1}). Intuitively $y_i = 1$ means that the\n\t      vertex $v_{i} $ is part of the set $U \\subseteq V$ considered for the\n\t      score.\n\t\\item $x$ variables are associated to edges (\\autoref{eq:ecp-edge-def1}).\n\t      A value of $x_{ij}^{k} = 1$ should be interpreted as the fact that\n\t      the edge $e_{ij} \\in E_k$ is contributing to the score,\n\t      i.e. $T_k \\in \\mathcal{S}_{C} (U)$.\n\t\\item $z$ variables are associated to threads\n\t      (\\autoref{eq:ecp-thread-def1}). A value greater than 0\n\t      is generally associated to \\emph{non-controversial} threads and\n\t      \\emph{controversial} threads have value $z_k = 0$.\n\\end{itemize}\n\nWe will now show that the \\acrshort{ECP} can be solved through\nMIP~\\eqref{eq:ecp-exact1}-\\eqref{eq:ecp-thread-def1}.\n\n\\begin{theorem}\n\t\\label{th:ecp-mip}\n\tLet $G = \\{G_k = (V,E_k) \\}_k$ be an \\emph{Interaction Graph} and $\\alpha \\in\n\t\t[0, 0.5]$. Then\n\n\t\\begin{equation}\n\t\t\\max_{U \\subseteq V} \\xi(U) = \\operatorname{OPT}(\\operatorname{MIP}),\n\t\\end{equation}\n\twhere $\\operatorname{OPT}(\\operatorname{MIP})$ denotes the optimal solution to\n\tMIP~\\eqref{eq:ecp-exact1}-\\eqref{eq:ecp-thread-def1}.\n\\end{theorem}\n\n\\begin{proof}\n\tWe will show the equality by first proving that $RHS \\geq LHS$ and then\n\tthat $LHS \\geq RHS$.\n\n\t\\begin{claim}\n\t\t\\label{th:claim-v-b-xi}\n\t\tFor any $U \\subseteq V$, the\n\t\tMIP~\\eqref{eq:ecp-exact1}-\\eqref{eq:ecp-thread-def1} achieves value at\n\t\tleast $\\xi(U)$.\n\t\\end{claim}\n\n\t\\begin{proof}\n\t\tLet $E_k[U]$ the set of edges induced by $U$ in thread $T_k$. We\n\t\tconstruct a MIP solution as follows:\n\n\t\t\\begin{alignat}{2}\n\t\t\t\\label{eq:ecpp-y}\n\t\t\ty_i        & = \\begin{cases}\n\t\t\t\t1, & \\text{if } v_{i} \\in U, \\\\\n\t\t\t\t0, & \\text{otherwise,}\n\t\t\t\\end{cases} & \\forall v_i \\in V                                \\\\\n\t\t\t\\label{eq:ecpp-z}\n\t\t\tz_k        & = \\begin{cases}\n\t\t\t\t1, & \\text{if } T_{k} \\in \\mathcal{S}_C(U), \\; C \\in\n\t\t\t\t\\mathcal{\\hat{C}} ,                                  \\\\\n\t\t\t\t0, & \\text{otherwise,}\n\t\t\t\\end{cases} & \\forall T_k \\in \\mathcal{T}_C, C \\in \\mathcal{C} \\\\\n\t\t\t\\label{eq:ecpp-x}\n\t\t\tx_{ij}^{k} & = \\begin{cases}\n\t\t\t\t1, & \\text{if } e_{ij} \\in E_{k}[U], \\; T_{k} \\in \\mathcal{S}_C(U), \\; C \\in\n\t\t\t\t\\mathcal{\\hat{C}},                                                           \\\\\n\t\t\t\t0, & \\text{otherwise.}\n\t\t\t\\end{cases} & \\forall e_{ij}^k \\in E_k\n\t\t\\end{alignat}\n\n\t\tTo satisfy \\eqref{eq:ecp-v1}-\\eqref{eq:ecp-e1} we need that\n\t\t\\begin{equation}\n\t\t\t\\label{eq:ecpp-x-iff}\n\t\t\tx_{ij}^{k} = 1 \\iff y_i = 1 \\land y_j = 1 \\land z_k = 1.\n\t\t\\end{equation}\n\t\tThis is always true since we defined $x_{ij}^{k}$ to be $1$ only and if it\n\t\tis associated to an edge induced in a $T_k \\in \\mathcal{S}_C(U), \\; C \\in\n\t\t\t\\mathcal{\\hat{C}} $.\n\n\t\tLet us now consider a thread $T_k \\in \\mathcal{S}_C(U)$. Then\n\n\t\t\\begin{equation}\n\t\t\t\\eta(T_k[U]) \\leq \\alpha \\implies \\frac{|E^{-}_{k}[U]|}{|E_{k}[U]|} \\leq\n\t\t\t\\alpha \\implies |E^{-}_{k}[U]| - \\alpha |E_{k}[U]| \\leq 0.\n\t\t\\end{equation}\n\t\tso \\eqref{eq:ecp-alpha-constraint1} is satisfied. It is easy to see that\n\t\tif $T_k \\not\\in \\mathcal{S}_C(U)$ then $x_{ij}^{k} = 0$ for all $ij \\in E_{k}$ and\n\t\tthe constraint is also satisfied.\n\n\t\tFinally, any edge contributing to $\\xi(U)$ will also\n\t\tequally contribute to the objective function.\n\t\\end{proof}\n\n\t\\begin{claim}\n\t\t\\label{th:claim-xi-b-v}\n\t\tGiven a feasible solution of\n\t\tMIP~\\eqref{eq:ecp-exact1}-\\eqref{eq:ecp-thread-def1} with value $v$ we can\n\t\tconstruct $U \\; s.t. \\; \\xi(U) \\geq v$.\n\t\\end{claim}\n\n\t\\begin{proof}\n\t\tWe define $U \\coloneqq \\{ v_{i} \\; s.t. \\; y_i = 1\\}$. Again, by\n\t\t\\eqref{eq:ecp-v1}-\\eqref{eq:ecp-e1} we have\n\t\t\\eqref{eq:ecpp-x-iff}, so\n\t\t\\begin{gather}\n\t\t\tx_{ij}^{k} = 1 \\implies z_k = 1, \\\\\n\t\t\t\\label{eq:ecpp-z-iff-xij}\n\t\t\tz_k = 1 \\implies x_{i'j'}^{k} = 1 \\; \\forall i'j'\n\t\t\t\\in E_k[U],\n\t\t\\end{gather}\n\t\tmeaning that if $z_k = 1$ then for all the edges $e_{ij} \\in E_k$ induced\n\t\tby $U$ we will have $x_{ij}^{k} = 1$ (i.e.\\ they will contribute to the\n\t\tobjective).\n\t\tLet us now consider $T_k \\; s.t. \\; z_k = 1$. Because of\n\t\t\\eqref{eq:ecp-alpha-constraint1} and \\eqref{eq:ecpp-z-iff-xij} we have\n\n\t\t\\begin{equation}\n\t\t\t\\label{eq:ecpp-nc-t}\n\t\t\t|E^{-}_{k}[U]| - \\alpha |E_{k}[U]| \\leq 0 \\implies\n\t\t\t\\frac{|E^{-}_{k}[U]|}{|E_{k}[U]|} \\leq \\alpha.\n\t\t\\end{equation}\n\t\ti.e. $\\eta(T_k[U]) \\leq \\alpha$. So $T_k \\in\n\t\t\t\\mathcal{S}_C(U), \\; C \\in \\mathcal{\\hat{C}}$, i.e. $z_k = 1 \\implies T_k\n\t\t\t\\in \\mathcal{S}_C(U), \\; C \\in \\mathcal{\\hat{C}}$, thus $T_k[U]$ contributes to\n\t\t$\\xi(U)$; more specifically any edge contributing to the objective function equally\n\t\tcontributes to $\\xi(U)$.\n\n\t\tNow suppose there exists $T_k \\in \\mathcal{S}_C(U) \\; s.t.\n\t\t\t\\; z_k = 0$. Then $ x_{ij}^{k} = 0$ by \\eqref{eq:ecp-t1}. Since $\\alpha \\leq 0.5$,\n\n\t\t\\begin{align}\n\t\t\t\\eta(T_k[U]) \\leq \\alpha & \\implies \\frac{|E^{-}_{k}[U]|}{|E_{k}[U]|}\n\t\t\t\\leq 0.5                                                                                            \\\\\n\t\t\t                         & \\implies |E^{-}_{k}[U]| \\leq 0.5 \\cdot (|E^{+}_{k}[U]| + |E^{-}_{k}[U]|) \\\\\n\t\t\t                         & \\implies 0.5 \\cdot |E^{+}_{k}[U]| - 0.5 \\cdot |E^{-}_{k}[U]| \\geq 0      \\\\\n\t\t\t\\label{eq:ecpp-nc-contr}\n\t\t\t                         & \\implies |E^{+}_{k}[U]| - |E^{-}_{k}[U]|\n\t\t\t\\geq 0.\n\t\t\\end{align}\n\t\tConsequently $T_k$ will contribute positively to $\\xi(U)$, i.e.\n\t\tin the subgraph induced on $T_k$ by $U$\n\t\tthe number of positive edges is greater or equal than the\n\t\tnumber of negative edges.\n\n\t\tMore generally, due to \\eqref{eq:ecp-v1}-\\eqref{eq:ecp-e1} we have\n\t\t\\begin{gather*}\n\t\t\tz_k = c > 0 \\implies x_{i'j'}^{k} = c \\; \\forall i'j'\n\t\t\t\\in E_k[U],\n\t\t\t% \\\\\n\t\t\t% x_{ij}^{k} = c \\iff z_k = c \\land y_i = 1 \\land y_j = 1,\n\t\t\\end{gather*}\n\t\tmeaning that if $z_k = c$ all and only the variables $x_{ij}^{k}$\n\t\tassociated to edges $e_{ij} \\in E_k$ induced by $U$\n\t\twill get value $c$ (any other $x_{ij}^{k}$ will get value $0$ for\n\t\t\\eqref{eq:ecp-v1}-\\eqref{eq:ecp-v2}).\n\n\t\tCombining this result with \\eqref{eq:ecp-alpha-constraint1} we get\n\t\tagain \\eqref{eq:ecpp-nc-t} and, consequently, \\eqref{eq:ecpp-nc-contr}.\n\t\tTherefore, the contribution of $T_k$ associated to $z_k > 0$ will be\n\n\t\t\\begin{equation}\n\t\t\t\\sum^{}_{ij \\in E^{+}_k } x_{ij}\n\t\t\t\t^{k} - \\sum_{ij \\in E^{-}_k } x_{ij} ^{k} = z_k (|E^{+}_{k}[U]| -\n\t\t\t|E^{-}_{k}[U]|) \\geq 0.\n\t\t\\end{equation}\n\t\tSince $z_k \\in [0, 1]$ the contribution of the same thread in $\\xi(U)$\n\t\twill be greater (if $z_k \\in [0, 1)$) or equal (if $z_k = 1$) to the\n\t\tcontribution of thread $T_k$ in the objective function.\n\n\t\t% can be similarly shown to be\n\t\t% \\emph{non-controversial}; furthermore its positive contribution in the\n\t\t% objective function will be $\\leq$ to $T_k$ contribution in $\\xi(U)$, so\n\t\t% $\\xi(U) \\geq v$.\n\t\\end{proof}\n\n\tThis concludes the proof for \\autoref{th:ecp-mip}.\n\\end{proof}\n\n\\subsubsection{A MIP Model for $\\alpha > 0.5$}\n\nPreviously, we solved the \\acrshort{ECP} for $\\alpha \\in [0, 0.5]$. Solving the problem for $\\alpha \\in [0, 1]$ requires the definition of\nadditional variables and constraints.\n\n\\begin{equation}\n\t\\label{eq:ecp-exact2}\n\t\\text{maximize}\\quad \\sum_{ T_{k} \\in \\mathcal{T}_{C}, \\; C \\in\n\t\t\\mathcal{\\hat{C}} } \\big( \\sum^{}_{ij \\in E^{+}_k } x_{ij}\n\t^{k} - \\sum_{ij \\in E^{-} _k} x_{ij} ^{k} \\big)\n\\end{equation} \\begin{center} subject to \\end{center}\n\\begin{alignat}{3}\n\t\\label{eq:ecp-v12}\n\t                                                                 &                    & x _{ij}^{k}                                                        \\leq y_i \\quad\\quad                   & \\forall ij \\in E_k                        \\\\\n\t\\label{eq:ecp-v22}\n\t                                                                 &                    & x _{ij}^{k}                                                        \\leq y_j \\quad\\quad                   & \\forall ij \\in E_k                        \\\\\n\t\\label{eq:ecp-t2}\n\t                                                                 &                    & x _{ij}^{k}                                                        \\leq z_k \\quad\\quad                   & \\forall ij \\in E_k                        \\\\\n\t\\label{eq:ecp-e2}\n\t                                                                 &                    & x _{ij} ^{k}                                                       \\geq - 2 + y_i + y_j + z_k \\quad\\quad & \\forall ij \\in E_k                        \\\\\n\t\\label{eq:ecp-a-alpha-constraint}\n\t                                                                 &                    & -N_k z_k < \\sum^{}_{ij \\in E^-_k} a_{ij}^{k}  - \\alpha \\sum^{}_{ij\n\t\t\\in E_k}\n\ta_{ij} ^{k}                   \\leq M_{k} (1 - z_{k})  \\quad\\quad & \\forall T_{k} \\in\n\t\\mathcal{T} _{C}, C \\in \\mathcal{\\hat{C}}                                                                                                                                                                                                    \\\\\n\t\\label{eq:ecp-a-ij-g-i-j2}\n\t                                                                 &                    & a_{ij}^{k}                                                         \\geq -1 + y_i + y_j \\quad\\quad        & \\forall ij \\in E_k                        \\\\\n\t\\label{eq:ecp-a-ij-l-i2}\n\t                                                                 &                    & a_{ij}^{k}                                                         \\leq y_i\\quad\\quad                    & \\forall ij \\in E_k                        \\\\\n\t\\label{eq:ecp-a-ij-l-j2}\n\t                                                                 &                    & a_{ij}^{k}                                                         \\leq y_j \\quad\\quad                   & \\forall ij \\in E_k                        \\\\\n\t\\label{eq:ecp-a-domain-2}\n\t                                                                 &                    & 0 \\leq\n\ta_{ij}^{k} \\leq 1  \\quad\\quad                                    & \\forall ij \\in E_k                                                                                                                                                        \\\\\n\t\\label{eq:ecp-vertex-def2}\n\t                                                                 &                    & y _{i}                                                             \\in  \\{0, 1\\} \\quad\\quad              & \\forall i \\in V                           \\\\\n\t\\label{eq:ecp-edge-def2}\n\t                                                                 &                    & 0 \\leq x _{ij} ^{k}                                                \\leq 1 \\quad\\quad                     & \\forall ij \\in E_k                        \\\\\n\t\\label{eq:ecp-z-domain-2}\n\t                                                                 &                    & z _{k}                                                             \\in  \\{0, 1\\} \\quad\\quad              & \\forall T_{k} \\in \\mathcal{T} _{C}, C \\in\n\t\\hat{\\mathcal{C}}\n\\end{alignat}\n\nWhere are $N_k$ and $M_k$ are constants of value $\\alpha (|E_k^{+}| + 1)$ and $(1 -\n\t\\alpha ) (|E^{-}_k| + 1)$, respectively.\n\nNote also that \\eqref{eq:ecp-a-alpha-constraint} involves a strict inequality,\nwhich is not allowed by the definition of\n\\acrshort{MIP} or \\acrshort{LP}. However, this constraint can easily be\ntransformed into a valid\nand equivalent formulation by the means of a small $\\epsilon > 0$ (generally\nwe can choose $\\epsilon < \\alpha \\cdot 10^{-10}$), so that\nit becomes\n\\begin{equation*}\n\t-N_k z_k \\leq \\sum^{}_{ij \\in E^-_k} a_{ij}^{k}  - \\alpha \\sum^{}_{ij\n\t\t\\in E_k}\n\ta_{ij} ^{k} - \\epsilon \\leq M_{k} (1 - z_{k})  \\quad\\quad \\forall T_{k} \\in\n\t\\mathcal{T} _{C}, C \\in \\mathcal{\\hat{C}}.\n\\end{equation*}\nWe will however use \\eqref{eq:ecp-a-alpha-constraint} for simplifying notation.\n\nThis problem requires the introduction of variables $a_{ij}^{k}$,\nassociated to edges \\eqref{eq:ecp-a-domain-2}, which\ngenerally take value one if they are associated to an edge induced by the\nset of vertices considered as solution (i.e. $y_i$ with value one). Note that,\nin order to contribute to the score, $x_{ij}^{k}$ also require that the\ncorresponding thread $T_k \\in S_C(U)$. The\nother variables have the same meaning as in MIP~\\eqref{eq:ecp-exact1}-\\eqref{eq:ecp-thread-def1}.\n\n\\begin{theorem}\n\t\\label{th:ecp-mip}\n\tLet $G = \\{G_k = (V,E_k) \\}_k$ be an \\emph{Interaction Graph} and $\\alpha \\in\n\t\t[0, 1]$. Then\n\n\t\\begin{equation}\n\t\t\\max_{U \\subseteq V} \\xi(U) = \\text{OPT(MIP)}\n\t\\end{equation}\n\n\twhere $OPT(MIP)$ denotes the optimal solution to\n\tMIP~\\eqref{eq:ecp-exact2}-\\eqref{eq:ecp-z-domain-2}.\n\\end{theorem}\n\\begin{proof}\n\tWe will prove the theorem by showing that $LHS \\geq RHS$ and that $LHS \\leq\n\t\tRHS$.\n\t\\begin{claim}\n\t\t\\label{th:claim-v-b-xi2}\n\t\tFor any $U \\subseteq V$, the\n\t\tMIP~\\eqref{eq:ecp-exact2}-\\eqref{eq:ecp-z-domain-2} gets value $\\geq \\xi(U)$.\n\t\\end{claim}\n\n\tIt is easy to see that by choosing $x_{ij}^{k}, \\; y_i, \\; z_k$ as in\n\tClaim~\\ref{th:claim-v-b-xi} and\n\t\\begin{equation*}\n\t\ta_{ij}^{k} = \\begin{cases}\n\t\t\t1 & \\text{if } e_{ij} \\in E_k[U] \\\\\n\t\t\t0 & \\text{otherwise}\n\t\t\\end{cases}\n\t\\end{equation*}\n\tall the constraints of the new formulation are satisfied and\n\tClaim~\\ref{th:claim-v-b-xi2} is consequently proved for\n\tMIP~\\eqref{eq:ecp-exact2}-\\eqref{eq:ecp-z-domain-2}.\n\n\tWe will instead focus on proving the analogous of Claim~\\ref{th:claim-xi-b-v}.\n\t\\begin{claim}\n\t\t\\label{th:claim-xi-b-v2}\n\t\tGiven a feasible solution of\n\t\tMIP~\\eqref{eq:ecp-exact2}-\\eqref{eq:ecp-z-domain-2} with value $v$ we can\n\t\tconstruct $U \\; s.t. \\; \\xi(U) \\geq v$ for any $\\alpha$.\n\t\\end{claim}\n\n\t\\begin{proof}\n\t\tLet $U \\coloneqq \\{ v_i \\; s.t. \\; y_i = 1\\} $. We will not prove\n\t\tsome results in Claim~\\ref{th:claim-xi-b-v} which still hold.\n\n\t\tDue to \\eqref{eq:ecp-a-ij-g-i-j2}-\\eqref{eq:ecp-a-ij-l-j2} we\n\t\thave that\n\t\t\\begin{equation}\n\t\t\ta_{ij}^{k} = 1 \\iff y_i = 1 \\land y_j = 1\n\t\t\\end{equation}\n\t\ti.e. all and only the edges induced by $U$ will have the corresponding\n\t\t$a_{ij}^{k} = 1$. Therefore,\n\t\t\\begin{align}\n\t\t\t\\label{eq:ecpp-a-E-sets}\n\t\t\t|E^{-}_{k}[U]| & = \\sum^{}_{ij \\in E^-_k} a_{ij}^{k}, &\n\t\t\t|E_{k}[U]|     & = \\sum^{}_{ij \\in E_k } a_{ij}^{k}.\n\t\t\\end{align}\n\t\tConsider now a thread $T_k \\in \\mathcal{S}_C(U)$. By definition, we\n\t\thave that\n\t\t\\begin{align}\n\t\t\t\\eta(T_k) \\leq \\alpha & \\implies \\frac{|E^{-}_{k}[U]|}{|E_{k}[U]|} \\leq \\alpha \\\\\n\t\t\t\\label{eq:ecpp-nc-thread2}\n\t\t\t                      & \\implies |E^{-}_{k}[U]| - \\alpha \\cdot\n\t\t\t|E_{k}[U]| \\leq 0.\n\t\t\\end{align}\n\t\tNow suppose $z_k = 0$. This means that\n\t\t\\eqref{eq:ecp-a-alpha-constraint} resolves to\n\t\t\\begin{equation*}\n\t\t\t0 < \\sum^{}_{ij \\in E^-_k} a_{ij}^{k}  - \\alpha \\sum^{}_{ij\n\t\t\t\t\\in E_k}\n\t\t\ta_{ij} ^{k} \\leq M_{k}\n\t\t\\end{equation*}\n\t\tWhich is not satisfied due to \\eqref{eq:ecpp-nc-thread2} and\n\t\t\\eqref{eq:ecpp-a-E-sets}, since they imply that $\\sum^{}_{ij \\in E^-_k} a_{ij}^{k}  - \\alpha \\sum^{}_{ij\n\t\t\t\t\\in E_k}\n\t\t\ta_{ij} ^{k} \\leq 0$. This justifies\n\t\t\\eqref{eq:ecp-a-alpha-constraint}.\n\n\t\tThus, $z_k = 1$. This\n\t\tmeans that the constraint resolves to\n\t\t\\begin{equation*}\n\t\t\t-N_k = -\\alpha (|E^{+}_{k}[U]| + 1)< \\sum^{}_{ij \\in E^-_k} a_{ij}^{k}  -\n\t\t\t\\alpha \\sum^{}_{ij \\in E_k} a_{ij} ^{k}\n\t\t\\end{equation*}\n\t\twhich is satisfied since\n\t\t\\begin{align}\n\t\t\t\\sum^{}_{ij \\in E^-_k} a_{ij}^{k}  - \\alpha \\sum^{}_{ij \\in E_k}\n\t\t\ta_{ij} ^{k} = & |E^{-}_{k}[U]| - \\alpha \\cdot |E_{k}[U]|                \\\\\n\t\t\t=             & (1- \\alpha)|E^{-}_{k}[U]| - \\alpha \\cdot |E^{+}_{k}[U]| \\\\\n\t\t\t\\geq          & - \\alpha \\cdot |E^{+}_{k}[U]|                           \\\\\n\t\t\t>             & - N_k.\n\t\t\\end{align}\n\n\t\tConsequently, because of \\eqref{eq:ecpp-z-iff-xij}, we have that\n\t\t\\begin{equation}\n\t\t\tT_k \\in \\mathcal{S}_C(U) \\iff x_{ij}^{k} = 1 \\; \\forall \\;i, j \\in U\n\t\t\\end{equation}\n\t\tmeaning that each \\emph{non-controversial} $T_k$ will contribute to\n\t\t$\\xi$ and $v$ with the same score, i.e.\n\t\t\\begin{equation*}\n\t\t\t\\sum^{}_{ij \\in E^{+}_k } x_{ij}\n\t\t\t\t^{k} - \\sum_{ij \\in E^{-} _k} x_{ij} ^{k} = |E^{-}_{k}[U]| -\n\t\t\t|E_{k}[U]|.\n\t\t\\end{equation*}\n\n\t\tNow consider $T_k$ \\emph{controversial} and suppose $z_k = 1$. This means that\n\t\t\\eqref{eq:ecp-a-alpha-constraint} resolves to\n\t\t\\begin{equation*}\n\t\t\t-N_k < \\sum^{}_{ij \\in E^-_k} a_{ij}^{k}  - \\alpha \\sum^{}_{ij\n\t\t\t\t\\in E_k}\n\t\t\ta_{ij} ^{k} \\leq 0,\n\t\t\\end{equation*}\n\t\twhere the second inequality is not satisfied due to \\eqref{eq:ecpp-a-E-sets} and by\n\t\tdefinition of \\emph{controversial}. So $z_k$ must be $0$.\n\t\tThen, we have\n\t\t\\begin{align*}\n\t\t\t\\sum^{}_{ij \\in E^-_k} a_{ij}^{k}  - \\alpha \\sum^{}_{ij\n\t\t\t\t\\in E_k}\n\t\t\ta_{ij} ^{k} = & |E^{-}_{k}[U]| - \\alpha \\cdot |E_{k}[U]|                \\\\\n\t\t\t=             & (1- \\alpha)|E^{-}_{k}[U]| - \\alpha \\cdot |E^{+}_{k}[U]| \\\\\n\t\t\t\\leq          & (1- \\alpha )\\cdot |E^{-}_{k}[U]|                        \\\\\n\t\t\t\\leq          & M_k,\n\t\t\\end{align*}\n\t\tthus satisfying \\eqref{eq:ecp-a-alpha-constraint}. Therefore, $x_{ij}^{k} = 0 \\; \\forall \\;i, j, \\in V$ (because of\n\t\t\\eqref{eq:ecp-t2}).\n\t\tThis means that the contribution of a controversial $T_k$ is the same in $\\xi$ and $v$ and,\n\t\tin general, $\\xi(U) = v$, proving the claim.\n\t\\end{proof}\n\n\tDue to Claims~\\ref{th:claim-v-b-xi2} and \\ref{th:claim-xi-b-v2} the theorem\n\tis proved.\n\\end{proof}\n\n\\subsection{A MIP Model for the \\acrshort{D-ECP}}%\n\\label{sub:a_mip_model_for_the_d_ecp}\n\nSimilarly to the \\acrshort{ECP}, here we propose a \\acrshort{MIP} model for\nfinding a solution for the \\acrshort{D-ECP}, $\\alpha \\in [0, 1]$.\n\nFor simplifying notation we define $E_{k} \\coloneqq E(T_{k}), T_{k} \\in\n\t\\mathcal{T}_{C}, C \\in \\mathcal{\\hat{C}}$.\n\n\\begin{equation}\n\t\\label{eq:d-ecp-objective}\n\t\\text{maximize} \\; \\sum_{ T_{k} \\in \\mathcal{T}_{C}, \\; C \\in\n\t\t\\mathcal{\\hat{C}} } \\big( \\sum^{}_{ij \\in E^+_k} x_{ij}\n\t^{k} - \\sum_{ij \\in E^-_k} x_{ij} ^{k} \\big)\n\\end{equation}\n\\begin{center} subject to \\end{center}\n\\begin{alignat}{3}\n\t\\label{eq:d-ecp-a-ij-l-bi}\n\t                                           &                                           & a_{ij}^{k} \\leq b_{i} \\quad\\quad                                              & \\forall ij \\in E_k                        \\\\\n\t\\label{eq:d-ecp-a-ij-l-bj}\n\t                                           &                                           & a_{ij}^{k} \\leq b_{j} \\quad\\quad                                              & \\forall ij \\in E_k                        \\\\\n\t\\label{eq:d-ecp-a-ij-g-ijk}\n\t                                           &                                           & a _{ij} ^{k} \\geq - 1 + b_i + b_j \\quad\\quad                                  & \\forall ij \\in E_k                        \\\\\n\t\\label{eq:d-ecp-alpha-constraint}\n\t                                           &                                           & -N_{k} z_k < \\sum^{}_{ij \\in E^-_k} a_{ij}^{k}  - \\alpha \\sum^{}_{ij \\in E_k}\n\ta_{ij} ^{k}  \\leq M_k (1 - z_k) \\quad\\quad & \\forall T_{k} \\in \\mathcal{T} _{C}, C \\in\n\t\\hat{\\mathcal{C}}                                                                                                                                                                                                  \\\\\n\t\\label{eq:d-ecp-edge-charikar1}\n\t                                           &                                           & x _{ij}^{k}  \\leq y_i \\quad\\quad                                              & \\forall ij \\in E_{k}                      \\\\\n\t\\label{eq:d-ecp-edge-charikar2}\n\t                                           &                                           & x _{ij} ^{k} \\leq y_j \\quad\\quad                                              & \\forall ij \\in E_k                        \\\\\n\t\\label{eq:d-ecp-vertex-charikar1}\n\t                                           &\n\t                                           & \\sum^{}_{i \\in V} y_i = 1\n\t\\quad\\quad\n\t                                           &                                                                                                                                                                       \\\\\n\t\\label{eq:d-ecp-vertex-l-b}\n\t                                           &                                           & y_i \\leq b_i \\quad\\quad                                                       & \\forall i \\in V                           \\\\\n\t\\label{eq:d-ecp-vertex-g-bi-yj}\n\t                                           &                                           & y_i \\geq -1 + b_i + y_j \\quad\\quad                                            & \\forall i,j \\in V                         \\\\\n\t\\label{eq:d-ecp-x-l-sum1}\n\t                                           &\n\t                                           & x_{ij}^{k} \\geq -2 +\n\ta_{ij} ^{k} + z_k + y_i \\quad\\quad         & \\forall ij \\in E_k                                                                                                                                                    \\\\\n\t\\label{eq:d-ecp-x-l-sum2}\n\t                                           &\n\t                                           & x_{ij}^{k} \\geq -2 +\n\ta_{ij} ^{k} + z_k + y_j \\quad\\quad         & \\forall ij \\in E_k                                                                                                                                                    \\\\\n\t\\label{eq:d-ecp-x-l-a}\n\t                                           &                                           & x_{ij} ^{k} \\leq a_{ij} ^{k} \\quad\\quad                                       & \\forall ij \\in E_k                        \\\\\n\t\\label{eq:d-ecp-x-l-z}\n\t                                           &                                           & x_{ij} ^{k} \\leq z_k \\quad\\quad                                               & \\forall T_{k} \\in \\mathcal{T} _{C}, C \\in\n\t\\hat{\\mathcal{C}}                                                                                                                                                                                                  \\\\\n\t\\label{eq:d-ecp-a-ij}\n\t                                           &                                           & a _{ij} ^{k}  \\in \\{0, 1\\} \\quad\\quad                                         & \\forall ij \\in E_k                        \\\\\n\t\\label{eq:d-ecp-b-i}\n\t                                           &                                           & b _{i} \\in \\{0, 1\\} \\quad\\quad                                                & \\forall i \\in V                           \\\\\n\t\\label{eq:d-ecp-y-i}\n\t                                           &                                           & y _{i} \\geq 0 \\quad\\quad                                                      & \\forall i \\in V                           \\\\\n\t\\label{eq:d-ecp-x-ij}\n\t                                           &                                           & x _{ij} ^{k}  \\geq 0 \\quad\\quad                                               & \\forall ij \\in E_k                        \\\\\n\t\\label{eq:d-ecp-z-k}\n\t                                           &                                           & z _{k} \\in \\{0, 1\\} \\quad\\quad                                                & \\forall T_{k} \\in \\mathcal{T} _{C}, C \\in\n\t\\hat{\\mathcal{C}}\n\\end{alignat}\n\nWhere are $N_k$ and $M_k$ are constants of value $\\alpha (|E_k^{+}| + 1)$ and $(1 -\n\t\\alpha ) ( |E^{-}_k| + 1)$, respectively.\nAgain the strict inequality of \\eqref{eq:d-ecp-alpha-constraint} can be\ntransformed into a valid constraint as explained in\n\\autoref{sub:a_mip_model_for_the_ecp}.\n% In this formulation we introduce variables $b_i$, associated to vertices, that\n% take the meaning of variables $y_i$ in\n\n\\begin{theorem}\n\t\\label{th:d-ecp-mip}\n\tLet $G = \\{G_k = (V,E_k) \\}_k$ be an \\emph{Interaction Graph} and $\\alpha \\in\n\t\t[0, 1]$.\n\n\t\\begin{equation}\n\t\t\\max_{U \\subseteq V} \\psi(U) = \\text{OPT(MIP)}\n\t\\end{equation}\n\n\twhere $OPT(MIP)$ denotes the optimal solution to\n\tMIP~\\eqref{eq:d-ecp-objective}-\\eqref{eq:d-ecp-z-k}.\n\\end{theorem}\n\n\\begin{proof}\n\tSimilarly to \\autoref{th:ecp-mip} we will prove this equality by $2$\n\tinequalities: $RHS \\geq LHS$ and $LHS \\geq RHS$\n\n\t\\begin{claim}\n\t\tFor any $U \\subseteq V$, the\n\t\tMIP~\\eqref{eq:d-ecp-objective}-\\eqref{eq:d-ecp-z-k} gets value at least\n\t\t$\\psi(U)$.\n\t\\end{claim}\n\n\t\\begin{proof}\n\t\tLet $c = 1 / |U|$. We construct a feasible solution for\n\t\tMIP~\\eqref{eq:d-ecp-objective}-\\eqref{eq:d-ecp-z-k} as follows:\n\n\t\t\\begin{align}\n\t\t\t\\label{eq:ecpp-y}\n\t\t\ty_i        & = \\begin{cases}\n\t\t\t\tc, & \\text{if } v_{i} \\in U, \\\\\n\t\t\t\t0, & \\text{otherwise,}\n\t\t\t\\end{cases} \\quad & \\forall v_i \\in U                                \\\\\n\t\t\tb_i        & = \\begin{cases}\n\t\t\t\t1, & \\text{if } v_{i} \\in U, \\\\\n\t\t\t\t0, & \\text{otherwise,}\n\t\t\t\\end{cases}\\quad  & \\forall v_i \\in U                                \\\\\n\t\t\t\\label{eq:ecpp-z}\n\t\t\tz_k        & = \\begin{cases}\n\t\t\t\t1, & \\text{if } T_{k} \\in \\mathcal{S}_C(U), \\; C \\in\n\t\t\t\t\\mathcal{\\hat{C}},                                   \\\\\n\t\t\t\t0, & \\text{otherwise,}\n\t\t\t\\end{cases} \\quad & \\forall T_k \\in \\mathcal{T}_C, C \\in\n\t\t\t\\mathcal{\\hat{C}}                                                                                  \\\\\n\t\t\t\\label{eq:ecpp-x}\n\t\t\ta_{ij}^{k} & = \\begin{cases}\n\t\t\t\t1, & \\text{if } e_{ij} \\in E_{k}[U], \\; T_{k} \\in \\mathcal{T} _C, \\; C \\in\n\t\t\t\t\\mathcal{\\hat{C}},                                                         \\\\\n\t\t\t\t0, & \\text{otherwise,}\n\t\t\t\\end{cases} \\quad & \\forall e_{ij} \\in E_k, T_k \\in \\mathcal{T}_C, C\n\t\t\t\\in \\mathcal{\\hat{C}}                                                                              \\\\\n\t\t\tx_{ij}^{k} & = \\begin{cases}\n\t\t\t\tc, & \\text{if } e_{ij} \\in E_{k}[U], \\; T_{k} \\in \\mathcal{S}_C(U), \\; C \\in\n\t\t\t\t\\mathcal{\\hat{C}},                                                           \\\\\n\t\t\t\t0, & \\text{otherwise.}\n\t\t\t\\end{cases}       & \\forall e_{ij} \\in E_k, T_k \\in \\mathcal{T}_C, C\n\t\t\t\\in \\mathcal{\\hat{C}}\n\t\t\\end{align}\n\n\t\t\\eqref{eq:d-ecp-a-ij-l-bi}-\\eqref{eq:d-ecp-a-ij-g-ijk} are easily\n\t\tsatisfied since $a_{ij}^{k} = 1 \\iff b_i = 1 \\land b_j = 1$, meaning\n\t\tthat an edge is induced (thus $a_{ij}^{k} = 1$) if and only if $ v_i,\n\t\t\tv_j \\in U$. The same idea applies to\n\t\t\\eqref{eq:d-ecp-edge-charikar1}-\\eqref{eq:d-ecp-edge-charikar2}.\n\t\t\\eqref{eq:d-ecp-vertex-l-b} is trivial and\n\t\t\\eqref{eq:d-ecp-x-l-a}-\\eqref{eq:d-ecp-x-l-z} hold since\n\t\t$\\mathcal{S}_C(U) \\subseteq \\mathcal{T}_C $. It is also easy to see that\n\t\t\\eqref{eq:d-ecp-vertex-g-bi-yj} is satisfied since we defined $y_i$\n\t\tand $b_i$ s.t. $b_i = 1$ if and only if $y_i = c$. Furthermore, since\n\t\t$y_i = c$ if and only if $\n\t\t\ty_i \\in U$ then\n\t\t\\begin{equation*}\n\t\t\t\\sum^{}_{i \\in V} y_i = \\sum^{}_{i \\in U} c = 1\n\t\t\\end{equation*}\n\t\tand \\eqref{eq:d-ecp-vertex-charikar1} is also satisfied.\n\n\t\tLet us know consider $T_k \\in \\mathcal{S}_C(U)$ which by definition\n\t\timplies $z_k = 1$. Then,\n\t\t\\begin{align}\n\t\t\t\\eta(T_k[U]) \\leq \\alpha & \\implies\n\t\t\t\\frac{|E^{-}_{k}[U]|}{|E_{k}[U]|} \\leq \\alpha               \\\\\n\t\t\t                         & \\implies |E^{-}_{k}[U]| - \\alpha\n\t\t\t(|E_{k}[U]|) \\leq 0.\n\t\t\\end{align}\n\n\t\tThus, due to the definition of $a_{ij}^k$, the second inequality of \\eqref{eq:d-ecp-alpha-constraint} is true;\n\t\tthe first one is also satisfied since\n\t\t\\begin{align}\n\t\t\t\\sum^{}_{ij \\in E^-_k} a_{ij}^{k}  - \\alpha \\sum^{}_{ij \\in E_k}\n\t\t\ta_{ij} ^{k} & = |E^{-}_{k}[U]| - \\alpha \\cdot |E_{k}[U]| \\\\\n\t\t\t            & = (1- \\alpha)|E^{-}_{k}[U]| - \\alpha \\cdot\n\t\t\t|E^{+}_{k}[U]|                                           \\\\\n\t\t\t            & \\geq - \\alpha \\cdot |E^{+}_{k}[U]|         \\\\\n\t\t\t            & > N_k.\n\t\t\\end{align}\n\n\t\t\\eqref{eq:d-ecp-x-l-sum1}-\\eqref{eq:d-ecp-x-l-sum2} are true\n\t\tsince in this case (for $z_k = 1$) by definition $a_{ij}^{k} = 1\n\t\t$ implies $x_{ij}^{k} = c$. If instead $T_k \\not\\in S_c$ and $z_k = 0$ we\n\t\thave that\n\n\t\t\\begin{align}\n\t\t\t\\eta(T_k[U]) > \\alpha & \\implies\n\t\t\t\\frac{|E^{-}_{k}[U]|}{|E_{k}[U]|} > \\alpha                                \\\\\n\t\t\t                      & \\implies |E^{-}_{k}[U]| - \\alpha (|E_{k}[U]|) > 0\n\t\t\\end{align}\n\n\t\tand consequently the first inequality of\n\t\t\\eqref{eq:d-ecp-alpha-constraint} is satisfied. Also\n\t\t\\begin{align}\n\t\t\t\\sum^{}_{ij \\in E^-_k} a_{ij}^{k}  - \\alpha \\sum^{}_{ij \\in E_k}\n\t\t\ta_{ij} ^{k} & = |E^{-}_{k}[U]| - \\alpha \\cdot |E_{k}[U]|\n\t\t\t\\\\ & =\n\t\t\t(1- \\alpha)|E^{-}_{k}[U]| - \\alpha \\cdot |E^{+}_{k}[U]|  \\\\\n\t\t\t            & \\leq (1 -\\alpha) \\cdot |E^{-}_{k}[U]|      \\\\\n\t\t\t            & < M_k.\n\t\t\\end{align}\n\n\t\tThus, also the second inequality is true. Also,\n\t\t\\eqref{eq:d-ecp-x-l-sum1}-\\eqref{eq:d-ecp-x-l-sum2} are trivially\n\t\tsatisfied.\n\n\t\t\\bigskip\n\t\tConsequently an edge contributing to $\\psi(U)$ will also count in the\n\t\tobjective function by $c$. So, for a given thread $T_k \\in \\mathcal{S}_C, C \\in \\mathcal{\\hat{C}}$\n\n\t\t\\begin{align*}\n\t\t\t\\sum^{}_{ij \\in E^+_k} x_{ij} ^{k} - \\sum_{ij \\in E^{-}\n\t\t\t(T_{k})} x_{ij} ^{k} & = \\sum^{}_{ij \\in E^{+}_k[U] } c - \\sum_{ij \\in E^{-}\n\t\t\t_k[U]} c                                                                     \\\\\n\t\t\t                     & = c (|E^{+}_{k}[U]| - |E^{-}_{k}[U]|)                 \\\\\n\t\t\t                     & = \\frac{|E^{+}_{k}[U]| -\n\t\t\t|E^{-}_{k}[U]|}{|U|}.\n\t\t\\end{align*}\n\n\t\tThus, for each thread we have the same contribution to both $\\psi(U)$\n\t\tand the objective function of\n\t\tMIP~\\eqref{eq:d-ecp-objective}-\\eqref{eq:d-ecp-z-k}. Therefore, the sum through\n\t\tall the threads will correspond as well.\n\t\\end{proof}\n\n\t\\begin{claim}\n\t\tGiven a feasible solution of\n\t\tMIP~\\eqref{eq:d-ecp-objective}-\\eqref{eq:d-ecp-z-k} with value $v$ we can\n\t\tconstruct $U \\; s.t. \\; \\psi(U) \\geq v$.\n\t\\end{claim}\n\n\t\\begin{proof}\n\n\t\tLet us define $U \\coloneqq \\{ v_i \\; s.t. \\; y_i \\neq 0\\}$; consider\n\t\t$v_i$ s.t. $y_i \\neq 0$ (if no such vertex exists then the proof is\n\t\ttrivial) and let $c \\coloneqq y_i$. By\n\t\t\\eqref{eq:d-ecp-vertex-g-bi-yj} and \\eqref{eq:d-ecp-vertex-l-b}\n\t\twe have that\n\t\t\\begin{gather}\n\t\t\t\\label{eq:d-ecpp-y-in}\n\t\t\t\\forall v_j \\in V, \\; y_j \\in \\{ 0, c\\}, \\\\\n\t\t\t\\forall i, j \\in V, \\; b_i = 1 \\land b_j = 1 \\implies y_i = y_j =\n\t\t\tc.\n\t\t\\end{gather}\n\n\t\tFurthermore, due to \\eqref{eq:d-ecp-a-ij-l-bi}-\\eqref{eq:d-ecp-a-ij-g-ijk} we\n\t\thave that\n\t\t\\begin{equation}\n\t\t\t\\label{eq:d-ecpp-a-iff}\n\t\t\ta_{ij}^{k} = 1 \\iff b_i = 1 \\land b_j = 1.\n\t\t\\end{equation}\n\n\t\tNow consider some $x_{ij}^{k} > 0 $. By \\eqref{eq:d-ecp-x-l-a}\n\t\t$x_{ij}^{k} > 0$ implies $a _{ij}^{k} = 1$ and, thanks to\n\t\t\\eqref{eq:d-ecp-x-l-z}, $x_{ij}^{k} > 0$ implies $z_k = 1$. Thus, combining\n\t\tthis to the results in \\eqref{eq:d-ecpp-y-in} and\n\t\t\\eqref{eq:d-ecpp-a-iff}\n\t\t\\begin{gather}\n\t\t\t\\label{eq:d-ecpp-x-impl}\n\t\t\tx_{ij}^{k} > 0 \\implies a_{ij}^{k} = 1 \\land z_k =1, \\\\\n\t\t\t\\label{eq:d-ecpp-z-impl}\n\t\t\tz_k = 1 \\implies x_{i'j'}^{k} = c, \\; \\forall i', j' \\in U, \\\\\n\t\t\t\\label{eq:d-ecpp-za-impl}\n\t\t\tz_k = 1 \\land a_{ij}^{k} = 1 \\implies x_{ij}^{k} = c.\n\t\t\\end{gather}\n\t\tThis means that if exists $ x_{ij}^{k} > 0$ then all the variables\n\t\t$x_{i'j'}^{k}$ associated to edges induced by $U$ have value $c$.\n\t\tAlso, since we have that $z_k = 1$, \\eqref{eq:d-ecp-alpha-constraint}\n\t\twill correspond to\n\n\t\t\\begin{equation}\n\t\t\t\\sum^{}_{ij \\in E^-_k} a_{ij}^{k}  - \\alpha \\sum^{}_{ij \\in E_k}\n\t\t\ta_{ij} ^{k} \\leq 0.\n\t\t\\end{equation}\n\t\tWe showed in \\eqref{eq:d-ecpp-x-impl} and \\eqref{eq:d-ecpp-za-impl} that $a_{ij}^{k} = 1 \\land z_k\n\t\t\t= 1$ if and only if $x_{ij}^{k} > 0 $. In other other words, the edges contributing to the objective\n\t\tfunction are part of a \\emph{non-controversial} subgraph, i.e. the\n\t\tcorresponding thread $T_k \\in\n\t\t\t\\mathcal{S}_C(U)$ and it will contribute to $\\psi(U)$.\n\n\t\tNow suppose exists $ T_k \\in \\mathcal{S}_C(U), \\; C \\in \\mathcal{\\hat{C}},\n\t\t\t\\; s.t. \\; z_k = 0$. By definition of $\\mathcal{S}_C(U)$ we have that\n\n\t\t\\begin{align}\n\t\t\t\\eta(T_k[U]) \\leq \\alpha & \\implies |E^{-}_{k}[U]| - \\alpha |E_{k}[U]|\n\t\t\t\\\\\n\t\t\t                         & \\implies \\sum^{}_{ij \\in E^-_k}\n\t\t\ta_{ij}^{k}  - \\alpha \\sum^{}_{ij \\in E_k}\n\t\t\ta_{ij} ^{k} \\leq 0,\n\t\t\\end{align}\n\t\tbecause $a_{ij}^{k} = 1$ for all edges induced by $U$. But, if $z_k =\n\t\t\t0$ then constraint \\eqref{eq:d-ecp-alpha-constraint} is violated,\n\t\tand this would be a \\emph{contradiction}. So no such $T_k$ exists and $T_k\n\t\t\t\\in \\mathcal{S}_C(U) \\iff z_k = 1$.\n\n\t\tThis means that a thread contributing to the objective function of\n\t\tMIP~\\eqref{eq:d-ecp-objective}-\\eqref{eq:d-ecp-z-k} also counts towards\n\t\t$\\psi(U)$. Due to \\eqref{eq:d-ecpp-z-impl} we can then write, for\n\t\t$T_k \\in \\mathcal{S}_C(U)$\n\n\t\t\\begin{align*}\n\t\t\t\\sum^{}_{ij \\in E^+_k} x_{ij} ^{k} - \\sum_{ij \\in E^{-}\n\t\t\t(T_{k})} x_{ij} ^{k} & = \\sum^{}_{ij \\in E^{+}_k[U] } c - \\sum_{ij \\in E^{-}\n\t\t\t_k[U]} c                                                                     \\\\\n\t\t\t                     & = c (|E^{+}_{k}[U]| - |E^{-}_{k}[U]|)                 \\\\\n\t\t\t                     & = \\frac{|E^{+}_{k}[U]| -\n\t\t\t|E^{-}_{k}[U]|}{|U|}.\n\t\t\\end{align*}\n\n\t\tThus, each threads equally contributes to $\\psi(U)$ and the objective\n\t\tfunction of MIP~\\eqref{eq:d-ecp-objective}-\\eqref{eq:d-ecp-z-k}.\n\t\tTherefore, $\\psi(U) \\geq v$.\n\t\\end{proof}\n\n\tThis concludes the proof of the theorem.\n\n\\end{proof}\n\n\\section{Heuristics}%\n\\label{sub:approximation_algorithms}\n\nWe now present some heuristic algorithms for solving the \\acrshort{ECP} and\n\\acrshort{D-ECP}. We start by describing how $\\xi(U)$ and $\\psi(U)$ can be\ncomputed in practice.\n\nLet $\\textsc{Score}_{\\xi} (U)$ and $\\textsc{Score}_{\\psi} (U)$ be the functions\ncomputing the \\emph{Echo Chamber Score} and \\emph{Densest-Echo Chamber Score}\nof $U$, respectively. These subroutines iterate over the edges of the vertices\nin $U$, ignoring those that are not induced by $U$, and counting for each\nthread $T \\in \\mathcal{T}_{C}, C \\in \\mathcal{\\hat{C}} $ the number of edges\nand negative edges to see which are \\emph{controversial}, then calculating\ntheir contributions (\\autoref{alg:score_xi} shows in detail\n$\\textsc{Score}_\\xi$; $\\textsc{Score}_\\psi$ can simply be computed as\n$\\textsc{Score}_\\xi(U)/|U|$).  Note that this algorithm operates also on the\nweights $w_{ij}^{k}$ of the edges. This is something that is \"implicitely\" done\nin the \\acrshort{MIP}s, as the sums iterate over positive and negative edges.\n\n\\begin{algorithm}\n\t\\SetAlgoLined\n\t\\KwIn{Interaction graph $G = \\{G_k = (V,E_k) \\}_k$, a set of users $U\n\t\t\t\\subseteq V$, $\\alpha \\in [0, 1]$}\n\t\\KwResult{$\\xi(U)$}\n\t$N^{+} (T) \\leftarrow 0, \\; N^{-} (T) \\leftarrow 0\\; $ for all threads $T\n\t\t\\in \\mathcal{T}_{C}, C \\in \\mathcal{\\hat{C}}   $ \\;\n\n\t\\ForEach{$v_{i} \\in U$}{\n\t\t$S_i \\leftarrow$ edges starting from $v_{i} $ \\;\n\t\t\\ForEach{$e_{ij} \\in S_i$ \\textbf{if} $v_{j} \\in U$}{\n\t\t\t$T_{ij}  \\leftarrow$ thread of $e_{ij} $ \\;\n\t\t\t$w_{ij}  \\leftarrow$ weight of $e_{ij} $ \\;\n\n\t\t\t\\uIf{$w_{ij} \\geq 0$}{\n\t\t\t\t$N^{+}(T_{ij} ) \\leftarrow N^{+}(T_{ij} ) + 1$ \\;\n\t\t\t}\\Else{\n\t\t\t\t$N^{-}(T_{ij} ) \\leftarrow N^{-}(T_{ij} ) + 1$ \\;\n\t\t\t}\n\n\t\t}\n\t}\n\n\t$\\xi(U) \\leftarrow 0$ \\;\n\t$\\eta(T) \\leftarrow\\frac{N^{-}(T)}{(N^{-}(T) + N^{+} (T))} \\; $ for all threads $T\n\t\t\\in \\mathcal{T}_{C}, C \\in \\mathcal{\\hat{C}}   $  \\;\n\t\\ForEach{$T\\in \\mathcal{T}_{C}, C \\in \\mathcal{\\hat{C}}$ \\textbf{if}\n\t\t$ \\eta(T) \\leq \\alpha $}{\n\t\t$\\xi(U) \\leftarrow \\xi(U) + N^{+}(T) - N^{-}(T)$\n\t}\n\t\\Return $\\xi(U)$ \\;\n\n\t\\caption{The $\\textsc{Score}_{\\xi}  $ subroutine}\n\t\\label{alg:score_xi}\n\\end{algorithm}\n\nWe present our algorithms focusing on \\acrshort{ECP} in detail. They can generally be\nadapted for solving the \\acrshort{D-ECP} by replacing calls to\n$\\textsc{Score}_{\\xi}$ with $\\textsc{Score}_{\\psi}$.\n\n\\subsection{The $\\beta$-Algorithm}%\n\\label{ssub:the_beta_approach}\n\nThe $\\beta$-algorithm is an heuristic for the \\acrshort{ECP}. The\n$\\beta$-algorithm (\\autoref{alg:algorithm_beta}) constructs a set of users $U$ by\niteratively adding the node which increases the most the score or removing from\n$U$ the one which contributes the least, stopping when the score cannot be\nincreased by adding a node. The frequencies of addition and removal are regulated\nthrough a parameter $\\beta \\in [0, 1]$ (for smaller values a higher density is to be expected,\ngenerally).\n\n$U$ is initialized by sampling one node from the graph. There are two possible\napproaches in doing that: one is uniformly;\nthe other is using probabilities proportional to the number\nof positive edges each node has.\n\n\\begin{algorithm}\n\t% \\KwIn{Interaction graph G, $\\alpha \\in [0,1]$} \\;\n\t\\SetAlgoLined\n\t% \\KwResult{Write here the result }\n\t$U = \\{$ a single random node $\\}$\\;\n\t$\\xi(U) = 0$ \\;\n\t\\While{ $\\exists \\; v_{j} \\; s.t. \\; \\textsc{Score}_{\\xi} (U \\cup \\; \\{\n\t\t\tv_{j} \\} )> \\xi(U)$}{\n\t\t$N(U) \\leftarrow $ neighbours of vertices in $U$ in the graph $G$ \\;\n\t\tFlip a coin which gives head with probability $\\beta$ \\;\n\t\tIf head\\:  {\n\t\t\t$U \\leftarrow U \\cup \\; \\{ \\arg\\max_{v_{j} \\in N(U)}\n\t\t\t\t\\textsc{Score}_{\\xi} (U \\cup \\;\n\t\t\t\t\\{ v_{j} \\}) \\}$ \\;\n\t\t}\n\n\t\telse\\: {\n\t\t\t$U \\leftarrow U \\setminus \\{ \\arg\\max_{v_{j} \\in U }\n\t\t\t\t\\textsc{Score}_{\\xi} (U \\setminus \\{ v_{j} \\}) \\}$ \\;\n\t\t}\n\n\t}\n\t\\Return $\\textsc{Score}_{\\xi} (U)$ \\;\n\t\\caption{$\\beta$-algorithm}\n\t\\label{alg:algorithm_beta}\n\\end{algorithm}\n\nIn addition, one may also want to ignore a node when it is removed for the\nnext iterations, in order to prevent the algorithm from repeatedly adding\nand taking out from $U$ the same vertex.\n\nThe result is clearly dependent on the choice of the initial node. For this\nreason the process should be repeated for different initial nodes.\n\nOne of the limitations of this approach is that the algorithm will only find\nsets of users that are connected in the original graph. This is due to the fact\nthat it will never add a node which is not connected to any of the vertices in\n$U$, as it produces an increase of the score equal to $0$.\n\n\\subsection{Peeling Algorithm}%\n\\label{ssub:peeling_algorithm}\n\nInspired to the greedy algorithm proposed in \\cite{charikar2000greedy}, the\npeeling\nalgorithm starts by considering a set $U = V$,\niteratively removing the worst nodes (\\autoref{alg:algorithm_peeling}).\n\n\\begin{algorithm}\n\t\\SetAlgoLined\n\t% \\KwResult{Write here the result }\n\t$U = V$\\;\n\t$S = \\textsc{Score}_{\\xi}(U)$ \\;\n\t\\While{$U \\neq \\emptyset$ }{\n\t\t$v = \\arg\\max_{v_{j} \\in U }\n\t\t\t\\textsc{Score}_{\\xi} (U \\setminus \\{ v_{j} \\})$ \\; $U \\leftarrow U \\setminus \\{ v \\}$ \\;\n\n\t\t$S_i = \\textsc{Score}_{\\xi} (U) $ \\;\n\t}\n\t\\Return $\\arg\\max_{i}S_i$ \\;\n\n\t\\caption{Peeling algorithm}\n\t\\label{alg:algorithm_peeling}\n\\end{algorithm}\n\nIf many nodes produce the same score, then one of them is\nrandomly selected (or, alternatively, the one which has the highest fraction of\nnegative edges).\n\n\\subsection{Rounding Algorithm}%\n\\label{ssub:rounding_algorithm}\n\nThis algorithm reconstructs a solution starting from the results of the\nrelaxation of the exact models and is again inspired by the algorithm for\nreconstructing the exact solution from the \\acrshort{LP} model in\n\\cite{charikar2000greedy}.\n\nMore specifically, our relaxation of\nMIP~\\eqref{eq:ecp-exact2}-\\eqref{eq:ecp-z-domain-2} replaces constraints\n\\eqref{eq:ecp-vertex-def2} and \\eqref{eq:ecp-z-domain-2} with\n\\begin{gather}\n\t0 \\leq y_i \\leq 1, \\\\\n\t0 \\leq z_i \\leq 1.\n\\end{gather}\nWe now have to solve an \\acrshort{LP} problem.\n\nLet $\\tilde{E}$ be the sequence of edges ordered in descending order by $x_{ij}\n\t\t^{k} $. The algorithm (\\autoref{alg:algorithm_rounding}) iterates over\nthe edges in $\\tilde{E}$, adding them to a \\emph{dummy} graph $\\hat{G}$, also eventually\nadding incident nodes if not already present. At each iteration it computes\nthe score of the vertices in the graph $\\hat{G}$ and the score\nof the vertices of each component in the graph, keeping track of the best\nresult.\n\n\\begin{algorithm}\n\t\\SetAlgoLined\n\tSolve the relaxation of MIP~\\eqref{eq:ecp-exact2}-\\eqref{eq:ecp-z-domain-2}\n\t\\;\n\t$\\hat{G} \\leftarrow $ empty graph \\;\n\t$\\hat{V} \\leftarrow $ vertices of $\\hat{G}$ \\;\n\t$S = 0$\n\n\t\\ForEach{ $e_{ij}^{k} \\in \\tilde{E}$ in descending order of $x_{ij}^{k}$ }{\n\t\t$\\hat{V} \\leftarrow \\hat{V} \\bigcup \\{ v_{i} \\}$ \\textbf{if} $v_i\n\t\t\t\\not\\in \\hat{V}$ \\;\n\t\t$\\hat{V} \\leftarrow \\hat{V} \\bigcup \\{ v_{j} \\}$ \\textbf{if} $v_j\n\t\t\t\\not\\in \\hat{V}$ \\;\n\n\t\t$S \\leftarrow \\max(S, \\; \\textsc{Score}_{\\xi}(\\hat{V})  )$\n\n\t\t\\ForEach{component $C$ in $\\hat{G}$}{\n\t\t\t$S \\leftarrow \\max(S, \\; \\textsc{Score}_{\\xi}(C)  )$\n\t\t}\n\n\t}\n\n\t\\Return S \\;\n\t\\caption{Rounding algorithm}\n\t\\label{alg:algorithm_rounding}\n\\end{algorithm}\n\nThe motivation for the algorithm can be seen in\nFigures~\\ref{fig:rounding-original}-\\ref{fig:rounding-relaxed}: the problem\nrelaxation involves a solution whose value assigned to the edges can be used to\nfind subgraphs with many positive edges by using each separate component as set\nof users $U$.\n\n\\begin{figure}\n\t\\begin{center}\n\t\t\\begin{subfigure}[b]{0.4\\textwidth}\n\t\t\t\\centering\n\t\t\t\\tikzfig{tex/tikz/rounding_original_t1}\n\t\t\t\\caption{$T_1$}\n\t\t\t\\label{fig:rounding-original-t1}\n\t\t\\end{subfigure}\n\t\t\\begin{subfigure}[b]{0.4\\textwidth}\n\t\t\t\\centering\n\t\t\t\\tikzfig{tex/tikz/rounding_original_t2}\n\t\t\t\\caption{$T_2$}\n\t\t\t\\label{fig:rounding-original-t2}\n\t\t\\end{subfigure}\n\t\\end{center}\n\t\\caption{Example original \\emph{Interaction Graph} $G$}\n\t\\label{fig:rounding-original}\n\\end{figure}\n\\begin{figure}\n\t\\begin{center}\n\t\t\\begin{subfigure}[b]{0.4\\textwidth}\n\t\t\t\\centering\n\t\t\t\\tikzfig{tex/tikz/rounding_integer_t1}\n\t\t\t\\caption{$T_1$}\n\t\t\t\\label{fig:rounding-integer-t1}\n\t\t\\end{subfigure}\n\t\t\\begin{subfigure}[b]{0.4\\textwidth}\n\t\t\t\\centering\n\t\t\t\\tikzfig{tex/tikz/rounding_integer_t2}\n\t\t\t\\caption{$T_2$}\n\t\t\t\\label{fig:rounding-original-t2}\n\t\t\\end{subfigure}\n\t\\end{center}\n\t\\caption{Exact solution of the example in \\autoref{fig:rounding-original},\n\t\t$\\alpha = 0.4$}\n\t\\label{fig:rounding-integer}\n\\end{figure}\n\\begin{figure}\n\t\\begin{center}\n\t\t\\begin{subfigure}[b]{0.4\\textwidth}\n\t\t\t\\centering\n\t\t\t\\scalebox{0.8}{\n\t\t\t\t\\tikzfig{tex/tikz/rounding_relaxed_t1}\n\t\t\t}\n\t\t\t\\caption{$T_1$, where $z_1 = 0.66$}\n\t\t\t\\label{fig:rounding-relaxed-t1}\n\t\t\\end{subfigure}\n\t\t\\begin{subfigure}[b]{0.4\\textwidth}\n\t\t\t\\centering\n\t\t\t\\scalebox{0.8}{\n\t\t\t\t\\tikzfig{tex/tikz/rounding_relaxed_t2}\n\t\t\t}\n\t\t\t\\caption{$T_2$, where $z_2 = 1.0$}\n\t\t\t\\label{fig:rounding-relaxed-t2}\n\t\t\\end{subfigure}\n\t\\end{center}\n\t\\caption{Solution of the relaxation of $G$ of\n\t\t\\autoref{fig:rounding-original}, $\\alpha = 0.4$}\n\t\\label{fig:rounding-relaxed}\n\\end{figure}\n\nWhile one may think from these examples that the relaxation trivially assigns\nnon-zero values only to positive edges, \\autoref{fig:rounding-original2} shows\na case in which a negative edge, $e_{31}$, gets the value of $1$. Furthermore,\nin this example the algorithm is able to reconstruct the exact solution of the problem.\n\n\\begin{figure}\n\t\\centering\n\t\\tikzfig{tex/tikz/rounding_original2}\n\t\\caption[Example of rounding algorithm finding the exact solution]{Another\n\t\t\\emph{Interaction graph} example, with only one thread. In\n\t\tthis case the rounding algorithm is able to find the exact solution by\n\t\tselecting all the nodes except for $v_4$. In the result of the\n\t\trelaxation all the edges except for $e_{42}$ get the value of $1$.}%\n\t\\label{fig:rounding-original2}\n\\end{figure}\n\n\\section{Alternative Formulations}%\n\\label{sec:alternative-formulations}\n\nDue to the intrinsic complexity of the problems\n(\\autoref{ch:complexity}) we define variants of\nthe \\acrshort{ECP} and \\acrshort{D-ECP} problems, for some of which we are also able to find an exact solution.\n\nFor these new problems we need to define new graphs, obtained by preprocessing\nthe \\emph{interaction graph}.\n\n\\subsection{The \\acrlong{PA} Graph}%\n\\label{sub:pa-graph}\n\nLet $G = \\{G_k = (V,E_k) \\}_k$ be the \\emph{interaction graph}, let $E_k$ and\n$E^-_k$ denote the edges and negative edges in thread $T_k$,\nrespectively. We define $\\delta(v_{i}, v_{j})$ and\n$\\delta^{-} (v_{i}, v_{j})$ to be the sum of the edges and negative edges, respectively,\nassociated to controversial contents between vertices $v_{i} $ and $v_{j}\n$, i.e.\\\n\n\\begin{align}\n\t\\label{eq:}\n\t\\delta(v_{i}, v_{j})   & = \\sum^{}_{T_k \\in \\mathcal{T}_C, C \\in\n\t\\mathcal{\\hat{C}} } ( \\sum^{}_{e_{ij} \\in E_k} w_{ij} + \\sum^{}_{e_{ji} \\in\n\tE_k} w_{ji} ),\n\t\\\\\n\t\\delta^-(v_{i}, v_{j}) & = \\sum^{}_{T_k \\in \\mathcal{T}_C, C \\in\n\t\\mathcal{\\hat{C}} } ( \\sum^{}_{e_{ij} \\in E^-_k} w_{ij} + \\sum^{}_{e_{ji} \\in\n\tE^-_k} w_{ji} ).\n\\end{align}\n\n\\bigskip\n\nThe \\acrfull{PA} graph $G_P = (V_{P}, E_{P}) $ is constructed as follows from\n$G$:\n\n\\begin{itemize}\n\t\\item For any vertex $v_{i} \\in V$ add a corresponding vertex in $V_{P} $.\n\t\\item For any pair of vertices $v_i, v_j$ in $G$ let $\\eta(v_i,v_j)\n\t\t      \\coloneqq \\frac{\\delta^{-} (v_i,v_j)}{\\delta (v_i,v_j)} $. If\n\t      $\\eta(v_i,v_j) \\leq \\alpha $, add a positive edge between $v_{i} $ and\n\t      $v_{j} $ in $G_{P} $. If, instead, $\\eta(v_i,v_j) > \\alpha $ or $\\delta(v_{i}, v_{j}) =\n\t\t      0$ then don't add any edge between the two vertices.\n\t      % \\item don't add any edge otherwise between $v_{i} $ and $v_{j} $\n\\end{itemize}\n\nThe problem then is finding the Densest Subgraph of $G_P$, i.e., if $E_{P} [U]$\nis the set of edges induced on $G_P$ by $U \\subseteq V$, finding $U$ maximizing\n\n\\begin{equation}\n\t\\xi(U) = \\frac{|E_{P} [U]|}{|U|}.\n\\end{equation}\n\n\\subsection{The \\acrlong{TPA} Graph}%\n\\label{ssub:the_tpa_graph}\n\nDifferently from the previous method, in this case edges are aggregated\nseparately for each thread.\n\n\\bigskip\n\nMore specifically, given an \\emph{interaction graph} $G = \\{G_k = (V,E_k) \\}_k$,\nlet $E(T)$ and\n$E^-(T)$ denote the edges and negative edges in thread $T$,\nrespectively. We define $\\delta_{T}(v_{i}, v_{j})$ and\n$\\delta^{-} _{T}(v_{i}, v_{j})$ to be the sum of the edges and negative edges, respectively,\nassociated to thread $T$ between vertices $v_{i} $ and $v_{j} $, being $T \\in\n\t\\mathcal{T}_{C}, C \\in \\mathcal{\\hat{C}}$, i.e.\n\n\\begin{align}\n\t\\label{eq:}\n\t\\delta_T(v_{i}, v_{j})   & = \\sum^{}_{e_{ij} \\in E(T)} w_{ij} + \\sum^{}_{e_{ji} \\in\n\tE(T)} w_{ji},\n\t\\\\\n\t\\delta^-_T(v_{i}, v_{j}) & =  \\sum^{}_{e_{ij} \\in E^-(T)} w_{ij} + \\sum^{}_{e_{ji} \\in\n\tE^-(T)} w_{ji}.\n\\end{align}\n\nWe will produce a graph, the \\acrfull{TPA} Graph\n\\begin{equation*}\n\tG_{TP} = (V_{TP}, E_{TP}),\n\\end{equation*}\nthat, differently from the \\acrshort{PA} Graph, is a multiplex\ngraph (each layer representing a thread). The construction of the\n\\acrshort{TPA} Graph is as follows:\n\n\\begin{itemize}\n\t\\item For any vertex $v_{i} \\in V$ add a corresponding vertex in $V_{P} $.\n\t\\item For any thread $T \\in\n\t\t      \\mathcal{T}_{C}, C \\in \\mathcal{\\hat{C}}$ we add a layer $T$ to\n\t      $G_{TP}$.\n\t\\item For any thread $T \\in\n\t\t      \\mathcal{T}_{C}, C \\in \\mathcal{\\hat{C}}$ and pair of vertices\n\t      $v_i, v_j$ in $G$, let $\\eta_{T}(v_i,v_j)\n\t\t      \\coloneqq \\frac{\\delta^{-} _{T}(v_i,v_j)}{\\delta _{T}(v_i,v_j)} $. If\n\t      $\\eta_{T}(v_i,v_j) \\leq \\alpha $ add a positive edge between $v_{i} $ and\n\t      $v_{j} $ in $G_{TP} $, in the layer associated to thread $T$.\n\t      % \\item don't add any edge otherwise between $v_{i} $ and $v_{j} $\n\\end{itemize}\n\nWe can then solve on $G_{TP}$:\n\n\\begin{enumerate}\n\t\\item The Densest Subgraph Problem (or, equivalently, the\n\t      \\acrshort{DCS}-MM), which we will refer to as the Densest\n\t      \\acrlong{TPA} (D-\\acrshort{TPA}) Problem\n\t      (\\autoref{sub:densest_subgraphs}).\n\t\\item The \\acrshort{O2BFF} Problem, more specifically \\acrshort{O2BFF}-AM,\n\t      which we will denote as \\acrshort{O2BFF} \\acrlong{TPA}\n\t      (\\acrshort{O2BFF}-\\acrshort{TPA}) Problem\n\t      (\\autoref{sub:the_o_2_bff_problem}).\n\\end{enumerate}\n", "meta": {"hexsha": "e2415ed73bb5b6a2b8b10d32d0e3cefaa3b88765", "size": 50755, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/methods.tex", "max_stars_repo_name": "morpheusthewhite/master-thesis", "max_stars_repo_head_hexsha": "2ab4c0509a119d7b5f332b842a4101470a884351", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-15T14:01:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-15T14:01:29.000Z", "max_issues_repo_path": "tex/methods.tex", "max_issues_repo_name": "morpheusthewhite/master-thesis", "max_issues_repo_head_hexsha": "2ab4c0509a119d7b5f332b842a4101470a884351", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/methods.tex", "max_forks_repo_name": "morpheusthewhite/master-thesis", "max_forks_repo_head_hexsha": "2ab4c0509a119d7b5f332b842a4101470a884351", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.0354924579, "max_line_length": 240, "alphanum_fraction": 0.5182937642, "num_tokens": 17464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979746, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.34661903402188093}}
{"text": "% language=uk\n\n\\environment luatex-style\n\n\\startcomponent luatex-math\n\n\\startchapter[reference=math,title={Math}]\n\n\\topicindex {math}\n\nThe handling of mathematics in \\LUATEX\\ differs quite a bit from how \\TEX82 (and\ntherefore \\PDFTEX) handles math. First, \\LUATEX\\ adds primitives and extends some\nothers so that \\UNICODE\\ input can be used easily. Second, all of \\TEX82's\ninternal special values (for example for operator spacing) have been made\naccessible and changeable via control sequences. Third, there are extensions that\nmake it easier to use \\OPENTYPE\\ math fonts. And finally, there are some\nextensions that have been proposed or considered in the past that are now added\nto the engine.\n\n\\section{Math styles}\n\n\\subsection{\\lpr {mathstyle}}\n\n\\topicindex {math+styles}\n\nIt is possible to discover the math style that will be used for a formula in an\nexpandable fashion (while the math list is still being read). To make this\npossible, \\LUATEX\\ adds the new primitive: \\lpr {mathstyle}. This is a \\quote\n{convert command} like e.g. \\prm {romannumeral}: its value can only be read,\nnot set.\n\nThe returned value is between 0 and 7 (in math mode), or $-1$ (all other modes).\nFor easy testing, the eight math style commands have been altered so that the can\nbe used as numeric values, so you can write code like this:\n\n\\starttyping\n\\ifnum\\mathstyle=\\textstyle\n    \\message{normal text style}\n\\else \\ifnum\\mathstyle=\\crampedtextstyle\n    \\message{cramped text style}\n\\fi \\fi\n\\stoptyping\n\nSometimes you won't get what you expect so a bit of explanation might help to\nunderstand what happens. When math is parsed and expanded it gets turned into a\nlinked list. In a second pass the formula will be build. This has to do with the\nfact that in order to determine the automatically chosen sizes (in for instance\nfractions) following content can influence preceding sizes. A side effect of this\nis for instance that one cannot change the definition of a font family (and\nthereby reusing numbers) because the number that got used is stored and used in\nthe second pass (so changing \\type {\\fam 12} mid|-|formula spoils over to\npreceding use of that family).\n\nThe style switching primitives like \\prm {textstyle} are turned into nodes so the\nstyles set there are frozen. The \\prm {mathchoice} primitive results in four\nlists being constructed of which one is used in the second pass. The fact that\nsome automatic styles are not yet known also means that the \\lpr {mathstyle}\nprimitive expands to the current style which can of course be different from the\none really used. It's a snapshot of the first pass state. As a consequence in the\nfollowing example you get a style number (first pass) typeset that can actually\ndiffer from the used style (second pass). In the case of a math choice used\nungrouped, the chosen style is used after the choice too, unless you group.\n\n\\startbuffer[1]\n    [a:\\mathstyle]\\quad\n    \\bgroup\n    \\mathchoice\n        {\\bf \\scriptstyle       (x:d :\\mathstyle)}\n        {\\bf \\scriptscriptstyle (x:t :\\mathstyle)}\n        {\\bf \\scriptscriptstyle (x:s :\\mathstyle)}\n        {\\bf \\scriptscriptstyle (x:ss:\\mathstyle)}\n    \\egroup\n    \\quad[b:\\mathstyle]\\quad\n    \\mathchoice\n        {\\bf \\scriptstyle       (y:d :\\mathstyle)}\n        {\\bf \\scriptscriptstyle (y:t :\\mathstyle)}\n        {\\bf \\scriptscriptstyle (y:s :\\mathstyle)}\n        {\\bf \\scriptscriptstyle (y:ss:\\mathstyle)}\n    \\quad[c:\\mathstyle]\\quad\n    \\bgroup\n    \\mathchoice\n        {\\bf \\scriptstyle       (z:d :\\mathstyle)}\n        {\\bf \\scriptscriptstyle (z:t :\\mathstyle)}\n        {\\bf \\scriptscriptstyle (z:s :\\mathstyle)}\n        {\\bf \\scriptscriptstyle (z:ss:\\mathstyle)}\n    \\egroup\n    \\quad[d:\\mathstyle]\n\\stopbuffer\n\n\\startbuffer[2]\n    [a:\\mathstyle]\\quad\n    \\begingroup\n    \\mathchoice\n        {\\bf \\scriptstyle       (x:d :\\mathstyle)}\n        {\\bf \\scriptscriptstyle (x:t :\\mathstyle)}\n        {\\bf \\scriptscriptstyle (x:s :\\mathstyle)}\n        {\\bf \\scriptscriptstyle (x:ss:\\mathstyle)}\n    \\endgroup\n    \\quad[b:\\mathstyle]\\quad\n    \\mathchoice\n        {\\bf \\scriptstyle       (y:d :\\mathstyle)}\n        {\\bf \\scriptscriptstyle (y:t :\\mathstyle)}\n        {\\bf \\scriptscriptstyle (y:s :\\mathstyle)}\n        {\\bf \\scriptscriptstyle (y:ss:\\mathstyle)}\n    \\quad[c:\\mathstyle]\\quad\n    \\begingroup\n    \\mathchoice\n        {\\bf \\scriptstyle       (z:d :\\mathstyle)}\n        {\\bf \\scriptscriptstyle (z:t :\\mathstyle)}\n        {\\bf \\scriptscriptstyle (z:s :\\mathstyle)}\n        {\\bf \\scriptscriptstyle (z:ss:\\mathstyle)}\n    \\endgroup\n    \\quad[d:\\mathstyle]\n\\stopbuffer\n\n\\typebuffer[1]\n\n% \\typebuffer[2]\n\nThis gives:\n\n\\blank $\\displaystyle \\getbuffer[1]$ \\blank\n\\blank $\\textstyle    \\getbuffer[1]$ \\blank\n\nUsing \\prm {begingroup} \\unknown\\ \\prm {endgroup} instead gives:\n\n\\blank $\\displaystyle \\getbuffer[2]$ \\blank\n\\blank $\\textstyle    \\getbuffer[2]$ \\blank\n\nThis might look wrong but it's just a side effect of \\lpr {mathstyle} expanding\nto the current (first pass) style and the number being injected in the list that\ngets converted in the second pass. It all makes sense and it illustrates the\nimportance of grouping. In fact, the math choice style being effective afterwards\nhas advantages. It would be hard to get it otherwise.\n\n\\subsection{\\lpr {Ustack}}\n\n\\topicindex {math+stacks}\n\nThere are a few math commands in \\TEX\\ where the style that will be used is not\nknown straight from the start. These commands (\\prm {over}, \\prm {atop},\n\\prm {overwithdelims}, \\prm {atopwithdelims}) would therefore normally return\nwrong values for \\lpr {mathstyle}. To fix this, \\LUATEX\\ introduces a special\nprefix command: \\lpr {Ustack}:\n\n\\starttyping\n$\\Ustack {a \\over b}$\n\\stoptyping\n\nThe \\lpr {Ustack} command will scan the next brace and start a new math group\nwith the correct (numerator) math style.\n\n\\section{Unicode math characters}\n\n\\topicindex {math+\\UNICODE}\n\\topicindex {\\UNICODE+math}\n\nCharacter handling is now extended up to the full \\UNICODE\\ range (the \\type {\\U}\nprefix), which is compatible with \\XETEX.\n\nThe math primitives from \\TEX\\ are kept as they are, except for the ones that\nconvert from input to math commands: \\type {mathcode}, and \\type {delcode}. These\ntwo now allow for a 21-bit character argument on the left hand side of the equals\nsign.\n\nSome of the new \\LUATEX\\ primitives read more than one separate value. This is\nshown in the tables below by a plus sign in the second column.\n\nThe input for such primitives would look like this:\n\n\\starttyping\n\\def\\overbrace{\\Umathaccent 0 1 \"23DE }\n\\stoptyping\n\nThe altered \\TEX82 primitives are:\n\n\\starttabulate[|l|l|r|c|l|r|]\n\\DB primitive       \\BC min \\BC max    \\BC \\kern 2em \\BC min \\BC max    \\NC \\NR\n\\TB\n\\NC \\prm {mathcode} \\NC 0   \\NC 10FFFF \\NC =         \\NC 0   \\NC 8000   \\NC \\NR\n\\NC \\prm {delcode}  \\NC 0   \\NC 10FFFF \\NC =         \\NC 0   \\NC FFFFFF \\NC \\NR\n\\LL\n\\stoptabulate\n\nThe unaltered ones are:\n\n\\starttabulate[|l|l|r|]\n\\DB primitive          \\BC min \\BC max     \\NC \\NR\n\\TB\n\\NC \\prm {mathchardef} \\NC 0   \\NC    8000 \\NC \\NR\n\\NC \\prm {mathchar}    \\NC 0   \\NC    7FFF \\NC \\NR\n\\NC \\prm {mathaccent}  \\NC 0   \\NC    7FFF \\NC \\NR\n\\NC \\prm {delimiter}   \\NC 0   \\NC 7FFFFFF \\NC \\NR\n\\NC \\prm {radical}     \\NC 0   \\NC 7FFFFFF \\NC \\NR\n\\LL\n\\stoptabulate\n\nFor practical reasons \\prm {mathchardef} will silently accept values larger\nthat \\type {0x8000} and interpret it as \\lpr {Umathcharnumdef}. This is needed\nto satisfy older macro packages.\n\nThe following new primitives are compatible with \\XETEX:\n\n% somewhat fuzzy:\n\n\\starttabulate[|l|l|r|c|l|r|]\n\\DB primitive                             \\BC min       \\BC max         \\BC \\kern 2em \\BC min       \\BC max         \\NC \\NR\n\\TB\n\\NC \\lpr {Umathchardef}                   \\NC 0+0+0     \\NC 7+FF+10FFFF \\NC           \\NC           \\NC             \\NC \\NR\n\\NC \\lpr {Umathcharnumdef}\\rlap{\\high{5}} \\NC -80000000 \\NC    7FFFFFFF \\NC           \\NC           \\NC             \\NC \\NR\n\\NC \\lpr {Umathcode}                      \\NC 0         \\NC      10FFFF \\NC =         \\NC 0+0+0     \\NC 7+FF+10FFFF \\NC \\NR\n\\NC \\lpr {Udelcode}                       \\NC 0         \\NC      10FFFF \\NC =         \\NC 0+0       \\NC   FF+10FFFF \\NC \\NR\n\\NC \\lpr {Umathchar}                      \\NC 0+0+0     \\NC 7+FF+10FFFF \\NC           \\NC           \\NC             \\NC \\NR\n\\NC \\lpr {Umathaccent}                    \\NC 0+0+0     \\NC 7+FF+10FFFF \\NC           \\NC           \\NC             \\NC \\NR\n\\NC \\lpr {Udelimiter}                     \\NC 0+0+0     \\NC 7+FF+10FFFF \\NC           \\NC           \\NC             \\NC \\NR\n\\NC \\lpr {Uradical}                       \\NC 0+0       \\NC   FF+10FFFF \\NC           \\NC           \\NC             \\NC \\NR\n\\NC \\lpr {Umathcharnum}                   \\NC -80000000 \\NC    7FFFFFFF \\NC           \\NC           \\NC             \\NC \\NR\n\\NC \\lpr {Umathcodenum}                   \\NC 0         \\NC      10FFFF \\NC =         \\NC -80000000 \\NC    7FFFFFFF \\NC \\NR\n\\NC \\lpr {Udelcodenum}                    \\NC 0         \\NC      10FFFF \\NC =         \\NC -80000000 \\NC    7FFFFFFF \\NC \\NR\n\\LL\n\\stoptabulate\n\nSpecifications typically look like:\n\n\\starttyping\n\\Umathchardef\\xx=\"1\"0\"456\n\\Umathcode   123=\"1\"0\"789\n\\stoptyping\n\nThe new primitives that deal with delimiter|-|style objects do not set up a\n\\quote {large family}. Selecting a suitable size for display purposes is expected\nto be dealt with by the font via the \\lpr {Umathoperatorsize} parameter (more\ninformation can be found in a following section).\n\nFor some of these primitives, all information is packed into a single signed\ninteger. For the first two (\\lpr {Umathcharnum} and \\lpr {Umathcodenum}), the\nlowest 21 bits are the character code, the 3 bits above that represent the math\nclass, and the family data is kept in the topmost bits This means that the values\nfor math families 128--255 are actually negative. For \\lpr {Udelcodenum} there\nis no math class. The math family information is stored in the bits directly on\ntop of the character code. Using these three commands is not as natural as using\nthe two- and three|-|value commands, so unless you know exactly what you are\ndoing and absolutely require the speedup resulting from the faster input\nscanning, it is better to use the verbose commands instead.\n\nThe \\lpr {Umathaccent} command accepts optional keywords to control various\ndetails regarding math accents. See \\in {section} [mathacc] below for details.\n\nThere are more new primitives and all of these will be explained in following\nsections:\n\n\\starttabulate[|l|l|]\n\\DB primitive                \\BC value range (in hex) \\NC \\NR\n\\TB\n\\NC \\lpr {Uroot}           \\NC 0 + 0--FF + 10FFFF   \\NC \\NR\n\\NC \\lpr {Uoverdelimiter}  \\NC 0 + 0--FF + 10FFFF   \\NC \\NR\n\\NC \\lpr {Uunderdelimiter} \\NC 0 + 0--FF + 10FFFF   \\NC \\NR\n\\NC \\lpr {Udelimiterover}  \\NC 0 + 0--FF + 10FFFF   \\NC \\NR\n\\NC \\lpr {Udelimiterunder} \\NC 0 + 0--FF + 10FFFF   \\NC \\NR\n\\LL\n\\stoptabulate\n\n\\section{Cramped math styles}\n\n\\topicindex {math+styles}\n\\topicindex {math+spacing}\n\\topicindex {math+cramped}\n\n\\LUATEX\\ has four new primitives to set the cramped math styles directly:\n\n\\starttyping\n\\crampeddisplaystyle\n\\crampedtextstyle\n\\crampedscriptstyle\n\\crampedscriptscriptstyle\n\\stoptyping\n\nThese additional commands are not all that valuable on their own, but they come\nin handy as arguments to the math parameter settings that will be added shortly.\n\nIn Eijkhouts \\quotation {\\TEX\\ by Topic} the rules for handling styles in scripts\nare described as follows:\n\n\\startitemize\n\\startitem\n    In any style superscripts and subscripts are taken from the next smaller style.\n    Exception: in display style they are in script style.\n\\stopitem\n\\startitem\n    Subscripts are always in the cramped variant of the style; superscripts are only\n    cramped if the original style was cramped.\n\\stopitem\n\\startitem\n    In an \\type {..\\over..} formula in any style the numerator and denominator are\n    taken from the next smaller style.\n\\stopitem\n\\startitem\n    The denominator is always in cramped style; the numerator is only in cramped\n    style if the original style was cramped.\n\\stopitem\n\\startitem\n    Formulas under a \\type {\\sqrt} or \\prm {overline} are in cramped style.\n\\stopitem\n\\stopitemize\n\nIn \\LUATEX\\ one can set the styles in more detail which means that you sometimes\nhave to set both normal and cramped styles to get the effect you want. If we\nforce styles in the script using \\prm {scriptstyle} and \\lpr {crampedscriptstyle}\nwe get this:\n\n\\startbuffer[demo]\n\\starttabulate\n\\DB style         \\BC example \\NC \\NR\n\\TB\n\\NC default       \\NC $b_{x=xx}^{x=xx}$ \\NC \\NR\n\\NC script        \\NC $b_{\\scriptstyle x=xx}^{\\scriptstyle x=xx}$ \\NC \\NR\n\\NC crampedscript \\NC $b_{\\crampedscriptstyle x=xx}^{\\crampedscriptstyle x=xx}$ \\NC \\NR\n\\LL\n\\stoptabulate\n\\stopbuffer\n\n\\getbuffer[demo]\n\nNow we set the following parameters\n\n\\startbuffer[setup]\n\\Umathordrelspacing\\scriptstyle=30mu\n\\Umathordordspacing\\scriptstyle=30mu\n\\stopbuffer\n\n\\typebuffer[setup]\n\nThis gives:\n\n\\start\\getbuffer[setup,demo]\\stop\n\nBut, as this is not what is expected (visually) we should say:\n\n\\startbuffer[setup]\n\\Umathordrelspacing\\scriptstyle=30mu\n\\Umathordordspacing\\scriptstyle=30mu\n\\Umathordrelspacing\\crampedscriptstyle=30mu\n\\Umathordordspacing\\crampedscriptstyle=30mu\n\\stopbuffer\n\n\\typebuffer[setup]\n\nNow we get:\n\n\\start\\getbuffer[setup,demo]\\stop\n\n\\section{Math parameter settings}\n\n\\topicindex {math+parameters}\n\nIn \\LUATEX, the font dimension parameters that \\TEX\\ used in math typesetting are\nnow accessible via primitive commands. In fact, refactoring of the math engine\nhas resulted in many more parameters than were accessible before.\n\n\\starttabulate\n\\DB primitive name                   \\BC description \\NC \\NR\n\\TB\n\\NC \\lpr {Umathquad}               \\NC the width of 18 mu's \\NC \\NR\n\\NC \\lpr {Umathaxis}               \\NC height of the vertical center axis of\n                                         the math formula above the baseline \\NC \\NR\n\\NC \\lpr {Umathoperatorsize}       \\NC minimum size of large operators in display mode \\NC \\NR\n\\NC \\lpr {Umathoverbarkern}        \\NC vertical clearance above the rule \\NC \\NR\n\\NC \\lpr {Umathoverbarrule}        \\NC the width of the rule \\NC \\NR\n\\NC \\lpr {Umathoverbarvgap}        \\NC vertical clearance below the rule \\NC \\NR\n\\NC \\lpr {Umathunderbarkern}       \\NC vertical clearance below the rule \\NC \\NR\n\\NC \\lpr {Umathunderbarrule}       \\NC the width of the rule \\NC \\NR\n\\NC \\lpr {Umathunderbarvgap}       \\NC vertical clearance above the rule \\NC \\NR\n\\NC \\lpr {Umathradicalkern}        \\NC vertical clearance above the rule \\NC \\NR\n\\NC \\lpr {Umathradicalrule}        \\NC the width of the rule \\NC \\NR\n\\NC \\lpr {Umathradicalvgap}        \\NC vertical clearance below the rule \\NC \\NR\n\\NC \\lpr {Umathradicaldegreebefore}\\NC the forward kern that takes place before placement of\n                                       the radical degree \\NC \\NR\n\\NC \\lpr {Umathradicaldegreeafter} \\NC the backward kern that takes place after placement of\n                                       the radical degree \\NC \\NR\n\\NC \\lpr {Umathradicaldegreeraise} \\NC this is the percentage of the total height and depth of\n                                       the radical sign that the degree is raised by; it is\n                                       expressed in \\type {percents}, so 60\\% is expressed as the\n                                       integer $60$ \\NC \\NR\n\\NC \\lpr {Umathstackvgap}          \\NC vertical clearance between the two\n                                       elements in a \\prm {atop} stack \\NC \\NR\n\\NC \\lpr {Umathstacknumup}         \\NC numerator shift upward in \\prm {atop} stack \\NC \\NR\n\\NC \\lpr {Umathstackdenomdown}     \\NC denominator shift downward in \\prm {atop} stack \\NC \\NR\n\\NC \\lpr {Umathfractionrule}       \\NC the width of the rule in a \\prm {over} \\NC \\NR\n\\NC \\lpr {Umathfractionnumvgap}    \\NC vertical clearance between the numerator and the rule \\NC \\NR\n\\NC \\lpr {Umathfractionnumup}      \\NC numerator shift upward in \\prm {over} \\NC \\NR\n\\NC \\lpr {Umathfractiondenomvgap}  \\NC vertical clearance between the denominator and the rule \\NC \\NR\n\\NC \\lpr {Umathfractiondenomdown}  \\NC denominator shift downward in \\prm {over} \\NC \\NR\n\\NC \\lpr {Umathfractiondelsize}    \\NC minimum delimiter size for \\type {\\...withdelims} \\NC \\NR\n\\NC \\lpr {Umathlimitabovevgap}     \\NC vertical clearance for limits above operators \\NC \\NR\n\\NC \\lpr {Umathlimitabovebgap}     \\NC vertical baseline clearance for limits above operators \\NC \\NR\n\\NC \\lpr {Umathlimitabovekern}     \\NC space reserved at the top of the limit \\NC \\NR\n\\NC \\lpr {Umathlimitbelowvgap}     \\NC vertical clearance for limits below operators \\NC \\NR\n\\NC \\lpr {Umathlimitbelowbgap}     \\NC vertical baseline clearance for limits below operators \\NC \\NR\n\\NC \\lpr {Umathlimitbelowkern}     \\NC space reserved at the bottom of the limit \\NC \\NR\n\\NC \\lpr {Umathoverdelimitervgap}  \\NC vertical clearance for limits above delimiters \\NC \\NR\n\\NC \\lpr {Umathoverdelimiterbgap}  \\NC vertical baseline clearance for limits above delimiters \\NC \\NR\n\\NC \\lpr {Umathunderdelimitervgap} \\NC vertical clearance for limits below delimiters \\NC \\NR\n\\NC \\lpr {Umathunderdelimiterbgap} \\NC vertical baseline clearance for limits below delimiters \\NC \\NR\n\\NC \\lpr {Umathsubshiftdrop}       \\NC subscript drop for boxes and subformulas \\NC \\NR\n\\NC \\lpr {Umathsubshiftdown}       \\NC subscript drop for characters \\NC \\NR\n\\NC \\lpr {Umathsupshiftdrop}       \\NC superscript drop (raise, actually) for boxes and subformulas \\NC \\NR\n\\NC \\lpr {Umathsupshiftup}         \\NC superscript raise for characters \\NC \\NR\n\\NC \\lpr {Umathsubsupshiftdown}    \\NC subscript drop in the presence of a superscript \\NC \\NR\n\\NC \\lpr {Umathsubtopmax}          \\NC the top of standalone subscripts cannot be higher than this\n                                       above the baseline \\NC \\NR\n\\NC \\lpr {Umathsupbottommin}       \\NC the bottom of standalone superscripts cannot be less than\n                                       this above the baseline \\NC \\NR\n\\NC \\lpr {Umathsupsubbottommax}    \\NC the bottom of the superscript of a combined super- and subscript\n                                       be at least as high as this above the baseline \\NC \\NR\n\\NC \\lpr {Umathsubsupvgap}         \\NC vertical clearance between super- and subscript \\NC \\NR\n\\NC \\lpr {Umathspaceafterscript}   \\NC additional space added after a super- or subscript \\NC \\NR\n\\NC \\lpr {Umathconnectoroverlapmin}\\NC minimum overlap between parts in an extensible recipe \\NC \\NR\n\\LL\n\\stoptabulate\n\nEach of the parameters in this section can be set by a command like this:\n\n\\starttyping\n\\Umathquad\\displaystyle=1em\n\\stoptyping\n\nthey obey grouping, and you can use \\type {\\the\\Umathquad\\displaystyle} if\nneeded.\n\n\\section{Skips around display math}\n\n\\topicindex {math+spacing}\n\nThe injection of \\prm {abovedisplayskip} and \\prm {belowdisplayskip} is not\nsymmetrical. An above one is always inserted, also when zero, but the below is\nonly inserted when larger than zero. Especially the later makes it sometimes hard\nto fully control spacing. Therefore \\LUATEX\\ comes with a new directive: \\lpr\n{mathdisplayskipmode}. The following values apply:\n\n\\starttabulate[|c|l|]\n\\DB value  \\BC meaning \\NC \\NR\n\\TB\n\\NC 0 \\NC normal \\TEX\\ behaviour \\NC \\NR\n\\NC 1 \\NC always (same as 0) \\NC \\NR\n\\NC 2 \\NC only when not zero \\NC \\NR\n\\NC 3 \\NC never, not even when not zero \\NC \\NR\n\\LL\n\\stoptabulate\n\n\\section{Font|-|based Math Parameters}\n\n\\topicindex {math+parameters}\n\nWhile it is nice to have these math parameters available for tweaking, it would\nbe tedious to have to set each of them by hand. For this reason, \\LUATEX\\\ninitializes a bunch of these parameters whenever you assign a font identifier to\na math family based on either the traditional math font dimensions in the font\n(for assignments to math family~2 and~3 using \\TFM|-|based fonts like \\type\n{cmsy} and \\type {cmex}), or based on the named values in a potential \\type\n{MathConstants} table when the font is loaded via Lua. If there is a \\type\n{MathConstants} table, this takes precedence over font dimensions, and in that\ncase no attention is paid to which family is being assigned to: the \\type\n{MathConstants} tables in the last assigned family sets all parameters.\n\nIn the table below, the one|-|letter style abbreviations and symbolic tfm font\ndimension names match those using in the \\TeX book. Assignments to \\prm\n{textfont} set the values for the cramped and uncramped display and text styles,\n\\prm {scriptfont} sets the script styles, and \\prm {scriptscriptfont} sets the\nscriptscript styles, so we have eight parameters for three font sizes. In the\n\\TFM\\ case, assignments only happen in family~2 and family~3 (and of course only\nfor the parameters for which there are font dimensions).\n\nBesides the parameters below, \\LUATEX\\ also looks at the \\quote {space} font\ndimension parameter. For math fonts, this should be set to zero.\n\n\\def\\MathLine#1#2#3#4#5%\n  {\\TB\n   \\NC \\llap{\\high{\\tx #2\\enspace}}\\ttbf \\string #1 \\NC \\tt #5 \\NC \\NR\n   \\NC \\tx #3 \\NC \\tt #4 \\NC \\NR}\n\n\\starttabulate[|l|l|]\n\\DB variable / style \\BC tfm / opentype \\NC \\NR\n\\MathLine{\\Umathaxis}               {}   {}                     {AxisHeight}                              {axis_height}\n\\MathLine{\\Umathoperatorsize}       {6}  {D, D'}                {DisplayOperatorMinHeight}                {\\emdash}\n\\MathLine{\\Umathfractiondelsize}    {9}  {D, D'}                {FractionDelimiterDisplayStyleSize}       {delim1}\n\\MathLine{\\Umathfractiondelsize}    {9}  {T, T', S, S', SS, SS'}{FractionDelimiterSize}                   {delim2}\n\\MathLine{\\Umathfractiondenomdown}  {}   {D, D'}                {FractionDenominatorDisplayStyleShiftDown}{denom1}\n\\MathLine{\\Umathfractiondenomdown}  {}   {T, T', S, S', SS, SS'}{FractionDenominatorShiftDown}            {denom2}\n\\MathLine{\\Umathfractiondenomvgap}  {}   {D, D'}                {FractionDenominatorDisplayStyleGapMin}   {3*default_rule_thickness}\n\\MathLine{\\Umathfractiondenomvgap}  {}   {T, T', S, S', SS, SS'}{FractionDenominatorGapMin}               {default_rule_thickness}\n\\MathLine{\\Umathfractionnumup}      {}   {D, D'}                {FractionNumeratorDisplayStyleShiftUp}    {num1}\n\\MathLine{\\Umathfractionnumup}      {}   {T, T', S, S', SS, SS'}{FractionNumeratorShiftUp}                {num2}\n\\MathLine{\\Umathfractionnumvgap}    {}   {D, D'}                {FractionNumeratorDisplayStyleGapMin}     {3*default_rule_thickness}\n\\MathLine{\\Umathfractionnumvgap}    {}   {T, T', S, S', SS, SS'}{FractionNumeratorGapMin}                 {default_rule_thickness}\n\\MathLine{\\Umathfractionrule}       {}   {}                     {FractionRuleThickness}                   {default_rule_thickness}\n\\MathLine{\\Umathskewedfractionhgap} {}   {}                     {SkewedFractionHorizontalGap}             {math_quad/2}\n\\MathLine{\\Umathskewedfractionvgap} {}   {}                     {SkewedFractionVerticalGap}               {math_x_height}\n\\MathLine{\\Umathlimitabovebgap}     {}   {}                     {UpperLimitBaselineRiseMin}               {big_op_spacing3}\n\\MathLine{\\Umathlimitabovekern}     {1}  {}                     {0}                                       {big_op_spacing5}\n\\MathLine{\\Umathlimitabovevgap}     {}   {}                     {UpperLimitGapMin}                        {big_op_spacing1}\n\\MathLine{\\Umathlimitbelowbgap}     {}   {}                     {LowerLimitBaselineDropMin}               {big_op_spacing4}\n\\MathLine{\\Umathlimitbelowkern}     {1}  {}                     {0}                                       {big_op_spacing5}\n\\MathLine{\\Umathlimitbelowvgap}     {}   {}                     {LowerLimitGapMin}                        {big_op_spacing2}\n\\MathLine{\\Umathoverdelimitervgap}  {}   {}                     {StretchStackGapBelowMin}                 {big_op_spacing1}\n\\MathLine{\\Umathoverdelimiterbgap}  {}   {}                     {StretchStackTopShiftUp}                  {big_op_spacing3}\n\\MathLine{\\Umathunderdelimitervgap} {}   {}                     {StretchStackGapAboveMin}                 {big_op_spacing2}\n\\MathLine{\\Umathunderdelimiterbgap} {}   {}                     {StretchStackBottomShiftDown}             {big_op_spacing4}\n\\MathLine{\\Umathoverbarkern}        {}   {}                     {OverbarExtraAscender}                    {default_rule_thickness}\n\\MathLine{\\Umathoverbarrule}        {}   {}                     {OverbarRuleThickness}                    {default_rule_thickness}\n\\MathLine{\\Umathoverbarvgap}        {}   {}                     {OverbarVerticalGap}                      {3*default_rule_thickness}\n\\MathLine{\\Umathquad}               {1}  {}                     {<font_size(f)>}                          {math_quad}\n\\MathLine{\\Umathradicalkern}        {}   {}                     {RadicalExtraAscender}                    {default_rule_thickness}\n\\MathLine{\\Umathradicalrule}        {2}  {}                     {RadicalRuleThickness}                    {<not set>}\n\\MathLine{\\Umathradicalvgap}        {3}  {D, D'}                {RadicalDisplayStyleVerticalGap}          {default_rule_thickness+abs(math_x_height)/4}\n\\MathLine{\\Umathradicalvgap}        {3}  {T, T', S, S', SS, SS'}{RadicalVerticalGap}                      {default_rule_thickness+abs(default_rule_thickness)/4}\n\\MathLine{\\Umathradicaldegreebefore}{2}  {}                     {RadicalKernBeforeDegree}                 {<not set>}\n\\MathLine{\\Umathradicaldegreeafter} {2}  {}                     {RadicalKernAfterDegree}                  {<not set>}\n\\MathLine{\\Umathradicaldegreeraise} {2,7}{}                     {RadicalDegreeBottomRaisePercent}         {<not set>}\n\\MathLine{\\Umathspaceafterscript}   {4}  {}                     {SpaceAfterScript}                        {script_space}\n\\MathLine{\\Umathstackdenomdown}     {}   {D, D'}                {StackBottomDisplayStyleShiftDown}        {denom1}\n\\MathLine{\\Umathstackdenomdown}     {}   {T, T', S, S', SS, SS'}{StackBottomShiftDown}                    {denom2}\n\\MathLine{\\Umathstacknumup}         {}   {D, D'}                {StackTopDisplayStyleShiftUp}             {num1}\n\\MathLine{\\Umathstacknumup}         {}   {T, T', S, S', SS, SS'}{StackTopShiftUp}                         {num3}\n\\MathLine{\\Umathstackvgap}          {}   {D, D'}                {StackDisplayStyleGapMin}                 {7*default_rule_thickness}\n\\MathLine{\\Umathstackvgap}          {}   {T, T', S, S', SS, SS'}{StackGapMin}                             {3*default_rule_thickness}\n\\MathLine{\\Umathsubshiftdown}       {}   {}                     {SubscriptShiftDown}                      {sub1}\n\\MathLine{\\Umathsubshiftdrop}       {}   {}                     {SubscriptBaselineDropMin}                {sub_drop}\n\\MathLine{\\Umathsubsupshiftdown}    {8}  {}                     {SubscriptShiftDownWithSuperscript}       {\\emdash}\n\\MathLine{\\Umathsubtopmax}          {}   {}                     {SubscriptTopMax}                         {abs(math_x_height*4)/5}\n\\MathLine{\\Umathsubsupvgap}         {}   {}                     {SubSuperscriptGapMin}                    {4*default_rule_thickness}\n\\MathLine{\\Umathsupbottommin}       {}   {}                     {SuperscriptBottomMin}                    {abs(math_x_height/4)}\n\\MathLine{\\Umathsupshiftdrop}       {}   {}                     {SuperscriptBaselineDropMax}              {sup_drop}\n\\MathLine{\\Umathsupshiftup}         {}   {D}                    {SuperscriptShiftUp}                      {sup1}\n\\MathLine{\\Umathsupshiftup}         {}   {T, S, SS,}            {SuperscriptShiftUp}                      {sup2}\n\\MathLine{\\Umathsupshiftup}         {}   {D', T', S', SS'}      {SuperscriptShiftUpCramped}               {sup3}\n\\MathLine{\\Umathsupsubbottommax}    {}   {}                     {SuperscriptBottomMaxWithSubscript}       {abs(math_x_height*4)/5}\n\\MathLine{\\Umathunderbarkern}       {}   {}                     {UnderbarExtraDescender}                  {default_rule_thickness}\n\\MathLine{\\Umathunderbarrule}       {}   {}                     {UnderbarRuleThickness}                   {default_rule_thickness}\n\\MathLine{\\Umathunderbarvgap}       {}   {}                     {UnderbarVerticalGap}                     {3*default_rule_thickness}\n\\MathLine{\\Umathconnectoroverlapmin}{5}  {}                     {MinConnectorOverlap}                     {0}\n\\LL\n\\stoptabulate\n\nNote 1: \\OPENTYPE\\ fonts set \\lpr {Umathlimitabovekern} and \\lpr\n{Umathlimitbelowkern} to zero and set \\lpr {Umathquad} to the font size of the\nused font, because these are not supported in the \\type {MATH} table,\n\nNote 2: Traditional \\TFM\\ fonts do not set \\lpr {Umathradicalrule} because\n\\TEX82\\ uses the height of the radical instead. When this parameter is indeed not\nset when \\LUATEX\\ has to typeset a radical, a backward compatibility mode will\nkick in that assumes that an oldstyle \\TEX\\ font is used. Also, they do not set\n\\lpr {Umathradicaldegreebefore}, \\lpr {Umathradicaldegreeafter}, and \\lpr\n{Umathradicaldegreeraise}. These are then automatically initialized to\n$5/18$quad, $-10/18$quad, and 60.\n\nNote 3: If \\TFM\\ fonts are used, then the \\lpr {Umathradicalvgap} is not set\nuntil the first time \\LUATEX\\ has to typeset a formula because this needs\nparameters from both family~2 and family~3. This provides a partial backward\ncompatibility with \\TEX82, but that compatibility is only partial: once the \\lpr\n{Umathradicalvgap} is set, it will not be recalculated any more.\n\nNote 4: When \\TFM\\ fonts are used a similar situation arises with respect to \\lpr\n{Umathspaceafterscript}: it is not set until the first time \\LUATEX\\ has to\ntypeset a formula. This provides some backward compatibility with \\TEX82. But\nonce the \\lpr {Umathspaceafterscript} is set, \\prm {scriptspace} will never be\nlooked at again.\n\nNote 5: Traditional \\TFM\\ fonts set \\lpr {Umathconnectoroverlapmin} to zero\nbecause \\TEX82\\ always stacks extensibles without any overlap.\n\nNote 6: The \\lpr {Umathoperatorsize} is only used in \\prm {displaystyle}, and is\nonly set in \\OPENTYPE\\ fonts. In \\TFM\\ font mode, it is artificially set to one\nscaled point more than the initial attempt's size, so that always the \\quote\n{first next} will be tried, just like in \\TEX82.\n\nNote 7: The \\lpr {Umathradicaldegreeraise} is a special case because it is the\nonly parameter that is expressed in a percentage instead of as a number of scaled\npoints.\n\nNote 8: \\type {SubscriptShiftDownWithSuperscript} does not actually exist in the\n\\quote {standard} \\OPENTYPE\\ math font Cambria, but it is useful enough to be\nadded.\n\nNote 9: \\type {FractionDelimiterDisplayStyleSize} and \\type\n{FractionDelimiterSize} do not actually exist in the \\quote {standard} \\OPENTYPE\\\nmath font Cambria, but were useful enough to be added.\n\n\\section {Nolimit correction}\n\n\\topicindex {math+limits}\n\nThere are two extra math parameters \\lpr {Umathnolimitsupfactor} and \\lpr\n{Umathnolimitsubfactor} that were added to provide some control over how limits\nare spaced (for example the position of super and subscripts after integral\noperators). They relate to an extra parameter \\lpr {mathnolimitsmode}. The half\ncorrections are what happens when scripts are placed on above and below. The\nproblem with italic corrections is that officially that correction italic is used\nfor above|/|below placement while advanced kerns are used for placement at the\nright end. The question is: how often is this implemented, and if so, does the\nkerns assume correction too. Anyway, with this parameter one can control it.\n\n\\starttabulate[|l|ck1|ck1|ck1|ck1|ck1|ck1|]\n    \\NC\n        \\NC \\mathnolimitsmode0    $\\displaystyle\\int\\nolimits^0_1$\n        \\NC \\mathnolimitsmode1    $\\displaystyle\\int\\nolimits^0_1$\n        \\NC \\mathnolimitsmode2    $\\displaystyle\\int\\nolimits^0_1$\n        \\NC \\mathnolimitsmode3    $\\displaystyle\\int\\nolimits^0_1$\n        \\NC \\mathnolimitsmode4    $\\displaystyle\\int\\nolimits^0_1$\n        \\NC \\mathnolimitsmode8000 $\\displaystyle\\int\\nolimits^0_1$\n    \\NC \\NR\n    \\TB\n    \\BC mode\n        \\NC \\tttf 0\n        \\NC \\tttf 1\n        \\NC \\tttf 2\n        \\NC \\tttf 3\n        \\NC \\tttf 4\n        \\NC \\tttf 8000\n    \\NC \\NR\n    \\BC superscript\n        \\NC 0\n        \\NC font\n        \\NC 0\n        \\NC 0\n        \\NC +ic/2\n        \\NC 0\n    \\NC \\NR\n    \\BC subscript\n        \\NC -ic\n        \\NC font\n        \\NC 0\n        \\NC -ic/2\n        \\NC -ic/2\n        \\NC 8000ic/1000\n    \\NC \\NR\n\\stoptabulate\n\nWhen the mode is set to one, the math parameters are used. This way a macro\npackage writer can decide what looks best. Given the current state of fonts in\n\\CONTEXT\\ we currently use mode 1 with factor 0 for the superscript and 750 for\nthe subscripts. Positive values are used for both parameters but the subscript\nshifts to the left. A \\lpr {mathnolimitsmode} larger that 15 is considered to\nbe a factor for the subscript correction. This feature can be handy when\nexperimenting.\n\n\\section {Math italic mess}\n\n\\topicindex {math+italics}\n\nThe \\lpr {mathitalicsmode} parameter can be set to~1 to force italic correction\nbefore noads that represent some more complex structure (read: everything\nthat is not an ord, bin, rel, open, close, punct or inner). We show a Cambria\nexample.\n\n\\starttexdefinition Whatever #1\n    \\NC \\type{\\mathitalicsmode = #1}\n    \\NC \\mathitalicsmode#1\\ruledhbox{$\\left|T^1\\right|$}\n    \\NC \\mathitalicsmode#1\\ruledhbox{$\\left|T\\right|$}\n    \\NC \\mathitalicsmode#1\\ruledhbox{$T+1$}\n    \\NC \\mathitalicsmode#1\\ruledhbox{$T{1\\over2}$}\n    \\NC \\mathitalicsmode#1\\ruledhbox{$T\\sqrt{1}$}\n    \\NC \\NR\n\\stoptexdefinition\n\n\\start\n    \\switchtobodyfont[cambria]\n    \\starttabulate[|c|c|c|c|c|c|]\n        \\Whatever{0}%\n        \\Whatever{1}%\n    \\stoptabulate\n\\stop\n\nThis kind of parameters relate to the fact that italic correction in \\OPENTYPE\\\nmath is bound to fuzzy rules. So, control is the solution.\n\n\\section {Script and kerning}\n\n\\topicindex {math+kerning}\n\\topicindex {math+scripts}\n\nIf you want typeset text in math macro packages often provide something \\type\n{\\text} which obeys the script sizes. As the definition can be anything there is\na good change that the kerning doesn't come out well when used in a script. Given\nthat the first glyph ends up in an \\prm {hbox} we have some control over this.\nAnd, as a bonus we also added control over the normal sublist kerning. The \\lpr\n{mathscriptboxmode} parameter defaults to~1.\n\n\\starttabulate[|c|l|]\n\\DB value     \\BC meaning \\NC \\NR\n\\TB\n\\NC \\type {0} \\NC forget about kerning \\NC \\NR\n\\NC \\type {1} \\NC kern math sub lists with a valid glyph \\NC \\NR\n\\NC \\type {2} \\NC also kern math sub boxes that have a valid glyph \\NC \\NR\n\\NC \\type {2} \\NC only kern math sub boxes with a boundary node present\\NC \\NR\n\\LL\n\\stoptabulate\n\nHere we show some examples. Of course this doesn't solve all our problems, if\nonly because some fonts have characters with bounding boxes that compensate for\nitalics, while other fonts can lack kerns.\n\n\\startbuffer[1]\n    $T_{\\tf fluff}$\n\\stopbuffer\n\n\\startbuffer[2]\n    $T_{\\text{fluff}}$\n\\stopbuffer\n\n\\startbuffer[3]\n    $T_{\\text{\\boundary1 fluff}}$\n\\stopbuffer\n\n\\unexpanded\\def\\Show#1#2#3%\n  {\\doifelsenothing{#3}\n     {\\small\\tx\\typeinlinebuffer[#1]}\n     {\\doifelse{#3}{-}\n        {\\small\\bf\\tt mode #2}\n        {\\switchtobodyfont[#3]\\showfontkerns\\showglyphs\\mathscriptboxmode#2\\relax\\inlinebuffer[#1]}}}\n\n\\starttabulate[|lBT|c|c|c|c|c|]\n    \\NC          \\NC \\Show{1}{0}{}         \\NC\\Show{1}{1}{}         \\NC \\Show{2}{1}{}         \\NC \\Show{2}{2}{}         \\NC \\Show{3}{3}{}         \\NC \\NR\n    \\NC          \\NC \\Show{1}{0}{-}        \\NC\\Show{1}{1}{-}        \\NC \\Show{2}{1}{-}        \\NC \\Show{2}{2}{-}        \\NC \\Show{3}{3}{-}        \\NC \\NR\n    \\NC modern   \\NC \\Show{1}{0}{modern}   \\NC\\Show{1}{1}{modern}   \\NC \\Show{2}{1}{modern}   \\NC \\Show{2}{2}{modern}   \\NC \\Show{3}{3}{modern}   \\NC \\NR\n    \\NC lucidaot \\NC \\Show{1}{0}{lucidaot} \\NC\\Show{1}{1}{lucidaot} \\NC \\Show{2}{1}{lucidaot} \\NC \\Show{2}{2}{lucidaot} \\NC \\Show{3}{3}{lucidaot} \\NC \\NR\n    \\NC pagella  \\NC \\Show{1}{0}{pagella}  \\NC\\Show{1}{1}{pagella}  \\NC \\Show{2}{1}{pagella}  \\NC \\Show{2}{2}{pagella}  \\NC \\Show{3}{3}{pagella}  \\NC \\NR\n    \\NC cambria  \\NC \\Show{1}{0}{cambria}  \\NC\\Show{1}{1}{cambria}  \\NC \\Show{2}{1}{cambria}  \\NC \\Show{2}{2}{cambria}  \\NC \\Show{3}{3}{cambria}  \\NC \\NR\n    \\NC dejavu   \\NC \\Show{1}{0}{dejavu}   \\NC\\Show{1}{1}{dejavu}   \\NC \\Show{2}{1}{dejavu}   \\NC \\Show{2}{2}{dejavu}   \\NC \\Show{3}{3}{dejavu}   \\NC \\NR\n\\stoptabulate\n\nKerning between a character subscript is controlled by \\lpr {mathscriptcharmode}\nwhich also defaults to~1.\n\nHere is another example. Internally we tag kerns as italic kerns or font kerns\nwhere font kerns result from the staircase kern tables. In 2018 fonts like Latin\nModern and Pagella rely on cheats with the boundingbox, Cambria uses staircase\nkerns and Lucida a mixture. Depending on how fonts evolve we might add some more\ncontrol over what one can turn on and off.\n\n\\def\\MathSample#1#2#3%\n  {\\NC\n   #1 \\NC\n   #2 \\NC\n   \\showglyphdata \\switchtobodyfont[#2,17.3pt]$#3T_{f}$         \\NC\n   \\showglyphdata \\switchtobodyfont[#2,17.3pt]$#3\\gamma_{e}$    \\NC\n   \\showglyphdata \\switchtobodyfont[#2,17.3pt]$#3\\gamma_{ee}$   \\NC\n   \\showglyphdata \\switchtobodyfont[#2,17.3pt]$#3T_{\\tf fluff}$ \\NC\n   \\NR}\n\n\\starttabulate[|Tl|Tl|l|l|l|l|]\n    \\FL\n    \\MathSample{normal}{modern}  {\\mr}\n    \\MathSample{}      {pagella} {\\mr}\n    \\MathSample{}      {cambria} {\\mr}\n    \\MathSample{}      {lucidaot}{\\mr}\n    \\ML\n    \\MathSample{bold}  {modern}  {\\mb}\n    \\MathSample{}      {pagella} {\\mb}\n    \\MathSample{}      {cambria} {\\mb}\n    \\MathSample{}      {lucidaot}{\\mb}\n    \\LL\n\\stoptabulate\n\n\\section {Unscaled fences}\n\n\\topicindex {math+fences}\n\nThe \\lpr {mathdelimitersmode} primitive is experimental and deals with the\nfollowing (potential) problems. Three bits can be set. The first bit prevents an\nunwanted shift when the fence symbol is not scaled (a cambria side effect). The\nsecond bit forces italic correction between a preceding character ordinal and the\nfenced subformula, while the third bit turns that subformula into a ordinary so\nthat the same spacing applies as with unfenced variants. Here we show Cambria\n(with \\lpr {mathitalicsmode} enabled).\n\n\\starttexdefinition Whatever #1\n    \\NC \\type{\\mathdelimitersmode = #1}\n    \\NC \\mathitalicsmode1\\mathdelimitersmode#1\\ruledhbox{\\showglyphs\\showfontkerns\\showfontitalics$f(x)$}\n    \\NC \\mathitalicsmode1\\mathdelimitersmode#1\\ruledhbox{\\showglyphs\\showfontkerns\\showfontitalics$f\\left(x\\right)$}\n    \\NC \\NR\n\\stoptexdefinition\n\n\\start\n    \\switchtobodyfont[cambria]\n    \\starttabulate[|l|l|l|]\n        \\Whatever{0}\\Whatever{1}\\Whatever{2}\\Whatever{3}%\n        \\Whatever{4}\\Whatever{5}\\Whatever{6}\\Whatever{7}%\n    \\stoptabulate\n\\stop\n\nSo, when set to 7 fenced subformulas with unscaled delimiters come out the same\nas unfenced ones. This can be handy for cases where one is forced to use \\prm\n{left} and \\prm {right} always because of unpredictable content. As said, it's an\nexperimental features (which somehow fits in the exceptional way fences are dealt\nwith in the engine). The full list of flags is given in the next table:\n\n\\starttabulate[|c|l|]\n\\DB value  \\BC meaning \\NC \\NR\n\\TB\n\\NC \\type{\"01} \\NC don't apply the usual shift \\NC \\NR\n\\NC \\type{\"02} \\NC apply italic correction when possible \\NC \\NR\n\\NC \\type{\"04} \\NC force a ordinary subformula \\NC \\NR\n\\NC \\type{\"08} \\NC no shift when a base character \\NC \\NR\n\\NC \\type{\"10} \\NC only shift when an extensible \\NC \\NR\n\\LL\n\\stoptabulate\n\nThe effect can depend on the font (and for Cambria one can use for instance \\type {\"16}).\n\n\\section {Math spacing setting}\n\n\\topicindex {math+spacing}\n\nBesides the parameters mentioned in the previous sections, there are also 64 new\nprimitives to control the math spacing table (as explained in Chapter~18 of the\n\\TEX book). The primitive names are a simple matter of combining two math atom\ntypes, but for completeness' sake, here is the whole list:\n\n\\starttwocolumns\n\\startlines\n\\lpr {Umathordordspacing}\n\\lpr {Umathordopspacing}\n\\lpr {Umathordbinspacing}\n\\lpr {Umathordrelspacing}\n\\lpr {Umathordopenspacing}\n\\lpr {Umathordclosespacing}\n\\lpr {Umathordpunctspacing}\n\\lpr {Umathordinnerspacing}\n\\lpr {Umathopordspacing}\n\\lpr {Umathopopspacing}\n\\lpr {Umathopbinspacing}\n\\lpr {Umathoprelspacing}\n\\lpr {Umathopopenspacing}\n\\lpr {Umathopclosespacing}\n\\lpr {Umathoppunctspacing}\n\\lpr {Umathopinnerspacing}\n\\lpr {Umathbinordspacing}\n\\lpr {Umathbinopspacing}\n\\lpr {Umathbinbinspacing}\n\\lpr {Umathbinrelspacing}\n\\lpr {Umathbinopenspacing}\n\\lpr {Umathbinclosespacing}\n\\lpr {Umathbinpunctspacing}\n\\lpr {Umathbininnerspacing}\n\\lpr {Umathrelordspacing}\n\\lpr {Umathrelopspacing}\n\\lpr {Umathrelbinspacing}\n\\lpr {Umathrelrelspacing}\n\\lpr {Umathrelopenspacing}\n\\lpr {Umathrelclosespacing}\n\\lpr {Umathrelpunctspacing}\n\\lpr {Umathrelinnerspacing}\n\\lpr {Umathopenordspacing}\n\\lpr {Umathopenopspacing}\n\\lpr {Umathopenbinspacing}\n\\lpr {Umathopenrelspacing}\n\\lpr {Umathopenopenspacing}\n\\lpr {Umathopenclosespacing}\n\\lpr {Umathopenpunctspacing}\n\\lpr {Umathopeninnerspacing}\n\\lpr {Umathcloseordspacing}\n\\lpr {Umathcloseopspacing}\n\\lpr {Umathclosebinspacing}\n\\lpr {Umathcloserelspacing}\n\\lpr {Umathcloseopenspacing}\n\\lpr {Umathcloseclosespacing}\n\\lpr {Umathclosepunctspacing}\n\\lpr {Umathcloseinnerspacing}\n\\lpr {Umathpunctordspacing}\n\\lpr {Umathpunctopspacing}\n\\lpr {Umathpunctbinspacing}\n\\lpr {Umathpunctrelspacing}\n\\lpr {Umathpunctopenspacing}\n\\lpr {Umathpunctclosespacing}\n\\lpr {Umathpunctpunctspacing}\n\\lpr {Umathpunctinnerspacing}\n\\lpr {Umathinnerordspacing}\n\\lpr {Umathinneropspacing}\n\\lpr {Umathinnerbinspacing}\n\\lpr {Umathinnerrelspacing}\n\\lpr {Umathinneropenspacing}\n\\lpr {Umathinnerclosespacing}\n\\lpr {Umathinnerpunctspacing}\n\\lpr {Umathinnerinnerspacing}\n\\stoplines\n\\stoptwocolumns\n\nThese parameters are of type \\prm {muskip}, so setting a parameter can be done\nlike this:\n\n\\starttyping\n\\Umathopordspacing\\displaystyle=4mu plus 2mu\n\\stoptyping\n\nThey are all initialized by \\type {initex} to the values mentioned in the table\nin Chapter~18 of the \\TEX book.\n\nNote 1: for ease of use as well as for backward compatibility, \\prm {thinmuskip},\n\\prm {medmuskip} and \\prm {thickmuskip} are treated especially. In their case a\npointer to the corresponding internal parameter is saved, not the actual \\prm\n{muskip} value. This means that any later changes to one of these three\nparameters will be taken into account.\n\nNote 2: Careful readers will realise that there are also primitives for the items\nmarked \\type {*} in the \\TEX book. These will not actually be used as those\ncombinations of atoms cannot actually happen, but it seemed better not to break\northogonality. They are initialized to zero.\n\n\\section[mathacc]{Math accent handling}\n\n\\topicindex {math+accents}\n\n\\LUATEX\\ supports both top accents and bottom accents in math mode, and math\naccents stretch automatically (if this is supported by the font the accent comes\nfrom, of course). Bottom and combined accents as well as fixed-width math accents\nare controlled by optional keywords following \\lpr {Umathaccent}.\n\nThe keyword \\type {bottom} after \\lpr {Umathaccent} signals that a bottom accent\nis needed, and the keyword \\type {both} signals that both a top and a bottom\naccent are needed (in this case two accents need to be specified, of course).\n\nThen the set of three integers defining the accent is read. This set of integers\ncan be prefixed by the \\type {fixed} keyword to indicate that a non-stretching\nvariant is requested (in case of both accents, this step is repeated).\n\nA simple example:\n\n\\starttyping\n\\Umathaccent both fixed 0 0 \"20D7 fixed 0 0 \"20D7 {example}\n\\stoptyping\n\nIf a math top accent has to be placed and the accentee is a character and has a\nnon-zero \\type {top_accent} value, then this value will be used to place the\naccent instead of the \\prm {skewchar} kern used by \\TEX82.\n\nThe \\type {top_accent} value represents a vertical line somewhere in the\naccentee. The accent will be shifted horizontally such that its own \\type\n{top_accent} line coincides with the one from the accentee. If the \\type\n{top_accent} value of the accent is zero, then half the width of the accent\nfollowed by its italic correction is used instead.\n\nThe vertical placement of a top accent depends on the \\type {x_height} of the\nfont of the accentee (as explained in the \\TEX book), but if value that turns out\nto be zero and the font had a \\type {MathConstants} table, then \\type\n{AccentBaseHeight} is used instead.\n\nThe vertical placement of a bottom accent is straight below the accentee, no\ncorrection takes place.\n\nPossible locations are \\type {top}, \\type {bottom}, \\type {both} and \\type\n{center}. When no location is given \\type {top} is assumed. An additional\nparameter \\nod {fraction} can be specified followed by a number; a value of for\ninstance 1200 means that the criterium is 1.2 times the width of the nucleus. The\nfraction only applies to the stepwise selected shapes and is mostly meant for the\n\\type {overlay} location. It also works for the other locations but then it\nconcerns the width.\n\n\\section{Math root extension}\n\n\\topicindex {math+radicals}\n\nThe new primitive \\lpr {Uroot} allows the construction of a radical noad\nincluding a degree field. Its syntax is an extension of \\lpr {Uradical}:\n\n\\starttyping\n\\Uradical <fam integer> <char integer> <radicand>\n\\Uroot    <fam integer> <char integer> <degree> <radicand>\n\\stoptyping\n\nThe placement of the degree is controlled by the math parameters \\lpr\n{Umathradicaldegreebefore}, \\lpr {Umathradicaldegreeafter}, and \\lpr\n{Umathradicaldegreeraise}. The degree will be typeset in \\prm\n{scriptscriptstyle}.\n\n\\section{Math kerning in super- and subscripts}\n\nThe character fields in a \\LUA|-|loaded \\OPENTYPE\\ math font can have a \\quote\n{mathkern} table. The format of this table is the same as the \\quote {mathkern}\ntable that is returned by the \\type {fontloader} library, except that all height\nand kern values have to be specified in actual scaled points.\n\nWhen a super- or subscript has to be placed next to a math item, \\LUATEX\\ checks\nwhether the super- or subscript and the nucleus are both simple character items.\nIf they are, and if the fonts of both character items are \\OPENTYPE\\ fonts (as\nopposed to legacy \\TEX\\ fonts), then \\LUATEX\\ will use the \\OPENTYPE\\ math\nalgorithm for deciding on the horizontal placement of the super- or subscript.\n\nThis works as follows:\n\n\\startitemize\n    \\startitem\n        The vertical position of the script is calculated.\n    \\stopitem\n    \\startitem\n        The default horizontal position is flat next to the base character.\n    \\stopitem\n    \\startitem\n        For superscripts, the italic correction of the base character is added.\n    \\stopitem\n    \\startitem\n        For a superscript, two vertical values are calculated: the bottom of the\n        script (after shifting up), and the top of the base. For a subscript, the two\n        values are the top of the (shifted down) script, and the bottom of the base.\n    \\stopitem\n    \\startitem\n        For each of these two locations:\n        \\startitemize\n            \\startitem\n                find the math kern value at this height for the base (for a subscript\n                placement, this is the bottom_right corner, for a superscript\n                placement the top_right corner)\n            \\stopitem\n            \\startitem\n                find the math kern value at this height for the script (for a\n                subscript placement, this is the top_left corner, for a superscript\n                placement the bottom_left corner)\n            \\stopitem\n            \\startitem\n                add the found values together to get a preliminary result.\n            \\stopitem\n        \\stopitemize\n    \\stopitem\n    \\startitem\n        The horizontal kern to be applied is the smallest of the two results from\n        previous step.\n    \\stopitem\n\\stopitemize\n\nThe math kern value at a specific height is the kern value that is specified by the\nnext higher height and kern pair, or the highest one in the character (if there is no\nvalue high enough in the character), or simply zero (if the character has no math kern\npairs at all).\n\n\\section{Scripts on horizontally extensible items like arrows}\n\n\\topicindex {math+scripts}\n\\topicindex {math+delimiters}\n\\topicindex {math+extensibles}\n\nThe primitives \\lpr {Uunderdelimiter} and \\lpr {Uoverdelimiter} allow the\nplacement of a subscript or superscript on an automatically extensible item and\n\\lpr {Udelimiterunder} and \\lpr {Udelimiterover} allow the placement of an\nautomatically extensible item as a subscript or superscript on a nucleus. The\ninput:\n\n% these produce radical noads .. in fact the code base has the numbers wrong for\n% quite a while, so no one seems to use this\n\n\\startbuffer\n$\\Uoverdelimiter  0 \"2194 {\\hbox{\\strut  overdelimiter}}$\n$\\Uunderdelimiter 0 \"2194 {\\hbox{\\strut underdelimiter}}$\n$\\Udelimiterover  0 \"2194 {\\hbox{\\strut  delimiterover}}$\n$\\Udelimiterunder 0 \"2194 {\\hbox{\\strut delimiterunder}}$\n\\stopbuffer\n\n\\typebuffer will render this:\n\n\\blank \\startnarrower \\getbuffer \\stopnarrower \\blank\n\nThe vertical placements are controlled by \\lpr {Umathunderdelimiterbgap}, \\lpr\n{Umathunderdelimitervgap}, \\lpr {Umathoverdelimiterbgap}, and \\lpr\n{Umathoverdelimitervgap} in a similar way as limit placements on large operators.\nThe superscript in \\lpr {Uoverdelimiter} is typeset in a suitable scripted style,\nthe subscript in \\lpr {Uunderdelimiter} is cramped as well.\n\nThese primitives accepts an option \\type {width} specification. When used the\nalso optional keywords \\type {left}, \\type {middle} and \\type {right} will\ndetermine what happens when a requested size can't be met (which can happen when\nwe step to successive larger variants).\n\nAn extra primitive \\lpr {Uhextensible} is available that can be used like this:\n\n\\startbuffer\n$\\Uhextensible width 10cm 0 \"2194$\n\\stopbuffer\n\n\\typebuffer This will render this:\n\n\\blank \\startnarrower \\getbuffer \\stopnarrower \\blank\n\nHere you can also pass options, like:\n\n\\startbuffer\n$\\Uhextensible width 1pt middle 0 \"2194$\n\\stopbuffer\n\n\\typebuffer This gives:\n\n\\blank \\startnarrower \\getbuffer \\stopnarrower \\blank\n\n\\LUATEX\\ internally uses a structure that supports \\OPENTYPE\\ \\quote\n{MathVariants} as well as \\TFM\\ \\quote {extensible recipes}. In most cases where\nfont metrics are involved we have a different code path for traditional fonts end\n\\OPENTYPE\\ fonts.\n\n\\section {Extracting values}\n\n\\topicindex {math+codes}\n\nYou can extract the components of a math character. Say that we have defined:\n\n\\starttyping\n\\Umathcode 1 2 3 4\n\\stoptyping\n\nthen\n\n\\starttyping\n[\\Umathcharclass1] [\\Umathcharfam1] [\\Umathcharslot1]\n\\stoptyping\n\nwill return:\n\n\\starttyping\n[2] [3] [4]\n\\stoptyping\n\nThese commands are provides as convenience. Before they came available you could\ndo the following:\n\n\\starttyping\n\\def\\Umathcharclass{\\directlua{tex.print(tex.getmathcode(token.scan_int())[1])}}\n\\def\\Umathcharfam  {\\directlua{tex.print(tex.getmathcode(token.scan_int())[2])}}\n\\def\\Umathcharslot {\\directlua{tex.print(tex.getmathcode(token.scan_int())[3])}}\n\\stoptyping\n\n\\section{fractions}\n\n\\topicindex {math+fractions}\n\nThe \\prm {abovewithdelims} command accepts a keyword \\type {exact}. When issued\nthe extra space relative to the rule thickness is not added. One can of course\nuse the \\type {\\Umathfraction..gap} commands to influence the spacing. Also the\nrule is still positioned around the math axis.\n\n\\starttyping\n$$ { {a} \\abovewithdelims() exact 4pt {b} }$$\n\\stoptyping\n\nThe math parameter table contains some parameters that specify a horizontal and\nvertical gap for skewed fractions. Of course some guessing is needed in order to\nimplement something that uses them. And so we now provide a primitive similar to the\nother fraction related ones but with a few options so that one can influence the\nrendering. Of course a user can also mess around a bit with the parameters\n\\lpr {Umathskewedfractionhgap} and \\lpr {Umathskewedfractionvgap}.\n\nThe syntax used here is:\n\n\\starttyping\n{ {1} \\Uskewed / <options> {2} }\n{ {1} \\Uskewedwithdelims / () <options> {2} }\n\\stoptyping\n\nwhere the options can be \\type {noaxis} and \\type {exact}. By default we add half\nthe axis to the shifts and by default we zero the width of the middle character.\nFor Latin Modern The result looks as follows:\n\n\\def\\ShowA#1#2#3{$x + { {#1} \\Uskewed           /    #3 {#2} } + x$}\n\\def\\ShowB#1#2#3{$x + { {#1} \\Uskewedwithdelims / () #3 {#2} } + x$}\n\n\\start\n    \\switchtobodyfont[modern]\n    \\starttabulate[||||||]\n        \\NC \\NC\n            \\ShowA{a}{b}{} \\NC\n            \\ShowA{1}{2}{} \\NC\n            \\ShowB{a}{b}{} \\NC\n            \\ShowB{1}{2}{} \\NC\n        \\NR\n        \\NC \\type{exact} \\NC\n            \\ShowA{a}{b}{exact} \\NC\n            \\ShowA{1}{2}{exact} \\NC\n            \\ShowB{a}{b}{exact} \\NC\n            \\ShowB{1}{2}{exact} \\NC\n        \\NR\n        \\NC \\type{noaxis} \\NC\n            \\ShowA{a}{b}{noaxis} \\NC\n            \\ShowA{1}{2}{noaxis} \\NC\n            \\ShowB{a}{b}{noaxis} \\NC\n            \\ShowB{1}{2}{noaxis} \\NC\n        \\NR\n        \\NC \\type{exact noaxis} \\NC\n            \\ShowA{a}{b}{exact noaxis} \\NC\n            \\ShowA{1}{2}{exact noaxis} \\NC\n            \\ShowB{a}{b}{exact noaxis} \\NC\n            \\ShowB{1}{2}{exact noaxis} \\NC\n        \\NR\n    \\stoptabulate\n\\stop\n\n\\section {Last lines}\n\n\\topicindex {math+last line}\n\nThere is a new primitive to control the overshoot in the calculation of the\nprevious line in mid|-|paragraph display math. The default value is 2 times\nthe em width of the current font:\n\n\\starttyping\n\\predisplaygapfactor=2000\n\\stoptyping\n\nIf you want to have the length of the last line independent of math i.e.\\ you don't\nwant to revert to a hack where you insert a fake display math formula in order to\nget the length of the last line, the following will often work too:\n\n\\starttyping\n\\def\\lastlinelength{\\dimexpr\n    \\directlua {tex.sprint (\n        (nodes.dimensions(node.tail(tex.lists.page_head).list))\n    )}sp\n\\relax}\n\\stoptyping\n\n\\section {Other Math changes}\n\n\\subsection {Verbose versions of single|-|character math commands}\n\n\\topicindex {math+styles}\n\n\\LUATEX\\ defines six new primitives that have the same function as\n\\type {^}, \\type {_}, \\type {$}, and \\type {$$}:\n\n\\starttabulate[|l|l|]\n\\DB primitive                  \\BC explanation \\NC \\NR\n\\TB\n\\NC \\lpr {Usuperscript}      \\NC duplicates the functionality of \\type {^} \\NC \\NR\n\\NC \\lpr {Usubscript}        \\NC duplicates the functionality of \\type {_} \\NC \\NR\n\\NC \\lpr {Ustartmath}        \\NC duplicates the functionality of \\type {$}, % $\n                                   when used in non-math mode. \\NC \\NR\n\\NC \\lpr {Ustopmath}         \\NC duplicates the functionality of \\type {$}, % $\n                                   when used in inline math mode. \\NC \\NR\n\\NC \\lpr {Ustartdisplaymath} \\NC duplicates the functionality of \\type {$$}, % $$\n                                   when used in non-math mode. \\NC \\NR\n\\NC \\lpr {Ustopdisplaymath}  \\NC duplicates the functionality of \\type {$$}, % $$\n                                   when used in display math mode. \\NC \\NR\n\\LL\n\\stoptabulate\n\nThe \\lpr {Ustopmath} and \\lpr {Ustopdisplaymath} primitives check if the current\nmath mode is the correct one (inline vs.\\ displayed), but you can freely intermix\nthe four mathon|/|mathoff commands with explicit dollar sign(s).\n\n\\subsection{Script commands \\lpr {Unosuperscript} and \\lpr {Unosubscript}}\n\n\\topicindex {math+styles}\n\\topicindex {math+scripts}\n\nThese two commands result in super- and subscripts but with the current style (at the\ntime of rendering). So,\n\n\\startbuffer[script]\n$\n    x\\Usuperscript  {1}\\Usubscript  {2} =\n    x\\Unosuperscript{1}\\Unosubscript{2} =\n    x\\Usuperscript  {1}\\Unosubscript{2} =\n    x\\Unosuperscript{1}\\Usubscript  {2}\n$\n\\stopbuffer\n\n\\typebuffer\n\nresults in \\inlinebuffer[script].\n\n\\subsection{Allowed math commands in non|-|math modes}\n\n\\topicindex {math+text}\n\\topicindex {text+math}\n\nThe commands \\prm {mathchar}, and \\lpr {Umathchar} and control sequences that are\nthe result of \\prm {mathchardef} or \\lpr {Umathchardef} are also acceptable in\nthe horizontal and vertical modes. In those cases, the \\prm {textfont} from the\nrequested math family is used.\n\n\\section{Math surrounding skips}\n\n\\topicindex {math+spacing}\n\nInline math is surrounded by (optional) \\prm {mathsurround} spacing but that is fixed\ndimension. There is now an additional parameter \\lpr {mathsurroundskip}. When set to a\nnon|-|zero value (or zero with some stretch or shrink) this parameter will replace\n\\prm {mathsurround}. By using an additional parameter instead of changing the nature\nof \\prm {mathsurround}, we can remain compatible. In the meantime a bit more\ncontrol has been added via \\lpr {mathsurroundmode}. This directive can take 6 values\nwith zero being the default behaviour.\n\n\\start\n\n\\def\\OneLiner#1#2%\n  {\\NC \\type{#1}\n   \\NC \\dontleavehmode\\inframed[align=normal,offset=0pt,frame=off]{\\mathsurroundmode#1\\relax\\hsize 100pt   x$x$x}\n   \\NC \\dontleavehmode\\inframed[align=normal,offset=0pt,frame=off]{\\mathsurroundmode#1\\relax\\hsize 100pt x $x$ x}\n   \\NC #2\n   \\NC \\NR}\n\n\\startbuffer\n\\mathsurround    10pt\n\\mathsurroundskip20pt\n\\stopbuffer\n\n\\typebuffer \\getbuffer\n\n\\starttabulate[|c|c|c|pl|]\n\\DB mode \\BC x\\$x\\$x \\BC x \\$x\\$ x \\BC effect \\NC \\NR\n\\TB\n\\OneLiner{0}{obey \\prm {mathsurround} when \\lpr {mathsurroundskip} is 0pt}\n\\OneLiner{1}{only add skip to the left}\n\\OneLiner{2}{only add skip to the right}\n\\OneLiner{3}{add skip to the left and right}\n\\OneLiner{4}{ignore the skip setting, obey \\prm {mathsurround}}\n\\OneLiner{5}{disable all spacing around math}\n\\OneLiner{6}{only apply \\lpr {mathsurroundskip} when also spacing}\n\\OneLiner{7}{only apply \\lpr {mathsurroundskip} when no spacing}\n\\LL\n\\stoptabulate\n\n\\stop\n\nMethod six omits the surround glue when there is (x)spacing glue present while\nmethod seven does the opposite, the glue is only applied when there is (x)space\nglue present too. Anything more fancy, like checking the begining or end of a\nparagraph (or edges of a box) would not be robust anyway. If you want that you\ncan write a callback that runs over a list and analyzes a paragraph. Actually, in\nthat case you could also inject glue (or set the properties of a math node)\nexplicitly. So, these modes are in practice mostly useful for special purposes\nand experiments (they originate in a tracker item). Keep in mind that this glue\nis part of the math node and not always treated as normal glue: it travels with\nthe begin and end math nodes. Also, method 6 and 7 will zero the skip related\nfields in a node when applicable in the first occasion that checks them\n(linebreaking or packaging).\n\n% \\section{Math todo}\n%\n% The following items are still todo.\n%\n% \\startitemize\n% \\startitem\n%     Pre-scripts.\n% \\stopitem\n% \\startitem\n%     Multi-story stacks.\n% \\stopitem\n% \\startitem\n%     Flattened accents for high characters (maybe).\n% \\stopitem\n% \\startitem\n%     Better control over the spacing around displays and handling of equation numbers.\n% \\stopitem\n% \\startitem\n%     Support for multi|-|line displays using \\MATHML\\ style alignment points.\n% \\stopitem\n% \\stopitemize\n\n\\subsection {Delimiters: \\type{\\Uleft}, \\prm {Umiddle} and \\prm {Uright}}\n\n\\topicindex {math+delimiters}\n\nNormally you will force delimiters to certain sizes by putting an empty box or\nrule next to it. The resulting delimiter will either be a character from the\nstepwise size range or an extensible. The latter can be quite differently\npositioned that the characters as it depends on the fit as well as the fact if\nthe used characters in the font have depth or height. Commands like (plain \\TEX\ns) \\type {\\big} need use this feature. In \\LUATEX\\ we provide a bit more control\nby three variants that supporting optional parameters \\type {height}, \\type\n{depth} and \\type {axis}. The following example uses this:\n\n\\startbuffer\n\\Uleft   height 30pt depth 10pt      \\Udelimiter \"0 \"0 \"000028\n\\quad x\\quad\n\\Umiddle height 40pt depth 15pt      \\Udelimiter \"0 \"0 \"002016\n\\quad x\\quad\n\\Uright  height 30pt depth 10pt      \\Udelimiter \"0 \"0 \"000029\n\\quad \\quad \\quad\n\\Uleft   height 30pt depth 10pt axis \\Udelimiter \"0 \"0 \"000028\n\\quad x\\quad\n\\Umiddle height 40pt depth 15pt axis \\Udelimiter \"0 \"0 \"002016\n\\quad x\\quad\n\\Uright  height 30pt depth 10pt axis \\Udelimiter \"0 \"0 \"000029\n\\stopbuffer\n\n\\typebuffer\n\n\\startlinecorrection\n\\ruledhbox{\\mathematics{\\getbuffer}}\n\\stoplinecorrection\n\nThe keyword \\type {exact} can be used as directive that the real dimensions\nshould be applied when the criteria can't be met which can happen when we're\nstill stepping through the successively larger variants. When no dimensions are\ngiven the \\type {noaxis} command can be used to prevent shifting over the axis.\n\nYou can influence the final class with the keyword \\type {class} which will\ninfluence the spacing. The numbers are the same as for character classes.\n\n\\subsection{Fixed scripts}\n\nWe have three parameters that are used for this fixed anchoring:\n\n\\starttabulate[|c|l|]\n\\DB parameter \\BC register \\NC \\NR\n\\NC $d$ \\NC \\lpr {Umathsubshiftdown}    \\NC \\NR\n\\NC $u$ \\NC \\lpr {Umathsupshiftup}      \\NC \\NR\n\\NC $s$ \\NC \\lpr {Umathsubsupshiftdown} \\NC \\NR\n\\LL\n\\stoptabulate\n\nWhen we set \\lpr {mathscriptsmode} to a value other than zero these are used\nfor calculating fixed positions. This is something that is needed for instance\nfor chemistry. You can manipulate the mentioned variables to achive different\neffects.\n\n\\def\\SampleMath#1%\n  {$\\mathscriptsmode#1\\mathupright CH_2 + CH^+_2 + CH^2_2$}\n\n\\starttabulate[|c|c|c|p|]\n\\DB mode \\BC down          \\BC up            \\BC example        \\NC \\NR\n\\TB\n\\NC 0    \\NC dynamic       \\NC dynamic       \\NC \\SampleMath{0} \\NC \\NR\n\\NC 1    \\NC $d$           \\NC $u$           \\NC \\SampleMath{1} \\NC \\NR\n\\NC 2    \\NC $s$           \\NC $u$           \\NC \\SampleMath{2} \\NC \\NR\n\\NC 3    \\NC $s$           \\NC $u + s - d$   \\NC \\SampleMath{3} \\NC \\NR\n\\NC 4    \\NC $d + (s-d)/2$ \\NC $u + (s-d)/2$ \\NC \\SampleMath{4} \\NC \\NR\n\\NC 5    \\NC $d$           \\NC $u + s - d$   \\NC \\SampleMath{5} \\NC \\NR\n\\LL\n\\stoptabulate\n\nThe value of this parameter obeys grouping but applies to the whole current\nformula.\n\n% if needed we can put the value in stylenodes but maybe more should go there\n\n\\subsection{Penalties: \\lpr {mathpenaltiesmode}}\n\n\\topicindex {math+penalties}\n\nOnly in inline math penalties will be added in a math list. You can force\npenalties (also in display math) by setting:\n\n\\starttyping\n\\mathpenaltiesmode = 1\n\\stoptyping\n\nThis primnitive is not really needed in \\LUATEX\\ because you can use the callback\n\\cbk {mlist_to_hlist} to force penalties by just calling the regular routine\nwith forced penalties. However, as part of opening up and control this primitive\nmakes sense. As a bonus we also provide two extra penalties:\n\n\\starttyping\n\\prebinoppenalty = -100 % example value\n\\prerelpenalty   =  900 % example value\n\\stoptyping\n\nThey default to inifinite which signals that they don't need to be inserted. When\nset they are injected before a binop or rel noad. This is an experimental feature.\n\n\\subsection{Equation spacing: \\lpr {matheqnogapstep}}\n\nBy default \\TEX\\ will add one quad between the equation and the number. This is\nhard coded. A new primitive can control this:\n\n\\startsyntax\n\\matheqnogapstep = 1000\n\\stopsyntax\n\nBecause a math quad from the math text font is used instead of a dimension, we\nuse a step to control the size. A value of zero will suppress the gap. The step\nis divided by 1000 which is the usual way to mimmick floating point factors in\n\\TEX.\n\n\\subsection {Tracing}\n\n\\topicindex {math+tracing}\n\nBecause there are quite some math related parameters and values, it is possible\nto limit tracing. Only when \\type {tracingassigns} and|/|or \\type\n{tracingrestores} are set to~2 or more they will be traced.\n\n\\subsection {Math options}\n\nThe logic in the math engine is rather complex and there are often no universal\nsolutions (read: what works out well for one font, fails for another). Therefore\nsome variations in the implementation will be driven by options for which a new\nprimitive \\lpr {mathoption} has been introduced (so that we don't end up with\nmany new commands). The approach of options also permits us to see what effect a\nspecific solution has.\n\n\\subsubsection {\\type {\\mathoption old}}\n\nThis option was introduced for testing purposes when the math engine got split\ncode paths and it forces the engine to treat new fonts as old ones with respect\nto italic correction etc. There are no guarantees given with respect to the final\nresult and unexpected side effects are not seens as bugs as they relate to font\nproperties.\n\n\\startbuffer\n\\mathoption old 1\n\\stopbuffer\n\nThe \\type {oldmath} boolean flag in the \\LUA\\ font table is the official way to\nforce old treatment as it's bound to fonts.\n\n\\subsubsection {\\type {\\mathoption noitaliccompensation}}\n\nThis option compensates placement for characters with a built|-|in italic\ncorrection.\n\n\\startbuffer\n{\\showboxes\\int}\\quad\n{\\showboxes\\int_{|}^{|}}\\quad\n{\\showboxes\\int\\limits_{|}^{|}}\n\\stopbuffer\n\n\\typebuffer\n\nGives (with computer modern that has such italics):\n\n\\startlinecorrection[blank]\n    \\switchtobodyfont[modern]\n    \\startcombination[nx=2,ny=2,distance=5em]\n        {\\mathoption noitaliccompensation 0\\relax \\mathematics{\\getbuffer}}\n            {\\nohyphens\\type{0:inline}}\n        {\\mathoption noitaliccompensation 0\\relax \\mathematics{\\displaymath\\getbuffer}}\n            {\\nohyphens\\type{0:display}}\n        {\\mathoption noitaliccompensation 1\\relax \\mathematics{\\getbuffer}}\n            {\\nohyphens\\type{1:inline}}\n        {\\mathoption noitaliccompensation 1\\relax \\mathematics{\\displaymath\\getbuffer}}\n            {\\nohyphens\\type{1:display}}\n    \\stopcombination\n\\stoplinecorrection\n\n\\subsubsection {\\type {\\mathoption nocharitalic}}\n\nWhen two characters follow each other italic correction can interfere. The\nfollowing example shows what this option does:\n\n\\startbuffer\n\\catcode\"1D443=11\n\\catcode\"1D444=11\n\\catcode\"1D445=11\nP( PP PQR\n\\stopbuffer\n\n\\typebuffer\n\nGives (with computer modern that has such italics):\n\n\\startlinecorrection[blank]\n    \\switchtobodyfont[modern]\n    \\startcombination[nx=2,ny=2,distance=5em]\n        {\\mathoption nocharitalic 0\\relax \\mathematics{\\getbuffer}}\n            {\\nohyphens\\type{0:inline}}\n        {\\mathoption nocharitalic 0\\relax \\mathematics{\\displaymath\\getbuffer}}\n            {\\nohyphens\\type{0:display}}\n        {\\mathoption nocharitalic 1\\relax \\mathematics{\\getbuffer}}\n            {\\nohyphens\\type{1:inline}}\n        {\\mathoption nocharitalic 1\\relax \\mathematics{\\displaymath\\getbuffer}}\n            {\\nohyphens\\type{1:display}}\n    \\stopcombination\n\\stoplinecorrection\n\n\\subsubsection {\\type {\\mathoption useoldfractionscaling}}\n\nThis option has been introduced as solution for tracker item 604 for fuzzy cases\naround either or not present fraction related settings for new fonts.\n\n\\stopchapter\n\n\\stopcomponent\n", "meta": {"hexsha": "5f82eb142d40e9c3bc0c4c4bb9f85f442f32865c", "size": 66829, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/texmf-context/doc/context/sources/general/manuals/luatex/luatex-math.tex", "max_stars_repo_name": "kensh/pandoc_resume", "max_stars_repo_head_hexsha": "74ea55abde343f4e6e07fa6cd94694816e6e3cc4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tex/texmf-context/doc/context/sources/general/manuals/luatex/luatex-math.tex", "max_issues_repo_name": "kensh/pandoc_resume", "max_issues_repo_head_hexsha": "74ea55abde343f4e6e07fa6cd94694816e6e3cc4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/texmf-context/doc/context/sources/general/manuals/luatex/luatex-math.tex", "max_forks_repo_name": "kensh/pandoc_resume", "max_forks_repo_head_hexsha": "74ea55abde343f4e6e07fa6cd94694816e6e3cc4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.5933715743, "max_line_length": 160, "alphanum_fraction": 0.6933367251, "num_tokens": 19369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953797290152, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.3466060044399067}}
{"text": "% !TeX root = ../main.tex\n% Add the above to each chapter to make compiling the PDF easier in some editors.\n\n\\chapter{Imperative B-Trees in Isabelle}\\label{chapter:imp-set}\n\nIn the previous chapter, we have seen\nan abstract definition of B-trees and the reasoning\nbehind its correct implementation of the set interface.\nHowever, the specification would not yield \nefficiently executable code.\n% main difference: specify allocation of data\nThe reason is that the abstract specification utilizes\nthe persistent data types node and list.\nThis way, trivially, no data is unknowingly\nmodified or corrupted,\nhowever this is at the cost of computational efficiency.\nA small change in a list or node\nrequires allocating complete copies of all objects that have to be updated,\nrecursively propagating through the whole data structure.\n\nIn order to obtain an efficient implementation\non ephemeral data structures common to imperative languages,\nwe specify imperative code and show that\nit refines the abstract specification.\nThe imperative code can then be translated to\nthe languages Scala \\parencite{OderskyScala} and SML \\parencite{DBLP:books/daglib/0069232}\nusing the code generator\nfor Isabelle/HOL \\parencite{Haftmann07acode}.\nHowever, code extraction is not limited\nto these specific languages\nsince the code generator is extensible.\n\n\\section{Refinement to Imperative/HOL}\n\nThe proofs of correct behavior for our imperative\ncode are stated in separation logic\nan extension of Hoare Logic invented by Reynolds \\parencite{DBLP:conf/lics/Reynolds02}.\nIt was formalized in Isabelle/HOL by Lammich \\parencite{DBLP:journals/jar/Lammich19}\nand comes with a framework that simplifies reasoning about\nits expressions.\n\n\\subsection{Separation Logic}\n\nSeparation logic provides a way to reason about mutable resources\nthat lie in separated parts of an external heap,\nan abstracted memory device.\nThe assumptions on the state of the heap are called \\textit{assertions}.\nThey are stated as formulae that hold for specific heap states.\nThe basic assertions used in this work are the following:\n\n\\begin{itemize}\n    \\item \\textit{emp} holds for the empty heap\n    \\item \\textit{true} and \\textit{false} hold for every and no heap respectively\n    \\item $\\uparrow(P)$ holds if the heap is empty and predicate $P$ holds\n    \\item $a \\mapsto_a as$ holds if the heap at position $a$ is reserved and contains\n    an array representing $as$.\n    \\item $a \\mapsto_r x$ holds if the heap at position $a$ is reserved and contains\n    value $x$ where $x$ is of some type $'a::heap$\n    \\item $\\exists_A x.\\ P\\ x$ holds if there exists some $x$ such that predicate P\n    holds on the heap for given $x$.\n    \\item $P_1 * P_2$ holds if each assertion holds on its part of the heap\n    and the areas of the heap described by each assertion are non-overlapping\n\\end{itemize}\n\nThe last assertion is key to enabling reasoning about local\nparts of the heap.\nWith the tools provided by separation logic,\nwe will prove our imperative implementations functionally correct\nby showing that they refine the abstract implementation in \\Cref{chapter:abs-set}.\n\nIn general, refinement relates a concrete data structure\nto an abstract structure via some refinement assertion.\nExamples for such a refinement assertion are the id assertion and the\nlist assertion.\nThe latter relates lists, given a refinement\nassertion between the elements of the first and second list.\n\n\\begin{lstlisting}[mathescape=true, language=Isabelle]\ndefinition id_assn a b = $\\uparrow$(a = b)\n\nfun list_assn :: ('a $\\Rightarrow$ 'c $\\Rightarrow$ assn) $\\Rightarrow$ 'a list $\\Rightarrow$ 'c list $\\Rightarrow$ assn where\n  list_assn P [] [] = emp\n| list_assn P (x#xs) (y#ys) = P x y * list_assn P xs ys\n| list_assn _ _ _ = false\n\\end{lstlisting}\n\nWe can then specify Hoare Triples on assertions,\nto encapsulate statements about imperative programs.\n\n\\begin{definition}{Hoare Triple}\n    $\\langle$ P $\\rangle$ c $\\langle \\lambda r. $ Q r $\\rangle$ holds iff \\\\\n    if assertion $P$ holds on some heap before operation $c$\n    is executed on the heap,\n    and operation $c$ returns some $r$, then assertion $Q$ holds\n    for $r$ and on the heap modified by $c$\n\\end{definition}\n\nA simple example Hoare Triple is \n$\\langle$ id\\_assn $a$ $b$ $\\rangle$ return $b$ $\\langle \\lambda r.$ id\\_assn $a$ $r$ $\\rangle$.\nIn the refinement process, we will use more complex relationship assertions\nbetween some abstract $b$ and some refined $bi$.\nWe then show that the value $r$ returned\nby the imperative program \\textit{imp\\_op} satisfies the same relationship\nto \\textit{op} $b$ where \\textit{op} is the refined abstract specification.\nFurther we use the notation $\\langle\\ P\\ \\rangle\\ c\\ \\langle \\lambda r.\\ Q\\ r\\ \\rangle_t$\nas a shorthand for $\\langle\\ P\\ \\rangle\\ c\\ \\langle \\lambda r.\\ Q\\ r\\ * true\\ \\rangle$.\nSince $true$ holds for any heap, this part of the assertion\nmay be used to subsume all temporary and discarded variables.\n\nRefining all set operations from \\Cref{chapter:abs-set}\nwill yield imperative code that operates on the heap\nwith the  option to use efficient destructive updates.\nWe do not need to show that the operations themselves\nsatisfy the requirements of the set interface.\nInstead we merely need to show that the imperative code\nacts on a concretized version of the B-trees\nthe same way as the abstract operations on the abstract version.\nThe abstract idea of this approach is discussed in more detail\nin the work of Lammich \\parencite{DBLP:journals/jar/Lammich19}\n\n% TODO note what to introduce here\n% abstract idea: implementation that has same effect on concrete ds\n% as abstract function on abstract ds\n% TODO short intro hoare triples and notation here\n% *  and \\uparrow\n\n\\subsection{Refinement of abstract lists}\n\nIn the imperative collection framework by Lammich\n\\parencite{DBLP:journals/jar/Lammich19},\nthe abstract data type list is usually\nrefined to a dynamic array like data structure.\nIt comprises an array and a natural number,\nwhere the latter denotes the current number of elements\nstored in the array.\nB-tree nodes do not always contain a constant number of elements,\nwhich is why this property should be transferred to\nthe data structure refining key-value lists. \n\n% TODO intended physical storing of B-tree on pages of memory\n% --> partially filled array, non-dynamic!\nHowever, dynamic arrays are designed to grow and shrink\nas elements are inserted and deleted.\nB-trees were invented to be stored on slow hard disks.\nAs one disk access loads as much data as fits into a page of main memory,\nnodes of roughly this size make the most efficient use of an access\n\\parencite{DBLP:journals/acta/BayerM72}.\n%TODO give clear reason\nTherefore the data structure to store the node content\nshould reserve arrays of fixed size, independent\nof the actual number of keys and children contained.\n\nBased on the definition of dynamic arrays in the \nimperative collection framework,\nwe introduce a simpler data structure,\nthe \\textit{partially filled array},\nthat keeps count of currently inserted elements,\nbut does neither grow nor shrink.\nA list $ls$ is represented by a partially filled array $(a,n)$\nif the array $a$ represents a list $ls'$, of which the first $n$\nelements form list $ls$.\nFormally,\n\n\\begin{lstlisting}[mathescape=true, language=Isabelle]\n\ndatatype 'a pfarray = 'a array $\\times$ nat\n\ndefinition is_pfa :: nat $\\Rightarrow$ 'a list $\\Rightarrow$ 'a pfarray where\n    is_pfa c ls (a,n) =\n        $\\exists_A$ ls'. a $\\mapsto_a$ ls' *  $\\uparrow$(c = length ls' $\\wedge$ n $\\le$ c $\\wedge$ ls = (take n ls'))\n\\end{lstlisting}\n\nwhere $c$ is the $capacity$ of the array,\nthe actually allocated size of the array on the heap.\nAll references to lists in the abstract data type $btree$\nwill in the imperative version be refined to partially filled arrays.\n\nHowever one should note that\nfrom the set operation specification in \\Cref{chapter:abs-set} alone\nit is not determined which operations are supposed to be conducted\nin-place and which will require copying data.\nTo obtain the most efficient code we therefore manually\ndefine the operations in \\Cref{lst:pfarray-def} to replace complex composite\noperations based on list construction and catenation.\n\n% abstract function has length, insertion, take/drop\n% --> concrete implementations\n\\begin{figure}\n\\begin{lstlisting}[mathescape=true, language=Isabelle,label={lst:pfarray-def},\n    caption={Important Partially Filled Array functions for Insertion.}]\ndefinition pfa_length $\\equiv$ $\\lambda$(a,n). return n\n\ndefinition pfa_get $\\equiv$ $\\lambda$(a,n) i. Array.nth a i (* returns the nth element in array a *)\n\ndefinition pfa_set $\\equiv$ $\\lambda$(a,n) i x. do {\n    Array.upd i x a; (* sets the element at position i in a to value x *)\n    return (a,n)\n}\n\ndefinition pfa_shrink k $\\equiv$ $\\lambda$(a,n). return (a,k)\n\ndefinition pfa_shrink_cap  k $\\equiv$ $\\lambda$(a,n). do {\n    a' $\\leftarrow$ array_shrink a k; (* returns an array with the given actual size, potentially reallocated*)\n    return (a',min k n)\n}\n\ndefinition pfa_drop $\\equiv$ $\\lambda$(src,sn) si (dst,dn). do {\n    blit src si dst 0 (sn-si);\n    return (dst,(sn-si))\n}\n\ndefinition pfa_insert $\\equiv$ $\\lambda$(a,n) i x. do {\n  array_shr a i 1; (* shifts elements from index i on to the right by 1 *)\n  Array.upd i x a;\n  return (a,n+1)\n}\n\ndefinition pfa_ensure $\\equiv$ $\\lambda$(a,n) k. do {\n  a' $\\leftarrow$ array_ensure a k default; (* returns an array with given minimal size, potentially reallocated *)\n  return (a',n)\n}\n\ndefinition pfa_insert_grow  $\\equiv$ $\\lambda$(a,n) i x. do {\n  a' $\\leftarrow$ pfa_ensure (a,n) (n+1);\n  a'' $\\leftarrow$ pfa_insert a' i x;\n  return a''\n}\n\n$\\dots$\n\\end{lstlisting}\n\\end{figure}\n\n% TODO also include what the rule gives us?\n\nDuring the splitting of nodes, a part of the overflowing\nlist is copied into another array.\nThe operation to copy data is based on the function $blit$,\nthat copies a slice of an array to a slice of another array.\nThe function already existed in the standard collection and could be reused\nto define the \\textit{pfa\\_drop} function in \\Cref{lst:pfarray-def}, which in this implementation copies data to a new array.\n\nThe $blit$ function is however not capable of correctly copying data\nwithin the array, as required for efficient in-place insertion and deletion.\nA suitable function, called $sblit$, was hence added in the course of this project.\nThe relevant addition is to differentiate between copying elements\nfrom higher to lower indices or from lower to higher indices.\nDepending on the direction of the copy, it is relevant\nin which order to copy singleton elements so that in case\nof overlapping ranges no elements are overwritten before being copied.\n\nBy adding a function that copies elements in reverse order\nand conditionally calling either copy function,\nloss-free in-place copying is achieved.\nThe resulting function is conveniently agnostic to the direction\nof the copying, just as the respective implementations\nin target languages for code extraction.\\footnote{\n    See for example \\href{https://caml.inria.fr/pub/docs/manual-ocaml/libref/Array.html}{the specification of \\texttt{Array.blit} in Ocaml} or\n    the \\href{https://smlfamily.github.io/Basis/array-slice.html\\#SIG:ARRAY_SLICE.copy:VAL}{\\texttt{ArraySlice.copy} specification in SML}.\n}\nThe \\textit{pfa\\_insert} function in \\Cref{lst:pfarray-def} makes\nimplicit use of in-place copying by calling a function to shift elements\nto the right by one.\nThis is achieved by copying the slice of elements\nfrom position $i$ to the end of the list\nto the slice $i+1$ to the end of the list.\nThe element to be inserted is then placed in the remaining free spot.\n\nFor all functions in \\Cref{lst:pfarray-def},\nappropriate Hoare Triples were derived.\nAll triples are straightforward to derive but the reader is encouraged\nto look them up in the proof documents.\nTo roughly sketch the obtained lemmas, the two examples\n\\textit{pfa\\_drop} and \\textit{pfa\\_shrink} are investigated below.\nThe most important difference is whether\nthe operations are destructive (in-place) or not.\nFor most operations, the approach that required the least\nmemory allocations was chosen.\\footnote{\n    The only exception is node$_i$, which in the case of overflow\n    currently requires temporary allocation of an array that holds more than $2k$ elements.\n}\n\n\\begin{lemma}\n    $k \\le \\length s \\wedge (\\length s - k) \\le dn \\Longrightarrow$ \\\\\n    \\begin{center}\n    $\\langle \\pfarraycap$ sn s si * $\\pfarraycap$ dn d di $\\rangle$ \\\\\n    $\\pfadrop$ si k di \\\\\n    $\\langle\\lambda di'. \\pfarraycap$ sn s si * $\\pfarraycap$ dn ($\\drop$ k s) di' $\\rangle$\n    \\end{center}\n\\end{lemma}\n\nThe array $si$ stays untouched.\nThis fact is expressed by the fact that the term about its relationship to $s$\nis still available in the postcondition of the triple.\nThe only thing that changed is the content of $di$.\\footnote{\n    In the actual proof, where possible, we even show that the array itself has not changed\n    (i.e. has not been reallocated).\n    The correct notation does however not yield high readability\n    and is hence abstracted here.\n}\nThe $take$ function was refined differently.\nThe cheapest and in our context consistent way to\nimplement $take$ is to\nreduce the number of elements knowingly stored in the array\nfrom $n$ to $k$.\nThe result is that the original array gets modified and we loose any information\nabout the content that is written beyond given $k$.\n\n\\begin{lemma}\n    $k \\le \\length s\\Longrightarrow$ \\\\\n    \\begin{center}\n    $\\langle \\pfarraycap$ sn s si$\\rangle$\n    $\\pfashrink$ si k\n    $\\langle\\lambda si'. \\pfarraycap$ sn ($\\take$ k s) si' $\\rangle$\n    \\end{center}\n\\end{lemma}\n\nWith these operations and suitable Hoare-Triples on them,\nwe have all the tools required to refine the abstract set implementation.\n% TODO more about sblit?\n\n\\section{Set-Operations}\n\nHaving covered the refinement for the list data type,\nthe B-tree data type itself can be refined.\nRather than actually storing nodes within lists,\nthe B-tree nodes are supposed to be stored in the heap,\nand the node list will only contain pointers to the corresponding nodes.\nPointers are represented by the type \\textit{ref} in Imperative/HOL.\nLeaf nodes contain no information and consequently don't have to be stored\non the heap, therefore we refine them using null pointers.\nSince Imperative/HOL does not support null pointers \\parencite{DBLP:conf/tphol/BulwahnKHEM08},\nand we do not want to explicitly store \\textit{Leaf} objects on the heap,\nB-tree nodes are refined by heap reference \\textit{options} instead.\nThus \\textit{None} represents leafs or empty trees,\nwhile \\textit{Some} heap reference points to refinements of internal nodes.\n\n\\begin{lstlisting}[mathescape=true, language=Isabelle]\ndatatype 'a btnode =\n    Btnode (('a btnode ref option*'a) pfarray) ('a btnode ref option)\n\\end{lstlisting}\n\nNote the similarity to the definition in \\Cref{lst:btree-def},\nonly that \\textit{btree} was replaced by \\textit{btnode ref option},\n\\textit{list} was replaced by \\textit{pfarray},\nand there is no leaf case anymore.\n\nAn abstract B-tree is represented by such a physical node\nif all references on subtrees represent the corresponding\nabstract subtrees and all keys are the same.\nThe precise refinement assertion can be seen in \\Cref{lst:imp-btree-refine}.\n\n\\begin{figure}\n\\begin{lstlisting}[mathescape=true, language=Isabelle, caption={The refinement assertion for B-trees},\n    label={lst:imp-btree-refine}]\nfun btree_assn :: nat $\\Rightarrow$ 'a::heap btree $\\Rightarrow$ 'a btnode ref option $\\Rightarrow$ assn where\n    btree_assn k Leaf None = emp |\n    btree_assn k (Node ts t) (Some a) = ($\\exists_A$ tsi ti tsi'.\n        a $\\mapsto_r$ Btnode tsi ti\n        * btree_assn k t ti\n        * is_pfa (2*k) tsi' tsi\n        * list_assn ((btree_assn k) $\\times_a$ id_assn) ts tsi'\n        ) |\n    btree_assn _ _ _ = false\n\nabbreviation blist_assn k $\\equiv$ list_assn ((btree_assn k) $\\times_a$ id_assn)\n\n\\end{lstlisting}\n\\end{figure}\n\nIt seems a little bit awkward that the definition\nincludes two relationships regarding only the list of elements in the subtree.\nThe reason is that there are two steps of refinements going on.\nFirst, all elements in the list are refined to their imperative counterparts.\nThis fact is expressed by the \\textit{list\\_assn} term in the assumption.\nSecond, the list itself is refined to an array.\nThis is expressed in \\textit{is\\_pfa} term.\nSince the list assumption makes recursive use of the\nB-tree assertion, we again cover up usage of the term\nby an abbreviation.\n\nUsing the parameters of \\textit{is\\_pfa},\nnote that we can specify that every node of a B-tree should have\na capacity of $2k$.\n\n\\subsection{The split function}\n\\label{sec:imp-split}\n\nTo implement any set operations we again need a split operation.\nHowever, what split function exactly will be used can be abstracted again.\nThe only important thing is that it refines an abstract split function.\nHowever we have some freedom on how to specify this refinement relationship.\n\nImperative split functions should be efficient and as such should not actually\nsplit the array in half.\nThe operation should rather return the index of the correct\nsubtree-separator pair.\nThe refinement condition derived from this relationship is as follows.\n\n\\begin{lstlisting}[mathescape=true, language=Isabelle]\ndefinition split_relation xs (ls,rs) i = i $\\le$ length xs $\\wedge$ ls = take i xs $\\wedge$ rs = drop i xs\n\\end{lstlisting}\n\nA very useful alternative statement of the relationship follows automatically.\nThis allows us to simplify terms that only contain $xs$\nto the two sublists when we obtain this relationship in proofs.\n\n\\begin{lemma}\n    $\\splitrelation xs\\ (ls,rs)\\ i = (xs = ls@rs \\wedge i = \\length ls)$\n\\end{lemma}\n\nFrom this, we characterize the desired imperative\nsplit function \\textit{imp\\_split} by its Hoare-Triple.\n\n\\begin{align*}\n    \\langle & \\pfarraycap c\\ xs\\ (a,n) \\rangle \\\\\n            & \\impsplit\\ (a,n)\\ p \\\\\n\\langle\\lambda i. & \\pfarraycap c\\ xs\\ (a,n)\\\\\n& * \\uparrow(\\splitrelation xs\\ (\\splitfun xs\\ p)\\ i)\\rangle_t\n\\end{align*}\n\nJust as with the abstract implementation,\nthe imperative refinements can be built with this characterization alone.\nHowever this time we are actually interested in finding an\nefficient split and will spend some time finding\na good split function.\n%TODO move to after the set operations?\n\nIn the imperative context, we prefer not to directly\nrefine the recursive function from \\Cref{fig:linear_split}\nbut we embark on the exercise of using a while loop.\nThe implementation in \\Cref{lst:imp-linear-split}\nnot more efficient than the functional linear search,\nbut suitable for getting to know\nthe usage of while loops in imperative HOL.\nEvery iteration, an index on the array is moved forward by one.\nThe main part is done in the loop head - if we\nare within the array bounds,\nwe obtain the current separator and check if it is\nsmaller than the partitioning element.\nWe return the first index at which the separator is greater or equal.\n\n\\begin{figure}\n\\begin{lstlisting}[mathescape=true, language=Isabelle, caption={The imperative linear split},\n    label={lst:imp-linear-split}]\ndefinition lin_split :: ('a::heap $\\times$ 'b::{heap,linorder}) pfarray $\\Rightarrow$ 'b $\\Rightarrow$ nat Heap where\n    lin_split (a,n) p = do { \n        i $\\leftarrow$ while  \n            ($\\lambda$i. if i<n then do { \n                (_,s) $\\leftarrow$ Array.nth a i; \n                return (s<p) \n            } else return False)  \n            ($\\lambda$i. return (i+1))  \n            0; \n        return i \n    }\n\\end{lstlisting}\n\\end{figure}\n\nAs mentioned, the internal behavior of this function is\nquite different to the abstract linear split from \\Cref{fig:linear_split}.\nTherefore, proving that it refines the abstract function requires a small detour.\nWe first express and show the most basic, non-trivial statement\nwe can make about the result of the function.\nWe then show that the result is the same as the result\nof applying the abstract function,\nthat is that to an external observer, the functions behave the same.\n\nWe begin by stating a simple matching Hoare Triple\nfor the function.\n\n\\begin{lemma}\n    \\label{lem:lin-split-ht}\n    \\begin{align*}\n        \\langle &\\pfarraycap c\\ xs\\ (a,n)\\rangle \\\\\n                  &\\linsplit\\ (a,n)\\ p \\\\\n        \\langle \\lambda i. & \\pfarraycap c\\ xs\\ (a,n) \\\\\n        * &\\uparrow(i \\leq n \n            \\wedge (\\forall j < i.\\ snd (xs!j) < p) \n            \\wedge (i<n \\longrightarrow snd (xs!i) \\geq p)) \\rangle_t \n    \\end{align*}\n\\end{lemma}\n\nIt follows by supplying the following loop invariant:\n\n\\begin{itemize}\n    \\item $\\forall j<i.\\ \\snd (xs!j) < p$: All elements up to the current $i$\n        are smaller than the partitioning element,\n    \\item $\\uparrow(i \\leq n)$: $i$ does not exceed the length of the array and\n    \\item $\\pfarraycap c\\ xs\\ (a,n)$: the array is not manipulated by the operation\n\\end{itemize}\n\nIn order to show that the loop also terminates,\nwe need to provide a measure that strictly decreases in each iteration.\nThe measure for the loop is the difference $n-i$ which\ndecrements by one in each iteration and stays positive.\n\nFor unexciting reasons, the post condition we have thus obtained\nactually suffices to imply that the split relation\nto the result of an abstract split function is satisfied.\nSpecifically, we use the abstract split function from\n\\Cref{fig:linear_split}. %TODO or explain why a different function was used\nFor the two cases of loop termination,\neither $i = n$, or $i < n$, we find that\nthe abstract function will return the exact same split.\n\nThis is fortunate since the previous lemma\nfollows directly from the computation and is closely related\nto the loop invariant.\nThis will simplify proofs for alternative imperative split functions.\n\\footnote{\n    Another, albeit more theoretical,\n    reason for excitement is that we can now specify imperative B-tree\n    interfaces without any reference to the abstraction.\n    We simply always use the abstract linear split function\n    and only require that the imperative split function satisfies\n    the hoare triple from \\Cref{lem:lin-split-ht}.\n}\nWith this reassurance we approach the binary split.\n\nA detailed analysis of binary search algorithms\nmay be found in the work of Montague \\parencite{DBLP:journals/csedu/Montague91},\nwhich has served as an orientation\nfor the derived algorithm in \\Cref{lst:imp-binary-split}.\nRather than walking through the array,\nit narrows the range in which the desired element may lie\nto a window that it bisected in every iteration.\nThis bisection is implemented by inspecting the middle element of the window.\nIf the desired element was not found, the algorithm\nrecurses into either the remaining subwindow to the left or right.\nIn the final iteration,\nthe window has narrowed down to a single element,\ncontaining the correct separator and subtree.\n\n\\begin{figure}\n\\begin{lstlisting}[mathescape=true, language=Isabelle, caption={The imperative binary split},\n    label={lst:imp-binary-split}]\ndefinition bin_split :: ('a::heap $\\times$ 'b::{heap,linorder}) pfarray $\\Rightarrow$ 'b $\\Rightarrow$ nat Heap \n    where bin_split (a,n) p = do { \n        (low',high') $\\leftarrow$ while  \n            ($\\lambda$(low,high). return (low < high))  \n            ($\\lambda$(low,high).\n            let mid = ((low  + high) div 2) in \n            do { \n                (_,s) $\\leftarrow$ Array.nth a mid; \n                if p < s then \n                    return (low, mid) \n                else if p > s then \n                    return (mid+1, high) \n                else\n                    return (mid,mid) \n            })  \n            (0::nat,n); \n        return low' \n    }\n\\end{lstlisting}\n\\end{figure}\n\nSince pairs as list elements (i.e. pairs of trees and separators)\nwere expected to add another layer of complexity,\na binary split algorithm on normal lists has been derived first.\nThe split function for lists of pairs was then defined\nand could be tackled using the same loop invariant.\nNote that the binary split works on two indices\nas states, the upper bound $h$ and the lower bound $l$.\n\n\\begin{itemize}\n    \\item $\\forall j<l.\\ \\snd (xs!j) < p$: All elements up to the current $l$\n        are smaller than the partitioning element,\n    \\item $h<n \\rightarrow \\snd (xs!h) < p$: If the upper bound $h$\n    is strictly less than the length of the array,\n    the element it points to is greater than the partioning element,\n    \\item $\\uparrow(l \\leq h)$: The lower bound is always less or equal to the upper bound,\n    \\item $\\uparrow(h \\leq n)$: the upper bound does not exceed the length of the array and\n    \\item $\\pfarraycap c\\ xs\\ (a,n)$: again, the array is not manipulated by the operation\n\\end{itemize}\n\nIn this case the window that is considered by the binary split\nprovides the loop measure, as $h-l$ decreases by at least one in each step.\nProving that this is the case was not the main issue,\nbut rather finding a correct formulation of the algorithm\nwhere this is actually true.\n\nOverall obtaining the same Hoare Triple\nas for the linear split required only\nthis slightly more complex loop invariant\nand invocation of a number of algebraic lemmas.\nThis came to us somewhat of a surprise, since the functional\nversion of a binary split is much harder to\nspecify and analyse than a functional linear split.\nThe additional requirement for the binary split is\nnaturally that the list of separators must be sorted.\n\n\\begin{lemma} $\\sorted (\\separators xs) \\Longrightarrow$ \\\\\n    \\label{lem:imp-bin-split-ht}\n    \\begin{align*}\n        \\langle &\\pfarraycap c\\ xs\\ (a,n)\\rangle \\\\\n                  &\\binsplit\\ (a,n)\\ p \\\\\n        \\langle \\lambda i. & \\pfarraycap c\\ xs\\ (a,n)\\\\\n        &* \\uparrow(i \\leq n \n            \\wedge (\\forall j < i. snd (xs!j) < p) \n            \\wedge (i<n \\longrightarrow snd (xs!i) \\geq p)) \\rangle_t \n    \\end{align*}\n\\end{lemma}\n\nSince we know that this implies equivalence to the abstract split function\nand sortedness of the separators is guaranteed by the sortedness\ninvariant of the B-trees,\nwe can safely use this function for specifying\nthe set operations.\n\n%TODO Note the choice of a while-loop for efficiency\n%TODO The split function can be implemented linearly (easier, proof of concept)\n% but due to abstraction of functionality may use binary split as well.\n\n\\subsection{The isin function}\n\nIn general, the formulation of the imperative set operations\ndo quite directly follow\nfrom the refinement of the abstract operations.\nThe main difference is the usage of pointers,\nthat need to be dereferenced and updated.\nFunctions such as length need to be called and have their result\nstored explicitly before use.\nOther than that, the definition of the imperative isin in \\Cref{lst:imp-isin-fun}\nfunction should bare no surprises.\nNote that it makes use of the function \\textit{imp\\_split}\nwhich is an arbitrary split function that fulfills the Hoare Triple\nof \\Cref{lem:imp-bin-split-ht}.\n\n\\begin{figure}\n\\begin{lstlisting}[mathescape=true, language=Isabelle, label={lst:imp-isin-fun},\n    caption={The imperative isin function}]\npartial_function (heap) isin :: 'a btnode ref option $\\Rightarrow$ 'a $\\Rightarrow$  bool Heap\n  where\n    isin p x = (case p of\n        None $\\Rightarrow$ return False |\n        (Some a) $\\Rightarrow$ do {\n        node $\\leftarrow$ !a;\n        i $\\leftarrow$ imp_split (kvs node) x;\n        tsl $\\leftarrow$ pfa_length (kvs node);\n        if i < tsl then do {\n            s $\\leftarrow$ pfa_get (kvs node) i;\n            let (sub,sep) = s in\n            if x = sep then\n            return True\n        else\n            isin sub x\n        } else\n            isin (last node) x\n    }\n)\n\\end{lstlisting}\n\\end{figure}\n\nThe convention for variables that refer to refined data types\nis that they have the same name as the abstract data type,\nwith the postfix \\textit{i}.\nFor example below, the abstract \\textit{btree} is referred to by $t$,\nhowever the refined \\textit{btnode ref option} is called $ti$.\nTo simplify notation, we simply assume that the set operations\nsuch as \\textit{isin} are overloaded and refer to abstract or\nimperative implementations, depending on the parameter type.\nThe Hoare Triple to argue that the imperative \\textit{isin}\nrefines the abstract \\textit{isin} follows.\n\n\\begin{lemma} $\\sorted (\\inorder t) \\Longrightarrow$ \\\\\n\\begin{align*}\n   \\langle &\\btreeassn k\\ t\\ ti\\rangle \\\\\n           &\\isinfun ti\\ x \\\\\n   \\langle \\lambda r. &\\btreeassn k\\ t\\ ti\\ * \\uparrow(\\isinfun t\\ x = r)\\rangle_t\n\\end{align*}\n\\end{lemma}\n\nNote how, in contrast to the abstract specification,\nwe need to also show that the imperative function does not modify the tree\nresiding in the heap.\nThe proof follows by induction on the computation of the abstract isin function.\n\n% TODO conclusion ?\nInside a structured proof skeleton of the induction,\nproving the subgoals in apply style turned out to be the most\nappropriate.\nThe separation automation tool only required help\nfor the instantiation of existential quantifiers,\nespecially after application of the inductive hypothesis. \n% TODO more details?\n\n\\subsection{Insertion}\n% TODO...\n\\begin{figure}\n\\begin{lstlisting}[mathescape=true, language=Isabelle, label={lst:imp-nodei-fun},\n    caption={The imperative node$_i$ function}]\ndefinition node$_i$ \n    :: nat $\\Rightarrow$ ('a btnode ref option $\\times$ 'a) pfarray $\\Rightarrow$ 'a btnode ref option $\\Rightarrow$ 'a btupi Heap\n    where node$_i$ k a ti $\\equiv$ do {\n        n $\\leftarrow$ pfa_length a;\n        if n $\\le$ 2*k then do {\n            a' $\\leftarrow$ pfa_shrink_cap (2*k) a;\n            l $\\leftarrow$ alloc (Btnode a' ti);\n            return (T$_i$ (Some l))\n        } else do {\n            b $\\leftarrow$ (pfa_empty (2*k) :: ('a btnode ref option $\\times$ 'a) pfarray Heap);\n            i $\\leftarrow$ split_half a;\n            m $\\leftarrow$ pfa_get a i;\n            b' $\\leftarrow$ pfa_drop a (i+1) b;\n            a' $\\leftarrow$ pfa_shrink i a; \n            a'' $\\leftarrow$ pfa_shrink_cap (2*k) a';\n            let (sub,sep) = m in do {\n                l $\\leftarrow$ alloc (Btnode a'' sub);\n                r $\\leftarrow$ alloc (Btnode b' ti);\n                return (Up$_i$ (Some l) sep (Some r))\n            }\n        }\n    }\n\n\\end{lstlisting}\n\\end{figure}\n\n\\begin{figure}\n\\begin{lstlisting}[mathescape=true, language=Isabelle, label={lst:imp-ins-fun},\n    caption={Excerpt of the imperative insert function}]\n\npartial_function (heap) ins :: nat $\\Rightarrow$ 'a $\\Rightarrow$ 'a btnode ref option $\\Rightarrow$ 'a btupi Heap \n    where ins k x apo = (case apo of \n    None $\\Rightarrow$ return (Up$_i$ None x None) | \n    (Some ap) $\\Rightarrow$ do { a $\\leftarrow$ !ap; i $\\leftarrow$ imp_split (kvs a) x; tsl $\\leftarrow$ pfa_length (kvs a); \n      if i < tsl then do { \n        s $\\leftarrow$ pfa_get (kvs a) i; \n        let (sub,sep) = s in \n        if sep = x then return (T$_i$ apo) \n        else do { \n          r $\\leftarrow$ ins k x sub; \n          case r of  \n            (T$_i$ lp) $\\Rightarrow$ do { pfa_set (kvs a) i (lp,sep); return (T$_i$ apo) \n            } | \n            (Up$_i$ lp x' rp) $\\Rightarrow$ do { \n              pfa_set (kvs a) i (rp,sep); \n              if tsl < 2*k then do { \n                  ts' $\\leftarrow$ pfa_insert (kvs a) i (lp,x'); \n                  ap := (Btnode ts' (last a)); \n                  return (T$_i$ apo) \n              } else do { \n                ts' $\\leftarrow$ pfa_insert_grow (kvs a) i (lp,x'); \n                node$_i$ k ts' (last a) \n        } } } } else $\\dots$\n\ndefinition insert :: nat $\\Rightarrow$ ('a::{heap,default,linorder}) $\\Rightarrow$ 'a btnode ref option $\\Rightarrow$ 'a btnode ref option Heap\n    where insert $\\equiv$ $\\lambda$ k x ti. do {\n    ti' $\\leftarrow$ ins k x ti;\n    case ti' of\n        T$_i$ sub $\\Rightarrow$ return sub |\n        Up$_i$ l a r $\\Rightarrow$ do {\n            ts' $\\leftarrow$ pfa_init (2*k) (l,a) 1;\n            t' $\\leftarrow$ alloc (Btnode ts' r);\n            return (Some t')\n        }\n    }\n\n\\end{lstlisting}\n\\end{figure}\n\n%TODO Description of applying the refinement framework to the insert function\nThe imperative implementation and derived heap rule of the \\textit{insert} function follow\nthe same pattern as the \\textit{isin} function.\nThe only interesting part is whether and how often new memory is allocated.\nAn excerpt of the refinement of the \\textit{ins} function\ncan be seen in \\Cref{lst:imp-ins-fun}\\footnote{\n    In the imperative language in Isabelle, allocating heap memory\n    is abbreviated by \\textit{ref}.\n    To clarify that this means allocation, it is named \\textit{alloc} here.\n}.\nThe function includes some simple optimizations, such as not calling\n\\textit{node$_i$} if the node is not overflowing.\nThis is an optimization as otherwise \\textit{node$_i$} in\n\\Cref{lst:imp-nodei-fun} would always allocate a new B-tree node\nrather than updating the current node in place.\n\nTo prove that this optimization is valid, the only obligation\nis to show that the updated node itself is equivalent\nto the node returned by \\textit{node$_i$}.\nSince we are in the branch where the node contains less than $2k$\nelements, this is easy to show, provided some intermediate lemmas\nthat relate concrete node and abstract node in this context.\n\n\\begin{lemma}$\\length ts \\leq 2k \\Longrightarrow\n    \\node_i k\\ ts\\ t = T_i (Node\\ ts\\ t)$\n\\end{lemma}\n\n\\begin{samepage}\nBy adding a lemma on the equivalence between abstract and imperative\n\\textit{node$_i$}, we obtain a lemma for \\textit{ins}\nby induction on the computation\nof the abstract \\textit{ins} function.\n\n\\begin{lemma} $\\sorted (\\inorder t) \\Longrightarrow$ \\\\\n    \\begin{align*}\n       \\langle &\\btreeassn k\\ t\\ ti\\rangle \\\\\n               &\\insfun k ti\\ x \\\\\n       \\langle \\lambda r. &\\btreeassn k\\ (\\insfun k\\ t\\ x) r\\rangle_t\n    \\end{align*}\n\\end{lemma}\n\\end{samepage}\n\nThe proof of this lemma was done in a mixed structural and apply style manner.\nIt could have been done in a complete apply style manner.\nHowever many subgoals are generated in the proof process that are\nsimply invalid due to the preconditions of the hoare triple.\nEmbedding the proof in the structural skeleton makes spotting\nthese void statements easier and allows to have a better\noverview over the current state of the proof.\n\nThe insertion function incorporates the function \\textit{tree}$_i$\nin much the same way as \\textit{ins} incorporated the small \\textit{node}$_i$ optimizations.\nHere the proof of equivalence followed automatically.\nWith the hoare triple for \\textit{ins}, we obtain the final desired lemma\non the imperative insertion.\n\n\\begin{theorem} $k > 0 \\wedge \\sorted (\\inorder t) \\Longrightarrow$ \\\\\n\\begin{align*}\n   \\langle &\\btreeassn k\\ t\\ ti\\rangle \\\\\n           &\\insertfun k\\ x\\ ti \\\\\n   \\langle \\lambda ri. &\\btreeassn k\\ (\\insertfun k\\ x\\ t)\\ ri\\rangle_t\n\\end{align*}\n\\label{thm:imp-ins-rule}\n\\end{theorem}\n\n% TODO say something about k?\nNote how we have the additional assumption that $k$ is positive.\nThis was only required to show correct order in the abstract setting.\nHere, the capacity of the root node needs to be specified at initialization.\nAnd since the capacity has to be $2k$ and the node has to hold at least one element\na positive $k$ is required such that no contradiction appears.\n\nUntil now we have only shown that the concrete\nimplementations refine the abstract interpretations.\nWhat does this mean concretely?\nDo we have to resort to an informal argument to show that the result\nsatisfies the invariants and the set interface?\nThis is not the case.\n\nThe final theorem that proves functional correctness of the imperative\nimplementations with respect to the set interface follows.\n\n\\begin{corollary} $k > 0 \\Longrightarrow$\n\\begin{align*}\n   \\langle &\\btreeassn k\\ t\\ ti \\wedge \\btree_k t \\rangle \\\\\n           &\\insertfun k\\ x\\ ti \\\\\n   \\langle \\lambda ri. \\exists_A r. &\\btreeassn k\\ r\\ ri \\wedge \\btree_k r \\wedge \\inorder r = \\inslist x\\ (\\inorder t)\\rangle_t\n\\end{align*}\n\\end{corollary}\n\nAnd indeed, this can be derived automatically with a single command invocation,\nunfolding \\Cref{def:btree-def} and using \\Cref{thm:imp-ins-rule}, \\Cref{thm:ins-set} and \\Cref{thm:ins-invar}.\\footnote{\n    Technically we also need the fact that ins$_{list}$ preserves sortedness.\n    This was already proven by Nipkow \\parencite{DBLP:conf/itp/Nipkow16}\n    and is not considered here.\n}\n\n\n\\subsection{Deletion}\n\nAn imperative version of the deletion operation has been specified.\nIt required some additional operations on partially filled arrays but\nposed no fundamental challenges.\nDue to its length it is not shown here but may be looked up in the\nactual proof documents.\n\nHowever, the proof of its refining property was not conducted.\nWe assume that this proof would be structured similar to\nthe previous proofs.\nThe only benefit would be exploring usage of the new\nheap rules introduced for the additional array operations.\nThe main difference to the verification of the\ninsertion function is that the refined functions\nare undefined for many cases.\nHence it is highly important\nto strongly tie the refined and imperative version\nin order to discharge void cases.\n", "meta": {"hexsha": "032a1eba840374d9366318b0ff15e0a3b877aa33", "size": 37286, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/03_imperative.tex", "max_stars_repo_name": "nielstron/btrees-thesis", "max_stars_repo_head_hexsha": "14b6d8a4819378140e5a977e5278ae0a48057f6f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/03_imperative.tex", "max_issues_repo_name": "nielstron/btrees-thesis", "max_issues_repo_head_hexsha": "14b6d8a4819378140e5a977e5278ae0a48057f6f", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/03_imperative.tex", "max_forks_repo_name": "nielstron/btrees-thesis", "max_forks_repo_head_hexsha": "14b6d8a4819378140e5a977e5278ae0a48057f6f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.4186575654, "max_line_length": 143, "alphanum_fraction": 0.7253124497, "num_tokens": 9512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.34660600397108476}}
{"text": "\n\\section*{Problem 2}\n\n\\begin{problem}{A.}\n\\vspace{2mm}\n\nWe have a hypothetical crystal, whose refractive index depends on both the polarisation and direction of propagation of an incoming EM wave.\n\\\\\nLet us choose a Cartesian reference frame, where the boundary between the medium we are investigating and vacuum is $x=0$ plane. The incident wave, lies in the xy plane, having a wave vector $\\vec{k}_i$, making an angle $\\theta_i$ with the $x-\\mathrm{axis}$ (As shown in the  figure). Let us define two polarisations, S and P. Where S polarisation is when the wave is polarised perpendicular to the incident $xy$ plane and P is the polarisation when the electric field of the wave lies in the xy plane. Let us assume two real and positive refractive indices for S and P waves $\\eta_S$ and $\\eta_P$ repectively. Without loss of generality assume $\\eta_P>\\eta_S$.\n\\\\\nSay the incoming wave is linearly polarised confined in the $xy$ plane, with its electric field making an angle $\\frac{\\pi}{4}$ with the $z$ axis. This wave is a mixture of both $S$ and $P$ polarisation. It splits into two at different angles $\\theta_{t\\pm}=\\theta_t \\pm \\alpha$, where $\\vec{k}_{t+}$ corresponds to S, and $\\vec{k}_{t-}$ corresponds to P. \n\\end{problem}\n\\begin{center}\n    \n\n\\tikzset{every picture/.style={line width=0.75pt}} %set default line width to 0.75pt        \n\n\\begin{tikzpicture}[x=0.75pt,y=0.75pt,yscale=-1,xscale=1]\n%uncomment if require: \\path (0,606); %set diagram left start at 0, and has height of 606\n\n%Shape: Rectangle [id:dp41394729732408253] \n\\draw  [draw opacity=0][fill={rgb, 255:red, 155; green, 155; blue, 155 }  ,fill opacity=0.35 ] (251.13,82.37) -- (485.49,82.37) -- (485.49,289) -- (251.13,289) -- cycle ;\n%Shape: Axis 2D [id:dp26172173283960065] \n\\draw [line width=1.5]  (153.17,162) -- (515.81,162)(250,15) -- (250,289) (508.81,157) -- (515.81,162) -- (508.81,167) (245,22) -- (250,15) -- (255,22)  ;\n%Straight Lines [id:da8337450025284996] \n\\draw  [dash pattern={on 4.5pt off 4.5pt}]  (119.17,285.2) -- (247.17,163.2) ;\n%Curve Lines [id:da1405822884062613] \n\\draw  [dash pattern={on 4.5pt off 4.5pt}]  (217.13,164) .. controls (212.3,164.95) and (226.77,183.09) .. (227.5,180.02) ;\n%Straight Lines [id:da479198997901781] \n\\draw [line width=2.25]    (162.74,243.46) -- (197.17,211) ;\n\\draw [shift={(200.81,207.57)}, rotate = 136.68] [fill={rgb, 255:red, 0; green, 0; blue, 0 }  ][line width=0.08]  [draw opacity=0] (11.43,-5.49) -- (0,0) -- (11.43,5.49) -- cycle    ;\n%Straight Lines [id:da6299546920152124] \n\\draw [line width=0.75]  [dash pattern={on 4.5pt off 4.5pt}]  (248.32,161.72) -- (444.81,58.57) ;\n%Straight Lines [id:da3883728648151408] \n\\draw [line width=0.75]  [dash pattern={on 4.5pt off 4.5pt}]  (247.17,163.2) -- (444.81,87.93) ;\n%Straight Lines [id:da4998060156867363] \n\\draw [line width=0.75]  [dash pattern={on 4.5pt off 4.5pt}]  (248.32,161.72) -- (445.81,118.93) ;\n%Curve Lines [id:da6470768122125261] \n\\draw [line width=1.5]  [dash pattern={on 5.63pt off 4.5pt}]  (379.8,92.91) .. controls (395.81,95.93) and (391.81,139.93) .. (390.81,127.93) ;\n%Curve Lines [id:da8038047661899634] \n\\draw [line width=1.5]  [dash pattern={on 5.63pt off 4.5pt}]  (329.8,131.91) .. controls (338.32,133.52) and (339.19,144.75) .. (337.99,153.1) .. controls (336.93,160.44) and (334.27,165.54) .. (333.81,159.93) ;\n%Straight Lines [id:da4217023866157301] \n\\draw [line width=2.25]    (345.56,110.14) -- (390.35,87.19) ;\n\\draw [shift={(394.8,84.91)}, rotate = 152.87] [fill={rgb, 255:red, 0; green, 0; blue, 0 }  ][line width=0.08]  [draw opacity=0] (10,-4.8) -- (0,0) -- (10,4.8) -- cycle    ;\n%Straight Lines [id:da49843178394801124] \n\\draw [line width=2.25]    (352.81,139.93) -- (403.95,127.14) ;\n\\draw [shift={(408.81,125.93)}, rotate = 165.96] [fill={rgb, 255:red, 0; green, 0; blue, 0 }  ][line width=0.08]  [draw opacity=0] (10,-4.8) -- (0,0) -- (10,4.8) -- cycle    ;\n%Shape: Circle [id:dp03983391745542253] \n\\draw  [fill={rgb, 255:red, 0; green, 0; blue, 0 }  ,fill opacity=1 ] (244.51,161.93) .. controls (244.51,158.46) and (247.33,155.64) .. (250.81,155.64) .. controls (254.28,155.64) and (257.1,158.46) .. (257.1,161.93) .. controls (257.1,165.41) and (254.28,168.22) .. (250.81,168.22) .. controls (247.33,168.22) and (244.51,165.41) .. (244.51,161.93) -- cycle ;\n%Shape: Cube [id:dp6684229072869232] \n\\draw  [fill={rgb, 255:red, 0; green, 0; blue, 0 }  ,fill opacity=0.22 ] (244.28,398.8) -- (295.28,347.8) -- (511.28,347.8) -- (511.28,473.8) -- (460.28,524.8) -- (244.28,524.8) -- cycle ; \\draw   (511.28,347.8) -- (460.28,398.8) -- (244.28,398.8) ; \\draw   (460.28,398.8) -- (460.28,524.8) ;\n%Straight Lines [id:da7498729323670823] \n\\draw    (123.68,487.8) -- (123.68,371.8) ;\n\\draw [shift={(123.68,368.8)}, rotate = 90] [fill={rgb, 255:red, 0; green, 0; blue, 0 }  ][line width=0.08]  [draw opacity=0] (10.72,-5.15) -- (0,0) -- (10.72,5.15) -- (7.12,0) -- cycle    ;\n%Straight Lines [id:da8208999367418137] \n\\draw    (123.68,487.8) -- (290.88,487.8) ;\n\\draw [shift={(293.88,487.8)}, rotate = 180] [fill={rgb, 255:red, 0; green, 0; blue, 0 }  ][line width=0.08]  [draw opacity=0] (10.72,-5.15) -- (0,0) -- (10.72,5.15) -- (7.12,0) -- cycle    ;\n%Straight Lines [id:da7174552504343465] \n\\draw    (123.68,487.8) -- (177.03,420.16) ;\n\\draw [shift={(178.88,417.8)}, rotate = 128.26] [fill={rgb, 255:red, 0; green, 0; blue, 0 }  ][line width=0.08]  [draw opacity=0] (10.72,-5.15) -- (0,0) -- (10.72,5.15) -- (7.12,0) -- cycle    ;\n%Straight Lines [id:da21779076116998253] \n\\draw  [dash pattern={on 4.5pt off 4.5pt}]  (123.68,487.8) -- (279.98,447.55) ;\n\\draw [shift={(282.88,446.8)}, rotate = 165.56] [fill={rgb, 255:red, 0; green, 0; blue, 0 }  ][line width=0.08]  [draw opacity=0] (10.72,-5.15) -- (0,0) -- (10.72,5.15) -- (7.12,0) -- cycle    ;\n%Straight Lines [id:da4538137858169531] \n\\draw    (175.88,474.8) -- (230,459.61) ;\n\\draw [shift={(232.88,458.8)}, rotate = 164.32] [fill={rgb, 255:red, 0; green, 0; blue, 0 }  ][line width=0.08]  [draw opacity=0] (10.72,-5.15) -- (0,0) -- (10.72,5.15) -- (7.12,0) -- cycle    ;\n%Curve Lines [id:da5782358459753356] \n\\draw  [dash pattern={on 4.5pt off 4.5pt}]  (151.28,452.8) .. controls (164.88,452.8) and (169.88,484.8) .. (162.88,487.8) ;\n\n%Straight Lines [id:da995607271595156] \n\\draw  [dash pattern={on 4.5pt off 4.5pt}]  (460.28,524.8) -- (459.96,555.61) -- (459.88,562.6) ;\n%Straight Lines [id:da22758558142862872] \n\\draw  [dash pattern={on 4.5pt off 4.5pt}]  (511.28,473.8) -- (511.12,489.63) -- (510.97,503.6) -- (510.88,511.6) ;\n%Straight Lines [id:da17388485750558225] \n\\draw  [dash pattern={on 4.5pt off 4.5pt}]  (462.41,541.68) -- (509.16,494.92) ;\n\\draw [shift={(511.28,492.8)}, rotate = 135] [fill={rgb, 255:red, 0; green, 0; blue, 0 }  ][line width=0.08]  [draw opacity=0] (10.72,-5.15) -- (0,0) -- (10.72,5.15) -- (7.12,0) -- cycle    ;\n\\draw [shift={(460.28,543.8)}, rotate = 315] [fill={rgb, 255:red, 0; green, 0; blue, 0 }  ][line width=0.08]  [draw opacity=0] (10.72,-5.15) -- (0,0) -- (10.72,5.15) -- (7.12,0) -- cycle    ;\n% Text Node\n\\draw (102.68,377.2) node [anchor=north west][inner sep=0.75pt]    {${y}$};\n% Text Node\n\\draw (295.88,491.2) node [anchor=north west][inner sep=0.75pt]    {${z}$};\n% Text Node\n\\draw (291.68,439.2) node [anchor=north west][inner sep=0.75pt]    {${x}$};\n% Text Node\n\\draw (212.68,434.2) node [anchor=north west][inner sep=0.75pt]    {${k_{i}}$};\n% Text Node\n\\draw (168.68,398.2) node [anchor=north west][inner sep=0.75pt]    {${E_{i}}$};\n% Text Node\n\\draw (170.68,441.2) node [anchor=north west][inner sep=0.75pt]    {$\\phi$};\n% Text Node\n\\draw (487.78,521.7) node [anchor=north west][inner sep=0.75pt]    {${d}$};\n% Text Node\n\\draw (516.8,169.31) node [anchor=north west][inner sep=0.75pt]    {${X}$};\n% Text Node\n\\draw (226.8,19.31) node [anchor=north west][inner sep=0.75pt]    {${Y}$};\n% Text Node\n\\draw (379.8,136.31) node [anchor=north west][inner sep=0.75pt]    {${k_{t-}}$};\n% Text Node\n\\draw (403.8,106.31) node [anchor=north west][inner sep=0.75pt]    {$-\\alpha $};\n% Text Node\n\\draw (393.62,86.13) node [anchor=north west][inner sep=0.75pt]  [rotate=-338.35]  {$+\\alpha $};\n% Text Node\n\\draw (364.8,68.31) node [anchor=north west][inner sep=0.75pt]    {${k_{t+}}$};\n% Text Node\n\\draw (349.06,143.73) node [anchor=north west][inner sep=0.75pt]    {${\\theta }_{t}$};\n% Text Node\n\\draw (191.8,167.4) node [anchor=north west][inner sep=0.75pt]    {${\\theta _{i}}$};\n% Text Node\n\\draw (181.7,234.84) node [anchor=north west][inner sep=0.75pt]  [rotate=-314.46]  {${k_{i}}$};\n% Text Node\n\\draw (228.8,142.4) node [anchor=north west][inner sep=0.75pt]    {$Z$};\n\n\n\\end{tikzpicture}\n\n\\end{center}\n\\newpage\n\\begin{subpr}{A1. \\hfill 1.5 pts.} Find $n_S$  and $n_P$ in terms of $\\theta_t$, $\\theta_i$, $\\alpha$. Assume that $n_S=n_0+\\Delta n$ and $n_P=n_0-\\Delta n$, where $\\Delta n/n_0 <<1$ and we only look for first-order terms in $\\Delta n/n_0$.\n\\end{subpr}\n\\begin{problem}{}\n Now assume the incidence to be normal, and the electric field still makes an angle $\\pi/4$ with the $z$-axis (As can be seen in the figure). The crystal has a thickness $t>>\\lambda$. \n\\end{problem}\n\\begin{subpr}{A2. \\hfill 1 pts.} Find the values of $t$ for which the light exiting crystal is either circularly polarised or it is linearly polarised, but rotated by and angle $\\pi/2$ with respect to the incident polarisation. You may neglect the difference between Reflection coefficients for $S$ and $P$.\n\\end{subpr}\n\n\\begin{problem}{B.}\n Let us investigate a plane EM wave, of frequency $\\omega$ travelling in a static uniform magnetic field $B_0 \\hat{z}$, where $\\hat{z}$ is the unit vector $z$ of the chosen Cartesian frame of reference. $B_0$ is much stronger than the field of the wave and the wave propagation is also along $\\hat{z}$. \n\\\\\n This medium contains $N_e$ bound electrons per unit volume, each obeying the classical equation of motion.\n \\begin{equation}\ne(\\vec{E}+\\frac{\\vec{v}}{c}\\times \\vec{B}) +m_e \\omega^2 r= -m_e \\ddot{\\vec{r}}, \\vec{v}=\\frac{d\\vec{r}}\n{dt}\\end{equation}\nWhere $m_e$ and $-e$ are the mass and charge of electron respectively.\n\\end{problem}\n\\begin{subpr}{B1. \\hfill 4.5 pts.} Prove that the wave propagation depends on polarisation, by calculating the refractive index for circular polarisation  (either left handed or right).\n\\end{subpr}\n\\begin{problem}{}\nNow consider the propagation of a linearly polarised in the same wave. Asuume the field at $z=0$ to be given by $\\vec{E}_i (z=0,t)=E_i e^{-i\\omega t} \\hat{x}$, and a relatively weak magnetic field such that $\\omega >> \\omega_c$ and higher order terms of $\\omega_c/\\omega$ can be neglected.\n\\end{problem}\n\\begin{subpr}{B2. \\hfill 3 pts.} Calculate the electric field at $z=l$, and find the angle by which the polarization has rotated.\n\\end{subpr}\n\\clearpage", "meta": {"hexsha": "04a96f60ea7cc7d52e55b59f5eea3c639a991eb2", "size": 10763, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/Round-3/Problems/2.tex", "max_stars_repo_name": "GRAMOLY-ORG/FIZIKA", "max_stars_repo_head_hexsha": "b6f920b15ea598de3777f386aa80edbb49657af8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-04T07:21:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T07:21:50.000Z", "max_issues_repo_path": "tex/Round-3/Problems/2.tex", "max_issues_repo_name": "GRAMOLY-ORG/FIZIKA", "max_issues_repo_head_hexsha": "b6f920b15ea598de3777f386aa80edbb49657af8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/Round-3/Problems/2.tex", "max_forks_repo_name": "GRAMOLY-ORG/FIZIKA", "max_forks_repo_head_hexsha": "b6f920b15ea598de3777f386aa80edbb49657af8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 75.7957746479, "max_line_length": 661, "alphanum_fraction": 0.6448945461, "num_tokens": 4324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.3466059957112453}}
{"text": "\\chapter{Bidirectional \\kl(tit){PCUIC}}\n\\label{chap:bidir-pcuic}\n\n\\margintoc\n\nAs we have seen in \\cref{sec:tech-pcuic}, there is much more to the real \\kl{Coq} than\n\\kl{CCω}.\nThe ideas exposed in the previous chapter nevertheless\nscale very well to these extensions.\nThere are two areas, though, where some care needs to be taken.\nThe first is cumulativity, which in particular forces us to reconsider the statement\nof the completeness and uniqueness properties, see \\cref{sec:bidir-pcuic-cumulativity}.\nBut the main one is the introduction of inductive types. In particular, there is a subtle\ninterplay with cumulativity in the treatment of pattern-matching.\nWorking on the formalized proof of completeness in \\kl{MetaCoq} led to the discovery of\nan incompleteness bug in the kernel of \\kl{Coq} linked to this.\nIn \\cref{sec:bidir-pcuic-inductives} we show how the bidirectional setting adapts to\ninductive types, and try and give an intuition of the origin of the completeness issue.\n\nWe do not give precise proofs in this chapter,\ninstead relying on the formalization in \\kl{MetaCoq} described in \\arefpart{metacoq}.\n\n  % The first area of difference are the universes. While on paper those are simply integer, to handle typical ambiguity and polymorphic (co)-inductive types, PCUIC uses algebraic universes, containing level variables, algebraic $\\vee$ and $+1$ operators, and a special level for the sort Prop. Moreover, those universes are cumulative, that is they behave as if smaller universes were included in larger ones. The precise handling of the algebraic universes is abstracted away in MetaCoq, and quite similar in the directed and undirected systems, so it did not prove too difficult to handle. Cumulativity, however, introduces some not-so-small differences with the previous presentation, so we spend some time on it in \\cref{sec:pcuic-cumul}.\n\n  % The second is the addition of new base type and term constructors. We describe the treatment of inductive types in \\cref{sec:pcuic-indu}. Co-inductive types and records behave very similarly to inductive types at the level of typing, so we do not dwell on them. The difference lies mainly at the level of reduction/conversion, but as our type system treats those as black boxes the differences have a negligible impact.\n  \n  \n\\section{Cumulativity}\n\\label{sec:bidir-pcuic-cumulativity}\n\n\\begin{marginfigure}\n  \\begin{mathpar}\n    \\inferdef{CheckCum}\n    {\\inferty{\\Gamma}{t}{T} \\\\ T \\cum T'}{\\checkty{\\Gamma}{t}{T'}}\n    \\label{rule:bd-check-cum}\n  \\end{mathpar}    \n\\end{marginfigure}\nThe introduction of the more liberal cumulativity rules in the undirected system\nof course calls for an update to the computation rules.\nThe change to \\ruleref{rule:bd-check} is direct: simply replace conversion with cumulativity,\nas done in \\ruleref{rule:bd-check-cum} opposite.\nAs for the constrained inference rules, they do not even need any modification.\nIntuitively, this is because there is no reason to degrade a type to a larger one,\nunless it is forced by a given target type in the checking judgment.\n\nThe statement of completeness also needs to account for cumulativity,\nand becomes the following one.\n\n\\begin{theorem}[Completeness, with cumulativity]\n  \\label{thm:comp-cumul}\n  If $\\Gamma \\vdash t \\ty T$, then $\\inferty{\\Gamma}{t}{T'}$ is derivable\n  for some $T'$ such that $T' \\cum T$.\n\\end{theorem}\n\nThis also means that in the setting of \\kl{PCUIC},\n\\kl{uniqueness of types} up to \\kl{conversion} is not true any more.\nFor instance, we both have $\\Gamma \\vdash \\uni[0] \\ty \\uni[1]$ and $\\Gamma \\vdash \\uni[0] \\ty \\uni[2]$, but $\\uni[1]$ and $\\uni[2]$ are not convertible. In that context, however,\nthe type $\\uni[1]$ still has a special property: it is minimal among all types, what\nwe call a \\kl{principal type}.\n\n\\begin{definition}[Principal type]\n  The type $T$ is a \\intro{principal type} for term $t$ – in a context $\\Gamma$ –\n  if $\\Gamma \\vdash t \\ty T$ and for any $T'$ such that $\\Gamma \\vdash t \\ty T'$,\n  we have $T \\cum T'$.\n\\end{definition}\n\nThe existence of such a principal type is the same as \\kl{uniqueness of types} \nup to cumulativity. Moreover, even in the cumulative setting, \\cref{thm:unique-inf}%\n\\sidenote{Uniqueness of inferred types up to joinability.}\nstays true. Intuitively, this is because it only relies on properties of reduction, but not of\nconversion. Thus, following the same proof as that of \\cref{thm:unique-undir},%\n\\sidenote{Uniqueness of types for undirected typing.}\nwe obtain that inferred types are principal.\n\n\\begin{theorem}[Inferred types are principal]\n  \\label{thm:princ-types}\n  If $\\Gamma$ is well-formed and $\\inferty{\\Gamma}{t}{T}$,\n  then $T$ is a \\kl{principal type} for $t$ in $\\Gamma$.\n\\end{theorem}\n  \n\\begin{proof}\n  If $\\Gamma \\vdash t \\ty T'$, then by completeness there exists some $T''$ such that\n  $\\inferty{\\Gamma}{t}{T''}$, and moreover $T'' \\cum T'$.\n  But by \\cref{thm:unique-inf}, $T \\conv T'' \\cum T'$ and thus $T \\cum T'$, and $T$ is thus indeed a principal type for $t$ in $\\Gamma$.\n\\end{proof}\n\nThe existence of \\kl{principal types} is not so easy to prove directly, as it more or less\namounts to showing correctness and completeness of the bidirectional system at once.\nNevertheless, it is useful, because it in particular means that any well-typed term $t$\nhas an unambiguous smallest universe, which can be obtained as the \\kl{principal\ntype} of its \\kl{principal type}. This means that there is a good separation between irrelevant \npropositions – those terms whose smallest universe is $\\Prop$ – and relevant terms\n– those whose smallest universe is some $\\uni[i]$ –, and that this stays true even in\npresence of cumulativity, and even if $\\Prop \\cum \\uni[i]$. If this were not the case,\nthe erasure of propositional content – which is one of the important use cases of $\\Prop$ –\nwould not make sense.\n\n\\section{Inductive Types}\n\\label{sec:bidir-pcuic-inductives}\n\n\\subsection{An example: the pair type}[The pair type]\n\n\\begin{figure}\n    \n  \\begin{mathpar}\n    \\inferdef{PairTy}{\n      \\pinferty{\\uni}{\\Gamma}{A}{\\uni[i]} \\\\ \n      \\pinferty{\\uni}{\\Gamma, x : A}{B}{\\uni[j]}}\n      {\\inferty{\\Gamma}{\\Sb x : A .\\ B}{\\uni[\\umax{i}{j}]}}\n      \\label{rule:pair-type-bd} \\and\n    \\inferdef{Pair}{\n      \\pinferty{\\uni}{\\Gamma}{A}{\\uni[i]} \\\\\n      \\pinferty{\\uni}{\\Gamma, x : A}{B}{\\uni[j]} \\\\\n      \\checkty{\\Gamma}{t}{A} \\\\\n      \\checkty{\\Gamma}{u}{\\subs{B}{x}{t}}}\n      {\\inferty{\\Gamma}{\\pair[A][x.B]{t}{u}}{\\Sb x : A .\\ B}}\n      \\label{rule:pair-bd} \\and\n    \\inferdef{PairInd}{\n      \\pinferty{\\Sb}{\\Gamma}{s}{\\Sb x : A .\\ B} \\\\\n      \\pinferty{\\uni}{\\Gamma, z : \\Sb x : A .\\ B}{P}{\\uni} \\\\\n      \\checkty{\\Gamma, y_1 : A, y_2 : \\subs{B}{x}{y_1}}{b}\n        {\\subs{P}{z}{\\pair[A][x.B]{y_1}{y_2}}}}\n      {\\inferty{\\Gamma}{\\ind{\\Sb}{s}{z.P}{y_1.y_2.b}}{\\subs{P}{z}{s}}}\n      \\label{rule:pair-ind-bd} \\and\n        \n    \\inferdef{PairInf}{\n      \\inferty{\\Gamma}{t}{T} \\\\ T \\red \\Sb x : A .\\ B}\n      {\\pinferty{\\Sb}{\\Gamma}{t}{\\Sb x : A .\\ B}}\n      \\label{rule:sig-inf} \n  \\end{mathpar}\n\n  \\caption{Bidirectional pair type}\n  \\label{fig:bidir-pair}\n\\end{figure}\n\nTo set ideas straight, let us look at how we can adapt the dependent pair type of\n\\cref{fig:sig} to the bidirectional setting: see \\cref{fig:bidir-pair}.\nTo obtain these rules, first notice that all undirected typing rules for the\npair type (\\cref{fig:sig})\nmust become inference rules if we want the resulting system to be complete.\nThe question therefore is once again to choose modes for the premises.\nRules \\nameref{rule:pair-type-bd} and \\nameref{rule:sig-inf} are\nvery similar to the rule for Π-types, there is not much surprise there.\n\n\\ruleref{rule:pair-bd} shows why we insisted in the undirected system\non recording the types $A$ and $B$ in the pair. Indeed, they are needed to\nknow which type to infer for the pair. Without the annotation, one could infer a\ntype $A$ for $t$ and a type $B'$ for $u$, but there are potentially many incomparable types $B$ that would be correct for the whole pair, depending on which instances of $t$ in $B'$ are abstracted to $x$. We only know that $B'$ is $\\subs{B}{x}{t}$,\nbut this is not enough to inambiguously determine $B$.\nThis impossibility to invert a substitution is a general source of need\nfor annotations, which is not specific to pair types!\n\nFinally, \\ruleref{rule:pair-ind-bd} is the most complex.\nIn presentations of \\kl{recursors}, often the predicate appears first, then the branches,\nand finally the scrutinee. But this is not possible here, as the parameters of the inductive\ntype are needed to construct the context in which the predicate is typed.\nInstead, those parameters can be inferred from the scrutinee.\nThus, a type for the scrutinee is first obtained using a new constrained inference judgment,\nforcing the inferred type to be a Σ-type, but leaving its parameters free.\nNext, these parameters can be used to construct the context to type the predicate.\nAnd finally, once the predicate is known to be well-formed,\nit can be used to type-check the branch.\n\nThis same approach can be readily extended to the other inductive types of\n\\cref{sec:tech-cic}, with recursion or indices posing no specific problems.\n%, see \\cref{fig:bidir-indu-other}.\n\n\\subsection{Polymorphic inductive types}\n\nThe account of general inductive types in \\kl{PCUIC} is slightly different from\nthe one we just gave. The reason for this is that giving a general account of rules\nwhich infer type levels like our \\ruleref{rule:pair-type-bd} is not easy.\nIndeed, the parameters of an inductive type can\nbe of a type much more complex than simply $\\uni$, and in that general setting deciding which\ntype variable can be inferred is a non-trivial problem.\nInstead, the polymorphic inductive types as implemented in \\kl{Coq} store explicit universe\nlevels on inductive types and constructors. The  pair type of \\cref{fig:bidir-pair},\nfor instance, would contain universe levels $i,j$, so that both $A$ and $B$\nwould be checked rather than having their level inferred.\nThe rule for the type constructor in that context is given opposite.\n\\begin{marginfigure}\n  \\begin{mathpar}\n  \\inferrule{\n    \\checkty{\\Gamma}{A}{\\uni[i]} \\\\ \n    \\checkty{\\Gamma, x : A}{B}{\\uni[j]}}\n    {\\inferty{\\Gamma}{\\Sb\\ulev{i,j} x : A .\\ B}{\\uni[\\umax{i}{j}]}}\n  \\end{mathpar}\n\\end{marginfigure}\nThis makes the treatment of complex inductive types possible by using checking uniformly –\nrather than relying on constrained inference to infer universe levels –\nat the cost of possibly needless annotations, as here with Σ-types.\nThis is mostly invisible for the end user though, as she does very seldom write universe\nlevels thanks to \\kl{typical ambiguity} anyway.\n\nIn the same spirit, pattern-matching in \\kl{Coq} – and its counterpart in \\kl{PCUIC} –\nalso stores enough information to easily reconstruct the context\nin which the predicate and branches are typed. This information consists in universe levels\n– for polymorphic inductive types – and parameters of the inductive type.\nThus, the actual typing rule for pattern-matching in the case of Σ-types\nis closer to the following one:\n\n\\begin{mathpar}\n  \\inferrule{\n    \\pinferty{\\Sb}{\\Gamma}{s}{\\Sb\\ulev{i,j} x : A .\\ B} \\\\\n    i \\le i' \\\\ j \\le j' \\\\ A \\cum A' \\\\ B \\cum B' \\\\\n    \\pinferty{\\uni}{\\Gamma, z : \\Sb x : A' .\\ B'}{P}{\\uni} \\\\\n    \\checkty{\\Gamma, y_1 : A', y_2 : \\subs{B'}{x}{y_1}}{b}\n      {\\subs{P}{z}{\\pair[A'][x.B']{y_1}{y_2}}}}\n    {\\inferty{\\Gamma}{\\match{\\Sb}{i',j'}{A',B'}{s}{z.P}{y_1.y_2.b}}{\\subs{P}{z}{s}}}\n\\end{mathpar}  \n\nNote that the domain and codomain are compared using \\kl{cumulativity}. This is crucial\nto retain \\kl{subject reduction}. Indeed, reduction of the scrutinee might make its inferred\ntype decrease. For instance, suppose we have a polymorphic inductive $I\\ulev{i}$ with a single\nconstructor $c$ such that $A : \\uni[i] \\vdash c\\ulev{i}(A)$. Now consider\n  \\[ \\left( \\l y : I\\ulev{1}.\\ y \\right)\\ c\\ulev{0}(\\Nat)\n    \\ored c\\ulev{0}(\\Nat) \\]\nthe redex infers type $I\\ulev{1}$, while the reduct infers\n$I\\ulev{0}$. Thus, if such a term is plugged as scrutinee in a pattern-matching,\nthe whole term is still typeable after the reduction of\nthe scrutinee because we allow inequalities rather than equalities between levels.\n\nBut here lies a subtle issue: in pen-and-paper accounts of recursors,\nthe predicate and branches are often\nrepresented respectively as Π-types and λ-abstractions. This is also how previous versions of\n\\kl{Coq} represented pattern-matching.%\n\\sidenote{Until version 8.14 to be precise.}\nBut recall that in \\kl{PCUIC}, cumulativity is\nequivariant on the domain of Π-types. This led to an implementation that wrongly compared\nthe universe levels using equality rather than inequality, leading to a completeness\nbug that manifested as a failure of subject reduction in situations such as the one above.%\n\\sidenote{A precise description of the problem in the kernel and an example similar to the\n  one above are given in issue \\coqIssue{13495}.}\nThis prompted subsequent work, both on the theory of \\kl{PCUIC} and on the implementation, to\nremove the use of Π- and λ-abstractions completely from pattern-matching%\n\\sidenote{This was carried out by Pierre-Marie Pédrot starting with pull-request \\coqPR{13563},\nfollowing ideas that had been laid down earlier by Hugo Herbelin in the\n\\href{https://github.com/coq/ceps/blob/master/text/inductive-branch-predicate-representation-and-reduction.md}{\\kl{Coq} enhancement\nproposal \\#34}.},\nmaking both the implementation less ad-hoc, and the theory cleaner.\nA detailed summary has been given in \\sidetextcite{Sozeau2022}.\n\nFurther investigations in that area might still be valuable though, in particular in order\nto determine what kind of annotations are actually needed for pattern-matching, both\nin theory and in practice. Can we give a presentation of polymorphic inductive types\nthat is as lightweight as pair types in \\cref{fig:bidir-pair}?\nThe bidirectional presentation is valuable there, because now\nit is clear what the specification of an alternative syntax is:\nit should remain complete, in the sense of \\cref{thm:comp-cumul}.", "meta": {"hexsha": "19050b1e53d7017454535350bf4fd8d959617587", "size": 14128, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Manuscript/bidir-pcuic.tex", "max_stars_repo_name": "MevenBertrand/PhD-Thesis", "max_stars_repo_head_hexsha": "5bb9852b747bf0700d7c60b74dc64e11372478f8", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Manuscript/bidir-pcuic.tex", "max_issues_repo_name": "MevenBertrand/PhD-Thesis", "max_issues_repo_head_hexsha": "5bb9852b747bf0700d7c60b74dc64e11372478f8", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-22T14:04:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T18:26:29.000Z", "max_forks_repo_path": "Manuscript/bidir-pcuic.tex", "max_forks_repo_name": "MevenBertrand/PhD-Thesis", "max_forks_repo_head_hexsha": "5bb9852b747bf0700d7c60b74dc64e11372478f8", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.7389558233, "max_line_length": 743, "alphanum_fraction": 0.7352066818, "num_tokens": 3963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.3466059957112453}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\marginpar{Thursday\\\\ 2020-8-27, \\\\ compiled \\\\ \\today}\n\nWe then expand the electron and photon energy distributions \\emph{after} the scattering up to second order in \\(\\Delta \\): using the fact that \\(\\epsilon' - \\epsilon = \\Delta \\Theta \\) (\\(\\Delta \\) \\emph{times} \\(\\Theta \\), not the variation of \\(\\Theta \\)) we find\n%\n\\begin{align}\nf(E') &= f(E - \\Delta \\Theta ) \\approx \\qty(1 + \\Delta + \\frac{\\Delta^2}{2}) f(E)  \\\\\nn(\\epsilon ') &= n( \\epsilon + \\Delta \\Theta ) \\approx n(\\epsilon ) + \\pdv{n}{\\epsilon } \\Delta \\Theta \n+ \\pdv[2]{n}{\\epsilon } \\frac{(\\Delta \\Theta )^2}{2 }\n\\,,\n\\end{align}\n%\nwhere we have used the explicit expression we have for the thermal distribution \\(f(E) \\sim e^{- E/ \\Theta }\\), which gives us a factor \\(-1/\\Theta\\) each we differentiate with respect to \\(E\\). \n\nIf we define the usual rescaled energy \\(x = h \\nu / k_B T = \\epsilon / \\Theta \\) we can express the latter expansion as \n%\n\\begin{align}\nn(x') \\approx n(x) + \\Delta \\pdv{n}{x} + \\frac{\\Delta^2}{2} \\pdv[2]{n}{x}\n\\,.\n\\end{align}\n\nWe will assume that the medium is \\textbf{homogeneous}, \\textbf{isotropic} and \\textbf{infinite}, and that the photon distribution is \\textbf{isotropic}. The latter point means that \\(n\\) is not a function of \\(\\Omega \\). \nThis will be close to true as long as the optical depth is large, since then we will see many interactions which will spread the photons. \n\nWe can then take out of the Boltzmann integral all the terms depending only on \\(n\\), since they have no more angular dependence. This yields the following expression (up to second order in \\(\\Delta \\)): \n%\n\\begin{align}\n\\pdv{n}{t} = \\qty[n' + n(n+1)]\n\\underbrace{\\int \\dd[3]{p} \\dd{\\Omega } \\dv{\\sigma }{\\Omega } f(E) \\Delta }_{I_1 }\n+ \n\\qty[\\frac{n''}{2}\n+ \\qty(n' + \\frac{n}{2})\n\\qty(n+1)]\n\\underbrace{\\int \\dd[3]{p} \\dd{\\Omega } \\dv{\\sigma }{\\Omega }\nf(E) \\Delta^2 }_{I_2 }\n\\,.\n\\end{align}\n\nHere we are denoting \\(n' = \\pdv*{n}{x}\\) for simplicity.  \nLet us then try to evaluate the integrals \\(I_1 \\) and \\(I_2 \\), starting from the latter. It depends on \\(\\Delta^2\\), which is given by \n%\n\\begin{align}\n\\Delta^2 = x^2 \\beta^2 (\\vec{\\Omega}' - \\vec{\\Omega})^2 \\cos^2 \\theta_v\n\\,,\n\\end{align}\n%\nso it evaluates to \n%\n\\begin{align}\nI_2 = \n\\int \\dd[3]{p} \\dd{\\Omega } \\dv{\\sigma }{\\Omega } f(E) \\Delta^2\n= x^2 \\int f(E) p^2 \\beta^2 \\cos^2 \\theta _v \\dd{p} \\sin \\theta _v \\dd{\\theta _v} \\dd{\\phi _v} \\int \\dd{\\Omega } \\dv{\\sigma }{\\Omega } (\\vec{\\Omega}' - \\vec{\\Omega})^2\n\\,,\n\\end{align}\n%\nwhere \\(\\theta _v\\) and \\(\\phi _v\\) are the two angles defining the unit vector \\(\\hat{p}\\), so that \\(\\dd[3]{p} = p^2 \\sin \\theta _v \\dd{p } \\dd{\\theta _v} \\dd{\\phi _v}\\). We choose them by placing the vector \\(\\vec{\\Omega}' - \\vec{\\Omega}\\) on the \\(z\\) axis, so that the angle \\(\\theta _v\\) is also the one appearing in \\((\\vec{\\Omega}' - \\vec{\\Omega}) \\cdot \\vec{p} = p \\abs{\\vec{\\Omega}' - \\vec{\\Omega}} \\cos \\theta _v\\). \n\nThe angular integrals in \\(\\dd{\\phi _v}\\) and \\(\\dd{\\theta _v}\\) are standard, while for the integral in the modulus of \\(p\\) we need to use the actual expression of the Maxwellian: substituting \\(\\beta = p / mc\\) and then \\(z= \\beta / \\sqrt{\\Theta }\\) we get \n%\n\\begin{align}\nI_2 \n&= 2 \\pi x^2m^3 c^3 \\frac{2}{3} (2 \\pi m k_B T)^{-3/2} n_e \n\\int_0^{\\infty } \\dd{\\beta } \\beta^{4} \\exp(- \\frac{\\beta^2}{2 \\Theta })\n\\int \\dd{\\Omega } \\dv{\\sigma }{\\Omega } \\qty(\\vec{\\Omega}' - \\vec{\\Omega})^2 \\\\\n&= 2 \\pi x^2m^3 c^3 \\frac{2}{3} \\Theta^{5/2} (2 \\pi m k_B T)^{-3/2} n_e \n\\underbrace{\\int_0^{\\infty } \\dd{z } z^{4} \\exp(- \\frac{z^2}{2})}_{= 3 \\sqrt{2 \\pi } / 2}\n\\int \\dd{\\Omega } \\dv{\\sigma }{\\Omega } \\qty(\\vec{\\Omega}' - \\vec{\\Omega})^2   \\\\\n&= x^2 \\Theta n_e \n\\int \\dd{\\Omega } \\dv{\\sigma }{\\Omega } \\qty(\\vec{\\Omega}' - \\vec{\\Omega})^2\n\\,,\n\\end{align}\n%\nso we are left with only the integral in the photon space: in order to evaluate it we need to substitute the expression of the modulus of the difference of the unit vectors and the differential cross section: \n%\n\\begin{align}\n\\qty(\\vec{\\Omega}' - \\vec{\\Omega})^2 = 2 (1 - \\cos \\theta )\n\\qquad \\text{and} \\qquad\n\\dv{\\sigma }{\\Omega } = \\frac{r_0^2}{2} \\qty(1 + \\cos^2 \\theta )\n\\,,\n\\end{align}\n%\nso, also substituting the explicit expression for the radius \\(r_0 \\) we get \n%\n\\begin{align}\nI_2 &= n_e x^2 \\Theta \\int \\sin \\theta \\dd{\\theta } \\underbrace{\\dd{\\phi }}_{= 2 \\pi } \\frac{3 \\sigma _T}{16 \\pi } 2 (1 + \\cos^2 \\theta ) (1 - \\cos \\theta )  \\\\\n&= 2 n_e x^2 \\Theta \\sigma _T \\frac{3}{16 \\pi } 2 \\pi \\underbrace{\\int_{-1}^{1} (1+\\mu^2) (1 - \\mu ) \\dd{\\mu }}_{= 8/3} \\\\\n&= 2 \\sigma _T x^2 n_e \\Theta \n\\,.\n\\end{align}\n\nThe integral \\(I_1 \\) looks similar, and one might try to evaluate it similarly. This turns out to be tricky, and there is a better indirect way to do it. \n\nThe photon number density in phase space is given by \n%\n\\begin{align}\n\\frac{ \\dd{N}}{ \\dd{V} \\dd[3]{p}} = \\frac{2}{h^3} n\n\\,,\n\\end{align}\n%\nso, since the momentum of a photon is proportional to its energy and also to \\(x = h \\nu / k_B T\\) we can write \n%\n\\begin{align}\n\\dv{N}{V} \\propto \\int_0^{\\infty } \\dd{x} n x^2\n\\,.\n\\end{align}\n\n\\todo[inline]{If I'm interpreting this correctly, the slides use \\(x\\) with two different meanings in the same equation: one is position, and the other is the normalized energy. Really confusing if it is the case.}\n\nSince the medium is assumed to be homogeneous and isotropic, the photon number \\emph{density} is conserved: this means that \n%\n\\begin{align}\n\\dv{}{t} \\qty(\\dv{N}{V}) = 0 \n\\implies\n\\dv{}{t} \\int_0^{\\infty } \\dd{x} n x^2 = \\int_0^{\\infty } \\dd{x} \\pdv{n}{t} x^2 = 0\n\\,.\n\\end{align}\n\nNow, for reasons which will become clear in a moment, we make an assumption: suppose that there is a function \\(j(x, t )\\) such that the derivative of the photon density can be written as \n%\n\\begin{align}\n\\pdv{n}{t} = - \\frac{1}{x^2} \\pdv{[x^2 j(x, t)]}{x}\n\\,.\n\\end{align}\n\nIf this is the case, then the integral which we have just seen shown to equal zero can be written as \n%\n\\begin{align}\n\\int_0^{\\infty } \\dd{x} \\pdv{n}{t} x^2  = -\\int_0^{\\infty } \\pdv{[x^2 j(x, t)]}{x}  = \\eval{- x^2 j(x, t) }_{0}^{\\infty } = 0\n\\,.\n\\end{align}\n\nThis gives us the boundary conditions for \\(j\\), which will have to be well-behaved at zero (non diverging) and at infinity (going to zero at least as \\(1/x^2\\)). \nNow, the Boltzmann equation's dependence on \\(n\\) and its derivatives is in the form \n%\n\\begin{align}\n\\pdv{n}{t} = C_1 (x ) n'' + C_2 (n, x) n' + C_3 (n, x)\n\\,,\n\\end{align}\n%\nand if we compare this expression with the one which defines \\(j\\)\\footnote{Seeing that \n%\n\\begin{align}\n\\pdv{n}{t} = - \\frac{1}{x^2} \n\\pdv{[x^2 j(x, t)]}{x}\n= - \\frac{2j}{x} - \\pdv{j}{x}\n\\,.\n\\end{align}\n%\n} we can prove that its dependence on \\(n\\) and \\(x\\) looks like \n%\n\\begin{align}\nj = g(x) \\qty[n' + h (n, x)]\n\\,,\n\\end{align}\n%\nfor some functions \\(g\\) and \\(h\\). In general \\(h\\) is a function of both \\(n\\) and \\(x\\), but we will assume it only depends on \\(n\\). \n\n\\todo[inline]{Why though? Is there a physical reason for it?}\n\nNow, we substitute this general expression for \\(j\\) back into the Boltzmann equation: this yields \n%\n\\begin{align}\n\\begin{split}\n&\\frac{1}{2} I_2 n'' + \\qty[(1+ n) I_2 + I_1 ]n' + \\qty(I_1 + \\frac{I_2}{2}) n (1+n) =\n\\\\\n&\\phantom{=}\\ = - g(x) n'' - \\qty( \\frac{2 g(x)}{x} + g(x) \\pdv{h}{n} + \\pdv{g}{x}) n' - \\qty(h \\frac{2 g(x)}{x} + g(x) \\pdv{h}{x} + h \\pdv{g}{x})\n\\end{split}\n\\,,\n\\end{align}\n%\nfrom which, identifying the terms, we can recover the expressions for \\(g\\), \\(I_1 \\) and \\(h\\): \n%\n\\begin{align}\ng &= - \\frac{I_2}{2} = - x^2 n_e \\sigma_T \\Theta   \\\\\nI_1 &= - 2 \\frac{g}{x}  - \\pdv{g}{x} - \\frac{I_2}{2} = (4-x) x n_e \\sigma_T \\Theta  \\\\\nh &= n (1 + n)\n\\,.\n\\end{align}\n\nThis means that the form of \\(j\\) is \n%\n\\begin{align}\nj= g(x) \\qty[n' + h (n, x)] = - x^2 n_e \\sigma_T \\Theta (n' + n + n^2 )\n\\,,\n\\end{align}\n%\nwhich we can finally substitute into the Kompaneets equation: \n%\n\\begin{align}\n\\pdv{n}{t} = - c \\frac{1}{x^2} \\pdv{[x^2 j]}{x}\n&= n_e \\sigma_T c \\frac{\\Theta }{x^2} \\pdv{[x^{4} (n' +n + n^2)]}{x}  \\\\\n\\pdv{n}{t_s} &= \\frac{\\Theta}{x^2} \\pdv{[x^{4} (n' + n + n^2)]}{x}\n\\,,\n\\end{align}\n%\nwhere we calculate time in units of the mean time between subsequent scatterings, \\(T = \\frac{1}{n_e \\sigma _T c} \\), so that \\(t_s = t / T\\).\n\\todo[inline]{There is now a \\(c\\) which was not there before\\dots}\n\nThis is the \\textbf{Kompaneets equation}. \nIn general this nonlinear equation must be solved numerically, it is an equation of the Fokker-Planck type, whose solution exhibit two main effects: \n\\begin{enumerate}\n    \\item drift of the photon distribution to higher energies, this is called the \\textbf{secular change}, and is due to the fact that \\(I_1 \\sim 4 k_B T - h \\nu \\) (as long as the photons start out with energies lower than \\(4 k_B T\\));\n    \\item broadening of the photon distribution, due to random walk effects: this is related to the integral \\(I_2 \\). \n\\end{enumerate}\n\n\\subsection{Stationary solutions}\n\nWe expect that, after the photons have interacted with the medium for a long time, their variation in time will become ever smaller, approaching a stationary solution which will satisfy \n%\n\\begin{align}\n0= \\pdv{[x^{4} (n' + n + n^2)]}{x}\n\\,,\n\\end{align}\n%\nmeaning that \n%\n\\begin{align}\nn' + n + n^2 = \\frac{A}{x^{4}}\n\\,.\n\\end{align}\n\nThe constant \\(A\\) must equal zero, since otherwise the solution will not be regular at zero: recall that \\(x^2 j = x^{4 }( n' + n +n^2)\\) must vanish at zero and infinity. \nThen, we can separate variables in order to integrate \\(n' + n + n^2 = 0\\): this yields \n%\n\\begin{align}\n\\log \\frac{n}{1 + n} = - x - \\mu    \n\\,\n\\end{align}\n%\nfor a constant \\(\\mu \\),\nmeaning that    \n%\n\\begin{align}\nn = \\frac{1}{ \\exp( x + \\mu ) - 1}\n\\,,\n\\end{align}\n%\nwhich is nice!\nWe found a Bose-Einstein distribution with an arbitrary chemical potential \\(\\mu \\): photons are at equilibrium with another chemical species. \n\nThe reason the photons do not achieve a Planck distribution (which is a Bose-Einstein distribution with \\(\\mu = 0\\)) is that their number must be conserved under our assumptions. \n\n\\todo[inline]{To understand better: the chemical potential quantifies how much the (energy?) changes if we change the number of particles, right?}\n\nThe Kompaneets equation is a \\textbf{parabolic} PDE, like the Fourier heat transport equation. \nThis means that we need to provide boundary conditions not only in the time domain, but also in the frequency domain for \\(x \\to 0\\) and \\(x \\to \\infty \\). We must set the distribution to zero in both regions, in order to avoid photons escaping through the boundary. \n\nIf the number of photons we initially insert in the model is smaller than the number of photons which would be contained in a blackbody at that temperature, then the evolution works out smoothly towards the blackbody distribution.\n\nOn the other hand, if we insert \\emph{more} photons than those which would be contained in the Planckian the numerical solution goes nuts. \n\n\\end{document}\n", "meta": {"hexsha": "633fa81e6327a3959660a59ef4b851846f6b4303", "size": 11003, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ap_second_semester/radiative_processes/apr16.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "ap_second_semester/radiative_processes/apr16.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ap_second_semester/radiative_processes/apr16.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 43.1490196078, "max_line_length": 427, "alphanum_fraction": 0.642188494, "num_tokens": 3839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.34660599571124523}}
{"text": "\\documentclass[Physics.tex]{subfiles}\r\n\\begin{document}\r\n\\chapter{Superposition}\r\nSuperposition is a property of linear systems where the net response at a given point and time caused by two or more stimuli is the sum of the responses which would have been caused by each stimulus individually.\r\n\r\nWhen contextualised to waves, the \\sldef{superposition principle} is as such: When two waves of the same kind meet at a point in space, the resultant displacement at that point is the vector sum of the displacements that the two waves would separately produce at that point.\r\n\\section{Interference}\r\n\\sldef{Interference} is the superposing of 2 or more waves of the same type, interacting according to the principle of superposition. \\sldef{Observable interference} is the superposing of 2 or more coherent waves to produce regions of maxima and minima in space, according to the principle of superposition.\r\n\r\n\\sldef{Coherent sources} are sources with the same frequency and a constant phase difference.\r\n\r\nFor interference to be observable, the sources must be coherent; the waves must have approximately equal amplitudes, and they must be polarised in the same plane, or unpolarised.\r\n\r\n\\sldef{Constructive interference} occurs when two or more waves arrive at the screen in phase with each other, such that the amplitude of the resultant wave is the sum of the amplitudes of the resultant waves.\r\n\r\n\\sldef{Destructive interference} occurs when two or more waves arrive at the screen \\(\\pi\\) out of phase with each other, such that the amplitude of the resultant wave is the minimum possible value.\r\n\r\nInterfering waves produce interference patterns with alternating maxima and minima. The zero order maximum is the brightest maximum; if there are multiple maxima with the highest amplitude, the zero order can be chosen as any. Successive maxima away from the 0 order are numbered the 1st, 2nd, 3rd and so on. Minima have the same order as the adjacent maximum away from the 0 order. This means that there is no 0 order minimum.\r\n\\subsection{One-source interference i.e. diffraction}\r\n\\sldef{Diffraction} is the bending or spreading of waves when they travel through a small opening. It is a special case of interference, and it occurs due to the Huygens-Fresnel principle, where each point along a slit is considered a source of spherical waves.\r\n\r\nIn diffraction, waves from the Huygens sources interfere with each other and produce a pattern with alternating maxima and minima, with minima at angles \\(\\theta\\) satisfying the equation \\begin{equation}a\\sin\\theta = m\\lambda\\end{equation} where \\(a\\) is the slit width and \\(m\\in\\mathbb{Z}^+\\) is the order of the minimum.\r\n\r\nGenerally, diffraction can only be observed when the size of the opening is approximately the same order as the wavelength or smaller.\r\n%\r\n%The intensity \\(I\\) of a diffraction pattern at distance \\(d \\propto\\sin\\theta\\) is \\[I = I_0\\left(\\frac{\\sin( \\pi a\\lambda^{-1}\\sin\\theta)}{\\pi a\\lambda^{-1}\\sin\\theta}\\right)^2\\] where \\(a\\) is the slit width.\r\n\\subsection{Two-source interference}\r\nTwo point sources of spherical waves can produce an interference pattern on a screen, with alternating maxima and minima. The zero order maximum occurs at the point on the screen that is equidistant from both sources (assuming the sources are in phase).\r\n\r\nThe separation between successive maxima is estimated by \\begin{equation}\\Delta x = \\frac{\\lambda D}{a}\\end{equation} for \\(D \\gg a\\), where \\(D\\) is the distance from the point sources to the screen, and \\(a\\) is the separation of the two point sources. If \\(D \\approx a\\) or \\(D < a\\), then Pythagoras' theorem must be used.\r\n\r\nThis phenomenon is investigated in Young's double slit experiment, where the two point sources are replaced by a monochromatic source of light passing through a single slit that acts as a point source, followed by a double slit that acts as two coherent point sources and causes light to diffract so that they can overlap and interfere.\r\n\r\nFor such a setup to produce a visible pattern, the double slits must be small enough for diffraction to occur; the single slit must be small enough so the light reaching the double slits is coherent; and the slit-screen separation must be at least one order larger than the slit separation so that the diffracted waves can overlap and interfere.\r\n\r\nThe path difference \\(\\Delta x\\) between the two waves reaching a maximum and minimum in two-source interference can be expressed in terms of the order of the maximum \\(n\\) or minimum \\(n\\). If the two sources are in phase, then for maxima \\begin{align}\\Delta x &= n\\lambda\\\\\\intertext{and for minima}\\Delta x &= (n - \\frac{1}{2})\\lambda\\end{align} and vice versa for sources in antiphase.\r\n%\r\n%The intensity \\(I\\) of a two-source interference pattern at distance \\(d \\propto \\sin\\theta\\) is \\[I = I_{0}\\left(\\frac{\\pi a\\sin\\theta}{\\lambda}\\right)\\] \\(I_0\\) can be expressed in terms of an unknown constant where required.\r\n\r\nTwo-source interference can be demonstrated with a ripple tank. Two dippers connected to a bar connected to a vibrator are set into vertical vibrations with the same amplitude and frequency and in phase. Each dipper produces circular waves that have the same frequency, which spread out and overlap, interfering constructively and destructively, and an interference pattern where there are points with water waves of maximum amplitude and points with minimum amplitude is formed.\r\n\r\nTwo-source interference can also be demonstrated with a microwave. Microwaves from a transmitter pass through two slits on an aluminium plate that act as coherent sources of microwaves. Microwaves emerging from the slits diffract and overlap, resulting in constructive and destructive interference. A microwave detector is moved along a line and the current registered will vary alternately from a maximum to a minimum, showing constructive and destructive interference. Since the wavelength of microwaves is about \\SI{3}{\\centi\\metre}, the slit size should be about \\SI{3}{\\centi\\metre}, and the slit separation should be about \\SI{30}{\\centi\\metre}, about \\(10\\lambda\\). The interference can be observed about \\SI{1}{\\metre} away.\r\n\\subsection{Many-source interference}\r\nA \\sldef{diffraction grating} is a plate with a large number of parallel, identically spaced slits of the same width. These multiple slits act as multiple coherent sources.\r\n\r\nMultiple sources of waves can produce an interference pattern similar to the previous two, with alternating maxima and minima. The zero order beam is the one parallel to the original beam of light.\r\n\r\nThe angle \\(\\theta\\) from the normal to the grating at which each maximum (or each beam) occurs satisfies the equation \\begin{equation}d\\sin\\theta = m\\lambda\\end{equation} where \\(d\\) is the slit separation, and \\(m\\) is the order of the maximum.\r\n\r\nThe maximum observable order for a planar screen parallel to the grating occurs at \\[0 < \\theta < \\SI{90}{\\degree} \\iff \\sin\\theta < 1\\] From the equation above, it can be derived that \\begin{equation}m < \\frac{d}{\\lambda}\\end{equation}\r\n\\section{Standing waves}\r\nWhen two waves of the same type, amplitude and frequency travel in opposite directions to each other and overlap, a standing wave will be formed due to superposition.\r\n\r\nStanding waves have points where constructive and destructive interference always occurs; they are known as \\sldef{antinodes} and \\sldef{nodes} respectively. Nodes are halfway between antinodes, and vice versa. Nodes have the minimum amplitude and intensity, while antinodes have the maximum amplitude and intensity.\r\n\r\nIn stationary waves, each point between consecutive nodes are in phase with each other i.e. they will reach the amplitude and equilibrium at the same time. Points to the between a node and the next node to the left are in antiphase with points between that node and the node to the right.\r\n\r\nThe distance between consecutive nodes or consecutive antinodes is half the wavelength of the original waves.\r\n\r\nStanding waves can be produced when a reflector reflects waves back in the direction they came from. In reality, however, reflected waves will not have the same amplitude, so perfect standing waves are not formed.\r\n%\r\n%The displacement-distance and time graph of a standing wave is given by \\(y = 2y_0\\sin kx\\sin\\omega t\\), where \\(k\\) is the wavenumber and \\(y_0\\) is the amplitude of the original waves. From this equation it can be seen that the amplitude at any point is \\(y\\prime_0 = 2y_0\\sin kx\\), where \\(x\\) is the distance from any node.\r\n\\subsection{Harmonics}\r\nA \\sldef{harmonic} of a wave is a frequency that is an integer multiple of the fundamental frequency.\r\n\r\nStanding waves can be produced with nodes at both ends of the wave. This occurs e.g. in a string fixed at both ends that is then plucked. The longest possible wavelength occurs when the two end nodes are consecutive nodes i.e. the distance \\(L\\) between the two nodes is half the wavelength. This mode is known as the 1st harmonic or the fundamental. The frequency, which is the fundamental frequency, is then \\[f_1 = \\frac{v}{2L}\\] The next possible standing wave occurs when there is one node between the two end nodes i.e. the distance \\(L\\) is the wavelength. This mode is the 2nd harmonic or the 1st overtone and has frequency \\[f_2 = \\frac{v}{L} = 2f_1\\] Therefore, the frequency and wavelength of the \\(n\\)th harmonic or \\((n-1)\\)th overtone are \\begin{align*}f_n &= nf_1\\\\\\lambda_n &= \\frac{2L}{n}\\end{align*}\r\n\r\nStanding waves can be produced with a node at one end and an antinode at the other. This occurs in a sound wave that enters an air column with one end closed, for example. The longest possible wavelength occurs also when the end node and antinode are adjacent i.e. \\[L = \\frac{1}{4}\\lambda\\] Thus the 1st harmonic or fundamental \\[f_1 = \\frac{v}{4L}\\] The next possible standing wave occurs when there is one node between the node and antinode i.e. \\[L = \\frac{3}{4}\\lambda\\] This is the \\emph{3rd} harmonic (since \\(f\\) is thrice that of \\(f_1\\)) or 1st overtone; \\[f_3 = 3\\frac{v}{4L} = 3f_1\\] Therefore, the frequency and wavelength of the \\(n\\)th harmonic or \\(\\frac{1}{2}(n-1)\\)th overtone are \\begin{align*}f_n &= nf_1\\\\\\lambda_n &= \\frac{4L}{n}\\end{align*}\r\n\r\nStanding waves can be produced with antinodes at both ends. This occurs in a sound wave that enters an air column open at both ends. The modes of operation for this are identical to standing waves with nodes as ends.\r\n\r\nIn general, closed ends are usually nodes as particles cannot vibrate there; conversely, open ends are antinodes as particles must vibrate there.\r\n\r\nFor sound waves, pressure nodes are displacement antinodes, and vice versa. At a pressure node, a microphone or ear will not detect sound as they sense pressure variations, not displacement.\r\n\r\nThe air at the end(s) of a pipe are generally free to move and so naturally vibrations will extend into the air outside the pipe i.e. the antinode is slightly beyond the open end. The extra length it extends is called the \\sldef{end correction}, and it is added to the length of the pipe i.e. \\[f_1 = \\frac{v}{4(L+e)}\\] for a pipe with one open end, and \\[f_1 = \\frac{v}{2(L+2e)}\\] for a pipe open at both ends.\r\n\\end{document}", "meta": {"hexsha": "d7598fdb7edf6f170033c45517a8ecab562689c3", "size": 11270, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "TeX/Physics/ch10_superposition.tex", "max_stars_repo_name": "oliverli/A-Level-Notes", "max_stars_repo_head_hexsha": "5afdc9a71c37736aacf3ae1db9d0384cdb6a0348", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-05T11:44:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-05T11:44:33.000Z", "max_issues_repo_path": "TeX/Physics/ch10_superposition.tex", "max_issues_repo_name": "oliverli/A-Level-Notes", "max_issues_repo_head_hexsha": "5afdc9a71c37736aacf3ae1db9d0384cdb6a0348", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TeX/Physics/ch10_superposition.tex", "max_forks_repo_name": "oliverli/A-Level-Notes", "max_forks_repo_head_hexsha": "5afdc9a71c37736aacf3ae1db9d0384cdb6a0348", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 146.3636363636, "max_line_length": 818, "alphanum_fraction": 0.7714285714, "num_tokens": 2696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.34660599571124523}}
{"text": "\\documentclass[simplex.tex]{subfiles}\n% NO NEED TO INPUT PREAMBLES HERE\n% packages are inherited; you can compile this on its own\n\n\\onlyinsubfile{\n\\title{NeuroData SIMPLEX Report: Reduced Dimension Clustering}\n}\n\n\\begin{document}\n\\onlyinsubfile{\n\\maketitle\n\\thispagestyle{empty}\n\nThe following report documents the progress made by the labs of Randal~Burns and Joshua~T.~Vogelstein at Johns Hopkins University towards goals set by the DARPA SIMPLEX grant.\n\n%%%% Table of Contents\n\\tableofcontents\n\n%%%% Publications\n\\bibliographystyle{IEEEtran}\n\\begin{spacing}{0.5}\n\\section*{Publications, Presentations, and Talks}\n%\\vspace{-20pt}\n\\nocite{*}\n{\\footnotesize\t\\bibliography{simplex}}\n\\end{spacing}\n%%%% End Publications\n}\n\n\\subsection{Reduced Dimension Clustering}\n\nWe develop a new statistical method, named ``automatic repulsive\nclustering'' (ARC, to handle the clustering problem when the\ndimensionality outgrows the number of the data points. The standard\ndimension reduction tool such as principle component analysis (PCA) is\nnot optimal for finding the subspace best suitable for clustering.\nTherefore, we seek the method to do dimension reduction and clustering\nat the same time: we develop a regularization to encourage good\nseparation of the clusters, forcing the subspace to an angle so that\neach point can belong to a cluster completely. The plots below shows the\ndifferent performances in clustering a equally proportioned 3\ncomponents: the subspace found by PCA leads to incorrect clustering of\nthe data, due to the orientation of the space; whereas ARC successfully\nidentifies the ideal clustering direction in one dimensional space,\nhence generating satisfactory clustering result.\n\n\n\\begin{figure}[h!]\n\\begin{cframed}\n\\centering\n\\includegraphics[width=0.45\\textwidth]{./figs/pcaBased.png}\n\\includegraphics[width=0.45\\textwidth]{./figs/ARC.png}\n\\caption{PCA (left) versus Reduced Dimension Clustering (right).}\n\\label{fig:arc}\n\\end{cframed}\n\\end{figure}\n\n\n\\end{document}\n", "meta": {"hexsha": "34865f25b34dd757a0b46afbfc5490f5559d05fc", "size": 1984, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Reporting/reports/2016-12Q4/reducedDimensionClustering.tex", "max_stars_repo_name": "openconnectome/SIMPLEX_Q2", "max_stars_repo_head_hexsha": "f10a6c4b9548670f9bf8e177914aa8d25fa1230b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Reporting/reports/2016-12Q4/reducedDimensionClustering.tex", "max_issues_repo_name": "openconnectome/SIMPLEX_Q2", "max_issues_repo_head_hexsha": "f10a6c4b9548670f9bf8e177914aa8d25fa1230b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Reporting/reports/2016-12Q4/reducedDimensionClustering.tex", "max_forks_repo_name": "openconnectome/SIMPLEX_Q2", "max_forks_repo_head_hexsha": "f10a6c4b9548670f9bf8e177914aa8d25fa1230b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0666666667, "max_line_length": 175, "alphanum_fraction": 0.7963709677, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.3466059874514057}}
{"text": "\\section{Coin and Multi-Asset Token algebras}\n\\label{sec:coin-ma}\n\nIn this chapter we introduce the concept of a \\emph{Token algebra},\nwhich is an abstraction used to generalize this specification to two\ndifferent eras depending on the Token algebra chosen.\n\n\\begin{definition}[Token algebra]\n  A \\emph{Token algebra} is a partially ordered commutative monoid\n  $T$, written additively, (i.e. a commutative monoid together with a\n  partial order, such that addition is monotonic in both variables)\n  together with the functions and properties as described in Figure\n  \\ref{fig:TokenAlgebra}.\n\\end{definition}\n\n%%\n%% Figure ValMonoid and its Functions\n%%\n\\begin{figure}[htb]\n  %\n  \\emph{Functions}\n  %\n  \\begin{align*}\n      & \\fun{coin} ~\\in~ T \\to \\Coin\\\\\n      & \\text{Return the Ada contained inside the $\\mathsf{ValType}$ element}\n      \\nextdef\n      %\n      & \\fun{inject} ~\\in~ \\Coin \\to T\\\\\n      & \\text{Create a $\\mathsf{ValType}$ element containing only this amount of Ada}\n      \\nextdef\n      %\n      & \\fun{policies} ~\\in~ T \\to \\powerset{\\PolicyID} \\\\\n      & \\text{The set of policy IDs required for minting}\n      \\nextdef\n      %\n      & \\fun{size} ~\\in~ T \\to \\MemoryEstimate\\\\\n      & \\text{Return the size, in words, of a $\\mathsf{ValType}$ element}\n  \\end{align*}\n  %\n  \\emph{Properties}\n  %\n  \\begin{align*}\n      & \\fun{coin} \\circ \\fun{inject} = \\fun{id}_{\\Coin}\n  \\end{align*}\n  \\caption{Additional functions and properties required for a Token algebra}\n  \\label{fig:TokenAlgebra}\n\\end{figure}\n\nA Token algebra is precisely the structure required to generalize the\n$\\Coin$ type of the Shelley specification in transaction outputs for\nthis ledger. We can then describe the ShelleyMA\ntransaction processing rules without fixing a concrete Token algebra.\n\nDepending on the Token algebra chosen, we obtain distinct ledgers. In\nparticular, we get\n\n\\begin{itemize}\n  \\item the Allegra ledger rules with $\\Coin$, and\n  \\item the Mary ledger rules with $\\Value$ (defined below).\n\\end{itemize}\n\nWhen multi-asset support on the ledger is introduced, Ada ($\\Coin$) will still be\nthe most common type of asset on the ledger, as the ledger rules enforce that\nsome quantity of it (specified via\nthe $\\fun{coinsPerUTxOWord}$ protocol parameter) must\nbe contained in every UTxO on the ledger.\nIt is the only\ntype of asset used for all non-UTxO ledger accounting, including deposits,\nfees, rewards, treasury, and the proof of stake protocol. For this reason, not\nall occurrences of $\\Coin$ inside a transaction or in the ledger state can or\nshould be replaced by the chosen Token algebra.\n\nBelow we give the definitions of all the functions that must be defined on\n$\\Coin$ and $\\Value$ in order for them to have the structure of a Token algebra.\nIn Section \\ref{sec:other-valmonoids} we give several other types which we can meaningfully\nsupport the definition of the required functions (addition, size, etc.), including\nan optimized representation that more accurately represents the implementation\nused in the Haskell implementation of the multi-asset type.\nThese types are convertible to and from the $\\Value$ type, and appear in other\nparts of the system as a multi-asset representation which is more suitable in particular\nuse cases.\n\n\\subsection{$\\Coin$ as a Token algebra}\n\nThis section defines the Token algebra structure for the $\\Coin$ type,\nsee Figure \\ref{fig:coin}. The structure of a partially ordered monoid\nis inherited from the (additive) integers.\n\nFor $\\Coin$, no policies are associated with $\\Coin$, since minting of Ada is not allowed.\n\n%%\n%% Figure Coin Functions\n%%\n\\begin{figure}[htb]\n  \\begin{align*}\n      & \\fun{coin} = \\fun{id}_{\\Coin}\n      \\nextdef\n      %\n      & \\fun{inject} = \\fun{id}_{\\Coin}\n      \\nextdef\n      %\n      & \\fun{policies}~v = \\emptyset\n      \\nextdef\n      %\n      & \\fun{size}~v = 0\n  \\end{align*}\n  \\caption{The Token algebra structure of $\\Coin$}\n  \\label{fig:coin}\n\\end{figure}\n\n\n\\subsection{Multi-assets and the Token algebra $\\Value$}\n\nElements of $\\Value$ represent heterogeneous collections of assets,\nboth user-defined and Ada. The Mary era ledger uses $\\Value$ as its Token algebra\nin order to support multi-assets.\n$\\Value$ and its Token algebra structure are given in Figure \\ref{fig:defs:value}.\n\n\\begin{figure*}[t!]\n  \\emph{Derived types}\n  %\n  \\begin{equation*}\n    \\begin{array}{r@{~\\in~}l@{\\qquad=\\qquad}lr}\n      \\var{aname} & \\AssetName & \\mathsf{ByteString} \\\\\n      \\var{pid} & \\PolicyID & \\ScriptHash \\\\\n      \\var{adaID} & \\AdaIDType & \\{~\\mathsf{AdaID}~\\} \\\\\n      \\var{aid} & \\AssetID & \\AdaIDType \\uniondistinct (\\PolicyID \\times \\AssetName) \\\\\n      \\var{quan} & \\Quantity & \\Z \\\\\n      \\var{v}, \\var{w} & \\Value & \\AssetID \\mapsto_0 \\Quantity\n    \\end{array}\n  \\end{equation*}\n  %\n  \\emph{Token algebra structure of $\\Value$}\n  %\n  \\begin{align*}\n    & \\fun{coin}~\\var{v} = \\var{v}~\\mathsf{AdaID}\n    \\nextdef\n    %\n    & \\fun{inject}~c  = \\mathsf{AdaID}~\\mapsto_0~\\var{c}\n    \\nextdef\n    %\n    & \\fun{policies}~v = \\{~\\var{pid}~\\vert~(\\var{pid,~\\wcard}) \\in \\supp v~\\}\n    \\nextdef\n    %\n    & \\fun{size} ~~~ \\text{see Section \\ref{sec:value-size}}\n  \\end{align*}\n  \\caption{$\\Value$ and its Token algebra structure}\n  \\label{fig:defs:value}\n\\end{figure*}\n\n\\begin{itemize}\n  \\item $\\PolicyID$ identifies monetary policies. A policy ID $\\var{pid}$ is associated with a script\n    $s$ such that $\\fun{hashScript}~s=pid$. When a transaction attempts to create or destroy assets\n    that fall under the policy ID $\\var{pid}$,\n    $s$ verifies that the transaction\n    respects the restrictions that are imposed by the monetary policy.\n    See sections \\ref{sec:transactions} and \\ref{sec:utxo} for details.\n\n  \\item $\\AssetName$ is a byte string used to distinguish different assets with the same $\\PolicyID$.\n    Each $aname$ identifies a particular kind of asset out of all the assets under the\n    $\\var{pid}$ policy (but not necessarily among assets under other policies).\n    The maximum length of this\n    byte string is 32 bytes (this is not explicitly enforced in this specification).\n\n  \\item $\\AssetID$ is either $\\mathsf{AdaID}$ or a pair of a policy ID and an asset name.\n  It is a unique and permanent\n  identifier of an asset. That is, there are is no mechanism to change it or\n  any part of it for any assets.\n\n  Mary MA assets are fungible with each other if and only if they have to the same $\\AssetID$.\n  The reason the unique identifier is a pair of two elements (except for the non-mintable Ada case) is to allow\n  minting arbitrary collections of unique assets under a single policy.\n\n  \\item $\\mathsf{AdaID}$ is a special asset ID for Ada, different than all other asset IDs.\n  It is a term of the single-term type $\\AdaIDType$.\n  It does not include a policy, so instead, the validation outcome in the presence\n  of Ada in the $\\fun{mint}$ field of the transaction is specified in the UTXO\n  ledger rule. The rule disallows the $\\fun{mint}$ field to contain Ada.\n\n  \\item $\\Quantity$ is an integer type that represents an amount of a specific $\\AssetName$. We associate\n    a $q\\in\\Quantity$ with a specific asset to track how much of that asset is contained in a given asset value.\n\n  \\item $\\Value$ is the multi-asset type that is used to represent\n    a collection of assets, including Ada. This type is a finitely supported map.\n\n    If $\\var{aid}$ is an $\\AssetID$ and $v \\in \\Value$,\n    the quantity of assets with that assed ID contained in $v$ is $v~\\var{aid}$.\n    Elements of $\\Value$ are sometimes also referred to as\n    \\emph{asset bundles}.\n\\end{itemize}\n\nTo give $\\Value$ the structure of a partially ordered monoid, we define the\nrequired operations\npointwise, in accordance with the usual definitions of these operations on\nfinitely supported maps. See Figure \\ref{fig:pointwise}.\n\n\\begin{figure*}[t!]\n  \\begin{align*}\n    v + w    &= \\{~ aid \\mapsto v~\\var{aid} + w~\\var{aid} ~\\vert~ \\var{aid} \\in \\fun{dom}~v \\cup \\fun{dom}~w ~\\} \\\\\n    v \\leq w &\\Leftrightarrow \\forall~\\var{aid} \\in \\AssetID, v~\\var{aid} \\leq w~\\var{aid}\n  \\end{align*}\n  \\caption{Pointwise operations on Value}\n  \\label{fig:pointwise}\n\\end{figure*}\n\n\\subsection{Special Ada representation}\nAlthough all assets are native on the Cardano ledger (ie. the accounting and\ntransfer logic for them is done directly by the ledger), Ada is still treated in a\nspecial way by the ledger rules, and is the most common type of asset on the ledger.\nIt can\nbe used for special purposes (such as fees) for which other assets cannot be used.\nThe underlying consensus algorithm relies on Ada in a way that\ncannot be extended to user-defined assets.\nAda can also neither be minted nor burned.\n\nNote that in the $\\Value$ definition above, we pick a special asset ID for Ada, that\nis not part of the type which represents the asset IDs for all other assets.\nCombining the asset name and policy for Ada gives a type-level guarantee that there is exactly\none kind of asset that is associated with it in any way, rather than\nderiving this guarantee as an emergent property of minting rules.\n\nAdditionally, not giving Ada an actual policy ID\n(that could have a hash-associated policy) eliminates the possibility\ncertain cryptographic attacks.\nWe sometimes refer to Ada as the primary or principal currency. Ada does not,\nfor the purposes of the Mary ledger specification, have a $\\PolicyID$ or an $\\AssetName$.\n\n\\subsection{Fixing a Token algebra}\n\nFor the remainder of this specification, let $\\ValMonoid$ be an\narbitrary but fixed Token algebra. As described above, choosing\n$\\Coin$ results in the Allegra ledger, and choosing $\\Value$ results\nin the Mary ledger.\n", "meta": {"hexsha": "34896122c06d8d23ceb5934fed9275cac9c0820b", "size": 9641, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "eras/shelley-ma/formal-spec/value.tex", "max_stars_repo_name": "MELD-labs/cardano-ledger", "max_stars_repo_head_hexsha": "9c3b4737b13b30f71529e76c5330f403165e28a6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 108, "max_stars_repo_stars_event_min_datetime": "2019-03-24T02:26:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-30T05:27:16.000Z", "max_issues_repo_path": "eras/shelley-ma/formal-spec/value.tex", "max_issues_repo_name": "MELD-labs/cardano-ledger", "max_issues_repo_head_hexsha": "9c3b4737b13b30f71529e76c5330f403165e28a6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1266, "max_issues_repo_issues_event_min_datetime": "2019-03-18T20:23:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-04T12:50:51.000Z", "max_forks_repo_path": "eras/shelley-ma/formal-spec/value.tex", "max_forks_repo_name": "MELD-labs/cardano-ledger", "max_forks_repo_head_hexsha": "9c3b4737b13b30f71529e76c5330f403165e28a6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 86, "max_forks_repo_forks_event_min_datetime": "2019-03-29T06:53:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-04T17:17:15.000Z", "avg_line_length": 41.2008547009, "max_line_length": 115, "alphanum_fraction": 0.7165231822, "num_tokens": 2621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3465371353713757}}
{"text": "% !TeX root = ../main.tex\n% !TEX spellcheck = en_GB\n\n\\chapter{Design}\n\\label{ch:Design}\n\n\n\\section{Matlab models}\n\\subsection{Speaker}\n\n\\subsection{Drive unit}\n\n\\subsection{Closed Box}\nThis modelling is primarily based on \\citetitle[chap.~2.6,~p.~49-52]{Elektroakustik}\n\n\\subsubsection{Physical parameters}\n\\begin{itemize}\n\t\\item Volume of box $V_B$\n\t\\item Density of air $\\rho_0$ \\footnote{\\href{https://en.wikipedia.org/wiki/Density_of_air}{Wikipedia, Density of air}}\n\t\\item Speed of sound $c$\n\\end{itemize}\n\n\\begin{equation}\n\tC_{AB} = \\frac{V_B}{\\rho c^2}\n\\end{equation}\n\n\\subsection{Crossover filter}\n\n\\FloatBarrier", "meta": {"hexsha": "b9a210b66a53bfd3a4d844f20263725d39371302", "size": 620, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Report/Report/design.tex", "max_stars_repo_name": "lsangild/ETLYAK", "max_stars_repo_head_hexsha": "cf26993e2642b0f5529e7ec1f309446ee5c3cbfa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Report/Report/design.tex", "max_issues_repo_name": "lsangild/ETLYAK", "max_issues_repo_head_hexsha": "cf26993e2642b0f5529e7ec1f309446ee5c3cbfa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Report/Report/design.tex", "max_forks_repo_name": "lsangild/ETLYAK", "max_forks_repo_head_hexsha": "cf26993e2642b0f5529e7ec1f309446ee5c3cbfa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3793103448, "max_line_length": 120, "alphanum_fraction": 0.7306451613, "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3464639096279216}}
{"text": "%% LyX 2.3.3 created this file.  For more info, see http://www.lyx.org/.\n%% Do not edit unless you really know what you are doing.\n\\documentclass[12pt,letterpaper,reqno,english]{amsart}\n\\usepackage[T1]{fontenc}\n\\synctex=-1\n\\usepackage{babel}\n\\usepackage{amstext}\n\\usepackage{amsthm}\n\\usepackage[unicode=true,pdfusetitle,\n bookmarks=true,bookmarksnumbered=false,bookmarksopen=false,\n breaklinks=false,pdfborder={0 0 1},backref=false,colorlinks=false]\n {hyperref}\n\n\\makeatletter\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LyX specific LaTeX commands.\n\\pdfpageheight\\paperheight\n\\pdfpagewidth\\paperwidth\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Textclass specific LaTeX commands.\n\\theoremstyle{definition}\n \\newtheorem{example}{\\protect\\examplename}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% User specified LaTeX commands.\n\\usepackage{tikz}\n\\usepackage{textgreek, enumitem}\n\\usepackage[T1]{fontenc}\n\\usetikzlibrary{decorations.pathreplacing, calc,fit,shapes, positioning,arrows, patterns}\n\n\n%\n\\@ifundefined{definecolor}\n {\\usepackage{color}}{}\n\\usepackage{amsfonts}\\setcounter{MaxMatrixCols}{30}\n\\usepackage{ifpdf} % part of the hyperref bundle\n\\ifpdf % if pdflatex is used\n % set fonts for nicer pdf view\n \\IfFileExists{lmodern.sty}\n  {\\usepackage{lmodern}}{}\n\\fi % end if pdflatex is used\n\n\n\\providecommand{\\U}[1]{\\protect \\rule{.1in}{.1in}}\n\n\n\\providecommand{\\possessivecite}[1]{\\citeauthor{#1}'s\\nolinebreak[2]\n(\\citeyear{#1})}\n\n\n\\renewcommand{\\baselinestretch}{1.35}\n\\setlength{\\topmargin}{0.0in}\n\\setlength{\\textheight}{8.0in}\n\\setlength{\\evensidemargin}{0.20in}\n\\setlength{\\oddsidemargin}{0.20in}\n\\setlength{\\textwidth}{6.1in}\n\n\n\\usepackage{bbold}\n\\DeclareMathOperator{\\EX}{\\mathbb{E}}\n\\DeclareMathOperator{\\E}{\\mathbb{E}}\n\\DeclareMathOperator{\\Prob}{\\mathbb{P}}\n\\DeclareMathOperator{\\R}{\\mathbb{R}}\n\\DeclareMathOperator{\\N}{\\mathbb{N}}\n\\DeclareMathOperator{\\1}{\\mathbb{1}}\n\\DeclareMathOperator{\\0}{\\mathbb{0}}\n\n\\DeclareMathOperator{\\CU}{\\mathcal{U}}\n\\DeclareMathOperator{\\CG}{\\mathcal{G}}\n\\DeclareMathOperator{\\CQ}{\\mathcal{Q}}\n\n\\DeclareMathOperator{\\val}{val}\n\\DeclareMathOperator{\\marg}{marg}\n\\DeclareMathOperator{\\supp}{supp}\n\n\\newcommand{\\euler}{\\mathrm{e}}\n\n\\usepackage{setspace}\n%\\onehalfspacing\n\n\\makeatother\n\n\\providecommand{\\examplename}{Example}\n\n\\begin{document}\n\\title{TA Assignment Problem}\n\\author{Marcin Pęski}\n\\begin{abstract}\nThe goal is to formulate a TA assignment problem and discuss some\nproblems with tryig to solve it using stability-like notions. \n\\end{abstract}\n\n\\date{\\today}\n\\maketitle\n\n\\section{Model}\n\nLet $S$ be the set of students (i.e., candidate TAs). Let $C$ be\nthe set of courses. A (TA) assignment is a mapping $\\phi:C\\rightarrow\\R_{+}^{S}$\nWe refer to $\\phi\\left(c\\right)$ as the assignment to course $c$.\nIf $\\phi$ is an assignment, then for each $s$, define $\\phi\\left(s\\right)\\in\\R_{+}^{C}$\nby $\\phi\\left(s,c\\right)=\\phi\\left(c,s\\right)$. We refer to $\\phi\\left(s\\right)$\nas the assignment of student $s$. Let $\\Phi$ be the space of the\nassignments.\n\nLet $A_{S}=\\R_{+}^{S}$ be the space of possible assignments to courses.\nAnalogously, let $A_{C}=\\R_{+}^{C}$ be the space of possible assignments\nfor students. \n\nEach course $c$ has a subset of assignments $F_{c}\\subseteq A_{S}$\nthat are feasible for it. Examples of feasibility constraints include:\n\\begin{itemize}\n\\item budget: Each course has a budget of $h_{c}$ TA hours that need to\nbe allocated and assignment $\\phi\\left(c\\right)\\in A_{S}$ is feasible\nfor $c$ if and only if \n\\[\n\\sum_{s}\\phi\\left(c,s\\right)=h_{c},\n\\]\n\\item minimum assignment hours: there is a constraint $\\tau_{c}$ such that\nan assignment is feasible only if for each $s$, either $\\phi\\left(c,s\\right)=0$\nor $\\phi\\left(c,s\\right)\\geq\\tau_{c}$. \n\\end{itemize}\nSimilarly, each student $s$ has a subset $A_{s}\\subseteq A_{C}$\nof assignments that are feasible for them. Examples of student feasibility\nconstraints:\n\\begin{itemize}\n\\item maximum assignment: each student $s$ cannot work for more than $\\kappa_{s}$\nhours: \n\\[\n\\sum_{c}\\phi\\left(c,s\\right)\\leq\\kappa_{s},\n\\]\n\\item minimum assignment: student $s$ must work for at least $l_{s}$ hours,\n\\item balance across semesters: There is a set $M$ of ``semesters'' and\neach course $c$ is associated with a subset $M_{c}\\subseteq M$ of\n``semesters'' in which this course is taught. The student $s$ assigned\nhours in semester $m$ are equal to \n\\[\nh_{s}\\left(m;\\phi\\right)=\\sum_{c:m\\in M_{c}}\\frac{1}{\\left|M_{c}\\right|}\\phi\\left(c,s\\right).\n\\]\nIt is required that the student assignment across semesters is balanced:\nfor some constant $\\rho>1$, for each $m,m^{\\prime}$, \n\\[\n\\frac{h_{s}\\left(m,\\phi\\right)}{h_{s}\\left(m^{\\prime},\\phi\\right)}\\leq\\rho.\n\\]\n\\end{itemize}\nAn assignment $\\phi$ is \\emph{feasible} if $\\phi\\left(i\\right)\\in A_{i}$\nfor each $i\\in S\\cup C$. \n\nEach student $s$ has preferences over possible assignments represented\nby utility function $u_{s}:A_{C}\\rightarrow\\R$. Similarly, each course\n$c$ has preferences over assignments represented by $u_{c}:A_{S}\\rightarrow\\R$.\n\nAn assignment is individually rational (for students) if none of the\nstudents is better off by dropping some courses from its assignment\n(the logic is that students cannot be made to work for a course, and\na typical TA contract is written separately for each course. If TAs\nsign up for a bundle, i.e., for each of their assignment, the individual\nrationality would require that each student prefers their assignment\nto \\textbf{0} assignment). Formally, for each $s$, each $D\\subseteq C$,\n$u\\left(\\phi\\left(s\\right)\\right)\\geq u\\left(\\phi_{D}\\left(s\\right)\\right)$,\nwhere $\\phi_{D}$ is an assignment obtained from $\\phi$ by zeroing\nall courses not in $D$ $\\phi_{D}\\left(c,s\\right)=\\begin{cases}\n\\phi\\left(c,s\\right) & c\\in D\\\\\n0 & \\text{otherwise}\n\\end{cases}$. \n\nLet $\\Phi^{*}$ be the set of feasible and individually rational assignments. \n\nA social planner has preferences over $\\Phi^{*}$. \n\n\\section{Core and stability}\n\nSuppose that the social planner would like its assignment to be stable,\nin some sense. It is not clear what exactly stable assignment means\n- as there are many options available. Perhaps the most straightforward\nwould be t consider individually rational assignments that are not\nblocked by 2-agent (student and course) coalitions. But, with many-to-many\nassignments, 2-agent coalitions may not be sufficient and one may\nwant to think about some sort of core-type concept. \n\nInstead of focusing on a stability notion, I want to illustrate the\nproblem with few examples why the any stability-like notion can be\nproblematic. \n\n\\subsection{No externalities\\label{subsec:No-externalities}}\n\nSuppose that student preferences are additive: for each $s$, there\nexist constants $\\nu_{s}\\left(c\\right)$ such that for each $a\\in A_{C}$,\n\\[\nu_{s}\\left(a\\right)=\\sum_{c}a_{c}\\nu_{s}\\left(c\\right).\n\\]\nAdditionally, suppose that all assignments of student $s$ are subject\nto maximum constraint $\\kappa_{s}$. \n\nSimilarly, suppose that course preferences are additive: for each\n$c$, there exist constants $\\nu_{c}\\left(s\\right)$ such that for\neach $a\\in A_{S}$,\n\\[\nu_{c}\\left(a\\right)=\\sum_{s}a_{s}\\nu_{c}\\left(s\\right).\n\\]\nAdditionally, suppose that all assignments of course $c$ are subject\nto maximum constraint $h_{s}$. \n\nIn this environment, one can show that the core is non-empty. Moreover,\ncore allocations can be found by a version of Gale-Shapley algorithm.\n(Should I add this?)\n\n\\subsection{Courses that span across semesters}\n\nIt is well-known that any type of externality (or, more precisely,\ncomplementarities) in many-to-many matching problems leads to problems\nwith the existence of a stable outcome (or core).\n\nOne source of externality that reduces the use of stability as a satisfactory\nsolution concept is given by courses that span across multiple semesters. \n\\begin{example}\n\\label{exa:There-are-three}There are three students $x,y,z$, and\nfour courses $aF,aS,bY,cY$. Courses $bY$ and $cY$ are offered across\ntwo semesters, the other two courses are offered only in one semester.\nEach course needs exactly 1 TA, and each student wants at most 1 course\nper semester. All allocations must be either 1 or 0. (In this example,\npartial allocations would not help anyway.) Student preferences over\nbundles of courses are \n\\begin{align*}\nx: & \\left\\{ aF,aS\\right\\} >bY>aF>\\emptyset,\\\\\ny: & aF>cY>\\emptyset,\\\\\nz: & cY>aS>\\emptyset,\n\\end{align*}\nEssentially, student $x$ really likes course $aF$, but also needs\nmoney and would rather TA for $aF$ and $aS$ than for the whole-year\ncourse $Y$, but is willing to TA for $aF$ only if that's the only\noption. Course preferences are \n\\begin{align*}\naF: & x>y>\\emptyset\\\\\naS: & z>x>\\emptyset,\\\\\nbY: & x>\\emptyset,\\\\\ncY: & y>z>\\emptyset.\n\\end{align*}\nSo, $x$ and $aF$ are top matches for e\\textbackslash each other,\nbut otherwise, there are no obvious matches. \n\nWe show that there is no core. If $y$ is assigned to $aF$, then\n$z$ must be assigned to $cY$ (as that is the top assignment for\n$z$ and the second best assignment for $cY$ after $y$ is taken).\nBut then, given that the best remaining for $aS$ is $x$, $x$ and\npair $\\left\\{ aF,aS\\right\\} $ are a blocking coalition (as the student\nand all courses prefer to rematch with each other). \n\nIf $y$ is assigned to $cY$, then $z$ must be assigned with $aS$\n(as $z$ is the top choice for $aS$ and $aS$ is the top choice for\n$z$ aparat from $cY$ which prefers $y$. But then, since $aS$ prefers\n$z$, $bY$ is the best option for $x$. As a consequence $aF$ is\navailable for $y$ who prefers it to $cY$.\n\nIf $y$ is not assigned to anybody, then $z$ gets $cY$, but then\n$y$ and and $cY$ is a blocking pair. \n\\end{example}\n\n\\subsection{Preferences over the number of assignments}\n\nAnother source of problematic externality is when either students\n(or, resp., courses) have preferences over the total number of assigned\ncourses (resp. students). In fact, a reinterpretation of Example \\ref{exa:There-are-three}\nillustrates a difficulty:\n\\begin{example}\nThere are three students $x,y,z$, and four courses $a,a^{\\prime},b,c$.\nEach student has up to 2h of work available. Courses $b$ and $c$\nrequire 2h of work and they only want to hire the same TA. Courses\n$a,a^{\\prime}$ require 1h of work each. Otherwise, the preferences\nare similar to Example \\ref{exa:There-are-three}: for students \n\\begin{align*}\nx: & \\left\\{ a,a^{\\prime}\\right\\} >b>a>\\emptyset,\\\\\ny: & a>c>\\emptyset,\\\\\nz: & c>a^{\\prime}>\\emptyset,\n\\end{align*}\nand for courses:\n\\begin{align*}\na: & x>y>\\emptyset\\\\\na^{\\prime}: & z>x>\\emptyset,\\\\\nb: & x>\\emptyset,\\\\\nc: & y>z>\\emptyset.\n\\end{align*}\nThere is no stable matching.\n\\end{example}\n\n\\subsection{Minimum assignment}\n\nThere are $n\\geq1$ students and $n+1$ courses. Each student has\n$n+1$ hours and each course needs $n$ hours. The student $s$ utility\nfrom assignment is linear in assignments (like in Section \\ref{subsec:No-externalities}),\nwith coefficients equal to \n\\[\nv_{s}\\left(c\\right)=\\begin{cases}\n1+\\varepsilon & c=s\\\\\n1 & c\\neq s.\n\\end{cases}.\n\\]\nCourse $c$ utility from the assignment $a\\in A_{S}$ depends on the\nnumber of non-zero assignments and it equal to \n\\[\nu_{c}\\left(a\\right)=\\varepsilon1_{s=c}+\\begin{cases}\n1 & \\left|\\left\\{ s:a_{s}>0\\right\\} \\right|=1\\\\\n1-\\varepsilon & \\left|\\left\\{ s:a_{s}>0\\right\\} \\right|=2\\\\\n1-10\\left|\\left\\{ s:a_{s}>0\\right\\} \\right| & \\left|\\left\\{ s:a_{s}>0\\right\\} \\right|>2.\n\\end{cases}\n\\]\nThe first term is a small boost of the utility when the student has\nthe same index as he course. \n\nThen, the unique core allocation (or stable matching under any reasonable\ndeifnition) is when each student is matched for $n$ hours with the\ncourse with the same index and for remaining $1$ hours is assigned\nto course $n+1$. \n\nOf course, the above assignment is Pareto-optimal, but wildly inefficient. \n\\end{document}\n", "meta": {"hexsha": "0c5ff4662f3953ec4ef3c5eb1026f6e27e61b3cd", "size": 11751, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "theory/taallocation.tex", "max_stars_repo_name": "michaelpetersubc/TA-algorithm", "max_stars_repo_head_hexsha": "8bb52be8bb53ce29768f9acf80c8a8b77a07b05f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "theory/taallocation.tex", "max_issues_repo_name": "michaelpetersubc/TA-algorithm", "max_issues_repo_head_hexsha": "8bb52be8bb53ce29768f9acf80c8a8b77a07b05f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "theory/taallocation.tex", "max_forks_repo_name": "michaelpetersubc/TA-algorithm", "max_forks_repo_head_hexsha": "8bb52be8bb53ce29768f9acf80c8a8b77a07b05f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-27T17:23:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T17:23:27.000Z", "avg_line_length": 37.0694006309, "max_line_length": 93, "alphanum_fraction": 0.7248744788, "num_tokens": 3550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.3464638956647564}}
{"text": "\\section{Introduction} \\label{sec:introduction}\nWorst-case optimal join (WCOJ) algorithms, e.g. Leapfrog Triejoin, in the last few years turned conventional thinking about join processing\non its head because these multi-join algorithms have provable lower complexity than classical binary joins,\ni.e. join algorithms that join just two tables at-a-time.\nIn the areas of data warehousing and OLAP, this finding does not have much impact, though,\nsince the join patterns most commonly encountered there are primary-foreign-key joins, short (PK-FK joins),\nwhere the join shapes a tree or snowflake and contains no cycles.\nThe computational complexity of PK-FK joins is by definition linear in size of the inputs.\nIn these \\textit{conventional} cases, binary joins are worst-case optimal already, e.g. hash joins.\n\nHowever, analytical graph queries often use FK-FK joins which can grow over linearly in the size of their inputs,\nand often contain cycles.\nFor these use-cases, binary joins often exhibit highly suboptimal run-times because they generate a rapidly increasing set of\nintermediary results, e.g. when navigating a social graph with an out-degree in the hundreds.\nMany of these intermediary results are eliminated in later joins, e.g. a join that closes a cycle.\nHence, an algorithm which avoids generating these results in the first place is to perform much better and\ncloser to the optimal possible performance given by the output size.\n\\textsc{WCOJ} avoid many of the intermediary results and are guaranteed to reach the best possible run time in terms of\nthe output size~\\cite{agm}.\n\nBecause of the frequent presence of cyclic join-patterns in graph-pattern matching, we believe that worst-case optimal join algorithms\ncould be a useful addition to (analytical) graph database systems.\nTherefore, we aim to integrate a scalable, \\textsc{WCOJ} algorithm in Spark which is used by some modern graph engines~\\cite{caps,gcore,\ngraphframe}.\n\nThe rest of our introduction is structures as follows.\n\\Cref{subsec:graph-pattern-matching} defines the term graph pattern matching, its translation into datalog and\nrelational queries and two examples of cyclic graph pattern used in practice.\nWe aim to give the reader an intuitive understanding of why \\textsc{WCOJ}s are superior to binary joins for graph pattern matching\nin~\\cref{subsec:intuitive-example}.\n\\Cref{subsec:graphs-on-spark} motivates our choice to use Spark as the base for our thesis.\nNext, we state our research questions and contributions in~\\cref{subsec:research-questions-and-contributions}.\nFinally in~\\cref{subsec:thesis-idea}, we outline the main ideas behind the thesis and their connections.\n\n\\subsection{Graph pattern matching}\\label{subsec:graph-pattern-matching}\nGraph pattern matching is the problem of finding all instances of a specific subgraph in a graph.\nThe subgraph to find is described as a pattern or query.\nIn this thesis, we use datalog queries to define subgraph queries.\n\nFor example, \\cref{eqn:triangle} shows the datalog query describing a triangle.\n\n\\begin{equation}\n    \\textit{triangle(a, b, c) $\\leftarrow$ R(a, b), S(b, c), T(c, a)} \\label{eqn:triangle}\n\\end{equation}\n\nHere we join three atoms $S, R$ and $T$ with two attributes each $(a, b)$, $(b, c)$ and $(a, c)$ respectively.\nThe task of enumerating all triangles within the three atoms can be also be described as finding all possible\nbindings for the join variables $a, b$ and $c$ within them.\n\nThe translation from datalog queries to graph patterns is straightforward.\nAn attribute or a variable refers to a vertice in a graph and an atom to an edge.\nA depiction of the subgraph pattern described by~\\cref{eqn:triangle} is shown in~\\cref{fig:pattern-triangle}.\n\n\\begin{figure}\n    \\centering\n    \\includesvg[width=0.2\\textwidth]{svg/triangle}\n    \\caption{Depiction of the triangle subgraph query.}\n    \\label{fig:pattern-triangle}\n\\end{figure}\n\nIn relational terms, a graph pattern matching query is an n-ary, conjunctive, self-equijoin on the edge relationship of the graph.\nIn this thesis, all join queries discussed belong to this subcategory of possible join queries.\nOther join queries can be useful to describe more complex graph patterns, e.g. disjunction for two edges of which only one needs to\nexist or negation to exclude instances that have too many connections.\nSome techniques used in this work can be extended to cover these cases, we mention related literature but do not focus\nour efforts on these extensions.\n\nGraph pattern matching is fundamental to analytical graph analysis workloads~\\cite{fraud-detection,flake2002,\nbodaghi2018automobile,newman2004detecting}.\nWe show two graph patterns which are used in practice below and explain the use-cases.\n\n\\Cref{fig:pattern-diamond} shows the diamond query which is used by Twitter to recommend their users new people to follow.\nThe idea is that if user $a$ is following multiple accounts $c_1, \\dots, c_k$ who all follow a person $b$ then it is likely that\n$b$ would be interesting to follow for $a$ as well.\nIn the figure, we see the diamond query for $k = 2$.\nThis is the diamond query as discussed in most papers in academia~\\cite{olddog,myria-detailed,mhedhbi2019}, although,\nTwitter uses $k = 3$ in production~\\cite{twitter-diamond}.\n\n\\begin{figure}\n    \\centering\n    \\includesvg[width=0.2\\textwidth]{svg/diamond}\n    \\caption{The dimaond query is used by Twitter. The vertices are users and the edges follower relationships.\n    In the example, they could recommend $A$ to follow $D$ because $A$ follows $B_1$ and $B_2$ which both follow $C$.\n    }\n    \\label{fig:pattern-diamond}\n\\end{figure}\n\nOur second concrete use-case example is the n-cycle.\nAs explained in~\\cite{fraud-detection}, cycles can be used to detect bank fraud.\nA typical bank-fraud often involves so-called \\textit{fraud-rings}.\nThese are two or more people who combine their legitimate contact information in new ways to craft multiple false identities.\nFor example, two people share real phone numbers and addresses to craft four fake identities; all combinations possible with two pieces\nof information.\nThey open accounts under wrong names with real contact information, use these accounts normally to build trust with the bank and\nbuild up bigger credit lines.\nAt a certain date, they max out all credit lines and disappear.\nThe phone numbers are dropped and the actual people living at the addresses deny ever knowing the identities that opened the accounts.\n\nThis scheme can be detected using graph pattern matching.\nLet us assume, we have a graph database in which customer of the bank, their addresses and phone numbers are all vertices and the\nrelationship of an address or phone number belonging to a customer are edges.\nThen, the case described above forms an 8-cycle of 4 persons (fake identities) connected by the shared use of phone numbers and\naddresses.\nThe imagined cycle is shown in~\\cref{fig:graph-pattern-example-bank-fraud}.\n\n\\begin{figure}\n    \\centering\n    \\includesvg[width=0.2\\textwidth]{svg/bank-fraud}\n    \\caption{Schematics of a bank fraud ring.\n    2 fraudsters share their phone numbers and addresses (labelled $P$ and $A$) to create four\n    fake customers ($C$ vertices).\n    }\n    \\label{fig:graph-pattern-example-bank-fraud}\n\\end{figure}\n\n\n\\subsection{Binary joins vs \\textsc{WCOJ}s: an intuitive example} \\label{subsec:intuitive-example}\nWe introduce the triangle query and possible binary join plans.\nThen we point out the general problem of binary join plans on this query and the idea of how \\textsc{WCOJ}s can improve the situation.\nNext, we give a concrete example of a database instance to illustrate the aforementioned problem.\nWe conclude our motivation to use worst-case optimal joins by reporting multiple papers that show that these joins are highly beneficial\nto graph pattern matching queries in practice.\n\nThe simplest example of a cyclical join query enumerates all triangles in a graph.\nIt is shown in~\\cref{eqn:triangle} and \\cref{fig:pattern-triangle}.\n\nTraditionally, this would be processed by using multiple binary joins:\n\\begin{equation}\n    R \\bowtie S \\bowtie T\n\\end{equation}\nThe join above can be solved in 3 different orders: $ (R \\bowtie S) \\bowtie T$, $ (R \\bowtie T) \\bowtie S$ and\n$ R \\bowtie (T \\bowtie S)$.\nIndependent of the chosen order, database instances exist where the intermediary result size is in $\\mathcal{O}(N^2)$ with\n\\textit{N}= |\\textit{R}| = |\\textit{S}| = |\\textit{T}|.\nHowever, it is provable that the output of this query is guaranteed to be in $\\mathcal{O}(n^{3/2})$~\\cite{agm,skew-strikes-back}\nfor any database instance.\nHence, binary joins materialize huge intermediary results after processing parts of the query,\nwhich are much bigger than the final result.\n\nThe described problem is a fundamental issue with traditional binary join plans~\\cite{agm,skew-strikes-back}.\nWe call these plans also \\textit{join-at-a-time} approach because they process whole joins at the time.\n\nFortunately, worst-case optimal join algorithms can materialize cyclic joins with memory usage linear to their output size\nby solving the join \\textit{variable-at-a-time} which avoids materializing big intermediary results~\\cite{lftj,nprr}.\n\nIn variable-at-a-time the algorithm finds a binding for the first variable $a$, then one for $b$ and\nfinally one for $c$.\nAfter this, it emits the tuple as part of the output.\nThen it finds further bindings via backtracking until they enumerated the whole join when all bindings for $a$ have been explored.\n\n% Example concrete\nA simple example graph database instance gives an idea of why a variable-at-a-time approach is beneficial for cyclic queries.\nIn \\cref{fig:edge-rel-example}, we see an edge relationship.\nIt is repeated three times labelled with different attributes to ease the understanding of the following explanation;\nhowever, in a system's implementation, only one table exists and is used by all joins as input.\n\n\\begin{figure}\n    \\centering\n    \\subfloat{\n      $R$\n    \\begin{tabular}{rr}\n        \\toprule\n        a &  b \\\\\\midrule\n        1 &  2 \\\\\n        2 &  7 \\\\\n        2 &  8 \\\\\n        2 &  9 \\\\\n        2 & 10 \\\\\n        3 &  2 \\\\\n        4 &  2 \\\\\n        5 &  2 \\\\\n        6 & 11 \\\\\n        11 & 12 \\\\\n        12 &  6 \\\\\\bottomrule\n    \\end{tabular}\n    }\n    \\hspace{0.2\\textwidth}\n    \\subfloat{\n     $S$\n    \\begin{tabular}{rr}\n        \\toprule\n        b &  c \\\\\\midrule\n        1 &  2 \\\\\n        2 &  7 \\\\\n        2 &  8 \\\\\n        2 &  9 \\\\\n        2 & 10 \\\\\n        3 &  2 \\\\\n        4 &  2 \\\\\n        5 &  2 \\\\\n        6 & 11 \\\\\n        11 & 12 \\\\\n        12 &  6 \\\\\\bottomrule\n    \\end{tabular}\n    }\n    \\hspace{0.2\\textwidth}\n    \\subfloat{\n    $T$\n    \\begin{tabular}{rr}\n        \\toprule\n        c &  a \\\\\\midrule\n        1 &  2 \\\\\n        2 &  7 \\\\\n        2 &  8 \\\\\n        2 &  9 \\\\\n        2 & 10 \\\\\n        3 &  2 \\\\\n        4 &  2 \\\\\n        5 &  2 \\\\\n        6 & 11 \\\\\n        11 & 12 \\\\\n        12 &  6 \\\\\\bottomrule\n    \\end{tabular}\n    }\n    \\caption{\n    Three aliases to an edge relationship which contains three triangles, the permutations of \\{6, 11, 12\\},\n    and one skewed value.\n    }\n    \\label{fig:edge-rel-example}\n\\end{figure}\n\nA binary join plan which joins $R$ and $S$ via $b$ first produces $16 + 3$ intermediary results;\n4 times 4 results for $b = 2$ and one for 6, 11, 12 each.\nThe next join reduces these 16 results to the three triangle instances; all permutations of the set \\{6, 11, 12\\}.\n\nA variable-at-a-time approach finds 4 bindings for $a$, namely  $2, 6, 11, 12$;\nthe intersections of both columns labelled $a$.\n\nIntersecting both columns of $b$ values we notice $2, 6, 11, 12$ could be possible bindings for $b$.\nWhen we fix an $a$ value these four possibilities are reduced to the $b$ values which exist for this\n$a$ value in the leftmost table.\nSo once we fixed a binding for $a$, we find one possible binding for $b$ each;\nexcept the binding $a = 2$ for which we cannot find a matching $b$ value.\n\nFinally, we find all three instances of the triangle by completing the three $a, b$ bindings with\nthe matching $c$ binding;\nonly one exists for each $a, b$ binding.\n\nWe can drastically reduce the workload by formulating the join as a problem of\nfinding variable bindings using information from all parts of the join, instead of, using only one constraint at the time\nand building it join-by-join.\n\nWe do not claim that the example above illustrates the generality of why binary join plans are provable worse than\n\\textsc{WCOJ}s.\nClearly, the example does not show an intermediary result of $N^2$ as $N = 11$ and the intermediary result has the size of 16.\nHowever, we note that even in such a simple example all possible binary join orders produce an intermediary result of size 16.\nWhile all possible variable orderings for a variable-at-a-time approach eliminate the skewed value (2) after finding no binding\nfor the second variable.\nA more general but less concrete example is explained in~\\cite{skew-strikes-back}.\n\n% WCOJ's in practice\nIn practice, these worst-case optimal join algorithms are highly beneficial for cyclic queries in analytical graph\nworkloads in an optimized, single machine system~\\cite{lftj,olddog}.\n\\cite{olddog} compares a system using \\textsc{WCOJ}s against multiple general-purpose database\nsystems using binary joins and some graph pattern matching engines on 15 datasets and 7 queries and\nfinds that worst-case optimal joins can beat all other systems in the vast majority of queries\nand datasets, often by the order of magnitudes or even being the only system to finish within 30 minutes.\n\nLater worst-case optimal joins have been applied successfully to a distributed shared-nothing settings~\\cite{myria-detailed,\nammar2018distributed};\nwe describe these systems in more detail in~\\cref{subsec:myria} and~\\ref{subsec:wcoj-timely-data-flow}.\n\n\\subsection{Graphs on Spark}\\label{subsec:graphs-on-spark}\nSpark is an attractive target for big graph processing, due to its generality, widespread acceptance in the industry, the ability to use\ncloud hardware and its fault tolerance by design.\nFor example, GraphFrames~\\cite{graphframe}, GraphX~\\cite{graphx} (a Pregel~\\cite{pregel} implementation) or graph query languages\nas \\mbox{G-CORE}~\\cite{gcore} and \\mbox{openCypher} with `Cyper for Apache Spark' or \\textsc{CAPS}~\\cite{caps} all aim to ease graph\nprocessing on Spark.\nThe last two technologies translate their graph specific operations to the relational interface of Spark (SparkSQL)\nto profit from Spark's relational query optimizer Catalyst~\\cite{spark-sql}.\nMoreover, they allow the user to formulate graph pattern matching queries naturally.\n\nHence, we believe that the \\textsc{WCOJ}s, with their efficiency for analytical graph queries, are a valuable addition to Spark's\nbuilt-in join algorithms in general and these graph-on-spark systems in particular.\nIdeally, they are integrated such that they can be naturally used in the ecosystem of Catalyst.\nThis would allow easier use in SQL like graph languages as \\textsc{G-CORE} or Cypher for graph pattern matching.\n\n\\subsection{Research questions and contributions}\\label{subsec:research-questions-and-contributions}\nWe identify two challenging, novel directions for our research.\nFirst, all papers about \\textsc{WCOJ} focus on queries widely used in graph pattern matching, e.g. clique finding or path queries.\nAs explained above, graph pattern matching uses only self-joins on a single relationship with two attributes\nnamely the edge relationship of the graph.\nHowever, all systems use worst-case optimal joins developed for general n-ary joins.\nThis raises the question if and how \\textsc{WCOJ}s can be specialized for graph pattern matching.\n\nSecond, while the communication costs for worst-case optimal joins in MapReduce like systems\\footnote{\nAn excellent definition of the term MapReduce like systems is given in~\\cite{shares}}\nis well-understood~\\cite{shares,shares-skew,shares-proof,shares-skew-proof},\ntheir scalability has not been studied in depth.\nGiven that the only integration in a MapReduce like system exhibits a speedup of 8 on 64 nodes over two workers (an efficiency of 0.125)\n~\\cite{myria-detailed},\nwe find that designing a scalable, distributed \\textsc{WCOJ} for a MapReduce like system is an unsolved challenge.\n\nIt is time to investigate how these algorithms scale in the provable most widely used, general-purpose big data processing engine: Spark.\nTo the best of our knowledge, this is also the first time a worst-case optimal join is integrated with an industrial-strength cluster\ncomputing model.\nWe detail our research questions below.\n\n\\begin{enumerate}\n    \\item Can we gain performance in \\textsc{WCOJ}s by specializing them to graph pattern matching?\n    \\begin{enumerate}\n        \\item How much performance can we gain by using compressed sparse row representations as backing data structure to \\textsc{WCOJ}s?\n        \\item Can we find a more suitable algorithm to build intersections for graph-pattern matching than the complex n-ary approach\n         proposed originally?\n    \\end{enumerate}\n    \\item How well do \\textsc{WCOJ}s scale in Spark when used for graph pattern matching?\n    \\begin{enumerate}\n        \\item How well does a previously proposed, optimal partitioning scheme, named Shares, scale?\n          We explain Shares in detail in~\\cref{subsubsec:shares}.\n        \\item How to integrate scalable work-stealing into Spark to counter tuple replication and skew?\n    \\end{enumerate}\n\\end{enumerate}\n\nTowards answering our research questions, we make the following contributions.\n\\begin{enumerate}\n    \\item We integrate a sequential, general worst-case optimal join into Spark.\n    This implementation serves as a baseline for our \\textsc{WCOJ} optimized to graph pattern matching.\n    \\item We design and implement GraphWCOJ which is a worst-case optimal join specialized to graph pattern matching.\n    It is backed by a compressed sparse row representation of the graph which reduces its memory footprint and speeds up execution by up\n    to 11 times over a normal \\textsc{LFTJ} because it acts as an index. % NUMBER\n    Furthermore, we exploit the typical low out-degree of most graphs to by specializing the \\textsc{LFTJ} for small intersections.\n    \\item We analyse how many tuples Shares replicates for typical graph pattern matching queries.\n    From this analysis and the fact that Shares is an optimal partitioning scheme, we conclude that replication is inevitable for complex\n    graph-pattern matching queries.\n    Therefore, we cache the graph in the memory of all workers.\n    \\item Based on a replicated edge relationship, we design \\textit{logical} Shares.\n    This is an approach where the graph is fully replicated but we use Shares partitioning to divide work between executors.\n    We measure a speedup of 13 on 64 workers for some queries and beat an existing implementation of (physical) Shares which reaches\n    a speedup of 8 for the same number of machines.\n    The results show that Shares is good in dealing with skew but requires too much replicated work to scale well.\n    \\item Therefore, we abandon static partitioning and design a \\textsc{WCOJ} that applies work-stealing.\n    We show that work-stealing can scale linearly on some input queries and beats \\textit{logical} Shares for all levels of parallelism\n    \\item for 3-cliques and 5-cliques on three different datasets.\n    \\item We run experiments on 5 datasets, 6 queries, for up to 382 workers using Spark's build-in hash join,\n    a general Leapfrog Triejoin and our specialized GraphWCOJ.\n\\end{enumerate}\n\n\\subsection{Thesis overview} \\label{subsec:thesis-idea}\nIn this section, we outline the main ideas, motivation and decisions taken in this thesis.\nWe summarize the whole thesis as a graph in~\\cref{fig:thesis-overview}.\nWe see the background that motivates our decision in the corners and our system in the centre.\nThe edges show connections between different ideas and components.\nWe give an overview of the thesis in the next paragraphs.\n\n\\begin{figure}\n    \\centering\n    \\includesvg[width=\\textwidth]{svg/thesis-overview}\n    \\caption{\n    Main ideas and components of the thesis.\n    Background and related work shown in the corners.\n    The center shows the main component of our parallized worst-case optimal join\n    }\n    \\label{fig:thesis-overview}\n\\end{figure}\n\nAs mentioned in~\\cref{subsec:graphs-on-spark}, Spark is a good platform for our work because many graph pattern matching systems use\nit, like neo4j's Cypher on Apache Spark (CAPS) and LDBC's G-CORE~\\cite{caps,gcore}.\nIn particular, they build on top of Spark's structured query execution offered by Catalyst.\nCatalyst is designed to be easily extendable and allows to introduce new operators, such as a worst-case optimal join,\nwithout modifying the core of Spark.\nThis is even possible in a way such that these new operators can be used with a native, unchanged installation of Spark.\nWe describe Catalyst query compilation process in~\\cref{subsubsec:catalyst}.\nOur integration is detailed in~\\cref{sec:spark-integration}.\n\nNormally, Spark achieves parallelism and distributed algorithms by partitioning data over all workers.\nWhen data from different tables needs to be joined, Spark repartitions the data such that each worker can process parts of the join locally.\nHowever, shuffling is an expensive operation in Spark, involving disk writes and reads, which should be avoided if possible.\nMoreover, we can show that a communication-optimal partitioning scheme degenerates into a full broadcast for bigger graph pattern queries;\nwe explain this in detail in~\\cref{subsubsec:shares}.\n\nGiven this finding, we design our system to build on a replicated and cached edge relationship on each worker.\nAs a short study of us reveals, most large graph problems described in literature, have edge structures that would fit in\nmain-memory (see~\\cref{subsec:graph-analysis});\nand our compressed storage format further helps to keep memory usage under control.\nThis has a few distinct advantages.\n\nFirst, the broadcast can be done once at system startup.\nThen, we can reuse it for any graph pattern matching query;\nall of them need to join over the edge relationship many times.\nTherefore, we can answer many graph pattern matching queries without shuffling data.\nWe explain the integration of replicated edge relationships into Spark in~\\cref{subsec:spark-integration-graphWCOJ} and introduce\nthe necessary background in~\\cref{subsubsec:broadcast-variables}.\n\nFurthermore, such reuse helps to amortize the non-trivial setup costs for worst-case optimal joins;\nthey require their input data to be sorted.\n\nFinally, a replicated data structure allows us to use dynamic work-sharing schemes as work-stealing cheaply without relocating\ndata.\nNormally, partitioning is done completely statically in Spark.\nHowever, this is problematic given that many real-world graphs are highly skewed, e.g. power-law graphs such as many follower graphs\n(Facebook, Twitter) or web graphs.\nWe find that this skew can easily lead to bad load-balancing with the static partitioning of Spark.\nWe explain how to integrate work-stealing with Spark in~\\cref{subsec:work-stealing}.\n\nUsing a fully replicated edge relationship and potentially work-stealing leads to the necessity to build data-partitioning into\nthe worst-case optimal join operators.\nThis is because Spark would normally have an operator work on all local data and archive parallelism via physically partitioning the\ndata over multiple workers.\nWe call partitioning built into our operators \\textit{logical} partitioning.\nThe concept and its implementation are described in~\\cref{sec:worst-case-optimal-join-parallelization}.\n\nWe choose to use the Leapfrog Triejoin~\\cite{lftj} as a basis for our system;\nthis choice is motivated in~\\cref{subsec:worst-case-optimal-join-algorithm}.\nThis join requires its input relationships to be presented in a sorted data structure which is searchable for upper bounds in\n$\\mathcal{O} (\\log N)$.\nFurthermore, it mainly uses intersections to compute the join.\nThe algorithm is explained in detail in~\\cref{subsubsec:leapfrog-triejoin}.\n\nWe specialize the Leapfrog Triejoin to graph pattern matching by introducing a compressed sparse row representation~(\\textsc{CSR}, see\n\\cref{subsec:csr-background}) as backing data structure for the input relationships.\n\\textsc{CSR} can compress the graph edge relationship by a compression factor of nearly 2.\nAdditionally, we show that it speeds up the \\textsc{WCOJ} execution to be backed by a \\textsc{CSR} because this representation\nacts like an index.\n\nAnother graph specific optimization we apply to \\textsc{LFTJ} is that we change the intersection building algorithm for one\nthat is specialized in small intersections.\nThis is motivated by the fact that real-world graphs have normally small average out degrees.\nHence, the intersection of multiple adjacency lists is predictably small.\nWe discuss both specializations to the Leapfrog Triejoin algorithm in~\\cref{sec:graphwcoj}.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n% Also introduce cached edge table, ref related work for why communication does not work\n% and goals for explanation of why we think caching is helpful\n% use mcsherry, other guy here?  --> read them\n\n% These academic systems are not very usable nor used, nor is LogicBlox on the market as a database system.\n% For all practical senses and purposes, there are no %systems available that implement WCOJs. Apache Spark is currently the most popular\n% analytical data processing system. It does not implement WCOJs yet and has %multiple popular graph processing APIs or subsystems, among\n% which GraphFrames, CAPS (neo4j's Cypher on Apache Spark) and the recent LDBC effort to implement the G-%CORE query language on Apache\n% Spark. All of these APIs could potentially benefit greatly from a WCOJ algorithm.\n\n%Spark offers a well optimized Relational interface [SparkSQL] [Catalsyst]\n%Relational interfaces rely on JOINS which have different characteristics different for graphs than for traditional star or snowflake schemes.\n% - they are cyclic for important graph algorithms (cluster, ?subgraphing?)\n%  - large intermediary results which make the queries really expensive for the CPU as well as the in memory\n%   - work is done for nothing because most of the intermediary results are filtered out later\n% - they are highly selective (paths starting from a specific node)\n%  - allowing to safe work when all \"filters\" are applied simultaneously\n%  - allowing for big jumps on sorted keys with a seek operation, naturally, applied by LFTJ\n% - therefore, they are a prime area of application for a new class of join algorithms with worst-case guarantees, which guarantee that no big intermediary results build up\n%because the evaluate multiple joins as once only materializing results that fulfil all join filters.\n% - Furthermore, they are naturally suited for highly selective queries because of using an O(log(N)) seek a method to jump over \"uninteresting\" parts of a sorted result.  \n", "meta": {"hexsha": "de634280c8b56fc8611eda69bc4707f6d29df8d4", "size": 27101, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "introduction.tex", "max_stars_repo_name": "PerFuchs/master-thesis", "max_stars_repo_head_hexsha": "85386c266fecf72348114bcbafeeb896a9e74601", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-02T20:23:03.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-02T20:23:03.000Z", "max_issues_repo_path": "introduction.tex", "max_issues_repo_name": "PerFuchs/master-thesis", "max_issues_repo_head_hexsha": "85386c266fecf72348114bcbafeeb896a9e74601", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "introduction.tex", "max_forks_repo_name": "PerFuchs/master-thesis", "max_forks_repo_head_hexsha": "85386c266fecf72348114bcbafeeb896a9e74601", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.0435729847, "max_line_length": 172, "alphanum_fraction": 0.7690860116, "num_tokens": 6409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.34646265258178166}}
{"text": "%$Id: Oral.tex 82 2007-06-08 14:32:56Z jlconlin $\n%$Author: jlconlin $\n%$Date: 2007-06-08 08:32:56 -0600 (Fri, 08 Jun 2007) $\n%$Revision: 82 $\n\n\\documentclass[11pt]{article}\n\\usepackage{geometry}\n\\usepackage[algo2e, ruled, linesnumbered]{algorithm2e}\n\\usepackage{amsmath}\n\\usepackage{amsfonts}\n\n\\SetKwComment{Comment}{$\\triangleright$ }{}\n\\dontprintsemicolon\n\n%\\renewcommand{\\span}{\\mathrm{span}}\n\n\\author{Jeremy Conlin}\n\\title{Oral Thesis Prospectus}\n\\date{June 6, 2007}\n\n\\begin{document}\n\\maketitle\n\\abstract{\n    The power method, or source iteration, has been the staple of Monte Carlo particle transport eigenvalue calculations for more than fifty years.  This method is easy to implement and provides the dominant eigenvalue and eigenfunction, however, this method is slow.  The rate of convergence is proportional to the dominance ratio, the ratio of the second largest eigenvalue to the largest eigenvalue.\n\n    For this thesis, I propose using an alternative to the power method, Arnoldi's Method of Minimized Iterations.  Arnoldi's method is an improvement over the power method; it uses information from all previous iterations---instead of only the last iteration---to calculate the eigenfunction. \n    \n    Preliminary results indicate that Arnoldi's method is less noisy than the Power method and the eigenvalue and the eigenfunction are converged more quickly.  However, the RMS error of the eigenfunction---compared to a deterministic SN calculation---calculated with Arnoldi's method is larger than the RMS error from a power method calculation for the same number of Monte Carlo histories.  Other results show that Arnoldi's method can calculate higher eigenmodes which the power method is unable to do without additional calculations.\n\n    Several questions must be explored before the use Arnoldi's method in Monte Carlo particle transport can be accepted.  Most importantly, how can the uncertainty be calculated?  Without a measure of the statistical uncertainty, the answer is meaningless.  A simple solution is to restart the method after a few iterations and find the mean and variance of the eigenvalues after each restart.  I believe there is a better and more efficient way; this is one aspect of my thesis research.\n\n    Arnoldi's method requires the calculation of an inner product between two functions.  In Monte Carlo particle transport, these functions are fission sources.  In initial studies, these fission sources were spatially binned; the height of these bins are the elements of a vector.  Discretizing a fission source in this manner introduces bias to the calculation.  The inner product of two vectors is a simple dot product.  Is there a way to calculate the inner product of two fission sources without resorting to binning the sources?  Can we use basis functions other than histogram step functions to expand the fission source?  These are additional questions I plan on addressing in my thesis.\n\n    All calculations so far have been performed in 1-D homogeneous slab geometries.  What will happen in heterogeneous and multi-dimensional geometries?  Is Arnoldi's method still valid and does it still offer the same benefits?  Although unknown for certain at this time, I propose the answer is yes.  The reduced noise when using Arnoldi's method may lead to dramatic improvements in calculating eigenfunctions of geometries where highly absorbing materials are separated by highly scattering materials (e.g. the eigenvalue of the world type problems).  No mathematical obstacles---other than lack of experience of the author---immediately present themselves as problems to using Arnoldi's method in higher dimensions.  \n}\n\n%\\end{document}\n\\section{Power Method---Source Iteration}\nThe particle transport equation\n\\begin{equation}\n    \\mathbf{\\Omega}\\cdot\\mathbf{\\nabla}\\psi(\\mathbf{r},\\mathbf{\\Omega})+\\Sigma_t\\psi(\\mathbf{r},\\mathbf{\\Omega}) = \\Sigma_s\\psi(\\mathbf{r},\\mathbf{\\Omega}) + \\frac{1}{k}\\nu\\Sigma_f\\psi(\\mathbf{r},\\mathbf{\\Omega}),\n\\end{equation}\ncan be written in operator form\n\\begin{subequations}\\begin{align}\n    (\\mathbf{L} + \\mathbf{C} - \\mathbf{S})\\psi &= \\frac{1}{k}\\mathbf{F}\\psi \\\\\n    \\mathbf{T}\\psi &= \\frac{1}{k}\\mathbf{F}\\psi. \\label{eq:Opr}\n\\end{align}\\end{subequations}\nwhere $\\mathbf{L}, \\mathbf{C},$ and $\\mathbf{S}$ are the leakage, collision, and scattering operators respectively; and $\\mathbf{F}$ is the fission operator.  The operator $\\mathbf{T}$ is the transport-collision operator.  The left-hand side represents the neutron loss mechanisms and the right-hand side represents the neutron gain mechanism.\n\nLet us define\n\\begin{align}\n    q &\\equiv \\mathbf{F}\\psi, \\\\\n    \\mathbf{A} &\\equiv \\mathbf{F}\\,\\mathbf{T}^{-1}\n\\end{align}\nand manipulate Eq. \\ref{eq:Opr} to find\n\\begin{equation}\n    q = \\frac{1}{k}\\mathbf{A}q. \\label{eq:evalue}\n\\end{equation}\nThis is a standard eigenvalue problem with eigenvalue $k$ and eigenvector $q$.  The linear operator $\\mathbf{A}$ first transports source particles and then computes a fission source from the resulting particle population.\n\nWe can use Eq. \\ref{eq:evalue} in an iterative manner\n\\begin{equation}\n    q^{(n+1)} = \\frac{1}{k^{(n)}}\\mathbf{A}q^{(n)}. \n\\end{equation}\ngiven an initial eigenvector $q$ and eigenvalue $k$ (usually $k=1$.)  Each iteration consists of calculating a new estimate of the eigenvector and eigenvalue,\n\\begin{equation}\n    k^{(n+1)} = \\frac{Aq^{(n)}}{q^{(n)}} = \\frac{q^{(n+1)}}{q^{(n)}}.\n\\end{equation}\n\n\\section{Krylov Subspaces}\nA careful reader will notice Power Method generates a series of vectors\n\\begin{equation}\n    \\{v, Av, A^2v, \\ldots, A^{m-1}v\\} = \\{q_0, q_1, q_2, \\ldots, q_{m-1}\\}.\n\\end{equation}\nThe vectors $\\{q\\}$ form a basis of the Krylov subspace denoted\n\\begin{equation}\n    \\mathcal{K}_m(A,v) = \\mathrm{span} \\{q_0, q_1, \\ldots, q_{m-1}\\}.\n\\end{equation}\nAny Monte Carlo based particle transport code will create a Krylov subspace.  One starts with the initial source distribution, $q_0$, and transports it defined by the operator, $A$.  This generates a new source distribution, $q_1$ which is then transported.  \n\nPower Method has been used for greater than 50 years, but isn't there a better way?  Deterministic numerical methods researchers have found eigenvalue methods that are faster than Power Method.  Can these be applied in a Monte Carlo code?  The answer is a resounding ``We think so.''\n\n\\section{Minimized Iteration---Arnoldi's Method}\nIn contrast to the Power Method, Arnoldi's Method uses all the vectors previously calculated; after $k$ steps, we have $k+1$ vectors $\\{q, Aq, A^2,\\ldots, A^kq\\}$.  In practice, these vectors usually are an ill-conditioned basis for the space they span.  The vector $A^jq$ points more and more in the direction of a dominant eigenveactor for $A$ as $j$ is increased.  \\marginpar{Why is this a problem?  Is it because we get little information about the other vectors?}\n\nArnoldi's method creates an orthonormal set of basis vectors $\\{q_1, \\ldots, q_{k+1}\\}$ that spans the same Krylov subspace, $\\mathcal{K}(A, q)$.  This orthonormal basis can be built up one vector at a time.  At the $k+1$st step we could simply multiply $A^{k-1}q$ by $A$ to get $A$.  It is inefficient to raise the matrix to a high poer, but we dont' have to.  To get $q_{k+1}$ we operate on $q_k$ by $A$ and orthogonalize against the previous vectors.  \n\nThe details of the Arnoldi process follow.  We begin with the normalization of the original vector\n\\begin{equation}\n    q_1 = q/\\|q\\|_2.    \\label{eq:begin}\n\\end{equation}\nAt all subsequent steps we take\n\\begin{equation}\n    \\tilde{q}_{k+1} = Aq_k - \\sum_{j=1}^k q_j h_{jk}.   \\label{eq:mvOrtho}\n\\end{equation}\nwhere\n\\begin{equation}\n    h_{jk} = \\langle Aq_k, q_j \\rangle.\n\\end{equation}\nLastly, the vector is normalized\n\\begin{equation}\n    q_{k+1} = \\frac{\\tilde{q}_{k+1}}{h_{k+1,k}},\n\\end{equation}\nwhere\n\\begin{equation}\n    h_{k+1,k} = \\|\\tilde{q}_{k+1}\\|_2. \\label{eq:end}\n\\end{equation}\n\nEqs. \\ref{eq:begin}-\\ref{eq:end} are summarized in Algorithm \\ref{alg:Arnoldi}.  The matrix/operator $A$ itself is never used, only the matrix-vector product (see line \\ref{algln:MonteCarlo}).  This is what allows us to use this method in a Monte Carlo code.  The Monte Carlo particle transport solves $\\tilde{q}_{k+1} = Aq_k$.\n\n\\begin{algorithm2e}\n    \\label{alg:Arnoldi}\n    \\SetVline\n    \\caption{Arnoldi Process (freely borrowed from Watkins(2002))}\n    $q_1 = q/\\left\\|q\\right\\|_2$ \\;\n    \\For{$k=1,\\ldots,m-1$}{\n        $\\tilde{q}_{k+1} \\gets Aq_k$\\;  \\nllabel{algln:MonteCarlo}\n        \\For(\\Comment*[f]{Orthogonalize}){$j=1, \\ldots, k$}{ \n            $h_{jk} \\gets \\left<q_j,q_{k+1}\\right>$\\;\n            $q_{k+1} \\gets q_{k+1} - q_jh_{jk}$}\n        $h_{k+1,k} \\gets \\left\\|q_{k+1}\\right\\|_2$\\;\n        \\If(\\Comment*[f]{Span \\{$q_1, \\ldots, q_k$\\} is invariant under $A$}){$h_{k+1,k} = 0$}{\n            quit.}\n        $q_{k+1} \\gets q_{k+1}/h_{k+1,k}$\\;\n    }\n\\end{algorithm2e}\n\n\\subsection{Finding Eigenvalues with Arnoldi's Method}\nThe orthonormal vectors can be combined into a single matrix\n\\begin{equation}\n    Q_m = \\left[q_1 \\cdots q_m\\right] \\in \\mathbb{C}^{n\\times m}.\n\\end{equation}\nThe inner products \n\\begin{equation}\n    h_{jk} = \\langle Aq_k, q_j\\rangle\n\\end{equation}\nform an upper Hessenberg matrix, \n\\begin{equation}\n    H = \n    \\begin{bmatrix}\n        h_{11} & h_{12} & \\cdots & h_{1,m-1} & h_{1m} \\\\\n        h_{21} & h_{22} & \\cdots & h_{2,m-1} & h_{2m} \\\\\n        0 & h_{32} & \\cdots & h_{3,m-1} & h_{3m} \\\\\n        \\vdots & \\ddots & \\ddots & & \\vdots \\\\\n        0 & \\cdots & 0 & h_{m,m-1} & h_{mm} \\\\\n        0 & 0 & \\cdots & 0 & h_{m+1,m}\n    \\end{bmatrix}\n    \\in \\mathbb{C}^{m+1 \\times m}.\n\\end{equation}\n\nWe can rewrite Eq. \\ref{eq:mvOrtho} in terms of $A$, $Q$, and $H$,\n\\begin{equation}\n    AQ_m = Q_{m+1}H_{m+1,m},    \\label{eq:MatrixRep}\n\\end{equation}\nor by separating the last column of $Q_{m+1}$ and the bottom row of $H_{m+1,m}$\n\\begin{equation}\n    AQ_m = Q_{m}H_{m} + q_{m+1}h_{m+1,m}e_m^T   \\label{eq:MRepmthIter}\n\\end{equation}\nwhere $e_m$ is the $m$th standard basis vector in $\\mathbb{R}^m$.  Writing the equation in this way shows how the result of Arnoldi's process proceeds at each step.\n\nIf the vectors $q_j, \\;j = 1, \\ldots, k$ are linearly independent then $h_{m+1,m} \\neq 0$.  If they are dependent, $h_{m+1,m} = 0$ and Eq. \\ref{eq:MatrixRep} becomes\n\\begin{subequations}\\begin{gather}\n    AQ_m = Q_mH_m \\\\\n    H_m = Q_m^{-1}AQ_m\n\\end{gather}\\end{subequations}\nand the Krylov space spanned by the columns of $Q$, $\\mathcal{K}_m(q,A)$, is invariant under $A$; that is for any vector $x \\in \\mathcal{K}_m$, $Ax$ is also in $\\mathcal{K}_m$.  It can be shown that the eigenvalues of $H_m$ are the eigenvalues of $A$ and the eigenvectors of $A$ are related to the eigenvectors of $H$ as\n\\begin{equation}\n    x = Q_mv\n\\end{equation}\nwhere $x$ is an eigenvector of $A$ and $v$ is the associated eigenvector of $H_m$.  \n\nIf carried out to completion, Arnoldi's method computes a similarity transform of the matrix $A$ to an upper Hessenberg matrix, $H$.  However, unless a very clever choice of the initial vector $q_1$ is used, one rarely finds an invariant subspace and must estimate the eigenvalues and eigenvectors of A from just a few steps of the Arnoldi process.\n\nWe can show that the eigenvalues of $H$ are estimates of the eigenvalues of $A$ with some residual error at any step of the Arnoldi process.  We begin by finding an eigenpair of $H$, $(\\mu,v)$.  If we multiply Eq. \\ref{eq:MRepmthIter} by $v$ we obtain\n\\begin{subequations}\\begin{gather}\n    AQ_mv = Q_{m}H_{m}v + q_{m+1}h_{m+1,m}e_m^Tv   \\\\\n    AQ_mv = \\mu Q_mv + q_{m+1}h_{m+1,m}e_m^Tv      \\\\[4mm]  \\label{eq:FullResidual}\n    Ax = \\mu x + r.\n\\end{gather}\\end{subequations}\nHere $x = Q_mv$ and $r = q_{m+1}h_{m+1,m}e_m^Tv$, the residual vector.  \n\nWe can quantify how close the eigenpair $(\\mu,x)$ is to a true eigenpair of $A$ by taking the 2-norm of the difference $Ax-\\mu x$\n\\begin{equation}\n    \\|Ax - \\mu x\\|_2 = |h_{m+1,m}||e_m^Tv|\n\\end{equation}\nwhere we have implicitly remembered $\\|q_{m+1}\\|_2 = 1$.  This difference is called the residual.  A small residual guarantees that $(\\mu, x)$ is an exact eigenpair of a matrix that is close to $A$ thus one can monitor the residual to determine convergence of the calculation.\n\n\\subsection{Restarted Arnoldi}\nPreviously I mentioned that unless a careful choice of the initial vector $q_1$ is made, one rarely finds an invariant subspace.  One can make a careful choice by taking a few Arnoldi iterations and use the estimated eigenvector as the initial vector for a new calculation.  This is how Arnoldi's method is restarted.  Arnoldi's method can be restarted many times, each time with a better estimate of the eigenvector.\n\nRestarting Arnoldi's method has several benefits including memory management and processing time of which I will not focus on at this time.  Performing restarts is a naive and simple way of duplicating the cycle in the power method.  The calculation of the eigenvalue and eigenvector after each restart can be compared to the eigenvalues and eigenvectors of the power method.  These eigenpairs can be evaluated to find their mean and variance, just like with the power method.  \n\n\\section{Questions to Answer}\n\\begin{enumerate}\n    \\item \\emph{What is the uncertainty?  Is the answer biased?}  This is the question of greatest import.  A Monte Carlo calculation is useless without some measure of its statistical uncertainty.  The easiest way to get this is to do restarted Arnoldi and find the mean and variance of of the eigenvalues and eigenvectors after each restart.  I think there is a better way.  There must also be some analysis of the bias (if one exists) in the answer.\n    \\item \\emph{Is there a better way to evaluate the inner product $\\langle q_k, q_j \\rangle$?}  We know the definition of the inner product\n    \\begin{equation}\n        \\langle q_k, q_j \\rangle \\equiv \\int q_j(x)q_k(x) dx.   \\label{eq:InnerProduct}\n    \\end{equation}\n    For vectors, this is a simple dot-product.  While this is simple, it requires biasing our results by spatial binning the fission source.  It should be possible to sample from a (semi-)continuous source distribution $q_j$ and finding the corresponding value from $q_k$\n    \\begin{equation}\n        \\langle q_k, q_j \\rangle  = \\frac{1}{N}\\sum_{i=1}^N q_k(x_i).\n    \\end{equation}\n    This is more of a Monte Carlo way of doing things and should reduce the bias in the calculation.\n    \\item \\emph{Beyond Histograms---Other Functional Expansions}  Our fission source vectors are histogram sources\n    \\begin{equation}\n        q(x) = \\sum_{i=1}^B a_if_i(x)\n    \\end{equation}\n    where $B$ is the number of spatial bins and\n    \\begin{equation}\n        f_i(x) = \\left \\{\n            \\begin{array}{ccc}\n                1 &,& x_{i} \\leq x < x_{i+1} \\\\\n                0 &,& \\mathrm{otherwise}\n            \\end{array}\\right. .\n    \\end{equation}\n    We can, however choose a different set of basis vectors, $f_i(x)$, about which we can expand. One choice to pursue is a linear inspace across each spatial bin, but I'm not going to show how this is done.\n\n\\end{enumerate}\n\n\\section{Tasks to Complete}\n\\begin{itemize}\n    \\item Heterogeneity\n    \\item Multi-dimensional\n\\end{itemize}\n\n\n\\end{document}\n", "meta": {"hexsha": "e8cdfaf6e6def9dd2b3de50e6d802e4a96c1bf1a", "size": 15299, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Prospectus1/Oral.tex", "max_stars_repo_name": "jlconlin/PhDThesis", "max_stars_repo_head_hexsha": "8e704613721a800ce1c59576e94f40fa6f7cd986", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Prospectus1/Oral.tex", "max_issues_repo_name": "jlconlin/PhDThesis", "max_issues_repo_head_hexsha": "8e704613721a800ce1c59576e94f40fa6f7cd986", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Prospectus1/Oral.tex", "max_forks_repo_name": "jlconlin/PhDThesis", "max_forks_repo_head_hexsha": "8e704613721a800ce1c59576e94f40fa6f7cd986", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 66.807860262, "max_line_length": 722, "alphanum_fraction": 0.7157984182, "num_tokens": 4578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.34646265258178166}}
{"text": "\\chapter{Synthesis in Example of a Magnetic Bearing on an Overhung Rotor}\\label{MagExample}\nAnalysis and modeling techniques of the previous chapters will now be put to use in a practical example. The goal of which will be to reduce vibration on an overhung disk rotor system with the use of an Active Magnetic Bearing(AMB). An experimental test rig, not unlike the system used in the experimental example of \\S\\ref{ExperimentalPlots}, will be used to calibrate a  finite element theoretical model. Then, the theoretical model will be extended to include an AMB near the overhung disk. The model will be evaluated for stability, and parameters of the control algorithm for the AMB will be varied to attempt to eliminate modes and stabilize the system.\n\\section{Physical System Description}\nThe rotor system of interest is depicted in Figure \\ref{fig:OverhungDiagram}. Geometric parameters are listed in Table \\ref{tab:GeometricParametersofOverhung}. The springs at nodes 1 \\& 4 are intended to represent bushings, portion at node 6 is the rotating disk, and nodal numbers are indications of how the rotor will be discretized for the finite element model.\n\\begin{figure}\n\t\\centering\n\t\\def\\svgwidth{250pt}\n\t\\import{figures/}{OverhungDiagram.pdf_tex}\n\t\\caption{Overhung rotor system diagram.}\n\t\\label{fig:OverhungDiagram}\n\\end{figure}\n\\begin{table}\n\t\\centering\n\t\\caption{Geometric parameters of the overhung rotor system.}\n\t\\label{tab:GeometricParametersofOverhung}\n\t\\begin{tabular}{cccccc}\n\t\t$ L[m] $&$ a[m] $&$ b[m] $&$ l_d[m] $&$ d_d[m] $&$ d_s[m] $\\\\\\hline\n\t\t$ 0.5 $&$ 0.23 $&$ 0.13 $&$ 0.025 $&$ 0.075 $&$ 0.01 $\n\t\t\\end{tabular}\n\\end{table}\n\\section{Experimental Results}\nThe rotor system was tested in a start-up from slow roll to $ 3000[RPM] $. Data shown here is taken from $ 1000[RPM] $ to $ 2000[RPM] $. A set of orthogonal eddy current position sensors placed near the disk on the outboard side were used to measure the position of the shaft throughout the start-up. Position data was recorded at a sampling rate of $ 128000[Hz] $ with no processing applied, this sampling rate is much higher than the required rate to avoid aliasing. The resulting 3D orbit of the start-up is shown in Figure \\ref{fig:MagExampleOrbit3D}. Of note is the necking in the 3D orbit during the natural frequency that is indicative of high anisotropy inducing a negative whirl during the first natural frequency. Also resulting from the experiment is the full spectrum cascade plot of Figure \\ref{fig:MagExampleCascade}, in which it is evident that synchronous vibration dominates the spectra. Though, for the production of the bode diagram (Figure \\ref{fig:MagExampleBode}) there was a benefit in clarity from filtering the data to synchronous speed.\n\\begin{figure}\n\t\\centering\n\t\\includegraphics[width=.5\\linewidth]{./figures/MagExpExampleOrbit3D.png}\n\t\\caption{3D Orbit of the experimental overhung rotor system.}\n\t\\label{fig:MagExampleOrbit3D}\n\\end{figure}\n\\begin{figure}\n\t\\centering\n\t\\includegraphics[width=.8\\linewidth]{./figures/MagExampleCascade.png}\n\t\\caption{Cascade of the experimental overhung rotor system.}\n\t\\label{fig:MagExampleCascade}\n\\end{figure}\n\\begin{figure}[!htb]\n\t\\def\\width{.7\\linewidth}\n\t\\def\\height{.4\\linewidth}\n\t\\def\\sep{3em}\n\t\\pgfplotsset{every picture/.style={trim axis left, trim axis right}, every axis/.style={ylabel style={xshift=0},xlabel style={yshift=0}}}%, every axis/.style={hide axis}}%\n\t\\centering\n\t\\import{}{./figures/MagExampleBode.tex}\n\t\\caption{Bode diagram of the experimental overhung rotor filtered to 1X.}\n\t\\label{fig:MagExampleBode}\n\\end{figure}\n\\section{Theoretical Model}\nTo create a finite element model for this rotor system the shaft will be discretized into 7 elements a disk at node 6 and bearings at nodes 1 and 4, as depicted in Figure \\ref{fig:OverhungDiagram}. In the experiment, a small length of shaft continued after the overhung disk and has been included in this model. The AMB will be included as a nodal point element with with stiffness and damping to be derived in \\S\\ref{Active Magnetic Bearing}. Parameter values for the finite element model are provided in Table \\ref{tab:OverhungParameters}. Discovered values such as $ \\eta_v $ and the stiffnesses of bearing are listed here, but the process for their determination is discussed.\n\\begin{table}\n\t\\caption{Properties of disks, shaft elements, and bearings of the theoretical model.} \\label{tab:MagTheoryRotorTable}\n\t\\centering\n\t\\label{tab:OverhungParameters}\n\t\\begin{tabular}{rcccccc}\n\t\t\t\t\t\t\t&$\\rho\\left[\\frac{kg}{m^3}\\right]$\t&$r[m]$\t\t\t\t\t&$\\nu$\t\t\t\t&$E[Pa]$\t\t\t&$ \\eta_v[s] $\t&$ \\eta_h $\t\\\\\\hline\n\t\t\\textbf{Shaft}\t\t&$7850$\t\t\t\t\t&$0.005$\t\t\t\t&$0.3$\t\t\t\t&$\\num{210E9}$\t\t&$ 0.0002 $\t\t&$ 0 $\t\t\\\\[-.2em]\n\t\t\t\t\t\t\t&$\\rho\\left[\\frac{kg}{m^3}\\right]$\t&$r[m]$\t\t\t\t\t&$l[m]$\t\t\t\t&\t\t\t\t\t&\t\t\t\t&\t\t\t\\\\\\hline\n\t\t\\textbf{Disks}\t\t&$7850$\t\t\t\t\t&$0.0375$\t\t\t\t&$0.025$\t\t\t&\t\t\t\t\t&\t\t\t\t&\t\t\t\\\\[-.2em]\n\t\t\t\t\t\t\t&$k_y\\left[\\frac{N}{m}\\right]$\t\t&$k_z\\left[\\frac{N}{m}\\right]$\t\t&$c_y\\left[\\frac{Ns}{m}\\right]$&$c_z\\left[\\frac{Ns}{m}\\right]$&\t\t\t\t&\t\t\t\\\\\\hline\n\t\t\\textbf{Bearing A}\t&$1.7\\e{5}$\t\t\t\t&$2.2\\e{5}$\t\t\t\t&$68$\t\t\t\t&$88$\t\t\t\t&\t\t\t\t&\t\t\t\\\\[-.5em]\n\t\t\\textbf{Bearing B}\t&$2.04\\e{5}$\t\t\t&$2.64\\e{5}$\t\t\t&$81.6$\t\t\t\t&$105.6$\t\t\t&\t\t\t\t&\t\t\t\\\\\n\t\\end{tabular}\n\\end{table}\nFirst the model is formed to match the experimental results. Known parameters, such as beam lengths, beam diameters, density of the material, and geometry of the disk and rotor are used to begin construction of the model. Then, guesses are made for the stiffnesses in the rotor bearings. The first natural frequency is calculated with the resulting model and its value compared to the experimentally found natural frequency from the bode diagram (fig.\\ref{fig:MagExampleBode}). Stiffness are then adjusted to better match the natural frequency, and this is repeated until the natural frequency of the model matches the experiment. After this process, the stiffness was determined to be around $ 2\\e{5} \\left[\\frac{N}{m}\\right]$.\\par\nIt is evident by inspection of the Bode diagram for the experimental system (fig.\\ref{fig:MagExampleBode}), and the 3D orbit, that there is anisotropy in the system, leading to the dip in amplitude of one plane of vibration. It is also known from inspection of the frequency spectrum in the cascade of figure \\ref{fig:MagExampleCascade} that in this speed range the orbit is in the opposite direction of the rotation--a phenomena only possible with anisotropy of the stiffness. Figures \\ref{fig:HorVertStiffAniCompare} \\& \\ref{fig:PosNegStiffAniCompare} demonstrate this affect anisotropy has on both the real coordinates, as well as positive and negative whirl amplitudes. In the real coordinates, cross coupling of from gyroscopic moments causes an interaction of the two peaks in amplitude. As the stiffness anisotropy approaches a value of 1, the vibration of the more flexible plane will split into two peaks. One peak coinciding with that planes natural frequency and one plane coinciding with the orthogonal natural frequency. During this change in anisotropy of stiffness, the peaks of both positive and negative amplitude spectrums split to coincide with either plane's natural frequency. When the two orthogonal planes have widely separated natural frequencies, the negative amplitude spectrum is greater than the positive amplitude spectrum for the range of speed between the two natural frequencies. \\par \n\\begin{figure}\n\\begin{subfigure}{\\textwidth/2}\n\t\\centering\n\t\\includegraphics[width=\\linewidth]{./figures/MagExampleHorVertStiffAniCompare.png}\n\t\\caption{Comparison of v \\& w as stiffness anisotropy is changed.}\n\t\\label{fig:HorVertStiffAniCompare}\n\\end{subfigure}\n\\begin{subfigure}{\\textwidth/2}\n\t\\centering\n\t\\includegraphics[width=\\linewidth]{./figures/MagExamplePosNegStiffAniCompare.png}\n\t\\caption{Comparison of positive and negative orbit amplitudes as stiffness anisotropy is changed.}\n\t\\label{fig:PosNegStiffAniCompare}\n\\end{subfigure}\n\\end{figure}\nUsing the bode diagram, the stiffness anisotropy is adjusted until the shapes of the amplitudes and phases match the experimental results of figure \\ref{fig:ExpExampleBode}. Then damping is added to the system to appropriately match the experimental results. The resulting bode diagram is Figure \\ref{fig:MagTheoryBode}. Stiffnesses were determined to be $ k_y=1.7\\e{5}[N/m]\\ \\&\\ k_z=2.2\\e{5}[N/m] $.\n\\begin{figure}[!htb]\n\t\\def\\width{.6\\linewidth}\n\t\\def\\height{.4\\linewidth}\n\t\\def\\sep{3em}\n\t\\pgfplotsset{every picture/.style={trim axis left, trim axis right}, every axis/.style={ylabel style={yshift=.5em},xlabel style={yshift=0}},\n\tevery axis plot/.style={line width=1.4pt}}%, every axis/.style={hide axis}}%\n\t\\centering\n\t\\import{figures/}{MagTheoryBode.tex}\n\t\\caption{Bode Diagram of overhung system without AMB.}\n\t\\label{fig:MagTheoryBode}\n\\end{figure}\nAnd now the resulting system is further described with an expanded speed range of $ 20000[RPM] $. This resulting model is described with the new Campbell diagram of Figure \\ref{fig:MagTheoryCampbell}, the roots locus of Figure \\ref{fig:MagTheoryRootLocus}, and the first three mode shapes (Figures \\ref{fig:MagTheoryShape1}, \\ref{fig:MagTheoryShape2}, \\& \\ref{fig:MagTheoryShape3}). Note that the first mode is conical in shape, but the disk is far from an antinode at node 6 so it does not experience significant gyroscopic moments. This idea is supported by the campbell diagram, fig. \\ref{fig:MagTheoryCampbell}, as the first mode natural frequency does not change significantly over the speed range. On the other hand, the second mode has its antinode atode 6 so the disk experience maximum gyroscopic moments and the second mode critical speed is much more dependent on speed.\n\\begin{figure}[!htb]\n\t\\def\\width{.6\\linewidth}\n\t\\def\\height{.4\\linewidth}\n\t\\def\\sep{3em}\n\t\\pgfplotsset{every picture/.style={trim axis left, trim axis right}, every axis/.style={ylabel style={yshift=.5em},xlabel style={yshift=0}},\n\tevery axis plot/.style={line width=1.4pt}}%, every axis/.style={hide axis}}%\n\t\\centering\n\t\\import{figures/}{MagTheoryCampbell.tex}\n\t\\caption{Campbell Diagram of the overhung system without AMB.}\n\t\\label{fig:MagTheoryCampbell}\n\\end{figure}\n\\begin{figure}[!htb]\n\t\\def\\width{.6\\linewidth}\n\t\\def\\height{.4\\linewidth}\n\t\\def\\sep{3em}\n\t\\pgfplotsset{every picture/.style={trim axis left, trim axis right}, every axis/.style={ylabel style={yshift=.0},xlabel style={yshift=0}},\n\tevery axis plot/.style={line width=1.4pt}}%, every axis/.style={hide axis}}%\n\t\\centering\n\t\\import{}{./figures/MagExampleRootsLocus.tex}\n\t\\caption{Roots Locus of overhung system without AMB.}\n\t\\label{fig:MagTheoryRootLocus}\n\\end{figure}\n\\begin{figure}\n\t\\def\\cs{.29}\n\t\\pgfplotsset{every picture/.style={trim axis left, trim axis right}, every axis/.style={yticklabel style={xshift=0,yshift=0},minor tick num=2}, grid style={line width=.1pt, draw=gray!20},major grid style={line width=.2pt,draw=gray!50},ticks=none,minor tick style={draw=none},\tevery axis plot/.style={line width=.9pt},}%, every axis/.style={hide axis}}% \n\t\\begin{subfigure}{\\cs\\textwidth}\n\t\t\\centering\n\t\t\\def\\width{\\linewidth}\n\t\t\\def\\height{\\linewidth}\n\t\t\\import{}{./figures/MagTheoryShape1.tex}\n\t\t\\caption{Mode Shape 1.}\n\t\t\\label{fig:MagTheoryShape1}\n\t\\end{subfigure}\n\t\\begin{subfigure}{\\cs\\textwidth}\n\t\t\\centering\n\t\t\\def\\width{\\linewidth}\n\t\t\\def\\height{\\linewidth}\n\t\t\\import{figures/}{MagTheoryShape2.tex}\n\t\t\\caption{Mode Shape 2.}\n\t\t\\label{fig:MagTheoryShape2}\n\t\\end{subfigure}\n\t\\begin{subfigure}{\\cs\\textwidth}\n\t\t\\centering\n\t\t\\def\\width{\\linewidth}\n\t\t\\def\\height{\\linewidth}\n\t\t\\import{}{./figures/MagTheoryShape3.tex}\n\t\t\\caption{Mode Shape 3.}\n\t\t\\label{fig:MagTheoryShape3}\n\t\\end{subfigure}\n\\end{figure}\n\\subsection{Active Magnetic Bearing}\\label{Active Magnetic Bearing}\nMagnetic pole-rotor relationship will be derived based on the detailed derivation in \\cite{das2008vibration}, with influence from \\cite{childs1993turbomachinery}. Assumptions made in this model are as follows:\n\\begin{itemize}\n\t\\item Air gap between the magnet pole face and the rotor is vanishingly small compared to the diameter of the shaft.\\\n\t\\item Flux leakage from the magnetic pole is negligible.\n\t\\item Curvature of rotor surface under the pole face is ignored.\n\t\\item A linear relationship of flux density and magnetic field is assumed.\n\t\\item Hysteresis of the magnetic field is negligible.\n\\end{itemize}\nThese assumptions lead to a magnetic force due to coil current in the relationship of\n\\begin{equation}\\label{key}\nF_m=\\frac{-k_mi^2}{l_g^2}\n\\end{equation}\nwhere, $ k_m=\\frac{\\mu_0A_pN^2}{4} $, and $ \\mu_0=4\\pi\\e{-7} $ is the absolute permeability in free air, $ N $ is the number of coil turns, $ A_p $ is the pole face area, $ i $ is the supplied electrical current, and $ l_g $ is the air gap.\\par \nConsider a set of magnetic pole pairs in each the $ y\\ \\&\\ z $ directions (i.e. One on the left and one on the right; one on top and one on bottom), where each pole pair has its own electrical circuit. There are four total magnets in this model, two in each direction, and eight total poles where two form a magnet. All poles in the neutral position of the system will have a nominal air gap of $ g_0 $ and will be supplied by a bias current of $ i_0 $. Deviations of the current from this bias will be considered as $ i_y $ and $ i_z $. Deviations of the position from this neutral position are the displacements of the rotor at this beam axis location, $ v,\\ \\&\\ w $. Therefore, total current will be $ (i_0\\pm i_y)\\ \\&\\ (i_0\\pm i_z) $ for opposing poles in the $ y\\ \\&\\ z $ directions respectively. Similarly, total gaps are given by $ (g_0\\pm v)\\ \\&\\ (g_0\\pm w) $. Using these new definitions for the gap and current, and summing forces in the $ y\\ \\&\\ z $ directions leads to the total forces\n\\begin{equation}\\label{eq:MagneticForceNL}\nF_y=K_m\\left\\{\\left(\\frac{i_0+i_y}{g_0+v}\\right)^2-\\left(\\frac{i_0-i_y}{g_0-v}\\right)^2\\right\\}\\ \\&\\ F_z=K_m\\left\\{\\left(\\frac{i_0+i_z}{g_0+w}\\right)^2-\\left(\\frac{i_0-i_z}{g_0-w}\\right)^2\\right\\}\n\\end{equation}\nwhere, $ K_m=k_m\\cos(\\alpha) $, and $ \\alpha $ is half of the angle between the poles of a magnet. Linearizing the magnetic force equations \\eqref{eq:MagneticForceNL}, while assuming the operating point for the system is where all positions and control currents are zero, results in\n\\begin{equation}\\label{eq:MagneticForce}\nF_y=k_ii_y+k_yv,\\ \\&\\ F_z=k_ii_z+k_zw\n\\end{equation}\nwhere, $ k_i=4K_m\\frac{i_0}{g_0^2} $ is the current stiffness developed by the bias current, and $ k_y=k_z=k_s=-4K_m\\frac{i_0^2}{g_0^3} $.\n\\subsubsection{Proportional Derivative Control}\nA control algorithm is used to control the current sent to each pair of poles based on the position (proportional) and velocity (derivative) of the rotor. It is assumed that each set of pole pairs will receive opposite currents to act as a unit. Current control is given by \n\\begin{equation}\\label{eq:ControlCurrent}\ni_y=-k_g(k_pv+k_v\\dot{v}),\\ \\&\\ i_z=-k_g(k_pw+k_v\\dot{w})\n\\end{equation}\nwhere, $ k_g $ is the power amplifier gain, $ k_p $ is the proportional gain, and $ k_v $ is the derivative gain. The total linearized force becomes\n\\begin{equation}\\label{key}\nF_y=-(k_gk_ik_p-k_s)v-k_gk_ik_v\\dot{v},\\ \\&\\ F_z=-(k_gk_ik_p-k_s)w-k_gk_ik_v\\dot{w}\n\\end{equation}\nso then the stiffness of the AMB is $ k_{mag}=(k_gk_ik_p-k_s) $ and the damping is $ d_{mag}=k_gk_ik_v $. As an equation of nodal stiffness and damping in the finite element system it can be represented by\n\\begin{equation}\\label{eq:DiskNodeEquationofMotion}\n\\bunderline{\\mathbf{D}}^m\\dot{\\vec{\\mathbf{q}}}_k+\\bunderline{\\mathbf{K}}^m\\vec{\\mathbf{q}}_k=0\n\\end{equation}\nwhere,\n\\begin{equation*}\n\\def\\cs{2em}\n\\begin{array}{cc}\n\\bunderline{\\mathbf{K}}^m=\\left[\\def\\arraystretch{.8}\\arraycolsep=0pt\\begin{array}{cccccc}\n\\makebox[\\cs]{$k_{mag}$}&\\makebox[\\cs]{0}&\\makebox[\\cs]{0}&\\makebox[\\cs]{0}&\\makebox[\\cs]{0}&\\makebox[\\cs]{0}\\\\\n0&k_{mag}&0&0&0&0\\\\\n0&0&0&0&0&0\\\\\n0&0&0&0&0&0\\\\\n0&0&0&0&0&0\\\\\n0&0&0&0&0&0\n\\end{array}\\right] & \\bunderline{\\mathbf{D}}^m=\\left[\\def\\arraystretch{.8}\\arraycolsep=0pt\\begin{array}{cccccc}\n\\makebox[\\cs]{$d_{mag}$}&\\makebox[\\cs]{0}&\\makebox[\\cs]{0}&\\makebox[\\cs]{0}&\\makebox[\\cs]{0}&\\makebox[\\cs]{0}\\\\\n0&d_{mag}&0&0&0&0\\\\\n0&0&0&0&0&0\\\\\n0&0&0&0&0&0\\\\\n0&0&0&0&0&0\\\\\n0&0&0&0&0&0\n\\end{array}\\right]\n\\end{array}\n\\end{equation*}\n\n\\section{Addition of Magnetic Bearing to the Rotor Model}\nIn order to measure the effectiveness of the AMB, the Stability of the theoretical model before the addition is shown in Figure \\ref{fig:MagTheoryStability}. The magnetic bearing added is modeled after a magnetic bearing that is currently in the lab at California Polytechnic State University. This theoretical exercise is intended to be followed by experimental verification not included in this work. The parameters used are listed in \\ref{tab:MagBearingParameters} as well as the control values whose determinations will be evaluated.\\par \nFirst the axial position of the AMB must be determined. By inspection of the mode shapes, it is evident that in the first mode (the mode we are most concerned about suppressing) a shape exists with increasing amplitude toward the end of the beam after the second bearing. It is also known that the source of vibration, the rotating disk, is located at nodal index six. With both these pieces of information, node seven is chosen as a starting point for the AMB for two reasons: having the AMB closer to the source of vibration reduces the phase lag between the source and the bearing, increasing the effectiveness of control; amplitude of vibration, according to the mode shape, is higher on the outboard side of the disk and placing the AMB on this side will minimize more vibration. Additionally, this location should significantly suppress the second mode of vibration as node seven is near the maximum amplitude of that mode as well.\\par \nIn order to choose a value for bias current, $ i_b $, and provide upper range estimates of the controller outputs, $ k_v,\\ \\&\\ k_p $, the maximum expected current output of the control loop must be determined. $ i_b $ will be set so that under peak power output, in the expected speed range, the control current will push the total current output beyond the system limits.\\par \nKnowing that the amplitude of vibration, $ A $, in the experimental system peaks at about 10 mils, or $ 2.54\\e{-4}[m] $, the greatest possible velocity for synchronous vibration is determined using the simple equation $ vel=(A/2)\\omega $, where $ \\omega $ is the whirl speed in rad/s. Under the assumption of synchronous vibration, $ \\omega $ during the natural frequency is then $ 167.6[Rad/s] $. Leading to a velocity, $ vel $, of $ 0.02[m/s] $. Also, another possible peak velocity occurs in the upper speed range. Knowing that the amplitude of vibration after the first natural frequency is equal to the eccentricity of the unbalance, with an eccentricity of $ 1\\e{-5} $, and an upper speed of $ 15000[RPM] $, the velocity is calulated to be $ 0.008[m/s] $. Since the estimated velocity during the natural frequency is higher, it will be used to limit the output of the AMB controller. Total voltage supply of most digital to analog converters is limited to $ 10[V] $. So the control voltage is calculated to be within this range for the given velocity and positions that will be seen under synchronous vibration. This results in a limitation of the term $ k_v $, which is proportional to the voltage control signal that is sent to the amplifier for conversion to control current. A value of $ 480[Vs/m] $ would max the converter, so the value to be determined must be less than this. With a similar, but separate, evaluation of the displacement leads to a maximum allowable value of $ 500000[V/m] $ for $ k_p $--a value not anticipated to be necessary. The maximum force due to unbalance is $ \\epsilon m_d\\Omega^2 $, where $ \\epsilon $ is the eccentricity, and $ m_d $ is the mass of the disk. At the maximum speed expected of $ 15000[RPM] $, the force will be $ 24[N] $. To counteract this force with a single coil would require $ 1.25[A] $, or $ 0.625[A] $ per coil in a opposing pair. The amplifier gain is assumed to be programmable to $ k_g=1[A/V] $, this leads to a reasonable choice of bias current at $ 0.5[A] $ to maintain a good resolution on the voltage output of the controller. Under the operating conditions described, the control voltage should not exceed $ 1.25[V] $, and will rest at an output of $ 0.5[V] $. Now in the next section, control parameters $ k_v\\ \\&\\ k_p $ will be determined to maximize stability of the system while also minimizing vibration.\\par\n To determine best derivative control constant ($ k_v $), the proportional control constant ($ k_p $) was set to zero. $ k_v $ is increased until the first mode on the Roots locus(fig. \\ref{fig:MagTheoryRootLocus}) moves away from the imaginary axis, becoming more damped. The resulting movement of the Roots on the Roots Locus is given in Figure \\ref{fig:MagTheoryRootLocusControllerTune}. Note that because of bias current flowing through the bearing, a baseline stiffness of $ k_S $ is present in the system even withou $ k_p $. None of the modes that appear on the roots locus of the system with $ k_p=0,\\ \\&\\ k_v=10[\\frac{Vm}{s}] $ control algorithm cross the real plane--this demonstrates the stability of the new system. Stability of the system with the AMB addition is confirmed in the stability plot of Figure \\ref{fig:MagTheoryStabilityWith}. In fact from the roots locus with $ k_v=1 $ to the roots locus with $ k_v=10 $ the first mode of vibration is completely relegated to the imaginary axis and not reaching break-away for this entire speed range--this indicates that the first mode has been over-damped. With additional damping through the increase of $ k_v $ it would be possible to over-damp the second mode as well, but in the speed range given, it would not improve the performance.\\par \n Proportional control, $ k_p $, was added after the ideal derivative control was determined, but it did not improve the performance of the controller. It is the case that the stiffness of the bearing inherent to the bias current is sufficient. In any case, proportional control in this scenario is only adding stiffness to the system, and with the objective being to minimize vibration, $ k_p $ is not effective. So the optimal control is determined to be with $ k_p=0,\\ \\&\\ k_v=10[Vs/m] $. The remaining parameters for this resulting controller are listed in table \\ref{tab:MagBearingParameters}. It is worthwhile to note that this optimal control is standing on the basis that the feedback is of synchronous vibration only. In a scenario where there is significant sub or super-synchronous vibrations, this controller may exceed its voltage limit. It is recommended that the feedback signal be filtered to match rotor speed to ensure this scenario does not take place. Furthermore, without at least low-pass filtering of the feedback signal the control would certainly provide out of range signals due to the volatile nature of derivatives of discrete signals.\\par \n The frequency spectrum is provided showing the result of the AMB application in the bode diagram of Figure \\ref{fig:MagTheoryBodeCompare}. Certainly it can be concluded that the AMB is successfully performing the desired task of reducing the vibration while also inproving the stability of the system.\\par \nThe result from this synthesis exercise can be implemented on the actual experimental test rig with the AMB set to the control parameters suggested. The power of the finite element method in this application is the ability to move components around with ease. For instance, with the changing of just two parmeters in the input file for this model, a new simulation is created for complete levitation of the overhung rotor. The AMB is put in place of bearing b and the resulting frequency spectrum is plotted in Figure \\ref{fig:MagLevTheoryBodeCompare}\n\\begin{table}\n\t\\centering\n\t\\caption{Active Magnetic Bearing Parameters.}\n\t\\begin{tabular}{cccccccc}\n\t\t$\\alpha[rad]$&$g_0[m]$&$i_0[A]$&$k_p[\\frac{V}{m}]$&$k_v[\\frac{Vs}{m}]$&$k_g[\\frac{A}{V}]$&$ N[\\#]$&$A_p[m^2]$\\\\\\hline\n\t\t$\\frac{\\pi}{8}$&$2.5\\e{-3}$&$0.5$&$0$&$10$&$1$&$800$&$\\frac{5}{100*100}$\n\t\\end{tabular}\n\t\\label{tab:MagBearingParameters}\n\\end{table}\n\\begin{figure}\n\t\\begin{subfigure}{\\textwidth/2}\n\t\t\\def\\width{.8\\linewidth}\n\t\t\\def\\height{.4\\linewidth}\n\t\t\\pgfplotsset{every picture/.style={trim axis left, trim axis right}, every axis/.style={ylabel style={yshift=-20},xlabel style={yshift=35}},every x tick scale label/.style={at={(xticklabel* cs:1,.3cm)},anchor=near xticklabel},every axis plot/.style={line width=1.4pt}}%, every axis/.style={hide axis}}%\n\t\t\\centering\n\t\t\\import{figures/}{MagTheoryStability.tex}\n\t\t\\caption{Stability plot of rotor without AMB, threshold of stability:$ \\ 4646[RPM] $.}\n\t\t\\label{fig:MagTheoryStability}\n\t\\end{subfigure}\n\t\\begin{subfigure}{\\textwidth/2}\n\t\t\\def\\width{.8\\linewidth}\n\t\t\\def\\height{.35\\linewidth}\n\t\t\\pgfplotsset{every picture/.style={trim axis left, trim axis right}, every axis/.style={xlabel style={yshift=-2em},xlabel style={yshift=25,at={(axis description cs:0.5,1.05)},anchor=north}},every x tick scale label/.style={at={(xticklabel* cs:1,.3cm)},anchor=near xticklabel},every axis plot/.style={line width=1.4pt}}%, every axis/.style={hide axis}}%\n\t\t\\centering\n\t\t\\import{figures/}{MagTheoryStabilityWith.tex}\n\t\t\\caption{Stability plot of rotor with AMB, indicates complete stability through speed range.}\n\t\t\\label{fig:MagTheoryStabilityWith}\n\t\\end{subfigure}\n\\end{figure}\n\\begin{figure}[!htb]\n\t\\def\\width{.7\\linewidth}\n\t\\def\\height{.5\\linewidth}\n\t\\def\\sep{3em}\n\t\\pgfplotsset{every picture/.style={trim axis left, trim axis right},every axis plot/.style={line width=1.4pt}}%, every axis/.style={ylabel style={yshift=0em},xlabel style={yshift=0}}}%, every axis/.style={hide axis}}%\n\t\\centering\n\t\\import{figures/}{MagTheoryRootLocusControllerTune.tex}\n\t\\caption{Roots locus of Overhung rotor system with varying $ k_v $.}\n\t\\label{fig:MagTheoryRootLocusControllerTune}\n\\end{figure}\n\\begin{figure}[!htb]\n\t\\def\\width{.6\\linewidth}\n\t\\def\\height{.4\\linewidth}\n\t\\def\\sep{3em}\n\t\\pgfplotsset{every picture/.style={trim axis left, trim axis right},every axis plot/.style={line width=1.3pt}}%, every axis/.style={ylabel style={yshift=0em},xlabel style={yshift=0}}}%, every axis/.style={hide axis}}%\n\t\\centering\n\t\\import{figures/}{MagTheoryBodeCompare.tex}\n\t\\caption{Bode diagram at node 6 comparing the rotor without AMB(solid) and with AMB(dashed).}\n\t\\label{fig:MagTheoryBodeCompare}\n\\end{figure}\n\\begin{figure}[!htb]\n\t\\def\\width{.6\\linewidth}\n\t\\def\\height{.4\\linewidth}\n\t\\def\\sep{3em}\n\t\\pgfplotsset{every picture/.style={trim axis left, trim axis right},every axis plot/.style={line width=1.3pt}}%, every axis/.style={ylabel style={yshift=0em},xlabel style={yshift=0}}}%, every axis/.style={hide axis}}%\n\t\\centering\n\t\\import{figures/}{MagLevTheoryBodeCompare.tex}\n\t\\caption{Bode diagram at node 6 comparing the rotor without AMB(solid) and with AMB(dashed) for complete levitation at node 4.}\n\t\\label{fig:MagLevTheoryBodeCompare}\n\\end{figure}", "meta": {"hexsha": "ba8ab1d238062b89c8ce2c220f84f35fa9580f33", "size": 27081, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/MagExample.tex", "max_stars_repo_name": "cameron1320/Cameron", "max_stars_repo_head_hexsha": "276144ab299ab00f102f3f3cc0869261a13e0059", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/MagExample.tex", "max_issues_repo_name": "cameron1320/Cameron", "max_issues_repo_head_hexsha": "276144ab299ab00f102f3f3cc0869261a13e0059", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/MagExample.tex", "max_forks_repo_name": "cameron1320/Cameron", "max_forks_repo_head_hexsha": "276144ab299ab00f102f3f3cc0869261a13e0059", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 102.1924528302, "max_line_length": 2383, "alphanum_fraction": 0.7535172261, "num_tokens": 7797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736783928749127, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.34646264377790675}}
{"text": "% !TEX root = ../zeth-protocol-specification.tex\n\n\\section{Processing $\\zethTx$}\\label{zeth-protocol:process-tx}\n\nWhen a $\\zethTx$ is mined (hence assuming that $\\ethVerifyTx(\\zethTx)$ returns $\\true$), the state transition specified by the $\\mix$ function of $\\mixer$ is executed.\n\nTo preserve the soundness of \\zeth, and make sure that no $\\zparty{U}$ is able to create value by double spending $\\zethnotes$, various checks need to be satisfied. The function $\\zethVerifyTx$ is defined as the function that returns $\\true$ if all the checks are satisfied, and $\\false$ otherwise.\n\nIf $\\zethVerifyTx(\\zethTx)$ returns $\\true$, then $\\mix$ modifies the ``World state'' $\\wstate$ to account for the spent $\\zethnotes$ and the newly generated ones. However, if $\\zethVerifyTx(\\zethTx)$ returns $\\false$, then the state transition ends.\n\n\\begin{notebox}\n    Even if $\\zethVerifyTx(\\zethTx)$ returns $\\false$, $\\wstate$ is modified since the \\ethereum~balances of the transaction originator is decremented by the sum of $\\txDefaultGas$ and the gas consumed by the $\\zethVerifyTx$ function, and the balance of the \\ethereum~account of the miner gets incremented by the same amount.\n\\end{notebox}\n\nThus, $\\mix$ proceeds as follows:\n\\begin{enumerate}\n    \\item Check that all the values of the primary inputs' ($\\inp{\\mix}.\\primInp$) entries are elements of the scalar field over which the zk-proof is generated:\n        \\[\n            \\inp{\\mix}.\\primInp \\in \\FFx{\\rCURVE}^*\n        \\]\n    \\item Unpack the nullifiers, signature hash and public values (see~\\cref{instantiation:statement:pack} for the definitions of the $\\unpack{}{}$ functions):\n        \\begin{align*}\n            \\nf{i} &= \\unpack{\\inp{\\mix}.\\primInp.\\nfs{i}, \\inp{\\mix}.\\primInp.\\resbits}{\\nf{}}\\ \\forall i \\in [\\jsin] \\\\\n            \\vin &= \\decode{\\unpack{(), \\inp{\\mix}.\\primInp.\\resbits}{\\vin}}{\\NN} \\\\\n            \\vout &= \\decode{\\unpack{(), \\inp{\\mix}.\\primInp.\\resbits}{\\vout}}{\\NN} \\\\\n            \\hsig &= \\unpack{\\inp{\\mix}.\\primInp.\\hsig, \\inp{\\mix}.\\primInp.\\resbits}{\\hsig}\n        \\end{align*}\n    \\item Check the validity of the $\\zethTx$ object ($\\zethVerifyTx$):\n        \\begin{enumerate}\n            \\item Check that $\\inp{\\mix}.\\primInp.\\hsig$ is correctly computed, i.e.~check that the following equation holds (to prevent transaction malleability, see~\\cref{appendix:trnm}):\n                \\[\n                    \\hsig = \\crhhsig{\\inp{\\mix}.\\primInp.\\nfs{}, \\inp{\\mix}.\\otsvk}\n                \\]\n            \\item\\label{zeth-protocol:process-tx:verify-zkp} Check that $\\zkp$ is a valid zk-SNARK proof for $\\inp{\\mix}.\\primInp$, i.e.~check that:\n                \\[\n                    \\zksnark.\\verifier(\\pparams_{\\zksnark}, \\zkp, \\inp{\\mix}.\\primInp) = \\true\n                \\]\n            \\item Check that none of the nullifiers in $\\inp{\\mix}.\\primInp.\\nfs{}$ have already been used, i.e.~check that:\n                \\[\n                    \\nf{i} \\not\\in \\nullifierset, \\forall i \\in [\\jsin]\n                \\]\n                where $\\nullifierset$ is the set of all nullifiers that are ``declared'' on $\\mixer$.\n            \\item\\label{zeth-protocol:process-tx:check-otsig} Check that $\\inp{\\mix}.\\otssig$ is a valid signature of the $\\ethereum{}$ sender's address $\\addr$ (see~\\cref{zeth-protocol:create-tx}) and the attributes of $\\inp{\\mix}$, to prevent transaction malleability (see~\\cref{appendix:trnm}), i.e.~check that:\n                \\begin{align*}\n                    & \\otsigscheme.\\verify(\\inp{\\mix}.\\otsvk, \\msg, \\inp{\\mix}.\\otssig) = \\true \\\\\n                    & \\text{where} \\ \\datatobesigned = \\addr \\concat \\inp{\\mix}.\\primInp \\concat \\inp{\\mix}.\\zkp \\concat \\inp{\\mix}.\\ciphers, \\\\\n                    & \\text{and} \\ \\msg = \\crhots{\\datatobesigned}\n                \\end{align*}\n            \\item Check that $\\inp{\\mix}.\\primInp.\\mkroot$ corresponds to a valid state of the Merkle tree held on $\\mixer$, i.e.~check that:\n                \\[\n                    \\inp{\\mix}.\\primInp.\\mkroot \\in \\rootset'\n                \\]\n                where $\\rootset'$ is the set of all Merkle roots corresponding to one of the states of the Merkle tree.\n            \\item Check that $\\vin$ corresponds to the value $\\val$ of the transaction object, i.e.~check that:\n                \\[\n                    \\vin = \\zethTx.\\val\n                \\]\n        \\end{enumerate}\n    \\item If all checks above pass, i.e.~if $\\zethVerifyTx(\\zethTx)$ returns $\\true$, then the following additional modifications are made in $\\wstate$:\n        \\begin{enumerate}\n            \\item Add the commitments $\\inp{\\mix}.\\primInp.\\cms{}$ to the Merkle tree held on $\\mixer$.\n            \\item $\\rootset' \\gets \\rootset' \\cup \\smallset{\\mkroot'}$, where $\\mkroot'$ is the Merkle root of the Merkle tree after insertion of the commitments $\\inp{\\mix}.\\primInp.\\cms{}$ in the Merkle tree.\n            \\item $\\nullifierset \\gets \\nullifierset \\cup \\indexedset{\\nf{i}}{i \\in [\\jsin]}$, i.e.~the nullifiers $\\nfs{}$ become ``declared''.\n            \\item Modify the \\ethereum~balances according to the public values:\n                \\begin{itemize}\n                    \\item $\\wstate[\\eparty{S}.\\addr].\\balance = \\wstate[\\eparty{S}.\\addr].\\balance - \\vin$\n                    \\item $\\wstate[\\eparty{S}.\\addr].\\balance = \\wstate[\\eparty{S}.\\addr].\\balance + \\vout$\n                    \\item $\\mixer.\\balance = \\mixer.\\balance + \\vin$\n                    \\item $\\mixer.\\balance = \\mixer.\\balance - \\vout$\n                \\end{itemize}\n            \\item Emit an event (\\cref{sssec:ethereum-events}) $\\evMixOut$ of type \\mixEventDType, containing the new root $\\mkroot'$ of the Merkle tree of commitments, the nullifiers $\\indexedset{\\nf{i}}{i \\in [\\jsin]}$, commitments to the newly created \\zethnotes $\\inp{\\mix}.\\primInp.\\cms{}$, and the corresponding ciphertexts $\\inp{\\mix}.\\primInp.\\ciphers$.\n        \\end{enumerate}\n\\end{enumerate}\n\n\\begin{remark}\\label{zeth-protocol:process-tx:dispatch-call}\n  In some deployments, verification of the zk-SNARK proof $\\zkp$ may be delegated to an external mechanism (in such a way that integrity of the system can still be guaranteed), and $\\zkp$ may not appear as public data on-chain. For example, where multiple \\zeth~transactions are aggregated by a system such as that described in \\cite{rondelet2020zecale}, the original zk-SNARK proofs become auxiliary inputs to a ``wrapping'' SNARK, which checks their validity via a single proof verification. A modified version of the \\mix~function receives \\mix~parameters from a specific contract (known to behave correctly with respect to the delegation protocol) without $\\inp{\\mix}.\\zkp$.\n\n  In this case, the value of $\\datatobesigned$ in \\cref{zeth-protocol:process-tx:check-otsig} may be replaced by:\n  \\[\n  \\datatobesigned = \\addr \\concat \\inp{\\mix}.\\primInp \\concat \\inp{\\mix}.\\ciphers, \\\\\n  \\]\n  and the equivalent change must be made when generating the \\mix~parameters, as described in \\cref{zeth-protocol:mix-inp:otsig-for-dispatch-call}. The transaction, as presented to an aggregator, is malleable since the $\\groth$ proofs can be modified in a way that preserves the validity. However, once aggregated, the transaction proof data for the transaction does not appear on chain (it is an auxiliary input to some externally generated ``wrapping'' poof). Hence, the transaction can only be identified by the remaining public data, which is protected by the one-time signature $\\otsSigma$, and hence non-malleable.\n\n  The external scheme used to verify the zk-SNARK proof must specify the exact requirements of the contact and how it should be modified, including any further checks that must be carried out. Thus, this modification is not part of the core \\zeth~protocol described in this document, but an augmentation forming part of an external protocol. However, for completeness, we briefly describe a \\emph{dispatch} entry point in the proof-of-concept \\mixer~implementation which supports delegation of proof verification, as described above. The \\emph{dispatch} entry point performs the following checks:\n  \\begin{itemize}\n  \\item Check that the \\mixer~has been deployed with the (immutable) address of a trusted contract, permitted to call this entry point. Otherwise, abort.\n  \\item Check that the caller $msg.sender$ matches the permitted caller set at deployment time, otherwise abort.\n  \\item Perform all checks related to the \\mix~parameters, except \\cref{zeth-protocol:process-tx:verify-zkp}, with the modification to \\cref{zeth-protocol:process-tx:check-otsig} described in this remark.\n  \\end{itemize}\n  After these checks, the state-transition continues as normal.\n\n  The \\zeth~client implementation is also augmented to include a flag to enable the corresponding change described in \\cref{zeth-protocol:mix-inp:otsig-for-dispatch-call} (to generate a signature on the modified $\\datatobesigned$). Naturally, the \\emph{dispatch} entry point can only be used with parameters generated using this flag (otherwise the signature check will fail).\n\n  Such modifications \\MUSTNOT{} be implemented except as described by the secure external scheme for delegating proof verification.\n\\end{remark}\n", "meta": {"hexsha": "0741d1e1e0e1e68483303a0f5872e7aa375ddeaa", "size": 9164, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/chap02-sec05.tex", "max_stars_repo_name": "clearmatics/zeth-specifications", "max_stars_repo_head_hexsha": "ba29c67587395f5c7b26b52ee7ab9cba12f1cc6b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-29T18:22:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-29T18:22:00.000Z", "max_issues_repo_path": "chapters/chap02-sec05.tex", "max_issues_repo_name": "clearmatics/zeth-specifications", "max_issues_repo_head_hexsha": "ba29c67587395f5c7b26b52ee7ab9cba12f1cc6b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2020-10-27T10:41:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-16T10:57:05.000Z", "max_forks_repo_path": "chapters/chap02-sec05.tex", "max_forks_repo_name": "clearmatics/zeth-specifications", "max_forks_repo_head_hexsha": "ba29c67587395f5c7b26b52ee7ab9cba12f1cc6b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-26T04:51:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T04:51:29.000Z", "avg_line_length": 95.4583333333, "max_line_length": 678, "alphanum_fraction": 0.6745962462, "num_tokens": 2476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.3463982669905446}}
{"text": "\\documentclass{article}\n\n\\usepackage{amsmath,amssymb}\n\\usepackage[dvipdfmx]{hyperref,graphicx}\n\\usepackage{listings}\n\n\\lstset{%\n  language={lisp},\n  basicstyle={\\small\\ttfamily},%\n  identifierstyle={\\small},%\n  commentstyle={\\small\\itshape},%\n  keywordstyle={\\small\\bfseries},%\n  ndkeywordstyle={\\small},%\n  stringstyle={\\small\\ttfamily},\n  frame={tb},\n  keepspaces=true,\n  breaklines=true,\n  columns=[l]{fullflexible},%\n  numbers=left,%\n  xrightmargin=0zw,%\n  xleftmargin=3zw,%\n  numberstyle={\\scriptsize},%\n  stepnumber=1,\n  numbersep=1zw,%\n  lineskip=-0.5ex%\n}\n\n\\title{Typing Rule of Baremetalisp}\n\\author{Yuuki Takano\\\\ ytakano@wide.ad.jp}\n\n\\begin{document}\n\n\\maketitle\n\n\\section{Introduction}\n\nIn this paper, I will formally describe the typing rule of Baremetalisp,\nwhich is a well typed Lisp for trusted execution environment.\n\n\\begin{table}[tb]\n    \\centering\n    \\caption{Notation}\n    \\label{tab:notation}\n    \\begin{tabular}{rl}\n        $A \\Rightarrow B$ & logical implication (if A then B)\\\\\n        $e$ & expression \\\\\n        $z$ & integer literal such as 10, -34, 112 \\\\\n        $x$ & variable \\\\\n        $t$ & type variable \\\\\n        $D$ & type name of user defined data \\\\\n        $L$ & label of user defined data \\\\\n        $E$ & effect \\\\\n        $E_\\mathcal{T}: T \\rightarrow E$ & effect of type \\\\\n        $\\mathcal{T}$ & type \\\\\n        $C$ & type constraint \\\\\n        $io(C): C \\rightarrow \\mathtt{Bool}$ & does $C$ contain $\\mathtt{IO}$ functions? \\\\\n        $\\Gamma$ & context \\\\\n        $\\mathcal{P}$ & pattern \\\\\n        $\\mathcal{P}_{let}$ & pattern of let expression \\\\\n        $\\mathcal{T}_1 \\equiv_\\alpha \\mathcal{T}_2$ & $\\mathcal{T}_1$ and $\\mathcal{T}_2$ are $\\alpha$-equivalent \\\\\n        $\\mathcal{S} : t \\rightarrow \\mathcal{T}$ & substitution from type variable to type\\\\\n        $\\mathcal{T} \\cdot \\mathcal{S}$ & apply $\\mathcal{S}$ to $\\mathcal{T}$ \\\\\n        $\\mathcal{X}$ & set of $t$ \\\\\n        $FV_\\mathcal{T} : \\mathcal{T} \\rightarrow \\mathcal{X}$ & function from $\\mathcal{T}$ to its free variables\\\\\n        $FV_\\Gamma : \\Gamma \\rightarrow \\mathcal{X}$ & function from $\\Gamma$ to its free variables\\\\\n        $Size : L \\rightarrow \\mathtt{Int}$ & the number of labels $L$'s type has \\\\\n        $\\Gamma \\vdash e : \\mathcal{T}\\ |_\\mathcal{X}\\ C$ & $e$'s type is deduced as $\\mathcal{T}$ from $\\Gamma$ \\\\\n        & under constraint $C$ and type variables $\\mathcal{X}$\n    \\end{tabular}\n\\end{table}\n\n\\begin{figure}[tb]\n    \\centering\n    \\begin{tabular}{rrll}\n    $\\mathcal{C}$ & := & $\\mathcal{T} = \\mathcal{T}, \\mathcal{C}$ & \\bf{type constraint} \\\\\n        & $|$ & $\\varnothing$ \\\\ \\\\\n\n    $\\Gamma$ & := & & \\bf{context} \\\\\n        &     & $x: \\mathcal{T}, \\Gamma$ & type of variable \\\\\n        & $|$ & $L: \\mathcal{T}, \\Gamma$ & type of label \\\\\n        & $|$ & $L_{nth}: \\mathcal{T}, \\Gamma$ & n-th type of label's element \\\\\n        & $|$ & $\\varnothing$ \\\\ \\\\\n\n    $E$ & := & $\\mathtt{Pure}\\ |\\ \\mathtt{IO}$ & \\bf{effect} \\\\ \\\\\n\n    $\\mathcal{T}$ & := & & \\bf{type} \\\\\n        &     & $\\mathtt{Int}$ \\\\\n        & $|$ & $\\mathtt{Bool}$ \\\\\n        & $|$ & $'(\\mathcal{T})$ & list type \\\\\n        & $|$ & $[\\mathcal{T}+]$ & tuple type \\\\\n        & $|$ & $D$    & user defined type \\\\\n        & $|$ & $(D\\ \\mathcal{T}+)$ & user defined type with type arguments \\\\\n        & $|$ & $(E\\ (\\rightarrow\\ (\\mathcal{T}*)\\ \\mathcal{T}))$ & function type \\\\\n        & $|$ & $t$ & type variable \\\\ \\\\\n\n    $\\mathcal{P}$ & := & & \\bf{pattern} \\\\\n        &     & $x$ & variable \\\\\n        & $|$ & $L$ & label \\\\\n        & $|$ & $(L\\ \\mathcal{P}+)$ & label with patterns \\\\\n        & $|$ & $'()$ & empty list \\\\\n        & $|$ & $[\\mathcal{P}+]$ & tuple \\\\ \\\\\n\n    $\\mathcal{P}_{let}$ & := & & \\bf{patten for let} \\\\\n        &     & $x$ & variable \\\\\n        & $|$ & $(L\\ \\mathcal{P}_{let}+)$ & label with patterns \\\\\n        & $|$ & $[\\mathcal{P}_{let}+]$ & tuple \\\\\n    \\end{tabular}\n    \\caption{Syntax}\n    \\label{fig:syntax}\n\\end{figure}\n\n\\section{Notation and Syntax}\n\nTable~\\ref{tab:notation} and Fig.~\\ref{fig:syntax} shows notation used in this paper\nand syntax for the typing rule, respectively.\n\n\\begin{lstlisting}[caption=Example of variable and type,label=src:vars]\n(defun add (a b) (Pure (-> (Int Int) Int))\n    (+ a b))\n\\end{lstlisting}\n\n$x$ is a variable.\nFor example, $x \\in \\{a, b\\}$ in Listing~\\ref{src:vars}.\n$\\mathcal{T}$ is a type.\nFor example, $\\mathcal{T} \\in \\{\\mathtt{Int}, (\\rightarrow\\ (\\mathtt{Int}\\ \\mathtt{Int})\\ \\mathtt{Int})\\}$\nin Listing~\\ref{src:vars}.\n$(\\rightarrow\\ (\\mathtt{Int}\\ \\mathtt{Int})\\ \\mathtt{Int})$ is a function type which takes 2 integer values\nand return 1 integer value.\n$\\mathtt{Pure}$ in Listing~\\ref{src:vars} denotes the effect of the function but I just ignore it now.\nFunction effects will be described in Sec.~\\ref{sec:effect}.\n$\\mathcal{T}$ can be other forms as described in Fig.~\\ref{fig:syntax} such as\n$\\mathtt{Bool}$, $'(\\mathtt{Int})$, $[\\mathtt{Bool}\\ \\mathtt{Int}]$, $(\\mathrm{List}\\ a)$, $(\\mathrm{List}\\ \\mathtt{Int})$.\n$C$ is a type constraint, which is a set of pairs of types.\nFor example, $C = \\{(\\rightarrow\\ (t_1\\ t_2)\\ t) = (\\rightarrow\\ (\\mathtt{Int}\\ \\mathtt{Int})\\ \\mathtt{Int})\\}$ deduced from\nListing~\\ref{src:vars} means $(\\rightarrow\\ (t_1\\ t_2)\\ t)$ and $(\\rightarrow\\ (\\mathtt{Int}\\ \\mathtt{Int})\\ \\mathtt{Int})$ are\nsemantically equal and every type variable in $C$, $t_1, t_2, t$, is thus $\\mathtt{Int}$.\n$\\Gamma$ is a map from variable and label to type.\nFor example, $\\Gamma = \\{a : t_1, b : t_2, + : (\\rightarrow\\ (\\mathtt{Int}\\ \\mathtt{Int})\\ \\mathtt{Int})\\}$\nin Listing~\\ref{src:vars}.\n$\\Gamma$ is called context generally, thus I call $\\Gamma$ context in this paper.\n\n\\begin{lstlisting}[caption=Example of user defined data type,label=src:cons]\n(data (List a)\n    (Cons a (List a))\n    Nil)\n\\end{lstlisting}\n\n$t$ is a type variable.\nFor example, $t \\in \\{a\\}$ in Listing~\\ref{src:cons}.\n$L$ is a label for user defined type.\nFor example, $L \\in \\{\\mathrm{Cons}, \\mathrm{Nil}\\}$ in Listing~\\ref{src:cons}.\n$D$ is user defined data.\nFor example, $D \\in \\{\\mathrm{List}\\}$ in Listing~\\ref{src:cons}.\n$\\Gamma$ will hold mapping from labels in addition to variables.\nFor example,\n$\\Gamma = \\{\\mathrm{Cons} : (\\mathrm{List}\\ a), \\mathrm{Nil} : (\\mathrm{List}\\ a), \\mathrm{Cons}_{1st} : a, \\mathrm{Cons}_{2nd} : (\\mathrm{List}\\ a)\\}$\nin Listing~\\ref{src:cons}.\n\n$FV_\\mathcal{T}$ and $FV_\\Gamma$ are functions, which take $\\mathcal{T}$ and $\\Gamma$ and return free variables.\nFor example, $FV_\\mathcal{T}((\\rightarrow\\ (t_1\\ t_2)\\ t)) = \\{t_1, t_2, t\\}$ and\n\\begin{equation*}\n    \\begin{aligned}\n        &FV_\\Gamma(\\{a : t_1, b : t_1, + : (\\rightarrow\\ (\\mathtt{Int}\\ \\mathtt{Int})\\ \\mathtt{Int})\\}) \\\\\n        &=\\{FV_\\mathcal{T}(t_1), FV_\\mathcal{T}(t_1), FV_\\mathcal{T}((\\rightarrow\\ (\\mathtt{Int}\\ \\mathtt{Int})\\ \\mathtt{Int}))\\} \\\\\n        &=\\{t_1, t_2\\}.\n    \\end{aligned}\n\\end{equation*}\n$\\mathcal{T}_1 \\equiv_\\alpha \\mathcal{T}_2$ denotes that $\\mathcal{T}_1$ and $\\mathcal{T}_2$ are $\\alpha$-equivalent,\nwhich means $\\mathcal{T}_1$ and $\\mathcal{T}_2$ are semantically equal.\nFor example, $(\\rightarrow\\ (t_1\\ t_2)\\ t) \\equiv_\\alpha (\\rightarrow\\ (t_{10}\\ t_{11})\\ t_{12})$.\n$\\mathcal{S}$ is a substitution, which is a map from type variable to type,\nand it can be applied to $\\mathcal{T}$ as $\\mathcal{T} \\cdot \\mathcal{S}$.\nFor example, if $\\mathcal{S}(t_1) = [\\mathtt{Bool}\\ \\mathtt{Int}], \\mathcal{S}(t_2) = (\\mathrm{List}\\ t_3)$ then\n$(\\rightarrow\\ (t_1\\ t_2)\\ t) \\cdot \\mathcal{S} = (\\rightarrow\\ ([\\mathtt{Bool}\\ \\mathtt{Int}]\\ (\\mathrm{List}\\ t_3))\\ t)$.\n\n\\begin{lstlisting}[caption=Example of pattern matching,label=src:match]\n(data Dim2 (Dim2 Int Int))\n\n(data (Maybe t)\n    (Just t)\n    Nothing)\n\n(defun match-let (a) (Pure (-> ((Maybe Dim2)) Int))\n    (match a\n        ((Just val)\n            (let (((Dim2 x y) val))\n                (+ x y)))\n        (Nothing\n            0)))\n\\end{lstlisting}\n$\\mathcal{P}$ and $\\mathcal{P}_{let}$ are pattern in match and let expressions.\nFor example, in listings~\\ref{src:match}, $(\\mathrm{Just}\\ val)$ and Nothing at line 9 and 12 are from $\\mathcal{P}$\nand $(\\mathrm{Dim2}\\ x\\ y)$ at line 10 is from $\\mathcal{P}_{let}$.\n$Size$ is a function which takes a label and return the number of labels the label's type has.\nFor example, $Size(\\mathrm{Just}) = Size(\\mathrm{Nothing}) = 2$ because Maybe type has 2 labels\nand $Size(\\mathrm{Dim2}) = 1$ because Dim2 type has 1 label in listings~\\ref{src:match}.\n\n\\begin{figure}[tb]\n    \\centering\n    \\begin{tabular}{rlrl}\n        $\\Gamma \\vdash \\mathtt{true} : \\mathtt{Bool}\\ |_\\varnothing\\ \\varnothing$ & (T-True) &\n        $\\Gamma \\vdash \\mathtt{false} : \\mathtt{Bool}\\ |_\\varnothing\\ \\varnothing$ & (T-False) \\vspace{5mm} \\\\\n\n        $\\dfrac{x : T \\in \\Gamma}{\\Gamma \\vdash x : T\\ |_\\varnothing\\ \\varnothing}$ & (T-Var) &\n        $\\Gamma \\vdash z : \\mathtt{Int}\\ |_\\varnothing\\ \\varnothing$ & (T-Num) \\vspace{5mm} \\\\\n\n        $\\dfrac{x : T' \\in \\Gamma \\hspace{5mm} T' \\cdot S \\equiv_\\alpha T}{\\Gamma \\vdash x : T\\ |_{FV_\\mathcal{T}(T)}\\ \\varnothing}$ & (T-VarPoly) \\vspace{5mm} \\\\\n\n        \\multicolumn{3}{r}{\n        $\\dfrac{\n            \\begin{aligned}\n                &\\Gamma_0 \\vdash \\mathcal{P}_{let} : \\mathcal{T}_0\\ |_{\\mathcal{X}_0}\\ C_0 \\hspace{5mm}\n                    \\Gamma \\vdash e_1 : \\mathcal{T}_1\\ |_{\\mathcal{X}_1}\\ C_1 \\hspace{5mm}\n                    \\Gamma, \\Gamma_0 \\vdash e_2 : \\mathcal{T}_2\\ |_{\\mathcal{X}_2}\\ C_2\\\\\n                &\\mathcal{X}_0 \\cap \\mathcal{X}_1 \\cap \\mathcal{X}_2 = \\varnothing \\hspace{5mm}\n                    C = C_0 \\cup C_1 \\cup C_2 \\cup \\{ \\mathcal{T}_0 = \\mathcal{T}_1 \\}\n            \\end{aligned}\n        }{\n            \\Gamma \\vdash (\\mathtt{let1}\\ \\mathcal{P}_{let}\\ e_1\\ e_2) : \\mathcal{T}_2\\ |_{\\mathcal{X}_0 \\cup \\mathcal{X}_1 \\cup \\mathcal{X}_2}\\ C\n        }$} & (T-Let1) \\vspace{5mm} \\\\\n\n        \\multicolumn{3}{r}{\n        $\\dfrac{\n            \\begin{aligned}\n                &\\Gamma \\vdash e_1 : \\mathcal{T}_1\\ |_{\\mathcal{X}_1}\\ C_1 \\hspace{5mm} \\Gamma \\vdash e_2 : \\mathcal{T}_2\\ |_{\\mathcal{X}_2}\\ C_2 \\hspace{5mm} \\Gamma \\vdash e_3 : \\mathcal{T}_3\\ |_{\\mathcal{X}_3}\\ C_3 \\\\\n                &\\mathcal{X}_1 \\cap \\mathcal{X}_2 \\cap \\mathcal{X}_3 = \\varnothing \\hspace{5mm} C = C_1 \\cup C_2 \\cup C_3 \\cup \\{ \\mathcal{T}_1 = \\mathtt{Bool}, \\mathcal{T}_2 = T_3 \\}\n            \\end{aligned}\n        }{\n            \\Gamma \\vdash (\\mathtt{if}\\ e_1\\ e_2\\ e_3) : \\mathcal{T}_2\\ |_{\\mathcal{X}_1 \\cup \\mathcal{X}_2 \\cup \\mathcal{X}_3}\\ C\n        }$} & (T-If) \\vspace{5mm} \\\\\n\n        \\multicolumn{3}{r}{\n        $\\dfrac{\n            \\begin{aligned}\n                &\\Gamma \\vdash e_1 : \\mathcal{T}_1\\ |_{\\mathcal{X}_1}\\ C_1 \\hspace{5mm}\n                    \\Gamma \\vdash e_2 : \\mathcal{T}_2\\ |_{\\mathcal{X}_2}\\ C_2 \\land \\cdots \\land \\Gamma \\vdash e_n : \\mathcal{T}_n\\ |_{\\mathcal{X}_n}\\ C_n \\\\\n                &\\{t\\} \\cap FV_\\Gamma(\\Gamma) = \\varnothing \\hspace{5mm} \\{t\\} \\cap \\mathcal{X}_1 \\cap \\cdots \\cap \\mathcal{X}_n = \\varnothing\\\\\n                &\\mathcal{X} = \\{t\\} \\cup \\mathcal{X}_1 \\cup \\cdots \\cup \\mathcal{X}_n \\hspace{5mm} E = E_\\mathcal{T}(\\mathcal{T}_1) \\\\\n                &C = C_1 \\cup \\cdots \\cup C_n \\cup \\{ \\mathcal{T}_1 = (E\\ (\\rightarrow\\ (\\mathcal{T}_2\\ \\cdots\\ \\mathcal{T}_n)\\ t)) \\}\n            \\end{aligned}\n        }{\n            \\Gamma \\vdash (e_1\\ e_2\\ \\cdots\\ e_n) : t\\ |_\\mathcal{X}\\ C\n        }$} & (T-App) \\vspace{5mm} \\\\\n\n        \\multicolumn{3}{r}{\n        $\\dfrac{\n            \\begin{aligned}\n                &\\Gamma \\vdash e_0 : \\mathcal{T}_0\\ |_{\\mathcal{X}_0}\\ C_0 \\\\\n                &\\Gamma, \\Gamma_1 \\vdash e_1 : \\mathcal{T}_{e1}\\ |_{\\mathcal{X}_{e1}}\\ C_{e1} \\land \\cdots \\land \\Gamma, \\Gamma_n \\vdash e_n : \\mathcal{T}_{en}\\ |_{\\mathcal{X}_{en}}\\ C_{en} \\\\\n                &\\Gamma_1 \\vdash \\mathcal{P}_1 : \\mathcal{T}_{p1}\\ |_{\\mathcal{X}_{p1}}\\ C_{p1} \\land \\cdots \\land \\Gamma_n \\vdash \\mathcal{P}_{pn} : \\mathcal{T}_{pn}\\ |_{\\mathcal{X}_{pn}}\\ C_{pn} \\\\\n                &\\mathcal{X}_0 \\cap \\mathcal{X}_{e1} \\cap \\cdots \\cap \\mathcal{X}_{en} \\cap \\mathcal{X}_{p1} \\cap \\cdots \\cap \\mathcal{X}_{pn} = \\varnothing \\\\\n                &\\mathcal{X} = \\mathcal{X}_0 \\cup \\mathcal{X}_{e1} \\cup \\cdots \\cup \\mathcal{X}_{en} \\cup \\mathcal{X}_{p1} \\cup \\cdots \\cup \\mathcal{X}_{pn} \\\\\n                &\\begin{aligned}\n                    C =\\ &C_0 \\cup C_{e1} \\cup \\cdots \\cup C_{en} \\cup C_{p1} \\cup \\cdots \\cup C_{pn} \\cup \\\\\n                         &\\{\\mathcal{T}_0 = \\mathcal{T}_{p1}, \\cdots, \\mathcal{T}_0 = \\mathcal{T}_{pn}\\} \\cup\n                         \\{\\mathcal{T}_{e1} = \\mathcal{T}_{e2}, \\cdots, \\mathcal{T}_{e1} = \\mathcal{T}_{en}\\}\n                \\end{aligned}\n            \\end{aligned}\n        }{\n            \\Gamma \\vdash (\\mathtt{match}\\ e_0\\ (\\mathcal{P}_1\\ e_1)\\ \\cdots\\ (\\mathcal{P}_n\\ e_n)) : T_{e1}\\ |_\\mathcal{X}\\ C\n        }$} & (T-Match)\n    \\end{tabular}\n    \\caption{Typing rule (1/2)}\n    \\label{fig:typing1}\n\\end{figure}\n\n\\begin{figure}[tb]\n    \\centering\n    \\begin{tabular}{rlrl}\n        $\\Gamma \\vdash\\ '() :\\ '(T)\\ |_{\\{T\\}}\\ \\varnothing$ & (T-Nil) &\n        $\\dfrac{L : \\mathcal{T}' \\in \\Gamma \\hspace{5mm} \\mathcal{T}' \\cdot \\mathcal{S} \\equiv_\\alpha \\mathcal{T}}{\\Gamma \\vdash L : \\mathcal{T}\\ |_{FV_\\mathcal{T}(\\mathcal{T})}\\ \\varnothing}$ & (T-Label0) \\vspace{5mm} \\\\\n\n        \\multicolumn{3}{r}{\n            $\\dfrac{\n                \\begin{aligned}\n                    &\\Gamma \\vdash e_1 : T_1\\ |_{\\mathcal{X}_1}\\ C_1 \\land \\cdots \\land \\Gamma \\vdash e_n : T_n\\ |_{\\mathcal{X}_n}\\ C_n \\\\\n                    &\\mathcal{X}_1 \\cap \\cdots \\cap \\mathcal{X}_n = \\varnothing \\hspace{5mm}\n                    \\mathcal{X} = \\mathcal{X}_1 \\cup \\cdots \\cup \\mathcal{X}_n \\hspace{5mm}\n                    C = C_1 \\cup \\cdots \\cup C_n\n                \\end{aligned}\n            }{\\Gamma \\vdash [e_1\\ \\cdots\\ e_n] : [T_1\\ \\cdots\\ T_n]\\ |_\\mathcal{X}\\ C}$\n        } & (T-Tuple) \\vspace{5mm} \\\\\n\n        \\multicolumn{3}{r}{\n            $\\dfrac{\n                \\begin{aligned}\n                    &\\Gamma \\vdash e_1 : T_1\\ |_{\\mathcal{X}_1}\\ C_1 \\land \\cdots \\land \\Gamma \\vdash e_n : T_n\\ |_{\\mathcal{X}_n}\\ C_n \\\\\n                    &\\mathcal{X}_1 \\cap \\cdots \\cap \\mathcal{X}_n = \\varnothing \\hspace{5mm}\n                    \\mathcal{X} = \\mathcal{X}_1 \\cup \\cdots \\cup \\mathcal{X}_n \\\\\n                    &C = C_1 \\cup \\cdots \\cup C_n \\cup \\{T_1 = T_2, \\cdots, T_1 = T_n \\}\n                \\end{aligned}\n            }{\\Gamma \\vdash\\ '(e_1\\ \\cdots\\ e_n) :\\ '(T_1)\\ |_\\mathcal{X}\\ C}$\n        } & (T-List) \\vspace{5mm} \\\\\n\n        \\multicolumn{3}{r}{\n        $\\dfrac{\n            \\begin{aligned}\n                &\\Gamma \\vdash e_1 : \\mathcal{T}_1\\ |_{\\mathcal{X}_1}\\ C_1 \\land \\cdots \\land\n                    \\Gamma \\vdash e_n : \\mathcal{T}_n\\ |_{\\mathcal{X}_n}\\ C_n \\\\\n                &L : \\mathcal{T}_0' \\in \\Gamma \\hspace{5mm} \\mathcal{T}_0' \\cdot \\mathcal{S}\\equiv_\\alpha \\mathcal{T}_0 \\hspace{5mm} FV(\\mathcal{T}_0) \\cap \\mathcal{X}_1 \\cap \\cdots \\cap \\mathcal{X}_n = \\varnothing \\\\\n                &FV_\\mathcal{T}(\\mathcal{T}_0) \\cap FV_\\Gamma(\\Gamma) = \\varnothing \\hspace{5mm}\n                    \\mathcal{X} = FV(\\mathcal{T}_0) \\cup \\mathcal{X}_1 \\cup \\cdots \\cup \\mathcal{X}_n \\\\\n                &L_{1st} : T_1' \\in \\Gamma \\land \\cdots \\land L_{nth} : T_n' \\in \\Gamma \\\\\n                &C = C_1 \\cup \\cdots \\cup C_n \\cup \\{T_1' \\cdot \\mathcal{S} = \\mathcal{T}_1, \\cdots, T_n' \\cdot \\mathcal{S} = \\mathcal{T}_n\\} \\\\\n            \\end{aligned}\n        }{\n            \\Gamma \\vdash (L\\ e_1\\ \\cdots\\ e_n) : \\mathcal{T}_0\\ |_{\\mathcal{X}}\\ C\n        }$} & (T-Label) \\vspace{5mm} \\\\\n\n        \\multicolumn{3}{r}{\n            $\\dfrac{\n                \\begin{aligned}\n                    &\\Gamma, x_1 : t_1, \\cdots, x_n : t_n \\vdash e : \\mathcal{T}_0\\ |_{\\mathcal{X}}\\ C_0 \\hspace{5mm} \\neg io(C)\\\\\n                    &C = \\{\\mathcal{T} = (\\mathtt{Pure}\\ (\\rightarrow\\ (t_1\\ \\cdots\\ t_n)\\ \\mathcal{T}_0))\\} \\cup C_0\n                \\end{aligned}\n            }\n            {\n                \\Gamma \\vdash (\\mathtt{lambda}\\ (x_1\\ \\cdots\\ x_n)\\ e) : \\mathcal{T}\\ |_\\mathcal{X}\\ C\n            }$\n        } & (T-Lambda) \\vspace{5mm} \\\\\n\n        \\multicolumn{3}{r}{\n            $\\dfrac{\n                \\begin{aligned}\n                    &\\Gamma, x_1 : t_1, \\cdots, x_n : t_n \\vdash e : \\mathcal{T}_0\\ |_{\\mathcal{X}}\\ C_0 \\hspace{5mm}\\\\\n                    &E = E_\\mathcal{T}(\\mathcal{T}) \\hspace{5mm} (E = \\mathtt{Pure}) \\Rightarrow \\neg io(C)\\\\\n                    &C = C_0 \\cup \\{\\mathcal{T} = (E\\ (\\rightarrow (\\mathcal{T}_1\\ \\cdots\\ \\mathcal{T}_n)\\ \\mathcal{T}_0)) \\}\n                \\end{aligned}\n            }{\n                \\Gamma \\vdash (\\mathtt{defun}\\ \\mathrm{name}\\ (x_1\\ \\cdots\\ x_n)\\ \\mathcal{T}\\ e) : \\mathcal{T}\\ |_\\mathcal{X}\\ C\n            }$\n        } & (T-Defun)\n    \\end{tabular}\n    \\caption{Typing rule (2/2)}\n    \\label{fig:typing2}\n\\end{figure}\n\n\n\\begin{figure}[tb]\n    \\centering\n    \\begin{tabular}{rlrl}\n        $\\Gamma \\vdash \\mathtt{true} : \\mathtt{Bool}\\ |_\\varnothing\\ \\varnothing$ & (P-True) &\n        $\\Gamma \\vdash \\mathtt{false} : \\mathtt{Bool}\\ |_\\varnothing\\ \\varnothing$ & (P-False) \\vspace{5mm} \\\\\n\n        $\\dfrac{x : T \\in \\Gamma}{\\Gamma \\vdash x : T\\ |_\\varnothing\\ \\varnothing}$ & (P-Var) &\n        $\\Gamma \\vdash z : \\mathtt{Int}\\ |_\\varnothing\\ \\varnothing$ & (P-Num) \\vspace{5mm} \\\\\n\n        $\\Gamma \\vdash\\ '() :\\ '(T)\\ |_{\\{T\\}}\\ \\varnothing$ & (P-Nil) &\n        $\\dfrac{L : \\mathcal{T}' \\in \\Gamma \\hspace{5mm} \\mathcal{T}' \\cdot \\mathcal{S} \\equiv_\\alpha \\mathcal{T}}{\\Gamma \\vdash L : \\mathcal{T}\\ |_{FV_\\mathcal{T}(\\mathcal{T})}\\ \\varnothing}$ & (P-Label0) \\vspace{5mm} \\\\\n\n        \\multicolumn{3}{r}{\n        $\\dfrac{\n            \\begin{aligned}\n                &\\Gamma \\vdash \\mathcal{P}_1 : \\mathcal{T}_1\\ |_{\\mathcal{X}_1}\\ C_1 \\land \\cdots \\land\n                    \\Gamma \\vdash \\mathcal{P}_n : \\mathcal{T}_n\\ |_{\\mathcal{X}_n}\\ C_n \\\\\n                &L : \\mathcal{T}_0' \\in \\Gamma \\hspace{5mm} \\mathcal{T}_0' \\cdot \\mathcal{S}\\equiv_\\alpha \\mathcal{T}_0 \\hspace{5mm} FV(\\mathcal{T}_0) \\cap \\mathcal{X}_1 \\cap \\cdots \\cap \\mathcal{X}_n = \\varnothing \\\\\n                &FV_\\mathcal{T}(\\mathcal{T}_0) \\cap FV_\\Gamma(\\Gamma) = \\varnothing \\hspace{5mm}\n                    \\mathcal{X} = FV(\\mathcal{T}_0) \\cup \\mathcal{X}_1 \\cup \\cdots \\cup \\mathcal{X}_n \\\\\n                &L_{1st} : T_1' \\in \\Gamma \\land \\cdots \\land L_{nth} : T_n' \\in \\Gamma \\\\\n                &C = C_1 \\cup \\cdots \\cup C_n \\cup \\{T_1' \\cdot \\mathcal{S} = \\mathcal{T}_1, \\cdots, T_n' \\cdot \\mathcal{S} = \\mathcal{T}_n\\} \\\\\n                &Size(L) = 1\\ \\mbox{for only}\\ P_{let}\n            \\end{aligned}\n        }{\n            \\Gamma \\vdash (L\\ \\mathcal{P}_1\\ \\cdots\\ \\mathcal{P}_n) : \\mathcal{T}_0\\ |_{\\mathcal{X}}\\ C\n        }$} & (P-Label) \\vspace{5mm} \\\\\n\n        \\multicolumn{3}{r}{\n        $\\dfrac{\n            \\begin{aligned}\n                &\\Gamma \\vdash \\mathcal{P}_1 : \\mathcal{T}_1\\ |_{\\mathcal{X}_1}\\ C_1 \\land \\cdots \\land\n                    \\Gamma \\vdash \\mathcal{P}_n : \\mathcal{T}_n\\ |_{\\mathcal{X}_n}\\ C_n \\\\\n                &\\mathcal{X}_1 \\cap \\cdots \\cap \\mathcal{X}_n = \\varnothing \\hspace{5mm}\n                    \\mathcal{X} = \\mathcal{X}_1 \\cup \\cdots \\cup \\mathcal{X}_n \\hspace{5mm}\n                    C = C_1 \\cup \\cdots \\cup C_n\n            \\end{aligned}\n        }{\n            \\Gamma \\vdash [\\mathcal{P}_1\\ \\cdots\\ \\mathcal{P}_n] : [\\mathcal{T}_1 \\cdots \\mathcal{T}_n]\\ |_{\\mathcal{X}}\\ C\n        }$} & (P-Tuple) \\\\\n    \\end{tabular}\n    \\caption{Typing rule of pattern}\n\\end{figure}\n\n\\section{Typing Rule}\n\nIn this section, I will introduce the typing rule of Baremetalisp.\nBefore describing the rule, I introduce an assumption\nthat there is no variable shadowing to make it simple.\nThis means that every variable should be properly $\\alpha$-converted\nby using the De Bruijn index technique or variable shadowing should be handled\nwhen implementing the type inference algorithm.\n\nFig.~\\ref{fig:typing1} and \\ref{fig:typing2} are the typing rule of\nexpressions and function definitions.\n\n\\section{Effect}\n\\label{sec:effect}\n\n\\end{document}", "meta": {"hexsha": "97be5c4084a1926d42c98c5c7b668faf92d9fa89", "size": 20142, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "specification/typing.tex", "max_stars_repo_name": "syohex/blisp", "max_stars_repo_head_hexsha": "3a884c44a74586d23aba17c60f24c5be80e476aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 115, "max_stars_repo_stars_event_min_datetime": "2020-11-20T13:15:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T23:01:16.000Z", "max_issues_repo_path": "specification/typing.tex", "max_issues_repo_name": "syohex/blisp", "max_issues_repo_head_hexsha": "3a884c44a74586d23aba17c60f24c5be80e476aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-11-06T23:47:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T04:47:58.000Z", "max_forks_repo_path": "specification/typing.tex", "max_forks_repo_name": "syohex/blisp", "max_forks_repo_head_hexsha": "3a884c44a74586d23aba17c60f24c5be80e476aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-07-31T11:12:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T01:57:03.000Z", "avg_line_length": 50.608040201, "max_line_length": 221, "alphanum_fraction": 0.5518319929, "num_tokens": 7354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.5, "lm_q1q2_score": 0.34632099156736806}}
{"text": "% !TEX root = ../00_thesis.tex\n%-------------------------------------------------------------------------------\n\\section{Designing \\triscale}\n\\label{sec:triscale}\n%-------------------------------------------------------------------------------\n\nIn this section, we first describe the data analysis performed by \\triscale and how the analysis procedure is linked to the design of experiments~(\\cref{subsec:metrics} to \\cref{subsec:repeatability}).\nWe then illustrate how the formalism introduced by \\triscale allows to unambiguously describe an entire performance evaluation with only a handful of parameters~(\\cref{subsec:parameters}).\nThereafter, we detail the robust and non-parametric statistical methods used by \\triscale~(\\cref{subsec:triscale_stats}), and discuss how the framework assists a user in deciding the required time span for a series of runs~(\\cref{subsec:network_profiling}).\nWe finally show how \\triscale helps assessing the reproducibility of experiments by computing a variability score~(\\cref{subsec:reproducibility}).\n\n%-------------------------------------------------------------------------------\n\\subsection{Runs and Metrics}\n\\label{subsec:metrics}\n\n\\afterpage{\n\\begin{figure}\n    \\centering\n    \\begin{subfigure}{\\linewidth}\n        \\centering\n       \t\\href{\\triscalefig{Figure-3a}}{\n        \\includegraphics[scale=1]{Figures/plot_example_metric.pdf}}\n        \\caption{\\raggedright Raw data (one-way delay) and metric data (95th percentile).}\n        \\label{fig:analysis_metric}\n    \\end{subfigure}\n\n    \\vspace{5pt}\n\n    \\begin{subfigure}{0.45\\linewidth}\n        \\centering\n       \t\\href{\\triscalefig{Figure-3b}}{\n        \\includegraphics[scale=1]{Figures/plot_example_KPI.pdf}}\n        \\caption{Runs' metric data and corresponding KPI value.}\n        \\label{fig:analysis_kpi}\n    \\end{subfigure}\n    %\n    \\hfill\n    \\begin{subfigure}{0.45\\linewidth}\n        \\centering\n     \t  \\href{\\triscalefig{Figure-3c}}{\n        \\includegraphics[scale=1]{Figures/plot_example_var_score.pdf}}\n        \\caption{Series' KPI data and corresponding variability score.}\n        \\label{fig:analysis_score}\n    \\end{subfigure}\n    \\caption{Example plots produced by \\triscale during the data analysis.\n    \\Cref{fig:analysis_metric}: computation of the metric (95th percentile on one-way delay) with convergence test (confidence 95\\%, tolerance 1\\%).\n    \\Cref{fig:analysis_kpi}: computation of the KPI (75th percentile with 75\\% confidence).\n    \\Cref{fig:analysis_score}: computation of the variability score (25-75th percentiles with 75\\% confidence).\n    \\capt{Sample data from the case study (\\cref{sec:triscale_eval}) for the \\textit{FillP} congestion-control scheme.}}\n    \\label{fig:analysis_examples}\n\\end{figure}\n}\n\nMetrics in \\triscale evaluate a performance dimension across a run, for example, the mean throughput achieved by a congestion-control scheme over 30\\s runtime of a full-throttle flow.\nComputing a metric takes the following inputs.\n\n\\fakepar{Inputs}\n\\custommini{%\n  \\begin{itemize}\n    \\item The metric \\emph{measure}; \\eg mean, maximum, \\etc\n    \\item The \\emph{convergence} requirements\\\\\n    \\begin{tabular}{@{\\quad}l@{\\quad}r@{\\;\\;:\\;\\;}ll@{\\quad}l}\n      \\{  & expected & \\multicolumn{2}{@{}l}{true/false,} &\\\\\n          & confidence & $C$  &(\\textit{default: 95\\%}),  &\\\\\n          & tolerance & $t$   &(\\textit{default: 5\\%})    &\\}\n    \\end{tabular}\n  \\item The raw data of the run.\n  \\end{itemize}\n}%\n\n\\noindent\nIn general, any measure can be used. The current implementation (\\cref{sec:triscale_implementation}) supports the arithmetic mean, the minimum, the maximum, and any percentile.\n\n\\fakepar{Procedure}\nIf the run is expected to converge, \\triscale starts by performing a convergence test, whose purpose is to assess whether the metric has reached a stable value by the end of the run (and hence if it is a good estimate of the long-running performance).\n%\nTo test this, \\triscale computes metric values over a sliding window of the raw data points. For each window, whose size is fixed to half of the data points, one metric value is computed, starting with the first half of the data.\nThe window repeatedly slides by 100th of the number of samples until all data points are used, leading to a set of 100 metric values.%\n\\triscale performs its convergence test~(detailed in \\cref{subsec:triscale_stats}) on the metric values.\nThis procedure tests the convergence of the \\emph{metric} (not the raw data) and damps the impact of transient behavior on the convergence test.\nIf the test is passed, \\triscale returns the median of metric values as run metric.\nIf convergence is not expected, \\triscale simply computes the run metric over the whole raw data.\n\n% To test this, \\triscale divides the raw data in 200 chunks. First, it considers the first 100 chunks (\\ie the first half of the data) and computes a first value of the measure. Then, \\triscale adds one chunk of data and recomputes a new measure value (\\ie using the first 101 chunks). The process repeats until all chunks are used, leading to a set of 100 measure values. \\triscale performs its convergence test~(detailed in \\cref{subsec:triscale_stats}) on the measure data.\n% This procedure (i)~tests what we are interested in (\\ie the convergence of the \\emph{measure}, not of the protocol in general) and (ii)~smooths the effects of ramp-up time by computing the first measure with already half of the run data.\n% If the test is passed, \\triscale returns the median of the measure data as the metric measure for the run.\n\n\\begin{remark}\n  If there are less than 100 raw data points, \\triscale reduces the number of windows to the number of data points.\n  \\triscale (arbitrarily) sets a minimum of 20 data points for a convergence test.\n\\end{remark}\n\n\\fakepar{Outputs}\n\\custommini{%\n\\begin{itemize}\n  \\item\n  The result of the convergence test (if performed),\n  \\item\n  The metric value for the run,\n  \\item\n  Textual logs; plot of the input data and metric (\\Cref{fig:analysis_metric}).\n\n\\end{itemize}\n}\n\n\\fakepar{Link to the experiment design}\nThe computation of \\triscale metrics is linked to the definition of the \\emph{runtime}; \\ie how long a run should be.\nIf the evaluation scenario is terminating (\\eg transmit 1\\MB through a link), the runtime must be long enough to complete the task.\nIf the evaluation is ``long-running'' (\\eg one-way delay in a full-throttle flow), the runtime must be long enough for the metric (the one-way delay) to converge (convergence test details in \\cref{subsec:triscale_stats}).\n\\triscale can analyze preliminary experiments to estimate the required runtime: by performing increasing long runs and test for convergence~(illustrated in \\cref{sec:triscale_eval}).\n\n%-------------------------------------------------------------------------------\n\\subsection{Series and KPIs}\n\\label{subsec:KPIs}\n%-------------------------------------------------------------------------------\n\n\\triscale's key performance indicators (KPIs) evaluate performance dimensions across a series of runs.\nPerforming multiple runs allows to mitigate the inherent variability of the experimental conditions.\nKPIs capture this variability by estimating percentiles of the (unknown) metric distributions.\nConcretely, a \\triscale KPI is a one-sided CI of one percentile; \\eg a lower-bound for the 75th percentile of the delay metric estimated with a 75\\% confidence level.\nComputing a KPI takes the following inputs.\n\n\\fakepar{Inputs}\n\\custommini{%\n  \\begin{itemize}\n    \\item\n    The {KPI} definition\\\\\n    \\begin{tabular}{@{\\quad}l@{\\quad}r@{\\;\\;:\\;\\;}l@{\\quad}l}\n      \\{  & percentile & $p$ &\\\\\n          & confidence & $C$&\\}\n    \\end{tabular}\n    \\item\n    The metric data (computed from a series of runs).\n\\end{itemize}}\n\n\n\\fakepar{Procedure}\nTo compute the KPI (\\ie to compute a CI for a given percentile), \\triscale uses the Thompson's method (\\cref{subsec:triscale_stats}), which requires the input data to be \\iid.\nThus, \\triscale starts by performing an independence test~(\\cref{subsec:triscale_stats})\non the metric data before computing the KPI.\n\n\\fakepar{Outputs}\n\\custommini{\n\\begin{itemize}\n  \\item The result of the independence test,\n  \\item The KPI value for the series of runs,\n  \\item Textual logs; plot of the metric data and corresponding KPI (\\Cref{fig:analysis_kpi}).\n\\end{itemize}\n}\n\n\\fakepar{Link to the experiment design}\nThe computation of \\triscale KPIs is linked to the definition of the number of runs in a series (\\emph{\\#\\,runs}) and the series time span (\\emph{span}).\nThe minimal number of runs in a series directly follows from the definition of the KPI; \\ie the percentile to estimate $p$ and the desired confidence level $C$.\nThe series time span refers to the time interval used for scheduling the runs in a series (\\ie when to run the experiment).\nThis is important because networks often feature time-dependent conditions; for example, there may be systematically more cross-traffic during daytime than nighttime. Failing to account for such dependencies may bias the results and yield wrong conclusions.\n\\triscale helps the experimenter handling this problem with a dedicated analysis module called ``network profiling'' (described in~\\cref{subsec:network_profiling}).\n\n\n\n%-------------------------------------------------------------------------------\n\\subsection{Sequels and Variability Score}\n\\label{subsec:repeatability}\n%-------------------------------------------------------------------------------\n\n\\emph{Sequels} are repetitions of series of runs.\n\\triscale's variability score evaluates the variations of KPI values across sequels, which enable to detect long-term variations of KPIs and ultimately quantify the reproducibility of an experiment.\n\nConcretely, a variability score is a two-sided CI, \\ie a symmetric pair of percentiles. For example, a 75\\% confidence interval is defined by the 25-75th percentiles of the delay KPIs from all sequels. Again, we attach a confidence value to the confidence interval, or equivalently, to the percentiles.\n\n\\fakepar{Inputs}\n\\custommini{%\n\\begin{itemize}\n  \\item\n  The {variability score} definition\\\\\n  \\begin{tabular}{@{\\quad}l@{\\quad}r@{\\;\\;:\\;\\;}l@{\\quad}l}\n    \\{  & percentile & $p$ (or 1-$p$) &\\\\\n        & confidence & $C$&\\}\n  \\end{tabular}\n  \\item\n  The KPI values of each sequel.\n\\end{itemize}}\n\n\\fakepar{Procedure}\nThe procedure is the same as for the KPI: The Thompson's method requires the input data to be \\iid~(\\cref{subsec:triscale_stats}), thus \\triscale performs an independence test on the KPI data before computing the variability score.\n\n\\fakepar{Outputs}\n\\custommini{%\n\\begin{itemize}\n  \\item\n  The result of the independence test,\n  \\item\n  The variability score value for the entire sequels,\n  \\item\n  Textual logs; plot of the KPI data and corresponding variability score (\\Cref{fig:analysis_score}).\n\\end{itemize}}\n\n\\fakepar{Link to the experiment design}\nThe computation of the variability score is linked to the definition of the number of series (\\emph{\\#series}).\nThe minimal number of series directly follows from the definition of the variability score; \\ie the percentile to estimate $p$ and the desired confidence level $C$.\n\n%-------------------------------------------------------------------------------\n\\subsection{Formalism Brings Conciseness}\n\\label{subsec:parameters}\n%-------------------------------------------------------------------------------\n\n\\afterpage{\n\\begin{landscape}\n  \\begin{table}\n      \\centering\n      \\caption{Exemplary evaluation parameters of typical networking use cases.\n      \\capt{$^{*}$\\triscale returns the minimal number of runs (\\#runs) and series (\\#series) based on the definition of KPI and variability score, respectively.}}\n      \\input{\\PathTab/triscale_parameters.csv}\n      \\label{table:triscale_param}\n  \\end{table}\n\\end{landscape}\n}\n\n\\triscale formalizes the definition of the evaluation objectives. For each performance dimension, the experimenter defines a metric and convergence requirements~(\\cref{subsec:metrics}), a KPI~(\\cref{subsec:KPIs}), and a variability score~(\\cref{subsec:repeatability}).\n\\triscale links these objectives with the experiment design, resulting in four additional parameters: the number of runs per series (\\emph{\\#\\,runs}), the number of series (\\emph{\\#\\,series}), the length of a run (\\emph{runtime}), and the time span of a series (\\emph{span}).\n\nThanks to this formalism, \\triscale meets the \\feature{Conciseness} requirement:\nAltogether, these 12 parameters are sufficient to \\emph{formally describe the entire performance evaluation} such that it can (eventually) be reproduced.\nIn particular, since the data analysis in \\triscale is automated and deterministic, documenting these parameters guarantees computational reproducibility (the ability to recreate the results when all raw data are available~\\cite{liu19computational}).\n\n\\Cref{table:triscale_param} shows a few examples of concrete parameter settings for typical networking evaluation objectives.\nFor example, evaluating the latency of a real-time protocol requires high confidence levels for extreme percentiles.\nThis very quickly increases the number of runs that one must perform:\\\\\n\\inlineitem\n  at least 90 runs for estimating the 95th percentile with 99\\% confidence;\\linebreak\n\\inlineitem\n  at least 299 runs for estimating the 99th percentile with 95\\% confidence.\\linebreak\nThis illustrates that it is ``easier'' to increase the confidence level of an estimate than to estimate a more extreme percentile with the same confidence level.\nNote that both \\emph{\\#runs} and \\emph{\\#series} are only derived based on the definition of the KPI and variability score; these parameters are not influenced by the runtime or the time span of an experiment.\n\nThe second use case in \\Cref{table:triscale_param} (bottom rows) illustrates two different perspectives on ``averages'', using delay as an example:\n\\\\\n% \\begin{itemize}\n    % \\item\n    \\inlineitem\n    If the metric is the median and the KPI the 90th percentile, one can conclude that 90\\% of the runs have a median delay equal or better than the KPI value.\n\\\\\n    % \\item\n    \\inlineitem\n    If the metric is the 90th percentile and the KPI the median, one can conclude that, in half of the runs, the 90th percentile of the delay in the run is equal or better than the KPI.\n% \\end{itemize}\n\\\\\nBoth are ``averages'' but with different meanings and different requirements in terms of number of runs.\n\n\n%-------------------------------------------------------------------------------\n\\subsection{Statistics in \\triscale}\n\\label{subsec:triscale_stats}\n%-------------------------------------------------------------------------------\n\n\\triscale uses carefully chosen statistical methods.\nAs discussed in~\\cref{sec:stats}, networking performance evaluations should focus on statistics that are both \\emph{robust} (\\ie that can tolerate outliers) and \\emph{non-parametric} (\\ie that do not make any assumption on the nature of the data distribution).\nThis section describes the three statistical methods used in \\triscale. We first present the convergence test used in the computation of metrics (\\cref{subsec:metrics});\nThis test is based on the \\mbox{Theil-Sen} linear regression~\\cite{theil1992RankInvariant, sen1968Estimates}.\nWe then introduce the computation of confidence intervals using Thompson's method~\\cite{thompson1936Confidence}, which requires the data to be \\iid. Thus, to verify this assumption, \\triscale integrates an independence test that we present last.\n\n%-------------------------------------------------------------------------------\n\\fakepar{Convergence test}\n\\label{subsec:test_convergence}\nWhen an evaluation aims to estimate the ``long-running'' performance (\\ie the expected performance if the run would run “forever”), one must verify whether the runs are long enough to produce reliable estimates.\n\n\\squarepar{%\n  To verify this, \\triscale implements a convergence test based on the Theil-Sen linear regression~\\cite{theil1992RankInvariant, sen1968Estimates}.\n  This approach computes the slope of the regression line as the median of all slopes between paired values.\n  A $C$\\% confidence interval (CI) for the slope is defined as the interval containing the middle $C$\\% of slopes between single pairs.\n  \\triscale convergence test is passed if the $C$\\% CI for the regression is included in the tolerance value ($\\pm$\\,$t$\\%).\n  To test the convergence of a run, \\triscale uses the confidence $C$ and tolerance $t$ parameters specified in the evaluation objectives (\\Cref{sec:triscale_overview});\n  otherwise defaults to 95\\% and 5\\%.}\n\nSuch a test is sensitive to the scale of the input data.\nTo remove this dependency, \\triscale first maps the data to $[-1, 1]$ using a linear transformation then performs the convergence test on the scaled data.\nHence, the convergence test becomes dimensionless and the same tolerance value can be used for different evaluations without introducing bias.\nAn example of the Theil-Sen slope (brown, solid), its CI (light orange, solid), and tolerance (black, dotted) is shown in \\Cref{fig:analysis_metric}.\n\n%-------------------------------------------------------------------------------\n\\fakepar{Confidence intervals}\n\\triscale defines KPIs and variability scores based on CIs for distribution percentiles, which can be computed using a robust and non-parametric approach based on Thompson's method~\\cite{thompson1936Confidence}, later shown to be valid for any independent samples of a continuous distribution~\\cite{david2005Order}.\n\nLet us denote by $P_p$, the $p$-th percentile of a distribution and $\\mathbb{P}(X)$ the probability of an event $X$.\nBy definition, every data sample $x$ is smaller than $P_p$ with probability $p$ (and larger with probability $1-p$).\nFor a sorted list of \\iid samples $x_i$ (where $i = 1 .. N$), the probability that $P_p$ lies between two consecutive samples follows the binomial distribution~\\cite{thompson1936Confidence}:\n\\begin{equation}\n    \\mathbb{P}(x_k \\leq P_p \\leq x_{k+1}) = \\binom{N}{k} p^k(1-p)^{N-k}, \\quad k = 0 .. N\n\\end{equation}\nwhere we assume $x_0 \\rightarrow - \\infty$ and $x_{N+1} \\rightarrow +\\infty$. From this result, it follows that the probability of $P_p$ to be larger than any sample $x_m$ (where $1\\leq m < N$) can be computed as:\n\\begin{align}\n  \\nonumber\n    \\mathbb{P}(x_m \\leq P_p)\n      &= \\mathbb{P}(x_{N-m+1} \\geq P_{1-p})\\\\\n  \\label{eq:lb}\n      &= 1 - \\sum_{k=0}^{m-1} \\binom{N}{k} p^k(1-p)^{N-k}\n\\end{align}\n\\Cref{eq:lb} provides the upper- and lower-bound required for computing of CIs.\nFurther, one can derive the minimum number of samples $N$ needed to compute a CI for any percentile $p$ with any confidence level $C$~\\cite{schmid2014measuring}:\n\\begin{equation}\n\\label{eq:minN}\n     \\cref{eq:lb} \\quad \\Rightarrow \\quad N \\;\\geq\\; \\frac{\\log(1-C)}{\\log(1-p)}\n\\end{equation}\nwhich defines the minimum number of runs and series required based on the definitions of the KPIs and the variability scores.\nIf the probability distribution is discrete, \\cref{eq:lb} becomes an inequality ($\\mathbb{P}(x_m \\leq P_p) \\geq \\ldots$~) that provides a safe (\\ie conservative) estimate of which sample $x_m$ is the bound of the CI of interest~\\cite{david2005Order}.\n\n\nThis approach provides robust estimates for distribution percentiles and \\emph{does not make any assumption on the nature of the underlying distribution}.\nIt does, however, require that the data samples are \\iid. \\triscale checks whether this hypothesis holds using an independence test, described below.\n\n%-------------------------------------------------------------------------------\n\\fakepar{Independence test}\nEstimating the percentile of a distribution requires often (if not always) that the samples are \\iid (\\cref{sec:stats}); this is also the case for Thompson's method~\\cite{thompson1936Confidence}.\n\\triscale implements an empirical independence test to verify whether the \\iid assumption holds.\n\n\\begin{remark}\n  Generally, independence results from the experiment design. For networking experiments, however, it is generally not possible to guarantee independence, \\eg the experimental conditions cannot be fully controlled and may be correlated.\n  In such cases, it is common to empirically check whether the data are correlated. If the effective dependence between data samples is sufficiently low, it is considered safe to treat the samples as \\iid.\n\\end{remark}\n\nThis independence test is applied to the metric data (resp. KPI data) before the computation of a KPI (resp. a variability score).\nThis poses the particular challenge that the number of data samples may be very small (\\eg 3 or 5 KPI values). \\triscale's independence test must therefore not be too strict.\n\nThe test is divided in two steps. First, \\triscale tests whether the data appear \\emph{weakly stationary} (\\ie no trend and constant autocorrelation structure~\\cite{brockwell1991Time}). \\triscale verifies this empirically using its convergence test with a confidence of 50\\% and tolerance of 10\\%; these ``loose'' parameters are used to compensate for (very) small sample sizes.\nSecond, \\triscale computes the \\emph{sample autocorrelation coefficients}, denoted by $\\widehat{\\rho_k}$, which measure the linear dependency between values of a weakly stationary data series.\nA series of size $N$ is \\iid with 95\\% probability if $|\\widehat{\\rho_k}| \\leq 1.95/\\sqrt{N}$ for $k \\geq 1$~\\cite{brockwell1991Time}.\n\n\\fakeparQM{What if the tests fail}\nThe experimenter is responsible for designing the evaluation in such a way that the collected data will (likely) pass the tests.\n\\triscale facilitates this by guiding the choice of runtime to pass the convergence test and informing about any network time dependencies~(\\cref{subsec:network_profiling}) to pass the independence test.\nYet, the data may still be correlated or unstable, leading to failing tests (see examples in ~\\cref{sec:triscale_eval}).\nEven in such cases, the data still contain useful information.\n\\triscale metrics, KPIs, or variability scores can be computed, however since the corresponding hypotheses do not hold, the statistics are \\emph{only descriptive}~(\\cref{sec:stats}); they do not predict the expected performance, and in particular they cannot (and should not be used to) assess the reproducibility of the experiment.\n\n%-------------------------------------------------------------------------------\n\\subsection{Network Profiling}\n\\label{subsec:network_profiling}\n\n\\begin{figure}\n    \\centering\n   \t\\href{\\triscalefig{Figure-4}}{\n    \\includegraphics[scale=1]{Figures/plot_flocklab_autocorr.pdf}}\n\n    \\caption{Autocorrelation plot for the wireless link quality on FlockLab, based on the raw data collected by the testbed maintainers~\\cite{jacob2019datasetLQE} (data from August 2019).\n    \\capt{The dataset contains one test every two hours. The first peak at lag 12 (\\ie 24h) reveals the daily seasonal component. The data also show another at lag 84; which corresponds to one week. Indeed, there is less interference in the weekends than on weekdays: this creates a weekly seasonal component.}}\n    \\label{fig:flocklab_autocorr}\n\\end{figure}\n\n\\triscale assists the user in deciding on the time span for a series of runs, \\ie when should the run be performed in a series. This is important to avoid biasing the evaluation results with time dependencies in the experimental conditions.\nIndeed, it is common for real-world networks to exhibit periodic patterns.\nFor example, there may be a lot more cross-traffic (\\ie interference) at specific times. In the statistics literature, these patterns are called \\emph{seasonal components}.\nNeglecting these may result in biased experiments leading to wrong conclusions, as illustrated in the case study below.\n\n\\squarepar{%\n  \\fakepar{Case study: low-power wireless}\n  We run a simple evaluation of Glossy~\\cite{ferrari2011Glossy}, a low-power wireless protocol based on synchronous transmissions~(\\cref{sec:ST}). Glossy includes as parameter the number of retransmissions of a packet, called $N$. We investigate the impact of two values of $N$ on the reliability of Glossy, measured as the packet reception ratio (PRR). We define our KPI as the median with 95\\% confidence level.\n  Refer to \\cref{append:triscale_artifacts} for the complete case study.%\n}\n\nWe collect data using the FlockLab testbed~\\cite{lim2013FlockLab}.\nThis testbed is located in an office building, where we expect more interference during daytime than nighttime.\nThus, we schedule a series of 24 runs randomly within one day.\\linebreak\n  \\inlineitem $N=1$ leads to a PRR of 88\\%,\\\\\n  \\inlineitem $N=2$ leads to a PRR of 84\\%.\\\\\nIn other words, it appears that doing two retransmissions (instead of one) reduces reliability.\n\nThe experiment leads to this (incorrect) conclusion because we have neglected a second seasonal component of the FlockLab testbed: there is a weekly time dependence, revealed by \\Cref{fig:flocklab_autocorr}.\nTo account for this dependency, one must schedule runs with a span of at least one week. When comparing again the performance of Glossy but with tests spanning over a week\\\\\n  \\inlineitem $N=1$ leads to a PRR of 80\\%,\\\\\n  \\inlineitem $N=2$ leads to a PRR of 88\\%,\\\\\nwhich better matches our knowledge about the performance of Glossy.\n\n\\fakepar{Conclusion}\nThis simple example illustrates that using a high confidence level is not enough to avoid drawing wrong conclusions due to the variability in the experimental conditions.\nOn a real network, short-term variations are unpredictable and (often) unavoidable. This is why it is important to perform multiple runs in a series: it increases the chances to do the experiment in the whole range of favorable to unfavorable conditions.\n\nHowever, we illustrated that systematic patterns are also present. In other words, there are times where there is consistently more or less interference. Knowing about these dependencies is important to\n  ensure fairness in the comparison between protocols, and\n  enable reproducibility of the evaluations.\nThe series span must be long enough such that it does not matter when the series actually starts (\\eg a weekend or a weekday)\n\n\\squarepar{%\n  \\triscale integrates a network profiling function that analyzes link quality data (\\eg available at~\\cite{jacob2019datasetLQE}) and searches for seasonal components in the link quality data. This helps the experimenter detecting (sometimes unexpected) time dependencies, thus choosing a suitable time span for series of runs.}\n\n\n%-------------------------------------------------------------------------------\n\\subsection{Assessing Reproducibility}\n\\label{subsec:reproducibility}\n\nReproducibility refers to the ability of obtaining ``the same'' results when performing ``the same'' experiment.\nIn statistics, such property can be investigated using \\textit{equivalence testing}~\\cite{lakens2017Equivalence}, which checks whether the values of some parameter of interest (\\eg the median) obtained for different samples are sufficiently close to be considered ``the same''.\nUnfortunately, there is no general way to define ``sufficiently close''; one must define in advance a threshold for the equivalence test based on expertise.\nThen, how to assess reproducibility of networking experiments? How to design a ``reproducibility test'' that fairly adapts to different networking contexts and different metrics?\nAfter some failed attempts, we conclude that defining a generic threshold for equivalence testing in networking might not be possible. But it may not be necessary.\n\nWe argue that the most important is to confidently estimate the variability of the results, which \\triscale computes with its variability score~(\\cref{subsec:repeatability}).\nThis score \\emph{quantifies reproducibility}: the larger the score, the less reproducible the results are.\nShall a binary cut between ``reproducible'' and ``not reproducible'' be desired, a threshold can be set based on the variability score; \\eg ``Results are said reproducible when the variability score is less than 20\\mbps.''.\nSuch a threshold can only be context-specific; thus, deciding on threshold values relates more to benchmarking and therefore goes beyond the scope of \\triscale~(see discussion in \\cref{sec:going_further}).\n", "meta": {"hexsha": "2ab72eabd9540c4a3d212294f2b68f6a05a4ced0", "size": 28278, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "20_TriScale/4_triscale.tex", "max_stars_repo_name": "romain-jacob/doctoral-theis", "max_stars_repo_head_hexsha": "fd21e9f0cddeda91821eb061c9ab12df9f610da9", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "20_TriScale/4_triscale.tex", "max_issues_repo_name": "romain-jacob/doctoral-theis", "max_issues_repo_head_hexsha": "fd21e9f0cddeda91821eb061c9ab12df9f610da9", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "20_TriScale/4_triscale.tex", "max_forks_repo_name": "romain-jacob/doctoral-theis", "max_forks_repo_head_hexsha": "fd21e9f0cddeda91821eb061c9ab12df9f610da9", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 70.8721804511, "max_line_length": 477, "alphanum_fraction": 0.7332555343, "num_tokens": 6810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.63341027751814, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3463095645783293}}
{"text": "\n\n\\section{Contractual Money}\n    \\label{sec:contractual}\n\n In our opinion, the overwhelming majority of use-cases for public blockchains (even those that claim to provide a general-purpose decentralized world computer) are for financial applications, which do not require Turing-completeness. For instance, if an oracle writes down non-financial data into the blockchain~(such as temperature), this data is usually used further in a financial\n contract. Another trivial observation we make is that many applications use digital tokens with mechanics different from the native token.\n\nFor an application developer, the Ergo Platform offers custom tokens~(which are first-class citizens) and a domain-specific language for writing box protecting\n conditions in order to implement flexible and secure financial applications.\n Ergo applications are defined in terms of protecting scripts built into boxes, which may also contain data involved in the execution.\n We use the term {\\em contractual money} to define Ergs (and secondary tokens) whose usage is bounded by a contract. This applies to all tokens on the platform in existence because any box with its contents~(Ergs, tokens, data) is bounded by a contract.\n \n However, we can distinguish between two types of contractual Ergs. The first, called {\\em free Ergs}, are the ones that could change their contracts easily and have no restrictions on the outputs or the other inputs of a spending transaction. The second type is {\\em bounded Ergs}, whose contracts require the spending transaction to have input and output boxes with specific properties.\n \n For example, if a box $A$ is protected by just a public key~(so providing a signature against a spending transaction is enough in order to destroy the box), the public key owner can spend $A$ and transfer the Ergs to any arbitrary output box. Thus, the Ergs within $A$ are free. \n% to change the contract. \nIn contrast, imagine a box $B$ protected by a combination of a public key and a condition that demands the spending transaction to create an output box with the same amount of Ergs as in $B$ and whose guarding script has the hash \\texttt{rBMUEMuPQUx3GzgFZSsHmLMBouLabNZ4HcERm4N} (in Base58 encoding). In this case, the Ergs in $B$ are bounded Ergs.\n \n Similarly, we can define free and bounded tokens. An Ergo contract can have several hybrids such as bounded Ergs and free tokens or both bounded under one public key and free under another.\n\n\\subsection{Preliminaries For Ergo Contracts}\n\n  While in Bitcoin, a transaction output is protected by a program in a stack-based language named {\\em Script}, in Ergo a box is protected by a logic formula which combines predicates over a context with cryptographic statements provable via zero-knowledge protocols using AND, OR, and $k$-out-of-$n$ connectives. The formula is represented as a typed direct\n acyclic graph, whose serialized form is written in a box. To destroy a box, a spending transaction needs to provide arguments (which include zero-knowledge proofs) satisfying the formula.\n\n However, in most cases, a developer is unlikely to develop contracts in terms of graphs. Instead, he would like to use a high-level language such as ErgoScript, which we provide with the reference client. \n \n Writing scripts in ErgoScript is easy. As an\n example, for a one-out-of-two signature, the protecting script would be ${pk_1 \\|pk_2}$, which means ``prove knowledge of\n a secret key corresponding to the public key $pk_1$ or knowledge of a secret key corresponding to public key $pk_2$''. We have\n two separate documents for help in developing contracts with ErgoScript: the ``ErgoScript Tutorial''~\\cite{ergoTutorial}\n and the ``Advanced ErgoScript Tutorial''~\\cite{ergoAdvTutorial}. Thus, we do not get into the details of developing contracts with ErgoScript. Rather, we provide a couple of motivating examples in the following sections.\n\nTwo more features of Ergo shaping contracting possibilities are:\n\n \\begin{itemize}\n    \\item {\\em Data Inputs: }\n To be used in a transaction, a box need not be destroyed but can instead be read-only. In the latter case, we refer to the box as being part of the {\\em data input} of the transaction. Thus, a transaction gets two box sets as its arguments, the inputs and\n data inputs, and produces one box set named {\\em outputs}. Data inputs are useful for oracle applications and interacting contracts.\n\n    \\item {\\em Custom Tokens: }\n A transaction can carry many tokens as long as the estimated complexity for processing them does not exceed a limit, a parameter that is set by miner voting. A transaction can also issue a single token with a unique identifier which is equal to the identifier of a first~(spendable) input box of the transaction. The identifier is unique assuming the collision resistance of an underlying hash function.\n The amount of the tokens issued could be any number within the range $[1, 9223372036854775807]$. The weak preservation rule is followed for tokens, which requires that the total amount of any token in a transaction's outputs should be no more\n than the total amount of that token in the transaction's inputs~(i.e., some amount of token could be burnt). In contrast, the strong reservation rule is followed for Ergs, which requires that the total amount of Ergs in the inputs and outputs must be the same.\n \\end{itemize}\n\n\\subsection{Contract Examples}\n\\label{sec:examples}\n\n In this section, we provide some examples which demonstrate the superiority of Ergo contracts compared to Bitcoin's. The examples include betting on oracle-provided data, non-interactive mixing, atomic swaps, complementary currency, and an initial coin offering implemented on top of the Ergo blockchain.\n\n \\subsubsection{An Oracle Example}\n \\label{sec:platform}\n\n Equipped with custom tokens and data inputs, we can develop a simple oracle example which also shows some design patterns that we discovered while playing with Ergo contracts. Assume that Alice and Bob want to bet on tomorrow's weather by putting money into a box that becomes spendable by Alice if tomorrow's temperature is more than 15 degrees, and spendable by Bob otherwise. To deliver the temperature into the blockchain, a trusted oracle is needed.\n\n In contrast to Ethereum with its long-lived accounts, where a trusted oracle's identifier is usually known in advance, delivering data with one-time boxes is more tricky. For starters, a box protected by the oracle's key cannot be trusted, as anyone can create such a box. It is possible to include signed data into a box and check the oracle's signature in the contract (we have such an example), but this is quite involved. Instead, a solution with custom\n tokens is very simple.\n\n Firstly, a token identifying the oracle should be issued. In the simplest case, the amount of this token could be one. We call such a token {\\em a singleton token}. The oracle creates a box containing this token along with its data (i.e., the temperature) in register $R_4$ and the UNIX epoch time in register $R_5$.\n In order to update the temperature, the oracle destroys this box and creates a new one with the updated temperature.\n\n Assume that Alice and Bob know the oracle's token identifier in advance. With this knowledge, they can jointly create a box with a contract that requires first (read-only) data input to contain the oracle's token. The contract extracts the temperature and time from the data input\n and decides who gets the payout. The code is as simple as following:\n\n \\begin{algorithm}[H]\n    \\caption{Oracle Contract Example}\n    \\label{alg:oracle}\n    \\begin{algorithmic}[1]\n        \\State val dataInput = CONTEXT.dataInputs(0)\n        \\State val inReg = dataInput.R4[Long].get\n        \\State val inTime = dataInput.R5[Long].get\n        \\State val inToken = dataInput.tokens(0).\\_1 == tokenId\n        \\State val okContractLogic = (inTime $>$ 1556089223) \\&\\&\n        \\State\\hspace{\\algorithmicindent}\\hspace{\\algorithmicindent} ((inReg $>$ 15L \\&\\& pkA) $||$ (inReg $\\le$ 15L \\&\\& pkB))\n        \\State inToken \\&\\& okContractLogic\n    \\end{algorithmic}\n \\end{algorithm}\n\n This contract shows how a singleton token could be used for authentication. As a possible alternative, the oracle\n can put the time and temperature into a box along with a signature on this data. However, this requires signature verification, which is more complex and expensive compared to\n the singleton token approach. Also, the contract shows how read-only data inputs could be useful for contracts which need to access data stored in some other box in the state. Without data inputs, an oracle must issue one spendable box for each\n pair of Alice and Bob. With data inputs, the oracle issues only a single box.\n\n\\subsubsection{A Mixing Example}\n \\label{sec:platform}\n\n Privacy is important for a digital currency but implementing it can be costly or require a trusted setup. Thus, it is desirable to find a cheaper way for coin mixing. As a first step towards that, we offer a non-interactive mixing protocol between two users Alice and Bob that works as follows:\n \\begin{enumerate}\n    \\item{} Alice creates a box which demands the spending transaction to satisfy certain conditions. After that, Alice only listens to the blockchain; no interaction with Bob is needed.\n    \\item{} Bob creates a transaction spending Alice's box along with one of his own to generate two outputs having identical scripts but different data. Each of Alice and Bob may spend only one of the two outputs but an observer decide which output belongs to whom because they look indistinguishable.\n \\end{enumerate}\n\n For simplicity, we do not consider fee in the example. The idea of mixing is similar to non-interactive Diffie-Hellman key exchange. First, Alice generates a secret value $x$~(a huge number) and publishes the corresponding public value $gX = g^x$. She requires Bob to generate a secret number $y$, and to include into each output two\n values $c_1$, $c_2$, where one value is equal to $g^y$ and the other is equal to $g^{xy}$. Bob uses a random coin to choose meanings for $\\{c_1, c_2\\}$. Without access to the secrets, an external observer cannot guess with probability better than  $\\frac{1}{2}$ whether $c_1$ is equal to $g^y$ or to $g^{xy}$. This is assuming that the cryptographic primitive we use has a certain property, that the Decision Diffie-Hellman (DDH) problem is hard. To destroy an output box, a proof should be given that either $y$ is known such that $c_2 = g^y$, or $x$ is known such that $c_2 = c_1^x$.\n The contract of Alice's box checks that $c_1$ and $c_2$ are well-formed. The code snippets for Alice's coin and the mixing transaction's output are provided in Algorithms \\ref{alg:alice} and \\ref{alg:mixing-out} respectively. Since ErgoScript currently doesn't have support for proving knowledge of some $x$ such that $c_2 = {c_1}^x$ for arbitrary $c_1$,  we will prove a slightly longer statement that is supported, namely, proving knowledge of $x$ such that $gX = g^x$ and $c_2 = {c_1}^x$. This is called proveDHTuple.\n\n \\begin{algorithm}[H]\n    \\caption{Alice's Input Script}\n    \\label{alg:alice}\n    \\begin{algorithmic}[1]\n        \\State val c1 = OUTPUTS(0).R4[GroupElement].get\n        \\State val c2 = OUTPUTS(0).R5[GroupElement].get\n        \\State\n        \\State OUTPUTS.size == 2 \\&\\&\n        \\State OUTPUTS(0).value == SELF.value \\&\\&\n        \\State OUTPUTS(1).value == SELF.value \\&\\&\n        \\State blake2b256(OUTPUTS(0).propositionBytes) == fullMixScriptHash \\&\\&\n        \\State blake2b256(OUTPUTS(1).propositionBytes) == fullMixScriptHash \\&\\&\n        \\State OUTPUTS(1).R4[GroupElement].get == c2 \\&\\&\n        \\State OUTPUTS(1).R5[GroupElement].get == c1 \\&\\& \\{\n        \\State\\hspace{\\algorithmicindent}  proveDHTuple(g, gX, c1, c2) $||$\n        \\State\\hspace{\\algorithmicindent}  proveDHTuple(g, gX, c2, c1)\n        \\State \\}\n    \\end{algorithmic}\n \\end{algorithm}\n\n \\begin{algorithm}[H]\n    \\caption{Mixing Transaction Output Script}\n    \\label{alg:mixing-out}\n    \\begin{algorithmic}[1]\n        \\State val c1 = SELF.R4[GroupElement].get\n        \\State val c2 = SELF.R5[GroupElement].get\n        \\State proveDlog(c2) $||$            // either c2 is $g^y$\n        \\State proveDHTuple(g, c1, gX, c2) // or c2 is $u^y = g^{xy}$\n    \\end{algorithmic}\n \\end{algorithm}\n\n We refer the reader to \\cite{ergoAdvTutorial} for a proof of indistinguishability of the outputs and details on why Alice and Bob can spend only their respective coins.\n\n\n\\subsubsection{More Examples}\n\n In this section, we briefly shed light on a few more examples along with links to the documents providing the details and code.\n\n\\paragraph{Atomic Swap}\nCross-chain atomic swap between Ergo and any blockchain that supports payment to either SHA-256 or Blake2b-256 hash preimages and time-locks can be done in a similar way to that proposed for Bitcoin~\\cite{Nol13}. An Ergo alternative implementation is provided in~\\cite{ergoTutorial}. As Ergo also has custom tokens, atomic exchange on the single Ergo blockchain (Erg-to-token or token-to-token) is also possible. An implementation for this can also be found in~\\cite{ergoTutorial}.\n\n\\paragraph{Crowdfunding}\n\n We consider the simplest crowdfunding scenario. In this example, a crowdfunding project with a known public key is considered successful if it can collect unspent outputs with a total value not less than a certain amount before a certain height. A project backer creates an output box protected by the following statement: the box can be spent\n if the spending transaction has the first output box protected by the project's key and amount no less than the target amount.\n Then the project can collect (in a single transaction) the biggest backer output boxes with a total value not less than the target amount~(it is possible to collect up to ~22,000 outputs, which is\n enough even for a big crowdfunding campaign). For the remaining outputs, it is possible to construct follow-up transactions. The code can be found in~\\cite{ergoTutorial}.\n\n\\paragraph{The Local Exchange Trading System}\n\n Here we briefly demonstrate a Local Exchange Trading System (LETS) in Ergo. In such a system, a member of a community may issue community currency via personal debt. For example, if Alice with zero balance is buying something for $5$\n community tokens from Bob, whose balance is zero as well, her balance after the trade would be $-5$ tokens, and\n Bob's balance would be $5$ tokens. Then Bob can buy something using his $5$ tokens, for example, from Carol.\n Usually, in such systems, there is a limit on negative balances (to avoid free-riding).\n\n Since a digital community is vulnerable to Sybil attacks~\\cite{sybilDef}, some mechanism is needed to prevent such attacks where Sybil nodes create debts.\n The simplest solution is to use a committee of trusted managers that approve new members of the community. A trust-less but more complex solution is to use security deposits made in Ergs. For simplicity, we consider the approach with the committee here.\n\n This example contains two interacting contracts. A {\\em management contract} maintains a list of community members, and a new member can be added if some management condition is satisfied  (for example, a threshold\n signature is provided). A new member is associated with a box containing a token that identifies the member. This box, which contains the {\\em member contract}, is protected by a special exchange script that requires the spending transaction to do a fair exchange.\n We skip the corresponding code, which can be found in a separate article~\\cite{letsTutorial}.\n \n What this contract shows, in contrast to the previous example, is that instead of storing the members list, only a short digest of an authenticated AVL+ tree can be included in the box. This allows a reduction in storage requirements for the state. A transaction doing lookup or modification of the member list should provide a proof for AVL+ tree lookup or modification operations. Thus, saving space in the state storage leads to bigger transactions, but this scalability problem is easier to solve.\n\n\\paragraph{Initial Coin Offering}\n\n We discuss an Initial Coin Offering (ICO) example that shows how multi-stage contracts can be created in Ergo. Like most ICOs, our example has three stages. In the first stage, the project raises money in Ergs. In the second stage, the project issues a new token, whose amount equals the number of nanoErgs raised in the first stage. In the third stage, the investors can withdraw issued tokens.\n\n Note that the first and third stages have many transactions on\n the blockchain, while a single transaction is enough for the second stage. Similar to the previous example, the ICO contract uses an AVL+ tree to store the list of (investor, amount) pairs. The complete code is available at~\\cite{icoTutorial}.\n\n\n\\paragraph{More Examples}\n\n We have even more examples of Ergo applications in \\cite{ergoTutorial, ergoAdvTutorial}. These examples include time-controlled emission, cold wallets contracts, rock-paper-scissors game, and many others.\n", "meta": {"hexsha": "0e30bddf0473061b8dca681af6ef04d77d105f07", "size": 17101, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "papers/whitepaper/money.tex", "max_stars_repo_name": "scasplte2/ergo", "max_stars_repo_head_hexsha": "9964f415526f491a4837774d80b59792e1e2b8bb", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 424, "max_stars_repo_stars_event_min_datetime": "2017-07-17T12:33:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:33:57.000Z", "max_issues_repo_path": "papers/whitepaper/money.tex", "max_issues_repo_name": "scasplte2/ergo", "max_issues_repo_head_hexsha": "9964f415526f491a4837774d80b59792e1e2b8bb", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 886, "max_issues_repo_issues_event_min_datetime": "2017-07-20T21:59:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T10:21:25.000Z", "max_forks_repo_path": "papers/whitepaper/money.tex", "max_forks_repo_name": "scasplte2/ergo", "max_forks_repo_head_hexsha": "9964f415526f491a4837774d80b59792e1e2b8bb", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 131, "max_forks_repo_forks_event_min_datetime": "2017-07-19T12:46:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T01:08:16.000Z", "avg_line_length": 98.2816091954, "max_line_length": 586, "alphanum_fraction": 0.7703058301, "num_tokens": 3937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.34630956457832923}}
{"text": "\\subsection{Pulsar Accelerations}\n\n\\textbf{key}: \\texttt{/pulsar}\n\n\\subsubsection{Datasets}\n\n\\begin{center}\n\\begin{table}[H]\n\\begin{tabular}{ | c | c | c | c | }\n    \\hline\n    Variable & Dataset Name & Supplementary Datasets &  attributes \\\\\n    \\hline\\hline\n    Radial distance & \\texttt{r\\(^*\\)} & & \\texttt{unit} \\\\\n    \\hline\n    Spin period & \\texttt{P\\(^*\\)} & \\texttt{\\(\\Delta\\)P} & \\texttt{unit}\\\\\n    \\hline\n    Spin period derivative & \\texttt{Pdot\\_meas\\(^*\\)} &\n    \\texttt{\\(\\Delta\\)Pdot\\_meas\\(^*\\)} & \\texttt{unit} \\\\\n    \\hline\n    Orbital period & \\texttt{Pb\\(^*\\)} & \\texttt{\\(\\Delta\\)Pb} & \\texttt{unit}\\\\\n    \\hline\n    Orbital period derivative & \\texttt{Pbdot\\_meas\\(^*\\)} &\n    \\texttt{\\(\\Delta\\)Pbdot\\_meas\\(^*\\)} & \\texttt{unit} \\\\\n    \\hline\n    Dispersion Measure & \\texttt{DM} & \\texttt{\\(\\Delta\\)DM} & \\texttt{unit} \\\\\n    \\hline\n    Pulsar identifier & \\texttt{id} & & \\\\\n    \\hline\n\\end{tabular}\n\\caption*{\n    Pulsars can be fit on the timing solutions of both the isolated\n    pulsar spin (P, Pdot\\_meas) and the binary systems orbit (Pb, Pbdot).\n    The period, derivative and corresponding errors are required for either.\n    Optionally, the dispersion measure (DM) can be used to provide a better\n    acceleration constraint, where available.\n}\n\\end{table}\n\\end{center}\n\n\\subsubsection{Attributes}\n\n\n\\begin{center}\n\\begin{table}[H]\n\\begin{tabular}{ | c | c | }\n    \\hline\n    Attribute & Description \\\\\n    \\hline\\hline\n    \\texttt{source} & Literature source(s) of data \\\\\n    \\hline\n    \\texttt{m} & Mean stellar mass of tracer stars [\\(M_\\odot\\)] \\\\\n    \\hline\n\\end{tabular}\n\\end{table}\n\\end{center}\n", "meta": {"hexsha": "eeea83b5152c7b60c0ee1cde1214b3f570bf9a27", "size": 1640, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/source/raws/DPC/DP_pulsar.tex", "max_stars_repo_name": "pjs902/GCfit", "max_stars_repo_head_hexsha": "f26f004bb9caf7429cbae23a6ca559fad42f3498", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-22T17:54:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T17:54:07.000Z", "max_issues_repo_path": "docs/source/raws/DPC/DP_pulsar.tex", "max_issues_repo_name": "pjs902/GCfit", "max_issues_repo_head_hexsha": "f26f004bb9caf7429cbae23a6ca559fad42f3498", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-02-09T16:04:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T17:44:09.000Z", "max_forks_repo_path": "docs/source/raws/DPC/DP_pulsar.tex", "max_forks_repo_name": "pjs902/GCfit", "max_forks_repo_head_hexsha": "f26f004bb9caf7429cbae23a6ca559fad42f3498", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-07T21:21:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T21:21:24.000Z", "avg_line_length": 29.2857142857, "max_line_length": 80, "alphanum_fraction": 0.6268292683, "num_tokens": 553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.63341026367784, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.3463095570113093}}
{"text": "\\hypertarget{premium-allocation-and-default-priority-rules}{%\n\\section{Premium Allocation and Default Priority\nRules}\\label{premium-allocation-and-default-priority-rules}}\n\nNov 25, 2018\n\nDerived from MM\\_2RM\n\n\\hypertarget{three-important-differentials-homogeneous-case}{%\n\\subsection{Three important differentials (homogeneous\ncase)}\\label{three-important-differentials-homogeneous-case}}\n\nFrom Tasche and other references. Let \\(X_u=X=u_1X_1 + u_2X_2\\) be a\nhomogeneous portfolio.\n\nThe deriviative of the survival function \\(S_u(t)=\\text{Pr}(X_u>t)\\) is\n\\[\n\\nabla_u S(t) = \\text{E}[X_i 1_{\\{X=t\\}}] = \\text{E}[X_i \\mid X=t] f_u(t)\n\\] where \\(f_u\\) is the sensity of \\(X_u\\).\n\nThe deriviative of value at risk \\(Q(u)\\) for \\(X_u\\) at a fixed\nthreshold \\(p\\) is \\[\n\\nabla_u Q(u) = E[X_i\\mid \\sum u_ix_i = Q(u,p)]\n\\]\n\nThe deriviative of tail value at risk \\(T\\) is \\[\n\\nabla_u T(u) = E[X_i\\mid \\sum u_ix_i>Q(u,p)]\n\\]\n\n\\hypertarget{method-a}{%\n\\subsection{Method A}\\label{method-a}}\n\nFor M\\textbf{A}jor :-)\n\nHomogeneous portfolio \\(X_u=X=u_1X_1 + u_2X_2\\).\n\nRegulatory capital measure \\(\\alpha\\), typically VaR or TVaR.\n\\textbf{Assume \\(\\alpha=\\)TVaR} at a threshold \\(p\\) close to 1. Thus\n\\(\\alpha(X_u) = \\text{E}[X\\mid X > F_u^{-1}(p)]\\). Total assets\n\\(\\alpha\\) have a natural co-measure allocation given by\n\\(\\alpha_i(X_u)= \\text{E}[u_iX_i \\mid X_u > F_u^{-1}(p)] = u_i \\partial T/\\partial u_i\\).\n\nDistortion \\(g\\) determines market pricing for risk transfer, via\n\\(E_g(X) = \\int g(S_X(t))dt\\).\n\nPrice is determined by using \\(g\\) to price\n\\(X\\wedge \\alpha(X):=\\text{min}(X, \\alpha(X))\\).\n\nThe resulting pricing functional \\(\\pi\\) can be written in several ways.\nLet \\(F_u^{-1}\\) be the quantile function (i.e.~value at risk) of\n\\(X_u\\). Then \\[\n\\begin{align}\n\\pi(X_u) &= \\int_0^{\\alpha(X)} g(S_u(t))dt \\\\\n&= \\text{E}[(X_u\\wedge \\alpha(X_u)) g'(S_u(X)] \\\\\n&= \\int_0^1 (F_u^{-1}(p)\\wedge \\alpha(X_u)) g'(1-p)dp. \\\\\n\\end{align}\n\\]\n\nWe both agree that, subject to certain continuity and differentiability\nassumptions, \\[\n\\begin{align}\n\\frac{\\partial\\pi}{\\partial u_i}(u) &= \\text{E}\\left[\\left(X_i 1_{\\{X\\le \\alpha\\}} + E[X_i\\mid X >  F_u^{-1}(p)]1_{\\{X > \\alpha\\}}\\right) g'(S_u(X_u) \\right] \\\\\n&= \\text{E}[ X_i g'(S(X)) \\mid X \\le \\alpha](1-g(S(\\alpha)))+ \\text{E}[X_i \\mid X > F_u^{-1}(p)]g(S(\\alpha)).\\\\\n\\end{align}\n\\] The premium for line \\(i\\) is \\(u_i\\partial\\pi / \\partial u_i\\) in\nthe usual way. Euler implies the premium ``adds-up'' because the\nportfolio is homogeneous.\n\nThe result can be seen in a couple of ways. From the first defintion of\n\\(\\pi\\) as an \\(\\int_0^\\alpha\\) and the three differentials noted above\nwe get \\[\n\\begin{align}\n\\nabla_u\\pi &= \\int_0^{\\alpha(X)} \\nabla_u(g(S_u(t)))dt + g(S_u(\\alpha))\\nabla_u\\alpha(u) \\\\\n&=\\int_0^{\\alpha(X)} g'(S_u(t))\\text{E}[X_i 1_{\\{X=t\\}}] dt + g(S_u(\\alpha))E[X_i\\mid X> F_u^{-1}(p) ] \\\\\n&=\\int_0^{\\alpha(X)} g'(S_u(t))\\text{E}[X_i \\mid X=t] f_u(t) dt + g(S_u(\\alpha))E[X_i\\mid X> F_u^{-1}(p) ] \\\\\n&=\\text{E}\\left[\\left(X_i 1_{\\{X\\le \\alpha\\}} + E[X_i\\mid X> F_u^{-1}(p)]1_{\\{X > \\alpha\\}}\\right) g'(S_u(X)) \\right]\n\\end{align}\n\\] where the last line follows from the conditional expectation (tower\nproperty) formula. Notice that the default expectation is take wrt\n\\(X>F_u^{-1}(p)\\) whereas the outside integral is split at tvar.\n\nAlternatively using the third definition of \\(\\pi\\) \\[\n\\begin{align}\n\\nabla_u\\pi\n&= \\nabla_u \\int_0^1 (F_u^{-1}(p)\\wedge \\alpha(u)) g'(1-p)dp  \\\\\n&= \\int_0^1 \\left(\\nabla_u F_u^{-1}(p) 1_{\\{X_u\\le \\alpha\\}} +\n            \\nabla_u \\alpha(u) 1_{\\{X_u > \\alpha\\}}\\right) g'(1-p)dp  \\\\\n&= \\int_0^{F(\\alpha)} \\text{E}[X_i \\mid X=F_u^{-1}(p) ] g'(1-p)dp + \\text{E}[X_i \\mid X> F_u^{-1}(p)] g(S(\\alpha)) \\\\\n&= \\int_0^{\\alpha} \\text{E}[X_i \\mid X=t ] g'(S(t))f(t)dt + \\text{E}[X_i \\mid X> F_u^{-1}(p)] g(S(\\alpha)) \\\\\n&= \\text{E}\\left[ \\text{E}[X_i \\mid X ]1_{\\{X\\le\\alpha\\}} g'(S(X_u)) \\right]\n+ \\text{E}[X_i \\mid X> F_u^{-1}(p)] g(S(\\alpha)) \\\\\n&= \\text{E}\\left[ X_i 1_{\\{X\\le\\alpha\\}} g'(S(X_u)) \\right]\n+ \\text{E}[X_i \\mid X> F_u^{-1}(p)] g(S(\\alpha)) \\\\\n\\end{align}\n\\] It is important that \\(g'(1-p)\\) \\emph{does not depend on \\(u\\)}. The\ndependence on \\(u\\) has been subsumed into the re-ordering defined by\n\\(F_u^{-1}\\). The fourth line follows from the third via substituting\n\\(F(t)=p\\).\n\n\\hypertarget{properties-of-method-a}{%\n\\subsubsection{Properties of Method A}\\label{properties-of-method-a}}\n\n\\begin{itemize}\n\\tightlist\n\\item\n  \\textbf{Assumes and relies critically on homogeneity}\n\\item\n  Result is independent of the default rule\n\\item\n  Produces core of fuzzy game and only measure consistent with\n  performance management. (In fuzzy game approach there is an assumption\n  that the underlying risks can be fractionally quota shared, not that\n  they are homogeneous themselves.)\n\\end{itemize}\n\n\\hypertarget{method-b}{%\n\\subsection{Method B}\\label{method-b}}\n\nPortfolio \\(X(u)\\) that may or may not be homogeneous. An inhomogenous\nexample is \\(X(u)=X_1(u_1) + X_2(u_2)\\) where \\(X_i(u_i)\\) is a compound\nPoisson distribution with expected claim count \\(u_i\\).\n\nRegulatory capital \\(\\alpha\\) determined by TVaR. Same distortion \\(g\\)\ndetermines cost of risk transfer.\n\nThe insurer sells the residual value of the risk when supported by\nassets of \\(a\\) to the capital markets for a premium \\(P(a)\\). The sale\nis structured by tranche, so the premium is an integral of the premium\ndensity. For a layer attaching at \\(x\\) (i.e.~a layer \\(x\\) to \\(x+dx\\))\nthe expected loss cost is \\(S(x)dx\\). As is well known, the expected\nlosses upto total capital \\(a\\) are given by \\[\n\\int_0^a S(x)dx.\n\\] The distortion function \\(g\\) prices the layer at \\(x\\) as\n\\(g(S(x))\\). Therefore the total premium is \\[\nP(a) = \\int_0^a g(S(x))dx.\n\\] The premium density is therefore \\[\nP'(x) = \\frac{dP}{da} = g(S(x)).\n\\]\n\nThe insurer now faces the problem of allocating the premium\n\\(P(\\alpha(X))\\) back to lines 1 and 2. Use a co-measure approach---this\nis exavtly what our spreadsheet did in the CAS sessions! We have a\nstable world, with \\(u_1,u_2\\) are fixed. The pricing distortion\nfunction \\(g\\) combined with fixed \\(X\\) gives a probability distortion\n\\(g'(S(X))\\), i.e.~and \\(E_{\\Bbb{Q}}[X] := E[Xg'(S(X))]\\). Standard\nfinance theory says that in this situation, with a linear pricing rule,\nwe price any payoff \\(Y\\) by \\$\nE\\_\\{\\Bbb{Q}\\}{[}Y{]}=E{[}Yg'(S(X)){]}\\$.\n\nWe have to specify the payoff to line \\(i\\) when the insurer only has\nassets \\(a\\). Consider two possibilities.\n\n\\begin{enumerate}\n\\def\\labelenumi{\\arabic{enumi}.}\n\\tightlist\n\\item\n  The two lines have equal priority in event of default. The payment to\n  line \\(i\\) is \\[\n  X_i(a):=\n  \\begin{cases}\n  X_i & X \\le a \\\\\n  X_i\\frac{a}{X} & X > a \\\\\n  \\end{cases}\n  = X_i \\frac{X\\wedge a}{X}.\n  \\]\n\\item\n  Line 2 has lower priority than line 1. In this case the payout to line\n  1 is \\(X_1\\wedge a\\) and the payout to line 2 is \\[\n  X_2(a):=\n  \\begin{cases}\n  X_2    & X \\le a \\\\\n  a-X_1  & X_1 \\le a < X  \\\\\n  0      & X_1 > a.\n  \\end{cases}\n  \\]\n\\end{enumerate}\n\nIn the case of equal priority the expected recovery to line \\(i\\) when\nthe insurer has assets \\(a\\) is \\[\n\\begin{align}\n\\text{E}[X_i(a)] &= \\text{E}[X_i \\mid X \\le a ]F(a) + a \\text{E}\\left[\\frac{X_i}{X} \\mid X > a \\right] S(a) \\\\\n&= \\text{E}\\left[ X_i\\frac{X\\wedge a}{X} \\right].\n\\end{align}\n\\] From the second expression it is obvious this is an additive\nallocation---in all cases, not just when \\(X\\) is a homogeneous family.\n\nFinance theory now tells us the price of the contingent payout\n\\(X_i(\\alpha)\\) is \\[\n\\begin{align}\nP_i(u)=P_i(\\alpha(X_u) &= \\text{E}_{\\Bbb{Q}}\\left[  X_i\\frac{X\\wedge a}{X} \\right] \\\\\n&= \\text{E}\\left[  X_i\\frac{X\\wedge a}{X} g'(S(X)) \\right] \\\\\n&= \\text{E}\\left[ \\text{E}\\left[  X_i\\frac{X\\wedge a}{X} g'(S(X)) \\mid X \\right] \\right] \\\\\n&= \\text{E}\\left[ \\text{E}\\left[\\frac{X_i}{X}\\mid X \\right] (X\\wedge a) g'(S(X)) \\right] \\\\\n&= \\text{E}\\left[ \\text{E}\\left[ X_i \\mid X \\le \\alpha \\right] g'(S(X)) \\right] (1-g(S(\\alpha)))\n    + a\\text{E}\\left[ \\text{E}\\left[\\frac{X_i}{X}\\mid X>\\alpha \\right] g'(S(X)) \\right] g(S(\\alpha)) \\\\\n&= \\text{E}\\left[ X_i 1_{\\{X \\le \\alpha \\}} g'(S(X)) \\right]\n    + a\\text{E}\\left[ \\frac{X_i}{X} g'(S(X)) 1_{\\{ X>\\alpha\\}} \\right] \\\\\n&= \\text{E}_{\\Bbb{Q}}\\left[ X_i 1_{\\{X \\le \\alpha \\}} + a \\frac{X_i}{X} 1_{\\{ X>\\alpha\\}} \\right] \\\\\n\\end{align}\n\\]\n\nThe price component when the insurer remains solvent is the same as for\nMethod A. However the value of the payment made in the event of\ninsolvency is different---and depends on the explicit default\nassumption: \\[\n\\begin{align}\n\\text{Method A: } & \\text{E}[X_i | X > \\alpha]g(S(\\alpha) \\\\\n\\text{Method B: } & a\\text{E}\\left[ \\frac{X_i}{X} g'(S(X)) \\mid X>\\alpha \\right] g(S(\\alpha))\n= a\\text{E}\\left[ \\text{E}[\\frac{X_i}{X} \\mid X] g'(S(X)) 1_{\\{ X>\\alpha\\}} \\right] \\\\\n\\end{align}\n\\]\n\nIn method A the expectation is the allocation of total assets \\(\\alpha\\)\nto line \\(i\\).\n\nSimilar calculations can be performed for the case Line 2 has lower\npriority.\n\n\\hypertarget{properties-of-method-b}{%\n\\subsubsection{Properties of Method B}\\label{properties-of-method-b}}\n\n\\begin{itemize}\n\\tightlist\n\\item\n  Does \\textbf{not} assume or rely on homogeneity\n\\item\n  Result dependents particular the default rule\n\\end{itemize}\n", "meta": {"hexsha": "a05d737e83f185a73986159b98657260d53235ab", "size": 9236, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "examples/dm.tex", "max_stars_repo_name": "mynl/aggregate", "max_stars_repo_head_hexsha": "48ab306fb9d19f08d6d42112490fc305c376ca8d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-01-07T13:42:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-23T19:46:55.000Z", "max_issues_repo_path": "examples/dm.tex", "max_issues_repo_name": "mynl/aggregate", "max_issues_repo_head_hexsha": "48ab306fb9d19f08d6d42112490fc305c376ca8d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/dm.tex", "max_forks_repo_name": "mynl/aggregate", "max_forks_repo_head_hexsha": "48ab306fb9d19f08d6d42112490fc305c376ca8d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3318777293, "max_line_length": 160, "alphanum_fraction": 0.6474664357, "num_tokens": 3351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.3463095570113093}}
{"text": "Having outlined a variety of models and metrics tracked for the\npurposes of their objective comparison, we proceed to present and discuss our\nresults in the next sections.\n\n\n\\subsection{Results of Decoupled Sampling}\n\\label{sec:modelres}\n\nWe begin by comparing the performance of a diverse set of surrogate families on previously generated samples of the expensive MC TBR model.\nThrough the four experimental cases described\nin~\\cref{sec:experiment-methodology}, we aim to study properties of the\nconsidered models in terms of regression performance, training and prediction\ntime.\n\n\n\\subsubsection{Hyperparameter Tuning}\n\nThe first two experiments perform Bayesian optimisation to maximise~$R^2$ in\na cross-validation setting as a function of model hyperparameters. While in the\nfirst experiment we limit training and test sets to the scope of four selected\nslices of the feature space, in the second experiment we lift this restriction\nto examine surrogate capability to model a more complex domain.\n\nThe results displayed in~\\cref{fig:exp1-time-vs-reg} (and listed\nin~\\cref{tbl:exp1-detailed-results} in the Appendix) indicate that in the first\nexperiment, GBTs clearly appear to be the most accurate as\nwell as the fastest surrogate family in terms of mean prediction time. Following\nthat, we note that ERTs, SVMs and ANNs also achieved satisfactory results with respect to both examined metrics.\nWhile the remainder of tested surrogate families does not exhibit problems in\ncomplexity, its regression performance falls below average.\n\n\\begin{figure}[h]\n\t\\centering\n\t\\begin{subfigure}[b]{0.333\\textwidth}\n\t\t\\centering\n\t\t\\includegraphics[width=\\linewidth]{exp1_slice0}\n\t\t\\caption{Run 2, batches 0-2}\n\t\\end{subfigure}\\hfill%\n\t\\begin{subfigure}[b]{0.333\\textwidth}\n\t\t\\centering\n\t\t\\includegraphics[width=\\linewidth]{exp1_slice1}\n\t\t\\caption{Run 2, batches 100-102}\n\t\\end{subfigure}\\hfill%\n\t\\begin{subfigure}[b]{0.333\\textwidth}\n\t\t\\centering\n\t\t\\includegraphics[width=\\linewidth]{exp1_slice2}\n\t\t\\caption{Run 2, batches 200-202}\n\t\\end{subfigure}\n\t\\caption{20~best-performing surrogates per each considered family, plotted in\n\t\tterms of complexity (as~$\\overline{t}_{\\text{pred.}}$) and regression\n\t\tperformance (as~$R^2$) on selected slices of run~2, evaluated in\n\texperiment~1. Here, batches refer to subsets of training and test datasets that\n\tmay be matched to slices using~\\cref{tbl:slices}.}\n\t\\label{fig:exp1-time-vs-reg}\n\\end{figure}\n\nThe results of the second experiment, shown in~\\cref{fig:exp2-time-vs-reg} (and listed\nin~\\cref{tbl:exp2-detailed-results} in the Appendix),\nseem to confirm our expectations. Compared to the previous case, we observe\nthat many surrogate families consistently achieved worse regression\nperformance and prediction times. The least\naffected models appear to be GBTs, ANNs and ERTs, which are known to be capable of capturing relationships\ninvolving mixed feature types that were deliberately withheld in the first\nexperiment. With only negligible differences, the first two of these families\nappear to be tied for the best performance as well as the shortest prediction\ntime. We observe that ERTs and RBFs also\ndemonstrated satisfactory results, relatively outperforming the remaining surrogates in\nterms of regression performance, and in some cases also in prediction time.\n\n\\begin{wrapfigure}[10]{r}{0.333\\textwidth}\n\t\\centering\n\t\\vspace{-2ex}\n\t\\includegraphics[width=\\linewidth]{exp2_time_vs_reg}\n\t\\caption{Results of experiment~2, plotted analogously\n\tto~\\cref{fig:exp1-time-vs-reg}.}\n\t\\label{fig:exp2-time-vs-reg}\n\\end{wrapfigure}\n\nFollowing both hyperparameter tuning experiments, we conclude that while domain\nrestrictions employed in the first case have proven effective in improving the\nregression performance of some methods, this result has fluctuated considerably\ndepending on the selected slices. Furthermore, in all instances the best\nresults were achieved by families of surrogates that were nearly unaffected by\nthis modification.\n\n\n\\subsubsection{Scaling Benchmark}\n\nIn the third experiment we examine surrogate scaling properties by correlating\nmetrics of interest with training set size. Firstly, the results shown \nin~\\cref{fig:scaling-r2} (and listed in~\\cref{tbl:exp3-detailed-results-r2} in\nthe Appendix) suggest that the most accurate families from the previous experiments\nconsistently maintain their relative advantage over others, even as we introduce\nmore training points. While such families achieve nearly comparable\nperformance on the largest dataset, in the opposite case tree-based approaches\nclearly outperform ANNs. This can be observed\nparticularly on sets of sizes up to~\\num{6000}.\n\n\\begin{figure}[h]\n\t\\centering\n\t\\begin{subfigure}[b]{0.333\\textwidth}\n\t\t\\centering\n\t\t\\includegraphics[width=\\linewidth]{scaling_metric_r2}\n\t\t\\caption{Regression performance (as $R^2$)}\n\t\t\\label{fig:scaling-r2}\n\t\\end{subfigure}\\hfill%\n\t\\begin{subfigure}[b]{0.333\\textwidth}\n\t\t\\centering\n\t\t\\includegraphics[width=\\linewidth]{scaling_time_train}\n\t\t\\caption{Complexity (as~$\\overline{t}_{\\text{trn.}}$)}\n\t\t\\label{fig:scaling-trn}\n\t\\end{subfigure}\\hfill%\n\t\\begin{subfigure}[b]{0.333\\textwidth}\n\t\t\\centering\n\t\t\\includegraphics[width=\\linewidth]{scaling_time_pred}\n\t\t\\caption{Complexity (as~$\\overline{t}_{\\text{pred.}}$)}\n\t\t\\label{fig:scaling-pred}\n\t\\end{subfigure}\n\t\\caption{Various metrics collected during experiment 3 (scaling\n\tbenchmark) displayed as a function of training set size.}\n\t\\label{fig:scaling}\n\\end{figure}\n\nNext, we examine scaling behaviour in terms of the mean training time (displayed\nin~\\cref{fig:scaling-trn} and listed in~\\cref{tbl:exp3-detailed-results-t-train} in\nthe Appendix). Consistent with our expectation, the shortest times\nwere achieved by instance-based learning methods (e.g. KNN, IDW) that\nare trained trivially at the expense of increased lookup complexity later during prediction.\nFurthermore, we observe that the majority of tree-based algorithms also perform\nand scale well, unlike RBFs and GPR which appear to behave superlinearly. We note that ANNs,\nwhich are the only family to utilise parallelisation during training, show an\ninverse scaling characteristic. Our conjecture is that this effect may be caused\nby a constant multi-threading overhead that possibly dominates the training process\non relatively small training sets.\n\nFinally, we study scaling with respect to the mean prediction time (shown\nin~\\cref{fig:scaling-pred} and listed in~\\cref{tbl:exp3-detailed-results-t-pred} in\nthe Appendix). Our initial observation is that all tested\nfamilies with the exception of previously mentioned instance-based\nmodels offer desirable characteristics overall. Analogous to previous\nexperiments, GBTs, ABTs and ANNs appear to be tied, as they not only exhibit\ncomparable times but also similar scaling slopes. Following that, we notice a\nclear hierarchy of ERTs, SVMs, GPR and RBFs, trailed by IDW and KNNs.\n\n\n\\subsubsection{Model Comparison}\n\nIn the fourth experiment proposed\nin~\\cref{sec:experiment-methodology}, we exploit previously collected information\nto produce surrogates with desirable properties for practical use. We\naim to create models that yield: (a)~the best regression performance regardless\nof other features, (b)~acceptable performance with the shortest mean\nprediction time, or (c)~acceptable performance with the smallest training set.\nTo this end, we trained 8~surrogates that are presented in~\\cref{fig:reg-performance}\nand~\\cref{tbl:exp4-detailed-results}.\n\n\\begin{figure}[h]\n\t\\centering\n\t\\begin{subfigure}[b]{0.25\\textwidth}\n\t\t\\centering\n\t\t\\includegraphics[width=\\linewidth]{exp4_model6}\n\t\\end{subfigure}\\hfill%\n\t\\begin{subfigure}[b]{0.25\\textwidth}\n\t\t\\centering\n\t\t\\includegraphics[width=\\linewidth]{exp4_model7}\n\t\\end{subfigure}\\hfill%\n\t\\begin{subfigure}[b]{0.25\\textwidth}\n\t\t\\centering\n\t\t\\includegraphics[width=\\linewidth]{exp4_model1}\n\t\\end{subfigure}\\hfill%\n\t\\begin{subfigure}[b]{0.25\\textwidth}\n\t\t\\centering\n\t\t\\includegraphics[width=\\linewidth]{exp4_model3}\n\t\\end{subfigure}\n\n\t\\begin{subfigure}[b]{0.25\\textwidth}\n\t\t\\centering\n\t\t\\includegraphics[width=\\linewidth]{exp4_model4}\n\t\\end{subfigure}\\hfill%\n\t\\begin{subfigure}[b]{0.25\\textwidth}\n\t\t\\centering\n\t\t\\includegraphics[width=\\linewidth]{exp4_model5}\n\t\\end{subfigure}\\hfill%\n\t\\begin{subfigure}[b]{0.25\\textwidth}\n\t\t\\centering\n\t\t\\includegraphics[width=\\linewidth]{exp4_model2}\n\t\\end{subfigure}\\hfill%\n\t\\begin{subfigure}[b]{0.25\\textwidth}\n\t\t\\centering\n\t\t\\includegraphics[width=\\linewidth]{exp4_model8}\n\t\\end{subfigure}\n\t\\caption{Regression performance of models 1-4 (row 1, from the left) and 5-8\n\t\t(row 2) trained in experiment~4 (model comparison), viewed\n\t\tas true vs.~predicted TBR on a test set of a selected cross-validation\n\t\tfold. Points are coloured by density.}\n\t\\label{fig:reg-performance}\n\\end{figure}\n\nHaving selected ANNs, GBTs, ERTs, RBFs and SVMs based on the results of\nexperiments~2-3, we utilised the best-performing hyperparameters.\nIn pursuit of goal~(a), the best approximator (no.~1,\nANN) achieved~$R^2=\\num{0.998}$ and mean prediction\ntime~$\\overline{t}_{\\text{pred.}}=\\SI{1.124}{\\micro\\second}$. These correspond\nto a standard error~$S=\\num{0.013}$ and a relative speedup~$\\omega=\\num{6916416} \\times$\nwith respect to the MC TBR evaluation baseline measured during run~1\n(see~\\cref{tbl:sampling-runs} for details). Satisfying\ngoal~(b), the fastest model (no.~2, ANN) achieved~$R^2=\\num{0.985}$,\n$\\overline{t}_{\\text{pred.}}=\\SI{0.898}{\\micro\\second}$, $S=\\num{0.033}$\nand~$\\omega=\\num{8659251} \\times$.\nWhile these surrogates\nwere trained on the entire available set of~\\num{500000} datapoints, to satisfy\ngoal~(c) we also trained a more simplified model (no.~4, GBT)\nthat achieved~$R^2=\\num{0.913}$,\n$\\overline{t}_{\\text{pred.}}=\\SI{6.125}{\\micro\\second}$, $S=\\num{0.072}$ and $\\omega=\\num{1269777} \\times$\nwith a set of size only~\\num{10000}.\n\n\\begin{table}[h]\n\t\\centering\n\t\\sisetup{round-mode=places,round-precision=3,detect-weight=true,detect-family=true}\n\t\\setlength\\tabcolsep{2pt}\n\t{\\scriptsize\n\t\t\\begin{tabular}{lrrrrrrrr}\n\t\t\\toprule\n\t\t{} & {} & \\multicolumn{4}{c}{Regression performance} &\n\t\t\\multicolumn{3}{c}{Complexity}\\\\\n\t\t\\cmidrule(lr){3-6}\n\t\t\\cmidrule(lr){7-9}\n\t\tModel & $|\\mathcal{T}|$ & MAE [TBR] & $S$ [TBR] & $R^2$ [rel.] & $R^2_{\\text{adj.}}$ [rel.]\n\t\t\t\t\t\t& $\\overline{t}_{\\text{trn.}}$ [\\si{\\milli\\second}] &\n\t\t$\\overline{t}_{\\text{pred.}}$ [\\si{\\milli\\second}] & $\\omega$ [rel.]\\\\\n\t\t\\midrule\n\t\t\\input{tbl/table11}\n\t\t\\bottomrule\n\t\t\\end{tabular}\n\t}\n\t\\caption{Results of experiment~4. Here, figures are reported over 5~cross-validation folds,\n\t\t$|\\mathcal{T}|$~denotes cross-validation set size ($\\times 10^3$)\n\t\tand $\\omega$ is a relative speedup with respect to\n\t\t$\\overline{t}_{\\text{eval.}}=\\SI{7.777049573054314}{\\second}$\n\t\tmeasured in the MC TBR model during run~1 (see~\\cref{tbl:sampling-runs}).\n\t\tThe best-performing metrics are highlighted in bold.}\n\t\\label{tbl:exp4-detailed-results}\n\\end{table}\n\nOverall we found that due to their superior performance, boosted tree-based\napproaches seem to be advantageous for fast surrogate modelling on relatively small training\nsets (up to the order of~$10^4$). Conversely, while neural networks perform\npoorly in such a setting, they dominate on larger training sets (at least of the\norder of~$10^5$) both in terms of regression performance and mean prediction time.\n\n\\begin{wrapfigure}[10]{r}{0.4\\textwidth}\n\t\\centering\n\t\\vspace{-16ex}\n\t\\includegraphics[width=\\linewidth]{fig5_sintoy}\n\t\\caption{Sinusoidal toy TBR theory over two continuous parameters,\n\t$n=1$.}\n\t\\label{fig:sintoy}\n\\end{wrapfigure}\n\n\\subsection{Results of Adaptive Sampling}\n\\label{sec:adaptiveres}\nIn order to test our QASS prototype, several functional toy theories for TBR were developed as alternatives to the expensive MC model. By far the most robust of these was the following sinusoidal theory with adjustable wavenumber parameter $n$:\n\n\\begin{equation}\n\t\\text{TBR} = \\frac{1}{|C|}\\sum_{i \\in C} \\left[1 + \\sin(2\\pi n (x_i - 1/2)) \\right]\n\\end{equation}\n\nplotted in~\\cref{fig:sintoy} for $n=1$ and two continuous parameters $C$.\nANNs trained on this model demonstrated similar performance to those on the expensive\nMC model. QASS performance was verified by training a $\\text{1h3f}(256)$ ANN on\nthe sinusoidal theory for varied quantities of initial, incremental, and MCMC\ncandidate samples. Although the scope of this project did not include thorough\nsearches of this hyperparameter domain, sufficient runs were made to identify\nsome likely trends.\n\nAn increase in initial samples with increment held constant had a strong impact\non final surrogate precision, an early confirmation of basic functionality. An\nincrease in MCMC candidate samples was seen to have a positive but very weak\neffect on final surrogate precision, suggesting that the runtime of MCMC on each\niteration can be limited for increased efficiency. The most complex dynamics\narose with the adjustment of sample increment, shown in~\\cref{fig:qassincr}. For\neach tested initial sample quantity $N$, the optimal number of step samples was seen to be well-approximated by $\\sqrt{N}$. The plotted error trends suggest that\nincremental samples larger than this optimum give slower model improvement on both the training and evaluation sets, and a larger minimum error on the evaluation set. This performance distinction is predicted to be even more significant when trained on the expensive MC model, where the number of sample evaluations will serve as the primary bottleneck for computation time.\n\\begin{figure}[h!]\n    \\centering\n    \\vspace{-1ex}\n    \\begin{subfigure}[t]{0.5\\textwidth}\n        \\centering\n        \\includegraphics[width=1.1\\linewidth]{fig6a_qassincrsamp.pdf}\n    \\end{subfigure}%\n    \\hfill%\n    \\begin{subfigure}[t]{0.5\\textwidth}\n        \\centering\n        \\includegraphics[width=1.1\\linewidth]{fig6b_qassincrtime.pdf}\n    \\end{subfigure}\n    \\caption{QASS absolute training error over total sample quantity (left) and number of iterations (right). MAE represents surrogate error on the adaptively-sampled training/test set, and E\\_MAE on the independent evaluation sets.}\n    \\label{fig:qassincr}\n    \\vspace{-1ex}\n\\end{figure}\n\nThe plateau effect in surrogate error on the evaluation set, seen\nin~\\cref{fig:qassincr}, was universal to all configurations and thought to\nwarrant further investigation. At first this was suspected to be a residual\neffect of retraining the same ANN instance without adjustment to data\nnormalisation. A ``Goldilocks scheme'' for checking normalisation drift was\nimplemented and tested, but did not affect QASS performance. Schemes in which\nthe ANN is periodically retrained were also discarded, as the retention of\nnetwork weights from one iteration to the next was demonstrated to greatly\nbenefit QASS efficiency. Further insight came from direct comparison between\nQASS and a baseline scheme with uniformly random incremental samples, shown\nin~\\cref{fig:qasssampling}.\n\n\\begin{figure}[h]\n\\centering\n\\begin{minipage}{.48\\textwidth}\n  \\centering\n  \\includegraphics[width=1.1\\linewidth]{fig7_qasssampling.pdf}\n  \\captionof{figure}{Absolute training error for QASS, baseline scheme, and mixed scheme.}\n  \\label{fig:qasssampling}\n\\end{minipage}%\n\\hfill%\n\\begin{minipage}{.48\\textwidth}\n  \\centering\n  \\includegraphics[width=1.1\\linewidth]{fig8_qasssampling100k.pdf}\n  \\captionof{figure}{Absolute training error for QASS and baseline scheme, with 100k initial samples.}\n  \\label{fig:qasssampling100k}\n\\end{minipage}\n\\end{figure}\n\nSuch tests revealed that while QASS has unmatched performance on its own\nadaptively-sampled training set, it is outperformed by the baseline scheme on\nuniformly-random evaluation sets. We suspected that while QASS excels in\nlearning the most strongly peaked regions of the TBR theory, this comes at the\nexpense of precision in broader, smoother regions where uniformly random\nsampling suffices. Therefore a mixed scheme was implemented, with half MCMC\nsamples and half uniformly random samples incremented on each iteration, which\nis also shown in~\\cref{fig:qasssampling}. An increase in initial sample size was observed to also resolve precision in these smooth regions of the toy theory, as the initial samples were obtained from a uniform random distribution. As shown in ~\\cref{fig:qasssampling100k}, with~\\num{100000} initial samples it was possible to obtain a ${\\sim}40\\%$ decrease in error as compared to the baseline scheme, from 0.0025 to 0.0015 mean averaged error. Comparing at the point of termination for QASS, this corresponds to a ${\\sim}6\\%$ decrease in the number of total samples needed to train a surrogate with the same error. \n\n\n", "meta": {"hexsha": "eb8e52632bf2bf553a34c848427b273c8d951952", "size": 16634, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "final_report/results.tex", "max_stars_repo_name": "ukaea-group-project/Documentation", "max_stars_repo_head_hexsha": "fcc642a2969e86c532d03254bb4b162e9f23ee01", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-22T11:25:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-22T11:25:42.000Z", "max_issues_repo_path": "final_report/results.tex", "max_issues_repo_name": "ukaea-group-project/Documentation", "max_issues_repo_head_hexsha": "fcc642a2969e86c532d03254bb4b162e9f23ee01", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "final_report/results.tex", "max_forks_repo_name": "ukaea-group-project/Documentation", "max_forks_repo_head_hexsha": "fcc642a2969e86c532d03254bb4b162e9f23ee01", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-04T14:53:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-04T14:53:55.000Z", "avg_line_length": 48.9235294118, "max_line_length": 617, "alphanum_fraction": 0.7759408441, "num_tokens": 4584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381372136564, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.3463095438717233}}
{"text": "\\documentclass[reqno]{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage{lmodern}\n\\usepackage{blindtext}\n\\usepackage{amsmath}\n\\usepackage{relsize} %bigger math symbols\n\\usepackage{bm} %bolder text\n\\usepackage[a4paper, inner=1.7cm, outer=2.7cm, top=3cm, bottom=3cm, bindingoffset=1.2cm]{geometry}\n\\usepackage{tcolorbox}\n\\usepackage{graphicx}\n\\usepackage{wrapfig}\n\\usepackage{enumitem}\n\\newlist{terms}{description}{1}\n\\begin{document}\n\\title{\\textbf{Scalable Reward Distribution with Compounding Stakes}}\n\\author{Richard Pardoe \\thanks{rick@liquity.org}}\n\\date{December 2020\\\\v1.0}\n\\maketitle\n\\begin{abstract}\n    Scalability of Ethereum dApps is constrained by the gas costs of writing to storage. \n    In previous work, Batog $\\cite{Batog}$ and Solmaz $\\cite{Solmaz}$ solved the problem of scalable reward distribution in a staking pool, distributing rewards in proportion to a staker’s share of total stakes with a ``pull'' based approach. Only a single running sum need be updated at each reward, sidestepping the need for an expensive $O(n)$ storage update for n stakers. However, their work stopped short of solving the problem for a compounding stake.\n    Here we derive formulas for a scalable implementation of a compounding, decreasing Stability Pool deposit and its corresponding ETH gain. Thus, Liquity tracks the deposits and rewards of every depositor with only $O(1)$ complexity for each liquidation.\n\\end{abstract}\n\n\\section{Introduction}\nThe Liquity protocol uses a Stability Pool as its primary mechanism to liquidate collateralized debt positions (called ``troves'') that fall below the minimum collateralization ratio of 110$\\%$ $\\cite{Whitepaper}$. Stability deposits (provided in LUSD) absorb and cancel the debt (in LUSD) from defaulted troves: an amount of LUSD in the Stability Pool corresponding to the debt of the liquidated trove is burned from the pool’s balance, offsetting the debt. In return, Stability Pool depositors are rewarded with the acquisition of collateral (in ETH) from liquidated positions at a significant discount. The proportion of a stability depositor’s current deposit to the total LUSD in the pool determines the collateral share it receives from the liquidation. \n\nThe fact that liquidated troves decrease all deposits in the Stability Pool leads to an implementation challenge: Due to Ethereum's block gas limit, it becomes impossible to iterate over all deposits in the Stability Pool for a large number of deposits. Such an operation has computational complexity of $O(n)$ and does not scale. \n\nThis paper presents a method to perform liquidations against the Stability Pool in a scalable manner with only $O(1)$ complexity. The method is ``pull-based\": Instead of adjusting all stability deposits upon every liquidation, the update is deferred to the moment at which an owner withdraws or tops up their deposit.\n\nThe methods presented in this paper are generalizable and can be used for other dApps running on Ethereum.\n\n\\section{Derivation}\nFor a pull-based implementation in Liquity’s Stability Pool, we must factor out the initial deposit, and track reward terms that are independent from the individual deposit values. We derive formulas for a compounding LUSD deposit and corresponding ETH gain as functions of the initial deposit, and involving a product $P$ and a sum $S$: the former is a function of the LUSD losses, and the latter is a function of $P$, the ETH rewards, and the total deposits.\n\n\\bigskip\n\\raggedright %align to the left side\n\n\\textbf{Terms}\n\\begin{terms}\n    \\item $d_i:$ A given user’s LUSD deposit at liquidation event \\textit{i}\\\\\n    \\item $Q_i:$ The LUSD debt absorbed by the Stability Pool from liquidation \\textit{i}\\\\\n    \\item $E_i:$ The ETH sent to the Stability Pool from liquidation \\textit{i}\\\\\n    \\item $D_i:$ Total LUSD deposits at liquidation \\textit{i}\n\\end{terms}\n\n\\bigskip\nLet $d_0$ represent the user’s initial Stability Pool deposit. After the first liquidation, their new\ndeposit $d_0$ is given by:\\\\\n\\begin{equation} \n    d_1=d_0-LUSDLoss\n\\end{equation}\n\n\\bigskip\nLiquidation assigns an LUSD loss to the deposit proportional to the prior share of total deposits:\n\\begin{equation} \\label{eq:2}\n    d_1=d_0-Q_1\\frac{d_0}{D_0}\n\\end{equation}\n\\begin{equation} \n    d_1=d_0\\left(1-\\frac{Q_1}{D_0}\\right)\n\\end{equation}\n\n\\bigskip\nSince the deposit compounds, the deposit value after liquidation 2 is a function of the previous deposit value:\n\\begin{equation} \n    d_2=d_1\\left(1-\\frac{Q_2}{D_1}\\right)\n\\end{equation}\n\n\\bigskip\nand substituting equation (\\ref{eq:2}):\n\\begin{equation} \n    d_2=d_0 \\left(1-\\frac{Q_2}{D_1}\\right) \\left(1-\\frac{Q_1}{D_o} \\right)\n\\end{equation}\n\n\\bigskip\nSimilarly:\n\\begin{equation} \n    d_3=d_2\\left(1-\\frac{Q_3}{D_2}\\right)\n\\end{equation}\n\\begin{equation} \n    d_3=d_0\\left(1-\\frac{Q_3}{D_2}\\right)\\left(1-\\frac{Q_2}{D_1}\\right)\\left(1-\\frac{Q_1}{D_0}\\right)\n\\end{equation}\n\n\\bigskip\nAnd the general case for a compounded deposit:\n\\begin{equation} \\label{eq:8}\n    d_n=d_0\\prod^n_{i=1}{\\left(1-\\frac{Q_i}{D_{i-1}}\\right)}\n\\end{equation}\n\\subsection{Compounded deposit for initial deposit made at $t>0$}\nFor a deposit made between liquidations $[t, t+1]$, which is withdrawn between liquidations $[s, s+1]$, rewards are earned from liquidations $t+1, t+2, \\ldots, s$.\n\nWe take a snapshot of the product at liquidation $t$, and calculate the compounded stake at liquidation $n$, with $t < n \\leq s$, as:\n\n\\begin{equation} \n    d_n=d_t\\prod^n_{i=t+1}{\\left(1-\\frac{Q_i}{D_{i-1}}\\right)}=d_t\\frac{\\displaystyle\\prod^n_{i=1}{\\left(1-\\frac{Q_i}{D_{i-1}}\\right)}}{\\displaystyle\\prod^t_{i=1}\\left(1-\\frac{Q_i}{D_{i-1}}\\right)}\n\\end{equation}\nThis assumes that every multiplicand is non-zero, i.e. that $Q_i < D_{i-1}$ for all $i$ (see section 3.1 for the case where $Q_i = D_{i-1}$ and the pool is emptied).\n\n\\bigskip\nLabelling the product term $P_k$, i.e: $P_k = \\displaystyle\\prod^k_{i=1}{\\left(1-\\frac{Q_i}{D_{i-1}}\\right)}$, yields:\n\n\\begin{equation} \\label{eq:10}\nd_n=d_t\\frac{P_n}{P_t}\n\\end{equation}\n\n\\bigskip\nWhere $P_n$ is the product at liquidation $n$, and $P_t$ is the snapshot of the product at the time when the user made the deposit.\n\n\\bigskip\n\\subsection{Corresponding ETH Gain}\n\n\\bigskip\nThe LUSD deposit earns an ETH gain at each liquidation.\nAt each liquidation $i$, the user’s LUSD deposit effectively decreases. Thus we can write the\nuser’s cumulative ETH gain $e_{n}$, from a series of \\textit{n} liquidations, as:\n\\begin{equation} \ne_n=d_0\\left(\\frac{E_1}{D_0}\\right)+d_1\\left(\\frac{E_2}{D_1}\\right)+d_2\\left(\\frac{E_3}{D_2}\\right)+...+d_{n-1}\\left(\\frac{E_n}{D_{n-1}}\\right)\n\\end{equation}\n\n\\bigskip\nThen, using our expression for the deposit from equation (\\ref{eq:8}):\n\\begin{equation} \ne_n=d_0\\left(\\frac{E_1}{D_0}\\right)+d_0\\left(\\frac{E_2}{D_1}\\right)\\prod^1_{i=1}\\left(1-\\frac{Q_i}{D_{i-1}}\\right)+d_0\\left(\\frac{E_3}{D_2}\\right)\\prod^2_{i=1}\\left(1-\\frac{Q_i}{D_{i-1}}\\right)+...+d_0\\left(\\frac{E_n}{D_{n-1}}\\right)\\prod^{n-1}_{i=1}\\left(1-\\frac{Q_i}{D_{i-1}}\\right)\n\\end{equation}\n\n\\bigskip\nAnd factoring out the initial deposit, $d_0$:\n\\begin{equation} \\label{eq:13}\n    e_n=d_0\\sum^n_{k=1}\\left[\\frac{E_k}{D_{k-1}}\\prod^{k-1}_{i=1}\\left(1-\\frac{Q_i}{D_{i-1}}\\right)\\right] = d_0\\sum^n_{k=1}\\left[\\frac{E_k}{D_{k-1}}P_{k-1}\\right]\n\\end{equation}\n\n\\bigskip\nWhere the initial product term $\\displaystyle\\prod^0_{i=1}(...)=1$.\n\n\\bigskip\nThus, we have the depositor's cumulative ETH gain $e_n$ as a function of the initial deposit $d_0$, and the rewards and total deposits at each liquidation.\\\\\nLet the summation $\\displaystyle\\sum^n_{k=1}[...]$ be denoted $S_n$.\n\n\\bigskip\n\\subsection{ETH gain for initial deposit made at $t>0$}\n\n\\bigskip\nFor a deposit made between liquidations $[t, t+1]$, which is withdrawn between liquidations $[s, s+1]$, rewards are earned from liquidations $t+1, t+2, \\ldots, s$.\n\nWe take a snapshot of the product at liquidation $t$, and calculate the compounded stake at liquidation $n$, with $t < n \\leq s$, as:\n\n\\bigskip\nTo account for the deposit entering after liquidations have already begun, we correct the product terms in (\\ref{eq:13}) to $\\frac{P_n}{P_t}$, as per (\\ref{eq:10}):\n\\begin{equation} \n    e_n = d_t\\sum^n_{k=t+1}\\left[\\frac{E_k}{D_{k-1}}\\frac{P_{k-1}}{P_t}\\right]\n\\end{equation}\n\n\\bigskip\nWe take a snapshot of the sum at liquidation $t$, $S_t$. Then, the ETH gain earned by the deposit at liquidation $n$ is:\n\\begin{equation} \ne_n=d_t\\frac{S_n-S_t}{P_t}\n\\end{equation}\n\n\\bigskip\n\\section{Basic Implementation}\n\\underline{Making a deposit:}\n\nRecord deposit: deposit[user] = $d_t$\\\\\nUpdate total deposits: $D = D + d_t$\\\\\nRecord product snapshot: $P_t = P$\\\\\nRecord sum snapshot: $S_t = S$\n\n\\bigskip\n\\underline{Upon each liquidation yielding LUSD debt ‘Q’ offset with the Stability Pool and ETH gain ‘E’:}\n\nUpdate $S$: $S = S + \\frac{E}{D}P$ (\\textit{intuition: a deposit’s marginal ETH gain is equal to the deposit $\\times$ ETH per unit staked $\\times$ current correction factor)}\\\\\nUpdate $P$: $P = P(1 - \\frac{Q}{D})$\\\\\nUpdate total deposits: $D = D - Q$\n\n\\bigskip\n\\underline{Withdrawing the deposit and ETH gain:}\n\nCompute final compounded LUSD deposit $d$: $d = d_t\\frac{P}{P_t}$\\\\\nCompute final corresponding cumulative ETH gain $e$: $e = d_t\\frac{S - S_t}{P_t}$\\\\\nSend $d$ and $e$ to user\\\\\nUpdate deposit: deposit[user] = 0\\\\\nUpdate total deposits: $D = D - d$\\\\\n\n\\bigskip\n\\section{Practical Implementation in Liquity}\nTwo further considerations are needed for our implementation:\n\\begin{enumerate}\n    \\item Liquidations that completely empty the Stability Pool\n    \\item How to handle the eternally decreasing product $P$, without truncating to 0\n\\end{enumerate}\n\n\\bigskip\n\\subsection{Liquidations that completely empty the Pool}\n\n\\bigskip\n\\textbf{Problem}: Pool-emptying should reduce all deposits to 0, but we should not set $P$ to 0. Doing so would break deposit computations for all future deposits: as $P$ is a running product, all snapshots and future values would be 0.\n\n\\bigskip\n\\textbf{Solution}: Complete pool-emptying is handled by tracking a “current epoch” variable. The ETH gain reward sum $S$ for each epoch is stored in a mapping.\n\n\\bigskip\nUpon a pool-emptying liquidation, $S$ is first updated as usual, for the current epoch. Then, the current epoch is incremented by 1, and $P$ and $S$ terms are reset for the new epoch. By definition, deposits that were made in past epochs will have been completely cancelled with liquidated debt, and so reduced to 0.\n\n\\bigskip\n\\underline{Making a deposit:}\n\nRecord a snapshot of the current epoch for the deposit\n\n\\bigskip\n\\underline{Liquidation that empties the Pool:}\n\nCompute the latest value of $S$, and store it for the current epoch.\nIncrease the epoch by 1, and reset the product and sum ($P$ = 1, $S$ = 0).\n\n\\bigskip\n\\underline{Withdrawing Deposit:}\n\nWhen users withdraw, check their epoch snapshot against the current epoch: If equal, deposit and ETH gain are computed as normal.\n\n\\bigskip\nIf the current epoch is greater than the deposit’s epoch snapshot, then the deposit was made before the pool-emptying liquidation. Therefore:\n\\begin{itemize}\n    \\item The \\textbf{compounded deposit} is 0, as the deposit has been fully used to absorb debt.\n    \\item The user’s \\textbf{ETH gain} is computed using the $S$ sum that corresponds to the epoch in which their deposit was made.\n\\end{itemize}\n\n\\bigskip\n\\subsection{Eternally decreasing the product $P$, without truncating to 0}\n\n\\bigskip\nAt liquidation $i$, $P$ is multiplied by some new term $0 < p_i <1$. Thus in theory, $P$ is always decreasing, but should never reach 0. \n\n\\bigskip\n\\textbf{Problem:} We cannot represent an arbitrarily small value in Solidity.  Eventually, division will truncate a small value to 0. If so, all future values of $P$ would be 0, and deposit computation would break.\n\n\\bigskip\n\\textbf{Solution:} use a “current scale” that allows $P$ to decrease indefinitely, but never reach 0. Each scale represents a division by 1e18.  \n\n\\bigskip\nUpon a liquidation that would otherwise truncate $P$ to 0, $S$ is first updated as usual, for the current scale. Then, the current scale is incremented by 1, and $P$ is updated and scaled by 1e18.\n\n\\bigskip\n\\underline{Making a deposit:}\n\nRecord a snapshot of the current scale for the deposit\n\n\\bigskip\n\\underline{Liquidation:}\n\nCompute the latest value of $S$, and store it for the current scale.\nLiquidation $L_i$ causes the product $P$ to be multiplied by some new product factor $p_i$.  If $P$ $\\times$ $p_i$ would be truncated to 0, instead do: $P = (P \\times p_i \\times 1e18)$, and increment the current scale by 1.\n\n\\bigskip\n\\underline{Withdrawing a deposit:}\n\nFirst, compute the number of scale changes made during the deposit’s lifetime, i.e. (currentScale - scaleSnapshot).\n\n\\bigskip\nIf the number of scale changes is 0, compute the deposit and ETH gain as normal.\n\n\\bigskip\nOtherwise:\n\n\\bigskip\n\\textbf{Compounded deposit:} If a scale change in $P$ was made during the deposit's lifetime, account for it in the deposit computation. If the deposit has decreased by a factor of $<$ 1e-18 (i.e. if more than one scale change was made) just return 0.\n\n\\bigskip\n\\textbf{ETH Gain:} Since the deposit may span up to one scale change, so too does the reward. In this case, obtain the ETH gain using the $S$ sums from the two consecutive scales that the deposit spans. The reward from the second sum is scaled by 1e-18. The rewards from both scales are added to make the final ETH gain.\n\n\\bigskip\n\\section{Putting it all together}\n\n\\bigskip\nThe implementation relies on a nested mapping: epochToScaleToSum. \n\n\\bigskip\nThe inner mapping stores the sum $S$ at different scales, for a given epoch. The outer mapping stores the ($scale \\Rightarrow sum$) mappings for each epoch.\n\n\\bigskip\nThis allows us to track the ETH reward terms at each scale and epoch.Thus we can correctly compute the ETH rewards for a compounding decreasing stake, taking account of periodic Pool-emptying, and getting around the limitations of Solidity arithmetic.\n\n\\bigskip\nAll implementation logic above is combined in PoolManager.sol, in the functions:\n\n\\bigskip\n$\\_getCompoundedLUSDDeposit()$\n\n$\\_getDepositorETHGain()$\n\n$\\_updateRewardSumAndProduct()$\n\n\\section{Acknowledgements}\nWe would like to thank Daniel Simon, Robert Lauko, Bingen Eguzkitza and Onur Solmaz for the helpful discussion on reward distributions and Bojan Peček for his help with preparing this paper.\n\n\\begin{thebibliography}{9}\n\\bibitem{Batog} \nB. Batog, L. Boca, N. Johnson.\n\\textit{Scalable Reward Distribution on the Ethereum Blockchain, 2018}. \nhttp://batog.info/papers/scalable-reward-distribution.pdf\n\n\\bibitem{Solmaz} \nO. Solmaz. \n\\textit{Scalable Reward Distribution with Changing Stake Sizes”, 2019}. \nhttps://solmaz.io/2019/02/24/scalable-reward-changing/\n\n\\bibitem{Whitepaper} \nR. Lauko, R. Pardoe. \n\\textit{Liquity: Decentralized Borrowing Protocol (Whitepaper), 2020}. \nhttps://docsend.com/view/bwiczmy\n\n\n\\end{thebibliography}\n\n\\end{document}", "meta": {"hexsha": "c42012752a2bb21559e84e2a09c76c09b382e694", "size": 14993, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "papers/Scalable_Reward_Distribution_with_Compounding_Stakes.tex", "max_stars_repo_name": "EthereumGeeks/dev", "max_stars_repo_head_hexsha": "daf2d0fb3418cac564461d03c1a9fed4fdec3589", "max_stars_repo_licenses": ["CC-BY-4.0", "MIT"], "max_stars_count": 133, "max_stars_repo_stars_event_min_datetime": "2021-04-06T09:59:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T17:53:12.000Z", "max_issues_repo_path": "papers/Scalable_Reward_Distribution_with_Compounding_Stakes.tex", "max_issues_repo_name": "EthereumGeeks/dev", "max_issues_repo_head_hexsha": "daf2d0fb3418cac564461d03c1a9fed4fdec3589", "max_issues_repo_licenses": ["CC-BY-4.0", "MIT"], "max_issues_count": 228, "max_issues_repo_issues_event_min_datetime": "2021-04-05T14:19:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T08:01:38.000Z", "max_forks_repo_path": "papers/Scalable_Reward_Distribution_with_Compounding_Stakes.tex", "max_forks_repo_name": "sparklingGibbon/dev", "max_forks_repo_head_hexsha": "daf2d0fb3418cac564461d03c1a9fed4fdec3589", "max_forks_repo_licenses": ["CC-BY-4.0", "MIT"], "max_forks_count": 169, "max_forks_repo_forks_event_min_datetime": "2021-04-06T09:55:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T08:20:06.000Z", "avg_line_length": 47.5968253968, "max_line_length": 760, "alphanum_fraction": 0.748882812, "num_tokens": 4433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3462784684960046}}
{"text": "\\documentclass{article}\n\\usepackage{amsmath,amssymb}\n\\newcommand{\\stepthecounter}[2]{\\stepcounter{#1} #2 \\texttt{.}}\n\\begin{document}\n\\section{Seminaive Evaluation}\n\\subsection{Non-Distributed Algorithm}\n\\newcounter{mycounter}\n\\[\n\\begin{array}{ll}\n\\stepthecounter{mycounter}{\\themycounter} & ARGUMENTS : (P, I) \\\\\n\\stepthecounter{mycounter}{\\themycounter} & RETURN : P(I) \\\\\n\\stepthecounter{mycounter}{\\themycounter} & P^{'} := \\{ rule : rule \\in rules(P) \\land idb(P) \\cap body(rule) = \\emptyset \\} \\\\\n\\stepthecounter{mycounter}{\\themycounter} & \\forall S \\in idb(P) : S := \\emptyset \\\\\n\\stepthecounter{mycounter}{\\themycounter} & \\forall S \\in idb(P) : \\Delta^{1}_{S} := P'(I)(S) \\\\\n\\stepthecounter{mycounter}{\\themycounter} & i := 1 \\\\\n\\stepthecounter{mycounter}{\\themycounter} & \\texttt{DO} \\\\\n\\stepthecounter{mycounter}{\\themycounter} & \\quad \\texttt{FOR } S \\in idb(P) \\\\\n\\stepthecounter{mycounter}{\\themycounter} & \\quad \\texttt{BEGIN} \\\\\n\\stepthecounter{mycounter}{\\themycounter} & \\quad \\quad P_{S} := \\{ rule : rule \\in rules(P) \\land S = head(rule) \\} \\\\\n\\stepthecounter{mycounter}{\\themycounter} & \\quad \\quad T := \\bigcup_{rule \\in P_{S}} body(rule) \\\\\n\\stepthecounter{mycounter}{\\themycounter} & \\quad \\quad S^{i} := S^{i-1} \\cup \\Delta^{i}_{S} \\\\\n\\stepthecounter{mycounter}{\\themycounter} & \\quad \\quad \\Delta^{i+1}_{S} := P^{i}_{S}(I, T^{i-1}, T^{i}, \\Delta^{i}_{T}) - S \\\\\n\\stepthecounter{mycounter}{\\themycounter} & \\quad \\texttt{END} \\\\\n\\stepthecounter{mycounter}{\\themycounter} & \\quad i := i + 1 \\\\\n\\stepthecounter{mycounter}{\\themycounter} & \\texttt{UNTIL } \\forall S \\in idb(P) : \\Delta^{i}_{S} = \\emptyset \\\\\n\\end{array}\n\\]\n\\newline\n% @@TODO: also do \\subsection{Distributed Blocking Algorithm}\n\\subsection{Distributed Streaming Algorithm}\n% @@TODO\n\\[\n\\begin{array}{l}\n\\texttt{REMOVE I AS ARGUMENT AND USE IO DIRECTIVES HERE} \\\\\nARGUMENTS : (P, I) \\\\\nRETURN : P(I) \\\\\nP^{'} := \\{ rule : rule \\in rules(P) \\land idb(P) \\cap body(rule) = \\emptyset \\} \\\\\n\\forall S \\in idb(P) : S := \\emptyset \\\\\n\\forall S \\in idb(P) : \\Delta^{1}_{S} := P'(I)(S) \\\\\n\\texttt{CONSUME AND MERGE ALL INPUT RELATIONS HERE} \\\\\ni := 1 \\\\\n\\texttt{DO} \\\\\n\\quad \\texttt{FOR } S \\in idb(P) \\\\\n\\quad \\texttt{BEGIN} \\\\\n\\quad \\quad P_{S} := \\{ rule : rule \\in rules(P) \\land S = head(rule) \\} \\\\\n\\quad \\quad T := \\bigcup_{rule \\in P_{S}} body(rule) \\\\\n\\quad \\quad S^{i} := S^{i-1} \\cup \\Delta^{i}_{S} \\\\\n\\quad \\quad \\Delta^{i+1}_{S} := P^{i}_{S}(I, T^{i-1}, T^{i}, \\Delta^{i}_{T}) - S \\\\\n\\quad \\quad \\texttt{PRODUCE DELTA i + 1 HERE} \\\\\n\\quad \\quad \\texttt{CONSUME AND MERGE WITH DELTA i + 1 HERE} \\\\\n\\quad \\texttt{END} \\\\\n\\quad i := i + 1 \\\\\n\\texttt{UNTIL } \\forall S \\in idb(P) : \\Delta^{i}_{S} = \\emptyset \\\\\n\\end{array}\n\\]\n\\end{document}\n", "meta": {"hexsha": "7002e658801fc18423b3689e32cde4cb7b313b9c", "size": 2732, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "kafka/lh/notes/notes.tex", "max_stars_repo_name": "kjezek/souffle", "max_stars_repo_head_hexsha": "3ec9442c288281c4486ab205094b129b0adf0be7", "max_stars_repo_licenses": ["UPL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kafka/lh/notes/notes.tex", "max_issues_repo_name": "kjezek/souffle", "max_issues_repo_head_hexsha": "3ec9442c288281c4486ab205094b129b0adf0be7", "max_issues_repo_licenses": ["UPL-1.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-11-20T22:48:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-20T22:48:09.000Z", "max_forks_repo_path": "kafka/lh/notes/notes.tex", "max_forks_repo_name": "kjezek/souffle", "max_forks_repo_head_hexsha": "3ec9442c288281c4486ab205094b129b0adf0be7", "max_forks_repo_licenses": ["UPL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.9298245614, "max_line_length": 127, "alphanum_fraction": 0.6383601757, "num_tokens": 1036, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3462784684960045}}
{"text": "\\achapter{Polymorphic Universes}\n\\aauthor{Matthieu Sozeau}\n\n\\label{Universes-full}\n\\index{Universes!presentation}\n\n\\asection{General Presentation}\n\n\\begin{flushleft}\n  \\em The status of Universe Polymorphism is experimental.\n\\end{flushleft}\n\nThis section describes the universe polymorphic extension of Coq.\nUniverse polymorphism allows writing generic definitions making use of\nuniverses and reuse them at different and sometimes incompatible levels.\n\nA standard example of the difference between universe \\emph{polymorphic} and\n\\emph{monomorphic} definitions is given by the identity function:\n\n\\begin{coq_example*}\nDefinition identity {A : Type} (a : A) := a.\n\\end{coq_example*}\n\nBy default, constant declarations are monomorphic, hence the identity\nfunction declares a global universe (say \\texttt{Top.1}) for its\ndomain. Subsequently, if we try to self-apply the identity, we will get\nan error:\n\n\\begin{coq_eval}\nSet Printing Universes.\n\\end{coq_eval}\n\\begin{coq_example}\nFail Definition selfid := identity (@identity).\n\\end{coq_example}\n\nIndeed, the global level \\texttt{Top.1} would have to be strictly smaller than itself\nfor this self-application to typecheck, as the type of \\texttt{(@identity)} is\n\\texttt{forall (A : Type@{Top.1}), A -> A} whose type is itself \\texttt{Type@{Top.1+1}}.\n\nA universe polymorphic identity function binds its domain universe level\nat the definition level instead of making it global.\n\n\\begin{coq_example}\nPolymorphic Definition pidentity {A : Type} (a : A) := a.\nAbout pidentity.\n\\end{coq_example}\n\nIt is then possible to reuse the constant at different levels, like so:\n\n\\begin{coq_example}\nDefinition selfpid := pidentity (@pidentity).\n\\end{coq_example}\n\nOf course, the two instances of \\texttt{pidentity} in this definition\nare different. This can be seen when \\texttt{Set Printing Universes} is\non:\n\n\\begin{coq_example}\nPrint selfpid.\n\\end{coq_example}\n\nNow \\texttt{pidentity} is used at two different levels: at the head of\nthe application it is instantiated at \\texttt{Top.3} while in the\nargument position it is instantiated at \\texttt{Top.4}. This definition\nis only valid as long as \\texttt{Top.4} is strictly smaller than\n\\texttt{Top.3}, as show by the constraints. Note that this definition is\nmonomorphic (not universe polymorphic), so in turn the two universes are\nactually global levels.\n\nInductive types can also be declared universes polymorphic, on universes\nappearing in their parameters or fields. A typical example is given by\nmonoids:\n\n\\begin{coq_example}\nPolymorphic Record Monoid := { mon_car :> Type; mon_unit : mon_car; \n  mon_op : mon_car -> mon_car -> mon_car }.\nPrint Monoid.\n\\end{coq_example}\n\nThe \\texttt{Monoid}'s carrier universe is polymorphic, hence it is\npossible to instantiate it for example with \\texttt{Monoid} itself.\nFirst we build the trivial unit monoid, in \\texttt{Set}:\n\\begin{coq_example}\nDefinition unit_monoid : Monoid := \n  {| mon_car := unit; mon_unit := tt; mon_op x y := tt |}.\n\\end{coq_example} \n\nFrom this we can build a definition for the monoid of\n\\texttt{Set}-monoids (where multiplication would be given by the product\nof monoids).\n\n\\begin{coq_example*}\nPolymorphic Definition monoid_monoid : Monoid.\n  refine (@Build_Monoid Monoid unit_monoid (fun x y => x)).\nDefined.\n\\end{coq_example*}\n\\begin{coq_example}\nPrint monoid_monoid.\n\\end{coq_example} \n\nAs one can see from the constraints, this monoid is ``large'', it lives\nin a universe strictly higher than \\texttt{Set}.\n\n\\asection{\\tt Polymorphic, Monomorphic}\n\\comindex{Polymorphic}\n\\comindex{Monomorphic}\n\\optindex{Universe Polymorphism}\n\nAs shown in the examples, polymorphic definitions and inductives can be\ndeclared using the \\texttt{Polymorphic} prefix. There also exists an\noption \\texttt{Set Universe Polymorphism} which will implicitly prepend\nit to any definition of the user. In that case, to make a definition\nproducing global universe constraints, one can use the\n\\texttt{Monomorphic} prefix. Many other commands support the\n\\texttt{Polymorphic} flag, including:\n\n\\begin{itemize}\n\\item \\texttt{Lemma}, \\texttt{Axiom}, and all the other ``definition''\n  keywords support polymorphism.\n\\item \\texttt{Variables}, \\texttt{Context}, \\texttt{Universe} and\n  \\texttt{Constraint} in a section support polymorphism.  This means\n  that the universe variables (and associated constraints) are\n  discharged polymorphically over definitions that use them. In other\n  words, two definitions in the section sharing a common variable will\n  both get parameterized by the universes produced by the variable\n  declaration. This is in contrast to a ``mononorphic'' variable which\n  introduces global universes and constraints, making the two\n  definitions depend on the \\emph{same} global universes associated to\n  the variable.\n\\item \\texttt{Hint \\{Resolve, Rewrite\\}} will use the auto/rewrite hint\n  polymorphically, not at a single instance.\n\\end{itemize}\n\n\\asection{Global and local universes}\n\nEach universe is declared in a global or local environment before it can\nbe used. To ensure compatibility, every \\emph{global} universe is set to\nbe strictly greater than \\Set~when it is introduced, while every\n\\emph{local} (i.e. polymorphically quantified) universe is introduced as\ngreater or equal to \\Set.\n\n\\asection{Conversion and unification}\n\nThe semantics of conversion and unification have to be modified a little\nto account for the new universe instance arguments to polymorphic\nreferences. The semantics respect the fact that definitions are\ntransparent, so indistinguishable from their bodies during conversion.\n\nThis is accomplished by changing one rule of unification, the\nfirst-order approximation rule, which applies when two applicative terms\nwith the same head are compared. It tries to short-cut unfolding by\ncomparing the arguments directly. In case the constant is universe\npolymorphic, we allow this rule to fire only when unifying the universes\nresults in instantiating a so-called flexible universe variables (not\ngiven by the user). Similarly for conversion, if such an equation of\napplicative terms fail due to a universe comparison not being satisfied,\nthe terms are unfolded. This change implies that conversion and\nunification can have different unfolding behaviors on the same\ndevelopment with universe polymorphism switched on or off.\n\n\\asection{Minimization}\n\nUniverse polymorphism with cumulativity tends to generate many useless\ninclusion constraints in general. Typically at each application of a\npolymorphic constant $f$, if an argument has expected type\n\\verb|Type@{i}| and is given a term of type \\verb|Type@{j}|, a $j \\le i$\nconstraint will be generated. It is however often the case that an\nequation $j = i$ would be more appropriate, when $f$'s\nuniverses are fresh for example. Consider the following example:\n\n\\begin{coq_eval}\nSet Printing Universes.\n\\end{coq_eval}\n\\begin{coq_example}\nDefinition id0 := @pidentity nat 0.\nPrint id0.\n\\end{coq_example}\n\nThis definition is elaborated by minimizing the universe of id to level\n\\Set~while the more general definition would keep the fresh level i\ngenerated at the application of id and a constraint that $\\Set \\le i$.\nThis minimization process is applied only to fresh universe\nvariables. It simply adds an equation between the variable and its lower\nbound if it is an atomic universe (i.e. not an algebraic \\texttt{max()}\nuniverse).\n\nThe option \\texttt{Unset Universe Minimization ToSet} disallows\nminimization to the sort $\\Set$ and only collapses floating universes\nbetween themselves.\n\n\\asection{Explicit Universes}\n\nThe syntax has been extended to allow users to explicitly bind names to\nuniverses and explicitly instantiate polymorphic definitions.\n\n\\subsection{\\tt Universe {\\ident}.\n  \\comindex{Universe}\n  \\label{UniverseCmd}}\n\nIn the monorphic case, this command declare a new global universe named\n{\\ident}. It supports the polymorphic flag only in sections, meaning the\nuniverse quantification will be discharged on each section definition\nindependently.\n\n\\subsection{\\tt Constraint {\\ident} {\\textit{ord}} {\\ident}.\n  \\comindex{Constraint}\n  \\label{ConstraintCmd}}\n\nThis command declare a new constraint between named universes. \nThe order relation can be one of $<$, $\\le$ or $=$. If consistent, \nthe constraint is then enforced in the global environment. Like\n\\texttt{Universe}, it can be used with the \\texttt{Polymorphic} prefix\nin sections only to declare constraints discharged at section closing time.\n\n\\begin{ErrMsgs}\n\\item \\errindex{Undeclared universe {\\ident}}.\n\\item \\errindex{Universe inconsistency}\n\\end{ErrMsgs}\n\n\\subsection{Polymorphic definitions}\nFor polymorphic definitions, the declaration of (all) universe levels\nintroduced by a definition uses the following syntax:\n\n\\begin{coq_example*}\nPolymorphic Definition le@{i j} (A : Type@{i}) : Type@{j} := A.\n\\end{coq_example*}\n\\begin{coq_example}\nPrint le.\n\\end{coq_example}\n\nDuring refinement we find that $j$ must be larger or equal than $i$, as\nwe are using $A : Type@{i} <= Type@{j}$, hence the generated\nconstraint. At the end of a definition or proof, we check that the only\nremaining universes are the ones declared. In the term and in general in\nproof mode, introduced universe names can be referred to in\nterms. Note that local universe names shadow global universe names.\nDuring a proof, one can use \\texttt{Show Universes} to display\nthe current context of universes.\n\nDefinitions can also be instantiated explicitly, giving their full instance:\n\\begin{coq_example}\nCheck (pidentity@{Set}).\nUniverses k l.\nCheck (le@{k l}).\n\\end{coq_example}\n\nUser-named universes are considered rigid for unification and are never\nminimized.\n\n\\subsection{\\tt Unset Strict Universe Declaration.\n  \\optindex{StrictUniverseDeclaration}\n  \\label{StrictUniverseDeclaration}}\n\nThe command \\texttt{Unset Strict Universe Declaration} allows one to\nfreely use identifiers for universes without declaring them first, with\nthe semantics that the first use declares it. In this mode, the universe\nnames are not associated with the definition or proof once it has been\ndefined. This is meant mainly for debugging purposes.\n\n%%% Local Variables: \n%%% mode: latex\n%%% TeX-master: \"Reference-Manual\"\n%%% End: \n", "meta": {"hexsha": "f47973601b3619ace5627ed83c259d6d17b37f82", "size": 10201, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "presentations/coq-workshop-2014-coq/doc/refman/Universes.tex", "max_stars_repo_name": "JasonGross/test-broken-tar", "max_stars_repo_head_hexsha": "6b52b8532879df53386b0f5413485888a1aa886a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "presentations/coq-workshop-2014-coq/doc/refman/Universes.tex", "max_issues_repo_name": "JasonGross/test-broken-tar", "max_issues_repo_head_hexsha": "6b52b8532879df53386b0f5413485888a1aa886a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "presentations/coq-workshop-2014-coq/doc/refman/Universes.tex", "max_forks_repo_name": "JasonGross/test-broken-tar", "max_forks_repo_head_hexsha": "6b52b8532879df53386b0f5413485888a1aa886a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6401515152, "max_line_length": 88, "alphanum_fraction": 0.7849230468, "num_tokens": 2542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.34627845961784715}}
{"text": "\\documentclass[11pt]{article}\n\\bibliographystyle{alpha}\n\n\\usepackage{todonotes}\n\n\\usepackage{fullpage}\n% Uncomment this when debuging labels. This will display labels\n% citations etc when they are refered. Which makes some debuggin\n% easier. Comment it for the final version.\n\n%\\usepackage{showkeys}\n\\input{preamble}\n\\renewcommand{\\R}{\\mathcal{R}} %these two are very specific to thsi\n\\renewcommand{\\F}{\\mathcal{F}} %file. was just lazy\n\n\\newcommand{\\mr}{\\mathcal{M}_\\mathcal{R}} %M_r\n\n\\title{Fast Integer Multiplication Using Modular Arithmetic \\footnote{A preliminary version appeared in the proceedings of the 40th ACM Symposium on Theory of Computing, 2008.}}\n\\author{Anindya De\\thanks{Research done while the author was at the Dept\n    of Computer Science and Engineering, IIT Kanpur}\\\\\n  Computer Science Division\\\\\n  University of California at Berkeley\\\\\n  Berkeley, CA 94720, USA\\\\\n  {\\tt anindya@eecs.berkeley.edu}\\\\\n  %\n  \\and\n  Piyush P Kurur%\n  \\thanks{Research supported through Research I Foundation project\n    NRNM/CS/20030163},\\\\ %\n  Dept. of Computer Science and Engineering\\\\%\n  Indian Institute of Technology Kanpur\\\\%\n  Kanpur, UP, India, 208016\\\\\n  {\\tt ppk@cse.iitk.ac.in}\\\\%\n  \\and%\n  Chandan Saha\\\\%\n  Dept. of Computer Science and Engineering\\\\%\n  Indian Institute of Technology Kanpur\\\\%\n  Kanpur, UP, India, 208016\\\\%\n  {\\tt csaha@cse.iitk.ac.in}%\n  \\and  Ramprasad Saptharishi%\n  \\thanks{Research done while visiting IIT Kanpur %\n    under Project FLW/DST/CS/20060225}\\\\%\n  Chennai Mathematical Institute\\\\%\n  Plot H1, SIPCOT IT Park\\\\%\n  Padur PO, Siruseri, India, 603103\\\\%\n  {\\tt ramprasad@cmi.ac.in}\n}\n\n\\date{}\n\n\\begin{document}\n\\maketitle\n\\begin{abstract}\nWe give an $N\\cdot \\log N\\cdot 2^{O(\\log^*N)}$ time algorithm to\nmultiply two $N$-bit integers that uses modular arithmetic for\nintermediate computations instead of arithmetic over complex numbers\nas in F\\\"{u}rer's algorithm, which also has the same and so far the\nbest known complexity. The previous best algorithm using modular\narithmetic (by Sch{\\\"{o}}nhage and Strassen) has complexity $O(N \\cdot\n\\log N \\cdot \\log\\log N)$. The advantage of using modular arithmetic\nas opposed to complex number arithmetic is that we can completely\nevade the task of bounding the truncation error due to finite\napproximations of complex numbers, which makes the analysis relatively\nsimple. Our algorithm is based upon F\\\"{u}rer's algorithm, but uses\nFFT over multivariate polynomials along with an estimate of the least\nprime in an arithmetic progression to achieve this improvement in the\nmodular setting. It can also be viewed as a $p$-adic version of\nF\\\"{u}rer's algorithm.\n\\end{abstract}\n\n\\section{Introduction}\n\nComputing the product of two $N$-bit integers is nearly a ubiquitous\noperation in algorithm design. Being a basic arithmetic operation, it\nis no surprise that multiplications of integers occur as intermediate\nsteps of computation in algorithms from every possible domain of\ncomputer science. But seldom do the complexity of such multiplications\ninfluence the overall efficiency of the algorithm as the integers\ninvolved are relatively small in size and the multiplications can\noften be implemented as fast hardware operations. However, with the\nadvent of modern cryptosystems, the study of the bit complexity of\ninteger multiplication received a significant impetus. Indeed, large\ninteger multiplication forms the foundation of many modern day\npublic-key crystosytems, like RSA, El-Gamal and Elliptic Curve\ncrytosystems. One of the most notable applications is the RSA\ncryptosystem, where it is required to multiply two primes that are\nhundreds or thousands of bits long. The larger these primes the harder\nit is to factor their product, which in turn makes the RSA extremely\nsecure in practice.\n\nIn this paper, our focus is more on the theoretical aspects of integer\nmultiplication, it being a fundamental problem in its own right. This\nis to say, we will be concerned with the asymptotic bit complexity of\nmutiplying two $N$-bit integers with little emphasis on optimality in\npractice. We begin with a brief account of earlier work on integer\nmultiplication algorithms.\n\n\\subsection{Previous Work}\n\nThe naive approach to multiply two $N$-bit integers leads to an\nalgorithm that uses $O(N^2)$ bit operations. Karatsuba \\cite{K63}\nshowed that some multiplication operations of such an algorithm can be\nreplaced by less costly addition operations which reduces the overall\nrunning time of the algorithm to $O(N^{\\log_23})$ bit\noperations. Shortly afterwards, this result was improved by Toom\n\\cite{T63} who showed that for any $\\varepsilon>0$, integer\nmultiplication can be done in $O(N^{1+\\varepsilon})$ time. This led to\nthe question as to whether the time complexity can be improved further\nby replacing the term $O(N^{\\epsilon})$ by a poly-logarithmic\nfactor. In a major breakthrough, Sch\\\"{o}nhage and\nStrassen~\\cite{SS71} gave two efficient algorithms for multiplying\nintegers using fast polynomial multiplication. One of the algorithms\nachieved a running time of $O(N\\cdot \\log N\\cdot \\log\\log N\\ldots\n2^{O(\\log^*N)})$ using arithmetic over complex numbers (approximated\nto suitable precisions), while the other used arithmetic modulo\ncarefully chosen integers to improve the complexity further to\n$O(N\\cdot \\log N\\cdot \\log\\log N)$ bit operations. The modular\nalgorithm remained the best for a long period of time until a recent\nremarkable result by F\\\"{u}rer \\cite{F07} (see also\n\\cite{F09}). F\\\"{u}rer gave an algorithm that uses arithmetic over\ncomplex numbers and runs in $N\\cdot\\log N\\cdot 2^{O(\\log^\\ast N)}$\ntime. Till date this is the best time complexity known for integer\nmultiplication and indeed our result is inspired by F\\\"{u}rer's\nalgorithm.\n\nFurther details on other approaches and enhancements to previous\ninteger multiplication algorithms can be found in \\cite{F09}.\n\n\\subsection{The Motivation}\n\nSch\\\"{o}nhage and Strassen introduced two seemingly different\napproaches to integer multiplication -- using complex and modular\narithmetic. F\\\"{u}rer's algorithm improves the time complexity in the\ncomplex arithmetic setting by cleverly reducing some costly\nmultiplications to simple shift operations. However, the algorithm\nneeds to approximate the complex numbers to certain precisions during\ncomputation. This introduces the added task of bounding the total\ntruncation errors in the analysis of the algorithm. On the contrary,\nin the modular setting the error analysis is virtually absent or\nrather more implicit, which in turn simplifies the overall\nanalysis. In addition, modular arithmetic gives a discrete approach to\na discrete problem like integer multiplication. Therefore, it seems\nnatural to ask whether we can achieve a similar improvement in time\ncomplexity of this problem in the modular arithmetic setting. In this\nwork, we answer this question affirmatively. We give an $N\\cdot\n\\log{N}\\cdot 2^{O(\\log^{*}{N})}$ time algorithm for integer\nmultiplication using only modular arithmetic, thus matching the\nimprovement made by F\\\"{u}rer.\n\n\\subsection*{Overview of our result}\n\nAs is the case in both Sch\\\"{o}nhage-Strassen's and F\\\"{u}rer's\nalgorithms, we start by reducing the problem to polynomial\nmultiplication over a ring $\\mathcal{R}$ by properly encoding the\ngiven integers. Polynomials can be multiplied efficiently using\nDiscrete Fourier Transforms (DFT). However, in order that we are able\nto use Fast Fourier Transform (FFT), the ring $\\mathcal{R}$ should\nhave some special roots of unity. For instance, to multiply two\npolynomials of degree less than $M$ using FFT, we require a\n\\emph{principal} $2M$-th root of unity (see\nDefinition~\\ref{def-principal-root} for principal roots). One way to\nconstruct such a ring in the modular setting is to consider rings of\nthe form $\\mathcal{R} = \\Z/(2^M + 1) \\Z$ as in Sch\\\"{o}nhage and\nStrassen's work ~\\cite{SS71}. In this case, the element $2$ is a\n$2M$-th principal root of unity in $\\mathcal{R}$. This approach can be\nequivalently viewed as attaching an `artificial' root to the ring of\nintegers. However, this makes the size of $\\mathcal{R}$ equal to $2^M$\nand thus a representation of an arbitrary element in $\\mathcal{R}$\ntakes $M$ bits. This means an $N$-bit integer is encoded as a\npolynomial of degree $M$ with every coefficient about $M$ bits long,\nthereby making $M \\approx \\sqrt{N}$ as the optimal choice. Indeed, the\nchoice of such an $\\mathcal{R}$ is the basis of Sch\\\"{o}nhage and\nStrassen's modular algorithm in which they reduce multiplication of\n$N$-bit integers to multiplication of $\\sqrt{N}$-bit integers and\nachieve a complexity of $O(N \\cdot \\log N \\cdot \\log \\log N)$ bit\noperations.\n\nNaturally, such rings are a little too expensive in our setting. We\nwould rather like to find a ring whose size is bounded by some\npolynomial in $M$ and which still contains a principal $2M$-th root of\nunity. In fact, it is this task of choosing a suitable ring that poses\nthe primary challenge in adapting F\\\"{u}rer's algorithm and making it\nwork in the discrete setting.\n\nWe choose the ring to be $\\mathcal{R} = \\Z/p^c\\Z$, for a prime $p$ and\na constant $c$ such that $p^c = \\mathsf{poly}(M)$. The ring\n$\\Z/p^c\\Z$, has a principal $2M$-th root of unity if and only if $2M$\ndivides $p-1$, which means that we need to find a prime $p$ from the\narithmetic progression $\\inbrace{1 + i\\cdot 2M}_{i>0}$. To make this\nsearch computationally efficient, we also need the degree of the\npolynomials, $M$ to be sufficiently small. This we can achieve by\nencoding the integers as multivariate polynomials instead of\nunivariate ones. It turns out that the choice of the ring as\n$\\mathcal{R} = \\Z/p^c\\Z$ is still not quite sufficient and needs a\nlittle more refinement. This is explained in Section \\ref{sec:ring}.\n\nThe use of multivariate polynomial multiplications along with a small\nbase ring are the main steps where our algorithm differs from earlier\nalgorithms by Sch\\\"{o}nhage-Strassen and F\\\"{u}rer. Towards\nunderstanding the notion of \\emph{inner} and \\emph{outer} DFT in the\ncontext of multivariate polynomials, we also present a group theoretic\ninterpretation of DFT. The use of inner\nand outer DFT plays a central role in both F\\\"{u}rer's as well as our\nalgorithm. Arguing along the line of F\\\"{u}rer \\cite{F07}, we show that\nrepeated use of efficient computation of inner DFT's using some\nspecial roots of unity in $\\mathcal{R}$ reduces the number of\n`bad multiplications' (in comparison to Sch\\\"{o}nhage-Strassen's algorithm)\nand makes the overall process efficient, thereby leading to an $N\\cdot \\log{N}\\cdot 2^{O(\\log^{*}{N})}$\ntime algorithm.\n\n\n\\section{The Basic Setup}\n\n\\subsection{The Underlying Ring} \\label{sec:ring}\n\nRings of the form $\\mathcal{R} = \\Z/(2^M + 1) \\Z$ have the nice\nproperty that multiplications by powers of $2$, the $2M$-th principal\nroot of unity, are mere shift operations and are therefore very\nefficient. Although by choosing the ring $\\mathcal{R} = \\Z/p^c\\Z$ we\nensure that the ring size is small, it comes with a price:\nmultiplications by principal roots of unity are no longer just shift\noperations. Fortunately, this can be redeemed by working with rings of\nthe form $\\mathcal{R} = \\Z[\\alpha]/(p^c, \\alpha^m + 1)$ for some $m$\nwhose value will be made precise later. Elements of $\\mathcal{R}$ are\nthus $m-1$ degree polynomials over $\\alpha$ with coefficients from\n$\\Z/p^c\\Z$. By construction, $\\alpha$ is a $2m$-th root of unity and\nmultiplication of any element in $\\mathcal{R}$ by any power of\n$\\alpha$ can be achieved by shift operations --- this property is\ncrucial in making some multiplications in the FFT less costly (see\nSection~\\ref{fourier_analysis}).\n\nGiven an $N$-bit number $a$, we encode it as a $k$-variate polynomial\nover $\\mathcal{R}$ with degree in each variable less than $M$. The\nparameters $M$ and $m$ are powers of two such that $M^k$ is roughly\n$\\frac{N}{\\log^2N}$ and $m$ is roughly $\\log{N}$. The parameter $k$\nwill ultimately be chosen a constant (see Section\n\\ref{complexity_section}). We now explain the details of this encoding\nprocess.\n\n\\subsection{Encoding Integers into $k$-variate\n  Polynomials}\\label{encoding_section}\n\nGiven an $N$-bit integer $a$, we first break these $N$ bits into $M^k$\nblocks of roughly $\\frac{N}{M^k}$ bits each. This corresponds to\nrepresenting $a$ in base $q = 2^{\\frac{N}{M^k}}$.  Let $a = a_0 +\n\\ldots + a_{M^k-1}q^{M^k - 1}$, where every $a_i < q$. The number $a$\nis converted into a polynomial as follows:\n\\begin{enumerate}\n\\item Express $i$ in base $M$ as $i = i_1 + i_2M + \\cdots +\n  i_kM^{k-1}$. \\label{base_M_item}\n\\item Encode each term $a_iq^i$ as the monomial $a_i\\cdot\n  X_1^{i_1}X_2^{i_1}\\cdots X_k^{i_k}$. As a result, the number $a$\n  gets converted to the polynomial $\\sum_{i=0}^{M^k - 1}\n  a_i\\cdot X_1^{i_1}\\cdots X_k^{i_k}$.\n\\end{enumerate}\n\nFurther, we break each $a_i$ into $\\frac{m}{2}$ equal sized blocks\nwhere the number of bits in each block is $u = \\frac{2N}{M^k\\cdot m}$.\nEach coefficient $a_i$ is then encoded as a polynomial in $\\alpha$ of\ndegree less than $\\frac{m}{2}$. The polynomials are then padded with\nzeroes to stretch their degrees to $m$. Thus, the $N$-bit number $a$\nis converted to a $k$-variate polynomial $a(X)$ over\n$\\Z[\\alpha]/(\\alpha^m + 1)$.\\\\\n\nGiven integers $a$ and $b$, each of $N$ bits, we encode them as\npolynomials $a(X)$ and $b(X)$ and compute the product polynomial. The\nproduct $a\\cdot b$ can be recovered by substituting $X_s =\nq^{M^{s-1}}$, for $1\\leq s\\leq k$, and $\\alpha = 2^u$ in the\npolynomial $a(X)\\cdot b(X)$.  The coefficients in the product\npolynomial could be as large as $M^k\\cdot m\\cdot 2^{2u}$ and hence it\nis sufficient to do arithmetic modulo $p^c$ where $p^c > 2M^k\\cdot\nm\\cdot 2^{2u}$. Our choice of\nthe prime $p$ ensures that $c$ is in fact a constant (see\nSection~\\ref{complexity_section}). We summarize this discussion as a lemma.\n\n\\begin{lemma}\\label{lem:encoding-time}\n  Multiplication of two $N$-bit integers reduces to\n  multiplication of two $k$-variate polynomials, with degree in each\n  variable bounded by $M$, over the ring $\\Z[\\alpha]/(p^c,\\alpha^m +\n  1)$ for a prime $p$ satisfying $p^c > 2M^k\\cdot m \\cdot 2^{2u}$,\n  where $u=\\frac{2N}{M^km}$. Furthermore, the reduction can be\n  performed in $O(N)$ time.\n\\end{lemma}\n\n\n\\subsection{Choosing the Prime}\\label{prime_section}\n\nThe prime $p$ should be chosen such that the ring $\\Z/p^c\\Z$ has a\n\\emph{principal} $2M$-th root of unity, which is required for\npolynomial multiplication using FFT. A principal root of unity is\ndefined as follows.\n\n\\begin{definition}\\label{def-principal-root}\n\\emph{\\textsf{(Principal root of unity)}} An $n$-th root of unity\n$\\zeta\\in \\mathcal{R}$ is said to be primitive if it generates a\ncyclic group of order $n$ under multiplication. Furthermore, it is\nsaid to be principal if $n$ is coprime to the characteristic of\n$\\mathcal{R}$ and $\\zeta$ satisfies $\\sum_{i=0}^{n-1}\\zeta^{ij}=0$ for\nall $0< j < n$.\n\\end{definition}\n\n\\noindent\nIn $\\Z/p^c\\Z$, a $2M$-th root of unity is principal if and only if\n$2M\\mid p-1$ (see also Section~\\ref{Qp_section}). As a result, we need\nto choose the prime $p$ from the arithmetic progression $\\inbrace{1 +\n  i\\cdot 2M}_{i> 0}$, which is potentially the main bottleneck of our\napproach. We now explain how to circumvent this problem. \\\\\n\n\nAn upper bound for the least prime in an arithmetic progression is\ngiven by the following theorem by Linnik \\cite{L44}:\n\n\\begin{theorem}\\label{linnik_theorem}\n\\emph{\\textsf{(Linnik)}} There exist absolute constants $\\ell$ and $L$\nsuch that for any pair of coprime integers $d$ and $n$, the least\nprime $p$ such that $p\\equiv d\\bmod{n}$ is less than $\\ell n^L$.\n\\end{theorem}\n\nHeath-Brown \\cite{B92} showed that the \\emph{Linnik constant} $L\\leq\n5.5$ (a recent work by Xylouris \\cite{X09} showed that $L \\leq\n5.2$). Recall that $M$ is chosen such that $M^k$ is\n$O\\inparen{\\frac{N}{\\log^2N}}$. If we choose $k=1$, that is if we use\nunivariate polynomials to encode integers, then the parameter $M =\nO\\inparen{\\frac{N}{\\log^2N}}$. Hence the least prime $p\\equiv\n1\\pmod{2M}$ could be as large as $N^L$. Since all known deterministic\nsieving procedures take at least $N^L$ time this is clearly infeasible\n(for a randomized approach see Section~\\ref{ERH_section}). However, by\nchoosing a larger $k$ we can ensure that the least prime $p\\equiv\n1\\pmod{2M}$ is $O(N^\\varepsilon)$ for some constant $\\varepsilon <\n1$. Since primality testing is in deterministic polynomial\\footnote{a\n  subexponential algorithm would suffice} time\\cite{AKS04}, we can find the least prime $p\\equiv 1 \\pmod{2M}$ in $o(N)$\ntime.\n\n\n\\begin{lemma}\\label{prime_time}\nIf $k$ is any integer greater than $L+1$, then $M^L =\nO\\inparen{N^{\\frac{L}{L+1}}}$ and hence the least prime $p\\equiv\n1\\pmod{2M}$ can be found in $o(N)$ time.\n\\end{lemma}\n\n\\subsubsection*{Choosing the Prime Randomly}\\label{ERH_section}\n\nTo ensure that the search for a prime $p\\equiv 1\\pmod{2M}$ does not\naffect the overall time complexity of the algorithm, we considered\nmultivariate polynomials to restrict the value of $M$; an alternative\nis to use randomization.\n\n\\begin{proposition} \\label{prop:randomprime}\nAssuming ERH, a prime $p\\equiv 1\\pmod{2M}$ can be computed by a\nrandomized algorithm with expected running time $\\tilde{O}(\\log^3 M)$.\n\\end{proposition}\n\\begin{proof}\nTitchmarsh \\cite{Titchmarsh} (see also Tianxin \\cite{Tianxin})\nshowed, assuming ERH, that the number of primes less than $x$ in the\narithmetic progression $\\{ 1 + i \\cdot 2M\\}_{i > 0}$ is given by,\n\\begin{equation*}\n\\pi(x,2M) = \\frac{Li(x)}{\\varphi(2M)} + O(\\sqrt{x} \\log x)\n\\end{equation*}\nfor $2M \\leq \\sqrt{x} \\cdot (\\log x)^{-2}$, where $Li(x) =\n\\Theta(\\frac{x}{\\log x})$ and $\\varphi$ is the Euler totient\nfunction. In our case, since $M$ is a power of two, $\\varphi(2M) = M$,\nand hence for $x \\geq 4M^2 \\cdot \\log^6 M$, we have $\\pi(x, 2M) =\n\\Omega\\inparen{\\frac{x}{M\\log x}}$. Therefore, for an $i$ chosen\nuniformly randomly in the range $1 \\leq i \\leq 2M \\cdot \\log^6 M$, the\nprobability that $i\\cdot 2M + 1$ is a prime is at least $\\frac{d}{\\log\n  x}$ for a constant $d$. Furthermore, primality test of an $O(\\log\nM)$ bit number can be done in $\\tilde{O}(\\log^2 M)$ time using\nRabin-Miller primality test \\cite{M76, R80}. Hence, with $x = 4M^2\n\\cdot \\log^6 M$, a suitable prime for our algorithm can be found in\nexpected $\\tilde{O}(\\log^3 M)$ time.\n\\end{proof}\n\n\\noindent \\textbf{Remark - } We prefer to use Linnik's theorem (Theorem\n\\ref{linnik_theorem}) instead of Proposition \\ref{prop:randomprime}\nwhile choosing the prime in the progression $\\{ 1 + i \\cdot 2M\\}_{i > 0}$\nso as to make the results in this paper independent of the ERH and the usage\nof random bits.\n\n\\subsection{Finding the Root of Unity}\\label{root_section}\n\nWe require a principal $2M$-th root of unity $\\rho(\\alpha)$ in\n$\\mathcal{R}$ to compute the Fourier transforms. This root\n$\\rho(\\alpha)$ should also have the property that its\n$\\inparen{\\frac{M}{m}}$-th power is $\\alpha$, so as to make some\nmultiplications in the FFT efficient (see Section\n\\ref{fourier_analysis}). The root $\\rho(\\alpha)$ can be computed by\ninterpolation in a way similar to that in F\\\"{u}rer's algorithm\n\\cite[Section 3]{F07}, except that we need a principal $2M$-th root of\nunity $\\omega$ in $\\Z/p^c\\Z$ to start with.\n\nTo obtain such a root, we first obtain a $2M$-th root of unity\n$\\omega_1$ in $\\Z/p\\Z$. A generator $\\zeta$ of $\\mathbb{F}_p^{\\times}$\ncan be computed by brute force, as $p$ is sufficiently small, and\n$\\omega_1 = \\zeta^{(p-1)/2M}$ is a principal $2M$-th root of unity in $\\Z/p\\Z$.\nA principal $2M$-root of unity\n$\\omega_1$ must be a root of the polynomial $f(x) = x^M+1$ in $\\Z/p\\Z$.  Having obtained $\\omega_1$,\nwe use Hensel Lifting \\cite[Theorem 2.23]{Zuckerman}.\n\n\\begin{lemma}[\\textsf{Hensel Lifting}]\n  Let $\\omega_s$ be a root of $f(x) = x^M + 1$ in $\\Z/p^s\\Z$. Then\n  there exists a unique root $\\omega_{s+1}$ in $\\Z/p^{s+1}\\Z$ such\n  that $\\omega_{s+1}\\equiv \\omega_s\\pmod{p^s}$ and $f(\\omega_{s+1}) =\n  0\\pmod{p^{s+1}}$. This unique root is given by $\\omega_{s+1} =\n  \\omega_s - \\frac{f(\\omega_s)}{f'(\\omega_s)}$.\\end{lemma}\n\n%%% HANDLING TODO PRES 5\n\n\\noindent\nIt is clear from the above lemma that we can compute a $2M$-th root of\nunity $\\omega = \\omega_c$ in $\\Z/p^c\\Z$. We will need the following\nwell-known and useful fact about principal roots of unity in any ring.\n\n\\begin{lemma}\\cite[Lemma 2.1]{F09}\\label{lem:Furer-principal-root}\n  If $M$ is a power of $2$ and $\\omega^{M} = -1$ in an arbitrary ring\n  $\\mathcal{R}$. If $M$ is relatively prime to the characteristic of\n  $\\mathcal{R}$, then $\\omega$ is a principal $2M$-th root of unity in\n  $\\mathcal{R}$.\n\\end{lemma}\n\n\\noindent\nHence it follows that the root $\\omega$ of $f(x) = x^M + 1$ in\n$\\Z/p^c\\Z$ is a principal $2M$-th root of unity in $\\Z/p^c\\Z$.\nFurthermore, $\\zeta^{(p-1)/2M} = \\omega_1 \\equiv \\omega\\bmod p$. Since\n$\\zeta$ is a generator of $\\mathbb{F}_p^\\times$, different powers of\n$\\zeta$ must generate the group $\\mathbb{F}_p^\\times$ and hence must\nbe distinct modulo $p$. Hence it follows that different powers of\n$\\omega$ must be distinct modulo $p$ as well. Therefore, the\ndifference between any two of them is a unit in $\\Z/p^c\\Z$ and this\nmakes the following\ninterpolation feasible in our setting. \\\\\n\n\\paragraph{Finding $\\rho(\\alpha)$ from $\\omega$:} Since $\\omega$ is a\nprincipal $2M$-th root of unity, $\\gamma = \\omega^{\\frac{2M}{2m}}$ is\na principal $2m$-th root of unity in $\\Z/p^c\\Z$. Notice that,\n$\\alpha^m + 1$ uniquely factorizes as, $\\alpha^m + 1 = (\\alpha -\n\\gamma)(\\alpha - \\gamma^3) \\ldots (\\alpha - \\gamma^{2m-1})$. The\nideals generated by $(\\alpha - \\gamma^i)$ and $(\\alpha - \\gamma^j)$\nare mutually coprime as $\\gamma^i -\\gamma^j$ is a unit for $i\\neq j$\nand is contained in the ideal generated by $(\\alpha - \\gamma^i)$ and\n$(\\alpha - \\gamma^j)$.  Therefore, using Chinese Remaindering,\n$\\alpha$ has the direct sum representation $(\\gamma, \\gamma^3, \\ldots,\n\\gamma^{2m-1})$ in $\\mathcal{R}$. Since we require\n$\\rho(\\alpha)^{\\frac{2M}{2m}} = \\alpha$, it is sufficient to choose a\n$\\rho(\\alpha)$ whose direct sum representation is $(\\omega, \\omega^3,\n\\ldots, \\omega^{2m-1})$. Now use Lagrange's formula to interpolate\n$\\rho(\\alpha)$ as,\n\\begin{equation*}\n  \\rho(\\alpha) = \\sum_{i=1, \\text{ } i \\text{ odd}}^{2m-1}{\\omega^i \\cdot \\prod_{j=1, \\text{ } j \\neq i, \\text{ } j \\text{ odd}}^{2m-1}{\\frac{\\alpha - \\gamma^j}{\\gamma^i - \\gamma^j}}}\n\\end{equation*}\nThe inverses of the elements $\\gamma^i - \\gamma^j$ in $\\Z/p^c\\Z$ can\nbe easily computed in $\\text{poly}(\\log p)$ time. It is also clear\nthat $\\rho(\\alpha)^M$, in the direct-sum representation, is\n$(\\omega^M, \\omega^{3M}, \\cdots, \\omega^{(2m -1)M})$ which is the element $-1$\nin $\\R$. Hence $\\rho(\\alpha)$ is\na principal $2M$-th root of unity (by Lemma~\\ref{lem:Furer-principal-root}).\\\\\n\nBesides finding a generator $\\zeta$ of $\\Z/p\\Z$ by brute-force (which\ncan be performed in $O(p)$ time), all other computations can be done\nin $\\text{poly}(\\log p)$ time. We summarize this as a lemma.\n\n\\begin{lemma}\\label{lem:root-time}\n  A principal $2M$-th root of unity $\\rho(\\alpha)\\in \\R$ such that\n  $\\rho(\\alpha)^{2M/2m} = \\alpha$ can be computed in deterministic\n  time $O(p \\cdot \\mathrm{poly}(\\log(p)))$ (which is $o(N)$ if $p =\n  o(N)$).\n\\end{lemma}\n\n% \\subsection*{old}\n\n% We require a principal $2M$-th root of unity $\\rho(\\alpha)$ in\n% $\\mathcal{R}$ to compute the Fourier transforms. This root\n% $\\rho(\\alpha)$ should also have the property that its\n% $\\inparen{\\frac{M}{m}}$-th power is $\\alpha$, so as to make some\n% multiplications in the FFT efficient (see Section\n% \\ref{fourier_analysis}). The root $\\rho(\\alpha)$ can be computed by\n% interpolation in a way similar to that in F\\\"{u}rer's algorithm\n% \\cite[Section 3]{F07}, except that we need a principal $2M$-th root of\n% unity $\\omega$ in $\\Z/p^c\\Z$ to start with. To obtain such a root, we\n% first obtain a $(p-1)$-th root of unity $\\zeta$ in $\\Z/p^c\\Z$ by\n% lifting a generator of $\\mathbb{F}_p^{\\times}$. The\n% $\\inparen{\\frac{p-1}{2M}}$-th power of $\\zeta$ gives us the required\n% $2M$-th root of unity $\\omega$. A generator of $\\mathbb{F}_p^{\\times}$\n% can be computed by brute force, as $p$ is sufficiently small. Having\n% obtained a generator, we use Hensel Lifting \\cite[Theorem\n%   2.23]{Zuckerman}.\n\n% \\begin{lemma}[\\textsf{Hensel Lifting}]\n% Let $\\zeta_s$ be a primitive $(p-1)$-th root of unity in\n% $\\Z/p^s\\Z$. Then there exists a unique primitive $(p-1)$-th root of\n% unity $\\zeta_{s+1}$ in $\\Z/p^{s+1}\\Z$ such that $\\zeta_{s+1}\\equiv\n% \\zeta_s\\pmod{p^s}$. This unique root is given by $\\zeta_{s+1} =\n% \\zeta_s - \\frac{f(\\zeta_s)}{f'(\\zeta_s)}$ where $f(x) = x^{p-1} - 1$.\n% \\end{lemma}\n\n% \\noindent It can be shown that the root $\\zeta$ in $\\Z/p^c\\Z$ thus\n% obtained by lifting is principal. Furthermore, different powers of\n% $\\zeta$ are distinct modulo $p$. Therefore, the difference between any\n% two of them is a unit in $\\Z/p^c\\Z$ and this makes the following\n% interpolation feasible in our setting.\n\n% \\paragraph{Finding $\\rho(\\alpha)$ from $\\omega$:} Since\n% $\\omega$ is a principal $2M$-th root of unity, $\\gamma =\n% \\omega^{\\frac{2M}{2m}}$ is a principal $2m$-th root of unity in\n% $\\Z/p^c\\Z$. Notice that, $\\alpha^m + 1$ uniquely factorizes as,\n% $\\alpha^m + 1 = (\\alpha - \\gamma)(\\alpha - \\gamma^3) \\ldots (\\alpha -\n% \\gamma^{2m-1})$, and the ideals generated by $(\\alpha - \\gamma^i)$ in\n% $\\mathcal{R}$ are mutually coprime as $\\gamma^i - \\gamma^j$ is a unit\n% for $i \\neq j$. Therefore, using Chinese Remaindering, $\\alpha$ has\n% the direct sum representation $(\\gamma, \\gamma^3, \\ldots,\n% \\gamma^{2m-1})$ in $\\mathcal{R}$. Since we require\n% $\\rho(\\alpha)^{\\frac{2M}{2m}} = \\alpha$, it is sufficient to choose a\n% $\\rho(\\alpha)$ whose direct sum representation is $(\\omega, \\omega^3,\n% \\ldots, \\omega^{2m-1})$. Now use Lagrange's formula to interpolate\n% $\\rho(\\alpha)$ as,\n% \\begin{equation*}\n% \\rho(\\alpha) = \\sum_{i=1, \\text{ } i \\text{ odd}}^{2m-1}{\\omega^i \\cdot \\prod_{j=1, \\text{ } j \\neq i, \\text{ } j \\text{ odd}}^{2m-1}{\\frac{\\alpha - \\gamma^j}{\\gamma^i - \\gamma^j}}}\n% \\end{equation*}\n% The inverses of the elements $\\gamma^i - \\gamma^j$ can be easily computed in $\\Z/p^c\\Z$.\n\n\\section{Fourier Transform}\n\\subsection{Inner and Outer DFT} \\label{sec:inoutDFT}\n\nSuppose that $a(x) \\in \\mathcal{S}[x]$ is a polynomial of degree less\nthan $2M$, where $\\mathcal{S}$ is a ring containing a $2M$-th principal\nroot of unity $\\rho$. Let us say that we want to compute the\n$2M$-point DFT of $a(x)$ using $\\rho$ as the root of unity. In other\nwords, we want to compute the elements $a(1), a(\\rho), \\ldots,\na(\\rho^{2M-1})$ is $\\mathcal{S}$. This can be done in two steps.\n\n\\paragraph{Step $1$:}\nCompute the following polynomials using $\\alpha = \\rho^{2M/2m}$.\n\\begin{eqnarray*}\na_0(x) &=& a(x) \\mod (x^{2M/2m} - 1) \\\\\na_1(x) &=& a(x) \\mod (x^{2M/2m} - \\alpha) \\\\\n\t\t\t &\\vdots& \\\\\na_{2m-1}(x) &=& a(x) \\mod (x^{2M/2m} - \\alpha^{2m-1}),\n\\end{eqnarray*}\nwhere $\\deg(a_j(x)) < \\frac{2M}{2m}$ for all $0 \\leq j < 2m$.\n\n\\paragraph{Step $2$:}\nNote that, $a_j(\\rho^{k \\cdot 2m + j}) = a(\\rho^{k \\cdot 2m + j})$ for\nevery $0 \\leq j < 2m$ and $0 \\leq k < \\frac{2M}{2m}$. Therefore, all\nwe need to do to compute the DFT of $a(x)$ is to evaluate the\npolynomials $a_j(x)$ at appropriate powers of $\\rho$.\\\\\n\n\\noindent The idea is to show that both Step $1$ and Step $2$ can be\nperformed by computation of some `smaller' DFTs. Let us see how.\n\n\\paragraph{Performing Step $1$:}\nThe crucial observation here is the following. Fix an integer $\\ell$\nin the range $[0, \\frac{2M}{2m} - 1]$. Then the $\\ell^{th}$\ncoefficients of $a_0(x), a_1(x), \\ldots, a_{2m-1}(x)$ are exactly\n$e_\\ell(1), e_\\ell(\\alpha), \\ldots, e_\\ell(\\alpha^{2m-1})$,\nrespectively, where $e_\\ell(y)$ is the polynomial,\n\n\\begin{equation*}\ne_\\ell(y) = \\sum_{j=0}^{2m-1}{a_{j \\cdot \\frac{2M}{2m} + \\ell} \\cdot y^j}.\n\\end{equation*}\nBut then, finding $e_\\ell(1), e_\\ell(\\alpha), \\ldots,\ne_\\ell(\\alpha^{2m-1})$ is essentially computing the $2m$-point DFT of\n$e_\\ell(y)$ using $\\alpha$ as the $2m^{th}$ root of unity. Therefore,\nall we need to do to find $a_0(x), \\ldots, a_{2m-1}(x)$ is to compute\nthe DFTs of $e_\\ell(y)$ for all $0 \\leq \\ell < \\frac{2M}{2m}$. These\n$\\frac{2M}{2m}$ many $2m$-point DFTs are called the \\emph{inner} DFTs.\n\n\\paragraph{Performing Step $2$:} In order to find $a_j(\\rho^{k \\cdot\n  2m + j})$, for $0 \\leq k < \\frac{2M}{2m}$ and a fixed $j$, we first\ncompute the polynomial $\\tilde{a}_j(x) = a_j(x \\cdot \\rho^j)$ followed\nby a $\\frac{2M}{2m}$-point DFT of $\\tilde{a}_j(x)$ using $\\rho^{2m}$\nas the root of unity. These $2m$ many $\\frac{2M}{2m}$-point DFTs ($j$\nrunning from $0$ to $2m - 1$) are called the \\emph{outer} DFTs. The\npolynomials $\\tilde{a}_j(x)$ can be computed by multiplying the\ncoefficients of $a_j(x)$ by suitable powers of $\\rho$. Such\nmultiplications are termed as \\emph{bad} multiplications (as they would result in recursive calls to integer\nmultiplication). \\\\\n\n\\noindent The above discussion is summarized in the following lemma.\n\n\\begin{lemma} \\label{lem:inoutDFT} \\emph{\\textsf{(DFT time = Inner\n      DFTs + Bad multiplications + Outer DFTs)}} \\\\ Time taken to\n  compute a $2M$-point DFT over $\\mathcal{S}$ is sum of:\n\\begin{enumerate}\n\\item Time taken to compute $\\frac{2M}{2m}$ many $2m$-point inner DFTs over $\\mathcal{S}$ using $\\alpha$ as the $2m$-th root of unity.\n\\item Time to do $2M$ multiplications in $\\mathcal{S}$ by powers of\n  $\\rho$ (bad multiplications).\n\\item Time taken to compute $2m$ many $\\frac{2M}{2m}$-point outer DFTs over $\\mathcal{S}$ using $\\rho^{2m}$ as the $\\frac{2M}{2m}$-th root of unity.\n\\end{enumerate}\n\\end{lemma}\n\n\\subsection{Analysis of the FFT}\\label{fourier_analysis}\n\nWe are now ready to analyse the complexity of multiplying the two\n$k$-variate polynomials $a(X)$ and $b(X)$ (see Section\n\\ref{encoding_section}) using Fast Fourier Transform. Treat $a(X)$ and\n$b(X)$ as univariate polynomials in variable $X_k$ over the ring\n$\\mathcal{S} = \\mathcal{R}[X_1, \\ldots, X_{k-1}]$. We write $a(X)$ and\n$b(X)$ as $a(X_k)$ and $b(X_k)$, respectively, where $\\deg(a(X_k))$\nand $\\deg(b(X_k))$ are less than $M$. Multiplication of $a(X)$ and\n$b(X)$ can be thought of as multiplication of the univariates $a(X_k)$\nand $b(X_k)$ over $\\mathcal{S}$. Also note that, the root\n$\\rho(\\alpha)$ (constructed in Section \\ref{root_section}) is a\nprimitive $2M$-th root of unity in $\\mathcal{S} \\supset\n\\mathcal{R}$. Denote the multiplication complexity of $a(X_k)$ and\n$b(X_k)$ by $\\mathcal{F}(2M, k)$.\n\nMultiplication of $a(X_k)$ and $b(X_k)$ using FFT involves computation\nof three $2M$-point DFTs over $\\mathcal{S}$ and $2M$ pointwise (or\ncomponentwise) multiplications in $\\mathcal{S}$. Let $\\mathcal{D}(2M,\nk)$ be the time taken to compute a $2M$-point DFT over\n$\\mathcal{S}$. By Lemma \\ref{lem:inoutDFT}, the time to compute a DFT\nis the sum of the time for the inner DFTs, the bad multiplications and\nthe outer DFTs. Let us analyse these three terms separately. We will\ngo by the notation in Section \\ref{sec:inoutDFT}, using $\\mathcal{S} =\n\\mathcal{R}[X_1, \\ldots, X_{k-1}]$ and $\\rho = \\rho(\\alpha)$.\n\n\\paragraph{Inner DFT time:} Computing a $2m$-point DFT requires $2m\n\\log (2m)$ additions in $\\mathcal{S}$ and $m \\log (2m)$\nmultiplications by powers of $\\alpha$. The important observation here\nis: since $\\mathcal{R} = \\Z[\\alpha]/(p^c, \\alpha^m + 1)$,\nmultiplication by a power of $\\alpha$ with an element in $\\mathcal{R}$\ncan be readily computed by simple cyclic shifts (with possible\nnegations), which takes only $O(m \\cdot \\log p)$ bit operations. An\nelement in $\\mathcal{S}$ is just a polynomial over $\\mathcal{R}$ in\nvariables $X_1, \\ldots, X_{k-1}$, with degree in each variable bounded\nby $M$. Hence, multiplication by a power of $\\alpha$ with an element\nof $\\mathcal{S}$ can be done using $\\mathcal{N}_{\\mathcal{S}} =\nO(M^{k-1} \\cdot m \\cdot \\log p)$ bit operations. A total of $m \\log\n(2m)$ multiplications takes $O(m \\log m \\cdot\n\\mathcal{N}_{\\mathcal{S}})$ bit operations. It is easy to see that $2m\n\\log (2m)$ additions in $\\mathcal{S}$ also require the same order of\ntime.\n\nSince there are $\\frac{2M}{2m}$ many $2m$-point DFTs, the total time\nspent in the inner DFTs is $O(2M \\cdot \\log m \\cdot\n\\mathcal{N}_{\\mathcal{S}})$ bit operations.\n\n\\paragraph{Bad multiplication time:}\nSuppose that two arbitrary elements in $\\mathcal{R}$ can be multiplied\nusing $\\mathcal{M}_{\\mathcal{R}}$ bit operations. Mulitplication in\n$\\mathcal{S}$ by a power of $\\rho$ amounts to $c_{\\mathcal{S}} =\nM^{k-1}$ multiplications in $\\mathcal{R}$. Since there are $2M$ such\nbad multiplications, the total time is bounded by $O(2M \\cdot\nc_{\\mathcal{S}} \\cdot \\mathcal{M}_{\\mathcal{R}})$.\n\n\\paragraph{Outer DFT time:}\nBy Lemma \\ref{lem:inoutDFT}, the total outer DFT time is $2m \\cdot\n\\mathcal{D}\\left(\\frac{2M}{2m}, k \\right)$.\n\n\\paragraph{Total DFT time:}Therefore, the net DFT time is bounded as,\n\\begin{eqnarray*}\n\\mathcal{D}(2M, k) &=& O\\left(2M \\cdot \\log m \\cdot \\mathcal{N}_{\\mathcal{S}} +\n  2M \\cdot c_{\\mathcal{S}} \\cdot \\mathcal{M}_{\\mathcal{R}}\\right) +\n2m \\cdot \\mathcal{D}\\left(\\frac{2M}{2m}, k\\right) \\\\\n&=& O\\left(2M \\cdot \\log m \\cdot \\mathcal{N}_{\\mathcal{S}} +\n  2M \\cdot c_{\\mathcal{S}} \\cdot \\mathcal{M}_{\\mathcal{R}}\\right) \\cdot\n\\frac{\\log 2M}{ \\log 2m} \\\\\n&=& O\\left(M^k \\log M \\cdot m \\log p + \\frac{M^k \\log M}{\\log m} \\cdot\n  \\mathcal{M}_{\\mathcal{R}}\\right),\n\\end{eqnarray*}\nputting the values of $\\mathcal{N}_{\\mathcal{S}}$ and $c_{\\mathcal{S}}$.\n\n\\paragraph{Pointwise multiplications:}\nFinally, FFT does $2M$ pointwise multiplications in\n$\\mathcal{S}$. Since elements of $\\mathcal{S}$ are $(k-1)$-variate\npolynomials over $\\mathcal{R}$, with degree in every variable bounded\nby $M$, the total time taken for pointwise multiplications is $2M\n\\cdot \\mathcal{F}(2M, k-1)$ bit operations.\n\n\\paragraph{Total polynomial multiplication time:}\nThis can be expressed as,\n\n\n\\begin{eqnarray} \\label{eqn_FFT_complexity}\n\\mathcal{F}(2M, k) &=& O\\left(M^k \\log M \\cdot m \\log p + \\frac{M^k \\log M}{\\log m} \\cdot \\mathcal{M}_{\\mathcal{R}}\\right) + 2M \\cdot \\mathcal{F}(2M, k-1) \\nonumber \\\\\n&=& O\\left(M^k \\log M \\cdot m \\log p + \\frac{M^k \\log M}{\\log m} \\cdot \\mathcal{M}_{\\mathcal{R}}\\right),\n\\end{eqnarray}\nas $k$ is a constant. \\\\\n\n% \\subsection*{Inverse FFT}\n\n\n% \\todo{Pres 9}Computing the inverse of a fourier transform  with $\\rho$ as the root\n% of unity just amounts to yet another fourier transform with\n% $\\rho^{-1}$ as the root of unity. This can be seen by observing that a\n% fourier transform can be thought of as a matrix multiplication. If $a(x) = a_0 + a_1 x + \\cdots a_{2M-1}x^{2M-1}$ and $b_i = a(\\rho^i)$ for $i=0\\cdots (2M-1)$,  then\n% \\begin{eqnarray*}\n% \\insquar{\\begin{array}{c}b_0\\\\b_1\\\\b_2\\\\ \\vdots \\\\b_{2M-1}\\end{array}} & = &  \\insquar{\\begin{array}{cccc}\n%       1      & 1          & \\cdots &  1\\\\\n%       1      & \\rho       & \\cdots & \\rho^{2M-1}\\\\\n%       1      & \\rho^2     & \\cdots & \\rho^{2(2M-1)}\\\\\n%       \\vdots & \\vdots     & \\ddots & \\vdots \\\\\n%       1      & \\rho^{2M-1}& \\cdots & \\rho^{(2M-1)(2M-1)}\n%     \\end{array}}\\insquar{\\begin{array}{c}a_0\\\\a_1\\\\a_2\\\\ \\vdots \\\\a_{2M-1} \\end{array}}.\n% \\end{eqnarray*}\n% Since $\\rho$ is a principal root of unity, it is easy to see that\n% \\begin{eqnarray*}\n% \\insquar{\\begin{array}{c}a_0\\\\a_1\\\\a_2\\\\ \\vdots \\\\a_{2M-1}\\end{array}} & = &  \\frac{1}{N}\\cdot\\insquar{\\begin{array}{cccc}\n%       1      & 1          & \\cdots &  1\\\\\n%       1      & \\rho^{-1}       & \\cdots & \\rho^{-(2M-1)}\\\\\n%       1      & \\rho^{-2}     & \\cdots & \\rho^{-2(2M-1)}\\\\\n%       \\vdots & \\vdots     & \\ddots & \\vdots \\\\\n%       1      & \\rho^{-(2M-1)}& \\cdots & \\rho^{-(2M-1)(2M-1)}\n%     \\end{array}}\\insquar{\\begin{array}{c}b_0\\\\b_1\\\\b_2\\\\ \\vdots \\\\b_{2M-1} \\end{array}}.\n% \\end{eqnarray*}\n% which is just another fourier transform with $\\rho^{-1}$ as a root of unity instead. \\\\\n\n\n\nWe now present an equivalent group theoretic interpretation of the\nabove process of polynomial multiplication, which is a subject of\ninterest in itself.\n\n\\subsection{A Group Theoretic Interpretation}\n\nA convenient way to study polynomial multiplication is to interpret it\nas multiplication in a \\emph{group algebra}.\n\n\\begin{definition}\n\\emph{\\textsf{(Group Algebra)}}\n  Let $G$ be any group. The \\emph{group algebra} of $G$ over a ring $R$ is\n  the set of formal sums $\\sum_{g \\in G} \\alpha_g g$ where $\\alpha_g\n  \\in R$ with addition defined point-wise and multiplication defined\n  via convolution as follows\n  $$ \\left(\\sum_g \\alpha_g g\\right) \\left(\\sum_h\n  \\beta_h h\\right) = \\sum_{u}\\inparen{\\sum_{gh=u} \\alpha_g \\beta_h}u $$\n\\end{definition}\n\nIn this section, we study the Fourier transform over the group algebra\n$R[E]$ where $E$ is an \\emph{additive abelian group}. Most of this,\nalbeit in a different form, is well known but is provided here for\ncompleteness \\cite[Chapter 17]{Igor}.\n\nIn order to simplify our presentation, we will fix the base ring to be\n$\\C$, the field of complex numbers. Let $n$ be the \\emph{exponent} of\n$E$, that is the maximum order of any element in $E$. A similar\napproach can be followed for any other base ring as long as it has a\nprincipal $n$-th root of unity.\n\nWe consider $\\C[E]$ as a vector space with basis $\\{ x \\}_{x \\in E}$\nand use the Dirac notation to represent elements of $\\C[E]$ --- the\nvector $\\ket{x}$, $x$ in $E$, denotes the element $1 . x$ of $\\C[E]$.\n\nMultiplying univariate polynomials over $R$ of degree less than $n$\ncan be seen as multiplication in the group algebra $R[G]$ where $G$ is\nthe cyclic group of order $2n$. Say $a(x) = a_0 + a_1 x +\n\\cdots + a_dx^d$ and $b(x)= b_0 + b_1x \\cdots + b_dx^d$ (with $d<n$)\nare the polynomials we wish to multiply, they can be embedded in\n$\\C[\\Z/2n\\Z]$ as $\\ket{a} = \\sum_{i=0}^d a_i \\ket{i}$ and $\\ket{b} =\n\\sum_{i=0}^d b_i\\ket{i}$. It is trivial to see that their product in\nthe group algebra is the embedding of the product of the\npolynomials. Similarly, multiplying $k$-variate polynomials of degree\nless than $n$ in each variable can be seen as multiplying in the group\nalgebra $R[G^k]$, where $G^k$ denotes the $k$-fold product group\n$G\\times\\ldots \\times G$.\n\n\n\n\\begin{definition}\n\\emph{\\textsf{(Characters)}} Let $E$ be an additive abelian group. A\n\\emph{character} of $E$ is a homomorphism from $E$ to $\\C^*$.\n\\end{definition}\n\nAn example of a character of $E$ is the trivial character, which we\nwill denote by $1$, that assigns to every element of $E$ the complex\nnumber $1$. If $\\chi_1$ and $\\chi_2$ are two characters of $E$ then\ntheir product $\\chi_1 . \\chi_2$ is defined as $\\chi_1 . \\chi_2(x) =\n\\chi_1(x) \\chi_2(x)$.\n\n\\begin{proposition}\\cite[Chapter 17, Theorem 1]{Igor}\\label{prop:dual-isomorphism}\n  Let $E$ be an additive abelian group of exponent $n$. Then the\n  values taken by any character of $E$ are $n$-th roots of\n  unity. Furthermore, the characters form a \\emph{multiplicative\n    abelian group} $\\hat{E}$ which is isomorphic to $E$.\n\\end{proposition}\n\nAn important property that the characters satisfy is the following\n\\cite[Corollary 2.14]{Isaacs}.\n\n\\begin{proposition}\\label{prop:schur-orthogonality}\n\\emph{\\textsf{(Schur's Orthogonality)}}\n  Let $E$ be an additive abelian group. Then\n  \\[ \\sum_{x \\in E} \\chi(x) =%\n  \\begin{cases}\n    0 & \\textrm{ if $\\chi \\neq 1$,}\\\\\n    \\# E &\\textrm{ otherwise}\n  \\end{cases} \\quad \\text{and}\\quad\n  \\sum_{\\chi \\in \\hat{E}} \\chi(x) =%\n  \\begin{cases}\n    0 & \\textrm{ if $x \\neq 0$,}\\\\\n    \\# E &\\textrm{ otherwise.}\n  \\end{cases}\n  \\]\n\\end{proposition}\n\nIt follows from Schur's orthogonality that the collection of vectors\n$\\ket{\\chi} = \\sum_x \\chi(x) \\ket{x}$ forms a basis of $\\C[E]$. We\nwill call this basis the \\emph{Fourier basis} of $\\C[E]$.\n\n\\begin{definition}\n\\emph{\\textsf{(Fourier Transform)}}\nLet $E$ be an additive abelian group and let $x \\mapsto \\chi_x$ be an\nisomorphism between $E$ and $\\hat{E}$. The \\emph{Fourier transform}\nover $E$ is the linear map from $\\C[E]$ to $\\C[E]$ that sends\n$\\ket{x}$ to $\\ket{\\chi_x}$.\n\\end{definition}\n\nThus, the Fourier transform is a change of basis from the point basis\n$\\{ \\ket{x} \\}_{x \\in E}$ to the Fourier basis $\\{\n\\ket{\\chi_x}\\}_{x\\in E}$. The Fourier transform is unique only up to\nthe choice of the isomorphism $x \\mapsto \\chi_x$. This isomorphism is\ndetermined by the choice of the principal root of unity.\n\nIt is a standard fact in representation theory that any character\n$\\chi$ of an abelian group satisfies $\\chi_y(x) = \\chi_x(y)$ for every\n$x,y$. Using this and Proposition~\\ref{prop:schur-orthogonality}, it is easy\nto see that this transform can be inverted by the map $\\ket{x} \\mapsto\n\\frac{1}{n}\\ket{\\overline{\\chi_x}}$. Hence the \\emph{Inverse Fourier\n  Transform} is essentially just a Fourier transform using $x\\mapsto\n\\overline{\\chi_x}$ as the isomorphism between $E$ and $\\hat{E}$.\n\n\\begin{remark}\\label{rem-Fourier-inner}\n  Given an element $\\ket{f} \\in\n  \\C[E]$, to compute its Fourier transform (or Inverse Fourier transform) it is sufficient to compute\n  the \\emph{Fourier coefficients} $\\{\\braket{\\chi}{f} \\}_{\\chi \\in\n    \\hat{E}}$.\n\\end{remark}\n\n\\subsubsection*{Fast Fourier Transform}\n\nWe now describe the Fast Fourier Transform for general abelian groups\nin the character theoretic setting. For the rest of the section fix an\nadditive abelian group $E$ over which we would like to compute the\nFourier transform. Let $A$ be any subgroup of $E$ and let $B =\nE/A$. For any such pair of abelian groups $A$ and $B$, we have an\nappropriate Fast Fourier transformation, which we describe in the rest\nof the section.\n\n\\begin{proposition}\\label{prop-character-lift}\n  \\begin{enumerate}\n  \\item Every character $\\lambda$ of $B$ can be ``lifted'' to a\n    character of $E$ (which will be denoted by $\\tilde\\lambda$ defined\n    as follows $\\tilde\\lambda(x) = \\lambda(x + A)$.\n  \\item Let $\\chi_1$ and $\\chi_2$ be two characters of $E$ that when\n    restricted to $A$ are identical. Then $\\chi_1 = \\chi_2 \\tilde\\lambda$ for\n    some character $\\lambda$ of $B$.\n  \\item The group $\\hat{B}$ is (isomorphic to) a subgroup of $\\hat{E}$\n    with the quotient group $\\hat{E}/\\hat{B}$ being (isomorphic to)\n    $\\hat{A}$.\n  \\end{enumerate}\n\\end{proposition}\n\\begin{proof}\nIt is very easy to check that $\\tilde\\lambda(x) = \\lambda(x + A)$ is indeed\na homomorphism from $E$ to $\\C$. This therefore establishes that\n$\\hat{B}$ is a subgroup of $\\hat{E}$.\n\n\\medskip As for the second, define the map $\\tilde\\lambda(x) =\n\\frac{\\chi_1(x)}{\\chi_2(x)}$. It is easy to check that this is a\nhomomorphism from $E$ to $\\C$. Then, for $x\\in E$ and $a\\in A$\n$$\n\\tilde\\lambda(x + a) = \\frac{\\chi_1(x)\\chi_1(a)}{\\chi_2(x)\\chi_2(a)} =\n\\frac{\\chi_1(x)}{\\chi_2(x)} = \\tilde\\lambda(x)\n$$\nAnd hence $\\tilde\\lambda$ is equal over cosets over $A$ in $E$ and hence $\\chi$\nis indeed a homomorphism from $B$ to $\\C$.\n\n\\medskip The third part follows from\nProposition~\\ref{prop:dual-isomorphism} and the fact that any quotient\ngroup of a finite abelian group is isomorphic to a subgroup.\n% For the third, every character $\\chi\\in \\hat{E}$ can be restricted\n% to $A$ to get a character $\\phi\\in \\hat{A}$. Therefore, the\n% restriction map is a natural homomorphism from $\\hat{E}$ to\n% $\\hat{A}$. It suffices to show that this homomorphism is surjective\n% and the kernel is $\\hat{B}$. Suppose $\\varphi$ is an arbitrary\n% character of $A$. Let $R = \\inbrace{x_b}_{b\\in B}$ be a set of coset\n% representatives of $A$ in $E$. Then every element $x\\in E$ can be\n% uniquely written as $x_b + a$ where $x_b\\in R$ and $a\\in\n% A$. Consider the following map:\n% $$\n% \\chi(x_b + a) =  \\varphi(a)\n% $$ It is easy to verify that this is indeed a character of $E$, whose\n% restriction to $A$ is $\\varphi$. Therefore, the restriction map is\n% surjective. And if $\\chi$ is in the kernel of this restriction, then\n% $\\chi$ and the trivial character are identical on $A$ and therefore\n% $\\chi = 1\\cdot \\lambda = \\lambda \\in \\hat{B}$. Thus, the kernel is\n% precisely $\\hat{B}$ and hence $\\hat{A}$ is the quotient of $\\hat{E}$\n% and $\\hat{B}$.\n\\end{proof}\n\n\n\nWe now consider the task of computing the Fourier transform of an\nelement $\\ket{f} = \\sum f_x \\ket{x}$ presented as a list of\ncoefficients $\\{f_x\\}$ in the point basis. For this, it is sufficient\nto compute the Fourier coefficients $\\{\\braket{\\chi}{f}\\}$ for each\ncharacter $\\chi$ of $E$ (Remark~\\ref{rem-Fourier-inner}). To describe\nthe Fast Fourier transform we fix two sets of cosets representatives,\none of $A$ in $E$ and one of $\\hat{B}$ in $\\hat{E}$ as follows.\n\n\\begin{enumerate}\n  \\item For each $b \\in B$, $b$ being a coset of $A$, fix a coset\n    representative $x_b \\in E$ such $b = x_b + A$.\n  \\item For each character $\\varphi$ of $A$, fix a character\n    $\\chi_\\varphi$ of $E$ such that $\\chi_\\varphi$ restricted to $A$ is\n    the character $\\varphi$. The characters $\\{ \\chi_\\varphi \\}$ form\n    (can be thought of as) a set of coset representatives of $\\hat{B}$\n    in $\\hat{E}$.\n\\end{enumerate}\n\nSince $\\{ x_b \\}_{b \\in B}$ forms a set of coset representatives, any\n$\\ket{f} \\in \\C[E]$ can be written uniquely as $\\ket{f} = \\sum f_{b,a}\n\\ket{x_b + a}$.\n\n\\begin{proposition}\\label{prop-Fourier-coefficient}\n  Let $\\ket{f} = \\sum f_{b,a}\\ket{x_b + a}$ be an element of $\\C[E]$.\n  For each $b \\in B$ and $\\varphi \\in \\hat{A}$ let $\\ket{f_b}\\in\n  \\C[A]$ and $\\ket{f_\\varphi} \\in \\C[B]$ be defined as\n  follows.\n  \\begin{eqnarray*}\n    \\ket{f_b} &= & \\sum_{a \\in A} f_{b,a} \\ket {a}\\\\\n    \\ket{f_\\varphi} & = &\\sum_{b \\in B} \\overline{\\chi}_{\\varphi}(x_b)\n    \\braket{\\varphi}{f_b} \\ket{b}\n  \\end{eqnarray*}\n  Then for any character $\\chi = \\chi_\\varphi\\tilde\\lambda$ of $E$ the\n  Fourier coefficient $\\braket{\\chi}{f} =\n  \\braket{\\lambda}{f_\\varphi}$.\n\\end{proposition}\n\n\\begin{proof}\n$$\n\\braket{\\chi}{f} \\quad=\\quad \\sum_{b\\in B , a\\in A} \\overline{\\chi_\\varphi\n  \\tilde\\lambda(x_b + a)} \\cdot f_{b,a}\n$$\n\\noindent\nRecall that for any $\\tilde\\lambda$, that is a lift of a character $\\lambda$ of\n$B$, acts identically inside cosets of $A$ and hence $\\tilde\\lambda(x_b + a) = \\lambda(b)$. Therefore, the above sum can be\nrewritten as follows:\n\\begin{eqnarray*}\n\\sum_{b\\in B , a\\in A} \\overline{\\chi_\\varphi\n  \\tilde\\lambda(x_b + a)} \\cdot f_{b,a} & = & \\sum_{b\\in B} \\sum_{a\\in A}\n\\overline{\\chi_\\varphi(x_b + a)}\\overline{\\lambda(b)} \\cdot\nf_{b,a}\\\\\n & = & \\sum_{b\\in B} \\overline{\\lambda(b)}\\cdot\n\\overline{\\chi_\\varphi(x_b)}\\sum_{a\\in A}\n\\overline{\\varphi(a)} f_{b,a}\n\\end{eqnarray*}\nThe inner sum over $a$ is precisely $\\braket{\\varphi}{f_b}$ and\ntherefore we have:\n\\begin{eqnarray*}\n\\braket{\\chi}{f} & = & \\sum_{b\\in B}\n\\overline{\\lambda(x_b)}\\cdot \\overline{\\chi_\\varphi(x_b)}\n\\braket{\\varphi}{f_b}\n\\end{eqnarray*}\nwhich can be rewritten as $\\braket{\\lambda}{f_\\varphi}$ as claimed.\n\\end{proof}\n\n\nWe are now ready to describe the Fast Fourier transform given an\nelement $\\ket{f} = \\sum f_x \\ket{x}$.\n\n\\begin{enumerate}\n\\item \\label{step_inner_dft} For each $b \\in B$ compute the Fourier\n  transforms of $\\ket{f_b}$. This requires $\\# B$ many Fourier\n  transforms over $A$.\n\\item \\label{step_bad_mult}As a result of the previous step we have\n  for each $b \\in B$ and $\\varphi \\in \\hat{A}$ the Fourier\n  coefficients $\\braket{\\varphi}{f_b}$. Compute for each $\\varphi$ the\n  vectors $\\ket{f_\\varphi} = \\sum_{b \\in B}\n  \\overline{\\chi}_{\\varphi}(x_b) \\braket{\\varphi}{f_b} \\ket{b}$. This\n  requires $\\# \\hat{A} . \\# B = \\# E$ many multiplications by roots of\n  unity.\n\\item \\label{step_outer_dft} For each $\\varphi \\in \\hat{A}$ compute\n  the Fourier transform of $\\ket{f_\\varphi}$. This requires $\\#\\hat{A}\n  = \\# A$ many Fourier transforms over $B$.\\label{item-Fourier-B}\n\\item Any character $\\chi$ of $E$ is of the\n  form $\\chi_\\varphi \\lambda$ for some $\\varphi \\in \\hat{A}$ and\n  $\\lambda \\in \\hat{B}$. Using\n  Proposition~\\ref{prop-Fourier-coefficient} we have at the end of\n  Step~\\ref{item-Fourier-B} all the Fourier coefficients\n  $\\braket{\\chi}{f} = \\braket{\\lambda}{f_\\varphi}$.\n\\end{enumerate}\n\nIf the quotient group $B$ itself has a subgroup that is isomorphic to\n$A$ then we can apply this process recursively on $B$ to obtain a divide and\nconquer procedure to compute Fourier transform. In the standard FFT we\nuse $E = \\Z/2^n\\Z$. The subgroup $A$ is $2^{n-1}E$ which is isomorphic\nto $\\Z/2\\Z$ and the quotient group $B$ is $\\Z/2^{n-1}\\Z$.\n\n\\subsubsection*{Analysis of the Fourier Transform}\n\nOur goal is to multiply $k$-variate polynomials over $\\mathcal{R}$, with the\ndegree in each variable less than $M$. This can be achieved by\nembedding the polynomials into the algebra of the product group $E =\n\\inparen{\\frac{\\Z}{2M\\cdot \\Z}}^k$ and multiplying them as elements of\nthe algebra. Since the exponent of $E$ is $2M$, we require a principal\n$2M$-th root of unity in the ring $\\mathcal{R}$. We shall use the root\n$\\rho(\\alpha)$ (as defined in Section~\\ref{root_section}) for the\nFourier transform over $E$.\n\nFor every subgroup $A$ of $E$, we have a corresponding FFT. We choose\nthe subgroup $A$ as $\\inparen{\\frac{\\Z}{2m\\cdot \\Z}}^k$ and let $B$ be\nthe quotient group $E/A$. The group $A$ has exponent $2m$ and $\\alpha$\nis a principal $2m$-th root of unity. Since $\\alpha$ is a power of\n$\\rho(\\alpha)$, we can use it for the Fourier transform over $A$. As\nmultiplications by powers of $\\alpha$ are just shifts, this makes\nFourier transform over $A$ efficient.\n\nLet $\\mathcal{F}(M,k)$ denote the complexity of computing the Fourier transform\nover $\\inparen{\\frac{\\Z}{2M\\cdot \\Z}}^k$. We have\n\\begin{equation}\n\\mathcal{F}(M,k) = \\inparen{\\frac{M}{m}}^k \\mathcal{F}(m,k) + (2M)^k\n\\mathcal{M}_{\\mathcal{R}}+(2m)^k\\mathcal{F}\\inparen{\\frac{M}{2m},k}\n\\label{first_recursive_step}\n\\end{equation}\nwhere $\\mathcal{M}_{\\mathcal{R}}$ denotes the complexity of multiplications in\n$\\mathcal{R}$. The first term comes from the $\\# B$ many Fourier transforms\nover $A$ (Step~\\ref{step_inner_dft} of FFT), the second term\ncorresponds to the multiplications by roots of unity\n(Step~\\ref{step_bad_mult}) and the last term comes from the $\\# A$\nmany Fourier transforms over $B$ (Step~\\ref{step_outer_dft}).\n\nSince $A$ is a subgroup of $B$ as well, Fourier transforms over $B$\ncan be recursively computed in a similar way, with $B$ playing the\nrole of $E$. Therefore, by simplifying the recurrence in\nEquation~\\ref{first_recursive_step} we get:\n\\begin{equation}\n\\mathcal{F}(M,k) = O\\inparen{\\frac{M^k\\log M}{m^k\\log m}\\mathcal{F}(m,k) +\n  \\frac{M^k\\log M}{\\log m}\\mathcal{M}_{\\mathcal{R}}}\n\\label{eqn_with_Fa}\n\\end{equation}\n\n\\begin{lemma}\\label{lem-Fmk}\n$\\mathcal{F}(m,k) = O(m^{k+1}\\log m\\cdot \\log p)$\n\\end{lemma}\n\\begin{proof}\nThe FFT over a group of size $n$ is usually done by taking $2$-point\nFFT's followed by $\\frac{n}{2}$-point FFT's. This involves $O(n\\log\nn)$ multiplications by roots of unity and additions in base\nring. Using this method, Fourier transforms over $A$ can be computed\nwith $O(m^k\\log m)$ multiplications and additions in $\\mathcal{R}$. Since each\nmultiplication is between an element of $\\mathcal{R}$ and a power of $\\alpha$,\nthis can be efficiently achieved through shifting operations. This is\ndominated by the addition operation, which takes $O(m\\log p)$ time,\nsince this involves adding $m$ coefficients from $\\Z/p^c\\Z$.\n\\end{proof}\n\nTherefore, from Equation~\\ref{eqn_with_Fa},\n\\begin{equation*}\n\\mathcal{F}(M,k) = O\\inparen{M^k\\log M\\cdot m\\cdot \\log p + \\frac{M^k\\log\n    M}{\\log m}\\mathcal{M}_{\\mathcal{R}}}.\n\\end{equation*}\n\n\\section{Algorithm and Analysis}\n\\subsection{Integer Multiplication Algorithm}\\label{intmult_section}\n\nWe are given two integers $a,b< 2^N$ to multiply. We fix constants $k$\nand $c$  whose values are given in\nSection~\\ref{complexity_section}. The algorithm is as follows:\n\\begin{enumerate}\n\\item Choose $M$ and $m$ as powers of two such that $M^k \\approx\n  \\frac{N}{\\log^2N}$ and $m \\approx \\log N$. Find the least prime\n  $p\\equiv 1\\pmod{2M}$ (Lemma~\\ref{prime_time}).\n\\item Encode the integers $a$ and $b$ as $k$-variate polynomials\n  $a(X)$ and $b(X)$, respectively, over the ring $\\mathcal{R} =\n  \\Z[\\alpha]/(p^c, \\alpha^m + 1)$ (Section~\\ref{encoding_section}).\n\\item Compute the root $\\rho(\\alpha)$ (Section~\\ref{root_section}).\n\\item Use $\\rho(\\alpha)$ as the principal $2M$-th root of unity to\n  compute the Fourier transforms of the $k$-variate polynomials $a(X)$\n  and $b(X)$. Multiply component-wise and take the inverse Fourier\n  transform to obtain the product polynomial. (Sections\n  \\ref{sec:inoutDFT} and \\ref{fourier_analysis})\n\\item Evaluate the product polynomial at appropriate powers of two to\n  recover the integer product and return it\n  (Section~\\ref{encoding_section}).\n\\end{enumerate}\n\n\\subsection{Complexity Analysis}\\label{complexity_section}\n\nThe choice of parameters should ensure that the following constraints\nare satisfied:\n\\begin{enumerate}\n\\item $M^k = O\\inparen{\\frac{N}{\\log^2N}}$ and $m = O(\\log\n  N)$.\n\\item $M^L = O(N^\\varepsilon)$, where $L$ is the Linnik constant\n  (Theorem~\\ref{linnik_theorem}) and $\\varepsilon$ is any constant less\n  than $1$. Recall that this makes picking the prime by brute force\n  feasible (see Lemma~\\ref{prime_time}).\n\\item $p^c > 2M^k\\cdot m\\cdot 2^{2u}$ where $u = \\frac{2N}{M^km}$. This\n  is to prevent overflows during modular arithmetic (see\n  Section~\\ref{encoding_section}).\n\\end{enumerate}\n\\noindent\nIt is straightforward to check that $k > L+1$ and $c > 5(k+1)$ satisfy\nthe above constraints. Since $L\\leq 5.2$, it is sufficient to choose\n$k = 7$ and $c = 42$.\\\\\n\n\nLet $T(N)$ denote the time complexity of multiplying two $N$ bit\nintegers. This consists of:\n\n\\begin{itemize}\n\\item Time required to pick a suitable prime $p$,\n\\item Computing the root $\\rho(\\alpha)$,\n\\item Encoding the input integers as polynomials,\n\\item Multiplying the encoded polynomials,\n\\item Evaluating the product polynomial.\n\\end{itemize}\n\nAs argued before, the prime $p$ can be chosen in $o(N)$ time. To\ncompute $\\rho(\\alpha)$, we need to lift a generator of\n$\\mathbb{F}_p^{\\times}$ to $\\Z/p^c\\Z$ followed by an interpolation. Since $c$\nis a constant and $p$ is a prime of $O(\\log N)$ bits, the time\nrequired for Hensel Lifting and interpolation is $o(N)$.\n\nThe encoding involves dividing bits into smaller blocks, and\nexpressing the exponents of $q$ in base $M$\n(Section~\\ref{encoding_section}) and all these take $O(N)$ time since\n$M$ is a power of $2$. Similarly, evaluation of the product polynomial\ntakes linear time as well. Therefore, the time complexity is dominated\nby the time taken for polynomial multiplication.\n\n\\subsubsection*{Time complexity of Polynomial Multiplication}\n\nFrom Equation~\\ref{eqn_FFT_complexity}, the complexity of polynomial multiplication is given by,\n\\[\n\\mathcal{F}(2M,k) = O\\inparen{M^k\\log M\\cdot m\\cdot \\log p + \\frac{M^k\\log\n    M}{\\log m}\\cdot \\mathcal{M}_{\\mathcal{R}}}.\n\\]\n\n\\begin{proposition}\\cite{scho_complex}\n  If $\\mathcal{M}_{\\mathcal{R}}$ denotes the complexity of\n  multiplication in $\\mathcal{R}$, then $\\mathcal{M}_{\\mathcal{R}} =\n  T\\left(O(\\log^2{N})\\right)$ where $T(x)$ denotes the complexity of\n  multiplying two $x$-bit integers.\n\\end{proposition}\n\\begin{proof}\n  Elements of $\\mathcal{R}$ can be viewed as polynomials in $\\alpha$\n  over $\\Z/p^c\\Z$ with degree at most $m$. Given two such polynomials\n  $f(\\alpha)$ and $g(\\alpha)$, encode them as follows: Replace\n  $\\alpha$ by $2^d$, transforming the polynomials $f(\\alpha)$ and\n  $g(\\alpha)$ to the integers $f(2^d)$ and $g(2^d)$ respectively.  The\n  parameter $d$ is chosen such that the coefficients of the product\n  $h(\\alpha) = f(\\alpha) g(\\alpha)$ can be recovered from the product\n  $f(2^d)\\cdot g(2^d)$. For this, it is sufficient to ensure that the\n  maximum coefficient of $h(\\alpha)$ is less than $2^d$.  Since $f$\n  and $g$ are polynomials of degree $m$, we would want $2^d$ to be\n  greater than $m\\cdot p^{2c}$, which can be ensured by choosing $d =\n  O\\left(\\log{N}\\right)$. The integers $f(2^d)$ and $g(2^d)$ are\n  bounded by $2^{md}$, which is of $O(\\log^2 N)$ bits. The product\n  $f(\\alpha)\\cdot g(\\alpha)$ can be decoded from the integer product\n  $f(2^d)\\cdot g(2^d)$ by splitting the bits into $(2m-1)$ blocks of\n  $d$ bits each (one for each coefficient of $\\alpha^i$) to obtain a\n  polynomial in $\\Z[\\alpha]$ and reducing it modulo $p^c$ and\n  $\\alpha^m + 1$. Reducing modulo $(\\alpha^m + 1)$ can be performed in\n  $O(md) = O(\\log^2N)$ time. Dividing by $p^c$, which has $O(\\log N)$\n  bits, can be performed in the same time as multiplying $O(\\log N)$\n  bit integers using standard techniques (see for example\n  \\cite[Chapter 4]{Knuth}). Since $T(N) = \\Omega(N)$, we have that\n  $\\mathcal{M}_{\\mathcal{R}} = T(O(\\log^2 N)) + O(\\log N \\cdot\n  T(O(\\log N))) = T(O(\\log^2 N))$ bit operations.\n\\end{proof}\n\nTherefore, the complexity of our integer multiplication algorithm\n$T(N)$ is given by,\n\\begin{eqnarray*}\nT(N) & = & O(\\mathcal{F}(2M, k)) = O\\inparen{M^k\\log M\\cdot m\\cdot \\log p + \\frac{M^k\\log\n  M}{\\log m} \\cdot \\mathcal{M}_{\\mathcal{R}}}\\\\\n& = & O\\inparen{N\\log N + \\frac{N}{\\log N\\cdot \\log\\log N} \\cdot T(O(\\log^2N))}\n\\end{eqnarray*}\n\n\\noindent Solving the above recurrence leads to the following theorem.\n\n\\begin{theorem} \\label{thm:mainthmx}\nGiven two $N$ bit integers, their product can be computed using\n$N\\cdot \\log N\\cdot 2^{O(\\log^*N)}$ bit operations.\n\\end{theorem}\n\n\\subsubsection*{Performing on multi-tape turing machines}\n\nThe upper-bound presented in Theorem \\ref{thm:mainthmx} holds for\nmulti-tape turing machines. The only part of the algorithm that\nwarrants an explanation is regrouping of the terms in preparation for\nthe inner and outer DFTs. For the inner DFT, we are given $\\ket{f} =\n\\sum_{a,b} f_{b,a}\\ket{x_b + a}$ and we wish to write down $\\ket{f_b}\n= \\sum_{a} f_{b,a}\\ket{a}$ for each $b\\in B$. The following discussion\nessentially outlines how this can be performed on a multi-tape turing\nmachine using $O(N\\log m)$ bit operations. (Recall that the group $E =\n(\\Z/2M\\Z)^k$ and $A = (\\Z/2m\\Z)^k$ and both $M$ and $m$ are powers of\n$2$). \\\\\n\nWe may assume that the coefficients are listed according to the\nnatural lexicographic order of $(\\Z/2M\\Z)^k$. To ease the\npresentation, we first present the approach for $k=1$. It would be\nstraightforward to generalize this to larger $k$ by repeated\napplications of this approach.\n\n\nGiven as input is a sequence of coefficients $f_g$ for each $g\\in\n\\tilde{E} = \\Z/2M\\Z$ in the natural lexicographic order on one of the\ntapes of the turing machine. We can then ``shuffle'' the input tape\nusing two passes to order the coefficients according to\n$\\inbrace{0,M,1,M+1,\\dots, M-1,2M-1}$ (by copying the first half with\nappropriate blanks, and copying the second half on the second\npass). This results in regrouping the inputs as various cosets of\n$\\Z/2\\Z$. By considering two successive elements as a block and\nrepeating the shuffling, we obtain various cosets of\n$Z/4\\Z$. Repeating this process $\\log(2m)$ times regroups the elements\naccording to various cosets of $\\Z/2m\\Z$.\\\\\n\nSuppose that $E = (\\Z/2M\\Z)^k$ and that the coefficients are ordered\naccording to the natural lexicographic order. By repeating the same\nshuffling process for $\\log(2m)$ steps, the coefficients are regrouped\naccording to the cosets of $\\inbrace{0}^{k-1} \\times (\\Z/2m\\Z)$ and\nhence there are $M/m$ many groups. By considering every $2m$\nsuccessive coefficients as one block, each of the $M/m$ groups can\nbe thought of as coefficients ordered according to the natural\nlexicographic order of $(\\Z/2M\\Z)^{k-1}$. By repeating this for\n$(k-1)$ more steps, we can reorder the coefficients according to the\ncosets of $(\\Z/2m\\Z^k)$.\n\nThe procedure totally requires $k\\log(2m)$ passes over the tapes and\nhence can be performed in $O(N\\log m)$ time on a $3$-tape\\footnote{an\n  input tape, an output tape, and a third tape for a counter} turing\nmachine. With the above discussion, it can be easily seen that the\nupper-bound holds for multi-tape turing machines.\n\n\\begin{theorem}\nGiven two $N$ bit integers, their product can be computed using\n$N\\cdot \\log N\\cdot 2^{O(\\log^*N)}$ bit operations on a multi-tape turing machine.\n\\end{theorem}\n\n\n\\section{A Comparison with F\\\"{u}rer's Algorithm} \\label{Qp_section}\n\nOur algorithm can be seen as a $p$-adic version of F\\\"{u}rer's integer\nmultiplication algorithm, where the field $\\C$ is replaced by $\\Q_p$,\nthe field of $p$-adic numbers (for a quick introduction, see Baker's\nonline notes \\cite{Baker}). Much like $\\C$, where representing a\ngeneral element (say in base $2$) takes infinitely many bits,\nrepresenting an element in $\\Q_p$ takes infinitely many $p$-adic\ndigits. Since we cannot work with infinitely many digits, all\narithmetic has to be done with finite precision. Modular arithmetic in\nthe base ring $\\Z[\\alpha]/(p^c, \\alpha^m + 1)$, can be viewed as\narithmetic in the ring $\\Q_p[\\alpha]/(\\alpha^m + 1)$ keeping a\nprecision of $\\varepsilon = p^{-c}$.\n\nArithmetic with finite precision naturally introduces some errors in\ncomputation. However, the nature of $\\Q_p$ makes the error analysis\nsimpler. The field $\\Q_p$ comes with a norm $\\abs{\\ \\cdot\\ }_p$ called\nthe $p$-adic norm, which satisfies the stronger triangle inequality\n$\\abs{x+y}_p \\leq \\max\\inparen{\\abs{x}_p, \\abs{y}_p}$ \\cite[Proposition\n  2.6]{Baker}. As a result, unlike in $\\C$, the errors in computation\ndo not compound.\\\\\n\nRecall that the efficiency of FFT crucially depends on a special\nprincipal $2M$-th root of unity in $\\Q_p[\\alpha]/(\\alpha^m + 1)$. Such\na root is constructed with the help of a primitive $2M$-th root of\nunity in $\\Q_p$. The field $\\Q_p$ has a primitive $2M$-th root of\nunity if and only if $2M$ divides $p-1$ \\cite[Theorem\n  5.12]{Baker}. Also, if $2M$ divides $p-1$, a $2M$-th root can be\nobtained from a $(p-1)$-th root of unity by taking a suitable power. A\nprimitive $(p-1)$-th root of unity in $\\Q_p$ can be constructed, to\nsufficient precision, using Hensel Lifting starting from a generator\nof $\\mathbb{F}_p^{\\times}$.\n\n\\section{Conclusion}\\label{conclusions_section}\n\nAs mentioned earlier, there has been two approaches to multiplying\nintegers - one using arithmetic over complex numbers and the other\nusing modular arithmetic. Using complex numbers, Sch\\\"{o}nhage and\nStrassen \\cite{SS71} gave an $O(N \\cdot \\log N \\cdot \\log\\log N\\ldots\n2^{O(\\log^* N)})$ algorithm. F\\\"{u}rer \\cite{F07} improved this\ncomplexity to $N\\cdot\\log N \\cdot2^{O(\\log^*N)}$ using some special\nroots of unity. The other approach, that is modular arithmetic, can be\nseen as arithmetic in $\\Q_p$ with certain precision. A direct\nadaptation of the Sch\\\"{o}nhage-Strassen's algorithm in the modular\nsetting leads to an $O(N \\cdot \\log N \\cdot \\log\\log N\\ldots\n2^{O(\\log^* N)})$ time algorithm. In this work, we show that by\nchoosing an appropriate prime and a special root of unity, a running\ntime of $N\\cdot \\log N \\cdot 2^{O(\\log^*N)}$ can be achieved through\nmodular arithmetic as well. Therefore, in a way, we have unified the\ntwo paradigms. The important question that remains open is:\n\\begin{itemize}\n\\item Can $N$-bit integers be multiplied using $O(N \\cdot \\log N)$ bit operations?\n\\end{itemize}\n\n\\noindent Even an improvement of the complexity to $O(N \\cdot \\log N\n\\cdot \\log^{*}N)$ operations will be a significant step forward\ntowards answering this question.\n\n\\section*{Acknowledgements}\n\nWe are greatly thankful to the anonymous reviewers for their detailed\ncomments that have improved the presentation of the paper\nsignificantly.\n\n\n\\bibliography{references}\n\\end{document}\n", "meta": {"hexsha": "2cd8077a5e68b8e50dad76e1500097feff82b3d8", "size": 63497, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "contents/research/publication/Journal/2013-04-18-Fast-integer-multiplication/intMult.tex", "max_stars_repo_name": "piyush-kurur-pages/website", "max_stars_repo_head_hexsha": "246dfa730328b45b65840ebed3293e96c497aa86", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-04-16T09:55:17.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-16T09:55:17.000Z", "max_issues_repo_path": "contents/research/publication/Journal/2013-04-18-Fast-integer-multiplication/intMult.tex", "max_issues_repo_name": "piyush-kurur-pages/website", "max_issues_repo_head_hexsha": "246dfa730328b45b65840ebed3293e96c497aa86", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "contents/research/publication/Journal/2013-04-18-Fast-integer-multiplication/intMult.tex", "max_forks_repo_name": "piyush-kurur-pages/website", "max_forks_repo_head_hexsha": "246dfa730328b45b65840ebed3293e96c497aa86", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-10T22:18:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T22:18:56.000Z", "avg_line_length": 48.8814472671, "max_line_length": 183, "alphanum_fraction": 0.7036237933, "num_tokens": 20548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.34605352095346736}}
{"text": "%\\documentclass[12pt]{article}\n\\documentclass[aip,jcp,preprint,superscriptaddress,floatfix]{revtex4-1}\n\\usepackage{url,graphicx,tabularx,array,geometry,amsmath,listings}\n\\setlength{\\parskip}{2ex} %--skip lines between paragraphs\n\\setlength{\\parindent}{20pt} %--don't indent paragraphs\n\n\\usepackage[colorinlistoftodos,prependcaption,textsize=tiny]{todonotes} %--TODO notes\n\n\\setlength{\\headheight}{-50pt}\n\\setlength{\\textheight}{700pt}\n\\setlength{\\textwidth}{500pt}\n\\setlength{\\oddsidemargin}{-10pt}\n\\setlength{\\footskip}{50pt}\n\\usepackage{graphicx}% Include figure files\n\\usepackage{bm}\n\\usepackage{url}\n\\usepackage[colorlinks = true,\n            linkcolor = blue,\n            urlcolor  = blue,\n            citecolor = blue,\n            anchorcolor = blue]{hyperref}\n\\graphicspath{{./Figures/}}\n\n%-- Commands for header\n\\renewcommand{\\title}[1]{\\textbf{\\large{#1}}\\\\}\n\\renewcommand{\\line}{\\begin{tabularx}{\\textwidth}{X>{\\raggedleft}X}\\hline\\\\\\end{tabularx}\\\\[-0.5cm]}\n\\newcommand{\\leftright}[2]{\\begin{tabularx}{\\textwidth}{X>{\\raggedleft}X}#1%\n& #2\\\\\\end{tabularx}\\\\[-1cm]}\n\n%\\linespread{2} %-- Uncomment for Double Space\n\\begin{document}\n\n\\title{\\center{Monte Carlo Simulation of the Lennard Jones Fluid in the Canonical Ensemble}}\n\\rule{\\textwidth}{1pt}\n\\leftright{The Molecular Sciences Software Institute}{Eliseo Marin-Rimoldi and John D.~Chodera} %-- left and right positions in the header\n\n\\bigskip\n\n\\section{Introduction}\n\\subsection{Monte Carlo Integration}\n\nIn statistical mechanics, we are interested in computing averages of\nthermodynamic properties as a function of atom positions and momenta~\\cite{Tuckerman.Book,Hill.Book,McQuarrie.Book}.\nA thermodynamic average depending only on configurational properties can be computed using the following\nexpectation value integral\n\\begin{equation}\n\t\\left<Q\\right> = \\int_V Q\\left(\\textbf{r}^N\\right)\n\t\\rho\\left(\\textbf{r}^N\\right) d\\textbf{r}^N\n\t\\label{eq.statMechAverage}\n\\end{equation}\n$\\textbf{r}^N$ is a $3N$ dimensional vector containing the positions of the $N$ atoms,\nwhere $Q(\\textbf{r}^N)$ is the thermodynamic quantity of interest that depends only on the configuration $\\textbf{r}^N$, \n$\\rho\\left(\\textbf{r}^N\\right)$ is the probability\ndensity whose functional form depends on the statistical mechanical ensemble\nof interest, and $V$ defines the volume of configuration space over which $\\rho$ has support. \nNote that the integrals over momenta have been factored out, as\nthey can be evaluated\nanalytically. The integral (Eq.~\\ref{eq.statMechAverage}) is very hard to compute\neven for small atomic systems.\nFor instance, a monoatomic system of 10 atoms leads to a 30-dimensional\nintegral. Consequently, we need to resort to a numerical integration scheme if we want to\nstudy atomic systems.\n\nMonte Carlo methods are numerical techniques\nfrequently used to estimate complex multidimensional\nintegrals which otherwise\n could not be performed~\\cite{Liu.Book,Newman.Book}.\n For instance, the integral of the function $f(\\textbf{x})$,\n where $\\textbf{x} \\in \\Re^{M}$, is approximated as\n \\begin{equation}\n\t I = \\int_V f(\\textbf{x}) \\, d\\textbf{x} = \\int_V\n\t \\frac{f(\\textbf{x})}{h(\\textbf{x})} h(\\textbf{x}) \\, d\\textbf{x} \n\t = \\left< \\frac{f(\\textbf{x})}{h(\\textbf{x})} \\right>_{h(\\textbf{x})}\n\t \\label{eq.averageGeneral}\n \\end{equation}\n The idea of Monte Carlo integration is to estimate the expectation value\n $\\left<\\frac{f(\\textbf{x})}{h(\\textbf{x})}\\right>_{{h(\\textbf{x})}}$ by\n generating random samples of \\textbf{x} from the probability density $h(\\textbf{x})$. \n\n\\subsection{Importance Sampling}\n\nIn Equation \\ref{eq.averageGeneral}, we are free to chose the probability\ndistribution\n$h(\\textbf{x})$. The simplest case is to uniformly generate $\\textbf{x}$\nin the volume $V$. In this way, $h(\\textbf{x})$ becomes constant as\n\\begin{equation}\n\th(\\textbf{x}) = \\frac{1}{V}\n\t\\label{eq.uniformDist}\n\\end{equation}\nUsing this sampling density $h(\\textbf{x})$, the integral (Eq.~\\ref{eq.averageGeneral}) becomes\n\\begin{equation}\n\tI = \\int_V f(\\textbf{x}) \\, d\\textbf{x} \\approx \\frac{V}{N} \\sum_{i=1}^N\n\tf(\\textbf{x}_i)\n\t\\label{eq.averageUniform}\n\\end{equation}\nwhere N is the total number of random samples and $f(\\textbf{x}_i)$ is the\nintegrand evaluated using the $i^{th}$ sample. While using a\nuniform sampling density often works sufficiently well for simple unidimensional cases, it generally fails to produce useful estimates\nfor complex problems.\n\nThe problem at hand involves the evaluation of $3N$-dimensional integral Eq.~\\ref{eq.statMechAverage}, which is dominated by a small region of configuration space~\\cite{Tuckerman.Book,Hill.Book,McQuarrie.Book}. \nUsing a uniform probability distribution $h(\\textbf{r}^N)$ over the configuration space hypervolume $V^{3N}$ to generate\nrepresentative samples of this subset is not efficient,\nas most states generated this way would have a low weight.\n\nA solution to this problem is to sample positions $\\textbf{r}^N$ from the desired equilibrium probability density $\\rho\\left(\\textbf{r}^N\\right)$:\n\\begin{eqnarray}\n\t\\textbf{r}^N &\\sim& \\rho(\\textbf{r}^N)\n\\end{eqnarray}\nThis is a way to generate\nrelevant configurations more frequently than configurations that have low\nprobability.\nMathematically, we set $h(\\textbf{r}^N)=\\rho\\left(\\textbf{r}^N\\right)$.\nThis idea is known as \\textit{importance sampling}.\n\nCombining Eqs.~\\ref{eq.statMechAverage} and \\ref{eq.averageGeneral}\nand the condition $h(\\textbf{r}^N)=\\rho\\left(\\textbf{r}^N\\right)$,\nwe find that\n\\begin{equation}\n\t%\\left<Q\\right> = \\frac{\\int Q e^{-\\beta U\\left(\\textbf{r}^N\\right)}\n\t%d\\textbf{r}^N}{\\int e^{-\\beta U\\left(\\textbf{r}^N\\right)}\n\t%d\\textbf{r}^N}\n\t\\left<Q\\right> \\approx \\frac{1}{N} \\sum_{i=1}^N Q\\left(\\textbf{r}_i^N\\right) .\n\t\\label{eq.importanceSamplingAverage}\n\\end{equation}\nThus, we can get thermodynamic properties by simply computing an unweighted sample average, given\nthat we perform importance sampling from $h(\\textbf{r}^N)=\\rho\\left(\\textbf{r}^N\\right)$.\n\n\\subsection{Detailed Balance Condition}\n\nThe question now becomes how to generate such atomic positions $\\textbf{r}^N$\n(or \\textit{states}) distributed\naccording to $\\rho\\left(\\textbf{r}^N\\right)$. In 1953, Metropolis, Rosenbluth, Rosenbluth, and Teller introduced a\nsolution based on Markov chains~\\cite{Metropolis.JCP.21.1087.1953}. \nThey proposed to use the detailed balance\ncondition in order to ensure proper configurational sampling from\nthe statistical mechanical distribution of interest. In order to generate\na new configuration $n$ from an old configuration $m$,\nthe detailed balance condition is\n\n\\begin{equation}\n\t\\rho_m\\left(\\textbf{r}^N\\right) \\alpha \\left(m \\rightarrow n \\right)\n\tP_{acc} \\left(m \\rightarrow n \\right) =\n\t\\rho_n\\left(\\textbf{r}^N\\right) \\alpha \\left(n \\rightarrow m \\right)\n\tP_{acc} \\left(n \\rightarrow m \\right) \n\t   \\label{eq.detailedBalance}\n\\end{equation}\n\nWhere $\\rho_m\\left(\\textbf{r}^N\\right)$ is the probability of observing\nstate $m$,\n$\\alpha \\left(m \\rightarrow n \\right)$ is the probability of\nattempting to generate a new state $n$ starting from a state $m$  and \n$P_{acc} \\left(n \\rightarrow m \\right)$ is the probability of accepting \nsuch transition. Basically, the condition of detailed balance tells us that the\n``flux'' of transitions\nfrom state $m$ to state $n$ equals the flux from state $n$ to state $m$ at\nequilibrium.\n\nThere are many ways to satisfy Eq.~\\ref{eq.detailedBalance} by construction of different acceptance probabilities. \nWhile Metropolis et.~al proposed a choice that both satisfies Eq.~\\ref{eq.detailedBalance} and maximizes the average acceptance probability $\\left< P_{acc} \\right>$~\\cite{Metropolis.JCP.21.1087.1953}, Hastings generalized this to the case where proposal probabilities are not symmetric, such that $\\alpha \\left(m \\rightarrow n \\right) \\ne \\alpha \\left(n \\rightarrow m \\right)$, producing the \\emph{Metropolis-Hastings}~\\cite{Hastings.Biometrika.57.97.1970} acceptance criteria:\n\\begin{equation}\n\tP_{acc}(m \\rightarrow n) = \\text{min} \\left[1,\\frac{\\alpha \\left(n\n\t\t\\rightarrow m \\right)}{\\alpha \\left(m \\rightarrow n \\right)}\n\t\t\\frac{\\rho_n\\left(\\textbf{r}^N\\right)}{\\rho_m\\left(\\textbf{r}^N\\right)}\n\t\\right]\n\t\\label{eq.MetropolisHastings} .\n\\end{equation}\nThis algorithm is one of a general class of \\emph{Markov chain Monte Carlo (MCMC)} algorithms that generate Markov chains to sample a desired target density, and a great deal of the MCMC literature is valuable for molecular simulations~\\cite{Liu.Book}.\n\n\\section{Canonical Ensemble Monte Carlo of a Lennard Jones Fluid}\n\nAssume we have $N$ monoatomic particles that interact using the Lennard-Jones (LJ) pairwise potential:\n\\begin{equation}\nU(r) = 4 \\epsilon \\left[\\left(\\frac{\\sigma}{r}\\right)^{12} -\\left(\\frac{\\sigma}{r}\\right)^{6} \\right] \n\\end{equation}\nwhere $r$ is the interparticle distance, $\\sigma$ is the distance where the interaction energy is zero, and $\\epsilon$ is the well depth. \nFor simulating argon, for example, a common choice is $\\sigma = 3.4$~\\AA and $\\epsilon/k_B = 120$~K.\n\nOur goal is to generate a set of states of $N$ LJ particles distributed according to the canonical (NVT) ensemble\n\\begin{eqnarray}\n\t\\rho_n \\left(\\textbf{r}^N ; \\beta \\right) &=& Z(\\beta)^{-1} e^{-\\beta U \\left( \\textbf{r}^N \\right)} \\label{eq:nvtDist} \\\\\n\tZ(\\beta) &\\equiv& \\int_V e^{-\\beta U \\left(  \\textbf{r}^N \\right)} \\, d\\textbf{r}^N \n\\end{eqnarray}\nwhere $U \\left( \\textbf{r}^N \\right)$ is the potential energy of the system, $\\beta = (k_B T)^{-1}$ is the inverse temperature, $k_B$ is the Boltzmann constant, and $T$ is the absolute temperature. \n\nNote that  $U \\left( \\textbf{r}^N \\right)$ is given by\n\\begin{equation}\n\tU \\left( \\textbf{r}^N \\right) = \\sum_{i < j} U \\left( r_{ij} \\right) \n\t\\label{eq.LennardJonesTotalPotential}\n\\end{equation}\nwhere $r_{ij} \\equiv || \\textbf{r}^N_j - \\textbf{r}^N_i ||_2$ is the interparticle separation distance.\n\nSubstituting Eq.~\\ref{eq:nvtDist} into Eq.~\\ref{eq.MetropolisHastings} and assuming $\\alpha \\left( n \\rightarrow m \\right) =  \\alpha \\left( m \\rightarrow n \\right)$, we obtain\n\\begin{equation}\n\tP_{acc}(m \\rightarrow n) = \\text{min} \\left[\n\t\t1,e^{-\\beta \\Delta U}\n\t\\right]\n\t\\label{eq.detailedBalanceNVT}\n\\end{equation}\nwhere $\\Delta U \\equiv U(\\textbf{r}^N_m) - U(\\textbf{r}^N_n)$ is the difference in potential energy of the system\nbetween the new state $n$ and the old state $m$. Note that the argument\nof the energy $\\textbf{r}^N$ has been dropped for clarity.\n\n\\subsection{Flow of Calculations in a Metropolis Monte Carlo simulation}\n\\label{sec.flow}\n\nThe following workflow can be used to implement the Metropolis algorithm to sample the canonical ensemble of configurations of LJ particles \\cite{Shell.Notes, Maginn.Notes}:\n\n\\begin{enumerate}\n\\setlength{\\itemsep}{0em} %--don't put a huge amount of space between items in a list\n\\item Generate an inital system state $m$.\n\\item Choose an atom with uniform probability from $\\{1, \\ldots, N\\}$ from old state $m$.\n\\item Propose a new state $n$ by translating a LJ particle by a uniform random displacement $\\Delta r \\sim U(-\\Delta x, +\\Delta x)$ in each dimension.\n\tThe displacement scale $\\Delta x$ should not be too large as this would\n\tlikely result in particle overlaps, but should not be too small\n\tas this would result in a slow sampling of configurational space.\n\tMore on this below.\n\\item The difference in energy between the new and old states is computed.\n\tNote that you do not need to compute the \\textit{total} system energy\n\tdifference, as all particles but one remain at the same position. \n\tIt is enough to get difference in energy of the selected molecule \n\tin the new and old states.\n\\item The new state is accepted or rejected using the Metropolis criterion.\n\tPractically, this can be implemented as follows. \n\tIf a move from $m$ to $n$ is ``downhill'', $\\beta \\Delta U \\leq 0$,\n\tthe move is always accepted. For ``uphill'' moves, a random\n\tnumber $\\zeta$ is generated uniformly on (0,1).  \n\tIf $\\zeta < \\exp[-\\beta {\\Delta U}]$, the move is\n\taccepted.  Otherwise, the move is rejected. \n\tIf a non-symmetric proposal is used, this acceptance scheme will have to be modified to implement Eq.~\\ref{eq.MetropolisHastings}.\n\\end{enumerate}\n\n\\subsection{Technical considerations}\n\n\\textbf{Initial configuration.} \nWhile computed equilibrium expectations should be independent of the starting configuration, from a practical standpoint, we have to select an initial configuration that is not so atypical of equilibrium configurations that relaxation to equilibrium will require an enormous amount of simulation time. \nFor this particular example, a good way to start is to place atoms in a 3D lattice. \nDuring the Metropolis Monte Carlo simulation at temperatures and box volumes (or pressures) typical of the liquid state, the lattice will ``melt'' and liquid configurations will be obtained. \nOnce a liquid configuration has been generated from a simulation, you can always save a ``snapshot'' from this simulation as a starting point for a new simulation of the liquid states, and relaxation to equilibrium will generally be much more rapid as long as the conditions are similar.\n\n\\textbf{Random number generation.} \nComputers cannot generate truly random numbers.\nInstead, they rely on \\emph{pseudorandom number generators} (PRNGs) that aim to produce random numbers with the desired statistical properties and long recurrence times between repeats of the same random number sequence.\nUsing a low-quality random number generator can lead to simulation artifacts that can lead to incorrect physical behavior~\\cite{Ferrenberg.PRL.69.3382.1992,Cerutti.JCTC.4.1669.2008}.\nWe recommend you avoid writing your own PRNGs, as this can lead to inadvertent implementation of an ill-conceived algorithm~\\cite{RANDU}.\nInstead, rely on high-quality, well-understood PRNGs and implementations that have are well-supported, such as the Mersenne Twister~\\cite{Mersenne.Twister,Matsumoto.ACMTransModelComputSimul.8.3.1998} implementation provided by \\href{https://docs.scipy.org/doc/numpy/reference/routines.random.html}{\\tt numpy.random}.\n\n\\textbf{Equilibration.} \nWhen the initial configuration is highly atypical compared to true samples from the equilibrium density---such as the initial 3D lattice conditions compared to a true disordered liquid state---it may require very long simulation times for the bias in equilibrium averages computed over the entire trajectory to become small compared to the statistical error~\\cite{Chodera.JCTC.12.1799.2016}.\nIt is therefore common practice to discard some initial part of the simulation to \\emph{equilibration} and to average over the subsequent \\emph{production} region to minimize this bias at the cost of potentially increasing statistical error by including less data in the average.\nWhile common practice traditionally had selected an arbitrary initial portion of the simulation to equilibrium, modern best practice recommends the use of an automated approach for selecting the optimal equilibration/production split point in a manner that maximizes the number of statistically uncorrelated samples in the production part of the trajectory~\\cite{Chodera.JCTC.12.1799.2016}.\nTo do this, you can use the \\href{http://pymbar.readthedocs.io/en/latest/timeseries.html#automatically-identifying-the-equilibrated-production-region}{\\tt pymbar.timeseries.detectEquilibration} function from the \\href{http://pymbar.org/}{\\tt pymbar} module to analyze an array containing timeseries data for your observable (such as energies, box volumes, or densities)~\\cite{Chodera.JCTC.12.1799.2016}.\n\n\\textbf{System size and periodic boundary conditions.} \nA typical simulation of a Lennard-Jones fluid is carried out anywhere from 216 to 10,000 particles. \nThis amount of particles is far away of being representative of a bulk liquid. \nTo get around this problem, we employ a trick called periodic boundary conditions. \nThe primary simulation box is surrounded\nby copy images of itself. For a cubic simulation, there would be 26 \nimages around the central box. This trick has two implications\n\\begin{enumerate}\n\\setlength{\\itemsep}{0em} %--don't put a huge amount of space between items in a list\n\t\\item If the position of a particle (i.e.\\ Cartesian coordinates) is\n\t\toutside the simulation box after a particle translation, \n\t\tan identical particle should enter the box through the\n\t\topposite face of the box, as shown in Figure ~\\ref{fig:pbc} \n\t\\item When computing distances $r_{ij}$ used in the evaluation of the LJ potential (Eq.~\\ref{eq.LennardJonesTotalPotential}), we use the \\textit{minimum image distance}. See Figure ~\\ref{fig:minimumImage}.\n\\end{enumerate}\n\n\\begin{figure}[t]\n        \\includegraphics[scale = 0.5]{pbc.eps}\n        \\caption{Molecule one is displaced outside the bounds of the central box and placed back\n        in through the oposite side of the box. Image from Allen and Tildesley. ~\\cite{Allen.Book}}\n        \\centering\n        \\label{fig:pbc}\n\\end{figure}\n\n\\begin{figure}[t]\n        \\includegraphics[scale = 0.5]{minimumImage.eps}\n        \\caption{Representation of the minimum image distance. Molecule 1 does not interact with\n                molecule 4 located in the simulation box because the distance between particles is\n                greater than the cutoff. However, molecule 1 does interact with\n                the image of molecule 4 located in box E. Image from Allen and\n                Tildesley ~\\cite{Allen.Book}}\n        \\centering\n        \\label{fig:minimumImage}\n\\end{figure}\n\n\\textbf{Maximum displacement $\\Delta x$.} \nAs noted above, the Metropolis Monte Carlo algorithm requires translating a selected LJ particle by a random perturbation. \nThis displacement should not be too large as this would result in particle overlaps and low acceptance rates; on the other hand, it should not be so small as to result in inefficient sampling of configuration space.\nA common practice is to adjust the maximum particle displacement $\\Delta x$ during an explicit equilibration phase in order to achieve $\\sim$50\\% acceptance translation rates over a recent window of $\\sim N$ Monte Carlo trial moves. \n\n\\textbf{Energy truncation and tail corrections.} \nIf two particles are separatedby more than a certain distance, we typically truncate their interaction energy if $r > r_c$, where $r_c$ denotes the \\emph{cutoff distance}. \nTruncating interactions removes contribution to the potential energy that might be non negligible and can lead to significant artifacts, such as significantly perturbed densities when a barostat is used to sample the NPT ensemble due to neglected long-range dispersion interactions. \nWe can estimate the truncated interactions by incorporating an energy \ncorrection, known as the tail or long range correction.\nFor the Lennard-Jones fluid, we assume that we have an homogeneous liquid at $r>r_c$ to obtain the correction for neglecting this contribution for all interacting pairs of particles~\\cite{Shirts.JPCB.111.13052.2007}:\n\\begin{equation}\n\tU_\\mathrm{correction} = \\frac{8 \\pi N^2}{3 V} \\epsilon \\sigma^3\n\t\\left[\\frac{1}{3} \\left(\\frac{\\sigma}{r_c} \\right)^9 \n\t- \\left(\\frac{\\sigma}{r_c} \\right)^3 \\right]\n\\end{equation}\nFor a Lennard-Jones fluid, it is common to set $r_c \\sim 3 \\sigma$, since the pair interaction at this separation is small, $U(3 \\sigma) \\approx 4 [(3)^{-12} - (3)^{-6} \\approx - 0.0055 \\epsilon$, or about 0.5\\% of the well depth $\\epsilon$.\nYou will want to verify that your computed properties are relatively insensitive to the choice of cutoff $r_c$ so that a too-short cutoff does not induce artifacts in computed physical properties.\n\n\\textbf{Units.}\nDealing with unit-bearing quantities---such as energies, distances, masses, and physical constants---in your code can be tricky.\nErrors can easily creep in when one part of the code assumes one set of implicit units while another part of the code assumes a different set of implicit units, and error like this have led to billion-dollar accidents (such as the loss of the Mars Polar Lander due to one part of the code using metric units while the other used English units~\\cite{MarsPolarLander}).\nTo avoid costly mistakes that complicate debugging, we recommend one of two approaches:\n(1) use a unit library such as \\href{http://pint.readthedocs.io/}{\\tt pint} or \\href{http://docs.openmm.org/7.1.0/userguide/library.html#units-and-dimensional-analysis}{\\tt simtk.unit} that automatically handles unit coversions,\nor (2) select a single compatible unit system (e.g.~mks or {\\AA}ngstroms-amu-picoseconds) and explicitly document the units for all unit-bearing constants and quantities;\nThe first option is highly preferred, though care must still be paid to ensuring unit-bearing quantities possess the appropriate dimensionality and some considerations must be made for performance impact in parts of the code that must be performant since unit conversion incurs non-negligible overhead.\n\n\\textbf{Compatible constants.}\nWhile some constants are exact, many physical constants are known only to a number of significant digits.\nAll values must be rounded to some number of significant figures when used in computer simulations, and these numbers have finite-precision floating-point representation that further reduces their accuracy.\nPerhaps surprisingly, choices of how many significant figures that each constant should be rounded to can have an impact on the resulting simulations if care is not take to ensure that constants frequently used together are not rounded in a self-consistent manner.\nFor example, a major difference between potential energies computed in CHARMM and AMBER arises from an early arbitrary choice of the number of significant digits to round a set of critical Coulomb energy coefficients~\\cite{Shirts.JCAMD.31.147.2017}.\nFortunately, the National Institute of Standards and Technology (NIST) provides up-to-date guidelines on consistent sets of physical parameters in the \\href{http://ws680.nist.gov/publication/get_pdf.cfm?pub_id=920686}{2014 CODATA Self-Consistent Physical Constants} (updated every four years).\nIt is highly recommended that the CODATA parameters be adopted unless there is strong need to reproduce flawed results from a specific molecular simulation package.\n\n\n\\textbf{Pressure, the virial and pressure tail corrections.} To compute the system pressure,\nwe use the virial theorem\n\n\\begin{equation}\n        P = \\frac{1}{3V} \\left< 3 N k_B T + \\sum_{i < j} \\textbf{f}_i \\cdot \\textbf{r}_i  \\right>\n\\end{equation}\n\nWhere\n\n\\begin{equation}\n        \\sum_{i < j} \\textbf{f}_i \\cdot \\textbf{r}_i = - \\sum_{i < j} \\frac{dU\\left(r_{ij} \\right)}{dr} r_{ij} = W\n\\end{equation}\n\nThe term $W$ is known as the virial and it is a pairwise sum and it can be computed\nalongside the energies. Note that the negative derivative of the energy is the force.\nFor the LJ potential, this is\n\n\\begin{equation}\n        \\mathbf{f}\\left(r_{ij} \\right) = -\\frac{dU \\left(r_{ij} \\right)}{dr} = - \\frac{48 \\epsilon}{r^2_{ij}} \\left[\\left(\\frac{\\sigma}{r_{ij}}\\right)^{12} -\\frac{1}{2}\\left(\\frac{\\sigma}{r_{ij}}\\right)^{6} \\right] \\mathbf{r}_{ij}\n\\end{equation}\n\nThe effect of the truncation of the interactions must be also taken into account for the pressure\ncomputation using a correction term\n\n\\begin{equation}\n        P_{tail} = \\frac{16 \\pi N^2}{3 V^2} \\epsilon \\sigma^3\n        \\left[\\frac{2}{3} \\left(\\frac{\\sigma}{r_c} \\right)^9 \n        - \\left(\\frac{\\sigma}{r_c} \\right)^3 \\right]\n\\end{equation}\n\n\n\n\n\\textbf{Reduced units.}\nLennard-Jones fluids have the surprisingly pleasant behavior of possessing universal behavior when expressed in terms of \\emph{reduced units} as\n\n\\begin{equation}\n\tU^*\\left(r_{ij} \\right) = 4 \\left[\\left(\\frac{1}{r^*_{ij}}\\right)^{12} -\\left(\\frac{1}{r^*_{ij}}\\right)^{6} \\right]\n\t\\label{eq.lennardjonesReduced}\n\\end{equation}\n\nwhere \n\n\\begin{equation}\n\tU^* = \\frac{U}{\\epsilon}\n\\end{equation}\n\nand \n\n\\begin{equation}\n\tr^* = \\frac{r}{\\sigma}\n\\end{equation}\n\nThat is, when plotted in reduced units, all Lennard-Jones fluids exhibit the same universal behavior despite the exact choices of $\\epsilon$ and $\\sigma$ used in the simulation. See Table \\ref{table:reducedUnits} for a list\nof variables in reduced units.\nUsing reduced units for input and output will allow you to compare your results with others.\n\n\\begin{table}[t]\n\\centering\n \\begin{tabular}{|c c|} \n \\hline\n Quantity & Expression \\\\ [0.5ex] \n \\hline\\hline\n Length &  $L^*=L / \\sigma$   \\\\ \n Density &  $\\rho^* = N \\sigma^3 / V$   \\\\\n Energy &  $U^* = U / \\epsilon$   \\\\\n Pressure &  $P^* = P \\sigma^3 / \\epsilon$   \\\\\n Temperature & $T^* = k_B T / \\epsilon$ \\\\\n Volume & $V^* = V / \\sigma^3$ \\\\\n Time & $t^* = t \\sqrt{\\frac{\\epsilon}{m \\sigma^2}}$ \\\\\n \\hline\n \\end{tabular}\n \\caption{Conversion factors between real and reduced units.}\n \\label{table:reducedUnits}\n\\end{table}\n\n\\subsection{Reference calculations}\n\nSee the following resources for NIST Lennard-Jones fluid reference data:\n\\begin{itemize}\n\\item \\href{https://mmlapps.nist.gov/srs/LJ_PURE/mc.htm}{Reference thermodynamic data ($N=500$, $T^*=0.90$ and $0.90$, $r_c = 3\\sigma$)}\n\\item \\href{https://www.nist.gov/mml/csd/chemical-informatics-research-group/lennard-jones-fluid-reference-calculations}{Reference snapshot potential energies and virials}\n\\end{itemize}\n\n\\section{Concrete tasks}\n\n\\textbf{Implement one (or more) methods to generate initial configurations. }\nYou will want implement more than one method to generate an initial\nconfiguration. This will allow you to test if your code produces the same\nfinal answers with different initial conditions. Among the possible options\nare random placement of particles in the box, placement of particles in a\nlattice or start a simulation using an old configuration.\n\n\\textbf{Implement the pairwise and long tail correction equations. } \nThese are the LJ potential, force (or virial) expression, energy and \npressure long tail corrections. Use reduced units, \nas in Equation ~\\ref{eq.lennardjonesReduced} to facilitate comparison with\nothers.\n\n\\textbf{Implement a function that computes the total energy of the system. } \nCompare to the NIST reference snapshot potential energies and virials.\n\n\\textbf{Implement the Metropolis algorithm and compare to the NIST\nbenchmark. } See Section ~\\ref{sec.flow} as\na reference. This is the part of the code where you will implement\nfeatures such as periodic boundary conditions, minimum image distance, \nparticle translation and the acceptance criteria. You can use the state point\n$T^* = 0.9$, $\\rho^* = 0.9$, and $r_c = 3\\sigma$  and compare to the\nNIST benchmark for thermodynamic data.\n\n\\textbf{Check if your energies are consistent with the NIST benchmark. }\n\n\n\\newpage\n%\n\\bibliographystyle{aip.bst}\n\\bibliography{references.bib}\n\n\\end{document}\n", "meta": {"hexsha": "d10f400baa5c3f4b95d200955247381d05ba2e7b", "size": 26729, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "handouts/01_MC_NVT.tex", "max_stars_repo_name": "MolSSI-SSS/MM_SSS_Lesson_Plan", "max_stars_repo_head_hexsha": "98af78796fbeca5924cbf800e573594cc24d96fc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-19T02:17:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-19T02:17:44.000Z", "max_issues_repo_path": "handouts/01_MC_NVT.tex", "max_issues_repo_name": "MolSSI-SSS/MM_SSS_Lesson_Plan", "max_issues_repo_head_hexsha": "98af78796fbeca5924cbf800e573594cc24d96fc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-07-20T20:23:32.000Z", "max_issues_repo_issues_event_max_datetime": "2017-07-21T20:44:29.000Z", "max_forks_repo_path": "handouts/01_MC_NVT.tex", "max_forks_repo_name": "dgasmith/MM_SSS_Lesson_Plan", "max_forks_repo_head_hexsha": "98af78796fbeca5924cbf800e573594cc24d96fc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 60.2004504505, "max_line_length": 477, "alphanum_fraction": 0.7547607468, "num_tokens": 7271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.34605352001778306}}
{"text": "\\chapter{Non-deterministic Classical Processes}\\label{sec:main}\nIn this section, we will discuss our main contribution: an extension of \\cp\nwhich allows for races while still excluding deadlocks. \nWe have seen in \\cref{sec:cp-example} how \\cp excludes deadlocks, but how exactly\ndoes \\cp exclude races?\nLet us return to our first example from \\cref{sec:introduction}, to the\ninteraction between John, Mary and the store.\n\\[\n  \\begin{array}{c}\n    \\tm{(\\piPar{%\n    \\piSend{x}{\\sliceofcake}{\\piSend{x}{\\nope}{\\store}}\n    }{%\n    \\piPar{\\piRecv{x}{y}{\\john}}{\\piRecv{x}{z}{\\mary}}\n    })}\n    \\\\[1ex]\n    \\rotatebox[origin=c]{270}{$\\Longrightarrow^{\\star}$}\n    \\\\[1ex]\n    \\tm{(\\piPar{\\store}{\\piPar{\\piSub{\\sliceofcake}{y}{\\john}}{\\piSub{\\nope}{z}{\\mary}}})}\n    \\quad\n    \\text{or}\n    \\quad\n    \\tm{(\\piPar{\\store}{\\piPar{\\piSub{\\nope}{y}{\\john}}{\\piSub{\\sliceofcake}{z}{\\mary}}})}\n  \\end{array}\n\\]\nRaces occur when more than two processes attempt to communicate simultaneously\nover the \\emph{same} channel. However, the \\text{Cut} rule of \\cp requires that\n\\emph{exactly two} processes communicate over each channel:\n\\begin{center}\n  \\cpInfCut\n\\end{center}\nWe could attempt write down a protocol for our example, stating that the store\nhas a pair of channels $\\tm{x}, \\tm{y} : \\ty{\\cake}$ with which it communicates\nwith John and Mary, taking \\cake to be the type of interactions in which cake\n\\emph{may} be obtained, i.e.\\ of both \\sliceofcake and \\nope, and state that the\nstore communicates with John \\emph{and} Mary over a channel of type \\ty{\\cake\n  \\parr \\cake}.\nHowever, this \\emph{only} models interactions such as the following:\n\\begin{prooftree}\n  \\AXC{$\\seq[{ \\john }]{ \\Gamma, \\tmty{x}{\\cake^\\bot} }$}\n  \\AXC{$\\seq[{ \\mary }]{ \\Delta, \\tmty{y}{\\cake^\\bot} }$}\n  \\SYM{\\tens}\n  \\BIC{$\\seq[{ \\cpSend{y}{x}{\\john}{\\mary} }]{\n      \\Gamma, \\Delta, \\tmty{y}{\\cake^\\bot \\tens \\cake^\\bot} }$}\n  \\AXC{$\\seq[{ \\store }]{ \\Theta, \\tmty{x}{\\cake}, \\tmty{y}{\\cake} }$}\n  \\SYM{\\parr}\n  \\UIC{$\\seq[{ \\cpRecv{y}{x}{\\store} }]{\n      \\Theta, \\tmty{y}{\\cake \\parr \\cake} }$}\n  \\NOM{Cut}\n  \\BIC{$\\seq[{ \\cpCut{y}{\\cpSend{y}{x}{\\john}{\\mary}}{\\cpRecv{y}{x}{\\store}} }]{\n      \\Gamma, \\Delta, \\Theta }$}\n\\end{prooftree}\nNote that in this interaction, John will get whatever the store decides to send\non \\tm{x}, and Mary will get whatever the store decides to send on \\tm{y}.\nThis means that this interactions gives the choice of who receives what \\emph{to\nthe store}. This is not an accurate model of our original example, where\nthe choice of who receives the cake is non-deterministic and depends on factors\noutside of any of the participants' control!\nAnd to make matters worse, the term which models our example is entirely\ndifferent from the one we initially wrote down in the \\textpi-calculus!\n\nThe ability to model racy behaviour, such as that in our example, is essential\nto describing the interactions that take place in realistic concurrent systems.\nTherefore, we would like to extend \\cp to allow such races.\nSpecifically, we would like to do it in a way which mirrors the way in which the\n\\textpi-calculus handles non-determinism.\nWe will base our extension on \\rcp, a subset of \\cp which we introduced in\n\\cref{sec:background}.\nWe have chosen to do this to keep our discussion as simple as possible.\nFurthermore, as compatibility with the \\textpi-calculus is of interest, we will\nuse the reduction system without commuting conversions, which we introduced in\n\\cref{sec:cppi}.\n\nThis chapter proceeds as follows.\nIn \\cref{sec:nc-terms-and-types}, we introduce the extensions to the terms,\nstructural congruence and types of \\cp.\nIn \\cref{sec:nc-typing-clients-and-servers}, we introduce the typing rules for\n\\nodcap. \nIn \\cref{sec:nc-running-clients-and-servers}, we introduce the reduction rules\nfor \\nodcap.\nIn \\cref{sec:nc-properties}, we prove that our extension preserves the\nmeta-theoretical of \\cp.\nFinally, in \\cref{sec:nc-local-choice}, we discuss the relation between\nnon-determinism in \\nodcap and the non-determinism introduced by the addition of\nnon-deterministic local choice.\n\n\\section{Terms and types}\\label{sec:nc-terms-and-types}\nLet us return, briefly, to our example.\n\\[\n  \\tm{(\\piPar{%\n      \\piSend{x}{\\sliceofcake}{\\piSend{x}{\\nope}{\\store}}\n    }{%\n      \\piPar{\\piRecv{x}{y}{\\john}}{\\piRecv{x}{z}{\\mary}}\n    })}\n\\]\nIn this interaction, we see that the channel \\tm{x} is used only as a way to\nconnect the various clients, John and Mary, to the store.\nThe \\emph{real} communication, sending the slice of cake and disappointment,\ntakes places on the channels \\tm{\\sliceofcake}, \\tm{\\nope}, \\tm{y} and \\tm{z}.\n\nInspired by this, we add two new constructs to the term language of \\cp: sending\nand receiving on a \\emph{shared} channel.\nThese actions are marked with a \\tm{\\star} in order to distinguish them\nsyntactically from ordinary sending and receiving.\nTo group clients, we add another form of parallel composition, which we refer to\nas \\emph{pooling}. \n\\input{def-nc-terms}\nAs before, round brackets denote input, square brackets denote output.\nNote that \\tm{\\ncCnt{x}{y}{P}}, much like \\tm{\\cpSend{x}{y}{P}{Q}}, is a bound\noutput---this means that both client creation and server interaction bind a new\nname.\n\nIn \\rcp, we terms are identified up to the commutativity and associativity of\nparallel composition. In \\nodcap, we add another form of parallel composition,\nand therefore must extend our structural congruence:\n\\input{def-nc-equiv}\nWe add axioms for the commutativity and associativity of pooling.\nWe do not add an axiom for \\ncEquivPoolAss2, as it follows from\n\\cref{def:nc-equiv}, see \\cref{thm:nc-pool-assoc2}.\nIt should be noted that \\tm{\\cpCut{x}{P}{Q}} is considered a single,\n\\emph{atomic} construct.\nTherefore you \\emph{cannot} use \\ncEquivPoolAss1 to rewrite\n\\tm{\\cpCut{x}{P}{\\ncPool{Q}{R}}} to \\tm{\\cpCut{x}{\\ncPool{P}{Q}}{R}}.\nWe do, however, add two axioms which relate cuts and pool.\nWe call these \\emph{extrusion}, because they closely resemble the\n\\textpi-calculus axiom for scope extrusion.\nWe add both \\ncRedKappaPool1 and \\ncRedKappaPool2, as these relate two different\nconstructs, and therefore we cannot use the one to derive the other. \n\\input{thm-nc-pool-assoc2}\nFurthermore, the extensions to structural congruence preserve symmetry.\n\\input{thm-nc-symmetry}\nWe can make another observation from our examples.\nIn every example in which a server interacts with a pool of clients, and which\ndoes not deadlock, there are \\emph{exactly} as many clients as there are\nserver interactions.\nTherefore, we add two new \\emph{dual} types for client pools and servers, which\ntrack how many clients or server interactions they represent.\n\\input{def-nc-types}\n\\input{def-nc-negation}\nWith these new types, duality remains an involutive function.\n\\input{thm-nc-negation-involutive}\n\n\\section{Typing clients and servers}\\label{sec:nc-typing-clients-and-servers}\nWe have to add typing rules to associate our new client and server\ninteractions with their types.\nThe definition for environments will remain unchanged, but we will extend the\ndefinition for the typing judgement.\nTo determine the new typing rules, we essentially have to answer the question\n``What typing constructs do we need to complete the following proof?''\n\\begin{prooftree}\n  \\AXC{$\\seq[{ \\john }]{ \\Gamma, \\tmty{y}{\\cake^\\bot} }$}\n  \\noLine\\UIC{$\\smash{\\vdots}\\vphantom{\\vdash}$}\n  \\AXC{$\\seq[{ \\mary }]{ \\Delta, \\tmty{y'}{\\cake^\\bot} }$}\n  \\noLine\\UIC{$\\smash{\\vdots}\\vphantom{\\vdash}$}\n  \\AXC{$\\seq[{ \\store }]{ \\Theta, \\tmty{z}{\\cake}, \\tmty{z'}{\\cake} }$}\n  \\noLine\\UIC{$\\smash{\\vdots}\\vphantom{\\vdash}$}\n  \\noLine\\TIC{$\\seq[{\n      \\cpCut{x}{\\ncPool{\\ncCnt{x}{y}{\\john}}{\\ncCnt{x}{y'}{\\mary}}}{\n        \\ncSrv{x}{z}{\\ncSrv{x}{z'}{\\store}}} }]{\n      \\Gamma, \\Delta, \\Theta }$}\n\\end{prooftree}\nIdeally, we would still like the composition of the client pool and the server\nto be a cut. This seems reasonable, as the left-hand side of the term above has\n2 clients, and the right-hand side has two server interactions, so \\tm{x} is\nused at type \\ty{\\take[2]{\\cake^\\bot}} on the left, and as \\ty{\\give[2]{\\cake}}\non the right.\n\\begin{prooftree}\n  \\AXC{$\\seq[{ \\john }]{ \\Gamma, \\tmty{y}{\\cake^\\bot} }$}\n  \\noLine\\UIC{$\\smash{\\vdots}\\vphantom{\\vdash}$}\n  \\AXC{$\\seq[{ \\mary }]{ \\Delta, \\tmty{y'}{\\cake^\\bot} }$}\n  \\noLine\\UIC{$\\smash{\\vdots}\\vphantom{\\vdash}$}\n  \\noLine\\BIC{$\\seq[{ \\ncPool{\\ncCnt{x}{y}{\\john}}{\\ncCnt{x}{y'}{\\mary}} }]{\n      \\Gamma, \\Delta, \\tmty{x}{\\take[2]{\\cake^\\bot}} }$}\n\n  \\AXC{$\\seq[{ \\store }]{ \\Theta, \\tmty{z}{\\cake}, \\tmty{z'}{\\cake} }$}\n  \\noLine\\UIC{$\\smash{\\vdots}\\vphantom{\\vdash}$}\n  \\noLine\\UIC{$\\seq[{ \\ncSrv{x}{z}{\\ncSrv{x}{z'}{\\store}} }]{\n      \\Theta, \\tmty{x}{\\give[2]{\\cake}} }$}\n\n  \\NOM{Cut}\n  \\BIC{$\\seq[{\n      \\cpCut{x}{\\ncPool{\\ncCnt{x}{y}{\\john}}{\\ncCnt{x}{y'}{\\mary}}}{\n        \\ncSrv{x}{z}{\\ncSrv{x}{z'}{\\store}}} }]{\n      \\Gamma, \\Delta, \\Theta }$}\n\\end{prooftree}\nWe will define the typing judgement, and then discuss servers and clients, the\ntwo sides of the above cut, describe the rules we add, and show how they allow\nus to complete our proof.\n\\input{def-nc-typing-judgement}\n\\input{fig-nc-typing-judgement}\n\n\\subsection{Clients and pooling}\\label{sec:clients-and-pooling}\nA client pool represents a number of independent processes, each wanting to\ninteract with the server. Examples of such a pool include John and Mary from our\nexample, customers for online stores in general, and any number of processes\nwhich interact with a single, centralised server.\n\nWe introduce two new rules: one to construct clients, and one to pool them\ntogether. The first rule, $(\\take[1]{})$, marks interaction over some channel as\na client interaction. It does this by receiving a channel \\tm{y} over a\n\\emph{shared} channel \\tm{x}. The channel \\tm{y} is the channel across which the\nactual interaction will eventually take place.\nThe second rule, \\textsc{Pool}, allows us to pool together clients. This is\nimplemented, as in the \\textpi-calculus, using parallel composition.\n\\begin{center}\n  \\ncInfTake1\n  \\ncInfPool\n\\end{center}\nUsing these rules, we can derive the left-hand side of our proof by marking John\nand Mary as clients, and pooling them together.\n\\begin{prooftree}\n  \\AXC{$\\seq[{ \\john }]{ \\Gamma, \\tmty{y}{\\cake^\\bot} }$}\n  \\SYM{(\\take[1]{})}\n  \\UIC{$\\seq[{ \\ncCnt{x}{y}{\\john} }]{ \\Gamma, \\tmty{z}{\\take[1]{\\cake^\\bot}} }$}\n\n  \\AXC{$\\seq[{ \\mary }]{ \\Delta, \\tmty{y'}{\\cake^\\bot} }$}\n  \\SYM{(\\take[1]{})}\n  \\UIC{$\\seq[{ \\ncCnt{x}{y'}{\\mary} }]{ \\Delta, \\tmty{y'}{\\take[1]{\\cake^\\bot}} }$}\n\n  \\NOM{Pool}\n  \\BIC{$\\seq[{ \\ncPool{\\ncCnt{x}{y}{\\john}}{\\ncCnt{x}{y'}{\\mary}} }]{\n      \\Gamma, \\Delta, \\tmty{x}{\\take[2]{\\cake^\\bot}} }$}\n\\end{prooftree}\n\n\\subsection{Servers and contraction}\\label{sec:servers-and-contraction}\nDual to a pool of clients is a server. Our interpretation of a server is a\nprocess which offers up some number of interdependent interactions of the same\ntype. Examples include the store from our example, which gives out slices of\ncake and disappointment, online stores in general, and any central server which\ninteracts with some number of client processes.\n\nWe introduce two new rules to construct servers. The first rule, $(\\give[1]{})$,\nmarks a interaction over some channel as a server interaction. It does this by\nsending a channel \\tm{y} over a \\emph{shared} channel \\tm{x}. The channel \\tm{y}\nis the channel across which the actual interaction will eventually take place.\nThe second rule, \\textsc{Cont}, short for contraction, allows us to contract\nseveral server interactions into a single server. This allows us to construct a\nserver which has multiple interactions of the same type, across the same shared\nchannel.\\footnote{%\n  While it ultimately does not matter whether $(\\give[1]{})$ and $(\\take[1]{})$\n  are implemented with a send or a receive action, it feels more natural to have\n  the server do the sending.\n  Clients indicate their interest in interacting with the server by connecting\n  to the shared channel, but it is up to the server to decide \\emph{when} to\n  interact with each channel.}\n\\begin{center}\n  \\ncInfGive1\n  \\ncInfCont\n\\end{center}\nUsing these rules, we can derive the right-hand side of our proof, by marking\neach of the store's interactions as server interactions, and then contracting\nthem.\n\\begin{prooftree}\n  \\AXC{$\\seq[{ \\store }]{ \\Theta, \\tmty{z}{\\cake}, \\tmty{z'}{\\cake} }$}\n  \\SYM{(\\give[1]{})}\n  \\UIC{$\\seq[{ \\ncSrv{x'}{z'}{\\store} }]{\n      \\Theta, \\tmty{z}{\\cake}, \\tmty{x'}{\\give[1]{\\cake}} }$}\n  \\SYM{(\\give[1]{})}\n  \\UIC{$\\seq[{ \\ncSrv{x}{z}{\\ncSrv{x'}{z'}{\\store}} }]{\n      \\Theta, \\tmty{x}{\\give[1]{\\cake}}, \\tmty{x'}{\\give[1]{\\cake}} }$}\n  \\NOM{Cont}\n  \\UIC{$\\seq[{ \\ncSrv{x}{z}{\\ncSrv{x}{z'}{\\store}} }]{\n      \\Theta, \\tmty{x}{\\give[2]{\\cake}} }$}\n\\end{prooftree}\nThus, we complete the typing derivation of our example.\n\n\\section{Running clients and servers}\\label{sec:nc-running-clients-and-servers}\nOnce we have a client/server interaction, how do we run it? Ideally, we would\nsimply use the reduction rule closest to the one used in the \\textpi-calculus. \n\\[\n  \\reducesto\n  {\\tm{\\cpCut{x}{\\ncCnt{x}{y}{P}}{\\ncSrv{x}{z}{R}}}}\n  {\\tm{\\cpCut{y}{P}{\\cpSub{y}{z}{R}}}}\n\\]\nHowever, our case is complicated by the fact that in \\tm{\\cpCut{x}{P}{Q}} the\nname restriction is an inseparable part of the composition, and therefore has to\nbe part of our reduction rule. \nBecause of this, the above reduction can only apply in the singleton case.\nIf the client pool contains more than one client, such as in the term below,\nthen there is no way to isolate a single client together with the server,\nbecause \\tm{x} occurs in both \\tm{\\ncCnt{x}{y}{P}} and \\tm{\\ncCnt{x}{z}{Q}}.\n\\[\n  \\tm{\\cpCut{x}{\\ncPool{\\ncCnt{x}{y}{P}}{\\ncCnt{x}{z}{Q}}}{\\ncSrv{x}{w}{R}}}\n  \\centernot\\Longrightarrow\n\\]\nTherefore, we add a second reduction rule, which handles communication between a\none client in a pool of multiple clients and a server.\n\\[\n  \\reducesto\n  {\\tm{\\cpCut{x}{\\ncPool{\\ncCnt{x}{y}{P}}{Q}}{\\ncSrv{x}{z}{R}}}}\n  {\\tm{\\cpCut{x}{Q}{\\cpCut{y}{P}{\\cpSub{y}{z}{R}}}}}\n\\]\nLastly, because we have added another form of parallel composition, we add\nanother congruence rule, to allow for reduction inside client pools.\n\\input{def-nc-term-reduction}\n\nThe rules \\ncRedBetaStar1 and \\ncRedBetaStar{n+1} seem like the elimination\nrules for a list-like construct. This may come as a surprise, as our client\npools are built up like binary trees, and the typing rules for both sides are\ntree-like, with $(\\take[1]{})$ and $(\\give[1]{})$ playing the role of leaves,\nand \\textsc{Pool} and \\textsc{Cont} merging two trees with $m$ and $n$ leaves\ninto one with $m+n$ leaves.\nHowever, the server process imposes a sequential ordering on its interactions,\nand it is because of this that we have to use list-like elimination rules.\n\nSo where does the non-determinism in \\nodcap come from? Let us say we have a\nterm of the following form:\n\\[\n  \\tm{\n    \\cpCut{x}\n    {\\ncPool{\\ncCnt{x}{y_1}{P_1}}{\\dots \\mid \\ncCnt{x}{y_n}{P_n}}}\n    {\\ncSrv{x}{y}{Q}}\n  }\n\\]\nBecause pooling is commutative and associative, we can rewrite this term to\nbring any client in the pool to the front, before applying \\ncRedBetaStar{n+1}.\nThus, like in the \\textpi-calculus, the non-determinism is introduced by the\nstructural congruence.\n\nDoes this mean that, for an arbitrary client pool \\tm{P} in\n\\tm{\\cpCut{x}{P}{\\ncSrv{x}{z}{Q}}}, every client in that pool is competing for\nthe server interaction on \\tm{x}?\nNot necessarily, as some portion of the clients can be blocked on an external\ncommunication. For instance, in the term below, clients\n$\\tm{\\ncCnt{x}{y_{n+1}}{P_{n+1}}} \\dots \\tm{\\ncCnt{x}{y_m}{P_m}}$ are blocked\non a communication on the external channel \\tm{a}.\n\\[\n  \\arraycolsep=0pt\n  \\tm{\n  \\begin{array}{lrl}\n    \\nu x.&  ((&\\; \\ncPool{\\ncCnt{x}{y_1}{P_1}}{\\dots\\mid\\ncCnt{x}{y_n}{P_n}}\\\\\n          &\\mid&\\; \\cpWait{a}{\\ncPool{\\ncCnt{x}{y_{n+1}}{P_{n+1}}}{\\dots \\mid \\ncCnt{x}{y_m}{P_m}}}\\;)\\\\\n          &\\mid&\\; \\ncSrv{x}{y_1}{\\dots\\ncSrv{x}{y_m}{Q}}\\;)\n  \\end{array}}\n\\]\nIf we reduce this term, then only the clients\n$\\tm{\\ncCnt{x}{y_1}{P_1}} \\dots \\tm{\\ncCnt{x}{y_n}{P_n}}$\nwill be assigned server interactions, and we end up with the following canonical\nform term. \n\\[\n  \\arraycolsep=0pt\n  \\tm{\n  \\begin{array}{lrl}\n    \\nu x.&   (&\\; \\cpWait{a}{\\ncPool{\\ncCnt{x}{y_{n+1}}{P_{n+1}}}{\\dots\\mid\\ncCnt{x}{y_m}{P_m}}}\\\\\n          &\\mid&\\; \\ncSrv{x}{y_{n+1}}{\\dots\\ncSrv{x}{y_m}{Q}}\\;)\n  \\end{array}}\n\\]\nThis matches the reduction behaviour of the \\textpi-calculus, and it fits with\nout notion of computation with processes.\n\n\\section{Properties of \\nodcap}\\label{sec:nc-properties}\nIn this section, we will revisit the proofs for three important properties of\n\\rcp, namely preservation, progress, and termination, and show that our\nextensions preserve these properties.\n\n\\subsection{Preservation}\nPreservation is the fact that term reduction preserves typing. There are two\nproofs involved in this. First, we show that structural congruence preserves\ntyping.\n\\input{thm-nc-preservation-equiv}\n\\input{fig-nc-preservation-equiv}\nSecondly, we prove that term reduction preserves typing.\n\\input{thm-nc-preservation}\n\\input{fig-nc-preservation-1}\n\n\\subsection{Canonical forms and progress}\nIn this section, we will extend the definition of canonical forms and the proof\nof progress progress given in \\cref{sec:cppi}.\n\n\\subsubsection{Canonical forms}\nFirst, we extend the definitions of actions with our actions for client and\nserver creation. \n\\input{def-nc-action}\nSecondly, as we can reduce inside client pools, we will add pooling to our\ndefinition of evaluation prefixes.\n\\input{def-nc-evaluation-prefixes}\nThe definition for the maximum evaluation prefix is unchanged.\n\nThere are some subtleties to our definition of canonical forms. The type system\nfor \\cp guarantees that all links directly under an evaluation context act on a\nbound channel. Not so for \\nodcap.\n\\begin{scprooftree}\n  \\AXC{}\n  \\NOM{Ax}\n  \\UIC{$\\seq[{ \\cpLink{x}{y} }]{ \\tmty{x}{\\take[m]{A}}, \\tmty{y}{\\give[m]{A^\\bot}} }$}\n  \\AXC{$\\seq[{ P }]{ \\Gamma, \\tmty{x}{\\take[n]{A}} }$}\n  \\NOM{Pool}\n  \\BIC{$\\seq[{ \\ncPool{\\cpLink{x}{y}}{P} }]{ \\Gamma, \\tmty{x}{\\take[m+n]{A}}, \\tmty{y}{\\give[m]{A^\\bot}} }$}\n\\end{scprooftree}\nThere is no way to sensibly reduce this link.\nFurthermore, in \\cp, if two processes act on the same channel, then they must be\non different sides of the cut introducing that channel. The addition of shared\nchannels and client pools invalidates this property.\nTherefore, we will have to be more careful about the way we define canonical\nforms.\nWe restate the definition of canonical forms below. The additions have been\nitalicised.\n\\input{def-nc-canonical-forms}\n\n\\subsection{Evaluation contexts}\nEvaluation contexts are one-holed term contexts under which reduction can take\nplace. Since we have added another congruence rule, stating that reduction can\ntake place inside client pools, we extend our definition of evaluation contexts\nto match this.\n\\input{def-nc-evaluation-contexts}\nWe also restate \\cref{thm:cp-display-cut-1}, and prove that our extension\npreserves the property.\n\\input{thm-nc-display-cut-1}\nFurthermore, it will be useful to prove a similar lemma, which shows that we can\npush any pooling downwards under an evaluation context.\n\\input{thm-nc-display-pool-1}\n\n\\subsection{Progress}\nProgress is the fact that every term is either in some canonical form, or can be\nreduced further.\nFirst, we will restate \\cref{thm:cp-progress-link} and \\cref{thm:cp-progress-beta},\nwhich relate evaluation prefixes and evaluation contexts, and show that our\nextension preserves these properties. \n\\input{thm-nc-progress-link}\n\\input{thm-nc-progress-beta}\nIn essence, \\cref{thm:nc-progress-link} and \\cref{thm:nc-progress-beta} cover\nthe cases in which either \\cpRedAxCut1 or a \\textbeta-reduction rule will be\napplied.\nHowever, after applying \\cref{thm:nc-progress-beta}, we cannot immediately apply\n\\ncRedBetaStar{n+1}. For that, we must uncover at least one layer of pooling.\nWe prove a lemma which states that if we have an interaction on a shared channel\n\\tm{x}, we can push all pooling rules which pool clients communicating on \\tm{x}\ninwards. \n\\input{thm-nc-progress-shared}\nFinally, we are ready to extend our proof of progress. The overall structure of\nthe proof remains the same, though the addition of pooling makes the wording\nslightly more subtle.\n\\input{thm-nc-progress}\n\n\\subsection{Termination}\nTermination is the fact that if we iteratively apply progress to obtain a\nreduction, and apply that reduction, we will eventually end up with a term in\ncanonical form.\nWe restate its proof here for the sake of completeness, but its wording is\nunchanged, modulo references to figures.\n\\input{thm-nc-termination}\n\n\\section{\\nodcap and non-deterministic local choice}\\label{sec:nc-local-choice}\nIn \\cref{sec:local-choice}, we discussed the non-deterministic local choice\noperator, which is used in several extensions of \\piDILL and\n\\cp~\\parencite{atkey2016,caires2014,caires2017}.\nThis operator is admissible in \\nodcap.\nWe can derive the non-deterministic choice \\tm{P+Q} by constructing the\nfollowing term:\n\\[\n  \\arraycolsep=0pt\n  \\tm{\n  \\begin{array}{lrlrl}\n    \\nu x.&((  & \\; \\ncCnt{x}{y}{\\cpInr{y}{\\cpHalt{y}}} \\\\\n          &\\mid& \\; \\ncCnt{x}{z}{\\cpInr{z}{\\cpHalt{z}}} \\; )\\\\\n          &\\mid& \\; \\ncSrv{x}{y}{\\ncSrv{x}{z}{}}\\text{case}\\;y\\;\n          &\\;\\{& \\; \\cpWait{y}{\\cpCase{y}{\\cpWait{y}{P}}{\\cpWait{y}{P}}}\\\\\n          &&& ;& \\; \\cpWait{y}{\\cpCase{y}{\\cpWait{y}{Q}}{\\cpWait{y}{Q}}}\\;\\}\\;)\n  \\end{array}\n  }\n\\]\nThe term is a cut between two processes.\nBoth sides are well-typed, see~\\cref{fig:nc-local-choice}.\n\\input{fig-nc-local-choice}\nLet us unpack what each side is doing. \nOn the left-hand side, we have a pool of two processes,\n\\tm{\\ncCnt{x}{y}{\\cpInr{y}{\\cpHalt{y}}}} and \\tm{\\ncCnt{x}{z}{\\cpInr{z}{\\cpHalt{z}}}}.\nEach makes a choice---the first sends \\tm{\\text{inl}}, the second sends \\tm{\\text{inr}}.\nOn the right-hand side, we have a server with both \\tm{P} and \\tm{Q}.\nThis server has two channels on which a choice is offered, \\tm{y} and\n\\tm{z}. However, the choice on \\tm{z} does not affect the outcome of the\nprocess.\nWhen these clients and the server are put together, the choices offered by the\nserver will be non-deterministically lined up with the clients which make\nchoices, and either \\tm{P} or \\tm{Q} will run.\n\nWhile there is a certain amount of overhead involved in this encoding, it scales\nlinearly in terms of the number of processes.\nThe reverse---encoding the non-determinism present in \\nodcap using\nnon-deterministic local choice---scales exponentially, as with the \\textpi-calculus.\n\nNonetheless, it is worrying that we duplicate each program \\tm{P} and \\tm{Q} in\norder to encode non-deterministic local choice.\nHowever, we can replace the each term of the form \\tm{\\cpCase{y}{\\cpWait{y}{P}}{\\cpWait{y}{P}}}\nwith \\tm{\\cpCut{w}{\\cpCase{z}{\\cpWait{z}{\\cpHalt{w}}}{\\cpWait{z}{\\cpHalt{w}}}}{\\cpWait{w}{P}}}.\nThis process is also well-typed, see below.\n\\begin{scprooftree}\n  \\AXC{}\n  \\SYM{(\\one)}\n  \\UIC{$\\seq[{ \\cpHalt{w} }]{ \\tmty{w}{\\one} }$}\n  \\SYM{(\\bot)}\n  \\UIC{$\\seq[{ \\cpWait{z}{\\cpHalt{w}} }]{ \\tmty{w}{\\one}, \\tmty{z}{\\bot} }$} \n  \\AXC{}\n  \\SYM{(\\one)}\n  \\UIC{$\\seq[{ \\cpHalt{w} }]{ \\tmty{w}{\\one} }$}\n  \\SYM{(\\bot)}\n  \\UIC{$\\seq[{ \\cpWait{z}{\\cpHalt{w}} }]{ \\tmty{w}{\\one}, \\tmty{z}{\\bot} }$} \n  \\SYM{(\\with)}\n  \\BIC{$\\seq[{\n      \\cpCase{z}{\\cpWait{z}{\\cpHalt{w}}}{\\cpWait{z}{\\cpHalt{w}}}\n    }]{ \\tmty{w}{\\one}, \\tmty{z}{\\bot\\with\\bot} }$} \n  \\AXC{$\\seq[{ P }]{ \\Gamma }$}\n  \\SYM{(\\bot)} \n  \\UIC{$\\seq[{ \\cpWait{w}{P} }]{ \\Gamma, \\tmty{w}{\\bot} }$}\n  \\NOM{Cut}\n  \\BIC{$\\seq[{\n      \\cpCut{w}{\\cpCase{z}{\\cpWait{z}{\\cpHalt{w}}}{\\cpWait{z}{\\cpHalt{w}}}}{\\cpWait{w}{P}}\n    }]{ \\Gamma, \\tmty{z}{\\bot\\with\\bot} }$} \n\\end{scprooftree}\n%%% Local Variables:\n%%% TeX-master: \"main\"\n%%% End:\n", "meta": {"hexsha": "baa39fbb5f4bccb315e43ab527105d409e956ce2", "size": 23932, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/thesis/cpnd.tex", "max_stars_repo_name": "wenkokke/nodcap", "max_stars_repo_head_hexsha": "fb5e78d6182276e4d93c4c0e0d563b6b027bc5c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-09-05T08:58:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-24T20:16:35.000Z", "max_issues_repo_path": "doc/thesis/cpnd.tex", "max_issues_repo_name": "pepijnkokke/nodcap", "max_issues_repo_head_hexsha": "fb5e78d6182276e4d93c4c0e0d563b6b027bc5c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/thesis/cpnd.tex", "max_forks_repo_name": "pepijnkokke/nodcap", "max_forks_repo_head_hexsha": "fb5e78d6182276e4d93c4c0e0d563b6b027bc5c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-09-05T08:58:13.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-05T08:58:13.000Z", "avg_line_length": 46.7421875, "max_line_length": 108, "alphanum_fraction": 0.7040364366, "num_tokens": 7528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.346005816693504}}
{"text": "% ==============================================================================\n%\n%                 T H E O R E T I C A L   B A C K G R O U N D\n%\n% ==============================================================================\n\\chapter{Theoretical Background} % ------------------------------------------- %\n\\label{ch:theory}\n% ---------------------------------------------------------------------------- %\n% ==============================================================================\n%\n%                               O V E R V I E W\n%\n% ==============================================================================\n\nBefore  delving  into the  design  process,  some  aspects of  the  underlying\ntheory should  be understood.   Whilte this  chapter is not  intended to  be a\ncomprehensive treatise on the subject, it shall serve as a short refresher. At\nits end,  the reader should  have sufficient  insight to understand  the basic\nmotivation of our project from a theoretical point of view.\n\n% ==============================================================================\n%\n%                              D S P   C H A I N\n%\n% ==============================================================================\n\\section{The Digital Signal Processing Chain}% <<< --------------------------- %\n\\label{sec:dsp_chain}\n% ---------------------------------------------------------------------------- %\n\nDigitally acquiring a signal generally requires at least the following steps:\n\\begin{itemize}\\tightlist\n        \\item\n            Passing the signal through an analog low-pass filter.\n        \\item\n            Sampling and quantizing the filtered signal.\n\\end{itemize}\n\nThe   resulting   sequence  of   values   can   then  be   further   digitally\nprocessed. The necessary  building blocks  for this  process are  portrayed in\nFigure~\\ref{fig:dspChain:blocks}.\n\n\\begin{figure}\n    \\centering\n    \\input{images/dspChain/dspChain.tikz}\n    \\caption[The DSP Chain]{%\n        The  basic  building   blocks  of  the  DSP  chain   from  its  analog\n        input  to its  digitally processed  output.  From  left to  right: The\n        analog  low-pass filter  (\\emph{LP}), the  analog-to-digital converter\n        (\\emph{ADC}), and  an arbitrary  digital signal processing  system for\n        further processing of the ADC's output (\\emph{DSP}).%\n    }\n    \\label{fig:dspChain:blocks}\n\\end{figure}\n\nOf particular  interest for our  application is  what happens in  the ADC. The\nquantization process converts a  value-continuous signal into a value-discreet\none, with  its resolution  being a  specification of  the ADC. As  an example,\nthe  ADC  in  our  system  has a  resolution  of  \\num{14}\\,bits,  meaning  it\ncan  divide its  valid input  range  into \\num{16384}  values. Given an  input\nrange of  \\SI{2}{\\volt_\\mathrm{PP}}, this equates  to a resolution  of roughly\n\\SI{122}{\\micro\\volt} (in theory). This quantization  process is the source of\nwhat is generally known as \\emph{quantization noise}.\n\nBesides the quantization,  the other step happening in the  ADC is sampling; a\ntime-continuous signal is converted into a series of time-discreet values. The\ntime between those values is known as \\emph{sampling time}, its inverse is the\n\\emph{sampling  frequency}. Note that  usually  these are  constant, at  least\nduring the  time where the signal  is measured. This need not  strictly be the\ncase  in theory  though. In our  system, this  sampling frequency  is a  fixed\nproperty of the ADC, and is \\SI{125}{\\mega\\hertz}.\n\nThe sampling  step lies  at the  core of  the problem  our project  intends to\naddress:  \\emph{aliasing}. Therefore, we  will take  a  closer look  at a  few\nconsequences  of the  sampling  process, and  how they  are  relevant to  this\nproject.\n\nDescriptively,  the  sampling process  can  be  thought  of  as looking  at  a\nsignal  at  specific  points  in  time   and  capturing  its  value  at  those\npoints. Mathematically, this amounts  to multiplying the signal  with a series\nof Dirac  pulses in  the time domain,  and convolving with  a series  of Dirac\npulses in the frequency domain\\footnote{%\n    \\emph{Pro memoria}: A series of Dirac pulses  in the time domain has as its\n    spectrum a series of Dirac pulses as well.%\n}.\nThis convolution in the  frequency domain lies at the heart  of the problem of\naliasing, because it results in  the incoming signal's spectrum being repeated\nat intervals of $f_s$ (see stage 3 in Figure~\\ref{fig:dspChain:signals}). This\nis no problem as  long as the spectrum of the incoming  signal fits within the\nboundaries set by this repetition. But if  the spectrum of the incoming signal\nis  too broad,  two or  more recurrences  of the  spectrum will  overlap. This\neffect is highlighted in Figure~\\ref{fig:aliasing:band}.\n\n\\begin{figure}[p]\n    \\centering\n    \\input{images/dspChain/timeDomain.tikz}\n    \\input{images/dspChain/freqDomain.tikz}\n    \\caption[Signals Passing Through the DSP Chain (Simplified)]{%\n        Simplified  time-domain  (top)   and  frequency-domain  (bottom)  view\n        of  the  signal  at  different  stages on  its  way  through  the  DSP\n        chain. The  circled  numbers  correspond  to the  stages  as  outlined\n        in  Figure~\\ref{fig:dspChain:blocks}.  Stage  1 is  the signal  before\n        passing through the  input low-pass filter, with  a significant amount\n        of  high-frequency noise. The  low-pass filter  removes any  frequency\n        components  above ${f_s}/{2}$  in an  ideal scenario  (in reality,  it\n        merely attenuates them, as we will see later), resulting in the signal\n        at  stage  2.\\protect\\newline\n        After  having  been  filtered,  the  ADC  samples  and  quantizes  the\n        signal, yielding a sequence of  values, schematically portrayed in the\n        rightmost picture for stage 3.  Note that due to the sampling process,\n        the  spectrum of  the  filtered  signal is  repeated  at intervals  of\n        $f_s$. This is the source of the issue of \\emph{aliasing}.%\n    }\n    \\label{fig:dspChain:signals}\n\\end{figure}\n\\begin{figure}[p]\n    \\centering\n    \\input{images/aliasing/band.tikz}\n    \\caption[Aliasing Illustrated via Signal Frequency Band]{%\n        Simplified view  of a signal  which does not produce  aliasing between\n        its recurrences  in the  frequency spectrum  (top), contrasted  with a\n        signal whose  frequency band  has components  above half  the sampling\n        frequency,  resulting   in  aliasing;  its  spectral   copies  overlap\n        (highlighted areas in the bottom plot).%\n    }\n    \\label{fig:aliasing:band}\n\\end{figure}\n\nThis overlap results in two primary problems:\n\\begin{itemize}\\tightlist\n    \\item\n        The digital  signal may not  be unambiguously reconstructable  into an\n        analog signal, if that is intended.\n    \\item\n        Frequencies  may occur  in the  digital  signal stream  which are  not\n        actually  present  in  the  original  signal. This  problem  is  often\n        referred to  as the  \\emph{folding back} of  frequency components. See\n        Figure~\\ref{fig:aliasing:dirac} for an illustration  of how this might\n        look.  This problem  is of particular interest to  our application, as\n        we will see later.\n\\end{itemize}\n\n\\begin{figure}\n    \\centering\n    \\input{images/aliasing/dirac.tikz}\n    \\caption[Aliasing With Harmonic Signals]{%\n        Example of  two harmonic signals  being sampled. In the top  plot, the\n        signal's frequency is  below half the sampling frequency  and there is\n        no aliasing. The  signal can be  reconstructed without error.   In the\n        bottom  plot,  the  signal's  frequency is  above  half  the  sampling\n        frequency. Consequently, the copies of the signal's frequency spectrum\n        centered around  the sampling  frequency and  its negative  alias back\n        into  the  band  between  $-f_s/2$  and  $f_s/2$. If  this  signal  is\n        reconstructed, the resulting  signal would have a frequency  of $f_s -\n        f_{\\mathrm{sig}}$ instead of $f_{\\mathrm{sig}}$.%\n    }\n    \\label{fig:aliasing:dirac}\n\\end{figure}\n\n\nOnce a signal  has left the ADC and  is handed down the DSP  chain for further\nprocessing,  the primary  problem becomes  one of  resources, particularly  in\nreal-time applications. In  most systems,  the available  hardware is  a fixed\nconstraint and depending on what sort of  processing is to be conducted on the\ndigital  data stream,  the available  resources may  or may  not suffice.   If\navailable resources are  found to be insufficient for  real-time processing of\nthe data stream, one may choose to\n\\begin{itemize}\\tightlist\n    \\item\n        not process the data in real time,\n    \\item\n        reduce the complexity of the computations, or\n    \\item\n        reduce the amount of data to be processed through \\emph{downsampling}\n        of the signal.\n\\end{itemize}\nThe  last case  is the  route  which is  chosen in  our application. The  main\nconstraint on the STEMlab is that the data being generated cannot be moved off\nthe device in real time.  Therefore the  amount of data must be reduced before\nit can be moved off the device to a computer for viewing or further processing\n(see Section~\\ref{sec:requirements}).\n\nBecause downsampling a signal is in  essence nothing more than the sampling of\na  signal  which  has  already  been sampled,  a  lot  of  the  considerations\nwhich  are  valid  for  the  step  from an  analog  to  a  digital  signal  as\noutlined above  are either very  similar or even  identical. Specifically, the\nsame  considerations for  aliasing  still  apply: If the  signal  which is  to\nbe  downsampled has  frequency components  above $f_\\mathrm{s,downsampled}/2$,\naliasing will occur. And since the signal coming out of the ADC has the analog\nsignal's spectrum (filtered by the analog lowpass before the ADC) recurring at\nintervals of the ADC's sampling frequency, this is always the case.\n\nTherefore,  the sampled  signal must  be  filtered through  a low-pass  filter\nbefore  being downsampled,  just as  the original  analog signal  was low-pass\nfiltered  before being  passed into  the  ADC. In light  of the  signal to  be\ndownsampled  being a  \\emph{digital} signal  instead  of an  analog one,  that\nlow-pass filter  must naturally  be a digital  filter as  well. Designing such\ndigital low-pass filters is the core mission of this project.\n\nThe key properties  of such filters which are relevant  to our application are\nits transition  band width  (filter steepness)  and its  aliasing attenuation.\nThe aliasing attenuation refers  to the fact that when a  filter is being used\nfor  downsampling,  copies  of  its  frequency response  will  be  created  at\nintervals  of the  lower  sampling  rate (analogous  to  the sampling  process\nproducing spectral copies of a signal when sampling an analog signal).\n\nThe stopband  components of these  copies overlap with the  intended passband,\nleading to aliasing  (it should be noted that this  phenomenon is also present\nin  the case  of  the analog  input  filter for  the DSP  chain  at the  ADC's\noutput). This effect is  portrayed in Figure~\\ref{fig:aliasing:iirCopies}. The\ntop  plot shows  the filter's  frequency response  along with  four copies  to\nillustrate the overlap effect. The bottom  plot shows the aliasing effect more\nclearly by removing the spectral copies and retaining the aliased components.\n\nThe overlapping parts of the spectrum  are composed of spectral copies both to\nthe right  and left side of  the original. Therefore, the aliased  regions are\nalternately flipped around the vertical axis. This creates in essence the same\neffect  as if  the paper  were folded  along multiples  of the  lower sampling\nrate  over the  frequency  range of  the  central  copy (in  the  case of  our\nexample: $0.2f_s$, $0.4f_s$, $0.6f_s$ and $0.8f_s$) like an accordion. This is\nwhere the term \\emph{folding back} originates.\n\n\\begin{figure}\n    \\centering\n    \\input{images/aliasing/iirCopies.tikz}\n    \\caption[Folding Back of Stopband Components Into Passband]{%\n        The phenomenon  of folding back  when downsampling, illustrated  for a\n        lowpass IIR  filter with a  cutoff frequency  of $0.2\\cdot f_s$  for a\n        downsampling ratio of $R=5$.  The downsampling process produces copies\n        of the filter's frequency response  at intervals of the lower sampling\n        frequency, visible  in the  top plot.  The  stopbands of  these copies\n        then  overlap with  the intended  passband.  The  bottom plot  shows a\n        close-up view with the spectral copies for clarity.%\n    }\n    \\label{fig:aliasing:iirCopies}\n\\end{figure}\n\n%>>>\n% ==============================================================================\n%\n%                        D I G I T A L   F I L T E R S\n%\n% ==============================================================================\n\\section{Digital Filters}% <<< ----------------------------------------------- %\n\\label{sec:digital_filters}\n% ---------------------------------------------------------------------------- %\n\nAhead of studying  any potential details of digital filters,  it is helpful to\nhave  an  overview of  the  major  types of  filters  and  some of  their  key\nproperties.  Digital filters can  be distinguished by several characteristics;\ncommon ways  to categorize them  are by  topology, impulse response  and their\nfrequency  response. There are  two to  three commonly  used types  of digital\nfilters, depending  on how they  are grouped: Infinite impulse  response (IIR)\nfilters and  finite impulse  response (FIR)  filters. A third  group, cascaded\nintegrator-comb (CIC)  filters, is variously thought  of as a special  type of\nFIR filter (similarity of its transfer  functions), a subgroup of IIR filtersk\n(it  contains  feedback  and  feedforward  paths) or  a  new  type  of  filter\naltogether,  depending on  which source  one  chooses to  consult.  While  our\nsystem uses  FIR and  CIC filters, a  brief overview of  IIR filters  is still\npresented here, for the sake of completeness and some context.\n\n\n% ==============================================================================\n%\n%                        I I R   F I L T E R S\n%\n% ==============================================================================\n\\subsection{IIR Filters} %<<< ------------------------------------------------ %\n\\label{subsec:iir_filters}\n% ---------------------------------------------------------------------------- %\n\nInfinite impulse response filters are  so named because their impulse response\ncontinues  into perpetuity,  never  reaching zero. In  practice, the  response\nusually comes  sufficiently close to  zero at a certain  point that it  can be\nconsidered zero for most intents and purposes.\n\nIIR  filters have  feedback paths,  resulting  in a  filter response  equation\nwith  non-zero   denominator  components. Their  basic  building   blocks  are\ndelay  elements,   multipliers  and  adders,   as  seen  in  the   example  of\nFigure~\\ref{fig:filtertopologies:iir}. Their transfer functions have the form\n\\begin{equation}\n    \\label{eq:iir_filter}\n    H(z) = \\frac{%\n            \\sum_{k=0}^N b_k \\cdot z^{-k}}{%\n            1 + \\sum_{i=0}^M a_i \\cdot z^{-i}}\n\\end{equation}\n\nIIR filters generally require a lower order (and therefore fewer resources) to\napproximate a  certain frequency  response specification  than FIR  filters do\n(particularly the constraint of a narrow transition band), but this comes at a\ncost:  IIR  filters have a  non-linear phase response;  linear-phase responses\ncan only  be approximated. Furthermore, IIR  filters are not guaranteed  to be\nBIBO stable due to their feedback paths.\n\n\\begin{figure}\n    \\centering\n    \\input{images/filtertopologies/iir.tikz}\n    \\caption[IIR Filter: Biquad]{Example of an IIR filter topology for a biquad}\n    \\label{fig:filtertopologies:iir}\n\\end{figure}\n\nSome of the generally used types of IIR filters are:\n\\begin{itemize}\\tightlist\n    \\item\n        Butterworth  filter: Named after  the British  engineer and  physicist\n        Stephen  Butterworth  (1885  --  1958),  who  first  described  it  in\n        1930. Characterized by a very flat passband (no passband ripple).\n    \\item\n        Chebyshev filter  (type I  and II): Named after  Russian mathematician\n        Pafnuty Chebyshev  (1821 --  1894). They are steeper  than Butterworth\n        filters, at the cost of suffering from ripple in the passband (type I)\n        or stopband (type II).\n    \\item\n        Bessel  filter: Named for  the German  mathematician Friedrich  Bessel\n        (1784 -- 1846). Optimized to have a maximally linear phase response in\n        order  to  minimize the  distortion  of  signals passing  through  the\n        filter.\n    \\item\n        Elliptical  filters: Also known  as  Cauer filters,  after the  German\n        mathematician Wilhelm Cauer (1900 -- 1945), or Zolotarev filter, after\n        Russian mathematician Yegor Zolotarev (1847 -- 1878). Characterized by\n        equiripple in the  bassband and stopband and a  very narrow transition\n        band compared to other filters of the same order.\n\\end{itemize}\n\n%>>>\n% ==============================================================================\n%\n%                            F I R   F I L T E R S\n%\n% ==============================================================================\n\\subsection{FIR Filters} %<<< ------------------------------------------------ %\n\\label{subsec:FIR_filters}\n% ---------------------------------------------------------------------------- %\n\nFIR filters are  characterized by an impulse response which  decays to zero in\nfinite time (see  Figure~\\ref{fig:filter_specs:coefs}, unlike IIR filters. The\nfilter response is characterized by Equation~\\ref{eq:fir_filter}:\n\\begin{equation}\n    \\label{eq:fir_filter}\n    H(z) = \\sum_{k=0}^{N} b_k \\cdot z^{-k}\n\\end{equation}\n\nFigure~\\ref{fig:filtertopologies:fir}   shows   one  possible   topology   for\nimplementing a  FIR filter,  the so-called  direct form. As  can be  seen, the\nbasic building  blocks of  a FIR  filter are  delay elements,  multipliers and\nadders, same as for IIR filters.\n\n\\begin{figure}[b]\n    \\centering\n    \\input{images/filtertopologies/fir.tikz}\n    \\caption[FIR Filter Topology Example]\n        {One possible topology for a FIR filter (direct form)}\n    \\label{fig:filtertopologies:fir}\n\\end{figure}\n\nFIR filters have several advantages:\n\\begin{itemize}\\tightlist\n    \\item\n        They are inherently BIBO stable because they lack feedback paths.\n    \\item\n        They  can  be  easily  designed  to  have  a  linear  phase  response,\n        preventing signal distortion due to  different group delays for signal\n        components of different frequencies.\n    \\item\n        The shape of  their frequency response can be  very finely tuned. This\n        makes them ideally  suited for certain purposes,  such as compensation\n        filters (see Section~\\ref{subsec:CIC_filters}).\n    \\item\n        Implementation is usually rather straightforward.\n\\end{itemize}\n\nTheir  main  disadvantage   is  that  due  to  the  lack   of  feedback,  they\ngenerally require comparatively high filter  orders for narrow transition band\nwidths. Illustratively, this can be understood by the following considerations:\n\\begin{itemize}\\tightlist\n    \\item\n        The frequency response of an ideal low-pass filter is a rectangle.\n    \\item\n        The inverse  Fourier transform  of a rectangle  is an  infinitely long\n        $sinc$ function.\n    \\item\n        Therefore,  the  impulse  response  of the  ideal  brick  wall  filter\n        (rectangular) would have an infinite number of taps.\n    \\item\n        Truncation of the number of taps  leads to a deviation of the filter's\n        frequency response from the brick wall  filter.  As the number of taps\n        (and  therefore the  FIR filter's  impulse response)  is reduced,  its\n        frequency response deviates more and  more from the brick wall filter,\n        resulting  in  a  flatter  transition between  the  passband  and  the\n        stopband as well as the introduction of ripple.\n\\end{itemize}\nThis     process     is     illustrated      in     simplified     form     in\nFigure~\\ref{fig:brick_wall_vs_FIR}.  The FIR filter's transition band width is\nparticularly  important  for  our  application in  order  to  reduce  aliasing\neffects, as will be shown later.\n\n\\begin{figure}\n    \\centering\n    \\input{images/brickwallVsFIR/bwVsFIR.tikz}\n    \\caption[Brick Wall Filter vs. FIR Filter (simplified)]{%\n        The effect of  truncating a $sinc$ function in the  time domain on its\n        spectrum (simplified)%\n    }\n    \\label{fig:brick_wall_vs_FIR}\n\\end{figure}\n\nDesigning    FIR    filters    is     usually    performed    by    specifying\ncertain     desired    characteristics     of    the     filter's    frequency\nresponse. Figure~\\ref{fig:filter_specs:freqResponse} shows one possible way of\ndoing this for FIR filters by specifying four parameters:\n\\begin{itemize}\\tightlist\n    \\item\n        pass band ripple: $A_\\mathrm{P}$\n    \\item\n        stop band attenuation: $A_\\mathrm{St}$\n    \\item\n        pass band edge frequency: $F_\\mathrm{P}$\n    \\item\n        stop band edge frequency: $F_\\mathrm{St}$\n\\end{itemize}\nThe resulting transition band width  $F_\\mathrm{Tb}$ is the difference between\nthe passband edge  frequency and the stopband edge frequency,  and serves as a\nuseful indicator of how many coefficients (i.e. resources) the filter will end\nup using. Narrower transition bands tend to require a higher filter order, and\ntherefore  more  resources. Coefficient  counts  of several  hundred  are  not\nuncommon  for steep  FIR filters.   Other sets  of parameters  can be  used to\ndesign filters,  but these are  the ones used  in this project,  therefore the\nemphasis on them.\n\nFigure~\\ref{fig:filter_specs:coefs}  shows  the   resulting  impulse  response\n(coefficient  set)  for  a  FIR  filter  designed  by  using  the  four  above\nmentioned parameters, with  values given by Equations~\\ref{eq:filter_specs:ap}\nthrough \\ref{eq:filter_specs:fst} handed to one  of Matlab's FIR filter design\nalgorithms.\n\\begin{align}\n    A_\\mathrm{P}  &= \\SI{2}{\\dB}   \\label{eq:filter_specs:ap}\\\\\n    A_\\mathrm{St} &= \\SI{60}{\\dB}  \\label{eq:filter_specs:ast}\\\\\n    F_\\mathrm{P}  &= 0.3 \\cdot f_s \\label{eq:filter_specs:fp}\\\\\n    F_\\mathrm{St} &= 0.4 \\cdot f_s \\label{eq:filter_specs:fst}\n\\end{align}\n\n\\begin{figure}\n    \\centering\n    \\input{images/filterSpecs/freqResponse.tikz}\n    \\caption[Specifying FIR Filter Constraints]{\n        Specifications in the frequency domain and the resulting filter's\n        frequency response as designed by Matlab.%\n    }\n    \\label{fig:filter_specs:freqResponse}\n\\end{figure}\n\n\\begin{figure}\n    \\centering\n    \\input{images/filterSpecs/coefs.tikz}\n    \\caption[Impulse Response of a FIR Filter]{\n        Impulse    response    (coefficients)     for    the    filter    from\n        Figure~\\ref{fig:filter_specs:freqResponse}    with   the    parameters\n        as     given     by     Equations~\\ref{eq:filter_specs:ap}     through\n        \\ref{eq:filter_specs:fst} passed to one  of Matlab's FIR filter design\n        algorithms, resulting  in a set  of \\num{39} coefficients.   Note that\n        the coefficients to the left and right of these values are zero, hence\n        \\emph{finite} impulse response filters.%\n    }\n    \\label{fig:filter_specs:coefs}\n\\end{figure}\n\nOne   particular  form   of  a   FIR   filter  is   the  so-called   half-band\nfilter. Half-band  filters   are  used   for  downsampling   by  a   ratio  of\n$R=2$.   They  are  characterized  by  a  point-symmetric  frequency  response\nacross  the $(f_s/4,0.5)$  point. Their advantage  lies in  the efficiency  of\ntheir  coefficient structure: Each  second coefficient  is zero,  and all  the\nnon-zero  coefficient  are  symmetrical  around  the  center  of  the  impulse\nresponse. For  higher  downsampling  rates,  multiple  half-band  filters  can\nbe cascaded. Figure~\\ref{fig:fir:halfband_linear_example}  shows the amplitude\nfrequency response and the coefficient set of an example filter.\n\n\\begin{figure}\n    \\centering\n    \\input{images/halfband/halfbandLinearExample.tikz}\n    \\caption[Half-band Filter Frequency Response]{%\n        The  frequency response  and coefficient  set of  a half-band  filter.\n        The  frequency response  is the  amplitude plotted  linearly, not  the\n        magnitude plotted logarithmically, in order to emphasize the symmetry.\n        The coefficient  set is  symmetrical around its  midpoint. Also, every\n        second coefficient outside the central peak is zero.%\n    }\n    \\label{fig:fir:halfband_linear_example}\n\\end{figure}\n%>>>\n% ==============================================================================\n%\n%                            C I C   F I L T E R S\n%\n% ==============================================================================\n\\clearpage\n\\subsection{CIC Filters} %<<< ------------------------------------------------ %\n\\label{subsec:CIC_filters}\n% ---------------------------------------------------------------------------- %\n\nCIC  filters  offer  a  very  computationally efficient  way  to  decimate  or\ninterpolate,  though their  design parameters  are limited.   They were  first\nintroduced  in 1981  in  \\cite{1163535} by  Eugene  B. Hogenauer. They can  be\nimplemented  both  as decimation  filters  (reduction  in sampling  rate)  and\ninterpolation filters (increase in sampling rate).\n\n\\subsubsection{General Description}\n\\label{subsubsec:cic:general_description}\n\nA   CIC  filter   is  a   cascade  of   integrator  and   comb  stages,   with\neither   a   sampling    rate   compressor   (in   case    of   a   decimator)\nor   a    sampling   rate    expander   (in    case   of    an   interpolator)\nbetween   the   integrator   and   comb   sections.    A   single   integrator\nstage   is   shown    in   Figure~\\ref{fig:filtertopologies:integrator},   and\nFigure~\\ref{fig:filtertopologies:comb}   shows   a   single  comb   stage   in\nfeedforward form. Figure~\\ref{fig:filtertopologies:cic} depicts a complete CIC\ndecimator with three stages.\n\n\\begin{figure}\n    \\centering\n    \\begin{minipage}[t][][b]{0.45\\textwidth}\n        \\centering\n        \\input{images/filtertopologies/integrator.tikz}\n        \\caption[Integrator Stage]{A single integrator stage}\n        \\label{fig:filtertopologies:integrator}\n    \\end{minipage}\n    \\begin{minipage}[t][][b]{0.45\\textwidth}\n        \\centering\n        \\input{images/filtertopologies/comb.tikz}\n        \\caption[Comb Stage]{A single comb stage in feedforward form}\n        \\label{fig:filtertopologies:comb}\n    \\end{minipage}\n\\end{figure}\n\n\\begin{figure}\n    \\centering\n    \\input{images/filtertopologies/cic.tikz}\n    \\caption[CIC Filter Topology]\n        {CIC decimation filter topology with three integrator and comb stages}\n    \\label{fig:filtertopologies:cic}\n\\end{figure}\n\nThe integrator stages run at $f_\\mathrm{s}$ and have a transfer function of\n\\begin{equation}\n    \\label{eq:cic:integrator_stage}\n    H_\\mathrm{I}(z) = \\frac{1}{1-z^{-1}}\\text{,}\n\\end{equation}\nwhile the  comb stages run  at the  reduced frequency of  $f_\\mathrm{s}/R$ and\nhave the transfer function\n\\begin{equation}\n    \\label{eq:cic:comb_stage}\n    H_\\mathrm{C}(z) = 1 - z^{-RM}\n\\end{equation}\nwhere  $M$  is the  \\emph{differential  delay},  one  of the  filter's  design\nparameters.\n\nThe  transfer function  of  a  complete CIC  filter  (referenced  to the  high\nsampling  rate  $f_\\mathrm{s}$)  consisting  of   $N$  stages  is  deduced  by\nmultiplying the  transfer functions  of the $N$  cascaded integrator  and comb\nstages, yielding\n\\begin{equation}\n    \\label{eq:cic:complete}\n    H_\\mathrm{CIC}(z) = H_\\mathrm{I}^N(z) \\cdot H_\\mathrm{C}^N(z) =\n    \\frac{\\left(1 - z^{-RM}\\right)^N}{\\left( 1 - z^{-1} \\right)^N} =\n    \\left[\\sum_{k = 0}^{RM-1} z^{-k}\\right]^N\n\\end{equation}\n\nLooking at  the last form  of the CIC  filter's transfer function,  it becomes\nevident  that  it  can also  be  thought  of  as  a FIR  filter  with  unitary\ncoefficients. Of particular  note is  the fact  that this  is so  despite each\nstage having  feedback or feedforward  paths and the integrator  stages having\npoles at  $f = 0$  (i.e. the  integrators by themselves  are not in  fact BIBO\nstable,  even though  the complete  system  is). The fact  that the  resulting\nfilter has no poles can be  intuitively understood by looking at the frequency\nresponses of  the integrator and comb  stages, and finally their  cascade (see\nSection~\\ref{subsubsec:cic:frequency_characteristics}).\n\nCIC filters are well-suited to large reductions in sampling rates because they\nare very  economical in  their resource  usage. This economy  is based  on six\nprimary factors~\\cite{1163535}:\n\\begin{itemize}\\tightlist\n    \\item\n        The filter requires no multipliers.\n    \\item\n        There are no filter coefficients to store.\n    \\item\n        The amount  of storage needed  for intermediate results is  reduced by\n        running the comb  stages at a lower sampling  rate. A conventional FIR\n        filter topology implementing the  same transfer function would require\n        more resources for storing its intermediate results because the entire\n        filter would run at the incoming sampling rate.\n    \\item\n        The  topology  of  the  filter   has  a  high  degree  of  regularity;\n        consisting of two  primary building blocks. This lends  itself well to\n        optimization.\n    \\item\n        The control logic can be kept simple.\n    \\item\n        The same filter  design can be used  for a large range  of rate change\n        factors $R$, requiring minimal  adaption in circuitry. This effect can\n        be  seen  in the  frequency  responses  plotted  in  the top  plot  of\n        Figure~\\ref{fig:cic:freq_responses:var}.\n\\end{itemize}\n\nHowever, CIC filters do suffer from some drawbacks. The two primary ones are:\n\\begin{itemize}\\tightlist\n    \\item\n        For large rate  change factors $R$, the register growth  of the filter\n        can become very high. See Section~\\ref{subsubsec:cic:register_growth}.\n    \\item\n        A   CIC  filter   has   only  three   design  parameters   determining\n        its   frequency  response: Rate   change   factor  $R$,   differential\n        delay   $M$,    and   the    number   of   stages    $N$. The   amount\n        of   fine-tuning   which   can    be   conducted   on   the   filter's\n        frequency   response  is   therefore   extremely   limited  (more   in\n        Section~\\ref{subsubsec:cic:frequency_characteristics}).\n\\end{itemize}\n\nAs  can  be  seen in  Equation~\\ref{eq:cic:integrator_stage},  the  integrator\nstages have  unity feedback coefficients. In  the case of CIC  decimators, the\nregisters of  the integrators  will therefore  suffer from  register overflow.\nThis causes no harm as long as two conditions are fulfilled:\n\\begin{itemize}\\tightlist\n    \\item\n        The filter's  implementation is based  on two's complement  or another\n        number system allowing wrap-around between  its most positive and most\n        negative numbers.\n    \\item\n        The maximum  magnitude which is expected  at the output is  within the\n        range of that number system.\n\\end{itemize}\n\nA numerical  example to demonstrate this  effect and better explain  the inner\nworkings  of a  CIC filter  can be  found in  Appendix~\\ref{sec:app:cic_simu},\nstarting on page~\\pageref{sec:app:cic_simu}.\n\n% ==============================================================================\n%\n%              F R E Q U E N C Y   C H A R A C T E R I S T I C S\n%\n% ==============================================================================\n\\subsubsection{Frequency Characteristics} % ---------------------------------- %\n\\label{subsubsec:cic:frequency_characteristics}\n% ---------------------------------------------------------------------------- %\n\nThis section presents some of  the more important frequency characteristics of\nthe  CIC  filter. We  will  start  with  some  considerations  about  how  the\nintegrators and comb  sections interact in the frequency domain  to create the\nCIC filter's frequency response.\n\nAs shown in the top plot in Figure~\\ref{fig:cic:freq_responses}, an integrator\nis in essence  a lowpass filter, with a pole  at $f = 0$.  A comb  filter is a\nfilter  which  attenuates one  specific  frequency  component along  with  its\nmultiples (in a notch comb filter; there is also the inverse concept of a peak\nfilter which only lets  a certain frequency and multiples of  it pass).  It is\nalso evident that comb filters have no poles (a fact which can be deduced from\nEquation~\\ref{eq:cic:comb_stage} as well, of course).\n\nThe  bottom plot  from  Figure~\\ref{fig:cic:freq_responses} is  the result  of\ncascading integrators and combs.  The integrator's pole at $f = 0$ compensates\nfor the  comb section's zero at  the same location, leading  to a significant,\nbut finite, DC gain of the CIC filter.\n\n\\begin{figure}\n    \\centering\n        \\input{images/cic/cicFreqResponses.tikz}\n        \\caption[Frequency Responses for Integrators, Combs and CIC Filters]{%\n            Frequency responses  for integrators, combs and  their combination\n            into a three-stage CIC filter with a rate change factor of \\num{9}\n            and a  differential delay of  \\num{1}.  Note that  \\num{4.5} lobes\n            fit into the plot for the comb  filter, due to $R\\cdot M = 9$ (the\n            order of the  comb filter).%\n        }\n        \\label{fig:cic:freq_responses}\n\\end{figure}\n\n\nOne  drawback   of  CIC  filters  is   that  they  have  no   clearly  defined\npassband  as  such. Rather,  their  frequency  response  starts  dropping  off\nright  as   the  frequency   axis  goes  beyond   zero. This  effect   (  also\nreferred  to  as  \\emph{passband  droop} or  \\emph{passband  attenuation})  is\nvisible  in  the bottom  plot  of  Figure~\\ref{fig:cic:freq_responses} and  in\nFigure~\\ref{fig:cic:freq_responses:passband:attenuation} in more detail. Since\nCIC  filters  lack  a  clearly  defined transition  band  edge,  defining  the\nfrequency band  which is  to be used,  i.e. the actual  passband, is  a design\ndecision  and can  vary even  when  using the  same filter,  depending on  the\napplication.\n\nThe   amount   of  passband   droop   is   constant   for  a   given   product\nof    the    differential    delay    $M$    and    the    cutoff    frequency\n$f_\\mathrm{c}$,    where    $f_\\mathrm{c}$    is    a    fraction    of    the\nlower   sampling    rate   (i.e.    a   fraction    of   the    first   lobe's\nwidth). Figure~\\ref{fig:cic:freq_responses:passband:attenuation}    highlights\nthis  effect  for  two  different  filters. Table~\\ref{tab:cic:pb_attenuation}\nin                 Appendix~\\ref{sec:app:cic_filter_tables}                 on\npage~\\pageref{tab:cic:pb_attenuation}  contains a  list with  more values  for\nsome common configurations.\n\nBecause of  the passband  droop, a  CIC filter  by itself  is rarely  a viable\nsolution. Rather, it is generally deployed as  the first element in a chain of\nfilters,  where the  later stages  are FIR  filters. Due to  the CIC  filter's\nfrugality in terms of resource usage, it is ideally suited as an initial stage\nwhere  the most  samples per  time  need to  be processed. The  fact that  FIR\nfilters need  to perform many  more computations  (and more complex  ones) per\nsample is  then no  longer as  much of a  problem, since  the FIR  filters run\nat  lower sampling  frequencies  and  therefore have  many  more clock  cycles\navailable  to  compute  each  output. Also,  because  the  frequency  response\nof  a  FIR  filter can  be  very  finely  tuned  to a  desired  profile,  they\ncan  be used  to  compensate for  the  CIC filter's  passband  droop; this  is\ngenerally  known as  a \\emph{CIC  compensation filter}. More  on the  topic in\nSection~\\ref{subsubsec:cic:compensators}.\n\n\\begin{figure}\n    \\centering\n        \\input{images/cic/cicPassbandAttenuation.tikz}\n        \\caption[CIC Filter: Passband and Aliasing Attenuation]{%\n            Passband   attenuation   for   two   CIC   filters   with   $R=9$,\n            $N=4$   and  $M=1$   and   $M=2$,  respectively. The   attenuation\n            is  identical   for  the  bandwidth-differential   delay  product,\n            which    is   $1/8$    for    the    two   configurations.     The\n            attenuation   is  \\SI{-3.65}{\\dB}   in  both   cases;  the   value\n            can    be   found    in   Table~\\ref{tab:cic:pb_attenuation}    on\n            page~\\pageref{tab:cic:pb_attenuation}.%\n        }\n        \\label{fig:cic:freq_responses:passband:attenuation}\n\\end{figure}\n\nAnother  effect which  must be  taken  into consideration  when designing  CIC\nfilters is  the amount  of aliasing  which occurs from  the stopband  into the\npassband. A region of width $f_\\mathrm{c}$ above  and below each $M$th null is\nfolded  back  into  the  filter's  passband. This  effect  is  highlighted  in\nFigure~\\ref{fig:cic:freq_responses:passband:aliasing}.   The  gravity of  this\neffect  depends  on  the  width  of the  cutoff  frequency  $f_\\mathrm{c}$  as\nwell  as  the  differential delay  $M$. Table~\\ref{tab:cic:pb_attenuation}  in\nAppendix~\\ref{sec:app:cic_filter_tables}  contains  some   values  for  common\nranges for M and $f_\\mathrm{c}$.\n\n\\begin{figure}\n    \\centering\n        \\input{images/cic/cicPassbandAliasing.tikz}\n        \\caption[CIC Filter: Passband and Aliasing Attenuation]{%\n            Passband  aliasing  for   a  CIC  filter  with  $R   =  9$,  $N=4$\n            and  $M=1$  and  a  cutoff frequency  of  $f_\\mathrm{c}  =  0.25$,\n            referenced  to the  lower  sampling frequency  $f_\\mathrm{s,low}$.\n            The  region  of  width  $f_\\mathrm{c}$  around  every  $M$th  null\n            is   folded   back   into   the   passband. The   regions   beyond\n            that   are  of   course  folded   back  as   well,  but   are  cut\n            off  by  the   compensator,  see  Figure~\\ref{fig:cic:cfir}.   The\n            resulting   passband  aliasing   attenuation  is   \\SI{41.8}{\\dB},\n            as     indicated     in     Table~\\ref{tab:cic:pb_aliasing}     on\n            page~\\pageref{tab:cic:pb_aliasing}.%\n        }\n        \\label{fig:cic:freq_responses:passband:aliasing}\n\\end{figure}\n\nAs  mentioned, the  CIC filter  has  only three  design parameters: Its  rate\nchange factor  $R$, the differential delay  $M$ and the number  of stages $N$.\nThe influence  of these parameters  on the  CIC filter's frequency  response is\nportrayed in Figure~\\ref{fig:cic:freq_responses:var}. Some things of note are:\n\\begin{itemize}\\tightlist\n    \\item\n        Increasing $R$ increases the amount  of nulls and the filter's overall\n        gain.\n    \\item\n        Increasing  $M$ also  increases the  number of  nulls as  well as  the\n        filter's gain.  Note that for  CIC decimators, the region around every\n        $M$th null is folded back  into the passband.  For practical purposes,\n        $M$ is usually set to \\num{1} or \\num{2}, see \\cite{1163535}.\n    \\item\n        Adding more stages leads to a  high increase in filter gain, since $N$\n        occurs in the exponent of the filter's transfer function. It does not,\n        however, change the number or placement of the nulls.\n\\end{itemize}\n\n\\begin{figure}\n    \\centering\n        \\input{images/cic/cicFreqResponsesVar.tikz}\n        \\caption[Influence of Design Parameters on Frequency Response]{%\n            The influence of  the design parameters $R$, $M$ and  $N$ on a CIC\n            filter' frequency  response.  Increasing $R$  and $M$ leads  to an\n            increased number  of nulls, as  visible in  the top two  plots, as\n            well as an  increase in the DC gain.  Adding  more stages does not\n            change  the location  of the  nulls, but  does add  significant DC\n            gain.%\n        }\n        \\label{fig:cic:freq_responses:var}\n\\end{figure}\n\n% ==============================================================================\n%\n%                           C O M P E N S A T O R S\n%\n% ==============================================================================\n\\subsubsection{Compensators} % ----------------------------------------------- %\n\\label{subsubsec:cic:compensators}\n% ---------------------------------------------------------------------------- %\n\nIn     order      to     achieve     a     flat      passband,     the     CIC\nfilter's    attenuation     in    the    frequency    range     observed    in\nFigure~\\ref{fig:cic:freq_responses:passband:attenuation}  can  be  compensated\nwith a filter  whose frequency response has the opposite  shape. Operated in a\ncascade, the two filters create a  frequency response with a flat passband and\na sharp drop-off into the stopband. Figure~\\ref{fig:cic:cfir} shows an example\nof such a  system, with frequency responses of a  CIC filter, its compensator,\nand the resulting cascade.\n\nThe compensation filter not only serves to compensate for the passband, but is\nalso responsible  for the transition band  width of the cascade. Due  to their\nflexibility, FIR filters are generally employed for this purpose. As mentioned\nin  the previous  section,  the  sharpness of  their  transition  band can  be\ncontrolled  by  adjusting their  kernel  size. If  more filters  follow  after\nthe  compensator  in  the  filter chain,  the  compensator's  transition  band\nneed  not be  very narrow. A  filter  with a  few dozen  coefficients in  size\nis  often  sufficient in  such  cases  (the filter  used  for  the example  in\nFigure~\\ref{fig:cic:cfir} has \\num{50} coefficients).\n\nThe design of CIC compensators is  usually left up to software algorithms, for\nexample with Matlab. For a more  detailed introduction to the topic, including\nexample  code  and  more  elaborate explanations,  Altera's  Application  Note\nfrom~\\cite{altera:an455} is warmly recommended.\n\n\\begin{figure}\n    \\centering\n    \\input{images/cic/cfirDemo.tikz}\n    \\caption[CIC Compensator]{%\n        Frequency behavior of  a CIC filter, its compensator,  and the cascade\n        of the  two. Note the  spectral copies of  the compensator  around the\n        nulls of the  CIC filter, i.e. the multiples of  its outgoing sampling\n        rate.%\n    }\n    \\label{fig:cic:cfir}\n\\end{figure}\n% ==============================================================================\n%\n%                        R E G I S T E R   G R O W T H\n%\n% ==============================================================================\n\\subsubsection{Register Growth}\n\\label{subsubsec:cic:register_growth}\n\nAs shown by Hogenauer in~\\cite{1163535}, the maximum register growth is\n\\begin{equation}\n    \\label{eq:cic:maximum_register_growth}\n    G_\\mathrm{max} = (R \\cdot M)^N\n\\end{equation}\nThe most  significant bit $B_\\mathrm{max}$ of  the output register as  well as\nfor all  stages (both the  integrators and the comb  stages) of the  filter is\ndetermined to be\n\\begin{equation}\n    \\label{eq:cic:maximum_register_growth:bit_width}\n    B_\\mathrm{max} = \\lceil N \\log_2 RM + B_\\mathrm{in} - 1 \\rceil\n\\end{equation}\nwhere $B_\\mathrm{in}$ is  the bit width of the input  register.  For high rate\nchange  factors, these  values can  become very  large.  A  filter with  three\nstages, a  differential delay of  \\num{1}, a rate  change of \\num{128}  and an\ninput  width of  \\num{16}\\,bits  yields  \\num{36}\\,bits output  width at  full\nprecision.\n% ==============================================================================\n%\n%         T R U N C A T I O N   A N D   R O U N D I N G   E R R O R S\n%\n% ==============================================================================\n\\subsubsection{Errors Due to Truncation and Rounding}\n\\label{subsubsec:cic:truncation_and_rounding}\n\nIn practical cases, it is often not feasible to retain full precision; in such\nsituations, either truncation or rounding may  be used at each filter stage to\nreduce register widths and keep resource usage within certain limits. For this\npurpose, it is necessary  to know the system function from  the $j$th stage up\nto and including the last:\n\\begin{equation}\n    \\label{eq:cic:truncation_rounding:system_function}\n    H_j(z) = \\left\\lbrace\n        \\begin{aligned}\n            H_I^{N-j+1}H_C^N                        &\n            = \\sum_{k=0}^{(RM-1)N+j-1} h_j[k]z^{-k} &\n            \\quad j                                 &\n            = 1, 2, \\cdots, N                       \\\\\n            H_C^{j-N}                                          &\n            = \\hspace{1.1em}\\sum_{k=0}^{2N+1-j} h_j[k]z^{-kRM} &\n            \\quad j                                            &\n            = N+1, \\cdots, 2N\n        \\end{aligned}\n    \\right.\n\\end{equation}\nwhere\n\\begin{equation}\n    \\label{eq:cic:truncation_rounding:system_function}\n    h_j[k] = \\left\\lbrace\n        \\begin{aligned}\n            \\sum_{l=0}^{\\lfloor k/(RM) \\rfloor} (-1)^l\n            {{N}\\choose{l}}{{N-j+k-RMl}\\choose{k = RMl}} &\n            j                                            &\n            = 1, 2, \\cdots N                             \\\\\n            (-1)^k{{2N+1-j}\\choose{k}} &\n            j                          &\n            = N+1, \\cdots 2N\n        \\end{aligned}\n    \\right.\n\\end{equation}\nare  the  impulse  response   coefficients. These  functions  are  derived  by\nHogenauer in~\\cite{1163535}.\n\nIn a  filter with $N$ stages,  there are $2N+1$  error sources in the  case of\nlimited precision: Each stage,  and the output register. Each  error source is\npresumed to have  white noise characteristics, i.e. its  noise is uncorrelated\nto its input as well as other error sources.  The error at the $j$th source is\nassumed to have a uniform probability distribution with a width of\n\\begin{equation}\n    \\label{eq:cic:truncation_rounding:probability_distribution}\n    E_j = \\left\\lbrace\n        \\begin{aligned}\n            0        & \\quad\\text{without truncation or rounding}\\\\\n            2^{B_j}  & \\quad\\text{otherwise}\n        \\end{aligned}\n    \\right.\n\\end{equation}\nwhere the number of bits discarded at the $j$th error source is $B_j$. The mean\nof this error is\n\\begin{equation}\n    \\label{eq:cic:truncation_rounding:mean}\n    \\mu_j = \\left\\lbrace\n        \\begin{aligned}\n            \\frac{1}{2}E_j & \\quad\\text{for truncation}\\\\\n            0              & \\quad\\text{otherwise}\n        \\end{aligned}\n    \\right.\n\\end{equation}\nand the variance comes out to\n\\begin{equation}\n    \\label{eq:cic:truncation_rounding:variance}\n    \\sigma_j^2 = \\frac{1}{12}E_j^2.\n\\end{equation}\n\nThe total mean error at the filter's output due to the $j$th stage is\n\\begin{equation}\n    \\label{eq:cic:truncation_rounding:total_mean_error_jth_stage}\n    \\mu_{T_j} = \\mu_jD_j\n\\end{equation}\nwhere\n\\begin{equation}\n    \\label{eq:cic:truncation_rounding:mean_error_gain}\n    D_j = \\left\\lbrace\n        \\begin{aligned}\n            (RM)^N         & \\quad j = 1\\\\\n            0              & \\quad j = 2, 3, \\cdots, 2N\\\\\n            1              & \\quad j = 2N+1\n        \\end{aligned}\n    \\right.\n\\end{equation}\nis the \\emph{mean  error gain} for the $j$th error  source. Note that only the\nfirst and the last  error source contribute to the filter's  mean error at the\noutput. This is because  the sum of the impulse response  coefficients is zero\nfor all other  stages. Consequently, whether one chooses to  truncate or round\nis  without  consequence except  in  the  case of  the  first  and last  error\nsources. In an analogous manner, the total variance computes to\n\\begin{equation}\n    \\label{eq:cic:truncation_rounding:total_variance_jth_stage}\n    \\sigma_{T_j}^2 = \\sigma_j^2F_j^2\n\\end{equation}\nwhere\n\\begin{equation}\n    \\label{eq:cic:truncation_rounding:variance_error_gain}\n    F_j = \\left\\lbrace\n        \\begin{aligned}\n            \\sum_k h_j^2[k]  & \\quad j = 1, 2, \\cdots, 2N\\\\\n            1                & \\quad j = 2N+1\n        \\end{aligned}\n    \\right.\n\\end{equation}\nis called the  \\emph{variance error gain} for the $jth$  error source.  We can\nnow compute the global mean error and variance of the filter:\n\\begin{align}\n    \\label{eq:cic:truncation_rounding:global:mean_error}\n    \\mu_T &= \\sum_{j = 1}^{2N+1} \\mu_{T_j} = \\mu_{T_1} + \\mu_{T_{2N+1}}\\\\\n    \\label{eq:cic:truncation_rounding:global:variance}\n    \\sigma_{T}^2 &= \\sum_{j=1}^{2N+1} \\sigma_{T_j}\n\\end{align}\nThese equations  are used  to calculate  the properties of  the CIC  filter as\ndeployed in our design in Section~\\ref{subsec:fpga:errors_in_cic_filter}.\n\n% ==============================================================================\n%\n%                   C I C   F I L T E R S :   S U M M A R Y\n%\n% ==============================================================================\n\\subsubsection{Summary}\n\\label{subsubsec:cic:summary}\n\nIn conclusion, the key properties of CIC filters are:\n\\begin{itemize}\\tightlist\n    \\item\n        They can be implemented both as decimators and interpolators.\n    \\item\n        Neither multipliers nor storage for coefficients are needed.\n    \\item\n        CIC  decimation  filters have  a  high  gain, leading  to  significant\n        register  growth.  Truncation  or rounding  can be  used to  limit the\n        resource usage, both at the filter's output and internally.\n    \\item\n        The three design parameters are  the rate change $R$, the differential\n        delay $M$ and the number of stages $N$.\n    \\item\n        The  presence of  passband  droop requires  a  compensation filter  to\n        achieve a flat passband response.\n\\end{itemize}\n%>>>\n\n%>>>\n\n% ==============================================================================\n%\n%             M U L T I - S T A G E   F I L T E R   D E S I G N S\n%\n% ==============================================================================\n\\section{Multi-Stage Filter Designs} % <<< ----------------------------------- %\n\\label{sec:multi_stage_filter_designs}\n% ---------------------------------------------------------------------------- %\n\nAt  first   sight,  the   most  obvious  way   to  implement   a  downsampling\nsystem  might  appear  to be  to  design  one  filter  for each  desired  rate\nchange   factor.   However,   this  would   be  highly   impractical. Instead,\nmulti-stage  designs  are usually  used  in  practice. An in-depth  discussion\nof  their  advantages and  drawbacks  was  offered  by Crochiere  and  Rabiner\nin~\\cite{crochiere-rabiner:multirate-dsp}. A few aspects of multi-stage filter\ndesign which are relevant to our application shall be presented here.\n\nTo  reduce  aliasing  effects  in  the passband,  it  is  generally  desirable\nto  keep  the width  of  the  transition  band  roughly constant  in  relation\nto  the   width  of   the  passband   (visible  in   the  filter's   flank  in\nFigure~\\ref{fig:aliasing:iirCopies}).   As  the downsampling  ratio  increases\nand  the  passband width  decreases,  the  transition band  therefore  becomes\nprogressively narrower,  necessitating higher filter orders  in a single-stage\ndesign.\n\nThis   effect  is   illustrated  in   Figure~\\ref{fig:fdesign:tbw_width_Rvar},\ncomparing two filters with a transition band $1/5$ as wide as the passband for\ndownsampling  ratios of  \\num{2} and  \\num{4}. The filter  for $R=4$  requires\n\\num{60}  coefficients,  compared  to  \\num{30} coefficients  for  the  filter\ndesigned  for $R=2$.   The other  specifications (passband  ripple, stop  band\nattenuation) are identical.   As an extreme case, a filter  designed by Matlab\nwith the  same parameters for  a downsampling  ratio of $R=625$  is \\num{8860}\ncoefficients in size.\n\nUsing multi-stage  designs helps to avoid  the need to implement  filters with\nsuch large kernels.  When cascading filters, it is the last stage of the chain\nwhich defines the overall passband and transition band width. The same overall\ntransition band  in absolute  terms can  be achieved  with smaller  filters in\nmulti-stage designs, because  a filter's transition band width  is relative to\nthe sampling rate at which it is running.  This is shown in the bottom plot in\nFigure~\\ref{fig:fdesign:tbw_width_Rvar}.\n\n\\begin{figure}\n    \\centering\n    \\input{images/fdesign/tbwDemoRVar.tikz}\n    \\caption\n        [Frequency Response of Multi-Stage Vs. Single-Stage Design]{%\n        Two filters are  used here: Both have a transition band  $1/5$ as wide\n        as  their passbands. The  top filter  is designed  for a  downsampling\n        ratio $R=2$ and  has a coefficient count of  $N=30$. The second filter\n        is designed for $R=4$ and  has \\num{60} coefficients. Cascading two of\n        the top filters into a two-stage  design, depicted in the bottom plot,\n        results in the same overall passband  and transition band width as the\n        single-stage design, but with fewer computations per time.%\n    }\n    \\label{fig:fdesign:tbw_width_Rvar}\n\\end{figure}\n\nSince  cascading  multiple  filters   does  increase  coefficient  count  (and\nstorage), one might  be inclined to think that not  much has been won. Indeed,\nthe  overall  number  of  coefficients   is  identical  for  both  filters  in\nFigure~\\ref{fig:fdesign:tbw_width_Rvar}  (though, this  obviously need  not be\nso  in  other  examples). However: Merely \\num{30}  multipliers  and  \\num{29}\nadders  (those  of the  first  filter  in the  cascade)  run  at the  incoming\nsampling  frequency in  the  case  of the  cascade,  while  the components  of\nthe  second  filter  run at  half  that.   In  the  case of  the  single-stage\nfilter,  all  its  \\num{60}  multipliers   and  \\num{59}  adders  run  at  the\nfull  sampling frequency. Distributing  the calculations  over two  stages has\ntherefore yielded  an overall reduction  in needed computation  power. As rate\nchange  factors increase,  the  benefits of  multi-stage  designs become  even\nmore pronounced~\\cite{crochiere-rabiner:multirate-dsp}. \n\nIn general, the  earlier stages in a cascade tend  to have higher downsampling\nratios  but  wider   transition  bands,  and  the  later   stages  have  lower\ndownsampling  ratios  and  narrower  transition  bands  (normalized  to  their\nrespective  sampling frequencies).   This  minimizes  computations across  the\noverall design by  using smaller filters for  high-frequency calculations, and\ngiving the larger filters more  time to compute their outputs. Multiple stages\nhaving the  same downsampling ratios  is also  a common approach,  but earlier\nstages having lower downsampling ratios than later stages is uncommon.\n\nA further advantage of cascading filters is that successive stages can be used\nto  shape the  overall frequency  response, as  seen in  the case  of the  CIC\ncompensator in Section~\\ref{subsubsec:cic:compensators} A drawback of cascades\nis that the ripple in their passband shows additive behavior, so the stages in\na cascade of  filters have more stringent ripple requirements  in the passband\nthen  a single-stage. However,  the cost  for this  is usually  offset by  the\nadvantages of multi-stage designs.\n\nWhen designing multi-stage filters, it can  happen that the transition band of\nan earlier stage overlaps with the spectral copy of a later stage running at a\nreduced sampling rate.  In that case, the stopband response of the cascade can\nhave  peaks exceeding  the  desired overall  stopband attenuation. To  prevent\nthis, the following condition must be satisfied:\n\\begin{equation}\n    \\label{eq:cascade:transition_band_overlap}\n    f_\\mathrm{st,1} < \\frac{f_\\mathrm{s,1} - f_\\mathrm{st,2}}{R_1}\n\\end{equation}\n\\begin{conditions}\n    f_\\mathrm{s,1}  & high sampling rate                  \\\\\n    f_\\mathrm{st,1} & stopband frequency of first filter  \\\\\n    f_\\mathrm{st,2} & stopband frequency of second filter \\\\\n    R_1             & rate reduction in first filter      \\\\\n\\end{conditions}\nFigure~\\ref{fig:fdesign:cascade:good_vs_bad}  shows  some  examples  for  this\ncondition being broken or fulfilled.\n\n\\begin{figure}\n    \\centering\n    \\input{images/fdesign/cascadeDemo.tikz}\n    \\caption[Cascade: Transition Band Overlap]{%\n        Comparison   of   two   cascades: The   first   cascade   (blue)   has\n        sufficient  distance   between  the  start  of   its  stopband  ($0.65\n        \\cdot  f_\\mathrm{s1}$)  and  the  start  of  the  transition  band  of\n        the  second stage's  first copy  around $f_\\mathrm{s2}$  ($0.675 \\cdot\n        f_\\mathrm{s1}$). The  second  cascade  (orange)  has  a  peak  in  its\n        stopband because the transition band  of its first stage overlaps with\n        the  copy of  the second  stage ($0.8  \\cdot f_\\mathrm{s1}$  vs.  $0.6\n        \\cdot f_\\mathrm{s1}$). \\emph{Note:} All  frequencies are normalized to\n        the high sampling rate $f_\\mathrm{s1}$.%\n    }\n    \\label{fig:fdesign:cascade:good_vs_bad}\n\\end{figure}\n\nOne last effect of note when cascading filters concerns stopband attenuation:\nWhen cascading two filters with different stopband attenuations, two things\ncan happen:\n\\begin{itemize}\\tightlist\n    \\item\n        The second  filter attenuates more  strongly than the  first one. This\n        results  in  peaks  above  the second  filter's  stopband  attenuation\n        in  the regions  where  the  spectral copies  of  the second  filter's\n        passband  are   located. This  can  be   seen  in  the  top   plot  in\n        Figure~\\ref{fig:fdesign:cascade:ast_demo}.\n    \\item\n        The first filter attenuates more  strongly than the first one. In that\n        case, the stopband region of the  cascade right next to its transition\n        band is  less strongly  attenuated than  the stopband  regions farther\n        away  from  the  edge. This  case  is shown  in  the  middle  plot  in\n        Figure~\\ref{fig:fdesign:cascade:ast_demo}.\n\\end{itemize}\nNeither of these two effects is usually desired.  In both cases, the resources\ninvested  into the  steeper filter's  stronger attenuation  are wasted  by the\nother filter's weaker stopband attenuation. It  therefore makes more sense for\nthe various  stages in  a cascade  to have the  same stopband  attenuation.\n\n\\begin{figure}\n    \\centering\n    \\input{images/fdesign/astDemo.tikz}\n    \\caption[Cascade: Stopband Attenuation]{%\n        Cascading  two  filters  with different  stopband  attenuations: If  a\n        filter with stronger  stopband attenuation is cascaded  after a filter\n        with weaker  attenuation, the  resulting cascade  has peaks  above the\n        second  filter's  stopband  attenuation (top  plot). If  the  stronger\n        filter is  first in the  cascade, the  drop-off in the  stopband right\n        next to the  transition band is weaker. The two  filters by themselves\n        are shown in the bottom plots.%\n    }\n    \\label{fig:fdesign:cascade:ast_demo}\n\\end{figure}\n\n%>>>\n\n%^^A vim: foldenable foldcolumn=4 foldmethod=marker foldmarker=<<<,>>>\n", "meta": {"hexsha": "dbe49f70b65498bdf030eb4197b20ccbd1385df3", "size": 59021, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/report/chunks/theory.tex", "max_stars_repo_name": "alpenwasser/pitaya", "max_stars_repo_head_hexsha": "a6ced99408171ffcd96c9444adfe30d2ba699f48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-03-22T15:26:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-15T20:19:03.000Z", "max_issues_repo_path": "doc/report/chunks/theory.tex", "max_issues_repo_name": "alpenwasser/pitaya", "max_issues_repo_head_hexsha": "a6ced99408171ffcd96c9444adfe30d2ba699f48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/report/chunks/theory.tex", "max_forks_repo_name": "alpenwasser/pitaya", "max_forks_repo_head_hexsha": "a6ced99408171ffcd96c9444adfe30d2ba699f48", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.2734241908, "max_line_length": 80, "alphanum_fraction": 0.6563765439, "num_tokens": 15594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.3460058095032024}}
{"text": "\\input{common/prelude.tex}\n\n% Spacing for logo\n\\addtolength{\\wpXoffset}{5.5cm}\n\\addtolength{\\wpYoffset}{13.1cm}\n\n\\begin{document}\n\n\\CenterWallPaper{0.3}{common/anchor-logo.png}\n\n\n{\\huge \\bfseries Control.Lens (viewing) \\\\[0.2cm]}\n\n\\HRule%\n\n\\begin{multicols}{2}\n\n\\begin{box1}\n\\subsection *{Getting with Getters}\n\nAny function $(s \\to a)$ can be flipped into continuation passing style, $(a \\to r)\n\\to s \\to r$ and decorated with \\textbf{Const} to obtain:\n\n\\begin{minted}{haskell}\ntype Getting r s a =\n  (a -> Const r a) -> s -> Const r s\n\\end{minted}\nA \\textbf{Getter} describes how to retrieve a single value in a way that can be composed\nwith other \\textbf{LensLike} constructions.\n\nWhen you see this in a type signature it indicates that you can pass the\nfunction a \\textbf{Lens}, \\textbf{Getter}, \\textbf{Traversal}, \\textbf{Fold},\n\\textbf{Prism}, \\textbf{Iso}, or one of the indexed\nvariants, and it will just ``do the right thing''.\n\\end{box1}\n\n\\begin{box2}\n\\subsection *{Safe head}\nPerform a safe head of a \\textbf{Fold} or \\textbf{Traversal} or retrieve\n\\textbf{Just} the result from a \\textbf{Getter} or \\textbf{Lens}.\n\n$ (\\ \\hat{}\\,?) \\equiv flip\\;preview $\n\n\\begin{minted}{haskell}\n(^?) :: s -> Getting (First a) s a -> Maybe a\n\n> Right 4 ^?_Left\nNothing\n> \"world\" ^? ix 3\nJust `l'\n\\end{minted}\n\\end{box2}\n\n\\begin{box1}\n\n\\subsection *{Viewing lenses}\n\nView the value pointed to by a \\textbf{Getter} or \\textbf{Lens} or the result\nof folding over all the results of a \\textbf{Fold} or \\textbf{Traversal} that\npoints at a monoidal values.\n\nThis is the same operation as \\textbf{view} with the arguments flipped.\n\n\\begin{minted}{haskell}\n(^.) :: s -> Getting a s a -> a \n\n> (0, -5)^._2.to abs\n5\n> [\"a\", \"b\", \"c\"] ^. traversed\n\"abc\"\n\\end{minted}\n\\end{box1}\n\n\\begin{box2}\n\\subsection*{Using MonadState}\n\nUse the target of a \\textbf{Lens}, \\textbf{Iso}, or \\textbf{Getter} in the\ncurrent state, or use a summary of a \\textbf{Fold} or \\textbf{Traversal} that\npoints to a monoidal value.\n\n\\begin{minted}{haskell}\nuse :: MonadState s m => Getting a s a -> m a\n\n> evalState (use _1) (1,2)\n1\n> evalState (uses _1 length) (\"hello\",\"\")\n5\n\\end{minted}\n\\end{box2}\n\n\\columnbreak\n\n\\begin{box1}\n\\subsection *{Folding Foldables}\n\\begin{minted}{haskell}\ntype Fold s a =\n  forall m. Monoid m => Getting m s a\n\\end{minted}\nA \\textbf{Fold s a} is a generalization of something \\textbf{Foldable}. It\nallows you to extract multiple results from a container. Every \\textbf{Getter}\nis a valid \\textbf{Fold} that simply doesn't use the Monoid it is passed.\n\nIf there exists a \\textbf{foo} method that expects a\n\\textbf{Foldable (f a)}, then there should be a \\textbf{fooOf} method that\ntakes a \\textbf{Fold s a} and a value of type \\textbf{s}.\n\n\\end{box1}\n\n\\begin{box2}\n\\subsection *{Extracting lists from Folds}\n\nExtract a list of the targets of a \\textbf{Fold}, an infix version of\n\\textbf{toListOf}.\n\n$ toList\\;xs \\equiv xs\\;\\hat{}.. folded $\n\n\\begin{minted}{haskell}\n(^..) :: s -> Getting (Endo [a]) s a -> [a] \n\n> [[1,2],[3]] ^.. traverse . traverse\n[1,2,3]\n> (1,2) ^.. both\n[1,2]\n\\end{minted}\n\\end{box2}\n\n\\begin{box1}\n\\subsection *{Checking for matches}\n\nCheck to see if this \\textbf{Fold} or \\textbf{Traversal} matches 1 or more entries. For the\nopposite, use \\textbf{hasn't}.\n\n\\begin{minted}{haskell}\nhas :: Getting Any s a -> s -> Bool\n\n> has (element 0) []\nFalse\n> has _Right (Left 12)\nFalse\n> hasn't _Right (Left 12)\nTrue\n\\end{minted}\n\\end{box1}\n\n\n\\begin{box2}\n\\subsection*{Indexed Getters}\nFor most operations, there is an indexed variant which will work as expected if\nthe underlying target supports a notion of \\textbf{Indexing}.\n\n\\begin{minted}{haskell}\n> [\"ab\", \"c\"] ^@.. itraversed <.> itraversed  \n[((0,0),'a'),((0,1),'b'),((1,0),'c')]\n> \"hello\" ^@.. itraversed . indices even\n[(0,'h'),(2,'l'),(4,'o')]\n\n> ifind (\\i k -> i > k) [1,2,2,2]\nJust (3,2)\n\\end{minted}\n\\end{box2}\n\\end{multicols}\n\\newpage\n\n{\\huge \\bfseries Control.Lens (setting) \\\\[0.2cm]}\n\n\\HRule%\n\n\\begin{multicols}{2}\n\n\\begin{box1}\n\\subsection *{Modifying records with Setters}\nA \\textbf{Setter s t a b} is a generalization of fmap from \\textbf{Functor}. It\nallows you to map into a structure and change out the contents, but it isn't\nstrong enough to allow you to enumerate those contents. Starting with\n$fmap :: Functor f \\Rightarrow (a \\to b) \\to f a \\to f b$ we monomorphize the type\nto obtain $(a \\to b) \\to s \\to t$ and then decorate it with Identity to obtain:\n\n\\begin{minted}{haskell}\ntype Setter s t a b =\n  (a -> Identity b) -> s -> Identity t\n\\end{minted}\n\nEvery \\textbf{Traversal} is a valid \\textbf{Setter}, since \\textbf{Identity} is\n\\textbf{Applicative}.\n\n\\end{box1}\n\n\\begin{box2}\n\\subsection *{Modifying with a function}\n\nModifies the target of a \\textbf{Lens} or all of the targets of a\n\\textbf{Setter} or \\textbf{Traversal} with a user supplied function.\n\nThis is an infix version of \\textbf{over}.\n\n\\begin{minted}{haskell}\n(%~) :: Profunctor p\n     => Setting p s t a b -> p a b -> s -> t\n\n> traverse %~ even $ [1,2,3]\n[False,True,False]\n\\end{minted}\n\\end{box2}\n\n\\begin{box1}\n\\subsection *{Modifying with a constant value}\n\nReplace the target of a \\textbf{Lens} or all of the targets of a\n\\textbf{Setter} or \\textbf{Traversal} with a constant value.\n\n\\begin{minted}{haskell}\n(.~) :: ASetter s t a b -> b -> s -> t\n\n> [1,2,3] & element 0 .~ 3\n[3,2,3]\n> [1,2,3] & traversed . filtered odd .~ 0\n[0,2,0]\n\\end{minted}\n\\end{box1}\n\n\\begin{box2}\n\\subsection *{Prisms and Isos}\n\nAn \\textbf{Iso} is a pair of inverse functions. You can invert an \\textbf{Iso} with \\textbf{from}.\n\n\\textbf{Prism}s can be thought of as \\textbf{Iso}s that can fail in one\ndirection. You can invert a \\textbf{Prism} with \\textbf{re}.\n\n\\begin{minted}{haskell}\ntype Prism s t a b \n  forall p f. (Choice p, Applicative f) =>\n              p a (f b) -> p s (f t)\ntype Prism' s a = Prism s s a a\n\nprism  :: (b -> t)\n       -> (s -> Either t a)\n       -> Prism s t a b\nprism' :: (a -> s)\n       -> (s -> Maybe a)\n       -> Prism' s a\n\n> 5^.re _Left ^?! _Left\n5\n> _Left # 1\nLeft 1\n\ntype Iso s t a b =\n  forall p f. (Profunctor p, Functor f) =>\n              p a (f b) -> p s (f t)\ntype Iso' s a = Iso s s a a\n\niso :: (s -> a) -> (b -> t) -> Iso s t a b\nfrom :: AnIso s t a b -> Iso b a t s\n\n> 'a' ^. from enum\n97\n> 97 ^. enum :: Char\n'a'\n\n> Map.empty & at \"hi\"\n>           . non Map.empty\n>           . at \"world\" ?~ \"!\"\nfromList [(\"hi\",fromList [(\"world\",\"!\")])]\n\\end{minted}\n\n\\end{box2}\n\n\\end{multicols}\n\n\\begin{box2}\n\\subsection *{Some setting operators}\n\\begin{tabular}{ l l l l l }\n\\textbf{Operator}  &  \\textbf{W/result}  &  \\textbf{W/state}  &  \\textbf{W/both}  &  \\textbf{Action}\\\\\n\\hline\n\\verb!+~ !         &  \\verb!<+~ !        &  \\verb!+= !        &  \\verb!<+= !      &  Add to target(s)\\\\\n\\verb!-~ !         &  \\verb!<-~ !        &  \\verb!-= !        &  \\verb!<-= !      &  Subtract from target(s)\\\\\n\\verb!*~ !         &  \\verb!<*~ !        &  \\verb!*= !        &  \\verb!<*= !      &  Multiply target(s)\\\\\n\\verb!//~!         &  \\verb!<//~!        &  \\verb!//=!        &  \\verb!<//=!      &  Divide target(s)\\\\\n\\verb!^~ !         &  \\verb!<^~ !        &  \\verb!^= !        &  \\verb!<^= !      &  Raise target(s) to a non-negative Integral power\\\\\n\\verb!^^~!         &  \\verb!<^^~!        &  \\verb!^^=!        &  \\verb!<^^=!      &  Raise target(s) to an Integral power\\\\\n\\verb!**~!         &  \\verb!<**~!        &  \\verb!**=!        &  \\verb!<**=!      &  Raise target(s) to an arbitrary power\\\\\n\\verb!||~!         &  \\verb!<||~!        &  \\verb!||=!        &  \\verb!<||=!      &  Logically or target(s)\\\\\n\\verb!&&~!         &  \\verb!<&&~!        &  \\verb!&&=!        &  \\verb!<&&=!      &  Logically and target(s)\\\\\n\\verb!<>~!         &  \\verb!<<>~!        &  \\verb!<>=!        &  \\verb!<<>=!      &  mappend to the target monoidal value(s)\\\\\n\\end{tabular}\n\\end{box2}\n\n\n\\end{document}\n", "meta": {"hexsha": "497206eb454476bd2055fdde8ca97a290a317392", "size": 7841, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "lens.tex", "max_stars_repo_name": "caiorss/haskell-cheat-sheets", "max_stars_repo_head_hexsha": "48b1980ef99bf723ac6e001b33f0dccc90386ba7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-07T09:52:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-07T09:52:45.000Z", "max_issues_repo_path": "lens.tex", "max_issues_repo_name": "caiorss/haskell-cheat-sheets", "max_issues_repo_head_hexsha": "48b1980ef99bf723ac6e001b33f0dccc90386ba7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lens.tex", "max_forks_repo_name": "caiorss/haskell-cheat-sheets", "max_forks_repo_head_hexsha": "48b1980ef99bf723ac6e001b33f0dccc90386ba7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0379310345, "max_line_length": 135, "alphanum_fraction": 0.6106363984, "num_tokens": 2751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.34600580231290085}}
{"text": "\\setlength{\\footskip}{8mm}\r\n\\chapter{ Methodology } \\label{methodology}\r\nThe chapter describes the methodology for the design and implementation of the system. \r\n\r\n\\section{Camera Calibration}\r\nSince I did not calibrate the camera I followed the \r\nfollowing steps to get the intrinsic and extrinsic parameters of the camera.  \r\n\r\n\\begin{figure}\r\n\\centering\r\n\\includegraphics[width=110mm]{figures/camera-car-coordinate-system3.pdf}\r\n\\caption{The relationship between world and car coordinate system.}\r\n\\label{fig:camera_car_coordinate}\r\n\\end{figure}\r\n\r\n\\subsection{Intrinsic Parameters}\r\n\\begin{itemize}\r\n  \\item Focal Length: Every picture taken by a digital camera contains some meta \r\ndata such as camera model, dimensions, color space, focal length, etc. The focal \r\nlength obtained from the meta data is in millimeters where as the focal length \r\nthat is needed in the camera matrix must be in pixels. Using the following \r\nequation\\fullcite{FocalLength} I was able to convert the focal length from \r\nmillimeters to pixels.  \r\n\\[ \\text{focal length in pixels} =\r\n     \\text{image width in pixels} \\times \r\n     \\frac{\\text{focal length in mm}} {\\text{CCD width in in mm}} \r\n\\]\r\n  \r\nThe value of CCD can be obtained from the camera specifications. \r\n\\item Principal Point: I assumed the principal point $(p_{x}, p_{y})$ to be at \r\nthe center of the image. \r\n\\item Skew: Skewing arise when the $x$ and $y$ axes of the pixel element are not \r\nperpendicular to each other. This is a very rare condition and it is safe to \r\nassume $s = 0$. \r\n\\end{itemize}\r\n\r\n\\subsection{Extrinsic Parameters}\r\nAs described in Section \\ref{sec:camera_calibration} the extrinsic parameters \r\nconsists of the rotational matrix $\\mat{R}$ and translation vector $\\vec{t}$. \r\n\r\nEstimating the rotational matrix $\\mat{R}$ without camera calibration is hard, since it depends on the yaw, pitch and roll of the camera. Thus, I conducted a simple experiment to estimate the rotational matrix. \r\n\r\nAssume three points $\\vec{X_{1}}, \\vec{X_{2}}, \\vec{X_{3}}$ in the homogenous \r\nworld coordinate system such that $\\vec{X_{1}} = \r\n\\begin{bmatrix}0&\\beta&0&1\\end{bmatrix}^{T}$, $\\vec{X_{2}} = \r\n\\begin{bmatrix}1&\\beta&0&1\\end{bmatrix}^{T}$, $\\vec{X_{3}} = \r\n\\begin{bmatrix}0&\\beta&1&1\\end{bmatrix}^{T}$ where $\\beta$ is a large number so \r\nthat the point $\\vec{X_{1}}$ will be projected on the horizontal row of the \r\nimage. Using Equation \\ref{eq:camera_equation} and \\ref{eq:camera_equation_2} \r\nthe points $X_{1}, X_{2}, X_{3}$ are projected onto the image. Thus, \r\n\r\n\\begin{center}\r\n\\begin{tabular}{c c c}\r\n  $\\vec{x_{1}} = \\mat{K}[\\mat{R}\\mid\\vec{t}]\\vec{X_{1}}$, & \r\n  $\\vec{x_{2}} = \\mat{K}[\\mat{R}\\mid\\vec{t}]\\vec{X_{2}}$ &\r\n  $\\vec{x_{3}} = \\mat{K}[\\mat{R}\\mid\\vec{t}]\\vec{X_{3}}$\r\n\\end{tabular}\r\n\\end{center}\r\n\r\nFrom the above equation it can be seen that $\\vec{x_{1}}, \\vec{x_{2}}, \\vec{x_{3}}$ depends on \r\n$\\mat{R}$, which needs to be estimated. Since we know that $\\vec{x_{1}}$ should be on \r\nthe horizontal row and at the center of the lane and $\\vec{x_{2}}, \\vec{x_{3}}$ being \r\nslightly to the right and top of $\\vec{x_{1}}$. $\\mat{R}$ is adjusted until the condition is \r\nmet. \r\n\r\nFigure \\ref{fig:rotation_matrix}(a) shows the three points $\\vec{x_{1}}$(red), \r\n$\\vec{x_{2}}$(green), $\\vec{x_{3}}$(blue) being off to the right. Figure \r\n\\ref{fig:rotation_matrix}(b) shows the results of tuning the rotational matrix \r\n$\\mat{R}$ so that the thee points are in the center of the lane.\r\n\r\n\\begin{figure}\r\n \\centering\r\n \\begin{tabular}{c c}\r\n   \\includegraphics[width=80mm]{figures/rotation_after.png} &\r\n   \\includegraphics[width=80mm]{figures/rotation_before.png} \\\\\r\n   (a) & (b) \\\\\r\n \\end{tabular}\r\n \\caption{Estimating the Rotation Matrix by using 3 points}\r\n \\label{fig:rotation_matrix}\r\n\\end{figure}\r\n\r\nThe translation vector $\\vec{t}$ is the distance from the world to camera \r\ncoordinate system. This is the distance between the two wheels in the $y$ axis \r\nand the distance from the ground to the camera in the $z$ axis.\r\n\r\n\\section{Road Lane Extraction}\r\nTo detect the road lane marking I used the ``Road Paint Detection using Matched\r\nFilters\" algorithm \\fullcite{huang2008rss}\r\n\r\n\\subsection{Calculating lane width in pixels}\r\nThe first step is to construct the matched filter. The matched filter varies \r\ndepending on the lane width at each row of the image. Therefore in order to \r\nconstruct the matched filter the lane width at each row of the image must be \r\ncalculated. Given that the camera matrix has already been determined as \r\ndescribed in Section \\ref{sec:camera_calibration}. A point in the image is \r\nrelated to a point in the real world by:\r\n\\begin{equation}\\vec{x} \\sim \\mat{P}\\vec{X} \\end{equation} \\label{eq:camera_eq}\r\nAs shown in Figure \\ref{fig:camera_car_coordinate} the $z$ co-ordinate points \r\nupward to the sky therefore the $x,y$ plane is the ground plane. Assuming that \r\nthe ground is flat $Z$ can be estimated to be $0$. \r\n\\[\r\n\\begin{bmatrix}x\\\\y\\\\1\\end{bmatrix}  \\sim \r\n\\mat{P} \\begin{bmatrix}X\\\\Y\\\\0\\\\1\\end{bmatrix}\r\n\\]\r\n\\begin{eqnarray*}\r\n\\begin{bmatrix}x\\\\y\\\\1\\end{bmatrix} & = & \r\n\\begin{bmatrix}\r\np_{11} & p_{12} & p_{13} & p_{14} \\\\\r\np_{21} & p_{22} & p_{23} & p_{24} \\\\\r\np_{31} & p_{32} & p_{33} & p_{34}\r\n\\end{bmatrix}\r\n\\begin{bmatrix}X\\\\Y\\\\0\\\\1\\end{bmatrix}\r\n\\end{eqnarray*}\r\n\\begin{eqnarray*}\r\n\\begin{bmatrix}x\\\\y\\\\1\\end{bmatrix} & = & \r\n\\begin{bmatrix}\r\n        Xp_{11} & Yp_{12} & \\cancelto{0}{p_{13}} & p_{14} \\\\\r\n        Xp_{21} & Yp_{22} & \\cancelto{0}{p_{23}} & p_{24} \\\\\r\n        Xp_{31} & Yp_{32} & \\cancelto{0}{p_{33}} & p_{34}\r\n\\end{bmatrix} \\\\\r\n\\end{eqnarray*}\r\nSince we are using homogenous coordinates therefore, \r\n\\begin{eqnarray*}\r\ny = \\frac {\\mat{P_{21}}X + \\mat{P_{22}}Y + \\mat{P_{24}}} \r\n                   {\\mat{P_{31}}X + \\mat{P_{32}}Y + \\mat{P_{34}}}\r\n\\end{eqnarray*}\r\nIn practice the width of the lane marking would not be uniform though out the \r\nentire row of the image. The lane marking that appeared directly in front of the \r\ncamera would be slightly wider ($\\sim$ 0.1 cm) than the lane marking that were \r\nat the sides. For simplification I've assumed that the width of the lane marking \r\nis uniform throughout the row. Therefore $X = 0$\r\n\r\n$Y$ which is the distance from the \r\nrear of the car can be calculated for every row of the image. \r\n\\begin{eqnarray*}\r\nY = \\frac{\\mat{P_{24}} - y\\mat{P_{34}}} \r\n                  {y\\mat{P_{32}} - \\mat{P_{22}}}\r\n\\end{eqnarray*}\r\nThe width of lane marking in pixels can be calculated by: \r\n\\begin{eqnarray*}\r\n\\mathrm{width(pixels)} = \r\n\\frac {\\mat{P_{1}}\\begin{bmatrix}W&Y&0&1\\end{bmatrix}^{\\mathrm{T}}}\r\n      {\\mat{P_{3}}\\begin{bmatrix}W&Y&0&1\\end{bmatrix}^{\\mathrm{T}}}\r\n- \r\n\\frac {\\mat{P_{1}}\\begin{bmatrix}0&Y&0&1\\end{bmatrix}^{\\mathrm{T}}}\r\n      {\\mat{P_{3}}\\begin{bmatrix}0&Y&0&1\\end{bmatrix}^{\\mathrm{T}}} \r\n\\end{eqnarray*}\r\nwhere $W$ in the lane width on the ground in centimeters. \r\n\r\n\\subsection{Matched Filter Convolution}\r\nA matched filter is created after obtaining the lane width in pixel of a row.\r\nRows with width less than one pixels are not are not considered. Since these \r\nrows are either above the horizon or are rows with no lane markings on them.\r\n\r\nThe size of the matched filter is calculated by the following:\r\n\\[ \\textrm{Kernel Size} = (\\textrm{Lane Width} \\times 2) + 1\\] \r\nThis ensures that the size of the kernel is always odd. The kernel needs to be \r\nodd so that they are equal negative signal on both side of the positive \r\nsignal. \r\n\r\nFigure \\ref{fig:kernel} shows a kernel for a lane width marking of size 10 \r\npixels. The sum of the kernel is always zero so that it has a DC response of \r\nzero. \r\n\\begin{figure}\r\n\\centering\r\n\\includegraphics[width=100mm]{figures/kernel}\r\n\\caption{Matched filter kernel for a lane width of 10 pixels.}\r\n\\label{fig:kernel}\r\n\\end{figure}\r\n\r\n\\subsection{Non-Maximum Suppression}\r\nThe results from ``Matched Filter Convolution\" consists of the detected lane \r\nmarking and noise. To simplify the processing I used the ``Non-Maximum \r\nSuppression'' technique to transform a lane marking which has some width to a \r\nlane marking which which is one pixel wide. The ``Non-Maximum Suppression\" used \r\nhere is similar to the one used in edge detectors except that in this case it is \r\napplied to each row of the image and only take the magnitude of the pixels into \r\nconsideration. \r\n\r\nFigure \\ref{fig:non_maxima} shows the effect of applying non-maximum suppression \r\nto an input signal. \r\n\r\n\\begin{figure}\r\n\\centering\r\n\\includegraphics[width=100mm]{figures/non_maxima_suppression.png}\r\n\\caption{The effect of applying Non-Maximum Suppression to an input signal.}\r\n\\label{fig:non_maxima}\r\n\\end{figure}\r\n\r\n\\section{Connected Component}\r\nAfter obtaining the results from non-maxima suppression. The pixels that are\r\nclose to each other and are likely to belong to the same lane marking needs to\r\nbe connected. For this I've used the connected component labeling algorithm \r\n\\fullcite{ConnectedComponent} with slight modification. In the connected \r\ncomponent algorithm the connectivity is either 4-connected or 8-connected. \r\n\r\nIn the 4-connected, connected component labeling algorithm a point $p$ at \r\ncoordinate $(x,y)$ is considered connected if there is another point in it's 4 \r\nneighbors which are:\r\n$$(x+1, y),  (x-1, y), (x, y+1), (x, y-1)$$ \r\nIn the case of the 8-connected the four diagonals neighbors are taken into account as well.\r\n$$(x+1, y+1), (x+1, y-1), (x-1, y+1), (x-1, y-1)$$ \r\n \r\n \r\n\\begin{figure}\r\n \\centering\r\n \\begin{tabular}{c c}\r\n   \\includegraphics[width=100mm]{figures/connected_component1.png} &\r\n   \\includegraphics[width=60mm]{figures/pixel_for_connected_component.png} \\\\\r\n   (a) & (b) \\\\\r\n \\end{tabular}\r\n \\caption{Connectivity for Connected Component}\r\n \\label{fig:connected_component}\r\n\\end{figure}\r\n \r\nFigure \\ref{fig:connected_component}(b) shows a sample of road lane marking that \r\nneeds to be connected. It can be seen that a road lane marking will only have \r\none pixel at each row and the closest pixel belonging to the same marking will \r\nbe either on the rows above or below or both. Figure \r\n\\ref{fig:connected_component}(a) shows the connectivity used to connect the \r\nindividual pixels of the road lane marking. The wideness of the connectivity is \r\nto ensure that all pixel in the lane marking gets connected since the distance \r\nbetween any two neighboring pixel in the lane marking varies. \r\n\r\n\\section{Image Plane To Ground Plane Transformation}\r\nIn order to do further post processing the detected road lanes needs to be \r\ntransformed from the image plane to the ground plane (bird-eye view). \r\n\r\nEquation ~\\ref{eq:camera_eq} already describes the relationship between a point in \r\nthe image plane and a point in the real world. Assuming that the ground is flat \r\nwould result in $Z = 0$. Hence equation ~\\ref{eq:camera_eq} can be written as: \r\n\\begin{eqnarray*}\r\n\\begin{bmatrix}x\\\\y\\\\1\\end{bmatrix} & = & \r\n\\begin{bmatrix}\r\np_{11} & p_{12} & p_{13} & p_{14} \\\\\r\np_{21} & p_{22} & p_{23} & p_{24} \\\\\r\np_{31} & p_{32} & p_{33} & p_{34}\r\n\\end{bmatrix}\r\n\\begin{bmatrix}X\\\\Y\\\\0\\\\1\\end{bmatrix}\r\n\\end{eqnarray*}\r\n\\begin{eqnarray*}\r\n& = & \\begin{bmatrix}\r\n        p_{11} & p_{12} & p_{14} \\\\\r\n        p_{21} & p_{22} & p_{24} \\\\\r\n        p_{31} & p_{32} & p_{34}                                            \r\n\\end{bmatrix}\\begin{bmatrix}X\\\\Y\\\\1\\end{bmatrix}\\\\\r\n                                      & = & \r\n\\mathrm{H}\\begin{bmatrix}X\\\\Y\\\\1\\end{bmatrix}\r\n\\end{eqnarray*}\r\nTherefore in order to calculate the ground point we can take the inverse of and \r\nmultiply it with the image point. \r\n\\begin{eqnarray*}\r\n\\mathrm{H}^{-1} \\begin{bmatrix}x\\\\y\\\\1\\end{bmatrix} & = & \r\n\\begin{bmatrix}X\\\\Y\\\\1\\end{bmatrix}.\r\n\\end{eqnarray*}\r\n\r\n\\section{Estimating Consistent Lane Marking}\r\n\r\nEach lane marking is just a set of points, these points can be represented in \r\neither the image plane or the ground plane. The transformation was described in \r\nthe previous section. After transforming the lane marking to the ground plane. A \r\nsimple RANSAC line-fitting algorithm is applied to each lane marking this helps \r\nin removing any outliers that may be present in any lane marking. \r\n\r\n\\subsection{Lateral Distance Estimation}\r\nOn the roads they are both straight and curved lane marking. \r\nSometimes even straight lane marking appear as curved due to the orientation of \r\nthe camera. As of this writing I've assumed all lane marking on to be a line. \r\n\r\nIn order to find the lateral distance from the vehicle to each side \r\nof the lane all the dash lane marking that are consistent must be grouped \r\ntogether to form just one line. The following steps describes how consistent \r\nlane marking are grouped together. \r\n\r\n\\begin{enumerate}\r\n\\item Randomly select two lane marking.\r\n\\item If the two lane marking are not consistent, then repeat step 1.  Two lane marking $L_{1}$ and $L_{2}$ are considered consistent if the following \r\nconditions are met: \r\n\\[ \r\n\\left(|v_{1} \\cdot v_{2}| > \\theta_{1} \\right) \\textbf{ and }\r\n\\left(\\left|v_{1} \\cdot \\frac{P_{2} - P_{1}}{\\vectornorm{P_{2} - P_{1}}}\\right| \r\n> \\theta_{2} \\right) \\textbf{ and }\r\n\\left(\\left|v_{2} \\cdot \\frac{P_{2} - P_{1}}{\\vectornorm{P_{2} - P_{1}}}\\right| \r\n> \\theta_{3} \\right)\r\n\\] \r\nwhere $v_{1,2}$ are the normalized unit vector representing the line $L_{1,2}$ \r\nand $p_{1,2}$ is a point that is on the line $L_{1,2}$.\r\n\\item Estimate a line $l$ from the two lane marking found in step 2.\r\n\\item Using RANSAC find all the lane marking that are consistent with the line \r\n$l$ formed in the previous step. These consistent lane marking are the inliers \r\nof line $l$\r\n\\item Pick the set that contain the highest amount of inliers.  \r\n\\item Remove the inliers found in step 5. \r\n\\item Repeat step 1 until no two lane marking that are consistent with each \r\nother can be found. \r\n\\end{enumerate}\r\n\r\nOnce the set of inliers $\\mathrm{I} =\\{\\mathrm{I_{1}}, \\mathrm{I_{2}}, . . \r\n., \\mathrm{I_{n}}\\}$ where $\\mathrm{I_{i}}$ are consistent lane \r\nmarking are found. The distance to the left and right boundary of the lane is \r\ncalculated as follow: \r\n\\begin{enumerate}\r\n  \\item Split $\\mathrm{I}$ into $\\mathrm{I_{L}}$ and $\\mathrm{I_{R}}$ where $\\mathrm{I_{L}}$ contain inliers which has the closest lane marking on the left side of the origin. Similarly $\\mathrm{I_{R}}$ contain inliers which has the closest lane marking on the right side of the origin.\r\n  \\item Find the distance from the origin to each inliers in $\\mathrm{I_{L}}$ and $\\mathrm{I_{R}}$\r\n  \\item The  minimum distance to the left and right inliers are assumed to be the distance to the left and right boundary of the lane. \r\n\\end{enumerate}", "meta": {"hexsha": "8cd51337079faef7fcc2cc68ae0978855c02d65a", "size": 14660, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "backup/ch3.tex", "max_stars_repo_name": "zkan/dissertation", "max_stars_repo_head_hexsha": "458c5fce241973008bdcc3958bdf962b9197e593", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "backup/ch3.tex", "max_issues_repo_name": "zkan/dissertation", "max_issues_repo_head_hexsha": "458c5fce241973008bdcc3958bdf962b9197e593", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "backup/ch3.tex", "max_forks_repo_name": "zkan/dissertation", "max_forks_repo_head_hexsha": "458c5fce241973008bdcc3958bdf962b9197e593", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.908496732, "max_line_length": 287, "alphanum_fraction": 0.7031377899, "num_tokens": 4251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.34582063799634805}}
{"text": "%% LaTeX2e Template by Stephen Iota (https://stepheniota.com/)\n%% last updated: May 2019\n\\documentclass[11pt]{article}\n\\usepackage[margin=2.5cm]{geometry}\n\\usepackage[utf8]{inputenc}\n\\usepackage{amsmath,amssymb,amsthm,physics}\n\\usepackage{mathtools} % for boxed answers in align environments\n\\usepackage{cancel}\n\\usepackage{graphicx}\n%\\usepackage[shortlabels]{enumitem} % change labels in enum/item environments\n\\usepackage[labelfont=bf,font=small]{caption}\n\\usepackage[dvipsnames]{xcolor}\n%\\usepackage[big]{titlesec} % [small,medium,big]\n\\usepackage{fancyhdr} %http://tug.ctan.org/tex-archive/macros/latex/contrib/fancyhdr/fancyhdr.pdf\n%\\usepackage[noadjust]{cite}\n%\\usepackage{lipsum}\n\\usepackage[\n\tcolorlinks=true,\n\tcitecolor=NavyBlue!90!black,\n\tlinkcolor=green!50!black,\n\turlcolor=RoyalBlue,\n\thypertexnames=false]{hyperref}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% My commands & environments %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\newcommand{\\email}[1]{\\texttt{\\href{mailto:#1}{#1}}}\n\\renewcommand{\\d}[1]{\\ensuremath{\\operatorname{d}\\!{#1}}}\n%\\newcommange{\\ave}[1]{\\ensuremath{\\langle {#1} \\rangle}}\n\n%\\newenvironment{question}[0]{\n%\\bigbreak\n%\\noindent\n%}\n\\theoremstyle{definition}\n\\newtheorem{question}{Part}[section]\n\\newtheorem*{solution}{Solution}\n%\\newenvironment{solution}[0]{\n%\\bigbreak\n%\\noindent\n%\\textbf{Solution:}\n%}\n\n%%%%%%%%%%%%%%%%%%\n%% Front Matter %%\n%%%%%%%%%%%%%%%%%%\n\\pagestyle{fancy}\n\\fancyhead[L]{\\footnotesize{\\leftmark}}\n\\fancyhead[C]{}\n\\fancyhead[R]{\\footnotesize{ IOTA \\textbf{\\thepage}}}\n\\fancyfoot[L,C,R]{}\n\\thispagestyle{plain} % no hf on first page\n%\\pagenumbering{gobble} % no page numbers\n%\\setcounter{section}{-1}\n\\graphicspath{{figures/}} % set directory for figures\n\\numberwithin{equation}{section}\n\\numberwithin{figure}{section}\n\n\n%%%%%%%%%%%%%\n%%% Title %%%\n%%%%%%%%%%%%%\n\\begin{document}\n\n\\begin{center}\n{\\LARGE \\textsc{Statistical Mechanics}: \\textbf{Final Exam}}\n\\end{center}\n\\bigbreak\n\n%%%%%%%%%%\n%% INFO %%\n%%%%%%%%%%\n\\begin{tabular}{rl}\n\\textsc{Name}:&\t\tStephen Iota (\\email{siota001@ucr.edu})\n\\\\\n\\textsc{Course}:&\t\tPhysics 133 (Spring 2019), Prof.~Kuhlman\n\\\\\n\\textsc{Date}:&\t\t\\today\n\\end{tabular}\n\\bigbreak\n\n\n\n%%%%%%%%%%%%%%\n%% PROBLEMS %%\n%%%%%%%%%%%%%%\n\n\\noindent\nSethna problems 2.1, 3.11, 5.2, 5.10, 7.3 and \\textbf{An unlikely event}. Final answers are \\boxed{\\text{boxed}}.\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% RANDOM WALKS IN GRADE SPACE %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Random walks in grade space}\nConsider a multiple-choice exam with ten questions of ten points each. Each problem on the exam is equally difficult. Students score a mean of $70$ on the exam. Assume all students are identical, and each question is answered at random with a probability of $0.7$ of being correct.\n\n%%%%%%%%%%%%\n%% PART A %%\n%%%%%%%%%%%%\n\\begin{question}\n\\textbf{(a)}~What is the expected mean and standard deviation for the exam?\n\\end{question}\n\n\\begin{solution}\nLet $p_+ = 0.7$ be the probability of a correct answer and $1 - p_+ = p_-$ be the probability of an incorrect answer; let $s \\in \\mathbb{S}$ be an exam score of a student in the set $\\mathbb{S}$ of all possible student scores, and let $N$ be the number of questions on the exam. The mean score $\\expval{s}$ is given by\n\\begin{equation}\n\\expval{s_N} = \\sum_{n = 0}^N \\binom{N}{n} \\ (N-n)p_-\\cdot(N-n)p_+\\cdot10n \\ \\text{pts}\n\\end{equation}\nand the rms score $\\expval{s^2}$is\n\\begin{equation}\n\\expval{s_N^2} = \\sum_{n = 0}^N \\binom{N}{n} \\ (N-n)p_-\\cdot(N-n)p_+\\cdot10n \\ \\text{pts}^2.\n\\end{equation}\nStandard deviation $\\sigma$ is related to the mean and rms by\n\\begin{equation}\n\\sigma = \\sqrt{\\expval{s^2} - \\expval{s}^2}.\n\\end{equation}\n\nFirst lets consider $N = 1$ questions on the exam. The mean, rms and std dev in this case are\n\\begin{align}\n\\expval{s_1} &= p_+(10 \\ \\text{pts}) = 7 \\ \\text{pts}\n\\\\\n\\expval{s_1^2} &= p_+(10 \\ \\text{pts})^2 = 70 \\ \\text{pts}\n\\\\\n\\sigma &= \\sqrt{70 - 7^2} = \\sqrt{21} \\ \\text{pts}\n\\end{align}\nWe can use the properties of random walks to see the evolution of these parameters as the number of questions on the exam $N$ increases. The mean score $\\expval{s_N}$ will be $7N$ pts. The std dev scales by $\\sqrt{N}$. This means that $\\sigma_N = \\sqrt{21N}$ pts.\n\nFor an exam of 10 questions, we find a mean of 10 pts and std dev of $\\sqrt{210}$.\n\\begin{align}\n\\Aboxed{\\expval{s_{10}} &= 10 \\ \\text{pts}}\n\\\\\n\\Aboxed{\\expval{s_{10}^2} &= \\sqrt{210} \\ \\text{pts} \\approx 14.5 \\ \\text{pts}}\n\\end{align}\n\\end{solution}\n\n\n\\newpage\n%%%%%%%%%%%%\n%% PART B %%\n%%%%%%%%%%%%\n\\begin{question}\n\\textbf{(b)}~A typical exam with mean 70 might have an observed std dev of about 15. What physical interpretation do you make of the ratio of the random standard deviation and the observed one?\n\\end{question}\n\n\\begin{solution}\nFor a completely random model with 10 questions, the mean score is $\\expval{s} = 50$ pts and the std dev is $\\sigma_\\text{random} = \\sqrt{250}$.\n\\begin{equation}\n\\frac{\\sigma}{\\sigma_\\text{random}} = \\frac{\\sqrt{210}}{\\sqrt{250}} \\approx \\frac{14.5}{15.8} \\approx 0.92\n\\end{equation}\nStudents in our model have a smaller spread of scores than in a completely random model. In our model, we made our students ``smarter.'' In a real exam setting, students rarely randomly guess on all questions. They have a higher probability of getting each question correct, which is why our model is slightly more accurate than the random model.\n\\end{solution}\n\n\n\n\n\n\n\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%\n%% Maxwell Relations %%\n%%%%%%%%%%%%%%%%%%%%%%%\n\\newpage\n\\section{Maxwell relations}\n\nConsider the microcanonical formula for the equilibrium energy $E(S,V,N)$ of some general system. One knows that the second derivatives of energy are symmetric; at fixed $N$, we get the same answer whichever order we take partial derivatives with respect to $S$ and $V$.\n\n\\begin{question}\n\\textbf{(a)} Use this to show the Maxwell relation\n\\begin{equation}\n\\pdv{T}{V}\\eval_{S,N} = - \\pdv{P}{S}\\eval_{V,N}.\\label{eq:2.0}\n\\end{equation}\nGenerate two other similar formul{\\ae} by taking other second partial derivatives of $E$.\n\\end{question}\n\n\\begin{solution}\nConsider the fundamental thermodynamic relation\n\\begin{equation}\n\\d{E} = T\\d{S} - P\\d{V} + \\mu\\d{N}.\n\\end{equation}\nKeeping $N$ constant, take the following derivatives.\n\\begin{align}\n\\pdv{E}{V}\\eval_{S,N} &= -P\n\\\\\n\\pdv{S}\\eval_{V,N} \\pdv{E}{V}\\eval_{S,N} &= - \\pdv{P}{S}\\eval_{V,N}\\label{eq:2.1}\n\\end{align}\nSince the second derivative of energy is symmetric, we can switch the order of integration in the second step.\n\\begin{align}\n\\pdv{V}\\eval_{S,N} \\pdv{E}{S}\\eval_{V,N} &= \\pdv{T}{S}\\eval_{V,N}\\label{eq:2.2}\n\\end{align}\nFrom eq.~\\eqref{eq:2.1} and \\eqref{eq:2.2}, it follows that\n\\begin{equation}\n\\boxed{\\pdv{T}{V}\\eval_{S,N} = - \\pdv{P}{S}\\eval_{V,N}.}\n\\end{equation}\n\nUsing the same recipe, we can construct more Maxwell relations. Another relationship is given by taking partials of energy with respect to volume and number of particles.\n\\begin{align}\n\\pdv{E}{V}\\eval_{S,N} &= -P\n\\\\\n\\pdv{N}\\eval_{S,V} \\pdv{E}{V}\\eval_{S,N} &= -\\pdv{P}{N}\\eval_{S,V}\n\\\\\n\\pdv{V}\\eval_{S,N} \\pdv{E}{N}\\eval_{S,V} &= \\pdv{\\mu}{N}\\eval_{S,V}\n\\\\\n\\Aboxed{\\pdv{\\mu}{V}\\eval_{S,N} &= -\\pdv{P}{N}\\eval_{S,V}}\n\\end{align}\nAnother one by differentiating energy by entropy and number of particles.\n\\begin{align}\n\t\\pdv{E}{S}\\eval_{V,N} &= T\n\t\\\\\n\t\\pdv{N}\\eval_{S,V} \\pdv{E}{S}\\eval_{V,N} &= -\\pdv{T}{N}\\eval_{S,V}\n\t\\\\\n\t\\pdv{S}\\eval_{V,N} \\pdv{E}{N}\\eval_{S,V} &= \\pdv{\\mu}{S}\\eval_{V,N}\n\t\\\\\n\t\\Aboxed{\\pdv{T}{N}\\eval_{S,V} &= \\pdv{\\mu}{S}\\eval_{V,N}}\n\\end{align}\n\\end{solution}\n\n\\begin{question}\n\\textbf{(b)}~Statistical mechanics check of the Maxwell relation. Using\n\\begin{equation}\nS(E,V,N) = \\frac{5}{2} Nk_B + Nk_B\\log\\Bigg[\\frac{V}{Nh^3}\\bigg( \\frac{4\\pi m E}{3N} \\bigg)^{3/2}\\Bigg]\\label{eq:2b1}\n\\end{equation}\nderive formul{\\ae} for $E(S,V,N)$, $T(S,V,N) = (\\pdv*{E}{S})|_{V,N}$, and $P(S,V,N) = -(\\pdv*{E}{V})|_{S,N}$ for the ideal gas. Show explicitly that eq.~\\eqref{eq:2.0} is satisfied.\n\\end{question}\n\n\\begin{solution}\nTo find $E(S,V,N)$, rearrange eq.~\\eqref{eq:2b1}.\n\\begin{align}\n\\log\\Bigg[\\frac{V}{Nh^3}\\bigg( \\frac{4\\pi m E}{3N} \\bigg)^{3/2}\\Bigg] &= \\frac{S}{Nk_B} - \\frac{5}{2}\n\\\\\n\\frac{V}{Nh^3}\\bigg( \\frac{4\\pi m E}{3N} \\bigg)^{3/2} &= \\exp(\\frac{S}{Nk_B} - \\frac{5}{2})\n\\\\\n\\bigg( \\frac{4\\pi m E}{3N} \\bigg)^{3/2} &= \\frac{Nh^3}{V} \\exp(\\frac{S}{Nk_B} - \\frac{5}{2})\n\\\\\n\\frac{4\\pi m E}{3N} &= \\Big( \\frac{Nh^3}{V} \\Big) ^{2/3} \\exp(\\frac{2}{3}\\frac{S}{Nk_B} - \\frac{5}{3})\n\\\\\n\\Aboxed{E &= \\frac{3N}{4\\pi m} \\Big( \\frac{Nh^3}{V} \\Big) ^{2/3} \\exp(\\frac{2}{3}\\frac{S}{Nk_B} - \\frac{5}{3})}\\label{eq:2b2}\n\\end{align}\n\nTo find an expression for $T(S,V,N)$, take the derivative of eq.~\\eqref{eq:2b2} with respect to $S$, keeping $V,N$ constant.\n\\begin{align}\nT(S,V,N) &= \\pdv{E}{S}\\eval_{V,N}\n\\end{align}\n\\begin{align}\n\\begin{aligned}\n\\pdv{E}{S} &= \\pdv{S} \\frac{3N}{4\\pi m} \\Big( \\frac{Nh^3}{V} \\Big) ^{2/3} \\exp(\\frac{2}{3}\\frac{S}{Nk_B} - \\frac{5}{3}) \\eval_{V,N}\n\\\\\n&= \\frac{3N}{4\\pi m} \\Big( \\frac{Nh^3}{V} \\Big) ^{2/3} \\pdv{S} \\exp(\\frac{2}{3}\\frac{S}{Nk_B} - \\frac{5}{3}) \\eval_{V,N}\n\\\\\n&= \\frac{3N}{4\\pi m} \\Big( \\frac{Nh^3}{V} \\Big) ^{2/3} \\exp(\\frac{2}{3}\\frac{S}{Nk_B} - \\frac{5}{3}) \\pdv{S} \\frac{2}{3}\\frac{S}{Nk_B} \\eval_{V,N}\n\\\\\n&= \\frac{1}{2k_B\\pi m} \\Big( \\frac{Nh^3}{V} \\Big) ^{2/3} \\exp(\\frac{2}{3}\\frac{S}{Nk_B} - \\frac{5}{3})\n\\end{aligned}\n\\end{align}\n\\begin{align}\n\\Aboxed{T(S,V,N) &= \\frac{1}{2k_B\\pi m} \\Big( \\frac{Nh^3}{V} \\Big) ^{2/3} \\exp(\\frac{2}{3}\\frac{S}{Nk_B} - \\frac{5}{3})}\\label{eq:2bT}\n\\end{align}\n\nNext, let's find an expression for $P(S,V,N)$.\n\\begin{equation}\nP(S,V,N) = -\\pdv{E}{V}\\eval_{S,N}\n\\end{equation}\n\\begin{align}\n\t\\begin{aligned}\n\\pdv{E}{V}\\eval_{S,N} &= - \\pdv{V} \\frac{3N}{4\\pi m} \\Big( \\frac{Nh^3}{V} \\Big) ^{2/3} \\exp(\\frac{2}{3}\\frac{S}{Nk_B} - \\frac{5}{3}) \\eval_{S,N}\n\\\\\n&= - \\frac{3N}{4\\pi m} \\exp(\\frac{2}{3}\\frac{S}{Nk_B} - \\frac{5}{3}) \\pdv{V} \\Big( \\frac{Nh^3}{V} \\Big) ^{2/3} \\eval_{S,N}\n\\\\\n&= \\frac{1}{2}\\frac{N^2h^3}{\\pi m V^2} \\Big( \\frac{V}{Nh^3} \\Big)^{1/3} \\exp(\\frac{2}{3}\\frac{S}{Nk_B} - \\frac{5}{3})\n\\end{aligned}\n\\end{align}\n\\begin{equation}\n\\boxed{P(S,V,N) = \\frac{1}{2}\\frac{N^2h^3}{\\pi m V^2} \\Big( \\frac{V}{Nh^3} \\Big)^{1/3} \\exp(\\frac{2}{3}\\frac{S}{Nk_B} - \\frac{5}{3})}\\label{eq:2bP}\n\\end{equation}\n\nNow, we can show that eq.~\\eqref{eq:2.0} is valid. First take the derivative of eq.~\\eqref{eq:2bT} with respect to volume.\n\\begin{equation}\n\\begin{aligned}\n\\pdv{T}{V}\\eval_{S,N} &= \\pdv{V} \\frac{1}{2k_B\\pi m} \\Big( \\frac{Nh^3}{V} \\Big) ^{2/3} \\exp(\\frac{2}{3}\\frac{S}{Nk_B} - \\frac{5}{3}) \\eval_{S,N}\n\\\\\n&= \\frac{1}{2k_B\\pi m} \\exp(\\frac{2}{3}\\frac{S}{Nk_B} - \\frac{5}{3}) \\pdv{V} \\Big( \\frac{Nh^3}{V} \\Big) ^{2/3}\n\\\\\n&= - \\frac{1}{3} \\frac{1}{k_B\\pi m} \\Big(\\frac{V}{Nh^3} \\Big)^{1/3} \\Big( \\frac{Nh^3}{V^2} \\Big) \\exp(\\frac{2}{3}\\frac{S}{Nk_B} - \\frac{5}{3}) \\label{eq:2c}\n\\end{aligned}\n\\end{equation}\nNow, take the derivative of eq.~\\eqref{eq:2bT} with respect to $S$.\n\\begin{equation}\n\\begin{aligned}\n\\pdv{P}{S}\\eval_{V,N} &= \\pdv{S} \\frac{1}{2k_B\\pi m} \\Big( \\frac{Nh^3}{V} \\Big) ^{2/3} \\exp(\\frac{2}{3}\\frac{S}{Nk_B} - \\frac{5}{3}) \\eval_{V,N}\n\\\\\n&= \\frac{1}{2k_B\\pi m} \\Big( \\frac{Nh^3}{V} \\Big) ^{2/3}  \\pdv{S} \\exp(\\frac{2}{3}\\frac{S}{Nk_B} - \\frac{5}{3}) \\eval_{V,N}\n\\\\\n&= \\frac{1}{3} \\frac{Nh^3}{\\pi m V^2k_B} \\Big( \\frac{V}{Nh^3} \\Big)^{1/3}  \\exp(\\frac{2}{3}\\frac{S}{Nk_B} - \\frac{5}{3})\n\\\\\n&= \\frac{1}{3} \\frac{1}{k_B\\pi m} \\Big(\\frac{V}{Nh^3} \\Big)^{1/3} \\Big( \\frac{Nh^3}{V^2} \\Big) \\exp(\\frac{2}{3}\\frac{S}{Nk_B} - \\frac{5}{3}) \\label{eq:2d}\n\\end{aligned}\n\\end{equation}\n\nWe find that eq.~\\eqref{eq:2c} is equal to negative eq.~\\eqref{eq:2d}, thus proving the Maxwell relation eq.~\\eqref{eq:2.0}. $\\qedhere$\n\\end{solution}\n\n\n\n\n\n\n\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Burning information and Maxwellian demons %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\newpage\n\\section{Burning information and Maxwellian demons}\n\n\\begin{figure}[p]\n\\centering\n\\includegraphics[width=0.4\\linewidth]{Final_Fig1}\n\\caption{Minimalist digital memory tape.\\label{fig:tape}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\centering\n\\includegraphics[width=0.4\\linewidth]{Final_Fig2}\n\\caption{Expanding piston.\\label{fig:piston}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\centering\n\\includegraphics[width=0.4\\linewidth]{Final_Fig3}\n\\caption{Information-burning engine.\\label{fig:engine}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\centering\n\\includegraphics[width=0.4\\linewidth]{Final_Fig4}\n\\caption{Pistons resetting a \\textit{known} bit for free.\\label{fig:zero}}\n\\end{figure}\n\n\nIs there a minimum energy cost for taking a measurement? Let's try to find out. We start by addressing the connection between information entropy and thermodynamic entropy. Can we burn information as fuel?\n\nConsider a really frugal digital memory tape, with one atom used to store each bit (fig~\\ref{fig:tape}). The tape is a series of boxes, with each box containing one ideal gas atom. The box is split into two equal pieces by a removable central partition. If the atom is in the top half of the box, the tape reads one; else the tape reads zero. The side walls are frictionless pistons that may be used to push the atom around.\n\n\\emph{If} we know the atom position in the $n$th box, we can move the other side wall in, remove the partition, and gradually retract the piston to its original position (fig~\\ref{fig:piston})--destroying our information about where the atom is, but extracting useful work.\n\n\\begin{question}\n\\textbf{(a)~Burning the information.} Assuming the gas expands at a constant temperature $T$, how much work $\\int P\\d{V}$ is done by the atom as the piston retracts?\n\\end{question}\n\n\\begin{solution}\nThis is an isothermal process; $T$ and $N$ are constant. Work in thermodynamic processes is given by $\\int P\\d{V}$, where $P = Nk_BT/V$. Before the piston retracts, $P_iV_i$ is equal to $Nk_BT$. We make this substitution in the integral. Finally we integrate to find the magnitude of the result. The final answer is \\emph{negative}; work is being done \\emph{by} the environment \\emph{on} the atom and gas.\n\\begin{align}\n\\begin{aligned}\nW& = - \\int_{V_i}^{V_f} P \\d{V}\n= - P_iV_i \\int_{V_i}^{V_f} \\frac{\\d{V}}{V}\n\\\\\n& = \\boxed{P_iV_i \\log \\! \\Bigg[ \\frac{V_i}{V_f} \\Bigg]}\\label{eq:work}\n\\end{aligned}\n\\end{align}\n\\end{solution}\n\n\\newpage\n\\begin{question}\n\\textbf{(b)~Rewriting a bit.} Give a sequence of particle insertion, partition removal, and adiabatic side-wall motions that will reversibly convert a bit zero into a bit one, with no net work done on the system.\n\\end{question}\n\n\\begin{solution}\n~\n\\\\\n\\begin{enumerate}\n\\item Place the atom into the bottom half of the partitioned box. Our bit is now in state zero.\n\n\\item Adiabatically snap the top piston down to the position of the partition. Atom still bit zero. There is no time for heat transfer; entropy gain zero. This motion costs us work $W_1$ equal to what we calculated in part \\textbf{(a)} (eq.~\\ref{eq:work}).\n\n\\item Remove the partition from underneath the top piston and place it just above the bottom piston. The atom is now in the ``top'' part of the box (bit one).\n\n\\item Adiabatically snap the bottom piston down the same distance the top piston traveled; the volume of the box is now back to the initial value. The atom is in bit one state. This work done by the atom $W_2$ is equal to $-W_1$, thus we have successfully changed to atom from bit zero to bit one with zero net work done on the system.\n\\end{enumerate}\n\\end{solution}\n\n\\begin{question}\n\\textbf{(c)~Forgetting a bit.} Suppose the atom location in the $n$th box is initially known. What is the change in entropy, if the partition is removed and the available volume doubles? Give both the thermodynamic entropy and the information entropy\n\\end{question}\n\n\\begin{solution}\n\\textit{Thermodynamic entropy.} If we define thermodynamic entropy change to be the ratio of heat flow to temperature, we can argue $\\Delta S_\\text{thermo} = 0$ if we double the volume by adiabatically drawing the pistons back. In addition, it is difficult to define temperature for a single atom. However, we can still think of $\\Delta S_\\text{thermo}$ as entropy change of mixing.\n\nWe can write down the entropy of mixing as\n\\begin{align}\nS& = k_B \\log \\Omega \\label{eq:S},\n\\end{align}\nwhere $\\Omega$ is the configurational energy-shell volume. For $N$ atoms in a box, the number of configurations in a volume $V$ is given by $V^N/N!$. Thus for our atom in a box, $\\Omega_i = V$ and $\\Omega_f = 2\\Omega_i$\n\\begin{align}\n\\Aboxed{\\Delta S_\\text{thermo} & = S_f - S_i = k_B \\log \\frac{\\Omega_f}{\\Omega_i} = k_B \\log 2} \\label{eq:DSthermo}\n\\end{align}\n\n\\textit{Information entropy.} We can write down information entropy generally as\n\\begin{align}\nS_\\text{info} & = - k_S \\sum_k p_k \\log p_k = - \\sum_k p_k \\log_2 p_k\\label{eq:Sinfo},\n\\end{align}\nwhere $p_k$ is the probability of each possible state $k$ of a bit. Before the volume is doubled, we already know the position of the atom in the box. Suppose we know it is in a bit zero state. The initial probability of the atom being in bit zero state is one; probability of bit one state is zero. Once we remove the partition and double the volume, we lose information about the atom's state. Each state becomes equally probable. We use this change in probabilities to write down $\\Delta S_\\text{info}$.\\footnote{eqs.~\\eqref{eq:DSthermo} \\& \\eqref{eq:DSinfo} differ by nothing more than a normalization factor. We write thermodynamic entropy in units of energy per temperature, hence the Boltzmann factor $k_B$. When speaking about the entropy of bits, it makes more sense to present our results in base 2.}\n\\begin{align}\nS_i &= -k_S \\cdot(1) \\cdot \\log 1 = 0\n\\\\\nS_f &= -k_S \\cdot(2) \\cdot \\frac{1}{2} \\log \\frac{1}{2} = \\log_2{2}\n\\\\\n\\Aboxed{\n\\Delta S_\\text{info}  &= S_f - S_i = k_S \\log{2} = 1}\\label{eq:DSinfo}\n\\end{align}\n\\end{solution}\n\n\\begin{question}\n\\textbf{(d)~Demonic states.} What prevents a Maxwellian demon from using an atom in an unknown state to extract work? The demon must first measure which side of the box the atom is on; this measurement needs no energy expenditure. (i) After the bit has been burned (see fig~\\ref{fig:engine}), is the demon in a known state?\\footnote{The demon can be thought of as a two-state system (e.g.~another partitioned box). If the demon starts in a known state, one can copy the state of the box into the demon with no cost in entropy or energy, by adiabatically turning on an appropriate coupling. The demon has now measured the atom position, and can extract work from the pistons.}\n(ii) What is its entropy? (iii) How much energy would it take to return the demon to its original state, at temperature T? (iv) Is the second law violated?\n\\end{question}\n\n\\begin{solution}\n~\\\\\n\\begin{enumerate}\n\\item[(i)] \\boxed{\\text{Yes,}} after the bit has been burned, the demon is in a known state. The information from the bit has been copied to the demon prior to the bit's burning-for-work.\n\n\\item[(ii)] Burning the bit, however, costs us entropy. Initially the bit was in a low entropy state. The cost of ``forgetting a bit'' is given by $\\boxed{k_B \\log{2}}$ (see eqs.~\\ref{eq:DSthermo} \\& \\ref{eq:DSinfo}).\n\n\\item[(iii)] It would take \\boxed{0} energy to return the demon to its original state, at temperature $T$. Its original state was a random state. We can wipe a bit by removing the partition and moving both pistons adiabatically in the same direction for a certain distance (see fig~\\ref{fig:zero}).\n\n\\item[(iv)] The Second Law of Thermodynamics states that the entropy of a closed system never decreases over time. This law is \\boxed{\\text{not violated.}} We can extract an unlimited amount of work with a demon by copying information from one bath to another. However, whenever we take energy from a bath, we have to pay for it with entropy. This is a fundamental truth about the Universe.\n\\end{enumerate}\n\\end{solution}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% ENTROPY INCREASES: DIFFUSION %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\newpage\n\\section{Entropy increases: diffusion}\n\nEntropy technically does not increase for a closed system. However, in most of the coarse-grained theories, entropy does increase; when we integrate out degrees of freedom, we provide a means for the information about the initial conditions to be destroyed.\n\nLet $\\rho(x,t)$ obey the one-dimensional diffusion equation $\\pdv*{\\rho}{t} = D\\pdv*[2]{p}{x}$. Assume that the density $\\rho$ and all its gradients die away rapidly at $x = \\pm \\infty$.\\footnote{Also, assume $\\pdv*[n]{\\rho}{x} \\log{\\rho}$ goes to zero at $x = \\pm \\infty$, even though $\\log{\\rho}$ goes to $-\\infty$.}\n\n\\begin{question}\nDerive a formula for the time derivative of the entropy $S = -k_B \\int \\rho(x)\\log{\\rho(x)} \\d{x}$ and show that it is strictly increasing in time.\n\\end{question}\n\n\n\n\\begin{solution}\nWe start by taking the time derivative of the definition of entropy.\n\\begin{align}\nS &= -k_B \\int_{\\text{all space}} \\rho \\log{\\rho} \\d{x}\n\\\\\n\\pdv{S}{t} &= -k_B \\int \\dot{\\rho} \\log{\\rho} + \\dot{\\rho} \\d{x}\n\\end{align}\nSince $\\rho$ obeys the diffusion equation, we can make the following substitution.\n\\begin{align}\n\\dot{S} &= -Dk_b \\int \\rho'' \\log{\\rho} + \\rho'' \\d{x}\n\\\\\n\\dot{S} &= -Dk_B \\bigg[\\cancelto{0}{\\rho'\\eval_{-\\infty}^{\\infty}} + \\int  \\rho'' \\log{\\rho} \\d{x}\\bigg]\n\\\\\n\\dot{S} &= -Dk_B \\int \\rho'' \\log{\\rho} \\d{x}\n\\end{align}\nThe $\\rho''$ term dies out when integrated over all space because we are assuming the probability density and all its gradients die out at the boundaries.\n\nNext, we will try to get the remaining integrand into a form that is always positive. We will use the \\textsc{di} method for integration by parts.\n\n\\begin{center}\n\\begin{tabular}{lrl}\n\t\t& \tD\t\t& \tI\n\\\\\n+\t\t&\t\t$\\log{\\rho}$\t\t&\t\t$\\rho''$\n\\\\\n-\t\t&\t\t$\\frac{1}{\\rho}\\rho'$\t\t&\t\t$\\rho'$\n\\end{tabular}\n\\end{center}\n\\begin{align}\n\\dot{S} &= -Dk_B \\int \\rho'' \\log{\\rho} \\d{x} = -Dk_B \\bigg[ \\cancelto{0}{\\rho'\\log{\\rho}\\eval_{-\\infty}^{\\infty}} - \\int \\frac{(\\rho')^2}{\\rho} \\d{x}    \\bigg]\n\\end{align}\nAfter integrating by parts, our first term dies again because of our initial assumption regarding the probability density (see footnote). We are left with the following integrand.\n\\begin{equation}\n\\dot{S} = Dk_B \\int \\frac{(\\rho')^2}{\\rho} \\d{x}\\label{eq:4.0}\n\\end{equation}\nWe cannot evaluate this integral, but we don't need to. First, consider the $1/\\rho$ term. $\\rho(x,t) \\in [0,1]$ is a probability density, it cannot physically be negative. Next, consider the $(\\rho')^2$ term. The square of any number is always positive. So although we do not know what $\\rho'$ looks like, we only care about its square. Therefore, we know that the integrand in eq.~\\eqref{eq:4.0} will always be positive for all values of $x$ that we are integrating over.\n\nWe can confidently say that the time derivative of entropy is always increasing.\n\\begin{align}\n\\Aboxed{\n\\pdv{S}{t} &\\geq 0}\n\\end{align}\n\\end{solution}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% PHASE SPACE UNITS AND THE ZERO OF ENTROPY %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\newpage\n\\section{Phase-space units and the zero of entropy}\n\nIn classical mechanics, entropy goes to minus infinity at the temperature is lowered to zero. In quantum mechnics the entropy per particle goes to zero, because states are quantized and the ground state is the only one populated.\n\nThe classical phase-space shell volume $\\Omega(E)\\var E$ has units of ([momentum]$\\cdot$[distance])$^{3N}$. We can make it unitless with Planck's constant $h^{3N}$; if we measure phase-space volume in units of $h$ per dimension, $\\Omega(E)\\var E$ will be dimensionless. Of course, the correct dimension could be a constant times $h$, like $\\hbar \\ldots$\n\n\\begin{question}\n\\textbf{(a)}~\\textbf{Arbitrary zero of the classical entropy.} Show that the width of the energy shell $\\var E$ in the definition of $\\Omega(E)$ does not change the microcanonical entropy per particle\n\\begin{equation}\nS/N = k_B\\log{\\Omega(E})/N\\label{eq:5.0}\n\\end{equation}\nin a large system. Show that the choice of units in phase space does change the classical entropy per particle.\n\\end{question}\n\n\\begin{solution}\nThe definition of classical phase-space is\n\\begin{equation}\n\\Omega(E) = \\frac{1}{\\var E}\\int_{H < E < H+ \\var E } \\d{\\mathbb{P}} \\d{\\mathbb{Q}}\n\\end{equation}\nFor our ensemble, we assume particles are non-interacting, so we do not have to integrate over configurations $\\mathbb{Q}$. The integral over momenta $\\mathbb{P}$ is equal to the difference in volumes of $3N$ dimensional spheres of radii $\\sqrt{2m(E + \\delta E)}$ and $\\sqrt{2mE}$. When we take the logarithm of the different of phase-space volumes for each sphere, we find that the exponents are eliminated thanks to the nifty properties of logarithms, and the $\\var E$'s cancel out.\n\\begin{align}\n\\Omega(E) &= \\frac{1}{\\var E} \\frac{\\pi^{3N/2}}{(3N/2)!} \\Bigg[ (2m(E + \\delta E))^{3N/2} -  (2mE)^{3N/2}\\Bigg]\n\\\\\nS &= k_B \\log(\\frac{1}{\\var E} \\frac{\\pi^{3N/2}}{(3N/2)!} \\Bigg[ (2m(E + \\delta E))^{3N/2} -  (2mE)^{3N/2}\\Bigg])\n\\\\\n&= k_B \\Bigg[ \\log{\\frac{\\pi^{3N/2}}{(3N/2)!}} + 3N/2\\log( 2m(E + \\var E) - 2mE) - \\log(\\var E)   \\Bigg]\n\\\\\nS/N &= k_B \\Bigg[ \\frac{1}{N} \\log{\\frac{\\pi^{3N/2}}{(3N/2)!}} + 3/2\\log{2m} + 3/2\\log{\\var E} -\\log{\\var E}    \\Bigg]\n\\end{align}\nThe value of $1/2 \\log{\\var E}$ is very small, so in the end we have shown that $S/N$ is independent of $\\var E$.\n\nHowever, if we chose the normalize our phase-space volume with $h^{3N}$ or $\\hbar^{3N}$, we would get a different result. Therefore, choice of units in phase-space does matter.\n\\end{solution}\n\n\n\n\\begin{question}\n\\textbf{(b)}~\\textbf{Phase-space density of states for a  particle in a one-dimensional box.} Show, or note, that the quantum momentum-space density of states for a free quantum particle in a one-dimensional box of length $L$ with periodic boundary conditions is $L/h$. Draw a picture of the classical phase space of this box $(p,x)$, and draw a rectangle of length $L$ for each quantum eigenstate. Is the phase-space area per eigenstate equal to $h$, as assumed?\n\\end{question}\n\n\\begin{solution}\nIn quantum mechanics, energy states are quantized. The energy eigenstates for a 1-$D$ particle in a box are $E_n = \\frac{n^2 h^2}{8m^2 L^2}$. Therefore, the momentum per eigenstate are $p_n = \\frac{nL}{2L}$. Taking into account the periodic boundary conditions (accounts for the factor of 2), we find that the phase space volume is indeed $L/h$.\n\\begin{figure}[h!]\n\\centering\n\\includegraphics[width=.3\\linewidth]{Final_Fig5}\n\\caption{Phase-space volume of a 1-D particle in a box.}\n\\end{figure}\nThe phase-space volume per eigenstate is indeed equal to $h$.\n\\end{solution}\n\n\n\\begin{question}\n\\textbf{(c)}~\\textbf{Phase-space density of states for $N$ particles in a box.} Show that the density of states for $N$ free particles in a cubical box of volume $V$ with periodic boundary conditions is $V^N/h^{3N}$, and hence that the phase-space volume per state is $h^{3N}$.\n\\end{question}\n\n\\begin{solution}\nThe energy eigenstates are given by $E_{nx,ny,nz} = \\frac{\\hbar^2 \\vb{k}^2}{2m}$ and we find that each 3D wave vector is given by\n$k = \\frac{n_x \\pi}{L} + \\frac{n_y \\pi}{L} + \\frac{n_z \\pi}{L}$. Therefore the phase space volume for one particle is given by $V/h^3$. If we have $N$ particles in a box, each occupies a respective volume, so we take our answer and raise it to the power of $N$. The phase-space volume then turns out to be $V^N/h^{3N}$, and the volume per state is $h^{3N}$.\n\\end{solution}\n\n\n\\begin{question}\n\\textbf{(d)}~\\textbf{Phase-space density of states for a harmonic oscillator.} Consider a harmonic oscillator with Hamiltonian $\\mathcal{H} = p^2/2m + 1/2 mw^2q^2$. Draw a picture of the energy surface with energy $E$, and find the volume of phase space enclosed. What is the volume per energy state?\n\\end{question}\n\n\\begin{solution}\nFor a fixed energy, the phase-space volume turns out to be elliptical. The volume (or rather area) is given by $\\pi p x$.\n\n\\begin{figure}[h!]\n\t\\centering\n\t\\includegraphics[width=.3\\linewidth]{Final_Fig6}\n\t\\caption{Phase-space volume of a quantum harmonic oscillator with energy $E$.}\n\\end{figure}\n\n\\end{solution}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%\n%% AN UNLIKELY EVENT %%\n%%%%%%%%%%%%%%%%%%%%%%%\n\\newpage\n\\section{An unlikely event}\n\nOn June 12, 2019 at 6:59 pm, you are exiting the elevator, walking toward \\textsc{ms\\&e} to hand in your final take home exam for Physics 133. Just a few moments before 6:59 pm, a small meteor falls from the sky and crashes into a physics textbook on the desk of a philosopher trying to understand the meaning of entropy. The meteor is burning at such a high temperature that it instantly incinerates the book and continues burning through floor after floor of the building until coming to rest near a water line adjacent to a 50 year-old water fountain. The pipe becomes super heated, compressing the water in the plumbing and causing a catastrophic failure of the building’s pipes. The compression shock shakes the foundation of the building and, just as you exit the elevator, a micro-earthquake rumbles across the entire campus. Your exam slips from your hands and falls like an autumn leaf right between the crack that separates the elevator from the third floor's surface. The exam can't be recovered. Assume that the observation of this event is extremely unlikely. How much information is contained in such an event?\n\n\\begin{question}\n\\textbf{(a)} From Shannon, we know that the entropy is in fact a measure of \\textit{information}. Suppose that any event, including that described above, occurs with probability $p$. We can associate with the observation of this event a function that quantifies the amount of information, call it $I(p)$. Find the functional form of $I(p)$ such that the following conditions are met:\n\\begin{enumerate}\n\\item Information is \\textit{non-negative}.\n\\item If two events occur independently so that their joint probability is the product of event 1 and event 2, then their information is \\textit{additive}.\n\\item Information is a continuous function of the probability $p$.\n\\item There is \\textit{no information} content to an event that is always observed.\n\\end{enumerate}\n\\end{question}\n\n\\begin{solution}\nWe need a function that satisfies the following four criteria.\n\\begin{enumerate}\n\\item Information is non-negative.\n\\begin{align}\nI(p) & \\geq 0\n\\end{align}\n\n\\item For two independent events $i$ and $j$ where the joint probability that they both occur is $p_i \\cdot p_j$, the total information of the events is given by $I(p_i) + I(p_j)$.\n\\begin{align}\nI(p_i) + I(p_j) & = I(p_i + p_j)\n\\end{align}\n\n\\item Information is a continuous function of the probability $p$. A function $I$ is continuous if and only if the limit\n\\begin{equation}\n\\lim_{p \\to a} I(p) = I(a)\n\\end{equation}\nexists.\n\n\\item If an event $i$ is always observed, that event contains no information such that\n\\begin{align}\n\\text{for an event $i$, if $p_i = 1$, then}\\  I(p_i)& = 0.\n\\end{align}\n\\end{enumerate}\nA simple function that has these four properties is the logarithm function.\\footnote{Proofs left as an exercise for the reader. Or see \\url{https://en.wikipedia.org/wiki/Logarithm}.} Let\n\\begin{align}\n\\Aboxed{I(p) & = - \\log{p} = \\log{\\frac{1}{p}}}\\label{eq:info}\n\\end{align}\nwhere $p \\in [0,1]$ is the probability of a given event occurring.\n\\end{solution}\n\n\\begin{question}\n\\textbf{(b)} Find the value of $I(p)$ for the event described above (i.e.~the probability of observing such an event approaches zero). How much information is contained in an event as unlikely as this one?\n\\end{question}\n\n\\begin{solution}\nThe chances of such an event happening are \\textbf{unlikely}. Let the probability of the unlikely event occurring go to zero. The amount of information contained in the event is given by\n\\begin{equation}\n\\boxed{I(p) = \\lim_{p \\to 0}  \\log\\frac{1}{p} = \\infty.}\n\\end{equation}\nThe amount of information contained in this event is infinite.\n\\end{solution}\n\n\\end{document}\n", "meta": {"hexsha": "78b6f3d4cab2051d7060d0dfe80eb53bb49f374a", "size": 32041, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "solved/P133_Final.tex", "max_stars_repo_name": "stepheniota/Physics133-UCR", "max_stars_repo_head_hexsha": "2018ae62e384205459175dbed525930e607f8956", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "solved/P133_Final.tex", "max_issues_repo_name": "stepheniota/Physics133-UCR", "max_issues_repo_head_hexsha": "2018ae62e384205459175dbed525930e607f8956", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solved/P133_Final.tex", "max_forks_repo_name": "stepheniota/Physics133-UCR", "max_forks_repo_head_hexsha": "2018ae62e384205459175dbed525930e607f8956", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.439667129, "max_line_length": 1124, "alphanum_fraction": 0.6865266377, "num_tokens": 10388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.34582062857361023}}
{"text": "% Copyright (c) Microsoft Corporation. All rights reserved.\n% Licensed under the MIT License.\n\n%!TEX program=xelatex\n% This cheatsheet is based on the template\n% provided at https://gist.github.com/alexander-yakushev/c773543bf9a957749f79.\n\\documentclass[10pt,english,landscape]{article}\n\\usepackage{multicol}\n\\usepackage{calc}\n\\usepackage[landscape]{geometry}\n\\usepackage{color,graphicx,overpic}\n\\usepackage{amsmath}\n\n% Workaround for left brackets not rendering\n% https://tex.stackexchange.com/questions/520847/left-matrix-bracket-not-rendered-properly\n\n\\newbox\\matrixrepresentationright\n\\sbox\\matrixrepresentationright{\\parbox{\\textwidth}{\n  \\footnotesize\n  $\\qquad \\underrightarrow{n \\text{ columns}} \\\\\n  \\rotatebox[origin=c]{270}{$\\underrightarrow{m \\text{ rows}}$}\n  \\begin{bmatrix} \n    a_{0,0}   & \\cdots & a_{0,n-1} \\\\ \n    \\vdots    & \\ddots & \\vdots \\\\\n    a_{m-1,0} & \\cdots & a_{m-1,n-1} \n  \\end{bmatrix}$\n}}\n\n\\newbox\\vectorrepresentationright\n\\sbox\\vectorrepresentationright{\n  \\footnotesize\n  $\\begin{bmatrix}\n    a_0 \\\\ \\vdots \\\\ a_{n-1}\n  \\end{bmatrix}$\n}\n\n\\newbox\\matrixadditionleft\n\\sbox\\matrixadditionleft{\\parbox{\\textwidth}{\n  \\footnotesize\n  Addition \\linebreak\n  $\\begin{bmatrix} \n    a & b \\\\ \n    c & d \n    \\end{bmatrix} + \n  \\begin{bmatrix}\n    e & f \\\\\n    g & h\n  \\end{bmatrix}$ \n}}\n\n\\newbox\\matrixadditionright\n\\sbox\\matrixadditionright{\\parbox{\\textwidth}{\n  \\footnotesize\n  $ \\begin{bmatrix}  \n    a + e & b + f \\\\\n    c + g & d + h \n  \\end{bmatrix} $\n}}\n\n\\newbox\\matrixscalarleft\n\\sbox\\matrixscalarleft{\\parbox{\\textwidth}{\n  \\footnotesize\n  Scalar product \\newline\n  $ a  \\cdot \\begin{bmatrix} \n    b & c \\\\\n    d & e\n  \\end{bmatrix} $\n}}\n\n\\newbox\\matrixscalarright\n\\sbox\\matrixscalarright{\\parbox{\\textwidth}{\n  \\footnotesize\n  $ \\begin{bmatrix}\n    a \\cdot b & a \\cdot c \\\\\n    a \\cdot d & a \\cdot e\n  \\end{bmatrix} $ \n}}\n\n\\newbox\\matrixmultiplicationleft\n\\sbox\\matrixmultiplicationleft{\\parbox{\\textwidth}{\n  \\footnotesize\n  Matrix product \\newline\n  $ \\begin{bmatrix} \n    a & b & c \\\\\n    d & e & f\n  \\end{bmatrix} \\cdot\n  \\begin{bmatrix} \n    x \\\\\n    y \\\\\n    z\n  \\end{bmatrix} $\n}}\n\n\\newbox\\matrixmultiplicationright\n\\sbox\\matrixmultiplicationright{\\parbox{\\textwidth}{\n  \\footnotesize\n  $ \\begin{bmatrix} \n    a \\cdot x + b \\cdot y + c \\cdot z \\\\\n    d \\cdot x + e \\cdot y + f \\cdot z \n  \\end{bmatrix} $\n}}\n\n\\newbox\\matrixtransposeleft\n\\sbox\\matrixtransposeleft{\\parbox{\\textwidth}{\n  \\footnotesize\n  Transpose \\newline \n  $ \\begin{bmatrix}\n    a & b & c\\\\\n    d & e & f \n  \\end{bmatrix}^T $\n}}\n\n\\newbox\\matrixtransposeright\n\\sbox\\matrixtransposeright{\\parbox{\\textwidth}{\n  \\footnotesize\n  $ \\begin{bmatrix}\n     a & d \\\\\n    b & e \\\\\n    c & f\n  \\end{bmatrix} $ \n}}\n\n\\newbox\\matrixadjointleft\n\\sbox\\matrixadjointleft{\\parbox{\\textwidth}{\n  \\footnotesize\n  Adjoint \\newline  \n  $ \\begin{bmatrix}\n    a & b & c \\\\\n    d & e & f\n  \\end{bmatrix}^\\dagger $ \n}}\n\n\\newbox\\matrixadjointright\n\\sbox\\matrixadjointright{\\parbox{\\textwidth}{\n  \\footnotesize\n  $ \\begin{bmatrix}\n     \\overline{a} & \\overline{e} \\\\\n    \\overline{b} & \\overline{d} \\\\\n     \\overline{c} & \\overline{f}\n  \\end{bmatrix} $ \n}}\n\n\\newbox\\outerproductleft\n\\sbox\\outerproductleft{\\parbox{\\textwidth}{\n  \\footnotesize\n  Outer product \\newline\n  $ \\begin{bmatrix} \n    a \\\\\n    b\n  \\end{bmatrix} $  and $\n  \\begin{bmatrix} \n    x \\\\ \n    y \\\\\n    z \n    \\end{bmatrix} $\n}}\n\n\\newbox\\innerproductleft\n\\sbox\\innerproductleft{\\parbox{\\textwidth}{\n  \\footnotesize\n  Inner product \\newline\n  $ \\left\\langle \n    \\begin{bmatrix}\n      a \\\\\n      b\n    \\end{bmatrix} ,\n    \\begin{bmatrix}  \n      c \\\\\n      d\n    \\end{bmatrix} \n  \\right\\rangle $ \n}}\n\n\\newbox\\innerproductright\n\\sbox\\innerproductright{\\parbox{\\textwidth}{\n  \\footnotesize\n  $ \\begin{bmatrix}\n    a \\\\\n    b\n  \\end{bmatrix}^\\dagger\n  \\begin{bmatrix}\n    c \\\\\n    d\n  \\end{bmatrix} =\n  \\begin{bmatrix} \n    \\overline{a} &  \\overline{b} \n  \\end{bmatrix}  \n  \\begin{bmatrix}\n    c \\\\\n    d\n  \\end{bmatrix} = \n  \\overline{a} c + \\overline{b} d $\n}}\n\n\\newbox\\outerproductright\n\\sbox\\outerproductright{\\parbox{\\textwidth}{\n  \\footnotesize\n  $ \\begin{bmatrix}\n    a \\\\\n    b\n  \\end{bmatrix} \n  \\begin{bmatrix}\n    x \\\\\n    y \\\\\n    z\n  \\end{bmatrix}^\\dagger =\n  \\begin{bmatrix}\n    a \\\\\n    b  \n  \\end{bmatrix}\n  \\begin{bmatrix}\n    \\overline{x} & \\overline{y} & \\overline{z}\n  \\end{bmatrix} = $ \\newline\n  $ = \\begin{bmatrix} \n        a \\cdot \\overline{x} & a \\cdot \\overline{y} & a \\cdot \\overline{z} \\\\\n        b \\cdot \\overline{x} & b \\cdot \\overline{y} & b \\cdot \\overline{z} \\\\\n      \\end{bmatrix} $ \n}}\n\n\\newbox\\xgate\n\\sbox\\xgate{\\parbox{\\textwidth}{\n  \\footnotesize\n   $ \\begin{bmatrix} 0 & 1 \\\\ 1 & 0 \\end{bmatrix} $ \n}}\n\n\\newbox\\ygate\n\\sbox\\ygate{\\parbox{\\textwidth}{\n  \\footnotesize\n  $ \\begin{bmatrix} 0 & -i \\\\ i & 0 \\end{bmatrix} $\n}}\n\n\\newbox\\zgate\n\\sbox\\zgate{\\parbox{\\textwidth}{\n  \\footnotesize\n  $ \\begin{bmatrix} 1 & 0 \\\\ 0 & -1 \\end{bmatrix} $\n}}\n\n\\newbox\\igate\n\\sbox\\igate{\\parbox{\\textwidth}{\n  \\footnotesize\n  $ \\begin{bmatrix} 1 & 0 \\\\ 0 & 1 \\end{bmatrix} $\n}}\n\n\\newbox\\hgate\n\\sbox\\hgate{\\parbox{\\textwidth}{\n  \\footnotesize\n  $ \\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1 & 1 \\\\ 1 & -1 \\end{bmatrix} $\n}}\n\n\\newbox\\sgate\n\\sbox\\sgate{\\parbox{\\textwidth}{\n  \\footnotesize\n  $ \\begin{bmatrix} 1 & 0 \\\\ 0 & i \\end{bmatrix} $\n}}\n\n\\newbox\\tgate\n\\sbox\\tgate{\\parbox{\\textwidth}{\n  \\footnotesize\n   $ \\begin{bmatrix} 1 & 0 \\\\ 0 & e^{i\\pi/4} \\end{bmatrix} $ \n}}\n\n\\newbox\\rxgate\n\\sbox\\rxgate{\\parbox{\\textwidth}{\n  \\footnotesize\n   $\\begin{bmatrix} \\cos\\frac{\\theta}{2} & -i\\sin\\frac{\\theta}{2} \\\\ -i\\sin\\frac{\\theta}{2} &  \\cos\\frac{\\theta}{2} \\end{bmatrix} $ \n}}\n\n\\newbox\\rygate\n\\sbox\\rygate{\\parbox{\\textwidth}{\n  \\footnotesize\n   $ \\begin{bmatrix} \\cos\\frac{\\theta}{2}  & -\\sin\\frac{\\theta}{2} \\\\ \\sin\\frac{\\theta}{2} & \\cos\\frac{\\theta}{2} \\end{bmatrix} $\n}}\n\n\\newbox\\rzgate\n\\sbox\\rzgate{\\parbox{\\textwidth}{\n  \\footnotesize\n  $ \\begin{bmatrix} e^{-i\\theta/2} & 0 \\\\ 0 & e^{i\\theta/2} \\end{bmatrix} $ \n}}\n\n\n\\newbox\\rgate\n\\sbox\\rgate{\\parbox{\\textwidth}{\n  \\footnotesize\n   $ \\begin{bmatrix} 1 & 0 \\\\ 0 & e^{i\\theta} \\end{bmatrix} $\n}}\n\n\\newbox\\cnotgate\n\\sbox\\cnotgate{\\parbox{\\textwidth}{\n  \\footnotesize\n   $ \\begin{bmatrix} 1 & 0 & 0 & 0 \\\\ 0 & 1 & 0 & 0 \\\\ 0 & 0 & \\mathbf{0} & \\mathbf{1} \\\\ 0 & 0 & \\mathbf{1} & \\mathbf{0} \\end{bmatrix} $\n}}\n\n\\newbox\\swapgate\n\\sbox\\swapgate{\\parbox{\\textwidth}{\n  \\footnotesize\n   $ \\begin{bmatrix} 1 & 0 & 0 & 0 \\\\ 0 & \\mathbf{0} & \\mathbf{1} & 0 \\\\ 0 & \\mathbf{1} & \\mathbf{0} & 0 \\\\ 0 & 0 & 0 & 1 \\end{bmatrix} $\n}}\n\n\\newbox\\controlledugate\n\\sbox\\controlledugate{\\parbox{\\textwidth}{\n  \\footnotesize\n  $\\begin{bmatrix} 1 & 0 & 0 & 0 \\\\ 0 & 1 & 0 & 0 \\\\ 0 & 0 & a_{0,0} & a_{0,1} \\\\ 0 & 0 & a_{1,0} & a_{1,1} \\end{bmatrix} $\n}}\n\n\\newbox\\ccnotgate\n\\sbox\\ccnotgate{\\parbox{\\textwidth}{\n  \\footnotesize\n  $\\begin{bmatrix}\n    1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\\\\n    0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\\\\n    0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\\\\n    0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\\\\n    0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\\\\n    0 & 0 &0  & 0 & 0 & 1 & 0 & 0 \\\\\n    0 & 0 & 0 & 0 & 0 & 0 & \\mathbf{0} & \\mathbf{1} \\\\\n    0 & 0 & 0 & 0 & 0 & 0 & \\mathbf{1} & \\mathbf{0}\n\\end{bmatrix}$\n}}\n\n\\newbox\\braketcx\n\\sbox\\braketcx{\\parbox{\\textwidth}{\n  \\footnotesize\n    $ |00\\rangle\\langle00| + |01\\rangle\\langle01| + |11\\rangle\\langle10| + |10\\rangle\\langle11| \\newline \\text{or} \\newline |0\\rangle\\langle0| \\otimes I + |1\\rangle\\langle1| \\otimes X $\n}}\n\n\\newbox\\braketcu\n\\sbox\\braketcu{\\parbox{\\textwidth}{\n  \\footnotesize\n    $  |0\\rangle\\langle0| \\otimes I + |1\\rangle\\langle1| \\otimes U $\n}}\n\n\\newbox\\braketccx\n\\sbox\\braketccx{\\parbox{\\textwidth}{\n  \\footnotesize\n    $ |00\\rangle\\langle00| + |10\\rangle\\langle01| + a_{0,0}|10\\rangle\\langle10| + \\newline a_{0,1}|10\\rangle\\langle11| + a_{1,0}|10\\rangle\\langle11| + a_{1,1}|11\\rangle\\langle11| \\newline \\text{Or} \\newline |0\\rangle\\langle0| \\otimes I + |1\\rangle\\langle1| \\otimes U $\n}}\n\n\n\n% https://tex.stackexchange.com/a/192067\n\\usepackage{fontawesome}\n  \\newfontfamily{\\FA}{[FontAwesome.otf]}\n\n% Known issue in {fontspec}: https://github.com/wspr/fontspec/issues/312#issuecomment-342125206\n% Since {fontspec} is included only when compiling with XeTeX, we guard\n% our fix accordingly.\n\\usepackage{ifxetex}\n    \\ifxetex\n        \\let\\latinencoding\\relax\n        \\usepackage{fontspec}\n        \\setmainfont{Segoe UI}\n        \\setmonofont{Consolas}\n    \\fi\n\n% \\usepackage[T1]{fontenc}\n% \\usepackage[bitstream-charter]{mathdesign}\n\\usepackage[utf8]{inputenc}\n\\usepackage{url}\n\\usepackage{amsfonts}\n\\usepackage{array,booktabs}\n\\usepackage{textcomp}\n\\usepackage[usenames,dvipsnames,table]{xcolor}\n\\usepackage[most]{tcolorbox}\n\\usepackage{menukeys}\n\\usepackage{tabularx}\n\\usepackage{multirow}\n\\usepackage{colortbl}\n\\usepackage{tikz}\n\\usepackage{environ}\n\\usepackage{braket}\n\n\\usetikzlibrary{calc}\n\\pgfdeclarelayer{background}\n\\pgfdeclarelayer{foreground}\n\\pgfsetlayers{background,main,foreground}\n\n\\geometry{top=1cm,left=1cm,right=1cm,bottom=1cm}\n\n\\pagestyle{empty} % Turn off header and footer\n\n% \\renewcommand\\rmdefault{phv} % Arial\n% \\renewcommand\\sfdefault{phv} % Arial\n\n% Redefine section commands to use less space\n\\makeatletter\n\\renewcommand{\\section}{\\@startsection{section}{1}{0mm}%\n  {-1ex plus -.5ex minus -.2ex}%\n  {0.5ex plus .2ex}%x\n  {\\normalfont\\large\\bfseries}}\n\\renewcommand{\\subsection}{\\@startsection{subsection}{2}{0mm}%\n  {-1explus -.5ex minus -.2ex}%\n  {0.5ex plus .2ex}%\n  {\\normalfont\\normalsize\\bfseries}}\n\\renewcommand{\\subsubsection}{\\@startsection{subsubsection}{3}{0mm}%\n  {-1ex plus -.5ex minus -.2ex}%\n  {1ex plus .2ex}%\n  {\\normalfont\\small\\bfseries}}\n\\makeatother\n\n\\setcounter{secnumdepth}{0} % Don't print section numbers\n\\setlength{\\parindent}{0pt}\n\\setlength{\\parskip}{0pt plus 0.5ex}\n\n\\definecolor{TableHead}{rgb}{0.353, 0.329, 0.667}\n\\definecolor{TableRow}{rgb}{0.816, 0.812, 0.902}\n\n% Turn off warnings about slightly overfull boxes\n% https://tex.stackexchange.com/questions/50830/do-i-have-to-care-about-bad-boxes/50850\n\n\\hfuzz=10pt\n\n\\NewEnviron{keysref}[1]{\n  % \\begin{center}\n  \\smallskip\n  \\begin{tikzpicture}\n      \\rowcolors{1}{}{TableRow}\n\n      \\node (tbl) [inner sep=0pt] {\n        \\begin{tabular}{p{2.5cm}p{5.05cm}}\n          \\rowcolor{TableHead}\n          \\multicolumn{2}{l}{\\normalsize\\textbf{\\color{white}{#1}}}\\parbox{0pt}{\\rule{0pt}{0.3ex+\\baselineskip}}\\\\\n          \\BODY\n          \\arrayrulecolor{TableHead}\\specialrule{.17em}{0em}{.2em}\n        \\end{tabular}};\n      \\begin{pgfonlayer}{background}\n        \\draw[rounded corners=2pt,top color=TableHead,bottom color=TableHead, draw=white]\n        ($(tbl.north west)-(0,-0.05)$) rectangle ($(tbl.north east)-(0.0,0.15)$);\n        \\draw[rounded corners=2pt,top color=TableHead,bottom color=TableHead, draw=white]\n        ($(tbl.south west)-(0.0,-0.11)$) rectangle ($(tbl.south east)-(-0.0,-0.02)$);\n      \\end{pgfonlayer}\n    \\end{tikzpicture}\n  % \\end{center}\n}\n\n\\NewEnviron{keysrefGates}[1]{\n  % \\begin{center}\n  \\smallskip\n  \\begin{tikzpicture}\n      \\rowcolors{1}{}{TableRow}\n\n      \\node (tbl) [inner sep=0pt] {\n        \\begin{tabular}{p{0.85cm}p{3.55cm}p{4.05cm}p{5.55cm}p{2.95cm}p{2.95cm}p{3.05cm}}\n          \\rowcolor{TableHead}\n          \\multicolumn{7}{l}{\\normalsize\\textbf{\\color{white}{#1}}}\\parbox{0pt}{\\rule{0pt}{0.3ex+\\baselineskip}}\\\\\n          \\BODY\n          \\arrayrulecolor{TableHead}\\specialrule{.17em}{0em}{.2em}\n        \\end{tabular}};\n      \\begin{pgfonlayer}{background}\n        \\draw[rounded corners=2pt,top color=TableHead,bottom color=TableHead, draw=white]\n        ($(tbl.north west)-(0,-0.05)$) rectangle ($(tbl.north east)-(0.0,0.15)$);\n        \\draw[rounded corners=2pt,top color=TableHead,bottom color=TableHead, draw=white]\n        ($(tbl.south west)-(0.0,-0.11)$) rectangle ($(tbl.south east)-(-0.0,-0.02)$);\n      \\end{pgfonlayer}\n    \\end{tikzpicture}\n  % \\end{center}\n}\n\n\\NewEnviron{keysrefMultiGates}[1]{\n  % \\begin{center}\n  \\smallskip\n  \\begin{tikzpicture}\n      \\rowcolors{1}{}{TableRow}\n\n      \\node (tbl) [inner sep=0pt] {\n        \\begin{tabular}{p{1.55cm}p{3,75cm}p{5,35cm}p{6,05cm}p{2.95cm}p{3.75cm}}\n          \\rowcolor{TableHead}\n          \\multicolumn{6}{l}{\\normalsize\\textbf{\\color{white}{#1}}}\\parbox{0pt}{\\rule{0pt}{0.3ex+\\baselineskip}}\\\\\n          \\BODY\n          \\arrayrulecolor{TableHead}\\specialrule{.17em}{0em}{.2em}\n        \\end{tabular}};\n      \\begin{pgfonlayer}{background}\n        \\draw[rounded corners=2pt,top color=TableHead,bottom color=TableHead, draw=white]\n        ($(tbl.north west)-(0,-0.05)$) rectangle ($(tbl.north east)-(0.0,0.15)$);\n        \\draw[rounded corners=2pt,top color=TableHead,bottom color=TableHead, draw=white]\n        ($(tbl.south west)-(0.0,-0.11)$) rectangle ($(tbl.south east)-(-0.0,-0.02)$);\n      \\end{pgfonlayer}\n    \\end{tikzpicture}\n  % \\end{center}\n}\n\n\n% https://tex.stackexchange.com/a/102523\n\\newcommand{\\forceindent}[1]{\\leavevmode{\\parindent=#1\\indent}}\n\n%% CUSTOM NOTATION %%\n\n\\newcommand{\\qs}{Q\\#}\n\\newcommand{\\unixlike}{\\hfill\\faApple\\faLinux}\n\\newcommand{\\ctrllike}{\\hfill\\faWindows\\faLinux}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n\\begin{document}\n\n\\raggedright\\\n\n\\Large{\\qs~0.15 Language Quick Reference}\n\n\\footnotesize\n\\begin{multicols}{3}\n\n  \\begin{keysref}{Primitive Types}\n    64-bit integers         & \\texttt{Int} \\\\\n    Double-precision \\newline floats & \\texttt{Double} \\\\\n    Booleans                & \\texttt{Bool}   \\newline \n                              e.g.: \\texttt{true} or \\texttt{false} \\\\\n    Qubits                  & \\texttt{Qubit}  \\\\\n    Pauli basis             & \\texttt{Pauli}  \\newline\n                              e.g.: \\texttt{PauliI}, \\texttt{PauliX}, \\texttt{PauliY}, or \\texttt{PauliZ} \\\\\n    Measurement \\newline results     & \\texttt{Result} \\newline\n                              e.g.: \\texttt{Zero} or \\texttt{One} \\\\\n    Sequences of \\newline integers   & \\texttt{Range}  \\newline\n                              e.g.: \\texttt{1..10} or \\texttt{5..-1..0} \\\\\n    Strings                 & \\texttt{String} \\newline \n                              e.g.: \\texttt{\"Hello Quantum!\"} \\\\\n    \"Return no \\newline information\" type   & \\texttt{Unit} \\newline e.g.: \\texttt{()} \\\\\n  \\end{keysref}\n\n  \\begin{keysref}{Derived Types}\n    Arrays                  & \\texttt{\\emph{elementType}[]} \\\\\n    Tuples                  & \\texttt{(\\emph{type0}, \\emph{type1}, ...)} \\newline\n                              e.g.: \\texttt{(Int, Qubit)} \\\\\n    Functions               & \\texttt{\\emph{input} -> \\emph{output}} \\newline\n                              e.g.: \\texttt{ArcCos : (Double) -> Double} \\\\\n    Operations              & \\texttt{\\emph{input} => \\emph{output} is \\emph{variants}} \\newline\n                              e.g.: \\texttt{H : (Qubit => Unit is Adj)} \\\\\n  \\end{keysref}\n  \n  \\begin{keysref}{User-Defined Types}\n  Declare UDT with \\newline anonymous items & \\texttt{newtype \\emph{Name} = (Type, Type);} \\newline\n                                     e.g.: \\texttt{newtype \\emph{Pair} = (Int, Int);} \\\\\n  Define UDT literal               & \\texttt{\\emph{Name}(\\emph{baseTupleLiteral})} \\newline\n                                     e.g.: \\texttt{let origin = Pair(0, 0);} \\\\\n  Unwrap operator \\texttt{!} \\newline (convert UDT to \\newline underlying type) \n                                   & \\texttt{\\emph{VarName}!} \\newline\n                                     e.g.: \\texttt{let originTuple = origin!;} \\newline \\hphantom{..........}(now \\texttt{originTuple = (0, 0)}) \\\\\n  Declare UDT with \\newline named items     & \\texttt{newtype \\emph{Name} =}   \\newline \\texttt{\\hphantom{....}(\\emph{Name1}: Type, \\emph{Name2}: Type);} \\newline\n                                     e.g.: \\texttt{newtype Complex =} \\newline \\texttt{\\hphantom{....}(Re : Double, Im : Double);} \\\\\n  Accessing named \\newline items of UDTs    & \\texttt{\\emph{VarName}::\\emph{ItemName}} \\newline\n                                     e.g.: \\texttt{complexVariable::Re} \\\\\n  Update-and-\\newline reassign for named \\newline UDT items & \\texttt{set \\emph{VarName} w/= \\emph{ItemName} <- \\emph{val};} \\newline\n                                            e.g.: \\texttt{mutable p = Complex(0., 0.);} \\newline\n                                                  \\texttt{\\hphantom{....}set p w/= Re <- 1.0;} \\\\\n  \\end{keysref}\n  \n  \\begin{keysref}{Symbols and Variables}\n    Declare immutable \\newline symbol           & \\texttt{let \\emph{varName} = \\emph{value}} \\\\\n    Declare mutable \\newline symbol (variable)  & \\texttt{mutable \\emph{varName} = \\emph{initialValue}} \\\\\n    Update mutable \\newline symbol (variable)   & \\texttt{set \\emph{varName} = \\emph{newValue}} \\\\\n    Apply-and-reassign                          & \\texttt{set \\emph{varName} \\emph{operator}= \\emph{expression}} \\newline\n                                                  e.g.: \\texttt{set counter += 1;} \\\\ \n  \\end{keysref}\n\n  \\columnbreak\n\n  \\begin{keysref}{Functions and Operations}\n    Define function \\newline (classical routine)\n              & \\texttt{function \\emph{Name}(\\emph{in0} : \\emph{type0}, ...) \\newline\n                : \\emph{returnType} \\{} \\newline\n                \\texttt{\\hphantom{....}// \\emph{function body}} \\newline\n                \\texttt{\\}} \\\\\n    Call function & \\texttt{\\emph{Name}(\\emph{parameters})} \\newline\n                    e.g.: \\texttt{let two = Sqrt(4.0);} \\\\\n    Define operation \\newline (quantum routine) \\newline with explicitly \\newline specified body, \\newline controlled and \\newline adjoint variants\n               & \\texttt{operation \\emph{Name}(\\emph{in0} : \\emph{type0}, ...) \\newline \n                 : \\emph{returnType} \\{} \\newline\n                 \\texttt{\\hphantom{....}body \\{ ... \\}} \\newline\n                 \\texttt{\\hphantom{....}adjoint \\{ ... \\}} \\newline\n                 \\texttt{\\hphantom{....}controlled \\{ ... \\}} \\newline\n                 \\texttt{\\hphantom{....}adjoint controlled \\{ ... \\}} \\newline\n                 \\texttt{\\}} \\\\\n    Define operation \\newline with automatically \\newline generated adjoint \\newline and controlled \\newline variants\n               & \\texttt{operation \\emph{Name}(\\emph{in0} : \\emph{type0}, ...) \\newline \n                 : \\emph{returnType} is Adj + Ctl \\{} \\newline\n                 \\texttt{\\hphantom{....}... \\newline\n                 \\} } \\\\\n    Call operation & \\texttt{\\emph{Name}(\\emph{parameters})} \\newline\n                     e.g.: \\texttt{Ry(0.5 * PI(), q);} \\\\\n    Call adjoint \\newline operation & \\texttt{Adjoint \\emph{Name}(\\emph{parameters})} \\newline\n                     e.g.: \\texttt{Adjoint Ry(0.5 * PI(), q);} \\\\\n    Call controlled \\newline operation & \\texttt{Controlled \\emph{Name}(\\emph{controlQubits}, \\newline \\hphantom{....}\\emph{parameters})} \\newline\n                     e.g.: \\texttt{Controlled Ry(controls, \\newline \\hphantom{....}(0.5 * PI(), target));} \\\\\n  \\end{keysref}\n\n  \\begin{keysref}{Control Flow}\n    Iterate over \\newline a range of numbers\n                       & \\texttt{for \\emph{index} in \\emph{range} \\{ }\\newline \n                         \\texttt{\\hphantom{....}// Use integer \\emph{index}} \\newline\n                         \\texttt{\\hphantom{....}...} \\newline\n                         \\texttt{\\}} \\newline\n                         e.g.: \\texttt{for i in 0..N-1 \\{ ... \\}} \\\\\n    While loop \\newline (within functions)\n                       & \\texttt{while (\\emph{condition}) \\{} \\newline\n                         \\texttt{\\hphantom{....}...} \\newline\n                         \\texttt{\\}} \\\\\n    Iterate over \\newline an array & \\texttt{for \\emph{val} in \\emph{array} \\{ }\\newline \n                                     \\texttt{\\hphantom{....}// Use value \\emph{val}} \\newline\n                                     \\texttt{\\hphantom{....}...} \\newline\n                                     \\texttt{\\}} \\newline\n                                     e.g.: \\texttt{for q in register \\{ ... \\}} \\\\\n    Repeat-until- \\newline success loop      & \\texttt{repeat \\{ ... \\} \\newline until \\emph{condition} \\newline fixup \\{ ... \\}} \\\\\n    Conditional \\newline statement & \\texttt{if \\emph{cond1} \\{ ... \\}} \\newline \n                                     \\texttt{elif \\emph{cond2} \\{ ... \\}} \\newline\n                                     \\texttt{else \\{ ... \\}} \\\\\n    Ternary operator   & \\texttt{\\emph{condition} ? \\emph{caseTrue} | \\emph{caseFalse} } \\\\\n    Return a value     & \\texttt{return \\emph{value}} \\\\\n    Stop with an error & \\texttt{fail \"\\emph{Error message}\"} \\\\\n    Conjugations \\newline ($ABA^\\dagger$ pattern)\n                       & \\texttt{within \\{ ... \\}} \\newline\n                         \\texttt{apply \\{ ... \\}} \\\\\n  \\end{keysref}\n  \n  \\columnbreak\n\n  \\begin{keysref}{Arrays}\n    Allocate array       & \\texttt{mutable \\emph{name} = new \\emph{Type}[\\emph{length}]} \\newline\n                           e.g.: \\texttt{mutable b = new Bool[2];} \\\\\n    Get array length     & \\texttt{Length(\\emph{name})} \\\\\n    Access k-th element  & \\texttt{\\emph{name}[k]} \\newline NB: indices are 0-based  \\\\\n    Assign k-th element \\newline (copy-and-update) \n                         & \\texttt{set \\emph{name} w/= \\emph{k} <- \\emph{value}} \\newline\n                           e.g.: \\texttt{set b w/= 0 <- true;} \\\\\n    Array literal        & \\texttt{[\\emph{value0}, \\emph{value1}, ...]} \\newline\n                           e.g.: \\texttt{let b = [true, false, true];} \\\\\n    Array concatenation  & \\texttt{\\emph{array1} + \\emph{array2}} \\newline \n                           e.g.: \\texttt{let t = [1, 2, 3] + [4, 5];} \\\\\n    Slicing (subarray)   & \\texttt{\\emph{name}[\\emph{sliceRange}]} \\newline\n                           e.g.: if \\texttt{t = [1, 2, 3, 4, 5]}, then \\newline\n                           \\texttt{\\hphantom{..}t[1 .. 3]\\hphantom{....}} is \\texttt{[2, 3, 4]} \\newline\n                           \\texttt{\\hphantom{..}t[3 ...]\\hphantom{.....}} is \\texttt{[4, 5]} \\newline\n                           \\texttt{\\hphantom{..}t[... 1]\\hphantom{.....}} is \\texttt{[1, 2]} \\newline\n                           \\texttt{\\hphantom{..}t[0 .. 2 ...]\\hphantom{}} is \\texttt{[1, 3, 5]} \\newline\n                           \\texttt{\\hphantom{..}t[...-1...]\\hphantom{..}} is \\texttt{[5, 4, 3, 2, 1]} \\\\\n  \\end{keysref}\n\n  \\begin{keysref}{Debugging (classical)}\n    Print a string     & \\texttt{Message(\"Hello Quantum!\")} \\\\\n    Print an \\newline interpolated string   \n                       & \\texttt{Message(\\$\"Value = \\{\\emph{val}\\}\")} \\\\\n  \\end{keysref}\n  \n  \\section{Resources}\n  \n  \\begin{keysref}{Documentation}\n    Quantum \\newline Development Kit & \\url{https://docs.microsoft.com/azure/quantum} \\\\\n    QDK user guides & \\url{https://docs.microsoft.com/azure/quantum/user-guide} \\\\\n    \\qs~Libraries \\newline Reference & \\url{https://docs.microsoft.com/qsharp/api} \\\\\n  \\end{keysref}\n\n  \\begin{keysref}{\\qs~Code Repositories}\n    QDK Samples                                & \\url{https://github.com/microsoft/quantum} \\\\\n    QDK Libraries                              & \\url{https://github.com/microsoft/QuantumLibraries} \\\\\n    Quantum Katas \\newline (tutorials)         & \\url{https://github.com/microsoft/QuantumKatas} \\\\\n    \\qs~compiler and \\newline extensions       & \\url{https://github.com/microsoft/qsharp-compiler} \\\\\n    Simulation \\newline framework              & \\url{https://github.com/microsoft/qsharp-runtime} \\\\\n    Jupyter kernel and \\newline Python host    & \\url{https://github.com/microsoft/iqsharp} \\\\\n    Source code for \\newline the documentation & \\url{https://github.com/MicrosoftDocs/quantum-docs} \\\\\n  \\end{keysref}\n\n  \\columnbreak\n\n  \\begin{keysref}{Qubit Allocation}\n    Allocate a register \\newline of $N$ qubits \n                         & \\texttt{use \\emph{reg} = Qubit[\\emph{N}]; } \\newline\n                           \\texttt{//} Qubits in \\texttt{\\emph{reg}} start in $\\ket{0}$. \\newline\n                           \\texttt{...} \\newline\n                           \\texttt{//} Qubits must be returned to $\\ket{0}$. \\\\\n    Allocate one qubit   & \\texttt{use \\emph{one} = Qubit(); } \\newline\n    \t\t\t\t\t\t \\texttt{...} \\\\\n    Allocate a mix of \\newline qubit registers and \\newline individual qubits\n                         & \\texttt{use (\\emph{x}, \\emph{y}, ... ) = } \\newline \n                           \\texttt{\\hphantom{...}(Qubit[N], Qubit(), ... ); } \\newline\n                           \\texttt{...} \\\\\n  \\end{keysref}\n\n  \\begin{keysref}{Debugging (quantum)}\n    Print amplitudes \\newline of wave function               & \\texttt{DumpMachine(\"dump.txt\")} \\\\\n    Assert that a qubit is in $\\ket{0}$ or $\\ket{1}$ state   & \\texttt{AssertQubit(Zero, \\emph{zeroQubit})} \\newline\n                                                               \\texttt{AssertQubit(One, \\emph{oneQubit})} \\\\\n  \\end{keysref}\n\n  \n\n\n \n  \\begin{keysref}{Measurements}\n    Measure qubit in \\newline Pauli $Z$ basis & \\texttt{M(\\emph{oneQubit})} \\newline yields a \\texttt{Result} (\\texttt{Zero} or \\texttt{One}) \\\\\n    Reset qubit to $\\ket{0}$     & \\texttt{Reset(\\emph{oneQubit})} \\\\\n    Reset an array of \\newline qubits to $\\ket{0..0}$ & \\texttt{ResetAll(\\emph{register})} \\\\\n  \\end{keysref}\n\n  \n\n  \\section{Working with \\qs~from command line}\n\n  \\begin{keysref}{Command Line Basics}\n    Change directory    & \\texttt{cd \\emph{dirname}} \\\\\n    Go to home          & \\texttt{cd \\textasciitilde} \\\\\n    Go up one directory & \\texttt{cd ..} \\\\\n    Make new directory  & \\texttt{mkdir \\emph{dirname}} \\\\\n    Open current \\newline directory in VS Code & \\texttt{code .} \\\\\n  \\end{keysref}\n\n  \\begin{keysref}{Working with \\qs~Projects}\n    Create new project & \\texttt{dotnet new console -lang Q\\# \\newline \n                         --output \\emph{project-dir}} \\\\\n    Change directory to \\newline project directory & \\texttt{cd \\emph{project-dir}} \\\\\n    Build project                     & \\texttt{dotnet build} \\\\\n    Run all unit tests                & \\texttt{dotnet test} \\\\\n  \\end{keysref}\n\n  \\columnbreak\n  \n  \\section{Math reference}\n\n  \\begin{keysref}{Complex Arithmetic}\n    $i^2 $                         & $-1$ \\\\\n    $ (a + bi) + (c + di) $        & $ (a + c) + (b + d)i $ \\\\\n    $ (a + bi)  (c + di) $         & $ a \\cdot c + a \\cdot di + b \\cdot ci + (b \\cdot d)i^2 =$ \\newline\n                                     $ = (a \\cdot c - b \\cdot d) + (a \\cdot d + b \\cdot c)i $ \\\\\n\t  Complex conjugate              & $ \\overline{a + bi} = a - bi $ \\\\\n    Division $ \\frac{a+bi}{c+di} $ & $ \\frac{a+bi}{c+di} \\cdot 1 = \\frac{a+bi}{c+di} \\cdot \\frac{c-di}{c-di} = \\frac{(a+bi)(c-di)}{c^2 + d^2} $ \\\\\n    Modulus $|a + bi|$             & $ \\sqrt{a^2 + b^2} $ \\\\\n    $e^{i\\theta} $                 & $ \\cos \\theta + i \\sin \\theta $ \\\\ \n    $ e^{a + bi} $                 & $ e^a \\cdot e^{bi} = e^a \\cos b  + i e^a \\sin b $  \\\\\n    $ r^{a+bi} $                   & $ r^a \\cdot r^{bi} = r^a \\cdot e^{bi\\ln r} = $ \\newline \n                                     $ = r^a \\cos(b\\ln r) + i \\cdot r^a \\sin(b\\ln r) $ \\\\\n    Polar form $re^{i\\theta}$ to \\newline Cartesian form $a + bi$ & $ a = r \\cos \\theta \\newline b = r \\sin \\theta $ \\\\\n    Cartesian form $a + bi$ \\newline to polar form $re^{i\\theta}$ & $ r = \\sqrt{a^2 + b^2}  \\newline  \\theta = \\arctan(\\frac{b}{a}) $ \\\\\n  \\end{keysref}\n\n  \\begin{keysref}{Linear Algebra}\n\n    $m \\times n$ matrix & \\usebox\\matrixrepresentationright \\\\\n\n    Vector of size $n$ & \\usebox\\vectorrepresentationright \\\\\n    \n    \\usebox\\matrixadditionleft & \\usebox\\matrixadditionright \\\\\n    \n    \\usebox\\matrixscalarleft &\\usebox\\matrixscalarright \\\\\n    \n    \\usebox\\matrixmultiplicationleft & \\usebox\\matrixmultiplicationright \\\\\n\n    \\usebox\\matrixtransposeleft & \\usebox\\matrixtransposeright \\\\   \n    \n    \\usebox\\matrixadjointleft & \\usebox\\matrixadjointright \\\\\n\n    \\usebox\\innerproductleft & \\usebox\\innerproductright \\\\   \n    \n    \\usebox\\outerproductleft & \\usebox\\outerproductright \\\\\n  \n  \\end{keysref}\n  \n  \\newpage\n  \\end{multicols}\n  \\section{Gates reference}\n\n  \\begin{keysrefGates}{Single Qubit gates}\n\n    Gate & \n    Matrix representation  & \n    Ket-bra representation & \n    Applying to $ \\ket{\\psi} = \\alpha\\ket{0} + \\beta\\ket{1} $ & \n    Applying to basis states: & $\\ket{0},\\: \\ket{1},\\: \\ket{+},\\: \\ket{-}\\:$ and  & \n    $\\ket{\\pm i} = \\frac{1}{\\sqrt2}(\\ket{0} \\pm i\\ket{1})$ \\\\\n    \n    X & \n    \\usebox\\xgate & $ \\ket{0}\\bra{1} + \\ket{1}\\bra{0}$ & \n    $ \\ket{\\psi} = \\alpha\\ket{1} + \\beta\\ket{0} $ & \n    $ X\\ket{0} = \\ket{1} \\newline X\\ket{1} = \\ket{0} $ & \n    $ X\\ket{+} = \\ket{+} \\newline   X\\ket{-} = -\\ket{-}  $ &\n    $ X\\ket{i} = i\\ket{-i} \\newline X\\ket{-i} = -i\\ket{i} $    \\\\\n\n    Y & \n    \\usebox\\ygate & \n    $ i(\\ket{1}\\bra{0} - \\ket{0}\\bra{1})$ & \n    $ Y\\ket{\\psi} = i\\big(\\alpha\\ket{1} - \\beta\\ket{0}\\big)$ & \n    $Y\\ket{0} = i\\ket{1} \\newline Y\\ket{1} = -i\\ket{0} $ & \n    $ Y\\ket{+} = -i\\ket{-}  \\newline Y\\ket{-} = i\\ket{+} $ & \n    $ Y\\ket{i} = \\ket{i} \\newline Y\\ket{-i} = -\\ket{-i}$   \\\\\n\n    Z & \n    \\usebox\\zgate & \n    $ \\ket{0}\\bra{0} - \\ket{1}\\bra{1} $ & \n    $ Z\\ket{\\psi} = \\alpha\\ket{0} - \\beta\\ket{1} $ & \n    $ Z\\ket{0} = \\ket{0} \\newline Z\\ket{1} = -\\ket{1} $ & \n    $  Z\\ket{+} = \\ket{-} \\newline Z\\ket{-} = \\ket{+} $ & \n    $ Z\\ket{i} = \\ket{-i} \\newline Z\\ket{-i} = \\ket{i} $  \\\\\n\n    I & \n    \\usebox\\igate & \n    $ \\ket{0}\\bra{0} + \\ket{1}\\bra{1} $  & \n    $ I\\ket{\\psi} = \\ket{\\psi} $ & & & \\\\\n\n    H & \n    \\usebox\\hgate & \n    $ \\ket{0}\\bra{+} + \\ket{1}\\bra{-} $ & \n    $ H\\ket{\\psi} = \\alpha\\ket{+} + \\beta\\ket{-} = \\frac{\\alpha + \\beta}{\\sqrt{2}}\\ket{0} + \\frac{\\alpha - \\beta}{\\sqrt{2}}\\ket{1} $ & \n    $ H\\ket{0} = \\ket{+}   \\newline H\\ket{1} = \\ket{-} $ & \n    $ H\\ket{+} = \\ket{0} \\newline H\\ket{-} = \\ket{1} $ & \n    $ H\\ket{i} = e^{i\\pi/4}\\ket{-i} \\newline H\\ket{-i} = e^{-i\\pi/4}\\ket{i} $ \\\\\n\n    S & \n    \\usebox\\sgate & \n    $ \\ket{0}\\bra{0} + i\\ket{1}\\bra{1} $ & \n    $ S\\ket{\\psi} = \\alpha\\ket{0} + i\\beta\\ket{1} $ & \n    $ S\\ket{0} = \\ket{0} \\newline S\\ket{1} = i\\ket{1} $ & \n    $ S\\ket{+} = \\ket{i} \\newline S\\ket{-} = \\ket{-i} $ & \n    $ S\\ket{i} = \\ket{-} \\newline S\\ket{-i} = \\ket{+} $  \\\\\n\n    T & \n    \\usebox\\tgate & \n    $ \\ket{0}\\bra{0} + e^{i\\pi/4}\\ket{1} \\bra{1} $ & \n    $ T\\ket{\\psi} = \\alpha\\ket{0} + e^{i\\pi/4} \\beta \\ket{1} $ & \n    $ T\\ket{0} = \\ket{0}  $ &\n    $ T\\ket{1} = e^{i\\pi/4}\\ket{1} $ &  \\\\\n\n    $ R_x(\\theta) $ & \n    \\usebox\\rxgate & \n    $ \\cos\\frac{\\theta}{2}\\ket{0}\\bra{0}  -i\\sin\\frac{\\theta}{2}\\ket{1}\\bra{0} - \\newline \n      -i\\sin\\frac{\\theta}{2}\\ket{0} \\bra{1} + \\cos\\frac{\\theta}{2}\\ket{1}\\bra{1} $ & \n    $ R_x(\\theta)\\ket{\\psi} = \\ (\\alpha\\cos\\frac{\\theta}{2} - i\\beta\\sin\\frac{\\theta}{2})\\ket{0} + \\newline \n      + (\\beta\\cos\\frac{\\theta}{2} - i\\alpha\\sin\\frac{\\theta}{2})\\ket{1} $ & \n    $ R_x(\\theta)\\ket{0} = \\newline\n      = \\cos\\frac{\\theta}{2}\\ket{0} - i\\sin\\frac{\\theta}{2}\\ket{1} $ & \n    $ R_x(\\theta)\\ket{1} = \\newline\n      = \\cos\\frac{\\theta}{2}\\ket{1} - i\\sin\\frac{\\theta}{2}\\ket{0} $ & \\\\ \n\n    $ R_y(\\theta) $ & \n    \\usebox\\rygate   & \n    $ \\cos\\frac{\\theta}{2}\\ket{0}\\bra{0} + \\sin\\frac{\\theta}{2} \\ket{1}\\bra{0} - \\newline \n      -\\sin\\frac{\\theta}{2}\\ket{0}\\bra{1} + \\cos\\frac{\\theta}{2}\\ket{1}\\bra{1}$ & \n    $ R_y(\\theta)\\ket{\\psi} =  (\\alpha\\cos\\frac{\\theta}{2} - \\beta\\sin\\frac{\\theta}{2})\\ket{0} + \\newline \n      + (\\beta\\cos\\frac{\\theta}{2} + \\alpha\\sin\\frac{\\theta}{2})\\ket{1} $ & \n    $ R_y(\\theta)\\ket{0} = \\newline \n      = \\cos\\frac{\\theta}{2}\\ket{0} + \\sin\\frac{\\theta}{2}\\ket{1} $ & \n    $ R_y(\\theta)\\ket{1} = \\newline \n      = \\cos\\frac{\\theta}{2}\\ket{1} - \\sin\\frac{\\theta}{2}\\ket{0} $  &  \\\\\n\n    $ R_z(\\theta) $ & \\usebox\\rzgate & \n    $  e^{-i\\theta/2}\\ket{0}\\bra{0} + e^{i\\theta/2}\\ket{1} \\bra{1} $ & \n    $ R_z(\\theta)\\ket{\\psi} = \\alpha e^{-i\\theta/2}\\ket{0} + \\beta e^{i\\theta/2}\\ket{1} $ & \n    $ R_z(\\theta)\\ket{0} = e^{-i\\theta/2}\\ket{0} $ & \n    $ R_z(\\theta)\\ket{1} = e^{i\\theta/2}\\ket{1} $  &  \\\\\n\n    $ R_1(\\theta) $ & \n    \\usebox\\rgate & \n    $  \\ket{0}\\bra{0} + e^{i\\theta}\\ket{1} \\bra{1} $ & \n    $ R_1(\\theta)\\ket{\\psi} =  \\alpha\\ket{0} + \\beta e^{i\\theta}\\ket{1} $ &  \n    $ R_1(\\theta)\\ket{0} = \\ket{0} $ & \n    $ R_1(\\theta)\\ket{1} = e^{i\\theta}\\ket{1} $  &  \\\\\n\n  \\end{keysrefGates}\n  \n  \\begin{keysrefMultiGates}{Two-qubit gates}\n  \n    Gate &\n    Matrix Representation & \n    Ket-Bra Representation &\n    Applying to $\\ket{\\psi} = \\alpha\\ket{00} + \\beta\\ket{01} + \\gamma\\ket{10} + \\delta\\ket{11}$ &\n    Applying to basis states & \\\\\n    \n    CNOT &\n    \\usebox\\cnotgate & \n    \\usebox\\braketcx &\n    $ \\text{CNOT}\\ket{\\psi} = \\alpha\\ket{00} + \\beta\\ket{01} + $ {\\boldmath $ \\delta\\ket{10} + \\gamma\\ket{11} $} &\n    $ \\text{CNOT}\\ket{00} = \\ket{00} \\newline\n      \\text{CNOT}\\ket{01} = \\ket{01} $ &\n    $ \\text{CNOT}\\ket{10} = \\ket{11} \\newline\n      \\text{CNOT}\\ket{11} = \\ket{10} $ \\\\\n \n    SWAP &\n    \\usebox\\swapgate & \n    $ \\ket{00}\\bra{00} + \\ket{01}\\bra{10} + \\ket{10}\\bra{01} + \\ket{11}\\bra{11} $ &\n    $ \\text{SWAP}\\ket{\\psi} = \\alpha\\ket{00} + $ {\\boldmath $ \\gamma\\ket{01} + \\beta\\ket{10} $} $+ \\delta\\ket{11}$ &\n    $ \\text{SWAP}\\ket{00} = \\ket{00} \\newline\n      \\text{SWAP}\\ket{01} = \\ket{10} $ &\n    $\\text{SWAP}\\ket{10} = \\ket{01} \\newline\n      \\text{SWAP}\\ket{11} = \\ket{11} $ \\\\\n      \n    Controlled U &\n    \\usebox\\controlledugate  & \n    \\usebox\\braketcu & \n    $ \\text{CU} \\ket{\\psi} =  \\alpha\\ket{00} + \\beta\\ket{01} + \\newline \n      + (\\gamma  a_{0,0} + \\delta  a_{0,1}) \\ket{10} + (\\gamma  a_{1,0} + \\delta  a_{1,1}) \\ket{11}  $ & \n    $ \\text{CU} \\ket{00} = \\ket{00} \\newline\n      \\text{CU} \\ket{01} = \\ket{01} $ & \n    $\\text{CU} \\ket{10} = a_{0,0} \\ket{10} + a_{1,0} \\ket{11} \\newline \n     \\text{CU} \\ket{11} = a_{0,1} \\ket{10} + a_{1,1} \\ket{11} $ \\\\\n  \\end{keysrefMultiGates}\n  \n  \\begin{keysrefMultiGates}{Toffoli (CCNOT) gate} \n  \n    Gate &\n    Matrix Representation &\n    Ket-Bra Representation &\n    Applying to $\\ket{\\psi} = \\alpha\\ket{000} + \\beta\\ket{001} + \\gamma\\ket{010} + \\delta\\ket{011} + \\epsilon\\ket{100} + \\lambda\\ket{101}  + \\eta\\ket{110} + \\kappa\\ket{111} $ &\n    Applying to basis states & \\\\\n    \n    \n    CCNOT &\n    \\usebox\\ccnotgate & \n    $ (I_2 - \\ket{11}\\bra{11}) \\otimes I_1 + \\ket{11}\\bra{11} \\otimes X $ &  %$ \\ket{000}\\bra{000} + \\ket{001}\\bra{001} + \\ket{010}\\bra{010} + \\ket{011}\\bra{011} + \\ket{100}\\bra{100} + \\ket{101}\\bra{101} + \\ket{110}\\bra{111} + \\ket{111}\\bra{110} $ &\n    $ \\text{CCNOT} \\ket{\\psi} = \\alpha\\ket{000} + \\beta\\ket{001} + \\gamma\\ket{010} + \\delta\\ket{011} + \\epsilon\\ket{100} + \\lambda\\ket{101}  + $ \\boldmath$ \\kappa \\ket{110} + \\eta\\ket{111} $ &\n    $ \\text{CCNOT} \\ket{000} = \\ket{000} \\newline \\text{CCNOT} \\ket{001} = \\ket{001} \n      \\newline \\text{CCNOT} \\ket{010} = \\ket{010} \\newline \\text{CCNOT} \\ket{011} = \\ket{011} $ &\n     $ \\text{CCNOT} \\ket{100} = \\ket{100} \\newline \\text{CCNOT} \\ket{101} = \\ket{101} \\newline \n       \\text{CCNOT} \\ket{110} = \\ket{111} \\newline \\text{CCNOT} \\ket{111} = \\ket{110} $\\\\\n  \n  \\end{keysrefMultiGates}\n\n\\end{document} \n", "meta": {"hexsha": "08ebf7bffefaef35d81881d8983d430a6b2b8cb1", "size": 34886, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "quickref/qsharp-quick-reference.tex", "max_stars_repo_name": "raffaeleterribile/quantum-katas", "max_stars_repo_head_hexsha": "d0616b148fc3914c1fa5ed4140fa371846ebb284", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "quickref/qsharp-quick-reference.tex", "max_issues_repo_name": "raffaeleterribile/quantum-katas", "max_issues_repo_head_hexsha": "d0616b148fc3914c1fa5ed4140fa371846ebb284", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "quickref/qsharp-quick-reference.tex", "max_forks_repo_name": "raffaeleterribile/quantum-katas", "max_forks_repo_head_hexsha": "d0616b148fc3914c1fa5ed4140fa371846ebb284", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1267759563, "max_line_length": 268, "alphanum_fraction": 0.5554377114, "num_tokens": 12568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.3458206285736102}}
{"text": "\\documentclass[../main.tex]{subfiles}\n\n\\begin{document}\n    \n\\chapter{Learning Methods Survey} \\label{learning_methods_survey}\n\n\nIn this chapter, we outline a set of ideal characteristics and desired behavior of an ideal candidate classification algorithm, and conduct a survey of potential unsupervised learning methods. We then evaluate each of these surveyed methods against our selection criteria, and determine the optimal method with which to proceed.\n\n\\section{Evaluation Criteria}\n\nDespite being not entirely objective, existing classification heuristics have a range of desirable behavior that we would wish to replicate with our candidate clustering algorithm. Additionally, we would want to replicate this behavior while also maintaining objectivity and stability in our new heuristic by utilizing a highly nonparametric learning method.\n\nIn particular, we would be extremely interested in preserving the nested hierarchical clustering behavior of the current schemes. That is, to be able to classify a market into sectors, and in turn those sectors into subsectors. Furthermore, it would be desirable to be able to determine these nested sub-sectors in the context of the greater market, rather than in isolated analysis of a particular sector.\n\nAdditionally, we would also like to vary the number of resulting sectors of our algorithm while maintaining stability. That is, if we were to request two sectors from a heuristic that was initially resulting in four sectors, the two sectors would be some combination of the initial four sectors, as opposed to an entirely new segmentation profile. This behavior is reflective of the real world, where economic sectors often exhibit nesting, as opposed to independent clustering.\n\nFinally, as per RG-1 (see Section~\\ref{research_goals:specific_research_goals}), we are extremely motivated to design a heuristic that is either entirely non-parametric, or parameterized with highly objective, quantitatively derived criteria. In addition to preserving mathematical objectivity of our results, a nonparametric approach would ensure that no personal biases - either explicit or implicit - are introduced to the final learned sectors.\n\n\n\\section{Candidate Learning Methods}\n\nGiven the required behavior outlined above, we evaluated three major families of clustering algorithms. We empirically evaluate each clustering technique through the lens of the requirements outlined above.\n\n\n\\subsection{$K$-means Clustering}\n\n$K$-Means Clustering is a method of partitioning $n$-dimensional data into a set of $K$ distinct clusters. The basic algorithm is outlined below\\citeFormat{\\cite{Lloyd1982LeastPCM}}:\n\n\\begin{gather*}\n    \\text{Let $C_1, C_2, \\ldots, C_K$} = \\text{Set of K possible clusters} \\\\\n    \\text{Let $W(C_k)$} = \\text{Measure of pariwise difference of observations in a cluster} \\\\\n    \\text{Let $x_{ij}$} = \\text{$j^\\text{th}$ feature in cluster $i$ with coordinates $x$} \\\\\n    \\Rightarrow W(C_k) = \\frac{1}{|C_k|} \\sum_{i, i^\\prime \\in C_k} \\sum_{j = 1}^p (x_{ij} - x_{i^\\prime j})^2 \\\\\n    \\\\\n    \\Rightarrow \\text{$K$-Means Clusters}\n    = \\underset{C_1, \\ldots, C_k}{\\text{minimize}} \\sum_{k=1}^K W(C_k)\n    = \\underset{C_1, \\ldots, C_k}{\\text{minimize}} \\sum_{k=1}^K \\frac{1}{|C_k|} \\sum_{i, i^\\prime \\in C_k} \\sum_{j = 1}^p (x_{ij} - x_{i^\\prime j})^2\n\\end{gather*}\n\nNotice that in the algorithm outlined above, the $K$-means clustering process requires two sets of parameters at initialization. First, it requires the number of target clusters, $K$, as well as a set of random initializations for cluster centroids, $\\frac{1}{|C_k} \\sum_{i \\in C_k} x_{ij}$. This high level of parameterization, coupled with the clear lack of congruity of assignment across varying values of $K$ make this family of algorithms poorly suited to the task of sector classification, as per the constraints detailed above.\n\n\\subsection{Support Vector Classifier}\n\nThe support vector classifier is based on the notion of finding a set of hyperplanes in a higher dimensional feature space that optimally divides a set of data into classes. Data is mapped to a higher dimensional space to ensure orthogonal hyperplanes in the divisions of the clusters. The support vector classifier objective function is outlined below\\citeFormat{\\cite{Ben-Hur2001SupportClustering}}:\n\n\\begin{equation*}\n    \\begin{aligned}\n        & \\underset{R, a, \\boldsymbol{\\alpha}}{\\text{minimize}} & & R^2 - \\sum_i \\alpha_i (R^2 - ||x_i - a||^2) \\\\\n        & \\text{subject to}\n        & & \\alpha_i \\geq 0 \\\\\n        & & & (R^2 - ||x_i - a||^2) = 0 \\; \\forall \\; i \\; \\text{(KKT Condition)}\n    \\end{aligned}\n\\end{equation*}\n\nAs indicated by the literature, and through inspection of the objective function, it is clear that the support vector classifier is parameterized on the kernel used for optimization, as well as the specific loss function employed during model training. Furthermore, this model also optimizes to a fixed numbed of sectors, as opposed to a dynamic number. Therefore, this method too is inappropriate as per the evaluation criteria.\n\n\\subsection{Hierarchical Cluster Analysis} \\label{learning_methods_survey:hca}\n\nHierarchical clustering is a greedy algorithm which seeks to build clusters following either an agglomerative, or a divisive approach.\\citeFormat{\\cite{Ward1963HierarchicalFunction}} Agglomerative clustering is \\textit{bottom-up}, with each observation starting it its own cluster, whereas divisive is \\textit{top-down}, with all observations starting in one cluster and splits performed recursively at each level. The clusters output by this algorithm are determined by two model settings; the distance metric (i.e. the algorithm for computation of pairwise distance between observations), and the linkage method, which specifies the algorithm governing the dissimilarity of entire sets, as a function of the pairwise distances of observations in those sets.\n\nThis method has the distinct advantage of being entirely additively hierarchical, with groups being nested as described in the evaluation criteria. Furthermore, this method is entirely nonparametric, with the sole exception being the choice of linkage and distance metric. Additionally, it is extremely stable with varying sector counts. This is a direct result of the greedy nature of the algorithm, as it does not recompute the hierarchy each time a new cluster arity is extracted, but rather just changes the level of extraction from the same hierarchy.\n\nAs per the evaluation of the different families of learning methods detailed in this chapter, we selected Hierarchical Clustering to be the basis of our Learned Sectors classification heuristic.\n\n\n\\end{document}", "meta": {"hexsha": "ef8e0bf852541e12993a87f42c2ef08c95263e43", "size": 6687, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "sections/05_learning_methods_survey.tex", "max_stars_repo_name": "rukmal/FE-800-Learned-Sectors-Report", "max_stars_repo_head_hexsha": "f60f09dc689c4adc172b576a261df5ed77518f8f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-14T08:39:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T08:39:24.000Z", "max_issues_repo_path": "sections/05_learning_methods_survey.tex", "max_issues_repo_name": "rukmal/MS-Thesis-Learned-Sectors-Report", "max_issues_repo_head_hexsha": "f60f09dc689c4adc172b576a261df5ed77518f8f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 39, "max_issues_repo_issues_event_min_datetime": "2019-05-13T22:30:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-17T03:37:55.000Z", "max_forks_repo_path": "sections/05_learning_methods_survey.tex", "max_forks_repo_name": "rukmal/MS-Thesis-Learned-Sectors-Report", "max_forks_repo_head_hexsha": "f60f09dc689c4adc172b576a261df5ed77518f8f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-06-01T06:32:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-01T06:32:20.000Z", "avg_line_length": 99.8059701493, "max_line_length": 759, "alphanum_fraction": 0.7803200239, "num_tokens": 1511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.3458206210919017}}
{"text": "\\section{Performance Analysis}\\label{sec:analysis}\n\nIn this section we analyze and discuss the overhead of the CCVPN design with respect\nto the additional processing time and state consumption needed to handle traffic.\n\n\\subsection{State Consumption}\nThe CCVPN design has an immediate impact on the FIB and PIT size of a gateway.\n(The content store size remains unaffected since only decapsulated content objects\nare ever cached.) Let $F_S$ be the total size of a standard forwarder\nFIB in terms of bytes and\n$N_F$ be the number of entries in the FIB. For simplicity, we will assume that\neach name prefix in the FIB has a constant size of $64$B. In practice we expect\nthis to be a comfortable upper bound. Thus, $F_S = N_Fs$, where $s$ is the size of\neach FIB entry. Here, $s$ includes a name prefix (of size $64$B) and a bit vector\nthat identifies the matching links for the interface. We assume that a gateway has\n$128$ links which, again, is a comfortable upper bound. Therefore, $F_S = 80N_F$B.\nNow consider the FIB size $F_G$ for a CCVPN gateway. Some entries in these FIBs will\npoint to ``private'' prefixes, i.e., other domains, and therefore have a larger size\nto account for the corresponding prefix and key material that must be stored.\nFor both public- and symmetric-key encryption, the key size is the same: $32$B \\cite{sodiumGithub}.\nTherefore, by taking into account two both the FIB entry prefix key, translation\nprefix, encryption key, and corresponding bit vector, the total size of one ``private''\nFIB entry will be $176$B, meaning that $F_G = 176N_F$B. By comparing $F_S$ to $F_G$, we\nsee that, in the worst case, the CCVPN FIB is at most $F_G/F_S = 176/80 = 2.2$ times larger\nthan the standard FIB. In practice, however, we expect this to be much smaller, since the\nfraction of public to private FIB entries in a gateway will be non-zero.\n\nWe will now apply the same analysis to the PIT size. A standard PIT entry includes a\ncomplete name and ingress bit vector. (They may also include the optional {\\tt KeyId}\nand {\\tt ContentId}, but since they are included in the gateway PIT as well we omit them\nfrom this analysis.) A gateway PIT entry will contain the same elements of a standard\nPIT entry but also a symmetric encryption key ($32$B), nonce ($12$B), and an\nencapsulation name ($64$B + $32$B).\nThe encapsulation name is the name of an encapsulated interest and includes an additional\n$32$B {\\tt PayloadID} segment to identify the encapsulated value in the payload. Let\n$P_S$ and $P_G$ be the sizes of the standard and gateway PIT, respectively, and let $N_P$\nbe the number of PIT entries in one such table. Based on the above discussion, and assuming\nagain that a name is at most $64$B, a standard PIT entry is of the size $80$B. In contrast,\na gateway PIT entry is of size $204$B. Therefore, in the worst case, the CCVPN PIT\nwill be at most $P_G / P_S = 204/80 = 2.55$B larger than the standard PIT. Assuming\na steady state size of approximately $1e^5$ entries \\cite{carofiglio2015pending},\nthis means that the PIT will be $20.4$MB, which is well within the capacity of\nmodern systems.\n\n\\subsection{Processing Overhead}\nIn terms of processing overhead, the gateway adds a number of new steps to the data\npath of a packet. The main computational burdens are packet encapsulation and decapsulation.\nIn the public-key variant of CCVPN, interests are processed using public-key encryption,\nwhereas content is always processed using symmetric-key encryption. Let $T_E^P(n)$ and $T_D^P(n)$\nbe the time to encrypt and decrypt $n$B of data using a suitable public-key encryption scheme.\nSimilarly, let $T_E^S(n)$ and $T_D^S(n)$ be the time to encrypt and decrypt $n$B of data\nusing a symmetric-key encryption scheme. Then, the latency in a single interest-content\nexchange is increased by $T = T_E^P(n_I) + T_D^P(n_I) + T_E^S(n_C) + T_D^S(n_C)$, where\n$n_I$ and $n_C$ are the original interest and content sizes, respectively. As a rough\nestimate, \\cite{benchmarks} lists the cost of AES-GCM to be $2.946\\mu s$ for setup\nfollowed by $102$MiB/second Intel Core 2 1.83 GHz processor under Windows Vista in\n32-bit mode (with AES ISA support). For packets that are at most $1500$B,\nthe total processing time is roughly $17\\mu s$. Moreover, The public-key encryption and\ndecryption operations will always be at least as expensive, so the total latency is\nincreased by at least $T = 4 \\times 17\\mu s = 68 \\mu s$. In comparison to the network\nlatency for a single packet this may not be noticable, but for a steady arrival state of\napproximatey $1e^5$, this would lead to an instable system that would quickly overflow.\n(This is because $65 \\mu s \\times 1e^5 = 6.8s$.) Therefore, there is an upper bound on\nthe number of private packets a gateway can process per second. This bound is entirely\ndependent on the system configuration and network conditions.\n\nAnother performance deficiency comes from the fact that gateways cannot process packets\nwithout allocating memory. Specifically, each packet requires either an encryption\nor decryption. However, this cannot be done entirely in-place, the gateway must allocate some amount\nof memory for every processed packet, e.g., to store the MAC tag, to account for\nciphertext expansion, or to apply padding, if desired. This overhead can outweigh\nthe cryptographic computations if the packet arrival rate is high enough. Therefore,\nwhen implementing CCVPN, special care must be taken to ensure that memory allocations\nare minimized or avoided where possible.\n", "meta": {"hexsha": "a6617079f76817a00694d6d084ee90ea977d27ee", "size": 5515, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/06-perf-analysis.tex", "max_stars_repo_name": "chris-wood/ccvpn", "max_stars_repo_head_hexsha": "61994629f6ebec54425ff3dfa7992a71ba3cc9a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paper/06-perf-analysis.tex", "max_issues_repo_name": "chris-wood/ccvpn", "max_issues_repo_head_hexsha": "61994629f6ebec54425ff3dfa7992a71ba3cc9a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/06-perf-analysis.tex", "max_forks_repo_name": "chris-wood/ccvpn", "max_forks_repo_head_hexsha": "61994629f6ebec54425ff3dfa7992a71ba3cc9a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 73.5333333333, "max_line_length": 100, "alphanum_fraction": 0.7747960109, "num_tokens": 1390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3458206210919017}}
{"text": "\\documentclass{article}\n\\usepackage{hyperref}\n\\usepackage{amsmath,amssymb}\n\\usepackage{graphicx}\n\\usepackage{caption}\n\\usepackage{subcaption}\n\\usepackage[section]{placeins}\n\\renewcommand{\\thesubsection}{\\thesection.\\alph{subsection}}\n\\usepackage{listings}\n\n\\title{\\bf{CSE397: Assignment \\#1}}\n\\author{Nicholas Malaya \\\\ Institute for Computational Engineering and Sciences \\\\ University of Texas at Austin} \\date{}\n\n\\begin{document}\n\\maketitle\n\n\\newpage\n\\section{Problem 1}\n\n\\begin{figure}[!htb]\n  \\includegraphics[scale=.5]{plots/data.pdf}\n  \\label{fig:data}\n  \\caption{The data (after applying the filter) with and without\n normally distributed noise. } \n\\end{figure}\n\nAfter applying the new filter $k(x)$ and adding gaussian noise, the data\nused as input for the inverse problem is plotted in figure 1. \n\nNotice that this filter is significant: the raw data generated after\npassing through the filter (even without statistical noise) has lost\nseveral features of the underlying ``true'' signal. \n\n\\subsection{$T_{\\text{SVD}}$}\n\n\n\\begin{figure}[!htb]\n        \\centering\n        \\begin{subfigure}[bh]{0.45\\textwidth}\n                \\includegraphics[width=\\textwidth]{plots/tsvd0001.pdf}\n                \\caption{$\\alpha=0.0001$}\n        \\end{subfigure}%\n        \\begin{subfigure}[bh]{0.45\\textwidth}\n                \\includegraphics[width=\\textwidth]{plots/tsvd001.pdf}\n                \\caption{$\\alpha=0.001$}\n        \\end{subfigure}\n        \\centering\n        \\begin{subfigure}[bh]{0.45\\textwidth}\n                \\includegraphics[width=\\textwidth]{plots/tsvd01.pdf}\n                \\caption{$\\alpha=0.1$}\n        \\end{subfigure}%\n        \\begin{subfigure}[bh]{0.45\\textwidth}\n                \\includegraphics[width=\\textwidth]{plots/tsvd1.pdf}\n                \\caption{$\\alpha=1.0$}\n        \\end{subfigure}\n        \\caption{$T_{\\text{SVD}}$ at varying values of $\\alpha$.}\n        \\label{fig:svd}\n\\end{figure}\n\nFigure \\ref{fig:svd} plots the solution to the inverse problem using\nTruncated SVD at several different values of $\\alpha$, the\nregularization parameter. We can see that actually, the filter nicely\nregularizing the inverse problem even for small values of $\\alpha$. It\nis only for the largest value of $\\alpha$ that the parameter is obviously\ntoo large, at which point almost all the frequencies are filtered out,\nand the solution to the inverse problem is constant and zero. \n\nAs expected, none of the solutions capture any of the very fine (high\nfrequency) features of the original data. \n\n\\subsection{Tikhanov Filter}\n\n\n\\begin{figure}[!htb]\n        \\centering\n        \\begin{subfigure}[bh]{0.45\\textwidth}\n                \\includegraphics[width=\\textwidth]{plots/reconstruct0001.pdf}\n                \\caption{$\\alpha=0.0001$}\n        \\end{subfigure}%\n        \\begin{subfigure}[bh]{0.45\\textwidth}\n                \\includegraphics[width=\\textwidth]{plots/reconstruct001.pdf}\n                \\caption{$\\alpha=0.001$}\n        \\end{subfigure}\n        \\centering\n        \\begin{subfigure}[bh]{0.45\\textwidth}\n                \\includegraphics[width=\\textwidth]{plots/reconstruct01.pdf}\n                \\caption{$\\alpha=0.1$}\n        \\end{subfigure}%\n        \\begin{subfigure}[bh]{0.45\\textwidth}\n                \\includegraphics[width=\\textwidth]{plots/reconstruct1.pdf}\n                \\caption{$\\alpha=1.0$}\n        \\end{subfigure}\n        \\caption{Solutions to the inverse problem using Tikhanov\n regularization at varying values of $\\alpha$.} \n \\label{fig:tik}\n\\end{figure}\n\nFigure \\ref{fig:tik} plots the solution to the inverse problem using\nTikhanov regularization at several different values of $\\alpha$, the\nregularization parameter.  \n\nThe Tikhanov filter is more sensitive, with (a) and (b) (low values of\n$\\alpha]$) completely being dominated by noise. None of the underlying\nsignal is regained, as all the high frequency content blown up and\ndominating. \n\nFor higher levels of the regularization parameter, we regain a solution\nsimilar to in the TSVD cases, where we capture the underlying trend of\nthe data, but none of the sharp features. Also, the highest value of the\nfilter does not overwhelm the signal completely, as in the TSVD case,\nwhich is interesting. \n\n\n\\subsection{L-Curve}\n\n\\begin{figure}[!htb]\n  \\includegraphics[scale=.6]{plots/L-curve.pdf}\n  \\caption{The L-curve} \n \\label{fig:lcurve}\n\\end{figure}\n\nFigure \\ref{fig:lcurve} plots the results of the L-curve criterion. The\nred dot plotted is at 0.01. This is approximately the ``optimal'' value\nof regularization, which is generally consistent with the observations\nof the previous plots. \n\n\n\\subsection{Morozov's Discrepancy Criterion}\n\n\\begin{figure}[!htb]\n  \\includegraphics[scale=.5]{plots/morozov.pdf}\n  \\caption{Morozov discrepancy Criterion} \n \\label{fig:moro}\n\\end{figure}\n\nFigure \\ref{fig:moro} plots the results of Morozov discrepancy\ncriterion. I could not get the plots to draw a horizontal line, so that\nred dot instead dictates the limit of $\\delta$, the norm of the\nerror. This occurs at $\\approx 4e-2$. This is smaller than the value\nobtained using the L-curve, but not so much smaller that the value\nappears suspect. \n\n\n\\subsection{Actual Error}\n\n\\begin{figure}[!htb]\n  \\includegraphics[scale=.5]{plots/true1d.pdf}\n  \\caption{The actual error in the reconstruction as a function of\n alpha. } \n \\label{fig:actual}\n\\end{figure}\n\nFigure \\ref{fig:actual} plots actual error in the reconstruction,\ne.g. the norm of the difference between the reconstruction and the\nactual (true) image, as a function of alpha. You can see that this\nplot forms a rotated ``S'' curve, with the minimum occuring\napproximately at the red dot. The value plotted is 0.01,\nwhich actually agrees with the L-curve estimate. \n\nIn any case, the values arrived at using the L-curve, Morozov's\ndiscrepancy criterion and the actual error all agree within at least an\norder of magnitude. So we are in the right ``ballpark''. As an aside, I\nwas actually quite pleased with the result, I would not have expected\nthese criterion to so closely arrive at values that are reasonable\nguesses, even without knowledge of the true underlying signal. While\nthis is a toy problem, it does show that these criterion can be\neffective means of approximating $\\alpha$. Given the similarities\nbetween the TSVD and Tikhanov, I would not be surprised to find that\nthese heuristics can be more generally useful for other regularizations as well. \n\n\n\\newpage\n\\section{Problem 2}\n\n% \\begin{figure}[!htb]\n%   \\includegraphics[scale=.5]{plots/longhorn.png}\n%   \\label{fig:true}\n%   \\caption{The true image.} \n% \\end{figure}\n\n% Figure \\ref{fig:true} plots the true image, that we will be attempting\n% to reconstruct through inversion. \n\n\\subsection{Memory Requirement}\n\nHow much memory would be required to form the entire matrix, $K$?\nWe have $N^2$ model parameters. K lives in $\\mathbb{R}^{N_2 * N_2}$. \nWith $N=128$, then \n\\begin{equation}\n\\frac{N^2 * N^2 * 8 \\text{Bytes}}{(1024)^3} = 2 \\text{GB}\n\\end{equation}\nSo while this is not inaccessible on modern HPC systems, it is certainly\nnot efficient.  \n\n\\subsection{L-Curve}\n\n\\begin{figure}[!htb]\n  \\includegraphics[scale=.5]{plots/L-curve2d.pdf}\n  \\caption{The L-curve for the 2d problem.} \n  \\label{fig:l2d}\n\\end{figure}\n\nFigure \\ref{fig:l2d} plots the L-curve. The red dot is approximately at\nthe location of the optimal value of $\\alpha$, which is found to be\n$\\approx 0.05 - 0.001$. \n\n\\subsection{Actual Error}\n\n\\begin{figure}[!htb]\n  \\includegraphics[scale=.5]{plots/2d-true.pdf}\n  \\caption{The actual error in the reconstruction as a function of\n alpha, for the 2d problem.} \n  \\label{fig:2dt}\n\\end{figure}\n\nFigure \\ref{fig:2dt} plots the true error. Surprisingly, the error curve\nappears to flatten out at lower values of alpha, implying a constant\nerror. Clearly any values less than $1e-3$ appear to be prefered, as the\nerror increases at higher values of $\\alpha$. \n\nTo calculate the error, I only needed to solve the conjugate gradient\n(as before) and then calculate the norm of the misfit against $I$, the\ntrue image:\n\\begin{lstlisting}\n I_alpha = pcg(@(in)apply(in,K1,K2,N1,N2,alpha),K_Ibn(:),1e-6,1500);\n misfit(k) = norm((K1 * (K2 * reshape(I_alpha,N2,N1))')' - I);        \n\\end{lstlisting}\n\\begin{figure}[!htb]\n        \\centering\n        \\begin{subfigure}[bh]{0.65\\textwidth}\n                \\includegraphics[width=\\textwidth]{plots/tikrecon0001.pdf}\n                \\caption{$\\alpha=0.0001$}\n        \\end{subfigure}%\n        \\begin{subfigure}[bh]{0.65\\textwidth}\n                \\includegraphics[width=\\textwidth]{plots/tikrecon001.pdf}\n                \\caption{$\\alpha=0.001$}\n        \\end{subfigure}\n \\caption{The reconstructed image.}  \n\\label{fig:tik}\n\\end{figure}\n\nThe ``true'' image would imply then that the L-curve is too conservative\nan estimate, and smaller values of $\\alpha$ are acceptable. However, I\ndon't believe that. Figure 9 plots the Tikhanov\nreconstruction for $\\alpha = 0.001$ and $\\alpha = 0.0001$. Clearly the\ntrue image is recognizable in the right hand side, and not at all in the\nleft. So I believe that I either have a bug in my calculation of the\nactual error, or the L-curve is, somehow, a more reliable estimate of\n``good'' values of $\\alpha$, here. \n\n\\end{document}", "meta": {"hexsha": "d6a3d78accbaecf58595e021b7de7d4af3e0ba23", "size": 9214, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "inv_prob/ps1/report.tex", "max_stars_repo_name": "nicholasmalaya/paleologos", "max_stars_repo_head_hexsha": "11959056caa80d3c910759b714a0f8e42f986f0f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-04T17:49:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T17:49:42.000Z", "max_issues_repo_path": "inv_prob/ps1/report.tex", "max_issues_repo_name": "nicholasmalaya/paleologos", "max_issues_repo_head_hexsha": "11959056caa80d3c910759b714a0f8e42f986f0f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inv_prob/ps1/report.tex", "max_forks_repo_name": "nicholasmalaya/paleologos", "max_forks_repo_head_hexsha": "11959056caa80d3c910759b714a0f8e42f986f0f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-01-04T16:08:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-16T19:34:24.000Z", "avg_line_length": 36.7091633466, "max_line_length": 121, "alphanum_fraction": 0.7100065118, "num_tokens": 2529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.3458206210919017}}
{"text": "% !TEX root = ../../../proposal.tex\n\n\\section{TLS}\\label{sec:subgroup_tls}\n\nTLS (Transport Layer Security) is a transport layer protocol designed to provide confidentiality,\nintegrity and (most commonly) one-side authentication for application sessions. \nIt is widely used to protect HTTP and mail protocols. \n\nA TLS client initiates a TLS handshake with the \\texttt{Client\\-Hello} message.\nThis message includes a list of supported cipher suites, and a client random\nnonce $r_c$. The server responds with a \\texttt{Server\\-Hello} message containing\nthe chosen cipher suite and server random nonce $r_s$, and a\n\\texttt{Certificate} message that includes the server's X.509 certificate. If\nthe server selects a cipher suite using ephemeral Diffie-Hellman key exchange,\nthe server additionally sends a \\texttt{Server\\-Key\\-Exchange} message containing\nthe server's choice of Diffie-Hellman parameters $p$ and $g$, the server's\nDiffie-Hellman public value $y_s = g^{x_s} \\bmod p$, a signature by the\nserver's private key over both the client and server nonces ($r_c$ and $r_s$),\nand the server's Diffie-Hellman parameters ($p$, $g$, and $y_s$). The client\nthen verifies the signature using the public key from the server's certificate,\nand responds with a \\texttt{Client\\-Key\\-Exchange} message containing the client's\nDiffie-Hellman public value $y_c = g^{x_c} \\bmod p$. The Diffie-Hellman shared\nsecret $Y = g^{x_s x_c} \\bmod p$ is used to derive encryption and MAC keys. The\nclient then sends \\texttt{Change\\-Cipher\\-Spec} and \\texttt{Finished} messages. The\n\\texttt{Finished} message contains a hash of the handshake transcript, and is\nencrypted and authenticated using the derived encryption and MAC keys. Upon\ndecrypting and authenticating this message, the server verifies that the hash\nof the transcript matches the expected hash.  Provided the hash matches, the\nserver then sends its own \\texttt{Change\\-Cipher\\-Spec} and \\texttt{Finished}\nmessages, which the client then verifies. If either side fails to decrypt or\nauthenticate the \\texttt{Finished} messages, or if the transcript hashes do not\nmatch, the connection fails immediately~\\cite{rfc5246}.\n\nTLS also specifies a mode of using Diffie-Hellman with fixed parameters from\nthe server's certificate~\\cite{rfc3279}. This mode is not forward secret, was\nnever widely adopted, and has been removed from all modern browsers due to\ndangerous protocol flaws~\\cite{kci-tls-2015}. The only widely used form of\nDiffie-Hellman in TLS today is ephemeral Diffie-Hellman, described above.\n\n\\subsection{Small Subgroup Attacks in TLS}\n\\label{sec:tls-subgroup-attack}\n\n\\paragraph{Small subgroup confinement attacks}\nA malicious TLS server can perform a variant of the small subgroup attack\nagainst a client by selecting group parameters $g$ and $p$ such that $g$\ngenerates an insecure group order. TLS versions prior to 1.3 give the server\ncomplete liberty to choose the group, and they do not include any method for\nthe server to specify the desired group order $q$ to the client.  This means a\nclient has no feasible way to validate that the group sent by the server has the\ndesired level of security or that a server's key exchange value is in\nthe correct group for a non-safe prime.\n\\looseness=-1\n\nSimilarly, a man in the middle with knowledge of the server's long-term private\nsigning key can use a small subgroup confinement attack to more easily\ncompromise perfect forward secrecy, without having to rewrite an entire\nconnection. The attack is similar to the those described by Bhargavan and\nDelignat-Lavaud~\\cite{bhargavan-channel-bindings-2015}. The attacker modifies the\nserver key exchange message, leaving the prime unchanged, but substituting a\ngenerator $g_i$ of a subgroup of small order $q_i$ for the group generator and \n$g_i$ for the server's key exchange value $y_s$. The attacker then forges a correct signature for the modified server key exchange message and passes it to the client.  The client then\nresponds with a client key exchange message $y_c = g_i^{x_c} \\bmod p$, which\nthe man-in-the-middle leaves unchanged. The server's view of the shared secret\nis then $g_i^{x_c x_s} \\bmod p$, and the client's view of the shared secret is\n$g_i^{x_c} \\bmod p$. These views are identical when ${x_s} \\equiv 1 \\bmod q_i$,\nso this connection will succeed with probability $1/q_i$. For small enough\n$q_i$, this enables a man in the middle to use a compromised server signing key to\ndecrypt traffic from forward-secret ciphersuites with a reasonable probability\nof success, while only requiring tampering with a single handshake message,\nrather than having to actively rewrite the entire connection for the duration of the session.\n\nFurthermore, if the server uses a static Diffie-Hellman key exchange value,\nthen the attacker can perform a small subgroup key-recovery attack as the\nclient in order to learn the server's static exponent $x_s \\bmod q_i$ for the\nsmall subgroup. This enables the attacker to calculate a custom generator such\nthat the client and server views of the shared secret are always identical,\nraising the above attack to a 100\\% probability of success.\n\n\n\\paragraph{Small subgroup key recovery attacks} In TLS, the client must\nauthenticate the handshake before the server, by providing a valid\n\\texttt{Finished} message. This forces a small subgroup key recovery attack\nagainst TLS to be primarily online. To perform a Lim-Lee small subgroup key\nrecovery attack against a server static exponent, a malicious client initiates\na TLS handshake and sends a generator $g_i$ of a small subgroup of order $q_i$\nas its client key exchange message $y_c$.  The server will calculate $Y_s =\ng_i^{x_s} \\bmod p$ as the shared secret. The server's view of the shared secret\nis confined to the subgroup of order $q_i$.  However, since $g_i$ and $g$\ngenerate separate subgroups, the server's public value $y_s = g^x_s$ gives the\nattacker no information about the value of the shared secret $Y_s$. Instead,\nthe attacker must guess a value for $x_s \\bmod q_i$, and send the corresponding\nclient \\texttt{Finished} message. If the server continues the handshake, the\nattacker learns that the guess is correct.  Therefore, assuming the server is\nreusing a static value for $x_s$, the attacker needs to perform at most $q_i$\nqueries to learn the  server's secret $x_s \\bmod q_i$~\\cite{lim-1997}. This\nattack is feasible if $q_i$ is small enough and the server reuses\nDiffie-Hellman exponents for sufficiently many requests.\n\nThe attacker repeats this process for many different primes $q_i$, and uses the\nChinese remainder theorem to combine them modulo the product of the primes\n$q_i$.  The attacker can also use the Pollard lambda algorithm to reconstruct\nany remaining bits of the exponent~\\cite{lim-1997}.\n\nWe note that the TLS False Start extension allows the\nserver to send application data before receiving the client's authentication~\\cite{rfc7918}.\nThe specification only allows this behavior for abbreviated handshakes, which\ndo not include a full key exchange.  If a full key exchange were allowed, the\nfact that the server authenticates first would allow a malicious client to\nmount a mostly offline key recovery attack.\n%\\todo{Add discussion of the old unused TLS extension that makes this offline. \\ref{rfc7918}}\n\n\n\n\\subsection{OpenSSL}\n\nPrior to early 2015, OpenSSL defaulted to using static-ephemeral Diffie-Hellman\nvalues. Server applications generate a fresh Diffie-Hellman secret exponent on\nstartup, and reuse this exponent until they are restarted.  A server would be\nvulnerable to small subgroup attacks if it chose a DSA prime, explicitly\nconfigured the \\texttt{dh->length} parameter to generate a short exponent, and\nfailed to set \\texttt{SSL\\_OP\\_SINGLE\\_DH\\_USE} to prevent repeated exponents.\nOpenSSL provides some test code for key generation which configures DSA group\nparameters, sets an exponent length to the group order, and correctly sets the\n\\texttt{SSL\\_OP\\_SINGLE\\_DH\\_USE} to generate new exponents on every\nconnection.  We found this test code widely used across many applications.  We\ndiscovered that Unbound, a DNS resolver, used the same parameters as the tests,\nbut without setting \\texttt{SSL\\_OP\\_SINGLE\\_DH\\_USE}, rendering them\nvulnerable to a key recovery attack.  A number of other applications including\nLighttpd used the same or similar code with non-safe primes, but correctly set\n\\texttt{SSL\\_OP\\_SINGLE\\_DH\\_USE}.\n\nIn spring 2015, OpenSSL added explicit support for RFC~5114\ngroups~\\cite{openssl-changelog-102}, including the ability for servers to\nspecify a subgroup order in a set of Diffie-Hellman group parameters. When the\nsubgroup order is specified, the exponent length is automatically adjusted to\nmatch the subgroup size.  However, the update did not contain code to validate\nsubgroup order for key exchange values, leaving OpenSSL users vulnerable to\nprecisely the key recovery attack outlined in\nSection~\\ref{sec:tls-subgroup-attack}.\n\nWe disclosed this vulnerability to OpenSSL in January 2016. The vulnerability\nwas patched by including code to validate subgroup order when a subgroup was\nspecified in a set of Diffie-Hellman parameters and setting\n\\texttt{SSL\\_OP\\_SINGLE\\_DH\\_USE} by default~\\cite{openssl-secadv-subgroup}.\nPrior to this patch, any code using OpenSSL for DSA-style Diffie-Hellman\nparameters was vulnerable to small subgroup attacks by default.\n\n\\ApplicationsTable\n\nExim~\\cite{exim}, a popular mail server that uses OpenSSL, provides a clear\nexample of the fragile situation created by this update. By default, Exim uses\nthe RFC~5114 Group 23 parameters with OpenSSL, does not set an exponent length,\nand does not set \\texttt{SSL\\_OP\\_SINGLE\\-\\_DH\\_USE}. In a blog post, an Exim\ndeveloper explains that because of ``numerous issues with automatic generation\nof DH parameters'', they added support for fixed groups specified in RFCs and picked\nGroup~23 as the default~\\cite{exim-blog}.  Exim narrowly avoided being fully\nvulnerable to a key recovery attack by not including the size of the subgroup\ngenerated by $q$ in the Diffie-Hellman parameters that it passes to OpenSSL.\nHad this been included, OpenSSL would have automatically shortened the exponent\nlength, leaving the server fully vulnerable to a key recovery attack.  For this\ngroup, an attacker can recover 130 bits of information about the secret\nexponent using $2^{33}$ online queries, but this does not allow the attacker to\nrecover the server's 2048-bit exponent modulo the correct 224-bit group order\n$q$ as the small subgroup orders $q_i$ are all relatively prime to $q$.\n\nWe looked at several other applications as well, but did not find them to be\nvulnerable to key recovery attacks (Table~\\ref{tab:common-applications}).\n\n\n% comprising 53.62\\% of all such servers~\\cite{esoft2016}.\n\n% Exim can be compiled either with GNU TLS or with OpenSSL. When compiled with OpenSSL,\n% it supports single use DH keys with an option that is off by default\n% (as of version 4.87, the latest at time of writing). In OpenSSL mode, it\n% includes checks for unsafe primes and incorrect generators, however it\n% ignores the generator check when the generator is not 2 or 5, due to a known\n% bug in OpenSSL. More significantly, it utilizes the DSA primes with small\n% subgroups. Their code comments note ``These have been thoroughly reviewed as\n% meeting certain eligibility criteria, which is more than can be said for primes\n% generated quickly''. However, they fail to note the difference in criteria for\n% the DSA primes as opposed to the others, resulting in the selection of vulnerable\n% groups. The subgroup size $q$ was not included in the Exim's default DSA parameter, saving \n% a default Exim installation from being vulnerable to the attack described \n% in Section~\\ref{sec:tls-subgroup-attack} due the fact that OpenSSL did not have the possibility \n% to match the exponent length to subgroup size. Said that, if the DSA parameter would have been generated using the \n% OpenSSL's genpkey utility~\\cite{genpkey} all the conditions to perform the Small subgroup key recovery attack\n% as per Section ~\\ref{sec:tls-subgroup-attack} would have been met.\n% In comparison Postfix an MX  utilized for 32.80\\% of mail servers~\\cite{esoft2016}\n% suggests generating a group at install time but neglects to set the single use OpenSSL option\n% and includes two hardcoded groups by default.\n\n\\subsection{Other Implementations} \\label{subsec:nss}\n\nWe examined the source code of multiple TLS implementations\n(Table~\\ref{tab:tls-implementations}). Prior to January 2016, no TLS\nimplementations that we examined validated group order, even for the well-known\nDSA primes from RFC~5114, leaving them vulnerable to small subgroup confinement attacks.\n\nMost of the implementations we examined attempt to match exponent length to the\nperceived strength of the prime. For example, Mozilla Network Security Services\n(NSS), the TLS library used in the Firefox browser and some versions of\nChrome~\\cite{nss-overview,chrome-to-openssl}, uses NIST's ``comparable key strength'' recommendations\non key management~\\cite{sp800} to determine secret exponent lengths from the length of the prime.~\\cite{nss-line-of-code}  Thus NSS uses 160-bit exponents with a 1024-bit prime, and 224-bit exponents with a 2048-bit prime.\n In fall 2015, NSS added an additional check to ensure that the\nshared secret $g^{x_ax_b} \\not \\equiv 1 \\bmod p$~\\cite{nss-code-secret-not-one}.\n\nSeveral implementations go to elaborate lengths to match exponent length to\nperceived prime strength.  The Cryptlib library fits a quadratic curve to the\nsmall exponent attack cost table in the original van~Oorschot\npaper~\\cite{van1996diffie} and uses the fitted curve to determine safe key\nlengths~\\cite{cryptlib-fitted-curve}. The Crypto++ library uses an explicit\n``work factor'' calculation, evaluating the function $2.4 n^{1/3} (\\log\nn)^{2/3}$~\\cite{cryptoplusplus-work-factor}. Subgroup order and exponent\nlengths are set to twice the calculated work factor. The work factor\ncalculation is taken from a 1995 paper by Odlyzko on integer\nfactorization~\\cite{odlyzko-1995}. Botan, a C++ cryptography and TLS library,\nuses a similar work factor calculation, derived from RFC~3766~\\cite{rfc3766},\nwhich describes best practices as of 2004 for selecting public key strengths\nwhen exchanging symmetric keys. RFC~3766 uses a similar work factor algorithm\nto Odlyzko, intended to model the running time of the number-field\nsieve. Botan then doubles the length of the work factor to obtain subgroup and\nexponent lengths~\\cite{botan-double}.\n\n% Apple Safari on OS X and iOS performed no validation of\n% Diffie-Hellman prime lengths until July 2015, and supported connections where\n% the server offered a trivially-broken group using a 16-bit prime~\\cite{weakdh-ccs15}.\n\n\\subsection{Measurements}\n\\label{sec:tls-measurements}\n\nWe used ZMap~\\cite{zmap-2013} to probe the public IPv4 address space for hosts\nserving three TLS-based protocols: HTTPS, SMTP+STARTTLS, and POP3S\\@.  To\ndetermine which primes servers were using, we sent a \\texttt{ClientHello}\nmessage containing only ephemeral Diffie-Hellman cipher suites.  We combined\nthis data with scans from Censys~\\cite{censys} to determine the overall\npopulation.  The results are summarized in Table~\\ref{tab:scandata}. \n\n\\ScanTable\n\n\\TLSHostValidationTable\n\nIn August 2016, we conducted additional scans of a random 1\\% sample\nof HTTPS hosts on the Internet.  First, we checked for nontrivial\nsmall subgroup attack vulnerability. For servers that sent us a prime\n$p$ such that $p-1$ was divisible by 7, we attempted a handshake using\na client key exchange value of $g_7\\bmod p$, where $g_7$ is a\ngenerator of a subgroup of order $7$.  (7 is the smallest prime factor\nof $p-1$ for Group 22.) When we send $g_7$, we expect to correctly\nguess the \\texttt{PreMasterSecret} and complete the handshake with one\nseventh of hosts that do not validate subgroup order. In our scan, we\nwere able to successfully complete a handshake with $1477$ of $10714$\nhosts that offered a prime such that $p-1$ was divisible by $7$,\nimplying that approximately 96\\% of these hosts fail to validate\nsubgroup order six months after OpenSSL pushed a patch adding group\norder validation for correctly configured groups.\n\nSecond, we measured how many hosts performed even the most basic\nvalidation of key exchange values. We attempted to connect to HTTPS hosts with\nthe client key exchange values of $y_c = 0 \\bmod p, 1 \\bmod p, -1 \\bmod p$. As\nTable~\\ref{tab:tlsvalidation} shows, we found that over 5\\% of hosts that\naccepted DHE ciphersuites accepted the key exchange value of $-1 \\bmod p$ and\nderived the \\texttt{PreMasterSecret} from it. These implementations are\nvulnerable to a trivial version of the small subgroup confinement attacks\ndescribed in Section~\\ref{sec:tls-subgroup-attack}, for \\emph{any} prime\nmodulus $p$. By examining the default web pages of many of these hosts,\nwe identified products from several notable companies including Microsoft,\nCisco, and VMWare. When we disclosed these findings, VMWare notified us that\nthey had already applied the fix in the latest version of their products;\nMicrosoft acknowledged the missing checks but chose not to include them since\nthey only use safe primes, and adding the checks may break functionality\nfor some clients that were sending unusual key exchange values; and Cisco\ninformed us that they would investigate the issue.\n\nOf 40.6\\,M total HTTPS hosts found in our scans, 10.8\\,M~(27\\%) supported\nephemeral Diffie-Hellman, of which 1.6\\,M~(4\\%) used a non-safe prime, and\n309\\,K~(0.8\\%) used a non-safe prime and reused exponents across multiple\nconnections, making them likely candidates for a small subgroup key recovery\nattack.  We note that the numbers for hosts reusing exponents are an\nunderestimate, since we only mark hosts as such if we found them using the same\npublic Diffie-Hellman value across multiple connections, and some load\nbalancers that cycle among multiple values might have evaded detection.\n\nWhile 77\\%~of POP3S hosts and 39\\%~of SMTP servers used a non-safe prime, a\nmuch smaller number used a non-safe prime and reused exponents (<0.01\\% in both\nprotocols), suggesting that the popular implementations (Postfix and\nDovecot~\\cite{mail-2015}) that use these primes follow recommendations to use\nephemeral Diffie-Hellman values with DSA primes.\n\nTable~\\ref{tab:primes} shows nine groups that accounted for the majority of\nnon-safe primes used by hosts in the wild. Over 1.17\\,M hosts across all of our\nHTTPS scans negotiated Group~22 in a key exchange. To get a better picture of\nwhich implementations provide support for this group, we examined the default\nweb pages of these hosts to identify companies and products, which we show in\nTable~\\ref{tab:tls-group22-support}.\n\n\\TLSGroupSupport\n\nOf the the 307\\,K HTTPS hosts that both use non-safe primes and reuse\nexponents, 277\\,K~(90\\%) belong to hosts behind Amazon's Elastic Load\nBalancer~\\cite{amazon-elb}. These hosts use a 1024-bit prime with a 160-bit\nsubgroup. We set up our own load balancer instance and found that the\nimplementation failed to validate subgroup order. We were able to use a\nsmall-subgroup key recovery attack to compute 17 bits of our load balancer's\nprivate Diffie-Hellman exponent $x_s$ in only 3813 queries.  We responsibly\ndisclosed this vulnerability to Amazon. Amazon informed us that they have\nremoved Diffie-Hellman from their recommended ELB security policy, and are\nencouraging customers to use the latest policy.  In May 2016, we performed\nadditional scans and found that 88\\% of hosts using this prime no longer\nrepeated exponents.   We give a partial factorization for $p-1$ in\nTable~\\ref{tab:group-order-factorization}; the next largest subgroups have 61\nand 89 bits and an offline attack against the remaining bits of a 160-bit\nexponent would take $2^{71}$ time.  For more details on the computation, see\nSection~\\ref{sec:ecm}.\n\nSSLeay~\\cite{ssleay}, a predecessor for OpenSSL, includes several default\nDiffie-Hellman primes, including a 512-bit prime. We found that 717 SMTP\nservers used a version of the OpenSSL 512-bit prime with a single character\ndifference in the hexadecimal representation.  The resulting modulus that these\nservers use for their Diffie-Hellman key exchange is no longer prime. We\ninclude the factorization of this modulus along with the factors of the\nresulting group order in Table~\\ref{tab:group-order-factorization}. The use of\na composite modulus further decreases the work required to perform a small\nsubgroup attack.\n\nAlthough TLS also includes static Diffie-Hellman cipher suites that require a\nDSS certificate, we did not include them in our study; no browser supports\nstatic Diffie-Hellman~\\cite{kci-tls-2015}, and Censys shows no hosts with DSS\ncertificates, with only 652 total hosts with non-RSA or ECDSA certificates.\n\n%In February 2016, we conducted an additional scan of a random 1\\% sample of the\n%Internet to check how many hosts performed even the most basic validation of\n%key exchange values. We attempted to connect to HTTPS hosts with a client\n%key exchange message of $y_c = 1$. We found that 322 of 589,241 hosts accepted\n%this key exchange value and derived the \\texttt{PreMasterSecret} from it. 248\n%of these hosts were Cisco devices, another 28 were VMware Horizon View servers,\n%and the remaining 46 devices did not fit into any clear category. These\n%implementations are vulnerable to a trivial version of the small subgroup\n%confinement attacks described in Section~\\ref{sec:tls-subgroup-attack}.\\todo{did we disclose this? we need to. also what about validation of values other than 0?}\n\n\n%\\TODO{classify implementations again and disclose to Cisco, etc}\n\n\\begin{landscape}\n\\TLSLibraryTable\n\\PrimesAllTLS\n\\end{landscape}\n\n\n\n\n", "meta": {"hexsha": "ee4ec5ff9e704fe40e2e2b794bda03e9e3b062ba", "size": 21823, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "papers/subgroup/paper/tls.tex", "max_stars_repo_name": "dadrian/dissertation", "max_stars_repo_head_hexsha": "5607114fb4340c5b6e944c73ed6019006d3ebec9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "papers/subgroup/paper/tls.tex", "max_issues_repo_name": "dadrian/dissertation", "max_issues_repo_head_hexsha": "5607114fb4340c5b6e944c73ed6019006d3ebec9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "papers/subgroup/paper/tls.tex", "max_forks_repo_name": "dadrian/dissertation", "max_forks_repo_head_hexsha": "5607114fb4340c5b6e944c73ed6019006d3ebec9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 62.1737891738, "max_line_length": 222, "alphanum_fraction": 0.7940246529, "num_tokens": 5335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.345799967212732}}
{"text": "%%% Copyright 2017 International Business Machines Corporation\n\\documentclass[11pt]{article} % use larger type; default would be 10pt\n\n\\usepackage[utf8]{inputenc} % set input encoding (not needed with XeLaTeX)\n\\usepackage[T1]{fontenc}\n\n\n%%% PAGE DIMENSIONS\n\\usepackage[top=1.5in,bottom=1in,right=1in,left=1in,headheight=90pt,headsep=1cm]{geometry} % to change the page dimensions\n\\geometry{a4paper} % or letterpaper (US) or a5paper or....\n \\geometry{margin=0.7in} % for example, change the margins to 2 inches all round\n\n\\usepackage{graphicx} % support the \\includegraphics command and options\n\n \\usepackage[parfill]{parskip} % Activate to begin paragraphs with an empty line rather than an indent\n\n%%% PACKAGES\n\\usepackage{amsmath}\n\\usepackage{cases}\n\\usepackage{ulem}\n\\usepackage{listings}\n\n\n\\usepackage{fancyhdr} % This should be set AFTER setting up the page geometry\n\\pagestyle{fancy} % options: empty , plain , fancy\n\\renewcommand{\\headrulewidth}{0.4pt} % customise the layout...\n\\lhead{}\\chead{\\footnotesize \\textit{IBM}}\\rhead{}\n\\lfoot{}\\cfoot{\\thepage}\\rfoot{}\n\n%%% SECTION TITLE APPEARANCE\n\\usepackage{sectsty}\n\n\\newenvironment{aside}\n  {\\begin{mdframed}[style=0,%\n      leftline=false,rightline=false,leftmargin=2em,rightmargin=2em,%\n          innerleftmargin=0pt,innerrightmargin=0pt,linewidth=0.75pt,%\n      skipabove=7pt,skipbelow=7pt]\\small}\n  {\\end{mdframed}}\n\n%COLOURING\n\\usepackage{color}\n\\newcommand{\\new}{\\textcolor{red}}\n%\\input{rgb}\n\n%%% ToC (table of contents) APPEARANCE\n\\usepackage[nottoc,notlof,notlot]{tocbibind} % Put the bibliography in the ToC\n\n\n\\title{The Iterative Reweighted Least Squares Method\\\\ for $\\ell_1$ Norm Minimisation}\n\\author{Cecilia Aas}\n\\date{October, 2015}\n\n\n\\def\\layersep{2.5cm}\n\n\\begin{document}\n\\lstset{language=C++,\n           commentstyle=\\textcolor[rgb]{0.00,0.66,0.33},\n           keywordstyle=\\textcolor[rgb]{0.00,0.00,1.00},\n           basicstyle=\\footnotesize\\ttfamily,\n           frame=lines,\n           framexleftmargin=2mm,\n           numbers=left,\n           numberstyle=\\footnotesize,\n           stepnumber=1,\n           numbersep=1pt}\n\\maketitle\n\\section{Overview}\nThe algorithm aims to solve the problem\n\\begin{equation}\n\\label{eq:l1min}\n\\min\\left|\\left| \\uline{x} \\right| \\right|_1 \\text{ subject to } \\uuline{A}\\uline{x} = \\uline{y}\n\\end{equation}\nby finding the minimisers $\\left\\{x_0, x_1, \\cdots \\right\\}$ of the functional\n\\begin{equation}\nJ_{\\lambda}(x) = \\frac{1}{2} \\left| \\left|\\uuline{A} \\uline{x} - \\uline{y} \\right| \\right|_2^2 + \\lambda \\left| \\left| \\uline{x} \\right| \\right|_1 \\; .\n\\end{equation}\nfor decreasing $\\lambda$.  The algorithm does this by tracing out the \\textit{homotopy path}, approaching the limit\n\\begin{equation}\n\\lim_{\\lambda \\rightarrow 0} J_{\\lambda}(x) = \\frac{1}{2} \\left| \\left|\\uuline{A} \\uline{x} - \\uline{y} \\right| \\right|_2^2 \\; .\n\\end{equation}\n\n\\section{Variables}\nWe have the following variables,\n\\begin{itemize}\n\\item $m \\times n$ sensing matrix, $\\uuline{A}$\n\\item signal vector of $m$ elements, $\\uline{y}$\n\\item solution vector of $n$ elements, $\\uline{x}$\n\\item weights vector of $n$ elements, $\\uline{w}$\n\\item the error, $\\epsilon$\n\\item iteration index $j$\n\\end{itemize}\n\n\\section{Algorithm}\n\nThe iterative reweighted least square algorithms requires initialisation of\n\\begin{itemize}\n\\item the value of $\\epsilon_0 = 0$\n\\item the weights vector to $\\uline{w} = \\uline{1}$ (i.e., a vector with all elements equal to one)\n\\end{itemize}\nIn each iterative step $j$, the iterative reweighted least square algorithms updates the solution approximation, $\\uline{x}^{(j)}$, and the weights, $\\uline{w}^{(j)}$, as follows.\n\\begin{itemize}\n\\item the approximate solution is updated\n\\begin{equation}\n\\uline{x}^{(j+1)} = \\uuline{D}_j^n \\uuline{A}^T\\left(\\uuline{A} \\uuline{D}^{-1} \\uuline{A}^T\\right) \\uline{y}\n\\end{equation}\nwhere the matrix $\\uuline{D}$ is a diagonal matrix containing the weights,\n\\begin{equation}\nD_{ii} = w_i^{(j)}\n\\end{equation}\n\\item the value of epsilon is updated\n\\begin{equation}\n\\epsilon_{j+1} =  \\min\\left(\\epsilon_n, \\frac{r\\left(x^{(j+1)}\\right)_{K+1}}{N}\\right)\n\\end{equation}\nwhere the vector $\\uline{r}\\left(\\uline{x}\\right)$ is defined to contain the non-increasing arrangement of the absolute values of the elements in $\\uline{x}$; $r\\left(\\uline{x}\\right)_i$ is thus the $i^{\\text{th}}$ largest element of $\\uline{x}$; a vector $\\uline{x}$ is $k$-sparse if and only if $r\\left(\\uline{x}\\right)_{k+1} = 0$\n\\item the weights are updated\n\\begin{equation}\nw_j^{(j+1)} = \\frac{1}{\\sqrt{\\left(x_j^{(j+1)}\\right)^2 + \\epsilon_{j+1}^2}}\n\\end{equation}\n\\end{itemize}\n\n\nThe loop breaks either\n\\begin{itemize}\n\\item when reaching the maximum number of iterations, $N_{iter}$, or\n\\item when the infinity-norm of the residual vector (i.e., the lambda parameter in Eq.~(\\ref{eq:l1min})) becomes smaller than the pre-set tolerance,\n\\end{itemize}\nwhichever happens first.\n\\end{document}", "meta": {"hexsha": "0f63a02c6dc5b056a30577dc0a7ecd0b84001b6c", "size": 4916, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/algorithms/irls-method/src.tex", "max_stars_repo_name": "rayglover-ibm/sparse-solvers", "max_stars_repo_head_hexsha": "601d74c5230fcab4dc4f83fb90049515b3bf7d06", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2017-05-13T10:33:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-13T06:18:25.000Z", "max_issues_repo_path": "docs/algorithms/irls-method/src.tex", "max_issues_repo_name": "rayglover-ibm/sparse-solvers", "max_issues_repo_head_hexsha": "601d74c5230fcab4dc4f83fb90049515b3bf7d06", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2017-05-12T23:26:56.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-11T13:52:54.000Z", "max_forks_repo_path": "docs/algorithms/irls-method/src.tex", "max_forks_repo_name": "rayglover-ibm/sparse-solvers", "max_forks_repo_head_hexsha": "601d74c5230fcab4dc4f83fb90049515b3bf7d06", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-05-21T03:53:05.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-21T03:53:06.000Z", "avg_line_length": 38.1085271318, "max_line_length": 332, "alphanum_fraction": 0.7082994304, "num_tokens": 1628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.345799963871278}}
{"text": "\\chapter{Reinforcement Learning}\n\\label{ch:reinforcement_learning}\n\nThe standard way to solve Markov decision processes is through dynamic programming, which simply consists in solving the Bellman fixed-point equations discussed in the previous chapter. Following this approach, the problem of finding the optimal policy is transformed into the problem of finding the optimal value function. However, apart from the simplest cases where the MDP has a limited number of states and actions, dynamic programming becomes computationally infeasible. Moreover, this approach requires complete knowledge of the Markov transition kernel and of the reward function, which in many real-world applications might be unknown or too complex to use. \\glsfirst{RL} is a subfield of Machine Learning which aims to turn the infeasible dynamic programming methods into practical algorithms that can be applied to large-scale problems. \\gls{RL} algorithms are based on two key ideas: the first is to use samples to compactly represent the unknown dynamics of the controlled system. The second idea is to use powerful function approximation methods to compactly estimate value functions and policies in high-dimensional state and action spaces. In the following sections, we present the \\gls{RL} problem in more depth and discuss how it relates to the standard discrete-time stochastic optimal control theory and to the other subfields of machine learning, such as supervised learning. In particular, we will see how RL extends ideas from optimal control theory and stochastic approximation to address the broader goal of artificial intelligence. This quick overview of RL is propaedeutic to the following chapters, where we will present in more detail a particular class of algorithms, called policy gradient methods, which are well suited for continuous action spaces. For a more thorough presentation, the reader may consult \\cite{sutton1998introduction}, \\cite{szepesvari2010algorithms} or \\cite{wiering2012reinforcement}.\n\n\\section{The Reinforcement Learning Problem}\nReinforcement Learning (RL) is a general class of algorithms in the field of machine learning that allows an agent to learn how to behave in a stochastic and possibly unknown environment, where the only feedback consists of a scalar reward signal. In order to maximize the long-run reward, the agent must learn which actions are the most profitable by trial-and-error. Therefore, RL algorithms can be seen as computational methods to solve Markov decision processes by directly interacting with the environment, for which a model may or may not be available. Trial-and-error search and a delayed reward signal can be seen as the most characteristic features of reinforcement learning.\\\\\nCompared to supervised learning, one of the main branches of machine learning, the feedback the learner receives is much less. In supervised learning, the agent is provided with examples of the correct or expected behavior by a knowledgeable external supervisor and the agent's goal is to learn how to replicate these examples as well as possible and possibly generalize this knowledge to new examples. In reinforcement learning, the agent only receives a numerical reward that only gives a partial feedback of the goodness of actions taken. Therefore, this feedback system is evaluative rather than instructive and it is much more difficult for the agent to learn how to behave in uncharted territory without any external guidance.\\\\ \nThis particular framework generates some challenges that are not present in other kinds of learning. The first one is the trade-off between exploration and exploitation. In order to maximize his reward, an agent would greedily select actions that have already been tried in the past and found to be effective in producing rewards. However, to find these actions, the agent must also test actions that have not been chosen before in order to evaluate their potential. Clearly, this might result in worse performance in the short-term because the actions might be suboptimal. However, without trying them, the agent might not be able to find possible improvements. Thus, an agent must exploit what is known to obtain rewards but also needs to explore to select better actions in the future. A second challenge is the credit assignment problem. Since rewards might be delayed in time, it will be difficult for the agent to understand which actions are mostly responsible for the outcome. \n\n\\section{Model-Free RL Methods}\nIn Section \\ref{sec:policy_evaluation}, we discussed the policy iteration method for computing an optimal policy for an \\gls{MDP} in a finite state and action spaces. This algorithm belongs to the class of \\emph{model-based} methods, since it requires perfect knowledge of the Markov transition kernel and reward function, which consists of a model of the MDP. RL is primarily concerned with how to obtain an optimal policy when such a model is not available. In this section, we discuss some classes of \\emph{model-free} methods which do not rely on the MDP model. The lack of a model generates the need to sample the MDP to gather statistical knowledge about this unknown model. In the control setting, the goal is to approximate the optimal policy, which depends on the optimal value, which in turn depends on the model of the MDP, as shown in Figure \\ref{fig:control_dependences}. Indeed, we have already seen that a policy which is greedy with respect to the optimal action-value funtion $Q_*$, namely for which holds\n\\begin{equation}\n\t\\int_{\\A} \\pi_*(s,a) Q_*(s,a) da = \\sup_a Q_*(s,a)\n\\end{equation} \nis optimal. Therefore, we can derive the following three methodologies that differ in which part of the solution process is approximated\n\\begin{enumerate}[label={\\roman*)}]\n\t\\item \\emph{Model-approximation} algorithms approximate the MDP model and compute an estimate of the optimal policy by dynamic programming.\n\t\\item \\emph{Value-approximation} algorithms use samples to directly approximate $V_*$ or $Q_*$, from which an estimate of $\\pi_*$ can be derived by acting greedily.\n\t\\item \\emph{Policy-approximation} algorithms directly try to estimate the optimal policy.\n\\end{enumerate}\nIt should be noticed that these approaches are not mutually exclusive and can be combined to derive hybrid algorithms. In the following sections we discuss these three classes of algorithm in more detail, following closely \\cite{wiering2012reinforcement}.\n\n\\begin{figure}[t]\n\t\\centering\n\t\\begin{tikzpicture}[node distance = 6em, auto, thick]\n\t\t\\node [block] (Model) {Model\\\\$\\calP$, $\\calR$};\n\t\t\\node [block, below of=Model] (Value) {Value functions\\\\$V_*$, $Q_*$};\n\t\t\\node [block, below of=Value] (Policy) {Policy\\\\$\\pi_*$};\t\t    \n\t\t\\path [line] (Model) edge (Value);\n\t\t\\path [line] (Value) edge (Policy);\n\t\\end{tikzpicture}\n\t\\caption{Solution process for the control problem.}\n\t\\label{fig:control_dependences}\n\\end{figure}\n\n\n\\subsection{Model Approximation}\nModel-approximation algorithms approximate the MDP model and compute an optimal policy by dynamic programming, using the techniques discussed in the previous chapter. Since $\\S$, $\\A$ and $\\gamma$ are assumed to be known, these methods are based on learning an approximation of the Markov transition kernel $\\calP$ and the reward function $\\calR$. Thanks to the Markov property, these quantities only depend on the current state and action, so that their approximation corresponds to a density estimation problem and a regression problem respectively, which are fairly standard supervised learning problems. Learning the model may not be trivial, but it is in general easier than learning the value of a policy or optimizing the policy directly. The major drawback of model-based algorithms in continuous-state MDPs is that, even if the model is available, it is in general infeasible to compute the value functions by dynamic programming and to extract an optimal policy for all states by acting greedily. Alternatively, a transition model estimate may be used to generate sample trajectories from the MDP, which can then be used to estimate the value function or directly improve the policy. However, the value function and the policy estimated using these samples can only be as accurate as the learned model, so that in many cases it may be easier to directly approximate the value function or the policy using the methods described below. \n\n\\subsection{Value Approximation}\nValue-approximation algorithms use samples from the MDP to approximate $V_*$ or $Q_*$ directly and then derive an estimate of the optimal policy by acting greedily with respect to $Q_*$. Typically, when the state and action spaces are large, the value functions are estimated using a parametric function approximator, whose parameters are iteratively updated given the observed samples. Many reinforcement learning algorithms fall into this category and they can be distinguishes based on whether they are on-policy or off-policy and whether they update the value function estimates online or offline. \\emph{On-policy} algorithms approximate the state-value function $V_\\pi$ or the action-value function $Q_\\pi$ from samples of the MDP obtained by following the same policy $\\pi$ to be evaluated. Although the optimal policy $\\pi_*$ is initially unknown, such algorithms can eventually approximate the optimal value functions $V_*$ or $Q_*$ from which an approximation of the optimal policy can be derived. On the other hand, \\emph{off-policy} algorithms can learn the value of a policy different from the one use for obtaining the MDP samples. \\emph{Online} algorithms adapt their value approximation after each observed sample while \\emph{Offline} algorithms operate on batches of samples. Online algorithms typically require less computation per sample but their convergence is slower. \n%Online on-policy algorithms include temporal-difference (TD) algorithms, such as TD-learning, Sarsa. Offline on-policy algorithms include least-squares approaches, such least-squares temporal difference (LSTD), least-squares policy evaluation (LSPE) and least-squares policy iteration (LSPI). The most known model-free online off-policy algorithm is Q-learning.\n\n\\subsection{Policy Approximation}\nPolicy-approximation algorithms only store a policy and update this policy to maximize a given performance measure and eventually converge to the optimal policy. Since these algorithms only use an estimate of the optimal policy and do not rely on a value function approximation, they are also referred to as \\emph{direct policy-search} or \\emph{actor-only} algorithms. Algorithms that store both a policy and a value function are commonly known as \\emph{actor-critic} algorithms \\cite{sutton1999policy}, \\cite{konda1999actor}. Policy gradient algorithms, the most studied policy-approximation methods, will be discussed in much more detail in the next chapter. \n\n\n\n\n\n", "meta": {"hexsha": "5b215aea3d56613d1cda6b38a763c7355dbe15bb", "size": 10883, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Report/Chapters/3_Reinforcement_Learning.tex", "max_stars_repo_name": "AmineAboussalah/Thesis", "max_stars_repo_head_hexsha": "1a3ae97023acff1ee5e2d197a446734117a6fb99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 80, "max_stars_repo_stars_event_min_datetime": "2016-06-13T15:20:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T23:47:13.000Z", "max_issues_repo_path": "Report/Chapters/3_Reinforcement_Learning.tex", "max_issues_repo_name": "pnecchi/Thesis", "max_issues_repo_head_hexsha": "1a3ae97023acff1ee5e2d197a446734117a6fb99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Report/Chapters/3_Reinforcement_Learning.tex", "max_forks_repo_name": "pnecchi/Thesis", "max_forks_repo_head_hexsha": "1a3ae97023acff1ee5e2d197a446734117a6fb99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34, "max_forks_repo_forks_event_min_datetime": "2017-05-15T07:51:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-21T21:48:53.000Z", "avg_line_length": 209.2884615385, "max_line_length": 1937, "alphanum_fraction": 0.8070385004, "num_tokens": 2263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.34578793835137167}}
{"text": "% !TeX root = ../main.tex\n\\begin{landscape}\n\\section{Semantics Derivation Tree Example}\n\\label{sec:semanticsTree}\nThis is an example of how to create a derivation tree for a program written in HCL.\nIt is based on the following code snippet.\n\n\\begin{lstlisting}[language=HCL,label=lis:derivationCode,firstnumber=1]\nnum x\nx = 5\n\\end{lstlisting}\n\nUsing the abstract syntax described in section \\ref{sec:semantics}, the code can be written as the following big step semantic:\n\n\\begin{center}\n\t$env_V, env_F \\vdash \\langle num\\ x;\\ x = 5, env_V, env_F, sto \\rangle \\rightarrow_{stm} (sto', env_V', env_F')$\n\\end{center}\nUsing the Compositional Big Step Semantic rule, the following derivation is produced:\n\n\\begin{center}\n\t\\begin{math}\n\t\t\\cfrac\n\t\t{env_V, env_F \\vdash \\langle num\\ x, env_V, env_F, sto \\rangle \\rightarrow_{stm} (sto'', env_V'', env_F'')\\quad env_V'', env_F'' \\vdash \\langle x = 5, env_V'', env_F'', sto'' \\rangle \\rightarrow_{stm} (sto', env_V', env_F')}\n\t\t{env_V, env_F \\vdash \\langle num\\ x;\\ x = 5, env_V, env_F, sto \\rangle \\rightarrow_{stm} (sto', env_V', env_F')}\n\t\\end{math}\n\\end{center}\n\nTable \\ref{tbl:progstates} shows how the program state changes after each statement in the code is run.\n\n\\begin{table}[H]\n\t\\centering\n\t\\caption{Table of program states after each statement.}\n\t\\label{tbl:progstates}\n\t\\setlength\\extrarowheight{5pt}\n\t\\begin{tabular}{|c|c|c|}\n\t\t\\hline\n\t\t& Abstract program state      & Concrete program state                          \\\\ \\hline\n\t\tInitial state          & $(sto, env_V, env_F)$       & $(sto, env_V, env_F)$                           \\\\ \\hline\n\t\tAfter first statement  & $(sto'', env_V'', env_F'')$ & $(sto[l \\mapsto 0], env_V[x \\mapsto l], env_F)$ \\\\ \\hline\n\t\tAfter second statement & $(sto', env_V', env_F')$    & $(sto[l \\mapsto 5], env_V[x \\mapsto l], env_F)$  \\\\ \\hline\n\t\\end{tabular}\n\\end{table}\n\n\\end{landscape}", "meta": {"hexsha": "4a0d6f86a9b67153d9ab9b17a5834782f8295958", "size": 1871, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/Appendix/SemanticsTree.tex", "max_stars_repo_name": "C0DK/P3-HCL", "max_stars_repo_head_hexsha": "b6adbc46cc7347aacd45dce5fddffd6fee2d37ac", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-02-08T12:34:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T11:33:53.000Z", "max_issues_repo_path": "report/Appendix/SemanticsTree.tex", "max_issues_repo_name": "C0DK/P3-HCL", "max_issues_repo_head_hexsha": "b6adbc46cc7347aacd45dce5fddffd6fee2d37ac", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2018-02-17T14:30:17.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-13T17:37:09.000Z", "max_forks_repo_path": "report/Appendix/SemanticsTree.tex", "max_forks_repo_name": "C0DK/P3-HCL", "max_forks_repo_head_hexsha": "b6adbc46cc7347aacd45dce5fddffd6fee2d37ac", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-07-04T13:55:53.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-04T13:55:53.000Z", "avg_line_length": 42.5227272727, "max_line_length": 226, "alphanum_fraction": 0.6702298236, "num_tokens": 597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.34578793835137167}}
{"text": "\\documentclass{article}\n\n\\usepackage{amssymb}\n\\usepackage{amsthm}\n\\usepackage[UKenglish]{babel}\n\\usepackage[backend=biber,sorting=none]{biblatex}\n\\usepackage{enumitem}\n\\usepackage{fancyhdr}\n\\usepackage[margin=1in]{geometry}\n\\usepackage{graphicx}\n\\usepackage[utf8]{inputenc}\n\\usepackage{listings}\n\\usepackage{mathtools}\n\\usepackage{tikz-cd}\n\\usepackage{csquotes}\n\n\\newcommand{\\F}{\\mathbb{F}}\n\\newcommand{\\Z}{\\mathbb{Z}}\n\\newcommand{\\Q}{\\mathbb{Q}}\n\\newcommand{\\R}{\\mathbb{R}}\n\\newcommand{\\C}{\\mathbb{C}}\n\\newcommand{\\A}{\\mathbb{A}}\n\\renewcommand{\\P}{\\mathbb{P}}\n\n\\newcommand{\\val}[1]{\\left. #1 \\right\\rvert}\n\\newcommand{\\rb}[1]{\\left( #1 \\right)}\n\\renewcommand{\\sb}[1]{\\left[ #1 \\right]}\n\\newcommand{\\cb}[1]{\\left\\{ #1 \\right\\}}\n\\newcommand{\\ab}[1]{\\left\\langle #1 \\right\\rangle}\n\\newcommand{\\abs}[1]{\\left\\lvert #1 \\right\\rvert}\n\n\\newcommand{\\twobyone}[2]{\\begin{pmatrix} #1 \\\\ #2 \\end{pmatrix}}\n\\newcommand{\\onebythree}[3]{\\begin{pmatrix} #1 & #2 & #3 \\end{pmatrix}}\n\\newcommand{\\threebyone}[3]{\\begin{pmatrix} #1 \\\\ #2 \\\\ #3 \\end{pmatrix}}\n\\newcommand{\\threebythree}[9]{\\begin{pmatrix} #1 & #2 & #3 \\\\ #4 & #5 & #6 \\\\ #7 & #8 & #9 \\end{pmatrix}}\n\n\\theoremstyle{definition}\n\\newtheorem*{definition}{Definition}\n\\newtheorem*{example}{Example}\n\\newtheorem*{remark}{Remark}\n\\newtheorem{proposition}{Proposition}[subsection]\n\\newtheorem{lemma}[proposition]{Lemma}\n\\newtheorem{theorem}[proposition]{Theorem}\n\\newtheorem{algorithm}[proposition]{Algorithm}\n\\newtheorem{conjecture}[proposition]{Conjecture}\n\n\\pagestyle{fancy}\n\\lhead{The Arithmetic of Elliptic Curves}\n\\rhead{David Kurniadi Angdinata}\n\n\\addbibresource{bibliography.bib}\n\n\\title{The Arithmetic of Elliptic Curves}\n\\author{David Kurniadi Angdinata}\n\\date{Monday, 2 July 2018 - Friday, 28 September 2018}\n\n\\begin{document}\n\n\\maketitle\n\n\\vspace{1cm}\n\n\\begin{center}\n\\includegraphics*[width=0.5\\textwidth]{img/EllipticCurveCatalog.png}\n\\end{center}\n\n\\vfill\n\n\\begin{center}\n\\emph{\"It is possible to write endlessly on elliptic curves. (This is not a threat.)\"\\cite{lang}} \\\\\n\\end{center}\n\n\\vspace{1cm}\n\n\\begin{abstract}\nIn the field of algebraic geometry, elliptic curves are deeply studied rich structures with far-fetching computational applications to classical number theory and contemporary cryptography. It is a fundamental tool in Wiles' proof of Fermat's last theorem, as well as the main object of discussion in the Birch and Swinnerton-Dyer conjecture, an open problem in number theory deemed worthy of being called one of the Millennium Prize Problems by the Clay Mathematics Institute. In this project, three of the four most fundamental theorems in the arithmetic of elliptic curves, namely the Hasse-Weil theorem, the Nagell-Lutz theorem, and the Mordell-Weil theorem, are proven in their respective special forms. Schoof's algorithm for counting rational points over Galois fields will also be briefly discussed, allowing for an application to integer factorisation and primality testing. An introductory section and a brief appendix on fields, varieties, curves, and groups are also included for completion.\n\\end{abstract}\n\n\\pagebreak\n\n\\tableofcontents\n\n\\pagebreak\n\n\\section*{Preface}\n\n\\addcontentsline{toc}{section}{Preface}\\par\n\nThe aim of this project is to provide a gentle introduction to the deep theory of \\emph{elliptic curves}. My approach for the report is to deliver information in the form of general propositions and fundamental theorems, providing adequate proofs whenever possible. Admittedly, almost all of the work here is unoriginal and should have been done elsewhere in a similar fashion, but I have tried to make the flow of information as coherent as possible, consulting various online resources as well as the two books \\cite{gtm} and \\cite{utm}.\n\nAs the theory of elliptic curves requires some technical background in algebraic geometry, which in turn requires prerequisites in commutative algebra, both of which I have zero background in, the report is rather superficial and may not provide as good of an insight to deeper theory. In addition to the first two years of undergraduate mathematics, the first three preliminary appendices A.1, A.2, and A.3 will provide all the required background to understand the first introductory section, while a few additional notions in appendix A.4 will allow the rest to be fully accessible to middle-year undergraduates such as myself.\n\nThe first section introduces elliptic curves while hiding away the definitions and results taken from algebraic geometry. For instance, the use of explicit \\emph{Weierstrass equations} and formulae for the \\emph{group law} is an active attempt to avoid bringing in the \\emph{Riemann-Roch theorem} in algebraic geometry to prove that they are related. As such, many proofs in this section are omitted, but are all given a direct reference.\n\nThe second section discusses elliptic curves over finite fields, which hinges on \\emph{Hasse's theorem} to explain \\emph{Schoof's algorithm} for counting rational points. This in turn paves the path for applications in the last section, as well as an alternative method of counting rational points in the following section. Proofs are mostly given in full, except for an overly lengthy but elementary proof based on induction.\n\nThe third section discusses elliptic curves over the rationals, which can be split into two parts due to the \\emph{fundamental theorem of finitely generated abelian groups}. The \\emph{Nagell-Lutz theorem} and \\emph{reduction modulo prime} are two related ways to compute the \\emph{torsion subgroup}, while \\emph{Mordell's theorem} proves that the fundamental theorem indeed holds and provides a semi-workable method to compute the \\emph{rank}. Again, proofs are mostly given in full, except for an assumption made in the last part of Mordell's theorem.\n\nThe last section touches on some applications to classical arithmetic, including integer factorisation and primality proving, as well as the basics of contemporary cryptography, which could potentially be explored into if time permitted. There was originally an intention to cover complex elliptic curves in here instead, leading to a brief exposition of Fermat's last theorem, but was omitted due to lack of time.\n\nThe appendices include the aforementioned preliminaries, as well as proofs of two algorithms and listings of code. The proofs are placed here as they are deemed less relevant and too lengthy to be included in the main text. All code under code listings are in the functional \\emph{Haskell} programming language compiled by the \\emph{Glassgow Haskell Compiler}, which is markedly different from many implementations publicly available.\n\nI will also present several remarks regarding the style of the report, which is an attempt to imitate typical lecture notes and textbooks. Definitions are all given in bold, while italics are reserved for less important terms that are undefined, all of which provided with adequate examples whenever possible. Theorems are important results and propositions those less important, while lemmas serve as intermediate checkpoints to theorems and propositions. All of these are provided immediate proofs after their statements, or postponed for later as \\emph{Proof of \\emph{statement}}. Remarks are largely irrelevant to the flow of the main discussion and can be disregarded, but are included for interesting points, which may include previously undefined terms.\n\nIn terms of notation, most of the symbols I have used are those found in books, such as $ \\F_p $, $ \\Z $, or $ \\Q $, and should be unambiguous. While there are unfortunate cases of equivalent symbols being used to mean completely different objects due to limitations of the English and Greek alphabet system, I have tried to minimise these or make them clear from context. An example being $ f, g, h $ being used for general functions, while homomorphisms are always denoted $ \\phi, \\psi, \\chi $ or their variants. In examples like the following,\n$$ f\\rb{x, y} = xg\\rb{y} + yh\\rb{x}, \\qquad g \\in F\\sb{y}, \\qquad h \\in F\\sb{x}, $$\n$ g $ and $ h $ are always existentially quantified, while $ f $ and $ F $ are initially fixed or explicitly universally quantified. A function $ f' $ will always be distinct, but possibly related, to the function $ f $, while differentiation with respect to a variable $ x $ will always be denoted $ d / dx $ or $ \\partial / \\partial x $. No distinction will be made between sums and \\emph{formal sums}, or derivatives and \\emph{formal derivatives}, as they are clear from the context of this report.\n\nI would like to thank my supervisor Prof Johannes Nicaise for his support and guidance throughout the duration of this project. I had many doubts and questions early on, all of which he clarified with great detail.\n\n\\pagebreak\n\n\\section{Introduction}\n\nInformally, an elliptic curve is a cubic curve with no cusps, self-intersections, or isolated points, whose solutions are confined to a region of space topologically equivalent to a torus. It can represented by a cubic equation in two variables, with its coefficients being elements of a specified field. Two elliptic curves over the field of real numbers are illustrated below.\n\n\\begin{center}\n\\includegraphics*[width=0.4\\textwidth]{img/ECClines-3.png}\n\\end{center}\n\n\\subsection{Definition}\n\nA formal definition is as follows.\n\n\\begin{definition}[Elliptic curve]\nAn \\textbf{elliptic curve} over a perfect field $ F $ is an ordered pair $ \\rb{E, \\mathcal{O}_E} $ such that $ E $ is a smooth projective plane curve of genus one over $ F $ and $ \\mathcal{O}_E \\in E $ is an $ F $-rational \\textbf{base point}.\n\\end{definition}\n\nThis definition uses several terms in other fields of mathematics, which are briefly covered in the appendices. In particular, one of the many characterisations of a perfect field is given in Appendix A.1, while several fundamental notions in projective and algebraic geometry such as projective planes and smoothness are laid out in Appendix A.2. Appendix A.3 defines a curve and the genus due to the \\emph{genus-degree formula}.\n\n\\begin{remark}\nThe genus in algebraic geometry is usually defined in general literature by the \\emph{Riemann-Roch theorem}, which does coincide with the topological definition.\n\\end{remark}\n\nAs the report is a gentle introduction to elliptic curves, further delving into the vast world of algebraic geometry will be avoided, and so explicit formulae will be provided whenever possible. To this end, the various definitions in the appendix can be summarised in the following proposition.\n\n\\begin{proposition}\n\\label{prop:appendices}\nLet $ \\rb{E, \\mathcal{O}_E} $ be an elliptic curve over a perfect field $ F $. Then:\n\\begin{enumerate}\n\\item $ I\\rb{E} = \\ab{e} $ for some homogeneous irreducible polynomial $ e $ of three variables,\n\\item any point $ P \\in E $ has multiplicity $ m_P\\rb{e} = 1 $, and\n\\item $ e $ have roots confined to a torus and is cubic.\n\\end{enumerate}\n\\end{proposition}\n\n\\begin{proof}\nThis follows directly from the appendices.\n\\end{proof}\n\nThus an elliptic curve can be fully defined in terms of its defining polynomial, which would need to satisfy certain conditions. As per the appendix, an abuse of notation will be used to denote an elliptic curve $ \\rb{E, \\mathcal{O}_E} $ over $ F $ \\emph{given} by a polynomial $ e $, namely\n$$ E : e\\rb{X, Y, Z} = 0 \\qquad \\iff \\qquad E : e\\rb{x, y} = 0, $$\nwhich are respectively the homogenised and dehomogenised forms of a polynomial that can be used interchangeably. For the rest of this section, let $ E : e\\rb{x, y} = 0 $ and $ E' : e'\\rb{x, y} = 0 $ be two elliptic curves over a perfect field $ F $ with algebraic closure $ K = \\overline{F} $. The notion of an isomorphism, as for any algebraic geometric structure, would be useful. This is captured in the following definition.\n\n\\begin{definition}[Isomorphism]\n$ \\rb{E, \\mathcal{O}_E} $ and $ \\rb{E', \\mathcal{O}_{E'}} $ are \\textbf{isomorphic}, denoted by $ \\rb{E, \\mathcal{O}_E} \\cong \\rb{E', \\mathcal{O}_{E'}} $, iff there is an isomorphism $ \\phi : E \\to E' $ such that $ \\phi\\rb{\\mathcal{O}_E} = \\mathcal{O}_{E'} $.\n\\end{definition}\n\n\\begin{remark}\nIsomorphism defines an equivalence relation of elliptic curves, such that two elliptic curves from an equivalence class are indistinguishable.\n\\end{remark}\n\nAgain, this abstract notion can be made explicit later by the defining polynomials of the elliptic curves.\n\n\\pagebreak\n\n\\subsection{Weierstrass equations}\n\nThe definition of an elliptic curve boils down to its defining polynomial, which will be made explicit in this subsection. A family of curves related to elliptic curves will be defined beforehand.\n\n\\begin{definition}[Weierstrass curve]\nA \\textbf{Weierstrass curve} is a projective plane curve $ W $ over $ F $ \\emph{given} by the \\textbf{Weierstrass equation}\n$$ W : w\\rb{x, y} = 0 : y^2 + a_1xy + a_3y = x^3 + a_2x^2 + a_4x + a_6, \\qquad a_i \\in F, $$\nwith associated quantities:\n$$ b_2 = a_1^2 + 4a_2, \\qquad b_4 = a_1a_3 + 2a_4, \\qquad b_6 = a_3^2 + 4a_6, \\qquad b_8 = a_1^2a_6 + 4a_2a_6 - a_1a_3a_4 + a_2a_3^2 - a_4^2, $$\n$$ c_4 = b_2^2 - 24b_4, \\qquad c_6 = 36b_2b_4 - b_2^3 - 216b_6, \\qquad \\Delta_W = 9b_2b_4b_6 - b_2^2b_8 - 8b_4^3 - 27b_6^2, \\qquad j_W = c_4^3 / \\Delta_W. $$\n\\end{definition}\n\nIt holds that $ 4b_8 = b_2b_6 - b_4^2 $ and $ 1728\\Delta_W = c_4^3 - c_6^2 $. It can be easily verified that Weierstrass curves, with the additional condition of smoothness, would almost satisfy Proposition \\ref{prop:appendices}. The only remaining requirement is having an additional base point in its definition, which can be easily fixed as follows.\n\n\\begin{definition}[Point at infinity]\nThe \\textbf{point at infinity} of $ E $ is the point $ \\mathcal{O} = \\sb{0, 1, 0} $.\n\\end{definition}\n\nIn contrast to general projective geometry, the \\emph{line at infinity} $ L : l\\rb{X, Y, Z} = Z = 0 $ intersects a Weierstrass curve only at $ \\mathcal{O} $, where $ X = Z = 0 $ and $ Y \\ne 0 $. As such, any other point would have $ Z \\ne 0 $ and can be treated as an affine point $ \\rb{a, b} $. Now since $ 0, 1 \\in F $, the point $ \\mathcal{O} $ is actually an $ F $-rational point, and can be paired with a smooth Weierstrass curve $ W $ to give an elliptic curve $ \\rb{W, \\mathcal{O}} $. Conversely, any elliptic curve can also be explicitly given by a smooth Weierstrass curve through an isomorphism as follows.\n\n\\begin{proposition}\n$ \\rb{E, \\mathcal{O}_E} \\cong \\rb{W, \\mathcal{O}} $ for some smooth Weierstrass curve $ W $ over $ F $.\n\\end{proposition}\n\n\\begin{proof}\nOmitted, see III.3.1a in \\cite{gtm}.\n\\end{proof}\n\nThere are even computerised algorithms to transform a general smooth projective plane cubic curve with a given arbitrary $ F $-rational flex point, or an elliptic curve, into a Weierstrass curve with the $ F $-rational point $ \\mathcal{O} $. The following algorithm summarises the process in \\cite{weierstrass} proven in the appendix.\n\n\\begin{algorithm}[Transformation of a cubic curve into Weierstrass form]\nInput: a cubic curve $ E $ over $ F $ with an $ F $-rational flex point $ P \\in E $. Output: $ E $ in Weierstrass form.\n\\begin{enumerate}\n\\item Get the unique tangent line $ L $ at $ P $.\n\\item Find the intersection $ L \\cap E $ to get a point $ Q \\in L \\setminus E $ distinct to $ P $.\n\\item Write down an invertible matrix $ M = \\onebythree{Q}{P}{R} $, where $ R \\in \\cb{\\sb{1, 0, 0}, \\sb{0, 1, 0}, \\sb{0, 0, 1}} $.\n\\item Transform $ \\sb{X, Y, Z} \\mapsto M\\sb{X, Y, Z}^T $ to get a scaled Weierstrass equation.\n\\item Rescale $ \\sb{X, Y, Z} \\mapsto \\sb{X, Y, cZ} $ for some $ c \\in K^* $ to get a Weierstrass equation.\n\\end{enumerate}\n\\end{algorithm}\n\nThe following example illustrates an implementation of the algorithm.\n\n\\begin{example}\nLet $ E : e\\rb{X, Y, Z} = 0 : X^3 + Y^3 = Z^3 $ be a smooth projective plane cubic curve over $ \\R $ with an $ \\R $-rational flex $ P = \\sb{1, -1, 0} \\in E $. Then the unique tangent at $ P $ is\n$$ L : \\twobyone{1}{1, 0, 0}\\val{\\dfrac{\\partial e}{\\partial X}}_P\\rb{X - 1} + \\twobyone{1}{0, 1, 0}\\val{\\dfrac{\\partial e}{\\partial Y}}_P\\rb{Y + 1} + \\twobyone{1}{0, 0, 1}\\val{\\dfrac{\\partial e}{\\partial Z}}_PZ = 3\\rb{X + Y} = 0, $$\nwhich intersects $ E $ at $ X^3 + \\rb{-X}^3 + Z^3 = 0 $, or $ Z = 0 $. Hence $ L \\cap E = \\cb{P} $ and let $ Q = \\sb{1, -1, 1} \\in L \\setminus E $. Then there is an invertible affine transformation matrix\n$$ M = \\threebythree{1}{1}{1}{-1}{-1}{0}{1}{0}{0} \\qquad \\implies \\qquad M^{-1} = \\threebythree{0}{0}{1}{0}{-1}{-1}{1}{1}{0}. $$\nsuch that the affine transformation $ \\sb{X, Y, Z} \\mapsto M\\sb{X, Y, Z}^{T} $ gives\n$$ \\rb{X + Y + Z}^3 + \\rb{-X - Y}^3 = X^3 \\qquad \\implies 3Y^2Z + 6XYZ + 3YZ^2 = X^3 - 3X^2Z - 3XZ^2 - Z^3. $$\nThus the affine transformation $ \\sb{X, Y, Z} \\mapsto \\sb{X, Y, \\tfrac{1}{3}Z} $ gives a Weierstrass curve\n$$ E : Y^2Z + 2XYZ + \\tfrac{1}{3}YZ^2 = X^3 - X^2Z - \\tfrac{1}{3}XZ^2 - \\tfrac{1}{27}Z^3. $$\n\\end{example}\n\nThis characterisation allows a smooth Weierstrass curve to act as an alternative definition for an elliptic curve, and will be done for ease of future discussions. For the rest of this subsection, let $ E $ and $ E' $ be respectively given by the two Weierstrass curves over $ F $\n$$ W : w\\rb{x, y} = 0 : y^2 + a_1xy + a_3y = x^3 + a_2x^2 + a_4x + a_6, \\qquad a_i \\in F, $$\n$$ W' : w'\\rb{x, y} = 0 : y^2 + a_1'xy + a_3'y = x^3 + a_2'x^2 + a_4'x + a_6', \\qquad a_i' \\in F, $$\nand write them interchangeably as an abuse of notation by\n$$ \\rb{E, \\mathcal{O}_E} = E : e\\rb{x, y} = 0 \\qquad \\iff \\qquad \\rb{W, \\mathcal{O}} = W : w\\rb{x, y} = 0, $$\n$$ \\rb{E', \\mathcal{O}_{E'}} = E' : e'\\rb{x, y} = 0 \\qquad \\iff \\qquad \\rb{W', \\mathcal{O}} = W' : w'\\rb{x, y} = 0. $$\nWith these explicit equations at hand, the abstract notion of isomorphism between elliptic curves can now be made explicit by considering affine transformations of these equations, which is given below.\n\n\\begin{proposition}\n\\label{prop:affine}\n$ E \\cong E' $ iff there is an affine transformation\n$$ \\rb{x, y} \\mapsto \\rb{u^2x + r, u^3y + u^2sx + t}, \\qquad u \\in K^*, \\qquad r, s, t \\in K $$\nfrom $ W $ to $ W' $.\n\\end{proposition}\n\n\\begin{proof}\nOmitted, see III.3.1b in \\cite{gtm}.\n\\end{proof}\n\n\\begin{remark}\nThis affine transformation also transforms the coefficients and quantities of $ W $ and $ W' $ by\n$$ a_1 \\mapsto \\dfrac{a_1 + 2s}{u}, \\qquad a_2 \\mapsto \\dfrac{a_2 - sa_1 + 3r - s^2}{u^2}, \\qquad a_3 \\mapsto \\dfrac{a_3 + ra_1 + 2t}{u^3}, $$\n$$ a_4 \\mapsto \\dfrac{a_4 - sa_3 + 2ra_2 - \\rb{t + rs}a_1 + 3r^2 - 2st}{u^4}, \\qquad a_6 \\mapsto \\dfrac{a_6 + ra_4 - ta_3 + r^2a_2 - rta_1 + r^3 - t^2}{u^6}, $$\n$$ b_2 \\mapsto \\dfrac{b_2 + 12r}{u^2}, \\qquad b_4 \\mapsto \\dfrac{b_4 + rb_2 + 6r^2}{u^4}, \\qquad b_6 \\mapsto \\dfrac{b_6 + 2rb_4 + r^2b_2 + 4r^3}{u^6}, $$\n$$ b_8 \\mapsto \\dfrac{b_8 + 3rb_6 + 3r^2b_4 + r^3b_2 + 3r^4}{u^8}, \\qquad c_4 \\mapsto \\dfrac{c_4}{u^4}, \\qquad c_6 \\mapsto \\dfrac{c_6}{u^6}, \\qquad \\Delta_W \\mapsto \\dfrac{\\Delta_W}{u^{12}}, \\qquad j_W \\mapsto j_W $$\nwhich can be tediously verified.\n\\end{remark}\n\nAgain, this will be treated as the definition of isomorphism between elliptic curves. Now in the original definition of a Weierstrass curve, it is given by a Weierstrass equation that is somewhat perverse. This \\emph{long} Weierstrass equation can in fact be greatly simplified, provided there are small restrictions on the characteristic of the underlying field.\n\n\\begin{proposition}\nIf $ char\\rb{F} \\ne 2 $, then\n$$ E : y^2 = x^3 + Ax^2 + Bx + C, \\qquad A, B, C \\in F. $$\nIf $ char\\rb{F} \\ne 3 $ as well, then\n$$ E : y^2 = x^3 + Ax + B, \\qquad A, B \\in F. $$\n\\end{proposition}\n\n\\begin{proof}\nLet $ char\\rb{F} \\ne 2 $, then the affine transformation $ \\rb{x, y} \\mapsto \\rb{x, y - \\tfrac{1}{2}\\rb{a_1x + a_3}} $ gives an isomorphism from $ E $ to the curve given by the \\emph{medium} Weierstrass equation\n$$ y^2 = x^3 + Ax^2 + Bx + C, \\qquad A = \\tfrac{1}{4}b_2, \\qquad B = \\tfrac{1}{2}b_4, \\qquad C = \\tfrac{1}{4}b_6. $$\nLet $ char\\rb{F} \\ne 3 $ as well, then the affine transformation $ \\rb{x, y} \\mapsto \\rb{x - \\tfrac{1}{12}b_2, y} $ gives an isomorphism from $ E $ to the curve given by the \\emph{short} Weierstrass equation\n$$ y^2 = x^3 + Ax + B, \\qquad A = -\\tfrac{1}{48}c_4, \\qquad B = -\\tfrac{1}{864}c_6. $$\n\\end{proof}\n\nMedium and short Weierstrass equations greatly reduce the tedium when manipulating them, since there is a symmetry to the equation itself, giving two $ y $ opposite in sign for each $ x $. As there are only two characteristics that do not permit the affine transformation to a short Weierstrass equation, they will be disregarded for ease of future discussions. Hence always assume that $ char\\rb{F} \\notin \\cb{2, 3} $ and write the Weierstrass equations of $ W $ and $ W' $ as\n$$ W : w\\rb{x, y} = 0 : y^2 = x^3 + Ax + B, \\qquad A, B \\in F, $$\n$$ W' : w'\\rb{x, y} = 0 : y^2 = x^3 + A'x + B', \\qquad A', B' \\in F. $$\nThe following example illustrates the affine transformation to a short Weierstrass equation.\n\n\\begin{example}\nLet\n$$ E : y^2 + 2xy + \\tfrac{1}{3}y = x^3 - x^2 - \\tfrac{1}{3}x - \\tfrac{1}{27} $$\nbe the Weierstrass curve over $ \\R $ from the example above. Since $ char\\rb{\\R} = 0 \\notin \\cb{2, 3} $, there is an affine transformation $ \\rb{x, y} \\mapsto \\rb{x, y - x - \\tfrac{1}{6}} $ such that\n$$ \\rb{y - x - \\tfrac{1}{6}}^2 + 2x\\rb{y - x - \\tfrac{1}{6}} + \\tfrac{1}{3}\\rb{y - x - \\tfrac{1}{6}} = x^3 - x^2 - \\tfrac{1}{3}x - \\tfrac{1}{27} \\qquad \\implies \\qquad y^2 = x^3 + \\tfrac{1}{108}, $$\nwhich is a short Weierstrass equation.\n\\end{example}\n\nAmong the quantities associated with Weierstrass curves, most are used in defining the simplified Weierstrass equations, while the last two, the discriminant $ \\Delta_W $ and the $ j $-invariant $ j_W $, encode various properties of the curve itself. As only short Weierstrass equations are considered, these two quantities can be restated in an equivalent form in terms of the new coefficients. The discriminant is redefined as follows.\n\n\\begin{definition}[Discriminant]\nThe \\textbf{discriminant} of $ W $ is\n$$ \\Delta_W = -16\\rb{4A^3 + 27B^2}. $$\n\\end{definition}\n\nThe discriminant is transformed as $ \\Delta_W \\mapsto \\Delta_W / u^{12} $ by the affine transformation in Proposition \\ref{prop:affine}. It encodes behaviours at the singularities of Weierstrass curves, and whether they exist. The following proposition allows for an easy method of checking the smoothness of a Weierstrass curve.\n\n\\begin{proposition}\n$ W $ is smooth iff $ \\Delta_W \\ne 0 $.\n\\end{proposition}\n\n\\begin{proof}\nAssume that $ W $ is not smooth and $ P = \\rb{a, b} \\in W $ is singular. Then\n$$ 0 = \\val{\\dfrac{\\partial w}{\\partial X}}_P = -3a^2 - A, \\qquad 0 = \\val{\\dfrac{\\partial w}{\\partial Y}}_P = 2b, \\qquad 0 = \\val{\\dfrac{\\partial w}{\\partial Z}}_P = b^2 - 2Aa - 3B. $$\nSince $ b = 0 $ and $ A = -3a^2 $, it holds that $ 0 = 2Aa + 3B = -6a^3 + 3B $, so $ B = 2a^3 $. Hence $ \\Delta_W = -16\\rb{4\\rb{-3a^2}^3 + 27\\rb{2a^3}^2} = 0 $. Conversely assume that $ \\Delta_W = -16\\rb{4A^3 + 27B^2} = 0 $, such that the discriminant of $ x^3 + Ax + B $ is $ -\\rb{4A^3 + 27B^2} = 0 $. Then there is a repeated root $ x = a \\in K $, so $ P = \\rb{a, 0} \\in W $ and\n$$ W : y^2 = \\rb{x - a}^2\\rb{x - a'}, \\qquad a' \\in K. $$\nThen\n$$ \\val{\\dfrac{\\partial w}{\\partial x}}_P = -2\\rb{a - a}\\rb{a - a'} - \\rb{a - a}^2 = 0, \\qquad \\val{\\dfrac{\\partial w}{\\partial y}}_P = 2\\rb{0} = 0. $$\nThus $ P $ is singular and $ W $ is not smooth.\n\\end{proof}\n\nHence $ W $ is eligible as an elliptic curve iff $ \\Delta_W \\ne 0 $, and by the proof above, iff $ x^3 + Ax + B $ has distinct factors. The following example illustrates the discriminant.\n\n\\begin{example}\nLet $ E $ be the Weierstrass curve over $ \\R $ from the example above. Then\n$$ \\Delta_E = -16\\rb{4\\rb{0}^3 + 27\\rb{\\tfrac{1}{108}}^2} = -\\tfrac{1}{27} < 0, $$\nso $ E $ is smooth. Thus $ E $ is an elliptic curve over $ \\R $.\n\\end{example}\n\nThe $ j $-invariant, defined only for smooth Weierstrass curves where $ \\Delta_W \\ne 0 $, is redefined as follows.\n\n\\begin{definition}[$ j $-invariant]\nThe \\textbf{$ j $-invariant} of $ W $ is\n$$ j_W = 1728\\rb{\\dfrac{4A^3}{4A^3 + 27B^2}}. $$\n\\end{definition}\n\nThe $ j $-invariant is transformed as $ j_W \\mapsto j_W $ by the affine transformation in Proposition \\ref{prop:affine}. It stays invariant between elliptic curves that are isomorphic, which gives its name. The following proposition allows for an alternative characterisation of an isomorphism.\n\n\\begin{proposition}\n$ E \\cong E' $ iff $ j_W = j_{W'} $.\n\\end{proposition}\n\n\\begin{proof}\nAssume that $ E \\cong E' $, then the affine transformation maps $ j_W $ to $ j_W $, so $ j_W = j_{W'} $. Conversely assume that $ j_W = j_{W'} $, so\n$$ 1728\\rb{\\dfrac{4A^3}{4A^3 + 27B^2}} = 1728\\rb{\\dfrac{4A'^3}{4A'^3 + 27B'^2}} \\qquad \\implies \\qquad A^3B'^2 = A'^3B^2. $$\nIf $ A = 0 $, then $ B \\ne 0 $ and $ A' = 0 $. Then there is an affine transformation\n$$ \\rb{x, y} \\mapsto \\rb{\\sqrt[3]{\\dfrac{B}{B'}}x, \\sqrt{\\dfrac{B}{B'}}y} \\qquad \\implies \\qquad \\dfrac{B}{B'}y^2 = \\dfrac{B}{B'}x^3 + A'\\sqrt[3]{\\dfrac{B}{B'}}x + B', $$\nsuch that $ y^2 = x^3 + B' = x^3 + A'x + B' $. If $ B = 0 $, then $ A \\ne 0 $ and $ B' = 0 $. Then there is also an affine transformation\n$$ \\rb{x, y} \\mapsto \\rb{\\sqrt{\\dfrac{A}{A'}}x, \\sqrt[4]{\\dfrac{A}{A'}}^3y} \\qquad \\implies \\qquad \\sqrt{\\dfrac{A}{A'}}^3y^2 = \\sqrt{\\dfrac{A}{A'}}^3x^3 + A'\\sqrt{\\dfrac{A}{A'}}x + B', $$\nsuch that $ y^2 = x^3 + A'x = x^3 + A'x + B' $. Otherwise $ A \\ne 0 $ and $ B \\ne 0 $, then there is an affine transformation from $ W $ to $ W' $ equal to the two affine transformations above. Thus $ E \\cong E' $.\n\\end{proof}\n\nWhile $ j $-invariant affine transformations preserve elliptic curves, this does not necessarily hold for their set of rational points. The following illustrates the $ j $-invariant.\n\n\\begin{example}\nLet $ E $ be the elliptic curve over $ \\R $ from the example above. Then\n$$ j_E = -1728\\rb{\\dfrac{4\\rb{0}^3}{4\\rb{0}^3 + 27\\rb{\\frac{1}{108}}^2}} = 0. $$\nHence $ E $ is isomorphic to any elliptic curve with zero $ j $-invariant. Now let $ E' : y^2 = x^3 + B $ for some $ B \\in \\R $ such that $ j_{E'} = 0 $, then there is an affine transformation\n$$ \\rb{x, y} \\mapsto \\rb{\\dfrac{1}{3\\sqrt[3]{2}^2B}x, \\dfrac{1}{2\\sqrt{3}^3B}y}. $$\nfrom $ E $ to $ E' $. Thus $ E \\cong E' $.\n\\end{example}\n\nThe definition and isomorphism classes of elliptic curves are now fully characterised.\n\n\\begin{remark}\nThere are alternate characterisations of elliptic curves by other families of curves, which will not be discussed here. One of these is the \\emph{Legendre form} of a Weierstrass curve, written as\n$$ E : y^2 = x\\rb{x - 1}\\rb{x - \\lambda}, \\qquad \\lambda \\in K \\setminus \\cb{0, 1}. $$\nThis is merely a transformation, but proves useful when studying elliptic curves over the reals.\n\\end{remark}\n\n\\pagebreak\n\n\\subsection{Group law}\n\nAn elliptic curve has an additional group theoretic property that makes it an \\emph{algebraic group}. This subsection provides a full definition of the additive group induced by an elliptic curve, as well as an attempt to prove that it is indeed one. The following lemma will be used in the definition of the addition operation.\n\n\\begin{lemma}\n\\label{lem:thirdpoint}\nLet $ P = \\sb{a, b, c} \\in E $ and $ Q = \\sb{a', b', c'} \\in E $ be points. Then:\n\\begin{enumerate}\n\\item if $ P \\ne Q $, there is a unique line joining $ P $ and $ Q $ given by\n$$ L : \\rb{bc' - b'c}X + \\rb{a'c - ac'}Y + \\rb{ab' - a'b}Z = 0, $$\n\\item if $ P = Q $, there is a unique tangent at $ P $ given by\n$$ L : \\rb{-3a^2 - Ac^2}X + 2bcY + \\rb{b^2 - 2Aac - 3Bc^2}Z = 0, $$\n\\item there is a unique third point $ R \\in E $ such that $ L $ intersects $ E $ at $ P $, $ Q $, and $ R $.\n\\end{enumerate}\n\\end{lemma}\n\n\\begin{proof}\nLet $ L : l\\rb{X, Y, Z} = 0 $.\n\\begin{enumerate}\n\\item If $ P \\ne Q $, then\n$$ l\\rb{X, Y, Z} = \\threebyone{X}{Y}{Z} \\cdot \\rb{\\threebyone{a}{b}{c} \\times \\threebyone{a'}{b'}{c'}}. $$\n\\item If $ P = Q $, then\n$$ l\\rb{X, Y, Z} = \\twobyone{1}{1, 0, 0}\\val{\\dfrac{\\partial e}{\\partial X}}_P\\rb{X - a} + \\twobyone{1}{0, 1, 0}\\val{\\dfrac{\\partial e}{\\partial Y}}_P\\rb{Y - b} + \\twobyone{1}{0, 0, 1}\\val{\\dfrac{\\partial e}{\\partial Z}}_P\\rb{Z - c}. $$\n\\item Since $ \\deg\\rb{l} = 1 $ and $ \\deg\\rb{\\gcd\\rb{e, l}} = 0 $, B\\'ezout's theorem gives that $ L $ intersects $ E $ at three points up to multiplicity. Assume that $ P = \\sb{a, b, c} \\ne Q = \\sb{a', b', c'} $. If $ I_P\\rb{e, l} = 1 $ and $ I_Q\\rb{e, l} = 1 $, then there is a unique third point $ R \\in E $ such that $ R \\ne P, Q $ and $ I_R\\rb{e, l} = 1 $. Otherwise $ I_P\\rb{e, l} = 2 $ or $ I_Q\\rb{e, l} = 2 $, then there is also a unique third point $ R = P $ or $ R = Q $ respectively. Otherwise assume that $ P = Q = \\sb{a, b, c} $. Since $ \\cb{l} = T_P\\rb{l} \\in T_P\\rb{e} $, it holds that $ I_P\\rb{e, l} > m_P\\rb{e}m_P\\rb{l} = 1 $. If $ I_P\\rb{e, l} = 2 $, then there is a unique third point $ R \\in E $ such that $ R \\ne P $ and $ I_R\\rb{e, l} = 1 $. Otherwise $ I_P\\rb{e, l} = 3 $, then there is also a unique third point $ R = P $.\n\\end{enumerate}\n\\end{proof}\n\nThe following example illustrates the unique lines and tangents above.\n\n\\begin{example}\nLet $ E : y^2 = x^3 + 2x + 1 $ be an elliptic curve over $ \\R $ with points $ P = \\rb{0, -1} \\in E $ and $ Q = \\rb{1, 2} \\in E $. Then the unique line joining $ P $ and $ Q $ is $ L : y = 3x - 1 $, while the tangent at $ P $ is $ L_P : y = -x - 1 $, and the tangent at $ Q $ is $ L_Q : y = \\tfrac{5}{4}x + \\tfrac{3}{4} $.\n\\end{example}\n\nInstead of defining the addition operation right away, it is clearer to define an intermediate operation with the above lemma as follows.\n\n\\begin{definition}[$ * $]\n$ * : E \\times E \\to E $ is defined by $ P * Q = R $, where $ R $ is the unique third point in Lemma \\ref{lem:thirdpoint}.\n\\end{definition}\n\nThe addition operation can then be defined immediately in terms of this intermediate operation, which are both symmetric and hence commutative.\n\n\\begin{definition}[$ + $]\n$ + : E \\times E \\to E $ is defined by $ P + Q = \\rb{P * Q} * \\mathcal{O} $.\n\\end{definition}\n\nThis definition is chosen carefully so as to make a group law possible. While it might be slightly convoluted, there is an easy geometrical interpretation. While $ P * Q \\in E $ is simply the unique third intersection point of two points $ P \\in E $ and $ Q \\in E $, reflecting it along the horizontal axis gives $ P + Q $. This motivates writing out several explicit formulae relating the affine coordinates of $ P $, $ Q $ and $ P + Q $, which will allow equation manipulations in later sections. The following algorithm summarises the explicit formulae for $ + $, which are proven in the appendix.\n\n\\begin{algorithm}[Group law explicit formulae]\nInput: points $ P, Q \\in E $. Output: $ P + Q $.\n$$ P + Q = \\begin{cases} R & P = \\rb{a, b}, \\ Q = \\rb{a', b'}, \\ a \\ne a' \\\\ S & P = Q = \\rb{a, b}, \\ b \\ne 0 \\\\ P & Q = \\mathcal{O} \\\\ \\mathcal{O} & P = Q = \\rb{a, 0} \\end{cases}, $$\nwhere\n$$ R = \\rb{\\dfrac{\\rb{A + aa'}\\rb{a + a'} + 2\\rb{B - bb'}}{\\rb{a - a'}^2}, \\dfrac{\\rb{Ab' - a'^2b}\\rb{3a + a'} + \\rb{a^2b' - Ab}\\rb{a + 3a'} - 4B\\rb{b - b'}}{\\rb{a - a'}^3}}, $$\n$$ S = \\rb{\\dfrac{a^4 - 2Aa^2 - 8Ba + A^2}{4b^2}, \\dfrac{a^6 + 5Aa^4 + 20Ba^3 - 5A^2a^2 - 4ABa - A^3 - 8B^2}{8b^3}}. $$\n\\end{algorithm}\n\nThe first case is referred to as the \\emph{addition formula}, while the second case is referred to as the \\emph{duplication formula}. The last two cases allows the definition of a negation operation used for inverses in the group law. This is referred to as the \\emph{negation formula}, where $ -\\mathcal{O} = \\mathcal{O} $ and $ -\\rb{a, b} = \\rb{a, -b} $. Now the group law explicit formulae for characteristic two and three are more complicated and given in full under code listings in the appendix. The following example illustrates an implementation of the algorithm in the appendix.\n\n\\begin{example}\nLet $ E $ be the elliptic curve over $ \\R $ and let $ L $, $ L_P $, $ L_Q $ be the lines for the points $ P, Q \\in E $ from the example above. Then $ L $ intersects $ E $ at $ \\rb{3x - 1}^2 = x^3 + 2x + 1 $, or $ x\\rb{x - 1}\\rb{x - 8} = 0 $. Hence $ P * Q = \\rb{8, 23} $, so $ P + Q = \\rb{8, -23} $. Similarly $ L_P $ intersects $ E $ at $ \\rb{-x - 1}^2 = x^3 + 2x + 1 $, or $ x^2\\rb{x - 1} = 0 $, while $ L_Q $ intersects $ E $ at $ \\rb{\\tfrac{5}{4}x + \\tfrac{3}{4}}^2 = x^3 + 2x + 1 $, or $ \\rb{x - 1}^2\\rb{16x + 7} = 0 $. Thus $ P * P = \\rb{1, -2} $ and $ Q * Q = \\rb{-7 / 16, 13 / 64} $, so $ P + P = \\rb{1, 2} $ and $ Q + Q = \\rb{-7 / 16, -13 / 64} $.\n\\end{example}\n\nAn alternative formulation for $ + $ is such that three points $ P, Q, R \\in E $ are collinear iff\n$$ P + Q + R = P + \\rb{Q + R} = \\rb{P + Q} + R = \\mathcal{O}. $$\nThis formulation will help in proving that certain maps obey some property later, but also allows for a pictorial description for $ * $. As per the notation in the appendix: the first pane describes $ \\rb{*}_2 $; the second pane describes $ \\rb{*}_3 $; the third pane describes $ \\rb{*}_1 $ and $ \\rb{*}_5 $; the fourth pane describes $ \\rb{*}_4 $; the unillustrated line at infinity describes $ \\rb{*}_6 $.\n\\begin{center}\n\\includegraphics*[width=0.9\\textwidth]{img/ECClines.png}\n\\end{center}\n\n\\pagebreak\n\nThe group structure of an elliptic curve with respect to $ + $ can now be stated in the following theorem.\n\n\\begin{theorem}[Group law]\n$ \\rb{E, \\mathcal{O}, +} $ is an abelian group.\n\\end{theorem}\n\nAs full proofs for associativity such as in III.3.4 of \\cite{gtm} require further prerequisites on algebraic curves, particularly on \\emph{divisors} and \\emph{differentials}, only the sketch of an alternative geometric proof is given, of which the special case of nine pairwise distinct points is assumed.\n\n\\begin{proof}\nThe unique right identity is $ \\mathcal{O} \\in E $ and unique right inverses are given by the negation formula. Symmetry of $ + $ gives the unique identity, unique right inverses, and commutativity. Associativity of $ + $ can be checked with various methods, such as by tediously verifying cases of the explicit formulae in \\cite{grouplaw}. Alternatively, let $ P, Q, R \\in E $ be points, and let\n\\begin{itemize}\n\\item $ L_1 : l_1\\rb{X, Y, Z} = 0 $ be the line joining $ P $, $ Q $, and $ P * Q = -\\rb{P + Q} $,\n\\item $ L_2 : l_2\\rb{X, Y, Z} = 0 $ be the line joining $ Q $, $ R $, and $ Q * R = -\\rb{Q + R} $,\n\\item $ L_3 : l_3\\rb{X, Y, Z} = 0 $ be the line joining $ P + Q $, $ \\mathcal{O} $, and $ \\rb{P + Q} * \\mathcal{O} = -\\rb{P + Q} $,\n\\item $ L_4 : l_4\\rb{X, Y, Z} = 0 $ be the line joining $ Q + R $, $ \\mathcal{O} $, and $ \\rb{Q + R} * \\mathcal{O} = -\\rb{Q + R} $,\n\\item $ L_5 : l_5\\rb{X, Y, Z} = 0 $ be the line joining $ P + Q $, $ R $, and $ \\rb{P + Q} * R = -\\rb{\\rb{P + Q} + R} $, and\n\\item $ L_6 : l_6\\rb{X, Y, Z} = 0 $ be the line joining $ P $, $ Q + R $, and $ P * \\rb{Q + R} = -\\rb{P + \\rb{Q + R}} $,\n\\end{itemize}\nassuming that these points are pairwise distinct except for $ -\\rb{\\rb{P + Q} + R} $ and $ -\\rb{P + \\rb{Q + R}} $. Now let\n$$ C_1 : \\rb{l_1l_4l_5}\\rb{X, Y, Z} = 0, \\qquad C_2 : \\rb{l_2l_3l_6}\\rb{X, Y, Z} = 0, $$\nbe cubics such that\n$$ I = \\cb{\\mathcal{O}, P, Q, R, P + Q, Q + R, -\\rb{P + Q}, -\\rb{Q + R}} \\subseteq C_1 \\cap C_2. $$\nThen B\\'ezout's theorem gives that $ E $, $ C_1 $, and $ C_2 $ pairwise intersect at nine points up to multiplicity. Hence\n$$ E \\cap C_1 = I \\cup \\cb{-\\rb{\\rb{P + Q} + R}}, \\qquad E \\cap C_2 = I \\cup \\cb{-\\rb{P + \\rb{Q + R}}}, \\qquad C_1 \\cap C_2 = I \\cup \\cb{S}, $$\nfor some ninth point $ S \\in C_1 \\cap C_2 $. Since $ I \\subseteq E $, the Cayley-Bacharach theorem gives $ S \\in E $, so\n$$ -\\rb{\\rb{P + Q} + R} = S = -\\rb{P + \\rb{Q + R}}. $$\nThus $ \\rb{P + Q} + R = P + \\rb{Q + R} $.\n\\end{proof}\n\nWith an abelian group at hand, some group theoretic properties of an elliptic curve can be explored. In particular, restricting an elliptic curve onto its $ F $-rational points retain the group structure.\n\n\\begin{proposition}\n$ \\rb{E\\rb{F}, \\mathcal{O}, +} \\le \\rb{E, \\mathcal{O}, +} $.\n\\end{proposition}\n\n\\begin{proof}\nSince $ 0, 1 \\in F $, it holds that $ \\mathcal{O} \\in E\\rb{F} $. Let $ P, Q \\in E\\rb{F} $ be points, then the explicit formulae give $ -P, P + Q \\in E\\rb{F} $. Thus $ \\rb{E\\rb{F}, \\mathcal{O}, +} \\le \\rb{E, \\mathcal{O}, +} $.\n\\end{proof}\n\nAdditionally, the $ n $-torsion points of an elliptic curve also form a group, provided $ \\mathcal{O} $ is included. The following example illustrates the structure of the $ 2 $-torsion subgroup.\n\n\\begin{example}\nLet $ P = \\rb{a, b} \\in E\\sb{2} $, then $ b = -b = 0 $. Since $ x^3 + Ax + B = 0 $ has three distinct solutions, there are three distinct points $ P_1 = \\rb{a_1, 0} $, $ P_2 = \\rb{a_2, 0} $, and $ P_3 = \\rb{a_3, 0} $ in $ E\\sb{2} $. Thus $ \\rb{E\\sb{2}, \\mathcal{O}, +} = \\rb{\\cb{\\mathcal{O}, P_1, P_2, P_3}, \\mathcal{O}, +} \\cong \\rb{\\Z_2^2, 0, +} $.\n\\end{example}\n\nHence $ b = 0 $ iff $ ord\\rb{a, b} = 2 $.\n\n\\begin{remark}\nIn fact, the $ n $-torsion points of $ E $ form a subgroup $ E\\sb{n} $ of $ E $, such that $ \\rb{E\\sb{p}, \\mathcal{O}, +} \\cong \\rb{\\Z_p^2, 0, +} $ if $ char\\rb{F} \\nmid p $, and either $ \\rb{E\\sb{p^e}, \\mathcal{O}, +} \\cong \\rb{\\cb{0}, 0, +} $ or $ \\rb{E\\sb{p^e}, \\mathcal{O}, +} \\cong \\rb{\\Z_{p^e}, 0, +} $ for all $ e \\in \\Z_{> 0} $ if $ char\\rb{F} \\mid p $.\n\\end{remark}\n\n\\pagebreak\n\n\\subsection{Isogenies}\n\nPrior to this section, the only maps between elliptic curves that have been defined were affine transformations. Now that the group law is defined, group homomorphisms can also be considered. However, a slightly different approach to this will be taken with the following definition, noting that morphisms of curves are either constant or surjective.\n\n\\begin{definition}[Isogeny]\nAn \\textbf{isogeny} from $ E $ to $ E' $ is a surjective morphism $ \\phi : E \\to E' $ such that $ \\phi\\rb{\\mathcal{O}} = \\mathcal{O} $.\n\\end{definition}\n\nAs isomorphisms are defined as invertible morphisms that preserve the point at infinity, they are isogenies as well. Now despite the simple condition, isogenies are actually group homomorphisms, which also preserve the point at infinity. The following proposition then gives an equivalent definition.\n\n\\begin{proposition}\nLet $ \\phi : E \\to E' $ be an isogeny. Then $ \\phi $ is a group homomorphism.\n\\end{proposition}\n\n\\begin{proof}\nOmitted, see III.4.8 in \\cite{gtm}.\n\\end{proof}\n\nThe following is a typical example of an isogeny.\n\n\\begin{example}\nThe \\emph{multiplication by $ n $ map} $ \\sb{n} : E \\to E $ defined by $ \\sb{n}\\rb{P} = nP $ is an isogeny such that $ Ker\\rb{\\sb{n}} = E\\sb{n} $.\n\\end{example}\n\nLet $ \\phi : E \\to E' $ be an isogeny. While isomorphisms are easily characterised by $ j $-invariant affine transformations, the smaller restriction on isogenies allow for a wider range of coordinate transformations that still obey the group homomorphism property. In particular, rational functions that define isogenies can be characterised by the following lemma.\n\n\\begin{lemma}\nLet $ f \\in F\\rb{E} $ be a rational function. Then\n$$ f\\rb{x, y} = \\dfrac{f'\\rb{x} + f''\\rb{x}y}{f'''\\rb{x}}, \\qquad f', f'' \\in F\\sb{x}, \\qquad f''' \\in F\\sb{x} \\setminus \\cb{0}. $$\n\\end{lemma}\n\n\\begin{proof}\nLet $ f = g / h $ for some $ g \\in F\\sb{x, y} $ and some $ h \\in F\\sb{x, y} \\setminus \\cb{0} $. Then $ g\\rb{x, y} = \\sum_{i = 0}^n g_i\\rb{x}y^i $ for some $ g_i \\in F\\sb{x} $, some $ h_i \\in F\\sb{x} \\setminus \\cb{0} $, and some $ n, m \\in \\Z_{\\ge 0} $, so:\n\\begin{align*}\ng\\rb{x, y}\n& = \\sum_{i = 0}^n g_i\\rb{x}y^i\n= \\sum_{i = 0}^{n / 2} g_{2i}\\rb{x}y^{2i} + \\sum_{i = 0}^{n / 2} g_{2i + 1}\\rb{x}y^{2i + 1} \\\\\n& = \\sum_{i = 0}^{n / 2} g_{2i}\\rb{x}\\rb{x^3 + Ax + B}^i + \\sum_{i = 0}^{n / 2} g_{2i + 1}\\rb{x}\\rb{x^3 + Ax + B}^iy \\\\\n& = g'\\rb{x} + g''\\rb{x}y, \\qquad g', g'' \\in F\\sb{x}.\n\\end{align*}\nSimilarly $ h\\rb{x, y} = h'\\rb{x} + h''\\rb{x}y $ for some $ h', h'' \\in F\\sb{x} $. Thus\n\\begin{align*}\nf\\rb{x, y}\n& = \\dfrac{g\\rb{x, y}}{h\\rb{x, y}}\n= \\dfrac{g'\\rb{x} + g''\\rb{x}y}{h'\\rb{x} + h''\\rb{x}y}\n= \\dfrac{\\rb{g'\\rb{x} + g''\\rb{x}y}\\rb{h'\\rb{x} - h''\\rb{x}y}}{\\rb{h'\\rb{x} + h''\\rb{x}y}\\rb{h'\\rb{x} - h''\\rb{x}y}} \\\\\n& = \\dfrac{g'\\rb{x}h'\\rb{x} - g''\\rb{x}h''\\rb{x}y^2 - g'\\rb{x}h''\\rb{x}y + g''\\rb{x}h'\\rb{x}y}{h'\\rb{x}^2 - h''\\rb{x}^2y^2} \\\\\n& = \\dfrac{g'\\rb{x}h'\\rb{x} - g''\\rb{x}h''\\rb{x}\\rb{x^3 + Ax + B} - g'\\rb{x}h''\\rb{x}y + g''\\rb{x}h'\\rb{x}y}{h'\\rb{x}^2 - h''\\rb{x}^2\\rb{x^3 + Ax + B}} \\\\\n& = \\dfrac{f'\\rb{x} + f''\\rb{x}y}{f'''\\rb{x}}, \\qquad f, f' \\in F\\sb{x}, \\qquad f'' \\in F\\sb{x} \\setminus \\cb{0}.\n\\end{align*}\n\\end{proof}\n\n\\pagebreak\n\nAn entire isogeny can now be characterised similarly, noting the group homomorphism property. The following proposition gives the explicit \\emph{standard form} of an isogeny, defined in terms of its image.\n\n\\begin{proposition}\nLet $ P = \\rb{a, b} \\in E \\setminus Ker\\rb{\\phi} $ be a point. Then\n$$ \\phi\\rb{P} = \\rb{\\dfrac{r\\rb{a}}{s\\rb{a}}, \\dfrac{u\\rb{a}}{v\\rb{a}}b} \\qquad r, u \\in F\\sb{x}, \\qquad s, v \\in F\\sb{x} \\setminus \\cb{0}, $$\nsuch that $ \\gcd\\rb{r, s} = \\gcd\\rb{u, v} = 1 $.\n\\end{proposition}\n\n\\begin{proof}\nLet $ \\phi = \\sb{\\phi_x, \\phi_y, \\phi_z} $ for some $ \\phi_x, \\phi_y, \\phi_z \\in F\\rb{E} $. Since $ \\phi\\rb{P} \\ne \\mathcal{O} $, it holds that $ \\phi_z\\rb{P} \\ne 0 $, so\n$$ \\phi\\rb{P} = \\sb{\\phi_x\\rb{P}, \\phi_y\\rb{P}, \\phi_z\\rb{P}} = \\rb{\\dfrac{\\phi_x\\rb{P}}{\\phi_z\\rb{P}}, \\dfrac{\\phi_y\\rb{P}}{\\phi_z\\rb{P}}}. $$\nThen $ \\phi_x\\rb{P} / \\phi_z\\rb{P}, \\phi_y\\rb{P} / \\phi_z\\rb{P} \\in F\\rb{E} $ are rational functions, so\n$$ \\dfrac{\\phi_x\\rb{P}}{\\phi_z\\rb{P}} = \\dfrac{\\psi\\rb{a} + \\psi'\\rb{a}b}{\\psi''\\rb{a}}, \\qquad \\dfrac{\\phi_y\\rb{P}}{\\phi_z\\rb{P}} = \\dfrac{\\chi\\rb{a} + \\chi'\\rb{a}b}{\\chi''\\rb{a}}, \\qquad \\psi, \\psi', \\chi, \\chi' \\in F\\sb{x}, \\qquad \\psi'', \\chi'' \\in F\\sb{x} \\setminus \\cb{0}. $$\nSince $ \\phi\\rb{-P} = -\\phi\\rb{P} $,\n$$ \\rb{\\dfrac{\\psi\\rb{a} + \\psi'\\rb{a}\\rb{-b}}{\\psi''\\rb{a}}, \\dfrac{\\chi\\rb{a} + \\chi'\\rb{a}\\rb{-b}}{\\chi''\\rb{a}}} = \\phi\\rb{-P} = -\\phi\\rb{P} = \\rb{\\dfrac{\\psi\\rb{a} + \\psi'\\rb{a}b}{\\psi''\\rb{a}}, -\\dfrac{\\chi\\rb{a} + \\chi'\\rb{a}b}{\\chi''\\rb{a}}}. $$\nHence $ \\psi'\\rb{a} = \\chi\\rb{a} = 0 $. Now let $ g = \\gcd\\rb{\\psi, \\psi''} $ and $ g' = \\gcd\\rb{\\chi', \\chi''} $. Thus let\n$$ r = \\dfrac{\\psi}{g}, u = \\dfrac{\\chi'}{g'} \\in F\\sb{x}, \\qquad s = \\dfrac{\\psi''}{g}, v = \\dfrac{\\chi''}{g'} \\in F\\sb{x} \\setminus \\cb{0}, $$\nsuch that $ \\gcd\\rb{r, s} = \\gcd\\rb{u, v} = 1 $.\n\\end{proof}\n\nIn the above proof, the assumption that a point $ P \\in E $ is not in the kernel allows for the isogeny to be scaled appropriately. If $ P $ is in the kernel, it would be mapped to the point at infinity, which would mean that $ \\phi_z $, and hence $ s $ or $ v $, is zero. With this in mind, an abuse of notation allows for the standard form to be written as\n$$ \\phi\\rb{x, y} = \\rb{\\dfrac{r\\rb{x}}{s\\rb{x}}, \\dfrac{u\\rb{x}}{v\\rb{x}}y}, \\qquad r, s, u, v \\in F\\sb{x}, \\qquad \\gcd\\rb{r, s} = \\gcd\\rb{u, v} = 1, $$\nremembering that $ \\phi\\rb{\\mathcal{O}} = \\mathcal{O} $, and $ \\phi\\rb{a, b} = \\mathcal{O} $ whenever $ s\\rb{a} = 0 $ or $ v\\rb{a} = 0 $ for any point $ \\rb{a, b} \\in E $. The following example rewrites the multiplication by two map with the familiar duplication formula.\n\n\\begin{example}\nBy the duplication formula,\n\\begin{align*}\n\\sb{2}\\rb{x, y}\n& = \\rb{\\dfrac{x^4 - 2Ax^2 - 8Bx + A^2}{4y^2}, \\dfrac{x^6 + 5Ax^4 + 20Bx^3 - 5A^2x^2 - 4ABx - A^3 - 8B^2}{8y^3}} \\\\\n& = \\rb{\\dfrac{x^4 - 2Ax^2 - 8Bx + A^2}{4\\rb{x^3 + Ax + B}}, \\dfrac{x^6 + 5Ax^4 + 20Bx^3 - 5A^2x^2 - 4ABx - A^3 - 8B^2}{8\\rb{x^3 + Ax + B}^2}y},\n\\end{align*}\nwhich is in standard form. Then $ \\sb{2}\\rb{a, b} = \\mathcal{O} $ iff $ b^2 = a^3 + Aa + B = 0 $ for any point $ \\rb{a, b} \\in E $.\n\\end{example}\n\nThere are also two useful notions of an isogeny, the first of which is its degree.\n\n\\begin{definition}[Isogeny degree]\nThe \\textbf{degree} of $ \\phi $ is $ \\deg\\rb{\\phi} = \\max\\cb{\\deg\\rb{r}, \\deg\\rb{s}} $.\n\\end{definition}\n\nThe degree of the constant morphism, while not an isogeny, is defined to be zero. The degrees of two trivial isogenies are given in the following example.\n\n\\begin{example}\nThe identity isogeny, or the multiplication by one map $ \\sb{1} $ has degree $ \\deg\\rb{\\sb{1}} = \\max\\cb{1, 1} = 1 $. Similarly, the multiplication by negative one map $ \\sb{-1} $ also has degree $ \\deg\\rb{\\sb{-1}} = 1 $.\n\\end{example}\n\n\\pagebreak\n\nThe second invariant notion of an isogeny is its separability.\n\n\\begin{definition}[Separable isogeny]\n$ \\phi $ is \\textbf{separable} iff $ d\\rb{r / s} / dx \\ne 0 $.\n\\end{definition}\n\n\\begin{remark}\nThe isogeny $ \\phi $ induces an injection $ \\phi^* : F\\rb{E'} \\to F\\rb{E} $ of function fields. Its separability is equivalently formulated as that of $ F\\rb{E} / \\phi^*F\\rb{E'} $, which reflects the definition of a separable extension.\n\\end{remark}\n\nThe following example of the multiplication by two map illustrates these two notions.\n\n\\begin{example}\n$ \\sb{2} $ has degree $ \\deg\\rb{\\sb{2}} = \\max\\cb{4, 3} = 4 $ and is separable since\n$$ \\dfrac{d}{dx}\\rb{\\dfrac{x^4 - 2Ax^2 - 8Bx + A^2}{4\\rb{x^3 + Ax + B}}} = \\dfrac{x^6 + 5Ax^4 + 20Bx^3 - 5A^2x^2 - 4ABx - A^3 - 8B^2}{4\\rb{x^3 + Ax + B}^2} \\ne 0. $$\n\\end{example}\n\nSeparability always holds in $ char\\rb{F} = 0 $, but there are inseparable isogenies in $ char\\rb{F} = p $ for some prime $ p \\in \\Z_{> 0} $. More on separable isogenies will be discussed in a later section. Now since $ + $ is a morphism, the set of all isogenies between $ E $ and $ E' $, together with the constant morphism, forms an abelian group $ Hom\\rb{E, E'} $ under the operation\n$$ \\rb{\\phi + \\psi}\\rb{P} = \\phi\\rb{P} + \\psi\\rb{P}. $$\nIsogenies in the group can also compose to form a ring when $ E = E' $ in the following definition.\n\n\\begin{definition}[Endomorphism]\n$ \\phi $ is an \\textbf{endomorphism} of $ E $ iff $ E = E' $. The \\textbf{endomorphism ring} $ End\\rb{E} $ of $ E $ is the ring of all endomorphisms of $ E $ with respect to $ + $ and $ \\circ $, where\n$$ \\rb{\\phi \\circ \\psi} = \\phi\\rb{\\psi\\rb{P}}. $$\n\\end{definition}\n\nThe following example gives an endomorphism of elliptic curves over fields of non-zero characteristic that is of particular interest.\n\n\\begin{example}\nLet $ F = \\F_p $ for some prime $ p \\in \\Z_{> 0} $. Then the \\emph{Frobenius endomorphism} $ Fr : E \\to E $ defined by $ Fr\\rb{x, y} = \\rb{x^p, y^p} $ is an inseparable endomorphism with degree $ \\deg\\rb{Fr} = p $.\n\\end{example}\n\nThe Frobenius endomorphism will be formally defined in a later section. On a final note, endomorphisms with inverses also form a multiplicative subgroup.\n\n\\begin{definition}[Automorphism]\n$ \\phi $ is an \\textbf{automorphism} of $ E $ iff it is an endomorphism and an isomorphism. The \\textbf{automorphism group} $ Aut\\rb{E} $ is the group of all automorphisms of $ E $.\n\\end{definition}\n\nUnlike the endomorphism ring, the automorphism group of an elliptic curve is easily characterised.\n\n\\begin{proposition}\n$$ Aut\\rb{E} \\cong \\begin{cases} \\Z_6 & j_E = 0 \\\\ \\Z_4 & j_E = 1728 \\\\ \\Z_2 & j_E \\notin \\cb{0, 1728} \\end{cases}. $$\n\\end{proposition}\n\n\\begin{proof}\nLet $ \\phi \\in Aut\\rb{E} $. Then $ \\phi $ induces a $ j $-invariant affine transformation\n$$ \\rb{x, y} \\mapsto \\rb{u^2x + r, u^3y + u^2sx + t}, \\qquad u \\in K^*, \\qquad r, s, t \\in K $$\nfrom $ W $ to itself. Since $ \\phi $ is an automorphism, it holds that $ r = s = t = 0 $, and $ A = A / u^4 $ and $ B = B / u^6 $. If $ j_E = 0 $, then $ A = 0 $ and $ B \\ne 0 $, so $ u^6 = 1 $. Hence $ u $ is a sixth root of unity and $  Aut\\rb{E} \\cong \\Z_6 $. If $ j_E = 1728 $, then $ A \\ne 0 $ and $ B = 0 $, so $ u^4 = 1 $. Hence $ u $ is a fourth root of unity and $ Aut\\rb{E} \\cong \\Z_4 $. Otherwise $ j_E \\notin \\cb{0, 1728} $, then $ A \\ne 0 $ and $ B \\ne 0 $, so $ u^6 = 1 $ and $ u^4 = 1 $. Hence $ u^2 = 1 $ and $ u $ is a second root of unity. Thus $ Aut\\rb{E} \\cong \\Z_2 $.\n\\end{proof}\n\n\\begin{remark}\nIf $ char\\rb{F} \\in \\cb{2, 3} $, then the above list of cases for $ Aut\\rb{E} $ with $ j_E = 0, 1728 $ is not exhaustive. In particular, if $ char\\rb{F} = 2 $, then $ Aut\\rb{E} \\cong \\Z_4 \\ltimes \\Z_3 $, otherwise $ char\\rb{F} = 3 $, then $ Aut\\rb{E} \\cong \\Z_3 \\ltimes Q_8 $.\n\\end{remark}\n\nThe above definitions are defined for $ E\\rb{F} $ as well, and are written $ Hom_F\\rb{E, E'} $, $ End_F\\rb{E} $, and $ Aut_F\\rb{E} $ respectively.\n\n\\pagebreak\n\n\\section{Elliptic curves over finite fields}\n\nWhen studying elliptic curves over a field or a family of fields, an important question would be to determine the set of solutions existing in that field. For instance, it is desirable to count the rational solutions in that field, which would have far fetching applications in number theory and cryptography. For finite fields, there is a finite process to compute the rational points that would always work. The following example illustrates a naive approach for this.\n\n\\begin{example}\nLet $ E : y^2 = x^3 + x + 1 $ be an elliptic curve over $ \\F_5 $. Since there are five distinct values for $ x \\in \\F_5 = \\cb{0, 1, 2, 3, 4} $, computing $ x^3 + x + 1 $ for each value of $ x $ and checking if it is a quadratic residue $ y^2 $ in $ \\F_5 $ gives the following\n\\begin{itemize}\n\\item If $ x = 0 $, then $ y^2 = x^3 + x + 1 = 1 = 1^2 = 4^2 $, so $ y = 1 $ or $ y = 4 $.\n\\item If $ x = 1 $, then $ y^2 = x^3 + x + 1 = 3 $ is not a quadratic residue.\n\\item If $ x = 2 $, then $ y^2 = x^3 + x + 1 = 1 = 1^2 = 4^2 $, so $ y = 1 $ or $ y = 4 $.\n\\item If $ x = 3 $, then $ y^2 = x^3 + x + 1 = 1 = 1^2 = 4^2 $, so $ y = 1 $ or $ y = 4 $.\n\\item If $ x = 4 $, then $ y^2 = x^3 + x + 1 = 4 = 2^2 = 3^2 $, so $ y = 2 $ or $ y = 3 $.\n\\end{itemize}\nSince $ \\mathcal{O} \\in E\\rb{\\F_5} $, there are exactly nine $ \\F_5 $-rational points\n$$ E\\rb{\\F_5} = \\cb{\\mathcal{O}, \\rb{0, 1}, \\rb{0, 4}, \\rb{2, 1}, \\rb{2, 4}, \\rb{3, 1}, \\rb{3, 4}, \\rb{4, 2}, \\rb{4, 3}}. $$\nHence $ E\\rb{\\F_5} \\cong \\Z_3^2 $ or $ E\\rb{\\F_5} \\cong \\Z_9 $. Now Lagrange's theorem gives that $ ord\\rb{P} = 3 $ or $ ord\\rb{P} = 9 $ for any non-zero point $ P \\in E\\rb{\\F_5} $. Let $ P = \\rb{0, 1} \\in E\\rb{\\F_5} $. By the addition and duplication formulae, it holds that $ 3P = \\rb{2, 1} $ and $ 9P = \\mathcal{O} $, so it has order $ ord\\rb{P} = 9 $ and is a generator of $ E\\rb{\\F_5} $. Thus $ E\\rb{\\F_5} \\cong \\Z_9 $.\n\\end{example}\n\nThis finite process is straightforward in the sense that it always terminates. However, as it runs with an asymptotic time complexity of $ O\\rb{q} $ for a finite field $ \\F_q $, the approach becomes rather intractable for large prime powers $ q \\in \\Z_{> 0} $. This section will attempt to develop several techniques to compute $ E\\rb{\\F_q} $, or more specifically $ \\abs{E\\rb{\\F_q}} $, which will span the next few subsections. Now let $ E $ be an elliptic curve over the perfect field $ F = \\F_q = \\F_{p^e} $ for some prime $ p \\in \\Z_{> 0} \\setminus \\cb{2, 3} $ and some $ e \\in \\Z_{> 0} $, given by the Weierstrass curve\n$$ E : y^2 = x^3 + Ax + B, \\qquad A, B \\in F, $$\nwith the group of rational points $ E\\rb{F} = \\rb{E\\rb{F}, \\mathcal{O}, +} $. \n\n\\subsection{Hasse's theorem: inseparable isogenies}\n\nThe following theorem bounds the maximum cardinality of the group of rational points.\n\n\\begin{theorem}[Hasse]\n\\label{thm:hasse}\n$ \\abs{E\\rb{F}} = q - t + 1 $ for some \\emph{trace} $ t \\in \\Z $ such that $ \\abs{t} \\le 2\\sqrt{q} $.\n\\end{theorem}\n\n\\begin{remark}\nThis is a special case of the Hasse-Weil theorem, which states that $ \\abs{C\\rb{F}} = q - t + 1 $ for some $ \\abs{t} \\le 2g\\sqrt{q} $ for any projective algebraic curve $ C $ over $ F $ of genus $ g $.\n\\end{remark}\n\nProof of Hasse's theorem concerns the properties of separable and inseparable isogenies, which are given by separable and inseparable polynomials. The following lemma allows inseparable polynomials to be written in a reduced form.\n\n\\begin{lemma}\nLet $ f \\in F\\sb{x} $ be an inseparable polynomial. Then $ f\\rb{x} = g\\rb{x^p} $ for some $ g \\in F\\sb{x} $.\n\\end{lemma}\n\n\\begin{proof}\nLet $ f\\rb{x} = \\sum_{i = 0}^n a_ix^i = \\sum_{a_i \\ne 0} a_ix^{m_i} $ for some $ a_i \\in F $ and some $ n, m_i \\in \\Z_{> 0} $. Since $ f $ is separable, it holds that $ 0 = df / dx = \\sum_{a_i \\ne 0} m_ia_ix^{m_i - 1} $. Then $ m_ia_i = 0 $ for each $ a_i \\ne 0 $, so $ p \\mid m_i $ and $ m_i = pk $ for some $ k \\in \\Z_{\\ge 0} $. Thus $ f\\rb{x} = \\sum_{a_i \\ne 0} a_i\\rb{x^p}^k = g\\rb{x^p} $ for some $ g \\in F\\sb{x} $.\n\\end{proof}\n\nThe polynomial $ g $ would then be of a smaller degree than $ f $, which justifies why it is deemed as reduced. A similar argument allows inseparable isogenies to be reduced, so let $ E' $ be another elliptic curve over $ F $ given by the Weierstrass curve\n$$ E' : y^2 = x^3 + A'x + B', \\qquad A', B' \\in F,  $$\nand let $ \\phi : E \\to E' $ be an isogeny. The following lemma again allows inseparable isogenies to be written in a reduced form.\n\n\\begin{lemma}\nLet $ \\phi $ be inseparable. Then\n$$ \\phi\\rb{x, y} = \\rb{\\dfrac{r'\\rb{x^p}}{s'\\rb{x^p}}, \\dfrac{u'\\rb{x^p}}{v'\\rb{x^p}}y^p}, \\qquad r', s', u', v' \\in F\\sb{x}. $$\n\\end{lemma}\n\n\\begin{proof}\nSince $ \\phi $ is inseparable,\n$$ 0 = \\dfrac{d}{dx}\\rb{\\dfrac{r}{s}} = \\dfrac{1}{s^2}\\rb{\\dfrac{dr}{dx}s - \\dfrac{ds}{dx}r} \\qquad \\implies \\qquad \\dfrac{dr}{dx}s = \\dfrac{ds}{dx}r. $$\nSince $ \\gcd\\rb{r, s} = 1 $, it holds that $ r \\mid dr / dx $. Since $ \\deg\\rb{dr / dx} < \\deg\\rb{r} $, it also holds that $ dr / dx = 0 $, so $ r $ is inseparable and $ r\\rb{x} = r'\\rb{x^p} $ for some $ r' \\in F\\sb{x} $. Similarly $ s $ is inseparable, so $ ds / dx = 0 $ and $ s\\rb{x} = s'\\rb{x^p} $ for some $ s' \\in F\\sb{x} $. Now\n$$ \\rb{\\dfrac{u}{v}y}^2 = \\rb{\\dfrac{r}{s}}^3 + A'\\dfrac{r}{s} + B' \\qquad \\implies \\qquad u^2s^3y^2 = v^2t, \\qquad t = r^3 + A'rs^2 + B's^3. $$\nThen $ dr / dx = 0 $ and $ ds / dx = 0 $ gives $ dt / dx = 0 $, which gives $ d\\rb{u^2y^2 / v^2} / dx = d\\rb{t / s^3} / dx = 0 $. Hence $ u\\rb{x}^2y^2 = y'\\rb{x^p} $ and $ v\\rb{x}^2 = v'\\rb{x^p} $ for some $ y', v' \\in F\\sb{x} $ similarly. Now since $ y^2 = x^3 + Ax + B $ has distinct factors, let $ y^2 = \\rb{x - \\alpha_1}\\rb{x - \\alpha_2}\\rb{x - \\alpha_3} $ for some $ \\alpha_i \\in K $. Then each $ \\rb{x - \\alpha_i} $ is a factor of $ y'\\rb{x^p} $, so $ \\rb{x^p - \\alpha_i^p} = \\rb{x - \\alpha_i}^p $ is also a factor of $ y'\\rb{x^p} $ and of $ u\\rb{x}y^2 $. Hence $ y'\\rb{x^p} = t'\\rb{x^p}\\rb{y^2}^p $ for some $ t' \\in F\\sb{x} $. Now any factor $ \\rb{x - \\alpha} $ of $ u\\rb{x} $ is such that $ \\rb{x - \\alpha}^p = \\rb{x^p - \\alpha^p} $ is a factor of $ t'\\rb{x^p} $. Since $ \\gcd\\rb{p, 2} = 1 $, it holds that $ \\rb{\\rb{x - \\alpha}^p}^2 $ is also a factor of $ t'\\rb{x^p} $, so $ t'\\rb{x^p} = u'\\rb{x^p}^2 $ for some $ u' \\in F\\sb{x} $. Thus $ u\\rb{x}^2y^2 = u'\\rb{x^p}^2\\rb{y^p}^2 $ and\n$$ \\phi\\rb{x, y} = \\rb{\\dfrac{r\\rb{x}}{s\\rb{x}}, \\dfrac{u\\rb{x}}{v\\rb{x}}y} = \\rb{\\dfrac{r'\\rb{x^p}}{s'\\rb{x^p}}, \\pm\\dfrac{u'\\rb{x^p}}{v'\\rb{x^p}}y^p}. $$\n\\end{proof}\n\nNow the above lemma might feel slightly arbitrary due to the presence of $ x^p $ and $ y^p $ in the isogeny. This brings the discussion to a particular endomorphism defined as follows, which would simplify the above expression.\n\n\\begin{definition}[Frobenius endomorphism]\nThe \\textbf{Frobenius endomorphism} $ Fr : E \\to E $ is defined by $ Fr\\rb{x, y} = \\rb{x^p, y^p} $ if $ e = 1 $. The $ q $-th power Frobenius endomorphism $ Fr_q : E \\to E $ is defined by $ Fr_q\\rb{x, y} = \\rb{x^q, y^q} $.\n\\end{definition}\n\nThe Frobenius endomorphism is also injective by virtue of the field characteristic, and hence bijective, which allows for an inverse isogeny to be easily defined.\n\n\\begin{remark}\nA remarkable equivalent characterisation of a perfect field is that the Frobenius endomorphism of a field with positive characteristic is an automorphism, which induces a similar property for isogenies defined over this field.\n\\end{remark}\n\nThe above lemmas for inseparable $ \\phi $ can now be written in terms of the Frobenius endomorphism $ \\phi = \\phi' \\circ Fr $, where\n$$ \\phi'\\rb{x, y} = \\rb{\\dfrac{r'\\rb{x}}{s'\\rb{x}}, \\dfrac{u'\\rb{x}}{v'\\rb{x}}y}, \\qquad r', s', u', v' \\in F\\sb{x}, $$\nwhich is a reduced standard form of an isogeny. In fact, any isogeny can be written as the composition of a Frobenius endomorphism. The following proposition summarises the above lemmas nicely.\n\n\\begin{proposition}\n$ \\phi = \\phi_s \\circ Fr^n $ for some separable isogeny $ \\phi_s : E \\to E' $ and some $ n \\in \\Z_{\\ge 0} $.\n\\end{proposition}\n\n\\begin{proof}\nIf $ \\phi $ is separable, then let $ \\phi_s = \\phi $ and $ n = 0 $. Otherwise $ \\phi = \\phi_1 \\circ Fr $ for some $ \\phi_1 : E \\to E' $. If $ \\phi_i : E \\to E' $ is inseparable, then $ \\phi_i = \\phi_{i + 1} \\circ Fr^i $ for some $ \\phi_{i + 1} : E \\to E' $. Since $ \\deg\\rb{\\phi} $ is finite, by induction, there is some $ n \\in \\Z_{\\ge 0} $ such that $ n \\le \\deg\\rb{\\phi} $ and $ \\phi_n : E \\to E' $ is separable. Thus let $ \\phi_s = \\phi_n $.\n\\end{proof}\n\n\\begin{remark}\nSince $ F $ is a perfect field, the isogeny $ \\phi $ can also be written as $ \\phi = Fr^n \\circ \\phi'_s $ for some separable isogeny $ \\phi'_s : E \\to E' $ such that $ \\deg\\rb{\\phi_s} = \\deg\\rb{\\phi'_s} $. If $ F $ is not a perfect field, the Frobenius endomorphism is not necessarily an automorphism, so $ Im\\rb{Fr} \\subseteq E $ and the domain of $ \\phi_s $ is only a subset of $ E $.\n\\end{remark}\n\nHence any isogeny can be decomposed as the unique composition of a separable isogeny and a Frobenius endomorphism, so $ \\phi $ will be written as\n$$ \\phi = \\phi_s \\circ Fr^n, \\qquad \\phi_s \\in F\\sb{E}, \\qquad n \\in \\Z_{\\ge 0}, $$\nwhere $ \\phi_s $ is a separable isogeny. Two additional notions of degree of an isogeny can then be defined as follows.\n\n\\begin{definition}[Separable degree]\nThe \\textbf{separable degree} of $ \\phi $ is $ \\deg_s\\rb{\\phi} = \\deg\\rb{\\phi_s} $. The \\textbf{inseparable degree} of $ \\phi $ is $ \\deg_i\\rb{\\phi} = p^n $.\n\\end{definition}\n\nIt is clear that the degree of an isogeny is related to these two degrees by\n$$ \\deg\\rb{\\phi} = \\deg_s\\rb{\\phi}\\deg_i\\rb{\\phi}. $$\nIf an isogeny is separable, its decomposition to a Frobenius endomorphism is trivial, so its separable degree is equal to its degree and its inseparable degree is one.\n\n\\begin{remark}\nAn inseparable isogeny does not necessarily have its inseparable degree equal to its degree and its separable degree equal to one. If this is the case, then the isogeny is \\emph{purely inseparable}. However, purely inseparable isogenies are not always inseparable, as with the case for degree one isogenies, which are isomorphisms, with all three degree equal to one.\n\\end{remark}\n\nThe following example illustrates the two additional notions of degree.\n\n\\begin{example}\n$ Fr $ has separable degree $ \\deg_s\\rb{Fr} = 1 $ and inseparable degree $ \\deg_i\\rb{Fr} = p $, while $ \\sb{2} $ has separable degree $ \\deg_s\\rb{\\sb{2}} = \\deg\\rb{\\sb{2}} = 4 $ and inseparable degree $ \\deg_i\\rb{\\sb{2}} = 1 $.\n\\end{example}\n\nThis digression leads to an important proposition relating the kernel and the separable degree of an isogeny as follows, which is crucial to the proof of Hasse's theorem.\n\n\\begin{proposition}\n$ \\abs{Ker\\rb{\\phi}} = \\deg_s\\rb{\\phi} $.\n\\end{proposition}\n\n\\begin{proof}\nLet\n$$ S_1 = \\cb{\\rb{a, 0} \\in E'} = E\\sb{2}, \\qquad S_2 = \\cb{\\rb{0, b} \\in E'}, \\qquad S_3 = \\cb{\\rb{a, b} \\in E' \\mid \\deg\\rb{r - as} < \\deg\\rb{\\phi_s}}, $$\n$$ S_4 = \\cb{\\rb{a, b} \\in E' \\ \\Bigg| \\ \\rb{\\dfrac{r}{s}}\\rb{a'} = a, \\ \\dfrac{d}{dx}\\rb{\\dfrac{r}{s}}\\rb{a'} = 0, \\ \\rb{a', b'} \\in E}, \\qquad S = S_1 \\cup S_2 \\cup S_3 \\cup S_4. $$\nThen $ \\abs{S_1} \\le 3 $ and $ \\abs{S_2} \\le 2 $ are finite. Since $ \\deg\\rb{\\phi_s} $ is finite, it holds that $ \\abs{S_3} \\le 2\\deg\\rb{\\phi_s} $ is also finite. Since $ \\phi_s $ is separable, it holds that $ d\\rb{r / s} / dx \\ne 0 $, so $ \\abs{S_4} \\le \\deg\\rb{r} $ is also finite. Hence $ S $ is finite and $ E' \\setminus S $ is non-empty. Now let $ P = \\rb{a, b} \\in E' \\setminus S $ and $ P' = \\rb{a', b'} \\in E $ be points, and let $ \\psi = r - as \\in K\\sb{x} $ be such that $ \\deg\\rb{\\psi} = \\deg\\rb{\\phi_s} $. Then $ \\phi_s\\rb{P'} = P $ iff $ \\rb{r / s}\\rb{a'} = a $ and $ \\rb{u / v}\\rb{a'}b' = b $. Since $ b \\ne 0 $ gives $ u\\rb{a'} \\ne 0 $, this also holds iff $ \\psi\\rb{a'} = r\\rb{a'} - as\\rb{a'} = 0 $ and $ b' = \\rb{v / u}\\rb{a'}b $. Hence $ \\abs{\\phi_s^{-1}\\rb{P}} $ is the number of distinct roots of $ \\psi $. Suppose for a contradiction that $ a' $ is a repeated root of $ \\psi $. Then\n$$ 0 = \\psi\\rb{a'} = r\\rb{a'} - as\\rb{a'}, \\qquad 0 = \\dfrac{d\\psi}{dx}\\rb{a'} = \\dfrac{dr}{dx}\\rb{a'} - a\\dfrac{ds}{dx}\\rb{a'}, $$\nsuch that\n$$ \\rb{\\dfrac{r}{s}}\\rb{a'} = a, \\qquad \\dfrac{dr}{dx}\\rb{a'}s\\rb{a'} = \\dfrac{ds}{dx}\\rb{a'}r\\rb{a'} \\qquad \\implies \\qquad \\dfrac{d}{dx}\\rb{\\dfrac{r}{s}}\\rb{a'} = 0, $$\nso $ P' \\in S_4 $, which is a contradiction. Hence $ \\psi $ splits over $ K $ and $ \\abs{\\phi_s^{-1}\\rb{P}} = \\deg\\rb{\\psi} $. Since $ \\chi : Ker\\rb{\\phi_s} \\to \\phi_s^{-1}\\rb{P} $ defined by $ \\chi\\rb{Q} = Q + P $ is a bijection, it holds that $ \\abs{Ker\\rb{\\phi_s}} = \\abs{\\phi_s^{-1}\\rb{P}} $. Since $ Fr $ is bijective, so are $ Fr^n $ and $ \\val{Fr^n}_{Ker\\rb{\\phi}} : Ker\\rb{\\phi} \\to Ker\\rb{\\phi_s} $, so $ \\abs{Ker\\rb{\\phi}} = \\abs{Ker\\rb{\\phi_s}} $. Thus\n$$ \\abs{Ker\\rb{\\phi}} = \\abs{Ker\\rb{\\phi_s}} = \\abs{\\phi_s^{-1}\\rb{P}} = \\deg\\rb{\\psi} = \\deg\\rb{\\phi_s} = \\deg_s\\rb{\\phi}. $$\n\\end{proof}\n\nMotivated by the endomorphism ring, composition of isogenies with appropriate domains can be seen as multiplication. In particular, their degrees multiply out naturally in the following lemma.\n\n\\begin{lemma}\nLet $ E'' $ be an elliptic curve over $ F $ such that $ \\psi : E' \\to E'' $ is an isogeny. Then\n$$ \\deg\\rb{\\psi \\circ \\phi} = \\deg\\rb{\\psi}\\deg\\rb{\\phi}, \\qquad \\deg_s\\rb{\\psi \\circ \\phi} = \\deg_s\\rb{\\psi}\\deg_s\\rb{\\phi}, \\qquad \\deg_i\\rb{\\psi \\circ \\phi} = \\deg_i\\rb{\\psi}\\deg_i\\rb{\\phi}. $$\n\\end{lemma}\n\n\\begin{proof}\nSince $ \\phi $ and $ \\psi $ are surjective, so is $ \\psi \\circ \\phi $, so the first isomorphism theorem gives\n$$ \\dfrac{E}{Ker\\rb{\\phi}} \\cong E', \\qquad \\dfrac{E'}{Ker\\rb{\\psi}} \\cong E'', \\qquad \\dfrac{E}{Ker\\rb{\\psi \\circ \\phi}} \\cong E'', $$\nsuch that\n$$ \\abs{Ker\\rb{\\psi \\circ \\phi}} = \\dfrac{\\abs{E}}{\\abs{E''}} = \\dfrac{\\abs{E'}\\abs{Ker\\rb{\\phi}}}{\\abs{E'} / \\abs{Ker\\rb{\\psi}}} = \\abs{Ker\\rb{\\psi}}\\abs{Ker\\rb{\\phi}}. $$\nHence $ \\deg_s\\rb{\\psi \\circ \\phi} = \\deg_s\\rb{\\psi}\\deg_s\\rb{\\phi} $. Now let $ \\psi = \\psi_s \\circ Fr^m $ and $ \\psi \\circ \\phi = \\chi_s \\circ Fr^k $ for some isogenies $ \\psi_s : E' \\to E'' $ and $ \\chi_s : E \\to E'' $ and some $ m, k \\in \\Z_{\\ge 0} $. Then\n$$ \\chi_s \\circ Fr^k = \\psi_s \\circ Fr^m \\circ \\phi_s \\circ Fr^n. $$\nSince $ \\deg_s\\rb{Fr} = 1 $, it holds that $ \\deg_s\\rb{Fr^m} = 1 $, so\n$$ \\deg_s\\rb{Fr^m \\circ \\phi_s} = \\deg_s\\rb{Fr^m}\\deg_s\\rb{\\phi_s} = \\deg_s\\rb{\\phi_s}. $$\nThen $ Fr^m \\circ \\phi_s = \\chi'_s \\circ Fr^m $ for some isogeny $ \\chi'_s : E \\to E' $ such that $ \\deg\\rb{\\phi_s} = \\deg\\rb{\\chi'_s} $, so\n$$ \\chi_s \\circ Fr^k = \\psi_s \\circ \\chi'_s \\circ Fr^{n + m}. $$\nSince $ \\psi_s \\circ \\chi'_s $ is separable, it holds that $ k = n + m $. Hence $ \\deg_i\\rb{\\psi \\circ \\phi} = \\deg_i\\rb{\\psi}\\deg_i\\rb{\\phi} $. Thus\n$$ \\deg\\rb{\\psi \\circ \\phi} = \\deg_s\\rb{\\psi}\\deg_i\\rb{\\psi}\\deg_s\\rb{\\phi}\\deg_i\\rb{\\phi} = \\deg\\rb{\\psi}\\deg\\rb{\\phi}. $$\n\\end{proof}\n\nThis paves the way to the proof of the following proposition on inseparable isogenies, which is also crucial to the proof of Hasse's theorem. Now let $ \\psi : E \\to E' $ be an isogeny.\n\n\\begin{proposition}\nLet $ \\phi $ and $ \\psi $ be inseparable, and let $ E'' $ and $ E''' $ be elliptic curves over $ F $ such that $ \\chi : E'' \\to E $ and $ \\chi' : E' \\to E''' $ are isogenies. Then $ \\phi \\circ \\chi $, $ \\chi' \\circ \\phi $, and $ \\phi - \\psi $ are inseparable.\n\\end{proposition}\n\n\\begin{proof}\nSince $ \\deg_i\\rb{\\phi \\circ \\chi} = \\deg_i\\rb{\\phi}\\deg_i\\rb{\\chi} > 1 $ and $ \\deg_i\\rb{\\chi' \\circ \\phi} = \\deg_i\\rb{\\phi}\\deg_i\\rb{\\chi} > 1 $, it holds that $ \\phi \\circ \\chi $ and $ \\chi' \\circ \\phi $ are inseparable. Now let $ \\phi = \\phi_s \\circ Fr^n $ and $ \\psi = \\psi_s \\circ Fr^m $ for some separable isogenies $ \\phi_s : E \\to E' $ and $ \\psi_s : E \\to E' $ and some $ n, m \\in \\Z_{> 0} $. Then\n$$ \\phi - \\psi = \\phi_s \\circ Fr^n - \\psi_s \\circ Fr^m = \\rb{\\phi_s \\circ Fr^{n - 1} - \\psi_s \\circ Fr^{m - 1}} \\circ Fr. $$\nThus $ \\phi - \\psi $ is inseparable.\n\\end{proof}\n\nHence adding a separable isogeny with an inseparable isogeny will give a separable isogeny. Returning to the initial motivation, letting $ E = E' = E'' = E''' $ in the above results implies that the set of all inseparable endomorphisms of $ E $ is an ideal of $ End\\rb{E} $.\n\n\\pagebreak\n\n\\subsection{Hasse's theorem: quadratic forms}\n\nNow the \\emph{degree map} $ \\deg : Hom\\rb{E, E'} \\to \\Z_{\\ge 0} $ has a particular property that allows a form of the Cauchy-Schwarz inequality to be defined on it. This property can be defined with the aid of the following notion.\n\n\\begin{definition}[Bilinear pairing]\nA pairing $ b : G \\times G \\to F $ of an group $ G $ is \\textbf{bilinear} iff $ b\\rb{x + y, z} = b\\rb{x, z} + b\\rb{y, z} $ and $ b\\rb{x, y + z} = b\\rb{x, y} + b\\rb{x, z} $ for any $ x, y, z \\in G $.\n\\end{definition}\n\nIn other words the pairing is linear in both components. A bilinear pairing can be defined in terms of the degree map, with the set of isogenies $ Hom\\rb{E, E'} $ as the abelian group, which has the following property.\n\n\\begin{definition}[Quadratic form]\nA \\textbf{quadratic form} is a map $ d : A \\to F $ of an abelian group $ A $ such that $ d\\rb{x} = d\\rb{-x} $ for any $ x \\in A $, and the \\textbf{associated pairing} $ b_d : A \\times A \\to F $ defined by\n$$ b_d\\rb{x, y} = \\tfrac{1}{2}\\rb{d\\rb{x + y} - d\\rb{x} - d\\rb{y}} $$\nis bilinear.\n\\end{definition}\n\nThe associated bilinear pairing is usually written $ \\ab{\\cdot, \\cdot} : A \\times A \\to F $ with context, and inherits all the definitions from linear algebra, such as the notions of being symmetric and positive definite.\n\n\\begin{remark}\nConversely, for any symmetric bilinear pairing $ \\ab{\\cdot, \\cdot} : A \\times A \\to F $, the map $ d : A \\to F $ defined by $ d\\rb{x} = \\ab{x, x} $ is a quadratic form, so notions related to symmetric bilinear pairings and quadratic forms are interchangeable, provided $ char\\rb{F} \\ne 2 $.\n\\end{remark}\n\nHence an aim would be to show that the degree map indeed is a positive definite quadratic form, as symmetry follows by definition. This could be done by proving a particular fundamental property that holds for all quadratic forms, which is given in the following theorem. Now denote $ -\\phi = \\sb{-1} \\circ \\phi $ and\n$$ \\phi + \\dots + \\phi = n\\phi = \\sb{n} \\circ \\phi, \\qquad \\psi + \\dots + \\psi = m\\psi = \\sb{m} \\circ \\psi, \\qquad n, m \\in \\Z, $$\nto ease the proofs below.\n\n\\begin{theorem}[Parallelogram law]\n$ \\deg\\rb{\\phi + \\psi} + \\deg\\rb{\\phi - \\psi} = 2\\deg\\rb{\\phi} + 2\\deg\\rb{\\psi} $.\n\\end{theorem}\n\n\\begin{proof}\nIf $ \\phi = 0 $ or $ \\psi = 0 $, then $ \\deg\\rb{\\phi + \\psi} + \\deg\\rb{\\phi - \\psi} = 2\\deg\\rb{\\phi} + 2\\deg\\rb{\\psi} $ holds. If $ \\phi = \\psi $ or $ \\phi = -\\psi $, then\n$$ \\deg\\rb{\\phi + \\psi} + \\deg\\rb{\\phi - \\psi} = \\deg\\rb{2\\phi} = \\deg\\rb{\\sb{2}}\\deg\\rb{\\phi} = 4\\deg\\rb{\\phi} = 2\\deg\\rb{\\phi} + 2\\deg\\rb{\\psi} $$\nalso holds. Otherwise let\n$$ \\phi\\rb{x, y} = \\rb{w_1, z_1}, \\qquad \\psi\\rb{x, y} = \\rb{w_2, z_2}, \\qquad \\rb{\\phi + \\psi}\\rb{x, y} = \\rb{w_3, z_3}, \\qquad \\rb{\\phi - \\psi}\\rb{x, y} = \\rb{w_4, z_4}, $$\nfor each $ w_i = r_i\\rb{x} / s_i\\rb{x} $ and $ z_i = u_i\\rb{x}y / v_i\\rb{x} $ for some homogeneous polynomials $ r_i, s_i, u_i, v_i \\in F\\sb{x} $ such that each $ \\gcd\\rb{r_i, s_i} = \\gcd\\rb{u_i, v_i} = 1 $ and\n$$ \\deg\\rb{\\phi} = \\deg\\rb{r_1} = \\deg\\rb{s_1}, \\qquad \\deg\\rb{\\psi} = \\deg\\rb{r_2} = \\deg\\rb{s_2}, $$\n$$ \\deg\\rb{\\phi + \\psi} = \\deg\\rb{r_3} = \\deg\\rb{s_3}, \\qquad \\deg\\rb{\\phi - \\psi} = \\deg\\rb{r_4} = \\deg\\rb{s_4}. $$\nBy the addition formula,\n$$ w_3 = \\dfrac{\\rb{A + w_1w_2}\\rb{w_1 + w_2} + 2\\rb{B - z_1z_2}}{\\rb{w_1 - w_2}^2}, \\qquad w_4 = \\dfrac{\\rb{A + w_1w_2}\\rb{w_1 + w_2} + 2\\rb{B + z_1z_2}}{\\rb{w_1 - w_2}^2}. $$\nAdding these two equations gives $ \\rb{w_3 + w_4}\\rb{w_1 - w_2}^2 = 2\\rb{A + w_1w_2}\\rb{w_1 + w_2} + 4B $, so\n$$ \\dfrac{r_3s_4 + r_4s_3}{s_3s_4} = \\dfrac{2\\rb{As_1s_2 + r_1r_2}\\rb{r_1s_2 + r_2s_1} + 4Bs_1^2s_2^2}{\\rb{r_1s_2 - r_2s_1}^2}. $$\nHence let\n$$ R = r_3s_4 + r_4s_3, \\qquad S = s_3s_4, \\qquad U = 2\\rb{As_1s_2 + r_1r_2}\\rb{r_1s_2 + r_2s_1} + 4Bs_1^2s_2^2, \\qquad V = \\rb{r_1s_2 - r_2s_1}^2. $$\nSimilarly multiplying these two equations gives\n\\begin{align*}\nw_3w_4\\rb{w_1 - w_2}^4\n& = \\rb{A + w_1w_2}^2\\rb{w_1 + w_2}^2 + 4B\\rb{A + w_1w_2}\\rb{w_1 + w_2} + 4B^2 - 4z_1^2z_2^2 \\\\\n& = \\rb{A^2 + 2Aw_1w_2 + w_1^2w_2^2}\\rb{w_1^2 + 2w_1w_2 + w_2^2} + 4B\\rb{Aw_1 + Aw_2 + w_1^2w_2 + w_1w_2^2} \\\\\n& \\qquad + 4B^2 - 4\\rb{w_1^3 + Aw_1 + B}\\rb{w_2^3 + Aw_2 + B} \\\\\n& = A^2w_1^2 - 2A^2w_1w_2 + A^2w_2^2 - 4Bw_1^3 + 4Bw_1^2w_2 + 4Bw_1w_2^2 - 4Bw_2^3 \\\\\n& \\qquad - 2Aw_1^3w_2 + 4Aw_1^2w_2^2 - 2Aw_1w_2^3 + w_1^4w_2^2 - 2w_1^3w_2^3 + w_1^2w_2^4 \\\\\n& = A^2\\rb{w_1 - w_2}^2 - 4Bw_1^2\\rb{w_1 - w_2} + 4Bw_2^2\\rb{w_1 - w_2} \\\\\n& \\qquad - 2Aw_1w_2\\rb{w_1 - w_2}^2 + w_1^2w_2^2\\rb{w_1 - w_2}^2 \\\\\n& = \\rb{A^2 - 2Aw_1w_2 + w_1^2w_2^2}\\rb{w_1 - w_2}^2 - 4B\\rb{w_1^2 - w_2^2}\\rb{w_1 - w_2} \\\\\n& = \\rb{A - w_1w_2}^2\\rb{w_1 - w_2}^2 - 4B\\rb{w_1 + w_2}\\rb{w_1 - w_2}^2,\n\\end{align*}\nsuch that $ w_3w_4\\rb{w_1 - w_2}^2 = \\rb{A - w_1w_2}^2 - 4B\\rb{w_1 + w_2} $, so\n$$ \\dfrac{r_3r_4}{s_3s_4} = \\dfrac{\\rb{As_1s_2 - r_1r_2}^2 - 4B\\rb{r_1s_2 + r_2s_1}s_1s_2}{\\rb{r_1s_2 - r_2s_1}^2}. $$\nHence also let\n$$ T = r_3r_4, \\qquad W = \\rb{As_1s_2 - r_1r_2}^2 - 4B\\rb{r_1s_2 + r_2s_1}s_1s_2, $$\nsuch that\n$$ \\deg\\rb{R} = \\deg\\rb{S} = \\deg\\rb{T} = \\deg\\rb{\\phi + \\psi} + \\deg\\rb{\\phi - \\psi}, $$\n$$ \\deg\\rb{U} = \\deg\\rb{V} = \\deg\\rb{W} = 2\\deg\\rb{\\phi} + 2\\deg\\rb{\\psi}. $$\nSuppose for a contradiction that $ \\gcd\\rb{R, S, T} \\ne 1 $, so $ g \\mid \\gcd\\rb{R, S, T} $ for some irreducible homogeneous polynomial $ g \\in F\\sb{x} $. If $ g \\mid r_3 $, then $ g \\nmid s_3 $, so $ g \\mid s_4 $ and $ g \\nmid r_4 $ gives $ g \\nmid r_3s_4 + r_4s_3 = R $. Otherwise $ g \\nmid r_3 $, then $ g \\mid r_4 $, so $ g \\nmid s_4 $ and $ g \\mid s_3 $ also gives $ g \\nmid r_3s_4 + r_4s_3 = R $, which is a contradiction. Hence $ \\gcd\\rb{R, S, T} = 1 $. Now let $ g' = \\gcd\\rb{U, V, W} $, so\n$$ U = g'U', \\qquad V = g'V', \\qquad W = g'W', \\qquad U', V', W' \\in F\\sb{x}, \\qquad \\gcd\\rb{U', V', W'} = 1, $$\nsuch that\n$$ \\deg\\rb{U'} = \\deg\\rb{V'} = \\deg\\rb{W'} = \\deg\\rb{U} - \\deg\\rb{g'}. $$\nCombining the two equations from adding and multiplying gives a ratio\n$$ \\sb{R, S, T} = \\sb{\\dfrac{R}{S}, 1, \\dfrac{T}{S}} = \\sb{\\dfrac{U}{V}, 1, \\dfrac{W}{V}} = \\sb{U, V, W} = \\sb{g'U', g'V', g'W'} = \\sb{U', V', W'}, $$\nsuch that $ R = U' $, $ T = W' $, and $ S = V' $. Hence\n$$ \\deg\\rb{\\phi + \\psi} + \\deg\\rb{\\phi - \\psi} = \\deg\\rb{R} = \\deg\\rb{U'} = \\deg\\rb{U} - \\deg\\rb{g'} \\le \\deg\\rb{U} = 2\\deg\\rb{\\phi} + 2\\deg\\rb{\\psi}. $$\nNow replacing $ \\rb{\\phi, \\psi} \\mapsto \\rb{\\phi + \\psi, \\psi + \\phi} $ gives the converse\n\\begin{align*}\n2\\deg\\rb{\\phi + \\psi} + 2\\deg\\rb{\\phi - \\psi}\n& \\ge \\deg\\rb{\\phi + \\psi + \\phi - \\psi} + \\deg\\rb{\\phi + \\psi - \\phi + \\psi} \\\\\n& = \\deg\\rb{\\sb{2}}\\deg\\rb{\\phi} + \\deg\\rb{\\sb{2}}\\deg\\rb{\\psi} \\\\\n& = 4\\deg\\rb{\\phi} + 4\\deg\\rb{\\psi},\n\\end{align*}\nThus $ \\deg\\rb{\\phi + \\psi} + \\deg\\rb{\\phi - \\psi} = 2\\deg\\rb{\\phi} + 2\\deg\\rb{\\psi} $.\n\\end{proof}\n\nAn application of the parallelogram law would be a simple inductive proof of the following lemma, which has many other proofs.\n\n\\begin{lemma}\nLet $ n \\in \\Z $. Then $ \\deg\\rb{\\sb{n}} = n^2 $.\n\\end{lemma}\n\n\\begin{proof}\n$ \\deg\\rb{\\sb{0}} = 0 $ and $ \\deg\\rb{\\sb{1}} = 1 $. Assume that $ \\deg\\rb{\\sb{m}} = m^2 $ for any $ m \\le n $ for some $ n \\in \\Z_{\\ge 0} $. Then\n$$ \\deg\\rb{\\sb{n + 1}} = 2\\deg\\rb{\\sb{n}} + 2\\deg\\rb{\\sb{1}} - \\deg\\rb{\\sb{n - 1}} = 2n^2 + 2 - \\rb{n - 1}^2 = n^2 + 2n + 1 = \\rb{n + 1}^2. $$\nHence $ \\deg\\rb{\\sb{n}} = n^2 $ for any $ n \\in \\Z_{\\ge 0} $ by induction. Similarly $ \\deg\\rb{\\sb{-n}} = \\deg\\rb{\\sb{-1}}\\deg\\rb{\\sb{n}} = \\deg\\rb{\\sb{n}} $ for any $ n \\in \\Z_{\\ge 0} $. Thus $ \\deg\\rb{\\sb{n}} = n^2 $ for any $ n \\in \\Z $.\n\\end{proof}\n\nIn fact, the above lemma can be generalised for arbitrary isogenies, as follows.\n\n\\begin{lemma}\nLet $ n, m \\in \\Z $. Then $ \\deg\\rb{n\\phi + m\\psi} = n^2\\deg\\rb{\\phi} + 2nm\\ab{\\phi, \\psi} + m^2\\deg\\rb{\\psi} $.\n\\end{lemma}\n\n\\begin{proof}\nSince $ \\ab{\\phi, \\phi} = \\tfrac{1}{2}\\rb{\\deg\\rb{2\\phi} - 2\\deg\\rb{\\phi}} = 2\\deg\\rb{\\phi} - \\deg\\rb{\\phi} = \\deg\\rb{\\phi} $, it holds that\n$$ \\deg\\rb{n\\phi + m\\psi} = \\ab{n\\phi + m\\psi, n\\phi + m\\psi} = n^2\\deg\\rb{\\phi} + 2nm\\ab{\\phi, \\psi} + m^2\\deg\\rb{\\psi}. $$\n\\end{proof}\n\nThe initial aim can then be proven in the following lemma.\n\n\\begin{lemma}\n$ \\deg : Hom\\rb{E, E'} \\to \\Z_{\\ge 0} $ is a positive definite quadratic form.\n\\end{lemma}\n\n\\begin{proof}\n$ \\deg\\rb{-\\phi} = \\deg\\rb{\\sb{-1}}\\deg\\rb{\\phi} = \\deg\\rb{\\phi} $. Let $ \\chi : E \\to E' $ be an isogeny. Since\n\\begin{align*}\n\\deg\\rb{\\phi + \\psi + \\chi}\n& = 2\\deg\\rb{\\phi + \\psi} + 2\\deg\\rb{\\chi} - \\deg\\rb{\\phi + \\psi - \\chi} \\\\\n& = 2\\deg\\rb{\\phi + \\psi} + 2\\deg\\rb{\\chi} - 2\\deg\\rb{\\phi - \\chi} - 2\\deg\\rb{\\psi} + \\deg\\rb{\\phi - \\psi - \\chi} \\\\\n& = 2\\deg\\rb{\\phi + \\psi} + 2\\deg\\rb{\\chi} - 2\\deg\\rb{\\phi - \\chi} - 2\\deg\\rb{\\psi} \\\\\n& \\qquad + 2\\deg\\rb{\\psi + \\chi} + 2\\deg\\rb{\\phi} - \\deg\\rb{\\phi + \\psi + \\chi},\n\\end{align*}\nit holds that $ \\deg\\rb{\\phi + \\psi + \\chi} =  \\deg\\rb{\\phi + \\psi} + \\deg\\rb{\\chi} - \\deg\\rb{\\phi - \\chi} - \\deg\\rb{\\psi} + \\deg\\rb{\\psi + \\chi} + \\deg\\rb{\\phi} $.\nHence\n\\begin{align*}\n\\ab{\\phi + \\psi, \\chi}\n& = \\tfrac{1}{2}\\rb{\\deg\\rb{\\phi + \\psi + \\chi} - \\deg\\rb{\\phi + \\psi} - \\deg\\rb{\\chi}} \\\\\n& = \\tfrac{1}{2}\\rb{-\\deg\\rb{\\phi - \\chi} - \\deg\\rb{\\psi} + \\deg\\rb{\\psi + \\chi} + \\deg\\rb{\\phi}} \\\\\n& = \\tfrac{1}{2}\\rb{-2\\deg\\rb{\\phi} - 2\\deg\\rb{\\chi} + \\deg\\rb{\\phi + \\chi} - \\deg\\rb{\\psi} + \\deg\\rb{\\psi + \\chi} + \\deg\\rb{\\phi}} \\\\\n& = \\tfrac{1}{2}\\rb{\\deg\\rb{\\phi + \\chi} - \\deg\\rb{\\phi} - \\deg\\rb{\\chi} + \\deg\\rb{\\psi + \\chi} - \\deg\\rb{\\psi} - \\deg\\rb{\\chi}}\n= \\ab{\\phi, \\chi} + \\ab{\\psi, \\chi}.\n\\end{align*}\nSimilarly $ \\ab{\\phi, \\psi + \\chi} = \\ab{\\phi, \\psi} + \\ab{\\phi, \\chi} $ by symmetry. Thus since $ \\deg\\rb{\\phi} > 0 $ for any $ \\phi \\ne 0 $ and $ \\deg\\rb{0} = 0 $, it holds that $ \\deg $ is a positive definite quadratic form.\n\\end{proof}\n\nReplacing the degree map with any map satisfying the parallelogram law also gives a quadratic form. The following variant of the Cauchy-Schwarz inequality generalises to quadratic forms similarly.\n\n\\begin{theorem}[Cauchy-Schwarz]\n$ \\ab{\\phi, \\psi}^2 \\le \\deg\\rb{\\phi}\\deg\\rb{\\psi} $.\n\\end{theorem}\n\n\\begin{proof}\nLet $ n = -\\ab{\\phi, \\psi} $ and $ m = \\deg\\rb{\\phi} $. Then\n$$ 0 \\le \\ab{\\phi, \\psi}^2\\deg\\rb{\\phi} - 2\\ab{\\phi, \\psi}^2\\deg\\rb{\\phi} + \\deg\\rb{\\phi}^2\\deg\\rb{\\psi} = \\deg\\rb{\\phi}\\rb{\\deg\\rb{\\phi}\\deg\\rb{\\psi} - \\ab{\\phi, \\psi}^2}. $$\nThus $ \\ab{\\phi, \\psi}^2 \\le \\deg\\rb{\\phi}\\deg\\rb{\\psi} $.\n\\end{proof}\n\nHasse's theorem can finally be proven.\n\n\\begin{proof}[Proof of Theorem \\ref{thm:hasse}]\nA point $ P = \\sb{a, b, c} \\in E\\rb{F} $ iff $ a^q = a $, $ b^q = b $, and $ c^q = c $ by Fermat's little theorem, or $ \\sb{a^q, b^q, c^q} = \\sb{a, b, c} $. This holds iff the $ q $-th power Frobenius endomorphism $ Fr_q : E \\to E $ is such that $ Fr_q\\rb{P} = P $, or $ P \\in Ker\\rb{Fr_q - \\sb{1}} $. Hence $ E\\rb{F} = Ker\\rb{Fr_q - \\sb{1}} $. Since $ \\sb{1} $ is separable and $ Fr_q $ is inseparable with degree $ \\deg\\rb{Fr_q} = \\deg_i\\rb{Fr_q} = q $, it holds that $ Fr_q - \\sb{1} $ is separable, so\n$$ Ker\\rb{Fr_q - \\sb{1}} = \\deg_s\\rb{Fr_q - \\sb{1}} = \\deg\\rb{Fr_q - \\sb{1}} = \\deg\\rb{Fr_q} - 2\\ab{Fr_q, \\sb{1}} + \\deg\\rb{\\sb{1}} = q - 2\\ab{Fr_q, \\sb{1}} + 1. $$\nThen let $ t = 2\\ab{Fr_q, \\sb{1}} $, so Cauchy-Schwarz gives $ t^2 = 4\\ab{Fr_q, 1}^2 \\le 4\\deg\\rb{Fr_q}\\deg\\rb{\\sb{1}} = 4q $. Thus $ \\abs{E\\rb{F}} = q - t + 1 $ for $ \\abs{t} \\le 2\\sqrt{q} $.\n\\end{proof}\n\n\\pagebreak\n\n\\subsection{Riemann hypothesis}\n\nHasse's theorem, or more accurately the Hasse-Weil theorem, is also sometimes referred to as the \\emph{Riemann hypothesis} for smooth projective algebraic curves over finite fields. It has an alternative formulation that makes it analogous to the famous classical Riemann hypothesis, an open problem in number theory deemed worthy of being called one of the Millennium Prize Problems by the Clay Mathematics Institute with a monetary prize of a million dollars. The conjecture revolves around zeroes of the following complex function.\n\n\\begin{definition}[Riemann zeta function]\nThe Riemann zeta function $ \\zeta : \\C \\to \\C $ is defined for any $ \\Re\\rb{s} > 1 $ as the power series $ \\zeta\\rb{s} = \\sum_{n = 1}^\\infty n^{-s} $, and extended to $ \\C $ by analytic continuation.\n\\end{definition}\n\nRiemann himself proved the analytic continuation, as well as a functional equation satisfied by the Riemann zeta function given by\n$$ \\xi\\rb{s} = \\xi\\rb{1 - s}, \\qquad \\xi\\rb{s} = \\tfrac{1}{2}\\sqrt{\\pi}^{-s}s\\rb{s - 1}\\Gamma\\rb{\\tfrac{1}{2}s}\\zeta\\rb{s}. $$\nThe conjecture is then formulated in \\cite{riemann} as follows.\n\n\\begin{conjecture}[Riemann]\nLet $ s \\in \\C $ be such that $ s \\notin -2\\Z_{> 0} $. If $ \\zeta\\rb{s} = 0 $, then $ \\Re\\rb{s} = \\tfrac{1}{2} $.\n\\end{conjecture}\n\nThe connection to this still open problem can be seen via a powerful theorem known as the \\emph{Weil conjectures}, proposed by Weil and proven in steps later by himself, Dwork, Deligne, Grothendieck, and many others. The so-called conjectures also involve a related zeta function encoding the number of rational points of a smooth projective algebraic varieties variety, which is defined as follows.\n\n\\begin{definition}[Local zeta function]\nThe \\textbf{local zeta function} of a projective algebraic variety $ V $ over $ F $ is the power series\n$$ Z_V\\rb{t} = \\exp\\rb{\\sum_{n = 1}^\\infty \\abs{V\\rb{F_n}}\\dfrac{t^n}{n}}, \\qquad \\abs{V\\rb{F_n}} = \\dfrac{1}{\\rb{n - 1}!}\\val{\\dfrac{d^n}{dt^n}\\ln\\rb{Z_V\\rb{t}}}_{t = 0}. $$\nwhere $ F_n = \\F_{q^n} $.\n\\end{definition}\n\nThe following example is a trivial application the local zeta function.\n\n\\begin{example}\nLet $ V\\rb{0} $ be the trivial projective algebraic variety over $ F $. Then $ \\abs{V\\rb{F_n}} = 1 $ for any $ n \\in \\Z_{> 0} $, so\n$$ Z_V\\rb{t} = \\exp\\rb{\\sum_{n = 1}^\\infty \\dfrac{t^n}{n}} = \\exp\\rb{\\ln\\rb{\\dfrac{1}{1 - t}}} = \\dfrac{1}{1 - t}. $$\n\\end{example}\n\nHis three conjectures are then formulated as follows, which are easily satisfied by the above example.\n\n\\begin{theorem}[Weil conjectures]\n\\label{thm:weil}\nLet $ V $ be a smooth projective algebraic variety over $ F $ of dimension $ n \\in \\Z_{\\ge 0} $.\n\\begin{itemize}\n\\item Rationality. $ Z_V\\rb{t} = P\\rb{t} / \\rb{1 - t}\\rb{1 - q^nt} \\in \\Q\\sb{t} $, where\n$$ P\\rb{t} = \\prod_{i = 1}^{2n - 1} P_i\\rb{t}^{\\rb{-1}^{i + 1}}, \\qquad P_i \\in \\Z\\sb{t}. $$\n\\item Functional equation. Let $ \\epsilon \\in \\Z $ be the \\emph{Euler characteristic} of $ V $. Then\n$$ Z_V\\rb{\\dfrac{1}{q^nt}} = \\pm \\sqrt{q}^{n\\epsilon} t^\\epsilon Z_V\\rb{t}. $$\n\\item Riemann hypothesis. Let $ S_i = \\cb{\\alpha \\in \\C \\mid \\abs{\\alpha} = \\sqrt{q}^i} $ and $ P_i $ be as per above. Then each\n$$ P_i\\rb{t} = \\prod_{\\alpha \\in S_i'} \\rb{1 - \\alpha t}, $$\nover some $ S_i' \\subseteq S_i $ such that $ P_i \\in \\Z\\rb{t} $.\n\\end{itemize}\n\\end{theorem}\n\n\\begin{proof}\nOmitted, see \\cite{weil1}, \\cite{weil2}, and \\cite{weil3}.\n\\end{proof}\n\n\\pagebreak\n\n\\begin{remark}\nThere is a fourth Weil conjecture on \\emph{Betti numbers} that states if $ V $ is a \\emph{reduction modulo $ q $} of a smooth projective algebraic variety $ W $ over a number field, then $ \\deg\\rb{P_i} $ is the $ i^{th} $ topological Betti number of $ W $ for each $ P_i $.\n\\end{remark}\n\nIn the special case where $ V $ is a smooth projective algebraic curve $ C $ of genus $ g_C $, its dimension is $ n = 1 $ and its Euler characteristic is $ \\epsilon = 2 - 2g_C $, which greatly simplifies Theorem \\ref{thm:weil}. The following is a formulation for the elliptic curve $ E $ of genus one.\n\n\\begin{theorem}[Weil conjectures for elliptic curves]\n\\label{thm:weilcurve}\n$ Z_E $ satisfies the following properties.\n\\begin{itemize}\n\\item Rationality. $ Z_E\\rb{t} = P\\rb{t} / \\rb{1 - t}\\rb{1 - qt} \\in \\Q\\rb{t} $ for some $ P \\in \\Z\\rb{t} $.\n\\item Functional equation. $ Z_E\\rb{1 / qt} = \\pm Z_E\\rb{t} $.\n\\item Riemann hypothesis. $ P\\rb{t} = \\prod_\\alpha \\rb{1 - \\alpha t} $ for some $ \\alpha \\in \\C $ such that $ \\abs{\\alpha} = \\sqrt{q} $ and $ P \\in \\Z\\rb{t} $.\n\\end{itemize}\n\\end{theorem}\n\nAs full proofs of the Weil conjectures, even just for elliptic curves, requires further prerequisites on algebraic geometry, particularly on the \\emph{Tate module} and the \\emph{Weil pairing}, only the final part of the proof is given, of which the following lemma will be assumed.\n\n\\begin{lemma}\n$ \\abs{E\\rb{F_n}} = 1 + q^n - \\alpha^n - \\overline{\\alpha}^n $ for some $ \\alpha \\in \\C $ such that $ \\abs{\\alpha} = \\sqrt{q} $.\n\\end{lemma}\n\n\\begin{proof}\nOmitted, see V.2.3 in \\cite{gtm}.\n\\end{proof}\n\nLetting $ n = 1 $ in the above lemma for Theorem \\ref{thm:weilcurve} gives $ \\abs{\\abs{E\\rb{F}} - 1 - q} = \\abs{-\\alpha - \\overline{\\alpha}} \\le 2\\abs{\\alpha} = 2\\sqrt{q} $, which proves Hasse's theorem once again. The final part of the proof is as follows.\n\n\\begin{proof}[Proof of Theorem \\ref{thm:weilcurve}]\nThe above lemma on the zeta function gives $ \\alpha \\in \\C $ such that $ \\abs{\\alpha} = \\sqrt{q} $, and\n$$ \\ln\\rb{Z_E\\rb{t}} = \\sum_{n = 1}^\\infty \\rb{1 + q^n - \\alpha^n - \\overline{\\alpha}^n}\\dfrac{t^n}{n} = -\\ln\\rb{1 - t} - \\ln\\rb{1 - qt} + \\ln\\rb{1 - \\alpha t} + \\ln\\rb{1 - \\overline{\\alpha} t}. $$\nThus\n$$ Z_E\\rb{t} = \\dfrac{\\rb{1 - \\alpha t}\\rb{1 - \\overline{\\alpha}t}}{\\rb{1 - t}\\rb{1 - qt}}, \\qquad \\abs{\\alpha} = \\sqrt{q}, $$\nwhich satisfies rationality and the Riemann hypothesis, and gives the functional equation\n$$ Z_E\\rb{\\dfrac{1}{qt}} = \\dfrac{\\rb{1 - \\dfrac{\\alpha}{qt}}\\rb{1 - \\dfrac{\\overline{\\alpha}}{qt}}}{\\rb{1 - \\dfrac{1}{qt}}\\rb{1 - \\dfrac{1}{t}}} = \\dfrac{qt^2 - \\rb{\\alpha + \\overline{\\alpha}}t + \\dfrac{\\alpha\\overline{\\alpha}}{q}}{\\rb{qt - 1}\\rb{t - 1}} = \\dfrac{\\rb{1 - \\alpha t}\\rb{1 - \\overline{\\alpha}t}}{\\rb{1 - t}\\rb{1 - qt}} = Z_E\\rb{t}. $$\n\\end{proof}\n\nBy the above proof, the connection to the classical Riemann hypothesis can then be seen as follows. An analogue of the Riemann zeta function can be defined for elliptic curves over $ F $ as $ \\zeta_E\\rb{s} = Z_E\\rb{q^{-s}} $. It then satisfies a similar functional equation,\n$$ \\zeta_E\\rb{s} = Z_E\\rb{q^{-s}} = Z_E\\rb{q^{s - 1}} = \\zeta_E\\rb{1 - s}. $$\nIf $ \\zeta_E\\rb{s} = 0 $, Theorem \\ref{thm:weilcurve} also gives\n$$ \\dfrac{\\rb{1 - \\alpha q^{-s}}\\rb{1 - \\overline{\\alpha}q^{-s}}}{\\rb{1 - q^{-s}}\\rb{1 - q^{1 - s}}} = 0, \\qquad \\abs{\\alpha} = \\sqrt{q}. $$\nHence $ 1 = \\alpha q^{-s} $ or $ 1 = \\overline{\\alpha} q^{-s} $, so $ q^{\\Re\\rb{s}} = \\abs{q^s} = \\sqrt{q} $. Thus $ \\Re\\rb{s} = \\tfrac{1}{2} $.\n\n\\begin{remark}\nThe Weil conjectures is a generalisation of Riemann hypothesis, which those for elliptic curves is in turn a special case of. In general, there are many zeta functions analogous to the Riemann zeta function. One such family of zeta functions is for a \\emph{finitely generated algebra} $ R $ over $ \\Z $, defined as\n$$ \\zeta_R\\rb{s} = \\prod_M \\dfrac{1}{1 - \\abs{R / M}^{-s}}, $$\nover all maximal ideals $ M \\subset R $.\n\\end{remark}\n\n\\pagebreak\n\n\\subsection{Schoof's algorithm}\n\nIn light of Hasse's theorem, there were improved algorithms to compute $ E\\rb{F} $ similar to the naive approach described in a previous subsection. Lagrange's theorem gives that $ ord\\rb{P} \\mid \\abs{E\\rb{F}} $ for any point $ P \\in E\\rb{F} $, the latter of which is bounded by Hasse's theorem. After obtaining a random point $ P \\in E\\rb{F} $ by inspection or otherwise, simply try all values of $ n \\in \\Z $ such that $ q - 2\\sqrt{q} + 1 \\le n \\le q + 2\\sqrt{q} + 1 $ to catch whenever $ nP = \\mathcal{O} $. If this $ n $ is unique, the point $ P $ is a generator of $ E\\rb{F} $ and hence $ \\abs{E\\rb{F}} = ord\\rb{P} = n $. Otherwise obtain a different random point $ P \\in E\\rb{F} $ and repeat. This process can be illustrated with a prior example.\n\n\\begin{example}\nLet $ E : y^2 = x^3 + x + 1 $ be an elliptic curve over $ \\F_5 $ and $ P = \\rb{0, 1} \\in E\\rb{\\F_5} $ be a point. Hasse's theorem gives $ \\abs{E\\rb{\\F_5}} = 5 - t + 1 $ for some $ \\abs{t} \\le 2\\sqrt{5} $, so $ \\abs{E\\rb{\\F_5}} \\in \\cb{2, \\dots, 10} $. Then the addition formula gives only $ 9P = \\mathcal{O} $, so $ \\abs{E\\rb{\\F_5}} = 9 $.\n\\end{example}\n\nThere is then room for algorithms like \\emph{baby-step giant-step} that trades a space complexity of $ O\\rb{\\sqrt{q}} $ for a time complexity of also $ O\\rb{\\sqrt{q}} $, speeding up the computation further. However, discussions here will be on a different algorithm for computing $ \\abs{E\\rb{F}} $, which also builds upon Hasse's theorem. A high-level description of the \\emph{deterministic polynomial time} algorithm is as follows.\n\n\\begin{algorithm}[Schoof's algorithm]\nInput: an elliptic curve $ E $ over $ \\F_q $. Output: $ \\abs{E\\rb{\\F_q}} $.\n\\begin{enumerate}\n\\item Generate a set $ S $ of distinct primes excluding $ p $ with product $ N \\in \\Z_{> 0} $, such that $ N > 4\\sqrt{q} $.\n\\item Compute $ t \\mod n $ for each $ n \\in S $.\n\\item Obtain $ t \\mod N $ from each $ t \\mod n $.\n\\item Reduce $ t $ into a value between $ -2\\sqrt{q} $ and $ 2\\sqrt{q} $.\n\\item Calculate $ \\abs{E\\rb{F}} = q - t + 1 $.\n\\end{enumerate}\n\\end{algorithm}\n\nThe proof of this algorithm will be done in reverse. The first and last two steps will be made clear later, but several results will be proven for the second and third. In particular, the former generates a system of prime congruences for the latter, which in turn employs a classical theorem in number theory as follows.\n\n\\begin{theorem}[Chinese remainder]\nLet $ n_1, \\dots, n_k \\in \\Z_{> 1} $ be pairwise coprime with product $ N \\in \\Z_{> 0} $, and let $ t_1, \\dots, t_k \\in \\Z $. Then there is a unique $ t \\in \\Z_{\\ge 0} $ such that $ t < N $ and each $ t \\equiv t_i \\mod n_i $.\n\\end{theorem}\n\n\\begin{proof}\nLet $ k = 2 $. B\\'ezout's identity gives $ m_1n_1 + m_2n_2 = 1 $ for some $ m_i \\in \\Z $. Let $ t' = t_2m_1n_1 + t_1m_2n_2 $, so\n$$ t' = \\rb{t_2 - t_1}m_1n_1 + t_1\\rb{m_1n_1 + m_2n_2} \\equiv t_1 \\mod n_1, $$\n$$ t' = t_2\\rb{m_1n_1 + m_2n_2} - \\rb{t_2 - t_1}m_2n_2 \\equiv t_2 \\mod n_2. $$\nIf $ t'' \\in \\Z $ is such that $ t'' \\equiv t_1 \\mod n_1 $ and $ t'' \\equiv t_2 \\mod n_2 $, then $ t' \\equiv t'' \\mod n_1 $ and $ t' \\equiv t'' \\mod n_2 $, so $ n_1 \\mid t' - t'' $ and $ n_2 \\mid t' - t'' $. Then $ N = n_1n_2 \\mid t' - t'' $, so $ t' \\equiv t'' \\mod N $ and $ t' $ is unique up to congruences. Hence division gives a unique $ t \\in \\Z_{\\ge 0} $ such that $ t < N $ and $ t \\equiv t' \\mod N $. Now let $ k \\in \\Z_{\\ge 2} $ with product $ N_k \\in \\Z_{> 0} $ and assume that there is a unique $ t' \\in \\Z_{\\ge 0} $ such that $ t' < N_k $ and each $ t' \\equiv t_i \\mod n_i $. Since $ N_k $ and $ n_{k + 1} $ are coprime, the case $ k = 2 $ gives a unique $ t \\in \\Z_{\\ge 0} $ such that $ t < N_kn_{k + 1} $, and $ t \\equiv t' \\mod N_k $ and $ t \\equiv t_{k + 1} \\mod n_{k + 1} $. Thus the unique $ t \\in \\Z_{\\ge 0} $ holds by induction.\n\\end{proof}\n\n\\begin{remark}\nThe Chinese remainder theorem can be generalised to ideals $ I_i $ of arbitrary commutative unital rings $ R $, replacing the coprime condition with $ I_n + I_m = R $ for all $ n, m \\in \\Z $ and modulo with respect to $ I_i $.\n\\end{remark}\n\nA general process for computing this unique $ t \\in \\Z_{\\ge 0} $ can be inferred directly from the proof of the Chinese remainder theorem, using the extended Euclidean algorithm for B\\'ezout's identity, illustrated as follows.\n\n\\begin{example}\nLet\n$$ t \\equiv 1 \\mod 2, \\qquad t \\equiv 2 \\mod 3, \\qquad t \\equiv 3 \\mod 5 $$\nbe a system of congruences for $ t \\in \\Z_{\\ge 0} $. B\\'ezout's identity gives $ \\rb{-1}\\rb{2} + \\rb{1}\\rb{3} = 1 $, so let $ t' = 2\\rb{-1}\\rb{2} + 1\\rb{1}\\rb{3} = -1 $ be such that $ t' \\equiv 1 \\mod 2 $ and $ t' \\equiv 2 \\mod 3 $. Hence division gives $ t'' = 1\\rb{6} + \\rb{-1} = 5 < 6 $ such that $ t'' \\equiv t' \\mod 6 $. Similarly B\\'ezout's identity gives $ \\rb{1}\\rb{6} + \\rb{-1}\\rb{5} = 1 $, so let $ t''' = 3\\rb{1}\\rb{6} + 5\\rb{-1}\\rb{5} = -7 $ be such that $ t''' \\equiv 5 \\mod 6 $ and $ t''' \\equiv 3 \\mod 5 $. Thus division gives $ t = 1\\rb{30} + \\rb{-7} = 23 < 30 $ such that $ t \\equiv t''' \\mod 30 $ similarly.\n\\end{example}\n\nFor the rest of this section, let $ S $ be as in the first step of Schoof's algorithm and $ n \\in S $ be a prime. Now invoking the Chinese remainder theorem on the system of congruences $ t' \\equiv t \\mod n $ generated by the second step gives a unique $ t'' \\in \\Z_{\\ge 0} $ such that $ t'' < N $ and $ t'' \\equiv t' \\mod N $, as in the third step. The fourth step then ensures this $ t'' $ falls within the required bound using careful Euclidean division to give the trace $ t \\in \\Z $, of which the first step has made possible by forcing $ S $ to span the entire interval over which it could lie in. The fifth step is merely a simple application of Hasse's theorem. It only remains to understand the second step of Schoof's algorithm. This uses the properties of a general system of polynomials allowing for recursive operations, given in the following definition.\n\n\\begin{definition}[Division polynomial]\nThe \\textbf{$ n $-th division polynomial} $ \\psi_n \\in F\\sb{x, y} $ is defined for $ n \\in \\Z $ by\n\\begin{align*}\n\\psi_0\\rb{x, y} & = 0, \\\\\n\\psi_1\\rb{x, y} & = 1, \\\\\n\\psi_2\\rb{x, y} & = 2y, \\\\\n\\psi_3\\rb{x, y} & = 3x^4 + 6Ax^2 + 12Bx - A^2, \\\\\n\\psi_4\\rb{x, y} & = 4y\\rb{x^6 + 5Ax^4 + 20Bx^3 - 5A^2x^2 - 4ABx - A^3 - 8B^2},\n\\end{align*}\nrecursively defined for $ n > 4 $ by\n\\begin{align*}\n\\psi_{2m} & = \\tfrac{1}{2y}\\psi_m\\rb{\\psi_{m + 2}\\psi_{m - 1}^2 - \\psi_{m - 2}\\psi_{m + 1}^2}, \\\\\n\\psi_{2m + 1} & = \\psi_{m + 2}\\psi_m^3 - \\psi_{m - 1}\\psi_{m + 1}^3,\n\\end{align*}\nand for $ n < 0 $ by $ \\psi_{-n} = -\\psi_n $, with associated polynomials $ \\phi_n, \\omega_n \\in F\\sb{x, y} $ defined for $ n \\in \\Z_{\\ge 0} $ by\n\\begin{align*}\n\\phi_n & = x\\psi_n^2 - \\psi_{n + 1}\\psi_{n - 1}, \\\\\n\\omega_n & = \\tfrac{1}{4y}\\rb{\\psi_{n + 2}\\psi_{n - 1}^2 - \\psi_{n - 2}\\psi_{n + 1}^2}.\n\\end{align*}\n\\end{definition}\n\nIt holds that $ \\phi_{-n} = -\\phi_n $ and $ \\omega_{-n} = -\\omega_n $, and $ \\psi_{2m} = 2\\omega_n\\psi_n $. The following lemma allows certain division polynomials to be written solely in terms of $ x $.\n\n\\begin{lemma}\nIf $ n \\in \\Z $ is even, then\n$$ \\psi_n \\in 2y\\Z\\sb{x, A, B}, \\qquad \\phi_n \\in \\Z\\sb{x, A, B}, \\qquad \\omega_n \\in \\Z\\sb{x, A, B}, $$\notherwise $ n \\in \\Z $ is odd, then\n$$ \\psi_n \\in \\Z\\sb{x, A, B}, \\qquad \\phi_n \\in \\Z\\sb{x, A, B}, \\qquad \\omega_n \\in y\\Z\\sb{x, A, B}. $$\n\\end{lemma}\n\n\\begin{proof}\nLet $ Z = \\Z\\sb{x, A, B} $, then $ \\psi_0, \\psi_2, \\psi_4 \\in 2yZ $ and $ \\psi_1, \\psi_3 \\in Z $. Assume that $ \\psi_n \\in 2yZ $ for any even $ n \\in \\Z_{\\ge 0} $ and $ \\psi_n \\in Z $ for any odd $ n \\in \\Z_{\\ge 0} $ such that $ n < 2m $. If $ m $ is even, then\n$$ \\psi_m, \\psi_{m + 2}, \\psi_{m - 2} \\in 2yZ, \\qquad \\psi_{m - 1}, \\psi_{m + 1} \\in Z \\qquad \\implies \\qquad \\psi_{2m} \\in 2yZ, \\qquad \\psi_{2m + 1} \\in Z. $$\nOtherwise $ m $ is odd, then similarly\n$$ \\psi_{m - 1}, \\psi_{m + 1} \\in 2yZ, \\qquad \\psi_m, \\psi_{m + 2}, \\psi_{m - 2} \\in Z \\qquad \\implies \\qquad \\psi_{2m} \\in 2yZ, \\qquad \\psi_{2m + 1} \\in Z. $$\nHence $ \\psi_n \\in 2yZ $ for any even $ n \\in \\Z $ and $ \\psi_n \\in Z $ for any odd $ n \\in \\Z $. If $ n $ is even, then\n$$ \\psi_n^2 \\in y^2Z = Z, \\qquad \\psi_{n + 1}\\psi_{n - 1} \\in Z \\qquad \\implies \\qquad \\phi_n \\in Z. $$\nOtherwise $ n $ is odd, then similarly\n$$ \\psi_n^2 \\in Z, \\qquad \\psi_{n + 1}\\psi_{n + 1} \\in 4y^2Z = Z \\qquad \\implies \\qquad \\phi_n \\in Z. $$\nNow if $ n $ is even, then also\n$$ \\psi_{n + 2}, \\psi_{n - 2} \\in 2yZ, \\qquad \\psi_{n - 1}, \\psi_{n + 1} \\in Z \\qquad \\implies \\qquad \\omega_n \\in Z. $$\nOtherwise $ n $ is odd, then similarly also\n$$ \\psi_{n - 1}, \\psi_{n + 1} \\in 2yZ, \\qquad \\psi_{n + 2}, \\psi_{n - 2} \\in Z \\qquad \\implies \\qquad \\omega_n \\in yZ. $$\n\\end{proof}\n\nThe division polynomials $ \\phi_n\\rb{x, y} $, $ \\psi_n\\rb{x, y}^2 $, and $ \\omega_n\\rb{x, y}^2 $ can then be written as $ \\phi_n\\rb{x} $, $ \\psi_n\\rb{x}^2 $, and $ \\omega_n\\rb{x}^2 $ respectively as an abuse of notation without ambiguity. Now the familiar expression for $ \\psi_4 $ is that of the multiplication by two map, generalised as follows.\n\n\\begin{proposition}\nLet $ n \\in \\Z $. Then\n$$ \\sb{n}\\rb{x, y} = \\rb{x - \\dfrac{\\psi_{n + 1}\\rb{x, y}\\psi_{n - 1}\\rb{x, y}}{\\psi_n\\rb{x}^2}, \\dfrac{\\psi_{2n}\\rb{x, y}}{2\\psi_n\\rb{x, y}^4}} = \\rb{\\dfrac{\\phi_n\\rb{x}}{\\psi_n\\rb{x}^2}, \\dfrac{\\omega_n\\rb{x, y}}{\\psi_n\\rb{x, y}^3}}. $$\n\\end{proposition}\n\nThe proof of this proposition is through induction on $ n \\in \\Z_{\\ge 0} $ with base cases $ n \\in \\cb{0, \\dots, 4} $, while $ n \\in \\Z_{< 0} $ follows directly from the above observation. While it is completely elementary through the group law explicit formulae, it is extremely tedious and computational and hence are omitted altogether.\n\n\\begin{proof}\nOmitted, see III.E.3.7 in \\cite{gtm}.\n\\end{proof}\n\n\\begin{remark}\nThis proof can be approached via other ways, such as through properties of the \\emph{Weierstrass elliptic function} $ \\wp $ in 9.33 of \\cite{crypto}, which will not be discussed. The fact that $ \\gcd\\rb{\\phi_n, \\psi_n^2} = 1 $ and $ \\deg\\rb{\\phi_n} = n^2 $ also lends itself to another proof that $ \\deg\\rb{\\sb{n}} = n^2 $ for any $ n \\in \\Z $.\n\\end{remark}\n\nRelating this back to the standard form of isogenies, it holds that $ \\psi_n\\rb{a, b} = 0 $ iff $ \\sb{n}\\rb{P} = \\mathcal{O} $ for any point $ P = \\rb{a, b} \\in E $, which is the case whenever $ P \\in E\\sb{n} $. Group operations in $ End\\rb{E\\sb{n}} $ can be more easily done since the polynomials involved in the endomorphisms have bounded degrees in the \\emph{coordinate ring} $ F\\sb{x, y} / \\ab{y^2 - x^3 - Ax - B, \\psi_n} $, provided $ \\psi_n $ is already precomputed. Now arithmetic in $ End\\rb{E\\sb{n}} $ is motivated by the second step of Schoof's algorithm, where all congruences are modulo $ n $ and endomorphisms are computed modulo $ \\psi_n $. A \\emph{characteristic} equation that all endomorphisms satisfy will be given in the following lemma.\n\n\\begin{lemma}\nLet $ \\phi \\in End\\rb{E} $ be an endomorphism, and let $ d = \\deg\\rb{\\phi} $ and $ t = 2\\ab{\\phi, \\sb{1}} $. Then $ \\phi^2 - t\\phi + \\sb{d} = 0 $.\n\\end{lemma}\n\n\\begin{proof}\nLet $ n \\in \\cb{-1, 1} $. Since $ \\deg{\\phi + \\sb{n}} = \\deg\\rb{\\phi} + 2n\\ab{\\phi, \\sb{1}} + \\deg\\rb{\\sb{n}} = d + nt + 1 $,\nit holds that\n\\begin{align*}\n\\ab{\\phi^2, \\sb{1}}\n& = -\\tfrac{1}{2}\\rb{\\deg\\rb{\\phi^2 - \\sb{1}} - \\deg\\rb{\\phi^2} - \\deg\\rb{-\\sb{1}}} \\\\\n& = -\\tfrac{1}{2}\\rb{\\deg\\rb{\\phi - \\sb{1}}\\deg\\rb{\\phi + \\sb{1}} - \\deg\\rb{\\phi}^2 - 1} \\\\\n& = -\\tfrac{1}{2}\\rb{\\rb{d + t + 1}\\rb{d - t + 1} - d^2 - 1}\n= -\\tfrac{1}{2}\\rb{2d - t^2}.\n\\end{align*}\nSince also\n$$ \\ab{\\phi^2, \\phi} = \\tfrac{1}{2}\\rb{\\deg\\rb{\\phi^2 + \\phi} - \\deg\\rb{\\phi^2} - \\deg\\rb{\\phi}} = \\tfrac{1}{2}\\deg\\rb{\\phi}\\rb{\\deg\\rb{\\phi + \\sb{1}} - \\deg\\rb{\\phi} - \\sb{1}} = d\\ab{\\phi, \\sb{1}} = \\tfrac{1}{2}dt, $$\nit holds that\n\\begin{align*}\n\\deg\\rb{\\phi^2 - t\\phi + \\sb{d}}\n& = \\deg\\rb{\\phi^2} + \\deg\\rb{t\\phi} + \\deg\\rb{\\sb{d}} - 2\\ab{\\phi^2, t\\phi} + 2\\ab{\\phi^2, \\sb{d}} - 2\\ab{t\\phi, \\sb{d}} \\\\\n& = \\deg\\rb{\\phi}^2 + t^2\\deg\\rb{\\phi} + d^2 - 2t\\ab{\\phi^2, \\phi} + 2d\\ab{\\phi^2, \\sb{1}} - 2dt\\ab{\\phi, \\sb{1}} \\\\\n& = 2d^2 - 2t\\ab{\\phi^2, \\phi} + 2d\\ab{\\phi^2, \\sb{1}} \\\\\n& = 2d^2 - 2\\rb{\\tfrac{1}{2}dt^2} + 2d\\rb{-\\tfrac{1}{2}\\rb{2d - t^2}}\n= 0.\n\\end{align*}\nThus $ \\phi^2 - t\\phi + \\sb{d} = 0 $.\n\\end{proof}\n\nIn particular, the $ q $-th Frobenius endomorphism satisfies the characteristic equation, so it can be written as $ tFr_q = Fr_q^2 + \\sb{q} $. While it is possible to compute the right hand side directly and try all values of $ t $ until one satisfies the characteristic equation, the polynomials involved in $ Fr_q $ and $ Fr_q^2 $ will have rapidly increasing degrees, which is highly impractical for huge $ q $. The second step handles exactly this by reducing the equation in $ End\\rb{E} $ to one in $ End\\rb{E\\sb{n}} $ with affine points, as seen in the following lemma.\n\n\\begin{lemma}\nLet $ P = \\rb{a, b} \\in E\\sb{n} $ be a point. Then there are unique $ t_n \\in \\Z_{\\ge 0} $ and $ q_n \\in \\Z_{> 0} $ such that $ t_n \\equiv t, \\ q_n \\equiv q \\mod n $ with $ \\abs{t_n}, \\abs{q_n} < n $, and\n$$ t_n\\rb{a^q, b^q} = \\rb{a^{q^2}, b^{q^2}} + \\rb{a_q, b_q}, \\qquad q_nP = \\rb{a_q, b_q} \\in E\\sb{n}. $$\n\\end{lemma}\n\n\\begin{proof}\nSince $ Fr_q $ is injective, so is $ Fr_q^2 $, so $ Fr_q\\rb{P} = \\rb{a^q, b^q} $ and $ Fr_q^2\\rb{P} = \\rb{a^{q^2}, b^{q^2}} $. Hence\n$$ t\\rb{a^q, b^q} = \\rb{a^{q^2}, b^{q^2}} + q\\rb{a, b}. $$\nNow Lagrange's theorem gives that $ P \\in E\\sb{n} $ iff $ ord\\rb{P} = n $. Since $ q $ is prime and $ q \\ne n $, it holds that $ \\gcd\\rb{q, n} = 1 $, so $ qP \\ne \\mathcal{O} $. Then division gives a unique $ q_n \\in \\Z_{> 0} $ such that $ q_n \\equiv q \\mod n $ with $ \\abs{q_n} < n $. Hence $ q_nP = qP = \\rb{a_q, b_q} $ for some point $ \\rb{a_q, b_q} \\in E\\sb{n} $. Similarly division gives a unique $ t_n \\in \\Z_{\\ge 0} $ such that $ t_n \\equiv t \\mod n $ and $ \\abs{t_n} < n $. Since $ Fr_q $ has a trivial kernel and $ nFr_q\\rb{P} = Fr_q\\rb{nP} = Fr_q\\rb{\\mathcal{O}} = \\mathcal{O} $, it holds that $ ord\\rb{Fr_q\\rb{P}} = n = ord\\rb{P} $, so $ t_nFr_q\\rb{P} = tFr_q\\rb{P} $ similarly. Thus\n$$ t_n\\rb{a^q, b^q} = \\rb{a^{q^2}, b^{q^2}} + \\rb{a_q, b_q}. $$\n\\end{proof}\n\nHence it boils down to obtaining a suitable $ t_n \\in \\Z_{\\ge 0} $ satisfying\n$$ t_n\\rb{x^q, y^q} = \\rb{x^{q^2}, y^{q^2}} + q_n\\rb{x, y}, $$\nall of which can be computed as per usual, but in the coordinate ring $ F\\sb{x, y} / \\ab{y^2 - x^3 - Ax - B, \\psi_n} $. The following algorithm illustrates the process of computing this $ t_n $, with further details given in \\cite{crypto}.\n\n\\begin{algorithm}[Computation of the trace modulo prime]\nInput: an elliptic curve $ E $ over $ \\F_q $ and a prime $ n \\in S $. Output: $ t_n $. If $ n = 2 $, then\n$$ t_n = \\begin{cases} 0 & g \\ne 1 \\\\ 1 & g = 1 \\end{cases}, \\qquad g = \\gcd\\rb{x^q - x, x^3 + Ax + B}. $$\nOtherwise $ n > 2 $, then compute $ \\psi_n $ and $ q_n $, and reduce $ q_n $ into a value between $ -n / 2 $ and $ n / 2 $. Let\n$$ \\rb{x', y'} = \\rb{x^{q^2}, y^{q^2}} + q_n\\rb{x, y}, \\qquad \\rb{x'', y''} = \\rb{x^q, y^q}. $$\nIf $ x' = x_i $, where $ \\rb{x_i, y_i} = i\\rb{x'', y''} $ for some $ i \\in \\cb{1, \\dots, \\rb{n - 1} / 2} $, then\n$$ t_n = \\begin{cases} i & y' = y_i \\\\ -i & y' = -y_i \\end{cases}. $$\nOtherwise if $ q_n \\equiv r_n^2 \\mod n $ for some $ r_n \\in \\cb{1, \\dots, \\rb{n - 1} / 2} $, then let $ \\rb{x_r, y_r} = r_n\\rb{x, y} $ and\n$$ \\rb{\\dfrac{r\\rb{x}}{s\\rb{x}}, \\dfrac{u\\rb{x}}{v\\rb{x}}y} = \\rb{x'' - x_r, y'' - y_r}, \\qquad \\gcd\\rb{r, s} = \\gcd\\rb{u, v} = 1. $$\nIf $ \\gcd\\rb{r, \\psi_n} = 1 $, then\n$$ t_n = \\begin{cases} 2r_n & g' \\ne 1 \\\\ -2r_n & g' = 1 \\end{cases}, \\qquad g' = \\gcd\\rb{u, \\psi_n} $$\nOtherwise $ t_n = 0 $.\n\\end{algorithm}\n\nAn analysis of Schoof's algorithm shows that it has a time complexity of $ O\\rb{\\log^8\\rb{q}} $, which is asymptotically faster than that of the naive approach. Subsequently, there were refinements that restricted the primes in $ S $ into \\emph{Elkies primes} and \\emph{Atkin primes} rather than arbitrary small primes, and made use of \\emph{modular polynomials} rather than division polynomials. Now known as the \\emph{Schoof-Elkies-Atkin} algorithm, it has a time complexity of $ O\\rb{\\log^6\\rb{q}} $ and is widely used in practicality when the prime $ q $ in question is huge, seen in the \\emph{ellcard} command in the \\emph{PARI} programming language. In implementations when maximum efficiency is required, a probabilistic version is used, which allows even faster computations of many operations.\n\n\\pagebreak\n\n\\subsection{Point counting}\n\nAs per the aim of this section, Schoof's algorithm computes the number of rational points of elliptic curves over finite fields. Although computations are generally done by code due to routine tedium, the following simple example illustrates a possible execution process.\n\n\\begin{example}\nLet $ E : y^2 = x^3 + 2x + 1 $ be an elliptic curve over $ \\F_{19} $, so let $ S = \\cb{2, 3, 5} $ be such that $ N = \\rb{2}\\rb{3}\\rb{5} = 30 > 20 = 4\\sqrt{25} > 4\\sqrt{19} $.\n\\begin{itemize}\n\\item Let $ n = 2 $. Then\n\\begin{align*}\nx^{19}\n& = x\\rb{-2x - 1}^6\n= 7x^7 + 2x^6 + 12x^5 + 8x^4 + 3x^3 + 12x^2 + x \\\\\n& = 7x\\rb{-2x - 1}^2 + 2\\rb{-2x - 1}^2 + 12x^2\\rb{-2x - 1} + 8x\\rb{-2x - 1} + 3\\rb{-2x - 1} + 12x^2 + x \\\\\n& = 4x^3 + x^2 + 2x + 18\n= 4\\rb{-2x - 1} + x^2 + 2x + 18\n= x^2 + 13x + 14,\n\\end{align*}\nso $ \\gcd\\rb{x^{19} - x, x^3 + 2x + 1} = \\gcd\\rb{x^2 + 12x + 14, x^3 + 2x + 1} = 1 $. Hence $ t_2 = 1 $.\n\\item Let $ n = 3 $. Then $ q_3 = 1 \\equiv 19 \\mod 3 $ such that $ -3 / 2 \\le 1 \\le 3 / 2 $, and $ \\psi_3\\rb{x} = 3x^4 + 12x^2 + 12x + 15 $. Since $ \\psi_3\\rb{8} = 3\\rb{8}^4 + 12\\rb{8}^2 + 12\\rb{8} + 15 = 0 $, it holds that $ \\rb{8, b} \\in E\\rb{\\F_{19}}\\sb{3} $ for some $ b \\in \\F_{19} $. Lagrange's theorem gives $ 3 \\mid \\abs{E\\rb{\\F_{19}}} $, so $ 19 - t + 1 \\equiv 0 \\mod 3 $ and $ t \\equiv 20 \\equiv 2 \\mod 3 $. Hence $ t_3 = 2 $.\n\\item Let $ n = 5 $. Then $ q_5 = -1 \\equiv 19 \\mod 5 $ such that $ -5 / 2 \\le 1 \\le 5 / 2 $, and\n\\begin{align*}\n\\psi_5\\rb{x}\n& = \\psi_4\\rb{x, y}\\psi_2\\rb{x, y}^3 - \\psi_1\\rb{x, y}\\psi_3\\rb{x, y}^3 \\\\\n& = 4y\\rb{x^6 + 10x^4 + x^3 + 18x^2 + 11x + 11 + 11}\\rb{2y}^3 - 1\\rb{3x^4 + 12x^2 + 12x + 15}^3 \\\\\n& = 13\\rb{x^3 + 2x + 1}^2\\rb{x^6 + 10x^4 + x^3 + 18x^2 + 11x + 3} \\\\\n& \\qquad + 11x^{12} + 18x^{10} + 18x^9 + 9x^8 + 11x^7 + 6x^6 + 12x^5 + 10x^4 + 18x^3 + 12x^2 + 13x + 7 \\\\\n& = 5x^{12} + 10x^{10} + 17x^8 + 5x^7 + x^6 + 9x^5 + 12x^4 + 2x^3 + 5x^2 + 8x + 8,\n\\end{align*}\nso let $ \\rb{x', y'} = \\rb{x^{361}, y^{361}} - \\rb{x, y} $ and $ \\rb{x'', y''} = \\rb{x^{19}, y^{19}} $. It can be tediously verified that $ x' \\ne x_1 $ but $ x' = x_2 $, where $ \\rb{x_i, y_i} = i\\rb{x'', y''} $, so $ t_n \\equiv 2 \\mod 5 $ or $ t_n \\equiv -2 \\mod 5 $. Another tedious verification gives $ y' = -y_2 $, so $ t_n \\equiv -2 \\equiv 3 \\mod 5 $. Hence $ t_5 = 3 $.\n\\end{itemize}\nThe Chinese remainder theorem from the example above gives $ t \\equiv 23 \\mod 30 $ such that $ 0 \\ge 23 < 30 = N $. Thus $ t = 23 - 30 = -7 $ is such that $ \\abs{-7} < 8 = 4\\sqrt{4} < 4\\sqrt{19} $ and $ \\abs{E\\rb{\\F_{19}}} = 19 - \\rb{-7} + 1 = 27 $.\n\\end{example}\n\nWhile just counting $ F $-rational points may have many practical applications, a subtler question would be characterising their group structure. This would be more than just Schoof's algorithm, but machinery from previous subsections can finally combine to give the following proposition.\n\n\\begin{proposition}\n$ E\\rb{F} \\cong \\Z_{n_1} $ or $ E\\rb{F} \\cong \\Z_{n_1} \\oplus \\Z_{n_2} $ for some $ n_1, n_2 \\in \\Z_{> 0} $ such that $ n_1 \\mid n_2 $.\n\\end{proposition}\n\n\\begin{proof}\nThe fundamental theorem of finite abelian groups gives\n$$ E\\rb{F} \\cong \\bigoplus_{i = 1}^m \\Z_{n_i}, \\qquad m \\in \\Z_{\\ge 0}, \\qquad n_i \\in \\Z_{> 0}, $$\nsuch that each $ n_i \\mid n_{i + 1} $. Let $ G_i = \\cb{x \\in \\Z_{n_i} \\mid ord\\rb{x} \\mid n_1} \\le \\Z_{n_i} $ be subgroups. Then each $ \\phi_i : \\Z_{n_1} \\to G_i $ defined by $ \\phi_i\\rb{x} = n_ix / n_1 $ is an isomorphism, so each $ \\abs{G_i} = \\abs{\\Z_{n_1}} = n_1 $. Hence\n$$ n_1^m = \\abs{\\bigoplus_{i = 1}^m G_i} = \\abs{E\\rb{F}\\sb{n_1}} \\le \\abs{E\\sb{n_1}} = \\abs{Ker\\rb{n_1}} = \\deg_s\\rb{\\sb{n_1}} \\le \\deg\\rb{\\sb{n_1}} = n_1^2. $$\nSince $ q \\notin \\cb{2, 3} $, it holds that $ \\abs{E\\rb{F}} = q - t + 1 \\ge q - 2\\sqrt{q} + 1 > 1 $. Thus $ \\abs{E\\rb{F}} \\ncong \\cb{0} $ and $ m \\in \\cb{1, 2} $.\n\\end{proof}\n\nBoth cases can arise from different elliptic curves and finite fields, as seen in the following example.\n\n\\begin{example}\n$ E\\rb{\\F_5} \\cong \\Z_9 $ in the above example, while $ E' : y^2 = x^3 + x $ over $ \\F_5 $ has $ E'\\rb{\\F_5} \\cong \\Z_2 \\oplus \\Z_2 $.\n\\end{example}\n\n\\begin{remark}\nIf $ q \\in \\cb{2, 3} $, then $ E\\rb{F} $ could be trivial, but the only examples with this property are $ E_2 : y^2 + y = x^3 + x + 1 $ and $ E_2' : y^2 + y = x^3 + x^2 + 1 $ over $ \\F_2 $ and $ E_3 : y^2 = x^3 - x - 1 $ over $ \\F_3 $, up to isomorphism.\n\\end{remark}\n\n\\pagebreak\n\n\\section{Elliptic curves over the rationals}\n\nAfter the discussion of elliptic curves over finite fields, the focus redirects to the field of rational numbers. Again, the question of computing the rational points arises again, with the unfortunate answer that it is not as straightforward as finite fields. Due to the countably infinite nature of the rationals, enumerating all possible rational solutions of all elliptic curves is not possible, so other techniques will be deployed. In particular, there will be an attempt to prove one of the most fundamental theorems of elliptic curves over the rationals, namely that the rational points form a finitely generated group. While finite groups arising from finite fields can be fully characterised by the fundamental theorem of finite abelian groups, finitely generated groups arising from the rationals can be fully characterised by the fundamental theorem of finitely generated abelian groups,\n$$ E\\rb{\\Q} \\cong \\Z^r \\oplus \\bigoplus_{i = 1}^m \\Z_{n_i}, \\qquad r, m \\in \\Z_{\\ge 0}, \\qquad n_i \\in \\Z_{> 1}, $$\nsuch that each $ n_i \\mid n_{i + 1} $, which is given in full in Appendix A.4. However, there are issues with computing $ r \\in \\Z_{\\ge 0} $, which will be discussed later. Now let $ E $ be an elliptic curve over the perfect field $ \\Q $, given by the Weierstrass curve\n$$ E : y^2 = x^3 + A'x + B', \\qquad A' = \\dfrac{p}{q}, B' = \\dfrac{p'}{q'} \\in \\Q, $$\nwith the group of rational points $ E\\rb{\\Q} = \\rb{E\\rb{\\Q}, \\mathcal{O}, +} $. Since there is a $ j $-invariant affine transformation $ \\rb{x, y} \\mapsto \\rb{q^{-2}q'^{-2}x, q^{-3}q'^{-3}y} $, there is an isomorphism from $ E $ to the curve given by the Weierstrass equation\n$$ \\rb{\\dfrac{1}{q^3q'^3}y}^2 = \\rb{\\dfrac{1}{q^2q'^2}x}^3 + \\dfrac{p}{q}\\rb{\\dfrac{1}{q^2q'^2}x} + \\dfrac{p'}{q'} \\qquad \\implies \\qquad y^2 = x^3 + pq^3q'^4x + p'q^6q'^5. $$\nHence for this section, assume without loss of generality that\n$$ E : y^2 = x^3 + Ax + B, \\qquad A, B \\in \\Z. $$\n\n\\subsection{Nagell-Lutz theorem}\n\nFor the following sections, let $ \\Delta'_E = \\tfrac{1}{16}\\Delta_E $ be the \\emph{reduced discriminant}. Then the following theorem characterises the affine coordinates of torsion points.\n\n\\begin{theorem}[Nagell-Lutz]\n\\label{thm:nagelllutz}\nLet $ P = \\rb{a, b} \\in E\\rb{\\Q} $ be a non-zero torsion point. Then:\n\\begin{enumerate}\n\\item $ a, b \\in \\Z $, and\n\\item $ b = 0 $ or $ b^2 \\mid \\Delta'_E $.\n\\end{enumerate}\n\\end{theorem}\n\nProof of the first part of the Nagell-Lutz theorem will be split into several definitions and lemmas, many of which follows from the properties of \\emph{$ p $-adic numbers}, which will not be discussed. Now let $ p \\in \\Z_{> 0} $ be a prime. A particular valuation in the construction of $ p $-adic numbers describing how a prime divides the numerator or denominator of a rational number is given in the following definition.\n\n\\begin{definition}[$ p $-adic valuation]\nThe \\textbf{$ p $-adic valuation} is a valuation $ v_p : \\Q \\to \\Z \\cup \\cb{\\infty} $ defined by\n$$ v_p\\rb{x} = \\begin{cases} \\max\\cb{v \\in \\Z_{\\ge 0} \\ \\Big| \\ x = \\dfrac{q}{r}p^v, \\ q \\in \\Z, \\ r \\in \\Z_{> 0}, \\ p \\nmid r} & x \\ne 0 \\\\ \\infty & x = 0 \\end{cases}. $$\n\\end{definition}\n\nHence any $ x \\in \\Q $ will be uniquely written as\n$$ x = \\dfrac{q}{r}p^v, \\qquad q \\in \\Z, \\qquad r \\in \\Z_{> 0}, $$\nsuch that $ p, q, r $ are pairwise coprime, where $ v = v_p\\rb{x} $. It is clear that $ v_p\\rb{q / r} $ is positive whenever $ p $ divides $ q $ and $ v_p\\rb{q / r} $ is negative whenever $ p $ divides $ r $, while $ v_p\\rb{q / r} $ is zero otherwise. This can be illustrated in the following example.\n\n\\begin{example}\n$$ v_5\\rb{\\dfrac{100}{10}} = v_5\\rb{\\dfrac{2}{1}5^1} = 1, \\qquad v_5\\rb{\\dfrac{10}{100}} = v_5\\rb{\\dfrac{1}{2}5^{-1}} = -1, \\qquad v_5\\rb{1} = v_5\\rb{5^0} = 0. $$\n\\end{example}\n\nThree properties given in the following lemma will come in handy when computing $ p $-adic valuations of sums and products.\n\n\\begin{lemma}\nLet $ x, y \\in \\Q $. Then:\n\\begin{enumerate}\n\\item $ v_p\\rb{1 / x} = -v_p\\rb{x} $,\n\\item $ v_p\\rb{xy} = v_p\\rb{x} + v_p\\rb{y} $, and\n\\item $ v_p\\rb{x + y} \\ge \\min\\cb{v_p\\rb{x}, v_p\\rb{y}} $, with equality if $ v_p\\rb{x} \\ne v_p\\rb{y} $.\n\\end{enumerate}\n\\end{lemma}\n\n\\begin{proof}\nLet\n$$ x = \\dfrac{q}{r}p^v, \\qquad y = \\dfrac{q'}{r'}p^{v'}, \\qquad q, q' \\in \\Z, \\qquad r, r' \\in \\Z_{> 0}, $$\nsuch that $ p, q, r $ are pairwise coprime and $ p, q', r' $ are pairwise coprime, where $ v = v_p\\rb{x} $ and $ v' = v_p\\rb{y} $.\n\\begin{enumerate}\n\\item Since $ \\gcd\\rb{r, q} = 1 $,\n$$ v_p\\rb{\\dfrac{1}{x}} = v_p\\rb{\\dfrac{r}{q}p^{-v}} = -v = -v_p\\rb{x}. $$\n\\item Since $ \\gcd\\rb{p, qq'} = \\gcd\\rb{p, rr'} = 1 $,\n$$ v_p\\rb{xy} = v_p\\rb{\\dfrac{qq'}{rr'}p^{v + v'}} = v + v' = v_p\\rb{x} + v_p\\rb{y}. $$\n\\item Assume that $ v = v' $. Then\n$$ v_p\\rb{x + y} = v_p\\rb{\\dfrac{qr'p^v + q'rp^v}{rr'}} = v_p\\rb{\\dfrac{qr' + q'r}{rr'}p^v} \\ge v = \\min\\cb{v, v'} = \\min\\cb{v_p\\rb{x}, v_p\\rb{y}}. $$\nAssume otherwise that $ v > v' $. Since $ \\gcd\\rb{rr'} = \\gcd\\rb{p, qr'p^{v - v'} + q'r} = 1 $,\n$$ v_p\\rb{x + y} = v_p\\rb{\\dfrac{qr'p^v + q'rp^{v'}}{rr'}} = v_p\\rb{\\dfrac{qr'p^{v - v'} + q'r}{rr'}p^{v'}} = v' = \\min\\cb{v, v'} = \\min\\cb{v_p\\rb{x}, v_p\\rb{y}}. $$\nSimilarly, if $ v < v' $, then $ v_p\\rb{x + y} = \\min\\cb{v_p\\rb{x}, v_p\\rb{y}} $.\n\\end{enumerate}\n\\end{proof}\n\nThe following example illustrates the above lemma.\n\n\\begin{example}\n$$ v_5\\rb{\\dfrac{25}{5}} = v_5\\rb{5} = 1 = 2 - 1 = v_5\\rb{25} - v_5\\rb{5}, \\qquad v_2\\rb{8} = 3 > 2 = \\min\\cb{v_2\\rb{4}, v_2\\rb{4}}. $$\n\\end{example}\n\nWith this trick, a relation between the $ p $-adic valuated coordinates of any affine rational point in an elliptic curve can be seen in the following lemma.\n\n\\begin{lemma}\nLet $ P = \\rb{a, b} \\in E\\rb{\\Q} $ be a point. Then $ v_p\\rb{a} < 0 $ iff $ v_p\\rb{b} < 0 $, for which $ v_p\\rb{a} = -2v $ and $ v_p\\rb{b} = -3v $ for some $ v \\in \\Z_{> 0} $.\n\\end{lemma}\n\n\\begin{proof}\nAssume that $ v_p\\rb{a} < 0 $. Since $ A, B \\in \\Z $, it holds that $ v_p\\rb{A}, v_p\\rb{B} \\ge 0 $, so\n$$ 2v_p\\rb{b} = v_p\\rb{b^2} = v_p\\rb{a^3 + Aa + B} = \\min\\cb{3v_p\\rb{a}, v_p\\rb{A} + v_p\\rb{a}, v_p\\rb{B}} = 3v_p\\rb{a}. $$\nHence $ 2 \\mid v_p\\rb{a} $ and $ 3 \\mid v_p\\rb{b} $, so $ v_p\\rb{a} = -2v $ and $ v_p\\rb{b} = -3v $ for some $ v \\in \\Z_{> 0} $. Conversely assume that $ v_p\\rb{a} \\ge 0 $. Then $ 2v_p\\rb{b} \\ge \\min\\cb{3v_p\\rb{a}, v_p\\rb{A} + v_p\\rb{a}, v_p\\rb{B}} \\ge 0 $. Thus $ v_p\\rb{b} \\ge 0 $.\n\\end{proof}\n\nHence for any point $ P = \\rb{a, b} \\in E\\rb{\\Q} $,\n$$ a = \\dfrac{q}{d^2}, \\qquad b = \\dfrac{r}{d^3}, \\qquad q, r \\in \\Z, \\qquad d \\in \\Z_{> 0} $$\nsuch that $ \\gcd\\rb{q, d} = \\gcd\\rb{r, d} = 1 $. This fact will be proven explicitly here as it will be used several times in later subsections. Now a change of coordinates will be undertaken to ease discussions, namely\n$$ t = T = \\dfrac{X}{Y}, \\qquad s = S = \\dfrac{Z}{Y}, \\qquad \\sb{X, Y, Z} \\mapsto \\sb{T, 1, S} = \\rb{t, s}, $$\nwhich is an invertible projective transformation\n$$ E : Y^2Z = X^3 + AXZ^2 + BZ^3 \\qquad \\iff \\qquad E' : S = T^3 + ATS^2 + BS^3 : s = t^3 + Ats^2 + Bs^3. $$\nThis has the effect that\n$$ \\mathcal{O} \\mapsto \\rb{0, 0}, \\qquad \\rb{a, b} \\mapsto \\rb{\\dfrac{a}{b}, \\dfrac{1}{b}} $$\nfor any point $ \\rb{a, b} \\in E\\rb{\\Q} $ such that $ b \\ne 0 $, while the three $ 2 $-torsion points $ \\rb{a, 0} $ map to three points at infinity and can be disregarded for now. The modified group law is then given in the following lemma.\n\n\\begin{lemma}\nLet $ P = \\rb{a, b} \\in E'\\rb{\\Q} $ and $ Q = \\rb{a', b'} \\in E'\\rb{\\Q} $ be points such that $ P + Q = \\rb{a'', b''} \\in E'\\rb{\\Q} $. Then $ -P = \\rb{-a, -b} $ and\n$$ a'' = a + a' + \\dfrac{2A\\lambda\\mu + 3B\\lambda^2\\mu}{1 + A\\lambda^2 + B\\lambda^3}, \\qquad \\lambda = \\dfrac{a^2 + aa' + a'^2 + Ab'^2}{1 - Aa\\rb{b + b'} - B\\rb{b^2 + bb' + b'^2}}, \\qquad \\mu = b - \\lambda a. $$\n\\end{lemma}\n\n\\begin{proof}\nSince $ \\rb{a, b} \\mapsto \\rb{a / b, 1 / b} $, it holds that $ -\\rb{a, b} = \\rb{a, -b} \\mapsto \\rb{-a / b, -1 / b} $. Let $ P * Q = -\\rb{P + Q} = \\rb{-a'', -b''} $. If $ a \\ne a' $, then the line joining $ P $ and $ Q $ is\n$$ L : s = \\lambda_1 t + \\mu_1, \\qquad \\lambda_1 = \\dfrac{b - b'}{a - a'}, \\qquad \\mu_1 = b - \\lambda_1 a. $$\nOtherwise $ a = a' $, then the tangent at $ P $ is\n$$ L : s = \\lambda_2 t + \\mu_2, \\qquad \\lambda_2 = \\dfrac{3a^2 + Ab^2}{1 - 2Aab - 3Bb^2}, \\qquad \\mu_2 = b - \\lambda_2 a. $$\nSince\n\\begin{align*}\nb - b'\n& = a^3 + Aab^2 + Bb^3 - a'^3 - Aa'b'^2 - Bb'^3 \\\\\n& = a^3 - a'^3 + Aab^2 - Aab'^2 + Aab'^2 - Aa'b'^2 + Bb^3 - Bb'^3 \\\\\n& = \\rb{a - a'}\\rb{a^2 + aa' + a'^2} + Aa\\rb{b - b'}\\rb{b + b'} + Ab'^2\\rb{a - a'} + B\\rb{b - b'}\\rb{b^2 + bb' + b'^2},\n\\end{align*}\nit holds that\n$$ \\rb{b - b'}\\rb{1 - Aa\\rb{b + b'} - B\\rb{b^2 + bb' + b'^2}} = \\rb{a - a'}\\rb{a^2 + aa' + a'^2 + Ab'^2}, $$\nso $ \\rb{b - b'} / \\rb{a - a'} = \\lambda = \\lambda_1 = \\lambda_2 $ and $ \\mu = \\mu_1 = \\mu_2 $. Now $ L : s = \\lambda t + \\mu $ intersects $ E' $ at\n$$ \\rb{1 + A\\lambda^2 + B\\lambda^3}t^3 + \\rb{2A\\lambda\\mu + 3B\\lambda^2\\mu}t^2 + \\rb{A\\mu^2 + 3B\\lambda\\mu^2 - \\lambda}t - \\rb{\\mu - B\\mu^3} = 0. $$\nThus comparing coefficients gives $ -\\rb{2A\\lambda\\mu + 3B\\lambda^2\\mu} / \\rb{1 + A\\lambda^2 + B\\lambda^3} = a + a' - a'' $.\n\\end{proof}\n\nThe above proof is brief but can be verified manually. Now let\n$$ E\\rb{p^v} = \\cb{\\mathcal{O}} \\cup \\cb{\\rb{a, b} \\in E\\rb{\\Q} \\mid v_p\\rb{a} \\le -2v, \\ v_p\\rb{b} \\le -3v} $$\nbe a subset of $ E\\rb{\\Q} $. Rewriting coordinates accordingly gives $ v_p\\rb{a / b} \\ge v $ and $ v_p\\rb{1 / b} \\ge 3v $, so let\n$$ E'\\rb{p^v} = \\cb{\\rb{0, 0}} \\cup \\cb{\\rb{a, b} \\in E'\\rb{\\Q} \\mid v_p\\rb{a} \\ge v, \\ v_p\\rb{b} \\ge 3v} $$\nbe a subset of $ E'\\rb{\\Q} $ bijective to $ E\\rb{p^v} $. These two sets induce two decreasing sequences of subsets.\n\n\\begin{definition}[Filtration]\nA \\textbf{filtration} is a decreasing sequence of subsets $ S_i $ such that $ S_i \\supseteq S_j $ for any $ i \\le j $.\n\\end{definition}\n\nA simple rephrasal gives that $ E\\rb{p^v} $ and $ E'\\rb{p^v} $ \\emph{induce} two $ p $-adic filtrations\n$$ E\\rb{\\Q} \\supseteq E\\rb{p} \\supseteq E\\rb{p^2} \\supseteq E\\rb{p^3} \\supseteq \\dots \\supseteq \\cb{\\mathcal{O}}, \\qquad E'\\rb{\\Q} \\supseteq E'\\rb{p} \\supseteq E'\\rb{p^2} \\supseteq E'\\rb{p^3} \\supseteq \\dots \\supseteq \\cb{\\rb{0, 0}}. $$\nThe individual subsets in these filtrations are actually subgroups, giving a filtration of subgroups, which will be proven in the following lemma.\n\n\\begin{lemma}\nLet $ v \\in \\Z_{> 0} $ and $ P = \\rb{a, b} \\in E'\\rb{p^v} $ and $ Q = \\rb{a', b'} \\in E'\\rb{p^v} $ be points such that $ P + Q = \\rb{a'', b''} \\in E'\\rb{\\Q} $. Then $ -P, P + Q \\in E'\\rb{p^v} $ and $ v_p\\rb{a + a' + a''} \\ge 5v $.\n\\end{lemma}\n\n\\begin{proof}\nSince $ -P = \\rb{-a, -b} $, it holds that $ v_p\\rb{-a} = v_p\\rb{a} $, so $ -P \\in E'\\rb{p^v} $. Since $ A, B \\in \\Z $, it holds that $ v_p\\rb{A}, v_p\\rb{B} \\ge 0 $. Now the group law gives\n$$ a'' = a + a' + \\dfrac{2A\\lambda\\mu + 3B\\lambda^2\\mu}{1 + A\\lambda^2 + B\\lambda^3}, \\qquad \\lambda = \\dfrac{a^2 + aa' + a'^2 + Ab'^2}{1 - Aa\\rb{b + b'} - B\\rb{b^2 + bb' + b'^2}}, \\qquad \\mu = b - \\lambda a. $$\nThen\n\\begin{align*}\nv_p\\rb{a^2 + aa' + a'^2 + Ab'^2} & \\ge \\min\\cb{2v_p\\rb{a}, v_p\\rb{a} + v_p\\rb{a'}, 2v_p\\rb{a'}, v_p\\rb{A} + 2v_p\\rb{b'}} \\ge 2v, \\\\\nv_p\\rb{Aa\\rb{b + b'}} & \\ge \\min\\cb{v_p\\rb{a} + v_p\\rb{a'} + v_p\\rb{b}, v_p\\rb{a} + v_p\\rb{a'} + v_p\\rb{b'}} \\ge 5v, \\\\\nv_p\\rb{B\\rb{b^2 + bb' + b'^2}} & \\ge \\min\\cb{v_p\\rb{B} + 2v_p\\rb{b}, v_p\\rb{B} + v_p\\rb{b} + v_p\\rb{b'}, v_p\\rb{B} + 2v_p\\rb{b'}} \\ge 6v,\n\\end{align*}\nso $ v_p\\rb{\\lambda} \\ge 2v - \\min\\cb{0, 5v, 6v} = 2v $ and $ v_p\\rb{\\mu} \\ge \\min\\cb{3v, 3v} = 3v $. Hence\n\\begin{align*}\nv_p\\rb{2A\\lambda\\mu + 3B\\lambda^2\\mu} & \\ge \\min\\cb{v_p\\rb{2} + v_p\\rb{A} + v_p\\rb{\\lambda} + v_p\\rb{\\mu}, v_p\\rb{3} + v_p\\rb{B} + 2v_p\\rb{\\lambda} + v_p\\rb{\\mu}} \\ge 5v, \\\\\nv_p\\rb{1 + A\\lambda^2 + B\\lambda^3} & = \\min\\cb{v_p\\rb{1}, v_p\\rb{A} + 2v_p\\rb{\\lambda}, v_p\\rb{B} + 3v_p\\rb{\\lambda}} = 0,\n\\end{align*}\nso $ v_p\\rb{a''} \\ge \\min\\cb{a, a', 5v} \\ge v $. Thus $ P + Q \\in E'\\rb{p^v} $ and $ v_p\\rb{a + a' - a''} \\ge 5v $.\n\\end{proof}\n\nNote that the second part of the lemma proves something stronger, that the $ x $ coordinates of three collinear points add to give a large $ p $-adic valuation. Now let $ R = \\cb{x \\in \\Q \\mid v_p\\rb{x} \\ge 0} $ be a unique factorisation domain such that $ \\ab{p^v} = \\cb{x \\in \\Q \\mid v_p\\rb{x} \\ge v} \\subseteq R $ is a principal ideal. This also induces a filtration of subgroups\n$$ R \\ge \\ab{p} \\ge \\ab{p^2} \\ge \\ab{p^3} \\ge \\dots \\cb{0}. $$\nThen $ v_p\\rb{a + a' - a''} \\ge 5v $ from the previous lemma can be rephrased as $ a + a' - a'' \\in \\ab{p^{5v}} $, or even better as $ \\ab{p^{5v}} + a + a' = \\ab{p^{5v}} + a'' $. The following lemma attempts to makes use of this fact.\n\n\\begin{lemma}\nThere is an injective group homomorphism\n$$ \\phi : E\\rb{p^v} / E\\rb{p^{5v}} \\to \\ab{p^v} / \\ab{p^{5v}}, \\qquad \\phi\\rb{E\\rb{p^{5v}} + P} = \\begin{cases} \\ab{p^{5v}} + \\dfrac{a}{b} & P = \\rb{a, b} \\\\ \\ab{p^{5v}} & P = \\mathcal{O} \\end{cases}. $$\n\\end{lemma}\n\n\\begin{proof}\nLet $ \\psi : E\\rb{p^v} \\to \\ab{p^v} / \\ab{p^{5v}} $ be defined by\n$$ \\psi\\rb{P} = \\begin{cases} \\ab{p^{5v}} + \\dfrac{a}{b} & P = \\rb{a, b} \\\\ \\ab{p^{5v}} & P = \\mathcal{O} \\end{cases}, $$\nand let $ P, Q \\in E\\rb{p^v} $ be points. If $ P = \\mathcal{O} $, then\n$$ \\psi\\rb{P} + \\psi\\rb{Q} = \\ab{p^{5v}} + \\ab{p^{5v}} + \\dfrac{a'}{b'} = \\ab{p^{5v}} + \\dfrac{a'}{b'} = \\psi\\rb{Q} = \\psi\\rb{P + Q}, $$\nor similar for $ Q = \\mathcal{O} $. If $ P = \\rb{a, b} $ and $ Q = \\rb{a, -b} $, then\n$$ \\psi\\rb{P} + \\psi\\rb{Q} = \\ab{p^{5v}} + \\dfrac{a}{b} + \\ab{p^{5v}} - \\dfrac{a}{b} = \\ab{p^{5v}} = \\psi\\rb{\\mathcal{O}} = \\psi\\rb{P + Q}. $$\nOtherwise $ P = \\rb{a, b} $ and $ Q = \\rb{a', b'} $ such that $ P + Q = \\rb{a'', b''} $, then\n$$ \\psi\\rb{P} + \\psi\\rb{Q} = \\ab{p^{5v}} + \\dfrac{a}{b} + \\ab{p^{5v}} + \\dfrac{a'}{b'} = \\ab{p^{5v}} + \\dfrac{a}{b} + \\dfrac{a'}{b'} = \\ab{p^{5v}} + \\dfrac{a''}{b''} = \\psi\\rb{P + Q}. $$\nHence $ \\psi $ is a group homomorphism. Now $ \\mathcal{O} \\in Ker\\rb{\\psi} $, and $ \\rb{a, b} \\in Ker\\rb{\\psi} $ iff $ v_p\\rb{a / b} \\ge 5v $. This holds iff $ \\rb{a / b, 1 / b} \\in E'\\rb{p^{5v}} $ and $ \\rb{a, b} \\in E\\rb{p^{5v}} $, so $ Ker\\rb{\\psi} = E\\rb{p^{5v}} $. Thus the first isomorphism theorem gives a natural injective group homomorphism\n$$ \\phi : \\dfrac{E\\rb{p^v}}{E\\rb{p^{5v}}} \\to Im\\rb{\\psi} \\subseteq \\dfrac{\\ab{p^v}}{\\ab{p^{5v}}}. $$\n\\end{proof}\n\nNow the subgroup $ E\\rb{p} $ can be proven to be \\emph{torsion-free} with a proof by contradiction in the following lemma, from which the first part of the Nagell-Lutz theorem can be deduced.\n\n\\begin{lemma}\n$ E\\rb{p} $ has no non-zero torsion points.\n\\end{lemma}\n\n\\begin{proof}\nLet $ P = \\rb{a, b} \\in E\\rb{\\Q} $ be an $ n $-torsion point. Suppose for a contradiction that $ P \\in E\\rb{p} $, so $ v_p\\rb{a} = -2v $ for some $ v \\in \\Z_{> 0} $ and $ v_p\\rb{a / b} = v $. Then\n$$ \\ab{p^{5v}} = \\phi\\rb{E\\rb{p^{5v}}} = \\phi\\rb{E\\rb{p^{5v}} + nP} = n\\phi\\rb{E\\rb{p^{5v}} + P} = n\\rb{\\ab{p^{5v}} + \\dfrac{a}{b}} = \\ab{p^{5v}} + n\\dfrac{a}{b}, $$\nso $ n\\rb{a / b} \\in \\ab{p^{5v}} $. Assume that $ p \\nmid n $, so $ a / b \\in \\ab{p^{5v}} $ and $ v = v_p\\rb{a / b} \\ge 5v $, which is a contradiction. Hence $ P \\notin E\\rb{p} $. Otherwise assume that $ p \\mid n $, then $ n = mp $ for some $ m \\in \\Z_{> 0} $. Now let $ Q = mP = \\rb{a', b'} \\in E\\rb{\\Q} $ be a $ p $-torsion point. Since $ P \\in E\\rb{p} $, it holds that $ Q \\in E\\rb{p} $, so $ v_p\\rb{a'} = -2v' $ for some $ v' \\in \\Z_{> 0} $ and $ v_p\\rb{a' / b'} = v' $. Then\n$$ \\ab{p^{5v'}} = \\phi\\rb{E\\rb{p^{5v'}}} = \\phi\\rb{E\\rb{p^{5v'}} + pQ} = p\\phi\\rb{E\\rb{p^{5v'}} + Q} = p\\rb{\\ab{p^{5v'}} + \\dfrac{a'}{b'}} = \\ab{p^{5v}} + p\\dfrac{a'}{b'}, $$\nso $ p\\rb{a' / b'} \\in \\ab{p^{5v'}} $. Then $ 5v' \\le v_p\\rb{p\\rb{a' / b'}} = v_p\\rb{p} + v_p\\rb{a' / b'} = 1 + v' $, which is again a contradiction. Hence $ Q \\notin E\\rb{p} $ and $ P \\notin E\\rb{p} $. Thus $ E\\rb{p} $ has no non-zero torsion points.\n\\end{proof}\n\nBoth parts of the Nagell-Lutz theorem can finally be proven here, the second part a corollary of the first.\n\n\\begin{proof}[Proof of Theorem \\ref{thm:nagelllutz}]\nLet $ P = \\rb{a, b} \\in E\\rb{\\Q} $ be a non-zero $ n $-torsion point.\n\\begin{enumerate}\n\\item Since $ P \\notin E\\rb{p} $ for any prime $ p \\in \\Z_{> 0} $, it holds that $ v_p\\rb{a} \\ge 0 $ and $ v_p\\rb{b} \\ge 0 $. Thus $ a, b \\in \\Z $.\n\\item Assume that $ b \\ne 0 $ and let $ 2P = \\rb{a', b'} \\in E\\rb{\\Q} $. By the duplication formula,\n$$ a' = \\dfrac{a^4 - 2Aa^2 - 8Ba + A^2}{4b^2}. $$\nSince $ P $ and $ 2P $ are torsion points, it holds that $ a, b, a', b' \\in \\Z $, so $ b^2 \\mid a^4 - 2Aa^2 - 8Ba + A^2 $. Thus\n$$ b^2 \\mid \\rb{a^4 - 2Aa^2 - 8Ba + A^2}\\rb{3a^2 + 4A} - \\rb{a^3 + Aa + B}\\rb{3a^3 - 5Aa - 27B} = 4A^3 + 27B^2 = \\Delta'_E. $$\n\\end{enumerate}\n\\end{proof}\n\n\\pagebreak\n\n\\subsection{Torsion computation}\n\nAn application of the Nagell-Lutz theorem is as follows. Assuming the fundamental theorem of finite abelian groups,\n$$ E\\rb{\\Q} \\cong \\Z^r \\oplus E\\rb{\\Q}_{tors}, \\qquad r \\in \\Z_{\\ge 0}, $$\nthe Nagell-Lutz theorem can be used to compute the torsion subgroup $ E\\rb{\\Q}_{tors} $, since there are only finitely many torsion points $ \\rb{a, b} \\in E\\rb{\\Q} $ such that $ b^2 \\mid \\Delta'_E $. The following example illustrates the full computation of the torsion subgroup of an elliptic curve.\n\n\\begin{example}\nLet $ E : y^2 = x^3 + 4 $ be an elliptic curve over $ \\Q $ and $ P = \\rb{a, b} \\in E\\rb{\\Q} $ be a torsion point. Then either $ b = 0 $ or $ b^2 \\mid 4\\rb{0}^3 + 27\\rb{4}^2 = 3\\rb{12}^2 $, so $ b \\in \\cb{0, \\pm 1, \\pm 2, \\pm 3, \\pm 4, \\pm 6, \\pm 12} $, of which only $ P_1 = \\rb{0, 2} \\in E\\rb{\\Q} $ and $ P_2 = \\rb{0, -2} \\in E\\rb{\\Q} $. Then\n$$ 2P_1 = \\rb{\\dfrac{0}{4\\rb{4}}, \\dfrac{2^2 - 3\\rb{4}}{2\\rb{2}}} = \\rb{0, -2} = P_2, $$\nso $ ord\\rb{P_1} = ord\\rb{P_2} = 3 $. Thus the torsion subgroup is $ E\\rb{\\Q}_{tors} = \\cb{\\mathcal{O}, P_1, P_2} \\cong \\Z_3 $.\n\\end{example}\n\nThe following algorithm summarises the process and code in the appendix.\n\n\\begin{algorithm}[Computation of the torsion subgroup]\nInput: an elliptic curve $ E $ over $ \\Q $. Output: $ E\\rb{\\Q}_{tors} $.\n\\begin{enumerate}\n\\item Calculate $ \\Delta'_E $ and get all non-negative $ b $ coordinates such that $ b^2 \\mid \\Delta'_E $.\n\\item Get all $ a $ coordinates for each non-negative $ b $ coordinate such that $ b^2 = a^3 + Aa + B $.\n\\item Add points $ \\rb{a, b} $ with itself repeatedly and stop at $ \\mathcal{O} $ or non-integer coordinates.\n\\item Negate each point $ \\rb{a, b} $ to $ \\rb{a, -b} $ and do the same.\n\\item Insert $ \\mathcal{O} $ into the list of all points that add to $ \\mathcal{O} $.\n\\end{enumerate}\n\\end{algorithm}\n\nThe torsion subgroups of the following examples of elliptic curves given by the Weierstrass equations $ y^2 = x^3 - px $ for $ p \\in \\Z_{> 0} $ can be computed similarly. This information will be used in a later subsection.\n\n\\begin{example}\nThe elliptic curves $ E : y^2 = x^3 - x $ has torsion subgroup $ E\\rb{\\Q}_{tors} = \\cb{\\mathcal{O}, \\rb{0, 0}, \\rb{1, 0}, \\rb{-1, 0}} \\cong \\Z_2^2 $, while the elliptic curves $ E : y^2 = x^3 - 5x $, $ E : y^2 = x^3 - 17x $, $ E : y^2 = x^3 - 226x $ all have torsion subgroup $ E\\rb{\\Q}_{tors} = \\cb{\\mathcal{O}, \\rb{0, 0}} \\cong \\Z_2 $.\n\\end{example}\n\nThe converse to the Nagell-Lutz theorem does not generally hold. It cannot be used to prove that a certain point is a torsion point, but it can be used to show the contrapositive, that a point is not a torsion point, by duplicating it until its coordinates are not integers. The following example illustrates this.\n\n\\begin{example}\nLet $ E : y^2 = x^3 - 4 $ be an elliptic curve over $ \\Q $ with torsion subgroup $ E\\rb{\\Q}_{tors} = \\cb{\\mathcal{O}} \\cong \\Z_1 $. Now let $ P = \\rb{2, 2} \\in E\\rb{\\Q} $ be a point. Then\n$$ 2P = \\rb{5, -11}, \\qquad 4P = \\rb{\\dfrac{785}{484}, -\\dfrac{5497}{10648}}. $$\nThus $ ord\\rb{P} $ is infinite.\n\\end{example}\n\nThese are several examples of different torsion subgroups. In fact, there are even elliptic curves with as large as $ 12 $-torsion elements, but there are strangely none with $ 11 $-torsion elements. The following difficult theorem was proven to be an exhaustive list of all possible torsion subgroups of all elliptic curves.\n\n\\begin{theorem}[Mazur]\n$ E\\rb{\\Q} $ is isomorphic to one of\n$$ \\Z_n, \\qquad n \\in \\cb{1, \\dots, 10, 12}, $$\n$$ \\Z_2 \\times \\Z_{2n}, \\qquad n \\in \\cb{1, \\dots, 4}. $$\n\\end{theorem}\n\n\\begin{proof}\nOmitted, see \\cite{mazur}.\n\\end{proof}\n\nAs such, the torsion subgroup of an elliptic curve $ E\\rb{\\Q} $ can be computed in a finite number of steps. However, computations may still be intensive if $ \\Delta'_E $ has many squared factors, as the computation involves solving a cubic equation. The next section provides an alternative method for this.\n\n\\pagebreak\n\n\\subsection{Reduction modulo prime}\n\nAnother method of computing the torsion subgroup is to reduce the elliptic curve over rationals into one over a finite field, by applying isomorphisms that simplify the Weierstrass equation, then applying a particular group homomorphism. The assumption of integer coefficients in a previous subsection makes the Weierstrass equation \\emph{integral}, but a further reduction can be done as follows.\n\n\\begin{definition}[Minimal]\nA Weierstrass equation is \\textbf{minimal} iff it is integral and $ g \\in \\cb{-1, 1} $ if $ g^4 \\mid A $ and $ g^6 \\mid B $.\n\\end{definition}\n\nA minimal Weierstrass equation is unique up to sign. The above definition reflects the minimality of the integer coefficients after $ j $-invariant affine transformations, which is illustrated in the following example.\n\n\\begin{example}\nLet $ E : y^2 = x^3 + n^4x + n^6 $ be an elliptic curve over $ \\Q $ for some $ n \\in \\Q $. Since there is a $ j $-invariant affine transformation $ \\rb{x, y} \\mapsto \\rb{n^2x, n^3y} $, there is an isomorphism from $ E $ to the curve given by the Weierstrass equation $ y^2 = x^3 + x + 1 $, which is integral and minimal.\n\\end{example}\n\nMinimal Weierstrass equations can then be treated as if their coefficients are modulo a prime, which is stated formally as a map in the following definition.\n\n\\begin{definition}[Reduction map]\nThe \\textbf{reduction modulo $ p $ map} $ r_p : E\\rb{\\Q} \\to E_p\\rb{\\F_p} $ for some prime $ p \\in \\Z_{> 0} $ is defined by\n$$ E_p : y^2 = x^3 + \\tilde{A}x + \\tilde{B}, \\qquad r_p\\rb{P} = \\begin{cases} \\rb{\\tilde{a}, \\tilde{b}} & P = \\rb{a, b} \\\\ \\mathcal{O} & P = \\mathcal{O} \\end{cases}, $$\nwhere $ \\tilde{\\cdot} : \\Z \\to \\F_p $ denotes modulo $ p $.\n\\end{definition}\n\nThere is a minor hiccup with this definition, since $ E_p $ might not even define a smooth Weierstrass curve. However, since $ 0 \\ne \\Delta_E = p_1 \\dots p_n $ for some primes $ p_i \\in \\Z_{> 0} $ and $ \\Delta_{E_p} = 0 $ only if any $ p_i \\mid p $, this issue can be easily fixed by considering only the primes that are not $ p_i $, which is given in the following definition.\n\n\\begin{definition}[Good reduction]\nA prime $ p \\in \\Z_{> 0} $ is of \\textbf{good reduction} iff $ p \\nmid \\Delta_E $.\n\\end{definition}\n\nHence $ r_p $ has a well-defined codomain for infinitely many primes of good reduction, while those of bad reduction will not be considered. Additionally since the discriminant has a coefficient of $ 16 $, the prime $ 2 $ will always be considered one of bad reduction. Now $ r_p $ is also well-defined, which is immediate considering the following lemma.\n\n\\begin{lemma}\n\\label{lem:normalise}\nLet $ P = \\sb{a, b, c} \\in E\\rb{\\Q} $ be a point. Then $ P = \\sb{a', b', c'} $ for some $ a', b', c' \\in \\Z $ such that $ \\gcd\\rb{a', b', c'} = 1 $.\n\\end{lemma}\n\n\\begin{proof}\nIf $ c = 0 $, then $ P = \\mathcal{O} $, so $ \\gcd\\rb{0, 1, 0} = 1 $. Otherwise $ c \\ne 0 $, then $ P = \\rb{a / c, b / c} $. Then $ a / c = q / d^2 $ and $ b / c = r / d^3 $ for some $ q, r \\in \\Z $ and some $ d \\in \\Z_{> 0} $ such that $ \\gcd\\rb{q, d} = \\gcd\\rb{r, d} = 1 $. Thus $ P = \\rb{q / d^2, r / d^3} = \\sb{qd, r, d^3} $ is such that $ \\gcd\\rb{qd, r, d^3} = 1 $.\n\\end{proof}\n\nThis integral and minimal condition will also be defined as follows.\n\n\\begin{definition}[Normalised]\nA point $ P \\in E\\rb{\\Q} $ has \\textbf{normalised} coordinates iff it satisfies Lemma \\ref{lem:normalise}.\n\\end{definition}\n\nWith this representation, there must be one of $ a', b', c' $ coprime to $ p $ for any prime $ p \\in \\Z_{> 0} $ of good reduction, so $ r_p\\rb{P} = \\sb{\\tilde{a'}, \\tilde{b'}, \\tilde{c'}} \\in E_p\\rb{\\F_p} $ is well-defined. The normalised coordinates of any point is unique up to sign, which is illustrated with the following example.\n\n\\begin{example}\nLet $ P = \\rb{2 / 5, -1 / 3} \\in E\\rb{\\Q} $ be a point. Then\n$$ \\rb{\\dfrac{2}{5}, -\\dfrac{1}{3}} = \\sb{\\dfrac{2}{5}, -\\dfrac{1}{3}, 1} = \\sb{6, -5, 15}, \\sb{-6, 5, -15} $$\nare its normalised coordinates.\n\\end{example}\n\n\\pagebreak\n\nLet $ p \\in \\Z_{> 0} $ be a prime of good reduction. Then the following proposition characterises $ r_p $.\n\n\\begin{proposition}\n$ r_p : E\\rb{\\Q} \\to E_p\\rb{\\F_p} $ is a group homomorphism such that $ Ker\\rb{r_p} = E\\rb{p} $.\n\\end{proposition}\n\n\\begin{proof}\nLet $ P, Q \\in E\\rb{\\Q} $ be points with normalised coordinates and\n$$ L : l\\rb{X, Y, Z} = kX + mY + nZ = 0 $$\nbe a line joining $ P $ and $ Q $ with coefficients in $ \\Q $ such that $ P, Q, -\\rb{P + Q} \\in E\\rb{\\Q} \\cap L $. Then normalising $ \\sb{l, m, n} $ similarly gives $ \\sb{l', m', n'} $ for some $ l', m', n '\\in \\Z $ such that $ \\gcd\\rb{l, m, n} = 1 $. Hence the line\n$$ L_p : l_p\\rb{X, Y, Z} = \\tilde{l}X + \\tilde{m}Y + \\tilde{n}Z = 0 $$\nwith coefficients in $ \\F_p $ is well-defined. Now let $ P = \\sb{a, b, c} $. Then\n$$ la + mb + nc = 0 \\qquad \\implies \\qquad \\tilde{l}\\tilde{a} + \\tilde{m}\\tilde{b} + \\tilde{n}\\tilde{c} = 0, $$\nso $ r_p\\rb{P} = \\rb{\\tilde{a}, \\tilde{b}, \\tilde{c}} \\in E_p\\rb{\\F_p} \\cap L_p $. Similarly $ r_p\\rb{Q} \\in E_p\\rb{\\F_p} \\cap L_p $. Since $ r_p\\rb{-\\mathcal{O}} = r_p\\rb{\\mathcal{O}} = -r_p\\rb{\\mathcal{O}} $ and\n$$ r_p\\rb{-\\rb{a, b}} = r_p\\rb{\\rb{a, -b}} = \\rb{\\tilde{a}, \\tilde{-b}} = \\rb{\\tilde{a}, -\\tilde{b}} = -\\rb{\\tilde{a}, \\tilde{b}} = -r_p\\rb{\\rb{a, b}} $$\nfor any point $ \\rb{a, b} \\in E\\rb{\\Q} $, similarly $ -r_p\\rb{P + Q} = r_p\\rb{-\\rb{P + Q}} \\in E_p\\rb{\\F_p} \\cap L_p $. Since $ \\gcd\\rb{e_p, l_p} = 1 $ where $ e_p\\rb{x, y} $ is the Weierstrass equation of $ E_p $, B\\'ezout's theorem gives that $ L_p $ intersects $ E_p\\rb{\\F_p} $ at three points up to multiplicity, so\n$$ E_p\\rb{\\F_p} \\cap L_p = \\cb{r_p\\rb{P}, r_p\\rb{Q}, -r_p\\rb{P + Q}}. $$\nHence $ r_p\\rb{P} + r_p\\rb{Q} = r_p\\rb{P + Q} $. Now let $ R = \\rb{a, b} \\in E\\rb{\\Q} $ be a point. Then $ a = q / d^2 $ and $ b = r / d^3 $ for some $ q, r \\in \\Z $ and some $ d \\in \\Z_{> 0} $ such that $ \\gcd\\rb{q, d} = \\gcd\\rb{r, d} = 1 $. Since $ R = \\sb{qd, r, d^3} $ has normalised coordinates, it holds that $ r_p\\rb{R} = \\sb{\\tilde{q}\\tilde{d}, \\tilde{r}, \\tilde{d}^3} \\in E_p\\rb{\\F_p} $. Then $ R \\in Ker\\rb{r_p} $ iff $ \\tilde{d}^3 = 0 $, or $ p \\mid d $. This holds iff $ v_p\\rb{a} \\le -2 $ and $ v_p\\rb{b} \\le -3 $, or $ R \\in E\\rb{p} $. Thus $ Ker\\rb{r_p} = E\\rb{p} $.\n\\end{proof}\n\nRestricting $ r_p $ into the torsion subgroup of its domain gives it a stronger property as follows.\n\n\\begin{theorem}[Reduction]\n$ E\\rb{\\Q}_{tors} \\cong G $ for some $ G \\le E_p\\rb{\\F_p} $.\n\\end{theorem}\n\n\\begin{proof}\nSince $ Ker\\rb{r_p} = E\\rb{p} $, it holds that $ v_p\\rb{a} \\le -2 $ and $ v_p\\rb{b} \\le -3 $ for any point $ P = \\rb{a, b} \\in Ker\\rb{r_p} $, so $ a, b \\notin \\Z $. Then the Nagell-Lutz theorem gives that $ ord\\rb{P} $ is infinite, so $ P \\notin E\\rb{\\Q}_{tors} $. Now let $ r_p' = \\val{r_p}_{E\\rb{\\Q}_{tors}} $ and $ G = Im\\rb{r_p'} $, so $ Ker\\rb{r_p'} = Ker\\rb{r_p} \\cap E\\rb{\\Q}_{tors} = \\cb{\\mathcal{O}} $. Thus the first isomorphism theorem gives $ G \\cong E\\rb{\\Q}_{tors} / Ker\\rb{r_p'} \\cong E\\rb{\\Q}_{tors} $.\n\\end{proof}\n\nLagrange's theorem then gives $ \\abs{E\\rb{\\Q}_{tors}} \\mid \\abs{E_p\\rb{\\F_p}} $, which enforces a restriction of the possible torsion subgroups. The following reignites a prior example, this time with the reduction theorem.\n\n\\begin{example}\nLet $ E : y^2 = x^3 + 4 $ be an elliptic curve over $ \\Q $. Then $ \\Delta_E = -16\\rb{4\\rb{0}^3 + 27\\rb{4}^2} = -\\rb{2}^8\\rb{3}^3 $, so let $ p = 5 $ be a prime of good reduction. Then the previous section gives $ \\abs{E_5\\rb{\\F_5}} = 6 $. Since $ \\abs{E\\rb{\\Q}_{tors}} \\mid \\abs{E_5\\rb{\\F_5}} $, it holds that $ \\abs{E\\rb{\\Q}_{tors}} \\in \\cb{1, 2, 3, 6} $. Since $ ord\\rb{\\rb{0, 2}} = 3 $ and there are no points $ P \\in E\\rb{\\Q} $ such that $ ord\\rb{P} = 2 $, it holds that $ E\\rb{\\Q}_{tors} = \\cb{\\mathcal{O}, \\rb{0, 2}, \\rb{0, -2}} \\cong \\Z_3 $.\n\\end{example}\n\nWhile this might not seem much of a timesave, the following example begs to differ.\n\n\\begin{example}\nLet $ E : y^2 = x^3 + 1680 $ be an elliptic curve over $ \\Q $. Then $ \\Delta'_E = 4\\rb{0}^3 + 27\\rb{1680}^2 = 3\\rb{5040}^2 = \\rb{2}^8\\rb{3}^5\\rb{5}^2\\rb{7}^2 $ and $ \\Delta_E = -\\rb{2}^{12}\\rb{3}^5\\rb{5}^2\\rb{7}^2 $, so $ p \\ge 11 $ are primes of good reduction. Now $ 5040 $ is a \\emph{colossally abundant number} with exactly $ 120 $ positive and negative divisors, so more than $ 120 $ values of $ b $ such that $ b^2 \\mid \\Delta'_E $ needs to be checked. Instead the previous section computes $ \\abs{E_{13}\\rb{\\F_{13}}} = 9 $ and $ \\abs{E_{19}\\rb{\\F_{19}}} = 28 $. Since $ \\abs{E\\rb{\\Q}_{tors}} \\mid \\abs{E_{13}\\rb{\\F_{13}}} $ and $ \\abs{E\\rb{\\Q}_{tors}} \\mid \\abs{E_{19}\\rb{\\F_{19}}} $, and $ \\gcd\\rb{9, 28} = 1 $, it holds that $ \\abs{E\\rb{\\Q}_{tors}} = 1 $. Thus $ E\\rb{\\Q}_{tors} = \\cb{\\mathcal{O}} $.\n\\end{example}\n\nCounting points over finite fields can generally be done very efficiently, so the reduction theorem allows for an immediate answer. In any case, computation of the torsion subgroup is relatively straightforward.\n\n\\pagebreak\n\n\\subsection{Mordell's theorem: descent}\n\nThe following theorem is one of the most fundamental theorems of elliptic curves over the rationals, as stated in a previous subsection.\n\n\\begin{theorem}[Mordell]\n\\label{thm:mordell}\nThe \\emph{Mordell-Weil group} $ E\\rb{\\Q} $ is finitely generated.\n\\end{theorem}\n\n\\begin{remark}\nThis is a special case of the \\emph{Mordell-Weil theorem}, which states that $ E\\rb{K} $ is finitely generated over any number field $ K $.\n\\end{remark}\n\nProof of Mordell's theorem will be split into two distinct steps. The first step of the proof develops some theory of a certain function that describes the size of points. The second step of the proof is a weak variant of the theorem stating that the index of a subgroup is finite. These two steps are then used in a variant of \\emph{Fermat's infinite descent}, which can be stated in full generalisation for arbitrary abelian groups as follows.\n\n\\begin{theorem}[Descent]\nLet $ G $ be an abelian group such that the index $ \\sb{G : 2G} $ is finite, and let $ h : G \\to \\R_{\\ge 0} $ be such that:\n\\begin{itemize}\n\\item the set $ \\cb{P \\in G \\mid h\\rb{P} \\le C_1} $ is finite for any $ C_1 \\in \\R_{\\ge 0} $,\n\\item for any $ Q \\in G $, there is a constant $ C_2 \\in \\R_{\\ge 0} $ such that $ h\\rb{P + Q} \\le 2h\\rb{P} + C_2 $ for any $ P \\in G $, and\n\\item there is a constant $ C_3 \\in \\R_{\\ge 0} $ such that $ h\\rb{2P} \\ge 4h\\rb{P} - C_3 $ for any $ P \\in G $.\n\\end{itemize}\nThen $ G $ is finitely generated.\n\\end{theorem}\n\n\\begin{proof}\nLet $ Q_1, \\dots, Q_n \\in G $ be representatives such that $ 2G + Q_i \\in G / 2G $ are distinct cosets. For any $ P \\in G $, the upper bound gives each $ h\\rb{P - Q_i} \\le 2h\\rb{P} + C_i $ for some $ C_i \\in \\R_{\\ge 0} $, so\n$$ h\\rb{P - Q_i} \\le 2h\\rb{P} + C, \\qquad i \\in \\cb{1, \\dots, n}, \\qquad C = \\max\\cb{C_i} \\in \\R_{\\ge 0}. $$\nFor any $ P \\in G $, the lower bound also gives\n$$ h\\rb{2P} \\ge 4h\\rb{P} - C', \\qquad C' \\in \\R_{\\ge 0}. $$\nThen there is a finite set\n$$ S = \\cb{P \\in G \\mid h\\rb{P} \\le C + C'}. $$\nNow let $ P \\in G $. Then $ 2G + P = 2G + Q_{i_0} $ for some $ i_0 \\in \\cb{1, \\dots, n} $, so $ P = 2P_0 + Q_{i_0} $ for some $ P_0 \\in G $. By induction, for any $ j \\in \\Z_{> 0} $, there is some $ i_j \\in \\cb{1, \\dots, n} $ such that $ 2G + P_{j - 1} = 2G + Q_{i_j} $, so\n$$ P_{j - 1} = 2P_j + Q_{i_j}, \\qquad P = 2^{j + 1}P_j + \\sum_{k = 0}^j 2^kQ_{i_k}, \\qquad P_j \\in G. $$\nNow for any $ j \\in \\Z_{> 0} $,\n$$ 4h\\rb{P_j} \\le h\\rb{2P_j} + C' = h\\rb{P_{j - 1} - Q_{i_j}} + C' \\le 2h\\rb{P_{j - 1}} + \\rb{C + C'}, $$\nso that\n$$ h\\rb{P_j} \\le \\tfrac{1}{2}h\\rb{P_{j - 1}} + \\tfrac{1}{4}\\rb{C + C'} = \\dfrac{3}{4}h\\rb{P_{j - 1}} - \\tfrac{1}{4}\\rb{h\\rb{P_{j - 1}} - \\rb{C + C'}}. $$\nIf $ h\\rb{P_{j - 1}} > C + C' $ for some $ j \\in \\Z_{> 0} $, then $ h\\rb{P_j} < \\dfrac{3}{4}h\\rb{P_{j - 1}} $, so $ h\\rb{P_m} \\le C + C' $ for some $ m \\in \\Z_{> 0} $ such that $ m \\ge j $ and $ P_m \\in S $. Otherwise $ h\\rb{P_{j - 1}} \\le C + C' $ for all $ j \\in \\Z_{> 0} $, so let $ m = 1 $ such that $ P_m \\in S $ as well. Hence\n$$ P = 2^{m + 1}P_m + \\sum_{k = 0}^m 2^kQ_{i_k} = \\sum_{S_i \\in S} n_iS_i + \\sum_{i = 1}^n m_iQ_i, \\qquad n_i, m_i \\in \\Z. $$\nThus $ G $ is finitely generated by $ S \\cup \\cb{Q_i} $.\n\\end{proof}\n\nMordell's theorem is simply an application of the general descent procedure.\n\n\\begin{proof}[Proof of Theorem \\ref{thm:mordell}]\nThe three properties of the function $ h $ will be given in Propositions \\ref{prop:finiteness}, \\ref{prop:upperbound}, \\ref{prop:lowerbound} of the next section. The weak version of the theorem will be given in Theorem \\ref{thm:weakmordell} of the section after the next. Applying descent to $ G = E\\rb{\\Q} $ with $ h $ gives that $ E\\rb{\\Q} $ is finitely generated.\n\\end{proof}\n\nThe next subsections will be devoted to proving these claims.\n\n\\pagebreak\n\n\\subsection{Mordell's theorem: heights}\n\nThe function $ h $ can be defined as follows.\n\n\\begin{definition}[Height]\nThe \\textbf{height} of a point $ P \\in E\\rb{\\Q} $ is a function $ h\\rb{P} : E\\rb{\\Q} \\to \\R_{\\ge 0} $ defined by $ h\\rb{P} = \\log_2\\rb{H\\rb{P}} $, where\n$$ H\\rb{P} = \\begin{dcases} \\max\\cb{\\abs{p}, \\abs{q}} & P = \\rb{\\dfrac{p}{q}, y}, \\ \\gcd\\rb{p, q} = 1 \\\\ 1 & P = \\mathcal{O} \\end{dcases}. $$\n\\end{definition}\n\n\\begin{remark}\nThe above definition for heights is chosen due to its simplicity, and is not the \\emph{canonical height} in the general literature. The theory of height functions will not be discussed here.\n\\end{remark}\n\nThe three intended properties of height function will then be proven, the first of which states that there are a finite number of points less than a given height. This property is trivial and stated as follows.\n\n\\begin{proposition}\n\\label{prop:finiteness}\nThe set $ S = \\cb{P \\in E\\rb{\\Q} \\mid h\\rb{P} \\le C_1} $ is finite for any $ C_1 \\in \\R_{\\ge 0} $.\n\\end{proposition}\n\n\\begin{proof}\nLet $ C_1 \\in \\R_{\\ge 0} $ and $ P \\in E\\rb{\\Q} $ be a point. If $ P = \\mathcal{O} $, then $ P \\in S $. Otherwise $ P = \\rb{p / q, y} $, then $ \\max\\cb{\\abs{p}, \\abs{q}} \\le 2^{C_1} $, so $ -2^{C_1} \\le p, q \\le 2^{C_1} $. Thus $ \\abs{S} \\le \\rb{2^{C_1 + 1} + 1}^2 + 1 $ is finite.\n\\end{proof}\n\nThe second property provides an upper bound for the height of added points. This is relatively easy and is stated in the following proposition.\n\n\\begin{proposition}\n\\label{prop:upperbound}\nLet $ Q \\in E\\rb{\\Q} $. Then there is a constant $ C_2 \\in \\R_{\\ge 0} $ such that $ h\\rb{P + Q} \\le 2h\\rb{P} + C_2 $ for any $ P \\in E\\rb{\\Q} $.\n\\end{proposition}\n\n\\begin{proof}\nIf $ P = \\mathcal{O} $ or $ Q = \\mathcal{O} $ or $ P + Q = \\mathcal{O} $, let $ C_2 = 2h\\rb{Q} $ such that $ h\\rb{P + Q} \\le 2h\\rb{P} + 2h\\rb{Q} $. Otherwise $ P = \\rb{a, b} $ and $ Q = \\rb{a', b'} $ for $ a \\ne a' $ or $ a = a' $ and $ b = b' \\ne 0 $. Assume that $ a = a' $ and $ b = b' \\ne 0 $, then let $ C_2 = h\\rb{2Q} $ such that $ h\\rb{P + Q} = h\\rb{2Q} \\le 2h\\rb{P} + h\\rb{2Q} $. Assume otherwise that $ a \\ne a' $, and let $ C_2 = \\log_2\\rb{\\max\\cb{K_3, K_2}} $, where\n$$ K_1 = \\sqrt{1 + \\abs{A} + \\abs{B}}, \\qquad K_2 = 1 + \\abs{a'}, \\qquad K_3 = \\rb{\\abs{A} + \\abs{a'}}K_2 + 2\\rb{\\abs{B} + \\abs{b'}K_1}. $$\nThen $ a = p / d^2 $ and $ b = q / d^3 $ for some $ p, q \\in \\Z $ and some $ d \\in \\Z_{> 0} $ such that $ \\gcd\\rb{p, d} = \\gcd\\rb{q, d} = 1 $, and $ q^2 = p^3 + Apd^4 + Bd^6 $. Since $ H\\rb{P} = \\max\\cb{\\abs{p}, \\abs{d}^2} $, it holds that $ \\abs{p}, \\abs{d}^2 \\le H\\rb{P} $, so $ \\abs{d} \\le \\sqrt{H\\rb{P}} $ and\n$$ \\abs{q}\\abs{d} = \\abs{\\sqrt{p^3 + Apd^4 + Bd^6}}\\abs{d} \\le \\sqrt{\\abs{p}^3\\abs{d}^2 + \\abs{A}\\abs{p}\\abs{d}^6 + \\abs{B}\\abs{d}^8} \\le K_1H\\rb{P}^2. $$\nNow let $ P + Q = \\rb{a'', b''} $. By the addition formula,\n$$ a'' = \\dfrac{\\rb{A + aa'}\\rb{a + a'} + 2\\rb{B - bb'}}{\\rb{a - a'}^2} = \\dfrac{\\rb{Ad^2 + a'p}\\rb{p + a'd^2} + 2\\rb{Bd^4 - b'qd}}{\\rb{p - a'd^2}^2}. $$\nThus\n\\begin{align*}\nh\\rb{P + Q}\n& \\le \\log_2\\rb{\\max\\cb{\\abs{\\rb{Ad^2 + a'p}\\rb{p + a'd^2} + 2\\rb{Bd^4 - b'qd}}, \\abs{\\rb{p - a'd^2}^2}}} \\\\\n& \\le \\log_2\\rb{\\max\\cb{\\rb{\\abs{A}\\abs{d}^2 + \\abs{a'}\\abs{p}}\\rb{\\abs{p} + \\abs{a'}\\abs{d}^2} + 2\\rb{\\abs{B}\\abs{d}^4 + \\abs{b'}\\abs{q}\\abs{d}}, \\rb{\\abs{p} + \\abs{a'}\\abs{d}^2}^2}} \\\\\n& \\le \\log_2\\rb{\\max\\cb{K_3H\\rb{P}^2, K_2H\\rb{P}^2}}\n= \\log_2\\rb{H\\rb{P}^2\\max\\cb{K_3, K_2}}\n= 2h\\rb{P} + C_2.\n\\end{align*}\n\\end{proof}\n\n\\pagebreak\n\nThe third property provides an lower bound for the height of doubled points. It is more difficult as it involves seemingly arbitrary identities, and is stated in the following proposition.\n\n\\begin{proposition}\n\\label{prop:lowerbound}\nThere is a constant $ C_3 \\in \\R_{\\ge 0} $ such that $ h\\rb{2P} \\ge 4h\\rb{P} - C_3 $ for any $ P \\in E\\rb{\\Q} $.\n\\end{proposition}\n\n\\begin{proof}\nIf $ P = \\mathcal{O} $, let $ C_3 = 0 $ such that $ h\\rb{2P} \\ge 4h\\rb{P} $. If $ P = \\rb{a, 0} $, let $ C_3 = 4h\\rb{P} $ such that $ h\\rb{2P} \\ge 0 $. Otherwise $ P = \\rb{a, b} $ for $ b \\ne 0 $. Let $ a = p / q $ for some $ p \\in \\Z $ and some $ q \\in \\Z^* $ such that $ \\gcd\\rb{p, q} = 1 $, and let\n\\begin{align*}\np' & = p^4 - 2Ap^2q^2 - 8Bpq^3 + A^2q^4, \\\\\nq' & = 4p^3q + 4Apq^3 + 4Bq^4, \\\\\n\\lambda & = 12p^2q + 16Aq^3, \\\\\n\\mu & = -3p^3 + 5Apq^2 + 27Bq^3, \\\\\n\\lambda' & = \\rb{16A^3 + 108B^2}p^3 - 4A^2Bp^2q + \\rb{12A^4 + 88AB^2}pq^2 + \\rb{12A^3B + 96B^3}q^3, \\\\\n\\mu' & = A^2Bp^3 + \\rb{5A^4 + 32AB^2}p^2q + \\rb{26A^3B + 192B^3}pq^2 - \\rb{3A^5 + 24A^2B^2}q^3, \\\\\nK_1 & = 4\\max\\cb{12, 16\\abs{A}}, \\\\\nK_2 & = 4\\max\\cb{3, 5\\abs{A}, 27\\abs{B}}, \\\\\nK_3 & = 4\\max\\cb{16\\abs{A}^3 + 108B^2, 4A^2\\abs{B}, 12A^4 + 88\\abs{A}B^2, 12\\abs{A}^3\\abs{B} + 96\\abs{B}^3}, \\\\\nK_4 & = 4\\max\\cb{A^2\\abs{B}, 5A^4 + 32\\abs{A}B^2, 26\\abs{A}^3\\abs{B} + 192\\abs{B}^3, 3\\abs{A}^5 + 24A^2B^2}.\n\\end{align*}\nThen it can be tediously verified that $ \\lambda p' + \\mu q' = 4\\Delta'_E q^7 $ and $ \\lambda' p' + \\mu' q' = 4\\Delta'_E p^7 $. Since $ \\abs{p}^2\\abs{q} $ and $ \\abs{p}\\abs{q}^2 $ are between $ \\abs{p}^3 $ and $ \\abs{q}^3 $, it holds that $ \\max\\cb{\\abs{p}^3, \\abs{p}^2\\abs{q}, \\abs{p}\\abs{q}^2, \\abs{q}^3} = \\max\\cb{\\abs{p}^3, \\abs{q}^3} $. Then it can also be verified that\n$$ \\abs{\\lambda} \\le K_1M, \\qquad \\abs{\\mu} \\le K_2M, \\qquad \\abs{\\lambda'} \\le K_3M, \\qquad \\abs{\\mu'} \\le K_4M, $$\nfor $ M = \\max\\cb{\\abs{p}^3, \\abs{q}^3} $, so let $ C_3 = \\log_2\\rb{2\\max\\cb{K_1, K_2, K_3, K_4}} $. Since\n\\begin{align*}\n4\\abs{\\Delta'_E}\\max\\cb{\\abs{p}^3, \\abs{q}^3}\\rb{\\max\\cb{\\abs{p}, \\abs{q}}}^4\n& = 4\\abs{\\Delta'_E}\\max\\cb{\\abs{q}^7, \\abs{p}^7}\n= \\max\\cb{\\abs{4\\Delta'_E q^7}, \\abs{4\\Delta'_E p^7}} \\\\\n& \\le \\max\\cb{\\abs{\\lambda}\\abs{p'} + \\abs{\\mu}\\abs{q'}, \\abs{\\lambda'}\\abs{p'} + \\abs{\\mu'}\\abs{q'}} \\\\\n& \\le 2\\max\\cb{\\abs{\\lambda}, \\abs{\\mu}, \\abs{\\lambda'}, \\abs{\\mu'}}\\max\\cb{\\abs{p'}, \\abs{q'}} \\\\\n& \\le 2M\\max\\cb{K_1, K_2, K_3, K_4}\\max\\cb{\\abs{p'}, \\abs{q'}},\n\\end{align*}\nit holds that\n$$ 4\\abs{\\Delta'_E}H\\rb{P}^4 = 4\\abs{\\Delta'_E}\\rb{\\max\\cb{\\abs{p}, \\abs{q}}}^4 \\le 2\\max\\cb{K_1, K_2, K_3, K_4}\\max\\cb{\\abs{p'}, \\abs{q'}}. $$\nNow let $ 2P = \\rb{a', b'} $. By the duplication formula,\n$$ a' = \\dfrac{a^4 - 2Aa^2 - 8Ba + A^2}{4b^2} = \\dfrac{a^4 - 2Aa^2 - 8Ba + A^2}{4a^3 + 4Aa + 4B} = \\dfrac{p'}{q'}. $$\nSince $ g = \\gcd\\rb{p', q'} \\mid \\gcd\\rb{4\\Delta'_E p^7, 4\\Delta'_E q^7} = 4\\Delta'_E $, it holds that $ 1 \\le \\abs{g} \\le 4\\abs{\\Delta'_E} $. Thus\n\\begin{align*}\nh\\rb{2P}\n& = \\log_2\\rb{\\max\\cb{\\abs{\\dfrac{p'}{g}}, \\abs{\\dfrac{q'}{g}}}}\n= \\log_2\\rb{\\dfrac{\\max\\cb{\\abs{p'}, \\abs{q'}}}{\\abs{g}}} \\\\\n& \\ge \\log_2\\rb{\\dfrac{\\max\\cb{\\abs{p'}, \\abs{q'}}}{4\\abs{\\Delta'_E}}}\n\\ge \\log_2\\rb{\\dfrac{H\\rb{P}^4}{2\\max\\cb{K_1, K_2, K_3, K_4}}}\n\\ge 4h\\rb{P} - C_3.\n\\end{align*}\n\\end{proof}\n\nThe properties of the height function $ h $ are now verified.\n\n\\pagebreak\n\n\\subsection{Mordell's theorem: weak Mordell}\n\nThe weak version of Mordell's theorem, restricted to $ \\Q $, states that the index of the normal subgroup $ 2E\\rb{\\Q} = \\cb{2P \\mid P \\in E\\rb{\\Q}} $ is finite.\n\n\\begin{theorem}[Weak Mordell]\n\\label{thm:weakmordell}\n$ \\abs{E\\rb{\\Q} : 2E\\rb{\\Q}} $ is finite.\n\\end{theorem}\n\nAs full proofs of the weak theorem, such as in VIII.1 of \\cite{gtm}, requires further prerequisites on algebraic number theory, particularly finiteness of the \\emph{ideal class group} of number fields, only an alternative proof is given, of which the special case of a rational $ 2 $-torsion point $ \\rb{a_0, 0} $ is assumed. Since there is a $ j $-invariant affine transformation $ \\rb{x, y} \\mapsto \\rb{x + a_0, y} $, there is an isomorphism from $ E $ to the curve given by the Weierstrass equation\n$$ y^2 = \\rb{x + a_0}^3 + A\\rb{x + a_0} + B \\qquad \\implies \\qquad y^2 = x^3 + 3a_0x^2 + \\rb{3a_0^2 + A}x. $$\nHence for this subsection and the next, assume without loss of generality that $ a_0 = 0 $ and\n$$ T = \\rb{a_0, 0} = \\rb{0, 0} \\in E : y^2 = x^3 + Ax^2 + Bx, \\qquad A, B \\in \\Z. $$\nThe modified discriminant and group law is then given in the following lemma.\n\n\\begin{lemma}\nThe following properties hold:\n\\begin{enumerate}\n\\item $ B \\ne 0 $ and $ A^2 - 4B \\ne 0 $.\n\\item Let $ P = \\rb{a, b} \\in E\\rb{\\Q} $ and $ Q = \\rb{a', b'} \\in E\\rb{\\Q} $ be points such that $ a \\ne a' $ and $ P + Q = \\rb{a'', b''} \\in E\\rb{\\Q} $. Then $ aa'a'' = \\mu^2 $ for some $ \\mu \\in \\Q $.\n\\item Let $ P = \\rb{a, b} \\in E\\rb{\\Q} $ be a point such that $ b \\ne 0 $. Then\n$$ 2P = \\rb{\\dfrac{\\rb{a^2 - B}^2}{4b^2}, \\dfrac{\\rb{a^2 - B}\\rb{a^4 + B^2 + 2Aa^3 + 2ABa + 6Ba^2}}{8b^3}} \\in E\\rb{\\Q}. $$\n\\end{enumerate}\n\\end{lemma}\n\n\\begin{proof}\nThe negation formula remains unmodified, so $ -\\rb{a, b} = \\rb{a, -b} $ for any point $ \\rb{a, b} \\in E $.\n\\begin{enumerate}\n\\item Since $ E $ is smooth and the discriminant is\n$$ \\Delta_E = 9\\rb{4A}\\rb{2B}\\rb{0} - \\tfrac{1}{4}\\rb{4A}^2\\rb{\\rb{4A}\\rb{0} - \\rb{2B}^2} - 8\\rb{2B}^3 - 27\\rb{0}^2 = 16B^2\\rb{A^2 - 4B}, $$\n$ 16B^2\\rb{A^2 - 4B} \\ne 0 $. Thus $ B \\ne 0 $ and $ A^2 - 4B \\ne 0 $.\n\\item The line joining $ P $ and $ Q $ is\n$$ L : y = \\lambda x + \\mu, \\qquad \\lambda = \\dfrac{b - b'}{a - a'}, \\qquad \\mu = \\dfrac{ab' - a'b}{a - a'}, $$\nwhich intersects $ E $ at $ x^3 - \\rb{\\lambda^2 - A}x^2 + \\rb{B - 2\\lambda\\mu}x - \\mu^2 = 0 $. Let $ P * Q = -\\rb{P + Q} = \\rb{a'', -b''} $. Thus comparing coefficients gives $ \\mu^2 = aa'a'' $.\n\\item The tangent at $ P $ is\n$$ L : y = \\lambda x + \\mu, \\qquad \\lambda = \\dfrac{3a^2 + 2Aa + B}{2b}, \\qquad \\mu = \\dfrac{b^2 - Aa^2 - 2Ba}{2b}, $$\nwhich intersects $ E $ at $ x^3 - \\rb{\\lambda^2 - A}x^2 + \\rb{B - 2\\lambda\\mu}x - \\mu^2 = 0 $. Let $ P * P = -2P = \\rb{a', -b'} $, so comparing coefficients gives $ \\lambda^2 - A = 2a + a' $. Thus\n$$ 2P = \\rb{\\lambda^2 - A - 2a, \\mu - \\lambda\\rb{\\lambda^2 - A - 2a}} \\in E\\rb{\\Q}. $$\n\\end{enumerate}\n\\end{proof}\n\nThe above proof is brief but can be verified manually. Let a related curve be\n$$ E' : y^2 = x^3 + A'x^2 + B'x, \\qquad A' = -2A, \\qquad B' = A^2 - 4B, $$\nsuch that $ T \\in E' $ and $ B' \\ne 0 $. Then $ A'^2 - 4B' = \\rb{-2A}^2 - 4\\rb{A^2 - 4B} = 16B $, and the group law is similar to that of $ E $ but with $ A' $ and $ B' $ instead of $ A $ and $ B $. Now let the two maps $ \\phi : E \\to E' $ and $ \\psi : E' \\to E $ be defined by\n$$ \\phi\\rb{P} = \\begin{dcases} \\rb{\\dfrac{b^2}{a^2}, \\dfrac{b\\rb{a^2 - B}}{a^2}} & P = \\rb{a, b} \\ne T \\\\ \\mathcal{O} & P \\in \\cb{\\mathcal{O}, T} \\end{dcases}, \\qquad \\psi\\rb{P} = \\begin{dcases} \\rb{\\dfrac{b^2}{4a^2}, \\dfrac{b\\rb{a^2 - B'}}{8a^2}} & P = \\rb{a, b} \\ne T \\\\ \\mathcal{O} & P \\in \\cb{\\mathcal{O}, T} \\end{dcases}. $$\nThese two maps are related in the obvious way, where one can be seen as the scaling of the other. They also relate the two elliptic curves, as seen in the following lemma.\n\n\\begin{lemma}\n$ \\phi : E \\to E' $ and $ \\psi : E' \\to E $ are isogenies such that $ \\psi \\circ \\phi = \\sb{2}_E $ and $ \\phi \\circ \\psi = \\sb{2}_{E'} $.\n\\end{lemma}\n\n\\begin{remark}\nPreserving the point at infinity induces a group homomorphism, but the full property can be tediously verified in III.4 of \\cite{utm} for each case of the group law.\n\\end{remark}\n\n\\begin{proof}\nFor any point $ P = \\rb{a, b} \\in E $,\n$$ \\rb{\\dfrac{b^2}{a^2}}^3 + A'\\rb{\\dfrac{b^2}{a^2}}^2 + B'\\dfrac{b^2}{a^2}\n= \\dfrac{b^2}{a^4}\\rb{\\dfrac{\\rb{b^2 - Aa^2}^2 - 4Ba^4}{a^2}}\n= \\dfrac{b^2}{a^4}\\rb{\\dfrac{\\rb{a^3 + Ba}^2 - 4Ba^4}{a^2}}\n= \\rb{\\dfrac{b\\rb{a^2 - B}}{a^2}}^2, $$\nso $ \\phi\\rb{P} \\in E' $. Since $ \\phi\\rb{T} = \\phi\\rb{\\mathcal{O}} = \\mathcal{O} $, it holds that $ \\phi $ is a well-defined non-constant morphism, and hence an isogeny. Since $ \\psi $ can be seen as applying $ \\chi \\circ \\phi $ to $ E $, where $ \\chi $ is the $ j $-invariant affine transformation $ \\rb{x, y} \\mapsto \\rb{x / 4, y / 8} $, it is also a well-defined non-constant morphism, and hence an isogeny. Now let $ P \\in E $. If $ P = \\mathcal{O} $ or $ P = \\rb{a, 0} $, then $ \\rb{\\psi \\circ \\phi}\\rb{P} = \\mathcal{O} = 2P $. Otherwise $ P = \\rb{a, b} $ such that $ a \\ne 0 $ and $ b \\ne 0 $, then\n\\begin{align*}\n\\rb{\\psi \\circ \\phi}\\rb{P}\n& = \\rb{\\dfrac{\\rb{b\\rb{a^2 - B} / a^2}^2}{4\\rb{b^2 / a^2}^2}, \\dfrac{\\rb{b\\rb{a^2 - B} / a^2}\\rb{\\rb{b^2 / a^2}^2 - B'}}{8\\rb{b^2 / a^2}^2}} \\\\\n& = \\rb{\\dfrac{\\rb{a^2 - B}^2}{4b^2}, \\dfrac{\\rb{a^2 - B}\\rb{b^4 - \\rb{A^2 - 4B}a^4}}{8b^3a^2}} \\\\\n& = \\rb{\\dfrac{\\rb{a^2 - B}^2}{4b^2}, \\dfrac{\\rb{a^2 - B}\\rb{a^4 + B^2 + 2Aa^3 + 2ABa + 6Ba^2}}{8b^3}} = 2P.\n\\end{align*}\nHence $ \\psi \\circ \\phi = \\sb{2}_E $. Similarly let $ P' \\in E' $. If $ P' = \\mathcal{O} $ or $ P' = \\rb{a, 0} $, then $ \\rb{\\phi \\circ \\psi}\\rb{P'} = \\mathcal{O} = 2P' $. Otherwise $ P' = \\rb{a, b} $ such that $ a \\ne 0 $ and $ b \\ne 0 $, then\n\\begin{align*}\n\\rb{\\phi \\circ \\psi}\\rb{P'}\n& = \\rb{\\dfrac{\\rb{b\\rb{a^2 - B'} / 8a^2}^2}{\\rb{b^2 / 4a^2}^2}, \\dfrac{\\rb{b\\rb{a^2 - B'} / 8a^2}\\rb{\\rb{b^2 / 4a^2}^2 - B}}{\\rb{b^2 / 4a^2}^2}} \\\\\n& = \\rb{\\dfrac{\\rb{a^2 - B'}^2}{4b^2}, \\dfrac{\\rb{a^2 - B'}\\rb{b^4 - 16\\rb{\\rb{A'^2 - 4B'} / 16}a^4}}{8b^3a^2}} \\\\\n& = \\rb{\\dfrac{\\rb{a^2 - B'}^2}{4b^2}, \\dfrac{\\rb{a^2 - B'}\\rb{a^4 + B'^2 + 2A'a^3 + 2A'B'a + 6B'a^2}}{8b^3}} = 2P'.\n\\end{align*}\nThus $ \\phi \\circ \\psi = \\sb{2}_{E'} $.\n\\end{proof}\n\nHence the multiplication by $ 2 $ map can be decomposed into two isogenies $ \\phi $ and $ \\psi $. As only the image of these isogenies will be used, their standard forms will not be used to prevent confusion.\n\n\\begin{remark}\nThese two isogenies are \\emph{dual isogenies} to each other. Any isogeny of degree $ n \\in \\Z_{> 0} $ has a dual isogeny, which composes with it to give two multiplication by $ n $ maps in their respective domains.\n\\end{remark}\n\n\\pagebreak\n\nThe image of the isogeny $ \\psi $ depends on whether $ B $ is a perfect square or whether $ x $ coordinates are in the normal subgroup $ \\rb{\\Q^*}^2 = \\cb{q^2 \\mid q \\in \\Q^*} $. In particular, the equation $ x^3 + A'x + B' = 0 $ with discriminant $ 16\\rb{A'^2 - 4B'} = 16B $ has two solutions in $ \\Q^* $ iff $ 16B \\in \\rb{\\Z^*}^2 $, or $ B \\in \\rb{\\Z^*}^2 $, stated as follows.\n\n\\begin{lemma}\nThe image $ Im\\rb{\\psi} $ is such that:\n\\begin{itemize}\n\\item $ \\mathcal{O} \\in Im\\rb{\\psi} $,\n\\item $ T \\in Im\\rb{\\psi} $ iff $ B \\in \\rb{\\Z^*}^2 $, and\n\\item $ \\rb{a, b} \\ne T \\in Im\\rb{\\psi} $ iff $ a \\in \\rb{\\Q^*}^2 $.\n\\end{itemize}\n\\end{lemma}\n\n\\begin{proof}\nSince $ \\psi\\rb{\\mathcal{O}} = \\mathcal{O} $, it holds that $ \\mathcal{O} \\in Im\\rb{\\psi} $. Now $ T \\in Im\\rb{\\psi} $ iff there is a point $ P = \\rb{a, b} \\in E'\\rb{\\Q} $ such that $ \\psi\\rb{P} = T $ and $ 0 = b^2 / 4a^2 $. This holds iff $ a \\in \\Q^* $ and $ b = 0 $, or $ B \\in \\rb{\\Z^*}^2 $. Now assume that $ P = \\rb{a, b} \\ne T \\in Im\\rb{\\psi} $. Then there is a point $ Q = \\rb{a', b'} \\in E'\\rb{\\Q} $ such that $ \\psi\\rb{Q} = P $, so $ a = b'^2 / 4a'^2 = \\rb{b' / 2a}^2 \\in \\rb{\\Q^*}^2 $. Conversely assume that $ P = \\rb{a, b} \\ne T \\in E\\rb{\\Q} $ and $ a \\in \\rb{\\Q^*}^2 $. Then $ a = c^2 $ for some $ c \\in \\Q^* $, so\n$$ b^2 = c^6 - \\dfrac{A'c^4}{2} + \\dfrac{A'^2 - 4B'}{16}c^2 \\qquad \\implies \\qquad B' = \\rb{2c^2 - \\dfrac{A'}{2} + \\dfrac{2b}{c}}\\rb{2c^2 - \\dfrac{A'}{2} - \\dfrac{2b}{c}}. $$\nNow let $ Q = \\rb{a', b'} $, where $ a' = 2c^2 - A' / 2 + 2b / c $ and $ b' = 2a'c $, such that $ B' = a'\\rb{a' - 4b / c} $. Then\n$$ a'^3 + A'a'^2 + B'a' = a'^3 + A'a'^2 + a'^2\\rb{a' - \\dfrac{2b}{c}} = 2a'^2\\rb{a' + \\dfrac{A'}{2} - \\dfrac{4b}{c}} = 4a'^2c^2 = b'^2, $$\nso $ Q \\in E'\\rb{\\Q} $, and\n$$ \\psi\\rb{Q} = \\rb{\\dfrac{b'^2}{4a'^2}, \\dfrac{b'\\rb{a'^2 - B'}}{8a'^2}} = \\rb{\\dfrac{4a'^2c^2}{4a'^2}, \\dfrac{2a'c\\rb{a'^2 - a'\\rb{a' - 4b / c}}}{8a'^2}} = \\rb{c^2, \\dfrac{c\\rb{4a'b / c}}{4a'}} = \\rb{a, b} = P. $$\nThus $ P \\in Im\\rb{\\psi} $.\n\\end{proof}\n\nThe image of the isogeny $ \\phi $ can be characterised analogously, and will not be explicitly stated here. Now let another map be defined as\n$$ \\alpha : E\\rb{\\Q} \\to \\Q^* / \\rb{\\Q^*}^2, \\qquad \\alpha\\rb{P} = \\begin{cases} \\rb{\\Q^*}^2a & P = \\rb{a, b} \\ne T \\\\ \\rb{\\Q^*}^2B & P = T \\\\ \\rb{\\Q^*}^2 & P = \\mathcal{O} \\end{cases}. $$\nThen $ \\psi $ and $ \\alpha $ induce an \\emph{exact sequence} $ E'\\rb{\\Q} \\xrightarrow{\\psi} E\\rb{\\Q} \\xrightarrow{\\alpha} \\Q^* / \\rb{\\Q^*}^2 $, which can be stated more concretely in the following lemma.\n\n\\begin{lemma}\n$ \\alpha : E\\rb{\\Q} \\to \\Q^* / \\rb{\\Q^*}^2 $ is a group homomorphism such that $ Im\\rb{\\psi} = Ker\\rb{\\alpha} $.\n\\end{lemma}\n\n\\begin{proof}\nLet $ P, Q \\in E\\rb{\\Q} $ be points. If $ P = \\mathcal{O} $,\n$$ \\alpha\\rb{P}\\alpha\\rb{Q} = \\rb{\\Q^*}^2\\alpha\\rb{Q} = \\alpha\\rb{Q} = \\alpha\\rb{P + Q}, $$\nor similar for $ Q = \\mathcal{O} $. If $ P = \\rb{a, b} $ and $ Q = \\rb{a', b'} $ such that $ a \\ne a' $ and $ P + Q = \\rb{a'', b''} \\in E\\rb{\\Q} $, then\n$$ \\alpha\\rb{P}\\alpha\\rb{Q} = \\rb{\\Q^*}^2a\\rb{\\Q^*}^2a' = \\rb{\\Q^*}^2aa' = \\rb{\\Q^*}^2\\dfrac{\\mu^2}{a''} = \\rb{\\Q^*}^2\\mu^2a'' = \\rb{\\Q^*}^2a'' = \\alpha\\rb{P + Q}. $$\nOtherwise $ P = \\rb{a, b} $ and $ Q = \\rb{a, b'} $, then\n$$ \\alpha\\rb{P}\\alpha\\rb{Q} = \\rb{\\Q^*}^2a\\rb{\\Q^*}^2a = \\rb{\\Q^*}^2a^2 = \\rb{\\Q^*}^2 = \\rb{\\Q^*}^2\\dfrac{\\rb{a^2 - B}^2}{4b^2} = \\alpha\\rb{P + Q}. $$\nHence $ \\alpha $ is a group homomorphism. Now $ \\mathcal{O} \\in Ker\\rb{\\alpha} $, the point $ T \\in Ker\\rb{\\alpha} $ iff $ B \\in \\rb{\\Q^*}^2 $, and a point $ \\rb{a, b} \\ne T \\in Ker\\rb{\\alpha} $ iff $ a \\in \\rb{\\Q^*}^2 $. Thus $ Im\\rb{\\psi} = Ker\\rb{\\alpha} $.\n\\end{proof}\n\nThe image of the group homomorphism $ \\alpha $ can again be characterised, as being contained in a finite subgroup of $ \\Q^* / \\rb{\\Q^*}^2 $. Now let $ S\\rb{B} $ be the set of primes $ p \\in \\Z_{> 0} $ such that $ p \\mid B $, and let\n$$ G\\rb{B} = \\cb{\\rb{\\Q^*}^2\\rb{\\prod_{p \\in S} p} \\ \\Bigg| \\ S \\subseteq S\\rb{B}} \\cup \\cb{\\rb{\\Q^*}^2\\rb{-\\prod_{p \\in S} p} \\ \\Bigg| \\ S \\subseteq S\\rb{B}}. $$\nRecalling the fact that for any point $ \\rb{a, b} \\in E\\rb{\\Q} $,\n$$ a = p / d^2, \\qquad b = q / d^3, \\qquad p, q \\in \\Z, \\qquad d \\in \\Z_{> 0}, $$ such that $ \\gcd\\rb{p, d} = \\gcd\\rb{q, d} = 1 $, the following lemma characterises $ \\alpha $.\n\n\\begin{lemma}\n$ G\\rb{B} $ is a group such that $ \\abs{G\\rb{B}} = 2^{\\abs{S\\rb{B}} + 1} $ and $ Im\\rb{\\alpha} \\le G\\rb{B} \\le \\Q^* / \\rb{\\Q^*}^2 $.\n\\end{lemma}\n\n\\begin{proof}\nSince $ \\emptyset \\subseteq S\\rb{B} $, it holds that $ \\rb{\\Q^*}^2 \\in G\\rb{B} $. Let $ a, b \\in G\\rb{B} $. Then\n$$ a = \\rb{\\Q^*}^2 j p_1 \\dots p_n p'_1 \\dots p'_{n'}, \\qquad b = \\rb{\\Q^*}^2 j' p_1 \\dots p_n p''_1 \\dots p''_{n''} $$\nfor some $ j, j' \\in \\cb{-1, 1} $ and some distinct primes $ p_i, p'_i, p''_i \\in S\\rb{B} $, so\n$$ \\dfrac{a}{b} = \\dfrac{\\rb{\\Q^*}^2 j p_1 \\dots p_n p'_1 \\dots p'_{n'}}{\\rb{\\Q^*}^2 j' p_1 \\dots p_n p''_1 \\dots p''_{n''}} = \\rb{\\Q^*}^2\\dfrac{j p'_1 \\dots p'_{n'}}{j' p''_1 \\dots p''_{n''}} = \\rb{\\Q^*}^2 j j' p'_1 \\dots p'_{n'} p''_1 \\dots p''_{n''} \\in G\\rb{B}. $$\nHence $ G\\rb{B} \\le \\Q^* / \\rb{\\Q^*}^2 $ and $ \\abs{G\\rb{B}} = 2^{\\abs{S\\rb{B}}} + 2^{\\abs{S\\rb{B}}} = 2^{\\abs{S\\rb{B}} + 1} $. Now let $ P \\in E\\rb{\\Q} $ be a point. If $ P = \\mathcal{O} $, then $ \\alpha\\rb{P} = \\rb{\\Q^*}^2 \\in G\\rb{B} $. If $ P = T $, then $ \\alpha\\rb{P} = \\rb{\\Q^*}^2B \\in G\\rb{B} $. Otherwise $ P = \\rb{a, b} \\ne T $, then $ a = r / d^2 $ and $ b = s / d^3 $ for some $ r, s \\in \\Z $ and some $ d \\in \\Z_{> 0} $ such that $ \\gcd\\rb{r, d} = \\gcd\\rb{s, d} = 1 $ and $ s^2 = r^3 + Ar^2d^2 + Brd^4 = r\\rb{r^2 + Ard^2 + Bd^4} $. Let $ g = \\gcd\\rb{r, r^2 + Ard^2 + Bd^4} $, then $ r = cg $ and $ r^2 + Ard^2 + Bd^4 = c'g $ for some $ c, c' \\in \\Z_{\\ge 0} $ such that $ \\gcd\\rb{c, c'} = 1 $. Since $ s^2 = \\rb{cg}\\rb{c'g} = cc'g^2 $, it holds that $ \\rb{s / g}^2 = cc' $, so $ c = k q_1^2 \\cdots q_m^2 $ for some $ k \\in \\cb{-1, 1} $ and some primes $ q_i \\in \\Z_{> 0} $. Since $ g \\mid r $ and $ g \\mid Bd^4 $, it also holds that $ g \\mid B $, so $ g = k' q'_1 \\dots q'_{m'} $ for some $ k' \\in \\cb{-1, 1} $ and some primes $ q'_i \\in \\Z_{> 0} $ such that $ q'_i \\mid B $, and hence $ q'_i \\in S\\rb{B} $. Hence\n$$ \\alpha\\rb{P} = \\rb{\\Q^*}^2a = \\rb{\\Q^*}^2\\dfrac{r}{d^2} = \\rb{\\Q^*}^2\\dfrac{k k' q_1^2 \\cdots q_m^2 q'_1 \\dots q'_{m'}}{d^2} = \\rb{\\Q^*}^2 k k' q'_1 \\dots q'_{m'} \\in G\\rb{B}. $$\nThus $ Im\\rb{\\alpha} \\le G\\rb{B} $.\n\\end{proof}\n\nA similar group homomorphism $ \\alpha' : E'\\rb{\\Q} \\to \\Q^* / \\rb{\\Q^*}^2 $ can again be characterised analogously, and will not be explicitly stated here. The weak theorem can then be proven here, for the special case of a rational $ 2 $-torsion point.\n\n\\begin{proof}[Proof of Theorem \\ref{thm:weakmordell}]\nThe first isomorphism theorem with the preceding lemmas give two inclusions\n$$ \\dfrac{E\\rb{\\Q}}{Im\\rb{\\psi}} = \\dfrac{E\\rb{\\Q}}{Ker\\rb{\\alpha}} \\cong Im\\rb{\\alpha} \\le G\\rb{B}, \\qquad \\dfrac{E'\\rb{\\Q}}{Im\\rb{\\phi}} = \\dfrac{E'\\rb{\\Q}}{Ker\\rb{\\alpha'}} \\cong Im\\rb{\\alpha'} \\le G\\rb{B'}, $$\nwhich give finite indices\n$$ n = \\abs{E\\rb{\\Q} : Im\\rb{\\psi}} \\le \\abs{G\\rb{B}} = 2^{\\abs{S\\rb{B}} + 1}, \\qquad m = \\abs{E'\\rb{\\Q} : Im\\rb{\\phi}} \\le \\abs{G\\rb{B'}} = 2^{\\abs{S\\rb{B'}} + 1}. $$\nLet $ P_1, \\dots, P_n \\in E\\rb{\\Q} $ be representative points such that $ Im\\rb{\\psi} + P_i \\in E\\rb{\\Q} / Im\\rb{\\psi} $ are distinct cosets, and let $ Q_1, \\dots, Q_m \\in E'\\rb{\\Q} $ be representative points such that $ Im\\rb{\\phi} + Q_i \\in E'\\rb{\\Q} / Im\\rb{\\phi} $ are distinct cosets. Now let $ P \\in E\\rb{\\Q} $ be a point. Then $ Im\\rb{\\psi} + P = Im\\rb{\\psi} + P_j $ for some $ j \\in \\cb{1, \\dots, n} $, so $ P = \\psi\\rb{Q} + P_j $ for some $ Q \\in E'\\rb{\\Q} $ and $ \\psi\\rb{Q} \\in Im\\rb{\\psi} $. Similarly $ Im\\rb{\\phi} + Q = Im\\rb{\\phi} + Q_k $ for some $ k \\in \\cb{1, \\dots, m} $, so $ Q = \\phi\\rb{P'} + Q_k $ for some $ P' \\in E\\rb{\\Q} $ and $ \\phi\\rb{P'} \\in Im\\rb{\\phi} $. Hence\n$$ P = \\psi\\rb{Q} + P_j = \\psi\\rb{\\phi\\rb{P'} + Q_k} + P_j = \\psi\\rb{\\phi\\rb{P'}} + \\psi\\rb{Q_k} + P_j \\in 2E\\rb{\\Q} + \\psi\\rb{Q_k} + P_j, $$\nand $ \\psi\\rb{Q_k} + P_j \\in E\\rb{\\Q} $ represent all cosets in $ E\\rb{\\Q} / 2E\\rb{\\Q} $. Thus\n$$ \\abs{E\\rb{\\Q} : 2E\\rb{\\Q}} \\le nm = 2^{\\rb{\\abs{S\\rb{B}} + 1}\\rb{\\abs{S\\rb{B'}} + 1}} $$\nis finite.\n\\end{proof}\n\nThe proof of Mordell's theorem is now complete.\n\n\\pagebreak\n\n\\subsection{Rank computation}\n\nA direct application of Mordell's theorem would be the fundamental theorem of finite abelian groups,\n$$ E\\rb{\\Q} \\cong \\Z^r \\oplus \\bigoplus_{i = 1}^m \\Z_{n_i}, \\qquad r, m \\in \\Z_{\\ge 0}, \\qquad n_i \\in \\Z_{> 1}, $$\nsuch that each $ n_i \\mid n_{i + 1} $. Thus for any point $ P \\in E\\rb{\\Q} $,\n$$ P = \\sum_{i = 1}^r r_iP_i + \\sum_{i = 1}^m m_iQ_i, \\qquad r_i \\in \\Z, \\qquad m_i \\in \\Z_{n_i}, \\qquad P_i, Q_i \\in E\\rb{\\Q}. $$\nWhile the torsion subgroup can be easily computed, the rank $ r $ is generally difficult to compute, and can only be made slightly easier with Mordell's theorem. Noting that $ \\bigoplus_i \\rb{G_i / H_i} \\cong \\rb{\\bigoplus_i G_i} / \\rb{\\bigoplus_i H_i} $ for any groups $ G_i, H_i $, the following proposition gives a direct formula for the rank.\n\n\\begin{proposition}\nThe rank $ r = rk\\rb{E\\rb{\\Q}} $ is such that\n$$ 2^r = \\tfrac{1}{4}\\abs{Im\\rb{\\alpha}}\\abs{Im\\rb{\\alpha'}}. $$\n\\end{proposition}\n\n\\begin{proof}\nThe fundamental theorem of finite abelian groups gives\n$$ \\dfrac{E\\rb{\\Q}}{2E\\rb{\\Q}} \\cong \\dfrac{\\Z^r \\oplus \\bigoplus_{i = 1}^m \\Z_{n_i}}{r2\\Z \\oplus \\bigoplus_{i = 1}^m 2\\Z_{n_i}} \\cong r\\rb{\\dfrac{\\Z}{2\\Z}} \\oplus \\bigoplus_{i = 1}^m \\dfrac{\\Z_{n_i}}{2\\Z_{n_i}}. $$\nThen $ \\Z / 2\\Z \\cong \\Z_2 $. If $ n_i \\nmid 2 $, then $ 2^{-1} \\in \\Z_{n_i} $, so $ \\Z_{n_i} \\cong 2\\Z_{n_i} $ and $ \\Z_{n_i} / 2\\Z_{n_i} \\cong 0 $, otherwise $ n_i \\mid 2 $. Now $ P \\in E\\rb{\\Q}\\sb{2} $ iff $ 2P = 0 $, or each $ r_i = 0 $ and each $ 2m_i = 0 \\mod n_i $, which holds iff $ m_i = 0 $ or $ n_i \\mid 2 $, so $ E\\rb{\\Q}\\sb{2} = \\bigoplus_{n_i \\mid 2} \\Z_{n_i} $. Hence\n$$ \\dfrac{E\\rb{\\Q}}{2E\\rb{\\Q}} \\cong \\Z^r_2 \\oplus E\\rb{\\Q}\\sb{2} \\qquad \\implies \\qquad \\abs{E\\rb{\\Q} : 2E\\rb{\\Q}} = 2^r\\abs{E\\rb{\\Q}\\sb{2}}. $$\nNow let $ \\theta : E'\\rb{\\Q} \\to Im\\rb{\\psi} / 2E\\rb{\\Q} $ be a surjective group homomorphism defined by $ \\theta\\rb{P} = 2E\\rb{\\Q} + \\psi\\rb{P} $. Then $ P \\in Ker\\rb{\\theta} $ iff $ \\psi\\rb{P} \\in 2E\\rb{\\Q} $, or $ \\psi\\rb{P} = \\psi\\rb{\\phi\\rb{Q}} $ for some $ Q \\in E\\rb{\\Q} $. This holds iff $ \\psi\\rb{P - \\phi\\rb{Q}} = 0 $, or $ P - \\phi\\rb{Q} \\in Ker\\rb{\\psi} $ and $ P \\in Ker\\rb{\\psi} + Im\\rb{\\phi} $. Then the three isomorphism theorems with $ Ker\\rb{\\theta} = Ker\\rb{\\psi} + Im\\rb{\\phi} $ give\n$$ \\dfrac{Im\\rb{\\psi}}{2E\\rb{\\Q}} \\cong \\dfrac{E'\\rb{\\Q}}{Ker\\rb{\\psi} + Im\\rb{\\phi}} \\cong \\dfrac{\\dfrac{E'\\rb{\\Q}}{Im\\rb{\\phi}}}{\\dfrac{Ker\\rb{\\psi} + Im\\rb{\\phi}}{Im\\rb{\\phi}}} \\cong \\dfrac{\\dfrac{E'\\rb{\\Q}}{Im\\rb{\\phi}}}{\\dfrac{Ker\\rb{\\psi}}{Ker\\rb{\\psi} \\cap Im\\rb{\\phi}}}. $$\nHence\n$$ \\abs{E\\rb{\\Q} : 2E\\rb{\\Q}} = \\dfrac{\\abs{E\\rb{\\Q} : Im\\rb{\\psi}}\\abs{E'\\rb{\\Q} : Im\\rb{\\phi}}}{\\abs{Ker\\rb{\\psi} : Ker\\rb{\\psi} \\cap Im\\rb{\\phi}}} = \\dfrac{\\abs{Im\\rb{\\alpha}}\\abs{Im\\rb{\\alpha'}}}{\\abs{Ker\\rb{\\psi} : Ker\\rb{\\psi} \\cap Im\\rb{\\phi}}}. $$\nNow $ B' \\in \\rb{\\Z^*}^2 $ iff $ T \\in Im\\rb{\\phi} $ and the equation $ x^2 + Ax + B = 0 $ with discriminant $ 16\\rb{A^2 - 4B^2} = 16B' $ has solutions in $ \\Z^* $. Since $ Ker\\rb{\\psi} = \\cb{\\mathcal{O}, T} $ and $ \\mathcal{O} \\in Im\\rb{\\phi} $, this holds iff $ Ker\\rb{\\psi} \\cap Im\\rb{\\phi} = \\cb{\\mathcal{O}, T} $. Since $ \\mathcal{O}, T \\in E\\rb{\\Q}\\sb{2} $, this also holds iff $ \\rb{a, 0}, \\rb{a', 0} \\in E\\rb{\\Q}\\sb{2} $ for the solutions $ a, a' \\in \\Q^* $ of $ x^2 + Ax + B = 0 $. Hence\n$$ E\\rb{\\Q}\\sb{2} = \\begin{cases} \\cb{\\mathcal{O}, T, \\rb{a, 0}, \\rb{a', 0}} & B' \\in \\rb{\\Z^*}^2 \\\\ \\cb{\\mathcal{O}, T} & B' \\notin \\rb{\\Z^*}^2 \\end{cases}, \\qquad \\dfrac{Ker\\rb{\\psi}}{Ker\\rb{\\psi} \\cap Im\\rb{\\phi}} = \\begin{cases} \\cb{\\mathcal{O}} & B' \\in \\rb{\\Z^*}^2 \\\\ \\cb{\\mathcal{O}, T} & B' \\notin \\rb{\\Z^*}^2 \\end{cases}, $$\nso $ \\abs{Ker\\rb{\\psi} : Ker\\rb{\\psi} \\cap Im\\rb{\\phi}}\\abs{E\\rb{\\Q}\\sb{2}} = 4 $. Thus\n$$ 2^r = \\dfrac{\\abs{Im\\rb{\\alpha}}\\abs{Im\\rb{\\alpha'}}}{\\abs{Ker\\rb{\\psi} : Ker\\rb{\\psi} \\cap Im\\rb{\\phi}}\\abs{E\\rb{\\Q}\\sb{2}}} = \\tfrac{1}{4}\\abs{Im\\rb{\\alpha}}\\abs{Im\\rb{\\alpha'}}. $$\n\\end{proof}\n\nComputation of the rank simply reduces to determining images of $ \\alpha $ and $ \\alpha' $. This in turn can be rephrased as a question of Diophantine equations.\n\n\\begin{proposition}\nThe image $ Im\\rb{\\alpha} $ is such that\n$$ Im\\rb{\\alpha} = \\cb{\\rb{\\Q^*}^2\\beta \\ \\Big| \\ \\beta, B / \\beta \\in \\Z^*, \\ \\rb{X, Y, Z} \\in \\Z^3 \\setminus \\cb{\\rb{0, 0, 0}}, \\ Y^2 = \\beta X^4 + AX^2Z^2 + \\rb{B / \\beta}Z^4}. $$\n\\end{proposition}\n\n\\begin{proof}\nSince $ \\rb{\\Q^*}^2 \\in Im\\rb{\\alpha} $, there is a solution $ \\rb{X, Y, Z} = \\rb{1, 1, 0} $ for $ \\beta = 1 $. Since $ \\rb{\\Q^*}^2B \\in Im\\rb{\\alpha} $, there is also a solution $ \\rb{X, Y, Z} = \\rb{0, 1, 1} $ for $ \\beta = B $. Let $ P = \\rb{a, b} \\ne T \\in E\\rb{\\Q} $ such that $ \\rb{\\Q^*}^2a \\in Im\\rb{\\alpha} $. Then $ a = r / Z_0^2 $ and $ b = s / Z_0^3 $ for some $ r, s \\in \\Z $ and some $ Z_0 \\in \\Z_{> 0} $ such that $ \\gcd\\rb{r, Z_0} = \\gcd\\rb{s, Z_0} = 1 $. Now let $ r = X_0^2\\beta_0 $, where $ X_0 = p_1 \\dots p_n \\in \\Z_{> 0} $ for some primes $ p_i \\in \\Z_{> 0} $ and $ \\beta_0 = j q_1 \\dots q_n $ for some $ j \\in \\cb{-1, 1} $ and some distinct primes $ q_i \\in \\Z_{> 0} $. Since $ \\rb{\\Q^*}^2\\beta_0 = \\rb{\\Q^*}^2X_0^2\\beta_0 / Z_0^2 = \\rb{\\Q^*}^2\\beta_0 \\in G\\rb{B} $, each $ q_i \\mid B $, so $ \\beta_0 \\mid B $ and hence $ B / \\beta_0 \\in \\Z^* $. Then\n$$ \\rb{\\dfrac{s}{Z_0^3}}^2 = \\rb{\\dfrac{X_0^2\\beta_0}{Z_0^2}}^3 + A\\rb{\\dfrac{X_0^2\\beta_0}{Z_0^2}}^2 + B\\dfrac{X_0^2\\beta_0}{Z_0^2} \\qquad \\implies \\qquad s^2 = \\beta_0^2X_0^2\\rb{\\beta_0X_0^4 + AX_0^2Z_0^2 + \\rb{B / \\beta_0}Z_0^4}, $$\nso let $ Y_0 = s^2 / \\beta_0^2X_0^2 \\in \\Z $ such that $ Y_0^2 = \\beta_0X_0^4 + AX_0^2Z_0^2 + \\rb{B / \\beta_0}Z_0^4 $. Hence there is a non-zero solution $ \\rb{X, Y, Z} = \\rb{X_0, Y_0, Z_0} $ for $ \\beta = \\beta_0 $. Conversely let $ \\rb{X, Y, Z} = \\rb{X_0, Y_0, Z_0} $ be a non-zero solution for some $ \\beta = \\beta_0 \\in \\Z^* $, so $ Y_0^2 = \\beta_0 X_0^4 + AX_0^2Z_0^2 + \\rb{B / \\beta_0}Z_0^4 $. Then $ P = \\rb{\\beta_0 X_0^2 / Z_0^2, \\beta_0 X_0Y_0 / Z_0^3} $ is such that\n$$ \\rb{\\dfrac{\\beta_0 X_0Y_0}{Z_0^3}}^2 = \\dfrac{\\beta_0^2X_0^2\\rb{\\beta_0 X_0^4 + AX_0^2Z_0^2 + \\rb{B / \\beta_0}Z_0^4}}{Z_0^6} = \\rb{\\dfrac{\\beta_0 X_0^2}{Z_0^2}}^3 + A\\rb{\\dfrac{\\beta_0 X_0^2}{Z_0^2}}^2 + B\\dfrac{\\beta_0 X_0^2}{Z_0^2}, $$\nso $ P \\in E\\rb{\\Q} $ and $ \\alpha\\rb{P} = \\rb{\\Q^*}^2\\rb{\\beta_0 X_0^2 / Z_0^2} = \\rb{\\Q^*}^2\\beta_0 $. Thus any non-zero solution is in $ Im\\rb{\\alpha} $.\n\\end{proof}\n\nAgain, the image of $ \\alpha' $ is similar to that of $ \\alpha $ but with $ B' $ instead of $ B $. The following example illustrates the full computation of the rank of a simple elliptic curve.\n\n\\begin{example}\nLet $ E : y^2 = x^3 - x $ be an elliptic curve over $ \\Q $. Then $ \\beta \\in \\cb{\\pm 1} $. Since $ \\beta = 1 $ and $ \\beta = -1 = B $ have solutions, it holds that $ \\abs{Im\\rb{\\alpha}} = 2 $. Now $ E' : y^2 = x^3 + 4x $ gives $ \\beta \\in \\cb{\\pm 1, \\pm 2, \\pm 4} $. Since $ \\rb{\\Q^*}^2\\rb{\\pm 1} = \\rb{\\Q^*}^2\\rb{\\pm 4} $, the Diophantine equations to consider are:\n\\begin{enumerate}\n\\item $ \\beta = 1 $ gives $ Y^2 = X^4 + 4Z^4 $, which has a solution $ \\rb{X, Y, Z} = \\rb{0, 2, 1} $.\n\\item $ \\beta = 2 $ gives $ Y^2 = 2X^4 + 2Z^4 $, which has a solution $ \\rb{X, Y, Z} = \\rb{1, 2, 1} $.\n\\item $ \\beta = -1 $ gives $ Y^2 = -X^4 - 4Z^4 $, which has no solutions by sign disparity.\n\\item $ \\beta = -2 $ gives $ Y^2 = -2X^4 - 2Z^4 $, which has no solutions by sign disparity.\n\\end{enumerate}\nHence $ \\abs{Im\\rb{\\alpha'}} = 2 $ and $ 2^r = \\tfrac{1}{4}\\rb{2}\\rb{2} = 1 $. Thus $ rk\\rb{E\\rb{\\Q}} = 0 $ and $ E\\rb{\\Q} = E\\rb{\\Q}_{tors} \\cong \\Z_2 $.\n\\end{example}\n\nThe following algorithm summarises the process and code in the appendix.\n\n\\begin{algorithm}[Computation of the rank]\nInput: an elliptic curve $ E $ over $ \\Q $. Output: $ rk\\rb{E\\rb{\\Q}} $.\n\\begin{enumerate}\n\\item Get all positive $ \\beta $ such that $ \\beta \\mid B $ and free the squares from each $ \\beta $.\n\\item Print all Diophantine equations of the form $ Y^2 = \\beta X^4 + AX^2Z^2 + \\rb{B / \\beta}Z^4 $.\n\\item Write down the elliptic curve $ E' : y^2 = x^3 - 2Ax^2 + \\rb{A^2 - 4B}x $ and do the same.\n\\item Check if there are non-zero solutions to the systems of Diophantine equations.\n\\item Compute the rank with the formula $ rk\\rb{E\\rb{\\Q}} = \\log_2\\abs{Im\\rb{\\alpha}} + \\log_2\\abs{Im\\rb{\\alpha'}} - 2 $.\n\\end{enumerate}\n\\end{algorithm}\n\nUnfortunately, there are no known effective method for the second to last step. In contrast to attempting at a number theoretic algorithm like in \\cite{rank}, only ad-hoc congruences will be used to complete the computations in the following examples of elliptic curves given by the Weierstrass equations $ y^2 = x^3 - px $ for $ p \\in \\Z_{> 0} $. The following example is an elliptic curve of rank one.\n\n\\begin{example}\nLet $ E : y^2 = x^3 - 5x $ be an elliptic curve over $ \\Q $, which gives $ \\beta \\in \\cb{\\pm 1, \\pm 5} $. Since $ \\beta = 1 $ and $ \\beta = -5 $ have trivial solutions, the Diophantine equations to consider are $ Y^2 = -X^4 + 5Z^4 $, which has a solution $ \\rb{X, Y, Z} = \\rb{1, 2, 1} $, and $ Y^2 = 5X^4 - Z^4 $, which has a solution by symmetry. Hence $ \\abs{Im\\rb{\\alpha}} = 4 $. Now $ E' : y^2 = x^3 + 20x $ gives $ \\beta \\in \\cb{\\pm 1, \\pm 2, \\pm 5, \\pm 10} $. If $ \\beta < 0 $, there are no solutions by sign disparity. Since $ \\beta = 1 $ and $ \\beta = 5 $ have trivial solutions, the Diophantine equations to consider are $ Y^2 = 2X^4 + 10Z^4 $ and $ Y^2 = 10X^4 + 2Z^4 $. Since $ \\gcd\\rb{X_0, Y_0} = 1 $, if the first has a solution $ \\rb{X, Y, Z} = \\rb{X_0, Y_0, Z_0} $, then $ Y_0^2 \\equiv 2X_0^4 \\equiv 2 \\mod 5 $ gives no solutions for $ Y_0 $, so both equations have no solutions. Hence $ \\abs{Im\\rb{\\alpha'}} = 2 $. Thus $ rk\\rb{E\\rb{\\Q}} = \\log_2\\rb{4} + \\log_2\\rb{2} - 2 = 1 $ and $ E\\rb{\\Q} \\cong \\Z \\oplus E\\rb{\\Q}_{tors} \\cong \\Z \\times \\Z_2 $.\n\\end{example}\n\nThe following example is an elliptic curve of rank two.\n\n\\begin{example}\nLet $ E : y^2 = x^3 - 17x $ be an elliptic curve over $ \\Q $, which gives $ \\beta \\in \\cb{\\pm 1, \\pm 17} $. Since $ \\beta = 1 $ and $ \\beta = -17 $ have trivial solutions, the Diophantine equations to consider are $ Y^2 = -X^4 + 17Z^4 $, which has a solution $ \\rb{X, Y, Z} = \\rb{1, 4, 1} $, and $ Y^2 = 17X^4 - Z^4 $, which has a solution by symmetry. Hence $ \\abs{Im\\rb{\\alpha}} = 4 $. Now $ E' : y^2 = x^3 + 68x $ gives $ \\beta \\in \\cb{\\pm 1, \\pm 2, \\pm 17, \\pm 34} $. If $ \\beta < 0 $, there are no solutions by sign disparity. Since $ \\beta = 1 $ and $ \\beta = 17 $ have trivial solutions, the Diophantine equations to consider are $ Y^2 = 2X^4 + 34Z^4 $, which has a solution $ \\rb{X, Y, Z} = \\rb{1, 6, 1} $, and $ Y^2 = 34X^4 + 2Z^4 $, which has a solution by symmetry. Hence $ \\abs{Im\\rb{\\alpha'}} = 4 $. Thus $ rk\\rb{E\\rb{\\Q}} = \\log_2\\rb{4} + \\log_2\\rb{4} - 2 = 2 $ and $ E\\rb{\\Q} \\cong \\Z^2 \\oplus E\\rb{\\Q}_{tors} \\cong \\Z^2 \\times \\Z_2 $.\n\\end{example}\n\nThe following example is an elliptic curve of rank three.\n\n\\begin{example}\nLet $ E : y^2 = x^3 - 226x $ be an elliptic curve over $ \\Q $, which gives $ \\beta \\in \\cb{\\pm 1, \\pm 2, \\pm 113, \\pm 226} $. Since $ \\beta = 1 $ and $ \\beta = -226 $ have trivial solutions, the Diophantine equations to consider are $ Y^2 = -X^4 + 226Z^4 $, $ Y^2 = 2X^4 - 113Z^4 $, $ Y^2 = -2X^4 + 113Z^4 $, $ Y^2 = 113X^4 - 2Z^4 $, $ Y^2 = -113X^4 + 2Z^4 $, and $ Y^2 = 226X^4 - Z^4 $. The first three have solutions $ \\rb{X, Y, Z} = \\rb{1, 15, 1} $, $ \\rb{X, Y, Z} = \\rb{3, 7, 1} $, and $ \\rb{X, Y, Z} = \\rb{1, 9, 2} $ respectively, while the last three have solutions by symmetry. Hence $ \\abs{Im\\rb{\\alpha}} = 8 $. Now $ E' : y^2 = x^3 + 904x $ gives $ \\beta \\in \\cb{\\pm 1, \\pm 2, \\pm 113, \\pm 226} $. If $ \\beta < 0 $, there are no solutions by sign disparity. Since $ \\beta = 1 $ and $ \\beta = 226 $ have trivial solutions, the Diophantine equations to consider are $ Y^2 = 2X^4 + 452Z^4 $, which has a solution $ \\rb{X, Y, Z} = \\rb{1, 22, 2} $, and $ Y^2 = 113X^4 + 8Z^4 $, which has a solution $ \\rb{X, Y, Z} = \\rb{1, 11, 1} $. Hence $ \\abs{Im\\rb{\\alpha'}} = 4 $. Thus $ rk\\rb{E\\rb{\\Q}} = \\log_2\\rb{8} + \\log_2\\rb{4} - 2 = 3 $ and $ E\\rb{\\Q} \\cong \\Z^3 \\oplus E\\rb{\\Q}_{tors} \\cong \\Z^3 \\times \\Z_2 $.\n\\end{example}\n\nThe ranks of elliptic curves above are relatively small in value and easy to compute, but there are elliptic curves with larger rank values. The record as of 2018 in \\cite{rankhistory} for the elliptic curve with the largest rank was discovered by Elkies in 2006, and is given by the Weierstrass curve\n$$ E : y^2 + xy + y = x^3 - x^2 - 20067762415575526585033208209338542750930230312178956502x $$\n$$ + 34481611795030556467032985690390720374855944359319180361266008296291939448732243429, $$\nwhich is proven to have rank at least 28. There are also elliptic curves with relatively large ranks known exactly, the largest of which was also discovered by Elkies in 2009, and is given by the Weierstrass curve\n$$ E : y^2 + xy + y = x^3 - x^2 + 31368015812338065133318565292206590792820353345x $$\n$$ + 302038802698566087335643188429543498624522041683874493555186062568159847, $$\nwhich has rank 19. In fact, it is conjectured that the rank of an elliptic curve does not have an upper bound.\n\n\\begin{conjecture}\nThere are elliptic curves over $ \\Q $ of arbitrary large rank.\n\\end{conjecture}\n\nHowever, while they exist, elliptic curves of rank greater than one are rare. This notion of rarity is measured by the \\emph{average rank} of all elliptic curves, of which is conjectured to exist as a quantity.\n\n\\begin{conjecture}\nThe average rank of all elliptic curves over $ \\Q $ is $ \\tfrac{1}{2} $.\n\\end{conjecture}\n\nIn particular, rank zero constitute a half and rank one constitute the other half, while all higher ranks constitute zero percent, of all elliptic curves. While it has not been definitely proven, Bhargava and Shankar showed in \\cite{rankaverage} that the average rank of all elliptic curves is at most $ 7 / 6 $.\n\n\\pagebreak\n\n\\subsection{Birch and Swinnerton-Dyer conjecture}\n\nUltimately, the rank of an elliptic curve is not completely understood. It was greatly studied for decades, and had lead mathematicians to formalise one of the most influential conjectures in number theory, which is also deemed worthy of being called one of the Millennium Prize Problems. The problem, now commonly known as the \\emph{Birch and Swinnerton-Dyer conjecture}, relates the rank with Taylor expansion of a particular complex series. Letting $ t_p $ denote the trace in Hasse's theorem applied to $ E_p\\rb{\\F_p} $ for any prime $ p \\in \\Z_{> 0} $ of good reduction, the series can be given as follows.\n\n\\begin{definition}[Incomplete Hasse-Weil $ L $-series]\nThe \\textbf{incomplete Hasse-Weil $ L $-series} is defined for any $ \\Re\\rb{s} > 3 / 2 $ as the \\emph{Euler product}\n$$ L\\rb{E, s} = \\prod_p \\dfrac{1}{1 - t_pp^{-s} + p^{1 - 2s}} $$\nover all primes $ p \\in \\Z_{> 0} $ of good reduction, and extended to $ \\C $ by analytic continuation.\n\\end{definition}\n\nThis analytic continuation, as well as a functional equation similar to that of the Riemann zeta function, was originally known as the \\emph{Hasse-Weil conjecture}, but was subsequently implied by the \\emph{modularity theorem}.\n\n\\begin{remark}\nThe \\emph{complete Hasse-Weil $ L $-series} is defined over all primes $ p \\in \\Z_{> 0} $ as the Euler product\n$$ L^*\\rb{E, s} = \\prod_{p \\mid \\Delta_E} \\dfrac{1}{1 - t_pp^{-s}} \\prod_{p \\nmid \\Delta_E} \\dfrac{1}{1 - t_pp^{-s} + p^{1 - 2s}} = \\sum_{n = 1}^\\infty \\dfrac{a_n}{n^s}. $$\nNow $ E $ might be a singular cubic curve, so that $ t_p $ can be defined for primes of bad reduction as either $ t_p = \\pm 1 $ or $ t_p = 0 $, depending on whether $ E $ has \\emph{split} or \\emph{non-split multiplicative} reduction or \\emph{additive} reduction, which corresponds to whether $ E_p $ has a \\emph{node} or a \\emph{cusp} respectively.\n\\end{remark}\n\nDue to analyticity in $ \\C $, it makes sense to consider the Taylor expansion of $ L\\rb{E, s} $ given by\n$$ L\\rb{E, s} = \\sum_{i = 0}^\\infty c_i\\rb{s - s_0}^i, \\qquad s_0 \\in \\C, \\qquad c_i \\in \\C, $$\nas well its \\emph{order of vanishing} $ ord_{s = s_0} $ or order of zero at $ s_0 $, a value $ i $ such that $ c_i \\ne 0 $ but $ c_j = 0 $ for any $ j < i $. A different notion of rank can then be defined for $ E $, as follows.\n\n\\begin{definition}[Analytic rank]\nThe \\textbf{analytic rank} of $ E $ is $ rk_{an}\\rb{E\\rb{\\Q}} = ord_{s = 1}L\\rb{E, s} $.\n\\end{definition}\n\nThe conjecture then relates both notions of ranks as follows.\n\n\\begin{conjecture}[Birch and Swinnerton-Dyer] $ rk\\rb{E\\rb{\\Q}} = rk_{an}\\rb{E\\rb{\\Q}} $.\n\\end{conjecture}\n\n\\begin{remark}\nThere is also a refined version of the conjecture that involves the \\emph{Tate-Shafarevich group}, which is omitted for further discussion. Proving this strong version will then indirectly lead to efficient algorithms for rank computation.\n\\end{remark}\n\nA direct consequence of the conjecture is that $ E\\rb{\\Q} $ is infinite iff its ranks $ rk\\rb{E\\rb{\\Q}} $ and $ rk_{an}\\rb{E\\rb{\\Q}} $ are positive. This holds iff $ L\\rb{E, s} $ does not have a constant term, or iff $ L\\rb{E, 1} $ computes to give a value of $ 0 $. In other words, the finiteness of $ E\\rb{\\Q} $ holds iff $ L\\rb{E, 1} \\ne 0 $. Now the conjecture has been supported with much numerical evidence in \\cite{bsd0}, and can also be verified by prior examples with the \\emph{Sage} programming language as follows.\n\n\\begin{example}\nLet $ E : y^2 = x^3 - x $ be an elliptic curve over $ \\Q $. Then $ rk\\rb{E\\rb{\\Q}} = 0 $ and\n$$ L\\rb{E, s} \\approx 0.655514388573030 + 0.447208159472739s - 0.233131198781643s^2 + 0.0342258563577268s^3 + \\dots, $$\nHence $ L\\rb{E, 1} \\approx 0.655514388573030 \\ne 0 $. Now let $ E' : y^2 = x^3 - 5x $ be an elliptic curve over $ \\Q $. Then $ rk\\rb{E'\\rb{\\Q}} = 1 $ and\n$$ L\\rb{E', s} \\approx 0.000000000000000 + 2.22876814774675s - 2.06654309593994s^2 + 0.549852427979257s^3 + \\dots. $$\nThus $ L\\rb{E', 1} \\approx 0.000000000000000 = 0 $.\n\\end{example}\n\nHowever, only special cases of the conjecture have been proven to date. The first general result, proven by Coates and Wiles, states that an elliptic curve $ E $ with $ L\\rb{E, 1} \\ne 0 $ and \\emph{complex multiplication}, or when $ \\abs{End\\rb{E}} $ is strictly larger than $ \\Z $, has finite $ E\\rb{\\Q} $, and hence $ rk\\rb{E\\rb{\\Q}} = 0 $. A later result, proven by Gross and Zagier with \\emph{Heegner points}, states that a \\emph{modular} elliptic curve $ E $ with $ L\\rb{E, 1} = 0 $ and $ \\rb{d / ds}L\\rb{E, 1} \\ne 0 $, or equivalently $ rk_{an}\\rb{E\\rb{\\Q}} = 1 $, has a non-torsion rational point in $ E\\rb{\\Q} $, and hence $ rk\\rb{E\\rb{\\Q}} > 0 $. Subsequently, Kolyvagin extended this proof by showing that $ rk\\rb{E\\rb{\\Q}} = 1 $ must hold for this latter case, and that $ rk\\rb{E\\rb{\\Q}} = 0 $ if $ L\\rb{E, 1} \\ne 0 $ instead. With the modularity theorem proven by Breuil et al, it is now known that any elliptic curve over $ \\Q $ is modular, hence proving the following special case of the Birch and Swinnerton-Dyer conjecture.\n\n\\begin{theorem}[Breuil, Coates, Conrad, Diamond, Gross, Kolyvagin, Taylor, Wiles, Zagier]\n$ rk\\rb{E\\rb{\\Q}} = rk_{an}\\rb{E\\rb{\\Q}} $ for $ rk_{an}\\rb{E\\rb{\\Q}} \\in \\cb{0, 1} $.\n\\end{theorem}\n\n\\begin{proof}\nOmitted, see \\cite{bsd1}, \\cite{bsd2}, \\cite{bsd3}, and \\cite{modularity}.\n\\end{proof}\n\nThe very recent result due to Bhargava and Shankar in \\cite{rankaverage} also showed that a large proportion of all elliptic curves must have either rank zero or one, but the conjecture still remain unproven for elliptic curves with higher ranks. Now as a Millenium Prize Problem, the Birch and Swinnerton-Dyer conjecture has significant implications in number theory, particularly on finiteness of the Tate-Shafarevich group, but it also proves other more elementary results, one of which concerns integers with the following property.\n\n\\begin{definition}[Congruent number]\n$ n \\in \\Z_{> 0} $ is a \\textbf{congruent number} iff it is the area of some right triangle with sides in $ \\Q_{> 0} $.\n\\end{definition}\n\nCongruent numbers can be illustrated with the following example.\n\n\\begin{example}\n$ 5 = \\tfrac{1}{2}\\rb{3 / 2}\\rb{20 / 3} $ is a congruent number since it is the area of the right triangle with sides $ 3 / 2, 20 / 3, 41 / 6 \\in \\Q_{> 0} $, while $ 10 $ is not a congruent number.\n\\end{example}\n\nAn open problem is the classification of all congruent numbers, known as the \\emph{congruent number problem}, which boils down to obtaining simultaneous solutions for $ a^2 + b^2 = c^2 $ and $ 2n = ab $, for some $ n \\in \\Z_{> 0} $ and some $ a, b, c \\in \\Q_{> 0} $. Considering the non-zero inverse transformations\n$$ \\rb{x, y} = \\rb{\\dfrac{n\\rb{a + c}}{b}, \\dfrac{2n^2\\rb{a + c}}{b^2}}, \\qquad \\rb{a, b, c} = \\rb{\\dfrac{\\rb{x^2 - n^2}}{y}, \\dfrac{2nx}{y}, \\dfrac{\\rb{x^2 + n^2}}{y}}, $$\nthe system of equations can be transformed with a bijective correspondence to the Weierstrass equation $ y^2 = x^3 - n^2x $. Hence checking whether $ n $ is a congruent number is in turn equivalent to determining whether an affine rational point with non-zero coordinates exists in the elliptic curve $ E : y^2 = x^3 - n^2x $ over $ \\Q $. This prompts the following theorem that further classify the conditions for being a congruent number.\n\n\\begin{theorem}[Tunnell]\nLet $ n \\in \\Z_{> 0} $ be a square-free congruent number. If $ n $ is odd, then\n$$ 2\\abs{\\cb{\\rb{x, y, z} \\in \\Z^3 \\mid n = 2x^2 + y^2 + 32z^2}} = \\abs{\\cb{\\rb{x, y, z} \\in \\Z^3 \\mid n = 2x^2 + y^2 + 8z^2}}. $$\nOtherwise $ n $ is even, then\n$$ 2\\abs{\\cb{\\rb{x, y, z} \\in \\Z^3 \\mid n = 2\\rb{4x^2 + y^2 + 32z^2}}} = \\abs{\\cb{\\rb{x, y, z} \\in \\Z^3 \\mid n = 2\\rb{4x^2 + y^2 + 8z^2}}}. $$\n\\end{theorem}\n\n\\begin{proof}\nOmitted, see \\cite{tunnell}.\n\\end{proof}\n\nThe Birch and Swinnerton-Dyer conjecture, on the other hand, provides the converse to Tunnell's theorem, hence giving a single criterion for any congruent number that can be checked by enumerating the four sets involved. The following example illustrates the process, assuming the conjecture.\n\n\\begin{example}\nSince $ 5 $ is an odd square-free congruent number, it holds that\n$$ 2\\abs{\\cb{\\rb{x, y, z} \\in \\Z^3 \\mid 5 = 2x^2 + y^2 + 32z^2}} = 0 = \\abs{\\cb{\\rb{x, y, z} \\in \\Z^3 \\mid 5 = 2x^2 + y^2 + 8z^2}}. $$\nConversely, since $ 10 $ is an even square-free non-congruent number, it holds that\n$$ 2\\abs{\\cb{\\rb{x, y, z} \\in \\Z^3 \\mid n = 2\\rb{4x^2 + y^2 + 32z^2}}} = 8 \\ne 4 = \\abs{\\cb{\\rb{x, y, z} \\in \\Z^3 \\mid n = 2\\rb{4x^2 + y^2 + 8z^2}}}. $$\n\\end{example}\n\nAs such, the conjecture, if proven even only for elliptic curves given by the Weierstrass equation $ y^2 = x^3 - n^2x $, would allow the congruence number problem to be fully resolved.\n\n\\pagebreak\n\n\\section{Applications}\n\nIn this section, two elementary applications of elliptic curves are briefly touched on, together with a brief history of their development prior to elliptic curves.\n\n\\subsection{Arithmetic}\n\nIn arithmetic, the widely known fact that $ \\Z $ is a unique factorisation domain acts as the modern rephrasing of the fundamental theorem of arithmetic, which states that any integer can be uniquely written as a product of primes up to rearrangement and sign. An classical problem in arithmetic is determining these primes, or more commonly known as integer factorisation, for a given huge integer $ N \\in \\Z_{> 0} $ with tens of digits. Clearly no work is required if $ N $ is prime, which can be verified for most cases by the following theorem.\n\n\\begin{theorem}[Fermat's little theorem]\nLet $ N $ be prime. Then $ a^{N - 1} \\equiv 1 \\mod N $ for any $ a \\in \\Z_{> 0} $ such that $ N \\nmid a $.\n\\end{theorem}\n\n\\begin{proof}\nSince $ N \\nmid a $, it holds that $ a \\not\\equiv 0 \\mod N $, so $ a \\in \\Z_N^* $. Lagrange's theorem gives $ ord\\rb{a} \\mid \\abs{\\Z_N^*} = N - 1 $, so $ a^{N - 1} = 1 $. Thus $ a^{N - 1} \\equiv 1 \\mod N $.\n\\end{proof}\n\nUnfortunately, its converse does not hold, due to the existence of \\emph{Carmichael numbers}, which are composite integers that seemingly satisfy Fermat's little theorem, the first of which being relatively small at $ 561 $. These integers can be avoided manually due to their relative rarity, but there are indeed more reliable tests to check if $ N $ is prime. Now simply assume that $ N $ is composite, with an unknown large prime factor $ p \\in \\Z_{> 0} $. On first sight, there is a simple naive approach to factorise $ N $ involving trial division, applying Euclidean division to every positive integer less than $ N $. A clear improvement can be made by only considering $ 2, 3 $ and integers of the form $ 6m \\pm 1 $, which is illustrated in the following example with a small value of $ N $.\n\n\\begin{example}\nLet $ N = 420 $ be composite. Trial division on $ \\cb{2, 3, 5, 7, \\dots} $ gives $ 420 = 2\\rb{210} + 0 $ and $ 210 = 2\\rb{105} + 0 $, but $ 105 = 2\\rb{52} + 1 $. Now $ 105 = 3\\rb{35} + 0 $, but $ 35 = 3\\rb{11} + 2 $. Then $ 35 = 7\\rb{5} + 0 $, but $ 7 = 1\\rb{5} + 2 $. Finally $ 7 = 1\\rb{7} + 0 $. Thus $ L' = \\cb{2, 2, 3, 5, 7} $ and $ N = \\rb{2}\\rb{2}\\rb{3}\\rb{5}\\rb{7} $.\n\\end{example}\n\nIt is immediately evident that this process of factorising $ N $ into $ p $ and $ N / p $ is laborious, and especially difficult if $ N / p $ is also prime and relatively similar in magnitude to $ p $, since every integer below $ p $ and $ N / p $ will be checked for failure. In fact, while multiplying $ p $ and $ N / p $ to produce $ N $ is relatively easy, there are no known efficient \\emph{non-quantum} polynomial time algorithms to deterministically do the reverse, of which is exactly the basis of modern cryptography. The fastest methods for integer factorisation involve either \\emph{sieves} or elliptic curves, the latter of which discussed here has motivations stemming from the classical \\emph{Pollard's $ p - 1 $ method}. The following definition, considering a fixed integer $ B \\in \\Z_{> 0} $, will be used.\n\n\\begin{definition}[$ B $-power smooth]\nLet $ n \\in \\Z_{> 0} $ be such that $ n = p_1^{e_1} \\dots p_n^{e_n} $ for some $ e_i \\in \\Z_{> 0} $ and some primes $ p_i \\in \\Z_{> 0} $. Then $ n $ is \\textbf{$ B $-power smooth} iff each $ p_i^{e_i} \\le B $.\n\\end{definition}\n\nThis definition is illustrated in the following example.\n\n\\begin{example}\n$ 420 $ is $ 7 $-smooth, and $ 2\\rb{420} $ is not $ 7 $-smooth but is $ 8 $-smooth.\n\\end{example}\n\n$ B $ is typically chosen to be fairly large, such that the composite integer $ p - 1 $ is likely to be $ B $-power smooth. Now let $ l_B = \\text{lcm}\\rb{2, \\dots, B} $, so that any prime below $ B $ divides $ l_B $, and so $ p - 1 \\mid l_B $. The algorithm again uses Fermat's little theorem to give $ a^{l_B} \\equiv 1 \\mod p $ for any $ a \\in \\Z_{> 0} $ such that $ p \\nmid a $. Hence $ p \\mid a^{l_B} - 1 $, so letting $ g_B = \\gcd\\rb{a^{l_B} - 1, N} $ gives $ p \\mid g_B \\mid N $. Obtaining $ g_B < N $ immediately implies that $ g_B $ is a proper divisor of $ N $, so the process can be repeated replacing $ N $ with $ g_B $. The algorithm is summarised as follows.\n\n\\begin{algorithm}[Pollard's $ p - 1 $ method]\nInput: an integer $ N \\in \\Z_{> 0} $. Output: a proper divisor of $ N $.\n\\begin{enumerate}\n\\item Choose a \\emph{smoothness bound} $ B \\in \\Z_{> 0} $.\n\\item Calculate $ l_B = \\text{lcm}\\rb{1, \\dots, B} $.\n\\item Compute $ g_B = \\gcd\\rb{a^{l_B} - 1, N} $ for some $ a \\in \\cb{2, \\dots, N - 1} $.\n\\item If $ g_B = 1 $, then choose a larger smoothness bound $ B $, else if $ g_B = N $, then choose a different $ a $.\n\\item Otherwise $ 1 < g_B < N $, then return $ g_B $.\n\\end{enumerate}\n\\end{algorithm}\n\n\\pagebreak\n\n\\begin{remark}\nIn practicality, this $ B $ typically fixed, and a different algorithm is forcibly switched into if this algorithm fails, which would mean that Pollard's $ p - 1 $ algorithm only serves to simplify the problem.\n\\end{remark}\n\nA simple observation picks out several possible concerns in the algorithm, most obviously being the question if the algorithm even terminates, which must be the case, as the smoothness bound $ B $ will eventually be large enough for $ l_B $ to exceed $ p - 1 $. Another issue might be the speed of computing $ l_B $ and $ g_B $, with the latter seemingly depending on the former. This is resolved by the realisation that $ l_B $ is arbitrarily defined as such to allow all factors below $ B $ to divide $ l_B $, so a purely multiplicative $ l_B = B! $ can be used. While $ g_B $ may require further exponentiation, this is not a concern as modular exponentiation with successive squaring to compute $ a^{l_B} $ is fast, and the result of this can be used in the computation instead of $ a^{l_B} - 1 $. In the highly unlikely chance that $ p \\mid a $, a fix to this issue could be first doing trial division up to a small integer $ n \\in \\Z_{> 0} $ to rule out any possibility that $ p < n $, and only considering the cases where $ a < n $. With these concerns in mind, Pollard's $ p - 1 $ algorithm can be illustrated with the following example involving a small $ N $, which on modern computers can actually be done instantly even with trial division.\n\n\\begin{example}\nLet $ N = 246082373 $. Then $ 2^{N - 1} \\equiv 114193013 \\ne 1 \\mod N $, so Fermat's little theorem gives that $ N $ is composite. Now let $ B = 7 $ and $ l_B = \\text{lcm}\\rb{1, \\dots, B} = 420 $, and let $ a = 2 $. Then $ a^{l_B} \\equiv 60592910 \\mod N $, so $ \\gcd\\rb{a^{l_B} - 1, N} = \\gcd\\rb{60592909, N} = 1 $. Hence choose $ B = 9 > 7 $ and $ l_B = \\text{lcm}\\rb{1, \\dots, B} = 2520 $, and let $ a = 2 $. Then $ a^{l_B} \\equiv 130940741 \\mod N $, so $ \\gcd\\rb{a^{l_B} - 1, N} = \\gcd\\rb{130940740, N} = 2521 < N $. Thus $ 2521 \\mid N $ and $ N = \\rb{2521}\\rb{97613} $, which are both prime.\n\\end{example}\n\nA final serious concern would be overall efficiency of the algorithm that is only reasonable with the initial supposition that $ p - 1 $ is $ B $-power smooth, which may not always be the case, inevitably forcing large values of $ B $. Despite so, it may still be desirable to check the $ B $-power smoothness of $ p + 1 $, or even $ p \\pm n $ for any small $ n \\in \\Z $, to see if the initially fixed $ B $ is sufficient to factorise $ N $. In this respect, Pollard's $ p - 1 $ algorithm has no way of allowing for other values of $ p \\pm n $ due to the restriction given by Fermat's little theorem. Now \\emph{Lenstra's elliptic curve factorisation method} takes this flaw into account by considering multiple random elliptic curves over finite fields. While the former considers the multiplicative group $ \\Z_p^* $ of order $ \\abs{\\Z_p^*} = p - 1 $ and checks if $ a \\in \\Z_p^* $ satisfies $ a^{l_B} = 1 $, the latter considers the elliptic curve $ E\\rb{\\F_p} $ of order $ \\abs{E\\rb{\\F_p}} = p - t + 1 $ and checks if $ P \\in E\\rb{\\F_p} $ satisfies $ l_BP = \\mathcal{O} $. Hasse's theorem gives $ \\abs{t} \\le 2\\sqrt{p} $, allowing $ \\abs{E\\rb{\\F_p}} $ to vary wildly within this interval and hence removing the aforementioned defect. The algorithm is stated as follows.\n\n\\begin{algorithm}[Lenstra's elliptic curve factorisation method]\nInput: an integer $ N \\in \\Z_{> 0} $. Output: a proper divisor of $ N $.\n\\begin{enumerate}\n\\item Set $ P = \\rb{a, b} $ and $ B = b^2 - a^3 - Aa $ for some $ A, a, b \\in \\cb{1, \\dots, N - 1} $.\n\\item If $ g = \\gcd\\rb{4A^3 + 27B^2, N} = N $, choose a different $ A $, else if $ 1 < g < N $, return $ g $, else let $ E : y^2 = x^3 + Ax + B $ be an elliptic curve over $ \\Q $, treated as over the ring $ \\Z_N^* $.\n\\item Choose a smoothness bound $ C $ and calculate $ l_C $ as per Pollard's $ p - 1 $ method.\n\\item Compute $ l_CP = \\rb{q / d^2, r / d^3} $ and $ g_C = \\gcd\\rb{d, N} $.\n\\item If $ g_C = 1 $, choose a larger $ C $ or a different $ A $, else if $ g_C = N $, choose a smaller $ C $, else return $ g_C $.\n\\end{enumerate}\n\\end{algorithm}\n\nA couple of remarks will be made on Lenstra's elliptic curve factorisation method, which has the first two steps markedly differently from Pollard's $ p - 1 $ method. The last three steps of the former mirror the latter, but it is worth noting that $ l_CP = \\mathcal{O} $ iff $ d = 0 $, which holds iff $ p \\mid d $, or $ p \\mid g_C = \\gcd\\rb{d, N} \\mid N $. While it is possible to directly obtain a random elliptic curve $ E : y^2 = x^3 + Ax + B $ over $ \\F_p $ by choosing some random $ A, B \\in \\Z $ and treating $ A, B $ as elements of $ \\F_p $, obtaining a point in $ E $ afterwards will involve the laborious process of finding a modular square root, and so the above approach is taken. Moreover, to avoid having $ P $ be a torsion point and hence resulting in $ N \\mid d $, a simple fix would be an additional condition to choose $ b^2 \\nmid 4A^3 + 27\\rb{A^3 + Aa} $ in this reverse approach, which by the contrapositive to the Nagell-Lutz theorem forces $ P $ to have infinite order. Again, computation of $ l_C $ will be done by successive duplication of points, but a concern arises from possibly having denominators $ d \\in \\Z_N $ being zero. Considering the cases when an inverse does not exist in $ \\Z_N^* $, or when $ \\gcd\\rb{d, N} > 1 $, either $ \\gcd\\rb{d, N} = N $, for which it is sufficient to simply choose a different curve $ E $, or $ 1 < \\gcd\\rb{d, N} < N $, for which $ \\gcd\\rb{d, N} $ can be returned as a proper divisor of $ N $. In practice, the affine coordinates are computed modulo $ N $, catching a division by zero error only when the extended Euclidean algorithm fails to give a modular inverse, then computing $ g_C $ separately. With these remarks at hand, Lenstra's elliptic curve factorisation method can be illustrated with the following example involving a small $ N $, which again can actually be done instantly with a modern computer.\n\n\\begin{example}\nLet $ N = 1715761513 $. Then $ 2^{N - 1} \\equiv 114094409 \\ne 1 \\mod N $, so Fermat's little theorem gives that $ N $ is composite. Let $ A = 1 $, $ a = 2 $, and $ b = 1 $, such that $ P = \\rb{2, 1} $ and $ B = 1^2 - 2^3 - 1\\rb{2} = -9 $. Then $ g = \\gcd\\rb{4A^3 + 27B^2, N} = 1 $, such that $ E : y^2 = x^3 + x - 9 $ is an elliptic curve over $ \\Q $. Now let $ C = 17 $ and $ l_C = \\text{lcm}\\rb{1, \\dots, C} = 12252240 $. Then $ l_CP = \\rb{1225303014, 142796033} $, so $ \\rb{d, N} = 1 $. Instead of choosing a larger $ C $, choose a different $ A \\in \\cb{2, \\dots, N} $ and recompute. Then $ A = 42 $ eventually returns $ \\rb{d, N} = 26927 $. Thus $ 26927 \\mid N $ and $ N = \\rb{26927}\\rb{63719} $, which are both prime.\n\\end{example}\n\nAs seen above, if choosing a different $ A $ does not work, a larger $ C $ could be tried, or even picking a different $ P = \\rb{a, b} $ if all else fails, a sign of high algorithmic flexibility. While it may involve more sophistication and possibly a larger overhead in maintaining the elliptic curve data structure than Pollard's $ p - 1 $ method, Lenstra's elliptic curve factorisation method \\emph{heuristically} runs at sub-exponential time complexity, due to a high probability that an integer is $ B $-power smooth within the interval in Hasse's theorem.\n\n\\begin{remark}\nUsing Pollard's $ p - 1 $ algorithm for this example will require $ B \\ge 13463 $, which will take a while.\n\\end{remark}\n\nWith the discussion on factorising the composite $ N $ completed, the initial question of checking if $ N $ is prime makes a comeback. After all, probabilistic factorisation algorithms may never terminate if $ N $ was never composite in the first place. Again, there is a trivial method to do this, which involves factoring $ N $ by trial division, Fermat's little theorem, or any other factorisation methods and hoping to result in a definite failure. While there were subsequent developments on fast non-deterministic tests, such as \\emph{Miller-Rabin}, that do not rely on factorisation but on Fermat's little theorem instead, the remaining discussion here focuses on one of the fastest \\emph{primality tests} that involves elliptic curves. In contrast to factorisation, currently doable for tens to hundreds of digits, the primality of integers up to tens of thousands of digits have been proven.\n\n\\begin{remark}\nThese forms of primality testing hold for arbitrary integers, but there are certain classes of huge integers that have been proven to be primes using specialised methods. For instance, the largest integer ever proven to be a prime is a \\emph{Mersenne prime} that has tens of millions of digits.\n\\end{remark}\n\nThe said primality test is also an elliptic curve version of another classical primality test, known as the \\emph{Pocklington-Lehmer primality test}, which has its basis on the following theorem.\n\n\\begin{theorem}[Pocklington-Lehmer]\n\\label{thm:pocklington}\nLet $ r \\in \\Z_{> 0} $ be such that $ r \\mid N - 1 $ and $ r \\ge \\sqrt{N} $. Then $ N $ is prime if\n$$ a_q^{N - 1} \\equiv 1 \\mod N, \\qquad \\gcd\\rb{a_q^{\\rb{N - 1} / q} - 1, N} = 1, \\qquad a_q \\in \\Z_{> 0}, $$\nfor any prime $ q \\in \\Z_{> 0} $ such that $ q \\mid r $.\n\\end{theorem}\n\n\\begin{proof}\nLet $ p \\in \\Z_{> 0} $ be a prime such that $ p \\mid N $, so $ p $ is a prime of good reduction, and let $ v = v_q\\rb{r} $ be the $ q $-adic valuation of $ r $. Now let $ a \\equiv a_q^{\\rb{N - 1} / q^v} \\mod p $ for some $ a \\in \\Z_p^* $. Then $ a^{q^v} = a_q^{N - 1} \\equiv 1 \\mod p $ and $ a^{q^{v - 1}} = a_q^{\\rb{N - 1} / q} \\not\\equiv 1 \\mod p $. Hence $ ord\\rb{a} = q^v $. Lagrange's theorem gives $ q^v \\mid \\abs{\\Z_p^*} = p - 1 $, so $ r \\mid p - 1 $ and $ p > r \\ge \\sqrt{N} $. Thus $ p = N $ and $ N $ is prime.\n\\end{proof}\n\nAgain, a simple observation points that integer factorisation is involved in finding $ r $, as well as its prime factors $ q $. Similar to Pollard's $ p - 1 $ method, a prior assumption is required for the algorithm to run at a reasonable time, namely that $ p - 1 $ has many small factors $ q $ that allow $ r $ to be generated quickly with trial division. It is also worth noting that finding $ a_q $ is equivalent to finding a generator of the group $ \\Z_p^* $, which might be laborious, but often letting $ a_q = 2 $ works. The test algorithm then simply follows from the theorem, but it is desirable to have a third party mechanism that checks validity of the primality proof, which will also help ensure functional correctness of implementations. In particular, the notion of a \\emph{primality certificate}, which is an ordered pair $ \\rb{r, c} $ as in Theorem \\ref{thm:pocklington}, where $ c $ is a list of ordered pairs $ \\rb{q, a_q} $, allows for a verification by simple modular exponentiation. The Pocklington-Lehmer primality test can be illustrated with a much larger value of $ N $ in the following example, owing to the fact that $ N - 1 $ has many small factors.\n\n\\begin{example}\nLet $ N = 9223372036854775783 $. Then $ N - 1 = 9223372036854775782 $. Trial division for primes less than $ 400000 $ gives $ r = \\rb{2}\\rb{3}^4\\rb{17}\\rb{23}\\rb{319279} \\mid N - 1 $, such that $ r = 20223770418 \\ge \\sqrt{N} $. Then\n$$ 2^{N - 1} \\equiv 3^{N - 1} \\equiv 1 \\mod N, \\qquad \\gcd\\rb{2^{\\rb{N - 1} / 3} - 1, N} = \\gcd\\rb{3^{\\rb{N - 1} / 2} - 1, N} = 1, $$\n$$ \\gcd\\rb{2^{\\rb{N - 1} / 17} - 1, N} = \\gcd\\rb{2^{\\rb{N - 1} / 23} - 1, N} = \\gcd\\rb{2^{\\rb{N - 1} / 319279} - 1, N} = 1. $$\nThus $ N $ is prime with primality certificate $ \\rb{r, \\sb{\\rb{2, 3}, \\rb{3, 2}, \\rb{17, 2}, \\rb{23, 2}, \\rb{319279, 2}}} $.\n\\end{example}\n\nAs for Lenstra's elliptic curve factorisation method, an elliptic curve analogue attempts to fix the $ p - 1 $ assumption by virtue of Hasse's theorem. By first choosing $ A, a, b \\in \\Z_N^* $, a valid elliptic curve over the ring $ \\Z_N^* $ is considered, giving the following analogous theorem.\n\n\\begin{theorem}[Goldwasser-Kilian]\nLet $ E : y^2 = x^3 + Ax + B $ be an elliptic curve over $ \\Q $ such that $ \\gcd\\rb{4A^3 + 27B^2, N} = 1 $, treated as over the ring $ \\Z_N^* $, and let $ m \\in \\Z_{> 0} $ be such that $ m > \\rb{\\sqrt[4]{N} + 1}^2 $. Then $ N $ is prime if\n$$ mP_q = \\mathcal{O}, \\qquad \\dfrac{m}{q}P_q \\ne \\mathcal{O}, \\qquad P_q \\in E\\rb{\\Q} \\setminus \\cb{\\mathcal{O}}, $$\nfor any distinct prime $ q \\in \\Z_{> 0} $ such that $ q \\mid m $.\n\\end{theorem}\n\n\\begin{proof}\nLet $ p \\in \\Z_{> 0} $ be a prime such that $ p \\mid N $, and let $ v = v_q\\rb{m} $ be the $ q $-adic valuation of $ m $. Now let $ r_p : E\\rb{\\Q} \\to E_p\\rb{\\F_p} $ be the reduction modulo $ p $ map, and let $ P_q' = \\rb{m / q^v}r_p\\rb{P_q} $. Then $ q^vP_q' = mr_p\\rb{P_q} = \\mathcal{O} $ and $ q^{v - 1}P_q' = \\rb{m / q}r_p\\rb{P_q} \\ne \\mathcal{O} $. Hence $ ord\\rb{P_q'} = q^v $. Lagrange's theorem gives $ q^v \\mid \\abs{E_p\\rb{\\F_p}} $, so $ m \\mid \\abs{E_p\\rb{\\F_p}} $. Now Hasse's theorem gives\n$$ \\rb{\\sqrt[4]{N} + 1}^2 < m \\le \\abs{E_p\\rb{\\F_p}} \\le p + 2\\sqrt{p} + 1 = \\rb{\\sqrt{p} + 1}^2. $$\nHence $ p > \\sqrt{N} $. Thus $ p = N $ and $ N $ is prime.\n\\end{proof}\n\nAs for the Pocklington-Lehmer primality test, an appropriate primality certificate, possibly with the form of an ordered triple $ \\rb{m, A, c} $ as in Theorem \\ref{thm:pocklington}, where $ c $ is a list of ordered pairs $ \\rb{q, P_q} $, will act as the output of a successful test. With all previous considerations, the Goldwasser-Kilian primality test can be illustrated with an even larger value of $ N $ in the following example.\n\n\\begin{example}\nLet $ N = 9223372036854775907 $. Instead let $ A = -2 $, $ a = 2 $, and $ b = 0 $, such that $ P = \\rb{2, 0} $ and $ B = 0^2 - 2^3 - -2\\rb{-2} = -4 $. Then $ \\gcd\\rb{4A^3 + 27B^2, N} = 1 $, such that $ E : y^2 = x^3 - 2x - 4 $ is an elliptic curve over $ \\Q $. Now let $ m = \\rb{2}\\rb{11}\\rb{13}\\rb{37}\\rb{269}\\rb{1327} = 3777382466 $ such that $ \\rb{\\sqrt[4]{N} + 1}^2 < 3037110719 < m $. Then $ ord\\rb{P} = 2 $, so $ mP = \\mathcal{O} $, and\n$$ \\dfrac{m}{2}P \\ne \\mathcal{O}, \\qquad \\dfrac{m}{11}P \\ne \\mathcal{O}, \\qquad \\dfrac{m}{13}P \\ne \\mathcal{O}, \\qquad \\dfrac{m}{37}P \\ne \\mathcal{O}, \\qquad \\dfrac{m}{269}P \\ne \\mathcal{O}, \\qquad \\dfrac{m}{1327}P \\ne \\mathcal{O}. $$\nThus $ N $ is prime with primality certificate $ \\rb{m, -2, \\sb{\\rb{2, P}, \\rb{11, P}, \\rb{13, P}, \\rb{37, P}, \\rb{269, P}, \\rb{1327, P}}} $.\n\\end{example}\n\nThe heart of the algorithm lies on finding a suitable elliptic curve $ E\\rb{\\Q} $, which in the above example is seemingly conjured from thin air. As for Lenstra's elliptic curve factorisation method, many random values of $ A $, $ a $, and $ b $ are generated, until their corresponding elliptic curve is found to have an order with enough small distinct prime factors to multiply and exceed $ \\rb{\\sqrt[4]{N} + 1}^2 $. This order $ E_p\\rb{F_p} $ is in turn efficiently computed through the Schoof-Elkies-Atkin algorithm.\n\n\\begin{remark}\nUsing the Pocklington-Lehmer primality test for this example will require $ r \\ge 273901883852669 $, which is a prime and will take forever, even with a supercomputer.\n\\end{remark}\n\nMost algorithms in this subsection are given in full under code listings in the appendix. Unfortunately, due to the difficulty in implementing Schoof's algorithm, the Goldwasser-Kilian primality test is omitted. Historically, Schoof's algorithm was seen as too cumbersome to implement, such that the theory of complex multiplication was utilised instead to construct an elliptic curve $ E $ with an easily computable order $ E_p\\rb{F_p} $. This became known as the \\emph{Atkin-Morain primality test}, which remained the fastest primality proving algorithm to date, despite the later advent of the much faster Schoof-Elkies-Atkin algorithm.\n\n\\pagebreak\n\n\\subsection{Cryptography}\n\n\\emph{Cryptography} is the study of computational techniques to allow for secure communication of information across public platforms in the presence of third party eavesdroppers. It is historically based on the computational intractability of certain mathematical problems, such as integer factorisation. As the difficult computations involved in elliptic curve point multiplication became more apparent, they saw great use in modern cryptography, of which a very brief introduction will be provided in this short subsection. With the standard notation of three parties, namely \\emph{Alice}, the sender, \\emph{Bob}, the receiver, and \\emph{Eve}, the eavesdropper, the standard process of secure communication is as follows.\n\n\\begin{algorithm}[Communication across a public domain]\nAlice sends a message to Bob.\n\\begin{enumerate}\n\\item Alice intends to send a \\emph{plaintext} message $ P $ to Bob, without Eve eavesdropping.\n\\item Alice \\emph{encrypts} $ P $ with an \\emph{encryption key} $ E $, which is owned only by Alice.\n\\item The \\emph{ciphertext} message $ C = E\\rb{P} $ is sent across a public domain, from Alice to Bob.\n\\item Bob \\emph{decrypts} $ C $ with a \\emph{decryption key} $ D $, which is owned only by Bob.\n\\item Bob recovers $ P = D\\rb{C} $ from Alice.\n\\end{enumerate}\n\\end{algorithm}\n\nIn this setup, it is clear that Bob should never leak $ D $ to Eve so as to keep $ P $ secret, and that $ D $ must be the left inverse of $ E $. In the case of \\emph{symmetric encryption}, the right inverse property also holds, allowing for the roles of $ E $ and $ D $ to swap. However, Alice and Bob would then need to secretly agree on $ E $ and $ D $ in advance, which may be infeasible if there are no means for prior contact. \\emph{Asymmetric encryption} solves this problem by introducing two pairs of inverse keys for Alice and Bob, such that they would publish their respective encryption keys $ E_A $ and $ E_B $, while hiding their respective decryption keys $ D_A $ and $ D_B $. Whenever Alice intends to send $ P $ to Bob, Alice would send $ C = E_B\\rb{P} $ across the public domain, so that only Bob could recover $ P = D_B\\rb{C} $, or vice versa. The modern \\emph{Rivest-Shamir-Adleman cryptosystem}, or more commonly known as the \\emph{RSA}, is a asymmetric encryption system that has its basis on the difficulty of integer factorisation, and is given in the following algorithm.\n\n\\begin{algorithm}[Rivest-Shamir-Adleman cryptosystem]\nOutputs a pair of keys.\n\\begin{enumerate}\n\\item Choose two distinct huge prime numbers $ p, q \\in \\Z_{> 0} $ of similar magnitude and compute $ n = pq $.\n\\item Compute $ \\lambda\\rb{n} = \\text{lcm}\\rb{p - 1, q - 1} $ and choose a small $ e \\in \\Z_{> 0} $ such that $ \\gcd\\rb{e, \\lambda\\rb{n}} = 1 $.\n\\item Compute the multiplicative inverse $ d $ of $ e $ modulo $ \\lambda\\rb{n} $.\n\\item Return the public encryption key $ \\rb{n, e} $ and function $ E\\rb{P} \\equiv P^e \\mod n $.\n\\item Return the private decryption key $ \\rb{n, d} $ and function $ D\\rb{C} \\equiv C^d \\mod n $.\n\\end{enumerate}\n\\end{algorithm}\n\nThe functional correctness of the algorithm trivially follows from Fermat's little theorem, and as such will not be discussed. Now $ e $ is typically chosen to be small enough for quick encryption computations, but not too small so as to be insecure. Moreover $ P $ is also assumed to have been translated into an integer beforehand with some form of \\emph{padded} cipher mechanism. The following example implements the RSA.\n\n\\begin{example}\nLet $ p = 2147483647 $ and $ q = 2147483659 $ be primes. Then $ n = pq = 4611686039902224373 $ and $ \\lambda\\rb{n} = \\text{lcm}\\rb{p - 1, q - 1} = 768614339267876178 $. Now choose a public encryption key $ n $ and $ e = 65537 $ such that $ \\gcd\\rb{e, \\lambda\\rb{n}} = 1 $. Thus the private decryption key is $ n $ and $ d = 73205833433176421 \\equiv e^{-1} \\mod l $.\n\\end{example}\n\nNow the availability of increasingly powerful techniques imposes a minimum bit size of $ p $ and $ q $ in order to make the RSA even remotely practical. Furthermore, the presence of specialised algorithms, such as Pollard's $ p - 1 $ method, forces a requirement on $ p - 1 $ and $ q - 1 $ to have large factors to prevent unprecedented \\emph{attacks} as well. To date, a few hundred bits of $ n $ is easily factorisable by a desktop computer within hours, if not seconds, with a suitably powerful algorithm. As such, the RSA generally chooses an $ n $ with thousands of bits, which is somewhat cumbersome for massive amounts of data, and would require larger chip sizes and power consumption in the process of encryption. On the other hand, this drawback is less evident in symmetric encryption systems, which are generally faster if $ E $ and $ D $ were somehow agreed by Alice and Bob in advance. This could be feasibly done without any prior contact with the following \\emph{key exchange protocol}.\n\n\\begin{algorithm}[Diffie-Hellman key exchange]\nOutputs a private symmetric key.\n\\begin{enumerate}\n\\item Alice and Bob agree on a huge prime $ p \\in \\Z_{> 0} $ and a small $ g \\in \\Z_{> 0} $ such that $ g < p $.\n\\item Alice chooses $ a \\in \\Z_{> 0} $ such that $ a < p $ and sends $ g_a \\equiv g^a \\mod p $ to Bob across the public domain.\n\\item Bob chooses $ b \\in \\Z_{> 0} $ such that $ b < p $ and sends $ g_b \\equiv g^b \\mod p $ to Alice across the public domain.\n\\item Alice computes $ s \\equiv g_b^a \\equiv g^{ab} \\mod p $ privately.\n\\item Bob computes $ s \\equiv g_a^b \\equiv g^{ab} \\mod p $ privately.\n\\end{enumerate}\n\\end{algorithm}\n\nThe algorithm simply uses basic properties of modular exponentiation and produces a private symmetric key $ s $ between Alice and Bob, which as aforementioned allows secure communication in a public domain. In this process, only $ p $, $ g $, $ g_a $, and $ g_b $ is immediately available to Eve, while $ a $, $ b $, and $ s $ are kept secret between Alice and Bob. The following example implements the Diffie-Hellman key exchange.\n\n\\begin{example}\nLet $ p = 2147483647 $ be prime and $ g = 65537 $. Alice chooses $ a = 16777259 $ and sends the public key $ g_a = 751856369 \\equiv g^a \\mod p $ to Bob, while Bob chooses $ b = 16777289 $ and sends the public key $ g_b = 1654172966 \\equiv g^b \\mod p $ to Alice. Thus the private symmetric key is $ s = 1288974049 \\equiv g^{ab} \\mod p $.\n\\end{example}\n\nReverse engineering these values as a third party attacker is known as the \\emph{discrete logarithm problem}, which is, analogous to integer factorisation, computationally infeasible provided $ p $ is chosen to be huge. While there is an impossibly slow, naive approach by simply trying $ g^n $ for each $ n \\in \\Z_{> 0} $ until $ g^n = g^a $ or $ g^n = g^b $ is obtained, there are no known algorithms efficient enough to crack the system.\n\n\\begin{remark}\nUnfortunately, the non-existence of efficient polynomial time algorithms for integer factorisation and the discrete logarithm problem is unproven. In fact, a \\emph{quantum computer} running \\emph{Shor's algorithm} would theoretically do both of these in polynomial time.\n\\end{remark}\n\nRephrasing the Diffie-Hellman key exchange in terms of finite cyclic groups, modulo operations involving $ p $ is equivalent to operating under the finite multiplicative cyclic group $ \\Z_p^* $, while $ g $ is simply any generator of $ \\Z_p^* $. A elliptic curve variant of Diffie-Hellman can then be stated easily as follows.\n\n\\begin{algorithm}[Elliptic curve Diffie-Hellman]\nOutputs a private symmetric key.\n\\begin{enumerate}\n\\item Alice and Bob agree on an elliptic curve $ E $ over $ \\F_p $ for some prime $ p \\in \\Z_{> 0} $ and a point $ P \\in E\\rb{\\F_p} $.\n\\item Alice chooses $ a \\in \\Z_p^* $ and sends $ P_a = aP $ to Bob across the public domain.\n\\item Bob chooses $ b \\in \\Z_p^* $ and sends $ P_b = bP $ to Alice across the public domain.\n\\item Alice computes $ S = a\\rb{P_b} = a\\rb{bP} = abP $ privately.\n\\item Bob computes $ S = b\\rb{P_a} = b\\rb{aP} = abP $ privately.\n\\end{enumerate}\n\\end{algorithm}\n\nThe prior example can then be illustrated with elliptic curve Diffie-Hellman as follows.\n\n\\begin{example}\nLet $ E : y^2 = x^3 + 65537x + 1 $ be an elliptic curve over $ \\F_p $ where $ p = 2147483647 $ and $ P = \\rb{0, 1} \\in E\\rb{\\F_p} $. Alice chooses $ a = 16777259 $ and sends the public key $ P_a = aP = \\rb{675295473, 1821381850} $ to Bob, while Bob chooses $ b = 16777289 $ and sends the public key $ P_b = bP = \\rb{294235749, 438747352} $ to Alice. Thus the private symmetric key is $ S = abP = \\rb{1210475635, 471187571} $.\n\\end{example}\n\nThe discrete logarithm problem on certain elliptic curves over finite fields is also significantly harder than that of generic finite fields, and as such a list of recommended elliptic curves for use in key exchanges was published publicly by the National Institute of Standards and Technology. These elliptic curves are used in several other cryptosystems, such as the underlying group of the \\emph{ElGamal encryption system}, or in other cryptographic contexts, such as \\emph{digital signatures}, but will not be discussed further. Most of these elliptic curve based systems require fewer bits than those based on traditional finite fields. An estimate places a key size of less than $ 2^9 $ bits having an equivalent security to a key size of $ 2^{12} $ bits for the RSA.\n\n\\begin{remark}\nUnfortunately, the discrete logarithm problem for elliptic curves is still susceptible to attacks from a quantum computer. The \\emph{supersingular isogeny key exchange} is an analogue of Diffie-Hellman that considers isogenies, and would in theory resist quantum attacks, but has a higher performance overhead.\n\\end{remark}\n\n\\pagebreak\n\n\\appendix\n\n\\section{Preliminaries}\n\n\\subsection{Rings and fields}\n\nLet $ R $ be a commutative unital ring and $ F \\subseteq K \\subseteq L $ be fields.\n\n\\begin{definition}[Automorphism]\nAn \\textbf{automorphism} of $ R $ is an isomorphism from $ R $ to itself, which are elements of the \\textbf{automorphism group} $ Aut\\rb{R} $ with respect to composition.\n\\end{definition}\n\n\\begin{example}\n$ id_R $ is an automorphism of $ R $.\n\\end{example}\n\n\\begin{definition}[Prime ideal]\nAn ideal $ I \\subset R $ is \\textbf{prime} iff $ ab \\in I $ implies $ a \\in I $ or $ b \\in I $ for any two elements $ a, b \\in I $.\n\\end{definition}\n\n\\begin{example}\nAn irreducible element $ r \\in R $ in a unique factorisation domain $ R $ generates a prime ideal $ \\ab{r} $.\n\\end{example}\n\n\\begin{definition}[Chain]\nA \\textbf{chain} of subsets in $ R $ of length $ n \\in \\Z_{\\ge 0} $ is a sequence of distinct subsets $ S_0 \\subset \\dots \\subset S_n \\subset R $.\n\\end{definition}\n\n\\begin{example}\n$ \\ab{0} \\subset \\ab{x_1} \\subset \\dots \\subset \\ab{x_1, \\dots, x_n} \\subset F\\sb{x_1, \\dots, x_n} $ is a chain of prime ideals of length $ n $.\n\\end{example}\n\n\\begin{definition}[Characteristic]\nThe \\textbf{characteristic} $ char\\rb{F} $ of $ F $ is the smallest $ n \\in \\Z_{> 0} $, if it exists, such that $ n \\cdot 1 = 1 + \\dots + 1 = 0 $. Otherwise $ char\\rb{F} $ is $ 0 $.\n\\end{definition}\n\n\\begin{example}\n$ char\\rb{\\C} = char\\rb{\\R} = char\\rb{\\Q} = 0 $ while $ char\\rb{\\F_{p^e}} = p $ for prime $ p \\in \\Z_{> 0} $ and $ e \\in \\Z_{\\ge 0} $.\n\\end{example}\n\n\\begin{definition}[Field extension]\n$ K $ is a \\textbf{field extension} of $ F $, denoted by $ K / F $, iff $ F $ is a subfield of $ K $.\n\\end{definition}\n\n\\begin{example}\n$ \\C / \\R $, $ \\R / \\Q $, $ \\C / \\Q $, and $ \\F_{p^e} / \\F_{p^{e'}} $ for prime $ p \\in \\Z_{> 0} $ and $ e \\mid e' $ are field extensions.\n\\end{example}\n\n\\begin{definition}[$ F $-homomorphism]\nAn \\textbf{$ F $-homomorphism} from $ K / F $ to another field extension $ K' / F $ is a field homomorphism $ \\phi : K \\to K' $ such that $ \\val{\\phi}_F = \\val{id}_F $. The definitions of \\textbf{$ F $-isomorphism} and \\textbf{$ F $-automorphism} extend naturally, with $ Aut_F\\rb{K} $ denoting the \\textbf{$ F $-automorphism group} of $ K $.\n\\end{definition}\n\n\\begin{example}\nComplex conjugation is an $ \\R $-automorphism of $ \\C $.\n\\end{example}\n\n\\begin{definition}[Finite extension]\n$ K / F $ is \\textbf{finite} iff the dimension $ dim_F K $ of $ K $ as a vector space over $ F $ is finite.\n\\end{definition}\n\n\\begin{example}\n$ \\C / \\R $ is a finite extension with $ \\sb{\\C : \\R} = 2 $ since $ \\cb{1, i} $ is a basis of $ \\C $ over $ \\R $.\n\\end{example}\n\n\\begin{definition}[Finitely generated]\n$ F\\rb{s_1, \\dots, s_n} $ is \\textbf{finitely generated} by $ s_1, \\dots, s_n \\in K $ over $ F $ iff $ F\\rb{S} $ is the smallest subfield of $ K $ containing $ s_1, \\dots, s_n $ and the elements of $ F $.\n\\end{definition}\n\n\\begin{example}\n$ \\Q\\rb{\\sqrt{2}, \\sqrt{3}} $ is finitely generated by $ \\cb{\\sqrt{2}, \\sqrt{3}} $ over $ \\Q $, by $ \\cb{\\sqrt{2}} $ over $ \\Q\\rb{\\sqrt{3}} $, and by $ \\cb{\\sqrt{3}} $ over $ \\Q\\rb{\\sqrt{2}} $.\n\\end{example}\n\n\\begin{definition}[Number field]\n$ K $ is a \\textbf{number field} iff $ K / F $ is finite and $ F = \\Q $.\n\\end{definition}\n\n\\begin{example}\n$ \\Q\\rb{\\sqrt{d}} $ for square-free $ d \\in \\Z $ are number fields with $ \\sb{\\Q\\rb{\\sqrt{d}} : \\Q} = 2 $.\n\\end{example}\n\n\\begin{definition}[Algebraic element]\n$ \\alpha \\in K $ is \\textbf{algebraic} over $ F $ iff it is a root of some non-zero polynomial in $ F\\sb{x} $. Otherwise $ \\alpha $ is \\textbf{transcendental} over $ F $.\n\\end{definition}\n\n\\begin{example}\n$ \\pi $ is transcendental over $ \\Q $ but algebraic over $ \\R $ since it is the root of $ x - \\pi $.\n\\end{example}\n\n\\begin{definition}[Minimal polynomial]\nThe \\textbf{minimal polynomial} $ m_\\alpha $ of $ \\alpha $ over $ F $ is the unique monic irreducible polynomial in $ F\\sb{x} $ with $ \\alpha $ as a root.\n\\end{definition}\n\n\\begin{example}\nThe minimal polynomial of $ \\sqrt{2} $ is $ x^2 - 2 $ over $ \\Q $ and is $ x - \\sqrt{2} $ over $ \\R $.\n\\end{example}\n\n\\begin{definition}[Algebraic extension]\n$ K / F $ is \\textbf{algebraic} iff any element in $ K $ is algebraic over $ F $. Otherwise $ K / F $ is \\textbf{transcendental}.\n\\end{definition}\n\n\\begin{example}\n$ \\C / \\Q $ is not an algebraic extension since $ \\pi $ is transcendental over $ \\Q $.\n\\end{example}\n\n\\begin{definition}[Algebraically closed]\n$ F $ is \\textbf{algebraically closed} iff any non-constant polynomial in $ F\\sb{x} $ has a root in $ F $.\n\\end{definition}\n\n\\begin{example}\n$ \\R $ is not algebraically closed since $ x^2 + 1 \\in \\R\\sb{x} $ has no roots in $ \\R $.\n\\end{example}\n\n\\begin{definition}[Algebraic closure]\nAn \\textbf{algebraic closure} of $ F $ is an algebraically closed algebraic extension of $ F $ that is unique up to $ F $-isomorphism.\n\\end{definition}\n\n\\begin{example}\n$ \\overline{\\R} = \\C $ while $ \\overline{\\Q} $ is the field of algebraic numbers.\n\\end{example}\n\nThe existence and uniqueness of algebraic closures can be proven from \\emph{Zorn's lemma}, which is equivalent to the \\emph{Axiom of choice}.\n\n\\begin{proposition}\nAn algebraic closure $ \\overline{F} $ of $ F $ exists and is unique up to $ F $-isomorphism.\n\\end{proposition}\n\n\\begin{definition}[Splits]\nA polynomial $ f\\rb{x} \\in F\\sb{x} $ of degree $ n > 0 $ \\textbf{splits} over $ K $ iff $ f\\rb{x} = c\\prod_{i = 0}^n \\rb{x - a_k} $ for some $ c \\in F $ and $ a_k \\in K $.\n\\end{definition}\n\n\\begin{example}\n$ x^2 - 2 $ splits over $ \\Q\\rb{\\sqrt{2}} $ but not over $ \\Q $ since $ x^2 - 2 = \\rb{x - \\sqrt{2}}\\rb{x + \\sqrt{2}} $ in $ \\Q\\rb{\\sqrt{2}} $.\n\\end{example}\n\n\\begin{definition}[Normal extension]\n$ K / F $ is \\textbf{normal} iff $ K / F $ is algebraic and any irreducible polynomial in $ F\\sb{x} $ with a root in $ K $ splits over $ F $.\n\\end{definition}\n\n\\begin{example}\n$ \\Q\\rb{\\sqrt{2}} / \\Q $ is a normal extension, while $ \\Q\\rb{\\sqrt[3]{2}} / \\Q $ is not a normal extension since $ f\\rb{x} = x^3 - 2 = \\rb{x - \\sqrt[3]{2}} \\rb{x^2 + \\sqrt[3]{2}x + \\sqrt[3]{4}} $ has a root $ x = \\sqrt[3]{2} $ but does not split over $ \\Q\\rb{\\sqrt[3]{2}} $.\n\\end{example}\n\n\\begin{definition}[Separable polynomial]\nAn polynomial $ f \\in F\\sb{x} $ is \\textbf{separable} iff $ df / dx \\ne 0 $.\n\\end{definition}\n\n\\begin{example}\n$ x^2 - 2 \\in \\Q\\sb{x} $ is a separable polynomial since $ d\\rb{x^2 - 2} / dx = 2x \\ne 0 $, while $ x^2 - y^2 \\in \\F_2\\rb{y^2} $ is an inseparable polynomial since $ d\\rb{x^2 - y^2} / d\\rb{y^2} = 0 $.\n\\end{example}\n\n\\begin{definition}[Separable extension]\n$ K / F $ is \\textbf{separable} iff $ K / F $ is algebraic and the minimal polynomial of any $ \\alpha \\in K $ is separable.\n\\end{definition}\n\n\\begin{example}\n$ \\Q\\rb{\\sqrt{2}} / \\Q $ is a separable extension, while $ \\F_2\\rb{y} / \\F_2\\rb{y^2} $ is an inseparable extension since the minimal polynomial of $ y $ over $ F_2\\rb{y^2} $ is $ x^2 - y^2 $, which is inseparable.\n\\end{example}\n\n\\begin{definition}[Galois extension]\n$ K / F $ is \\textbf{Galois} iff $ K / F $ is normal and separable.\n\\end{definition}\n\n\\begin{example}\n$ \\C / \\R $ and $ \\Q\\rb{\\sqrt{2}} / \\Q $ are Galois extensions.\n\\end{example}\n\n\\begin{definition}[Galois group]\n$ Aut_F\\rb{K} $ is the \\textbf{Galois group} $ Gal_F\\rb{K} $ of $ K $ over $ F $ iff $ K / F $ is Galois.\n\\end{definition}\n\n\\begin{example}\n$ Gal_\\R\\rb{\\C} = \\cb{id_\\R, \\phi} $ where $ \\phi $ is complex conjugation, while $ Gal_\\Q\\rb{\\Q\\sqrt{2}} = \\cb{id_\\Q, \\phi} $ where $ \\phi $ is the $ \\Q $-automorphism that swaps $ \\sqrt{2} $ and $ -\\sqrt{2} $.\n\\end{example}\n\n\\begin{definition}[Perfect field]\n$ F $ is \\textbf{perfect} iff the algebraic closure of $ F $ is Galois.\n\\end{definition}\n\n\\begin{example}\nExamples of perfect fields include any field of characteristic zero including $ \\Q $, $ \\R $, and $ \\C $, any finite field $ \\F_{p^e} $, and any algebraically closed field including $ \\overline{\\Q} $. Examples of imperfect fields include the field of rational functions $ \\F_p\\rb{y} $ of any finite field $ \\F_p $ since $ x^p - y \\in \\F_p\\rb{y} $ is irreducible but inseparable.\n\\end{example}\n\n\\pagebreak\n\n\\subsection{Algebraic varieties}\n\nLet $ F $ be a perfect field of $ char\\rb{F} \\notin \\cb{2, 3} $ with algebraic closure $ K = \\overline{F} $ and Galois group $ Gal_F\\rb{K} $.\n\n\\begin{definition}[Affine space]\nAn \\textbf{affine $ n $-space} over $ F $ is $ \\A^n = K^n $.\n\\end{definition}\n\n\\begin{definition}[Projective space]\nA \\textbf{projective $ n $-space} over $ F $ is $ \\P^n = \\rb{\\A^{n + 1} \\setminus \\cb{\\rb{0, \\dots, 0}}} / \\sim $, the set of equivalence classes of \\textbf{homogeneous coordinates} $ \\sb{p_0, \\dots, p_n} $, where $ \\rb{x_0, \\dots, x_n} \\sim \\rb{y_0, \\dots, y_n} $ iff each $ x_i = \\lambda y_i $ for some $ \\lambda \\in F^* $.\n\\end{definition}\n\n$ \\P^n $ can be considered a superset of $ n + 1 $ copies of $ \\A^n $ by the natural inclusions $ \\phi_i : \\A^n \\to \\P^n $ for each $ i \\in \\cb{0, \\dots, n} $ defined by\n$$ \\phi_i\\rb{x_1, \\dots, x_n} = \\sb{x_1, \\dots, x_i, 1, x_{i + 1}, \\dots, x_n}, $$\nso write $ \\A^n \\subseteq \\P^n $. Now let $ \\A^n $ be an affine $ n $-space over $ F $ and $ \\P^n $ be a projective $ n $-space over $ F $.\n\n\\begin{definition}[Rational point]\nThe set of \\textbf{$ F $-rational points} of $ \\A^n $ is $ \\A^n\\rb{F} = F^n $, and of $ \\P^n $ is\n$$ \\P^n\\rb{F} = \\cb{\\sb{p_0, \\dots, p_n} \\in \\P^n \\mid \\forall p_j \\ne 0, \\ \\forall p_i, \\ p_i / p_j \\in F}. $$\n\\end{definition}\n\n$ \\A^n $ can be equipped with $ Gal_F\\rb{K} $, such that $ \\A^n\\rb{F} = \\cb{a \\in \\A^n \\mid \\forall \\sigma \\in Gal_F\\rb{K}, \\ \\sigma\\rb{a} = a} $. This holds similarly in $ \\P^n $.\n\n\\begin{example}\n$ \\C^n $ is an affine $ n $-space over $ \\R $, with $ \\C^n\\rb{\\R} = \\R $. $ \\overline{\\F}^n $ is a projective $ n $-space over $ \\F^n $, with $ \\overline{\\F}^n\\rb{\\F^n} $ being the projective plane of order $ n $.\n\\end{example}\n\n\\begin{definition}[Homogeneous]\nA polynomial $ f \\in K\\sb{x_0, \\dots, x_n} $ is \\textbf{homogeneous} of degree $ d \\in \\Z_{\\ge 0} $ iff for any $ \\lambda \\in K $, it holds that $ f\\rb{\\lambda x_0, \\dots, \\lambda x_n} = \\lambda^d f\\rb{x_0, \\dots, x_n} $. An ideal $ I \\subseteq K\\sb{x_0, \\dots, x_n} $ is homogeneous iff $ I $ is generated by homogeneous polynomials in $ K\\sb{x_0, \\dots, x_n} $.\n\\end{definition}\n\nA homogeneous polynomial $ f^* \\in K\\sb{x_0, \\dots, x_n} $ can be \\emph{dehomogenised} into $ f \\in K\\sb{x_1, \\dots, x_n} $ by\n$$ f\\rb{x_1, \\dots, x_n} = f^*\\rb{1, x_1, \\dots, x_n}, $$\nwhile a non-homogeneous polynomial $ g \\in K\\sb{x_1, \\dots, x_n} $ can be \\emph{homogenised} into $ g^* \\in K\\sb{x_0, \\dots, x_n} $ by\n$$ g^*\\rb{x_0, \\dots, x_n} = x_0^d g\\rb{x_1 / x_0, \\dots, x_n / x_0}. $$\n\n\\begin{example}\n$ z^3 + wxy + 7w^3 \\in \\C\\sb{w, x, y, z} $ is homogeneous, which can be dehomogenised to $ z^3 + xy + 7 \\in \\C\\sb{x, y, z} $. Conversely $ x^3 + 3x^2y + z^7 \\in \\C\\sb{x, y, z} $ is non-homogeneous, which can be homogenised to $ w^4x^3 + 3w^4x^2y + z^7 \\in \\C\\sb{w, x, y, z} $. Thus $ \\ab{z^3 + wxy + 7w^3, w^4x^3 + 3w^4x^2y + z^7} \\subseteq \\C\\sb{w, x, y, z} $ is a homogeneous ideal.\n\\end{example}\n\nThe following definitions are simplified by considering only prime ideals in \\emph{Hilbert's Nullstellensatz}.\n\n\\begin{definition}[Algebraic variety]\nAn \\textbf{affine algebraic variety} of $ \\A^n $ over $ F $ is\n$$ A = \\cb{a \\in \\A^n \\mid \\forall f \\in I, \\ f\\rb{a} = 0} $$\nfor some finitely generated prime ideal $ I \\subseteq F\\sb{x_1, \\dots, x_n} $, denoted by $ A\\rb{I} $ and $ I\\rb{A} $ respectively. The set of $ F $-rational points of $ A $ is $ A\\rb{F} = A \\cap \\A^n\\rb{F} $. A \\textbf{projective algebraic variety} $ P $ of $ \\P^n $ over $ F $ and the set of $ F $-rational points of $ P $ are defined similarly but with homogeneous prime ideals.\n\\end{definition}\n\nSince $ I\\rb{A} $ can be finitely generated by $ f_1, \\dots, f_m \\in F\\sb{x_1, \\dots, x_n} $, it holds that $ A\\rb{f_1, \\dots, f_m}\\rb{F} $ is the set of solutions in $ F $ to the system of equations $ f_1\\rb{x_1, \\dots, x_n} = \\dots = f_m\\rb{x_1, \\dots, x_n} = 0 $. This holds similarly in $ \\P^n $.\n\n\\begin{example}\nLet $ \\ab{x^2 + y^2 - 1} \\subseteq \\R\\sb{x, y} $ be a finitely generated prime ideal. Thus $ A\\rb{x^2 + y^2 - 1} $ is an affine algebraic variety of $ \\C^2 $ over $ \\R $ and $ A\\rb{x^2 + y^2 - 1}\\rb{\\R} $ is the unit circle $ S^1 $. Homogenisation gives a finitely generated homogeneous ideal $ \\ab{x^2 + y^2 - w^2} \\subseteq \\R\\sb{w, x, y} $. Similarly $ P\\rb{x^2 + y^2 - w^2} $ is a projective algebraic variety of $ \\C^2 $ over $ \\R $ and $ P\\rb{x^2 + y^2 - w^2}\\rb{\\R} $ is the unit circle $ S^1 $.\n\\end{example}\n\nLet $ A $ be an affine algebraic variety of $ \\A^n $ over $ F $ and $ P $ be a projective algebraic variety of $ \\P^n $ over $ F $.\n\n\\begin{definition}[Dimension]\nThe \\textbf{dimension} $ dim\\rb{A} $ of $ A $ is the length of any longest chain of prime ideals in $ F\\sb{x_1, \\dots, x_n} / I\\rb{A} $. The dimension of $ P $ is $ dim\\rb{P} = dim\\rb{A\\rb{I\\rb{P}}} - 1 $ for any $ A\\rb{I\\rb{P}} \\subseteq \\A^n $.\n\\end{definition}\n\n\\begin{example}\nLet $ A\\rb{x - y} $ be an affine algebraic variety of $ \\C^3 $ over $ \\R $. Then a longest chain of prime ideals is $ \\ab{0} \\subset \\ab{y} \\subset \\ab{y, z} \\subset \\R\\sb{x, y, z} / \\ab{x - y} $, which has length two. Thus it has dimension $ dim\\rb{A\\rb{x - y}} = 2 $. A projective algebraic variety $ P\\rb{x - y} $ of $ \\C^2 $ over $ \\R $ has dimension $ dim\\rb{P\\rb{x - y}} = dim\\rb{A\\rb{x - y}} - 1 = 1 $.\n\\end{example}\n\nThe dimension of projective algebraic varieties can also be defined from \\emph{Krull's Hauptidealsatz}.\n\n\\begin{proposition}\n$ dim\\rb{P} = n - 1 $ iff $ I\\rb{P} $ is generated by a homogeneous irreducible polynomial in $ F\\sb{X_0, \\dots, X_n} $.\n\\end{proposition}\n\n\\begin{definition}[Smooth]\nA point $ a \\in A $ is \\textbf{singular} iff the Jacobian $ m \\times n $ matrix $ J $ defined by $ J_{ij} = \\partial f_i / \\partial x_j $ is such that $ rk\\rb{\\val{J}_a} < n - dim\\rb{A} $. $ A $ is \\textbf{smooth} if it has no singular points. This holds similarly for $ P $.\n\\end{definition}\n\n\\begin{example}\nLet $ A\\rb{x - y} $ be an affine algebraic variety of $ \\C^3 $ over $ \\R $. Then $ dim\\rb{A\\rb{x - y}} = 2 $, so a point $ a = \\rb{x, y, z} \\in A\\rb{x - y} $ is singular iff $ rk\\rb{\\val{J}_a} < 3 - 2 = 1 $, or\n$$ 0 = rk\\rb{\\val{J}_a} = rk\\onebythree{\\val{\\dfrac{\\partial \\rb{x - y}}{\\partial x}}_a}{\\val{\\dfrac{\\partial \\rb{x - y}}{\\partial y}}_a}{\\val{\\dfrac{\\partial \\rb{x - y}}{\\partial z}}_a} = rk\\onebythree{1}{-1}{0} = 1. $$\nThus there are no singular points and $ A\\rb{x - y} $ is smooth.\n\\end{example}\n\n\\begin{definition}[Function field]\nThe \\textbf{function field} of $ P $ is\n$$ F\\rb{P} = \\cb{f\\rb{x_0, \\dots, x_n} / g\\rb{x_0, \\dots, x_n} \\mid f, g \\in F\\sb{x_0, \\dots, x_n}, \\ \\deg\\rb{f} = \\deg\\rb{g}, \\ g \\notin I\\rb{P}} / \\sim, $$\nthe field of equivalence classes of \\textbf{rational functions} of homogeneous polynomials, where $ f / g \\sim f' / g' $ iff $ fg' - f'g \\in I\\rb{P} $.\n\\end{definition}\n\n\\begin{example}\nLet $ P\\rb{xy} $ be a projective algebraic variety of $ \\C $ over $ \\R $. Then $ x \\in \\R\\sb{x, y} $ and $ y \\in \\R\\sb{x, y} $ are homogeneous of degree one, and $ y \\notin I\\rb{P} $. Thus $ x / y \\in \\R\\rb{P} $.\n\\end{example}\n\nLet $ P' $ be a projective algebraic variety of $ \\P^m $ over $ F $.\n\n\\begin{definition}[Morphism]\nA \\textbf{morphism} from $ P $ to $ P' $ is an equivalence class of rational functions $ \\phi = \\sb{\\phi_0, \\dots, \\phi_m} : P \\to P' $ for some $ \\phi_i \\in F\\rb{P} $, such that for any $ p \\in P $, there is a rational function $ g \\in F\\rb{P} $ such that $ g\\phi_i\\rb{p} \\in P' $ for each $ \\phi_i $ and $ g\\phi_i\\rb{p} \\ne 0 $ for some $ \\phi_i $, where $ \\rb{\\phi_0, \\dots, \\phi_m} \\sim \\rb{\\psi_0, \\dots, \\psi_m} $ iff each $ \\phi_i = g'\\psi_i $ for some $ g' \\in F\\rb{P} $.\n\\end{definition}\n\n\\begin{example}\nLet $ P\\rb{x^2 + y^2 - w^2} $ be a projective algebraic variety of $ \\C^2 $ over $ \\R $ and $ P'\\rb{0} $ be a projective algebraic variety of $ \\C $ over $ \\R $, and let $ \\phi = \\sb{w + x, y} : P \\to P' $ be such that $ w + x, y \\in \\R\\rb{P} $. Let $ p = \\sb{w, x, y} \\in P $ be a point such that $ w + x \\ne 0 $ or $ y \\ne 0 $. Then $ w + x, y \\ne 0 $ are well-defined at $ p $. Now let $ p' = \\sb{w, x, y} \\in P $ be a point such that $ w + x = y = 0 $. Then $ \\rb{\\rb{w - x} / y}\\rb{w + x} = \\rb{w^2 - x^2} / y = y^2 / y = y $ and $ \\rb{\\rb{w - x} / y}y = w - x \\ne 0 $ are well-defined at $ p' $. Thus $ \\phi $ is a morphism.\n\\end{example}\n\nA standard result in algebraic geometry states that images of morphisms are projective algebraic varieties.\n\n\\begin{proposition}\nLet $ \\phi : P \\to P' $ be a morphism and $ dim\\rb{P} = dim\\rb{P'} = 1 $. Then $ \\phi $ is either constant or surjective.\n\\end{proposition}\n\n\\begin{definition}[Isomorphism]\nAn \\textbf{isomorphism} is a morphism $ \\phi : P \\to P' $ such that there is another morphism $ \\phi' : P' \\to P $ where $ \\phi' \\circ \\phi = id_P $ and $ \\phi \\circ \\phi' = id_{P'} $. $ P $ and $ P' $ are \\textbf{isomorphic}, denoted by $ P \\cong P' $, iff there is an isomorphism $ \\phi : P \\to P' $.\n\\end{definition}\n\n\\begin{example}\nLet $ P\\rb{x^2 + y^2 - w^2} $ be a projective algebraic variety of $ \\C^2 $ over $ \\R $ and $ P'\\rb{0} $ be a projective algebraic variety of $ \\C $ over $ \\R $ with a morphism $ \\phi : \\sb{w + x, y} : P \\to P' $. Then $ \\phi' = \\sb{x^2 + y^2, x^2 - y^2, 2xy} : P' \\to P $ is also a morphism such that $ \\phi \\circ \\phi' = \\sb{2x^2, 2xy} = \\sb{x, y} = id_{P'} $ and\n$$ \\phi' \\circ \\phi = \\sb{\\rb{w + x}^2 + y^2, \\rb{w + x}^2 - y^2, 2\\rb{w + x}y} = \\sb{2w\\rb{w + x}, 2x\\rb{w + x}, 2y\\rb{w + x}} = \\sb{w, x, y} = id_P. $$\nThus $ \\phi $ is an isomorphism and $ P \\cong P' $.\n\\end{example}\n\n\\pagebreak\n\n\\subsection{Algebraic curves}\n\nLet $ F $ be a perfect field of $ char\\rb{F} \\notin \\cb{2, 3} $ with algebraic closure $ K = \\overline{F} $ and $ V $ be a projective algebraic variety of $ \\P^n $ over $ F $.\n\n\\begin{definition}[Projective plane curve]\n$ V $ is a \\textbf{projective plane curve} iff $ dim\\rb{V} = 1 $ and $ n = 2 $.\n\\end{definition}\n\nSince a projective plane curve $ V $ is such that $ \\dim\\rb{V} = 1 = 2 - 1 $, it holds that $ I\\rb{V} $ is generated by some homogeneous irreducible polynomial $ f \\subseteq F\\sb{X, Y, Z} $. For ease of notation $ V $ will be written in the form $ V : f\\rb{X, Y, Z} = 0 $, or in its simpler dehomogeneous form $ V : f\\rb{x, y} = 0 $. Now let $ C : f\\rb{X, Y, Z} = 0 $ and $ C' : g\\rb{X, Y, Z} = 0 $ be two projective plane curves over $ F $ with a point $ P = \\sb{a, b, c} \\in C \\cap C' $.\n\n\\begin{definition}[Multiplicity]\nThe \\textbf{multiplicity} $ m_P\\rb{f} $ of $ C $ at $ P $ is the smallest $ m \\in \\Z_{> 0} $ such that\n$$ \\forall i, j, k \\in \\Z_{\\ge 0}, \\qquad i + j + k = n, \\qquad \\val{\\dfrac{\\partial^n f}{\\partial X^i \\partial Y^j \\partial Z^k}}_P = 0 $$\nfor any $ n \\in \\cb{0, \\dots, m - 1} $ but not $ n = m $.\n\\end{definition}\n\n$ P $ is singular iff $ rk\\rb{\\val{J}_P} < 1 $, or $ \\val{\\partial f / \\partial X}_P = \\val{\\partial f / \\partial Y}_P = \\val{\\partial f / \\partial Z}_P = 0 $, which holds iff $ m_P\\rb{f} > 1 $.\n\n\\begin{example}\nAssume $ char\\rb{F} = 0 $, and let $ f\\rb{X, Y, Z} = f\\rb{x, y} = \\rb{x^2 + y^2}^2 + 3x^2y - y^3 $ with $ P = \\sb{0, 0, 1} = \\rb{0, 0} $. Then\n$$ \\val{\\dfrac{\\partial f}{\\partial x}}_P = \\val{\\dfrac{\\partial f}{\\partial y}}_P = \\val{\\dfrac{\\partial^2 f}{\\partial x^2}}_P = \\val{\\dfrac{\\partial^2 f}{\\partial y^2}}_P = \\val{\\dfrac{\\partial^2 f}{\\partial x \\partial y}}_P = 0, \\qquad \\val{\\dfrac{\\partial^3 f}{\\partial y^3}}_P = -6 \\ne 0. $$\nThus the multiplicity of $ C $ at $ P $ is $ m_P\\rb{f} = 3 $ and $ P $ is singular.\n\\end{example}\n\n\\begin{definition}[Tangent]\nThe \\textbf{tangents} $ T_P\\rb{f} $ of $ C $ at $ P = \\sb{a, b, c} $ with multiplicity $ m = m_P\\rb{f} $ are the irreducible factors of the polynomial\n$$ t_P\\rb{f}\\rb{X, Y, Z} = \\sum_{i + j + k = m} \\twobyone{m}{i, j, k} \\val{\\dfrac{\\partial^m f}{\\partial X^i \\partial Y^j \\partial Z^k}}_P \\rb{X - a}^i \\rb{Y - b}^j \\rb{Z - c}^k. $$\n\\end{definition}\n\n\\begin{example}\nLet $ f\\rb{X, Y, Z} = f\\rb{x, y} = \\rb{x^2 + y^2}^2 + 3x^2y - y^3 $ with $ P = \\sb{0, 0, 1} = \\rb{0, 0} $ and $ m = m_P\\rb{f} = 3 $. Then\n\\begin{align*}\nt_P\\rb{f}\\rb{X, Y, Z} = t_P\\rb{f}\\rb{x, y}\n& = \\twobyone{3}{0}\\val{\\dfrac{\\partial^3 f}{\\partial x^3}}_Px^3 + \\twobyone{3}{1}\\val{\\dfrac{\\partial^3 f}{\\partial x^2 \\partial y}}_Px^2y + \\twobyone{3}{2}\\val{\\dfrac{\\partial^3 f}{\\partial x \\partial y^2}}_Pxy^2 + \\twobyone{3}{3}\\val{\\dfrac{\\partial^3 f}{\\partial y^3}}_Py^3 \\\\\n& = 18x^2y - 6y^3 = 6y\\rb{\\sqrt{3}x - y}\\rb{\\sqrt{3}x + y}.\n\\end{align*}\nThus the tangents of $ C $ at $ P $ are $ T_P\\rb{f} = \\cb{y, \\sqrt{3}x - y, \\sqrt{3}x + y} $.\n\\end{example}\n\n\\begin{definition}[Ordinary singularity]\nA singular point $ P \\in C $ is \\textbf{ordinary} iff $ t_P\\rb{f} $ has distinct factors.\n\\end{definition}\n\n\\begin{example}\nLet $ f\\rb{X, Y, Z} = f\\rb{x, y} = \\rb{x^2 + y^2}^2 + 3x^2y - y^3 $ with $ P = \\sb{0, 0, 1} = \\rb{0, 0} $. Then $ t_P\\rb{f} $ have distinct factors $ y $, $ \\sqrt{3}x - y $, and $ \\sqrt{3}x + y $. Thus $ P $ is ordinary.\n\\end{example}\n\n\\begin{definition}[Intersection number]\nThe \\textbf{intersection number} of $ C $ and $ C' $ at $ P $ if $ \\deg\\rb{\\gcd\\rb{f, g}} = 0 $ is $ I_P\\rb{f, g} $, where $ I_P : F\\sb{X, Y, Z} \\times F\\sb{X, Y, Z} \\to \\Z_{> 0} $ is defined for any $ f', g' \\in F\\sb{X, Y, Z} $ by:\n\\begin{itemize}\n\\item $ I_P\\rb{f', g'} = I_P\\rb{g', f'} $,\n\\item $ I_P\\rb{f', g'} = I_P\\rb{f', g' \\circ h} $ for any affine transformation $ h $,\n\\item $ I_P\\rb{f', g'} = I_P\\rb{f', g' + hf'} $ for any $ h \\in F\\sb{X, Y, Z} $,\n\\item $ I_P\\rb{f', hh'} = I_P\\rb{f', h} + I_P\\rb{f', h'} $ for any $ h, h' \\in F\\sb{X, Y, Z} $, and\n\\item $ I_P\\rb{f', g'} \\ge m_P\\rb{f'} m_P\\rb{g'} $, with equality iff $ T_P\\rb{f'} \\cap T_P\\rb{g'} = \\emptyset $.\n\\end{itemize}\n\\end{definition}\n\nSince $ T_P\\rb{X} = \\cb{X} $, $ T_P\\rb{Y} = \\cb{Y} $, and $ T_P\\rb{Z} = \\cb{Z} $ are all distinct, it holds that $ I_P\\rb{X, Y} = I_P\\rb{X, Z} = I_P\\rb{Y, Z} = 1 $.\n\n\\pagebreak\n\n\\begin{example}\nLet $ f\\rb{X, Y, Z} = f\\rb{x, y} = \\rb{x^2 + y^2}^2 + 3x^2y - y^3 $ and $ g\\rb{X, Y, Z} = g\\rb{x, y} = \\rb{x^2 + y^2}^3 - 4x^2y^2 $ with $ P = \\sb{0, 0, 1} = \\rb{0, 0} $. Then $ \\gcd\\rb{f, g} = 1 $, so $ \\deg\\rb{\\gcd\\rb{f, g}} = 0 $. Now let $ h\\rb{x, y} = 4x^2y + 4y^3 + 5x^2 - 3y^2 $, such that\n$$ g + \\rb{3y - x^2 - y^2}f = y^2h \\qquad \\text{and} \\qquad f + \\rb{y^2 - 2x^2y - y^3 - 3x^2}y = x^4. $$\nThen\n$$ I_P\\rb{f, g} = I_P\\rb{f, g + \\rb{3y - x^2 - y^2}f} = I_P\\rb{f, y^2h} = I_P\\rb{f, y^2} + I_P\\rb{f, h}. $$\nThe first term can be computed as\n$$ I_P\\rb{f, y^2} = 2I_P\\rb{f, y} = 2I_P\\rb{f + \\rb{y^2 - 2x^2y - y^3 - 3x^2}y, y} = 2I_P\\rb{x^4, y} = 8I_P\\rb{x, y} = 8. $$\nNow $ m_P\\rb{f} = 3 $ and $ T_P\\rb{f} = \\cb{y, \\sqrt{3}x - y, \\sqrt{3}x + y} $. Since $ C'' : h\\rb{x} = 0 $ is also a projective plane curve, its multiplicity at $ P $ can be computed to be $ m_P\\rb{h} = 2 $ and its tangents at $ P $ can also be computed to be $ T_P\\rb{h} = \\cb{\\sqrt{5}x - \\sqrt{3}y, \\sqrt{5}x + \\sqrt{3}y} $. Hence $ I_P\\rb{f, h} = m_P\\rb{f} m_P\\rb{h} = \\rb{3}\\rb{2} = 6 $. Thus the intersection number of $ C $ and $ C' $ at $ P $ is $ I_P\\rb{f, g} = 8 + 6 = 14 $.\n\\end{example}\n\n\\begin{definition}[Flex]\n$ P $ is a \\textbf{flex} iff $ I_P\\rb{f, g} > 2 $ is odd.\n\\end{definition}\n\n\\begin{example}\nLet $ f\\rb{X, Y, Z} = f\\rb{x, y} = y - x^3 $ with $ P = \\sb{0, 0, 1} = \\rb{0, 0} $. Then $ \\val{\\partial f / \\partial y}_P = 1 \\ne 0 $, so $ m_P\\rb{f} = 1 $. Since\n$$ g\\rb{X, Y, Z} = g\\rb{x, y} = t_P\\rb{f}\\rb{x, y} = \\val{\\partial f / \\partial x}_Px + \\val{\\partial f / \\partial y}_Py = y, $$\nit holds that $ \\gcd\\rb{f, g} = 1 $, so $ \\deg\\rb{\\gcd\\rb{f, g}} = 0 $. Hence\n$$ I_P\\rb{f, g} = I_P\\rb{f - y, y} = I_P\\rb{-x^3, y} = 3I_P\\rb{-x, y} = 3 > 2. $$\nThus $ P $ is a flex.\n\\end{example}\n\nThe following follows from the fundamental theorem of algebra on the \\emph{resultant} of $ f $ and $ g $.\n\n\\begin{theorem}[B\\'ezout]\n$ C $ intersects $ C' $ at $ \\rb{\\deg\\rb{f}}\\rb{\\deg\\rb{g}} $ points \\emph{up to multiplicity}, so\n$$ \\sum_{P \\in C \\cap C'} I_P\\rb{f, g} = \\rb{\\deg\\rb{f}}\\rb{\\deg\\rb{g}}. $$\n\\end{theorem}\n\nThe following follows from a \\emph{dimension counting} argument.\n\n\\begin{theorem}[Cayley-Bacharach]\nLet $ \\deg\\rb{f} = \\deg\\rb{g} = 3 $ such that $ C $ intersects $ C' $ at nine points up to multiplicity, and let $ C'' : h\\rb{X, Y, Z} = 0 $ be a cubic projective plane curve over $ F $ such that at least eight of these points are in $ C'' $. Then the ninth point is also in $ C'' $.\n\\end{theorem}\n\nThe following definition is the \\emph{genus-degree formula}, which is a corollary of the \\emph{adjunction formula} and the \\emph{Riemann-Roch theorem} for arbitrary curves and surfaces.\n\n\\begin{definition}[Degree]\nThe \\textbf{degree} of $ C $ is $ d_C = \\deg\\rb{f} $.\n\\end{definition}\n\n\\begin{definition}[Genus]\nThe \\textbf{genus} of $ C $ is\n$$ g_C = \\tfrac{1}{2}\\rb{d_C - 1}\\rb{d_C - 2} - \\tfrac{1}{2}\\sum_{P \\in C} m\\rb{m - 1}, $$\nover all ordinary singularities $ P \\in C $ with multiplicity $ m_P\\rb{f} = m $.\n\\end{definition}\n\nThe genus of $ C $ is $ g_C = \\tfrac{1}{2}\\rb{d_C - 1}\\rb{d_C - 2} $ if $ C $ is smooth.\n\n\\begin{example}\nThe line $ L : y = x $ is a smooth projective plane curve of degree one and genus zero. The unit circle $ S_1 : x^2 + y^2 = 1 $ is a smooth projective plane curve of degree two and genus zero. An elliptic curve $ E : y^2 = x^3 + Ax + B $ is a smooth projective plane curve of degree three and genus zero.\n\\end{example}\n\n\\pagebreak\n\n\\subsection{Groups}\n\nLet $ G $ be an additive abelian group, with multiplication $ \\cdot : \\Z \\times G \\to G $ defined by\n$$ nx = \\begin{dcases} x + \\dots + x & n > 0 \\\\ 0 & n = 0 \\\\ \\rb{-x} + \\dots + \\rb{-x} & n < 0 \\end{dcases}. $$\n\n\\begin{theorem}[Isomorphism theorems]\nThe following theorems hold:\n\\begin{enumerate}\n\\item Let $ H $ be a group and $ \\phi : G \\to H $ be a group homomorphism. Then:\n$$ Ker\\rb{\\phi} \\trianglelefteq G, \\qquad \\dfrac{G}{Ker\\rb{\\phi}} \\cong Im\\rb{\\phi}. $$\n\\item Let $ N \\trianglelefteq G $ and $ H \\le G $ be subgroups. Then:\n$$ N \\cap H \\trianglelefteq H, \\qquad \\dfrac{H}{N \\cap H} \\cong \\dfrac{N + H}{N}. $$\n\\item Let $ N \\trianglelefteq G $ and $ H \\trianglelefteq G $ be subgroups such that $ N \\le H $. Then:\n$$ \\dfrac{H}{N} \\trianglelefteq \\dfrac{G}{N}, \\qquad \\dfrac{G / N}{H / N} \\cong \\dfrac{G}{H}. $$\n\\end{enumerate}\n\\end{theorem}\n\nAll subgroups of $ G $ are normal, but the above theorems still hold if $ G $ is non-abelian.\n\n\\begin{definition}[Torsion element]\nAn \\textbf{$ n $-torsion element} is an element $ x \\in G $ such that $ n = ord\\rb{x} $ is finite.\n\\end{definition}\n\n\\begin{example}\n$ \\Z + p / q \\in \\Q / \\Z $ is a torsion element since $ ord\\rb{x} \\mid q $ is finite.\n\\end{example}\n\n\\begin{definition}[Torsion subgroup]\nThe \\textbf{$ n $-torsion subgroup} $ G\\sb{n} $ is the group of $ m $-torsion elements of $ G $ such that $ m \\mid n $. The \\textbf{torsion subgroup} $ G_{tors} $ of $ G $ is the group of $ m $-torsion elements of $ G $ for any $ m \\in \\Z_{\\ge 0} $.\n\\end{definition}\n\n\\begin{example}\n$ G = \\R / \\Z $ has torsion subgroup $ G_{tors} = \\Q / \\Z $ since any $ n $-torsion element $ \\Z + x \\in G $ is such that $ nx \\in \\Z $ and $ x \\in \\Q $.\n\\end{example}\n\n\\begin{definition}[Finitely generated]\n$ G $ is \\textbf{finitely generated} iff there are finitely many elements $ x_1, \\dots, x_n \\in G $ such that any element $ x \\in G $ is a sum\n$$ x = \\sum_{i = 1}^n m_ix_i, \\qquad m_i \\in \\Z. $$\n\\end{definition}\n\n\\begin{example}\n$ \\Z $ and $ \\Z_n $ are finitely generated abelian groups.\n\\end{example}\n\nThe \\emph{direct sum} $ \\oplus $ of finitely many abelian groups is equivalent to their direct product $ \\times $, thus $ \\Z^n = \\Z \\times \\dots \\times \\Z = \\Z \\oplus \\dots \\oplus \\Z $. Now let $ G $ be finitely generated.\n\n\\begin{theorem}[Fundamental theorem of finitely generated abelian groups]\n\\label{thm:ftfgag}\nThere are unique $ r, m \\in \\Z_{\\ge 0} $ and $ n_1, \\dots, n_m \\in \\Z_{> 1} $ such that\n$$ G \\cong r\\Z \\oplus \\bigoplus_{i = 1}^m \\Z_{n_i}, $$\nwith each $ n_i \\mid n_{i + 1} $.\n\\end{theorem}\n\n\\begin{definition}[Rank]\nThe \\textbf{rank} $ rk\\rb{G} $ of $ G $ is the unique $ r \\in \\Z_{\\ge 0} $ in Theorem \\ref{thm:ftfgag}.\n\\end{definition}\n\n\\begin{example}\nA finite abelian group $ G $ has rank $ rk\\rb{G} = 0 $ since $ G_{tors} = G $.\n\\end{example}\n\n\\pagebreak\n\n\\section{Algorithm proofs}\n\n\\subsection{Transformation of a cubic curve into Weierstrass form}\n\nLet\n$$ E : f\\rb{X, Y, Z} = a_1X^3 + a_2X^2Y + a_3XY^2 + a_4Y^3 + a_5X^2Z + a_6XYZ + a_7Y^2Z + a_8XZ^2 + a_9YZ^2 + a_{10}Z^3 = 0 $$\nfor some $ a_i \\in F $ be an elliptic curve over a perfect field $ F $, and let $ P = \\sb{a, b, c} \\in E $ be an $ F $-rational point. Then the unique tangent at $ P $ is\n\\begin{align*}\nL\n: & \\twobyone{1}{1, 0, 0}\\val{\\dfrac{\\partial f}{\\partial X}}_P\\rb{X - a} + \\twobyone{1}{0, 1, 0}\\val{\\dfrac{\\partial f}{\\partial Y}}_P\\rb{Y - b} + \\twobyone{1}{0, 0, 1}\\val{\\dfrac{\\partial f}{\\partial Z}}_P\\rb{Z - c} = 0 \\\\\n: & \\rb{3a_1a^2 + 2a_2ab + a_3b^2 + 2a_5ac + a_6bc + a_8c^2}\\rb{X - a} \\\\\n& + \\rb{a_2a^2 + 2a_3ab + 3a_4b^2 + a_6ac + 2a_7bc + a_9c^2}\\rb{Y - b} \\\\\n& + \\rb{a_5a^2 + a_6ab + a_7b^2 + 2a_8ac + 2a_9bc + 3a_{10}c^2}\\rb{Z - c} = 0.\n\\end{align*}\nIf $ P $ is not a flex, B\\'ezout's theorem gives that $ L $ intersects $ E $ at three points up to multiplicity, so $ E \\cap L = \\cb{P, P'} $ for some other $ F $-rational point $ P' \\in E $, and repeat inductively with $ P' $. This \\emph{chord-tangent} method eventually terminates until $ P' $ is a flex, so assume without loss of generality that $ P $ is a flex. Now let $ Q \\in L \\setminus E $ be a point distinct to $ P $ and define a matrix\n$$ M = \\onebythree{Q}{P}{R}, \\qquad R \\in \\cb{\\sb{1, 0, 0}^T, \\sb{0, 1, 0}^T, \\sb{0, 0, 1}^T}. $$\nSince $ P $ and $ Q $ are linearly independent, at least one of these is invertible. Then transforming $ \\sb{X, Y, Z} \\mapsto M\\sb{X, Y, Z}^T $ gives $ Q \\mapsto \\sb{1, 0, 0} $ and $ P \\mapsto \\sb{0, 1, 0} = \\mathcal{O} $, and the elliptic curve\n$$ E' : f'\\rb{X, Y, Z} = a_1'X^3 + a_2'X^2Y + a_3'XY^2 + a_4'Y^3 + a_5'X^2Z + a_6'XYZ + a_7'Y^2Z + a_8'XZ^2 + a_9'YZ^2 + a_{10}'Z^3 = 0. $$\nfor some $ a_i' \\in F $. Since $ \\mathcal{O} \\in E' $, it holds that $ f'\\rb{0, 1, 0} = a_4' = 0 $. Now the tangent at $ \\mathcal{O} $ is\n$$ L' : \\twobyone{1}{1, 0, 0}\\val{\\dfrac{\\partial f'}{\\partial X}}_\\mathcal{O}X + \\twobyone{1}{0, 1, 0}\\val{\\dfrac{\\partial f'}{\\partial Y}}_\\mathcal{O}\\rb{Y - 1} + \\twobyone{1}{0, 0, 1}\\val{\\dfrac{\\partial f'}{\\partial Z}}_\\mathcal{O}Z = 0 : a_3'X + a_7'Z = 0. $$\nSince $ L' : Z = 0 $, it holds that $ a_3' = 0 $ and $ a_7' \\ne 0 $. Then $ L' $ intersects $ E' $ at\n$$ a_1'X^3 + a_2'X^2Y + a_5'X^2\\rb{0} + a_6'XY\\rb{0} + a_7'Y^2\\rb{0} + a_8'X\\rb{0}^2 + a_9'Y\\rb{0}^2 + a_{10}'\\rb{0}^3 = X^2\\rb{a_1'X + a_2'Y} = 0. $$\nSince $ \\mathcal{O} $ is a flex, it holds that $ X = 0 $ is repeated three times, so $ a_1' \\ne 0 $ and $ a_2' = 0 $. Hence\n\\begin{align*}\nE'\n& : a_1'X^3 + a_5'X^2Z + a_6'XYZ + a_7'Y^2Z + a_8'XZ^2 + a_9'YZ^2 + a_{10}'Z^3 = 0 \\\\\n& : X^3 + \\dfrac{a_5'}{a_1'}X^2Z + \\dfrac{a_6'}{a_1'}XYZ + \\dfrac{a_7'}{a_1'}Y^2Z + \\dfrac{a_8'}{a_1'}XZ^2 + \\dfrac{a_9'}{a_1'}YZ^2 + \\dfrac{a_{10}'}{a_1'}Z^3 = 0.\n\\end{align*}\nThen rescaling $ \\sb{X, Y, Z} \\mapsto \\sb{X, Y, -\\rb{a_1' / a_7'}Z} $ gives\n\\begin{align*}\nE'\n& : X^3 - \\dfrac{a_5'}{a_7'}X^2Z - \\dfrac{a_6'}{a_7'}XYZ - Y^2Z + \\dfrac{a_8'a_1'}{a_7'^2}XZ^2 + \\dfrac{a_9'a_1'}{a_7'^2}YZ^2 - \\dfrac{a_{10}'a_1'^2}{a_7'^3}Z^3 = 0 \\\\\n& : Y^2Z + \\dfrac{a_5'}{a_7'}X^2Z + \\dfrac{a_6'}{a_7'}XYZ = X^3 + \\dfrac{a_8'a_1'}{a_7'^2}XZ^2 + \\dfrac{a_9'a_1'}{a_7'^2}YZ^2 - \\dfrac{a_{10}'a_1'^2}{a_7'^3}Z^3.\n\\end{align*}\nThus $ E' $ is a Weierstrass equation.\n\n\\pagebreak\n\n\\subsection{Group law explicit formulae}\n\nLet $ P, Q \\in E $ be points such that $ R = P * Q \\in E $. Since $ * $ is symmetric, it is commutative, so only the following six cases need to be considered.\n\\begin{enumerate}[label=$ \\rb{*}_\\arabic* $]\n\\item Assume that $ P = \\rb{a, b} $ and $ Q = \\rb{a, b'} $ for $ b \\ne b' $. Then the line joining $ P $ and $ Q $ is\n$$ L : \\rb{b - b'}X + \\rb{ab' - ab}Z = 0 : X = aZ, $$\nwhich intersects $ E $ at\n$$ Y^2Z = \\rb{aZ}^3 + A\\rb{aZ}Z^2 + BZ^3 \\qquad \\implies \\qquad Z\\rb{a^3Z^2 + AaZ^2 + BZ^2 - Y^2} = 0. $$\nIf $ Z \\ne 0 $, then this can be dehomogenised into\n$$ y^2 = a^3 + Aa + B, $$\nwhich has trivial solutions opposite in sign, so $ b' = -b $. Thus $ Z = 0 $ and $ R = \\mathcal{O} $.\n\\item Assume that $ P = \\rb{a, b} $ and $ Q = \\rb{a', b'} $ for $ a \\ne a' $, and let\n$$ \\lambda = \\dfrac{b - b'}{a - a'}, \\qquad \\mu = \\dfrac{ab' - a'b}{a - a'}. $$\nThen the line joining $ P $ and $ Q $ is\n$$ L : \\rb{b - b'}X + \\rb{a' - a}Y + \\rb{ab' - a'b}Z = 0 : Y = \\lambda X + \\mu Z, $$\nwhich intersects $ E $ at\n$$ \\rb{\\lambda X + \\mu Z}^2Z = X^3 + AXZ^2 + BZ^3 \\qquad \\implies \\qquad X^3 - \\lambda^2X^2Z + \\rb{A - 2\\lambda\\mu}XZ^2 - \\rb{\\mu^2 - B}Z^3 = 0. $$\nSince $ Z = 0 $ gives $ Y = 0 $, it holds that $ Z \\ne 0 $, and this can be dehomogenised into\n$$ x^3 - \\lambda^2x^2 + \\rb{A - 2\\lambda\\mu}x - \\rb{\\mu^2 - B} = 0. $$\nLet $ R = \\rb{a'', b''} $. Since\n$$ 0 = \\rb{x - a}\\rb{x - a'}\\rb{x - a''} = x^3 - \\rb{a + a' + a''}x^2 + \\rb{aa' + a'' + a'a''}x - aa'a'', $$\ncomparing coefficients gives\n$$ \\lambda^2 = a + a' + a'', \\qquad A - 2\\lambda\\mu = aa' + aa'' + a'a'', \\qquad \\mu^2 - B = aa'a''. $$\nThus $ R = \\rb{\\lambda^2 - a - a', \\lambda\\rb{\\lambda^2 - a - a'} + \\mu} $.\n\\item Assume that $ P = Q = \\rb{a, b} $ for $ b \\ne 0 $, and let\n$$ \\lambda = \\dfrac{3a^2 + A}{2b}, \\qquad \\mu = \\dfrac{2Aa + 3B - b^2}{2b}. $$\nThen the tangent at $ P $ is\n$$ L : \\rb{-3a^2 - A}X + 2bY + \\rb{b^2 - 2Aa - 3B}Z = 0 : Y = \\lambda X + \\mu Z, $$\nwhich intersects $ E $ by $ \\rb{*}_2 $ at\n$$ x^3 - \\lambda^2x^2 + \\rb{A - 2\\lambda\\mu}x - \\rb{\\mu^2 - B} = 0. $$\nLet $ R = \\rb{a', b'} $. Since\n$$ 0 = \\rb{x - a}^2\\rb{x - a'} = x^3 - \\rb{2a + a'}x^2 + \\rb{2aa' + a^2}x - a^2a', $$\ncomparing coefficients gives\n$$ \\lambda^2 = 2a + a', \\qquad A - 2\\lambda\\mu = 2aa' + a^2, \\qquad \\mu^2 - B = a^2a'. $$\nThus $ R = \\rb{\\lambda^2 - 2a, \\lambda\\rb{\\lambda^2 - 2a} + \\mu} $.\n\\item Assume that $ P = Q = \\rb{a, 0} $. Then since $ a\\rb{3a^2 + A} = 3\\rb{a^3} + Aa = 3\\rb{-Aa - B} + Aa = -2Aa - 3B $, the tangent at $ P $ is\n$$ L : \\rb{-3a^2 - A}X + \\rb{-2Aa - 3B}Z = 0 : X = aZ, $$\nwhich intersects $ E $ at $ \\rb{a, 0} $, $ \\rb{a, -0} = \\rb{a, 0} $, and $ \\mathcal{O} $ by $ \\rb{*}_1 $. Thus $ R = \\mathcal{O} $.\n\\item Assume that $ P = \\rb{a, b} $ and $ Q = \\mathcal{O} $. Then the line joining $ P $ and $ Q $ is\n$$ L : -X + aZ = 0 : X = aZ, $$\nwhich intersects $ E $ at $ \\rb{a, b} $, $ \\rb{a, -b} $, and $ \\mathcal{O} $ by $ \\rb{*}_1 $. Thus $ R = \\rb{a, -b} $.\n\\item Assume that $ P = Q = \\mathcal{O} $. Then the tangent at $ P $ is\n$$ L : Z = 0. $$\nThus $ R = \\mathcal{O} $.\n\\end{enumerate}\nSimilarly since $ + $ is symmetric, it is commutative, so only the following four cases need to be considered. If $ P = \\rb{a, b} $ and $ Q = \\rb{a', b'} $ for $ a \\ne a' $, then $ \\rb{*}_2 $ and $ \\rb{*}_5 $ give\n\\begin{align*}\nP + Q\n& = \\rb{\\lambda^2 - a - a', -\\rb{\\lambda\\rb{\\lambda^2 - a - a'} + \\mu}}, \\qquad \\lambda = \\dfrac{b - b'}{a - a'}, \\qquad \\mu = \\dfrac{ab' - a'b}{a - a'} \\\\\n& = \\rb{\\dfrac{\\rb{A + aa'}\\rb{a + a'} + 2\\rb{B - bb'}}{\\rb{a - a'}^2}, \\dfrac{a'b - ab' - \\rb{\\dfrac{\\rb{A + aa'}\\rb{a + a'} + 2\\rb{B - bb'}}{\\rb{a - a'}^2}}\\rb{b - b'}}{a - a'}} \\\\\n& = \\rb{\\dfrac{\\rb{A + aa'}\\rb{a + a'} + 2\\rb{B - bb'}}{\\rb{a - a'}^2}, \\dfrac{\\rb{Ab' - a'^2b}\\rb{3a + a'} + \\rb{a^2b' - Ab}\\rb{a + 3a'} - 4B\\rb{b - b'}}{\\rb{a - a'}^3}}.\n\\end{align*}\nIf $ P = Q = \\rb{a, b} $ for $ b \\ne 0 $, then $ \\rb{*}_3 $ and $ \\rb{*}_5 $ give\n\\begin{align*}\nP + Q\n& = \\rb{\\lambda^2 - 2a, -\\rb{\\lambda\\rb{\\lambda^2 - 2a} + \\mu}}, \\qquad \\lambda = \\dfrac{3a^2 + A}{2b}, \\qquad \\mu = \\dfrac{2Aa + 3B - b^2}{2b} \\\\\n& = \\rb{\\dfrac{a^4 - 2Aa^2 - 8Ba + A^2}{4b^2}, \\dfrac{b^2 - 2Aa - 3B - \\rb{\\dfrac{a^4 - 2Aa^2 - 8Ba + A^2}{4b^2}}\\rb{3a^2 + A}}{2b}} \\\\\n& = \\rb{\\dfrac{a^4 - 2Aa^2 - 8Ba + A^2}{4b^2}, \\dfrac{a^6 + 5Aa^4 + 20Ba^3 - 5A^2a^2 - 4ABa - A^3 - 8B^2}{8b^3}}.\n\\end{align*}\nIf $ P = \\rb{a, b} $ and $ Q = \\mathcal{O} $, then $ \\rb{*}_5 $ gives\n$$ P + Q = \\rb{\\rb{a, b} * \\mathcal{O}} * \\mathcal{O} = \\rb{a, -b} * \\mathcal{O} = \\rb{a, b} = P. $$\nOtherwise $ P + Q = \\mathcal{O} $ or $ P = Q = \\mathcal{O} $, then $ \\rb{*}_1 $, $ \\rb{*}_4 $, and $ \\rb{*}_6 $ give\n$$ P + Q = \\rb{P * Q} * \\mathcal{O} = \\mathcal{O} * \\mathcal{O} = \\mathcal{O}. $$\nThus the explicit formulae hold.\n\n\\pagebreak\n\n\\section{Code listings}\n\n\\subsection{Fields.hs}\n\nThis module includes basic types and instances for fields and prime subfields in Section 2.\n\n\\lstinputlisting{hs/Fields.hs}\n\n\\pagebreak\n\n\\subsection{WeierstrassEquations.hs}\n\nThis module includes data for Weierstrass curves in Section 1.2, as well as related quantities and transformations.\n\n\\lstinputlisting{hs/WeierstrassEquations.hs}\n\n\\pagebreak\n\n\\subsection{GroupLaw.hs}\n\nThis module includes data for the group law in Section 1.3, as well as those of points.\n\n\\lstinputlisting{hs/GroupLaw.hs}\n\n\\pagebreak\n\n\\subsection{Rationals.hs}\n\nThis module includes the algorithms in Section 3.2 and Section 3.7.\n\n\\lstinputlisting{hs/Rationals.hs}\n\n\\pagebreak\n\n\\subsection{Applications.hs}\n\nThis module includes the algorithms in Section 4.1 and Section 4.2.\n\n\\lstinputlisting{hs/Applications.hs}\n\n\\pagebreak\n\n\\subsection{Test.hs}\n\nThis module includes input of computations from previous modules.\n\n\\lstinputlisting{hs/Test.hs}\n\n\\pagebreak\n\n\\subsection{Output.txt}\n\nThis file includes output of computations from previous modules.\n\n\\lstinputlisting{hs/Output.txt}\n\n\\pagebreak\n\n\\nocite{*}\n\n\\printbibliography[heading=bibintoc]\n\n\\end{document}", "meta": {"hexsha": "23026d57af7a9fae07a277e67f7842b059b78ec9", "size": 250201, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "urop/report/EllipticCurves.tex", "max_stars_repo_name": "Multramate/EllipticCurves", "max_stars_repo_head_hexsha": "f46652e975c1d7af5977fc0f2b5b845972eec63d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-04-19T17:04:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T08:58:48.000Z", "max_issues_repo_path": "urop/report/EllipticCurves.tex", "max_issues_repo_name": "Multramate/EllipticCurves", "max_issues_repo_head_hexsha": "f46652e975c1d7af5977fc0f2b5b845972eec63d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "urop/report/EllipticCurves.tex", "max_forks_repo_name": "Multramate/EllipticCurves", "max_forks_repo_head_hexsha": "f46652e975c1d7af5977fc0f2b5b845972eec63d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 81.7917620137, "max_line_length": 1876, "alphanum_fraction": 0.6239383536, "num_tokens": 98905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.34578793835137156}}
{"text": "\n\n    \\filetitle{xsf}{Power spectrum and spectral density of model variables}{model/xsf}\n\n\t\\paragraph{Syntax}\\label{syntax}\n\n\\begin{verbatim}\n[S,D,List] = xsf(M,Freq,...)\n[S,D,List,Freq] = xsf(M,NFreq,...)\n\\end{verbatim}\n\n\\paragraph{Input arguments}\\label{input-arguments}\n\n\\begin{itemize}\n\\item\n  \\texttt{M} {[} model {]} - Model object.\n\\item\n  \\texttt{Freq} {[} numeric {]} - Vector of frequencies at which the\n  XSFs will be evaluated.\n\\item\n  \\texttt{NFreq} {[} numeric {]} - Total number of requested\n  frequencies; the frequencies will be evenly spread between 0 and\n  \\texttt{pi}.\n\\end{itemize}\n\n\\paragraph{Output arguments}\\label{output-arguments}\n\n\\begin{itemize}\n\\item\n  \\texttt{S} {[} namedmat \\textbar{} numeric {]} - Power spectrum\n  matrices.\n\\item\n  \\texttt{D} {[} namedmat \\textbar{} numeric {]} - Spectral density\n  matrices.\n\\item\n  \\texttt{List} {[} cellstr {]} - List of variable in order of\n  appearance in rows and columns of \\texttt{S} and \\texttt{D}.\n\\item\n  \\texttt{Freq} {[} numeric {]} - Vector of frequencies at which the\n  XSFs has been evaluated.\n\\end{itemize}\n\n\\paragraph{Options}\\label{options}\n\n\\begin{itemize}\n\\item\n  \\texttt{'applyTo='} {[} cellstr \\textbar{} char \\textbar{}\n  \\emph{\\texttt{Inf}} {]} - List of variables to which the option\n  \\texttt{'filter='} will be applied; \\texttt{Inf} means all variables.\n\\item\n  \\texttt{'filter='} {[} char \\textbar{} \\emph{empty} {]} - Linear\n  filter that is applied to variables specified by `applyto'.\n\\item\n  \\texttt{'nFreq='} {[} numeric \\textbar{} \\emph{\\texttt{256}} {]} -\n  Number of equally spaced frequencies over which the `filter' is\n  numerically integrated.\n\\item\n  \\texttt{'matrixFmt='} {[} \\emph{\\texttt{'namedmat'}} \\textbar{}\n  \\texttt{'plain'} {]} - Return matrices \\texttt{S} and \\texttt{D} as\n  either \\href{namedmat/Contents}{\\texttt{namedmat}} objects\n  (i.e.~matrices with named rows and columns) or plain numeric arrays.\n\\item\n  \\texttt{'progress='} {[} \\texttt{true} \\textbar{}\n  \\emph{\\texttt{false}} {]} - Display progress bar on in the command\n  window.\n\\item\n  \\texttt{'select='} {[} \\emph{\\texttt{@all}} \\textbar{} char \\textbar{}\n  cellstr {]} - Return XSF for selected variables only; \\texttt{@all}\n  means all variables.\n\\end{itemize}\n\n\\paragraph{Description}\\label{description}\n\n\\paragraph{Example}\\label{example}\n\n\n", "meta": {"hexsha": "a07a0819a99e8cef9c49024af5ad48045eab84f8", "size": 2331, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "-help/model/xsf.tex", "max_stars_repo_name": "OGResearch/IRIS-Toolbox-For-Octave", "max_stars_repo_head_hexsha": "682ea1960229dc701e446137623b120688953cef", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-12-06T13:38:38.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-06T13:38:38.000Z", "max_issues_repo_path": "-help/model/xsf.tex", "max_issues_repo_name": "OGResearch/IRIS-Toolbox-For-Octave", "max_issues_repo_head_hexsha": "682ea1960229dc701e446137623b120688953cef", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-03-28T08:13:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-02T10:40:25.000Z", "max_forks_repo_path": "-help/model/xsf.tex", "max_forks_repo_name": "OGResearch/IRIS-Toolbox-For-Octave", "max_forks_repo_head_hexsha": "682ea1960229dc701e446137623b120688953cef", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-17T07:06:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T07:06:39.000Z", "avg_line_length": 30.2727272727, "max_line_length": 86, "alphanum_fraction": 0.6846846847, "num_tokens": 735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213368305399, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.3456949830213013}}
{"text": "\n\\documentclass{article}\n\\usepackage{graphicx}\n\\usepackage[utf8]{inputenc}\n\\usepackage{amsmath, amssymb, latexsym}\n\\usepackage{neuralnetwork}\n\\usepackage{multicol}\n\\usepackage{expl3}\n\n\\usepackage{pgfplots}\n\\usepackage{algorithm}\n\\usepackage[noend]{algpseudocode}\n\\usepackage{tikz}\n\\usepackage{nicefrac}\n\\pgfplotsset{every axis legend/.append style={\nat={(0,0)},\nanchor=north east}}\n\\usetikzlibrary{shapes,positioning,intersections,quotes}\n\\usetikzlibrary{arrows.meta,\n                bending,\n                intersections,\n                quotes,\n                shapes.geometric}\n                \n\\definecolor{darkgreen}{rgb}{0.0, 0.6, 0.0}\n\\definecolor{darkred}{rgb}{0.7, 0.0, 0.0}\n\\makeatletter\n\\def\\BState{\\State\\hskip-\\ALG@thistlm}\n\\makeatother\n\\title{Week 13}\n\\begin{document}\n\\pagenumbering{gobble}\n\\maketitle\n\\newpage\n\\pagenumbering{arabic}\n\n\\section*{Unsupervised learning}\n\n\\begin{itemize}\n  \\item Try to figure out the structure of the data.\n  \\item The clustering algorithm organizes data based on data characteristics.\n  \\item Market segmentation is categorizing clients into different market categories.\n  \\item Social network analysis.\n  \\item Computer clusters and data centers are organized for network structure and location.\n  \\item Understanding galaxy creation through astronomical data analysis.\n\\end{itemize}\n\n\\section*{K-means algorithm}\n\n\\begin{itemize}\n  \\item Would you like an algorithm to automatically arrange data into coherent clusters?\n  \\item By far the most used clustering algorithm is K-means.\n\\end{itemize}\n\n~\\\\\nAlgorithm overview:\n\n\\begin{enumerate}\n    \\item Assign k locations at random as cluster centroids.\n    \\item Go through each example and assign each point to one of the k clusters based on which center it is closest to.\n\n\\includegraphics[width=\\textwidth]{resources/kclusters_1}\n\n    \\item Move to the average of the similarly allocated data-points for each centroid.\n\n\\includegraphics[width=\\textwidth]{resources/kclusters_2}\n\n    \\item Repeat 2) and 3) until convergence.\n\\end{enumerate}\n\n\\section*{K-means for non-separated clusters}\n\n\n\\begin{itemize}\n  \\item So far, we've looked at K-means, which has well-defined clusters.\n  \\item However, K-means is frequently used on datasets with poorly defined clusters.\n  \\item As an example, consider t-shirt sizes. How large do you make them if you want three sizes (S,M,L)?\n  \\item As a result, three clusters are formed, even if they are not actually there.\n  \\item This is an example of market segmentation; create items that are tailored to the demands of your subpopulations.\n\\end{itemize}\n\n\\includegraphics[width=0.5\\textwidth]{resources/t_shirt}\n\n\\section*{K means optimization objective}\n\n\\begin{itemize}\n  \\item K-means, like the supervised learning functions we've examined, has an optimization goal.\n  \\item While K-means is running, we keep track of two sets of variables.\n  \\item $c^i$ is the index of clusters ${1,2, ..., K}$ to which $x^i$ is currently assigned.\n  \\item $\\mu_k$, is the cluster associated with centroid $k$.\n  \\item  $\\mu_c^i$, is the cluster centroid of the cluster to which example $x^i$ has been assigned to.\n  \\item We may write the optimization objective using this notation:\n\\end{itemize}\n\n$$J(c^{(1)}, ..., c^{(m)}, \\mu_1, ...,\\mu_K)=\\frac{1}{m}\\sum_{i=1}^{m}||x^{(i)}-\\mu_{c^{(i)}}||^2$$\n\n~\\\\\ni.e. squared distances between training example $x^i$ and the cluster centroid to which $x^i$ has been assigned to.\n\n\\includegraphics[width=0.5\\textwidth]{resources/cost_cluster}\n\n~\\\\\nWhen we look at the k-means method:\n\n\\begin{itemize}\n  \\item The cluster assigned step is minimizing $J(...)$ with respect to $c_1, c_2 ... c_i$ i.e. find the centroid closest to each example. Doesn't change the centroids themselves.\n  \\item The move centroid step. We can show this step is choosing the values of $\\mu$ which minimizes $J(...)$ with respect to $\\mu$.\n  \\item So, we're partitioning the algorithm into two parts: First part minimizes the $c$ variables. Second part minimizes the $J$ variables.\n\\end{itemize}\n\n\\section*{Random initialization}\nDepending on the starting setting, K means might converge to different solutions.\n\n\\includegraphics[width=\\textwidth]{resources/optimum_cluster}\n\n\\begin{itemize}\n  \\item Randomly initialize K-means.\n  \\item For each n (e.g. 100) random initialization run K-means.\n  \\item Then compute the distortion on the set of cluster assignments and centroids at convergent.\n  \\item End with n ways of cluster the data.\n  \\item Pick the clustering which gave the lowest distortion.\n\\end{itemize}\n\n\\section*{Elbow method}\n\n\\begin{itemize}\n  \\item How do we choose the number of clusters K?\n  \\item Vary K and compute cost function at a range of K values.\n  \\item $J(...)$'s minimum value should decrease as K rises (i.e. you decrease the granularity so centroids can better optimize).\n  \\item Look for the \"elbow\" on the graph ($K$ vs $J()$).\n\\end{itemize}\n\n\\includegraphics[width=0.47\\textwidth]{resources/elbow}\n\n\\end{document}\n", "meta": {"hexsha": "4eb33aa9a6c1c4422d0e3197a4841ecd5f474f28", "size": 4991, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "slides/week_13.tex", "max_stars_repo_name": "djeada/Stanford-Machine-Learning", "max_stars_repo_head_hexsha": "e6ef77939b7c581aebb5e9454669ad2dbb4f98f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "slides/week_13.tex", "max_issues_repo_name": "djeada/Stanford-Machine-Learning", "max_issues_repo_head_hexsha": "e6ef77939b7c581aebb5e9454669ad2dbb4f98f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slides/week_13.tex", "max_forks_repo_name": "djeada/Stanford-Machine-Learning", "max_forks_repo_head_hexsha": "e6ef77939b7c581aebb5e9454669ad2dbb4f98f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6985294118, "max_line_length": 180, "alphanum_fraction": 0.7387297135, "num_tokens": 1340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.3456541598145602}}
{"text": "% arara: makechapters: {items: [syllabus, dtt, pi, inductive, identity, equivalences, contractible, fundamental, hierarchy, funext, pullback, univalence]}\n\n\\documentclass[11pt]{memoir} %[ebook,10pt,oneside]\n  \n\\usepackage{hott}\n\n\\title{Introduction to homotopy type theory}\n\\author{Egbert Rijke}\n\\date{Carnegie Mellon University\\\\Pittsburgh PA\\\\Summer 2019}%\\\\Version: \\today}\n%\\address{Carnegie Mellon University}\n%\\email{erijke@andrew.cmu.edu}\n\n\\pretitle{\\begin{center}\\textsc\\bgroup\\LARGE}\n\\posttitle{\\egroup\\end{center}\\vspace{2cm}}\n\\preauthor{\\begin{center}\\textsc\\bgroup\\Large}\\postauthor{\\egroup\\end{center}\\vfill}\n\\predate{\\begin{center}\\textsc\\bgroup}{\\postdate{\\egroup\\end{center}}\n\n\n  % The following is to avoid overfull hboxes in the table of contents.\n% https://tex.stackexchange.com/questions/49887/overfull-hbox-warning-for-toc-entries-when-using-memoir-documentclass\n%\\renewcommand*{\\cftdotsep}{1}\n\\setpnumwidth{2em}\n\\setrmarg{3em}\n\\setlength{\\cftchapternumwidth}{2em}\n\\setlength{\\cftsectionindent}{2em}\n\\setlength{\\cftsectionnumwidth}{2em}\n\\setlength{\\cftsubsectionindent}{4em}\n\\setlength{\\cftsubsectionnumwidth}{3em}\n\n% We number sections independently of chapters, and subsections will be\n% numbered too.\n\n\\counterwithout{section}{chapter}\n\\settocdepth{subsection}\n\n% We set up the exercise environment, which produces list environment in a new\n% unnumbered subsection that also gets mentioned in the table of contents.\n\n\\newlist{exenum}{enumerate}{1}\n\\setlist[exenum]{noitemsep,label=\\thesection.\\arabic*}\n  %,ref=\\thechapter.\\arabic*}\n\n\\crefname{exenumi}{Exercise}{Exercises}\n  \n\\newlist{subexenum}{enumerate}{1}\n\\setlist[subexenum]{noitemsep,label=(\\alph*),ref=\\theexenumi.\\alph*}\n\\crefname{subexenumi}{Exercise}{Exercises}\n  \n\\newenvironment{exercises}\n{%\n\\subsection*{Exercises}%\n\\addcontentsline{toc}{subsection}{Exercises}%\n\\sectionmark{Exercises}%\n\\begin{exenum}}\n{%\n\\end{exenum}}\n      \n\\addbibresource{bibliography.bib}\n\n\\makeindex\n\n\\begin{document}\n\n\\begin{titlingpage}\n  \\maketitle \n\\end{titlingpage}\n\n\\mbox{}\n\\vfill\n\\doclicenseThis\\thispagestyle{empty}\n\n\\cleardoublepage\n\n\\frontmatter\n\n\\tableofcontents\n\n%\\include{intro}\n\n\\chapter{Introduction}\n\nTo include introduction:\n\\begin{enumerate}\n\\item What are types in mathematics. Dependent types and dependent functions are everywhere in mathematics.\n\\item Why univalent foundations. Why should homotopy be in the foundation of mathematics\n\\item Constructive nature of homotopy type theory. Discuss differences with set theory.\n\\item What this course is about\n\\item How to use this book\n\\item Formal type theory versus informal type theory\n\\item Mention the formalization\n\\end{enumerate}\n\n\\begin{rmk}\n  One difference between set theory and type theory is that every well-formed term is specified along with its type and with its context. One way of looking at this is that there are three sorts in type theory: contexts, types, and terms. On the other hand, there is only one sort in set theory: sets. Sets are governed by the elementhood relation: the formula $x\\in y$ is a well-formed formula of set theory for any two sets $x$ and $y$. In particular, for a given set $x$, the formula $x\\in y$ can be true for many sets $y$, which is very different to the situation in type theory, where every term is assigned a unique type.\n  \n  Another important difference between set theory and type theory is that set theory is formulated in the language of first order logic, whereas type theory is its own deductive system, not making use of any ambient logic. We will see in the present chapter and in the next few chapters what this deductive system looks like.\n\\end{rmk}\n\n\\mainmatter\n\n\\renewcommand{\\thechapter}{\\Roman{chapter}}\n\\setsecnumdepth{subsection}\n\n\\chapter{Martin-L\\\"of's dependent type theory}\n\\input{dtt}\n\\input{pi}\n\\input{nat}\n\\input{inductive}\n\\input{identity}\n\\input{universes-relations}\n\\input{number-theory}\n\\input{finite-types}\n\n\\chapter{Basic concepts of type theory}\n\\input{equivalences}\n\\input{contractible}\n\\input{fundamental}\n\\input{hierarchy}\n\n\\chapter{Univalent mathematics}\n\\input{funext}\n\\input{univalence}\n\\input{circle}\n\n\\chapter{Homotopy pullbacks and pushouts}\n\\input{pullback}\n\\input{pushout}\n\\input{cubical}\n\\input{descent}\n\\input{id-pushout}\n\n\\chapter{The homotopy image of a map}\n\\input{sequences}\n\\input{image}\n\\input{replacement}\n\\input{sets}\n\\section{The classifying type of a group}\n\\input{truncation}\n\\section{Truncations}\n\n\\chapter{Synthetic homotopy theory}\n\\input{homotopy_groups}\n\\input{les}\n\\input{connected}\n\\input{smash}\n\\input{blakers-massey}\n\n%\\include{open_problems}\n\n\\backmatter\n\n\\printbibliography\n\n\\printindex\n\n\\end{document}\n", "meta": {"hexsha": "a5adbc6770439c3241a6b03878f6fa1aa72e0084", "size": 4655, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Book/hott-intro.tex", "max_stars_repo_name": "tadejpetric/HoTT-Intro", "max_stars_repo_head_hexsha": "f4228d6ecfc6cdb119c6e8b0e711fea05b98b2d5", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Book/hott-intro.tex", "max_issues_repo_name": "tadejpetric/HoTT-Intro", "max_issues_repo_head_hexsha": "f4228d6ecfc6cdb119c6e8b0e711fea05b98b2d5", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Book/hott-intro.tex", "max_forks_repo_name": "tadejpetric/HoTT-Intro", "max_forks_repo_head_hexsha": "f4228d6ecfc6cdb119c6e8b0e711fea05b98b2d5", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6496815287, "max_line_length": 627, "alphanum_fraction": 0.7767991407, "num_tokens": 1315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.6187804337438502, "lm_q1q2_score": 0.3454818288208155}}
{"text": "\\subsubsection{Total number of messages sent}\\label{subsubsec:ld2krmessages}\n\nThis is an indication of the energy efficiency of the entire network.\n\nThe maximum number of copies is the dominant factor (\\(85.18\\%\\)), as in the\nhigh density case. In the previous case the size of the hear window was the\nsecond most important factor. Here, instead, we have the broadcast radius\n(\\(6.57\\%\\)) and its combination with the maximum number of copies. The\nunexplained variation is extremely low \\(0.31\\%\\).\n\nFrom \\figref{fig:ldperfmessagesR} we notice that increasing the broadcast radius\nis useful to reduce the total number of messages sent when the maximum number of\ncopies is low. This can be explained by the fact that with an higher value for\n\\(m\\) means that nearly all the users in the network will relay the message\nafter they have successfully heard it. So, if \\(m\\) is high, there is not much\nto do to reduce the total number of messages sent.\n\n\\begin{figure}[htb]\n\t\\centering\n\t\\includegraphics[width=0.6\\textwidth]{img/ld/messages-R-perfplot}\n\t\\caption{Performance plot for the total number of messages sent. The\n\tbroadcast radius can be used to reduce the total number of messages sent\n\twhen the maximum number of copies is not\n\thigh}\\label{fig:ldperfmessagesR}\n\\end{figure}\n", "meta": {"hexsha": "5c08cfa651fa3f739aafabb610861e0525d2d726", "size": 1280, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/chapters/scenarios/low-density/2kr/messages.tex", "max_stars_repo_name": "SpeedJack/pecsn", "max_stars_repo_head_hexsha": "40c757cddec978e06de766c9dff00abf57ccd6b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/chapters/scenarios/low-density/2kr/messages.tex", "max_issues_repo_name": "SpeedJack/pecsn", "max_issues_repo_head_hexsha": "40c757cddec978e06de766c9dff00abf57ccd6b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/chapters/scenarios/low-density/2kr/messages.tex", "max_forks_repo_name": "SpeedJack/pecsn", "max_forks_repo_head_hexsha": "40c757cddec978e06de766c9dff00abf57ccd6b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.2307692308, "max_line_length": 80, "alphanum_fraction": 0.778125, "num_tokens": 317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.34548181972574316}}
{"text": "\\documentclass{dw2014}\n\n\\usepackage{mathptmx}\n\\usepackage{helvet}\n\\usepackage{courier}\n\\usepackage{graphicx}\n\n\\title{Identification of human control during perturbed walking}\n\n\\author{Jason K. Moore, Sandra K. Hnat, Antonie J. van den Bogert\\\\\n  Human Motion and Control Laboratory, Cleveland State University, Cleveland, Ohio, USA\\\\\n  {\\it j.k.moore19@csuohio.edu, s.hnat@vikes.csuohio.edu, a.vandenbogert@csuohio.edu}}\n\n\\date{}\n\n\\begin{document}\n\n\\maketitle\n\n\\section*{Introduction}\n%\nRecent research and commercial activity have shown that gait-related powered\nprosthetics will play an important role in assisting humans with disabilities.\nThese devices include a variety of sensors and actuators than can be coupled to\na control system to provide acutated gait assistance. However, the available\nlightweight, lower extremity exoskeletons lack gait that resembles an\nable-bodied human. To improve the gait of powered prosthetics, our intent is to\nidentify a simple, linear controller from a large set of data collected from\nable-bodied subjects being perturbed by random longitudinal forces.\n%\n\\section*{Methods}\nThe example data shown here was collected from a single subject (age: 29, mass:\n63 kg, height: 172 cm) walking on an instrumented treadmill (V-Gait, Motek\nMedical). The subject was longitudinally perturbed using random white noise\nwith 10\\% std around a nominal 1.2 m/s belt speed. Data was recorded for 8\nminutes at 100 Hz, which included approximately 500 steps of walking. Ankle\nplantarflexion, knee flexion, and hip flexion angles, rates, and moments were\ncomputed using 2D inverse dynamics.\n%\n\\begin{figure}[hbt]\n  \\begin{center}\n    \\includegraphics[width=\\columnwidth]{fig/gains.pdf}\n    \\caption{Gait phase percent scheduled gains for right (blue) and left (red) legs.}\n    \\label{fig:gains}\n  \\end{center}\n\\end{figure}\n\nJoint angle, rate, and torque time series were sectioned into steps based on\nthe right foot's heel strike. Subsequently, 20 evenly spaced data points from\neach series were interpolated along the gait cycle. We assume a simple\nscheduled proportional derivative controller that generates the joint torques\ngiven the joint angles and rates that fits the following form.\n%\n\\begin{equation}\n  \\mathbf{m}(t) = \\mathbf{m}^*(\\varphi(t)) -\n  \\mathbf{K}(\\varphi(t))\\mathbf{s}(t)\n\\end{equation}\n%\nwhere $t$ is an instance of time, $\\varphi(t)$ is the phase in the right leg\ngait cycle, $\\mathbf{m}(t)$ is a vector of joint torques,\n$\\mathbf{m}^*(\\varphi(t))$ is a vector of the nominal joint torques,\n$\\mathbf{K}(\\varphi(t))$ is a gain matrix scheduled with respect to gait\nphase which multiplies the vector of joint angles and rates, $\\mathbf{s}(t)$.\nThis equation is linear in the gains and the reference torques. Given\nsufficient joint angle, rate, and torque measurements, the reference torques\nand the gains can be solved for using linear least squares.\n%\n\\section*{Results}\n%\nHere we present an example result from a controller structure which is limited\nto joint torque generation only from error in the sensors from the same joint.\nFigure \\ref{fig:gains} shows the estimates of the scheduled gains with respect\nto the percent gait cycle in each leg. Figure \\ref{fig:fit} demonstrates an\nexample prediction of the measured ankle plantarflexion torque in the right leg\nby the identified control model.\n%\n\\begin{figure}[b]\n  \\begin{center}\n    \\includegraphics[width=\\columnwidth]{fig/fit.pdf}\n    \\caption{Predicted torque compared to independent validation data.}\n    \\label{fig:fit}\n  \\end{center}\n\\end{figure}\n%\n\\section*{Discussion}\n%\nWe are able to identify a simple linear controller that exhibits larger gains\nin the stance phase than in the swing phase. Additionally, similar gain\npatterns in the right and left legs are observed that use both positive and\nnegative feedback. The controller is capable of predicting the measured joint\ntorques with greater than 65\\% VAF in all joints. Results and conclusions from\na larger sample of subjects and conditions will be presented at the conference.\n\n%\\section*{Acknowledgments}\n%\n%This research was funded by the Ohio's Wright Center for Sensor Systems\n%Engineering and the Parker Hannifin Corporation.\n\\end{document}\n", "meta": {"hexsha": "c30c8428287eaca2172fe9b4e8c9c0be4d8d7fa2", "size": 4211, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "abstract/moore.tex", "max_stars_repo_name": "moorepants/DW2014", "max_stars_repo_head_hexsha": "b588f837ecaaa098dea5db6a72903632edd352aa", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "abstract/moore.tex", "max_issues_repo_name": "moorepants/DW2014", "max_issues_repo_head_hexsha": "b588f837ecaaa098dea5db6a72903632edd352aa", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "abstract/moore.tex", "max_forks_repo_name": "moorepants/DW2014", "max_forks_repo_head_hexsha": "b588f837ecaaa098dea5db6a72903632edd352aa", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.5353535354, "max_line_length": 89, "alphanum_fraction": 0.7791498456, "num_tokens": 1060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.34548181972574304}}
{"text": "%!TEX root = ../thesis.tex\n%*******************************************************************************\n%****************************** Second Chapter *********************************\n%*******************************************************************************\n\n\\chapter{The Rotating Sun}\n\n\\section{Differential Rotation}\nThe sun is known to rotate differentially, unlike the earth. This means that angular rate of rotation of a point in the sun about its spin axis is depends on depth and latitude, $\\Omega = \\Omega(r,\\theta)$. Splitting of p-mode\\footnote{pressure waves are also called p-modes} frequencies due to differential rotation is well understood and has a long history of inversion analysis \\cite{ritzwoller,lavely92,schou98}.\nThis $\\Omega$ is generally taken to be symmetric about the equitorial plane \\cite{ritzwoller}.\n\nAs a result of Alfven's freezing theorem\\footnote{Alfven's freezing theorem states that in a perfectly conducting plasma, magnetic flux through \\textit{every} surface is conserved as it gets dragged along with the ambient flow. See \\cite{goedbloed2004} for proof. This theorem implies that magnetic field lines are $frozen$ in the plasma as it flows.}, differential rotation is responsible for winding the solar magnetic field around its spin axis in an axisymmetric fashion. Thus we'll be investigating the effects of an axis symmetric magnetic field on the spectrum in this work, although the method we develop can very well accommodate non-axisymmetric fields too.\n\\section{Detection from frequency spectrum}\nBecause of axis symmetry of differential rotation, the flow profile is given as,\n\\begin{equation}\n\\vrot = \\sum_{s = 1,3,5,...}^{\\infty} -w_s^0(r) \\partial_{\\theta} Y_s^0 \\ev{\\phi}\n\\end{equation}\n\nNote that $w_1^0$ is responsible for shell like (pure) rotation as it couples with $\\partial_{\\theta} Y_1^0 \\sim \\sin\\theta$. Hence $w_3^0$ onwards components of flow are responsible for the differential part of the rotation. The fact that the azimuthal index for the $\\vrot$ profile is $0$ means that it has no azimuthal dependence. Finding frequency splittings due to differential rotation is a problem in DPT or QDPT depending on whether we're using the isolated multiplet approximation or not. The isolated multiplet approximation is the assumption that there exists negligible cross coupling between different $\\mode{n}{l}$ modes. \nBelow we outline the QDPT approach to the problem because when applied to a single multiplet $_n S_l$ it reduces to the DPT approach. It has been argued via analysis differential rotation coupling of \\mode{n}{1} and \\mode{n}{3} multiplets that eigenfrequency correction to DPT via QDPT from cross coupling between these two is negligible ($\\sim 1 \\mu Hz$) \\cite{lavely92}. We'll show in Chapter 5 (figure \\ref{fig:split_dr}) that for $l\\sim 100$ modes, a frequency corrections of upto $600 nHz$ frequencies are obtained when QDPT is used.\n\n%which is close to the correction obtained due presence of realistically strong magnetic fields too, and hence cannot be ignored in an analysis which accounts for both differential rotation and magnetic fields.\n\n\\subsection{QDPT Analysis}\nThe pertubation operator \\dLd for a differential rotaional flow is given by \n\\begin{equation}\n\\dLd = -2i \\omega \\rho \\vrot \\cdot \\grad\n\\end{equation}\nwhere $\\omega$ is the reference frequency in the problem, and $\\rho$ is the static background density profile \\cite{ritzwoller}.\nThe supermatrix element $Z_{k' k}$ for a pertubation \\dLd is given by\n\\begin{equation}\nZ_{k' k} = \\Lamdr_{k'k} - \\delta_{k'k} (\\omref^2 - \\omega_k^2)\n\\end{equation}\nwhere $\\Lamdr$ is the coupling matrix element $\\Lamdr = \\inner{\\xiv_{k'}}{\\dLd \\xiv_{k}}$ .\nCoupling matrix element is given by\n\\begin{equation}\n\\Lamdr_{k'k} = 8 \\pi \\omref \\gam{l'}\\gam{l} \\oddsum{s} \\gam{s} \\wigred{-m}{0}{m} \\ints dr \nr^2 w_s^0(r) T_s(r)\n\\end{equation}\nwhere the sensitivity kernel $T_s$ is given by\n\\begin{dmath}\nT_s(r) = (1-(-1)^{s+l+l'}) \\om{l'}{0} \\om{l}{0} \\wigred{-1}{0}{1} r^{-1}\n \\enc{U'V+V'U-U'U-\\frac{1}{2}\\enc{l'(l'+1) + l(l+1) - s(s+1) V'V}}\n\\end{dmath}\nwhere the rounded brackets represent Wigner 3j symbols \\cite{ritzwoller}, and $\\gam{l}$ and $\\Omega_{l}^{N}$ are constants defined in Appendix \\ref{app_conventions}.\n\\subsection{Selecition rules in mode coupling}\\label{sec:selec_rules}\nThis matrix element enforces the following selection rules for inter-mode interaction which derive from the properties of Wigner 3j symbols \\cite{lavely92}.\n\\begin{enumerate}\n\\item $m'=m$\n\\item $l'+l+s = \\text{odd}$\n\\item $|l'-l| \\leq s \\leq l'+l$\n\\end{enumerate}\nIt should be noted here that even though only sum over odd s is considered, the expression for $T_s$ is general and holds for all $s$. This has been verified independently using the Mathematica packaged developed for the sake of this work \\cite{GSH_repo}. Hence, as far as self coupling is concerned ($l'=l$), $T_s$ vanishes for even $s$. This means that even if $\\Omega(\\theta,\\phi)$ had a component which is antisymmetric about the equatorial plane, DPT analysis would not reveal any signature of that in the frequency splittings.\n\n\\subsubsection{Form of supermatrix $Z_{k'k}$}\n\nIt is clear from selection rule (1) in \\ref{sec:selec_rules} that $Z_{k'k}$ is going to be a sparse matrix consisting of a diagonal and a number of sub-diagonals (proportional to number of multiplets being considered). Also, as $s$ is always odd, $l-l'$ has to be even for non-zero coupling as consequence of selection rule (2). This influences our choice of modes whose inter-coupling will be studied hereafter. Figure (\\ref{fig:coup_mat}) is a visual representation of a typical supermatrix consisting of three multiplets. The logarithm scale demonstrates the order of magnitude difference between self-coupling (main diagonal elements), and cross-coupling (subdiagonal elements). Also notice that largest elements (yellow) are in the first and third section in the main diagonal. These are large because these frequencies are placed away from $\\omref$ which is taken to be mean of the three mode frequencies. The relative weakness of the sub-diagonal terms compared to the main-diagonals is because $l-l'\\geq 2$ forces $s\\geq 2$ which makes the largest component of differential rotation, i.e. $w_1^0$, unable to couple these modes; $w_3^0$ and $w_5^0$ are one and two orders of magnitude smaller than $w_1^0$ respectively.\n\n\\begin{figure}[h]\n\\includegraphics[scale=0.6,center]{Chapter2/figs/coup_mat}\n\\caption{Visualisation of $\\log_{10}|Z_{k'k}|$ in $\\mu Hz^2$ for the multiplets $\\mode{0}{11}$, $\\mode{0}{13}$, and $\\mode{0}{15}$ with frequencies $603.69 \\mu Hz$, $641.84\\mu Hz$, and $677.55 \\mu Hz$ respectively. Numbers on the X and Y axes represent cumulative $m$ of all three multiplets. White spaces correspond to $0$ value.}  \n\\label{fig:coup_mat}\n\\end{figure}", "meta": {"hexsha": "c74f22f3a8fffcbeadc64de1a41447e4e3f662b9", "size": 6849, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapter2/chapter2.tex", "max_stars_repo_name": "tuneerch/masters_thesis", "max_stars_repo_head_hexsha": "487646d71dc5f1f2bfbb8e29ee4878d14825c344", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter2/chapter2.tex", "max_issues_repo_name": "tuneerch/masters_thesis", "max_issues_repo_head_hexsha": "487646d71dc5f1f2bfbb8e29ee4878d14825c344", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter2/chapter2.tex", "max_forks_repo_name": "tuneerch/masters_thesis", "max_forks_repo_head_hexsha": "487646d71dc5f1f2bfbb8e29ee4878d14825c344", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 108.7142857143, "max_line_length": 1226, "alphanum_fraction": 0.734413783, "num_tokens": 1816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.34548181972574304}}
{"text": "\\documentclass[a4paper,12pt]{article}\n\n% Font\n\\usepackage[T1]{fontenc}\n\\usepackage{gentium}\n\n% Math packages\n\\usepackage{amsmath}\n\\usepackage{amsfonts}\n\\usepackage{amssymb}\n\\usepackage{amsthm}\n\\usepackage{bm}\n\n% Define symbol shortcuts\n\\newcommand{\\cc}{\\mathcal{C}}\n\\newcommand{\\dd}{\\mathcal{D}}\n\\newcommand{\\hh}{\\mathcal{H}}\n\\newcommand{\\xx}{{\\bm x}}\n\\newcommand{\\yy}{{\\bm y}}\n\n% Math environment\n\\newtheorem*{thm}{Theorem}\n\n% Better list management:\n% - vertical spacing in lists\n% - items in lists start with dash not bullet point.\n\\usepackage{enumitem}\n\\setlist{label=\\textemdash,\n  itemsep=0pt, topsep=3pt, partopsep=0pt} \n\n% Include graphics\n\\usepackage{graphicx}\n\\usepackage{subcaption}\n\n% Page format \n\\usepackage[top=2cm,left=2cm,right=2cm,bottom=2cm]{geometry}\n\\usepackage{float}\n\n\\begin{document}\n%%% HEADER\n\\raisebox{0.6in}[0in]{\\makebox[\\textwidth][r]{\\it Unproofed version }}\n\\vspace{-0.7in}\n\n\\begin{center}\n\\bf\\large MA2823 : Foundations of Machine Learning \\\\\nChapter 5 : Linear Regression\n\\end{center}\n\n\\noindent\nLecturer : Chlo\\'e-Agathe Azencott   \n\\hfill\nScribes : Emilie Leblanc, Antoine Salon, Hippolyte Jacomet \n\n\\noindent\n\\rule{\\textwidth}{1pt}\n\n\\medskip\n\n%%% NOTES START HERE\nIn this chapter we will see how to :\n\\begin{itemize}\n\\item define parametric methods ;\n\\item define the maximum likelihood estimator and compute it\nfor Bernoulli, multinomial and Gaussian densities ;\n\\item define the Bayes estimator and compute it for normal\npriors ;\n\\item compute the maximum likelihood estimator / least-square\nfit solution for linear regression ;\n\\item compute the maximum likelihood estimator for logistic\nregression.\n\\end{itemize}\n\n\\section{Parametric methods}\n\nIn this chapter we would like to define different ways of building estimators that are part of a statistical model, and how to assess their performances.\n\n\\paragraph{Definitions and notations} Let us consider a training set of $n$ $p$-dimensional vectors denoted by $\\mathcal{X}=\\{x^i\\}_{i=1,\\dots,n}$, and let's assume that each of these observation follows a law of probability given a parameter $\\theta$. \n\n\\[\n\\forall i \\in [1,\\dots,n],\\ \\xx^{i}\\sim{}p(\\xx|\\theta)\n\\]\\\\\nThe {\\em parametric estimation} consists in {\\em assuming} a form for $p(\\xx|\\theta)$ and then {\\em estimating} the parameter $\\theta$ using our training set $\\mathcal{X}$. \\\\\nFor example, if we assume that the observations of our training set follow a Gaussian distribution $p(x_{j}|\\theta_j)\\sim{}\\mathcal{N}(\\mu_j,{\\sigma_j}^2)$ our goal would be to estimate the parameter $\\theta=\\{\\mu_1,\\sigma_1,\\dots,\\mu_p,\\sigma_p\\}$. \\\\\n\\\\\nTo achieve that goal, the observations of the training set $\\xx^i$ are usually assumed to be {\\em independent and identically distributed} (i.i.d.). \\\\\n\nIn the following sections we sill study two different methods to estimate the parameters : the {\\em maximum likelihood estimation} and the {\\em Bayes estimation}.\n\n\n\\subsection{Maximum likelihood estimation}\n\nThis first method relies on the idea that $\\theta$ should maximize the likelihood for $\\mathcal{X}$ to be drawn from the law of probability we chose in our model.\n\n\\paragraph{Likelihood and log-likelihood} We call {\\em likelihood of} $\\theta$ given $\\mathcal{X}$ the function : $\\ell(\\cdot{}|\\mathcal{X}) : \\theta \\mapsto p(\\mathcal{X}|\\theta).$\\\\\nIn the case of an i.i.d. sample $\\mathcal{X}$, this becomes :\n\n\\[\\ell(\\theta|\\mathcal{X})=p(\\mathcal{X}|\\theta)=p(\\xx^1|\\theta)p(\\xx^2|\\theta)\\dots{}p(\\xx^p|\\theta)\\] \\\\\nIt is often useful to also consider the {\\em log-likelihood}, simply defined by $\\mathcal{L} (\\cdot{}|\\mathcal{X}) : \\theta \\mapsto \\log \\ell(\\theta|\\mathcal{X})$, which in our previously mentioned case becomes :\n\\[\\mathcal{L}(\\theta|\\mathcal{X})=\\log{p(\\xx^1|\\theta)}+\\dots{}+\\log{p(\\xx^n|\\theta)}\\]\n\\\\\nGiven these two functions, we will then try to find the estimator that maximizes them, called the {\\em maximum likelihood estimator} or MLE, and defined by :\n\n\\[\\hat{\\theta}=\\arg\\underset{\\theta}\\max \\  \\ell(\\theta|\\mathcal{X})=\\arg\\underset{\\theta}\\max \\  \\mathcal{L}(\\theta|\\mathcal{X})\\]\\\\\n\n\nLet us now look at these MLE for Bernoulli, Multinomial and Normal laws.\n\n\\subsubsection{Bernoulli density}\n\nSuch a law corresponds to observations that reflect two states of either failure or success (think of a coin toss for example), and thus let us consider a data set $\\mathcal{X}=\\{x^i\\}_{i=1,\\dots,n}$ with  $x^i\\in\\{0,1\\}$ $\\forall i\\in[1,\\dots,n]$.\\\\\n\\\\\nThe Bernoulli density is given by $P(X=x|p_0)={p_0}^{x}(1-p_0)^{(1-x)}$, let us try to find the MLE $\\ \\hat{p_0}$ of the parameter $p_0$.\\\\\n\\\\\nWe first compute the log-likelihood :\n\n\\[\\mathcal{L}(p_0|\\mathcal{X})=\\log{P(\\mathcal{X}|p_0)}=\\sum_{i=1}^n\\left(x^i\\log p_0 + (1-x^i)\\log{(1-p_0)}\\right)\\]\nThis is a concave function which we can easily maximize by setting its gradient to 0 :\n\n\\[\\frac{\\sum_{i=1}^nx^i}{\\hat{p_0}}-\\frac{n}{(1-\\hat{p_0})}+\\frac{\\sum_{i=1}^nx^i}{(1-\\hat{p_0})}= 0\n\\]\nWhich yields the MLE of $p_0$ :\n\n\\[\\hat{p_0}=\\frac{1}{n}\\sum_{i=1}^nx^i\\]\n\n\n\\subsubsection{Multinomial density}\n\nLet us consider $K$ mutually exclusive and exhaustive classes. The probability for each class to occur is $p_k$, with $\\sum_{k=1}^Kp_k=1$. We represent these classes with $K$ indicator variables $x_1, x_2, \\dots, x_K$ knowing \n\\[\n    x_k= \n\\begin{cases}\n    1& \\text{if the outcome is class } k\\\\\n    0              & \\text{otherwise}\n\\end{cases}\n\\]\nThe joint probability distribution is given by :\n\\[P(x_1,x_2,\\dots,x_K)=\\displaystyle\\prod_{k=1}^{K}p_k^{x_k}\\]\\\\\n\\\\\nLet us compute the MLE $\\bm{\\hat{p}}=(\\hat{p_1},\\dots,\\hat{p_K})$. The observations are i.i.d. thus the log-likelihood looks dramatically like :\n\\\\\n\\[\\mathcal{L}(\\bm p|\\mathcal{X})=\\sum_{i=1}^n\\sum_{k=1}^K x_k^i\\log p_k\n\\]\\\\\nAnd we now have to maximize it under the constraint $\\displaystyle\\sum_{k=1}^Kp_k=1$.\\\\\nWe must call on to a Lagrange multiplier $\\lambda$ and define the Lagrangian function \n\\[\\mathcal{F} : (\\bm p, \\lambda) \\mapsto \\mathcal{L}(\\bm p|\\mathcal{X})-\\lambda \\left(\\sum_{k=1}^Kp_k - 1\\right)\\]\nSetting its gradient to zero gently yields a system of equations from which we are happy to learn that $\\lambda=n$ and consequently that\n\n\\[\\hat{p}_k=\\dfrac{1}{n}\\displaystyle\\sum_{i=1}^nx_k^i\\ \\ \\ \\ \\ \\ \\ \\ \\forall k \\in [1,\\dots,K]\\]\n\n\n\\subsubsection{Gaussian distribution}\n\nLet us now assume that our observations $x^i$ are i.i.d. following a Gaussian distribution, i.e. : \n\n$\\forall i \\in [1,\\dots,n]$,\n\\[x^i\\sim\\mathcal{N}(\\mu,\\sigma^2)\\]\n\n\\[p(x^i|\\mu,\\theta)=\\dfrac{1}{\\sqrt[]{2\\pi}\\sigma}\\exp\\left[-\\frac{(x^i-\\mu)^2}{2\\sigma^2}\\right]\\]\n\\\\\n\nSetting the gradient of the log-likelihood to zero yields the estimators :\n\n\\[ \\hat{\\mu} = \\frac{1}{n} \\sum_{i=1}^nx^i\\]\n\\[ \\hat{\\sigma}^2 = \\frac{1}{n} \\sum_{i=1}^n (x^i-\\hat{\\mu})^2\\]\n\n\\subsection{Bias-variance trade-off}\n\nWe can assess the performance of the estimator (be it obtain through MLE or another method) by computing the {\\em mean squared error} or MLE, defined by :\n\n\\[\\mbox{MSE}(\\hat{\\theta}) = \\mathbb{E}[(\\hat{\\theta}-\\theta_0)^2]\\]\n\n\\paragraph{Bias-variance trade-off} Let us try to link this MSE to two previously known notions that help characterize our estimator, the variance and the bias. As a reminder, the {\\em bias} of an estimator is the difference between this estimator's expected value and the true value of the parameter being estimated : $\\mbox{Bias}(\\hat{\\theta})=\\mathbb{E}[\\hat{\\theta}]-\\theta_0$. \n\n\\begin{align*}\n\\mbox{MSE}(\\hat{\\theta}) &= \\mathbb{E}[(\\hat{\\theta}-\\theta_0)^2]\\\\  \n&= \\mathbb{E}\\left[(\\hat{\\theta}-\\mathbb{E}[\\hat{\\theta}])^2+2\\hat{\\theta}\\mathbb{E}[\\hat{\\theta}]-\\mathbb{E}[\\hat{\\theta}]^2-2\\hat{\\theta}\\theta_0+\\theta_0^2\\right]\\\\\n&=\\mbox{Var}(\\hat{\\theta})+\\mathbb{E}[\\hat{\\theta}]^2-2\\mathbb{E}[\\hat{\\theta}]\\theta_0+\\theta_0^2\\\\\n&=\\mbox{Var}(\\hat{\\theta})+\\mbox{Bias}^2(\\hat{\\theta})\n\\end{align*}\\\\\nWe see that the MSE is a balance between these two positive expressions, hence the idea of a {\\em bias-variance trade-off}. We understand that a biased estimator may achieve better MSE than an\nunbiased one, as illustrated below :\n\n\\begin{center}\n\\includegraphics[width=100mm]{biasvariance.png}\n\\end{center}\n\n\\subsection{Bayes estimator}\nFrom now on let us study another way of building an estimator, using Bayes rule which in its general form is :\n\\[P(C|\\xx)  = \\dfrac{P(C)p(\\xx|C)}{p(\\xx)}\\]\\\\\nHere we choose to treat $\\theta$ as a random variable with a given prior distribution $p(\\theta)$. Considering an observation-set $\\mathcal{X}$, the Bayes rule yields :\n\n\\[p(\\theta|\\mathcal{X})=\\frac{p(x|\\theta)p(\\theta)}{p(\\mathcal{X})}\\]\\\\\n\\\\\nWe define the {\\em Bayes estimate} as the conditional expected value of $\\theta$ given our data set $\\mathcal{X}$ :\n\\[\\hat{\\theta}_{\\mbox{Bayes}}=\\mathbb{E}[\\theta|\\mathcal{X}]=\\int{\\!\\theta p(\\theta|\\mathcal{X})d\\theta}\\]\\\\\n\\\\\nHere's a reminder of the estimates we have previously seen :\\\\\n\n{\\em Maximum a posteriori} estimate :\n\\[\\hat{\\theta}_{\\mbox{MAP}}=\\arg\\underset{\\theta}\\max \\  p(\\theta|\\mathcal{X})\\]\n\n{\\em Maximum likelihood} estimate :\n\\[\\hat{\\theta}_{\\mbox{MLE}}=\\arg\\underset{\\theta}\\max \\  p(\\mathcal{X}|\\theta)\\]\\\\\n\n\n\\subsubsection{Bayes estimator for normal priors}\n\nLet us consider $n$ i.i.d. data points $x^i$ following a normal law, $x^i\\sim\\mathcal{N}(\\theta,\\sigma^2)$ and let's assume that $\\theta$ is of Gaussian prior distribution : $\\theta\\sim\\mathcal{N}(\\mu,\\sigma_0^2)$.\\\\\n\\\\\nWe know that the MLE of $\\theta$ is its sample mean : $\\hat{\\theta}_{\\mbox{MLE}} = \\frac{1}{n} \\sum_{i=1}^nx^i$ and we would like to compare it to its Bayes estimator.\\\\\n\\\\\nAfter a long and troublesome computation, a quick look at $p(\\theta|\\mathcal{X})$ shows us that it follows a normal distribution with mean $m$ and variance $s^2$ :\n\n\\[m = \\frac{n\\hat{\\theta}_{\\mbox{MLE}}\\sigma^2+\\mu\\sigma_0^2}{n\\sigma^2+\\sigma_0^2}\n\\]\n\n\\[s^2 = \\frac{\\sigma^2\\sigma_0^2}{n\\sigma^2+\\sigma_0^2}\n\\]\\\\\n\\\\\nKnowing that :\n\\[\\mathbb{E}[\\theta|\\mathcal{X}]=m\\]\nWe can conclude with :\n\\[\\hat{\\theta}_{\\mbox{Bayes}}=\\frac{\\frac{n}{\\sigma_0^2}}{\\frac{n}{\\sigma_0^2}+\\frac{1}{\\sigma^2}}\\hat{\\theta}_{\\mbox{MLE}}+\\frac{\\frac{1}{\\sigma^2}}{\\frac{n}{\\sigma_0^2}+\\frac{1}{\\sigma^2}}\\mu\n\\]\\\\\n\\\\\nIt is interesting to notice that when n increases, $\\hat{\\theta}_{\\mbox{Bayes}}$ gets closer to the sample average (uses\ninformation from the sample) and When $\\sigma$ is small, $\\hat{\\theta}_{\\mbox{Bayes}}$ gets closer to $\\mu$ (little uncertainty\nabout the prior). \n\n\\section{Linear regression}\n\nThe goal of a {\\em linear regression} is to approximate the law followed by our data \\(\\textit{y}\\) by a linear combination of observed variables \\(\\xx\\) such as :\n\\[ f(\\xx|\\beta)= \\displaystyle\\sum_{j=1}^{p} \\beta_j*x_j + \\beta_0\\]\nwith \\(\\xx^i \\in \\mathbb{R}^p\\)  and \\(\\textit{y}^i \\in \\mathbb{R}\\) and noting \\(\\dd = {\\{\\xx^i,\\textit{y}^i\\}}_{\\textit{i}=1,..,\\textit{n}}\\). \n\\begin{center}\n\\includegraphics[width=100mm]{linear_regression_example.png}\n\\end{center}\n\nWe assume that the error \\(\\epsilon\\) we have while doing a regression is \\textbf{Gaussian distributed}. Therefore, with \\(y = g(\\xx) + \\epsilon \\),  \\(f(\\xx|\\beta)\\) being \\(g\\)'s estimator, we have : \n\\begin{center}\n\\(\\epsilon = y - g(\\xx)\\) and \\(\\epsilon\\sim{}\\mathcal{N}(0,{\\sigma}^2)\\)\n\\end{center}\n\nWe therefore have our \\(\\dd = {\\{\\xx^i,\\textit{y}^i\\}}_{\\textit{i}=1,..,\\textit{n}}\\) observations (the blue dots), the linear regression obtained \\(\\mathbb{E}(y|x) = \\beta*x + \\beta_0\\) and, for each new \\(x^*\\) point, we can compute the hypothetical \\(y^* = \\mathbb{E}(y|x^*)\\) value and the corresponding error \\(\\epsilon^* \\) and confidence interval given by \\(p(y|x^*)\\) since : \n\\[p(y|\\xx)\\sim{}\\mathcal{N}(f(\\xx|\\beta),{\\sigma}^2)\\]\n\\begin{center}\n\\includegraphics[width=100mm]{LR_2.png}\n\\end{center}\n\n\\subsection{Maximum likelihood estimation under Gaussian noise}\n\nWe are now going to use the \\textit{maximum likelihood estimation} in order to find the best linear regression possible to fit the data and predict new points. \\\\\n\\\\\nUnder Gaussian noise, considering i.i.d. observations and with \\(p(y|\\xx)\\sim{}\\mathcal{N}(f(\\xx|\\beta),{\\sigma}^2)\\), the log-likelihood defined earlier becomes : \n\\begin{align*}\n\\mathcal{L}(\\beta|\\dd) &= \\log\\displaystyle\\prod_{i=1}^{n} p(y^i|\\xx^i) + \\log\\displaystyle\\prod_{i=1}^{n} p(\\xx^i) \\\\  &= \\log \\left(\\displaystyle\\prod_{i=1}^{n} \\frac{1}{\\sqrt{2\\pi}\\sigma}*exp\\left[ - \\frac{(y^i - f(\\xx^i|\\beta))^2}{2\\sigma^2} \\right] \\right ) + Cte  \\\\\n& = Cte - \\frac{1}{2\\sigma^2} \\displaystyle\\sum_{i=1}^{n} (y^i - f(\\xx^i|\\beta))^2\n\\end{align*}\nSince \\(\\log\\displaystyle\\prod_{i=1}^{n} p(\\xx^i)\\) is independent of \\(\\beta\\), its value is added to a term \\(Cte\\) along with others. \\\\\nAssuming Gaussian error, maximizing the likelihood \\(\\mathcal{L}(\\beta|\\dd)\\) is therefore equivalent to minimizing the sum of squared residuals \\(\\displaystyle\\sum_{i=1}^{n} (y^i - f(\\xx^i|\\beta))^2\\). \nThis expression of the residual sum of squares can also be written in matrix form : \n\\begin{align*}\nRSS(\\beta) &= \\displaystyle\\sum_{i=1}^{n} (y^i - f(\\xx^i))^2 \\\\  &= \\displaystyle\\sum_{i=1}^{n} \\left( y^i - \\beta_0 - \\displaystyle\\sum_{j=1}^{p} x_j^i \\beta_j \\right)^2 \\\\\n& = (y - \\textbf{\\textit{X}} \\beta)^T * (y - \\textbf{\\textit{X}} \\beta)\n\\end{align*}\nwith \\(\\textbf{\\textit{X}} = \\left( \\begin{array}{ccccc}\n1 & x_1^1 & x_2^1 & ... & x_p^1 \\\\\n1 & x_1^2 & x_2^2 & ... & x_p^2 \\\\\n. & . & . & ... & .\\\\\n. & . & . & ... & .\\\\\n. & . & . & ... & .\\\\\n1 & x_1^n & x_2^n & ... & x_p^n \\end{array} \\right) \\). \nHere, we added a vector \\(\\left( \\begin{array}{c}\n1 \\\\\n1 \\\\\n.\\\\\n. \\\\\n. \\\\\n1 \\end{array} \\right)\\) to \\({\\{\\xx^i\\}}_{\\textit{i}=1,..,\\textit{n}}\\) in  \\(\\textbf{\\textit{X}}\\)'s expression in order to compute the scalar \\(\\beta_0\\). \\\\\n\\\\ \nHistorically, the use of the residual sum of squares minimization can be attributed to Carl Friedrich Gauss (to predict the location of Ceres) and Adrien Marie Legendre. \n\\\\\n\\\\\n\\textbf{In this method, under which conditions is \\(\\beta\\)'s estimator unique ? }\n\\\\\n\n\\begin{itemize}\n\\item \nIn order to minimize \\(RSS(\\beta)\\), \\(\\textbf{\\textit{X}}\\) must have a full column rank, hence \\(\\textbf{\\textit{X}}^T\\textbf{\\textit{X}}\\) \\textit{invertible}. In this case, the \\(\\beta\\) minimizing \\(RSS(\\beta)\\) is : \n\\[\\hat{\\beta} = (\\textbf{\\textit{X}}^T\\textbf{\\textit{X}})^{-1} \\textbf{\\textit{X}}^T y\\]\n\\item \nIf \\(\\textbf{\\textit{X}}^T\\textbf{\\textit{X}}\\) is not invertible (or \\textit{rank-deficient}), we can use its pseudo-inverse. However, when doing so, we must keep in mind that the solution is \\textit{not} unique. \\\\ A pseudo-inverse of\\textbf{ A} is a matrix \\textbf{G} such as \\textbf{AGA = A}.\n\\end{itemize}\n \n\n\n\\subsection{Gauss-Markov Theorem}\n\n\\textbf{Gauss-Markov Theorem :} Under the assumption that \\(\\epsilon\\sim{}\\mathcal{N}(0,{\\sigma}^2)\\), the least-squares estimator of \\(\\beta\\) is its best linear unbiased estimator. This Best Linear Unbiased Estimator is unique if \\(\\textbf{\\textit{X}}^T\\textbf{\\textit{X}}\\) is invertible. We call it the \"\\textit{BLUE}\". \n\\\\\n\\\\\nIndeed, with \\(\\hat{\\beta} = (\\textbf{\\textit{X}}^T\\textbf{\\textit{X}})^{-1} \\textbf{\\textit{X}}^T y\\), we can show that (demonstration of the Gauss-Markov Theorem) : \n\\begin{center}\n\\(\\forall \\beta^*\\) unbiased estimator of \\(\\beta\\), \\(\\mathbb{V}ar(\\beta^*) \\geq \\mathbb{V}ar(\\hat{\\beta})\\) and when \\(\\mathbb{V}ar(\\beta^*) = \\mathbb{V}ar(\\hat{\\beta}) => \\beta^* = \\hat{\\beta} \\)\n\\end{center}\n\\vspace{1cm}\n\n\\textbf{Proof of the Gauss-Markov theorem :} \n\\\\ We have \\(\\hat{\\beta} = (\\textbf{\\textit{X}}^T\\textbf{\\textit{X}})^{-1} \\textbf{\\textit{X}}^T y\\) \\textit{BLUE} estimator and let \\(\\beta^* = A y\\) be another linear estimator of \\(\\beta\\). As we're restricting to unbiased estimators, minimum mean squared error implies minimum variance. The goal is therefore to show that such an estimator has a variance no smaller than that of \\(\\hat{\\beta}\\). \nWe have \\(A = (\\textit{\\textbf{X}}^T \\textit{\\textbf{X}})^{-1} \\textit{\\textbf{X}}^T + D\\) where \\(D\\) is a non-zero matrix. \n\\\\ In order to have \\(\\beta^*\\) unbiased, we compute: \n\\begin{align*}\n\\mathbb{E}[\\beta^*] &= \\mathbb{E}[Ay] \\\\  &= \\mathbb{E}[((\\textit{\\textbf{X}}^T \\textit{\\textbf{X}})^{-1} \\textit{\\textbf{X}}^T + D)(\\textit{\\textbf{X}}\\beta + \\epsilon)] \\\\\n& = ((\\textit{\\textbf{X}}^T \\textit{\\textbf{X}})^{-1} \\textit{\\textbf{X}}^T + D)\\textit{\\textbf{X}}\\beta + ((\\textit{\\textbf{X}}^T \\textit{\\textbf{X}})^{-1} \\textit{\\textbf{X}}^T + D)\\mathbb{E}[\\epsilon] \\\\ &= ((\\textit{\\textbf{X}}^T \\textit{\\textbf{X}})^{-1} \\textit{\\textbf{X}}^T + D)\\textit{\\textbf{X}}\\beta \\\\ &=  (\\textit{\\textbf{I}} + D\\textit{\\textbf{X}})\\beta\n\\end{align*}Since \\(\\mathbb{E}(\\epsilon) = 0\\). Therefore, in order to have an unbiased  \\(\\beta^*\\) estimator, we must have \\(DX = 0\\). \\\\\nNow, we calculate and compare the variances :\n\\begin{align*}\n\\mathbb{V}ar(\\hat{\\beta}) &= \\mathbb{E}[((\\textit{\\textbf{X}}^T \\textit{\\textbf{X}})^{-1} \\textit{\\textbf{X}}^T \\epsilon \\epsilon^T \\textit{\\textbf{X}} (\\textit{\\textbf{X}}^T \\textit{\\textbf{X}})^{-1}] \\\\  &= (\\textit{\\textbf{X}}^T \\textit{\\textbf{X}})^{-1} \\textit{\\textbf{X}}^T * \\sigma \\textit{\\textbf{I}} * \\textit{\\textbf{X}} (\\textit{\\textbf{X}}^T \\textit{\\textbf{X}})^{-1} \\\\\n& = \\sigma^2 (\\textit{\\textbf{X}}^T \\textit{\\textbf{X}})^{-1} \n\\end{align*}\n\\begin{align*}\n\\mathbb{V}ar(\\beta^*) &= \\mathbb{V}ar(Ay)  \\\\  &= A\\mathbb{V}ar(y)A^T \\\\\n& = \\sigma^2*AA^T \\\\ &= \\sigma^2*((\\textit{\\textbf{X}}^T \\textit{\\textbf{X}})^{-1} \\textit{\\textbf{X}}^T + D)(\\textit{\\textbf{X}}^T \\textit{\\textbf{X}})^{-1} \\textit{\\textbf{X}}^T + D)^T \\\\ &= \\sigma^2[(\\textit{\\textbf{X}}^T\\textit{\\textbf{X}})^{-1} + (\\textit{\\textbf{X}}^T\\textit{\\textbf{X}})^{-1}(D\\textit{\\textbf{X}})^T + D(\\textit{\\textbf{X}}(\\textit{\\textbf{X}}^T\\textit{\\textbf{X}})^{-1} + DD^T] \\\\ &= \\sigma^2\\textit{\\textbf{X}}^T\\textit{\\textbf{X}})^{-1} + \\sigma^2 DD^T \\\\ &= \\mathbb{V}ar(\\hat{\\beta}) + \\sigma^2 DD^T\n\\end{align*}since \\(DX = 0\\). \\\\\nTherefore \\(\\mathbb{V}ar(\\beta^*) = \\sigma^2 D D^T +  \\mathbb{V}ar(\\hat{\\beta})\\) and since \\(\\sigma^2 D D^T \\) is positive semi-defined and minimal for \\(D = 0\\),  \\(\\mathbb{V}ar(\\beta^*)\\) exceeds \\(\\mathbb{V}ar(\\hat{\\beta})\\).  \n\n\n\\subsection{Interpretation with correlated or uncorrelated variables}\n\nThe interpretation of the coefficients of a linear regression can be tricky. Indeed, once we have found \\(\\beta_0,...,\\beta_p\\) such as : \n\\[f(\\textbf{\\textit{X}}) = \\beta_0 + \\beta_1 x_1 + ... + \\beta_p x_p\\]\nwe first have to study the correlation of the variables. \n\\begin{itemize}\n\\item If the variables are \\textit{decorrelated}, each coefficient can be estimated separately and the interpretation is thus easy : \"A change in 1 in \\(x_j\\) is associated with a change of \\(\\beta_j\\) in Y, while everything else stays the same.\"\n\\end{itemize}\n\\begin{itemize}\n\\item This interpretation is no longer true if the variables are \\textit{correlated}. The correlations between variables cause problems : the variance of all coefficients tend to increase and the interpretation is much harder (when \\(x_j\\) changes, so does everything else). \n\\end{itemize}\n\n\\section{Logistic regression}\n\n\\paragraph{What about classification ?} \nThere are different conceptual issues with linear regression that make it unsuitable for classification. The main one is that we can't model the probability \\(P(y=1|\\xx)\\) as a linear function of $\\xx$ because it must be between 0 and 1. Moreover, this cannot model \"diminishing returns\" where the impact of a change in $\\xx$ is not constant along the probability range. Indeed, if \\(P(y=1|\\xx)\\) is close to 0 or +1, $\\xx$ must change a lot for y to change and this is not the case when \\(P(y=1|\\xx)\\) is close to 0.5. \\\\\nHence we use a \\textbf{logit transformation} through a \\textit{logistic regression}.\\\\\n\n\\begin{figure}[H]\n\\centering\n\\begin{minipage}[b!]{0.4\\textwidth}\n\\includegraphics[width=70mm]{graphe1.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[b!]{0.4\\textwidth}\n\\includegraphics[width=70mm]{graphe2.png}\n\\end{minipage}\n\\end{figure}\n\\begin{center}\n\\(\\log \\dfrac{P(y=1|\\xx)}{1 - P(y=1|\\xx)} = \\beta^T\\xx + \\beta_0\\) with \\(\\beta = (\\beta_0, ..., \\beta_p)\\)\\\\\n\\end{center}\n\n\\paragraph{Maximum likelihood estimation of logistic regression coefficients}\n\nAs usual, let's compute the log likelihood for this logistic regression, knowing our data \\(\\dd = {\\{\\xx^i,\\textit{y}^i\\}}_{\\textit{i}=1,..,\\textit{n}}\\)  :\\\\\n\\\\\n\\[\\mathcal{L}(\\beta|\\dd) = \\displaystyle\\sum_{i=1}^{n} log P(y^i|\\xx^i) + Cte = \\displaystyle\\sum_{i=1}^{n} (y^i \\log g^i + (1-y^i) \\log(1-g^i))\\]\n\\begin{center}\nwith \\(g = P(y=1|\\xx) = \\frac{1}{1+e^{-\\beta^T\\xx}}\\) \n\\end{center}\nWe find the maximum of the log-likelihood by calculating its gradient \\(\\nabla_{\\beta}\\mathcal{L}\\): \n\n\\[\\nabla_{\\beta}g^i = \\xx^i g^i (1-g^i)\\]\n\n\\[\\nabla_{\\beta}\\mathcal{L} = \\displaystyle\\sum_{i=1}^{n} (y^i-g^i)\\xx^i\\]\\\\\n\\\\\nAnd solving for zero in the gradient formula :\n\n\\[\\displaystyle\\sum_{i=1}^{n} \\left( y^i - \\frac{1}{1 + e^{-\\beta^T\\xx^i}} \\right) = 0\\]\\\\\n\\\\\nHowever, this expression cannot be solved analytically. \\\\ Since $\\mathcal{L}$ is concave, hence there is no local minima, we can use the gradient ascent method.\n\\\\\n\\paragraph{Gradient ascent method} For a function J concave in $\\beta$ :\n\n\\begin{itemize}\n\\item Update rule : \\(\\beta^{(t+1)} \\leftarrow \\beta^{(t)} + \\eta \\nabla_\\beta J(\\beta^{(t)})\\)\n\\item Iterate until change is inferior to a chosen margin $\\epsilon$\n\\item $\\eta$ is the learning rate\n\\end{itemize}\n\n\\begin{center}\n\\includegraphics[width=100mm]{gradient.png}\n\\end{center}\nOther methods remain possible such as the Newton method, conjugate gradient ascent or IRLS.\n\n\n\\section{Summary}\n\nThe main points to keep in mind from this lesson are the following : \n\\begin{itemize}\n\\item MAP estimate : \\(\\hat{\\theta}_{\\mbox{MAP}}=\\arg\\underset{\\theta}\\max \\  p(\\theta|\\mathcal{X})\\)\n\\item MLE : \\(\\hat{\\theta}_{\\mbox{MLE}}=\\arg\\underset{\\theta}\\max \\  p(\\mathcal{X}|\\theta)\\)\n\\item Bayes estimate : \\(\\hat{\\theta}_{\\mbox{Bayes}}=\\mathbb{E}[\\theta|\\mathcal{X}]=\\int{\\!\\theta p(\\theta|\\mathcal{X})d\\theta}\\)\n\\item Assuming a Gaussian error, maximizing the likelihood (MLE) is equivalent to minimizing the RSS (residual sum of squares). \n\\item Linear regression MLE : \\(\\hat{\\beta} = (\\textbf{\\textit{X}}^T\\textbf{\\textit{X}})^{-1} \\textbf{\\textit{X}}^T y\\) \n\\item Logistic regression : to solve with gradient ascent. \n \\end{itemize}\n\\end{document}\n", "meta": {"hexsha": "aa6fca5b7507e9701f313bb2ae9a1dd320c226f1", "size": 22340, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "lecture_notes/chap05_linreg.tex", "max_stars_repo_name": "taeraa/ma2823_2016", "max_stars_repo_head_hexsha": "b91642e8b3cac059f91d6785f9da6a436b382db8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2016-09-13T16:35:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T02:16:53.000Z", "max_issues_repo_path": "lecture_notes/chap05_linreg.tex", "max_issues_repo_name": "taeraa/ma2823_2016", "max_issues_repo_head_hexsha": "b91642e8b3cac059f91d6785f9da6a436b382db8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-10-03T10:42:43.000Z", "max_issues_repo_issues_event_max_datetime": "2016-10-03T10:43:16.000Z", "max_forks_repo_path": "lecture_notes/chap05_linreg.tex", "max_forks_repo_name": "taeraa/ma2823_2016", "max_forks_repo_head_hexsha": "b91642e8b3cac059f91d6785f9da6a436b382db8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 62, "max_forks_repo_forks_event_min_datetime": "2016-09-07T06:25:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-30T13:21:05.000Z", "avg_line_length": 55.0246305419, "max_line_length": 527, "alphanum_fraction": 0.6714861235, "num_tokens": 7754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.34548181972574304}}
{"text": "\\documentclass[runningheads]{llncs}\n\\usepackage[hyphens]{url}\n\\usepackage{graphicx}\n\\usepackage{amsmath}\n\n\n\\begin{document}\n\n\\title{Genetic Model Design for 2021 Huawei Delivery Optimization Competition}\n\n\\author{Zhenshuo Chen\\inst{1}\\orcidID{0000-0003-2091-4160} \\and\n    Guowen Liu\\inst{2}\\orcidID{0000-0002-8375-5729}}\n\n\\institute{Dublin City University, Dublin, Ireland \\and\n    Trinity College Dublin, Dublin, Ireland}\n\n\\maketitle\n\n\n\\begin{abstract}\nWe design a genetic model for 2021 Huawei Delivery Optimization Competition,\nwhich aims to minimize multi-vehicle transportation costs within the constraints of vehicle specifications.\nWe use the one-dimensional array as genotype to represent the transportation routes of multiple vehicles.\nThis representation allows us to directly use existing genetic algorithms for multi-vehicle route optimization.\n\n\\keywords{Genetic Algorithm \\and Multi-vehicle Route Optimization.}\n\\end{abstract}\n\n\n\\section{INTRODUCTION}\nThe competition task is to takes care of deliveries of consumables from a depot to customers, as shown in Fig.~\\ref{fig:overview}.\n\n\\begin{figure}[htbp]\n    \\centerline{\\includegraphics[width=0.8\\linewidth]{figures/overview.png}}\n    \\caption{The overview}\n    \\label{fig:overview}\n\\end{figure}\n\n\\begin{itemize}\n    \\item\n    The depot has a given set of home vehicles, each with a certain capacity for carrying consumables.\n\n    \\item\n    Customers are represented as nodes in a graph, in which edges have an associated transportation cost equal to the distance between the nodes.\n\n    \\item\n    Each customer node has an associated demand for a consumable.\n\\end{itemize}\n\nThe target is to minimize the total transportation cost by determining a set of routes that meet the following requirements:\n\n\\begin{itemize}\n    \\item Each vehicle has one route that starts and finishes at the depot.\n\n    \\item Each customer is visited exactly once.\n\n    \\item The total demand along each route is less than the vehicle capacity.\n\\end{itemize}\n\nIn a route, the depot is represented by node $1$ and customer numbers start from node $2$.\nFor example, the route $[1, 2, 3, 4, 1]$ means a vehicle starts from the depot ($1$), visits customer nodes $2$, $3$, $4$ and returns to the depot ($1$).\n\n\n\\section{MODEL DESIGN}\nWe used the genetic algorithm as our main process.\nIt simulates the process of natural selection which means those species who can adapt to changes in their environment are able to survive, reproduce and go to next generation as Fig.~\\ref{fig:genetic}.\n\n\\begin{figure}[htbp]\n    \\centerline{\\includegraphics[width=\\linewidth]{figures/genetic.jpg}}\n    \\caption{A genetic model}\n    \\label{fig:genetic}\n\\end{figure}\n\n\\subsection{Individual}\nFor a task containing $N$ customers and $M$ vehicles, we used a permutation of $N + M - 1$ consecutive numbers (0-based) to represent a transportation plan, consisting of both customers and depots.\n$M - 1$ depots can split the customers into $M$ segments. Each segment represents a route.\nFor instance, if a task contains eight customers and three vehicles, a transportation plan can be generated as Fig.~\\ref{fig:individual}.\nIn the example individual, $0, \\ldots, 7$ are customers and $8, 9$ are the depot.\n\n\\begin{figure}[htbp]\n    \\centerline{\\includegraphics[width=\\linewidth]{figures/individual.png}}\n    \\caption{Using an individual to represent multi-vehicle routes}\n    \\label{fig:individual}\n\\end{figure}\n\nThis representation can produce empty routes such as the individual $[3,0,1,2]$ for a task containing three customers and two vehicles.\nThe depot $3$ is in the first position, so the routes are $[1, 1]$ and $[1, 2, 3, 4, 1]$, transformed from an empty segment and $[0,1,2]$.\n\n\\subsection{Mutation}\nIn a mutation operation, we randomly swapped the order of two nodes as Fig.~\\ref{fig:mutation}.\n\n\\begin{figure}[htbp]\n    \\centerline{\\includegraphics[width=0.8\\linewidth]{figures/mutation.png}}\n    \\caption{Mutation}\n    \\label{fig:mutation}\n\\end{figure}\n\n\\subsection{Crossover}\nIn a crossover operation, we executed ordered crossover on two parents to produce children, as shown in Fig.~\\ref{fig:crossover}.\n\n\\begin{figure}[htbp]\n    \\centerline{\\includegraphics[width=0.8\\linewidth]{figures/crossover.png}}\n    \\caption{Ordered crossover}\n    \\label{fig:crossover}\n\\end{figure}\n\n\\subsection{Selection}\nWe use tournament selection, keeping transportation plans with the highest fitness from randomly chosen candidates.\n\nThe fitness is the cost of a transportation plan.\nFor overloaded plans, a large value is added to fitness as a penalty. This value increases as overload weight increases, see Equation.~\\ref{eq:penalty}.\n\n\\begin{equation}\n    Penalty = \\sum_{i}\\sum_{j}c_{i, j} + 2 \\cdot W\n    \\label{eq:penalty}\n\\end{equation}\n\n$c_{i, j}$ is the cost between the node $i$ and $j$, and $W$ is overloaded weight of the transportation plan.\n\n\n\\section{IMPLEMENTATION}\nOur implementation is based on \\verb|DEAP| framework \\cite{deap}.\nThe source code is available on the GitHub \\footnote{\\url{https://github.com/Zhuagenborn/Huawei-Delivery-Optimization}}.\n\n\n\\bibliographystyle{splncs04}\n\\bibliography{huawei-delivery-optimization}\n\n\\end{document}", "meta": {"hexsha": "68ff354d26ddb7a67cb2011abc6d004099f2f909", "size": 5175, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper-tex/huawei-delivery-optimization.tex", "max_stars_repo_name": "Zhuagenborn/Huawei-Delivery-Optimization", "max_stars_repo_head_hexsha": "af7ccf077eadda1e40af88a555598e844d16f5db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-20T15:44:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T15:44:36.000Z", "max_issues_repo_path": "paper-tex/huawei-delivery-optimization.tex", "max_issues_repo_name": "Zhuagenborn/Huawei-Delivery-Optimization", "max_issues_repo_head_hexsha": "af7ccf077eadda1e40af88a555598e844d16f5db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper-tex/huawei-delivery-optimization.tex", "max_forks_repo_name": "Zhuagenborn/Huawei-Delivery-Optimization", "max_forks_repo_head_hexsha": "af7ccf077eadda1e40af88a555598e844d16f5db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1162790698, "max_line_length": 201, "alphanum_fraction": 0.7605797101, "num_tokens": 1325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.3454818118755473}}
{"text": "\\subsection{Multi-Agent Proximal Policy Optimization}\n\\label{subsec:41}\n\nSince the naive application of standard reinforcement learning algorithms performs poorly in multi-agent settings, our goal is to derive an algorithm that can operate under the following constraints:\n\\begin{itemize}\n\\item{The learned policies can only use local information (i.e. own observations) at execution time.}\n\\item{There is no particular communication method between the agents, since it can restrict the scalability of the solution.}\n\\item{We do not assume a differential model of the environment dynamics.}\n\\end{itemize}\nFulfilling the above desiderata would provide a general-purpose multi-agent learning algorithm that could be applied not just to cooperative games with explicit communication channels, but also to competitive games and games involving only physical interactions between agents.\n\nWe accomplish our goal by adopting the framework of centralized training with decentralized execution in which agent policies are composed of two separate networks with different parameters: a policy network (actor) that generates an action distribution and a critic network (critic) that predicts discounted future returns. The critic uses extra information to ease training process whilst actors take actions based solely on their own local observations. This is still a valid approach as long as the information used during the training of the agents are not used at test/execution time.\n\n% For figures use\n%\n\\begin{figure}[h!]\n%\\sidecaption\n% Use the relevant command for your figure-insertion program\n% to insert the figure file.\n% For example, with the graphicx style use\n\\includegraphics[scale=.65]{images/MAPPO}\n%\n% If no graphics program available, insert a blank space i.e. use\n%\\picplace{5cm}{2cm} % Give the correct figure height and width in cm\n%\n\\caption{Overview of our multi-agent decentralized actor, centralized critic approach. The centralized action-value function (critic) for each agent takes as input the actions and observations of all agents and predicts the discounted future returns (Q-values) for the agent while the actor produces an action distribution based solely on the agent's observations and actions.}\n\\label{fig:MAPPO}       % Give a unique label\n\\end{figure}\n\nAs illustrated in Fig. \\ref{fig:MAPPO}, our centralized action-value function (critic) for each agent takes as input the actions and observations of all agents and predicts the discounted future returns for the agent. Additional information can also be included in the inputs. Since each action-value function is learned separately, each agent can have arbitrary rewards including conflicting rewards in competitive scenarios.\n\nFurthermore, we extend the idea of \\cite{schulman2017proximal} by adopting the proximal policy optimization algorithm (PPO) as the main policy optimization algorithm instead of deep deterministic policy gradient (DDPG) as presented in the paper. PPO is a family of policy optimization methods that use multiple epochs of stochastic gradient ascent to perform each policy update. It performs comparably to or better than DDPG while being much simpler to implement and tune.\n\n\\subsection{Cooperation and Competition}\n\\label{subsec:42}\nAs we seek the emergence of coordination strategies between the components of the micro-grid, the agents controlling the micro-grid components are trained using \\textit{self-play} in an \\textit{autocurricula} configuration. This acts as a natural curriculum as these agents are always in a mixed cooperative and competitive setting. For example, the energy loads (i.e. production machines) of the micro-grid are always in competitive settings. If there is not enough electrical energy available in the grids, then some production machines have to turn themselves off so that the production can be carried on by the other machines. In the same direction, cooperation can take place if, for example, the energy storage components need to be switched to the discharging state in order to increase the electrical energy available on the energy bus and thus enable the production machines to perform additional production tasks.\n\nAdopting such a configuration also offers many advantages. If a new successful strategy is adopted by an agent, it implicitly changes the task distribution for the competing agents which are then forced to develop a better strategy. These evolutionary arms races create an implicit autocurriculum in which competing agents constantly create new tasks for each other and thus discover new powerful and robust strategies and counter-strategies. In addition, the multi-agent autocurriculum is open-ended. That means that the training will only stabilizes once equilibrium between the different agents is founded which can only be reached if a suitable coordination strategy between the agents has emerged. Due to the exploration factors, many coordination strategies can also emerge at different stages of the training.\n\nIn order to create a competitive setting, competing agents are rewarded with competitive rewards. If an agent wins the game, it receives a positive reward and all other competing agents are penalized by an opposite negative reward. If nobody wins the game, then all competing agent are penalized. In a cooperative setting, agents are given a team based reward; meaning that all members of the team receive a positive reward, if a team member wins the game. To confine agent behavior to a reasonable space, we also introduced an environmental-based penalization.\n\nThe success of agents in the autocurricula setting requires the agents to occasionally solve the task (win the game) by random actions. The probability of this happening in most games is minuscule as they require as a prerequisite some fundamental skills like the ability to properly control the operational state machine of the grid component. For example the agent must first quickly learn how to bring a production machine in the $execute$-state in order to start a production task or how to turn on/off the storage component without suspending/halting the production. To overcome this problem, we use simple dense rewards at each step so that the agents can first learn basic motor skills that increase the likelihood that random actions of the agent will result in a relatively small positive reward. We refer to this reward as the \\textit{exploration reward}. The exploration reward is then gradually annealed to zero, in favor of the \\textit{competition/cooperation reward}, to allow the agents to learn coordination strategies for the remaining training time. This is achieved using a linear annealing factor $\\alpha$. We also introduce an \\textit{environmental reward} which aims to penalize action sequences leading to dangerous outcomes (for example system configurations violating the constraints formulated in Eq. \\ref{eq:constraint_energy_balance} and Eq. \\ref{eq:constraint_load_profile}) and a \\textit{productivity reward} which encourage production machines to execute production tasks more frequently. \n\nSo, at time-step $t$, if the exploration reward is $r_{explo}$, the competition reward is $r_{comp}$, the environmental reward $r_{env}$, the the productivity reward $r_{prod}$ and T is the termination time-step, then the total agent reward is:\n\\begin{equation}\n\\label{eq:total_reward}\t\n\tr_t = \\alpha \\cdot r_{explo} + (1 - \\alpha) \\cdot (r_{comp} + r_{env} + r_{prod})\n\\end{equation} \n\nWith this formulation, the agents are trained initially on the dense reward for only about 10-20\\% of the training epochs in order to gain some basic skills first. \n", "meta": {"hexsha": "f50fbfe84855314c6ac6a69011bb657ced44a7db", "size": 7623, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "author/approach.tex", "max_stars_repo_name": "jupiterbak/Artificial-Intelligence-in-Industry-4.0", "max_stars_repo_head_hexsha": "7ddeb55de44c4e50b195edf7a75aa4afb99fcd9e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-09T11:05:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-09T11:05:49.000Z", "max_issues_repo_path": "author/approach.tex", "max_issues_repo_name": "jupiterbak/Artificial-Intelligence-in-Industry-4.0", "max_issues_repo_head_hexsha": "7ddeb55de44c4e50b195edf7a75aa4afb99fcd9e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "author/approach.tex", "max_forks_repo_name": "jupiterbak/Artificial-Intelligence-in-Industry-4.0", "max_forks_repo_head_hexsha": "7ddeb55de44c4e50b195edf7a75aa4afb99fcd9e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 149.4705882353, "max_line_length": 1520, "alphanum_fraction": 0.8126721763, "num_tokens": 1518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.34545842328678156}}
{"text": "\\section{Results}\n\\label{results}\n\nOur Spark program is written in Scala using Hadoop distribution $2.7.2$, and run on a Intel (R) Xeon machine with two physical CPUs. Each CPU has $16$ E$5-2650$ @ $2.00$GHz cores, giving us a total $32$ cores. The machine also has $32$GB of RAM, and runs Ubuntu $16.04$.  \n\n\\subsection{Input description}\n\nAs discussed earlier, our input graph $G$ is an undirected, unweighted graph with $679965$ edges and $899162$ vertices. Each vertex and edge is represented using 8 bytes and so the total amount of memory required by our graph is about $20$MB. \n\nOur input graph also consists of $199004$ connected components, with the maximum component size at $145$ and the minimum at $2$. The distribution of component sizes is shown in Fig. \\ref{fig:vertices-components-all}, where the numbers of components with sizes above, say $40$, were dwarfed by the components with smaller sizes. Fig. \\ref{fig:vertices-components-40} (resp. Fig. \\ref{fig:vertices-components-20}) is an alternative figure that reveals the distribution of larger (resp. smaller) components. \n\nTo investigate the scalability of our code for increasing input, we replicate the graph by doubling it (labeled graph $G_2$) then quadrupling it (labeled graph $G_4$), whilst preserving the same structure as far as connected components are concerned.\n\n\\subsection{Failures and connectivity loss analysis}\n\nFor each of the four scenarios described in Sec. \\ref{methods}, we vary the number of threads and partitions, compute the percentage of loss, and plot this value against the number of nodes removed from the graph. In all the tables and figures below, $R$ corresponds to random failures, $D$ to degree based failures, $BC$ to betweenness centrality (load) failures, and $C$ to cascading failures. Fig. \\ref{fig:loss-100} and \\ref{fig:loss-1000} present a refined view demonstrating the progression of loss for the first 100 and 1000 failures on transmission and distribution nodes. Fig. \\ref{fig:loss-all} shows the loss for the entire failures. The connectivity loss is faint and proportional to the number of failures in the random case. It is worse for the cascading scenario, whereas the connectivity losses associated with the load-based versus degree based scenarios are more or less comparable. These findings are confirmed in Table~\\ref{resilience}, which presents, for each scenario, the percentage of failed nodes effecting in $60\\%$ and $80\\%$ (nearly total) connectivity loss. Some of these figures, particularly, the relatively high percentages required in each of the $BC$, $D$, and $R$ scenarios that precede total failure, can be interpreted to say that the Lebanese grid is highly redundant, and thus somehow resilient, thanks to its decomposition into numerous components and its reliance on local diesel generators that alleviate the effects of blackouts and failures. \n\n\n\\begin{table}[t]\n\\centering\n\\caption{Percentage of vertices to be removed to reach $60\\%$ and $80\\%$ losses}\n\\label{tab:threshold-percentage}\n{\\small\n\\begin{tabular}{||c||c|c|c|c||}\n\\hline\n\\textbf{Loss}\t&\\cellcolor{black!10}BC&\t\\cellcolor{black!10}C & \\cellcolor{black!10} R & \\cellcolor{black!10} D \\\\ \\hline \\hline\n60\\% &\t\t11.6\\%&\t4.3\\%\t&59.8\\%&\t7.7\\%\t \\\\ \\hline\t\t\n80\\%\t&\t\t27.8\\%&\t14.6\\%\t&79.7\\%&\t29.5\\%\t \\\\ \\hline\t\t\n\\end{tabular}\n}\n\\label{resilience}\n\\end{table}\n\n\n\n\n\\begin{figure}\n\\centering\n\\includegraphics[scale=0.35]{bench/generated/loss-100-crop.pdf}\n\\caption{Loss percentage: first 100 attacks}\n\\label{fig:loss-100}\n\\end{figure}\n\n\\begin{figure}\n\\centering\n\\includegraphics[scale=0.35]{bench/generated/loss-1000-crop.pdf}\n\\caption{Loss percentage: first 1000 attacks}\n\\label{fig:loss-1000}\n\\end{figure}\n\n\\begin{figure}\n\\centering\n\\includegraphics[scale=0.35]{bench/generated/loss-all-crop.pdf}\n\\caption{Loss percentage: overall attacks}\n\\label{fig:loss-all}\n\\end{figure}\n\n\\subsection{Run-time and parallel efficiency analysis}\n\\secondedited{\nThe run-time for each pair of ({\\it thread},{\\it partition}) values using our input graphs are shown in the tables~\\ref{tab:graph1}, \\ref{tab:graph2}, and \\ref{tab:graph4}, for $G$, $G_2$, and $G_4$ respectively. Moreover, the corresponding performance efficiency plots are shown in Fig. \\ref{fig:effbc1}, \\ref{fig:effbc2}, \\ref{fig:effbc4}, \\ref{fig:effc1}, \\ref{fig:effc2}, \\ref{fig:effc4}, \\ref{fig:effd1}, \\ref{fig:effd2}, \\ref{fig:effd4}, \\ref{fig:effr1}, \\ref{fig:effr2}, and \\ref{fig:effr4}.  \n}\n%\n\\edited{\nHere, parallel efficiency is defined as $\\frac{T_s}{p\\cdot T_p}$, where $T_s$ denotes the serial run-time and $T_p$ denotes the parallel run-time given $p$ parallel processes.}\n%\n\\secondedited{\nThe timings shown in the tables correspond to the parallel phase of the algorithm. The sequential run-time was omitted because it was extremely negligible compared to the parallel part that is of higher order (in contrast to linear running time in steps 7 and 8).\n%\nBy default, Spark sets the partition size at 64 MB. This is too large for our given graph. As a result, we choose to override the default value by specifying the number of partitions at compile time. When this is done, Spark re-adjusts the size of each partition based on their total number as well as on the size of the input graph. The several connected components in each graph get mapped onto all partitions such that the number of vertices in each partition is balanced across all partitions. We experiment with a number of partitions ranging from $4$, $8$, $16$, and $32$ in order to explore the effect that the number of partitions have on run-time and parallel efficiency. From Fig. \\ref{fig:vertices-components-all} and \\ref{fig:vertices-components-40}, we gather that there would be enough connected components in each partition to engage all threads assigned to the partition. Also, the fact that many connected components have sizes greater than, say, 40, ensures that the distributed work is more or less balanced.}\n\nAs expected, for all three graphs, the fastest and yet the worst parallel efficiency correspond to the R (random failures) scenario that does not rely on any centrality measure computation. In contrast, the highest run-times and hence best efficiency are for the C (cascading scenario) that updates the betweenness centrality of all the nodes following each node removal. It is clear that the more work entailed by a certain scenario, the better it will be for the parallel program to compensate for the overheads associated with the partitioning and scheduling operations. Reading across the three tables for the same partition size and same scenario, our tool shows improved scalability as the input size grows. \n\nFor each given graph and for each scenario employed, we notice that the actual run-time has opposing trends that depend on the number of partitions. For all three tables, there is a cut-off value for the number of partitions, before which run-time continues to improve, and after which it starts to deteriorate. For graph $G$, the cut-off number is at $8$, for graph $G_2$ it is somewhere between $8$ and $16$, and for $G_4$, it is at $16$. We justify the improvement in run-time as we move closer to the cut-off threshold as follows. With a higher number of partitions, one would expect that the multiple threads will be spread about, sharing the work but on data that is more split into distinct regions of main memory. As such, we have reduced contention over the shared address space, as well as scheduling costs associated with managing threads on one single partition. We now argue that creating more partitions beyond the cut-off number drastically affects the performance and introduces a huge overhead -- particularly when the number of threads is low. For instance, in Table II, if we consider only one thread of the BC scenario, it takes 161 (resp. 423) seconds in case of 4 (resp. 32) partitions. We attribute this overhead to the shuffling and repartition operations taking place at the end of each stage that assigns one or more threads from one partition to another. In that phase, some transformations (e.g., \\texttt{groupByKey}, \\texttt{reduceByKey}, \\texttt{join} operations) require shuffling and repartitioning of data, for instance, to group all the items with the same keys in the same partition. \n\nWith that said, we observe that efficiency actually improves for larger partitions. This isn't to be construed, however, to mean that the parallelisation has improved in any way, but rather that the rate of deterioration in the performance for a smaller number of threads (particularly, the case of one thread) is higher when the number of partitions exceeds the cut-off number, resulting in a higher-speedup as the number of threads grows larger. \n\n%Our own Spark implementation of contingency analysis executes in real-time for the entire power grid, achieving a speed-up of ? on ? processors. We conclude with a spatial understanding of the hotspots on Lebanese soil where energy centers can be exposed and are at risk, using a spatial correlation supported by a binary search tree. The amenability of our work to big data processing makes it extendable to larger networks of networks, towards a fuller understanding of resilence at many vital levels beyond the power grid. Examples are as communications network, Internet networks, transportation networks, hospitals and medical centers networks, to name a few.\n\n\\secondedited{\nMoreover, we notice that the parallel efficiency in some cases is above one (e.g., in case of betweenness centrality 32 partitions and 2 threads). This may due to the effect of the garbage collectors. In case of one thread and several partitions, the threshold of the garbage collector would be reached ahead of time. Whereas in case of more threads/processes, less data needs to be freed.\n%\nAdditionally, another cause behind super-linear speedup can be attributed to the ``caching effect'', which results from the varying speeds in accessing different levels of the memory hierarchy on which the input graph and intermediate data are stored. As the number of threads increases, the data assigned to each thread decreases, rendering it into the smaller cache levels which are faster to access. As a result, the reduction in run-time is not solely explained by the increase in the number of working threads but also in the reduction of the time spent on I/O, which causes the theoretical estimate for parallel speedup to go beyond $p$ (given $p$ threads), or equivalently, for parallel efficiency to go beyond 1.}\n\n%\\begin{figure}\n%\\centering\n%\\includegraphics[scale=0.35]{bench/generated/frequencyall-crop.pdf}\n%\\caption{Components size -- overall distribution}\n%\\label{fig:cs-overall}\n%\\end{figure}\n\n%\\begin{figure}\n%\\centering\n%\\includegraphics[scale=0.35]{bench/generated/frequency-selected-crop.pdf}\n%\\caption{Components size -- cropped distribution}\n%\\label{fig:cs-selected}\n%\\end{figure}\n\n\\begin{table*}[t]\n\\begin{minipage}[b]{\\textwidth}\n\\caption{Run-time \\edited{(in seconds)} for graph $G$}\n\\label{tab:graph1}\n{\\small\n\\centering\n\\begin{tabular}{||c||c|c|c|c||c|c|c|c||c|c|c|c||c|c|c|c|}\n\\hline\n\\textbf{Threads}\t&\\cellcolor{black!10}BC-4&\t\\cellcolor{black!10}BC-8\t&\\cellcolor{black!10}BC-16\t&\\cellcolor{black!10}BC-32&\t\\cellcolor{black!10}C-4\t&\\cellcolor{black!10}C-8&\t\\cellcolor{black!10}C-16&\t\\cellcolor{black!10}C-32&\t\\cellcolor{black!10}D-4&\t\\cellcolor{black!10}D-8\t&\\cellcolor{black!10}D-16&\\cellcolor{black!10}\tD-32&\t\\cellcolor{black!10}R-4\t&\\cellcolor{black!10}R-8&\t\\cellcolor{black!10}R-16&\t\\cellcolor{black!10}R-32 \\\\ \\hline \\hline\n64&\t\t27\t&17\t&22\t&41\t&53\t&34\t&32\t&52\t&26\t&15\t&20\t&41\t&23\t&17\t&20\t&39\t\t\t\\\\ \\hline\t\t\t\t\t\n32&\t\t24\t&17\t&19\t&37\t&52\t&33\t&31\t&49\t&20\t&16\t&18\t&36\t&20\t&19\t&19\t&36\t\\\\ \\hline\n16&\t\t24\t&18\t&22\t&39\t&53\t&35\t&37\t&54\t&21\t&16\t&19\t&37\t&19\t&16\t&20&37\t\\\\ \\hline\n8\t&\t25\t&25\t&30\t&54\t&55\t&50\t&56\t&80\t&21\t&21\t&26\t&51\t&20\t&20\t&26\t&50\t\\\\ \\hline\n4\t&\t41\t&41\t&53\t&97\t&87\t&86\t&98\t&138\t&33\t&33\t&45\t&89\t&30\t&31\t&44\t&90\t\\\\ \\hline\n2&\t\t82\t&84\t&108\t&206\t&165\t&165\t&189\t&287\t&65\t&66\t&92\t&188\t&55\t&62\t&87\t&186\t\\\\ \\hline\n1&\t\t161\t&167\t&219\t&423\t&312\t&320\t&369\t&543\t&124\t&127\t&187\t&384\t&104\t&114\t&174\t&344\t\\\\ \\hline\n\\end{tabular}\n}\n\\end{minipage}\n\\end{table*}\n\n\n\\begin{table*}[t]\n\\begin{minipage}[b]{\\textwidth}\n\\caption{Run-time \\edited{(in seconds)} for graph $G_2$}\n\\label{tab:graph2}\n{\\small\n\\begin{tabular}{||c||c|c|c|c||c|c|c|c||c|c|c|c||c|c|c|c|}\n\\hline\n\\textbf{Threads}\t&\\cellcolor{black!10}BC-4&\t\\cellcolor{black!10}BC-8\t&\\cellcolor{black!10}BC-16\t&\\cellcolor{black!10}BC-32&\t\\cellcolor{black!10}C-4\t&\\cellcolor{black!10}C-8&\t\\cellcolor{black!10}C-16&\t\\cellcolor{black!10}C-32&\t\\cellcolor{black!10}D-4&\t\\cellcolor{black!10}D-8\t&\\cellcolor{black!10}D-16&\\cellcolor{black!10}\tD-32&\t\\cellcolor{black!10}R-4\t&\\cellcolor{black!10}R-8&\t\\cellcolor{black!10}R-16&\t\\cellcolor{black!10}R-32 \\\\ \\hline \\hline\n64\t\t&127\t&71\t&48\t&55\t&119\t&64\t&60\t&76\t&108\t&58\t&45\t&53\t&45\t&32\t&31\t&50\t\t \\\\ \\hline\t\t\n32\t\t&120\t&59\t&45\t&49\t&116\t&68\t&56\t&71\t&108\t&57\t&42\t&47\t&40\t&29\t&29\t&45\t\t \\\\ \\hline\t\t\t\n16\t\t&128\t&66\t&39\t&52\t&115\t&66\t&65\t&79\t&112\t&57\t&36\t&50\t&41\t&33\t&30\t&46 \\\\ \\hline\t\t\t\t\n8\t\t&123\t&66\t&56\t&77\t&120\t&97\t&98\t&121\t&106\t&54\t&46\t&68\t&40\t&34\t&39\t&63\t \\\\ \\hline\t\t\t\n4\t\t&164\t&104\t&101\t&142\t&210\t&191\t&185\t&223\t&134\t&83\t&80\t&119\t&60\t&57\t&69\t&113\t \\\\ \\hline\t\t\t\n2\t\t&263\t&203\t&207\t&292\t&416\t&353\t&366\t&462\t&209\t&159\t&153\t&239\t&111\t&110\t&131\t&224\t \\\\ \\hline\t\t\n1\t\t&452&357\t&371\t&525\t&761\t&804\t&793\t&969\t&355\t&281\t&286\t&434\t&196\t&201\t&230\t&402 \\\\ \\hline\t\t\n\\end{tabular}\n}\n\\end{minipage}\n\\end{table*}\n\n\\begin{table*}[t]\n\\begin{minipage}[b]{\\textwidth}\n\\caption{Run-time \\edited{(in seconds)} for graph $G_4$}\n\\label{tab:graph4}\n{\\small\n\\begin{tabular}{||c||c|c|c|c||c|c|c|c||c|c|c|c||c|c|c|c|}\n\\hline\n\\textbf{Threads}\t&\\cellcolor{black!10}BC-4&\t\\cellcolor{black!10}BC-8\t&\\cellcolor{black!10}BC-16\t&\\cellcolor{black!10}BC-32&\t\\cellcolor{black!10}C-4\t&\\cellcolor{black!10}C-8&\t\\cellcolor{black!10}C-16&\t\\cellcolor{black!10}C-32&\t\\cellcolor{black!10}D-4&\t\\cellcolor{black!10}D-8\t&\\cellcolor{black!10}D-16&\\cellcolor{black!10}\tD-32&\t\\cellcolor{black!10}R-4\t&\\cellcolor{black!10}R-8&\t\\cellcolor{black!10}R-16&\t\\cellcolor{black!10}R-32 \\\\ \\hline \\hline\n64 &\t\t525&\t317\t&171&\t117\t&411\t&179&\t127\t&123\t&430\t&220\t&134\t&104&\t133&\t79&\t70\t&87\t \\\\ \\hline\t\t\n32\t&\t491&\t274\t&153\t&99\t&387\t&202\t&123\t&121 &449\t&243&\t149&\t100\t&122\t&101&\t64&\t75\\\\ \\hline\n16\t&\t473\t&311\t&133\t&96\t&401\t&184\t&127\t&137 &457\t&236\t&113\t&77\t&130\t&86\t&62\t&78 \\\\ \\hline\n8\t&\t557&\t250\t&132\t&126\t&387\t&234\t&204\t&212 &452\t&222\t&113\t&105\t&119&\t93\t&75\t&93 \\\\ \\hline\n4\t\t&750&\t333\t&221\t&234\t&612\t&431\t&374\t&398 &601\t&274 &168\t&190\t&151\t&126&\t120\t&163 \\\\ \\hline\n2\t\t&1041 &526 &430 &467\t&1042\t&791\t&736\t&793 &888\t&436\t&344\t&395\t&273\t&235\t&237\t&337 \\\\ \\hline\n1\t\t&1626&902&879 &1021 &2156 &1784 &1577 &1754 &1584 &905 &730 &783& 533 &458 &456 &647 \\\\ \\hline\n\\end{tabular}\n}\n\\end{minipage}\n\\end{table*}\n\n\\begin{figure}\n\\centering\n\\includegraphics[scale=0.35]{bench/generated/efficiency-bc-1-crop.pdf}\n\\caption{Efficiency for the load based (BC) scenario and graph $G$}\n\\label{fig:effbc1}\n\\end{figure}\n\n\\begin{figure}\n\\centering\n\\includegraphics[scale=0.35]{bench/generated/efficiency-c-1-crop.pdf}\n\\caption{Efficiency for the cascading (C) scenario and graph $G$}\n\\label{fig:effc1}\n\\end{figure}\n\n\\begin{figure}\n\\centering\n\\includegraphics[scale=0.35]{bench/generated/efficiency-d-1-crop.pdf}\n\\caption{Efficiency for the degree-based (D) scenario and graph $G$}\n\\label{fig:effd1}\n\\end{figure}\n\n\n\\begin{figure}\n\\centering\n\\includegraphics[scale=0.35]{bench/generated/efficiency-r-1-crop.pdf}\n\\caption{Efficiency for the random (R) scenario and graph $G$}\n\\label{fig:effr1}\n\\end{figure}\n\n\\begin{figure}\n\\centering\n\\includegraphics[scale=0.35]{bench/generated/efficiency-bc-2-crop.pdf}\n\\caption{Efficiency for the load based (BC) scenario and graph $G_2$}\n\\label{fig:effbc2}\n\\end{figure}\n\n\\begin{figure}\n\\centering\n\\includegraphics[scale=0.35]{bench/generated/efficiency-c-2-crop.pdf}\n\\caption{Efficiency for the cascading (C) scenario and graph $G_2$}\n\\label{fig:effc2}\n\\end{figure}\n\n\\begin{figure}\n\\centering\n\\includegraphics[scale=0.35]{bench/generated/efficiency-d-2-crop.pdf}\n\\caption{Efficiency for the degree-based (D) scenario and graph $G_2$}\n\\label{fig:effd2}\n\\end{figure}\n\n\n\\begin{figure}\n\\centering\n\\includegraphics[scale=0.35]{bench/generated/efficiency-r-2-crop.pdf}\n\\caption{Efficiency for the random (R) scenario and graph $G_2$}\n\\label{fig:effr2}\n\\end{figure}\n\n\\begin{figure}\n\\centering\n\\includegraphics[scale=0.35]{bench/generated/efficiency-bc-4-crop.pdf}\n\\caption{Efficiency for the load based (BC) scenario and graph $G_4$}\n\\label{fig:effbc4}\n\\end{figure}\n\n\\begin{figure}\n\\centering\n\\includegraphics[scale=0.35]{bench/generated/efficiency-c-4-crop.pdf}\n\\caption{Efficiency for the cascading (C) scenario and graph $G_4$}\n\\label{fig:effc4}\n\\end{figure}\n\n\\begin{figure}\n\\centering\n\\includegraphics[scale=0.35]{bench/generated/efficiency-d-4-crop.pdf}\n\\caption{Efficiency for the degree-based (D) scenario and graph $G_4$}\n\\label{fig:effd4}\n\\end{figure}\n\n\n\\begin{figure}\n\\centering\n\\includegraphics[scale=0.35]{bench/generated/efficiency-r-4-crop.pdf}\n\\caption{Efficiency for the random (R) scenario and graph $G_4$}\n\\label{fig:effr4}\n\\end{figure}\n\n\n\n\\subsection{Spatial analysis}\nThe spatial correlation analysis shown in Fig. \\ref{fig:correlation} reveals a long range correlated case with correlation decaying slowly with distance, particularly, in the linear regime where $C(r) \\propto r^{-\\gamma} $, $\\gamma = 1.13$, which is in agreement with the literature results in \\cite{DaqingAl14}.  Overload failures usually propagate through collective interactions among system components. Our results reveal that high failures in critical nodes has impact that propagates across long path lengths on Lebanese soil.\n\n\\begin{figure}\n\\centering\n\\includegraphics[scale=0.65]{bench/fixed/correlation-eps-converted-to.pdf}\n\\caption{Spatial correlation between nodes in the cascading scenario on a logarithmic scale.}\n\\label{fig:correlation}\n\\end{figure}\n\n\n\n\n", "meta": {"hexsha": "85671cf2949510f61c397e701567ea5dcf6bf8c7", "size": 17996, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/journal-tcss/results.tex", "max_stars_repo_name": "okm02/Power-grid-analysis", "max_stars_repo_head_hexsha": "1c24a2c8bcdedd04d3e63f2db7abfa6ab135a107", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tex/journal-tcss/results.tex", "max_issues_repo_name": "okm02/Power-grid-analysis", "max_issues_repo_head_hexsha": "1c24a2c8bcdedd04d3e63f2db7abfa6ab135a107", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/journal-tcss/results.tex", "max_forks_repo_name": "okm02/Power-grid-analysis", "max_forks_repo_head_hexsha": "1c24a2c8bcdedd04d3e63f2db7abfa6ab135a107", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 68.6870229008, "max_line_length": 1619, "alphanum_fraction": 0.7438319627, "num_tokens": 5743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.34533680814633055}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% # TO DO LIST\n% \n% * read again and put all the citations needed when something is stated \n%   without demonstration (a lot of times...)\n% * find a reference for the duality theory (other that Bourbaki ?)\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\documentclass[a4paper,11pt]{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage[T1]{fontenc}\n\\usepackage[english]{babel}\n\\usepackage{amsmath,amssymb,amsthm,amsopn}\n\\usepackage{mathrsfs}\n%\\usepackage{stmaryrd} % to get <--| \\mapsfrom\n\\usepackage{graphicx}\n\\usepackage{hyperref}\n\\usepackage{tikz}\n\\usepackage{array}\n%\\usepackage[top=1cm,bottom=1cm]{geometry}\n%\\usepackage{listings}\n%\\usepackage{xcolor}\n\\usepackage{bm}\n\\usepackage{bbm}\n\n% Création des labels Théorème, Lemme, etc...\n\n\\newtheoremstyle{break}%\n{}{}%\n{\\itshape}{}%\n{\\bfseries}{}%  % Note that final punctuation is omitted.\n{\\newline}{}\n\n\\theoremstyle{break}\n\\newtheorem{thm}{Theorem}[section]\n\\newtheorem{lm}[thm]{Lemma}\n\\newtheorem{prop}[thm]{Proposition}\n\\newtheorem{cor}[thm]{Corollary}\n\n\\theoremstyle{definition}\n\\newtheorem{defi}[thm]{Definition}\n\\newtheorem{ex}[thm]{Example}\n\n\\theoremstyle{remark}\n%\\newtheorem{rem}[thm]{Remarque}\n\n% Raccourcis pour les opérateurs mathématiques (les espaces avant-après sont\n% modifiés pour mieux rentrer dans les codes mathématiques usuels)\n% \\deg already exists !!\n\\DeclareMathOperator{\\Ker}{Ker}\n\\DeclareMathOperator{\\Id}{Id}\n\\DeclareMathOperator{\\Img}{Im}\n\\DeclareMathOperator{\\Card}{Card}\n\\DeclareMathOperator{\\Vect}{Vect}\n\\DeclareMathOperator{\\rev}{rev}\n\\DeclareMathOperator{\\rem}{rem}\n\n\\DeclareBoldMathCommand{\\bxi}{\\xi}\n\\DeclareBoldMathCommand{\\bupsilon}{\\upsilon}\n\\DeclareBoldMathCommand{\\bzeta}{\\zeta}\n\n% Nouvelles commandes\n\\newcommand{\\ps}[2]{\\langle#1,#2\\rangle}\n\\newcommand{\\ent}[2]{[\\![#1,#2]\\!]}\n\\newcommand{\\psdot}{\\ps{\\cdot}{\\cdot}}\n\\newcommand{\\remt}{\\rem^t}\n\n% opening\n\\title{Internship report}\n\\author{Édouard \\textsc{Rousseau}\\\\edouard.rousseau@u-psud.fr\\\\ \\\\Internship \nsupervised by Luca \\textsc{De \nFeo}}\n\n\\usepackage{tikz-cd}\n\\usetikzlibrary{matrix, calc, arrows}\n\n\n\n\\begin{document}\n\n\\maketitle\n\n\\begin{abstract}\n\n  This internship took place during July and August 2016, the aim was to study\n  the algorithms presented in~\\cite{DeDoSc14}, and to implement them in\n  Nemo~\\cite{Nemo}, a computer algebra package for the Julia~\\cite{Julia} programming\n  language. These algorithms were designed to deal with the algebraic closure \n  of finite fields, and often have a quasi-linear cost, whereas traditional \n  algorithms have quadratic cost. This paper intends to compare the Julia \n  and the C implementations of the code, in terms of speed, but also genericity \n  and ease of writing and reading such code. As we will see, writing code in \n  Julia is really easy, and the tools available to develop the code are \n  sharp, but the speed of the implementation in Julia does not match the speed \n  of the C implementation.\n\n\\end{abstract}\n\n\\tableofcontents\n\n\\clearpage\n\n\\section{Julia}\n\\subsection{Overview of Julia's caracteristics}\nJulia is a free and open-source, high-level programming language developed since \n2012, with dynamic\ntype system and high-performance. It is a compiled language, with a\n\\emph{just-in-time} (jit) compilation. This means that when one writes a\nfunction, e.g. \n\\begin{verbatim}\njulia> function myFunction(n)\n       return n^3+n+2\n       end\n\\end{verbatim}\nthe function will be compiled during the very first call. After this first\ncall, it will be much faster to run the compiled function\n\\begin{verbatim}\njulia> myFunction(BigInt(2)^300)\n\\end{verbatim}\nthan the expression below.\n\\begin{verbatim}\njulia> (BigInt(2)^300)^3 + BigInt(2)^300 + 2\n\\end{verbatim}\nIn order to optimize the code, the compiler creates a new function for each\ntype of input that one can think of when calling myFunction. For example, in the\ncode \nbelow, Julia will compile myFunction three times, which will result in\nthree functions, each one of them optimized for \\texttt{Int64} (the default type\nof $17$), \\texttt{Float64}, or \\texttt{BigInt}.\n\\begin{verbatim}\njulia> myFunction(17)\n4932\njulia> myFunction(17.)\n4932.0\njulia> myFunction(BigInt(17))\n4932\n\\end{verbatim}\nJulia is a very easy-to-learn language, the syntax is intuitive for someone who\nalready worked with high-level langages, like Python.\nThe code written in \\href{https://github.com/edouardRousseau/FastArithmetic.jl}{FastArithmetic.jl} is\nvery generic, thanks to the type system of Julia, and works for fields\n$\\mathbb{F}_{p^n}$ with a small $p$ as well as large $p$. More importantly, the\n\\emph{jit} compiler creates a function for each kind of $p$. Indeed the elements\nof $\\mathbb{F}_{p^n}$ have type \\texttt{fq\\_nmod} for $p$ small or \\texttt{fq}\nfor $p$ large, so one can write only one function and have two compiled\nfunctions: one for each type, which will be optimized by the compiler for this \ntype.\n\n\\subsection{Nemo}\n\nNemo is a computer algebra package of Julia, it can be installed with \n\\begin{verbatim}\njulia> Pkg.add(\"Nemo\")\njulia> using Nemo\n\\end{verbatim}\nand tested with the following.\n\\begin{verbatim}\njulia> Pkg.test(``Nemo'')\n\\end{verbatim}\nNemo is based on C/C++ libraries such as Flint, Antic, Pari, etc. and is also\nwritten in Julia. It provides a lot of features, and all the work of this\ninternship is based on Nemo. Indeed, we work with Nemo finite fields and Nemo\npolynomials over these fields. \\texttt{fq}, \\texttt{fq\\_nmod}, and\n\\texttt{fq\\_nmod\\_poly} (the type of the polynomials over $\\mathbb{F}_{p^n}$) \nare\nall Nemo types. The interested reader can learn more in Nemo's manual, which is very well\ndocumented.\n\n\\section{A bit of theory}\n\\subsection{General background}\nIn most of the computer algebra systems, like Sage, Magma, Flint, etc., it is \npossible to work with finite\nfields and their algebraic closure. Let $p$ be a prime number and\n$k=\\mathbb{F}_p$ the field with $p$ elements, the algebraic closure of $k$ is\ninfinite and is $\\bar k = \\cup_{i\\geq 0} \\mathbb{F}_{p^i}$, dealing with $\\bar\nk$ means being able to compute the finite fields $\\mathbb{F}_{p^i}$, and also\nbeing able to embed small fields into large ones, or project elements of large\nfields into smaller ones (when possible).\n\nThese algorithms often rely on linear algebra, and the cost is at least \nquadratic in the degree of the extension used. The algorithms presented\nin~\\cite{DeDoSc14} rely on polynomial arithmetic, and have a quasi-linear cost for \nmost of the algorithms needed to\ncompute in the algebraic closure of a finite field. In this section, we will\nintroduce (briefly) the tools used in the algorithms, and explain how they work.\nThe most important result is the \\emph{transposition principle}, an\nalgorithmic proposition that guarantees that with any linear algorithm\nperforming a matrix-vector product $v\\mapsto Mv$, one can \\emph{transpose} it to\nobtain another algorithm, which has essentially the same cost, performing the \ntransposed matrix-vector product $v\\mapsto\nM^tv$. But we first need to talk about \\emph{duality}, because the transposition\nprinciple also changes the used basis. \n\\subsection{Trace and duality}\nLet $k$ be a finite field, and  $E,F$ be two $k$-vector spaces with the same\nfinite dimension $\\dim E = \\dim F < \\infty$. Let also\n$\\ps{\\cdot}{\\cdot}:E\\times F\\rightarrow k$ be a non-degenerate bilinear form. \nThen,\nfor any basis $\\bxi=(\\xi_i)_i$ of $E$, there exists a unique basis\n$\\bxi^*=(\\xi_j^*)_j$ of $F$\nsuch that $\\forall (i,j),\\ps{\\xi_i}{\\xi_j^*}=\\delta_{i,j}$ where $\\delta_{i,j}$ \nis\nthe \\textsc{Kronecker} symbol and $\\delta_{i,j}=1$ if $i=j$ and 0 otherwise.\nThe basis $\\bxi^*$ is called the \\emph{dual basis} of $\\bxi$.\nSimilarly, let $E',F'$ be two other $k$-vector spaces with $\\dim E' = \\dim F' <\n\\infty$ and $\\ps{\\cdot}{\\cdot}':E'\\times F'\\rightarrow k$ another \nnon-degenerate\nbilinear form. Then, for any linear map $u:E\\rightarrow E'$, there exists a\nunique map $u^t:F'\\rightarrow F$ such that $\\forall (a,b)\\in E\\times\nF',\\ps{u(a)}{b}'=\\ps{a}{u^t(b)}$. This map is called the \\emph{dual} map of $u$,\nwith respect to $\\ps{\\cdot}{\\cdot}$ and $\\ps{\\cdot}{\\cdot}'$.\n\nIt is now time to speak about the \\emph{trace form}, it will be our candidate to \nbe \n$\\ps{\\cdot}{\\cdot}$, the non-degenerate bilinear form. Let $P$ be an irreducible\npolynomial of $k[x]$ of degree $m$, let $K=k[x]/(P)$ be a finite\nextension of $k$, and $a\\in K$. We denote by $\\mu_a$ the application of\nmultiplication-by-$a$, $\\mu_a:K\\rightarrow K, b\\mapsto ab$. $K$ is a $k$-vector\nspace of dimension $m$ and $\\mu_a$ is an endomorphism of $K$. For all \n$a,b\\in K$, we also denote by $\\tau_P(ab)$ the trace of the endomorphism \n$\\mu_{ab}$, and we define\n$\\ps{a}{b}_P=\\tau_P(ab)$. This defines a non-degenerate bilinear form on \n$K\\times\nK$. Thus, if $\\bxi$ is a basis of $K$, one can obtain a dual basis $\\bxi^*$ with\nrespect to the bilinear form $\\ps{\\cdot}{\\cdot}_P$. Hence, if $a\\in K$ has the\ncoordinates $(a_i)_i$ in the basis $\\bxi^*$, these coordinates are given by\n$a_i=\\ps{\\xi_i}{a}$, so $a=\\sum a_i\\xi_i^*=\\sum\\ps{\\xi_i}{a}\\xi_i^*$. This\nformula will be important for the change-of-basis algorithms.\n\nLet now $Q$ be an irreducible polynomial of $k[y]$ of degree $n$, with $n$\ncoprime to $m$, then $L=k[x,y]/(P,Q)\\cong \\mathbb{F}_{p^{mn}}$ is also a finite \nextension of $k$, of\ndegree $mn$. Since $L$ is a $k$-vector space (of dimension $mn$), it is again\npossible to construct the trace $\\tau_{P,Q}$ of an element of $L$, and we define \nthe same way\na non-degenerate bilinear form $\\psdot_{P,Q}$ on $L\\times L$. If\n$\\bxi=(x^i)_{0\\leq i\\leq m-1}$ and $\\bupsilon=(y^j)_{0\\leq j \\leq n-1}$ are the\nmonomial bases of respectively $k[x]/(P)$ and $k[y]/(Q)$, then\n$\\bxi\\otimes\\bupsilon=(x^iy^j)_{0\\leq i \\leq m-1,0\\leq j \\leq n-1}$ is the\ncannonical monomial basis of $L$. But, if $\\bxi^*$ and $\\bupsilon^*$ are\nrespectively the dual basis of $\\bxi$ with respect to $\\tau_P$ and the dual\nbasis of $\\bupsilon$ with respect to $\\tau_Q$, $\\bxi\\otimes\\bupsilon^*$, \n$\\bxi^*\\otimes\\bupsilon$, and $\\bxi^*\\otimes\\bupsilon^*$, are also bases of $L$.\nWhat's more, $\\bxi\\otimes\\bupsilon$ and  $\\bxi^*\\otimes\\bupsilon^*$ are dual\nwith respect to $\\tau_{P,Q}$, and so are $\\bxi\\otimes\\bupsilon^*$ and\n$\\bxi^*\\otimes\\bupsilon$.\n\nConstructing\n$\\mathbb{F}_{p^{mn}}$ this way leads to a bivariate reprentation of the\nelements. We prefer a univariate representation, because the algorithms we have\nin this case are more efficient, even for simple operations such as \nmultiplication. Hence, we can represent $\\mathbb{F}_{p^{mn}}$ by $k[z]/(R)$\nwhere $R=P\\odot Q$ is the composed product of $P$ and $Q$. It means that if\n$(p_i)_{0\\leq i \\leq m-1}$ and $(q_j)_{0\\leq j\\leq n-1}$ are respectively the\nroots of $P$ and $Q$ in a algebraic closure of $k$, $R$ is the polynomial whose\nroots are the products $p_iq_j$. So we have embeddings $\\varphi_x$, $\\varphi_y$\nand an isomorphism $\\Phi$ of the form:\n\\[\n\\begin{array}{crcl}\n  \\varphi_x: & k[x]/(P) & \\to & k[z]/(R),\\\\[2mm]\n  \\varphi_y: & k[y]/(Q) & \\to & k[z]/(R),\\text{ and}\\\\[2mm]\n  \\Phi:&  A=k[x,y]/(P,Q) & \\to & k[z]/(R) \\\\\n  &  xy & \\mapsto & z.\n\\end{array}\n\\]\n\nWe will provide algorithms for $\\varphi_x$, $\\varphi_y$ and $\\Phi$ in Section~\\ref{sec-algo}.\n\n\\subsection{Transposition principle}\nLet, as in the previous section, $\\bxi$ be a basis of $E$, and $\\bxi^*$ the\nbasis of $F$ which is dual to $\\bxi$. Let also $\\bupsilon$ and $\\bupsilon^*$ be, respectively,\na\nbasis of $E'$ and its dual basis of $F'$. If $M$ is the matrix of a linear map\n$u:E\\rightarrow E'$ in the\nbases $(\\bxi,\\bupsilon)$, then the matrix of the linear map $u^t:F'\\rightarrow \nF$ in the bases\n$(\\bupsilon^*,\\bxi^*)$ is $M^t$. Given an algorithm to compute a linear map\n$u:E\\rightarrow E'$ in the bases $(\\bxi,\\bupsilon)$, the transposition principle\nsays that one can transpose it to obtain a new algorithm computing the dual map \n$u^t:F'\\rightarrow F$ in the bases\n$(\\bupsilon^*,\\bxi^*)$. The costs of the two algorithms only differ by a\nconstant. Roughly speaking, transposing an algorithm consists on transposing all\nthe subroutines and inverse their orders.\n\n\\begin{ex}\nLet $A$ be an algorithm taking $x_1$ and $x_2$ as input, and computing \n$y_1=ax_1+bx_2$ and $y_2=cx_1+dx_2$. $A$ is linear and we obtain its \ntransposition $A^t$ by reversing all the arrows and exchanging $\\times$ and $+$ \nin the graph representing $A$. We obtain an algorithm that takes $y_1$ and \n$y_2$ as input and compute $x_1=ay_1+cy_2$ and $x_2=by_1+dy_2$.\n\n\\begin{figure}[!h]\n\\begin{tikzpicture}\n  \\matrix[matrix of math nodes,column sep={60pt,between origins},row\n    sep={60pt,between origins},nodes={asymmetrical rectangle}] (s)\n  {\n    &|[name=x1]| x_1 &|[name=1]| \\times &|[name=2]| + & |[name=y1]| y_1\\\\\n    %\n    &|[name=x2]| x_2 &|[name=3]| \\times &|[name=4]| + &|[name=y2]| y_2 \\\\\n  };\n  \\draw[->,>=latex] (1) edge node[auto] {\\(a\\)} (2)\n  \t\t\t(3) edge node[auto] {\\(d\\)} (4)\n            (1) edge (4)\n            (3) edge (2)\n            (x1) edge (1)\n            (x2) edge (3)\n            (2) edge (y1)\n            (4) edge (y2)\n            ;\n            \\draw (1.5,0.3) node {$b$}\n            (1.5,-0.3) node {$c$}\n            ;\n\t    \\draw[->,>=latex,gray,dotted,thick] (1,-1.5) -- (1,-2.5);\n\t    \\draw[gray] (3,-2) node {transposition principle};\n\\end{tikzpicture}\n\n\\begin{tikzpicture}\n  \\matrix[matrix of math nodes,column sep={60pt,between origins},row\n    sep={60pt,between origins},nodes={asymmetrical rectangle}] (s)\n  {\n    &|[name=x1]| x_1 &|[name=1]| + &|[name=2]| \\times & |[name=y1]| y_1\\\\\n    %\n    &|[name=x2]| x_2 &|[name=3]| + &|[name=4]| \\times &|[name=y2]| y_2 \\\\\n  };\n  \\draw[->,>=latex] (2) edge node[auto] {\\(a\\)} (1)\n  \t\t(4) edge node[auto] {\\(d\\)} (3)\n            (4) edge (1)\n            (2) edge (3)\n            (1) edge (x1)\n            (3) edge (x2)\n            (y1) edge (2)\n            (y2) edge (4)\n            ;\n            \\draw (1.5,0.3) node {$b$}\n            (1.5,-0.3) node {$c$};\n\\end{tikzpicture}\n\\caption{Transposition of a simple arithmetic circuit}\n\\end{figure}\n\\end{ex}\n\nLet us introduce some operations and their transposes. Let $k$ be a field and \n$k[x]_m$ the vector space of polynomials of degree at most $m$, the reversal \noperator of $k[x]_m$ is the map such that\n\n\\[  \n\\begin{array}{rccc}\n  \\textbf{rev}(\\cdot,m): & k[x]_m & \\to & k[x]_m \\\\\n   & Q & \\mapsto & x^mQ(1/x)\n\\end{array}.\n\\]\nWe can see that \\textbf{rev} is its own transpose, indeed \\textbf{rev} is a \nlinear map and its matrix in the cannocial basis of $k[x]_m$ is symmetric: it \nis the matrix with $1$'s on the anti-diagonal. Let now $P\\in k[x]$ be a monic \npolynomial of degree $m$ and $n\\in\\mathbb{N}$ an integer, we denote by \n$\\textbf{rem}(\\cdot,P,n)$ the remainder by $P$ with length $n$, defined by \n\\[  \n\\begin{array}{rccc}\n  \\textbf{rem}(\\cdot,P,n): & k[x]_n & \\to & k[x]_{m-1} \\\\\n   & Q & \\mapsto & Q\\mod P\n\\end{array}.\n\\]\n\nAs explained in~\\cite{BoLeSc03}, $\\textbf{rem}^t(\\cdot,P,n)$ is the linear \nsequence extension: it takes as input the $m$ first terms of a linear \nrecurring sequence and computes the $n+1$ first terms using $P$ as the minimal \npolynomial of the sequence.\n\n\\subsection{The algorithms}\n\\label{sec-algo}\nAll the algorithms described here, and their complexity analysis, have been\ndiscussed in~\\cite{DeDoSc14}, that is why we will not show all the pseudo-codes but\nrather try to explain how they work and on which result they are based. The \ncomplexities will also be given without any proofs. \n\nAs we saw in the previous section, transposing an algorithm results in a change\nof basis. Thus, it is important to be able to go from a basis to another. Here\nagain $k$ is a finite field, $P$ an irreducible monic polynomial of $k[x]$, \nand\n$K=k[x]/(P)$ is a finite extension of $k$. We will be considering two bases of\n$K$: the monomial basis $\\bxi=(x^i)_{0\\leq i \\leq m-1}$ (where $m$ is the\ndegree of $P$), and its dual basis $\\bxi^*$ with respect to $\\psdot_P$.\n\n\\paragraph{Change of basis.}The two\nfirst algorithms allow us to juggle between the monomial and the dual basis. They are\nboth based on a lemma which describes the generating series of the traces\n$\\tau_P(ax^i)_{0\\leq i \\leq m-1}$, where $a\\in K$. \n\\begin{lm}\n  \\label{lm-basis}\n  Let $a\\in K$ be an element of $K$. In the formal power series ring $k[[x]]$,\n  we have:\n  \\[\n    \\sum_{i\\geq 0}\\tau_P(ax^i)x^i=\\frac{\\rev(P'a\\bmod P,m)}{\\rev(P,m+1)}.\n  \\]\n\\end{lm}\nGoing from the monomial basis to the dual basis can be done by computing\n$\\rev(P'a\\bmod P,m)\\mod x^m$, $(\\rev(P,m+1)\\bmod x^m)^{-1}$, and the product of\nthem. We obtain, by Lemma~\\ref{lm-basis}:\n\\[\n  \\frac{\\rev(P'a\\bmod P,m)}{\\rev(P,m+1)}\\mod x^m=\\sum_{i=0}^{m-1}\\tau_P(ax^i)x^i.\n\\]\nSince we said that\n$(\\tau_P(ax^i))_{0\\leq i \\leq m-1}$ are the coordinates of $a$ in the dual basis\n$\\bxi^*$, taking the coefficient of the polynomial\n$\\sum_{i=0}^{m-1}\\tau_P(ax^i)x^i$ gives a solution to go from the monomial basis\nto the dual basis, that can be written as follows.\n\\newline\n\n\\texttt{monomialToDual}(a, P)\\\\\n\\textbf{Input} $\\textbf{a}=(a_i)_{0\\leq i\\leq m-1}\\in k^m$, $P$ an irreducible\nmonic polynomial of degree~$m$.\\\\\n\\textbf{Output} $(\\tau_P(ax^i))_{0\\leq i \\leq m-1}$, with $a=\\sum_{0\\leq i\n\\leq m-1}a_ix^i$\n\\begin{enumerate}\n  \\item $T=1/\\rev(P,m+1) \\mod x^m$\n  \\item $b=\\rev(P'a=\\sum_{0\\leq i\\leq m-1}a_ix^i \\mod P,m)T\\mod x^m$\n  \\item \\textbf{return} (coefficient($b,x^i))_{0\\leq i \\leq m-1}$\n\\end{enumerate}\n\nObtaining the coefficients in the monomial basis $\\bxi$\nknowing the coefficients in the dual basis $\\bxi^*$ is done using the same\nequality, but starting from the other half. So, computing $\\sum_{0\\leq i \\leq\nm-1}\\tau_P(ax^i)x^i \\mod x^m$, $\\rev(P,m+1)$, and multiplying them gives, by\nLemma~\\ref{lm-basis} again: \n\\[\n\\rev(P,m+1)\\sum_{0\\leq i \\leq m-1}\\tau_P(ax^i)x^i \\mod x^m = \\rev(P'a\\mod P,m) \n\\mod x^m.\n\\]\nThen, applying $\\rev(\\cdot,m)$ and multiplying by $(P')^{-1}\\mod P$ gives $a\\mod\nP$, so taking the coefficients of $a$ gives the coefficients in the monomial\nbasis $\\bxi$.\n\\newline\n\n\\texttt{dualToMonomial}(b, P)\\\\\n\\textbf{Input} $\\textbf{b}=(b_i)_{0\\leq i\\leq m-1}\\in k^m$, $P$ an irreducible\nmonic polynomial of degree $m$.\\\\\n\\textbf{Output} $(a_i)_{0\\leq i \\leq m-1}$ such that\n$\\tau_P(\\sum_{0\\leq i \\leq m-1}ax^{i+j})=b_j$ for all $j$\n\\begin{enumerate}\n  \\item $S=1/P \\mod P$\n  \\item $b=\\rev(P,m+1)\\sum_{0\\leq i\\leq m-1}b_ix^i\\mod x^m$\n  \\item $c=\\rev(b,m)$\n  \\item $d=cS \\mod P$\n  \\item \\textbf{return} (coefficient($d,x^i))_{0\\leq i \\leq m-1}$\n\\end{enumerate}\n\nAs we see, even if the lemma holds in $k[[x]]$, we just need to work $\\mod x^m$\nso the inverses can be obtained with fast algorithms for \\textsc{Euclide}\ndivision. \\texttt{monomialToDual} uses $O(M(m))$ operations in $k$, where \n$M(m)$ is the number of operations in $A$ of a multiplication of polynomials of \ndegree at most $m$ on any ring $A$. The cost of \\texttt{dualToMonomial} is \n$O(M(m)\\log(m))$, but can be reduced to $O(M(m))$ with precomputations. $M$ is \na function that is quasi-linear, so the change-of-basis algorithms are \nquasi-linaear too. \n\n\\paragraph{Embedding and computing R.} Let $Q$ be an irreducible monic\npolynomial of $k[y]$ of degree $n$, with $n$ coprime to $m$. Let also $R=P\\odot\nQ$ be the composed product of $P$ and $Q$. We have the extensions $k[x]/(P)$,\n$k[y]/(Q)$, $k[x,y]/(P,Q)$, and $k[z]/(R)$ which respectively have the traces\n$\\tau_P$, $\\tau_Q$, $\\tau_{P,Q}$, $\\tau_R$ and the associated bilinear forms.\nThese extensions are respectively endowed with the monomial bases $\\bxi$,\n$\\bupsilon$, $\\bxi\\otimes\\bupsilon$ and $\\bzeta$. Finally, we denote by\n$\\bxi^*$, $\\bupsilon^*$ and $\\bzeta^*$ the dual bases of $\\bxi$, $\\bupsilon$ and\n$\\bzeta$ with respect to $\\psdot_P$, $\\psdot_Q$ and $\\psdot_R$. In this paragraph, we will\ngive algorithms to compute the embeddings $\\varphi_x$, $\\varphi_y$, their\nsections, and to compute the polynomial $R$. The algorithms follow from the next\nlemma.\n\\begin{lm}\n  \\label{lm-trac}\n  Let $b$ be in $k[x]/(P)$ and $c$ in $k[y]/(Q)$. Then we have\n  $\\tau_R(\\Phi(bc))=\\tau_{P,Q}(bc)=\\tau_P(b)\\tau_Q(c)$.\n\\end{lm}\nThis lemma will permit us to compute the restriction of $\\Phi$ to the set \n\\[\n  \\Pi=\\left\\{ bc \\;|\\; b\\in k[x]/(P), c\\in k[y]/(Q) \\right\\}\\subset\n  k[x,y]/(P,Q).\n\\]\nIndeed, if we have the coordinates $(\\tau_P(bx^i))$ and $(\\tau_Q(cy^j))$ of $b$ and\n$c$ in the dual bases, we can extend them up to $mn-1$ using $\\remt$, then, by Lemma~\\ref{lm-trac}, we have\n$(\\tau_P(bx^i)\\tau_Q(cy^i))_{0\\leq i \\leq mn-1}=(\\tau_R(\\Phi(bc)z^i))_{0\\leq i\n\\leq mn-1}$ which gives us the coordinates of $\\Phi(bc)$ in the dual basis\n$\\bzeta^*$. So we can obtain $\\varphi_x$ and $\\varphi_y$ by applying the last\nformula with respectively $c=1$ and $b=1$. This can be written as follows.\n\\newline\n\n\\texttt{embed}(b, c, r)\\\\\n\\textbf{Input} $\\textbf{b}=(b_i)_{0\\leq i\\leq m-1}\\in k^m$,\n$\\textbf{c}=(c_i)_{0\\leq i\\leq n-1}\\in k^n$, an optional integer $r\\geq mn$ set\nto $r=mn$ by defaut\\\\\n\\textbf{Output} $\\textbf{a}=(a_i)_{0\\leq i\\leq r-1}\\in k^r$\n\\begin{enumerate}\n  \\item $(t_i)_{0\\leq i \\leq r-1}=\\remt(\\textbf{b},P,r)$\n  \\item $(u_i)_{0\\leq i \\leq r-1}=\\remt(\\textbf{c},P,r)$\n  \\item \\textbf{return} $(t_iu_i)_{0\\leq i \\leq r-1}$\n\\end{enumerate}\n\\texttt{embed} uses $O(r(M(m)/m + M(n)/n))$ operations in $k$.\nIf $u_P$ is the vector of the coordinates of $1\\in k[x]/(P)$ in the dual basis\n$\\bxi^*$ and $u_Q$ the vector defined similarly, we can compute\n$\\varphi_x=\\texttt{embed}(\\cdot,u_Q)$ and $\\varphi_y=\\texttt{embed}(u_P,\\cdot)$.\nSince $R$ is the minimal polynomial of the sequence\n$(\\tau_R(z^i))=\\texttt{embed}(u_P,u_Q)$, we can obtain $R$ by computing the\n\\textsc{Berlekamp-Massey} algorithm (which computes minimal polynomials of linear\nsequences).\n\nAs we have just seen, the theory of duality gives us a very simple algorithm for\n\\texttt{embed}, but together with the transposition principle, it will also\nprove useful to find algorithms for the section of $\\varphi_x$, and, as we will\nsee later, for $\\Phi^{-1}$. Let $c\\in k[y]/(Q)$ such that $\\tau_Q(c)=1$ (for\nexample $c=\\upsilon^*_0$ is convenient), $\\varepsilon:k[x]/(P)\\to k[z]/(R),\nb\\mapsto \\Phi(bc)$, and $\\varepsilon^t:k[z]/(R)\\to k[x](P)$ its dual map with\nrespect to $\\psdot_P$ and $\\psdot_R$. Then, for any $b$, $b'$ in $k[x]/(P)$, we\nhave\n\\[\n\\begin{array}{rcl}\n  \\ps{b}{b'}_P &=& \\tau_P(bb') = \\tau_P(bb')\\tau_Q(c) = \\tau_R(\\Phi(bb'c))\\\\\n  &=& \\ps{\\varepsilon(b)}{\\Phi(b')}_R = \\ps{b}{\\varepsilon^t(\\Phi(b'))}_P.\n\\end{array}\n\\]\nSince $\\psdot_P$ is non-degenerate, this means that \n$b'=\\varepsilon^t(\\Phi(b'))=\\varepsilon^t(\\varphi_x(b'))$ for all $b'\\in \nk[x]/(P)$. In other words, $\\varepsilon^t$ is an inverse of $\\varphi_x$ on its \nimage, also called a section of $\\varphi_x$. Remarking that $\\varepsilon$ is \nnothing else that $\\texttt{embed}(\\cdot,c)$, where $c=(1,0,\\dots,0)$, we have \nan algorithm for $\\varepsilon$, and, by transposing this algorithm, we have an \nalgorithm for $\\varepsilon^t$, which is the section of $\\varphi_x$ we were \nsearching. This algorithm uses $O(nM(m)+nM(n))$ operations in $k$.\n\n\\paragraph{Isomorphism.} We will apply the same kind of strategy to deduce an \nalgorithm for $\\Phi^{-1}$ from an algorithm for $\\Phi$. First, recall that \n$\\bxi\\otimes\\bupsilon$, $\\bxi^*\\otimes\\bupsilon^*$, $\\bxi^*\\otimes\\bupsilon$ \nand $\\bxi\\otimes\\bupsilon^*$ are all bases of $k[x,y]/(P,Q)$ and that the \nsecond is dual to the first and the third to the fourth, with respect to \n$\\psdot_{P,Q}$. Let $\\Phi^t$ be the dual map to $\\Phi$ with respect to \n$\\psdot_{P,Q}$ and $\\psdot_R$. For any $b$ and $b'$ in $k[x,y]/(P,Q)$, we have\n\\[\n\\begin{array}[here]{rcl}\n  \\ps{b}{b'}_{P,Q} &=& \\tau_{P,Q}(bb') = \\tau_R(\\Phi(bb')) \\\\\n  &=& \\ps{\\Phi(b)}{\\Phi(b')}_R = \\ps{b}{\\Phi^t(\\Phi(b'))}_{P,Q}.\n\\end{array}\n\\]\nSo, here again, thanks to the non-degeneracy of $\\psdot_{P,Q}$, we have \n$\\Phi^t=\\Phi^{-1}$. Hence, if we have an algorithm computing $\\Phi$ in  \nsome bases $\\textbf{a}$ and $\\textbf{b}$, we can deduce, using the \ntransposition principle, an algorithm computing $\\Phi^{-1}$ in the dual bases \n$\\textbf{b}^*$ and $\\textbf{a}^*$. We have two algorithms for computing $\\Phi$, \nthe first is better in cases where $m$ is small compared to $n$, and uses the \nlinearity of $\\Phi$ and the work already done. The idea is to express $b\\in \nk[x,y]/(P,Q)$ in the form $b=\\sum_i^{m-1}b_ix^i$ with $b_i\\in k[y]/(Q)$ for all \n$0\\leq i \\leq m-1$. Since the $b_ix^i$ are all in $\\Pi$, we can apply \n\\texttt{embed} and sum the result to obtain $\\Phi(b)=\\sum_i^{m-1}\\Phi(b_ix^i)$. \nTo apply this strategy, the $b_i$ must be expressed in the dual basis \n$\\bupsilon^*$ of $k[y]/(Q)$, because \\texttt{embed} takes its input in the dual \nbases. In the end, exploiting the fact that the coordinates of the $x^i$ in the \ndual basis $\\bxi^*$ are $(\\tau_P(x^{i+j}))_{0\\leq j\\leq m-1}$ ($u_P$ shifted \n$i$ times), we have an algorithm to compute $\\Phi$ in the basis \n$\\bxi\\otimes\\bupsilon^*$ and giving the result in the basis $\\bzeta^*$. As we \nnoticed, transposing this algorithm will create a new algorithm computing \n$\\Phi^{-1}$ and expressed in the bases $\\bzeta$ and $\\bxi^*\\otimes\\bupsilon$. \nThese algorithms both have a quadratic cost in the degree $m$: $O(m^2M(n))$.\n\nThe second way of computing $\\Phi$ does not depend on previous algorithms, but \nwe will still be able to deduce an algorithm for $\\Phi^{-1}$ from it using the \ntransposition principle. It is best suited when dealing with $m$ and $n$ of the \nsame magnitude and it uses baby steps / giant steps: a technique consisting of \nsacrificing memory to gain speed. Recall that $\\Phi(xy)=z$, then, if $b\\in \nk[x,y]/(P,Q)$, we can write\n\\begin{eqnarray*}\nb&=&\\sum_{i=0}^{m-1}\\sum_{j=0}^{n-1} b_{i,j}x^i y^j\n=~\\sum_{i=0}^{m-1}\\sum_{j=0}^{n-1} b_{i,j}x^i y^i y^{j-i}\\\\\n&=&\\sum_{h=-m+1}^{n-1}\\sum_{i=0}^{m-1} b_{i,i+h}(xy)^i y^h\n=~\\frac{1}{y^{m-1}} \\sum_{h=0}^{m+n-2} c_h(xy) y^h,\n\\end{eqnarray*}\nwith $c_h(xy)=\\sum_{0 \\leq i \\leq m-1} b_{i,i+h-m+1} (xy)^i$, and where \nundefined indices $b_{i,i+h-m+1}$ equal zero. So $\\Phi(xy)=z$ is known, but \nalso $T=\\Phi(y)$, because $y\\in\\Pi$ so we can use $\\texttt{embed}$ to compute \nit. Then, we have \n\\[\na = \\frac{1}{T^{m-1}}\\tilde a \\mod R \\text{ with } \\tilde a = \\sum_{h=0}^{m+n-2} \nc_h(z) T^h.\n\\]\nThis is the equality that will be exploited to compute $\\Phi$, and, thanks to \nbaby steps / giant steps techniques, this will be reduced to matrix \nmultiplication (but the coefficients of those matrices are polynomials). This \ntechnique gives an algorithm expressed in the bases $\\bxi\\otimes\\bupsilon$ and \n$\\bzeta$. Details can be found in~\\cite{DeDoSc14}. As we said earlier, we \nimmediatly deduce an algorithm for $\\Phi^{-1}$ using the \ntransposition principle, this last algorithm will be expressed in the bases \n$\\bzeta^*$ and $\\bxi^*\\otimes\\bupsilon^*$. Both these algorithms use \n$O(M(mn)n^{1/2}+M(m)n^{(\\omega+1)/2})$ operations in $k$, where $\\omega$ is a \nconstant such that one can multiply two matrices of size $n\\times n$ over any \nring $A$ in $O(n^\\omega)$ operations in $A$ (we know that $2 < \\omega \\leq \n2.38$).\n\n\n\\section{Julia/Nemo in practice}\nSince Julia is easy-to-write, we hope it is also\neasy-to-read. If not, it is probably due to the way FastArithmetic.jl is written,\nrather than to Julia itself. The code can be found at\n\\url{https://github.com/erou/FastArithmetic.jl}. What's more, it is really\neasy to install personal packages, one just has to clone the repository\ninside Julia, using\n\\begin{verbatim}\njulia> Pkg.clone(``https://github.com/edouardRousseau/FastArithmetic.jl'') \n\\end{verbatim}\nand the package can be easily tested by running the following.\n\\begin{verbatim}\njulia> Pkg.test(``FastArithmetic'') \n\\end{verbatim}\nThe code is very likely to change, but it is possible to update the package as\nfollows.\n\\begin{verbatim}\njulia> Pkg.update()\n\\end{verbatim}\n\\subsection{Benchmarks}\nWe will now look at the speed of the code in Julia, and compare it with\nthe speed in C. All the benchmarks in Julia were realised with the\n\\texttt{@benchmark} macro available in the BenchmarkTools package. This macro\ncan be used to benchmark any function with \n\n\\begin{verbatim}\njulia>@benchmark 1+1\nBenchmarkTools.Trial: \n  samples:          10000\n  evals/sample:     1000\n  time tolerance:   5.00%\n  memory tolerance: 1.00%\n  memory estimate:  0.00 bytes\n  allocs estimate:  0\n  minimum time:     3.00 ns (0.00% GC)\n  median time:      3.00 ns (0.00% GC)\n  mean time:        3.04 ns (0.00% GC)\n  maximum time:     10.00 ns (0.00% GC)\n\\end{verbatim}\nwhich runs the desired function and measures the time it takes. It is possible\nto choose all the parameters (number of samples, number of evaluation\nper sample,\\dots) of the benchmark and one can use different\nestimators. For the following benchmarks, we use the median time, because it\nis more stable than the mean time and still gives an idea of the average time\nthe function will take. The stability we are talking about is linked with the\nmemory management in Julia. Indeed, in Julia, we do not have to concern about\nmemory, and the variables we assign are cleared by the Garbage Collector\n(GC). The time Julia passes in the GC is not very clear nor predictible, and the\noperations in the GC take a significant time. That is why the time taken by a\nfunction can change between two samples, depending on the time spent in the GC.\nBy default, before every benchmark, the garbage is automaticaly collected, but\nthere is still a bit of instability. We benchmark our functions in the case\n$p=5$, as in~\\cite{DeDoSc14}, because no difference is seen between different\nvalues of $p$.\nSince all the functions written in FastArithmetic.jl depend on at least one\npolynomial $P$, sometimes also $Q$ and $R=P\\odot Q$, we let $m=\\deg (P)$ grow\nfrom $1$ to $200$ and benchmark the functions for all these values of $m$. We\nchoose $\\deg (Q)=m+1$, and both $P$ and $Q$ are irreducible polynomials.\nIrreducible polynomials of degree $1$ to $201$ were precomputed, by choosing\nrandom elements in $\\mathbb{F}_{p}[X]$, in order to\nalways use the same list and to be sure that we are not using special\npolynomials that could be speeding up the functions (like sparse\npolynomials). When only one field is involved in an operation (such as in \nmodular multiplication or in change of basis) the field used is \n$\\mathbb{F}_{p^{m(m+1)}}\\cong k[z]/(R)$.\n\nThe benchmarks of the C code were realized thanks to a python \nscript written by the authors of the code, that can be found at \n\\url{https://github.com/defeo/ff\\_compositum}. The benchmarks work the same but not \nall the values of $m$ were tested, so we just chose to compare the results for \ncertain values of $m$ tested (we also could have change the script\\dots).\n\nIn the tables, the speed of\nthe C code is set to $1.00$, and smaller is better. One of the functions \nbenchmarked in the C code, the modular multiplication \\texttt{mulmod}, was \nalready implemented in Nemo, so we start to compare the results. We see no\ndifference in terms of speed and it was predictible: the Julia\nfunction is calling C code.\n\n\\begin{center}\n  \\begin{tabular}[here]{c}\n    \\texttt{mulmod} \\\\\n    \\begin{tabular}[here]{cc}\n   $m$ & Julia \\\\\n   $10$ & $0.99$\\\\\n   $51$ & $1.04$\\\\\n   $104$ & $1.03$\\\\\n   $140$ & $1.05$\\\\\n   $187$ & $1.07$\\\\\n    \\end{tabular}\n  \\end{tabular}\n\\end{center}\nThe speed of \\texttt{monomialToDual} and of \\texttt{dualToMonomial} are the \nsame, either in C or Julia, so we show the results only for the first.\nAll the Julia functions differ from the C ones by a\nconstant factor, which depends on the functions but is around $8$.\nSurprisingly, \\texttt{inversePhi1} is three times faster than its transposition\n\\texttt{phi1}, and \\texttt{inversePhi2} is slower than \\texttt{phi2} for small\nvalues of $m$ but equals its speed at $m\\approx 100$ and is two times faster for $m\\geq170$.\nIn Julia, the cross point between \\texttt{phi1} and \\texttt{phi2} is earlyer than\nin C, it occures at $m=30$.\n\nWe did not mention the time to compute $R$ in these tables, the reason \nis because the implementation of the \\textsc{Berlekamp-Massey} algorithm used \nin it is naive, so the algorithm \\texttt{computeR} can be improved easily by \nimproving \\textsc{Berlekamp-Massey}.\n\n\\begin{center}\n\\begin{tabular}[here]{ccc}\n  \\texttt{monomialToDual} & \\texttt{monomialToDual\\_pre} & \\texttt{mulModT} \\\\\n\n  \\begin{tabular}[here]{cc}\n   $m$ & Julia \\\\\n   $10$ & $10.50$\\\\\n   $51$ & $10.92$\\\\\n   $104$ & $10.26$\\\\\n   $140$ & $10.43$\\\\\n   $187$ & $11.03$\\\\\n\n  \\end{tabular}\n\n  &\n\n \\begin{tabular}[here]{cc}\n   $m$ & Julia \\\\\n   $10$ & $3.13$\\\\\n   $51$ & $2.99$\\\\\n   $104$ & $1.96$\\\\\n   $140$ & $2.06$\\\\\n   $187$ & $3.06$\\\\\n\n  \\end{tabular}\n\n\n  &\n  \n  \\begin{tabular}[here]{cc}\n   $m$ & Julia \\\\\n   $10$ & $19.92$\\\\\n   $51$ & $15.62$\\\\\n   $104$ & $16.23$\\\\\n   $140$ & $17.73$\\\\\n   $187$ & $17.97$\\\\\n\n  \\end{tabular}\n\n\\end{tabular}\n\\end{center}\n  \n\n\\begin{center}\n\\begin{tabular}[here]{cccc}\n  \\texttt{embed} & \\texttt{project} & \\texttt{phi1} & \\texttt{phi2} \\\\\n   \\begin{tabular}[here]{cc}\n   $m$ & Julia \\\\\n   $10$ & $5.29$\\\\\n   $51$ & $4.51$\\\\\n   $104$ & $3.85$\\\\\n   $140$ & $6.78$\\\\\n   $187$ & $5.42$\\\\\n\n  \\end{tabular}\n\n  &\n\n  \\begin{tabular}[here]{cc}\n   $m$ & Julia \\\\\n   $10$ & $5.73$\\\\\n   $51$ & $3.54$\\\\\n   $104$ & $3.00$\\\\\n   $140$ & $2.65$\\\\\n   $187$ & $6.44$\\\\\n\n  \\end{tabular}\n\n  &\n\n  \\begin{tabular}[here]{cc}\n   $m$ & Julia \\\\\n   $10$ & $5.39$\\\\\n   $51$ & $6.29$\\\\\n   $104$ & $5.26$\\\\\n   $140$ & $4.91$\\\\\n   $187$ & $5.74$\\\\\n\n  \\end{tabular}\n\n  &\n \n  \\begin{tabular}[here]{cc}\n   $m$ & Julia \\\\\n   $10$ & $1.90$\\\\\n   $51$ & $3.40$\\\\\n   $104$ & $5.78$\\\\\n   $140$ & $8.28$\\\\\n   $187$ & $9.94$\\\\\n\n  \\end{tabular}\n\\end{tabular}\n\\end{center}\n\n\\section{Conclusion}\nAs we see, we are not able to reach C speed, and the Julia code is slower by a\nconstant factor, approximately $8$. Part of this factor is due to\nprecomputations in C that are not done in Julia. With further investigations and\nunderstanding of the Julia langage, we could probably diminish this constant.\nAnyway, Julia provides a much more generic code and we could have benchmarked\nthe code for $p=2^{127}-1$ without changing a single line. On top of that, Julia\nprovides a variety of tools that makes life easier when coding : the benchmark\nparckage, the package manager, a high-level syntax\\dots It will be up to reader\nto decide if the price of the constant factor $8$ is too much.\n\nAny error in this report or in the code of FastArithmetic.jl can be signaled by\ne-mail (edouard.rousseau@u-psud.fr). Finally, this work would not have been done\nwithout the help of Luca \\textsc{De Feo}, who took the time to answer all the\nnaive questions he received.\n\n\n\\clearpage\n\\bibliographystyle{unsrt}\n\\bibliography{biblio}\n\\end{document}\n", "meta": {"hexsha": "ba2d6539e948bfda3241a9d967a574351e7cb0c0", "size": 34784, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/report.tex", "max_stars_repo_name": "artichaut/fastarithmetic", "max_stars_repo_head_hexsha": "b0484612cec0b9e0d442452fcb17f3569673fb38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "report/report.tex", "max_issues_repo_name": "artichaut/fastarithmetic", "max_issues_repo_head_hexsha": "b0484612cec0b9e0d442452fcb17f3569673fb38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/report.tex", "max_forks_repo_name": "artichaut/fastarithmetic", "max_forks_repo_head_hexsha": "b0484612cec0b9e0d442452fcb17f3569673fb38", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.6274509804, "max_line_length": 107, "alphanum_fraction": 0.6795078197, "num_tokens": 11711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.3453368045945626}}
{"text": "%#########################################################\n\\chapter{Diffusion Modeling to Study Microarchitecture in Human Skeletal Muscles}\n\\label{ch: DiffusionExp}\n%#########################################################\nThe resolution of the MR images is not sufficient to perform direct measurements of the muscle fiber geometry and other physical parameters such as membrane permeability at the level of individual fiber. \nWhile typical resolution of the MR images is $\\approx \\SI{e-3}{\\m}$ histology studies showed that cross-sectional liner dimensions are in the range of $10^{-5} - \\SI{e-4}{\\m}$ \\cite{TAYLOR200335}. \nIn recent years a number of diffusion models were developed in the effort to relate macroscopic signal measured in MRI experiments to the microscopic parameters of muscle tissue. \n%-new paragraph-%\n\n%-new paragraph-%\nThis chapter presents work on application of two diffusion models to interpret disuse atrophy and age related changes in human lower leg muscle.\n\n%=========================================================\n\\section{Monitoring Changes in the Medial Gastrocnemius in Disuse Atrophy Induced by Unilateral Limb Suspension}\n\\label{sec: DTI ULLS}\n%=========================================================\nThe feasibility of diffusion tensor imaging (DTI) of skeletal muscle including muscle fiber tracking for extraction of fiber lengths and pennation angles has been established, and the technique has been applied to monitor muscle injury, aging, gender related differences, and compartmental syndrome~\\cite{RND1, RND2, RND3, RND4, RND5, RND6}. \nAdditionally, some studies have explored changes in muscle DTI with atrophy; e.g., arising from age-related atrophy in human skeletal muscle~\\cite{RND7}, from denervation and from Achilles tenotomy-induced atrophy in rodent models~\\cite{RND8, RND9}.\nFurther, DTI combined with diffusion models is increasingly being used to explore tissue microstructural parameters such as fiber diameter, permeability or intracellular volume fraction~\\cite{RND10}.\nWhile most modeling studies have focused on the brain, a few recent studies have extended modeling efforts to the diffusion in skeletal muscle~\\cite{RND11, RND12, RND13}. \nRecent studies have combined combine magnetic resonance imaging deformation analyses and diffusion tensor imaging tractography in the medial gastrocnemius~\\cite{RNSS4,RNCS4}. \nKarakuzu~et~al. showed that sub-maximal plantar flexion activity at 15\\% Maximum voluntary contraction (MVIC) causes heterogeneous length changes along the fascicles of human medial gastrocnemius (MG) muscle~\\cite{RNCS4}.\nThe heterogeneity of fascicle strains was explained on the basis of epimuscular myofascial force transmission. \n%-new paragraph-%\n\n%-new paragraph-%\nIt is well established that disuse (e.g., by chronic unloading) leads to skeletal muscle atrophy that is accompanied by a significant loss of muscle force~\\cite{RNS1}.\nThe Unilateral Limb Suspension (ULLS) is a validated model to study the effects of chronic unloading~\\cite{RNS8}.\nUnilateral limb suspension results in both loss of muscle mass (muscle fiber atrophy) as well as a decrease in muscle force~\\cite{RNS8}.\nPrior studies of induced immobilization indicate that muscle remodeling with inactivity is a fast process that occurs after about a week of unloading~\\cite{RNS8, RNS5}.\nThese studies documented the decrease in both fiber length and pennation angle, a decrease in Focal Adhesion Kinase content ($-20\\%$) and activity ($-30\\%$), associated with a $50\\%$ fall in muscle protein synthesis and a $5\\%$ decrease in quadriceps muscle anatomical cross-sectional area (ACSA)~\\cite{RNS8, RNS5}.\nDTI with its ability to probe at the microstructural level is ideally suited to investigate potential muscle remodeling that occurs with chronic unloading.\nHowever, no studies to date have investigated unloading induced changes in skeletal muscle using DTI in human subjects.\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\\subsection{Methods}\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n%---------------------------------------------------------\n\\subsubsection{\\textit{In-vivo} experiments}\n%---------------------------------------------------------\nThe study was carried out under the approval of the Medical Research Ethics Board of UC~San~Diego and conformed to all standards for the use of human subjects in research as outlined in the Declaration of Helsinki on the use of human subjects in research.\nIRB approval was obtained from the Medical Research Ethics Board of UC~San~Diego and all subjects were recruited after obtaining written informed consent. A total of 7 normal healthy young subjects (2 females, $29.1 \\pm 5.7$ years, body mass $75.4 \\pm \\SI{22.7}{\\kilogram}$, height $168.1 \\pm \\SI{7.4}{\\centi\\meter}$) were recruited for this study.\nThe criterion for inclusion was that subjects should be moderately physically active. Subjects participating in competitive sports as well as those with any surgical procedures performed on the lower leg were excluded.\n%---------------------------------------------------------\n\\subsubsection{Study design} \n%---------------------------------------------------------\nThe effect of chronic unloading on the force production capability and diffusion tensor indices of the MG muscle were assessed by comparing the baseline (pre) to immediately after four weeks of limb suspension (post).\nDuring the four week suspension period, subject compliance to the protocol was monitored at two weeks to check for muscle atrophy (MRI morphological scan) and loss of force production.\nIn addition, compliance was also monitored by a wireless activity tracker that was integrated into the crutches; the subject was not informed of the tracker to ensure that it was not removed or tampered with to simulate crutch usage.\nAfter the four week suspension, subjects were required to attend structured physical rehabilitation sessions.\nMRI morphological scans were performed at the end of the rehabilitation period (four weeks) to confirm that the muscle had recovered to baseline status.\n%---------------------------------------------------------\n\\subsubsection{Unilateral Limb Suspension (ULLS)}\n%---------------------------------------------------------\nThe ULLS model is an established model of inducing controlled atrophy~\\cite{RNS19} and was used in the current study to induce muscle atrophy on the non-dominant leg with four weeks of chronic unloading.\nThe dominant leg was self-identified by subjects as the one they preferentially used to regain balance from a jostle.\nThe non-dominant leg was the left leg for all subjects in this study.\nThe ULLS protocol allowed the subjects a reasonable amount of freedom to carry out their daily activities including driving since the dominant leg (right in this study) was not unloaded.\nA crutch was used to prevent the foot (of the left leg) from touching the ground.\nThe right foot was raised with a $\\SI{5}{\\centi\\meter}$ sole on the shoe to further minimize accidental loading of the foot.\n%---------------------------------------------------------\n\\subsubsection{MR imaging} \n%---------------------------------------------------------\nSubjects were positioned supine in a $\\SI{3}{\\tesla}$ whole-body scanner (GE Medical Systems, WI, USA) and only the limb selected for suspension was scanned (pre- and post-suspension).\nA custom-built receive-only phased array coil with a large FOV was used to image approximately $\\SI{30}{\\centi\\meter}$ of the lower leg without moving the subject or coil; the intent was to cover the medial gastrocnemius muscle from its origin to insertion in two acquisitions without having to reposition the subject in the coil.\nThe coil moved relative to the magnet between acquisitions, the subject did not move with respect to the coil.\nOne anatomical slice was common between the two sets of acquisitions and the two sets were reoriented by a transformation obtained from the rigid alignment of the slice common to both sets.\nThe subject's leg was fully extended while the foot was maintained in a fixed position at $\\approx \\SI{15}{\\degree}$ in plantarflexion; the foot rested on an adjustable wedge to maintain the angle constant for the scan duration. This foot position was used to ensure that there was no passive tension in the lower leg muscles.\n%-new paragraph-%\n\n%-new paragraph-%\nThe MRI pulse sequence used in the image acquisition was a fat suppressed single shot EPI spin-echo sequence with monopolar diffusion gradients (diffusion gradient duration, $\\delta = \\SI{12}{\\milli\\second}$, and diffusion time $\\Delta = \\SI{20}{\\milli\\second}$). \nSpectral-spatial water selective excitation was used to suppress fat.\nThe total number of slices (acquired in two multi-slice 2D sets) required to cover the calf muscles ranged from 32 to 40 slices.\n$B_0$ shimming in the selected region of interest was performed with vendor supplied automated second order shims.\nThirty-two non-collinear gradient directions with a \\mbox{\\textit{b-}value} of $\\SI{400}{\\second \\per \\milli\\meter^2}$ were used to map the direction dependent diffusion.\nImaging parameters: echo time (TE) $\\SI{52.7}{\\milli\\second}$, repetition time (TR) $\\SI{7000}{\\milli\\second}$ ms with 4 signal averages, field of view (FOV) $240 \\times 240 \\; \\SI{}{\\milli\\meter^2}$, slice thickness $\\SI{5}{\\milli\\meter}$, no gap and acquisition matrix $80 \\times 80$; no parallel imaging was employed. The $80 \\times 80$ matrix was reconstructed to $128 \\times 128$ matrix by partial fourier with homodyne reconstruction.\nThe homodyne algorithm pre-weights the \\mbox{\\textit{k-}space} data so that when the real part of the image is extracted, it corresponds to uniform weighting in \\mbox{\\textit{k-}space}~\\cite{RND20}.\nThe $128 \\times 128$ matrix is then extrapolated to a $256 \\times 256$ matrix yielding a voxel resolution of $\\SI{0.94}{\\milli\\meter} \\times \\SI{0.94}{\\milli\\meter} \\times \\SI{5.00}{\\milli\\meter}$.\nIn addition to the diffusion weighted images, a morphological volume was acquired with a fat saturated fast gradient echo (FGRE) sequence for two echo times with the following parameters: $\\mathrm{TE_1}/\\mathrm{TE_2}$/TR: $\\SI{3.2}{\\milli\\second}/\\SI{5.6}{\\milli\\second}/\\SI{350}{\\milli\\second}$ and a flip angle (FA) of $\\SI{20}{\\degree}$; all geometric parameters were the same as in the DTI scans.\nThe acquired morphological volume was used to generate phase maps to correct $B_0$ distortions in the echo planar images.\nThe total scan time including the morphological images for each session was 17 minutes. \n%---------------------------------------------------------\n\\subsubsection{Force measurements}\n%---------------------------------------------------------\nIsometric MVIC of the plantarflexor muscles was determined for each subject prior to MR imaging. For this purpose, the ankle was fixed in a neutral position ($\\SI{90}{\\degree}$ angle between the axis of the foot and the shank).\nTo estimate the maximum force acting along the Triceps Surae tendon, the force recorded by the force transducer was divided by the Achilles tendon moment arm corresponding to $\\SI{90}{\\degree}$ angle between the axis of the foot and the shank detailed earlier~\\cite{RNS20}.\nIn brief, a sagittal MR image of the lower leg and foot was used to identify the joint (ankle) center of rotation as well as Achilles tendon line of action (the latter marked as a straight line along the center of the tendon). \nThe perpendicular distance of the joint center to the line of action was measured as the Achilles tendon moment arm~\\cite{RNS20}.\nThe measured muscle force is that generated by the gastrocnemius (lateral and medial) and the soleus muscles.\n%---------------------------------------------------------\n\\subsubsection{Muscle volume measurements}\n%---------------------------------------------------------\nThe manual contouring was performed using parametric Bezier curves every fifth slice using OsiriX~\\cite{RND22}.\nAutomated interpolation was performed for the intervening slices; all automated contours were examined and edited if needed.\n%---------------------------------------------------------\n\\subsubsection{Image preprocessing and DTI indices computation}\n%---------------------------------------------------------\nFigure~\\ref{fig: DTI-flowchart} is the flowchart of the sequence of image processing steps~\\cite{DTI}.\n%*********************************************************\n\\begin{figure}[!h]\n\\vspace{+0.2cm}\n\\centering\n\\includegraphics[width=0.9\\textwidth]{Figures/DTI_flowchart.pdf}\n\\caption[The image processing flowchart showing the sequence of steps leading to the extraction of the diffusion tensor indices]{The image processing flowchart showing the sequence of steps leading to the extraction of the diffusion tensor indices.}\n\\label{fig: DTI-flowchart}\n\\end{figure}\n%*********************************************************\nAll diffusion weighted image volumes were registered to the baseline ($b=0$) image to correct for eddy currents and motion related artifacts using the \\textit{eddy} algorithm from FSL~\\cite{RND23}. \nThe phase images of the dual echo (FGRE) volumes were used to correct for $B_0$ field inhomogeneities using the \\textit{fugue} algorithm from FSL~\\cite{RND23}.\nDiffusion weighted images were then denoised using a Joint Rician Linear Minimum Mean Square Error (LMMSE) estimator~\\cite{RND24}. \nThe noise in magnitude MR images is best modeled by a Rician distribution and the LMMSE estimator has been shown to out-perform other Rician denoising techniques~\\cite{RND25}.\nThe tensor was calculated from the distortion corrected and denoised data using a Gaussian model of diffusion.\nThe tensor was then diagonalized to yield the eigenvalues followed by the calculation of the fractional anisotropy (FA), apparent diffusion coefficient (ADC) and coefficient of planarity (CP) maps. \nThe contour of the MG traced in the FGRE volume slices was transferred to the DTI indices map.\nAverage values of the DTI indices were obtained from a $5 \\times 5$ region of interest (ROI) automatically placed at the centroid of the MG mask at each anatomical slice (in most subjects, 40 axial slices were required to cover the MG); this placement ensured that the ROI was not at the edges which would bias estimates due to partial volume effects. \nA manual check was also made to ensure that the ROI was not in the region of a blood vessel, fascia or contained artifacts; such ROIs were manually adjusted. \nThough the ROI was small at 25 pixels~/~slice, the total number of pixels across all slices was $\\approx 900 (25 \\times 36)$. \n%---------------------------------------------------------\n\\subsubsection{Simulation}\n%---------------------------------------------------------\nThe model used here closely follows that proposed originally by Karampinos~et~al.~\\cite{RND12}. \nSimulations were carried out by varying the fit parameters ($\\alpha$, $d$, $\\tau_{\\mathrm{in}}$, $\\nu_{\\mathrm{in}}$, $\\nu_{\\mathrm{col}}$) to compute DTI eigenvalues. \nThe five parameter-space was searched to find the optimal combination of the five parameters that minimized the normalized root mean square difference (NRMSE) between the eigenvalues computed from the simulation and those determined from experiments (Equation~\\ref{eq: KargerRMSE}).\n%.........................................................\n\\begin{equation}\\label{eq: KargerRMSE}\n\\mathrm{NRMSE} = \\sqrt{\\dfrac{\\sum\\limits_{i=1}^3 \\left( \\lambda_{i,\\mathrm{expr}}-\\lambda_{i, \\mathrm{sim}} \\right)^2}{\\sum\\limits_{i=1}^3 \\lambda_{i,\\mathrm{expr}}^2}}\n\\end{equation}\n%.........................................................\nwhere $\\lambda_{i,\\mathrm{expr}}$ is the experimentally determined eigenvalues while $\\lambda_{i,\\mathrm{sim}}$ is the eigenvalue from the model simulation. \nSince there are five variables that are fit to the model, the search space was limited to physiologically relevant ranges in order to prevent the search from minimizing at non-physiological values, these ranges were taken from~\\cite{RND12}. \nThe simulations were carried out with the values for intra-cellular diffusion coefficient ($D_{\\mathrm{in}}$), extracellular matrix diffusion coefficient ($D_{\\mathrm{ex}}$), intra-cellular $\\mathrm{T_2}$ ($\\mathrm{T}_{\\mathrm{2,in}}$), and extra-cellular $\\mathrm{T_2}$ ($\\mathrm{T}_{\\mathrm{2,ex}}$) taken from the literature~\\cite{RND12, RND26}.\nIt should be noted here that Karampinos~et~al. fitted $D_{\\mathrm{in}}$ and $D_{\\mathrm{ex}}$ to the diffusion model, but these variables were kept fixed in the current paper at the values obtained for young normal subjects in the former paper~\\cite{RND12}. \nThis was done to limit the number of model variables in order to increase the robustness of the fit.\nFurther, as $D_{\\mathrm{in}}$ is determined by the various intracellular membrane and protein structure; it is not anticipated to change with atrophy. \n$D_{\\mathrm{ex}}$, the diffusion in the extracellular compartment is determined by the collagen fraction in the endomysium and the diffusion coefficient of water.\nBased on the findings from imaging that \\% connective tissue fraction does not change with atrophy (unreported study on the same subjects), it is also anticipated that \\% collagen fraction in the endomysium may not change significantly with atrophy. \nThe experimental values of the eigenvalues ($\\lambda_{i,\\mathrm{expr}}$) used in obtaining the optimal solution from the simulation were the mean values of all the subjects for pre- and post-suspension. \nThe optimization was performed in Wolfram Research, Inc., Mathematica, (Version 11.3, Champaign, IL). \nThe conjugate gradient search algorithm was used to find the parameters that minimize NRMSE. \nAs this method only guarantees a local minimum, the global minimum was obtained by a search performed over all combinations of the five-parameter space~\\cite{BiComp}; the range and step size of the search space are provided in Table~\\ref{tab: Karger2}.\n%=========================================================\n\\begin{table}[!htb]\n\\vspace{+0.2cm}\n\\caption[Tissue microstructural parameters from bicompartmental diffusion model]{Tissue microstructural parameters from bicompartmental diffusion model.}\n\\label{tab: Karger2}\n\\begin{center}\n\\begin{tabular}{@{}llllll@{}}\n\\toprule[1pt]\\midrule[0.3pt]\n  & & Pre-ULLS & Post-ULLS & Range     & Step size \\\\ \\midrule\n$\\alpha$     & & 0.55     & 0.95      & 0.05 - 0.95 & 0.05      \\\\[6pt]\n$d$ & $[\\SI{}{\\micro\\meter}]$   & 82       & 65        & 50 - 110    & 5         \\\\[6pt]\n$\\tau_{\\mathrm{in}}$ & $\\left[\\SI{}{\\second}\\right]$   & 0.8      & 2.6       & 0.8 - 2.6   & 0.2       \\\\[6pt]\n$\\nu_{\\mathrm{in}}$  & &0.95     & 0.89      & 0.89 - 0.95 & 0.0025    \\\\[6pt]\n$\\nu_{\\mathrm{col}}$ & &0.5      & 0.6       & 0.5 - 0.6   & 0.0025    \\\\ \\midrule[0.3pt]\\toprule[1pt]\n\\end{tabular}\n\\end{center}\n\\vspace{-0.2cm}\n\\end{table}\n%=========================================================\n%---------------------------------------------------------\n\\subsubsection{Statistical analysis} \n%---------------------------------------------------------\nThe outcome variables of the analysis are the diffusion tensor indices ($\\lambda_1$, $\\lambda_2$, $\\lambda_3$, FA and CP). \nThe assumption of normality of data was tested using both the Shapiro-Wilk test and by visual inspection of quantile-quantile plots. \nSince deviations from normality were only minor and no non-parametric alternative to factorial ANOVA exists, differences between pre- and post-ULLS values were assessed using two-way repeated measures ANOVAs. \nData are reported as mean $\\pm$ standard deviation. \nFor all tests, the level of significance was set at 0.05. \nThe statistical analyses were carried out using SPSS for Mac OSX (SPSS 23.0, IBM Inc, Armonk, NY).\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\\subsection{Bicompartmental Diffusion Model with Exchange}\n\\label{subsec: bicompart}\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nThe multi-compartment diffusion model used here is originally proposed by K\\\"arger~\\cite{KARGER19881} and extended by Karampinos~\\cite{RND12}. \nMuscle fibers are approximated with infinite cylinders of an elliptical cross-section and ratio between major axis $\\alpha = d_s/d_l$ as shown in Figure~\\ref{fig: KargerModel}. \n%*********************************************************\n\\begin{figure}[!htb]\n\\vspace{+0.2cm}\n\\centering\n\\includegraphics[scale=.3]{Figures/FibersModel.pdf}\n\\caption[Schematic of muscle fibers and endomaysium matrix]{Schematic of muscle fibers and endomaysium matrix.}\n\\label{fig: KargerModel}\n\\end{figure}\n%*********************************************************\nMuscle fiber diameter $d$ defined as the mean of the short axis and long axis lengths.\nThe model allows exchange between two compartments: the intracellular space (inside the muscle fiber) and the extracellular space (collagenous intramuscular connective tissue consisting of endomysium and perimysium).\nThe volumes of the two compartments are denoted as $\\nu_{\\mathrm{in}}$ (intramyocellular volume fraction) and $\\nu_{\\mathrm{ex}}$ (extracellular volume fraction), with $\\nu_{\\mathrm{in}} + \\nu_{\\mathrm{ex}} = 1$. \nFurther, the collagen fraction in the extracellular matrix is represented by $\\nu_{\\mathrm{coll}}$. \nThe last parameter of the fit is the intracellular residence time $(\\tau_{\\mathrm{in}})$, which is related to the permeability ($\\kappa$) of the sarcolemma (i.e. the cell membrane of muscle fibers) through the relationship: $\\tau_{\\mathrm{in}} = d/2\\kappa$. \nTotal MR signal $S$ which is a function of time $t$ and \\mbox{\\textit{b-}value} is a sum of signals from intracellular and extracellular compartments:\n%.........................................................\n\\begin{equation}\\label{eq: Karger Signal}\nS(t,b) = S_{\\mathrm{in}}(t,b)+S_{\\mathrm{ex}}(t,b)\n\\end{equation}\n%.........................................................\nTime evolution of the signals $S_\\mathrm{in}$ and $S_\\mathrm{ex}$ can be found from the system of ordinary differential equations:\n%.........................................................\n\\begin{equation}\\label{eq: Karger ODE}\n{\\setstretch{1.0}\n\\begin{cases}\n\\dfrac{dS_{\\mathrm{in}}}{dt}=-q^2D^{\\mathrm{app}}_{\\mathrm{in}}S_{\\mathrm{in}}-\\dfrac{1}{\\tau_{\\mathrm{in}}}S_{\\mathrm{in}}+\\dfrac{1}{\\tau_{\\mathrm{ex}}}S_{\\mathrm{ex}}-\\dfrac{1}{\\mathrm{T}_{2,\\mathrm{in}}}S_{\\mathrm{in}}\\\\[20pt]\n\\dfrac{dS_{\\mathrm{ex}}}{dt}=-q^2D^{\\mathrm{app}}_{\\mathrm{ex}}S_{\\mathrm{ex}}-\\dfrac{1}{\\tau_{\\mathrm{ex}}}S_{\\mathrm{ex}}+\\dfrac{1}{\\tau_{\\mathrm{in}}}S_{\\mathrm{in}}-\\dfrac{1}{\\mathrm{T}_{2,\\mathrm{ex}}}S_{\\mathrm{ex}}\n\\end{cases}\n}\n\\end{equation}\n%.........................................................\nwhere $q$ is a product of gyromagnetic ratio $\\gamma$, gradient $G$ of duration $\\delta$. \nUsing $q$ the \\mbox{\\textit{b-}value} can be expressed as $b=q^2(\\Delta-\\delta/3)$, $\\Delta$ is time separation between diffusion gradients. \nWith initial conditions:\n%.........................................................\n\\begin{equation}\\label{eq: Karger IC}\n{\\setstretch{1.0}\n\\begin{aligned}\n& S_{\\mathrm{in}}(0,b)=\\nu_{\\mathrm{in}}\\\\[10pt]\n& S_{\\mathrm{ex}}(0,b)=\\nu_{\\mathrm{ex}}\\\\[10pt]\n& \\dfrac{S_{\\mathrm{in}}(0,b)}{\\tau_{\\mathrm{in}}}=\\dfrac{S_{\\mathrm{ex}}(0,b)}{\\tau_{\\mathrm{ex}}}\n\\end{aligned}\n}\n\\end{equation}\n%.........................................................\nsystem of Equations~\\ref{eq: Karger ODE} has the solution:\n%.........................................................\n\\begin{equation}\\label{eq: Karger Solution}\nS(t,b)=\\nu'_{\\mathrm{in}} e^{-q^2tD'_{\\mathrm{in}}}+\\nu'_{\\mathrm{ex}} e^{-q^2tD'_{\\mathrm{ex}}}\n\\end{equation}\n%.........................................................\nwith modified volumes and diffusion coefficients:\n%.........................................................\n\\begin{equation}\\label{eq: Karger v modified}\n\\begin{array}{l}\n\\nu'_{\\mathrm{ex}} = \\dfrac{1}{D'_{\\mathrm{ex}}-D'_{\\mathrm{in}}} \\left[\\nu_{\\mathrm{in}}\\left( D^{\\mathrm{app}}_{\\mathrm{in}} + \\dfrac{1}{q^2 \\mathrm{T}_{2,\\mathrm{in}}} \\right) + \\nu_{\\mathrm{in}}\\left( D^{\\mathrm{app}}_{\\mathrm{in}} + \\dfrac{1}{q^2 \\mathrm{T}_{2,\\mathrm{in}}} \\right) - D'_{\\mathrm{in}} \\right]\\\\[10pt]\n\\nu'_{\\mathrm{in}} = 1 - \\nu'_{\\mathrm{ex}}\n\\end{array}\n\\end{equation}\n%.........................................................\n%.........................................................\n\\begin{equation}\\label{eq: Karger ADC}\n\\begin{split}\nD'_\\mathrm{in,ex} &= \\frac{1}{2}\\left( D^{\\mathrm{app}}_\\mathrm{in} + D^{\\mathrm{app}}_\\mathrm{ex} + \\frac{1}{q^2}\\left(\\frac{1}{\\tau_{\\mathrm{in}}} + \\frac{1}{\\tau_{\\mathrm{ex}}} + \\frac{1}{\\mathrm{T}_{2,\\mathrm{in}}} + \\frac{1}{\\mathrm{T}_{2,\\mathrm{ex}}} \\right) \\right) \\mp \\\\ &\\mp \\frac{1}{2}\\sqrt{\\left( D^{\\mathrm{app}}_\\mathrm{in} - D^{\\mathrm{app}}_\\mathrm{ex} + \\frac{1}{q^2}\\left(\\frac{1}{\\tau_{\\mathrm{in}}} - \\frac{1}{\\tau_{\\mathrm{ex}}} - \\frac{1}{\\mathrm{T}_{2,\\mathrm{in}}} + \\frac{1}{\\mathrm{T}_{2,\\mathrm{ex}}} \\right) \\right) + \\frac{4}{q^4\\tau_{\\mathrm{in}}\\tau_{\\mathrm{ex}}}}\\\\\n\\end{split}\n\\end{equation}\n%.........................................................\n\\\\\nIntracellular apparent diffusion coefficient $D^{\\mathrm{app}}_\\mathrm{in}$ is found by investigating signal attenuation due to diffusion inside two impermeable walls separated by distance $d$ with gradient $G$ applied perpendicular to these walls. \nSignal $S$ defined as ratio between $\\bar{M}$ and $M_{0}$ expressed through conditional probability $P(z_2|z_1, \\Delta)$:\n%.........................................................\n\\begin{equation}\\label{eq: Karger AppEx}\nS (t,b)= \\dfrac{1}{d}\\iint dz_1 dz_2  \\cos \\left[ \\gamma \\delta G (z_2-z_1)\\right]P(z_2|z_1, \\Delta)\n\\end{equation}\n%.........................................................\nfrom Fick's law (Equation~\\ref{eq:probability_diffusion}) with initial conditions imposed:\n%.........................................................\n\\begin{equation}\\label{eq: probability initial conditions}\n\\begin{array}{c}\n\tP\\left( z,0\\right) = \\delta\\left( z-z_1\\right)\\\\[10pt]\n\t\\left. \\dfrac{\\partial P}{\\partial z}\\right\\vert_{z=\\pm d/2} = 0\n\\end{array}\n\\end{equation}\n%.........................................................\nusing Equation~\\ref{eq: Diffusion from bvalue} intracellular apparent diffusion coefficient is expressed:\n%.........................................................\n\\begin{equation}\\label{eq: Karger AppEx}\n\\begin{split}\n\tD^{\\mathrm{app}}_{\\mathrm{in}} (D_{\\mathrm{in}},\\Delta, b, d) &= -\\dfrac{1}{b} \\ln  \\left[ \\frac{2 - 2 \\cos(qd)}{(qd)^2} + \\vphantom{ \\exp \\left( - \\frac{n^2 \\pi^2 D_{\\mathrm{in}} \\Delta}{d^2}\\right)\\frac{1-(-1)^n \\cos{(qd)}}{\\left( \\left(qd\\right)^2 - \\left( n \\pi\\right)^2\\right)^2}} \\right. \\\\\n                   &+ \\left. 4(qd)^2 \\sum^{\\infty}_{n=1} \\exp \\left( - \\frac{n^2 \\pi^2 D_{\\mathrm{in}} \\Delta}{d^2}\\right)\\frac{1-(-1)^n \\cos{(qd)}}{\\left( \\left(qd\\right)^2 - \\left( n \\pi\\right)^2\\right)^2} \\right]\n\\end{split}\n\\end{equation}\n%.........................................................\nExtracellular apparent diffusion coefficient as a function of water diffusion coefficient $(D_{\\mathrm{w}})$, orientation parameter $(\\zeta)$, extracellular $(\\nu_{\\mathrm{ex}})$ and collagen $(\\nu_{\\mathrm{col}})$ volume fractions was defined in~\\cite{RND12}:\n%.........................................................\n\\begin{equation}\\label{eq: Karger AppEx}\nD^{\\mathrm{app}}_{\\mathrm{ex}}=D_{\\mathrm{w}}(1-\\nu_{\\mathrm{col}})^{2/3}\\nu_{\\mathrm{ex}}^\\zeta\n\\end{equation}\n%.........................................................\nwhere $\\zeta$ can take three values: 0 when considering diffusion parallel to the longitudinal axes of cylinder, $\\alpha$ when parallel to the major axis in the cylinder cross-section and $1/\\alpha$ when parallel to the minor axis.\nFinally the diffusion eigenvalue from the model can then be calculated as following:\n%.........................................................\n\\begin{equation}\\label{eq: Karger AppEx}\n\\lambda_i = -\\frac{1}{b} \\mathrm{ln}\\left( \\frac{S_i(q,\\Delta)}{S_i(q,0)}\\right)\n\\end{equation}\n%.........................................................\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\\subsection{Results}\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nMuscle force decreased significantly post-suspension (change of $-32.6 \\pm 24.7\\%$; $p=0.013$); this is the average over the seven subjects. \nThe average change (over all subjects) in the volume of the MG, LG, and SOL muscles after the 4-week suspension was $-9.6 \\pm 4.5\\%$ ($p=0.001$), $-11.1 \\pm 7.4\\%$ ($p=0.008$), and $-7.4 \\pm 5.9\\%$ ($p=0.006$) respectively (significance of pre- and post- suspension volume changes indicated for each muscle).\nWhile the DTI measurements~/~modeling are focused on the MG, the measured isometric plantarflexion force is generated by the Triceps Surae muscles and thus the volume change of all three muscles are included here. \nTypical maps of the eigenvalues, ADC, FA, and CP at one anatomical location of the lower leg in one subject pre- and post-suspension are shown in Figure~\\ref{fig: KargerEV}. \nThe two left columns are pre-suspension and the two right columns are corresponding images from the same subjects post-suspension; \nan anatomical level close top row shows the maps pre-suspension and the bottom the maps at a corresponding anatomic location post-suspension. \nThe maps are (top to bottom, column 1 and 3): ADC, $\\lambda_1, \\lambda_2, \\lambda_3$; (top to bottom, column 2 and 4): FA, CP, lead eigenvector, mask of MG muscle with ROI superposed on the eigenvalue weighted eigenvector color map. \nEigenvalues are in units of $\\SI{}{\\micro\\meter^2 / \\milli\\second}$, the FA and CP are unitless. $\\mathrm{ev}_1$ is the colormap of the eigenvector corresponding to the lead eigenvalue, $\\lambda_1$. \nThe colormap is the projection of the primary eigenvector following the convention: Left $\\rightarrow$ Right ($x$-projection): red, Anterior $\\rightarrow$ Posterior ($y$-projection): green, Superior $\\rightarrow$ Inferior ($z$-projection): blue. \nThe predominantly blue hue confirms the superior-inferior direction of the muscle fiber. \nThe same anatomic location is shown pre- and post-suspension; \nthe atrophy of the muscles is clearly seen comparing the pre- to the post-suspension images. \nThe effectiveness of the fat suppression can be seen by the absence of fat artifacts (shifted subcutaneous fat) in the image.\n%*********************************************************\n\\begin{figure}[!htb]\n\\vspace{+0.2cm}\n\\centering\n\\includegraphics[width=\\textwidth]{Figures/DTI_2compart.pdf}\n\\caption[The parametric maps extracted from the diffusion tensor]{The parametric maps extracted from the diffusion tensor.}\n\\label{fig: KargerEV}\n\\end{figure}\n%*********************************************************\nVisual assessment of the parametric DTI maps confirms the image quality (SNR) and lack of image artifacts (good fat suppression as well as small image distortions).\n%-new paragraph-%\n\n%-new paragraph-%\nThe DTI indices evaluated pre- and post-suspension in the medial gastrocnemius are summarized in Table~\\ref{tab: Karger1};\nthe values listed here are the averages for all subjects. Three eigenvalues and apparent diffusion coefficient  decreased significantly post-suspension ($\\lambda_1$:  $p = 0.025$, $\\lambda_2$: $p = 0.035$, $\\lambda_3$: $p = 0.049$, ADC: $p = 0.029$) while FA increased and CP decreased with suspension, although the latter indices two did not show significant changes ($p = 0.239$ for FA and $p=0.763$ for CP). \nThe maximum decrease was in the secondary eigenvalue that in turn resulted in a smaller difference between the secondary and tertiary eigenvalue post suspension (reflected also as a decrease in CP).\n%=========================================================\n\\begin{table}[!htb]\n\\vspace{+0.2cm}\n\\caption[Diffusion tensor indices pre- and post-suspension]{Diffusion tensor indices pre- and post-Unilateral Limb Suspension (ULLS).}\n\\label{tab: Karger1}\n\\begin{center}\n\\begin{threeparttable}\n\\begin{tabular}{@{}llll@{}}\n\\toprule[1pt]\\midrule[0.3pt]\n  &   & Pre-ULLS    & Post-ULLS   \\\\ \\midrule\n$\\lambda_1$\\tnote{$\\dagger$} & $\\left[\\SI{}{\\micro\\meter^2 / \\milli\\second}\\right]$ & 2.06 $\\pm$ 0.11 & 1.91 $\\pm$ 0.15 \\\\[6pt]\n$\\lambda_2$\\tnote{$\\dagger$} & $\\left[\\SI{}{\\micro\\meter^2 / \\milli\\second}\\right]$ & 1.44 $\\pm$ 0.08 & 1.31 $\\pm$ 0.11 \\\\[6pt]\n$\\lambda_3$\\tnote{$\\dagger$}& $\\left[\\SI{}{\\micro\\meter^2 / \\milli\\second}\\right]$ & 1.30 $\\pm$ 0.11 & 1.17 $\\pm$ 0.10 \\\\[6pt]\nADC\\tnote{$\\dagger$}   \t&\t& 1.60 $\\pm$ 0.07 & 1.47 $\\pm$ 0.11 \\\\[6pt]\nFA   \t\t\t\t\t&\t& 0.25 $\\pm$ 0.04 & 0.27 $\\pm$ 0.04 \\\\ \\midrule[0.3pt]\\bottomrule[1pt]\n\\end{tabular}\n\\begin{tablenotes}[flushleft]\\footnotesize\n\\item[$\\dagger$] significant difference between pre- and post-suspension\n\\end{tablenotes}\n\\end{threeparttable}\n\\end{center}\n\\vspace{-0.2cm}\n\\end{table}\n%=========================================================\nIn addition to the average over all subjects listed in Table~\\ref{tab: Karger1}, the DTI indices (eigenvalues, ADC, FA and CP) pre- and post-suspension are also plotted for each subject individually in Figure~\\ref{fig: KargerPlots}. \nThis was done to confirm the consistency of DTI changes with suspension across the seven subjects and hence the validity of the data.\nPre- and post- values for each subject are connected for ease of visualization of the changes in the indices with suspension. \nFor most of the DTI indices the majority of subjects show the same direction of changes: e.g., six out of seven subjects show a decrease in $\\lambda_1, \\lambda_2$, ADC, and an increase in FA, while five out of seven subjects show a decrease in $\\lambda_3$ and in CP.\n%*********************************************************\n\\begin{figure}[!htb]\n\\vspace{+0.2cm}\n\\centering\n\\includegraphics[width=\\textwidth]{Figures/KargerPlots.pdf}\n\\caption[Individual plots of the DTI indices pre- and post-suspension]{Individual plots of the DTI indices pre- and post-suspension.}\n\\label{fig: KargerPlots}\n\\end{figure}\n%*********************************************************\nTable~\\ref{tab: Karger2} lists the model parameters obtained by the search of the parameter space for the values of ($\\alpha$, $d$, $\\tau_{\\mathrm{in}}$, $\\nu_{\\mathrm{in}}$, $\\nu_{\\mathrm{col}}$) that yielded the lowest value of the error index~\\cite{RND12}. \nThe increase in the ellipticity index with disuse indicates that the fiber becomes more circular, while the decrease in muscle fiber diameter is as anticipated with atrophy. \n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\\subsection{Discussion}\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nWhile it is known that the quadriceps muscles show greater atrophy than the medial gastrocnemius in aging and are a better correlate to physical function~\\cite{RND27}, the motivation for the focus on the MG in the current study is based on the ease of performing functional MRI studies on the MG for correlation to structural MRI studies~\\cite{RNSS4, RNCS4, Malis:2018fr, RNS16}. \nFurther, calf circumference (and by extension calf muscle mass as well) has been shown in a large-scale study to provide information on muscle related disability and physical function~\\cite{RND30}.\n%-new paragraph-%\n\n%-new paragraph-%\nMuscle force loss was approximately greater by a factor of 3 compared to reduction in muscle mass. \nPrior work on gravitational unloading effects on fast and slow rat hind-limb muscles data indicate that predominantly slow muscles are more responsive to unloading than predominantly fast muscles~\\cite{RND31}.\nSince the soleus has a higher proportion of slow twitch muscles compared to the gastrocnemius muscles, it would be anticipated that the soleus would show the highest atrophy (volume decrease). \nHowever, comparing \\% volume changes in the three muscles in the current study, larger changes were seen in the gastrocnemius muscles.  \nIt should be noted though that the soleus muscle had the highest changes in terms of absolute volume changes comparing pre- and post-suspension muscles.\n%-new paragraph-%\n\n%-new paragraph-%\nComparing the values of DTI indices in the current study with that reported by Karampinos~et~al.~\\cite{RND12}, there are considerable differences in FA and in CP between the two studies.\nThe reasons for these differences may arise from differences in the measurement methodology.\nA simulated echo EPI diffusion weighted sequence was used by Karampinos~et~al.~\\cite{RND12} in contrast to the current study that uses a spin echo EPI diffusion weighted sequence.\nIt has been shown earlier that the simulated echo is better for diffusion imaging of muscle than a spin echo~\\cite{RND32}. \nHowever, the sequence used in~\\cite{RND12} has a TE of $\\SI{52}{\\milli\\second}$~\\cite{RND12} which is really long for a stimulated echo that has half the signal of a spin echo with a similar TE.\nThis raises the issue that the SNR of the sequence used in~\\cite{RND12} may not have been high and low SNR has been shown to bias the estimation of DTI indices~\\cite{RND33}.\nFurther, values reported for the eigenvalues and FA for the MG are in good agreement between the current study with another recent rigorous study that evaluated DTI indices for voxels with SNR $> 20$~\\cite{RND33}.\n%-new paragraph-%\n\n%-new paragraph-%\nPrevious studies on denervation induced atrophy on rodent models showed a reduction in $\\lambda_2$ and $\\lambda_3$, an increase in fractional anisotropy while $\\lambda_1$ was unchanged~\\cite{RND8}. \nIt is well accepted that DTI measurements in muscle reflect water diffusion in the intracellular space, thus the authors of this paper attributed the decrease in the secondary and tertiary eigenvalues to a decrease in the diameter of myofibers (i.e., myofiber atrophy). \nIn another study, the triceps surae was assessed with DTI after Achilles tenotomy in rats~\\cite{RND9}. \nBoth muscle atrophy as well as a decrease in plantarflexion force was seen post-tenotomy. \nSignificant decreases in $\\lambda_1$, $\\lambda_2$, and $\\lambda_3$ and an increase in FA were seen between the control and treatment sides at four weeks post-tenotomy~\\cite{RND9}. \nThis is in contrast to denervation induced atrophy where no changes were seen in $\\lambda_1$.\nIn the present study, decreases in all three eigenvalues were significant. \nThe eigenvector corresponding to the lead eigenvalue is in the direction of the muscle fiber and thus $\\lambda_1$ represents diffusion along the long axis of the muscle fiber. \nSince the muscle fiber is orders of magnitude greater than the diffusion distances, changes in muscle fiber length are not expected to cause changes in $\\lambda_1$. \nFurther, changes in fiber cross-section diameters should also not affect $\\lambda_1$ as the diffusion direction is along the long axis of the muscle fiber. \nThus, the decrease in $\\lambda_1$ is difficult to explain. \nPossibly, the reduced diffusivity along the fibers' long axis is related to a loss in myosin content~\\cite{RNS10} and reduction in the packing density of actin filament proteins~\\cite{RND35} that result in structurally weakened sarcomeres. \nWhile the underlying physiological mechanisms are unclear, presented observations of a decrease in $\\lambda_1$ is similar to that seen in the tenotomy induced atrophy~\\cite{RND9}.\nThe decrease in $\\lambda_2$ and $\\lambda_3$ can potentially be related to a change in muscle fiber diameter and is similar to that seen in denervation induced atrophy~\\cite{RND8}. \nIt should also be noted that the largest decrease was seen in $\\lambda_2$. \nIf the secondary and tertiary eigenvalues reflect the long axis and short axis diameters respectively of the muscle fiber cross-section, then the muscle fiber is more circular post-suspension. \n%-new paragraph-%\n\n%-new paragraph-%\nIn this context, Karampinos~et~al.~\\cite{RND12} advanced the hypothesis that the elliptic fiber cross-section arises from a response to the mechanical stimulus as the fiber is strained more along one direction in the muscle fiber cross-section than in the orthogonal direction. \nWhen the mechanical stimulus is reduced or removed as with ULLS induced disuse, the preferential deformation along one axis in the fiber cross-section is removed.\nThis may well result in the fiber cross-section becoming more circular in the absence of a mechanical stimulus.\nAs opposed to the progressive circularity accompanying disuse-atrophy~\\cite{RND36},\nADC decreased significantly with suspension and may potentially arise from a combination of a decrease in inherent intracellular diffusivity (decrease in all three eigenvalues) and a decrease in muscle fiber size (decrease in secondary and tertiary eigenvalues).\nIn the context of a reduction of a mechanical stimulus with suspension, the discussion of findings from related studies using strain~/~strain rate tensor imaging is worthwhile~\\cite{RNSS4, RNCS4, Malis:2018fr, RNS16}. \nStrain and strain rate tensor imaging evaluate tissue deformation and the tensor provides information of the strain (or strain rate) in three orthogonal directions. \nThe primary, secondary, and tertiary eigenvectors of the strain rate tensor correspond approximately to the muscle fiber direction and to two orthogonal directions in the muscle fiber cross-section, respectively. \nWhen the muscle fiber contracts, a negative strain will be seen along the muscle fiber direction and accompanying this, a positive strain from radial expansion will be seen in the fiber cross-section.\nHowever, this positive strain is not symmetric in the fiber cross-section, with much larger expansion along one direction than the orthogonal direction; this asymmetry has been reported in a number of studies~\\cite{Malis:2018fr, RNS16, RNS31}.\n%-new paragraph-%\n\n%-new paragraph-%\nA recent study on strain rate tensor imaging after unilateral limb suspension reported that the fiber cross-section strain rate asymmetry decreased post-suspension~\\cite{Malis:2018fr}.\nThis decrease in strain rate asymmetry may also be tied to the structural response to the lack of mechanical stimulus.\nThis potentially may imply that the long axis of the elliptical cross-section (proportional to the secondary eigenvalue of the diffusion tensor) is a consequence of the external mechanical stimulus since the radial expansion is preferentially along this direction resulting in an elongation of the fiber cross-section in one direction. Once this stimulus is removed (as in limb suspension) the elongated axes is no longer preferentially stretched, and may potentially become less elliptical (more circular).\nThis is reflected in a lower CP value post-suspension. \nAnother potential explanation for the observed structural changes may be the altered muscle fiber-extracellular matrix interactions from limb suspension~\\cite{RNSS4, RNCS4}. \n%-new paragraph-%\n\n%-new paragraph-%\nThe values of $\\alpha$ reported in the literature for the vastus lateralis muscle are in the range of $0.4$ to $0.68$~\\cite{RND38, RND39}; the current value of $0.55$ for MG ellipticity in the pre-suspension case appears to be reasonable~\\cite{RND38, RND39}.\nKarampinos~et~al. report the value of $\\alpha$ from the fit to the diffusion model with a range of $0.6 - 0.9$; the lower end of this range is close to the current paper.\nThe MG muscle fiber diameter extracted from the model in the current study ($\\SI{82}{\\micro\\meter}$) is in agreement with values reported in the literature~\\cite{RND38} and also with the range ($70 - \\SI{110}{\\micro\\meter}$) determined for the MG in the earlier diffusion modeling study by Karampinos~et~al.~\\cite{RND12}.\nFurther, the focus of the modeling was on determining if meaningful changes in microstructure with suspension can be extracted from the experimentally determined diffusion eigenvalues.\nWith suspension, the ratio of the short axis to long axis muscle fiber length increases which implies that the fiber becomes more circular.\nIn the light of the hypothesis that the elliptical muscle fiber shape arises from the mechanical stimulus, the modeling result of a more circular muscle fiber can be explained by the lack of mechanical stimulus during the 4-week suspension.\nThe diameter of the muscle fiber decreases; this finding is consistent with muscle fiber atrophy. \nIn fitting both pre- and post-suspension DTI data, the search algorithm converged on the upper or lower limits for $\\tau_{\\mathrm{in}}, \\nu_{\\mathrm{in}}$ and $\\nu_{\\mathrm{col}}$.\nThus, the best-fit values for these parameters may be in error. \nThe NRMSE was quite flat with respect to these variables; this was noted for $\\tau_{\\mathrm{in}}$ by Karampinos~et~al.~\\cite{RND12}, and thus, fitting the available DTI data to this model does not allow one to draw conclusions regarding $\\tau_{\\mathrm{in}}, \\nu_{\\mathrm{in}}$ and $\\nu_{\\mathrm{col}}$.\n%-new paragraph-%\n\n%-new paragraph-%\nThere are limitations to the current study: the study population is small but since it is a longitudinal study (pre- and post-ULLS), statistical significance was reached for the changes in the eigenvalues. \nA one-point diffusion measurement is not ideal for extracting tissue parameters through modeling; future work using multi-point DTI data (obtained for example, by varying diffusion time and~/~or \\mbox{\\textit{b-}value}s) will allow more robust modeling to extract accurate values for these microstructural features. \nFurther, multi-point DTI data may allow greater flexibility to extend to single subject rather than limit to cohort modeling as in the current study.\nIt should also be noted that if the fit was performed independently on each subject, it would have allowed testing of the significant changes in the microstructural parameters with limb suspension.\nMeasurements on the contralateral leg would have provided information on the effects of a change in mechanical loading of the unsuspended leg.\nHowever, the current study was part of a larger protocol that besides DTI, included quantification of fat, connective tissue as well as functional measurements and acquiring data on the contralateral leg would have prolonged the scanning time excessively.\nFurther, imaging both legs at the same time was restricted by the customized coil that accommodated only one leg.\nHowever, the customized coil provided higher SNR than vendor coils and allowed the acquisition of the entire lower leg without repositioning the subject.\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\\subsection{Conclusion}\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nThe current study shows that the DTI eigenvalues decrease with suspension induced disuse atrophy. \nExperimentally, the secondary eigenvalue showed the largest decrease with suspension.\nThis could potentially be related to a hypothesis that attributes the elliptical shape of the muscle fiber cross-section as arising from a response to an external load~\\cite{RND12}. \nWhile it is still a conjecture, the asymmetry of deformation in the fiber cross-section may result in one axis becoming longer than the orthogonal one and then unloading conditions can cause this shape asymmetry to be reduced. \nAs the secondary and tertiary eigenvalues are related to the fiber cross-section diameters, this results in larger changes in the secondary eigenvalue as the fiber reduces the most in diameter along this direction with unloading. \nAn exploratory modeling of the DTI data to extract microstructural parameters showed that it is feasible and the disuse atrophy related changes in muscle ellipticity, mean diameter, residence time, intracellular volume and collagen volume extracted from the model were physiologically reasonable.\n%=========================================================\n\\section{Random Permeable Barrier Modeling of Age Induced Changes in the Time Dependent Diffusion Eigenvalues}\n\\label{sec: STEAM RPBM}\n%=========================================================\nMuscle mass loss have been reported in the aging muscle and this is in part, responsible for functional loss. \nHowever, non-invasive monitoring of microstructural changes as in muscle fiber diameter with age has not been reported. \nCommonly employed diffusion weighted acquisition protocols collect data at a single diffusion time. \nThe time dependence of the diffusion tensor eigenvalues can provide additional information to improve quantification of tissue microstructure. \nA diffusion model is required to make inferences about the microstructure from the time dependent eigenvalue data.\nRandom permeability barrier model (RPBM) was recently introduced and applied to retrieve microscopic parameters such as membrane permeability and fiber diameter in human skeletal muscles~\\cite{NovikovRPBM, RND13}. \n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\\subsection{Random Permeable Barrier Model}\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nThe model treats muscle as a volume with randomly oriented infinite flat semipermeable membranes. \nFor each membrane permeability ($\\kappa$) relates the difference in concentrations on both sides of the membrane and the flux through it which provides the following boundary conditions:\n%.........................................................\n\\begin{equation}\\label{eq: RPBM bc}\nD_0\\mathbf{n}\\left.\\frac{\\partial{c}}{\\partial r} \\right\\vert_{\\pm} = \\kappa \\left[ c|_+ - c|_-  \\right]\n\\end{equation}\n%.........................................................\nRPBM model is characterized by three parameters: the free diffusion coefficient ($D_0$), membrane surface to volume ratio ($S/V$) and permeability ($\\kappa$). Time-dependent diffusion coefficient is found by solving the diffusion equation (Equation~\\ref{eq:Fick2}) and then averaging the result over disorder using real-space renormalization group~\\cite{NovikovRPBM}.\n%.........................................................\n\\begin{equation}\\label{eq: RPBM}\nD(t) = \\frac{D_0}{2\\pi t}\\int\\limits^{\\infty}_{-\\infty}\\dfrac{d\\omega}{(-i\\omega)^2}\\frac{e^{-i\\omega t}}{1 + \\zeta +2z_{\\omega}(1-z_{\\omega})  \\left[\\sqrt{1+\\zeta/\\left(1-z_{\\omega}\\right)}-1 \\right] }\n\\end{equation}\n%.........................................................\nwhere $z_\\omega = i \\sqrt{i \\omega t}$ and $\\zeta=(S/V)D_0/4\\kappa$ is an effective volume fraction occupied by membranes.\nThe integral~(\\ref{eq: RPBM bc}) can be integrated numerically as outlined in reference~\\cite{RND13}.\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\\subsection{Materials and Methods}\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nImage acquisition protocol used a custom-built STEAM-EPI DTI sequence (Figure~\\ref{fig: STEAM_GE}) discussed in more details in section~\\ref{sec: EPI}. \nA water selective SPSP RF-pulse was used for fat suppression. \nSix non-collinear gradient directions with a nominal \\mbox{\\textit{b-}value} of $\\SI{400}{\\second \\per\\milli\\meter^2}$ were used to map the direction dependent diffusion at ten values of the diffusion time~$\\Delta$ ($\\SI{20}{\\milli\\second}$ to $\\SI{600}{\\milli\\second}$). \nImaging parameters were; echo time (TE):~$\\SI{32}{\\milli\\second}$, repetition time (TR):~$\\SI{4000}{\\milli\\second}$, signal averages (NEX):~$2$ , acquisition matrix size:~$80~\\times~80$, field of view (FOV):~$200 \\times 200 \\; \\SI{}{\\milli\\meter^2}$, 3 slices of $\\SI{5}{\\milli\\meter}$ thickness. \nDiffusion data were pre-processed for eddy current mis-registration and denoised by applying Joint-Rican LMMSE filter~\\cite{RND24} prior to computing the diffusion tensor and the diffusion eigenvalues. \nThe corrected full \\textit{b-}matrix that accounted for the diffusion, imaging and crusher gradients was calculated as outlined in subsection~\\ref{subsection: STEAM b value}. For the nominal $b = 0$ images, the \\mbox{\\textit{b-}value} varied from $\\SI{1.7}{\\second \\per  \\milli\\meter^2}$ at $\\Delta = \\SI{20}{\\milli\\second}$ to $\\SI{22}{\\second\\per\\milli\\meter^2}$ at $\\Delta = \\SI{600}{\\milli\\second}$ and for the nominal $b = \\SI{400}{\\second\\per\\milli\\meter^2}$ images, the \\mbox{\\textit{b-}value} varied from $\\SI{371}{\\second\\per\\milli\\meter^2}$ at $\\Delta = \\SI{20}{\\milli\\second}$ to $\\SI{547}{\\second\\per\\milli\\meter^2}$ at $\\SI{600}{\\milli\\second}$, emphasizing the need for full \\textit{b-}matrix calculation. \nPrior to human scans a set of images was obtained in a water phantom following the same imaging protocol as described above. \nFractional anisotropy (FA) maps were calculated from the acquired data to validate diffusion tensor calculations at long diffusion times. \nFA maps side by side with the corresponding magnitude images at nominal \\mbox{\\textit{b-}value} for diffusion times 20 and $\\SI{600}{\\milli\\second}$ are show in the Figure~\\ref{fig:STEAM phantom}. \n%*********************************************************\n\\begin{figure}[!htb]\n\\vspace{+0.2cm}\n\\centering\n\\includegraphics[width=0.9\\textwidth]{Figures/STEAM_Phantom.pdf}\n\\caption[Baseline magnitude images and FA colormaps of water phantom acquired with STEAM-EPI DTI image sequence at two diffusion times]{Baseline magnitude images and FA colormaps of water phantom acquired with STEAM-EPI DTI image sequence at two mixing times: 20 and $\\SI{590}{\\milli\\second}$.}\n\\label{fig:STEAM phantom}\n\\end{figure}\n%*********************************************************\n%-new paragraph-%\n\n%-new paragraph-%\nAll human imaging studies were performed after IRB approval on a $\\SI{3}{\\tesla}$ scanner (GE Medical Systems, WI, USA) on seven young ($31 \\pm 8$ years) and six senior ($75 \\pm 5$ years) subjects. \nThe RPBM model was fitted by fixing the free diffusion coefficient $D_0$ at the long diffusion time limit of the primary eigenvalue ($\\lambda_1$) to extract the following parameters: the membrane permeability ($\\kappa$), and the membrane surface to volume ratio ($S/V$). \nThe myofiber size (a) is derived from the surface to volume ratio as: $4V/S$. \nThe RPBM fits were made to the time dependence of the average of $\\lambda_2$, and $\\lambda_3$ ($D_{\\perp}$); the values of $D_{\\perp}$ were the average over the medial gastrocnemius (MG) muscle segmented from all three~slices.\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\\subsection{Results}\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nFigure~\\ref{fig:STEAM_EV} shows parametric $D_\\parallel$ and $D_\\perp$ maps for a young and for a senior subject at two diffusion times.\nExcellent fat suppression was seen in all the STEAM DTI data. \nTypical eigenvalue images ($D_\\parallel \\equiv \\lambda_1$) and ($D_\\perp \\equiv (\\lambda_2 + \\lambda_3)/2$) at two values of mixing time ($20$ and $\\SI{590}{\\milli\\second}$) for a young (left panel) and a senior (right panel) subject. \nThe decrease in SNR with diffusion time can be visualized by the noisier images of the bottom panel. \n%*********************************************************\n\\begin{figure}[!htb]\n\\vspace{+0.2cm}\n\\centering\n\\includegraphics[width=0.9\\textwidth]{Figures/STEAM_EV.pdf}\n\\caption[Diffusion tensor eigenvalues grayscale maps at two values of mixing time  for a young and a senior subject]{Diffusion tensor eigenvalues $D_\\parallel$ and $D_\\perp$ grayscale maps at two values of mixing time (20 and $\\SI{600}{\\milli\\second}$) for a young (left) and a senior (right) subject. The decrease in SNR with TM can be visualized by the noisier images of the bottom panel.}\n\\label{fig:STEAM_EV}\n\\end{figure}\n%*********************************************************\n%=========================================================\n\\begin{table}[!htb]\n\\vspace{+0.2cm}\n\\begin{center}\n\\caption[Diffusion eigenvalues at different mixing times]{Diffusion eigenvalues ($\\lambda_1, \\lambda_2, \\lambda_3$) at different mixing times.}\n\\label{tab:RPBM}\n\\begin{tabular}{@{}ccccccccc@{}}\n\\toprule[1pt]\\midrule[0.3pt]\n\\multirow{2}{*}{$\\mathrm{TM}$ {[}ms{]}} & \\multicolumn{2}{c}{$\\lambda_1 \\quad [\\SI{}{\\micro\\meter^2\\per\\milli\\second}]$}  &  & \\multicolumn{2}{c}{$\\lambda_2 \\quad [\\SI{}{\\micro\\meter^2\\per\\milli\\second}]$}  &  & \\multicolumn{2}{c}{$\\lambda_3 \\quad [\\SI{}{\\micro\\meter^2\\per\\milli\\second}]$}  \\\\ \\cmidrule(lr){2-3} \\cmidrule(lr){5-6} \\cmidrule(lr){8-9} \n                             & Young     & Senior    &  & Young     & Senior    &  & Young     & Senior    \\\\ \\cmidrule(){1-9}\n20                           & 2.8 $\\pm$ 0.2 & 2.8 $\\pm$ 0.2 &  & 2.4 $\\pm$ 0.1 & 2.3 $\\pm$ 0.3 &  & 1.2 $\\pm$ 0.1 & 1.2 $\\pm$ 0.1 \\\\\n30                           & 2.6 $\\pm$ 0.2 & 2.7 $\\pm$ 0.2 &  & 2.0 $\\pm$ 0.1 & 2.1 $\\pm$ 0.3 &  & 1.2 $\\pm$ 0.1 & 1.3 $\\pm$ 0.1 \\\\\n60                           & 2.4 $\\pm$ 0.2 & 2.5 $\\pm$ 0.2 &  & 1.9 $\\pm$ 0.2 & 1.8 $\\pm$ 0.2 &  & 0.8 $\\pm$ 0.1 & 1.0 $\\pm$ 0.2 \\\\\n90                           & 2.4 $\\pm$ 0.3 & 2.4 $\\pm$ 0.2 &  & 1.7 $\\pm$ 0.2 & 1.7 $\\pm$ 0.2 &  & 0.8 $\\pm$ 0.1 & 0.9 $\\pm$ 0.1 \\\\\n190                          & 2.3 $\\pm$ 0.3 & 2.3 $\\pm$ 0.2 &  & 1.7 $\\pm$ 0.1 & 1.7 $\\pm$ 0.2 &  & 0.4 $\\pm$ 0.1 & 0.6 $\\pm$ 0.1 \\\\\n290                          & 2.2 $\\pm$ 0.2 & 2.2 $\\pm$ 0.2 &  & 1.8 $\\pm$ 0.1 & 1.7 $\\pm$ 0.1 &  & 0.2 $\\pm$ 0.1 & 0.4 $\\pm$ 0.1 \\\\\n340                          & 2.2 $\\pm$ 0.1 & 2.2 $\\pm$ 0.2 &  & 1.2 $\\pm$ 0.1 & 1.3 $\\pm$ 0.1 &  & 0.7 $\\pm$ 0.1 & 0.8 $\\pm$ 0.1 \\\\\n390                          & 2.2 $\\pm$ 0.1 & 2.2 $\\pm$ 0.3 &  & 1.3 $\\pm$ 0.2 & 1.3 $\\pm$ 0.2 &  & 0.7 $\\pm$ 0.1 & 0.7 $\\pm$ 0.1 \\\\\n490                          & 2.1 $\\pm$ 0.1 & 2.2 $\\pm$ 0.2 &  & 1.3 $\\pm$ 0.2 & 1.3 $\\pm$ 0.1 &  & 0.6 $\\pm$ 0.1 & 0.7 $\\pm$ 0.1 \\\\\n590                          & 2.1 $\\pm$ 0.2 & 2.2 $\\pm$ 0.2 &  & 1.3 $\\pm$ 0.2 & 1.3 $\\pm$ 0.1 &  & 0.6 $\\pm$ 0.1 & 0.7 $\\pm$ 0.1 \\\\ \\midrule[0.3pt]\\bottomrule[1pt]\n\\end{tabular}\n\\end{center}\n\\vspace{-0.2cm}\n\\end{table}\n%=========================================================\nTable~\\ref{tab:RPBM} summarizes the eigenvalues for the MG muscle in the young and senior cohort at the ten diffusion times. \nLarger changes with diffusion time are seen in $\\lambda_2$, and $\\lambda_3$ (compared~to~$\\lambda_1$). \nThe RPBM fits to the time dependence of $D_\\perp$ for a subject from the young cohort and from the senior cohort are shown for the Figure~\\ref{fig:RPBM fit}. The large variation of $D_\\perp$ with TM is in contrast to the smaller variation of $D_\\parallel$ with TM.\nTable~\\ref{tab:RPBM2} is a list of model derived muscle microstructure parameters; volume fraction decreased with age while diffusion time and residence time in a cell increased with age while other model parameters such as the fiber size and membrane permeability increased with age but did not reach significance.\n%*********************************************************\n\\begin{figure}[!htb]\n\\vspace{+0.2cm}\n\\centering\n\\includegraphics[width=0.9\\textwidth]{Figures/RPBM_fit.pdf}\n\\caption[RPBM model fit to the time dependence of diffusion indices for a young and senior subjects]{RPBM model fit to the time dependence of diffusion indices for a young and senior subjects.}\n\\label{fig:RPBM fit}\n\\end{figure}\n%*********************************************************\n%=========================================================\n\\begin{table}[!htb]\n\\vspace{+0.2cm}\n\\begin{center}\n\\caption[Parameters of muscle tissue extracted from the RPBM model]{Parameters of muscle tissue extracted from the RPBM model.}\n\\label{tab:RPBM2}\n\\begin{tabular}{@{}lrr@{}}\n\\toprule[1pt]\\midrule[0.3pt]\n                        \t\t\t\t\t\t\t\t& \\multicolumn{1}{c}{Young}         & \\multicolumn{1}{c}{Senior}  \\\\ \\cmidrule(){1-3}\n$D_0 \\; \\left[\\SI{}{\\micro\\meter^2\\per\\milli\\second}\\right]$      & \\multirow{2}{*}{2.20 $\\pm$ 0.16}  & \\multirow{2}{*}{2.18 $\\pm$ 0.24}   \\\\\nfree diffusion          \t\t\t\t\t\t\t\t&                                \t&                                \\\\[6pt]\n$\\zeta$                 \t\t\t\t\t\t\t\t& \\multirow{2}{*}{3.26 $\\pm$ 1.62}  & \\multirow{2}{*}{2.79 $\\pm$ 0.63}   \\\\\nvolume fraction         \t\t\t\t\t\t\t\t&                                \t&                                 \\\\[6pt]\n$S/V \\; \\left[\\SI{}{\\micro\\meter^{-1}}\\right]$                      & \\multirow{2}{*}{0.14 $\\pm$ 0.03}  & \\multirow{2}{*}{0.13 $\\pm$ 0.02}   \\\\\nsurface to volume ratio \t\t\t\t\t\t\t\t&                                \t&                                 \\\\[6pt]\n$\\kappa \\; \\left[\\SI{}{\\micro\\meter / \\milli\\second}\\right]$\t\t& \\multirow{2}{*}{0.025 $\\pm$ 0.005}& \\multirow{2}{*}{0.027 $\\pm$ 0.009} \\\\\npermeability            \t\t\t\t\t\t\t\t&                                \t&                                 \\\\[6pt]\n$a \\; \\left[\\SI{}{\\micro\\meter}\\right]$                        \t& \\multirow{2}{*}{28.63 $\\pm$ 4.94} & \\multirow{2}{*}{32.00 $\\pm$ 3.72}  \\\\\nmyofiber diameter       \t\t\t\t\t\t\t\t&                                \t&                                 \\\\[6pt]\n$\\tau_{R} \\; \\left[\\SI{}{\\milli\\second}\\right]$                        \t\t\t\t\t\t\t\t& \\multirow{2}{*}{552.2 $\\pm$ 122.1}& \\multirow{2}{*}{650.6 $\\pm$ 159.2} \\\\\nresidence time  \t\t\t\t\t\t\t\t&                                \t&                                 \\\\[6pt]\n$\\tau_{D} \\; \\left[\\SI{}{\\milli\\second}\\right]$                       \t\t\t\t\t\t\t\t& \\multirow{2}{*}{194.5 $\\pm$ 71.9} & \\multirow{2}{*}{238.1 $\\pm$ 50.7}  \\\\\ndiffusion time  \t\t\t\t\t\t\t\t&                                \t&                                \\\\ \\midrule[0.3pt]\\bottomrule[1pt]\n\\end{tabular}\n\\end{center}\n\\vspace{-0.2cm}\n\\end{table}\n%=========================================================\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\\subsection{Discussion} \n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nThe values of the model derived parameters are in general agreement with that reported for the MG in an earlier study. \nThe RPBM model yields a lower volume fraction for the aging muscle which is a measure of the membrane's ability to hinder diffusion. \nIt is possible that aging muscle may have compromised sarcolemma integrity that makes it more permeable and thus poses less of a barrier to diffusion. \nBased on the fact that muscle atrophies with age a decrease in fiber diameter with age is expected. \nHowever fiber diameters derived from the RPBM model did not show anticipated changes. \nA sarcolemma with compromised integrity (as seen here in aging muscle) may potentially affect lateral transmission of force, the latter is mediated by proteins in the sarcolemma.\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\\subsection{Conclusions} \n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nThe study has demonstrated the potential of diffusion modeling to extract muscle tissue parameters from time dependent $D_\\perp$ derived from DTI data and its potential application it to study age related skeletal muscle remodeling.\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\\section{Acknowledgments}\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nSection~\\ref{sec: DTI ULLS} is a reprint of material, with additional details provided in subsection~\\ref{subsec: bicompart}, as it appears in: V.~Malis, U.~Sinha, R.~Csapo, M.~Narici, E.~Smitaman, and S.~Sinha, ``Diffusion tensor imaging and diffusion modeling: Application to monitoring changes in the medial gastrocnemius in disuse atrophy induced by unilateral limb suspension,'' \\emph{J. Magn. Reson. Imaging}, vol. 49, no. 6, pp. 1655-1664, Dec. 2018.\nThe author of the dissertation was the primary author of this paper.\n%-new paragraph-%\n\n%-new paragraph-%\nSection~\\ref{sec: STEAM RPBM} is a reprint of material, with additional details, as it appears in: V.~Malis, S.~Sinha, E.~Smitaman, and U.~Sinha, ``Skeletal Muscle Diffusion Modeling to Identify Age Related Remodeling of Muscle Microstructure,'' \\emph{Proceedings of the International Society of Magnetic Resonance in Medicine}, Sydney, 2020.\nThe author of the dissertation was the primary author of this abstract.", "meta": {"hexsha": "3b3b7434facb881329cbe1b636ffb812cba15b05", "size": 63813, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapter6.tex", "max_stars_repo_name": "vmalis/PhDissertation", "max_stars_repo_head_hexsha": "7c6a343f902eb7a76d3f0ceca9aeb54def160c59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapter6.tex", "max_issues_repo_name": "vmalis/PhDissertation", "max_issues_repo_head_hexsha": "7c6a343f902eb7a76d3f0ceca9aeb54def160c59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter6.tex", "max_forks_repo_name": "vmalis/PhDissertation", "max_forks_repo_head_hexsha": "7c6a343f902eb7a76d3f0ceca9aeb54def160c59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 104.7832512315, "max_line_length": 720, "alphanum_fraction": 0.6765235924, "num_tokens": 16367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6548947155710233, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.34533680459456245}}
{"text": "There are many types of neural networks and each of them perform differently according to the task. Considering the low vocabulary of our task and the large amount of data, we'll be looking to search for patterns through the identification of templates with neural networks. Therefore, CNN comes immediately to mind. But many works suggests the use of recurrent neural networks. Therefore we'll focus on those two types of networks that seems to be the most promising. Finally, MLPs are usually mentionned but not for their performances, mostly because they are easy to implement and it's always a nice comparison.\n\n\\vspace{5mm}\n\nKeyword spotting task are extremely fit to CNNs according to many research \\cite{CNN}, \\cite{init}. A DNN cannot take advantage of the topology of the signal, however CNNs are extremely good at acoustic modeling which permits to give a good representation of a speech spectrum. The differences of frequencies between each speaker and also the timing differences between each examples are known to be easily handled by CNNs.\n\n\\vspace{5mm}\n\nRNNs and especially LSTMs are also fit to this task because of their ability to take into account time sequences through feedback connections. They also benefits from the combination of lstm layers with deep or convolutionnal layers \\cite{graves}. But one of the main problem encountered with RNNs, is that they are slow for many reasons (no parrellelization, slow learning, ...). Therefore the trend is to move away from recurrent structures.\n\n\n\n\\section{MLP}\n\nNeural networks are used to approximate functions which solving a non linear optimization problem that tries to find the minimum \"distance\" between the approximation and the real function. To do so, training algorithms try to find the set of weights that minimize the \"distance\" represented by the loss function.\n\n\\vspace{5mm}\n\nMLPs are one of the most simple form yet usually reliable of neural networks. They are composed of one input layer, one output layer and at least one hidden layer. They are feed forward that means that the flow of information goes in only one direction : from input layer to output layer.\n\n\n\\section{CNN}\nCNNs are an evolution of MLPs. Indeed, usually they have an MLP base that is situated at the end of the network but they also have some convolutions layers. the role of those convolution layers will be to split the input in order to find interesting information in a small subset of it. This will make CNN be able space dependecies in 2-d data. In addition of that, CNNs are usually more effective than MLPs in term of computation. \n\n\\section{LSTM}\n\nLSTM structures (Long short term memory) are a chain like network where you gives the output of a block as an input of the next one. The idea being similar to recurrent neural networks, it's about creating an artificial memory of how inputs evoluate over time. It is extremely interesting for tasks with temporal dependencies such as speech recognition. The improvement over the RNN structures is the forget gate that allows to manipulate weights of recurrents connections in order to face the vanishing gradient problem. Therefore \n\n\\begin{figure}[h!]\n    \\centering\n    \\includegraphics[width=1\\textwidth]{chapters/pictures/lstm_unit.png}\n    \\caption{Inside of a LSTM unit}\n    \\label{fig:mlp}\n\\end{figure}\n", "meta": {"hexsha": "995dc1ca754746200da35d297183ef662e7efafc", "size": 3324, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/chapters/3-Literrature_review.tex", "max_stars_repo_name": "TMarquet/speech_recognition", "max_stars_repo_head_hexsha": "06cf66b89e706306d676e127126d525bd18588f0", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "report/chapters/3-Literrature_review.tex", "max_issues_repo_name": "TMarquet/speech_recognition", "max_issues_repo_head_hexsha": "06cf66b89e706306d676e127126d525bd18588f0", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/chapters/3-Literrature_review.tex", "max_forks_repo_name": "TMarquet/speech_recognition", "max_forks_repo_head_hexsha": "06cf66b89e706306d676e127126d525bd18588f0", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 94.9714285714, "max_line_length": 614, "alphanum_fraction": 0.7999398315, "num_tokens": 695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.34529197632961595}}
{"text": "\\documentclass[a4paper]{article}\n\n% Language and Font Encoding\n\\usepackage[english]{babel}\n%\\usepackage[utf8x]{inputenc}\n\\usepackage[T1]{fontenc}\n\\usepackage{listings}\n\\usepackage{float}\n\\usepackage{caption}         % For captions\n\\usepackage{fancyhdr}        % For header and footer\n\\usepackage{rotating}\n\\usepackage{amssymb}\n%\\usepackage{varwidth}\n\\usepackage[colorlinks=true, allcolors=blue]{hyperref}\n\n% Page size and margins\n\\usepackage[a4paper,top=3cm,bottom=2cm,left=2cm,right=2cm,marginparwidth=1.75cm]{geometry}\n\n% Useful Packages\n\\usepackage{amsmath}\n\\usepackage{graphicx}\n\\usepackage{amsthm}\n%\\usepackage{bbm}\n\\usepackage{siunitx}\n\\usepackage{cite}\n\\DeclareMathOperator*{\\argmax}{argmax}\n\\DeclareMathOperator*{\\argmin}{argmin}\n\\DeclareMathOperator*{\\softmax}{softmax}\n\n\\newcommand{\\squeezeup}{\\vspace{-2.5mm}}\n\\newcommand{\\norm}[1]{\\left\\lVert#1\\right\\rVert}\n\n\n\\pagestyle{fancy}\n\\lhead{Appendix: Topology}\n\\rhead{}\n\n\\begin{document}\n\n\\title{Optimization on Manifolds, Appendix: Topology}\n\\author{Ibrahim Akbar}\n\\maketitle\n\n\\section{Definitions}\nThis serves as a light introduction into the topic of topology, but is not sufficient to have a complete or deep understanding. For further information, I suggest reading James Munkres' \\textit{Topology} text for a thorough introduction.\\\\\n\n\\noindent Just as an n-dimensional vector space is an abstraction of $\\mathbb{R}^{n}$, a topology on a set $X$ is an abstraction of open sets in $\\mathbb{R}^{n}$.\\\\\n\n\\noindent A \\textbf{topology} on a set $X$ is a collection $\\mathcal{T}$ of open subsets of $X$ such that:\n\n\\begin{enumerate}\n\\item $X,\\{0\\}\\in\\mathcal{T}$\n\\item Given a subcollection $\\mathcal{S}$ of $\\mathcal{T}$, $\\cup_{i}S_{i}\\in\\mathcal{T}$\n\\item Given a finite subcollection $\\mathcal{S}$ of $\\mathcal{T}$, $\\cap_{i}S_{i}\\in\\mathcal{T}$\n\\end{enumerate}\n\n\\noindent Thus a topology is the couple $(X,\\mathcal{T})$, but when notation allows it will be abbreviated to $X$. Currently, the definition for topology is not well-defined as we do not know what \"open\" means.\\\\\n\n\\noindent Let $X$ be a topological space. Let $A$ be a subset of $X$. A \\textbf{neighborhood} of a point $x$ on $X$ is a subset $\\mathcal{V}$ that includes an open set, $\\mathcal{U}$ containing $x$.\n$$\nx\\in\\mathcal{U}\\subset\\mathcal{V}\\subseteq X\n$$\n\n\\noindent A \\textbf{limit point} or \\textbf{accumulation point} of a subset $A$ of $X$ is a point $x$ of $X$ such that every neighborhood of $x$ intersects $A$ in some point \\textit{other than} $x$. Note that it is important to distinguish between intersecting at $x$ and somewhere else. If the restriction of intersecting at points other than were to be removed $x$ would be a \\textbf{point of closure}. Thus every point of closure is a limit point but not necessarily every limit point is a point of closure.\\\\\n\n\\noindent A subset is \\textbf{closed} if and only if it contains all it's limit points. An open set is naturally one that does not contain all it's limit points.\\\\\n\n\\noindent A sequence of points $\\{x_{k}\\}_{k=1,2,\\ldots}$ of $X$ \\textbf{converges} to a point $x\\in X$ if for every neighborhood $\\mathcal{U}$ of $x$ there exists a positive integer $K$ such that $x_{k}$ belongs to $\\mathcal{U}$ for all $k\\geq K$.\\\\\n\n\\noindent Since topology needs to satisfy relatively few axioms it is natural that properties that may hold for $\\mathbb{R}^{n}$ may not hold for $X$. As an example a \\textbf{singleton} which is a set containing only one element may not be closed in the topological sense. Take for example the topology of $[-1,1]$. The open sets are $[-1, a)$ for $a > 0$,$(b,a)$ for $a < 0, b > 0$, and  $(b, 1]$ for $b < 0$ \\textit{(Why?)}. To avoid such situations \\textbf{separation axioms} have been introduced to make a distinction between topologies.\\\\\n\n\\noindent A topological space $X$ is $T_{1}$; \\textbf{accessible} or \\textbf{Fr\\'{e}chet}, if for any distinct points $x$ and $y$ of $X$ there is an open set containing $x$ and not $y$. (Every singleton is closed.)\\\\\n\n\\noindent A topological space $X$ is $T_{2}$, \\textbf{Hausdorff}, if any two distinct points of $X$ have disjoint neighborhoods. A Hausdorff topology means that any sequence of points on $X$ converges to at most one point of $X$.\\textit{(Why?)}\\\\\n\n\\noindent Let $\\mathcal{T}_{1}$ and $\\mathcal{T}_{2}$ be topological spaces of $X$. If $\\mathcal{T}_{1}\\subseteq\\mathcal{T}_{2}$ then $\\mathcal{T}_{2}$ is said to be \\textbf{finer}.\\\\\n\n\\newpage\n\\noindent A \\textbf{base} or \\textbf{basis} for a topology on set $X$ is a collection $\\mathcal{B}$ of subsets of $X$ such that\n\\begin{enumerate}\n\\item each $x\\in X$ belongs to at least one element in $\\mathcal{B}$\n\\item if $x\\in(B_{1}\\cap B_{2})$ with $B_{1},B_{2}\\in\\mathcal{B}$, then there exists $B_{3}\\in\\mathcal{B}$ such that $x\\in B_{3}\\subseteq B_{1}\\cap B_{2}$.\n\\end{enumerate}\n\n\\noindent If $\\mathcal{B}$ is a base for topology $\\mathcal{T}$ then $\\cup_{i}\\mathcal{B} = \\mathcal{T}$ and a topology is denoted as \\textbf{second-countable} if it's base is finite.\\\\\n\n\\noindent If $X$ and $Y$ are topological spaces then the \\textbf{product topology} $X\\times Y$ has the base $\\mathcal{B}$ which is the collection of all sets of the form $U\\times V$ where $U$ is an open set of $X$ and $V$ is an open set of $Y$.\\\\\n\n\\noindent If $Y$ is a subset of a topological space $(X,\\mathcal{T})$. Then $\\mathcal{T}_{Y} = \\{Y\\cap U\\mid U\\in\\mathcal{T}\\}$ is a topology on $Y$ called the \\textbf{subspace topology}.\\\\\n\n\\noindent A collection $\\mathcal{A}$ of subsets of $X$ \\textbf{cover} or is a \\textbf{covering} of $X$ if the union of the elements of $\\mathcal{A}$ is equal to $X$.\\\\\n\n\\noindent \\textbf{Heine-Borel Theorem}: A subset of $\\mathbb{R}^{n}$ with the subspace topology is compact if and only if it is closed and bounded.\\\\ \n\n\\end{document}\n\n", "meta": {"hexsha": "c6b669774dcccf3e5e19be5d0a27db50c7f413f3", "size": 5775, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "files/notes/tex/opti-manifold/append/opti-manifold-append-topo.tex", "max_stars_repo_name": "ibrahimkakbar/ibrahimkakbar.github.io", "max_stars_repo_head_hexsha": "5e6b0ea67f5e5f8f3a7bb4394095ea7f7992673a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "files/notes/tex/opti-manifold/append/opti-manifold-append-topo.tex", "max_issues_repo_name": "ibrahimkakbar/ibrahimkakbar.github.io", "max_issues_repo_head_hexsha": "5e6b0ea67f5e5f8f3a7bb4394095ea7f7992673a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "files/notes/tex/opti-manifold/append/opti-manifold-append-topo.tex", "max_forks_repo_name": "ibrahimkakbar/ibrahimkakbar.github.io", "max_forks_repo_head_hexsha": "5e6b0ea67f5e5f8f3a7bb4394095ea7f7992673a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.5360824742, "max_line_length": 543, "alphanum_fraction": 0.7168831169, "num_tokens": 1822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.34529196893354036}}
{"text": "\\subsection{Affine coordinate systems}\\label{subsec:affine_coordinate_system}\n\n\\begin{remark}\\label{rem:affine_coordinate_system_concept}\n  Most humans possess a strong intuition for visual information like drawings or diagrams. A paper or a painting is only a medium for communicating information and emotions. \\Fullref{def:euclidean_plane/figures} contains some highlighted curves that our mind maps to abstract geometric figures, without considering the size limitations of the page, the precision of the drawings or the thickness of the lines.\n\n  \\begin{figure}[b]\n    \\centering\n    \\text{\\todo{Add diagram}}\\iffalse\\begin{mplibcode}\n      u := 1cm;\n\n      beginfig(1);\n      draw (0, -1) * u -- (3, 0) * u;\n      draw (-1, 2) * u -- (3, 1) * u -- (1, 3) * u -- cycle;\n      draw fullcircle scaled 1.5u shifted ((0, 0.5) * u);\n      endfig;\n    \\end{mplibcode}\\fi\n    \\caption{A triangle, a circle and a line in the Euclidean plane.}\\label{def:euclidean_plane/figures}\n  \\end{figure}\n\n  Our goal is to map these visualizations to the concept of vector spaces. Formalisms at the level of formal \\hyperref[def:first_order_language]{logic} will not be stated because we only want to sketch some high-level concepts. We only give definitions that are strictly necessary, plane geometry itself is described in \\fullref{subsec:analytic_geometry_in_the_plane}. We will proceed as follows:\n\n  \\begin{itemize}\n    \\item Define an affine plane in \\fullref{def:affine_plane} with auxiliary definitions.\n    \\item Describe the Euclidean plane \\( A_2 \\) in \\fullref{def:euclidean_plane} as a very special affine plane.\n    \\item Give additional definitions for the Euclidean plane in \\fullref{def:euclidean_plane_auxiliary_definitions}.\n    \\item Define the set \\( F_2 \\) of free vectors over \\( A_2 \\) in \\fullref{def:euclidean_plane_free_vector}.\n    \\item Show that \\( F_2 \\) is a two-dimensional vector space over \\( \\BbbR \\) in \\fullref{thm:euclidean_plane_factorization}.\n    \\item Define coordinate systems that give explicit isomorphisms between \\( A_2 \\), \\( F_2 \\) and \\( \\BbbR^2 \\) in \\fullref{def:euclidean_plane_coordinate_system}.\n    \\item Generalize these notions in \\fullref{rem:coordinate_systems}\n  \\end{itemize}\n\\end{remark}\n\n\\begin{definition}\\label{def:affine_plane}\\mcite[1]{Hartshorne1967}\n  An \\term{affine plane} consists of\n  \\begin{itemize}\n    \\item a set \\( X \\), whose elements are called \\term{points},\n    \\item a family of subsets of \\( X \\), whose members are called \\term{lines}\n  \\end{itemize}\n  with the additional relations\n  \\begin{itemize}\n    \\item a \\term{parallel} relation \\( l \\parallel g \\) for lines that holds if either \\( l = g \\) or if they have no points in common,\n    \\item a \\term{collinearity} relation for a set \\( B \\) of points that holds if \\( B \\) is a subset of some line,\n  \\end{itemize}\n  such that\n  \\begin{thmenum}\n    \\thmitem[def:affine_plane/A1]{A1} Given two distinct points, there exists only one line that contains both.\n    \\thmitem[def:affine_plane/A2]{A2} Given a line \\( l \\) and a point \\( P \\not\\in l \\), there exists exactly one line \\( g \\parallel l \\) that contains \\( P \\).\n    \\thmitem[def:affine_plane/A3]{A3} There exist three non-collinear points.\n  \\end{thmenum}\n\\end{definition}\n\n\\begin{definition}\\label{def:euclidean_plane}\n  The \\term{Euclidean plane} \\( A_2 \\) is a formalization of a straight infinite surface. An axiomatic definition can be found in \\cite{nLab:euclidean_geometry}. We will use that\n  \\begin{itemize}\n    \\item The Euclidean plane \\( A_2 \\) is an \\hyperref[def:affine_plane]{affine plane}\n    \\item \\( A_2 \\) is a \\hyperref[def:complete_metric_space]{complete metric space} with distance \\( \\op{dist} \\).\n    \\item There is a \\term{betweenness} relation for points that says if the point \\( R \\) is \\term{between} \\( P \\) and \\( Q \\).\n  \\end{itemize}\n\n  \\begin{figure}\n    \\centering\n    \\text{\\todo{Add diagram}}\\iffalse\\begin{mplibcode}\n      input metapost/plotting;\n\n      u := 1.5cm;\n\n      beginfig(1);\n      path l, g, h, P, Q, R;\n      l = (0, -1) * u -- (3, 0) * u;\n      draw l;\n      label.top(\"$l$\", midpoint of l);\n\n      g = (0, -2) * u -- (3, -1) * u;\n      draw g;\n      label.bot(\"$g$\", midpoint of g);\n\n      h = (0, 0) * u -- (3, -2) * u;\n      draw h;\n      label.urt(\"$h$\", midpoint of h);\n\n      P = dot shifted point 0.2 of h;\n      fill P;\n      label.llft(\"$P$\", midpoint of P);\n\n      Q = dot shifted point 0.8 of h;\n      fill Q;\n      label.llft(\"$Q$\", midpoint of Q);\n\n      R = dot shifted point 0.4 of h;\n      fill R;\n      label.llft(\"$R$\", midpoint of R);\n      endfig;\n    \\end{mplibcode}\\fi\n    \\caption{Three lines and three points in the Euclidean plane. The lines \\( l \\) and \\( g \\) are collinear, while the point \\( R \\) is between \\( P \\) and \\( Q \\)}\\label{def:affine_plane/figure}\n  \\end{figure}\n\\end{definition}\n\n\\begin{definition}\\label{def:euclidean_plane_auxiliary_definitions}\n  We will also need the following definitions:\n  \\begin{thmenum}\n    \\thmitem{def:affine_plane/half_plane} Every line \\( l \\) gives rise to two (closed) \\term{half-planes} \\( H^+ \\) and \\( H^- \\) as follows:\n    \\begin{itemize}\n      \\item \\( H^+ \\cap H^- = l \\)\n      \\item \\( H^+ \\cup H^- = A_2 \\)\n      \\item If \\( P \\in H^+ \\setminus l \\) and \\( Q \\in H^- \\setminus l \\), then there is a point \\( R \\in l \\) between \\( P \\) and \\( Q \\)\n    \\end{itemize}\n\n    Note that the superscripts \\( + \\) and \\( - \\) are only for distinguishing between the two half-planes and are not assigned based on some property of the half-planes. See \\fullref{def:half_space} for a definition of a half-plane that actually has a concept of signs.\n\n    \\begin{figure}\n      \\centering\n      \\text{\\todo{Add diagram}}\\iffalse\\begin{mplibcode}\n        input metapost/plotting;\n\n        u := 1cm;\n\n        beginfig(1);\n        input hatching;\n\n        path l, Hp, Hm;\n        l = (0, -1) * u -- (3, 0) * u;\n        draw l;\n\n        Hp = l -- (3, 0.5) * u -- (0, 0.5) * u -- cycle;\n        hatchfill Hp withcolor (45, 1mm, -.5bp);\n        label.ulft(\"$H^+$\", startpoint of l);\n\n        Hm = l -- (3, -1.5) * u -- (0, -1.5) * u -- cycle;\n        hatchfill Hm withcolor (135, 1mm, -.5bp);\n        label.lrt(\"$H^-$\", endpoint of l);\n        endfig;\n      \\end{mplibcode}\\fi\n\n      \\caption{Differently hatched half-planes in the Euclidean plane.}\\label{def:affine_plane/bound_vector/half_plane}\n    \\end{figure}\n\n    \\thmitem{def:affine_plane/ray} Every line \\( l \\) and every point \\( R \\) give rise to two (closed) \\term{rays} \\( l^+ \\) and \\( l^- \\) as follows:\n    \\begin{itemize}\n      \\item \\( l^+ \\cap l^- = \\{ R \\} \\) are disjoint\n      \\item \\( l^+ \\cup l^- = l \\)\n      \\item If \\( P \\in l^+ \\setminus \\{ R \\} \\) and \\( Q \\in l^- \\setminus \\{ R \\} \\), then \\( R \\) is between \\( P \\) and \\( Q \\)\n    \\end{itemize}\n\n    The rays \\( l^+ \\) and \\( l^- \\) are called \\term{opposite} of each other.\n\n    We say that \\( R \\) is the \\term{vertex} of \\( l^+ \\) and \\( l^- \\).\n\n    See \\fullref{def:geometric_ray} for a definition of a ray that actually has a concept of signs.\n\n    \\begin{figure}\n      \\centering\n      \\text{\\todo{Add diagram}}\\iffalse\\begin{mplibcode}\n        input metapost/plotting;\n\n        u := 1cm;\n\n        beginfig(1);\n        path l, R;\n\n        l = (0, -1) * u -- (3, 0) * u;\n        drawdblarrow l;\n        label.lft(\"$l^-$\", startpoint of l);\n        label.rt(\"$l^+$\", endpoint of l);\n\n        R = dot shifted midpoint of l;\n        fill R;\n        label.bot(\"$R$\", midpoint of R);\n        endfig;\n      \\end{mplibcode}\\fi\n\n      \\caption{Opposite rays in the Euclidean plane.}\\label{def:affine_plane/day/figure}\n    \\end{figure}\n\n    \\thmitem{def:affine_plane/rays_unidirectional} Two rays are said to be \\term{unidirectional} if there exists a line distinct from the lines containing the rays, such that both rays are contained in the same half-plane with respect to the line.\n\n    \\thmitem{def:affine_plane/bound_vector} An ordered pair \\( \\vect{PQ} \\) of points is called a \\term{bound vector}. The point \\( P \\) is called the \\term{beginning} of \\( \\vect{PQ} \\) and \\( Q \\) is called the \\term{end} of \\( \\vect{PQ} \\).\n\n    \\begin{figure}\n      \\centering\n      \\text{\\todo{Add diagram}}\\iffalse\\begin{mplibcode}\n        input metapost/plotting;\n\n        u := 0.75cm;\n\n        beginfig(1);\n        path P, Q, R, PQ, PR;\n\n        PQ = (0, -1) * u -- (3, 0) * u;\n        drawarrow PQ;\n        label.bot(\"$\\vect{PQ}$\", midpoint of PQ);\n\n        P = dot shifted startpoint of PQ;\n        fill P;\n        label.bot(\"$P$\", midpoint of P);\n\n        Q = dot shifted endpoint of PQ;\n        label.bot(\"$Q$\", midpoint of Q);\n\n        PR = (0, -1) * u -- (-2, 0.5) * u;\n        drawarrow PR;\n        label.llft(\"$\\vect{PR}$\", midpoint of PR);\n\n        R = dot shifted endpoint of PR;\n        label.llft(\"$R$\", midpoint of R);\n        endfig;\n      \\end{mplibcode}\\fi\n\n      \\caption{Bound vectors in the Euclidean plane can be regarded as oriented line segment.}\\label{def:affine_plane/bound_vector/figure}\n    \\end{figure}\n  \\end{thmenum}\n\\end{definition}\n\n\\begin{definition}\\label{def:euclidean_plane_free_vector}\n  We say that the bound vectors \\( \\vect{P_1 Q_1} \\) and \\( \\vect{P_2 Q_2} \\) in \\( A_2 \\) are \\term{congruent} if \\( \\op{dist}(P_1, Q_1) = \\op{dist}(P_2, Q_2) \\) and if the rays \\( r_i, i = 1, 2 \\) beginning at \\( P_i \\) and containing \\( Q_i \\), are unidirectional.\n\n  We define \\term{free vectors} as \\hyperref[thm:equivalence_partition]{equivalence classes} of bound vectors by this congruence relation. We denote the corresponding equivalence partition by \\( F_2 \\).\n\\end{definition}\n\n\\begin{theorem}\\label{thm:euclidean_plane_factorization}\n  The set \\( F_2 \\) of free vectors over \\( A_2 \\) is a two-dimensional \\hyperref[def:vector_space]{vector space} over \\( \\BbbR \\) with the following operations:\n  \\begin{thmenum}\n    \\thmitem{thm:euclidean_plane_factorization/sum} We define the \\term{sum} of the cosets \\( [\\vect{PQ}] \\) and \\( [\\vect{QR}] \\) as the coset \\( [\\vect{PR}] \\).\n\n    \\thmitem{thm:euclidean_plane_factorization/scalar_product} We define the \\term{scalar multiplication} of \\( \\lambda \\in \\BbbR \\) with the coset \\( [\\vect{PQ}] \\) to be the coset \\( [\\vect{PR}] \\), where \\( \\vect{PR} \\) is the unique vector that is unidirectional with \\( \\vect{PQ} \\) and \\( \\op{dist}(P, R) = \\lambda \\op{dist}(P, Q) \\).\n  \\end{thmenum}\n\\end{theorem}\n\\begin{proof}\n  Proving the well-definedness of the operations and verifying that \\( F_2 \\) is a two-dimensional vector space requires a lot of work and the proof is skipped.\n\\end{proof}\n\n\\begin{definition}\\label{def:euclidean_plane_coordinate_system}\n  Just because \\fullref{thm:euclidean_plane_factorization} states that the set \\( F_2 \\) of free vectors is a vector space does not mean that we can work with it as with \\( \\BbbR^2 \\). \\Fullref{thm:finite_dimensional_spaces_are_isomorphic} says that \\( F_2 \\) is isomorphic to \\( \\BbbR^2 \\), however the proof requires the \\hyperref[def:zfc/choice]{axiom of choice}. The concrete way to select a basis in \\( F_2 \\) is through coordinate systems.\n\n  Somewhat confusingly, we define coordinate systems over \\( A_2 \\) rather than over \\( F_2 \\), but this will, soon be justified.\n\n  A \\term{coordinate system} \\( Oxy \\) in \\( A_2 \\) is a choice of\n  \\begin{thmenum}\n    \\thmitem{def:euclidean_plane_coordinate_system/origin} A point \\( O \\in A_2 \\), called the \\term{origin} of the coordinate system.\n    \\thmitem{def:euclidean_plane_coordinate_system/basis} An \\hyperref[def:partially_ordered_set]{ordered} \\hyperref[def:hamel_basis]{basis} \\( (x, y) \\) of \\( F_2 \\), called the \\term{basis} of \\( Oxy \\).\n  \\end{thmenum}\n\n  What we achieve through the choice of \\( O \\) is that, for each point \\( P \\in A_2 \\), we select the bound vector \\( \\vect{OP} \\in V_2 \\), called the \\term{radius vector} of \\( P \\). This injects \\( A_2 \\) into \\( V_2 \\), however if we take the free vector \\( [\\vect{OP}] \\), we instead obtain a bijection between \\( A_2 \\) and \\( F_2 \\).\n\n  Now that we have a correspondence between \\( A_2 \\) and \\( F_2 \\), coordinates for the point \\( P \\) are defined simply as the \\hyperref[def:module_basis_projection]{coordinates} of \\( [\\vect{OP}] \\) with respect to the basis \\( (x, y) \\).\n\n  Thus, the pair \\( (A_2, Oxy) \\) has an explicit isomorphism with \\( \\BbbR^2 \\).\n\n  The \\term{coordinate axis} of \\( x \\) is the unique \\hyperref[def:affine_plane/ray]{ray} starting at \\( O \\) and containing the end of \\( x \\). It is called the \\term{abscissa}. The coordinate axis of \\( y \\) is called the \\term{ordinate}.\n\\end{definition}\n\n\\begin{remark}\\label{rem:coordinate_systems}\n  We sketched how to embed mental images of planes into \\( \\BbbR^2 \\), however in mathematics we are often interested in the opposite: given a set of points in \\( \\BbbR^2 \\), visualize them on a screen or paper and then absorb the the resulting image in our brain.\n\n  This is one of the most powerful constructions in mathematics, yet it is, so intuitive that it is not really given a lot of attention, at least until generalizations are required. Given any vector space \\( V \\) in the sense of \\fullref{def:vector_space}, we want a way to assign a pair of numbers to each vector in \\( V \\). This is only possible if \\( \\dim V = 2 \\), however we can generalize this to tuples of coordinates via bases - see \\fullref{def:hamel_basis}. This well for finitely dimensional vector spaces, however we need to generalize these notion for infinitely dimensional vector spaces and general modules over \\hyperref[def:module]{rings}. This allows us to generalize coordinates further to manifolds - see \\fullref{def:topological_manifold}.\n\n  See \\fullref{subsec:vector_space_geometry} for immediate generalizations of the concepts introduced here.\n\\end{remark}\n", "meta": {"hexsha": "744a36d759047625427553c4e9dc4268353a140f", "size": 13802, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/affine_coordinate_systems.tex", "max_stars_repo_name": "v--/anthology", "max_stars_repo_head_hexsha": "89a91b5182f187bc1aa37a2054762dd0078a7b56", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/affine_coordinate_systems.tex", "max_issues_repo_name": "v--/anthology", "max_issues_repo_head_hexsha": "89a91b5182f187bc1aa37a2054762dd0078a7b56", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/affine_coordinate_systems.tex", "max_forks_repo_name": "v--/anthology", "max_forks_repo_head_hexsha": "89a91b5182f187bc1aa37a2054762dd0078a7b56", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.496124031, "max_line_length": 760, "alphanum_fraction": 0.6567888712, "num_tokens": 4180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.3452919594453517}}
{"text": "\\subsection{Gradient computation, case of NewtonEuler with quaternion}\n\nIn the section, $q$ is the quaternion of the dynamical system.\n\n\\begin{figure}[h]\n  \\centering\n   \n  %\\input{./Figures/NewtonEulerImpact.pstex_t}\n  \\input{./Figures/NewtonEulerImpact.pdf_t}\n  \n  \\caption{Impact of one DS.}\n  \\label{figCase}\n\\end{figure}\n\nThe normal vector $N$ is view as a constant.\n\\[~\\tilde h(q)=P_c(\\frac{q}{\\|q\\|})\\]\n\\[^t \\nabla h(q)(\\delta q) = \\lim _{e \\to 0}\\frac{(\\tilde h (q+e\\delta q)-\\tilde h (q)).N}{e}  \\]\n\n$\\nabla _q h$ consist in computing $P_c(\\frac{q+\\delta q}{\\|q+\\delta q\\|})-P_c(q)$.\n\\[GP(q)=qG_0P_0~^cq\\]\n\\[GP(\\frac{q+\\delta q}{\\|q+\\delta q\\|})=(q+\\delta q)G_0P_0~^c(q+\\delta q)\\frac{1}{\\|q+\\delta q\\|^2}\\]\n\\[=(q+\\delta q)~^cqGP(q)q~^c(q+\\delta q)\\frac{1}{\\|q+\\delta q\\|^2}\\]\n\\[=((1,0,0,0)+\\delta q~^cq)GP(q)((1,0,0,0)+q~^c\\delta q)\\frac{1}{\\|q+\\delta q\\|^2}\\]\n\\[=GP(q)+\\delta q~^cqGP(q) + GP(q)q~^c\\delta q+0(\\delta q)^2\\frac{1}{\\|q+\\delta q\\|^2}\\]\nSo, because G is independant of $q$:\n\\[P(\\frac{q+\\delta q}{\\|q+\\delta q\\|})-P(q)=qGP(\\frac{q+\\delta q}{\\|q+\\delta q\\|})-GP(q)=\\delta q~^cqGP(q) + GP(q)q~^c\\delta q+0(\\delta q)^2 + GP(q)\\frac{1}{\\|q+\\delta q\\|^2}\\]\nFor the directional derivation, we chose $\\delta q = \\epsilon * (1,0,0,0)$. using a equivalent to $\\frac{1}{1+\\epsilon}$\n\\[\\lim_{\\epsilon \\to 0}\\frac{P(\\frac{q+\\delta q}{\\|q+\\delta q\\|})-P(q)}{\\epsilon}=~^cqGP(q) + GP(q)q-2q_iGP(q)\\]\nFor the directional derivation, we chose $\\delta q = \\epsilon * (0,1,0,0)=\\epsilon * e_i$\n\\[\\lim_{\\epsilon \\to 0}\\frac{P(\\frac{q+\\delta q}{\\|q+\\delta q\\|})-P(q)}{\\epsilon}=e_i~^cqGP(q) - GP(q)qe_i-2q_iGP(q)\\]\nApplication to the NewtonEulerRImpact:\n\\[H:\\mathbb{R}^7 \\to \\mathbb{R}\\]\n\\[\\nabla _q H \\in \\mathcal{M}^{1,7}\\]\n\\[\\nabla _q H =\\left(\\begin{array}{c} N_x\\\\N_y\\\\N_z\\\\\n(~^cqGP(q) + GP(q)q-2q_0GP(q)).N\\\\\n(e_2~^cqGP(q) - GP(q)qe_2-2q_1GP(q)).N\\\\\n(e_3~^cqGP(q) - GP(q)qe_3-2q_2GP(q)).N\\\\\n(e_4~^cqGP(q) - GP(q)qe_4-2q_3GP(q)).N\\\\\n\\end{array}\\right)\\]\n\\subsection{Ball case}\nIt is the case where $GP=-N$:\nfor $e2$:\n\\[(0,1,0,0).(q_0,-\\underline p).(0,-N)=\\]\n\\[\\left(\\left(\\begin{array}{c}1\\\\0\\\\0\\end{array}\\right).\\underline p,\\left(\\begin{array}{c}q_0\\\\0\\\\0\\end{array}\\right) -\\left(\\begin{array}{c}1\\\\0\\\\0\\end{array}\\right)*\\underline p \\right).(0,-N)=\\]\n\\[\\left(?, -\\underline p_x~N-\\left(\\left(\\begin{array}{c}q_0\\\\0\\\\0\\end{array}\\right)- \\left(\\begin{array}{c}1\\\\0\\\\0\\end{array}\\right)*\\underline p \\right)*N\\right)=\\]\nand:\n\\[(0,-N).(q_0,\\underline p).(0,1,0,0)=\\]\n\\[(N.\\underline p,-q_0N-N*\\underline p).(0,1,0,0)=\\]\n\\[\\left(?,(N.\\underline p)\\left(\\begin{array}{c}1\\\\0\\\\0\\end{array}\\right) + \\left(\\begin{array}{c}1\\\\0\\\\0\\end{array}\\right)*(q_0N+N*\\underline p)\\right)=\\]\n\\[\\left(?,(N.\\underline p)\\left(\\begin{array}{c}1\\\\0\\\\0\\end{array}\\right)+q_0 \\left(\\begin{array}{c}1\\\\0\\\\0\\end{array}\\right)*N+\\left(\\begin{array}{c}1\\\\0\\\\0\\end{array}\\right)*(N*\\underline p)\\right)\\]\nsub then and get the resulting vector.N:\n\\[\\left[ -\\underline p_x~N -N.\\underline p~\\left(\\begin{array}{c}1\\\\0\\\\0\\end{array}\\right)+()*N-\\left(\\begin{array}{c}1\\\\0\\\\0\\end{array}\\right)*(N*\\underline p)\\right].N=\\]\n\\[-\\underline p_x-N_xN.\\underline p+0-(\\left(\\begin{array}{c}1\\\\0\\\\0\\end{array}\\right)*(N*\\underline p)).N=\\]\n  using $a*(b*c)=b(a.c)-c(a.b)$ leads to\n  \\[-q_1-N_xN.\\underline p-(q_1~N-N_x~\\underline p).N=\\]\n\\[-q_1-N_xN.\\underline p-q_1+N_xN.\\underline p=-2q_1\\]\nfor $e1=(1,0,0,0)$:\n\\[(q_0,-\\underline p).(0,-N)=(?,-q_0N+\\underline p*N)\\]\n\\[(0,-N).(q_0,\\underline p)=(?,-q_0N-\\underline p*N)\\]\nSo\n\\[\\nabla _q H =\\left(\\begin{array}{c} N_x\\\\N_y\\\\N_z\\\\\n0\\\\\n0\\\\\n0\\\\\n0\\\\\n\\end{array}\\right)\\]\n\n\\subsection{Case FC3D: using the local frame and momentum}\n\n\\[\\left(\\begin{array}{c}m \\dot V\\\\I \\dot \\Omega + \\Omega I \\Omega \\end{array}\\right)= \\left(\\begin{array}{c}Fect+R\\\\Mext _{R_{obj}} + (R*PG) _{R_{obj}} \\end{array}\\right)\\]\n  with * vectoriel product, $R$ reaction in the globla frame. $P$ the point of contact.\n  $r$ is the reaction in the local frame.  $M_{R_{obj}toR_{abs}}=M_{R_{abs}toR_{obj}}^t r=R$ with:\n  \\[M_{R_{C}toR_{abs}}=\\left(\\begin{array}{ccc} nx&t_1x&t_2x \\\\ny&t_1y&t_2y\\\\nz&t_1z&t_2z \\end{array}\\right)\\]\n  we have :\n  \\[\\left(\\begin{array}{c}R\\\\(R*PG) _{R_{obj}}\\end{array}\\right)=\\left(\\begin{array}{c} I_3\\\\M_{R_{abs}toR_{obj}}N_{PG}\\end{array}\\right).R\\]\n  \\[=\\left(\\begin{array}{c} I_3\\\\M_{R_{abs}toR_{obj}}N_{PG}\\end{array}\\right).M_{R_{obj}toR_{abs}}r\\]\n  \\[ N_{PG}=\\left(\\begin{array}{ccc} 0&PG_z&-PG_y\\\\-PG_z&0&PG_x\\\\PG_y&-PG_X&0\\end{array}\\right)\\]\n    that is:\n      \n\\[\\left(\\begin{array}{c}m \\dot V\\\\I \\dot \\Omega + \\Omega I \\Omega \\end{array}\\right)=\n\\left(\\begin{array}{c} M_{R_{C}toR_{abs}} \\\\\n  M_{R_{abs}toR_{obj}}N_{PG}M_{R_{C}toR_{abs}}\n\\end{array}\\right) r\\]\nSo $jachqt=MN$\n\n\\subsection{Case FC3D: using the local frame local velocities}\n\\begin{figure}[h!]\n  \\centering\n   \\scalebox{0.6}{\n  \\input{./Figures/SolideContact.pdf_t}\n  %   \\input{./Figures/SolideContact.pdf_t}\n  }\n  \\caption{Two objects colliding.}\n  \\label{figCase}\n\\end{figure}\n\n\nWe are looking for an operator named $CT$ such that:\n\n\\[V_C=\\left(\\begin{array}{c} V_N \\\\ V_T \\\\ V_S \\end{array}\\right)_{R_{C}}=CT \\left(\\begin{array}{c} V_{G1}~_{R_{abs}} \\\\ \\Omega_1~_{R_{obj1}} \\\\ V_{G2}~_{R_{abs}}\\\\ \\Omega_2~_{R_{obj2}} \\end{array}\\right)\\]\n\n\\[V_c=V_{G1}~_{R_{abs}} + w_1 * G_1P~_{R_{abs}} -(V_{G2}~_{R_{abs}} + w_2 * G_1P~_{R_{abs}})\\]\nwhere $w_1$ and $w_2$ are given in $R_{abs}$. We note $M_{R_{obj1}toR_{abs}}$ the matrice converting the object 1 coordinate to the absolute coordinate. We note $N_{GP}$ the matrice such that $w_1*G_1P~_{R_{abs}} = N_{GC} w_1$. Endly, we note $M_{R_{abs}toR_C}$ converting the absolute coordinate to the $R_C$ frame.\nwe get:\n\\[CT= M_{R_{abs}toR_C}   \\left(\\begin{array}{cccc} I_3 & N_{G_1C}M_{R_{obj1}toR_{abs}} & -I_3 & -N_{G_2C}M_{R_{obj2}toR_{abs}} \\end{array}\\right)\\]\n\n\\subsubsection{Expression of $M_{R_{obj1}toR_{abs}}$}\nUsing quaternion, we get :\n\\begin{equation}\n  \\label{eq:newton_Mobjtoabs}\nM_{R_{obj1}toR_{abs}} = \\left(\\begin{array}{ccc} q \\left(\\begin{array}{c}1\\\\0\\\\0 \\end{array}\\right)~^cq & q \\left(\\begin{array}{c}  0\\\\1\\\\0 \\end{array}\\right)~ ^cq & q \\left(\\begin{array}{c}  0\\\\0\\\\1 \\end{array}\\right)~ ^cq  \\end{array}\\right)\n\\end{equation}\n\n\\subsubsection{Expression of $N_1$}\n\\[N_{GC}=\\left(\\begin{array}{ccc} 0&G_1C_z&-G_1C_y\\\\-G_1C_z&0&G_1C_x\\\\G_1C_y&-G_1C_X&0\\end{array}\\right)\\]\n\n%%% Local Variables: \n%%% mode: latex\n%%% TeX-master: \"DevNotes\"\n%%% End: \n", "meta": {"hexsha": "da7702b4541619915497af573995242be78c25a9", "size": 6422, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/sphinx/devel_guide/notes/NewtonImpactJacobian.tex", "max_stars_repo_name": "ljktest/siconos", "max_stars_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "docs/sphinx/devel_guide/notes/NewtonImpactJacobian.tex", "max_issues_repo_name": "ljktest/siconos", "max_issues_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "docs/sphinx/devel_guide/notes/NewtonImpactJacobian.tex", "max_forks_repo_name": "ljktest/siconos", "max_forks_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 53.0743801653, "max_line_length": 316, "alphanum_fraction": 0.6222360635, "num_tokens": 2843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.3452692837950837}}
{"text": "\\documentclass[11pt]{article}\n\\usepackage{fullpage}\n\\usepackage{amsmath, amssymb, bigints, graphicx}\n\n\\title{Classical Lamination Theory \\\\\n      { \\normalsize ~ \\\\ A note in support of \\textit{Fiber Orientation Tools} \\\\\n       \\texttt{http://github.com/charlestucker3/Fiber-Orientation-Tools}}}\n\n\\author{Charles L.~Tucker III \\\\\n       Department of Mechanical Science and Engineering \\\\\n        University of Illinois at Urbana-Champaign \\\\\n        1206 W.~Green St. \\\\\n        Urbana, IL 61801 \\\\\n        }\n\\include{defs}  % Macro definitions\n\n\\begin{document}\n\\maketitle\n\nThe function \\texttt{Clayer2laminate} in \\emph{Fiber Orientation Tools} uses classical lamination theory to find the stiffness properties of a composite where the fiber orientation, fiber volume fraction, and/or the fiber length distribution vary across the thickness.  Such structures are typical for injection molded composites.  \n\nThis note explains the nomenclature used by \\texttt{Clayer2laminate} and summarizes the underlying theory.  We develop the laminate properties in a notation  that is common in the structural mechanics of laminated composite materials\\footnote{E.g., R. M. Jones, \\emph{Mechanics of Composite Materials}. Taylor \\& Francis, Philadelphia, 2nd edition, 1999.}.  Equation numbers with a period, e.g., Eqn.~(8.2), and section numbers refer to items from \\emph{Fundamentals of Fiber Orientation}, C. L. Tucker, Hanser, Munich, 2022.  \n\n\\subsection*{Coordinate System}\n\nIn the language of laminated composites, a \\emph{laminate} is a plate-like structure consisting of multiple discrete layers, or \\emph{lamina}, bonded together.  Choose $(x,y,z)$ coordinates so that $z = 0$ is the midplane of the laminate, and let the total thickness of the laminate be $H$.  \n\n\\subsection*{Strains and Curvatures}\n\nLet the components of the displacement vector be $(u, v, w)$.  The components of the strain tensor follow from the usual definitions, e.g., Eqns.~(8.2) and (8.3):\n\\begin{equation}\n   \\varepsilon_{xx} = \\frac{\\partial u}{\\partial x}   \\qquad  \\qquad\n   \\varepsilon_{yy} = \\frac{\\partial v}{\\partial y}   \\qquad  \\qquad\n   \\gamma_{xy} = \\frac{\\partial u}{\\partial y} + \\frac{\\partial v}{\\partial x} \n   \\label{epsilonDef}\n\\end{equation}\nNote that we are using engineering shear strain here, rather than tensor shear strain.  \n\nLet $w_0$ be the $z$-direction displacement of the laminate midplane, $z = 0$.  The midplane curvatures of the laminate are then described by the second derivatives of $w_0$:\n\\begin{equation}\n   \\kappa_{xx} = -\\frac{\\partial^2 w_0}{\\partial x^2}   \\qquad  \\qquad\n   \\kappa_{yy} = -\\frac{\\partial^2 w_0}{\\partial y^2}   \\qquad  \\qquad\n   \\kappa_{xy} = -2\\frac{\\partial ^2 w_0}{\\partial x \\partial y}\n   \\label{kappaDef}\n\\end{equation}\nThe inclusion of a factor of 2 in $\\kappa_{xy}$ is common, and parallels the use of the engineering shear strain.  These two choices are a departure from the notation in \\emph{Fundamentals of Fiber Orientation}, where all tensors are contracted using a consistent procedure, but they are standard in laminate analysis.  \n\n\n\\subsection*{Lamina Stress-Strain Equations}\n\nThe next task is to find the stress-strain relationships for a lamina in plane stress.  In our case we know (or can calculate) the 3-D stiffness tensor $\\Cfour$ for each lamina, so we will start with that.  Using $[\\Cfour]$ to represent the $6 \\times 6$ matrix that is the contracted form of this tensor, the lamina stress-strain equation is\n\\begin{equation}\n    \\left\\{ \\begin{array}{c}\n           \\sigma_{xx}  \\\\  \\sigma_{yy}  \\\\  \\sigma_{zz} \\\\  \\sigma_{yz} \\\\ \\sigma_{zx} \\\\  \\sigma_{xy}\n           \\end{array} \\right\\}\n           =\n              \\left[ \\begin{array}{cccccc}\n     \\Cfour_{11} &  \\Cfour_{12} &  \\Cfour_{13} &  \\Cfour_{14} &  \\Cfour_{15} &  \\Cfour_{16} \\\\\n     \\Cfour_{21} &  \\Cfour_{22} &  \\Cfour_{23} &  \\Cfour_{24} &  \\Cfour_{25} &  \\Cfour_{26} \\\\\n     \\Cfour_{31} &  \\Cfour_{32} &  \\Cfour_{33} &  \\Cfour_{34} &  \\Cfour_{35} &  \\Cfour_{36} \\\\\n     \\Cfour_{41} &  \\Cfour_{42} &  \\Cfour_{43} &  \\Cfour_{44} &  \\Cfour_{45} &  \\Cfour_{46} \\\\\n     \\Cfour_{51} &  \\Cfour_{52} &  \\Cfour_{53} &  \\Cfour_{54} &  \\Cfour_{55} &  \\Cfour_{56} \\\\\n     \\Cfour_{61} &  \\Cfour_{62} &  \\Cfour_{63} &  \\Cfour_{64} &  \\Cfour_{65} &  \\Cfour_{66} \n    \\end{array} \\right] \n        \\left\\{ \\begin{array}{c}\n           \\varepsilon_{xx}  \\\\  \\varepsilon_{yy}  \\\\  \\varepsilon_{zz} \\\\  \\gamma_{yz} \\\\ \\gamma_{zx} \\\\  \\gamma_{xy}\n           \\end{array} \\right\\}\n     \\label{stiffnessC}\n \\end{equation}\n\nThe laminate is assumed to be thin relative to its in-plane dimensions, so each lamina is in a state of \\emph{plane stress}:  $\\sigma_{zz} = \\sigma_{xz} = \\sigma_{yz} = 0$.  We would like to specialize Eqn.~(\\ref{stiffnessC}) for plane stress.  To do this, take the matrix inverse of $[ \\Cfour ]$ to find $[ \\tilde{\\Sfour} ] = [ \\Cfour ]^{-1}$.  In many books $[ \\tilde{\\Sfour} ]$  is called the compliance matrix.  This converts Eqn.~(\\ref{stiffnessC}) to a strain-stress relationship:\n\\begin{equation}\n        \\left\\{ \\begin{array}{c}\n           \\varepsilon_{xx}  \\\\  \\varepsilon_{yy}  \\\\  \\varepsilon_{zz} \\\\  \\gamma_{yz} \\\\ \\gamma_{zx} \\\\  \\gamma_{xy}\n           \\end{array} \\right\\}\n           =\n              \\left[ \\begin{array}{cccccc}\n     \\tilde{\\Sfour}_{11} &  \\tilde{\\Sfour}_{12} &  \\tilde{\\Sfour}_{13} &  \\tilde{\\Sfour}_{14} &  \\tilde{\\Sfour}_{15} &  \\tilde{\\Sfour}_{16} \\\\\n     \\tilde{\\Sfour}_{21} &  \\tilde{\\Sfour}_{22} &  \\tilde{\\Sfour}_{23} &  \\tilde{\\Sfour}_{24} &  \\tilde{\\Sfour}_{25} &  \\tilde{\\Sfour}_{26} \\\\\n     \\tilde{\\Sfour}_{31} &  \\tilde{\\Sfour}_{32} &  \\tilde{\\Sfour}_{33} &  \\tilde{\\Sfour}_{34} &  \\tilde{\\Sfour}_{35} &  \\tilde{\\Sfour}_{36} \\\\\n     \\tilde{\\Sfour}_{41} &  \\tilde{\\Sfour}_{42} &  \\tilde{\\Sfour}_{43} &  \\tilde{\\Sfour}_{44} &  \\tilde{\\Sfour}_{45} &  \\tilde{\\Sfour}_{46} \\\\\n     \\tilde{\\Sfour}_{51} &  \\tilde{\\Sfour}_{52} &  \\tilde{\\Sfour}_{53} &  \\tilde{\\Sfour}_{54} &  \\tilde{\\Sfour}_{55} &  \\tilde{\\Sfour}_{56} \\\\\n     \\tilde{\\Sfour}_{61} &  \\tilde{\\Sfour}_{62} &  \\tilde{\\Sfour}_{63} &  \\tilde{\\Sfour}_{64} &  \\tilde{\\Sfour}_{65} &  \\tilde{\\Sfour}_{66} \n    \\end{array} \\right] \n    \\left\\{ \\begin{array}{c}\n           \\sigma_{xx}  \\\\  \\sigma_{yy}  \\\\  \\sigma_{zz} \\\\  \\sigma_{yz} \\\\ \\sigma_{zx} \\\\  \\sigma_{xy}\n           \\end{array} \\right\\}\n     \\label{3Dcompliance}\n \\end{equation}\nNow we can write the in-plane strains as functions of the in-plane stresses by selecting the first, second, and sixth lines of Eqn.~(\\ref{3Dcompliance}) and setting $\\sigma_{zz}$, $\\sigma_{xz}$, and $\\sigma_{yz}$ to zero:\n\\begin{equation}\n        \\left\\{ \\begin{array}{c}\n           \\varepsilon_{xx}  \\\\  \\varepsilon_{yy}  \\\\  \\gamma_{xy}\n           \\end{array} \\right\\}\n           =\n              \\left[ \\begin{array}{ccc}\n     \\tilde{\\Sfour}_{11} &  \\tilde{\\Sfour}_{12} &   \\tilde{\\Sfour}_{16} \\\\\n     \\tilde{\\Sfour}_{21} &  \\tilde{\\Sfour}_{22} &   \\tilde{\\Sfour}_{26} \\\\\n     \\tilde{\\Sfour}_{61} &  \\tilde{\\Sfour}_{62} &   \\tilde{\\Sfour}_{66} \n    \\end{array} \\right] \n    \\left\\{ \\begin{array}{c}\n           \\sigma_{xx}  \\\\  \\sigma_{yy}  \\\\   \\sigma_{xy}\n           \\end{array} \\right\\}\n     \\label{2Dcompliance}\n \\end{equation}\n This matrix simply uses selected components from the full $[ \\tilde{\\Sfour} ]$ matrix.  \n \n To obtain stress-strain relationships we invert the matrix in Eqn.~(\\ref{2Dcompliance}) to find the \\emph{plane-stress lamina stiffness matrix} $[Q]$,\n \\begin{equation}\n   \\left[ \\begin{array}{ccc}\n     Q_{11} &  Q_{12} &   Q_{16} \\\\\n     Q_{21} &  Q_{22} &   Q_{26} \\\\\n     Q_{61} &  Q_{62} &   Q_{66} \n    \\end{array} \\right] \n    =\n              \\left[ \\begin{array}{ccc}\n     \\tilde{\\Sfour}_{11} &  \\tilde{\\Sfour}_{12} &   \\tilde{\\Sfour}_{16} \\\\\n     \\tilde{\\Sfour}_{21} &  \\tilde{\\Sfour}_{22} &   \\tilde{\\Sfour}_{26} \\\\\n     \\tilde{\\Sfour}_{61} &  \\tilde{\\Sfour}_{62} &   \\tilde{\\Sfour}_{66} \n    \\end{array} \\right]  ^{-1}\n    \\label{Qdef}\n \\end{equation}\n Now the lamina stress-strain relationship for plane stress is\n \\begin{equation}\n    \\left\\{ \\begin{array}{c}\n           \\sigma_{xx}  \\\\  \\sigma_{yy}  \\\\   \\sigma_{xy}\n           \\end{array} \\right\\}\n           =\n              \\left[ \\begin{array}{ccc}\n     Q_{11} &  Q_{12} &   Q_{16} \\\\\n     Q_{21} &  Q_{22} &   Q_{26} \\\\\n     Q_{61} &  Q_{62} &   Q_{66} \n    \\end{array} \\right] \n        \\left\\{ \\begin{array}{c}\n           \\varepsilon_{xx}  \\\\  \\varepsilon_{yy}  \\\\  \\gamma_{xy}\n           \\end{array} \\right\\}\n     \\label{laminaQ}\n \\end{equation}\nThis numbering of the entries in $[Q]$ is standard.  \n\nThis route to obtain $[Q]$ is different from the ones usually used in books on composite mechanics, but it starts from the lamina information that is available when analyzing discontinuous fiber composites, which is the lamina stiffness tensor $\\mathbf{\\Cfour}$.  In practice all of these calculations are carried out numerically.\n\n\\subsection*{Laminate Loads and Moments}\n\nThe standard way to describe the in-plane loads in a laminate is to define a vector of forces per unit width $\\{ N \\}$ whose components are\n\\begin{equation}\n   \\left\\{ \\begin{array}{c}\n     N_x \\\\ N_y \\\\ N_{xy}\n   \\end{array} \\right\\}\n   = \\bigintss_{-H/2}^{H/2} \n    \\left\\{ \\begin{array}{c}\n           \\sigma_{xx}  \\\\  \\sigma_{yy}  \\\\   \\sigma_{xy}\n           \\end{array} \\right\\}\n      \\ud z\n  \\label{Ndef}\n\\end{equation}\nFigure~\\ref{Nfig} sketches these loads.  \nNote that $N_x$ is the $x$-direction force per unit width in the $y$ direction, acting on the entire thickness of the laminate.  The stress $\\sigma_{xx}$ will vary across the laminate thickness because the stiffness varies with $z$, and possibly because the laminate is being bent.  The average value of $\\sigma_{xx}$ across the thickness of the laminate is $N_x / H$.  \n\n\\begin{figure}[tb]\n  \\centering\n   \\includegraphics[width = 0.48\\textwidth, trim = 10  00 10 10, clip = true, keepaspectratio = true]{Nlaminate.png}\n   \\includegraphics[width = 0.50\\textwidth, trim = 10  15 10 10, clip = true, keepaspectratio = true]{Mlaminate.png}\n   \\caption{The in-plane loads per unit width (left) and moments per unit width (right) on a laminate.}\n   \\label{Nfig}\n\\end{figure}\n\n\nSimilarly, the vector of moments per unit width $\\{M\\}$ is defined as\n\\begin{equation}\n   \\left\\{ \\begin{array}{c}\n     M_x \\\\ M_y \\\\ M_{xy}\n   \\end{array} \\right\\}\n   = \\bigintss_{-H/2}^{H/2} \n    \\left\\{ \\begin{array}{c}\n           \\sigma_{xx}  \\\\  \\sigma_{yy}  \\\\   \\sigma_{xy}\n           \\end{array} \\right\\}\n      z \\ud z\n  \\label{Mdef}\n\\end{equation}\nThese are also sketched in Fig.~\\ref{Nfig}, where you can see that $M_x$ and $M_y$ are bending moments, while $M_{xy}$ is a twisting moment in the $x$--$y$ coordinate system.  \n\n\n\n\\subsection*{Kirchoff-Love Hypothesis}\n\nWe would like to relate $\\{ N \\}$ and $\\{ M \\}$ to the deformation of the laminate.  To do this, classical lamination theory uses the Kirchoff-Love hypothesis.  This states that any material line initially normal to the $x$--$y$ plane remains straight and normal during deformation.  This is the laminated-plate analogy of slender beam theory.  However, while both a plate and a beam can bend in response to $M_x$, a plate can also bend in response to $M_y$ and twist in response to $M_{xy}$.  \n\nWith this hypothesis, the in-plane strains at any height $z$ are related to the strains on the midplane, which are $\\varepsilon^0_{xx}$, $\\varepsilon^0_{yy}$, and $\\gamma^0_{xy}$, and to the midplane curvatures by\n\\begin{equation}\n\\renewcommand\\arraystretch{1.2}\n        \\left\\{ \\begin{array}{c}\n           \\varepsilon_{xx}  \\\\  \\varepsilon_{yy}  \\\\  \\gamma_{xy}\n           \\end{array} \\right\\}\n           =\n        \\left\\{ \\begin{array}{c}\n           \\varepsilon^0_{xx}  \\\\  \\varepsilon^0_{yy}  \\\\  \\gamma^0_{xy}\n           \\end{array} \\right\\}\n           + z\n        \\left\\{ \\begin{array}{c}\n           \\kappa_{xx}  \\\\  \\kappa_{yy}  \\\\  \\kappa_{xy}\n           \\end{array} \\right\\}\n     \\label{Kirchoff}\n\\end{equation}\nIn the absence of curvature, every layer in a laminate has the same in-plane strain.  With curvature, strain increases linearly with $z$, in proportion to the corresponding component of curvature.  For example, a positive $\\kappa_{xx}$ stretches the layers above the midplane, and compresses the layers below the midplane.  \n\n\\subsection*{Laminate Stiffness Equations}\n\nEquations~(\\ref{laminaQ}--\\ref{Kirchoff}) can be combined to write an overall relationship between the forces and moments on the laminate and its midplane strains and curvatures.  That equation is\n\\begin{equation}\n\\renewcommand\\arraystretch{1.2}\n   \\left\\{ \\begin{array}{c}\n     N_x \\\\ N_y \\\\ N_{xy} \\\\  M_x \\\\ M_y \\\\ M_{xy}\n   \\end{array} \\right\\}\n   =\n\\renewcommand\\arraystretch{2}\n   \\left[ \\begin{array}{c|c}\n            A & B \\\\\n            \\hline\n            B & D\n      \\end{array} \\right]\n\\renewcommand\\arraystretch{1.2}\n        \\left\\{ \\begin{array}{c}\n           \\varepsilon^0_{xx}  \\\\  \\varepsilon^0_{yy}  \\\\  \\gamma^0_{xy}  \\\\ \\kappa_{xx}  \\\\  \\kappa_{yy}  \\\\  \\kappa_{xy}\n           \\end{array} \\right\\}\n     \\label{laminateStiffness}     \n\\end{equation}\nThe $6 \\times 6$ matrix on the right-hand side of this equation contains several $3 \\times 3$ sub-matrices, which are defined as\n\\begin{align}\n     [A] &= \\int_{-H/2}^{H/2} \\: [Q(z)] \\: \\ud z  \\label{Amatrix} \\\\\n     [B] &= \\int_{-H/2}^{H/2} \\: [Q(z)] \\: z \\ud z \\label{Bmatrix}  \\\\\n     [D] &= \\int_{-H/2}^{H/2}\\: [Q(z)] \\: z^2 \\ud z  \\label{Dmatrix}\n\\end{align}\nThe plane-strain stiffness matrix $[Q]$ is a function of $z$ because different layers have different fiber orientation.  We can see that $[A]$ relates the midplane strains to the in-plane loads $\\{ N \\}$, while $[D]$ relates the the midplane curvatures to the moments $\\{ M \\}$.  The $[B]$ matrix describes coupling, either between curvature and in-plane loads or between in-plane strains and moments.  If the laminate is symmetric about the midplane, i.e., if $[Q(z)] = [Q(-z)]$, then $[B] = 0$ and there is no coupling.  \n\nTo compute these matrices in a practical situation (and in \\texttt{Clayer2laminate}), divide the laminate into $n$ discrete layers, and treat each layer as having a uniform $[Q]$.  Number the layers $i = 1$ to $n$ from the bottom of the laminate to the top, and let $[Q_i]$ be the plane-strain stiffness matrix for layer $i$.  Define $z_i$ such that layer $i$ extends from $z_{i-1}$ to $z_{i}$, with $z_0 = -H/2$ and $z_n = H/2$.  Now Eqns.~(\\ref{Amatrix}--\\ref{Dmatrix}) can be integrated analytically for each layer, and the matrices computed as\n\\begin{align}\n     [A] &= \\sum_{i=1}^n \\: [Q_i] \\: \\left( z_i - z_{i-1} \\right)  \\label{Asum} \\\\\n     [B] &= \\sum_{i=1}^n  \\: [Q_i] \\: \\left( \\frac{z^2_i - z^2_{i-1}}{2} \\right)  \\label{Bsum}  \\\\\n     [D] &= \\sum_{i=1}^n  \\: [Q_i] \\: \\left( \\frac{z^3_i - z^3_{i-1}}{3} \\right)  \\label{Dsum}\n\\end{align}\n$[A]$, $[B]$ and $[D]$ fully describe the elastic behavior of the laminate, and they are returned by \\texttt{Clayer2laminate}.  \n\n\\subsection*{Extracting Tensile and Flexural Moduli}\n\nAs discussed in Section~8.1.5, any engineering constant like Young's modulus is defined in terms of a mechanical test where loads are applied and deformations are measured.  For the tensile modulus in the $x$ direction, a stress $\\sigma_{xx}$ is applied, with all other stresses equal to zero, and the modulus is the ratio of the applied stress to $\\varepsilon_{xx}$.  For a laminate we'll used the midplane strain, and also require that there be no moments applied.  Then, the $x$-direction tensile modulus is\n\\begin{equation}\n    E^t_{xx} = \\frac{\\sigma_{xx}}{\\varepsilon^0_{xx}}   = \\frac{N_{x}/H}{\\varepsilon^0_{xx}} \n    \\label{EtensileDef}\n \\end{equation}\nWe have used a superscript $t$ to indicate that this is a tensile modulus, and the second expression replaces the average stress $\\sigma_{xx}$ with the load per unit width $N_x$.  A similar expression gives the $y$-direction tensile modulus.\n\nTo find the flexural modulus in the $x$ direction, one subjects the sample to a bending test where a moment $M_x$ is applied, with no other loads or moments, and the curvature $\\kappa_{xx}$ is determined by measuring the deflection.  If this test were performed on a homogeneous beam of width $b$ and thickness $H$, the moment-curvature relationship would be\n\\begin{equation}\n   M_x b = E^f_{xx} I \\, \\kappa_{xx} = \\frac{E^f_{xx} b H^3}{12} \\kappa_{xx}\n   \\label{momentCurvature}\n\\end{equation}\nHere $I = bH^3/12$ is the moment of inertia of the cross-section, and the superscript $f$ on $E$ indicates a flexural modulus.  Note that $M_x$ is a moment per unit width, so the total applied moment is $M_x b$.  We can cancel $b$ from both sides and rearrange this equation to get the effective flexural modulus,\n\\begin{equation}\n   E^f_{xx} = \\frac{12 M_x}{H^3 \\kappa_{xx}}\n   \\label{EflexDef}\n\\end{equation}\nAnalogous equations apply in the $y$ direction.  \n\nTo apply these results to a specific laminate, we need to find the midplane strain and the midplane curvature for the two load cases.  To do this numerically, invert the $6 \\times 6$ matrix from the right-hand side of Eqn.~(\\ref{laminateStiffness}).  The resulting matrix seems to have no official title, so we'll call it the laminate compliance matrix $[S^\\mathrm{lam}]$:\n\\begin{equation}\n    [S^\\mathrm{lam}] \n    = \n   \\left[ \\begin{array}{c|c}\n            A & B \\\\\n            \\hline\n            B & D\n      \\end{array} \\right] ^{-1}\n   \\label{SlamDef}\n\\end{equation}\nNow the strain-stress relationship for the laminate is\n\\begin{equation}\n\\renewcommand\\arraystretch{1.2}\n        \\left\\{ \\begin{array}{c}\n           \\varepsilon^0_{xx}  \\\\  \\varepsilon^0_{yy}  \\\\  \\gamma^0_{xy}  \\\\ \\kappa_{xx}  \\\\  \\kappa_{yy}  \\\\  \\kappa_{xy}\n           \\end{array} \\right\\}\n           = [S^\\mathrm{lam}] \n\\renewcommand\\arraystretch{1.2}\n   \\left\\{ \\begin{array}{c}\n     N_x \\\\ N_y \\\\ N_{xy} \\\\  M_x \\\\ M_y \\\\ M_{xy}\n   \\end{array} \\right\\}\n     \\label{laminateCompliance}     \n\\end{equation}\nFor a tensile test, with all loads and moments zero except $N_x$, the midplane strain is $\\varepsilon^0_{xx} = S^\\mathrm{lam}_{11} N_x$.  Using this in Eqn.~(\\ref{EtensileDef}), we can calculate the laminate's tensile modulus in the $x$ direction as\n\\begin{equation}\n     E^t_{xx} = \\frac{1}{S^\\mathrm{lam}_{11} H} \n     \\label{EtxxFinal}\n \\end{equation}\n Similarly, the tensile modulus in the $y$ direction is\n\\begin{equation}\n     E^t_{yy} = \\frac{1}{S^\\mathrm{lam}_{22} H} \n     \\label{EtyyFinal}\n \\end{equation}\n For a bending test in the $x$ direction, the moment and curvature are related by $\\kappa_{xx} = S^\\mathrm{lam}_{44} M_x$.  Substituting this into Eqn.~(\\ref{EflexDef}), we obtain an equation for the flexural modulus of the laminate in the $x$ direction,\n \\begin{equation}\n     E^f_{xx} = \\frac{12}{S^\\mathrm{lam}_{44} H^3}\n     \\label{EfxxFinal}\n\\end{equation}\nThe $y$-direction flexural modulus is found similarly,\n \\begin{equation}\n     E^f_{yy} = \\frac{12}{S^\\mathrm{lam}_{55} H^3}\n     \\label{EfyyFinal}\n\\end{equation}\n Equations~(\\ref{EtxxFinal}--\\ref{EfyyFinal}) are implemented in \\texttt{Clayer2laminate}.  \n  For an example calculation, see \\break \\texttt{LaminatedPlateProperties.mlx}.\n\n\n\\end{document}", "meta": {"hexsha": "9619e00fba0d34f55612e3a08402a9bcb46547a8", "size": 19201, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Documentation/LaTeX Source Files/LaminateTheory.tex", "max_stars_repo_name": "charlestucker3/Fiber-Orientation-Tools", "max_stars_repo_head_hexsha": "4047e06f2bf88f349be494c7078a7101e61f57b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-19T20:38:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T20:38:27.000Z", "max_issues_repo_path": "Documentation/LaTeX Source Files/LaminateTheory.tex", "max_issues_repo_name": "charlestucker3/Fiber-Orientation-Tools", "max_issues_repo_head_hexsha": "4047e06f2bf88f349be494c7078a7101e61f57b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Documentation/LaTeX Source Files/LaminateTheory.tex", "max_forks_repo_name": "charlestucker3/Fiber-Orientation-Tools", "max_forks_repo_head_hexsha": "4047e06f2bf88f349be494c7078a7101e61f57b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 61.3450479233, "max_line_length": 547, "alphanum_fraction": 0.649497422, "num_tokens": 6357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.3452606306180124}}
{"text": "\\pagenumbering{arabic}\n\\setcounter{page}{1}\n\n\\chapter{Introduction}\n\n\\section{Magnetohydrodynamics}\n\n\n\n\\subsection{Navier-Stokes}\n\n\\subsection{Maxwell}\n\n\\section{A model problem}\n\nstationary incompressible and resistive magnetohydrodynamics (MHD) system:\n\\begin{subequations}\n\\label{eq:mhd}\n\\begin{alignat}2\n\\label{eq:mhd1} - \\nu  \\, \\Delta\\uu{u} + (\\uu{u} \\cdot \\nabla)\n\\uu{u}+\\nabla p - \\kappa\\,\n(\\nabla\\times\\uu{b})\\times\\uu{b} &= \\uu{f} & \\qquad &\\mbox{in $\\Omega$},\\\\[.1cm]\n\\label{eq:mhd2}\n\\nabla\\cdot\\uu{u} &= 0 & \\qquad &\\mbox{in $\\Omega$},\\\\[.1cm]\n\\label{eq:mhd3}\n\\kappa\\nu_m  \\, \\nabla\\times( \\nabla\\times \\uu{b})\n+ \\nabla r\n- \\kappa \\, \\nabla\\times(\\uu{u}\\times \\uu{b}) &= \\uu{g} & \\qquad &\\mbox{in $\\Omega$},\\\\[.1cm]\n\\label{eq:mhd4} \\nabla\\cdot\\uu{b} &= 0 & \\qquad &\\mbox{in\n$\\Omega$}.\n\\end{alignat}\n\\end{subequations}\n\n\\begin{subequations}\n\\label{eq:bc}\n\\begin{alignat}2\n\\label{eq:bc1} \\uu{u} &= \\uu{u_D} & \\qquad &\\mbox{on $\\partial\\Omega$},\\\\[.1cm]\n\\label{eq:bc2}\n   \\uu{n}\\times\\uu{b} &= \\uu{n} \\times \\uu{b_D} & \\qquad &\\mbox{on $\\partial\\Omega$},\\\\[.1cm]\n\\label{eq:bc3}      r &=0 &\\qquad &\\mbox{on $\\partial\\Omega$},\n\\end{alignat}\n\\end{subequations}\n\n\\section{Finite element methods}\n${\\mathcal P}_{k}$: the space of polynomials of total degree at most $k$\n$ \\uu{R}_k$: the space of homogeneous vector polynomials of total degree $k$ that are orthogonal to the position vector $\\uu{x}$\n\n\\section{Iterative Methods}\n\n\\section{Objectives and contributions}\n\n\n%{\\bf [ changed order of equations to $(u,p,b,r)$] }\n% Here, $\\Omega$ is a bounded simply-connected Lipschitz polyhedron in~$\\mathbb{R}^3$, with a connected boundary~$\\partial\\Omega$. The unknowns are the velocity~$\\uu{u}$, the hydrodynamic pressure~$p$, the magnetic field $\\uu{b}$, and the Lagrange multiplier $r$ associated with the divergence constraint on the magnetic field. The functions $\\uu{f}$ and $\\uu{g}$ represent\n% external force terms.\n\n% The equations \\eqref{eq:mhd} are characterized by three dimensionless parameters: the hydrodynamic Reynolds number ${\\rm Re}=\\nu^{-1}$, the magnetic Reynolds number ${\\rm Rm}~=~\\nu_m^{-1}$, and the coupling number~$\\kappa$. For further discussion of these parameters and their typical values, we refer the reader to~\\cite{ArmeroSimo96, Gerbeau2006, Roberts67}. We consider the following homogeneous and inhomogeneous Dirichlet boundary conditions:\n% with $\\uu{n}$ being the unit outward normal on $\\partial\\Omega$. By taking the divergence of the magnetostatic equation~(\\ref{eq:mhd3}), we obtain the Poisson problem\n% \\begin{equation}\n% \\label{eq:zero-r} \\Delta r =\\nabla \\cdot \\uu{g} \\quad \\mbox{in\n% $\\Omega$}, \\qquad r=0 \\quad\\mbox{on $\\partial\\Omega$}.\n% \\end{equation}\n% Since $\\uu{g}$ is divergence-free in physically relevant applications, the multiplier $r$ is typically zero and its primary purpose is to ensure stability; see also~\\cite{Greif10}.\n\n% Our goal in this paper is to derive a scalable numerical solution procedure for solving \\eqref{eq:mhd}-\\eqref{eq:bc}. We first present in Section~\\ref{sec:discretization} the finite element discretization and the structure of the matrices that arise throughout the nonlinear iterations. In Section~\\ref{sec:preconditioning} we introduce the proposed preconditioners for the indefinite linear systems that arise; our ideas are based on combining preconditioners for the incompressible Navier-Stokes and Maxwell sub-systems appearing  in the MHD system~\\eqref{eq:mhd1}--\\eqref{eq:mhd4} while taking into account the presence of coupling terms. Spectral analysis is performed in Section~\\ref{sec:mhd_eigenvalue}. {\\bf [DS: More precise and quote earlier papers]}. In Section~\\ref{sec:decoupling} we consider circumstances where the incompressible Navier-Stokes and the Maxwell systems can be decoupled; in such cases the preconditioning approach may be significantly simplified. In Section~\\ref{sec:numerical_results_mhd_\n% solver} we provide preliminary results in two dimensions that show that our numerical  solution techniques are feasible and reasonably scalable. Finally, we offer some concluding remarks in Section~\\ref{sec:conclusions}.\n", "meta": {"hexsha": "c95acc223c8c0cdee95d92644bd331a021641fff", "size": 4132, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "MHD/THESISnew/Intro/Intro.tex", "max_stars_repo_name": "wathen/PhD", "max_stars_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-10-25T13:30:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T21:27:30.000Z", "max_issues_repo_path": "MHD/THESISnew/Intro/Intro.tex", "max_issues_repo_name": "wathen/PhD", "max_issues_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MHD/THESISnew/Intro/Intro.tex", "max_forks_repo_name": "wathen/PhD", "max_forks_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-28T16:12:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-13T13:59:44.000Z", "avg_line_length": 61.671641791, "max_line_length": 1020, "alphanum_fraction": 0.7347531462, "num_tokens": 1280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.34513531479044884}}
{"text": "\\input{docs/preamble}\n\\title{The Speed of Light}\n\\author{Max Bigras and David Frawley}\n\n\\begin{document}\n\n\\maketitle\n\n\\section{The speed of light}\n\\subsection{Light speed in air}\nUsing a pulse modulated diode laser and fast photodiode detector we measured the time lag between the laser pulse and detection. We adjusted the distance the laser pulse traveled in air using mirrors. By plotting distance vs. time, shown in Figure \\ref{air}, we determined $c^{\\mathrm{air}}_{\\mathrm{exp}} = 3.02 \\times 10^{8} \\pm 0.03 $ m/s, which agrees with the accepted value, $c^{\\mathrm{air}} = 2.99792458 \\times 10^{8}$ m/s.\n\\begin{figure}[H]\n  \\includegraphics[totalheight=0.6\\textwidth]{figs/air_final}\n  \\caption{Determining the speed of light in air}\n  \\label{air}\n\\end{figure}\n\n\\subsection{Light speed in an optical fiber}\nUsing a pulse modulated diode laser and fast photodiode detector we measured the time lag between the laser pulse and detection. We adjusted the distance the laser pulse traveled in an optical fiber by using different lengths of fiber. By plotting distance vs. time, shown in Figure \\ref{fiber}, we determined $c^{\\mathrm{fiber}}_{\\mathrm{exp}} = 1.85 \\times 10^{8} \\pm 0.03 $ m/s. The refractive index for a material is given by the equation\n\\begin{equation}\nn^{\\mathrm{material}} = c^{\\mathrm{vacuum}}/c^{\\mathrm{material}}\n\\label{n}\n\\end{equation}\n\nApplying Equation \\ref{n} and using $c^{\\mathrm{air}}_{\\mathrm{exp}} \\approx c^{\\mathrm{vacuum}}$ we determined $n^{\\mathrm{fiber}}_{\\mathrm{exp}} = 1.63 \\pm 0.01$ which agrees with the accepted value for the core of a optical fiber $n^{\\mathrm{fiber}} \\approx 1.62$ \\cite{wiki}.\n\n\\begin{figure}[H]\n  \\includegraphics[totalheight=0.6\\textwidth]{figs/fiber_final}\n  \\caption{Determining the speed of light in optical fiber}\n  \\label{fiber}\n\\end{figure}\n\\subsection{Light speed in a coaxial cable}\nWe propagated electromagnetic waves in a RG-6/U coaxial cable terminated by a resistor box. Depending on the resistance of the box we observed the signal at the end of the cable be: reflected, inverted and absorbed. We measured the speed of an electromagnetic wave in the cable, $c^{\\mathrm{cable}} = 2.32 \\times 10^{8}$. We determined the velocity factor = 0.79, which agrees with the accepted velocity factor for a RG-6/U coaxial cable = 0.82 \\cite{cable}.\n\n\\begin{thebibliography}{99}\n\n\\bibitem{manual} Physics Dept., ``The Speed of Light'', Quantum Lab,\n  California Polytechnic University, (2013).\n\n\\bibitem{wiki} ``Optical fiber.'' Wikipedia: The Free Encyclopedia. Wikimedia Foundation, Inc., 05 December 2013. Web.\n\n\\bibitem{cable} C. R. Parashare, and R. F. Bradley, ``75 $\\Omega$ Transmission System'', National Radio Astronomy Observatory Technology Center, Virginia, 2006.\n\n\\end{thebibliography}\n\n\\end{document}\n", "meta": {"hexsha": "15cf8db9d4d49da994feb97b07ec6a0b16fada1d", "size": 2786, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "senior_project/report/speed_of_light/report/lab_report.tex", "max_stars_repo_name": "mbigras/physics_projects", "max_stars_repo_head_hexsha": "7dd29707b3ac8adea7ed8b63786245e34097345e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-12-05T23:34:30.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-11T19:45:07.000Z", "max_issues_repo_path": "senior_project/report/speed_of_light/report/lab_report.tex", "max_issues_repo_name": "mbigras/physics_projects", "max_issues_repo_head_hexsha": "7dd29707b3ac8adea7ed8b63786245e34097345e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "senior_project/report/speed_of_light/report/lab_report.tex", "max_forks_repo_name": "mbigras/physics_projects", "max_forks_repo_head_hexsha": "7dd29707b3ac8adea7ed8b63786245e34097345e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.2765957447, "max_line_length": 458, "alphanum_fraction": 0.7465900933, "num_tokens": 794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.6224593241981982, "lm_q1q2_score": 0.3451353109071283}}
{"text": "\\documentclass[10pt]{article}\n\\usepackage{multicol, caption}\n\\usepackage[margin=1in]{geometry}\n\\usepackage{graphicx}\n\\newenvironment{Figure}\n  {\\par\\medskip\\noindent\\minipage{\\linewidth}}\n  {\\endminipage\\par\\medskip}\n\\graphicspath{ {images/} }\n\\title{\\textbf{Real-time Mesh Deformation using Volumetric Graph Laplacian}}\n\\author{Elias Eberhardsson}\n\\date{}\n\\begin{document}\n\\maketitle\n\n\\textit{\nThis paper describes the implementation and testing of a mesh deformation method using volumetric graph laplacian for use in real-time. First a graph of nodes in a crystal structure inside the 3D mesh is constructed. The nodes are connected together and linked with the mesh. These nodes and their connections are used to preserve volumetric detail when deforming vertices contained in the mesh. The laplacian on vertices based on this graph is how volumetric details are preserved, coupled with the laplacian on the mesh, which preserves outer details. And such the deformed locations are calculated. This method should ideally be used together with quadratic minimization, but due to the time constraint this was left out in favour of a simple interpolation of new vertex position and the two laplacian values.\n}\n\\begin{multicols}{2}\n\\section{Introduction}\nMesh deformation has been interesting to computer scientists for as long as we have been able to draw vertices on the screen. Much research has been done and many many methods have been created and put forth through scientific publications. \n\nThere are many applications for mesh deformation: animation, modelling and simulations are some of the more prominent ones.\n\nThe method showcased in this paper aims to in real-time deform a mesh while balancing volumetric and surface details and such prevent self-intersection and unnatural looking bends and twists. \nThe method builds on the Volumetric Graph Laplacian (VGL), used in [Zhou et al. 2005], which owes itself to differential domain techniques and graph theory. This represents detail as points differences from origo to be balanced between.\n\\section{Related work}\n\nThis project is an attempt at implementing the method described in the paper Large Mesh Deformation Using the Volumetric Graph Laplacian [Zhou et al. 2005] which was an attempt at much better preserve detail and volume when doing deformations such as bending and twisting parts of a mesh. This method used quadratic minimization on energy functions to as closely as possible simulate a real deformation.\n\nSupposed to be used but cut due to time constraints are WIRE deformation [Singh and Fiume 1998] where a method of connecting vertices in a mesh on a curve and deforming with some constraints to how the curve may bend. This combined with volumetric graph laplacian is what is described in [Zhou et al. 2005].\n\nAs mentioned in the introduction this is also closely related to differential domain techniques [Yu et al. 2004] and spectral graph theory [Chung 1997].\n\n\\section{Deformation on Volumetric Graphs}\n\nGiven a mesh \\textit{M = (V, K, N)}, where \\textit{ \\[ V = \\{ p_i \\in R^3|1\\leq i \\leq n \\} \\] } are the vertex positions as points in 3D-space and \\textit{K} is the connective data to each of the adjacent volumetric nodes in the 3-dimensional array that is used to store them: \\textit{ \\[ K = \\{ I_i \\in R^3|1\\leq i \\leq m \\} \\] } And \\textit{N} is similarily the conncetive data to adjacent vertices in the mesh: \\textit{ \\[ N = \\{ N_i \\in R|1\\leq i \\leq k \\} \\] } Using this as a starting point we can lay out the details of the deformation method.\n\\subsection{Volumetric graph}\n\\begin{Figure}\n\t\\centering\n\t\\includegraphics[width=\\linewidth]{graph1.png}\n\t\\captionof{figure}{Graph structure.}\n\\end{Figure}\n\\begin{Figure}\n\t\\centering\n\t\\includegraphics[width=\\linewidth]{graph2.png}\n\t\\captionof{figure}{Final volume graph.}\n\\end{Figure}\nTo construct the graph that is used to represent volume in the deformation we build two 3-dimensional fields of nodes. The distance, \\textit{d}, between each node is set to the average edge-distance in the mesh. The fields are offset by half of \\textit{d} in each direction to create a structually sound, crystal-like, volume, see figure 2.\n \nWhen this is done all nodes which are not contained within the mesh are discarded. Finally each node in the resulting graph are connected to each of its neighbors and any mesh-vertices within \\textit{d\\textbackslash2} is connected and that vertex is also given information on which connections that have been made, see figure 3.\n\nThe method used to determine whether a node is contained within the mesh is to calculate triangle-ray intersections from the node in an arbitrary direction. Given an even number of intersections the node is outside of the mesh, and given an uneven number, the node is contained within the mesh.\n\n\\subsection{Laplacian of graph}\nThe laplacian of a graph is the same as the laplacian operator on manifolds [Chung 1997] and computes the difference of a point \\textit{p} and all of its adjacencies. Given a weight \\textit{w} for each neighbor that satisfies \\[ \\sum_{j\\in N_i \\cup K_i} w_{ij} = 1\\] we linearly compute the difference of the graph adjacencies: \\[ \\bigtriangledown_G(p_i) = p_i - \\sum_{j\\in K_i}w_{ij}p_j \\] Similarly we do this for mesh adjacencies: \\[ \\bigtriangledown_M(p_i) = p_i - \\sum_{j\\in N_i}w_{ij}p_j \\] Here $\\bigtriangledown$ is the laplacian operator and \\textit{G} and \\textit{M} is the volumetric graph and the 3D mesh respectivly.\n\nThis gives us two terms, one which encodes volumetric detail and one that contains surface detail.\n\\subsection{Deformation}\nGiven a point \\textit{q\\textsubscript{i}} that is the target deformation point for \\textit{p\\textsubscript{i}} we need to find the point \\textit{p`\\textsubscript{i}} that balances volume and detail but still deforms \\textit{p\\textsubscript{i}} satisfactorily. \n\nWe have the three terms a, b, and c: \n\\[ a = \\bigtriangledown_G(h_{i}) - \\bigtriangledown_G(p_i)\\]\n\\[ b = h_i - q_i\\]\n\\[ c = \\bigtriangledown_M(h_{i}) - \\bigtriangledown_M(p_i)\\]\nwhere \\[ h_i = p_i + \\gamma*(p_i - q_i)\\]\n$\\gamma \\in \\{ 0..1 \\}$ gives $h_i$ an approximate value of a deformed location. $\\gamma$ is set to 0.6 in our implementation.\n\nThe final deformed location $p`_i$ is calculated:\n\\[ p`_i = a*(1 - \\alpha - \\beta) + b*\\alpha + c*\\beta \\]\n$\\beta$ balances between surface and volume details. $\\beta = n/N$ works well where n is the number of vertices on the mesh and N is the count of the volumetric nodes contained in the graph. \n\nExperimenting with $\\alpha$ is needed to achive good results based on the mesh that is to be deformed, but 0.4 seems like a good number, as used in [Zhout et al. 2005].\n\n\\subsection{Propagation}\nWhen a new position has been calculated we use it to get the relative translation needed to be done. $T = p`_i - p_i$. The translation \\textit{T} is propagated throughout the mesh using a simple propagation scheme. So that each of $p_i$'s neighbor $n$ is translated $T*(1/||p_n - p_i||)$.\n\n\\section{Results}\n\nThe results were subpar if you were to compare this to any proper implementation using energy functions and quadratic minimization. Also a better way to propagate would have been great to get good looking reults. \n\n\\begin{Figure}\n\t\\centering\n\t\\includegraphics[width=\\linewidth]{mondef.png}\n\t\\captionof{figure}{Face deformation.}\n\\end{Figure}\n\nSmall deformations work fine, moving parts of a face as an example looks fine, as shown in figure 4. But trying to bend bigger shapes do not come out good without much tweaking to the balancing and changes to the weight used in propagation, shown in figure 5 and 6.\n\n\\begin{Figure}\n\t\\centering\n\t\\includegraphics[width=\\linewidth]{korv1.png}\n\t\\captionof{figure}{Pre deformed.}\n\\end{Figure}\n\\begin{Figure}\n\t\\centering\n\t\\includegraphics[width=\\linewidth]{korv2.png}\n\t\\captionof{figure}{Post deformed.}\n\\end{Figure}\n\n\\section{Conclusion and Reflections}\n\nOur implementation of these deformation algorithms are subpar at best. We underestimated the work and planning needed to properly implement and use VGL [Zhou et al. 2005], completely missing the need for WIRE deformation to do large deformations the first ten times I read the paper.\n\nWe had intended to use quadratic minimization on energy functions, as laid out in [Zhou et al. 2005], but we did not understand the bounds used nor had we enough time to implement or get used to any library needed for such computation. And as such our simple interpolation does prove decent at preserving volume and detail in small deformation and does prevent self-intersection. But it fails at any large deformation, or any greater deformations tried, which results in odd looking results.\n\nInstead of simply a translation to be propagated, it should be a transformation-matrix, otherwise proper turning and twisting would have a hard time looking proper.\n\nIf I got to do this all over again, I would plan in much greater detail all parts of the implementation, choice of datastructures used and all things that actually needed to be understood.\n\n\\begin{thebibliography}{7}\n\\bibitem{zhou} \nKun Zhou, Jin Huang, John Snyder, Xinguo Liu, Hunun Bao, Baining Guo and Heung-Yeung Shun. 2005.\n\\textit{Large Mesh Deformation Using the Volumetric Graph Laplacian}. \nACM Trans. Graphics (Proc. ACM SIGGRAPH), vol. 24, no. 3, pp. 496-503.\n \n\\bibitem{moller} \nTomas M{\\\"o}ller. 1997.\n\\textit{A Fast Triangle-Triangle Intersection Test}.\nJournal of Graphics Tools, 2(2):25-30.\n \n\\bibitem{moller2}\nTomas M{\\\"o}ller and Ben Trumbore. 1997.\n\\textit{Fast, Minimum Storage Ray/Triangle Intersection}.\nJournal of Graphics Tools, 2(1):21-28.\n\n\\bibitem{chung} \nChung F.R.K. 1997.\n\\textit{Spectral Graph Theory}.\nCBMS 92, AMS.\n\n\\bibitem{gingh} \nKaran Singh and Eugene Fiume. 1998.\n\\textit{Wires: A Gerometric Deformation Technique}.\nSIGGRAPH 98 Conference Proceedings, pages 405-414.\n\\end{thebibliography}\n\n\n\n\\end{multicols}\n\\end{document}\n", "meta": {"hexsha": "481545216a66acb999f9d30b94c8a97807e0dff7", "size": 9896, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper-eliebe-5/paper-eliebe-5.tex", "max_stars_repo_name": "eliebe-5/vgl-deform", "max_stars_repo_head_hexsha": "d82e12587cc9aa5618ecf110b50b9902fbed6300", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paper-eliebe-5/paper-eliebe-5.tex", "max_issues_repo_name": "eliebe-5/vgl-deform", "max_issues_repo_head_hexsha": "d82e12587cc9aa5618ecf110b50b9902fbed6300", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper-eliebe-5/paper-eliebe-5.tex", "max_forks_repo_name": "eliebe-5/vgl-deform", "max_forks_repo_head_hexsha": "d82e12587cc9aa5618ecf110b50b9902fbed6300", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 70.1843971631, "max_line_length": 812, "alphanum_fraction": 0.7747574778, "num_tokens": 2577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3451353070238076}}
{"text": "\\documentclass[leqno,11pt,a4paper]{article}\n\\usepackage{amsmath,amsthm}\n\n\\textheight=9.0truein\n\\hoffset=-0.4truein\n\\textwidth=6.1truein\n\\voffset=-0.5truein\n\n\\input{header.tex}\n\\input{defs_AHM.tex}\n\n%\\usepackage{mathabx} %package utilisé pour définir \"\\lll\" comme le symbole d'absolue continuité de 2 mesures\n\\usepackage[toc,page]{appendix} %package utilisé pour l'appendice voir : https://texfaq.org/FAQ-appendix\n\\usepackage{tikz}\n%\\usetikzlibrary{shapes}\n%\"Ce document a été généré avec la version de TikZ \\pgfversion .\" : à mettre après \"begin{document}\" si affichage souhaité...\n\\newtheorem{rem}{Remark}\n\\setcounter{secnumdepth}{3} %permet de numéroter les sous-sous-sections\n\n\\begin{document}\n\\title{A quantitative Mac Diarmid's inequality for geometrically ergodic Markov chains}\n%\\title{Density estimation for RWRE : a Bayesian non-parametric approach}\n%\\author{A. Havet, M. Lerasle, E. Moulines and E. Vernet}\n\\author{D. Belomestny, E. Moulines and S. Samsonov}\n\\maketitle\n\n\\begin{abstract}\n We state and prove a quantitative version of the bounded difference inequality for geometrically ergodic Markov chains.\n Our proof uses the same martingale decomposition as \\cite{MR3407208} but, compared to this paper, the exact coupling argument is modified to fill a gap between the strongly aperiodic case and the general aperiodic case.\n\\end{abstract}\n\n\n\\noindent\n{\\small {\\bf Keywords:} Concentration inequalities ; Markov chains ; Geometric ergodicity ; Coupling.}\n\n\\noindent\n{\\small {\\bf AMS MSC 2010:} 60J05; 60E15.}\n\n\\section{Introduction}\nThe purpose of this note is to establish a quantitative version of Mc Diarmid's inequality for geometrically ergodic Markov chains.\nLet $X_0,\\ldots,X_{n-1}$ denote independent random variables taking values in a measurable space $(\\sX,\\cX)$ and $c=(c_0,\\ldots,c_{n-1})$ denote a vector of non-negative real numbers. A function  $f:\\sX^n\\to\\Rbb$ satisfies the bounded difference inequality if for all $x=(x_0,\\ldots,x_{n-1})$ and\n$y=(y_0,\\ldots,y_{n-1})\\in \\sX^{n}$, we have\n\\begin{equation}\\label{def:BDP}\n|f(x)-f(y)|\\leqslant \\sum_{i=0}^{n-1}c_i\\indiacc{x_i\\ne y_i}\\eqsp.\n\\end{equation}\nThe bounded difference inequality, first established in \\cite{MR1036755}, shows that for all $t > 0$,\n\\[\n\\Pbb\\big(f(X_0,\\ldots,X_{n-1})-\\Ebb[f(X_0,\\ldots,X_{n-1})]>t\\big)\\leqslant \\rme^{-2t^2/\\|c\\|^2}\\eqsp,\n\\]\nwhere $\\|c\\|^2=\\sum_{i=0}^{n-1}c_i^2$.\nSeveral attempts have been made to extend this result to Markov chains.\nIn \\cite{MR2424985}, the concentration of particular functionals of the form $f(x_0,\\ldots,x_{n-1})=\\sup_{g\\in \\cF}\\sum_{i=0}^{n-1}g(x_i)$, for centered functions $g$ in a class $\\cF$ is established.\nThe concentration of general functionals (satisfying \\eqref{def:BDP}) of geometrically ergodic Markov chains was established in \\cite{MR3407208}, where it is also proved that geometric ergodicity is a necessary assumption. However, the result in \\cite{MR3407208} is not quantitative.\nIt states that for all geometrically recurrent set $C$, there exists a constant $\\beta$, depending on $C$ such that for all $x \\in C$ and $t > 0$,\n\\begin{equation}\n\\label{eq:mcdiarmid-markov}\n\\Pbb_x\\big(f(X_0,\\ldots,X_{n-1})-\\Ebb_x[f(X_0,\\ldots,X_{n-1})]>t\\big)\\leqslant \\rme^{-\\beta t^2/\\|c\\|^2}\\eqsp,\n\\end{equation}\nwhere for any $x\\in\\Xsigma$, $\\Pbb_x$ is the distribution of the Markov chain $\\{X_k\\}_{k=0}^\\infty$ starting from $x$ (see the precise definition below).\nIn many  applications, it is necessary to get the explicit dependence of the constant $\\beta$ as a function of the set $C$.\nIn particular, this problem arises when establishing posterior concentration rates of Bayesian non-parametric estimators; see for example \\cite{rousseau:2016,ghosal:vandervaart:2017} for recent accounts on this theory.\nTo extend these results to Markovian settings, the result of \\cite{MR3407208} cannot be applied directly and a quantitative version of  \\eqref{eq:mcdiarmid-markov} is required, where the dependence of $\\beta$ on constants characterizing the mixing of the Markov chain is needed; see for example \\cite{vernet:2015,lecorff:lerasle:vernet:2018}.\n\n\nA quantitative version of Mc Diarmid's inequality for Markov chains was established in \\cite{paulin:2015}, where the constant $\\beta$ depends here explicitly on the mixing time of the chain.\nThe existence of finite mixing times requires \\emph{uniform} ergodicity of the chain, see for example \\cite[Section 3.3]{MR2095565}, an  assumption that typically fails when the chain takes value in general state spaces.\nIn this note, we prove an extension of Mc Diarmid's inequality to geometrically ergodic Markov chains.\nOur proof is based on  \\cite{MR3407208},\nbut avoids the use of \\cite[Lemma~6]{MR3407208} which requires the construction of an exact coupling.\nExact coupling can actually be built in the strongly aperiodic case but there is a gap in the general aperiodic case.\n\nThe remaining of the paper is decomposed as follows, Section~\\ref{sec:Setting} introduces formally the notations and the assumptions of the main result, which is stated and proved in Section~\\ref{sec:Main}.\n\n\n\\section{Notations and assumptions}\\label{sec:Setting}\nLet $(\\sX,\\cX)$ be a measurable space.\nWe denote by $\\tvdistsym$  the total variation distance between probability measures.\nFor any sequence $x=\\sequence{x}[n][\\Nbb]$ and any non-negative integers $a$ and $b$, with $a\\leqslant b$, let $\\chunk[a]{x}[b]=(x_a,x_{a+1},\\ldots,x_b)$.\nFor any $n\\geqslant 0$ and any vector $c=\\chunk[0]{c}[n-1]\\in \\R^n$, let $\\|c\\|$ denote the Euclidean norm of $c$ and $\\|c\\|_\\infty=\\max_{0\\leqslant i\\leqslant n-1}|c_i|$ denote its sup-norm.\n\n\nWe denote by $(\\sX^{\\Zbb_+},\\cX^{\\otimes\\Zbb_+}, (\\cF_k)_{k\\geqslant 0})$ the canonical filtered space,\n$\\{X_n\\}_{n=0}^\\infty$ the canonical process and $\\theta: \\sX^{\\Zbb_+}\\to\\sX^{\\Zbb_+}$  the shift operator on the canonical space defined, for any $x=(x_{n})_{n\\geqslant 0}\\in \\sX^{\\Zbb_+}$ by $\\theta(x)\\in \\sX^{\\Zbb_+}$, where, for any $n\\geqslant 0$, $\\theta(x)_n=x_{n+1}$.\nSet $\\theta_1=\\theta$ and for $n\\in \\Nbb^*$, define inductively, $\\theta_n=\\theta_{n-1} \\circ \\theta$. We also need to define $\\theta_\\infty$. To this aim, fix an arbitrary $x^*\\in \\Xset$, we define $\\theta_\\infty:\\Xset^\\Nbb \\to \\Xset^\\Nbb$ such that for $z=\\sequence{z}[k][\\Nbb] \\in \\Xset^\\Nbb$, $\\theta_\\infty z\\in \\Xset^\\Nbb$ is the constant sequence  $(\\theta_\\infty z)_k=x^*$ for all $k \\in \\Nbb$.\n\n\nLet $P$ be a Markov kernel on $\\sX \\times \\cX$.\nFor any probability measure $\\xi$ on $(\\Xset,\\Xsigma)$, denote by $\\Pbb_{\\xi}$  the unique probability under which $(X_n)_{n\\geqslant 0}$ is a Markov chain with Markov kernel $P$ and initial distribution $\\xi$ and let $\\Ebb_{\\xi}$ denote the expectation under the distribution $\\Pbb_{\\xi}$.\nRecall that $\\cF_n$ denotes the $\\sigma$-algebra generated by $X_0, \\ldots,X_n$.\nFor any $x\\in \\sX$, let $\\delta_x$ denote the Dirac mass at point $x$.\nWith some abuse of notation, we also denote $\\Pbb_x$ (resp. $\\Ebb_x$) instead of $\\Pbb_{\\delta_x}$ (resp. $\\Ebb_{\\delta_x}$).\n\nFor any $\\cB\\in \\cX$ and any integer $i\\geqslant 0$, let\n\\[\n\\tau_{\\cB}^i=\\inf\\{n\\geqslant i: X_n\\in \\cB\\}=i+\\tau_{\\cB}^0\\circ \\theta^i\n\\qquad \\text{and} \\qquad\n\\sigma_{\\cB}=\\tau_{\\cB}^1=1+\\tau_{\\cB}^0\\circ \\theta\\eqsp.\n\\]\nFor $c = \\chunk[0]{c}[n-1] \\in \\R_+^n$, we denote by  $\\functionboundeddiff{\\sX^n}{c}$  the set of measurable functions $f:\\sX^n\\to\\R$ such that for all $x= (x_0,\\dots,x_{n-1})$ and $y= (y_0,\\dots,y_{n-1})$, $|f(x)-f(y)|\\leqslant \\sum_{i=0}^{n-1} c_i\\indiacc{x_i\\ne y_i}$\nThe main result is established under the following conditions.\n\\begin{itemize}\n\\item[{\\bf H1}] The Markov kernel $P$ is irreducible and aperiodic, with unique invariant probability $\\pi$.\n\\item[{\\bf H2 (drift condition)}] There exist a measurable function $V: X \\rightarrow [1; +\\infty)$, real numbers $\\lambda \\in (0,1)$, $b > 0$ and a non-empty set $\\cC \\in \\cX$ such that for any $x \\in X$,\n\\[\nPV(x) \\leq \\lambda V(x) + b\\indiacc{x \\in \\cC}\n\\]\n%\\item[{\\bf H2}] There exist a non-empty set $\\cC \\in \\cX$ and two real numbers $u>1$ and $M>0$ such that\n%  \\[\\sup_{x\\in \\cC}\\Ebb_x[u^{\\sigma_{\\cC}}]\\leqslant M\\eqsp.\\]\n%\\item[{\\bf H3}] There exist $r\\in (0,1)$ and $L\\geqslant 1$ such that, for any $x$ in the set $\\cC$ of {\\bf H2} and any $n\\geqslant 0$,\n%\\[\n%\\tvdist{\\delta_xP^n}{\\pi} \\leqslant Lr^n\\eqsp,\n%\\]\n%where $\\pi$ is the unique invariant measure granted in {\\bf H1}.\n\\item[{\\bf H3 (V-ergodicity)}] There exist $r \\in (0,1)$, $L \\geqslant 1$ and function $V: X \\rightarrow \\mathbb{R}$ such that for any $x  \\in  X$ and any $n \\geqslant 0$, it holds\n\\[\nd_V(\\delta_xP^n,\\pi) \\leqslant L V(x) r^n\\eqsp,\n\\]\n\\end{itemize}\nwhere $\\pi$ is the unique invariant measure from {\\bf H1}.\n\\par\nWhen the Markov kernel $P$ is uniformly ergodic, then {\\bf H3} holds with $V(x) = 1$.   \n\\par\nNote that \\cite[Proposition 14.3.1]{douc:moulines:priouret:soulier:2018} implies that if Markov kernel $P$ satisfies the drift condition {\\bf H2} with the set $\\cC \\in \\cX$, $\\cC = \\{x: V(x) < d\\}$, then it holds for any $x \\in \\cC$ that\n\\begin{equation}\n\\label{eq:exp_moment_hit}\n\\sup_{x\\in \\cC}\\Ebb_x[\\lambda^{-\\sigma_{\\cC}}]\\leqslant M\\eqsp\n\\end{equation}\nwith some $M$ depending on $V(x)$ and $d$.\n\\par\nThe following Lemma is a coupling result that replaces \\cite[Lemma~6]{MR3407208}. It is instrumental in the sequel.\n\\begin{lemma}\\label{lem:DMPS18}\n For any probability measures $\\xi$ and $\\xi'$ on $(\\sX,\\cX)$, any $n\\geqslant 1$, any $c\\in \\R_+^n$ and any $h\\in \\bB\\Dbb(\\sX^n,c)$,\n\\begin{equation*}\\label{eq:Step1}\n |\\Ebb_\\xi[h(\\chunk[0]{X}[n-1])]-\\Ebb_{\\xi'}[h(\\chunk[0]{X}[n-1])]|\\leqslant 2\\sum_{i=0}^{n-1}c_i \\tvdist{\\xi P^i}{\\xi'P^i} \\leqslant 2\\sum_{i=0}^{n-1}c_i \\vfuncdist{\\xi P^i}{\\xi'P^i} \\eqsp.\n\\end{equation*}\n\\end{lemma}\n\\begin{remark}\n It is possible to avoid the factor $2$ in \\eqref{eq:Step1} under additional technical conditions, for example, when there exists a maximal coupling for $(\\Pbb_\\xi,\\Pbb_{\\xi'})$, see \\cite[Lemma 23.2.1]{douc:moulines:priouret:soulier:2018}.\n\\end{remark}\n\\begin{proof}\nFix an arbitrary\n$x^* \\in \\Xset$. For $i \\in \\{1,\\ldots,n-1\\}$, we set $\\bar{h}_i(\\chunk[i]{x}[n-1])=h(x^*,\\dots,x^*,\\chunk[i]{x}[n-1])$. By convention,\nwe set $\\bar{h}_n$ the constant function $\\bar{h}_n=h(x^*,\\ldots,x^*)$ and $\\bar{h}_0=h$. With these\nnotations, we have the decomposition\n\\[\nh(\\chunk{x})=\\sum_{i=0}^{n-1} \\{\\bar{h}_i(\\chunk[i]{x}[n-1]) - \\bar{h}_{i+1}(\\chunk[i+1]{x}[n-1]) \\} +\\bar{h}_n \\eqsp.\n\\]\nFor all $i \\in \\{0,\\ldots,n-1\\}$ and all $x_i \\in \\Xset$, let\n\\begin{align}\n\\bar{w}_i(x_i)&=\\int \\lrcb{\\bar{h}_i(\\chunk[i]{x}[n-1])-\\bar{h}_{i+1}(\\chunk[i+1]{x}[n-1])}  \\prod_{\\ell=i+1}^{n-1} P(x_{\\ell-1}, \\rmd x_{\\ell})\\eqsp, \\nonumber \\\\\n&=\\int \\lrcb{h(x^*,\\ldots,x^*,\\chunk[i]{x})-h(x^*,\\ldots,x^*,\\chunk[i+1]{x})}  \\prod_{\\ell=i+1}^{n-1} P(x_{\\ell-1}, \\rmd x_{\\ell}) \\eqsp. \\label{eq:delta:diarmid:fond}\n\\end{align}\nIt is easily seen that $\\CPE{\\{\\bar{h}_i(\\chunk[i]{X}[n-1])-\\bar{h}_{i+1}(\\chunk[i+1]{X}[n-1])\\}}{\\cF_{i}}=\\bar{w}_i(X_i)$, $\\Pbb_\\xi-\\as$,  which implies that\n\\[\n\\Ebb_\\xi \\lrb{h(\\chunk{X})}=\\sum_{i=0}^{n-1} \\xi P^i \\bar{w}_i + \\bar{h}_n \\eqsp.\n\\]\nSince  $h \\in\\functionboundeddiff{\\Xset^n}{c}$, \\eqref{eq:delta:diarmid:fond} shows that  $\\supnorm{\\bar{w}_i} \\leq c_i$.\nTherefore,\n\\[\n|\\Ebb_\\xi \\lrb{h(X^{n-1})}-\\Ebb_{\\xi'} \\lrb{h(X^{n-1})} |\\\\\n\\leq \\sum_{i=0}^{n-1} |\\xi P^i \\bar{w}_i-\\xi' P^i \\bar{w}_i| \\leq 2 \\sum_{i=0}^{n-1} c_{i}\\tvdist{\\xi P^{i}}{\\xi' P^{i}} \\eqsp.\n\\]\nThe result now follows from the trivial bound $\\tvdist{\\xi}{\\eta} \\leq \\vfuncdist{\\xi}{\\eta}$ for arbitrary measures $\\xi,\\eta$ given that $V(x) \\geq 1$ for any $x \\in X$.\n\\end{proof}\n\n\\section{Main result}\\label{sec:Main}\nThe main result of this paper  is the following quantitative version of Mac Diarmid's inequality for $V-$ergodic Markov chains under certain drift condition.\n%\\begin{theorem}\\label{thm:ConcMarkQuant}\n %Assume {\\bf H1}, {\\bf H2}, {\\bf H3}. Let $n\\geqslant 1$, $c\\in \\R^n$ and  $f\\in \\functionboundeddiff{\\sX^n}{c}$. Then, for all $x\\in \\cC$ and $t > 0$,\n %\\[\n%\\Pbb_x\\big(f( \\chunk[0]{X}[n-1])-\\Ebb_x[f(\\chunk[0]{X}[n-1])]>t\\big)\\leqslant \\exp\\bigg(-\\frac{\\beta t^2}{\\|c\\|^2}\\bigg)\\eqsp,\n% \\]\n%where $\\beta$ is given by\n %\\[\n %\\beta=\\frac{(1-r\\vee u^{-1/4})^2}{16L}\\bigg(\\frac5{\\log u}+4ML\\bigg)^{-1}\\eqsp.\n %\\]\n%\\end{theorem}\n\\begin{theorem}\\label{thm:ConcMarkVErgodic}\n Assume {\\bf H1}, {\\bf H2} and {\\bf H3} holds with drift function $V(x)$. Let $M$ be a constant from \\ref{eq:exp_moment_hit}, $\\cC = \\{V(x) < d\\}$, $n\\geqslant 1$, $c\\in \\R^n$ and  $f\\in \\functionboundeddiff{\\sX^n}{c}$. Then, for all $x\\in \\cC$ and $t > 0$,\n \\[\n\\Pbb_x\\big(f( \\chunk[0]{X}[n-1])-\\Ebb_x[f(\\chunk[0]{X}[n-1])]>t\\big)\\leqslant \\exp\\bigg(-\\frac{\\beta t^2}{\\|c\\|^2}\\bigg)\\eqsp,\n \\]\nwhere $\\beta$ is given by\n \\[\n \\beta=\\frac{(1-r\\vee \\lambda^{1/4})^2}{16Ld}\\bigg(-\\frac5{\\log \\lambda}+4MLd\\bigg)^{-1}\\eqsp.\n \\]\n\\end{theorem}\n\n\\begin{proof}[Proof of \\Cref{thm:ConcMarkVErgodic}]\nFix $c\\in \\Rbb^n$, $x\\in\\sX$ and $f\\in \\functionboundeddiff{\\sX^n}{c}$. Note that drift condition {\\bf H3} implies that\n\\[\n\\sup_{x\\in \\cC}\\Ebb_x[\\lambda^{-\\sigma_{\\cC}}]\\leqslant M\\eqsp\n\\]\nFollowing \\cite{MR3407208}, we decompose $f(\\chunk[0]{X}[n-1])-\\Ebb_x[f(\\chunk[0]{X}[n-1])]$ into martingale increments by conditioning to the stopping times $\\tau_{\\cC}^i$, $i=0,\\ldots, n-1$.\nFor any integer $i\\in [0,n-1]$, define\n\\[\nG_i=\\Ebb_x\\big[f(\\chunk[0]{X}[n-1])|\\cF_{\\tau_{\\cC}^i}\\big]\\eqsp.\n\\]\nAs $\\tau_{\\cC}^0=0$ $\\Pbb_x$-a.s., it holds $\\Ebb_x[f(\\chunk[0]{X}[n-1])]=\\Ebb_x[f(\\chunk[0]{X}[n-1])|\\cF_{\\tau_{\\cC}^0}]=G_0$.\nMoreover, as $\\tau_{\\cC}^{n-1}\\geqslant n-1$, it also holds $G_{n-1}=\\Ebb_x[f(\\chunk[0]{X}[n-1])|\\cF_{\\tau_{\\cC}^{n-1}}]=f(\\chunk[0]{X}[n-1])$.\nTherefore, the difference $f(\\chunk[0]{X}[n-1])-\\Ebb_x[f(\\chunk[0]{X}[n-1])]$ is decomposed into a sum of the martingale increments $G_{i+1}-G_i$ as follows\n\\begin{equation}\\label{eq:LinkWithG}\n f(\\chunk[0]{X}[n-1])-\\Ebb_x[f(\\chunk[0]{X}[n-1])]=G_{n-1}-G_0=\\sum_{i=0}^{n-2}(G_{i+1}-G_i)\\eqsp.\n\\end{equation}\nThe proof is now decomposed into three facts that aim at bounding the Laplace transform of $f(\\chunk[0]{X}[n-1])-\\Ebb_x[f(\\chunk[0]{X}[n-1])]$.\n\n\\noindent\n{\\bf Fact 1.} \\emph{For any $i\\in \\{1,\\ldots,n-1\\}$,}\n\\begin{equation}\\label{eq:Fact1}\n G_i-G_{i-1}=(G_i-G_{i-1})\\indiacc{\\tau_{\\cC}^{i-1}=i-1}\\eqsp.\n\\end{equation}\n\\begin{proof}[Proof of Fact 1.] By definition $\\tau_{\\cC}^{i-1}\\geqslant i-1$ and $\\tau_{\\cC}^{i-1}> i-1$ if and only if $\\tau_{\\cC}^{i-1}=\\tau_{\\cC}^{i}$.\n Therefore,\n \\[\n G_i-G_{i-1}=(G_i-G_{i-1})\\left(\\indiacc{\\tau_{\\cC}^{i-1}=i-1}+\\indiacc{\\tau_{\\cC}^{i-1}=\\tau_{\\cC}^{i}}\\right)\\eqsp.\n \\]\nTo prove that $(G_i-G_{i-1})\\indiacc{\\tau_{\\cC}^{i-1}=\\tau_{\\cC}^{i}}=0$, we decompose according to the values of $\\tau_{\\cC}^{i}$:\n \\[\n(G_i-G_{i-1})\\indiacc{\\tau_{\\cC}^{i-1}=\\tau_{\\cC}^{i}}=\\sum_{j\\geqslant i} (G_i-G_{i-1})\\indiacc{\\tau_{\\cC}^{i-1}=\\tau_{\\cC}^{i}=j}\\eqsp.\n \\]\nNow, remark that, for any $i\\geqslant 0$,\n\\begin{align}\n G_i\\indiacc{\\tau_{\\cC}^{i}=j}=\n\\begin{cases}\\label{eq:Gitaui=j}\n \\Ebb_x\\big[f(\\chunk[0]{X}[n-1])|\\cF_j\\big]&\\text{ if } j\\leqslant n-2\\eqsp,\\\\\n f(\\chunk[0]{X}[n-1])&\\text{ if } j\\geqslant n-1\\eqsp.\n\\end{cases}\n\\end{align}\nThen, for any $j\\geqslant i$,\n\\[\n G_i\\indiacc{\\tau_{\\cC}^{i}=j}\\indiacc{\\tau_{\\cC}^{i-1}=\\tau_{\\cC}^{i}}= G_{i-1}\\indiacc{\\tau_{\\cC}^{i-1}=j}\\indiacc{\\tau_{\\cC}^{i-1}=\\tau_{\\cC}^{i}}=G_{i-1}\\indiacc{\\tau_{\\cC}^{i}=j}\\indiacc{\\tau_{\\cC}^{i-1}=\\tau_{\\cC}^{i}}\\eqsp.\n\\]\nThis proves Fact 1.\n\\end{proof}\n\nFact 2. bounds the increments $G_i-G_{i-1}$. The proof relies on the following lemma which is a consequence of the coupling result Lemma~\\ref{lem:DMPS18}.\nDefine $g_{n-1}=g_{n-1,\\pi}=f$ and, for any $i\\in [0,n-2]$, let $g_i$ and $g_{i,\\pi}$ denote the functions defined for any $\\chunk[0]{x}[i]\\in\\sX^{i+1}$ by \n\\begin{equation}\n\\label{eq:definition-g-i}\ng_i(\\chunk[0]{x}[i])=\\Ebb_{x_i}[f(\\chunk[0]{x}[i],\\chunk[1]{X}[n-1-i])],\\qquad g_{i,\\pi}(\\chunk[0]{x}[i])=\\Ebb_{\\pi}[f(\\chunk[0]{x}[i],\\chunk[1]{X}[n-1-i])]\\eqsp.\n\\end{equation}\n\n\\begin{lemma}\n\\label{lem:gi-gipi}\n Assume {\\bf H1}, {\\bf H2}, {\\bf H3} and let $\\cC = \\{x:V(x) < d\\}$. \n For any $i\\in \\{0,\\ldots,n-1\\}$ and $(\\chunk[0]{x}[i-1],x_i)$ in $\\sX^i\\times\\cC$,\n\\begin{equation}\\label{eq:gi-gipi}\n|g_i(\\chunk[0]{x}[i])-g_{i,\\pi}(\\chunk[0]{x}[i])|\\leqslant 2LV(x_i)\\sum_{j=i+1}^{n-1}c_jr^{j-i} \\leqslant 2Ld \\sum_{j=i+1}^{n-1}c_jr^{j-i}\\eqsp.\n\\end{equation}\n\\end{lemma}\n\\begin{proof}\n Fix $i\\in\\{0,\\ldots,n-1\\}$ and $\\chunk[0]{x}[i]\\in \\sX^{i+1}$.\nAs $f\\in\\functionboundeddiff{\\sX^n}{c}$, the function $\\tilde{f}_i:\\chunk[1]{y}[n-1-i]\\in \\sX^{n-1-i}\\mapsto f(\\chunk[0]{x}[i],\\chunk[1]{y}[n-1-i])\\in \\R$ satisfies\n\\[\n|\\tilde{f}_i(\\chunk[1]{y}[n-1-i])-\\tilde{f}_i(\\chunk[1]{z}[n-1-i])|\\leqslant \\sum_{k=1}^{n-1-i}c_{i+k}\\indiacc{y_k\\ne z_k}\\eqsp.\n\\]\nHence, $\\tilde{f}_i\\in\\bB\\Dbb(\\sX^{n-1-i},c_{i+1:n-1})$. Applying Lemma~\\ref{lem:DMPS18} to the function $h=\\tilde{f}_i$ yields\n\\begin{align*}\n |g_i(\\chunk[0]{x}[i])-g_{i,\\pi}(\\chunk[0]{x}[i])|&=|\\Ebb_{x_i}[f(\\chunk[0]{x}[i],\\chunk[1]{X}[n-1-i])]-\\Ebb_{\\pi}[f(\\chunk[0]{x}[i],\\chunk[1]{X}[n-1-i])]|\\\\\n &=|\\Ebb_{x_i}[\\tilde{f}_i(\\chunk[1]{X}[n-1-i])]-\\Ebb_{\\pi}[\\tilde{f}_i(\\chunk[1]{X}[n-1-i])]| \\leqslant 2\\sum_{j=i+1}^{n-1}c_j \\vfuncdist{\\delta_{x_i}P^{j-i}}{\\pi} \\eqsp.\n\\end{align*}\nNow inequality \\eqref{eq:gi-gipi} follows from {\\bf H3}.\n\\end{proof}\n\n\n\n\n\n\\noindent\n{\\bf Fact 2.} \\emph{Let $\\rho$ such that $r\\leqslant \\rho<1$ and $i\\in\\{1,\\ldots,n-1\\}$.\nThen,}\n\\begin{align}\n\\label{eq:Gi-Gi-1} |G_i-G_{i-1}|&\\leqslant C_1\\|c\\|_{\\infty}\\indiacc{\\tau_{\\cC}^{i-1}=i-1}\\sigma_{\\cC}\\circ\\theta^{i-1}\\eqsp,\\\\\n\\label{eq:Gi-Gi-1Sq}  |G_i-G_{i-1}|^2&\\leqslant C_2\\indiacc{\\tau_{\\cC}^{i-1}=i-1}\\frac1{\\rho^{2\\sigma_{\\cC}\\circ\\theta^{i-1}}}\\sum_{k=i}^{n-1}c_k^2\\rho^{k-i}\\eqsp.\n\\end{align}\n\\emph{where, $C_1=5Ld/(1-r)$ and $C_2=16L^2d^2/(1-\\rho)$.}\n\\begin{proof}[Proof of Fact 2.]\nFor any integer $i\\in\\{1,\\ldots,n\\}$, let\n\\[\nG_{i,1}=\\Ebb_x[f(\\chunk[0]{X}[n-1])|\\cF_{\\tau_{\\cC}^{i-1}}]\\indiacc{\\tau_{\\cC}^{i-1}=i-1},\\qquad G_{i,2}=\\Ebb_x[f(\\chunk[0]{X}[n-1])|\\cF_{\\tau_{\\cC}^{i}}]\\indiacc{\\tau_{\\cC}^{i-1}=i-1}\\eqsp.\n\\]\nFrom Fact 1., $G_i-G_{i-1}=G_{i,2}-G_{i,1}$.\nBy Markov's property, for any $i\\in \\{0,\\ldots,n-1\\}$ and  $x\\in \\sX$,\n\\[\n\\Ebb_x[f(\\chunk[0]{X}[n-1])|\\cF_i]=g_i(X_{0:i}),\\qquad \\Pbb_{x}-\\text{a.s.}\\eqsp.\n\\]\nNow, let $R_{i,1}=g_{i-1}(\\chunk[0]{X}[i-1])\\indiacc{\\tau_{\\cC}^{i-1}=i-1}-g_{i-1,\\pi}(\\chunk[0]{X}[i-1])\\indiacc{\\tau_{\\cC}^{i-1}=i-1}$.\nWe have\n\\begin{align}\n\\notag G_{i,1}&=\\Ebb_x[f(\\chunk[0]{X}[n-1])|\\cF_{\\tau_{\\cC}^{i-1}}]\\indiacc{\\tau_{\\cC}^{i-1}=i-1}=\\Ebb_x[f(\\chunk[0]{X}[n-1])|\\cF_{i-1}]\\indiacc{\\tau_{\\cC}^{i-1}=i-1}\\\\\n\\label{eq:Gi1} &=g_{i-1}(\\chunk[0]{X}[i-1])\\indiacc{\\tau_{\\cC}^{i-1}=i-1}=g_{i-1,\\pi}(\\chunk[0]{X}[i-1])\\indiacc{\\tau_{\\cC}^{i-1}=i-1}+R_{i,1}\\eqsp.\n\\end{align}\nMoreover, as $\\tau_{\\cC}^i\\geqslant i$, by \\eqref{eq:Gitaui=j},\n\\begin{align}\n\\notag G_{i,2}&=\\sum_{j\\geqslant i}\\Ebb_x[f(\\chunk[0]{X}[n-1])|\\cF_{\\tau_{\\cC}^{i}}]\\indiacc{\\tau_{\\cC}^{i-1}=i-1}\\indiacc{\\tau_{\\cC}^i=j}\\\\\n%\\notag &=\\sum_{j=i}^{n-2}\\Ebb_x[f(\\chunk[0]{X}[n-1])|\\cF_{j}]\\indiacc{\\tau_{\\cC}^{i-1}=i-1}\\indiacc{\\tau_{\\cC}^i=j}+f(\\chunk[0]{X}[n-1])\\indiacc{\\tau_{\\cC}^{i-1}=i-1}\\indiacc{\\tau_{\\cC}^i\\geqslant n-1}\\\\\n\\label{eq:Gi2} &=\\sum_{j=i}^{n-2}g_j(\\chunk[0]{X}[j])\\indiacc{\\tau_{\\cC}^{i-1}=i-1,\\tau_{\\cC}^i=j}+f(\\chunk[0]{X}[n-1])\\indiacc{\\tau_{\\cC}^{i-1}=i-1,\\tau_{\\cC}^i\\geqslant n-1}\\eqsp.\n\\end{align}\nLet $R_{i,2}=\\sum_{j=i}^{n-2}(g_j(\\chunk[0]{X}[j])-g_{j,\\pi}(\\chunk[0]{X}[j]))\\indiacc{\\tau_{\\cC}^{i-1}=i-1,\\tau_{\\cC}^i=j}$.\nFrom \\eqref{eq:Gi1} and \\eqref{eq:Gi2},\n\\begin{align}\n\\label{eq:Gi1-Gi2} |G_{i,2}-G_{i,1}|=|&R_{i,2}-R_{i,1}+\\sum_{j=i}^{n-2}(g_{j,\\pi}(\\chunk[0]{X}[j])-g_{i-1,\\pi}(\\chunk[0]{X}[i-1]))\\indiacc{\\tau_{\\cC}^{i-1}=i-1,\\tau_{\\cC}^i=j}\\\\\n\\notag &+(f(\\chunk[0]{X}[n-1])-g_{i-1,\\pi}(\\chunk[0]{X}[i-1]))\\indiacc{\\tau_{\\cC}^{i-1}=i-1,\\tau_{\\cC}^i\\geqslant n-1}|\n% \\\\\n% \\leqslant 4&\\indiacc{\\tau_{\\cC}^{i-1}=i-1}L\\sum_{j=i+1}^{n-1}c_jr^{j-i}+\\sum_{j=i}^{n-2}|(g_{j,\\pi}(\\chunk[0]{X}[j])-g_{i-1,\\pi}(\\chunk[0]{X}[i-1]))\\indiacc{\\tau_{\\cC}^{i-1}=i-1,\\tau_{\\cC}^i=j}|\\\\\n% &+|(f(\\chunk[0]{X}[n-1])-g_{i-1,\\pi}(\\chunk[0]{X}[i-1]))\\indiacc{\\tau_{\\cC}^{i-1}=i-1,\\tau_{\\cC}^i\\geqslant n-1}|\n\\eqsp.\n\\end{align}\nWe bound separately all the terms in this decomposition.\nFirst, as $\\pi$ is invariant and $f\\in \\functionboundeddiff{\\sX^n}{c}$, for any $j\\in \\{i+1,\\ldots,n-1\\}$ and any $\\chunk[0]{x}[j]\\in \\sX^{j+1}$,\n\\[\n|g_{j,\\pi}(\\chunk[0]{x}[j])-g_{i-1,\\pi}(\\chunk[0]{x}[i-1])|=\\Ebb_{\\pi}[f(\\chunk[0]{x}[j],\\chunk[j+1]{X}[n-1])-f(\\chunk[0]{x}[i-1],\\chunk[i]{X}[n-1])]\\leqslant \\sum_{k=i}^jc_k\\eqsp.\n\\]\nHence,\n\\begin{equation}\n\\label{eq:Bound:Easyterms}\n\\begin{aligned} \\sum_{j=i}^{n-2}|(g_{j,\\pi}(\\chunk[0]{X}[j])-g_{i-1,\\pi}(\\chunk[0]{X}[i-1]))|\\indiacc{\\tau_{\\cC}^i=j}&\\leqslant \\sum_{j=i}^{n-2}\\indiacc{\\tau_{\\cC}^i=j}\\sum_{k=i}^jc_k=\\indiacc{\\tau_{\\cC}^i\\leqslant n-2}\\sum_{k=i}^{\\tau_{\\cC}^i}c_k\\eqsp,\\\\\n|f(\\chunk[0]{X}[n-1])-g_{i-1,\\pi}(\\chunk[0]{X}[i-1])|\\indiacc{\\tau_{\\cC}^i\\geqslant n-1}&\\leqslant \\indiacc{\\tau_{\\cC}^i\\geqslant n-1}\\sum_{k=i}^{n-1}c_k\\eqsp.\n\\end{aligned}\n\\end{equation}\n\n\n\n %where $|R_{i,1}|$ and $|R_{i,2}|$ are respectively bounded in \\eqref{eq:Bound:R1} and \\eqref{eq:Bound:R2}.\n%\\anici{Selon moi, ta majoration de $|R_{i,1}|$ et $|R_{i,2}|$ par le même terme n'était pas juste : j'ai commenté dans le fichier source (au dessus de cette anotation) et propose donc}\n%\\begin{align*}\n% |G_{i,2}-G_{i,1}|=|&R_{i,2}-R_{i,1}+\\sum_{j=i}^{n-2}(g_{j,\\pi}(\\chunk[0]{X}[j])-g_{i-1,\\pi}(\\chunk[0]{X}[i-1]))\\indiacc{\\tau_{\\cC}^{i-1}=i-1,\\tau_{\\cC}^i=j}\\\\\n% &+(f(\\chunk[0]{X}[n-1])-g_{i-1,\\pi}(\\chunk[0]{X}[i-1]))\\indiacc{\\tau_{\\cC}^{i-1}=i-1,\\tau_{\\cC}^i\\geqslant n-1}|\\\\\n% \\leqslant  |& R_{i,1}| + |R_{i,2}|+\\sum_{j=i}^{n-2}|(g_{j,\\pi}(\\chunk[0]{X}[j])-g_{i-1,\\pi}(\\chunk[0]{X}[i-1]))\\indiacc{\\tau_{\\cC}^{i-1}=i-1,\\tau_{\\cC}^i=j}|\\\\\n% &+|(f(\\chunk[0]{X}[n-1])-g_{i-1,\\pi}(\\chunk[0]{X}[i-1]))\\indiacc{\\tau_{\\cC}^{i-1}=i-1,\\tau_{\\cC}^i\\geqslant n-1}|\\\\\n% \\leqslant  2&\\indiacc{\\tau_{\\cC}^{i-1}=i-1}L \\left( \\sum_{j=i+1}^{n-1}c_jr^{j-i} + \\sum_{k=\\tau_{\\cC}^i+1}^{n-1}c_kr^{k-\\tau_{\\cC}^i} \\right)\\\\\n% & +  \\sum_{j=i}^{n-2}|(g_{j,\\pi}(\\chunk[0]{X}[j])-g_{i-1,\\pi}(\\chunk[0]{X}[i-1]))\\indiacc{\\tau_{\\cC}^{i-1}=i-1,\\tau_{\\cC}^i=j}|\\\\\n% &+|(f(\\chunk[0]{X}[n-1])-g_{i-1,\\pi}(\\chunk[0]{X}[i-1]))\\indiacc{\\tau_{\\cC}^{i-1}=i-1,\\tau_{\\cC}^i\\geqslant n-1}|\\eqsp.\n%\\end{align*}\nTo bound $|R_{i,1}|$ and $|R_{i,2}|$ in \\eqref{eq:Gi1-Gi2}, we use Lemma~\\ref{lem:gi-gipi}.\nFirst, \\eqref{eq:gi-gipi} directly yields\n\\begin{equation}\\label{eq:Bound:R1}\n|R_{i,1}|\\leqslant 2\\indiacc{\\tau_{\\cC}^{i-1}=i-1}Ld\\sum_{j=i+1}^{n-1}c_jr^{j-i}\\eqsp.\n\\end{equation}\nMoreover, as $\\{\\tau_{\\cC}^i=j\\}\\subset \\{X_j\\in \\cC\\}$, \\eqref{eq:gi-gipi} also yields\n\\[\n(g_j(\\chunk[0]{X}[j])-g_{j,\\pi}(\\chunk[0]{X}[j]))\\indiacc{\\tau_{\\cC}^i=j}\\leqslant 2L\\sum_{k=j+1}^{n-1}c_kr^{k-j}\\indiacc{\\tau_{\\cC}^i=j}\\leqslant 2Ld\\indiacc{\\tau_{\\cC}^i=j}\\sum_{k=\\tau_{\\cC}^i+1}^{n-1}c_kr^{k-\\tau_{\\cC}^i}\\eqsp.\n\\]\nTherefore,\n\\begin{equation}\\label{eq:Bound:R2}\n|R_{i,2}|\\leqslant 2Ld\\indiacc{\\tau_{\\cC}^{i-1}=i-1}\\sum_{k=\\tau_{\\cC}^i+1}^{n-1}c_kr^{k-\\tau_{\\cC}^i}\\eqsp.\n\\end{equation}\nPlugging \\eqref{eq:Bound:Easyterms}, \\eqref{eq:Bound:R1} and \\eqref{eq:Bound:R2} in \\eqref{eq:Gi1-Gi2} yields\n\\begin{align}\n\\label{eq:Gi1-Gi22} |G_{i,2}-G_{i,1}|\\leqslant &2Ld\\bigg(\\sum_{j=i+1}^{n-1}c_jr^{j-i}+\\sum_{k=\\tau_{\\cC}^i+1}^{n-1}c_kr^{k-\\tau_{\\cC}^i}+\\frac1{2Ld}\\sum_{k=i}^{\\tau_{\\cC}^i\\wedge (n-1)}c_k\\bigg)\\indiacc{\\tau_{\\cC}^{i-1}=i-1}\\eqsp.\n\\end{align}\nBoth \\eqref{eq:Gi-Gi-1} and \\eqref{eq:Gi-Gi-1Sq} follow from \\eqref{eq:Gi1-Gi22} by bounding separately the $3$ terms in the right-hand side of this inequality.\nLet us first establish \\eqref{eq:Gi-Gi-1}.\nSince $r<1$,\n\\[\n\\sum_{j=i+1}^{n-1}c_jr^{j-i}\\leqslant \\frac{\\|c\\|_\\infty r}{1-r},\\qquad \\sum_{k=\\tau_{\\cC}^i+1}^{n-1}c_kr^{k-\\tau_{\\cC}^i}\\leqslant \\frac{\\|c\\|_\\infty r}{1-r}\\eqsp.\n\\]\n%\\anici{Dans toutes les équations suivantes, je pense qu'il y avait une erreur dans l'indice du $\\theta$ car par définition $\\tau_{\\cC}^i = i + \\tau_{\\cC}^0 \\circ \\theta^i$ et $\\sigma_{\\cC}=1+\\tau_{\\cC}^0 \\circ \\theta$ d'où $1-i+\\tau_{\\cC}^i\\wedge (n-1) \\leqslant 1-i+\\tau_{\\cC}^i = 1 - i + i +\\tau_{\\cC}^0 \\circ\\theta \\circ \\theta^{i-1}=\\sigma_{\\cC}\\circ\\theta^{i-1}$. Cela est par ailleurs cohérent avec \\eqref{eq:Gi-Gi-1} que l'on souhaite montrer. J'ai donc modifié en conséquence.}\nMoreover,\n\\[\n\\sum_{k=i}^{\\tau_{\\cC}^i\\wedge (n-1)}c_k\\leqslant \\|c\\|_{\\infty}[1-i+\\tau_{\\cC}^i\\wedge (n-1) ]\\leqslant \\|c\\|_{\\infty}[1+\\tau_{\\cC}^0\\circ \\theta^i]=\\|c\\|_{\\infty}\\sigma_{\\cC}\\circ\\theta^{i-1}\\eqsp.\n\\]\nAs $r<1\\leqslant \\sigma_{\\cC}\\circ\\theta^{i-1}$, plugging these upper bounds in \\eqref{eq:Gi1-Gi22} shows\n\\[\n|G_{i}-G_{i-1}|=|G_{i,2}-G_{i,1}|\\leqslant \\frac{5Ld\\|c\\|_{\\infty}}{1-r}\\sigma_{\\cC}\\circ\\theta^{i-1}\\indiacc{\\tau_{\\cC}^{i-1}=i-1}\\eqsp.\n\\]\nThis proves \\eqref{eq:Gi-Gi-1}.\nWe use slightly different controls to prove \\eqref{eq:Gi-Gi-1Sq} from \\eqref{eq:Gi1-Gi22}.\nAs $r\\leqslant \\rho<1$, $\\rho^{-\\sigma_{\\cC}\\circ\\theta^{i-1}}\\geqslant 1$, and\n\\begin{align}\n\\label{eq:Step1Var} \\sum_{j=i+1}^{n-1}c_jr^{j-i}\\leqslant \\sum_{j=i}^{n-1}c_j\\rho^{j-i}\\leqslant \\rho^{-\\sigma_{\\cC}\\circ\\theta^{i-1}}\\sum_{j=i}^{n-1}c_j\\rho^{j-i}\\eqsp.\n\\end{align}\n%\\anici{Ci après, je pense qu'il y avait également la même erreur d'indice pour $\\theta$ et j'ai modifié en conséquence.}\nMoreover,\n\\begin{align*}\n \\sum_{k=\\tau_{\\cC}^i+1}^{n-1}c_kr^{k-\\tau_{\\cC}^i}\\leqslant\\rho^{i-\\tau_{\\cC}^i}\\sum_{k=\\tau_{\\cC}^i+1}^{n-1}c_k\\rho^{k-i}\\eqsp.\n\\end{align*}\nAs $\\tau_{\\cC}^i\\geqslant i$ and $i-\\tau_{\\cC}^i=1-\\sigma_{\\cC}\\circ\\theta^{i-1}$,\n\\begin{equation}\\label{eq:Step2Var}\n\\sum_{k=\\tau_{\\cC}^i+1}^{n-1}c_kr^{k-\\tau_{\\cC}^i}\\leqslant \\rho^{1-\\sigma_{\\cC}\\circ\\theta^{i-1}} \\sum_{j=\\tau^i_{\\cC}+1}^{n-1}c_j\\rho^{j-i}\\leqslant \\rho^{-\\sigma_{\\cC}\\circ\\theta^{i-1}}\\sum_{j=\\tau^i_{\\cC}+1}^{n-1}c_j\\rho^{j-i}\\eqsp.\n\\end{equation}\nIn addition,\n\\begin{align}\\label{eq:Step3Var}\n \\sum_{k=i}^{\\tau_{\\cC}^i\\wedge (n-1)}c_k\\leqslant &\\sum_{k=i}^{\\tau_{\\cC}^i\\wedge (n-1)}c_k\\rho^{k-\\tau_{\\cC}^i}=\\sum_{k=i}^{\\tau_{\\cC}^i\\wedge (n-1)}c_k\\rho^{k-i-\\sigma_{\\cC}\\circ\\theta^{i-1}+1}\\leqslant \\rho^{-\\sigma_{\\cC}\\circ\\theta^{i-1}}\\sum_{k=i}^{\\tau_{\\cC}^i\\wedge (n-1)}c_k\\rho^{k-i}\\eqsp.\n\\end{align}\n%\\anici{Je ne sais pas si c'est important quantitativement mais dans les deux majorations précédentes, on se débarasses du $\\tau_{\\cC}^i$ assez \"brutalement\" alors que si on fait comme dans mon manuscrit de thèse, on parvient dans l'inégalité suivante non pas à $25L^2$ mais $16 L^2$ (en supposant bien évidemment comme ici que $L\\geq 1$).}\nPlugging \\eqref{eq:Step1Var}, \\eqref{eq:Step2Var} and \\eqref{eq:Step3Var} in \\eqref{eq:Gi1-Gi22} and applying Cauchy-Schwarz inequality shows\n\\begin{align*}\n |G_{i}-G_{i-1}|^2=&|G_{i,2}-G_{i,1}|^2\\leqslant16L^2d^2\\rho^{-2\\sigma_{\\cC}\\circ\\theta^{i-1}}\\bigg(\\sum_{k=i}^{n-1}c_k\\rho^{k-i}\\bigg)^2\\indiacc{\\tau_{\\cC}^{i-1}=i-1}\\\\\n \\leqslant &\\frac{16L^2d^2}{1-\\rho}\\rho^{-2\\sigma_{\\cC}\\circ\\theta^{i-1}}\\sum_{k=i}^{n-1}c_k^2\\rho^{k-i}\\indiacc{\\tau_{\\cC}^{i-1}=i-1}\\eqsp.\n\\end{align*}\nThis proves \\eqref{eq:Gi-Gi-1Sq} and thus {\\bf Fact 2.}\n\\end{proof}\n\n\n\\noindent\n{\\bf Fact 3.} \\emph{ Assume {\\bf H1}, {\\bf H2}, {\\bf H3}. Let $\\cC = \\{x: V(x) < d\\}$. Then for any $x\\in \\cC$,}\n\\begin{align}\n\\Ebb_x\\bigg[\\rme^{f(\\chunk[0]{X}[n-1])-\\Ebb_x[f(\\chunk[0]{X}[n-1])]}\\bigg]\\leqslant \\rme^{C_3\\|c\\|^2}\\eqsp.\n\\end{align}\n\\emph{where $C_3=\\fracaa{4Ld\\left(-\\fracaa{5}{\\log \\lambda}+4MLd\\right)}{(1-r\\vee \\lambda^{1/4})^2}$.}\n\\begin{proof}[Proof of Fact 3.]\nFor any $t\\in \\Rbb$, $\\rme^t\\leqslant 1+t+t^2\\rme^{|t|}$. Hence, as $\\Ebb_{x}[G_{i+1}-G_i|\\cF_{\\tau_{\\cC}^{i}}]=0$, for any $i\\geqslant 0$, we have\n\\begin{align*}\n \\Ebb_x[\\rme^{G_{i+1}-G_i}|\\cF_{\\tau_{\\cC}^{i}}]\\leqslant 1+\\Ebb_x[(G_{i+1}-G_i)^2\\rme^{|G_{i+1}-G_i|}|\\cF_{\\tau_{\\cC}^{i}}]\\eqsp.\n\\end{align*}\nBy Fact 2.,\n\\begin{align*}\n \\Ebb_x[\\rme^{G_{i+1}-G_i}|\\cF_{\\tau_{\\cC}^{i}}]&\\leqslant 1+C_2\\sum_{k=i+1}^{n-1}c_k^2\\rho^{k-i-1}\\indiacc{\\tau_{\\cC}^{i}=i}\\Ebb_x[\\rho^{-2\\sigma_{\\cC}\\circ\\theta^{i}}\\rme^{C_1\\|c\\|_{\\infty}\\sigma_{\\cC}\\circ\\theta^{i}}|\\cF_{\\tau_{\\cC}^{i}}]\\eqsp.\n \\end{align*}\n Now by Markov's property,\n %\n\\begin{align*}\n\\indiacc{\\tau_{\\cC}^{i}=i} \\Ebb_x[\\rho^{-2\\sigma_{\\cC}\\circ\\theta^{i}}\\rme^{C_1\\|c\\|_{\\infty}\\sigma_{\\cC}\\circ\\theta^{i}}|\\cF_{\\tau_{\\cC}^{i}}]&=\\indiacc{\\tau_{\\cC}^{i}=i} \\Ebb_x[\\rho^{-2\\sigma_{\\cC}\\circ\\theta^{i}}\\rme^{C_1\\|c\\|_{\\infty}\\sigma_{\\cC}\\circ\\theta^{i}}|\\cF_{i}]\\\\\n&=\\indiacc{\\tau_{\\cC}^{i}=i}\\Ebb_{X_i}[\\rho^{-2\\sigma_{\\cC}}\\rme^{C_1\\|c\\|_{\\infty}\\sigma_{\\cC}}]\\eqsp.\n\\end{align*}\nHence,\n \\begin{align*}\n \\Ebb_x[\\rme^{G_{i+1}-G_i}|\\cF_{\\tau_{\\cC}^{i}}]\n &=1+C_2\\sum_{k=i+1}^{n-1}c_k^2\\rho^{k-i-1}\\indiacc{\\tau_{\\cC}^{i}=i}\\Ebb_{X_i}[\\rho^{-2\\sigma_{\\cC}}\\rme^{C_1\\|c\\|_{\\infty}\\sigma_{\\cC}}]\\eqsp.\n \\end{align*}\nLet $\\rho=r\\vee u^{-1/4}$, $\\varepsilon=\\log u/(2C_1)$ and assume first that $\\|c\\|_{\\infty}\\leqslant \\varepsilon$. By {\\bf H$2$},\n\\[\n\\indiacc{\\tau_{\\cC}^{i}=i}\\Ebb_{X_i}[\\rho^{-2\\sigma_{\\cC}}\\rme^{C_1\\|c\\|_{\\infty}\\sigma_{\\cC}}]\\leqslant \\indiacc{\\tau_{\\cC}^{i}=i}\\sup_{x\\in\\cC}\\Ebb_x[\\rho^{-2\\sigma_{\\cC}}\\rme^{C_1\\|c\\|_{\\infty}\\sigma_{\\cC}}]\\leqslant\\sup_{x\\in\\cC}\\Ebb_x[u^{\\sigma_{\\cC}}]\\leqslant M\\enspace.\n\\]\nHence,\n\\[\n \\Ebb_x[\\rme^{G_{i+1}-G_i}|\\cF_{\\tau_{\\cC}^{i}}]\\leqslant 1+C_2M\\sum_{k=i+1}^{n-1}c_k^2\\rho^{k-i-1}\\leqslant \\rme^{C_2M\\sum_{k=i+1}^{n-1}c_k^2\\rho^{k-i-1}}\\eqsp.\n\\]\nBy recurrence, it follows that\n\\begin{align*}\n\\Ebb_x\\bigg[\\rme^{f(\\chunk[0]{X}[n-1])-\\Ebb_x[f(\\chunk[0]{X}[n-1])]}\\bigg]&\\leqslant \\rme^{C_2M\\sum_{i=0}^{n-2}\\sum_{k=i+1}^{n-1}c_k^2\\rho^{k-i-1}}\\\\\n&=\\rme^{C_2M\\sum_{k=1}^{n-1}c_k^2\\sum_{i=0}^{k-1}\\rho^{k-i-1}}\\leqslant \\rme^{\\frac{C_2M}{1-\\rho}\\|c\\|^2} \\eqsp.\n\\end{align*}\nFix $\\tilde{x}$ in $\\sX$ and let $\\tilde{f} : \\sX^n \\rightarrow \\Rbb$ be defined, for any $x_{0:n-1}$ in $\\sX^n$, by\n\\[\n\\tilde{f}(\\chunk[0]{X}[n-1])\n=\nf(x_0\\mathbbm{1}_{\\{c_{0}\\leq\\varepsilon\\}} + \\tilde{x} \\mathbbm{1}_{\\{c_{0}>\\varepsilon\\}},\\dots, x_{n-1}\\mathbbm{1}_{\\{c_{n-1}\\leq\\varepsilon\\}} + \\tilde{x} \\mathbbm{1}_{\\{c_{n-1}>\\varepsilon\\}})\n\\eqsp .\n\\]\nAs $f$ belongs to $\\mathbb{BD}\\left(\\sX^n,c\\right)$, $\\tilde{f}$ belongs to $ \\mathbb{BD}\\left(\\sX^n,\\tilde{c}\\right)$, where\n\\[\n\\tilde{c}\n=\n\\left( c_0\\mathbbm{1}_{\\{c_{0}\\leq\\varepsilon\\}},\\dots,c_{n-1}\\mathbbm{1}_{\\{c_{n-1}\\leq\\varepsilon\\}}\\right)\n\\eqsp .\n\\]\nSince $\\|\\tilde{c}\\|_{\\infty} < \\varepsilon$ and $\\|\\tilde{c}\\|\\leqslant \\|c\\|$, $\\tilde{f}$ satisfies\n\\begin{align}\\label{ineq:max-gamma-leq-varepsilon-ftilde}\n\\Ebb_{x}\\left[\\rme^{\\tilde{f}(\\chunk[0]{X}[n-1])-\\Ebb_{x}[\\tilde{f}(\\chunk[0]{X}[n-1])]}\\right]\n& \\leqslant\n\\rme^{\\frac{MC_2}{1-\\rho}\n\\| \\tilde{c}\\|^2} \\leqslant\n\\rme^{\\frac{MC_2}{1-\\rho}\n\\| c\\|^2}\n\\eqsp .\n\\end{align}\nFurthermore, by definition of $\\tilde{f}$ and since $f$ is in $\\mathbb{BD}(\\sX^n,c)$, for any $x\\in\\sX^n$,\n\\begin{align}\\label{ineq:difference-f-tildef}\n|f(x)-\\tilde{f}(x)|\n& =\n%|f(x_0,\\dots,x_{n-1})-f(x_0\\mathbbm{1}_{\\{\\gamma_{0}\\leq\\varepsilon\\}} + \\tilde{x} \\mathbbm{1}_{\\{\\gamma_{0}>\\varepsilon\\}},\\dots, x_{n-1}\\mathbbm{1}_{\\{\\gamma_{n-1}\\leq\\varepsilon\\}} + \\tilde{x} \\mathbbm{1}_{\\{\\gamma_{n-1}>\\varepsilon\\}})|\\\\\n%& \\leq\n\\sum_{i=0}^{n-1} c_i \\mathbbm{1}_{\\{c_i>\\varepsilon\\}}\n\\leq\n\\sum_{i=0}^{n-1} c_i \\frac{c_i}{\\varepsilon}\n\\leq\n\\frac{\\|c\\|^2}{\\varepsilon}.\n\\end{align}\nThis implies\n\\[\n\\Ebb_x\\bigg[\\rme^{f(\\chunk[0]{X}[n-1])-\\Ebb_x[f(\\chunk[0]{X}[n-1])]}\\bigg]\\leqslant \\rme^{\\frac{2\\|c\\|^2}{\\varepsilon}}\\Ebb_{x}\\left[\\rme^{\\tilde{f}(\\chunk[0]{X}[n-1])-\\Ebb_{x}[\\tilde{f}(\\chunk[0]{X}[n-1])]}\\right]\\leqslant \\rme^{\\bigg(\\frac2{\\varepsilon}+\\frac{MC_2}{1-\\rho}\\bigg)\n\\| c\\|^2}\n\\eqsp .\n\\]\nThis shows {\\bf Fact 3} since\n\\[\n\\frac2{\\varepsilon}+\\frac{MC_2}{1-\\rho}\\leqslant \\frac{4Ld}{(1-r\\vee \\lambda^{1/4})^2}\\bigg(-\\frac5{\\log \\lambda}+4MLd\\bigg)\\eqsp.\n\\]\n\\end{proof}\n\n\\noindent\n{\\bf Fact 3} proves that there exists a constant $C=2C_3$ such that, for any $c\\in \\Rbb^n$, $f\\in \\functionboundeddiff{\\sX^n}{c}$ and $x\\in \\cC$,\n\\begin{equation}\\label{ControlLaplace}\n \\Ebb_x\\bigg[\\rme^{f(\\chunk[0]{X}[n-1])-\\Ebb_x[f(\\chunk[0]{X}[n-1])]}\\bigg]\\leqslant \\rme^{C\\| c\\|^2/2}\n\\eqsp .\n\\end{equation}\nLet $f\\in \\functionboundeddiff{\\sX^n}{c}$ and $x\\in \\cC$. \nFor any $s>0$, $sf\\in \\functionboundeddiff{\\sX^n}{c}$.\nHence, from \\eqref{ControlLaplace}, for any $s,t>0$,\n\\begin{align*}\n \\Pbb\\big(f(\\chunk[0]{X}[n-1])-\\Ebb_x[f(\\chunk[0]{X}[n-1])]>t\\big)&\\leqslant \\rme^{-st+\\log\\Ebb_x\\big[\\rme^{sf(\\chunk[0]{X}[n-1])-\\Ebb_x[sf(\\chunk[0]{X}[n-1])]}\\big]}\\\\\n &\\leqslant \\rme^{-st+s^2C\\| c\\|^2/2}\\enspace.\n\\end{align*}\nChoosing $s=t/(C\\|c\\|^2)$ proves Theorem~\\ref{thm:ConcMarkQuant} with\n\\[\n\\beta=\\frac1{2C}=\\frac1{4C_3}=\\frac{(1-r\\vee \\lambda^{1/4})^2}{16Ld}\\bigg(-\\frac5{\\log \\lambda}+4MLd\\bigg)^{-1}\\eqsp.\n\\]\n\\end{proof}\n\n\\section{Applications to Unadjusted Langevin Algorithm}\\label{sec:ULA}\nWe illustrate the applicability of the results by the example on one of the MCMC methods. Suppose that we aim at sampling from the distribution with density $\\pi(x) = \\frac{e^{-U(x)}}{\\int\\limits_{\\mathbb{R}^d} e^{-U(y)}\\,dy}$. One of the popular algorithms for solving this problem is the Unadjusted Langevin Algorithm, which suggests constructing the Markov Chain\n$$\nX_{k+1} = h_{k+1}(X_k) + \\sqrt{2\\gamma_{k+1}}Z_{k+1}, h_{k+1}(X_k) := X_{k} - \\gamma_{k+1}\\nabla U(X_{k}) \n$$\nwith some non-increasing sequence $\\gamma_k \\geq 0$, where $Z_k \\sim \\mathcal{N}(0,I)$ are i.i.d. standard normal $d$-dimensional random variables. Let us denote ULA kernel with parameter $\\gamma$ as $P_{\\gamma}$, that is,\n\\begin{equation}\n\\label{eq:ula_kernel}\nP_{\\gamma}(x,dy) = \\frac{1}{(4\\pi\\gamma)^{\\frac{d}{2}}}\\exp{\\left(-\\frac{\\|y-x+\\gamma\\nabla U(x)\\|^2}{4\\gamma}\\right)}\\,dy\n\\end{equation}\nLet us also introduce the multiple steps kernel\n$$\nQ^{p,n} = P_{\\gamma_p}\\ldots P_{\\gamma_n}, Q^{n} := Q^{1,n}\n$$\nStandard assumptions on the sequence $\\{\\gamma_k\\}$ are $\\sum\\limits_{k=0}^{\\infty}\\gamma_k = \\infty$ and $\\sum\\limits_{k=0}^{\\infty}\\gamma_k^2 < \\infty$. Thus it is impossible to analyze properties of additive functionals of $\\{X_k\\}$ by standard tools, since the assumptions {\\bf H2} and {\\bf H3} fails in case $\\gamma_k \\rightarrow 0$.  Yet we might establish some alternative bounds on the speed of convergence to stationary distribution. We need to impose condition\n\\par\n[{\\bf C1}] Potential $U(x)$ satisfies for all $x,y \\in \\mathbb{R}^d$ the condition\n$$\n\\|U(x) - U(y)\\| \\leq L\\|x-y\\|\n$$\nThis condition obviously implies\n$$\n\\|h_{k}(X) - h_k(Y)\\| \\leq (1+L\\gamma_k)\\|X-Y\\|\n$$\nHence, by \\cite[Theorem~19]{durmus:moulines:2018}, we might obtain the following minorization condition\n\\begin{lemma} Assume that the condition {\\bf C1} holds. Then for all $x,y \\in \\mathbb{R}^d, n\\geq 1$ it holds\n$$\n\\|\\delta_xQ^n - \\delta_yQ^n\\|_{TV} \\leq \\mathbb{I}(x \\neq y)\\left(1 - 2\\Phi\\left(-\\frac{\\|x-y\\|}{2\\sqrt{b_n}}\\right)\\right)\n$$\nwhere $b_n := \\sum\\nolimits_{i=1}^{k}\\frac{\\gamma_i}{\\prod_{j=1}^{i}(1+L\\gamma_j)^2}$\n\\end{lemma}\nNow we aim at establishing Foster-Lyapunov drift conditions for the kernel $P_{\\gamma_n}$.We will say that function $V(x): \\mathbb{R}^d \\rightarrow [1,+\\infty)$ satisfies a Foster-Lyapunov drift condition for the Markov kernel $P_\\gamma$ if. there are such $\\overline{\\gamma} > 0, \\lambda \\in [0,1), C > 0$ such that for any $\\gamma \\in (0, \\overline{\\gamma}]$ it holds\n\\begin{equation}\n\\label{eq:drift}\nP_{\\gamma}V \\leq \\lambda^{\\gamma}V + \\gamma C\n\\end{equation}\nGiven that this condition holds, we may prove drift condition for. the kernel $Q^n$.\n\n\\begin{lemma}\n\\label{lem:drift_prod}\n Assume that $P_{\\gamma}$ satisfies condition \\ref{eq:drift} for any $0 < \\gamma < \\overline{\\gamma}$. Then it holds\n$$\nQ^{n,p}V \\leq \\lambda^{\\Gamma_{p,n}}V + C\\frac{\\lambda^{\\Gamma_{1,p}} - \\lambda^{\\Gamma_{1,n}}}{\\log{\\frac{1}{\\lambda}}}\n$$ \n\\end{lemma}\n\\begin{proof} For notation simplicity let us consider only $p=1$. Then by induction\n$$\nQ^{n}V \\leq \\lambda^{\\Gamma_{1,n}}V + C \\sum\\limits_{k=1}^{n}\\gamma_k \\lambda^{\\Gamma_{1,k-1}} \\leq \\lambda^{\\Gamma_{1,n}}V + C \\int\\limits_{0}^{\\Gamma_{1,n}}\\lambda^{x}\\,dx \\leq\n$$\n$$\n\\leq \\lambda^{\\Gamma_{1,n}}V + C\\frac{1-\\lambda^{\\Gamma_{1,n}}}{\\log{\\frac{1}{\\lambda}}}\n$$\n\\end{proof}\nLet us check that ULA kernel \\ref{} satisfies the drift condition \\label{eq:drift}. We will need additional assumption\n\\par\n[{\\bf C2}] There exists such constants $K_1 > 0$ and $m > 0$, such that for any $x \\notin B(0,K_1)$ it holds\n$$\n\\langle \\nabla U(x), x \\rangle \\geq \\frac{m}{2}\\|x\\|^2\n$$\nAnother popular condition on the potential is strong convexity outside some euclidean ball:\n\\par\n[{\\bf C3}] There exist constants $K_1 > 0$ and $m > 0$ such that for any $x \\notin B(0,K_1)$ and $y \\in \\mathbb{R}^d$, it holds $\\langle D^2U(x)y,y\\rangle \\geq m\\|y\\|^2$. Moreover, there exists $M \\geq 0$ such that for any $x \\in \\mathbb{R}^d$, $\\|D^3U(x)\\| \\leq M$.\n\\par\nYet it is possible to show that assumption {\\bf C3} and {\\bf C1} imply {\\bf C2} (see \\cite[Lemma~14]{brosse:2018:diffusion}), so in the sequel we are going to work with the condition {\\bf C2}. It allows us to prove the following result\n\n\\begin{lemma} Assume that the potential $U(x)$ satisfies conditions {\\bf C1} and {\\bf C2} and without loss of generality consider $\\nabla U(0) = 0$. Then the kernel \\ref{} satisfies drift condition \\ref{eq:drift} for any $0 < \\gamma < \\overline{\\gamma} = \\frac{m}{4L^2}$ with drift function $V(x) = 1 + \\|x\\|^2$, constants $\\lambda = \\exp{-\\left(\\frac{m}{2}\\right)}$, $C = 3K_1^2 + 2d + C_1$ for some absolute constant $C_1 > 0$.\n\\end{lemma}\n\n\\begin{proof} Consider $V(x) = 1 + \\|x\\|^2$, then\n$$\nP_{\\gamma}V(x) = \\int\\limits_{\\mathbb{R}^d}V(y)P_{\\gamma}(x,dy) = \\int\\limits_{\\mathbb{R}^d}(1+\\|y\\|^2)\\frac{1}{(4\\pi\\gamma)^{\\frac{d}{2}}}\\exp{\\left(-\\frac{\\|y-x+\\gamma\\nabla U(x)\\|^2}{4\\gamma}\\right)}\\,dy = \n$$\n\n$$\n=1 + \\frac{1}{(4\\pi\\gamma)^{\\frac{d}{2}}}\\int\\limits_{\\mathbb{R}^d}\\|z + x - \\gamma \\nabla U(x)\\|^2 \\exp{\\left(-\\frac{\\|z\\|^2}{4\\gamma}\\right)}\\,dz\n$$\nLet us first consider the case $x \\notin B(0,K_1)$. Note that $\\|z+x-\\gamma \\nabla U(x)\\|^2 = \\|z\\|^2 + 2 \\langle z, x - \\gamma \\nabla U(x) \\rangle + \\gamma^2 \\|x - \\gamma \\nabla U(x)\\|^2$ and the linear term vanishes after integration, moreover, for $Z \\sim \\mathcal{N}(0,2\\gamma I_d$, it holds $\\mathbb{E}\\|Z\\|^2 = 2\\gamma d$. It remains to notice that due to {\\bf C1} and {\\bf C2}\n$$\n\\|x - \\gamma \\nabla U(x) \\|^2 = \\|x\\|^2 - 2\\gamma \\langle \\nabla U(x), x\\rangle + \\gamma^2 \\|\\nabla U(x)\\|^2 \\leq\n$$\n$$\n \\leq (1-\\gamma m)\\|x\\|^2 + 2\\gamma^2 L^2 \\|x\\|^2\n$$\nThus, plugging everything into expression for $P_{\\gamma}V$ and using $\\gamma < \\frac{m}{4L}$, we obtain\n$$\nP_{\\gamma}V(x) \\leq (1-\\gamma m + 2\\gamma^2 L^2)V(x) + 2\\gamma d + (\\gamma m - 2\\gamma^2 L^2) \\leq \\exp^{-\\frac{\\gamma m}{2}}V(x) + 2\\gamma d\n$$\nNow let $x \\in B(0,K_1)$. Then simply using $\\|x-\\gamma \\nabla U(x)\\|^2 \\leq 2(1+L\\gamma)^2\\|x\\|^2$, we obtain\n$$\nP_{\\gamma}V(x) \\leq (1-\\gamma m + 2\\gamma^2 L^2)V(x) + \\gamma\\left((m - 2\\gamma L^2)(1+\\|x\\|^2) + 2d + 2(1+L\\gamma)^2\\|x\\|^d\\right) \\leq \n$$\n\n$$\n\\leq \\exp^{-\\frac{\\gamma m}{2}}V(x) + \\gamma(3K_1^2 + 2d + C_1)\n$$\nfor some absolute constant $C_1$, which does not depend on $\\gamma, d, x$.\n\\end{proof}\n\nNow the geometric ergodicity result readily follows from \\cite[Theorem~19.4.1]{douc:moulines:priouret:soulier:2018}, namely, the following lemma holds:\n\n\\begin{lemma} Let the potential $U(x), x \\in \\mathbb{R}^D$ satisfy conditions {\\bf C1} and {\\bf C2}. Then for $0 < \\gamma < \\overline{\\gamma}=\\frac{m}{4L^2}$, for any $x \\in X$ it holds\n$$\nd_V(\\delta_xQ^n_\\gamma,\\pi_\\gamma) \\leq C\\rho^n\\left(V(x) + \\pi_\\gamma(V)\\right)\n$$ \nwith $V(x) = 1 + \\|x\\|^2$ and constants\n$$\nb = \\gamma(3K_1^2 + 2D + C_1); \\quad \\overline{b} = b\\exp^{-\\frac{m\\gamma}{2}} + d; \\quad \\varepsilon = 2\\Phi\\left(-\\frac{\\sqrt{d}(1+L\\gamma)}{2\\sqrt{\\gamma}}\\right); \\quad\n$$\n\n$$\nC = \\left(1 + \\exp^{-\\frac{m\\gamma}{2}}\\right)\\left(1+\\frac{\\overline{b}}{(1-\\varepsilon)(1-\\exp^{-\\frac{m\\gamma}{2}} - \\frac{2b}{1+d})}\\right);\n$$\n\n$$\n\\rho = \\exp^{-\\gamma\\left(\\frac{m}{2} - 2\\frac{3K_1^2 + 2D + C_1}{d}\\right)\\frac{\\log{(1-\\varepsilon)}}{\\log{(1-\\varepsilon)} + \\log{(\\exp^{-\\frac{m\\gamma}{2}} + \\frac{2b}{d+1})}}}\n$$\nfor some $C_1 > 0$, which does not depend on $d, \\gamma$ and $n$.\n\\end{lemma}\n\n\\begin{proof} Note that the condition {\\bf C1} implies that the Markov kernel $Q^n_\\gamma$ satisfies $(1,\\varepsilon)$-Doeblin condition with $\\varepsilon = 2\\Phi\\left(-\\frac{\\sqrt{d}(1+L\\gamma)}{2\\sqrt{\\gamma}}\\right)$. Together with drift condition {\\bf C2} it allows to apply \\cite[Theorem~19.4.1]{douc:moulines:priouret:soulier:2018} with appropriate constants. \n\\end{proof}\n\n\\bibliographystyle{plain}\n\\bibliography{BiblioSource}\n\n\n\\end{document} ", "meta": {"hexsha": "69d1ea0393b1a89933fde1e20d6a3eaf0de381aa", "size": 40673, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Note_exponential_moment/MarkovCon.tex", "max_stars_repo_name": "svsamsonov/VR-MCMC", "max_stars_repo_head_hexsha": "335ffb0835917b1cdce633877099c8452e3aeb78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Note_exponential_moment/MarkovCon.tex", "max_issues_repo_name": "svsamsonov/VR-MCMC", "max_issues_repo_head_hexsha": "335ffb0835917b1cdce633877099c8452e3aeb78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Note_exponential_moment/MarkovCon.tex", "max_forks_repo_name": "svsamsonov/VR-MCMC", "max_forks_repo_head_hexsha": "335ffb0835917b1cdce633877099c8452e3aeb78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 64.7659235669, "max_line_length": 486, "alphanum_fraction": 0.6356059302, "num_tokens": 18385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.6791787121629465, "lm_q1q2_score": 0.344895008002215}}
{"text": "\\section{Jastrow Factors}\n\\label{sec:jastrow}\n\nJastrow factors are among the simplest and most effective ways of including\ndynamical correlation in the trial many body wavefunction.  The resulting many body\nwavefunction is expressed as the product of an antisymmetric (in the case\nof Fermions) or symmetric (for Bosons) part and a correlating Jastrow factor\nlike so:\n\\begin{equation}\n\\Psi(\\vec{R}) = \\mathcal{A}(\\vec{R}) \\exp\\left[J(\\vec{R})\\right]\n\\end{equation}\n\nIn this section we will detail the types and forms of Jastrow factor used \nin QMCPACK.  Note that each type of Jastrow factor needs to be specified using\nits own individual \\texttt{jastrow} XML element.  For this reason, we have repeated the\nspecification of the \\texttt{jastrow} tag in each section, with specialization for the\noptions available for that given type of Jastrow.\n\n\\subsection{One-body Jastrow functions}\n\\label{sec:onebodyjastrow}\nThe one-body Jastrow factor is a form that allows for the direct inclusion\nof correlations between particles that are included in the wavefunction with\nparticles that are not explicitly part of it.  The most common example of\nthis are correlations between electrons and ions.  \n\nThe Jastrow function is specified within a \\texttt{wavefunction} element\nand must contain one or more \\texttt{correlation} elements specifying\nadditional parameters as well as the actual coefficients. Section\n\\ref{sec:1bjsplineexamples} gives examples of the typical nesting of\n\\texttt{jastrow}, \\texttt{correlation}, and \\texttt{coefficient} elements.\n\n\\subsubsection{Input Specification}\n\n\\begin{table}[h]\n\\begin{center}\n\\begin{tabular}{l c c c l }\n\\hline\n\\multicolumn{5}{l}{Jastrow element} \\\\\n\\hline\n\\bfseries name & \\bfseries datatype & \\bfseries values & \\bfseries defaults  & \\bfseries description \\\\\n\\hline\nname & text &    & (required) & Unique name for this Jastrow function \\\\\ntype & text & One-body & (required) & Define a one-body function \\\\ \nfunction & text & Bspline & (required) & BSpline Jastrow \\\\\n             & text & pade2 & & Pade form \\\\\n             & text & \\ldots & & \\ldots \\\\\nsource & text & name & (required) & Name of attribute of classical particle set \\\\ \nprint & text & yes / no & yes & Jastrow factor printed in external file?\\\\\n  \\hline\n\\multicolumn{5}{l}{elements}\\\\ \\hline\n& Correlation & & & \\\\ \\hline\n\\multicolumn{5}{l}{Contents}\\\\ \\hline\n& (None)  & & &  \\\\ \\hline\n\\end{tabular}\n%\\end{tabular*}\n\\end{center}\n\\end{table}\n\nTo be more concrete, the one-body Jastrow factors used to describe correlations\nbetween electrons and ions take the form below\n\\begin{equation}\nJ1=\\sum_I^{ion0}\\sum_i^e u_{ab}(|r_i-R_I|)\n\\end{equation}\nwhere I runs over all of the ions in the calculation, i runs over the electrons\nand $u_{ab}$ describes the functional form of the correlation between them.\nMany different forms of $u_{ab}$ are implemented in QMCPACK.  We will detail \ntwo of the most common ones below.\n\\include{jastrow_one_body_spline}\n\\include{jastrow_one_body_pade}\n\n\\subsection{Two-body Jastrow functions}\nThe two-body Jastrow factor is a form that allows for the explicit inclusion\nof dynamic correlation between two particles included in the wavefunction.  It\nis almost always given in a spin dependent form so as to satisfy the Kato cusp\ncondition between electrons of different spins\\cite{kato}.\n\n The two body Jastrow function is specified within a \\texttt{wavefunction} element\nand must contain one or more correlation elements specifying additional parameters\nas well as the actual coefficients.  Section \\ref{sec:2bjsplineexamples} gives \nexamples of the typical nesting of \\texttt{jastrow}, \\texttt{correlation} and\n\\texttt{coefficient} elements.\n\n\\subsubsection{Input Specification}\n\n\\begin{table}[h]\n\\begin{center}\n\\begin{tabular}{l c c c l }\n\\hline\n\\multicolumn{5}{l}{Jastrow element} \\\\\n\\hline\n\\bfseries name & \\bfseries datatype & \\bfseries values & \\bfseries defaults  & \\bfseries description \\\\\n\\hline\nname & text &    & (required) & Unique name for this Jastrow function \\\\\ntype & text & Two-body & (required) & Define a one-body function \\\\ \nfunction & text & Bspline & (required) & BSpline Jastrow \\\\\nprint & text & yes / no & yes & Jastrow factor printed in external file?\\\\\n  \\hline\n\\multicolumn{5}{l}{elements}\\\\ \\hline\n& Correlation & & & \\\\ \\hline\n\\multicolumn{5}{l}{Contents}\\\\ \\hline\n& (None)  & & &  \\\\ \\hline\n\\end{tabular}\n%\\end{tabular*}\n\\end{center}\n\\end{table}\n\nThe two-body Jastrow factors used to describe correlations between electrons take the form\n\\begin{equation}\nJ2=\\sum_i^{e}\\sum_{j>i}^{e} u_{ab}(|r_i-r_j|)\n\\end{equation}\n\nThe most commonly used form of two body Jastrow factor supported by the code is a splined\nJastrow factor, with many similarities to the one body spline Jastrow.\n\n\\include{jastrow_two_body_spline}\n\n\n\\subsection{Long-ranged Jastrow factors}\nWhile short-ranged Jastrow factors capture the majority of the benefit \nfor minimizing the total energy and the energy variance, long-ranged \nJastrow factors are important to accurately reproduce the short-ranged \n(long wavelength) behavior of quantities such as the static structure \nfactor, and are therefore essential for modern accurate finite size \ncorrections in periodic systems.\n\nBelow two types of long-ranged Jastrow factors are described.  The \nfirst (the k-space Jastrow) is simply an expansion of the one and/or \ntwo body correlation functions in plane waves, with the coefficients \ncomprising the optimizable parameters.  The second type have few \nvariational parameters and use the optimized breakup method of Natoli \nand Ceperley\\cite{Natoli1995} (the Yukawa and Gaskell RPA Jastrows).\n\n\n\\subsubsection{Long-ranged Jastrow: k-space Jastrow}\nThe k-space Jastrow introduces explicit long-ranged dependence commensurate with the periodic supercell.  This Jastrow is to be used in periodic boundary conditions only.  \n\nThe input for the k-space Jastrow fuses both one and two-body forms into a single element and so they are discussed together here.  The one- and two-body terms in the k-Space Jastrow have the form:\n\\begin{align}\n  J_1 &= \\sum_{G\\ne 0}b_G\\rho_G^I\\rho_{-G} \\\\\n  J_2 &= \\sum_{G\\ne 0}a_G\\rho_G\\rho_{-G}\n\\end{align}\nHere $\\rho_G$ is the Fourier transform of the instantaneous electron density:\n\\begin{align}\n  \\rho_G=\\sum_{n\\in electrons}e^{iG\\cdot r_n}\n\\end{align}\nand $\\rho_G^I$ has the same form, but for the fixed ions. In both cases the coefficients are restricted to be real, though in general the coefficients for the one-body term need not be.  See section \\ref{sec:feature_kspace_jastrow} for more detail.\n\nInput for the k-space Jastrow follows the familar nesting of \\texttt{jastrow-correlation-coefficients} elements, with attributes unique to the k-space Jastrow at the \\texttt{correlation} input level.\n\n\\FloatBarrier\n\\begin{table}[h]\n\\begin{center}\n\\begin{tabularx}{\\textwidth}{l l l l l l }\n\\hline\n\\multicolumn{6}{l}{\\texttt{jastrow type=kSpace} element} \\\\\n\\hline\n\\multicolumn{2}{l}{parent elements:} & \\multicolumn{4}{l}{\\texttt{wavefunction}}\\\\\n\\multicolumn{2}{l}{child  elements:} & \\multicolumn{4}{l}{\\texttt{correlation}}\\\\\n\\multicolumn{2}{l}{attributes}  & \\multicolumn{4}{l}{}\\\\\n   &   \\bfseries name     & \\bfseries datatype & \\bfseries values          & \\bfseries default  & \\bfseries description \\\\\n   & \\texttt{type}$^r$    &  text              & \\textbf{kSpace}           &                    & Must be kSpace           \\\\\n   & \\texttt{name}$^r$    &  text              & \\textit{anything}         & 0                  & Unique name for Jastrow \\\\\n   & \\texttt{source}$^r$  &  text              & \\texttt{particleset.name} &                    & Ion particleset name\\\\\n  \\hline\n\\end{tabularx}\n\\end{center}\n\\end{table}\n\\FloatBarrier\n\n\\FloatBarrier\n\\begin{table}[h]\n\\begin{center}\n\\begin{tabularx}{\\textwidth}{l l l l l l }\n\\hline\n\\multicolumn{6}{l}{\\texttt{correlation} element} \\\\\n\\hline\n\\multicolumn{2}{l}{parent elements:} & \\multicolumn{4}{l}{\\texttt{jastrow type=kSpace}}\\\\\n\\multicolumn{2}{l}{child  elements:} & \\multicolumn{4}{l}{\\texttt{coefficients}}\\\\\n\\multicolumn{2}{l}{attributes}  & \\multicolumn{4}{l}{}\\\\\n   &   \\bfseries name           & \\bfseries datatype & \\bfseries values  & \\bfseries default  & \\bfseries description \\\\\n   & \\texttt{type}$^r$          &  text              & \\textbf{One-Body},\\textbf{Two-Body}    &                     & Must be One-Body/Two-Body     \\\\\n   & \\texttt{kc}$^r$            &  real              & kc$\\ge$ 0                                & 0.0                 & k-space cutoff in a.u. \\\\\n   & \\texttt{symmetry}$^o$      &  text              & crystal,isotropic,none                 & crystal             & Symmetry of coefficients\\\\\n   & \\texttt{spinDependent}$^o$ &  boolean           & yes,no                                 & no                  & \\textit{No current function} \\\\\n  \\hline\n\\end{tabularx}\n\\end{center}\n\\end{table}\n\\FloatBarrier\n\n\\FloatBarrier\n\\begin{table}[h]\n\\begin{center}\n\\begin{tabularx}{\\textwidth}{l l l l l l }\n\\hline\n\\multicolumn{6}{l}{\\texttt{coefficients} element} \\\\\n\\hline\n\\multicolumn{2}{l}{parent elements:} & \\multicolumn{4}{l}{\\texttt{correlation}}\\\\\n\\multicolumn{2}{l}{child  elements:} & \\multicolumn{4}{l}{\\textit{None}}\\\\\n\\multicolumn{2}{l}{attributes}  & \\multicolumn{4}{l}{}\\\\\n   &   \\bfseries name     & \\bfseries datatype & \\bfseries values  & \\bfseries default   & \\bfseries description \\\\\n   & \\texttt{id}$^r$      &  text              & \\textit{anything} &     cG1/cG2         & Label for coeffs     \\\\\n   & \\texttt{type}$^r$    &  text              & \\texttt{Array}    &   0                 & Must be Array \\\\\n\\multicolumn{2}{l}{body text}  & \\multicolumn{4}{l}{}\\\\\n   &                           & \\multicolumn{4}{l}{The body text is a list of real values for the parameters.}     \\\\\n  \\hline\n\\end{tabularx}\n\\end{center}\n\\end{table}\n\\FloatBarrier\n\n\nAdditional information:\n\\begin{itemize}\n  \\item{It is normal to provide no coefficients as an initial guess.  The number of coefficients will be automatically calculated according to the k-space cutoff + symmetry and set to zero. }\n  \\item{Providing an incorrect number of parameters also results in all parameters being set to zero.}\n  \\item{There is currently no way to turn optimization on/off for the k-space Jastrow.  The coefficients are always optimized.}\n  \\item{Spin dependence is currently not implemented for this Jastrow.}\n  \\item{\\texttt{kc}: Parameters with G vectors magnitudes less than \\texttt{kc} are included in the Jastrow.  If \\texttt{kc} is zero, it is the same as excluding the k-space term.}\n  \\item{\\texttt{symmetry=crystal}: Impose crystal symmetry on coefficients according to the structure factor.}\n  \\item{\\texttt{symmetry=isotropic}: Impose spherical symmetry on coefficients according to G-vector magnitude.}\n  \\item{\\texttt{symmetry=none}: Impose no symmetry on the coefficients.}\n\\end{itemize}\n\n\n\\begin{lstlisting}[style=XML,caption=k-space Jastrow with one- and two-body terms.]\n  <jastrow type=\"kSpace\" name=\"Jk\" source=\"ion0\">\n     <correlation kc=\"4.0\" type=\"One-Body\" symmetry=\"cystal\">\n        <coefficients id=\"cG1\" type=\"Array\">                  \n        </coefficients>\n     </correlation>\n     <correlation kc=\"4.0\" type=\"Two-Body\" symmetry=\"crystal\">\n        <coefficients id=\"cG2\" type=\"Array\">                  \n        </coefficients>\n     </correlation>\n  </jastrow>\n\\end{lstlisting}\n\n\\begin{lstlisting}[style=XML,caption=k-space Jastrow with one-body term only.]\n  <jastrow type=\"kSpace\" name=\"Jk\" source=\"ion0\">\n     <correlation kc=\"4.0\" type=\"One-Body\" symmetry=\"cystal\">\n        <coefficients id=\"cG1\" type=\"Array\">                  \n        </coefficients>\n     </correlation>\n  </jastrow>\n\\end{lstlisting}\n\n\\begin{lstlisting}[style=XML,caption=k-space Jastrow with two-body term only.]\n  <jastrow type=\"kSpace\" name=\"Jk\" source=\"ion0\">\n     <correlation kc=\"4.0\" type=\"Two-Body\" symmetry=\"crystal\">\n        <coefficients id=\"cG2\" type=\"Array\">                  \n        </coefficients>\n     </correlation>\n  </jastrow>\n\\end{lstlisting}\n\n\n\n\n\\subsubsection{Long-ranged Jastrows: Gaskell RPA and Yukawa forms}\n\\label{sec:twobodyjastrowlr}\n\\textbf{NOTE: The Yukawa and RPA Jastrows do not work at present \nand are currently being revived.  Please contact the developers if \nyou are interested in using them.} \n\nThe exact Jastrow correlation functions contain terms which have a \nform similar to the Coulomb pair potential.  In periodic systems \nthe Coulomb potential is replaced by an Ewald summation of the \nbare potential over all periodic image cells.  This sum is often \nhandled by the optimized breakup method\\cite{Natoli1995} and this \nsame approach is applied to the long-ranged Jastrow factors in QMCPACK.\n\nThere are two main long-ranged Jastrow factors of this type \nimplemented in QMCPACK: the Gaskell RPA\\cite{Gaskell1961,Gaskell1962} \nform and the Yukawa\\cite{Ceperley1978} form.  Both of these forms \nwere used by Ceperley in early studies of the electron gas\\cite{Ceperley1978}, \nbut they are also appropriate starting points for general solids. \n\nThe Yukawa form is defined in real space.  It's long-range form is \nformally defined as\n\\begin{align}\n  u_Y^{PBC}(r) = \\sum_{L\\ne 0}\\sum_{i<j}u_Y(\\abs{r_i-r_j+L})\n\\end{align}\nwith $u_Y(r)$ given by\n\\begin{align}\n  u_Y(r) = \\frac{a}{r}\\left(1-e^{-r/b}\\right)\n\\end{align}\nIn QMCPACK a slightly more restricted form is used:\n\\begin{align}\n  u_Y(r) = \\frac{r_s}{r}\\left(1-e^{-r/\\sqrt{r_s}}\\right)\n\\end{align}\nhere ``$r_s$'' is understood to be a variational parameter.\n\nThe Gaskell RPA form--which contains correct short/long range limits \nand minimizes the total energy of the electron gas within the RPA--is \ndefined directly in k-space:\n\\begin{align}\n  u_{RPA}(k) = -\\frac{1}{2S_0(k)}+\\frac{1}{2}\\left(\\frac{1}{S_0(k)^2}+\\frac{4m_ev_k}{\\hbar^2k^2}\\right)^{1/2}\n\\end{align}\nwhere $v_k$ is the Fourier transform of the Coulomb potential and \n$S_0(k)$ is the static structure factor of the non-interacting \nelectron gas:\n\\[\n  S_0(k) = \\left.\n  \\begin{cases}\n    1 &  k>2k_F \\\\\n    \\frac{3k}{4k_F}-\\frac{1}{2}\\left(\\frac{k}{2k_F}\\right)^3 & k<2k_F\n  \\end{cases}\n  \\right.\n\\]\nWhen written in atomic units, RPA Jastrow implemented in QMCPACK has the \nform\n\\begin{align}\n  u_{RPA}(k) = \\frac{1}{2N_e}\\left(-\\frac{1}{S_0(k)}+\\left(\\frac{1}{S_0(k)^2}+\\frac{12}{r_s^3k^4}\\right)^{1/2}\\right)\n\\end{align}\nHere ``$r_s$'' is again a variational parameter and $k_F\\equiv(\\tfrac{9\\pi}{4r_s^3})^{1/3}$.\n\nFor both the Yukawa and Gaskell RPA Jastrows, the default value for $r_s$ is $r_s=(\\tfrac{3\\Omega}{4\\pi N_e})^{1/3}$.\n\n\n\\FloatBarrier\n\\begin{table}[h]\n\\begin{center}\n\\begin{tabularx}{\\textwidth}{l l l l l l }\n\\hline\n\\multicolumn{6}{l}{\\texttt{jastrow type=Two-Body function=rpa/yukawa} element} \\\\\n\\hline\n\\multicolumn{2}{l}{parent elements:} & \\multicolumn{4}{l}{\\texttt{wavefunction}}\\\\\n\\multicolumn{2}{l}{child  elements:} & \\multicolumn{4}{l}{\\texttt{correlation}}\\\\\n\\multicolumn{2}{l}{attributes}  & \\multicolumn{4}{l}{}\\\\\n   &   \\bfseries name        & \\bfseries datatype & \\bfseries values             & \\bfseries default  & \\bfseries description   \\\\\n   & \\texttt{type}$^r$       &  text              & \\textbf{Two-Body}            &                    & Must be Two-Body   \\\\\n   & \\texttt{function}$^r$   &  text              & \\textbf{rpa}/\\textbf{yukawa} &                    & Must be rpa or yukawa   \\\\\n   & \\texttt{name}$^r$       &  text              & \\textit{anything}            & RPA\\_Jee            & Unique name for Jastrow \\\\\n   & \\texttt{longrange}$^o$  &  boolean           & yes/no                       & yes                & Use long-range part     \\\\\n   & \\texttt{shortrange}$^o$ &  boolean           & yes/no                       & yes                & Use short-range part    \\\\\n\\multicolumn{2}{l}{parameters}  & \\multicolumn{4}{l}{}\\\\\n   & \\texttt{rs}$^o$         &  rs                & $r_s>0$                      & $\\tfrac{3\\Omega}{4\\pi N_e}$ & Avg. elec-elec distance \\\\\n   & \\texttt{kc}$^o$         &  kc                & $k_c>0$                      & $2\\left(\\tfrac{9\\pi}{4}\\right)^{1/3}\\tfrac{4\\pi N_e}{3\\Omega}$ & K-space cutoff\\\\\n  \\hline\n\\end{tabularx}\n\\end{center}\n\\end{table}\n\\FloatBarrier\n\n\n\\begin{lstlisting}[style=XML,caption=Two body RPA Jastrow with long- and short-ranged parts.]\n<jastrow name=''Jee'' type=''Two-Body'' function=''rpa''>\n</jastrow>\n\\end{lstlisting}\n\n\n\n% J1 RPA (intended for electron-proton system)\n%   source = particleset.name\n%   function = RPA\n%   name = anything [Jep]\n%   rs = >0 [-1]\n%   kc = >0 [-1]\n% \n% J2 RPA\n%   attributes\n%     function = yukawa or rpa\n%     name = anything [RPA_Jee]\n%     longrange = yes/no [yes]\n%     shortrange = yes/no [yes]\n%   parameters\n%     rs = >0 [-1]  3\\Omega/4\\pi N_e\n%     kc = >0 [-1]  2 (9\\pi/4)^1/3 * 4\\pi N_e/3\\Omega\n\n\n\n\\subsection{Three-body Jastrow functions}\nExplicit three-body correlations can be included in the wavefunction via the three-body Jastrow factor.\nThe three-body electron-electron-ion correlation function ($u_{\\sigma\\sigma'I}$) currently used in \\qmcpack is identical to the one proposed in \\cite{Drummond2004}:\n\\begin{eqnarray}\nu_{\\sigma\\sigma'I}(r_{\\sigma I},r_{\\sigma'I},r_{\\sigma\\sigma'}) &= \\sum_{\\ell=0}^{M_{eI}}\\sum_{m=0}^{M_{eI}}\\sum_{n=0}^{M_{ee}}\\gamma_{\\ell mn} r_{\\sigma I}^\\ell r_{\\sigma'I}^m r_{\\sigma\\sigma'}^n \\\\\n   &\\times \\left(r_{\\sigma I}-\\frac{r_c}{2}\\right)^3 \\Theta\\left(r_{\\sigma I}-\\frac{r_c}{2}\\right) \\nonumber \\\\\n   &\\times \\left(r_{\\sigma' I}-\\frac{r_c}{2}\\right)^3 \\Theta\\left(r_{\\sigma' I}-\\frac{r_c}{2}\\right) \\nonumber\n\\end{eqnarray}\nHere $M_{eI}$ and $M_{ee}$ are the maximum polynomial orders of the\nelectron-ion and electron-electron distances, respectively,\n$\\{\\gamma_{\\ell mn}\\}$ are the optimizable parameters (modulo\nconstraints), $r_c$ is a cutoff radius, and $r_{ab}$ are the distances\nbetween electrons or ions $a$ and $b$. i.e. The correlation function\nis only a function of the interparticle distances and not a more\ncomplex function of the particle positions, $\\mathbf{r}$. As indicated by the\n$\\Theta$ functions, correlations are set to zero beyond a distance of\n$r_c/2$ in either of the electron-ion distances and the largest\nmeaningful electron-electron distance is $r_c$.  This is the\nhighest-order Jastrow correlation function currently implemented.\n\n\nToday, solid state applications of \\qmcpack usually utilize one and\ntwo-body B-spline Jastrow functions, with calculations on heavier\nelements often also using the three-body term described above.\n\n\\paragraph{Example use case}\nHere is an example of H2O molecule. After optimizing one and two body Jastrow factors, add the following block in the wavefunction.\nThe coefficients will be filled zero automatically if not given.\n\\begin{lstlisting}[style=XML]\n<jastrow name=\"J3\" type=\"eeI\" function=\"polynomial\" source=\"ion0\" print=\"yes\">\n  <correlation ispecies=\"O\" especies=\"u\" isize=\"3\" esize=\"3\" rcut=\"10\">\n    <coefficients id=\"uuO\" type=\"Array\" optimize=\"yes\"> </coefficients>\n  </correlation>\n  <correlation ispecies=\"O\" especies1=\"u\" especies2=\"d\" isize=\"3\" esize=\"3\" rcut=\"10\">\n    <coefficients id=\"udO\" type=\"Array\" optimize=\"yes\"> </coefficients>\n  </correlation>\n  <correlation ispecies=\"H\" especies=\"u\" isize=\"3\" esize=\"3\" rcut=\"10\">\n    <coefficients id=\"uuH\" type=\"Array\" optimize=\"yes\"> </coefficients>\n  </correlation>\n  <correlation ispecies=\"H\" especies1=\"u\" especies2=\"d\" isize=\"3\" esize=\"3\" rcut=\"10\">\n    <coefficients id=\"udH\" type=\"Array\" optimize=\"yes\"> </coefficients>\n  </correlation>\n</jastrow>\n\\end{lstlisting}\n", "meta": {"hexsha": "73e111e686a3a3773abc3592b3f74f2e5f702f02", "size": 19499, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "manual/jastrow.tex", "max_stars_repo_name": "bwvdg/qmcpack", "max_stars_repo_head_hexsha": "cd09fc54b36de2579c9802f5e64b7ec15506f3c3", "max_stars_repo_licenses": ["NCSA"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "manual/jastrow.tex", "max_issues_repo_name": "bwvdg/qmcpack", "max_issues_repo_head_hexsha": "cd09fc54b36de2579c9802f5e64b7ec15506f3c3", "max_issues_repo_licenses": ["NCSA"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-10T15:33:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-10T15:35:59.000Z", "max_forks_repo_path": "manual/jastrow.tex", "max_forks_repo_name": "bwvdg/qmcpack", "max_forks_repo_head_hexsha": "cd09fc54b36de2579c9802f5e64b7ec15506f3c3", "max_forks_repo_licenses": ["NCSA"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.7601918465, "max_line_length": 248, "alphanum_fraction": 0.6841376481, "num_tokens": 5896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.34489500140698126}}
{"text": "\\section{Preliminaries} \\label{gua:sec:prelim}\\label{gua:sec:definitions}\nMany definitions intersect with those defined in previous chapters,\nbut to keep the chapter self-contained we define them here.\n\nNotation:\n$\\bbB = \\{\\true,\\false\\}$ is the set of Boolean values,\n$\\bbN$ is the set of natural numbers (excluding $0$),\n$\\bbN_0 = \\bbN\\cup\\{0\\}$,\n$[k]$ is the set $\\{i \\in \\bbN \\| i \\leq k\\}$\nand $[0..k]$ is the set $[k] \\cup \\{0\\}$ for $k \\in \\bbN$.\nFor a sequence $x=x_1x_2\\ldots$ denote the $i$-$j$-subsequence as $x\\slice{i}{j}$,\ni.e., ${x\\slice{i}{j}}=x_i \\ldots x_j$.\n\n\n\\subsection{System Model} \\label{gua:sec:model}\n\nWe consider systems $A {\\parallel} B^n$, usually written $\\largesys$, \nconsisting of\none copy of a process template $A$ and $n$ copies of a process template $B$,\nin an interleaving parallel composition.%\n%% AK: moved to a separate note, to be able to explain why we _cannot_ generalize for 1-conj\n%\\footnote{As shown in \\cite{Emerson00}, cutoffs for this case generalize to cutoffs \n%          for systems of the form $A^m {\\parallel} B^n$, and further \n%          to systems with an arbitrary number of process templates \n%          $U_1^{n_1} {\\parallel} \\ldots {\\parallel} U_m^{n_m}$.} \nWe distinguish objects that belong to different templates by indexing them with\nthe template. E.g., for process template $U \\in \\{A,B\\}$, $Q_U$ is the set of\nstates of $U$. For this section, fix two disjoint finite sets $Q_A$, $Q_B$ as\nsets of states of process templates $A$ and $B$, and a positive integer $n$.\n\n\\parbf{Processes} A \\emph{process template} \n is a transition system\n  $U=(\\stateset, \\init, \\inputs, \\delta)$ with \n\t\\begin{itemize}\n\t\\item $\\stateset$ is a finite set of states including the\n  initial state $\\init$,\n\t\\item $\\inputs$ is a finite input alphabet,\n\t\\item $\\delta: \\stateset \\times \\inputs \\times \\mP(Q_A \\cupdot Q_B) \\times \\stateset$ is a guarded transition relation.\n\t\\end{itemize}\nA process template is \\emph{closed} if $\\inputs = \\emptyset$, and otherwise \\emph{open}.\n\nBy $\\transition{q_i}{q_j}{e:g}$\nwe denote a process transition from $q_i$ to $q_j$\nfor input $e \\in \\Sigma$ and guarded by guard $g \\in \\mP(Q_A \\cupdot Q_B)$.\nWe skip the input $e$ and guard $g$\nif they are not important or can be inferred from the context.\n\nWe define the size $\\card{U}$ of a process template $U \\in \\{A,B\\}$ as $\\card{\\stateset_U}$. A copy of a template $U$ will be called a \\emph{$U$-process}.\nDifferent $B$-processes are distinguished by subscript, i.e., for $i \\in [1..n]$, $B_i$ is the $i$th copy of $B$, and $\\state_{B_i}$ is a state of $B_i$. A state of the $A$-process is denoted by $q_A$. \n\nFor the rest of this subsection, fix templates $A$ and $B$. We assume that $\\inputs_A \\cap \\inputs_B = \\emptyset$. We will also write $p$ for a process in $\\{ A, B_1, \\ldots, B_n\\}$, unless $p$ is specified explicitly.\nWe often denote the set $\\{B_1,...,B_n\\}$ as $\\mB$.\n\n\n\\parbf{Disjunctive and conjunctive systems}\nIn a system $\\largesys$,\nconsider the global state $s = (\\state_A,\\state_{B_1},\\ldots,\\state_{B_n})$ and\nglobal input $e=(\\localin_A,\\localin_{B_1},\\ldots,\\localin_{B_n})$.\nWe write $s(p)$ for $q_p$, and $e(p)$ for $\\sigma_p$.\nA local transition $(\\state_p,\\localin_p,g,\\state_p') \\in \\delta_U$ of a process $p$ is \\emph{enabled for $s$ and $e$}\nif the \\emph{guard} $g$ is satisfied by the state $s$ wrt.\\ the process $p$, written $(s,p) \\models g$ (defined below).\nThe semantics of $(s,p) \\models g$ differs for disjunctive and conjunctive systems:\n%\n\\begin{align*}\n\\text{In disjunctive systems: } & (s,p) \\models g \\text{~~~iff~~~} \n\\exists p' \\in \\{A,B_1,\\ldots,B_n\\} \\setminus \\{p\\}:\\ \\ \\state_{p'} \\in g. \\\\\n\\text{In conjunctive systems: } & (s,p) \\models g \\text{~~~iff~~~} \n\\forall p' \\in \\{A,B_1,\\ldots,B_n\\} \\setminus \\{p\\}:\\ \\ \\state_{p'} \\in g.\n\\end{align*}\n\nNote that we check containment in the guard (disjunctively or conjunctively) \nonly for local states of processes \\emph{different from} $p$. A process is \\emph{enabled} for $s$ and $e$ if at least one of its transitions is enabled for $s$ and $e$, otherwise it is \\emph{disabled}.\n\nLike Emerson and Kahlon~\\cite{Emerson00}, \nwe assume that in conjunctive systems $\\init_A$ and $\\init_B$ are contained in all guards,\ni.e., they act as neutral states.\nFurthermore, we call a conjunctive system \\emph{$1$-conjunctive} if every guard is of the form $(Q_A \\cupdot Q_B) \\setminus \\{q\\}$ for some $q \\in Q_A\\cupdot Q_B$.\n\nThen, \\largesys is defined as the transition \nsystem $(S,\\init_S,\\globIn,\\delta)$ with \n\\begin{itemize}\n\\item set of global states $S = \\stateset_A \\times \\stateset_B^{n}$, \n\\item global initial state $\\init_S = (\\initstate_A,\\initstate_B,\\ldots,\\initstate_B)$, \n\\item set of global inputs $\\globIn = (\\inputs_A) \\times (\\inputs_B)^{n}$,\n\\item and global transition relation $\\delta \\subseteq S \\times \\globIn \\times S$ with $(s,e,s') \\in \\delta$ iff \n\\begin{enumerate}[label=\\roman*)] \n  \\item $s=(\\state_A,\\state_{B_1},\\ldots,\\state_{B_n})$, \n  \\item $e=(\\localin_A, \\localin_{B_1},\\ldots,\\localin_{B_n})$, and \n  \\item $s'$ is obtained from $s$ by replacing one local state $\\state_p$ with a new local state $\\state_p'$, where $p$ is a $U$-process with local transition $(\\state_{p},\\localin_{p},g,\\state_p') \\in \\delta_U$ and $(s,p) \\models g$. \n        Thus, we consider so-called interleaved systems,\n        where in each step exactly one process transits.\n\\end{enumerate}\n\\end{itemize}\nWe say that a system $\\largesys$ is \\emph{of type} $(A,B)$. It is called a\n\\emph{conjunctive system} if guards are interpreted conjunctively, and a\n\\emph{disjunctive system} if guards are interpreted disjunctively. \nA system is \\emph{closed} if all of its templates are closed.\n\n\n\\parbf{Runs} \nA \\emph{configuration} of a system is a triple $(s,e,p)$, where $s \\in S$, $e \n\\in \\globIn$, and $p$ is either a system process, or the special symbol $\\bot$.\n A \\emph{path} of a system is a configuration sequence \n$x = (s_1,e_1,p_1),(s_2,e_2,p_2),\\ldots$ such that, for all $\\time < |x|$, there is a \ntransition $(s_\\time,e_\\time,s_{\\time+1}) \\in \\delta$ based on a local \ntransition of process $p_\\time$. We say that process \n$p_\\time$ \\emph{moves} at \\emph{moment} $\\time$. \nConfiguration $(s,e,\\bot)$ appears\n iff all processes are disabled for $s$ and $e$.\nAlso, for every $p$ and $\\time < |x|$: \neither $e_{\\time+1}(p) = e_\\time(p)$ or process $p$ moves at moment $\\time$. \nThat is, the environment keeps the input to each process unchanged until \nthe process can read it.\\footnote{By only considering inputs that are actually processed, we \napproximate an \naction-based semantics. Paths that do not fulfill this requirement are not \nvery interesting, since the environment can violate any interesting \nspecification that involves input signals by manipulating them when the \ncorresponding process is not allowed to move.} \n\nA system \\emph{run} is a maximal path starting in the initial state. Runs are either infinite, or they end in a configuration $(s,e,\\bot)$. We say that a run is \\emph{initializing} if every \n%$B$-process \nprocess\nthat moves infinitely often also visits \n%$\\initstate_B$ \nits $\\initstate$ \ninfinitely often.\n\nGiven a system path $x = (s_1,e_1,p_1),(s_2,e_2,p_2),\\ldots$ and a process $p$, the \\emph{local path} of $p$ in $x$ is the projection $x(p) = (s_1(p),e_1(p)),(s_2(p),e_2(p)),\\ldots$ of $x$ onto local states and inputs of $p$.\nSimilarly, we define the projection on two processes $p_1,p_2$ denoted by $x(p_1,p_2)$.\n\n%The \\emph{destuttering} $\\destutter(x)$\\ak{make it work with inf runs} of a (local) path \\sj{local path not defined} $x=x_0,x_1,\\ldots$ is obtained by removing stuttering steps from the sequence, i.e., $\\destutter(x)$ is the maximal subsequence $x'$ of $x$ such that for every $\\time$ we have $x'_\\time \\neq x'_{\\time+1}$. Two (local) paths $x$ and $y$ are \\emph{stutter-equivalent}, written $x \\simeq y$, if $\\destutter(x)=\\destutter(y)$. Define an extension of $\\destutter$ to sets of paths in the obvious way. Then two systems $S_1, S_2$ are \\emph{stutter-equivalent}, written $S_1 \\simeq S_2$, if $\\destutter(X_1) = \\destutter(X_2)$, where $X_i$ is the set of all infinite runs of system $S_i$.\n\n\\parbf{Deadlocks and fairness}\nA run is \\emph{globally deadlocked} if it is finite.\nAn infinite run is \\emph{locally deadlocked} for process $p$ if there exists $\\time$ such that $p$ is disabled for all $s_{\\time'},e_{\\time'}$ with $\\time'\\ge \\time$. A run is \\emph{deadlocked} if it is locally or globally deadlocked.\nA system \\emph{has a (local/global) deadlock} if it has a (locally/globally) deadlocked run. Note that the absence of local deadlocks for all $p$ implies the absence of global deadlocks, but not the other way around.\n\nA run $(s_1,e_1,p_1), (s_2,e_2,p_2),...$ is \\emph{unconditionally-fair} if every process moves infinitely often. \nA run is \\emph{strong-fair} if it is infinite and, for every process $p$, if $p$ is enabled infinitely often, then $p$ moves infinitely often.\n%\\sj{weak fairness needed?} Finally, $x$ is \\emph{weak-fair} if it is infinite and for every process $p$, if there exists $t$ such that $p$ is enabled for every $s_{\\time'}, e_{\\time'}$ with $\\time' \\ge \\time$, then $p$ moves infinitely often.\nWe will discuss the role of deadlocks and fairness in synthesis in Section~\\ref{gua:sec:paramsynt}.\n\n\\begin{remark}[$A^m {\\parallel} B^n$]\nOne usually starts with studying parameterized systems of the form $A^n$ (having one process template),\nthen proceeds to systems of the form $A^m {\\parallel} B^n$ (having two templates)\nand $U_1^{n_1} {\\parallel} \\ldots {\\parallel} U_m^{n_m}$ (having an arbitrary fixed number of templates).\nOur work studies systems $A {\\parallel} B^n$,\nwhich have one $A$-process and a parameterized number of $B$-processes,\nbecause the results for such systems can be generalized to systems $U_1^{n_1} {\\parallel} \\ldots {\\parallel} U_m^{n_m}$\n(see~\\cite{Emerson00} for details).\nThis generalization works for our results as well,\nexcept for the cutoffs for deadlock detection that are restricted to 1-conjunctive systems of the form $A\\parallel B^n$\n(Section~\\ref{gua:sec:cutoffs}).\n\\end{remark}\n\n\\subsection{Specifications}\n\\label{gua:sec:semantics}\nFix templates $(A,B)$.\nWe consider formulas in $\\LTLmX$---$\\LTL$ without the next-time operator $\\nextt$---%\nthat are prefixed by path quantifiers $\\E$ or $\\A$\n(for LTL and path quantifiers see Section~\\ref{defs:ctlstar}).\nLet $h(A,B_{i_1},\\ldots,B_{i_k})$ be an $\\LTLmX$ formula over atomic propositions from $Q_A \\cup \\Sigma_A$ and indexed propositions from $(Q_B \\cup \\Sigma_B) \\times \\{i_1,\\ldots,i_k\\}$.\nFor a system $\\largesys$ with $n \\geq k$ and every $i_j \\in [1..n]$,\nsatisfaction of $\\A h(A,B_{i_1},\\ldots,B_{i_k})$ and $\\E h(A,B_{i_1},\\ldots,B_{i_k})$ is defined in the usual way.\n\n\n\\parbf{Parameterized specifications} \\label{gua:sec:parameterized}\nA \\emph{parameterized specification} is a temporal logic formula\nwith indexed atomic propositions and quantification over indices. \nWe consider formulas of the forms\n$\\forall{i_1,\\ldots,i_k.} \\A h(A,B_{i_1},\\ldots,B_{i_k})$ and\\\\ \n$\\forall{i_1,\\ldots,i_k.} \\E h(A,B_{i_1},\\ldots,B_{i_k})$. \nFor a given $n \\geq k$, \n$$\n\\largesys \\models \\forall{i_1,{\\ldots},i_k.} \\A h(A,B_{i_1},{\\ldots},B_{i_k})\n$$\n~iff~\n$$\n\\largesys \\models \\!\\!\\!\\!\\!\\!\\!\\!\\bigwedge_{j_1 \\neq {\\ldots} \\neq j_k \\in [1..n]}\\!\\!\\!\\!\\!\\!\\!\\!\\A h(A,B_{j_1},{\\ldots},B_{j_k}).\n$$ \nBy symmetry of guarded systems (see~\\cite{Emerson00}),\nthe second formula is equivalent to\n$\\largesys \\models \\A h(A,B_1,\\ldots,B_k)$. \nThe formula $\\A h(A,B_1,\\ldots,B_k)$ is denoted by $\\A h(A,B^{(k)})$, \nand we often use it instead of the original $\\forall{i_1,\\ldots,i_k.} \\A h(A,B_{i_1},...,B_{i_k})$.\nFor formulas with the path quantifier $\\E$,\nsatisfaction is defined analogously\nand is equivalent to satisfaction of $\\E h(A,B^{(k)})$.\n\\begin{example}\nConsider the formula\n$$\n\\forall{i_1,i_2}.\\A \\big(\\G (r_{i_1} \\impl \\F g_{i_1}) \\land \\G \\neg (g_{i_1} \\land g_{i_2})\\big).\n$$\nBy our definition, its satisfaction by a system $(A,B)^{(1,3)}$ means\n\\begin{align*}\n(A,B)^{(1,3)} \\models\n\\A \\left(\n\\begin{aligned}\n&\\G(r_1 \\impl \\F g_1) \\land \\G(r_2 \\impl \\F g_2) \\land \\G(r_3 \\impl \\F g_3) \\land \\\\\n&\\G \\neg (g_1 \\land g_2) \\land \\G \\neg (g_1 \\land g_3) \\land \\G \\neg (g_2 \\land g_3)\n\\end{aligned}\n\\right),\n\\end{align*}\nwhere $g_1$ and $r_1$ refer to the propositions $g$ and $r$ of the process $B_1$,\n$g_2$ and $r_2$ belong to $B_2$, and so on.\nBy symmetry, the latter satisfaction is equivalent to\n\\begin{align*}\n(A,B)^{(1,3)} \\models\n\\A \\left(\n\\begin{aligned}\n&\\G(r_1 \\impl \\F g_1) \\land \\G(r_2 \\impl \\F g_2) \\land \\\\\n&\\G \\neg (g_1 \\land g_2)\n\\end{aligned}\n\\right).\n\\end{align*}\nNote that this formula talks about processes $B_1$ and $B_2$, but does not mention $B_3$.\n\\end{example}\n\n\n\\parbf{Specification of fairness and local deadlocks}\nIt is often convenient to express fairness assumptions and local deadlocks \nas parameterized specifications.\nTo this end,\ndefine auxiliary atomic propositions $\\sched_p$ and $\\enabled_p$ for every process $p$ of system $(A,B)^{(1,n)}$. At moment $\\time$ of a given run $(s_1,e_1,p_1),(s_2,e_2,p_2), \\ldots$, let $\\sched_p$ be true whenever $p_\\time = p$, and let $\\enabled_p$ be true if $p$ is enabled for $s_\\time, e_\\time$. Note that we only allow the use of these propositions to define fairness, but not in general specifications.\nThen, an infinite run is \n\\begin{itemize}\n\\item \\emph{local-deadlock-free} if it satisfies $\\forall{p}. \\GF \\enabled_p$, abbreviated as $\\spec_{\\neg dead}$,\n\\item \\emph{strong-fair} if it satisfies $\\forall{p}. \\GF \\enabled_p \\impl \\GF \\sched_p$, abbreviated as $\\spec_{strong}$, and \n\\item \\emph{unconditionally-fair} if it satisfies $\\forall{p}. \\GF \\sched_p$, abbreviated as $\\spec_{uncond}$.\n%\\item \\sj{needed?:}\\emph{weak-fair} if it satisfies $\\forall{p}. \\A \\spec_{weak}$, where $\\spec_{weak} = \\FG \\enabled_p \\impl \\GF \\sched_p$.\n\\end{itemize}\n\nIf $f \\in \\{strong, uncond\\}$ is a fairness notion and \n$\\A h(A,B^{(k)})$\na specification, then we write\n$\\A_{f} h(A,B^{(k)})$ for $\\A (\\spec_{f} \n\\rightarrow h(A,B^{(k)}))$.\nSimilarly, we write $\\E_{f} h(A,B^{(k)})$ for $\\E (\\spec_{f} \\land h(A,B^{(k)}))$.\n\n\n\n\\subsection{Model Checking and Synthesis Problems}\n\\label{gua:sec:nonparameterized_synthesis}\n%\nGiven a system $\\largesys$ and a specification $\\A h(A,B^{(k)})$, where $n \\ge k$. Then:\n\\begin{itemize}\n\\item the \\emph{model checking problem} is to decide whether $\\largesys \\models \\A h(A,B^{(k)})$,\n\\item the \\emph{deadlock detection problem} is to decide whether $\\largesys$\n      does not have global nor local deadlocks,\n%\\item the \\emph{deadlock detection problem} is to decide whether all runs of $\\largesys$\n%are infinite and $\\largesys \\models \\A \\spec_{\\neg dead}$, \n%i.e., there are no local deadlocks,\n\\item the \\emph{parameterized model checking problem} (PMCP) is to decide whether $\\forall m \\ge n:\\ (A,B)^{(1,m)} \\models \\A h(A,B^{(k)})$, and \n%\\item the \\emph{parameterized deadlock detection problem} is to decide whether for all $m \\ge n$, all runs of $(A,B)^{(1,m)}$ are infinite and $(A,B)^{(1,m)} \\models \\A \\spec_{\\neg dead}$.\n\\item the \\emph{parameterized deadlock detection problem} is to decide whether, \n      for all $m \\ge n$, $(A,B)^{(1,m)}$ does not have global nor local deadlocks.\n\\end{itemize}\nFor a given number $n \\in \\bbN$ and specification $\\A h(A,B^{(k)})$ with $n \\ge k$,\n\\begin{itemize}\n\\item the \\emph{template synthesis problem} is to find process templates $A,B$ such that\n$\\largesys \\models \\A h(A,B^{(k)})$ and $\\largesys$ does not have global deadlocks\\footnote{\\label{footnote:local-deadlocks}Here we do not explicitly mention local deadlocks because they can be specified as a part of $\\A h(A,B^{(k)})$.}\n\\item \nthe \\emph{bounded template synthesis problem} for a pair of bounds $(\\bound_A,\\bound_B) \\in \\bbN \\times \\bbN$ \nis to solve the template synthesis problem with\n$\\card{A} \\leq \\bound_A$ and $\\card{B} \\leq \\bound_B$.\n\\item the \\emph{parameterized template synthesis problem} is to find process templates $A,B$ such that $\\forall m \\ge n:\\ (A,B)^{(1,m)} \\models \\A h(A,B^{(k)})$ and $(A,B)^{(1,m)}$ does not have global deadlocks\\footnoteref{footnote:local-deadlocks}.\n\\end{itemize}\nSimilarly, we define problems for specifications having $\\E$ instead of $\\A$.\nThe definitions can be flavored with different notions of fairness.\n", "meta": {"hexsha": "4e9e1b2324ffe0f7589909970b0e3321103f80bb", "size": 16385, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/guarded-systems/prelim.tex", "max_stars_repo_name": "5nizza/phd-thesis", "max_stars_repo_head_hexsha": "74a7a4c6ed06aa2894d2ba05f417f5f812730b78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thesis/guarded-systems/prelim.tex", "max_issues_repo_name": "5nizza/phd-thesis", "max_issues_repo_head_hexsha": "74a7a4c6ed06aa2894d2ba05f417f5f812730b78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis/guarded-systems/prelim.tex", "max_forks_repo_name": "5nizza/phd-thesis", "max_forks_repo_head_hexsha": "74a7a4c6ed06aa2894d2ba05f417f5f812730b78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 60.6851851852, "max_line_length": 699, "alphanum_fraction": 0.6956972841, "num_tokens": 5379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.679178686187839, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3448949948117473}}
{"text": "\\documentclass[a4paper]{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage{tikz}\n\\usetikzlibrary{quantikz}\n\\usepackage{physics}\n\\usepackage{pgfplots}\n\\usepgfplotslibrary{units}\n\\usetikzlibrary{patterns}\n\\usepackage{siunitx}\n\\usetikzlibrary{angles, quotes}\n\\usepackage{amssymb}\n\\usetikzlibrary{angles, arrows.meta, quotes}\n\\pgfplotsset{compat=1.17}\n\n\\usepackage{minted}\n\\usepackage[most]{tcolorbox}\n\\definecolor{lightgreen}{rgb}{0.56, 0.93, 0.56}\n\\definecolor{moonstoneblue}{rgb}{0.45, 0.66, 0.76}\n\n\\newtcblisting{myminted}{%\n    listing engine=minted,\n    minted language=c,\n    listing only,\n    breakable,\n    enhanced,\n    minted options = {\n        linenos,\n        breaklines=true,\n        breakbefore=.,\n        fontsize=\\footnotesize,\n        numbersep=2mm\n    },\n    overlay={%\n        \\begin{tcbclipinterior}\n            \\fill[gray!25] (frame.south west) rectangle ([xshift=4mm]frame.north west);\n        \\end{tcbclipinterior}\n    }\n}\n\\begin{document}\n\t\\title{\n\n\t\\vspace{1cm}\n\t\\Huge Grover's Algorithm\n\t}\n\n\t\\vspace{1cm}\n\n\t% if you are the only author, you might use the following\n\t% \\author{Name of student}\n\n\t% Insert here your name and correct mail address\n\t\\author{\\Large {Rahul Goel} \\Large \\\\  \\ \\ 2019111034\n\t\\date{November 2020}\n\t\\vspace{0.5cm}}\n\n\t% name of the course and module\n\t\\date{\n\t\\large Algorithm Analysis And Design \\\\\n\t\\vspace{1cm}\n\t}\n\n\t\\maketitle\n\t\\setlength{\\parindent}{0pt}\n\n\\vspace{8cm}\n\\begin{abstract}\n\\begin{center}\n\\normalsize\nThis document can be used as an introductory tutorial to Grover's Algorithm. It also includes certain peculiar observations that help to deepen the understanding about the differences between Quantum Computing and Classical Computing.\n\\end{center}\n\\end{abstract}\n\t\\newpage\n\t\\tableofcontents\n\t\\newpage\n\n\n\n\\maketitle\n\n\\textbf{Note - It has been assumed that $N = 2 ^ n$ throughout this sheet.}\n\n\\section{The Problem - Needle in a Haystack}\n\\indent The problem that Grover's Algorithm solves is the unstructured search problem. In simple words, among $N$ given entities, our task is to find one unique entity that satisfies a particular property.\n\nIn most cases, the situation is random and the only way a classical computer knows how to solve it is by brute force. This can take $O(N / 2)$ on average and up to $O(N)$ time in the worst case.\n\nThe problem of unstructured search is considered to be a hard problem for a classical computer as $N$ gets bigger in size. Grover's Algorithm provides a quadratic speedup to this and reduces the number of queries (time taken) to $O(\\sqrt{N})$. In fact, it has been proven that for a quantum computer, this is the best possible time complexity.\n\nNote - The problem gets easier and the complexity gets reduced by a constant factor when the entities that satisfy the property are more in number.\n\n\\section{How the Algorithm works}\n\\subsection{Intution 1}\nInitially, we start with $n$ qubits in such a way that in their superposition, all the $N$ states have equal amplitude (each has an equal probability of popping up when we measure the state).\n$$\\ket{\\psi_{initial}} = \\sum_{0}^{N-1} {\\alpha_i}\\ket{i} \\text{ where } \\alpha_i = \\frac{1} {\\sqrt{N}}$$\n\nLet $\\ket{j}$ be our needle in the haystack.\nNow, by means of certain quantum gates, the amplitude $\\alpha_j$ is first negated i.e. it becomes $-\\alpha_j$. And then every single $\\alpha_i$ is flipped about the mean of all amplitudes. As a result, $\\alpha_j$ stands out more than every other $\\alpha_i$.\n\\\\[3cm]\n\\indent This has been explained by means of the following diagrams (Not to scale).\nInitially the amplitudes of all the states are equal and the sum of their squares is equal to $1$.\n\n\\begin{tikzpicture}\n\\begin{axis}[ybar interval, ymax=0.8,ymin=-0.5, minor y tick num = 1, xmax = 8]\n\\addplot coordinates { (0, 0.353) (1, 0.353) (2, 0.353) (3, 0.353) (4, 0.353) (5, 0.353) (6, 0.353) (7,0.353)};\n\\draw [dashed] (0,0.353) -- (7, 0.353);\n\n\\end{axis}\n\\end{tikzpicture}\n\nThen a quantum circuit is applied to the state which flips the amplitude of the desired state.\n\n\\begin{tikzpicture}\n\\begin{axis}[ybar interval, ymax=0.8,ymin=-0.5, minor y tick num = 1, xmax = 8]\n\\addplot coordinates { (0, 0.353) (1, 0.353) (2, -0.353) (3, 0.353) (4, 0.353) (5, 0.353) (6, 0.353) (7,0.353)};\n\\draw [dashed] (0,0.3) -- (7, 0.3);\n\\end{axis}\n\\end{tikzpicture}\n\nNow the inversion of one of the amplitudes results in a slight decrement of the mean of all the amplitudes. If we now flip the amplitudes about their mean, we land up in the following state.\n\n\\begin{tikzpicture}\n\\begin{axis}[ybar interval, ymax=0.8,ymin=-0.5, minor y tick num = 1, xmax = 8]\n\\addplot coordinates { (0, 0.25) (1, 0.25) (2, 0.65) (3, 0.25) (4, 0.25) (5, 0.25) (6, 0.25) (7,0.25)};\n\\draw [dashed] (0,0.3) -- (7, 0.3);\n\\end{axis}\n\\end{tikzpicture}\n\nThe amplitude of the needle in the haystack has increased and hence if we measure the state now, the chance of getting the correct value is more than it was previously. However, the sum of probabilities of getting other states is still greater than the probability of getting the answer.\\\\[4pt]\n\nHence, we repeat the negation and inversion steps a number of times so that when we measure the state, we can be pretty sure that the outcome is the answer (the desirable state).\\\\[4pt]\n\nInitially $\\alpha_j = \\dfrac{1}{\\sqrt{N}}$. As we run iterations of the algorithm, $\\alpha_j$ increases and $\\alpha_i$, $\\forall$ $i \\neq j$, decreases, all in such a way that $\\sum_0 ^{N-1} {\\alpha_i}^2 = 1$.\nIf we want the probability of getting $\\ket{j}$ to be at least half, we need to pump up the magnitude $\\alpha_j$ to $\\dfrac{1}{\\sqrt{2}}$. At the point in time when $\\alpha_j = \\dfrac{1}{\\sqrt{2}}$, $\\alpha_i \\approx \\dfrac{1}{\\sqrt{2N}}$ $\\forall$ $i \\neq j$. Because the amplitude of the other states decreases continuously, we can say that throughout our iterations $\\alpha_i \\geq \\dfrac{1}{\\sqrt{2N}}$. Since in one iteration, the amplitude $\\alpha_j$ increases by at least by $2 \\alpha_i$ $\\left( i \\neq j\\right)$, the increment is at least $\\sqrt{\\dfrac{2}{N}}$. Therefore the number of iterations required is at least $\\dfrac{1 / \\sqrt{2}}{\\sqrt{2 / N}}$ $=$ $\\sqrt{N}$.\\\\\nWhen the number of favourable states is $M$, the number of iterations comes out to be $\\sqrt{\\dfrac{N}{M}}$.\n\n\\subsection{Intution 2}\n\nLet $\\ket{a}$ represent our desirable state i.e. $\\ket{j}$. And $\\ket{b}$ represent the superposition of all the remaining states with equal amplitudes i.e. $\\ket{b} = \\sum_{i \\neq j} \\dfrac{1}{\\sqrt{N - 1}} \\ket{i}$. It can be easily noticed that $\\ket{a}$ and $\\ket{b}$ are orthogonal to each other. Let $\\psi_0$ be our initial state which is $\\sum_{0}^{N - 1} \\dfrac{1}{\\sqrt{N}} \\ket{i}$. Now initially $\\ket{\\psi_0}$ lies really close to $\\ket{b}$ and it is the task of Grover's Algorithm to move it closer to $\\ket{a}$.\\\\[4pt]\n\n\\begin{tikzpicture}[\n            > = Straight Barb,\nphasor/.style = {very thick,-{Stealth}},\nangles/.style = {draw, <->, angle eccentricity=1,\n                 right, angle radius=15mm}\n                        ]\n% coordinates\n    \\draw[->, thick] (-0.5,0) -- (4,0) coordinate (x) node[below left] {$\\ket{b}$};\n    \\draw[->, thick] (0,-0.5) -- (0,4) node[below left] (y) {$\\ket{a}$};\n% phasors\n    \\draw[phasor] (0,0) -- (15:4) coordinate (i)  node[right] {$\\psi_0$};% used polar coordinates\n% angles drawn by pic\n\\coordinate (X)   at (0,0);\n\\draw\n    pic[\"$\\theta$\",angles] {angle=x--X--i}\n    ;\n\\end{tikzpicture}\n\nThe amplitude negation step leads to reflection of $\\ket{\\psi_0}$ about $\\ket{b}$. This is true because $\\ket{b}$ represents the superposition of all the undesirable states of equal amplitude. So the projection of $\\ket{\\psi_0}$ on $\\ket{b}$ will remain as it is while the projection of $\\ket{\\psi_0}$ perpendicular to $\\ket{b}$ will get negated. This is nothing but reflection about $\\ket{b}$.\n\n\\begin{tikzpicture}[\n            > = Straight Barb,\nphasor/.style = {very thick,-{Stealth}},\nangles/.style = {draw, <->, angle eccentricity=1,\n                 right, angle radius=15mm}\n                        ]\n% coordinates\n    \\draw[->, thick] (-0.5,0) -- (4,0) coordinate (x) node[below left] {$\\ket{b}$};\n    \\draw[->, thick] (0,-0.5) -- (0,4) node[below left] (y) {$\\ket{a}$};\n% phasors\n    \\draw[phasor, dotted] (0,0) -- (15:4) coordinate (i)  node[right] {$\\psi_0$};% used polar coordinates\n    \\draw[phasor] (0,0) -- (-15:4) coordinate (j)  node[right] {$\\psi$};% used polar coordinates\n% angles drawn by pic\n\\coordinate (X)   at (0,0);\n\\draw\n    pic[\"$\\theta$\",angles] {angle=x--X--i}\n    pic[\"$\\theta$\",angles] {angle=j--X--x}\n    ;\n\\end{tikzpicture}\n\nNow, we need to do inversion about the mean which is equivalent to reflection about the the equal amplitude state $\\sum_{0}^{N - 1} \\dfrac{1}{\\sqrt{N}} \\ket{i}$.\n\n\\begin{tikzpicture}[\n            > = Straight Barb,\nphasor/.style = {very thick,-{Stealth}},\nangles/.style = {draw, <->, angle eccentricity=1,\n                 right, angle radius=15mm}\n                        ]\n% coordinates\n    \\draw[->, thick] (-0.5,0) -- (4,0) coordinate (x) node[below left] {$\\ket{b}$};\n    \\draw[->, thick] (0,-0.5) -- (0,4) node[below left] (y) {$\\ket{a}$};\n% phasors\n    \\draw[phasor, dotted] (0,0) -- (15:4) coordinate (i)  node[right] {$\\psi_0$};% used polar coordinates\n    \\draw[phasor, dotted] (0,0) -- (-15:4) coordinate (j)  node[right] {$\\psi$};% used polar coordinates\n    \\draw[phasor] (0,0) -- (45:4) coordinate (k)  node[right] {$\\psi$};% used polar coordinates\n% angles drawn by pic\n\\coordinate (X)   at (0,0);\n\\draw\n    pic[\"$\\theta$\",angles] {angle=x--X--i}\n    pic[\"$\\theta$\",angles] {angle=j--X--x}\n    pic[\"\",angles] {angle=x--X--k}\n;\n\\end{tikzpicture}\n\nSo, after one iteration we have moved closer to the required state. We need to carry these iterations certain number of times so that when we measure a state, it collapses to the desirable state with high probability.\n\nEvery time the inversion about mean is done using the equal amplitude state only. It happens to be our initial state too but this is true only for the first iteration and not for further iterations.\n\n\\section{How to Implement the circuit?}\n\nNow that we know what to do, we have to question how to do it.\n\\subsection{Negation of Amplitude}\nOur first task is to negate the amplitude of the desirable quantum state.\nThe situation is like this that we have been given a quantum black box that outputs 1 for the desirable states and 0 for the undesirable states.\n\nInsert diagram here.\n\nIn other words, given the superposition $\\ket{x}\\ket{0}$, the circuit spits out the superposition $\\ket{x}\\ket{f(x)}$. We know the quantum circuits are designed in such a way that the answer register gets XORed with the output $f(x)$. So if the input superposition is $\\ket{x}\\ket{y}$, then the output superposition will be $\\ket{x}\\ket{y \\oplus{f(x)}}$.\n\nWith this knowledge, we can apply neat little hack and trick our black box into doing the task for us. We will initialise the answer register to $\\ket{-}$. Since\n\n\\begin{align*}\n\\ket{-} &= \\dfrac{1}{\\sqrt{2}} ( \\ket{0} - \\ket{1} )\\\\\n\\ket{- \\oplus {f(x)}} &= \\dfrac{1}{\\sqrt{2}} \\left( \\ket{0 \\oplus {f(x)}} - \\ket{0 \\oplus {f(x)}} \\right)\\\\\n\\ket{- \\oplus {f(x)}} &= \\dfrac{1}{\\sqrt{2}} \\left( \\ket{{f(x)}} - \\ket{\\overline{f(x)}} \\right)\\\\\n\\ket{- \\oplus {f(x)}} &= \\dfrac{1}{\\sqrt{2}} \\left( -1 \\right) ^ {f(x)} \\left( \\ket{0} - \\ket{1} \\right)\\\\\n\\ket{- \\oplus {f(x)}} &= \\left( -1 \\right) ^ {f(x)} \\ket{-}\\\\\n\\end{align*}\n\nTherefore, the entire transition will be\n$$\\ket{x}\\ket{-} \\longrightarrow \\left( -1 \\right) ^ {f(x)} \\ket{x} \\ket{-}$$\n\nNow, since it is a superposition that is being looked at as a whole, the term $\\left( -1 \\right) ^ {f(x)}$ can be associated with either $\\ket{x}$ or $\\ket{-}$.\nPutting $\\ket{x}  = \\sum_0^{N-1}\\alpha_i\\ket{i}$, we get the output from the black box as $\\sum_0^{N-1}\\alpha_i\\ket{i} \\left( -1 \\right) ^ {f(x)}$. Now since $f(x) = 1$ for $\\ket{j}$ and $0$ for all others, the amplitude is negated only for $\\ket{j}$. Thus we can do the amplitude negation easily.\n\\subsection{Inversion about mean}\nInversion about mean is the same as reflection about the uniform state i.e. reflection about the state $\\sum_0 ^{N - 1} \\dfrac{1}{\\sqrt{N}}$. Now for reflection about the uniform state, we can first map the uniform state to the all-zero state using a Hadamard Gate and then reflect about the all-zero state and then map the state back to the uniform state using another Hadamard Gate (Since Hadamard Gate is it's own inverse). So now we need a method to reflect about the all-zero state ($\\ket{00\\dots0}$ or simply $\\ket{0}$). Consider the following matrix :-\n\n\\[\nA = \\begin{bmatrix}\n    1       & 0      & \\dots & 0 \\\\\n    0       & -1     & \\dots & 0 \\\\\n    \\vdots  & \\vdots & \\ddots & \\vdots \\\\\n    0       & 0      & \\dots  & -1\n    \\end{bmatrix}\n\\]\n\nThis matrix maps negates all the states except for the state $\\ket{0}$. This is the same as reflection about $\\ket{0}$. This matrix is also a unitary matrix because $A A^{\\dagger} = I$ i.e. the conjugate transpose is its inverse. So we can conclude that the sequence of matrices $H_N A H_N$ (where $H_N$ stands for the unitary matrix corresponding to Hadamard Gate applied to n qubits.) does a reflection about the mean. And since all the matrices are unitary, they can be implemented using quantum gates.\n\nSo when we apply the operations of amplitude negation and inversion about mean repeatedly for around $\\sqrt{N}$ times, the probability of getting the correct answer exceeds half and we are highly likely to get the current answer. We can perform this several times to be sure of the answer since the method is probabilistic.\n\n\\section{Qiskit Code}\n\\textbf{Note - Please refer to the Jupyter Notebook for the output of the program and the explanatory comments and further experimentation.}\n\n\\begin{tcolorbox}[\n    enhanced,\n    attach boxed title to top left={xshift=6mm,yshift=-3mm},\n    title=Simulation Code,\n    boxed title style={size=small,sharp corners},\n    sharp corners,\n]\n\\begin{minted}{python}\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom qiskit import IBMQ, Aer, QuantumCircuit,\n    ClassicalRegister, QuantumRegister, execute\nfrom qiskit.providers.ibmq import least_busy\nfrom qiskit.quantum_info import Statevector\nfrom qiskit.visualization import plot_histogram\nfrom qiskit.extensions import UnitaryGate\nfrom math import sqrt\n\nn = 5\nN = 2 ** n\n\ndef initialize(qc, qubits):\n    for q in qubits:\n        qc.h(q)\n    return qc\n\ndef get_oracle_matrix(N, values):\n    oracle_matrix = np.identity(N)\n    for value in values:\n        oracle_matrix[value][value] = -1\n    return oracle_matrix\n\ndef get_diffusion_matrix(N):\n    diffusion_matrix = np.zeros((N, N), dtype = float)\n    diffusion_matrix.fill(2 / N)\n    diffusion_matrix -= np.identity(N)\n    return diffusion_matrix\n\n\\end{minted}\n\\end{tcolorbox}\n\\begin{tcolorbox}[\n    enhanced,\n    attach boxed title to top left={xshift=6mm,yshift=-3mm},\n    title=Simulation Code,\n    boxed title style={size=small,sharp corners},\n    sharp corners,\n]\n\\begin{minted}{python}\n\noracle_matrix = get_oracle_matrix(N, values = [2])\noracle_unitary_gate = UnitaryGate(oracle_matrix)\n\ndiffusion_matrix = get_diffusion_matrix(N)\ndiffusion_unitary_gate = UnitaryGate(diffusion_matrix)\n\nqc = QuantumCircuit(n)\nqc = initialize(qc, [x for x in range(n)])\n\nfor i in range(5):\n    qc.unitary(oracle_matrix, [x for x in range(n)])\n    qc.unitary(diffusion_matrix, [x for x in range(n)])\nqc.draw()\n\nqc.measure_all()\n\nqasm_simulator = Aer.get_backend('qasm_simulator')\nshots = 1024\nresults = execute(qc, backend=qasm_simulator,\n                    shots=shots).result()\nanswer = results.get_counts()\nplot_histogram(answer, figsize = (15, 12))\n\\end{minted}\n\\end{tcolorbox}\n\n\\section{Findings}\nWhile it was mostly studying stuff discovered by others, I did observe some things on my own that most probably have already been observed.\n\n\\subsection{Going beyond $\\sqrt{N}$ queries}\n\nIn classical computers, it just doesn't hurt to go a few extra steps (since they don't harm the overall time complexity) just to be sure of our result.\nI tried this out on the implementation that I wrote and the results surprised me. After exceeding the required number of queries the amplitude of the desired state starts to decrease again and reaches a certain value and increases again and oscillates like this. Also, the period of this oscillation varies along with the number of qubits we are dealing with. When the number of qubits is small, the value decreases quite suddenly and even deviating by 1 query can alter the probability of the outcome easily. However, when the number of qubits is large this is smoothened out, and a query or two give or take doesn't affect the outcome by much.\n\nAll in all, minimum $\\sqrt{N}$ queries are required and should be sufficient to give the answer. One should not go beyond this limit. Rather, one should re-conduct the experiment from the initial state to verify the answer.\n\nSo, what may be happening has been attempted to be explained with the following diagrams.\\\\\nAfter $\\sqrt{N}$ iterations, the state $\\psi$ is quite close to the desirable state. The probability of collapsing to the desirable state is as high as $80\\% - 90\\%$ (usual number as seen from the simulator code).\n\n\\begin{tikzpicture}[\n            > = Straight Barb,\nphasor/.style = {very thick,-{Stealth}},\nangles/.style = {draw, <->, angle eccentricity=1,\n                 right, angle radius=15mm}\n                        ]\n% coordinates\n    \\draw[->, thick] (-4,0) -- (4,0) coordinate (x) node[below left] {$\\ket{b}$};\n    \\draw[->, thick] (0,-1) -- (0,4) node[below left] (y) {$\\ket{a}$};\n% phasors\n    \\draw[phasor, dotted] (0,0) -- (15:4) coordinate (i)  node[right] {$\\psi_0$};% used polar coordinates\n    \\draw[phasor] (0,0) -- (80:4) coordinate (k)  node[right] {$\\psi$};% used polar coordinates\n% angles drawn by pic\n\\coordinate (X)   at (0,0);\n\\draw\n    pic[\"\",angles] {angle=x--X--i}\n    pic[\"$\\theta$\",angles] {angle=x--X--k}\n;\n\\end{tikzpicture}\n\nNow, when we do amplitude negation by reflecting about $\\ket{b}$, we get state as shown.\n\n\\begin{tikzpicture}[\n            > = Straight Barb,\nphasor/.style = {very thick,-{Stealth}},\nangles/.style = {draw, <->, angle eccentricity=1,\n                 right, angle radius=15mm}\n                        ]\n% coordinates\n    \\draw[->, thick] (-4,0) -- (4,0) coordinate (x) node[below left] {$\\ket{b}$};\n    \\draw[->, thick] (0,-4) -- (0,4) node[below left] (y) {$\\ket{a}$};\n% phasors\n    \\draw[phasor, dotted] (0,0) -- (15:4) coordinate (i)  node[right] {$\\psi_0$};% used polar coordinates\n    \\draw[phasor] (0,0) -- (-80:4) coordinate (k)  node[right] {$\\psi$};% used polar coordinates\n% angles drawn by pic\n\\coordinate (X)   at (0,0);\n\\draw\n    pic[\"\",angles] {angle=x--X--i}\n    pic[\"$\\theta$\",angles] {angle=k--X--x}\n;\n\\end{tikzpicture}\n\nAnd when we do the inversion about mean, we get the state as shown.\n\n\\begin{tikzpicture}[\n            > = Straight Barb,\nphasor/.style = {very thick,-{Stealth}},\nangles/.style = {draw, <->, angle eccentricity=1,\n                 right, angle radius=15mm}\n                        ]\n% coordinates\n    \\draw[->, thick] (-4,0) -- (4,0) coordinate (x) node[below left] {$\\ket{b}$};\n    \\draw[->, thick] (0,-1) -- (0,4) node[below left] (y) {$\\ket{a}$};\n% phasors\n    \\draw[phasor, dotted] (0,0) -- (15:4) coordinate (i)  node[right] {$\\psi_0$};% used polar coordinates\n    \\draw[phasor] (0,0) -- (105:4) coordinate (k)  node[right] {$\\psi$};% used polar coordinates\n% angles drawn by pic\n\\coordinate (X)   at (0,0);\n\\draw\n    pic[\"\",angles] {angle=x--X--i}\n    pic[\"$\\theta$\",angles] {angle=x--X--k}\n;\n\\end{tikzpicture}\n\nSo exceeding one query does not make much difference, but when we do this a few number of times, $\\psi$ keeps on deviating from the required state. And then after some number of such iterations, it again starts to return to the position. And this \"some number of iterations\" is less than $\\sqrt{N}$ because since the angle made from $\\ket{b}$ is large, the iterations of the algorithm make huge changes in the states and thus requires fewer steps.\n\n\\textbf{Note - This was observed when there was only one desirable state. With multiple desirable states a similar pattern was followed but not accurately.}\n\n\\subsection{Assumption about the given black box}\nIt is assumed that a quantum circuit has already been implemented that identifies the answer that we use as a black box. Well, if such a black box has been implemented, the maker of the black box would already know about the desired state.\\\\\nI think that maybe in future a situation may arise when the implemented black box is provided by nature and the algorithm may be used to find the desirable state.\\\\\n\n\\section{Conclusion}\n\nRegardless of the black-box property mentioned above, this amazing algorithm does give an idea about the power of Quantum Computing. It gives a quadratic speed up in searching which can be used in database searching. The quadratic speed up can be used to solve some NP-Complete Problems by doing exhaustive searching over the set of all possible solutions (though not for large $N$ as exponential term still dominates).\n\n\\end{document}.\n", "meta": {"hexsha": "f9628cba3e0435e374dd017ebd707cd437f56a8c", "size": 21177, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Sheets/GroversAlgorithm/GroversAlgorithm.tex", "max_stars_repo_name": "ishaanshah/Cuantum-Qomputing", "max_stars_repo_head_hexsha": "79035133f148f37d049f3e009408b17262115efd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-04T12:45:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T12:45:43.000Z", "max_issues_repo_path": "Sheets/GroversAlgorithm/GroversAlgorithm.tex", "max_issues_repo_name": "ishaanshah/Cuantum-Qomputing", "max_issues_repo_head_hexsha": "79035133f148f37d049f3e009408b17262115efd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sheets/GroversAlgorithm/GroversAlgorithm.tex", "max_forks_repo_name": "ishaanshah/Cuantum-Qomputing", "max_forks_repo_head_hexsha": "79035133f148f37d049f3e009408b17262115efd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-24T04:34:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T04:34:35.000Z", "avg_line_length": 50.6626794258, "max_line_length": 679, "alphanum_fraction": 0.6866411673, "num_tokens": 6276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.34488799028809203}}
{"text": "\\chapter{Background}\n\\label{chap:background}\nImage classification refers to a task that requires from method to determine the categories to which picture belongs. Such challenges that utilize standard datasets like ImageNet and PASCAL VOC limit this problem to a question if objects of particular classes presented on the image \\cite{Russakovsky2015ImageNet, Everingham2010PASCAL-VOC}. However, real-world settings might require extending this question to more general one \\cite{Wang2016CNN-RNN:Classification}. For instance, in this study, the search extended beyond merely objects to include other image properties including color, weather, action, and sceneries. %In other words, image classification system should be able to find a correct placement of a picture in a multi-dimensional space of categories.\n\n% \\section{Image classification}\n% definition of image classification\n\n\\section{Deep convolutional neural networks}\n\nA standard neural network consists of computational units called neurons. Neurons are connected to each other in particular way to form a network. Neurons in such networks are organized in groups or ``layers'' for computational efficiency reasons since it allows to apply vector operations \\cite{cs231n-nn1}.  Each input connection to a neuron has dedicated weight. Non-liner \\textit{activation function} use these input weights to determine when to activate particular neuron and send a signal further \\cite{Schmidhuber2015DeepOverview}. Activation function can be different, however recent years ReLU function is mostly used in modern DNN due to its computational efficiency and good output results \\cite{relu, Krizhevsky2012ImageNetDNN}. The ``depth'' of the neural network is identified as an amount of layers except input one \\cite{Schmidhuber2015DeepOverview}.\n\nThe process of \\textit{training} the neural network is optimization of each neuron input weights in such way that the particular input to a network will produce desired output. This optimization is achieved by first introducing loss function which represents how ``far'' given output is from the desired one. After that, on each iteration of training, by calculating gradients of a loss function on given weights, the system determines how it should adjust weights to decrease the computed loss \\cite{cs231n-opt1}. Modern DNNs use backpropagation approach of gradient calculation due to its efficiency \\cite{cs231n-opt2}. \n\nConvolutional Neural Networks (CNN) have the same core ideas as any other neural networks except that CNN architectures assume that the inputs are images \\cite{cs231n-conv}. Unlike conventional neural networks, instead of processing images pixel-by-pixel CNN is searching for patterns in image patches of different sizes. Each convolution can also be perceived as a feature extractor, such as the one that detects particular edge angle or color. Such convolution functions are also organized in layers where output features from one layer can be an input data for next convolutional filters. Therefore, an end system consists of filters cascade, where, similar to human vision, low-level features, like edges, are recognized on the fist levels, and higher levels trigger on more complex features like different shapes and patterns~\\cite{Zeiler2014VisualizingNets}\n\nThe main difference between machine learning approach and deep convolutional neural networks is that the former one has an additional step of supervised feature extraction. In contrast, in deep learning approach feature extraction happens automatically by the internal network itself. Therefore DNN can be considered as a ``black box'' system. For instance, in the case of image classification, such system will have raw picture pixels as an input and classified category numbers as output.\n\nTo improve the generalizability of results and to be able to compare networks with different hyperparameters the common approach is to use dataset splitting where an image collection is partitioned into three parts \\cite{cs231n-cls}. The first part, \\textit{called training} set, is employed directly for training, while the second part, called \\textit{validation set}, is used to compare different architectures and control overfitting.  Overfitting is a state of the system when it optimizes to a noise in a training data instead of searching the underlying patterns \\cite{cs231n-nn1}. Such optimization can potentially reduce the generalizability of the system and should be avoided \\cite{cs231n-nn1}. The usual way to control overfitting of the model is to check system performance on a validation set periodically during the training process \\cite{cs231n-nn3}. If the loss computed on a training set gets smaller with more iterations, but validation loss increases or stays the same, then it is an evidence that the model is starting to overfit on the training set \\cite{cs231n-nn3}. To be able to monitor the generalizability of the method, validation set should not contain any images from the training set. The third part of the dataset, which is called \\textit{test set}, is used for a final evaluation of the method. The separation between validation and test sets is important for the similar reason as with separation between training and validation sets. When different network implementations are compared using the validation set, and the best one is selected, hyperparameters can overfit on the validation set similar to the state when network is overfitting on the training set \\cite{cs231n-cls}. Meaning that chosen parameters will be optimized for the particular images in the validation set. Therefore, it is important to test the final system on a separate set of pictures, which CNN has not seen at any time during the training process. According to Andrew Ng, The common ratio between these tree sets is 60\\%/20\\%/20\\%, where the training set gets 60\\% of images while validation and test sets receive 20\\% each \\cite{Ng2016NutsLearning}.\n% train, val, test split\n% different layers\n% overfitting\n% backpropagation\n\n\\section{Multi-label image classification}\nOpposite to a single-label image classification, in multi-label case picture can belong to more than one category. Several labels can both describe all objects presented on the picture and characterize the objects or picture itself.\n\nThere are two group of multi-label image classification methods:\n\\begin{itemize}\n    \\item That process parts of the images and use CNN to find a single label for each of the part \\cite{Wei2016HCP, Ren2016,  Yang2015},\n    \\item That train CNN on the whole picture, similarly to single label methods, but use different loss functions that take several labels into account \\cite{Gong2013DeepRanking}.\n\\end{itemize}\n\nAn example of the first type of network is described by Wei et al. in their paper ``HCP: A Flexible CNN Framework for Multi-Label Image Classification''  \\cite{Wei2016HCP}. The core idea of the proposed method is to reuse already developed CNNs that were trained to classify single-labeled pictures in a multi-label scenario. The authors proposed deep CNN infrastructure called ``Hypotheses-CNN-Pooling'' (HCP) to achieve this. Its architecture is shown on Figure \\ref{fig:hcp-net}.\n\n\\begin{figure}[h!]\n    \\centering\n    \\includegraphics[width=\\textwidth]{hcp-net}\n    \\caption{Hypotheses-CNN-Pooling infrastructure \\cite{Wei2016HCP}}\n    \\label{fig:hcp-net}\n\\end{figure}\n\nThe whole classification pipeline proposed by the authors consists of the following steps:\n\\begin{enumerate}\n    \\item Applying state of the art object detection technique (for example BING \\cite{Cheng2014} or EdgeBoxes \\cite{Zitnick2014}) to get the set of hypothesis,\n    \\item Using proposed hypothesis selection method reduce the number of initial hypotheses,\n    \\item Use pre-trained CNN to assign single label for each hypothesis,\n    \\item Use cross-hypothesis max-pooling to create the vector of labels found on the whole picture.\n\\end{enumerate}\n\nAuthors claim of getting up to 90.9\\% of Mean Average Precision (which is defined in PASCAL Challenge \\cite{Everingham2010PASCAL-VOC}) on PASCAL VOC 2012 image dataset.\n\nYang et al. proposed similar infrastructure, but extended it with additional large-margin nearest neighbor (LMNN) CNN that incorporates knowledge of ground truth bounding boxes of the training set to improve results  \\cite{Yang2015}. This extra layer tries to find similar objects in the test image to the ones extracted from the training set (ground-truth object set) independently from the other layer that employs more usual CNN. Results from the both layers are taken into account in the final prediction vector.\n\nThe method described by Girshik et al. in ``Rich feature hierarchies for accurate object detection and semantic segmentation'' paper also highly rely on the ground-truth bounding box during the training phase \\cite{Girshick2014}. In particular, generated hypothesis are ranged based on the overlap with ground-truth box.\n\nOquab et al. proposed method that also use bounding box information to produce labels for training images \\cite{Oquab2014TransferringMidLevel}. Specifically, they propose to generate around 500 square patches from the picture and put a single label on each patch dependently on the overlap with the ground truth bounding box. Patches which intersect with two or more objects are filtered out, and the once which do not intersect with any objects are labeled as a background. Example training data generated from the image and ground-truth information is shown on Figure \\ref{fig:patches-example}.\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[scale=0.35]{patches-example}\n    \\caption{Training data generation example using patching method \\cite{Oquab2014TransferringMidLevel}}\n    \\label{fig:patches-example}\n\\end{figure}\n\nCurrently, the first type of multi-label classification methods with image partitioning show improved performance compared to the ones that use the whole pictures \\cite{Wei2016HCP, Ren2016, Yang2015}. However, such methods require having either ground truth bounding box encoded in metadata in addition to labels which identifies the location of all objects on the image \\cite{Chen2015ContextualizingClassification, Dong2013Subcategory-AwareClassification}, or pre-trained single-label classifier for the same set of categories \\cite{Wei2016HCP}. In addition, this approach might be more suitable for searching for objects in the picture, but not perform as good to assign labels describing the whole image since it processes only part of a picture at a time. For instance, the dataset used in this study had label \\textit{alone} that separates images with single objects, or \\textit{landscapes} which characterize the whole picture. These kinds of categories might be challenging to classify using method that splits an image.\n\nIn contrast to previous papers, Gong et al. applied CNN to the whole picture without partitioning \\cite{Gong2013DeepRanking}. The main contribution of this study was not to produce new multi-label classification method, but to compare different loss functions in multi-label classification context. Results showed that weighted approximated-ranking loss (WARP) improved the classification performance of the categories with a small number of pictures which can be an essential factor for unbalanced datasets.\n\nWang et al. in their research were also trying to improve multi-label image classification performance for realistic image collections \\cite{Wang2016CNN-RNN:Classification}. Authors point out on issues connected with methods that transforming multi-label task into a single-label one. Researchers identify the lack of modeling semantic dependencies between categories in such methods. The main reason for this is that such approaches treat image categories completely independently, while some of the labels might occur together more often than others. To solve this problem, the authors propose to utilize Recurrent Neural Network (RNN) in addition to CNN, which can model semantic relevance between images.\n\nMost of the presented methods use so-called transfer learning technique in different ways to improve their results and to utilize the work from the other studies to their benefit. Brief description and motivation behind this approach presented in the next section.\n\n% \\section{Caffe framework}\n\n% pipeline of computations going through layers\n% sigmoid cross entropy\n\n\\section{Transfer learning}\n\\label{sec:transfer-learning}\n\nUsually, the usage of deep learning approach adds additional requirements: to have enough processing power and big enough image dataset. One of the most common methods to reduce these constraints called \\textit{transfer learning}. The main principal behind it is to reuse ``knowledge'' of a pre-trained neural network on one task and transfer this knowledge to another one \\cite{Pan2010TransferLearningSurvey, Oquab2014TransferringMidLevel}. This idea appeared when people noticed that first layers of most CNNs learn to trigger on the same features like corners, edges, color conjunctions, therefore there is no need to discover them in each network \\cite{Zeiler2014VisualizingNets}.\n\nThere are two types of transfer learning \\cite{Yosinski2014HowTransferable}:\n\\begin{itemize}\n    \\item With frozen layers, when layers copied from the pre-trained network do not change their weights during the backpropagation phase, in other words, their learning rates are set to zero,\n    \\item Fine-tuning, when copied layers only start with pre-trained weights, but during the training phase adjust just their values like all other layers.\n\\end{itemize}\n\nOquab et al. describe in detail the usage of transfer learning for multi-label classification. In particular, they show how pre-trained network on one category set can be used to find labels for more general categories (for example source categories might include different dog breeds while target set may contain only general label ``dog'') or even entirely new ones \\cite{Oquab2014TransferringMidLevel}. Insights provided in this research will be applied in the project since target NTB dataset also has a different set of categories compared to the ones available in the standard image collections.\n\nRecent studies also suggest that the usage of a pre-trained model can improve the generalizability of the final image classification system in contrast to the system trained on the target dataset from scratch \\cite{Oquab2014TransferringMidLevel, Yosinski2014HowTransferable}. The transfer learning method employed in this project, which is described in the next chapter, allowed to reduce dataset size and performance requirements needed for successful system training. \n\n\\section{Real-world datasets}\nSome datasets like PASCAL VOC or NUS WIDE are created from realistic pictures that contain several objects or people in different combination and interactions between them \\cite{Everingham2010PASCAL-VOC, Chua2009NUS-WIDE}. Creators of such datasets, as well as other researchers, argue that real-world images are more likely to have multi-label nature by having both multiple entities in the picture as well as such category set that can describe image or object in several prospectives \\cite{Everingham2010PASCAL-VOC, Chua2009NUS-WIDE, Wang2016CNN-RNN:Classification, Dong2013Subcategory-AwareClassification}. Wang et al. poit out that in addition to objects, such images can contain labels that represent scenes, actions, and parts of some entities \\cite{Wang2016CNN-RNN:Classification}. Authors also identify the challenge of small objects on such images that can be ignored by classification methods, especially when full pictures are processed in a neural network.\n\nExcept for the picture collection itself, dataset should also contain metadata for image and a defined set of categories. While datasets described earlier consist of realistic pictures, the set of categories and therefore images were designed and moderated for the purpose of further training and comparison of image classification systems. Therefore, there is still a question on how different state of the art methods can be applied to datasets that were created for other reasons and how their metadata utilization can be maximized. In addition to realistic pictures, such datasets can have additional challenges connected with a unique set of labels, a less balanced size of categories, a big number of both systematic and random errors.\n\n\\subsection{Current state of the NTB dataset}\nAs it was mentioned earlier, NTB provided their labeled image collection for the purpose of these project. Currently, NTB dataset contains around one million of manually annotated pictures and more than ten millions of images without labels. Therefore, the fist usage of the automatic image classification system for the company is to propagate annotations on other images from the collection. NTB has its unique set of categories organized in a tree structure. The company uses these tags to provide a solution for pictures search to their customers. Therefore the second application of the system would be to incorporate an image classification in this search solution. The dataset is specific to Norway and to particular topics including sports, finances, politics, and media. More in-depth analysis of the NTB dataset will be presented in Section \\ref{sec:dataset-analysis}.\n\n% own set of categories, have to trafsfer them as many as possible", "meta": {"hexsha": "781a192c9b822c5ab54b84a3bd319d5a81058c10", "size": 17415, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "background.tex", "max_stars_repo_name": "uvNikita/master-thesis", "max_stars_repo_head_hexsha": "56b22f7b8a645ee3b144860bccf8c2c8551b287b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-02-27T13:25:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-04T03:49:18.000Z", "max_issues_repo_path": "background.tex", "max_issues_repo_name": "uvNikita/master-thesis", "max_issues_repo_head_hexsha": "56b22f7b8a645ee3b144860bccf8c2c8551b287b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "background.tex", "max_forks_repo_name": "uvNikita/master-thesis", "max_forks_repo_head_hexsha": "56b22f7b8a645ee3b144860bccf8c2c8551b287b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 172.4257425743, "max_line_length": 2161, "alphanum_fraction": 0.8164226242, "num_tokens": 3576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.34488799028809203}}
{"text": "%\n% CMPT 454: Database Systems II - A Course Overview\n% Section: Query Optimization\n%\n% Author: Jeffrey Leung\n%\n\n\\section{Query Optimization}\n\t\\label{sec:query-optimization}\n\\begin{easylist}\n\n& Notation: Given a schema $R$:\n\t&& The size in pages is denoted as $|R|$\n\t&& The number of records per page is denoted as $p_R$\n\t&& The size of the buffer is $B$\n\n& Clustered indices are only applicable for terms which form a prefix of the search key\n\t&& E.g. The index $<A, B, C>$ can be used for the search key $A = 1, B = 3$\n\n\\clearpage\n\\end{easylist}\n\\subsection{Optimizing Equality Joins}\n\t\\label{subsec:optimizing-equality-joins}\n\\begin{easylist}\n\n& \\textbf{Join:} Database operation where a single set of rows are returned, created from two relations\n\n& E.g. \\textrm{SELECT * FROM Sailors S, Reserves R WHERE R.id = S.id}\n\t\n& \\textbf{Simple Nested Loops (SNL) join:} Equality join implementation where nested loops compare equality values using 1-page buffers\n\t&& Consists of multiple nested loops, each of which loops through a table\n\t\t&&& \\textbf{Outer table:} Table in an SNL join which is scanned outside the other nested loop(s)\n\t\t&&& \\textbf{Inner table:} table in an SNL join which is scanned inside the other nested loop(s)\n\t&& Runtime:\n\t\t\\begin{align*}\n\t\t\t|Outer| + |Outer| \\cdot |Inner|\n\t\t\\end{align*}\n\t\t&&& $|Outer|$ is the cost of loading each value from the outer table into memory\n\t\t&&& $|Outer| * |Inner|$ is the cost of loading each value from the inner table into memory, and comparing with an outer table value\n\t\t&&& To optimize, smaller tables should be implemented as the outer\n\t\t\t\n& \\textbf{Block Nested Loops (BNL) join:} Equality join implementation where nested loops compare equality values using multi-page buffers\n\t&& \\textbf{Block:} Fixed-size set of pages representing the size of a buffer\n\t&& Runtime:\n\t\t\\begin{align*}\n\t\t\t|Outer| + |Outer\\ Blocks| \\cdot |Inner| \\\\\n\t\t\t= |Outer| + \\left\\lceil \\frac{|Outer|}{B-2} \\right\\rceil \\cdot |Inner|\n\t\t\\end{align*}\n\t\t&&& Two buffer pages are used; one as the output buffer and one as the input buffer for the inner table\n\t\t&&& To optimize, smaller tables should be implemented as the outer\n\n& \\textbf{Index Nested Loops (INL) join:} Equality join implementation where nested loops compare equality values, and inner loops use an index to search matching values from the outer loop\n\t&& Runtime:\n\t\t\\begin{align*}\n\t\t\t|Outer| + |Outer| \\cdot p_{outer} \\cdot \\textrm{probing costs}\n\t\t\\end{align*}\n\t\t&&& $|Outer| \\cdot p_{outer}$ represents the number of records in table $R$\n\t\t&&& \\textbf{Probing cost:} I/O cost to search for an entry and record using an index\n\t\t\t&&&& Probing cost of data entries in a hash index: 1.2\n\t\t\t&&&& Probing cost of data entries in a B+ tree: 3-4\n\t\t\t&&&& Probing cost of data records when the search key is a candidate key: 1\n\t\t\t&&&& Probing cost of data records when the search key is not a candidate key, in a clustered index: 1\n\t\t\t&&&& Probing cost of data records when the search key is not a candidate key, in an unclustered index: $\\frac{\\textrm{records in inner}}{\\textrm{records in outer}}$\n\t\t\t\t\n\t&& Equality with multiple attributes: Index must apply to one or more of the attributes\n\t&& Inequality: Index must be clustered B+ tree\n\n& \\textbf{Sort-merge-join (SMJ):} Equality join implementation where tables are sorted externally, written back to the disk, merged by equality, then sent to output\n\t&& Runtime:\n\t\t&&& Sorting:\n\t\t\\begin{align*}\n\t\t\t  2 \\cdot |T_1| \\cdot (\\left\\lceil \\log_{B-1} (\\frac{|T_1|}{B}) \\right\\rceil + 1) \\\\\n\t\t\t+ 2 \\cdot |T_2| \\cdot (\\left\\lceil \\log_{B-1} (\\frac{|T_2|}{B}) \\right\\rceil + 1)\n\t\t\\end{align*}\n\t\twhere $T_1$, $T_2$ are tables and $B$ is the buffer size\n\t\t&&& Merging:\n\t\t\\begin{align*}\n\t\t\t|T_1| + |T_2|\n\t\t\\end{align*}\n\t\t&&& Optimization 1: Find the tables which have the fewest maximum count of any repeating value, then use those those tables as the outer loop (to fit as much outer loop data as possible into the input buffer)\n\t\t&&& Optimization 2: Join the runs of the sorted tables after only the first pass of the external sort\n\t\t\t&&&& When joining, each run is allocated a single buffer\n\t\t\t&&&& Only possible if $B \\geq \\sqrt{\\textrm{max} \\{ |T_1|, |T_2| \\} }$\n\t\t\t&&&& Runtime:\n\t\t\t\\end{easylist}\n\t\t\t\\begin{align*}\n\t\t\t\t& \\textrm{(Cost of pass 0)} + \\textrm{(Merging all runs)} \\\\\n\t\t\t\t& = 2 (|R|+|S|) + (|R|+|S|) \\\\\n\t\t\t\t& = 3 (|R|+|S|)\n\t\t\t\\end{align*}\n\t\t\t\\begin{easylist}\n\t\t\t\t\n\t&& Equality with multiple attributes: Sort based on all joined attributes\n\t&& Inequality: Not applicable\n\t\t\t\n\n& \\textbf{In-memory probing by hash table:} CPU runtime optimization which hashes database table pages into buckets\n\t&& Reduces excess page retrieval and optimizes access speed to specific pages\n\n& \\textbf{Hash-join (HJ):} Equality join implementation where tables are partitioned into hash buckets, then the values in each hash bucket is joined with the matching values in the hash bucket from the other table\n\t&& Hash bucket notation:\n\t\t&&& $T_i$ represents the contents of hash bucket $i$ created by partitioning $T$\n\t\t&&& Assuming partitions are roughly equally sized: $|T_i| = \\frac{|T|}{B-1}$\n\t&& Tables can be hash-joined in one scan if and only if $B-2 \\geq \\textrm{min} \\{ |R_i|, |S_i| \\}$ for all $R_i$, $S_i$ given tables $R$, $S$\n\t\t&&& Implies $B \\geq \\sqrt{\\textrm{min} \\{ |R_i|, |S_i| \\} }$\n\t\t&&& If tables cannot be hash-joined in one scan, recursively apply hash-join to the bucket(s) which are too large to fit in memory\n\t&& Runtime (assuming $R_i$ or $S_i$ can fit in memory):\n\t\\end{easylist}\n\t\\begin{align*}\n\t\t& \\textrm{Cost of partitioning both relations - read and write} + \\textrm{Cost of joining relations} \\\\\n\t\t& = 2( |R|+|S|) + (|R|+|S|) \\\\\n\t\t& = 3( |R|+|S|)\n\t\\end{align*}\n\t\\begin{easylist}\n\t&& Parallelizable\n\t&& Sensitive to data skew\n\t\n\t&& Equality with multiple attributes: Hash  based on all joined attributes\n\t&& Inequality: Not applicable\n\n\\clearpage\n\\end{easylist}\n\\subsection{Optimizing Selections}\n\t\\label{subsec:optimizing-selections}\n\\begin{easylist}\n\n& \\textbf{Selection:} Database operation where a subset of rows are returned from a relation\n\n& Notation:\n\t&& \\textbf{Reduction factor (RF):} Percent of data that a table is reduced by through a selection operation\n\n& Size of result:\n\\begin{align*}\n\t|T| \\cdot \\textrm{RF}\n\\end{align*}\n\n& Runtime:\n\t&& No index or not clustered on the attributes: $|T|$\n\t&& Clustered on the attributes: $|T| \\cdot \\textrm{RF}$\n\n& Page I/O:\n\t&& No index or not clustered on the attributes: $|T| \\cdot \\textrm{RF} \\cdot p_T$\n\t\t&&& Optimization: Collect and sort record IDs before retrieving them\n\t&& Clustered on the attributes: $|T| \\cdot \\textrm{RF}$\n\t\t&&& Clustered records are more likely to be on the same page\n\n& Converted to conjunctive normal form (CNF) before processing\n\n& Optimizing with multiple indices:\n\t&& Approach 1: Retrieve a set of records using the most selective/restrictive index (minimizing returned values), then apply remaining terms\n\t&& Approach 2: Retrieve sets of record IDs using all indices, intersect them, sort them, retrieve the records, then  apply remaining terms\n\n\\clearpage\n\\end{easylist}\n\\subsection{Optimizing Projections}\n\t\\label{subsec:optimizing-projections}\n\\begin{easylist}\n\n& \\textbf{Projection:} Database operation where a subset of columns are returned from a relation\n\t&& Often includes a $\\textrm{DISTINCT}$ operation\n\n& \\textbf{Standard projection:} Projection implementation using a modified version of the external sort Pass 0\n\t&& When writing during external sort Pass 0, drop unnecessary fields\n\t&& During external sort merging of runs, drop duplicate rows\n\n\t&& Page I/O:\n\t\\end{easylist}\n\t\\begin{align*}\n\t& \\textrm{(Reading all records)} + \\textrm{(Writing partial columns)} \\\\\n\t& + \\textrm{(Reading the same data)} \\\\\n\t& + \\textrm{(Merging non-duplicate rows)} \\\\\n\t= & |T| + |T| \\cdot \\textrm{(\\% of data projected)} * 2 \\\\\n\t  & + |T| \\cdot \\textrm{(\\% of data projected)} \\cdot \\textrm{(\\% of distinct data merged)}\n\t\\end{align*}\n\t\\begin{easylist}\n\n& \\textbf{Hash projection:} Projection implementation where hashing is used to eliminate duplicates\n\t&& Process: Use a hash function on all wanted attributes to partition the table into $B-1$ partitions (while discarding unprojected fields), use a new hash function on all fields of each partition to discard duplicates\n\n& Index terms:\n\t&& \\textbf{Index-only projection:} Projection operation where all projected attributes are in the index's search key\n\t\t&&& Requires sorting afterwards if the projected attributes are not a prefix of the search key\n\t\t&&& Requires duplicate removal\n\t&& \\textbf{Index-only, no sort needed projection:} Projection operation where all projected attributes constitute a prefix of the index's search key\n\t\t&&& Requires duplicate removal\n\n\\clearpage\n\\end{easylist}\n\\subsection{Optimizing Unions}\n\t\\label{subsec:optimizing-unions}\n\\begin{easylist}\n\n& \\textbf{Union:} Database operation where two relations with matching columns are combined\n\t&& Includes removal of duplicates\n\n& \\textbf{Hash-based union:} Union implementation which utilizes two hash functions\n\t&& Process:\n\t\t&&& Hash both relations into partitions\n\t\t&&& Re-hash a partition from the first relation, into new partitions\n\t\t&&& Re-hash the matching partition from the second relation, into the same re-partitions (avoiding adding duplicates)\n\n\\end{easylist}\n\\subsection{Optimizing Differences}\n\t\\label{subsec:optimizing-differences}\n\\begin{easylist}\n\n& \\textbf{Difference:} Database operation between two relations where any row from the first relation which exists in the second relation is removed\n\n& \\textbf{Hash-based difference:} Difference implementation which utilizes two hash functions\n\t&& Process:\n\t\t&&& Hash both relations into partitions\n\t\t&&& Re-hash a partition from the first relation, into new partitions\n\t\t&&& For each value in the second relation's matching partition:\n\t\t\t&&&& Re-hash it to find the corresponding partition\n\t\t\t&&&& Remove it from the partition if it exists\n\n\\end{easylist}\n\\subsection{Optimizing Aggregation}\n\t\\label{subsec:optimizing-aggregation}\n\\begin{easylist}\n\n& \\textbf{Aggregation:} Database operation where numerical values in rows are combined\n\n& If the index is clustered based on the attribute to be grouped, then no sorting will be required\n\n& \\textbf{Index-only aggregation:} Aggregation case where the search key contains all attributes to be searched and grouped, therefore no record access is required (only entries)\n\n\\end{easylist}\n\\subsection{Combined Operations}\n\t\\label{subsec:combined-operations}\n\\begin{easylist}\n\n& If grouping by a specific attribute:\n\t&& Ensure the relation is clustered/sorted on the attribute (if not, sort it externally)\n\t&& Use the relation with the attribute as the outer loop to preserve order \n\n\\end{easylist}\n\\clearpage\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "493f0bbc6b466785e606ba5210924aee3b9cae1e", "size": 10813, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "cmpt-454-database-systems-ii/tex/query-optimization.tex", "max_stars_repo_name": "AmirNaghibi/notes", "max_stars_repo_head_hexsha": "c4640bbcb65c94b8756ccc3e4c1bbc7d5c3f8e92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2019-08-11T08:45:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T02:37:39.000Z", "max_issues_repo_path": "cmpt-454-database-systems-ii/tex/query-optimization.tex", "max_issues_repo_name": "AmirNaghibi/notes", "max_issues_repo_head_hexsha": "c4640bbcb65c94b8756ccc3e4c1bbc7d5c3f8e92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmpt-454-database-systems-ii/tex/query-optimization.tex", "max_forks_repo_name": "AmirNaghibi/notes", "max_forks_repo_head_hexsha": "c4640bbcb65c94b8756ccc3e4c1bbc7d5c3f8e92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-11-18T09:17:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-27T21:44:56.000Z", "avg_line_length": 42.9087301587, "max_line_length": 219, "alphanum_fraction": 0.7217238509, "num_tokens": 3066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.344887990288092}}
{"text": "\n\\section{The Inverse Method}\n\n\\subsection{Requirements}\n\n\\begin{enumerate} \n\\item Typechecker\n  \\begin{itemize} \n  \\item Internal api, e.g. ``\\%doublecheck''\n  \\item External api, for Deepak say.  Perhaps support explicit sharing of terms.\n  \\end{itemize} \n\\item Term Reconstruction\n\\item Logic programming engine (Bottom up)\n\\item M2 Checker (\\%mode,\\%worlds,\\%terminates,\\%covers,\\%total)\n\\item logic programming engine (Top down)\n\\item Meta-theorem prover (produce .prf files from .thm files)\n\\end{enumerate} \n\n\\subsection{The Subformula Property}\n\n\\begin{Theorem} The cut rule is admissible in LF \\end{Theorem} \n\\XXX{Needs reference}\n\nIt is a property of cut-free sequent calculi that all propositions occurring\nin a derivation are \\emph{subformulas} of the endsequent in the following sense.\n\nWe define \\emph{signed subformulas} of a formula $F$ with judgments:\n\n\\begin{align*} \n\\PSubform{A} & & \\mbox{$A$ is a positive subformula of the initial goal.}\\\\\n\\NSubform{A} & & \\mbox{$A$ is a negative subformula of the initial goal.}\n\\end{align*} \n\nwhere \n$$\\Psi ::= \\cdot \\Spb \\Psi, v:A \\Spb \\Psi, x:A$$\n\nHere $v$ ranges over arbitrary terms and $x$ ranges over\nfixed parameters.\n\n\nThese rules are defined as a forward logic program by the following inference\nrules:\n\n\\bigskip \n\\begin{tabular}{cc}\n\\infer{\\NSubform{A}}{\\PSubform{(A\\LFArrow B)}} &\n\\infer{\\NSubform{B}}{\\PSubform{(A\\LFArrow B)}} \\\\\n\\infer{\\PSubform{A}}{\\NSubform{(A\\LFArrow B)}} &\n\\infer{\\PSubform{B}}{\\NSubform{(A\\LFArrow B)}} \\\\\n\\infer{\\PSubform[\\Psi,x:A]{B}}{\\PSubform{(\\PiTyp{x}{A}{B})}} &\n\\infer{\\NSubform[\\Psi,u:A]{B}}{\\NSubform{(\\PiTyp{u}{A}{B})}} \\\\\n\\end{tabular} \n\\bigskip \n\nNote that there are no rules for families of kind $\\Type$.\n\nTo find the subformulas of a given goal formula $G$, we run\nthe above rules as a forward logic program to saturation on $\\PSubform{G}$.  \n\n\\subsection{Admissible Substitutions}\n\nExplicit substitutions are an integral part of the theory and \nimplementation of our development.  They are necessary because\nwhen logic variables arise during proof search, it is not always\npossible to apply a substitution immediately.  While contexts \ndo the necessary bookkeeping of tracking the types of bound variables,\nsubstitutions track variable (term) instantiations.\nThe language of substitutions is\n\n$$\\sigma ::= \\circ \\Spb \\sigma,(M/u) \\Spb \\sigma, (y//x)$$ \n\nwhere $M$ ranges over arbitrary terms, and $y$ ranges over\nparameters.\n\nAn invariant(*) of admissible substitutions is that if $\\AdmSub{\\sigma}{\\Psi}$ then\nthe domain of $\\sigma$ is exactly the free variables of $\\Psi$.  (The codomain\nneed not mention all of $\\Sigma$.)  Similarly, whenever we apply \n$A[\\Theta]$ it will be the case that $\\Theta$ substitutes exactly for the\nfree variables of $A$.  \n\nThe judgment on admissible substitutions will be \n$$\\AdmSub{\\sigma}{\\Psi}$$\nread ``$\\sigma$ is an admissible substitution from $\\Psi$ to $\\Sigma$''.\nand meaning that $\\sigma$ substitutes for all the free variables in\n$\\Psi$, but can mention variables in $\\Sigma$.  \n\n\\bigskip \n\n\\infer{\\AdmSub{\\cdot}{\\cdot}}{} \n\\bigskip \n\n\\infer{\\AdmSub{(\\sigma,M/u)}{\\Psi,u:A}}{\\AdmSub{\\sigma}{\\Psi} & \\CheckTy[\\Sigma]{M}{A[\\sigma]}} \n\\smallskip \nwhen $u\\not\\in\\Psi$\n\\bigskip \n\n\\infer{\\AdmSub{(\\sigma,y//x)}{\\Psi,x:A}}{\\AdmSub{\\sigma}{\\Psi} & \\SynthTy[\\Sigma]{y}{A'} & A' = \\HerSub{A}} \n\\smallskip \nwhen $x\\not\\in\\Psi$\n\\bigskip \n\n\\subsection{Forward Sequents}\n\nFor the inverse method, we think of the usual sequent calculus rules, which work bottom-up, \nbackwards to work top-down.  \n\nThe judgment \n\n$$\\Sequent{\\Sigma}{A_1[\\tau_1],\\ldots,A_n[\\tau_n]}{C[\\sigma]}$$\n\nwhere for all $i$, \n\n\\begin{align*} \n  &\\AdmSub{\\tau_i}{\\Psi_i}\\\\\n  &\\NSubform[\\Psi_i]{A_i}\\\\\n  &\\AdmSub{\\sigma}{\\Psi}\\\\\n  &\\PSubform[\\Psi]{C}\n\\end{align*} \n\ncan be read as (modulo constraints on substitutions)\n``Given the parameters $\\Sigma$ and hypotheses and derived formulas \n$A_i$ under admissible substitutions $\\tau_i$, the goal $C$ under admissible\nsubstitution $\\sigma$ is derivable.''\n\n\\subsection{Subsumption}\n\n$$\n(\\Sequent{\\Sigma}{A_1[\\tau_1],\\ldots,A_n[\\tau_n]}{C[\\sigma]}) \\leq \n(\\Sequent{\\Sigma'}{A_1[\\tau_1'],\\ldots,A_k[\\tau_k']}{C[\\sigma']})\n$$\n\nif there exists an admissible substitution $\\AdmSub[\\Sigma']{\\Theta}{\\Sigma}$\nsuch that \n$\\tau_1' = \\tau_1 \\Comp \\Theta, \\ldots, \\tau_k' = \\tau_k \\Comp \\Theta, \\sigma' = \\sigma \\Comp \\Theta$\n\nfor some $n\\leq k$.  \n\n\\subsection{Unification}\n\n\\subsection{Most General Unifiers}\nIn the pattern fragment of LF, most general unifiers exist.  Therefore the\nfunction $\\mgu(x,y)$ is well defined.  Keeping our invariant (*) in mind, \nwe will write $\\mgu = (\\Theta_1,\\Theta_2)$ when the domain of the intended\nterms to which we apply the substitutions have different sets of free variables.\nThat is, if the most general unifier of $A_1,A_2$ is $\\Theta$ and \n$fv(A_1) \\neq fv(A_2)$ then \n\\begin{align*} \n  \\Theta_1 &= \\mathbf{filter}\\ (\\lambda(x,\\_).\\ \\mathbf{mem}(fv(A_1,x),x))\\ \\Theta \\\\ \n  \\Theta_2 &= \\mathbf{filter}\\ (\\lambda(x,\\_).\\ \\mathbf{mem}(fv(A_2,x),x))\\ \\Theta\n\\end{align*} \n\n\n\\subsection{Forward Sequent Rules, Pattern Fragment}\n\n\\infer[\\textbf{Init}]{\\Sequent{\\Sigma}{P_1[\\Theta_1]}{P_2[\\Theta_2]}}{}\nwhen\n\\begin{align*} \n  &\\NSubform[\\Psi_1]{P_1}\\\\\n  &\\PSubform[\\Psi_2]{P_2}\\\\\n  &\\MGU{(\\Theta_1,\\Theta_2)}{\\NSubform[\\Psi_1]{P_1}}{\\PSubform[\\Psi_2]{P_2}}\\\\\n  &\\AdmSub{\\Theta_1}{\\Psi_1}\\\\\n  &\\AdmSub{\\Theta_2}{\\Psi_2}\n\\end{align*} \n\n\\infer[\\textbf{Contract}]{\\Sequent{\\Sigma'}{\\Gamma[\\Theta],A[\\tau_1] \\Comp \\Theta}{C[\\sigma \\Comp \\Theta]}}\n                         {\\Sequent{\\Sigma}{\\Gamma,A[\\tau_1],A[\\tau_2]}{C[\\sigma]}}\nwhen\n\\begin{align*} \n  &\\AdmSub{\\tau_1}{\\Psi}\\\\\n  &\\AdmSub{\\tau_2}{\\Psi}\\\\  \n  &\\MGU[\\Sigma']{\\Theta}{\\tau_1}{\\tau_2}\n\\end{align*} \n\n\\infer[\\textbf{ArrowR1}]{\\Sequent{\\Sigma'}{\\Gamma[\\Theta]}{(A\\LFArrow B)[\\tau \\Comp \\Theta]}}\n                       {\\Sequent{\\Sigma}{\\Gamma,A[\\tau]}{B[\\sigma]}}\nwhen \n\\begin{align*} \n  &\\MGU[\\Sigma']{\\Theta}{\\tau}{\\sigma} \\\\\n  &\\AdmSub{\\Theta}{\\Psi} \\\\\n  &\\AdmSub{\\sigma}{\\Psi}\\\\\n  &\\PSubform{A \\LFArrow B}\n\\end{align*} \n\n\\infer[\\textbf{ArrowR2}]{\\Sequent{\\Sigma}{\\Gamma}{(A\\LFArrow B)[\\sigma]}}\n                        {\\Sequent{\\Sigma}{\\Gamma}{B[\\sigma]}}\nwhen \n\\begin{align*} \n  &\\AdmSub{\\sigma}{\\Psi}\\\\\n  &\\PSubform{A \\LFArrow B}\n\\end{align*} \n\n\\infer[\\textbf{ArrowL}]{\\Sequent{\\Sigma}{\\Gamma_1[\\Theta_1],\\Gamma_2[\\Theta_2],(A\\LFArrow B)[\\tau_1 \\Comp \\Theta_1]}{C[\\sigma \\Comp \\tau_2]}}\n                       {\\Sequent{\\Sigma_1}{\\Gamma_1}{A[\\tau_1]} & \\Sequent{\\Sigma_2}{\\Gamma_2,B[\\tau_2]}{C[\\sigma]}}\nwhen\n\\begin{align*} \n  &\\MGU{(\\Theta_1,\\Theta_2)}{\\AdmSub{\\Theta_1}{\\Sigma_1}}{\\AdmSub{\\Theta_2}{\\Sigma_2}}\\\\\n  &\\AdmSub{\\tau_1}{\\Psi}\\\\\n  &\\AdmSub{\\tau_2}{\\Psi}\\\\\n  &\\NSubform{A \\LFArrow B}\n\\end{align*} \n\n\\infer[\\textbf{PiL}]{\\Sequent{\\Sigma}{\\Gamma, (\\PiTyp{u}{A}{B})[\\tau]}{C[\\sigma]}}\n                    {\\Sequent{\\Sigma}{\\Gamma, B[\\tau,M/u]}{C[\\sigma]}}\nwhen \n\\begin{align*} \n  \\NSubform{\\PiTyp{u}{A}{B}}\n\\end{align*} \n\n\\infer[\\textbf{PiR}]{\\Sequent{\\Sigma}{\\Gamma}{(\\PiTyp{x}{A}{B})[\\sigma]}}\n                    {\\Sequent{\\Sigma,y:A'}{\\Gamma}{B[\\sigma,y//x]}}\n\nwhen \n\\begin{align*} \n  &y\\not\\in \\Gamma \\\\\n  &A' = A[\\sigma] \\\\\n  &\\PSubform{\\PiTyp{x}{A}{B}}\n\\end{align*} \n\n%% \\subsection{Junk}\n\n\n%% \\newcommand{\\init}{(\\Gamma_0^-,C_0^+)}\n\n%% \\infer[$Atom$]{P \\vdash P}{}\n%% \\bigskip \n%% when $P \\leq^+ \\init$ and $P \\leq^- \\init$\n%% \\bigskip \n\n%% \\infer[$Contract$]{\\Gamma,A \\vdash B}{\\Gamma,A,A\\vdash B}\n%% \\bigskip \n\n%% \\infer[\\to$R1$]{\\Gamma\\vdash A \\LFArrow B}{\\Gamma,A \\vdash B & (A\\LFArrow B \\leq^+ \\init)}\n%% \\bigskip \n\n%% \\infer[\\LFArrow$R2$]{\\Gamma\\vdash A \\LFArrow B}{\\Gamma \\vdash B & A \\not\\in\\Gamma & (A\\LFArrow B \\leq^+ \\init)}\n%% \\bigskip \n\n%% \\infer[\\LFArrow$L$]{\\Gamma_1,\\Gamma_2,A \\LFArrow B\\vdash C}{\\Gamma_1,\\vdash A,& \\Gamma_2,A \\vdash B & (A\\LFArrow B \\leq^- \\init)}\n%% \\bigskip \n\n%% \\subsection{The First Order Case}\n\n%% \\newcommand{\\seq}[3][\\Sigma]{#1 ; #2 \\vdash #3}\n%% \\newcommand{\\unif}[3][\\Sigma]{#1 ; #2 = #3}\n%% \\newcommand{\\renaming}[1]{#1\\ \\mathsf{renaming}}\n\n%% General Form:\n\n%% $$\\Sigma; \\Gamma[\\tau] \\vdash C[\\sigma]$$\n\n%% which is shorthand for\n\n%% $$\\Sigma; A_1[\\tau_1],\\ldots,A_n[\\tau_n] \\vdash C[\\sigma]$$\n\n%% \\bigskip \n\n%% \\infer[$Atom$]{\\seq{P_1^-[\\rho\\circ\\tau]}{P_2^+[\\tau]}} {}\n%% \\bigskip \n%% when $\\unif{P_1^-[\\rho\\circ\\tau]}{P_2^+[\\tau]}$ and $\\renaming{\\rho}$\n%% \\bigskip \n\n%% \\infer[\\Pi$-R$]{\\seq{\\Gamma}{}}{}\n%% \\bigskip \n\n", "meta": {"hexsha": "0d9c32d9a048329353b08e955edd9904c6a7471e", "size": 8425, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/inverse/tex/inverse.tex", "max_stars_repo_name": "kryptine/twelf", "max_stars_repo_head_hexsha": "1edad1846921cc962138cd4a5a703d3b1e880af2", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 61, "max_stars_repo_stars_event_min_datetime": "2015-01-24T18:10:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T12:41:05.000Z", "max_issues_repo_path": "src/inverse/tex/inverse.tex", "max_issues_repo_name": "kryptine/twelf", "max_issues_repo_head_hexsha": "1edad1846921cc962138cd4a5a703d3b1e880af2", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-02-27T22:17:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-27T22:17:51.000Z", "max_forks_repo_path": "src/inverse/tex/inverse.tex", "max_forks_repo_name": "kryptine/twelf", "max_forks_repo_head_hexsha": "1edad1846921cc962138cd4a5a703d3b1e880af2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2016-05-06T01:32:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T19:33:29.000Z", "avg_line_length": 31.7924528302, "max_line_length": 141, "alphanum_fraction": 0.6490207715, "num_tokens": 3037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3448879766744842}}
{"text": "\\documentclass[journal=jpcbfk,manuscript=article,layout=singlecolumn,articletitle=true]{achemso}\n\\setkeys{acs}{articletitle = true}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Place any additional packages needed here.  Only include packages\n%% which are essential, to avoid problems later.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\usepackage{graphicx,bm,lineno,mathpazo}  \n\\usepackage{amssymb,amsfonts,amsmath,mathtools}\n\\usepackage{algorithm,algpseudocode,booktabs,dcolumn}\n\\captionsetup{labelfont=bf}\n\\usepackage[input-decimal-markers={.},separate-uncertainty=true,table-auto-round,scientific-notation = false,zero-decimal-to-integer=true]{siunitx}\n\\DeclareMathOperator*{\\tr}{tr}\n\\DeclareMathOperator*{\\argmax}{arg\\,max}\n\\usepackage[caption=false,font=normalsize,position=top]{subfig}\n\\usepackage[kerning,spacing,tracking]{microtype}\n\\microtypecontext{spacing=nonfrench}\n\\usepackage{indentfirst}\n\\overfullrule=5pt\n\\usepackage[normalem]{ulem} \n\\usepackage{color}\n\\usepackage{empheq}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% New command\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\newcommand{\\boxedeq}[2]{\\begin{empheq}[box={\\fboxsep=6pt\\fbox}]{align}\\label{#1}#2\\end{empheq}}\n\n\\title{EM: From Langevin-Dynamics}\n\\author{Yi-Tsao Chen}\n\\date{December 2019}\n\n\\begin{document}\n \n\\maketitle\n\n\\section{Langevin-Dynamics}\nGiven a potential mean force $V(x)$ and a diffusion coefficient $D$, we simulate a trajectory, $X(t)$, from\n\\begin{equation}\n\\label{eq:ODLD}\ndx_t=D F(x_t)dt  + \\sqrt{2D}d{W}_t,\n\\end{equation}\n\n\\section{Formulate the problem as Hidden Markov Model}\nWe denote a particular configuration as $(\\textbf{x}, \\textbf{y})$:\n\\begin{equation}\n(\\textbf{x}, \\textbf{y})=(x_0, x_1, \\cdots, x_T, y_0, y_1, \\cdots, y_T)\n\\end{equation}\nThe joint probability is:\n\\begin{equation}\np(\\textbf{x}, \\textbf{y})= p(x_0)\\prod_{t=0}^{T-1} p(x_{t+1}|x_t) \\prod_{t=0}^{T}p(y_t|x_t)\n\\end{equation}\n\n\\begin{figure}[h]\n\\includegraphics{figures/graphical.pdf}\n\\caption[Graphical Model]{Graphical Model}\n\\label{domaindecomp}\n\\end{figure}\n\n\\section{Inference}\n\\subsection{state representation}\nWe represent the state at time $t$ as a multinomial random varialbe $x_{t}$, with components $x_t^i$ for $i=0,...,M$. Thus $x_t^i$ is equal to one for a particular value of $i$ and is equal to zero for $j \\neq i$.\n\\begin{equation}\nx_t = \n\\begin{bmatrix}\nx_t^0 & x_t^1 & x_t^2 &\\cdots & x_t^M\n\\end{bmatrix}^T\n\\end{equation}\nFor example, if the state is in the second state, \n\\begin{equation}\nx_t = \n\\begin{bmatrix}\n0 & 0 & 1 & \\cdots & 0\n\\end{bmatrix}^T\n\\end{equation}\n\\subsection{alpha-beta}\nWe focus on a particular state node $x_t$ and ask to calculate its posterior probability, $p(x_t| \\textbf{y})$. And by Bayes' theorem,\n\\begin{equation}\np(x_t | \\textbf{y}) = \\frac{p(\\textbf{y}|x_t) p(x_t)}{p(\\textbf{y})}\n\\end{equation}\nThen, conditioning on $x_t$ and use conditional independence:\n\\begin{equation}\np(x_t | \\textbf{y}) = \\frac{p(y_0,\\cdots,y_t|x_t) p(y_{t+1},\\cdots,y_T|x_t) p(x_t)}{p(\\textbf{y})}\n\\end{equation}\nRegroup the terms\n\\begin{equation}\n\\begin{split}\np(x_t | \\textbf{y}) &= \\frac{p(y_0,\\cdots,y_t,x_t) p(y_{t+1},\\cdots,y_T|x_t)}{p(\\textbf{y})}\\\\\n&=\\frac{\\alpha(x_t)\\beta(x_t)}{p(\\textbf{y})}\n\\end{split}\n\\end{equation}\nwhere \n\\begin{equation}\n\\alpha(x_t) \\triangleq p(y_0,\\cdots,y_t,x_t)\n\\end{equation}\nis the probability of emitting a partial sequence of outputs $y_0,\\cdots,y_t$ and ending up in state $x_t$, and\n\\begin{figure}[h]\n\\includegraphics{figures/alpha_example.pdf}\n\\caption[Alpha]{The illustration of $\\alpha(x_2)=p(y_0,y_1,y_2,x_2)$}\n\\label{alpha}\n\\end{figure}\n\\begin{equation}\n\\beta(x_t) \\triangleq p(y_{t+1},\\cdots,y_T|x_t)\n\\end{equation}\nis the probability of emitting a partial sequence of outputs $y_{t+1},\\cdots,y_T$ given that the system starts in state $x_t$. \n\\begin{figure}[h]\n\\includegraphics{figures/beta_example.pdf}\n\\caption[Beta]{The illustration of $\\beta(x_2)=p(y_3,y_4|x_2)$}\n\\label{beta}\n\\end{figure}\n\n\\begin{figure}[b]\n\\includegraphics{figures/graphical_example.pdf}\n\\caption[Graphical Model]{The example of forward-backward}\n\\label{domaindecomp}\n\\end{figure}\n\n\\subsection{Likelihood function}\nThe sum of $p(x_t|\\textbf{y})$ over the possible values of $x_t$ must equal one.\n\\begin{equation}\n1 = \\sum_{x_t} p(x_t|\\textbf{y}) = \\frac{\\sum_{x_t} \\alpha(x_t)\\beta(x_t)}{p(\\textbf{y})}\n\\end{equation}\nSo, the likelihood function $p(\\textbf{y})$ can be written as\n\\begin{equation}\np(\\textbf{y})=\\sum_{x_t} \\alpha(x_t)\\beta(x_t)\n\\end{equation}\n\n\\subsection{Posterior probability $p(x_t | \\textbf{y})$}\nWe denote the posterior probablity $p(x_t | \\textbf{y})$ as $\\gamma(x_t)$\n\\begin{equation}\n\\gamma(x_t) \\triangleq \\frac{\\alpha(x_t)\\beta(x_t)}{p(\\textbf{y})}\n\\end{equation}\n\n\\subsection{Forward algorithm}\n\\begin{equation}\n\\alpha(x_{t+1}) = \\sum_{x_t} \\alpha(x_t) a_{x_t,x_{t+1}} p(y_{t+1}|x_{t+1})\n\\end{equation}\nwhere $a_{x_t,x_{t+1}}$ is the transition probability from $x_t$ to $x_{t+1}$. The definition of alpha at the first time step yields:\n\\begin{equation}\n\\alpha(x_0) = p(y_0, x_0) = p(y_0|x_0)p(x_0) = p(y_0|x_0) \\pi_{x_0} \n\\end{equation}\nand these values are used to initialize the recursion.\n\n\\subsection{Backward algorithm}\n\\begin{equation}\n\\beta(x_t) = \\sum_{x_{t+1}} \\beta(x_{t+1}) a_{x_t,x_{t+1}} p(y_{t+1}|x_{t+1})\n\\end{equation}\nThe beta recursion is a backwards recursion; that is, we start at the final time step $T$ and proceed backwards to the initial time step.\n\nSome remarks:\n\\begin{enumerate}\n\\item $\\beta(x_T)$ is unhelpful because it makes reference to a non-existent $y_{T+1}$\n\\item If we assign $\\beta(x_T)$ to be a vector of ones, i.e., $\\beta(x_T)=\\textbf{1}$, we can compute $\\beta(x_{T-1})$ correctly\n\\begin{equation}\n\\begin{split}\n\\beta(x_{T-1}) &= p(y_T|x_{T-1}) \\\\\n&= \\sum_{x_T} \\beta(x_T) a_{x_{T-1}, x_T} p(y_T|x_T) \\\\\n&= \\sum_{x_T} a_{x_{T-1}, x_T} p(y_T|x_T) \n\\end{split}\n\\end{equation}\n\\end{enumerate}\n\n\\subsection{Computing $p(\\textbf{y})$ by a single forward pass for the alphas}\n\\begin{equation}\n\\begin{split}\np(\\textbf{y}) &= \\sum_{i} \\alpha(x_T^i) \\beta(x_T^i) \\\\\n&= \\sum_{i} \\alpha(x_T^i) \\\\\n&= \\sum_{i} p(y_0,y_1,\\cdots,y_T,x_T^i)\n\\end{split}\n\\end{equation}\n\\end{enumerate}\n\n\n\\section{Expectation maximization}\nPreparing an initial potential mean force $V_0(x)$ and a diffusion coefficient $D_0$, and try to using the framework in the 2013 JPCB paper to learn $V(x)$ and $D$ back.\n\n\\section{Question}\n\\begin{enumerate}\n\\item If we ignore the information of photons, what is the observed data, $Y(t)$?\n\\item What is the likelihood functional?\n\\begin{equation}\n\\label{eq:PathP}\n\\begin{split}\n\\mathcal{P}(Y(t) ; F(x),D) &= \\mathcal{P}(Y(t) ; \\theta)= \\mathcal{L}[\\theta]\\\\\n&=\\langle \\alpha_{t_0} |e^{-\\bm{H}\\Delta t_1}\\bm{y}_1e^{-\\bm{H}\\Delta t_2}\\bm{y}_2 \\ldots e^{-\\bm{H}\\Delta t_{N_{\\mathrm{P}}}}\\bm{y}_{N_{\\mathrm{P}}} | \\beta_{t_{\\mathrm{exp}}} \\rangle\n\\end{split}\n\\end{equation}\n\\end{enumerate}\n\n\\section{Appendix A: Bayes' theorem}\n\\begin{equation}\np(A|B) = \\frac{p(B|A)p(A)}{p(B)}\n\\end{equation}\n\n\\end{document}\n", "meta": {"hexsha": "83426360984ae6dcb39705c9991fc24906b4332d", "size": 7077, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "old/em_0.tex", "max_stars_repo_name": "yizaochen/em_theory", "max_stars_repo_head_hexsha": "a9260f17ff59d7a265dd9e629607376b8d909ae6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "old/em_0.tex", "max_issues_repo_name": "yizaochen/em_theory", "max_issues_repo_head_hexsha": "a9260f17ff59d7a265dd9e629607376b8d909ae6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "old/em_0.tex", "max_forks_repo_name": "yizaochen/em_theory", "max_forks_repo_head_hexsha": "a9260f17ff59d7a265dd9e629607376b8d909ae6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2923076923, "max_line_length": 213, "alphanum_fraction": 0.6850360322, "num_tokens": 2512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.3447485798802805}}
{"text": "% arara: pdflatex\n% arara: bibtex\n% arara: pdflatex\n% arara: pdflatex\n\n\\documentclass[a4paper,11pt]{article}\n\\pdfoutput=1 % if your are submitting a pdflatex (i.e. if you have\n             % images in pdf, png or jpg format)\n\n\\usepackage[a4paper,\ntotal={170mm,257mm},\nleft=20mm,\ntop=20mm,]{geometry}\n\n\\usepackage[dvipsnames]{xcolor}\n\\usepackage{longtable}\n\\usepackage{authblk}\n\\usepackage{hyperref}\n\n\\usepackage{titlesec}\n\\titleformat{\\section}[block]{\\color{blue}\\Large\\bfseries\\filcenter}{}{1em}{}\n\\titleformat{\\subsection}[hang]{\\bfseries}{}{1em}{}\n\n\n\\title{\\textcolor{red}{\\texttt{\\Huge TpMp}} - topology mapping}\n\n\n\\author{Andrey Pikelner}\n\\affil{II.~Institut f\\\"ur Theoretische Physik, Universit\\\"at Hamburg,\\\\\nLuruper Chaussee 149, 22761 Hamburg, Germany}\n\n\n% \\emailAdd{andrey.pikelner@desy.de}\n\n\n% Mathematica commands in blue\n\\newcommand{\\mma}[1]{\\textcolor{BlueGreen}{\\texttt{#1}}}\n% Color tt\n\\newcommand{\\ctt}[1]{\\textcolor{OliveGreen}{\\texttt{#1}}}\n\n\\setcounter{secnumdepth}{0}\n\\begin{document} \n\\maketitle\n\n\\abstract{We present program for diagram generation and mapping on\n  topology working with \\texttt{Mathematica} interface. Available from\n  \\url{https://github.com/apik/TpMp}}\n\n\n\\section*{Design ideas}\n\n\\subsection*{QGRAF input conventions}\n\\begin{itemize}\n\\item We use all particles as internal in QGRAF and having momentum\n  $p_1,\\dots,p_n$. Field out kept blank.\n\\begin{verbatim}\n   in  = q, Q ;\n   out = ;\n\\end{verbatim}\n\n\\item All fields in model file must contain field \\ctt{type} with\n  possible values \\ctt{F,M,S,C,A} in addition to\n  comutativity flag $\\pm$.\n\\begin{verbatim}\n   [ phi, phi, + ; type='S']\n\\end{verbatim}\n\n\\item We set internal momentum to be \\ctt{k}\n\\end{itemize}\n\n\n\\subsection*{DB storage}\n\\label{sec:dbstore}\n\n\n\\section*{Main commands available in package }\n\n\\subsection*{Loading diagrams}\n\\begingroup\n\\renewcommand\\arraystretch{2}\n\\begin{longtable}{p{4cm}|p{11cm}}\n  \\mma{LoadQGRAF[\"qlist\"]}\n  & Load \\texttt{QGRAF}\\cite{Nogueira:1991ex} output \\texttt{qlist.yaml} in YAML format produced with the help of\n    yaml.sty style file and produce SQLite 3 DB with generated\n    diagrams and name \\texttt{qlist.sqlite3}.\\\\\n  \\mma{nDB=LoadDB[\"db\"]}\n  & Load SQLite 3 DB from file \\texttt{db.sqlite3} with diagrams and\n    return numeric descriptor \\texttt{nDB} of open DB.\\\\\n  \\mma{GetDia[nDia,nDB]}\n  & Retrive diagram with number \\texttt{nDia} from DB with descriptor\n    \\texttt{nDB}.\\\\\n\\end{longtable}\n\\endgroup\n\nWhen DB loaded all commands need DB decriptor to be specified. If DB\ndescriptor not specified explicitly - all commands applyed to first\nopen DB.\n\n\\subsection*{Selecting diagrams}\n\n\\begingroup\n\\renewcommand\\arraystretch{2}\n\\begin{longtable}{p{4cm}|p{11cm}}\n  \\mma{WithField[\"f\"]}\n  & Select diagrams with field named \"f\".\\\\\n  \\mma{WithFieldType[T]}\n  & Select diagrams with field type \\texttt{T}, where \\texttt{T} is\n  one of: \\texttt{F} - for Dirac fermion, \\texttt{M} - for Majorana\n  fermion, \\texttt{S} - for scalar, \\texttt{C} - for ghost and\n  \\texttt{A} - for auxiliary field type.\\\\\n\\end{longtable}\n\\endgroup\n\n\\subsection*{Plotting diagrams}\n\n\n\\section{Mapping}\n\\subsection{\\boldmath $U$ and $F$ polynomials}\n\nIf we define $P_i=-q_j^2+m_j^2$, than:\n\\begin{equation}\n  \\label{eq:MQJdefMass}\n  \\sum\\limits_{j=1}^{n}x_j(-q_j^2+m_j^2)=-\\sum\\limits_{r=1}^{l}\\sum\\limits_{s=1}^{l}k_rM_{rs}k_s+\\sum\\limits_{r=1}^{l}2k_r\\cdot\n  Q_r+J\n\\end{equation}\nTerm $J$ contain all dependence on external momentum products and\nmasses and can be decomposed:\n\n\\begin{equation}\n  \\label{eq:Jdecompose}\n  J=J^{p}+J^{m} = J^{p}(p_i^2,p_i\\cdot p_j)+\\sum\\limits_{j=1}^{n}x_jm_j^2\n\\end{equation}\n\nIf only information about momentum distribution needed we can neglect\nmasses and use $P$ polynomial instead of $F$\n\n\\begin{equation}\n  \\label{eq:MQJdefNoMass}\n  -\\sum\\limits_{j=1}^{n}x_jq_j^2=-\\sum\\limits_{r=1}^{l}\\sum\\limits_{s=1}^{l}k_rM_{rs}k_s+\\sum\\limits_{r=1}^{l}2k_r\\cdot\n  Q_r+J^{p}\n\\end{equation}\n\nAnd Feynman graph polymnomials defined as\n\\begin{equation}\n  \\label{eq:UFMdef}\n  U=\\det(M),\\quad P=\\det(M)(J^p+QM^{-1}Q),\\quad F=\\det(M)(J+QM^{-1}Q).\n\\end{equation}\n\n$U$ polynomial determine internal structure of diagram, $P$ polynomial\ndetermines external momenta distribution and kinematic of the diagram\nand $F$-polynomial determines how masses are distributed between lines.\n\n\n\\begin{verbatim}\n<|-x[1] -> \n        <|{} -> <|{1} -> {{{}, T12[{1, k1, m1}]}}|>|>, \n\n-x[1] - x[2] -> \n        <|{{1, 1}} -> \n             <|{1,  1} -> {{{{1, 1} -> -p1^2}, T12[{1, k1,      m1}, {2, k1 + p1, m2}]}}, \n               {0,  1} -> {{{{1, 1} -> -p1^2}, T02[{2, k1 + p1, m2}, {1, k1, 0}]}}, \n               {1,  0} -> {{{{1, 1} -> -p1^2}, T10[{1, k1,      m1}, {2, k1 + p1, 0}]}}, \n               {0,  0} -> {{{{1, 1} -> -p1^2}, T00[{1, k1,       0}, {2, k1 + p1, 0}]}}|>|>|>\n\\end{verbatim}\n\n\\subsection{External momentum flow}\n\\label{sec:extflow}\n\nIt is possible to map diagram with $p_1,\\dots,p_n$ external momentum on topology\nwith $p_1,\\dots,p_k,k<n$ external momenta. This mean that momenta flow\nfor $p_{k+1},\\dots,p_n$ kept according to flow in original\ndiagram. Momentum to be kept should be marked as optional parameter of\n\\ctt{MapOnAux} function as \\ctt{SplitMomenta->\\{p2,p3,...\\}}.\n\n\\subsection{Internal structure}\n\nFor set of diagrams it is possible to define ``projections'' i.e.\ndiagrams with contraints on kinematical variables: masses and external\nmomentums.\n\nProjections created with the help of command \\texttt{Project[\"pr\",subs]} where\nparameters \\texttt{\"pr\"} - unique name of projection and \\texttt{subs}\n- substitution rules.\n\n% \\appendix\n% \\section{Additions}\n% \\acknowledgments\n\n\\bibliographystyle{plain}\n\\bibliography{TpMp} \n\n\\end{document}\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: t\n%%% End:\n", "meta": {"hexsha": "818f987dcfbcbb8583bd76e320810cd2bd155c08", "size": 5764, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/TpMp.tex", "max_stars_repo_name": "apik/TpMp", "max_stars_repo_head_hexsha": "840416d0eededfc3b0cfbe21f3c2af3a438be080", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/TpMp.tex", "max_issues_repo_name": "apik/TpMp", "max_issues_repo_head_hexsha": "840416d0eededfc3b0cfbe21f3c2af3a438be080", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/TpMp.tex", "max_forks_repo_name": "apik/TpMp", "max_forks_repo_head_hexsha": "840416d0eededfc3b0cfbe21f3c2af3a438be080", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1111111111, "max_line_length": 127, "alphanum_fraction": 0.6835530881, "num_tokens": 2012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3447238421626679}}
{"text": "\\documentclass[11pt]{scrartcl} % Font size\n\\input{structure.tex} % Include the file specifying the document structure and custom commands\n\n%----------------------------------------------------------------------------------------\n%\tTITLE SECTION\n%----------------------------------------------------------------------------------------\n\n\\title{\n\t\\normalfont\\normalsize\n\t\\textsc{Harvard Privacy Tools Project}\\\\ % Your university, school and/or department name(s)\n\t\\vspace{25pt} % Whitespace\n\t\\rule{\\linewidth}{0.5pt}\\\\ % Thin top horizontal rule\n\t\\vspace{20pt} % Whitespace\n\t{\\huge Generalized Resize Notes}\\\\ % The assignment title\n\t\\vspace{12pt} % Whitespace\n\t\\rule{\\linewidth}{2pt}\\\\ % Thick bottom horizontal rule\n\t\\vspace{12pt} % Whitespace\n}\n\n\\author{} % Your name\n\n\\date{} % Today's date (\\today) or a custom date\n\n\\begin{document}\n\n\\maketitle\n\n\\textbf{This is a work in progress.}\n\n\\section{Goals}\nThe generalized resize component is a means of jointly achieving a few different goals:\n\\begin{enumerate}\n    \\item guarantee known $n$,\n    \\item give users flexibility in how they trade off between bias and privacy usage, and\n    \\item allow for a combination of c-stability and privacy amplification from subsampling.\n\\end{enumerate}\n\n\\section{Algorithm Statement}\n\\label{sec:algorithm_statement}\nThe function will take the following inputs:\n\\begin{enumerate}\n    \\item $X$: The private underlying data.\n    \\item $\\tilde{n}$: The size of the private underlying data.\n    \\item $n$: The desired size of the new data.\n    \\item $p$: The proportion of the underlying data that can be used to construct the new data. Can be $> 1$.\n    \\item $...$: Various arguments explaining imputation rules (not of interest for this doc)\n\\end{enumerate}\n\nLet $sample(Y, m)$ be a function that samples $m$ elements from data set $Y$ without replacement. \nLet $Aug(Y, m, \\hdots)$ be a function that imputes new elements independent of the data (using imputation parameters given by $\\hdots$) for a data set $Y$ until it is of size $m$. \nThe algorithm will look something like the following:\n\\begin{algorithm}[H]\n    \\caption{Generalized Resize: resize(X, n, p, neighboring, ...)}\n    \\label{alg:gen_resize}\n    \\begin{algorithmic}[1]\n        \\State $c \\gets \\lceil p \\rceil$ \\Comment{sets c-stability property}\n        \\State $s \\gets p/c$ \\Comment{sets subsampled\\_proportion property}\n        \\State $X_c \\gets \\bigcup_{i=1}^{c}X$ \\Comment{create new database of size $c\\tilde{n}$, composed of $c$ copies of $X$}\n        \\If{neighboring == ``replace one''}\n            \\State $m \\gets \\lfloor sc\\tilde{n} \\rfloor$ \\Comment{number of records that can be filled using subsampled private data}\n        \\ElsIf{neighboring == ``add/remove one''}\n            \\State $m \\gets Binomial(c\\tilde{n}, s)$ \\Comment{number of records that can be filled using subsampled private data}\n        \\EndIf\n        \\State $(\\epsilon', \\delta') \\gets \\left(\\log\\left(1+s\\left(e^{c\\epsilon}-1\\right) \\right), s\\left(\\sum_{i=1}^{c-1}e^{i \\epsilon}\\right)\\delta \\right)$ \\Comment{privacy amplification via subsampling}\n        \\State $X' \\gets sample\\left( X_c, \\max(m, n), neighboring \\right) \\bigcup \\left( Aug(\\varnothing, \\max(0, n - m), \\hdots) \\right)$\n        \\\\ \\Return $(X', \\epsilon', \\delta')$\n    \\end{algorithmic}\n\\end{algorithm}\n\nThe $\\epsilon', \\delta'$ terms come from first applying the group privacy definition with group size $c$ to the \ndatabase $X_c$ to get $\\left(c\\epsilon, \\left(\\sum_{i=1}^{c-1}e^{i \\epsilon}\\right)\\delta \\right)$ \\cite{Vad17}\nand then applying privacy amplification by subsampling results from Theorems 8 and 9 of \\cite{BBG18}. \nNote that, for the ``replace one'' definition, we could be using $\\frac{m}{c\\tilde{n}}$ instead of $s$ in the privacy calculation. Using $s$ gives us a very slightly \nworse privacy guarantee (the only difference is the $\\lfloor \\cdot \\rfloor$ we used to get $m$), but is nice for \nconsistency between the methods and not having to keep track of $m$ as an extra property.\n\n\\section{Functional Privacy Parameters}\nWe established in section~\\ref{sec:algorithm_statement} that a user asking for an $(\\epsilon, \\delta)$-DP guarantee will get an \n$(\\epsilon', \\delta')$-DP guarantee with respect to the original private data. What we'd really like, however, is for the user to ask for an $(\\epsilon, \\delta)$-DP \ngurantee and have the library come up with what we will call a \\emph{functional $(\\epsilon'', \\delta'')$} that will ensure $(\\epsilon, \\delta)$-DP \non the original data. Any components that operate on the resized data will use the \\emph{functional $(\\epsilon'', \\delta'')$} internally instead of \nthe parameters passed by the user.\n\n\\begin{theorem}\n    A mechanism that respects \n    \\[ \\left( \\frac{1}{c}\\log\\left(\\frac{e^{\\epsilon'}-1}{s} + 1 \\right), \\frac{\\delta'}{s\\left(\\sum_{i=1}^{c-1}e^{i \\epsilon}\\right)} \\right)\\text{-DP} \\] \n    on the resized data respects $(\\epsilon, \\delta)$-DP on the true private data.\n    \\begin{proof}\n        We know that an $(\\epsilon, \\delta)$-DP on the resized data corresponds to a \n        \\[ (\\epsilon', \\delta') = \\left(\\log\\left(1+s\\left(e^{c\\epsilon}-1\\right) \\right), s\\left(\\sum_{i=1}^{c-1}e^{i \\epsilon}\\right)\\delta \\right) \\]\n        guarantee on the private data. We just need to invert the function to find $(\\epsilon, \\delta)$ in terms of $(\\epsilon', \\delta')$. \\newline \n\n        Let's start with $\\epsilon, \\epsilon'$:\n        \\begin{align*}\n            \\epsilon' &= \\log\\left(1+s\\left(e^{c\\epsilon}-1\\right)\\right) \\\\\n            e^{\\epsilon'} &= 1+s\\left(e^{c\\epsilon}-1\\right) \\\\\n            \\frac{e^{\\epsilon'}-1}{s} &= e^{c\\epsilon}-1 \\\\\n            \\frac{1}{c}\\log\\left(\\frac{e^{\\epsilon'}-1}{s} + 1 \\right) &= \\epsilon.\n        \\end{align*}\n\n        We carry out a similar calculation for $\\delta, \\delta'$:\n        \\begin{align*}\n            \\delta' &= s\\left(\\sum_{i=1}^{c-1}e^{i \\epsilon}\\right)\\delta \\\\\n            \\frac{\\delta'}{s\\left(\\sum_{i=1}^{c-1}e^{i \\epsilon}\\right)} &= \\delta.\n        \\end{align*}\n    \\end{proof} \n    So, in order for a mechanism to respect $(\\epsilon, \\delta)$-DP on the original data, it must respect \n    $\\left( \\frac{1}{c}\\log\\left(\\frac{e^{\\epsilon}-1}{s} + 1 \\right), \\frac{\\delta}{s\\left(\\sum_{i=1}^{c-1}e^{i \\epsilon}\\right)} \\right)$-DP \n    on the resized data.\n\\end{theorem}\n\nWe now present an mini-algorithm for finding the \\emph{functional} $(\\epsilon, \\delta)$.\n\\begin{algorithm}\n    \\caption{Finding Functional $(\\epsilon_f, \\delta_f)$: get\\_func\\_priv($p, \\epsilon, \\delta$)}\n    \\label{alg:finding_functional_privacy}\n    \\begin{algorithmic}[1]\n        \\State $c \\gets \\lceil p \\rceil$ \\Comment{sets c-stability property}\n        \\State $s \\gets p/c$ \\Comment{sets subsampled\\_proportion property}\n        \\State $\\epsilon_{f} \\gets \\frac{1}{c}\\log\\left(\\frac{e^{\\epsilon}-1}{s} + 1\\right)$\n        \\State $\\delta_{f} \\gets \\frac{\\delta}{s\\left(\\sum_{i=1}^{c-1}e^{i \\epsilon}\\right)}$\n        \\\\ \\Return $(\\epsilon_{f}, \\delta_{f})$ \n    \\end{algorithmic}\n\\end{algorithm}\n\n\\section{Examples} \\label{sec:examples}\nLet $X$ be such that $\\tilde{n} = \\vert X \\vert = 100$. We can look at a few examples of calls to the generalized resize function (which will return $X'$) and check the behavior.\n\\begin{enumerate}\n    \\item resize(X, 150, 1, ...): $X'$ will be made up of the 100 true elements of $X$ and 50 imputed values. The functional privacy parameters are identical to the ones the user provides. \n    \\item resize(X, 100, 0.75, ...): $X'$ will be made up of 75 true elements of $X$ and 25 imputed values. The functional privacy parameters will benefit (lower noise) from amplification via subsampling.\n    \\item resize(X, 90, 1.5, ...): $X'$ will be a random sample of $X \\bigcup X$ of size 90. \n            The functional privacy parameters will lead to greater noise than what the user provides, as they have to take into account the new c-stability of $2$. \n            This example is illustrative in that is shows that the functional privacy usage is affected only by $p$ -- it has nothing to do with the relative sizes of the $X$ and $X'$.\n\\end{enumerate}\n\n\\bibliographystyle{alpha}\n\\bibliography{generalized_resize}\n\n\\end{document}\n", "meta": {"hexsha": "8f56c84eee3c8ac3f2e5eb9cfce73234d732cf2d", "size": 8203, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "whitepapers/data_processing/generalized_resize.tex", "max_stars_repo_name": "confiare/SN-Core", "max_stars_repo_head_hexsha": "40604b288b407b154541740290db9eeac990b4ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 53, "max_stars_repo_stars_event_min_datetime": "2021-02-18T07:02:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:10:13.000Z", "max_issues_repo_path": "whitepapers/data_processing/generalized_resize.tex", "max_issues_repo_name": "confiare/SN-Core", "max_issues_repo_head_hexsha": "40604b288b407b154541740290db9eeac990b4ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34, "max_issues_repo_issues_event_min_datetime": "2020-10-22T13:56:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-11T13:44:20.000Z", "max_forks_repo_path": "whitepapers/data_processing/generalized_resize.tex", "max_forks_repo_name": "confiare/SN-Core", "max_forks_repo_head_hexsha": "40604b288b407b154541740290db9eeac990b4ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-10-22T13:29:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-08T15:57:02.000Z", "avg_line_length": 59.0143884892, "max_line_length": 207, "alphanum_fraction": 0.6592709984, "num_tokens": 2378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.5, "lm_q1q2_score": 0.34465280839272305}}
{"text": "\\documentclass[12pt]{article}\n\\usepackage{geometry}\n\\geometry{left=1in,right=0.75in,top=1in,bottom=1in}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Replace ABCDEF in the next line with your chosen problem\n% and replace 1111111 with your Team Control Number\n\\newcommand{\\Problem}{E}\n\\newcommand{\\Team}{2102362}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\usepackage{newtxtext}\n\\usepackage{amsmath,amssymb,amsthm}\n\\usepackage{indentfirst}\n\\usepackage{gensymb}\n\\usepackage{setspace}\n\\usepackage{subfigure}\n\\usepackage{listings}\n\\usepackage{bm}\n\\usepackage{float}\n\\usepackage{newtxmath} % must come after amsXXX\n\\usepackage{textcomp}\n\\usepackage{graphicx}\n\\usepackage{cite}\n\\usepackage{xcolor}\n\\usepackage{fancyhdr}\n\\usepackage{booktabs}\n\\usepackage{multirow}\n\\usepackage{makecell}\n\\usepackage{epstopdf}\n\\usepackage{hyperref}\n\\usepackage{titlesec}\n\\usepackage{titletoc}\n\\usepackage{appendix}\n\\usepackage{url}\n\\usepackage[final]{pdfpages}\n\\linespread{1}\n\\setlength{\\parskip}{0.5\\baselineskip}\n\\setlength{\\parindent}{2em}\n\\lhead{Team \\Team}\n\\rhead{}\n\\cfoot{}\n\n\\newtheorem{theorem}{Theorem}\n\\newtheorem{corollary}[theorem]{Corollary}\n\\newtheorem{lemma}[theorem]{Lemma}\n\\newtheorem{definition}{Definition}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\setlength{\\headheight}{15pt}\n\n\\begin{document}\n\\graphicspath{{.}}  % Place your graphic files in the same directory as your main document\n\\DeclareGraphicsExtensions{.pdf, .jpg, .tif, .png}\n\\thispagestyle{empty}\n\\vspace*{-16ex}\n\\centerline{\\begin{tabular}{*3{c}}\n        \\parbox[t]{0.3\\linewidth}{\\begin{center}\\textbf{Problem Chosen}\\\\ \\Large \\textcolor{black}{\\Problem}\\end{center}}\n         & \\parbox[t]{0.3\\linewidth}{\\begin{center}\\textbf{2021\\\\ MCM/ICM\\\\ Summary Sheet}\\end{center}}\n         & \\parbox[t]{0.3\\linewidth}{\\begin{center}\\textbf{Team Control Number}\\\\ \\Large \\textcolor{black}{\\Team}\\end{center}} \\\\\n        \\hline\n    \\end{tabular}}\n%%%%%%%%%%% Begin Summary %%%%%%%%%%%\n\n\\begin{center}\n    {\\Large \\quad Prior Factors of a Food System: Money or Balance? \\newline Case Studies on China, USA, and Ethiopia }\n\n    \\vspace{1em}\n    {\\large \\textbf{Summary}}\n\\end{center}\n\\vspace{-0.5em}\n\n\\textbf{Food system} is an integrated concept reflecting human activities in the production and acquisition of food. A food system is strongly associated with other systems such as economy system, ecology system, and society system. Nowadays, the stability of a food system are of greater and greater significance for building a harmonious society and promoting national development. However, at present our global food system works mainly based on the control of market, where people in the system are blindly in pursuit of high efficiency and high profitability, causing problems including the imbalance of distribution and environmental degradation. The aim of this report is to \\textbf{build a re-optimization model} to evaluate the result of reordering the significance of different \\textbf{indicators}. These indicators are efficiency, profitability, equity, and sustainability. We also establish a \\textbf{predictive model} to reflect the change of the food system along with time variation. Besides, we do case studies and discuss the completeness of the model. \n\nFor the re-optimization model, we collect data of 18 indices in 3 countries from 2000 to 2020 in total, and use these indices to build four models for the four indicators. In this part, we first adopt the \\textbf{logistic model} to predict the population change. Then we build an differential equation for finding efficiency, and use \\textbf{Runge-Kutta method} to get the numerical solution. According to the results, we build a model for evaluating equity. Next, in the model for evaluating profitability, we use \\textbf{linear programming} to ensure that the data we use is within a reasonable range. Finally, we use \\textbf{linear} and \\textbf{nonlinear fitting} method to evaluate sustainability. \n\nFor the prediction model, we normalize all the data we derived, and then obtain the values of weight through \\textbf{analytic hierarchy process (AHP)}. We assess the validity of the weights to prove the correctness of comparison matrix. We also provide calculations of the final prioritized food system index $PFSI$ by doing a special \\textbf{weighted summation}. The result of $PFSI$ shows the food system evaluation results under a certain degree of emphasis for the four indicators. If $PFSI$ is closer to 0, then the focus of the food system we analyze is more on efficiency and profitability. If the result is closer to 0, then the focus is more on sustainability and equity.\n\nFor the discussion section, we first use the data we collected for the prediction of the food system after re-optimization. Then, we discuss the benefits and costs for changing the order of the four indicators. We apply our model into \\textbf{China}, \\textbf{USA}, and \\textbf{Ethiopia} for case studies and analyze the different consequence between developing countries and developed countries. Moreover, we pay attention to the scalability and adaptability of the model. Finally, we discuss the strengths and potential improvements of the food system model.\n\n\n\n\\vspace{2em}\n\\textbf{Keywords}: Food system, Analytic hierarchy process (AHP), Logistic model, Linear Programming, Runge-Kutta method, Nonlinear fitting, Linear fitting\n\n% to here\n%%%%%%%%%%% End Summary %%%%%%%%%%%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\clearpage\n\\pagestyle{fancy}\n% Uncomment the next line to generate a Table of Contents\n\n\\newpage\n\\setcounter{page}{1}\n\\rhead{Page \\thepage\\ }\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\titlecontents{section}[0cm]{\\fontsize{12pt}{\\baselineskip}\\selectfont}{\\hspace*{3em}\\contentslabel{2em}\\ }%\n{}{\\titlerule*[0.5pc]{$\\cdot$}\\contentspage\\hspace*{1cm}\\vspace*{-0.3em}}%\n\n\\titlecontents{subsection}[1cm]{\\fontsize{10pt}{\\baselineskip}\\selectfont}{\\hspace*{3em}\\contentslabel{2em}\\ }%\n{}{\\titlerule*[0.5pc]{$\\cdot$}\\contentspage\\hspace*{1cm}\\vspace*{-0.5em}}%\n\n\\titlecontents{subsubsection}[2cm]{\\fontsize{10pt}{\\baselineskip}\\selectfont}{\\hspace*{3em}\\contentslabel{2em}\\ }%\n{}{\\titlerule*[0.5pc]{$\\cdot$}\\contentspage\\hspace*{1cm}\\vspace*{-0.6em}}%\n\n\\tableofcontents\n\n\n\\newpage\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Introduction}\n\\vspace{-1em}\n\\subsection{Background}\n\n\nThe food system is conceived as a set of human activities from food production to processing, distribution, and consumption \\cite{cite:Prior}. Its complexity shows up in its manifold drivers, feedback, outcomes, and relations with other human systems, and its concepts are constantly enriched with human's increasing attention to its connotation. From a macroscopic perspective, the current analysis of food systems is strongly connected to the topic of \\textbf{food security}, which refers to a goal that everyone in the world can get access to sufficient and nutritious food to satisfy the diet needs \\cite{cite:Concept}. For example, a scientific group for the 2021 United Nations food systems summit suggests that the ability of the food system to enable every human to be well-nourished should be the core of the overall action tracks, which can be recognized as a pursuit for sustainability and equity \\cite{cite:Summit}.\n\n\\vspace{-1em}\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width = 0.5\\textwidth]{figure/FS.pdf}\n    \\vspace{-1em}\n    \\caption {Sustainable food systems \\cite{cite:fig}}\n\\end{figure}\n\n\\vspace{-1em}\nHowever, due to the leading rule of the market, at present the prior objective of the global food system is maximum efficiency along with the highest profit \\cite{cite:Market}. The market control of trade and prices and regional inherent inequities make the basic demands for food by many kinds of vulnerable groups hard to be satisfied. As a result, distribution problems such as food waste and food shortage have emerged. For example, in 2016 about 10.7\\% people in the world suffer from malnutrition problems, but at the same time about 1/3 of all the food produced is wasted \\cite{cite:USDA}. Furthermore, negative interactions that are exerted between the food system and other correlated systems like environment system and economic system make the dilemma of the food system harder to solve. \n\n\\vspace{-1em}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Restatement of the Problem}\n\nTo ensure a more stable food system with a more comprehensive selection of different objectives, an optimization model must be established to improve the current conditions of the food system. As a consultant team for the International Comestibles Management (ICM) Committee, we are going to implement the following tasks:\n\n\\begin{itemize}\n    \\item Find the factors related to the food system, determine the objectives of our model, and choose representative indicators.\n    \\item According to the indicators we fix, build a comprehensive evaluation model for the current food system.\n    \\item Re-optimize the food system given a more preferable objective, and compare the ideal food system with the current one, and then analyze the feasibility of improving the food system.\n    \\item Discuss the trade-offs of optimization, including both benefits and costs of the change.\n    \\item Apply the model to countries with different levels of development and compare the results.\n    \\item Analyze the extendability and adaptability of the food system model. \n\\end{itemize}\n\n\\vspace{-1em}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Our Work}\nOur efforts can be summarized in the following flow chart.\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width = 1\\textwidth]{figure/procedure.pdf}\n    \\caption{Structure of the model and paper}\n    \\label{procedure}\n\\end{figure}\n\n\\section{Assumptions and Justifications}\n\nWe make the following assumptions in the modelling process. \n\n\\noindent \\textbf{Assumption 1.} \\textit{Country is the unit of a food system.}\n\nAccording to the instructions of the question of comparison between developed and developing countries, we assume that our evaluation for food systems is conducted in terms of country, and the model only synthesizes the consideration of food system for profitability, efficiency, equity, and sustainability.\n\n\\noindent \\textbf{Assumption 2.} \\textit{Imports and exports among countries are neglected.}\n\nWe assume that we do not consider the import and export of food among countries. In addition, we assume that food is distributed equally within the country we study. Since based on the data provided by FAO almost all the major countries in the world have the self-sufficiency rate of food larger than 0.8 \\cite{cite:Self_support}, we regard each country we analyze as an independent place where people produce and market all by themselves. \n\n\\noindent \\textbf{Assumption 3.} \\textit{All the data is reliable and precise.}\n\nWe assume that the data we collected from databases are reliable. They are from major websites including FAO \\cite{cite:FAO_data}, World bank \\cite{cite:Worldbank}, Statista \\cite{cite:Statista}, and Worldometers \\cite{cite:Worldometers}.\n\n\\noindent \\textbf{Assumption 4.} \\textit{Unpredictable natural disasters and other sudden changes will not happen.}\n\nUnforeseen natural hazard such as drought and flood disasters will affect the food system as well as its indices dramatically, so we assume that within the predicted time there are no sudden far-reaching changes.\n\n\\noindent \\textbf{Assumption 5.} \\textit{The change in the population of a country is continuous.}\n\nSince indices of the model is based on the population in a country, we assume that there are not mass migrations or wars that could affect the population in the country. \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Model Preparation}\n\\subsection{Notation}\n\nIn this paper, we define some symbols and parameters, and their notations are shown in Table \\ref{tab:notation}.\n\n\n\\begin{table}[!h]\n    \\centering\n    \\caption{\\label{tab:notation} Notations}\n    \\vspace{1em}\n    \\begin{tabular}{lll}\n        \\toprule\n        Symbols & Description & Units \\\\\n        \\midrule\n        $t$ & time & year \\\\\n        $PM$ & Policy motivation, an adjustable constant & 1 \\\\\n        $UR_{2020}$ & Undernourishment rate in 2020 & \\% \\\\\n        $OR_{2020}$ & Obesity rate in 2020 & \\% \\\\\n        $p(t)$ & Population & person\\\\\n        $p_{2020}$ & Population in 2020 & person \\\\\n        $S_m(t)$ & Target total yield in year $t$ & ton \\\\\n        $S(t)$ & Total yield & ton \\\\\n        $S_{2020}$ & Total yield in 2020 & ton \\\\\n        $s_1(t)$ &Target total yield of cereal in year $t$& ton\\\\\n        $s_2(t)$ &Target total yield of fruit in year $t$& ton\\\\\n        $s_3(t)$ &Target total yield of oil crops in year $t$& ton\\\\\n        $s_4(t)$ &Target total yield of vegetables in year $t$& ton\\\\\n        $s_5(t)$ &Target total yield of dairy in year $t$& ton\\\\\n        $s_6(t)$ &Target total yield of meat in year $t$& ton \\\\\n        $PR_i(t)$ &The corresponding average prices for six different foods in year $t$ & \\$/ton \\\\\n        $IF$ &Average inflation rate of the studied country from 2000 to 2020 & \\%\\\\\n        $IN(t)$ &The annual income of the Food sales in year $t$ & 100000 \\$ \\\\\n        $GHG(t)$ & Total greenhouse gas emissions from agriculture in year $t$ & CO$_2$ equivalent \\\\\n        $r_1$ & Weight of efficiency & 1 \\\\\n        $r_2$ & Weight of equity & 1 \\\\\n        $r_3$ & Weight of profitability & 1 \\\\\n        $r_4$ & Weight of sustainability & 1 \\\\\n        $rs$  & Relative significance of \\textit{EQ} (or \\textit{SU}) with respect to \\textit{EF} (or \\textit{PF}) & 1\\\\\n        $EF(t)$ & Score of efficiency in the food system & 1 \\\\\n        $EQ(t)$ & Score of equity in the food system & 1 \\\\\n        $PF(t)$ & Score of profitability in the food system & 1 \\\\\n        $SU(t)$ & Score of sustainability in the food system & 1 \\\\\n        $PFSI(t)$ & Prioritized food system index & 1 \\\\\n        \\bottomrule\n    \\end{tabular}\n\\end{table}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Model Design}\n\nTo complete our model for the food system, we use $EF$, $EQ$, $PR$, and $SU$ to denote the score of efficiency, score of equity, score of profitability, and score of sustainability respectively. Then the final food system index $PFSI$ can be derived by a special weighted average process. \n\n\\subsection{Preparation: Classic Population Logistic Prediction Model}\n\nTo predict the population in the future for each year, we searched for possible population forecasting models in the database. We choose \\textbf{logistic model} to complete the prediction \\cite{cite:logi}, since compared with \\textbf{Malthus model} we should consider constraints on natural resources, environmental capacity and policies to give a changing population growth rate $r$. We use \\textbf{linear least square method} to obtain the initial value $r_0$ and maximum population $P_{max}$. The solution procedure is shown below.\n\n\\begin{enumerate}\n    \\item Collect population data of China, USA, and Ethiopia from 2000 to 2020.\n    \\item Suppose the population growth rate $r$ is a function varying with population $P$: $r(P) = r_0 - P$. The equation of the logistic model is given by $$\\frac{\\mathrm{d} P}{\\mathrm{d} t} = r_0 (1-\\frac{P(t)}{P_{max}})P(t).$$\n    \\item Get the difference equation by backward difference:\n    \n    $$\\frac{P(k)-P(k-1)}{P(k)} = r_0 - s\\cdot P(k),\\text{ }k = 2, 3, \\cdots, 21.$$\n    \n    \\item Fit the parameters $r_0$ and $P_{max}$ by linear least square method. The result of China and USA are shown in Table \\ref{tab:pplt} below. \n    \n    \\begin{table}[H]\n        \\centering\n        \\caption{\\label{tab:pplt} Values of $r_0$ and $P_{max}$}\n        \\vspace{1em}\n        \\begin{tabular}{ccc}\n            \\toprule\n            & $r_0$ & $P_{max}$ \\\\\n            \\midrule\n            China & -0.0219 & $1.83\\times 10^9$ \\\\ \n            USA & -0.0332 & $0.408\\times 10^9$ \\\\\n            Ethiopia & -0.0381 & 0.328\\times 10^9\\\\\n            \\bottomrule\n        \\end{tabular}\n    \\end{table}\n    \n    \\item Use the separation of variables method for differential equation to derive the analytical solution \n    $$P(t) = \\frac{P_{max}}{1+(\\frac{P_{max}}{P_{2020}}-1)\\cdot e^{r_0(t-2020)}}.$$\n\\end{enumerate}\n\nThe result of our fitting for the population in China and USA is shown in Figure \\ref{fig:USA_pplt} and \\ref{fig:China_pplt}.\n\\begin{figure}[htbp]\n    \\centering\n    \\begin{minipage}[t]{0.48\\textwidth}\n        \\centering\n        \\includegraphics[width=0.9\\textwidth]{figure/model/USA/USA_pplt.eps}\n        \\caption{Logistic Fit of Population of USA.\\label{fig:USA_pplt}}\n    \\end{minipage}\n    \\begin{minipage}[t]{0.48\\textwidth}\n        \\centering\n        \\includegraphics[width=0.9\\textwidth]{figure/model/China/China_pplt.eps}\n        \\caption{Logistic Fit of Population of USA.\\label{fig:China_pplt}}\n    \\end{minipage}\n\\end{figure}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Model for evaluating \\textit{EF}} \\label{sec:EF}\n\nStockholm Environment Institute defines the efficiency in the food system as ``the ratio of outputs to inputs'' \\cite{cite:Efficiency_1}. However, to estimate factors of input and output of different kinds of food requires a huge set of data from measurements and experiments, and from all the literature we read no one even try to explore the overall efficiency of a complex food system. We finally select the sum of the annual food yield of different food as an indicator for efficiency. The selection of the indicator refers to work by \\cite{cite:Esti_efficiency}. \n\nIn order to calculate the value of efficiency in the food system we choose, we do the following steps:\n\n\\begin{itemize}\n    \\item \\textbf{Find the total yield.} Based on the food pyramid provided by a Harvard research \\cite{cite:Food_pyramid}, we divide food into six groups: cereal, fruit, oil crops, vegetable, dairy, and meat. The total food yield is given by Formula \\eqref{eq:yield} below.\n    \n    \\begin{align}\n        \\label{eq:yield} S = \\sum^6_{i=1}s_i, \\text{ where }s_i\\text{ is the yield of the i-th food.}\n    \\end{align}\n    \n    \\item \\textbf{Determine the target yield in year $t$.} Consider the malnutrition rate and obesity rate among adults, the value of the target yield in the i-th year $S_m(t)$ can be obtained by Formula \\eqref{eq:target} below.\n    \n    \\begin{align}\n        \\label{eq:target} S_m(t) = \\frac{S_{2020}/(1+OR_{2020}-UR_{2020})}{p_{2020}}\\cdot p(t).\n    \\end{align}\n    \n    \\item \\textbf{Establish the equation for yield $S(t)$.} In the equation we introduce a coefficient $PM$, called policy motivation, to reflect the regulation of priorities. First, our aim is to ensure that the larger $PM$ is, the greater the efficiency $EF$ changes. Second, we anticipate that if the current food yield $S$ is larger than the target yield $S_m$, $S(t)$ will decrease with respect to time $t$, and if the current $S$ is less than the target yield $S_m$, $S(t)$ will increase with respect to time $t$. Third, the first two changes should be applied to food yield $S(t)$ itself. Then we obtain Equation \\eqref{eq:logi}, which is similar to the equation of logistic model, but \\textbf{the denominator in the middle entry is now a variable, instead of a constant}: \n    \n    \n    \\begin{equation}\n    \\left\\{\n    \\begin{aligned}\n        \\label{eq:logi} & \\frac{\\mathrm{d} S}{\\mathrm{d} t} = PM\\cdot  (1-\\frac{S(t)}{S_m(t)})\\cdot S(t) \\\\\n        & S_{\\text{initial}}  =  S_{2020} \\\\ \n    \\end{aligned}\n    \\right.\n    \\end{equation}\n\n    \\item \\textbf{Solve the differential equation.} In order to obtain the numerical solution of this differential equation, we adopt \\textbf{Runge-Kutta method} for the initial-value problem \\cite{cite:Runge}. First, we separate the interval $[2020, 2050]$ (indicating the year from 2020 to 2050 as our evaluation range) into $N$ sub-intervals $[t_n, t_{n+1}]$ ($n = 0, 1, \\cdots, N-1$). Then, by the mean value theorem we have \n    \n    \\begin{align}\n        S(t_{n+1}) - S(t_n) = \\int^{t_{n+1}}_{t_n} f(t,S(t)) \\mathrm{d}t = (t_{n+1}-t_{n}) f(\\xi, S(\\xi)), \\text{where }\\xi\\in [t_n, t_{n+1}] \\text{\\cite{cite:Runge}}.\n    \\end{align}\n    \n    Finally, by approximation we get \n    \n    \\begin{align}\n        S_{n+1} -S_n = (t_{n+1}-t_n) \\sum^m_{i = 1} c_i f(\\xi_i, y(\\xi_i)), \\text{where we choose }m = 4, c_1 = c_4 =1/6, \n    \\end{align}\n    \n    and $c_2 = c_3 = 1/3$.\n    \n    \\item \\textbf{Normalize the result.} After obtaining results of the total yield, we rate the values by making a \\textbf{min-max normalization}. The form is shown in Formula \\eqref{eq:Normal}.\n    \n    \\begin{align}\n        \\label{eq:Normal} EF(t) = \\frac{S(t)-S_{\\min}}{S_{\\max}-S_{\\min}}\n    \\end{align}\n\\end{itemize}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Model for evaluating \\textit{EQ}}\n\nAccording to the literature found on the database \\cite{cite:Equity_def, cite:Equity_def2}, equity problems in the food system includes racism, gap between the rich and the poor, gender inequality, etc. In our model for the food system, since we take each country as a unit, we are aimed at regarding a country as a whole and finding the difference between countries. \n\nTherefore, for all studied objects, we assume that categories in the dietary structure are totally included by the types of agricultural products produced, which is actually mostly the case. Therefore we claim that countries we selected can be \\textbf{self-sufficient} in food categories. We then come up with a method making full use of the outcomes of Subsection \\ref{sec:EF}. \n\nWe use \\textbf{the ratio of supply and demand $S(t)/S_m(t)$} to denote the level of equity. The interpretation comes from the fact that if the current total yield is close to the target yield then everyone in the country has a chance to have the necessary amount of food, neither too excessive (which implies that there are some people in the country possess the food amount more than they need) nor too insufficient (which implies that there are some people in the country possess the food amount less than they need). Finally, we normalize the result in the same procedure as what is shown in Subsection \\ref{sec:EF}.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Model for evaluating \\textit{PF}} \\label{sec:pf}\n\nThe profitability in the food system can be defined as the \\textbf{total income} by selling all the food in terms of their different prices. Besides, the price by prediction should have limits in the scope of value to prevent price mutations in a certain year. We assume that people are rational enough to always pursue the maximum profit. Therefore, we use \\textbf{linear programming} to solve this problem. \n\nFormula \\eqref{eq:profit} shows the calculation form. For the constraints on linear programming problems, we stipulate the yields of each food \\textbf{within the yields interval for recent five years}, so that we can ensure the continuity of the yields. For the future price of food, we apply \\textbf{linear fit} to each kind of food to predict.\n\n\n\\begin{gather}\n% \n% \\centering\n\\max \\quad  \\sum_{i=1}^{6} (s_i \\frac{PR_i}{IF}), \\notag\\\\\n\\mbox{s.t.} \\quad \n\\sum_{i=1}^{6} s_i =S(t),\\label{eq:profit} \\\\\n\\min \\{ \\frac{s_k(t-j)}{S(t-j)} \\} \\leq \\frac{s_k(t)}{S(t)} \\leq \\max \\{ \\frac{s_k(t-j)}{S(t-j)} \\}, j=1,2,3,\\ldots,5, \\quad k = 1,2,3,\\ldots,6. \\notag\n\\end{gather}\n% &\\min \\{ \\frac{s_2(t-j)}{S(t-j)} \\} \\leq \\frac{s_2(t)}{S(t)} \\leq \\max \\{ \\frac{s_2(t-j)}{S(t-j)} \\},&j=1,2,3\\ldots,5 \\\\\n% &\\min \\{ \\frac{s_3(t-j)}{S(t-j)} \\} \\leq \\frac{s_3(t)}{S(t)} \\leq \\max \\{ \\frac{s_3(t-j)}{S(t-j)} \\},&j=1,2,3\\ldots,5 \\\\\n% &\\min \\{ \\frac{s_4(t-j)}{S(t-j)} \\} \\leq \\frac{s_4(t)}{S(t)} \\leq \\max \\{ \\frac{s_4(t-j)}{S(t-j)} \\},&j=1,2,3\\ldots,5 \\\\\n% &\\min \\{ \\frac{s_5(t-j)}{S(t-j)} \\} \\leq \\frac{s_5(t)}{S(t)} \\leq \\max \\{ \\frac{s_5(t-j)}{S(t-j)} \\},&j=1,2,3\\ldots,5 \\\\\n% &\\min \\{ \\frac{s_6(t-j)}{S(t-j)} \\} \\leq \\frac{s_6(t)}{S(t)} \\leq \\max \\{ \\frac{s_6(t-j)}{S(t-j)} \\},&j=1,2,3\\ldots,5 \\\\\n\n\nFinally, we normalize the result in the same procedure as what is shown in Subsection \\ref{sec:EF}.\n\n\n\\subsection{Model for evaluating \\textit{SU}}\n\nAccording to Holden et al. \\cite{cite:Sus1}, the excessive consumption of fossil fuel is one of the most severe influence current food systems have on the natural environment, and causing the food system unsustainable. Hence, we choose the total emissions from agriculture in one country as an indicator of the sustainability. Considering the fact that the larger food production is, the more emissions from agriculture will be, we take the quotient, i.e., the emissions per unit of the yield, to reflect the performance of sustainability. We should also take the policy motivation into account:\n\n\\begin{itemize}\n    \\item Before the policy change, we do \\textbf{liner fittings} for the data of greenhouse gas emissions and the data of total yield per year we collected respectively. Figure \\ref{fig:lf_E_yield_GHG} shows the fitting performance of greenhouse gas emission and annual yield. The coefficients of determination of linear fit of them are $0.9706$ and $0.9603$ respectively, which are very close to the ideal value $1$. Equations \\eqref{eq:lf_E_GDG} and \\eqref{eq:lf_E_yield} show the fitting results.\n    \\begin{figure}[htbp]\n        \\centering\n    \t\\subfigure[Linear Fit of the Annual Yield of Ethiopia.]{\\includegraphics[width=0.48\\textwidth]{figure/model/Ethiopia/Ethiopia_yield_fit.eps}} \n    \t\\subfigure[Linear Fit of the Greenhouse Gas Emmision of Ethiopia.]{\\includegraphics[width=0.48\\textwidth]{figure/model/Ethiopia/Ethiopia_GHG_fit.eps}} \n        \\caption{Sensitivity Test for Policy Motivation \\textit{PM}.\\label{fig:lf_E_yield_GHG}}\n    \t\\vspace{0.2in}\n    \\end{figure}\n    \\begin{gather}\n        GHG(t) = a\\cdot t - b, \\text{where } a = 2576, b = 5.049\\times10^6 \\label{eq:lf_E_GDG}\\\\\n        S(t) = c\\cdot t - d, \\text{where } c = 1.228\\times10^6, d = 2.443\\times10^9 \\label{eq:lf_E_yield}\n    \\end{gather}\n    Then we have the expression below:\n    \n    $$\\frac{GHG(t)}{S(t)} = \\frac{a t-b}{c t-d}.$$\n    \\item \\textbf{Modify the equation.} After the policy change, we take $PM$ into account, and update the expression as below (suppose the policy change occurs in 2020):\n    \n    $$\\frac{GHG(t)}{S(t)} = \\frac{a (t-2020) + (2020 a -b)(1-PM)}{c (t-2020) + (2020 c - b)(1-PM)},$$\n    \n    from where we should notice that the new function has \\textbf{the same asymptotic line as the older one} (which is $y = a/c$ as $x\\to \\infty$), and the two functions \\textbf{intersect at \\textit{t = 2020}}. The new function also indicates that \\textbf{when \\textit{PM} = 0 the two functions are equal}, and given a stronger policy motivation $PM$ the new function will drop more steeply.\n\\end{itemize}\n\nAfter we predict the value of sustainability by year, we normalize the result in the same procedure as what is shown in Subsection \\ref{sec:EF}.\n\n\\subsection{Model for evaluating \\textit{PFSI}}\nWe obtain the prioritized food system index $PFSI$ by making weighted summation of $EF$, $EQ$, $PR$, and $SU$. Values of weight are obtained through \\textbf{Analytic Hierarchy Process (AHP)}. To reasonably indicate the main focus of the food system, we define Formula \\eqref{eq:PFSI} below to find the value of $PFSI$:\n\n\\begin{align}\n    \\label{eq:PFSI} PFSI(t) = (1-EF(t))\\cdot r_1 + (1-PR(t))\\cdot r_3 + EQ(t)\\cdot r_2 + SU(t)\\cdot r_4\n\\end{align}\n\nIt is suggested that \\textbf{when \\textit{PFSI} is closer to 0 the focus of the food system is more on \\textit{EF} and \\textit{PR}}, and \\textbf{when \\textit{PFSI} is closer to 1 the focus of the food system is more on \\textit{SU} and \\textit{EQ}}.\n\n%图？\n\nThe steps of calculating weights by \\textbf{AHP} are shown below:\n\\begin{itemize}\n    \\item We first determine the relative significance of four factors (\\textit{EF}, \\textit{PF}, \\textit{EQ}, and \\textit{SU}). Specifically, \\textit{EF} and \\textit{PF} are considered to have the same significance, and \\textit{EQ} and \\textit{SU} are considered to have the same significance. We set the the significance of \\textit{EQ} (or \\textit{SU}) with respect to \\textit{EF} (or \\textit{PF}) to be $rs$. Then, the comparison matrix $A$ (Equ. \\eqref{eq:comM}) is set up.\n    \\begin{equation}\n        A=\\left[\\begin{array}{cccc}\n        1 & 1 & 1/rs & 1/rs \\\\\n        1 & 1 & 1/rs & 1/rs \\\\\n        rs & rs & 1 & 1     \\\\\n        rs & rs & 1 & 1\n        \\end{array}\\right]\n        \\label{eq:comM}\n    \\end{equation}\n    In the case study (Sec. \\ref{sec:case}), we set $rs = 7$. However, the absolute value of $rs$ does not affect the general shape of the final result, which will be verified in sensitivity analysis (Sec. \\ref{sec:sense}).\n    \\item Calculated the eigenvalues of matrix $A$, we can further determine the weights of \\textit{EF}, \\textit{PF}, \\textit{EQ}, and \\textit{SU} by normalize the eigenvector of the maximum eigenvalue. Namely, the weight vector can be calculated through Equ. \\eqref{eq:AHPweight}.\n    \\begin{equation}\n        \\mathbf{w} = \\frac{\\mathbf{v}}{\\|\\mathbf{v}\\|_1} = \\frac{\\mathbf{v}}{\\sum_{i=1}^4|v_i|}\n        \\label{eq:AHPweight}\n    \\end{equation}\n    \\item To prevent the possible conflict caused by arbitrarily set significance, we are supposed to assess the validity of the weights. We define the consistency index $CI$ as\n    \\begin{equation}\n        CI = \\frac{\\lambda - 4}{4-1} = \\frac{\\lambda - 4}{3},\n    \\end{equation}\n    where $\\lambda$ is the maximum eigenvalue of comparison matrix $A$. Then, the consistency ratio $CR$ can be calculated through\n    \\begin{equation}\n        CR = \\frac{CI}{RI},\n    \\end{equation}\n    where $RI$ is random consistency index. Here, we have 4 factors in total, so $RI=0.9$. In general, if $CR<0.1$, the weights obtained from AHP is valid.\n\\end{itemize}\n\n\\section{Discussion}\n\\subsection{Task 1: Re-Optimization for the Food System}\n\nSince there are interactions among the model for efficiency, profitability, sustainability, and equity, after the optimization for equity and sustainability we need to look at the consequence of the changes of their weight. We consider the situation in different countries. \n\n\\begin{itemize}\n    \\item \\textbf{For a country in which the undernourishment rate is less than the obesity rate, we claim that the total food production amount is enough to satisfy the need of all the population.} The country produces food surpluses. As a result, under the influence of policy motivation, the country will tend to produce exactly the amount of food they need, so that the total yield of food \\textbf{will decrease at first}, causing a decline of $EF$. When the intermediate rate state is reached, the prediction of the level of efficiency will depend on the population change as well. In the countries where the population is growing continuously, the annual food yield should try to catch up with the population, and accordingly \\textbf{the total yield and $EF$ will increase since then}. In the countries where the population is declining, the change will be in the opposite case.\n    \n    Besides, the value of the level of \\textbf{equity ($S/S_m$) will decrease to 1} at first since the food yield is large. According to the differential equation, we can see that at this time the growth rate of the yield is 0. Hence, the value of $S/S_m$ will go on decreasing until less than 1. However, the slope of $S$ will be higher until it surpasses the population growth rate, so that \\textbf{in the end $S/S_m$ will approach to 1}, implying that the amount of food per person is more equitable. \n    \n    As for the profitability, since the prices of each kind of food is not fixed, these prices are predicted by linear fitting. However, one thing is known that we use the yields interval for recent five years for the linear programming, so that we may infer from the expression that \\textbf{the level of profitability will change smoothly}. Another supporting argument is that we aim to find the maximum income for each year so that the \\textbf{food system still seek for the maximum benefits even sustainability is considered now}.\n    \n    For the prediction of the change of sustainability, we can find that the \\textbf{greenhouse gas emissions keep increasing in developing countries} like China, and remain nearly constant in developed countries like the USA. Then after exerting policy motivation, \\textbf{the value of $GHG(t)/S(t)$ will decrease faster than the case before re-optimization}. However, for our model in the end the level of sustainability will be the same as before because the two functions have the same asymptotic line. It reflects that this model loses some accuracy for a very long term prediction.\n    \n    \n    \\item \\textbf{For a country in which the undernourishment rate is higher than the obesity rate}, the total food production amount is not enough. In this case, the total yield will be raised to meet the need for food by residents. If the population growth rate is larger than \\textbf{$PM$, $S/S_m$ will be firstly less than 1 then approach 1}. In the end, the population reaches its limit, and correspondingly the yield will approach approximately a constant.\n    \n    On the contrary, \\textbf{if the population growth rate is less than $PM$}, then $S/S_m$ will decline due to the fact that the yield does not catch up with the rate of population growth. When the population growth rate begins decreasing, $S/S_m$ will rise up again until leveling off to 1.\n    \n    The analysis of profitability and sustainability is the same as above.\n    \n\\end{itemize}\n\n\n\\textbf{We define 0.5 as the balance value for efficiency, profitability, equity, and sustainability.} It means that we regard them as equally important. According to our model, the time that a food system needs to implement should be counted from the occurrence of policy change to the moment when $PFSI$ reaches 0.5 from either side for the first time. The interpretation is that when $PFSI > 0.5$ indicators including sustainability and equity become more important than efficiency and profitability. \n\n%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Task 2: Benefits and Costs}\n\nWe only consider the case of changing the priorities of a food system from efficiency and profitability to sustainability and equity. The opposite direction will give the contrary result. \n\n\\subsubsection{Potential benefits}\n\n\\begin{itemize}\n    \\item \\textbf{Distribution become more reasonable within developed countries, and will first receive a drop in some developing countries, but later will recover.} When we change the prioritization of food system to sustainability and equity, it is obvious that \\textbf{ developed countries will tend to distribute its food more fairly} among its residents, because the equity is always approaching 1. However, for some developing countries, Ethiopia, for example, firstly received a drop in equity. This can result from the fact that the production rate fails to exceed the population rate at first. But later, equity of developing countries will approach 1 again as the production rate increases and the population growth rate decreases.\n    \\item \\textbf{Under the motivation of policy, sustainability for both developed countries and developing countries become stronger.} As it will also \\textbf{limits the increase of emission amount of greenhouse gas} if the total yields grow. Such effect becomes \\tetxbf{mostly apparent in the developed country}, as the obesity rate is much larger than the undernourishment rate, and the yield generally decreases. While in some developing country, which has a large undernourishment rate, yield growth is also limited with stronger sustainability, so that the atmosphere and environment are protected, and used more efficiently.\n\\end{itemize}\n\n\\subsubsection{Potential costs}\n\\begin{itemize}\n    \\item \\textbf{Developing countries will become tougher when cooperating with the increase of the population} For some developing countries, whose obesity rate is slightly larger than the undernourishment rate, they will first drop the yields to fit the current population and then try to keep pace with the population growth. Comparing with such a \"following\" strategy, if countries try to increase their yields at first to cope with the future population, they will become more prepared.\n    \n    \\item \\textbf{Profit from the food industry will always decrease regardless of developed and developing countries.} In the later case study section, we illustrate the change of profitability, and these charts show that all developed and developing countries received profit loss. On one hand, this can result from some yield drop in some developed countries. On the other hand, some developing countries have a relatively large inflation rate, causing the actual profit to become less valuable. \n\\end{itemize}\n\n\\subsubsection{Prediction on the occurrence of the benefits and costs}\nHere, we firstly define \\textbf{the occurrence of the previously mentioned benefits and costs as the time when equity is within the interval [0.95,1.05] and is continuously monotonically increasing/ monotonically decreasing to approach 1}. With that definition and referring to the findings in section \\ref{sec:case}, we can find that China's occurrence time happened in the approximately year 2045 and that Ethiopia's occurrence time happened in the approximately year 2025, while America's occurrence time happened in the approximately year 2051. Therefore, with these experiment result, we can qualitatively conclude that \\textbf{the occurrence time of developed countries is later than the developing countries under the same policy motivation (PM)}.\n\n%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Task 3: Case Studies}\\label{sec:case}\n\nInstead, we need to utilize the prediction result of food prices and greenhouse gas emissions. Here we only show the plot of the scores for each indicator by using the method mentioned before. \n\n\\subsubsection{China: Developing Country with $UR_{2020}$ relatively less than $OR_{2020}$}\nChina is the representative developing country whose economic situation is very close to some developed countries. Specifically, the undernourishment rate of China is much smaller than the obesity rate in year 2020. This fact reflected a high possibility that the food China produced is more than the demand of people. However, as a developing country, its population is still in the quickly rising period. Thus, \\textbf{the current supply of food can not satisfy the demand of its future maximum population}. To satisfy the food demand of current population, \\textbf{the yield amount will firstly receive a slight drop until year 2035. But after that, the yield will continuously increase to follow the increase of population and corresponding demand.} Figure \\ref{fig:China_yield} shows the predicted situation with policy motivation. This result is obtained from the model for evaluating \\textit{EF} with \\textit{PM}$=0.1$. Meanwhile, the equity of food will be improved due to a better arrangement of supply. As the annual yield is controlled by the policy, the supply is gradually close to the demand (Fig. \\ref{fig:China_equity}), which ensures the domestic equity of food system. As shown in the Figure \\ref{fig:China_yield} and \\ref{fig:China_equity}, the effect of the policy will reach the maximum at approximately year \\textbf{2035}, namely, 15 years after the implementation of policy. After about \\textbf{25 years} of continuously policy motivation, the re-optimized food system is finally set up. \\textbf{At that time, the ratio of supply demand is extremely close to 1 and the yield is almost constant.}\n\\begin{figure}[htbp]\n    \\centering\n    \\begin{minipage}[t]{0.48\\textwidth}\n        \\centering\n        \\includegraphics[width=0.9\\textwidth]{figure/model/China/China_yield.eps}\n        \\caption{Annual Yield of China with Policy Interference.\\label{fig:China_yield}}\n    \\end{minipage}\n    \\begin{minipage}[t]{0.48\\textwidth}\n        \\centering\n        \\includegraphics[width=0.9\\textwidth]{figure/model/China/China_equity.eps}\n        \\caption{Ratio of Supply and Demand of Food of China with Policy Interference.\\label{fig:China_equity}}\n    \\end{minipage}\n\\end{figure}\n\nBesides, the policy will have a \\textbf{negative effect on the income} of the people served in the food system and a \\textbf{positive effect on the sustainability} of the food system. Due to the effect of inflation, the short-term decrease of yield will result in a \\textbf{continuous attenuation of the income}. Using the model stated in Section \\ref{sec:pf}, we can predict the income (Fig. \\ref{fig:China_income}). Furthermore, the policy will also \\textbf{push the development of science} in order to decrease the labor cost. This in turn improves the production method such that less greenhouse gas emission is necessary for the same yield. Red line in figure \\ref{fig:China_GHG} shows the \\textbf{accelerated decreasing trend greenhouse gas emission} with policy motivation. \n\\begin{figure}[H]\n    \\centering\n    \\begin{minipage}[t]{0.48\\textwidth}\n        \\centering\n        \\includegraphics[width=0.9\\textwidth]{figure/model/China/China_profit.eps}\n        \\caption{Income of Food System of China with Policy Interference.\\label{fig:China_income}}\n    \\end{minipage}\n    \\begin{minipage}[t]{0.48\\textwidth}\n        \\centering\n        \\includegraphics[width=0.9\\textwidth]{figure/model/China/China_sustainability.eps}\n        \\caption{Greenhouse Gas Emission per yield of the Food System of China with Policy Interference.\\label{fig:China_GHG}}\n    \\end{minipage}\n\\end{figure}\n\nFinally, with the economic, social, scientific, and environmental factors taken into account, the food system in China will prioritize equity and sustainability \\textbf{after the 15 years} of implementation of the policy. With \\textbf{10 more years} of development, the benefits and the costs of the new food system will be manifest. Figure \\ref{fig:China_score} shows the change of evaluated \\textit{PFSI} with \\textit{EF}, \\textit{PF}, \\textit{EQ}, and \\textit{SU} marked. Figure \\ref{fig:China_radar} shows the standardized score of \\textit{EF}, \\textit{PF}, \\textit{EQ}, and \\textit{SU} in 2021, 2035 (15 years after policy's implementation), 2045 (25 years after policy's implementation).\n\\begin{figure}[!htb]\n    \\centering\n    \\begin{minipage}[t]{0.48\\textwidth}\n        \\centering\n        \\includegraphics[width = 0.8\\textwidth]{figure/model/China/China_score.eps}\n        \\caption{\\textit{PFSI} of China with All Four Factors Specified from 2015 to 2045.\\label{fig:China_score}}\n    \\end{minipage}\n    \\begin{minipage}[t]{0.48\\textwidth}\n        \\centering\n        \\includegraphics[width = 0.8\\textwidth]{figure/radar/China_radar.pdf}\n        \\caption{The Change of Four Factors of China's Food System.\\label{fig:China_radar}}\n    \\end{minipage}\n\\end{figure}\n\n\\subsubsection{Ethiopia: Developing Country with $UR_{2020}$ larger than $OR_{2020}$} \nEthiopia is a typical developing country with a high undernourishment rate and low obesity rate. Therefore, the current food supply of Ethiopia is far away from the demand of its possible maximum population. As we change the priority of the food system by introducing the policy motivation, the annual yield will \\textbf{quickly increase to satisfy the demand of the population} (Fig. \\ref{fig:Ethiopia_yield}). As for the equity, policy motivation \\textbf{inhibits increasing speed of equity} to prevent it exceeds the ideal value $1$. Similar to Ethiopia, the income will be affected by the policy so that it \\textbf{decreases quickly at the beginning of the policy's implementation}. However, due to the large inflation rate, the \\textbf{decreasing speed is much larger} than in China. Besides, the sustainability of Ethiopia will also be improved with the policy motivation. The biggest difference between China and Ethiopia is the value of policy motivation \\textit{PM}. To obtain the same effect as the food system of China, Ethiopia needs to \\textbf{implement a much stronger policy regulation}. Through our estimation, the value of policy motivation of Ethiopia should be approximately 10 times that of China to get the same effect. In this case study, we choose to use policy motivation \\textit{PM}$=1$.\n\\begin{figure}[htbp]\n    \\centering\n    \\begin{minipage}[t]{0.48\\textwidth}\n        \\centering\n        \\includegraphics[width=0.9\\textwidth]{figure/model/Ethiopia/Ethiopia_yield.eps}\n        \\caption{Annual Yield of Ethiopia with Policy Interference.\\label{fig:Ethiopia_yield}}\n    \\end{minipage}\n    \\begin{minipage}[t]{0.48\\textwidth}\n        \\centering\n        \\includegraphics[width=0.9\\textwidth]{figure/model/Ethiopia/Ethiopia_equity.eps}\n        \\caption{Ratio of Supply and Demand of Food of Ethiopia with Policy Interference.\\label{fig:Ethiopia_equity}}\n    \\end{minipage}\n\\end{figure}\n\nFinally, we calculate the line of \\textit{PFSI}. After changing the weight of efficiency, profitability, equity, and sustainability, a gap appears in the year 2020. Different from China, the growth rate of Ethiopia's \\textit{PFSI} is not that big. Instead, \\textit{PFSI} \\textbf{increases gradually in the beginning} and \\textbf{is stable in year 2030}. Namely, only \\textbf{10 years of policy motivation} can bring the underdeveloped food system of Ethiopia back to the right track, the balanced mode. Figure \\ref{fig:Ethiopia_radar} shows the standardized score of \\textit{EF}, \\textit{PF}, \\textit{EQ}, and \\textit{SU} in 2021, 2035, and 2045.\n\\begin{figure}[!htb]\n    \\centering\n    \\begin{minipage}[t]{0.48\\textwidth}\n        \\centering\n        \\includegraphics[width = 0.8\\textwidth]{figure/model/Ethiopia/Ethiopia_score.eps}\n        \\caption{\\textit{PFSI} of Ethiopia with All Four Factors Specified from 2015 to 2045.\\label{fig:Ethiopia_score}}\n    \\end{minipage}\n    \\begin{minipage}[t]{0.48\\textwidth}\n        \\centering\n        \\includegraphics[width = 0.8\\textwidth]{figure/radar/Ethiopia_radar.pdf}\n        \\caption{The Change of Four Factors of Ethiopia's Food System.\\label{fig:Ethiopia_radar}}\n    \\end{minipage}\n\\end{figure}\n\n\\subsubsection{The USA: Developed Country with $UR_{2020}$ much less than $OR_{2020}$}\nThe USA is a developed country where the undernourishment rate is very small while the obesity rate is very large. \\textbf{Therefore, the current food supply of the USA even exceeds the demand of its possible maximum population.} After we change the priority to sustainability and equity, \\textbf{the total yield amount (Fig. \\ref{fig:USA_yield}) will generally receive a drop to satisfy the demand of population}, even in the year 2050, there will be a historically lowest point for the yields.  Moreover, as the equity index($S/S_m$) (Fig. \\ref{fig:USA_equity}) is high at the present yield speed (about 1.4 in 2020), under the control of $PM$(policy motivation, set as 0.1), the equity will drop to 0.98 at the lowest level in the approximately year 2050 and then recover to 1 gradually so that it can compensate the increasing food demand caused by population growth. We can conclude that dropping the unnecessary yield of food can improve the sustainability of the food system, and increase equity in the long run.\n\\begin{figure}[htbp]\n    \\centering\n    \\begin{minipage}[t]{0.48\\textwidth}\n        \\centering\n        \\includegraphics[width=0.9\\textwidth]{figure/model/USA/USA_yield.eps}\n        \\caption{Annual Yield of USA with Policy Interference.\\label{fig:USA_yield}}\n    \\end{minipage}\n    \\begin{minipage}[t]{0.48\\textwidth}\n        \\centering\n        \\includegraphics[width=0.9\\textwidth]{figure/model/USA/USA_equity.eps}\n        \\caption{Ratio of Supply and Demand of Food of USA with Policy Interference.\\label{fig:USA_equity}}\n    \\end{minipage}\n\\end{figure}\n\nSimilar to China, policy motivation will have a \\textbf{negative effect on the income} of the people served in the food system due to the effect of inflation and price change. This is reasonable after taking the decrease in food yield into consideration. Besides, the ratio $GHG(t)/S(t)$ is also continuously drop with time. With the motivation of policy ($PM$=0.1), \\textbf{the drops will be more quickly} comparing with the slope of $PM=0$.\n\nFinally, we can calculate the line of $PFSI$ (figure\\ref{fig:USA_score}). After changing the weight of equity, sustainability, profitability, and efficiency, a sudden drop happens in the year 2020. Then, \\textbf{$PFSI$ will continuously grow} with its slope continuously drop. In approximately \\textbf{the year 2027}, the scoring of $PFSI$ will exceed 0.5, which is the time the food system is optimized for equity and sustainability. In approximately \\textbf{the year 2040},\nefficiency received its historical highest point, and the differential of $PFSI$ received a sudden drop, which is the time the benefits and cost become manifest. Figure\\ref{fig:USA_score} shows the standardized score of $EF$, $PF$, $EQ$, and $SU$ in 2021,2035, and 2045.\n\n\n\\begin{figure}[!htb]\n    \\centering\n    \\begin{minipage}[t]{0.48\\textwidth}\n        \\centering\n        \\includegraphics[width = 0.8\\textwidth]{figure/model/USA/USA_score.eps}\n        \\caption{\\textit{PFSI} of USA with All Four Factors Specified from 2015 to 2045.\\label{fig:USA_score}}\n    \\end{minipage}\n    \\begin{minipage}[t]{0.48\\textwidth}\n        \\centering\n        \\includegraphics[width = 0.8\\textwidth]{figure/radar/USA_radar.pdf}\n        \\caption{The Change of Four Factors of USA's Food System.\\label{fig:USA_radar}}\n    \\end{minipage}\n\\end{figure}\n\n\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Task 4: Scalability and Adaptability of the Model}\n\n\\subsubsection{Scalability}\n\nFood systems with different scales are under consideration. After analysis, we make the following conclusions.\n\n\\begin{itemize}\n    \\item \\textbf{The larger the food system is, the better our optimization will be}. Given a larger food system (major economies or unions of nations), the production structure of the food system will fit better with the common dietary structure for the residents. The reason is that we do not consider the food trade as well as other food communications between countries, and a larger scale can provide a more self-sufficient system.\n    \\item \\textbf{Food systems of countries suit best}. Since the model is designed for countries, we consider the yearly inflation rate of a country in the model of profitability. The data processing may be revised if given other systems than countries.\n\\end{itemize}\n\n\\subsubsection{Adaptability}\n\nFood systems with different properties are under consideration. Adaptability reflects the consequence when we change the object of the food system model. We have the following results.\n\n\\begin{itemize}\n    \\item \\textbf{The model fits with countries with different $PM$}. For big countries like China and the USA, there is a large population along with strong scientific and technological support. However, for countries which have a smaller population and weaker policy support, the intensity of policy motivation needs to be modified to reflect the difference.\n    \\item \\textbf{The model reflects the global polarization between rich countries and poor countries}. In Section \\ref{sec:EF}, we include the undernourishment rate and the obesity rate into our evaluation model. With regard to Formula \\eqref{eq:logi}, if $S_{2020}$ of a country is less than $S_m$, namely the average undernourishment rate is larger than the average obesity rate, then $1-S/S_m$ will be larger than 0. It indicates that the formula adapts to countries with different conditions of rich and poor.\n    \\item \\textbf{The model is suitable for the comparison among countries with similar production capacity for food}. Since the costs in the production of food are neglected, the closer the production capacity among countries, the more comparable the result of profitability will be.\n\\end{itemize}\n\n\n\\section{Sensitivity Analysis}\\label{sec:sense}\nIn our model, there are two variables whose value is set by us without derivation. They are the policy motivation \\textit{PM} and the relative significance $rs$. \\textit{PM} is set to $0.1$ in the cases of China and the USA and is set to $0.5$ in the cases of Ethiopia. $rs$ is set to $7$ in calculating weights of \\textit{EF}, \\textit{PF}, \\textit{EQ}, and \\textit{SU}. In this part, we will argue that the results we get from the model are not sensitive to the change of the values of \\textit{PM} and $rs$.\n\n\\subsection{\\textit{PM} Fluctuation Test.}\nPolicy motivation $PM$ represents the strength of policy in encouraging the balanced development of the food system. It is first used to calculate the annual yield and equity index in our model for a prioritized food system. We re-calculate the annual yield and equity index with a different value of \\textit{PM}, ranging from $0.04$ to $0.4$. The results are shown in Figure \\ref{fig:sense_pm}.\n\\begin{figure}[!htb]\n    \\centering\n\t\\subfigure[Re-calculating of Annual Yield of USA with Different Values of \\textit{PM}.]{\\includegraphics[width=0.48\\textwidth]{figure/sense/sense_pm_yield.pdf}} \n\t\\subfigure[Re-calculating of Equity Index of USA with Different Values of \\textit{PM}.]{\\includegraphics[width=0.48\\textwidth]{figure/sense/sense_pm_equity.pdf}} \n    \\caption{Sensitivity Test for Policy Motivation \\textit{PM}.\\label{fig:sense_pm}}\n\t%\\vspace{0.2in}\n\\end{figure}\n\nAlthough the value of \\textit{PM} varies dramatically, the general shape of the annual yield does not change a lot. Annual yield always has a trend of decreasing to a minimum and increasing to a fixed asymptote. it is the same for the equity index (ratio of supply and demand). No matter how $PM$ swings, it will approach 1 as the year goes to infinity. Thus, we can conclude that the selection of the value \\textit{PM} is not a significant issue in our model, since the annual yield and equity index is convergent with respect to \\textit{PM}.\n\n\\subsection{\\textbf{\\textit{rs}} Fluctuation Test.}\n$rs$ represents the relative significance of \\textit{EQ} (or \\textit{SU}) with respect to \\textit{EF} (or \\textit{PF}). It is used to calculate the weights to get the final score of \\textit{PFSI}. To verify that the change of this value dose not significantly incluence the final score, we test different values of $rs$, ranging from $1$ to $8$. Figure \\ref{fig:sense_rs} shows the result of the recalculated \\textit{PFSI}. \n\nAlthough the change of $rs$ brings a difference to the weights, the final score does not change significantly. Meanwhile, its trend is generally the same. Namely, \\textit{PFSI} will increases faster in the beginning, and the speed of increasing decreases at approximately the year 2040. This observation confirms that $PFSI$ is not sensitive to the value of $rs$ in our model.\n\\begin{figure}[h]\n    \\centering\n    \\includegraphics[width = 0.6\\textwidth]{figure/sense/sense_AHP.eps}\n    \\caption{Sensitivity Test for $rs$ by Re-calculating the Corresponding \\textit{PFSI}.\\label{fig:sense_rs}}\n\\end{figure}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Strengths and Possible Improvements}\n\\subsection{Strength}\n\n\\begin{itemize}\n    \\item \\textbf{Practicability}: To make our model conform to reality, we divide the food into six groups: cereal. fruit, oil crops, vegetable, dairy, and meat. The model considers all the components of the dietary pyramid.\n    \\item \\textbf{Globality}: We have a macroscopic view of the current food system in the world without taking internal effects into account.\n    \\item \\textbf{Flexibility}: By introducing a variable parameter named policy motivation ($PM$), we can adjust the priorities of efficiency, profitability, sustainability, and equity accordingly. Assigning $PM$ with different possible values (implying that the intensity of policy motivation may vary), our prediction result can be varied to be more flexible.\n\\end{itemize}\n\n\\subsection{Possible Improvements}\n\n\\begin{itemize}\n    \\item \\textbf{We do not consider imports and exports}. If for a particular country there is a huge difference between the total amount of food imports and exports, the deviation of our model with reality will increase. \n    \\item \\textbf{Indicators for our model could be more comprehensive}. In the model of equity, we can add another parameter depicting the matching degree of the dietary structure and the production structure, so that differences in the food distribution within countries can be considered. In addition, in the model of sustainability, more indicators except for greenhouse gas emissions may be added to improve the completeness of the model. The cost of food production may also be included to perfect the model. \n\\end{itemize}\n\n\n\\section{Conclusions}\n\nIn this paper, we first adopt the logistic model to predict the population growth from 2020 to 2050. Next, we build four models for evaluating efficiency, profitability, equity, and sustainability respectively. We use differential equations, linear programming, and linear fitting to help to find the solutions of our model. Then we propose an index called Prioritized Food System Index ($PFSI$) to denote the emphasis of the food system. In the discussion part, we analyze the benefits and costs for re-optimizing the food system, do case studies on China, the USA, and Ethiopia, and discuss the scalability and adaptability of the model. Finally, we conduct a sensitivity analysis to show the influence of policy motivation on the food system index and discuss strengths as well as improvements for our work.\n\n\n\\bibliographystyle{IEEEtran}\n\\bibliography{mybib}\n\n% \\newpage\n\\begin{appendices}\n\\section{Supporting Figures}\n\\begin{figure}[htbp]\n    \\centering\n    \\begin{minipage}[t]{0.48\\textwidth}\n        \\centering\n        \\includegraphics[width=0.7\\textwidth]{figure/model/USA/USA_profit.eps}\n        \\caption{Income of Food System of USA with Policy Interference.}\n    \\end{minipage}\n    \\begin{minipage}[t]{0.48\\textwidth}\n        \\centering\n        \\includegraphics[width=0.7\\textwidth]{figure/model/USA/USA_sustainability.eps}\n        \\caption{Greenhouse Gas Emission per yield of the Food System of USA with Policy Interference.}\n    \\end{minipage}\n\\end{figure}\n\\begin{figure}[htbp]\n    \\centering\n    \\begin{minipage}[t]{0.48\\textwidth}\n        \\centering\n        \\includegraphics[width=0.7\\textwidth]{figure/model/Ethiopia/Ethiopia_profit.eps}\n        \\caption{Income of Food System of Ethiopia with Policy Interference.}\n    \\end{minipage}\n    \\begin{minipage}[t]{0.48\\textwidth}\n        \\centering\n        \\includegraphics[width=0.7\\textwidth]{figure/model/Ethiopia/Ethiopia_sustainability.eps}\n        \\caption{Greenhouse Gas Emission per yield of the Food System of Ethiopia with Policy Interference.}\n    \\end{minipage}\n\\end{figure}\n\\begin{figure}[htbp]\n    \\centering\n    \\begin{minipage}[t]{0.48\\textwidth}\n        \\centering\n        \\includegraphics[width=0.7\\textwidth]{figure/model/USA/USA_GHG_fit.eps}\n        \\caption{Linear Fit of the Greenhouse Gas Emission of USA.}\n    \\end{minipage}\n    \\begin{minipage}[t]{0.48\\textwidth}\n        \\centering\n        \\includegraphics[width=0.7\\textwidth]{figure/model/USA/USA_yield_fit.eps}\n        \\caption{Linear Fit of the Annual Yield of USA.}\n    \\end{minipage}\n\\end{figure}\n\\begin{figure}[htbp]\n    \\centering\n    \\begin{minipage}[t]{0.48\\textwidth}\n        \\centering\n        \\includegraphics[width=0.7\\textwidth]{figure/model/China/China_GHG_fit.eps}\n        \\caption{Linear Fit of the Greenhouse Gas Emission of China.}\n    \\end{minipage}\n    \\begin{minipage}[t]{0.48\\textwidth}\n        \\centering\n        \\includegraphics[width=0.7\\textwidth]{figure/model/China/China_yield_fit.eps}\n        \\caption{Linear Fit of the Annual Yield of China.}\n    \\end{minipage}\n\\end{figure}\n\\begin{figure}\n    \\centering\n    \\includegraphics[width = 0.5\\textwidth]{figure/model/Ethiopia/Ethiopia_pplt.eps}\n    \\caption{Logistic Fit of Population of Ethiopia.}\n\\end{figure}\n%     \\section{Code Example}\n%     %     \\lstset{\n%     %     basicstyle          =   \\sffamily,          % 基本代码风格\n%     %     keywordstyle        =   \\bfseries,          % 关键字风格\n%     %     commentstyle        =   \\rmfamily\\itshape,  % 注释的风格，斜体\n%     %     stringstyle         =   \\ttfamily,  % 字符串风格\n%     %     flexiblecolumns,                % 别问为什么，加上这个\n%     %     numbers             =   left,   % 行号的位置在左边\n%     %     showspaces          =   false,  % 是否显示空格，显示了有点乱，所以不现实了\n%     %     % numberstyle         =   \\zihao{-5}\\ttfamily,    % 行号的样式，小五号，tt等宽字体\n%     %     showstringspaces    =   false,\n%     %     captionpos          =   t,      % 这段代码的名字所呈现的位置，t指的是top上面\n%     %     frame               =   lrtb,   % 显示边框\n%     % }\n\n%     \\vspace{-2em}\n%     \\lstset{frame=tb,\n%         language=Python,\n%         aboveskip=3mm,\n%         belowskip=3mm,\n%         showstringspaces=false,\n%         columns=flexible,\n%         basicstyle={\\small\\ttfamily},\n%         numbers=none,\n%         numberstyle=\\tiny\\color{gray},\n%         keywordstyle=\\color{blue},\n%         % commentstyle=\\color{dkgreen},\n%         % stringstyle=\\color{mauve},\n%         breaklines=true,\n%         breakatwhitespace=true,\n%         tabsize=3\n%     }\n%     % \\lstdefinestyle{Python}{\n%     %     language        =   Python, % 语言选Python\n%     %     basicstyle      =   \\tt\n%     %     % numberstyle     =   \\zihao{-5}\\ttfamily,\n%     %     keywordstyle    =   \\color{blue},\n%     %     % keywordstyle    =   [2] \\color{teal},\n%     %     stringstyle     =   \\color{magenta},\n%     %     commentstyle    =   \\color{red}\\ttfamily,\n%     %     breaklines      =   true,   % 自动换行，建议不要写太长的行\n%     %     columns         =   fixed,  % 如果不加这一句，字间距就不固定，很丑，必须加\n%     %     basewidth       =   0.5em,\n%     % }\n%     % \\lstinputlisting[title = Grey Forecast]{code/GreyPre.py}\n%     \\lstinputlisting[title = Moving Entropy Weight Method]{code/EWM.py}\n%     \\lstinputlisting[title = Grey Forecast]{code/GreyPre.py}\n\n\n\\end{appendices}\n\\end{document}\n\n", "meta": {"hexsha": "2762d2f72de74fd6f521dc6ead1d433241fbe05e", "size": 61769, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "main.tex", "max_stars_repo_name": "zyxum/2021-ICM", "max_stars_repo_head_hexsha": "5533ff4f0606a1ad20a57a8e964ced6a4c026c18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.tex", "max_issues_repo_name": "zyxum/2021-ICM", "max_issues_repo_head_hexsha": "5533ff4f0606a1ad20a57a8e964ced6a4c026c18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.tex", "max_forks_repo_name": "zyxum/2021-ICM", "max_forks_repo_head_hexsha": "5533ff4f0606a1ad20a57a8e964ced6a4c026c18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 77.4047619048, "max_line_length": 1618, "alphanum_fraction": 0.7302206608, "num_tokens": 16261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.3446291108731628}}
{"text": "% 19DistributionsaFoliations.tex\n% Fund Science! & Help Ernest finish his Physics Research! : quantum super-A-polynomials - a thesis by Ernest Yeung\n%                                               \n% http://igg.me/at/ernestyalumni2014                                                                             \n%                                                              \n% Facebook     : ernestyalumni  \n% github       : ernestyalumni                                                                     \n% gmail        : ernestyalumni                                                                     \n% google       : ernestyalumni                                                                                   \n% linkedin     : ernestyalumni                                                                             \n% tumblr       : ernestyalumni                                                               \n% twitter      : ernestyalumni                                                             \n% youtube      : ernestyalumni                                                                \n% indiegogo    : ernestyalumni                                                                        \n%\n% Ernest Yeung was supported by Mr. and Mrs. C.W. Yeung, Prof. Robert A. Rosenstone, Michael Drown, Arvid Kingl, Mr. and Mrs. Valerie Cheng, and the Foundation for Polish Sciences, Warsaw University.                  \n%\n%These notes are open-source, governed by the Creative Common license.  Use of these notes is governed by the Caltech Honor Code: ``No member of the Caltech community shall take unfair advantage of any other member of the Caltech community.'' \\\\\n%\n\n\\subsection*{Distributions and Involutivity}\n\n\\textbf{distribution on $M$ of rank $k$} is rank-$k$ subbundle of $TM$, \\textbf{smooth distribution} if it's smooth subbundle \\\\\nOften rank-$k$ distribution described by specifying $\\forall \\, p \\in M$ linear subspace $D_p \\subseteq T_pM$ of $\\text{dim}D_p = k$, \\\\\n\\phantom{\\quad \\quad \\,} $D = \\bigcup_{p \\in M} D_p$\n\nLemma 10.32, local frame criterion for subbundles, that $D$ smooth distribution iff $\\forall \\, p \\in M$, $\\exists \\, $ open $U \\ni p$ on which $\\exists \\, $ smooth vector fields $X_1 \\dots X_k : U \\to TM$ s.t. $\\left. X_1 \\right|_q \\dots \\left. X_k \\right|_q$ is basis for $D_q$ $\\forall \\, q \\in U$\n\n\\subsubsection*{Integral Manifolds and Involutivity}\n\nSuppose smooth distribution $D \\subseteq TM$ \\\\\n\\textbf{integral manifold of $D$} : immersed submanifold $N \\neq \\emptyset$, $N \\subseteq M$ if $T_pN = D_p$ $\\forall \\, p \\in N$\n\n\\textbf{Example 19.1 (Distributions and Integral Manifolds)}\n\n\\begin{enumerate}\n\\item[(a)] \n\\item[(b)]\n\\item[(c)]\n\\item[(d)]\n\\end{enumerate}\n\n$D$ \\textbf{involutive} if $\\forall \\, $ pair of smooth local sections of $D$ (i.e. smooth vector fields $X,Y$ defined on open subset of $M$ s.t. $X_p, Y_p \\in D_p$ \\, $\\forall \\, p$) \\\\\n\n\\textbf{integrable} : smooth distribution $D$ on $M$ integrable if $\\forall \\, p \\in M$, $p$ in integral manifold of $D$, i.e. \\\\\n\\phantom{\\quad \\quad \\, } $T_p M = D_p$\n\n\\begin{proposition}[19.3] $\\forall \\, $ integrable distribution is involutive. \\end{proposition}\n\n\\begin{proof} Let $D \\subseteq TM$ is integrable distribution. \\\\\nsuppose smooth local sections of $D$, $X,Y$ on some open $U\\subseteq M$. \\\\\n$\\forall \\, p \\in U$, let $N$ integral manifold of $D$, $N \\ni p$ \\\\\n$X,Y$ sections of $D$, so $X,Y$ tangent to $N$ \\\\\nBy Corollary 8.32, $[X,Y]$ also tangent to $N$, so $[X,Y]_p \\in D_p$\n\\end{proof}\n\n\n\n\\subsubsection*{Involutivity and Differential Forms}\n\n\\begin{lemma}[19.5] (\\textbf{1-form Criterion for Smooth Distributions}) Suppose smooth $n$-dim. manifold $M$, distribution $D \\subseteq TM$, rank $k$  \\\\ \n$D$ smooth iff $\\forall \\, p \\in M$, $\\exists \\, $ neighborhood $U$ on which $\\exists \\, $ smooth 1-forms $\\omega^1 \\dots \\omega^{n-k}$ s.t. $\\forall \\, q \\in U$, \n\\begin{equation}\n  D_q = \\text{ker} \\left. \\omega^1 \\right|_q \\bigcap \\dots \\bigcap \\left. \\text{ker} \\omega^{n-k} \\right|_q  \\quad \\quad \\quad \\, (19.1)\n\\end{equation}\n\\end{lemma}\n \\begin{proof}\nBy Prop. 10.15, complete forms $\\omega^1 \\dots \\omega^{n-k}$ to smooth coframe $(\\omega^1 \\dots \\omega^n)$ \\quad \\, $\\forall \\, p$ \\\\\nif $(E_1 \\dots E_n)$ dual frame, easy to sheet that $D$ locally spanned by $E_{n-k+1 }, \\dots , E_n$, so smooth by local frame criterion.  \n\nConverse, suppose $D$ smooth. \\\\\n$\\forall \\, $ open $U \\ni p \\in M$, $\\exists \\, $ smooth vector fields $Y_1 \\dots Y_k$ spanning $D$. \\\\\nBy Prop. 16.5, complete $Y_1 \\dots Y_k$ to smooth local frame $(Y_1 \\dots Y_n)$ for $M$ in open $U\\ni p$ \\\\\nwith dual coframe $(\\epsilon^1 \\dots \\epsilon^n)$, it follows easily that $D$ characterized locally by $D_q = \\text{ker} \\left. \\epsilon^{k+1} \\right|_q \\bigcap \\dots \\bigcap \\text{ker} \\left. \\epsilon^n \\right|_q$ \n\n\\end{proof}\n\n\nif $D$ rank-$k$ distribution on smooth $n$-manifold $M$, any \\\\\n\\phantom{if $D$ } $n-k$ linearly independent 1-forms $\\omega^1 \\dots \\omega^{n-k}$ on open $U\\subseteq M$ s.t. (19.1) \n\\[\nD_q = \\left. \\text{ker}\\omega^1 \\right|_q \\bigcap \\dots \\bigcap \\left. \\text{ker}\\omega^{n-k} \\right|_q = \\lbrace X | X=X^iX_i, \\, i =1 \\dots k, \\, \\omega^1(X) = 0\\rbrace \\bigcap \\dots \\bigcap \\lbrace X | \\omega^{n-k}(X) = 0\\rbrace\n\\]\n$\\forall \\, q \\in U$ are \\textbf{local defining forms} for $D$\n\n\n\n\\begin{proposition}[19.8] \\textbf{(Local Coframe Criterion for Involutivity)}\n  Let $D$ smooth distribution of rank $k$ on smooth $n$-manifold $M$ \\\\\nlet $\\omega^1 \\dots \\omega^{n-k}$ smooth defining forms for $D$ on open $U \\subseteq M$. \n\nThe following are equivalent:\n\\begin{enumerate}\n\\item[(a)] $D$ is involutive on $U$ \n\\item[(b)] $d\\omega^1 \\dots d\\omega^{n-k}$ annihilate $D$\n\\item[(c)] $\\exists \\, $ smooth 1-forms $\\lbrace \\alpha^i_j | i, j =1 \\dots n-k \\rbrace$ s.t. \n\\[\nd\\omega^i = \\sum_{j=1}^{n-k} \\omega^j \\wedge \\alpha^i_j \\quad \\quad \\, \\forall \\, i = 1 \\dots n-k\n\\]\n\\end{enumerate}\n\\end{proposition}\n\n\\exercisehead{19.9} Prove the preceding proposition, 19.8.  \n\n\\begin{proof}\n(a) $\\Longrightarrow$ (b) \n\nOn open $U\\subseteq M$, $\\forall \\, q \\in U$, $\\omega^i$ smooth defining form for $D$, $i=1\\dots k$, and $\\omega^i(X) = 0$ \\, $\\forall \\, X \\in D_q$  \\\\\n\\phantom{ On open } Then $d\\omega^i$ also annihilates $D$ on $U$ (Thm. 19.7 1-form Criterion for Involutivity (19.3) ) \\\\\n$d\\omega^1 \\dots d\\omega^{n-k}$ annihilate $D$\n\n(b) $\\Longrightarrow $ (c)\n\n$d\\omega^i \\in \\Omega^2_q(M)$, $\\forall \\, q \\in U$ \\\\\nBy Lemma 19.6, smooth $p$-form $\\eta$ on $U$ annihilates $D$ iff $\\eta$ ofform $\\eta = \\sum_{i=1}^{n-k} \\omega^i\\wedge \\beta^i$, for $(p-1)$ forms $\\beta^1 \\dots \\beta^{n-k}$ on $U$ \\\\\n$d\\omega^i$ annihilates $D$ \\\\\n\\phantom{\\quad \\, } $\\Longrightarrow d\\omega^i = \\sum_{j=1}^{n-k} \\omega^j \\wedge \\beta_j^i \\quad \\quad \\, \\beta^i_{ \\, j} $ smooth 1-forms on $U$, $i,j=1\\dots n-k$\n\n(c) $\\Longrightarrow $ (a) \n\nUse Thm. 19.7 Proof\n\\[\n\\omega^i([X,Y]) = X(\\omega^i(Y)) - Y(\\omega^i(X)) - d\\omega^i(X,Y)  = 0 -0 - d\\omega^i(X,Y)\n\\]\n\\[\nd\\omega^i(X,Y) - \\sum_{j=1}^{n-k} \\omega^j \\wedge \\alpha^i_{ \\, j}(X,Y) = \\sum_{j=1}^{n-k} \\omega^j(X) \\alpha^i_{ \\, j }(Y) - \\alpha^i_{ \\, j}\\omega^j(Y) = 0 - 0 = 0 \n\\]\nwhere I used this local formula:\n\\[\n(\\alpha \\wedge \\beta)_p(v,w) = \\alpha_p(v) \\beta_p(w) - \\alpha_p(w) \\beta_p(v)\n\\]\n$\\omega^i([X,Y]) = 0$ so $[X,Y] \\in \\text{ker}\\omega^i$ \\quad \\, $\\forall \\, i = 1 \\dots n-k$\n\n\\end{proof}\n\n\n\n\\subsection*{Problems}\n\n\\problemhead{19-3}\n\nLet $\\omega \\in \\Omega^1(M)$ \\\\\nintegrating factor $\\mu $ for $\\omega \\equiv \\mu \\in C^{\\infty}(M)$, $\\mu > 0$, and $\\mu \\omega $ exact on $U$, i.e. $\\mu \\omega = df$, for some $f \\in \\mathcal{C}^{\\infty}(M)$\n\n\\begin{enumerate}\n\\item[(a)] If $\\omega \\neq 0$ on $U$, \\\\\nSuppose $\\omega$ admits an integrating factor $\\mu$.  \n\n\\[\nd\\omega \\wedge \\omega = d\\left( \\frac{df}{\\mu} \\right) \\wedge \\frac{df}{\\mu} = \\left( \\frac{d^2 f}{ \\mu} + -\\frac{df}{\\mu^2} \\frac{ \\partial \\mu }{ \\partial x^i } dx^i \\wedge df \\right) \\wedge \\frac{df}{\\mu} = 0 \n\\]\nas $d^2f =0$ and $df\\wedge df =0$\n\nIf $d\\omega \\wedge \\omega =0$, consider $\\mu \\in \\mathcal{C}^{\\infty}(M)$ s.t. $\\mu >0$ (i.e. positive) on open $U\\subseteq M$ (build it up with partitions of unity if need to).  \n\nNow, using the formula for exterior differentiation, \n\\[\nd(\\mu \\omega) = d\\mu \\wedge \\omega + (-1)^0 \\mu d\\omega \n\\]\nso that \n\\[\nd (\\mu \\omega) \\wedge \\omega = d\\mu \\wedge \\omega \\wedge \\omega + \\mu d\\omega \\wedge \\omega = 0 + \\mu d\\omega \\wedge \\omega = 0 + 0 = 0 \n\\]\n\n$\\omega$ nonzero, so $d(\\mu \\omega) =0$.  EY : 20150221 I'm not sure about this statement. Surely, locally,\n\n\\[\nd(\\mu \\omega) \\wedge \\omega = \\frac{1}{2} ( d(\\mu \\omega) )_{ij} \\omega_k dx^i \\wedge dx^j \\wedge dx^k = d(\\mu \\omega)_{ \\underline{I}} \\omega_k dx^{\\underline{I}} \\wedge dx^k\n\\]\nwith $\\underline{I} = (i_1,i_2)$ and $i_1 < i_2$.  \n\nBy considering every $k \\neq \\underline{I}$, then I think one can conclude, component by component, that $d(\\mu \\omega) =0$. \n\nThen, consider a compact submanifold $B$, $\\text{dim}{B} =3$ that is a submersion of $U$.  Then use Stoke's theorem in the following:\n\n\\[\n\\int_B d(\\mu \\omega) = \\int_{\\partial B} \\mu \\omega = 0 \\Longrightarrow \\mu \\omega = df\n\\]\n\nSo \n\\[\n\\boxed{ \\begin{gathered} \\text{ If } \\omega \\neq 0 \\text{ on } U \\\\\n    \\omega \\text{ admits an integrating factor $\\mu$ } \\text{ iff } d\\omega \\wedge \\omega  =0  \\end{gathered} }\n\\]\n\nEY 20150221 : I didn't use Frobenius' theorem for the converse.  Should I have?\n\\item[(b)] If $\\text{dim}{M}=2$, $d\\omega \\wedge \\omega =0$ (immediately) \\\\\nThen $\\omega $ admits an integrating factor by the above solution.\n\\end{enumerate}\n", "meta": {"hexsha": "567af46d98cfd842f617558a655e899ed6bba31a", "size": 9603, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "LeeJM/19DistributionsaFoliations.tex", "max_stars_repo_name": "wacfeldwang333/mathphysics", "max_stars_repo_head_hexsha": "59eb794dfa46e2b80e43df0440bb8ec3c472d973", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50, "max_stars_repo_stars_event_min_datetime": "2017-01-10T14:24:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:19:23.000Z", "max_issues_repo_path": "LeeJM/19DistributionsaFoliations.tex", "max_issues_repo_name": "wacfeldwang333/mathphysics", "max_issues_repo_head_hexsha": "59eb794dfa46e2b80e43df0440bb8ec3c472d973", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2017-09-29T09:29:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T03:12:29.000Z", "max_forks_repo_path": "LeeJM/19DistributionsaFoliations.tex", "max_forks_repo_name": "wacfeldwang333/mathphysics", "max_forks_repo_head_hexsha": "59eb794dfa46e2b80e43df0440bb8ec3c472d973", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25, "max_forks_repo_forks_event_min_datetime": "2018-01-21T05:33:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T20:15:13.000Z", "avg_line_length": 50.5421052632, "max_line_length": 300, "alphanum_fraction": 0.585129647, "num_tokens": 3259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.34455971863092255}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n% \\section*{Wed Nov 06 2019}\n\n\\subsection{Non-isothermal winds}\n\nNow, we consider the possibility that our winds are \\emph{not isothermal}.\nThis will change the structure of the wind, by the introduction of an additional pressure gradient.\n\nIt will change the speed of sound and thus the Mach number.\n\nIt is useful to define the energy per unit mass \\(e\\): \n%\n\\begin{align}\n  e(r) = \\frac{v^2(r)}{2} - \\frac{GM}{r} + \\frac{\\gamma }{\\gamma -1} \\frac{ \\mathcal{R} T}{\\mu }\n\\,,\n\\end{align}\n%\nwhere \\(\\gamma / (\\gamma -1) = 5/2\\) for a monoatomic gas, which has \\(\\gamma = 3/2\\).\n\nIn the lower boundary of the wind the velocity is much less than the escape velocity (\\(v \\ll v _{\\text{esc}}\\)), and also the thermal velocity of the particles is not enough for them to escape the gravitational well: \\(\\mathcal{R} T / \\mu \\ll v _{\\text{esc}}\\) at the surface of the star, while far from the star we have \\(v \\gg v _{\\text{esc}}\\).\n\nIf we have an isothemal wind, some energy must be added in order to prevent the adiabatic cooling of the gas, lift it from the potential well, and to increase its kinetic energy.\n\nIf a force is applied it increases the momentum, but the heat transmission \\(q\\) also appears in the momentum equation, which is \\(\\Delta e = \\int f + q \\dd{r} \\).\nHeat transmission changes the pressure profile, which affects the momentum, even though \\(q\\) does not appear explicitly in the momentum equation.\n\nWe define the total heat deposition \\(Q\\) and the total work done by the force \\(W\\):\n%\n\\begin{align}\nQ(r) = \\int_{r_0 }^{r} q(\\widetilde{r}) \\dd{\\widetilde{r}}\n\\qquad \\text{and} \\qquad\nW(r) = \\int_{r_0 }^{r} f(\\widetilde{r}) \\dd{\\widetilde{r}}\n\\,,\n\\end{align}\n%\nand we will have \\(e( \\infty ) - e(r_0 ) = Q( \\infty ) + W( \\infty )\\). \n\nThe most general momentum equation is given by: \n%\n\\begin{align}\n  \\frac{1}{v} \\dv{v}{r} = \\qty(2 \\frac{c_s^2}{r} - \\frac{GM}{r^2} + f -(\\gamma - 1) q) / \\qty(v^2- c_s^2)\n\\,,\n\\end{align}\n%\nwhere we introduce the adiabatic speed of sound \\(c_s = \\sqrt{\\gamma a^2} \\), \\(a\\) being the \\emph{isothermal} speed of sound.\nIn general \\(- (\\gamma - 1)<0\\), therefore if we add heat this is equivalent to pushing \\emph{inward}.\n\nIf either \\(f\\) or \\(q\\) depend on the velocity gradient \\(\\dv*{v}{r}\\) then the sonic point can \\emph{decouple} from the critical point.\n\nThere are cases in which we have multiple critical points (specifically, multiple zeros of the denominator).\n\nThe momentum equation plus the energy equation \n%\n\\begin{align}\n  \\dv{}{r} \\qty(\\frac{v^2}{2} + \\frac{5}{2} \\frac{RT}{\\mu } - \\frac{GM}{r}) = f(r) + q(r)\n\\,,\n\\end{align}\n%\ncan be solved numerically, and if we impose smooth passage through the critical point this yields the mass loss rate.\n\nQualitatively, the results are the same as in the isothermal case.\nAdding either momentum or energy to the subsonic region of the wind increases the bottom-of-the-corona velocity and the mass loss rate. Doing it in the supersonic region has no effect.\n\nThis ends our general introduction to stellar winds.\n\n\\subsection{Exercises}\n\nNow we will do a couple of exercises to get familiar with the theory. \n\n\\begin{greenbox} \\textbf{Exercise}\n\nThe wind is isothermal.\nThe solar wind has a mean coronal temperature of \\SI{1.5e6}{K} and a mass loss rate of \\num{2e-14} solar masses per year.\nThe bottom of the corona is at \\(r_0 \\approx 1.003 R_{\\odot}\\), where the density is \\(\\rho (r_0 ) = \\SI{e-14}{g\\per\\centi\\metre\\cubed}\\).\n\nCalculate the potential energy, the kinetic energy and the enthalpy of the gas at \\(r_0 \\).\n\nCalculate the same quantities at the critical point. Which of these energies has absorbed the largest fraction of the energy input?\n\\end{greenbox}\n\n\\begin{bluebox}\nWe can use the continuity equation \\(\\dot{M} = 4 \\pi \\rho_0 r_0^2 v_0 \\) to get \n%\n\\begin{align}\n  v_0 = \\frac{\\dot{M}}{4 \\pi r_0^2 \\rho_0 }\n  \\approx \\SI{21}{m/s}\n\\,,\n\\end{align}\n%\nand with this we can calculate \n%\n\\begin{align}\n  e(r_0 ) = - \\frac{GM}{r_0 } + \\frac{1}{2} v_0^2 + \\frac{5}{2} \\frac{RT}{\\mu }\n\\,.\n\\end{align}\n\nWe get: \n%\n\\begin{align}\n  E _{\\text{kin, 0}} = \\frac{v_0^2}{2} \\approx \\SI{212}{J/kg}\n\\,,\n\\end{align}\n%\nwhile for the gravitational energy we'd need the mass of the star. Assuming it is equal to the solar mass, we find \n%\n\\begin{align}\n  E _{\\text{grav, 0}} = -\\frac{GM}{r_0 } \\approx \\SI{-1.9e11}{J/kg}\n\\,.\n\\end{align}\n%\n\nThe mean molecular weight of the gas for the Sun is something like \\(\\mu = 0.62\\) (we count electrons in it).\nThen we get \n%\n\\begin{align}\n  E _{\\text{chem, 0}} = E _{\\text{\\text{chem, crit}}} = \\frac{5}{2} \\frac{RT}{\\mu } \\approx \\SI{5.0e7}{J/kg}  \n\\,.\n\\end{align}\n%\n\nThe enthalpy is the same everywhere in the flow, since the flow is isothermal.\n\nThe values at the critical radius are calculated with the same formula. The velocity will be the speed of sound \\(a = \\sqrt{RT / \\mu } \\approx \\SI{4.5e3}{m/s} \\).\n\nThen we find: \n%\n\\begin{align}\n  E _{\\text{kin, crit}} = \\frac{a^2}{2} \\approx \\SI{1.0e7}{J/kg} \\approx \\num{5e4} \\times E _{\\text{kin, 0}} \n\\,.\n\\end{align}\n%\n\nThe critical radius is given by \\(r_c = GM / (2 a^2)\\): so, we get \n%\n\\begin{align}\n  E _{\\text{grav, crit}} = - \\frac{GM}{r_{c}} = -2 a^2 \\approx - \\SI{4.0e7}{J/kg} \\approx \\num{2.1e-4} \\times E _{\\text{grav, 0}}\n\\,.\n\\end{align}\n%\n\nQualitatively, at the corona we have \n%\n\\begin{align}\n   \\abs{ E _{\\text{grav, 0}}} \\gg E _{\\text{chem, 0}} \\gg E _{\\text{kin, 0}}\n\\,,\n\\end{align}\n%\nwhile at the critical point they are similar, and specifically \n%\n\\begin{align}\n  E _{\\text{chem, crit}} \\gtrsim \\abs{E _{\\text{grav, crit}}} \\gtrsim E _{\\text{kin, crit}}\n\\,.\n\\end{align}\n%\n\n\\end{bluebox}\n\n\\begin{greenbox}\n    \\textbf{Exercise}\n\n  A star with \\(T _{\\text{eff}} = \\SI{3200}{K}\\), \\(R_{*} = 30 R_{\\odot}\\), \\(L_{*} = 85 L_{\\odot}\\) and \\(M_{*} = 6 M_{\\odot}\\) has an isothermal corona of \\(T = \\SI{e6}{K}\\) with a density at the lower boundary of \\SI{e-13}{g \\per\\centi\\metre\\cubed}.\n\n  Calculate the energy per unit mass at the bottom of the corona at \\(r_0 = R_{*}\\).\n\n  Calculate the location of the critical point, \\(r_c\\), and the mass loss rate.\n\n  Calculate the energy per gram gained by the wind between \\(r_0 \\) and \\(r\\). What fraction of the stellar luminosity is used to drive the wind up to the critical point?\n\\end{greenbox}\n\n\\begin{bluebox}\n  The energy per unit mass at the bottom of the corona is given by \n  %\n  \\begin{align}\n    e(r_0 ) = - \\frac{GM}{r_0 } + \\frac{1}{2} v_0^2 + \\frac{5}{2} \\frac{RT}{\\mu }\n  \\,,\n  \\end{align}\n\n  where we have everything but \\(v_0 \\): we can calculate it by imposing that the solution passes through the critical point, the formula we found for it is \n  %\n  \\begin{align}\n  v_0 = a \\qty(\\frac{r_c}{r_0 })^2 \\exp(- 2 \\frac{r_c}{r_0 } + \\frac{3}{2}) \\approx \\SI{61}{km/s}\n  \\,.\n  \\end{align}\n  %\n  \n  Using this figure, we can find \n  %\n  \\begin{align}\n  e(r_0 ) &\\approx \\SI{-2.76e9}{m^2/s^2}  \\\\ \n  e(r_c ) &\\approx \\SI{1.34e10}{m^2/s^2}\n  \\,,\n  \\end{align}\n  %\n  where we assumed \\(\\mu = \\num{.62}\\) since the matter is ionized, and computed the energy density for both the bottom of the corona and the critical point \\(r_c = GM/2a^2 \\approx \\SI{2.97e10}{m} \\approx 1.4 R_{*}\\).\n\n  The isothermal speed of sound is given by \\(a = \\sqrt{RT/\\mu } \\approx \\SI{116}{km/s}\\). \n\n  The mass loss rate can be computed at the bottom of the corona: it is given by \n  %\n  \\begin{align}\n  \\dot{M} = 4 \\pi r_0 ^2 v_0 \\rho_0 \\approx \\SI{3.34e16}{kg/s}\n  \\,,\n  \\end{align}\n  %\n  therefore we can compute the power needed to accelerate the wind: \n  %\n  \\begin{align}\n  P = \\dot{M} \\qty(e(r_c) - e(r_0 )) \\approx \\SI{5.40e26}{J/s} \\approx \\SI{1.66}{\\percent} L_{*}\n  \\,,\n  \\end{align}\n  %\n  \n  %\n% but we cannot use this formula since we do not have \\(v_0 \\) nor \\(\\dot{M}\\). However, we can approximate the density profile as an exponential, applying the formula \n% %\n% \\begin{subequations}\n% \\begin{align}\n%   \\dot{M} &= 4 \\pi r_c^2 a \\rho_{c}  \\\\\n%   &= 4 \\pi r_c^2 a \\rho_0 \\exp(- \\frac{r_c - r_0 }{H_0 } \\frac{r_0 }{r_c})  \n% \\,,\n% \\end{align}\n% \\end{subequations}\n% %\n% where we have: the length scale \\(H_0 = RT r_0^2 / (GM \\mu )\\), the critical velocity \\(a = \\sqrt{RT/\\mu }\\), and the critical radius \\(r_c = GM/(2a^2)\\).\n\n% Plugging these in, we find: \n% %\n% \\begin{subequations}\n% \\begin{align}\n%   \\dot{M} &= 4 \\pi \\qty(\\frac{GM \\mu }{2 RT})^2 \\sqrt{\\frac{RT}{\\mu }} \\rho_0 \n%   \\exp(\\frac{\\mu GM}{RT} \\qty(\\frac{2RT}{GM \\mu } - \\frac{1}{r_0 }))  \\\\\n%   &= \\pi (GM)^2 \\qty(\\frac{\\mu }{RT})^{3/2} \\rho_0 \n%   \\exp(2 - \\frac{\\mu GM}{RT r_0 })\n% \\,.\n% \\end{align}\n% \\end{subequations}\n% %\n% \\todo[inline]{One temperature should probably be the effective temperature, but I do not really know what that means. }\n\n% Then, the mass loss rate can be calculated, since we have all of these quantities. It comes out to be barely anything, since \\(\\mu GM / RT r_0 \\) is very large and we have a negative exponential of it\\dots\n\n\\end{bluebox}\n\n% Lamers-Cassinelli: chap 4, section 3: multiple critical points.\n\n% Next Tuesday, the 12th, after the lecture, we will likely move to the DFA in Via Marzolo until 14.30.\n\n\\section{Wind types}\n\n\\paragraph{Coronal winds}\nThese are driven by gas pressure due to high temperature.\nStars with a convection zone right under the photosphere can have coronas of a few million Kelvin degrees. \nThese are rather well described as isothermal, however the temperature decreases slowly because of conduction.\n\n\\paragraph{Dust driven winds}\nFor these winds, the driving mechanism is the radiation pressure on the dust grains, which are continuum absorbers. The gas component is dragged along by momentum transfer. \nThis happens for cool stars, whose envelopes have temperatures of less than a thousand degrees Kelvin, in which the dust grains can actually be formed. \nThese can be well modelled as winds with a force like \\(f = [r \\geq r_d] A / r^2\\), where the radius \\(r_d\\) is the one after which the temperature is low enough for the grains to form.\n\n\\paragraph{Line-driven winds}\nThese are winds of hot stars, driven by radiation pressure on spectral lines of abundant ions which have many in the UV and far UV.\nThe pressure depends on the Doppler effect: the ions can absorb different wavelengths of light at different radii because of it.\nThe force depends on the velocity gradient: it cannot be modelled with what we discussed so far.\n\n\\paragraph{Pulsation driven winds}\nStars such as Miras and those in the Asymptotic Giant Branch may pulsate: the atmosphere is tossed up and then falls back. Because of the low gravity, they fall slowly and are hit by an outmoving layer before they have completed their fall. \nThis means that for each pulsation cycle they get a ``kick''.  \n\nThis can be a very efficient driving method if we account for dust formation. The shockfront from the pulsation cycle basically travels outwards to infinity.\n\n\\paragraph{Sound wave driven winds}\nThey are modelled in a way that is similar to coronal winds. \nThe resulting amplitudes are usually small. \n\n\\paragraph{Alfvén Wave Driven winds}\nDue to magnetic fields: if the points at which the field lines make contact with the surface move, than a magnetic wave travels forward with a speed \\(v_A = B / \\sqrt{4 \\pi \\rho } \\gg a\\). \nThis can be very efficient, and result in high wind speeds. \nIt is relevant for stars which do not have strong radiation pressure (ie not more than a thousand times more luminous than the Sun). \n\n\\paragraph{Magnetic rotating winds}\nMaterial is ``flung out'' moving along magnetic field lines. \nThe terminal velocity is heavily dependent on the strength of the field.\n\n\\section{Line driven winds}\n\nNow, we introduce the next topic.\nWe deal with hot, luminous stars: at the top left of the HR diagram.\n\n[Picture from the slides]\n\nWe talk of line-driven winds for hot stars.\nThese are winds driven by \\emph{spectral lines}. \nThe blackbody emission for these stars is mainly at high frequencies, like the UV.\n\nOne may ask: hydrogen is much more abundant than heavier elements like carbon, nitrogen\\dots why do we see the spectral lines for these heavier elements?\n\nThis is because hydrogen is completely ionized at these temperatures, and helium is also.\n\nThe strongest lines are far in the UV, where the stellar flux is low: only few atoms are hit, the rest of the gas is dragged along.\n\nA peculiar characteristic of the spectrum is the so-called P-Cygni profile.\n\nNow, an overview of the formation of spectral lines:\nthere are 5 processes \\begin{enumerate}\n    \\item Line scattering: if it comes from the ground state of the atom, it is called \\emph{resonance scattering}, which is the main phenomenon.\n    \\item Emission by recombination: the ion recombines to an excited state.\n    \\item Emissional from collisional or photo-excitation. A photon is absorbed, it excites the atom which then descends to a lower energy level.\n    \\item Pure absorption and then de-excitation of an already excited atom.\n    \\item Masering by stimulated emission: it can happen in a very narrow set of circumstances: an excited atom is hit by a photon which has exactly the same energy as the one between the atom's state and the ground state, so the atom is deexcited and now there are two photons.\n    This happens when there are many excited atoms, and when the velocity gradient is very small --- otherwise, the photons are Doppler-shifted out of the right frequency.\n\\end{enumerate}\n\n\n\\end{document}", "meta": {"hexsha": "da193ab535cda447608790147b6cc5317d5ac4c3", "size": 13442, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ap_first_semester/advanced_astrophysics/06nov.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "ap_first_semester/advanced_astrophysics/06nov.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ap_first_semester/advanced_astrophysics/06nov.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 42.5379746835, "max_line_length": 348, "alphanum_fraction": 0.6961017706, "num_tokens": 4130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.34455971010999603}}
{"text": "\\documentclass{article}\n\n\\usepackage{luatexja}\n\n\\usepackage{url}\n\\usepackage{amssymb,amsmath,stmaryrd,bcprules,xspace}\n\\usepackage{etoolbox,xcolor,here}\n\n\\usepackage[top=0pt,bottom=0pt,left=2cm,right=2cm]{geometry}\n\n\\input{macro.tex}\n\n\\author{nymphium}\n\\title{\\lambdaeff}\n\n\\begin{document}\n\\thispagestyle{empty}\n\\maketitle\n\n\\section*{Syntax}\n\\begin{figure}[ht]\n    \\[\n        \\begin{array}{rrl}\n            x & \\in & \\variable{Variables}\\\\\n            \\variable{eff} & \\in & \\variable{Effects}\\\\\n              &&\\\\\n            v & ::= & x \\mid h \\mid \\lambda x. e \\mid \\variable{eff}\\\\\n            e & ::= & v \\mid e\\ e \\mid \\letT{x}{e}{e}\\\\\n              &\\mid & \\instT \\mid \\withhandle{v\\ }{e} \\\\\n              &\\mid & \\perform{\\variable{e\\ }{e}}\\\\\n            h & ::= & \\handlerK v\\ \\left(\\keyword{val} x \\rightarrow e\\right) \\left(\\left(x, k\\right)\\rightarrow e\\right)\\\\\n              &&\\\\\n            F & ::= & e\\ \\square \\mid \\square\\ v \\mid \\letT{x}{\\square}{e} \\\\\n              &\\mid & \\withhandle{v\\ }{\\square} \\mid \\perform{\\square\\ }{e} \\mid \\perform{\\variable{v\\ }}{\\square}\\\\\n            s &::= & \\left[\\right] \\mid F :: s\n        \\end{array}\n    \\]\n    \\caption{the syntax of \\lambdaeff}\n    \\label{fig:lambdaeff}\n\\end{figure}\n\n\\section*{Semantics}\n\\newcommand{\\flatfn}[1]{%\n  \\variable{flatfn}\\ #1\n}\n\n\\begin{figure}[ht]\n    \\begin{flalign*}\n        \\flatfn{\\left[\\right]} &= \\lambda x. x\\\\\n        \\flatfn{\\B{F :: s}} &= \\lambda x. \\flatfn{s}\\ \\B{F\\left[x\\right]}\n    \\end{flalign*}\n\n    \\caption{utility function \\variable{flatfn}}\n\\end{figure}\n\n\\begin{figure}[ht]\n    \\newcommand{\\defspace}{\\vskip.5\\baselineskip}\n\n    \\centering\n\n    \\infax[Push]{\\model{F\\left[e\\right]}{s}{es} \\mapsto \\model{e}{F :: s}{es}}%\n    \\defspace\n\n    \\infax[Pop]{\\model{v}{F :: s}{es} \\mapsto \\model{F\\left[v\\right]}{s}{es}}%\n    \\defspace\n\n    \\infax[Result]{\\model{v}{[]}{es} \\mapsto \\model{v}{[]}{es}}%\n    \\defspace\n\n    \\infax[Apply]{\\model{\\lambda x. e}{\\left(\\square\\ v\\right) :: s}{es} \\mapsto \\model{e\\left[x = v\\right]}{s}{es}}%\n    \\defspace\n\n    \\infax[Instanciate]{\\model{\\instT}{s}{es} \\mapsto \\model{\\variable{eff}}{s}{es}}%\n    \\defspace\n\n    \\infax[Rethrow]{%\n        \\model{\\perform{\\variable{eff}}{v}}{F :: s}{es}%\n        \\mapsto%\n        \\model{\\perform{\\variable{eff}{v}}}{s}{F :: es}}%\n    \\defspace\n\n    \\infax[Handle\\textsubscript{eff}]{%\n      \\begin{array}{l}\n          \\model{\\perform{\\variable{eff}}{v}}{F :: s}{es}%\n            \\mapsto%\n            \\model{e_\\variable{eff}\\left[x = v, k = \\flatfn{es}\\right]}{F :: s}{\\left[\\right]}\\\\%\n          \\begin{array}{ll}\n            \\mathrm{where} & F = \\withhandle{h\\ }{\\square} \\\\\n                           & h = \\handlerK \\variable{eff} \\left(\\valK x \\rightarrow e_v\\right) \\left(\\left(x, k\\right) \\rightarrow e_\\variable{eff}\\right)\n          \\end{array}\n      \\end{array}}%\n    \\defspace\n\n    \\infax[Handle\\textsubscript{v}]{%\n      \\model{v}{F :: s}{es}%\n      \\mapsto%\n      \\model{e_v[x = v]}{s}{es}\\\\\n      \\begin{array}{ll}\n        \\mathrm{where} & F = \\withhandle{h\\ }{\\square} \\\\\n                       & h = \\handlerK \\variable{eff} \\left(\\valK x \\rightarrow e_v\\right) \\left(\\left(x, k\\right) \\rightarrow e_\\variable{eff}\\right)\n      \\end{array}\n    }\n    \\defspace\n\n    \\infax[Leak]{%\n        \\model{\\perform{\\variable{eff}}{v}}{\\left[\\right]}{es}%\n        \\mapsto%\n        \\textsl{abort}}%\n\\caption{the semantics of \\lambdaeff}\n\\end{figure}\n\\end{document}\n", "meta": {"hexsha": "91ec848ea503e5fcd4c501b8eff9677f939f1e88", "size": 3442, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "text/main.tex", "max_stars_repo_name": "Nymphium/lambdaeff", "max_stars_repo_head_hexsha": "afaa9736c6151a969884c3bc413c0b5f03e3ff57", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-01T11:26:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-01T11:26:04.000Z", "max_issues_repo_path": "text/main.tex", "max_issues_repo_name": "Nymphium/lambdaeff", "max_issues_repo_head_hexsha": "afaa9736c6151a969884c3bc413c0b5f03e3ff57", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "text/main.tex", "max_forks_repo_name": "Nymphium/lambdaeff", "max_forks_repo_head_hexsha": "afaa9736c6151a969884c3bc413c0b5f03e3ff57", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7321428571, "max_line_length": 154, "alphanum_fraction": 0.5435793144, "num_tokens": 1214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.34455971010999603}}
{"text": "\\documentclass[12pt,preprint]{aastex}\n\n\\pdfoutput=1\n\n\\usepackage{color,hyperref}\n\\definecolor{linkcolor}{rgb}{0,0,0.5}\n\\hypersetup{colorlinks=true,linkcolor=linkcolor,citecolor=linkcolor,\n            filecolor=linkcolor,urlcolor=linkcolor}\n\\usepackage{url}\n\\usepackage{amssymb,amsmath}\n\\usepackage{subfigure}\n\\usepackage{booktabs}\n\n\\usepackage{natbib}\n\\bibliographystyle{apj}\n\n\n\\newcommand{\\project}[1]{\\textsl{#1}}\n\\newcommand{\\kepler}{\\project{Kepler}}\n\\newcommand{\\terra}{\\project{TERRA}}\n\\newcommand{\\license}{MIT License}\n\n\\newcommand{\\paper}{\\textsl{Article}}\n\n\\newcommand{\\foreign}[1]{\\emph{#1}}\n\\newcommand{\\etal}{\\foreign{et\\,al.}}\n\\newcommand{\\etc}{\\foreign{etc.}}\n\\newcommand{\\True}{\\foreign{True}}\n\\newcommand{\\Truth}{\\foreign{Truth}}\n\n\\newcommand{\\figref}[1]{\\ref{fig:#1}}\n\\newcommand{\\Fig}[1]{\\figurename~\\figref{#1}}\n\\newcommand{\\fig}[1]{\\Fig{#1}}\n\\newcommand{\\figlabel}[1]{\\label{fig:#1}}\n\\newcommand{\\Tab}[1]{Table~\\ref{tab:#1}}\n\\newcommand{\\tab}[1]{\\Tab{#1}}\n\\newcommand{\\tablabel}[1]{\\label{tab:#1}}\n\\newcommand{\\Eq}[1]{Equation~(\\ref{eq:#1})}\n\\newcommand{\\eq}[1]{\\Eq{#1}}\n\\newcommand{\\eqalt}[1]{Equation~\\ref{eq:#1}}\n\\newcommand{\\eqlabel}[1]{\\label{eq:#1}}\n\\newcommand{\\sectionname}{Section}\n\\newcommand{\\Sect}[1]{\\sectionname~\\ref{sect:#1}}\n\\newcommand{\\sect}[1]{\\Sect{#1}}\n\\newcommand{\\sectalt}[1]{\\ref{sect:#1}}\n\\newcommand{\\App}[1]{Appendix~\\ref{sect:#1}}\n\\newcommand{\\app}[1]{\\App{#1}}\n\\newcommand{\\sectlabel}[1]{\\label{sect:#1}}\n\n\\newcommand{\\dd}{\\ensuremath{\\,\\mathrm{d}}}\n\\newcommand{\\bvec}[1]{\\ensuremath{\\boldsymbol{#1}}}\n\\newcommand{\\densityunit}{{\\ensuremath{\\mathrm{nat}^{-2}}}}\n\n% TO DOS\n\\newcommand{\\todo}[3]{{\\color{#2} \\emph{#1} TODO: #3}}\n\\newcommand{\\dfmtodo}[1]{\\todo{DFM}{red}{#1}}\n\\newcommand{\\hoggtodo}[1]{\\todo{HOGG}{blue}{#1}}\n\n% Response to referee\n\\definecolor{mygreen}{rgb}{0, 0.50196, 0}\n\\newcommand{\\response}[1]{#1}\n% \\newcommand{\\response}[1]{{\\color{mygreen} {\\bf #1}}}\n\n% Document specific variables.\n\\newcommand{\\rate}{\\ensuremath{\\lambda}}\n\\newcommand{\\intrate}{\\ensuremath{\\Lambda}}\n\n\\begin{document}\n\n\\title{%\n    Note about the Poisson Process for population inference\n}\n\n\\newcommand{\\uw}{2}\n\\newcommand{\\nyu}{3}\n\\author{%\n    Daniel~Foreman-Mackey\\altaffilmark{1,\\uw,\\nyu}\n}\n\\altaffiltext{1}         {Sagan Fellow; \\url{danfm@nyu.edu}}\n\\altaffiltext{\\uw}       {Department of Astronomy, University of Washington,\n                          Seattle, WA, 98195, USA}\n\\altaffiltext{\\nyu}      {Center for Cosmology and Particle Physics,\n                          Department of Physics, New York University,\n                          4 Washington Place, New York, NY, 10003, USA}\n\n\\section{The Poisson Process}\n\nGiven a rate density function $\\rate(\\bvec{w})$, the Poisson probability of\nobserving $N$ events in some volume $\\bvec{w} \\in \\bvec{W}$ is\n\\begin{eqnarray}\\eqlabel{count}\np(N) &=& \\frac{\\intrate^N\\,e^{-\\intrate}}{N!}\n\\end{eqnarray}\nwhere\n\\begin{eqnarray}\n\\intrate &=& \\int_{\\bvec{W}} \\rate(\\bvec{w}) \\dd\\bvec{w}\n\\end{eqnarray}\nis the total rate in the volume.\n\nUnder this same model, the probability of an event at $\\bvec{w}_n$ is\n\\begin{eqnarray}\np(\\bvec{w}_n) &=& \\frac{\\rate(\\bvec{w}_n)}{\\intrate} \\quad.\n\\end{eqnarray}\nThen, once we have $N$ independent events $\\{\\bvec{w}_n\\}_{n=1}^N$, the\nprobability across the full sample is\n\\begin{eqnarray}\\eqlabel{ind}\np(\\{\\bvec{w}_n\\}) &=& N!\\,\\prod_{n=1}^N\\frac{\\rate(\\bvec{w}_n)}{\\intrate}\n\\end{eqnarray}\nwhere the $N!$ combinatoric term comes from the exchangeability of the\nsamples and it is important for the next step.\n\nCombining \\eq{count} and \\eq{ind}, we can derive the standard expression for\nthe Poisson Process likelihood function\n\\begin{eqnarray}\np(N,\\,\\{\\bvec{w}_n\\}) &=& p(N)\\,p(\\{\\bvec{w}_n\\}) \\\\\n&=& \\frac{\\intrate^N\\,e^{-\\intrate}}{N!} \\,\n    N!\\,\\prod_{n=1}^N\\frac{\\rate(\\bvec{w}_n)}{\\intrate} \\\\\n&=& e^{-\\intrate} \\, \\prod_{n=1}^N\\rate(\\bvec{w}_n) \\quad.\n\\end{eqnarray}\n\n\\section{Mixture of Poisson Processes}\n\nLet's say that each point $n$ in our sample is generated from one of $K$\ndistinct populations with underlying rate densities $\\rate_k(\\bvec{w})$.\nIn this case, the joint likelihood across the full sample can be written as\n\\begin{eqnarray}\np(N,\\,\\{\\bvec{w}_n\\}\\,|\\,\\{q_n\\}) &=&\n    \\exp\\left(-\\sum_{k=1}^K\\intrate_k\\right) \\,\n    \\prod_{n=1}^N\\prod_{k=1}^K\n        \\left[\\rate_k(\\bvec{w}_n)\\right]^{\\bvec{1}(q_n = k)}\n\\end{eqnarray}\nwhere $q_n$ is the class of object $n$ and $\\bvec{1}(\\cdot)$ is the indicator\nfunction that equals one if the argument is true and zero otherwise.\nThis equation can be easily derived by splitting the sample into the $K$\nsubsamples, writing the Poisson Process likelihood for each subsample, and\ntaking the product.\n\nNow, we will relax our assumptions and allow for the fact that we don't know\nthe class memberships $\\{q_n\\}$ \\foreign{a priori}.\nInstead, we can choose a prior over class memberships\n\\begin{eqnarray}\np(q_n) &=& \\prod_{k=1}^K {Q_k}^{\\bvec{1}(q_n = k)}\n\\end{eqnarray}\nwhere $\\sum_k Q_k = 1$, and marginalize over choice of class for each sample.\nDoing this, we find\n\\begin{eqnarray}\np(N,\\,\\{\\bvec{w}_n\\}) &=&\n    \\exp\\left(-\\sum_{k=1}^K\\intrate_k\\right) \\,\n    \\prod_{n=1}^N\\sum_{k=1}^K\n        Q_k\\,\\rate_k(\\bvec{w}_n)\n\\end{eqnarray}\n\n\n% \\begin{figure}[p]\n% \\begin{center}\n% \\includegraphics[width=\\textwidth]{figures/smooth/results.pdf}\n% \\end{center}\n% \\caption{%\n% {\\bf Simulated data}.\n% Inferences about the rate density based on the simulated catalog \\modela.\n% \\emph{Center:} the points with error bars show the exoplanet candidates in the\n% simulated incomplete catalog, the contours show the survey completeness\n% function (\\citealt{petigura}), and the grayscale shows the median posterior\n% occurrence surface.\n% \\emph{Top and left:} the red dashed line shows the true distribution that was\n% used to generate the catalog, the points with error bars show the results of\n% the inverse-detection-efficiency procedure, and the histograms are posterior\n% samples from the marginalized rate density as inferred by our method.\n% \\figlabel{smooth-results}}\n% \\end{figure}\n\n\\end{document}\n", "meta": {"hexsha": "d649cba7c1d3cb80a77804aad83a6ae4ca1ea7dc", "size": 6081, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "document/poisson.tex", "max_stars_repo_name": "dfm/exopop2", "max_stars_repo_head_hexsha": "fb67b4bab39a7c77811548f365690da159fb88d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "document/poisson.tex", "max_issues_repo_name": "dfm/exopop2", "max_issues_repo_head_hexsha": "fb67b4bab39a7c77811548f365690da159fb88d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "document/poisson.tex", "max_forks_repo_name": "dfm/exopop2", "max_forks_repo_head_hexsha": "fb67b4bab39a7c77811548f365690da159fb88d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3546511628, "max_line_length": 80, "alphanum_fraction": 0.6883736228, "num_tokens": 2073, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.34455971010999603}}
{"text": "\\chapter{Introduction} \\label{sec:intro}\nPositioning assets, such as facilities and equipment, within a pre-defined region, such as a plot of land or a building, in a fashion that is tailoured towards a criteria of optimality for a specific problem is one endeavour that has multiple applications in different fields, primarily due to the benefits it provides. Finding the best possible asset positioning can result in improved operations efficiency, better productivity \\cite{El-Baz2004}, and even decreases in expenses \\cite{Sahin2011}. As a matter of fact, due to the benefits of asset positioning, \\$300 billion dollars have been spent each year on just determining suboptimal locations of buildings and facilities in the United States alone \\cite{Asl2015a}. This is further proof of the importance of asset positioning. One entertaining example of said application is showcased by Barriga et al. (2014). In their paper, the authors developed a genetic algorithm that optimized placement of buildings in a StarCraft match. The algorithm produced building placements that allowed the defending player's base to better survive base assaults from the opposing player \\cite{Barriga2014}. Developing an open-plan office layout is another application of asset positioning. Chen et al. (2020) also developed a genetic algorithm that generates an open-office layout where the space utilization is maximized as possible \\cite{Chen2020}. This task of arranging assets within a given space according to some criteria has a formal term, which is the \"facility layout problem\", often abbreviated as \"FLP\". We will be discussing facility layout problems in more detail in this chapter.\n\nFLP is a field that has been researched as early as 1957 (with Koopsman T.C., and Beckman, M. being the first to model the problem) \\cite{Kusiak1987}, and there is still active research around it to this day. This research paper is one of the testaments to that. In this research, we will be solving the classical facility layout problem using a recent optimization algorithm called the Grey Wolf Optimization (GWO) algorithm. The specific type of FLP that we will solve is called the unequal area static FLP. The categorization will be discussed later in this paper. The proposed algorithm will then be compared to a genetic algorithm using experimental data used in other related papers.\n\n\\section{Facility Layout Problem}\nThe problem of arranging a set of facilities and/or machines in a pre-determined area, or a set of possible locations (such as in the work of Farmakis, P., and Chassiakos, A. \\cite{Farmakis2018}) is called the facility layout problem (FLP). The facilities and/or machines are arranged in such a way that the resulting layout is in line with some criteria or objectives and under certain constraints. These constraints, which must not be violated, include shape, size, orientation, pick-up/drop-off points \\cite{Hosseini-Nasab2018}, and usable area \\cite{Fernando2015}. Facilities and/or machines must also not overlap. Solutions that satisfy the aforementioned conditions are called feasible solutions \\cite{Meller1996}.\n\nGenerally, the facility layout problem is considered to be an \\textbf{NP-Hard} problem \\cite{Drira2007}. Hosseini-Nasab, H., Fereidouni, S., and Fatemi, S. have noted in their systematic review of FLP that most researches dealing with the facility layout problem model their problems either as a quadratic assignment problem (QAP) or a mixed integer programming problem \\cite{Hosseini-Nasab2018}. According to Drira, A., Pierreval, H., and Hajri-Gabouj, S., the former is sometimes used in discrete FLP formulations, while the latter is often used in continuous formulations \\cite{Drira2007}. Discrete and continuous FLP formulations will be discussed later. \\textbf{Quadratic assignment problems} deal with placing $n$ facilities in $n$ locations in such a way that minimizes the assignment cost. The assignment cost is the sum of all facility pairs's flow rate between each other multiplied by their flow rate \\cite{QAPDefinition}. This assignment cost is commonly seen in many FLP researches, as we will discuss later. QAP is also known to be an NP-Hard problem \\cite{Garey1979}. It should be noted though that \\textit{some} instances of QAP are easy to solve \\cite{Feizollahi2015}. The other modeling framework, \\textbf{mixed integer programming}, can solve problems with both discrete decisions and continuous variables. An example of such problem is the assignment problem \\cite{Richards2005}, which the FLP can be classified under. In this formulation, a set of integer and real-valued integers are being optimized based on an objective function that is being minimized or maximized, while satisfying constraints which are linear equations or inequalities \\cite{Wolsey2008}. Mixed integer programming, when in the context of optimization, is also known to be NP-Hard \\cite{Richards2005}. These two formulations being known to be generally NP-Hard proves that FLP is indeed generally NP-Hard.\n\nThe fact that FLP is an NP-Hard problem has resulted in many research works that utilize heuristics (such as simulated annealing and genetic algorithms). Note that there are also works that utilize exact methods, which seek to find the \\textit{optimal} solution for a problem. However, the NP-Hard nature of the FLP prevents them from finding the solution in large problems within reasonable time \\cite{Asl2015}.\n\n\\subsection{The Basic Mathematical Model}\nEach problem instances of the facility layout problem naturally will have their own mathematical models tailor-fit for their problem instance. Nevertheless, based on our observations and from readings, most of those models are derivatives of or use (such as in \\cite{Garcia-Hernandez2013}, \\cite{Lin2019}, and \\cite{Navarro2016}) what will be calling a basic minimization function, which is defined as:\n\n$$\n\\text{min} F = \\sum_{i=1}^{n}\\sum_{j=1}^{n}c_{ij}f_{ij}d_{ij}\n$$\n\nwhere $N$ is the number of facilities, $c_{ij}$ is the cost of handling materials between locations $i$ and $j$, $f_{ij}$ is the flow rate between $i$ and $j$, and $d_{ij}$ is the distance between the centroids of $i$ and $j$. The distance function may differ from work to work. For example, Liu, J., et. al. uses the Manhattan distance in their work \\cite{Liu2018}, while in the work of Ripon, K. S. N., et. al., Euclidean distance was used \\cite{Ripon2013}. In works that derive from this formula, such as in \\cite{Farmakis2018}, \\cite{Solimanpur2008}, and \\cite{Peng2018}, it was observed that $d_{ij}$, or a similar variable or expression, is commonly present in the work's objective function while $c_{ij}$ and $f_{ij}$ \\textit{may} be present and/or the work uses more or fewer variables.\n\nDrira, A., Pierreval, H., and Hajri-Gabouj, S. note the same observation but showcase a slightly differing formula in their 2007 survey of facility layout problems. Unlike the basic minimization formula above, their formula has $f_{ij}$ and $c_{ij}$ combined. They also note that the function above is typically used in continuous formulations of the FLP. The discrete formulation uses a similar function, but ensures that a facility is only in one location, a location only contains one facility, and makes sure that only pairs of locations that contain facilities contribute to the fitness value of a solution. (The descriptions and the differences of the discrete and continuous formulations are discussed in the next section.) Additionally, they mention that the function is also subject to the following constraints: (1) facilities must obviously not overlap with one another, and (2) the total area used by the facilities must be equal to or less than the allotted area \\cite{Drira2007}. These constraints have been observed to be generally in many FLP works.\n\n\\subsection{Discrete vs Continuous Formulations}\nSolving instances of the facility layout problem requires determining the form of the solution. The form is highly dependent on the problem being solved. Some problems may require a solution that assigns assets to pre-existing locations, while others may require more flexibility. Facility layout problems may be categorized based on the characteristics of these solutions, or formally known as formulations: discrete, and continuous.\n\nIn a discrete formulation, the region where the facilities will be laid out are divided into equal rectangular blocks of the same shape and size, or have pre-determined possible facility locations \\cite{Drira2007}. Each facility will be given a number of blocks, or be assigned to one facility location, respectively. This formulation, however, does not suit well when the facilities require exact positions and it cannot model facility attributes such as orientation. In problems that have such requirements, a continuous formulation is more appropriate \\cite{Hosseini-Nasab2018}. Facilities in a continuous formulation are usually located by either their centroid coordinates, half length, and half width, or by their bottom-left coordinates, length, and width \\cite{Drira2007}. This allows for the formulation's flexibility compared to its discrete counterpart. However, this does provide challenges towards ensuring that no two facilities overlap with one another. Discrete formulations do not need to consider this problem due to their inherent characteristics.\n\n\\subsection{Static vs Dynamic Facility Layout Problems}\nAnother categorization for facility layout problems is based on whether the layouts will change over time. There are situations where a regular change of layout over some periods of time is necessitated. The layout of facilities in a construction is one example. As the construction of a building moves to from phase to another, the layout of facilities within the construction site change to better fit the needs of the current phase of construction \\cite{Farmakis2018}. A similar need is the motivation behind changing layouts in manufactories. Product demand variations, and even a change in product design can incline a factory's management to reorganize facilities in the building to be more efficient in response to the changes \\cite{Pourhassan2017}. There are two categories for the aformentioned criteria. These are: (1) static, and (2) dynamic. We will refer to these categories as \\textbf{\"period-based layout categories\"} in this paper.\n\nThe survey of Hoisseini-Nasab et al. (2018) showed that the most common period-based categorization in literature is the static facility layout problem \\cite{Hosseini-Nasab2018}. This is likely due to the fact that static facility layout problems are easier to solve than dynamic facility layout problems. Though, it is also possible that many problems just happen to not require consideration of variable changes over time. The \\textbf{static facility layout problem}, abbreviated as SFLP, is a type of FLP where variables to be considered such as material handling costs do not change for a considerable amount of time \\cite{Perez-Gosende2020}. For this type of problems, only a single layout is generated since no changes are made in the considered variables over time.\n\nHowever, some industries will find SFLPs inadequate for their needs. There are companies that require adaptability to changes to, for example, product demands. For cases like this, the other category, dynamic facility layout problems are more appropriate \\cite{DerakhshanAsl2017}. In the dynamic facility layout problem, abbreviated to DFLP, the variables to be considered change over time, unlike in SFLP. The cost of rearranging facilities are also considered in the problem \\cite{Hosseini2016}. The solutions for DFLPs are also divided into time periods, where each period has a different layout. This period may equate to years, seasons, months, or weeks \\cite{DerakhshanAsl2017}. DFLPs can also be viewed as extensions of SFLP, since each layout in a period can be viewed as a solution to an SFLP with that period's variables into consideration but with rearrangement costs considered. While most research today is focused on SFLPs, Hosseini-Nasab et al. (2018) recommends that research should deal with DFLPs more these days due to rapid scientific developments, and product changes \\cite{Hosseini-Nasab2018}.\n\n\\subsection{Other FLP Classifications}\nFacility layout problems can also be categorized based on different characteristics. FLPs can be divided by the area of their facilities. The facilities may have the same areas, referred to as equal areas, or have different areas, referred this time to as unequal areas \\cite{DerakhshanAsl2017}. They can also be divided based on the possible arrangements of facilities. Some problems may have facilities located only in a single pre-defined row (single-row), or they may be placed anywhere in the region (open field) \\cite{Drira2007}. There are multiple classifications for FLP and discussing them in this chapter would take long and dislocate the focus of this paper. Due to that, we would like to refer the reader to the papers of Drira et al. (2007) \\cite{Drira2007} and Hosseini-Nasab et al. (2018) \\cite{Hosseini-Nasab2018} for more information on FLP classifications.\n\n\\section{The Grey Wolf Optimization Algorithm}\nIn this paper, we will be using the Grey Wolf Optimization algorithm to solve the unequal-area static facility layout problem. As such, we will be introducing the algorithm here for us to gain a better understanding of the algorithm.\n\n\\begin{figure}[h!]\n\t\\centering\n\t\\includegraphics{./images/chap01-introduction/wolves.jpg}\n\t\\caption{The Grey Wolf Optimization algorithm was inspired from the behaviour of grey wolves. Pictured are white wolves, different from grey wolves, but why pass up the opportunity to add a meme in a research paper? Profeshonal.}\n\t\\label{wolves-meme}\n\\end{figure}\n\nThe Grey Wolf Optimization algorithm, abbreviated as GWO, was first conceived by Mirjalili  et al. (2014) in 2014. The optimization algorithm is inspired from the hunting and social behaviour of grey wolves. There is a hierarchy in packs of wolves. Each category in the hierarchy have specific responsibilities. There are four categories: alpha ($\\alpha$), beta ($\\beta$), delta ($\\delta$), and omega ($\\omega$). Alpha wolves are responsible for making major decisions for the pack. Every wolf must follow the alpha. However, sometimes the alpha follows other wolves. The second in line is the beta, which ensures the discipline of the pack and advises the alpha. They also command other wolves and reinforces the alpha's commands. The lowest in the hierarchy are the omegas. They must follow the orders of the other wolves, and are the last to eat. Despite their low status, they are still crucial in the pack as their absence causes the pack to face internal fighting and problems. If a wolf is not an alpha, beta, nor omega, they are considered to a delta, the third category in the hierarchy. Deltas may act as scouts, sentinels, elders, hunters, or caretakers. They are also at a category higher than the omegas \\cite{Mirjalili2014} \\cite{Gupta2018}. As an interesting side note, the inspiration for Grey Wolf Optimization initially came from The Grey, a movie where survivors of a plane crash must survive, but a pack of grey wolves surround them \\cite{TheGreyPlotSummary2011}.\n\n\\subsection{Mathematical Model}\nThe mathematical model assumes the existence of a \"pack of wolves\". The number of wolves in this pack can be determined by the researcher. Each wolf of this a solution to the problem. We will be delving into the model more in this section, discussing about the model of leadership hierarchy, encircling, and hunting behaviour of grey wolves. The prey being hunted in this scenario is the best solution for a given problem \\cite{Mirjalili2014}.\n\n\\subsubsection{Leadership Hierarchy}\nSolutions are assigned to a certain hierarchy in the mathematical model of GWO. The fittest solution is considered the alpha ($\\alpha$), while the second and third fittest are considered to be the beta  (\\beta) and delta ($\\delta$) solutions. The rest of the solutions are referred to as the omega solutions. The leading wolves guide the omegas towards the prey throughout the search process \\cite{Gupta2018}.\n\n\\subsubsection{Encircling the Prey}\nPrey encirclement, which is one of the first steps when grey wolves hunt for their prey, can be modeled with the following:\n\n\\begin{align*}\n\t\\vec{X}(t + 1) &= \\vec{X_{p}}(t)\n\t\t\t\t\t  - \\vec{A} \\cdot \\vec{D}                     \\\\\n\t\\vec{D}        &= \\left | \\vec{C} \\cdot \\vec{X_{p}}(t)\n\t\t\t\t\t  - \\vec{X}(t) \\right | \\\\\n\t\\vec{A}        &= 2 \\cdot \\vec{a} \\cdot \\vec{r_{1}}\n\t\t\t\t\t  - \\vec{a}                \\\\\n\t\\vec{C}        &= 2 \\cdot \\vec{r_{2}}\n\\end{align*}\n\nwhere $\\vec{X}(t)$ and $\\vec{X}(t + 1)$ are the positions of the wolf at the iteration $t$ and $t + 1$ respectively, $\\vec{X_{p}}(t)$ represents the location of the prey at the iteration $t$, $\\vec{D}$ is the difference vector, $\\vec{A}$ and $\\vec{C}$ are coefficient vectors, and $\\vec{r_{1}}$ and $\\vec{r_{2}}$ are uniformly random vectors with the range $\\left[ 0, 1 \\right]$. $\\vec{a}$ is vector that linearly decreases from $2$ to $0$ over the course of iterations \\cite{Mirjalili2014}. The original paper on GWO does not specify but Gupta, S. and Deep, K. provided the following equation to specify the decrease of $\\vec{a}$ from $2$ to $0$ \\cite{Gupta2018}:\n\n$$\n\\vec{a} = 2 - 2 \\cdot \\left( \\frac{t}{\\text{maximum number of iterations}} \\right)\n$$\n\nNote that the multiplication of vectors in the equations above is a component-wise multiplication, and not a dot product \\cite{Mirjalili2020-MathModel}.\n\n\\subsubsection{Hunting}\nWe typically do not know the position of the prey in an abstract search space. As such, it is presumed that the $\\alpha$, $\\beta$, and $\\delta$ solutions have the best idea so far of the position of the prey \\cite{Mirjalili2014}. Each wolf updates their positions based on the following equations.\n\n\\begin{align}\n\t\\vec{D}_{\\alpha} &= \\left | \\left ( \\vec{C}_{1} \\cdot \\vec{X}_{\\alpha} \\right ) - \\vec{X} \\right | \\\\\n\t\\vec{D}_{\\beta} &= \\left | \\left ( \\vec{C}_{2} \\cdot \\vec{X}_{\\beta} \\right ) - \\vec{X} \\right | \\\\\n\t\\vec{D}_{\\delta} &= \\left | \\left ( \\vec{C}_{3} \\cdot \\vec{X}_{\\delta} \\right ) - \\vec{X} \\right | \\\\\n\t\\vec{X_{1}^{'}} &= \\vec{X_{\\alpha}}(t) - \\vec{A_{\\alpha}} \\cdot \\vec{D_{\\alpha}} \\\\\n\t\\vec{X_{2}^{'}} &= \\vec{X_{\\beta}}(t) - \\vec{A_{\\beta}} \\cdot \\vec{D_{\\beta}} \\\\\n\t\\vec{X_{3}^{'}} &= \\vec{X_{\\delta}}(t) - \\vec{A_{\\delta}} \\cdot \\vec{D_{\\delta}} \\\\\n\t\\vec{X}(t + 1)  &= \\frac{\\vec{X_{1}^{'}} + \\vec{X_{2}^{'}} + \\vec{X_{3}^{'}}}{3}\n\\end{align}\n\nwhere $\\vec{X_{\\alpha}}$, $\\vec{X_{\\beta}}$, and $\\vec{X_{\\delta}}$ represent the $\\alpha$, $\\beta$, and $\\delta$ solutions \\cite{Gupta2018}.\n\n\\subsubsection{Exploration and Exploitation}\nThe exploration phase of metaheuristics is modeled by the search phase, while exploitation is modeled by the attack phase. When $\\left| \\vec{A} \\right| < 1$, or $\\vec{C} < 1$, GWO is undergoing exploitation of the search space. Exploitation can be viewed as the wolves approaching towards the prey. On the other hand, when $\\left| \\vec{A} \\right| > 1$, or $\\vec{C} > 1$, the algorithm is in the search phase, where the wolves can be viewed as searching for the prey. In the search process, as the number of iterations $t$ reach the maximun possible number, the algorithm tends to focus more on exploitation than exploration. $\\vec{A}$ and $\\vec{a}$ eventually approach $0$, leaving $\\vec{C}$ the sole vector to eventually influence the search exploration. At this point, the algorithm will intensify towards exploitation. ", "meta": {"hexsha": "34e7dbf24ad38ad4867bc9c47b9b7c396c8690e3", "size": 19632, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapter1_intro.tex", "max_stars_repo_name": "seanballais/undergraduate-thesis-manuscript", "max_stars_repo_head_hexsha": "d2ae4c524b93ed1cb7a5fb6eedcfd3db3f90799d", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapter1_intro.tex", "max_issues_repo_name": "seanballais/undergraduate-thesis-manuscript", "max_issues_repo_head_hexsha": "d2ae4c524b93ed1cb7a5fb6eedcfd3db3f90799d", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter1_intro.tex", "max_forks_repo_name": "seanballais/undergraduate-thesis-manuscript", "max_forks_repo_head_hexsha": "d2ae4c524b93ed1cb7a5fb6eedcfd3db3f90799d", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 208.8510638298, "max_line_length": 1898, "alphanum_fraction": 0.7763854931, "num_tokens": 4700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.34455971010999603}}
{"text": "\\chapter{Basics on classification}\\label{ch:2}\n\n\\begin{remark}{Outline}\nIn this chapter, we introduce classification models from a machine learning perspective. \nFirst, in Section~\\ref{sec:2:classification}, we give a self contained introduction to \nclassification, including the most-common algorithms, and the main applications of \nclassification models. Then, in Section~\\ref{sec:2:measures}, we present the different evaluation \nmeasures that are normally used for analyzing the performance of classification methods.\n\\end{remark}\n\n\\section{Introduction}\n\\label{sec:2:classification}\n\nIn machine learning, classification refers to the attempt of identifying to which of a set of \nclasses a new example belongs, based on learning from examples whose class membership is known. \nA classification task begins with a training set in which the class of a set of examples is known. \nFor example, a classification model that predicts credit card fraud is developed by analyzing \nmany observed credit transactions over a period of time. The class in this case is a variable which \nindicates for each example whether or not the transaction was or not a fraud. Also, the features, \nare the transaction attributes like place, amount and time of the transaction.\n\nThen, during the training process, a classification algorithm finds the patterns and relationships \nbetween the values of the features and the values of the target class. Different algorithms use \ndifferent methods and techniques to estimate these relationships. Afterwards, these relationships \nare summarized in a model that is able to make predictions on new sets of data.\n\nIn general, there are two types of classification models: binary and multi-class. In binary \nclassification problems, the objective is to classify examples between two classes, usually \nreferred to as the negative and positive classes. On the other hand, multi-class problems are not \nbound to two classes but instead aim to classify examples among a number of classes. In this work we \nfocus on binary classification problems.\n\nBinary classification algorithms are widely used across a variety of domains. For example in the \nmedical field, models have been used for making predictions about tumors, probability \nof a disease, probability of selecting the right drug for a particular patient, and estimating the \nprobability of relapsing, among others \\citep{Herland2014}. In the financial sector, classification \nmodels have been successfully applied for fraud detection, credit scoring, portfolio management and \nalgorithmic trading. Also, in marketing, several models are being currently used for churn modeling, \ncustomer targeting, behavior prediction and direct marketing \\citep{Baesens2014}. Additionally, \nclassification algorithms are used in many other emerging applications such as terrorism \nprevention, malware detection, computer security, energy consumption prediction, spam \nclassification, and others \\citep{Kriegel2007}.\n\nFormally, a binary classification algorithm deals with the problem\tof predicting the class $y_i$ \nof a set $\\mathcal{S}$ of examples or instances $i$, given their $k$ features \\mbox{$\\mathbf{x}_i \n\\in \\mathbb{R}^k$}. The objective is to construct a function $f(\\cal{S})$ that makes a prediction \n$c_i$ of the class of each example $i$ from $\\cal{S}$ using its feature vector $\\mathbf{x}_i$, \nwhere $\\vert \\mathcal{S} \\vert= N$. Moreover, some algorithms allow to not only estimate the \nprediction, but also its confidence, in the form of the probability $\\hat p_i$ of belonging to the \npositive class, i.e. $c_i = 1$. The way for finding from $\\hat p_i$ to $c_i$ is simply by defining \na probability threshold $t$, and applying the following formula\n\\begin{equation}\\label{eq_pred}\n  c_i = \n  \\begin{cases}\n    \\phantom{-}0 \\phantom{-} \\mbox{if} \\phantom{-} \\hat p_i \\le t\\\\\n    \\phantom{-}1 \\phantom{-}\\mbox{otherwise,}\n  \\end{cases}\n\\end{equation}\nUsually $t=\\frac{1}{2}$ \\citep{Hastie2009}. However, if $t \\ne \\frac{1}{2}$, the \nfunction that generates the predicted class labels $\\mathbf{c}=[c_i]$ is denoted as \n$f^t$.\n\n\\begin{figure}\n\t\\centering\n\t\\input{figures/src/ch2_fig_classification_process}\n  \\caption{Classification process}\n  \\label{fig:2:1}\n\\end{figure}\n\nIn \\figurename{ \\ref{fig:2:1}}, the process of training and prediction in a classification \nalgorithm are summarized. First, during the training phase, using a training set \n$\\mathcal{S}_{train}$, an algorithm is trained to predict $\\mathbf{y}$, where\n$\\mathbf{y}=[y_i]$. Then the algorithm is used to estimate the classes \n$\\mathbf{c}$ of a set of testing examples $\\mathcal{S}_{test}$.\n\n\\begin{figure}[!t]\n\\centering\n\\includegraphics{ch2_fig1b}\n\\caption{Example of a classification algorithm. Using a set of examples from two classes, a \n\tclassification algorithm is learned in order to separate between the positives and the negatives. \n}\n\\label{fig:2:2}\n\\end{figure} \n\nThere exists several algorithms that can be used for classification tasks. In general a \nclassification algorithm is learned with the objective of finding patterns that separate between \nthe different classes \\citep{Hastie2009}. In order to clarify this intuition, in \\figurename{ \n\\ref{fig:2:2}} an example of a classification algorithm is shown. Let us consider a set of \nexamples, where the red points represent the positive examples and the blue ones the negative \nexamples. The objective of a classifier is to find the best way to separate between the positive and \nnegative examples. Then, the output of a classifier learned using the set of training examples is \nshown as the dashed black line. It is observed that this classifier is able to separate almost all \nthe examples using a linear classifier. However, not all examples are correctly classified. In \nparticular, there are four negative examples that were predicted as positive, and five positive \nexamples that were predicted as negative. In the next section, we present the standard methods for \nevaluating the performance of a classification algorithm.\n\n\n\\section{Traditional evaluation measures}\n\\label{sec:2:measures}\n\nWhen evaluating the performance of a classification algorithm, the first thing to do is to check \nthe number of examples that were misclassified, since the true class of the examples \nis known. Therefore, evaluating the error of a model is as simple as counting the number of times \nan example is misclassified divided by the number of examples\n\\begin{equation}\\label{eqn:ch2:error}\nErr(f({\\cal S})) = 1 -\\frac{1}{N}  \\sum_{i=1}^N \\mathbf{1}_{y_i}(c_i),\n\\end{equation}\nwhere $\\mathbf{1}_q(z)$ is an indicator function that is calculated as:\n\\begin{equation}\n   \\mathbf{1}_q(z) = \n  \\begin{cases}\n    \\phantom{-}1 \\phantom{-} \\mbox{if} \\phantom{-} z = q\\\\\n    \\phantom{-}0 \\phantom{-} \\mbox{if} \\phantom{-} z \\neq q.\n  \\end{cases}\n\\end{equation}\nMoreover the accuracy is defined as the percentage of times the algorithm \nmade the correct prediction\n\\begin{equation}\\label{eqn:2:accuracy}\nAcc(f({\\cal S})) = 1- Err(f({\\cal S})).\n\\end{equation}\n\nHowever, just knowing these statistics is not enough to make decisions, as in many applications \nit is important to know where the errors are coming from. In particular, the misclassified examples \nmay belong only to one class, which may give interesting insights about the problem. A way to \nobserve the different errors is by looking at the confusion matrix, as shown in \n\\mbox{\\tablename{~\\ref{tab:2:1}}}. Afterwards, using the cost matrix several statistics are \nextracted. In particular:\n  \\begin{flalign}\n    &Recall = \\frac{TP}{TP+FN} &\\\\\n    &Precision = \\frac{TP}{TP+FP}& \\\\\n    &F_1Score = 2\\frac{Precision \\cdot Recall}{Precision + Recall}&\n  \\end{flalign}\n  \n\t\\begin{table}[!t]\n\t\t\\centering\n\t\t\\footnotesize\n    \\begin{tabular}{c|c|c}\n      \\multicolumn{3}{c}{}\\\\\n\t\t\t\\multicolumn{1}{c|}{}  & Actual Positive& Actual Negative \\\\\n\t\t\t\\multicolumn{1}{c|}{} & $y_i=1$& $y_i=0$ \\\\\n\t\t\t\\hline\n\t\t\tPredicted Positive \t\t& \\multirow{ 2}{*}{True Positive ($TP$)} & \\multirow{ \n\t\t\t2}{*}{False Positive ($FP$)} \\\\\n\t\t\t$c_i=1$ & &\\\\\n\t\t\t\\hline\n\t\t\tPredicted Negative  \t& \\multirow{ 2}{*}{False Negative ($FN$)} & \\multirow{ \n\t\t\t2}{*}{True Negative ($TN$)} \\\\\n\t\t\t$c_i=0$ & &\\\\\n\t\t\\end{tabular}\n\t\t\\caption{Classification confusion matrix}\n\t\t\\label{tab:2:1}\n  \\end{table}  \n \n \\newpage\n  As an illustrative example, the different statistics are calculated for the example presented \n  in Section~\\ref{sec:2:classification}. First, the confusion matrix is calculated as \n  follows:\n  \\begin{center}\n    \\footnotesize\n  \\begin{tabular}{c|c|c}\n    \\multicolumn{1}{c|}{}  & Actual Positive& Actual Negative \\\\\n    \\multicolumn{1}{c|}{} & $y_i=1$& $y_i=0$ \\\\\n    \\hline\n    Predicted Positive    & \\multirow{ 2}{*}{36} & \\multirow{ \n    2}{*}{4} \\\\\n    $c_i=1$ & &\\\\\n    \\hline\n    Predicted Negative    & \\multirow{ 2}{*}{5} & \\multirow{ \n    2}{*}{68} \\\\\n    $c_i=0$ & &\\\\\n  \\end{tabular}\n  \\end{center}\n  Then using the confusion matrix, the different statistics are calculated as: Error = \n11.11\\%, Recall = 87.8\\%, Precision = 90\\% and $F_1Score$ = 88.8\\%.\n\t\nThere are, however, several instances that are misclassified, that is because the simple linear \nclassifier that was used in this example may not be good enough to separate between the positive \nand negative classes. In order to make a comparison, using the same example, a new \nalgorithm is learned. This time the algorithm made the correct prediction more often as shown in \n\\figurename{ \\ref{fig:2:3}}. Afterwards, the confusion matrix is calculated as follows:\n\n\\begin{figure}[t!]\n  \\centering\n  \\includegraphics{ch2_fig2}\n  \\caption{Example of a classification algorithm. Using a set of examples from two classes, a \n  classification algorithm is learned in order to separate between the positives and the negatives. \n}\n  \\label{fig:2:3}\n\\end{figure}\n\n\\begin{center}\n\t\t\\footnotesize\n    \\begin{tabular}{c|c|c}\n\t\t\t\\multicolumn{1}{c|}{}  & Actual Positive& Actual Negative \\\\\n\t\t\t\\multicolumn{1}{c|}{} & $y_i=1$& $y_i=0$ \\\\\n\t\t\t\\hline\n\t\t\tPredicted Positive \t\t& \\multirow{ 2}{*}{37} & \\multirow{ \n\t\t\t2}{*}{2} \\\\\n\t\t\t$c_i=1$ & &\\\\\n\t\t\t\\hline\n\t\t\tPredicted Negative  \t& \\multirow{ 2}{*}{4} & \\multirow{ \n\t\t\t2}{*}{70} \\\\\n\t\t\t$c_i=0$ & &\\\\\n\t\t\\end{tabular}\n\\end{center}\nThen the different statistics are calculated as: Error = 5.3\\%, Recall = 90.2\\%, Precision = \n94.9\\% and $F_1Score$ = 92.5\\%.\nIt is observed that in this case the FP are reduced more than the FN, this leads to a higher \nincrease in precision  than in recall. There is not a single rule regarding which one is more \nimportant than the other, it depends on the application. For example in applications with a high \nfalse negative cost such as failing to identify a tumor in a medical exam, the recall should be the \npriority, even if that implies having a significant number of false positives. On the other hand, \nIn applications such as spam detection, predicting a normal email as spam it may have a large \nimpact on the customer, therefore, in this example is better to allow some false negatives and \nfocus on the false positives.\n\nIt is not always straightforward  to define the right tradeoff between false positives \nand false negatives. The best approximation to solve that, is to focus on the actual costs incurred \nby the different decisions. This is usually solved using cost-sensitive classification methods. \n\n\\subsection{Brier score}\n\\label{sec:2:brier}\n\nTraditional evaluation measures of binary classification problems, such as Accuracy and \n$F_1Score$, provide a way to analyze the performance of a model. However, when using the classifier \noutput as a basis for decision making, there is a need of a measure that takes into account not \nonly the misclassification of a classifier predicted class $c$, but also the quality of the \nestimated probabilities $\\mathbf{\\hat p}$ \\citep{cohen2004}. The most appropriate  is the Brier \nscore \\citep{brier1950}. The Brier score belongs to the class of so-called proper scores which are \nused in evaluating the subjective probability assessment of the prediction \\citep{DeGroot1983}. The \nBrier score is the average squared difference between the estimated probability and the true class \nlabel. It is defined as:\n\\begin{equation}\n  BS(f(\\mathcal{S})) = \\frac{1}{N} \\sum_{i=1}^{N} (\\hat p_i - y_i)^2.\n\\end{equation}\n\nThe main justification of this score is based on decision theoretic considerations, in the sense \nthat, a forecaster should pay a price proportional to the confidence with which it asserts its \ndecision.\n\n\n\\subsection*{}\n", "meta": {"hexsha": "ce19b02c27161585902893c6ced7dfaa4cd3bffc", "size": 12553, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/chapters/chapter02.tex", "max_stars_repo_name": "albahnsen/phd-thesis", "max_stars_repo_head_hexsha": "8aedb00cba939b6f8a2f891f453a37206db1f635", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2015-10-07T13:31:49.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-09T12:02:27.000Z", "max_issues_repo_path": "tex/chapters/chapter02.tex", "max_issues_repo_name": "albahnsen/phd-thesis", "max_issues_repo_head_hexsha": "8aedb00cba939b6f8a2f891f453a37206db1f635", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/chapters/chapter02.tex", "max_forks_repo_name": "albahnsen/phd-thesis", "max_forks_repo_head_hexsha": "8aedb00cba939b6f8a2f891f453a37206db1f635", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-01-25T17:16:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-11T13:47:21.000Z", "avg_line_length": 51.4467213115, "max_line_length": 101, "alphanum_fraction": 0.7463554529, "num_tokens": 3296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.34455971010999603}}
{"text": "\\renewcommand*\\chappic{img/intro.pdf}\n\\renewcommand*\\chapquote{}\n\\renewcommand*\\chapquotesrc{}\n%\n\\chapter{Introduction}\n\\label{ch:intro}\n\\section{Overview}\n\\label{sec:intro-overview}\n%\nHash functions are used as cryptographic primitives in many applications and protocols.\nThey take an arbitrary input message and provide a hash value. Input message and hash value\nare considered as byte strings in a particular encoding.\nThe hash value is of fixed length and satisfies several properties which make it useful\nin a variety of applications.\n\nIn this thesis, we consider the hash algorithms MD4 and SHA-256.\nOur goal is to find hash collisions using differential cryptanalysis.\nWe define differences between two messages and determine actual bits\nsuch that the two messages result in the same hash value. \\\\\nThis whole equation system will be modelled as a satisfiability problem.\nA SAT solver reports satisfiability if and only if the particular\ndifferences can be resolved and an actual hash collision is found.\nWe introduce a bit condition notation which allows us to visualize\nsuch differential states. Verification is done by several SAT solvers\nand we compare their runtime. Because the Boolean functions modelled in\na CNF have a major influence on the runtime, we investigate several\napproaches and compare them.\n\nBased on experience with these kind of problems with previous heuristic search tools\nwe aim to apply best practices to a satisfiability setting.\nWe will discuss, which SAT techniques lead to best performance characteristics\nfor our MD4 and SHA-256 testcases.\n\n\\section{Thesis Outline}\n\\label{sec:intro-outline}\n%\nThis thesis is organized as follows:\n\n\\begin{description}\n\\item[In Chapter~\\ref{ch:intro},] we briefly introduce basic subjects of this\n  thesis. We explain our high-level goal involving hash functions and SAT solvers.\n\n\\item[In Chapter~\\ref{ch:hash},] we introduce the MD4 and SHA-256 hash functions.\n  Certain design decisions imply certain properties which can be used in differential\n  cryptanalysis. We discuss those decisions in this chapter after a formal definition\n  of the function itself. Beginning with this chapter we develop a theoretical notion\n  of our tools.\n\n\\item[In Chapter~\\ref{ch:dc},] we discuss approaches of differential cryptanalysis.\n  We start with work done by Wang, et al. and followingly introduce differential\n  notation to simplify representation of differential states. This way we can easily dump\n  hash collisions.\n\n\\item[In Chapter~\\ref{ch:sat},] we discuss SAT solving techniques. We discuss how\n  the problem needs to be encoded and give a brief overview over used SAT solvers.\n  This includes a customized lingeling version by Armin Biere for our purposes.\n\n\\item[In Chapter~\\ref{ch:features},] we define SAT features which help us to\n  classify SAT problems. This is a small subproject we did to look at properties\n  of resulting DIMACS CNF files.\n\n\\item[In Chapter~\\ref{ch:enc},] we discuss how we represent a problem (i.e. the hash\n  function and a differential characteristic) as SAT~problem. This ultimatively\n  allows us to solve the problem using a SAT solver.\n\n\\item[In Chapter~\\ref{ch:results},] we present the result of our work.\n  Runtimes are the main part of this chapter, but also results of Chapter~\\ref{ch:features}\n  are presented.\n\n\\item[In Chapter~\\ref{ch:summary},] we conclude and discuss future work based on our results.\n\\end{description}\n", "meta": {"hexsha": "eda0fb23ce93353c2c8eeeceb92f00087a0671b0", "size": 3434, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "intro.tex", "max_stars_repo_name": "prokls/master_iaik", "max_stars_repo_head_hexsha": "30703774eaac6a514add2424f5c408a549cd4db1", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-05-13T21:45:11.000Z", "max_stars_repo_stars_event_max_datetime": "2016-05-13T21:45:11.000Z", "max_issues_repo_path": "intro.tex", "max_issues_repo_name": "prokls/master_iaik", "max_issues_repo_head_hexsha": "30703774eaac6a514add2424f5c408a549cd4db1", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "intro.tex", "max_forks_repo_name": "prokls/master_iaik", "max_forks_repo_head_hexsha": "30703774eaac6a514add2424f5c408a549cd4db1", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.6944444444, "max_line_length": 93, "alphanum_fraction": 0.795573675, "num_tokens": 775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3445189346395196}}
{"text": "\\documentclass[letterpaper,11pt]{article}\n\\usepackage{ltcadiz}\n\n%%side margin is 1.0in + oddside, so we're creating a 1 inch margin\n\\oddsidemargin 0.0in \n\\topmargin 0.0in\n\\textwidth 6.5in\n\n\\usepackage{fullpage}\n\n\\title{Z Examples Found on the Internet}\n\n\\begin{document}\n\n\\maketitle\n\n\\section{Introduction}\n\n\\subsection{Z section heading}\n\n    \\begin{zsection}\n    \\SECTION gearsystem \\parents standard\\_toolkit\n    \\end{zsection}\n\n\\subsection{Free types paragraph}\n\n    \\begin{zed}\n    gearing ::= Single | Hub \\ldata \\nat \\rdata\n        | Derailleurs \\ldata \\nat \\cross \\nat \\rdata\n    \\end{zed}\n\n\\subsection{Horizontal definition paragraph}\n\n    \\begin{zed}\n    Wellgeared == [ gears : gearing | gears \\in \\ran Derailleurs ]\n    \\end{zed}\n\n\\subsection{Generic axiomatic description paragraph}\n\n    \\begin{gendef}[X,Y]\n    First : X \\cross Y \\fun X \\\\\n    Second : X \\cross Y \\fun Y\n    \\where\n    \\forall x : X; y : Y @ \\\\\n    \\t1     First~(x,y) = x \\land \\\\\n    \\t1     Second~(x,y) = y\n    \\end{gendef}\n\n\\subsection{Schema definition paragraph}\n\n    \\begin{schema}{Gear}\n    Wellgeared \\\\\n    ingear : \\nat \\cross \\nat\n    \\where\n    \\exists r, s : \\nat | gears = Derailleurs (r,s) @\\\\\n    \\t1 First~ingear < r \\land Second~ingear < s\n    \\end{schema}\n\n\\subsection{Generic schema definition paragraph}\n\n    \\begin{schema}{Bicycle}[G]\n    gears:\\power G\n    \\end{schema}\n\n\\subsection{Axiomatic description paragraph}\n\n    \\begin{axdef}\n    numgears : gearing \\fun \\nat\n    \\where\n    \\forall g : gearing @ \\\\\n    \\t1 (g = Single \\implies numgears~g = 1) \\land \\\\\n    \\t1 (\\exists x : \\nat @ g = Hub~x \\implies numgears~g = x) \\land \\\\\n    \\t1 (\\exists r, s :\\nat @ g = Derailleurs~(r, s) \\implies numgears~g = r*s)\n    \\end{axdef}\n\n\\subsection{Conjecture paragraph}\n\n    \\begin{theorem}{Lemma1}\n    \\thrm numgears (Derailleurs (3,7)) = 21\n    \\end{theorem}\n\n\n\\end{document}\n", "meta": {"hexsha": "3244020adce9d04b5d522dc55e027b66f1f918e0", "size": 1879, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "z/z_example.tex", "max_stars_repo_name": "CraigKelly/latex-samples", "max_stars_repo_head_hexsha": "48330f4b91ce2bf721441f27f2f0950cabcde1e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-08-09T08:11:58.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-09T08:11:58.000Z", "max_issues_repo_path": "z/z_example.tex", "max_issues_repo_name": "CraigKelly/latex-samples", "max_issues_repo_head_hexsha": "48330f4b91ce2bf721441f27f2f0950cabcde1e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "z/z_example.tex", "max_forks_repo_name": "CraigKelly/latex-samples", "max_forks_repo_head_hexsha": "48330f4b91ce2bf721441f27f2f0950cabcde1e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-08-09T08:11:59.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-09T08:11:59.000Z", "avg_line_length": 22.369047619, "max_line_length": 79, "alphanum_fraction": 0.6391697712, "num_tokens": 616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.3445189262749576}}
{"text": "\n% This LaTeX was auto-generated from an M-file by MATLAB.\n% To make changes, update the M-file and republish this document.\n\n\n\n    \n    \n\n\\subsection*{conT.m} \n\n\\begin{par}\n\\textbf{Summary:} Test derivatives of controller functions. It is assumed that the controller function computes the mean and the variance of the control signal for a Gaussian distributed input $x\\sim\\mathcal N(m,s)$\n\\end{par} \\vspace{1em}\n\\begin{verbatim}function [dd dy dh] = conT(deriv, policy, m, s, delta)\\end{verbatim}\n\\begin{par}\n\\textbf{Input arguments:}\n\\end{par} \\vspace{1em}\n\\begin{verbatim}deriv    desired derivative. options:\n     (i)    'dMdm' - derivative of the mean of the predicted control\n             wrt the mean of the input distribution\n     (ii)   'dMds' - derivative of the mean of the predicted control\n             wrt the variance of the input distribution\n     (iii)  'dMdp' - derivative of the mean of the predicted control\n             wrt the controller parameters\n     (iv)   'dSdm' - derivative of the variance of the predicted control\n             wrt the mean of the input distribution\n     (v)    'dSds' - derivative of the variance of the predicted control\n             wrt the variance of the input distribution\n     (vi)   'dSdp' - derivative of the variance of the predicted control\n              wrt the controller parameters\n     (vii)  'dCdm' - derivative of inv(s)*(covariance of the input and the\n             predicted control) wrt the mean of the input distribution\n     (viii) 'dCds' - derivative of inv(s)*(covariance of the input and the\n             predicted control) wrt the variance of the input distribution\n     (ix)   'dCdp' - derivative of inv(s)*(covariance of the input and the\n             predicted control) wrt the controller parameters\npolicy   policy structure\n  .fcn   function handle to policy\n  .\\ensuremath{<}\\ensuremath{>}    other fields that are passed on to the policy\nm        mean of the input distribution\ns        covariance of the input distribution\ndelta    (optional) finite difference parameter. Default: 1e-4\\end{verbatim}\n\\begin{par}\n\\textbf{Output arguments:}\n\\end{par} \\vspace{1em}\n\\begin{verbatim}dd         relative error of analytical vs. finite difference gradient\ndy         analytical gradient\ndh         finite difference gradient\\end{verbatim}\n\\begin{par}\nCopyright (C) 2008-2013 by Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen.\n\\end{par} \\vspace{1em}\n\\begin{par}\nLast modified: 2013-05-30\n\\end{par} \\vspace{1em}\n\n\\begin{lstlisting}\nfunction [dd dy dh] = conT(deriv, policy, m, s, delta)\n\\end{lstlisting}\n\n\n\\subsection*{Code} \n\n\n\\begin{lstlisting}\nif nargin < 5; delta = 1e-4; end % default value\n\n% if no input arguments, create random policy parameters and check derivatives\nif nargin == 0\n  D = 2;\n  d = 3;\n  policy.w = randn(D,d);\n  policy.b = randn(D,1);\n  m = randn(d,1);\n  s = randn(d); s = s*s';\n  policy.maxU = '2 3';\n  policy.fcn = @(policy, m, s)conCat(@conLin, @gSat, policy, m, s);\nend\n\nD = length(policy.maxU);\nd = length(m);\n\nswitch deriv\n  case 'dMdm'\n      [dd dy dh] = checkgrad(@conT0, m, delta, policy, s);\n\n  case 'dSdm'\n      [dd dy dh] = checkgrad(@conT1, m, delta, policy, s);\n\n  case 'dCdm'\n      [dd dy dh] = checkgrad(@conT2, m, delta, policy, s);\n\n  case 'dMds'\n      [dd dy dh] = checkgrad(@conT3, s(tril(ones(d))==1), delta, policy, m);\n\n  case 'dSds'\n      [dd dy dh] = checkgrad(@conT4, s(tril(ones(d))==1), delta, policy, m);\n\n  case 'dCds'\n      [dd dy dh] = checkgrad(@conT5, s(tril(ones(d))==1), delta, policy, m);\n\n  case 'dMdp'\n      [dd dy dh] = checkgrad(@conT6, policy.p, delta, policy, m, s);\n\n  case 'dSdp'\n      [dd dy dh] = checkgrad(@conT7, policy.p, delta, policy, m, s);\n\n  case 'dCdp'\n      [dd dy dh] = checkgrad(@conT8, policy.p, delta, policy, m, s);\n\nend\n\\end{lstlisting}\n\n\\begin{lstlisting}\nfunction [f, df] = conT0(m, policy, s)                                  % dMdm\nif nargout < 2\n    M = policy.fcn(policy, m, s);\nelse\n    [M, S, C, dMdm] = policy.fcn(policy, m, s);\n    df = dMdm;\nend\nf = M;\n\nfunction [f, df] = conT1(m, policy, s)                                  % dSdm\nif nargout < 2\n    [M, S] = policy.fcn(policy, m, s);\nelse\n    [M, S, C, dMdm, dSdm] = policy.fcn(policy, m, s);\n     df = dSdm;\nend\nf = S;\n\nfunction [f, df] = conT2(m, policy, s)                                  % dCdm\nif nargout < 2\n    [M, S, C] = policy.fcn(policy, m, s);\nelse\n    [M, S, C, dMdm, dSdm, dCdm] = policy.fcn(policy, m, s);\n    df = dCdm;\nend\nf = C;\n\nfunction [f, df] = conT3(s, policy, m)                                  % dMds\nd = length(m);\nv(tril(ones(d))==1) = s; s = reshape(v,d,d); s = s+s'-diag(diag(s));\nif nargout < 2\n    M = policy.fcn(policy, m, s);\nelse\n    [M, S, C, dMdm, dSdm, dCdm, dMds] = policy.fcn(policy, m, s);\n    dd = length(M); dMds = reshape(dMds,dd,d,d); df = zeros(dd,d*(d+1)/2);\n    for i=1:dd;\n        dMdsi(:,:) = dMds(i,:,:); dMdsi = dMdsi + dMdsi'-diag(diag(dMdsi));\n        df(i,:) = dMdsi(tril(ones(d))==1);\n    end\nend\nf = M;\n\nfunction [f, df] = conT4(s, policy, m)                                  % dSds\nd = length(m);\nv(tril(ones(d))==1) = s; s = reshape(v,d,d); s = s+s'-diag(diag(s));\nif nargout < 2\n    [M, S] = policy.fcn(policy, m, s);\nelse\n    [M, S, C, dMdm, dSdm, dCdm, dMds, dSds] = policy.fcn(policy, m, s);\n    dd = length(M); dSds = reshape(dSds,dd,dd,d,d); df = zeros(dd,dd,d*(d+1)/2);\n    for i=1:dd; for j=1:dd\n        dSdsi(:,:) = dSds(i,j,:,:); dSdsi = dSdsi+dSdsi'-diag(diag(dSdsi));\n        df(i,j,:) = dSdsi(tril(ones(d))==1);\n    end; end\nend\nf = S;\n\nfunction [f, df] = conT5(s, policy, m)                                  % dCds\nd = length(m);\nv(tril(ones(d))==1) = s; s = reshape(v,d,d); s = s+s'-diag(diag(s));\nif nargout < 2\n    [M, S, C] = policy.fcn(policy, m, s);\nelse\n    [M, S, C, dMdm, dSdm, dCdm, dMds, dSds, dCds] = policy.fcn(policy, m, s);\n    dd = length(M); dCds = reshape(dCds,d,dd,d,d); df = zeros(d,dd,d*(d+1)/2);\n    for i=1:d; for j=1:dd\n        dCdsi = squeeze(dCds(i,j,:,:)); dCdsi = dCdsi+dCdsi'-diag(diag(dCdsi));\n        df(i,j,:) = dCdsi(tril(ones(d))==1);\n    end; end\nend\nf = C;\n\nfunction [f, df] = conT6(p, policy, m, s)                               % dMdp\npolicy.p = p;\nif nargout < 2\n    M = policy.fcn(policy, m, s);\nelse\n    [M, S, C, dMdm, dSdm, dCdm, dMds, dSds, dCds, dMdp] = policy.fcn(policy, m, s);\n    df = dMdp;\nend\nf = M;\n\nfunction [f, df] = conT7(p, policy, m, s)\npolicy.p = p;\nif nargout < 2\n    [M, S] = policy.fcn(policy, m, s);\nelse\n    [M, S, C, dMdm, dSdm, dCdm, dMds, dSds, dCds, dMdp, dSdp] = policy.fcn(policy, m, s);\n    df = dSdp;\nend\nf = S;\n\nfunction [f, df] = conT8(p, policy, m, s)\npolicy.p = p;\nif nargout < 2\n    [M, S, C] = policy.fcn(policy, m, s);\nelse\n    [M, S, C, dMdm, dSdm, dCdm, dMds, dSds, dCds, dMdp, dSdp, dCdp] = ...\n                                                      policy.fcn(policy, m, s);\n    df = dCdp;\nend\nf = C;\n\\end{lstlisting}\n", "meta": {"hexsha": "aa1e8533d28b64823978eccb71de295ab6313611", "size": 6919, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/tex/conT.tex", "max_stars_repo_name": "SJTUGuofei/pilco-matlab", "max_stars_repo_head_hexsha": "a0b48b7831911837d060617903c76c22e4180d0b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 53, "max_stars_repo_stars_event_min_datetime": "2016-12-17T15:15:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T16:59:27.000Z", "max_issues_repo_path": "doc/tex/conT.tex", "max_issues_repo_name": "sahandrez/quad_pilco", "max_issues_repo_head_hexsha": "2c99152e3a910d147cd0a52822da306063e6a834", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-24T11:02:23.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-24T11:09:45.000Z", "max_forks_repo_path": "doc/tex/conT.tex", "max_forks_repo_name": "sahandrez/quad_pilco", "max_forks_repo_head_hexsha": "2c99152e3a910d147cd0a52822da306063e6a834", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 36, "max_forks_repo_forks_event_min_datetime": "2017-04-19T06:55:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-19T10:19:12.000Z", "avg_line_length": 31.7385321101, "max_line_length": 215, "alphanum_fraction": 0.5852001734, "num_tokens": 2445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.3445189262749576}}
{"text": "\\chapter{Discussion}\\label{c4}\n\nAs mentioned earlier, kNN compares the test sample to k neighbouring training samples to determine the class. This means all training samples have to be stored in memory \\cite{Gutie} which in turn could slow down the computer, causing the classifier to take a longer time to produce results. Being a non-parametric technique \\cite{16N} unlike DT and RF, kNN is prone to the curse of dimensionality \\cite{Gutie}, which happens when the dimensions or number of features increases \\cite{Distr}. This might explain the lower performance metric scores in comparison. There are big differences between the optimal k values for some turbines as shown in \\autoref{f3} which could be due to the data for each turbine having different distributions and characteristics.\n\nOverall, using a single multiclass-multilabel classifier with imbalanced training data produced better scores, which could be due to presence of correlations between the different turbine categories used as labels that are generalised better using this approach \\cite{110}.\n\nAs the labels `gearbox' and `electrical system' are in the top three out of 14 labels used causing longest downtimes, they should have more samples classed as `faulty' and `X hours before fault' compared to other categories, which therefore should result in better performance as the classifier would have learned the characteristics of different samples belonging to the same classes. This was not the case, however, looking at the confusion matrices in \\autoref{a4}. The classifier tends to misclassify `faulty' and `X hours before fault' classes as `normal' at a higher rate than the accuracy for these classes. This is still the case after removing the `curtailment' class, which saw an improvement in the accuracy of the `faulty' class. The accuracies of `X hours before fault' classes could potentially be increased by reducing the 6-hour intervals used and the maximum of 48 hours before a fault. The analysis should be repeated by reducing 48 hours to a smaller timescale, such as 12 hours, or by combining all samples that fall under this with `faulty' points to make the classification binary. Although this is likely to improve the performance, the classifier will not be able to give an indication of the timescale before a potential fault, therefore making it more difficult to decide on the appropriate action to be taken to avoid catastrophic failure in the turbine.\n\nBased on the feature importance in \\autoref{t6}, active power SCADA fields were least influential in predicting faults for both labels. The labelled power curves for `electrical system' in \\autoref{f5} below shows no clear relationship between fault points and the power curve shape. There are also many overlapping `normal', `faulty' and `X hours before fault' points even after filtration of curtailment and anomalies, which could explain why this feature was less important.\n\n\\begin{figure}\n  \\centering\n  \\begin{subfigure}[t]{.5\\textwidth}\n    \\centering\n    \\includegraphics[height=5cm]{../images/f5a}\n    \\caption{\\label{f5a}}\n  \\end{subfigure}%\n  \\begin{subfigure}[t]{.5\\textwidth}\n    \\centering\n    \\includegraphics[height=5cm]{../images/f5b}\n    \\caption{\\label{f5b}}\n  \\end{subfigure}\n  \\begin{subfigure}[t]{.5\\textwidth}\n    \\centering\n    \\includegraphics[height=5cm]{../images/f5c}\n    \\caption{\\label{f5c}}\n  \\end{subfigure}\n  \\caption{\\label{f5}Labelled power curve for turbine 1 with turbine category 10 (`electrical system') through the two stages of filtering out anomalous and curtailment points labelled as `normal'. The original power curve is shown in \\ref{f5a}. The first stage involves a filter based on a pitch angle threshold, which produces \\ref{f5b}. The second stage involves several additional filters to produce the final power curve \\ref{f5c}.}\n\\end{figure}\n\nThe reactive power and generator speed played a bigger role in the classification for `electrical system', which makes sense considering the reactive power is produced as a result of impedance in the current due to electromagnetic fields produced by generators and transformers \\cite{React}. It is likely that the features used in classification for this label are unsuitable. A fault in the electrical system would be reflected in voltages, currents, frequencies \\cite{Overb} and temperature of power switchboards and cables. Electrical system faults could also be caused by environmental conditions such as lightning strikes and contact of wires with wildlife \\cite{Overb}. If there are such conditions recorded as environmental downtime categories, these should be accounted for when analysing faults in the electrical system.\n\nThe `gearbox' label was also found to perform poorly for these classes, despite having a higher mean F1 score than `electrical faults', which could be due to feature selection as well. Statistics from the National Renewable Energy Laboratory's gearbox failure database indicate that most faults are caused by bearings, gears and other components including filtration and lubrication systems \\cite{Stati15}. These are mostly due to wear, fatigue and cracks \\cite{Sheng11} and may be detected with higher accuracy if the features include quantities such as torque, oil pressure and gearbox temperature.\n\nThe SCADA data provided for this project only had 17 SCADA fields, of which 10 are used as features. This did not include voltages, currents, frequencies, torques or temperature readings, but the SCADA system for the turbine model used does measure these parameters. When a more complete SCADA data is available, the evaluation should be done by increasing the number of features to include these fields. The role of environmental conditions on failures could explain why wind speed and direction were very influential in detecting faults in the two labels analysed, although further in-depth analysis is required to verify this.\n\nBalancing the training dataset improved the classification accuracy of `X hours before fault' classes slightly. An overall improved model may be developed by oversampling only these classes for training, but there is a trade-off between this and the training time and computational resources required.\n\nThe dataset could have incorrect readings in the SCADA fields caused by broken or unresponsive sensors which are not detected as unusual when the downtime data is used in labelling. This was why a power threshold before cut-in speed was applied to remove redundant data points, by visually inspecting the power curve of the turbine as seen in \\autoref{f1}. The dataset should be manually inspected for all other features using curves such as pitch versus power and power versus rotor speed, to see if there are any other incorrect values previously undetected which may affect the classifier's accuracy in detecting faults. The rows of data corresponding to these values should then be excluded from the training data.\n\n\\section{Future work}\n\nIn addition to possible areas for future work discussed above, the following were identified.\n\nWhen more data is available, the analysis should be repeated using historic datasets spanning the life of the turbine. Historic data would have recorded the different states a turbine has experienced over its life, and therefore when a classifier is trained on this, it could detect future turbine states easier. However, this will mean the training data will be bigger, which in turn causes longer training time and more computing resources to be used. Another area of work is to test the performance of a classifier using different lengths of datasets for training while keeping the testing set and hyperparameter settings constant. This will allow for the most appropriate length of dataset for training to be determined based on the resources available to produce satisfactory results in terms of training time and classification accuracy.\n\nAfter a classifier has been trained and used in practice, its performance over time should be monitored. If the performance is found to diminish over time or after a major component replacement, the classifier should be retrained using recent data. As the classification makes a distinction between the different faults, the ability to alert relevant maintenance professionals for a specific fault automatically is possible.\n\nInstead of using turbine categories in the downtime data, which is supervised, for labelling, the alarm logs, which are unsupervised, can instead be used to compare the results. The number of alarm logs for the turbines used, however, is 480, compared to 23 turbine categories. This will mean the number of labels will be much higher, which will cause longer computational time. A solution to reduce this is to group similar alarms into one class. Another approach would be to use a single label with each alarm as a separate class, but there is likely to be overlap between classes when fault prediction is also included. If actual failure records are available, a comparison can be made between the predicted classes, actual classes, and actual failures that have occurred and their costs.\n\nFurther optimisation of hyperparameters is possible, such as finding the optimal number of estimators for RF. Each optimisation takes time and is limited by the specifications of the computer used, which is why this was not carried out in this project. Detailed analysis done on the results using RF for two labels above should be repeated for each label and classifier used for fair comparisons to be made.\n\nThe methodology could also be tested for wind turbines of different models in different sites. Provided these turbines have similar SCADA data with downtime records, only slight modifications to the codes, such as the data source, field names, and number of features, would be required in order to be used on other turbine models.\n\nIn industry, a cost function analysis needs to be done prior to implementing this fault detection method. It is defined as the cost of a false alarm (false positive) or failing to detect a fault in advance (false negative). False positives and false negatives both incur charges. The first is due to transporting labour and equipment to site, which could be expensive especially for sites in harsh environments, such as offshore wind farms. The second would cause unscheduled downtime, the loss of revenue due to no power generation and replacement of turbine components due to irreversible damage. This cost should then be compared to the cost of alternatively using a condition monitoring system, and the overall cost of running the wind farm or wind turbine. The analysis should give an indication on which performance metric is more important; if the cost of false negatives is more, attention should be paid to the recall score, while the precision is more important if false positives cost more \\cite{deRu15}.\n", "meta": {"hexsha": "5c87833c31727cb40c6d7bb6d53c8b08e88a48fd", "size": 10869, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/discussion.tex", "max_stars_repo_name": "nmstreethran/WindTurbineClassification", "max_stars_repo_head_hexsha": "b0ea6de909ccd5bb425cee291ca3c252c11df4eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 34, "max_stars_repo_stars_event_min_datetime": "2019-03-01T21:24:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T09:59:17.000Z", "max_issues_repo_path": "docs/discussion.tex", "max_issues_repo_name": "nmstreethran/WindTurbineClassification", "max_issues_repo_head_hexsha": "b0ea6de909ccd5bb425cee291ca3c252c11df4eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/discussion.tex", "max_forks_repo_name": "nmstreethran/WindTurbineClassification", "max_forks_repo_head_hexsha": "b0ea6de909ccd5bb425cee291ca3c252c11df4eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2019-03-01T21:24:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-26T15:04:14.000Z", "avg_line_length": 194.0892857143, "max_line_length": 1381, "alphanum_fraction": 0.8094580918, "num_tokens": 2179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3445189262749576}}
{"text": "\\documentclass[]{aastex62}\n\\usepackage{amssymb,amsmath}\n\n \n\\newcommand{\\vk}{von K\\'{a}rm\\'{a}n}\n\\newcommand{\\vdag}{(v)^\\dagger}\n\\newcommand\\aastex{AAS\\TeX}\n\\newcommand\\latex{La\\TeX}\n\n\n\\def\\eq#1{\\begin{equation} #1 \\end{equation}}\n\\def\\mic              {\\hbox{$\\mu\\mathrm{m}$}}\n\\def\\atm    {\\hbox{\\rm{ATM}}}\n\\def\\dC     {\\hbox{$^{o}C$}}\n\\graphicspath{{./}{figures/}}\n\n%% Reintroduced the \\received and \\accepted commands from AASTeX v5.2\n%\\received{May 7, 2019}\n%\\revised{May 8, 2019}\n%\\accepted{--}\n%% Command to document which AAS Journal the manuscript was submitted to.\n%% Adds \"Submitted to \" the arguement.\n%\\submitjournal{Icarus}\n\n\\shorttitle{Variation of CubeSat Temperature along its Orbit}\n\\shortauthors{}\n\n\\begin{document}\n\n\\title{A Simple Model for the Variation of CubeSat Temperature along its Orbit}  \n \n%\\email{ivezic@uw.edu}\n\n\\author[0000-0001-5250-2633]{\\v{Z}eljko Ivezi\\'{c}}\n\\affiliation{Department of Astronomy, University of Washington, 3910 15th Avenue NE, Seattle, \n                      WA 98195, USA; e-mail: ivezic@uw.edu}\n\n\\begin{abstract}\nWe discuss a simple model for the variation of CubeSat temperature along its orbit. First \nwe consider an analytic solution for the satellite temperature variation with time when subjected to \na bistable heat source: two segments with piece-wise constant power, such as orbits with an eclipsed \nsegment when the Sun is not directly visible. The model assumes that at a given time a single \ntemperature applies to the entire satellite body. Discussion is focused on CubeSat satellites in \nlow-Earth orbits, the uncertainties in predicted temperatures due to uncertain input parameters, and \nit emphasizes the importance of the satellite thermal inertia in setting the amplitude of the temperature \nvariation along the orbit. This simplified ``spherical cow'' model is suitable for studying the relative \neffects of surfaces with different emissivities, the effects of small changes in the solar flux between \nJune and December, the impact of thermal inertia, and as a ``sanity check'' for the results obtained \nwith numerical thermal models that utilize detailed geometrical and thermal descriptions of all satellite \ncomponents. We also developed a numerical model with arbitrary time dependence of the heating power, including its \ndependence on the satellite temperature, and validated it using analytic solution for a bistable heat \nsource. Analysis of a typical 2U CubeSat shows that low temperatures are more worrisome than\nhigh temperatures, and that low temperatures can be mitigated by active temperature control such\nas releasing heat when the satellite is in eclipse using electrical energy stored in batteries that\nare charged during non-eclipsed portion of the orbit. \n\\end{abstract}\n\n\\keywords{Satellites --- CubeSat --- Radiative transfer -- Analytic solution}\n\n\n\\section{Introduction} \n \nOver the last two decades, the concept of a small modular satellite named CubeSat\\footnote{For more \ndetails and references, see https://en.wikipedia.org/wiki/CubeSat} has become\nextremely popular -- to date about two thousand satellites were launched or are in preparation \nstage\\footnote{See https://en.wikipedia.org/wiki/List\\_of\\_CubeSats}. CubeSat projects have both\nscientific and educational values, and are suported by many universities as well as space organizations\nsuch as NASA and ESO. \n\nWhen designing a satellite, it is crucial to establish that the temperature variation for each component \nwill be within its operating range. In practice, professional engineering tools (such as Ansys framework)\nand numerical analysis are used to analyze complex systems. Nevertheless, approximately correct temperature estimates \nand physical insight can be derived even using simple analytic models. Such models can be used as\na ``sanity check'' for the results obtained with complex thermal models that include \nnumerous input parameters, and for fast input parameter exploration (e.g., runtime for a numerical \ntransient model using the Ansys code can be several hours). Simplified models are also useful as an\neducational tool and they help develop deeper physical understanding than numerical simulations. \n\nWhile there is relatively abundant literature on CubeSat thermal modeling, it appears that a \ncompact reference appropriate for undergraduate and graduate students entering this field,\nand supported by easy to use open source code, has not been published yet. This paper is\nattempting to fill this gap and it is a result of our work with two CubeSat projects:  the SOC-i satellite project\\footnote{https://www.aa.washington.edu/news/article/2019-02-11/cubesat-team}\nat the University of Washington and the Perun satellite project\\footnote{https://perun-i.hr/en/} in Croatia.  \n\nA simple model for the satellite temperature variation with time can be derived by assuming that a single\ntemperature applies to the entire satellite body at any  given time. An implication of this assumption is \nthat the thermal resistivity across the surface is vanishing and thus the entire surface can reach the\nsame temperature very quickly (under a minute or less). This model permits an analytic solution \nwhen subjected to a bistable heat source with two segments that each have constant input power \n(the sum of input heating flux and internal power dissipation). A bistable heat source is a good \napproximation for a satellite orbit with an eclipsed segment when the Sun is not directly visible. \n\nThe governing equations for such a simple model with bistable heat source are presented in the \nfollowing Section, and numerical results are discussed in Section 3.  In Section 4 we discuss\nactive temperature control and summarize our conclusions in Section 5. \n\n\n\\section{Simple single-temperature thermal model} \n\nConsider a satellite with a given geometry and assume a uniform temperature over its surface\nat any given time, $T(t)$. The temperature variation with time depends on the difference between\nheat source, $Q_{in}$, and heat sink, $Q_{out}$, \n\\eq{\n\\label{eq:dTdt}\n                 m C {dT \\over dt} =  Q_{in} - Q_{out}, \n}\nwhere $m$ is the satellite mass and $C$ is the material heat capacity. The heat capacity for \nmost common materials used in satellites is listed in Table~\\ref{tab:inputsMatProp}. \nThe $mC$ product is often called the thermal inertia. Heat sources and sinks are measured in \nWatts (W = Js$^{-1}$). \n\n\\begin{table}[ht!]\n\t\\centering\n\t\\caption{Common material properties (Gilmore 2002). }\n\t\\label{tab:inputsMatProp}\n\t\\begin{tabular}{r|r|r|r} % \n\t\t\\hline\n  \t        Material    &      density &   specific heat & thermal conductivity \\\\\n\t\t\\hline\n                 \\phantom{x}              & $\\rho$ (kg\\,m$^{-3}$)   &   $C$ (J\\,kg$^{-1}$\\,K$^{-1}$)  & $k$ (W\\,m$^{-1}$\\,K$^{-1}$)  \\\\\n             Aluminum  &       2,710       &         768--921      &     120--205  \\\\ \n             Solar cells  &       2,285       &         300--700      &     60--100    \\\\\n \t\t\\hline\n\t\\end{tabular} \n      % $^a$ $\\rho$ is mass density, $C$ is heat capacity (specific heat), and $k$ is thermal conductivity. \n\\end{table}\n \n\\subsection{Radiative heat sink} \n\nAssuming that the satellite is in vacuum, the heat sink is due to radiative losses\n\\eq{\n\\label{eq:Qout}\n                      Q_{out} = A_{tot} \\epsilon_T \\, \\sigma T^4  \n}\nwhere $A_{tot}$ is the satellite total surface area (e.g., for a spherical satellite $A_{tot} = 4\\pi R^2$,\nwhere $R$ is the satellite radius), $\\sigma=5.67\\times10^{-8}$ Wm$^{-2}$K$^{-4}$ is the Stefan-Boltzmann \nconstant,  and $\\epsilon_T$ is the wavelength-averaged surface emissivity over the thermal flux distribution. \nThe surface emissivity $\\epsilon_T$ is approximately equal to the emissivity at the wavelength of the peak emission. From Wien's \nlaw, this wavelength is equal to (3000 K$\\mic$)/T and thus for $T \\approx 300$ K, $\\epsilon_T$ is approximately \nequal to the material emissivity around 10 $\\mic$. Typical values of $\\epsilon_T$  for materials used in \nsatellite industry are in the range 0.8-0.9; values of $\\epsilon_T$ for common materials are listed in \nTable~\\ref{tab:inputsAbsEmiss}. \n\nThe energy spent on battery charging (the conversion of incoming solar flux to chemical energy) is \nalso a heat sink. However, essentially all of that energy is returned back as a heat source at a later time. \nThe treatment of these effects is discussed separately further below (see \\S~\\ref{sec:batteries}). \n\n\n\\begin{table}[t]\n\t\\centering\n\t\\caption{Surface optical absorptivity and infrared emissivity (Gilmore 2002). }\n\t\\label{tab:inputsAbsEmiss}\n\t\\begin{tabular}{r|r|r} % \n\t\t\\hline\n  \t                  Surface       &    $\\alpha_S$  &   $\\epsilon_T$    \\\\\n\t\t\\hline\n  Black anodized aluminum  &       0.86      &         0.86     \\\\ \n    Blue anodized aluminum  &       0.67      &         0.86     \\\\ \n Yellow anodized aluminum  &       0.47     &         0.86     \\\\ \n   Solar panels                      &        0.92     &         0.85     \\\\\n   Black plastic                     &       0.95       &         0.87     \\\\ \n   Catalac White Paint          &        0.24      &         0.90      \\\\ \n   Dupont Silver Paint        &          0.43      &         0.49      \\\\\n   Buffed Aluminum           &          0.16      &         0.03      \\\\  \n    Buffed Copper               &          0.30      &         0.03      \\\\  \n  Polished stainless steel   &         0.42        &        0.11     \\\\ \n      Gold coating                &        0.19        &       0.02       \\\\\n     Kapton foil                    &       0.11         &        0.33      \\\\\n\t\t\\hline\n\t\\end{tabular} \n\\end{table}\n\n\n\n\\subsection{Heat sources} \n\nThe heat sources can include direct solar radiation, $Q_{sun}$, solar radiation reflected from Earth, \n$Q_{ref}$, and thermal infrared emission from Earth, $Q_{IR}$. When the satellite is exposed to direct \nsunlight, the maximum possible heat source corresponds to \n\\eq{\n\\label{eq:QinSun} \n                   Q_{in}^{sun}  = Q_{sun} + Q_{ref} + Q_{IR}  \n} \nwhile the minimum possible heating corresponds to \n\\eq{\n\\label{eq:QinEclipse} \n                     Q_{in}^{eclipse}  = Q_{IR},\n} \nwhen the satellite is in Earth's shadow (eclipsed by Earth). For illustration, see figure~\\ref{fig:JacquesFig22}. \n\n%The two extremes, ``hot'' and ``cold'', should not be confused with ``hot'' and ``cold'' scenarios\n% that maximize/minimize the satellite temperature over an orbital cycle. \n \n\n\\begin{figure}[t]\n\\centering\n\\includegraphics[width=0.65\\textwidth, keepaspectratio]{figures/Jacques_heatSources.png} \n\\caption{An illustration of the satellite heat balance (here 1U CubeSat satellite is shown). \nThe heat sources include direct solar radiation, solar radiation reflected from Earth (albedo), \ninfrared radiation emitted by Earth, and internally dissipated power. Conversion of input\nradiation to chemical energy in batteries is not shown. The heat sink is thermal infrared radiation \nemitted by the satellite and energy for battery charging. Credit: Figure 2.2 from the master thesis \nby Lionel Jacques (2009, University of Liege). \n\\label{fig:JacquesFig22}}\n\\end{figure}\n\n\n\\subsubsection{Solar radiation} \n\nThe time-averaged solar flux is about $F_{sun}$=1372 Wm$^{-2}$ and its spectral energy distribution peaks \nat wavelenghts of about 0.5 $\\mic$ (yellow light; the Sun's surface temperature is about 5,800 K). Since \nEarth's orbit is not circular, the solar flux varies from 1322 Wm$^{-2}$ in June to 1422 Wm$^{-2}$ in December, \nor by about 4\\% around its mean value (see Table~\\ref{tab:inputsEnvParam}). The absorbed energy due to \nsolar flux is then \n\\eq{\n\\label{eq:Qsun}\n                   Q_{sun}  = A_S \\, \\alpha_S  \\, F_{sun} = \\eta_S \\, A_{tot} \\, \\alpha_S  \\, F_{sun} \n} \nwhere  $A_S$ is the satellite's mean projected surface area towards the Sun (for sphere, $A_S = \\pi R^2$ and\n$\\eta_S=1/4$), and $\\alpha_S$ is the wavelength-averaged surface absorptivity over the solar flux distribution. \nFollowing Kirchhoff's law, absorptivity $\\alpha_S$ is approximately equal to the emissivity at 0.5 $\\mic$, the wavelength \nof the peak of the solar spectral energy distribution\\footnote{The following convention is used in ESA and NASA \nliterature: $\\epsilon$ is the mean emissivity (and absorptivity) in the infrared wavelength range (5--35 \\mic), \nand $\\alpha$ is the mean absorptivity (and emissivity) in the optical wavelength range (0.3--2.4 \\mic).}. The low \nvalues of $\\alpha_S$ imply high reflectivity and ``shiny'' surfaces. The values of  $\\alpha_S$ for common \nmaterials are listed in Table~\\ref{tab:inputsAbsEmiss}. \n \n\n\\begin{table}[t]\n\t\\centering\n\t\\caption{The range of input enviromental parameters. }\n\t\\label{tab:inputsEnvParam}\n\t\\begin{tabular}{r|r|r|r|r} % \n\t\t\\hline\n  \t         Quantity & max    &   min   &  mean &  unit            \\\\\n\t\t\\hline\n              Solar flux   &  1422  &  1322  &  1372 & Wm$^{-2}$  \\\\\n           Earth albedo  &    35    &    25    &     30  &   \\%            \\\\ \n            Earth IR flux &  260    &   220   &    240 & Wm$^{-2}$   \\\\\n \t\t\\hline\n\t\\end{tabular} \n\\end{table}\n\n\\subsubsection{Solar radiation reflected from Earth} \n\n \nThe fraction of solar flux reflected by Earth back towards the satellite is typically $\\rho_E=0.3$, and it \nvaries in the range $\\rho_E=0.2-0.4$ across Earths' surface and oceans. The reflected flux depends on the\n\"Sun-Earth-satellite\" angle, $\\theta$, and it is maximized when the satellite is at the subsolar point. \nGilmore (2002) gives an approximate formula for the variation of reflected light with $\\theta$ as \n\\eq{\n                f(\\theta) = \\left[ \\cos(0.9\\theta)\\right]^{1.5},\n}\nthat can be used to derive mean correction, $f_{alb}$, for a given orbit. For example, for a polar orbit passing\nthrough subsolar point, $f_{alb}=0.62$ for the non-eclipsed part of the orbit, and for a polar orbit perpendicular \nto it (with $\\theta=90$ deg. and no eclipsed part), $f_{alb}=0.06$. \n \nThe absorbed energy from the reflected solar radiation is then\n\\eq{\n\\label{eq:Qref}\nQ_{ref} =  f_E \\, A_E  \\, f_{alb} \\, \\rho_E  \\, \\alpha_S  \\,  F_{sun} = f_E \\, \\eta_E \\, A_{tot} \\, f_{alb} \\, \\rho_E  \\, \\alpha_S  \\,  F_{sun} \n}\nwhere $A_E$ is the satellite's effective projected surface area towards Earth. The $f_E$ factor  \naccounts for the fact that Earth fills less than 2$\\pi$ srad (``half the sky'') as viewed from the satellite, and is defined as \n\\eq{\n               f_E = \\left( R_E \\over R_E + h \\right)^2,  \n}\nwhere $R_E=6,378$ km is the Earth's mean radius and $h$ is the satellite's altitude (typically, $h=550$ km \nfor a low-Earth orbit, giving $f_E \\sim 0.85$).  The ratio $\\eta_E=A_E/A_{tot}$ needs to account for the fact\nthat incoming radiation from Earth is not plane-parallel as is the case for direct solar radiation. The computation\nof $\\eta_E$ is based on the concept of radiative viewing factors and it is discussed in more detail in Appendix A. \nThe resulting $\\eta_E$ for spherical and CubeSat satellites are further discussed in \\S~\\ref{sec:effA}. \n\nTherefore, \n\\eq{\n                          Q_{ref} =  f_E \\, {\\eta_E \\over \\eta_S} \\, f_{alb} \\, \\rho_E  \\, Q_{sun}. \n}\n\n\n\\subsubsection{Infrared radiation emitted by Earth} \n\nThe thermal infrared flux emitted by Earth is about $F_{IR}$=240 Wm$^{-2}$ on average (see Table~\\ref{tab:inputsEnvParam}), \nand it is equal to one quarter (the ratio $A_S/A_{tot}$ for Earth) of the absorbed solar radiation (for $\\rho_E=0.3$, 70\\% of \n$F_{sun}$ is absorbed by Earth).  Since Earth's equilibrium temperature of $\\approx$300 K, the spectral energy \ndistribution of this radiation peaks at about 10 $\\mic$. Therefore, \n\\eq{\n              Q_{IR} =  f_E \\,  A_E \\, \\alpha_{IR} \\, F_{IR} =  f_E \\,  \\eta_E \\, A_{tot}  \\, \\alpha_{IR} \\, F_{IR} \n}\nwhere $\\alpha_{IR}$ is the wavelength-averaged surface absorptivity over the Earth's thermal flux distribution.\nGiven Kirchhoff's law and the fact that the satellite and Earth's temperatures are similar, \n$\\alpha_{IR} \\approx \\epsilon_T$. Due to varying emission properties of Earth's surface (oceans, continents,\nclouds), $F_{IR}$ can vary by about $\\pm$10\\% along the satellite's orbit. \n\n\n\n\\subsection{Internal power dissipation \\label{sec:batteries}} \n\nA fraction of absorbed optical flux (the sum of $Q_{sun}$ and $Q_{ref}$) is often used to charge \non-board batteries. Up to about 30\\% of absorbed flux can be thus converted into chemical energy.\nThis energy conversion is also a heat sink. However, essentially all of that energy is returned back \nas a heat source at a later time (except for a small fraction needed to power on-board computer and\nto emit communication signal back to Earth), motivating a separate treatment.  \n\nThe energy stored in batteries can be dissipated in various ways, including at a constant rate and \nin short bursts. Here it will be assumed that batteries are charged using 30\\% of absorbed flux \n(solar cell efficiency $\\eta_{cell} = 0.3$) during non-eclipsed portion of the orbit, and that this \naccumulated energy is dissipated at a constant rate during the entire orbit. If fraction $\\eta_P$ \nof the orbital period $P$ is spent in Earth's shadow, then eqs.~\\ref{eq:QinSun} and \\ref{eq:QinEclipse} \nhave to be modified as \n\\eq{\n                  Q_{in}^{sun}  = (1 - \\eta_P  * \\eta_{cell}) * (Q_{sun} + Q_{ref}) + Q_{IR}    \n} \nand \n\\eq{\n\\label{eq:Qeclipse}\n                   Q_{in}^{eclipse}  = Q_{IR} +  \\eta_{cell} \\, (1 - \\eta_P) \\, (Q_{sun} + Q_{ref}), \n} \nwhere the second term in eq.~\\ref{eq:Qeclipse} is the battery power internally dissipated as heat\nat a constant rate during the entire orbit,\n\\eq{\n                   Q_{dissip}  =  \\eta_{cell} \\, (1 - \\eta_P) \\, (Q_{sun} + Q_{ref}).\n} \nOf course, eqs.~\\ref{eq:QinSun} and \\ref{eq:QinEclipse} are recovered when $\\eta_{cell} = 0$. Finally,\nit is good to emphasize that $\\eta_{cell}$ represents the fraction of all absorbed radiation that\nwas converted to battery charge. For example, if the cells occupy 2/3 of all external surfaces, and \nthe cell conversion efficiency is 30\\%, then $\\eta_{cell}$= 0.2. For randomized orientiations, it's only\n``effective'' quantities that count in the model considered here; however, when a specific satellite orientation\nis known, one could incorporate information about where exactly the solar cell panels are positioned, too.  \n\n\n\\subsection{Effective surface areas $A_S$ and $A_E$  for 1U and 2U CubeSat satellites \\label{sec:effA}} \n\nThree surface areas matter for heat balance: \n\\begin{itemize}\n\\item The total surface area, $A_{tot}$, that controls infrared radiation emitted by the satellite.\n\\item The satellite projected surface area as viewed from the direction of incoming solar radiation, $A_S=\\eta_SA_{tot}$.\n     For example, $\\eta_S= 1/4$ in case of spherical satellites. \n\\item The projected surface area as viewed from Earth, with satellite in zenith, $A_E=\\eta_EA_{tot}$. In more\n   detail, the computation of $A_E$ is a bit more complicated than in case of $A_S$ because Earth is much closer\n   than the Sun and it fills a much larger solid angle on the sky (e.g., in case of a spherical satellite very \n   close to Earth, $\\eta_S = 1/4$ and $\\eta_E = 1/2$, while asymptotically $\\eta_E = 1/4$ when the satellite\n   is much further away; for an orbit altitude of 550 km, $\\eta_E =0.36$). \n\\end{itemize}\n\nIn case of non-spherical satellites, the satellite orientation matters. For a given orientation and CubeSat\nsatellites, $\\eta_S$ and $\\eta_E$ can be computed by adding values for six individual sides, which are \ncomputed as discussed in Appendix A.  When averaged over plausible orientations and orbits, \nfor 1U and 2U CubeSat geometries $\\eta_S = 0.21$ and $\\eta_E = 0.36$, with a plausible uncertainty due to\nactual orbit specifics of the order 10\\%. \nGiven that equilibrium temperature is proportional to \n$\\eta^{1/4}$ (see eq.~\\ref{eq:Teq} below), the implied temperature uncertainty due to 10\\% uncertainties \nin $\\eta$ factors is about 2.5\\%, or about 7 \\dC\\ assuming a typical temperature of 273 K. \n% The actual variation of a 2U CubeSat temperature along the orbit will have a much smaller amplitude \n% due to finite thermal inertia (discussed in detail further below and illustrated in Figure~\\ref{fig:Tt}). \n\nFor an orbit altitude of 550 km, for a spherical satellite $\\eta_S = 0.25$ and $\\eta_E =0.36$, while\nfor a 2U CubeSat $\\eta_S \\approx 0.21$ and $\\eta_E \\approx 0.36$. Therefore, given everything else same, \nthe equilibrium temperature for the spherical satellite will be slightly higher (typically of the order \n10 $^\\circ$C) than for the CubeSat because of 20\\% higher absorbed direct solar radiation. \n\n\n\\subsection{Typical numerical values of heat sources and sinks for 2U CubeSat} \n\nA ``randomly oriented'' 2U CubeSat is used for numerical analysis and illustration, with $A_{tot}=0.1$ m$^2$, $\\eta_S=0.21$,\nand $\\eta_E=0.36$. Numerical input assumptions include mean environmental parameters from \nTable~\\ref{tab:inputsEnvParam}, aluminum heat capacity $C=921$ J\\,kg$^{-1}$\\,K$^{-1}$, satellite \nmass $m=2.0$ kg, surfaces with $\\alpha_S=0.86$ and $\\epsilon_T=0.86$ (black anodized aluminum), \n$\\eta_{cell}=0.2$,  and a Sun-synchronous orbit with $h=550$ km (assumed orbital period of 90 minutes), \nwith $\\eta_P=0.33$ and $f_{alb}=0.62$. Note that these parameters do {\\bf not} correspond to any particular satellite.  \n\nWith these input parameters, $Q_{in}^{sun}=$40.1 W and $Q_{in}^{eclipse}$=11.1 W, with absorbed direct\nsolar radiation $Q_{sun}$=29.5 W, and with dissipated thermal power contributing a constant rate of\n$Q_{dissip}=$4.8 W. Absorbed direct solar radiation is about five times as large as absorbed\nreflected solar radiation, and larger by a similar factor than absorbed Earth's infrared emission. \nThe total battery energy charged and then dissipated during one orbital period is 7.2 Wh. \n\n\n\\subsection{High and low equilibrium temperatures} \n\nThe equilibrium temperature can be computed by assuming that the satellite is exposed to a constant \nheat source for an infinitely long time and thus $dT/dt=0$. It then follows from eqs.~\\ref{eq:dTdt} and \n\\ref{eq:Qout} that\n\\eq{\n\\label{eq:Teq}\n     T_{eq} = \\left(  {Q_{in} \\over A_{tot} \\, \\epsilon_T \\, \\sigma} \\right)^{1/4}. \n}\nNote that the equilibrium temperature does {\\bf not} depend on satellite's thermal inertia (the product of \nmass and heat capacity).  Because for a given geometry and orientation $Q_{in}$ is proportional to the\ntotal area $A_{tot}$, the equilibrium temperature does {\\bf not} depend on satellite's size either. \n\nAssuming $Q_{in}^{sun}=$40.1 W and $Q_{in}^{eclipse}$=11.1 W, the corresponding equilibrium temperatures\nare $T_{eq}^{sun}$ = 301.1 K  (27.9 $^\\circ$C) and $T_{eq}^{eclipse}$ = 218.6 K  ($-$54.6 $^\\circ$C).\nThis temperature range is {\\bf much larger} than satellite temperature variation expected for oscillatory \nheating in a typical orbit, as discussed next. \n\n\n\\subsection{Analytic solution for the temperature's return to its equilibrium value} \n\n \n\\begin{figure}[t]\n\\centering\n\\includegraphics[width=0.45\\textwidth, keepaspectratio]{figures/analyticUp.png}\n\\includegraphics[width=0.45\\textwidth, keepaspectratio]{figures/analyticDown.png}\n\\caption{The analytic solution for dimensionless temperature parameter $\\tau(t) = T(t)/T_{eq}$\nas a function of  dimensionless time parameter $t/t_o$ for initial conditions with $\\tau_o<1$\n(left) and $\\tau_o>1$ (right). Note that in both cases $\\tau(t)$ asymptotically approaches unity,\nthat is, $T(t)$ asymptotically approaches $T_{eq}$. \n\\label{fig:analytic}}\n\\end{figure}\n\n\n\nEquation~\\ref{eq:dTdt} is typically solved using numerical integration. When the heat source is constant\nin time, the solution can be obtained analytically. Equation~\\ref{eq:dTdt} can be recast using \neqs.~\\ref{eq:Qout}  and \\ref{eq:Teq} as \n\\eq{\n\\label{eq:dtaudx}\n               {d\\tau \\over dx }  = 1 - \\tau^4, \n}\nwhere $\\tau=T/T_{eq}$, $x=t/t_o$ and the time scale $t_o$ is given by \n\\eq{\n\\label{eq:t0}\n     t_o =   { C m \\over A_{tot} \\, \\epsilon_T \\, \\sigma \\, T_{eq}^3}. \n}\nThe derivative $d\\tau/ dx$ is positive when starting temperature $T_o=T(t=0)$ is\n$T_o < T_{eq}$. Thus, when $Q_{in} = Q_{in}^{sun}$ and $T_{eq} = T_{eq}^{sun}$, the temperature\nwill be increasing with time, while for $Q_{in} = Q_{in}^{eclipse}$ and $T_{eq} = T_{eq}^{eclipse}$\nthe derivative is negative and the temperature decreases with time.\n\nThe simplified dimensionless differential equation \\ref{eq:dtaudx} admits an implicit analytic \nsolution:\n\\eq{\n\\label{eq:analytic}\n{t \\over t_o} = {1\\over 2}\\left[\\arctan(\\tau) - \\arctan(\\tau_o)\\right] + {1\\over 4}\\left[\\ln\\left({\\tau+1\\over\\tau_o+1}\\right) - \\ln\\left({\\tau-1\\over\\tau_o-1}\\right) \\right], \n}\nwhere $\\tau_o = T_o/T_{eq}$ is the initial condition. When $t \\gg t_o$, $\\tau$ asymptotically approaches unity. \nFigure~\\ref{fig:analytic} illustrates solutions given by eq.~\\ref{eq:analytic} for both $\\tau_o<1$ and $\\tau_o>1$. \n\n\n\n\\subsection{Temperature variation for a bistable heat source} \n\n\n\\begin{figure}[t]\n\\centering\n\\includegraphics[width=0.31\\textwidth, keepaspectratio]{figures/3tempsVStime_DefaultsMassVariationMsmall.png}\n\\includegraphics[width=0.31\\textwidth, keepaspectratio]{figures/3tempsVStime_DefaultsMassVariationMdefault.png}\n\\includegraphics[width=0.31\\textwidth, keepaspectratio]{figures/3tempsVStime_DefaultsMassVariationMlarge.png}\n\\caption{The satellite orbital temperature variation as a function of the surface emissivity properties \nand thermal inertia. The satellite total surface area is 0.1 m$^2$ (similar to 2U CubeSat), with \neffective absorptive surfaces corresponding to a spherical satellite. Three different types of anodized \naluminum surfaces are modeled: black with $\\alpha_S, \\epsilon_T$  = (0.86, 0.86), blue: (0.67, 0.87)  \nand yellow: (0.47, 0.87).  The thermal inertia is controlled by the satellite mass; left: low (0.05 kg), \nmiddle: medium (2.2 kg), right: high (10 kg). The temperature variation is compared to a typical battery operating \ntemperature range (the blue horizontal band).  \n\\label{fig:Tt}}\n\\end{figure}\n\n\nNow consider a bistable heat source, such as a satellite in an orbit and the heat source periodically\nswitching between $Q_{in}^{sun}$ and $Q_{in}^{eclipse}$. Because corresponding equilibrium temperatures \n$T_{eq}^{sun}$ and $T_{eq}^{eclipse}$ are different, the implied time scales for the temperature's return to its\nequilibrium value, $t_o$ given by eq.~\\ref{eq:t0}, will be different, too. Eq. ~\\ref{eq:t0} implies that\nthe ratio of time scales in eclipse and when exposed to sunlight is \n\\eq{\n  { t_o^{eclipse} \\over t_o^{sun} }= \\left(Q_{in}^{sun} \\over Q_{in}^{eclipse} \\right)^{3/4} \\approx 3. \n}\n\nFor a bistable heat source, the temperature at the end of the rising phase must be equal to the\ntemperature at the start of cooling phase and vice versa. As a result of this condition, the \ntemperature will oscillate between two extremes, $T_{min}$ and $T_{max}$ with $T_{min} \\ge T_{eq}^{eclipse}$ \nand $T_{max} \\le T_{eq}^{sun}$.  Eq.~\\ref{eq:analytic} appears too cumbersome to derive closed-form\nanalytic solutions for  $T_{min}$ and $T_{max}$; in practice,  $T_{min}$ and $T_{max}$ are easily determined\nnumerically (see Appendix B). \n\nWhen thermal inertia is vanishing, the temperature will return to its equilibrium values essentially\ninstantaneously and most of the time the satellite temperature will be either $T_{eq}^{eclipse}$ or $T_{eq}^{sun}$. \nOn the other hand, for infinitely large thermal inertia the temperature will assume an equilibrium\nvalue that corresponds to the heat source averaged over the satellite orbit. For example, if the satellite \nspends one third of the orbital period in eclipse, then\n\\eq{\n\\label{eq:TeqAve} \n      T_{eq}^{ave} = \\left[ {1\\over 3} \\left(T_{eq}^{eclipse}\\right)^4 +  {2\\over 3} \\left(T_{eq}^{sun}\\right)^4 \\right]^{1/4}. \n}\nWith $T_{eq}^{sun} = 301.1$ K and $T_{eq}^{eclipse} = 218.6$ K,  $T_{eq}^{ave}$ = 281.1 K  (7.9 $^\\circ$C).  \nWith thermal inertia corresponding to heat capacity for aluminum ($C=921$ J\\,kg$^{-1}$\\,K$^{-1}$, see\nTable~\\ref{tab:inputsMatProp}), and satellite mass $m=2.0$ kg, the actual temperature extremes are $T_{min}$ = 272.4 K \n($-$0.8 $^\\circ$C) and $T_{max}$ = 289.1 K  (16.0 $^\\circ$C). Note that the $T_{max} - T_{min}$ difference  is about\nfive times smaller than the $T_{eq}^{sun}  - T_{eq}^{eclipse}$ difference. The variation of these extreme orbital \ntemperatures on various input parameters is discussed next. \n\n\n\\section{Numerical Examples} \n\nThis section explores the impact of variations in input parameters on the mean satellite temperature and the \namplitude of temperature variations.  The concept of hot and cold cases is also discussed. Note that numerical\nvalues of various parameters were chosen to be similar to 2U CubeSat parameters; however, they do {\\bf not}\ncorrespond to any particular satellite. \n\n\\begin{figure}[t]\n\\centering\n\\includegraphics[width=0.45\\textwidth, keepaspectratio]{figures/3tempsVStime_BlackAnodizedMassVariation.png}\n\\includegraphics[width=0.45\\textwidth, keepaspectratio]{figures/3tempsVStime_BlackAnodizedFsunVariation.png}\n\\includegraphics[width=0.45\\textwidth, keepaspectratio]{figures/3tempsVStime_BlackAnodizedChargingVariation.png}\n\\includegraphics[width=0.45\\textwidth, keepaspectratio]{figures/3tempsVStime_BlackAnodizedOrbitVariation.png}\n\\caption{The impact of thermal inertia (top left), solar flux variation (top right), solar cell efficiency (bottom left)\nand the eclipse duration (bottom right) on satellite orbital temperature variation (all for black anodized aluminum \nsurface with $\\alpha_S, \\epsilon_T$  = 0.86, 0.86). In the bottom left panel, it is assumed that a fraction of \nabsorbed solar radiation is used to charge batteries, and it is then dissipated as heat at a constant rate\nthroughout the orbit. In the bottom right panel, the no eclipse case corresponds to a polar orbit whose normal\nvector points to the Sun. The effective albedo is varied from 0.06 times its maximum value, as expected for such\nan orbit, to 0.6 times its maximum value, as expected for an orbit that includes subsolar point. The temperature variation \nis compared to a typical battery operating temperature range (0--40 $^\\circ$C, the blue horizontal band).  \n\\label{fig:Tt2}}\n\\end{figure}\n\n\n\\newpage\n\\subsection{The impact of thermal inertia on the amplitude of temperature variation} \n\nFigure~\\ref{fig:Tt} shows the satellite orbital temperature variation as a function of the surface emissivity\nproperties and thermal inertia. The temperature variation is computed using analytic solution given by\neq.~\\ref{eq:analytic} and emissivity properties corresponding to three different types of anodized aluminum \nsurfaces (see figure caption). It is assumed that the orbital period is 90 min, with the eclipse portion lasting \n30 min. The aluminium heat capacity is assumed and the thermal inertia is controlled by the satellite mass. \n\nFor low thermal inertia (left panel), the temperature displays large variation, drops quickly to the cold \nequilibrium temperature and rises back even faster to the hot equilibrium temperature. For very high\nthermal inertia (right panel) the temperature varies by only a few degrees around the value given by \neq.~\\ref{eq:TeqAve} (7.9 $^\\circ$C for black anodized Al surface). In the most realistic case shown in the \nmiddle panel, the temperature variation amplitude is 10--17 degrees, depending on the surface properties. \n\nThis behavior is similar to potatoes taken from a hot oven: small satellites would cool faster \nthan their scaled-up larger versions. However, here the difference in behavior is due to different \nthermal inertia for satellites that look identical from the outside (same size, shape and surface properties). \nInstead of small and large potatoes, a better analogy is solid and hollow potatoes of the same size.\n\nIt is important to recognize that some components within the satellite could achieve temperatures \nhigher than $T_{max}$ (components close to the locations of internal power dissipation) but {\\bf never\nlower} than $T_{min}$  (assuming steady-state after many cycles). To obtain temperature variation for \nindividual components, a professional tool (e.g., Thermal Desktop, Ansys) and detailed numerical \ncomputations need to be employed. Nevertheless, the essential impact of thermal inertia on the \namplitude of temperature variation will remain. Perhaps the most important conclusion of this \nsimplified analysis that pertains to detailed numerical modeling is that {\\bf a full transient model\nmust be employed to assess the temperature variation} between $T_{min}$ and $T_{max}$. The \nextreme equilibrium temperatures, $T_{eq}^{sun}$ and $T_{eq}^{eclipse}$ are {\\bf not} representative of the\nactual temperature variation experienced by the satellite. \n\nIn practice, the uncertainty in thermal inertia is much smaller than discussed in figure~\\ref{fig:Tt}.\nThe top left panel in figure~\\ref{fig:Tt2} shows that varying thermal inertia by $\\pm$30\\% \naround its mean value changes temperature predictions by about  5 $^\\circ$C. \n\n\n\\begin{figure}[t]\n\\centering\n\\includegraphics[width=0.45\\textwidth, keepaspectratio]{figures/3tempsVStime_BlackAnodizedShotVScold.png}    \n\\includegraphics[width=0.45\\textwidth, keepaspectratio]{figures/3tempsVStime_BlackAnodized2UareaVariation.png} \n\\includegraphics[width=0.45\\textwidth, keepaspectratio]{figures/3tempsVStime_BlackAnodized2UhotVScold.png} \n\\includegraphics[width=0.45\\textwidth, keepaspectratio]{figures/3tempsVStime_BlackAnodized2UhotVScoldExtreme.png} \n\n\\caption{The impact of choosing extreme values of environmental conditions (top left), varying geometry expressed\nthrough 20\\% variation of the absorptive surface area (top right), extreme values of environmental conditions when \nassuming 2U CubeSat satellite geometry with randomized orientation (bottom left, $\\eta_S=0.21$ and $\\eta_E=0.36$), \nand with orientation that maximizes the temperature range between these so-called ``hot'' and ``cold'' cases (bottom\nright, hot: $\\eta_S=0.30$ and $\\eta_E=0.38$; cold:  $\\eta_S=0.10$ and $\\eta_E=0.34$).  The temperature variation is \ncompared to a typical battery operating temperature range (the blue horizontal band).  \n\\label{fig:Tt3}}\n\\end{figure}\n\n\n\n\\subsection{The impact of  variable solar flux on predicted satellite temperature} \n\nDue to Earth's elliptical orbit around the Sun, the solar flux at Earth's location varies by about 3.6\\%\naround its mean value, between its maximum at winter solstice and its minimum at summer solstice\n(see Table~\\ref{tab:inputsEnvParam}). The top right panel in figure~\\ref{fig:Tt2} shows that this \nvariation changes the minimum and maximum temperatures by about 3-4 degrees. \n\n \n\\subsection{The impact of  battery charging on the amplitude of temperature variation} \n\nThe energy spent to charge on-board batteries is converted to chemical energy and subtracted\nfrom heat balance (see eq.~\\ref{eq:dTdt}). It is returned to heat balance in the form of resistive\nheat dissipation, at a constant rate as assumed here. Because the charging does not happen \nduring the eclipsed portion of the orbit, this dissipation effectively ``flattens'' the heat source \nvariation and decreases the amplitude of temperature variation. The bottom left panel in \nfigure~\\ref{fig:Tt2} shows that the conversion of 20\\% of incoming solar flux to battery charge\nand release as heat can decrease the amplitude of temperature variation by about 5 degrees\ncompared to no-battery case. \n \n\n\\subsection{The impact of  eclipse duration on the amplitude of temperature variation} \n\nGiven a fixed orbital period, the shorter is the eclipse the higher is the total accumulated\nenergy. The bottom right panel in figure~\\ref{fig:Tt2} compares two polar orbits, one whose \nnormal vector points to the Sun, with no eclipse, and another one that includes subsolar point\nand has one third of orbital period spent in eclipse. The impact on mean temperature is about \n10-15 degrees. Uncertainties in effective albedo contribute to the uncertainty in predicted\ntemperatures; when\nalbedo is varied from 0.06 times its maximum value, as expected for the first orbit with\nno eclipse, to 0.6 times its maximum value, the temperature is raised by another 10 degrees.\n\n\n\\subsection{The concept of hot and cold cases} \n\nDue to uncertainties in input parameters, including environmental, orbital and satellite parameters,\nengineering pre-launch analysis often focuses on the most extreme scenarios that predict the coldest \nand the hottest satellite temperatures. \n \nThe top left panel in figure~\\ref{fig:Tt3} compares the cold and hot cases for a spherical satellite, \nwith the extreme values of environmental parameters taken from Table~\\ref{tab:inputsEnvParam}. \nThe predicted temperature extremes differ by about 25 degrees.\n \nThe top right panel in figure~\\ref{fig:Tt3} explores the impact of uncertainties in orbital parameters \nand satellite orientation by varying $\\eta_E$ by 20\\% around its mean value (about twice as much \nas typical uncertainties for a 2U CubeSat). The predicted temperature extremes differ by about \n10 degrees.\n\nThe bottom left panel is analogous to the top left panel, except that typical values of $\\eta_S$\nand $\\eta_E$ for 2U CubeSat are used instead of values for a spherical satellite. \nNote that these parameters do {\\bf not} correspond to any particular satellite.  \nAs expected, the predicted temperatures are about 8 $^\\circ$C higher for the spherical satellite \nbecause of higher absorbed direct solar radiation. \n\nThe bottom right panel in figure~\\ref{fig:Tt3} pushes the comparison of hot and cold cases for \n2U CubeSat to its extreme. It is assumed that for hot case the satellite orientation is actively \ncontrolled so that during non-eclipsed portion its maximum possible projected area is always \npointing towards the Sun, while during the eclipse it's pointed towards Earth (see figure caption). \nFor cold case, the projected areas towards the Sun and Earth are minimized. The resulting\ntemperature extremes differ by as much as 80 degrees. It is noteworthy that it is possible\nto reverse this scenario. If the satellite orientation is such that  the projected areas are\nminimized for hot case, and maximized for cold case, the impact of environmental parameters \ncan be reversed and hot case can be made colder than cold case. In other words, {\\bf the satellite \norientation can be more important than the variation of environmental parameters.} \n\n\n\n\\section{Active temperature control \\label{sec:active}} \n\nGiven the allowed operating temperature ranges for satellite components (the most stringent requirement\ncomes from batteries, chosen here as 0--40 $^\\circ$C for illustration), these results imply that \nlow temperatures will be more worrisome than high temperatures. Motivated by this finding, we \nexplored a model for active temperature control.\n\nAs a concrete satellite example, we used SOC-i CubeSat developed at the University of Washington. \nAdopted parameter values are discussed and listed in Appendix D. \n\n\n\\subsection{A toy model for active temperature control } \n\nWe developed a toy model for active temperature control that assumes an additional internal power \ndissipation whenever the satellite temperature drops below a pre-defined threshold. Analytic solution\ngiven by eq.~\\ref{eq:analytic} is not applicable any more because the time dependence of heat source\nis now an unspecified function and numerical integration is used to obtain the solution\\footnote{Python\ncode and Jupyter notebooks are publicly available at https://github.com/ivezic/CubeSats}. Analytic \nsolution given by eq.~\\ref{eq:analytic} was used to validate the numerical solution code in case of bistable \nheat source. \n\nWe investigated cold case and three levels of power (2 W, 5, W, 10 W) that is applied whenever the temperature \ndrops below 273 K (0 $^\\circ$C). Results are shown in figure~\\ref{fig:SOCi2}. \nAdditional power can raise the satellite temperature by 5 to 11 degrees. The consumed power ranges\nfrom 1.9 Wh to 4.3 Wh, and it is under the total available battery power (5.6 Wh for cold case and\n$\\eta_{cell}=0.2$; for hot, extreme case, it could be boosted to 18 Wh with $\\eta_{cell}=0.3$). \nThese results show that such an approach is a viable method for mitigating low temperatures.\n\n\\begin{figure}[t!]\n\\centering\n\\includegraphics[width=0.3\\textwidth, keepaspectratio]{figures/TempsPlotCompare_SOCi-cold-heated2.png} \n\\includegraphics[width=0.3\\textwidth, keepaspectratio]{figures/TempsPlotCompare_SOCi-cold-heated5.png} \n\\includegraphics[width=0.3\\textwidth, keepaspectratio]{figures/TempsPlotCompare_SOCi-cold-heated10.png} \n\\caption{Illustration of the impact of active thermal control. A toy model assumes that whenever the satellite temperature\ndrops below zero $^\\circ$C (273 K), an additional heating source with power of 2 W (left),  5 W (middle), or 10 W (right) contributes\nto the heat balance. The blue lines correspond to the blue line in the left panel in figure~\\ref{fig:SOCi1} (cold case) and the \nred dashed line is the corresponding temperature prediction with this additional heating power. The consumed power is about \n1.9 Wh, 3.4 Wh and 4.3 Wh, respectively (the total available battery power is 5.6 Wh). \n\\label{fig:SOCi2}}\n\\end{figure}\n\n\n\n\n\n\\newpage\n\\section{Conclusions} \n\nWhen a body assumed to have a uniform temperature field is subjected to a bistable heat source,\nthere exists an analytic solution for the temperature variation with time. This simplified model is \nsuitable for addressing a variety of satellite thermal analysis problems: studying the relative effects \nof surfaces with different emissivities, the effects of small changes in the solar flux between June \nand December, the impact of thermal inertia on predicted amplitude of temperature variation, and \nas a ``sanity check'' for the results obtained with numerical thermal models that utilize detailed \ngeometrical and thermal descriptions of all satellite components. \n\nBrief examples of such studies are presented here. The most notable conclusions for further,\nmore detailed studies with numerical tools, include:\n\\begin{itemize}\n\\item The mean satellite temperature depends on the extreme values of steady-state equilibrium \n    temperatures for eclipsed and non-eclipsed parts of the orbit, and the duration of the eclipse\n    relative to the orbital period (see eq.~\\ref{eq:TeqAve}). \n\\item The amplitude of temperature variation around the mean temperature is by and large \n     controlled by the satellite thermal inertia (see figure~\\ref{fig:Tt}).\n\\item Although one might naively think that the satellite temperature is lower during the eclipse\n    than when the satellite is exposed to direct sunlight, the satellite temperature range is {\\bf identical} \n    for these two orbital phases because of cyclic boundary condition (unless the thermal inertia \n    is unrealistically low). \n\\item Satellites with non-spherical geometry can be modeled within the same framework with \n    judiciously chosen effective surface areas, parametrized with $\\eta_S$ and $\\eta_E$\n    (see eq.~\\ref{eq:Qsun} and Appendix A). \n\\item For non-spherical satellites, such as 2U CubeSat, the satellite orientation can have a\n    significant impact on the predicted temperatures; indeed, with active 2U CubeSat orientation \n    control, the impact of environmental variations could be mitigated entirely (i.e., ``hot case'' \n    achieving lower temperatures than ``cold case''). \n\\item {\\bf Model uncertainties, including uncertainties in input parameters, result in uncertainties\n   of predicted temperatures of at least 10 $^\\circ$C!} \n\\end{itemize} \n\nSince it appeared that low temperatures will be more concerning than high temperatures,\nwe also explored a toy model for active temperature control that assumes an additional internal \npower dissipation whenever the satellite temperature drops below a pre-defined threshold. \nWe found out that such an approach is a viable method for mitigating low temperatures.\n\nThe latex source for this document, and the supporting python code for evaluating analytic and\nnumerical models and producing all the plots presented here, are publicly available\\footnote{https://github.com/ivezic/CubeSats}. \n\n\n\\vskip 0.2in \n%\\newpage \n\\leftline{\\bf Acknowledgments} \nAn initial version of the code for obtaining a numerical solution of the differential equation \\ref{eq:dTdt} was \ncontributed by Haley Stewart (University of Washington). I thank the University of Washington SOC-i team, in \nparticular Boone Tate, Henry Brown and Charlie Kelly, for access to technical parameters describing their \n2U CubeSat named SOC-i. Without seeing their enthusiasm, I would have never written this paper. \n \n\n%\\bibliographystyle{aasjournal}\n%\\bibliography{ref}{}\n%\\input{appendix}\n\n\\vskip 0.2in \n\\leftline{\\bf References}\nGilmore, D. 2002, ``Spacecraft Thermal Control Handbook: Fundamental Technologies'', 2nd ed. Aerospace Press \n\nJacques, L. 2009, ``Thermal Design of the Oufti-1 Nanosatellite'', Master Thesis, University of Liege\n\n\n%\\newpage\n\\appendix{}\n\n\\vskip 0.2in\n\\leftline{\\bf A. Effective area for the absorption of radiation from Earth}\n\n\\vskip 0.1in\n Effective area for the absorption of radiation from Earth can be computed using geometric radiative viewing factors\n(and remembering that the factor $f_E$ is explicitly included in eq.~\\ref{eq:Qref}). \n\nFor a spherical satellite, \n\\eq{\n                  \\eta_E  =  {1\\over 2}  \\left(1 - \\sqrt{1- f_E} \\right) \\, f_E^{-1},\n} \nwhere $f_E=[R_E/(R_E+h)]^2$, with Earth's radius $R_E=6,378$ km and $h$ is the satellite's altitude. As $h$\nincreases, $\\eta_E$ for sphere varies from 1/2 to 1/4; for $h=550$ km, $\\eta_E=0.36$.\n\nFor CubeSat satellites, $\\eta_E$ can be obtained as the sum of values for all 6 sides because the viewing\nfactors are additive. For a flat surface whose normal is at angle $\\beta$ relative to Earth's surface, \n\\eq{\n            \\eta_E  = \\cos(\\beta), \n} \nfor $|\\beta|\\le\\arccos(\\sqrt{f_E})$, and otherwise\n\\eq{\n            \\eta_E  = \\pi^{-1} \\left[ \\left( \\cos(\\beta)\\arccos(y) - x \\,z \\, \\sin(\\beta) \\right) + f_E^{-1} \\, \\arctan(x^{-1} \\, y \\, \\sin(\\beta)) \\right] \n} \nwhere $x=\\sqrt{f_E^{-1}-1}$, $y=-x\\tan(\\beta)^{-1}$ and $z=\\sqrt{1-y^2}$. The same expressions can\nbe used to compute $\\eta_S$ for CubeSat satellites by setting $h$ to a very large value. \n\nFor randomly oriented CubeSat satellites, $\\eta_S \\approx 0.21$ and $\\eta_E \\approx 0.36$ for both 1U and 2U versions,\nwith a scatter of about 10\\% around these mean values for realistic orientations. For 2U CubeSat\nwith $h=550$ km, the possible ranges are  $\\eta_S = 0.10 - 0.30$ and $\\eta_E = 0.34 - 0.38$. \n\n\\vskip 0.2in\n\\leftline{\\bf B. A method for enforcing cyclic boundary condition for equation~\\ref{eq:dTdt}}\n\n\\vskip 0.1in\nGiven the orbital period and eclipse duration, two cooling time scales $t_o$ (see eq.~\\ref{eq:t0}) and two \nsteady-state equilibrium temperatures $T_{eq}^{sun}$ and $T_{eq}^{eclipse}$, there are four unknowns to \nbe solved for: $\\tau_o^C$, $\\tau_f^C$, $\\tau_o^H$, and $\\tau_f^H$, where $\\tau=T/T_{eq}$, subscripts \n$o$ and $f$ correspond to the initial and final values, and superscripts $C$ and $H$ correspond to \neclipsed and non-eclipsed parts of the orbit. \n \nTwo equations come from the cyclic boundary condition that the final temperature for the $C$ phase\nmust be equal to the initial temperature for the $H$ phase, and vice versa\n\\eq{\n\\label{eq:taueqs}\n     \\tau_o^H = C_1 \\,\\tau_f^C \\,\\,  \\,\\,   {\\rm and} \\,\\, \\,\\,   \\tau_f^H = C_1 \\, \\tau_o^C,\n} \nwhere $C_1 =  T_{eq}^{eclipse}/T_{eq}^{sun} \\le 1$. The remaining two equations come\nfrom applying eq.~\\ref{eq:analytic} to $C$ and $H$ phases, where the left side is known and the right\nhand side involves $\\tau_o^C$ and $\\tau_f^C$, and $\\tau_o^H$ and $\\tau_f^H$, respectively. \n\nAfter substituting eqs.~\\ref{eq:taueqs} into two eqs.~\\ref{eq:analytic}, the resulting system of \ntwo equations with two unknowns is easily solved numerically.  In case of numerical solution\nfor an arbitrary time dependence of the heating source, the cyclic boundary condition is satisfied\nusing iterations (usually only a few iterations are sufficient). \n\n%\\vskip 0.2in\n\\newpage\n\\leftline{\\bf C. Model parameters for the University of Washington SOC-i CubeSat}\n\nThe University of Washington SOC-i\\footnote{A nod toward the Pacific Northwest salmon.}  \n(the Satellite for Optimal Control and Imaging)  project\\footnote{https://www.aa.washington.edu/news/article/2019-02-11/cubesat-team}\nhas a specific mission to demonstrate the ability to satisfy two constraints with its orientation\ncontrol and imaging systems. It was selected by NASA CubeSat Launch Initiative for launch in\n2022 or 2023. We use it here as a specific example to quantitatively demonstrate the impact\nof active temperature control on the satellite's minimum temperature. \n\n\\vskip 0.1in \n\\leftline{\\bf Input satellite parameters}\n\nWe used the SOC-i CAD model\\footnote{I am grateful to Boone Tate for extracting the model parameters.} \ndeveloped for structural analysis to extract information about\nexternal satellite surfaces and their material properties. We adopted the following description \nof external SOC-i surfaces: \n\\begin{itemize}\n\\item  Top: 60\\% solar panel, 40\\% aluminum frame\n\\item  Bottom: 38\\% aluminum frame, 62\\% PCB (printed circuit board). \n\\item  Sides (2): 64\\% solar panels, 19\\% aluminum panels (outside), 17\\% aluminum frame rails\n\\item  Sides (2): 57\\% solar panels, 26\\% aluminum panels (outside), 17\\% aluminum frame rails\n\\end{itemize}\n\nWith the values of absorptivity and emissivity listed in Table~\\ref{tab:inputsAbsEmiss}, we obtained\ntheir surface-weighted values $\\alpha=0.83$ and $\\epsilon=0.79$ (54\\% of external surface area\nis covered by solar panels). In addition, we assumed that the satellite mass is $m=2.6$ kg and \nadopted specific heat corresponding to aluminum ($C=768$  J\\,kg$^{-1}$\\,K$^{-1}$), yielding a\nthermal intertia of $mC = 2.00$ kJ\\,K$^{-1}$ (we note that a more accurate value of thermal inertia \ncan be obtained by summing the $mC$ product for all individual structural components\nin the SOC-i CAD model). \n\n\\begin{table}[t]\n\t\\centering\n\t\\caption{Surface optical absorptivity and infrared emissivity for SOC-i surface materials. }\n\t\\label{tab:inputsAbsEmiss}\n\t\\begin{tabular}{r|r|r|r|r|r} % \n\t\t\\hline\n  \t              Part        &                Surface          &    $\\alpha$  &   $\\epsilon$    &   $k$ (W\\,m$^{-1}$\\,K$^{-1}$)   &  $C$ (J\\,kg$^{-1}$\\,K$^{-1}$)  \\\\\n\t  \t\\hline\n         Solar panels        &       GaAs, with AR coating  &           0.92      &          0.85      &   60.6    &      324   \\\\  \n     Al panels, outside   &     7075 Al, Kapton             &           0.87       &         0.81       &  121.2   &    801   \\\\ \n          Al frame rails    &       5052 Al, hard anodized &          0.86        &        0.86      &    138.5   &    768    \\\\  \n                Al frame      &       5052 Al, alodine            &          0.08        &        0.15       &   138.5   &    768    \\\\\n                PCBs            &               FR4                        &           0.81       &         0.90        &   18.0  &    1544  \\\\ \n \t\t\\hline     \n\t\\end{tabular} \n\\end{table}\n \n\n\\vskip 0.1in \n\\leftline{\\bf Assumptions for orbital parameters}\n\nIt is already known that SOC-i will have a nearly-polar sun-synchronous \norbit\\footnote{See https://en.wikipedia.org/wiki/Sun-synchronous\\_orbit} \nwith an altitude of $h=550$ km and orbital inclination of 97.7 degrees. A satellite in sun-synchronous \norbit passes over any given point of the planet's surface at the same local mean solar time because the \norbit precesses through one complete revolution each year (that is, the orbit always maintains the same \nrelationship with the Sun). \n\nThe eclipse duration for sun-synchronous orbits depends on their right ascension of the \nascending node (RAAN), which will not be known until the launch date (RAAN is determined\nby the exact launch time). The orbital period for sun-synchronous orbit with an altitude of \n$h=550$ km is 96 mins, and the maximum eclipse duration is 36 mins.  When the orbital \nplane is perpendicular to incoming solar radiation, there is no eclipse (the satellite is following \nthe terminator line at all times). \n\n\n\n\\vskip 0.1in \n\\leftline{\\bf Hot and cold cases} \n\nWe define ``hot'' and ``cold'' cases by first adopting \nthe extreme values of environmental parameters from Table~\\ref{tab:inputsEnvParam}. \nIn addition, we make an assumption that the orientation of SOC-i's sun-synchronous orbit\nresults in an eclipse with maximum duration (36 min) for cold case, and no eclipse at all for \nhot case. \n\nThe intensity of solar radiation reflected from Earth varies along the orbit. For a polar \norbit passing through subsolar point, $f_{alb}=0.62$ for the non-eclipsed part of the orbit, while \nfor a polar orbit aligned with the terminator (with no eclipse), $f_{alb}=0.06$. Therefore, \nwe adopt $f_{alb}=0.62$ for hot case and $f_{alb}=0.06$ for cold case (note that reflected solar \nradiation contributes more flux for cold case, when not in eclipse). \n \nWith these assumptions, we compute incoming heating flux.\nFor cold case, the only heating flux during the eclipsed portion of the orbit is IR flux from Earth. \nThe variation of flux between hot and cold cases for three main heat sources is summarized in \nTable~\\ref{tab:inputflux}. Note that reflected solar flux is smaller for hot case but this difference\nis compensated by the absence of eclipsed orbital portion in hot case. \n\nTable~\\ref{tab:inputflux} lists absorbed flux per unit area, assuming SOC-i's effective \nabsorption coefficient ($\\alpha$). The listed value are also appropriate for detailed \nAnsys-based modeling, but need to be corrected for $\\alpha$ of each surface material.\nThe actual absorbed power (absorbed energy per unit time) depends on \nthe values of $\\eta_S$ and $\\eta_E$, which in turn depend on orientation. We make additional \nassumptions about satellite orientation, as discussed next. \n\n\\begin{table}[t]\n\t\\centering\n\t\\caption{Absorbed flux ($\\alpha=0.83$) for hot and cold cases (in  Wm$^{-2}$). }\n\t\\label{tab:inputflux}\n\t\\begin{tabular}{r|r|r|r} % \n\t\t\\hline\n  \t                    Quantity  & hot case   &   cold  case &   ratio hot/cold    \\\\\n\t\t\\hline\n              Direct solar flux    &    1181        &     1098         &     1.08       \\\\\n           Reflected solar flux  &     21.0        &     144.2        &     0.15     \\\\    \n                       Earth IR flux  &   174.6       &     147.8        &     1.18      \\\\\n\t\t\\hline\n\t\\end{tabular} \n\\end{table}\n\n\n\n\\vskip 0.1in \n\\leftline{\\bf Assumptions for satellite orientation}\n\nThe satellite orientation determines effective surface areas for the absorption of radiation from \nthe Sun and Earth. For convenience, these surface areas are expressed relative to the total surface area, $A_{tot}$\n(=0.1 m$^2$ for SOC-i), using $\\eta$ factors ($\\eta_S$ and $\\eta_E$, respectively).  \nWe used results discussed in Section 2.4 to adopt the following values for SOC-i.\n\nWhen averaged over plausible orientations and orbits, $\\eta_S = 0.21$ and $\\eta_E = 0.36$, \nwith an uncertainty due to actual orbit specifics of the order 10\\%. The limits of \npossible ranges are  $\\eta_S = 0.10 - 0.30$ and $\\eta_E = 0.34 - 0.38$. The limits for \n$\\eta_S$ reflect the range of projected area towards plane-parallel rays for 2U CubeSat geometry, \nwith the minimum value corresponding to one small side oriented perpendicularly to the incoming \nsolar radiation. For $\\eta_E$, the variation is much smaller because typically all six sides can \n``see'' Earth's surface\\footnote{We note that even for spherical geometry $\\eta_S$ and $\\eta_E$\nare generally different:  $\\eta_S=1/4$, while $\\eta_E$ decreases from 1/2 to 1/4 as the orbit\naltitude varies from zero to infinity.}. \n \nWe do not adopt specific satellite orientation for hot and cold cases but instead explore two \noptions in each case.  First, we adopt averaged orientations for both hot and cold cases,\nwith $\\eta_S = 0.21$ and $\\eta_E = 0.36$ corresponding to 2U CubeSat values. As the second \nassumption, we consider the following extreme cases: $\\eta_S = 0.30$ and $\\eta_E = 0.34$ for \nhot case, and $\\eta_S = 0.10$ and $\\eta_E = 0.38$ for cold case.  \n \nThe second set of values assumes that the satellite orientation is actively controlled.  For hot\ncase, the maximum possible projected satellite area for plane-parallel rays is always pointing \ntowards the Sun ($\\eta_S = 0.30$). For cold case and during non-eclipsed portion, the smallest \nsatellite side is always pointing towards the Sun ($\\eta_S = 0.10$).  The adopted values of \n$\\eta_E$ are its extreme values. \n\n \n\\vskip 0.1in \n\\leftline{\\bf Assumptions for internal power dissipation}\n\n\nA fraction of absorbed optical flux (the sum of direct solar flux and reflected solar flux) is often \nused to charge on-board batteries. We assume that 20\\% of absorbed flux\\footnote{Here, $\\eta_{cell}$ \nrepresents the fraction of all absorbed radiation that was converted to battery charge. For example, if \nthe cells occupy 2/3 of all external surfaces, and the cell conversion efficiency is 30\\%, then $\\eta_{cell}$= 0.2. \nFor randomized orientiations, it's only ``effective'' quantities that count in the model considered here; \nhowever, when a specific satellite orientation is known, one could incorporate information about where \nexactly the solar cell panels are positioned, too.} is converted into chemical\nenergy ($\\eta_{cell}=0.2$). This energy is returned back at a constant rate as internal heat dissipation. \n\nIn hot case, satellite is always exposed to the Sun and there is {\\bf no net effect} within the context\nof single-temperature model considered here. In reality, and in detailed Ansys models, this\ninternal heat dissipation can modify the temperature distribution within the satellite (areas closer\nto the heater will have elevated temperature). In cold case, the effect of internal heat dissipation\nis to {\\bf minimize} the amplitude of temperature variation, or equivalently, to {\\bf raise the minimum\ntemperature} (at the end of eclipsed portion). \n \nThese assumptions complete the specification of SOC-i hot and cold thermal models.  \n\n\\begin{table}[t]\n\t\\centering\n\t\\caption{Absorbed power (in Watt) and equilibrium temperatures for hot and cold SOC-i cases. }\n\t\\label{tab:powertemp}\n\t\\begin{tabular}{r|r|r|r|r} % \n\t\t\\hline\n  \t                    Quantity          & hot, random   &  hot, extreme &   cold, random  & cold, extreme   \\\\\n\t\t\\hline\n           Absorbed direct solar         &  24.8        &  36.6     &  23.1         &  11.0      \\\\\n           Absorbed Earth albedo       &    0.8        &    0.8   &     5.2           &  4.9      \\\\    \n               Absorbed Earth IR           &    6.3        &    6.6     &     5.3        &  5.0     \\\\\n             Internal dissipation           &    5.1        &   7.5     &     3.5         &  2.0     \\\\\n\t\t\\hline \n             Total input in eclipse       &     ---      &   ---   &     8.9       &    7.0  \\\\\n              Total input in sun            &    31.8      &   44.0  &   31.4        &  19.7  \\\\\n\t\t\\hline\n              Equilibrium T in eclipse  &     ---     &    ---   &    211       &   199 \\\\\n              Equilibrium T in sun       &      290      &   315   &    289        &  257  \\\\\n \t\t\\hline\n                    $T_{min}$  (K)               &      290      &   315   &   259       &  235  \\\\\n                   $T_{max}$  (K)               &      290      &   315   &   274        &  244  \\\\\n\t\t\\hline\n                    $T_{min}$  ($^\\circ$C)   &       16.7         &  41.5             &  {\\bf   $-$14.2  }  &  {\\bf  $-$37.6}  \\\\\n                   $T_{max}$  ($^\\circ$C)    &  {\\bf  16.7  }  &    {\\bf  41.5}  &        1.3      &  $-$28.9   \\\\\n\t\t\\hline\n\t\\end{tabular} \n\\end{table}\n\n \n\n\n\\vskip 0.1in \n\\leftline{\\bf Predicted absorbed power and equilibrium temperatures for hot and cold cases} \n\n\nGiven all the input assumptions described above, it is straightforward to solve the\ngoverning equation with direct numerical integration. Table~\\ref{tab:powertemp} lists predicted \nabsorbed power for all four modeled cases.  We note that the total energy stored in batteries, and \ndissipated as heat at a constant rate, ranges from 3.2 Wh for cold, extreme case to 12 Wh for hot, \nextreme case. \n\n\\end{document}\n ", "meta": {"hexsha": "e3e97a14c008d261d9fc06f62d6e662490f2bce5", "size": 60498, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/cubsats.tex", "max_stars_repo_name": "ivezic/CubeSats", "max_stars_repo_head_hexsha": "b392124c8481b10721008184b884fe488801b0bf", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paper/cubsats.tex", "max_issues_repo_name": "ivezic/CubeSats", "max_issues_repo_head_hexsha": "b392124c8481b10721008184b884fe488801b0bf", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/cubsats.tex", "max_forks_repo_name": "ivezic/CubeSats", "max_forks_repo_head_hexsha": "b392124c8481b10721008184b884fe488801b0bf", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.6627218935, "max_line_length": 191, "alphanum_fraction": 0.7235776389, "num_tokens": 16180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.3445189262749576}}
{"text": "\\documentclass[pdftex,12pt,a4paper]{article}\n\n\\usepackage[pdftex]{graphicx}\n\n\\newcommand{\\HRule}{\\rule{\\linewidth}{0.5mm}}\n\n\\begin{document}\n\t\\input{./title.tex}\n\t\n\t\\tableofcontents\n\t\\newpage\n\t\n\t\\section{Problem Statement}\n\t\tUsing the movielens ml-100k data set, build a system that predicts for an unknown user (whose simple demographics are\navailable):\n\t\t\\begin{itemize}\n\t\t\t\\item Whether the user is likely to see a given movie.\n\t\t\t\\item And if the answer to the above is Yes then the star rating (on a scale of 1 to 5) that the user will most likely give to the movie.\n\t\t\\end{itemize}\n\t\n\t\\section{Challenges}\n\t\tToday's world is full of choices across all product categories which makes it important for consumers to always make a better choice. Recommender systems were created to solve this need and have revolutionalized e-commerce and advertising. Movie recommendation systems study a user's movie viewing and rating history and intelligently predict the genre of movies that a particular user might prefer and the rating he might give to a movie. This provides a powerful tool to both movie viewers and distributers. In a movie recommender system there can be several challenges:\n\t\t\\begin{itemize}\n\t\t\t\\item If a movie has very few ratings, it is difficult to predict recommendations on it.\n\t\t\t\\item Users have varying rating patterns. Some users give an average rating to almost all movies while some always give extreme ratings. Still others show a spread from 1 to 5. Some users give higher ratings to some directors and stars.\n\t\t\t\\item There can be attributes which are not given in the existing data set but which contribute to a user's rating.\n\t\t\\end{itemize}\n\t\n\t\\section{Related Work}\n\t\tEarlier works~\\cite{Schein2002,MarlinThesis2004} have implemented several techniques like K-Nearest Neighbour classifiers, Naive Bayes classifiers and K-Medians clustering to make recommendations on this same dataset and to compare the results to Probabilistic and Collaborative prediction techniques. The most effective techniques for movie recommendation on this dataset have been Collaborative Filtering~\\cite{Sarwar2001,Agarwal2009} and other matrix factorization methods~\\cite{CoTriFactor2009}. MovieLens itself uses collaborative filtering to make recommendations~\\cite{Herlocker1999}.\n\t\n\t\\section{DataSet Review}\n\t\tThe data set consists of entries for 943 users, 1,682 movies and 100,000 ratings. Demographic data of the users has also been provided and includes age, gender, occupation and zipcode. The genre of the movies and some other information about the movies is also provided.\n\t\n\t\\section{Methodology}\n\t\tWe are using Collaborative Filtering to provide movie recommendations. The rating $r$ which we predict for a movie $i$ by a user $u$ will be an aggregation of ratings given by top N users who are most similar to user $u$ and rated movie $i$.\n\t\t\\begin{center}\n\t\t\t$r_{u,i} = aggr_{u^\\prime \\in U} r_{u^\\prime, i}$\n\t\t\\end{center}\n\t\twhere $U$ is the set of all users except $u$.\\\\\\\\\n\t\tFor finding the most similar N users, we will use either the Pearson correlation similarity between two users x, y which is:\n\t\t\\begin{center}\n\t\t\t$simil(x,y) = \\frac{\\sum\\limits_{i \\in I_{xy}}(r_{x,i}-\\bar{r_x})(r_{y,i}-\\bar{r_y})}{\\sqrt{\\sum\\limits_{i \\in I_{xy}}(r_{x,i}-\\bar{r_x})^2\\sum\\limits_{i \\in I_{xy}}(r_{y,i}-\\bar{r_y})^2}}$\n\t\t\\end{center}\n\t\tor the cosine similarity which is:\n\t\t\\begin{center}\n\t\t\t$simil(x,y) = \\frac{\\sum\\limits_{i \\in I_{xy}}r_{x,i}r_{y,i}}{\\sqrt{\\sum\\limits_{i \\in I_{xy}}r_{x,i}^2}\\sqrt{\\sum\\limits_{i \\in I_{xy}}r_{y,i}^2}}$\n\t\t\\end{center}\n\t\twhere $I_{xy}$ is the set of movies rated by both users x and y.\\\\\\\\\n\t\tWhile both of these are memory based approaches, we might also go for model based approaches. The similarity functions can be used to find similarity between both users and movies. The final recommeder system will handle 2 tasks:\n\t\t\\begin{itemize}\n\t\t\t\\item Recommendation: Will the user like a movie? This can either be given as a confidence measure or as a simple yes or no answer by keeping a threshold on the confidence measure. For this, we will first find out some N similar users to our new user using user attributes if the user is completely new or using user attributes and past history if he has rated some movies. Based on this we will recommend a movie.\n\t\t\t\\item Prediction: If the user will view a movie, what rating will he give to it? This will be a number from 1 to 5. This will also take into account ratings the user has given to similar movies.\n\t\t\\end{itemize}\n\n\t\\bibliographystyle{amsplain}\n\t\\bibliography{references}\n\\end{document}", "meta": {"hexsha": "c86ea53f92cadbd9c8f608d510fdda1a8c540f4f", "size": 4597, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Reports/Initial Report/Group_11_Project_Proposal.tex", "max_stars_repo_name": "kracwarlock/Movie-Recommender-and-Score-Prediction-System", "max_stars_repo_head_hexsha": "4298a8e3a8e621fff76f7c751e5ec64f8f6ad67b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2016-02-23T23:17:06.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-17T10:55:10.000Z", "max_issues_repo_path": "Reports/Initial Report/Group_11_Project_Proposal.tex", "max_issues_repo_name": "kracwarlock/Movie-Recommender-and-Score-Prediction-System", "max_issues_repo_head_hexsha": "4298a8e3a8e621fff76f7c751e5ec64f8f6ad67b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Reports/Initial Report/Group_11_Project_Proposal.tex", "max_forks_repo_name": "kracwarlock/Movie-Recommender-and-Score-Prediction-System", "max_forks_repo_head_hexsha": "4298a8e3a8e621fff76f7c751e5ec64f8f6ad67b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-09-27T18:04:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-29T03:23:51.000Z", "avg_line_length": 79.2586206897, "max_line_length": 593, "alphanum_fraction": 0.7624537742, "num_tokens": 1223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.3445189176770466}}
{"text": "% A '%' character causes TeX to ignore all remaining text on the line,\n% and is used for comments like this one.\n% All LaTex files require the commands:\n% \\documentclass (with argument)\n% \\begin{document} command\n% \\end{document} command\n\n% specifies the document class. We usually use article but there are others. \n\\documentclass{article}   \n\n% these are standard packages used for the math symbols\n\\usepackage{amsmath,amssymb,amsthm, graphicx, color, gensymb,mathpazo, enumitem}\n\n% These commands below is to make sure the numbering of these are consistent with theorem\n% If you are not sure what something means, delete them, build a new file and see the\n% difference between the files. You can ignore this part for now.\n\\newtheorem{theorem}{Theorem}[section]\n\\newtheorem{conjecture}[theorem]{Conjecture}\n\\newtheorem{observation}[theorem]{Observation}\n\\newtheorem{definition}[theorem]{Definition}\n\\newtheorem{corollary}[theorem]{Corollary}\n\\newtheorem{lemma}[theorem]{Lemma}\n\\newtheorem{example}[theorem]{Example}\n\\newtheorem{remark}[theorem]{Remark}\n\\newtheorem{notation}[theorem]{Notation}\n\n\n\\begin{document}\n\n% Title of my document\n\\title{\\Large Infinite Stream of Electrons}\n\n% The author command places text right after title\n\\author{Prannaya Gupta}\n\\date{\\today}\n\\maketitle\n\n\\section{Question}\nLet's say you have devised a system called the \"Stop-Time-inator\" that has allowed you to momentarily stop time. In that moment, no effect of force is seen but the force you yourself apply, and your physical body does not age. You thus stop time and open up a dimension, let's just call this the Cartesian Dimension, where it's just a single infinite plane with no gravitational force present. You enter it, starting at a certain origin which is assumed to be the centre of this dimension. From here, you can also see four paths around you, representing the positive and negative x-axis and positive and negative y-axis of the Cartesian Coordinate plane. Now, in stopped time, you get to work.\n\\\\\n\\\\\nYou bring along a device called the \"Charged-Particle-inator\" which releases a charged particle of charge q, set by the user. Now, you place your hand on the knob and cover the dial so that you cannot see the charge q that you set. You turn the knob and release it. Let's say this charge is denoted as a value $q_o$.\n\\\\\n\\\\\nNow, you decide to do very interesting thing: you use the python random module to generate a random integer between 2 and a super large number. You label this value as k in the interpreter, but do not check what k is. Now you load this values of k into a \"Move-inator\", which allows you to go to a specific x and y with respect to the assumed origin. What this \"Move-inator\" now does is it sends the \"Charged-Particle-inator\" to points ($k^n$, $k^n$) for all n from 0 to infinity (let's just assume that the \"Move-inator\" is able to do this within the stopped time) and releases one charge there.\n\\\\\n\\\\\nNow it returns, and you haven't died (consider yourself lucky). Now you have set the Move-inator to go to the points ($-k^n$, $-k^n$) for all n from 0 to infinity (again, let's just assume that the \"Move-inator\" is able to do this within the stopped time), and to each n, it swaps another charge knob that toggles the charge between positive and negative while keeping the magnitude intact (i.e. at ($-k^0$, $-k^0$), a negative charge of $q_o$ is released, while at (-k, -k), a positive charge of $q_o$ is released and so on). \n\\\\\n\\\\\nNow you use another device you have created called the \"Uncharge-inator\" and use it to completely discharge yourself, and then another called the \"Charge-inator\" to charge yourself to the same $q_o$ which you still do not know. Now you relocate to the assumed origin and stop the the \"Stop-Time-inator\". What is the acceleration that you, a 60-year old esteemed physicist who has spent years devising this complex system and has a mass of m, experience?\n\n\\begin{enumerate}[label=\\uppercase\\alph*)]\n  \\item $\\frac{q_o}{4\\pi\\epsilon_0} \\frac{k^2}{m(k^4 - 1)}$, facing north-east\n  \\item \\textbf{$\\frac{q_o}{4\\pi\\epsilon_0} \\frac{k^4}{m(k^4 - 1)}$, facing south-west}\n  \\item $\\frac{q_o}{4\\pi\\epsilon_0} \\frac{k^4}{m(k^4 - 1)}$, facing north-east\n  \\item $\\frac{q_o}{4\\pi\\epsilon_0} \\frac{k^2}{m(k^4 - 1)}$, facing south-west\n\\end{enumerate}\n\n\\newpage\n\\section{Solution}\n\nTo calculate this, you must use the formula \n\n\\begin{align*}\nF &= \\frac{1}{4\\pi\\epsilon_0} \\frac{Qq}{r^2}\n\\end{align*}\n\\\\\nHere, we know that Q and q are both equal to $q_o$, which you already know as a constant, but the direction may change based on the charge of the charges dropped by the \"Charged-Particle-inator\". Thus, you extract it as \n\\\\\n\\begin{align*}\nF &= \\frac{q_o}{4\\pi\\epsilon_0} \\frac{1}{r^2}\n\\end{align*}\n\\\\\nTo calculate $r^2$, what you do is you calculate based on the points as given. From this we have $r^2 = k^{2n} + k^{2n} = 2k^{2n}$.\n\\\\\\\\\nWe thus derive a series representing the force exhibited for the positive direction (i.e. x and y are both positive) \n\\\\\n\\begin{align*}\nF_1 &= \\frac{q_o}{4\\pi\\epsilon_0}(\\frac{1}{2k^0} + \\frac{1}{2k^2} + \\frac{1}{2k^4} + ...)\n\\end{align*}\n\\\\\nwhich faces south-west.\n\\\\\n\\\\\nMeanwhile, we can also derive a similar series representing the force exhibited for the positive direction (i.e. x and y are both positive) \n\\\\\n\\begin{align*}\nF_2 &= \\frac{q_o}{4\\pi\\epsilon_0}(\\frac{1}{2k^0} - \\frac{1}{2k^2} + \\frac{1}{2k^4} - ...) \n\\end{align*}\n\\\\\nwhich faces south-west as well.\n\\\\\n\\\\\nWe add these two forces up and we get\n\\\\\n\\begin{align*}\nF_{net} &= \\frac{q_o}{4\\pi\\epsilon_0}(\\frac{1}{k^0} + \\frac{1}{k^4} + \\frac{1}{k^8} + ...)\n\\end{align*}\n\\\\\n which faces south-west.\n\\\\\n\\\\\nNow, I would like to divert to derive an expression for\n\\\\\n\\begin{align*}\nS &= \\frac{1}{k^0} + \\frac{1}{k^4} + \\frac{1}{k^8} + ...\n\\end{align*}\n\\\\\n\\\\\nTo do this, we derive \n\\\\\n\\begin{align*}\nk^4S &= k^4 + \\frac{1}{k^0} + \\frac{1}{k^4} + .... \\\\\n&= k^4 + S\n\\end{align*}\n\\\\\n\\\\\nFrom this, we get \n\\\\\n\\begin{align*}\nS &= \\frac{k^4}{k4 - 1}\n\\end{align*}\n\\\\\n\\\\\nNow substituting back in, we get \n\\\\\n\\begin{align*}\nF_{net} &= \\frac{q_o}{4\\pi\\epsilon_0} \\frac{k^4}{k4 - 1}\n\\end{align*}\n\\\\\n\\\\\nSince $F_{net} = ma$\n\\\\\n$\\therefore a &= \\frac{q_o}{4\\pi\\epsilon_0} \\frac{k^4}{m(k^4 - 1)}$, facing south-west.\n\n\\end{document}", "meta": {"hexsha": "dc717a1735a6ee23673ff31dfb5527b37cc80cc2", "size": 6273, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Y3S2/Electrostatics/Inator/Inator.tex", "max_stars_repo_name": "ThePyProgrammer/peerwise", "max_stars_repo_head_hexsha": "1da806a6b238ce13ae9c7328953b2497d2da9e25", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Y3S2/Electrostatics/Inator/Inator.tex", "max_issues_repo_name": "ThePyProgrammer/peerwise", "max_issues_repo_head_hexsha": "1da806a6b238ce13ae9c7328953b2497d2da9e25", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Y3S2/Electrostatics/Inator/Inator.tex", "max_forks_repo_name": "ThePyProgrammer/peerwise", "max_forks_repo_head_hexsha": "1da806a6b238ce13ae9c7328953b2497d2da9e25", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.7883211679, "max_line_length": 693, "alphanum_fraction": 0.7122588873, "num_tokens": 1907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.34443738628506126}}
{"text": "\\documentclass[a4paper]{article}\n\n\\input{temp}\n\n\\begin{document}\n\n\\title{Model Theory Example Sheet 3}\n\n\\author{Xiaojia Rao}\n\n\\maketitle\n\n\\setcounter{secnumdepth}{0}\n\n\\section{Question 4}\n\nSuppose $a \\not\\in acl(A)$. Then there exists a model $\\mathcal{M} \\preccurlyeq U$ which contains $A$ but not $a$. But $a \\in acl(A,b)$ for any realization $b$ of $\\phi(z)$, so $\\mathcal{M}$ cannot contain any of those $b$, i.e. $\\mathcal{M}$ does not contain any realization of $\\phi(z)$. But it does contain $A$, so the sentence $\\exists z \\phi(z)$ should be true in $\\mathcal{M}$ since it is true in $U$ and by elementarity. Contradiction.\n\nFor types it's similar: similarly we have a model $\\mathcal{M}$ containing $A$ that does not contain $a$ and  has no realization of $p(z)$. Note that by elementarity $p(z)$ is still finitely consistent in $\\mathcal{M}$, so $p(z)$ must be an infinite type.\n\n\\section{Question 7}\n\nSuppose $C \\cap acl(A) = \\phi$. Then for each $c \\in C$, consider its type over $A$, $p_c(x):=tp(c/A)$: for $\\phi(x) \\in p_c(x)$, we have $|\\phi(U)| \\geq \\omega$. So by the same argument from lecture we know $|p_c(U)| = |U|$.\\\\\nWe continue mimicking the proof: let $\\mathcal{M} \\supset A$ be a model, then $p_c(U) \\setminus \\mathcal{M} \\neq \\phi$ for each $c \\in C$. Pick $b_c \\in p_c(U) \\setminus \\mathcal{M}$, then by homogeneity\n\n\\end{document}\n", "meta": {"hexsha": "7d8dd4fa6fc9197a8f86f62232643c1091f80eda", "size": 1360, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Notes/Model Theory ES3.tex", "max_stars_repo_name": "raoxiaojia/raoxiaojia.github.io", "max_stars_repo_head_hexsha": "d20c23a64794b500f2e0356fd01017ee31830fa2", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-25T17:34:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-25T17:34:25.000Z", "max_issues_repo_path": "Notes/Model Theory ES3.tex", "max_issues_repo_name": "raoxiaojia/raoxiaojia.github.io", "max_issues_repo_head_hexsha": "d20c23a64794b500f2e0356fd01017ee31830fa2", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Notes/Model Theory ES3.tex", "max_forks_repo_name": "raoxiaojia/raoxiaojia.github.io", "max_forks_repo_head_hexsha": "d20c23a64794b500f2e0356fd01017ee31830fa2", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.3703703704, "max_line_length": 442, "alphanum_fraction": 0.6801470588, "num_tokens": 450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.3444373776110126}}
{"text": "\\chapter{Microbial Network Modelling}\n\\pagenumbering{arabic} \\setcounter{page}{21}\n\nAs stated in the previous chapters, the microbes form associations, which can be studied using the principles of network science. There is a long chain of essential process from the abundance matrix of sequences to community network models. This chapter reviews the strategies involved while making microbial co-occurrence networks.\n\n\\begin{figure}[!hb]\n  \\centering\n  \\includegraphics[width=12cm, height=6cm] {../figures/Figure6.png}\n  \\caption{Graphical representation of the pairwise interactions}\n  \\label{fig:figure6}\n\\end{figure}\n\n\\section{Pairwise Interactions}\nThe associations are primarily classified into three categories,i.e., positive interaction, negative interaction, of neutral interaction. Figure \\ref{fig:figure6} shows the graphical summary of the interaction types \\cite{faust_2012_microbial}. The most basic interaction is \\emph{mutualism}, which is a win-win scenario for both members of the pair. These members benefit from each other under this association (e.g. co-operative and symbiotic pairs). Opposite to that, the \\emph{Competition} association is the lose-lose situation as both the members compete for resources. \\emph{Predation} \\& \\emph{Parasitism} can have win-lose effects on either member as if one is the predator/parasite; the other has to be the prey/host. Following that, in a situation where a member is neutral, and the other member in the pair is being harmed, this kind of association is known as \\emph{Amensalism} or \\emph{Commensalism} if other benefits. Co-occurrence networks derived using pairwise associations are perceived as simple networks and made using similarity-based inferences as discussed in the previous chapters \\cite{faust_2012_microbial}. Initially, all the normally derived permutation-combinations are used to calculate the mathematical measures and then the significant ones are retained to form co-occurrence networks [Figure \\ref{fig:figure7}].\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=12cm, height=7.5cm] {../figures/Figure7.png}\n  \\caption{Steps involved for designing the pairwise-interaction network}\n  \\label{fig:figure7}\n\\end{figure}\n\n\\section{Complex Interactions and Dynamic Networks}\nThe cases may arise when more than one microbial interaction is under study. The associations involve more than two members undergoing either positive, negative or neutral associations. The rules of pairwise interaction still apply; however, the number of contributing members changes in order to map the complex interactions methods like multiple-regression and associative rule mining is used\\cite{faust_2012_microbial} . The multiple-regression predicts the dependent variable/interaction based on the independent variables/group of pairwise interactions. The networks generated are called the directed hypergraphs, which have hyperedges \\cite{faust_2012_microbial}. Figure \\ref{fig:figure8} shows a typical complex co-occurrence network made using associative rule mining. The generalized Lotka-Volterra equations used to simulate a dynamic model of a microbial community. As input, they need the growth rates $b_{i}$ and interaction strengths $a_{ij}$ of the different community members, which can either be obtained experimentally or estimated from time-series data. The abundance of taxa $i$ at time $t$ are denoted by $x_{i}(t)$\n\n$$\\frac{dx_{i}(t)}{dt} = x_{i}(t)(b_{i} + \\sum^{N}_{j=1}a_{ij}x_{j}(t))$$\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=12cm, height=8cm] {../figures/Figure8.png}\n  \\caption[A typical directed hypergraph]{A typical directed hypergraph made using the OTUs. Hyper-edges connects more than two nodes}\n  \\label{fig:figure8}\n\\end{figure}\n\n\\subsection*{Pitfalls}\nThe networks rec-construction is not independent of compositional bias. Arising from the sampling, the measure of the relative abundance can heavily impact the downstream analysis \\cite{faust_2012_microbial}. Other than that, microbial datasets are full of zeros that could arise because either sampling is inappropriate or the member is missing. Even if the construction is successful, an inference could be error-prone, as it is difficult to segregate between the interaction.", "meta": {"hexsha": "59364fea01121a61160994da229a6734a73e005d", "size": 4241, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "literatureReview/tex/ch7.tex", "max_stars_repo_name": "spriyansh/metagenomics-CSG-2021", "max_stars_repo_head_hexsha": "bfa93af6bb8631ee0e19ac6005db72bbf18f0fae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "literatureReview/tex/ch7.tex", "max_issues_repo_name": "spriyansh/metagenomics-CSG-2021", "max_issues_repo_head_hexsha": "bfa93af6bb8631ee0e19ac6005db72bbf18f0fae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "literatureReview/tex/ch7.tex", "max_forks_repo_name": "spriyansh/metagenomics-CSG-2021", "max_forks_repo_head_hexsha": "bfa93af6bb8631ee0e19ac6005db72bbf18f0fae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 117.8055555556, "max_line_length": 1345, "alphanum_fraction": 0.8033482669, "num_tokens": 978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.34443737761101256}}
{"text": "\\section{Inference}\n\\label{inf}\n\nTRILL systems can answer many different queries. To do so, it exploits an algorithm called \\emph{tableau} algorithm, which is able to collect explanations. In the following you can find an example that shows how the tableau works. In section~\\ref{sec:trillq} we will see how queries can be asked with TRILL systems.\n\nConsider a simple knowledge base inspired by the film ``The Godfather'' containing the following axioms:\n\\begin{align}\n&tom : Cat\\\\\n&(donVito, tom) : hasPet\\\\\n&Cat \\sqsubseteq Pet\\\\\n&\\exists hasAnimal.Pet \\sqsubseteq NatureLover\\\\\n&NatureLover \\sqsubseteq GoodPerson\\\\\n&hasPet \\sqsubseteq hasAnimal\n\\end{align}\n\nThe axioms are telling what is known about the domain: (1) Tom is an individual of the domain, and he is a Cat; (2) donVito (Vito Corleone) has tom as his pet; (3) all cats are also pets; (4) everyone having at least one animal which is a pet is a nature lover; (5) nature lovers are good people; and (6) if one has a pet, she/he also has an animal.\n\nThis KB can be defined by the following TRILL syntax axioms:\n\\begin{verbatim}\nclassAssertion(cat, tom).\npropertyAssertion(hasPet, donVito, tom).\nsubClassOf(cat, pet).\nsubClassOf(someValuesFrom(hasAnimal, pet), natureLover).\nsubClassOf(natureLover,goodPerson).\nsubPropertyOf(hasPet,hasAnimal).\n\\end{verbatim}\nYou can run this example \\href{http://trill-sw.eu/example/trill/donVito.pl}{here}.\n\nThe first two axioms are assertional axioms (hence they constitute the ABox), the other four axioms define the TBox. Axiom 1 is called class assertion, 2 is called property assertion, 3,4,5 are called class subsumption axioms, and axiom 6 is called property subsumption axiom.\n\nTo check, for example, whether don Vito Corleone is a good person, the tableau algorithm builds a graph, called the \\emph{tableau}. The initial tableau contains information from the ABox plus the negation of the query, as depicted in Figure\\ref{fig:tab1}. This last axiom is added since the underlying proof mechanism uses refutation. In logic, working by refutation means assuming the opposite of the query one wants to prove. Then, if this assumption leads to a contradiction, this means that the axioms of the ontology allows to prove that the query is true, and thus that its opposite is false. In practice, working by refutation means that the graph must assume that the posed query be false, the tableau algorithm expands all the known axioms (including the negation of the query) and looks for contradictions present in the final graph. The presence of a contradiction in a node proves that the query is true because the graph depicts at least one way to contradict the negation of that query, and thus it depicts at least one way to prove that the opposite of the query contradicts what is defined by the ontology. \n\n\\begin{figure}\n\t\\centering\n\t\\includegraphics[width=0.5\\linewidth]{img/tab1}\n\t\\caption{Initial tableau}\n\t\\label{fig:tab1}\n\\end{figure}\n\nThis means that if the opposite of the query is (artificially) added to the knowledge base as a new axiom, this ontology will contain at least two pieces of information one contradicting the other.\n\nThe tableau has one node for each individual: tom is labelled as cat, $donVito$ is labelled as not a good person (the negation of the query), and the edge between them is labelled as $hasPet$ because the individuals are connected by this property (Figure~\\ref{fig:tab1}).\n\nAt this point, the graph of Figure~\\ref{fig:tab1} is expanded using the axioms of the ontology to check the truth of the query and to build the justifications. Therefore, the tableau algorithm takes e.g. the axiom 3, ``cats are pets'', and adds to the node for tom also the label $pet$ since he is a cat. This new information is true and its justification is given directly by the set of axioms {1,3}: axiom 3 because since $tom$ is a $cat$ (axiom 1) he is also a $pet$. The same operation can be done for the edge (relationship) between tom and $donVito$, which can be labelled also as $hasAnimal$ because of axioms~2 and~6.\n\nAt this point, the calculus can deduce that $donVito$ belongs to the class \\linebreak $\\exists hasAnimal.Pet$ because $donVito$ is connected with $tom$, which is a $pet$ (axioms {1,3}), via property $hasAnimal$ (axioms {2,6}). Therefore, $donVito$’s node is labelled also as $\\exists hasAnimal.Pet$ with a justification given by the union of the axioms associated with the used axioms, therefore its justification is given by the set of the involved axioms {1,2,3,6}. Then, the tableau graph is further expanded by adding the class $NatureLover$ to $donVito$’s node using axiom 4 and finally, by adding also the class $GoodPerson$ using label $NatureLover$ (axioms {1,2,3,4,6}) and axiom 5, creating as justification the set of axioms {1,2,3,4,5,6}.\n\nThe final graph is shown in Figure~\\ref{fig:tab2}.\n\\begin{figure}\n\t\\centering\n\t\\includegraphics[width=0.5\\linewidth]{img/tab2}\n\t\\caption{Final tableau}\n\t\\label{fig:tab2}\n\\end{figure}\nThe expanded graph contains now a contradiction, i.e., $donVito$ is labelled as $GoodPerson$ and as not a $GoodPerson$ (i.e., $\\neg GoodPerson$), therefore, by refutation, the query ``Is don Vito Corleone a good person?'' is true, with justification given by the axioms {1,2,3,4,5,6}, that are the axioms of the KB necessary to deduce this information.\n\nFrom this example, it would be clear why the use of probabilistic information is useful. Indeed, don Vito Corleone is hardly classifiable as a good person. This is because not all people who are nature lovers are also good, and therefore, one could say that axiom 5 is true with probability 0.4. It would also be arguable that everyone who has animals is also a nature lover, making probabilistic also this axiom. For a formal description of how the probability of the query is computed see the Appendix~\\ref{app:inf}.", "meta": {"hexsha": "766cdb661e3e9bb3656b6a54452a4d8805fdc6e3", "size": 5848, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/inference.tex", "max_stars_repo_name": "rzese/trill", "max_stars_repo_head_hexsha": "145781966a4203e43c3cfe18e62435557e764297", "max_stars_repo_licenses": ["Artistic-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2016-02-02T07:36:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T01:23:49.000Z", "max_issues_repo_path": "doc/inference.tex", "max_issues_repo_name": "rzese/trill", "max_issues_repo_head_hexsha": "145781966a4203e43c3cfe18e62435557e764297", "max_issues_repo_licenses": ["Artistic-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-10-19T12:53:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-29T15:14:51.000Z", "max_forks_repo_path": "doc/inference.tex", "max_forks_repo_name": "rzese/trill", "max_forks_repo_head_hexsha": "145781966a4203e43c3cfe18e62435557e764297", "max_forks_repo_licenses": ["Artistic-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-04-05T10:34:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-30T10:46:54.000Z", "avg_line_length": 102.5964912281, "max_line_length": 1123, "alphanum_fraction": 0.7742818057, "num_tokens": 1519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.34443737761101256}}
{"text": "\\documentclass{amsart}\r\n\r\n\\usepackage{amsmath}\r\n\\usepackage[framemethod=TikZ]{mdframed}\r\n\\usepackage{xparse}\r\n\\ExplSyntaxOn\r\n\\NewDocumentCommand{\\cfracdots}{ }\r\n  {\r\n   \\rule{0pt}{1.5\\baselineskip}\r\n   \\raisebox{.5\\baselineskip}{\\enspace$\\ddots$\\enspace}\r\n  }\r\n\\NewDocumentCommand{\\cfraccdots}{}{\\cdots}\r\n\\NewDocumentCommand{\\cfracddots}{}{\\ddots}\r\n\\NewDocumentCommand{\\cfracldots}{}{\\ldots}\r\n\r\n\\NewDocumentCommand{\\xcontfrac}{ s O{c} >{\\SplitArgument{1}{;}}m }\r\n  { \r\n   \\IfBooleanTF{#1}\r\n     { \\cfrac_inline:nn #3 }\r\n     { \\cfrac_map:nnn { #2 } #3 }\r\n  }\r\n\r\n\\cs_new:Npn \\cfrac_inline:nn #1 #2\r\n  {\r\n   \\IfNoValueTF { #2 }\r\n     {\r\n      \\tl_use:N \\c_cfrac_message_tl\r\n      \\xcontfrac*{;#1}\r\n     }\r\n     {\r\n      \\group_begin:\r\n      \\cs_set_eq:NN \\cfracdots \\dots\r\n      [\\, \\tl_if_empty:nTF { #1 } { 0 } { #1 } ; #2 \\,]\r\n      \\group_end:\r\n     }\r\n  }\r\n\r\n\\tl_const:Nn \\c_cfrac_lbrace_tl { \\if_true:  { \\else: } \\fi: }\r\n\\tl_const:Nn \\c_cfrac_rbrace_tl { \\if_false: { \\else: } \\fi: }\r\n\\tl_const:Nn \\c_cfrac_strut_tl { \\vrule width 0pt depth .3\\baselineskip }\r\n\\tl_new:N \\l_cfrac_left_tl\r\n\\tl_new:N \\l_cfrac_right_tl\r\n\\msg_new:nnn { cfrac } { wrong-syntax }\r\n  {\r\n   Wrong~syntax~for~\\token_to_str:N \\xcontfrac,~\r\n   assuming~0~in~the~integer~part,~on~line~\\msg_line_number:.\r\n  }\r\n\r\n\\cs_new:Npn \\cfrac_map:nnn #1 #2 #3\r\n  {\r\n   \\tl_clear:N \\l_cfrac_left_tl \\tl_clear:N \\l_cfrac_right_tl\r\n   \\IfNoValueTF { #3 }\r\n     { \r\n      \\msg_warning:nn { cfrac } { wrong-syntax }\r\n      \\xcontfrac[#1]{;#2}\r\n     }\r\n     {\r\n      \\tl_if_empty:nTF { #2 }\r\n        { \\cfrac_map_aux:nn { #1 } { \\exp_not:N \\use_none:n , #3 } }\r\n        { \\cfrac_map_aux:nn { #1 } { #2 , #3 } }\r\n     }\r\n  }\r\n\\cs_new:Npn \\cfrac_map_aux:nn #1 #2\r\n  {\r\n   \\clist_map_inline:nn { #2 }\r\n     {\r\n      \\tl_put_right:Nn \\l_cfrac_left_tl { \\cfrac_begin:nn { #1 } { ##1 } }\r\n      \\tl_put_right:Nn \\l_cfrac_right_tl { \\exp_not:N \\c_cfrac_rbrace_tl }\r\n     }\r\n   \\tl_set:Nx \\l_cfrac_left_tl\r\n     { \\l_cfrac_left_tl \\c_cfrac_strut_tl \\l_cfrac_right_tl }\r\n   \\tl_set:Nx \\l_cfrac_left_tl { \\l_cfrac_left_tl }\r\n   \\exp_after:wN \\use_none:nnnnnn \\l_cfrac_left_tl\r\n  }\r\n\\cs_new:Npn \\cfrac_begin:nn #1 #2\r\n  {\r\n   \\exp_not:n\r\n     { + \\exp_not:N \\cfrac[#1] { 1 } \\c_cfrac_lbrace_tl \\exp_not:N \\mathstrut #2 }\r\n  }\r\n\\ExplSyntaxOff\r\n\r\n\\usepackage{listings}\r\n\\usepackage{color}\r\n\r\n\\definecolor{mygreen}{rgb}{0,0.6,0}\r\n\\definecolor{mygray}{rgb}{0.5,0.5,0.5}\r\n\\definecolor{mymauve}{rgb}{0.58,0,0.82}\r\n\r\n\\lstset{ \r\n  backgroundcolor=\\color{white},   % choose the background color; you must add \\usepackage{color} or \\usepackage{xcolor}; should come as last argument\r\n  basicstyle=\\footnotesize,        % the size of the fonts that are used for the code\r\n  breakatwhitespace=false,         % sets if automatic breaks should only happen at whitespace\r\n  breaklines=true,                 % sets automatic line breaking\r\n  captionpos=b,                    % sets the caption-position to bottom\r\n  commentstyle=\\color{mygreen},    % comment style\r\n  deletekeywords={...},            % if you want to delete keywords from the given language\r\n  escapeinside={\\%*}{*)},          % if you want to add LaTeX within your code\r\n  extendedchars=true,              % lets you use non-ASCII characters; for 8-bits encodings only, does not work with UTF-8\r\n  firstnumber=1000,                % start line enumeration with line 1000\r\n  frame=single,\t                   % adds a frame around the code\r\n  keepspaces=true,                 % keeps spaces in text, useful for keeping indentation of code (possibly needs columns=flexible)\r\n  keywordstyle=\\color{blue},       % keyword style\r\n  language=Octave,                 % the language of the code\r\n  morekeywords={*,...},            % if you want to add more keywords to the set\r\n  numbers=none,                    % where to put the line-numbers; possible values are (none, left, right)\r\n  numbersep=5pt,                   % how far the line-numbers are from the code\r\n  numberstyle=\\tiny\\color{mygray}, % the style that is used for the line-numbers\r\n  rulecolor=\\color{black},         % if not set, the frame-color may be changed on line-breaks within not-black text (e.g. comments (green here))\r\n  showspaces=false,                % show spaces everywhere adding particular underscores; it overrides 'showstringspaces'\r\n  showstringspaces=false,          % underline spaces within strings only\r\n  showtabs=false,                  % show tabs within strings adding particular underscores\r\n  stepnumber=2,                    % the step between two line-numbers. If it's 1, each line will be numbered\r\n  stringstyle=\\color{mymauve},     % string literal style\r\n  tabsize=2,\t                   % sets default tabsize to 2 spaces\r\n  title=\\lstname                   % show the filename of files included with \\lstinputlisting; also try caption instead of title\r\n}\r\n\r\n\\usepackage{tikz}\r\n\\usetikzlibrary{calc}\r\n\\newcommand{\\tikzmark}[1]{\\tikz[overlay,remember picture] \\node (#1) {};}\r\n\r\n\r\n\\newmdtheoremenv{theorem}{Theorem}\r\n\\newtheorem{example}{Example}\r\n\r\n\\newcounter{theo}[section]\\setcounter{theo}{0}\r\n\\newenvironment{theo}[2][]{%\r\n    \\refstepcounter{theo}\r\n    \\ifstrempty{#1}%\r\n% if condition (without title)\r\n{\\mdfsetup{%\r\n    frametitle={%\r\n        \\tikz[baseline=(current bounding box.east),outer sep=0pt]\r\n        \\node[anchor=east,rectangle,fill=blue!20]\r\n        {\\strut Theorem~\\thetheo};}\r\n    }%\r\n% else condition (with title)\r\n}{\\mdfsetup{%\r\n    frametitle={%\r\n        \\tikz[baseline=(current bounding box.east),outer sep=0pt]\r\n        \\node[anchor=east,rectangle,fill=blue!20]\r\n        {\\strut Theorem~\\thetheo:~#1};}%\r\n    }%\r\n}%\r\n% Both conditions\r\n\\mdfsetup{%\r\n    innertopmargin=10pt,linecolor=blue!20,%\r\n    linewidth=2pt,topline=true,%\r\n    frametitleaboveskip=\\dimexpr-\\ht\\strutbox\\relax%\r\n}\r\n\\begin{mdframed}[]\\relax}{%\r\n\\end{mdframed}}\r\n\r\n\\newcounter{lem}[section]\\setcounter{lem}{0}\r\n\\renewcommand{\\thelem}{\\arabic{section}.\\arabic{lem}}\r\n\\newenvironment{lem}[2][]{%\r\n\\refstepcounter{lem}%\r\n\\ifstrempty{#1}%\r\n{\\mdfsetup{%\r\nframetitle={%\r\n\\tikz[baseline=(current bounding box.east),outer sep=0pt]\r\n\\node[anchor=east,rectangle,fill=green!20]\r\n{\\strut ~\\thelem};}}\r\n}%\r\n{\\mdfsetup{%\r\nframetitle={%\r\n\\tikz[baseline=(current bounding box.east),outer sep=0pt]\r\n\\node[anchor=east,rectangle,fill=green!20]\r\n{\\strut ~#1};}}%\r\n}%\r\n\\mdfsetup{innertopmargin=10pt,linecolor=green!20,%\r\nlinewidth=2pt,topline=true,%\r\nframetitleaboveskip=\\dimexpr-\\ht\\strutbox\\relax\r\n}\r\n\\begin{mdframed}[]\\relax%\r\n\\label{#2}}\r\n{\\end{mdframed}}\r\n\r\n\\begin{document}\r\n\\title{Euclid's extended algorithm and applications}\r\n\\author{Franklin}\r\n\\maketitle\r\n\r\nThe foundation of the algorithm is the following theorem\r\n\r\n\\begin{theo}[Euclidean division theorem]{}\\label{euclid}\r\nIf $a,b$ are integers, then there exist integers $q,r$, such that \r\n\\begin{align*}\r\na&=bq+r\\\\\r\n0&\\leq r<|b|\r\n\\end{align*}\r\n\\end{theo}\r\n\r\n\\begin{lem}[Extended Euclidean Algorithm]{}\r\n\\noindent\\textbf{Input:} Two integers $a$ and $b$. The input could also be two polynomials, or in general anything that satisfies Theorem \\ref{euclid}.\r\n\r\n\\noindent\\textbf{Algorithm:}\r\n\\begin{itemize}\r\n\\item \\textbf{Step 1:} If $b>a$, then swap $a$ and $b$. In other words, assume that $a\\geq b$.\r\n\\item \\textbf{Step 2:} Call $r_{0}=a$ and $r_1=b$ and set $i=0$.\r\n\\item \\textbf{Step 3:} While $r_{i+1}\\neq 0$, divide $r_{i}$ by $r_{i+1}$ as in Theorem \\ref{euclid} $$r_{i}=r_{i+1}q_{i}+r_{i+2}$$ and increment $i$.\r\n\\end{itemize}\r\n\r\n\\noindent\\textbf{Output:}\r\nThe algorithm outputs all the equations obtained in the loop of Step 2.\r\nThese are \r\n\\begin{align*}\r\nr_{0}&=r_1q_0+r_2\\\\\r\nr_1&=r_2q_1+r_3\\\\\r\nr_2&=r_3q_2+r_4\\\\\r\n\\vdots&\\phantom{{}={}}\\vdots\\\\\r\nr_{n-1}&=r_{n}q_{n-1}+r_{n+1}\\\\\r\nr_{n}&=r_{n+1}q_{n} + 0\r\n\\end{align*}\r\n\\end{lem}\r\n\r\n\r\nThe algorithm always ends when the last remainder computed is $0$.\r\n\r\n\\section*{Information that can be read from the output of Euclid's algorithm}\r\n\\begin{itemize}\r\n\\item The $\\gcd(a,b)$ satisfies $$\\gcd(a,b)=r_{n+1}$$This is, the greatest common divisor of $a$ and $b$ is the last number used as divisor when the algorithm terminated.\r\n\\item Bezout's equation expressing $\\gcd(a,b)$ as a combination $$ax+by=\\gcd(a,b)$$ for some integers $x$ and $y$.\r\n\\end{itemize}\r\n\r\n\\section*{Bezout's equation}\r\n\r\nTo produce Bezout's equation for $a,b$, from the output of Euclid's extended algorithm we first write the output by solving in each equation for the remainder \r\n\\begin{align*}\r\nr_{0}-r_1q_0&=\\tikzmark{a}r_2\\\\\r\nr_1-\\tikzmark{b}r_2q_1&=\\tikzmark{c}r_3\\\\\r\nr_2-\\tikzmark{d}r_3q_2&=r_4\\\\\r\n\\vdots&\\phantom{{}={}}\\vdots\\\\\r\nr_{n-2}-r_{n-1}q_{n-2}+&=\\tikzmark{e}r_{n}\\\\\r\nr_{n-1}-\\tikzmark{f}r_{n}q_{n-1}+&=r_{n+1}\\\\\r\nr_{n}&=r_{n+1}q_{n} + 0\r\n\\begin{tikzpicture}[overlay,remember picture,out=225,out=335,distance=0.6cm]\r\n    \\draw[->,red] (a.south) to (b.north);\r\n\t\t\\draw[->,red] (c.south) to (d.north);\r\n\t\t\\draw[->,red] (e.south) to (f.north);\r\n  \\end{tikzpicture}\r\n\\end{align*}\r\n\r\nSubstituting all of these equations into the second to last one, we get $\\gcd(a,b)$ expressed in terms of $r_0$ and $r_1$, which are $a$ and $b$, as wanted.\r\n\r\n\\section*{Multiplicative inverse in modular arithmetic}\r\nIn the case that $\\gcd(a,b)=1$, Bezout's equation takes the form $$ax+by=1$$\r\nIf we reduce this equation modulo $b$, the term $bx$ becomes $0$, for being a multiple of $b$. We obtain $$ax\\equiv 1\\pmod{b}$$\r\nTherefore, $x$, or rather its remainder modulo $b$, is the multiplicative inverse of $a$, modulo $b$.\r\n\r\n\\section*{Numeric example} Let us compute the $\\gcd$ of $2519$ and $377$.\r\n\r\nFirst, we perform Euclid's Extended Algorithm.\r\n\r\n\\begin{align*}\r\n2519&=\\tikzmark{a}377\\cdot6+\\tikzmark{c}257\\\\\r\n&\\\\\r\n\\tikzmark{b}377&=\\tikzmark{d}257\\cdot1+\\tikzmark{f}120\\\\\r\n&\\\\\r\n\\tikzmark{e}257&=\\tikzmark{g}120\\cdot2+\\tikzmark{h}17\\\\\r\n&\\\\\r\n\\tikzmark{i}120&=\\tikzmark{j}17\\cdot7+\\tikzmark{k}\\boxed{1}\\\\\r\n&\\\\\r\n\\tikzmark{l}17&=\\tikzmark{m}\\boxed{1}\\cdot 17+0\r\n\\begin{tikzpicture}[overlay,remember picture,out=225,out=335,distance=0.6cm]\r\n    \\draw[->,red] (a.south) to (b.north);\r\n\t\t\\draw[->,red] (c.south) to (d.north);\r\n\t\t\\draw[->,red] (d.south) to (e.north);\r\n\t\t\\draw[->,red] (f.south) to (g.north);\r\n\t\t\\draw[->,red] (g.south) to (i.north);\r\n\t\t\\draw[->,red] (h.south) to (j.north);\r\n\t\t\\draw[->,red] (j.south) to (l.north);\r\n\t\t\\draw[->,red] (k.south) to (m.north);\r\n  \\end{tikzpicture}\r\n\\end{align*}\r\n\r\nThe last divisor used is the $\\gcd$. So, $\\gcd(2519,377)=1$.\r\n\r\nNow, to form Bezout's equation, let's solve for the remainders in all these equations and substitute each into the next one until we get to the second-to-last equation. We don't want to carry out any of the arithmetic operations, while we are doing the substitutions, at least not the ones with the numbers $2519$ and $377$.\r\n\r\n\\begin{align*}\r\n2519-\\tikzmark{a}377\\cdot6&=\\tikzmark{c}257\\\\\r\n&\\\\\r\n\\tikzmark{b}377-\\tikzmark{d}257\\cdot1&=\\tikzmark{f}120\\\\\r\n&\\\\\r\n\\tikzmark{e}257-\\tikzmark{g}120\\cdot2&=\\tikzmark{h}17\\\\\r\n&\\\\\r\n\\tikzmark{i}120-\\tikzmark{j}17\\cdot7&=\\tikzmark{k}\\boxed{1}\r\n\\begin{tikzpicture}[overlay,remember picture,out=225,out=335,distance=0.6cm]\r\n    \\draw[->,red] (c.south) to (d.north);\r\n\t\t\\draw[->,red] (f.south) to (g.north);\r\n\t\t\\draw[->,red] (h.south) to (j.north);\r\n  \\end{tikzpicture}\r\n\\end{align*}\r\n\r\nSubstituting the third (second-to-last) equation into the last one to eliminate the remainder $17$, we get \r\n\r\n$$120-(257-120\\cdot 2)\\cdot 7=\\boxed{1}$$\r\n\r\nNow we can use the second equation to eliminate from this one all occurrences of the remainder $120$. We get \r\n\r\n$$(377-257\\cdot1)-(257-(377-257\\cdot1)\\cdot 2)\\cdot 7=\\boxed{1}$$\r\n\r\nNow we use the first equation to eliminate from this one all occurences of the remainder $257$. We get\r\n\r\n$$(377-(2519-377\\cdot 6)\\cdot1)-((2519-377\\cdot 6)-(377-(2519-377\\cdot 6)\\cdot1)\\cdot 2)\\cdot 7=\\boxed{1}$$\r\n\r\nFinally, we gather together all terms that are multiplied by $2519$ and all that are multiplied by $377$. We get\r\n\r\n$$2519\\cdot (-22)+377\\cdot (147) =\\boxed{1}$$\r\n\r\nThe two factors $-22$ and $147$ in Bezout's equation are not unique. We could, for example add and subtract a multiple of $2519\\cdot 377$ and get \r\n\r\n\\begin{align*}\\boxed{1}&=2519\\cdot (-22)+2519\\cdot377\\cdot k-2519\\cdot377\\cdot k+377\\cdot (147)\\\\\r\n&=2519\\cdot (377\\cdot k-22)+377\\cdot (147-2519\\cdot k)\r\n\\end{align*}\r\n\r\nSo, the factors $377\\cdot k-22$ and $147-2519\\cdot k$ also work.\r\n\r\nIn the process we also got that $$377\\cdot 147\\equiv1\\pmod{2519}$$\r\nand that $$2519\\cdot (-22)\\equiv1\\pmod{377}$$\r\n\r\n\\section*{Implementation}\r\n\r\nIt is important to practice the computations above a few times, by hand. \r\nTo verify your computations we can use a computer.\r\n\r\nThe following is a function in Python that inputs $a$ and $b$ and returns a triple $d,x,y$ such that $$ax+by=d$$\r\n\r\n\\begin{lstlisting}[language=Python]\r\ndef xgcd(a, b):\r\n    \"\"\"return (d, x, y) such that a*x + b*y = d = gcd(a, b)\"\"\"\r\n    x0, x1, y0, y1 = 0, 1, 1, 0\r\n    while a != 0:\r\n        (q, a), b = divmod(b, a), a\r\n        y0, y1 = y1, y0 - q * y1\r\n        x0, x1 = x1, x0 - q * x1\r\n    return b, x0, y0\r\n\\end{lstlisting}\r\n\r\n\\noindent\\textbf{Note:} To copy this code into a Python interpreter, remember that in Python the indentation of the lines is important. So, give $4$ spaces to indent each indented line.\r\n\r\nExecuting \\lstinline{xgcd(2519,377)} we get \\lstinline{(1,-22,147)}. So, the example should be OK (or both the example and the Python code are wrong).\r\n\r\n\\section*{Continued fractions}\r\n\r\nA byproduct of the output of the Extended Euclid's Algorithm for the input $a,b$, with $a\\geq b$, is a \\emph{continued fraction} expansion of the rational number $\\frac{a}{b}$. With the notation above, we get that \r\n\r\n$$\\frac{a}{b}=\\frac{r_0}{r_1}=\\xcontfrac{q_0;q_1,q_2,\\cfracdots,q_n}$$\r\n\r\n\r\n\r\n\r\n\\end{document}", "meta": {"hexsha": "beef9eadf459f1691e0d59c6b0a6167f2d34ccbe", "size": 13750, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "assets/files/ExtendedEuclid.tex", "max_stars_repo_name": "franklinvp/franklinvp.github.io", "max_stars_repo_head_hexsha": "fea6ac7ad8df6a00eb1b5fd04f54eab5ba756006", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assets/files/ExtendedEuclid.tex", "max_issues_repo_name": "franklinvp/franklinvp.github.io", "max_issues_repo_head_hexsha": "fea6ac7ad8df6a00eb1b5fd04f54eab5ba756006", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assets/files/ExtendedEuclid.tex", "max_forks_repo_name": "franklinvp/franklinvp.github.io", "max_forks_repo_head_hexsha": "fea6ac7ad8df6a00eb1b5fd04f54eab5ba756006", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8418079096, "max_line_length": 325, "alphanum_fraction": 0.6521454545, "num_tokens": 4730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.3443218050191248}}
{"text": "\\chapterquote{%\nTime and Space\\dots It is not nature which imposes them upon us, it is we who impose them upon nature because we find them convenient.}%\n{-- Henri Poincar\\'e, \\textit{The Value of Science} (1905)}\n\nIn this chapter\\footnote{The present chapter was based on the articles \\cite{dester2018} and \\cite{dester2021part}.}, we include the spatial position of the nodes in the analysis.\n%\nTherefore, the transmission success probability $p_s$ can no longer be an arbitrary function of the traffic, because it needs to include the spatial positions into its model.\n%\nThus, we need a more specific model for $p_s$, preferably one that entails analytical tractability.\n%\nIn the following section, we propose a model inspired in Proposition~\\ref{prop:PPP_ps} and other models adopted throughout the literature.\n\nAnother important concept we deal with in this chapter is the \\textit{stability} of the queued packets. When a queue is not stable the number of queued packets tends to infinity \\textit{almost surely} as time tends to infinity.\n%\nWe are very interested in stable queues, because one of the important metrics, namely the delay, tends to infinity in unstable systems, and that is not desirable.\n\nThe additional notations used in this chapter are summarized in Table~\\ref{tab:symbols}.\n%\n\\begin{table}[hbt]\n    \\centering\n    \\caption{Notations and symbols used in this chapter}\n    \\label{tab:symbols}\n    \\setlength{\\tabcolsep}{3pt}\n    \\begin{tabular}{l l}\n      \\hline\n      \\hline\n      \\textbf{Symbol} & \\textbf{Definition/explanation} \\\\\n      \\hline\n        $\\alpha\\in(2,\\infty)$\t& path loss exponent \\\\\n        $\\delta\\in(0,1)$\t\t& $\\triangleq 2/\\alpha$ \\\\\n        $N \\in \\N^*$            & number of user classes \\\\\n        $\\cal{C}$\t\t\t\t& $\\triangleq \\{1,2,\\dots,N\\}$, set of classes \\\\\n        $n\\in\\cal{C}$\t\t\t& refers to the $n$th user class \\\\\n        $p_n\\in(0,1)$\t\t\t& medium access probability \\\\\n      \t$a_n\\in(0,1)$\t\t\t& packet arrival rate per time slot \\\\\n        $\\bm{a}\\in(0,1)^N$\t\t& $=(a_1,a_2,\\dots,a_N)$ \\\\\n        $p_{s,n}\\in(0,1)$\t\t& transmission success probability \\\\\n        $\\theta_n \\in\\R_+$\t\t& SIR threshold for successful communication \\\\\n        $\\overline{R}_n\\in\\R_+$\t& average transmission distance \\\\\n        $D_n\\in(1,\\infty)$\t\t& average packet transmission delay \\\\\n        $\\bm{D}\\in(1,\\infty)^N$ & $=(D_1,D_2,\\dots,D_N)$ \\\\\n        $P_n\\in\\R_+$\t\t\t& transmission power \\\\\n        $\\bm{P}\\in\\R_+^N$ \t\t& $=(P_1,P_2,\\dots,P_N)$ \\\\\n        $\\Phi_\\TX^{(n)}$\t    & Poisson point process for the transmitters \\\\\n        $\\lambda_n\\in\\R_+$\t\t& density of $\\Phi_\\TX^{(n)}$ \\\\\n        $\\psi_n\\in\\R_+$\t\t\t& $\\triangleq 4\\,\\overline{R}_n^2 \\,\\theta_n^{\\delta}     \\,\\pi\\delta/\\sin(\\pi \\delta)$ \\\\\n        \\hline\n      \\hline\n    \\end{tabular}\n\\end{table}\n\n\\newpage\n\n% % % % % % % % % % % % % % % % % % % % % % % % % % \n% % % % % % % % % % % % % % % % % % % % % % % % % % \n\\section{Multi-class High-mobility Bipolar Networks} \\label{sec:N-class}\n\n\\subsection{Main Contributions}\nThe main contributions of the work presented in this section when compared to the literature, particularly the paper by Stamatiou and Haenggi \\cite{stamatiou2010random}, are twofold.\n%\nFirstly, we have extended the analysis of stability (Definition~\\ref{def:stability}) and delay in random-access wireless networks to the case of a network with an arbitrary number $N$ of user classes. As far as we know, this is the first time in the literature the stability region is found in closed form for a network with $N > 3$ different user classes sharing the same channel.\n%\nSecondly, we have expanded the analysis to show that the channel sharing mechanism in the investigated scenario can be seen as a process of partitioning a fixed and well-defined quantity into portions, each portion allotted to each user class, the size of which varying in accordance with the user class parameters.\n\nMore specifically, the novelty of the results on this section are summarized below:\n\\begin{itemize}[itemsep=3pt,parsep=3pt,topsep=3pt,partopsep=3pt]\n    \\item We propose a tractable scenario to study the performance and stability of a Poisson network with an arbitrary number $N$ of classes of users sharing the same channel;\n    \\item a simple and elegant expression relating mean delays, arrival rates, user densities, mean link distances, and bit rates of all $N$ classes is derived for the case of a stable network. This expression clearly shows that each class of user takes a well-defined portion of the available finite resource in the RF channel (Proposition~\\ref{prop:identity_1});\n    \\item a closed form solution (Definition~\\ref{def:closed_form}) to the fixed-point system of equations that determine the stationary transmission success probabilities for $N$ user classes is found;\n    \\item an intuitive equation is presented relating link quality, packet arrival rate, density of users, and stationary mean delay (Proposition 1);\n    \\item we prove the necessary and sufficient conditions that determine whether a given network is stable (Theorems \\ref{TH:NEC_SUFF} and \\ref{TH:STABILITY});\n    \\item we establish a simple necessary condition for stability that does not depend on the transmit powers (Corollary~\\ref{cor:stab});\n    \\item the optimum transmit powers per user class that achieve the optimum stationary mean delays for each user class (Proposition~\\ref{prop:opt}) are derived;\n    \\item the optimum packet arrival rates per user class that achieve the maximum channel throughput per unit of area (Proposition~\\ref{prop:eps}) are derived;\n    \\item we conclude that depending on the channel and user classes, the best strategy to maximize channel throughput is to share the channel, instead of using one single class per channel.\n\\end{itemize}\n\n% This section is organized as follows: Section \\ref{sec:SysMod} describes the model used throughout the chapter and provides some important results from the literature to be used in the following sections;\n% Section \\ref{sec:N-users} presents the main results of the paper, i.e., necessary and sufficient conditions for stability when we have $N$ interacting user classes, and shows a simple expression for the stationary mean delay and the packet success probability; Section \\ref{sec:application} applies the obtained results in two general scenarios: one scenario optimizes the transmission power of different user classes with different delay requirements sharing the same channel and the other optimizes the throughput per unit of area; Section \\ref{sec:conclusion} concludes the paper.\n\n\n\\subsection{System Model}\n\nWe consider a stationary high-mobility Poisson network with density $\\lambda$ on $\\R^2$ and with $N$ classes of users that share the same radio frequency channel as defined in the general network model of Chapter~\\ref{cap:P2_00}.\n%\nTime is slotted, $\\T=\\N$, and for each time slot $t \\in \\T$ and each user class $n \\in \\cal{C} \\triangleq \\{1,2,\\dots,N\\}$, we have a homogeneous Poisson point process (PPP) denoted by $\\Phi_\\TX^{(n)}(t)\\stackrel{*}{=} \\{ X_{i\\,n}(t) \\}_{i\\in\\N}$ of density $\\lambda_n$ on $\\R^2$, which represents the position of the sources. These PPPs are independent from each other and from the past.\n%\nFurthermore,\n\\begin{align*}\n    \\lambda = \\sum_{n\\in\\cal{C}} \\lambda_n,\n    \\quad\\text{then,}\\quad\n    \\Phi_\\TX(t) = \\sum_{n\\in\\cal{C}} \\Phi_\\TX^{(n)}(t) \\quad\\text{for every $t\\in\\T$}.\n\\end{align*}\n\n\\begin{remark}\n    Using the general network model of Chapter~\\ref{cap:P2_00}, the set of transmitters $\\cal{N}_\\TX = \\N\\times\\cal{C}$. Thus, each transmitter should be indexed by a number and a class. However, for ease of notation and since the network is stationary across the users within a class, we shall omit the number and only refer to the class for parameters and metrics.\n    %\n    For example, the transmission success probability $p_{s,n}$ refers to $p_{s,\\N\\times\\{n\\}}$, i.e., it refers to the set of all users from $n$th class (or a typical user of that class).\n\\end{remark}\n\n\\begin{figure}[H]\n    \\centering\n    \\if\\printfig1\n        \\includegraphics[width=0.8\\textwidth]{Figures/Ch7_BipolarQueuedNetwork.pdf}\n    \\else\n        \\includegraphics[draft,width=0.8\\textwidth]{Figures/Ch7_BipolarQueuedNetwork.pdf}\n    \\fi\n    \\caption{Example of a bipolar high-mobility random network with $N=3$ user classes (one for each color). The queues represent the transmitters, and the potential receivers are represented by circular shapes of the corresponding color. The purpose of the arrows is to remember that the nodes are moving. Each transmitter communicates with the closest potential receiver, as it is shown by the dashed lines. Unconnected circles represent inactive receivers. The quantities $\\lambda$, $a$, $p_s$ and $\\phi$ are related to density of users, rate of arrival of packets, rate of service of packets and link quality, respectively.}\n    \\label{fig:BipolarNetwork}\n\\end{figure}\n\nEach transmitter of user class $n$ transmits with power $P_n$ constant over time, and the transmitted signal is subjected to Rayleigh short-term fading and power law path loss function $\\ell(r) = r^{-\\alpha}, r>0$, where $\\alpha>2$ is the path loss exponent.\n\n% For each time slot the position $X_{i\\,n}(t)$ of the $i$th transmitter is reallocated following the high-mobility random walk model \\cite{baccelli2010stochastic}.\n%\n% The $i$th transmitter of user class $n$ communicates with a receiver located at $Y_{i\\,n}(t)$. Thus, the distance between the $i$th transmitter of class $n$ and its destination is given by $R_{i\\,n}(t) = || X_{i\\,n}(t) - Y_{i\\,n}(t) ||$.\n%\nWe further assume that each transmitter is associated with a ``son'' PPP that models the locations of its potential receivers. The receiver associated with the $i$th transmitter of class $n$ is chosen as the closest point in the respective son PPP as illustrated in Figure~\\ref{fig:BipolarNetwork}.\n\nAs a consequence, the link distances $\\{ R_{i\\,n}(t) \\}_t$ are iid Rayleigh random variables\\footnote{The iid random variables for the link separation distance are of grave importance for the theoretical model. Otherwise, there would exist unstable queues and, consequently, the queueing network would be unstable.} \\cite[Eq.~(2.35)]{kingman1992poisson}.\n%\nRayleigh distributed link separation distance has been used in several other works investigating similar scenarios (see \\cite{haenggi2013diversity}).\n%\nWe denote the mean transmission distance $\\E[R_{i\\,n}(t)]$ simply by $\\overline{R}_n$ because we have stationarity across time and across users of a given class. Then, the density of $R_{i\\,n}$ can be expressed as\n\\begin{align*}\n    f_{R_n}(r) = \\frac{\\pi\\,r}{2 \\overline{R}_n^2} \\exp\\!\\left[ - \\frac{\\pi\\,r^2}{4\\overline{R}_n^2}\\right], \\qquad r\\in\\R_+.\n\\end{align*}\n\nThe occupation of the buffer at each transmitter is represented by its queue length $\\{ Q_{i\\,n}(t) \\}_t$ of infinite capacity.\n%\nThe packet arrival probability at each queue is denoted by $a_n$ and the medium access probability by $p_n$.\n%\nWithin each slot, the first event to take place for each transmitter with a non-empty queue is the medium access decision with probability $p_n$. If it is granted access and the signal to interference ratio (SIR) %\\footnote{We assume thermal noise is negligible; refer to \\cite{haenggi2012stochastic} for further details.}\nis greater than a threshold $\\theta_n>0$, a packet is successfully transmitted and leaves the queue. Then, we have the arrival of the next packet with probability $a_n$. The last event to take place is the displacement of the transmitters and destinations.\n\nThe queue lengths of the $i$th transmitter, user class $n$ are Markov chains represented by\n\\begin{equation*}\n\tQ_{i\\,n}(t+1) = (Q_{i\\,n}(t) - B_{i\\,n}(t))_+ + E_{i\\,n}(t), \\quad t \\in \\N,\n\\end{equation*}\nwhere $(\\cdot)_+ \\triangleq \\max\\{\\cdot,0\\}$, $\\{E_{i\\,n}(t)\\}_t$ are iid Bernoulli random variables of parameter $a_n$, i.e., $E_{i\\,n}(t)\\sim\\mathscr{B}(a_n)$ and represents the arrival process,\n$\n\tB_{i\\,n}(t) = e_{i\\,n}(t)\\,\\ind\\{\\text{SIR}_{i\\,n}(t)>\\theta_{n}\\}\n$\nrepresents the departure process, where $\\{e_{i\\,n}(t)\\}_t$ are iid Bernoulli random variables of parameter $p_n$, i.e., $e_{i\\,n}(t)\\sim\\mathscr{B}(p_n)$, and the constant $\\theta_n > 0$ represents the SIR threshold for successful communication.\n\n\\begin{remark}\n        In view of the model of Chapter~\\ref{cap:P2_00}, we have that the arrival point process $A_{i\\,(n)}$ is a Bernoulli point process of parameter $a_n$, the access point process $T_{i\\,(n)}$ is a Bernoulli point process of parameter $p_n$ and the transmissions times $T_{i\\,(n)}^*$ is a thinning of $T_{i\\,(n)}$ conditioned to the corresponding queue being non-empty, and the success probability model $\\mathscr{S}(f) = \\ind\\{f(0) > 1\\}$, where $f(t') = \\SIR_{i\\,n}(t-t')/\\theta_n$.\n\\end{remark}\n\n% % % % % % % % % % % % % % % % % % % % % % % % % % % % % %\n\\subsection{Analysis and Results}\n\\label{ssec:N-users}\n\nFrom the stationarity across users of a class and ergodicity regarding time (if the system is stable), the transmission success probability $p_{s,n}$ is the limiting probability of a successful transmission from a typical user of class $n$, i.e., $$p_{s,n} = \\lim_{t\\to\\infty} \\P(\\mathrm{SIR}_{i,n}(t) > \\theta_n).$$\n\n\\begin{note}\n    Remember that, \\textit{à priori}, we do not need to take $t\\to\\infty$, any $t$ would suffice in an ergodic process.\n    %\n    However, as discussed in Section~\\ref{sec:poisson_network} we would have to start the system at $-\\infty$ or start the system distributed according to the stationary distribution.\n\\end{note}\n\nThe stationary mean delay $D_n$ to transmit packets of class $n$ is defined as the limiting ($t\\to\\infty$) expected time a packet spends in the buffer and the server.\n%\nSee Theorem~\\ref{th:little}.\n% For each time slot and for each class we have an independent homogeneous PPP, which is stationary and isotropic (invariant to translation and rotation, respectively).\n\n% The following results from the literature are used in many proofs throughout the chapter. In a wireless network, let us assume that \\textit{(i)} the separation distance between a given pair TX - RX is equal to $r$, \\textit{(ii)} the positions of the interferers (users who will transmit packets in a given time slot) follow a PPP of density $\\lambda_\\mathrm{eff}$, and \\textit{(iii)} every transmitter has the same transmit power. Then, the probability of a successful transmission between TX and RX is given by \\cite[Sec.~III.A]{haenggi2009stochastic}\n% \\begin{align}\n% \t\\P(\\mathrm{SIR} > \\theta) &= \\E[\\euler^{-\\theta r^\\alpha I}] \\nonumber\\\\\n%     \t&= \\exp\\left( - \\pi\\,\\Gamma(1+\\delta) \\Gamma(1-\\delta)\\,\\theta^{\\delta}\\,r^2\\,\\lambda_\\mathrm{eff} \\right),\n% \\end{align}\n% where $\\delta \\triangleq 2/\\alpha$ and $I \\triangleq \\sum_{X\\in\\Phi} ||X||^{-\\alpha}$ is the interference received by RX normalized by the transmit power and $\\Phi$ is a PPP of density $\\lambda_\\mathrm{eff}$, which is the effective density of active sources.\n%\n\n% As described in the previous section, we consider a network with $N$ classes of users.\n%\nThe following proposition presents the stationary success probability and mean delay when transmitting a packet in a stable network. The results that guarantee stability are presented later in the sequence, in Theorem~\\ref{TH:NEC_SUFF}.\n\n\\begin{proposition} \\label{prop:psk}\n\tIf the network is stable, then the stationary success probability and mean delay for a typical user of class $n \\in \\cal{C}$ are given by\n\t\\begin{align}\n    \tp_{s,n} &= \\left( 1 + \\dfrac{\\psi_n}{P_n^\\delta}\\, \n        \\dfrac{\\sum_j P_j^\\delta\\,a_j\\lambda_j}\n        {1 - \\sum_j \\psi_j\\,a_j\\lambda_j} \\right)^{-1},\\label{eq:psn}\\\\ \n        D_n &= \\dfrac{1 - a_n}{p_n\\,p_{s,n} - a_n},\t\\label{eq:Dn}\n    \\end{align}\n    where the sums are taken over the set of user classes $\\cal{C}$, ${\\delta \\triangleq 2/\\alpha}$, and \n    \\begin{equation}\\label{eq:DefPhi}\n        \\psi_n\n            \\triangleq 4\\,\\Gamma(1+\\delta) \\Gamma(1-\\delta) \\overline{R}_n^2 \\theta_n^\\delta\n            = 4\\,\\overline{R}_n^2\\,\\theta_n^{\\delta}\\, \\frac{\\pi\\delta}{\\sin(\\pi \\delta)}.\n    \\end{equation}\n\\end{proposition}\n\n\\begin{proof}\n    First, we need to calculate the transmission success probability for a given traffic and a given link distance.\n    %\n    Using the reasoning of Proposition~\\ref{prop:PPP_ps} for the case of several classes of users, we have\n    \\begin{align} \\label{eq:P_SIR}\n    \t\\P(\\text{SIR}_{i\\,n}(t)>\\theta_n \\mid R_{i\\,n}) &= \\E\\!\\left[\\exp\\left(-\\frac{\\theta\\,R_{i\\,n}^\\alpha}{P_n} \\sum_{k\\in\\cal{C}} P_k\\,I_k\\right)\\right]\\nonumber\\\\\n        \t&= \\prod_{k\\in\\cal{C}} \\E\\!\\left[\\exp\\left(-\\theta\\,R_{i\\,n}^\\alpha\\frac{P_k}{P_n} I_k\\right)\\right] \\nonumber\\\\\n            &= \\prod_{k\\in\\cal{C}} \\exp\\!\\left( - \\pi R_{i\\,n}^2\\, \\theta^{\\delta}\\,\\frac{\\pi\\delta}{\\sin(\\pi\\delta)} \\frac{P_k^\\delta}{P_n^\\delta}\\lambda_\\mathrm{eff}^{(k)}(t)\\right) \\nonumber\\\\\n        \t&= \\exp\\!\\left( - \\pi R_{i\\,n}^2\\,\\theta^{\\delta}\\,\\frac{\\pi\\delta}{\\sin(\\pi\\delta)} \\,\\sum_{k\\in\\cal{C}}\\frac{P_k^\\delta}{P_n^\\delta}\\lambda_\\mathrm{eff}^{(k)}(t)\\right),\n    \\end{align}\n    where $I_n$ is the interference from the $n$th class normalized by the transmit power, and $\\lambda_{\\mathrm{eff}}^{(n)}$ is the density of the thinned Poisson point process $\\Phi_\\TX^{(n)}$ by the nodes that are transmitting.\n    %\n    It is assumed that $\\{I_n\\}_{n \\in \\cal{C}}$ is iid.\n\n    As $t\\to\\infty$, the effective PPP density of active sources $\\lambda_\\mathrm{eff}^{(n)}$ for each user class $n\\in\\cal{C}$ converges (by hypothesis) to $\\lambda_n\\,p_n\\,\\rho_n$, where $\\rho_n = a_n/(p_n\\,p_{s,n})$ is the load of the queue (or the probability of having a non-empty queue), which is the ratio between the arrival rate and the service rate of packets. Thus, $\\lambda_\\mathrm{eff}^{(n)} = \\lambda_n\\,a_n/p_{s,n}$.\n\n    Then, to calculate the transmission success probability $p_{s,n}$, we use \\eqref{eq:P_SIR}. Thus, by deconditioning the transmission success probability on $R_{i\\,n}$, we take into account that $R_{i\\,n}$ is Rayleigh distributed, that is\n    \\begin{align} \\label{eq:aux_psk}\n    \tp_{s,n} &= \\lim_{t\\to\\infty}\\P(\\text{SIR}_{i\\,n}(t)>\\theta_n) \\nonumber\\\\\n        \t&= \\int_0^\\infty \\lim_{t\\to\\infty} \\P(\\text{SIR}_{i\\,n}(t)>\\theta_n\n            \t\\mid R_{i\\,n}(t) = r)\\,f_{R_n}(r)\\,\\mathrm{d}r \\nonumber\\\\\n            &= \\int_0^\\infty \\frac{\\pi r}{2 \\overline{R}_n^2} \\exp\\!\\left[ - \\frac{\\pi\\,r^2}{4\\overline{R}_n^2} \\left(1+\\psi_n\\sum_{k\\in\\cal{C}}\\frac{P_k^\\delta}{P_n^\\delta}\\lambda_\\mathrm{eff}^{(k)}\\right)\\right]\\mathrm{d}r \\nonumber\\\\\n            &= \\left( 1 + \\dfrac{\\psi_n}{P_n^\\delta}\n      \t\t\t\\sum_{k\\in\\cal{C}} P_k^\\delta \\dfrac{a_k\\lambda_k}{p_{s,k}} \\right)^{-1}.\n    \\end{align}\n    This expression can be rearranged as\n    \\begin{equation} \\label{eq:psk_equivalence}\n    \t\\dfrac{P_n^\\delta}{\\psi_n} \\left( \\dfrac{1-p_{s,n}}{p_{s,n}}\\right) = \n        \\sum_{k\\in\\cal{C}} P_k^\\delta \\dfrac{a_k\\lambda_k}{p_{s,k}}.\n    \\end{equation}\n    Note that the right-hand side of \\eqref{eq:psk_equivalence} does not depend on $n$. Then, for all $j\\in\\cal{C}$, we have%\n    \\begin{equation} \\label{eq:Pi_Pk}\n    \t\\dfrac{P_j^\\delta}{\\psi_j} \\left( \\dfrac{1-p_{s,j}}{p_{s,j}}\\right) = \n        \\dfrac{P_n^\\delta}{\\psi_n} \\left( \\dfrac{1-p_{s,n}}{p_{s,n}}\\right).\n    \\end{equation}\n    For each $j$, we can solve the above equation for $p_{s,j}$ and plug it into the sum of \\eqref{eq:aux_psk}. Then, we can solve it for $p_{s,n}$, which ends the proof for the $p_{s,n}$.\n    \n    The buffer (plus server) is a discrete time Geo/Geo/1 queue (Definition~\\ref{def:geo/geo/1}) at stationary \\cite{stamatiou2010random} and the equation for the delay $D_n$ comes from Theorem~\\ref{th:geo/geo/1}.\n\\end{proof}\n\nThe following theorem shows the conditions for which the network is stable, i.e., it presents the region formed by all arrival rates $\\bm{a}$ that make the system stable.\n\n\\begin{theorem} \\label{TH:NEC_SUFF}\n\tA necessary and sufficient condition for the system network to be stable is that $\\bm{a} \\in \\bigcup_{\\nu\\in\\cal{V}} \\cal{E}_\\nu$, where $\\cal{V}$ is the space of all bijective functions from $\\cal{C}$ to $\\cal{C}$ and $\\cal{E}_\\nu$ is defined below with the convention $\\sum_{k=1}^0 \\cdot = 0$.\n\t\\begin{align} \\label{eq:stab_long}\n    \t\\cal{E}_{\\nu} \\triangleq \\Bigg\\{ \\bm{a} \\in [0,1)^N \\Bigm\\vert~ \n    \t& 0 \\le \n        \\dfrac{\\psi_{\\nu(n)}}{P_{\\nu(n)}^\\delta}\\dfrac{a_{\\nu(n)}}{p_{\\nu(n)}-a_{\\nu(n)}} \\nonumber\\\\\n        & < \\dfrac{ 1 - \\sum_{k=1}^{n-1} \\psi_{\\nu(k)} a_{\\nu(k)} \\lambda_{\\nu(k)} }\n        {\\sum_{k=1}^{n-1} P_{\\nu(k)}^{\\delta} a_{\\nu(k)}\\lambda_{\\nu(k)} +\n        \\sum_{k=n}^N P_{\\nu(k)}^\\delta p_{\\nu(k)}\\lambda_{\\nu(k)}},\n        \\quad n \\in \\cal{C} \\Bigg\\}.\n    \\end{align}\n\\end{theorem}\n%\n\\begin{proof}\n    Using stochastic dominance through dominant networks \\cite[Section~2.1.2]{kompella2014stable}, it is possible to derive necessary and sufficient conditions for stability.\n    %\n    A dominant network behaves exactly the same as the original network, except that all user classes in a subset $\\cal{D}$ of $\\cal{C}$ transmit dummy packets.\n    %\n    Thus, the dominant network have more or the same number of buffered packets as the original network  \\textit{almost surely}.\n    %\n    Then, if the dominant network is stable, the original network is stable as well. On the other hand, if the queues of the user classes in $\\cal{D}$ are not empty in the original network, then this system behaves exactly like the dominant network, i.e, both systems are \\emph{indistinguishable}, see Definition~\\ref{def:indistinguishable} and \\cite[Section~3.2]{szpankowski1994stability}.\n    %\n    Therefore, if the dominant network is unstable, then the original network is unstable as well.\n    %\n    In order to have necessary and sufficient conditions, we must perform this verification for all $\\cal{D} \\subset \\cal{C}$.\n    \n    Let us start with $\\cal{D}=\\cal{C}$, i.e., all users transmit dummy packets. For each step of the verification, we remove the stable user class from the set $\\cal{D}$. This procedure repeats until the set $\\cal{D}$ becomes empty. In order to attain stability of the dominant network we must have an arrival rate smaller than the service rate (Theorem~\\ref{th:loynes}). Thus, a sufficient condition for the first user class stability is, for any queue $i$ of this class (by symmetry),\n    \\begin{equation*}\n    \ta_1 < p_1\\,\\P(\\widetilde{\\text{SIR}}_{i,1} > \\theta_1) = p_1 \\left( 1 + \\dfrac{\\psi_1}{P_1^\\delta} \\sum_{k=1}^N P_k^\\delta\\,p_k\\lambda_k \\right)^{-1},\n    \\end{equation*}\n    where $\\widetilde{\\text{SIR}}$ represents the signal-interference ratio in the dominant network and the second equality comes from the same procedure to obtain \\eqref{eq:aux_psk} with $\\lambda_\\mathrm{eff}^{(n)} = \\lambda_n$ (all users are active, since every TX transmits dummy packets).\n    %\n    This guarantees stability for the first user class. Let us remove it from the set $\\cal{D}$. Then, we calculate the stationary success probability of the first user class $\\widetilde{p}^{(1)}_{s,1}$ for this dominant network. At steady state, we have\n    \\begin{equation*}\n    \t\\widetilde{p}^{(1)}_{s,1} = \\left( 1 + \\dfrac{\\psi_1}{P_1^\\delta} \\left( P_1^\\delta\\,p_1\\lambda_1\\dfrac{a_1}{p_1\\widetilde{p}^{(1)}_{s,1}} + \\sum_{k=2}^N P_k^\\delta\\,p_k\\lambda_k \\right) \\right)^{-1},\n    \\end{equation*}\n    which can be solved for $\\widetilde{p}^{(1)}_{s,1}$,\n    \\begin{equation*}\n    \t\\widetilde{p}^{(1)}_{s,1} = \\dfrac{1 - \\psi_1\\,\\lambda_1\\,a_1}{1 + \\frac{\\psi_1}{P_1^\\delta} \\sum_{k=2}^N P_k^\\delta\\,p_k\\lambda_k}.\n    \\end{equation*}\n    The next step is to verify the conditions of stability for the second user class, when the first user class is at steady state. After that, we remove the second user class from the set $\\cal{D}$ and calculate the stationary success probability of the two stable user classes in the dominant network. We repeat these steps until we remove all user classes, \\textit{i.e}, $\\cal{D} = \\{\\}$. We show this by induction; we suppose stability of the user classes $1,2,\\dots,j-1$. Let $\\cal{D} = \\{j,j+1,\\dots\\,N\\}$; the $j$th user class is stable, given that all the user classes in $\\cal{C}\\setminus\\cal{D}$ are stable, when\n    \\begin{align} \\label{eq:aux_aj}\n    \ta_j \n    \t&< p_j\\,\\P(\\widetilde{\\text{SIR}}_{i,j} > \\theta_j) \\nonumber\\\\\n    \t&= p_j \\left( 1+\\dfrac{\\psi_j}{P_j^\\delta} \n            \\left( \\sum_{k=1}^{j-1} P_k^\\delta\\,\\lambda_k\\,\\dfrac{a_k}\n            {\\widetilde{p}^{(j)}_{s,k}} + \\sum_{k=j}^N P_k^\\delta\\,p_k\\lambda_k \\right) \\right)^{-1},\n    \\end{align}\n    where $\\widetilde{p}^{(j)}_{s,k}$ is the $k$th user class success probability ($1 \\leq k < j$) at steady state in the dominant network at the $j$th step. To calculate this probability, we must solve the following system of equations. For $k \\in \\{1,2,\\dots,j-1\\}$\n    \\begin{equation*}\n    \t\\widetilde{p}^{(j)}_{s,k} = \\left( 1 + \\dfrac{\\psi_k}{P_k^\\delta}\n        \\left( \\sum_{\\ell = 1}^{j-1} P_\\ell^\\delta\\,\\lambda_\\ell\\,\n        \\dfrac{a_\\ell}{\\widetilde{p}^{(j)}_{s,\\ell}} + \n        \\sum_{\\ell = j}^{N} P_\\ell^\\delta\\,p_\\ell\\lambda_\\ell \\right) \\right)^{-1}.\n    \\end{equation*}\n    Using an analogous approach as the one presented in the proof of Proposition~\\ref{prop:psk}, we have that for $k \\in \\{1,2,\\dots,j-1\\}$,\n    \\begin{equation*}\n    \t\\widetilde{p}^{(j)}_{s,k} =\n        \\left( 1 + \\dfrac{\\psi_k}{P_k^\\delta} \n        \\dfrac{ \\sum_{\\ell=1}^{j-1} P_\\ell^\\delta\\,a_{\\ell}\\,\\lambda_\\ell +\n        \\sum_{\\ell=j}^{N} P_\\ell^\\delta\\,p_\\ell\\lambda_\\ell }\n        { 1 - \\sum_{\\ell=1}^{j-1} \\psi_{\\ell}\\,a_{\\ell}\\,\\lambda_\\ell} \n        \\right)^{-1}.\n    \\end{equation*}\n    Comparing the last two equations, it is easy to see that\n    \\begin{align*}\n    \t\\sum_{\\ell = 1}^{j-1} P_\\ell^\\delta\\,\\lambda_\\ell\\,\n        &\\dfrac{a_\\ell}{\\widetilde{p}^{(j)}_{s,\\ell}} + \n        \\sum_{\\ell = j}^{N} P_\\ell^\\delta\\,p_\\ell\\,\\lambda_\\ell = \\dfrac{ \\sum_{\\ell=1}^{j-1} P_\\ell^\\delta\\,a_{\\ell}\\,\\lambda_\\ell +\n        \\sum_{\\ell=j}^{N} P_\\ell^\\delta\\,p_\\ell\\lambda_\\ell }\n        { 1 - \\sum_{\\ell=1}^{j-1} \\psi_{\\ell}\\,a_{\\ell}\\,\\lambda_\\ell } .\n    \\end{align*}    \n    Finally, we can use this result to rewrite \\eqref{eq:aux_aj} as, for all $j \\in \\cal{C}$,\n    \\begin{equation*}\n        0 \\le\n    \t\\dfrac{\\psi_j}{P_j^\\delta}\\,\\dfrac{a_j}{p_j-a_j} <\n        \\dfrac{1 - \\sum_{k=1}^{j-1} \\psi_k\\,a_k\\,\\lambda_k}\n        {\\sum_{k=1}^{j-1} P_k^\\delta\\,a_k\\lambda_k +\n        \\sum_{k=j}^N P_k^\\delta\\,p_k\\lambda_k}.\n    \\end{equation*}\n    This concludes the proof since the extension for the other partitions of $\\cal{C}$ is analogous.\n\\end{proof}\n\nTheorem~\\ref{TH:NEC_SUFF} requires verifying $N\\!\\times\\!N!$ inequalities, whereas the following theorem is equivalent and it involves only $N$ inequalities.\n%\nThus, Theorem~\\ref{TH:STABILITY} presents a simpler form of verifying the conditions for stability.\n% Also, it relates (in the proof) the stability condition with the stationary mean delays $\\bm{D}$.\nHowever, we cannot prove \\ref{TH:STABILITY} without \\ref{TH:NEC_SUFF}.\n\n\\begin{theorem}[\\textbf{Network Stability}] \\label{TH:STABILITY}\n\tThe system network is stable if and only of $\\bm{a}\\in\\cal{R}$,\n    \\begin{align*}\n    \t\\cal{R}\n        \\triangleq \\bigg\\{ \\bm{a}\\in[0,1)^N \\bigm\\vert ~ a_n < p_n, \\dfrac{\\psi_n}{P_n^\\delta}\\,\\dfrac{a_n}{p_n-a_n} < \n        \\dfrac{1 - \\sum_{k} \\psi_k\\,a_k \\lambda_k}\n        {\\sum_{k} P_k^{\\delta}\\,a_k \\lambda_k} \n        \\quad\\forall n \\in \\cal{C}  \\bigg\\}.\n        % &= \\bigg\\{ \\bm{a}\\in[0,1)^N \\bigm\\vert ~ a_n < p_n, \\\\\n        % &\\hspace{2mm} \\dfrac{\\psi_n}{P_n^\\delta}\\,\\dfrac{a_n}{p_n-a_n} < \n        % \\dfrac{1 - \\sum_{k \\neq n} \\psi_k\\,a_k\\,\\lambda_k}\n        % {P_n^\\delta\\,p_n\\lambda_n + \\sum_{k \\neq n} P_k^{\\delta}\\,a_k\\,\\lambda_k}\n        % ~\\forall n \\in \\cal{C}  \\bigg\\}.\n    \\end{align*}\n\\end{theorem}\n\n\\begin{proof}\n\tThe proof consists of showing that the set $\\cal{R}$ is equal to the set defined in Theorem~\\ref{TH:NEC_SUFF}.\n    %\n    First, let us prove that $\\bigcup_{\\nu\\in\\cal{V}} \\cal{E}_\\nu \\subset \\cal{R}$.\n    %\n    For that we suppose $\\bm{a} \\in \\cal{E}_\\nu$ and we show $\\bm{a} \\in \\cal{R}$ for all $\\nu\\in\\cal{V}$ by induction.\n    %\n    For simplicity of exposition let us take $\\cal{E}_\\nu$ with $\\nu: n \\longmapsto n$, $n\\in\\cal{C}$.\n    %\n    We assume the inequality\n    \\begin{align}\n        \\dfrac{\\psi_{N-j}}{P_{N-j}^\\delta}\\,\\dfrac{a_{N-j}}{p_{N-j}-a_{N-j}} \n        & < \\dfrac{1 - \\sum_{k=1}^{N} \\psi_k\\,a_k \\lambda_k}{\\sum_{k=1}^{N} P_k^\\delta\\,a_k\\lambda_k}. \\label{eq:th2_basecase}\n    \\end{align}\n    %\n    is true for all $j\\in\\{0,\\dots,m-1\\}$ and we prove that it is also true for $j=m$.\n    %\n    First, we have to prove the base case $m = 1$.\n    %\n    Since $\\bm{a}\\in \\cal{E}_\\nu$, then for $j=0$ ($n=N$)\n    %\n    \\begin{align*}\n        \t\\dfrac{\\psi_N}{P_N^\\delta}\\,\\dfrac{a_N}{p_N-a_N} \n        \t& < \\dfrac{1 - \\sum_{k=1}^{N-1} \\psi_k\\,a_k \\lambda_k}{\\sum_{k=1}^{N-1} P_k^\\delta\\,a_k\\lambda_k + P_N^\\delta\\,p_N\\lambda_N} \\\\\n        & = \\dfrac{1 - \\sum_{k=1}^{N} \\psi_k\\,a_k \\lambda_k + \\psi_N\\,a_N \\lambda_N}{\\sum_{k=1}^{N} P_k^\\delta\\,a_k\\lambda_k + P_N^\\delta\\,(p_N-a_N)\\lambda_N}.\n    \\end{align*}\n    %\n    Then, using simple manipulations, we can show that the above inequality is equivalent to\n    %\n    \\begin{align*}\n        \t\\dfrac{\\psi_N}{P_N^\\delta}\\,\\dfrac{a_N}{p_N-a_N} \n        \t& < \\dfrac{1 - \\sum_{k=1}^{N} \\psi_k\\,a_k \\lambda_k}{\\sum_{k=1}^{N} P_k^\\delta\\,a_k\\lambda_k}.\n    \\end{align*}\n    %\n    Thus, the base case $m = 1$ is true.\n    %\n    Now, for $j=m$ and $\\bm{a}\\in \\cal{E}_\\nu$, we know that\n    \\begin{align*}\n        \\dfrac{\\psi_{N-m}}{P_{N-m}^\\delta}\\,\\dfrac{a_{N-m}}{p_{N-m}-a_{N-m}}\n        & < \\dfrac{1 - \\sum_{k=1}^{N-m-1} \\psi_k\\,a_k \\lambda_k}\n        \t{\\sum_{k=1}^{N-m-1} P_k^\\delta\\,a_k\\lambda_k \n        \t    + \\sum_{k=N-m}^{N} P_k^\\delta\\,p_k\\lambda_k} \\\\\n        & = \\dfrac{1 - \\sum_{k=1}^{N} \\psi_k\\,a_k \\lambda_k \n                + \\sum_{k=N-m}^{N} \\psi_k\\,a_k \\lambda_k}\n            {\\sum_{k=1}^{N} P_k^\\delta\\,a_k\\lambda_k \n                + \\sum_{k=N-m}^{N} P_k^\\delta\\,(p_k-a_k)\\lambda_k}.\n    \\end{align*}\n    Through simple manipulations we can show that the above inequality is equivalent to\n    \\begin{align*}\n        & \\dfrac{\\psi_{N-m}}{P_{N-m}^\\delta}\\,\\dfrac{a_{N-m}}{p_{N-m}-a_{N-m}} < \\dfrac{1 - \\sum_{k=1}^{N} \\psi_k\\,a_k \\lambda_k \n                + \\sum_{k=N-m+1}^{N} \\psi_k\\,a_k \\lambda_k}\n            {\\sum_{k=1}^{N} P_k^\\delta\\,a_k\\lambda_k \n                + \\sum_{k=N-m+1}^{N} P_k^\\delta\\,(p_k-a_k)\\lambda_k}.\n    \\end{align*}\n    Now, we only need to verify that\n    \\begin{align*}\n    &\\dfrac{1 - \\sum_{k=1}^{N} \\psi_k\\,a_k \\lambda_k \n                + \\sum_{k=N-m+1}^{N} \\psi_k\\,a_k \\lambda_k}\n            {\\sum_{k=1}^{N} P_k^\\delta\\,a_k\\lambda_k \n                + \\sum_{k=N-m+1}^{N} P_k^\\delta\\,(p_k-a_k)\\lambda_k} < \\dfrac{1 - \\sum_{k=1}^{N} \\psi_k\\,a_k \\lambda_k}\n            {\\sum_{k=1}^{N} P_k^\\delta\\,a_k\\lambda_k}.\n    \\end{align*}\n    Again, simple manipulations lead to the equivalent inequality\n    \\begin{align*}\n    &\\dfrac{\\sum_{k=N-m+1}^{N} \\psi_k\\,a_k \\lambda_k}\n            {\\sum_{k=N-m+1}^{N} P_k^\\delta\\,(p_k-a_k)\\lambda_k}\n        < \\dfrac{1 - \\sum_{k=1}^{N} \\psi_k\\,a_k \\lambda_k}\n            {\\sum_{k=1}^{N} P_k^\\delta\\,a_k\\lambda_k},\n    \\end{align*}\n    which is true from the base case. This can be seen by multiplying  \\eqref{eq:th2_basecase} by $P^\\delta_{N-j}(p_{N-j}-a_{N-j})$ at both sides of the inequality and summing over $j\\in\\{0,\\dots,m-1\\}$. Thus, $\\cal{E}_\\nu \\subset \\cal{R}$ for the mapping $\\nu: n \\longmapsto n$. The extension for another instances of $\\nu\\in\\cal{V}$ is analogous. This concludes the proof that $\\bigcup_{\\nu\\in\\cal{V}} \\cal{E}_\\nu \\subset \\cal{R}$.\n    %\n    \n    However, we still need to prove the converse, that is ${\\cal{R} \\subset \\bigcup_{\\nu\\in\\cal{V}}} \\cal{E}_\\nu$.\n    %\n    Note that the set of arrival rates that makes the system stable in Theorem~\\ref{TH:NEC_SUFF} requires that at least one $a_n$ ($n\\in\\cal{C}$) satisfies\n    \\begin{equation} \\label{eq:aux_stab_first}\n    \t\\dfrac{\\psi_n}{P_n^\\delta}\\,\\dfrac{a_n}{p_n-a_n} <\n        \\dfrac{1}{\\sum_{k=1}^N P_k^\\delta\\,p_k \\lambda_k}.\n    \\end{equation}\n    \tLet us show that $\\cal{R}$ requires the same restriction by contradiction. Suppose that there exist $\\bm{a}\\in\\cal{R}$ such that\n        %\n    \\begin{equation} \\label{eq:aux_contr0}\n        \\dfrac{\\psi_n}{P_n^\\delta}\\,\\dfrac{a_n}{p_n-a_n} \\ge\n        \\dfrac{1}{\\sum_{k=1}^N P_k^\\delta\\,p_k \\lambda_k}\n        \\quad \\forall n \\in \\cal{C}.\n    \\end{equation}\n    %\n    Multiplying \\eqref{eq:aux_contr0} by $P_n^\\delta(p_n-a_n)\\lambda_n > 0$ at both sides and summing over $n\\in\\cal{C}$ we have\n    %\n    \\begin{align*}\n        \\sum_{n=1}^N \\psi_n a_n \\lambda_n \n            \\ge \\frac{\\sum_{n=1}^N P_n^\\delta (p_n-a_n) \\lambda_n}\n            {\\sum_{k=1}^N P_k^\\delta\\,p_k \\lambda_k},\n    \\end{align*}\n    %\n    which is equivalent to\n    %\n    \\begin{align} \\label{eq:aux_case0}\n        \\left(\\sum_{n=1}^N \\psi_n a_n \\lambda_n \\right)\n            \\left(\\sum_{k=1}^N P_k^\\delta\\,p_k \\lambda_k \\right)\n            \\ge \\sum_{n=1}^N P_n^\\delta (p_n-a_n) \\lambda_n.\n    \\end{align}\n    %\n    Since $\\bm{a}\\in\\cal{R}$, then\n    \\begin{align} \\label{eq:aux_theo2}\n        \\dfrac{\\psi_n}{P_n^\\delta}\\,\\dfrac{a_n}{p_n-a_n} < \n            \\dfrac{1 - \\sum_{k} \\psi_k\\,a_k \\lambda_k}\n            {\\sum_{k} P_k^{\\delta}\\,a_k \\lambda_k} \\quad \\forall n\\in\\cal{C}.\n    \\end{align}\n    %\n    Again, multiplying \\eqref{eq:aux_theo2} by $P_n^\\delta(p_n-a_n)\\lambda_n > 0$ at both sides, summing over $n\\in\\cal{C}$ and performing some manipulations we have\n    %\n    \\begin{align} \\label{eq:aux_theo2_case0}\n        &\\left(\\sum_{n=1}^N \\psi_n a_n \\lambda_n \\right)\n            \\left(\\sum_{k=1}^N P_k^\\delta\\,a_k \\lambda_k \\right) < \\left(1 - \\sum_{k=1}^N \\psi_k\\,a_k \\lambda_k \\right)\\left(\\sum_{n=1}^N P_n^\\delta (p_n-a_n) \\lambda_n\\right).\n    \\end{align}\n    %\n    Then, through some manipulations on \\eqref{eq:aux_case0} and \\eqref{eq:aux_theo2_case0}, we have\n    %\n    \\begin{align*}\n        0 &\\le \\sum_{n=1}^N P_n^\\delta a_n \\lambda_n - \\left(1 - \\sum_{k=1}^N \\psi_k\\,a_k \\lambda_k \\right)\\left(\\sum_{n=1}^N P_n^\\delta p_n \\lambda_n\\right) < 0,\n    \\end{align*}\n    which clearly is a contradiction, since $\\cal{R}$ is a non-empty set. Thus, there exists at least one $a_n$, $n\\in\\cal{C}$ that satisfies \\eqref{eq:aux_stab_first}.\n    %\n    For simplicity of exposition, let us suppose that the arrival rate $a_n$ that satisfies this restriction is from the first user class ($n=1$). The next step is to show that as in the set $\\bigcup_{\\nu\\in\\cal{V}}\\cal{E}_\\nu$, the set $\\cal{R}$ also requires that we have at least one $a_n$, aside from $a_1$, that satisfies\n    %\n    \\begin{equation*}\n    \t\\dfrac{\\psi_n}{P_n^\\delta}\\,\\dfrac{a_n}{p_n-a_n} <\n        \\dfrac{1-\\psi_1\\,\\lambda_1\\,a_1}{P_1^\\delta\\,a_1\\lambda_1+\n        \\sum_{k=2}^N P_k^\\delta\\,p_k\\lambda_k}.\n    \\end{equation*}\n    %\n    We can also prove this by contradiction and then, for simplicity of exposition, suppose that $a_2$ is the one that satisfies this restriction. We repeat this procedure until we reach all user classes. Let us show the $j$th step for completeness, $j\\in\\cal{C}$. Suppose that for all $n \\in \\{j,j+1,\\dots,N\\}$,\n    %\n    \\begin{align} \\label{eq:aux_contr_j}\n        \\dfrac{\\psi_n}{P_n^\\delta}\\dfrac{a_n}{p_n-a_n}\n        \\ge \\dfrac{ 1 - \\sum_{k=1}^{j-1} \\psi_k a_k \\lambda_k }\n        {\\sum_{k=1}^{j-1} P_k^{\\delta} a_k\\lambda_k +\n        \\sum_{k=j}^N P_k^\\delta p_k\\lambda_k}.\n    \\end{align}\n    Multiplying \\eqref{eq:aux_contr_j} by $P_n^\\delta(p_n-a_n)\\lambda_n > 0$ at both sides, summing over $n\\in\\{j,j+1,\\dots,N\\}$ and manipulating we have\n    %\n    \\begin{align} \\label{eq:aux_case_j}\n        &\\left(\\sum_{n=j}^N \\psi_n a_n \\lambda_n \\right)\\!\n            \\left(\\sum_{k=1}^N P_k^\\delta\\,a_k \\lambda_k + \\sum_{k=j}^N P_k^\\delta\\,(p_k-a_k) \\lambda_k \\right) \\ge \\left( 1 - \\sum_{k=1}^{j-1} \\psi_k a_k \\lambda_k \\right)\\!\n            \\left( \\sum_{n=j}^N P_n^\\delta (p_n-a_n) \\lambda_n \\right).\n    \\end{align}\n    %\n    Once again, multiplying \\eqref{eq:aux_theo2} by $P_n^\\delta(p_n-a_n)\\lambda_n > 0$ at both sides, summing over $n\\in\\{j,j+1,\\dots,N\\}$ and manipulating we have\n    %\n    \\begin{align} \\label{eq:aux_theo2_case_j}\n        &\\left(\\sum_{n=j}^N \\psi_n a_n \\lambda_n \\right)\n            \\left(\\sum_{k=1}^N P_k^\\delta\\,a_k \\lambda_k \\right) < \\left(1 - \\sum_{k=1}^N \\psi_k\\,a_k \\lambda_k \\right)\\left(\\sum_{n=j}^N P_n^\\delta (p_n-a_n) \\lambda_n\\right).\n    \\end{align}\n    %\n    Then, through some manipulations on \\eqref{eq:aux_case_j} and \\eqref{eq:aux_theo2_case_j}, we have\n    %\n    \\begin{align*}\n        0 &\\le \\left(1 - \\sum_{k=1}^N \\psi_k\\,a_k \\lambda_k \\right)\\left(\\sum_{n=j}^N P_n^\\delta (p_n-a_n) \\lambda_n\\right) - \\left(\\sum_{n=j}^N \\psi_n a_n \\lambda_n \\right)\n            \\left(\\sum_{k=1}^N P_k^\\delta\\,a_k \\lambda_k \\right) < 0.\n    \\end{align*}\n    %\n    As expected, we have a contradiction. Then, we must have at least one $a_n$, $n\\in{\\{j,j+1,\\dots,N\\}}$ that satisfies\n    %\n    \\begin{equation} \\label{eq:aux_region_j}\n    \t\\dfrac{\\psi_n}{P_n^\\delta}\\,\\dfrac{a_n}{p_n-a_n} <\n        \\dfrac{1-\\sum_{k=1}^{j-1} \\psi_k\\,a_k\\,\\lambda_k}\n        {\\sum_{k=1}^{j-1} P_k^\\delta\\,a_k\\lambda_k+\n        \\sum_{k=j}^N P_k^\\delta\\,p_k\\lambda_k}.\n    \\end{equation}\n    %\n    We assume that this is satisfied by the $j$th class and in this case, $\\cal{R} \\subset \\cal{E}_\\nu$ for $\\nu: n \\longmapsto n$.\n    %\n    Without the assumption of the ordering in which \\eqref{eq:aux_region_j} is satisfied, we conclude that \\eqref{eq:aux_region_j} must hold for at least one permutation of $\\cal{C}$. This region is exactly $\\bigcup_{\\nu\\in\\cal{V}} \\cal{E}_\\nu$. Therefore, ${\\cal{R} \\subset \\bigcup_{\\nu\\in\\cal{V}} \\cal{E}_\\nu}$.\n    %\n    Finally, ${\\cal{R} = \\bigcup_{\\nu\\in\\cal{V}} \\cal{E}_\\nu}$.\n\\end{proof}\n\n\\begin{remark}\n        The convoluted conditions of Theorem~\\ref{TH:NEC_SUFF} are extensively reduced in Theorem~\\ref{TH:STABILITY}, for which we can see that as the density of users $\\lambda_n$ increases or the quantity $\\psi_n$ (which is inversely related to link quality, see \\eqref{eq:DefPhi}) increases for some $n\\in\\cal{C}$, then the stability region $\\cal{R}$ decreases for all user classes. On the other hand, if the transmission power $P_n$ increases for some $n\\in\\cal{C}$, then the stability region $\\cal{R}$ increases for the $n$th class and decreases for all other classes. Surprisingly, when the access probability $p_n$ varies, the only affected class (regarding stability region) is the $n$th class, as long $p_n>a_n$.\n\\end{remark}\n\nFigure~\\ref{fig:ThStab} shows an example of stability region for $N=3$ classes, where we have used only three non-linear inequalities instead of 18.\n%\nThe following corollary establishes a simple result on stability, which is used in Section~\\ref{sec:application} to propose and solve optimization problems regarding delay and throughput.\n\n\\begin{corollary} \\label{cor:stab}\n\tThere exists a vector of transmit powers  ${\\bm{P} \\in \\R_+^N}$ such that the network is stable if and only if $\\bm{a}\\in\\cal{S}_0$, where\n    \\begin{equation*}\n    \t\\cal{S}_0 \\triangleq \\left\\lbrace \\bm{a}\\in[0,1)^N \\bigm\\vert 0 \\le \\sum_{n\\in\\cal{C}} \\dfrac{\\psi_n \\lambda_n}{\\frac{1}{a_n}-\\frac{1}{p_n}} < 1 \\right\\rbrace.\n    \\end{equation*}\n\\end{corollary}\n\\begin{proof}\n    First, let us show that $\\cal{R} \\subset \\cal{S}_0$ for all ${\\bm{P} \\in \\R_+^N}$.\n    %\n    If $\\bm{a}\\in\\cal{R}$, then for all $n\\in\\cal{C}$\n    \\begin{align*}\n        \\dfrac{\\psi_n}{P_n^\\delta}\\,\\dfrac{a_n}{p_n-a_n} < \n        \\dfrac{1 - \\sum_{k} \\psi_k\\,a_k \\lambda_k}\n        {\\sum_{k} P_k^{\\delta}\\,a_k \\lambda_k}.\n    \\end{align*}\n    %\n    Multiplying both sides of the above equation by $P_n a_n \\lambda_n$ and summing over all $n\\in\\cal{C}$ results in \\vspace{-5mm}\n    \\begin{align*}\n        \\sum_{n\\in\\cal{C}} \\psi_n \\lambda_n\\,\\dfrac{p_n\\,a_n}{p_n-a_n} < 1\n    \\end{align*}\n    after some manipulations. Thus, $a\\in\\cal{S}_0$.\n    \n    Now, let us show that $\\cal{S}_0 \\subset \\cal{R}$ for some $\\bm{P}\\in\\R_+^N$.\n    %\n    In particular, let us choose $P_n = \\psi_n a_n/(p_n-a_n)$, $n\\in\\cal{C}$. Then, the inequalities that describe the region $\\cal{R}$ can be rewritten as one unique inequality\n    \\begin{align*}\n        1 < \\frac{1 - \\sum_{k} \\psi_k a_k \\lambda_k}\n            {\\sum_k \\psi_k a_k^2 \\lambda_k / (p_k-a_k)}\n    \\end{align*}\n    that does not depend on $n$ anymore. It is easy to show that this inequality is the same as the one that defines the region $\\cal{S}_0$. Thus, if $\\bm{a}\\in\\cal{S}_0$, then $\\bm{a}\\in\\cal{R}$ for that choice of $\\bm{P}$ (or any scalar multiple). This ends the proof.\n\\end{proof}\n\nFigure~\\ref{fig:CorStab} shows the region of arrival rates, according to Corollary~\\ref{cor:stab}, for which it is possible to find transmit powers that make the network stable.\n%\nOn the other hand, out of this region, the system is always unstable. It is worth mentioning that $\\psi_n$, defined in \\eqref{eq:DefPhi}, is related to the quality of the link between receiver and transmitter for class $n\\in\\cal{C}$; the larger is the value of $\\psi_n$, the poorer is the quality of the link.\n%\nAlso, the stability region $\\cal{R}$ showed in Fig.~\\ref{fig:ThStab} is contained in $\\cal{S}_0$. This is expected since we used the same parameters for both sets and Corollary~\\ref{cor:stab} considers the best case scenario, where we can choose the transmit powers $\\bm{P}$ for each $\\bm{a}$.\n\n\\begin{figure}\n\\centering\n\\begin{subfigure}[t]{.45\\textwidth}\n  \\centering\n    \\if\\printfig1\n        \\includegraphics[width=\\textwidth]{Figures/Ch7_theorem_stab.pdf}\n    \\else\n        \\includegraphics[draft,width=\\textwidth]{Figures/Ch7_theorem_stab.pdf}\n    \\fi\n    \\caption{Stability region $\\cal{R}$ according to Theorem~\\ref{TH:STABILITY} for $p_1 = 1/3$, $p_2 = 2/3$, $p_3 = 1$, $\\psi_1\\lambda_1=1$, $\\psi_2\\lambda_2=2$, $\\psi_3\\lambda_3=3$, $\\psi_1/P_1 = 1/3$, $\\psi_2/P_2 = 1/2$, $\\psi_3/P_3= 1$.}\n\\label{fig:ThStab}\n\\end{subfigure}%\n\\begin{subfigure}{.05\\textwidth}\n\\hspace{.05\\textwidth}\n\\end{subfigure}%\n\\begin{subfigure}[t]{.45\\textwidth}\n  \\centering\n    \\if\\printfig1\n        \\includegraphics[width=\\textwidth]{Figures/Ch7_corollary_stab.pdf}\n    \\else\n        \\includegraphics[draft,width=\\textwidth]{Figures/Ch7_corollary_stab.pdf}\n    \\fi\n    \\caption{Maximum stability region $\\cal{S}_0$ according to Corollary~\\ref{cor:stab} for $p_1 = 1/3$, $p_2 = 2/3$, $p_3 = 1$,  $\\psi_1\\lambda_1=1$, $\\psi_2\\lambda_2=2$, $\\psi_3\\lambda_3=3$.}\n\\label{fig:CorStab}\n\\end{subfigure}\n\\caption{}\n\\end{figure}\n\nFrom now on, we assume that whenever there is a packet in the buffer, the corresponding transmitter attempts to transmit, i.e., the medium access probability $p_n=1$ for all $n\\in\\cal{C}$.\n%\nWe discuss in Section~\\ref{sec:high-mobility} the validity of this assumption and the high-mobility assumption. The motivation is that, when the access probability of all classes is equal to one, we maximize the stability region $\\cal{R}$.\n%\nThis is easy to see with the inequalities of Theorem~\\ref{TH:STABILITY}, where the right-hand side does not depend on $p_n$ and the left-hand side decreases monotonically with $p_n$. Thus, the stability region is maximized when $p_n=1$ for all $n\\in\\cal{C}$. The same occurs in Corollary~\\ref{cor:stab}.\n%\nThis result is surprising and might be explained by the fact that we have independence between adjacent time slots and, therefore, for each time slot there is a new scenario (a new effective PPP).\n%\nThen, it makes sense to always try retransmission. This approach also minimizes the mean delay according to \\eqref{eq:Dn}, since the success probability $p_{s,n}$ in \\eqref{eq:psn} does not depend on the access probability in a stable network.\n\nUsing Proposition \\ref{prop:psk}, Proposition~\\ref{prop:identity_1} is introduced, which presents an equation that relates all performance parameters independently of the transmission powers. Also, the conditions for stability are extensively simplified, see Corollary~\\ref{cor:stab}.\n%\n\\begin{proposition} \\label{prop:identity_1}\n\tIf the network is stable and $p_n=1$ for all ${n\\in\\cal{C}}$, then the following identities hold (at stationary state):\n    \\begin{equation}\\label{eq:identity_1}\n    \t\\sum_{n\\in\\cal{C}} \\psi_n\\,\\lambda_n\\,\\dfrac{D_n}{D_n-1}\\,\\dfrac{a_n}{1-a_n} = 1,\n    \\end{equation}\n    and\n    \\begin{equation*}\n    \t\\frac{\\psi_j}{P_j^\\delta}\n        \\left( \\frac{D_j}{D_j-1}\\,\\frac{1}{1-a_j} - 1\\right) =\n        \\frac{\\psi_k}{P_k^\\delta} \\left( \\frac{D_k}{D_k-1}\\,\n        \\frac{1}{1-a_k} - 1 \\right)\n        \\quad \\forall\\,j,k\\in\\cal{C}.\n    \\end{equation*}\n\\end{proposition}\n\n\\begin{proof}\n\tWe start with the terms of the sum,\n\t\\begin{align*}\n\t\t\\psi_n\\,\\lambda_n\\,\\dfrac{D_n}{D_n-1}\\,\\dfrac{a_n}{1-a_n}\n        &\\stackrel{\\text{(i)}}{=} \\psi_n\\lambda_n\\dfrac{a_n}{1-p_{s,n}}\\\\ \n\t\t&= P_n^\\delta \\dfrac{\\lambda_n\\,a_n}{p_{s,n}} \\left( \n        \\dfrac{\\psi_n}{P_n^\\delta} \\dfrac{p_{s,n}}{1-p_{s,n}} \\right)\\\\\n        &\\stackrel{\\text{(ii)}}{=} \\frac{ P_n^\\delta\\frac{\\lambda_n\\,a_n}{p_{s,n}} }\n        { \\sum_j P_j^\\delta\\frac{\\lambda_j\\,a_j}{p_{s,j}} },\n\t\\end{align*}\n    where (i) comes from \\eqref{eq:Dn} with $p_n=1$ and (ii) comes from \\eqref{eq:psk_equivalence}. Summing over $\\cal{C}$ ends the proof of the first identity.\n    %\n    For the second relation of Proposition~\\ref{prop:identity_1}, we use \\eqref{eq:Dn} once again to find\n    \\begin{equation*}\n    \t\\dfrac{\\psi_n}{P_n^\\delta} \\left( \\dfrac{D_n}{D_n-1}\\,\\dfrac{1}{1-a_n} - 1\\right) = \\dfrac{\\psi_n}{P_n^\\delta} \\dfrac{p_{s,n}}{1-p_{s,n}}.\n    \\end{equation*}\n    Comparing this expression with \\eqref{eq:Pi_Pk} ends the proof.\n\\end{proof}\n\nProposition~\\ref{prop:identity_1} is an elegant form to see that a channel is a limited resource regarding traffic intensity and delay. Let us rewrite the identity \\eqref{eq:identity_1} in terms of physical parameters,\n\\begin{equation} \\label{eq:physical}\n\t\\sum_{n=1}^N 4\\,\\lambda_n\\,\\overline{R}_n^2\\,\\theta_n^{2/\\alpha}\\,\\dfrac{D_n}{D_n-1}\\,\\dfrac{a_n}{1-a_n} = \\dfrac{\\sin(2\\pi/\\alpha)}{2\\pi/\\alpha}.\n\\end{equation}\n%\nNote that $\\frac{a_n}{1-a_n}$ and $\\frac{\\sin(2\\pi/\\alpha)}{2\\pi/\\alpha}$ are monotonic increasing functions and $\\frac{D_n}{D_n-1}$ is a monotonic decreasing function. The right hand-side of \\eqref{eq:physical} can be seen as the amount of resource available to all users of the channel.\n%\nLarger $\\alpha$ results in higher   $\\frac{\\sin(2\\pi/\\alpha)}{2\\pi/\\alpha}$, meaning that a larger amount of resource is available to users. This can be explained by recalling that a larger path loss exponent leads to stronger isolation among links sharing the channel and, consequently, more users can be accommodated in the network.\n%\nTherefore, the larger the path loss exponent $\\alpha$, the larger (smaller) the terms $\\lambda_n$, $\\overline{R}_n$, $\\theta_n$, $a_n$ ($D_n$) can be. The identity \\eqref{eq:physical} also tells us that the $n$th class of user takes a well-defined portion of the amount of resource available in the network, which is given by the $n$th term in the summation. \n%\nThis means that the values of $\\lambda_n$, $\\overline{R}_n$, $\\theta_n$, $a_n$ and $D_n$ for a given class $n$ can be adjusted, while keeping the quantity $\\lambda_n\\,\\overline{R}_n^2\\,\\theta_n^{2/\\alpha}\\,\\frac{D_n}{D_n-1}\\,\\frac{a_n}{1-a_n}$ unchanged.\n%\nFor instance, we can make a direct exchange between decreasing the delay $D_n$ and decreasing the arrival rate of packets $a_n$ (by controlling the ratio of transmit power levels), such that the term $\\frac{D_n}{D_n-1}\\,\\frac{a_n}{1-a_n}$ remains constant; or else, increase the arrival rate of packets and decrease the density of users, such that the term $\\lambda_n\\,\\frac{a_n}{1-a_n}$ remains constant. \n%\nTherefore, Proposition \\ref{prop:identity_1} reveals, through a simple expression, the interplay among traffic intensity, mean delay, density of users, link distance, and outage probability, when the network is stable.\n\n\\begin{remark}\n    Corollary~\\ref{cor:stab} and Proposition~\\ref{prop:identity_1} are the simplest and the most meaningful results of the present chapter, as they translate the behavior of the network in simple equations, which do not directly depend on the transmission powers.\n\\end{remark}\n\n\n\\begin{figure}\n\\centering\n\\begin{subfigure}[t]{.45\\textwidth}\n  \\centering\n    \\if\\printfig1\n        \\includegraphics[width=\\textwidth]{Figures/Ch7_Opt_Delay_equal_a.pdf}\n    \\else\n        \\includegraphics[draft,width=\\textwidth]{Figures/Ch7_Opt_Delay_equal_a.pdf}\n    \\fi\n    \\caption{Optimum delays}\n\\label{fig:Opt_Delay_equal}\n\\end{subfigure}%\n\\begin{subfigure}{.05\\textwidth}\n\\hspace{.05\\textwidth}\n\\end{subfigure}%\n\\begin{subfigure}[t]{.45\\textwidth}\n  \\centering\n    \\if\\printfig1\n        \\includegraphics[width=\\textwidth]{Figures/Ch7_Opt_Power_equal_a.pdf}\n    \\else\n        \\includegraphics[draft,width=\\textwidth]{Figures/Ch7_Opt_Power_equal_a.pdf}\n    \\fi\n    \\caption{Optimum transmit powers}\n\\label{fig:Opt_Power_equal}\n\\end{subfigure}\n\\caption{These figures represent the optimization of a 3-class network with the following parameters: $a_1=a_2=a_3=a$, $\\psi_1\\,\\lambda_1 = 0.1$, $\\psi_2\\,\\lambda_2 = 0.3$, $\\psi_3\\,\\lambda_3 = 0.6$ and $c_1 = \\frac{10}{16},~ c_2 = \\frac{5}{16},~ c_3 = \\frac{1}{16}$.}\n\\label{fig:opt}\n\\end{figure}\n\n% % % % % % % % % % % % % % % % % % % % % % % % % % % % % %\n\\subsection{Interpretation and Application}\n\\label{sec:application}\n\nIn this section, we solve two optimization problems using the proposed formulation applied to scenarios of different classes of terminals sharing a radio channel.\n\n% -------------------------------- %\n\\subsubsection{Delay Optimization}\n\\label{ssec:opt_delay}\n\nLet us consider the scenario with $N$ classes sharing a channel. Each class may represent a particular user application, with each application having a different delay requirement in the network.\n%\nLet us suppose we are interested in adjusting the transmit power of each user class, such that the weighted average delay among all classes is minimized.\n%\nThis problem is addressed as follows. For fixed arrival rates of vector $\\bm{a}$ that satisfies Corollary~\\ref{cor:stab}, i.e., for $\\bm{a}\\in\\cal{S}_0$, let us minimize the delays $\\bm{D}$ by changing the ratio between the transmit powers $\\bm{P}$.\n%\nEach user class requires a different response time, then we weight the optimization problem with the vector $(c_1,c_2,\\dots,c_N) \\in \\R_+^N$. The larger the coefficient of a class, the smaller the resulting mean delay to deliver packets for that class. Then, we have\n\\begin{equation} \\label{eq:opt_prob}\n\t\\min_{\\bm{P}\\in\\R_+^N} \\sum_{n\\in\\cal{C}} c_n D_n\n    = \\min_{\\bm{P}\\in\\R_+^N} \\sum_{n\\in\\cal{C}} \\frac{c_n\\,(1-a_n)}\n        \t{\\left( 1 + \\frac{\\psi_n}{P_n^\\delta}\n        \t\\frac{\\sum_j P_j^\\delta\\,a_j\\lambda_j}\n        \t{1 - \\sum_j \\psi_j\\,a_j\\lambda_j} \\right)^{\\hspace{-1mm}-1}\\!\\!\\! - a_n},\n\\end{equation}\nwhere $D_n$ is given by Proposition~\\ref{prop:psk}. Note that as thermal noise is not considered in our model, we have a degree of freedom for the optimum solution $\\bm{P}^*$, which agrees with the formulation in \\eqref{eq:opt_prob}.\n\n\\begin{proposition} \\label{prop:opt}\n\tThe minimum of the optimization problem \\eqref{eq:opt_prob} is attained by\n    \\begin{equation} \\label{eq:opt_D}\n        {P_n^*}^\\delta\n        \t= \\dfrac{\\beta}{\\lambda_n a_n} \\left( \\frac{a_n\\,\\cal{A}_n}\n            {1 - \\sum_{k} \\cal{A}_k }\n            + \\frac{\\sqrt{c_n\\,\\cal{A}_n}}\n            { \\sum_{k} \\sqrt{c_k\\,\\cal{A}_k } } \\right), \\quad n\\in\\cal{C},\n    \\end{equation}\n    where $\\beta$ is any positive real constant, $\\cal{A}_n \\triangleq \\psi_n\\,\\lambda_n\\,\\frac{a_n}{1-a_n}$ and the sums are over $\\cal{C}$.\n\\end{proposition}\n\n\\begin{proof}\n\tSince we have one degree of freedom for the solution $\\bm{P}^*$, let us set $\\sum_j P_j^\\delta\\,a_j\\lambda_j = 1 - \\sum_j \\psi_j\\,a_j\\lambda_j$ to extensively simplify the algebraic manipulations. Then, we use the Karush-Kuhn-Tucker conditions \\cite[Section~3.3.1]{bertsekas1999nonlinear} in the \\emph{Lagrangian} function\n    \\begin{equation*}\n    \\begin{split}\n    \t\\cal{L}(\\bm{P},\\mu) \n    \t    &= \\sum_{n\\in\\cal{C}} \\frac{c_n (1-a_n)}\n        \t    {\\left( 1 + \\frac{\\psi_n}{P_n^\\delta}\\right)^{-1}\\! - a_n} + \\mu\\left[ \\sum_{j\\in\\cal{C}} P_j^\\delta\\,a_j\\lambda_j \n            \t- \\left(1 - \\sum_{j\\in\\cal{C}} \\psi_j\\,a_j\\lambda_j\\right) \\right],\n    \\end{split}\n    \\end{equation*}\n    where $\\mu\\in\\R$ is the \\emph{Lagrange} multiplier.\n    %\n    The objective function is strictly convex (the Hessian is a diagonal matrix with positive eigenvalues) and the feasible region is a hyperplane, therefore the solution is the global optimum.\n    %\n    Now, we return to the original problem that does not have the artificial constraint. Thus, we multiply the solution by an arbitrary constant $\\beta>0$ to obtain the general solution.\n\\end{proof}\n\nIt is interesting to note that ${\\sum_k\\cal{A}_k<1}$ by Corollary~\\ref{cor:stab}. Therefore, ${P_n^*}^\\delta$ is always a positive quantity.\n%\nAlso, if $c_n = \\cal{A}_n$ for all $n\\in\\cal{C}$, then the optimum delays are all equal and given by ${D_1 = D_2 = \\cdots = D_N = \\left( 1 - \\sum_k \\cal{A}_k \\right)^{-1}}$. Thus, we can always choose transmit powers, such that we have the same mean delay for all classes!\n\n\nAs an example, let us consider a 3-class network, where Class 1 has a more restrictive delay requirement than Class 2, which is more restrictive than Class 3. We consider that all classes have the same arrival rate of packets, i.e., $a_1=a_2=a_3=a$. Figure~\\ref{fig:Opt_Delay_equal} shows the expected waiting time of a packet before a successful transmission, which is $D_n^*-1$, ($n = 1,2,3$) since a transmission takes exactly one time slot. As expected, the optimization resulted in monotonic increasing functions and $D_1^* < D_2^* < D_3^*$ for all $a$.\n\n\nFigure~\\ref{fig:Opt_Power_equal} shows the normalized\\footnote{Whenever we refer to normalized $b_n {P_n^*}^\\delta$, it means that we choose $\\beta$ in Proposition~\\ref{prop:opt} such that $\\sum_k b_k {P_k^*}^\\delta = 1$ and $b_n$ is any term that depends on $n$, for example $b_n = \\lambda_n$ or $b_n = a_n \\lambda_n$.} transmit powers per unit of area $\\lambda_n {P_n^*}^\\delta$ as a function of $a$. In this case, we do not have a clear hierarchy among the transmit powers, as it depends on the traffic intensity. For $n\\in\\cal{C}$, if the network is close to saturation, i.e., $\\sum_k\\cal{A}_k$ tends to 1, then the normalized $\\lambda_n {P_n^*}^\\delta$ approaches $\\cal{A}_n/\\sum_k\\cal{A}_k$ and, at first order, it does not depend on the coefficients $c_1, c_2, \\dots, c_N$. On the other hand, if the network is at low traffic, i.e., $\\sum_k\\cal{A}_k$ tends to 0, then the normalized $a_n \\lambda_n {P_n^*}^\\delta$ approaches $\\sqrt{c_n\\cal{A}_n}/\\sum_k\\sqrt{c_k\\cal{A}_k}$.\n\n% -------------------------------- %\n\\subsubsection{Throughput Optimization}\n\nNow, let us maximize the total throughput of the channel per unit of area with the constraint that the system is stable.\n%\nSince each transmitter performs retransmissions until the packet is correctly received by the intended receiver, then all packets are successfully transmitted (eventually) in a stable system. Thus, the throughput per transmitter is given by the packet arrival rate $a_n$.\n%\nThe density of users per unit of area is given by $\\lambda_n$, then the throughput of the $n$th user class per unit of area is simply $\\mathscr{T}_n = \\lambda_n\\,a_n$ and the throughput per unit of area of the entire system $\\mathscr{T}$ is the sum of the throughput for all classes $n\\in\\cal{C}$.\n\nUsing Corollary~\\ref{cor:stab}, we can formulate the optimization problem as\n${\\displaystyle\\max_{\\bm{a}\\in\\cal{S}_0}} \\sum_{n} \\lambda_n\\,a_n$.\n%\nHowever, the strict inequality in the region $\\cal{S}_0$ of Corollary~\\ref{cor:stab} results in an optimization problem that is not well-posed. In this case, if the optimum solution lies in the boundary of the feasible region, then the solution does not exist.\n%\nTo circumvent this problem, we propose a new region $\\cal{S}_\\epsilon\\subset\\cal{S}_0$ by adding an arbitrarily small parameter $\\epsilon \\in (0,1)$ in the inequality, i.e., the new region is given by\n\\begin{equation*}\n\t\\cal{S}_{\\epsilon} = \\left\\lbrace \\bm{a}\\in[0,1)^N \\bigm\\vert \\sum_{n\\in\\cal{C}} \\psi_n\\,\\lambda_n\\,\\dfrac{a_n}{1-a_n} \\le 1-\\epsilon \\right\\rbrace.\n\\end{equation*}\n%\nAs the parameter $\\epsilon$ increases, the system becomes less sensitive to perturbations\\footnote{When the system parameters suffer a sufficiently small change, the system remains stable.}.\nNow, the optimization problem is posed as\n\\begin{equation} \\label{eq:opt_thr}\n\t\\max_{\\bm{a}\\in\\cal{S}_\\epsilon} \\mathscr{T} = \\max_{\\bm{a}\\in\\cal{S}_\\epsilon} \\sum_{n\\in\\cal{C}} \\lambda_n\\,a_n.\n\\end{equation}\n%\nThe following proposition presents the solution to the optimization, i.e., the optimum arrival rates $\\bm{a}^*$ that maximize the throughput per unit of area and maintain the system stable.\n\n\\begin{proposition} \\label{prop:eps}\n\tIf \n    \\begin{equation} \\label{eq:opt_req}\n\t\t\\sum_{k\\in\\cal{C}}\\lambda_k\\psi_k\\left(\\sqrt{\\frac{\\max_n \\psi_n}{\\psi_k}}-1\\right)<1-\\epsilon,\n\t\\end{equation} then the solution of \\eqref{eq:opt_thr} is attained by\n    \\begin{equation}\n    \ta_n^* = 1 - \\frac{\\sum_k \\lambda_k \\sqrt{\\psi_n\\psi_k}}{1-\\epsilon+\\sum_k\\lambda_k\\psi_k}, \\quad n\\in\\cal{C},\n    \\end{equation}\n    where the sums are over $\\cal{C}$. If the inequality \\eqref{eq:opt_req} is not satisfied, then the $m$th class is excluded, where $m = \\arg\\max_n \\psi_n$, and the inequality is checked again.\n\\end{proposition}\n\n\\begin{proof}\n\tIt is a direct application of the Karush-Kuhn-Tucker conditions \\cite[Section~3.3.1]{bertsekas1999nonlinear} in the \\emph{Lagrangian} function\n    \\begin{align*}\n    \t\\cal{L}(\\bm{a},\\mu) = \\sum_{n\\in\\cal{C}} \\lambda_n a_n + \\mu \\left[ \\sum_{k\\in\\cal{C}}\\psi_k\\lambda_k\\frac{a_k}{1-a_k} - (1-\\epsilon)\\right],\n    \\end{align*}\n    where $\\mu\\in\\R$ is the Lagrange multiplier associated with the constraint of stability. Equation~\\eqref{eq:opt_req} guarantees that the solution $\\bm{a}^*\\in[0,1)^N$.\n    %\n    The objective function is convex (affine function) and the region $\\cal{S}_\\epsilon$ is strictly convex because the Hessian of the function that defines the region is a diagonal matrix with negative eigenvalues. Therefore the presented solution is the global optimum and it is unique.\n\\end{proof}\n\nIn the optimization \\eqref{eq:opt_thr}, we still have freedom to choose the transmit powers $\\bm{P}$, as long the network remains stable. The best way of choosing $\\bm{P}$ is by minimizing the delays, which we have already done in Subsection~\\ref{ssec:opt_delay}, Proposition~\\ref{prop:opt}, where the arrival rates $\\bm{a} \\in \\cal{S}_\\epsilon \\subset \\cal{S}_0$ are fixed. When the optimization is performed in this sequence (maximization of throughput, then minimization of delay), we have the optimum throughput (per unit of area) and the optimum delays for the optimum configuration of arrival rates.\n%%\nLater in this section, we illustrate this procedure with a numerical example.\n\nIn order to solve the optimization problem \\eqref{eq:opt_thr} we did not have to handle with the transmit powers $\\bm{P}$ directly, which would make the solution and the problem formulation more cumbersome. This shows the usefulness of Corollary~\\ref{cor:stab}.\n\n\\begin{figure}\n\\centering\n\\begin{subfigure}[t]{.45\\textwidth}\n  \\centering\n    \\if\\printfig1\n        \\includegraphics[width=\\textwidth]{Figures/Ch7_Opt_a_eps.pdf}\n    \\else\n        \\includegraphics[draft,width=\\textwidth]{Figures/Ch7_Opt_a_eps.pdf}\n    \\fi\n    \\caption{Optimum arrival rates}%\n    \\label{fig:Opt_a_eps}\n\\end{subfigure}%\n\\begin{subfigure}{.05\\textwidth}\n    \\hspace{.05\\textwidth}\n\\end{subfigure}%\n\\begin{subfigure}[t]{.45\\textwidth}%%\n  \\centering\n    \\if\\printfig1\n        \\includegraphics[width=\\textwidth]{Figures/Ch7_Opt_lam_a_eps.pdf}\n    \\else\n        \\includegraphics[draft,width=\\textwidth]{Figures/Ch7_Opt_lam_a_eps.pdf}\n    \\fi\n    \\caption{Optimum throughput. The dashed curve corresponds to a scenario with only the best performing class}\n    \\label{fig:Opt_lam_a_eps}\n\\end{subfigure}\n%\n\\begin{subfigure}[t]{.45\\textwidth}%%%\n  \\centering\n    \\if\\printfig1\n        \\includegraphics[width=\\textwidth]{Figures/Ch7_Opt_D_eps.pdf}\n    \\else\n        \\includegraphics[draft,width=\\textwidth]{Figures/Ch7_Opt_D_eps.pdf}\n    \\fi\n    \\caption{Optimum delays}\n    \\label{fig:Opt_D_eps}\n\\end{subfigure}%\n\\begin{subfigure}{.05\\textwidth}\n    \\hspace{.05\\textwidth}\n\\end{subfigure}%\n\\begin{subfigure}[t]{.45\\textwidth}%%%%\n  \\centering\n    \\if\\printfig1\n        \\includegraphics[width=\\textwidth]{Figures/Ch7_Opt_P_eps.pdf}\n    \\else\n        \\includegraphics[draft,width=\\textwidth]{Figures/Ch7_Opt_P_eps.pdf}\n    \\fi\n    \\caption{Optimum transmit powers}\n    \\label{fig:Opt_P_eps}\n\\end{subfigure}\n\\caption{These figures represent the optimization of the throughput and mean delay of a 3-class network with the parameters given in Table~\\ref{tab:param}.}\n\\label{fig:opt_eps}\n\\end{figure}\n\nLet us illustrate the throughput optimization problem with a system for which the parameters are shown in Table~\\ref{tab:param}. Figure~\\ref{fig:Opt_a_eps} shows the optimum arrival rates $\\bm{a^*}$ that maximizes the throughput per unit of area.\n%\n\\begin{table}[hbt]\n  \\centering\n  \\caption{Network parameters for Fig.~\\ref{fig:opt_eps}}\n  \\begin{tabular}{l l}\n        \\hline\n      \\hline\n      \\textbf{Parameters} & \\textbf{Values} \\\\\n      \\hline\n        $(\\lambda_1,\\lambda_2,\\lambda_3)$\t& $=(1,2,3)$ \\\\\n        $(\\psi_1,\\psi_2,\\psi_3)$\t\t\t& $=(0.3,0.5,0.4)$ \\\\\n\t\t$(c_1,c_2,c_3)$\t\t\t\t\t\t& $=(\\frac{1}{3},\\frac{1}{3},\\frac{1}{3})$ \\\\\n      \\hline\n      \\hline\n  \\end{tabular}\n  \\label{tab:param}\n%   \\vspace*{-\\baselineskip}\n\\end{table}\n%\nIt is quite interesting that the optimum solution is not (necessarily) exclusively activating the class with the best link quality (i.e., the class with the smallest $\\psi$, which is Class 1 in this example). In Fig.~\\ref{fig:Opt_lam_a_eps} it is shown the optimum throughput for each class and the total throughput of the system.\n%\nFor comparison, we plotted a dashed curve representing the total throughput if we only use the best performing user class, regarding throughput.\nThe dashed curve is below the optimum total throughput for all $\\epsilon$. Therefore, the best solution is always a combination of all user classes, as long as \\eqref{eq:opt_req} is satisfied.\n%\nOn the other hand, if this equation is not satisfied, it means that there is at least one user class with a bad link quality, such that it is better (regarding throughput efficiency) to reallocate this user class to another channel.\n\nNow that we have, for each $\\epsilon$, the arrival rate configuration $\\bm{a}^*(\\epsilon)$ which gives the maximum throughput, we can use Proposition~\\ref{prop:opt} to find the best configuration of transmit powers $\\bm{P}^*(\\epsilon)$ that minimizes the sum of the mean delays for each optimum configuration of arrival rates $\\bm{a}^*(\\epsilon)$.\n%\nFigure~\\ref{fig:Opt_D_eps} shows the result of this optimization, which is a direct application of \\eqref{eq:opt_D}.\n%\nIt is worth noting that as we increase $\\epsilon$ the system is farther from instability, which corresponds to having a smaller delay to transmit packets, as we can see in Fig.~\\ref{fig:Opt_D_eps}, and a smaller throughput, as shown in Fig.~\\ref{fig:Opt_lam_a_eps}.\n%\nFigure~\\ref{fig:Opt_P_eps} shows the optimum distribution of power per unit of area required by each user class. Notice that the first user class, which has the best link quality, uses the smallest power per unit of area. However, this behavior is more intricate; it also depends on the density of users of the corresponding class. Notice, for example, the inversion between user classes 2 and 3 as we increase $\\epsilon$ in Fig.~\\ref{fig:Opt_P_eps}.\n\nAnother interesting and direct result from Corollary~\\ref{cor:stab} is to provide an upper bound for the total throughput per unit of area $\\mathscr{T}$ in a stable system, which is given by $1/(\\min_n\\psi_n)$.\n%\nThis is not a tight bound, however it is interesting on its own, due to its simplicity and the fact that it does not depend on the density of users. The proof follows\n\\begin{align}\n\t\\mathscr{T} = \\sum_{k\\in\\cal{C}} a_k\\lambda_k &\\le \\frac{1}{\\min_{n}\\psi_n} \\sum_{k\\in\\cal{C}} \\psi_k\\,a_k\\,\\lambda_k \\nonumber\\\\\n        &< \\frac{1}{\\min_{n}\\psi_n} \\sum_{k\\in\\cal{C}}\\psi_k\\,\\lambda_k\\,\\frac{a_k}{1-a_k} \\nonumber\\\\\n        &< \\left(\\textstyle\\min_{n}\\psi_n \\right)^{-1},\n\\end{align}\nwhere the last inequality comes from Corollary~\\ref{cor:stab}.\n\n% % % % % % % % % % % % % % % % % % % % % % % % % % \n% % % % % % % % % % % % % % % % % % % % % % % % % % \n\\section{On the High-mobility Assumption} \\label{sec:high-mobility}\n\nIn this section, we address the high-mobility assumption, which may not be realistic in real wireless networks, since the mobility of transmitters does not change drastically between adjacent time slots. Therefore, the independence assumption would not hold.\n%\nNevertheless, in a stable wireless network that has a small packet arrival rate $a$ per user or a small access probability $p$, the correlation might be sufficiently small such that the independence (high-mobility) assumption is reasonable. In \\cite{haenggi2013diversity} the authors show that if the access probability $p$ is sufficiently small, then the independence assumption provides a good approximation.\n\nWhen the packet arrival rate $a$ or the access probability $p$ are small, the typical user sees a significantly different PPP of transmitters for each time slot, which justifies the independence (high-mobility) assumption. We verified this claim through simulations and the result is shown in Fig.~\\ref{fig:high-mobility}, where it is used one user class with ${\\lambda c \\overline{R}^2 = \\pi/4}$, ${\\alpha = 3}$ and ${\\theta = 1}$.\n%\n\\begin{figure}\n    \\centering\n    \\if\\printfig1\n        \\includegraphics[width=0.55\\textwidth]{Figures/Ch7_high-mobility.pdf}\n    \\else\n        \\includegraphics[draft,width=0.75\\textwidth]{Figures/Ch7_high-mobility.pdf}\n    \\fi\n    \\caption{Queue load $\\rho$ as a function of the access probability $p$. Simulation results with a static network are presented in marks and the theoretical results with the high-mobility assumption are presented in curves.}\n    \\label{fig:high-mobility}\n\\end{figure}\n\nThe mean load of the queues $\\rho$, which is equivalent to the percentage of queues with packets to transmit, are plotted as a function of the access probability $p$ for several values of arrival rate $a$. As expected, for small values of $a$ or $p$, the theoretical model presents good estimations of the average queue load.\n%\nIt is important to emphasize that we did not plot the mean delay $D$, because in a static PPP there might exist a set of unstable users, whose queues and delays tend to infinity. This would raise the average delay to infinity too. Then, we chose to plot the mean load $\\rho$, which is equal to 1 for unstable users and does not tend to infinity opposed to the mean delay $D$.\n\nTo establish Proposition~\\ref{prop:identity_1}, we supposed that the access probability $p$ is equal to one for all users. In the context of high-mobility, this approach makes sense, since the typical user sees a different interference scenario for each time slot. Thus, it is reasonable to attempt a retransmission every time slot until the packet is successfully transmitted. This also minimizes the mean delay $D$, which is in accordance with \\eqref{eq:Dn}, as the transmission success probability $p_{s,n}$ does not depend on the access probability $p_n$ in a stable network.\n\nThere is another scenario, which does not require high-mobility to achieve spatial independence between adjacent time slots. This scenario is a network that uses the frequency-hopping scheme over a set of channels \\cite{tse2005fundamentals}. For each time slot, there is a different PPP pattern, since the transmitting nodes select with equal probability one channel to transmit. Thus, the spatial correlation between time slots decreases with the number of channels available for selection.\n\n% % % % % % % % % % % % % % % % % % % % % % % % % % \n% % % % % % % % % % % % % % % % % % % % % % % % % % \n\\section{Bandwidth Partitioning on High-mobility Bipolar Networks}\n\\label{sec:bandwidth}\n\nIn this section, we consider the model presented in Section~\\ref{sec:N-class} with only two classes of users, i.e., $N=2$.\n%\nHowever, differently from our previous models, the available frequency band is partitioned among users of one of the classes, such that users of this class can access only a fraction of the original bandwidth available to the network at a time.\n%\nThe other class continues using the whole frequency band available.\n%\nThe motivation for such bandwidth partitioning is to reduce the interference among users, leading to a higher network capacity.\n\nThe work presented in this section generalizes the paper by Jindal et al. in \\cite{jindal2008bandwidth} in the sense that it (\\textit{i}) considers two user classes and (\\textit{ii}) investigates the effects of bandwidth partitioning on the mean \\textit{queuing} delay.\n%\nBy considering two classes of users, we are able to study the performance of a network in which users of one class are allowed to transmit on a fraction of the channel accessed by users of the other class. Also, by studying the delay, we are able to have a better understanding of the effects of bandwidth partitioning on network performance.\n%\n% The present work also extends the study presented in \\cite{dester2018} by using bandwidth partitioning on one of the user classes. \n% More specifically, we recover some results from \\cite{jindal2008bandwidth} and \\cite{dester2018} by setting the arrival rate of Class 2 $a_2 = 0$ and by setting the number of band partitions $M=1$, respectively.\n\nWe used the wireless network formulation proposed in Section~\\ref{sec:N-class} to achieve a tractable framework for the analysis of the bandwidth partitioning.\n\nThe main contributions presented in this section can be summarized as follows:\n\\begin{itemize}\n    \\item We have found a pair of simple equations that relate the main parameters of the network and guarantees network stability (Theorem~\\ref{th:identity});\n    \\item A transcendental equation to find the optimum Class 1 spectral efficiency is derived, along with the optimum number of partitions (Theorem~\\ref{th:optimum_eta});\n    \\item The first-order expansion of the optimum spectral efficiency around a small use of the channel by Class 2 (Eq.~\\eqref{eq:eta_expansion});\n    \\item We show that the bandwidth partitioning strategy is more effective when the path loss exponent is not small and the performance requirements of Class 2, the one whose users access the whole bandwidth, is not high in respect to the maximum performance attainable (Fig.~\\ref{fig:a_ratio}).\n\\end{itemize}\n\n% The paper is organized as follows. In Section~\\ref{sec:sysmod_M} the system model is presented and in Section~\\ref{sec:stab} we derive the stability conditions and expressions for stationary transmission success probability and mean delay. Using these expressions, we present in Section~\\ref{sec:opt} the optimization problem involving bandwidth partitioning and proves the existence and uniqueness of the solution.  Section~\\ref{sec:num} provides some numerical examples of bandwidth optimization. %, also including a case involving cellular and D2D.\n% Section~\\ref{sec:conc} concludes the paper.\n\n% % % % % % % % % % % % % % % % % % % % % % % % % % % % % %\n\\subsection{System Model} \\label{sec:sysmod_M}\n\nWe consider the network model presented in Section~\\ref{sec:N-class} with two user classes (namely Class 1 and Class 2), and only one and important difference that users of Class 1 access a fraction of the bandwidth during each transmission.\n\n%The high-mobility model, which is used in several works (see, for instance \\cite{jindal2008bandwidth}, \\cite{baccelli2010stochastic}, \\cite{stamatiou2010random}, \\cite{dester2018}), assumes that users occupy a different point in space for each time slot. \n%The communication protocol is the slotted Aloha, i.e., for each time slot, if a source (transmitter) has packets to transmit, it will transmit one packet with a fixed probability, independently from other sources and the past. The position of source $i \\in \\N$ of class $n\\in\\{1,2\\}$ at time $t\\in\\N$ is denoted by $X_{i,n}(t) \\in \\R^2$. We assume that $\\{X_{i,n}(t)\\}_i\\subset \\R^2$ is a marked homogeneous Poisson point process (PPP) of density $\\lambda_n$. These PPPs are independent across classes and time slots. The transmit power of a source of class $n$ is denoted by $P_n$, assumed to be constant over time slots and the same for all sources within a class.\n%\n% Let $Y_{i,n}(t)\\in\\R^2$ be the position of the destination terminal with which the $i$th source of class $n$ communicates. The distribution of $Y_{i,n}(t)$ is such that the location of the destination terminal is at a random distance $R_{i,n}(t) = ||X_{i,n}(t) - Y_{i,n}(t)||$ from the corresponding transmitter in a uniformly random direction, where $||\\cdot||$ is the euclidean norm. We assume that $R_{i,n}(t)$ is iid across time slots and users, and it follows a Rayleigh distribution of mean $\\overline{R_n}$.\n%\n% This assumption contributes to the tractability of the model and it was also used in \\cite{dester2018, lin2014spectrum, di2014stochastic}. In this context, a reasonable assumption is to consider an interference-limited network, i.e., the noise is negligible.\n% It should be noted that the destination terminals are not part of the Poisson Point Processes that model the positions of the sources.\n\n% Each source has a buffer of infinite capacity for arriving packets. The total number of packets in the $i$th source of class $n$ at time $t$ is denoted by the queue length $Q_{i,n}(t)$. If the queue of a given source is not empty, then the source tries to transmit a packet with probability $p_n$ (medium access probability) following the first-come-first-serve\n% (FCFS) discipline and the transmission takes exactly one time slot.\n% %\n% Thus, each queue length $Q_{i,n}(t)$ forms a Markov chain (for more details, see \\cite{dester2018}).\n% %\n% The packet is successfully transmitted when the signal-to-interference ratio (SIR) of the received signal is greater than a threshold $\\theta_n$ (capture effect). In this case, the receiver sends an acknowledge through an error-free channel and the packet leaves the queue. Packets arrive at the queue according to an iid Bernoulli distribution of parameter $a_n$.\n% %\n% Chronologically, within each time slot, we have the transmission of packets, then the arrival of packets, and, at the end of the time slot, the displacement of the sources occurs to form a new and independent PPP realization.\n\n% The SIR experienced by the typical user from class $n$ is given by $\\mathrm{SIR}_{i,n}= P_n h_{i,n} R_{i,n}^{-\\alpha}/I$, where $\\alpha>2$ is the path-loss exponent, the Rayleigh fading effect is represented by the fading coefficient $h_{i,n}$, which is an iid (with respect to time and users) exponentially distributed random variable of unit mean and remains constant during the time slot, and $I$ is the aggregate interference from other sources. It is known that $\\mathrm{SIR}_{i,n}$ is an iid random variable with respect to time \\cite{baccelli2010stochastic}.\n\nMore specifically, the frequency band of bandwidth $B_0$ is shared by users of both classes. For Class 1 transmissions, this frequency band is divided into $M$ partitions (sub-bands) of bandwidth $B_0/M$, and each Class 1 user transmits over one randomly selected sub-band. Therefore, the density of sources for each partition becomes $\\lambda_1/M$. On the other hand, users of Class 2 transmit over the whole available bandwidth $B_0$.\n%\nNote that front-end receiver filters of the first class destinations will capture $1/M$ of the power from transmissions of users of the second class and do not capture anything from other partitions of the first class. On the other hand, the second class destinations capture all the power coming from sources of both classes.\n\nThe transmission rate $R_T$ for the first-class users is fixed and, as in \\cite{jindal2008bandwidth}, the SIR threshold\\footnote{The transmission successfully happens if and only if the SIR is greater than the threshold.} $\\theta_1$ comes from the following equation: ${R_T = (B_0/M)\\,\\ln(1+\\theta_1)}$. Then, ${\\theta_1 = \\euler^{M\\eta_0}-1}$, where ${\\eta_0 \\triangleq R_T/B_0}$ is the spectral efficiency without partitioning the frequency band. Note that the transmission rate for the first class of users remains unchanged with bandwidth partitioning.\n\n% Both user classes use the same bandwidth and the goal is to find the optimum number of partitions $M$ for the first user class.\n% Table~\\ref{tab:symbols} summarizes the notation.\n\n% \\begin{table}[hbt]\n%   \\centering\n%   \\caption{Symbols and Definitions}\n%   \\begin{tabular}{ll}\n%       \\toprule\n%       \\textbf{Symbol} & \\textbf{Definitions} \\\\\n%       \\midrule\n%         $\\alpha\\in(2,\\infty)$\t& Path loss exponent \\\\\n%         $\\delta\\in(0,1)$\t\t& $\\triangleq 2/\\alpha$ \\\\\n% \t\t$M \\in \\N$\t\t\t\t& Number of partitions \\\\\n%         $\\eta_0 \\in \\R_+$\t\t& Spectral efficiency without bandwidth partitioning \\\\\n%         $\\eta  \\in \\R_+$\t\t& $\\triangleq M \\eta_0 $, spectral efficiency of Class 1 \\\\\n%         $p_n\\in[0,1]$   \t\t& Medium access probability \\\\\n%       \t$a_n\\in[0,1]$\t\t\t& Packet arrival rate \\\\\n%         $p_{s,n}\\in[0,1]$\t\t& Stationary transmission success probability \\\\\n%         $\\theta_n\\in \\R_+$\t\t& SIR threshold for successful transmission \\\\\n%         $D_n\\in(1,\\infty)$\t\t& Average packet transmission delay \\\\\n%         $\\overline{R}_n\\in \\R_+$& Mean source-destination separation distance \\\\\n%         $P_n\\in \\R_+$\t\t\t& Transmit power \\\\\n%         $\\lambda_n\\in \\R_+$\t\t& User density of class $n$\\\\\n%         $\\psi_n\\in \\R_+$ \t\t& $\\triangleq 4\\,\\Gamma(1+\\delta)\\,\n%          \t\t\t\t\t\t  \\Gamma(1-\\delta)\\,\\overline{R}_n^2\\,\n%                                   \\theta_n^{\\delta}$~~(link quality)\\\\\n% %          $||\\cdot||$\t\t\t& Euclidean norm \\\\\n%         % $\\ind_A(x)$\t\t\t\t& indicator function\\\\\n%         $\\Psi_n\\in \\R_+$       ~& $\\triangleq \\psi_n\\lambda_n \\left(\\frac{D_n}{D_n-1}\\right) \\left(\\frac{a_n}{1-a_n}\\right)$~~(resource utilization)\\\\\n%       \\bottomrule\n%   \\end{tabular}\n%   \\label{tab:symbols}\n% %    \\vspace*{-\\baselineskip}\n% \\end{table}\n\n% % % % % % % % % % % % % % % % % % % % % % % % % % % % % %\n\\subsection{Stability Conditions and Stationary Analysis}\n\\label{sec:stab}\n\nIn this section, we derive conditions for stability and carry a stationary analysis of the network, which leads to expressions relating network parameters and performance metrics. These expressions are used in Section \\ref{sec:opt} to formulate an optimization problem to maximize the network performance when bandwidth partitioning is employed. \n\n% In order to derive the stability conditions, we first determine the successful transmission probability of a typical user from class $n\\in\\{1,2\\}$, given the \\textit{effective density of active sources} $\\lambda^\\mathrm{eff}_k(t)$ for each class $k\\in\\{1,2\\}$ in a time slot $t\\in\\Z_+$.\n% %\n% The effective density of active sources of a class is the PPP density of the sources with non-empty queues and allowed by the medium access control technique to transmit a packet.\n% %\n% This access control is modeled in this work by the medium access probability $p_n$. One can calculate the probability of successful transmission by deconditioning the general expression for the successful probability given in \\cite[Eq.~(9)]{haenggi2009stochastic} for the distance $R$, when $R$ follows a Rayleigh distribution. This was done in \\cite[Proposition~1]{dester2018}. Then, the successful transmission probability is given by\n\nFrom the proof of Proposition~\\ref{prop:psk} in Eq.~\\eqref{eq:P_SIR}, for two classes of users, we can write that%\n\\begin{equation} \\label{eq:P_SIR_M}\n\t\\P(\\mathrm{SIR}_{i,n}(t) > \\theta_n) \n    \t= \\nu_n\\!\\left( P_1^\\delta\\,\\lambda_\\mathrm{eff}^{(1)}(t)\n        \t+ P_2^\\delta\\,\\lambda_\\mathrm{eff}^{(2)}(t) \\right), \\quad t\\in\\N,\n\\end{equation}\nwhere the function ${\\nu_n: \\R_+ \\longrightarrow \\R_+}$ is defined as\n\\begin{equation}\\label{defNu}\n\\nu_n(x) \\triangleq \\left(1+\\frac{\\psi_n}{P_n^\\delta}x\\right)^{-1}, \\quad x\\in\\R_+, n\\in\\{1,2\\}.\n\\end{equation}\n\nA necessary and sufficient condition for the stability of the buffers for both user classes is given by the following proposition.\n%\n% A system is stable whenever the Markov chain describing the system admits a proper limit distribution when $t\\to\\infty$ \\cite{szpankowski1994stability}.\n%\nStability region refers to the set of arrival rates for which the system is stable.\n\n\\begin{proposition} \\label{prop:stability}\nThe system network is stable if and only if $(a_1,a_2) \\in \\mathcal{E}_1 \\cup \\mathcal{E}_2$, where\n\\begin{align*}\n\t\\mathcal{E}_1\n    \t&= \\left\\lbrace (a_1,a_2)\\in [0,1]^2 \\mid\n    \t\ta_1 < p_1\\,\\nu_1\\!\\left( P_1^\\delta\\tfrac{\\lambda_1}{M}p_1\n            \t+\\tfrac{P_2^\\delta}{M^\\delta}\\lambda_2 p_2\\right), \n            a_2 < p_2\\,\\nu_2\\!\\left( P_1^\\delta\\lambda_1\n        \t\t\\tfrac{a_1}{\\widetilde{p}_{s,1}} + P_2^\\delta\\lambda_2 p_2 \\right) \\right\\rbrace,\\\\\n\t\\mathcal{E}_2\n    \t&= \\left\\lbrace (a_1,a_2)\\in [0,1]^2 \\mid\n    \t\ta_2 < p_2\\,\\nu_2\\!\\left( P_1^\\delta\\lambda_1 p_1\n            \t+P_2^\\delta\\lambda_2p_2\\right), \n            a_1 < p_1\\,\\nu_1\\!\\left(P_1^\\delta\n        \t\t\\tfrac{\\lambda_1}{M}p_1+\\tfrac{P_2^\\delta}{M^\\delta}\n                \\lambda_2\\tfrac{a_2}{\\widetilde{p}_{s,2}} \\right)\n\t\t\t\\right\\rbrace,\n\\end{align*}\nwhere\n\\begin{equation*}\n\t\\widetilde{p}_{s,1} = \\frac{1-\\psi_1\\tfrac{\\lambda_1}{M}a_1}\n    \t{1+\\psi_1(\\tfrac{P_2}{M P_1})^\\delta\\lambda_2p_2}, \\qquad\n    \\widetilde{p}_{s,2} = \\frac{1-\\psi_2\\lambda_2 a_2}\n    \t{1+\\psi_2(\\tfrac{P_1}{P_2})^\\delta\\lambda_1 p_1}.\n\\end{equation*}\n\\end{proposition}\n%\n\\begin{proof}\n\tSufficient conditions for the network stability are obtained by using the concept of dominant network \\cite[Section~2.1.2]{kompella2014stable}, which corresponds to a network almost identical to the original one, differing only on the fact that users of some classes of the dominant network transmit dummy packets when their queues are empty. If the dominant network is stable, then the original network is stable as well.\n\t%\n    Let us analyze a dominant network where both classes transmit dummy packets with the correspondent medium access probability $p_1, p_2$. In this case, the effective density of active sources for the $n$th traffic class is $\\lambda_\\mathrm{eff}^{(n)} = \\lambda_n\\,p_n$ for all $t$, since we are assuming that sources transmit dummy packets when their queues are empty.\n    %\n    Note that we have partitioned the frequency band of the first class of users into $M$ sub-bands, i.e., the destinations of packets of this user class only receive signals within their bandwidth, i.e., signals from $1/M$ of the sources of the first user class and $1/M$ of the power of signals the sources of the second class of users.\n\n%    In general, a sufficient condition for stability\\footnote{The system is stable if the expected rate of incoming packets is smaller than the expected number of packets leaving the queue per time slot \\cite{loynes1962stability}.} for both classes are \n\tA sufficient condition for stability is\n    \\begin{equation}\n    a_n < p_n \\, P(\\mathrm{SIR}_{i,n} > \\theta_n), \\quad n\\in\\{1,2\\},\n    \\end{equation}\nby Loynes' theorem (Theorem~\\ref{th:loynes}). Then, using Eq.~\\eqref{eq:P_SIR_M}, sufficient conditions for stability for the first and the second classes are  \n    \\begin{equation} \\label{eq:stabClass1}\n    \ta_1<p_1\\,\\nu_1\\!\\left[P_1^\\delta\\tfrac{\\lambda_1}{M}p_1+\\left(\\tfrac{P_2}{M}\\right)^\\delta\\lambda_2p_2\\right]\n    \\end{equation}\n    and \n    \\begin{equation} \\label{eq:stabClass2}\n\ta_2 < p_2\\,\\nu_2\\!\\left(P_1^\\delta\\lambda_1p_1\n    \t+ P_2^\\delta\\lambda_2p_2\\right).\n    \\end{equation}\n    If both equations \\eqref{eq:stabClass1} and \\eqref{eq:stabClass2} are satisfied, then the system is stable. However, the stability region described by Proposition \\ref{prop:stability} can be expanded, as presented next. Let us consider two cases: (i) the arrival rate $a_1$ satisfies Eq.~\\eqref{eq:stabClass1}; (ii) the arrival rate $a_2$ satisfies Eq.~\\eqref{eq:stabClass2}.\n\\begin{enumerate}[label=(\\roman*)]\n    \\item For this case, we consider another dominant network, where only users of the second class transmit dummy packets. We know that the first class is stable and it has a limit stationary distribution as $t\\to\\infty$, since we are assuming $a_1$ satisfies \\eqref{eq:stabClass1}, and we want to determine a new stability condition for the second user class. We begin by noting that, in this context, the load $\\rho_1$ of a queue of the first user class can be written as the ratio of the packet arrival probability and the probability a packet that leaves the queue, i.e., $\\rho_1 = a_1/(p_1\\widetilde{p}_{s,1})$, where $\\widetilde{p}_{s,k} \\triangleq \\P(\\mathrm{SIR}_{i,k}>\\theta_k)$, $k\\in\\{1,2\\}$, is the Class $k$ coverage probability in the dominant network. Therefore, the stationary  effective density of active sources from the first class is $\\lambda_1^\\mathrm{eff} = \\lambda_1\\,p_1\\,\\rho_1$. From Eq.~\\eqref{eq:P_SIR_M}, we have the following fixed-point equation\n    \\begin{equation*}\n    \t\\widetilde{p}_{s,1}\n        \t= p_1\\,\\nu_1\\!\\left[ P_1^\\delta\\tfrac{\\lambda_1}{M}\\tfrac{a_1}{\\widetilde{p}_{s,1}}\n            \t+ \\left(\\tfrac{P_2}{M}\\right)^\\delta\\!\\lambda_2 p_2 \\right],\n    \\end{equation*}\n    which is easily solvable for $\\widetilde{p}_{s,1}$. Then, we can use this value to derive a weaker stability condition for the second user class, i.e., $a_2<p_2\\,\\nu_2(P_1^\\delta\\lambda_1 p_1\\rho_1+P_2^\\delta\\lambda_2 p_2)$, where $\\rho_1 = a_1/(p_1\\widetilde{p}_{s,1})$. This establishes the region $\\cal{E}_1$.\n    \n    \\item Analogously to case (i), we now consider a dominant network where users from the first class transmit dummy packets when their queues are empty. Following the same procedure as in the previous case, we arrive at the following fixed-point equation for the stationary successful transmission probability of the second user class,\n    \\begin{equation*}\n    \t\\widetilde{p}_{s,2}\n        \t= p_2\\,\\nu_2\\!\\left( P_1^\\delta\\lambda_1 p_1\n            \t+ P_2^\\delta\\lambda_2 \\tfrac{a_2}{\\widetilde{p}_{s,2}} \\right),\n    \\end{equation*}\n    whose solution allows us to establish a weaker stability condition for the first class of user as\n    \\begin{equation}\n    \ta_1<p_1\\,\\nu_1 \\left[P_1^\\delta\\tfrac{\\lambda_1}{M}p_1+\\left(\\tfrac{P_2}{M}\\right)^\\delta\\lambda_2p_2 \\rho_2 \\right],\n    \\end{equation}\n    where $\\rho_2 = a_2/(p_2\\widetilde{p}_{s,2})$ is the load of queues from the second user class. This condition establishes region $\\cal{E}_2$.\n\\end{enumerate}\nNecessary conditions are established when we analyze the case $(a_1,a_2)\\notin\\cal{E}_1\\cup\\cal{E}_2$.\nNote that, if the pair $(a_1,a_2)$ does not belong to the cases (i) or (ii), then there exists a positive probability that the original network and the dominant network, which transmits dummy packets for both classes, are \\emph{indistinguishable} \\cite[Section~3.2]{szpankowski1994stability} and, therefore, both systems are not stable by Loynes' Theorem (Theorem~\\ref{th:loynes}). If all the queues start with a large number of packets, the original and the dominant networks behave identically with a positive probability (see \\cite[Proposition~1]{stamatiou2010random}).\nOn the other hand, if $(a_1,a_2)$ belongs to only one of the cases (i) or (ii), then one of the classes is stable, but again with a positive probability, the original network behaves identically as the correspondent dominant network and, therefore, the other class is not stable.\n\\end{proof}\n\n\\begin{remark} \\label{rem:stab}\nThe stability region in Proposition~\\ref{prop:stability} is maximized when ${p_1 = p_2 = 1}$. This can be shown by noting that the two boundary inequalities that define the region $\\cal{E}_1 \\cup \\cal{E}_2$ in the first quadrant are monotonically increasing with $p_1$ or $p_2$.\n\\end{remark}\n\nSince we have established the conditions for stability, we now proceed by showing the stationary probability of successful transmission and mean delay for each user class. \n\n\\begin{proposition}\\label{prop:stationary}\n\tIf the system is stable, then the stationary transmission success probabilities $p_{s,1}$ and $p_{s,2}$ and the stationary mean delays $D_1$ and $D_2$, for user classes 1 and 2, are given by \n\\begin{gather*}\n    \tp_{s,1} = \\frac{(1-\\psi_1\\tfrac{\\lambda_1}{M}a_1)(1-\\psi_2\\lambda_2 a_2)\n        \t- \\tfrac{1}{M^\\delta}\\psi_1\\psi_2\\lambda_1\\lambda_2 a_1 a_2}\n            {1+\\lambda_2 a_2 \\left[\\psi_1\\left(\\tfrac{P_2}{M P_1}\\right)^\\delta-\\psi_2\\right]},\\\\\n    \tp_{s,2} = \\frac{(1-\\psi_1\\tfrac{\\lambda_1}{M}a_1)(1-\\psi_2\\lambda_2 a_2)\n        \t- \\tfrac{1}{M^\\delta}\\psi_1\\psi_2\\lambda_1\\lambda_2 a_1 a_2}\n            {1+\\lambda_1 a_1 \\left[\\psi_2\\left(\\tfrac{P_1}{P_2}\\right)^\\delta-\\tfrac{\\psi_1}{M}\\right]},\n     \\end{gather*}  \n     \\begin{equation*}       \n    \tD_1 = \\frac{1-a_1}{p_1\\,p_{s,1}-a_1}, \\qquad\n    \tD_2 = \\frac{1-a_2}{p_2\\,p_{s,2}-a_2}.\n    \\end{equation*}\n\\end{proposition}\n\n\\begin{proof}\n\tIf the system is stable, then for each user class $n$, there exists the limit transmission success probability $p_{s,n}$, as $t\\to \\infty$. The load at a typical queue is given by $\\rho_n = a_n/(p_n\\,p_{s,n})$ and the effective density of active sources is $\\lambda_n^\\mathrm{eff}=\\lambda_n p_n\\rho_n$. Considering bandwidth partitioning and stationary state, we derive the following system of equations from Eq.~\\eqref{eq:P_SIR_M}:\n\\begin{align*}\n\tp_{s,1} \n    \t&= \\nu_1\\!\\left[ P_1^\\delta \\tfrac{\\lambda_1}{M} \\tfrac{a_1}{p_{s,1}}\n        \t+\\left(\\tfrac{P_2}{M}\\right)^\\delta\\!\\lambda_2\\tfrac{a_2}{p_{s,2}}\\right],\\\\\n\tp_{s,2} \n    \t&= \\nu_2\\!\\left( P_1^\\delta \\lambda_1 \\tfrac{a_1}{p_{s,1}}\n        \t+P_2^\\delta \\lambda_2 \\tfrac{a_2}{p_{s,2}}\\right),\n\\end{align*}\n\twhich can be solved for $p_{s,1}$ and $p_{s,2}$. The mean delays $D_1$ and $D_2$ follow from Theorem~\\ref{th:geo/geo/1} as all queues in the network can be modeled as Geo/Geo/1 queues. \n\\end{proof}\n\nNext, we provide an identity that is useful when stating the optimization problem of bandwidth partitioning in Section~\\ref{sec:opt}.\n\n\\begin{theorem}\\label{th:identity}\n\tLet $p_1=p_2=1$. The system is stable if and only if the following equations hold:\n    \\begin{align}\n    \t\\frac{\\Psi_1}{M} \n        \t&= \\frac{1-\\Psi_2}{1+(M^{1-\\delta}-1)\\,\\Psi_2}, \\label{eq:theor01} \\\\\n        \\frac{P_1^\\delta}{P_2^\\delta}\n    \t\t&= \\left(\\frac{1-\\Psi_2}{\\Psi_1}\\right) \\left(\\frac{\\psi_1-\\frac{\\Psi_1}{\\lambda_1 a_1}}\n        \t\t{\\psi_2-\\frac{\\Psi_2}{\\lambda_2 a_2}}\\right), \\label{eq:theor02} \n    \\end{align}\n    with $D_1, D_2 > 1$ and \n\\begin{equation} \\label{eq:defPsi}\n\\Psi_n \\triangleq \\psi_n\\lambda_n \\left(\\frac{D_n}{D_n-1}\\right) \\left(\\frac{a_n}{1-a_n}\\right) \\ge 0, \\qquad n\\in\\{1,2\\}.\n\\end{equation}    \n% with $D_n\\in(1,\\infty)$, $n\\in\\{1,2\\}$.\n\\end{theorem}\n\n\\begin{proof}\n\tIf the system is stable, then the equations can be verified through Proposition~\\ref{prop:stationary} and some manipulations. On the other hand, to prove that a set of parameters that satisfy the equations of the theorem implies stability, one can follow these steps: plug Eq.~\\eqref{eq:theor02} into the inequalities of Proposition~\\ref{prop:stability}; then use Eq.~\\eqref{eq:theor01} and the fact that $\\Psi_n > \\psi_n\\lambda_n\\frac{a_n}{1-a_n}$ (since $\\frac{D_n}{D_n-1}>1$) to show that the inequalities of Proposition~\\ref{prop:stability} are satisfied. Then, the system is stable.\n\\end{proof}\n\\begin{remark} \\label{rmk:Th.Stb.}\n\tFrom Theorem~\\ref{th:identity},\n\t$\\frac{\\Psi_1}{M} + \\Psi_2 \\le 1$.\n\tThis follows directly from equations \\eqref{eq:theor01} and \\eqref{eq:defPsi}.\n\t%\n\tFurthermore, for fixed $M$, the quantity $\\Psi_1$ decreases if $\\Psi_2$ increases. For example, let the parameters $M,\\psi_1,\\psi_2,a_1,a_2,D_1$, and $D_2$ be fixed; if we wish to increase the density of users $\\lambda_1$ of Class 1 and maintain the aforementioned parameters constant, we necessarily need to decrease the density $\\lambda_2$ of Class 2.\n\t%\n\tNote also that $\\Psi_n$ increases with $a_n$ and decreases with $D_n$, such that $\\Psi_n$ can be seen as a comprehensive measure of the performance of users of class $n \\in \\{1,2\\}$.\n\\end{remark}\n\n\\begin{remark} \\label{rmk:FreePowers}\nIn a network where we can freely choose the transmit power ratio $P_1/P_2$, at first we only need to satisfy Eq.~\\eqref{eq:theor01} when specifying system parameters ($M,\\psi_1,\\psi_2,\\lambda_1$,$\\lambda_2$) and performance parameters ($a_1,a_2,D_1$,$D_2$). After that, we use Eq.~\\eqref{eq:theor02} to specify the transmit power levels $P_1$ and $P_2$.\n\\end{remark}\n\nTheorem~\\ref{th:identity} considers $p_1=p_2=1$, which minimizes the mean delay for both classes (see Proposition~\\ref{prop:stationary}) and maximizes the stability region (see Remark~\\ref{rem:stab}). Also, if $M=1$, we recover the result in Proposition~\\ref{prop:identity_1}, i.e., $\\sum_n \\Psi_n = 1$.\n\nIt is worth noticing the simple form through which the performance parameters $a_1,a_2,D_1$, and $D_2$ of both user classes and system stability are related.\n% \\textcolor{blue}{If the system does not have constraints regarding the ratio of the transmit powers, we may only use equation \\eqref{eq:theor01} of Theorem~\\ref{th:identity}, since it is always possible to satisfy equation \\eqref{eq:theor02} in this case. Precisamos explicar melhor essa ultima sentenca}\n\n% % % % % % % % % % % % % % % % % % % % % % % % % % % % % %\n\\subsection{Optimum Bandwidth Partition}\n\\label{sec:opt}\nLet us suppose we want to maximize the performance of Class 1 users when bandwidth partitioning is employed. More specifically, for given fixed arrival rate $a_2$ and required mean delay $D_2$ of the second user class (i.e., fixed $\\Psi_2$), we are interested in maximizing the quantity $\\frac{\\Psi_1}{\\psi_1\\lambda_1}=\\frac{D_1}{D_1-1}\\frac{a_1}{1-a_1}$, when $p_1=p_2=1$ (see Remark~\\ref{rem:stab}), by adjusting the number of partitions $M$. Note that, if we set a maximum tolerable mean delay $D_1$, this choice of optimization leads to the maximum arrival rate $a_1$ admissible. On the other hand, if we fix $a_1$, this choice of optimization leads to the minimum $D_1$ achievable. From Eq. \\eqref{eq:theor01} of Theorem~\\ref{th:identity} and recalling that $\\psi_1 = 4\\,\\Gamma(1+\\delta) \\Gamma(1-\\delta) \\overline{R}_1^2 \\theta_1^\\delta$, where $\\theta_1 = \\euler^{M\\eta_0} - 1$, one can show with simple manipulations of the ratio $\\frac{\\Psi_1}{\\psi_1\\lambda_1}$ that maximizing the quantity $\\frac{D_1}{D_1-1}\\frac{a_1}{1-a_1}$ is equivalent to the following optimization problem:\n%\n\\begin{equation} \\label{eq:opt_M}\n\tM^* = \\argmax_{M\\in\\N} \\dfrac{M\\,(\\euler^{M\\eta_0}-1)^{-\\delta}}\n    \t{1+(M^{1-\\delta}-1)\\,\\Psi_2}.\n\\end{equation}\n\n% Our interest lies in finding the optimum number of bandwidth partitions $M^*$ for the first user class.\nAfter finding the optimum number of partitions $M^*$, it is necessary to adjust the transmit power levels to satisfy Theorem~\\ref{th:identity}. In this sense, we are also choosing the optimum transmit power ratio $P_1/P_2$ (see Remark~\\ref{rmk:FreePowers}).\n\nLet us now relax the constraint that $M$ must be integer to find a closed form equation for the optimization problem \\eqref{eq:opt_M}, analogously to \\cite{jindal2008bandwidth}. Note that after the bandwidth partition, the spectral efficiency is given by $\\eta = M\\eta_0$. Now, without the constraint that $M$ must be integer, we have a new goal, which is to find the optimum spectral efficiency $\\eta^*$. An equivalent relaxed problem of \\eqref{eq:opt_M} is\n\\begin{equation} \\label{eq:opt_eta}\n\t\\eta^* = \\argmin_{\\eta\\in\\R_+} \\left(\\euler^\\eta-1\\right)^\\delta\\,\n    \\left( \\dfrac{1}{\\eta} + \\dfrac{\\beta}{\\eta^\\delta}\\right),\n\\end{equation}\nwhere \n\\begin{equation}\n\\beta \\triangleq \\frac{\\Psi_2}{1-\\Psi_2}\\eta_0^{-(1-\\delta)} \\ge 0. \n\\end{equation}\nThis new formulation can be obtained by taking the multiplicative inverse of the objective function in \\eqref{eq:opt_M}, followed by some manipulations. The following theorem guarantees the existence and uniqueness of the optimum spectral efficiency and shows how to find it.\n\n\\begin{theorem} \\label{th:optimum_eta}\n\tThe optimum spectral efficiency $\\eta^*$ is given by the unique positive solution of the following equation\n\\begin{equation}\\label{eq:Theor02}\n% \t\\dfrac{h(\\eta^*) - \\delta}{1 - h(\\eta^*)} =\n%     \\delta\\,\\beta\\,{\\eta^*}^{1-\\delta},\n\t\\big(1-h(\\eta^*)\\big) \\big(1+\\delta\\,\\beta\\,{\\eta^*}^{1-\\delta}\\big) = 1-\\delta,\n\\end{equation}\n\twhere $h(\\eta) \\triangleq (1-\\euler^{-\\eta})/\\eta$. Furthermore, $\\eta^*$ decreases monotonically with respect to $\\beta$.\n\\end{theorem}\n\n\\begin{proof}\n\tLet us prove that the objective function \\eqref{eq:opt_eta} is strictly convex in the region of interest. Since the sum of two strictly convex functions is strictly convex, then it is enough to show that ${[(\\euler^\\eta-1)/\\eta]^\\delta}$ and ${(\\euler^\\eta-1)^\\delta/\\eta}$ are convex with respect to $\\eta > 0$. Throughout the proof we need the inequalities\n    \\begin{equation} \\label{eq:aux_ineq}\n    \t0 < \\euler^{-\\eta} < h(\\eta)^2 < h(\\eta) < 1,\n    \\end{equation}\n    which are valid when $\\eta > 0$, and are easily proved using series expansion. First, let us show that\n    $\n    \t{\\frac{\\partial^2}{\\partial \\eta^2} \\left(\\frac{\\euler^\\eta-1}\n        {\\eta}\\right)^\\delta > 0}.\n    $\n    For $\\eta > 0$ and $\\delta > 0$ and after taking the derivatives with respect to $\\eta$, this inequality can be written as\n\t$\n\t{\\delta\\left( 1 - h(\\eta) \\right)^2 > \\euler^{-\\eta} - h(\\eta)^2},\n\t$\nwhich is true by \\eqref{eq:aux_ineq}. Therefore, the function ${[(\\euler^\\eta-1)/\\eta]^\\delta}$ is strictly convex, since its second derivative is positive. Now, let us show that\n\t$\n\t\t\\frac{\\partial^2}{\\partial \\eta^2} \n        \\frac{(\\euler^\\eta-1)^\\delta}{\\eta} > 0.\n\t$\n\tAgain, for $\\eta > 0$ and $\\delta > 0$, this inequality can be written as\n\\begin{equation}\\label{eq:der2eq}\n\t\\delta^2 - \\left(2\\,h(\\eta) +\n    \\euler^{-\\eta} \\right)\\,\\delta + 2\\,h(\\eta)^2 > 0.\n\\end{equation}\n\tFrom \\eqref{eq:aux_ineq}, the inequality \\eqref{eq:der2eq} is satisfied if $\\delta \\notin [1,2]$. Since $\\alpha >2$, then $\\delta\\in(0,1)$, and this is enough to prove strict convexity for the function ${(\\euler^\\eta-1)^\\delta/\\eta}$ as well. Therefore, the function to be optimized is strictly convex and differentiable, i.e., if there exists a point where the derivative vanishes, then this point is unique and it is the global minimum.\n    It is easy to verify that this strictly convex function is arbitrarily large when $\\eta$ approaches 0 or $\\infty$, then the global minimum exists and $\\eta^*\\in(0,\\infty)$. Now, manipulating the equation \n\\begin{equation*}\n\\frac{\\partial}{\\partial\\eta} \\left[ \\left( 1 + \\beta\\,\\eta^{1-\\delta}\\right)  \\frac{\\left(\\euler^\\eta-1\\right)^\\delta}{\\eta}\\right] = 0\n\\end{equation*}\nwe obtain \\eqref{eq:Theor02}, concluding the proof.\nThe proof that $\\eta^*$ decreases monotonically with respect to $\\beta$ is immediate, since $h$ is a monotonically decreasing function.\n\\end{proof}\n\nFigure~\\ref{fig:optimum_partition} shows the optimum spectral efficiency $\\eta^*$ of the first class as a function of $\\beta$ for some values of the path loss exponent $\\alpha$.\n\\begin{figure}[!t]\n\t\\centering\n\t\\includegraphics[]{./Figures/Ch7_optimum_partition.pdf}\t\n\t\\caption{Optimum spectral efficiency $\\eta^*$ of the first class as a function of the parameter $\\beta$, which is an increasing function of the parameter $\\Psi_2$ of the second user class.}\n\t\\label{fig:optimum_partition}\n\\end{figure}\nRecall that $\\beta$ is an increasing function of $\\Psi_2$, which, in turn, is a comprehensive measure of the performance requirement of Class 2 users. As expected from the previous discussion, $\\eta^*$ decreases as the performance requirement of the second class becomes more stringent, i.e., when $\\Psi_2$ increases. This behavior of $\\eta^*$ can be explained by recalling that higher spectral efficiency requires higher SIR threshold $\\theta_1$, causing stronger interference to users of the second class.\n%\nThis increased interference reduces the maximum admissible rate $a_2$ and increases the minimum achievable delay $D_2$. Since $\\Psi_2$ is kept fixed in this optimization problem, $\\eta^*$ must be limited. In fact, from Eq. \\eqref{eq:theor01} we can see that if $\\Psi_2$ increases, then $\\Psi_1$ must be reduced in order to keep the system stable.\n%\nThe propagation environment also affects the optimum spectrum efficiency. Environments with larger path loss exponent $\\alpha$ reduce the interference among users, improving the channel quality and allowing for the use of higher spectral efficiency transmission schemes.\n\nFinally, note that without the second user class ($\\Psi_2 = 0$), we have $\\beta=0$ and the equation for $\\eta^*$ in Theorem~\\ref{th:optimum_eta} has a closed form solution, which is\n\\begin{equation}\\label{eq:opt_eff}\n\t\\eta^*(\\beta=0) = \\tfrac{\\alpha}{2} +\n    W_0\\big(-\\tfrac{\\alpha}{2}\\,\\euler^{-\\alpha/2} \\big),\n\\end{equation}\nwhere $W_0$ is the principal branch of the Lambert-$W$ function, which is defined as the solution on $[-1,\\infty)$ of the equation $W_0(x)\\,\\euler^{W_0(x)} = x$, for $x \\ge -1/\\euler$.\n%\nThe above result is consistent with \\cite[Theorem~2]{jindal2008bandwidth}, where the optimization is over the traffic density achievable and the system consists of a single user class. Expression \\eqref{eq:opt_eff} was also obtained by Haenggi in \\cite{Haenggi_Lambert}.\n\nAs discussed in \\cite{jindal2008bandwidth}, the quantity $\\delta \\eta^*(0) \\to 1$ as $\\delta \\to 0$ (i.e. $\\alpha\\to\\infty$), which means that $\\eta^*(0)$ grows asymptotically as $\\alpha/2$ when the path loss exponent $\\alpha$ tends to infinity.\n%\nHowever, for a given $\\beta>0$, the same does not hold true. We can show that $\\delta \\eta^*(\\beta) \\to 0$ as $\\delta \\to 0$.\n\nIn fact, we can be more precise and show through \\eqref{eq:Theor02} that if $\\beta>0$, then $\\sqrt{\\delta} \\eta^* \\to 1/\\sqrt{\\beta}$ as $\\delta\\to 0$, which means that $\\eta^*$ grows asymptotically as $\\sqrt{\\alpha/2\\beta}$ when the path loss exponent $\\alpha$ tends to infinity.\n%\nThus, by introducing interference from another class in the system ($\\beta>0$, i.e. $\\Psi_2>0$), we change the asymptotic behavior of the optimal spectral efficiency from linear growth to squared root growth with respect to the path loss exponent $\\alpha$.\n\nThis asymptotic result can be seen in Figure~\\ref{fig:optimum_eta_delta}, where we plot the optimal spectral efficiency $\\eta^*$ adjusted by the multiplicative factor $\\sqrt{\\beta\\delta}$, which corresponds to the reciprocal of the asymptote as $\\delta$ tends to $0$ (that is why all curves converge to $1$ at $\\delta = 0$).\n%\nAnother simple asymptote of $\\eta^*$ is given by $2(1-\\delta)/(1+\\beta)$ when $\\delta$ tends to $1$ (i.e. $\\alpha\\to2$).\n\n\\begin{figure}[!t]\n\t\\centering\n\t\\includegraphics[]{./Figures/Ch7_optimum_eta_delta.pdf}\t\n\t\\caption{Optimum spectral efficiency $\\eta^*$ of the first class adjusted by the multiplicative factor $\\sqrt{\\beta\\delta}$ as a function of the parameter $\\delta = 2/\\alpha$ for several values of $\\beta$.}\n\t\\label{fig:optimum_eta_delta}\n\\end{figure}\n\nAlso, we can obtain a generalization of \\eqref{eq:opt_eff} when the performance requirements of Class 2 is small (i.e., $\\Psi_2 \\approx 0$), which is equivalent to $\\beta \\approx 0$. Then, we have the following first order expansion for the optimum spectral efficiency\n\\begin{align} \\label{eq:eta_expansion}\n    \\frac{\\eta^*\\!(\\beta)}{\\eta^*\\!(0)} = 1 - \\frac{(1-\\delta)\\eta^*\\!(0)^{1-\\delta}}{\\eta^*\\!(0)+1-\\frac{1}{\\delta}} \\beta + \\cal{O}(\\beta^2),\n\\end{align}\nas $\\beta$ tends to zero, $\\eta^*\\!(0)$ is given by Eq.~\\eqref{eq:opt_eff} and $\\cal{O}$ is the big O notation as defined in Definition~\\ref{def:landau}.\n% \\footnote{\n% We say $f(x) = \\cal{O}(g(x))$ as $x\\to a$, if $\\limsup\\limits_{x\\to a} \\frac{|f(x)|}{g(x)} < \\infty$.\n% }.\n%\nThe above expression is found using implicit differentiation on \\eqref{eq:opt_eta} and some manipulations.\n\nWe can verify through \\eqref{eq:eta_expansion} that the optimal spectral efficiency has a steeper (relative) decay for larger values of the path loss exponent $\\alpha$, when $\\alpha > 2.48$.\n%\nThis means that the presence of interference from another class has a larger relative impact on the optimal spectral efficiency when $\\alpha$ is large.\n\n% \\begin{figure}[!t]\n% \t\\centering\n% \t\\input{./Plots/optimum_partition_norm.tex}\t\n% \t\\caption{Optimum spectral efficiency $\\eta^*$ of the first class as a function of the parameter $\\beta$, which is an increasing function of the parameter $\\Psi_2$ of the second user class.}\n% \t\\label{fig:optimum_partition_norm}\n% \\end{figure}\n\n% % % % % % % % % % % % % % % % % % % % % % % % % % % % % %\n\\subsection{Applications}\n\\label{sec:num}\n\nIn this section, we illustrate the analytical results through some numerical examples. Let the first and second user classes represent the opportunist and the main users of a given bandwidth $B_0$, respectively.\n%\nThe opportunist users access the same frequency band as the main users and we perform bandwidth partitioning for the opportunistic access in order to improve the performance of the opportunist users for a given performance of the main users, which is equivalent to fixing the quantity $\\Psi_2$.\n\nFrom now on, we shall use the numerical values in Table~\\ref{tab:user_classes} for the numerical examples.\n%\n\\begin{table}[!ht]\n    \\centering\n        \\caption{Parameter values.}\n    \\begin{tabular}{ c|l }\n    \\hline\n    Parameters & Values \\\\\n    \\hline\\hline\n     $\\lambda_1$        & $\\SI{0.005}{/m^2}$      \\\\\n     $\\lambda_2$        & $\\SI{0.002}{/m^2}$      \\\\\n     $\\overline{R}_1$   & $\\SI{10}{m}$            \\\\\n     $\\overline{R}_2$   & $\\SI{20}{m}$           \\\\\n     $\\eta_0$           & $\\SI{0.2}{bits/s/\\hertz}$   \\\\\n     $p_1=p_2$          & $1$   \\\\\n    \\hline\n    \\end{tabular}\n    \\label{tab:user_classes}\n\\end{table}\n%\nWe begin our analysis by comparing the stability regions with and without bandwidth partition. \n% Let the system parameters be $\\lambda_1 = \\SI{0.005}{/m^2}$, $\\lambda_2 = \\SI{0.002}{/m^2}$, $\\overline{R}_1 = \\SI{10}{m}$, $\\overline{R}_2 = \\SI{20}{m}$ and the (initial) spectral efficiency $\\eta_0 = 0.2\\,\\ln(2)\\,\\si{nats/s/\\hertz}$ for both classes.\n%\nOur approach to determine the stability regions is the following: we begin by using  Theorem~\\ref{th:optimum_eta} to find the optimum spectral efficiency $\\eta^*$ of the first class for a given value of ${\\Psi_2\\in(0,1)}$ (see Remark~\\ref{rmk:Th.Stb.}); then, we choose the number of sub-bands $M$ as the closest integer%\n\\footnote{This is a functional thumb rule to find the optimum number of partitions $M^*$. However, the ideal approach is to verify through the objective function if the best is to round up or round down.\nIn our plots, we used the thumb rule, since there is no visual difference.}\nto $\\eta^*/\\eta_0$ (it is worth remembering that $\\Psi_2$ is fixed, so the performance requirements of Class 2 are still satisfied); finally, we use Theorem~\\ref{th:identity} along with the fact that $p_1=p_2=1$ maximizes the stability region to obtain the union of the stability regions for all the transmit power ratios $P_1/P_2$ and for all medium access probabilities $p_1$ and $p_2$. The results are shown in Fig.~\\ref{fig:optimum_stab_region} for $\\alpha = 2.5$ and $4.5$.\n%\n\\begin{figure}[!t]\n\t\\centering\n\t\\includegraphics[]{./Figures/Ch7_optimum_stab_region.pdf}%\n\t\\caption{Stability regions of the network for different values of path loss exponent $\\alpha$. The arrival rates $a_1$ and $a_2$ are the opportunist and main users, respectively; full and dashed curves correspond to the boundaries of the stability region with and without bandwidth partition, respectively. Parameter values are shown in Table~\\ref{tab:user_classes}.}\n\t\\label{fig:optimum_stab_region}\n\\end{figure}\n%\nWe can see that the optimization of the spectral efficiency of the first user class (through bandwidth partitioning) expands the stability region. Note that when the path loss exponent $\\alpha$ is small (close to 2), the optimization does not improve significantly the system performance.\n%\nAnother observation is that if the traffic from main users (Class 2) is high, i.e., it is responsible for the majority of the interference, then it makes practically no difference to perform bandwidth partitioning in the opportunist class (Class 1). On the other hand, as the traffic from opportunist users increases, the impact of the optimization also increases\n% \\textcolor{red}{(esse melhor desempenho no canto direito inferior da região ($a_1$ alto e $a_2$ baixo) tem a ver apenas com a baixa interferência causada pelos usuários 2? Acho que poderíamos explorar esse melhor desempenho nessa região, pois é a região de interesse da ideia da partição.)}.\n\nLet us now consider another example to analyze the effects of bandwidth partitioning on the mean delay.\n% For this, we set the initial spectral efficiency for the opportunist class $\\eta_0 = 0.2\\,\\ln(2)\\,\\si{nats/s/\\hertz}$, the access probabilities $p_1=p_2=1$.\n%\nWe then determine the mean delay $D_1$ of the opportunist class as a function of its arrival rate of packets $a_1$, for $\\Psi_2 = 0.25, \\, 0.5, \\, 0.75$. Note that $\\Psi_2$ can be seen here as a measure of the performance required by the main class (see Remark~\\ref{rmk:Th.Stb.}). The procedure to find $M^*$ is analogous to the one used in the last example. The results are shown in Fig.~\\ref{fig:optimum_delay}.\n%\n\\begin{figure}[!t]\n\t\\centering\n\t\\includegraphics[]{./Figures/Ch7_optimum_delay.pdf}%\n\t\\caption{Opportunist (first class) mean delay $D_1$ as a function of opportunist arrival rate $a_1$, for different values of the main user performance requirement $\\Psi_2$. Full and dashed curves correspond to the cases with and without bandwidth partition, respectively. Parameter values are shown in Table~\\ref{tab:user_classes}.}\n\t\\label{fig:optimum_delay}\n\\end{figure}\n%\nWhen the performance requirements of the main users are modest (small $\\Psi_2$), bandwidth partitioning allows for a more efficient use of the channel by opportunist users, i.e., a larger arrival rate $a_1$ is possible, or a smaller mean delay is achieved. On the other hand, and as expected from the previous analysis, we can also see that when the requirements of main users become more stringent (larger $\\Psi_2$), then less noticeable is the improvement from the bandwidth partitioning.\n%\n\\begin{figure}[!t]\n\t\\centering\n\t\\includegraphics[width=0.7\\columnwidth]{./Figures/Ch7_a_ratio.pdf}%\n\t\\caption{Maximum throughput relative improvement of Class 1 after band partition. Parameter values are shown in Table~\\ref{tab:user_classes}.}\n\t\\label{fig:a_ratio}\n\\end{figure}\n\n% \\begin{figure}[!t]\n% \t\\centering\n% \t\\input{./Plots/a_ratio_v2.tex}\t\n% \t\\caption{Maximum throughput improvement of Class 1 after band partition. Parameter values are shown in Table~\\ref{tab:user_classes}. \\textcolor{red}{Daria para colocar ``curvas de nível'', relativas a alguns valores de ganho?}}\n% \t\\label{fig:a_ratio_v2}\n% \\end{figure}\n\nFigure~\\ref{fig:a_ratio} shows the relative improvement of the maximum throughput after band partition of Class 1 relative to the maximum throughput before band partition, for all possible values of $\\Psi_2$ and $\\delta$. For example, in the yellow region, we have almost doubled the throughput ($\\approx 100\\%$ improvement) after implementing the optimum number of band partitions. As we have previously seen through figures \\ref{fig:optimum_stab_region} and \\ref{fig:optimum_delay}, the bandwidth partitioning strategy of the first user class improves significantly the performance of Class 1 users as the Class 2 performance requirements $\\Psi_2$ is small and the path loss exponent $\\alpha$ is large (which is equivalent to small $\\delta = 2/\\alpha$). On the other hand, when the path loss exponent $\\alpha$ is small or the performance requirements of the main (Class 2) users $\\Psi_2$ is stringent, there is almost no gain in performing bandwidth partitioning of the opportunistic class (Class 1).\n\n% % % % % % % % % % % % % % \n\\section{Summary} \\label{sec:summ_P2_03}\n\nIn this chapter, we derived necessary and sufficient conditions for stability in a network with $N$ user classes; we also provided simple closed form expressions for the packet success probability and mean delay. The advantage of using this model as a base to model other network effects is its analytic tractability.\n%\nAs an example, we were able to derive simple conditions to verify the stability of an interference-limited network with undetermined transmit powers using Corollary~\\ref{cor:stab}.\n%\nWe also solved (analytically and in closed form) two optimization problems regarding the minimization of the delays in a network and maximization of the total throughput per unit of area.\n%\nAn interesting insight from the optimization problems is that the best solution to maximize the throughput of a channel is not necessarily using solely the user class with the best link quality, i.e., a mix with other user classes may result in better use of the channel.\n% \n% All in all, this paper provides a simple way to evaluate the existing trade-offs involved in the design of wireless networks when different classes of nodes co-exist.\n\nFurther, we showed that, under certain conditions, bandwidth partitioning can significantly improve the performance of the network (under stability condition) by means of higher allowable arrival rates or lower mean delays. This is the first time the problem of bandwidth partitioning is treated analytically for two interacting user classes, for which arriving packets are queued.", "meta": {"hexsha": "8e4f7f4e6004c0c0be8aadf8c5b36d8261e0a7bb", "size": 114407, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "P2_03.tex", "max_stars_repo_name": "pliniodester/PhD_thesis", "max_stars_repo_head_hexsha": "65b00b31ebdac9dda68b1e83e937fcaed92ce354", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "P2_03.tex", "max_issues_repo_name": "pliniodester/PhD_thesis", "max_issues_repo_head_hexsha": "65b00b31ebdac9dda68b1e83e937fcaed92ce354", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "P2_03.tex", "max_forks_repo_name": "pliniodester/PhD_thesis", "max_forks_repo_head_hexsha": "65b00b31ebdac9dda68b1e83e937fcaed92ce354", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 79.7261324042, "max_line_length": 1089, "alphanum_fraction": 0.7009798351, "num_tokens": 35275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.3443218050191247}}
{"text": "\\documentclass[12pt, a4paper]{scrartcl}\n\\usepackage[utf8]{inputenc}\n\\usepackage{graphicx}\n\\usepackage{amsmath, amsthm, amssymb, textcomp}\n\\usepackage{setspace}\n\\usepackage{paralist}\n\\usepackage{graphicx}\n\\usepackage{caption}\n\\graphicspath{{WSK_im/}} %Graphic is in a folder named WSK_im in the currend directory\n\\usepackage{float}\n\\usepackage{authblk}\n\\renewcommand\\Authfont{\\fontsize{12}{14.4}\\selectfont}\n\\title{Bayesian probability theory - Lesson 8:\\\\\nContinuous probability distributions and invariance}\n\n\\author{Wolfgang von der Linden, Gerhard Dorn, Johanna Moser}\n\\date{Transcript}\n\n\\begin{document}\n\\setlength{\\parindent}{0pt}\n\\maketitle\n\\onehalfspacing\n\nWelcome to unit 8 of the course on Bayesian probability theory. My name\nis Wolfgang von der Linden and I will enable you to help Captain Bayes and\nher crew to deal with \\textbf{continuous variables} and to learn how to\\textit{assign prior probabilites}.\n\\begin{itemize}\\item We will learn how to work with \\textbf{probability densities} instead of probability mass functions.\n\\item We will learn how to use the \\textbf{transformation law} to locate the lighthouse and the principle of \\textbf{transformation invariance} will allow us to derive \\textbf{Jeffrey’s prior}\n\\item We will study the probability distribution of the first digits of mathematical tables.\n\\end{itemize}\n\n\n\\section*{Continuous variables}\nUp to this point we have actually only introduced the rules of probability\ntheory for \\textbf{discrete variables}. But you certainly realized that \\textbf{continuous\nvariables} have also crept into the problems of the last unit, for example in the star\npath problem or the fishing ground problem. We even mentioned probability\ndensities. \\\\\nThe values of the parameters in the continuous case can take on\n\\textit{any real number} in a given interval or even on the entire real axis.\nNow it’s time to extend the rules of probability theory to continuous variables.\\\\\n\nLet’s start with the following consideration: Assume we are interested in the height of trees. Typically it ranges between 0 and and a maximum height $h_{max}$. To get started we discretize the possible heights into $N$ intervals of equal length. For simplicity, we assume that all heights are equally probable. Therefore,\nthe probability that the height $l$ of a randomly selected tree lies in\nthe interval $I_i$ is the same for all intervals.\n\\[P(\\Delta I_i)=\\frac 1N = \\frac{\\Delta l}{l_{max}}\\]%\n\nTwo things are important to note here:\\\\\na) If we increase the number of intervals the probability goes to zero. So\nthe \\textit{probability for a continuous variable to have a precise value is zero} and\nhence it makes no sense to speak of probabilities or to use a probability mass\nfunction to assign probabilities to certain variables.\\\\\n\n\\fbox{\\parbox{\\linewidth}{\\textbf{Question 1.} Which of the following statements are true?\\\\\na) The height of trees shall be uniform in the interval [0,30]. Then, the probability for a tree to have a height of 20 meters is $\\frac{1}{30}$.\\\\\nb) The height of trees shall be uniform in the interval [0,30]. Then, the probability to have a tree of 15 to 17 meters is $\\frac{1}{15}$.\\\\\nc) The height of trees shall be uniform in the interval [0,30]. Then, the probability to have a tree of 14 to 16 meters is $\\frac{1}{15}$.\\\\\nd) Assuming a unifor mistribution with the probability given for an interval $P(\\Delta I)=A$, the probability for $P(\\Delta I/2)=A/2$.\n}}\n\\\\\n\nb) We see that the probability is \\textit{proportional to the interval size} $\\Delta l$ .\\\\\nBoth points stay valid in the case of non-equidistant intervals and also if the height\ndistribution of trees is not uniform.\\\\\n\nIn general, we find for the probability, that the height of a tree lies in a certain interval, is \\textit{proportional} to the length of this interval. The proportionality function is the \\textbf{probability density} $p(l)$.\n It is the probability to find a tree with a length in the interval $[l,l+\\Delta l]$ divided by the interval length.\n \\begin{equation*}\\boxed{p(l)=\\frac{P(\\Delta I_l)}{\\Delta l}\n}\\end{equation*}\\\\\nThe probability for the height of a tree to fall into an interval can also be obtained\nform the difference\n\\[P(\\Delta I_l)=P(\\text{height}\\leq l+\\Delta l)-P(\\text{height} \\leq l)\\]\n\nWe introduce a special function $P(\\text{height}\\leq l)=F(l)$ for these probabilities, which are called \\textbf{cumulative distribution functions}. %\nThe reason for this term becomes clear when we rewrite $p(l)$ in\nterms of the cdf:\\\\\n\\[p(l)=\\frac{F(l+\\Delta l)-F(l)}{\\Delta l}\\]\n\nFor infinitesimal interval length the pdf turns into the \\textit{derivative} of the cdf\nand in turn the cdf is the integral of the pdf.\\\\\n \\begin{equation*}\\boxed{F(l)=\\int_0^lp(l')\\text{d}l'\n }\\end{equation*}\\\\\n\nThat explains why it is called cumulative. We also see that the normalization\nimplies that the cdf approaches 1 when the length approaches the upper\nlimit of the the range of this random variable.\\\\\n\n\\fbox{\\parbox{\\linewidth}{\\textbf{Question 2.} Which of the following statements are true?\\\\\na) If the pdf is Gaussian, then the cdf is also Gaussian.\\\\\nb) If the pmf is given, then the pdf can be obtained by the derivative.\\\\\nc) If I want to know the probability that a tree is at max 20 meters high, I can use the cdf $F(20)$.\\\\\nd) The cdf has the following form: $F(x)\\propto x^2$. Then the pdf reads $p(x)\\propto x$.\n}}\n\\\\\n\nTo keep the notation clear, we denote pdfs with the lowercase letter $p$ and\nstick with the uppercase letter $P$ for the probability mass functions.\\\\\n\n\\section*{Calculations with continuous variables}\nThe sum and product rule are the same for continuous and discrete variables.\nBut the normalization and the marginalization rule are slightly different, as we do have integrals instead of sums. %8_1\n \\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{8_1.png}\n\\end{figure}\nHere, the difference between the four marginalization formulas is that capital letters stand for discrete lower case letters for continuous variables. Similarly, the mean value of functions $f(x)$ of continuous random variables x are also converted to integrals. \\\\\n\\begin{equation*}\\boxed{\\langle f(X)\\rangle = \\sum_i f(X_i)P(X_i)\\qquad \\langle f(x)\\rangle = \\int \\text{d}x f(x)p(x)\n}\\end{equation*}\\\\\nHere, the probability mass function is replaced by the pdf.\\\\\n\n\nNow there is a specialty of continuous variables: You can introduce \\textbf{transformations} like $l\\mapsto m(l)=l^3$, which for a spherical tree would be proportional\nto the mass and if one is interested in the mass then the corresponding pdf would be $p(m)$. Then a question occurs naturally: \\textit{If we know the pdf $p(l)$ for the length what is the pdf $p(m)$ for the mass?}\\\\\n\nThe probability, that the height of a tree lies in the interval $[l,l+\\Delta l]$, is given by d$P$.\nThe mass of these trees lies in the interval $[m,m+\\Delta m]$. Since they are the same trees, we can express dP in terms of the mass and finally, due to the unique relation ``$m$ is a unique function of $l$ and $l$ is a unique function of $m$'' (i.e. bijection), we obtain the very important transformation law.\\\\\n\\begin{equation*}\\boxed{p(m)=p(l(m))\\left|\\frac{\\text{d}l(m)}{\\text{d}m}\\right|\n}\\end{equation*}\\\\\n\nFor the case of the uniform height distribution from above, $p(l)$ is constant, we\nobtain the pdf for the mass. \\[p(m)=\\frac{1}{l_{\\text{max}}}\\frac{\\text{d}(m^{1/3})}{\\text{d}m}=\\frac{1}{3l_{\\text{max}}}m^{-2/3}\\]\n\n\\fbox{\\parbox{\\linewidth}{\\textbf{Question 3.} Which of the following transformations are correct?\\\\\na) $p(x)=\\frac 1x$ and $y(x)=\\frac 1x$. Then, the pdf of $y$ is $p(y)=\\frac{1}{y^3}$\\\\\nb) $p(x)=\\frac 1x$ and $y(x)=\\frac 1x$. Then, the pdf of $y$ is $p(y)=\\frac{1}{y^2}$\\\\\nc) $p(x)=x^2$ and $y(x)=\\tan(x)$. Then, the pdf of $y$ is $p(y)=\\arctan(y)^2\\frac{1}{1+y^2}$\n}}\n\\\\\n\n%8_2\n \\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{8_2.png}\n\\end{figure}\nSo instead of being uniform, the pdf for the mass is sharply peaked at zero.\nThat brings us to a very fundamental question: \\textit{How do we describe ignorant pdfs?}\\\\\n\nIn the discrete case the law of indifference implied equal probability but in the\ncase of continuous variables ignorance does not necessarily imply a uniform pdf.\nAs a further example, let us consider a non-negative quantity $x$ that is known\nto have a uniform pdf in the interval $[0,x_{\\text{max}}]$. But we are interested in the\npdf of a variable $y=\\exp(x)$. The desired pdf is proportional\nto $\\frac{1}{y}$. So we have found, if a variable is \\textit{linear on a logarithmic scale $\\log(y)=kx+d$}, \nthen it's pdf has a \\textit{$\\frac 1y$ dependance on the linear scale}.\\\\\n\nFinally, we want to consider the transformation law for the \\textbf{multivariate case}.\nLet $\\vec{x}$ be a set of variables with $N$ elements and $\\vec{y}$ a new set of variables with the invertible transformations: \n$\\vec{y}(\\vec{x})$ is a unique function of $\\vec{x}$ and $\\vec{x}(\\vec{y})$ in turn is a unique function of $\\vec{y}$. Then the pdfs are related by the following expression, where the last factor is the \\textbf{Jacobi-determinant}.\\\\\n\\begin{equation*}\\boxed{p(\\vec{y})=p(\\vec{x}(\\vec{y}))\\left|\\frac{\\text{d}x_i}{\\text{d}y_j}\\right|\n}\\end{equation*}\\\\\n\n\\fbox{\\parbox{\\linewidth}{\\textbf{Question 4.} We look at the polar transformation of a uniform pdf:\\\\\nGiven is a uniform pdf of $\\vec{x}=(x_1,x_2), \\vec{y}=(r,\\phi)$ with $x_1=r\\cos(\\phi),x_2=r\\sin(\\phi)$. Which of the following statements are true?\\\\\na) The pdf of $\\vec{y}$ is given by $p(r,\\phi)\\propto r$\\\\\nb) If $p(\\vec{x})=p(x_1,x_2)\\propto x_1+x_2$, then $p(\\vec{y})=p(r,\\phi)=r^2(\\cos(\\phi)+\\sin(\\phi))$\\\\\nc) The determinant of the Jacobi Matrix is given by $r^2(\\sin^2(\\phi)+\\cos^2(\\phi)=r^2$\\\\\nd) The Jacobi matrix is given by $\\left( {\\begin{array}{cc}\n   \\cos(\\phi) & -r\\sin(\\phi)\\\\\n   \\sin(\\phi) & r\\cos(\\phi) \\\\\n  \\end{array} } \\right)$\n}}\n\\\\\n\n\\section*{Bertrand paradox - ignorant priors}\nThe crew of Captain Bayes was pondering about the so-called \\textbf{Bertrand paradox} which is defined as follows:\\\\\n\\textit{Given a circle of radius R and a random set of lines that cross the circle,\nwhat is the probability that a random line has a distance from the center that is less than half the radius?}\\\\%8_3\n \\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{8_3.png}\n\\end{figure}\n\nThe line cuts the circle at two points $P_1$ and $P_2$.\nWe can define these endpoints by the angles $\\varphi_1$ and $\\varphi_2$ formed by the \\textit{radial lines to the endpoints with the x-axis}. These are two independent variables that uniquely define the line.\\\\%8_4\n \\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.4\\textwidth]{8_4.png}\n\\end{figure}\n\nThe line is also uniquely defined by the midpoint $P$ of the two endpoints $P_1$ and $P_2$. \nThis involves again two\nindependent variables, namely the $x$ and $y$ coordinate of the point. Finally, for solving the problem, it is enough to know the distance $r$ of the line from the center of the circle. \\\\%8_5\n \\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.4\\textwidth]{8_5.png}\n\\end{figure}\n\nNow think of how you would simulate the problem on the computer.\nBernoulli came up with the idea to choose the points $P_1$ and $P_2$ at random\non the circle. That is equivalent to choosing the two angles $\\varphi_1$ and $\\varphi_2$\nat random. That in turn implies that the \\textit{pdf of the intermediate angle is\nuniform.}\\\\\n\nIn this variable, the distance of the line to the center is given by $R\\cos(\\varphi/2)$\n and the\ncondition, that the line has a distance less than $R$ half from the center, is given by \\[R\\cos(\\varphi/2)\\leq R/2\\]\n\n\\fbox{\\parbox{\\linewidth}{\\textbf{Question 5.} What is the range of $\\varphi\\in(0,\\pi]$ fulfilling the inequality $R\\cos(\\varphi/2)\\leq R/2$?\\\\\na) $\\varphi \\in [\\pi/4,\\pi/3]$\\\\\nb) $\\varphi \\in [0,\\pi/2]$\\\\\nc) $\\varphi \\in [0,2\\pi/3]$\\\\\nd) $\\varphi \\in [2\\pi/3,\\pi]$\\\\\n}}\n\\\\\n\nwhich implies $\\varphi < \\frac{\\pi}{6}$. Hence the desired probability is $\\frac 13$.\\\\%8_6\n \\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{8_6.png}\n\\end{figure}\n\nAnother way of generating the line at random was proposed in the adventure\nby Pascal. She generates the midpoint at random, which means the points\nare \\textit{uniformly distributed within the circle}. Then the desired probability is\nthe probability that the point lands in the circle of radius $\\frac R2$. This is a nice\nillustration of the transformation law for two variables.\\\\\nInstead of the Cartesian coordinates $x$ and $y$ we use spherical coordinates $r$ and $\\varphi$. The transformation law yields for the correctly normalized pdf the following expression. %8_7\n \\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{8_7.png}\n\\end{figure}\nThe desired result requires that $r<\\frac R2$ and the corresponding probability gives $\\frac 14$.\n\nFinally, Laplace suggested to generate the radial distance uniformly between 0 and $R$ resulting in a constant pdf. In that case the probability is $0.5$. \nThe question is now, \\textit{which algorithm describes the physical experiment?}\\\\\n\n\\fbox{\\parbox{\\linewidth}{\\textbf{Question 6.} Guess who is right! What is the probability for a free day (= that the line does not cut the inner circle)? Do you know why?\\\\\na) Laplace: It is a 50\\% chance to have a free day.\\\\\nb) Pascal: It is a 75\\% chance to have a free day.\\\\\nc) Bernoulli: It is a 67\\% chance to have a free day.\n}}\n\\\\\n\nThis question is already on the mind of scientists for generations and still is.\nWe can phrase this problem more generally: If we know nothing about the\npdf apart from the definition of the setup - so there are no experimental\ndata or additional theoretical constraints - what is the correct way to find an\nun-informative prior? So how do we assign probabilities in the continuous way?\nSuch an object is also called an \\textbf{ignorant prior}.\\\\\n\nFor ignorant priors Ed Jaynes came up with the following idea. \\textit{If there is a\ncontinuous and invertible map $\\vec{T}(\\vec{x})$ from one set of variables $\\vec{x}$ to a\nnew set $\\vec{y}$, then the corresponding pdfs should be the same, i.e $p(\\vec{y})=p(\\vec{x})$.} In the case of the die it\nmeans that putting the pips on different sites of the cube should not modify the probability mass function.\nIn other words, \\textit{the probability mass function should be invariant against\npermuting the indices}, which results in the well-known uniform distribution.\nSince the mapping in the continuous case is assumed to be continuous as\nwell, we can introduce a parameter$\\epsilon$ such that for $\\epsilon\\rightarrow 0$ the mapping is the\nidentity. \\[\\lim_{\\epsilon\\rightarrow 0}\\vec{T}_{\\epsilon}(\\vec{x})=\\vec{x}\\]\n\nUsing the transformation law from above and the invariance properties of\nthe pdf, Jaynes came up with the following equation for the pdf:%8_8\n \\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{8_8.png}\n\\end{figure}\n\nLet’s illustrate this approach for a \\textbf{scale variable} $y=\\alpha x$. A scale variable $x$ is a\n\\textit{non-negative quantity for which the pdf should be scale invariant}. In this case, the infinitesimal transformation has the following form:\\[T_{\\epsilon}=(1+\\epsilon)x\\]\nJaynes’ equation can be solved by elementary tools\nand the result is \n\\begin{equation*}\\boxed{p(x)=\\frac 1x\n}\\end{equation*}\\\\\nNote that this is a so-called \\textbf{improper pdf}, as it \\textit{cannot be normalized}. In the\nframe of Bayesian probability theory, such a prior is not forbidden as long as\nthe resulting posterior is normalizable.\nThis scale-invariant pdf is often called \\textbf{Jeffreys’ prior}, although it is only a\nspecial application of Jeffreys’ idea.\\\\\n\nThe uninformative prior pdf of parameters a depends of course on the\nmeaning of the parameters. In many cases these are uniquely determined\nby the likelihood function $p(d|a)$. In that case, a pdf that is invariant against reparameterization is given by $p$ of a is given by the determinant of g (see picture).%8_9\n \\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{8_9.png}\n\\end{figure}\n\nA typical example of the scale variable is the standard deviation $\\sigma$ that enters\na Gaussian likelihood. This is a nice and informative exercise for the application of Jeffrey’s prior. The result is the same as that obtained by Jaynes’\napproach $p(\\sigma)=\\frac{1}{\\sigma}$\\\\\n\nEd Jaynes applied the principle of transformation invariance to the Bertrand paradox.\nHe used the following transformations under which the problem is invariant:%\n\\begin{enumerate}\n\t\\item Translation of the center of the circle\n\t\\item Rescaling of the radius\n\t\\item Rotation of the circle about the center\n\\end{enumerate} \nThe solution of his equation yields the same result that Laplace proposed :\\\\\n\\[p(r)=\\text{const}=\\frac 1R\\]\n\nThere is another way to approach the Bertrand paradox. Since the lines\nare drawn randomly and without knowing the position of the circle, we can\nequally well draw the line first and then randomly place the circle on the\nplane. The circle is uniquely defined by its center and therefore this is equivalent to randomly choosing the coordinates $x$ and $y$ of the center. If we define\nthe direction of the line as the $x$-axis, then the $x$-coordinate of the center is\nirrelevant. Consequently, the distance of the line from the center of the circle is given by the absolute value of $y$. As the coordinates of the center are\nchosen at random, the distance is a uniform random variable corroborating\nJaynes' result.\\\\%\n\n\\section*{Maximum Entropy}\nWe have encountered the \\textbf{maximum entropy principle} already in the discrete case. It\nwas introduced to obtain the probability mass function in the case of testable\ninformation given for instance in the form of mean values. Maximum entropy can also\nbe invoked for pdfs given testable information for instance in the following form:\\[\\int \\text{d}x f_i(x)p(x)=\\mu_i\\]\n\nThe only complication in the continuous case is that the entropy is not entirely what you would expect.\\\\\n\\begin{equation*}\\boxed{S(p)=-\\int dx p(x)ln\\left(\\frac{p(x)}{p_0(x)}\\right)\n}\\end{equation*}\\\\\n\nThe function $p_0(x)$ is sometimes called the \\textbf{default model}, because the MaxEnt\nsolution without any constraints apart from normalization yields $p(x)=p_0(x)$.\\\\\nThe deeper reason why we have a default model in the continuous case and\nnot in the discrete case is that the transition by discretization from the\ncontinuous to the discrete case is not unique.\nThe default model plays the role of an ignorant prior.\nOtherwise, the implementation of testable information in the maximum entropy procedure is the same as in the discrete case.\nOn passing we want to discuss a simple application from statistical physics.\nWe want to infer the pdf $p(x)$ of particles at the height $x$ above the earth.\nThe mean potential energy of these particles is proportional to the mean\nheight.\\[E=mg\\int x p(x)\\text{d}x \\propto \\langle x\\rangle\\]\n\nIn a canonical ensemble the mean energy is given by $k_BT$\nSo the constraint has the following form: \\[ \\langle x \\rangle = \\int xp(x)\\text{d}x = \\frac{k_BT}{mg}\\]\n\nMaximizing the entropy yields the \\textbf{Barometric formula} $P\\propto \\exp(-\\alpha x)$.\nNote that $x$ is \\textit{not\na scale variable here as there is an upper limit for it}. Therefore, a uniform prior\nis adequate, which is corroborated by the experimental observation for free\nparticles without potential energy.\\\\\n\nIn closing, it should be mentioned that this form of entropy is also called\n \\textbf{cross-entropy} or in other context the  \\textbf{Kullback-Leibler distance}.\n \\[d_{KL}(p,q)=\\int_{-\\infty}^{+\\infty}p(x)log\\left(\\frac{p(x)}{q(x)}\\right)\\text{d}x\\]\n It can be\nconsidered as distance between distributions $p(x)$ and $p_0(x)$, and it plays\nan important role in machine learning.\\\\\n\n\\fbox{\\parbox{\\linewidth}{\\textbf{Question 7.} Which of the following statements is true?\\\\\na) We need a default model $p_0$ in the entropy $S$ in the continuous case, since the mapping from the continuous to the discrete case is not unique.\\\\\nb) The height variable $x$ when deriving the barometric formula is uniform since the earth has a finite atmosphere.\\\\\nc) We need a default model $p_0$ of the entropy $S$ in the continuous case, since variables are scale invariant.\n}}\n\\\\\n\n\n\\section*{The lighthouse problem}\nThe lighthouse problem that Lyra addressed in the adventure is another\nexample of the  \\textbf{transformation of coordinates}. Let $x_0$ and $y_0$ be the coordinates\nof the lighthouse and let the coast line define the $x$-axis with the origin of\nthe coordinate system being on the coast line.\nThe lighthouse emits light signals that are uniformly distributed in the rotation angle $\\varphi$ about the lighthouse axis. We are interested in the pdf for a\nlight signal being detected at point $\\boldsymbol{x}$ on the coast line.\nThe following relation exists between the coastline position x and the\nangle $\\varphi$, and the transformation law yields the desired pdf for $\\boldsymbol{x}$ from the uniform pdf for\nthe angle.\\\\ %8_10\n \\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{8_10.png}\n\\end{figure}\n\n$p(\\boldsymbol{x}|x_0,y_0)$ is the probability to find a light signal at position $\\boldsymbol{x}$ given the parameters\n$x_0,y_0$ and therefore it represents the likelihood of the problem.\nWe assume for simplicity that the data points $\\boldsymbol{x}_i$ are uncorrelated. Bayes\ntheorem then yields for the desired pdf for the position of the lighthouse the following form.\n\\[p(x_0,y_0|\\boldsymbol{x})=\\frac 1Z \\prod_i p(\\boldsymbol{x}_i|x_0,y_0)p(x_0,y_0)\\]\nThe prior probability depends on our knowledge about lighthouses.\n\\textit{In the Pluto notebook you can gain experience with this problem and see that\nit is indeed possible to locate the lighthouse on the basis of the distribution\nof the light ﬂashes on the coastline.}\n\n\\section*{Important distributions}\nThere are many important distributions for continuous variables. Here we\nonly want to mention the most popular ones.\nWe have repeatedly used Bayes’ theorem to compute the posterior pdf for a\nparameter a given some data d.\nLet’s first ignore the prior $p(a)$, then the posterior is proportional to the likelihood $p(a|\\boldsymbol{d})\\propto p(\\boldsymbol{d}|a)$.\nIn case of a counting experiment with a Poisson likelihood the parameter\n$a$ corresponds to the mean $\\mu$ and the data are the counts $\\boldsymbol{N}$. Then the\nposterior is of the following form:\n\\begin{equation*}\\boxed{p(\\mu|\\boldsymbol{N})\\propto e^{-\\mu}\\mu^\\boldsymbol{N}\n}\\end{equation*}\\\\\nThis function is a  \\textbf{Gamma-distribution}, that is defined for the range $x\\in [0,\\infty)$\nand with the correct normalization it reads.%8_11\n \\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{8_11.png}\n\\end{figure}\nIt has a \\textit{power-law dependence for small x} and \\textit{decays exponentially for large\nx}. Mean and variance are given by the following expressions.\n\\begin{equation*}\\boxed{\\langle x\\rangle = \\frac{\\alpha}{\\beta} \\qquad \\text{var}(x)=\\frac{\\alpha}{\\beta^2}\n}\\end{equation*}\\\\\nThey can easily be derived from the Gamma function which is part of\nthe normalization.\n\\[\\Gamma(\\alpha):=\\int_0^{\\infty}t^{\\alpha-1}e^{-t}\\text{d}t\\]\nThe Gamma function has a very convenient recursion relation\nand for an integer argument it is related to the factorial: \\[\\Gamma(N)=(N-1)! \\quad N\\in\\mathbb{N}\\]\n\nMoreover, we want to mention that $\\Gamma(\\frac 12)=\\sqrt{\\pi}$.\nSpecial cases of the Gamma distribution are the  $\\mathbf{\\chi^2}=\\Gamma(\\frac n2, \\frac 12)$ \\textbf{distribution} \nand the  \\textbf{exponential distribution} $\\Gamma(1, \\beta)$.\\\\%\n\nSo far we have only discussed the likelihood which lead to the Gamma distribution. If we include an arbitrary prior, then the posterior will be different.\nFor that reason it is common practice to also use a Gamma distribution for\nthe prior. This is not a significant restriction, as prior knowledge is typically\nvague and the Gamma distribution is very ﬂexible and can cover a wide range\nof prior knowledge. Such a so-called  \\textbf{conjugate prior} has the advantage that\nthe posterior is still a Gamma distribution and mean and covariance can be\ncomputed analytically.\\\\\n\n\nNow we turn to a Bernoulli experiment with sample size $N$. Here, the parameter a\ncorresponds to the intrinsic probability $q$ and the data is the number $K$ of\noccurrences of the outcome of interest, so $p(a|d)=p(q|K,N)$. Then the posterior is of the following form:\n\\begin{equation*}\\boxed{p(q|K,N))\\propto q^K(1-q)^{N-K}\n}\\end{equation*}\\\\\nThis function is a  \\textbf{Beta-distribution}, which has the range$x\\in [0,1]$ and the\nnormalized distribution reads.%8_12\n \\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{8_12.png}\n\\end{figure}\nMean and variance\ncan be determined by means of the beta function.\nIt also enters the normalization of the beta distribution.\nIn case of a Bernoulli experiment the conjugate prior is therefore a Beta\ndistribution.\\\\\n\nFinally, we want to mention the  \\textbf{Gaussian distribution}, which we have already\nencountered several times. The Gaussian is of central importance for the\ndescription of experimental noise and the range of the random variable in\nthe one-dimensional case is the entire real axis. The normalized Gaussian has a mean and a variance which is given by the following expressions.\\\\%8_13\n \\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{8_13.png}\n\\end{figure}\n\\textit{See the Pluto notebook about popular distributions and study the possible\nshapes that emerge by varying the parameters.}\\\\\n\n\\fbox{\\parbox{\\linewidth}{\\textbf{Question 8.} Match the distributions: \\{Gauss, Gamma, Beta\\}\\\\\nThe domain of the .............. distribution is $x\\in[0,1]$, as it describes the probability of a probability.\\\\\nThe ......... distribution is the conjugate prior of a Poisson Likelihood.\\\\\nThe .......... distribution is parametrized by mean and variance.\n}}\n\\\\\n\n\\section*{Benford's law}\nLyra in the adventure also mentioned a very interesting discovery that \\textit{the\nleading digits of large numbers form a pattern} no matter what is considered: %8_14\n \\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{8_14.png}\n\\end{figure}\nFor the amount of collected shells, bottles, coloured stones per day, the leading numbers all behave the same and\nthey are  \\textbf{not} uniformly distributed. This is in contradiction to the principle\nof indifference.\\\\\nThis phenomenon has to do with  \\textbf{scale invariances}. We have seen before that\nthe pdf of scale invariant quantities $x$ is given by Jeffrey’s prior $p(x)\\propto \\frac 12$.\nPut differently the pdf for log($x$) is uniform, so for $y=\\log_{10}(x)\\rightarrow p(y)= \\text{const}$.\nIf you recall the intervals on logarithmic axes you may have noticed that the\ninterval sizes \\textit{decrease} from 1 to 9. %\nLet’s consider numbers x between 1 and 9.99999$\\ldots$\n\nThe leading digit corresponds to the interval $x \\in [1,2)$.\nThen the probability is $P_1\\propto \\int_1^2\\frac{\\text{d}x}{x}\\ln(2)-\\ln(1)$.\nIn general, the probability that the leading digit has the value $I$ is proportional to $\\log(I+1)-\\log(I)$.\nWith the correct normalization for all possible digits 1 up to 9 we have the probability that the leading digit is $I$ given by $\\log_{10}(I+1)-\\log_{10}(I)$\nThis distribution is depicted in the figure.\\\\%8_15\n \\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{8_15.png}\n\\end{figure}\n\nThe same result is obtained if the numbers are in the interval 10 to 99.9999\nor a 100 to 999.999 and so on.\nActually, the same law holds true also for \\textit{counting experiments when the\nnumbers vary over many orders of magnitude}. Also in this case the probability mass function is \\textit{uniform on a logarithmic scale} or  \\textbf{log-uniform} as it is\nsometimes called.\\\\\n\n\\fbox{\\parbox{\\linewidth}{\\textbf{Question 9.} Which of the following variables could be scale invariant?\\\\\na) Rain drops per day/km$^2$\\\\\nb) The results of repeated dice throws, using a 100 faced die\\\\\nc) The number of sand grains in your shoes\n}}\n\\\\\n\n\\textit{You will find a Pluto notebook to perform random experiments with log-uniform distributions.}\\\\\n\n\nThis concludes lesson 8. We have learned about continuous variables and\nhow to assign prior probabilities using the principle of transformation invariance or the maximum entropy principle. We have discussed Bertrand's paradox and know now why Benford’s law\ndescribes the leading digit of counting lists and measurement tables.\nCheck out the interactive Pluto notebooks to solve the lighthouse problem,\nto do your own Benford computer experiments, and to experiment with\nvarious popular distributions. Feel free to ask questions in the forum and feel encouraged to test your knowledge in the quiz.\n\n\\vspace{2cm}\n\\begin{minipage}[t]{1\\textwidth}\n\t\\raggedleft\n\t\\centering\n\t\\includegraphics[width = 0.20\\textwidth]{CC-BY_icon}\n\t\\vspace{0.2cm}\n\t\n\t\\centering\n\t{\\large ITPCP, TU Graz} \\\\\n\thttps://creativecommons.org/licenses/by/4.0/legalcode\n\\end{minipage}\n\\end{document}", "meta": {"hexsha": "03137b9a2a26341bc768e63d2f923fac0eac39c6", "size": 29202, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "transcripts/tex-files/Lection_8.tex", "max_stars_repo_name": "moserjo/bayes-imoox", "max_stars_repo_head_hexsha": "144bde64410b7e740efa28c82b5e7dfe66885141", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-03-19T04:40:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-30T14:12:16.000Z", "max_issues_repo_path": "transcripts/tex-files/Lection_8.tex", "max_issues_repo_name": "moserjo/bayes-imoox", "max_issues_repo_head_hexsha": "144bde64410b7e740efa28c82b5e7dfe66885141", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-02-20T10:51:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-26T13:57:05.000Z", "max_forks_repo_path": "transcripts/tex-files/Lection_8.tex", "max_forks_repo_name": "moserjo/bayes-imoox", "max_forks_repo_head_hexsha": "144bde64410b7e740efa28c82b5e7dfe66885141", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-19T18:14:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-27T07:07:35.000Z", "avg_line_length": 57.4842519685, "max_line_length": 322, "alphanum_fraction": 0.7527224163, "num_tokens": 8051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.3443218050191247}}
{"text": "\\documentclass[10pt,fleqn]{article}\n\\usepackage{amsmath}\n\\usepackage{cancel}\n\\usepackage[letterpaper, landscape, margin=1in]{geometry}\n\n\\setlength{\\parindent}{0pt}\n\n\n\\begin{document}\n\n\\section{Isotropic visco-acoustic constant density second order self-adjoint system}\nJohn Washbourne, Ken Bube\\\\\nSeptember 20, 2013\n\n\n\\section{Introduction}\nThis note shows the derivation of \\textit{time update equations} and the linearization \nfor the isotropic constant density self-adjoint system. We implement attenuation with a \nmonochromatic approximation to Maxwell bodies, and use this attenuation model to \nimplement zero outgoing absorbing boundary conditions on the exterior of the modeling \ndomain.\n\\vspace{10pt}\n\nThe time update equations are used to advance solutions in time, expressing the pressure\nwavefield at time $p_{(t + \\Delta)}$ as a function of $p_{(t - \\Delta)}$ and $p_{(t)}$.\n\n\\subsection{Symbols}\n\\begin{center}\n\t\\begin{tabular}{ll}                                                                      \\\\[-10pt]\n\t\t$\\partial_t$    & $\\displaystyle \\frac{\\partial }{\\partial t}$            \\\\[10pt]\n\t\t$\\nabla p $     & Laplacian: $ \\left(\n\t\t\t\\displaystyle \\frac{\\partial^2 }{\\partial x^2} +\n\t\t\t\\displaystyle \\frac{\\partial^2 }{\\partial y^2} +\n\t\t\t\\displaystyle \\frac{\\partial^2 }{\\partial z^2} \\right) p $                \\\\[15pt]\n\t\t$\\Delta$        & Temporal sampling rate                                  \\\\[10pt]\n\t\t$\\omega$        & reference frequency for attenuation                     \\\\[10pt]\n\t\t$Q$             & attenuation at frequency $\\omega$                       \\\\[10pt]\n\t\t$P$             & Pressure wavefields                                     \\\\[10pt]\n\t\t$S(x,y,z,t)$    & Pressure source term                                    \\\\[10pt]\n\t\t$b$             & buoyancy = $\\displaystyle 1/\\rho $ (reciprocal density) \\\\[10pt]\n\t\t$ \\{\\ V_p\\ \\} $ & Material parameters                                     \\\\[10pt]\n\t\\end{tabular}\n\\end{center}\n\n\\newpage\n\\subsection{Modeling system}\nEquation \\ref{eq:system} shows the modeling system with absorbing boundaries implemented \nusing amplitude only (dissipation only, no dispersion) Q. \\vspace{10pt}\n\nWe apply the time derivative in the term $\\displaystyle \\frac{\\omega}{Q} \\partial_t p$ \nusing a backward one-sided numerical difference. We tested both forward one-sided and \ncentered difference alternatives and found them to be less stable.\n\n\\begin{equation}\n\t\\frac{1}{v^2} \\left( \\partial_t^2 p + \\frac{\\omega}{Q} \\partial_t p \\right) = \\nabla p + S\n\t\\label{eq:system}\n\\end{equation}\n\n\\section{Time update equations}\n\n\\subsection{Time update numerical difference formulas, first and second order}\n\\begin{equation}\n\t\\partial_t p = \\frac{1}{\\Delta} \\left[ p_{(t)} - p_{(t - \\Delta)} \\right]\n\t\\label{eq:diff1}\n\\end{equation}\n\n\\begin{equation}\n\t\\begin{aligned}\n\t\t\\partial_t^2 p & = \\frac{1}{\\Delta^2} \\left[ p_{(t+\\Delta)} - 2 p_{(t)} + p_{(t - \\Delta)} \\right] \\\\[10pt]\n\t\tp_{(t+\\Delta)} & = \\Delta^2 \\partial_t^2 p + 2 p_{(t)} - p_{(t - \\Delta)}\n\t\\end{aligned}\n\t\\label{eq:diff2}\n\\end{equation}\n\n\\subsection{Rearrange equation \\ref{eq:system} for $\\partial_t^2 p$}\n\\begin{equation}\n\t\\partial_t^2 p = v^2 \\left( \\nabla p + S \\right) - \\frac{\\omega}{Q} \\partial_t p\n\\end{equation}\n\n\\subsection{Apply equations \\ref{eq:diff1} and \\ref{eq:diff2}, and rearrange}\n\\begin{equation}\n\tp_{(t+\\Delta)} = \\Delta^2 v^2 \\left( \\nabla p + S \\right) - \\Delta \\frac{\\omega}{Q} \\left[ p_{(t)} - p_{(t - \\Delta)} \\right]\n\t+ 2 p_{(t)} - p_{(t - \\Delta)}\n\\end{equation}\n\n\\newpage\n\\section{Linearization and Born modeling equation}\n\n\\subsection{Nonlinear modeling equation}\n\\begin{equation}\n\t\\frac{1}{v^2} \\left( \\partial_t^2 p + \\frac{\\omega}{Q} \\partial_t p \\right) = \\nabla p + S\n\\end{equation}\n\n\\subsection{Taylor expand $\\displaystyle \\frac{1}{v^2} \\rightarrow \\left( \\frac{1}{v_0^2} - \\frac{2}{v_0^3} \\delta v \\right) $\n\tand replace $\\displaystyle p \\rightarrow \\displaystyle (p_0 + \\delta p)$}\n\\begin{equation}\n\t\\left( \\frac{1}{v_0^2} - \\frac{2}{v_0^3} \\delta v \\right) \\left( \\partial_t^2 p_0 + \\partial_t^2 \\delta p +\n\t\\frac{\\omega}{Q} \\partial_t p_0 + \\frac{\\omega}{Q} \\partial_t \\delta p \\right) =\n\t\\nabla p_0 + \\nabla \\delta p + S\n\\end{equation}\n\n\\subsection{Expand}\n\\begin{equation}\n\t\\frac{1}{v_0^2} \\partial_t^2 p_0\n\t+ \\frac{1}{v_0^2} \\partial_t^2 \\delta p\n\t+ \\frac{1}{v_0^2} \\frac{\\omega}{Q} \\partial_t p_0\n\t+ \\frac{1}{v_0^2} \\frac{\\omega}{Q} \\partial_t \\delta p\n\t- \\frac{2}{v_0^3} \\delta v \\partial_t^2 p_0\n\t- \\frac{2}{v_0^3} \\delta v \\partial_t^2 \\delta p\n\t- \\frac{2}{v_0^3} \\delta v \\frac{\\omega}{Q} \\partial_t p_0\n\t- \\frac{2}{v_0^3} \\delta v \\frac{\\omega}{Q} \\partial_t \\delta p\n\t= \\nabla p_0 + \\nabla \\delta p + S\n\\end{equation}\n\n\\subsection{Cancel reference terms}\n\\begin{equation}\n\t\\cancel{ \\frac{1}{v_0^2} \\partial_t^2 p_0 }\n\t+ \\frac{1}{v_0^2} \\partial_t^2 \\delta p\n\t+ \\cancel{ \\frac{1}{v_0^2} \\frac{\\omega}{Q} \\partial_t p_0 }\n\t+ \\frac{1}{v_0^2} \\frac{\\omega}{Q} \\partial_t \\delta p\n\t- \\frac{2}{v_0^3} \\delta v \\partial_t^2 p_0\n\t- \\frac{2}{v_0^3} \\delta v \\partial_t^2 \\delta p\n\t- \\frac{2}{v_0^3} \\delta v \\frac{\\omega}{Q} \\partial_t p_0\n\t- \\frac{2}{v_0^3} \\delta v \\frac{\\omega}{Q} \\partial_t \\delta p\n\t= \\cancel{ \\nabla p_0 } + \\nabla \\delta p + \\cancel{ S }\n\\end{equation}\n\n\\subsection{Zero terms second order in perturbations $\\delta p,\\delta v$ }\n\\begin{equation}\n\t\\frac{1}{v_0^2} \\partial_t^2 \\delta p\n\t+ \\frac{1}{v_0^2} \\frac{\\omega}{Q} \\partial_t \\delta p\n\t- \\frac{2}{v_0^3} \\delta v \\partial_t^2 p_0\n\t- \\cancel{ \\frac{2}{v_0^3} \\delta v \\partial_t^2 \\delta p }\n\t- \\frac{2}{v_0^3} \\delta v \\frac{\\omega}{Q} \\partial_t p_0\n\t- \\cancel{ \\frac{2}{v_0^3} \\delta v \\frac{\\omega}{Q} \\partial_t \\delta p }\n\t= \\nabla \\delta p\n\\end{equation}\n\n\\subsection{Rearrange for the Born modeling equation}\n\\begin{equation}\n\t\\begin{aligned}\n\t\t\\frac{1}{v_0^2} \\left( \\partial_t^2 \\delta p + \\frac{\\omega}{Q} \\partial_t \\delta p \\right)\n\t\t & = \\nabla \\delta p + \\frac{2}{v_0^3} \\delta v \\left( \\partial_t^2 p_0 + \\frac{\\omega}{Q} \\partial_t p_0 \\right) \\\\[10pt]\n\t\t & = \\nabla \\delta p + \\frac{2}{v_0^3} \\delta v \\left( v_0^2 \\nabla p_0 + v_0^2 S \\right)                         \\\\[10pt]\n\t\\end{aligned}\n\\end{equation}\n\nNote: it is procedurally simplest to serialize the quantity \n$\\displaystyle \\left( v_0^2 \\nabla p_0 + v_0^2 S \\right)$ when we perform nonlinear \nforward modeling, and use that field as the Born source for the linearized forward and \nadjoint operators.\n\\end{document}\n", "meta": {"hexsha": "4f69247b822816e25ad90459fa3023b566b32191", "size": 6436, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/latex_notes/IsotropicAcousticQ.tex", "max_stars_repo_name": "ChevronETC/WaveFD", "max_stars_repo_head_hexsha": "555cf24fc70835e789a8126a1d9866e25de4a8d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-10-28T16:59:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-25T21:55:17.000Z", "max_issues_repo_path": "docs/latex_notes/IsotropicAcousticQ.tex", "max_issues_repo_name": "ChevronETC/WaveFD", "max_issues_repo_head_hexsha": "555cf24fc70835e789a8126a1d9866e25de4a8d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2020-10-06T03:03:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T23:29:11.000Z", "max_forks_repo_path": "docs/latex_notes/IsotropicAcousticQ.tex", "max_forks_repo_name": "ChevronETC/WaveFD", "max_forks_repo_head_hexsha": "555cf24fc70835e789a8126a1d9866e25de4a8d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-26T15:19:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-26T15:19:51.000Z", "avg_line_length": 42.0653594771, "max_line_length": 126, "alphanum_fraction": 0.6390615289, "num_tokens": 2298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.34432179571675076}}
{"text": "%!TEX root = paper.tex\n%\n% Riemann\n%\n\n\\subsection{Riemann: A Community-Driven Collection of Approximate Riemann\nSolvers}\\label{sec:riemann}\n\nThe methods implemented in \\clawpack, and all modern Godunov-type\nmethods for hyperbolic PDEs, are based on the solution of Riemann\nproblems as discussed in \\cref{sec:hyp}.  Whereas most existing codes\nfor hyperbolic PDEs use Riemann solvers to compute fluxes, \\clawpack\nRiemann solvers instead compute the waves (or discontinuities) that\nmake up the Riemann solution.  In the unsplit algorithm, \\clawpack\nalso makes use of {\\em transverse} Riemann solvers, responsible for\ncomputing transport between cells that are only corner (in 2d) or edge\n(in 3d) adjacent.\n\nFor nonlinear systems, the exact solution of the Riemann problem is\ncomputationally costly and may involve both discontinuities (shocks and contact\nwaves) and rarefactions.  It is almost always preferable to employ inexact\nRiemann solvers that approximate the solution using discontinuities only, with\nan appropriate entropy condition.  The solvers available in \\clawpack are\nall approximate solvers, although one could easily implement their own exact\nsolver and make it available in the format needed by \\clawpack routines.\n\nA common feature in all packages in the \\clawpack suite is the\nuse of a standard interface for Fortran Riemann solver routines.  This ensures that new\nsolvers or solver improvements developed for one package can immediately\nbe used by all packages.  To further facilitate this sharing and to avoid\nduplication, Riemann solvers are (with rare exceptions) not maintained under\nthe other packages but are collected in a single repository named\n\\texttt{riemann}.\nUsers who develop new solvers for \\clawpack are encouraged to submit them to the\nRiemann repository.\n\nIn the Fortran-based packages (Classic, AMRClaw, and GeoClaw) the Riemann solver\nis selected at compile-time by modifying a problem-specific Makefile. In\n\\pyclaw, the Riemann solver to be used is selected at run-time.  This is made\npossible by compiling all of the Riemann solvers (when \\pyclaw is installed) and\ngenerating Python wrappers with \\texttt{f2py}.  For \\pyclaw, \\texttt{riemann}\nalso\nprovides metadata (such as the number of equations, the number of waves,\nand the names of the conserved quantities) for each solver so that setup is\nmade more transparent.\n", "meta": {"hexsha": "5fe7a055a7d36c28a1f60d7bf5321887c0faa877", "size": 2361, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "papers/clawpack-5x/riemann.tex", "max_stars_repo_name": "kbarnhart/doc", "max_stars_repo_head_hexsha": "ede1e86c883ad9336f6334c967a89212d2b9cdc7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-01-08T12:17:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-15T21:17:44.000Z", "max_issues_repo_path": "papers/clawpack-5x/riemann.tex", "max_issues_repo_name": "kbarnhart/doc", "max_issues_repo_head_hexsha": "ede1e86c883ad9336f6334c967a89212d2b9cdc7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 76, "max_issues_repo_issues_event_min_datetime": "2015-01-31T20:22:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-05T16:55:53.000Z", "max_forks_repo_path": "papers/clawpack-5x/riemann.tex", "max_forks_repo_name": "kbarnhart/doc", "max_forks_repo_head_hexsha": "ede1e86c883ad9336f6334c967a89212d2b9cdc7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-03-01T08:26:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-06T02:59:13.000Z", "avg_line_length": 51.3260869565, "max_line_length": 87, "alphanum_fraction": 0.8085556967, "num_tokens": 591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.3443151021119291}}
{"text": "\\section{Results}\n\\label{Resul}\n\nThe following Section summarises the work by presenting the obtained results. Comments on the goodness of such results are also present, together with possible future developments. \nThe popularity distribution computed through Eq. (\\ref{Popc}) shows a gaussian-like distribution centred in 0 (Fig. \\ref{PopDist}), meaning that on average comments are neutral, with lateral tails of comments with strong polarity, both positive and negative. Recommendations play a small role, because of some outliers causing the normalised recommendation count to be quite a small number. It is fundamental for this distribution to be unbiased as it will be used to estimate controversy. \n\n\\begin{figure}[b]\n\\centering\n    \\begin{subfigure}{0.5\\tw}\n    \\centering\n    \\includegraphics[height=4.5cm]{Pictures/PopularityDist.pdf}\n    \\caption{Popularity distribution}\n    \\label{PopDist}\n    \\end{subfigure}%\n\\hfill\n    \\begin{subfigure}{0.5\\tw}\n    \\centering\n    \\includegraphics[height=4.5cm]{Pictures/articleScoreDist.pdf}\n    \\caption{Article score distribution.}\n    \\label{AScore}\n    \\end{subfigure}\n\\caption{Preliminary distributions.}\n\\end{figure}\n\nThe article score distribution shows a similar behaviour; it is reported in Fig. \\ref{AScore} even though it will not be included in further analyses. Again, the article score calculated with Eq. \\ref{ASeq} shows a quite symmetrical distribution, meaning that the estimator is consistent and the articles are equally distributed among the polarity spectrum.\n\n\\subsection{Strategy 1 (linear)}\n\\label{Strategy1}\nThe first strategy to estimate controversy in news articles (Eq. \\ref{Str1}) was to multiply the number of comments related to each article with the IQR of the popularity distribution for such comments (labelled as \\textit{debate}). This calculation lead to an index of controversy peaked near 0. Furthermore, the controversy distribution looks very similar to the comment number distribution (see Fig. \\ref{Str1Dist}). This suggests that popularity and controversy are strongly correlated, while debate plays an insignificant role in the compute. \n\n\\begin{figure}[h]\n\\centering\n\\includegraphics[width=\\tw]{Pictures/Strat1Dist.pdf}\n\\caption{Popularity, Debate and Controversy distributions for Strategy 1}\n\\label{Str1Dist}\n\\centering\n\\includegraphics[width=\\tw]{Pictures/Strat1Corr.pdf}\n\\caption{Correlation plots for Strategy 1.}\n\\label{Str1Corr}\n\\end{figure}\n\nTo corroborate this hypothesis, the correlation scatter plots for the three variables were built, and Fig. \\ref{Str1Corr} shows a very strong linear correlation between popularity and controversy. This correlation rows against the thesis of the project, which is trying to differentiate the so-called \"hot topics\" from the most controversial ones. For this reason, another strategy was implemented to see if some other definition of controversy can detach more efficiently from the concept of popularity.\n\nTo go deeper into the analysis, the controversy scores for each articles were averaged among articles of the same section. This grouping was made to see if any article section is more controversial than others. Unfortunately, Strategy 1 did not prove to be useful in this case, as the most controversial topics are also the most popular one. Figure \\ref{RG1} shows how, for each section, the controversy and the popularity score look very similar to each other (after proper normalisation).\n\n\\begin{figure}[htb]\n\\centering\n\\includegraphics[width=\\tw]{Pictures/Strat1SN.pdf}\n\\caption{Most controversial sections for Strategy 1}\n\\label{RG1}\n\\centering\n\\includegraphics[width=\\tw]{Pictures/Strat1ND.pdf}\n\\caption{Most controversial desks for Strategy 1}\n\\label{RG1nd}\n\\end{figure}\n\nAfter that, articles were also grouped by the \"new desk\" index, to see if there is any category that stands out as the most controversial. Again, results (Fig. \\ref{RG1nd}) indicate a high similarity between controversy and popularity, with \"National\" desk as the most popular desk.\n\n%\\begin{figure}[hbt]\n\n%\\end{figure}\n\n\\subsection{Strategy 2 (log)}\n\nStrategy 2 consisted on applying the natural logarithm to the number of comments under each article, in order to dampen the strong dependencies between the former and controversy. Thanks to this new strategy, results change significantly, and they are reported in the same format as Section \\ref{Strategy1}.\nFirst of all, the popularity distribution (hence the controversy index) are represented in their new shapes, while the debate distribution obviously does not change (Fig. \\ref{Str2Dist}).\nBy looking at the correlation plots, it can be seen that the strong linear correlation between the two distributions has been removed (Fig. \\ref{Str2Corr}). The problem is now that distributions are not smooth for small values of popularity, because of the logarithm. However, the distribution of controversy looks smoother and more balanced compared to the one adopted in Strategy 1.\n\n\\begin{figure}[h]\n\\centering\n\\includegraphics[width=\\tw]{Pictures/Strat2Dist.pdf}\n\\caption{Popularity, Debate and Controversy distributions for Strategy 2.}\n\\label{Str2Dist}\n\\end{figure}\n\n\n\\begin{figure}[h]\n\\centering\n\\includegraphics[width=\\tw]{Pictures/Strat2Corr.pdf}\n\\caption{Correlation plots for Strategy 2.}\n\\label{Str2Corr}\n\\end{figure}\n\n\nIf we look at the averages on categories (Fig. \\ref{RG2} and \\ref{RG2nd}), it can be seen that popularity and controversy are now two very different quantities. The bar plots both for section name and desk show different behaviour between the two data series. However, the problem with Strategy 2 is that the categories labelled as \"highly controversial\" are quite unexpected, such as Cycling and Entertainment. On the other hand, controversial categories in Strategy 1 were Politics, Editorials and Middle East (categories one would expect to be controversial).\n\n\\begin{figure}[h]\n\\centering\n\\includegraphics[width=\\tw]{Pictures/Strat2SN.pdf}\n\\caption{Most controversial sections for Strategy 2}\n\\label{RG2}\n\\end{figure}\n\n\\begin{figure}[h]\n\\centering\n\\includegraphics[width=\\tw]{Pictures/Strat2ND.pdf}\n\\caption{Most controversial desks for Strategy 2}\n\\label{RG2nd}\n\\end{figure}\n\n\n\\subsection{Keyword extraction}\nLastly, a feature extraction was performed to check which words were common in comments related to the most controversial articles (top 10\\%). A corpus vectorisation was performed via a {\\tt TfidfVectorizer}, and then a $\\chi2$ analysis was invoked to select words with higher frequency. Since TF-IDF tends to boost the score of words which are very uncommon in the corpus, among the \"top controversial words\" there were many nonsensical words that occurred only once in the whole corpus, probably originated by typos of the comment authors. For this reason, only the words with a match in the AFINN dictionary were kept. Figure \\ref{TopWords} depicts the words selected by the $\\chi^2$ analysis. An ample fraction of the word list is made of polarised words, indicating that polarity is at the basis of controversy.\n\n\\begin{figure}[h!]\n\\centering\n\\includegraphics[width=\\linewidth]{Pictures/TopWs.png}\n\\caption{Most controversial words in the comment dataset.}\n\\label{TopWords}\n\\end{figure}\n\n\\section{Conclusions}\n\nThe aim of this project was to define controversy in news articles by analysing the comments below the articles. Two different strategies were adopted, each one with its pros and cons.\nStrategy 1 defined controversy through a linear relationship; it was the one who guaranteed the results with most common sense (Politics and Middle East were among the top categories), but it failed to detach from popularity.\nOn the other hand, strategy 2 guaranteed a significant shift from popularity and removed linear correlations, but the results leave us with some doubts.\nIn any case, it was proved that in either case polarity in the comments is the key to analyse controversy. \nSome future developments to this work could be:\n\\begin{itemize}\n\\item Perform aspect-based sentiment analysis to go deeper into the comments, and analyse which aspects within a given comment generated controversy\n\\item Using topic modelling, extract the article section name from the comments, since nearly half of the articles in the dataset were provided with \"Unknown\" section name\n\\item Demonstrate the robustness of this controversy estimator by changing the lexicon (for example, WordNet could be used instead of AFINN) and look for similar behaviour of the controversy distribution\n\\item Find another strategy to remove correlation between popularity and controversy without the need to apply a logarithm\n\\item Train a classifier able to predict controversy in other datasets of news and comments\n\\end{itemize}", "meta": {"hexsha": "de83e5ead316f582e995674a5082c012ab6b4acf", "size": 8731, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Report/Results.tex", "max_stars_repo_name": "andreasala98/NYMines", "max_stars_repo_head_hexsha": "3e9eb3da22f815d3179f10ff98b9887a2a4f1360", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Report/Results.tex", "max_issues_repo_name": "andreasala98/NYMines", "max_issues_repo_head_hexsha": "3e9eb3da22f815d3179f10ff98b9887a2a4f1360", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Report/Results.tex", "max_forks_repo_name": "andreasala98/NYMines", "max_forks_repo_head_hexsha": "3e9eb3da22f815d3179f10ff98b9887a2a4f1360", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 69.848, "max_line_length": 816, "alphanum_fraction": 0.7991066315, "num_tokens": 1959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.344315093906683}}
{"text": "\\documentclass[a4paper,12pt]{article}\n\n% Font\n\\usepackage[T1]{fontenc}\n\\usepackage{gentium}\n\n% Math packages\n\\usepackage{amsmath}\n\\usepackage{amsfonts}\n\\usepackage{amssymb}\n\\usepackage{amsthm}\n\\usepackage{bm}\n\n% Define symbol shortcuts\n\\newcommand{\\cc}{\\mathcal{C}}\n\\newcommand{\\dd}{\\mathcal{D}}\n\\newcommand{\\hh}{\\mathcal{H}}\n\\newcommand{\\xx}{{\\bm x}}\n\\newcommand{\\yy}{{\\bm y}}\n\n% Math environment\n\\newtheorem*{thm}{Theorem}\n\n% Better list management:\n% - vertical spacing in lists\n% - items in lists start with dash not bullet point.\n\\usepackage{enumitem}\n\\setlist{label=\\textemdash,\n  itemsep=0pt, topsep=3pt, partopsep=0pt}\n\n% Include graphics\n\\usepackage{graphicx}\n\\usepackage{subcaption}\n\n% Page format \n\\usepackage[top=2cm,left=2cm,right=2cm,bottom=2cm]{geometry}\n\n\\begin{document}\n%%% HEADER\n\\raisebox{0.6in}[0in]{\\makebox[\\textwidth][r]{\\it Unproofed version }}\n\\vspace{-0.7in}\n\n\\begin{center}\n\\bf\\large MA2823: Foundations of Machine Learning \\\\\nChapter 6: Regularized Linear Regression\n\\end{center}\n\n\\noindent\nLecturer: Chlo\\'e-Agathe Azencott   \n\\hfill\nScribe: Adrien Galamez \\\\\n\\null \\hfill Paul Magon de la Villehuchet\n\n\n\\noindent\n\\rule{\\textwidth}{1pt}\n\n\\medskip\n\nIn this chapter we will see:\n\\begin{itemize}\n\\item what is regularization;\n\\item how to use regularization as a means to control model complexity;\n\\item several forms of regularizing linear regression models.\n\\end{itemize}\n\n\\section{Regression setting}\n\\subsection{Large $p$, small $n$}\nThis section is a reminder of the context in which we work. We consider a dataset that has $p$ features and $n$ samples. Thus, we're working with a data matrix $X$ that have $n$ rows and $p$ columns. The outcome vector $y$ describes the quantity we want to predict. The goal of linear regression model is to approximate $y$ as a linear combination of $X$.\n\\begin{figure}[!h]\n\\centerline{\n\\includegraphics[scale = 0.3]{figures/RegressionSettings.png}}\n\\caption{Figure illustrating the dimensions of the data matrix and the outcome vector.}\n\\label{DataMatrix}\n\\end{figure}\n\nOn the Figure \\ref{DataMatrix}, we can see that the data matrix is taller than it is wide ($p < n$). This is a  common shape. But, conversed settings can also appear. \n\nThis configuration is called large $p$, small $n$. The data matrix is wider than it is tall. This is the kind of settings we have in genetics and neuroimaging: we have many more descriptors than we have data points. For instance, in genetics, a data set can gather informations for thousands of genes as this information is easy to access. Yet, as each row holds data gathered on a patient, we have at best hundreds of patients. Thus, we have a wide but not tall data matrix. In neuroimaging, brain images are big objets, typically thousands pixels or voxels (3D images). Yet, as brainscans are costly to obtain, we repeat the process on thousands of patient only. Thus, we have more features than observations. In this configuration, regularization is usefull.\n\n\\subsection{Linear regression}\n\\subsubsection{Pro and cons of least-squares fit}\nLinear regression is aimed at approximating $y$ as a linear combination of $X$. In the previous chapter, we said that, if we're doing a least-squares fit (which is equivalent to Maximum Likelihood estimation under the assumption of Gaussian noise), we obtain this solution\n\\begin{equation}\n\\hat{\\beta} = \\arg\\min_{\\beta} (y-X\\beta)^{T} (y-X\\beta) = (X^T X)^{-1} X^T y.\n\\label{LR}\n\\end{equation}\nThis solution is uniquely defined when $X^T X$ is invertible, hence when $X$ has a full column rank. As $X$ is an $n \\times p$ matrix, if $p$ is larger than $n$ (as in the large $p$, small $n$ configuration), $X$ can not be inverted.\n\nThis fit has several advantages.\n\\begin{itemize}\n\\item The predicted vector $\\hat{\\beta}$ is unbiased ($\\mathbb{E}[\\hat{\\beta}]= \\beta$).\n\\item If we're restricting to unbiased estimators, minimum mean squared error implies minimum variance.\n\\item This fit gives an explicit solution (Equation \\ref{LR}).\n\\item If $n \\gg p$, the computational time is linear in the number of samples. Indeed, the computational time is $O(\\underbrace{np^2}_{\\text{compute } X^T X}+\\underbrace{p^3}_{\\text{invert } X^T X})$. \n\\end{itemize}\n\nYet, this fit has also some drawbacks.\n\\begin{itemize}\n\\item Correlated variable leads to high variance of the estimator.\n\\item Prediction error increases linearly as a function of $p$.\n\\item The solution is hard to interpret when $p$ is large as shown in the section \\ref{LargeP}.\n\\end{itemize}\n\n\\subsubsection{When $p$ in larger than $n$}\n\\label{LargeP}\nWhen $X^T X$ is not invertible, we still have ways to find $\\hat{\\beta}$. In this case, we can use the pseudo-inverse of $X$. We can also use numerical methods to solve a linear system of $p$ equations such as gradient descent (aimed at minimizing a convexe function), Gaussian elimination or LU decomposition.\nOn the Figure \\ref{LRPseudoInverse}, we can compare the predicted coefficient (thanks to a linear regression using pseudo-inverse) and the true coefficient when $p = 1000$ and $n = 10$. So, we're in the case of the large $p$, small $n$ configuration. In fact, the outcome vector $y$ was created by a linear combination of the data-matrix $X$ using the weights shown on the left hand graph. \n\nThe objectif was to retrieve those weights using a linear regression on the vectors $X$ and $y$. $10$ causal features were highlighted in orange on both graphs. A good approximation would be to use only those $10$ causal features. Nevertheless, as the right hand graph shows, the linear regression gives coefficients that have approximately the same weight. The causal features are lost entirely in the noise created by the others coefficients. Information has been lost. Regularization is a way of addressing this issue.\n\n\\begin{figure}[!h]\n\\centerline{\n\\includegraphics[scale = 0.3]{Figures/linear_regression_pseudoinverse.png}}\n\\caption{Example of weights obtained from linear regression when $X$ is not invertible, thus using the pseudo-inverse. On the left, the graph is showing the true coefficients of the vector $\\beta$. On the right, the graph presents the predicted coefficients of the vector $\\hat{\\beta}$ obtained from linear regression.}\n\\label{LRPseudoInverse}\n\\end{figure}\n\n\\section{Regularization}\nThe Figure \\ref{LRPseudoInverse} showed that the linear regression used all the features available to predict the outcome vector $y$. Yet, all the weights are very small. Thus, the solution is hard to interpret. Usually, we prefer having a small subset of features with strong weights. This is one of the advantages of regularization. Moreover, the more we have variables in our model, the more complex our model is. And, the more complex our model is, the more chances we have to overfit our data. Thus, we want to find a way to simplify our model.\n\n So, instead of minimizing only the sum of squared error, the idea of regularization is to minimize\n \\[ \\text{Sum of squared error} + \\lambda \\text{ prenalty on model complexity}.\\]\nThus, when using regularization, the estimator is biased (if $\\lambda \\not = 0$). Yet, because the model will be less complex, we'll have a smaller variance. We're willing to accept a biased estimator in exchange for smaller variance. So, there's a tradeoff to make between bias and variance. $\\lambda$ can be set by cross-validation. \\label{CVlambda}\n\nThis method is also called \\emph{shrinkage} in the context of linear regression. Indeed, this is going to shrink the weights of the model. Thus, the final model is simpler.\n\nThe following sections are presenting examples of regularization technique.\n\n\\subsection{Ridge regression}\n\\subsubsection{Ridge estimator}\nInstead of minimizing our sum of squared error, ridge regression is aimed at minimizing $||y - X\\beta||_2^2 + \\lambda ||\\beta||_2^2$. Thus, the ridge estimator is given by\n\\[ \\hat{\\beta}_\\text{ridge} = \\arg \\min_\\beta ||y - X\\beta||_2^2 + \\lambda ||\\beta||_2^2. \\]\n\n\\begin{thm} The ridge regression estimator is given by\n\\[ \\hat{\\beta}_\\text{ridge} = (X^T X+ \\lambda I)^{-1} X^T y. \\]\n\\end{thm}\n\n\\begin{proof}\nWe consider the function $f$ defined by\n\\[ f(\\beta) = ||y - X\\beta||_2^2 + \\lambda ||\\beta||_2^2.\\]\nIn order to minimize this function, we take its gradient.\n\\[ \\nabla_{\\beta}f(\\beta) = -2X^T (y-X\\beta) + 2\\lambda \\beta.\\]\nThen, $\\beta_\\text{ridge}$ is defined as $\\nabla_{\\beta}f(\\beta_{\\text{ridge}}) = 0$. Thus,\n\\[ (X^TX+\\lambda I)\\beta_\\text{ridge} = X^T y.\\]\nIf $\\lambda > 0$, $(X^T X + \\lambda I)$ is invertible, then\n\\[ \\hat{\\beta}_\\text{ridge} = (X^T X+ \\lambda I)^{-1} X^T y. \\]\n\\end{proof}\n\n\\subsubsection{Solution path}\n\\label{SectionSolutionPathRR}\nWe've said in section \\ref{CVlambda} that we can find the optimal value of $\\lambda$ by cross-validation. We can compute solution paths (Figure \\ref{SolutionPathRR}) that is a plot showing how the feature coefficient evolves when we decrease the value of $\\lambda$. Indeed, when $\\lambda = 0$, there's no regularization anymore. And, if $\\lambda \\gg 1$, we only want to minimize the model complexity. So, all coefficient are then equal to $0$. Then, on the Figure \\ref{SolutionPathRR}, on the left hand, we start with the model in which all coefficients are equal to zero and we end, on the right hand, with the linear regression without any regularization model.\n\nThe vertical red line shows the value of $\\lambda$ that was obtained by cross-validation. The goal is to choose the value of $\\lambda$ that gives the best generalization on another set of data.\n\\begin{figure}[!h]\n\\centerline{\n\\includegraphics[width = 0.7\\textwidth]{figures/solution_path_ridge_regression.png}}\n\\caption{Ridge regression solution path}\n\\label{SolutionPathRR}\n\\end{figure}\n\n\\subsubsection{Standardization}\nThe goal of this section is to describe what will happen to our model if we multiply our features by a constant.\n\\begin{enumerate}\n\\item \\textbf{Standard linear regression}~: Without any regularization, we multiply, in the data matrix $X$, the column $j$ by a real $c \\not = 0$. So, \n\\[\\forall i \\in [|0;n-1|], x_{ij} \\to c x_{ij}.\\]\nThen, the corresponding weight $\\beta_j$ is going to be divided by $c$.\n\\[ \\beta_j \\to \\frac{1}{c} \\beta_j.\\]\nThus, the weight is different but the solution is similar.\n\\item \\textbf{Ridge regression}~: When we multiply, in the data matrix $X$, the column $j$ by a real $c \\not = 0$, we can't know what will happen because of the penalization term $\\lambda \\beta_j^2$. So, it's important to use standardized feature \\emph{before} regularizing linear regression.\n\\end{enumerate}\n\\subsubsection{Advantages and drawbacks}\nFinally,\n\\begin{enumerate}\n\\item \\textbf{Advantages}~: Ridge regression has several advantages\n\\begin{itemize}\n\\item Correlated variables get similar weights.\n\\item Identical variables get identical weights.\n\\item An analytical solution is provided\n\\end{itemize}\n\\item \\textbf{Drawbacks}~: And it also have drawbacks\n\\begin{itemize}\n\\item Ridge regression shrinks coefficients but does \\emph{not} result in a sparse model. A model is sparse when many coefficient get a weight of $0$. Then, when a model is sparse, many coefficient can be eliminated from the model.\n\\end{itemize} \n\\end{enumerate}\n\n\\subsection{Lasso regression}\n\\subsubsection{Lasso estimator}\nInstead of using the $L^2$ penalty, like the Ridge estimator, the Lasso estimator is based on a $L^1$ penalty. Hence we have to minimize : $||y - X\\beta||_2^2 + \\lambda ||\\beta||_1$.\n\\begin{equation}\n\\hat{\\beta}_\\text{lasso} = \\arg \\min_\\beta ||y - X\\beta||_2^2 + \\lambda ||\\beta||_1.\n\\label{DefLagrange}\n\\end{equation}\n\nUnlike the Ridge estimator, there is no explicit solution. We can however, transform this problem into a quadratic problem.\n\n\\begin{thm} There is a bijection between $\\lambda$ and $t$ such as ${\\beta}_\\text{lasso}$ is solution of the quadratic problem : \n\\begin{equation}\n\\hat{\\beta}_\\text{lasso} = \\arg \\min_\\beta ||y - X\\beta||_2^2 \\quad s.t \\quad ||\\beta||_1\\leq t.\n\\label{DefQuadratic}\n\\end{equation}\n\\end{thm}\n\n\\begin{proof}\nWe consider the functions $f$ and $g$ defined by\n\\[ f(\\beta) = ||y - X\\beta||_2^2.\\]\n\\[ g(\\beta) = ||\\beta||_1 - t.\\]\nFrom (\\ref{DefQuadratic}) to (\\ref{DefLagrange}). Let $H$ be the feasible region, i.e, $\\{ \\beta$ $, g(\\beta) \\leq 0\\}$\n\\[ \\hat{\\beta}_\\text{0} = \\arg \\min_{\\beta \\in H} ||y - X\\beta||_2^2 \\quad.\\]\nTwo cases are possible:\\\\\n\\begin{itemize}\n\\item Case 1 : the unconstrained minimum lies in the feasible region. Problem is solved.\n\\item Case 2 : the unconstrained minimum does not lie in the feasible region. \\\\\nIn this case, the solution is the intersection of the iso-contours of $f$ with the boundary of $H$, as shown in the next figure.\n\\end{itemize}\n~\\\\\n\\begin{figure}[!h]\n\\centerline{\n\\includegraphics[width = 0.7\\textwidth]{figures/sol_lasso.png}}\n\\caption{Solution of Lasso-estimator}\n\\label{SolutionLasso}\n\\end{figure}\n~\\\\\nFurthermore, we know that the gradient of $g(\\beta)$ is orthogonal to the boundary of $H$.\nThe gradient of $f(\\beta)$ is also orthogonal to the iso-contours of $f$.\\\\\nHence, at $\\beta_{0}$, the gradient of $f$ and $g$ are parallel.\\\\\nWe also know that $\\nabla_{\\beta}g(\\beta)$ points towards the unconstrained minimum of $f$ while $\\nabla_{\\beta}f(\\beta)$ points in the opposite direction.\\\\\n~\\\\\n\\begin{figure}[!h]\n\\centerline{\n\\includegraphics[width = 0.7\\textwidth]{figures/sol_lasso2.png}}\n\\caption{Gradients of $f$ and $g$ and solution of Lasso-estimator}\n\\label{SolutionLasso2}\n\\end{figure}\n~\\\\\nWe can conclude from previous results that $\\nabla_{\\beta}f(\\beta) = -\\lambda \\nabla_{\\beta}g(\\beta)$.\\\\\nThe Lagrangian of the Lasso-problem : $L(\\beta) = f(\\beta) + \\lambda g(\\beta)$ is minimized at $\\beta_{0}$. \\\\\n\nFrom (\\ref{DefLagrange}) to (\\ref{DefQuadratic}). Let us fix $\\lambda$ and define $\\beta_*  = \\arg \\min_\\beta f(\\beta) + \\lambda ||\\beta||_1^2$. Let us define $t = ||\\beta_*||_1^2.$\\\\ \nThen, for any $\\beta, f(\\beta_*)+ \\lambda ||\\beta_*||_1^2 \\leq f(\\beta)+\\lambda||\\beta||_1^2$. Hence $f(\\beta_*)\\leq f(\\beta)+\\lambda(||\\beta||_1^2 - t).$\\\\\nUnder the constraint that $||\\beta||_1^2 \\leq t, \\lambda(||\\beta||_1^2 - t) \\leq 0$. Hence $f(\\beta_*) \\leq f(\\beta)$, i.e. $\\beta_* = \\beta_{lasso}$\\\\\n\nThus, the two problems are equivalent.\n\\end{proof}\n\\subsubsection{Solution path}\nAs we did before in Section \\ref{SectionSolutionPathRR} for the Ridge Regression estimator, we can also compute solution paths for the Lasso estimator (Figure \\ref{SolutionPathLasso}). On the left hand of the graph, we start with high values of $\\lambda$ that give very simple models. We move towards lower values of $\\lambda$ that gives more complex models. Yet, there's one difference with the ridge regression solution path. In fact, we see here that our features ``enter the model one by one'': their weight is equal to $0$ for all values of $\\lambda$ lower to a certain $\\lambda_0$. For instance, here, when the model complexity increases, features ``enter'' the model in this order: \\texttt{lcavol}, \\texttt{lweight}, \\texttt{svi}, \\ldots, \\texttt{gleason}. Thus, at every stage, we have a \\emph{sparse model}. For example, on the vertical red line, we have a model with only $5$ parameters that are not null (\\texttt{lcavol}, \\texttt{svi}, \\texttt{lweight}, \\texttt{pgg45}, \\texttt{lbph}).\n\n\\subsubsection{Forward stepwise regression}\nWe just saw that, in the lasso regularization, the features are ``entering'' the model one by one. Then, we can also get the lasso solution by using forward stepwise regression: the model is built sequentially by adding one variable at a time. Then, this a greedy method.\n\\begin{itemize}\n\\item We start with the intercept only.\n\\item At each step, the variable that most improves the fit is added. All variables are tested and the one that gives the better fit is kept.\n\\item We stop when $||\\beta ||_1 \\leq t$.\n\\end{itemize}\n\n\\subsubsection{Least Angle Regression}\nThe computation of the lasso solution is a quadratic problem, and can be tackled by standard algorithms. But, the least angle regression algorithm is a better approach. In the previous section, when a variable and its weight was added in the model, and this weight was never updated. The least angle regression procedure follow the same general scheme, but doesn't add a feature fully into the model. Here, at each step, ``only as much of a variable as needed'' is added. In fact, the coefficient of that feature is increased only until that feature is no longer the one most correlated with the residual $r$. This algorithms can be described as follow\n\\begin{enumerate}\n\\item Standardize the features to have mean zero and unit norm. Start with the residual $r = y - \\bar{y}$ and $\\beta_1, \\ldots, \\beta_p = 0$. The residual is ``what is left to explain from our model''. The perfect model would have a residual that is equal to $0$.\n\\item Find the one feature that explains $r$ the most. In other words, find the feature $x_j$ most correlated with $r$.\n\\item Update the weight $\\beta_j$ until $x_j$ is no longer the one most correlated with $r$: move $\\beta_j$ from $0$ towards in the direction of the sign of its correlation with $y$. In fact, move $\\beta_j$ from $0$ towards its least-squares coefficient $\\langle x_j, r \\rangle$ until some other competitor $x_k$ has as much correlation with the current residual as does $x_j$. So\n\\[ \\beta_j + \\alpha \\frac{1}{\\sum_{i=1}^n (x_j^i)^2} \\sum_{i=1}^n x_j^i r^i \\to \\beta_j,\\]\n\\[ (y - \\bar{y}) - \\beta_j x_j \\to r,\\]\nwhere $\\alpha$ is called the step size.\n\\item Move $\\beta_j$ and $\\beta_k$ in the direction defined by their joint least squares coefficient of the current residual on $\\langle x_j, x_k \\rangle$ until some other competitor $x_l$ has a much correlation with the current residual $r = (y-\\bar{y} - \\beta_j x_j - \\beta_k x_k)$.\n\\item If a non-zero coefficient hits zero, drop its variable from the active set of variables and recompute the current joint least squares direction.\n\\item Continue in this way until all $p$ predictors have been entered.\n\\end{enumerate}\n\n\\begin{figure}[!h]\n\\centerline{\n\\includegraphics[width = 0.7\\textwidth]{figures/solution_path_lasso.png}}\n\\caption{Ridge regression solution path}\n\\label{SolutionPathLasso}\n\\end{figure}\n\n\\subsection{Elastic Net}\n\\subsubsection{Elastic Net estimator}\nThe Elastic Net estimator is a convex combination of Lasso and Ridge. It is defined by :\n\\[ \\hat{\\beta}_\\text{enet} = \\arg \\min_\\beta ||y - X\\beta||_2^2 + \\lambda(\\alpha||\\beta||_2^2 + (1 - \\alpha)||\\beta||_1) \\]\nThe main advantage is to combine both :\n\\begin{itemize}\n\\item It selects variables like the Lasso-estimator. \n\\item It shrinks together correlated and identical variables like the Ridge-estimator\n\\end{itemize}\nOf course, this cames with the cost of having two parameters ($\\lambda$, $\\alpha$) to set instead of one.\n\n\\subsubsection{Comparison of Elastic Net-estimator and Lasso-estimator}\nThe Figure \\ref{Lassoenet} represents results of both Lasso-estimator and Elastic Net-estimator on Leukemia data. We can see that Elastic Net results in more non-zero coefficients than Lasso, but with smaller amplitudes.\n\n\\begin{figure}[!h]\n\\centerline{\n\\includegraphics[width = 0.9\\textwidth]{figures/lassoenet.png}}\n\\caption{Comparison of weights on Lasso-estimator and Elastic Net estimator}\n\\label{Lassoenet}\n\\end{figure}\n\n\\subsection{$L^q$ regression}\n\\subsubsection{$L^q$ estimator}\nThe $L^q$ estimator is a generalization of the Ridge and Lasso estimator : the penalty is based on the $L^q$ norm of $\\beta$.\n\\[||\\beta||_q^q = \\sum_{i = 1}^{n}{\\beta_{i}^q}\\]\nThe $L^q$ estimator is then defined by :\n\\[ \\hat{\\beta}_\\text{$L^q$} = \\arg \\min_\\beta ||y - X\\beta||_2^2 + \\lambda ||\\beta||_q^q. \\]\nWe have the same theorem to transform this problem into a quadratic problem with constraints.\\\\\n\n\\begin{thm} There is a bijection between $\\lambda$ and $t$ such that ${\\beta}_\\text{$L^q$}$ is solution of the quadratic problem : \n\\[ \\hat{\\beta}_\\text{$L^q$} = \\arg \\min_\\beta ||y - X\\beta||_2^2 \\quad s.t \\quad ||\\beta||_q^q\\leq t. \\]\n\\end{thm}\n\n\\begin{proof}\nThe proof follow the same steps than the previous one.\n\\end{proof}\n\nThe Figure \\ref{Bound2} represents the feasible sets for different values of $q$.\n\\begin{figure}[!h]\n\\centerline{\n\\includegraphics[width = 0.7\\textwidth]{figures/bound.png}}\n\\caption{Boundaries of the feasible set with different values of q}\n\\label{Bound2}\n\\end{figure}\n\n\\subsubsection{Comparison between Lasso and Ridge}\nBecause the feasible depends on the value of $q$, the Ridge $(q = 2)$ and Lasso $(q = 1)$ estimator will be different. The feasible set will be a square in one case and a circle in the other. This helps understand why the $L^1$ norm gives sparse models. Indeed, the $L^1$ ball has corners. This means that when we're moving from the unconstrained minimum towards the ball, we're more likely to ``hit'' a corner of the ball. And, on a corner of the ball, only one feature has a weight non equal to zero.\n\n\\begin{figure}[!h]\n\\centerline{\n\\includegraphics[width = 0.7\\textwidth]{figures/comparison.png}}\n\\caption{Comparison of the Lasso-estimator and the Ridge-estimator}\n\\label{Comparison}\n\\end{figure}\n\n\\subsection{Structured Regularization}\n\\subsubsection{Group Lasso}\nThe \\emph{group Lasso} is a variant of Lasso. All $p$ variables are partitioned in $K$ predefined groups of variables that are known to work together and expected to work together and thus be all active or inactive together. For instance, genes belonging to the same biological pathway can form a group.\n\nLet $X_k$ be the features belonging to group $k$. Let $p_k$ be the size of group $k$. We have : $\\sum_{k = 1}^K{p_k} = p$. We can define the Group Lasso-estimator:\n\\[ \\hat{\\beta}_\\text{grlasso} = \\arg \\min_\\beta ||y - \\sum_{k = 1}^K{X_k\\beta_k}||_2^2 + \\lambda \\sum_{k = 1}^K{\\sqrt{p_k}||\\beta_k||_2}\\]\n\n\\subsubsection{Other structured penalties}\nOther regularizations exist :\n\\begin{itemize}\n\\item Overlapping groups\n\\item Graphs\n\\item Trees\n\\item Multiple related Tasks\n\\end{itemize}\n\n\\section{Conclusion}\nWe've replaced the minimization of the sum of squared errors (that gave us the solution of the linear regression problem) by minimizing the sum of squared errors \\emph{plus} a regularizer that penalizes the model complexity. We've seen 3 major forms of regularizers:\n\\begin{itemize}\n\\item Ridge regression ($L^2$ norm)\n\t\\begin{itemize}\n\t\\item gives similar weights to similar variables,\n\t\\item doesn't really give sparse solution,\n\t\\item but has the advantage of having an explicit solution.\n\t\\end{itemize}\n\\item Lasso regression ($L^1$ norm)\n\t\\begin{itemize}\n\t\\item randomly picks one of several correlated variables,\n\t\\item gives sparse solution,\n\t\\item can be implemented by the Least Angle Regression algorithm.\n\t\\end{itemize}\n\\item Elastic net (combining $L^1$ and $L^2$ norm)\n\t\\begin{itemize}\n\t\\item selects variables like the lasso,\n\t\\item shrinks together the coefficients of correlated variables.\n\t\\end{itemize}\n\\end{itemize}\n\n\\end{document}", "meta": {"hexsha": "6bb877238b6eecd02f462f193e3a67c6221a42b8", "size": 22906, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "lecture_notes/chap06_regularization.tex", "max_stars_repo_name": "taeraa/ma2823_2016", "max_stars_repo_head_hexsha": "b91642e8b3cac059f91d6785f9da6a436b382db8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2016-09-13T16:35:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T02:16:53.000Z", "max_issues_repo_path": "lecture_notes/chap06_regularization.tex", "max_issues_repo_name": "taeraa/ma2823_2016", "max_issues_repo_head_hexsha": "b91642e8b3cac059f91d6785f9da6a436b382db8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-10-03T10:42:43.000Z", "max_issues_repo_issues_event_max_datetime": "2016-10-03T10:43:16.000Z", "max_forks_repo_path": "lecture_notes/chap06_regularization.tex", "max_forks_repo_name": "taeraa/ma2823_2016", "max_forks_repo_head_hexsha": "b91642e8b3cac059f91d6785f9da6a436b382db8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 62, "max_forks_repo_forks_event_min_datetime": "2016-09-07T06:25:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-30T13:21:05.000Z", "avg_line_length": 61.9081081081, "max_line_length": 996, "alphanum_fraction": 0.740679298, "num_tokens": 6441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.34415215672215116}}
{"text": "%\\section{Discussion}\n\n\n\\subsection{Comparison of beading schemes}\nWe can see from \\cref{TEST_naive_accuracy}(top) and~\\ref{over_underfill} that the uniform technique causes a lot of overfills and underfills: on average \\revise{approximately}{} \\revise{\\SI{1}{\\percent}}{\\SI{1.6}{\\percent}} of the total target area is covered by underfill and likewise for overfill.\nTo our knowledge, the uniform beading scheme, as well as the outer beading scheme, is of little use to FDM printers.\n\nThe constant bead count scheme effectively deals with underfills, but generates orders of magnitude more overfills compared to the other schemes. \nAlso, the scheme comes at the cost of greatly varying bead widths and an average bead width that is not close to the preferred bead width.\nNote that most overfill areas occur near regions of alternating bead width. \n\\revise{}{While the scheme results in short toolpaths, as indicated by the idealized print time, it also results in a wide range of bead widths, which cause the back pressure compensation print time to be very large.\nSee \\cref{statisticsfig}.}\nFor an input outline shape which contains both very small and very large features, the constant bead count scheme produces bead widths which can fall outside of the range of manufacturable bead widths.\nMoreover the centrality marking is not robust against small perturbations in the outline; adding a small chamfer in a corner causes the unmarked ST to be very small at that location, which results in tiny bead widths.\n\\revise{}{See top right of \\cref{TEST_Constant_accuracy}.}\n\nIn \\cref{TEST_Center_accuracy} we can see that\nthe centered beading scheme effectively deals with \\revise{both }{}overfill \\revise{and underfill }{}and produces desired bead widths in all locations, except for the extrusion paths in the center, where the bead widths \\revise{are within a factor 2 off from the desired bead width.}{range between $0.25 w^*$ and $1.8w^*$.}\n\\revise{}{However, it does produce some narrow underfill regions.}\n\\revise{%gs\nAccording to \\cref{over_underfill} the overfill and underfill for the centered, the evenly distributed and the inward distributed scheme are all approximately \\SI{0.2}{\\percent}, which is a considerable improvement over the uniform technique.\n}{%sg\nCompared to the uniform technique the centered technique increases the (open) path count, but considerably reduces over- and underfill and decimates the number of toolpath angles below \\SI{45}{\\degree}.\nSee \\cref{statisticsfig}.%afs\n}%zgds\n\nHowever, according to \\cref{widthHistogram} the centered scheme exhibits a wider range of bead widths than the distributed schemes:\nthe standard deviation of the bead widths in the centered scheme is approximately \\revise{\\SI{39}{\\micro\\meter}}{\\SI{53}{\\micro\\meter}}, while that of the distributed schemes is approximately \\revise{\\SI{14}{\\micro\\meter}}{\\SI{23}{\\micro\\meter}}.%_\n\\revise{}{\\footnote{\\revise{}{Although the standard deviation $\\sigma$ of the inward distributed scheme is slightly higher than that of the evenly distributed scheme, the mean absolute deviation is lower (i.e. \\SI{9}{\\micro\\meter} versus \\SI{11}{\\micro\\meter}), because its distribution is more peaked.}}}\n\\revise{}{Moreover, because the quantization operator rounds to the nearest number of beads, in the worst case where we switch from a single to two beads the widths switch from $0.75w^*$ to $1.5w^*$, which is a considerably smaller range than in the centered scheme.}\nWe therefore conclude that the distributed schemes \\revise{result in bead widths closer to the preferred widths}{exhibit a lower bead width variation and lower (open) path count} compared to the centered scheme.\n%This is desirable for the manufacturability of the beads and can therefore have a positive effect on the mechanical properties and surface quality of the 3D prints. \n\n\\revise{It is hard to visually identify the difference between the evenly and the inward distributed scheme in \\cref{visualized_accuracy}, because that particular example shape does not have wide features.}\n{\\Cref{distributed_comparison,TEST_Distributed_accuracy,TEST_InwardDistributed_accuracy} show that in the inward distributed scheme the outer toolpaths have the preferred width more often than in the evenly distributed scheme, which means that the outline accuracy of the inward distributed beading is less affected by inaccuracies in the adaptive width control system.}\n%{\\Cref{TEST_InwardDistributed_accuracy} shows that in the inward distributed scheme the outer beads are more often equal to the preferred width compared to the evenly distributed scheme in \\cref{TEST_Distributed_accuracy}, but that effect is more pronounced for wider geometry such as in \\cref{distributed_comparison}.}\n%While the difference between the evenly and inward distributed scheme in \\cref{visualized_accuracy} results only in the outer bead being the preferred width in some locations, the effect of the inward distributed scheme is more pronounced in larger geometry, as can be seen in \\cref{distributed_comparison}.}\n\\revise{However, \\cref{distributed_comparison} and  \\cref{widthIndexedHistogram} confirm that the outer toolpaths have the preferred bead width more often.}{}% _\nFurthermore, \\revise{from \\cref{smoothness} }{}we find that compared to evenly distributed, the inward distributed scheme produces \\revise{smoother toolpaths overall}{less corners with angles above \\SI{130}{\\degree} and less overfill, because the area of influence that bead count transitions have is limited in the inward distributed scheme}.\nThus the inward distributed scheme prevents over- and underfill, generates smooth toolpaths with more homogeneous width and affects smaller more centered parts of the print than the other schemes\\revise{}{, while incurring little to no extra print time}. \n\n\n\n\\revise{}\n{\n\\subsection{Limitations}\n% design considerations\nBecause the performance of the various toolpathing techniques depends on the geometry of a model, they have ramifications for the practice of design for additive manufacturing.\nBecause the naive method produces under- or overfill for parts of an outline with a constant diameter $d \\neq 2 i w^*$ it is best practice to design a model such that horizontal cross-sections have a feature diameter of an even integer multiple $i$ of the bead width.\nFor the center\\revise{ed} scheme and for the current state of the art one should only avoid parts for which $(2i + 1.8) w^* < d < (2i + 0.25) w^*$ in order to avoid underfill.\nFor the distributed schemes however, there is no diameter at which the framework produces under- or overfill for a part with a constant diameter $d$.\nThe design consideration therefore reduces to limiting the diameter of your parts to be within the range $[w_\\text{min}, \\infty)$,\nwhere $w_\\text{min}$ is a configurable parameter when using the widening meta-scheme.\n\n\n% single line segments & continuity\nThe default limit bisector angle $\\alpha_\\text{max} = \\SI{135}{\\degree}$ ensures that we don't employ transitioning in shallow wedge regions, which would result in a lot of short odd single bead polylines, which would break up the semi-continuous nature of polygonal extrusion paths;\n$\\alpha_\\text{max} = \\SI{135}{\\degree}$ corresponds to $w^* / \\cos \\nicefrac12 \\alpha_\\text{max} \\approx \\SI{0.4}{\\milli\\meter}$ long segments\nand under-/overfill areas of $\\nicefrac14 (w^*)^2 \\left( \\tan ( \\alpha / 2) - \\alpha / 2 \\right) \\approx \\SI{0.05}{\\milli\\meter\\squared}$.\nHowever, future work might be aimed at reducing under-/overfill in regions with a low bisector angle without the introduction of short single polyline extrusion segments.\nIf the over-/underfill problem is also solved for non-significant regions we might be able to increase $\\alpha_\\text{max}$ and reduce the discontinuity introduced by short extrusion segments.\n\n% single beads\nAnother limitation of our method is that in a location $v$ with locally maximal $R(v) \\approx (i + \\nicefrac12) w^*$ the odd bead count will result in a single polyline extrusion segment consisting of only a single point.\nThis can be viewed in the bottom right of \\cref{TEST_InwardDistributed_accuracy} for example.\nIn order to print such a dot, we make it into a \\SI{10}{\\micro\\meter} long extrusion segment, with an altered width such that the total volume remains correct.\nA more principled way of dealing with such a situation remains future work.\n\n% emulation troubles\nFinally it should be noted that although our framework can accurately emulate the constant bead count approach by \\citeauthor{Ding2016a}, its emulation of the centered approach by \\citeauthor{Jin2017JMS} is imperfect.\nThe transitions resulting from out framework introduce sharper corners and there is more width variation in those corners.\nWhereas the width of the connecting segment in the approach by \\citeauthor{Jin2017JMS} is the preferred width $w^*$, the bead widths closer to the center resulting from our framework will be twice the local radius, which is larger than $w^*$.\nHowever, this inflated bead width variation is expected to have an insignificant impact on the measured bead width variation.\n}\n\n\n\n\\input{10_applications}\n\n\n\n\n\n\n\\revise{\n\\subsection{Discussion on implications}\nNote that the current industry standard in FDM printing employs little to no bead width variation.\nProperly performing bead width variation calls for adaptations and developments in printers and firmware.\nIn the beading schemes we set a transition length of $t(n) = w^*$.\nThat will demand changes in cross-sectional area of the bead up to \\SI{200}{\\percent} over a small distance that is comparable to the nozzle size, which is challenging for some hardware systems.\nVarying the movement speed can be utilized to change the cross-sectional area, but this approach is limited, since the movement speed is constrained by acceleration considerations near bends in the toolpath~\\cite{Ertay2018,Kuipers2018}.\nOur schemes require a more accurate control of the volumetric flow rate in \\si{\\milli\\meter\\cubed\\per\\second}.\nUsing a filament feeder directly mounted on the print head (a.k.a. direct drive) can control the flow more dynamicaly then FDM printers where the material is fed through a Bowden tube from a feeder mounted on the frame.\nStill direct drive printers require some control system in order to accurately change the volumetric flow rate such as pressure advance algorithms~\\cite{tronvoll2019investigating}.\nYet inaccuracies in direct drive systems employing advance algorithms might arise due to the changes in back-pressure required by changing bead size.\nWe expect that developments in printing hardware and firmware will address these challenges in the future.\n\nAnother limiting factor for adopting adaptive bead width is the format of G-code which stores machine instructions.\nG-code does not support moves with varying cross-sectional area.\nA typical extrusion move \\lstinline!G1 X$x$ Y$y$ E$v$! only specifies the total amount of volume $v$ to be extruded in the move, not how that total amount should be distributed along the extrusion move.\nA workaround is to approximate a variable width extrusion segment by smaller segments with constant width.\nHowever, this introduces errors nevertheless.\nIdeally the G-code language would be expanded in some way to allow for extrusion segments with varying cross-sectional area.\n}{}\n\n% Taking a broader perspective, we note that our proposed inward distributed scheme is a pragmatic solution.\n% Rather than deriving some optimal beading scheme from a clear specification of the objective, we propose some arbitrary inward distributed beading scheme and show that it is better than the other beading schemes.\n% An optimal beading scheme can be derived if the objective is formalized terms of a unambiguous fitness function, but that would depend on the specific hardware setup and application for which toolpaths are generated.\n% This manuscript is therefore limited to showing the flexibility and versatility of the framework, rather than deriving an optimal beading scheme.\n\n\n\n\n", "meta": {"hexsha": "9702ff8602a12f61074c20b824542721c021126d", "size": 12057, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "8_discussion.tex", "max_stars_repo_name": "BagelOrb/variable_width_paper", "max_stars_repo_head_hexsha": "8b8b7a2b9b913e56267a578d2a15ed7e97fa3503", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-23T10:22:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-23T10:22:42.000Z", "max_issues_repo_path": "8_discussion.tex", "max_issues_repo_name": "BagelOrb/variable_width_paper", "max_issues_repo_head_hexsha": "8b8b7a2b9b913e56267a578d2a15ed7e97fa3503", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "8_discussion.tex", "max_forks_repo_name": "BagelOrb/variable_width_paper", "max_forks_repo_head_hexsha": "8b8b7a2b9b913e56267a578d2a15ed7e97fa3503", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 105.7631578947, "max_line_length": 370, "alphanum_fraction": 0.7987890852, "num_tokens": 2676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.34415214789850984}}
{"text": "\\subsection{Fishing Mortality in Stock Synthesis}\n\nThe implementation and reporting of fishing mortality rate, $F$, in SS3 has some aspects that can be confusing.  This description provides an overview of the ways in which $F$ is calculated, used, and reported.  \n\n\\myparagraph{Rationale}\nFishery management systems expect to have a measure of annual fishing mortality that describes the intensity of the fishery such that an optimal level of $F$ can be articulated and accountability measures can be invoked if $F$ is too high, e.g., overfishing.  This concept is simple and straightforward if the model is a simple biomass dynamics such that a single annual $F$ value operates on the entirety of a non-age structured population. It also is simple for age-structured models that have a single fishing fleet and knife-edge selectivity beginning at some specified age.\n\nThe simplicity of $F$ disappears quickly as models invoke a variety of realistic complexities such as: allowing the $F$ to differ among ages or to be based on size; using a collection of fleets with different $F$ levels and different age patterns for $F$; spreading the population across areas and allowing different fleets with different $F$ among the areas.  An unambiguous measure of annual fishing intensity that represents the cumulative effect of all that complexity has not been defined.  This problem has not been solved with SS, but some logical alternatives have been made available.\n\n\\myparagraph{Nomenclature}\nThe nomenclature below ignores sex, morphs and areas for simplicity. The quantities associated with $F$ calculations are defined as:\n\n$f$ is fleet.\n\n$t$ is a time step; continuous across years $y$ and seasons $s$; equivalent to year if only 1 season.\n\n$a$ is age.\n\n$C_{t,f}$ is fleet-specific catch in a time step.\n\n$B_{t,f}$ is fleet specific available biomass, e.g., total biomass filtered by fleet-specific age selectivity, $s_{t,f,a}$.\n\n$s_{t,f,a}$ is age-specific selectivity for a fleet. If selectivity is length-specific, then age-specific selectivity is calculated as the dot product across length bins of length selectivity and the normal (or lognormal) distribution of length-at-age.  If selectivity is both length- and age-based, which is an entirely normal concept in SS, then age selectivity due to length selectivity is calculated first, then multiplied by the direct age selectivity.  This compound age selectivity is used in the mortality calculations and is reported as asel2 in report file.  See appendix to \\citet{methotstock2013} for more detail on this.\n\n$F_{t,f}'$ is the apical fishing mortality for a fleet. This means that it is the rate for the age that has selectivity equal to 1.0. If your model is using $F'$s as parameters, then the parameter values are for $F'$.\n\n$F_{t,f,a}$ is age and fleet-specific fishing mortality rate equal to $F_{t,f}' * s_{t,f,a}$. Note that it is possible for no age to have a selectivity equal to 1.0. In this case, $F'$ is still the rate for the hypothetical age that has selectivity equal to 1.0. The reported $F'$ values are not rescaled to be an $F$ for the age with peak selectivity. Users need to take this into account if they are comparing reported $F'$ values to reported vector of $F_{t,f,a}$ values.\n\n$\\text{ann}F_y$ is a measure of the total fishing intensity for a year, based on one of several user-specified options (see below).\n\n$F\\text{std}_y$ is a standardized measure of the total fishing intensity for a year and is reported in the derived quantities, so variance is calculated for this quantity. See below for how it relates to $annF$.\n\nTerminology and reporting of $\\text{ann}F$ and $F\\text{std}$ has been slightly revised for clarity in 3.30.15.00 and the description here follows the new conventions.\n\n\\myparagraph{$F$ Calculation}\nSS3 allows for three approaches to estimate the $F'$ that will match the input values for retained catch. Note that SS3 is calculating the $F'$ to match the retained catch conditional on the fraction of total catch that is retained, e.g., the total catch is partitioned into retained and discarded portions.\n\n\\begin{enumerate}\n\t\\item Pope’s method decays the numbers-at-age to the middle of the season, calculates a harvest rate for each fleet, $H_{t,f}$, that is the ratio of $C_{t,f}$ to $B_{t,f}$, then decays the survivors to the end of the season. the total mortality, $Z_{t,a}$, from the ratio of survivors to initial numbers, is then calculated. The $Z$ is subsequently used for in-season interpolation to get expected values for observations.\n\t\n\t\\item $F$ as parameters uses the standard Baranov catch equation and lets ADMB find the $F'$ parameter values that produce the lowest negative log-likelihood, which includes fit to the input catch data. $F$ as parameters method tends to work better than Pope’s or hybrid in high $F$ situations because it allows for some lack of fit to catch levels in early iterations and can later improve this fit as it closes in on the best solution.\n\t\n\t\\item Hybrid $F$ starts by calculating a harvest rate, $H$, using Pope’s, then converts these $H$ values, which have units of fractional harvest rate, into an approximate of $F'$ in exponential units, tuning these $F'$ values over a few iterations to get a better match to each fleet’s catch.\n\\end{enumerate}\n\nItems to note:\n\\begin{itemize}\n\t\\item SS3 includes a permutation on the $F$ as parameters method. In the first few phases, SS3 uses hybrid, then between phases it converts these directly calculated $F'$ values into parameters and proceeds in subsequent phases and MCMC to use the parameter approach. This variation on the parameter method is the recommend approach in high $F$ situations.\n\t\n\t\\item With Pope’s method, the $H$ values are fraction caught, so duration of the season does not matter. Parameter and hybrid treat $F'$ identically and multiply the $F'$ values by season duration (which has units of fraction of a year) as it is used. Each of the $F$ methods ends up with a $Z_{t,f}$ that is used for in-season interpolation.\n\\end{itemize}\n\n\\myparagraph{Relative $F$ and $F$mult}\nThe $F'$ is fleet-specific, so it is useful to have a concept of relative $F$, $\\text{rel}F_f$, among fleets. In SS, $\\text{rel}F_f= F_{t,f}'/\\sum_{f}^{}F_{t,f}'$ for a single time period $t$. In the benchmark and forecast routines, SS3 can calculate $\\text{rel}F_f$ using $F_{t,f}'$ over a range of years, or the user can input custom $\\text{rel}F$ values for benchmark and forecast in the forecast.ss file. Note that in a multi-season model setup, $\\text{rel}F_f$ is implemented as $\\text{rel}F_{s,f}$ where $s$ is the season. These get multiplied by season duration as they are used.\n\nIn the benchmark section of the code, SS3 searches for an $F$mult to achieve various management reference points (often referred to as benchmarks). In this search, SS3 calculates a benchmark $F$ as  $F_{ben,f}' = F\\text{mult} * \\text{rel}F_f$, then calculates equilibrium yield and spawning biomass per recruit (SPR). SS3 searches for the $F$mult that satisfies the search conditions, first for user-specified SPR, then for user-specified spawning biomass at a management target (B\\textsubscript{TGT} or $F_{0.1}$), then for MSY. The resultant benchmark quantities are reported in the derived quantities, but $F$mult and $F_{ben,f}'$ are only reported in the Forecast\\_report.sso file. SS3 stores the benchmark $F$mult values so that user can invoke them for the forecast.\n\n\\myparagraph{Annual $F$}\nThe $\\text{ann}F$ is a single annual value across all fleets and areas according to F\\_report\\_units, which is specified by users in the starter file. If there are many fleets, across several areas and with very different selectivity patterns, $\\text{ann}F$ can have a complicated relationship to apical $F$. The F\\_report\\_units specification in the starter.ss file, see example line below, allows user to calculate it using $F'$ directly, use exploitation rate, or be derived from $Z$-at-age.\n\nExample $F$ reporting unit specification in the starter.ss file:\n\n\\begin{center}\n\t\\begin{longtable}{p{2cm} p{12cm}}\n\t\t\\hline\n\t\t5 & \\# F\\_report\\_units:\\Tstrut\\\\\n\t\t  & 0 = skip; \\\\\n\t\t  & 1 = exploitation(Bio); \\\\\n\t\t  & 2 = exploitation(Num); \\\\ \n\t\t  & 3 = sum(Frates); \\\\\n\t\t  & 4 = true F for range of ages; \\\\\n\t\t  & 5 = unweighted avg. F for range of ages. \\Bstrut\\\\\n\t\t\\hline\n\t\t3 7 & \\# min and max age over which average F will be calculated \\Tstrut\\Bstrut\\\\\n\t\t\\hline\n\t\\end{longtable}\n\\end{center}\n\nFor options 4 and 5 of F\\_report\\_units, the $F$ is calculated as $Z-M$ where $Z$ is calculated as $ln(N_{t+1,a+1}/N_{t,a})$, thus $Z$ subsumes the effect of $F$.\n\nThe ann$F$ is calculated for each year of the estimated time series and of the forecast. Additionally, an ann$F$ is calculated in the benchmark calculations to provide equilibrium values that have the same units as ann$F$ from the time series. In versions previous to 3.30.15, it was labeled inaccurately as $F$std in the output, not ann$F$. For example, in the Management Quantities section of derived quantities prior to 3.30.15, there is a quantity labeled Fstd\\_Btgt. This is more accurately labeled as the annual $F$ associated with the biomass target, ann\\_F\\_Btgt, in 3.30.15.\n\n\\myparagraph{$F$std}\n$F$std is a single annual value based on ann$F$ and the relationship to ann$F$ is specified by F\\_report\\_basis in the starter.ss file. The benchmark ann$F$ may be used to rescale the time series of ann$F$s to become a time series of standardized values representing the intensity of fishing, $F$std. The report basis is selected in the starter file as:\n\n\\begin{center}\n\t\\begin{longtable}{p{2cm} p{12cm}}\n\t\t%\\multicolumn{2}{l}{The starter file line:}\\\\\n\t\t\\hline\n\t\t0 & \\# F\\_report\\_basis: \\Tstrut\\\\\n\t\t& 0 = raw F report; \\\\\n\t\t& 1 = F / F\\textsubscript{SPR}; \\\\ \n\t\t& 2 = F / F\\textsubscript{MSY}; \\\\\n\t\t& 3 = F / F\\textsubscript{BTGT}.\\Bstrut\\\\\n\t\t\\hline\n\t\\end{longtable}\n\\end{center}\n\nFor example, if user selects option 1, $F$ / $F_\\text{SPR}$, the time series of ann$F$ will be divided by each value by the ann$F$ calculated in benchmark.\n\n\\myparagraph{Units for Stock Synthesis inputs related to $F$}\nBelow is a list of items to consider in terms of units for $F$ in SS:\n\\begin{itemize}\n\t\\item If F\\_ballpark is specified in the control.ss file, its units are the same as ann$F$, so is not fleet-specific.\n\t\n\t\\item $F$ as parameter values has units of fleet-specific apical $F'$.\n\t\n\t\\item In the forecast.ss file there is an option to input a vector of rel$F$ values. These are dimensionless and will be rescaled to sum to 1.0.\n\t\n\t\\item In the forecast.ss file there is an option to specify an $F$ scalar for the forecast.  The units of $F$ scalar are the same as the $F$mult values calculated in benchmark.  There are a full set of options for forecast $F$ scalar that can be selected in the forecast file \n\t%(-1 = none; 0 = simple; 1 = F\\textsubscript{SPR}; 2 = F\\textsubscript{MSY} 3 = F\\textsubscript{BTGT} or F\\textsubscript{0.1}; 4 = Ave F (uses first-last relative F years); and 5 = input annual F scalar). \n\tIf the forecast $F$ scalar is set as $F_\\text{SPR}$, then SS3 will use SPR\\_Fmult calculated in benchmark and reported in Forecast-report.sso.  If user selects the option to input an annual $F$ scalar, option 5, then the value is input on a following line.  Whichever method the user selects for forecast $F$ scalar ($F$mult), SS3 will start the forecast by creating a fleet-specific vector of apical $F$ values from $F$mult*rel$F_f$.\n\t\n\t\\item Also in the forecast.ss file, the last section of inputs allows for input of time and fleet specific apical $F_{t,f}'$ values that override the basic forecast $F$ specification described above.\n\\end{itemize}", "meta": {"hexsha": "72a0bdfbefe01c765d79b48f7228051e9e4a2234", "size": 11721, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "_f_mortality.tex", "max_stars_repo_name": "nmfs-stock-synthesis/ss-documentation", "max_stars_repo_head_hexsha": "941401b1f21582ad9d17b3b261761b307d6ea669", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-05T22:03:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T15:23:29.000Z", "max_issues_repo_path": "_f_mortality.tex", "max_issues_repo_name": "nmfs-stock-synthesis/ss-documentation", "max_issues_repo_head_hexsha": "941401b1f21582ad9d17b3b261761b307d6ea669", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 70, "max_issues_repo_issues_event_min_datetime": "2021-03-02T22:47:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-30T17:51:05.000Z", "max_forks_repo_path": "_f_mortality.tex", "max_forks_repo_name": "nmfs-stock-synthesis/ss-documentation", "max_forks_repo_head_hexsha": "941401b1f21582ad9d17b3b261761b307d6ea669", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 101.9217391304, "max_line_length": 772, "alphanum_fraction": 0.7536899582, "num_tokens": 3057, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.34411648543097656}}
{"text": "% Chapter 2\n\n\\chapter{Conclusion} % Main chapter title\n\n\\label{Chapter6} % For referencing the chapter elsewhere, use \\ref{Chapter2} \n\n\nWe have reviewed some of the algorithms used for sampling a uniform spanning tree. The main impetus for going into the details of \\citet{harvey2016generating} is due to the fact that it uses the Sherman-Morrison-Woodbury identity for updating the laplacian pseudoinverse. Recently \\citet{DBLP:journals/corr/abs-2004-12739} also used the same identity for showing that \\textbf{REACHABILITY} problem is in \\texttt{DynFO} + \\texttt{Mod} $2(\\leq, +, \\times)$. Hence we explored the possibility of using the same framework for sampling spanning trees in the dynamic setting. But it turns out that there are a lot of subtleties in coming up with a proper formulation. \n\n%----------------------------------------------------------------------------------------\n\n\n%----------------------------------------------------------------------------------------\n\n\n\n\n\n", "meta": {"hexsha": "6bfdcda11b11cbc89c0fa32207f7f7fd46caee67", "size": 987, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/Chapters/Chapter6.tex", "max_stars_repo_name": "severus-tux/masters-thesis", "max_stars_repo_head_hexsha": "c6d3856cccda06735a01699c91ad923590f08ab7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thesis/Chapters/Chapter6.tex", "max_issues_repo_name": "severus-tux/masters-thesis", "max_issues_repo_head_hexsha": "c6d3856cccda06735a01699c91ad923590f08ab7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis/Chapters/Chapter6.tex", "max_forks_repo_name": "severus-tux/masters-thesis", "max_forks_repo_head_hexsha": "c6d3856cccda06735a01699c91ad923590f08ab7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-14T15:34:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-14T15:34:34.000Z", "avg_line_length": 51.9473684211, "max_line_length": 662, "alphanum_fraction": 0.6382978723, "num_tokens": 213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6723317123102955, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3440433010583621}}
{"text": "\\documentclass[12]{scrartcl}\n\\usepackage{amssymb,amsmath,gensymb,dsfont,calc,multicol,fullpage}\n\\makeatletter\n\\newcommand\\Aboxed[1]{\n   \\@Aboxed#1\\ENDDNE}\n\\def\\@Aboxed#1&#2\\ENDDNE{%\n   &\n   \\settowidth\\@tempdima{$\\displaystyle#1{}$}\n   \\setlength\\@tempdima{\\@tempdima+\\fboxsep+\\fboxrule}\n   \\kern-\\@tempdima\n   \\boxed{#1#2}\n}\n\\makeatother\n\n\\begin{document}\n\n\\title{Homework 1, Section 5.2: 21, 22, 23}\n\\author{Alex Gordon}\n\\date{\\today}\n\\maketitle\n\\section*{Homework}\n\\subsection*{21. A)}\nFalse. If a matrix is not invertible then its determinant is zero. By the invertible Matrix Theorem, then \n\\subsection*{21. B)}\nFalse. This contradicts the properties of a determinant (see theorem 3).\n\\subsection*{21. C)}\nTrue. This contradicts the properties of a determinant (see theorem 3).\n\\subsection*{21. D)}\nFalse. Example 4 proves this wrong. \n\n\\subsection*{22. A)}\nFalse. When A is a 3 x 3 matrix, det A turns out to be the volume of the parallelepiped determined by the columns of $a_1, a_2, a_3$\n\\subsection*{22. B)}\nFalse. This contradicts the properties of a determinant (see theorem 3).\n\\subsection*{22. C)}\nTrue. In general, the algebraic multiplicity of an eigenvalue is its multiplicity as a root of the characteristic equation. \n\\subsection*{22. D)}\nFalse. The slightly incorrect warning on page 277 shows this. \n\n\\subsection*{23.}\nIf $A = QR$, with Q invertible, and if $A_1 = RQ$ then $A_1 = Q^{-1}QRQ = Q^{-1} AQ$ which shows that $A_1$ is similar to A\n\n\n\n\\end{document}", "meta": {"hexsha": "2eb6bd7672a4c3263023022fa7310bda3494d80d", "size": 1480, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "LinearAlgebra/Homework28.tex", "max_stars_repo_name": "alexggordon/latex", "max_stars_repo_head_hexsha": "7dd945f33490e6585e26cff39d9cf6ad8f582a0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LinearAlgebra/Homework28.tex", "max_issues_repo_name": "alexggordon/latex", "max_issues_repo_head_hexsha": "7dd945f33490e6585e26cff39d9cf6ad8f582a0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LinearAlgebra/Homework28.tex", "max_forks_repo_name": "alexggordon/latex", "max_forks_repo_head_hexsha": "7dd945f33490e6585e26cff39d9cf6ad8f582a0e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8888888889, "max_line_length": 132, "alphanum_fraction": 0.722972973, "num_tokens": 495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.3440432943390066}}
{"text": "\\documentclass[12pt]{article}\n\\input{physics1}\n\\newcommand{\\ap}{\\mathrm{ap}}\n\\newcommand{\\peri}{\\mathrm{peri}}\n\\begin{document}\n\n\\section*{NYU Physics I---Problem Set 12}\n\nDue Thursday 2018 November 29 at the beginning of lecture.\n\n\\paragraph{\\problemname~\\theproblem:}\\refstepcounter{problem}%\nWhat is the most expensive ingredient of a typical, traditional\nThanksgiving dinner \\emph{by weight} (that is, in dollars per ounce or\nper pound).  Start with the turkey and show your work (that is,\ncompare some ingredients). Don't forget the trace (that is, small\nin quantity) ingredients!\nWhat is the relevance of all this to world\nhistory? Keep it traditional---traditional food with traditional\ningredients, like you could have cooked in 1850.\nYou might want to discuss with someone who cooked\na Thanksgiving dinner (or did the shopping for it).\n\n\\paragraph{\\problemname~\\theproblem:}\\refstepcounter{problem}%\nIf all goes well in class on 2018-11-20, we will get a quadratic equation\nfor the radii $r_\\ap$ and $r_\\peri$ of aphelion and perihelion. The argument\ngoes like this: The total energy of an orbit can be written in terms of the\nangular momentum and the radial velocity\n\\begin{eqnarray}\nE & = & \\frac{1}{2}\\,m\\,v^2 - \\frac{G\\,M\\,m}{r}\n\\\\\nE & = & \\frac{1}{2}\\,m\\,v_r^2 + \\frac{1}{2}\\,m\\,v_\\perp^2 - \\frac{G\\,M\\,m}{r}\n\\\\\nE & = & \\frac{1}{2}\\,m\\,v_r^2 + \\frac{L^2}{2\\,m\\,r^2} - \\frac{G\\,M\\,m}{r}\n\\label{foo}\n\\end{eqnarray}\nwhere $E$ is the total energy of the orbit, $v_r$ is the radial component of the velocity,\nand $L$ is the angular momentum of the orbit.\nThe radial velocity $v_r$ is exactly zero at aphelion and perihelion.\nSo set it to zero in equation~(\\ref{foo}),\nand solve the resulting quadratic equation! It will give two answers,\nwhich are $r_\\ap$ and $r_\\peri$.\nUse the definition of eccentricity\n\\begin{equation}\ne \\equiv \\frac{r_\\ap - r_\\peri}{r_\\ap + r_\\peri}\n\\end{equation}\nto figure out\nthe relationship between eccentricity $e$ of an elliptical orbit and\nthe total energy $E$ and the angular momentum $L$.\n\n\\paragraph{\\problemname~\\theproblem:}\\refstepcounter{problem}%\n\\textsl{(a)}\nSketch orbits of fixed semi-major axis but increasing\neccentricity, from a circular orbit, to one that is close to radial\n(eccentricity close to unity). Make sure you show the location of\nthe point around which the object is orbiting!\n\n\\textsl{(b)}\nWhat is the transfer time for a radial plunge orbit\nfrom the radius of the Moon's orbit down to the surface of the Earth?\nUse the period of the Moon's orbit, the relevant  Kepler's law, and\nthe properties of the unit-eccentricity and circular orbits.\n\n\\textsl{(c)}\nLook up the timeline of the Apollo~11 mission, especially\nthe return to Earth.  Do you see any issues there? What's your best\nexplanation of what happened?\n\n\\paragraph{\\problemname~\\theproblem:}\\refstepcounter{problem}%\n\\textsl{(a)}\nHow fast do you have to move with respect to the Earth's surface to\nescape Earth's gravity? That is, what is escape velocity from the Earth.\nCalculate it yourself in terms of the radius $R$ of the Earth and the\nvalue of $g$ at the surface. Then give it also in $\\mps$.\n\n\\textsl{(b)} A spaceship of mass $m$ resting on the surface of the\nEarth is bound to the Earth but also to the Sun. If we make\nthe naive (and close to correct) assumption that these energies just\nadd, what is the total binding energy of the spaceship in the Solar\nSystem? This calculation can be confusing, because although you can assume\nthe spaceship is stationary with respect to the Earth (so there is\nonly gravitational potential energy with respect to the Earth), the\nspaceship is moving fast relative to the Sun (so there is both\ngravitational potential and kinetic energy with respect to the\nSun). The best way to do the calculation is to just pick the Newtonian reference\nframe centered on the Sun, and compute the kinetic and potential\nenergies in that frame. Now what is the escape velocity from the Solar\nSystem? Give your answer in $\\mps$.\n\n\\textsl{(c)} Look up the derivation of how a rocket accelerates. You\nshould be able to find a rocket equation that relates the initial mass\nof the rocket+fuel, the final mass of the rocket after the fuel is\nspent, the speed at which the rocket ejects exhaust, and the final\nspeed of the rocket. (Hint: The equation is exponential in a mass\nratio.) If the rocket can eject exhaust at 10 times the speed of sound\nin air at STP (and that's optimistic!), what is the ratio of initial\nmass to final mass of a rocket that will leave the Solar System? What\nis the maximum fraction of the spaceship initial mass that can be used\nfor payload---that is, for cabin, crew, and cargo?\n\n\\textsl{(d)} Now imagine the spaceship is going to another planet just\nlike the Earth. What fraction of the spaceship can be used for\nnon-fuel payload in this case? The point is that it takes just as much\nvelocity change to slow down at the end of the journey as it took to\ntake off at the beginning, and that the end-of-flight fuel is part of\nthe cargo that the ship has to take with it at launch. You should get\nthat the payload fraction is (something like) the square of what you got in\nthe previous part.\n\n\\paragraph{Extra Problem (will not be graded for credit):}%\nWhat do you think the above problem means for interstellar travel?\n\n\\paragraph{Extra Problem (will not be graded for credit):}%\nMake a spreadsheet integration that integrates a test-particle\n(low-mass) orbit in the central force law, and show that you do indeed\nget an elliptical orbit. You want to use a time step that is $<0.001$\nof the period and go for $>1000$ timesteps if you want the integration\nto look good! This integration is harder than other integrations you\nhave done in this class, because you have to project the force onto\nthe $x$ and $y$ directions correctly. That is, you have to keep track\nof both $x$ and $y$ positions, velocities, and accelerations. Do the\nproblem in the two-dimensional plane of the orbit. If you want\nfeedback or get stuck, bring your intermediate work to Prof~Hogg for\ndiscussion.\n\n\\end{document}\n", "meta": {"hexsha": "cfdbdfd2a60a07000b0695b38a029beee0215819", "size": 6060, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/physics1_ps12.tex", "max_stars_repo_name": "davidwhogg/Physics1", "max_stars_repo_head_hexsha": "6723ce2a5088f17b13d3cd6b64c24f67b70e3bda", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-11-13T03:48:56.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-13T03:48:56.000Z", "max_issues_repo_path": "tex/physics1_ps12.tex", "max_issues_repo_name": "davidwhogg/Physics1", "max_issues_repo_head_hexsha": "6723ce2a5088f17b13d3cd6b64c24f67b70e3bda", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2016-10-07T19:48:57.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-29T22:47:25.000Z", "max_forks_repo_path": "tex/physics1_ps12.tex", "max_forks_repo_name": "davidwhogg/Physics1", "max_forks_repo_head_hexsha": "6723ce2a5088f17b13d3cd6b64c24f67b70e3bda", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.0952380952, "max_line_length": 90, "alphanum_fraction": 0.7630363036, "num_tokens": 1601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.34404329433900654}}
{"text": "\\documentclass[twocolumn,longbibliography]{quantumarticle-customized}\n\\usepackage{amsmath}\n\\usepackage{amsfonts}\n\\usepackage{graphicx}\n\\usepackage[pdfpagelabels,pdftex,bookmarks,breaklinks]{hyperref}\n\\usepackage[all]{hypcap}\n\\hypersetup{colorlinks,citecolor=blue,urlcolor=blue,linkcolor=blue}\n\n\\title{Factoring with $n+2$ clean qubits and $n-1$ dirty qubits}\n\\author{Craig Gidney}\n\\affiliation{Google, Santa Barbara, CA 93117, USA}\n\\email{craiggidney@google.com}\n\n\\def\\sectionautorefname{Section}\n\n\\begin{document}\n\\maketitle\n\n\\begin{abstract}\nWe present reversible classical circuits for performing various arithmetic operations aided by dirty ancillae (i.e. extra bits/qubits in an unknown state that must be restored before the circuit ends).\nWe improve the number of clean qubits needed to factor an $n$-bit number with Shor's algorithm \\cite{Shor1999} from $1.5n + O(1)$ \\cite{zalka2006} to $n+2$, assisted by $n-1$ dirty qubits, without increasing the asymptotic size or depth of the circuit.\n\\end{abstract}\n\n\\section{Introduction} \\label{sec:introduction}\n\nWhen constructing quantum circuits, or classical reversible circuits, an important resource is the number of available ancillae.\nAn ancilla is an extra bit or qubit that is available for use by a circuit as temporary workspace.\nAncillae may be initialized to a known computational basis state (``clean bit\"), or be given to the circuit in an unknown and potentially entangled state that must be restored before the circuit finishes (``dirty bit\").\nClean bits are more valuable, allowing for simpler and more compact circuit constructions, but dirty bits are more plentiful, since any temporarily unused bit is a borrowable dirty bit.\n\nOne part of a circuit can borrow dirty bits from another part of the same circuit, so circuit constructions that require only dirty bits are easier to apply under tight space constraints, or on circuit topologies where other ancillae are too far away to be acquired quickly.\nWhen attempting to reduce the number of bits or qubits required by a circuit, replacing constructions that use clean ancillae with ones that use dirty ancillae is a useful intermediate goal.\n\nIt is important to note that, pragmatically speaking, it is far more important to, for example, achieve low T gate counts under plausible architectural constraints than to reduce the number of clean qubits required by a circuit.\nOur goal in this paper is not to come up with an implementation of Shor's algorithm optimized in the ways that matter for plausible future quantum computer architectures.\nOur goal is to explore the consequences of picking a metric, trying to optimize it, and seeing what ideas fall out.\nThe circuit constructions we present will not be optimized to achieve good constant factors on circuit depth or gate count (though their asymptotics are fine).\nAnd they will ignore machine architecture; they assume all-to-all connectivity between qubits.\nAnd the {\\em total} number of qubits we use ($2n+1$) is higher than previous work.\nBut interesting ideas don't always come from thinking directly about a problem; there is much to be found by placing artificial goals and seeing where they lead.\nThat exploration is our intent.\nIn this paper, we reduce the number of clean qubits required to factor an $n$-bit number with Shor's algorithm from $1.5n + O(1)$ clean qubits \\cite{zalka2006} to $n+2$ clean qubits assisted by $n-1$ dirty qubits.\nWe do so without increasing the asymptotic circuit depth or size.\n\nOur paper is structured as follows.\n\\autoref{sec:introduction} introduces and describes the conventions our circuit constructions and circuit diagrams will follow.\nIn \\autoref{sec:construct} we describe all the circuit constructions we use to reduce the period finding step of Shor's algorithm into constant-sized gates, while tracking the number of required dirty ancillae.\nThen, in \\autoref{sec:costs}, we discuss the novelty and comparative costs of the presented circuit constructions.\nFinally, \\autoref{sec:conclusion} concludes with a discussion of possible future improvements.\n\nAll constructions in this paper use a two's-complement representation of integers.\nWhen a result would exceed the size of a register, it wraps (i.e. all the non-modular arithmetic constructions we discuss actually perform arithmetic modulo $2^n$, where $n$ is the size of the target register).\n\nAll diagrams order qubits from least significant bit (LSB) at the top to most significant bit (MSB) at the bottom.\n\nAll our circuit diagrams annotate operations with the number of clean and/or dirty ancillae they need.\nFor example, a dashed line from an operation down to a triangle inscribed with ``3 dirty\" means that the operation needs 3 dirty ancilla.\nIf there are 3 unused wires that the operation can borrow, then the triangle will be green and a note of ``(satisfied)\" will be written underneath.\nIf there are not enough unused wires shown in the diagram, the triangle will be yellow.\n\nThe ancillae counts shown in diagrams and discussed in the text are not optimal; they are entirely based on what the constructions we discuss in this paper achieve.\nNearly all the circuit constructions we present are classical reversible circuits (i.e. they do not use any quantum operations), so tricks such as the ancilla bootstrap shown in \\autoref{fig:bootstrap-ancilla} could cut the ancilla count in several places.\nHowever, none of these improvements decrease the ancillae required at any crucial bottleneck, and so they do not reduce the number of qubits required by our overall construction of Shor's algorithm.\n\nTo avoid ambiguity, circuit diagrams will divide multi-register operations into separate parts.\nFor example, for an addition operation that adds a register $x$ into a register $y$ (i.e. performs $|x\\rangle |y\\rangle \\rightarrow |x\\rangle |y + x \\pmod{2^n} \\rangle$), we will place a light-gray box with the text ``Input A\" over the wires corresponding to $x$ and a white box with the text ``+A\" over the wires corresponding to $y$.\nThe ``A\" symbol refers to the value of the input register, in the computational basis, at the time of the operation.\nDiagrams will often use a sequence of operations each with their own ``Input A\" box specific to that operation.\nThis reuse of ``A\" does not indicate any relation between those input values.\nThe use of ``A\" is merely a convention for indicating how the input-indicating box and the effect-indicating box are supposed to combine to form a single operation.\n\nIn the case of operations parametrized by compile-time constants, diagrams will use the letters ``K\" and/or ``R\".\nFor example, a box showing ``+K (mod R)\" refers to the modular-offset operation $|x\\rangle \\rightarrow |x+K \\pmod{R}\\rangle$.\nWe use $R$ to refer to the modulus in modular-arithmetic operations, and to the value that is factored by Shor's algorithm.\nIn several constructions we assume that $R$ is odd.\nRemoving factors of 2 from a factoring problem is trivial, so this assumption does not decrease the generality of the overall construction.\n\nBecause adding a constant into a register is more expensive than adding one register into another, we avoid ambiguity between the two operations by always referring to the operation that adds a constant as an ``offset operation\".\nWe will refer to the operation that adds one register into another as just ``addition\" or, if needed for clarity, ``enregistered addition\".\n\nWhen an operation is controlled by a wire bundle, it is conditioned on all wires in the bundle.\nWhen a single-qubit gate is applied to a wire bundle, the gate applies separately to every wire.\nFor example, when a NOT gate controlled by one wire bundle is applied to another wire bundle, every wire in the latter is toggled when and only when every wire in the former is on.\n\nFor completeness, even when the period finding reduction doesn't require a controlled version of an operation, we nevertheless provide a controllable construction that scales linearly with the number of controls.\n\nFor brevity, we take for granted that each circuit's inverse operation is decomposed into the same operations as the original operation but run in reverse order and with each sub-operation inverted.\nA decrement is a reversed increment, a multiply-add is a reversed multiply-subtract, a modular division is a reversed modular multiplication, a modular halving is a reversed modular double, and so forth.\n\nWe do not attempt to define or implement reasonable behavior for modular arithmetic circuits applied to out of range values (ones equal to or larger than the modulus).\nThis {\\em includes input values}.\nFor example, if our modular addition construction ($x \\mathrel{{+}{=}} y \\pmod{R}$) is applied to a $y \\geq R$, then we don't guarantee that $y \\mod R$ will be added into $x$, that the operation will commute with other additions, that optimizations won't change the behavior, or that anything sensible at all will happen.\nIf the precondition $y < R$ is violated, what occurs is undefined behavior \\cite{c11}.\n\n\n\\section{Constructions} \\label{sec:construct}\n\nOur reduction, from the period finding step of Shor's algorithm down to constant-sized gates, uses many circuit constructions.\n\\autoref{fig:dependencies} shows an overview of the various operations we will use, and the path through them that we will take.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[height=17.3cm]{assets/dependencies.png}\n  \\caption{\n    Graph of the transitive reduction of dependencies between constructions in our paper.\n    Edge labels indicate which constructions use a dependency more than a constant number of times.\n  }\n  \\label{fig:dependencies}\n\\end{figure}\n\n\\subsection{Period Finding for Modular Exponentiation}\n\n\\begin{figure}\n  \\centering\n  \\makebox[\\linewidth]{\n    \\includegraphics[width=\\linewidth]{assets/shor-period-finding.png}\n  }\n  \\caption{\n\tHigh-level definition of the period finding circuit \\cite{Shor1999} used by Shor's algorithm.\n\t$R$ is the modulus and the number to be factored, $B$ is a randomly chosen base, $n$ is the number of bits needed to store $R$, and $p \\in \\Theta(n)$ controls the precision of the phase estimation step.\n    The triangles indicate how many ancillae are needed ``behind the scenes\", by our constructions, to perform an operation.\n\tRecovering the period requires classical post-processing of the sampled output.\n  }\n  \\label{fig:period-finding}\n\\end{figure}\n\nA high-level view of the circuit for period finding applied to modular exponentiation, the core quantum subroutine of Shor's quantum factoring algorithm \\cite{Shor1999}, is shown in \\autoref{fig:period-finding}.\n\nBefore the quantum circuit is constructed, a base $B$ is chosen at random.\nThe randomly chosen $B$ must be co-prime to $R$.\nWhen a $B$ that is not co-prime to $R$ is accidentally chosen, the lucky victim can instead factor $R$ by recursively factoring $R_1 = \\gcd(B, R)$ and $R_2 = R / \\gcd(B, R)$.\n\nThe circuit begins by preparing a uniform superposition $|\\psi_0\\rangle = \\sqrt{2^{-n}} \\sum_{k=0}^{2^n-1} |k\\rangle$, then uses the $\\times B^A {\\pmod R}$ operation to separate that superposition into equivalence classes modulo the unknown period $l$ of this operation.\nThat is to say, w.l.o.g. the state ends up equal to $|\\psi_{1,x}\\rangle = \\sqrt{l 2^{-n}} \\sum_{k=0}^{\\approx (2^n/l)-1} |l k + x \\rangle$ for some $x$.\nThe circuit then applies an inverse Fourier transform to the state.\nFourier transforming a uniform signal with period $l$ produces a spectrum with peaks near $N \\cdot 0/l$, $N \\cdot 1/l$, $N \\cdot 2/l$, ..., $N \\cdot (p-1)/l$.\nShor's algorithm recovers the period $l$ by sampling values $s_i$ from this spectrum, then using a continued fractions algorithm to compute the denominator of the fraction (with denominator below $R$) that is closest to $s_i/N$.\n\nBecause period-finding measures all qubits immediately after performing a QFT, most of the transformed qubits can be measured earlier than shown.\nIn fact, each qubit can be measured so early that the next qubit needed for the QFT does not even need to be initialized yet!\nOnly one of the qubits in the phase-estimation register needs to be present at a time, and so the phase register can be reduced to a single repeatedly-used qubit \\cite{zalka1998, mosca1999, parker2000, beauregard2003}.\n\\autoref{fig:period-finding-solo-phase-qubit} shows a period-finding circuit with this property.\nIt uses (a) controlled modular multiplication, (b) measurement, (c) X-axis rotations classically parametrized by previous measurements, and (d) qubit resets.\nThe only non-trivial operation is (a), the controlled modular multiplication of an $n$-qubit register.\n\nWe perform modular multiplication with modular scaled-addition operations and an ancilla register as in \\cite{beauregard2003}.\nHowever, to allow our ancilla register to be mostly dirty, we extend the operation so that it has a well defined effect on the second register: multiplying by the inverse factor.\nWe will refer to this combined operation as a ``bimultiply\".\n\nThe bimultiplications we perform throughout the algorithm do change the value of the ancilla register, but after the usual end of the circuit we can undo the damage.\nThe key insight is that the work register is initialized to $|1\\rangle$ and gets multiplied by constants inverse to the ones trashing the dirty ancilla register.\nInstead of discarding the work register after performing phase estimation, as is normally done, we have a use for it.\nWe measure the work register to recover the fixup factor needed to restore the dirty register's original value.\n\\autoref{fig:period-finding-solo-phase-qubit-explicit-dirty-register} shows this construction.\n\nBecause our modular circuit constructions would have undefined behavior if any register had a value equal to or larger than $R$, we need the ancilla register to contain a value less than $R$.\nWe ensure this by requiring that the ancilla register's MSB be $|0\\rangle$ (i.e. clean) and that the registers be as small as possible (i.e. have size $n = \\lceil \\lg_2(R) \\rceil$).\n\n\\begin{figure*}\n  \\centering\n  \\makebox[\\linewidth]{\n    \\includegraphics[width=\\linewidth]{assets/shor-period-finding-solo-phase-qubit.png}\n  }\n  \\caption{\n\tPeriod finding with a single phase-estimation qubit \\cite{beauregard2003}.\n\tThe small oplus' ({\\tiny $\\oplus$}) are ``X-axis controls\".\n\tAn X-axis control is equivalent to a normal control, but with a Hadamard gate applied before and after.\n\tIt conditions on the state $\\frac{1}{\\sqrt 2}|0\\rangle - \\frac{1}{\\sqrt 2}|1\\rangle$ instead of on the state $|1\\rangle$.\n  }\n  \\label{fig:period-finding-solo-phase-qubit}\n\\end{figure*}\n\n\\begin{figure*}\n  \\centering\n  \\makebox[\\linewidth]{\n    \\includegraphics[width=\\linewidth]{assets/shor-period-finding-solo-phase-qubit-double-register.png}\n  }\n  \\caption{\n\tPeriod finding with a single phase-estimation qubit and paired inverse multiplications (``bimultiplications\").\n\tUses $O(n^3 \\lg n)$ gates, $O(n^3)$ depth, and no additional qubits beyond those shown.\n  }\n  \\label{fig:period-finding-solo-phase-qubit-explicit-dirty-register}\n\\end{figure*}\n\n\n\\subsection{Modular Bimultiplication}\n\nAs in \\cite{beauregard2003}, we perform controlled modular multiplication with a second register and modular scaled-addition operations.\nHowever, to allow the second register to be dirty, we use an additional scale-add as well as a negation operation as in \\cite{zalka2006}.\nSee \\autoref{fig:controlled-modular-multiply} for the circuit diagram.\n\nTo show that the circuit works, suppose that the two registers start in the state $(x, y)$, working modulo $R$.\nWe scale-add the first register times $K$ into the second register to produce the state $(x, y+xK)$.\nThen a scale-subtract times $K^{-1}$ out of the first register puts the system into the state $(x-yK^{-1}-xKK^{-1}, y+xK)$, which is just $(-yK^{-1}, y+xK)$.\nNext, we cancel the $y$ term in the second register by scale-adding the first register times $K$ into it again, leaving $(-yK^{-1}, y+xK-yK^{-1} \\cdot K)$ which is simply $(-yK^{-1}, xK)$.\nFinally, we swap the terms and negate the second term to get $(xK, yK^{-1})$ as desired.\n\nIn the case where $K$ has no multiplicative inverse modulo $R$, this construction will not work (it would define an invalid irreversible operation).\nHowever, that would mean $K$ is a factor of $R$; a case that can be checked for and handled classically before bothering to factor $R$ with a quantum computer.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=\\linewidth]{assets/controlled-modular-multiply.png}\n  \\caption{\n    Controlled modular bimultiplication, with a constant multiplier $K$, using three modular scaled-additions and a swap.\n    $K$ must have a multiplicative inverse modulo $R$.\n    Uses no ancillae, $O(c + n^2 \\lg n)$ gates, and $O(c + n^2)$ depth where $c$ is the number of controls and $n$ is the register size.\n    The negation operation requires 2 dirty ancillae, but notice there are free wires in the other register that can be borrowed, so the overall construction requires no additional dirty ancilla (for non-trivial $n$).\n  }\n  \\label{fig:controlled-modular-multiply}\n\\end{figure}\n\n\n\\subsection{Modular Scaled-Addition}\n\nTo perform modular scale-add operations, we use a shift-and-add approach similar to \\cite{beauregard2003}.\nWe right-shift (i.e. divide by $2 {\\pmod R}$) the target register $n-1$ times, then begin iteratively left-shifting (i.e. multiplying by $2 {\\pmod R}$) and adding $K$ into the target.\nWe condition the first modular addition on the most significant bit of the input, the second addition on the next most significant bit, and so forth.\n(The more significant bits go first because their effects must be hit by more left-shifts.)\nSee \\autoref{fig:controlled-modular-scale-accumulate}.\n\nThe conditional offset and modular doubling operations need a dirty bit, but for non-trivial $n$ there are more than enough unused bits available to borrow, so the circuit as a whole doesn't require any dirty bits.\n\nNote that the modular doublings (and halvings) require $R$ to be odd, since otherwise the operation would be irreversible.\nHowever, given that in the intended use case $R$ is a number to be factored, it is reasonable to require callers to have factored out multiples of two beforehand.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=\\linewidth]{assets/controlled-modular-multiply-accumulate.png}\n  \\caption{\n    Reducing a controlled modular scale-add, with a constant multiplier $K$, into the modular equivalent of shift-and-add.\n    Requires the modulus $R$ to be odd.\n    Uses no ancillae, $O(c + n^2 \\lg n)$ gates, and $O(c + n^2)$ depth where $c$ is the number of controls and $n$ is the register size.\n  }\n  \\label{fig:controlled-modular-scale-accumulate}\n\\end{figure}\n\n\n\\subsection{Modular Doubling}\n\nTo multiply a register by 2 modulo an odd $R$, we note that the permutation this operation performs is to take the values from $[(R+1)/2, R)$, the top-half of the valid range, and interleave them between the values from $[0, (R+1)/2)$, the bottom-half of the valid range.\n\nWe can perform this interleaving by moving the valid-top-half up until it starts at $2^{n-1}$, i.e. aligns with the MSB boundary.\nA left-rotate of the register bits then moves the MSB to the LSB, converting the alignment into interleaving.\n\nBecause it's expensive to perform an offset that affects values above $R/2$ while leaving values below $R/2$ alone, the circuit shown in \\autoref{fig:modular-double} uses a different alignment strategy.\nIt starts by offset-ing the whole range down by $\\lceil R/2 \\rceil$, which wraps the valid-bottom-half of the input around to the top of the register's range.\nThis offset also aligns what was originally the valid-top-half against the bottom of the register range.\nThen the circuit uses a controlled offset to move just the top half of the register (including the invalid range above $R$) up by $\\lceil R/2 \\rceil$, re-wrapping what was originally the valid-bottom-half past the top and around to the middle, aligning it with the MSB boundary.\nThe circuit then toggles the MSB, fixing the fact that, although the valid-top-half is aligned with 0 and the valid-bottom-half is aligned with $2^{n-1}$, that's exactly the reverse of what we want.\nWith the desired alignment achieved, the circuit interleaves the two halves with a left-rotate.\n\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=\\linewidth]{assets/controlled-modular-double.png}\n  \\caption{\n    Controlled modular doubling.\n    $R$ must be odd.\n    Uses 1 dirty ancilla, $O(c + n \\lg n)$ gates, and $O(c + n)$ depth, where $c$ is the number of controls and $n$ is the register size.\n  }\n  \\label{fig:modular-double}\n\\end{figure}\n\n\n\\subsection{Pivot-Flips} \\label{sec:pivot-flips}\n\nWe will implement both modular negation and modular offset/addition in terms of a non-standard operation we call a ``pivot-flip\".\nA pivot-flip is an operation that reverses the order of states less than a given pivot value, without affecting other states.\nFor example, a pivot-flip with the pivot equal to 4 would swap $|0\\rangle$ and $|3\\rangle$, swap $|1\\rangle$ and $|2\\rangle$, and leave all other states untouched.\n\nThe exact permutation performed by a pivot-flip with pivot equal to $K$ is:\n\n$$\\text{PivotFlip}_K = \\sum_{i=0}^{K-1} |K-i-1\\rangle \\langle i| + \\sum_{i=K}^{N-1} |i\\rangle \\langle i|$$\n\nTo perform a pivot-flip efficiently, we use the fact that $x \\rightarrow \\lnot(x - K)$ nearly does what is required: it flips the range below $K$ but unfortunately also flips the range above-and-including $K$.\nIt's a ``bi-flip\".\n\nThe bi-flip operation is its own inverse, so it can be ``toggle-controlled''.\nIf we apply two bi-flips controlled by the same control qubit, then toggling the control qubit determines whether or not a bi-flip is applied to the target register.\nWhen the control qubit stays off, neither bi-flip fires and nothing happens to the target.\nWhen the control qubit stays on, both bi-flips fire and they undo each other.\nBut if the control qubit is toggled after the first bi-flip but before the second, then exactly one of them will fire and the target register ends up bi-flipped.\n\nAnother useful property of a bi-flip is that it doesn't move any states across the pivot.\nA bi-flip at $K$ preserves $x<K$ for all $x$.\nThis allows the toggling of the control qubit, that determines whether a toggle-controlled bi-flip will happen, to be based on a comparison of the pivot against the target register we are operating on.\nEven at points where the target may or may not have been bi-flipped.\n\nSee \\autoref{fig:controlled-pivot-flip} and \\autoref{fig:controlled-const-pivot-flip} for the circuit diagrams.\nFor states that are less than the pivot, the comparison against the pivot keeps toggling the ancilla and exactly one of the controlled bi-flips will fire.\nFor states equal to or larger than the pivot, the ancilla does not get toggled and so the bi-flips undo each other.\nTherefore only the range below the pivot is flipped.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=\\linewidth]{assets/controlled-pivot-flip.png}\n  \\caption{\n    Controlled pivot-flip circuit with an enregistered pivot.\n    The target register can be larger than the input register, but not smaller.\n    Uses $2$ dirty ancillae, $O(c + m \\lg m)$ gates, and $O(c + m)$ depth where $c$ is the number of controls, $n$ is the size of the input register, $e$ is the extra size of the target register, and $m=n+e$ is the size of the target register.\n  }\n  \\label{fig:controlled-pivot-flip}\n\\end{figure}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=\\linewidth]{assets/controlled-const-pivot-flip.png}\n  \\caption{\n    Controlled pivot-flip circuit with a constant pivot.\n    Uses $2$ dirty ancillae, $O(c + n \\lg n)$ gates, and $O(c + n)$ depth where $c$ is the number of controls and $n$ is the register size.\n  }\n  \\label{fig:controlled-const-pivot-flip}\n\\end{figure}\n\n\n\\subsection{Modular Addition / Offset}\n\nAs shown in \\autoref{fig:mod-add-from-pivot-flip-bars}, a modular addition can be implemented by three pivot-flips.\nTo add $K$ into a register modulo $R$, perform pivot-flips with the pivot at $R-K$, then $R$, then $K$.\nSee \\autoref{fig:controlled-modular-add} for the circuit.\n(An optimization we don't show is that, because the values above $R$ don't matter, the pivot-flip at $R$ can be replaced by a bi-flip.)\n\nInterestingly, controlled modular addition can borrow its own controls as dirty bits.\nFor modular offset (i.e. adding a compile-time constant into a register), the two dirty bits are required whether or not the operation is controlled.\nSee \\autoref{fig:controlled-modular-offset}.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=\\linewidth]{assets/mod-add-from-pivot-flip-bars.png}\n  \\caption{\n     Modular addition of $A \\pmod{R}$ can be done with three pivot flips.\n     One at $R-A$, then one at $R$, then one at $A$.\n     Requires $A \\leq R$.\n   }\n  \\label{fig:mod-add-from-pivot-flip-bars}\n\\end{figure}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=\\linewidth]{assets/controlled-modular-addition.png}\n  \\caption{\n    Controlled modular addition construction based on pivot-flips.\n    The arithmetic being performed on the input register temporarily transitions it from storing $x$ to $R-x$ for the first pivot flip.\n    Because $R$ is a compile-time constant, $R+1$ is also a compile-time constant and the $+R+1$ operation is a normal offset operation.\n    All arithmetic is two's complement, i.e. modulo $2^n$.\n    Uses $2-c$ dirty ancillae, $O(c + n \\lg n)$ gates, and $O(c + n)$ depth where $c$ is the number of controls and $n$ is the register size.\n  }\n  \\label{fig:controlled-modular-add}\n\\end{figure}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=\\linewidth]{assets/controlled-modular-offset.png}\n  \\caption{\n    Controlled modular offset construction based on pivot-flips.\n    Uses $2$ dirty ancillae, $O(c + n \\lg n)$ gates, and $O(c + n)$ depth where $c$ is the number of controls and $n$ is the register size.\n  }\n  \\label{fig:controlled-modular-offset}\n\\end{figure}\n\n\n\\subsection{Modular Negation}\n\nTo negate a number mod $R$, we need to reverse the order of the states $|1\\rangle$ to $|R-1\\rangle$.\nWe do so by temporarily moving $|0\\rangle$ out the way with a decrement, pivot-flipping at $R-1$, then undoing the decrement.\nSee \\autoref{fig:negate-mod}.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=\\linewidth]{assets/negate-mod.png}\n  \\caption{\n    Controlled modular negation.\n    Uses $2$ dirty ancillae, $O(c + n \\lg n)$ gates, and $O(c + n)$ depth where $c$ is the number of controls and $n$ is the register size.\n  }\n  \\label{fig:negate-mod}\n\\end{figure}\n\n\n\\subsection{Comparison}\n\nComparison operations toggle a target bit based on the relationship between two input registers.\nWe implement comparisons as in \\cite{takahashi2005}, using an addition followed by a slightly smaller subtraction that clears all changes except the overflow signal into the target bit.\nSee \\autoref{fig:compare}.\n\nFor comparisons against another register this approach uses $1$ dirty ancilla (if controlled, otherwise no ancillae), $O(c + n)$ gates, and $O(c + n)$ depth.\nFor comparisons against a constant, the number of gates increases to $O(c + n \\lg n)$ and an extra dirty ancilla is required.\n\nWhen $n$ dirty qubits are available, the overflow-predicting construction from \\cite{haner2016} with better constant factors can be used instead.\n\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=\\linewidth]{assets/comparison-less-const.png}\n  \\caption{\n    Controlled comparison.\n    Uses $2$ dirty ancillae, $O(c + n \\lg n)$ gates, and $O(c + n)$ depth where $c$ is the number of controls and $n$ is the register size.\n  }\n  \\label{fig:compare}\n\\end{figure}\n\n\n\\subsection{Addition / Offset}\n\n\\cite{takahashi2005} provides a reversible adder circuit that uses $O(n)$ gates, $O(n)$ depth, and no ancillae.\nWe show an equivalent circuit in \\autoref{fig:inlineadder}.\n\nBecause the construction in \\autoref{fig:inlineadder} uses the input register as workspace, it doesn't work when the input is a compile-time constant or when the target register is larger than the input register.\n(When the target register is smaller, we simply ignore the high bits of the input due to overflow wraparound.)\nThis is a problem for us, because some of our constructions add constants into register (e.g. modular scale-add), and some others add inputs into larger target registers (e.g. comparison).\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=\\linewidth]{assets/inline-adder.png}\n  \\caption{ Adder for input and target registers of the same size.\n  Requires no ancillae, and uses $O(n)$ gates and depth.\n  Based on \\cite{van2004, takahashi2005}.}\n  \\label{fig:inlineadder}\n\\end{figure}\n\nWhen the value to be added into a register is a compile-time constant (i.e. when applying an offset gate), we use the offset construction from \\cite{haner2016}.\nTheir offset circuit, shown in \\autoref{fig:offset}, uses $O(n \\lg n)$ gates, $O(n)$ depth, and one dirty ancilla.\n\nWhen the target register is larger than the input register, the addition circuit in \\autoref{fig:inlineadder} can be modified without increasing the asymptotic cost.\nWe do this by removing the surrounding CNOTs and adding three increment/decrement operations to the circuit, as follows.\n(Note that, to avoid cyclic dependencies, the increment and decrement constructions described in the next subsection will only use the same-register-size adder.)\n\nFirst, because there are many target bits not reached by the time we have swept through the entire input register, carry signals aren't reaching the high bit of the target register.\nWe fix this by replacing the innermost CNOT, the carry-propagating CNOT, with a controlled increment.\nSecond and third, because we're using the MSB of the input register as the carry signal, it causes an increment at the LSB instead of at the correct position.\nWe undo the LSB increment with a controlled decrement, and use a controlled increment to apply the MSB's effect where it should have actually gone.\nSee the circuit diagram in \\autoref{fig:inline-adder-into-large}.\n\nTo control addition gates, and offset gates, we use ``commutator controlling\": finding operations $G$ and $H$ such that their group-theory commutator $[G, H] = G \\cdot H \\cdot G^\\dagger \\cdot H^\\dagger$ equals a desired operation $U$ and either $G$ or $H$ can be efficiently controlled.\nIn particular, we focus on the case where $G^2 = U$ and $H$ satisfies $H \\cdot G \\cdot H^\\dagger = G^\\dagger$ (i.e. framing $G$ with $H$ inverts the effect of $G$).\n\nIn the case of addition, we have the property $\\lnot (\\lnot x + K) = \\lnot (-x - 1 + K) = -(-x - 1 + K) - 1 = x-K$.\nSo a valid inverting operation $H$ for addition is a NOT gate applied to every target wire; $H=X^{\\otimes n}$.\nIf we then consider $G=\\text{S}_{\\text{-} K}$, where $S$ is an offset-by-subscript operation, we find that $[G, H] = [\\text{S}_{-K}, X^{\\otimes n}] = \\text{S}_{2K}$.\nWe can control this constructed $\\text{S}_{2K}$ operation by adding controls only to the multi-not operation $H$, which is cheap to do.\nTo add $K$ instead of $2K$, we temporarily prepend a dirty LSB onto the target register.\nWe show this construction in \\autoref{fig:controlled-addition}.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=\\linewidth]{assets/offset.png}\n  \\caption{\n      Offset circuit from \\cite{haner2016}.\n      $e$ is either 0 or 1.\n      Uses $1$ dirty ancilla, $O(n \\lg n)$ gates, and $O(n)$ depth (by overlapping the recursive cases).\n  }\n  \\label{fig:offset}\n\\end{figure}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=\\linewidth]{assets/inline-adder-into-large.png}\n  \\caption{\n      Adder with target larger than source, using no ancillae.\n      Uses $O(n)$ gates and depth.\n      The increment and decrement gates all have at least one free wire to borrow as a dirty ancilla.\n  }\n  \\label{fig:inline-adder-into-large}\n\\end{figure}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=\\linewidth]{assets/controlled-addition.png}\n  \\caption{\n    Reducing controlled addition to uncontrolled addition.\n    Uses $O(c + m)$ gates, $O(c + m)$ depth, and a dirty ancilla.\n    When applied to offset gates, uses $O(c + m \\lg m)$ gates, $O(m + c)$ depth, and two dirty ancillae.\n    $c$ is the number of controls, $n$ is the size of the input, and $m > n$ is the size of the target register.\n  }\n  \\label{fig:controlled-addition}\n\\end{figure}\n\n\n\\subsection{Increment}\n\nA register can be incremented by subtracting both $x$ and $\\neg x = -x-1$ from it, for any $x$.\nWhen $n$ dirty bits are available, $x$ can come from a register defined by those $n$ arbitrary bits, as shown in \\autoref{fig:increment-many-dirty}.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=\\linewidth]{assets/increment-many-dirty.png}\n  \\caption{ Subtracting $x$ and $-x-1$ from a register increments it. Requires $O(n)$ depth and size, and $n$ dirty ancillae.}\n  \\label{fig:increment-many-dirty}\n\\end{figure}\n\nTo improve from $n$ dirty bits to the single dirty bit used by the circuit in \\autoref{fig:controlled-increment-odd}, we break the register into two halves.\nA high-half that is incremented only if all of the low bits are on, and a low-half that is unconditionally incremented.\n\nIf the increment is uncontrolled, the low-half can be incremented with the double-subtraction trick by borrowing the high-half.\nWhen there are controls, we instead increment the low-half using a commutator-control construction where one operation subtracts the ancilla register out of the target and the other applies a NOT gate to every input wire and target wire.\nThis works because $\\lnot (\\lnot T + \\lnot K) - K = \\lnot (-T - 1 - K - 1) - K = (T+2+K) - 1 - K = T + 1$.\n\nThe high-half is trickier to deal with.\nWe want to borrow the low-half for the double-subtraction trick, but the low-half is being used as a control and so can't be borrowed.\nTo work around not being able to operate on the borrowed low-half bits while using them as a control, we use more commutator control tricks and some knowledge of what state the low-half must be in if operations it is controlling are firing.\n\nWe add and subtract the low-half out of the high-half, but frame the addition with NOT gates controlled by all bits in the low half.\nWhen any of the bits in the low-half are off, the NOT gates don't fire and the addition and subtraction will cancel each other.\nWhen all of the bits in the low-half are on, i.e. when the low-half is storing the two's complement representation of -1, the NOT gates do fire.\nThis inverts the addition into a subtraction, and the low-half (which is storing -1) is subtracted out of the high-half twice.\nTherefore the high-half was incremented by 2.\nTo halve the +2 into a +1, we prepend a dirty LSB onto the target register.\n\nRecall that, earlier in the paper, we used increments and decrements to implement addition where the target was larger than the input.\nTo avoid an expensive cyclic dependency in our increment construction, the additions we use must not be larger-target additions.\n(Also, when the two registers are not the same size, they define arithmetic modulo different powers of 2.\nThis breaks properties such as $T + \\lnot K = T - K - 1$.)\n\nBecause we can only perform additions and subtractions with input and target registers of the same size, the construction described so far in this section only works for odd-sized registers.\nTo handle even-sized registers, we decompose the increment into a controlled-increment and a NOT gate.\nWe use the LSB as a control determining whether the (odd-sized) rest of the register is incremented, and then toggle the LSB.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=\\linewidth]{assets/controlled-increment-odd.png}\n  \\caption{\n    Odd-sized controlled increment.\n    For the even-sized case, separate the LSB from the rest of the register, increment the rest of the register using the LSB as an extra control, then toggle the LSB.\n    Uses $O(c+n)$ gates, $O(c+n)$ depth, and 1 dirty ancilla.\n  }\n  \\label{fig:controlled-increment-odd}\n\\end{figure}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=\\linewidth]{assets/ancilla-bootstrap.png}\n  \\caption{ Bootstrapping a dirty ancilla out of an increment gate using quantum operations.\n  The $i^{\\text{frac}}$ gate is a ``phase gradient\" operation that phases each computational basis state $|v\\rangle$ by an amount proportional to $v/2^d$, where $d$ is the size of the register.\n  In this case each state is phased by $e^{i \\frac{\\pi}{2} v/2^d}$.\n  The phase gradient is implemented by a column of $Z^{2^{-k}}$ gates.}\n  \\label{fig:bootstrap-ancilla}\n\\end{figure}\n\n\n\\subsection{Bit Swaps, Rotations, and Reversals}\n\nBit permuting operations can usually be emulated by re-labelling qubits, so they are easy to overlook in circuits.\nBut some of our circuit diagrams have used controlled bit rotations which require actual gates.\nWe provide the relevant constructions in \\autoref{fig:bit-rotate} and \\autoref{fig:bit-reverse}.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=\\linewidth]{assets/controlled-bit-rotate.png}\n  \\caption{\n    A controlled bit rotation / bit swap is three controlled bit-reverses.\n    Uses no ancillae, $O(c + n)$ gates, and $O(c + n)$ depth.\n  }\n  \\label{fig:bit-rotate}\n\\end{figure}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=\\linewidth]{assets/controlled-reverse.png}\n  \\caption{\n    Inline controlled bit order reversal on an odd-sized register of size $n=2k+1$, and on an even-sized register of size $n=2k+2$.\n    Each XOR operation is a series of independent CNOTs (note that the inputs have opposite endian-ness to the outputs).\n    Uses no ancillae, $O(c + n)$ gates, and $O(c + n)$ depth.\n  }\n  \\label{fig:bit-reverse}\n\\end{figure}\n\n\n\\subsection{Multi-Nots}\n\nSeveral of our constructions have used CNOTs applied to wire bundles, with many controls and many targets.\nA naive approach to implementing these operations would be to apply a separate NOT, each controlled by every control, to every target.\nBut this would use $O(n \\cdot c)$ gates, which is not linear in the number of controls.\n\nTo avoid paying the overhead of $c$ controls for every target, we toggle {\\em one} target conditioned on all of the controls.\nWe then use toggle-controlling to spread the toggling effect to all of the other targets.\n\nTo efficiently reduce the single remaining CNOT with $c$ controls into constant-sized Toffoli gates, we take advantage of the many available dirty ancilla.\nSee \\autoref{fig:multi-not} and \\autoref{fig:cnot-reduction}.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=\\linewidth]{assets/multi-cnot-to-single-cnots.png}\n  \\caption{\n    Reducing a many-control many-target CNOT into one many-control single-target CNOT and many single-target single-control CNOTs.\n    Uses no ancillae, $O(c + n)$ gates, and $O(c + n)$ depth where $n$ is the number of targets and $c$ is the number of controls.\n    The depth can be reduced to $O(c + \\lg n)$ by spreading the toggling effect more intelligently.\n  }\n  \\label{fig:multi-not}\n\\end{figure}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=\\linewidth]{assets/cnot-reduction.png}\n  \\caption{\n    When $c-2$ dirty ancillae are available, a controlled-not with $c$ controls can be reduced into $4c - 8$ Toffoli gates \\cite{barenco1995}.\n    It is possible to reduce the number of ancilla needed to just one, by using twice as many Toffoli gates, but that construction isn't needed in the context of period finding because there are always enough unused qubits to borrow.\n  }\n  \\label{fig:cnot-reduction}\n\\end{figure}\n\n\\section{Overview and Improvements} \\label{sec:costs}\n\n\\begin{figure*}\n  \\centering\n  \\makebox[\\linewidth]{\n    \\begin{tabular}{ l | c c c c c l }\n       & Year & Depth & Gates & Clean Qubits & Total Qubits \\\\\n      \\hline\n      Shor \\cite{Shor1999} & 1994 & $\\Theta(n M(n))$ & $\\Theta(n M(n))$ & $\\Theta(n)$ & $\\Theta(n)$ \\\\\n      Beckman et al. \\cite{beckman1996} & 1996 & $\\Theta(n^3)$ & $\\Theta(n^3)$ & $5n + 1$ & $5n + 1$ \\\\\n      Veldral et al. \\cite{vedral1996} & 1996 & $\\Theta(n^3)$ & $\\Theta(n^3)$ & $4n + 3$ & $4n + 3$ \\\\\n      Beauregard \\cite{beauregard2003} & 2003 & $\\Theta(n^3 \\lg \\frac{1}{\\varepsilon})$ & $\\Theta(n^3 \\lg \\frac{n}{\\varepsilon} \\lg \\frac{1}{\\varepsilon})$ & $2n+3$ & $2n+3$ \\\\\n      Takahashi et al. \\cite{takahashi2006} & 2006 & $\\Theta(n^3 \\lg \\frac{1}{\\varepsilon})$ & $\\Theta(n^3 \\lg \\frac{n}{\\varepsilon} \\lg \\frac{1}{\\varepsilon})$ & $2n+2$ & $2n+2$ \\\\\n      Zalka \\cite{zalka2006} & 2006 & $\\Theta(n^3 \\lg \\frac{1}{\\varepsilon})$ & $\\Theta(n^3 \\lg \\frac{n}{\\varepsilon} \\lg \\frac{1}{\\varepsilon})$ & $1.5n+O(1)$ & $1.5n+O(1)$ \\\\\n      H\\\"{a}ner et al. \\cite{haner2016} & 2016 & $\\Theta(n^3)$ & $\\Theta(n^3 \\lg n)$ & $2n+2$ & $2n+2$ \\\\\n      (ours) & 2017 & $\\Theta(n^3)$ & $\\Theta(n^3 \\lg n)$ & $n+2$ & $2n+1$ \\\\\n    \\end{tabular}\n  }\n  \\caption{\n    Space-efficient constructions of Shor's algorithm over time.\n    The table only includes papers that presented explicit circuit constructions and improved the minimum number of qubits required to perform the algorithm (or else the time complexity at a slightly larger qubit count).\n    $M(n)$ is the classical time-complexity of multiplication, which is known to be asymptotically at most $n \\cdot (\\lg n) \\cdot 2^{O(\\lg^* n)}$ \\cite{furer2007}.\n    $\\varepsilon$ is the maximum error when synthesizing the circuit out of a fixed set of universal gates, which is asymptotically relevant for algorithms that use Draper addition \\cite{draper2000} (i.e. applying phase gradients in frequency space) instead of Toffoli-based addition/offset constructions.\n  }\n  \\label{fig:table-over-time}\n\\end{figure*}\n\n\nRecall that \\autoref{fig:dependencies} shows a dependency graph of the constructions discussed in this paper.\nOur asymptotic costs are dominated by performing $O(n)$ modular multiplications, each of which uses $O(n)$ modular additions and offsets, each of which uses $O(n \\lg n)$ constant-sized classical gates \\cite{haner2016} and $O(n)$ depth.\nThe total cost of the period-finding step in Shor's algorithm, using our construction, is $O(n^3 \\lg n)$ gates and $O(n^3)$ depth.\n\nIn \\autoref{fig:table-over-time} we show how the number of qubits needed for Shor's algorithm has improved over time.\nOur main improvements over previous arithmetic constructions are 1) the use of pivot-flips for modular addition, 2) the use of dirty bimultiplication for modular multiplication, and 3) the $O(n)$ incrementer requiring only a single dirty ancilla.\n\nPrevious modular addition constructions worked by temporarily storing an is-wraparound-needed comparison in a clean ancilla \\cite{takahashi2006, haner2016}.\nPivot flips also require ancillae, but the ancillae can be dirty and, in the context of Shor's algorithm, there are always qubits available to borrow whenever a pivot-flip is needed.\nThis improvement ends up saving a qubit, reducing the total number of qubits we would have needed from $2n+2$ as in \\cite{haner2016} to $2n+1$.\n\nPrevious modular multiplication constructions did not work with a dirty ancilla register.\nThey either required a clean ancilla register because they leaked the ancilla register into the work register \\cite{haner2016}, or else a trashable ancilla register because there was no way to undo the damage being done by the multiplications \\cite{zalka2006}.\nThe leakage problem is fixed by adding an extra scale-add operation and a negation operation \\cite{zalka2006}.\nWe fixed the trashing problem by measuring the work register at the end of the circuit, and using its value to drive a clean-up multiplication that restores the ancilla register.\nThis improvement allows $n-1$ of the qubits in the ancilla register to be dirty.\nThe MSB has to stay clean to ensure the register's value is less than the modulus being factored.\n\nPrevious published incrementers (not counting an unpublished version of our construction being cited by \\cite{haner2016}) required either $O(n^2)$ gates or $\\omega(1)$ ancillae \\cite{draper2000, barenco1995}.\nOur classical incrementer construction uses $O(n)$ gates and a single dirty ancilla.\n\nNote that, for classical reversible computation, 1 dirty ancilla is the minimum possible for an incrementer.\nAn increment operation on $n$ bits is equivalent to performing a state-permutation that uses $2^n-1$ swaps to sweep the state $|2^n-1\\rangle$ from the top of the state-space to the bottom of the state-space one step at a time.\nNote that $2^n-1$ is odd for non-trivial $n$, and therefore the parity of the state permutation performed by an increment operation is odd.\nHowever, the parity of the permutation performed by any classical gate that doesn't cover the entire circuit is even.\nSince odd-parity permutations can't be implemented by composing even-parity permutations, it is impossible to compose smaller operations into an increment operation that covers every bit.\nAn uncovered bit (i.e. a dirty ancilla) must be present.\n\nWhen quantum operations are available, the parity barrier can be bypassed and incrementing can be performed without any ancilla.\nThe asymptotic cost is slightly worse due to the cost of synthesizing tiny rotations, and the constant factors hidden by the asymptotic notation are also worse.\nSee \\autoref{fig:bootstrap-ancilla} for the construction.\n\nWe used \\href{https://github.com/Strilanc/Quirk}{Quirk} \\cite{quirk2016} to explore \\cite{victor2013}, check, and refine individual constructions.\nThe full construction down to Toffoli gates was tested in \\href{https://github.com/ProjectQ-Framework/ProjectQ}{ProjectQ} \\cite{projq2016}.\nThe python source code for our test implementation, and an issue tracker for submitting errata, can be found online at \\href{https://github.com/Strilanc/PaperImpl-2017-DirtyPeriodFinding}{https://github.com/Strilanc/PaperImpl-2017-DirtyPeriodFinding}.\n\nAlthough the asymptotic costs of our constructions match previous work, the constant factors are significantly worse.\nFor example, our equivalent of a controlled 32-qubit multiplication uses roughly 1.3 million Toffoli gates (the specific number depends on the factor to multiply by, the modulus, whether or not a number of optimizations are used, and whether or not those optimizations apply to a given case).\nThis cost is over an order of magnitude worse than previous work \\cite{haner2016}.\nThe reason for the increased cost is that using dirty ancillae results in more uncomputation work, in repeating some operations twice conditionally to do them once unconditionally, and in less efficient constructions in general.\nThese inefficiencies stack multiplicatively when one construction uses another as a subroutine.\n\n\n\\section{Future Work and Conclusion} \\label{sec:conclusion}\n\nIn this paper we described how to perform various arithmetic operations using only dirty ancilla.\nWe also described various techniques we used to find the constructions: pivot flipping, toggle controlling, commutator controlling, and exploration by directly manipulating circuit diagrams.\nWe showed how these constructions reduce the number of clean qubits required to perform Shor's algorithm from $1.5n+O(1)$ to $n+2$.\n\nOf the $2n+1$ qubits our period-finding construction requires, $1$ is used for the phase estimation qubit, $n$ are used to store the work register, and $n$ are ancillae used to implement modular multiplication in terms of scaled modular addition.\nExcept for multiplication, all our arithmetic constructions use two or fewer dirty ancillae.\nSince we reduce modular scale-addition into operations that have a $\\Theta(n)$ surplus of unused qubits, in context there are always more than enough dirty ancillae available to implement the simpler arithmetic inline.\nBecause there is slack in the simpler arithmetic constructions, improving the overall number of qubits used by Shor's algorithm requires only that we improve the first step of reducing modular multiplication into some other operation.\n\nOne way we could reduce modular multiplication into better operations is by knowing the factorization $p \\cdot q$ of the modulus $R$, with $p$ and $q$ each having size $\\approx n/2$.\nThe Chinese remainder theorem guarantees that $x \\mod R$ could be uniquely represented as the pair of half-sized values $(x \\mod p, x \\mod q)$.\nMultiplications of the half-sized values could use and reuse the same half-sized ancilla register, for a total of three half-sized registers (one for $x \\mod p$, one for $x \\mod q$, and one hopefully-dirty ancilla register).\nDespite the large reduction in the number of ancillae available to the underlying arithmetic operations, each operation would still have more than enough ancillae and contribute no additional ancillae to the overall circuit.\n(Note: because the initial value $x_0 = 1$ is trivial, and the final value is measured or discarded, it's not necessary to implement circuits that translate between the Chinese-remainder representation and the usual 2s-complement representation.)\nOf course, since we use Shor's algorithm to compute the factorization of $R$, using the factorization of $R$ to optimize Shor's algorithm would be paradoxical.\nThe $1.5n$ achieved in \\cite{zalka2006} was done via this kind of method, except that instead of factoring $R$ Zalka factored the value to multiply by and the factoring was done modulo $R$ (by stopping a generalized gcd at a midway point) instead of in $\\mathbb{Z}$.\n\nA second way to reduce modular multiplication into (slightly) smaller operations could be with commutator control.\nNote that the modular Fourier transform inverts the effect of modular multiplication: $QFT_{R} \\cdot (\\times K \\,\\text{mod}\\, R) \\cdot QFT_R^{-1} = (\\times K^{-1} \\,\\text{mod}\\, R)$.\nThis has two useful high-level effects.\nFirst, by applying the bimultiplication gate used in this paper twice, but inverting the effect on the ancilla register for the second application, we can build a proper modular multiplication gate that only affects a single register.\nSecond, we can use commutator control to move controls from the modular multiplication gate onto modular Fourier transform gates.\nAssuming controlled modular QFTs can be performed with fewer ancillae than controlled modular multiplication, we could save a qubit when performing the modular multiplication by borrowing the control qubit.\n\nPossible future improvements aside, in this paper we showed that the number of clean qubits sufficient to perform Shor's algorithm is no more than $n + O(1)$.\nWe consider this to be a step towards a construction for Shor's algorithm that uses only $n + O(1)$ qubits total.\nWe do note, however, that these improvements are of more theoretical than practical interest.\nIn practice, on error corrected quantum computers, the important cost to optimize is the number of T gates.\nIn that sense, the main {\\em practical} contribution of this paper is the improved increment circuit and the demonstration of constructing circuits under tight space constraints.\n\n\n\\section{Acknowledgements}\n\nWe thank Matthew Neeley, Dave Bacon, and Austin Fowler for comments on earlier versions of this paper, from which it greatly benefited.\n\n\n\\bibliographystyle{plain}\n\\bibliography{citations}\n\n\\end{document}\n", "meta": {"hexsha": "3a6087d1b0819c259f55781cca19925cb33e75e8", "size": 51348, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/paper.tex", "max_stars_repo_name": "Strilanc/PaperImpl-PeriodFindCutQubits", "max_stars_repo_head_hexsha": "402d216e5c1641f878153dc604792f529bcb79f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-09-05T13:37:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-01T01:10:35.000Z", "max_issues_repo_path": "doc/paper.tex", "max_issues_repo_name": "Strilanc/PaperImpl-PeriodFindCutQubits", "max_issues_repo_head_hexsha": "402d216e5c1641f878153dc604792f529bcb79f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-09-16T21:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2017-09-19T22:20:58.000Z", "max_forks_repo_path": "doc/paper.tex", "max_forks_repo_name": "Strilanc/PaperImpl-PeriodFindCutQubits", "max_forks_repo_head_hexsha": "402d216e5c1641f878153dc604792f529bcb79f4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-09-27T20:07:34.000Z", "max_forks_repo_forks_event_max_datetime": "2017-09-27T20:07:34.000Z", "avg_line_length": 71.9159663866, "max_line_length": 335, "alphanum_fraction": 0.7616654982, "num_tokens": 12857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.34404329433900654}}
{"text": "\\chapter[Ionisation]{Ionisation}\n \n\n The class G4eIonisation calculates the continuous energy loss\n  due to ionisation and\n simulates the 'discrete' part of the ionisation , the Moller and Bhabha\nscattering or delta ray production by $e^-/e^+$ . The formulae used here\n are the same than those in GEANT3 (\\cite{eion.geant3}).\n\n\\section{Method}\n\nLet: \\[\\frac{d\\sigma(E,T)}{dT}\\]\nbe the differential cross-section\nfor the ejection of an electron with kinetic energy $T$ by an incident\n${e^{\\pm}}$ of total energy $E$ moving in a medium of density $\\rho$.\n Let us denote the value of the {\\em kinetic energy cut-off} or\n {\\em production threshold for $\\delta$-rays} by  $T_{cut}$.\nBelow this threshold the soft\nelectrons ejected are simulated as continuous energy loss by the incident\n$e^+/e^-$, and above it they are explicitly generated.\n\nThe mean value of the energy lost by the incident ${\\rm e^{\\pm}}$ to\nthe soft $\\delta$-rays is:\n\\begin{equation}\nE_{soft}(E,T_{cut})\n= \\int_{0}^{T_{cut}} \\frac{d \\sigma (E,T)}{dT} T \\: dT  \\label{eion.a}\n\\end{equation}\nwhereas the total cross-section for the ejection of\nan electron of energy \\linebreak $T > T_{cut}$ is:\n\\begin{equation}\n\\sigma (E,T_{cut})\n= \\int_{T_{cut}}^{T_{Max}}\\frac{d \\sigma (E,T)} {dT} \\: dT \\label{eion.b}\n\\end{equation}\nwhere $T_{Max}$ is the maximum energy transferable to the free electron:\n\\begin{equation}\n\\label{eion.c}\nT_{Max} = \\left\\{ \\begin{array}{ll}\n             E-m & {for \\hspace{.2cm} e^+}  \\\\\n             (E-m)/2 & {for \\hspace{.2cm} e^- ,} \\\\\n              \\end{array} \\right .\n\\end{equation}\nwhere $m$ is the electron mass.\nThe method of calculation of the continuous energy loss\nand the total cross-section are\nexplained below. \n\n\\section{Continuous energy loss}\nThe integration of \\ref{eion.a} leads to the Berger-Seltzer\nformulae ( see e.g in \n   \\cite{eion.messel}) :\n\n\\begin{equation}\n\\label{eion.d}\n\\frac {dE}{dx} = \\frac{2 \\pi r_0^ 2 mn }{\\beta^2}\n       \\left [\\ln \\frac{2(\\tau + 2)} {(I/m)^2}+ F^{\\pm} (\\tau , \\Delta )\n- \\delta \\right ],\n\\end{equation}\n where\n\n\\[\n\\begin{array}{ll}\n\\gamma           & \\frac{E}{m}                           \\\\\n\\beta^2          & 1-\\frac{1}{\\gamma^2}                  \\\\\n\\tau             & \\gamma-1                              \\\\\n\\tau_c           & \\frac{T_{cut}}{m}           \\\\\n T_{cut}         &  \\mbox{energy cut for} \\: e^{\\pm}      \\\\\n\\tau_{max}       & \\mbox{maximum possible energy transfer in $e^-$ mass:\n  $\\tau$ for $e^+$, $\\tau/2$ for $e^-$}  \\\\\n\\Delta           & \\min(\\tau_c,\\tau_{max})              \\\\\nn                & \\mbox{electron density of the medium}        \\\\\nI                & \\mbox{average mean ionisation energy}        \\\\\n\\delta           & \\mbox{density effect correction}.\n\\end{array}\n\\]\n\nThe functions $ F^{\\pm}$  are given by\n\\begin{equation}\n\\label{eion.e}\nF^+ (\\tau,\\Delta) =\\ln(\\tau\\Delta ) -\n\\frac{\\Delta^2}{\\tau}\\left[\\tau + 2 \\Delta -\n\\frac{3\\Delta^2 y } {2} -\\left(\\Delta - \\frac{\\Delta^3 }{3} \\right) y^2 \n- \\left (\\frac{\\Delta^2}{2} - \\tau\n       \\frac{\\Delta^3}{3} + \\frac{\\Delta^4 } {4} \\right)\n          y^3  \\right]  \n\\end{equation}\n\n\\begin{equation}\n\\label{eion.f}\nF^- (\\tau,\\Delta ) = -1 -\\beta^2 +\\ln \\left [(\\tau - \\Delta)\n\\Delta \\right ] + \\frac{\\tau}{\\tau -\\Delta}+\\frac{\\left [\n\\frac{\\Delta^2}{2} + ( 2\\tau +1) \\ln\n\\left (1- \\frac{\\Delta}{\\tau} \\right ) \\right ]}{\\gamma^2}\n\\end{equation}\n\nwhere $ y = 1/(\\gamma+1) $.\n\nThe density effect correction is calculated according to the\n formalism of Sternheimer ( \\cite{eion.sternheimer}). \n\n\\section{Total cross-sections}\nThe integration of formula \\ref{eion.b} gives the total cross-section\n (\\cite{eion.messel}) for M\\\"{o}ller scattering ($e^- e^-$):\n\\begin{equation}\n\\label{eion.g}\n\\sigma ( Z,E,T_{cut} ) =\\frac {2 \\pi r_0^2 mZ}{\\beta^2(E-m)}\n \\left[\\frac{(\\gamma-1)} {\\gamma^2}\\left(\\frac{1}{x}-1\\right)\n             +\\frac{1}{x}-\\frac{1}{1-x}-\\frac{2\\gamma-1}{\\gamma^2}\\ln\n\\frac{1-x}{x}\\right]\n\\end{equation}\nand for Bhabha scattering ($e^+ e^-$) :\n\\begin{equation}\n\\label{eion.h}\n\\sigma (Z,E,T_{cut}) =\\frac{ 2 \\pi r^2_0  mZ }\n      {(E-m)}\\left [\\frac {1 }{\\beta^2}  \\left(\\frac{1}{x}-1\\right)\n  + B_1 x + B_2 (1-x) -\n \\frac {B_3 } {2} ( 1-x^2 ) +\\frac{B_4}{3}(1-x^3)\\right]\n\\end{equation}\nwhere\n\n\\[\n\\begin{array}{ll}\n\\gamma = \\frac{E}{m}       & \\beta^2 = 1-\\frac{1}{\\gamma^2} \\\\ [.2cm]\n x     =\\frac {T_{cut}}{E-m}  & \\gamma=\\frac{1}{\\gamma + 1} \\\\ [.2cm]\n B_1=2-y^2                 &  B_2=(1-2y)(3+y^2)              \\\\ [.2cm]\nB_3=(1-2y)^2+(1-2y)^3      &  B_4=(1-2y)^3\n\\end{array}\n\\]\n\nThe formulae [\\ref{eion.g}] and [\\ref{eion.h}]\ngive the total cross-section of the scattering\nabove the threshold energies\n\n\\begin{equation}\nT_{\\rm Moller}^{\\rm thr} =2T_{cut}  \\mbox{\\hspace{2cm}and\\hspace{2cm}}\nT_{\\rm Bhabha}^{\\rm thr} = T_{cut}\n\\end{equation}\nThe interaction length for the production of $\\delta$-rays is calculated\nduring initialisation .\n\n\\section{Simulation of the $\\delta -ray$ production}\n\\subsection{Differential cross section}\n\nThe differential cross-section of the $\\delta$-ray production can\nbe written as in equation \\ref{eion.i} , \\ref{eion.j}\n (\\cite{eion.messel}). For the\nelectron/electron (M\\\"{o}ller) scattering we have:\n\\begin{equation}\n\\label{eion.i}\n\\frac{d\\sigma }{d \\epsilon }=\\frac{2 \\pi Z r^2 _0 m }{\\beta^2 (E-m)}\n\\left[ \\frac{(\\gamma -1 )^2}  {\\gamma^2 }+\\frac{1}{\\epsilon}\n\\left(\\frac{1}{\\epsilon}-\\frac{2 \\gamma -1 } {\\gamma^2 } \\right) +\n\\frac{1}{1- \\epsilon}\\left(\\frac{1} {1- \\epsilon} \\frac{2 \\gamma - 1}\n{\\gamma^2 }\\right)  \\right]\n\\end{equation}\nand for the positron-electron (Bhabha) scattering:\n\\begin{equation}\n\\label{eion.j}\n\\frac{d \\sigma}{d \\epsilon}=\\frac{2 \\pi Z r^2_0 m }{(E-m)}\\left[\n\\frac{1} {\\beta^2 \\epsilon^2}-\\frac{B_1}{\\epsilon}+B_2 - B_3 \\epsilon\n+ B_4 \\epsilon^2\\right]\n \\end{equation}\n\nwhere\n\n\\[\n\\begin{array}{lcllcl}\nZ        & = & \\mbox{atomic number of the medium}   &\nE        & = & \\mbox{energy of the incident particle} \\\\\nM        & = & \\mbox{rest mass of the incident particle} &\n\\gamma   & = & \\frac{E}{M}   \\\\ [.2cm]\n\\beta^2  & = & 1- \\frac{1} {\\gamma^2 } &\n y       & = & \\frac{1} {\\gamma + 1}               \\\\ [.2cm]\n B_1     & = & 2-y^2                   &\n B_2     & = & (1-2y)(3+y^2 )                       \\\\\n B_3     & = & (1-2y)^2+(1-2y)^3 &\n B_4     & = & (1-2y)^3  \\\\\n\\epsilon & = & \\frac{T} {E-m}\n\\end{array}\n\\]\n\nwith $T$ the kinematic energy of the scattered electron (of the lower\nenergy in the case of $e^+ e^-$ scattering).\n\nThe kinematical limits for the variable $\\epsilon$ are:\n\n\\[\n\\epsilon_0 = \\frac{T_{cut}}{E-m} \\leq \\epsilon \\leq \\frac{1}{2}\n\\mbox{\\hspace{.2cm} for $e^- e^-$} \\hspace{2cm}\n\\epsilon_0 = \\frac{T_{cut}}{E-m} \\leq \\epsilon \\leq 1\n\\mbox{\\hspace{.2cm} for $e^+ e^-$}\n\\]\n\n\\subsection{Sampling}\n\nApart from the normalisation, the cross-section can be written as\n\\[\n\\frac{d\\sigma}{d\\epsilon}=f(\\epsilon) g(\\epsilon),\n\\]\nwhere, for $e^- e^-$ scattering,\n\\begin{eqnarray*}\nf(\\epsilon)&=&\\frac{1}{\\epsilon^2} \\frac{\\epsilon_0 }{1- 2\\epsilon_0} \\\\\ng(\\epsilon)&=&\\frac{4}{9\\gamma^2 - 10 \\gamma + 5}\\left[(\\gamma -1)^2\n\\epsilon^2 - (2 \\gamma^2 +2\\gamma -1) \\frac{\\epsilon} {1- \\epsilon }+\n\\frac{\\gamma^2}{(1- \\epsilon )^2 }\\right]\n\\end{eqnarray*}\nand for $e^+ e^-$ scattering\n\\begin{eqnarray*}\n  f(\\epsilon)&=&\\frac{1}{\\epsilon^2} \\frac{\\epsilon_0}{1- \\epsilon_0 } \\\\\n  g(\\epsilon)&=&\\frac{B_0 -B_1 \\epsilon +B_2 \\epsilon^2\n     -B_3 \\epsilon^3 +B_4 \\epsilon ^4}{B_ 0-B_1\\epsilon_0\n+B_2\\epsilon^2_0\n    -B_3 \\epsilon^3_0 +B_4 \\epsilon^4_0 }\n\\end{eqnarray*}\nHere $ B_0=\\gamma^2/(\\gamma^2-1)$ and\nall the other quantities have been defined above.\n\nThe variable $\\epsilon$ is sampled by:\n\\begin{enumerate}\n\\item sample $\\epsilon$ from $f(\\epsilon)$\n\\item calculate the rejection function $g(\\epsilon)$ and accept the\nsampled $\\epsilon$ with a probability of $g(\\epsilon)$.\n\\end{enumerate}\n\nAfter the successful sampling of $\\epsilon$,  the direction\n of the scattered electron is generated with respect to the direction of the\nincident particle. The azimuthal angle $\\phi$ is generated isotropically;\nthe polar angle\n$\\theta$ is calculated from the energy momentum conservation.\nThis information\nis used to calculate the energy and momentum of both scattered\nparticles and to transform them into the {\\em global} coordinate system.\n\n\\section{Status of this document}\n\n 9.10.98     created by L. Urb\\'an.\n\n\\begin{thebibliography}{99}\n\n\\bibitem[GEANT3]{eion.geant3}\n  GEANT3 manual ,CERN Program Library Long Writeup W5013 (October 1994).\n\\bibitem[Mess70]{eion.messel}\n  H.Messel and D.F.Crawford. Pergamon Press,Oxford,1970.\n\\bibitem[Ster71]{eion.sternheimer}\n  R.M.Sternheimer. Phys.Rev. B3 (1971) 3681.\n\n\\end{thebibliography}\n\n", "meta": {"hexsha": "6e029cbbef6d346586d02b7c41c5a2df22216e82", "size": 8648, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "geant4/electromagnetic/standard/eion.tex", "max_stars_repo_name": "berghaus/cernlib-docs", "max_stars_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-24T12:30:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-24T12:30:01.000Z", "max_issues_repo_path": "geant4/electromagnetic/standard/eion.tex", "max_issues_repo_name": "berghaus/cernlib-docs", "max_issues_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geant4/electromagnetic/standard/eion.tex", "max_forks_repo_name": "berghaus/cernlib-docs", "max_forks_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8709677419, "max_line_length": 76, "alphanum_fraction": 0.6187557817, "num_tokens": 3112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.34404329433900654}}
{"text": "\\documentclass[a4paper,11pt]{article}\n\\usepackage{setspace}\n\\usepackage[utf8]{inputenc}\n%\\usepackage{subfigure}\n\n\\pagestyle{plain}\n\n\\usepackage{amssymb, bm, blkarray, multicol}\n\\usepackage{listings,xcolor,lmodern}\n\\usepackage{graphicx}\n\\usepackage{enumitem}\n\\usepackage{tikz}\n\\usepackage{booktabs}\n\\usepackage{amsmath}\n\\usepackage{algorithm}\n\\usepackage{algpseudocode}\n\\usepackage[nottoc]{tocbibind}\n\\usepackage{upgreek}\n\n\\usepackage{mathtools}\n\\mathtoolsset{showonlyrefs}\n\n\\usepackage{hyperref}\n\\usepackage{url}\n\\usepackage{nicefrac}\n\\usepackage{microtype}\n\n\\usepackage{latexsym}\n% \\usepackage{a4wide}\n\n\\newtheorem{theorem}{THEOREM}\n\\newtheorem{lemma}[theorem]{LEMMA}\n\\newtheorem{corollary}[theorem]{COROLLARY}\n\\newtheorem{proposition}[theorem]{PROPOSITION}\n\\newtheorem{remark}[theorem]{REMARK}\n\\newtheorem{definition}[theorem]{DEFINITION}\n\\newtheorem{fact}[theorem]{FACT}\n\n\\newtheorem{problem}[theorem]{PROBLEM}\n\\newtheorem{exercise}[theorem]{EXERCISE}\n\\def \\set#1{\\{#1\\} }\n\n\\lstset{\n  basicstyle=\\ttfamily,\n  columns=fullflexible,\n  frame=single,\n  breaklines=true,\n  postbreak=\\mbox{\\textcolor{red}{$\\hookrightarrow$}\\space},\n}\n\n\\newcommand{\\E}{\\mathbb{E}}\n\\newcommand{\\var}{\\mathrm{Var}}\n\\newcommand{\\cov}{\\mathrm{Cov}}\n\\newcommand{\\KL}{\\mathrm{KL}}\n\\newcommand{\\neighb}{\\text{ne}}\n\\DeclareMathOperator*{\\argmax}{arg\\,max}\n\\DeclareMathOperator*{\\argmin}{arg\\,min}\n\\newcommand{\\Perp}{\\mathrel{\\text{\\scalebox{1.07}{$\\perp\\mkern-10mu\\perp$}}}}\n\n\\usetikzlibrary{shapes.geometric}\n\n\\begin{document}\nExisting tests test moments of the marginal distributions of $\\theta$ and sometimes the evaluations of $p(y|\\theta), p(\\theta)$. What test functions should we choose for the MMD tests?\n\n\\section{MMD-SC}\n\nLet $q_{\\text{SC}}$ denote the transition kernel for Algorithm \\ref{alg:sc-sampler}. Then $q_{\\text{SC}}(\\theta', y' | \\theta, y) = q(\\theta' | y') p(y' | \\theta) q(\\theta, y)$ and \n\\begin{align*}\n    q_{\\text{SC}}(\\theta', y') &= \\int q_{\\text{SC}}(\\theta', y' | \\theta, y) q(\\theta, y) d\\theta dy \\\\\n                    &= \\int q_{\\text{SC}}(\\theta' | y') p(y' | \\theta) q_{\\text{SC}}(\\theta, y) d\\theta dy \\\\\n                    &= q_{\\text{SC}}(\\theta' | y') \\int p(y' | \\theta) q_{\\text{SC}}(\\theta) d\\theta \\\\\n\\end{align*}\nIf the marginals are correct, $q_{\\text{SC}}(\\theta) = p(\\theta)$ and\n\\begin{align*}\n    q_{\\text{SC}}(\\theta', y') = q_{\\text{SC}}(\\theta' | y') \\int p(y' | \\theta) q_{\\text{SC}}(\\theta) d\\theta = q_{\\text{SC}}(\\theta' | y') p(y')\n\\end{align*}\n$q_{\\text{SC}}(\\theta' | y') = p(\\theta'|y') \\rightarrow q_{\\text{SC}}(\\theta' | y') p(y') = p(\\theta', y') \\rightarrow q_{\\text{SC}}(\\theta) = p(\\theta) $, but the other direction does not necessarily hold. Equality of the marginal distributions of $\\theta$ is not enough to show equality of the joints.\n\nHowever, $q_{\\text{SC}}(\\theta) = p(\\theta)$ does imply $q_{\\text{SC}}(y) = p(y)$, so\n\\begin{align*}\n    q_{\\text{SC}}(\\theta' | y') &= \\frac{q_{\\text{SC}}(y' | \\theta') q_{\\text{SC}}(\\theta')}{q_{\\text{SC}}(y')} \\\\\n                                &= \\frac{q_{\\text{SC}}(y' | \\theta') p(\\theta')}{p(y')} \\\\\n\\end{align*}\n\nThus, if $q_{\\text{SC}}(y' | \\theta') = p(y' | \\theta')$, then $q_{\\text{SC}}(\\theta' | y') = p(\\theta' | y')$ and the joint distributions are the same. \n\nIs testing the evaluation of the likelihood enough? Example where it is not:\n\\begin{align*}\n    \\theta &\\sim \\mathcal{U}(\\{0, 1\\}) \\\\\n    y &\\sim \\mathcal{U}(\\{0, 1\\}) \\\\\n    p(y | \\theta) &= 0.25\n\\end{align*}\nvs\n\\begin{align*}\n    \\theta &\\sim \\mathcal{U}(\\{0, 1\\}) \\\\\n    q(y=i|\\theta) &= \\begin{cases}\n                            1 & \\theta = i \\\\\n                            0 & \\text{otherwise}\n                        \\end{cases} \\quad i \\in \\{0, 1\\}\n\\end{align*}\nThe evaluations of $p(y | \\theta)$ and the marginals are the same, but the joint distributions differ; the first model gives $(i, j) \\quad \\forall i, j \\in \\{0,1\\}$, while the second gives $(i, i)$. This example relies on the independence of $\\theta$ and $y$. \n\nCan we come up with other examples? How might these arise in MCMC?\n\n\\section{MMD-BC}\nLet $q_{\\text{BC}}$ denote the joint distribution from Algorithm \\ref{alg:bc-sampler}.\n\\begin{align*}\n    q_{\\text{BC}}(\\theta', y') &= q_{\\text{BC}}(\\theta'|y')q(y') = q_{\\text{BC}}(\\theta'|y')p(y') \\\\\n\\end{align*}\nBy the same logic as for the MMD-SC test, if $q_{\\text{BC}}(y' | \\theta') = p(y' | \\theta')$, then $q_{\\text{BC}}(\\theta' | y') = p(\\theta' | y')$ and the joint distributions are the same.\n\\newpage \n\n\\begin{algorithm}\n    \\centering\n    \\caption{Marginal-conditional (MC) joint simulator}\\label{alg:mc-sampler}\n    \\begin{algorithmic}[1]\n        \\State \\text{Initialize} $\\mathbf{g}_{MC} \\in \\mathbb{R}_{N\\times |\\mathbf{g}|}$\n        \\For{$n = 1, \\ldots, N$}\n            \\State $\\mathbf{\\Theta}_{n} \\sim P(\\mathbf{\\Theta})$ \n            \\State $\\mathbf{Y}_{n} \\sim P(\\mathbf{Y}|\\mathbf{\\Theta}_{n})$ \n            \\State $\\mathbf{g}_{MC}[n, :] = \\mathbf{g}(\\mathbf{\\Theta}_{n}, \\mathbf{Y}_{n})$ \n        \\EndFor        \n        \\State \\textbf{return} $\\mathbf{g}_{MC}$\n    \\end{algorithmic}\n\\end{algorithm}\n\n\\begin{algorithm}\n    \\centering\n    \\caption{Successive-conditional (SC) joint simulator}\\label{alg:sc-sampler}\n    \\begin{algorithmic}[1]\n        \\State \\text{Initialize} $\\mathbf{g}_{SC} \\in \\mathbb{R}_{N\\times |\\mathbf{g}|}$\n        \\State $\\mathbf{\\Theta}_{0} \\sim P(\\mathbf{\\Theta})$ \n        \\For{$n = 1, \\ldots, N$}\n            \\State $\\mathbf{Y}_{n} \\sim P(\\mathbf{Y}|\\mathbf{\\Theta}_{n-1})$ \n            \\State $\\mathbf{\\Theta}_{n} \\sim \\text{PosteriorSampler}(\\mathbf{\\Theta}_{n-1}, \\mathbf{Y}_{n})$ \n            \\State $\\mathbf{g}_{SC}[n, :] = \\mathbf{g}(\\mathbf{\\Theta}_{n}, \\mathbf{Y}_{n})$ \n        \\EndFor        \n        \\State \\textbf{return} $\\mathbf{g}_{SC}$\n    \\end{algorithmic}\n\\end{algorithm}\n\n\\begin{algorithm}[H]\n    \\centering\n    \\caption{Backward-conditional (BC) joint simulator}\\label{alg:bc-sampler}\n    \\begin{algorithmic}[1]\n        \\State \\text{Initialize} $\\mathbf{g}_{BC} \\in \\mathbb{R}_{N\\times |\\mathbf{g}|}$\n        \\For{$n = 1, \\ldots, N_{BC}$}\n            \\State $\\mathbf{\\Theta}_{0} \\sim P(\\mathbf{\\Theta})$ \n            \\State $\\mathbf{Y}_{n} \\sim P(\\mathbf{Y}|\\mathbf{\\Theta}_{0})$ \n            \\For{$m = 1, \\ldots, M$}    \n                \\State $\\mathbf{\\Theta}_{n} \\sim \\text{PosteriorSampler}(\\mathbf{\\Theta}_{n}, \\mathbf{Y}_{n})$\n            \\EndFor\n            \\State $\\mathbf{g}_{BC}[n, :] = \\mathbf{g}(\\mathbf{\\Theta}_{n}, \\mathbf{Y}_{n})$ \n        \\EndFor        \n        \\State \\textbf{return} $\\mathbf{g}_{BC}$\n    \\end{algorithmic}\n\\end{algorithm}\n\n\\end{document}", "meta": {"hexsha": "0dfa54c7455f59ffb77c49e139d03a864ab969e9", "size": 6621, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "notes.tex", "max_stars_repo_name": "awjiang/mcmc-joint-tests", "max_stars_repo_head_hexsha": "ce94b9070f8976ad2dc0731e46a5125db48c66b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notes.tex", "max_issues_repo_name": "awjiang/mcmc-joint-tests", "max_issues_repo_head_hexsha": "ce94b9070f8976ad2dc0731e46a5125db48c66b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notes.tex", "max_forks_repo_name": "awjiang/mcmc-joint-tests", "max_forks_repo_head_hexsha": "ce94b9070f8976ad2dc0731e46a5125db48c66b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.641509434, "max_line_length": 304, "alphanum_fraction": 0.6076121432, "num_tokens": 2324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.6723316926137811, "lm_q1q2_score": 0.3440432909793286}}
{"text": "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                            First Chapter                            %\n%                         Problem Formulation                         %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\chapter{Posture Generation: Problem Formulation}\n\\label{cha:posture_generation_problem_formulation}\n\n%\\nomenclature[z-PG]{PG}{Posture Generation}\n%\\nomenclature[z-IK]{IK}{Inverse Kinematics}\n%\\nomenclature[z-DoF]{DoF}{degrees of freedom}\n%\\nomenclature[z-w.r.t]{w.r.t}{with respect to}\n%\\nomenclature[x-I]{$\\mathbb{I}_n$}{Matrix identity of dimension $n$}\n%\\nomenclature[x-w]{$\\wedge$}{cross product}\n%\\nomenclature[a-F]{F}{a frame}\n%\\nomenclature[a-W]{W}{the world frame}\n%\\nomenclature[a-w]{w}{a wrench or a force}\n%\\nomenclature[a-f]{f}{a force resultant}\n%\\nomenclature[a-m]{m}{a force moment}\n\n\n\\graphicspath{{Chapter2-PG/Figs/}}\n\n%{{{List of contributions\n%\\section{List of contributions}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%                   SECTION LIST OF CONTRIBUTIONS                     %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%\\begin{itemize}\n  %\\item Generalities, introduction\n  %\\item Presentation of the existing methods\n  %\\item From Inverse Kinematics to Generalized IK/posture Generation/pose estimation (addition of articular limits, forces, stability etc).\n  %\\item Topology of the parametrization space (Free-flyer, q, f, other)\n  %\\item Formulation as a nonlinear constrained optimization problem\n  %\\item Adrien \\& Karim's formulations\n  %\\item Formulation of several types of cost/constraints\n  %\\begin{itemize}\n    %\\item Contact with planar surface\n    %\\item Collision avoidance\n    %\\item Auto-Collision avoidance\n    %\\item Static equilibrium: Newton/CoM projection\n    %\\item Forces in friction cones\n    %\\item Articular limits\n    %\\item Torque limits\n    %\\item Torque minimization\n    %\\item Goal Posture\n  %\\end{itemize}\n  %\\item Reasons why it is not enough and why we needed a new PG\n    %\\begin{itemize}\n      %\\item Having an easier way to formulate problems\n      %\\item Avoid having to de some gymnastic to remain on manifolds\n      %\\item Automatic variable management\n      %\\item Robustness\n    %\\end{itemize}\n  %\\item Utilization of posture generation in planning\n%\\end{itemize}\n%}}}\n\n\nIn this Chapter, we present in detail the formulation of a posture generation problem.\nWe present the algorithms used to compute the kinematics of a robot and its derivatives as well as the joint torques.\nThen we formulate some classical functions that are often used in posture generation: joint limits, contact constraints, collision avoidance, stability, torque limits and friction cones.\nIn~\\Figref{fig:PG}, we illustrate those constraints with the result of a posture generation problem where the HRP-4 robot must climb on a stack of cubes while being statically stable, respecting its joint and torque limits, the contact forces must remain within their respective friction cones and the robot must avoid auto-collisions and non-desired contacts (i.e. collisions) with the environment.\n\n%\\begin{figure}[ht]\n  %\\centering\n  %\\includegraphics[width=0.7\\textwidth]{PG.pdf}\n  %\\caption{HRP4 on a stack of cubes. The color of each box corresponds to the color of the item it depicts.}\n%\\label{fig:PG}\n%\\end{figure}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                    SECTION PROBLEM FORMULATION                      %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\\section{Kinematics Formulation}\n%\\label{sec:kinematics_formulation}\n\n\n\\section{Forward Kinematics}\n\\label{sec:forward_kinematics}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                   SUBSECTION FORWARD KINEMATICS                     %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nIn this section, we present a formulation of robotic systems that allows specifying most of the typical constraints encountered in robotics problems.\n\nWe consider a robotic system made of $n_B$ bodies and $n_J(=n_B+1)$ joints.\nThe global structure of the robot is described by an ordered graph called multibody graph.\nThe base body (World) has index $0$ and each of the remaining bodies get a different positive integer index.\nWe denote the body of index $i$, $B_i$.\n$B_0$ refers to the World.\nEach body $B_i$ has its reference frame $F_i$ attached to it.\n$F_0$ denotes the World frame.\nBodies are linked together by joints that also are indexed by positive integers, we denote the joint of index $i$, $J_i$, and the body that comes after it is $B_i$.\nEach joint defines the relation between its predecessor and successor bodies.\nFor joint $J_i$, they are respectively denoted $pred(i)$ and $succ(i)$, and $B_{pred(i)}$ is called the parent body of $B_{succ(i)}$.\nWe denote $\\lambda(j)$ the index of the parent body of $B_j$.\nThe number of degrees of freedom of $J_i$ is denoted $dof^J_i$ and the number of degrees of freedom of the whole robot is denoted $dof$.\n\\Figref{fig:mbg} illustrates this numbering system for a simple robot with 4 joints and 5 bodies (including the basis)\n\nThe geometric relations between bodies and joints are described through transformations between their reference frames.\nWe use transformations as described in the Spatial Vector Algebra chapter of `Rigid Body Dynamics Algorithm' by Roy Featherstone~\\cite{featherstone:book:2007}.\nMotion vectors (vectors describing motion quantities as positions, velocities and accelerations) and their force counterpart are defined in~\\cite{featherstone:book:2007}.\n\nFor any 3D vector $v\\in\\mathbb{R}^3$, $\\hat{v}$ denotes the $3\\times 3$ skew-symmetric matrix such that $\\hat{v}u = v\\wedge u$.\nWhere $\\wedge$ denotes the cross product operator.\n\nLet A and B be Cartesian frames with origins O and P respectively.\nLet $\\mathbf{t}$ be the coordinate vector expressing $\\overrightarrow{OP}$ in A.\nAnd $\\mathbf{R}$ be the rotation matrix that transforms 3D vectors from A to B coordinates.\nThe transformation from A to B for a motion vector is defined by:\n\\begin{equation}\n  {}^B X_A =\n  \\begin{bmatrix}\n    \\mathbf{R} & \\mathbf{0} \\\\\n    -\\mathbf{R}\\hat{\\mathbf{t}} & \\mathbf{R} \\\\\n  \\end{bmatrix}\n\\end{equation}\nIts inverse is:\n\\begin{equation}\n  {{}^B X_A}^{-1} = {}^A X_B =\n  \\begin{bmatrix}\n    \\mathbf{R}^T & \\mathbf{0} \\\\\n    \\hat{\\mathbf{t}}\\mathbf{R}^T & \\mathbf{R}^T \\\\\n  \\end{bmatrix}\n\\end{equation}\nThe transformation from A to B for a force vector is defined by:\n\\begin{equation}\n  {}^B X_A^* =\n  \\begin{bmatrix}\n    \\mathbf{R} & -\\mathbf{R}\\hat{\\mathbf{t}} \\\\\n    \\mathbf{0} & \\mathbf{R} \\\\\n  \\end{bmatrix}\n\\end{equation}\nIts inverse is:\n\\begin{equation}\n  {}^B X_A^{-*} = {}^A X_B^* =\n  \\begin{bmatrix}\n    \\mathbf{R}^T & \\hat{\\mathbf{t}}\\mathbf{R}^T \\\\\n    \\mathbf{0} & \\mathbf{R}^T \\\\\n  \\end{bmatrix}\n\\end{equation}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=0.7\\textwidth]{mbg.pdf}\n  \\caption{MultiBody graph}\n\\label{fig:mbg}\n\\end{figure}\n\n%Each joint $J_i$ is defined in the reference frame of its predecessor body by a static transformation $X^x_i = \\{\\mathbf{R}^x_i, \\mathbf{t}^x_i\\}$ from the base of the body to the base of the joint.\nEach joint $J_i$ is defined by a static transformation $X^x_i = \\{\\mathbf{R}^x_i, \\mathbf{t}^x_i\\}$ between the reference frame of its predecessor body and its own reference frame.\nEach joint $J_i$ is associated with a motion subspace which representation matrix is denoted $S_i$.\nEach column of $S_i$ described a degree of freedom of $J_i$ its upper part for the rotations and lower for translations (see Section~\\ref{sec:joints_formulations}).\n\\begin{equation}\n  S_i =\n  \\begin{bmatrix}\n    S^R_{i,0} & \\cdots &\n    S^R_{i,j} & \\cdots &\n    S^R_{i,dof} \\\\\n    S^t_{i,0} & \\cdots &\n    S^t_{i,j} & \\cdots &\n    S^t_{i,dof}\n  \\end{bmatrix}\n\\end{equation}\n\nFor a given joint configuration $\\mathbf{q}$, the transformation due to the joint $J_i$ current configuration from its reference frame to the reference frame of its successor body is denoted \\\\$X^J_i (\\mathbf{q}) = \\{\\mathbf{R}^J_i (\\mathbf{q}), \\mathbf{t}^J_i (\\mathbf{q})\\}$.\n\nThe transformation between $B_{\\lambda(i)}$ and $B_i$ is denoted $X^{PtS}_i (\\mathbf{q}) = \\{\\mathbf{R}^{PtS}_i, \\mathbf{t}^{PtS}_i\\}$ (PtS stands for `Parent to Son') can then be computed as:\n\\begin{equation}\n  {X}^{PtS}_i (\\mathbf{q}) = {}^{i}X_{\\lambda (i)} (\\mathbf{q}) = X^J_i (\\mathbf{q}) X^x_i\n  \\label{eq:PtS}\n\\end{equation}\n\nLet $\\kappa (i) =\\{0, i_1, i_2 \\ldots i\\}$ be the list of indexes of successive joints going from $B_0$ to $B_i$.\nIt can easily be computed by adding iteratively the parent of the current body:\n\n\\begin{algorithm}\n  \\caption{Joint Path to $B_i$}\n\\label{alg:JP}\n\\begin{algorithmic}\n  \\State{$j \\leftarrow i$, $\\kappa(i)=[i]$}\n  \\While{$j \\neq 0$}\n  \\State{$j \\leftarrow \\lambda(j)$}\n  \\State{$\\kappa(i) \\leftarrow [\\kappa(i),\\ j]$}\n  \\EndWhile{}\n\\end{algorithmic}\n\\end{algorithm}\n\nThe transformation from the World base to $B_i$ is denoted \\\\ ${}^i X_0 (\\mathbf{q}) = \\{{}^i \\mathbf{R}_0 (\\mathbf{q}), {}^i \\mathbf{t}_0 (\\mathbf{q})\\}$.\nThe formula~\\Eqref{eq:PtS} can be used iteratively on all bodies of the robot to obtain the expression of ${}^i X_0 (\\mathbf{q})$.\n\nWe obtain the full expression of ${}^i X_0$ as:\n\\begin{equation}\n  {}^i X_0 (\\mathbf{q}) = \\prod_{j\\in\\kappa (i)}X^J_j (\\mathbf{q}) X^x_j = \\prod_{j\\in\\kappa (i)}\\ {}^j X_{\\lambda (j)}\n  = {}^i X_{\\kappa (1)}\\ ^{\\kappa (1)}X_{\\kappa (2)} \\dots ^{\\kappa (\\text{end}-1)}X_{W}\n\\end{equation}\n\nWhich can be computed recursively by a Forward Kinematics algorithm:\n\n\\begin{algorithm}\n  \\caption{Forward Kinematics}\n\\label{alg:FK}\n\\begin{algorithmic}\n  \\For{$i = 0:n_J$}\n  \\If{$\\lambda (i) \\neq -1$} ${}^i X_0 = {}^i X_{\\lambda (i)}\\ ^{\\lambda (i)}X_0$\n  \\Else$\\ {}^i X_0 = X^{PtS}_i$\n  \\EndIf{}\n  \\EndFor{}\n\\end{algorithmic}\n\\end{algorithm}\n\nIn the following section, we provide some detailed description of how to compute $X_J (\\mathbf{q})$ for a variety of useful joints.\nUsing the joint descriptions and the Forward Kinematics algorithm, we are able to explicit a relation between $\\mathbf{q}$ the joint parameters of the robot and the 3D position and orientation of any geometric quantity defined in the reference frame of a body of the robot.\nGiven a transformation ${}^p X_i$ defined in the frame of $B_i$, its value in the world frame is given by ${}^p X_0 (\\mathbf{q}) = {}^p X_i\\ {}^i X_0 (\\mathbf{q})$\n\n\n\n\\section{Joints formulations}\n\\label{sec:joints_formulations}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                   SUBSECTION JOINTS FORMULATIONS                    %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nThe entire geometry of our system is described by the list of static transformations $X^x_j$ and of joint transformations $X^J_j (q)$.\nIn this section, we explicit the descriptions and formulations of common joints type.\n\nLet us consider a joint $J$ that governs the transformation between two frames $F_1=\\{O_1, x_1, y_1, z_1\\}$ and $F_2=\\{O_2, x_2, y_2, z_2\\}$.\nThe most common type of joint encountered in robotics (and even virtual avatars) systems is the revolute joint, that allows a rotation around a fixed axis.\nIf $J$ is a revolute joint around the axis $(O_1,z_1)$ with parameter $q$, its motion subspace, rotation, and translation are as follows:\n\\begin{table} [H]\n\\centering\n\\begin{tabular}{cccc}\n  \\toprule\n  Joint type & $S$ & $Rotation$ & $translation$ \\\\\n  \\midrule\n  Revolute $(O_1,z_1)$\n  &\n  $\\begin{bmatrix}\n    0 \\\\ 0 \\\\ 1 \\\\ 0 \\\\ 0 \\\\ 0\n  \\end{bmatrix}$\n  &\n  $\\begin{bmatrix}\n    1 & 0 & 0 \\\\\n    0 & \\cos (q) & \\sin (q) \\\\\n    0 & -\\sin (q) & \\cos (q) \\\\\n  \\end{bmatrix}$\n  &\n  ${\\bf 0}_{3\\times1}$\n  \\\\\n  \\bottomrule\n\\end{tabular}\n\\end{table}\n\nSimilar formulas can be devised for rotations around any other axis, provided that $R$ describes the rotation of angle $q$ around that axis.\n\nIn the case of a prismatic joint, all rotations are blocked, and only one translation along a given axis is allowed.\nA prismatic joint along $x_1$ is described by the following formulas:\n\\begin{table}[H]\n\\centering\n\\begin{tabular}{cccc}\n  \\toprule\n  Joint type & $S$ & $Rotation$ & $translation$ \\\\\n  \\midrule\n  Prismatic $(x_1)$\n  &\n  $\\begin{bmatrix}\n    0 \\\\ 0 \\\\ 0 \\\\ 1 \\\\ 0 \\\\ 0\n  \\end{bmatrix}$\n  &\n  ${\\bf 1}_{3\\times3} $\n  &\n  $\\begin{bmatrix}\n    q \\\\ 0 \\\\ 0\n  \\end{bmatrix}$\n  \\\\\n  \\bottomrule\n\\end{tabular}\n\\end{table}\n\nPlanar joints are also frequently used in robotics.\nA planar joint describes a plane sliding on another plane. Assuming that the normal to both planes is $z_1 = z_2$, this type of joint allows free relative rotation of $F_2$ around $z_1$ and relative translations along $x_1$ and $y_1$.\nWe denote $q = \\{q_1, q_2, q_3\\}$ the joint parameters, $q_1$ corresponding to the rotation and $q_2,\\ q_3$ to the translations.\nWe get:\n\\begin{table}[H]\n\\centering\n\\begin{tabular}{cccc}\n  \\toprule\n  Joint type & $S$ & $Rotation$ & $translation$ \\\\\n  \\midrule\n  Planar $(z_1)$\n  &\n  $\\begin{bmatrix}\n    0 & 0 & 0 \\\\ 0 & 0 & 0 \\\\ 1 & 0 & 0 \\\\ 0 & 1 & 0 \\\\ 0 & 0 & 1 \\\\ 0 & 0 & 0\n  \\end{bmatrix}$\n  &\n  $\\begin{bmatrix}\n    \\cos(q_1) & \\sin(q_1) & 0 \\\\\n    -\\sin(q_1) & \\cos(q_1) & 0 \\\\\n    0 & 0 & 1 \\\\\n  \\end{bmatrix}$\n  &\n  $\\begin{bmatrix}\n    \\cos(q_1)q_2 - \\sin(q_1)q_3 \\\\ \\sin(q_1)q_2 + \\cos(q_1)q_3 \\\\ 0\n  \\end{bmatrix}$\n  \\\\\n  \\bottomrule\n\\end{tabular}\n\\end{table}\n\nA spherical joint blocks all translations and allows all rotations.\nThis joint must be parametrized by a 3D rotation.\nThe space of 3D rotations $SO(3)$ can be represented in many different ways.\nThe simplest and most intuitive way to parametrize $SO(3)$ is to use Euler Angles.\nIt comes down to decomposing the 3D rotation into a succession of three 1D rotations around different axes.\nFor example, the roll, pitch, yaw is a succession of a rotation of $F_1$ around its $x$ axis, followed by a rotation around the $y$ axis of the resulting frame, finally a rotation around the $z$ axis of the resulting  frame of the latter rotation.\nThe rotation matrix for such a convention is given by:\n\\begin{equation}\n  {\\bf R} =\n  \\begin{bmatrix}\n    1 & 0 & 0 \\\\\n    0 & \\cos(q_3) & \\sin(q_3) \\\\\n    0 & -\\sin(q_3) & \\cos(q_3) \\\\\n  \\end{bmatrix}\n  \\cdot\n  \\begin{bmatrix}\n    \\cos(q_2) & 0 & -\\sin(q_2) \\\\\n    0 & 1 & 0 \\\\\n    \\sin(q_2) & 0 & \\cos(q_2) \\\\\n  \\end{bmatrix}\n  \\cdot\n  \\begin{bmatrix}\n    \\cos(q_1) & \\sin(q_1) & 0 \\\\\n    -\\sin(q_1) & \\cos(q_1) & 0 \\\\\n    0 & 0 & 1\n  \\end{bmatrix}\n\\end{equation}\n\nEuler Angle formulations have the advantage to be simple and intuitive.\nThere are many other possible choices of the rotation order and conventions.\nBut they all suffer from the so-called gimbal-lock problem or more generally from singularities, which happens when two of the three rotation axes become aligned.\nIn such a configuration, the only rotations possible are one rotation around the two aligned axis and one rotation around the third axis.\nThus, one degree of freedom is lost.\nThose singularities are prohibitive for the use of that type of formulation in a posture generation.\nIn~\\cite{grassia1998}, Grassia states that any attempt to parametrize the entire set of 3D rotations by an open subset of Euclidean space (as do Euler angles) will suffer from gimbal lock.\nNote that this singularity is only due to the user's choice of parametrization, it is not intrinsic to the manifold $SO(3)$.\n%One can prove that there is no smooth mapping between $SO(3)$ and $\\mathbb{R}^3$ that is free of singularities.\nIt is possible to parametrize $SO(3)$ without having to face singularities by parametrizing it over another non-Euclidean manifold.\nThe most common ones are the set of unit quaternion embedded in $\\mathbb{R}^4$ and the set of rotation matrices embedded in $\\mathbb{R}^{3\\times 3}$.\n%To avoid singularities, one must use a higher dimension parametrization, such as the most common $SO(3)$ representation in robotics that are the unit quaternions and the rotation matrices.\n%The unit quaternions space is the subset of $\\mathbb{R}^4$ where all elements have unit norm.\nWith the unit quaternion parametrization, a variable on $SO(3)$ is represented by 4 parameters $q = [q_w, q_x, q_y, q_z]$, and it is necessary to ensure that the quaternion is of norm 1, $\\{q\\in\\mathbb{R}^4:||q||=1\\}$.\nSimilarly, if a variable is parametrized by a rotation matrix, then the matrix $M$ representing it has 9 parameters and M must be orthogonal and have determinant 1: $\\{M\\in\\mathbb{R}^{3\\times 3}:M^T M = \\mathbf{1}_3\\  \\text{and}\\ \\det (M) = 1\\}$.\nSimilar issues can be found with the parametrization of other non-Euclidean manifolds, like $S^2$ for example.\n\nA quaternion $q = [q_w, q_x, q_y, q_z]$ is a unit quaternion iff $q_w^2+q_x^2+q_y^2+q_z^2 = 1$.\nIt represents a rotation of angle $\\theta$ around an axis ${\\bf u}$ such that:\n\\begin{align}\n  q_w &= \\cos(\\theta/2) \\\\\n  q_x &= \\sin(\\theta/2)u_x \\\\\n  q_y &= \\sin(\\theta/2)u_y \\\\\n  q_z &= \\sin(\\theta/2)u_z \\\\\n\\end{align}\nThe rotation matrix associated with this quaternion is:\n\\begin{equation}\n  {\\bf R} = 2 \\begin{bmatrix}\n    \\frac{1}{2} - {q_y}^2 - {q_z}^2 &\tq_x q_y - q_z q_w &\tq_x q_z + q_y q_w \\\\\n    q_x q_y + q_z q_w\t& \\frac{1}{2} - {q_x}^2 - {q_z}^2 &\tq_y q_z - q_x q_w \\\\\n    q_x q_z - q_y q_w &\tq_y q_z + q_x q_w\t& \\frac{1}{2} - {q_x}^2 - {q_y}^2 \\\\\n  \\end{bmatrix}\n\\end{equation}\n\nThat formulation does not suffer from singularities, but it requires to maintain 4 parameters for a 3D rotation.\nAnd those 4 parameters must satisfy the unit norm constraint which in turn would become an additional constraint in the optimization formulation.\nGiven a parameter set $q = \\{ q_w, q_x, q_y, q_z\\}$, we get the following table.\n\n\\begin{table}[ht]\n  \\centering\n  \\begin{tabular}{cccc}\n    \\toprule\n    Joint type & $S$ & $Rotation$ & $translation$ \\\\\n    \\midrule\n    Spherical\n    &\n    $\\begin{bmatrix}\n      1 & 0 & 0 \\\\ 0 & 1 & 0 \\\\ 0 & 0 & 1 \\\\ 0 & 0 & 0 \\\\ 0 & 0 & 0 \\\\ 0 & 0 & 0\n    \\end{bmatrix}$\n    &\n    $2 \\begin{bmatrix}\n    \\frac{1}{2} - {q_y}^2 - {q_z}^2 &\tq_x q_y - q_z q_w &\tq_x q_z + q_y q_w \\\\\n    q_x q_y + q_z q_w\t& \\frac{1}{2} - {q_x}^2 - {q_z}^2 &\tq_y q_z - q_x q_w \\\\\n    q_x q_z - q_y q_w &\tq_y q_z + q_x q_w\t& \\frac{1}{2} - {q_x}^2 - {q_y}^2 \\\\\n    \\end{bmatrix}$\n    &\n    $\\begin{bmatrix}\n      0 \\\\ 0 \\\\ 0\n    \\end{bmatrix}$\n    \\\\\n    \\bottomrule\n  \\end{tabular}\n\\end{table}\n\nFinally, a free joint allows free motion of its successor body with respect to its predecessor body.\nIt can be viewed as a combination of a spherical joint and 3 perpendicular prismatic joints.\nGiven a parameter set $q = \\{ q_w, q_x, q_y, q_z, t_x, t_y, t_z\\}$, we get the following table.\n\n\\begin{tabular}{cccc}\n  \\toprule\n  Joint type & $S$ & $Rotation$ & $translation$ \\\\\n  \\midrule\n  Spherical\n  &\n  $\\mathbf{1}_6$\n  &\n  $2 \\begin{bmatrix}\n    \\frac{1}{2} - {q_y}^2 - {q_z}^2 &\tq_x q_y - q_z q_w &\tq_x q_z + q_y q_w \\\\\n    q_x q_y + q_z q_w\t& \\frac{1}{2} - {q_x}^2 - {q_z}^2 &\tq_y q_z - q_x q_w \\\\\n    q_x q_z - q_y q_w &\tq_y q_z + q_x q_w\t& \\frac{1}{2} - {q_x}^2 - {q_y}^2 \\\\\n  \\end{bmatrix}$\n  &\n  ${\\bf R}^{-1}\\begin{bmatrix}\n    t_x \\\\ t_y \\\\ t_z\n  \\end{bmatrix}$\n  \\\\\n  \\bottomrule\n\\end{tabular}\n\n\n\n\\section{Jacobian computation}\n\\label{sec:jacobian_computation}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                  SUBSECTION JACOBIAN COMPUTATION                    %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nIn order to solve our problem with a gradient-based nonlinear optimization algorithm, it is useful to compute the derivatives of every function used as constraint or cost with respect to any variable of the problem.\nThe transformations ${}^i X_0$ are used in many functions, therefore, having an efficient algorithm to compute their derivatives and the derivatives of any transformation defined in $B_i$ is necessary.\n\nGiven a static transformation ${}^p X_i$ defined in body $B_i$.\nIts expression in the world frame is ${}^p X_0 = {}^p X_i\\ {}^i X_0$ and its expression in the frame of $B_j$ is ${}^p X_j = {}^p X_i\\ {}^i X_0\\ {{}^j X_i}^{-1}$.\n\nWe denote $\\text{Jac}_i$ the Jacobian of body $i$, and $\\text{Jac}_i(X)$ the jacobian of the frame defined by $X$ in the referential of body $i$.\n$q_i$ is the part of $q$ that corresponds to the degrees of freedom of joint $J_i$.\nWe denote $\\text{Jac}_i.\\text{cols}(j)$ the columns of $\\text{Jac}_i$ associated with joint $J_j$.\nThe jacobian of the frame defined by ${}^p X_i$ in $B_i$ with respect to $q_j$ is given by\n\\begin{equation}\n\\label{partial_jacobian}\n  \\text{Jac}_i({}^p X_i).\\text{cols}(j) = {}^p X_j\\ S_i\n\\end{equation}\n\nThe complete Jacobian of a body $\\text{Jac}_i$ is a $6\\times \\text{dof}$ matrix that can be computed by using the formula~\\ref{partial_jacobian} on every index $j$ in $\\kappa(i)$ and filling the rest of $\\text{Jac}_i$ with zeros.\n\nThe algorithm that we use to compute $\\text{Jac}_i({}{}^p X_i)$ writes as follows:\n\n\\begin{algorithm}\n  \\caption{Jacobian Computation}\n\\label{alg:jacobian_computation}\n\\begin{algorithmic}\n  \\State{$\\text{Jac}_i({}^p X_i) = {\\bf 0}_{6\\times\\text{dof}}$}\n  \\State{${}^p X_0 = {}^p X_i\\ {({}^i X_0)}^{-1}$}\n  \\For{$j = 0:\\text{size}(\\kappa(i))$}\n  \\State{$k \\leftarrow \\kappa(j)$}\n  \\State{${}^p X_k = {}^p X_0\\ {({}^k X_0)}^{-1}$}\n  \\State{$\\text{Jac}_i({}^p X_i).\\text{cols}(k) = {}^p X_k\\ S_k$}\n  \\EndFor{}\n\\end{algorithmic}\n\\end{algorithm}\n\nWe write the jacobian of each body at its origin as follows:\n\\begin{equation}\n  \\mathbf{Jac}^0_i =\n  \\begin{bmatrix}\n    \\frac{\\partial {}^i\\mathbf{R}_0}{\\partial q_0} & \\cdots &\n    \\frac{\\partial {}^i\\mathbf{R}_0}{\\partial q_j} & \\cdots &\n    \\frac{\\partial {}^i\\mathbf{R}_0}{\\partial q_{dof}} \\\\\n    \\frac{\\partial {}^i\\mathbf{t}_0}{\\partial q_0} & \\cdots &\n    \\frac{\\partial {}^i\\mathbf{t}_0}{\\partial q_j} & \\cdots &\n    \\frac{\\partial {}^i\\mathbf{t}_0}{\\partial q_{dof}}\n  \\end{bmatrix}\n=\n  \\begin{bmatrix}\n    \\omega_{i,0} & \\cdots &\n    \\omega_{i,j} & \\cdots &\n    \\omega_{i,dof} \\\\\n    v_{i,0} & \\cdots &\n    v_{i,j} & \\cdots &\n    v_{i,dof}\n  \\end{bmatrix}\n\\end{equation}\n\n\n\n%\\section{Geometric constraints}\n%\\label{sec:geometric_constraints}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%          SECTION GEOMETRIC CONSTRAINTS                              %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Joint Limits}\n\\label{sec:joint_limits}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                      SUBSECTION JOINT LIMITS                        %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nMost robotic joints have limits which define the range of value that can be accessed by the joint variables.\nThe joint limits for 1D joints like revolute and prismatic joints are trivial to formulate: We denote $q^-$ and $q^+$ the lower and upper values accessible and add a boundary constraint to the optimization problem:\n\\begin{equation}\n\\label{eq:joint_limits}\n  \\boxed{q^- \\leq q \\leq q^+}\n\\end{equation}\n\nMost joints are easy to limit because their variables are independent.\nLimiting the movements of a spherical joint, and by extension, of a free joint, is more complicated.\nIn humanoid robotics, spherical joints can be used to model the shoulder or hip joint of the robot.\nA common approach to limit shoulder joint, inspired from the biomechanics field, considers the spherical motion (or swing) and the axial motion (or twist) separately as shown in~\\Figref{fig:ballAndSocket}.\n\n\\begin{figure}[htb]\n  \\centering\n  \\includegraphics[width=0.7\\linewidth]{ballAndSocket.pdf}\n  \\caption{Swing and Twist in ball and socket joint}\n\\label{fig:ballAndSocket}\n\\end{figure}\n\nThe spherical motion can be parametrized by a vector of the 3D unit sphere $S^2$ and constrained to lay within a limit cone, the axial motion can be parametrized in $\\mathbb{R}$ and limited by equation~\\Eqref{eq:joint_limits}.\nThis type of formulation is presented in~\\cite{baerlocher}.\n\n\n\n\\section{Contact constraints}\n\\label{sec:contact_constraints}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                   SUBSECTION CONTACT CONSTRAINTS                    %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nMost of the tasks the robots achieve (grasping, manipulation, walking, etc.) are made by making and breaking contacts.\nA contact can be defined between 2 surfaces: one on the robot and the other on the entity (that can be another robot, object or the environment) to contact with.\nThe most usual types of contact constraint encountered are the planar contact and the fixed contact.\nA planar contact constraint is used when a planar surface of a robot is put in contact with a planar surface of the environment.\nWe denote $F_1 = \\{O_1, \\vec{x_1}, \\vec{y_1}, \\vec{z_1}\\}$ a frame defined on $S_1$, the surface of the first body involved in the contact, such that the 3D point $O_1$ is on $S_1$ and the vector $\\vec{z_1}$ is normal to $S_1$ and pointing toward the inside of the body.\n$F2 = \\{O_2, \\vec{x_2}, \\vec{y_2}, \\vec{z_2}\\}$ is a frame on $S_2$, the surface of the second body involved, such that $O_2$ is on $S_2$ and the vector $\\vec{z_2}$ is normal to $S_2$ and pointing away from the body.\n\nConstraining $S_1$ and $S_2$ to be coplanar boils down to aligning $\\vec{z_1}$ with $\\vec{z_2}$ and to ensure that the projection of the distance between $O_1$ and $O_2$ along $\\vec{z_1}$ is null.\nNote that we avoid using the dot product of two vectors that are meant to be aligned e.g. $\\vec{z_1}\\cdot\\vec{z_2} = 1$ because when that constraint is satisfied, its gradient is zero, which implies that in the optimization context it is unqualified.\nThat is why we prefer imposing orthogonality constraints.\nThis translates into adding the following set of constraints to our problem:\n\n\\begin{equation}\n\\label{eq:coplanarity}\n\\boxed{\\left\\{\n  \\begin{array}{l}\n    \\overrightarrow{O_1O_2} \\cdot \\vec{z_1} = 0\\\\\n    \\vec{x_1}\\cdot\\vec{z_2} = 0\\\\\n    \\vec{y_1}\\cdot\\vec{z_2} = 0\\\\\n    \\vec{z_1}\\cdot\\vec{z_2} \\geq 0\n  \\end{array}\n  \\right.}\n\\end{equation}\n\nThis set of constraints leaves free the displacements of $F_2$ along $\\vec{x_1}$ and $\\vec{y_1}$ as well as its rotation around $\\vec{z_1}$.\nWe call this a floating planar contact, the optimization algorithm will be able to choose the location of $F_2$ in the plane $\\{O_1, \\vec{x_1}, \\vec{y_1}\\}$.\nThis contact has 3 degrees of freedom.\n\n\\begin{figure}[htpb]\n  \\centering\n  \\includegraphics[width=0.8\\linewidth]{contactConstraint.pdf}\n  \\caption{Floating and Fixed Contacts}\n\\label{fig:contactConstraint}\n\\end{figure}\n\nIf we constrain the location of $F_2$ in $\\{O_1, \\vec{x_1}, \\vec{y_1}\\}$ such that $O_1$ and $O_2$ are superimposed and $\\vec{x_1}$, $\\vec{y_1}$, $\\vec{z_1}$ are aligned with respectively $\\vec{x_2}$, $\\vec{y_2}$, $\\vec{z_2}$, we obtain a fixed contact with zero degrees of freedom.\nThis translates into adding the following set of constraints to our problem:\n\n\\begin{equation}\n\\label{eq:fixed_contact}\n\\boxed{\\left\\{\n  \\begin{array}{l}\n    \\overrightarrow{O_1O_2} = \\vec{0}\\\\\n    \\vec{x_1}\\cdot\\vec{z_2} = 0\\\\\n    \\vec{y_1}\\cdot\\vec{z_2} = 0\\\\\n    \\vec{x_1}\\cdot\\vec{y_2} = 0\\\\\n    \\vec{z_1}\\cdot\\vec{z_2} \\geq 0\\\\\n    \\vec{x_1}\\cdot\\vec{x_2} \\geq 0\\\\\n  \\end{array}\n  \\right.}\n\\end{equation}\n\nWe illustrate those two types of contacts in~\\Figref{fig:contactConstraint}\n\n\n\n\\section{Collision avoidance}\n\\label{sec:collision_avoidance}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                   SUBSECTION COLLISION AVOIDANCE                    %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nIn order to avoid unwanted collisions between bodies of robots, for two bodies $B_1$ and $B_2$, we want to define a continuously differentiable function $d_{\\{B_1, B_2\\}}(q)$ that has the properties of a pseudo-distance:\n\\begin{itemize}\n  \\item $d_{\\{B_1, B_2\\}}(q) > 0$ when the bodies are not touching each other\n  \\item $d_{\\{B_1, B_2\\}}(q) = 0$ when the bodies are in collision without interpenetration\n  \\item $d_{\\{B_1, B_2\\}}(q) < 0$ when the bodies are in collision with interpenetration\n\\end{itemize}\n\nUsing the cartesian distance between the exact surfaces of $B_1$ and $B_2$ might result in a discontinuous gradient of $d_{\\{B_1, B_2\\}}$ if the surfaces of $B_1$ and $B_2$ are not convex.\nA conservative approach is to associate to each body, a strictly convex bounding volume and to compute the distance between those volumes.\n\\cite{escande:humanoids:2007} and~\\cite{escande:itro:2014} proposes a method to generate a strictly convex Sphere-Torus-Patch Bounding Volumes (STP-BV) that guarantees the gradient continuity of the proximity distance.\nThe distance between the STP-BV of $B_1$ and $B_2$ computed by an enhanced GJK~\\cite{gilbert-1988a} collision-detection algorithm is a continuously differentiable pseudo-distance.\nThus, we can use this function in our optimization algorithm to ensure that the distance between the bodies is greater than a safety distance $\\epsilon_{12}$:\n\n\\begin{equation}\n  \\boxed{d_{\\{B_1, B_2\\}}(q) \\geq \\epsilon_{12}}\n\\end{equation}\n\nThis function can be used to avoid collisions between a robot and the environment as well as auto collisions between bodies of the same robot.\nWe denote $Coll$ the list of triplets $\\{B_i, B_j, \\epsilon_{ij}\\}$ defining each collision that we want to avoid.\n\nThen the set of constraints to add to our problem is:\n\n\\begin{equation}\n  \\boxed{\\forall \\{B_i, B_j, \\epsilon_{ij}\\} \\in Coll,\\ d_{\\{B_i, B_j\\}}(q) \\geq \\epsilon_{ij}}\n\\end{equation}\n\nIn many cases, it is possible to avoid the collision between two bodies of a robot by modifying the joint limits and reducing them to a span where the collision of interest cannot happen.\nThat approach is conservative and ad-hoc but can save some precious computation time.\n\n\n%\\section{Static constraints}\n%\\label{sec:static_constraints}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                SECTION STATIC CONSTRAINTS                           %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{External Forces}\n\\label{sec:external_forces}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                     SUBSECTION EXTERNAL FORCES                      %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nFor a robot to contact with the real world (or another robot), its geometric description is not enough.\nThe robot is subject to forces applied on its bodies as a reaction to that it applies, and which can be generated by contacts with the environment or with another actor (human, another robot, manipulated object...), by the effect of physical forces fields like gravitation or magnetism, or by contacts between two bodies of the robot.\nOur posture generator must take those `External forces' into account, to be able to estimate the stability of the robot and compute the internal torques generated in the joints, or to be able to generate desired force-driven posture for given tasks when needed.\n\nAn external force applied on a rigid body can be represented by a \\emph{wrench}, from screw theory, and is composed of a resultant part $f$ (sometimes called force) and a moment part (sometimes called couple).\nLet $w$ be a wrench, $w|_F^O$ is the expression of $w$ calculated at the point $O$ expressed in the frame $F$.\nWe denote $\\vec{f}$ the resultant part of $w$, and $\\vec{f}|_F$ the expression of $\\vec{f}$ in $F$.\n$\\vec{m}$ is the moment part of $w$ and $\\vec{m}|_F^O$ the expression of $\\vec{m}$ in $F$ calculated at the point $O$.\n\n\\begin{equation}\n  w|_F^O = \\left\\{ \\begin{array}{r}\n    \\vec{m}\\\\\n    \\vec{f}\\\\\n  \\end{array} \\right\\}^O_F\n  = \\left\\{ \\begin{array}{r}\n    \\vec{m}|_F^O\\\\\n    \\vec{f}|_F\\\\\n  \\end{array}\\right\\}\n\\end{equation}\n\nThe expression of the moment part on a different point $P$ is given by the Varignon formula:\n\n\\begin{equation}\n  \\vec{m}|_F^P = \\vec{m}|_F^O + \\overrightarrow{PO} \\wedge \\vec{f}|_F\n\\end{equation}\n\nThe resultant part is invariant with respect to the point at which the wrench is calculated.\n\nWe drop the frame subscript when the choice of the frame does not matter and all quantities are computed in the same frame.\n\n\n\n\\section{Static stability}\n\\label{sec:static_stability}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                    SUBSECTION STATIC STABILITY                      %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nWe denote $g$ the acceleration of gravity on earth $g = 9.81 m.s^{-2}$.\nThe wrench associated with the action of gravity on a body of mass $M$ which center of mass is denoted $G$ with $\\vec{z}$ the upward vertical vector in the world frame $F_0$ is:\n\\begin{equation}\n  w_g|^G_{F_0} = \\left\\{ \\begin{array}{r}\n     \\vec{0} \\\\\n     -Mg\\vec{z} \\\\\n \\end{array}\\right\\}^G_{F_0}\n\\end{equation}\n\nA solid is statically stable if it satisfies the Euler-Newton Equation.\nWe consider a robot on which $m$ external wrench $w_i = \\left\\{ \\begin{array}{r}\n    \\vec{m_i}\\\\\n    \\vec{f_i}\\\\\n\\end{array} \\right\\}^{P_i}$ are applied.\nWe denote $P$ the application point at which the equation and all its terms are calculated:\n\\begin{equation}\n  \\sum\\limits_i w_i|^P + w_g|^P = 0\n\\end{equation}\nwhich is equivalent to:\n\\begin{equation}\n\\left\\{\n\\begin{array}{r}\n  \\sum\\limits_i \\vec{m_i}|^P + \\overrightarrow{GP}\\wedge Mg\\vec{z} = 0 \\\\\n  \\sum\\limits_i \\vec{f_i} - Mg\\vec{z} = 0 \\\\\n\\end{array}\n\\right.\n\\end{equation}\n\nThis equation can be simplified by applying it at the center of mass of the body as:\n\\begin{equation}\n  \\left\\{\n  \\begin{array}{r}\n    \\sum\\limits_i \\vec{m_i}|^G = 0 \\\\\n    \\sum\\limits_i \\vec{f_i} - Mg\\vec{z} = 0 \\\\\n  \\end{array}\n  \\right.\n\\label{eq:stability}\n\\end{equation}\n\nSatisfying equation~\\Eqref{eq:stability} ensures the static equilibrium of a rigid body.\nIf the robot's actuators are powerful enough to maintain its posture under any external perturbation, namely, when they can generate infinite or at least large enough torques, then the robot can be approximated as a rigid body and satisfying equation~\\Eqref{eq:stability} is enough to ensure its stability.\n%In some cases, an articulated robot is considered as a rigid body and this equation alone can be used to ensure its stability.\n%It is only valid if the robot can generate infinite torques in its articulations, or at least if we have some guarantee that the robot is able to generate large enough torques.\nOtherwise, it is necessary to verify that the robot's actuators can generate large enough torques to maintain that posture.\nThe details concerning the torque computations are discussed in Section~\\ref{sec:torque_limits}\n\nEquation~\\Eqref{eq:stability} can be used in an optimization problem.\nWe consider that each wrench $w_i$ applied on the system is defined by the position of its application point $P_i$ and the values $m_i$ and $f_i$ that represent the moment and resultant of $w_i$ at $P_i$.\n$P_i$ depends on $q$ the joint parameter of the robot.\n$m_i$ and $f_i$ are new variables that need to be added to the problem.\nIn summary, $w_i$ depends on $q$, $m_i$ and $f_i$.\nWe denote $f$ the concatenation of all the variables $m_i$ and $f_i$.\n\n\\begin{equation}\n  \\boxed{s(q,f) = \\left\\{\n  \\begin{array}{r}\n    \\sum\\limits_i \\vec{m_i} + \\overrightarrow{P_i G}\\wedge \\vec{f_i} \\\\\n    \\sum\\limits_i \\vec{f_i} - Mg\\vec{z} \\\\\n  \\end{array}\n  \\right\\}\n  = 0}\n\\end{equation}\n\nThe optimization problem~\\Eqref{eq:optim_form_PG} becomes (we denote m the dimension of the force variables):\n\n\\begin{equation}\n\\label{eq:optim_form_PG_with_stab}\n  \\left\\{\n  \\begin{array}{l}\n    \\min\\limits_{q\\in\\mathcal{C}, f\\in \\mathbb{R}^m}{f(q)}\\\\\n    \\text{ s.t. }\n    \\left\\{\n    \\begin{array}{l}\n      s(q,f) = 0\\\\\n      c_i(q) = 0,\\ \\forall i\\in{E}\\\\\n      c_i(q) \\geq 0,\\ \\forall i\\in{I}\\\\\n    \\end{array}\n    \\right.\n  \\end{array}\n  \\right.\n\\end{equation}\n\nThe derivation of the static stability constraint is straightforward.\nAll the terms of equation~\\Eqref{eq:stability} are components of wrenches.\nA wrench is completely defined by the frame in which it is expressed and its values of resultant and moment in that frame.\nDeriving the stability condition boils down to deriving each term w.r.t its components values and w.r.t the transformation of its frame.\n\n\\begin{equation}\n\\left\\{\n\\begin{array}{r}\n  \\partial\\left(\\sum\\limits_i m_i|^G\\right) = \\sum\\limits_i \\partial(m_i|^G) \\\\\n  \\partial\\left(\\sum\\limits_i f_i\\right) = \\sum\\limits_i \\partial(f_i) \\\\\n\\end{array}\n\\right.\n\\label{eq:derivation_stability}\n\\end{equation}\n\nWe will explicit a method to automatically compute those derivatives in a later chapter.\n\n\n\n\\section{Center of mass projection}\n\\label{sec:center_of_mass_projection}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                SUBSECTION CENTER OF MASS PROJECTION                 %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nWhen all the wrenches applied to the body are due to unilateral punctual contacts on the same horizontal plane $H = \\{O, \\vec{x}, \\vec{y}\\}$, the stability criterion~\\Eqref{eq:stability} can be simplified.\nThe wrench $w_i$ generated by a unilateral punctual contact is a pure force resultant, its moment part is zero on the contact point.\n\n\\begin{equation*}\n    \\left. w_i \\right|^{P_i} =\n    \\left\\{\n      \\begin{array}{r}\n      \\vec{0}\\\\\n      \\vec{f_i}\\\\\n  \\end{array} \\right\\}^{P_i}\n\\end{equation*}\n\nEquation~\\Eqref{eq:stability} becomes:\n\n\\begin{equation}\n\\left\\{\n\\begin{array}{r}\n  \\sum\\limits_i \\overrightarrow{OP_i}\\wedge \\vec{f_i} - \\overrightarrow{OG} \\wedge Mg\\vec{z} = 0 \\\\\n  \\sum\\limits_i \\vec{f_i} - Mg\\vec{z} = 0 \\\\\n\\end{array}\n\\right.\n\\end{equation}\n\nWe can write $\\overrightarrow{OG} = \\overrightarrow{OG_p} + z_G\\vec{z}$ with $G_P$ the projection of $G$ on $H$. Replacing in the moment equation gives:\n\n\\begin{equation}\n  \\sum\\limits_i \\overrightarrow{OP_i}\\wedge \\vec{f_i} - \\sum\\limits_i\\overrightarrow{OG_P} \\wedge \\vec{f_i} = 0\n\\label{eq:projCoM}\n\\end{equation}\n\nWith $f_i = f_i^x\\vec{x} + f_i^y\\vec{y} + f_i^z\\vec{z}$, $G$ and $P_i$ can be written as $\\overrightarrow{OG_P} = G_x \\vec{x} + G_y\\vec{y}$ and $\\overrightarrow{OP_i} = P_{ix} \\vec{x} + P_{iy} \\vec{y}$. The two first lines of equation~\\Eqref{eq:projCoM} give:\n\n\\begin{align}\n\\sum\\limits_i \\left\\{\\begin{array}{r} P_{iy}f_i^z\\\\-P_{ix}f_i^z\\end{array}\\right\\}\n= \\left\\{\\begin{array}{r} G_{y}\\\\-G_{x}\\end{array}\\right\\} \\sum\\limits_i f_i^z\\\\\n  \\overrightarrow{OG_P} = \\frac{\\sum\\limits_i \\overrightarrow{OP_i} f_i^z}{\\sum\\limits_i f_i^z}\n\\end{align}\n\nSince all the contacts are unilateral, all the $f_i^z$ must be positive.\nFor any set of $f_i^z\\geq0$, $G_P$ is a barycenter with positive coefficients of the $P_i$.\nAny point $G_P$ that is included in the convex hull of all the $P_i$ is a solution.\n\nThus, we have the property: a rigid body that has all its contacts with the environment being punctual, unilateral and all lying on the same horizontal plane $H$, is said stable if and only if the projection of its center of mass on $H$ is inside the convex hull of all its contact points.\n\n\n\n\\section{Torque limits}\n\\label{sec:torque_limits}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                      SUBSECTION TORQUE LIMITS                       %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nIn general, satisfying equation~\\Eqref{eq:stability} is not enough to ensure that a robot can be statically stable.\nThe joint torques that are required to hold the posture must be within the physical capabilities of the robot, namely, its torque limits.\nWe denote $\\tau_i^-$ and $\\tau_i^+$ the minimal and maximal torques that can be generated by the robot's actuators on joint $J_i$.\nIn some cases, the torque limits can depend on the joint parameters $\\tau_i^-(q)$ and $\\tau_i^+(q)$.\nFor example, it is the case with the Atlas robot that is hydraulically actuated.\n\nFeatherstone~\\cite{featherstone:book:2007} proposes a recursive algorithm to compute the torques, accelerations, and velocities generated in a multi-articulated system by a set of external forces called the Inverse Dynamics Algorithm.\nFor the purpose of generating statically stable postures, the velocities and accelerations are not needed.\nThus, we devise a specialized algorithm to fit our needs and call it the Inverse Static Algorithm.\n\nWe denote $a_g$ the gravity acceleration vector with $\\vec{a_c}$ its rotation part and $\\vec{a_f}$ its translation part:\n\\begin{equation}\n  a_g = \\left\\{ \\begin{array}{r}\n    \\vec{a_c} \\\\\n    \\vec{a_f} \\\\\n  \\end{array} \\right\\}\n  = \\left\\{ \\begin{array}{r}\n    \\vec{0} \\\\\n    g\\vec{z}\\\\\n  \\end{array} \\right\\}\n\\end{equation}\n\nThe algorithm first computes the generalized forces $f^G_i$ applied to each body.\nIt is the sum of the action of gravity and of the external forces applied on a body calculated at the origin of the world frame, expressed in the world frame.\nThen, the generalized forces are used to compute the torques.\nWe denote $\\mathbf{I}_i$ the inertia matrix of body $i$.\n\n\\begin{algorithm}\n  \\caption{Inverse Static Algorithm}\n\\label{alg:IS}\n\\begin{algorithmic}\n  \\For{$i = 0:n_B$}\n  \\State$f^G_i = \\mathbf{I}_i {}^i\\mathbf{X}_0 a_g - {{}^i\\mathbf{X}_0}^*f_i^{ext}$\n  \\EndFor{}\n  \\For{$i = n_J-1:0$}\n  \\State$\\tau_i = {f^G_i}^T S_i$\n  \\If{$pred(i) \\neq -1$}\n  \\State$f^G_{pred(i)} += {\\mathbf{X}^{PtS}_i(\\mathbf{q})}^{-*} f^G_i$\n  \\EndIf{}\n  \\EndFor{}\n\\end{algorithmic}\n\\end{algorithm}\n\nWe can write the torques as a function of the joint parameters and the external forces $\\tau(\\mathbf{q},\\mathbf{f})$.\nThe torque limit constraint writes as:\n\\begin{equation}\n  \\boxed{\\tau^- \\leq \\tau(\\mathbf{q},\\mathbf{f}) \\leq \\tau^+}\n\\end{equation}\n\nWe will detail the derivation of this constraint in Section~\\ref{sec:torque_derivation}.\n\n\n\\section{Contact Forces and Friction Cones}\n\\label{sec:contact_forces_and_friction_cones}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%            SUBSECTION CONTACT FORCES AND FRICTION CONES             %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%Here we use the same frames and notations as introduced in Section~\\ref{sec:contact_constraints}.\n\nThe contacts involved in a posture generation problem can be separated into two types:\n\\begin{itemize}\n  \\item Geometric Contacts, and\n  \\item Stability Contacts.\n\\end{itemize}\nThe Geometric Contact is a contact where the position of contact is reached with theoretically zero force, i.e. that contact does not support any forces (this is a necessary step to generate a sequence of quasi-static transitions).\nPhysically, that correspond to the transition state between a configuration without contact and a configuration with contact on which forces are applied.\nWe defined the Geometric Contacts in Section~\\ref{sec:contact_constraints}.\nThe Stability Contact is a Geometric Contact that bears contact forces.\n\n%In planning, contacts are added or removed one by one between successive postures.\n%In order to add or remove a stability contact, it is necessary to go through a geometric contact (that guarantees the continuity on contact forces).\n%First a geometric contact configuration is found, then on the next posture, that geometric contact is fixed ond forces are added on it, it becomes a stability contact.\n%Similarly, to remove a stability contact, we first look for a posture with a fixed geometric contact in place of the stability contact to remove.\n%And on the next posture, the contact can be removed.\n\nWe denote $w_{1\\rightarrow 2}$ the force applied by body $B_1$ on body $B_2$.\nThen the force applied by $B_2$ on $B_1$ is $w_{2\\rightarrow 1} = -w_{1\\rightarrow 2}$.\n%These interaction forces must be taken into account in the stability and torque computations of each robot involved in the contact.\n\nThe interaction force resulting from a punctual contact (see~\\Figref{fig:frictionCone}) on a point $P$ can be modeled as a pure force resultant along the $z_1$ direction $\\vec{f_n} = f_z \\vec{z_1}$ and the tangential efforts due to the friction in that contact can be modeled as $\\vec{f_t} = f_x \\vec{x_1} + f_y \\vec{y_1}$.\n%A punctual contact cannot carry moments on its contact point.\n\n\\begin{equation}\n\\label{eq:punctual_force}\n\\left. w_{2\\rightarrow 1}\\right|^P = \\left\\{\n  \\begin{array}{l}\n    \\vec{0} \\\\\n    \\overrightarrow{f_{2\\rightarrow 1}} = \\vec{f_t} + \\vec{f_n} \\\\\n  \\end{array}\n  \\right\\}^P\n\\end{equation}\n\n\\begin{figure}[htpb]\n  \\centering\n  \\includegraphics[width=0.6\\linewidth]{frictionCone.pdf}\n  \\caption{Punctual unilateral stability contact with friction}\n\\label{fig:frictionCone}\n\\end{figure}\n\nThis formulation of the interaction force defines a bilateral contact, in the sense that the force can be in any direction, $B_1$ can push as well as pull on $B_2$.\n\nTo model a unilateral contact, we must constrain the normal component of $f_{2\\rightarrow 1}$ to be oriented toward the inside of $B_1$.\nThis means that only pushing actions can be generated, not pulling ones.\nThis translates into:\n\\begin{equation}\n  \\overrightarrow{f_{2\\rightarrow 1}}\\cdot \\vec{z_1} = f_z \\geq 0\n\\end{equation}\n\nFurthermore, to avoid slippage, the Coulomb friction law must be respected for each contact force $\\vec{f}$.\n%This law states that the contact force resultant must lay inside a friction cone of angle $\\mu$, the friction coefficient.\nWhich translates into the following equation, with $\\vec{f_n}$ and $f_t$, respectively the normal and tangential parts of $\\vec{f}$ and $\\mu$, the friction coefficient:\n\n\\begin{equation}\n  \\mu\\|\\vec{f_n}\\| \\geq \\|\\vec{f_t}\\|\n\\end{equation}\n\nGiven the decomposition of $f_{2\\rightarrow 1}$ in $F_1$, $f_{2\\rightarrow 1} = f_x \\vec{x_1} + f_y \\vec{y_1} + f_z \\vec{z_1}$, for any punctual contact in a posture generation problem, we can add the following set of constraint to our optimization problem:\n\\begin{equation}\n  \\label{eq:unilateralContact}\n  \\left\\{\n  \\begin{array}{l}\n    f_z \\geq 0 \\\\\n    \\mu^2 f_z^2 - f_x^2 +f_y^2 \\geq 0\n  \\end{array}\n  \\right.\n\\end{equation}\n\nWhen it comes to planar contacts on surface $S$ with $\\vec{n}$ the outbound normal to $S$, the interaction force can have components of forces and moments in all directions.\nThe forces components intrinsic to the planar contact model are a resultant part aligned with $\\vec{n}$ $\\vec{f_n} = f_z \\vec{z_1}$ and a moment part tangential to $S$: $\\vec{m_t} = m_x \\vec{x_1} + m_y \\vec{y_1}$.\nThe forces due to friction are a tangential friction resultant part $\\vec{f_t} = f_x \\vec{x_1} + f_y \\vec{y_1}$ and a normal friction moment $\\vec{m_n} = m_z \\vec{z_1}$.\n\nThis type of force can be modeled by a set of unilateral punctual efforts applied on each vertex of a polygon describing the contact area.\nAnd ensuring that each of them lay in their respective friction cone, thus satisfying the equation~\\Eqref{eq:unilateralContact}.\nAs depicted in~\\Figref{fig:planarContact}\n\n\\begin{figure}[htpb]\n  \\centering\n  \\setlength{\\fboxsep}{0pt}%\n  \\setlength{\\fboxrule}{1pt}%\n  \\fbox{\\includegraphics[width=0.6\\linewidth]{planarContact.pdf}}\n  \\caption{Modeling of a planar contact between the foot on HRP-4 and the ground.}\n\\label{fig:planarContact}\n\\end{figure}\n\n\n\\section{Cost Functions}\n\\label{sec:cost_functions}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                       SECTION COST FUNCTIONS                        %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nIn addition to constraints, it is often useful to add a cost function to our optimization problem.\nThe submanifold of feasible configurations $\\mathcal{C}_F$ can contain an infinity of solutions and even some continuous solution areas in which all points are solutions.\nThe cost function helps to choose the `best' candidate solution.\nVarious types of cost functions can be chosen, for example, we can minimize the distance to a reference posture $q_R$:\n\n\\begin{equation*}\n  f_\\text{posture}(\\mathbf{q}) = {\\|\\mathbf{q}-q_R\\|}^2\n\\end{equation*}\n\nThe effect of that type of cost function is illustrated in~\\Figref{fig:cost}.\nOn both images, the HRP-2Kai robot is stable, respects its joints and torques limits.\nThe only difference is that the right one minimizes the distance to a reference posture (standing straight with bent knees) while the left result does not use a cost function.\n\n\\begin{figure}[htpb]\n  \\centering\n  \\setlength{\\fboxsep}{0pt}%\n  \\setlength{\\fboxrule}{1pt}%\n  \\fbox{\\includegraphics[width=0.5\\linewidth]{cost.pdf}}\n  \\caption{Effect of cost function. Left: no cost function. Right: Distance to a half-sitting predefined posture.}\n\\label{fig:cost}\n\\end{figure}\n\nOne can also want to minimize the sum of norms of the contact forces:\n\\begin{equation*}\n  f_\\text{forces}(\\mathbf{f}) = \\sum\\limits_i {\\|f_i(\\mathbf{f})\\|}^2\n\\end{equation*}\nor the torques in the robot's joints:\n\\begin{equation*}\n  f_\\text{torques}(\\mathbf{q},\\mathbf{f}) = \\sum\\limits_i {\\|\\tau_i(\\mathbf{q},\\mathbf{f})\\|}^2\n\\end{equation*}\nSome more custom cost functions can also be considered, for example, we may want a point $P_i$ on body $B_i$ with to be as far as possible in a direction $\\vec{d}$\n\\begin{equation*}\n  f_\\text{point} (\\mathbf{q}) = -{\\overrightarrow{O_0 P_i}}\\cdot{\\vec{d}}\n\\end{equation*}\n\nAny positively weighted combination of cost function can be used, in which case it is important to choose the weights $p_i$ carefully to scale all the costs so that they all can influence the result and none is completely dominated by another.\n\\begin{equation}\n  f_\\text{cost}(\\mathbf{q},\\mathbf{f}) = \\sum\\limits_i{p_i f_i(\\mathbf{q},\\mathbf{f})} = p_0 f_\\text{posture}(\\mathbf{q}) + p_1 f_\\text{forces}(\\mathbf{f}) + p_2 f_\\text{torques}(\\mathbf{q},\\mathbf{f}) + \\cdots\n\\end{equation}\n\n\n\n\\section{Conclusion}\n\\label{sec:Ch1_Conclusion}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                         SECTION CONCLUSION                          %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nIn this Chapter, we have seen how to formulate a robotics problem with several different tasks and objectives as an optimization problem.\n\nWe denote $\\mathcal{T}_i$ the additional tasks added to the problem, which is described by the set of equalities $g_i(\\mathbf{q},\\mathbf{f}) = 0$ and inequalities $h_i(\\mathbf{q},\\mathbf{f}) \\geq 0$.\nThe contact tasks are included in those and the equations describing them must encompass the geometric contact constraint equation like~\\Eqref{eq:coplanarity} as well as the unilateral and friction constraints equations~\\Eqref{eq:unilateralContact} in the case of a unilateral contact.\n\nA typical robotics problem can be written as a combination of all those costs and constraints:\n\\begin{align}\n\\minimize_{\\mathbf{q}, \\mathbf{f}} & \\quad f_\\text{cost}(\\mathbf{q},\\mathbf{f}) \\nonumber\\\\\n\\text{s.t.}&\n\\left\\{\n\\begin{array}{lr}\nq^- \\le \\mathbf{q} \\le q^+\\\\\ns(\\mathbf{q},\\mathbf{f}) = 0 \\\\\n\\tau^- \\le \\tau(\\mathbf{f},\\mathbf{q}) \\le \\tau^+\\\\\n\\forall \\{B_i, B_j, \\epsilon_{ij}\\} \\in Coll,\\ d_{\\{B_i, B_j\\}}(\\mathbf{q}) > \\epsilon_{ij}\\\\\ng_i(\\mathbf{q},\\mathbf{f}) = 0\\ \\ \\forall\\mathcal{T}_i,\\\\\nh_i(\\mathbf{q},\\mathbf{f}) \\geq 0\\ \\ \\forall\\mathcal{T}_i.\n\\end{array}\\right.\n\\label{eq:PG}\n\\end{align}\n\nIn the following chapter, we present an extension to the contact constraint formulation that allows generating non-inclusive contacts, an algorithm to compute the exact derivatives of the torques in robot's joints, and our endeavor to apply a different optimization approach to solving posture generation problems.\n", "meta": {"hexsha": "343675c6dd142142c4d7ba707de7a5d9f93618aa", "size": 51900, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapter2-PG/chapter2.tex", "max_stars_repo_name": "stanislas-brossette/phd-thesis", "max_stars_repo_head_hexsha": "7f4d2d46dfdd1f59ac29770585e8cee6dc4f2668", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter2-PG/chapter2.tex", "max_issues_repo_name": "stanislas-brossette/phd-thesis", "max_issues_repo_head_hexsha": "7f4d2d46dfdd1f59ac29770585e8cee6dc4f2668", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter2-PG/chapter2.tex", "max_forks_repo_name": "stanislas-brossette/phd-thesis", "max_forks_repo_head_hexsha": "7f4d2d46dfdd1f59ac29770585e8cee6dc4f2668", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.1894150418, "max_line_length": 399, "alphanum_fraction": 0.6678034682, "num_tokens": 15265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3439531101038274}}
{"text": "\\documentclass[11pt]{article}\n\\usepackage{graphicx}\n\\usepackage{amssymb}\n\\usepackage{multicol}\n\\usepackage{epstopdf}\n\\DeclareGraphicsRule{.tif}{png}{.png}{`convert #1 `dirname #1`/`basename #1 .tif`.png}\n\n\\textwidth = 6.5 in\n\\textheight = 9 in\n\\oddsidemargin = 0.0 in\n\\evensidemargin = 0.0 in\n\\topmargin = 0.0 in\n\\headheight = 0.0 in\n\\headsep = 0.0 in\n\\parskip = 0.2in\n\\parindent = 0.0in\n\n\\newtheorem{theorem}{Theorem}\n\\newtheorem{corollary}[theorem]{Corollary}\n\\newtheorem{definition}{Definition}\n\n\\title{{\\tt kuramoto\\underline{ }1d.m} - Kuramoto-Sivashinsky Solvers}\n\\author{Jeff Borggaard}\n\\begin{document}\n\\maketitle\n\n\\section*{Summary}\nThis software (and the similar {\\tt kuramoto\\underline{ }1da.m}) solves the \nKuramoto-Sivashinsky equation using $C^1$ Hermite cubic elements in a \nperiodic domain.\n\n\\section*{The Equations}\nThere are two popular forms of the Kuramoto-Sivashinsky equations.  The first\nmimics the form originally derived by Kuramoto \\cite{kuramoto}.\n%\n\\begin{equation}\n\\label{eq:ks1}\n d\n\\end{equation}\n\nThe second has the form of the derivative of equation (\\ref{eq:ks1}), namely\n%\n\\begin{displaymath}\n  w_t + w_{xx} + w_{xxxx} + 2 w w_x = 0.\n\\end{displaymath}\n%\nNote that if we scale the spatial variable so that the computational\ndomain occurs over the unit interval: $\\bar{x} = x/L$, and define\n$\\epsilon = 1/L^2$, then we have the following version of the Kuramoto-Sivashinsky equation\n%\n\\begin{equation}\n\\label{eq:ks2}\n  w_t + \\epsilon w_{\\bar{x}\\bar{x}} + \\epsilon^2 w_{\\bar{x}\\bar{x}\\bar{x}\\bar{x}} + 2 \\epsilon w w_{\\bar{x}} = 0\n\\end{equation}\n%\nwith $t>0$, $\\bar{x} \\in (0,1)$, $w(0,t) = w(1,t)$ and $w_{\\bar{x}}(0,t) = \nw_{\\bar{x}}(1,t)$.  The initial condition is scaled so that \n$w(\\bar{x},0) = w_0(\\bar{x})$.\n\nA nice property of solutions to equation (\\ref{eq:ks2}) is that the integral\n%\n\\begin{equation}\n\\label{eq:w_ave}\n  \\int_0^1 w(\\bar{x},t) \\ d\\bar{x}\n\\end{equation}\n%\nis independent of time.  In other words, the average of the solutions is\ndetermined from the average of the initial conditions.  This imposes a \ngreat deal of structure on the solutions as will be seen in the numerical\ntests.\n\n\n\\section*{Parameters}\nInput parameters\n%\n\\begin{itemize}\n  \\item {\\tt epsilon} - \\newline\n  This parameter has the effect of changing the length of the periodic\n  domain.  See the scaling of the equations above.\n\\end{itemize}\n\nInternal parameters\n%\n\\begin{itemize}\n  \\item {\\tt n\\underline{ }gauss} - \\newline\n  The number of Gauss point used in element integration\n  \\item {\\tt n\\underline{ }nodes} - \\newline\n  The number of nodes (including the shared endpoints) used in the \n  spatial discretization.  The number of Hermite elements is equal to\n  {\\tt n\\underline{ }nodes-1}.\n  \\item {\\tt t\\underline{ }initial}, {\\tt t\\underline{ }step}, \n  {\\tt t\\underline{ }save}, and {\\tt t\\underline{ }final} - \\newline\n  Time integration parameters.  The solution is saved at multiples of\n  {\\tt t\\underline{ }save}, so {\\tt t\\underline{ }save}/{\\tt t\\underline{ }step}\n  should be a positive integer.\n  \\item {\\tt resid\\underline{ }tol} - \\newline\n  Residual tolerance for Newton solve at each timestep.\n  \\item {\\tt step\\underline{ }tol} - \\newline\n  Step tolerance for Newton solve at each timestep.\n  \\item {\\tt max\\underline{ }iterations} - \\newline\n  Number of Newton iterations attempted to achieve one of the convergence\n  tolerances in each timestep.\n\\end{itemize}\n\n\\section*{Dynamical Systems Analysis}\n\n\\begin{table}\n\\begin{center}\n\\begin{tabular}{lll}\n\\hline\nlength $L$ & \\multicolumn{1}{c}{$\\epsilon$} & solution behavior \\\\\n\\hline\n12.5664  &  0.00633257  & bifurcation \\\\\n12.8767  &  0.00603102  & heteroclinic bifurcation \\\\\n13.1403  &  0.00579148  & hopf bifurcation \\\\\n402.2590 &  0.00000618  & ``chaos'' \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\end{table}\n\n\\end{document}", "meta": {"hexsha": "4a415ed8eabddf974da033ef20d89a3403142210", "size": 3821, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "SplitDMD_KS-master/FEM code/kuramoto_1d.tex", "max_stars_repo_name": "jovanzigic/SplitDMD_KS", "max_stars_repo_head_hexsha": "ddfe2eb81ffcda58837e3e7fe63476ff578b8bf4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SplitDMD_KS-master/FEM code/kuramoto_1d.tex", "max_issues_repo_name": "jovanzigic/SplitDMD_KS", "max_issues_repo_head_hexsha": "ddfe2eb81ffcda58837e3e7fe63476ff578b8bf4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SplitDMD_KS-master/FEM code/kuramoto_1d.tex", "max_forks_repo_name": "jovanzigic/SplitDMD_KS", "max_forks_repo_head_hexsha": "ddfe2eb81ffcda58837e3e7fe63476ff578b8bf4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3196721311, "max_line_length": 112, "alphanum_fraction": 0.7110704004, "num_tokens": 1264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961013, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.3439486172814331}}
{"text": "\n\n    \\filetitle{srf}{Shock (impulse) response function}{SVAR/srf}\n\n\t\\paragraph{Syntax}\\label{syntax}\n\n\\begin{verbatim}\n[Resp,Cum] = srf(V,NPer)\n[Resp,Cum] = srf(V,Range)\n\\end{verbatim}\n\n\\paragraph{Input arguments}\\label{input-arguments}\n\n\\begin{itemize}\n\\item\n  \\texttt{V} {[} SVAR {]} - SVAR object for which the impulse response\n  function will be computed.\n\\item\n  \\texttt{NPer} {[} numeric {]} - Number of periods.\n\\item\n  \\texttt{Range} {[} numeric {]} - Date range.\n\\end{itemize}\n\n\\paragraph{Output arguments}\\label{output-arguments}\n\n\\begin{itemize}\n\\item\n  \\texttt{Resp} {[} tseries \\textbar{} struct {]} - Shock response\n  functions.\n\\item\n  \\texttt{Cum} {[} tseries \\textbar{} struct {]} - Cumulative shock\n  response functions.\n\\end{itemize}\n\n\\paragraph{Options}\\label{options}\n\n\\begin{itemize}\n\\item\n  \\texttt{'presample='} {[} \\texttt{true} \\textbar{}\n  \\emph{\\texttt{false}} {]} - Include zeros for pre-sample initial\n  conditions in the output data.\n\\item\n  \\texttt{'select='} {[} cellstr \\textbar{} char \\textbar{} logical\n  \\textbar{} numeric \\textbar{} \\emph{\\texttt{Inf}} {]} - Selection of\n  shocks to which the responses will be simulated.\n\\end{itemize}\n\n\\paragraph{Description}\\label{description}\n\n\\paragraph{Example}\\label{example}\n\n\n", "meta": {"hexsha": "8c49f6d7789dc88e78110a168716c3879187fcb2", "size": 1258, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "-help/SVAR/srf.tex", "max_stars_repo_name": "OGResearch/IRIS-Toolbox-For-Octave", "max_stars_repo_head_hexsha": "682ea1960229dc701e446137623b120688953cef", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-12-06T13:38:38.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-06T13:38:38.000Z", "max_issues_repo_path": "-help/SVAR/srf.tex", "max_issues_repo_name": "OGResearch/IRIS-Toolbox-For-Octave", "max_issues_repo_head_hexsha": "682ea1960229dc701e446137623b120688953cef", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-03-28T08:13:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-02T10:40:25.000Z", "max_forks_repo_path": "-help/SVAR/srf.tex", "max_forks_repo_name": "OGResearch/IRIS-Toolbox-For-Octave", "max_forks_repo_head_hexsha": "682ea1960229dc701e446137623b120688953cef", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-17T07:06:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T07:06:39.000Z", "avg_line_length": 23.7358490566, "max_line_length": 70, "alphanum_fraction": 0.6939586645, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.3439486172814331}}
{"text": "\\section*{Results}\nWhile the prospect of private property drives cooperation,\\footnote{I don't know how this assertion finds an operationalization in the model $\\rightarrow$ maybe rephrase or even drop} cooperation is itself sensitive to property violation. While small quantities of property violation introduce some amount of randomness that enhances cooperation (see Figure \\ref{fig:phase_transition}a), we focus on the limit amount of property violation beyond which cooperation transitions to defection.\\footnote{as said above the overall rational is that private property enforcement is costly for society, and hence there is an incentive to find the maximum bearable level of private property.}\\\\\n\nOur model operationalizes the action of property violation as a uniform random variable [$p(S \\geqslant s) = 1$], with sure strategy update ($r=0$),\\footnote{for strategy update we resort to the update method proposed by Helbing and Yu \\cite{helbing2009outbreak}, which in our noiseless case is equivalent to the Fermi update with Fermi temperature equal to 1.} no random strategy reset ($q=0$) and no random migration to an empty site ($m=0$). And as players choose their best shot in the success-driven migration step, we can say that they are fully rational agents (in their migration range), which choice to expel another individual results only from odds of property enforcement.\\footnote{These parameters settings ensure the simplest possible model that guaranties that the observed stylized facts are genuine to the property violation phenomenon.} \\\\\n\n\\subsection*{Population density, Migration Range and Cooperation Level} \nThe outcome of the property violation game is nevertheless constrained by the initial conditions, such as population density and migration range: Increased population density reduces the opportunities to find an empty location, and thus, mechanically increases the odds of property violation. The migration range on the one hand increases the chances to find an empty sweet spot in case of success-driven  or forced migrations. On the other hand, it also increases opportunities for property violators. Migration influences the capability by defectors to penetrate clusters of cooperators. However, expelled cooperators can move far enough to make the cluster move away from the defector. Hence, larger migration ranges increase tolerance to property violation (see Figure \\ref{fig:phase_transition}b), but their beneficial effects are limited for highly densely populations. On the contrary, populations with very short migration ranges -- here, embodied by unitary migration distance ($M=1$) -- can hardly stand any property violation. \n\n%Nevertheless, the intensity of property violation is determinant in the ability by defectors to break clusters of cooperators %(see Figure \\ref{fig:viz} and online visualization tool).\n\n\\subsection*{Optimizing for Property Violation is Managing at the Edge of Collapse}\nProperty enforcement is costly, and thus, there is an incentive to limit enforcement to the strict minimum, which will ensure high cooperation (which is equivalent to decide how much property crime a society can stand). For large enough migration ranges ($M\\geqslant 3$), a little property violation ($s < 1 \\%$), brings the necessary randomness that reduces friction and enhances cooperation, similarly to previous results obtained with other types of noise involved in success-driven migration games \\cite{helbing2009outbreak}. For larger property violation $s > 1\\%$, cooperation decreases linearly according to $ c = 1 - 2.2\\cdot s$, until a critical phase transition is reached (see Figure \\ref{fig:phase_transition}a), which itself depends on the population density and the migration range as reported on Figure \\ref{fig:phase_transition}b. There is no hard limit, but rather a transition from sure striving society with high cooperation to a sure collapse. The region in between is large compared to the absolute value of the upper limit: For instance, for $M=5$ and $d=0.5$, the phase transition spans from $s = 3.7\\%$ to $s= 4.2\\%$, with an equal chance to survive or collapse for property violation $s=4\\%$. Hence, the ``danger zone\" spans over more than 10\\% of the limit value, and the decreasing probability of striving in the critical phase transition region, makes it very hard to determine whether the course of a society will end up positively or negatively.\\footnote{We have verified that the outcome is independent from the initial grid organization, by running multiple simulations from the same initial grid.}\n\n\\subsection*{Decoupling for Sustainable Cooperation}\nThe sudden phase transition from high cooperation to collapse suggests a ``grain of sand\" factor deciding whether a society operating at the limit level of property violation will strive or collapse.\\footnote{Again, it's important to stress that it is natural for a society to operate close to the limit, since private property enforcement is costly, and even sometimes socially undesired.}\\\\\n\nTo better determine this ``grain of sand\", we resort to simple of economics implied by the property game and opportunities evolve over time: To maximize their payoff, individuals are endowed with three basic rules, \n\n\\begin{itemize}\n  \\item {\\bf strategy update rule:} the player updates its prisoner's dilemma strategy (i.e., cooperate or defect), as a function of her neighbors strategies,\n  \\item {\\bf success driven migration:} the player migrates to the best empty site within her migration area determined by the Moore distance $M$,\n  \\item {\\bf property violation:} the player attempts to expel with probability $s$ another player from her location within their migration area determined by the Moore distance $M$.\n\\end{itemize}\n\nThe three strategies are opportunity based, deterministic for the first two (i.e., if players are presented with better options they will update their strategy or migrate) and random for property violation, reflecting the unsure nature of taking the property of someone else. While decisions are idiosyncratic at the individual level, at the aggregate level, they reveal the expected utility $U$ carried by each rule, which can be formulated as \n\n\\begin{equation}\nU_{rule} = p_{rule} \\times u_{rule},\n\\label{U}\n\\end{equation}\n\nwith $p_{rule}$ the probability to execute one of the 3 {\\it rules} defined above (i.e., $rule = \\{$update, migration, expel$\\}$, and $u_{rule}$ the payoff increase from executing a {\\it rule}. For prisoner's dilemma strategy update and success-driven migration $p_{rule} = (1~|~u_{rule} > 0)$ (reflecting the deterministic decision to execute these rules) and for property violation $p_{rule} = (s~|~u_{rule} > 0)$, reflecting the unsure nature of attempting to expel another individual. For each rule, $U_{rule}(t)$ provides a direct measure -- at the aggregate level -- of opportunity associated with each rule and how it evolves. Similarly, one can define an expected mobility distance,\n\n\\begin{equation}\nN_{rule} = p_{rule} \\times n_{rule},\n\\end{equation}\n\nwhere $p_{rule}$ is similar as in (\\ref{U}) and $n_{rule}$ is the migration distance. $N_{rule}$ shows the expected travel distance for success-driven and property violation migration rules.\\\\\n\nStarting from a population randomly scattered across the grid with an even number of cooperators and defectors, $U$ and $N$ undergo significant changes over time, with subtle yet determinant differences between a striving and a collapsing society (see Figure \\ref{fig:tseries} for an illustration of a successful and a failed outcome with similar parameters $d=0.5$, $M=5$ and $s=0.037$; This particular case illustrates similar stylized facts obtained for different values of $d$, $M$ and $s$). In both the successful and the failed dynamics, {\\it success-driven} migration provides the highest expected payoff increase ($U_{migration} > U_{update} > U_{expel}$)  in the early iterations $t < 1.5\\times10^{5}$ (over $20\\times10^6$ MCS iterations). After $t > 1.5\\times10^{5}$, a significant change occurs: In striving societies (Figure \\ref{fig:tseries}b) a switch of expected payoff occurs, which becomes : $U_{expell} > U_{update} > U_{migration}$, while in the failed society case (Figure \\ref{fig:tseries}b), strategy update provides the highest expected increased payoff, and the expected increased payoff from success-driven and property violation migrations converge.\\footnote{ nb: It is important to note that expected payoff is not necessarily increasing overall the entire population: players expelled from their site suffer a negative expected payoff increase (not shown), as well as neighbors around the focal player who changes prisoner's dilemma strategy to defect, or a defector migrating or performing a property violation.} At the time of the switch, we observe an inflection point of the cooperation level (purple dashed circle on Figure \\ref{fig:tseries}b): After this point, cooperation still increases in the failed case, but at much lower pace,\\footnote{Mostly driven by strategy updates, which provide the highest expected payoff increase? These updates are at first of the type : $D \\rightarrow C$ and then, after the peak rather $C \\rightarrow D$. The intuition is that, somewhen migration (whether success driven or property violation) does bring enough payoff increase, compared to strategy update, therefore something weird occurs which is that cooperation increases (more or larger clusters?), which in turn prepare for an invasion of defectors!} on the contrary to striving societies for which we observe a smooth continuous increase of cooperation, up to saturation and stabilization at a high level ($c > 0.8$). In the failed scenario illustrated in Figure \\ref{fig:tseries}, the peak of cooperation is reached at  $t \\approx 5\\times10^5$, and collapse occurs after roughly$10^6$ iterations, nearly $850,000$ iterations after the switching point!\\\\\n\nWhile it is hard to observe the detailed switching mechanisms occurring at the transition point,\\footnote{This may be done in the future.} we find that the expected mobility (the probability to remains high in the failed scenario in comparison with the successful case (Figures \\ref{fig:tseries}c and \\ref{fig:tseries}d).\\footnote{It is important to note that mobility by property violation and consecutively by individuals forced to move, is not nearly as large as the mobility induced by success-driven actions (c.f., Figures \\ref{fig:tseries}b Inset 2).} Also, we find that in the successful scenario, a strong decoupling between expected payoff increase occurs (Figures \\ref{fig:tseries}a inset 1), while for the collapsing scenario, dependence between expected payoff remain high and get even reinforced (Figures \\ref{fig:tseries}b inset 2).\\footnote{The correlogram before the switch also shows high dependence (not shown here), which is natural somehow, as the system gets organized {\\bf [This correlogram (pre-switching) should be shown too, at least in the supplementary materials. In the failing scenario, it shows that property violation may influence ]}} Moreover, in the latter case, success-driven migration actions strongly drive private property violations (green correlogram) and strategy updates (red correlogram).\\footnote{The correlation peak occurs for a negative lag (roughly 15-20 bins {\\bf [I must check the size of a bin in terms of iterations]}) when considering the influence of private property violations and strategy updates on migration} Dependence between property violation and strategy update is also high (blue correlogram), but with no lag thus one cannot say whether $E \\rightarrow U$ or $U \\rightarrow E$. One can infer however that they are both influenced by success-driven migration (see red and green correlograms).\\footnote{It is unclear however what makes success-driven migration the driver of other actions. Something special must occur before or at the switching point.}\\\\\n\nPast the very first iterations where success-driven migration is the predominant way to increase payoff (in order to build and reach clusters of cooperators, regardless of whether the moving player is a cooperator or a defector), our findings draw two completely different stories leading to either collapse or well-established cooperative societies. In the latter scenario, expected payoff from success-driven migration rapidly decays to a level comparable to the expected payoff derived from strategy update and property violation. Additionally expected payoff increase from the three rules get highly independent: A spatio-temporal decoupling occurs and players no longer undergo long-range migration, and while property violation brings the highest expected payoff increase, it is tackled by some kind of locally established self-organization \\footnote{(which remains to be explained/documented in further details)}. On the contrary, the collapse scenario is driven by long-range migrations,\\footnote{We need perhaps more insights on the nature of these migrations, e.g., do they spread defectors or rather cooperators? Does this evolve over time?} which in turn trigger strategy updates and property violation.\\footnote{These long-range spatio-temporal dependences look like systemic risk to me, which may appear in a seamless, subtle and hardly noticeable way!} \\footnote{It would be interesting to check the dynamics with a residual level of property violation, e.g., $s=0.01$, and with a super high level of $s$, to see if these extreme cases magnify differences between success and failure.}\n\n\\subsection*{Enduring and Adaptive Societies Facing Property Violation}\nOne striking observation is that even though the system switches early on, and determines the final outcome, changes may remain unnoticed for a while, as cooperation increases for 4 times more iterations (since $t=0$) until collapse actually occurs.\\footnote{In some simulations, the inflection point in the increase of cooperation is hardly noticed (e.g. Figure \\ref{fig:adaptation})}\\\\\n\nThus, on the one hand it may take time to realize that a society is running towards the edge of collapse, and on the other hand, it may take time to take corrective action, such as taking actions to reduce private property violations.\\footnote{As a result of Figure \\ref{fig:phase_transition}b, one could also think of increasing migration ranges (which would require massive and long-term infrastructure investments) and decreasing population density, which concretely in our world would mostly require reducing population and would be ethically questionable. Here, we limit our study to private property violations as the main control parameter.}\\\\\n\nBudgets allocated to property right enforcement may vary over time, in particular, a typical situation is that property crime is low and therefore there is a reduced sense of urgency and budgets might be reduced as a consequence. Also on the long term, institutions concerned with property enforcement may experience downturns of efficiency (e.g., through some kind of corruption).\\\\\n\nHere, we ask two questions:  \n\n\\begin{enumerate}\n  \\item {\\bf Resistance:} Given that a cooperative society is in the process of establishing \\footnote{I am currently running simulations for this.} or has stabilized at a high level of cooperation (given a level of property violation), how much more property violation and for how long can this society stand a higher level of property violation?\n  \\item {\\bf Adaptation:} Given that a society is on the path to collapse (as shown e.g., on Figure \\ref{fig:tseries}b), how early and by how much property violation shall be reduced to ensure it will strive by reaching a stable high level of cooperation?\n\\end{enumerate}\n\n\\paragraph{Resistance:} We find that when a society has stabilized at a high cooperation level ($s=4\\%$), increasing a property violation a little ($0.05 \\leqslant s \\leqslant 0.06$) increases the chance that cooperation will collapse suddenly yet on the long run ( iterations > $3 \\times 10^5$ after change of property violation level). For higher levels of  property violation ($s>0.06$), the cooperation curves decreases in a more or less parabolic shape, which seems to be invariant in the limit of $s \\rightarrow \\infty$, and it looks like that the zero-cooperation level can be hit at earliest around $3 \\times 10^5$ after the increase of property violation (see Figure \\ref{fig:resistance}).\n\n\\paragraph{Adaptation:} The tipping point  ($t \\approx 10^5$) occurs way before the edge of actual collapse ($t \\approx 10^{5.7}$), and thus, a very natural question is whether it is possible to take corrective actions to prevent the collapse of cooperation once the tipping point has passed and has \nbeen detected. We find that unless property violation can be reduced drastically (e.g., 75\\%, c.f., Figure \\ref{fig:adaptation}d), action must be taken at latest when cooperation is at its maximum  to ensure resilience (see Figure \\ref{fig:adaptation}c when property violation is halved). For more realistic property violation reduction (10\\% to 25\\%, c.f. Figures \\ref{fig:adaptation}a and\\ref{fig:adaptation}b), the policy maker must intervene as the cooperation still increases. We could of course imagine more complicated and progressive property violation mitigation schemes (which is actually more relevant for drastic actions to reduce of property violation that may take time to take effect), but the idea is that in order to avoid collapse, action must be taken {\\bf before} the effects of property violation get actually widely noticed.\\footnote{with more simulations, we could actually compute thoroughly the odds of survival given timing and effort deployed to reduce property violation, but I think what is presented here is enough to demonstrate that it is super important to avoid doing what politicians do -- or are forced to do by the ``real-politics\" democratic mechanisms, which is taking action only when the problem get sufficiently noticeable by the population.}\\\\\n\n", "meta": {"hexsha": "a56223a7a5d329dace58cbf52581f9706adf0c89", "size": 18010, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "manuscript/sections/results.tex", "max_stars_repo_name": "wazaahhh/pgames", "max_stars_repo_head_hexsha": "acf6fbb86d689ee307b6b2f807bc29fb6a818535", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "manuscript/sections/results.tex", "max_issues_repo_name": "wazaahhh/pgames", "max_issues_repo_head_hexsha": "acf6fbb86d689ee307b6b2f807bc29fb6a818535", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2015-11-06T18:21:13.000Z", "max_issues_repo_issues_event_max_datetime": "2015-11-06T20:28:50.000Z", "max_forks_repo_path": "manuscript/sections/results.tex", "max_forks_repo_name": "wazaahhh/pgames", "max_forks_repo_head_hexsha": "acf6fbb86d689ee307b6b2f807bc29fb6a818535", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-01T15:55:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T15:55:10.000Z", "avg_line_length": 277.0769230769, "max_line_length": 2681, "alphanum_fraction": 0.7962798445, "num_tokens": 3837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499941, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.34388304749192006}}
{"text": "% !Mode:: \"TeX:UTF-8\"\n% !TEX program  = xelatex\n\\section{Summary}\nIf English is not your first language then writing the mathematical paper is doubly difficult, since you cannot guarantee the proper use of words even though with a large scientific and technical vocabulary. Therefore, Halmos comes up with three specific advice on how to use scientific and technical terms carefully,\n\\begin{enumerate}[label={\\Alph*.}]\n\t\\item Avoid using technical terms as much as possible, especially creating new ones;\n\t\\item Be careful when thinking about the new terms you have to create by looking up the dictionary to make it as appropriate as possible;\n\t\\item Correctly and consistently use the old terms without awkwardness.\n\\end{enumerate}\n\nIn addition to the terminology, you should also pay attention to the language itself. Science and technology English is generally not emotional, and its expression is relatively straightforward, which helps to make the readers easy to understand without creating too much imagination irrelevant. That is, the vocabulary using in science and technology English requires specific and sTable. Therefore, you need to accumulate basic mathematical vocabulary, mathematical symbols with their pronunciation, common phrases and language structures to better write rational mathematics papers.\n\n\n\\subsection{Basic Vocabulary}\nBasic vocabulary is an important prerequisite because you have to grapple with a large vocabulary as you try to express your thoughts. There is a large mathematical vocabulary, but the spelling is relatively simple compared to other disciplines, and as long as you master a certain amount of mathematical vocabulary, writing an uncomplicated mathematics paper will not be too difficult.\n\nPlease see Table~2.1 to Table~2.13 in \\emph{Mathematical Writing in English}\\cite{2013数学之英文写作} about the basic vocabulary in different fields of mathematics.\n\n\n\\subsection{Symbol Overview}\nMathematical language is the universal language, therefore, when using English to write technical papers or using spoken English to express certain symbols in scientific communication, you should understand the English expression of the common mathematical symbols. In this way, you can do more with less.\n\nPlease see Table~2.14 to Table~2.17 in \\emph{Mathematical Writing in English}\\cite{2013数学之英文写作} about the common symbols in different fields of mathematics.\n\n\n\\subsection{Common Phrases}\nThe common mathematical phrases found in professional English textbooks or theoretically papers are very practical and require proper collection and organization because proficiently using these phrases can be beneficial to your writing.\n\nPlease see Table~2.18 to Table~2.20 in \\emph{Mathematical Writing in English}\\cite{2013数学之英文写作} about the common phrases.\n\n\n\\subsection{Language Structures}\nSince mathematics writing has certain rules and formats in language structures and styles, there are many fixed modes in mathematics writing, which include some common sentence patterns, modified vocabulary, verbs in mathematical operations and transition statements.\n\\begin{itemize}[label={\\dag}]\n\t\\item Please see Table~2.21 in \\emph{Mathematical Writing in English}\\cite{2013数学之英文写作} about the common sentence patterns;\n\t\\item Please see Table~2.22 in \\emph{Mathematical Writing in English}\\cite{2013数学之英文写作} about the modified vocabulary;\n\t\\item Please see Table~2.23 in \\emph{Mathematical Writing in English}\\cite{2013数学之英文写作} about the verbs used in mathematical operations;\n\t\\item Please see Table~2.24 in \\emph{Mathematical Writing in English}\\cite{2013数学之英文写作} about the common verbs used in mathematics writing;\n\t\\item Please see Section~2.4.5 in \\emph{Mathematical Writing in English}\\cite{2013数学之英文写作} about the transition statements.\n\\end{itemize}\n\n\n\n\\nocite{2013数学之英文写作,Nicholas1998Handbook}\n\\bibliography{ref}\n", "meta": {"hexsha": "a4ebc91721c3d910be15c55713658253226a50a5", "size": 3844, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "MA320/sections/3.tex", "max_stars_repo_name": "iydon/homework", "max_stars_repo_head_hexsha": "253d4746528ef62d33eba1de0b90dcb17ec587ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-10-20T08:18:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-11T12:14:56.000Z", "max_issues_repo_path": "MA320/sections/3.tex", "max_issues_repo_name": "iydon/homework", "max_issues_repo_head_hexsha": "253d4746528ef62d33eba1de0b90dcb17ec587ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-01-13T03:04:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:49:10.000Z", "max_forks_repo_path": "MA320/sections/3.tex", "max_forks_repo_name": "iydon/homework", "max_forks_repo_head_hexsha": "253d4746528ef62d33eba1de0b90dcb17ec587ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-11-02T05:46:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T23:11:28.000Z", "avg_line_length": 83.5652173913, "max_line_length": 585, "alphanum_fraction": 0.8163371488, "num_tokens": 858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.34388304056234414}}
{"text": "\\section{Data}\n\\label{sec:data}\n\n\\newcommand{\\ncomoving}{10,000}\n\\newcommand{\\nfollow}{800}\n\\newcommand{\\nfollowme}{363}\n\\newcommand{\\ohpercent}{80}\n\\newcommand{\\mypercent}{80}\n\\newcommand{\\nconfirmed}{500}\n\\newcommand{\\pairprob}{99.99\\%}\n\\newcommand{\\badpairprob}{50\\%}\n\nHere we use comoving pairs and groups of stars identified in the TGAS\ncatalogue by \\citet{Oh2016}.\nThese stars do not have precise absolute ages: their absolute ages are\ninferred by fitting isochrones to their photometric colours and parallaxes.\nHowever their relative ages are very precise---they should be identical to\nwithin a few million years as we assume that they formed at the same time from\nthe same molecular cloud.\nWe use the fact that these stars are coeval to test gyrochronology by\npredicting their ages from their rotation periods.\nWe use the gyrochronal ages predicted for each star in the pair to infer the\nintrinsic scatter the gyrochronology relations.\n\nThese comoving pairs were identified in the TGAS catalogue by identifying\nstars with similar positions and proper motions by \\citet{Oh2016}.\nThe probability that the stars were comoving was compared with the probability\nthat the stars were drawn from an isotropic, random distribution of\nvelocities.\nIn this way, \\citet{Oh2016} identified \\ncomoving\\ comoving pair candidates.\n\nRadial velocity (RV) follow-up of \\nfollow\\ comoving pair candidates was\nperformed in February 2017.\n\\ohpercent\\% of these candidates were confirmed to have RVs consistent with\nbeing a comoving pair.\nOver seven nights, from the 26$^{th}$ of June to the 2${^nd}$ of July, we\nobtained RVs of \\nfollowme\\ further comoving pair candidates which fall in\nthe \\kepler\\ field of view.\nSince a small number of stars in the original \\citet{Oh2016} catalogue fall in\nthe \\kepler\\ field, we used a slightly different sample with less stringent\nfalse positive rates.\nThe original catalogue contains stars with a formal probability of being\ncomoving of \\pairprob.\nWe used a catalogue of lower probability stars, specifically with a\n\\badpairprob\\ formal probability of being a true comoving pair and selected\nonly stars within 10 parsecs of each other in order to reduce the false\npositive rate.\n\\badpairprob\\ may seem like a low probability, however with follow-up RV\nobservations we were able to identify many of the false positives in this\nlist.\nWe found \\mypercent\\% to be true comoving pairs based on their RVs.\nWe targeted stars in the \\kepler\\ field as these targets have ultra-precise\ntime-series photometry, from which we can measure rotation periods.\nWe selected the \\nconfirmed\\ confirmed comoving pairs to perform further\nanalysis.\n", "meta": {"hexsha": "9f2b4770a1d6271ba68048f6ab3a18a0e3848ce7", "size": 2652, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/data.tex", "max_stars_repo_name": "RuthAngus/teacups", "max_stars_repo_head_hexsha": "299863eb2e579cb71efce3769cf13b38eb460fd5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paper/data.tex", "max_issues_repo_name": "RuthAngus/teacups", "max_issues_repo_head_hexsha": "299863eb2e579cb71efce3769cf13b38eb460fd5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/data.tex", "max_forks_repo_name": "RuthAngus/teacups", "max_forks_repo_head_hexsha": "299863eb2e579cb71efce3769cf13b38eb460fd5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.3571428571, "max_line_length": 78, "alphanum_fraction": 0.8009049774, "num_tokens": 644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3438551753353145}}
{"text": "\\section{Introduction}\nThe idea of quantum computation was first proposed by Richard Feynman in 1981 to simulate quantum systems that are too hard to simulate using conventional classical digital computers.\n\nIn 1994, Peter Shor found an efficient quantum algorithm for factoring large numbers, which caused great intrest in quantum computation for its implications for cryptanalysis.\n\nThen, it was again Peter Shor who found quantum error-correcting codes and fault-tolerant methods for executing a quantum computation reliably using noisy hardware. It makes it possible for quantum computing to be scaled up to large devices that solve very hard problems in principal.\n\nWe often use NISQ to describe the current state of quantum computation. It stands for \\textit{Noisy Intermediate-Scale Quantum}. \"Intermediate-Scale\" conveys that today's device with more than 50 well-controlled qubits cannot be simulated by brute force using the most powerful currently existing classical computer.\n\"noisy\" means it is still not error corrected, which limits its computational power.\n\n\n\nAlthough physical realization of universal quantum computation is still in a primitive stage, there has been a lot of work in software field like IBM's QisKit, Google's Cirq and Microsoft's Q$\\sharp$.\nThey provide software tools to describe and simulate quantum algorithms and give access of cloud quantum processors or simulators to wide community.\n\nThere are three main models of quantum computing: \\textit{Quantum Turing Machine}, \\textit{Quantum $\\lambda$-Calculus} and \\textit{Quantum Circuit}, among which the third one is the most practical.\nMost quantum programming languages are \\textit{quantum-circuit description languages}, which means they are used to describe the architecture of quantum circuits.\nThe current quantum programming languages can be categorized into two categories according to their styles: functional quantum programming languages and imperative quantum programming languages.\n\\begin{multicols}{2}\n  \\begin{center}\n    Functional:\n  \\end{center}\n  \\begin{itemize}\n    \\item Qwire\n    \\item QML\n    \\item Quipper\n    \\item QuaFL\n    \\item Silq\n  \\end{itemize}\n\n  \\columnbreak\n\n  \\begin{center}\n    Imperative:\n  \\end{center}\n  \\begin{itemize}\n    \\item QASM\n    \\item QCL\n    \\item ScaffCC\n    \\item Qiskit\n    \\item Quil\n  \\end{itemize}\n\\end{multicols}\n\nAdvanced quantum programming languages can use more powerful abstract constructs and type systems to make it easier for programmers to write correct quantum programs.\nIn particular, we design a simple quantum programming language named $\\lambda_Q$, which means \\textbf{$\\boldsymbol{\\lambda}$-calculus with quantum circuit}.\nIts syntax consists of a traditional part, which is a simple $\\lambda$-calculus, and a quantum part, whose syntax is based on Qwire~\\cite{qwire}, a functional quantum programming language with linear type system.\nWhat's more, we implement a compiler from $\\lambda_Q$ to QASM (Quantum Assembly Language) ~\\cite{qasm}, an imperative quantum programming language with low-level instruction sets.\nThe output QASM program can run on the IBM cloud quantum machine.\n\nThe main feature of $\\lambda_Q$ is that the syntax for traditional computation and quantum computation are separated.\nThey communicate with each other via some specific operations : quantum circuit can be \\textit{abstracted} or \\textit{lifted (measured)} into traditional term, and traditional term for quantum circuit can be applied to quantum bits.\nThus, the syntax of quantum circuit can use \\textit{linear type system} to guarantee that the Quantum Non-cloning Theorem is not violated, meanwhile the $\\lambda$-calculus of the traditional part makes it easier to write quantum programs.\nWe will explain it in detail in Section \\ref{spec}.\n\nThe overall structure of the compiler can be visualized in Figure \\ref{compiler}.\nThe frontend is implemented using \\texttt{Haskell}, and the backend is implemented using \\texttt{C}.\nThe code can be found in \\url{https://github.com/thwfhk/lambdaQ}.\nWe will discuss the implementation of $\\lambda_Q$ compiler in detail in Section \\ref{front} and \\ref{back}.\n\n\n\\begin{center}\n  \\begin{figure}\n    \\label{compiler}\n    \\centering\n    \\includegraphics[width=0.9\\linewidth]{images/overview.png}\n    \\caption{Structure of $\\lambda_Q$ compiler.}\n  \\end{figure}\n\\end{center}", "meta": {"hexsha": "6f44d3ea7351f9c97f0c083b6b53ff8b1efd0987", "size": 4353, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/motivation.tex", "max_stars_repo_name": "thwfhk/lambdaQ", "max_stars_repo_head_hexsha": "834c0a42e234f486ac0f7b55f76e096d70cf7262", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-04-10T08:42:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-09T07:09:53.000Z", "max_issues_repo_path": "report/motivation.tex", "max_issues_repo_name": "thwfhk/lambdaQ", "max_issues_repo_head_hexsha": "834c0a42e234f486ac0f7b55f76e096d70cf7262", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/motivation.tex", "max_forks_repo_name": "thwfhk/lambdaQ", "max_forks_repo_head_hexsha": "834c0a42e234f486ac0f7b55f76e096d70cf7262", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-09T06:13:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-09T06:13:15.000Z", "avg_line_length": 63.0869565217, "max_line_length": 316, "alphanum_fraction": 0.7898001378, "num_tokens": 973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.3438551753353145}}
{"text": "\n\n%############################################################################################\n%############################################################################################\n\\section{Fixed Model-Driven MU-MIMO Evaluation}\n\\label{sec:model}\nIn order to understand how different environments and operational frequencies will effect the performance of a \\ac{MU-MIMO} system, we first turn to modern statistical MIMO channel models \\cite{liu2012cost}.\nSince this statistical model requires tuning for different environments and frequencies, we compare the results using two published parametrizations  for 300~MHz \\cite{zhu2013cost} and 5.8~GHz\\cite{poutanen2011cost}. These results provide the theoretical motivation for over-the-air experiments to explore common application scenarios for UHF and 2.4/5.8~GHz WiFi.\n\n\\subsection{UHF vs. 2.4/5 GHz: Channel Models}\n\\label{sec:specDiff}\n\n\tSpectrum differences between 2.4/5~GHz WiFi and sub-gigahertz frequencies are essentially due to the different manifestations of Doppler effects given each band's wavelength.\n\tDoppler effects are a result of transmitter, receiver, and client movement with respect to a transmission's wavelength.  \n\tBecause sub-gigahertz wavelengths are 2-4 times longer than 2.4/5~GHz, environmental variation will affect sub-gigahertz transmissions 2-4 times less (without considering multi-path effects).  \n\n\tFig.~\\ref{fig:doppler} shows the theoretical, freespace 50\\% coherence time for various sub-gigahertz and 2.4/5~GHz frequencies \\cite{rappaport1996wireless}.\n\tThe 50\\% coherence time is expected length of time that the channel characteristics will  vary at most 50\\% given some velocity (effectively channel variation).\n\n\tThe coherence time difference between 2.4/5~GHz WiFi and sub-gigahertz frequencies is between 1-2 \\textit{orders of magnitude}.\n\tThis channel characterization does not consider many real world effects such as multi-path or fading but provides a coarse characterization of the key differences in the two bands.\n\n\\begin{figure}[htbp!]\n\t\\centering\n  \t\\includegraphics[width=0.7\\linewidth]{figs/doppler}   \n    \t\\caption{50\\% coherence time for various sub-gigahertz and 2.4/5~GHz WiFi frequencies.}\n\t\\label{fig:doppler}\n\\end{figure}\n\n\tFor a more realistic characterization of the spectrum differences, we employ the COST 2100 MIMO channel model, a flexible channel model that is well suited for \\ac{MU-MIMO} scenarios \\cite{liu2012cost}.\n\tThis channel model is tuned with parameters that are extracted from empirical measurements and thus does consider real-world channel effects such as fading,  multi-path, and \\ac{NLoS} transmissions.\n\tParametrized realizations of the COST 2100 model have been created for 300~MHz \\cite{zhu2013cost} and 5~GHz \\cite{poutanen2011cost} bands.\n\tUsing these models, we generate 15,000 channel snapshots at a simulated rate of 100 snapshots per second to characterize the variation of channel state over time and the separability of individual users. \n\tSpecifically we explore the temporal correlation  and receiver separability  (shown in Fig.~\\ref{fig:corr}) of the generated matrices.\n\n\\begin{figure}[ht]\n\t\\centering\n\t\\subfigure[Temporal correlation between channel snapshots from 0 to 10 seconds apart.  Higher time correlation allows for more robust MU-MIMO performance. $T_{0.9}$ is 50~ms and 4~s for 5 GHz and 300 MHz respectively.] {\n\t\\includegraphics[width=0.48\\linewidth]{figs/theo_tempDiff}\n\t\t\\label{fig:theo_tempCorr}\n\t}\n\t\\subfigure[CDF of model-generated Demmel condition number. Left is better for \\ac{MU-MIMO}] {\n\t\t\\includegraphics[width=0.48\\linewidth]{figs/dcond_cdf}  \n\t\t\\label{fig:spatCorr}\n\t}\n  \t\\caption{Temporal correlation and channel condition of 300~MHz and 5~GHz 2x2 MU-MIMO channels generated by COST 2100 MIMO channel model. \\label{fig:corr}} \n\\end{figure}\n \n\tThe correlation coefficient $\\rho$ presented in Equation~\\ref{eq_corr_coeff} is calculated for all combinations of transmit antenna, receive antenna, and starting time sample.\n\tWe show the magnitude of the temporal correlation coefficient in Fig.~\\ref{fig:theo_tempCorr} for our generated channels.  \n\tLower temporal correlation results in less robust MU-MIMO transmissions because the measured channel state has a high probability of being stale.\n\tAs seen in Fig.~\\ref{fig:theo_tempCorr}, the temporal correlation of 5~GHz WiFi almost immediately drops to below 0.9 ($T_{0.9}$) a point when when re-sounding the channel is strongly suggested \\cite{breit2009coherence}. \n\nAccording to the channel models, the approximate re-sounding time for 5~GHz is 50~ms and 300~MHz is approximately 4.5~s (almost two orders of magnitude longer). \nThis result is similar to what we expect from Doppler effects of the different frequency bands (Fig.~\\ref{fig:doppler}) and is similar to our indoor temporal characterization in \\S~\\ref{sec:indoor}.\n\n\\subsection{Demmel Condition Number}\n\\label{sec:demmel}\n\nUser separability refers to how well a multi-antenna transmitter can serve a set of users in parallel.  \nThe Demmel condition number is a modified matrix condition number that directly predicts the efficacy of an adaptive MIMO or MU-MIMO transmission for a particular channel realization \\cite{zhong2011distribution}.\n\nThe Demmel condition number is computed using the eigenvalues $\\lambda_k$ of $HH^{\\dagger}$ as:\n\\begin{align}\nd\\triangleq\\frac{\\sum^{n}_{k=1}{\\lambda_k}}{\\lambda_{n}}\n\\label{eq:dcond}\n\\end{align}\nwhere $\\lambda_1 > \\lambda_2 > \\hdots > \\lambda_n$.\nThis ratio represents how well a matrix can be inverted, a key component of many adaptive MU-MIMO techniques such as Zero-Forcing Beamforming \\cite{goldsmith2006zf} and MMSE \\cite{tse2005fundamentals}.\nSpecifically, the higher the condition number, the more numerically unstable the inverse and thus the more inter-user interference during MU-MIMO transmissions reducing received SINR.  \nThe condition number ranges from 1 to infinity for well to ill-conditioned matrices, respectively.  \n\nThis method of calculating the condition number is less forgiving than the traditional singular value ratio. \nThe singular values of $H$ are the square root of the eigenvalues of $HH^{\\dagger}$.\nThus, instead of $\\sigma_k/\\sigma_n$, the Demmel condition number is equivalent to $\\sum{\\sigma^2}/\\sigma_n^2$ meaning that channel matrices with low singular values (resulting in inaccurate inversion) are even further ``penalized.``\nThis modification to the condition number better predicts MU-MIMO performance, in fact, it is consistent and accurate enough to be used for determining parameters such as supported modulation rate and user selection \\cite{zhong2011distribution}.\n\n\nThe COST channel models show a significant difference between the 5~GHz WiFi and UHF bands.  \nThe CDF shown in Fig.~\\ref{fig:spatCorr} depicts how almost all of the generated 5~GHz channel matrices have a Demmel condition number less than 10 while UHF's channel condition varies far more and is significantly worse.\nThis results in an increased ability for a \\ac{MU-MIMO} transmitter to invert the channel matrix and send orthogonal streams to each intended user. \n\n\nThus, existing MIMO channel models show that while the UHF channel is more temporally stable over time, its ill-conditioned channel matrices can result in lower served SINR due to inter-user interference. \nHowever, the available parametrizations of the COST model are for indoor 5~GHz  and outdoor UHF scenarios.  \n%We show in \\S~\\ref{sec:expDrivenEval} how restricting these bands to these transmission environments does not tell the full story.\n\n\\section{Fixed Indoor MU-MIMO Channel Characterization}\n\\label{sec:mumimo_channels} \n\n%############################################################################################\n%############################################################################################\n%\\subsection{Experiment-Driven Fixed Wireless Evaluation}\n%\\label{sec:expDrivenEval}\nThe models analyzed in Section~\\ref{sec:model} are parametrized for particular environments, frequency bands, and topologies. While they suggest that the performance of \\ac{MU-MIMO} beamforming in UHF bands may be advantageous, it it difficult to directly predict or simulate UHF performance using these models as they were not validated for application scenarios such as indoor or urban outdoor, nor the UHF frequency band.\n\nIn order to address uncertainty in these models for our target application (indoor and outdoor \\ac{WLAN}), we perform a set of  experiments utilizing our custom \\ac{SDR} radio platform that allows us to measure the performance of a \\ac{MU-MIMO} transmission over a diverse set of carrier frequencies and characterize the wireless \\ac{MU-MIMO} channel for important temporal and spatial correlation properties.\n\nWe perform over-the-air beam-forming transmissions in a densely packed, challenging office scenario with multiple subscriber nodes and demonstrate not only the ability to simultaneously beamform to distinct users in relatively close proximity, but also the relative improvement that shifting to UHF frequencies provides.\n\nFinally, we perform two sets of experiments with a customized MAC and PHY designed to gather dense, wideband, over-the-air channel estimates in realistic indoor and outdoor \\ac{WLAN} scenarios with multiple subscriber nodes. Using this data, we then demonstrate that the spatial correlation for outdoor users remains similar to that of 2.4~GHz WiFi, thus incurring no beamforming ``penalty'' for utilizing a frequency band with superior propagation and temporal correlation.\n\n\\subsection{Indoor MU-MIMO Transmissions}\n\\label{sec_static_indoor_exp}\n\n\\label{sec:indoor}\n\\textbf{Experimental Setup.}\nFirst, we evaluate the performance of UHF \\ac{MU-MIMO} in an indoor \\ac{NLoS}  office environment.\nExperiments were conducted during the work day with people walking through the halls in the environment depicted in Fig.~\\ref{fig:indoorExp}.\n\n\n\\begin{figure*}[t!]\n\t\\centering\n  \t\\includegraphics[width=1\\linewidth]{figs/indoor_wl_all}   \n    \t\\caption{Indoor fixed MU-MIMO achievable rate.\\label{fig:indoor_cap_all}}\n\\end{figure*}\n\n\n\\begin{figure}[th]\n\\vspace{-5mm}\n\t\\centering\n  \t\\includegraphics[width=0.7\\linewidth]{figs/indoorExp}   \n    \t\\caption{Indoor fixed WURC-based experimental test setup.\n\t\\label{fig:indoorExp}}\n\\end{figure}\n\n\nThe \\hspace{0.01pt} transmitting \\hspace{0.01pt} array\\hspace{0.01pt}  was \\hspace{0.01pt}  placed \\hspace{0.01pt} on \\hspace{0.01pt} a \\hspace{0.01pt} third \\hspace{0.01pt} floor \\hspace{0.01pt} walkway bridge and 6 separate receivers in two adjacent offices within the adjoining hallway.\nNote that the to-scale depiction in Fig.~\\ref{fig:indoorExp} shows the relative co-location of all receiving nodes with respect to the distance from the transmitter to simulate a densely packed office environment.\nThis represents a realistic, challenging case for indoor stationary MU-MIMO transmissions due to the co-located receivers.\n\nTo encompass a wide range of user grouping conditions, every possible combination of transmit and receive antennas are considered. Sixty transmissions are performed for each topology. The center frequencies for each frequency band (\\textit{i.e.} channel) were chosen so that transmissions did not encounter interference from other equipment. Specifically, the UHF channel was first directly scanned for existing DTV or microphone transmissions and an experimental license was obtained to operate equipment on that channel. The channels selected for 2.4 and 5.8 GHz are not currently supported by the regulatory domain where these experiments were performed, thus ensuring minimal ISM-band interference.\n\tUsing the measurement technique specified in Section~\\ref{sec_static_miso_chan_est}, every possible topology's MU-MIMO capacity is measured for each frequency band and shown in Fig.~\\ref{fig:indoor_cap_all}.\n\n\n\n\\begin{figure}[th]\n\t\t\\centering  \n\t\\includegraphics[width=0.7\\linewidth]{figs/meas_indoor_dcond} \n    \t\\caption{Demmel condition number measured for the indoor environment. Left is better for \\ac{MU-MIMO}.\n\t\\label{fig:indoor_demmel}}\n\\end{figure}\n\n\n      \n\\subsubsection{Fixed Wireless Measured Achievable Sum-Rate Capacity.}\n\nBased on the channel models and accompanying analysis presented in Section~\\ref{sec:specDiff}, we expect that the increased spatial correlation of UHF channels will not \\  allow \\ for \\ MU-MIMO \\ transmissions\\ to \\ accurately separate nearby users.\nHowever, we find that UHF \\ac{MU-MIMO} transmissions can actually achieve a sum capacity similar to that of 2.4~GHz WiFi transmissions (always between 1-2~b/s/Hz above of below the 2.4~GHz band).\n\nIn fact, we find that majority of the intuition and channel models surrounding UHF MU-MIMO are not specific to the frequency band itself but rather generalized characteristics of MU-MIMO transmissions.\nFor example, the available MU-MIMO channel models characterize \\textit{indoor} WiFi and \\textit{outdoor} UHF channel environments where, regardless of frequency band, we expect increased difficulty in user separability in outdoor environments.  \nNote the channel condition of the different transmission bands in the NLOS environment in Figure~\\ref{fig:indoor_demmel} are similar in contrast to Fig.~\\ref{fig:spatCorr}.  \nEven though the wavelength of UHF is longer resulting in better propagation through materials, the UHF-band transmission still experiences enough multi-path to successfully beamform to multiple users in parallel.\n\n\n\nAdditionally, the results shown in Figure~\\ref{fig:indoor_cap_all} show a known trend of achievable capacity for MU-MIMO transmissions where the MU-MIMO gain plateaus as the available \\ac{DoF}\\footnote{\\ac{DoF} here refers to how many more transmit antennas there are than receive antennas in a MIMO transmission.} are reached.\nThe consistently worse performance of 5.8~GHz is explained by the high attenuation experienced by that frequency band in \\ac{NLoS} conditions combined with its sensitivity to environmental variation.    \n\nNote that UHF MU-MIMO consistently outperforms 2.4~GHz transmissions except for in the 2x2 transmission scenario.  \nBecause the sum transmit power emanating from the array is held constant regardless of the number of transmit antennas in use, the performance differential is solely a result of channel state, specifically it is an indicator of temporal channel correlation due to the WARPLab measurement platform.\n\n\n\tAs discussed in Section~\\ref{sec_warplab_timing}, the latency in the WARPLab platform is due to the rate at which the host PC can download and upload samples to each of the WARP boards over Ethernet. \n\tIn our system, we benchmark a read/write rate of approximately 2.5~ms per buffer and the closed loop beamforming method employed requires between  10 to 20~ms to complete depending on the number of transmit and receive antennas (the difference between a 2x2 and 4x4 transmission scenario).\n\n\n\\subsection{Fixed Wireless Measured Temporal Correlation.}\n\\label{sec_fixed_temporal}\n\nTo gain additional insight into the measured capacity results and to infer real world performance from \nour MU-MIMO transmissions, we also consider the channel correlation measured during each experiment.\n\nFor each topology, we consider each of the 60 MU-MIMO transmissions and their channel matrices.\nWe calculate channel correlation between varying times during the experiment to measure the rate of change of the channel information with respect to time.  \nThese calculations are an average over all topologies (all combinations of transmit and receive antennas).\n\n\n\\begin{figure}[th]\n\t\\centering\n \t \\includegraphics[width=0.7\\linewidth]{figs/measCorrWl}   \n   \t \\caption{Measured Temporal Channel Correlation, depicting Beacon Interval, and $T_{0.9}$.  WARPLab latency is 10-20~ms depending number of transmit and receive antennas.\n\t\\label{fig:meas_corr}}\n\\end{figure}\n\n\nFig.~\\ref{fig:meas_corr} shows how the channels decorrelate over the course of one measured second in time.\nThis is effectively an indicator of how long a transmitter has after measuring the channel matrix and before actually transmitting parallel streams using that measurement.  \nA coherence time of $T_{0.9}$ represents when the probability of the channel being too stale to successfully beamform over is high.\n\nFirst, note that the WARPLab latency range of 10 to 20~ms is approximately $T_{0.9}$ for the \nthe two WiFi frequency bands.\nThis indicates why only the 2x2 transmission scenario has the 2.4~GHz transmitter outperform UHF MU-MIMO; the latency between the sounding and transmission phase was the lowest and just at the $T_{0.9}$ limit.\n\nWhile the 2.4/5~GHz frequencies both drop significantly within 100~ms, UHF remains above the $T_{0.9}$  threshold for the maximum one measured second difference between channel matrices.  \nWhile these correlation values are not asymptotic and will eventually degrade, the performance of 2.4 and 5.8~GHz is sufficently low for stationary devices \\cite{breit2009coherence}. \n\nThe 802.11 infrastructure \\ac{BSS} beacon rate\\footnote{The IEEE Std 802.11-2012 Target Beacon Transmission Time (TBTT) is configured in ``Time Units'' defined as 1 TU = 1024 $\\mu s$, and is often set to 100~TU.} (102.4~ms \\cite{std11_2012}) is greater than the interval that 2.4/5~GHz MU-MIMO channels decorrelate.  \nHowever, the stability of the UHF channel implies that a UHF MU-MIMO system could use periodic protocol packets for exchanging channel state information. \n\nFinally, the channel correlation result shown in Fig.~\\ref{fig:meas_corr} effectively scales the MU-MIMO achievable rate shown in Fig.~\\ref{fig:indoorExp}.\nThe rate at which the 2.4/5~GHz channel decorrelates necessitates channel sounding on a per packet basis adding considerable overhead to MU-MIMO transmissions. \nHowever, the temporal stability of the UHF MU-MIMO channel allows a transmitter to significantly reduce this overhead intensive sounding process and thus significantly increase the potential MU-MIMO gains. \n\n%############################################################################################\n%############################################################################################\n\n\\begin{figure}[p]\n\t\\centering\n\t\\subfigure[Experimental setup for outdoor channel sounding.] {\n\t\\centering\n\t\\includegraphics[width=0.48\\linewidth]{figs/meas/outdoorExp}\n\t\t\\label{fig_fix_outdoor_diagram}\n\t}\n\t\\subfigure[Example of outdoor STA with dual antennas.] {\n\t\t\\includegraphics[width=0.48\\linewidth]{figs/meas/ryan_tripod_platform}  \n\t\t\\label{fig_fix_outdoor_sta}\n\t}\n  \t\\caption{Fixed outdoor multi-band measurement setup \\label{fig_fixed_outdoor}} \n\\end{figure}\n\n\\section{Fixed Outdoor MU-MIMO Channel Characterization}\n\n%\\rgnote{TODO: I'm missing autocorrelation results from this experiment. Need to add.}\n\n%\\begin{figure}[th!]\n%\\centering\n  %\\includegraphics[width=0.5\\linewidth]{figs/meas/outdoorExp}  \n    %\\caption{}\\label{fig:outdoor}\n%\\end{figure}\n\n\n\n\n\tFinally, using the experimental framework developed in Section~\\ref{sec_static_miso_chan_est}, we perform outdoor channel sounding experiments to directly compare the performance and stability of UHF \\ac{MU-MIMO} channels.\n\tTo that end, we setup an experimental network of a collection of nodes located outdoors being served by our array from a third floor balcony.  \n\tAlthough the UHF transmitter is capable of transmitting much further distances, we limited the scale of the topology as shown in Figure~\\ref{fig_fix_outdoor_diagram} to ensure a fair comparison between UHF and 2.4/5~GHz bands.   \n\tThe locations of the nodes were chosen such that the transmissions from the UHF and 2.4/5~GHz bands would reach the receivers (the UHF band transmitters can easily transmit further than 50~m).\n\tHowever, even by reducing the receiver distance to what is shown in Figure~\\ref{fig_fix_outdoor_diagram}, the 5~GHz band transmissions did not reliably reach the receiving nodes.\n\tSince this severely limited the number of measured channel matrices at 5~GHz, we restrict our outdoor comparison to the UHF and 2.4~GHz bands.\n\n\tJust as we evaluated  temporal correlation in the multi-path rich, indoor transmission environment, we seek to similarly characterize the most detrimental aspect of the outdoor MU-MIMO channel: receiver separability.  \n\tIll-conditioned channel matrices, as discussed in \\S~\\ref{sec:specDiff}, have a detrimental effect on an MU-MIMO enabled transmitter's ability to separate multiple users.  \n\n\tIn the previous section, we found that while temporal stability of UHF was greater than that of 2.4/5 GHz, spatial correlation did not suffer as the UHF MU-MIMO transmissions were able to separate the co-located receivers.\n\tHowever, in an open, outdoor \\ac{LoS} environment, we find that both the UHF and 2.4~GHz bands exhibit the same Demmel condition number. \n\tAdditionally, the CDF of the Demmel condition number closely matches the COST UHF channel condition shown in Fig.~\\ref{fig:spatCorr}.\n\tThis suggests that the comparison shown in Fig.~\\ref{fig:spatCorr} is not a result of the frequency band itself, but rather the wholly different channel environments in which the model was parametrized.\n\n\\begin{figure}[t]\n\\centering\n  \\includegraphics[width=0.7\\linewidth]{figs/measSpatCorr}   \n    \\caption{Measured Demmel Condition Number of the outdoor MU-MIMO channel.}\\label{fig:measSpat}\n\t\t\\vspace{-5mm}\n\\end{figure}\n\n%% UHF-band MUMIMO Conclusions\n%\\subsection{Discussion}\n\t\t%\\rgnote{what does this mean for system design? the implications are very important}\n", "meta": {"hexsha": "c90335c0829ae0a040587fc7b197cbf898554ef6", "size": 21547, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "sec/uhf_mumimo.tex", "max_stars_repo_name": "RyanEGuerra/ryan_guerra_phd_thesis", "max_stars_repo_head_hexsha": "acf1ebafee00a8e4375008e60e35da8affc97d9b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sec/uhf_mumimo.tex", "max_issues_repo_name": "RyanEGuerra/ryan_guerra_phd_thesis", "max_issues_repo_head_hexsha": "acf1ebafee00a8e4375008e60e35da8affc97d9b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sec/uhf_mumimo.tex", "max_forks_repo_name": "RyanEGuerra/ryan_guerra_phd_thesis", "max_forks_repo_head_hexsha": "acf1ebafee00a8e4375008e60e35da8affc97d9b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 82.5555555556, "max_line_length": 702, "alphanum_fraction": 0.7777880911, "num_tokens": 5043, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.34385517157861917}}
{"text": "%---------------------------------------------------------------------\n\\section{Summary and Conclusions}\n\\label{summary}\n\nWe have used leading order matrix elements to separate expected single\ntop quark signals from background. This analysis used lepton+jets\nevents selected from nearly 1~fb$^{-1}$ of Run~II~ data. The\ntwo-dimensional discriminant output from the analysis is used to\nmeasure the single top cross section. We obtain the following result:\n$$\n\\sigma\\left({\\ppbar}{\\rargap}tb+tqb+X\\right)\n= 4.6^{+1.8}_{-1.5}~{\\rm pb}\n$$\n\nThis result has a p-value of $0.22\\%$, corresponding to a $2.9\\sigma$\nGaussian equivalent significance, meaning it is highly unlikely to be\nan upward fluctuation of the background that has produced this\nmeasured cross section.\n", "meta": {"hexsha": "15e36c75645dae1c29ab3efd87f5e2b606e72211", "size": 763, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "MEnote/Summary.tex", "max_stars_repo_name": "tgadf/thesis", "max_stars_repo_head_hexsha": "19d4a6bc7f7ac8660fce582322703d50e0d6bd31", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MEnote/Summary.tex", "max_issues_repo_name": "tgadf/thesis", "max_issues_repo_head_hexsha": "19d4a6bc7f7ac8660fce582322703d50e0d6bd31", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MEnote/Summary.tex", "max_forks_repo_name": "tgadf/thesis", "max_forks_repo_head_hexsha": "19d4a6bc7f7ac8660fce582322703d50e0d6bd31", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1578947368, "max_line_length": 70, "alphanum_fraction": 0.6959370904, "num_tokens": 190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.34382655076868646}}
{"text": "\\documentclass{article}\n\\usepackage[T1]{fontenc}\n\\usepackage[utf8]{inputenc}\n\\usepackage{lmodern}\n\\usepackage{textcomp}\n\\usepackage{lastpage}\n\n\\input{common_symbols_and_format.tex}\n\\usepackage{tocloft}\n\\renewcommand{\\cfttoctitlefont}{\\Large\\bfseries}\n\n\\begin{document}\n\\normalsize\n\\logo\n\\rulename{Difference Regression}\n\\tblofcontents\n\\ruledescription{This trading rules regresses the 1-day price changes seen historical against the prior day's \\% change of the research series.}\n\\ruleparameters{Difference Coefficient}{0.1}{Multiplier for regression.}{$k_1$}{Constant Coefficient}{0.1}{Initial constant for regression.}{$k_2$}\n\\stoptable\n\\section{Equation}\nBelow is the equation which governs how this specific trading rule calculates a trading position.\n\\begin{equation}\n\\position_\\currenttime = k_1*(\\frac{R_t}{P_{t-1}}-1)+k_2\n\\end{equation}\n\\\\\nwhere:\n\n$\\position_\\currenttime$ is the portfolio allocation at time $\\currenttime$\n\n$R_t$: Research value at time $\\currenttime$\n\n$P_{t-1}$: Price value at time $\\currenttime -1$  \n\n$k_1$: Difference coefficient\n\n$k_2$: Constant coefficient\n\n\\keyterms\n\\furtherlinks\n\\end{document}", "meta": {"hexsha": "6d3b22fef9cfffe362dc45921e70f57c578162a2", "size": 1129, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/strategies/tex/DifferenceRegression.tex", "max_stars_repo_name": "parthgajjar4/infertrade", "max_stars_repo_head_hexsha": "2eebf2286f5cc669759de632970e4f8f8a40f232", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 34, "max_stars_repo_stars_event_min_datetime": "2021-03-25T13:32:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-06T23:03:01.000Z", "max_issues_repo_path": "docs/strategies/tex/DifferenceRegression.tex", "max_issues_repo_name": "parthgajjar4/infertrade", "max_issues_repo_head_hexsha": "2eebf2286f5cc669759de632970e4f8f8a40f232", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 137, "max_issues_repo_issues_event_min_datetime": "2021-03-25T10:59:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-28T19:36:30.000Z", "max_forks_repo_path": "docs/strategies/tex/DifferenceRegression.tex", "max_forks_repo_name": "parthgajjar4/infertrade", "max_forks_repo_head_hexsha": "2eebf2286f5cc669759de632970e4f8f8a40f232", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 28, "max_forks_repo_forks_event_min_datetime": "2021-03-26T14:26:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-10T18:21:14.000Z", "avg_line_length": 28.225, "max_line_length": 147, "alphanum_fraction": 0.7794508415, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819874558604, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3437045864125405}}
{"text": "\\documentclass[runningheads]{llncs}\n\\usepackage{graphicx}\n\\usepackage{times}\n\\usepackage{float}\n\\usepackage{latexsym}\n\\usepackage[T1]{fontenc}\n\\usepackage[utf8]{inputenc}\n\\usepackage{microtype}\n\\usepackage[utf8]{inputenc}\n\\usepackage[ruled,vlined]{algorithm2e}\n\\graphicspath{ {./images/} }\n\\begin{document}\n\\title{Neural Network Pruning as a N Player NIM Game}\n\\author{Daniel Campos\\orcidID{0000-0002-5138-8426} }\n\\authorrunning{D. Campos et al.}\n\\institute{University of Illinois at Urbana-Champaign, Urbana, Il, 61801, USA}\n\\maketitle              % typeset the header of the contribution\n%\n\\begin{abstract}\nUnstructured pruning has become one of the most popular methods for Neural Network model pruning since it provides an intuitive method of extracting a sub network from the original Neural Network which matches the pruning goals. Pruning approaches have been used to reduce model size, increase adversarial robustness, increase stability and generizability, and increase model inference speed but each of these goals works independently. By framing Network Pruning as a $N$ player NIM game we provide a framework which can be used to combine pruning strategies depending on needs. In our work, each pruning method takes the role of a NIM game player where they remove weights from a network in an iterative fashion. We find that 2 player methods combining $L1$ and Random pruning outperform existing method across datasets and models. We believe this formulation of network pruning provides a comprehensive framework which can be used to prune networks for multiple goals. \n\\keywords{Neural Network \\and Subtraction Game \\and Neural Network Pruning.}\n\\end{abstract}\n\\section{Introduction}\nNeural Networks have become popular choices for complex computation tasks like image recognition \\cite{Howard2017MobileNetsEC}, image generation \\cite{Goodfellow2014GenerativeAN}, speech processing \\cite{Zhao2017RecurrentCN}, and question answering \\cite{Seo2017BidirectionalAF}. These networks have grown to hundred billions of parameters \\cite{Brown2020LanguageMA} which require specialized hardware like clusters of GPUs and FPGAs in order to infer on unseen data. Recent work has shown that larger networks can learn quicker \\cite{Li2020TrainLT}, are more accurate and are more sample efficient \\cite{Kaplan2020ScalingLF}. Seeking to allow the improvements that large models have brought to be used on smaller devices and in a more energy efficient way researchers have produced many methods which produce smaller networks that approximate, match, or exceed the original network performance. \\\\ \nModel distillation, quantization, and pruning have emerged as successful methods to produce smaller networks from the original over-parametized network. In model distillation  \\cite{Ba2014DoDN} the original network is used to train a smaller network to mimic the behavior of the large network. In model quantization \\cite{Han2016DeepCC} models are made smaller by  reducing the numbers of bits that represent each weight. Model Pruning \\cite{LeCun1989OptimalBD} has focused on finding sub-networks in the original network by structured and unstructured pruning. In structured pruning, successful sub-networks are found by removing neurons  \\cite{Wang2019StructuredPF} or larger network specific structures like attention heads \\cite{Voita2019AnalyzingMS}. In unstructured pruning the successful sub-networks are found by setting individual weights to zero \\cite{Kwon2019StructuredCB}. \\\\\nUsing network pruning, The Lottery Ticket Hypothesis \\cite{Frankle2019TheLT} proved the concept that in large neural networks there exists a sub network which can match the accuracy of the full network despite its smaller size. Building on the notion that there are many sub networks in an overparamertized network we formulate network pruning as a combinatorial problem. Given an initial structure $S$ and a target network size $\\epsilon$ the goal is to find the sub network $s_m$ of size $\\epsilon$ which maximizes the optimization metric. Sub networks can have many different optimization goals such as: accuracy, size, adversarial robustness, computation speed, explainability, etc. Given that networks commonly have millions of parameters and the network can continually be updated by retraining even a greedy strategy for optimal model selection would require a millions of combinations. Instead, using network pruning we can can produce sub network $s_a$ with minimal compute and using a targeted pruning strategy we only remove neurons that minimize our optimization goal. \\\\\nBelieving that the future of network pruning is likely to focus on multi metric optimization we formulate network pruning as a $N$ player game of NIM. In a game of NIM \\cite{Dass2006SecretsBT} players remove items from a variety of bins in alternating turns. Using this strategy we are able to combine different pruning strategies to produce networks that maximize sparsity and performance and outperform traditional iterative pruning mechanisms. \n\\section{Related Work}\nNeural network compression is an area that has attracted the attention of researchers for the last few decades. Methods for producing smaller networks that approximate original network performance include: distillation, quantization, structured and unstructured pruning. While each of these methods can compress models substantially on their own many researchers have found that some combination of these methods can produce the smallest models with the highest performance \\cite{Polino2018ModelCV}, \\cite{Sanh2020MovementPA}. \\\\\nModel distillation \\cite{Ba2014DoDN} addresses compressing models by first training a large network and calling it a teacher. Then using this teacher model a smaller student model learns to approximate what the teacher model would do. This framework is quite popular because it can leverage existing large models easily and the student model can be designed to fit the application requirements in terms of speed and model size. Distillation has been one of the most common methods of deployment of large scale language models where student models like DistilBERT \\cite{Sanh2019DistilBERTAD} can approximate full model performance at a fraction of the size. \\\\\nModel quantization \\cite{Gong2014CompressingDC} \\cite{Han2016DeepCC} addresses compressing models by reducing the number of bits that are require to represent parameters in a model. In simple implementations this means changing representation of weights from Float32 to float16(effectively cutting model size in half). Complex implementations tune networks to find the smallest amount of bits that can be used for weights, biases, and gradient updates using values as low as 1 bit \\cite{Courbariaux2016BinarizedNN}. Quantization is particularly effective because it both leverages that networks are defaulted to a level of precision which is too high and by decreasing the size of representations networks are forced to share weights making networks more robust. \\\\\nModel pruning \\cite{LeCun1989OptimalBD} addresses model compression by decreasing the connection in a network. The goal of network pruning is to produce a sub network of the original network which optimizes some network property(accuracy, speed, robustness) while preserving the original network function. Network pruning has been show to produce a similar effect to random noise injection \\cite{Bartoldson2019TheGT} and this noise can be used to make the network more efficient. Bartoldson et al., showed that network pruning is not just used for decreasing size but can be used to increase the generalization of the network. The formulate that pruning methods generally generally focus on how important a prune target is currently to the network but believe that algorithms should also should be designed to consider the damage that removal has on a network.  \\\\\nAs mentioned earlier, there is structured pruning and unstructured pruning. In structured pruning, the structure of the network is altered by removal of entire neurons, layers, or portions neural network. This method has proven especially successful in language model compression where despite having dozens of attention heads \\cite{Vaswani2017AttentionIA} few heads do most of the work and the rest can be removed \\cite{Michel2019AreSH}. In unstructured pruning the network structure is altered by removal of individual weights. Unstructured pruning when paired with optimization engines can produce networks that are smaller, more accurate, and run faster than the original network. \\\\\nLiu et al., \\cite{Liu2019RethinkingTV} proposed that network pruning is doing something similair to neural architecture search to find an optimal architecture given a set of optimization metrics. Recently, researchers have explored pruning methods that simultaneously remove and reintroduce weights \\cite{Jia2020StochasticMP} which helps keep a pruned network from being stuck in a local minimum. Within unstructured pruning methods can be local or global. Global pruning pools together all parameters across layers while local performs each pruning operation focused on individual layers. \\\\\nThe use of Game Theory has proven successful for model compresion. KDGAN \\cite{Wang2018KDGANKD} explores formulation of distillation as a 3 player game which\nimproves model performance, train time, and training efficient. Many more\nmethods \\cite{Guo2018SparseDW} \\cite{Dhillon2018StochasticAP}, \\cite{Sehwag2020OnPA}, \\cite{Xie2020BlindAP}, explore the use of Adversarial methods in model\npruning with a goal of making NN more robust to adversarial inputs. HYDRA \\cite{Sehwag2020HYDRAPA} prunes models for adversarial robustness by formulating pruning as a empirical risk minimization (ERM) problem removing neurons that maximize risk.\n\\section{Pruning as an N Player Game}\nWe propose the formulation of pruning as an $N$ player game of NIM as a way to allow multi objective network pruning. NIM is traditionally a combinatorial game where two players take turns removing objects from several heaps. NIM is the most well known example of an impartial game because every player has the same amount of moves in a game. In our implementation, the game is played on unstructured local pruning where each player is able to remove a single weights from the layer of the neural network which is currently being played. This game is an extensive subtraction game since it happen over many rounds of play and players make moves by removing parts of a structure. \\\\\nIn this game, pruning methods are implemented as a collection of $P$ players in which each player $p \\in P$ has a unique strategy which does does not change based on other players nor any prior round. Prior to playing their turn, each player ranks the existing weights based on how each weight maximizes their optimization metric. When its a players turn to play they simply select the first non zero weight in their ranking. At the beginning of each round the order in which the players $p \\in P$ execute their prune is selected at random to ensure that one method is not favored over others.  Since the outcome of the game is independent of players performance we will not discuss their reward and utility functions further. \\\\\nThe utility in this implementation of pruning is the ability to easily combine strategies and ratio of strategies depending on targeted applications. In single objective pruning there is only one player who plays the game alone. As more optimization goals get introduced the amount of players grow. In a complex game there may be multiple players with the same strategy which gives the game organizer(the network pruner) the ability to set importance of pruning optimization metrics. \n\\section{Experiment}\nThe structure of our experiments is straightforward: train an initial baseline method and prune this networks iteratively using each of the candidate methodologies. To evaluate the effect of our formulation we select 3 popular image recognition frameworks which vary in structure, size and recency: VGG-16 \\cite{Simonyan2015VeryDC}, ResNet50 \\cite{He2016DeepRL}, DPN92 \\cite{Chen2017DualPN}. We train each network on the CIFAR-10 \\cite{Krizhevsky2009LearningML} and CIFAR-100 \\cite{CIFAR-10} dataset which are common benchmarks for evaluating image systems. The CIFAR-10 dataset consists of 60,000 32x32 color images where each image belongs to one of ten classes. The CIFAR-100 dataset is just like CIFAR-10 but it has 100 classes instead of 10 and each class includes 600 examples instead of 6,000.\n\\subsection{Generating Baselines}\nEach of our model baselines are trained in an identical fashion. For each combination of model architecture and dataset each model is trained with a batch size of 128, an initial learning rate of 0.1 and trained for 1000 epochs. Models are trained using 2 Nvidia 2080 Ti GPUs with a  Intel Core™ i9-10900X CPU and 128GB of RAM. Training time ranges from 1 hour for VGG-16 to 1 day for DPN-92. During this training regime we evaluate the model on the validation portion of the dataset at the end of each epoch and the final candidate baseline is the checkpoint that maximised validation accuracy. Numerical details on baseline models can be found in Table \\ref{tab:tab1}.\n\\subsection{Pruning}\nOur pruning experiments are focused on Iterative Pruning as it has become one of the most popular methods. In these experiments we only prune the weights of convolutions layers and we prune each layer independently. While other research has shown that optimal pruning of a network has different sparsity at different layers \\cite{Blalock2020WhatIT} we keep a uniform pruning for ease of experimentation. By focusing only on pruning convolutional layers we are not exploring every possible sub network but as shown in Table \\ref{tab:tab1}, convolutional weights make up the majority of each network. The process is formalized in Algorithm 1 where $NN$ is a neural network, $lambda_i$ is the $i$th prunable layer in a $NN$, $\\pi$ represents what percentage of weights need to be trimmed at each time step and $M$ represents a sorting function which maximizes the pruning optimization metric, $P$ represents the players playing our NIM game where each player $p_i$ has a strategy $s_i$ which is based on a $m_i$, $s_j$ represents sparsity at epoch j and $s_{target}$ represents the target network sparsity. \\\\\nIn our experiments we set $s_{target} = 0.95$, $\\pi=0.05$ and we evaluate model performance after each epoch. Our iterative pruning has three steps: stabilization, pruning, and fine tuning. In stabilization the network is trained with a learning rate of $0.1$ for 2 epochs. In network pruning we gradually remove $\\pi\\%$ of  weights and retrain the network with one pass the entire training data with a learning rate of 0.01. This stage lasts 19 epochs as $s_j = s_{j-1} + \\pi$ takes 19 steps to reach $s_{target}$. In fine tuning we set the learning rate to 0.001 and train the network for 10 epochs on the full dataset to ensure the network has reached optimal performance and is stable. \\\\\nIn the network pruning step, we prune each layer independently and implement it as a NIM game as shown in Algorithm 2. In this NIM game there are some set of players $N$ which each has a strategy for network pruning $s_i$. For each round, player order is randomly selected and each players removes a single weight from the layer. A NIM game is played for each $\\lambda_i \\in NN$ and if the network sparsity is under the $s_{current sparsity}$ then another round of NIM is played on each layer that is still under the target. Since target sparsity is a global parameter some layer sparsity will have lower and higher sparsity than the target. If a layer is over pruned in one epoch it will not be pruned until its sparsity is lower than the target.  Each player $n_i \\in N$ is defined by what pruning strategy is used and while our experiments focus on 2 and 3 player games $N$ could be much bigger. We will expand on network pruning as an $N$ payer game shortly.\n\\subsection{Pruning Methods}\nUsing the methodology previously described we explore the effect of. To explore how NIM can be used in Network pruning we formulate 8 games with a mixture and strategies. Each method is implement as $1-n$ player game where each player has a strategy $s_i$ which is represented via a sorting method $M_i$ which they use to sort the weights $W$ of the given layer they are pruning. Each of these ranking methods ranks weights of 0 as lowest and then ranks all existing weights to maximize their desired outcome. Details on each pruning method can be founding in the appendix.\n\\section{Results}\nIn our experiments our main goal was to see if combining pruning strategies could lead to improved models across sparcity. If we focus initially on performance on high sparcity networks(90\\% +) we find that L1 + Random pruning out performs other methods on five out of our six baselines. We believe this is because the combination of L1 and random pruning simultaneously keeps the most important sub networks while introducing generalization as the network cannot only rely on the strongest weights. We also note that across all experiments we see a large variation in optimal pruning mechanism given a target sparcity. We believe this further underscores the utility of the NIM game because it allows researchers to choose the most optimal game formulation depending on desired results. We also note that we see a wider spread in model accuracy on pruning of models targeting CIFAR-10 vs CIFAR-100. We believe this is because the dataset has few classes which results in more independent class specific sub networks which our various methods effect differently. \\\\\nOne of the surprises in our experiments was the consistent high performance of Random pruning even at high sparcity. We believe this is the case because even at high scarcities since the datasets are easier the networks are still highly over parametized. We reason that as we scale the difficulty of the target task random pruning alone would start to cause complete model failure. Since the focus of our work is on the formulation of pruning as a $N$ player game we will not further analyze our results but the full results can be found in the appendix. \n\\section{Conclusion and Future Work}\nThe addition of game theory to AI has proven to be a robust framework which leads to new discoveries and methods. We connect this literature to Neural Network pruning to build a framework which can optimize networks to a variety of goals. Using this framework we then show that the combination of strategies can be used to surpass single strategy pruning mechanism across a wide and representative set of models. By using a game of NIM to prune a network we have created a framework which can be used to create pruning strategies which outperforms traditional iterative pruning with limited computational overhead. While our method shows promise on CIFAR-10 and CIFAR-100 we believe that larger and more complex datasets are required to explore the effects of our pruning strategies further. \\\\\nGoing forward we many areas we wish to continue to explore. First off, we wish to explore what other games can be used to model Neural Networks pruning. While we show that NIM can be used successfully to improve pruning we believe that there may be other game formulations which are a better fit. Second, we wish to explore how NIM pruning can be used in the pruning of large language models. These models have scaled to billions of parameters and are used for a breadth of tasks so multi goal pruning will likely prove beneficial. Third, we want to explore network performance with the addition of new pruning goals. We believe the addition of FLOP optimization, Adversarial Robustness, and class aware pruning can all be introduced to NIM pruning to produce networks that maximize many goals and are small. Finally, in future work we seek to improve our framework for pruning to allow for global weight pruning. By moving to global weight pruning the game can expand to have strategies which optimize to network depth and breath, weight distribution, and take into account the varying sensitivity to pruning each layer may have. \n\\bibliographystyle{splncs04}\n\\bibliography{references}\n\\section{Appendix}\n\\subsection{Baseline Statistics}\n\\begin{tiny}\n\\begin{table}\n\\begin{tabular}{|l|l|l|l|l|}\n\\hline\nModel& Data   & Param & Conv& Acc\\\\ \\hline\nVGG-16       & CIFAR-10  & 14.73             & 14.71   & 86.85                 \\\\ \\hline\nVGG-16       & CIFAR-100 & 14.77           & 14.71     & 58.43                 \\\\ \\hline\nRESNET50     & CIFAR-10  & 23.52  & 20.68              & 86.89              \\\\  \\hline\nRESNET50     & CIFAR-100 & 23.71 & 20.68               & 62.74               \\\\\\hline\nDPN-92       & CIFAR-10  & 34.24         & 29.88       & 88.61                 \\\\\\hline\nDPN-92       & CIFAR-100 & 34.47            & 29.88    & 66.13  \\\\  \\hline             \n\\end{tabular}\n\\caption{Baseline models accuracy, characteristics, and parameter size. Parameters are in millions and Conv represents the parameters in convolutional layers. }\n\\label{tab:tab1}\n\\end{table}\n\\end{tiny}\n\\subsection{L1 Pruning Mechanism}\nWe implement L1 as a single player game where player $n_1$ sorts weights by ranking those closest to the L1-Norm as lowest. The L1-norm is the sum of the magnitudes of the vectors in a space. L1 pruning is thought to be a successful because weights with a small l1 are likely to produce small activation's and thus not influence the end result much.In most existing pruning implementation L1 pruning usually produces the best results. \n\\subsubsection{Random Pruning Mechanism}\nWe implement Random as a single player game where player $n_1$ sorts weights at random. Random pruning has shown to be highly effective as it acts as a regularizer in the network forcing many sub networks to learn effective representations as the network cannot rely on only one part of the network.\n\\subsubsection{Magnitude Pruning Mechanism}\nMagnitude pruning is a common strategy in which all weights closest to zero are removed. We implement this strategy as a two player game where the first player does positive magnitude pruning and the second does negative magnitude pruning. The positive pruning agent, $n_1$, sorts weights by ranking $w_j \\in W$ where $w_j >= 0$ which removes smallest positive weights. The negative pruning agent, $n_2$, behaves the same as positive but removes the smallest negative weights.\n\\subsection{L1 + Random Pruning Mechanism}\nWe implement L1 + Random as a two player game where the first player, $n_1$, plays an L1 strategy and the second player, $n_2$, plays a random strategy. This strategies goal is to remove unimportant weights and force the existing network to learn a sparse generalizable representation.\n\\subsection{L1 + Magnitude Pruning Mechanism}\nWe implement L1 + Magnitude as a three player game where the first player, $n_1$, plays an L1 strategy, the second player, $n_2$, plays a positive magnitude strategy and the third player, $n_3$, plays a negative magnitude strategy.\n\\subsection{Random + Magnitude Pruning Mechanism}\nWe implement Random + Magnitude as a three player game where the first player, $n_1$, plays an random strategy, the second player, $n_2$, plays a positive magnitude strategy and the third player, $n_3$, plays a negative magnitude strategy.\n\\begin{tiny}\n\\begin{algorithm}[]\n\\label{algo:iterprune}\n\\SetAlgoLined\n\\KwResult{Sparse Neural Network}\n\\SetKwFunction{FPrune}{Prune}\n\\SetKwFunction{FMain}{IterativePrune}\n\\SetKwFunction{FTrain}{Train}\n\\SetKwFunction{FEval}{Evaluate}\n\\SetKwFunction{FNim}{NimGame}\n\\SetKwFunction{Fc}{isConvLayer}\n\\SetKwFunction{Fs}{GetNetworksparsity}\n\\SetKwFunction{Fss}{GetLayersparsity}\n  \\SetKwProg{Fn}{Function}{:}{}\n  \\Fn{\\FMain{$NN, \\pi, s_{target}, P$}}{\n  pruningepochs = $\\frac{s_{target}}{\\pi}$\\;\n  \\FEval($NN$)\\;\n  \\For{i in range(0,2)}{\n      \\FTrain{$NN$}\\;\n      \\FEval($NN$)\\;\n    }\n    $s_{current target} = 0$\\;\n    \\For{i in range(0,pruningepochs)}{\n        $s_{current target} =  s_{current target} + \\pi$ \\;\n        $s_{current} =$ \\Fs{$NN$}\\;\n        \\While{$s_{current} < s_{current target}$}{\n            \\For{$\\lambda \\in NN$}{\n                \\If{\\Fc{$\\lambda$}} {\n                    \\If{\\Fss{$\\lambda $}   $ < s_{current target}$} {\n                        $\\lambda = $ \\FNim{$\\lambda , P$}\\;\n                    }\n                }\n                $s_{current} =$ \\Fs{$NN$}\\;\n        }\n        }\n        \\FEval($NN$)\\;\n        \\FTrain{$NN$}\\;\n        \\FEval($NN$)\\;\n    }\n    \\For{i in range(0,10)}{\n      \\FTrain{$NN$}\\;\n      \\FEval($NN$)\\;\n    }\n}\n\\caption{Iterative Network Pruning}\n\\end{algorithm}\n\\end{tiny}\n\\begin{algorithm}[]\n\\label{algo:nim}\n\\SetAlgoLined\n\\KwResult{pruned layer of a NN}\n\\SetKwFunction{FPrune}{Prune}\n\\SetKwFunction{FMain}{NimGame}\n\\SetKwFunction{Fs}{getStrategy}\n\\S\n  \\SetKwProg{Fn}{Function}{:}{}\n  \\Fn{\\FMain{$\\lambda_i, P$}}{\n  \\For{p $\\in$ P}{$\\lambda_i$=\n  \\FPrune{$\\lambda_i$,\\Fs{$p$}}\\; \n  }\n}\n\\caption{Iterative Network Pruning}\n\\end{algorithm}\n\\begin{algorithm}[]\n\\label{algo:prune}\n\\SetAlgoLined\n\\KwResult{Pruned Neural Network Layer}\n\\SetKwFunction{FMain}{Prune}\n  \\SetKwProg{Fn}{Function}{:}{}\n  \\Fn{\\FMain{$\\lambda_i$, $M$}}{\n        idx-sort = Sort weights $w_j \\in \\lambda_i$ using by $M$ \\CommentSty{//produce a sorted lookup index of weights in layer based on a sorting function $M$}\\;\n        j = 0 \\; \n        \\While{$\\lambda_i$[idx-sort[j]] == 0} {\n         j = j + 1  \\CommentSty{//Find first non pruned weight}\n        }\n        $\\lambda_i$[idx-sort[j]] = 0 \\CommentSty{Prune weight by setting to 0} \\; \n        \\KwRet $\\lambda_i$\n}\n\\caption{Prune Function sorts the weights in layer given using the optimization goal and sets the least important non zero weigth to 0 }\n\\end{algorithm}\n\\begin{figure}[H]\n\\centering\n\\includegraphics[width=6cm, height=6cm]{Paper/images/resnet50cifar10.png}\n\\caption{RESNET50 on CIFAR10}\n\\end{figure}\n\\begin{figure}[H]\n\\centering\n\\includegraphics[width=6cm, height=6cm]{Paper/images/resnet50cifar100.png}\n\\caption{RESNET50 on CIFAR100}\n\\end{figure}\n\\begin{figure}[H]\n\\centering\n\\includegraphics[width=6cm, height=6cm]{Paper/images/dpn92cifar10.png}\n\\caption{DPN92 on CIFAR10}\n\\end{figure}\n\\begin{figure}[H]\n\\centering\n\\includegraphics[width=6cm, height=6cm]{Paper/images/dpn92cifar100.png}\n\\caption{DPN92 on CIFAR100}\n\\end{figure}\n\\begin{figure}[H]\n\\centering\n\\includegraphics[width=6cm, height=6cm]{Paper/images/vgg16cifar10.png}\n\\caption{VGG16 on CIFAR10}\n\\end{figure}\n\\begin{figure}[H]\n\\centering\n\\includegraphics[width=6cm, height=6cm]{Paper/images/vgg16cifar100.png}\n\\caption{VGG16 on CIFAR100}\n\\end{figure}\n\\begin{table}[h]\n\\begin{tabular}{|l|r|r|r|}\n\\hline\n     prune\\_method &  sparsity &  accuracy \\\\ \\hline\n     Baseline  &  0.000000 &     66.13 \\\\ \\hline\n        MAGNITUDE &  0.925926 &     74.10 \\\\ \\hline\n        L1+RANDOM &  0.925926 &     74.82 \\\\ \\hline\n         Negative &  0.925926 &     74.18 \\\\ \\hline\n         Positive &  0.925926 &     74.35 \\\\ \\hline\n               L1 &  0.925926 &     74.82 \\\\ \\hline\n           RANDOM &  0.925926 &     74.21 \\\\ \\hline\n MAGNITUDE+RANDOM &  0.925926 &     73.91 \\\\ \\hline\n     MAGNITUDE+L1 &  0.925926 &     74.79 \\\\ \\hline\n\\end{tabular}\n\\label{tab:cifar100-DPN92}\n\\caption{DPN-92 on CIFAR 100. }\n\\end{table}\n\n\n\\begin{table}[h]\n\\begin{tabular}{|l|r|r|r|}\n\\hline\n     prune\\_method &  sparsity &  accuracy \\\\ \\hline\n   Baseline  &  0.000000 &     88.61 \\\\ \\hline\n               L1 &  0.925926 &     95.45 \\\\ \\hline\n         Positive &  0.925926 &     95.25 \\\\ \\hline\n         Negative &  0.925926 &     93.85 \\\\ \\hline\n MAGNITUDE+RANDOM &  0.925926 &     94.32 \\\\ \\hline\n        MAGNITUDE &  0.925926 &     92.78 \\\\ \\hline\n           RANDOM &  0.925926 &     95.17 \\\\ \\hline\n        L1+RANDOM &  0.925926 &     95.16 \\\\ \\hline\n     MAGNITUDE+L1 &  0.925926 &     94.30 \\\\ \\hline \n\\end{tabular}\n\\label{tab:cifar10-DPN92}\n\\caption{DPN-92 on CIFAR 10. Unlike all other experiments the most successful mechanism is a one player game.}\n\\end{table}\n\n\\begin{table}[h]\n\\begin{tabular}{|l|r|r|r|}\n\\hline\n     prune\\_method &  sparsity &  accuracy \\\\ \\hline \n     Baseline &  0.000000 &     86.85 \\\\ \\hline\n         Positive &  0.961008 &     90.81 \\\\ \\hline\n        MAGNITUDE &  0.985989 &     90.16 \\\\ \\hline\n         Negative &  0.961008 &     88.92 \\\\ \\hline\n           RANDOM &  0.975409 &     90.27 \\\\ \\hline\n MAGNITUDE+RANDOM &  0.994909 &     90.80 \\\\ \\hline\n        L1+RANDOM &  0.981350 &     91.10 \\\\ \\hline\n               L1 &  0.975409 &     90.37 \\\\ \\hline\n     MAGNITUDE+L1 &  0.921536 &     90.04 \\\\ \\hline\n\\end{tabular}\n\\label{tab:cifar10-VGG16}\n\\caption{VGG16 on CIFAR 10. While all methods outperform initial baseline the combination of L1+Random outperforms all other methods.}\n\\end{table}\n\n\\begin{table}[h]\n\\begin{tabular}{|l|r|r|r|}\n\\hline\n     prune\\_method &  sparsity &  accuracy \\\\ \\hline \n        Baseline &  0.000000 &     58.43 \\\\ \\hline\n         Positive &  0.961008 &     67.27 \\\\ \\hline\n           RANDOM &  0.975409 &     67.61 \\\\ \\hline\n     MAGNITUDE+L1 &  0.921484 &     65.71 \\\\ \\hline\n        MAGNITUDE &  0.985989 &     66.66 \\\\ \\hline\n        L1+RANDOM &  0.981350 &     67.98 \\\\ \\hline\n         Negative &  0.961008 &     64.96 \\\\ \\hline\n MAGNITUDE+RANDOM &  0.994906 &     67.39 \\\\ \\hline\n               L1 &  0.975409 &     67.44 \\\\ \\hline\n\\end{tabular}\n\\label{tab:cifar100-VGG16}\n\\caption{VGG16 on CIFAR 100. While all methods outperform initial baseline the combination of L1+Random outperforms all other methods.}\n\\end{table}\n\n\\begin{table}[h]\n\\begin{tabular}{|l|r|r|r|}\n\\hline\n     prune\\_method &  sparsity &  accuracy \\\\ \\hline\n           Baseline &  0.000000 &     62.74 \\\\ \\hline\n           RANDOM &  0.925926 &     73.23 \\\\ \\hline\n         Positive &  0.925926 &     73.06 \\\\ \\hline\n        MAGNITUDE &  0.925926 &     72.00 \\\\ \\hline\n MAGNITUDE+RANDOM &  0.925926 &     71.54 \\\\ \\hline\n     MAGNITUDE+L1 &  0.925926 &     71.63 \\\\ \\hline\n        L1+RANDOM &  0.925926 &     73.35 \\\\ \\hline\n         Negative &  0.925926 &     72.31 \\\\ \\hline\n               L1 &  0.925926 &     72.75 \\\\ \\hline\n\\end{tabular}\n\\label{tab:cifar100-RESNET50}\n\\caption{RESNET50 on CIFAR 100. While all methods outperform initial baseline the combination of L1+Random outperforms all other methods.}\n\\end{table}\n\n\\begin{table}[h]\n\\begin{tabular}{|l|r|r|r|}\n\\hline\n     prune\\_method &  sparsity &  accuracy \\\\ \\hline\n         Baseline &  0.000000 &     86.89 \\\\ \\hline\n         Positive &  0.925926 &     91.69 \\\\ \\hline\n         Negative &  0.925926 &     91.68 \\\\ \\hline\n MAGNITUDE+RANDOM &  0.925926 &     92.09 \\\\ \\hline\n        MAGNITUDE &  0.925926 &     90.78 \\\\ \\hline\n        L1+RANDOM &  0.925926 &     92.36 \\\\ \\hline\n               L1 &  0.925926 &     91.92 \\\\ \\hline\n           RANDOM &  0.925926 &     92.20 \\\\ \\hline\n     MAGNITUDE+L1 &  0.925926  &     91.49 \\\\ \\hline\n\\end{tabular}\n\\label{tab:cifar10-RESNET50}\n\\caption{RESNET50 on CIFAR 10. While all methods outperform initial baseline the combination of L1+Random outperforms all other methods.}\n\\end{table}\n\\end{document}\n", "meta": {"hexsha": "7ddbf45e08bd747c593e2e271b17c5e0103a4229", "size": 31178, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Paper/other_main.tex", "max_stars_repo_name": "spacemanidol/PriceOfAnarchyPruning", "max_stars_repo_head_hexsha": "ea20c251a1eca04abb566d5968c3e41204dc3fc9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-02T09:02:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-02T09:02:34.000Z", "max_issues_repo_path": "Paper/other_main.tex", "max_issues_repo_name": "spacemanidol/PriceOfAnarchyPruning", "max_issues_repo_head_hexsha": "ea20c251a1eca04abb566d5968c3e41204dc3fc9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-03T08:39:42.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-03T08:39:42.000Z", "max_forks_repo_path": "Paper/other_main.tex", "max_forks_repo_name": "spacemanidol/GameTheoreticPruning", "max_forks_repo_head_hexsha": "ea20c251a1eca04abb566d5968c3e41204dc3fc9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 100.5741935484, "max_line_length": 1131, "alphanum_fraction": 0.7508499583, "num_tokens": 7977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3437045784511603}}
{"text": "\\chapter{Proposed Translator}\n\\label{ch:proposed-translator}\n\nThis chapter focuses on proposing a solution to ODMTP.\nFirst formalizing the solution. And then modelling it\nwith elements of software engineering such as use cases\nand requirements.\n\n\\section{Translator Formalization}\nAs a solution to the previous chapter, this section focuses on\nproposing a application $f : S' \\rightarrow M$ such that\napplied on a schema, results in a domain model based on\nplain objects.\n\nLets define $f(S') = \\begin{bmatrix}f'(s_1')\\\\ f'(s_2')\\\\ \\vdots\\\\ f'(s_n')\\end{bmatrix}$ and\n$f'(s_i') = \\begin{bmatrix}f''(e_1')\\\\ f''(e_2')\\\\ \\vdots\\\\ f''(e_n')\\end{bmatrix}$. Then $f''(e_i')$\nis the application that maps a triple expression $e'$ from $N \\times T_{g} \\times \\{(1,1),(0,\\infty)\\}$\nto $N \\times T_g$. To find such a function we will use the knowledge that we already have.\nWe know that $p$ has a direct mapping as it belongs to $N$, $T_g$ maps to $T_g$ if\nthe cardinality value is $(1,1)$ or $(1, \\infty)$. And the cardinality is aggregated to the type\nso its not needed to map it. Then we define the application $f''(e')$ as $f:(p,t,c) \\in N \\times T_g \\times \\{(1,1), (0,\\infty)\\} \\rightarrow (n,t)\\in N \\times T_g$\nand therefore,\n\n\\begin{equation}\\label{eq:transformation}\nf''(e_i')\n\\begin{cases}\n    (p,Proy_{t_g}lst) & if \\; c=(1,1) \\\\\n    (p,List[Proy_{t_g}lst]) & if \\; c=(0,\\infty)\n\\end{cases}.\n\\end{equation}\n\nThis application's function is to transform a triple expression\ninto an annotated type property. Where the $Proy_{tg}lst$ represents\nthe projection of the generic type from the abstraction of languages\nof representation of plain objects on to the language specific type.\n\\cref{fig:lst-diagram} illustrates how the same input can lead to\nmultiple types due to the specific translators, that perform the \n$Proy_{tg}lst$ operation.\n\n\\begin{figure}\n    \\includegraphics[scale=0.8]{images/lsc-diagram.pdf}\n    \\centering\n\t\\caption[Different target types generated by specific translators]{Different target types generated by specific translators.}\n    \\label{fig:lst-diagram}\n\\end{figure}\n\n\\section{Translator modelling}\nAt this point we already have an abstraction of our system ready.\nWe know that you must implement the transformation function previously explained.\nNow we will lower our abstraction one level.\nFor this we will model our system by means of software engineering techniques\nsuch as use cases, requirements or class diagrams. First, we will use the use case\nmethod to find the necessary functionality of our system.\n\n\\begin{figure}[h!]\n    \\includegraphics[scale=0.8]{images/trans-use-case.pdf}\n    \\centering\n    \\caption[Translator use cases]{Translator use cases.}\n    \\label{fig:trans-use-case}\n\\end{figure}\n\n\\cref{fig:trans-use-case} shows us that in our system we will, of course, have the functionality to\ntranslate ShEx schemas to domain models based on plain objects.\nBut we can also see that the entry may be wrong.\nThis implies that there must be some kind of input validation.\nIn addition, an error management system is also necessary.\n\\cref{fig:trans-flow} illustrates a high level view of the flowchart that the translator follows.\n\n\\begin{figure}\n    \\includegraphics[width=\\textwidth]{images/diagrama-flujo-traductor.pdf}\n    \\centering\n    \\caption[Translator high level flowchart]{Translator high level flowchart.}\n    \\label{fig:trans-flow}\n\\end{figure}\n\nAlso from the developed use cases we can extract the list of functional and\nnon-functional requirements (external interfaces) that our system must support.\n\n\\begin{figure}[h!]\n    \\includegraphics[width=\\textwidth]{images/trans-reqf.pdf}\n    \\centering\n    \\caption[Translator functional requirements]{Translator functional requirements.}\n    \\label{fig:trans-reqf}\n\\end{figure}\n\n\\begin{figure}[h!]\n    \\includegraphics[width=\\textwidth]{images/trans-reqnf.pdf}\n    \\centering\n    \\caption[Translator non functional requirements]{Translator non functional requirements.}\n    \\label{fig:trans-reqnf}\n\\end{figure}\n\nThus, for the previous use cases and requirements the implementation abstract diagram will be.\n\n\\begin{figure}[h!]\n    \\includegraphics[width=\\textwidth]{images/trans-diagram.pdf}\n    \\centering\n    \\caption[Translator component and class diagrams]{Translator component and class diagrams.}\n    \\label{fig:trans-diag}\n\\end{figure}", "meta": {"hexsha": "a155989829c95dd4cf752664522e8e8dbd5aeef3", "size": 4339, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/part_2/translator-analysis.tex", "max_stars_repo_name": "thewilly/shex-lite-book", "max_stars_repo_head_hexsha": "ce22ebcf6cd1ce5bafd79398ee87e50dcb18c41d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/part_2/translator-analysis.tex", "max_issues_repo_name": "thewilly/shex-lite-book", "max_issues_repo_head_hexsha": "ce22ebcf6cd1ce5bafd79398ee87e50dcb18c41d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/part_2/translator-analysis.tex", "max_forks_repo_name": "thewilly/shex-lite-book", "max_forks_repo_head_hexsha": "ce22ebcf6cd1ce5bafd79398ee87e50dcb18c41d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.39, "max_line_length": 164, "alphanum_fraction": 0.7483291081, "num_tokens": 1153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.34347927713960125}}
{"text": "\\documentclass[oneside,9pt]{article}\n\\usepackage[a4paper,width=170mm,top=18mm,bottom=22mm,includeheadfoot]{geometry}\n\\pdfoutput=1\n\\usepackage{multicol}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{caption}\n\\usepackage{hyperref}\n\\usepackage{mathtools}\n\\usepackage[linesnumbered,algoruled,boxed,lined]{algorithm2e}\n\\usepackage{graphicx}\n\\usepackage{float}\n\n\\hypersetup{\n    colorlinks=true,\n    urlcolor=cyan\n}\n\\hypersetup{final}\n\n% paper version\n\\newcommand{\\PaperVersionNumber}{0.1 - 2018-02-28}\n\n\\providecommand{\\keywords}[1]{\\textbf{\\textit{Keywords---}} #1}\n\n% list of elements\n\\newcommand{\\lista}[3][_]{ #2#10, \\dots, #2#1{#3} }\n% set\n\\newcommand{\\setd}[1]{ \\mathit{#1} }\n\\newcommand{\\setl}[2]{ \\left\\{ \\lista{#1}{#2} \\right\\}  }\n% vector\n\\newcommand{\\vecd}[1]{ \\textbf{#1} }\n\\newcommand{\\vecl}[2]{ (\\lista{#1}{#2}) }\n% poly\n\\newcommand{\\poly}[2]{ p_{\\textbf{#1}}(#2) }\n\\newcommand{\\polysum}[3][x]{ #2_0 + #2_1 #1 + #2_2 #1^2 + \\dots + #2_{#3} #1^{#3} }\n% big O\n\\newcommand{\\bigo}[1]{ \\mathcal{O}(#1) }\n\n% evaluated point\n\\newcommand{\\ele}{s}\n% linear codes \\ec{n}{k}\n\\newcommand{\\ec}[2]{ \\mathcal{C}(#1, #2) }\n% finite field \\gf{q} or \\gf[n]{p}\n\\newcommand{\\gf}[2][]{ \\mathbb{F}_{{#2}^{#1}} }\n% ring nf4\n\\newcommand{\\ringn}[1][n]{ \\mathbb{R}_{F_4}(#1) }\n% fft\n\\newcommand{\\fft}[1]{ \\text{FFT}(#1) }\n\\newcommand{\\fftl}{N}\n% coef\n\\newcommand{\\ith}[1]{#1^\\text{th}}\n% set of points\n\\newcommand{\\sete}{\\setd{S}}\n% complexity\n\\newcommand{\\an}[1][N]{\\mathcal{A}(#1)}\n\\newcommand{\\mn}[1][N]{\\mathcal{M}(#1)}\n% F4\n\\newcommand{\\ffour}{65537}\n\\newcommand{\\ffourMinusOne}{65536}\n% operator\n\\newcommand{\\op}{\\diamond}\n\n\\DeclarePairedDelimiter{\\ceil}{\\lceil}{\\rceil}\n\\newcommand*\\eg{e.g.\\@\\xspace}\n\\newcommand*\\Eg{e.g.\\@\\xspace}\n\\newcommand*\\ie{i.e.\\@\\xspace}\n\\newcommand*\\samethanks[1][\\value{footnote}]{\\footnotemark[#1]}\n\n%\\renewcommand{\\itemhook}{\\setlength{\\topsep}{0pt}  \\setlength{\\itemsep}{0pt}\\setlength{\\leftmargin}{15pt}}\n\n%% Authors\n\\author{ Vianney Rancurel\\thanks{Scality in San Francisco, CA, 94104.}\\\\ \\texttt{vianney.rancurel@scality.com}\n    \\and L\\^am Pham-Sy\\thanks{Scality France.}\\\\ \\texttt{lam.pham-sy@scality.com} \n    \\and Sylvain Laperche\\samethanks[3]\\\\ \\texttt{sylvain.laperche@scality.com}\n}\n\n\\title{QuadIron: A library for Number Theoretic Transform-based Erasure Codes\\thanks{Manuscript received Januray 12, 2020.}}\n\n\\begin{document}\n\\maketitle\n\n\\begin{abstract}\nReed-Solomon codes can be seen as polynomial operations which can be implemented by number theoretic transforms and accelerated by different fast Fourier transform algorithms according to the characteristics of the fields. We present a library, QuadIron, which implements FFTs in binary, prime, and extension fields, as well as a set of optimizations to make them practical for a very large number of symbols. These FFT-based erasure codes could be useful for applications like decentralized storage over Internet, or real-time video high-quality streams.\n\\end{abstract}\n\n\n\\keywords{Number Theoretic Transforms, Discrete Fourier Transforms, Finite Fields, Erasure Codes, Digital Storage, Distributed storage, Decentralized Storage, Decentralized Cloud Storage, Real-time video, high-quality streaming}\n\n\n\\section{Introduction}\n\\label{sec:introduction}\n\nA {$\\ec{n}{k}$} erasure code is defined by $n=k+m$, $k$ being the number of data fragments, $m$ being the number of desired erasure fragments. In an application it is required to transmit the $n$ fragments. A Maximum Distance Separable (MDS) code guarantees that any $k$ fragments can be used to decode a file. Erasure codes can be either systematic or non-systematic. Systematic codes generate $n-k$ erasure fragments and therefore maintain $k$ data fragments. Non-systematic codes generate $n$ erasure fragments. In the case of systematic codes, we try to retrieve primarily the $k$ data fragments if possible because there is nothing to decode. A decoding is necessary only if one or more data fragments are missing. In the case of non-systematic codes, we need to decode $k$ fragments. Erasure codes can also be compared by their sensitivity to the rate $r=k/n$, which may or may not impact the encoding and decoding speed. Another comparison criterion is the support of adaptive rate: does the erasure code allows to change $k$ and $m$ dynamically, without having to regenerate the whole set of erasure fragments. Another critical property is called the 'confidentiality' \\cite{li_confidentiality} which is determined if an attacker can partially decode the data if he obtains less than k fragments. Finally, we can also compare erasure code according to their repair bandwidth, i.e.\\ the number of fragments required to repair a fragment. To sum up, here is a list of codes' properties that are of interest for us:\n\\begin{itemize}\n\\item MDS/non-MDS\n\\item Systematic/Non-systematic\n\\item Encoding/Decoding speed according to various $n$\n\\item Encoding/Decoding speed predictivity and stability acc/ to $n$\n\\item Rate sensitivity\n\\item Adaptive vs non-adaptive rate\n\\item Confidentiality\n\\item Repair bandwidth\n\\end{itemize}\n\nReed-Solomon (RS) codes are MDS codes constructed from Vandermonde or Cauchy matrices \\cite{reed_sol} that are systematic and support adaptive rates. The RS encoding process is traditionally performed by multiplying a $[n \\times k]$ matrix by a $k$ data vector in $\\gf{2^w}$, leading to a high complexity of $\\bigo{k \\times n}$. The topic of optimizing those codes has been widely discussed. While such optimizations reduce the overall complexity, most of them rely solely on hardware optimizations, therefore their real complexity in ''big O'' notation has not been widely studied.\n% * <wabernat@sonic.net> 2018-03-02T18:03:30.509Z:\n% \n% Question on notation: I am assuming that an n*k matrix is a different expression than k x n. If not, make them the same.\n% \n% ^.\n\nLow-Density-Parity-Check (LDPC) codes are also an important class of erasure codes and are constructed over sparse parity-check matrices. Although initially used in networking applications, some researchers recently showed that it is possible to use them in distributed storage scenarios \\cite{plank_ldpc}. Those codes, which even though require to store $n=k+m$ fragments (like MDS codes), need to retrieve $[f \\times k]$ fragments to recover the data (instead of only $k$ for MDS codes), $f$ being called the overhead or the inefficiency. The study \\cite{plank_ldpc} shows 3 types of LDPC codes where $f$ oscillates between $1.10$ and $1.30$ for $n \\lessapprox 100$, and shows that you need a larger $n$, e.g.\\ $n \\gtrapprox 1000$ in order to have an $f$ approaching $1.0$. As shown by \\cite{plank_ldpc}, those codes are more sensible to network latency because of the extra fragments, due to the overhead, that they need to retrieve, so in cases where latency can be important RS codes seems more interesting than LDPC codes. More recently hybrid-LDPC schemes such as \\cite{wirehair} have reduced the overhead to $[k + f]$ with a very small f. Also, \\cite{park_ldpc} have shown that it is possible to design LDPC codes which beat RS codes when taking into account the repair bandwidth, because RS codes always need to retrieve $k$ fragments to be able to repair the data, while it is possible to design LDPC codes that require less than $k$ fragments for the repair process. However:\n\\begin{itemize}\n\\item LDPC are not MDS: it is always possible to find a pattern (e.g.\\ stopping sets) that cannot decode (e.g. having only k fragments out of n).\n\\item You can always find/design an LDPC code optimized for few properties (i.e.\\ tailored for a specific use case) that beats other codes on those few properties, but there is no silver bullet: it will be sub-optimal for the other properties (its a trade-off, e.g.\\ good for large $n$ and with an optimal repair bandwidth, but not good for small $n$ and cannot support adaptive rate): these cannot be used in a generic library.\n\\item Designing a good LDPC code is some kind of black art that requires a lot of fine tuning and experimentation. Ultimately an LDPC code optimal for all the interesting properties for a given use case could exist but would be very complex and/or would only be available in a commercial library.\n\\end{itemize}\n\nRecently some other types of codes, called Locally-Repairable-Codes (LRC) \\cite{xor_elephant} \\cite{erasure_azure}, have tackled the repair bandwidth issue of the RS codes. They combine multiple layers of RS: the local codes and the global codes. However those codes are not MDS and they require an higher storage overhead than MDS codes.\n\nFast Fourier transform (FFT) based RS codes remain relatively simple, and can be used to perform encoding on finite fields with clearer and lower announced complexities therefore having a good set of desirable properties:\n\\begin{itemize}\n\\item They are MDS\n\\item Support both systematic or non-systematic codes\n\\item Fast for a wide range of $n$\n\\item Rate insensitive (for non-systematic codes).\n\\item Confidential (for systematic codes).\n\\end{itemize}\nWe focus our research on optimizing their encoding and decoding speed.\n% * <wabernat@sonic.net> 2018-03-02T18:07:38.602Z:\n% \n% > Recently, thanks to fast Fourier transform\n% Are you announcing your findings here? If so: \"We have found that using FFT...\"\n% \n% ^.\n\nSince the computational complexities of FFT operations mainly depend on the chosen finite field, we investigate two types of finite fields: prime finite fields and binary extension finite fields. For each type, there are different approaches to accelerate the FFT operations.\n\n%\\hfill The authors\n \n%\\hfill April 26, 2018\n\n\\section{Reed-Solomon codes}\n%%%%%%%%%%%%%%%%%%%%%%%%\n\nA Reed-Solomon (RS) code is an MDS code $\\ec{n}{k}$ defined over a finite field $\\gf{q}$ where $q$ is a prime power $q=p^w$. A code word composed of $n$ symbols is generated from a message of length $k$. The message is recovered from a subset of at least $k$ elements of the code word.\n% * <wabernat@sonic.net> 2018-03-02T18:23:50.138Z:\n% \n% > code word\n% Changing this to code word from \"codeword\" globally. If you know better (i.e., if \"codeword\" is a widely accepted neologism), you can roll it back.\n% \n% ^.\n\n\\subsection{Encoding}\nAs  Reed and Solomon described in their foundational paper\\cite{reed_sol}, a code word is encoded from a message using polynomial evaluation. \n\nA message $\\vecd{m} = \\vecl{m}{k} \\in \\gf{q}^k$ can be represented as a polynomial $\\poly{m}{x}$ of degree $k-1$:\n\n\\begin{equation}\\label{eq:poly}  \n\t\\poly{m}{x} = \\polysum{m}{k-1}\n\\end{equation}\n\nThe code word $\\vecd{c} = \\vecl{c}{n-1}  \\in \\gf{q}^n$ of the message $\\vecd{m}$ is obtained by evaluating $\\poly{m}{x}$ at a given but arbitrary set of $n$ \\emph different points $\\sete = \\setl{\\ele}{n-1}$ of the field $\\gf{q}$,  called the set of evaluation points. Concretely,\n\n\\begin{equation}\\label{eq:enc_def}\n\\begin{split}\n\tc_0 &= \\polysum[\\ele_0]{m}{k-1},\\\\\n\tc_1 &= \\polysum[\\ele_1]{m}{k-1},\\\\\n\t& \\dots \\\\\n\tc_{n-1} &= \\polysum[\\ele_{n-1}]{m}{k-1}\\\\\n\\end{split}\n\\end{equation}\n\nEquation (\\ref{eq:enc_def}) can be represented as a multiplication of the message $\\vecd{m}$ and matrix $G$:\n\n\\begin{equation}\n\\vecd{c} = \\vecd{m} \\times G\n\\end{equation}\n where $G$ is the generator matrix of the RS codes:\n\n\\begin{equation}\\label{eq:gen_mat}\nG = \\begin{bmatrix}\n1 & 1 & \\dots & 1 \\\\\n\\ele_0 & \\ele_1 & \\dots & \\ele_{n-1} \\\\\n\\ele_0^2 & \\ele_1^2 & \\dots & \\ele_{n-1}^2 \\\\\n\\vdots & \\vdots & & \\vdots \\\\\n\\ele_0^{k-1} & \\ele_1^{k-1} & \\dots & \\ele_{n-1} ^{k-1}\n\\end{bmatrix}\n\\end{equation}\n\nSince $\\ele_i \\neq \\ele_j$ when  $i \\neq j$, $G$ is actually a Vandermonde matrix \\cite{book_ecc}.\n% * <wabernat@sonic.net> 2018-03-02T18:31:07.849Z:\n% \n% > for\n% do you mean \"when\" or \"because\"?\n% \n% ^.\n\nStraightforwardly, the encoding process has a computational complexity of $\\bigo{k \\times n}$ for performing a multiplication of a vector $\\vecd{m}$ and a matrix $G$.\n\nThis complexity can be reduced by using a Discrete Fourier Transform (DFT) on a finite field that evaluates polynomial $\\poly{m}{x}$ at the set $\\sete$ of evaluating points. Currently, two main Fast Fourier Transform (FFT) techniques apply for prime field $\\gf{p}$ \\cite{cooley_tukey,fnt_lacan,fnt_ida}, and for binary extension field $\\gf{2^w}$ \\cite{fft_add_wang_zhu,fft_add_cantor,fft_add_gao_mateer,fft_add_chung}. We summarize these techniques in Section \\ref{sec:fft}. Briefly, thanks to the FFT techniques, the encoding complexity drops to $\\bigo{n \\times \\log{n}}$.\n\n%Briefly, the codeword $\\vecd{c}$ can be calculated by one FFT operation on message $\\vecd{m}$:\n%\\begin{equation}\\label{eq:fft_1}\n%\\vecd{c} = \\fft{\\vecd{m}}\n%\\end{equation}\n\n\\subsection{Decoding}\n\nA message $\\vecd{m}$ can be decoded from a code word $\\vecd{c}$ that could miss at most $n-k$ elements. Indeed, given a set of $k$ coefficients of $\\vecd{c}$, the polynomial $\\poly{m}{x}$ in Equation (\\ref{eq:poly}) can be regenerated using Lagrange interpolation because its degree is at most $k-1$. Let $\\setl{\\tilde{c}}{k-1}$ denote the set of $k$ known coefficients corresponding to $k$ evaluation points $\\setl{\\tilde{\\ele}}{k-1}$. The polynomial $\\poly{m}{x}$ is thus interpolated:\n\n\\begin{equation}\n\\label{eq:lagrange}\n\\poly{m}{x} = \\sum_{i=0}^{k-1} \\big( \\tilde{c}_i \\times \\sum_{0 \\leq j \\leq k-1, j \\neq i} \\frac{x - \\tilde{\\ele}_j}{ \\tilde{\\ele}_i - \\tilde{\\ele}_j } \\big)\n\\end{equation}\n\nCoefficients of the message $\\vecd{m}$ are actually coefficients of $\\poly{m}{x}$.\n\nOn prime field, equation \\ref{eq:lagrange} can be simplified as proposed in \\cite{fnt_lacan}. Note that degree of $\\poly{m}{x}$ is at most $(k-1)$, the polynomial is derived as:\n\n\\begin{equation}\n\\poly{m}{x} =  \\Big( A(x) \\times \\sum_{i=0}^{k-1} \\frac{n_i}{x -  \\tilde{\\ele}_i}  \\Big) \\text{ mod } x^k\n\\end{equation}\nwhere\n\\[\n\\begin{split}\nA(x) &= \\prod_{i=0}^{k-1}(x -  \\tilde{\\ele}_i), \\\\\nn_i &= \\frac{ \\tilde{c}_i }{ A'( \\tilde{\\ele}_i) }\n\\end{split}\n\\]\n\nUsing Taylor series, we have\n\n\\[\n\\frac{1}{ \\tilde{\\ele}_i - x } = \\sum_j \\frac{ x^j }{ {\\tilde{\\ele}_i}^{j+1} }\n\\]\n\nAnd by defining the following polynomial:\n\\[\nN(x) := \\sum_{i = 0}^{k-1} \\frac{n_i}{\\tilde{\\ele}_i} \\times x^{z_i}\n\\]\nwhere its exponents $\\{z_i, i = 0, \\dots, k-1 \\}$ are determined by the evaluation set $S$ and the $\\ith{n}$-root of unity $r$\n\\[\n\\tilde{\\ele}_i = r^{z_i}, \\ i = 0, \\dots, k-1\n\\]\n \n We obtain a simpler formula:\n\n\\begin{equation}\n\\poly{m}{x} =  \\Big( A(x) \\times B(x) \\Big) \\text{ mod } x^k\n\\end{equation}\nwhere $B(x) := \\sum_{i=0}^{k-1} N(r^{-i}) x^i $ whose coefficients are obtained by evaluating $N(x)$ at $k$ points $\\{ r^{-i} \\}$ that can be efficiently performed using the inverse FFT algorithm.\n\nThanks to the convolution theorem, we can use FFT techniques to accelerate the multiplication of two polynomials $A(x), B(x)$:\n\\begin{equation}\nA(x) \\times B(x) = iFFT_{2k} ( FFT_{2k}(A) \\cdot FFT_{2k}(B) )\n\\end{equation}\nwhere $FFT_{2k},  iFFT_{2k}$ are FFT and inverse FFT of length $2 \\times k$.\n\nNote that $A(x)$ depends only on evaluation points, hence $A(x), A'(x), FFT_{2k}(A)$ can be calculated once.\n\nThe decoding computation is composed of:\n(1) one inverse FFT of length $n$ to compute $N(x)$;\n(2) one FFT and one inverse FFT of length $2k$ to compute $A(x) \\times B(x)$.\nIt leads to a decoding complexity of $\\bigo{ n \\log n + 4 k \\log{2k}}$.\n\nCompared to \\cite{fnt_lacan}, our computations are based on the fact that the degree of $\\poly{m}{x}$ is smaller than $k$. Hence we use $2k$-length FFT instead of $2n$-length FFT.\n\n%%%%%%%%%  Section %%%%%%%%%%\n\\section{How can FFT reduce Encoding Complexity?}\\label{sec:fft}\n%%%%%%%%%%%%%%%%%%%%%%%%\n\nIn this section, we summarize two FFT techniques on the field $\\gf{q}$ that can the reduce computational complexity of the encoding process. Their common methodology is to split an FFT operation on a vector $\\vecd{m}$ into two FFT operations on a smaller set $\\vecd{m}_1$ and $\\vecd{m}_2$. \nLet $\\fftl$ denote the length of input vector $\\vecd{m}$ that is also represented as a polynomial $\\poly{m}{x}$\n\n\\begin{equation}\\label{eq:poly_fft}  \n\t\\poly{m}{x} = \\polysum{m}{\\fftl-1}\n\\end{equation}\n\nGiven a set $\\sete = \\setl{\\ele}{\\fftl-1}$ of different elements of $\\gf{q}$, FFT transforms the input vector to an output vector $\\vecd{c}$ whose coefficients are values of $\\poly{m}{x}$ evaluated at points of $\\sete$.\n\n\\begin{equation}\\label{eq:enc_fft}  \n\t\\vecd{c} = \\big( \\poly{m}{\\ele_0}, \\poly{m}{\\ele_1}, \\dots, \\poly{m}{\\ele_{\\fftl-1}} \\big)\n\\end{equation}\n\nThis is similar to the described RS encoding process, except that the input and output vectors are of the same length $\\fftl$.\n\nThe key factor that allows splitting FFTs into smaller transformations is choosing the set $\\sete$. The two methods of constructing such a set are described here.\n% * <wabernat@sonic.net> 2018-03-02T18:43:34.525Z:\n% \n% > The key factor that allows splitting FFT into smaller ones is choosing the set $\\sete$.\n% Smaller whats? \n% \n% ^.\n\n\\subsection{$\\sete$ as multiplicative group}\n\nThe set $\\sete$ is constructed as a multiplicative group whose generator is the $\\ith{\\fftl}$ root of unity of the field $\\gf{q}$, i.e.\n\n\\begin{equation}\n\\sete = \\left\\{ \\lista[^]{\\alpha}{\\fftl-1} \\right\\}\n\\end{equation}\nwhere $\\alpha$ is the $\\ith{\\fftl}$ root of unity of the field $\\gf{q}$. We call this technique \\textit{multiplicative FFT}.\n\nThe FFT technique applied for the constructed set $\\sete$ was first introduced in \\cite{cooley_tukey}. Supposing that $\\fftl = \\fftl_1 \\times \\fftl_2$, the FFT operation on $\\vecd{m}$ is split into two FFT operations on two vectors $\\vecd{m}_1$ and $\\vecd{m}_2$ of length $\\fftl_1$ and $\\fftl_2$ respectively. This results in a computational complexity $\\bigo{\\fftl(\\fftl_1+\\fftl_2)}$. If $\\fftl$ is highly composite, this technique reduces the computation time to $\\bigo{\\fftl\\log{\\fftl}}$.\n\nTo obtain such advantages, however, this technique requires the satisfaction of two conditions:\n\\begin{enumerate}\n\\item $\\fftl$ is a divisor of $q-1$ (for the existing $\\ith{\\fftl}$ root of unity of the field $\\gf{q}$),\n\\item $\\fftl$ is highly composite, e.g. $\\fftl = 2^v$ ideally\n\\end{enumerate}\n\nA simple solution to satisfying these conditions  is to use the field $\\gf{q=p^w}$ where  $p$ is prime and $p-1$ is highly composite. Fermat numbers, i.e. $F_i = 2^{2^i} + 1$ for $i \\leq 4$, are perfectly suitable for that. This technique, also called Fermat Number Transform (FNT) based erasure codes, was introduced and analyzed in \\cite{fnt_lacan, fnt_ida}.\n\nThis technique, however, does not efficiently apply to the binary extension field $\\gf[w]{2}$ because divisors of $(2^w-1)$ are not highly composite. However, $\\gf[w]{2}$ is perfectly suitable for most practical applications because each element can be expressed by $n$ bits. The following FFT technique focuses on this field.\n\n\\subsection{$\\sete$ as additive group}\n\nThis technique focuses on the binary extension field $\\gf[w]{2}$. Introduced in\\cite{fft_add_wang_zhu, fft_add_cantor}, it was recently improved in \\cite{fft_add_gao_mateer} by using Taylor extension algorithms. A further improvement is shown in \\cite{fft_add_chung}.\n\n%We describe briefly the technique introduced in \\cite{fft_add_gao_mateer}. \nThe FFT length is necessarily a power of 2, i.e. $\\fftl = 2^m$ with $m \\leq w$.\nLet $\\lista{\\beta}{m-1}$ be $m$ linearly independent elements of $\\gf[n]{2}$. The set $\\sete$ is chosen as a subspace spanned by $\\beta_i$ over $\\gf{2}$, i.e.\n\n\\begin{equation}\n\\begin{split}\n\\ele_i = i_0 \\beta_0 + i_1 \\beta_1 + i_2 \\beta_2 + \\dots + i_{m-1} \\beta_{m-1},\\\\\n\\text{ for } 0 \\leq i \\leq 2^m-1\\\\\n\\end{split}\n\\end{equation}\n\nwhere $i = \\polysum[2]{i}{m-1}$ with $i_j \\in \\gf{2}$.\nThe FFT operation on a vector $\\vecd{m}$ is re-expressed as two FFTs on two vectors of half length.\n\n\\subsection{Computational complexity}\n\nLet $\\an[\\fftl]$ denote the number of additions or subtractions in the field $\\gf{q}$ needed for an FFT operation with an input vector of length $\\fftl$  (assuming that an addition requires the same amount of effort to implement as a subtraction).\n\nLet $\\mn[\\fftl]$ denote the number of multiplications required in the field $\\gf{q}$ needed for an FFT operation with an input vector of length $\\fftl$.\n\nThe computational complexities of these algorithms are shown in Table \\ref{tab:compare}, which shows that, with suitable parametrization of the FFT length and the field $\\gf{q}$, multiplicative FFT is faster than all available additive FFTs.\n\n\\begin{table*}[!ht]\n \\caption{Computational complexity of FFT techniques}\n \\label{tab:compare}\n \\begin{center}\n \\begin{tabular}{|c | c | c | c|} \n \\hline\n Name\n \t& Restriction\n\t& Addition $\\an[\\fftl]$\n\t& Multiplication $\\mn[\\fftl]$\n\t\\\\ \\hline\n Multiplicative FFT \n \t& $\\fftl = 2^v$ and $(q-1) \\% \\fftl = 0$ \n \t& $\\fftl \\log_2(\\fftl)$  \n\t& $\\frac{1}{2} \\fftl \\log_2(\\fftl) - \\fftl + 1$\n\t\\\\ \\hline\n Additive FFT \\cite{fft_add_gao_mateer}\n \t& $\\fftl = 2^v$ and $q=2^w$\n\t& $4 \\fftl (\\log_2(\\fftl))^2 + \\frac{3}{4} \\fftl \\log_2(\\fftl) - \\frac{1}{2} \\fftl$ \n\t& $2 \\fftl \\log_2(\\fftl) - 2 \\fftl + 1$\n\t\\\\ \\hline \n Additive FFT \\cite{fft_add_gao_mateer}\n \t& $\\fftl = 2^{2^v}$ and $q=2^w$\n\t& $\\fftl \\log_2(\\fftl) + \\frac{1}{2} \\fftl \\log_2(\\fftl) \\log_2\\log_2(\\fftl)$ \n\t& $\\frac{1}{2} \\fftl \\log_2(\\fftl)$\n\t\\\\ \\hline \n Additive FFT \\cite{fft_add_chung}\n \t& $\\fftl = 2^{v}$ and $q=2^w$\n\t& $\\fftl \\log_2(\\fftl) $ \n\t& $\\frac{1}{2} \\fftl \\log_2(\\fftl)$\n\t\\\\ \\hline \n \\end{tabular}\n \\end{center}\n\\end{table*}\n\n%%%%%%%%%  Section %%%%%%%%%%\n\\section{The QuadIron library}\n%%%%%%%%%%%%%%%%%%%%%%%%\n\nThe QuadIron library is a C++ library, written in C++14, that provides a streaming API to use the different flavors of NTT-based erasure codes.\n\nThe library focuses primarily on high fragmentation, i.e. $n \\gg k$.\n\nIt includes general modular arithmetic routines, algorithms for manipulating rings of integers modulo \\textit{n}, finite fields (including binary, prime, and non-binary extension fields), polynomial operations, different flavors of discrete Fourier transforms, and forward error correction (FEC) algorithms.\n% * <wabernat@sonic.net> 2018-03-02T19:25:31.132Z:\n% \n% >  (non-binary)\n% Parens why?\n% \n% ^.\n% * <wabernat@sonic.net> 2018-03-02T19:24:18.536Z:\n% \n% > n\n% italic?\n% \n% ^.\n\nThe library also includes an abstraction for writing systematic and non-systematic codes, although for applications requiring high fragmentation, systematic codes are not especially useful.\n\n\\subsection{Optimizations}\n\nThe QuadIron library's code relies heavily on templates to generate specifically optimized code at compile time. We use this template to allow a selection of numeric types matching the size of the processor's registers to optimize performance.\n\n\\subsection{Vectorization} \\label{sec:vectorization}\n\nWe focus here on vectorizing multiplicative FFTs which are based on prime (non-binary) field $\\gf{q}$ operations.\n\nWe observe that there are three operations that are costly in multiplicative FFT transformation: addition, subtraction and Hadamard multiplication. All of them are element-wise operations where the inputs are two vectors $\\vec{a}, \\vec{b}$ and the output is a vector $\\vec{c}$. All of these vectors are of the same length $n$.\n\n\\begin{equation}\n\\begin{split}\n\\vec{a} = (a_1, a_2, \\dots, a_n) \\\\\n\\vec{b} = (b_1, b_2, \\dots, b_n) \\\\\n\\vec{c} = (c_1, c_2, \\dots, c_n)\n\\end{split}\n\\end{equation}\n\n\\begin{itemize}\n\\item Addition\n$$\nc_i = (a_i + b_i) \\% q, \\text{ for } i = 1, \\dots, n\n$$\n\\item Subtraction\n$$\nc_i = (a_i - b_i) \\% q, \\text{ for } i = 1, \\dots, n\n$$\n\n\\item Hadamard multiplication\n$$\nc_i = (a_i * b_i) \\% q, \\text{ for } i = 1, \\dots, n\n$$\n\n\\end{itemize}\n\nFor simplicity, we express these operations by using a super-operator $\\oplus$ as below:\n\n\\begin{figure}[H]\n\\centering\n\\includegraphics[width=0.5\\columnwidth]{operator.pdf}\n\\caption{Element-wise operations $\\vec{c} = \\vec{a} \\oplus \\vec{b}$}\n\\label{fig:operator}\n\\end{figure}\n\nWe accelerate these operations in two ways: horizontal and vertical vectorizations. Note that the number of operations performed in parallel depends on bit-size of the elements and the bit-size of the vector registers. For example, if elements are 32-bit integers and registers are 128-bit wide, then there are 128/32 = 4 operations that can be performed in parallel.\n\nWithout loss of generality, we assume that 4 element-wise operations can be performed in parallel.\n\n\\subsubsection{Horizontal vectorization}\n\nEach vector is defined as an $n$-length array of integers. Four operations applied on four consecutive elements of $\\vec{a}$ and $\\vec{b}$ are performed in parallel. Therefore,  operations on $\\vec{a}$ and $\\vec{b}$ corresponds to $\\frac{n}{4}$ vector operations.\n\n\\begin{figure}[!ht]\n\\centering\n\\includegraphics[width=0.5\\columnwidth]{vec_horizontal.pdf}\n\\caption{Horizontal vectorization}\n\\label{fig:vec_horizontal}\n\\end{figure}\n\n\n\\subsubsection{Vertical vectorization}\n\n\\begin{figure}[!ht]\n\\centering\n\\includegraphics[width=0.5\\columnwidth]{vec_buffers.pdf}\n\\caption{Vector of buffers}\n\\label{fig:vec_buffers}\n\\end{figure}\n\n\\begin{figure*}[!ht]\n\\includegraphics[width=\\textwidth]{vec_vertical.pdf}\n\\caption{Vertical vectorization}\n\\label{fig:vec_vertical}\n\\end{figure*}\n\nEach vector is defined as an $n$-length array of buffers. Each element of these vectors is a buffer composed of  integers, see Figure \\ref{fig:vec_buffers}.\n\nAn operation $c_i = a_i \\oplus b_i$ is equivalent to $s$ operations performed on $s$ elements each of $a_i$ and $b_i$. \nWe accelerate operations performed on each pair of buffers $a_i$ and $b_i$,  i.e.\\ in vertical way as shown in Figure \\ref{fig:vec_vertical}. Four operations applied on four consecutive elements of $a_i$ and $b_i$ are performed in parallel. Therefore, $s$ operations on $a_i$ and $b_i$ corresponds to $\\frac{s}{4}$ vector operations.\n\n\\subsection{Vectorized modular operations in $\\gf{q}$ where $q$ is a Fermat number}\n\nIn the previous section, we described the two methods to transform element-wise operations to packed vector operations. Each vector operation performs several element-wise operations in parallel. In this section, we describe how the parallel operations are performed on packed vectors.\n\nNote that we focus on vectorizing modular arithmetic of finite field $\\gf{q}$ where $q=2^{2^w}+1$, a Fermat number.\nThis case is very interesting since it allows performing multiplicative FFT of low computational complexity (see the 1st row of Table \\ref{tab:compare}) \\cite{fnt_lacan}\n\nLet $\\vec{q}$ denote a packed vector whose elements are $q$.\nLet $\\vec{h}$ denote a packed vector whose elements are $q-1$.\nLet $\\vec{u}, \\vec{v}$ denote two input packed vectors. \n\nLet $vector_<operation>(\\vec{u}, \\vec{v})$ denote an instruction that applies an operation on two input packed vectors $\\vec{u}, \\vec{v}$.\n\n\\begin{itemize}\n\\item \\texttt{vector\\_add}$(\\vec{u}, \\vec{v})$ does element-wise addition\n\\item \\texttt{vector\\_sub}$(\\vec{u}, \\vec{v})$ does element-wise subtraction\n\\item \\texttt{vector\\_mullo}$(\\vec{u}, \\vec{v})$ does element-wise multiplication\n\\item \\texttt{vector\\_or}$(\\vec{u}, \\vec{v})$ compute bitwise OR operation\n\\item \\texttt{vector\\_and}$(\\vec{u}, \\vec{v})$ compute bitwise AND operation\n\\item \\texttt{vector\\_andnot}$(\\vec{u}, \\vec{v})$ compute bitwise NOT of $\\vec{u}$ then AND with $\\vec{v}$\n\\item \\texttt{vector\\_cmpgt}$(\\vec{u}, \\vec{v})$ returns $((u_i > v_i) ? 1 : 0, i=1, \\dots, n)$\n\\item \\texttt{vector\\_cmpeq}$(\\vec{u}, \\vec{v})$ returns $((u_i == v_i) ? 1 : 0, i=1, \\dots, n)$\n\\item \\texttt{vector\\_rshift}$(\\vec{u})$ returns $(x[i] \\gg m, i=1, \\dots, n)$\n\\end{itemize}\n\n\\subsubsection{Addition}\n\nThe pseudocode of addition is as below. This algorithm works as $0 \\leq u_i + v_i < 2q$, hence\n\\begin{equation}\nu_i + v_i = \n\\begin{cases}\n\tu_i + v_i, & \\text{if}\\ u_i + v_i < q \\\\\n\tu_i + v_i - q, & \\text{otherwise}\n\\end{cases}\n\\end{equation}\n\n\\begin{algorithm}[]\n \\KwData{two vectors $\\vec{u}, \\vec{v}$}\n \\KwResult{Element-wise addition modulo $q$ of $\\vec{u}, \\vec{v}$}\n \\tcc{compute element-wise addition}\n $\\vec{r} := \\texttt{vector\\_add}(\\vec{u}, \\vec{v})$\\;\n \\tcc{subtract to $q$}\n $\\vec{m} := \\texttt{vector\\_sub}(\\vec{r}, \\vec{q})$\\;\n \\tcc{If $r_i \\ge q $, result is $m_i$. Otherwise, i.e. $r_i < q$, result is $r_i$}\n \\KwRet{$\\texttt{vector\\_min}(\\vec{r}, \\vec{m})$}\n \\caption{Addition}\n\\end{algorithm}\n\n\\subsubsection{Subtraction}\nThe pseudocode of subtraction is as below. This algorithm works as \n\\begin{equation}\nu_i - v_i = \n\\begin{cases}\n\tu_i - v_i, & \\text{if}\\ u_i \\geq v_i \\\\\n\tq + u_i - v_i, & \\text{otherwise}\n\\end{cases}\n\\end{equation}\n\n\\begin{algorithm}[]\n \\KwData{two vectors $\\vec{u}, \\vec{v}$}\n \\KwResult{Element-wise subtraction modulo $q$ of $\\vec{u}, \\vec{v}$}\n \\tcc{compute element-wise subtraction}\n $\\vec{r} := \\texttt{vector\\_sub}(\\vec{u}, \\vec{v})$\\;\n \\tcc{add by $q$}\n $\\vec{m} := \\texttt{vector\\_add}(\\vec{r}, \\vec{q})$\\;\n \\tcc{If $r_i \\ge 0 $, result is $r_i$. Otherwise, i.e. $r_i < 0$, result is $m_i$}\n \\KwRet{$\\texttt{vector\\_min}(\\vec{r}, \\vec{m})$}\n \\caption{Subtraction}\n\\end{algorithm}\n\n\\subsubsection{Hadamard multiplication}\n\nNote, we need to check and to perform extra operations for the case both elements $u_i, v_i$ are equal to $(q-1)$. However, this case occurs with a low probability. Hence, we implement two multiplication operations:\n\\begin{itemize}\n\t\\item Simple multiplication of $u, v$ whose pair elements  $u_i, v_i$ are not both equal to $(q-1)$.\n\t\\item General multiplication of $u, v$ where the special case will be handled.\n\\end{itemize}\n\nObviously the simple multiplication is faster than the general multiplication. And it?s useful in performing FFT techniques in which a term of multiplications (twiddle factors) is generally known at compile-time. \n\nThe general multiplication consists in two steps:\n\\begin{itemize}\n\\item Step 1: compute element-wise multiplication.\n\t\\texttt{vector\\_mullo}$(\\vec{u}, \\vec{v})$ does element-wise multiplication. We should handle the overflow case where\n\t\\begin{itemize}\n\t\t\\item $u_i = v_i = (q-1)$\n\t\t\\item bit-size of elements smaller than $2^{w+1}$\n\t\\end{itemize}\n\tIndeed, $u_i * v_i = 2^{2^{w+1}}$ is out-of-range of defined integer for elements.\n\tNote that in the overflow case the product result is one as $(u_i * v_i) \\% q = (q-1)^2 \\% q = 1$.\n\\item Step 2: perform a modulo on the multiplication result.\n\\end{itemize}\nLet $r := (u[i]* v[i])$. Let $r_{\\text{hi}}$ and $r_{\\text{lo}}$ denote the high and low $2^w$-bit values of $r$.\nWe express $r$ in the following way thanks to $q = 2^{2^{w} + 1}$\n\n\\begin{equation}\n\\begin{split}\nr &= r_{\\text{hi}} * (q-1) + r_{\\text{lo}} \\\\\n  &= r_{\\text{hi}} * q + (r_{\\text{lo}} - r_{\\text{hi}}) \\\\\n\\Rightarrow r \\% q &= (r_{\\text{lo}} - r_{\\text{hi}}) \\% q\n\\end{split}\n\\end{equation}\n\n\\begin{algorithm}[]\n \\KwData{two vectors $\\vec{u}, \\vec{v}$ whose elements $u_i, v_i$ are not both equal to $(q-1)$}\n \\KwResult{$\\texttt{simp\\_mul}(\\vec{u}, \\vec{v})$: simple multiplication modulo $q$ of $\\vec{u}, \\vec{v}$}\n \\tcc{compute element-wise addition}\n $\\vec{s} := \\texttt{vector\\_mullo}(\\vec{u}, \\vec{v})$\\;\n \\tcc{get low part of $s$}\n $\\vec{l} := \\texttt{vector\\_blend}(0, \\vec{s},0x55)$\\;\n \\tcc{get high part of $s$}\n $\\vec{h} := \\texttt{vector\\_blend}(0, \\texttt{vector\\_rshift}(\\vec{s}, 2), 0x55)$\\;\n  \\tcc{result is returned by subtracting the low part by the high part}\n  \\KwRet{$subtraction(\\vec{l}, \\vec{h})$}\n \\caption{Simple multiplication}\n\\end{algorithm}\n\n\\begin{algorithm}[]\n \\KwData{two vectors $\\vec{u}, \\vec{v}$}\n \\KwResult{General multiplication modulo $q$ of $\\vec{u}, \\vec{v}$}\n \\tcc{perform a simple multiplication}\n $\\vec{s} := \\texttt{simp\\_mul}(\\vec{u}, \\vec{v})$\\;\n \\tcc{create a mask checking whether both of elements $u_i, v_i$ are equal to $q-1$}\n $\\vec{m} := \\texttt{vector\\_and}(\\texttt{vector\\_cmpeq}(u, h), \\texttt{vector\\_cmpeq}(v, h))$\\;\n \\tcc{return simple multiplication if no pair of elements $u_i, v_i$ are equal to $q-1$}\n  \\lIf{$\\texttt{is\\_zero}(\\vec{m})$} { \\Return $\\vec{s}$ }\n \\tcc{create a vector whose element is 1 according to the mask, otherwise zero}\n  $\\vec{d} := \\texttt{vector\\_and}(1, \\vec{m})$\\;\n \\tcc{set specified element $s_i=1$ for $u_i= v_i=q-1$ and return it}\n \\KwRet{$\\texttt{vector\\_or}(\\vec{s}, \\vec{d})$}\n \\caption{General multiplication}\n\\end{algorithm}\n\n\\subsection{Testing}\n\nThe QuadIron library contains a test suite (to ensure correctness) and a benchmark suite (to measure  performance).\nThese suites are integrated in our continuous integration system and run regularly, allowing early detection of performance regressions and bugs.\n\n\\subsection{Documentation}\n\nThe library comes with a Doxygen-generated documentation that associates the implementation with corresponding formulas and references.\n\n\\subsection{Contribution process}\n\nThe implementation is open source (licensed under the 3-Clause BSD License) and open to external contributions. The code can be found on Github, on the scality/quadiron repository.\n\n%\\href{https://github.com/scality/quadiron}{quadiron repository}.\n\n\\section{Performance}\n\nEncoding performance is expressed by the encoding speed metric that is the ratio of encoded data size to encoding time.\n\nIn our measurements, for systematic codes whose encoding performs a matrix multiplication, the encoding speed is given by:\n\n\\begin{equation}\\label{eq:enc_metric_def_sys}\n\\text{Encoding speed} =  \\frac{ n - k }{ k } \\times  \\frac{ \\text{file size}  }{ \\text{encoding time} }\n\\end{equation}\n\nFor other codes, i.e. FFT-based codes, the encoding speed is given by:\n\n\\begin{equation}\\label{eq:enc_metric_def}\n\\text{Encoding speed} =  \\frac{ n }{ k } \\times  \\frac{ \\text{file size}  }{ \\text{encoding time} }\n\\end{equation}\n\nWe use the two different formulas that expresses the computational cost of the corresponding encoder.\n\nDecoding performance is expressed by the decoding speed metric that is the ratio of information data size to decoding time, i.e.\n\n\\begin{equation}\\label{eq:dec_metric_def}\n\\text{Decoding speed} =  \\frac{ \\text{file size}  }{ \\text{decoding time} }\n\\end{equation}\n\nSimulated files are composed of $k$ fragments each of a fixed  $50$-KiB size. Encoding speed is therefore linear to $\\frac{n}{\\text{encoding time}}$. With our optimization resulting in an encoding complexity of $\\bigo{\\fftl \\log{k}}$, the encoding speed is thus linear to $\\frac{1}{\\log{k}}$:\n\\begin{equation}\\label{eq:enc_metric_on_k}\n\\text{Encoding speed} \\sim  \\frac{ 1 }{ \\log{k} }\n\\end{equation}\nWe measured performance of RS codes $\\ec{n}{k}$ over $\\gf{2^{2^4}+1}$ on a Intel Core i5 processor rated at 2.7 GHz, running Mac OS X v.10.12.5 with 64-bit compilation, L2 cache (per core) of 256 KB and L3 cache of 3 MB. All tests were on a single core.\n% * <wabernat@sonic.net> 2018-03-02T20:12:27.248Z:\n% \n% > operating at 2.7 GHz \n% I added \"operating at\" You need to say either \"operating at 2.7 GHZ\" (meaning we tested or otherwise verified the clock speed) or \"rated at 2.7 GHZ\" (meaning \"that's what it said on the box.\")\n% \n% ^.\n\n\\subsection{Vertical vs. horizontal vectorizations}\n\nWe have two methods of vectorizations as described in section \\ref{sec:vectorization}. Theoretically, the two optimization methods result in similar improvements. However, in practice  the vertical vectorization enhances significantly the performance as it benefits from the cache memory.\n\nWe measure encoding performance of RS($k=8, n=128$) and RS($k=8, n=1024$) by using the two methods. With horizontal vectorization using 128-bit vector, encoding speed of the two codes are  roughly 90 MiB/s and 99 MiB/s. These encoding speeds can be improved significantly by using vertical vectorization using also a 128-bit vector. The packet size $s$, i.e.\\ number of elements in each buffers, impact on the encoding speed is shown in Figure \\ref{fig:fnt_vertical_vec_pkt_size}. By choosing a \"good\" packet size, e.g. $s=1024$, these RS codes can be encoded at very high speeds, such as 1424 MiB/s and 1294 MiB/s.\n\nIn both curves of figure \\ref{fig:fnt_vertical_vec_pkt_size} there are three parts. The first part that increases quickly for $s$ from 16 to 256 represents the advantages of L2 cache on small size. The second part on larger packet sizes corresponds to the use of the L3 cache. Finally, when the packet size is too large to fit into the L3 cache, the performance decreases dramatically.\n\n\\begin{figure}[!ht]\n\\centering\n\\includegraphics[width=0.7\\columnwidth]{fnt_vertical_vec_pkt_size.pdf}\n\\caption{Vertical vectorization: impact of packet size $s$ on encoding speed of RS codes over $\\gf{2^{2^4}+1}$: RS($k=8, n=128$) and RS($k=8, n=1024$).}\n\\label{fig:fnt_vertical_vec_pkt_size}\n\\end{figure}\n\n\n\\subsection{Impact of data length $k$}\nMindful of hyper-fragmentation, we measured the following parameters:\n\n\\begin{itemize}\n\\item $n \\in \\left\\{ 256, 1024, 2048 \\right\\}$\n\\item $k \\in \\left\\{ 8, 16, 32 \\right\\}$\n\\end{itemize}\n\nFigure \\ref{fig:fnt_k_n} shows the encoding speed for the three cases of code length $n$ over different number of data fragments $k$. Each curve represents the encoding speed for a given $n$. We observe that for each code length $n$ the speed is linear to $\\frac{1}{\\log{k}}$. The gap between the curves shows that the advantages of cache memory is more important for short code length than long ones. For short code length, encoding process can benefit from the different cache memories L2 and L3, while long code lengths can only exploit the L3 cache.\n% * <wabernat@sonic.net> 2018-03-02T20:19:37.872Z:\n% \n% Is there a unit? \n% \n% ^.\n\\begin{figure}[!ht]\n\\centering\n\\includegraphics[width=0.7\\columnwidth]{fnt_k_n.pdf}\n\\caption{Encoding speed of RS codes over $\\gf{2^{2^4}+1}$. Each curve represents a fixed $n$.}\n\\label{fig:fnt_k_n}\n\\end{figure}\n\nFigure \\ref{fig:dec_fnt_k_n} shows the decoding speed.\n\n\\begin{figure}[!ht]\n\\centering\n\\includegraphics[width=0.7\\columnwidth]{dec_fnt_k_n.pdf}\n\\caption{Decoding speed of RS codes over $\\gf{2^{2^4}+1}$. Each curve represents a fixed $n$.}\n\\label{fig:dec_fnt_k_n}\n\\end{figure}\n\n\\section{Applications}\n\n\\subsection{Decentralized Storage over the Internet}\n\nAs drive density continues to be driven higher in keeping with Moore's Law, the price of storage continues to fall. This makes extra data copies cheaper. For example, generating and spreading hundreds of fragments from a file makes it possible to reconstruct the data while having only a fraction of the total data available. In this context, it is possible and interesting to develop a reliable decentralized cloud storage system that allows to exploit unused storage on the heterogeneous edge nodes (smartphones, laptops, servers, \\dots) of the network (see figure \\ref{fig:network}).\n\n\\begin{figure}[!h]\n\\centering\n\\includegraphics[width=0.7\\columnwidth]{network.png}\n\\caption{A decentralized storage system based on heterogeneous nodes}\n\\label{fig:network}\n\\end{figure}\n\nWe have to compensate the unreliability of the underlying devices (which can go off-line anytime for any duration of time) if we want to have a reliable and resilient storage. Erasure coding is an excellent solution to increase durability while keeping the storage overhead low. Existing practical systems, such as Storj, are going toward encoding schemes like $\\ec{30}{10}$, $\\ec{60}{20}$ or $\\ec{120}{40}$.\n\nThe systematic property is interesting but not absolutely necessary in a decentralized storage application: Indeed a decentralized storage software may choose to place the plain text data fragments on the peers having the best quality of service. But in an environment like the Internet where it is difficult to evaluate the quality of service of peers, or when the quality of service is very variable, the probability of reaching a peer that contains a plain text data fragment is getting lower as k gets bigger (see figure \\ref{fig:systematic}). Therefore the systematic property becomes useless. Moreover non-systematic code are rate insensitive.\n\n\\begin{figure}[!h]\n\\centering\n\\includegraphics[width=0.7\\columnwidth]{systematic.png}\n\\caption{Evolution of the reachability of the whole set of data fragments in function of k}\n\\label{fig:systematic}\n\\end{figure}\n\nThe adaptive rate property may also be useful in a decentralized storage application because it is not practically possible to delete and rewrite the erasure code fragments which are already in place. However if the initial durability chosen is already very high, the need for re-dimensioning the code is not critical.\n\nThe repair bandwidth is indeed a problem for RS codes but it can be mitigated in multiple ways in a decentralized storage scenario:\n\\begin{itemize}\n\\item Generally we cut a file in sub-blocks of fixed size called stripes. Since the stripes are spread in a very high number of peers, the loss of a peer will affect only one stripe with a very high probability.\n\\item It is possible to detect a missing fragment at the time of the read and repair it immediately after (read-repair).\n\\item Because of the chosen very high durability, a pro-active repair mechanism (called scrubbing) is not absolutely critical and can be scheduled rarely. \n\\end{itemize}\n\nFinally one can argue that both the systematic property and the optimization of the repair bandwidth at the level of a stripe is still advantageous in order to support get\\_range() operations: the ability to read a portion of a stripe without decoding or by minimizing the decoding. The get\\_range() properties might indeed be of interest in the case of a local distributed file system or a local big data cluster, but not in a decentralized storage system which targets primarily the cloud storage use case (for archival purpose) where people generally wants the files stored and retrieved in their totality.\n\nWe do compare our erasure codes with other libraries (ISA-L, Leopard, Wirehair) for k up to 1024. The ISA-L library \\cite{isal} is a performance-oriented open-source library developed by Intel that implements a systematic RS code defined over $\\gf{2^8}$ (which limits the code length to at most 255). Leopard \\cite{leopard} is a performance-oriented RS codes using additive FFT techniques. Wirehair \\cite{wirehair} is a performance-oriented hybrid LDPC library that implements a systematic code defined over $\\gf{2^8}$ that also leverage SIMD instructions.\n\nFigures \\ref{fig:comp_enc_rate_1_4}, \\ref{fig:comp_enc_rate_1_3}, \\ref{fig:comp_enc_rate_1_2}, \\ref{fig:comp_enc_rate_2_3} show encoding speeds of these codes for different coding rates 1/4, 1/3, 1/2 and 2/3 respectively. We observe that for small $k$, ISA-L codes are very good. But for $k > 24$, our codes outperform ISA-L codes thanks to FFT operations. \n%Figure \\ref{fig:isal_vs_fnt_vs_leo_enc} shows encoding speeds of these codes for different number of data fragments. We observe that for small $k$, ISA-L codes are very good. But for $k > 24$, our codes outperform ISA-L codes thanks to FFT operations. \n\nLDPC encoding speed worsen as $k$ grows. Note the graphs shows the pure decoding speed and does not show the additional time needed to retrieve the additional fragments due to the overhead (see \\cite{plank_ldpc} for a detailed study on this topic).\n\nWirehair is also less good for higher code rates.\n\nFigures \\ref{fig:comp_dec_rate_1_4}, \\ref{fig:comp_dec_rate_1_3}, \\ref{fig:comp_dec_rate_1_2}, \\ref{fig:comp_dec_rate_2_3} show decoding speeds of these codes for different coding rates 1/4, 1/3, 1/2 and 2/3 respectively. We observe that average decoding time of FNT codes is about only 3.5 times longer than encoding time, compared to 8 times mentioned in \\cite{fnt_lacan}. However our FNT decode speed is still slow compared to others. We plan to implement the approach defined in \\cite{fnt_ida}.\n\n\\begin{figure}[!ht]\n\\centering\n\\includegraphics[width=0.7\\columnwidth]{Enc_Rate1-4.pdf}\n\\caption{Encoding speed of RS codes of rate 1/4: comparison our FNT codes vs. ISA-L vs. Leopard vs. WireHair}\n\\label{fig:comp_enc_rate_1_4}\n\\end{figure}\n\n\\begin{figure}[!ht]\n\\centering\n\\includegraphics[width=0.7\\columnwidth]{Enc_Rate1-3.pdf}\n\\caption{Encoding speed of RS codes of rate 1/3: comparison our FNT codes vs. ISA-L vs. Leopard vs. WireHair}\n\\label{fig:comp_enc_rate_1_3}\n\\end{figure}\n\n\\begin{figure}[!ht]\n\\centering\n\\includegraphics[width=0.7\\columnwidth]{Enc_Rate1-2.pdf}\n\\caption{Encoding speed of RS codes of rate 1/2: comparison our FNT codes vs. ISA-L vs. Leopard vs. WireHair}\n\\label{fig:comp_enc_rate_1_2}\n\\end{figure}\n\n\\begin{figure}[!ht]\n\\centering\n\\includegraphics[width=0.7\\columnwidth]{Enc_Rate2-3.pdf}\n\\caption{Encoding speed of RS codes of rate 2/3: comparison our FNT codes vs. ISA-L vs. Leopard vs. WireHair}\n\\label{fig:comp_enc_rate_2_3}\n\\end{figure}\n\n\\begin{figure}[!ht]\n\\centering\n\\includegraphics[width=0.7\\columnwidth]{Dec_Rate1-4.pdf}\n\\caption{Decoding speed of RS codes of rate 1/4: comparison our FNT codes vs. ISA-L vs. Leopard vs. WireHair}\n\\label{fig:comp_dec_rate_1_4}\n\\end{figure}\n\n\\begin{figure}[!ht]\n\\centering\n\\includegraphics[width=0.7\\columnwidth]{Dec_Rate1-3.pdf}\n\\caption{Decoding speed of RS codes of rate 1/3: comparison our FNT codes vs. ISA-L vs. Leopard vs. WireHair}\n\\label{fig:comp_dec_rate_1_3}\n\\end{figure}\n\n\\begin{figure}[!ht]\n\\centering\n\\includegraphics[width=0.7\\columnwidth]{Dec_Rate1-2.pdf}\n\\caption{Decoding speed of RS codes of rate 1/2: comparison our FNT codes vs. ISA-L vs. Leopard vs. WireHair}\n\\label{fig:comp_dec_rate_1_2}\n\\end{figure}\n\n\\begin{figure}[!ht]\n\\centering\n\\includegraphics[width=0.7\\columnwidth]{Dec_Rate2-3.pdf}\n\\caption{Decoding speed of RS codes of rate 2/3: comparison our FNT codes vs. ISA-L vs. Leopard vs. WireHair}\n\\label{fig:comp_dec_rate_2_3}\n\\end{figure}\n\nAs wee see in practical decentralized storage applications like Storj the typical code rate is 1/3 or 1/4 which means relatively high durability and relatively low number of fragments to retrieve which is good for latency. LDPC such as Wirehair show to be very good, although non MDS, we show that FNT has a relatively good performance but is still inferior to LDPC, we think we can improve FNT perf in improving the FFT method (we currently implement a bit-reverse method that requires copying data and we could replace by other more efficient methods). We also think that accelerating additive FFT such as what has been done in Leopard \\cite{leopard} is very promising.]\n\nAnother interesting property for this application is the confidentiality of the erasure code, even though the client decides to encrypt or not the files beforehand, using a non-systematic FNT augments the security.\n\n\\subsection{Real-Time Video Encoding High-Quality Streaming}\n\nThere are many types of video streams. For high quality ingress of a broadcast system, the master stream is typically broken up into pieces and encoded to lower quality with a few seconds of delay.\n\nThose real-time video high quality streams with 30\\% interleaving (code rate 2/3) have many pieces, and are generally encoded using $\\bigo{N^2}$ streaming convolutional codes e.g. like CauchyCaterpillar \\cite{cauchycaterpillar} which operates on  $\\gf{2^8}$ and is limited to 2MB/s. To go faster the technique generally used is interleaving block codes (which is how video FEC is usually done \\cite{al_fec}). The overhead from using something fast like a XOR based LDPC on $\\gf{2^2}$ is highly inefficient. Our MDS NTT approach is much better because we have no overhead and we can keep up with the speed.\n\nIn this type of application there is a need for a systematic code. As wee see in \\cite{leopard}, \\cite{fft_add_chung} and \\cite{fnt_lacan} we can implement systematic NTT based codes with lesser but similar performance.\n\n\\section{Conclusion}\n\nNTT codes offer superior encoding performance compared to matrix-based RS erasure codes for applications requiring $n \\gtrapprox 24$ symbols, and are simpler than LDPC codes, while supporting all the desirable properties: Fast, MDS, systematic or non-systematic, confidential (for systematic codes). As we have seen the optimization of repair bandwidth as offered by LRC codes is not critical for a decentralized cloud storage application. The most important property for us remains the MDS property as a rock solid contract: being sure than if k fragments are available then the data is recoverable. Also, as we seen, FNT aka multiplicative FFT codes offer not necessarily always faster but more predictive performance than additive FFT codes for various $n$. \n\nThose codes may have other potential applications such as high-quality video streaming but a lot of experiments and analysis have yet to be conducted.\n\n\\section{Future Work}\nThe next steps for the QuadIron library are in order of priority:\n\\begin{itemize}\n\\item Optimize the multiplicative FFT decoding, which is for now relatively slow (\\cite{fnt_ida} and \\cite{gao_decode} has shown a way to optimize). It can be possible for special values of k and m, e.g. $k \\% m = 0$ or $m \\% k = 0$.\n\\item Optimize additive FFTs (for now we don't have any HW acceleration).\n\\item Implement additive FFT based systematic codes.\n\\item Design and implement NTT based adaptive codes for multiplicative FFTs.\n\\item Design and implement NTT based adaptive codes for additive FFTs.\n\\item Implement Frobenius multiplicative FFT \\cite{frobenius_fft}.\n\\item Implement Frobenius additive FFT \\cite{frob_additive}.\n\\end{itemize}\n\n\\bibliographystyle{unsrt}\n\\bibliography{bib}\n\n\n\\section*{Authors}\n\n\\begin{description}\n\n\\item[Vianney Rancurel] is a computer professional with more than 20 years of experience designing and developing computer products. He currently leads the Scality research team which is responsible for feasibility studies, prototypes and patents/publications. Previously he worked in the messaging and telco industries on both software and hardware technologies at Bizanga, Borea Technologies, and Freescale. He was also a professor at the EPITA engineering school and was responsible for its System Research Lab. His specialties are system software programming, distributed systems, embedded systems and security. Vianney has a degree of Systems \\& Networks Engineering from EPITA.\n\n% if you will not have a photo at all:\n\\item[Lam Pham-Sy] is a research engineer working on information theory and computer science. His main research focuses on different families of forward erasure correcting codes such as Reed-Solomon codes, Low-Density Parity-Check codes, Locally Repairable codes etc. Their application covers from digital communication to data storage. He did his PhD program in a collaboration between CEA-Leti and Eutelsat S.A. on the subject of forward erasure codes for satellite communications. Afterwards, he continued his researches at ETIS laboratory and at Orange Labs. Currently he works at Scality S.A. as a research engineer whose research topics include application of erasure codes in distributed storage systems, finite field arithmetics.\n\n\\item[Sylvain Laperche] is a code craftsman. With a background in biotech engineering,he learnt how to hack bacteria before learning how to hack a computer. That changed when it studied bioinformatics, and since then he honed and applied its skill on a wide set of problematics: genome sequencing, complex embedded systems, climate modelling at European scale, mass-scale geolocation for telco industries. Its steps led him to work on distributed storage systems and he currently works as an R\\&D engineer at Scality.\nSylvain Laperche has an Engineer's degree in Hardware, Circuit Design and Embedded Systems from ISIMA.\n\n\\end{description}\n\n\\end{document}\n\n\n", "meta": {"hexsha": "99c730dff77d1c2e55a9d42074f8cdd0370eea35", "size": 51480, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/quadiron.tex", "max_stars_repo_name": "scality/quadiron", "max_stars_repo_head_hexsha": "c062e908ba39a3989acad3234044ec11a5891cbf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2018-09-20T05:42:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T14:53:04.000Z", "max_issues_repo_path": "paper/quadiron.tex", "max_issues_repo_name": "scality/quadiron", "max_issues_repo_head_hexsha": "c062e908ba39a3989acad3234044ec11a5891cbf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 67, "max_issues_repo_issues_event_min_datetime": "2018-07-26T14:44:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-16T16:58:23.000Z", "max_forks_repo_path": "paper/quadiron.tex", "max_forks_repo_name": "scality/quadiron", "max_forks_repo_head_hexsha": "c062e908ba39a3989acad3234044ec11a5891cbf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-10-07T00:41:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T19:25:50.000Z", "avg_line_length": 59.5144508671, "max_line_length": 1520, "alphanum_fraction": 0.7387917638, "num_tokens": 14883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.3434701827220722}}
{"text": "\\documentclass[12pt]{article}\n\\usepackage{amsmath}\n\\usepackage{graphicx}\n\\usepackage{hyperref}\n\\usepackage{xcolor}\n\\usepackage{subcaption}\n\\usepackage{siunitx}\n\n\\addtolength{\\oddsidemargin}{-.875in}\n\\addtolength{\\evensidemargin}{-.875in}\n\\addtolength{\\textwidth}{1.75in}\n\n\\addtolength{\\topmargin}{-.875in}\n\\addtolength{\\textheight}{1.75in}\n\n\\title{Model Predictive Control}\n\\date{2020}\n\\author{sentry5588, MIT License}\n\n\\begin{document}\n\\pagecolor{lightgray}\n\\maketitle\n\\section{Introduction}\nThis note documents the Model Predictive Control (MPC) method for the two\nwheel balancing robot. Many people has built similar self-balancing robots.\nAlmost all of them uses PID control as the control strategy. For position\nestimation, some uses Kalman filters, and others uses complementary filters.\n\nThe purpose of using MPC in this robot is not trying to invent a new MPC\ntechnique, which usually the case for research papers.\nBut rather I intend to 1) practice MPC and 2) test how well MPC behaves\ncompares to other control schemes.\n\n\\section{Robot Coordinates}\nAs shown in Figure~\\ref{fig_coordinates}, $\\theta_k$ and $\\omega_k$ denotes \nthe angular position at time step $k$, respectively.\nCounter-clockwise rotation is positive. Angular acceleration is denoted\nby $\\dot{\\omega}_k$.\n$u_k$ is the horizontal force\nwith positive to the right. Robot specifications can be found in \nTable~\\ref{tab_robot_specification}\n\n\n\\begin{figure}\n\n\\begin{subfigure}{0.3\\textwidth}\n\\includegraphics[width=\\linewidth]{./figures/coordinates.png}\n\\caption{Robot Coordinates} \\label{fig_coordinates}\n\\end{subfigure}\n\\hspace*{\\fill} % separation between the subfigures\n\\begin{subfigure}{0.3\\textwidth}\n\\includegraphics[width=\\linewidth]{./figures/one_d_rotation.png}\n\\caption{1D Rotation} \\label{fig_one_d_rotation}\n\\end{subfigure}\n\\hspace*{\\fill} % separation between the subfigures\n\\begin{subfigure}{0.3\\textwidth}\n\\includegraphics[width=\\linewidth]{./figures/free_body_diagram.png}\n\\caption{1D Free Body Diagram} \\label{fig_1d_free_body_diagram}\n\\end{subfigure}\n\\caption{Two Wheel Balancing Robot} \\label{fig_robots}\n\\end{figure}\n\n\n\\begin{table}\n  \\centering\n  \\begin{tabular}{l|c|c}\n    \\hline\n\tSpecification & Notation & Value \\\\ \\hline\n    Center of Gravity (CoG) & $h$ & ?? 0.2 m \\\\ \n\tMass & $m$ & ?? 1.1 kg \\\\ \n\tMoment of Inertia & I & ?? 0.8 \\si{\\kilogram\\cdot\\meter^2} \\\\ \\hline\n  \\end{tabular}\n  \\caption{Robot specification} \n  \\label{tab_robot_specification}\n\\end{table}\n\n\n\\section{Problem Formulation}\nThe model is a 1-input-2-output model.\n\\begin{align}\n\\label{equ_orig_nonlinear_dynamics}\nx_{k+1} & = f(x_k, u_k) \\\\\ny_k & = C(x_k)x_k\n\\end{align}\n\n$x_k=[\\theta_k\\;\\;\\omega_k\\;\\;\\dot{\\omega}_k]^T$ is the system state. \nLinearize Equ~\\ref{equ_orig_nonlinear_dynamics}, we have\n\\begin{align}\nx_{k+1} & = A(x_k)x_k + B(x_k)u_k \\\\\ny_k & = C(x_k)x_k\n\\end{align}\n\nwhere $A(x_k)$ and $B(x_k)$ are Jacobians and given by\n\\begin{align}\nA(x_k) = \\frac{\\partial f}{\\partial x_k},\nB(x_k) = \\frac{\\partial f}{\\partial u_k}\n\\end{align}\n\nFigure~\\ref{fig_1d_free_body_diagram} is the 1-D free body diagram.\nIn the next subsection, I will develop the nonlinear continuous-time\ndynamics.\n\n\\subsection{Nonlinear Continuous-Time Model}\n\\subsubsection{Derived from Newton's 2nd law}\nSumming the forces in figure~\\ref{fig_1d_free_body_diagram} in the horizontal\ndirection we have\n\\begin{align}\nF_x=m\\ddot{p}_x\n\\end{align}\nwhere $p_x$ is the horizontal velocity of the CoG.\nSumming the forces in figure~\\ref{fig_1d_free_body_diagram} in the vertical\ndirection we have\n\\begin{align}\nmg-F_z = m\\ddot{p}_z\n\\label{equ_vertical_newton}\n\\end{align}\nwhere $p_x$ is the horizontal velocity of the CoG.\nSumming the torques in figure~\\ref{fig_1d_free_body_diagram} around the\ncenter of gravity we have\n\\begin{align}\nF_x h\\cos(\\theta) + F_z h\\sin(\\theta) + mg\\cdot 0= \\ddot{\\theta}I\n\\label{equ_rotation_newton}\n\\end{align}\n\\textcolor{blue}{\nThe contact point between the robot and the ground has $0$ vertical velocity.\nIt's vertical velocity is a combination of the rod rotation around \nCoG, $\\dot{\\theta}h\\sin(\\theta)$,\nand vertical velocity of CoG, $\\dot{p}_z$. Therefore\n\\begin{align}\n-\\dot{\\theta}h\\sin(\\theta) + \\dot{p}_z = 0\n\\label{equ_velocity_equation}\n\\end{align}\nTake time derivative of~(\\ref{equ_velocity_equation})\n\\begin{align}\n-\\ddot{\\theta}h\\sin(\\theta) - \\dot{\\theta}^2h\\cos(\\theta) + \\ddot{p}_z = 0\\\\\n\\ddot{p}_z = \\ddot{\\theta}h\\sin(\\theta) + \\dot{\\theta}^2h\\cos(\\theta)\n\\label{equ_ddot_p_z}\n\\end{align}}\nSubstitute $\\ddot{p}_z$ in~(\\ref{equ_vertical_newton}) \nwith~(\\ref{equ_ddot_p_z})\n\\begin{align}\nmg-F_z = m(\\ddot{\\theta}h\\sin(\\theta) + \\dot{\\theta}^2h\\cos(\\theta)) \\\\\nmg-F_z = m\\ddot{\\theta}h\\sin(\\theta) + m\\dot{\\theta}^2h\\cos(\\theta) \\\\\nF_z = mg - m\\ddot{\\theta}h\\sin(\\theta) - m\\dot{\\theta}^2h\\cos(\\theta)\n\\end{align}\nSubstitute $F_z$ with above equation in~(\\ref{equ_rotation_newton})\n\\begin{align}\nF_xh\\cos(\\theta) + (mg - m\\ddot{\\theta}h\\sin(\\theta) \n- m\\dot{\\theta}^2h\\cos(\\theta))h\\sin(\\theta) + mg\\cdot 0= \\ddot{\\theta}I\\\\\nF_xh\\cos(\\theta) + mgh\\sin(\\theta) - m\\ddot{\\theta}h^2\\sin^2(\\theta) \n- m\\dot{\\theta}^2h^2\\cos(\\theta)\\sin(\\theta) = \\ddot{\\theta}I \\\\\n(I+mh^2\\sin^2(\\theta))\\ddot{\\theta}+mh^2\\cos(\\theta)\\sin(\\theta)\\dot{\\theta}^2\n=F_xh\\cos(\\theta) + mgh\\sin(\\theta)\n\\end{align}\n\nSo the dynamics can be written as \n\\begin{align}\nF_x &= m\\ddot{p}_x \\\\\n(I+mh^2\\sin^2(\\theta))\\ddot{\\theta}+mh^2\\cos(\\theta)\\sin(\\theta)\\dot{\\theta}^2\n&= F_xh\\cos(\\theta) + mgh\\sin(\\theta)\n\\label{equ_nonlinear_CT_dynamics}\n\\end{align}\n\n\\textbf{Check dynamics at special points \nfor~(\\ref{equ_nonlinear_CT_dynamics})}\n\nWhen $\\theta=0$, i.e. the vertical up position,\n(\\ref{equ_nonlinear_CT_dynamics}) becomes\n\\begin{align}\nI\\ddot{\\theta} = F_xh\n\\end{align}\nWhen $\\theta=\\pi/2$, i.e. the horizontal position pointing to the left\n(assume single contact point with the ground)\n(\\ref{equ_nonlinear_CT_dynamics}) becomes\n\\begin{align}\n(I+mh^2)\\ddot{\\theta} = mgh\n\\end{align}\nWhen $\\theta=-\\pi/2$, i.e. the horizontal position pointing to the right\n(assume single contact point with the ground)\n(\\ref{equ_nonlinear_CT_dynamics}) becomes\n\\begin{align}\n(I+mh^2)\\ddot{\\theta} = -mgh\n\\end{align}\nWhen $\\theta=\\pi/4$, i.e. the horizontal position pointing to the left\n(assume single contact point with the ground)\n(\\ref{equ_nonlinear_CT_dynamics}) becomes\n\\begin{align}\n(I+\\frac{1}{2}mh^2)\\ddot{\\theta}+\\frac{1}{2}mh^2\\dot{\\theta}^2\n&= \\frac{\\sqrt{2}}{2}F_xh + \\frac{\\sqrt{2}}{2}mgh\n\\end{align}\n\n\\subsubsection{Derived from Lagrangian mechanics}\nThe derivation follows~\\cite{peacock_2007_mit_lagrange}.\nThe Lagrangian is $L=KE-PE$ where $KE$ and $PE$ are the\nkinematic energy and potential energy, respectively.\n$W$ is the virtual work.\nThe equation of motion can be determined by applying\nLagrange mechanics in two generalized coordinate $p_x$ and $\\theta$\n\\begin{align}\n\\label{equ_lagrangian_original}\n\\frac{\\mathrm{d}}{\\mathrm{d}t}\\bigg(\n\\frac{\\partial L}{\\partial \\dot{p}_x}\\bigg)\n-\\frac{\\partial L}{\\partial p_x}=\n\\frac{\\partial W}{\\partial p_x}, \\quad\n\\frac{\\mathrm{d}}{\\mathrm{d}t}\\bigg(\n\\frac{\\partial L}{\\partial \\dot{\\theta}}\\bigg)\n-\\frac{\\partial L}{\\partial \\theta}=\n\\frac{\\partial W}{\\partial \\theta}\n\\end{align}\nThe contact point displacement relative to the center of gravity is\n$h\\theta \\cos(\\theta)$. Therefore the absolute velocity of\nthe contact point is $p_x + h\\theta \\cos(\\theta)$.\nThe kinematic energy, potential energy and virtual work are\n\\begin{align}\nKE = \\frac{1}{2}m\\dot{p}_x^2\n+\\frac{1}{2}I\\dot{\\theta}^2,\\quad\nPE = mgh\\cos(\\theta), \\quad\nW = F_x (p_x+ h\\theta \\cos(\\theta)) + F_x h \\theta \\cos(\\theta)\n= F_x p_x + 2F_x h \\theta \\cos(\\theta)\n\\label{equ_lagrangian_energy_work}\n\\end{align}\nSubstitute~(\\ref{equ_lagrangian_original})\nwith~(\\ref{equ_lagrangian_energy_work}), in $p_x$ direction we have\n\\begin{align}\n\\frac{\\mathrm{d}}{\\mathrm{d}t}\\bigg(\n\\frac{\\partial}{\\partial \\dot{p}_x}\\bigg(\n\\frac{1}{2}m\\dot{p}_x^2 + \\frac{1}{2}I\\dot{\\theta}^2\\bigg)\\bigg) \\quad &\\\\\n-\\frac{\\partial}{\\partial p_x}\\bigg(\n\\frac{1}{2}m\\dot{p}_x^2+\\frac{1}{2}I\\dot{\\theta}^2\n-mgh\\cos(\\theta)\\bigg)=&\n\\frac{\\partial}{\\partial p_x}F_x p_x\n+\\frac{\\partial}{\\partial p_x} 2F_x h \\theta \\cos(\\theta) \\\\\n\\frac{\\mathrm{d}}{\\mathrm{d}t}\n(m\\dot{p}_x + 0)\n-(0+0-0)=&\nF_x + 0\\\\\n\\frac{\\mathrm{d}}{\\mathrm{d}t}\nm\\dot{p}_x = & F_x \\\\\nm\\ddot{p}_x =& F_x\n\\end{align}\nSubstitute~(\\ref{equ_lagrangian_original})\nwith~(\\ref{equ_lagrangian_energy_work}), in $\\theta$ direction we have\n\\begin{align}\n&\\frac{\\mathrm{d}}{\\mathrm{d}t}\\bigg(\n\\frac{\\partial}{\\partial\\dot{\\theta}}\\bigg(\n\\frac{1}{2}m\\dot{p}_x^2+\\frac{1}{2}I\\dot{\\theta}^2\n-mgh\\cos(\\theta)\\bigg)\\bigg)\n-\\frac{\\partial}{\\partial \\theta}\\bigg(\n\\frac{1}{2}m\\dot{p}_x^2+\\frac{1}{2}I\\dot{\\theta}^2\n-mgh\\cos(\\theta)\\bigg)  \\\\\n=&\\frac{\\partial}{\\partial \\theta}F_x p_x\n+\\frac{\\partial}{\\partial \\theta} 2F_x h \\theta \\cos(\\theta) \n\\end{align}\n\\begin{align}\n\\frac{\\mathrm{d}}{\\mathrm{d}t}\n(0+I\\dot{\\theta}-0)\n-(0+0+mgh\\sin(\\theta))=&-2 F_x h\\theta \\sin(\\theta)\n+2F_x h\\cos(\\theta)\\\\\n(0+I\\ddot{\\theta}-0)\n-(0+0+mgh\\sin(\\theta))=& -2 F_x h\\theta \\sin(\\theta)\n+2F_x h\\cos(\\theta) \\\\\nI\\ddot{\\theta}-mgh\\sin(\\theta)=&-2 F_x h\\theta \\sin(\\theta)\n+2F_x h\\cos(\\theta) \\\\\nI\\ddot{\\theta}\n=& 2 F_x h\\cos(\\theta)+mgh\\sin(\\theta)\n-2 F_x h\\theta \\sin(\\theta)\n\\end{align}\n\n\n\\subsection{Model Linearization and discretization}\nI follow~\\cite{zhakatayev_2017_successive_linearize_MPC}\nto linearize and discretize the nonlinear continuous-time dynamics\nin~\\cite{???}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\bibliographystyle{apalike}\n\\bibliography{MPC}{}\n\n\n\\end{document}\n%\n%\n%\n%\n%\n%\n%\n%\n%\n%\n%\n%\n%\n%\n%\n%\n", "meta": {"hexsha": "88e187a2c48201f6917b3ab37ad7a56fc9ad3311", "size": 9602, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "control/tex/MPC.tex", "max_stars_repo_name": "sentry5588/two_wheeler", "max_stars_repo_head_hexsha": "ba62de060af3bb47052e21157bb440ba55d3a7a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-04-18T23:29:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-30T23:05:04.000Z", "max_issues_repo_path": "control/tex/MPC.tex", "max_issues_repo_name": "sentry5588/two_wheeler", "max_issues_repo_head_hexsha": "ba62de060af3bb47052e21157bb440ba55d3a7a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-04-04T14:43:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-11T19:27:44.000Z", "max_forks_repo_path": "control/tex/MPC.tex", "max_forks_repo_name": "sentry5588/two_wheeler", "max_forks_repo_head_hexsha": "ba62de060af3bb47052e21157bb440ba55d3a7a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.32996633, "max_line_length": 78, "alphanum_fraction": 0.7114142887, "num_tokens": 3381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.34347018272207214}}
{"text": "\\section{Wavelet transforms}\n\n\\begin{frame} \\frametitle{Wavelet transforms for EXAFS analysis}\n\n\\begin{cenpage}{105mm}\n\n  The Fourier transform is fundamental to understanding EXAFS.\n\n  Wavelet transforms extend Fourier transforms, mixing $k$ and $R$.\n\n  They have been used by a handful of groups.\n\n\n\n\\end{cenpage}\n\n\\begin{columns}\n  \\begin{column}[T]{70mm}\n\n    {\\onslide+<2->  \\includegraphics[width=70mm]{figs/wavelets/wavelet_composite_mag}  }\n\n  \\end{column}\n\n\\begin{column}[T]{52mm}\n\n  {\\onslide+<2-> \\includegraphics[width=52mm]{figs/wavelets/wavelet_surface} }\n\n  \\vmm\n\n  Wavelet transform for FeO data.\n\n  \\vmm \\vmm\n\n{\\hspace{-15mm}{\n    {\\onslide+<2->\n    \\begin{minipage}{60mm}\n      {\\tiny{\n          This is using the ``Continuous Cauchy'' wavelet transform, as\n          described by Munoz, Argoul, and Farges, {\\emph{Am Mineralogist}},\n          2003\n\n          Others (Funke {\\emph{et al}}, Penfold, {\\emph{et al}}) have used Morlet\n          wavelets.\n        }}\n  \\end{minipage}\n}\n}}\n\n\n  \\end{column}\n\n\\end{columns}\n\\end{frame}\n", "meta": {"hexsha": "ceffb80be1edf6506d9af23e757faa821e12d219", "size": 1047, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "slides/wavelets.tex", "max_stars_repo_name": "newville/xafsfun", "max_stars_repo_head_hexsha": "525b0b8fb6ec61396dc7dd2950a3e2a3ab6c17d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "slides/wavelets.tex", "max_issues_repo_name": "newville/xafsfun", "max_issues_repo_head_hexsha": "525b0b8fb6ec61396dc7dd2950a3e2a3ab6c17d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slides/wavelets.tex", "max_forks_repo_name": "newville/xafsfun", "max_forks_repo_head_hexsha": "525b0b8fb6ec61396dc7dd2950a3e2a3ab6c17d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.3888888889, "max_line_length": 88, "alphanum_fraction": 0.6561604585, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.34347018272207214}}
{"text": "\\section{Fl---The Meta Language of Voss}\n\nIn this section\\footnote{This section is to a large extent modeled\nafter Chapter 1 in the HOL System DESCRIPTION from Cambridge University.\nIn particular, many of the early examples are taken from this source.}\nwe provide an introduction to the functional language FL.\n\nSimilar to many theorem provers (e.g., the HOL%\n\\index{HOL}%\n{}\nsystem~\\cite{HOLsystem,HOLbook}) the\nVoss command language for the verification system is a general\npurpose programming language%\n\\index{programming language}%\n{}.\nIn fact, the FL language shows a strong degree of influence from\nthe version of ML%\n\\index{ML}%\n{} used in the HOL-88%\n\\index{HOL-88}%\n{} system.\nHowever, there are several differences:  many syntactic but some\nmore fundamental.\nIn particular, the functional language used in Voss has lazy evaluation\nsemantics.\nIn other words, no expression is evaluated until it is\nabsolutely needed.\nSimilarly, no expression is evaluated more than once.\nAnother difference is that Boolean functions are first-class\nobjects and can be created, evaluated, compared and printed out.\nFor efficiency reasons these Boolean functions are represented as\nordered binary decision diagrams%\n\\index{ordered binary decision diagrams}%\n{}. \n\nFl is an interactive language.\nAt top-level one can:\n\\begin{enumerate}\n\\item define functions (possibly of arity 0),\n\\item define new concrete types,\n\\item define aliases for types,\n\\item modify the parser, and\n\\item evaluate expressions.\n\\end{enumerate}\nIn this section we introduce the language by several examples.\n\n\\subsection{Invoking FL}\n\nIf the Voss system is installed on your system\nand you have the suitable search path set up, it suffices\nto type \\verb@fl@ to get a stand-alone version of FL. In this manual, we\nhave used Voss 1.8b throughout. In other words, typing \\verb@fl@ yielded:\n\n\\begin{hol}\n% fl\n      /\\verb@\\@\n     /  \\verb@\\@/\\verb@\\@\n /\\verb@\\@ /      \\verb@\\@\n/  Voss 1.8b\\verb@\\@\nVOSS-LIBRARY-DIRECTORY = /isd/local/generic/lib/vosslib\n\n:\n\\end{hol}\nNote that the VOSS-LIBRARY-DIRECTORY%\n\\index{VOSS-LIBRARY-DIRECTORY}%\n{} is installation dependent.\nWe return to this below and in Section~\\ref{vossrc}.\n\nThe fl program can take a number of arguments.\n\\index{command-line arguments}\nIn particular, \n\\begin{description}\n\\item[-d]\nTurn debugging mode%\n\\index{debugging mode}%\n{} on.\nIn this mode a function call trace%\n\\index{call trace}%\n{} will be generated\nwhen a failure that is not caught by an exception handler occurs.\nThis feature is not as useful as in many other languages, but\nis retained for backwards compatibility.\n\\item[-D]\nTurn debugging mode off.\nUnless the DEBUG-ON flag is set in the .vossrc file, the default\nis for debugging mode to be turned off.\n\\item[-f n]\nStart FL by first reading in the content of the file named n.\n\\item[-h]\nA flag that is needed when fl is used as a subroutine in the\nHOL%\n\\index{HOL}%\n{} theorem prover in the HOL-Voss%\n\\index{HOL-Voss}%\n{}\nsystem~\\cite{JoyceSegerDAC,SegerJoyceTwoLevel}.\nThis flag should not be used when FL is used stand-alone.\n\\item[-I dir]\nSet the default search directory%\n\\index{search directory}%\n{} to dir.\n\\item[-s i]\nSet the initial OBDD table size to be $2^i$, where $i$ can range\nfrom 12 to 24.\nNote that each OBDD node in this table requires 16 bytes, and thus\nthe memory requirement increases very rapidly with increasing table size.\nNote that FL automatically grows the OBDD table if it needs to, and\nthe only reason using this flag is to reduce the time it takes\nto grow the tables.\nThe flag is kept for historical reasons, but with the modern\ndynamical re-ordering version of the OBDD table, this user setable\nconstant is rarely needed.\n\\index{OBDD!table size}\n\\index{dynamic variable re-ordering}\n\\item[-o]\nBefore reaching the fl command prompt, print out all defaults\nread from the .vossrc%\n\\index{.vossrc}%\n{} file.\nThis is useful both for finding out the names of most (but unfortunately\nnot all) options%\n\\index{options}%\n{} as well as checking that a particular option\nhas the correct value.\n\\item[-r i]\nInitialize the random number%\n\\index{random number}%\n{} generator with the seed i.\nThis allows the {\\tt rvariable}\n\\index{rvariable}%\n{} command to create new sets\nof random variable values.\nSee the rvariable command description in Section~\\ref{rvariable} for\nmore details.\n\\item[-v fn]\nStore the variable ordering obtained by dynamic variable re-ordering%\n\\index{variable re-ordering}%\n{}\nin the file fn.\n\\index{dynamic variable re-ordering}\n\\end{description}\n\n\\subsection{Expressions}\n\\index{expressions}\nThe Fl prompt%\n\\index{prompt}%\n{} is : so lines beginning with this contain\nthe user's input; all other lines are output of the system.\n\\begin{hol}\n: 2+3;\nit::int\n5\n\\end{hol}\nHere we simply evaluated the expression 2+3 and FL reduced\nit to normal form; in this case computed the result 5. Note that\nfl does only support integers%\n\\index{integers}%\n{} as number types.\nThe integers are represented in arbitrary precision, and grow as needed.\n\nNote also that Voss stores the result of the most recent expression\nin a variable called {\\tt it}.\n\\index{it}%\nThus, continuing the example by evaluating the expression {\\tt it;} yields:\n\\begin{hol}\n: it;\nit::int\n5\n\\end{hol}\n\n\\subsection{Declarations}\n\nThe declaration%\n\\index{declaration}%\n{} let x = e binds a computation of e to\nthe variable x.\nNote that it does not evaluate e (since the language is fully lazy%\n\\index{lazy}%\n{}).\nOnly if x is printed or used in some other expression that is evaluated\nwill it be evaluated.\nAlso, once e is evaluated, x will refer to the result of the evaluation\nrather than the computation.\nHence, the expression e is evaluated at most once, but it may\nnot be evaluated at all.\n\\begin{hol}\n: let x = 3+3;\nx::int\n\\end{hol}\nNote that when expressions are bound to variables, the system simply\nprints out the inferred type%\n\\index{inferred type}%\n{} of the expression. We will return to\nthe typing scheme in FL later.\nFor now, it suffices to say that FL tries to find as general type as\npossible that is consistent with the type of the expression.\n\nA declaration%\n\\index{declaration!local}%\n{} can be made local to the evaluation of an expression\ne by evaluating the expression decl in e.\nFor example:\n\\begin{hol}\n: let y = let x = 4 in x-5;\ny::int\n\\end{hol}\nwould bind the expression 4 to x only inside the expression\nbound to y. Thus, we get:\n\\begin{hol}\n: let x = 2;\nx::int\n: let y = let x = 4 in x-5;\ny::int\n: x;\n2\n: y;\n-1\n\\end{hol}\nFL is lexically scoped%\n\\index{scoping}%\n{}, and thus\nthe binding in effect at the time of definition is the one used.\nIn other words, if we write:\n\\begin{hol}\n: let x = 2;\nx::int\n: let y = x*5;\ny::int\n: let x = 12;\nx::int\n\\end{hol}\nand we then evaluate y we will get 10\nrather than 60.\n\nContrary to ML, at the top level FL 1.8b does not allow\nsimultaneous bindings%\n\\index{simultaneous bindings}%\n{}.\nHence, if we would like to bind the expressions 2 and 4-5 to the\nvariables x and y respectively, we would have to write:\n\\begin{hol}\n: let x = 2;\nx::int\n: let y = 4-5;\ny::int\n\\end{hol}\nHowever, inside local bindings, a special keyword {\\tt val}\n\\index{val}%\n{}\nis available to take a complicated object apart automatically.\nFor example, if e is an expression of type (int\\verb@#@bool) then\nwe could write:\n\\begin{hol}\n: let top\\_level q =\n\tval (i,b) = q in\n\ti < 3 => b | F;\ntop\\_level::(int\\verb@#@bool)->bool\n\\end{hol}\nIn general, the expression to the right of the val keyword\ncan be an arbitrary complex pattern similar to the patterns%\n\\index{patterns}%\n{}\nallowed in function definitions and lambda expressions.\nFor more details, see the section on pattern matching on page~\\ref{val}.\n\n\\subsection{Functions}\n\nTo define a function%\n\\index{function}%\n{} f with formal parameter x and body e one performs\nthe declaration: let f x = e.\nTo apply the function f to an actual parameter e one evaluates\nthe expression f e.\n\\begin{hol}\n: let f x = x+2;\nf::(int) -> (int)\n: f 4;\n6\n\\end{hol}\nNote that the type inferred for f is essentially ``a function taking\nan int as argument and returning an int''.\nApplications binds more tightly than anything else in FL; thus for example:\nf 3 * 4 would be evaluated as: ((f 3)*4) and thus yield 20.\n\nFunctions of several arguments can also be defined:\n\\begin{hol}\n: let add x y = x+2*y;\nadd::(int) -> ((int) -> (int))\n: add 1 4;\n9\n: let f = add 1;\nf::(int) -> (int)\n: f 4;\n9\n\\end{hol}\nApplications associate%\n\\index{association rules}%\n{} to the left so add 3 4 means (add 3) 4. In the\nexpression add 3, the\nfunction add is partially applied to 3; the resulting value is the\nfunction of type int\\funarrow int which\nadds 3 to twice its argument. Thus add takes its arguments one at a time.\nWe could have made add take a single argument of the cartesian product%\n\\index{cartesian product}%\n{}\ntype (int\\verb@#@int):\n\\begin{hol}\n: let add (x,y) = x+y;\nadd::((int # int)) -> (int)\n: add (3,4);\n7\n: add 3;\n===Type mismatch: (int # int) and int\n#### Run-time error\n---- Type error\n\\end{hol}\nAs well as taking structured arguments (e.g. (3,4)) functions may also return\nstructured results:\n\\begin{hol}\n: let manhat\\_dist (x1,y1) (x2,y2) = (x2-x1, y2-y1);\nmanhat\\_dist::((int # int)) -> (((int # int)) -> ((int # int)))\n: manhat\\_dist (1,1) (3,5);\n(2,4)\n\\end{hol}\n\nTrying to print%\n\\index{print}%\n{} a function with insufficient number of actual arguments\nyield a dash for the function and the type of the expression is printed out.\nFor example:\n\\begin{hol}\n: (5, manhat\\_dist (1,2));\n(5,-) ::(int # ((int # int)) -> ((int # int)))\n\\end{hol}\nThe only exception to this rule is for concrete types\nfor which the user has installed a printing function%\n\\index{printing function}%\n{}.\nFor more details of concrete types, see page~\\ref{concreteTypes}.\n\n\\subsection{Recursion}\n\nThe following is an attempt to define the factorial function:\n\\begin{hol}\n: let fact n = n=0 => 1 | n*fact (n-1);\n#### Run-time error\n---- Undefined variable (fact)\n\\end{hol}\nThe problem is that any free variables in the body of a function have\nthe bindings they had\njust before the function was declared; fact is such a free variable\nin the body of the declaration\nabove, and since it is not defined before its own declaration, an error\nresults. To make things\nclear consider:\n\\begin{hol}\n: let f n = n+1;\nf::(int) -> (int)\n: let f n = n=0 => 1 | n*f (n-1);\nf::(int) -> (int)\n: f 3;\n9\n\\end{hol}\nHere 3 results in the evaluation of 3*(f 2), but now the first f is\nused so f 2 evaluates to 2+1=3.\nTo make a function declaration hold within its own body, letrec%\n\\index{letrec}%\n{}\ninstead of let must be used.\nThe correct recursive%\n\\index{recursive}%\n{} definition of the factorial function is thus:\n\\begin{hol}\n: letrec fact n = n=0 => 1 | n*fact (n-1);\nfact::(int) -> (int)\n: fact 5;\n120\n\\end{hol}\n\nIt should be pointed out that FL currently does not allow direct definition\nof mutually recursive functions%\n\\index{mutually recursive functions}%\n{}.\nFor an example on how this limitation can be dealt with, see\nthe subsection on concrete type decalartions.\n\n\\subsection{Tuples}\n\nIf $e\\_1, e\\_2, \\ldots , e\\_n$ have types $t\\_1, t\\_2, \\ldots , t\\_n$, then\nthe FL expression $(e\\_1, e\\_2, \\ldots , e\\_n)$ have type\n$t\\_1$\\verb@#@$t\\_2$\\verb@#@$\\ldots$\\verb@#@$t\\_n$.\nThe standard functions on tuples are fst%\n\\index{fst}%\n{} (first), snd%\n\\index{snd}%\n{} (second), and the infix\noperation , (pair%\n\\index{pair}%\n{}).\n\\begin{hol}\n: let q = ((1,2),3);\nq::((int # int) # int)\n: let qq = (1,2,3);\nqq::(int # (int # int))\n: q;\n((1,2),3)\n: qq;\n(1,2,3)\n: let qqq = (1,\"abc\");\nqqq::(int # string)\n: qqq;\n(1,\"abc\")\n\\end{hol}\n\n\\subsection{Lists}\n\nIf $e\\_1, e\\_2, \\ldots , e\\_n$ have type $t$, then the FL expression\n$[e\\_1, e\\_2, \\ldots , e\\_n]$ has type ($t$ list%\n\\index{list}%\n{}).\nThe standard functions on lists are hd%\n\\index{hd}%\n{} (head%\n\\index{head}%\n{}), tl%\n\\index{tl}%\n{} (tail%\n\\index{tail}%\n{}), []%\n\\index{[]}%\n{} (the empty list%\n\\index{empty list}%\n{}), and the infix operation : (cons%\n\\index{cons}%\n{}).\nNote that all elements of a list must have the same type (compare\nthis with a tuple where the size is determined but each member of\nthe tuple can have different type).\n\\begin{hol}\n: let l = [1,2,3,3,2,1,2];\nl::(int list)\n: hd l;\n1\n: tl l;\n[2,3,3,2,1,2]\n: 0:l;\n[0,1,2,3,3,2,1,2]\n: letrec (len [] = 0) /\\verb!\\! (len (a:rest) = 1+len rest);\nlen::((* list)) -> (int)\n: len l;\n7\n\\end{hol}\n\n\\subsection{Strings}\n\nA sequence of characters enclosed between \\verb@\"@ or \\verb@`@ is a string%\n\\index{string}%\n{}.\nThe standard functions on strings are \\verb@^@ (catenation%\n\\index{catenation}%\n{}), explode%\n\\index{explode}%\n{}\n(make string into list of strings) and\nimplode%\n\\index{implode}%\n{} (make list of strings into single string).\nThere are also int2str%\n\\index{int2str}%\n{} and bool2str%\n\\index{bool2str}%\n{} functions that create a string\nfrom an integer or an object of type boolean.\nWe will return to these later.\n\\begin{hol}\n: let q = \"abc and \\_12!@@#\";\nq::string\n: let qq = `qw\"q qw`;\nqq::string\n: q^qq;\n\"abc and \\_12!@@#qw\"q qw\"\n: explode q;\n[\"a\",\"b\",\"c\",\" \",\"a\",\"n\",\"d\",\" \",\"\\_\",\"1\",\"2\",\"!\",\"@\",\"@\",\"#\"]\n: implode [\"1\", \"2\"];\n\"12\"\n: int2str (1-34);\n\"-33\"\n: bool2str ((variable \"a\") AND (variable \"b\"));\n\"a&b\"\n\\end{hol}\n\n\\subsection{Polymorphism}\n\nThe list processing functions hd, tl, etc. can be used on all types of lists.\n\\begin{hol}\n: hd [1,2,3];\n1\n: hd [\"abc\", \"edf\"];\n\"abc\"\n: (hd [\"a\", \"b\"]), hd [4,2,1];\n(\"a\",4)\n: let q = [T,T,F];\nq::(bool list)\n: hd q;\nT\n\\end{hol}\nThus hd has several types; for example, it is used above with types\n(int list) \\funarrow int,\n(string list) \\funarrow string, and (bool list) \\funarrow bool.\nIn fact if ty is any type then hd has the type (ty list) \\funarrow ty.\nFunctions, like hd, with many types are called polymorphic%\n\\index{polymorphic}%\n{},\nand FL uses type variables%\n\\index{type variables}%\n{} *, **, ***, etc. to represent their types.\n\\begin{hol}\n: let f x = hd x;\nf::((* list)) -> (*)\n: letrec map fn [] = []\n   /\\verb!\\!    map fn (h:rest) = (fn h) : (map fn rest);\nmap::((*) -> (**)) -> (((* list)) -> ((** list)))\n: letrec fact n = n=0 => 1 | n*fact (n-1);\nfact::(int) -> (int)\n: map fact [1,2,3,4,5,6,7];\n[1,2,6,24,120,720,5040]\n\\end{hol}\nThe FL function map%\n\\index{map}%\n{} takes a function f (with argument type * and result\ntype **), and a list l\n(of elements of type *), and returns the list obtained by applying\nf to each element of l\n(which is a list of elements of type **). Map can be used at any instance\nof its type: above, both *\nand ** were instantiated to int; below, * is instantiated to (int list)\nand ** to bool. Notice that the\ninstance need  not be  specified; it is determined by the type checker.\n\\begin{hol}\n: let eq1 x = x=1;\neq1::(int) -> (bool)\n: map eq1 [1,2,3,4,12,2,1,2];\n[T,F,F,F,F,F,T,F]\n\\end{hol}\n\nIt should be pointed out that FL has a polymorphic type system that\nis sightly different from\nstandard ML's. In particular, only ``top-level'' user-defined functions\ncan be polymorphic. In\nother words, the following works as we would expect.\n\\begin{hol}\n: let null l = l = [];\nnull::((* list)) -> (bool)\n: let f x y = null x OR null y;\nf::((* list)) -> (((** list)) -> (bool))\n: f [1,2,3] [\"abc\", \"cdef\"];\nF\n\\end{hol}\nHowever, if we use the same declaration inside the expression, it must\nbe monomorphic%\n\\index{monomorphic}%\n{}. In other\nwords, the following example fails.\n\\begin{hol}\n: let f x y =\n    let null l = l = [] in\n    null x OR null y;\nf::((* list)) -> (((* list)) -> (bool))\n: f [1,2,3] [\"abc\", \"cdef\"];\n===Type mismatch: int and string\n#### Run-time error\n---- Type error\n\\end{hol}\nIn this respect, FL is similar to the functional language called\nMiranda\\footnote{Miranda is a trademark of\nResearch Software Ltd.}~\\cite{Miranda}.\n\n\\subsection{Type Annotations}\nSometimes it is useful to inform the type inference mechanism\nof FL what type is expected.\nIn particular, when using overloaded%\n\\index{overloaded}%\n{} operators or functions\nit is quite common to have to explicitly type arguments.\nIn FL a variable or expression can be annotated%\n\\index{type annotation}%\n{} with its expected\ntype by enclosing it in curly braces and decorate the expression\nwith a type expression.\nIn particular, if we would like to define a function ihd that\nreturn the head of a list, but that only can be used on integer lists,\nwe could define ihd as follows:\n\\begin{hol}\nlet ihd \\{l::int list\\} = hd l;\n\\end{hol}\nSimilarly, if we have overloaded the operator + to either\noperate over strings or integers, we can extend this opverloading\nwith yet another function by declaring\n\\begin{hol}\noverload + \\{+::int->int->int\\} \\{+::string->string->string\\} foo;\n\\end{hol}\nIf we now were to write a function that adds three integer numbers\nwe would have to decorate the types so that the overload resolution\ncan succeed. For example, we could write:\n\\begin{hol}\nlet f \\{x::int\\} \\{y::int\\} \\{z::int\\} = x+y+z;\n\\end{hol}\nor we could write\n\\begin{hol}\nlet f x y z = \\{x+\\{y::int\\} ::int\\}+z;\n\\end{hol}\nalthough the former is easier to read and more general.\n\n\\subsection{Lambda Expressions}\n\nThe expression \\verb@\\@x.e evaluates to a function with formal parameter x\nand body e. Thus the\ndeclaration let f x = e is equivalent to let f = \\verb@\\@x.e. The character\n\\verb@\\@ is our representation of lambda,\nand expressions like \\verb@\\@x.e are called lambda-expressions%\n\\index{lambda-expressions}%\n{}.\n\\begin{hol}\n: \\verb!\\!x.x+1;\n- ::(int) -> (int)\n\n: let q = \\verb!\\!x.x+1;\nq::(int) -> (int)\n: q 1;\n2\n: map (\\verb!\\!x.x*x) [1,2,3,4,5];\n[1,4,9,16,25]\n\\end{hol}\n\n\\subsection{Failures}\n\nSome standard functions fail at run-time on certain arguments, printing\nout a string (which is usually the function name) to identify the sort\nof failure. A failure%\n\\index{failure}%\n{} with string \"t\" may also be\ngenerated explicitly by evaluating the expression error \"t\" (or more\ngenerally error%\n\\index{error}%\n{} e where e has type string).\n\\begin{hol}\n: hd(tl [2]);\nFailure:    ----  Cannot compute hd of the empty list\n\n: 1/0;\nFailure:    ----  Division by zero\n\n\n: error \"My message\";\nFailure:    ----   My message\n\\end{hol}\n\nA failure can be trapped%\n\\index{trap a failure}%\n{} by catch%\n\\index{catch}%\n{}; the value of the expression $e\\_1$ catch\n$e\\_2$ is that of $e\\_1$, unless\n$e\\_1$ causes a failure, in which case it is the value of $e\\_2$. One important\nproperty of catch is that it is\n(very) strict in its first argument. In other words, (hd ($e\\_1$ catch\n$e\\_2$)) will completely evaluate $e\\_1$\neven though only the first element in the list may be needed. In view\nof FL's lazy semantics%\n\\index{lazy semantics}%\n{}, the\nuse of catch should be very carefully considered. In particular, the\nbindings of catch is dynamic\nrather than static so the user beware!\n\n\\subsection{Boolean Expressions}\n\nAll Boolean expressions%\n\\index{Boolean expression}%\n{} in FL are maintained as ordered binary decision\ndiagrams. Hence, it\nis very easy to compare complex Boolean expressions and to combine\nthem in different ways.\nBoolean variables%\n\\index{Boolean variable}%\n{} are created by variable%\n\\index{variable}%\n{} s, where s is of type string.\nThe system uses name\nequivalence, and thus\n\\begin{hol}\n: let v = variable \"v\";\nv::bool\n: v=v;\nT\n: variable \"v\" = variable\"v\";\nT\n\\end{hol}\n\nThe constants true%\n\\index{true}%\n{} and false%\n\\index{false}%\n{} are denoted T and F respectively. The\nstandard boolean functions\nare available, i.e., AND%\n\\index{AND}%\n{}, OR%\n\\index{OR}%\n{}, NOT%\n\\index{NOT}%\n{}, XOR%\n\\index{XOR}%\n{}, and =%\n\\index{=}%\n{} are all defined for objects of type Boolean..\nFurthermore, there\nis a special identity%\n\\index{identity}%\n{} operator ==%\n\\index{==}%\n{} that return true or false depending\non whether the two arguments\nrepresent the same Boolean function or not.\n\nNote that the variable ordering%\n\\index{variable ordering}%\n{} in the OBDD representation is defined\nby the order in which each variable function call {\\em gets evaluated}.\nSince FL is a fully lazy language%\n\\index{lazy language}%\n{}, and thus the order in which expressions\nare evaluated is often difficult to predict, it is strongly recommended\nthat each variable declaration is forced to be evaluated before it\nis being used.\nAlternatively, one can request that FL re-orders the variables\nby evaluating the function var\\_order%\n\\index{var\\_order}%\n{} and give as argument a list\nof variable names.\nFL will then apply the dynamic variable re-ordering mechanism and\nenforce that the variables mentioned in the list will be the first\narguments and that they will occur in exactly this order.\n\\begin{hol}\n: let a = variable \"a\";\na::bool\n: let b = variable \"b\";\nb::bool\n: a AND b;\na&b\n: a OR b;\na + b\n: NOT a AND NOT b AND T;\na'&b'\n: a = b;\na&b + a'&b'\n:  a == b;\nF\n: (a=b) == (a AND b OR NOT a AND NOT b);\nT\n\\end{hol}\n\nThe default style for printing Boolean expressions%\n\\index{printing Boolean expressions}%\n{} is as a sum-of-products%\n\\index{sum-of-products}%\n{}.\nSince this may require printing an extremely large expression, there\nis a user-setable limit on how many products that will be printed\nand the maximum size of a product.\nFor more details how to modify these two parameters, see Section~\\ref{vossrc}.\n\n\\subsection{Quantifiers}\n\nThere are several ways of using quantification%\n\\index{quantification}%\n{}.\nThe ``traditional'' !x. e%\n\\index{$!x.\\,e$}%\n{} (for all x) and ?x. e%\n\\index{$?x. e$}%\n{}\n(there is an x) can be used as long as the type of x and e is bool.\nIn addition, you can also quantify away a variable in an expression\nby quant\\_forall%\n\\index{quant\\_forall}%\n{} v e or quant\\_thereis%\n\\index{quant\\_thereis}%\n{} v e.\n\\begin{hol}\n: !a. ?b. (a XOR b);\nT\n: let a = variable \"a\"; let b = variable \"b\"; let c = variable \"c\";\na::bool\nb::bool\nc::bool\n: : : a AND b OR c;\na&b + c\n:  quant\\_forall a (a AND b OR c);\nc\n: quant\\_thereis (a OR c) (a AND b OR c);\nT\n\\end{hol}\nIn fact, quant\\_forall and quant\\_thereis quantifies away all variables\nin the first Boolean expression.\nFor example:\n\\begin{hol}\n: let v s = variable s;\nv::(string) -> (bool)\n: let a = v \"a\"; let b = v \"b\"; let c = v \"c\"; let d = v \"d\";\na::bool\nb::bool\nc::bool\nd::bool\n: : : : let ex = (a AND NOT b);\nex::bool\n: ex;\na&b'\n: let nex = ex AND (a=c) AND (b=d);\nnex::bool\n: quant\\_thereis (a AND b) nex;\nc&d'\n\\end{hol}\nNote that the actual Boolean expression used as first argument is irrelevant.\nThe only important fact is on what variables the expression depends.\n\n\\subsection{Dependencies}\n\nSometimes it is useful to find out which Boolean variables a\nBoolean function actually depends on.\nThe built-in function depends%\n\\index{depends}%\n{} takes a list of elements of type\nbool and return the union of the variables these functions depend on.\nFor example:\n\\begin{hol}\n: let v s = variable s;\nv::(string) -> (bool)\n: let a = v \"a\"; let b = v \"b\"; let c = v \"c\"; let d = v \"d\";\na::bool\nb::bool\nc::bool\nd::bool\n: : : : let ex1 = (a=c) AND d;\nex1::bool\n: let ex2 = a = b;\nex2::bool\n: depends [ex1];\n[\"a\",\"c\",\"d\"]\n: depends [ex1,ex2];\n[\"a\",\"b\",\"c\",\"d\"]\n\\end{hol}\n\nNote that the order of the variables in the list returned by depends\nis the variable order of the OBDD representation.\n\n\\subsection{Substitutions}\n\nGiven a Boolean function represented as an OBDD, it is convenient to\nbe able to apply the function to some arguments.\nThis can be accomplished by the substitute%\n\\index{substitute}%\n{} command that takes a\nlist of (variable name, expression) and an expression in which the\nsimultaneous substitution%\n\\index{substitution}%\n{} is to be made.\nFor example,:\n\\begin{hol}\n: let v s = variable s;\nv::(string) -> (bool)\n: let a = v \"a\"; let b = v \"b\"; let c = v \"c\"; let d = v \"d\";\na::bool\nb::bool\nc::bool\nd::bool\n: : : : let ex = (a AND NOT b);\nex::bool\n: ex;\na&b'\n: substitute [(\"a\", c), (\"b\", d)] ex;\nc&d'\n\\end{hol}\n\nIt should be pointed out that there are no restrictions on the expressions\nin the substitutions.\nIn particular, it is possible to ``swap'' variables.\nWe illustrate this by continuing the example above:\n\\begin{hol}\n: ex;\na&b'\n: substitute [(\"a\", b), (\"b\", a)] ex;\na'&b\n\\end{hol}\n\n\\subsection{Type Abbreviations}\n\\index{type abbreviations}\n\nTypes can be given names:\n\\begin{hol}\n: new\\_type\\_abbrev pair = int#int;\n: let p = (1,2);\np::(int # int)\n\\end{hol}\nHowever, as can be seen from the example, the system does not\nmake any distinction between the new type name\nand the actual type. It is purely a short hand that is useful when\ndefining concrete types below.\n\n\\subsection{Concrete Types}\n\nNew types (rather than mere abbreviations) can also be defined.\nConcrete types%\n\\index{concrete type}%\n{} are types\ndefined by a set of constructors%\n\\index{type constructor}%\n{} which can be used to create objects\nof that type and also (in\npatterns) to decompose objects of that type. For example, to define\na type card one could use the\nconstruct type:\n\\begin{hol}\n: lettype card = king | queen | jack | other int;\nother::(int) -> (card)\njack::card\nqueen::card\nking::card\n\\end{hol}\nSuch a declaration declares king, queen, jack and other as constructors\nand gives them\nvalues. The value of a 0-ary constructor such as king is the constant\nvalue king. The value of a\nconstructor such as other is a function that given an integer value\nn produces other(n).\n\\begin{hol}\n: king;\n- ::card\n\n: other 9;\n- ::card\n\\end{hol}\n\nNote that there is no print routine%\n\\index{print routine}%\n{} for concrete types. If a print\nroutine is desired, one has to\ndefine it.\nTo define functions that take their argument from a concrete type,\nwe introduce the idea of pattern matching%\n\\index{pattern matching}%\n{}.\nIn particular\n\\begin{hol}\nlet f pat1 = e1\n /\\verb@\\@ f pat2 = e2\n /\\verb@\\@ ...\n /\\verb@\\@ f patn = en;\n\\end{hol}\ndenotes a function that given a value v selects the first pattern that\nmatches $v$, say pati, binds the variables of pati to\nthe corresponding components of the value $v$ and then evaluates the\nexpression ei.\nWe could for example define a print function for the cards in the following way:\n\\begin{hol}\n: let pr\\_card king = \"K\"\n  /\\verb@\\@  pr\\_card queen = \"Q\"\n  /\\verb@\\@  pr\\_card jack = \"J\"\n  /\\verb@\\@  pr\\_card (other n) = int2str n;\npr\\_card::(card) -> (string)\n: pr\\_card king;\n\"K\"\n: pr\\_card queen;\n\"Q\"\n: pr\\_card jack;\n\"J\"\n: pr\\_card (other 5);\n\"5\"\n\\end{hol}\nIf we now issue the top-level command \n\\begin{hol}\n: install\\_print\\_function pr\\_card;\nInstalled pretty printer for objects of type: card\n\\end{hol}\n\\index{install\\_print\\_function}\nevery time we evaluate an expression of type card this routine would\nbe called and the string printed out on standard out.\n\nMutually recursive types%\n\\index{mutually recursive types}%\n{} can also be defined. To do so, simply list\nthe type names on the left\nhand side of the equality sign and list the type expressions on the\nright hand side. For example:\n\\begin{hol}\n: lettype IExpr, BExpr = Ivar string | Plus IExpr IExpr | ITE BExpr IExpr IExpr,\n                         And BExpr BExpr | GEQ IExpr IExpr;\nGEQ::IExpr->IExpr->BExpr\nAnd::BExpr->BExpr->BExpr\nITE::BExpr->IExpr->IExpr->IExpr\nPlus::IExpr->IExpr->IExpr\nIvar::string->IExpr\n\\end{hol}\ndefines two mutually recursive concrete data types for integer expressions\nand Boolean expressions (very simple versions!).\n\nCurrently, FL does not provide any direct way of defining\nmutually recursive functions%\n\\index{mutually recursive functions}%\n{}.\nThe easiest work-around is to pass the later defined functions as\nparameters to the earlier function.\nAfter all functions have been defined, one can re-define the early ones.\nTo illustrate the approach, consider writing functions that converts\nobjects of type IExpr and BExpr to strings.\nOne possible solution is as follows:\n\\begin{hol}\n: let prIExpr prBexpr expr =\n    letrec prIExpr (Ivar s) = s\n     /\\verb@\\@    prIExpr (Plus a b) = (prIExpr a)^\" + \"^(prIExpr b)\n     /\\verb@\\@    prIExpr (ITE c t e) = \"if \"^(prBexpr c)^\" then \"^\n                                 (prIExpr t)^\" else \"^(prIExpr e) in\n    prIExpr expr;\nprIExpr::(BExpr->string)->IExpr->string\n\n: letrec prBExpr (And a b) = (prBExpr a) ^ \" AND \" ^ (prBExpr b)\n   /\\verb@\\@    prBExpr (GEQ a b) = (prIExpr prBExpr a)^\" >= \"^\n\t\t\t     (prIExpr prBExpr b);\nprBExpr::BExpr->string\n\n: let prIExpr e = prIExpr prBExpr e;\nprIExpr::IExpr->string\n\\end{hol}\nNote that we simply pass prBExpr as an argument to the initial definition\nof prIExpr.\n\n\\subsection{Abstract Types}\n\nIn FL one can also hide the definitions of types, type constructors,\nand functions. By\nenclosing a sequence of type declarations and function definitions\nwithin begin\\_abstype%\n\\index{begin\\_abstype}%\n{}\nend\\_abstype%\n\\index{end\\_abstype}%\n{} elist, only the constructors and/or functions mentioned\nin the elist will be visible\nand accessible for other functions and definitions. Thus, one can protect\na concrete type and only\nmake some abstract constructor functions available. To illustrate the\nconcept, consider defining a\nconcrete type called theorem. The only way we would like the user to\nbe able to create a new theorem is to give a Boolean expression that\ndenotes a tautology (something always true).\nFirst we define the expression type.\n\\begin{hol}\n: lettype expr =  Forall string expr |\n                Thereis string expr |\n                Var string |\n                True |\n                False |\n                And expr expr |\n                Or expr expr |\n                Not expr;\nNot::(expr) -> (expr)\nOr::(expr) -> ((expr) -> (expr))\nAnd::(expr) -> ((expr) -> (expr))\nFalse::expr\nTrue::expr\nVar::(string) -> (expr)\nThereis::(string) -> ((expr) -> (expr))\nForall::(string) -> ((expr) -> (expr))\n\\end{hol}\n\nWe then define the concrete type theorem and the constructor function\nis\\_taut. Note that we\nalso define a couple of help functions. However, only the is\\_taut function\nis exported out of the\nabstract type%\n\\index{abstract type}%\n{}, and thus is the only way of creating a theorem.\n\\begin{hol}\n: begin\\_abstype;\n: lettype theorem = Thm expr;\nThm::(expr) -> (theorem)\n: letrec assoc x l = l = [] => error \"assoc\" |\n                let h = hd l in\n                (fst h) = x => (snd h) | assoc x (tl l);\nassoc::(*) -> ((((* # **) list)) -> (**))\n: letrec  (eval (Forall s e) al = !x.(eval e ((s,x):al))) /\\verb@\\@\n        (eval (Thereis s e) al = ?x.(eval e ((s,x):al))) /\\verb@\\@\n        (eval (Var s) al = (assoc s al) catch\n                                   (error \"Free variable\")) /\\verb@\\@\n        (eval True al = T) /\\verb@\\@\n        (eval False al = F) /\\verb@\\@\n        (eval (And e1 e2) al = (eval e1 al) AND (eval e2 al))/\\verb@\\@\n        (eval (Or e1 e2) al = (eval e1 al) OR (eval e2 al)) /\\verb@\\@\n        (eval (Not e) al = NOT (eval e al));\neval::(expr) -> ((((string # bool) list)) -> (bool))\n: let is\\_taut e = ((eval e []) == T) => Thm e |\n                                       error \"Not a tautology\";\nis\\_taut::(expr) -> (theorem)\nend\\_abstype is\\_taut;\n\\end{hol}\n\nWe can now use this very safe theorem system, since we can only generate\ntheorems that are\ntautologies. For example\n\\begin{hol}\n: let e = (Forall \"a\" (Thereis \"b\" (And (Var \"a\") (Var \"b\"))));\ne::expr\n: is\\_taut e;\nFailure:    ----   Not a tautology\n\n\n: let f = (Forall \"a\" (Thereis \"b\" (Or (Var \"a\") (Var \"b\"))));\nf::expr\n: is\\_taut f;\n- ::theorem\n\\end{hol}\n\n\\subsection{Infix Operators}\n\nIn order to make the FL code more readable, it is possible to declare\na function to be infix%\n\\index{infix}%\n{} (associating from the left), infixr%\n\\index{infixr}%\n{}\n(associating from the right), nonfix%\n\\index{nonfix}%\n{} (no fixity at all), prefix\n\\index{prefix}%\n{} (prefix operator with tighter binding than ``normal'' function definitions),\npostfix%\n\\index{postfix}%\n{}, or\nof a binder%\n\\index{binder}%\n{} type.\nFor the infix and infixr directives, the precedence can be given as\na number from 1 to 9, where a higher number binds tighter.\nSimilarly, prefix also takes a precedence number, but only 0 or 1.\nNote that prefix and postfix functions bind higher than any infix function.\nBeware that the fixity declaration modifies the parser and\nthus remains in effect whether\nthe function is exported out of an abstract data type or note.\nAs an illustration of this idea, consider the following example:\n\\begin{hol}\n: lettype expr = Var int |\n                Mult expr expr |\n                Plus expr expr |\n                Negate expr;\nNegate::expr->expr\nPlus::expr->expr->expr\nMult::expr->expr->expr\nVar::int->expr\n: letrec eval (Var i) = i\n  /\\verb@\\@     eval (Mult e1 e2) = (eval e1) * (eval e2)\n  /\\verb@\\@     eval (Plus e1 e2) = (eval e1) + (eval e2)\n  /\\verb@\\@     eval (Negate e1) = 0-(eval e1);\neval::expr->int\n: let ** a b = Mult a b;\n**::expr->expr->expr\n: let ++ a b = Plus a b;\n++::expr->expr->expr\n: infix 4 **;\n: infix 3 ++;\n: let ' i = Var i;\n'::int->expr\n: prefix 0 ';\n: let q = '1 ++ Negate '2 ** Negate '4;\nq::expr\n: eval q;\nit::int\n9\n\\end{hol}\n\nThe next example illustrates how postfix declarations can make the\ncode more readable.\n\\begin{hol}\n: let ns i = 1000*i;\nns::(int) -> (int)\n: postfix ns;\n: let to a b = (a,b);\nto::(*) -> ((**) -> ((* # **)))\n: infix 3 to;\n: 2 ns to 4 ns;\n(2000,4000)\n\\end{hol}\n\nOur final example deals with the binder declaration.\nThe command binder takes a function and makes it into a binder, i.e., an\nobject that introduces a new bound variable in an expression.\nNote that the type of the function declared to be a binder must be\n(*\\funarrow **)\\funarrow string\\funarrow **, since the first argument of\na binder function will be a lambda expression and the second argument will\nbe a string with the name of the bound variable.\nThus, if a function f has been declared as a binder, then\nf x.E will be parsed as f (\\protect\\verb!\\! x.E) \"x\".\n\n\\subsection{Overloading}\n\nFL supports a limited amount of user defined overloading%\n\\index{overloading}%\n{} of functions\nand operators.\nHowever, in order to avoid an exponential type inference algorithm, the\noverloaded operators must be resolved from the types of their arguments only. \nTo illustrate the construct, consider the following example:\n\\begin{hol}\n: let pplus (a,b) (c,d) = (a+c, b+d);\npplus::(int#int)->(int#int)->(int#int)\n: let pprod (a,b) (c,d) = (a*c, b*d);\npprod::(int#int)->(int#int)->(int#int)\n: overload + + pplus;\n: overload * * pprod;\n: (1,2)+(3,4)*(9,3*2);\nit::int#int\n(28,26)\n\\end{hol}\nHere we overloaded the symbols + and *.\nNote that we essentially added new meanings to + and * since we included\nthe (built-in) versions as possible candidates.\n\nThe one area where overloaded operators are somewhat cumbersome to use is\nwhen defining new functions.\nHere it is often necessary to decorate the arguments to the functions\nin order to make the resolution function succeed.\n\\begin{hol}\n: let f x y z = x*(y+z);\n===Type error around line 1\nCannot resolve overloading of `+'\nBoth `pplus' and `+' matches the type\n: let f \\{x::int\\} \\{y::int\\} \\{z::int\\} = x*(y+z);\nf::int->int->int->int\n\\end{hol}\nFinally, overloaded operators and functions can of course also\nbe declared infix, binders, or postfix as any other function or operator.\n\n\\subsection{Quotation of Expressions}\n\\index{quotation of expression}\nSometimes it is convenient to retain the actual text that was used\nto denote an expression.\nBy enclosing the expression in \\verb@``@ and \\verb@''@, FL will return\na pair consisting of the text of the expression as well as the expression\nitself.\n\\begin{hol}\n: `` 1+3*4 '';\nit::string#int\n(\" 1+3*4 \",13)\n\\end{hol}\nNote that it is advisable to include an extra space after the opening quotes\nand before the closing quotes since the parser otherwise is likely to\nview the quotes as being part of an operator or variable.\n\n\\subsection{Circuit Models}\n\nSince the main use of the FL system, and its historical root, is related\nto hardware verification, there are a number of built-in\nfunctions specifically tailored towards hardware modeling\nand symbolic trajectory evaluation in particular. \nInternally, a circuit is represented by a list of nodes (names),\nand a next state function%\n\\index{next state function}%\n{}.\nThe next state function is mapping the current state of the circuit\n(including the current values on the inputs) to a new state\nof the circuit.\nSince the circuit representation is intended for trajectory evaluation,\nthe value domain for each node in the circuit is $\\{0,1,\\X,\\top\\}$\nand thus the next state function consists of quaternary%\n\\index{quaternary}%\n{} (four-valued)\nextensions of the usual Boolean function.\nThe type of such circuit is fsm%\n\\index{fsm}%\n{} (for finite state machine%\n\\index{finite state machine}%\n{}) and, by\ndefault, it does not have a print function (since the machines\nare usually much too large to be meaningful anyway to the user.\nHowever, for the curious reader, the command print\\_fsm%\n\\index{print\\_fsm}%\n{} will print out\na pretty complete version of the state machine.\nNote that for efficiency reasons, the next state function also\ncontains delay and fan-in and fan-out information to aid in the\nefficient simulation.\n\nIn general, there are two ways of creating a fsm object:\n\\begin{enumerate}\n\\item\nLoading a pre-compiled version of a circuit in .exe format.\n\\item\nConverting a FL structure into an fsm.\n\\end{enumerate}\n\n\\subsubsection{Loading a .exe File}\n\nIf the original circuit was described in Berkeley .sim format or\nas a SILOS II gate list, there are programs distributed with the\nsystem that can be used to compile an fsm model directly from\nthese formats.\nThe common format for such pre-compiled circuit model is a (binary)\nfile with a .exe%\n\\index{.exe file}%\n{} suffix.\n%In Section~\\ref{CompanionTools} we discuss in more detail how\n%to create such .exe file.\nLoading in the .exe file and making it an fsm object simply\ninvolves calling the load\\_exe function.\n\nFor example, if there is a full\\_adder.exe file in the current\nworking directory, the following command would create an fsm object\nof the circuit.\n\\begin{hol}\n: let ckt1 = load\\_exe \"full\\_adder.exe\";\nckt1::fsm\n\\end{hol}\nNote that there is no theoretical limit on the number of circuit that can\nbe loaded into the FL system at any particular point in time.\nHowever, since fsm models are often quite large, it is generally\nadvisable not to load more models than absolutely necessary.\n%(In most cases, only one model will be used, but there are times\n%when several models can be useful. We will return to this later\n%in Section~\\ref{ModelChecking}.)\n\n\\subsubsection{Creating an fsm Object Inside FL}\n\\label{makeSTEsection}\n\n{\\bf Warning:} This addition is fairly young and has thus not\nbeen extensively tested. Also, it leaves quite a bit to\nbe desired in terms of not being very ``clean and simple''.\nFor a reader that is more interested in using the Voss system rather\nthan writing a new conversion program from some other netlist format, this\nsection can be skipped.\n\nThe main routine for creating an fsm object is make\\_fsm%\n\\index{make\\_fsm}%\n{}.\nThe type of make\\_fsm is (Set)\\funarrow (fsm)\\footnote{Currently, when\nFL is invoked, the type of make\\_fsm is actually (*)\\funarrow (fsm), but\nthis is a bug that will be removed in the next release.}\nBefore going into how an object of type Set%\n\\index{Set}%\n{} can be constructed, we\nneed to make a small digression and introduce the quaternary logic type.\nFor historical reasons, the name of the quaternary objects is tern%\n\\index{tern}%\n{},\nand tern is defined as the concrete type:\n\\begin{hol}\n: lettype tern =  One |\n                Zero |\n                X |\n                Z |\n                Val string |\n                And tern tern |\n                Or tern tern |\n                Not tern |\n                Glb tern tern |\n                Lub tern tern;\nLub::tern->tern->tern\nGlb::tern->tern->tern\nNot::tern->tern\nOr::tern->tern->tern\nAnd::tern->tern->tern\nVal::string->tern\nZ::tern\nX::tern\nZero::tern\nOne::tern\n\\end{hol}\nwhere One%\n\\index{One}%\n{}, Zero%\n\\index{Zero}%\n{}, X%\n\\index{X}%\n{},  And%\n\\index{And}%\n{}, Or%\n\\index{Or}%\n{}, and Not%\n\\index{Not}%\n{} are the obvious functions.\nGlb%\n\\index{Glb}%\n{} stands for the greatest lower bound and Lub%\n\\index{Lub}%\n{} for the least upper bound.\nZ%\n\\index{Z}%\n{} is used to represent the top value%\n\\index{top value}%\n{}.\nFinally, Val%\n\\index{Val}%\n{} s is used to refer to the value on node s.\nThus, as a concrete example, the next state function of a node \"o\" may\nbe described as (Not (And (Val \"in1\") (Val \"in2\"))).\n\nThere are four constructor functions for an object of type Set:\n\\begin{enumerate}\n\\item\nEmpty%\n\\index{Empty}%\n{},\n\\item\nElement%\n\\index{Element}%\n{} (string\\verb@#@((tern\\verb@#@tern) list)),\n\\item\nUnion%\n\\index{Union}%\n{} Set Set, and\n\\item\nSequential%\n\\index{Sequential}%\n{} Set Set.\n\\end{enumerate}\nThe Empty is introduced to make writing functions that generate\nobjects of type Set easier.\nElement is the constructor that actually introduces new nodes and\nalso give driver functions for the node.\nIn general, Element n gvl, will create a node named n.\nThis node will at least have (more about this later) the drivers\nlisted in the gvl list.\nA driver is simply a pair of quaternary expressions:\nthe first object of the pair is a guard, and the second part\nis the value being driven when the guard is true.\nFor a combinational node, the driver list is a single pair whose\nguard is One and whose value component is the next state function\nof the gate.\nFor more complex nodes, like register nodes or bus nodes, the guard-value\nlist is often much longer.\n\nThe Union construct is used to gather a collection of these Element\ndeclarations so that an fsm can eventually be made.\nFinally, the Sequential constructor takes two objects S1 and S2 of\ntype Set and merges them into a single object of type Set.\nIn that sense, Sequential behaves exactly like Union.\nThe difference is how the two deal with nodes defined in both set S1 and set S2\nand for which both nodes may have at least one of their guards enabled\nat the same time.\nUnion will find the greatest lower bound of the values being driven\nat the same time whereas Sequential will assume that the driver in the\nsecond set overrides the driver in the first.\nTo illustrate the difference, consider the following example:\n\\begin{hol}\n: let a = Element (\"in1\", [(One, One)]);\na::Set\n: let b = Element (\"in1\", [(One, Zero)]);\nb::Set\n: let ex1 = Union a b;\nex1::Set\n: let ex2 = Sequential a b;\nex2::Set\n: let m1 = make\\_fsm ex1;\nm1::fsm\n: let m2 = make\\_fsm ex2;\nm2::fsm\n: m1;\n\\end{hol}\nNow m1 and m2 will both be fsm models with a single node called in1.\nHowever, in m1, the next state function of in1 will be $\\X$, since that\nis the most we can say from the inconsistent driver commands given\nin the example.\nOn the other hand, the next state function of the in1 node in m2 will be Zero.\n\nFor an example of using this facility, the directory HDL in the demo\ndistribution illustrates how one can go about defining a new description\nlanguage in order to create an fsm object.\n\n\\subsection{Queries to the Circuit Model}\n\nThere are five built-in functions that are useful in dealing with\nan fsm model: nodes%\n\\index{nodes}%\n{}, fanin%\n\\index{fanin}%\n{}, fanout%\n\\index{fanout}%\n{}, is\\_stable%\n\\index{is\\_stable}%\n{}, and get\\_node\\_val%\n\\index{get\\_node\\_val}%\n{}.\nNodes takes an fsm model and returns a {\\em list of lists} of circuit nodes.\nThe reason for the double listing is that a node may have more than\none name (only from .exe file translations).\nFanin takes an fsm model and a name of a node and returns the\nlist of node names that the next state function depend on.\nFanout works in a similar way, but for the fanout nodes.\nIs\\_stable returns T (true) if the circuit is currently stable.\nIt is mainly used when the simulation is aborted at some\nparticular time with the \"-m\" option to STE.\nFinally, get\\_node\\_val takes an fsm object and the name of a node\nand returns the encoded version of the current value of the node.\nThe encoding used is: $\\X = (T,T)$, $1=(T,F)$, $0=(F,T)$, and $\\top=(F,F)$.\nOf course, the two Boolean values are often Boolean functions over some\nvariables.\nThe main use of the get\\_node\\_val function is when the simulation\nis aborted for some reason.\nGet\\_node\\_val can then be used to probe the current state of the system.\nFor example, assuming there is a full\\_adder.exe file in the current\nworking directory, we would get:\n\\begin{hol}\n: let ckt = load\\_exe \"full\\_adder.exe\";\nckt::fsm\n: nodes ckt;\n..[[\"cout\"],[\"t4\"],[\"t3\"],[\"t2\"],[\"result\"],[\"cin\"],[\"t1\"],[\"b\"],[\"a\"]]\n: fanin ckt \"cout\";\n[\"t2\",\"t3\",\"t4\"]\n: fanout ckt \"t3\";\n[\"cout\"]\n: fanout ckt \"t4\";\n[\"cout\"]\n: fanout ckt \"a\";\n[\"t3\",\"t2\",\"t1\"]\n: get\\_node\\_val ckt \"t2\";\n..(T,T)\n\\end{hol}\n\nIf the user also loads in the \"default.fl\" standard library, there is\nthe very useful function {\\em excitation}%\n\\index{excitation}\nthat also takes an fsm model\nand a node name, but that returns the next state function for binary inputs.\nNote, however, that the current version of the excitation function\nonly works correctly for unit delay nodes.\n\\begin{hol}\n: load \"defaults.fl\";\n-Loading file defaults.fl\nT\n\n: excitation ckt \"cout\";\n....\nTrace started for node: cout \n        Current value:X\n.Time: 1\n.Trace: Node cout  at time 1: t4' + t3' + t2'\nTime: 2\n\nTrace ended for node: cout \n\"t4' + t3' + t2'\"\n\\end{hol}\nWe will return to this in Section~\\ref{vossrc}.\n\n\\subsection{Symbolic Trajectory Evaluation}\n\nThere is actually only one built-in command for symbolic trajectory%\n\\index{symbolic trajectory evaluation}%\n{}\nevaluation called STE%\n\\index{STE}%\n{}.\nIn general, STE determines, through symbolic trajectory evaluation, whether\nan antecedent/consequent pair hold in for some circuit.\nSTE will return a Boolean function that gives the condition for the\nverification to succeed.\nFor most applications the desired return value is T.\n\nIn general STE is invoked as\n\\begin{hol}\nSTE options fsm weak\\_list ant\\_list cons\\_list trace\\_list\n\\end{hol}\nwhere options%\n\\index{STE options}%\n{} is a string that can contain a combinations of the\nfollowing flags:\n\\begin{description}\n\\item[-a] Abort%\n\\index{abort STE}%\n{} the verification at the first antecedent or consequent failure.\nIf the verification is aborted, STE will return a Boolean function that\ngives {\\em the condition for this failure to manifest itself}.\nNote that this is contrary to STE's usual behavior which is to return\nthe Boolean function that gives the conditions for the verification to\nsucceed.\n\\item [-m n]\nAbort the verification after reaching time n.\n\\item [-e]\nEvaluate evey node in the circuit whether the node is in the\nfan-in tree of some node that is checked or traced or not.\nIn other words, with the -e option, the simulator will compute\nthe value on every node. Normally, a node whose value\ncannot be observed (directly or indirectly) is simply kept at X.\nOf course, the STE command can run significantly slower with the\n-e option, so beware!\n\\item [-i]\nAllow antecedent failures%\n\\index{antecedent failures}%\n{}.\nIn other words, compute a straight implication.\nThe normal behavior of the verification process is to disallow\nantecedent failures.\nThus the default verification condition is both to check that every\ntrajectory the circuit can go thorough that is consistent with the\nantecedent is also consistent with the consequent, and that there\nis at least one (real) circuit trajectory that is consistent\nwith the antecedent.\n\\item [-n]\nAllow over-constrained values, i.e., allow nodes to take\non the top value in the value lattice.\nNormally, over-constrained values are viewed as failures.\n\\item[-w]\nDo not print out warning messages%\n\\index{warning messages}%\n{}.\n\\item[-t s]\nIn addition to printing out trace messages on stderr, also send\nthe trace events in Postscript%\n\\index{Postscript waveform}%\n{} format to the file s.\nBy previewing or printing out the file the user gets a waveform diagram for\nthe traced signals.\n\\item[-T s]\nSame as -t, but generate Postscript code in landscape mode.\n\\end{description}\n\nThe second argument to STE must be an object of the fsm type representing\na circuit that is to be simulated.\n\nThe weak\\_list is a list of 4-tuples.\nEach 4-tuple is of the form (g,n,f,t), where $n$ is a node name, $f$ and $t$\ndenote start and stop times, and $g$ is a Boolean function\ndenoting the domain for which this node should be weakened%\n\\index{weakened}%\n{}.\nFor assignments making the guard true, the next state function of the\ncircuit node is set to $X$.\nThis is often useful when verifying a subsystem of a larger system\nthat has shared input signals.\nBy weakening%\n\\index{weakening}%\n{} the model, unnecessary computations does not have\nto be performed.\nNote that weakening a model is a ``safe'' operation in that\nthe monotonicity of the circuit models guarantee that if we\ncan verify something in the weakened model, then that same property\nis guaranteed to hold in the original model.\n\nThe ant\\_list and cons\\_list are  both lists of five-tuples.\nEach five-tuple%\n\\index{five-tuple}%\n{} is of the form $(g,n,v,s,t)$, where $g$ is a Boolean function\ndenoting the domain for which this assertion/check should be carried out,\n$n$ is the name of a node, $v$ is the value to be asserted/checked, and\n$s$ and $t$ denote the start and stop times for this assertion/check\nrespectively.\n\nFinally, the last argument to STE is a list of triples.\nEach triple is of the form $(n,s,t)$, where $n$ is a name of a node\nto be traced%\n\\index{traced}%\n{} and $s$ and $t$ are the start and stop times for this\ntrace respectively.\n\nOf course, in practice, it would be quite tedious to have to\nwrite all specifications in terms of lists of five-tuples.\nConsequently, a small language (actually a small set of useful functions)\nhas been defined in the library file \"verification.fl\".\nThese functions make it much easier to write specification.\nHowever, it should be remembered that when the verification\nis actually performed, all these higher level constructs gets translated\ndown to the two lists of five-tuples.\n\nFor more details on how to use the STE function, we refer the reader\nto Section~\\ref{tutorial}.\n", "meta": {"hexsha": "24ec134bb1252f526176c88ee4c53b9181852e92", "size": 49967, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/new_doc/03_fl.tex", "max_stars_repo_name": "mfernan2/VossII", "max_stars_repo_head_hexsha": "e1c1142c9c94255995c13efe2e1b7af4ae03f2e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/new_doc/03_fl.tex", "max_issues_repo_name": "mfernan2/VossII", "max_issues_repo_head_hexsha": "e1c1142c9c94255995c13efe2e1b7af4ae03f2e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/new_doc/03_fl.tex", "max_forks_repo_name": "mfernan2/VossII", "max_forks_repo_head_hexsha": "e1c1142c9c94255995c13efe2e1b7af4ae03f2e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8667065152, "max_line_length": 80, "alphanum_fraction": 0.7087277603, "num_tokens": 14097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.34347018272207214}}
{"text": "\\documentclass[xcolor=dvipsnames]{beamer}\n\n\\usepackage[utf8]{inputenc}\n\\usepackage{default}\n\\usepackage{beamerthemesplit}\n\\usepackage{tikz}\n\\usetikzlibrary{positioning,shapes,arrows}\n\\usetheme{Berkeley}\n\\usecolortheme[named=Black]{structure}\n\n\\title[]{Floating Base Rigid Body Dynamics Estimation}\n\\author[]{Francesco Nori, Jorhabib Eljaik}\n\\date{\\today}\n\n\n\\begin{document}\n% \\maketitle\n\n\\begin{frame}\n \\titlepage\n\\end{frame}\n\n\\begin{frame}\n \\frametitle{Table of contents}\n \\tableofcontents\n\\end{frame}\n\n\\section{Introduction}\n\\begin{frame}\n  \\frametitle{Sensor fusion on the iCub}\n\\begin{figure} \n  \\centering \n\t  \\includegraphics[height=0.55\\hsize]{images/png/FT.png} \n\t  \\includegraphics[height=0.55\\hsize]{images/png/acc.png} \n\t  \\includegraphics[height=0.55\\hsize]{images/png/gyroAcc.png} \n\\end{figure}\n\\end{frame}\n\n\\begin{frame}\n  \\frametitle{Sensor fusion on the iCub}\n\\begin{figure} \n  \\centering \n\t  \\includegraphics[height=0.55\\hsize]{images/pdf/rigidBody.pdf} \n\\end{figure}\n\\end{frame}\n\n\\begin{frame}\n  \\frametitle{Sensor fusion on the iCub}\n\\begin{figure} \n  \\centering \n\t  \\includegraphics[height=0.55\\hsize]{images/pdf/foot.pdf} \n\\end{figure}\n\\end{frame}\n\n\\begin{frame}\n  \\frametitle{Sensor fusion on the iCub}\n \\begin{eqnarray*}\nm    \\dot v^B    + \\omega^B \\times (m       v^B) & = & f^B_1  + ... + f^B_n + mg^B \\\\\nI^B \\dot \\omega^B + \\omega^B \\times (I^B \\omega^B) & = & \\mu^B_1 + ... + \\mu^B_n\n\\end{eqnarray*}\n\\begin{itemize}\n\\item $I^B$    : inertia in the body reference frame\n\\item $m$      : mass of the rigid body\n\\item $f^B_i$  : i-th force expressed in the body reference frame\n\\item $\\mu^B_i$ : i-th torque expressed in the body reference frame\n\\item $\\omega^B$: angular velocity expressed in the body reference frame\n\\item $v^B$    : linear velocity in the body reference frame\n\\item $q$      : quaternion representing the rigid body orientation\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}\n  \\frametitle{Sensor fusion on the iCub}\n \\begin{eqnarray*}\nm    \\textcolor{red}{\\dot v^B}    + \\omega^B \\times (m       v^B) & = & \\textcolor{red}{f^B_1  + ... + f^B_n} + mg^B \\\\\nI^B \\dot \\omega^B + \\omega^B \\times (I^B \\omega^B) & = & \\textcolor{red}{\\mu^B_1 + ... + \\mu^B_n}\n\\end{eqnarray*}\n\\begin{itemize}\n\\item $I^B$    : inertia in the body reference frame\n\\item $m$      : mass of the rigid body\n\\item \\textcolor{red}{$f^B_i$}  : i-th force expressed in the body reference frame\n\\item \\textcolor{red}{$\\mu^B_i$} : i-th torque expressed in the body reference frame\n\\item \\textcolor{green}{$\\omega^B$}: angular velocity expressed in the body reference frame\n\\item \\textcolor{red}{$\\dot v^B$}    : linear acceleration in the body reference frame\n\\item $q$      : quaternion representing the rigid body orientation\n\\end{itemize}\n\\end{frame}\n\n\\section{Bayesian Network for a Floating Base Rigid Body System}\n\\begin{frame}\n \\frametitle{Bayesian Network for a Floating Base Rigid Body System}\n \n \\centering\n \\begin{tikzpicture}[\n  node distance=1cm and 0cm,\n  mynode/.style={draw,circle,text width=1cm,align=center}\n  ]\n  \\node[mynode] (x) {$x$};\n  \\node[mynode,below=of x] (y) {$y$};\n  \\path (x) edge[-latex] (y);\n  \n  \\node[right=of x, right=0.5cm of x]\n  {\n  $x = \\left[ v^B \\quad \\omega^B \\quad f_o \\quad \\mu_o \\quad f_c \\quad \\mu_c \\right]^T$ \n   };\n   \n   \\node[right=of y, right=0.5cm of y]\n   {\n   $y = \\left[ f_o \\quad \\mu_o \\quad f_c \\quad \\mu_c \\quad \\dot{v}^B \\right]^T$\n   };\n \\end{tikzpicture}\n\n\\end{frame}\n\n\n\\section{The Extended Kalman Filter}\n\\begin{frame}\n  \\frametitle{The Extended Kalman Filter}\n  Given a nonlinear system:\n  \\begin{align}\n   y_k &= h(x) + \\rho_m \\\\\n   x_k &= f(x_{k-1}) + \\rho_p\n  \\end{align}\n  \n  Where $y$, the measurement vector and $x$, the state vector have gaussian uncertainties.\n\n  After linearizing our dynamical system about an estimate of the current state ${x}_{k|k-1}$, the corresponding Extended Kalman Filter can be obtained following a \\textbf{prediction} and \\textbf{update} steps.\n  \\begin{alertblock}{Prediction}\n    $\\mathbf{x}_{k|k-1} = f(\\mathbf{x}_{k-1|k-1})$\n  \\end{alertblock}\n  \n  \\begin{alertblock}{\\textbf{Update}}\n    $\\mathbf{x}_{k|k} = x_{k|k-1} + K_k(y_k - h(\\mathbf{x}_{k|k-1}))$\n  \\end{alertblock}\n\\end{frame}\n\n\\begin{frame}\n  \\frametitle{The Extended Kalman Filter}\n Linearized measurement model: $y = Cx + e$ where:\\\\\n y = \\begin{pmatrix}\n  0& 0& \\mathbf{I}& 0& 0& 0\\\\\n  0& 0& 0& \\mathbf{I}& 0& 0\\\\\n  0& 0& 0& 0& \\mathbf{I}& 0\\\\\n  0& 0& 0& 0& 0& \\mathbf{I}\\\\ \n  S(\\bar{\\omega}_B)& -S(\\bar{V}_B)& \\mathbf{I}& 0& \\mathbf{I}& 0\n \\end{pmatrix} x \n+ \\begin{pmatrix}\n   0\\\\\n   0\\\\\n   0\\\\\n   0\\\\\n   S(\\bar{V}^B)\\bar{\\omega}^B\n  \\end{pmatrix}\n\\end{frame}\n\n\n\\begin{frame}\n  \\frametitle{Extended Kalman Filter results}\n  Linear Velocities smoothing\n\\begin{figure} \n  \\centering \n\t  \\includegraphics[height=0.70\\hsize]{images/png/linVel.png} \n\\end{figure}\n\\end{frame}\n\n\\begin{frame}\n  \\frametitle{Extended Kalman Filter results}\n   Angular velocities smoothing\n\\begin{figure} \n  \\centering \n\t  \\includegraphics[height=0.70\\hsize]{images/png/angVel.png} \n\\end{figure}\n\\end{frame}\n\n\n% \\section{Update Step of the Kalman Filter as a Bayesian Network}\n% \\begin{frame}\n%   \\frametitle{Update Step of the Kalman Filter as a Bayesian Network}\n%   \\textbf{Update Step} $\\leftrightarrow $ \\textbf{Conditional probability of} $\\mathbf{x}_{k|k-1}$ \\textbf{given} $\\mathbf{y}_k$ \\\\\n%   in other words, we can also obtain $\\mathbf{x}_{k|k}$ as:\n%   \\begin{equation}\n%   \\mathbf{x}_{k|k} = E[x_k \\; \\vert \\; y_k, x_{k|k-1}]\n%   \\end{equation}\n%   Where:\n%   \\begin{align}\n%   \\mathbf{y}_k \\vert_{x_{k|k-1}} &\\backsim \\mathcal{N}(C\\mathbf{x}, R) \\\\\n%   \\mathbf{x} &\\backsim \\mathcal{N}(x_{k|k-1},P_{k|k-1})\n%   \\end{align}\n%   \n%   And $\\mathbf{y}$ has been linearized as: $y=Cx + e$\n% \\end{frame}\n\n\n% \\section{Solving a Linear System with a Bayesian Network}\n% \\begin{frame}\n%   \\frametitle{Solving a Linear System with a Bayesian Network}\n%   Given a linear system $\\mathbf{Ax} = \\mathbf{b}$, the computation of the solution vector $\\mathbf{x^*}$ is identical to the inference of the vector of marginal means $\\mu = \\{\\mu_1, ... , \\mu_n\\}$ over the graph $\\mathcal{G}$ with the associated Joint Gaussian Probability Density Function\n%   \n%  \\begin{equation}\n%   p(\\mathbf{x}) \\backsim \\mathcal{N}(\\mu \\triangleq \\mathbf{A}^{-1}\\mathbf{b}, \\mathbf{A}^{-1})\n%  \\end{equation}\n% \n%  The mean of this probability distribution is the target solution. The solution of the system implies inferring the marginal densities:\n%  \n%  \\begin{equation}\n%   p(x_i) \\backsim \\mathcal{N}(\\mu_i = \\{\\mathbf{A^{-1}}\\mathbf{b}\\}_i,P^{-1}_i = \\{\\mathbf{A}^{-1}_{ii})\n%  \\end{equation}\n%  \n%  Where $\\mu_i$ and $P_i$ are the marginal mean and inverse variance.\n% \n% %  Reference: Gaussian Belief Propagation Solver for Systems of Linear Equations. Ori Shental 1 , Paul H. Siegel and Jack K.   Wolf, Danny Bickson and Danny Dolev\n% \\end{frame}\n\n\\end{document}\n", "meta": {"hexsha": "e37dcd9cd0a08dc677d53a47cecfd05402033877", "size": 6900, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ICRA2015/VVV14Pres/EKFforDynamicalSystems.tex", "max_stars_repo_name": "jeljaik/extended-kalman-filter", "max_stars_repo_head_hexsha": "b8d2d510291bc67b503eb799f18fe459dfe6a4f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2015-04-10T13:04:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T09:42:04.000Z", "max_issues_repo_path": "ICRA2015/VVV14Pres/EKFforDynamicalSystems.tex", "max_issues_repo_name": "jeljaik/extended-kalman-filter", "max_issues_repo_head_hexsha": "b8d2d510291bc67b503eb799f18fe459dfe6a4f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32, "max_issues_repo_issues_event_min_datetime": "2015-02-06T14:59:44.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-19T17:41:01.000Z", "max_forks_repo_path": "ICRA2015/VVV14Pres/EKFforDynamicalSystems.tex", "max_forks_repo_name": "jeljaik/extended-kalman-filter", "max_forks_repo_head_hexsha": "b8d2d510291bc67b503eb799f18fe459dfe6a4f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 36, "max_forks_repo_forks_event_min_datetime": "2015-09-09T10:18:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T09:51:19.000Z", "avg_line_length": 32.0930232558, "max_line_length": 293, "alphanum_fraction": 0.6695652174, "num_tokens": 2459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.3434701755844631}}
{"text": "\\section{Debugging}%\n\\label{sec:debugging}%\n\\subsection{Net Weights}\n\\label{subsec:net_weights}\n%\nIn an attempt to better understand the source of this unexpected behavior,\nmultiplicative weights (referred to as `nw' for `network weights' in\nFig.~\\ref{fig:bad_convergence}) were introduced to scale the individual\ncontribution from each of the `learned' functions $S$, $T$, and $Q$,\nexplicitly:\n%\n\\begin{align}\n  S &\\rightarrow \\alpha_{S}\\, S \\\\\n  T &\\rightarrow \\alpha_{T}\\, T \\\\\n  Q &\\rightarrow \\alpha_{Q}\\, Q.\n\\end{align}\n%\nBy varying each of these weights individually allows us to selectively `tune'\nhow much each of these functions contribute when running inference on the\ntrained model.\n%\nNote that in the limit $\\alpha_{S}, \\alpha_{T}, \\alpha_{Q} \\rightarrow 0$, we\nrecover generic HMC, and as can be seen in Fig.~\\ref{fig:bad_convergence},\nthe error in the average plaquette $\\delta_{\\phi_{P}} \\simeq 0$, as expected.\n%\nAs an additional sanity check, we looked at how the error in the average\nplaquette behaves for different values of the weights $\\alpha_{i}$ ($i = S, T,\nQ$).\n%\nExplicitly, beginning with $\\vec{\\alpha} \\equiv [\\alpha_{S}, \\alpha_{Q},\n\\alpha_{T}] = [0, 0, 0]$, we increase each of the weights one by one and compute\nthe average value of the plaquette difference.\n%\nFor example, the blue line (Transformation $(Q)$ function) in\nFig.~\\ref{fig:plaq_diff_vs_net_weights} was obtained by keeping both\n$\\alpha_{S}$ and $\\alpha_{T}$ fixed and $0$ and varying $\\alpha_{Q} \\in\n[0.1, 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 5.0]$, and similarly for $\\alpha_{S}$ and\n$\\alpha_{Q}$.\n%\n\\begin{figure}\n  \\centering\n  \\begin{subfigure}[t]{0.48\\textwidth}\n    \\caption{$N_{LF} = 10$}\n    \\includegraphics[width=\\textwidth]{new_figures/plaq_error/plaq_diff_vs_net_weights_lf10.pdf}\n  \\end{subfigure}\n  % \\vspace{2pt}\n  % \\hfill\n  % \\centering\n  \\begin{subfigure}[t]{0.48\\textwidth}\n    \\caption{$N_{LF} = 12$}\n    \\includegraphics[width=\\textwidth]{new_figures/plaq_error/plaq_diff_vs_net_weights_lf12.pdf}\n  \\end{subfigure}\n  % \\vspace{2pt}\n  \\begin{subfigure}[b]{0.48\\textwidth}\n    \\caption{$N_{LF} = 16$}\n    \\includegraphics[width=\\textwidth]{new_figures/plaq_error/plaq_diff_vs_net_weights_lf16.pdf}\n  \\end{subfigure}\n  \\caption{Plaquette difference $\\delta_{\\phi_{P}}$ for different values of the\n    net weights $\\vec{\\alpha} \\equiv [\\alpha_{S}, \\alpha_{T}, \\alpha_{Q}]$.\n    Note that $\\delta_{\\phi_{P}} \\rightarrow 0$ as $\\vec{\\alpha} \\rightarrow\n  [0, 0, 0]$, as expected.}%\n\\label{fig:plaq_diff_vs_net_weights}\n\\end{figure}\n%\nThese results seem to indicate that each of the individual functions contribute\nseparately to the error, with the scaling ($S$) and translation ($T$) functions\nhaving the largest effect.\n%  }}}\n\\subsection{Updates (11/11/2019)}\n\\begin{todolist}\n  \\item[\\done] Ensure reproducibility across training/inference runs when\n    using same input parameters.\n    \\begin{itemize}\n      \\item Essential for debugging the bias in the average plaquette.\n      \\item Somewhat tricky problem due to the fact that tensorflow \n        has two distinct methods of specifying a seed: graph-level and\n        operation-level. Additionally, when using horovod for distributed\n        training across multiple ranks, we must ensure that each rank gets a\n        different seed otherwise they will all be training identical copies of\n        the model.\n    \\end{itemize}\n\n  \\item[\\done] Implement reversibility checker that ensures that the L2HMC\n    dynamics (i.e.\\ the augmented HMC sampler) is reversible.\n    \\begin{itemize}\n      \\item Starting with $\\xi = (x, v, d)$, run the dynamics in the forward\n        direction to get $\\xi^{\\prime}$. If $\\mathbf{L}_{\\theta}\n        \\xi =  \\xi^{\\prime}$, and $\\mathbf{F} \\xi = \\mathbf{F} (x, v, d) = (x,\n        v, -d)$, then a complete (invertible) update step can be written as\n        $\\mathbf{FL}_{\\theta}\\xi = \\xi^{\\prime}$.\n        %\n      \\item If our sampler is reversible, running the dynamics backwards on\n        $\\xi^{\\prime}$ should return us to the original state $\\xi$. \n        %\n        \\begin{equation}\n          \\mathbf{FL}_{\\theta}\\mathbf{FL}_{\\theta} \\xi = \\xi\n        \\end{equation}\n    \\end{itemize}\n\n  \\item[\\done] Try increasing floating point precision (\\texttt{tf.float32 -->\n    tf.float64}) (\\textbf{\\textcolor{red}{Error still present.}}) \n\n  \\item[\\done] Try anti-symmetric Gaussian Mixture Model and see if the trained\n    model is an accurate representation of the target distribution (e.g.\\ by\n    looking at the locations of the means).\n    % \\href{https://l2hmc.slack.com/archives/CK0SMC6NS/p1567623563026900}{(link\n    % to post)}.\n\n  \\item[\\done] At James' suggestion, we decided to look at the\n    kinetic/potential energies and the Hamiltonian at the beginning and end of\n    each trajectory (\\textbf{\\textcolor{red}{Solved! Issue was being caused by\n    unexpected resampling of the momentum}}).\n    % Fig~\\ref{fig:potential_energy},~\\ref{fig:kinetic_energy},~\\ref{fig:hamiltonian}).\n  \\end{todolist}\n\\section{GMM Results}%\n\\label{sec:gmm_results}\n\\begin{figure}[htpb] \n  \\centering \n  \\includegraphics[width=0.5\\textwidth]{updates/single_chain}\n  \\caption{Inference run shown for a single chain using the L2HMC\n  sampler trained on this gaussian mixture model.}%\n  \\label{fig:gmm_single_chain}\n\\end{figure}\n\n\\begin{figure}[htpb] \n  \\centering \n  \\begin{subfigure}[t]{0.48\\textwidth}\n    \\caption{L2HMC samples}\n    \\includegraphics[width=\\textwidth]{updates/means_hist_observed}\n  \\end{subfigure}\n  % \\hfill\n  \\begin{subfigure}[t]{0.48\\textwidth}\n    \\caption{true target distribution}\n    \\includegraphics[width=\\textwidth]{updates/means_hist_true}\n  \\end{subfigure}\n  \\caption{Histograms of $\\langle x\\rangle$ and $\\langle y\\rangle$ in this\n  two-dimensional target space.}\n\\end{figure}\n% }}}\n", "meta": {"hexsha": "9812510b831096aead1754c5194e8ad1de051bb0", "size": 5801, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/debugging/debugging.tex", "max_stars_repo_name": "saforem2/l2hmc-qcd", "max_stars_repo_head_hexsha": "b5fe06243fae663607b6c88e71373b68b19558fc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2019-04-18T18:50:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T18:30:48.000Z", "max_issues_repo_path": "doc/debugging/debugging.tex", "max_issues_repo_name": "saforem2/l2hmc-qcd", "max_issues_repo_head_hexsha": "b5fe06243fae663607b6c88e71373b68b19558fc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2019-09-09T21:10:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T17:43:51.000Z", "max_forks_repo_path": "doc/debugging/debugging.tex", "max_forks_repo_name": "saforem2/l2hmc-qcd", "max_forks_repo_head_hexsha": "b5fe06243fae663607b6c88e71373b68b19558fc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-10-31T02:25:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-25T00:49:14.000Z", "avg_line_length": 41.4357142857, "max_line_length": 96, "alphanum_fraction": 0.7021203241, "num_tokens": 1737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160666, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.34342015362247647}}
{"text": "\\chapter{Long-term surface water change detection}\n\\label{ch5}\n\n\\begin{abstract}\n\tMethods to detect long-term surface water changes are discussed. A simple method based on reflectance percentile composites and linear regression is presented. As an example, Siling Lake in the Tibetan Plateau is used as a study area. The advantages and drawbacks of the method are discussed.\n\t\n\t\\begin{center}\n\t\t\\begin{tikzpicture}[every node/.style={inner sep=0,outer sep=0}]\n\t\t\\node[draw=none,shade,blur shadow={shadow blur steps=5}] {\n\t\t\t\\includegraphics[width=3in]{01.4-change-detection/figures/change-detection-dubai}\n\t\t};    \n\t\t\\end{tikzpicture}\n\t\\end{center}\n\t\n\t\\textbf{Keywords:} $M_3$, reflectance percentiles, NDWI, linear regression, long-term surface water changes.\n\t\n\\end{abstract}\n\n{\n\t\\setlength{\\parindent}{0pt}This chapter is based on \\bibentry{donchyts2016earth}.\n}\n\n\n%% Start the actual chapter on a new page.\n\\newpage\n\n\\section{Introduction}\n\\dropcap{A}{s} we have seen in the previous three chapters, accurate surface water detection is a complex task and may require many steps. However, different land use changes may occur at different temporal scales. If we are interested only in long-term (inter-annual) land-use changes, more generic statistical methods can be applied to detect these changes. With sufficient observations available and under the assumption that statistics of reflectance values for different years remain the same, we can use relatively simple methods, when compared to those discussed in the Chapter \\ref{ch4}. \n\nThe first step that should be done when analyzing optical passive sensor satellite imagery is the elimination of clouds and cloud shadow effects. Cleaning images from cloud, cloud shadows, and snow can be a challenging and time-consuming process, especially when images partially covered by clouds need to be considered. Many methods were developed to do this properly, as has been discussed in chapters \\ref{ch2}, \\ref{ch3}, and \\ref{ch4}. These methods can be used to construct completely cloud-free images, or to extract information required to analyze temporal changes in different land cover classes. \n\nAs an alternative to this, we can generate inter-annual composites directly from the top-of-atmosphere or surface reflectance values. In recent years, this approach was used in \\citet{Hansen2013} to study forest cover changes by employing a combination of metrics, such as: \n\\begin{enumerate*}[label=(\\emph{\\alph*})]\n\t\\item selected percentile values\n\t\\item mean reflectance values for selected percentile ranges\n\t\\item slope of linear regression of band reflectance values versus image date\n\\end{enumerate*}. Furthermore, they make use of supervised classification methods based on decision trees to relate these metrics to homogeneously varying subsets of data.\n\nHere, a similar approach to estimate long-term surface water changes is introduced. However, instead of developing multiple metrics like in \\citet{Hansen2013}, a single combined metric employing percentiles is used to estimate average cloud-free reflectance values and the slope of linear regression to identify pixels where long-term changes have been occurring. \n\nThe resulting method is also more resource efficient because applying linear regression after averaging is cheaper to compute. The cost of applying linear regression directly to reflectance values is $O(n^3)$, and the cost to calculate the average value for every pixel is $O(n)$, where n is the number of analyzed images. The $O$ notation is frequently used in computer science to indicate scalability of the algorithm with the growth of the dataset. By employing a two-step approach, surface water changes can be estimated in almost $O(n)$ time, making it attractive to be applied across multiple sensors, assuming similarity in reflectance values among different satellite sensors for some spectral bands. For surface water change studies, the most used spectral index is \\gls{NDWI}. The index uses near-infrared and green bands. These bands have similar spatial and spectral resolution across multiple Landsat missions and seem to be in agreement with regards to spectral response and spectral resolution, except for Landsat 8. For Landsat 8, the OLI sensor covers the thinner spectral range for the near-infrared band when compared to TM and ETM+ sensors used by Landsat 4, 5, and 7 \\citet{roy2016characterization, angal2014cross}. A detailed comparison of spectral responses between Landsat 5 and 7 can be found in \\citet{teillet2001radiometric} and between Landsat 7 and 8 in \\citet{flood2014continuity}. Additionally, the literature says that data produced from Landsat was cross-calibrated to ensure consistency and continuity of values between different missions \\citet{mishra2014radiometric}. This makes combining images across different Landsat sensors, and the use of statistical methods to process their values, very promising.\n\n\\begin{figure}[H]\n\t\\includegraphics[width=1.0\\textwidth,left]{01.4-change-detection/figures/aral}\n\t\\caption{Aral Sea, Uzbekistan. False-color reflectance percentile composite (swir1, nir, green, 20\\%). The red circle indicates the location where reflectance and \\gls{NDWI} values shown on charts were plotted. The composite images and the time series were computed from 4325 Landsat scenes between 1984 and 2017. \\opt{source}{Source: \\url{https://code.earthengine.google.com/c1ccc09c6b5e7d73bd3a3601f8edfaf3}}}\n\t\\label{fig:ch4-aral-sea}\n\\end{figure}\n\nSurface water is very dynamic and may change on a daily, monthly, and annual basis. To estimate long-term, inter-annual surface water changes from raw satellite images, we have to exclude effects caused by both clouds and by intra-annual or seasonal variations, assuming these changes remain the same across years. Examples of intra-annual changes can be seasonal changes in surface water due to natural processes, a regular water cycle, changes of surface water levels caused by tidal effects in coastal areas, and variability in surface water levels due to man-made activities, such as the operation of reservoirs, which may also cause surface water changes in the downstream rivers. Long-term surface water changes may be due to natural changes of water boundaries, such as erosion or accretion, natural changes caused by climate changes, or manmade changes in rivers or coastal zones (embankments, land reclamation, construction of reservoirs). \n\nIn reality, a combination of these surface water changes may occur and interfere with each other, making the task of surface water change detection extremely difficult.\n\nTo demonstrate the variability of reflectance values in different bands for an area where both long and short-term changes took place, a long-term time series in the middle of the Aral Sea is obtained for pixels which have dried up during the past few decades, as shown in Figure \\ref{fig:ch4-aral-sea}. This area has faced dramatic changes regarding surface water and, as can be seen from the reflectance values, this has influenced both reflectance and corresponding \\gls{NDWI} value changes. While it would be possible to detect the trend of \\gls{NDWI} values from the raw reflectance value time series, doing this may be less efficient, mainly because \\gls{NDWI} values for many pixels corresponding to clouds may look very similar to the values corresponding to water. Additionally, it would require significantly more computing resources.\n\n\\section{Long-term surface water change detection}\n\nTo address long-term surface water changes, we can first try to exclude short-term variability of reflectance values by computing average images for a long time intervals, excluding effects of clouds and cloud shadows in this way. By estimating this type of composite images for multiple time intervals, followed by the application of spectral water indices, such as \\gls{NDWI}, we should be able to reconstruct long-term variability of the surface water changes, which will be reflected in the variability of the \\gls{NDWI} values. One of the important questions arising using this method is how to select the best percentile, allowing to minimize the effect of clouds and cloud shadows, and at the same time, avoiding the appearance of cloud shadows in the images. \n\nThe method will work only if a sufficient number of observations is available. A large number of images is required to ensure that the distribution of values, used to compute reflectance percentile composites, converges to the actual distribution representing different land or atmosphere values for a given location  is based on similar distributions. Ideally, the resulting percentile should look the same for two areas when no long-term surface water changes take place. \n\nBecause surface water has a very distinctive spectral signature, with very low reflectance values in almost all bands, the presence or absence of water in a given pixel will be reflected in the final distribution represented as a probability distribution function (PDF) or a cumulative distribution function (CDF) for a given location.\n\n\\afterpage{%\n\t\n\t\\begin{figure}\n\t\t\\includegraphics[width=1.0\\textwidth,left]{01.4-change-detection/figures/Tibet-lake-changes}\n\t\t\\caption{Siling Lake, Tibetan Plateau, China. Two reflectance composite images at the top-left show how the lake looked like in 80's (left) and how it looks like today (right). The blue color indicates submerged land due to climate changes. \\opt{source}{Source: \\url{https://code.earthengine.google.com/87d0057d8b3d28817b1da7cfc1bd6b6e}}}\n\t\t\\label{fig:ch4-tibet-lake}\n\t\\end{figure}\n\t\n\t\\begin{figure}\n\t\t\\includegraphics[width=1.0\\textwidth,left]{01.4-change-detection/figures/Tibet-time-series}\n\t\t\\caption{Estimating surface Siling Lake, Tibetan Plateau, China. The actual TOA reflectance values (left-top), annually-averaged (20\\%) reflectance values (left-middle) and \\gls{NDWI} values, estimated from annually-averaged reflectance values (left-bottom). The three charts on the left indicate values and distributions of the sun parameters for the images used to compute these values.}\n\t\t\\label{fig:ch4-tibet-lake-time-series}\n\t\\end{figure}\n\t\n\t\\clearpage\n}\n\nTo demonstrate the main steps used in the methods, surface water changes which have occurred around the Siling Lake are analyzed - one of the lakes of Tibetan Plateau, China. In the last few decades, an enormous area of new surface water has been created due to climate changes. Figure \\ref{fig:ch4-tibet-lake} shows the final estimate for the submerged land, equal to $22.5 km^2$. \n\nA straightforward and efficient way to estimate long-term surface water changes may be to use a two-step approach. First, the intensity percentile composites are computed for all temporal intervals $T$ used for the change detection analysis:\n\n\\begin{equation}\nF(\\rho) = \\int_{-\\infty}^{\\rho^i} P(\\rho)d\\rho\n\\end{equation}\n\nwhere $F$ - cumulative distribution function, the superscript index $i$ denotes the $i^{th}$ percentile, $\\rho$ - reflectance values for a given band.\n\nThen, for every percentile reflectance value $\\rho^i$, the spectral index is computed as an image:\n\n\\begin{equation}\nI = \\frac{\\rho_{green}^i-\\rho_{nir}^i}{\\rho_{green}^i+\\rho_{nir}^i} \\\\\n\\end{equation}\n\nAfter that, the linear regression is performed on a set of all index values for all intervals $T$:\n\n\\begin{equation}\nI = \\beta_0 + \\beta_1 T + \\epsilon\n\\end{equation}\n\nThe resulting slope of the linear regression $\\beta_1$ is then analyzed to identify pixels, where significant surface water changes took place. \n\nUsually, the percentile is determined empirically and corresponds to low reflectance values, but not too low, to avoid confusing water with cloud shadows, which can also be very dark for green and nir (or swir) bands used to estimate spectral indices. For those pixels, where the slope $\\beta_1$ of the linear regression is significant. The spectral index values $I$ are also tested to exclude false positive changes, detected for images where most images correspond to water or land:\n\n\\begin{equation}\n\\begin{split}\n\\begin{aligned}\nI &= min\\left(I, I_{min}^{water}\\right) \\\\\nI &= max\\left(I, I_{max}^{land}\\right) \n\\end{aligned}\n\\end{split}\n\\label{eq:water-land-suppression}\n\\end{equation}\n\nwhere $I_{min}^{water}$ and $I_{max}^{land}$ indicate minimum and maximum values of the spectral index to be considered as water and land correspondingly. The equation \\ref{eq:water-land-suppression} is applied for every interval used during temporal averaging.\n\nThe first equation of the \\ref{eq:water-land-suppression} allows to filter pixels, where the slope of the regression is significant, with all values still belonging to water. The second equation of the \\ref{eq:water-land-suppression} does the same to eliminate locations where all of the temporal intensity values belong to the land.\n\nAdditionally, \\gls{NDVI} vegetation index is used similarly to remove locations, where, for example, deforestation took place. In this case, \\gls{NDWI} values may also change significantly in time, but the actual changes do not correspond to surface water changes.\n\n\\afterpage{%\n\t\n\t\\begin{figure}\n\t\t\\includegraphics[width=1.0\\textwidth,left]{01.4-change-detection/figures/images_real}\n\t\t\\caption{Examples of false-color (swir1, nir, green) images from 1998 acquired by Landsat TM sensor for Siling Lake, Tibetan Plateau, China. \\opt{source}{Source: \\url{https://code.earthengine.google.com/882ab2929f536676d56bc79cbc895ded}}\n\t\t}\n\t\t\\label{fig:ch4-tibet-lake-false}\n\t\\end{figure}\n\t\n\t\\begin{figure}\n\t\t\\includegraphics[width=1.0\\textwidth,left]{01.4-change-detection/figures/images_percentiles}\n\t\t\\caption{False-color (swir1, nir, green) reflectance percentile images estimated from 751 images acquired by multiple NASA Landsat missions during 1984-2017, Siling Lake, Tibetan Plateau, China}\n\t\t\\label{fig:ch4-tibet-lake-percentiles}\n\t\\end{figure}\n\t\\clearpage\n}\n\nThe actual number of images available need to be adjusted based on the cloud frequency present for a given area. For the area around this lake, the average cloud frequency is 13\\%, with relatively low intra-annual variation, as estimated by \\citet{wilson2016remotely} from MODIS images. However, for some areas on Earth, mainly near the equator, 95\\% of the images may be covered by clouds. This means, that to apply this method, many more images need to be analyzed. In this case, only long-term surface water changes may be estimated using passive optical sensors. \n\n% t-test using regression \\url{https://en.wikipedia.org/wiki/Student%27s_t-test#Slope_of_a_regression_line}\n% non-parametric tests \\url{ftp://cran.r-project.org/pub/R/web/packages/trend/vignettes/trend.pdf}\n\n% CDF sun parameters mismatch, topographic errors \\url{https://code.earthengine.google.com/c9ed4d65ee90db7d4944e4c257969e1b}\n% \\url{https://code.earthengine.google.com/5ddaeea0946642afe23d7557c3c0c657}\n\n\\section{Topographic noise for inconsistent image collections}\nEven though the method described in Chapter \\ref{ch5} allows detection of surface water changes at high accuracy, a substantial commission error may occur in mountain regions. These errors are caused mainly by combined errors of elevation and azimuth, causing differences in hill shadows in composite images, used to detect surface water changes. For global analysis, most of these errors were eliminated by masking-out the final surface water changes images with the topographic index derived from \\gls{HAND}. The topographic mask, constructed by HAND < 40m, was used to filter out these errors. The \\gls{HAND} dataset used for the processing was generated from 30m \\gls{SRTM} and some auxiliary 90m datasets to cover areas where it was not acquired (>60 degree north latitude) \\citet{donchyts2016hand}. However, for very accurate surface water change estimates this may also result in omission errors in the areas when DEM values are incorrect. For the time being, no free high-resolution DEM exists to be used as a topographic index (via \\gls{HAND}). Therefore, the Aqua Monitor website does not perform this correction during on-the-fly estimation of surface water changes. This may change in future versions, when a more appropriate method is introduced.\n\n\\begin{figure}\n\t\\centering\n\t\\includegraphics[width=1\\textwidth]{01.8-aqua-monitor/figures/problem1}\n\t\\caption{False-positive composites (swir1, nir, green) and surface water changes commission errors due to inconsistent sun parameters in the samples used to compute changes in the hilly areas (2000-2015). Top: upstream of the Lake Mead (\\href{http://aqua-monitor.appspot.com/?from=2000&to=2013&view=36.103119715292486,-113.93795967102045,13z&max_doy=365}{36.10, -113.90}); bottom: river near Yogongxiang, China (\\href{http://aqua-monitor.appspot.com/?mode=dynamic&from=2000&to=2013&view=30.269128374988604,94.89677429199217,12z&max_doy=365&averaging_months1=36&averaging_months2=36}{30.27, 94.90}).}\n\t\\label{fig:am-topographic-errors}\n\\end{figure}\n\nExamples of these errors are demonstrated in Figure \\ref{fig:am-topographic-errors}. \n\nThe same errors were reported in the \\citet{Hansen2013} dataset, which uses similar methods to estimate surface water changes (interval mean percentile composites versus percentile composites in Aqua Monitor).\n\nA time consuming approach to eliminate these errors could be to perform topographic correction on every image before passing them to the change detection algorithm. However, this may significantly increase the amount of resources needed, making this type of analysis hardly achievable today.\n\n\n\\section{Conclusions and Discussion}\n\nThe method presented in this chapter showed surprisingly good performance for most of the places on Earth and was used to analyze global surface water changes over the last thirty years. Despite its simplicity, the method can very accurately detect long-term surface changes. Additionally, it is easy to implement using the Google Earth Engine parallel processing platform.\n\nAnother advantage of the method is that it is less resource intensive when compared to a more streamlined approach to detecting surface water changes. Hence it can be used for large planetary-scale studies and for a wide range of users, which is demonstrated in Chapter \\ref{ch6}. For example, all images are first classified e.g. using supervised machine learning methods, and then the changes are computed from the resulting thematic maps.\n\nHowever, it may be difficult to reliably detect surface water changes when:\n\n\\begin{enumerate}[label=(\\alph*)]\n\t\\item \\label{enum:changes-low-count} the number of images used to compute percentiles is low\n\t\\item \\label{enum:changes-complex-trend} surface water changes follow a more complex pattern than a one directional trend\n\t\\item \\label{enum:changes-multple-classes} multiple land-use changes are present, represented by low reflectance values but irrelevant to surface water changes\n\t\\item \\label{enum:changes-topo} complex topographic conditions combined with unequally distributed sun parameters in different time intervals\n\\end{enumerate}\n\nSome of these issues can be easily addressed, for example, by changing empirically chosen percentiles to ensure one captures pixels free from cloud and snow effects.\n\nAdditionally, image samples used to compute percentiles can also be selected to only represent certain seasons, where some of the effects are less present, filtering image collections by day-of-year or by sun parameters, to avoid the most evident topographic effects. \n\nThe methods presented here work best when reflectance values, representing complex land-use and atmospheric changes, are similarly distributed. While for surface water this is frequently true, it may be less trivial under very complex land-use change \\ref{enum:changes-multple-classes}. To detect these kind of changes automatically, additional inference steps may be required, for example, where different patterns can be recognized in the distributions such as those presented in Chapter \\ref{ch4}, Figure \\ref{fig:prob-sampled-water-cloud-snow}.\n\nWhile linear regression may be a good choice to detect monotonic long-term changes, surface water may follow much more complex trends, requiring the use of more complex methods to capture them. For example, logistic regression can be used instead of linear regression to detect abrupt changes such as construction or decommissioning of reservoirs, or to analyze autocorrelation to detect recurring surface water changes.\n\nWith the increasing number of satellite images available, the use of statistical methods may be a powerful instrument, providing an easy way for change or anomaly detection before the use of more complex methods.\n\n\n", "meta": {"hexsha": "a289d442fc57093e16aaeef9862e012c538b5415", "size": 20662, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "01.4-change-detection/change-detection.tex", "max_stars_repo_name": "songyingxu/thesis", "max_stars_repo_head_hexsha": "b4f027f6d5362c61a2ca5b76d99b6563466610cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2018-06-22T20:41:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-19T11:57:16.000Z", "max_issues_repo_path": "01.4-change-detection/change-detection.tex", "max_issues_repo_name": "Yorklii/thesis", "max_issues_repo_head_hexsha": "b4f027f6d5362c61a2ca5b76d99b6563466610cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "01.4-change-detection/change-detection.tex", "max_forks_repo_name": "Yorklii/thesis", "max_forks_repo_head_hexsha": "b4f027f6d5362c61a2ca5b76d99b6563466610cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2019-05-02T05:50:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T14:45:59.000Z", "avg_line_length": 108.7473684211, "max_line_length": 1741, "alphanum_fraction": 0.8010841158, "num_tokens": 4725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878414043814, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.34342014574354174}}
{"text": "\\section{Essential ML ideas}\n\\smallskip \\hrule height 2pt \\smallskip\n\n\\begin{itemize}\n\t\\item Never ever \\underline{ever} touch the test set\n\t\\item You know you are overfitting when there is a big test between train and test results.  E.g. metric of percent wrong. \n\t\\item Need to be comfortable taking a hit on fitting accuracy if you can get a benefit on the result.\n\t\\item Bias vs variance trade-off.  \n\t\tHigh bias when the model is too simple \\& doesn't fit the data well.  \n\t\tHigh variance is when small changes to the data set lead to large solution changes. \n\t\\item If features are non discriminative in the beginning, they don't work for any classifier.  % week 4 reminder\n\t\\item Your feature vector often has a smaller dimension that the feature space.    % week 4, Friday. \n\t\tIf you have too long of a feature vector, you may get overfitting. \n\t\\item You need to prevent the optimizer from getting an easy way out.  % week 7 audio\n\t\\item Whenever we are building a discriminative classifier, \n        \t\twe should not expect it to reason about things it has never seen before\n    \t\tYou can't classify on something that has only seen + points. \n    \t\tThe classifier needs to see some + and some - or it will fail miserably.   % week 8 audio\n\t\\item We should always avoid making hard decisions early.  % week 8 audo. \n\t\t E.g. don't put a lot of trust in classifiers early on in bagging. \n\\end{itemize}\n\nYou can do $l_2$ normalization for a feature vector to get a unit vector:   % week 6 audio. \n\tConvert $x$ to $\\hat{x}$ so that if you form $||\\hat{x}||_2^2 = 1$\n\tCan also do $l_1$  \n", "meta": {"hexsha": "610c53efe0d1a20057485fd557a215f391a518f2", "size": 1591, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/essential_ideas.tex", "max_stars_repo_name": "JanetMatsen/Machine-Learning", "max_stars_repo_head_hexsha": "12e1f701eb7de89b97d5caffe86b0267731e4cb5", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2016-02-07T23:35:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-26T05:13:33.000Z", "max_issues_repo_path": "tex/essential_ideas.tex", "max_issues_repo_name": "JanetMatsen/Machine-Learning", "max_issues_repo_head_hexsha": "12e1f701eb7de89b97d5caffe86b0267731e4cb5", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/essential_ideas.tex", "max_forks_repo_name": "JanetMatsen/Machine-Learning", "max_forks_repo_head_hexsha": "12e1f701eb7de89b97d5caffe86b0267731e4cb5", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2016-08-29T00:15:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-06T22:36:19.000Z", "avg_line_length": 61.1923076923, "max_line_length": 124, "alphanum_fraction": 0.7297297297, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832354982647, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.34334891129283307}}
{"text": "In this section, we discuss dynamic steady-state power and temperature analysis\nunder process variation. Unlike transient analysis, this analysis cannot be done\none time step at a time, since the repetitive workload needs to be taken into\naccount at once in order to calculate the corresponding dynamic steady state.\nThus, similarly to the contrast between \\sref{transient-analysis} and\n\\sref{dynamic-steady-analysis}, the solutions in \\sref{chaos-transient-analysis}\nand this section differ. However, they still rely on the same methodology\noutlined in \\sref{chaos-uncertainty-analysis} and shown in\n\\fref{chaos-overview}.\n\n\\subsection{\\problemtitle}\n\nThe system model is the same as the one in \\sref{chaos-transient-analysis}. The\nonly difference is that it is more convenient to define the power model as\nfollows:\n\\begin{equation} \\elab{chaos-power-model-bulk}\n  \\mp = \\f(\\vu, \\mq).\n\\end{equation}\nThe function $\\f: \\real^\\nu \\times \\real^{\\np \\times \\ns} \\to \\real^{\\np \\times\n\\ns}$ is supposed to return the periodic power profile that corresponds to the\nperiodic workload being analyzed.\n\n\\inputalgorithm{chaos-dynamic-steady-solution-iterative}\nThe solution to probabilistic dynamic steady-state analysis is based on the\ndeterministic one presented in \\sref{dynamic-steady-solution}. The power,\ntemperature, and other vectors that appear in \\sref{dynamic-steady-solution}\nbecome stochastic in the present context, which also concerns the boundary\ncondition given in \\eref{dynamic-steady-condition}. The pseudocode for a\nprocedure that delivers \\mq for a fixed \\vu is listed in\n\\aref{dream-dynamic-steady-solution}. The algorithm does not take account of the\ninterdependence between power and temperature; however, this interdependence can\nbe addressed via one of the techniques presented in \\sref{power-temperature}. In\nthis section, we use the iterative approach illustrated in\n\\aref{dream-dynamic-steady-solution-iterative}. For clarity, this algorithm is\nrewritten here as shown in \\aref{chaos-dynamic-steady-solution-iterative}; the\nmain difference is that the calculation of power on line~3 is now based on\n\\eref{chaos-power-model-bulk}.\n\n\\begin{remark}\nThe application of the linear approximation described in\n\\sref{power-temperature} is problematic in this case. This technique is suitable\nwhen the only varying parameter is temperature, and all other parameters have\nnominal values. In that case, it is relatively easy to decide on a\nrepresentative temperature range and apply a curve-fitting procedure. In this\ncase, however, the power model has multiple parameters that range far from their\nnominal values.\n\\end{remark}\n\nTo recapitulate, the quantity of interest \\g in \\fref{chaos-overview} is the\ndynamic steady-state power and temperature profiles, which are denoted by \\mp\nand \\mq, respectively. The calculation of this quantity is shown in\n\\aref{chaos-dynamic-steady-solution-iterative}.\n\n\\subsection{Surrogate Construction}\n\nAt Stage~3 in \\fref{chaos-overview}, the procedure delineated in\n\\sref{chaos-construction} is applied to\n\\aref{chaos-dynamic-steady-solution-iterative} from Stage~1 with respect to the\noutput of Stage~2. Concretely, \\aref{chaos-dynamic-steady-solution-iterative} is\nutilized inside \\aref{chaos-construction} via Algorithm~G. In this case,\nAlgorithm~G calls \\aref{chaos-dynamic-steady-solution-iterative} and returns \\mp\nor \\mq or both, depending on what is actually needed for the subsequent\ncalculations, in a suitable format.\n\nSuppose, for instance, that the designer is interested in analyzing solely the\ndynamic steady-state temperature profile \\mq. Following\n\\rref{chaos-multidimensional-output} concerning vector-valued quantities, \\g is\ntreated as an $\\np \\ns$-element row vector, in which case each coefficient\n$\\hat{\\g}_{\\vi}$ in \\eref{chaos-expansion} is also such a vector. The projection\nmatrix, which is defined in \\eref{chaos-projection-matrix}, and\n\\aref{chaos-construction} should be reinterpreted accordingly: \\vg is an $\\nq\n\\times \\np \\ns$ matrix whose row~$j$ is \\mq computed at point~$j$ of the\nquadrature in \\eref{chaos-coefficient} and reshaped into a row vector.\nSimilarly, $\\hat{\\vg}$ should be understood as an $\\nc \\times \\np \\ns$ matrix\nwhose row~$i$ is coefficient~$i$ of the expansion in \\eref{chaos-expansion}.\nRecall that a certain ordering is assumed to be imposed on quadrature points and\npolynomial terms.\n\nThe constructed \\ac{PC} expansion can now be post-processed as required, which\nis already the topic of Stage~4 in \\fref{chaos-overview}; see\n\\sref{chaos-processing}.\n", "meta": {"hexsha": "54b1e7d6be8202d91625f443d91fcd938f669bb4", "size": 4554, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "include/uncertainty/process/development/dynamic-steady-analysis.tex", "max_stars_repo_name": "IvanUkhov/thesis", "max_stars_repo_head_hexsha": "95a7e2ee7664b94156906322610555e36e53cfe0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/uncertainty/process/development/dynamic-steady-analysis.tex", "max_issues_repo_name": "IvanUkhov/thesis", "max_issues_repo_head_hexsha": "95a7e2ee7664b94156906322610555e36e53cfe0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/uncertainty/process/development/dynamic-steady-analysis.tex", "max_forks_repo_name": "IvanUkhov/thesis", "max_forks_repo_head_hexsha": "95a7e2ee7664b94156906322610555e36e53cfe0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.5365853659, "max_line_length": 80, "alphanum_fraction": 0.7940272288, "num_tokens": 1165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3431612818573753}}
{"text": "\\documentclass[11pt]{article}\n\\usepackage{geometry}                \n\\geometry{a4paper,left=2.5cm,right=2.5cm,top=2.5cm,bottom=2.5cm}\n\\usepackage{natbib}\n\\usepackage{color}\n\\definecolor{mygreen}{RGB}{28,172,0} % color values Red, Green, Blue\n\\definecolor{mylilas}{RGB}{170,55,241}\n\\usepackage{epsfig}\n\\usepackage{amssymb,amsmath}\n\\usepackage{enumerate}\n\\usepackage{enumitem}\n\\usepackage[utf8]{inputenc}\n\\usepackage{hyperref}\n\\usepackage{mathtools}\n\n\n\\newcommand{\\ssd}{\\text{ssd}}\n\\newcommand{\\sS}{\\mathsf{S}}\n\\newcommand{\\tot}{\\text{tot}}\n\n\\begin{document}\n\n\n\\input{symbols}\n\n\\section*{One-Layer Rotating Shallow Water Model}\n\n\\subsection*{Classical Form}\n\nThe one-layer, two-dimensional rotating shallow water model\non a rotating $f$-plane can be written as,\n\\begin{align} \n\\frac{\\partial u}{\\partial t} + \\left(\\bf{u} \\cdot \\nabla\\right) u - f v \n&= - g \\frac{\\partial h}{\\partial x},\\\\\n\\frac{\\partial v}{\\partial t} + \\left(\\bf{u} \\cdot \\nabla\\right) v + f u \n&= - g \\frac{\\partial h}{\\partial y},\\\\\n\\frac{\\partial h}{\\partial t} + \\nabla \\cdot \\left( h \\bf{u} \\right) &= 0.\n\\end{align}\nThis describes the motion of a pancake like fluid in that it is thin in the vertical\nand much longer in the horizontal.  It contains pressure forces due to the free surface\nand a Coriolis pseudo-force because of the rotating frame of reference.\n\nThe fluid moves as columns that can be\ntranslated in the horizontal and stretched/contracted in the vertical.  If the \nheight of a column changes then the voriticty must change, as can be reflected \nin the fact that, in the absence of forcing and dissipation, \nPotential Vorticity is conserved following the motion,\n$$\n\\frac{D}{Dt} \\left( \n\\frac{ \\frac{\\partial v}{\\partial x} - \\frac{\\partial u}{\\partial y} + f }{h} \\right) = 0.\n$$\n\n\\subsection*{Conservation Form}\n\nThere are a variety of forms, these equations can be written.  \nOne of them is conservation where the three fields that have time \nderivatives are $U = hu$, $V = hv$ and $h$.  \n\\begin{align} \n\\frac{\\partial U}{\\partial t} \n+ \\frac{\\partial}{\\partial x}\\left( \\frac{U^2}{h} + \\frac{g h^2}{2} \\right)\n+ \\frac{\\partial}{\\partial y}\\left( \\frac{U V}{h}  \\right) \n- f V \n&= 0,\\\\\n\\frac{\\partial V}{\\partial t} \n+ \\frac{\\partial}{\\partial x}\\left( \\frac{U V}{h}  \\right) \n+ \\frac{\\partial}{\\partial y}\\left( \\frac{V^2}{h} + \\frac{g h^2}{2} \\right)\n+ f U \n&= 0,\\\\\n\\frac{\\partial h}{\\partial t} + \\nabla \\cdot \\left( h \\bf{u} \\right) &= 0.\n\\end{align}\n\nConservation form is attractive because it can help to ensure that, using a clever numerical\nscheme, some quantitites are conserved.  Note that if you have topography then there\nare source terms that appear on the right-hand side and this causes some problems.\n\n\\subsection*{Vorticity-Bernoulli Form}\n\nA third form arises from rewriting the nonlinear \nacceleration terms as a gradient and a cross product term.  Using a vector identity,\nit can be shown that the above system is mathematically equivalent to the following,\n\\begin{align} \n\\frac{\\partial u}{\\partial t}  - q h v \n&= - \\frac{\\partial B}{\\partial x},\\\\\n\\frac{\\partial v}{\\partial t}  + q h u \n&= - \\frac{\\partial B}{\\partial y},\\\\\n\\frac{\\partial h}{\\partial t} + \\nabla \\left( h \\bf{u} \\right) &= 0.\n\\end{align}\nNote that above we have defined the vorticity and the Bernoulli function,\n\\begin{align}\nq &= \\frac{\\zeta + f}{h} \n = \\frac{\\frac{\\partial v}{\\partial x} - \\frac{\\partial u}{\\partial y} + f}{h},\\\\\nB & = g h + \\frac12 \\left( u^2 + v^2 \\right).\n\\end{align}\n\nBefore we look at solving this complicated set of equations \n\n\\subsection*{ $1 \\frac12$ Dimensional Limit}\n\nWe assume that none of the variables depend on one horizontal direction, say $y$. \nBut, it is very important to realize that the velocity in that direction is not necessarily zero.\nIndeed, if you have flow in the $x$-direction, the Coriolis force will deflect it to the right,\nwhich will then generate a flow that is perpendicular.  This will continue and often give rise\nto inerital oscialltions in the horizontal.  So we can have motion in either direction but\nthe motion only changes with respect to $x$.  \n\nIf we simply the governing equations we get\n\\begin{align} \n\\frac{\\partial u}{\\partial t}  - q h v \n&= - \\frac{\\partial B}{\\partial x},\\\\\n\\frac{\\partial v}{\\partial t}  + q h u \n&= 0,\\\\\n\\frac{\\partial h}{\\partial t} + \\frac{\\partial}{\\partial x} \\left( h u \\right) &= 0.\n\\end{align}\nwhere the vorticity and the Bernoulli function simplify to,\n\\begin{align}\nq & = \\frac{\\zeta + f}{h} = \\frac{\\frac{\\partial v}{\\partial x} + f}{h},\\\\\nB & = g h^2 + \\frac12 \\left( u^2 + v^2 \\right).\n\\end{align}\n\n\\subsection*{Conserved Quantities}\n\nIn the purely conservative or nondissipative limit, \nthere are three quantities that are exactly conserved.  \n\n1) Mass:\n$$\nM = \\int_D h \\, dA\n$$\n\n2) Total Energy: sum of potential and kinetic energies\n$$\nE = \\frac12 \\int_D \\left(g h^2 + h( u^2 + v^2)\\right) \\, dA\n$$\n\n3) Potenal Enstrophy: \n$$\nQ = \\frac12 \\int_D  h q^2 \\, dA\n$$\n\nIn a numerical model we cannot expect these to be conserved \nbut we would like them to be close to be conserved.  \nIf they are very badly conserved than this could reflect that\nthe numerical scheme is behaving badly.\nHowever, just because these are conserved that does not \nguarantee that the solution is correct. \nBut they are usually good indicators as to how our method is \ndoing in the conservative limit.  \n\nOf course when nonconservative forces are introduced things will change.\nOne might argue that since the world is non-dissipative then we don't\nneed to worry about conserving these.  However, it is desirable to\nknow that basis of your model is well behaved and therefore why\nwe should worry about conserved quantities.\n\n\\end{document}", "meta": {"hexsha": "bde87055db77967afe77f52508d4db1ff7c9d5a4", "size": 5699, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/sw_intro.tex", "max_stars_repo_name": "nishantsule/PyRsw", "max_stars_repo_head_hexsha": "753788608a0d227b5c8dc8b863d85bfc3a907310", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2015-11-10T21:45:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-13T08:47:38.000Z", "max_issues_repo_path": "docs/sw_intro.tex", "max_issues_repo_name": "nishantsule/PyRsw", "max_issues_repo_head_hexsha": "753788608a0d227b5c8dc8b863d85bfc3a907310", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2015-11-26T16:14:28.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-09T04:49:37.000Z", "max_forks_repo_path": "docs/sw_intro.tex", "max_forks_repo_name": "nishantsule/PyRsw", "max_forks_repo_head_hexsha": "753788608a0d227b5c8dc8b863d85bfc3a907310", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2015-11-10T10:30:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-21T18:21:13.000Z", "avg_line_length": 36.7677419355, "max_line_length": 97, "alphanum_fraction": 0.7085453588, "num_tokens": 1757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.3431612818573753}}
{"text": "%-----------------------------------------------------------------------------------------------\n\\section{Introduction}\n\n    Polytropic        processes---\\emph{poly}:        many,        \\emph{tropic}:         forms,\n    ways~\\cite{2020-NaaktgeborenC-engrXiv}---are a versatile class of equilibrium thermodynamics\n    processes          with          many          applications          in          engineering\n    thermodynamics~\\cite{2002-MoranMJ+ShapiroHN-LTC,                 2013-CengelYA+BolesMA-AMGH,\n    2015-KroosKA+PotterMC-Cengage,  1986-JonesJB+HawkinsGA-Wiley},  given   by   the   following\n    relationship\n    %\n    \\begin{equation}\n        Pv^n = \\mathsf{c} = \\mbox{const.},\n        \\label{eq:polytropic}\n    \\end{equation}\n    %\n    \\noindent where $P$ is the system pressure, $v$ the system specific volume, and $n$  is  the\n    polytropic exponent.\n\n    Polytropic       processes       are       said       to       find        support        in\n    measurements~\\cite{2013-CengelYA+BolesMA-AMGH,                   2002-MoranMJ+ShapiroHN-LTC,\n    1985-WylenG-Wiley};         however,          theory~\\cite{2012-ChristiansJ-IntJMechEngEduc,\n    2020-NaaktgeborenC-engrXiv} predicts a fairly restrictive set of conditions---on the process\n    boundary and internal conditions and on the underlying substance model---are required for  a\n    process to follow Eq.~(\\ref{eq:polytropic}) \\emph{exactly}---see, for instance, Theorem~3 of\n    reference~\\cite{2020-NaaktgeborenC-engrXiv}.\n\n    Thus, in non-ideal  settings,  polytropic  processes  either  (i)~hold  approximately  in  a\n    \\emph{local} neighborhood of  a  given  state,  for  constant-$n$,  or  (ii)~the  polytropic\n    exponent must be generalized into a function of a state property, such  as  temperature,  or\n    even further generalized.\n\n    Reference~\\cite{2020-NaaktgeborenC-engrXiv} brings useful definitions for  discussions  like\n    this, such as that of a \\emph{logical process},  and  also  those  of  \\emph{exact}  and  of\n    \\emph{local} polytropic processes.\n\n    In \\emph{exact polytropic process}, Eq.~(\\ref{eq:polytropic}) holds exactly with a constant,\n    unique polytropic exponent, for the entire duration of the \\emph{logical process}. They  are\n    shown to be able to represent any straight line segment process in $\\log P  \\times  \\log  v$\n    coordinates~\\cite{2020-NaaktgeborenC-engrXiv}.\n\n    Moreover, process whose representations in $\\log P \\times \\log v$  coordinates  are  curved,\n    are shown to be able to be  approximated  by  a  finite  number  of  \\emph{local  polytropic\n    processes} within  finite  error  intervals~\\cite{2020-NaaktgeborenC-engrXiv}.  Observations\n    like these attest the flexibility of processes based on the  polytropic  relationship,  thus\n    justifying the flexibility encoded in their name.\n\n    Despite their enormous flexibility, the defining concept  of  polytropic  processes  can  be\n    further generalized as to allow for increased flexibility, so that some  processes  families\n    with curved representation in $\\log P  \\times  \\log  v$  coordinates  might  have  an  exact\n    representation in such further generalized process relation  concept.  The  introduction  of\n    such generalizations can be of theoretical and of applied interest.\n\n    Therefore, this work proposes one such generalization, named \\emph{polyekthetic  processes},\n    that form a \\emph{larger process set} of which  the  polytropic  process  set  is  a  proper\n    subset, so that any polytropic process is a particular case of a polyekthetic  process,  but\n    not necessarily the opposite.\n\n    The origin  (etymology)  for  the  proposed  `polyekthetic'  term  is  also  given,  and  an\n    application yielding exact polyekthetic processes  (but  not  exactly  polytropic  ones)  is\n    provided.\n\n%-----------------------------------------------------------------------------------------------\n\n", "meta": {"hexsha": "507d288fcf5cfbfd5039d55d0bcbfee47eddb8b8", "size": 3939, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "01-01-Introduction.tex", "max_stars_repo_name": "cnaak/man-Polyekthetic", "max_stars_repo_head_hexsha": "0918d9d87e9e8841126059ce3346f15bd6826999", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "01-01-Introduction.tex", "max_issues_repo_name": "cnaak/man-Polyekthetic", "max_issues_repo_head_hexsha": "0918d9d87e9e8841126059ce3346f15bd6826999", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "01-01-Introduction.tex", "max_forks_repo_name": "cnaak/man-Polyekthetic", "max_forks_repo_head_hexsha": "0918d9d87e9e8841126059ce3346f15bd6826999", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 61.546875, "max_line_length": 96, "alphanum_fraction": 0.6636202082, "num_tokens": 1058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.3431612785414188}}
{"text": "\n\n    \\filetitle{rngcmp}{Compare two IRIS date ranges}{dates/rngcmp}\n\n\t\\paragraph{Syntax}\\label{syntax}\n\n\\begin{verbatim}\nFlag = rngcmp(R1,R2)\n\\end{verbatim}\n\n\\paragraph{Input arguments}\\label{input-arguments}\n\n\\begin{itemize}\n\\itemsep1pt\\parskip0pt\\parsep0pt\n\\item\n  \\texttt{R1}, \\texttt{R2} {[} numeric {]} - Two IRIS date ranges that\n  will be compared.\n\\end{itemize}\n\n\\paragraph{Output arguments}\\label{output-arguments}\n\n\\begin{itemize}\n\\itemsep1pt\\parskip0pt\\parsep0pt\n\\item\n  \\texttt{Flag} {[} \\texttt{true} \\textbar{} \\texttt{false} {]} - True\n  if the two date ranges are the same.\n\\end{itemize}\n\n\\paragraph{Description}\\label{description}\n\nAn IRIS date range is distinct from a vector of dates in that only the\nfirst and the last dates matter. Often, date ranges are context\nsensitive. In that case, you can use \\texttt{-Inf} for the start date\n(meaning the earliest possible date in the given context) and\n\\texttt{Inf} for the end date (meaning the latest possible date in the\ngiven context), or simply \\texttt{Inf} for the whole range (meaning from\nthe earliest possible date to the latest possible date in the given\ncontext).\n\n\\paragraph{Example}\\label{example}\n\n\\begin{verbatim}\nr1 = qq(2010,1):qq(2020,4);\nr2 = [qq(2010,1),qq(2020,4)];\n\nrngcmp(r1,r2)\nans =\n    1\n\\end{verbatim}\n\n\n", "meta": {"hexsha": "0772ee22a693d3995bf3ab4aeb2bf817219299af", "size": 1295, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "-help/dates/rngcmp.tex", "max_stars_repo_name": "OGResearch/IRIS-Toolbox-For-Octave", "max_stars_repo_head_hexsha": "682ea1960229dc701e446137623b120688953cef", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-12-06T13:38:38.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-06T13:38:38.000Z", "max_issues_repo_path": "-help/dates/rngcmp.tex", "max_issues_repo_name": "OGResearch/IRIS-Toolbox-For-Octave", "max_issues_repo_head_hexsha": "682ea1960229dc701e446137623b120688953cef", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-03-28T08:13:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-02T10:40:25.000Z", "max_forks_repo_path": "-help/dates/rngcmp.tex", "max_forks_repo_name": "OGResearch/IRIS-Toolbox-For-Octave", "max_forks_repo_head_hexsha": "682ea1960229dc701e446137623b120688953cef", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-17T07:06:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T07:06:39.000Z", "avg_line_length": 24.9038461538, "max_line_length": 72, "alphanum_fraction": 0.7374517375, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.3430989396434626}}
{"text": "% vim: set spell spelllang=en\n\\documentclass[10pt]{article}\n\\usepackage[pdftex]{graphicx}\n\\usepackage{amssymb, amsmath}\n\\usepackage{url}\n\n\\usepackage{fullpage}\n\\setlength{\\parindent}{0pt}\n\\setlength{\\parskip}{\\baselineskip}\n\n\\title{Implementation of the Density Evolution method with\nFokker-Planck for L-NLIF Model in Python}\n\\author{Valentin Haenel \\\\\nvalentin.haenel@gmx.de \\\\\nBCCN Berlin}\n\n\\begin{document} \n\n\\maketitle\n\n\\section{Introduction}\n\nThis report is a description of the work done by Valentin Haenel\nfor a Lab Rotation within the Bernstein Center for Computational\nNeuroscience in Berlin. The rotation was completed under the\nsupervision of  Gabriel and Bartosz Telenczuk. \n\nThroughout the project I have implemented a variant of the Leaky\nIntegrate and Fire Neuron (LIF), and a method to fit the parameters of this\nneuron using a model of the input and extracellularly recorded spikes.\nPrimarily this involved solving a partial differential equation and constructing\na maximum likelihood objective function. \n\nThis project is motivated by the fact that recording intracellularly from awake\nbehaving animals is usually not possible, and extracellularly recorded spike\ntrains are much more common in this setting. The model implemented allows us to\ngain at least some partial insight into the subthreshold voltage of such\nneurons. A further motivation comes from the fact, that algorithms described are\nnot publicly available in the form of an easy to use software package. \n\n\\section{Model}\nThe original model is a L-NLIF model, which consists of a Linear\n(L) Filter, followed by a probabilistic or Noisy (N) form of Leaky\nIntegrate and Fire spike generation (LIF) (Paninski et\nal.\\cite{PaninskiPillowSimoncelli}). For sake of completeness the\nmodel is briefly described here.\n\nThe evolution of the Voltage $V$ is given by:\n\\begin{equation}\n    dV = (-g(V(t) -V_{leak}) +I_{stim}(t) + I_{hist}(t)) dt + W_{t}\n\\end{equation}\nWhere $g$ is the leak conductance $V_{leak}$ is the leak reversal\npotential $I_{stim}$ is the convolution of linear filter with the\ninput signal, $I_{hist}$ is the spike current history and $W_t$ is\nstandard Gaussian white noise. More precisely:\n\\begin{equation}\n    I_{stim}(t) = \\vec{k} \\cdot  \\vec{x}(t) \n\\end{equation}\n\\begin{equation}\n    I_{hist}(t) = \\sum_{j=0}^{i-1}h(t-t_j)\n\\end{equation}\nWhere $k$ is a linear filter and $h$ is a fixed postspike current waveform. \n\n\\section{Algorithms}\n\n\\subsection{PDE Solver}\n\n\\subsubsection{The Problem}\nLet \n\\begin{equation}\n    P(V,t) \\equiv P(V(t) \\cap  V(s) < V_{th} \\forall s < t)\n\\end{equation}\nThis refers to the probability of $V(t)$, the membrane potential,\nbeing less than $V_{th}$ the firing threshold until time $t$.  \n\nAs stated in \\cite{PaninskiPillowSimoncelli} the method of density\nevolution requires us to solve the\nfollowing Fokker-Planck drift diffusion equation numerically.\n\\begin{equation}\n    \\frac{\\partial P(V,t)}{\\partial t} =\n    \\frac{\\sigma^2}{2} \\frac{\\partial^2 P(V,t) } {\\partial V^2} +\n    g\\frac{\\partial[(V-V_{rest})P(V,t)]}{\\partial V}\n    \\label{fokkerplanck}\n\\end{equation}\n\nWe will be solving the evolution of the probability density for a\ngiven inter-spike interval (ISI). And therefore we will constrain the range\nof $V$ and $t$.\n\\begin{equation}\n    P(V_{th},t) = 0\n    \\label{boundarytop}\n\\end{equation}\n\\begin{equation}\n    P(V,0) = \\delta(V-V_{reset})\n    \\label{boundaryleft}\n\\end{equation}\n\nCondition (\\ref{boundarytop}) ensures that the probability of obtaining a spike\nduring an ISI is zero. Condition (\\ref{boundaryleft}) ensures\nthat at the beginning of an ISI, i.e. at the time of the last spike,\nthe probability of the neuron being at reset potential is exactly one.\nThereby we have obtained the constraints for the top and the left hand\nside of our solution grid, however, when solving numerically we also\nneed a lower bound on the voltage $V_{lb}$, so this becomes an\nadditional boundary condition, for the  bottom:\n\\begin{equation}\n    P(V_{lb},t) = 0 \n    \\label{boundarybottom}\n\\end{equation}\n\nIdeally $V_{lb} = -\\infty $.\n\n$V_{rest}$ is defined as the stationary point of the noiseless\nsubthreshold dynamics:\n\\begin{equation}\n    V_{rest}(t) = V_{leak} + \\frac{1}{g}(\\vec{k} \\cdot \\vec{x}(t) +\n    \\sum_{j=0}^{i-1}h(t-t_j))\n\\end{equation}\n\n% This was just wasting space\n%\n%We can rewrite (\\ref{fokkerplanck}) as:\n%\\begin{equation}\n%    \\frac{\\sigma^2}{2} \\frac{\\partial^2 P(V,t) } {\\partial V^2} +\n%    g(V-V_{rest})\\frac{\\partial P(V,t)}{\\partial V} +\n%    gP(V,t) -\n%    \\frac{\\partial P(V,t)}{\\partial t} = \n%    0\n%\\end{equation}\n%Since we know that:\n%\\begin{equation}\n%    \\frac{\\partial[(V-V_{rest})P(V,t)]}{\\partial V} =\n%    \\frac{\\partial (V-V_{rest})}{\\partial V}  P +\n%    \\frac{\\partial P}{\\partial V} (V-V_{rest})\n%\\end{equation}\n%and\n%\\begin{equation}\n%    \\frac{\\partial (V-V_{rest})}{\\partial V} = 1\n%\\end{equation}\n\n\\subsubsection{Finite Differencing}\n\nIn order to solve (\\ref{fokkerplanck}) numerically we discretized time\nand potential. We adopt the notation that Potential is discretized\ninto $W$ intervals of length $w$ and indexed\nby $\\nu= 0,1, \\dots W $.  Time is discretized  into $U$ intervals of\nlength $u$ and indexed by: $\\tau= 0,1, \\dots U $.\nWe adopt the notation: $P_{\\nu,\\tau} = P(\\nu w,\\tau u)$\n\nA forward finite differencing scheme would like:\n\\begin{eqnarray}\n    \\hat{P}(v,t) =& P_{\\nu,\\tau}\\\\\n%\n\\frac{\\partial \\hat{P}(v,t)}{\\partial t} =& \\frac{P_{\\nu,\\tau +1 } -\n    P_{\\nu,\\tau}}{u} \\\\\n%\n    \\frac{\\partial \\hat{P}(v,t)}{\\partial V} =& \n    \\frac{P_{\\nu +1,\\tau } -\n    P_{\\nu - 1,\\tau } }\n    {2w} \\\\ \n%\n    \\frac{\\partial^2 \\hat{P}(v,t)}{\\partial V^2} =& \n    \\frac{P_{\\nu+1,\\tau} - 2 P_{\\nu,\\tau} + P_{\\nu-1,\\tau}}\n    {w^2} \n\\end{eqnarray}\n\nHowever as suggested in \\cite{PaninskiHaithSzirtes} we will use the\ncomputationally more stable Crank-Nicolson scheme \\cite{press}.  \nWe rewrite the derivatives using the new scheme which is centered around $t +\nu/2$.\n\n\\begin{eqnarray}\n    P_{CN}(v,t) =& \\frac{P_{\\nu,\\tau} + P_{\\nu,\\tau + 1}}{2} \\\\\n    %\n    \\frac{\\partial P_{CN}(v,t)}{\\partial t} =& \\frac{P_{\\nu,\\tau +1 } -\n    P_{\\nu,\\tau}}{u} \\\\\n    %\n    \\frac{\\partial P_{CN}(v,t)}{\\partial V} =&\n    \\frac{P_{\\nu +1,\\tau } + P_{\\nu +1,\\tau +1 } -\n    P_{\\nu - 1,\\tau } - P_{\\nu -1,\\tau +1}} \n    {4w} \\\\\n    %\n    \\frac{\\partial^2 P_{CN}(v,t)}{\\partial V^2} =&\n    \\frac{P_{\\nu+1,\\tau} - 2 P_{\\nu,\\tau} + P_{\\nu-1,\\tau} +\n    P_{\\nu+1,\\tau+1} - 2 P_{\\nu,\\tau+1} + P_{\\nu-1,\\tau+1}}\n    {2w^2} \n\\end{eqnarray}\n\n\\subsubsection{Tridiagonal Equations}\n\nIf we now let:\n\\begin{align*}\na &= \\frac{\\sigma^2}{2} \\\\\nb &= g(V - V_{rest}) \\\\\nc &= g \\\\\n\\end{align*}\nand multiply throughout with $4w^2u$\nwe may rearrange all the $P_{*,\\tau+1} $ terms on the left hand side:\n\\begin{multline}\n    \\overbrace{-(2au+bwu)}^{A_\\nu} P_{\\nu+1,\\tau+1} + \n    \\overbrace{(4au - 2cw^2u + 4w^2)}^{B_\\nu} P_{\\nu,\\tau+1}\n    \\overbrace{-(2au-bwu)}^{C_\\nu} P_{\\nu-1,\\tau+1}\n    =  \\\\\n    \\underbrace{(2au+bwu) P_{\\nu+1,\\tau} +  \n    (-4au +2cw^2u + 4w^2) P_{\\nu,\\tau} + \n    (2au-bwu) P_{\\nu-1,\\tau}}_{D_{\\nu}}\n    \\label{rearrange}\n\\end{multline}\nFor each $ \\nu = 1 , \\dots , W-1 $\n\nUsing (\\ref{rearrange}) and incorporating the boundary conditions\n\\ref{boundarytop} and \\ref{boundaryleft} we have obtain a complete system \nof $W-1$ linear equations which we may now rewrite in the following\ntridiagonal matrix notation.\n\n\\begin{equation}\n\\underbrace{\n\\begin{pmatrix}\n    & B_1   & A_1    & 0      & \\cdots   \\\\\n    & C_2   & B_2    & A_2    & 0        \\\\\n    &       & \\ddots & \\ddots & \\ddots   \\\\\n    & \\cdots & 0      & C_{W-1}& B_{W-1} \\\\\n\\end{pmatrix}}_{\\Lambda}\n\\underbrace{\n\\begin{pmatrix}\n    P_{1,\\tau+1}   \\\\\n    P_{2,\\tau+1}   \\\\\n    \\vdots         \\\\\n    P_{W-1,\\tau+1} \\\\\n\\end{pmatrix}}_{\\chi}\n=\n\\underbrace{\n\\begin{pmatrix}\n    D_1     \\\\\n    D_2     \\\\\n    \\vdots  \\\\\n    D_{W-1} \\\\\n\\end{pmatrix}}_{\\beta}\n\\end{equation}\n\nWe can then use a tridiagonal matrix algorithm to solve $\\Lambda \\chi\n= \\beta$. This allows us to iteratively obtain the density evolution $P(V,t)$ of the\nmembrane potential for a given ISI. Where the initial $\\beta$ for an ISI is given by\n(\\ref{boundaryleft}) and the halting criterion is the time of the next\nspike. So for the $i$th spike we obtain values for $V$ in the range\n$[V_{lb}, V_{th}]$ and for $t$ in the range $[t_{i-1},t_{i}]$. An\nexample can be seen in figure \\ref{P_vt}.\n\n\n\\subsection{First Passage Time}\n\nThe maximum likelihood optimizer proposed in\n\\cite{PaninskiPillowSimoncelli} however uses the first passage time\ndensity at a given time point which is defined as:\n\n\\begin{equation}\n    \\mathrm{FPT}(t)  = -\\frac{\\partial}{\\partial t} \\int P(V,t)dV \n    \\label{eq:fpt}\n\\end{equation}\n\nand this can be easily computed from a $P(V,t)$ matrix by a finite differences\n/ sums scheme.\n\n\\subsection{Maximum Likelihood Estimator}\n\nPutting together the PDE Solver and method for computing the First\nPassage Time \nThe final likelihood is then simply\n\n\\begin{equation}\n    L_{\\vec{x},t_{i}} = \\prod_{i} \\mathrm{FPT}(t_{i})\n\\end{equation}\n\nThis is the product of the first passage time at the times of\nspiking for all spikes.\n\nThe pseudocode for the objective function can be described as follows:\n\n{\\tt\nfor each spike interval do:\n\\begin{enumerate}\n    \\item compute $P(V,t)$ as matrix\n    \\item compute FPT$(t)$ as vector\n\\end{enumerate}\nreturn the product of the last scalars in the FPT vectors.}\n\nThis objective function could be presented to a standard numerical\noptimizer, for example the Nelder-Mead Downhill simplex \\cite{press},\nthis needs no gradients and is fairly robust but slow.\n\n\\subsection{Monte Carlo Method}\n\nTo double check the results of the PDE Solver and the resulting First\nPassage Time, we additionally implemented some basic Monte Carlo\nsimulations. The basic idea is to simulate a few thousand traces of the neuron\nup to the first spike, with noise. The resulting potential traces, and spike\ntimes were used to obtain both $P(V,t)$ and $fpt$. The density evolution is\ncompared qualitatively to the density evolution technique as can bee seen in:\n\\ref{P_vt}. The FPT is compared using a Kolmogorov-Smirnov (K-S)\ntest\\cite{press}.\n\n\n\\section{Implementation}\n\nThis section describes the concrete implementation\n\n\\subsection{Availability and Design}\n\nThe algorithm has been implemented in Python, and the full source code\nhas been made available within a revision control system under a free\nsoftware license at: http://github.com/esc/molif/tree/master. Given\nthat the Python Language was named after the British Comedians Monty\nPython we decided to call the software {\\it Meaning Of LIF},\n(abbreviated to {\\it molif}) which is a reference to the Monty Python\nmovie {\\it Meaning of Life}. \n\nThe software is structured into a series of modules contained within\nthe package {\\tt molif} \n\n\\begin{itemize}\n    \\item {\\tt model} implementation of the neuron model\n    \\item {\\tt density} implementation of the PDE solver \n    \\item {\\tt likelihood} connects the optimizer and the PDE solver\n    \\item {\\tt montecarlo} implementation of Monte Carlo simulator\n    \\item {\\tt plotting} methods used to generate plots\n    \\item {\\tt util} methods to determine timing\n\\end{itemize}\n\nThe software uses the additional packages numpy, scipy for vector\nbased and scientific computing, and pylab/matplotlib for plotting the\nresults. We used the modules {\\it scipy.sparse} and {\\it\nscipy.linsolve} for computing the solution to tridiagonal equations, and the\nmethod {\\it optimize.fmin}, which implements the Nelder-Mead Downhill\nSimplex, for minimizing the negative likelihood.\n\n\n\\subsection{Limitations and Future Work}\n\nThe PDE solver uses sparse matrix algorithms to store and solve the\ntridiagonal matrix. Ideally we would like to use the routine $TRIDAG$\ndescribed in \\cite{press}, however an open source implementation in\npython was not available, although feasible. This improvement could\npossibly speed up the computation of $P(V,t)$.\n\nThere is a serious bug, whereby the value of sigma,\nmust be within a specific range of $0.1 - 0.05$, otherwise strange\noscillatory instabilities occur. Among the possible causes, are a\nnumerical instability in the finite differencing scheme, a bug in our\ncode, a bug in the solver for the linear equations or the\ndiscretization of $V$ and $t$ being to large. \n\nCurrently the gradient of the objective function isn't implemented,\nand any gradient based optimizer would need to compute their\napproximation from the function values. \n\nWe used a Kolmogorov-Smirnov (K-S) test to check that the first\npassage time computed by the PDE-solver and the Monte Carlo method\ncome from the same distribution. However the test currently returns a\nnegative result, although at first glance the distributions look very\nsimilar. \n\nLastly we should mention that the objective function isn't fully\noperational yet. A simple test is executed as follows: first we\ngenerate some spikes with given parameters, and then we attempt to fit\nparameters to these spikes. If the code operates correctly the\noptimizer should not deviate away from the initial parameters vector.\nHowever currently this is not the case and the optimizer finds a\nminimum at a different position in parameter space.\n\n\\subsection{Results}\n\nThis section presents some plots.\n\nFigure \\ref{P_vt} shows a comparison of PDE Solver (top) and Monte Carlo\n(bottom) method when computing the density evolution. As expected the two plots\nlook the same, and corresponds very nicely to what we would expect from the\niterative solution to a Fokker-Planck equation. The drift term is responsible for\nthe shift of the mean, and the diffusion is responsible for the flattening. \n\nFigure \\ref{fpt} shows the comparison of the PDE Solver and Monte\nCarlo method when computing the first passage time. Unfortunately a\nK-S test allows us to reject the hypothesis that these two come from\nthe same distribution, even though they look very much alike at a\nfirst glance.\n\n\\begin{figure}[htp]\n\\centering\n\\includegraphics[scale=0.60]{P_vt}\n\\caption{Density Evolution}\n\\label{P_vt}\n\\end{figure}\n\n\\begin{figure}[htp]\n\\centering\n\\includegraphics[scale=0.60]{fpt.png}\n\\caption{First Passage Time Comparison}\n\\label{fpt}\n\\end{figure}\n\n\\begin{figure}[htp]\n\\centering\n\\includegraphics[scale=0.60]{traces.png}\n\\caption{Voltage Traces for 5000 Monte Carlo simulations }\n\\label{traces}\n\\end{figure}\n\n\\section{Conclusion}\n\nNot all of the initial Project Goals were reached to my full\nsatisfaction. We did implement an Integrate and Fire\nneuron, and a method to fit the parameters, however we did not get as\nfar as actually fitting real experimental data. None the less \nuseful code has been produced and solid numerical techniques (Solving\nPartial Differential Equations) were\nlearnt, and I consider the lab rotation to be successful. \n\n\\bibliography{documentation}{ \\bibliographystyle{abbrv} }\n\n\\end{document}\n", "meta": {"hexsha": "9198874bdb67cd7fc71c6272c58e64a4797681dd", "size": 14877, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "documentation/documentation.tex", "max_stars_repo_name": "tibrewalabhay/molif", "max_stars_repo_head_hexsha": "fd7e6478ffd81f44f17b3e32a286f9c773e03b0c", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-05-08T19:56:45.000Z", "max_stars_repo_stars_event_max_datetime": "2016-05-08T19:56:45.000Z", "max_issues_repo_path": "documentation/documentation.tex", "max_issues_repo_name": "tibrewalabhay/molif", "max_issues_repo_head_hexsha": "fd7e6478ffd81f44f17b3e32a286f9c773e03b0c", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-02T13:05:23.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-02T13:05:23.000Z", "max_forks_repo_path": "documentation/documentation.tex", "max_forks_repo_name": "tibrewalabhay/molif", "max_forks_repo_head_hexsha": "fd7e6478ffd81f44f17b3e32a286f9c773e03b0c", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-02T12:57:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-02T12:57:43.000Z", "avg_line_length": 35.4214285714, "max_line_length": 84, "alphanum_fraction": 0.7188277206, "num_tokens": 4369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.34309547480636743}}
{"text": "\\section*{Results}\n\nIn order to demonstrate the efficacy of our approach, we experiment with D-NeRF's synthetic\ndataset which contains 6 different scenes.\n\n\\subsection*{Quantitative Results}\n\nOur method is able to slightly outperform D-NeRF on their synthetic dataset. This is likely because D-NeRF can predict non-realistic movement, such as jumping from frame-to-frame. In practice, D-NeRF does not do this, but the movement is not bound to have any smoothness properties, so it may not resemble real movement, by coming to full stops or suddenly accelerating. In contrast, our method enforces that movement is fluid, and thus is better able to reproduce missing frames. This only leads to a small improvement in PSNR, because the dataset contains relatively simple movement, but we expect that in longer sequences this difference would become more apparent.\n\n\\subsection*{Qualitative Results}\n\nThe difference between the architectures can be observed in the difference of flow between scenes. It's clear from Figure~\\ref{fig:dnerf_cmp} that our method more accurately captures squashing and stretching of movement, as the top of the ball is not moving but the bottom of the ball is falling. In contrast, D-NeRF contains approximately equal flow for the entire ball. Since there is no forced prior on movement given by D-NeRF, there is also flow on rigid components.\n\nThe difference between the two is also more clearly seen in videos of reconstruction. $C^0$-NeRF visibly has the effect of 'tweening between views, slowing into stops, while D-NeRF has more abrupt starts and stops. While it's difficult to characterize the plausibility of this movement, future work may seek to characterize smoothness of the velocity, as well as smoothness of acceleration and use that as a way to characterize movement.\n\n\\begin{table*}[t]\n    \\centering\n    \\begin{tabular}{|c|c|c|c|c|}\n    \\hline\n    \\textbf{PSNR$^\\uparrow$} & Bouncing Balls & Hellwarrior & Hook & Jumping Jacks \\\\\n    \\hline\n    D-NeRF & 22.978 & 32.712 & 26.757 & 26.278 \\\\\n    \\hline\n    $C^0$-NeRF & 24.251 & 33.504 & 27.705 & 27.432 \\\\\n    \\hline\n    & Lego & Mutant & Standup & T-Rex \\\\\n    \\hline\n    D-NeRF & 22.679 & 27.408 & 29.435 & 24.494 \\\\\n    \\hline\n    $C^0$-NeRF & 22.945 & 28.486 & 31.050 & 25.421 \\\\\n    \\hline\n    \\end{tabular}\n    \\centering\n    \\begin{tabular}{|c|c|c|c|c|}\n    \\hline\n    \\textbf{MS-SSIM$^\\uparrow$} & Bouncing Balls & Hellwarrior & Hook & Jumping Jacks \\\\\n    \\hline\n    D-NeRF & 0.917 & 0.949 & 0.961 & 0.931 \\\\\n    \\hline\n    $C^0$-NeRF & 0.971 & 0.966 & 0.976 & 0.978 \\\\\n    \\hline\n    & Lego & Mutant & Standup & T-Rex \\\\\n    \\hline\n    D-NeRF & 0.912 & 0.960 & 0.975 & 0.957  \\\\\n    \\hline\n    $C^0$-NeRF & 0.935 & 0.980 & 0.988 & 0.972 \\\\\n    \\hline\n    \\end{tabular}\n    \\caption{\n        Our method is able to recover movement with slightly improved accuracy in dynamic scenes as compared to D-NeRF~\\cite{pumarola2020dnerf}. Despite, or maybe because of, the forced prior of continuous movement, we are able to learn a smooth interpolation through each frame. In our training regime which randomly samples all frames, we reconstruct each with much lower variance as compared to D-NeRF.\n    }\n\\end{table*}\n\n\\begin{figure*}\n    \\includegraphics[width=\\textwidth]{dnerf_compare}\n    \\caption{\n        \\label{fig:dnerf_cmp}\n        Results comparing movement in D-NeRF~\\cite{pumarola2020dnerf} versus our work for a small timestep. There is substantial qualitative difference in predicted flow, since D-NeRF cannot guarantee the initial frame has no movement. There is also a significant difference in rigidity, which is not easily explained. We assume that it may be significantly easier to model low movement with splines, thus there is less of a need for rigidity gating.\n    }\n\\end{figure*}\n", "meta": {"hexsha": "e1f4b7d8050f456f946fecb5ce5459e2e45413d5", "size": 3796, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "c0_paper/results.tex", "max_stars_repo_name": "princeton-computational-imaging/nerf_atlas", "max_stars_repo_head_hexsha": "f66ba284ea440cd816b303cdb7312288901da97e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2021-05-17T13:17:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T00:44:44.000Z", "max_issues_repo_path": "c0_paper/results.tex", "max_issues_repo_name": "princeton-computational-imaging/nerf_atlas", "max_issues_repo_head_hexsha": "f66ba284ea440cd816b303cdb7312288901da97e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-09-07T08:31:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-28T06:55:40.000Z", "max_forks_repo_path": "c0_paper/results.tex", "max_forks_repo_name": "princeton-computational-imaging/nerf_atlas", "max_forks_repo_head_hexsha": "f66ba284ea440cd816b303cdb7312288901da97e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2021-05-16T01:06:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-26T01:48:09.000Z", "avg_line_length": 62.2295081967, "max_line_length": 668, "alphanum_fraction": 0.7241833509, "num_tokens": 1071, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.34309547480636743}}
{"text": "The multi-model concept was introduced in \\mf using GWF Model Exchange objects to support a tight coupling between any two groundwater flow models at the matrix level. This concept has proven to be successful and valued by the modeling community, but the implementation has had its drawbacks too. The information on the spatial discretization at the interface between models as it is available in the Model Exchange object is limited, designed to carry out the basic conductance calculation between connected cells but not sufficient for more advanced discretization schemes. For example, the XT3D option in the NPF package enables simulation of fully three-dimensional (3D) anisotropy by taking into account the full, three-dimensional conductivity tensor \\cite{modflow6xt3d}. In doing so, it requires data not only from any pair of cells between which a flow needs to be calculated but also from their neighboring cells. These data are not available in the Model Exchange object and the XT3D option could not be applied across the model interface, at least not without a significant restructuring of the code.\n\nThe extension of \\mf with the transport model (GWT) comes with the need for a more generic coupling of sub-models too. Here the XT3D option is used in a similar fashion for the dispersion calculation, and the TVD (total variation diminishing) scheme in the advective transport calculation has a computational stencil (i.e. the group of cells required to determine the flux through a particular cell face) that requires information from neighboring cells as well. Finally, the GWF Model Exchange object merely replicates logic already present in the standard GWF packages, e.g. the standard NPF conductance calculation, the Newton-Raphson formulation, or the cell rewetting algorithm, and is not easily adapted when additions or modifications to those packages are made. We introduce a generalized method for coupling of Numerical Models that addresses these challenges and extends \\mf with the capability to couple GWT models.\n\nThe generalized coupling uses the concept of an Interface Model and is described in more detail below. In essence, this Interface Model uses the object-oriented paradigm in \\mf to mimic a regular GWF or GWT model by means of type extension. This way it can use the existing packages and their algorithms in those models to calculate coefficients for the matrix and right-hand-side vector in the Numerical Solution, a responsibility it takes over from the Model Exchange object on which it relies. Its grid is constructed around the interface defined by the Model Exchange with a sufficiently large extent to perform the calculations. Note that the Interface Model is never being solved and neither its configuration data nor its solution vector have any independent meaning: they are merely an image of those parts of the actual Numerical Models that contribute to the interface grid. As a matter of fact, and this is probably the most important point to make here, this generalized coupling with the Interface Model does not introduce any new model functionality. It even avoids the need for the alternative formulations currently present in the GWF Model Exchange. However, it does enable the user to apply the well-tested concepts of existing \\mf packages not only on a model’s interior domain, but also across the interface between connected models.\n  \n\\subsection{The Interface Model}\nGeneralized coupling is based on the Interface Model to provide the coefficients for the linear system in Numerical Solution. In order to utilize the routines in the existing flow and transport packages to calculate these coefficients, the grid for the Interface Model is constructed from the individual model grids and the coupling information specified by the user and its package data is kept synchronized with the model data during each step of the simulation. Because the Model Exchange makes it possible to connect model grids of different type (DIS, DISV, and DISU), the resulting interface grid is always unstructured, i.e. of type DISU.\n\nConnecting models such that the dynamics at the interface can be described properly by an Interface Model does impose a few conditions on the configuration. For more advanced functionality such as XT3D, it is required that the relative position of the model grids is specified. They should also share the cell faces over which they are connected, such that the resulting grid for the interface can be specified as a valid DISU discretization. Another consequence is that a certain compatibility is required with respect to the active processes and configuration in the individual models: enabling advection (ADV) or dispersion (DSP), for example, only in one of two connected models introduces ambiguity in how to construct the Interface Model for the transport process. Similar arguments hold when two groundwater models are connected and only one of them is configured with a buoyancy package (BUY). Such model setups are currently not supported.\n\n\\begin{figure}[!t]\n\t\\begin{center}\n\t\\includegraphics[width=0.5\\textwidth]{./Figures/InterfaceModel/mt3dms-p10-modelgrid.png}\n\t\\caption[A plan view of the model grid from MT3DMS problem 10]{A plan view of the model grid for the simulation as defined in MT3DMS problem 10. The green dashed rectangle shows the location of the interface that is used for decomposing this case into a system of coupled GWF and GWT models}\n\t\\label{fig:gwtgwt-fullgrid}\n\t\\end{center}\n\\end{figure}\n\nTo illustrate the concept of this new coupling, a well known, single-model case study (problem 10 in the MT3DMS manual \\cite{zheng1999mt3dms}) is implemented as a coupled system where the connection between the GWT models is handled by the Interface Model framework. This study is part of the official set of examples that comes with every \\mf software release\\footnote{https://modflow6-examples.readthedocs.io/en/master/}. The coefficients for the flow coupling in this case are calculated with the basic GWF Model Exchange module and the following discussion will focus on the GWT-GWT exchange. Figure~\\ref{fig:gwtgwt-fullgrid} shows a plan view of the grid and the location of the interface between the submodels. Note that changing only the composition of the grid and leaving the model configuration the same, does not affect the outcome of the simulation\\footnote{At the highest level of detail, the outcome does change because the numbering of the grid nodes is different in both scenarios leading to a reordered matrix system to be solved. As expected, these differences turn out to be well within the configured (IMS) solver tolerance.} and therefore makes for a very suitable test case of this coupling.\n\n\\begin{figure}[!ht]\n\t\\begin{center}\n\t\\includegraphics[width=0.8\\textwidth]{./Figures/InterfaceModel/gwt-ifmod-grid.png}\n\t\\caption[A top view of the Interface Model grid]{A top view of the grid for the Interface Model belonging to the inner GWT model in the example described in the text. The blue cells are located in the outer model’s grid, the red cells are internal. Note that deeper layers have an identical horizontal structure.}\n\t\\label{fig:gwtgwt-interface-grid}\n\t\\end{center}\n\\end{figure}\n\nFigure~\\ref{fig:gwtgwt-interface-grid} shows a plan view of the grid that is reconstructed as part of the Interface Model for the inner GWT model. The red band with cells belong to the inner model’s grid and the blue cells are part of the outer, coarser grid. Because two Interface Models are constructed for every Exchange, (one for each of the models in it) a similar though not identical picture can be drawn for the outer GWT model. However, the extent of this grid is not necessarily equal on both sides of the exchange. The task of the Interface Model is twofold. First of all, it is designed to calculate the coefficients for the linear system for fluxes through the faces directly at the interface. Additionally, it can provide coefficients for those fluxes that would be affected by cells on the other side of the interface just as if the simulation would have been set up as a single model. It is the requirement to support the latter that causes the asymmetry. This becomes clearer when looking at Figure~\\ref{fig:gwtgwt-stencils} which shows the XT3D computational stencils and how they determine what the required extent of the interface grid is. To determine the flux through a face at the model interface, the cells on either side and their immediate neighbors are sufficient (the circle). To correctly calculate the flux through cell faces not directly at the interface but influenced by the connection to another model, more additional levels of connectivity are required, depending on the exact size of the computation stencil (the diamond).\n\n\\begin{figure}[!ht]\n\t\\begin{center}\n\t\\includegraphics[width=0.8\\textwidth]{./Figures/InterfaceModel/gwt-ifmod-stencils.png}\n\t\\caption[Stencil size and the extent of the Interface Model grid]{Top view when zoomed in to the South-West corner of the interface grid. The dashed line surrounds the grid cells participating in the calculation of the dispersive XT3D flux directly at the interface (the white circle) and through a face in the model’s interior (the white diamond) which is nonetheless affected by the connection to the outer GWT model. The extension of the computational stencil in the vertical direction is omitted but straightforward.}\n\t\\label{fig:gwtgwt-stencils}\n\t\\end{center}\n\\end{figure}\n\nThis case study is used to demonstrate the concept of the generalized coupling method with the Interface Model. It serves as an excellent test case because the outcome should be identical to the known results, at least within the configured tolerance of the Numerical Solution. However, from a modeling perspective it would make more sense to redesign the model grid of the problem. With the new capability to use the multi-model approach also for problems containing solute transport, there is no longer a need to refine the study area by using varying column and row width as was done in the original MT3DMS problem. Both the study area and the surrounding domain can be configured as coupled models with a regularly structured (DIS) grid. The granularity of the inner grid can be independently refined to improve the resolution of the results without the need to set up the entire problem based on an unstructured (DISU) grid.\n\nFinally, such a setup would allow to apply the Interface Model in another powerful way. A refinement of the grid is known to produce inaccuracies at the interface, as discussed in the introduction of \\cite{modflow6xt3d}. This can be remedied by enabling the XT3D option in the GWF NPF package. The new coupling mechanism based on the Interface Model makes it now possible to enable this option \\emph{only} at the interface, which will mitigate the distorting effects of such a grid refiniment on the calculated flow field and still avoids the computational overhead of calculating the XT3D terms on the entire domain.\n\n", "meta": {"hexsha": "c1e33587524276b4a85fd540ec388106b25be10c", "size": 11031, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/SuppTechInfo/gen-coupling.tex", "max_stars_repo_name": "kzeiler/modflow6", "max_stars_repo_head_hexsha": "a185d95b91985e965f8a04ae353305dff19b9637", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/SuppTechInfo/gen-coupling.tex", "max_issues_repo_name": "kzeiler/modflow6", "max_issues_repo_head_hexsha": "a185d95b91985e965f8a04ae353305dff19b9637", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/SuppTechInfo/gen-coupling.tex", "max_forks_repo_name": "kzeiler/modflow6", "max_forks_repo_head_hexsha": "a185d95b91985e965f8a04ae353305dff19b9637", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 250.7045454545, "max_line_length": 1559, "alphanum_fraction": 0.812347022, "num_tokens": 2264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.3430337617223085}}
{"text": "\\section{Joint SED modeling of Photometry and Spectra} \\label{sec:methods}\n\\subsection{Stellar Population Synthesis Modeling} \\label{sec:sps} \nPROVABGS will provide galaxy properties inferred from joint SED modeling of\nDESI photometry and spectra. \nFor the SED modeling, we use a state-of-the-art stellar population synthesis\n(SPS) model that uses a non-parametric SFH with a starburst, a non-parametric\nZH that varies with time, and a flexible dust attenuation prescription. \n\n% describe SFH prescription\nThe form of the SFH is one of the most important factors in the accuracy of an\nSPS model.\nIn general, the form of the SFH requires balancing between being flexible enough\nto describe the wide range of SFHs in observations while not being too flexible\nthat it can describe any SFH at the expense of constraining power.  \nIf the model SFH is not flexible enough to describe actual SFHs of galaxies,\nthen unbiased galaxy properties cannot be inferred using the SPS model. \nFor instance, most SPS models~(\\emph{e.g.} CIGALE,~\\citealt{serra2011,\nboquien2019}; BAGPIPES,~\\citealt{carnall2017}) use parametric SFH such as the\nexponentially declining $\\tau$-model.\nSuch functional forms, however, produce biased estimates of galaxy properties\n(\\emph{e.g.} $M_*$ and SFR) when used to fit mock observations of simulated \ngalaxies~\\citep{simha2014, pacifici2015, ciesla2017, carnall2018}.\nOn the other hand, many non-parametric forms of the SFH are overly flexible\nand allow unphysical SFHs~\\citep{leja2019}, which unncessarily increases \nparameter degeneracies and discards constraining power. \n\nIn our SPS model, we use a non-parametric SFH with two components: one based on\nnon-negative matrix factorization (NMF) basis functions and a starburst component.\nFor the first component, SFH is a linear combination of four NMF SFH bases:\n\\begin{equation} \\label{eq:nmf} \n    {\\rm SFH}^{\\rm NMF} (t, t_{\\rm age}) = \\sum\\limits_{i=1}^{4} \\beta_i\n    \\frac{s_i^{\\rm SFH}(t)}{\\int\\limits_0^{t_{\\rm age}} s_i^{\\rm SFH}(t) \\,\n    {\\rm d}t}. \n\\end{equation} \n$\\{s^{\\rm SFH}_i\\}$ are the NMF basis functions and $\\{\\beta_i\\}$ are the\ncoefficients. \nThe integral in the denominator normalizes the NMF basis functions to unity. \nWe constrain $\\sum_i \\beta_i = 1$, so the total SFH of the component over the\nage of the galaxy ($t_{\\rm age})$ is normalized to unity.\n$\\{s^{\\rm SFH}_i\\}$ are derived from the Illustris cosmological hydrodynamic\nsimulation~\\citep{vogelsberger2014, genel2014, nelson2015}.\nWe compile, rebin, and smooth the SFHs of Illustris galaxies and then perform\nnon-negative matrix factorization~\\citep{lee1999,cichocki2009, fevotte2011} on\nthem to derive $\\{s^{\\rm SFH}_i\\}$. \nWe find that 4 components is sufficient to accurately reconstruct the SFHs\nfrom Illustris. \nWe present the NMF SFH bases as a function of lookback time in\nleft panel of Figure~\\ref{fig:nmf}.\n\\edits{\n    By using NMF instead of \\emph{e.g.} Principal Component Analysis (PCA), we\n    ensure that all of the SFH bases are non-negative and, thus, physically\n    meaningful. \n}\nFor further details on the derivation of the NMF bases, we refer readers to\nAppendix~\\ref{sec:nmf}. \nAssuming that the SFHs of Illustris galaxies resemble the SFHs of actual\nobserved galaxies, our NMF form provides a compact and flexible representation\nof the SFHs. \n\nThe NMF basis functions are derived from smooth SFHs, which means that it does\nnot include any stochasticity. \nHowever, observations and high resolution zoom-in hydrodyanmical simulations\nboth find significant stochasticity in galaxy SFHs~\\citep{sparre2017,\ncaplar2019, hahn2019b, iyer2020}. \nTo include some stochasticity in our SPS model, we include a starburst\ncomponent that consists of a SSP. \nThus, for the total SFH, we use\n\\begin{equation} \\label{eq:sfh}\n    {\\rm SFH} (t, t_{\\rm age}) = (1 - f_{\\rm burst})~{\\rm SFH}^{\\rm NMF} (t,\n    t_{\\rm age}) + f_{\\rm burst}~\\delta_{\\rm D}(t - t_{\\rm burst}).\n\\end{equation}\n$f_{\\rm burst}$ is the fraction of total stellar mass formed during the\nstarburst; $t_{\\rm burst}$ is the time at which the starburst occurs; \n$\\delta_{\\rm D}$ is the Dirac delta function.\nIn total we use 6 free parameters in our SFH: 4 NMF basis coefficients \n($\\beta_i$), $f_{\\rm burst}$, and $t_{\\rm burst}$. \n\n% describe ZH \nAnother key part of an SPS model is the chemical enrichment history, or ZH. \nCurrent SPS models mostly assume a\n\\edits{\n    flat ZH, constant metallicity over time~\\citep{carnall2017, leja2019}.\n} \nSince galaxies do not have constant metallicities throughout their history,\nthis assumption can significantly bias the inferred galaxy\nproperties~\\citep{thorne2021}. \nInstead, we take a similar approach to the SFH and use NMF basis functions for\nour ZH:\n\\begin{equation}\n    {\\rm ZH}(t) = \\sum\\limits_{i=1}^2 \\gamma_i s_i^{\\rm ZH}(t).\n\\end{equation} \n$\\{s_i^{\\rm ZH}(t)\\}$ are the ZH NMF basis functions and $\\{\\gamma_i\\}$ are the\ncoefficients. \n$\\{s_i^{\\rm ZH}(t)\\}$ are fit using the ZHs of simulated galaxies from\nIllustris in the same fashion as the SFH. \nIn the right panel of Figure~\\ref{fig:nmf}, we present the ZH NMF bases as a\nfunction of lookback time. \nWe use two NMF components, so our ZH prescription has 2 free parameters. \n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=0.8\\textwidth]{figs/nmf_bases.pdf} \n    \\caption{\n        Non-negative matrix factorization basis functions for the SFH (left)\n        and ZH (right) used in the non-parametric SFH and ZH prescriptions of\n        our SPS model. \n        These basis functions are derived from the SFHs and ZHs of simulated\n        galaxies in the Illustris cosmological hydrodynamic simulations. \n        With the NMF basis functions, we can reproduce the wide range of SFHs\n        and ZHs of Illustris galaxies (Appendix~\\ref{sec:nmf}).  \n    }\n    \\label{fig:nmf}\n\\end{center}\n\\end{figure}\n\nWe use the SFH and ZH above to model the unattenuated rest-frame luminosity as\na linear combination of multiple SSPs, evaluated at logarithmically-spaced\nlookback time bins.\nWe use a fixed log-binning with the bin egdes starting with $(0, 10^{6.05}{\\rm\nyr})$, $(10^{6.05}, 10^{6.15}{\\rm yr})$, and continuing on with bins of width\n0.1 dex.\nThe binning is truncated at the age of the model galaxy. \nFor a $z=0$ galaxy, this binning produces 43 $\\tlb$ bins.\nWe use log-spaced $\\tlb$ bins because it better reproduces galaxy luminosities\nevaluated with much higher resolution $\\tlb$ binning than linearly-spacing, for\nthe same number of bins. \n\\edits{At each of the 43 $\\tlb$ bin $i$,}\nwe evaluate the luminosity of a SSP with ${\\rm ZH}(t_i)$, where $t_i$ is the\ncenter of $\\tlb$ bin, and total stellar mass calculated by resampling the SFH\nin Eq.~\\ref{eq:sfh}. \n\\edits{\n    We use \\fsps~to evaluate the SSP luminosities and use the MIST isochrones, the\n    combination of MILES and BaSeL spectral libraries, and the \\cite{chabrier2003}\n    IMF (same as in Section~\\ref{sec:sed}).  \n}\nSince we use MIST isochrones, we impose a minimum and maximum limit to ${\\rm\nZH}$ based on its coverage: $4.49\\times10^{-5}$ and $4.49\\times10^{-2}$,\nrespectively.\n\\edits{\n    These metallicity values are in units of absolute metallicity and can be\n    converted to solar metallicity using $Z_\\odot = 0.019$. \n}\nWe note that our stellar metallicity range is significantly broader than\nprevious studies for additional flexibility~\\citep[\\emph{e.g.}][]{carnall2017,\nleja2017, tacchella2021}. \n\\edits{\n    Since we model galaxies solely as a linear combination of SSPs, we do not\n    model nebular emission.  \n    We, therefore, exclude emission lines in our SED modeling by masking the\n    wavelength ranges of emission lines.\n}\n\nBefore we combine the SSP luminosities, we apply dust attenuation.\nWe use a two component \\cite{charlot2000} dust attenuation model with birth\ncloud (BC) and diffuse-dust (ISM) components. \nThe BC component represents the extra dust attenuation of young stars that are\nembedded in modecular clouds and HII regions. \nFor SSPs younger than $t_i < 100{\\rm Myr}$, we apply the\nfollowing BC dust attenuation: \n\\begin{equation}\n    L_i(\\lambda) = L_i^{\\rm unatten.}(\\lambda) \\exp\\left[-\\tau_{\\rm BC} \\left(\n    \\frac{\\lambda}{5500\\AA} \\right)^{-0.7} \\right].\n\\end{equation}\n$\\tau_{\\rm BC}$ is the BC optical depth that determines the strength of the BC\nattenuation. \nAfterwards, {\\em all} SSPs are attenuated by the diffuse dust using the\n\\cite{kriek2013} attenuation curve parameterization: \n\\begin{equation}\n    L_i(\\lambda) = L_i^{\\rm unatten.}(\\lambda) \\exp\\left[-\\tau_{\\rm ISM} \\left(\n    \\frac{\\lambda}{5500\\AA} \\right)^{n_{\\rm dust}} \\left(k_{\\rm Cal}(\\lambda) +\n    D(\\lambda) \\right) \\right].\n\\end{equation}\n$\\tau_{\\rm ISM}$ is the diffuse dust optical depth.\n$n_{\\rm dust}$ is the \\cite{calzetti2001} dust index, which determines the\nslope of the attenuation curve. \n$k_{\\rm Cal}(\\lambda)$ is the \\cite{calzetti2001} attenuation curve and\n$D(\\lambda)$ is the UV dust bump, parameterized using a Lorentzian-like Drude \nprofile:\n\\begin{equation}\n    D(\\lambda) = \\frac{E_b(\\lambda~\\Delta \\lambda)^2}{(\\lambda^2 -\n    \\lambda_0^2)^2 + (\\lambda~\\Delta \\lambda)^2}\n\\end{equation}\nwhere $\\lambda_0 = 2175 \\AA$, $\\Delta \\lambda = 350\\AA$, and \n$E_b=0.85 - 1.9\\,n_{\\rm dust}$ are the central wavelength, full width at half\nmaximum, and strength of the bump, respectively. \nOnce dust attenuation is applied to the SSPs, we sum them up to get the\nrest-frame luminosity of the galaxy. \nIn total, our SPS model has 12 free parameters: $M_*$, 4 SFH basis\ncoefficients, $f_{\\rm burst}$, $t_{\\rm burst}$, 2 ZH basis coefficients,\n$\\tau_{\\rm BC}$, $\\tau_{\\rm ISM}$, and $n_{\\rm dust}$. \n\n%description of our speculator SED model \\citep{alsing2019}, which is based on FSPS. We use Chabrier IMF \\ch{do we need to justify htis?}. \n\nIn practice, evaluating each SSP using \\fsps~requires \\ch{X} seconds. \nFor each model evaluation, we evaluate $\\sim 43$ SSPs in each of the log-spaced\n$\\tlb$ bins. \nThough this is not a prohibitive computational cost on its own, sampling a\nhigh dimensional parameter space for inference requires $>100,000$ evaluations\n--- \\emph{i.e.} \\ch{$>100$} CPU hours \\emph{per galaxy}. \nFor the >10 million BGS galaxies, this would require \\ch{\\emph{a billion}}\nCPU hours. \nInstead, we use an emulator for the model luminosity, which uses a PCA neural\nnetwork (NN) following the approach of \\cite{alsing2019}. \n\n%The NN provides a flexible and accurate mapping between the SPS model\n%parameters and PCA coefficients --- \\emph{i.e.} the NN predicts PCA\n%coefficients for a given set of SPS parameters. \n%Then the linear combination of the predicted coefficients and PCA basis\n%functions give us the emulated model luminosity. \n%The PCA basis functions and NN are trained using 1,000,000 SPS parameters and\n%model luminosity pairs, $\\{(\\theta, L(\\lambda;\\theta))\\}$. \n\n\\edits{\n    To construct our emulator, we first generate $N_{\\rm model} = 1,000,000$\n    model luminosities, $L(\\lambda;\\theta)$, from unique SPS parameters,\n    $\\theta$, sampled from the prior (Section~\\ref{sec:infer},\n    Table~\\ref{tab:params}).\n    We then split the model luminosities into four wavelength bins: 2000 - 3600,\n    3600 - 5500, 5500 - 7410, and 7410 - $60000\\AA$ with $N_{\\rm spec}$ = 127, 2109,\n    2113, and 549 resolution elements, respectively.\n    For each wavelength bin, a PCA is done in the $N_{\\rm spec}$-dimensional\n    space to yield PCA basis functions, or eigenspectra. \n    We represent the model luminosity using the first $N_{\\rm basis}$ = 50, 50, 50, and 30\n    eigenspectra and their corresponding PCA coefficients. \n    A NN is then trained on the set of $N_{\\rm model}$ models to\n    derive a mapping from the 12 SPS parameters to the $N_{\\rm basis}$ PCA\n    coefficients for each wavelength bin. \n}\n\n\\edits{\n    Once trained, our emulator works as follows.\n    For a given set of SPS parameters, the NN for each wavelength bin predicts\n    PCA coefficients. \n    The coefficients are then linearly combined with the eigenspectra to\n    predict the model luminosity in the wavelength bin. \n    The luminosity in all four wavelength bins are concatenated to produce the\n    full model luminosity. \n}\nThroughout the wavelength range relevant for BGS, $3000 < \\lambda < 9800\\AA$,\nwe achieve $< 1\\%$ accurate with the emulator. \nFor details on the training, validation, and performance of our PCA NN\nemulator, we refer readers to Kwon \\etal~(in prep.). \n\nFrom the rest-frame luminosity, we obtain the observed-frame, redshifted, flux\nin the same way as Eq.~\\ref{eq:sed}.\nIn our case, redshift is not a free parameter since we will have high quality\nspectroscopic redshifts for every DESI BGS galaxy.\nBGS redshifts will have small redshift error, $\\sigma_z < 0.0005 (1+z)$\n(150 km/s), and <5\\% catastrophic failures, $\\Delta z/(1+z) < 0.003$ (<1000\nkm/s).\nTo model DESI photometry, we convolve the model flux with the LS broadband\nfilters as in Eq.~\\ref{eq:photo}.\nTo model DESI spectra, we first apply Gaussian velocity dispersion. \nIn this work, we keep velocity dispersion fixed at 0 km/s but in practice\nvelocity dispersion can be set as a free parameter. \nThen the broadened flux is resampled into the DESI wavelength binning. \nSince DESI spectra do not necessarily include all the light of a galaxy, we\ninclude a nuisance parameter $f_{\\rm fiber}$, a normalization factor on the\nspectra to account for fiber aperture effects. \nFinally, the SPS model photometry and spectrum can be directly compared to\nobservations.\n\n\\begin{table} \n\\caption{Parameters of the PROVABGS SPS model and their priors used for joint\n    SED modeling of DESI photometry and spectroscopy.} \n\\begin{center}\n    \\begin{tabular}{ccc} \\toprule\n        name & description & prior \\\\[3pt]\n        \\hline \n        $\\log M_*$                              & log galaxy stellar mass & uniform over [7, 12.5] \\\\\n        $\\beta_1, \\beta_2, \\beta_3, \\beta_4$    & NMF basis coefficients for SFH & Dirichlet prior \\\\\n        $f_{\\rm burst}$ & fraction of total stellar mass formed in starburst event & uniform over [0, 1] \\\\\n        $t_{\\rm burst}$ & time of starburst event & uniform over [10Myr, 13.2Gyr] \\\\\n        $\\gamma_1, \\gamma_2$ & NMF basis coefficients for ZH & log uniform over\n        [$4.5\\times10^{-5}, 1.5\\times10^{-2}$] \\\\\n        $\\tau_{\\rm BC}$ & Birth cloud optical depth & uniform over [$0, 3$] \\\\\n        $\\tau_{\\rm ISM}$ & diffuse-dust optical depth & uniform over [$0, 3$] \\\\\n        $n_{\\rm dust}$ & \\cite{calzetti2001} dust index & unifrom over[$-2, 1$]\\\\\n        $f_{\\rm fiber}$ & spectrum fiber-aperture effect normalization &\n        Gaussian $\\mathcal{N}(\\hat{f}^{\\rm fiber}_r, \\frac{f^{\\rm fiber}_r}{f_r} \\sigma_r)$\\\\\n        \\hline            \n\\end{tabular} \\label{tab:params}\n\\end{center}\n\\end{table}\n\n\\begin{figure}\n\\begin{center}\n    \\includegraphics[width=0.9\\textwidth]{figs/mcmc_posterior_demo.pdf}\n    \\caption{\n        \\emph{Top}: \n        Posterior probability distribution of our 12 SPS model parameters\n        derived from joint SED modeling of the mock DESI photometry and\n        spectrum.\n        The contours mark the 68 and 95\\% percentiles.\n        We use a Gaussian likelihood and the prior specified in\n        Table~\\ref{tab:params} to evaluate the posterior and sample the\n        distribution using ensemble slice MCMC. \n        \\emph{With our Bayesian SED modeling approach, we capture the significiant\n        parameter degeneracies and multimodality of the posterior\n        distribution.}\\\\\n        \\emph{Bottom}: \n        We compare the best-fit model observables (orange) to the mock\n        observations (black).  \n        We find excellent agreement for both the LS photometry (left) and the\n        DESI spectrum (right). \n    } \\label{fig:posterior}\n\\end{center}\n\\end{figure}\n\n\n\\subsection{Bayesian Parameter Inference} \\label{sec:infer} \nUsing the SPS model above, we perform Bayesian parameter inference to derive\nposterior probability distributions of the SPS parameters from photometry and\nspectroscopy. \nFrom Bayes rule, we write down the posterior as\n\\begin{equation} \\label{eq:bayes}\n    p(\\theta\\given {\\bf X}) \\propto p(\\theta)~p({\\bf X} \\given \\theta)\n\\end{equation}\nwhere ${\\bf X}$ is the photometry or spectrum and $\\theta$ is the set of SPS\nparameters. \n$p({\\bf X} \\given \\theta)$ is the likelihood, which we calculate separately for\nthe photometry\n\\begin{equation}\n    \\mathcal{L}^{\\rm photo} \\propto \\exp\\left[-\\frac{1}{2} \\left(\\frac{X^{\\rm photo} -\n    m^{\\rm photo}(\\theta)}{\\sigma^{\\rm photo}}\\right)\\right]\n\\end{equation}\nand for the spectrum\n\\begin{equation}\n    \\mathcal{L}^{\\rm spec} \\propto \\exp\\left[-\\frac{1}{2} \\left(\\frac{X^{\\rm spec} -\n    m^{\\rm spec}(\\theta)}{\\sigma^{\\rm spec}} \\right)^2\\right].\n\\end{equation}\n$m^{\\rm photo}$ and $m^{\\rm spec}$ represent SPS model for photometry and\nspectroscopy. \n$\\sigma^{\\rm photo}$ and $\\sigma^{\\rm spec}$ respresent the uncertainties on\nthe measured photometry and spectrum. \nIn calculating $\\mathcal{L}^{\\rm spec}$, we exclude wavelength ranges of width\n40\\AA~surrounding the OII, H$\\beta$, OIII, and H$\\alpha$ emission lines since\nour SED model does not model gas emissions.\nWe consider the photometry indepedent from the spectrum so we combine the\nlikelihoods when jointly modeling the spectrophotometry: \n\\begin{equation}\n    \\log \\mathcal{L} \\approx \\log \\mathcal{L}^{\\rm photo} + \\log\n    \\mathcal{L}^{\\rm spec}.\n\\end{equation}\n$p(\\theta)$ in Eq.~\\ref{eq:bayes} is the prior on the SPS parameters. \nFor most of our parameters, we use uninformative uniform priors with\nconservatively chosen ranges that are listed in Table~\\ref{tab:params}. \nHowever, for the priors of $\\{\\beta_1, \\beta_2, \\beta_3, \\beta_4 \\}$, the NMF coefficients\nfor the SFH, we use a Dirichlet distribution to main the normalization of the SFH in Eq.~\\ref{eq:nmf}. \nWith a Dirichlet distribution, $\\beta_i$ are within $0 < \\beta_i < 1$ and\nsatisfy the constraint $\\sum_i \\beta_i = 1$. \n\nNow that we can evaluate the posterior at given $\\theta$, we estimate the\nposterior distributions using Markov Chain Monte Carlo (MCMC) sampling. \nWe use the \\cite{karamanis2020} ensemble slice sampling MCMC algorithm with the\n{\\sc zeus} Python\npackage\\footnote{\\href{https://zeus-mcmc.readthedocs.io/}{https://zeus-mcmc.readthedocs.io/}}. \nEnsemble slice sampling is an extension of standard slice sampling that does\nnot requires specifying the initial length scale or any further hand-tuning.\nIt generally converges faster than other MCMC algorithms (\\emph{e.g.}\nMetropolis) and generates chains with significantly lower autocorrelation.\n\nWhen we sample the posterior, we do not directly sample our 12 dimensional\nSPS parameter space because we use a Dirichlet prior on the SFH NMF\ncoefficients. \nDirichlet distributions are difficult to directly sample so we instead use the\n\\cite{betancourt2012} sampling method, which transforms an $N$ dimensional\nDirichlet distribution into an easier to sample $N-1$ dimensional space.\nHence, we sample the posterior in the transformed 11 dimensional space. \nGiven this dimensionality, we run our MCMC sampling with 30 walkers.\nOverall, we find that the sampling converges after 2,500 iterations with a 500\niteration burn in. \nDeriving the posterior distribution from a joint SED modeling of photometry and\nspectra, with the emulator, takes \\ch{0.5 CPU hours}. \nIn principle, since our emulator uses a PCA NN, we can further expedite our\nparemeter inference using more efficient sampling methods that exploit gradient\ninformation, such as Hamiltonian Monte Carlo.  \nWe will explore further speed ups to our SED modeling in future works. \n\nIn Figure~\\ref{fig:posterior} we present the posterior distribution of our 12\nSPS model parameters for an arbitrarily chosen \\lgal~mock observation. \nWe mark the 68 and 95 percentiles of the distribution with the contours. \nThe posterior distribution reveal there are significant degeneracies between\nSPS parameters: \\emph{e.g.} $\\beta_2^{\\rm SFH}$ and $f_{\\rm burst}$. \nFurthermore, the distribution is multimodal (see $f_{\\rm burst}$ panels). \nWith our Bayesian SED modeling, we are able to capture such complexities in the\nposterior that would be lost with point estimates or maximum likelihood\napproaches.\nIn the bottom panels, we compare our SPS model evaluated at the best-fit\nparameters (orange) with the \\lgal~mock observations (black). \nOn the left, we compare the $g$, $r$, $z$ band magnitudes; on the right, we\ncompare spectra. \nWe find excellent agreement between the best-fit SPS model and mock\nobservations.\nThe entire PROVABGS SED modeling pipeline, including the neural emulators and\nparameter inference framework, is publicly available at\n\\href{https://github.com/changhoonhahn/provabgs/}{https://github.com/changhoonhahn/provabgs/}. \n", "meta": {"hexsha": "63aae0deee6cd3f03c56ff0b2752c25abe3f4c98", "size": 20758, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/paper/methods.tex", "max_stars_repo_name": "changhoonhahn/gqp_mc", "max_stars_repo_head_hexsha": "abdfadac2e7d7e12c1642743e2b3c6a6a6fe370b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-12-18T20:51:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T05:59:24.000Z", "max_issues_repo_path": "doc/paper/methods.tex", "max_issues_repo_name": "changhoonhahn/gqp_mc", "max_issues_repo_head_hexsha": "abdfadac2e7d7e12c1642743e2b3c6a6a6fe370b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44, "max_issues_repo_issues_event_min_datetime": "2020-02-20T06:02:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-13T20:00:50.000Z", "max_forks_repo_path": "doc/paper/methods.tex", "max_forks_repo_name": "changhoonhahn/gqp_mc", "max_forks_repo_head_hexsha": "abdfadac2e7d7e12c1642743e2b3c6a6a6fe370b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-10-04T22:25:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:05:03.000Z", "avg_line_length": 52.1557788945, "max_line_length": 139, "alphanum_fraction": 0.7343674728, "num_tokens": 5939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.5, "lm_q1q2_score": 0.34297472108399646}}
{"text": "\\pdfoutput=1\n\n%\\documentclass[preprint]{article}\n\\documentclass[10pt]{amsart}\n\\usepackage{stmaryrd}\n\n\\usepackage{fullpage}\n\\usepackage[colorlinks=true]{hyperref}\n\\usepackage{amsmath,amssymb,amsfonts,amsthm}\n\\usepackage{array} \n\\usepackage{mathtools}\n%\\usepackage{pdfpages}\n\\usepackage{bm}\n\\usepackage{bbm}\n\\usepackage{tikz}\n\\usepackage[normalem]{ulem}\n\\usepackage{hhline}\n\\usepackage{graphicx}\n\\usepackage{subfig}\n\\usepackage{color}\n\\usepackage{doi}\n\n%% ====================================== graphics\n\n\\usepackage{pgfplots}\n\\usepackage{pgfplotstable}\n\\definecolor{markercolor}{RGB}{124.9, 255, 160.65}\n\\pgfplotsset{\ncompat=1.3,\nwidth=10cm,\ntick label style={font=\\small},\nlabel style={font=\\small},\nlegend style={font=\\small}\n}\n\n\\usetikzlibrary{calc}\n\\usetikzlibrary{intersections} \n\n%%% START MACRO FOR ANNOTATION OF TRIANGLE WITH SLOPE %%%.\n\\newcommand{\\logLogSlopeTriangle}[5]\n{\n    % #1. Relative offset in x direction.\n    % #2. Width in x direction, so xA-xB.\n    % #3. Relative offset in y direction.\n    % #4. Slope d(y)/d(log10(x)).\n    % #5. Plot options.\n\n    \\pgfplotsextra\n    {\n        \\pgfkeysgetvalue{/pgfplots/xmin}{\\xmin}\n        \\pgfkeysgetvalue{/pgfplots/xmax}{\\xmax}\n        \\pgfkeysgetvalue{/pgfplots/ymin}{\\ymin}\n        \\pgfkeysgetvalue{/pgfplots/ymax}{\\ymax}\n\n        % Calculate auxilliary quantities, in relative sense.\n        \\pgfmathsetmacro{\\xArel}{#1}\n        \\pgfmathsetmacro{\\yArel}{#3}\n        \\pgfmathsetmacro{\\xBrel}{#1-#2}\n        \\pgfmathsetmacro{\\yBrel}{\\yArel}\n        \\pgfmathsetmacro{\\xCrel}{\\xArel}\n\n        \\pgfmathsetmacro{\\lnxB}{\\xmin*(1-(#1-#2))+\\xmax*(#1-#2)} % in [xmin,xmax].\n        \\pgfmathsetmacro{\\lnxA}{\\xmin*(1-#1)+\\xmax*#1} % in [xmin,xmax].\n        \\pgfmathsetmacro{\\lnyA}{\\ymin*(1-#3)+\\ymax*#3} % in [ymin,ymax].\n        \\pgfmathsetmacro{\\lnyC}{\\lnyA+#4*(\\lnxA-\\lnxB)}\n        \\pgfmathsetmacro{\\yCrel}{\\lnyC-\\ymin)/(\\ymax-\\ymin)} % THE IMPROVED EXPRESSION WITHOUT 'DIMENSION TOO LARGE' ERROR.\n\n        % Define coordinates for \\draw. MIND THE 'rel axis cs' as opposed to the 'axis cs'.\n        \\coordinate (A) at (rel axis cs:\\xArel,\\yArel);\n        \\coordinate (B) at (rel axis cs:\\xBrel,\\yBrel);\n        \\coordinate (C) at (rel axis cs:\\xCrel,\\yCrel);\n\n        % Draw slope triangle.\n        \\draw[#5]   (A)-- node[pos=0.5,anchor=north] {}\n                    (B)-- \n                    (C)-- node[pos=0.5,anchor=west] {#4}\n                    cycle;\n    }\n}\n%%% END MACRO FOR ANNOTATION OF TRIANGLE WITH SLOPE %%%.\n\n\\newcommand{\\logLogSlopeTriangleNeg}[5]\n{\n    % #1. Relative offset in x direction.\n    % #2. Width in x direction, so xA-xB.\n    % #3. Relative offset in y direction.\n    % #4. Slope d(y)/d(log10(x)).\n    % #5. Plot options.\n\n    \\pgfplotsextra\n    {\n        \\pgfkeysgetvalue{/pgfplots/xmin}{\\xmin}\n        \\pgfkeysgetvalue{/pgfplots/xmax}{\\xmax}\n        \\pgfkeysgetvalue{/pgfplots/ymin}{\\ymin}\n        \\pgfkeysgetvalue{/pgfplots/ymax}{\\ymax}\n\n        % Calculate auxilliary quantities, in relative sense.\n        \\pgfmathsetmacro{\\xArel}{#1}\n        \\pgfmathsetmacro{\\yArel}{#3}\n        \\pgfmathsetmacro{\\xBrel}{#1-#2}\n        \\pgfmathsetmacro{\\yBrel}{\\yArel}\n        \\pgfmathsetmacro{\\xCrel}{\\xArel}\n\n        \\pgfmathsetmacro{\\lnxB}{\\xmin*(1-(#1-#2))+\\xmax*(#1-#2)} % in [xmin,xmax].\n        \\pgfmathsetmacro{\\lnxA}{\\xmin*(1-#1)+\\xmax*#1} % in [xmin,xmax].\n        \\pgfmathsetmacro{\\lnyA}{\\ymin*(1-#3)+\\ymax*#3} % in [ymin,ymax].\n        \\pgfmathsetmacro{\\lnyC}{\\lnyA+#4*(\\lnxA-\\lnxB)}\n        \\pgfmathsetmacro{\\yCrel}{\\lnyC-\\ymin)/(\\ymax-\\ymin)} % THE IMPROVED EXPRESSION WITHOUT 'DIMENSION TOO LARGE' ERROR.\n\n        % Define coordinates for \\draw. MIND THE 'rel axis cs' as opposed to the 'axis cs'.\n        \\coordinate (A) at (rel axis cs:\\xArel,\\yArel);\n        \\coordinate (B) at (rel axis cs:\\xBrel,\\yBrel);\n        \\coordinate (C) at (rel axis cs:\\xCrel,\\yCrel);\n\n        % Draw slope triangle.\n        \\draw[#5]   (A)-- node[pos=.5,anchor=south] {}\n                    (B)-- \n                    (C)-- node[pos=0.5,anchor=west] {#4}\n                    cycle;\n    }\n}\n%%% END MACRO FOR ANNOTATION OF TRIANGLE WITH SLOPE %%%.\n\n%%% START MACRO FOR ANNOTATION OF TRIANGLE WITH SLOPE %%%.\n\\newcommand{\\logLogSlopeTriangleFlipNeg}[5]\n{\n    % #1. Relative offset in x direction.\n    % #2. Width in x direction, so xA-xB.\n    % #3. Relative offset in y direction.\n    % #4. Slope d(y)/d(log10(x)).\n    % #5. Plot options.\n\n    \\pgfplotsextra\n    {\n        \\pgfkeysgetvalue{/pgfplots/xmin}{\\xmin}\n        \\pgfkeysgetvalue{/pgfplots/xmax}{\\xmax}\n        \\pgfkeysgetvalue{/pgfplots/ymin}{\\ymin}\n        \\pgfkeysgetvalue{/pgfplots/ymax}{\\ymax}\n\n        % Calculate auxilliary quantities, in relative sense.\n        %\\pgfmathsetmacro{\\xArel}{#1}\n        %\\pgfmathsetmacro{\\yArel}{#3}\n        \\pgfmathsetmacro{\\xBrel}{#1-#2}\n        \\pgfmathsetmacro{\\yBrel}{#3}\n        \\pgfmathsetmacro{\\xCrel}{#1}\n\n        \\pgfmathsetmacro{\\lnxB}{\\xmin*(1-(#1-#2))+\\xmax*(#1-#2)} % in [xmin,xmax].\n        \\pgfmathsetmacro{\\lnxA}{\\xmin*(1-#1)+\\xmax*#1} % in [xmin,xmax].\n        \\pgfmathsetmacro{\\lnyA}{\\ymin*(1-#3)+\\ymax*#3} % in [ymin,ymax].\n        \\pgfmathsetmacro{\\lnyC}{\\lnyA+#4*(\\lnxA-\\lnxB)}\n        \\pgfmathsetmacro{\\yCrel}{\\lnyC-\\ymin)/(\\ymax-\\ymin)} % THE IMPROVED EXPRESSION WITHOUT 'DIMENSION TOO LARGE' ERROR.\n\n\t\\pgfmathsetmacro{\\xArel}{\\xBrel}\n        \\pgfmathsetmacro{\\yArel}{\\yCrel}\n\n        % Define coordinates for \\draw. MIND THE 'rel axis cs' as opposed to the 'axis cs'.\n        \\coordinate (A) at (rel axis cs:\\xArel,\\yArel);\n        \\coordinate (B) at (rel axis cs:\\xBrel,\\yBrel);\n        \\coordinate (C) at (rel axis cs:\\xCrel,\\yCrel);\n\n        % Draw slope triangle.\n        \\draw[#5]   (A)-- node[pos=0.5,anchor=east] {#4}\n                    (B)-- \n                    (C)-- node[pos=0.5,anchor=north] {1}\n                    cycle;\n    }\n}\n%%% END MACRO FOR ANNOTATION OF TRIANGLE WITH SLOPE %%%.\n\n\n%%% START MACRO FOR ANNOTATION OF TRIANGLE WITH SLOPE %%%.\n\\newcommand{\\logLogSlopeTriangleFlip}[5]\n{\n    % #1. Relative offset in x direction.\n    % #2. Width in x direction, so xA-xB.\n    % #3. Relative offset in y direction.\n    % #4. Slope d(y)/d(log10(x)).\n    % #5. Plot options.\n\n    \\pgfplotsextra\n    {\n        \\pgfkeysgetvalue{/pgfplots/xmin}{\\xmin}\n        \\pgfkeysgetvalue{/pgfplots/xmax}{\\xmax}\n        \\pgfkeysgetvalue{/pgfplots/ymin}{\\ymin}\n        \\pgfkeysgetvalue{/pgfplots/ymax}{\\ymax}\n\n        % Calculate auxilliary quantities, in relative sense.\n        %\\pgfmathsetmacro{\\xArel}{#1}\n        %\\pgfmathsetmacro{\\yArel}{#3}\n        \\pgfmathsetmacro{\\xBrel}{#1-#2}\n        \\pgfmathsetmacro{\\yBrel}{#3}\n        \\pgfmathsetmacro{\\xCrel}{#1}\n\n        \\pgfmathsetmacro{\\lnxB}{\\xmin*(1-(#1-#2))+\\xmax*(#1-#2)} % in [xmin,xmax].\n        \\pgfmathsetmacro{\\lnxA}{\\xmin*(1-#1)+\\xmax*#1} % in [xmin,xmax].\n        \\pgfmathsetmacro{\\lnyA}{\\ymin*(1-#3)+\\ymax*#3} % in [ymin,ymax].\n        \\pgfmathsetmacro{\\lnyC}{\\lnyA+#4*(\\lnxA-\\lnxB)}\n        \\pgfmathsetmacro{\\yCrel}{\\lnyC-\\ymin)/(\\ymax-\\ymin)} % THE IMPROVED EXPRESSION WITHOUT 'DIMENSION TOO LARGE' ERROR.\n\n\t\\pgfmathsetmacro{\\xArel}{\\xBrel}\n        \\pgfmathsetmacro{\\yArel}{\\yCrel}\n\n        % Define coordinates for \\draw. MIND THE 'rel axis cs' as opposed to the 'axis cs'.\n        \\coordinate (A) at (rel axis cs:\\xArel,\\yArel);\n        \\coordinate (B) at (rel axis cs:\\xBrel,\\yBrel);\n        \\coordinate (C) at (rel axis cs:\\xCrel,\\yCrel);\n\n        % Draw slope triangle.\n        \\draw[#5]   (A)-- node[pos=0.5,anchor=east] {#4}\n                    (B)-- \n                    (C)-- node[pos=0.5,anchor=south] {}\n                    cycle;\n    }\n}\n%%% END MACRO FOR ANNOTATION OF TRIANGLE WITH SLOPE %%%.\n\n\\theoremstyle{definition}\n\\newtheorem{definition}{Definition}\n\\theoremstyle{lemma}\n\\newtheorem{lemma}{Lemma}\n\\newtheorem*{remark}{Remark}\n\\theoremstyle{theorem}\n\\newtheorem{theorem}{Theorem}\n\\theoremstyle{assumption}\n\\newtheorem{assumption}{Assumption}\n\n%\\DeclareMathOperator{\\diag}{diag}\n\\DeclareMathOperator{\\diam}{diam}\n\n\\renewcommand{\\topfraction}{0.85}\n\\renewcommand{\\textfraction}{0.1}\n\\renewcommand{\\floatpagefraction}{0.75}\n\n\n\\newcommand{\\bbm}[1]{\\mathbbm{#1}}\n\\newcommand{\\bs}[1]{\\boldsymbol{#1}}\n\\newcommand{\\equaldef}{\\stackrel{\\mathrm{def}}{=}}\n\n\n\\newcommand{\\mb}[1]{\\mathbf{#1}}\n\\newcommand{\\mbb}[1]{\\mathbb{#1}}\n\\newcommand{\\mc}[1]{\\mathcal{#1}}\n\n\\renewcommand{\\hat}{\\widehat}\n\\renewcommand{\\tilde}{\\widetilde}\n\\newcommand{\\td}[2]{\\frac{{\\rm d}#1}{{\\rm d}{\\rm #2}}}\n\\newcommand{\\pd}[2]{\\frac{\\partial#1}{\\partial#2}}\n\\newcommand{\\pdn}[3]{\\frac{\\partial^{#3}#1}{\\partial#2^{#3}}}\n\\newcommand{\\snor}[1]{\\left| #1 \\right|}\n\\newcommand{\\nor}[1]{\\left\\| #1 \\right\\|}\n\\newcommand{\\LRp}[1]{\\left( #1 \\right)}\n\\newcommand{\\LRs}[1]{\\left[ #1 \\right]}\n\\newcommand{\\LRa}[1]{\\left\\langle #1 \\right\\rangle}\n\\newcommand{\\LRb}[1]{\\left| #1 \\right|}\n\\newcommand{\\LRc}[1]{\\left\\{ #1 \\right\\}}\n\\newcommand{\\LRceil}[1]{\\left\\lceil #1 \\right\\rceil}\n\\newcommand{\\LRl}[1]{\\left. \\LRp{#1} \\right|}\n\\newcommand{\\jump}[1] {\\ensuremath{\\llbracket#1\\rrbracket}}\n\\newcommand{\\avg}[1] {\\ensuremath{\\LRc{\\!\\{#1\\}\\!}}}\n\\newcommand{\\Grad} {\\ensuremath{\\nabla}}\n\\newcommand{\\note}[1]{{\\color{blue}{#1}}}\n\\newcommand{\\lcwnote}[1]{{\\color{magenta}{#1}}}\n\\renewcommand{\\d}{\\partial}\n\\newcommand{\\diag}[1]{{\\rm diag}\\LRp{#1}}\n\n\n\n\\newcommand{\\LK}{L^2\\LRp{D^k}}\n\\newcommand{\\LdK}{L^2\\LRp{\\partial D^k}}\n\\newcommand{\\Dhat}{\\widehat{D}}\n\\newcommand{\\Lhat}{L^2\\LRp{\\Dhat}}\n\n\n\\newcommand*\\diff[1]{\\mathop{}\\!{\\mathrm{d}#1}} % d in integrand\n\n\\date{}\n\\author{Jesse Chan, Lucas C. Wilcox}\n\\title{On discretely entropy stable weight-adjusted discontinuous Galerkin methods: curvilinear meshes}% and GPU acceleration}\n\\graphicspath{{./figs/}}\n\n\n\\begin{document}\n\n\\maketitle\n\n\\begin{abstract}\nWe construct entropy conservative and entropy stable high order accurate discontinuous Galerkin (DG) discretizations for time-dependent nonlinear hyperbolic conservation laws on curvilinear meshes by extending the methodology of \\cite{chan2017discretely}.  The resulting schemes preserve a semi-discrete quadrature approximation of a continuous global entropy inequality.  The proof requires the satisfaction of a discrete geometric conservation law, which we enforce through a modification of an approach introduced in \\cite{kopriva2006metric}.  We extend the construction of entropy conservative and entropy stable DG schemes to the case when high order accurate curvilinear mass matrices are approximated using low-storage weight-adjusted approximations \\cite{chan2016weight1, chan2016weight2}.  We present numerical experiments which verify theoretical results for the compressible Euler equations on triangular and tetrahedral meshes.  %in two and three dimensions.\n\\end{abstract}\n\n%\\tableofcontents\n\n\\section{Introduction}\n\nHigh order discontinuous Galerkin (DG) methods are attractive for the simulation of time-dependent wave propagation due to their low numerical dispersion and dissipation \\cite{hu1999analysis, ainsworth2004dispersive} and ability to handle unstructured meshes and complex geometries.  These same properties make them attractive for the resolution of transient waves and vortices in compressible flow \\cite{wang2013high}.  However, whereas the construction of stable DG methods for wave propagation is relatively well-established, it is not possible to extend the same formulations directly from linear wave problems to the nonlinear conservation laws which govern compressible fluid flow.  \n\nThe low numerical dissipation of high order DG methods combined with the lack of inherently stable formulations for nonlinear conservation laws has given high order discretizations the reputation of being non-robust and highly sensitive to instabilities and under-resolved features \\cite{wang2013high}.  This instability is addressed in practice by adding additional stabilization through limiting, filtering, or artificial viscosity \\cite{persson2006sub, krivodonova2007limiters, barter2010shock, guermond2011entropy}.  However, these approaches are typically ad-hoc, and do not guarantee the stability of the resulting scheme.  Moreover, high order accuracy can be lost if the stabilization is too strong.  \n\nThe lack of inherently stable formulations was addressed for high order nodal DG methods on quadrilateral and hexahedral meshes in \\cite{fisher2013high, carpenter2014entropy}.  The resulting schemes ensure that that the numerical solution satisfies a semi-discrete version of an entropy inequality, independently of discrete effects such as under-integration.  This results in significantly more robust high order simulations, where the numerical solution does not blow up even in the presence of under-resolved features such as shock discontinuities or turbulence.  High order entropy stable schemes have since been extended to staggered grid and non-conforming \\cite{parsani2016entropy, friedrich2017entropy} tensor product elements, as well as to simplicial meshes \\cite{chen2017entropy, chan2017discretely, crean2018entropy}.  \n\nEntropy stable methods have largely relied on a finite difference summation-by-parts (SBP) framework.  The summation-by-parts property holds for spectral element DG methods (DG-SEM), which assume a polynomial basis which collocates the solution at Gauss--Legendre--Lobatto (GLL) quadrature nodes on tensor product elements.  The collocation approach requires the number of quadrature nodes to be identical to the number of basis functions.  Because analogous quadrature rules on the triangle and tetrahedron must contain more nodes than the dimension of the underlying polynomial space \\cite{helenbrook2009existence, hicken2016multidimensional}, GLL-like collocation cannot be replicated on simplicial elements.  It is still possible to construct entropy stable schemes on simplicial elements within the SBP framework \\cite{chen2017entropy, crean2018entropy}.   However, the resulting SBP operators are not ``modal'', in the sense that the matrices are not associated with an underlying basis or approximation space.  \n\nEntropy stable schemes were extended to modal discretizations on affine meshes in \\cite{chan2017discretely}, allowing for the use of arbitrary basis functions and over-integrated quadrature rules.  In this work, we show how to extend the construction of modal high order entropy stable schemes to curved meshes.  As noted in \\cite{crean2018entropy}, this requires the use of a split formulation for the geometric terms involved in differentiation, as well as the satisfaction of a discrete geometric conservation law (GCL) \\cite{thomas1979geometric, kopriva2006metric}.  We also show how to extend entropy stable schemes to accomodate weight-adjusted mass matrices, which provide low storage approximations of inverse weighted mass matrices appearing for curved meshes \\cite{chan2016weight2}.  These weight-adjusted approximations can be applied more efficiently than inverse weighted mass matrices on many-core architectures such as Graphics Processing Units (GPUs) \\cite{chan2017weight}.   However, additional steps are required to ensure entropy stability and the conservation of mass, momentum, and energy under weight-adjusted mass matrices.\n\nThe paper is organized as follows: Section~\\ref{sec:1} reviews the derivation of entropy inequalities for systems of nonlinear conservation laws, and describes why this does not hold under a high order DG discretization.  Section~\\ref{sec:2} describes the construction of entropy stable DG methods for curved meshes using weighted mass matrices, and Section~\\ref{sec:3} describes how to extend this to the case of weight-adjusted mass matrices.  Section~\\ref{sec:4} describes how to enforce the geometric conservation law using a modification of the approach described in \\cite{kopriva2006metric}, and Section~\\ref{sec:num} concludes by presenting two and three-dimensional numerical experiments which verify the accuracy and stability of the presented schemes.  \n\n\\section{Systems of nonlinear conservation laws}\n\\label{sec:1}\nThis work addresses high order accurate schemes for the following system of $n$ nonlinear conservation laws in $d$ dimensions \n\\begin{equation}\n  \\pd{\\bm{u}}{t} + \\sum_{j=1}^d\\pd{\\bm{f}_j(\\bm{u})}{x_j}  = 0, \\qquad \\bm{u} : \\mathbb{R}^d \\times [0,\\infty) \\rightarrow  \\mathbb{R}^n, \\qquad \\bm{f}_j : \\mathbb{R}^n\\rightarrow \\mathbb{R}^n,\n\\label{eq:nonlineqs}\n\\end{equation}\nwhere $\\bm{u}(\\bm{x},t)$ denotes the \\emph{conservative variables} for this system.  %We assume the system is well-posed under appropriate boundary conditions.\nWe are interested in nonlinear conservation laws for which an entropy function $U(\\bm{u})$ exists, where $U(\\bm{u})$ is convex with respect to the conservative variables $\\bm{u}$.  If this function exists, then it is possible to define \\emph{entropy variables} $\\bm{v}(\\bm{u}) = \\pd{U}{\\bm{u}}$.  These functions symmetrize the system of nonlinear conservation laws (\\ref{eq:nonlineqs}) \\cite{hughes1986new}.  \n\nIt can be shown (see, for example, \\cite{mock1980systems}) that symmetrization is equivalent to the existence of entropy flux functions $F_j(\\bm{u})$ and entropy potentials $\\psi_j$ such that\n\\[\n\\bm{v}^T \\pd{\\bm{f}_j}{\\bm{u}} = \\pd{F_j(\\bm{u})}{\\bm{u}}^T, \\qquad \\psi_j(\\bm{v}) = \\bm{v}^T\\bm{f}_j(\\bm{u}(\\bm{v})) - F_j(\\bm{u}(\\bm{v})), \\qquad \\psi_j'(\\bm{v}) = \\bm{f}_j(\\bm{u}(\\bm{v})).\n\\]\nSmooth solutions of (\\ref{eq:nonlineqs}) can be shown to satisfy a conservation of entropy by multiplying (\\ref{eq:nonlineqs}) by $\\bm{v}(\\bm{u})$. Using the definition of the entropy variables, entropy flux, and the chain rule yields\n\\begin{equation}\n\\bm{v}^T\\pd{\\bm{f}_j(\\bm{u})}{x_j} = \\pd{U(\\bm{u})}{\\bm{u}}^T\\pd{\\bm{f}_j(\\bm{u})}{\\bm{u}}\\pd{\\bm{u}}{x_j} = \\pd{F_j(\\bm{u})}{x_j}, \\qquad \\pd{U(\\bm{u})}{t} + \\sum_{j=1}^d \\pd{F_j(\\bm{u})}{x_j} = 0.\n\\label{eq:chainrule}\n\\end{equation}\n%and that\n%\\begin{equation*}\n%\n%%\\label{eq:entropyeqstrong}\n%\\end{equation*}\nLet $\\Omega \\subset \\mathbb{R}^d$ be a closed domain with boundary $\\partial \\Omega$.  Integrating over $\\Omega$ and using Gauss' theorem on the spatial derivative yields\n\\begin{equation}\n  \\int_{\\Omega}\\pd{U(\\bm{u})}{t}\\diff{\\bm{x}} + \\int_{\\partial \\Omega} \\sum_{j=1}^d \\LRp{\\bm{v}{(\\bm{u})}^T\\bm{f}_j(\\bm{u}) - \\psi_j\\LRp{\\bm{v}(\\bm{u})}}n_j \\diff{\\bm{x}} = 0,\n\\label{eq:entropyeq}\n\\end{equation}\nwhere $\\bm{n} = \\LRp{n_1,\\ldots,n_d}^T$ denotes the unit outward normal vector on $\\partial \\Omega$.  \n\nGeneral solutions (including non-smooth solutions such as shocks) satisfy an entropy \\emph{inequality}\n\\begin{equation}\n  \\int_{\\Omega}\\pd{U(\\bm{u})}{t}\\diff{\\bm{x}} + \\int_{\\partial \\Omega} \\sum_{j=1}^d \\LRp{\\bm{v}{(\\bm{u})}^T\\bm{f}_j(\\bm{u}) - \\psi_j\\LRp{\\bm{v}(\\bm{u})}}n_j \\diff{\\bm{x}} \\leq 0,\n\\label{eq:entropyineq}\n\\end{equation}\nwhich results from considering solutions of an appropriate viscous form of the equations (\\ref{eq:nonlineqs}) and taking the limit as viscosity vanishes.  In this work, schemes which satisfy a discrete form of (\\ref{eq:entropyineq}) will be constructed by first enforcing a discrete version of entropy conservation (\\ref{eq:entropyeq}), then adding an appropriate numerical dissipation which will enforce the entropy inequality (\\ref{eq:entropyineq}).  \n\n\n\\subsection{Standard DG formulations for nonlinear conservation laws}\n\nWe begin by reviewing the construction of standard high order accurate DG formulations for (\\ref{eq:nonlineqs}).  \n\n\\subsubsection{Mathematical notation}\n\nLet the domain $\\Omega \\subset \\mathbb{R}^d$ be decomposed into elements (subdomains) $D^k$, and let $\\hat{D}$ denote a $d$-dimensional reference element with boundary $\\partial \\hat{D}$.  Let $\\hat{\\bm{x}} = \\LRc{\\hat{x}_1,\\ldots,\\hat{x}_d}$ denote coordinates on $\\hat{D}$, and let $\\hat{n}_i$ denote and the $i$th component of the unit normal vector on $\\partial \\hat{D}$.  We assume that $\\hat{n}_i$ is constant; i.e., that the faces of the reference element are planar (this assumption holds for all commonly used reference elements \\cite{chan2015gpu}).  \n\nWe will assume that each physical element $D^k$ is the image of $\\hat{D}$ under some smoothly differentiable mapping $\\bm{\\Phi}_k(\\hat{\\bm{x}})$ such that\n\\[\n\\bm{x} = \\bm{\\Phi}_k(\\hat{\\bm{x}}), \\qquad \\bm{x}\\in D^k.\n\\]\nThis also implies that integrals over physical elements can be mapped back to the reference element as follows\n\\[\n\\int_{D^k} u \\diff{\\bm{x}} = \\int_{\\hat{D}} u J^k\\diff{\\hat{\\bm{x}}}, \n\\]\nwhere $J^k$ denotes the determinant of the Jacobian of $\\bm{\\Phi}_k$.  Integrals over physical faces of $D^k$ can similarly be mapped back to reference faces.\n\n\nWe define an approximation space using degree $N$ polynomials on the reference element.  For example, on a $d$-dimensional reference simplex, the natural polynomial space are total degree $N$ polynomials \n\\[\nP^N\\LRp{\\widehat{D}} = \\LRc{\\hat{x}_1^{i_1}\\ldots\\hat{x}_d^{i_d}, \\quad \\hat{\\bm{x}} \\in \\widehat{D}, \\quad 0\\leq \\sum_{k=1}^d i_k \\leq N}.\n\\]\nOther element types possess different natural polynomial spaces \\cite{chan2015gpu}, but typically contain the space of total degree $N$ polynomials.  This work is directly applicable to other elements and spaces as well.  We denote the dimension of the approximation space $P^N$ as $N_p = {\\rm dim}\\LRp{P^N\\LRp{\\widehat{D}}}$.  We also define trace spaces for each face of the reference element.  Let $\\hat{f}$ be a face of the reference element $\\hat{D}$.  The trace space over $\\hat{f}$ is defined as the space of traces of functions in $P^N\\LRp{\\hat{D}}$\n\\[\nP^N_f \\LRp{\\hat{f}} = \\LRc{ \\left.u\\right|_{\\hat{f}}, \\quad u \\in P^N\\LRp{\\hat{D}}}, \\qquad \\hat{f}\\in \\partial\\hat{D}.\n\\]\nWe denote the dimension of the trace space as ${\\rm dim}\\LRp{P^N_f\\LRp{\\hat{f}}} = N^f_p$.\n\nWe next define the $L^2$ norm and inner products over the reference element $\\hat{D}$ and the surface of the reference element $\\partial \\hat{D}$ as\n\\[\n  \\LRp{\\bm{u},\\bm{v}}_{\\hat{D}} =  \\int_{\\widehat{D}} \\bm{u}\\cdot\\bm{v} \\diff{\\hat{\\bm{x}}}, \\qquad \\nor{\\bm{u}}^2_{\\hat{D}} = (\\bm{u},\\bm{u})_{\\hat{D}}, \\qquad \\LRa{\\bm{u},\\bm{v}}_{\\partial \\hat{D}} = \\int_{\\partial \\hat{D}} \\bm{u} \\cdot \\bm{v} \\diff{\\hat{\\bm{x}}}.\n\\]\nWe also introduce the continuous $L^2$ projection operator $\\Pi_N$ and lifting operator $L$.  For $u \\in L^2\\LRp{\\widehat{D}}$, the $L^2$ projection $\\Pi_N u$ is defined through\n\\begin{equation}\n\\int_{\\widehat{D}} \\Pi_N u v \\diff{\\hat{\\bm{x}}} = \\int_{\\widehat{D}} u v \\diff{\\hat{\\bm{x}}}, \\qquad \\forall v\\in P^N\\LRp{\\hat{D}}.\n\\label{eq:l2proj}\n\\end{equation}\nLikewise, for a boundary function $u \\in L^2\\LRp{\\partial \\hat{D}}$, the lifting operator $L$ \\cite{hesthaven2007nodal, di2011mathematical} is defined through \n\\begin{equation}\n\\LRp{L u,v}_{\\hat{D}} = \\LRa{u,v}_{\\partial \\hat{D}}, \\qquad \\forall v \\in P^N\\LRp{\\hat{D}}.\n\\label{eq:lift}\n\\end{equation}\n\nFinally, we introduce $L^2, L^{\\infty}$ Sobolev norms and spaces, which will be utilized for error estimates.  The $L^2$ space is defined as the space of functions with finite $L^2$ norm.  The Lebesgue $L^\\infty$ norm and the associated $L^\\infty$ space over a general domain $\\Omega$ are \n\\begin{align*}\n\\nor{u}_{L^{\\infty}\\LRp{\\Omega}} &= \\inf\\LRc{C \\geq 0: \\LRb{u\\LRp{\\bm{x}}} \\leq C \\quad \\forall \\bm{x}\\in \\Omega}, \\qquad\nL^{\\infty}\\LRp{\\Omega} = \\LRc{u: \\Omega\\rightarrow \\mathbb{R}, \\quad \\nor{u}_{L^{\\infty}\\LRp{\\Omega}} < \\infty}.\n\\end{align*}\nThe $L^2$ and $L^{\\infty}$ Sobolev norms of degree $s$ are then defined  as\n\\begin{align*}\n%\\LRb{u}_{W^{s,p}\\LRp{\\Omega}} &= \\LRp{\\sum_{\\LRb{\\alpha}= s} \\nor{ D^{\\alpha} u}_{L^p\\LRp{\\Omega}}^p}^{1/p}, \\qquad \\LRb{u}_{W^{s,\\infty}\\LRp{\\Omega}} = \\max_{\\LRb{\\alpha}= s} \\nor{D^{\\alpha}u}_{L^{\\infty}\\LRp{\\Omega}}\\\\\n\\nor{u}_{W^{s,2}\\LRp{\\Omega}}^2 &= {\\sum_{\\LRb{\\alpha}\\leq s} \\nor{ D^{\\alpha} u}_{L^2\\LRp{\\Omega}}^2}, \\qquad \\nor{u}_{W^{s,\\infty}\\LRp{\\Omega}} = \\max_{\\LRb{\\alpha}\\leq s} \\nor{D^{\\alpha}u}_{L^{\\infty}\\LRp{\\Omega}},\n\\end{align*}\nrespectively.  Here $\\alpha = \\LRc{\\alpha_1,\\ldots,\\alpha_d}$ is a multi-index\nof order $\\LRb{\\alpha} = \\alpha_1 + \\cdots + \\alpha_d$ such that\n\\[\nD^{\\alpha}u = \\pd{^{\\alpha_1}}{x_1^{\\alpha_1}}\\cdots\\pd{^{\\alpha_d}}{x_d^{\\alpha_d}} u.\n\\]\nThe Sobolev spaces $W^{s,2}$ and $W^{s,\\infty}$ are defined as the spaces of functions with finite $L^2$ and $L^\\infty$ Sobolev norms of degree $s$, respectively.\n\n\n\n\\subsubsection{Discontinuous Galerkin formulations and the $L^2$ projection}\n\nDiscontinuous Galerkin methods have been widely applied to systems of nonlinear conservation laws (\\ref{eq:nonlineqs}) \\cite{cockburn1989tvb, cockburn1998runge, cockburn2001devising}.  The development of new discontinuous Galerkin methods for nonlinear conservation laws has focused heavily on the choice of numerical flux \\cite{qiu2006numerical} or the development of  slope limiters \\cite{krivodonova2007limiters, zhang2012maximum} and artificial viscosity strategies \\cite{persson2006sub, barter2010shock, klockner2011viscous}.  However, the treatment of the underlying volume discretization remains relatively unchanged between each of these approaches.  \n\nIgnoring terms involving filters, limiters, or artificial viscosity, a semi-discrete ``weak'' DG formulation  for (\\ref{eq:nonlineqs}) can be given locally over an element $D^k$: find $\\bm{u}\\in \\LRp{P^N\\LRp{D^k} \\times [0,\\infty)}^n$ such that\n\\begin{align}\n\\int_{D^k} \\LRp{\\pd{\\bm{u}}{t}\\cdot \\bm{v} - \\sum_{j=1}^d\\bm{f}_j(\\bm{u}) \\cdot \\pd{\\bm{v}}{x_i}} \\diff{\\bm{x}} \n+ \\sum_{j=1}^d \\int_{\\partial D^k} \\LRp{\\bm{f}^*_j\\LRp{\\bm{u}^+,\\bm{u}} }\\cdot \\bm{v} n_j  \\diff{\\bm{x}} = 0, \\qquad \\forall \\bm{v}\\in \\LRp{P^N\\LRp{D^k}}^n,\n\\label{eq:weakdg}\n\\end{align}\nwhere the numerical flux $\\bm{f}^*$ is a function of the solution $\\bm{u}$ on both $D^k$ and neighboring elements.  \n\nUnfortunately, solutions to (\\ref{eq:weakdg}) do not (in general) obey a discrete version of the entropy inequality (\\ref{eq:entropyineq}).  Since (\\ref{eq:entropyineq}) is a generalized statement of energy stability, the lack of a discrete entropy inequality implies that the discrete solution can blow up in finite time.  The reason for this is due to the fact that, in practice, the integrals in (\\ref{eq:weakdg}) are not computed exactly and are instead approximated using polynomially exact quadratures.  This is compounded by the fact that the nonlinear flux function $\\bm{f}_j\\LRp{\\bm{u}}$ is often rational and impossible to integrate exactly using polynomial quadratures.  \n\nWhile this paper focuses on curved meshes, the inexactness of quadrature leads to the loss of the chain rule and thus the loss of entropy conservation or entropy dissipation (\\ref{eq:entropyineq}) even on affine meshes.  We can rewrite (\\ref{eq:weakdg}) in a strong form using a discrete quadrature-based $L^2$ projection.  For polynomial approximation spaces on affine meshes, $\\pd{\\bm{v}}{x_i}$ is polynomial.  \nThen, mapping (\\ref{eq:weakdg}) back to the reference element $\\hat{D}$ and using the $L^2$ projection and (\\ref{eq:l2proj}), we have that\n\\[\n\\int_{D^k} \\bm{f}_j(\\bm{u}) \\cdot \\pd{\\bm{v}}{x_i} \\diff{\\bm{x}} = \\int_{\\hat{D}} \\Pi_N \\bm{f}_j(\\bm{u}) \\cdot \\pd{\\bm{v}}{x_i} J^k\\diff{\\bm{x}}.\n\\]\nThus, integrating by parts (\\ref{eq:weakdg}) recovers a ``strong'' DG formulation involving the projection operator\n\\begin{align}\n&\\int_{D^k} \\LRp{\\pd{\\bm{u}}{t} - \\sum_{j=1}^d \\pd{\\Pi_N \\bm{f}_j(\\bm{u})}{x_j}} \\cdot \\bm{v} \\diff{\\bm{x}} \\nonumber\\\\\n&+ \\sum_{j=1}^d \\int_{\\partial D^k} \\LRp{\\bm{f}^*_j\\LRp{\\bm{u}^+,\\bm{u}} - \\Pi_N\\bm{f}_j(\\bm{u})}\\cdot \\bm{v} n_j  \\diff{\\bm{x}} = 0, \\qquad \\forall \\bm{v}\\in \\LRp{P^N\\LRp{D^k}}^n.  \n\\label{eq:strongdg}\n\\end{align}\nFrom this, we see that our discrete scheme does not differentiate the nonlinear flux function $\\bm{f}_j\\LRp{\\bm{u}}$ exactly, but instead differentiates the projection of $\\Pi_N \\bm{f}_j\\LRp{\\bm{u}}$ onto polynomials of degree $N$.  Because the $L^2$ projection operator is introduced, the chain rule no longer holds at the discrete level and step (\\ref{eq:chainrule}) of the proof of entropy conservation is no longer valid.  Thus, ensuring discrete entropy stability will require a discrete formulation of the system of nonlinear conservation laws (\\ref{eq:nonlineqs}) from which we can prove a discrete entropy inequality without relying on the chain rule.  \n\n%We note that it is not strictly necessary to introduce the projection operator; however, constructing a ``strong'' DG formulation without a projection operator requires an analytical expression for derivatives of the nonlinear flux function $\\bm{f}_j\\LRp{\\bm{u}}$, which can be complex or expensive to compute.  Moreover, because polynomial quadrature rules are typically used in practice to evaluate integrals, it is not possible to use integration by parts when the nonlinear flux function is rational due to errors in approximating integrals.  Introducing the $L^2$ projection operator resolves both issues, as the integrands involved in integration by parts are polynomials of degree $2N-1$, for which efficient quadratures exist. \n\n\\section{Discretely entropy stable DG methods on curved meshes}\n\\label{sec:2}\nWe will first show how to construct discretely entropy stable high order accurate DG methods on curvilinear meshes, but will present this using a matrix formulation as opposed to a continuous formulation.  This is to ensure that the effects of discretization, nonlinear, and quadrature are accounted for in the proof of semi-discrete entropy stability.  We first introduce quadrature-based matrices, which we will then use to construct discretely entropy stable DG formulations.\n\n\n\\subsection{Basis and quadrature rules}\n\n{We now introduce quadrature-based matrices for the $d$-dimensional reference element $\\widehat{D}$, which we will use to construct matrix-vector formulations of DG methods.   Assuming $u(\\hat{\\bm{x}}) \\in P^N\\LRp{\\widehat{D}}$, it can be represented in terms of the vector of coefficients $\\bm{u}$ using some polynomial basis $\\phi_i$ of degree $N$ and dimension $N_p$ \n\\[\n  u(\\hat{\\bm{x}}) = \\sum_{j=1}^{N_p}\\bm{u}_j \\phi_j(\\widehat{\\bm{x}}), \\qquad P^N\\LRp{\\widehat{D}} = {\\rm span}\\LRc{\\phi_i(\\widehat{x})}_{i=1}^{N_p}.\n\\]\n\nWe construct quadrature-based matrices based on $\\phi_i$ and appropriate volume and surface quadrature rules.  The volume and surface quadrature rules are given by points and positive weights $\\LRc{(\\hat{\\bm{x}}_i, \\hat{w}_i)}_{i=1}^{N_q}$ and $\\LRc{(\\hat{\\bm{x}}^f_i, \\hat{w}^f_i)}_{i=1}^{N^f_q}$, respectively.  We make the following assumptions on the strength of these quadratures: %\\note{finish!  Note that we want quadratures such that discrete IBP holds.  For example, GLL or $2N-1$ vol and $2N$ surface. }\n\\begin{assumption}[Integration by parts under quadrature]\n  The volume quadrature rule  $\\LRc{(\\hat{\\bm{x}}_i, \\hat{w}_i)}_{i=1}^{N_q}$ is exact for polynomials of degree $2N-1$.  Additionally, \nfor any $u, v \\in P^N\\LRp{\\hat{D}}$, integration by parts \n\\[\n  \\LRp{\\pd{u}{\\hat{x}_i},v}_{\\hat{D}} = \\LRa{u,v\\hat{n}_i}_{\\partial \\hat{D}} - \\LRp{u,\\pd{v}{\\hat{x}_i}}_{\\hat{D}}\n\\]\nholds when the volume and surface integrals are approximated using quadrature.\n\\label{ass:quad}\n\\end{assumption}\nAssumption~\\ref{ass:quad} holds, for example, for any surface quadrature rule which is exact for degree $2N$ polynomials on the boundary of the reference element $\\partial \\hat{D}$.  \n\n\n\\subsection{Reference element matrices}\n\\label{sec:matrix}\n\nLet $\\bm{W}, \\bm{W}_f$ denote diagonal matrices whose entries are volume and surface quadrature weights, respectively.  The surface quadrature weights are given by quadrature weights on reference faces, which are mapped to faces of the reference element.  We define the volume and surface quadrature interpolation matrices $\\bm{V}_q$ and $\\bm{V}_f$ such that\n\\begin{align}\n\\LRp{\\bm{V}_q}_{ij} &= \\phi_j(\\hat{\\bm{x}}_i), \\qquad 1 \\leq j \\leq N_p, \\qquad 1 \\leq i \\leq N_q, \\nonumber\\\\\n\\LRp{\\bm{V}_f}_{ij} &= \\phi_j(\\hat{\\bm{x}}^f_i), \\qquad 1 \\leq j \\leq N_p, \\qquad 1 \\leq i \\leq N^f_q,\\label{eq:qinterp}\n\\end{align}\nwhich map coefficients $\\bm{u}$ to evaluations of $u$ at volume and surface quadrature points.  \n\nNext, let ${\\bm{D}}_i$ denote the differentiation matrix with respect to the $i$th coordinate, defined implicitly through the relations\n\\[\nu(\\hat{\\bm{x}}) = \\sum_{j=1}^{N_p} \\bm{u}_j \\phi_j(\\hat{\\bm{x}}), \\qquad \\pd{u}{\\hat{\\bm{x}}_i} = \\sum_{j=1}^{N_p} \\LRp{{\\bm{D}}_i \\bm{u}}_j\\phi_j(\\hat{\\bm{x}}).\n\\]\nThe matrix ${\\bm{D}}_i$ maps basis coefficients of some polynomial $u \\in P^N\\LRp{\\hat{D}}$ to coefficients of its $i$th derivative with respect to the reference coordinate $\\hat{\\bm{x}}$, and is sometimes referred to as a ``modal'' differentiation matrix (with respect to a general non-nodal ``modal'' basis \\cite{hicken2016multidimensional}).  \n\nUsing the volume quadrature interpolation matrix $\\bm{V}_q$, we can compute a quadrature-based mass matrix $\\bm{M}$ by evaluating $L^2$ inner products of different basis functions using quadrature\n\\[\n  \\bm{M} = \\bm{V}_q^T\\bm{W}\\bm{V}_q, \\qquad \\bm{M}_{ij} = \\sum_{k=1}^{N_q} \\hat{w}_k \\phi_j(\\hat{\\bm{x}}_k)\\phi_i(\\hat{\\bm{x}}_k) \\approx \\int_{\\hat{D}}\\phi_j\\phi_i \\diff{\\hat{\\bm{x}}} = \\LRp{\\phi_j,\\phi_i}_{\\hat{D}}.\n\\]\nThe approximation in the formula for the mass matrix becomes an equality if the volume quadrature rule is exact for polynomials of degree $2N$.  The mass matrix is symmetric and positive definite under Assumption~\\ref{ass:quad}; however, we do not make any distinctions between diagonal and dense (lumped) mass matrices in this work.  \n\n\nThe mass matrix appears in the discretization of $L^2$ projection (\\ref{eq:l2proj}) and lift operators (\\ref{eq:lift}) using quadrature.  The result are quadrature-based $L^2$ projection and lift operators $\\bm{P}_q, \\bm{L}_q$, \n\\begin{equation}\n\\bm{P}_q = \\bm{M}^{-1}\\bm{V}_q^T\\bm{W}, \\qquad \\bm{L}_q = \\bm{M}^{-1}\\bm{V}_f^T \\bm{W}_f,\n\\label{eq:projlift}\n\\end{equation}\nwhich are discretizations of the continuous $L^2$ projection operator $\\Pi_N$ and continuous lift operator $L$.  The matrix $\\bm{P}_q$ maps a function (in terms of its evaluation at quadrature points) to coefficients of the $L^2$ projection in the basis $\\phi_j(x)$, while the matrix $\\bm{L}_q$ ``lifts'' a function (evaluated at surface quadrature points) from the boundary of an element to coefficients of a basis defined in the interior of the element.  \n\nFinally, we introduce quadrature-based operators $\\bm{D}_N^i$ which will be used to construct discretizations of our nonlinear conservation laws.  This operator was introduced in \\cite{chan2017discretely} as a ``decoupled summation-by-parts'' operator\n\\begin{equation}\n\\bm{D}_N^i =\\LRs{\n\\begin{array}{cc}\n\\bm{V}_q\\bm{D}_i \\bm{P}_q - \\frac{1}{2}\\bm{V}_q\\bm{L}_q \\diag{\\hat{\\bm{n}}_i\\circ\\bm{\\hat{J}}_f}\\bm{V}_f\\bm{P}_q & \\frac{1}{2}\\bm{V}_q\\bm{L}_q  \\diag{\\hat{\\bm{n}}_i\\circ\\bm{\\hat{J}}_f}\\\\\n- \\frac{1}{2}\\diag{\\hat{\\bm{n}}_i\\circ\\bm{\\hat{J}}_f} \\bm{V}_f\\bm{P}_q &  \\frac{1}{2}\\diag{\\hat{\\bm{n}}_i\\circ\\bm{\\hat{J}}_f}\n%=======\n%  \\bm{V}_q\\bm{D}_i \\bm{P}_q - \\frac{1}{2}\\bm{V}_q\\bm{L}_q \\diag{\\hat{\\bm{n}}_i\\circ\\bm{\\hat{J}}_f}\\bm{V}_f\\bm{P}_q & \\frac{1}{2}\\bm{V}_q\\bm{L}_q  \\diag{\\hat{\\bm{n}}_i\\circ\\bm{\\hat{J}}_f}\\\\\n%  - \\frac{1}{2}\\diag{\\hat{\\bm{n}}_i\\circ\\bm{\\hat{J}}_f} \\bm{V}_f\\bm{P}_q &  \\frac{1}{2}\\diag{\\hat{\\bm{n}}_i\\circ\\bm{\\hat{J}}_f}\n%>>>>>>> cd72d858ec79933e123c7bf1361e488006d5956d\n\\end{array}\n}\n\\label{eq:decoupledsbp}\n\\end{equation}\nwhere $\\hat{\\bm{n}}_i$ is the vector containing values of the $i$th component of the unit normal on the surface of the reference element $\\hat{D}$, and $\\bm{\\hat{J}}_f$ is the vector containing values of the face Jacobian factor $\\hat{J}_f$ which result from mapping a face of $\\hat{D}$ to a reference face.  Here $\\hat{\\bm{n}}_i\\circ\\bm{\\hat{J}}_f$ is the Hadamard product (i.e., the entrywise product) of the vectors $\\hat{\\bm{n}}_i$ and $\\bm{\\hat{J}}_f$.  When combined with projection and lifting matrices, $\\bm{D}_N^i$ produces a high order approximation of non-conservative products.  Let $\\bm{f},\\bm{g}$ denote vectors containing the evaluation of functions $f(\\bm{x}),g(\\bm{x})$ at both volume and surface quadrature points\n\\[\n\\LRs{\\begin{array}{cc}\\bm{P}_q & \\bm{L}_q\\end{array}} \\diag{\\bm{f}}\\bm{D}_N^i \\bm{g} \\approx f\\pd{g}{\\hat{x}_i}.\n\\]\nIt was shown in \\cite{chan2017discretely} that the matrix $\\bm{D}_N^i$ satisfies several key properties.  First, it can be observed that $\\bm{D}_N^i\\bm{1} = 0$, where $\\bm{1}$ is the vector of all ones.  Second, $\\bm{D}_N^i$ satisfies a summation-by-parts property.  Let $\\bm{Q}_N^i$ be the scaling of $\\bm{D}_N^i$ by the diagonal matrix of volume and surface quadrature weights \n\\[\n\\bm{Q}_N^i = \\bm{W}_N \\bm{D}_N^i, \\qquad \\bm{W}_N = \\LRp{\\begin{array}{cc}\n\\bm{W} &\\\\\n& \\bm{W}_f \n\\end{array}}.\n\\]\nThen, $\\bm{Q}_N^i$ satisfies the following discrete analogue of integration by parts \n\\begin{equation}\n\\bm{Q}_N^i + \\LRp{\\bm{Q}_N^i}^T = \\bm{B}^i_N, \\qquad \\bm{B}_N = \\LRp{\\begin{array}{cc}\n\\bm{0}&\\\\\n      & \\bm{W}_f \\diag{\\hat{\\bm{n}}_i\\circ\\hat{\\bm{J}}_f}\n\\end{array}}.\n\\label{eq:sbpprop1}\n\\end{equation}\nThe matrix $\\bm{D}_N^i$ reduces to polynomial differentiation when applied to polynomials, in the sense that\n\\begin{align}\n\\bm{D}_N^i \\LRs{\\begin{array}{c}\n\\bm{V}_q\\\\\n\\bm{V}_f\n\\end{array}} = \\LRs{\\begin{array}{c}\n\\bm{V}_q\\bm{D}_i\\\\\n\\bm{0}\n\\end{array}}.\n\\label{eq:dnvqvf}\n\\end{align}\n\n%, and $\\hat{J}_f$ denotes the Jacobian of the mapping from a face of $\\hat{D}$ to a reference face (for example, the faces of a triangle are mapped back to the bi-unit interval $[-1,1]$).  \n\n\\subsection{Matrices on curved physical elements}\n\\label{sec:curv}\n\nThe key difference between curvilinear and affine meshes is that geometric terms now vary spatially over each element.  In practice, derivatives are computed over the reference element and mapped to the physical element $D^k$ through a change of variables formula\n\\[\nJ^k \\pd{u}{x_i} = \\sum_{j=1}^d G^k_{ij}\\pd{u}{\\hat{x}_j}, \\qquad G^k_{ij} = J^k\\pd{\\hat{x}_j}{x_i},\n\\]\nwhere we have defined the elements of the matrix $\\bm{G}^k$ as the derivatives of the reference coordinates $\\hat{x}_j$ with respect to the physical coordinates $x_i$ on $D^k$ times the Jacobian of the transformation from reference to physical coordinates $J^k$.  We denote evaluations of $G^k_{ij}$ at both volume and surface quadrature points as the vector $\\bm{G}^k_{ij}$.\n\nWe assume in this work that the mesh is stationary.  It can be shown at the continuous level that, for any differentiable and invertible mapping, the quantity $\\bm{G}^k$ satisfies a geometric conservation law (GCL) \\cite{kopriva2006metric, thomas1979geometric}\n\\begin{equation}\n\\sum_{j=1}^d\\pd{}{\\hat{x}_j}G^k_{ij} = 0,\n\\label{eq:gcl}\n\\end{equation}\nor that $\\hat{\\Grad}\\cdot \\bm{G}^k = 0$.  Using (\\ref{eq:gcl}), the scaled physical derivative $J^k\\pd{u}{x_i}$ can be computed via\n\\begin{equation}\nJ^k\\pd{u}{x_i} = \\frac{1}{2}\\sum_{j=1}^d \\LRp{G^k_{ij}\\pd{u}{\\hat{x}_j} + \\pd{\\LRp{G^k_{ij}u}}{\\hat{x}_j}}.\n\\label{eq:splitderiv}\n\\end{equation}\n\nWe will require the following assumptions on the mesh, as well as the geometric terms and outward normal vectors:\n\\begin{assumption}[Mesh assumptions]\nWe assume that the mesh is quasi-uniform.  The mesh is also assumed to be watertight, such that normals are consistent across neighboring elements as follows: for a shared face $f$ between $D^k$ and $D^{k,+}$, the scaled outward normal vectors for each element are equal and opposite at all points such that \n\\begin{align}\n\\bm{n}J^k_f = -\\bm{n}^+J^{k,+}_f.\n\\label{eq:normalsign}\n\\end{align}\nWe also assume that the scaled matrix of geometric terms transforms scaled reference normal vectors to scaled physical normals, such that\n\\begin{align}\n\\sum_{j=1}^d G^k_{ij} \\hat{n}_j\\hat{J}_f = n_i J^k_f, \\qquad \\LRp{\\sum_{j=1}^d \\LRp{\\bm{G}^k_{ij}}_f \\circ\\LRp{\\hat{\\bm{n}}_j\\circ\\hat{\\bm{J}}_f}}\n= \\LRp{\\bm{n}_i\\circ\\bm{J}^k_f},\n\\label{eq:normalconsistency}\n\\end{align}\nwhere $\\bm{n}_j$ and $\\bm{J}^k_f$ are vectors containing evaluations of the physical unit normals and face Jacobian factors for $D^k$ at surface quadrature points, respectively.\nLikewise, $\\LRp{\\bm{G}^k_{ij}}_f$ is a vector containing evaluations of $G^k_{ij}$ at the surface quadrature points.\n\\label{ass:norm}\n\\end{assumption}\nThe properties (\\ref{eq:normalsign}) and (\\ref{eq:normalconsistency}) hold at the continuous level for a watertight mesh \\cite{ciarlet1978finite}, and thus at all points where the geometric terms are computed exactly.  However, we will also consider cases where the geometric terms $G^k_{ij}$ are modified to enforce a discrete form of (\\ref{eq:gcl}); in these situations, it will be important to ensure that (\\ref{eq:normalconsistency}) holds after such modifications.  \n\nSimilar to what is done to stabilize finite difference discretizations~\\cite{nordstrom2006cfdf, gassner2016split}, we define physical differentiation matrices based on the approximation of (\\ref{eq:splitderiv}).  Define $\\bm{D}^i_k$ as\n\\[\n  \\bm{D}^i_k = \\frac12 \\sum_{j=1}^d \\left(\\diag{\\bm{G}^k_{ij}}\\bm{D}^j_N + \\bm{D}^j_N\\diag{\\bm{G}^k_{ij}}\\right).\n\\]\nUsing properties of the Hadamard product \\cite{horn2012matrix}, we can rewrite $\\bm{D}^i_k$ as \n\\begin{equation}\n\\bm{D}^i_k = \\sum_{j=1}^d \\LRp{\\bm{D}^j_N \\circ \\avg{\\bm{G}^k_{ij}}}, \\qquad \\avg{\\bm{G}^k_{ij}}_{mn} = \\frac{1}{2}\\LRp{\\LRp{\\bm{G}^k_{ij}}_m + \\LRp{\\bm{G}^k_{ij}}_n},\n\\label{eq:dik}\n\\end{equation}\nwhere $\\avg{\\bm{G}^k_{ij}}$ denotes the matrix of averages between each of the entries of $\\bm{G}^k_{ij}$.  From Assumption~\\ref{ass:norm} and (\\ref{eq:dik}), it is straightforward to show that (because $\\avg{\\bm{G}^k_{ij}}$ is symmetric) $\\bm{Q}^i_k = \\bm{W}_N\\bm{D}^i_k$ also satisfies a summation-by-parts property\n\\begin{equation}\n\\bm{Q}^i_k + \\LRp{\\bm{Q}^i_k}^T = \\bm{B}^i_k, \\qquad \\bm{B}^i_k = \n\\LRp{\\begin{array}{cc}\n\\bm{0}&\\\\\n& \\bm{W}_f \\diag{\\bm{n}_i\\circ\\bm{J}^k_f}\n\\end{array}}.\n\\label{eq:sbpk}\n\\end{equation}\n\nCurvilinear mappings also imply that integrals over each physical element $D^k$ are no longer simple scalings of integrals over $\\hat{D}$.  The $L^2$ projection of $u\\in L^2\\LRp{D^k}$ over a curvilinear element $D^k$ is defined through \n\\begin{equation}\n\\LRp{\\Pi^k_N u,v}_{D^k} = \\LRp{u,v}_{D^k}, \\qquad \\forall v\\in P^N\\LRp{\\hat{D}}.\n\\label{eq:l2curv}\n\\end{equation}\nMapping integrals to the reference element $\\hat{D}$ yields\n\\begin{equation}\n\\LRp{\\Pi^k_N u,v J^k}_{\\hat{D}} = \\LRp{u,vJ^k}_{\\hat{D}}, \\qquad \\forall v\\in P^N\\LRp{\\hat{D}}.\n\\label{eq:l2curvmap}\n\\end{equation}\nFor affine elements, $J^k$ is constant and can be cancelled.  Thus, the $L^2$ projection over affine elements is equivalent to simply taking the $L^2$ projection of a function over the reference element.  However, for curved elements, $J$ acts as a spatially varying weight within the $L^2$ inner product.  \n\nDiscretizing (\\ref{eq:l2curvmap}) requires a weighted mass matrix.  We define a curved mass matrix over an element $D^k$ by weighting the discrete $L^2$ norm with values of $J$ at quadrature points\n\\begin{equation}\n\\bm{M}^k = \\bm{V}_q^T \\bm{W}\\diag{\\bm{J}^k}\\bm{V}_q,\n\\label{eq:curvedmass}\n\\end{equation}\nwhere $\\bm{J}^k$ is a vector containing evaluation of the physical Jacobian factors for $D^k$ at volume quadrature points.\nThen, curvilinear $L^2$ projection and lift matrices can be defined in a manner analogous to (\\ref{eq:projlift})\n\\begin{equation}\n\\bm{P}^k_q = \\LRp{\\bm{M}^k}^{-1}\\bm{V}_q^T\\bm{W}\\diag{\\bm{J}^k}, \\qquad \\bm{L}^k_q = \\LRp{\\bm{M}^k}^{-1}\\bm{V}_f^T\\bm{W}_f\\diag{\\bm{J}^k_f}.\n\\label{eq:projliftcurved}\n\\end{equation}\nThese matrices are distinct from element to element, reflecting the fact that problem (\\ref{eq:l2curvmap}) is distinct from element to element.  \n\n\\subsection{A discretely entropy stable DG formulation on curved meshes}\n\nGiven the matrices in Section~\\ref{sec:curv}, we can now define a local entropy stable DG formulation on an element $D^k$.  Here, we seek an approximation solution $\\bm{u}_N(\\bm{x},t)$ to (\\ref{eq:nonlineqs}), which is represented using vector-valued coefficients $\\bm{u}_h(t)$ such that\n\\[\n\\bm{u}_N(\\bm{x},t) = \\sum_{j=1}^{N_p} \\LRp{\\bm{u}_h(t)}_j \\phi_j(\\bm{x}), \\qquad \\LRp{\\bm{u}_h(t)}_j \\in \\mathbb{R}^n.\n\\]\nSince the coefficients are vector valued, we assume that all matrices act component-wise on $\\bm{u}_h$ in the Kronecker product sense.  \n\nWe first define the numerical fluxes $\\bm{f}_{i,S}\\LRp{\\bm{u}_L,\\bm{u}_R}$ as the bivariate function of ``left'' and ``right'' conservative variable states $\\bm{u}_L, \\bm{u}_R$.  % Such a numerical flux is referred to as entropy conservative (or entropy stable) if it satisfies the following conditions:\n\\begin{definition}\nThe numerical flux $\\bm{f}_{i,S}\\LRp{\\bm{u}_L,\\bm{u}_R}$ is entropy conservative (or entropy stable) if it satisfies the following conditions:\n\\begin{enumerate}\n\\item $\\bm{f}_{i,S}\\LRp{\\bm{u}_L,\\bm{u}_R} = \\bm{f}_{i,S}\\LRp{\\bm{u}_R,\\bm{u}_L}$ (symmetry).\n\\item $\\bm{f}_{i,S}\\LRp{\\bm{u},\\bm{u}} = \\bm{f}_i\\LRp{\\bm{u}}$ (consistency).\n\\item $\\bm{f}_{i,S}$ is referred to as entropy conservative if it satisfies conditions 1, 2, and  \n\\[\n  \\LRp{\\bm{v}_L-\\bm{v}_R}^T\\bm{f}_{i,S}\\LRp{\\bm{u}_L,\\bm{u}_R} = \\psi_i\\LRp{\\bm{u}_L}-\\psi_i\\LRp{\\bm{u}_R}.\n\\]\n%\\item $\\bm{f}_{i,S}$ is referred to as entropy stable if it satisfies conditions 1, 2, and  \n%\\[\n%\\LRp{\\bm{v}_L-\\bm{v}_R}^T\\bm{f}_{i,S}\\LRp{\\bm{u}_L,\\bm{u}_R} \\leq \\psi_i\\LRp{\\bm{u}_L}-\\psi_i\\LRp{\\bm{u}_R}.\n%\\]\n\\end{enumerate}\n\\label{def:entropyflux}\n\\end{definition}\n\nWe now introduce the $L^2$ projection of the entropy variables $\\bm{v}_h$ and the entropy-projected conservative variables $\\tilde{\\bm{u}}$ \n\\begin{align}\n\\bm{u}_q = \\bm{V}_q \\bm{u}_h, \\qquad \\bm{v}_h = \\bm{P}^k_q \\bm{v}\\LRp{\\bm{u}_q}, \\qquad \n\\tilde{\\bm{v}} = \\LRs{\\begin{array}{c}\n\\tilde{\\bm{v}}_q\\\\\n\\tilde{\\bm{v}}_f\n\\end{array}} = \\LRs{\\begin{array}{c}\n\\bm{V}_q\\\\\n\\bm{V}_f\n\\end{array}}\\bm{v}_h, \\qquad \\tilde{\\bm{u}} = \\LRs{\\begin{array}{c}\n\\tilde{\\bm{u}}_q\\\\\n\\tilde{\\bm{u}}_f\n\\end{array}} = \\bm{u}\\LRp{\\tilde{\\bm{v}}}.\n\\label{eq:evars1}\n\\end{align}\nIn (\\ref{eq:evars1}), the entropy-projected conservative variables $\\tilde{\\bm{u}}$ denote the evaluation of the conservative variables in terms of the projected entropy variables at volume and face quadrature points.  We note that, under an appropriate choice of quadrature on quadrilaterals and hexahedra, this approach is equivalent to the approach taken in \\cite{parsani2016entropy}, where the entropy variables are evaluated at Gauss nodes, then interpolated to a different set of nodes and used to compute the nonlinear fluxes.  \n\nWe now introduce a semi-discrete DG formulation for $\\bm{u}_h$\n\\begin{align}\n&\\td{\\bm{u}_h}{t} + \\LRs{\\begin{array}{cc}\\bm{P}^k_q & \\bm{L}^k_q\\end{array}}\n  \\sum_{j=1}^d \\LRp{2\\bm{D}^j_k \\circ \\bm{F}_{j,S}}\\bm{1} + \\sum_{j=1}^d \\bm{L}^k_q \\diag{\\bm{n}_j}\\LRp{\\bm{f}_j^* - \\bm{f}_j(\\tilde{\\bm{u}}_f)} = 0,\\label{eq:dgform1}\\\\\n  &\\LRp{\\bm{F}_{j,S}}_{mn} = \\bm{f}_{j,S}\\LRp{\\LRp{\\tilde{\\bm{u}}}_m,\\LRp{\\tilde{\\bm{u}}}_n}, \\qquad 1 \\leq m,n \\leq N_q + N^f_q,\\nonumber\\\\\n  &\\bm{f}_j^* = \\bm{f}_{j,S}(\\tilde{\\bm{u}}_f^+,\\tilde{\\bm{u}}_f) \\text{ on interior faces},\\nonumber\n\\end{align}\nwhere $\\tilde{\\bm{u}}^+$ denotes the values of the entropy-projected conservative variables on the neighboring element across each face of $D^k$, and $\\bm{f}_j^*$ on the boundary denotes the $j$th component of some numerical flux through which boundary conditions are imposed.  Note that the face/surface Jacobian factors $\\bm{J}^k_f$ are incorporated into the definition of $\\bm{L}^k_q$.  \n\nDefine the diagonal boundary quadrature matrix $\\bm{W}_{\\partial \\Omega}$ such that\n\\[\n\\LRp{\\bm{W}_{\\partial \\Omega} }_{ii} = \\begin{cases}\n  \\bm{W}_f, & \\text{if $\\hat{\\bm{x}}^f_i$ is on the $\\partial \\Omega$}\\\\\n0, & \\text{otherwise}. \n\\end{cases}\n\\]\nWe have the following semi-discrete statement of entropy conservation:\n\\begin{theorem}\n  Let $\\bm{f}_{i,S}$ be an entropy conservative flux from Definition~\\ref{def:entropyflux} and assume that $\\bm{Q}^j_k\\bm{1} = 0$ for $j = 1,\\ldots,d$ over each element $D^k$.  Then, (\\ref{eq:dgform1}) is entropy conservative in the sense that\n\\[\n  \\sum_k \\bm{1}^T\\diag{\\bm{J}^k}\\bm{W}\\td{U(\\bm{u}_q)}{t} = \\sum_k \\sum_{j=1}^d \\bm{1}^T\\diag{\\bm{n}_j\\circ\\bm{J}^k_f}\\bm{W}_{\\partial \\Omega} \\LRp{\\psi_j\\LRp{\\tilde{\\bm{u}}_f}-\\tilde{\\bm{v}}_f^T\\bm{f}_j^*}.\n\\]\n\\label{thm:stab1}\n\\end{theorem}\n\\begin{proof}\nUnder the assumption that $\\bm{Q}^j_k\\bm{1} = 0$ for $i = 1,\\ldots,d$ over each element and (\\ref{eq:sbpk}), the proof of entropy conservation is identical to that of \\cite{chan2017discretely}.  \n%\\note{Expand out!  Do spatial term only, punt for time term.  }\n%To prove entropy conservation, we multiply on both sides by $\\bm{M}_k$ \n%\\begin{align}\n%\\bm{M}_k\\td{\\bm{u}_h}{t} + \\LRs{\\begin{array}{c}\\bm{V}_q \\\\ \\bm{V}_f\\end{array}}^T\n%\\sum_{j=1}^d \\LRp{\\bm{Q}^j_k \\circ \\bm{F}_{j,S}}\\bm{1} + \\sum_{j=1}^d \\bm{V}_f^T \\bm{W}_f\\diag{\\bm{n}_j\\bm{J}^k_f}\\LRp{\\bm{f}_j^* - \\bm{f}_j(\\tilde{\\bm{u}}_f)} = 0.\n%\\end{align}\n%We now test on both sides by $\\bm{v}_h^T$ and note that $\\bm{v}_h^T\\bm{M} = \\bm{v}(\\bm{u}_q)^T \\bm{W} \\bm{J}^k \\bm{V}_q$.  For the time term, we assuming continuity in time and use the chain rule\n%\\[\n%\\bm{v}(\\bm{u}_q)^T \\bm{W} \\bm{J}^k \\td{\\bm{V}_q\\bm{u}_h}{t} = \\bm{1}^T \\bm{W} \\bm{J}^k \\bm{v}(\\bm{u}_q)^T\\td{\\bm{u}_q}{t} = \n%\\bm{1}^T \\bm{W} \\bm{J}^k \\td{U(\\bm{u}_q)}{t},\n%\\]\n%where we have used that $\\bm{W}$ is diagonal, that $\\bm{v}(\\bm{u}) = \\pd{U(\\bm{u})}{\\bm{u}}$, and the chain rule in time.  The right hand side terms\n%\\[\n%\\sum_{j=1}^d \\LRp{\\bm{Q}^j_k \\circ \\bm{F}_{j,S}}\\bm{1} + \\sum_{j=1}^d \\bm{V}_f^T \\bm{W}_f\\diag{\\bm{n}_j\\bm{J}^k_f}\\LRp{\\bm{f}_j^* - \\bm{f}_j(\\tilde{\\bm{u}}_f)} = 0.\n%\\]\n%\\note{Finish proof}\n\\end{proof}\nAn entropy stable scheme can be constructed by adding an entropy-dissipating penalty term, such as a Lax-Friedrichs penalization or the matrix dissipation terms introduced in \\cite{chandrashekar2013kinetic, winters2017uniquely}.  For example, Lax-Friedrichs penalization can be incorporated by replacing the flux term with\n\\[\n\\bm{L}^k_q \\diag{\\bm{n}_j} \\LRp{\\bm{f}_j^*-\\bm{f}(\\bm{u})} \\Longrightarrow \\bm{L}^k_q\\LRp{\\diag{\\bm{n}_j} \\LRp{\\bm{f}_j^*- \\bm{f}(\\bm{u})} - \\frac{\\lambda}{2}\\jump{\\tilde{\\bm{u}}_f}},\n\\]\nwhere $\\lambda$ is an estimate of the maximum eigenvalue of $\\pd{\\bm{f}(\\bm{u})}{\\bm{u}}$ \\cite{chen2017entropy, chan2017discretely}.\n\n%\\note{maybe add more here?}\n\n\\section{Discretely stable and low storage DG methods on curved meshes}\n\\label{sec:3}\nA disadvantage of the formulation (\\ref{eq:dgform1}) is high storage costs, especially at high orders of approximation.  While the matrices $\\bm{Q}^i_k$ can be applied to a vector without needing to explicitly store the matrix, the projection and lifting matrices (\\ref{eq:projliftcurved}) differ from element to element, necessitating either explicit pre-computation and storage or the assembly and inversion of a weighted mass matrix for each right hand side evaluation.  The latter option is computationally expensive, while the former option increases storage costs.  This increase in storage can result in suboptimal performance on modern computational architectures \\cite{chan2017weight}, due to the increasing cost of memory operations and data movement compared to arithmetic operations.  \n\nIn this section, we present a discretely entropy stable scheme which avoids this high storage cost through the use of a low-storage weight-adjusted approximation to the inverse of a weighted mass matrix.  To ensure a discrete entropy conservation or a discrete entropy inequality, we also modify the formulation (\\ref{eq:dgform1}) to take into account the use of a weight-adjusted mass matrix.\n\n\\subsection{A weight-adjusted approximation to the curvilinear mass matrix}\n\n%Recall that, by mapping back to the reference element $\\hat{D}$, the $L^2$ projection $\\Pi_N^k$ on a curved element $D^k$ is defined as\n%\\begin{equation}\n%\\LRp{J \\Pi_N^k u,v}_{\\hat{D}} = \\LRp{uJ,v}_{\\hat{D}}, \\qquad \\forall v\\in P^N\\LRp{\\hat{D}}.\n%\\label{eq:l2projcurv}\n%\\end{equation}\nThe presence of the weighted $L^2$ inner product $\\LRp{J^k \\Pi_N^k u,v}_{\\hat{D}}$ in (\\ref{eq:l2curvmap}) results in the presence of a weighted mass matrix.  Because the weight $J^k$ varies spatially over each element, the inverse of a weighted mass matrix is no longer a scaling of the inverse reference mass matrix.  The motivation for the weight-adjusted mass matrix is to replace the inversion of weighted mass matrices over each element with the application of inverse reference mass matrices and quadrature-based operations involving the spatially varying weights $J^k$ \\cite{chan2016weight1, chan2016weight2}.  \n\nTo define a weight-adjusted approximation to the curvilinear $L^2$ inner product, we first define the operator $T_{w}^{-1}: L^2\\rightarrow P^N$ as follows\n\\begin{equation}\n  \\LRp{wT_{w}^{-1} u,v}_{\\hat{D}} = \\LRp{ u,v}_{\\hat{D}}, \\qquad \\forall v\\in P^N\\LRp{\\hat{D}}.\n\\label{eq:wadgTw}\n\\end{equation}\nRoughly speaking, $T_{w} u$ approximates $u/w$.  Thus, taking $w = 1/J^k$ provides an approximation of the curvilinear $L^2$ inner product\n\\begin{equation*}\n\\LRp{J^k u,v}_{\\hat{D}} \\approx \\LRp{T_{1/J^k}^{-1} u,v}_{\\hat{D}}.\n\\end{equation*}\n\nComputing $T_{1/J^k}^{-1}u$ requires solving (\\ref{eq:wadgTw}).  Let $u \\in P^N\\LRp{\\hat{D}}$, and let $\\bm{u}_J$ denote coefficients for the polynomial $T_{1/J^k}^{-1}u$.  This results in the following matrix system\n\\[\n\\bm{M}_{1/J^k}\\bm{u}_{J} = \\bm{M}\\bm{u}, \\qquad {\\bm{M}_{1/J^k}} = \\bm{V}_q^T \\bm{W}\\diag{1/\\bm{J}^k}\\bm{V}_q,%\\LRp{\\frac{1}{J^k}\\phi_i,\\phi_j}_{\\hat{D}},\n\\]\nwhich implies that, when restricted to polynomials, the matrix form of $T_{1/J^k}^{-1}$ is $\\bm{M}_{1/J^k}^{-1}\\bm{M}$.  Then, the weight-adjusted mass matrix is the Gram matrix with respect to the weight-adjusted inner product $\\LRp{T_{1/J^k}^{-1} u,v}_{\\hat{D}}$, such that\n\\[\n\\bm{M}^k \\approx \\bm{M}\\bm{M}_{1/J^k}^{-1}\\bm{M}, \\qquad \\LRp{\\bm{M}^k}^{-1} \\approx \\bm{M}^{-1}\\bm{M}_{1/J^k}\\bm{M}^{-1}.\n\\]\nThe inverse of the weight-adjusted mass matrix can be applied in a matrix-free fashion by using quadrature to form $\\bm{M}_{1/J^k} $.  This requires storage of the inverse reference mass matrix and the values of $\\bm{J}^k$ at quadrature points.  Assuming that the number of quadrature points scales as $O(N^d)$ in $d$ dimensions, this yields a storage cost of $O(N^d)$ per-element compared to an $O(N^{2d})$ per element storage cost required for the storage of inverse weighted mass matrices $\\LRp{\\bm{M}^k}^{-1}$.  This application of the weight-adjusted mass matrix is typically applied using the $L^2$ projection matrix $\\bm{P}_q$ as follows\n\\[\n\\bm{M}^{-1}\\bm{M}_{1/J^k}\\bm{M}^{-1} = \\bm{P}_q \\diag{1/\\bm{J}^k} \\bm{V}_q \\bm{M}^{-1}.\n\\]\nWhen evaluating the right hand side of a semi-discrete formulation such as (\\ref{eq:dgform1}), the inverse mass matrix is typically merged into operations on the right hand side, such that the main work in applying the weight-adjusted mass matrix consists of applying the interpolation matrix $\\bm{V}_q$, scaling by pointwise values of $1/\\bm{J}^k$ at quadrature points, and multiplying by the $L^2$ projection matrix $\\bm{P}_q$.\n\n\n\\subsection{A discretely entropy stable low storage DG formulation on curved meshes}\n\nGiven the weight-adjusted inverse mass matrix, we can also define a weight-adjusted version of the $L^2$ projection over a curved element $D^k$.  We refer to this operator as $\\tilde{\\Pi}^k_N: L^2\\rightarrow P^N$, which satisfies\n\\[\n\\LRp{T^{-1}_{1/J^k}\\tilde{\\Pi}^k_N u,v}_{\\hat{D}} = \\LRp{uJ^k,v}_{\\hat{D}}, \\qquad \\forall v\\in P^N\\LRp{\\hat{D}}.\n\\]\nIt was shown in \\cite{chan2016weight2} that $\\tilde{\\Pi}^k_N $ is given explicitly by\n\\begin{equation}\n\\tilde{\\Pi}^k_N u = \\Pi_N\\LRp{\\frac{1}{J^k}\\Pi_N\\LRp{uJ^k}},\n\\label{eq:wadgprojop}\n\\end{equation}\nwhere $\\Pi_N$ is the $L^2$ projection operator on the reference element $\\hat{D}$.  We can discretize $\\tilde{\\Pi}^k_N$ using quadrature to yield a weight-adjusted projection matrix $\\tilde{\\bm{P}}^k_q$ \n\\begin{align}\n\\tilde{\\bm{P}}^k_q &= \\bm{M}^{-1}\\bm{M}_{1/\\bm{J}^k}\\bm{M}^{-1}\\bm{V}_q^T\\bm{W}\\diag{\\bm{J}^k} = \\bm{M}^{-1}\\bm{V}_q^T\\bm{W}\\diag{1/\\bm{J}^k} \\bm{V}_q\\bm{P}_q\\diag{\\bm{J}^k} \\nonumber\\\\\n&= \\bm{P}_q \\diag{{1}/{\\bm{J}^k}} \\bm{V}_q\\bm{P}_q \\diag{\\bm{J}^k}.\n\\label{eq:wadgproj}\n\\end{align}\nWe can similarly define a weight-adjusted lifting matrix $\\tilde{\\bm{L}}_q$ by replacing the weighted mass matrix in (\\ref{eq:projliftcurved}) with the weight-adjusted mass matrix\n\\begin{align}\n\\tilde{\\bm{L}}^k_q &= \\bm{M}^{-1}\\bm{M}_{1/\\bm{J}^k}\\bm{M}^{-1}\\bm{V}_f^T\\bm{W}_f\\diag{\\bm{J}^k_f} = \\bm{M}^{-1}\\bm{V}_q^T\\bm{W}\\diag{1/\\bm{J}^k} \\bm{V}_q\\bm{L}_q\\diag{\\bm{J}^k_f} \\nonumber\\\\\n&= \\bm{P}_q \\diag{{1}/{\\bm{J}^k}} \\bm{V}_q\\bm{L}_q \\diag{\\bm{J}^k_f}.\n\\label{eq:wadglift}\n\\end{align}\n\nWe can now introduce the weight-adjusted projection of the entropy variables $\\bm{v}_h$ and the corresponding entropy-projected conservative variables $\\tilde{\\bm{u}}$ \n\\begin{align}\n\\bm{u}_q = \\bm{V}_q \\bm{u}_h, \\qquad \\bm{v}_h = \\tilde{\\bm{P}}^k_q \\bm{v}\\LRp{\\bm{u}_q}, \\qquad \n\\tilde{\\bm{v}} = \\LRs{\\begin{array}{c}\n\\bm{V}_q\\\\\n\\bm{V}_f\n\\end{array}}\\bm{v}_h, \\qquad \\tilde{\\bm{u}} =  \\LRs{\\begin{array}{c}\n\\tilde{\\bm{u}}_q\\\\\n\\tilde{\\bm{u}}_f\n\\end{array}} = \\bm{u}\\LRp{\\tilde{\\bm{v}}}.\n\\label{eq:evars2}\n\\end{align}\nA semi-discrete DG formulation for $\\bm{u}_h$ can be constructed using the variables defined in (\\ref{eq:evars2})\n\\begin{align}\n&\\td{\\bm{u}_h}{t} + \\LRs{\\begin{array}{cc}\\tilde{\\bm{P}}^k_q & \\tilde{\\bm{L}}^k_q\\end{array}}\n  \\sum_{j=1}^d \\LRp{2\\bm{D}^j_k \\circ \\bm{F}_{j,S}}\\bm{1} + \\sum_{j=1}^d \\tilde{\\bm{L}}^k_q \\diag{\\bm{n}_j}\\LRp{\\bm{f}_j^* - \\bm{f}_j(\\tilde{\\bm{u}}_f)} = 0,\\label{eq:dgform2}\\\\\n  &\\LRp{\\bm{F}_{j,S}}_{mn} = \\bm{f}_{j,S}\\LRp{\\LRp{\\tilde{\\bm{u}}}_m,\\LRp{\\tilde{\\bm{u}}}_n}, \\qquad 1 \\leq m,n \\leq N_q + N^f_q,\\nonumber\\\\\n  &\\bm{f}_j^* = \\bm{f}_{j,S}(\\tilde{\\bm{u}}_f^+,\\tilde{\\bm{u}}_f) \\text{ on interior faces}.\\nonumber\n\\end{align}\nSince the  weight-adjusted mass matrix inverse is low-storage, and since the matrices $\\bm{D}^j_k$ in (\\ref{eq:dik}) can be assembled from reference matrices $\\bm{D}^i_N$ and the values of geometric terms at quadrature points, the overall scheme requires only $O(N^d)$ storage per element.  We can additionally show that formulation (\\ref{eq:dgform2}) is entropy conservative in the same sense as Theorem~\\ref{thm:stab1}: \n\\begin{theorem}\n  Let $\\bm{f}_{i,S}$ be an entropy conservative flux from Definition~\\ref{def:entropyflux} and assume that $\\bm{Q}^j_k\\bm{1} = 0$ for $j = 1,\\ldots,d$ over each element $D^k$.  Then, (\\ref{eq:dgform2}) is entropy conservative in the sense that\n\\[\n  \\sum_k \\bm{1}^T\\diag{\\bm{J}^k}\\bm{W}\\td{U(\\bm{u}_q)}{t} = \\sum_k \\sum_{j=1}^d \\bm{1}^T\\diag{\\bm{n}_j\\circ\\bm{J}^k_f}\\bm{W}_{\\partial \\Omega} \\LRp{\\psi_j\\LRp{\\tilde{\\bm{u}}_f}-\\tilde{\\bm{v}}_f^T\\bm{f}_j^*}.\n\\]\n\\label{thm:stab2}\n\\end{theorem}\n\\begin{proof}\nThe proof is similar to that of Theorem~\\ref{thm:stab1}.  \nFirst, recall from the definitions of the weight-adjusted projection matrix~(\\ref{eq:wadgproj}) and weight-adjusted lift matrix~(\\ref{eq:wadglift}) that\n\\begin{align}\n\\tilde{\\bm{P}}^k_q &= \\bm{M}^{-1}\\bm{M}_{1/J^k} \\bm{M}^{-1} \\bm{V}_q^T \\bm{W}  \\diag{\\bm{J}^k  }\\label{eq:projidentity},\\\\\n\\tilde{\\bm{L}}^k_q &= \\bm{M}^{-1}\\bm{M}_{1/J^k} \\bm{M}^{-1} \\bm{V}_f^T \\bm{W}_f\\diag{\\bm{J}^k_f}\\label{eq:liftidentity}.\n\\end{align}\nThen, multiplying by the weight-adjusted mass matrix $\\bm{M}\\bm{M}_{1/J^k}^{-1}\\bm{M}$ on both sides of (\\ref{eq:dgform2}) and using (\\ref{eq:projidentity}), (\\ref{eq:liftidentity}) yields the weak form of (\\ref{eq:dgform2})\n\\begin{equation}\n\\bm{M}\\bm{M}_{1/J^k}^{-1}\\bm{M}\\td{\\bm{u}_h}{t} + \\LRs{\\begin{array}{cc}{\\bm{V}}_q^T & {\\bm{V}}_f^T\\end{array}}\n\\sum_{j=1}^d \\LRp{2\\bm{Q}^j_k \\circ \\bm{F}_{j,S}}\\bm{1} + \\sum_{j=1}^d {\\bm{V}}_f^T\\bm{W}_f \\diag{\\bm{n}_j}\\LRp{\\bm{f}_j^* - \\bm{f}_j(\\tilde{\\bm{u}}_f)} = 0.\n\\label{eq:dgform2weak}\n\\end{equation}\nTesting with the weight-adjusted projection of the entropy variables $\\bm{v}_h = \\tilde{\\bm{P}}^k_q \\bm{v}\\LRp{\\bm{u}_q}$ and using (\\ref{eq:projidentity}) then yields for the time term\n\\begin{align*}\n\\LRp{\\tilde{\\bm{P}}^k_q \\bm{v}\\LRp{\\bm{u}_q}}^T\\bm{M}\\bm{M}_{1/J^k}^{-1}\\bm{M}\\td{\\bm{u}_h}{t} &= \\bm{v}\\LRp{\\bm{u}_q}^T\\bm{W}\\diag{\\bm{J}^k}\\bm{V}_q \\bm{M}^{-1}\\bm{M}_{1/J^k} \\bm{M}^{-1} \\bm{M}\\bm{M}_{1/J^k}^{-1}\\bm{M}\\td{\\bm{u}_h}{t}\\\\\n                                                                                               &= \\bm{v}\\LRp{\\bm{u}_q}^T\\bm{W}\\diag{\\bm{J}^k} \\td{\\bm{V}_q\\bm{u}_h}{t} = \\bm{1}^T\\bm{W}\\diag{\\bm{J}^k} \\left({\\rm diag}\\LRp{\\bm{v}\\LRp{\\bm{u}_q}}\\td{\\bm{u}_q}{t}\\right) \\\\\n                                                                                               &= \\bm{1}^T\\bm{W}\\diag{\\bm{J}^k} \\td{U(\\bm{u}_q)}{t}.\n\\end{align*}\nThe remainder of the proof is identical to that of Theorem~\\ref{thm:stab1} and \\cite{chan2017discretely}.\n\\end{proof}\n\n\\subsection{Analysis of weight-adjusted projection} \n\nThe construction of the discretely entropy stable weight-adjusted DG formulation (\\ref{eq:dgform2}) replaces the $L^2$ projection operator $\\Pi_N^k$ with the weight-adjusted projection operator $\\tilde{\\Pi}^k_N$.\nWhile this preserves entropy stability, it is unclear whether $\\tilde{\\Pi}^k_N$ is high order accurate.  In this section, we prove that the weight-adjusted projection is high order accurate due to the fact that, for a fixed geometric mapping and sufficiently regular $u$, the difference between the $L^2$ and weight-adjusted projection is $\\nor{\\Pi_N^k u - \\tilde{\\Pi}^k_N  u}_{L^2\\LRp{\\Omega}} = O(h^{N+2})$.  Because the approximation error for the $L^2$ projection is $O(h^{N+1})$ for sufficiently regular $u$, the difference between the $L^2$ and weight-adjusted projection converges faster than the $L^2$ best approximation error.  Consequentially, solutions computed using the $L^2$ and weight-adjusted projection are typically indistinguishable for a fixed geometric mapping \\cite{chan2018multi}.  \n\nWe first note that $\\tilde{\\Pi}^k_N  = \\Pi_N\\LRp{\\frac{1}{J^k}\\Pi_N\\LRp{uJ^k}}$ is self-adjoint with respect to the $J$-weighted $L^2$ inner product\n\\begin{equation}\n  \\LRp{J^k \\tilde{\\Pi}^k_N  u, v}_{\\hat{D}} = \\LRp{\\Pi_N\\LRp{\\frac{1}{J^k}\\Pi_N\\LRp{uJ^k}}, vJ^k}_{\\hat{D}} = \\LRp{uJ^k, \\Pi_N\\LRp{\\frac{1}{J^k}\\Pi_N\\LRp{vJ^k}}}_{\\hat{D}} =  \\LRp{uJ^k, \\tilde{\\Pi}^k_N  v}_{\\hat{D}}.\n\\label{eq:PNsym}\n\\end{equation}\nFurthermore, using that the operator $T_{1/J^k}^{-1}$ is self-adjoint for $v \\in P^N\\LRp{\\hat{D}}$ with respect to the $L^2$ inner product \\cite{chan2016weight1}, we find that a projection-like property holds for the weight-adjusted $L^2$ inner product\n\\begin{equation}\n  \\LRp{T_{1/J^k}^{-1} \\tilde{\\Pi}^k_N  u,v}_{\\hat{D}} = \\LRp{ \\frac{1}{J^k}\\Pi_N(uJ^k),T_{1/J^k}^{-1}v}_{\\hat{D}} = \\LRp{\\Pi_N(u J^k),v}_{\\hat{D}} = \\LRp{u J^k,v}_{\\hat{D}}, \\qquad \\forall v\\in P^N{\\hat{D}}.\n\\label{eq:PNproj}\n\\end{equation}\n\nTo prove $\\nor{\\Pi_N^k u - \\tilde{\\Pi}^k_N  u}_{L^2\\LRp{\\hat{D}}} = O(h^{N+2})$, we use a generalized inverse inequality and results from \\cite{chan2016weight1,chan2016weight2}.  We first introduce a modification of Theorem 3.1 in \\cite{warburton2013low, chan2016weight1}\n\\begin{theorem}%[Theorem 3.1 in \\cite{warburton2013low, chan2016weight1}]\nLet $D^k$ be a quasi-regular element with representative size $h = \\diam\\LRp{D^k}$, and let $\\hat{D}$ be the reference element.  For $N \\geq 0$, $w\\in W^{N+1,\\infty}\\LRp{D^k}$, and $u\\in W^{r,2}\\LRp{D^k}$, \n\\begin{align*}\n%\\nor{u - \\frac{1}{w} \\Pi_N\\LRp{{u}{w}}}_{L^2\\LRp{D^k}} &\\leq C h^{N+1}\\nor{\\frac{1}{\\sqrt{J^k}}}_{L^{\\infty}\\LRp{D^k}}\\nor{\\frac{\\sqrt{J^k}}{w}}_{L^{\\infty}\\LRp{D^k}} \\nor{w}_{W^{N+1,\\infty}\\LRp{D^k}}  \\nor{u}_{W^{N+1,2}\\LRp{D^k}},\\\\\n\\nor{u - \\frac{1}{w} \\Pi_N\\LRp{{u}{w}}}_{L^2\\LRp{\\hat{D}}} &\\leq C h^{\\min\\LRp{r,N+1}} \\nor{\\frac{1}{\\sqrt{J^k}}}_{L^{\\infty}\\LRp{D^k}}\\nor{\\frac{1}{w}}_{L^{\\infty}\\LRp{D^k}} \\nor{w}_{W^{N+1,\\infty}\\LRp{D^k}} \\nor{u}_{W^{r,2}\\LRp{D^k}}.\n\\end{align*}\n\\label{thm:wproj}\n\\end{theorem}\nThe proof is a straightforward modification of the proofs presented in \\cite{warburton2013low, chan2016weight1} accounting for reduced regularity of $u$ when $r < (N+1)$.  The next result we need is a generalized inverse inequality.  \n\\begin{lemma}\n\\label{lemma:sobolev}\nLet $v \\in P^N\\LRp{\\hat{D}}$, and let $h = \\diam\\LRp{D^k}$.  Then,\n\\[\n  \\nor{v}_{W^{N+1,2}\\LRp{D^k}} \\leq C_{N}  h^{-N} \\nor{\\sqrt{J^k}}_{L^{\\infty}} \\nor{\\frac{1}{\\sqrt{J^k}}}_{L^{\\infty}} \\nor{\\frac{1}{J^k}\\bm{G}^k}_{W^{N,\\infty}\\LRp{D^k}} \\nor{v}_{L^2\\LRp{D^k}}.\n\\]\nwhere $C_{N}$ depends on $N$, but is independent of $h$.\n\\end{lemma}\n\\begin{proof}\n  By applying Fa\\`{a} di Bruno's formula, we can express the degree $(N+1)$ Sobolev norm of $v$ on $D^k$ in terms of derivatives of $v$ on the reference element $\\hat{D}$.  Noting that all $(N+1)$ derivatives of $v$ disappear for $v\\in P^N\\LRp{\\hat{D}}$ allows us to bound the degree $(N+1)$ Sobolev norm of $v$ by its degree $N$ Sobolev norm\n\\[\n  \\nor{v}_{W^{N+1,2}\\LRp{D^k}} \\leq C_N \\nor{\\frac{1}{J^k}\\bm{G}^k}_{W^{N,\\infty}\\LRp{D^k}} \\nor{v}_{W^{N,2}\\LRp{D^k}},\n\\]\nwhere $\\bm{G}^k$ is the matrix of scaled geometric terms for $D^k$.  Then, a scaling argument \\cite{ciarlet1978finite, brenner2007mathematical} yields\n\\begin{align}\n\\nor{v}_{W^{N,2}\\LRp{D^k}}  \\leq C_1 h^{-N} \\nor{\\sqrt{J^k}}_{L^{\\infty}} \\nor{v}_{W^{N,2}\\LRp{\\hat{D}}}.  \n\\end{align}\nThe quantity $\\nor{v}_{W^{N,2}\\LRp{\\hat{D}}}$ can be bounded by noting that $v\\in P^N\\LRp{\\hat{D}}$.  Since $P^N\\LRp{\\hat{D}}$ is finite-dimensional, the Sobolev norm can be bounded from above by the $L^2$ norm of $\\hat{D}$ with a constant $C_{2}$ depending on $N, d$.  By another scaling argument, we have \n\\begin{align}\n\\nor{v}_{W^{N+1,2}\\LRp{\\hat{D}}} \\leq C_{2} \\nor{v}_{L^2\\LRp{\\hat{D}}} \\leq \\nor{\\frac{1}{\\sqrt{J^k}}}_{L^{\\infty}} C_{2}  \\nor{v}_{L^2\\LRp{D^k}}.\n\\end{align}\n%where $\\bm{M}$ is the $L^2$ mass matrix over $D^k$ and $\\bm{K}_N$ is the Gram matrix corresponding to the Sobolev inner product on the reference element  $W^{N+1,2}\\LRp{\\hat{D}}$.  The constant $C_N$ depends on the largest generalized eigenvalue of \\ref{eq:eig}, which in turn depends on the order $N$ and dimension $d$.  \n\\end{proof}\n\nWe can now prove that $\\tilde{\\Pi}^k_N u$ is superconvergent to the curvilinear $L^2$ projection $\\Pi_N^k u$: \n\\begin{theorem}\nLet $u \\in W^{r,2}\\LRp{D^k}$.  The difference between the $L^2$ projection $\\Pi^k_Nu$ and the weight-adjusted projection $\\tilde{\\Pi}^k_N u$ is\n\\[\n\\nor{\\Pi_N^k u - \\tilde{\\Pi}^k_N  u}_{L^2\\LRp{D^k}} \\leq C_N C_J h^{\\min\\LRp{r,N+1}+1}\\nor{u}_{W^{N+1,2}\\LRp{D^k}},\n\\]\nwhere $C_N$ is a mesh-independent constant which depends on $N, d$ and $C_J$ is\n\\[\n  C_J = \\nor{J^k}_{L^{\\infty}\\LRp{D^k}}^{1.5}  \\nor{\\frac{1}{J^k}}_{L^{\\infty}\\LRp{D^k}}^{1.5} \\nor{\\frac{1}{J^k}}_{W^{N+1,\\infty}\\LRp{D^k}}\\nor{J^k}_{W^{N+1,\\infty}\\LRp{D^k}}\\nor{\\frac{1}{J^k}\\bm{G}^k}_{W^{N,\\infty}\\LRp{D^k}}.\n\\]\n\\label{thm:superconverge}\n\\end{theorem}\n\\begin{proof}\nWe can rewrite the norm of the difference between the weight-adjusted and $L^2$ projections\n\\[\n\\nor{\\Pi_N^k  u - \\tilde{\\Pi}^k_N  u}_{L^2\\LRp{D^k}}^2 = \\LRp{\\Pi_N^k  u - \\tilde{\\Pi}^k_N  u,vJ^k}_{\\hat{D}}, \\qquad v = \\Pi_N^k  u - \\tilde{\\Pi}^k_N  u.\n\\]\nBecause $v \\in P^N\\LRp{\\hat{D}}$, we can also evaluate the squared error as\n\\begin{align*}\n\\nor{\\Pi_N^k  u - \\tilde{\\Pi}^k_N  u}_{L^2\\LRp{D^k}}^2 &= \\LRb{\\LRp{\\Pi_N^k u,vJ^k}_{\\hat{D}} - \\LRp{\\tilde{\\Pi}^k_N  u,vJ^k}_{\\hat{D}}} = \\LRb{\\LRp{u,vJ^k}_{\\hat{D}} - \\LRp{\\tilde{\\Pi}^k_N  u,vJ^k}_{\\hat{D}}} \\\\\n%&\\leq \\LRp{J^k,1}_{\\hat{D}} \\LRb{\\LRp{u-\\tilde{\\Pi}^k_Nu,v}_{\\hat{D}}} = \\LRb{D^k}\\LRb{\\LRp{u-\\tilde{\\Pi}^k_Nu,v}_{\\hat{D}}},\n&\\leq \\nor{J^k}_{L^{\\infty}\\LRp{D^k}} \\LRb{\\LRp{u-\\tilde{\\Pi}^k_Nu,v}_{\\hat{D}}}.% = \\LRb{D^k}\\LRb{\\LRp{u-\\tilde{\\Pi}^k_Nu,v}_{\\hat{D}}},\n\\end{align*}\n%where we have applied the Cauchy-Schwarz inequality in the last steps.  \nWe can then note that $\\tilde{\\Pi}^k_Nu = \\Pi_N\\LRp{\\frac{1}{J^k} \\Pi_N\\LRp{uJ^k}}$ to show that\n\\begin{align*}\n{\\LRp{u-\\tilde{\\Pi}^k_Nu,v}_{\\hat{D}}} &= {\\LRp{uJ^k,\\frac{v}{J^k}}_{\\hat{D}}-\\LRp{\\Pi_N\\LRp{\\frac{1}{J^k} \\Pi_N\\LRp{uJ^k}},v}_{\\hat{D}}} \\\\\n&= \\LRp{uJ^k,\\frac{v}{J^k}}_{\\hat{D}}-\\LRp{\\Pi_N\\LRp{uJ^k},\\frac{v}{J^k}}_{\\hat{D}}. %+ \\LRp{\\Pi_N\\LRp{uJ^k},\\Pi_N\\LRp{\\frac{v}{J^k}}}_{\\hat{D}} - \\LRp{\\Pi_N\\LRp{uJ^k},\\Pi_N\\LRp{\\frac{v}{J^k}}}_{\\hat{D}}\\\\\n%&= \\LRp{uJ^k,\\frac{v}{J^k}}_{\\hat{D}}-\\LRp{\\Pi_N\\LRp{uJ^k},\\frac{v}{J^k}}_{\\hat{D}} + \\LRp{\\Pi_N\\LRp{uJ^k},\\Pi_N\\LRp{\\frac{v}{J^k}}}_{\\hat{D}} - \\LRp{\\Pi_N\\LRp{uJ^k},\\Pi_N\\LRp{\\frac{v}{J^k}}}_{\\hat{D}}\n\\end{align*}\nAdding and subtracting $\\LRp{\\Pi_N\\LRp{uJ^k},\\Pi_N\\LRp{\\frac{v}{J^k}}}_{\\hat{D}}$ and using Theorem~\\ref{thm:wproj} (noting that $v\\in W^{N+1,2}\\LRp{D^k}$ since it is polynomial) gives\n\\begin{align*}\n\\nor{\\Pi^k_Nu-\\tilde{\\Pi}^k_Nu}_{L^2\\LRp{D^k}}^2 &\\leq \\nor{J^k}_{L^{\\infty}\\LRp{D^k}}\\LRb{\\LRp{u-\\tilde{\\Pi}^k_Nu,v}_{\\hat{D}}}\\\\\n&= \\nor{J^k}_{L^{\\infty}\\LRp{D^k}}\\LRb{\\LRp{uJ^k - \\Pi_N\\LRp{uJ^k},\\frac{v}{J^k}-\\Pi_N\\LRp{\\frac{v}{J^k}}}_{\\hat{D}}} \\\\\n&\\leq \\nor{J^k}_{L^{\\infty}\\LRp{D^k}}\\nor{uJ^k - \\Pi_N\\LRp{uJ^k}}_{\\hat{D}}\\nor{\\frac{v}{J^k}-\\Pi_N\\LRp{\\frac{v}{J^k}}}_{\\hat{D}}\\\\\n&\\leq C h^{\\min\\LRp{r,N+1}+N+1} \\tilde{C}_J \\nor{u}_{W^{r,2}\\LRp{D^k}} \\nor{v}_{W^{N+1,2}\\LRp{D^k}},\n\\end{align*}\nwhere \n\\[\n\\tilde{C}_J = \\nor{J^k}_{L^{\\infty}\\LRp{D^k}}\\nor{\\frac{1}{J^k}}_{L^{\\infty}\\LRp{D^k}} \\nor{J^k}_{W^{N+1,\\infty}\\LRp{D^k}}\\nor{\\frac{1}{J^k}}_{W^{N+1,\\infty}\\LRp{D^k}}.\n\\]\nApplying Lemma~\\ref{lemma:sobolev} then yields\n\\begin{align*}\n\\nor{\\Pi^k_Nu-\\tilde{\\Pi}^k_Nu}_{L^2\\LRp{D^k}}^2 &\\leq C_N h^{\\min\\LRp{r,N+1}+1} C_J \\nor{u}_{W^{N+1,2}\\LRp{D^k}} \\nor{v}_{L^2\\LRp{D^k}}.\n\\end{align*}\nDividing through by $\\nor{v}_{L^2\\LRp{D^k}} = \\nor{\\Pi^k_N u - \\tilde{\\Pi}^k_N  u}_{L^2\\LRp{D^k}}$ gives the desired result.  % $C_J = \\nor{J}_{L^{\\infty}} \\nor{\\frac{1}{J}}^2_{L^\\infty} \\nor{J}^2_{W^{N+1,\\infty}\\LRp{\\hat{D}}}$.\n\\end{proof}\nTheorem~\\ref{thm:wproj} can be used to show that the $L^2$ error between $\\Pi^k_N u, \\tilde{\\Pi}^k_N u$ and $u \\in W^{r,2}\\LRp{D^k}$ is $O(h^r)$.  Theorem~\\ref{thm:superconverge} demonstrates that the $L^2$ difference between $\\Pi^k_N u, \\tilde{\\Pi}^k_N u$ is $O(h^{r+1})$, or at least one order higher than the approximation error.  We note that optimal convergence of the weight-adjusted projection requires that the geometric mapping $\\bm{\\Phi}_k$ is asymptotically affine (i.e., the Sobolev norm of $J^k, \\bm{G}^k$ does not grow under mesh refinement), which is ensured under nested mesh refinement and appropriate curvilinear blending strategies \\cite{lenoir1986optimal, warburton2013low, chan2016weight2}.  \n%We note that, while Theorem~\\ref{thm:superconverge} requires sufficient smoothness of $u$, numerical experiments in Section~\\ref{sec:num} demonstrate that even for discontinuous functions, the $L^2$ and weight-adjusted projections are indistinguishable from each other on a curved element.  \n\n\\subsubsection{Local and global conservation}\n\\label{sec:conservation}\nWe next address local conservation of the weight-adjusted scheme (\\ref{eq:dgform2}), which is also referred to as primary conservation \\cite{fisher2013discretely, fisher2013high, carpenter2014entropy, friedrich2017entropy}.  We begin by noting that (\\ref{eq:dgform2}) is locally conservative with respect to the weight-adjusted inner product.  Testing (\\ref{eq:dgform2weak}) with $\\bm{1}$ yields\n\\[\n\\bm{1}^T\\bm{M}\\bm{M}_{1/J^k}^{-1}\\bm{M}\\td{\\bm{u}_h}{t} + \n\\sum_{j=1}^d \\bm{1}^T \\LRp{2\\bm{Q}^j_k \\circ \\bm{F}_{j,S}}\\bm{1} + \\sum_{j=1}^d \\bm{1}^T\\bm{W}_f \\diag{\\bm{n}_j}\\LRp{\\bm{f}_j^* - \\bm{f}_j(\\tilde{\\bm{u}}_f)} = 0.\n\\]\nLocal conservation can be shown by applying the SBP property (\\ref{eq:sbpk}) and noting that $\\LRp{\\bm{B}^i_k \\circ \\bm{F}_{j,S}}\\bm{1} = \\bm{W}_f\\diag{\\bm{n}_j \\circ \\bm{J}^k_f}\\bm{f}_j(\\bm{u})$ (using the consistency of $\\bm{f}_S$ and diagonal nature of $\\bm{B}^i_k$) yields\n\\[\n\\bm{1}^T\\bm{M}\\bm{M}_{1/J^k}^{-1}\\bm{M}\\td{\\bm{u}_h}{t} + \n\\sum_{j=1}^d \\bm{1}^T \\LRp{\\LRp{\\bm{Q}^j_k-\\LRp{\\bm{Q}^j_k}^T} \\circ \\bm{F}_{j,S}}\\bm{1} + \\sum_{j=1}^d \\bm{1}^T\\bm{W}_f \\diag{\\bm{n}_j}\\LRp{\\bm{f}_j^*} = 0.\n\\]\nSince $\\LRp{\\bm{Q}^j_k-\\LRp{\\bm{Q}^j_k}^T} $ is skew-symmetric and $\\bm{F}_{j,S}$ is symmetric, the Hadamard product of these two matrices is skew-symmetric.  As a result, $\\bm{1}^T \\LRp{\\LRp{\\bm{Q}^j_k-\\LRp{\\bm{Q}^j_k}^T} \\circ \\bm{F}_{j,S}}\\bm{1} = 0$ and \n\\begin{equation}\n\\bm{1}^T\\bm{M}\\bm{M}_{1/J^k}^{-1}\\bm{M}\\td{\\bm{u}_h}{t} + \\sum_{j=1}^d \\bm{1}^T\\bm{W}_f \\diag{\\bm{n}_j}\\LRp{\\bm{f}_j^*} = 0.\n\\label{eq:localcons}\n\\end{equation}\nGlobal conservation is shown by summing (\\ref{eq:localcons}) over all elements $D^k$.  Because the flux $\\bm{f}_j^*$ is single-valued on each face and the outward normal $\\bm{n}_j$ changes sign on adjacent elements, the contributions $\\bm{1}^T\\bm{W}_f \\diag{\\bm{n}_j}\\LRp{\\bm{f}_j^*}$ cancel on all interior interfaces.\\footnote{Conservation still holds when incorporating entropy dissipation through penalty terms involving jumps.  This is because the definition of the jump changes sign on adjacent elements, such that jump contributions cancel when summing over all elements.} On periodic meshes, this yields conservation with respect to the weight-adjusted mass matrix\n\\[\n\\sum_k \\bm{1}^T\\bm{M}\\bm{M}_{1/J^k}^{-1}\\bm{M}\\td{\\bm{u}_h}{t} = 0.\n\\]\nHowever, while the weight-adjusted approximation of the mass matrix is high order accurate and efficient, it does not preserve the average over a physical element, which is equivalent to the $J$-weighted average over the reference element.  This is due to the fact that, in general,\n\\begin{equation}\n\\int_{\\hat{D}}u J^k \\diff{\\hat{\\bm{x}}} - \\int_{\\hat{D}} T_{1/J^k}^{-1}u \\diff{\\hat{\\bm{x}}} \\approx \\bm{1}^T\\bm{M}_{J^k}\\bm{u} - \\bm{1}^T\\bm{M}\\bm{M}_{1/J^k}^{-1}\\bm{M}\\bm{u} \\neq 0.  \n\\label{eq:conserr}\n\\end{equation}\nResults in \\cite{chan2016weight1} show that the difference between the true mean and weight-adjusted mean in (\\ref{eq:conserr}) converges extremely fast at a rate of $O(h^{2N+2})$.  However, for systems of conservation laws, it is often desired that the local element average is preserved exactly up to machine precision.  We present two simpler approaches to ensuring local conservation in this section.  \n\nThe simplest way to ensure local conservation is to approximate $J$ using a degree $N$ polynomial and utilize a sufficiently accurate quadrature.  Then, we have the following lemma:\n\\begin{lemma}\nLet $J^k \\in P^N$, and let integrals be computed using quadrature which is exact for degree $2N$ polynomials.  Then, \n\\[\n\\bm{1}^T\\bm{M}\\bm{M}^{-1}_{1/J^k}\\bm{M}\\bm{u} = \\int_{\\hat{D}}T^{-1}_{1/J^k} u \\diff{\\hat{\\bm{x}}}=  \\int_{\\hat{D}} u J^k\\diff{\\hat{\\bm{x}}}.\n\\]\n\\label{eq:conscorrect1}\n\\end{lemma}\n\\begin{proof}\nThe proof relies on (\\ref{eq:wadgTw}), which states that $\\LRp{\\frac{1}{J^k} T^{-1}_{1/J^k}u,v}_{\\hat{D}} = \\LRp{u,v}_{\\hat{D}}$ for all $v\\in P^N$.  If $J^k$ is a polynomial of degree $N$, then taking $v = 1$ yields\n\\[\n\\LRp{T^{-1}_{1/J^k}u,1}_{\\hat{D}} = \\LRp{\\frac{1}{J^k}T^{-1}_{1/J^k}u,{J^k}}_{\\hat{D}}= \\LRp{u,{J^k}}_{\\hat{D}} = \\int_{\\hat{D}} uJ^k\\diff{\\hat{\\bm{x}}}. \n\\]\nAdditionally, the proof still holds if integrals are approximated using a quadrature rule which exactly integrates $uJ^k \\in P^{2N}$.\n\\end{proof}\nWe note that, for isoparametric curved elements, $J^k \\not\\in P^N$ in general (in 2D, $J^k \\in P^{2N-2}$, while in 3D, $J^k \\in P^{3N-3}$ \\cite{johnen2013geometrical}).  Thus, to ensure local conservation, we will approximate $J^k$ using a degree $N$ polynomial (for example, the interpolant or $L^2$ projection onto $P^N$).  We note that this approximation is required only in the weight-adjusted mass matrix, and does not modify the scaled geometric terms $G^k_{ij}$.  \n\nThe second approach relies on a simple correction which restores exact conservation of the true mean.  In \\cite{chan2016weight2}, it was shown that a rank one correction of the weight-adjusted mass matrix inverse preserves the mean exactly.  However, this requires the use of the Sherman--Morrison formula to compute the inverse of a rank one matrix update, which can be cumbersome to incorporate.  We present a simpler explicit correction formula which does not involve matrices.  Let $u_J$ and $u_{\\rm WADG}$ be defined through \n%coefficients \n%\\[\n%\\bm{u} = \\bm{M}^{-1}\\bm{M}_{1/J}\\bm{M}^{-1} \\LRp{\\bm{V}_q^T\\bm{W}\\bm{f}},\n%\\]\n%where $\\bm{f}$ are the values of $f$ at quadrature points on $\\hat{D}$.  \n\\begin{align*}\n\\LRp{u_J J,v}_{\\hat{D}} &= \\LRp{f,v}_{\\hat{D}}, \\qquad \\forall v \\in P^N\\LRp{\\hat{D}},\\\\\n\\LRp{T_{1/J}^{-1}u_{\\rm WADG},v}_{\\hat{D}} &= \\LRp{f,v}_{\\hat{D}}, \\qquad \\forall v \\in P^N\\LRp{\\hat{D}},\n\\end{align*}\nwhere $u_J$ corresponds to the inversion of the weighted mass matrix and $u_{\\rm WADG}$ corresponds to the inversion of a weight-adjusted mass matrix.  For example, if $f = u J$ for some function $u(\\bm{x})$, then $u_J = \\Pi^k_N u$ and $u_{\\rm WADG} = \\tilde{\\Pi}^k_N u$.  To ensure both local and global conservation, we require that the weighted average of $u_{\\rm WADG}$ is the same as the weighted average of $u_J$.  Let the conservative weight-adjusted $\\tilde{u}_{\\rm WADG}$ be defined as\n\\begin{equation}\n  \\tilde{u}_{\\rm WADG} = u_{\\rm WADG} + \\frac{\\int_{\\hat{D}} \\left(f  - J u_{\\rm WADG}\\right)\\diff{\\hat{\\bm{x}}}}{\\int_{\\hat{D}} J \\diff{\\hat{\\bm{x}}}}.  \n  \\label{eq:conscorrect}\n\\end{equation}\nTaking the weighted integral of $\\tilde{u}_{\\rm WADG}$ yields\n\\[\n  \\int_{\\hat{D}}\\tilde{u}_{\\rm WADG}J \\diff{\\hat{\\bm{x}}} = \\int_{\\hat{D}} f \\diff{\\hat{\\bm{x}}}.\n\\]\nIn other words, (\\ref{eq:conscorrect}) ensures local conservation by correcting the weighted average of $u_{\\rm WADG}$ to match that of $u_J$.  Applying this correction to the right hand side of (\\ref{eq:dgform2}) then yields a scheme which locally and globally conserves mean values of the conservative variables.\n\nThis approach is applicable to an arbitrary weight, and can be generalized to matrix-valued weights as well \\cite{chan2017weight}.  Moreover, using Theorem 6 in \\cite{chan2016weight1}, one can show that the $L^2$ norm of the difference $\\tilde{u}_{\\rm WADG} - u_{\\rm WADG}$ is $O(h^{2N+1})$, and does not affect high order accuracy.  \n\n\\section{Enforcing the discrete geometric conservation law}\n\\label{sec:4}\nAn important aspect of Theorem~\\ref{thm:stab1} is the assumption that $\\bm{Q}^j_k\\bm{1} = 0$ for $j = 1,\\ldots,d$.  However, this is not always guaranteed to hold for $\\bm{Q}^j_k$ as defined through (\\ref{eq:dik}).  In this section, we discuss methods of constructing the geometric terms $G^k_{ij}$ for curvilinear meshes in a way that ensures $\\bm{Q}^j_k\\bm{1} = 0$.  \n\nFrom (\\ref{eq:dik}), the condition $\\bm{Q}^j_k\\bm{1} = 0$ is equivalent to\n\\begin{align*}\n\\bm{Q}^j_k\\bm{1} = \\bm{W}_N\\sum_{j=1}^d\\bm{D}^j_N\\circ \\avg{\\bm{G}_{ij}^k}\\bm{1} &= \\frac{1}{2}\\bm{W}_N\\sum_{j=1}^d \\LRp{ \\diag{\\bm{G}_{ij}^k}\\bm{D}^j_N \\bm{1} + \\bm{D}^j_N\\diag{\\bm{G}_{ij}^k}\\bm{1}} \\\\\n&= \\frac{1}{2}\\bm{W}_N\\sum_{j=1}^d \\bm{D}^j_N \\bm{G}_{ij}^k = 0,\n\\end{align*}\nwhere we have used that $\\bm{D}^j_N \\bm{1} = 0$ to eliminate the first term.  Since $\\bm{W}_N$ is a diagonal matrix with positive entries, $\\bm{Q}^j_k\\bm{1} = 0$ is equivalent to ensuring that a discrete version of the GCL (\\ref{eq:gcl}) holds\n\\begin{equation}\n\\sum_{j=1}^d \\bm{D}^j_N \\bm{G}_{ij}^k = 0.\n\\label{eq:dgcl}\n\\end{equation}\nThis condition is required to ensure that free-stream preservation holds at the discrete level.  In other words, we wish to ensure that the semi-discrete scheme preserves (for $\\bm{u}$ constant) \n\\[\n\\pd{\\bm{u}}{t} + \\Grad \\cdot \\bm{f}(\\bm{u}) = \\pd{\\bm{u}}{t} = 0.\n\\]\nFor isoparametric geometric mappings (where the degree of the mapping matches the degree of the polynomial approximation) in two dimensions, the GCL is naturally enforced by the ``cross-product'' form, noting that the scaled metric terms $G^k_{ij}$ are exactly polynomials of degree $N$.  As a result, computing the metric terms exactly automatically enforces that both the continuous GCL (\\ref{eq:gcl}) and the discrete GCL (\\ref{eq:dgcl}) are satisfied.  However, the discrete GCL is not always maintained at the discrete level in 3D.  \n\nIn three dimensions, geometric terms are typically computed in ``cross-product'' form\n\\begin{align}\n\\LRs{\\begin{array}{c}\nG^k_{1i}\\\\\nG^k_{2i}\\\\\nG^k_{3i}\\end{array}} &= \\pd{\\bm{x}}{\\hat{x}_j}\\times \\pd{\\bm{x}}{\\hat{x}_k}, \\qquad (i,j,k) = (1,2,3), \\text{ cyclic}.\n\\end{align}\nNote the abuse of notation here and in the sequel, the superscript $k$ refers to the element number and the subscript $k$ to the cyclic index. \nThis formula can be used to compute the geometric terms exactly at volume and surface quadrature points.  However, because $\\pd{\\bm{x}}{\\hat{x}_j},\\pd{\\bm{x}}{\\hat{x}_k} \\in P^{N-1}$, the geometric terms $G^k_{ij}$ are polynomials of degree $P^{2N-2}$.  The discrete GCL condition holds only if $G^k_{ij} \\in P^{2N-2}$ are differentiated exactly; however, because applying $\\bm{D}^j_N$ involves the $L^2$ projection, and because $G^k_{ij}$ and its $L^2$ projection onto degree $N$ polynomials can differ, the discrete GCL (\\ref{eq:dgcl}) does not hold in general \\cite{kopriva2006metric}.  \n\nThis can be remedied by using an alternative form of the geometric terms, which ensures that (\\ref{eq:dgcl}) is satisfied a-priori \\cite{thomas1979geometric, visbal2002use, kopriva2006metric}.  The geometric terms $G^k_{ij}$ can also be computed using a ``conservative curl'' form, where $G^k_{ij}$ are the image of the curl applied to some quantity\n%We use the invariant curl form, which is given as\n%\\begin{align}\n%J^k\\bm{G}^k_{nj} = -\\frac{1}{2}\\bm{e}_j\\cdot \\hat{\\Grad} \\times \\LRp{x_l\\hat{\\Grad}x_m - x_m\\hat{\\Grad}x_l}, \\qquad j = 1,2,3, \\quad (n,m,l) = (1,2,3), \\text{ cyclic},\n%\\label{eq:conscurl}\n%\\end{align}\n%where $\\bm{e}_j$ is the $j$th canonical vector and $\\hat{\\Grad} \\times $ denotes the curl with respect to the reference element coordinates. \n% Expanding and simplifying allows (\\ref{eq:conscurl}) to be rewritten \n as follows: % \\cite{hindenlang2012explicit}:\n\\begin{align}\n\\LRs{\\begin{array}{c}\nG^k_{1i}\\\\\nG^k_{2i}\\\\\nG^k_{3i}\\end{array}} =\n\\LRs{\\begin{array}{c}\n    {\\left(         - \\hat{\\nabla} \\times \\left(x_3 \\hat{\\nabla} x_2\\right)\\right)}_i\\\\\n    {\\left(\\phantom{-}\\hat{\\nabla} \\times \\left(x_3 \\hat{\\nabla} x_1\\right)\\right)}_i\\\\\n    {\\left(\\phantom{-}\\hat{\\nabla} \\times \\left(x_1 \\hat{\\nabla} x_2\\right)\\right)}_i\\end{array}},\n\\label{eq:conscurl}\n\\end{align}\nwhere the subscript $i$ denotes the $i$th component of the vector quantity.\nFrom (\\ref{eq:conscurl}), it can be observed that, because the divergence of a curl vanishes, the continuous GCL condition (\\ref{eq:gcl}) holds.  \n%\\begin{align}\n%\\hat{\\Grad}\\cdot \\LRs{\\begin{array}{c}\n%J^k\\bm{G}^k_{1i}\\\\\n%J^k\\bm{G}^k_{2i}\\\\\n%J^k\\bm{G}^k_{3i}\\end{array}} = \\sum_{j=1}^d \\pd{}{\\hat{x}_j}J^k\\bm{G}^k_{ij} = 0.\n%\\end{align}\nThe central idea of \\cite{visbal2002use, kopriva2006metric} is to use (\\ref{eq:conscurl}), but to interpolate before applying the curl  %This approximates the geometric terms via\n\\begin{align}\n\\LRs{\\begin{array}{c}\nG^k_{1i}\\\\\nG^k_{2i}\\\\\nG^k_{3i}\\end{array}} =\n\\LRs{\\begin{array}{c}\n    {\\left(         - \\hat{\\nabla} \\times I_N\\left(x_3 \\hat{\\nabla} x_2\\right)\\right)}_i\\\\\n    {\\left(\\phantom{-}\\hat{\\nabla} \\times I_N\\left(x_3 \\hat{\\nabla} x_1\\right)\\right)}_i\\\\\n    {\\left(\\phantom{-}\\hat{\\nabla} \\times I_N\\left(x_1 \\hat{\\nabla} x_2\\right)\\right)}_i\\end{array}},\n\\label{eq:iconscurl}\n\\end{align}\nwhere $I_N$ denotes the degree $N$ polynomial interpolation operator. Since the geometric terms are still computed by applying a curl, the continuous GCL condition (\\ref{eq:gcl}) is still satisfied. We shall also show that this approximation also satisfies the discrete GCL condition. \n\nWe adopt a slight modification of (\\ref{eq:iconscurl}) in this work which is tailored towards triangular and tetrahedral elements.   Because the geometric terms are computed by applying the curl, the geometric terms are approximated as degree $(N-1)$ polynomials rather than degree $N$ polynomials, which can reduce accuracy.   Instead, we approximate geometric terms by using the interpolation operator $I_{N+1}$ onto degree $(N+1)$ polynomials, then interpolating back to degree $N$ polynomials \n\\begin{align}\n\\LRs{\\begin{array}{c}\nG^k_{1i}\\\\\nG^k_{2i}\\\\\nG^k_{3i}\\end{array}} =\n\\LRs{\\begin{array}{c}\n    I_N{\\left(         - \\hat{\\nabla} \\times I_{N+1}\\left(x_3 \\hat{\\nabla} x_2\\right)\\right)}_i\\\\\n    I_N{\\left(\\phantom{-}\\hat{\\nabla} \\times I_{N+1}\\left(x_3 \\hat{\\nabla} x_1\\right)\\right)}_i\\\\\n    I_N{\\left(\\phantom{-}\\hat{\\nabla} \\times I_{N+1}\\left(x_1 \\hat{\\nabla} x_2\\right)\\right)}_i\\end{array}}.\n\\label{eq:iconscurl2}\n\\end{align}\nFor any $u \\in P^N\\LRp{\\hat{D}}$, $\\pd{u}{\\hat{x}_i} \\in P^{N-1}\\LRp{\\hat{D}}$ for $i = 1,2,3$.  Thus, the interpolation to degree $N$ polynomials is exact, since the derivatives of a degree $(N+1)$ polynomial are degree $N$ on triangles and tetrahedra.  % the approximation generated by (\\ref{eq:iconscurl2}) is a degree $N$ polynomial.  \n\n\\begin{remark}\nThe accuracy of (\\ref{eq:iconscurl2}) depends on the choice of interpolation points.  It is well known that interpolating at equispaced points can result in inaccurate polynomial approximations.  One can determine good interpolation point sets by optimizing over some measure of interpolation quality (such as the Lebesgue constant), and in practice, sets of interpolation points are pre-computed for some polynomial degrees $N = 1,\\ldots, N_{\\max}$ on the reference element and stored \\cite{chen1996optimal, hesthaven1998electrostatics}, or explicitly computed as the image of equispaced points under an appropriately defined mapping \\cite{blyth2006lobatto, warburton2006explicit, chan2015comparison}.  \n\\end{remark}\n\nTo prove that the construction (\\ref{eq:iconscurl2}) satisfies Assumption~\\ref{ass:norm}, we must assume that the interpolation points for a degree $N$ element include an appropriate number of points on each face.  We note that these assumptions exclude interpolation points which lie purely in the interior of an element, such as those introduced in \\cite{williams2014symmetric, witherden2015identification}.  We can now show that the geometric terms satisfy all conditions necessary to guarantee entropy stability:\n\\begin{theorem}\n%<<<<<<< HEAD\nLet the mesh consist of triangles or tetrahedral elements which satisfy Assumption~\\ref{ass:norm}, and let the interpolation points which define the degree $N$ interpolation operator be distributed such that $N^f_p$ points lie on each face. Then, the approximate geometric terms $\\tilde{J^k\\bm{G}^k_{ij}}$  and approximate scaled normals $\\tilde{n_iJ^k_f}$ computed using (\\ref{eq:iconscurl2}) and (\\ref{eq:normalconsistency})) satisfy both the discrete GCL condition (\\ref{eq:dgcl}) and Assumption~\\ref{ass:norm}.  Additionally, the error in the approximation satisfies\n%=======\n%Let the mesh satisfy Assumption~\\ref{ass:norm}, and let the interpolation points which define the interpolation operator $I_N$ be distributed such that $N^f_p$ points lie on each face. Then, the approximate geometric terms $\\tilde{G^k_{ij}}$  and approximate scaled normals $\\tilde{n_iJ^k_f}$ computed using (\\ref{eq:iconscurl2}) and (\\ref{eq:normalconsistency})) satisfy both the discrete GCL condition (\\ref{eq:dgcl}) and Assumption~\\ref{ass:norm}.  Additionally, the error in the approximation satisfies\n%>>>>>>> 97186f466cf2432ab515d0a2d65cf4dd49645850\n\\[\n%\\sqrt{\\sum_{k}\\sum_{ij=1}^d\\nor{{J^k\\bm{G}^k_{ij}}-\\tilde{J^k\\bm{G}^k_{ij}}}_{L^2\\LRp{\\hat{D}}}^2} \\leq C_N h^{N+2} \\nor{\\cdot}_{W^{N+2,2}\\LRp{D^k}}.\n\\nor{{G^k_{ij}}-\\tilde{G^k_{ij}}}_{L^2\\LRp{\\Omega}}^2  \\leq C_N \\LRb{\\Omega} h^{N+2} \\sqrt{\\sum_{i=1}^d \\sum_k \\nor{\\bm{r}_i}^2_{W^{N+2,2}\\LRp{D^k}}}.\n\\]\n\\label{thm:koprivagcl}\n\\end{theorem}\n\\begin{proof}\n  The satisfaction of (\\ref{eq:dgcl}) relies on the fact that $\\tilde{G^k_{ij}}$ is a degree $N$ polynomial and is equal to its own $L^2$ projection.  Let $\\tilde{\\bm{G}^k_{ij}}$ denote the polynomial coefficients of $\\tilde{G^k_{ij}}$.  \nThen, applying $\\bm{D}^j_N$ to evaluations of $\\tilde{G^k_{ij}}$ at volume and surface quadrature points and using (\\ref{eq:dnvqvf}), we have\n\\[\n\\sum_{j=1}^d\\bm{D}^j_N \\LRs{\n\\begin{array}{c}\n\\bm{V}_q\\\\\n\\bm{V}_f\n\\end{array}}\n\\tilde{\\bm{G}^k_{ij}} = \n\\sum_{j=1}^d \\LRs{\\begin{array}{c}\n\\bm{V}_q\\bm{D}_i\\tilde{\\bm{G}^k_{ij}} \\\\\n0\n\\end{array}}.\n\\]\nThe entries of $\\bm{V}_q\\bm{D}_i\\tilde{\\bm{G}^k_{ij}}$ correspond to values of the derivatives of $\\tilde{G^k_{ij}}$ evaluated at quadrature points.  Since \n\\[\n\\sum_{j=1}^d\\pd{}{\\hat{x}_j}\\tilde{G^k_{ij}} = 0\n\\]\nby construction using (\\ref{eq:iconscurl2}), $\\sum_{j=1,\\ldots,d} \\bm{V}_q\\bm{D}_i\\tilde{\\bm{G}^k_{ij}} = \\bm{0}$ as well.  \n\nEquation (\\ref{eq:normalconsistency}) of Assumption~\\ref{ass:norm} is satisfied by directly constructing the scaled normals $\\tilde{\\bm{n}}J^k_f$ using values of $\\tilde{G^k_{ij}}$ at quadrature points.  We must now prove that the construction of $\\tilde{\\bm{n}}J^k_f$ implies that Equation (\\ref{eq:normalsign}) holds. This is not immediately clear; since the normals are constructed from the approximate geometric terms and the formula (\\ref{eq:normalconsistency}), it is not guaranteed that $\\tilde{\\bm{n}}^+J^{k,+}_f = -\\tilde{\\bm{n}}J^k_f$ will hold across a shared face.  However, the scaled normal vectors involve only nodal values on the shared face because the normals are computed in terms of the tangential reference derivatives \\cite{kopriva2006metric}.  Thus, assuming a watertight mesh, the interpolation nodes on two neighboring elements will coincide for a shared face $f$, such that the trace of $\\tilde{G^k_{ij}}$ from either neighboring element will be the same lower-dimensional polynomial on $f$.  This is sufficient to ensure that the scaled normal vectors $\\tilde{\\bm{n}}^+J^{k,+}_f, \\tilde{\\bm{n}}J^k_f$ will be equal and opposite.  \n\nThe local $L^2$ error $\\nor{{G^k_{ij}}-\\tilde{G^k_{ij}}}_{L^2\\LRp{D^k}}$ can be bounded by noting that, since the error $G^k_{ij}-\\tilde{G^k_{ij}}$ consists of linear combinations of derivatives of the interpolation error $\\bm{r}_i-I_{N+1}\\bm{r}_i$, it can be bounded by the $H^1$-seminorm of the latter quantity\n\\begin{align*}\n\\nor{{G^k_{ij}}-\\tilde{G^k_{ij}}}_{L^2\\LRp{D^k}} &\\leq %\\nor{\\sqrt{J^k}}_{L^2\\LRp{\\hat{D}}} \\nor{\\hat{\\Grad}\\times \\LRp{\\bm{r}_i-I_{N+1}\\bm{r}_i}}_{L^2\\LRp{\\hat{D}}}\\\\\n%\\leq \n \\sum_{i=1}^d C_1 \\nor{\\sqrt{J^k}}_{L^2\\LRp{\\hat{D}}} \\LRb{\\LRp{\\bm{r}_i-I_{N+1}\\bm{r}_i}}_{H^1\\LRp{\\hat{D}}}\\\\\n &\\leq  \\sum_{i=1}^d \\tilde{C}_N \\nor{\\sqrt{J^k}}_{L^2\\LRp{\\hat{D}}} \\LRb{\\bm{r}_i}_{W^{N+2,2}\\LRp{\\hat{D}}},\n\\end{align*}\nwhere we have used the Bramble-Hilbert lemma \\cite{brenner2007mathematical} on the reference element in the last step.  Since it is applied on the reference element $\\hat{D}$ rather than the physical element $D^k$, the constant $\\tilde{C}_N$ depends on the reference element and order of approximation, but not the mesh size $h$.  A scaling argument for quasi-uniform meshes then yields that\n\\begin{align}\n\\LRb{\\bm{r}_i}_{W^{N+2,2}\\LRp{\\hat{D}}} \\leq C_2 h^{N+2}\\nor{\\bm{r}_i}_{W^{N+2,2}\\LRp{D^k}}.\n\\label{eq:localgeoerr}\n\\end{align}\nThe global estimate results from squaring (\\ref{eq:localgeoerr}), summing over all elements and using $\\nor{\\sqrt{J^k}}^2_{L^2\\LRp{\\hat{D}}} = \\LRb{D^k}$.\n%\\[\n%%\\sqrt{\\sum_k \\nor{{J^k\\bm{G}^k_{ij}}-\\tilde{J^k\\bm{G}^k_{ij}}}_{L^2\\LRp{D^k}}^2 }\n%\\nor{{J^k\\bm{G}^k_{ij}}-\\tilde{J^k\\bm{G}^k_{ij}}}_{L^2\\LRp{\\Omega}}^2  \\leq C_N \\LRb{\\Omega} h^{N+2} \\sqrt{\\sum_k \\nor{\\bm{r}}_2_{W^{N+2,2}\\LRp{D^k}}}.\n%\\]\n\\end{proof}\n\n%<<<<<<< HEAD\n\\begin{remark}\nIt should be pointed out that this approach does not work on hexahedral elements.  This is due to the fact that the natural polynomial space on hexahedral elements is the tensor product space $Q^N\\LRp{\\widehat{D}}$\n\\[\nQ^N\\LRp{\\widehat{D}} = \\LRc{\\hat{x}_1^{i_1}\\ldots\\hat{x}_d^{i_d}, \\quad \\hat{\\bm{x}} \\in \\widehat{D}, \\quad 0 \\leq i_k \\leq N}.\n\\]\nFor $u\\in Q^{N+1}\\LRp{\\hat{D}}$, $\\pd{u}{\\hat{x}_i}$ is at most degree $N$ in the coordinate $\\hat{x}_i$, but can remain a polynomial of degree $N+1$ in all other coordinates.  Thus, interpolating from degree $N+1$ to degree $N$ polynomials in (\\ref{eq:iconscurl2}) introduces aliasing errors and is no longer exact.  The result of (\\ref{eq:iconscurl2}) is no longer the image of a curl, and thus does not satisfy the discrete GCL by construction.  \n\\end{remark}\n\n\n%We briefly outline how to compute $\\tilde{J^k\\bm{G}^k_{ij}}$ in three dimensions.  Let $\\LRc{\\hat{\\bm{x}}^N_i}_{i=1}^{N_p}$ denote the set of degree $N$ interpolation points, and let $\\ell^N_i(\\hat{\\bm{x}})$ denote the $i$th degree $N$ Lagrange basis function on the reference element.  We define interpolation matrices $\\bm{V}_N^{N+1}$ and $\\bm{V}^N_{N+1}$ between degree $N$ and $N+1$ polynomials such that \n%=======\nWe briefly outline how to compute $\\tilde{G^k_{ij}}$ in three dimensions.  Let $\\LRc{\\hat{\\bm{x}}^N_i}_{i=1}^{N_p}$ denote the set of degree $N$ interpolation points, and let $\\ell^N_i(\\hat{\\bm{x}})$ denote the $i$th degree $N$ Lagrange basis function on the reference element.  We define interpolation matrices $\\bm{V}_N^{N+1}$ and $\\bm{V}^N_{N+1}$ between degree $N$ and $N+1$ polynomials such that \n%>>>>>>> 97186f466cf2432ab515d0a2d65cf4dd49645850\n\\begin{align}\n\\LRp{\\bm{V}_N^{N+1}}_{ij} &= \\ell^N_j(\\hat{\\bm{x}}^{N+1}_i) , \\qquad 1\\leq i \\leq N_p, \\qquad \\qquad 1\\leq i \\leq (N+1)_p\\\\\n\\LRp{\\bm{V}^N_{N+1}}_{ij} &= \\ell^{N+1}_j(\\hat{\\bm{x}}^{N}_i) , \\qquad 1\\leq i \\leq (N+1)_p, \\qquad \\qquad 1\\leq i \\leq N_p, \\nonumber\n\\end{align}\nwhere $N_p, (N+1)_p$ denotes the number of interpolation points for degree $N$ and $N+1$ polynomials, respectively.  Next, let $\\bm{x}_1,\\bm{x}_2,\\bm{x}_3$ denote vectors containing $x_1,x_2,x_3$ coordinates of degree $N$ interpolation points on a curved physical element $D^k$, and let $\\tilde{\\bm{x}}_1,\\tilde{\\bm{x}}_2,\\tilde{\\bm{x}}_3$ denote their evaluation at degree $(N+1)$ interpolation points\n\\begin{align}\n\\tilde{\\bm{x}}_1 = \\bm{V}_N^{N+1}\\bm{x}_1, \\qquad \\tilde{\\bm{x}}_2 = \\bm{V}_N^{N+1}\\bm{x}_2, \\qquad \\tilde{\\bm{x}}_3 = \\bm{V}_N^{N+1}\\bm{x}_3.\n\\end{align}\nLet $\\tilde{\\bm{D}}^{N+1}_i$ denote the nodal differentiation matrix of degree $N+1$ with respect to the $i$th coordinate direction.  The geometric factors are computed as follows:\n\\begin{align}\n\\bm{G^k}_{11} &= \\phantom{-}\\bm{V}_{N+1}^N\\LRp{\\tilde{\\bm{D}}^{N+1}_3 \\LRp{\\LRp{ \\tilde{\\bm{D}}^{N+1}_2 \\tilde{\\bm{x}}_2} \\circ\\tilde{\\bm{x}}_3} - \\tilde{\\bm{D}}^{N+1}_2 \\LRp{ \\LRp{\\tilde{\\bm{D}}^{N+1}_3\\tilde{\\bm{x}}_2} \\circ\\tilde{\\bm{x}}_3}} \\\\\n\\bm{G^k}_{12} &= \\phantom{-}\\bm{V}_{N+1}^N\\LRp{\\tilde{\\bm{D}}^{N+1}_1 \\LRp{ \\LRp{\\tilde{\\bm{D}}^{N+1}_3\\tilde{\\bm{x}}_2} \\circ\\tilde{\\bm{x}}_3} - \\tilde{\\bm{D}}^{N+1}_3 \\LRp{ \\LRp{\\tilde{\\bm{D}}^{N+1}_1\\tilde{\\bm{x}}_2 }\\circ\\tilde{\\bm{x}}_3}} \\nonumber\\\\\n\\bm{G^k}_{13} &= \\phantom{-}\\bm{V}_{N+1}^N{\\LRp{\\tilde{\\bm{D}}^{N+1}_2 \\LRp{\\LRp{ \\tilde{\\bm{D}}^{N+1}_1\\tilde{\\bm{x}}_2} \\circ\\tilde{\\bm{x}}_3} - \\tilde{\\bm{D}}^{N+1}_1 \\LRp{\\LRp{ \\tilde{\\bm{D}}^{N+1}_2\\tilde{\\bm{x}}_2} \\circ\\tilde{\\bm{x}}_3}}} \\nonumber\\\\\n%\n\\bm{G^k}_{21} &= -\\bm{V}_{N+1}^N\\LRp{\\tilde{\\bm{D}}^{N+1}_3 \\LRp{\\LRp{ \\tilde{\\bm{D}}^{N+1}_2 \\tilde{\\bm{x}}_1} \\circ\\tilde{\\bm{x}}_3} - \\tilde{\\bm{D}}^{N+1}_2 \\LRp{\\LRp{ \\tilde{\\bm{D}}^{N+1}_3\\tilde{\\bm{x}}_1} \\circ\\tilde{\\bm{x}}_3}} \\nonumber \\\\\n\\bm{G^k}_{22} &= -\\bm{V}_{N+1}^N\\LRp{\\tilde{\\bm{D}}^{N+1}_1 \\LRp{ \\LRp{\\tilde{\\bm{D}}^{N+1}_3\\tilde{\\bm{x}}_1} \\circ\\tilde{\\bm{x}}_3} - \\tilde{\\bm{D}}^{N+1}_3 \\LRp{ \\LRp{\\tilde{\\bm{D}}^{N+1}_1\\tilde{\\bm{x}}_1 }\\circ\\tilde{\\bm{x}}_3}} \\nonumber\\\\\n\\bm{G^k}_{23} &= -\\bm{V}_{N+1}^N\\LRp{\\tilde{\\bm{D}}^{N+1}_2 \\LRp{ \\LRp{\\tilde{\\bm{D}}^{N+1}_1\\tilde{\\bm{x}}_1} \\circ\\tilde{\\bm{x}}_3} - \\tilde{\\bm{D}}^{N+1}_1 \\LRp{ \\LRp{\\tilde{\\bm{D}}^{N+1}_2\\tilde{\\bm{x}}_1 }\\circ\\tilde{\\bm{x}}_3}} \\nonumber\\\\\n%\n\\bm{G^k}_{31} &= -\\bm{V}_{N+1}^N\\LRp{\\tilde{\\bm{D}}^{N+1}_3 \\LRp{ \\LRp{\\tilde{\\bm{D}}^{N+1}_2 \\tilde{\\bm{x}}_2} \\circ\\tilde{\\bm{x}}_1} - \\tilde{\\bm{D}}^{N+1}_2 \\LRp{ \\LRp{\\tilde{\\bm{D}}^{N+1}_3\\tilde{\\bm{x}}_2} \\circ\\tilde{\\bm{x}}_1}} \\nonumber\\\\\n\\bm{G^k}_{32} &= -\\bm{V}_{N+1}^N\\LRp{\\tilde{\\bm{D}}^{N+1}_1 \\LRp{ \\LRp{\\tilde{\\bm{D}}^{N+1}_3\\tilde{\\bm{x}}_2} \\circ\\tilde{\\bm{x}}_1} - \\tilde{\\bm{D}}^{N+1}_3 \\LRp{  \\LRp{\\tilde{\\bm{D}}^{N+1}_1\\tilde{\\bm{x}}_2 }\\circ\\tilde{\\bm{x}}_1}} \\nonumber\\\\\n\\bm{G^k}_{33} &= -\\bm{V}_{N+1}^N\\LRp{\\tilde{\\bm{D}}^{N+1}_2 \\LRp{ \\LRp{\\tilde{\\bm{D}}^{N+1}_1\\tilde{\\bm{x}}_2} \\circ\\tilde{\\bm{x}}_1} - \\tilde{\\bm{D}}^{N+1}_1 \\LRp{  \\LRp{\\tilde{\\bm{D}}^{N+1}_2\\tilde{\\bm{x}}_2 }\\circ\\tilde{\\bm{x}}_1}}. \\nonumber\n\\end{align}\n\\begin{remark}\n\nWe note that the discrete GCL (\\ref{eq:dgcl}) can also be enforced directly through a local constrained minimization problem \\cite{fernandez2016simultaneous, crean2018entropy}, which yields a solution in terms of a pseudo-inverse.  However, we have not found a straightforward way to simultaneously enforce both the discrete GCL condition (\\ref{eq:dgcl}) and Assumption~\\ref{ass:norm} using this approach.\n\\end{remark}\n\n\n\\section{Numerical experiments}\n\\label{sec:num}\n\nIn this section, we present numerical results which verify the theoretical results in this work.  We first verify that the weight-adjusted $L^2$ projection $\\tilde{\\Pi}^k_N$ and the GCL-satisfying geometric factors $G^k_{ij}$ obey the error estimates in Theorem~\\ref{thm:superconverge} and Theorem~\\ref{thm:koprivagcl}.  \n\nNext, we verify the semi-discrete entropy conservation, primary conservation, and accuracy of the proposed high order accurate methods for the compressible Euler equations on curved meshes in two and three dimensions.  For all curved meshes, we utilize the low storage weight-adjusted formulation (\\ref{eq:dgform2}).  \n\nIn choosing the timestep $dt$, we follow \\cite{chan2015gpu} and set \n\\begin{equation}\ndt = \\min_{k} {\\rm CFL} \\frac{\\nor{J}_{L^{\\infty}\\LRp{D^k}}}{C_N\\nor{J^f}_{L^{\\infty}\\LRp{\\partial D^k}}},\n\\end{equation}\nwhere $C_N$ is the $O(N^2)$ order-dependent constant in the surface trace inequality \\cite{chan2015gpu} and ${\\rm CFL}$ is a user-chosen constant.  All numerical experiments in this work utilize the five-stage fourth order low storage Runge--Kutta (LSRK-45) time-stepper \\cite{carpenter1994fourth}.  \n\n\n\\subsection{Accuracy of weight-adjusted projection and geometric terms}\n\nIn this section, we verify Theorems~\\ref{thm:superconverge} and \\ref{thm:koprivagcl} concerning the accuracy of the weight-adjusted projection and modified construction of geometric terms satisfying the discrete geometric conservation law.  Figure~\\ref{fig:superconverge} shows $L^2$ errors for both the standard $L^2$ projection (\\ref{eq:l2curv}) and the weight-adjusted projection (\\ref{eq:wadgproj}) for a series of warped meshes of degree $N = 4$.  Errors are estimated using degree $2N+1$ quadratures for triangles and tetrahedra \\cite{xiao2010quadrature}.  We compute $L^2$ errors for both smooth and discontinuous functions\n\\[\nf(\\bm{x}) = e^{x_1+x_2}\\sin\\LRp{{\\pi x_1}}\\sin\\LRp{{\\pi x_2}}, \\qquad g(\\bm{x}) = f(\\bm{x}) + H(x_1+x_2-\\sin(\\pi x_1)),\n\\]\nwhere $H$ is the Heaviside function.  For the smooth function $f(\\bm{x})$, we observe that the difference between the $L^2$ and weight-adjusted projections indeed converges at a rate of $O\\LRp{h^{N+2}}$ as predicted by Theorem~\\ref{fig:superconverge}, such that the $L^2$ errors for each projection appear identical.  The $L^2$ errors for the $L^2$ and weight-adjusted projections of the discontinuous function $g(\\bm{x})$ are also virtually identical.  However, the difference beteween the $L^2$ and weight-adjusted projection converges faster than estimated by Theorem~\\ref{fig:superconverge}, with the $L^2$ error converging as $O(h^{1/2})$ and the difference converging as $O(h^{2+1/2})$. \n\n%, despite the fact that Theorem~\\ref{thm:superconverge} only holds for functions with sufficient regularity.  Moreover, the difference between the two projections appears to converge even more rapidly for the discontinuous function $g(\\bm{x})$, with the $L^2$ error converging as $O(h^{1/2})$ and the difference converging as $O(h^{2+1/2})$. \n\n\\begin{figure}\n\\centering\n\\subfloat[Warped curvilinear mesh]{\\includegraphics[width=.285\\textwidth]{figs/wadgCurved.png}}\n\\subfloat[$f(\\bm{x}) = e^{x_1+x_2}\\sin\\LRp{{\\pi x_1}}\\sin\\LRp{{\\pi x_2}}$]{\n\\begin{tikzpicture}\n\\begin{loglogaxis}[\n    legend cell align=left,\n    legend style={legend pos=south east, font=\\tiny},\n    width=.37\\textwidth,    \n    xlabel={Mesh size $h$},\n    ylabel={$L^2$ error}, \n     ymin=1e-11, ymax=1e-1,    \n    grid style=dashed,\n] \n\n\\addplot[color=blue,mark=*,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(0.5,0.0268241)(0.25,0.00198388)(0.125,7.29929e-05)(0.0625,2.43094e-06)(0.03125,7.71592e-08)};\n\\logLogSlopeTriangleFlip{0.3}{0.15}{0.48}{5}{blue}\n\\addplot[color=red,mark=x,dashed,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(0.5,0.0269391)(0.25,0.00197894)(0.125,7.29563e-05)(0.0625,2.43063e-06)(0.03125,7.71567e-08)};\n\\addplot[color=black,mark=triangle*,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(0.5,0.00237193)(0.25,5.41179e-05)(0.125,7.6934e-07)(0.0625,1.18362e-08)(0.03125,1.84801e-10)};\n\\logLogSlopeTriangleFlip{0.3}{0.15}{0.225}{6}{black}\n\n\\legend{$L^2$ projection,Weight-adjusted,Difference}\n%\\legend{Uniform, Optimal, Smoothed}\n\\end{loglogaxis}\n\\end{tikzpicture}\n}\n\\subfloat[$g(\\bm{x}) = f(\\bm{x}) + H(x_1+x_2-\\sin(\\pi x_1))$]{\n\\begin{tikzpicture}\n\\begin{loglogaxis}[\n    legend cell align=left,\n    legend style={legend pos=south east, font=\\tiny},\n    width=.37\\textwidth,\n    xlabel={Mesh size $h$},\n%     ymin=1e-7, ymax=1e1,\n%    ylabel={$L^2$ error}, \n    grid style=dashed,\n] \n\n\\addplot[color=blue,mark=*,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(0.5,0.323258)(0.25,0.227822)(0.125,0.160387)(0.0625,0.114753)(0.03125,0.0792918)};\n\\logLogSlopeTriangleFlip{0.4}{0.25}{0.875}{.5}{blue}\n\\addplot[color=red,mark=x,dashed,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(0.5,0.324117)(0.25,0.227927)(0.125,0.160411)(0.0625,0.114756)(0.03125,0.0792924)};\n\\addplot[color=black,mark=triangle*,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(0.5,0.00466574)(0.25,0.000804201)(0.125,0.000182886)(0.0625,2.96701e-05)(0.03125,5.01885e-06)};\n\\logLogSlopeTriangleFlip{0.3}{0.15}{0.18}{2.5}{black}\n\n%\\legend{$L^2$ projection,Weight-adjusted, Difference}\n%\\legend{Uniform, Optimal, Smoothed}\n\\end{loglogaxis}\n\\end{tikzpicture}\n}\n\\caption{$L^2$ errors in approximating both smooth and discontinuous functions using $L^2$ and weight-adjusted projections on a curved mesh.  The approximation order is $N=4$, and a degree $2N$ quadrature rule is used to compute integrals over the reference triangle. }\n\\label{fig:superconverge}\n\\end{figure}\n\nWe next compare the approximation of the geometric factors on a curved three-dimensional mesh.  We generate a sequence of quasi-uniform unstructured tetrahedral meshes using GMSH \\cite{geuzaine2009gmsh} and construct a curvilinear mesh from the distorted coordinates $\\tilde{\\bm{x}} = \\bm{x} + \\frac{1}{8}\\cos\\LRp{\\frac{\\pi}{2}x_1}\\cos\\LRp{\\frac{\\pi}{2}x_2}\\cos\\LRp{\\frac{\\pi}{2}x_3}$.\nWe then compute the $L^2$ error in approximating geometric terms for each element $D^k$ by computing $G^k_{ij}-\\tilde{G^k_{ij}}$ at quadrature points.  \n%\\[\n%\\sqrt{\\sum_{k}\\sum_{ij=1}^d \\nor{G^k_{ij} - \\tilde{G^k_{ij}}}^2_{L^2\\LRp{\\hat{D}}}}.  \n%\\]\nWe estimate the mesh size as $h = \\max_k \\nor{J^k/J^k_f}_{L^{\\infty}}$, since $J^k = O(h^d)$ and $J^k_f = O(h^{d-1})$ in $d$ dimensions \\cite{chan2015gpu}.  Figure~\\ref{fig:geomerr} shows errors for an $N=3$ and $N=4$ mesh.  We refer to the construction of approximate geometric terms $\\tilde{G^k_{ij}}$ introduced in \\cite{kopriva2006metric, hindenlang2012explicit} as ``Geo-$N$'', since the interpolation is performed using a degree $N$ interpolation operator.  We refer to the construction of $\\tilde{G^k_{ij}}$ in (\\ref{eq:iconscurl2}) and Theorem~\\ref{thm:koprivagcl} as ``Geo-$(N+1)$'', since the main interpolation step is performed on degree $(N+1)$ polynomials instead.  It can be observed that the Geo-N scheme converges at a rate of $O(h^{N+1})$, while the Geo-(N+1) scheme converges at a rate of $O(h^{N+2})$.  We note that the error in both the Geo-$N$ and Geo-$(N+1)$ approximations of $\\tilde{G^k_{ij}}$ converge at the same rate or faster than the best approximation error.  \n%\\note{Optimal rates are observed for $N=5$, geometry order 3 by Hindenlang, but this is be because $G^k_{ij} \\in Q^{2N_{\\rm geo}-2} = Q^4$, so it should not be necessary to enforce the GCL in that situation. Note sensitivity of nonlinear solvers to geometry error \\cite{toulorge2016optimizing}}.\n\n\\begin{figure}\n\\centering\n\\subfloat[$N=3$]{\n\\begin{tikzpicture}\n\\begin{loglogaxis}[\n    legend cell align=left,\n    legend style={legend pos=south east, font=\\tiny},\n    width=.45\\textwidth,    \n    xlabel={Mesh size $h$},\n    ylabel={$L^2$ error}, \n%     ymin=1e-10, ymax=1e-1,    \n    grid style=dashed,\n] \n\n\\addplot[color=blue,mark=*,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(0.67574,0.00231891)(0.374388,7.21634e-05)(0.16654,3.2502e-06)(0.0867431,1.31183e-07)};\n\\addplot[color=magenta,dashed,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(0.67574,0.00231891)(0.374388,0.000121059)(0.16654,2.10855e-06)(0.0867431,8.08278e-08)};\n\\addplot[color=red,mark=square*,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(0.67574,0.00635039)(0.374388,0.000542466)(0.16654,4.85003e-05)(0.0867431,4.03792e-06)};\n\\addplot[color=black,dashed,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(0.67574,0.00952559)(0.374388,0.000897556)(0.16654,3.51441e-05)(0.0867431,2.58651e-06)};\n\n%coordinates{(0.5,0.00237193)(0.25,5.41179e-05)(0.125,7.6934e-07)(0.0625,1.18362e-08)(0.03125,1.84801e-10)};\n%\\logLogSlopeTriangleFlip{0.3}{0.15}{0.225}{6}{black}\n\n\\legend{Geo-$(N+1)$, $h^{N+2}$, Geo-$N$, $h^{N+1}$}\n%\\legend{Uniform, Optimal, Smoothed}\n\\end{loglogaxis}\n\\end{tikzpicture}\n}\n\\subfloat[$N=4$]{\n\\begin{tikzpicture}\n\\begin{loglogaxis}[\n    legend cell align=left,\n    legend style={legend pos=south east, font=\\tiny},\n    width=.45\\textwidth,\n    xlabel={Mesh size $h$},\n%         ymin=1e-10, ymax=1e-1,    \n%     ymin=1e-7, ymax=1e1,\n%    ylabel={$L^2$ error}, \n    grid style=dashed,\n] \n\n\\addplot[color=blue,mark=*,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(0.673351,0.000766195)(0.373777,1.44835e-05)(0.166655,2.91207e-07)(0.0867501,5.69685e-09)};\n\\addplot[color=magenta,dashed,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(0.673351,0.000957743)(0.373777,2.80204e-05)(0.166655,2.20143e-07)(0.0867501,4.37946e-09)};\n\\addplot[color=red,mark=square*,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(0.673351,0.00231677)(0.373777,0.000127702)(0.166655,5.3742e-06)(0.0867501,2.11781e-07)};\n\\addplot[color=black,dashed,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(0.673351,0.00405434)(0.373777,0.000213685)(0.166655,3.7653e-06)(0.0867501,1.43901e-07)};\n\n%coordinates{(0.5,0.00237193)(0.25,5.41179e-05)(0.125,7.6934e-07)(0.0625,1.18362e-08)(0.03125,1.84801e-10)};\n%\\logLogSlopeTriangleFlip{0.3}{0.15}{0.225}{6}{black}\n\n\\legend{Geo-$(N+1)$, $h^{N+2}$, Geo-$N$, $h^{N+1}$}\n\\end{loglogaxis}\n\\end{tikzpicture}\n}\n\\caption{$L^2$ errors in the approximation of metric terms $G^k_{ij}$ with metric terms $\\tilde{G^k_{ij}}$ satisfying the discrete GCL condition (\\ref{eq:dgcl}) and Assumption~\\ref{ass:norm}.}\n\\label{fig:geomerr}\n\\end{figure}\n\n% N = 3\n\\subsection{Two-dimensional compressible Euler equations}\n\nThe compressible Euler equations in two dimensions are given as follows:\n\\begin{align}\n\\pd{\\rho}{t} + \\pd{\\LRp{\\rho u}}{x_1} + \\pd{\\LRp{\\rho v}}{x_2} &= 0,\\\\\n\\pd{\\rho u}{t} + \\pd{\\LRp{\\rho u^2 + p }}{x_1} + \\pd{\\LRp{\\rho uv}}{x_2} &= 0,\\nonumber\\\\\n\\pd{\\rho v}{t} + \\pd{\\LRp{\\rho uv}}{x_1} + \\pd{\\LRp{\\rho v^2 + p }}{x_2} &= 0,\\nonumber\\\\\n\\pd{E}{t} + \\pd{\\LRp{u(E+p)}}{x_1} + \\pd{\\LRp{v(E+p)}}{x_2}&= 0.\\nonumber\n\\end{align}\nIn two dimensions, the pressure is $p = (\\gamma-1)\\LRp{E - \\frac{1}{2}\\rho (u^2+v^2)}$, and the specific internal energy is $\\rho e = E - \\frac{1}{2}\\rho (u^2+v^2)$.  \n\nThe choice of convex entropy for the Euler equations is non-unique \\cite{harten1983symmetric}.  However, a unique entropy can be chosen by restricting to choices of entropy variables which symmetrize the viscous heat conduction term in the compressible Navier-Stokes equations \\cite{hughes1986new}.  This leads to $U(\\bm{u})$ of the form\n\\begin{equation}\nU(\\bm{u}) = -\\frac{\\rho s}{\\gamma-1},\n\\label{eq:entropy2d}\n\\end{equation}\nwhere $s = \\log\\LRp{\\frac{p}{\\rho^\\gamma}}$ is the physical specific entropy. The entropy variables in two dimensions are \n\\begin{align}\nv_1 = \\frac{\\rho e (\\gamma + 1 - s) - E}{\\rho e}, \\qquad v_2 = \\frac{\\rho u}{\\rho e}, \\qquad v_3 = \\frac{\\rho v}{\\rho e}, \\qquad v_4 = -\\frac{\\rho}{\\rho e}.\n\\end{align}\nThe conservation variables in terms of the entropy variables are given by\n\\begin{equation}\n\\rho = -(\\rho e) v_4, \\qquad \\rho u = (\\rho e) v_2, \\qquad \\rho v = (\\rho e) v_3, \\qquad E = (\\rho e)\\LRp{1 - \\frac{{v_2^2+v_3^2}}{2 v_4}},\n\\end{equation}\nwhere $\\rho e$ and $s$ in terms of the entropy variables are \n\\begin{equation}\n\\rho e = \\LRp{\\frac{(\\gamma-1)}{\\LRp{-v_4}^{\\gamma}}}^{1/(\\gamma-1)}e^{\\frac{-s}{\\gamma-1}}, \\qquad s = \\gamma - v_1 + \\frac{{v_2^2+v_3^2}}{2v_4}.\n\\end{equation}\nThe entropy conservative numerical fluxes for the two-dimensional compressible Euler equations are given by Chandrashekar \\cite{chandrashekar2013kinetic}\n\\begin{align}\n&f^1_{1,S}(\\bm{u}_L,\\bm{u}_R) = \\avg{\\rho}^{\\log} \\avg{u},& &f^1_{2,S}(\\bm{u}_L,\\bm{u}_R) = \\avg{\\rho}^{\\log} \\avg{v},&\\\\\n&f^2_{1,S}(\\bm{u}_L,\\bm{u}_R) = f^1_{1,S} \\avg{u} + p_{\\rm avg},&  &f^2_{2,S}(\\bm{u}_L,\\bm{u}_R) = f^1_{2,S} \\avg{u},&\\nonumber\\\\\n&f^3_{1,S}(\\bm{u}_L,\\bm{u}_R) = f^2_{2,S},& &f^3_{2,S}(\\bm{u}_L,\\bm{u}_R) = f^1_{2,S} \\avg{v} + p_{\\rm avg},&\\nonumber\\\\\n&f^4_{1,S}(\\bm{u}_L,\\bm{u}_R) = \\LRp{E_{\\rm avg} + p_{\\rm avg}}\\avg{u},& &f^4_{2,S}(\\bm{u}_L,\\bm{u}_R) = \\LRp{E_{\\rm avg} + p_{\\rm avg} }\\avg{v},& \\nonumber\n\\end{align}\nwhere we have defined the auxiliary quantities \n\\begin{gather}\np_{\\rm avg} = \\frac{\\avg{\\rho}}{2\\avg{\\beta}}, \\qquad E_{\\rm avg} = \\frac{\\avg{\\rho}^{\\log}}{2\\avg{\\beta}^{\\log}\\LRp{\\gamma -1}}   + \\frac{\\nor{\\bm{u}}^2_{\\rm avg}}{2}, \\\\\n \\nor{\\bm{u}}^2_{\\rm avg} = 2(\\avg{u}^2 + \\avg{v}^2) - \\LRp{\\avg{u^2} +\\avg{v^2}} \\nonumber.  \n\\end{gather}\n\n\\subsubsection{Entropy conservation}\n\nWe begin by testing the propagation of a shock on a two-dimensional curved mesh using a discontinuous profile on the domain $\\Omega = [0,20] \\times [-5,5]$.   We set the initial velocities to be zero, and initialize the density and pressure as a discontinuous square pulse as in \\cite{chan2017discretely}\n\\begin{equation}\n\\rho(\\bm{x},t) = \\begin{cases}\n3 & \\LRb{x_1} < 1/2 \\text{ and } \\LRb{x_2} < 1/2\\\\\n2 & \\text{otherwise},\n\\end{cases} \\qquad \nu(\\bm{x},t) = v(\\bm{x},t) = 0, \\qquad\np(\\bm{x},t) = \\rho^\\gamma.\n\\label{eq:discontin}\n\\end{equation}\nTo test the scheme (\\ref{eq:dgform2}), we utilize an entropy conservative flux and run it on a uniform triangular mesh with a curvilinear warping shown in Figure~\\ref{fig:warp2d}.   Theorem~\\ref{thm:stab2} ensures that, under an entropy conservative flux, (\\ref{eq:dgform2}) is semi-discretely entropy conservative.  This does not hold at the fully discrete level; however, it is possible to verify that (\\ref{eq:dgform2}) is entropy stable using other approaches.  \n\nFirst, can examine the entropy RHS, which we define as the right hand side of (\\ref{eq:dgform2}) tested with $\\bm{v}_h$ \n\\begin{equation}\n  \\text{entropy RHS}= -\\sum_{j=1}^d\\LRp{ \\tilde{\\bm{v}}^T\\LRp{2\\bm{Q}^j_k \\circ \\bm{F}_{j,S}}\\bm{1} + \\tilde{\\bm{v}}_f^T\\bm{W}_f^k \\diag{\\bm{n}_j}\\LRp{\\bm{f}_j^* - \\bm{f}_j(\\tilde{\\bm{u}}_f)}}.  \n\\label{eq:entropyrhs}\n\\end{equation}\n%\\lcwnote{I put a 2 in the previous equation to match \\eqref{eq:dgform2weak}.  Do we also want minus signs since these terms are moved to the RHS?}  JC: thanks!  sure - added a zero, though the term should be zero so the sign shouldn't matter\nFor positive density and pressure, (\\ref{eq:entropyrhs}) should be zero to machine precision.  We can also track the change in entropy $\\Delta U = \\LRb{U(\\bm{u}(\\bm{x},t))-U(\\bm{u}(\\bm{x},0))}$, which should converge to $0$ as the timestep $dt$ approaches zero.  Furthermore, the rate of convergence should match the order of the time-stepper used \\cite{gassner2016well, chan2017discretely}.  \n\n\\begin{figure}\n\\centering\n\\subfloat[Uniform mesh]{\\includegraphics[width=.35\\textwidth]{figs/vortexMeshUniform.png}}\n\\hspace{1em}\n\\subfloat[Warped mesh]{\\includegraphics[width=.35\\textwidth]{figs/vortexMeshCurved.png}}\n\\caption{2D curved meshes used for testing entropy conservation and primary conservation.}\n\\label{fig:warp2d}\n\\end{figure}\n\nFigure~\\ref{fig:dSconverge} shows the evolution of entropy $U(\\bm{u})$ over time $[0,T]$, where the final time $T = 2$.  We compare when the entropy-projected conservative variables $\\tilde{\\bm{u}}$ are computed using the standard $L^2$ projection on the reference element, and when $\\tilde{\\bm{u}}$ are computed using the weight-adjusted projection.  For the standard $L^2$ projection, the change in entropy does not decrease as $dt$ decreases (for a fixed mesh and order $N$).  When $\\tilde{\\bm{u}}$ is defined using the weight-adjusted projection, the entropy decreases as $dt$ decreases.  Moreover, the rate of convergence is approximately $O(dt^{4.675})$, which is slightly higher than the expected rate of $O(dt^4)$ when using LSRK-45.  Regardless of whether the standard and weight-adjusted projection was used, the entropy RHS (\\ref{eq:entropyrhs}) is $O(10^{-14})$, indicating that the proposed scheme is implemented correctly.  \n\n\\begin{figure}\n\\centering\n\\subfloat[With weight-adjusted projection]{\n\\begin{tikzpicture}\n\\begin{semilogyaxis}[\n    legend cell align=left,\n    legend style={legend pos=south east, font=\\tiny},\n    width=.45\\textwidth,    \n    xlabel={Time $t$},\n    ylabel={Change in entropy $\\Delta U(\\bm{u})$}, \n     ymin=1e-9, ymax=5e-4,    \n    grid style=dashed,\n] \n\n\\addplot[color=blue,mark=*,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(0.025641,0)(0.128205,1.81455e-05)(0.230769,1.84993e-05)(0.333333,1.81016e-05)(0.435897,2.38212e-05)(0.538462,3.43804e-05)(0.641026,3.75077e-05)(0.74359,3.80509e-05)(0.846154,4.02406e-05)(0.948718,4.57864e-05)(1.05128,5.21023e-05)(1.15385,5.52339e-05)(1.25641,5.93653e-05)(1.35897,6.53204e-05)(1.46154,7.10508e-05)(1.5641,7.58692e-05)(1.66667,8.21148e-05)(1.76923,8.86933e-05)(1.87179,9.52306e-05)(1.97436,0.000102832)};\n%\\addplot[color=blue,dashed,semithick, mark options={solid,fill=markercolor}]\n%coordinates{(0.025641,9.95731e-16)(0.128205,4.11303e-15)(0.230769,1.09496e-14)(0.333333,1.86934e-14)(0.435897,1.8624e-14)(0.538462,4.82253e-14)(0.641026,2.80886e-14)(0.74359,3.34073e-14)(0.846154,3.41116e-14)(0.948718,1.12826e-14)(1.05128,1.02106e-14)(1.15385,7.27543e-15)(1.25641,3.21965e-15)(1.35897,2.70617e-15)(1.46154,2.28116e-15)(1.5641,1.01134e-14)(1.66667,9.05179e-15)(1.76923,8.96852e-15)(1.87179,2.69368e-14)(1.97436,1.20043e-15)};\n\\addplot[color=red,mark=square*,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(0.0129032,0)(0.116129,9.54018e-07)(0.219355,8.64409e-07)(0.322581,7.28292e-07)(0.425806,1.00547e-06)(0.529032,1.54507e-06)(0.632258,1.58376e-06)(0.735484,1.48926e-06)(0.83871,1.52599e-06)(0.941935,1.77263e-06)(1.04516,2.04306e-06)(1.14839,2.10785e-06)(1.25161,2.25231e-06)(1.35484,2.49471e-06)(1.45806,2.7075e-06)(1.56129,2.86391e-06)(1.66452,3.11015e-06)(1.76774,3.35711e-06)(1.87097,3.6045e-06)(1.97419,3.88568e-06)};\n%\\addplot[color=red,dotted,semithick, mark options={solid,fill=markercolor}]\n%coordinates{(0.0129032,1.00787e-15)(0.116129,2.48065e-16)(0.219355,8.43769e-15)(0.322581,1.07483e-14)(0.425806,6.18255e-15)(0.529032,4.95159e-14)(0.632258,1.19835e-14)(0.735484,3.68837e-14)(0.83871,2.35957e-14)(0.941935,1.19904e-14)(1.04516,1.73785e-14)(1.14839,7.88952e-15)(1.25161,2.44249e-14)(1.35484,6.38031e-15)(1.45806,1.78781e-14)(1.56129,5.72459e-16)(1.66452,4.02456e-15)(1.76774,1.7316e-14)(1.87097,2.50425e-14)(1.97419,3.55375e-14)};\n\\addplot[color=black,mark=pentagon*,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(0.00647249,0)(0.110032,5.38994e-08)(0.213592,4.43651e-08)(0.317152,3.18878e-08)(0.420712,4.65967e-08)(0.524272,7.64772e-08)(0.627832,7.36288e-08)(0.731392,6.33475e-08)(0.834951,6.22881e-08)(0.938511,7.43794e-08)(1.04207,8.71374e-08)(1.14563,8.67872e-08)(1.24919,9.19998e-08)(1.35275,1.02781e-07)(1.45631,1.11204e-07)(1.55987,1.16121e-07)(1.66343,1.26634e-07)(1.76699,1.36562e-07)(1.87055,1.46567e-07)(1.97411,1.57581e-07)};\n%\\addplot[color=black,dashdotted,semithick, mark options={solid,fill=markercolor}]\n%coordinates{(0.00647249,2.19226e-16)(0.110032,5.88071e-15)(0.213592,1.34059e-14)(0.317152,2.30337e-14)(0.420712,8.23647e-15)(0.524272,2.68709e-14)(0.627832,2.53304e-14)(0.731392,2.95527e-14)(0.834951,2.5948e-14)(0.938511,4.56579e-15)(1.04207,2.28428e-14)(1.14563,8.22259e-15)(1.24919,1.51094e-14)(1.35275,7.86871e-15)(1.45631,1.11508e-14)(1.55987,1.57721e-14)(1.66343,6.95624e-15)(1.76699,2.07681e-14)(1.87055,2.72421e-14)(1.97411,1.7028e-14)};\n\n% % N = 4, K= 8, dt = .25\n % N = 4, K= 8, dt = .125\n % N = 4, K= 8, dt = .0625\n\n\\legend{${\\rm CFL} = .25$,${\\rm CFL} = .125$,${\\rm CFL} = .0625$ }\n%\\legend{Uniform, Optimal, Smoothed}\n\\end{semilogyaxis}\n\\end{tikzpicture}\n}\n\\subfloat[Without weight-adjusted projection]{\n\\begin{tikzpicture}\n\\begin{semilogyaxis}[\n    legend cell align=left,\n    legend style={legend pos=south east, font=\\tiny},\n    width=.45\\textwidth,\n    xlabel={Time $t$},\n%         ymin=1e-10, ymax=1e-1,    \n%     ymin=1e-7, ymax=1e1,\n     ymin=1e-9, ymax=5e-4,    \n%    ylabel={$L^2$ error}, \n    grid style=dashed,\n] \n\n\\addplot[color=blue,mark=*,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(0.025641,0)(0.128205,4.45681e-05)(0.230769,6.82313e-05)(0.333333,0.000131517)(0.435897,0.000108761)(0.538462,8.51562e-05)(0.641026,2.94791e-05)(0.74359,3.62904e-05)(0.846154,2.97564e-05)(0.948718,9.87886e-05)(1.05128,0.000136806)(1.15385,7.64601e-05)(1.25641,0.000111044)(1.35897,5.72761e-05)(1.46154,4.27e-05)(1.5641,5.03819e-05)(1.66667,4.99789e-05)(1.76923,5.07438e-05)(1.87179,4.26361e-05)(1.97436,2.48694e-05)};\n%\\addplot[color=blue,dashed,semithick, mark options={solid,fill=markercolor}]\n%coordinates{(0.025641,5.11743e-16)(0.128205,1.16547e-14)(0.230769,7.91034e-15)(0.333333,1.28231e-14)(0.435897,4.79131e-15)(0.538462,3.44134e-14)(0.641026,6.92502e-15)(0.74359,2.28047e-14)(0.846154,2.15314e-14)(0.948718,4.36456e-15)(1.05128,2.09416e-14)(1.15385,4.86763e-15)(1.25641,3.59088e-15)(1.35897,3.43475e-16)(1.46154,1.03632e-14)(1.5641,1.03598e-14)(1.66667,1.83881e-16)(1.76923,5.94663e-15)(1.87179,3.18252e-14)(1.97436,1.88495e-14)};\n\\addplot[color=red,mark=square*,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(0.0129032,0)(0.116129,6.48664e-05)(0.219355,8.24474e-05)(0.322581,0.000152373)(0.425806,0.000138342)(0.529032,0.000126709)(0.632258,1.85501e-05)(0.735484,6.98555e-05)(0.83871,7.53129e-05)(0.941935,0.00013915)(1.04516,0.000196476)(1.14839,0.000133645)(1.25161,0.000173751)(1.35484,0.000126668)(1.45806,0.000116008)(1.56129,0.000127919)(1.66452,0.0001343)(1.76774,0.000140992)(1.87097,0.00013971)(1.97419,0.0001291)};\n%\\addplot[color=red,dotted,semithick, mark options={solid,fill=markercolor}]\n%coordinates{(0.0129032,3.00107e-16)(0.116129,6.93196e-15)(0.219355,1.00198e-14)(0.322581,7.79932e-15)(0.425806,2.48759e-15)(0.529032,3.46181e-14)(0.632258,1.7205e-14)(0.735484,2.30718e-14)(0.83871,3.0146e-14)(0.941935,9.4369e-15)(1.04516,1.07969e-14)(1.14839,5.59275e-15)(1.25161,5.34295e-15)(1.35484,5.7801e-15)(1.45806,8.74648e-15)(1.56129,1.24137e-14)(1.66452,2.95597e-15)(1.76774,2.64441e-14)(1.87097,2.58023e-14)(1.97419,6.984e-15)};\n\\addplot[color=black,mark=pentagon*,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(0.00647249,0)(0.110032,6.52844e-05)(0.213592,8.08628e-05)(0.317152,0.000153077)(0.420712,0.000141625)(0.524272,0.000130883)(0.627832,2.58046e-05)(0.731392,6.81127e-05)(0.834951,7.92926e-05)(0.938511,0.000137768)(1.04207,0.000201777)(1.14563,0.000136705)(1.24919,0.000177364)(1.35275,0.000131153)(1.45631,0.000119851)(1.55987,0.000131686)(1.66343,0.000138676)(1.76699,0.00014539)(1.87055,0.000144608)(1.97411,0.000134142)};\n%\\addplot[color=black,dashdotted,semithick, mark options={solid,fill=markercolor}]\n%coordinates{(0.00647249,7.31403e-16)(0.110032,1.05055e-14)(0.213592,2.58127e-15)(0.317152,1.04916e-14)(0.420712,5.12437e-15)(0.524272,4.40203e-14)(0.627832,1.147e-14)(0.731392,2.81025e-14)(0.834951,3.01946e-14)(0.938511,4.51028e-15)(1.04207,1.096e-14)(1.14563,6.11317e-15)(1.24919,3.69843e-15)(1.35275,6.47399e-15)(1.45631,9.41608e-15)(1.55987,1.58901e-15)(1.66343,6.39766e-15)(1.76699,1.56819e-14)(1.87055,2.11949e-14)(1.97411,1.12063e-14)};\n\n%\\legend{Geo-$(N+1)$, $h^{N+2}$, Geo-$N$, $h^{N+1}$}\n\\legend{${\\rm CFL} = .25$,${\\rm CFL} = .125$,${\\rm CFL} = .0625$ }\n\\end{semilogyaxis}\n\\end{tikzpicture}\n}\n\\caption{Change in entropy under an entropy conservative formulation with $N=4$.  In both cases, the magnitude of the entropy RHS (\\ref{eq:entropyrhs}) is $O\\LRp{10^{-14}}$. }\n\\label{fig:dSconverge}\n\\end{figure}\n\nThese results suggest that the weight-adjusted projection is necessary to produce an entropy conservative scheme on curvilinear meshes.  However, entropy conservative schemes result in spurious oscillations and lower convergence rates \\cite{chan2017discretely}.  In practice, dissipative interface terms are added to produce entropy stable schemes.  In the presence of interface dissipation, the evolution of entropy over time, $L^2$ errors for smooth solutions, and the qualitative behavior of the solution are very similar with or without the weight-adjusted projection.  This may reflect the fact that aliasing-driven instabilities arise from the spatial discretization, and the entropy RHS (\\ref{eq:entropyrhs}) is machine precision zero with or without the weight-adjusted projection.  In contrast,  the presence of the weight-adjusted projection affects only the time-derivative on the left-hand side, and may not play as large a role in suppressing aliasing instabilities.  \n\n\n\\subsubsection{Local and global conservation}\n\\label{sec:conservationcheck}\nNext, we check that primary conservation is maintained numerically on curved meshes.  We follow \\cite{friedrich2017entropy} and examine the semi-discrete evolution of the average of $\\bm{u}$ over the domain $\\Omega$\n\\begin{align}\n  \\pd{}{t}\\int_{\\Omega} \\bm{u} \\diff{\\bm{x}} = \\sum_k \\int_{D^k} \\pd{\\bm{u}}{t} \\diff{\\bm{x}} = \\sum_k \\int_{\\hat{D}} \\pd{\\bm{u}}{t} J^k \\diff{\\hat{\\bm{x}}} = \\sum_k \\bm{1}^T \\bm{W}\\diag{\\bm{J}^k} \\bm{V}_q \\td{\\bm{u}_h}{t}.  \n\\label{eq:conssemidiscrete}\n\\end{align}\nThe quantity (\\ref{eq:conssemidiscrete}) is computed using quadrature by multiplying the semi-discrete system (\\ref{eq:dgform2}) by $\\bm{1}^T\\bm{W}\\diag{\\bm{J}^k} \\bm{V}_q$\n\\begin{align}\n&\\sum_k \\bm{1}^T \\bm{W}\\diag{\\bm{J}^k} \\bm{V}_q \\td{\\bm{u}_h}{t}= \\nonumber\\\\\n& \\underbrace{\\bm{1}^T\\bm{W}\\diag{\\bm{J}^k}\\bm{V}_q\\LRp{\n \\LRs{\\begin{array}{cc}\\tilde{\\bm{P}}^k_q & \\tilde{\\bm{L}}^k_q\\end{array}} \\sum_{j=1}^d \\LRp{2\\bm{D}^j_k \\circ \\bm{F}_{j,S}}\\bm{1} + \\sum_{j=1}^d \\tilde{\\bm{L}}^k_q \\diag{\\bm{n}_j}\\LRp{\\bm{f}_j^* - \\bm{f}_j(\\tilde{\\bm{u}}_f)}}}_{\\text{conservation residual}}.\n \\label{eq:consres}\n\\end{align}\n\nWe consider three different cases:\n\\begin{enumerate}\n\\item \\textbf{Unmodified:} the weight-adjusted DG scheme (\\ref{eq:dgform2}) is used without any special modifications,\n\\item \\textbf{Polynomial approximation:} the weight-adjusted DG scheme (\\ref{eq:dgform2}) utilizes the $L^2$ projection of $J^k$ onto $P^N(\\hat{D})$ in the weight-adjusted mass matrix (such that Lemma~\\ref{eq:conscorrect1} holds), \n\\item \\textbf{Conservative correction:} the conservation correction (\\ref{eq:conscorrect}) is applied to the right hand side of the scheme (\\ref{eq:dgform2}).  \n\\end{enumerate}\nAll results use a Lax-Friedrichs flux, a CFL of $1/2$, $N=4$, and the curved mesh warping shown in Figure~\\ref{fig:warp2d}.  We use volume quadrature rules from \\cite{xiao2010quadrature} which are exact for degree $2N+1$ polynomials, and use $(N+1)$-node 1D Gauss--Legendre quadrature rules on the faces.  \n\nFigure~\\ref{subfig:cons1} shows computed conservation residuals from (\\ref{eq:consres}) on the curved mesh in Figure~\\ref{fig:warp2d} for the discontinuous pulse initial condition (\\ref{eq:discontin}).  The conservation residual oscillates around $O(10^{-6})$ for the unmodified scheme (\\ref{eq:dgform2}).  Modifying the scheme using either the ``Polynomial approximation'' or ``Conservative correction'' approaches reduces the conservation error to $O(10^{-12})$.  %The magnitude of the conservation residual is due to roundoff effects.  Repeating the same experiments on a smaller mesh of $8\\times 8$ curved elements reduces the conservation residual to $O(10^{-13})$, while using a larger mesh of $32\\times 32$ curved elements results in a conservation residual of $O(10^{-11})$.  \nWe have also studied the accuracy of each case in by comparing $L^2$ errors on a curved mesh for a smooth vortex solution  at time $T=5$.  We observe that in all cases, the $L^2$ errors are virtually identical.  For $N=4$ on an $8\\times 8$ mesh, the $L^2$ errors for each case differ only in the 5th digit, while for the $16\\times 16$ and $32\\times 32$ meshes, they differ only in the 8th digit.  This confirms that both approaches outlined in Section~\\ref{sec:conservation} restore primary conservation with no perceivable effect on accuracy.  \n\n%\\note{finish}\n\n\\begin{figure}\n\\centering\n\\subfloat[ Conservation residual over time (unmodified)]{\n\\begin{tikzpicture}\n\\begin{semilogyaxis}[\n    legend cell align=left,\n    legend style={legend pos=north east, font=\\tiny},\n    width=.45\\textwidth,    \n    xlabel={Time},\n    ylabel={Conservation residual}, \n    ymin=1e-8, ymax=1e-5,    \n    grid style=dashed,\n%    ytick={1e-12,1e-10,1e-8,1e-6,1e-4,1e-2 }\n] \n\n\\addplot[color=blue,mark=*,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(0.00642674,9.9266e-07)(0.404884,4.12992e-07)(0.803342,5.14326e-07)(1.2018,1.86091e-07)(1.60026,1.48526e-07)(1.99871,2.64763e-07)(2.39717,5.64483e-07)(2.79563,2.71857e-07)(3.19409,2.62073e-07)(3.59254,2.40249e-07)(3.991,2.80807e-07)(4.38946,3.23725e-07)(4.78792,3.9606e-07)(5.18638,3.46717e-07)(5.58483,2.17698e-07)(5.98329,1.99781e-07)(6.38175,9.91165e-08)(6.78021,2.63862e-07)(7.17866,3.13545e-07)(7.57712,4.01892e-07)(7.97558,2.37462e-07)(8.37404,3.91475e-07)(8.77249,7.92905e-07)(9.17095,2.75479e-07)(9.56941,4.42523e-07)(9.96787,6.28215e-07)};\n\n%\\addplot[color=red,mark=x,dashed,semithick, mark options={solid,fill=markercolor}]\n%coordinates{(0.00642674,3.34034e-12)(0.404884,3.31953e-12)(0.803342,3.47682e-12)(1.2018,3.48782e-12)(1.60026,3.69874e-12)(1.99871,3.55961e-12)(2.39717,3.69915e-12)(2.79563,3.67725e-12)(3.19409,3.84246e-12)(3.59254,3.84801e-12)(3.991,3.9449e-12)(4.38946,3.95075e-12)(4.78792,4.05986e-12)(5.18638,4.07415e-12)(5.58483,4.18282e-12)(5.98329,4.34447e-12)(6.38175,4.3659e-12)(6.78021,4.34614e-12)(7.17866,4.46538e-12)(7.57712,4.37571e-12)(7.97558,4.35258e-12)(8.37404,4.16896e-12)(8.77249,4.22267e-12)(9.17095,4.14187e-12)(9.56941,4.10735e-12)(9.96787,3.90628e-12)};\n%\n%\\addplot[color=black,mark=triangle*,semithick, mark options={solid,fill=markercolor}]\n%coordinates{(0.00642674,3.28579e-12)(0.404884,3.32419e-12)(0.803342,3.37232e-12)(1.2018,3.50534e-12)(1.60026,3.64225e-12)(1.99871,3.47872e-12)(2.39717,3.62415e-12)(2.79563,3.68648e-12)(3.19409,3.79388e-12)(3.59254,3.84432e-12)(3.991,3.97812e-12)(4.38946,3.96804e-12)(4.78792,4.0684e-12)(5.18638,4.04986e-12)(5.58483,4.22413e-12)(5.98329,4.25356e-12)(6.38175,4.39801e-12)(6.78021,4.37474e-12)(7.17866,4.39737e-12)(7.57712,4.38242e-12)(7.97558,4.31792e-12)(8.37404,4.28398e-12)(8.77249,4.21688e-12)(9.17095,4.10925e-12)(9.56941,4.17163e-12)(9.96787,3.96996e-12)};\n\\legend{Unmodified}\n%\\legend{Unmodified, Polynomial approx., Conservative correction }\n%\\legend{Uniform, Optimal, Smoothed}\n\\end{semilogyaxis}\n\\end{tikzpicture}\n\\label{subfig:cons1}}\n\\subfloat[Conservation residual over time (modified)]{\n\\begin{tikzpicture}\n\\begin{semilogyaxis}[\n    legend cell align=left,\n    legend style={legend pos=north east, font=\\tiny},\n    width=.45\\textwidth,    \n    xlabel={Time},\n    ylabel={Conservation residual}, \n    ymin=.5e-12, ymax=2e-11,    \n    grid style=dashed,\n    ytick={1e-12, 1e-11},\n    yticklabels={{$ 10^{-12}$},{$ 10^{-11}$}}\n] \n\n%\\addplot[color=blue,mark=*,semithick, mark options={solid,fill=markercolor}]\n%coordinates{(0.00642674,9.9266e-07)(0.404884,4.12992e-07)(0.803342,5.14326e-07)(1.2018,1.86091e-07)(1.60026,1.48526e-07)(1.99871,2.64763e-07)(2.39717,5.64483e-07)(2.79563,2.71857e-07)(3.19409,2.62073e-07)(3.59254,2.40249e-07)(3.991,2.80807e-07)(4.38946,3.23725e-07)(4.78792,3.9606e-07)(5.18638,3.46717e-07)(5.58483,2.17698e-07)(5.98329,1.99781e-07)(6.38175,9.91165e-08)(6.78021,2.63862e-07)(7.17866,3.13545e-07)(7.57712,4.01892e-07)(7.97558,2.37462e-07)(8.37404,3.91475e-07)(8.77249,7.92905e-07)(9.17095,2.75479e-07)(9.56941,4.42523e-07)(9.96787,6.28215e-07)};\n\n\\addplot[color=red,mark=x,dashed,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(0.00642674,3.34034e-12)(0.404884,3.31953e-12)(0.803342,3.47682e-12)(1.2018,3.48782e-12)(1.60026,3.69874e-12)(1.99871,3.55961e-12)(2.39717,3.69915e-12)(2.79563,3.67725e-12)(3.19409,3.84246e-12)(3.59254,3.84801e-12)(3.991,3.9449e-12)(4.38946,3.95075e-12)(4.78792,4.05986e-12)(5.18638,4.07415e-12)(5.58483,4.18282e-12)(5.98329,4.34447e-12)(6.38175,4.3659e-12)(6.78021,4.34614e-12)(7.17866,4.46538e-12)(7.57712,4.37571e-12)(7.97558,4.35258e-12)(8.37404,4.16896e-12)(8.77249,4.22267e-12)(9.17095,4.14187e-12)(9.56941,4.10735e-12)(9.96787,3.90628e-12)};\n\n\\addplot[color=black,mark=triangle*,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(0.00642674,3.28579e-12)(0.404884,3.32419e-12)(0.803342,3.37232e-12)(1.2018,3.50534e-12)(1.60026,3.64225e-12)(1.99871,3.47872e-12)(2.39717,3.62415e-12)(2.79563,3.68648e-12)(3.19409,3.79388e-12)(3.59254,3.84432e-12)(3.991,3.97812e-12)(4.38946,3.96804e-12)(4.78792,4.0684e-12)(5.18638,4.04986e-12)(5.58483,4.22413e-12)(5.98329,4.25356e-12)(6.38175,4.39801e-12)(6.78021,4.37474e-12)(7.17866,4.39737e-12)(7.57712,4.38242e-12)(7.97558,4.31792e-12)(8.37404,4.28398e-12)(8.77249,4.21688e-12)(9.17095,4.10925e-12)(9.56941,4.17163e-12)(9.96787,3.96996e-12)};\n\\legend{Polynomial approx., Conservative correction }\n%\\legend{Unmodified, Polynomial approx., Conservative correction }\n%\\legend{Uniform, Optimal, Smoothed}\n\\end{semilogyaxis}\n\\end{tikzpicture}\n\\label{subfig:cons2}}\n%\\subfloat[$L^2$ errors at time $T=5$]{\n%\\begin{tikzpicture}\n%\\begin{loglogaxis}[\n%    legend cell align=left,\n%    legend style={legend pos=south east, font=\\tiny},\n%    width=.4\\textwidth,    \n%    xlabel={Time},\n%    ylabel={Conservation residual}, \n%    ymin=1e-2, ymax=2,    \n%    grid style=dashed,\n%    ytick={1e-13,1e-11,1e-9,1e-7,1e-5,1e-3,1e-1 }\n%] \n%\n%\\addplot[color=blue,mark=*,semithick, mark options={solid,fill=markercolor}]\n%% 1.315466363259058   0.263564848187665   0.018309692309614\n%coordinates{(1.25,1.315466)(0.625,0.263565)(0.3125,0.0183097)};\n%\n%\\addplot[color=red,mark=x,dashed,semithick, mark options={solid,fill=markercolor}]\n%%1.315440699275237   0.263564850056684   0.018309677771005\n%coordinates{(1.25,1.31544)(0.625,0.263565)(0.3125,0.0183097)};\n%\n%\\addplot[color=black,mark=triangle*,semithick, mark options={solid,fill=markercolor}]\n%% 1.315467094406914\n%coordinates{(1.25,1.315467)(0.625,0.263565)(0.3125,0.0183097)};\n%\n%\\legend{Unmodified, Polynomial approx., Conservative correction }\n%\n%\\end{loglogaxis}\n%\\end{tikzpicture}\n%\\label{subfig:cons2}}\n%\\caption{Conservation residuals for a discontinuous solution and $L^2$ errors for a vortex solution using the unmodified WADG formulation (\\ref{eq:dgform2}) and two different techniques for restoring local conservation.  Both experiments use a Lax-Friedrichs flux, a CFL of $1/2$, $N=4$, and the curved mesh warping shown in Figure~\\ref{fig:warp2d}.  }\n\\caption{Conservation residuals for a discontinuous initial condition using the unmodified WADG formulation (\\ref{eq:dgform2}) and two different techniques for restoring local conservation.  Both experiments use a Lax-Friedrichs flux, a CFL of $1/2$, $N=4$, and the curved mesh warping shown in Figure~\\ref{fig:warp2d}.  }\n\\label{fig:cons}\n\\end{figure}\n\n\n\\subsubsection{Accuracy and convergence}\n\n\\begin{figure}\n\\centering\n\\subfloat[Affine mesh]{\\includegraphics[width=.4\\textwidth]{figs/mesh2d_affine_converge2.png}}\n\\hspace{2em}\n\\subfloat[Curved mesh]{\\includegraphics[width=.4\\textwidth]{figs/mesh2d_curved_converge2.png}}\n\\caption{Example of affine and warped meshes (corresponding to $h = 1$) used in convergence studies.}\n\\label{fig:warp2dconverge}\n\\end{figure}\n\nFinally, we test the accuracy of the proposed schemes for smooth solutions on curved meshes in two dimensions.  \nWe use the isentropic vortex problem \\cite{shu1998essentially}, which has an analytical solution \n\\begin{align}\n\\rho(\\bm{x},t) &= \\LRp{1 - \\frac{\\frac{1}{2}(\\gamma-1)(\\beta e^{1-r(\\bm{x},t)^2})^2}{8\\gamma \\pi^2}}^{\\frac{1}{\\gamma-1}}, \\qquad p = \\rho^{\\gamma},\\\\\nu(\\bm{x},t) &= 1 - \\frac{\\beta}{2\\pi} e^{1-r(\\bm{x},t)^2}(x_2-c_2), \\qquad v(\\bm{x},t) = \\frac{\\beta}{2\\pi} e^{1-r(\\bm{x},t)^2}(x_2-c_2),\\nonumber\n\\end{align}\nwhere $u, v$ are the $x_1$ and $x_2$ velocity and $r(\\bm{x},t) = \\sqrt{(x_1-c_1-t)^2 + (x_2-c_2)^2}$.  Here, we take $c_1 = 5, c_2 = 0$ and $\\beta = 5$.  \nThe solution is computed on a periodic rectangular domain $[0, 20] \\times [-5,5]$ at final time $T=5$.  Quasi-uniform triangular meshes are generated using \\textsc{GMSH} \\cite{geuzaine2009gmsh}, and a curvilinear warping is applied to the mesh to test the effect of non-affine mappings.  This warping is shown in Figure~\\ref{fig:warp2dconverge} and is defined by mapping nodal positions on each triangle to warped nodal positions $(\\tilde{x_1},\\tilde{x_2})$ via\n\\begin{align*}\n\\tilde{x_1} &= x_1 + \\sin\\LRp{\\pi x_1 / 20}\\sin\\LRp{2\\pi (x_2+5)/10}\\\\\n\\tilde{x_2} &= x_2 - \\frac{1}{2}\\sin\\LRp{2 \\pi x_1 / 20}\\sin\\LRp{\\pi (x_2+5)/10}.\n\\end{align*}  \nTo ensure primary conservation, we use the ``Polynomial Approximation'' strategy described in Section~\\ref{sec:conservation} and compute the inverse of the weight-adjusted mass matrix using the degree $N$ $L^2$ projection $\\hat{\\Pi}_N J^k$ instead of $J^k$.  The computed $L^2$ errors are shown in Figure~\\ref{fig:converge2d}.  We observe optimal $O(h^{N+1})$ rates of convergence for $N=2, N= 4$.  For degree $N=3$, the rate of convergence is slightly higher than $O(h^{4})$ and may indicate that the mesh is not yet sufficiently fine for the $L^2$ error to show the asymptotic convergence rate.  \n\n\\begin{figure}\n\\centering\n\\begin{tikzpicture}\n\\begin{loglogaxis}[\n    legend cell align=left,\n    legend style={legend pos=south east, font=\\tiny},\n    width=.45\\textwidth,    \n    xlabel={Mesh size $h$},\n    ylabel={$L^2$ error}, \n     ymin=5e-6, ymax=2,    \n     xmin=1e-1, xmax=2.5,         \n    grid style=dashed,\n    legend entries={Affine,Curved}\n] \n\\addlegendimage{no markers,black}\n\\addlegendimage{no markers,dashed,black}\n\n\\addplot[color=blue,mark=*,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(2,1.06717)(1,0.149639)(0.5,0.025693)(0.25,0.00342827)} [yshift=4pt] node[left, pos=1.05, color=blue] {$N = 2$};\n\\addplot[color=blue,mark=*,dashed,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(2,1.37709)(1,0.219501)(0.5,0.0385896)(0.25,0.0039906)};\n\\logLogSlopeTriangleFlip{0.45}{0.15}{0.575}{3}{blue}\n\n\n\\addplot[color=red,mark=square*,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(2,0.50782)(1,0.0516053)(0.5,0.00249425)(0.25,0.000110618)}[yshift=8pt] node[left, pos=1.05, color=red] {$N = 3$};\n\\addplot[color=red,mark=square*,dashed,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(2,0.535036)(1,0.0657418)(0.5,0.00501536)(0.25,0.000243005)};\n\\logLogSlopeTriangleFlip{0.45}{0.15}{0.34}{4}{red}\n\n\\addplot[color=black,mark=triangle*,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(2,0.235374)(1,0.0125714)(0.5,0.000321559)(0.25,1.06097e-05)} [yshift=8pt] node[left, pos=1.05, color=black] {$N = 4$};\n\\addplot[color=black,mark=triangle*,dashed,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(2,0.297758)(1,0.0207604)(0.5,0.000816006)(0.25,2.36102e-05)};\n\\logLogSlopeTriangle{0.45}{0.15}{0.05}{5}{black}\n\n%\\legend{$L^2$ projection,Weight-adjusted,Difference}\n%\\legend{Uniform, Optimal, Smoothed}\n\\end{loglogaxis}\n\\end{tikzpicture}\n\\caption{Convergence of $L^2$ errors for the 2D isentropic vortex problem on affine and curved meshes.}\n\\label{fig:converge2d}\n\\end{figure}\n\n%The mesh is constructed by first building a mesh of uniform quadrilateral elements and subdividing each quadrilateral into two uniform triangles.  We estimate the $L^2$ errors and their rates of convergence, which are shown in Figure~\\ref{fig:converge2d}.  We observe $L^2$ optimal $O(h^{N+1})$ rates of convergence for $N = 1,\\ldots, 3$, while for $N = 4$ we observe a rate of convergence between $O(h^{N+1})$ and $O(h^{N+1/2})$.  We note that the rate of $O(h^{N+1/2})$ is the theoretically proven rate of convergence for upwind DG methods on general meshes applied to linear hyperbolic problems  \\cite{johnson1986analysis,cockburn2008optimal}.  We note that this observed rate does not change significantly if the time-step is halved (improving from $4.785$ to $4.8$), suggesting that this slight degradation in convergence rate is not due to temporal errors.  \n\n\\subsection{Three dimensional compressible Euler equations}\n\nIn three dimensions, the compressible Euler equations are given by\n\\begin{align}\n\\pd{}{t}\\LRp{\\begin{array}{c}\n\\rho\\\\\n\\rho u\\\\\n\\rho v\\\\\n\\rho w\\\\\nE\n\\end{array}} +\n\\pd{}{x_1}\\LRp{\\begin{array}{c}\n\\rho u\\\\\n\\rho u^2+p\\\\\n\\rho uv\\\\\n\\rho uw\\\\\nu(E+p)\n\\end{array}} + \\pd{}{x_2}\\LRp{\\begin{array}{c}\n\\rho v\\\\\n\\rho uv\\\\\n\\rho v^2+p\\\\\n\\rho vw\\\\\nv(E+p)\n\\end{array}}  + \\pd{}{x_3}\\LRp{\\begin{array}{c}\n\\rho w\\\\\n\\rho uw\\\\\n\\rho vw\\\\\n\\rho w^2+p\\\\\nw(E+p)\n\\end{array}} &= 0,\n\\label{eq:euler3d}\n\\end{align}\nwhere the pressure $p$ and specific internal energy $\\rho e$ are defined \n\\begin{align}\np = (\\gamma-1)\\LRp{E - \\frac{1}{2}\\rho (u^2+v^2+w^2)}, \\qquad \\rho e = E - \\frac{1}{2}\\rho (u^2+v^2+w^2).  \n\\label{eq:pressure3d}\n\\end{align}\nThe formula for the entropy $U(\\bm{u})$ in three dimensions is the same as the two-dimensional formula (\\ref{eq:entropy2d}).  \n The entropy variables in three dimensions are \n\\begin{align}\nv_1 = \\frac{\\rho e (\\gamma + 1 - s) - E}{\\rho e}, \\qquad v_2 = \\frac{\\rho u}{\\rho e}, \\qquad v_3 = \\frac{\\rho v}{\\rho e}, \\qquad v_4 = \\frac{\\rho w}{\\rho e}, \\qquad v_5 = -\\frac{\\rho}{\\rho e}.\n\\end{align}\nThe conservation variables in terms of the entropy variables are given by\n\\begin{equation}\n\\rho = -(\\rho e) v_5, \\qquad \\rho u = (\\rho e) v_2, \\qquad \\rho v = (\\rho e) v_3, \\qquad \\rho w = (\\rho e) v_4, \\qquad E = (\\rho e)\\LRp{1 - \\frac{{v_2^2+v_3^2+v_4^2}}{2 v_5}},\n\\end{equation}\nwhere $\\rho e$ and $s$ in terms of the entropy variables are \n\\begin{equation}\n\\rho e = \\LRp{\\frac{(\\gamma-1)}{\\LRp{-v_5}^{\\gamma}}}^{1/(\\gamma-1)}e^{\\frac{-s}{\\gamma-1}}, \\qquad s = \\gamma - v_1 + \\frac{{v_2^2+v_3^2+v_4^2}}{2v_5}.\n\\end{equation}\nA set of entropy conservative numerical fluxes for the three-dimensional compressible Euler equations can be written as\n\\begin{gather}\n\\bm{f}_{1,S} = \\LRp{\\begin{array}{c}\n\\avg{\\rho}^{\\log}\\avg{u}\\\\\n\\avg{\\rho}^{\\log}\\avg{u}^2 + p_{\\rm avg}\\\\\n\\avg{\\rho}^{\\log}\\avg{u}\\avg{v}\\\\\n\\avg{\\rho}^{\\log}\\avg{u}\\avg{w}\\\\\n(E_{\\rm avg}+ p_{\\rm avg})\\avg{u}\\\\\n\\end{array}}, \n\\qquad \n\\bm{f}_{2,S} = \\LRp{\\begin{array}{c}\n\\avg{\\rho}^{\\log}\\avg{v}\\\\\n\\avg{\\rho}^{\\log}\\avg{u}\\avg{v}\\\\\n\\avg{\\rho}^{\\log}\\avg{v}^2 + p_{\\rm avg}\\\\\n\\avg{\\rho}^{\\log}\\avg{v}\\avg{w}\\\\\n(E_{\\rm avg}+ p_{\\rm avg})\\avg{v}\\\\\n\\end{array}},\\\\\n\\bm{f}_{3,S} = \\LRp{\\begin{array}{c}\n\\avg{\\rho}^{\\log}\\avg{w}\\\\\n\\avg{\\rho}^{\\log}\\avg{u}\\avg{w}\\\\\n\\avg{\\rho}^{\\log}\\avg{v}\\avg{w}\\\\\n\\avg{\\rho}^{\\log}\\avg{w}^2 + p_{\\rm avg}\\\\\n(E_{\\rm avg}+ p_{\\rm avg})\\avg{w}\\\\\n\\end{array}}.\\nonumber\n%&f^1_{1,S}(\\bm{u}_L,\\bm{u}_R) = \\avg{\\rho}^{\\log} \\avg{u},& &f^1_{2,S}(\\bm{u}_L,\\bm{u}_R) = \\avg{\\rho}^{\\log} \\avg{v},&\\\\\n%&f^2_{1,S}(\\bm{u}_L,\\bm{u}_R) = f^1_{1,S} \\avg{u} + p_{\\rm avg},&  &f^2_{2,S}(\\bm{u}_L,\\bm{u}_R) = f^1_{2,S} \\avg{u},&\\nonumber\\\\\n%&f^3_{1,S}(\\bm{u}_L,\\bm{u}_R) = f^2_{2,S},& &f^3_{2,S}(\\bm{u}_L,\\bm{u}_R) = f^1_{2,S} \\avg{v} + p_{\\rm avg},&\\nonumber\\\\\n%&f^4_{1,S}(\\bm{u}_L,\\bm{u}_R) = \\LRp{\\frac{p_{\\rm avg}^{\\log}}{\\gamma -1} + p_{\\rm avg} + \\frac{\\nor{\\bm{u}}^2_{\\rm avg}}{2}}\\avg{u},& &f^4_{2,S}(\\bm{u}_L,\\bm{u}_R) = \\LRp{\\frac{p_{\\rm avg}^{\\log}}{\\gamma -1} + p_{\\rm avg} + \\frac{\\nor{\\bm{u}}^2_{\\rm avg}}{2}}\\avg{v},& \\nonumber\n\\end{gather}\nwhere we have defined the auxiliary quantities\n\\begin{align}\np_{\\rm avg} &= \\frac{\\avg{\\rho}}{2\\avg{\\beta}}, \\qquad E_{\\rm avg} = \\frac{\\avg{\\rho}^{\\log}}{2(\\gamma-1)\\avg{\\beta}^{\\log}} + \\frac{1}{2}\\avg{\\rho}^{\\log}\\nor{\\bm{u}}^2_{\\rm avg}\\\\\n\\nor{\\bm{u}}^2_{\\rm avg} &= 2(\\avg{u}^2 + \\avg{v}^2 + \\avg{w}^2) - \\LRp{\\avg{u^2} +\\avg{v^2} + \\avg{w^2}}.\\nonumber\n\\end{align}\n\n\\subsubsection{Accuracy and convergence}\n\nAs before, we test the accuracy of the proposed scheme using an isentropic vortex solution adapted to three dimensions.  We take the solution to be the extruded 2D vortex propagating in the $x_2$ direction, whose analytic expression is derived from \\cite{williams2013nodal}\n\\begin{align*}\n\\rho(\\bm{x},t) &= \\LRp{1-\\frac{(\\gamma-1)}{2}\\Pi^2}^{\\frac{1}{\\gamma-1}}\\\\\n\\bm{u}(\\bm{x},t) &= \\Pi \\bm{r}, \\\\\nE(\\bm{x},t) &= \\frac{p_0}{\\gamma-1}\\LRp{1-\\frac{\\gamma-1}{2}\\Pi^2}^{\\frac{\\gamma}{\\gamma-1}} + \\frac{\\rho}{2}\\LRb{\\bm{u}}.\n\\end{align*}\nwhere $\\bm{u} = (u,v,w)^T$ is the velocity vector and % $\\Pi$, $\\bm{r}$ are defined as\n\\[\n\\Pi = \\Pi_{\\max}e^{\\frac{1-\\bm{r}^T\\bm{r}}{2}}, \\qquad \\bm{r} = \\begin{pmatrix}\n-(x_2-c_2-t)\\\\\nx_1-c_1\\\\\n0\n\\end{pmatrix}.\n\\]\nIn this problem, we take $c_1 = c_2 = 5$, $p_0 = {1}/{\\gamma}$, and $\\Pi_{\\max} = 0.4$.  The problem is solved on the domain $[0,10]\\times [0,20]\\times [0,10]$.  \n%\\begin{figure}\n%\\centering\n%\\subfloat[$h = 1$]{\\includegraphics[width=.4\\textwidth]{figs/periodicCube2.png}}\n%\\hspace{2em}\n%\\subfloat[$h = 1/2$]{\\includegraphics[width=.4\\textwidth]{figs/periodicCube3.png}}\n%\\caption{Unstructured affine tetrahedral meshes used for convergence tests.}\n%\\label{fig:mesh3d}\n%\\end{figure}\nWe use \\textsc{GMSH} to construct three unstructured meshes consisting of 1354, 9543, and 72923 affine tetrahedra, corresponding to $h = 2$, $h = 1$, and $h = 1/2$ (shown in Figure~\\ref{subfig:mesh3d}).  We apply a curvilinear warping by again mapping nodal positions each tetrahedron to warped nodal positions $(\\tilde{x_1},\\tilde{x_2},\\tilde{x_3})$ via\n\\begin{align*}\n\\tilde{x_1} &= x_1 + \\frac{1}{2}\\sin\\LRp{\\pi \\frac{x_1}{10}}\\sin\\LRp{2\\pi \\frac{x_2}{20}}\\sin\\LRp{\\pi \\frac{x_3}{10}},\\\\\n\\tilde{x_2} &= x_2 - \\sin\\LRp{2 \\pi \\frac{x_1}{10}}\\sin\\LRp{\\pi \\frac{x_2}{10}}\\sin\\LRp{2\\pi \\frac{x_3}{10}},\\\\\n\\tilde{x_3} &= x_3 + \\frac{1}{2}\\sin\\LRp{\\pi \\frac{x_1}{10}}\\sin\\LRp{2\\pi \\frac{x_2}{10}}\\sin\\LRp{\\pi \\frac{x_3}{10}}.\n\\end{align*} \nThe geometric terms are approximated using (\\ref{eq:iconscurl2}) to ensure the satisfaction of the discrete GCL.  \n\n\\begin{figure}\n\\centering\n\\subfloat[Mesh for $h = 1/2$]{\\raisebox{2em}{\\includegraphics[width=.4\\textwidth]{figs/periodicCube3.png}}\\label{subfig:mesh3d}}\n\\subfloat[$L^2$ errors]{\\begin{tikzpicture}\n\\begin{loglogaxis}[\n    legend cell align=left,\n    legend style={legend pos=south east, font=\\tiny},\n    width=.45\\textwidth,    \n    xlabel={Mesh size $h$},\n    ylabel={$L^2$ error}, \n     ymin=1e-4, ymax=2,    \n     xmin=2.5e-1, xmax=2.5,         \n    grid style=dashed,\n    legend entries={Affine,Curved}\n] \n\\addlegendimage{no markers,black}\n\\addlegendimage{no markers,dashed,black}\n\n\\addplot[color=blue,mark=*,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(2,1.05519)(1,0.143515)(0.5,0.0212682)}[yshift=4pt] node[left, pos=1.05, color=blue] {$N = 2$};\n\\addplot[color=blue,mark=*,dashed,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(2,1.20915)(1,0.2069)(0.5,0.0284505)};\n\\logLogSlopeTriangleFlip{0.45}{0.15}{0.6}{3}{blue}\n\n\\addplot[color=red,mark=square*,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(2,0.339318)(1,0.0314342)(0.5,0.00197699)}[yshift=8pt] node[left, pos=1.05, color=red] {$N = 3$};\n\\addplot[color=red,mark=square*,dashed,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(2,0.464613)(1,0.0513369)(0.5,0.00334595)};\n\\logLogSlopeTriangleFlip{0.45}{0.15}{0.375}{4}{red}\n\n\\addplot[color=black,mark=triangle*,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(2,0.122229)(1,0.00488434)(0.5,0.000192453)}[yshift=8pt] node[left, pos=1.05, color=black] {$N = 4$};\n\\addplot[color=black,mark=triangle*,dashed,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(2,0.184547)(1,0.0104361)(.5,0.0003960681)};\n\\logLogSlopeTriangle{0.45}{0.15}{0.04}{5}{black}\n\n%\\legend{$L^2$ projection,Weight-adjusted,Difference}\n%\\legend{Uniform, Optimal, Smoothed}\n\\end{loglogaxis}\n\\end{tikzpicture}}\n\\caption{Convergence of $L^2$ errors for the 3D isentropic vortex problem on unstructured affine and curved meshes, with optimal $O(h^{N+1})$ rates of convergence shown for reference.}\n\\label{fig:converge3d}\n\\end{figure}\n\nFigure~\\ref{fig:converge3d} shows $L^2$ errors for $N = 2,3,4$ on both affine and curved meshes.  In both cases, we observe optimal  $O(h^{N+1})$ asymptotic rates of convergence for $N = 2,3$, while for $N = 4$ we observe a rate which is slightly higher than $O(h^{N+1/2})$ but not quite $O(h^{N+1})$.  This may be due to the fact that the time-stepper is $4$th order while the spatial discretization is $5$th order.  \n\nWe also compared approximations of geometric factors using degree $N$ polynomials via (\\ref{eq:iconscurl2}) and degree $N-1$ polynomials via (\\ref{eq:iconscurl}).  For the isentropic vortex problem on warped meshes, the approximation of the geometric factors does not impact accuracy significantly.  Utilizing (\\ref{eq:iconscurl}) and approximating geometric factors with degree $N-1$ polynomials only changed the error in the $5$th significant digit, and resulted in the same asymptotic rates of convergence on curved 3D meshes.  Future work will explore the effect of a more accurate geometric approximation on curved boundaries where a solid wall boundary condition is applied, where the approximation of geometry has been shown to have a more significant effect  \\cite{toulorge2016optimizing}.  \n\n%\\note{Isentropic vortex on curved and non-curved meshes}\n\n\\subsubsection{Inviscid Taylor--Green vortex}\n\nOur last numerical experiment investigates the behavior of entropy stable DG schemes for the inviscid Taylor--Green vortex \\cite{ae1937mechanism, gassner2016split, crean2018entropy}.  The domain is the periodic box $[-\\pi,\\pi]^3$, and the initial conditions are given as\n\\begin{align*}\n\\rho &= 1\\\\\nu &= \\sin(x_1)\\cos(x_2)\\cos(x_3),\\\\\nv &= -\\cos(x_1)\\sin(x_2)\\cos(x_3),\\\\ \nw &= 0,\\\\\np &= \\frac{100}{\\gamma} + \\frac{1}{16} \\LRp{\\cos(2x_1) + \\cos(2x_2)}\\LRp{2+\\cos(2x_3)}.\n\\end{align*}\nThe Taylor--Green vortex is used to study the transition and decay of turbulence \\cite{debonis2013solutions}.  In the absence of viscosity, the Taylor--Green vortex develops smaller and smaller scales, implying that for sufficiently large times, the solution contains under-resolved features.  We study the evolution of the kinetic energy $\\kappa(t)$ \n\\[\n\\kappa(t) =\\frac{1}{\\LRb{\\Omega}} \\int_{\\Omega} \\rho \\bm{u}\\cdot\\bm{u} \\diff{\\bm{x}},\n\\]\nas well as the kinetic energy dissipation rate $-\\pd{\\kappa}{t}$, which we approximate by differencing $\\kappa(t)$.  Figure~\\ref{fig:tg} shows the evolution of $\\kappa(t)$ over time for both affine and curvilinear meshes with $h = \\pi/8$ and $N = 3$.  We also use a curved coarse mesh with element size $h = \\pi$ test the convergence of the average entropy for a non-dissipative entropy conservative formulation as the timestep decreases.  In both cases, the mesh is defined by constructing nodal positions $\\tilde{\\bm{u}}$ from warpings of affine nodal positions $\\bm{x}$ as follows \n\\[\n\\tilde{\\bm{x}} = \\bm{x} + .125 \\sin(x_1)\\sin(x_2)\\sin(x_3).\n\\]\nThe kinetic energy is plotted at 100 equally spaced times between $[0,20]$.  The simulation is stable and does not blow up despite the lack of filtering, limiting, or artificial viscosity.  The results are qualitatively similar to those reported in the literature, with the kinetic energy dissipation rate increasing around $t = 4$ and peaking with a value of roughly $0.014$ before $t = 9$ \\cite{debonis2013solutions, gassner2016split}.  We also observe that, for an entropy conservative formulation, the average entropy appears to converge at a rate of $O(dt^{5})$ for a 4th order time-stepping method.  The same phenomena was also observed in \\cite{chan2017discretely, crean2018entropy}.  \n\n\\begin{figure}\n\\centering\n\\subfloat[KE dissipation rate for $N=3$, $h = \\pi/8$]{\n\\begin{tikzpicture}\n\\begin{axis}[\n        scaled ticks=false, \n        tick label style={/pgf/number format/fixed},\n\tlegend cell align=left,\n\tlegend style={font=\\tiny},\n\twidth=.475\\textwidth,\n    xlabel={Time $t$},\n    ylabel={$-\\pd{\\kappa}{t}$},\n%    xmin=.005, xmax=1,\n%    ymin=1e-10, ymax=1e-1,\nymin=-.0025, ymax=.017,\n    legend pos=north east,\n    xmajorgrids=true,\n    ymajorgrids=true,\n    grid style=dashed,\n    ytick={0, .005, .01, .015},\n    yticklabels={0, .005, .01, .015}    \n] \n\\addplot[color=blue,semithick, mark options={fill=markercolor}]\ncoordinates{(0,-0)(0.18796,-8.45875e-06)(0.37592,-9.02267e-06)(0.563879,-1.63536e-05)(0.751839,-1.40979e-05)(0.939799,-2.48123e-05)(1.12776,-2.65041e-05)(1.31572,-2.76319e-05)(1.50368,-2.53763e-05)(1.69164,-2.0301e-05)(1.8796,-2.31206e-05)(2.06756,-1.69175e-05)(2.25552,-1.3534e-05)(2.44348,2.25567e-06)(2.63144,1.63536e-05)(2.8194,2.98876e-05)(3.00736,4.90608e-05)(3.19532,7.38731e-05)(3.38328,0.000117859)(3.57124,0.000183837)(3.7592,0.000306771)(3.94716,0.000514292)(4.13512,0.000819935)(4.32308,0.00122765)(4.51104,0.00175378)(4.699,0.00240454)(4.88696,0.00307729)(5.07491,0.00363332)(5.26288,0.00394291)(5.45083,0.00414817)(5.6388,0.00436754)(5.82676,0.00455927)(6.01471,0.00484235)(6.20267,0.00527544)(6.39063,0.00577169)(6.57859,0.0063638)(6.76655,0.00709971)(6.95451,0.00787679)(7.14247,0.00860142)(7.33043,0.0093097)(7.51839,0.0100575)(7.70635,0.0109236)(7.89431,0.011972)(8.08227,0.0129661)(8.27023,0.013675)(8.45819,0.0141244)(8.64615,0.0142863)(8.83411,0.0141814)(9.02207,0.0139541)(9.21003,0.0136913)(9.39799,0.0134325)(9.58595,0.0133152)(9.77391,0.0132047)(9.96187,0.0130733)(10.1498,0.0127473)(10.3378,0.0122686)(10.5258,0.0118191)(10.7137,0.0114588)(10.9017,0.011108)(11.0896,0.0107578)(11.2776,0.0104415)(11.4656,0.0101274)(11.6535,0.00979918)(11.8415,0.00946253)(12.0294,0.00913827)(12.2174,0.00885124)(12.4053,0.00859409)(12.5933,0.00836514)(12.7813,0.00814465)(12.9692,0.00790724)(13.1572,0.00766025)(13.3451,0.00740818)(13.5331,0.0071578)(13.7211,0.00691137)(13.909,0.00667057)(14.097,0.0064264)(14.2849,0.00616305)(14.4729,0.0058918)(14.6609,0.00565045)(14.8488,0.00543559)(15.0368,0.00524499)(15.2247,0.00506736)(15.4127,0.00490326)(15.6007,0.00475551)(15.7886,0.00460156)(15.9766,0.00443803)(16.1645,0.00427562)(16.3525,0.00412054)(16.5405,0.00397618)(16.7284,0.00384422)(16.9164,0.00371339)(17.1043,0.00357805)(17.2923,0.00344835)(17.4803,0.00333275)(17.6682,0.00323237)(17.8562,0.00313369)(18.0441,0.00303105)(18.2321,0.00292842)(18.4201,0.00282973)(18.608,0.00273556)(18.796,0.00264082)(18.9839,0.00254834)(19.1719,0.00246319)(19.3599,0.0023848)(19.5478,0.00231431)(19.7358,0.00225059)(19.9237,0.00218969)};\n\n\\addplot[color=red, dashed,semithick, mark options={fill=markercolor}]\ncoordinates{(0,5.36239e-07)(0.18796,-9.65229e-06)(0.37592,-1.01885e-05)(0.563879,-1.98408e-05)(0.751839,-1.76959e-05)(0.939799,-1.93046e-05)(1.12776,-2.14495e-05)(1.31572,-1.93046e-05)(1.50368,-2.4667e-05)(1.69164,-1.66234e-05)(1.8796,-8.57982e-06)(2.06756,-0)(2.25552,1.17972e-05)(2.44348,1.76959e-05)(2.63144,3.70005e-05)(2.8194,6.43486e-05)(3.00736,0.000107784)(3.19532,0.000173741)(3.38328,0.000268656)(3.57124,0.000432745)(3.7592,0.000693357)(3.94716,0.00106122)(4.13512,0.00156796)(4.32308,0.00222485)(4.51104,0.00299597)(4.699,0.00373597)(4.88696,0.00432584)(5.07491,0.00468404)(5.26288,0.00495645)(5.45083,0.00521599)(5.6388,0.00551361)(5.82676,0.0059426)(6.01471,0.00650672)(6.20267,0.00717005)(6.39063,0.00793258)(6.57859,0.00878681)(6.76655,0.0095858)(6.95451,0.0103457)(7.14247,0.0110685)(7.33043,0.0116551)(7.51839,0.0124011)(7.70635,0.013015)(7.89431,0.0133341)(8.08227,0.0135652)(8.27023,0.0136097)(8.45819,0.0135175)(8.64615,0.0134918)(8.83411,0.0133647)(9.02207,0.0131925)(9.21003,0.0130242)(9.39799,0.012703)(9.58595,0.0123292)(9.77391,0.011971)(9.96187,0.0115586)(10.1498,0.0111345)(10.3378,0.0107687)(10.5258,0.0103671)(10.7137,0.0100089)(10.9017,0.00969788)(11.0896,0.00941206)(11.2776,0.00916861)(11.4656,0.00893803)(11.6535,0.00868707)(11.8415,0.00840018)(12.0294,0.00807897)(12.2174,0.00776742)(12.4053,0.00747785)(12.5933,0.00721187)(12.7813,0.00696306)(12.9692,0.00670834)(13.1572,0.00645792)(13.3451,0.00619624)(13.5331,0.00595922)(13.7211,0.00574312)(13.909,0.00552219)(14.097,0.00531841)(14.2849,0.0051318)(14.4729,0.0049527)(14.6609,0.00476984)(14.8488,0.00459717)(15.0368,0.00443791)(15.2247,0.00428401)(15.4127,0.00412689)(15.6007,0.00396924)(15.7886,0.00382231)(15.9766,0.00368503)(16.1645,0.00355633)(16.3525,0.00343783)(16.5405,0.00332253)(16.7284,0.00320563)(16.9164,0.00309088)(17.1043,0.00298524)(17.2923,0.00288282)(17.4803,0.00277932)(17.6682,0.00268602)(17.8562,0.00260719)(18.0441,0.00253641)(18.2321,0.00245865)(18.4201,0.00237071)(18.608,0.0022833)(18.796,0.00220501)(18.9839,0.00213584)(19.1719,0.00207203)(19.3599,0.00201358)(19.5478,0.00196102)(19.7358,0.0019074)(19.9237,0.00185056)};\n\n\\legend{Affine, Curved}\n\\end{axis}\\end{tikzpicture}\n}\n%\\hspace{1em}\n\\subfloat[Entropy conservative convergence of $\\int_{\\Omega}U(\\bm{u})$ ]{\n\\begin{tikzpicture}\n\\begin{loglogaxis}[\n        scaled ticks=false, \n        tick label style={/pgf/number format/fixed},\n\tlegend cell align=left,\n\tlegend style={font=\\tiny},\n\twidth=.475\\textwidth,\n    xlabel={CFL},\n    ylabel={Average entropy},\n%    xmin=.005, xmax=1,\n%ymin=-.0025, ymax=.017,\n    legend pos=south east,\n    xmajorgrids=true,\n    ymajorgrids=true,\n    grid style=dashed,\n%    ytick={0, .005, .01, .015},\n%    yticklabels={0, .005, .01, .015}    \n] \n\\addplot[color=blue,mark=*,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(0.25,6.22584e-05)(0.125,2.42033e-05)(0.0625,2.70793e-06)(0.03125,9.23535e-08)};\n\n\\addplot[color=red,dashed,mark=square*,semithick, mark options={solid,fill=markercolor}]\ncoordinates{(0.25,5.32822e-05)(0.125,1.5792e-05)(0.0625,9.458e-07)(0.03125,3.05056e-08)};\n\n\\logLogSlopeTriangleFlip{0.275}{0.15}{0.3}{5}{black}\n%\\addplot[color=red, dashed,semithick, mark options={fill=markercolor}]\n\n\\legend{Affine, Curved} %Affine\n\\end{loglogaxis}\n\\end{tikzpicture}\n}\n\\caption{Evolution of the kinetic energy dissipation rate over time on affine and curvilinear meshes, as well as dependence of average entropy over the domain $\\int_{\\Omega} U(\\bm{u})$ at time $T = 20$ for an entropy conservative formulation.  }\n\\label{fig:tg}\n\\end{figure}\n\n%\\note{Add Taylor--Green vortex}\n\n\\section{Conclusions}\n\nThis work describes how to extend entropy conservative and entropy stable DG ``modal'' discretizations to curvilinear meshes using both weighted and weight-adjusted mass matrices.   Assuming that the geometric terms satisfy a discrete geometric conservation law, the presented schemes allow for the use of over-integration while satisfying a semi-discrete entropy equality or inequality on curved meshes.  Numerical results show the presented schemes achieve optimal rates of convergence for smooth solutions on both two and three dimensional affine and curvilinear meshes while remaining robust in the presence of under-resolved solutions such as shocks and turbulence.  \n\nSeveral outstanding computational questions remain to be answered.  First, the use of weight-adjusted mass matrices is motivated by the low storage requirements and their efficient application on GPUs.  However, to guarantee discrete entropy stability, the computation of a weight-adjusted projection is necessary, which adds additional computational cost compared to the affine case.  Furthermore, numerical results suggest that, while computing the entropy-projected conservative variables $\\tilde{\\bm{u}}$ using the weight-adjusted projection is necessary to ensure a semi-discrete conservation of entropy, the difference between using a weight-adjusted projection and regular projection may be negligible in practice.  The necessity of the weight-adjusted projection in computing $\\tilde{\\bm{u}}$ should be examined further.  Secondly, on triangular and tetrahedral meshes, the proposed schemes involve more computational work than under-integrated collocation-style SBP schemes \\cite{hicken2016multidimensional, chen2017entropy, crean2018entropy}.  A careful computational comparison of the presented schemes with existing methods should be done to weigh the benefits of improved accuracy with additional computational costs.  \n\nFinally, we note that while this work has focused on triangular and tetrahedral elements, the approaches outlined here are applicable to more arbitrary pairings of approximations spaces and quadratures.  For example, similar techniques can be used to construct entropy stable B-spline or Galerkin difference discretizations on curved meshes \\cite{banks2016galerkin, chan2018multi}.  \n\n\\section{Acknowledgements}\n\nThe authors thank Mark H.\\ Carpenter and David C.\\ Del Rey Fernandez for informative discussions.  Jesse Chan is supported by NSF DMS-1719818.  \n\n\\bibliographystyle{unsrturl}\n\\bibliography{dg}\n\n\n\\end{document}\n\n\n\n\n", "meta": {"hexsha": "97f7f5acf06f50052a7768b87eb9fdc33e3eb90b", "size": 158066, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/main.tex", "max_stars_repo_name": "ntan15/scratch_wadge", "max_stars_repo_head_hexsha": "0657069749b9507062c1f7e875c6545076fb85c8", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/main.tex", "max_issues_repo_name": "ntan15/scratch_wadge", "max_issues_repo_head_hexsha": "0657069749b9507062c1f7e875c6545076fb85c8", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/main.tex", "max_forks_repo_name": "ntan15/scratch_wadge", "max_forks_repo_head_hexsha": "0657069749b9507062c1f7e875c6545076fb85c8", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 80.6459183673, "max_line_length": 2134, "alphanum_fraction": 0.6944820518, "num_tokens": 59412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.640635847978761, "lm_q1q2_score": 0.3428032355753118}}
{"text": "%!TEX root=report.tex\n\\section{Data}\n\nThe GRACE dataset can be downloaded from GRGS \\cite{GRACE-data-source}.\nThis report is based on the Equivalent Water Height (denoted EWH) dataset from release 2 in the GRGS format with a 10-day interval.\n\nThis dataset contains quite a few text files, each containing information in both its filename and its content.\nThe filenames have the format:\n\n\\begin{lstlisting}\ngrid.water.10day_model_minus_RL02MF.19202_19211.txt\ngrid.water.10day_model_minus_RL02MF.19212_19221.txt\n...\n\\end{lstlisting}\n\nIn the filename, the last two numbers (e.g. \\texttt{19202\\_19211}) are important.\nThe first number denotes the start date and the second number the end date for the file content.\nEach number specifies the number of days since ``1950-01-01'' \\cite{GRACE-data-format-dates}.\n\nThe actual content of each text file should be read as a ``Space Separated Values'' format.\nWhen this is done one will have a $6480 \\times 10$ matrix.\nThis matrix can then be \\texttt{reshape}'ed row-wise into a $180 \\times 360$ matrix.\nThe result is a matrix with decreasing latitude on the rows and increasing longitude on the columns \\cite{GRACE-data-format-grids}.\n\n\\subsection{Data example}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=\\textwidth]{figures/data-example-world}\n\t\\caption{Plot of the data, 10 day period starting on 3 April 2009}\n\t\\label{fig:data-example-world}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=\\textwidth]{figures/data-example-scatter}\n\t\\caption{Plot of EWH at 63.5 N 49.5 W, west coast of Greenland.}\n\t\\label{fig:data-example-scatter}\n\\end{figure}\n\nFrom Figure \\ref{fig:data-example-world} local mass losses at Greenland and the South Pole are seen.\nIn Figure \\ref{fig:data-example-scatter}, the mass loss at Greenland is seen with a yearly periodic trend. For both locations, the ice melting may be caused by ice melting.\nHowever it is also possible that these changes are caused by post glacial rebound, in partially because no glacial isostatic adjustment (GIA) have been performed on this version of the GRACE dataset.\nIn fact it is quite complicated to do sufficient adjustments to conclusively say something about ice melting \\cite{NASA-GIA-incomplete}.\nWhen that is said, attempts to analyze the GRACE data with the prospect of saying something about the ice melting patterns, will still be made.\n\nFrom Figure \\ref{fig:data-example-world} a mass increment in South America can also been seen, this is caused by the rain season.\n", "meta": {"hexsha": "a39063ea1bf6af21907c4247b46a4db93f7b2a86", "size": 2506, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Rapport/data.tex", "max_stars_repo_name": "AndreasMadsen/grace", "max_stars_repo_head_hexsha": "bf472d30a2fac76145d3f68e819c92da4a1970ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-05-17T22:52:19.000Z", "max_stars_repo_stars_event_max_datetime": "2016-05-17T22:52:19.000Z", "max_issues_repo_path": "Rapport/data.tex", "max_issues_repo_name": "AndreasMadsen/grace", "max_issues_repo_head_hexsha": "bf472d30a2fac76145d3f68e819c92da4a1970ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Rapport/data.tex", "max_forks_repo_name": "AndreasMadsen/grace", "max_forks_repo_head_hexsha": "bf472d30a2fac76145d3f68e819c92da4a1970ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.2083333333, "max_line_length": 199, "alphanum_fraction": 0.7849162011, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.34278524085459566}}
{"text": "%% This is emulateapj reformatting of the AASTEX sample document\n%%\n%\\documentclass[trackchanges]{aastex6}\n%\\documentclass[twocolumn,twocolappendix]{aastex6}\n%\\usepackage{amssymb,amsmath}\t% Advanced maths commands\n%\\usepackage{graphicx}\n%\\usepackage{todonotes}\n%\\usepackage{xcolor}\n%\\usepackage{hyperref}\n%\\newcommand\\earl[1]{\\textcolor{red}{ #1}}\n\n%\\newcommand\\earl[1]{\\textcolor{red}{ [#1]}}\n%usepackage{aas_macros}\n\n%\\newcommand\\abs[1]{\\left|#1\\right|}\n\n%\\newcommand{\\vdag}{(v)^\\dagger}\n%\\newcommand{\\myemail}{angelou@mps.mpg.de}\n\n\n%% You can insert a short comment on the title page using the command below.\n\n%\\slugcomment{Not to appear in Nonlearned J., 45.}\n\n%% If you wish, you may supply running head information, although\n%% this information may be modified by the editorial offices.\n%% The left head contains a list of authors,\n%% usually a maximum of three (otherwise use et al.).  The right\n%% head is a modified title of up to roughly 44 characters.\n%% Running heads will not print in the manuscript style.\n\n%\\shorttitle{Statistical Properties of the MS}\n%\\shortauthors{Angelou \\& Bellinger et al.}\n\n%% This is the end of the preamble.  Indicate the beginning of the\n%% paper itself with \\begin{document}.\n\n%\\begin{document}\n\n%% LaTeX will automatically break titles if they run longer than\n%% one line. However, you may use \\\\ to force a line break if\n%% you desire.\n\n%\\title{\n\\chapter{On the Statistical Properties of the Lower Main Sequence}\n\\label{chap:statistical}\n\nThe contents of this chapter were authored \n%as ``\\emph{On The Statistical Properties of the Lower Main Sequence}'' \nby G.~C.~Angelou, E.~P.~Bellinger, S.~Hekker, and S.~Basu and published in April of 2017 in \\emph{The Astrophysical Journal}, 839 (2), 116.\\footnote{Contribution statement: The work and writing of this chapter were done in equal parts between G.~C.~Angelou and myself, under the supervision of S.~Hekker and S.~Basu.} \n\\nocite{2017apj...839..116a} \n\n%% Use \\author, \\affil, and the \\and command to format\n%% author and affiliation information.\n%% Note that \\email has replaced the old \\authoremail command\n%% from AASTeX v4.0. You can use \\email to mark an email address\n%% anywhere in the paper, not just in the front matter.\n%% As in the title, use \\\\ to force line breaks.\n\n%\\author{George C. Angelou \\altaffilmark{1,2}, Earl P. Bellinger\\altaffilmark{1,2,3,4}, Saskia Hekker\\altaffilmark{1,2} and Sarbani Basu\\altaffilmark{4}}\n%\\affil{\\altaffilmark{1} Max-Planck-Institut f\\\"{u}r Sonnensystemforschung, Justus-von-Liebig-Weg 3, 37077 G\\\"{o}ttingen, Germany\\\\\n%\\altaffilmark{2} Stellar Astrophysics Centre, Department of Physics and Astronomy, Aarhus University, Ny Munkegade 120, DK-8000 Aarhus C, Denmark \\\\\n%\\altaffilmark{3} Institut f\\\"{u}r Informatik, Georg-August-Universit\\\"{a}t G\\\"{o}ttingen, Goldschmidtstrasse 7, 37077 G\\\"{o}ttingen, Germany \\\\\n%\\altaffilmark{4} Department of Astronomy, Yale University, New Haven, CT 06520, USA}\n\n\n%% Mark off your abstract in the ``abstract'' environment. In the manuscript\n%% style, abstract will output a Received/Accepted line after the\n%% title and affiliation information. No date will appear since the author\n%% does not have this information. The dates will be filled in by the\n%% editorial office after submission.\n\n\\section*{Chapter Summary}\nAstronomy is in an era where all-sky surveys are mapping the Galaxy. \nThe plethora of photometric, spectroscopic, asteroseismic and astrometric data allows us to characterize the comprising stars in detail.  \nHere we quantify to what extent precise stellar observations reveal information about the properties of a star, including properties that are unobserved, or even unobservable. \nWe analyze the diagnostic potential of classical and asteroseismic observations for inferring stellar parameters such as age, mass and radius from evolutionary tracks of solar-like oscillators on the lower main sequence. \nWe perform rank correlation tests in order to determine the capacity of each observable quantity to probe structural components of stars and infer their evolutionary histories. We also analyze the principal components of classic and asteroseismic observables to highlight the degree of redundancy present in the measured quantities and demonstrate the extent to which information of the model parameters can be extracted.\nWe perform multiple regression using combinations of observable quantities in a grid of evolutionary simulations and appraise the predictive utility of each combination in determining the properties of stars.\nWe identify the combinations that are useful and provide limits to where each type of observable quantity can reveal information about a star. We investigate the accuracy with which targets in the upcoming TESS and PLATO missions can be characterized.  We demonstrate that the combination of observations from GAIA and PLATO will allow us to tightly constrain stellar masses, ages and radii with machine learning for the purposes of galactic and planetary studies.\n%\\end{abstract}\n\n%% Keywords should appear after the \\end{abstract} command. The uncommented\n%% example has been keyed in ApJ style. See the instructions to authors\n%% for the journal to which you are submitting your paper to determine\n%% what keyword punctuation is appropriate.\n\n%% Authors who wish to have the most important objects in their paper\n%% linked in the electronic edition to a data center may do so in the\n%% subject header.  Objects should be in the appropriate \"individual\"\n%% headers (e.g. quasars: individual, stars: individual, etc.) with the\n%% additional provision that the total number of headers, including each\n%% individual object, not exceed six.  The \\objectname{} macro, and its\n%% alias \\object{}, is used to mark each object.  The macro takes the object\n%% name as its primary argument.  This name will appear in the paper\n%% and serve as the link's anchor in the electronic edition if the name\n%% is recognized by the data centers.  The macro also takes an optional\n%% argument in parentheses in cases where the data center identification\n%% differs from what is to be printed in the paper.\n\n%\\keywords{methods: statistical --- stars: abundances --- stars: fundamental parameters --- stars: low-mass --- stars: oscillations --- stars: solar-type}\n\n%% From the front matter, we move on to the body of the paper.\n%% In the first two sections, notice the use of the natbib \\citep\n%% and \\citet commands to identify citations.  The citations are\n%% tied to the reference list via symbolic KEYs. The KEY corresponds\n%% to the KEY in the \\bibitem in the reference list below. We have\n%% chosen the first three characters of the first author's name plus\n%% the last two numeral of the year of publication as our KEY for\n%% each reference.\n\n\\section{Introduction} \n\nThe main sequence is generally considered the most well-understood phase of stellar evolution. \nOur Sun is a main-sequence star, and its proximity provides a wealth of constraints to the physics that may occur in low-mass counterparts during this phase \\citep[e.g.,][]{2015SSRv..196...49B,2016lrsp...13....2b}. \nCore-hydrogen burning stars are long-lived and hence numerous: indeed, the majority of the stars for which we can resolve parallaxes reside on the main sequence \\citep{2016arXiv160904172G}. \nAdditionally, many stars of this type display stochastic or ``solar-like'' oscillations that serve to reveal the stellar interior (see, for example, \\citealt{2013ARA&A..51..353C} for a review on solar-like oscillators).  \nMain-sequence stars are important astrophysical laboratories for testing theories of stellar physics, structure, and evolution; and are a testbed for general physical theories such as nuclear fusion, diffusion, and convection \\citep[e.g.,][]{1994MNRAS.269.1137B,1990ARAA..28..263S}. \n\nDespite all of this, however, the ages of main-sequence stars remain uncertain to at least  $10\\%$. This uncertainty stems not only from observational imprecision, but also from the inability of observations to fully constrain stellar parameters.  \nRecently, \\citetalias{2016apj...830...31b} showed that even for stellar models without observational uncertainties, some model attributes of stars---such as their initial helium abundance or efficiency of convection---could not be fully resolved via global information that can be gleaned from their surfaces. \n\n\nIt is well-known that different observable quantities of stars constrain different model properties. For example, in the now-famous Christensen-Dalsgaard diagram (C--D diagram, the so-called ``asteroseismic HR diagram''), in which the large frequency separation is plotted against the small frequency separation (Appendix \\ref{sec:sdefs}), the large frequency separation covaries with the mass of the star and the small frequency separation covaries with its core-hydrogen abundance. Hence, observing one of these quantities sheds light on its unobservable counterpart.\nHowever, to date, a systematic investigation of the extent to which each observable quantity constrains each model property has not been performed.\n\nThe equations dictating stellar structure and evolution, and the corresponding microphysics that these equations respond to, give rise to emergent behaviors that are difficult to characterize through examination of the constituting ingredients themselves. To elucidate these opaque relationships, we seek to determine the extent to which observable stellar properties are capable of constraining the internal structures, chemical mixtures, and evolutionary histories of stars. Here we employ the methodology of exploratory data science, a statistical philosophy by which underlying structure in data---simulated or otherwise---can be unearthed.\n\n\n\nBA1 used machine learning to build a statistical description of main-sequence stellar evolution. They trained a random forest (RF) of decision trees to learn the relationships that exist between model input parameters and their resultant observable quantities. The technique was developed with particular focus on the determination of stellar ages.  Ages are essential for understanding stellar evolution, characterizing extrasolar planetary systems and advancing models of galactic chemical evolution. \nNotably, the RF developed by BA1 was able to accurately predict stellar properties such as radii and luminosities using other information collected from the stars in their sample. This illustrates that there is redundant information in the stellar quantities, and that there exist model covariances between these quantities that can be characterized and exploited. \n\n\n\nThe philosophy employed in BA1 is a departure from the standard practice of stellar model fitting. Ordinarily, stellar parameters of observed stars are sought via $\\chi^2$-minimization.\nThe difference in approaches give rise to two points that motivate this paper:\n\\begin{enumerate}\n\n    \\item Methods based on $\\chi^2$-minimization assume that each bit of observed information contributes to the objective of constraining the model properties of a star in an exact proportion to how precisely it has been measured. However, two quantities may be measured independently with no measured covariance, and yet still provide redundant information about the star. The result of such a minimization procedure will therefore be a model that is biased towards that redundant information.  The RF developed in BA1, on the other hand, uses the process of statistical bagging to mitigate over-fitting of the data (see also \\citealt{hastie2005elements}).  Here we demonstrate the degree to which the observables  carry redundant information about the star. \n\n    \\item The %blind\n    optimization searches of iterative model finding procedures provide solutions but do not indicate the elements that were important in doing so. The use of regression requires that the observables correlate with those model parameters that we wish to infer.  We therefore identify to what extent each observable constrains each model property, and how well the observables must be measured to achieve a desired precision from the regression.  \n    \n\\end{enumerate}\n\n\nThe method developed in BA1 makes use of an artificial intelligence strategy known as supervised learning. The RF that they train seeks relations in evolutionary simulations that enable model properties to be inferred as precisely as possible. Although the RF performs the analysis quickly, precisely, and automatically; supervised machine learning strategies do not provide much insight into how the end result is obtained. The algorithm essentially produces a formula for inferring stellar properties from observations, but one that is too complex for people to use analytically by hand. \n\nHere we incorporate a complementary strategy. We use the counterpart of supervised learning---\\emph{unsupervised learning}---to explicitly uncover the relations between observable properties of stars and their model parameters. Hence, BA1 is of a strictly practical nature: stellar parameters can be inferred rapidly without regard for the how or why; and this paper is aimed to further an understanding of the processes actually involved in such a deduction. \n\nIn this study we draw heavily from the work presented in BA1.\nOur analysis initially focuses on elucidating the inherent statistical properties of the grid of stellar models used to train the BA1 RF. \nWe determine the relationships and covariances between a chosen subset of stellar parameters and asteroseismic quantities (see Table~\\ref{tab:parmdefs}). \nWe carry out simultaneous rank correlation tests on the chosen parameters and identify the necessary, dispensable, and irrelevant information for determining each stellar property.\nThen, using principal component analysis %(PCA)\nwe reduce the dimensionality of the observable quantities and identify to what extent they reveal information of the model parameters.\nWe subsequently shift the focus of our analysis to how the grid properties are used by the RF and how the choices in the parameters impact on the precision of the regression. \nWe train RFs using all combinations of observable quantities in our dataset. The purpose of this is two-fold: first, it is often the case that we wish to quickly characterize a star from a few easily observed quantities---the Hertzsprung-Russell (HR) diagram serves as the classic example. Training and scoring all possible RF combinations provides a means to \\emph{quantify} the utility and predictive power of classical and asteroseismic parameters for inferring stellar properties. Secondly, it provides insight into the relationships determined by machine learning algorithms. \nFinally, we identify the observational accuracy required to satisfactorily constrain key stellar parameters. We investigate the observable quantities independently as well as consider the measurements expected from the upcoming TESS and PLATO missions.\n\n\n\\section{Stellar Models and Parameters}\n\\begin{table}\n\\centering\n{\n\\renewcommand{\\arraystretch}{1.2}\n\\centering\n\\begin{tabular}{lll} \n\\hline \\hline  \n\\textbf{Qty} & \\textbf{Definition} & \\textbf{Unit} \\\\ \n\\hline\n\\multicolumn{3}{l}{Model Input Parameters} \\\\ \n$M$ & Initial mass & M$_{\\odot}$ \\\\\n$Y_0$ & Initial helium mass fraction & \\\\\n$Z_0$ & Initial metal mass fraction & \\\\\n$\\alpha_{\\text{MLT}}$ & Mixing length parameter & \\\\\n$\\alpha_{\\text{ov}}$ & Overshoot parameter & \\\\ \n$D$ & Diffusion efficiency factor & \\\\[8pt] \n%\\hline\n\\multicolumn{3}{l}{Stellar Attributes} \\\\\n$\\tau$ & Age & yr \\\\\n$\\tau_{\\text{MS}}$ & Normalized main-sequence lifetime &  \\\\\nM$_{\\text{cc}}$ & Convective core mass & M$_{\\odot}$ \\\\\nX$_{\\text{surf}}$ & Surface hydrogen mass fraction & \\\\\n$Y_{\\text{surf}}$ & Surface helium mass fraction & \\\\\nX$_c$ & Central hydrogen mass fraction & \\\\\n$L$ & Luminosity & L$_{\\odot}$ \\\\ \n$R$ & Radius & R$_{\\odot}$ \\\\[8pt]\n%X & Hydrogen mass fraction & \\\\ \n%Y & Surface helium mass fraction & \\\\[8pt] \n%\\hline\n\\multicolumn{3}{l}{Classical Observables} \\\\\n$[\\text{Fe/H}]$ & Surface metallicity & \\\\\n$\\log{} g$ & Logarithmic surface gravity &  \\\\ %cm s$^{-2}$ \\\\ \n$T_{\\text{eff}}$ & Effective temperature & K \\\\[8pt]\n\n%\\hline\n\\multicolumn{3}{l}{Asteroseismic Observables} \\\\\n$\\nu_{\\max}$ & Frequency of maximum oscillation power & $\\mu$Hz \\\\\n$\\langle\\Delta\\nu_0\\rangle$ & Large frequency separation ($\\ell=0$) & $\\mu$Hz \\\\\n$\\langle\\delta\\nu_{02}\\rangle$ & Small frequency separation ($\\ell=0,2$) & $\\mu$Hz \\\\\n$\\langle\\delta\\nu_{13}\\rangle$ & Small frequency separation ($\\ell=1,3$) & $\\mu$Hz \\\\\n$\\langle r_{02}\\rangle$ & Frequency separation ratio ($\\ell=0,2$) &  \\\\\n$\\langle r_{13}\\rangle$ & Frequency separation ratio ($\\ell=1,3$) &  \\\\\n$\\langle r_{01}\\rangle$ & Frequency average ratio ($\\ell=0,1$) & \\\\\n$\\langle r_{10}\\rangle$ & Frequency average ratio ($\\ell=1,0$) & \\\\[8pt]\\hline \n\\end{tabular}\n}\n\\caption{Definitions of the quantities analyzed in this study separated into four parts: model input parameters, stellar attributes, classical observables, and asteroseismic observables. \nAsteroseismic definitions are in Appendix \\ref{sec:sdefs}. \nAngled parenthesis indicate the quantity is a calculated weighted median.} \n\\label{tab:parmdefs} \n\\end{table} \n\n\n\nWe used  \\emph{Modules for Experiments in Stellar Astrophysics} \\citep[MESA,][]{2011apjs..192....3p} to generate a grid of stellar evolutionary sequences initially for the purpose of training a random forest. The tracks are varied in initial mass $M$, helium $Y_0$, metallicity $Z_0$, mixing length parameter $\\alpha_{\\text{MLT}}$, overshoot coefficient $\\alpha_{\\text{ov}}$, and atomic diffusion multiplication factor $D$ (see BA1 Section~2.1 for details).\nInitial model parameters were chosen in a quasi-random fashion from the parameter ranges listed in Table~\\ref{tab:prange}.\nIn total $5325$ evolutionary tracks were evolved from ZAMS to either an age of ${\\tau=15}$~Gyr or until terminal-age main sequence (TAMS), which we define as having a fractional core-hydrogen abundance $X_{\\text{c}}$ below $10^{-3}$. We conduct our analysis on a subset of stellar models chosen from each sequence so not to bias our statistics towards longer lived stars or numerically challenging evolutionary tracks. \nDetails of the choice of input physics, grid generation strategy, and model selection procedure are further outlined in BA1. \nIn addition to computing the stellar structure we post process  each model with  the ADIPLS pulsation package \\citep{2008Ap&SS.316..113C}.  P-mode oscillations up to spherical degree ${\\ell=3}$ below the acoustic cut-off frequency are computed, and from these, frequency separations and separation ratios calculated (see Appendix \\ref{sec:sdefs} for mathematical definitions). \n\n\nThere are many quantities that could be included in the current analysis. \nThe $25$ parameters we have selected to investigate are listed in Table~\\ref{tab:parmdefs}. \nThey  comprise key asteroseismic and structural quantities and reflect our focus on characterizing the relationships between observable quantities (observables hereinafter) and those variables that allow us to generate detailed stellar models. \n\n\n\\begin{table}\n\\centering\n\\begin{tabular}{llll}\n\\hline \\hline\nParameter\t&\tMin Value\t&\tMax Value\t&\tVariation \t\\\\ \n\\hline \nMass\t&\t0.7\t&\t1.6\t&\tlinear\\\\\n$Y_0$\t&\t0.22\t&\t0.34\t&\tlinear\\\\\n$Z_0$\t&\t$10^{-5}$\t&\t$10^{-1}$\t&\tlogarithmic\\\\\n$\\alpha_{\\text{MLT}}$\t&\t1.5\t&\t2.5\t&\tlinear\\\\\n$\\alpha_{\\text{ov}}$\t&\t$10^{-4}$\t&\t1\t&\tlogarithmic\\\\\nD\t&\t$10^{-6}$\t&\t$10^{2}$\t&\tlogarithmic\t\\\\\n\\hline\n\\end{tabular}\n\\caption{Ranges and sampling strategy for the initial model parameters in the BA1 grid.}\n\\label{tab:prange}\n\\end{table}\n\nWe consider two parameters not included in the RF training data. \nBA1 elected to omit the frequency of maximum oscillation power, $\\nu_{\\max}$ (Equation~\\ref{equ:nmax}), in their regression model\\footnote{$\\nu_{\\max}$ does have some role in the algorithm developed by BA1, as it is responsible for the location of the Gaussian envelope used to weight and derive averaged/median frequency separations.}. This quantity displays a strong correlation with ${\\langle\\Delta\\nu_0\\rangle}$  (see Figure~\\ref{fig:filt_corr}  or \\citealt{2009A&A...506..465H,2009MNRAS.400L..80S}) and thus offers very little additional information when frequencies are known. \nWe include it in the current analysis because $\\nu_{\\max}$ is the simplest global asteroseismic parameter to extract from time-series observations, and because recent work by Theme{\\ss}l~et~al.~(private communication) indicates that the $\\nu_{\\max}$ scaling relation more accurately reproduces stellar parameters in well-constrained binary systems than the ${\\langle\\Delta\\nu_0\\rangle}$ relation (Equation~\\ref{equ:dnu}). This is despite the fact that ${\\langle\\Delta\\nu_0\\rangle}$ can be measured more precisely and that the relation can be corrected for temperature and metallicity dependencies (Equation~\\ref{eq:corrfunc2}) to yield greater accuracy \\citep{2016MNRAS.460.4277G, 2016ApJ...822...15S}. \n\nTo complement $\\tau$, we have also added normalized main-sequence age, $\\tau_{\\text{MS}}$, which describes how parameters change as a function of stellar evolution. \nMany low-mass stars in the grid do not reach the terminal-age main sequence (TAMS) before their evolution is stopped. \nTheir main-sequence lifetime is estimated by linearly extrapolating the rate at which the central hydrogen is depleted,\n\\begin{equation}\n\\tau_{\\text{TAMS}} =  \\frac{\\tau_{\\text{last}}}{1-(X_{\\text{c, last}}/X_{\\text{c, init}})}\n\\end{equation}\nwhere $\\tau_{\\text{TAMS}}$ is the TAMS age,  $\\tau_{\\text{last}}$ is the age of the last model in  the track,  $X_{\\text{c, last}}$ is the corresponding core-hydrogen abundance for that model and $X_{\\text{c, init}}$ is the core-hydrogen abundance of the initial model in that track. \nFor the longest-lived stars we find such an extrapolation is within about  $25\\%$ of the true TAMS age. The uncertainty in the extrapolation for these stars stems from the fact we only capture the hydrogen depletion in the early part of the main sequence i.e., when  ${X_{\\text{c, last}} > 0.3}$.  Estimating the TAMS age in this manner, however,  will not impact our conclusions.\nLarge discrepancies are limited to a small number of tracks (192) and differences between the true and extrapolated ages are reduced as ${X_{\\text{c, last}} \\to 0}$. \nMain sequence lifetime  provides insight into the general correlations that develop as a function of main-sequence stellar evolution. Thus it is the monotonicity of $\\tau_{\\text{MS}}$ within a given track that is key.  The stellar age parameter, on the other hand, is useful for exploring correlations across the whole parameter space. \n\n\n\\needspace{5\\baselineskip}\n\\section{Rank Correlation Test}\n\\label{sec:RCT}\n\n\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=0.6\\linewidth]{HRD6.png}\n    \\caption[Hertzsprung-Russell diagram for the grid of models]{Hertzsprung-Russell diagram for those tracks in the truncated grid (see text for details). Here each model is coloured by stellar radius.}\n    \\label{fig:HRDRad}\n\\end{figure}\n\n\n\n\\begin{figure*}\n    \\centering\n    \\includegraphics[trim={1.5cm 0 2cm 1cm},clip, width=\\textwidth]{filter-corr-spearman2.pdf}\n    \\caption[Rank correlation diagram]{Spearman rank correlation matrix comprising various stellar and asteroseismic parameters. The quantities are as described in Table~\\ref{tab:parmdefs}\n    with model input parameters marked in green.\n    The size and the color of each circle both indicate the magnitude of the Spearman coefficient with red and blue denoting negative and positive correlations respectively.  The presence of a cross indicates that \nthe two parameters have failed our significance test; i.e., the correlation is indistinguishable from nil. \nThe variables are ordered according to their correlation with the first eigensolution of the correlation matrix$^2$.}\n    \\label{fig:filt_corr}\n\\end{figure*}\n\n%No support for footnote in caption. This footnote corresponds to the $^2$ in figure \\ref{fig:filt_corr} above\n\\footnotetext{As principal component analysis is the eigensolution of the correlation (or covariance) matrix, the first eigenvalue indicates the maximum variance in the variables that can be accounted for by a linear model with a single underlying `factor.'\nOrdering the parameters in this way  demonstrates the direction of the first principal component (PC$_1$) vector. Figure~\\ref{fig:filt_corr} thus  offers a visual representation of principal component analysis which we employ in Section~\\ref{sec:PCA}.}\n\nWe begin our analysis with a rank correlation test, the purpose of which being to understand the \nstatistical properties of the collective lower main sequence.\nThis is distinct from typical analyses that focus on the evolutionary properties within \nindividual stellar tracks or chemically homogeneous isochrones. By identifying correlations present across the entire parameter space we reveal exploitable relationships available to model fitting and regression methods. \n\n\nSince many quantities (see Table~\\ref{tab:parmdefs}) are known to vary in a highly non-linear fashion, we opt to study \\emph{rank} statistics. In particular, we replace each quantity by its rank, i.e., an integer representing how big or small a particular quantity is compared to the other models; and calculate Spearman's correlation coefficient $\\rho$ between all variables. We further calculate the significance of these correlations (p-values) using the Spearman $\\rho$ test. We adopt a conservative significance cut-off of ${\\alpha = 10^{-5}}$ and use the Bonferroni correction to account for the fact that we are making multiple ($625$) comparisons \\citep[e.g.,][]{doi:10.1080/01621459.1955.10501294}. \n\nThis analysis allows us to determine whether quantities vary monotonically in the same direction (${\\rho \\approx 1}$), i.e.~both increasing or both decreasing; monotonically apart (${\\rho \\approx -1}$), i.e.~one increases while the other decreases; or neither (${\\rho \\approx 0}$)\\footnote{Spearman's~$\\rho$ is equivalent to Pearson's~$r$ on ranked quantities. We note also that ${\\rho = 0}$ does not necessarily indicate a  relationship does not exist; simply that the relationship is not monotonic. A parabolic function for example would result in ${\\rho = 0}$.}. When $\\abs{\\rho}$ is nearly one, the information from one parameter can be used to determine information about the other. Therefore, this is a valuable tool for probing the relationships that exist in and across evolutionary tracks and determining which model properties can be inferred from which observable quantities. \n\nIn the current analysis, we are strictly interested in the relationships expected from the observational data. We apply cuts to the grid computed by BA1 as it spans a wide parameter range\\footnote{When training a RF for the purposes of characterizing stellar systems,  sampling the parameter space well beyond the expected ranges of each quantity is prudent. RFs do not extrapolate---doing so would be undesirable anyway---so characterizing a star requires that all of its observations are firmly within the boundaries of the grid used to train the RF. Doing this furthermore avoids pre-conceived biases in the analysis: it allows the observations to dictate the interesting regions of the parameter space rather than limiting the ranges to the values we \\emph{expect} the parameters to take.}. The full set of tracks in the BA1 grid includes models with temperatures exceeding the limit in which solar-like oscillations are thought to develop (${ T_{\\text{eff}} \\approx 6700}$~K, i.e., the approximate surface temperature beyond which the stellar envelopes are radiative rather than convective). \nEvolutionary tracks in the training grid with more than half of the constituent models having $T{_{\\text{eff}} > 6700}$~K are excluded from the rank correlation analysis.\nNote that the grid will still contain models with $T{_{\\text{eff}} > 6700}$~K if more than half the models in a track display temperatures below this cutoff; there is some chance we may observe such stars. \nLikewise, we omit tracks where high atomic-diffusion rates significantly drain metals from the surface, i.e., tracks where more than half the models display surface-hydrogen mass fractions ${> 0.95}$. The dearth of stars observed at zero metallicity indicates that there are some physical processes not included in our models (e.g., radiative levitation or turbulent diffusion) which inhibit the unabated flow of metals from the stellar surface.\nThis is a common result in models of high-mass stars that include gravitational settling and therefore the process is \\emph{ordinarily} suppressed once  ${M \\gtrsim 1.1\\;M_{\\odot}}$. Metal depletion may also arise in cases when settling is made to operate extremely efficiently. \nThe removal of these sequences reduces the BA1 training set from $5325$ to $2010$ evolutionary tracks (truncated grid hereinafter) for the current analysis. \nIn Figure~\\ref{fig:HRDRad} we plot the truncated grid in the HR diagram and color the models according to radius.  \n\n\n\nFigure~\\ref{fig:filt_corr} shows the results of the correlation analysis for the truncated grid.\nWe defer correlation analysis on the full grid of models to Appendix \\ref{sec:fullcorr}. \nCare is needed when interpreting Figure~\\ref{fig:filt_corr}. \nFirst, it is important to remember that correlation is not transitive\\footnote{This is irrespective of whether one is using Pearson's~$r$, Spearman's~$\\rho$ or Kendall's~$\\tau$.} \\citep{lang}, i.e.,\n\\begin{equation}\n\\corr(X,Y) \\wedge \\corr(Y,Z) \\not \\Rightarrow \\corr(X,Z)\n\\end{equation}\neven when the correlations are due to causative relationships \\citep{stav}.\nIn fact one can only draw inference on the direction of ${\\corr(X,Z)}$ in cases when \n\\begin{equation}\n\\rho_{X,Y}^2 + \\rho_{Y,Z}^2 > 1\n\\end{equation}\n(transitive criterion hereinafter).\n\nSecond, recall that these correlations hold only for the main sequence. During the main sequence there is generally a positive correlation between, say, $L$ and $T_{\\text{eff}}$. \nThis relationship will change as the stars evolve further beyond the main-sequence turnoff. \n\nThird, save for correlations with $\\tau_{\\text{MS}}$, the relationships presented here do not describe how parameters correlate internally throughout an evolutionary track. Rather, they describe how they correlate across \\emph{all} tracks. For example, as a star ascends the main sequence, luminosity increases and therefore one may expect a strong positive correlation between $\\tau$ and $L$. The fact that we report a negative correlation is because higher-mass stars are shorter lived -- thus high $L$ corresponds to a lower $\\tau$  when the whole parameter space is considered. This correlation is in fact stronger in the analysis of the complete grid used in BA1 which we report in Appendix \\ref{sec:fullcorr}, as our grid truncation preferentially selects against higher-mass stars. \nFurthermore we note that some initial model variables ($M$, $Y_0$, $Z_0$, $\\alpha_{\\text{MLT}}$, $\\alpha_{\\text{ov}}$ and $D$; all indicated in green) correlate with other parameters.  This would not be the case if we reported correlations within tracks, as these parameters do not change within a given track. \n\nIt should be noted that there is some bias present in the grid as the low-mass stars are not computed to the end of their main-sequence lifetime. The strengths of some correlations would change had we considered evolution beyond the age of the Universe. \n\\subsection{Interpreting the Correlations}\nHaving set the general context in which to interpret Figure~\\ref{fig:filt_corr}, we highlight some statistical features of the lower main sequence that can be extracted: \n\n\\begin{itemize}\n\\item Most pairs of parameters with ${| \\rho | \\approx 1}$ correspond to well known main-sequence and/or asteroseismic relations. Pairs displaying strong correlations include:\n\n%\\begin{math}\n%\\langle\\Delta\\nu_0\\rangle  -  \\log{} g; \\qquad   \\langle\\Delta\\nu_0\\rangle - \\nu_{\\max}; \\qquad     \\log{} g  - \\nu_{\\max};  \\\\\n%\\langle\\Delta\\nu_0\\rangle  -  R;   \\qquad   \\qquad     \\log{} g - R;            \\qquad              \\qquad   M  -  R;  \\\\\n% L - R; \\qquad \\quad  \\qquad\\langle\\delta\\nu_{02}\\rangle - X_c.\n%\\end{math}\n\\begin{tabular}{lll}\n  $\\langle\\Delta\\nu_0\\rangle  -  \\log{} g$; \n& $\\langle\\Delta\\nu_0\\rangle - \\nu_{\\max}$; \n& $\\log{} g - \\nu_{\\max}$;  \\\\\n  $\\langle\\Delta\\nu_0\\rangle - R$; \n& $\\log{} g - R$; \n& $M  -  R$;  \\\\\n  $L - R$; \n& $\\langle\\delta\\nu_{02}\\rangle - X_c$. \n&\n\\end{tabular}\n\n\\item Figure~\\ref{fig:HRDRad} illustrates why $T_{\\text{eff}}$ and its correlations with $R$ and $L$ are weaker than those listed above. \nMany of the tracks evolve past the main-sequence turn off before exhausting their core-hydrogen abundance. The change in morphology of the HR diagram and resultant increase in radius impacts on the monotonicity of the respective correlations. \n\n \n\n\\item The mass of the convective core (M$_{\\text{cc}}$) displays a moderate negative correlation with age whereas it barely registers a relationship with $\\tau_{\\text{MS}}$. \nIt is the higher-mass and hence shorter-lived stars that preferentially develop convective cores. A negative correlation with age is therefore according to expectations.  \nIn stars that burn hydrogen radiatively no correlation will develop between M$_{\\text{cc}}$ and $\\tau_{\\text{MS}}$. \nIn those stars that burn convectively, the size of the convective core will grow but then recede as the CNO-burning region becomes more centrally condensed. \nThese two factors lead to an (essentially) null result between M$_{\\text{cc}}$ and $\\tau_{\\text{MS}}$. \n\n\n\\item The correlations between $\\tau$ and the ratios ${\\langle r_{02}\\rangle}$ and ${\\langle r_{13}\\rangle}$ are stronger than the correlation between $\\tau$ and  X$_c$. \nThe grid comprises large ranges in mass and metallicity and hence stars at different ages can possess the same X$_c$, thereby weakening the strength of that correlation.\nConversely, as one might expect,  $\\tau_{\\text{MS}}$ exhibits a stronger relationship with X$_c$ than the ratios. \n\n\\item The small frequency separations and the asteroseismic frequency ratios strongly correlate with both $\\tau$ and X$_c$. The large frequency separation, however, demonstrates a much stronger correlation with X$_c$ than it does with $\\tau$. The rate at which stars burn their central fuel will largely depend on their mass, thus the \nmodels can attain the same density (which is proportional to the large frequency separation) at a range of ages. Both $\\tau_{\\text{MS}}$ and X$_c$ are evolutionary variables and display the expected correlations with ${\\langle\\Delta\\nu_0\\rangle}$. \n\n\\item We lack the necessary information to constrain some of the initial model variables. Indeed ${[\\text{Fe/H}]}$ provides some constraints on the diffusion efficiency factor $D$, but there is much degeneracy: a model can attain the same surface Y starting with a low ${[\\text{Fe/H}]}$ and low diffusion rate as a track with a high ${[\\text{Fe/H}]}$ and high diffusion rate. It is possible that fitting for the base of the convective envelope through seismic analysis of the acoustic glitch signal \\citep{2014ApJ...782...18M, 2014ApJ...794..114V} could help further constrain these parameters. \n\n\n\\end{itemize}\n\nFigure~\\ref{fig:filt_corr} immediately reveals information about the relationships utilized in the machine learning algorithms. \nFor those parameter pairs that failed the significance test, neither is likely to feature in the regression model that predicts the other, except in a circumstance where a subset of models exhibit a trend that is absent from the general case of all the models being considered together.\nConversely, where possible, the regressor will attempt to draw on information from pairs that display the strongest correlations.\nQuantities such as radius illustrate that there is indeed redundant information in independently measured parameters.\nThis is useful as the observables measured, and their corresponding accuracy, will vary from survey to survey. \nIf a key piece of datum is missing or unreliable, a new regression model can be trained using an appropriate substituted quantity in its place.   \nThis requires that the redundant information in the observables are treated correctly, if however they are not, then they will lead to biases in model finding procedures. We explore this point further in the next section.  \n\n\n\\section{Principal Component Analysis}\n\\label{sec:PCA}\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=0.8\\linewidth]{PCA_CUMUL3.pdf}\n    \\caption[Explained variance of principal components]{{The explained variance (Ve$_{\\,\\text{pca}}$) and cumulative Ve$_{\\,\\text{pca}}$ of the principal components comprising the \\emph{observable} quantities listed in Table~\\ref{tab:parmdefs}. The figure demonstrates that  $98\\%$ of the variance in the $11$ observational parameters can be explained by four independent components and $99.2\\%$ of the variance explained when a fifth component is considered. The Ve$_{\\,\\text{pca}}$ of each component is  also presented in the second column of Table~\\ref{tab:PCAEV}. }}\n    \\label{fig:GCA-pca}\n\\end{figure}\n\n\n\\begin{figure} \\centering\n\\includegraphics[width=0.7\\textwidth]{barchart2a.pdf}%\n\\caption[Correlation between principal components and stellar observables]{ Pearson correlation strength between the first five principal components and the stellar observables.  Quantities are ordered according to their correlation strength with the first principal component.  Strong correlations indicate that much of the variance of the quantity is captured by the given PC. Note that the ordinate axes in this figure are on different scales. }\n\\label{fig:GCA-pcabar}\n\\end{figure}\n\n\\begin{figure} \\centering\n\\includegraphics[width=0.7\\textwidth]{barchart3a.pdf}%\n\\caption[Correlation between principal components and model parameters]{ Pearson correlation strength between the first five principal components and the model parameters (\\emph{cf.} Figure~\\ref{fig:GCA-pcabar}). }\n\\label{fig:GCA-pcabarb}\n\\end{figure}\n\n\n\n\\iffalse\n\\begin{figure} \\centering\n%\\gridline{\\fig{barchart2a.pdf}{0.48\\textwidth}{\\qquad \\qquad (a)}\n%          \\fig{barchart3a.pdf}{0.48\\textwidth}{\\qquad \\qquad (b)}}\n\\includegraphics[width=0.5\\textwidth]{barchart2a.pdf}%\n\\includegraphics[width=0.5\\textwidth]{barchart3a.pdf}%\n\\caption{ Pearson correlation strength between the first five principal components and (left) the stellar observables and (right) the model parameters.  Quantities are ordered according to their correlation strength with the first principal component.  Strong correlations indicate that much of the variance of the quantity is captured by the given PC. Note that the ordinate axes in this figure are on different scales. }\n\\label{fig:GCA-pcabar}\n\\end{figure}\n\n\n\\afterpage{\n\\clearpage\n\\begin{landscape}\n\\begin{figure} \\centering\n%\\gridline{\\fig{barchart2a.pdf}{0.48\\textwidth}{\\qquad \\qquad (a)}\n%          \\fig{barchart3a.pdf}{0.48\\textwidth}{\\qquad \\qquad (b)}}\n\\includegraphics[height=\\textwidth,angle=-90,origin=c]{barchart2a.pdf}\\\\\n\\includegraphics[height=\\textwidth,angle=-90,origin=c]{barchart3a.pdf}%\n\\caption{ Pearson correlation strength between the first five principal components and (left) the stellar observables and (right) the model parameters.  Quantities are ordered according to their correlation strength with the first principal component.  Strong correlations indicate that much of the variance of the quantity is captured by the given PC. Note that the ordinate axes in this figure are on different scales. }\n\\label{fig:GCA-pcabar}\n\\end{figure}\n\\end{landscape}\n}\n\\fi\n\n\n\\iffalse\n\\begin{figure}\n    \\centering\n        \\includegraphics[width=\\columnwidth]{figs/GCA/barchart2a.pdf}\n    \\caption{Pearson correlation strength between the stellar observables and first five principal components. Parameters are ordered according to their correlation strength with the first principal component.  Strong correlations indicate that much of the variance of the quantity is captured by the given PC. Note that the ordinate axes in this figure are on different scales. }\n    \\label{fig:GCA-pcabar2}\n\\end{figure}\n\n\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=\\columnwidth]{figs/GCA/barchart3a.pdf}\n    \\caption{Pearson correlation strength between the model parameters and first five principal components. Parameters are ordered according to their correlation strength with the first principal component. Strong correlations indicate a significant degree of linearity exists between the quantity and the observables. Note that the ordinate axes in this figure are on different scales.} \n    \\label{fig:GCA-pcabar3}\n\\end{figure}\n\n\\fi\n\nPast studies, particularly \\citet{1994ApJ...427.1013B}, have argued that redundancies and covariances in the stellar observables should be taken into account during any model fitting procedure. \nThey demonstrated one particular method (singular value decomposition, SVD hereinafter) of avoiding such biases. In the previous section we identified correlations present in the lower main sequence. Here we demonstrate the degree of redundant information contained in the observables by applying dimensionality reduction. \nWe perform principal component analysis (PCA) in order to discover latent structure in observable stellar quantities such that they may be related more directly---and without redundancy---to parameters of stellar modelling. \nThrough the principal components (PCs) we quantify the extent to which the observables capture information of the model parameters.\n\n\nA natural strategy for dealing with high-dimensional data is to reduce the dimensionality in search of \\emph{latent variables}; i.e., hidden variables that are more useful than the original quantities under consideration. \nPrincipal component analysis (PCA) is a technique to transform data into a sequence of orthogonal, and hence independent,  linear combinations of the variables.\nEach successive component is constructed to maximize the residual variance from the original data whilst remaining orthogonal to the previous components.\nIt is a linear transformation in which the change of basis captures the variance contained in original data. \nIf parameters in the data are highly correlated, then PCA can potentially produce a lower-dimensional representation without significant loss of the information. \nThe method can therefore introduce a new set of variables capable of revealing the underlying structure of an originally high-dimensional space.\n\n \n\nPCA  belongs to a family of matrix decomposition techniques that also include methods such as non-negative matrix factorization and independent components analysis as well as variations such as sparse PCA and kernel PCA. \nIt has previously been employed in an astrophysical context \\citep{2008ApJ...686.1349B, 1987ASSL..131.....M} along with SVD \\citep{1994ApJ...427.1013B, 2009ApJ...699..373M} to handle correlated errors in observational data. \nThe PCs in this work are calculated from the eigensolution of the correlation matrix, the results of which are not scale invariant. \nWe note that PCA can be interpreted as the singular value decomposition of a data matrix in cases where the columns have first been centered by their means. \nThus SVD analysis\\footnote{This method is in fact more numerically stable but more computationally expensive for extracting PCs.} is an alternative method for extracting the PCs (see also Appendix \\ref{sec:lambdaa}). \nWe indeed compare both methods as a check on our methodology and find that the magnitude of PC scores are identical although the direction (sign) of the vector may differ on occasion.\n\n\n\n\n\n\\subsection{Explained Variance of the Principal Components}\n\\label{sec:ev}\nWe perform PCA on $11$ classical and asteroseismic observables listed in Table~\\ref{tab:parmdefs}.\nThe chosen parameters reflect the quantities typically  extracted\\footnote{Radius and luminosity are in some cases observable, but not ubiquitously available in the pre-GAIA era. We concede that the inclusion of ${\\ell=3}$ modes is an optimistic assumption.} from stars in the \\emph{Kepler} \\citep{2004SPIE.5487.1491K,2010Sci...327..977B} field.\nOur analysis focuses on the  truncated grid of models\\footnote{To extract a robust interpretation of the PCs we consider different subsets of the BA1 grid (see Appendix \\ref{sec:fullPCA}).} (see Section~\\ref{sec:RCT}).\nThe truncated grid reduces our matrix to size ${128640 \\times 11}$ on which we perform the PCA (there are $340,800$ models in the full BA1 grid). \n\nThe PCs throughout this analysis are calculated from the eigendecomposition of observables in the correlation matrix. Here we wish to explain the variance in the data values rather than their rankings. \n We employ Pearson's~$r$ in the computation of the correlation matrix for the PCA analysis rather than Spearman's~$\\rho$. This allows us to transform freely back and forth between the original data space and the space of Pearson PCs.  \n \nA given data matrix $\\mathbf{X}$ (grid) is of size ${n \\times p}$ where $n$ is the number of models  and $p$ is the number of observable parameters. \nEach entry $x_{np}$ in $\\mathbf{X}$ is centered and scaled such that \n\\begin{equation}\n\\bar{x}_{np} = (x_{np} -\\hat{x_n})/\\sigma_{x_n}\n\\end{equation}\nwhere $\\bar{x}_{np}$ is the centered and scaled value,  $x_{np}$ is the original entry, $\\hat{x}_n$ is the mean of the particular parameter and $\\sigma_{x_n}$ is its standard deviation. \nWith all variables having zero mean and unit variance ($\\mathbf{\\bar{X}}$), our analysis is equivalent to performing eigendecomposition on the covariance matrix\\footnote{We are essentially performing the eigendecompostion of the normalized covariance matrix.}. \nWe compute $\\boldsymbol\\Sigma$, the matrix of Pearson's~$r$  coefficients, between all entries in $\\mathbf{\\bar{X}}$; and compute the eigenvalues and eigenvectors of $\\boldsymbol\\Sigma$ to determine the PCs.\nThe eigenvalues, $\\lambda_i$, of $\\boldsymbol\\Sigma$ indicate the absolute variance explained by the eigenvectors. We use this to compute the fraction of variance explained by the eigenvector in the dataset, Ve$_{\\, \\text{pca}}$, such that:\n\\begin{equation}\n\\text{Ve}_{\\, \\text{pca}} \\ (\\text{PC}_i)=\\frac{\\lambda_i}{\\sum_{i=1}^p \\lambda_i}, \n\\label{eqn:pcaev}\n\\end{equation}\nwhere the number of observables in the data matrix, $p$, is equivalent to the number of principal components we extract.\n\n\n\n\nThe Ve$_{\\,\\text{pca}}$ and the cumulative explained variance of the PCs are reported in Figure~\\ref{fig:GCA-pca} (see also the second column in Table~\\ref{tab:PCAEV}).\nRemarkably, we find that $99.2\\%$ of the variance in our 11-dimensional observable space can be explained by a space of five components.\nHence, observable stellar quantities are clearly highly redundant in what they reveal, as only five dimensions contain original information about the star. \n\n\nFurther insight into the PCs can be gained through correlation analysis between the transformed data (i.e., data matrix projected onto the new PC features) and the original data matrix of observables.\nAny observable that correlates with a PC contributes to the linear combination of parameters that comprise that PC -- the PC is capturing part of the variance in that observable/dimension. \nMultiple parameters that simultaneously have a large fraction of their variance explained by the same PC, must therefore carry redundant information about the star\\footnote{The correlation analysis is in general similar to reporting the PC loadings. \nIn PCA loadings are the elements of the eigenvector scaled by the square roots of the respective eigenvalues.\nThe elements of the eigenvector are coefficients that indicate the weighting of the original data parameters that combine to form that PC. \nAs we have centred and scaled the data before performing the PCA, the correlation coefficients are equivalent to the loadings.}.\nIn Figure~\\ref{fig:GCA-pcabar} we quantify, through Pearson's~$r$ coefficient, the extent to which each observable correlates with the first five PCs.\nThe parameters in the top panel of Figure~\\ref{fig:GCA-pcabar} are ordered by their correlation with the first principal component. \nPC$_1$ accounts for a significant fraction of the variance in the observables (Ve${_{\\, \\text{pca}}=42.36\\%}$). \nThe top panel of  Figure~ \\ref{fig:GCA-pcabar} reveals that this component correlates very strongly \n(${r > 0.85}$)  with   \n$\\nu_{\\max}$, \n${\\langle\\Delta\\nu_0\\rangle}$,\n${\\langle\\delta\\nu_{02}\\rangle}$, \n${\\langle\\delta\\nu_{13}\\rangle}$,\nand ${\\log{} g}$.  \nThe strong correlations imply that the basis vector captures most of the variance across the five parameters simultaneously and points to a common latent variable. \n\n\n\\subsection{Interpreting the Principal Components}\n\\label{sec:intPC}\n\n\nIn Figure~ \\ref{fig:GCA-pcabar} and Figure~\\ref{fig:GCA-pcabarb} we plot the results of correlation analysis between all parameters in the grid and the transformed observables (PCs). \nThe figures offer a quantitative overview of the PCs allowing  us to identify what interpretable features the PCs have captured.\nWe have seen that Figure~\\ref{fig:GCA-pcabar} demonstrates the extent to which each observable correlates with the first five PCs, similarly  Figure~\\ref{fig:GCA-pcabarb} demonstrates how the principal components correlate with the model parameters. The corresponding correlation coefficients between the parameters and \\emph{all} PCs are listed in Tables \\ref{tab:ocoefs} \\& \\ref{tab:mcoefs}.\n\nAny interpretation of the PCs based on Figures \\ref{fig:GCA-pcabar} and \\ref{fig:GCA-pcabarb} are only valid for the truncated grid of models to which this PCA has been applied. For results on other sub grids we refer the reader to Appendices \\ref{sec:fullPCA} and \\ref{sec:PCAg}. \nWe draw upon the figures for generality in the discussion section (Section~\\ref{sec:disc}).\n\n\nInformation about \\emph{direct} correlations between parameters can be extracted from PCA which further helps with interpreting the underlying features.\nAny two parameters that correlate with a given principal component and meet the transitive criterion will be positively correlated if they both have the same sign with respect to the PC, and negatively correlated if their signs differ. \n\nAs is often the case with PCA, the first few principal components can be interpreted as describing the large-scale physical behavior of the system.\nWe interpret that the underlying feature that PC$_1$ captures is straightforwardly the stellar radius.  \nThis is the physical property that has the greatest impact on the observables.\nFrom PC$_1$ in Figures \\ref{fig:GCA-pcabar} and \\ref{fig:GCA-pcabarb} we can infer (from the transitive criterion) that as a star evolves along the main sequence, i.e., $\\tau_{\\text{MS}}$ increases or $X_c$ decreases, radius (and for the most part L) will increase.  \nThe consequence of increasing radius being $\\nu_{\\max}$, \n${\\langle\\Delta\\nu_0\\rangle}$,\n${\\langle\\delta\\nu_{02}\\rangle}$, \n${\\langle\\delta\\nu_{13}\\rangle}$,\n ${\\log{} g}$ all decrease and thus their variance is explained by PC$_1$. \nWe note that this PC also correlates with $M$ as stars with larger $M$ will have larger radii.  \n\n\nPC$_2$ can be interpreted as a `core-surface' feature.\nPC$_2$ correlates strongly with different combinations of seismic ratios and small frequency separations. % across the four grids.\nWith strong weightings from the core it is no surprise that PC$_2$ features a moderate-to-strong correlation with $\\tau$.  \nThis direction of maximal variance comprises information from all the observables and correlates with (mostly) all the dependent model variables further suggesting some form of time evolution. \nThe information from the surface is provided by $T_{\\text{eff}}$.  \nThere is a degree to which the variance in $T_{\\text{eff}}$ is captured by the time-evolutionary aspect of this component. \nHowever PC$_2$ also displays a moderate correlation with the time-independent $Z_0$ and thus there is a second aspect to  PC$_2$.\n$Z_0$ dictates the temperature at the surface through opacities and nuclear burning in the core.\n\nPC$_3$ appears to have the role of capturing the more extreme models in the grid. \nIn the truncated grid the correlations with $[\\text{Fe/H}]$ and $T_{\\text{eff}}$ suggest that the focus of this PC to account for the variance in the observations imparted by low-metallicity models. \n\nPC$_4$ appears to be a secondary `core-surface' feature much like PC$_2$.  \nIt uses surface information, in this case ${[\\text{Fe/H}]}$, in conjunction with some information from the core in the form of the ${\\langle r_{02}\\rangle}$ and ${\\langle r_{13}\\rangle}$ ratios.  \n\nPC$_5$ encapsulates the mixing processes that impact upon the surface abundances of the star but it is only required to explain a small fraction of the total variance in the data. \n\n\n\n\n\n\n\\subsection{Inferring Stellar Parameters} \n\\label{sec:ISP}\n\n\n\nThe dimensionality reduction achieved by the PCA quantifies the degree of redundancy in the stellar observables alluded to by Figure~\\ref{fig:filt_corr}. \nHowever, we also wish to quantify the extent to which the observed stellar properties constrain the internal structures and chemical mixtures of the star, i.e., the model properties. \n\n\nIn our application of RF regression the machine tries to fit for each model parameter, the success of which we can appraise (see Section~\\ref{sec:qu}). \nHere we conduct a more fundamental evaluation: how well can we capture the variance in the model parameters simply by explaining the variance in the observed data? \nIn other words: having removed the redundancies, to what extent is information of the model parameters encoded in the observables? We hence devise a score, $\\Lambda$, such that:\n\\begin{equation}\n   \\Lambda(X) = \\  \\sum^{p}_{i=1}  r(X, PC_i)^2\n\\end{equation}\nwhere $X$ is the parameter of interest, $p$ is the number of PCs ($11$ in our case)  and  ${r(X, PC_i)}$ is the Pearson coefficient between the parameter and the PC.\nAs we centred and scaled our data before computing the correlation matrix and extracting the PCs, the $\\Lambda(X)$ score is equivalent to summing the square of the PC loadings. The square of each loading indicates the variation in an observable that is explained by the component. A useful property of having scaled our data is that ${\\Lambda(X) =1}$  for each of our observables. We demonstrate these properties further in Appendix \\ref{sec:lambdaa}.\n\nIn Figure~\\ref{fig:GCA-pcabarb} we projected the parameter space of our model quantities onto the PC space.  Whilst these are not the optimum vectors to explain our model parameters, that is not their purpose; we instead wish to determine what we can learn about the model quantities by understanding the observables. \nAs the square of the correlation coefficients (loadings) will indicate the fraction of explained variance for the parameter by a given PC, determining the  \n$\\Lambda(X)$ score for the model parameters gives an indication of the extent the model data are retrievable from the observables.  \n\nIn Table~\\ref{tab:corrL} we list the $\\Lambda$ score for each of the model parameters in Table~\\ref{tab:parmdefs}. Parameters with larger $\\Lambda$ scores have much of their variance captured by the linear models used to explain the observables.  We expect  to be able to infer parameters such as $R$, $L$ and $\\tau_{\\text{MS}}$ with a great deal of confidence through regression. \nParameters with intermediate values of $\\Lambda$ ($\\tau$, M$_{cc}$) we can expect to recover with some success by employing more sophisticated modelling, however, it is not clear that there is enough information contained in the observables to always do so. In cases with the lowest values of $\\Lambda$, such as the initial model parameters $\\alpha_{\\text{MLT}}$, $Y_0$ and $\\alpha_{\\text{ov}}$, explaining the variance in the observables does not explain the variance in the model parameters. New observables that provide independent information about the star are required to recover these parameters with higher confidence. Fitting the acoustic glitch for example may (eventually) provide constraints on the degree of convective envelope overshoot or atomic diffusion \\citep{2017ApJ...837...47V}. \n\n\n\n\\begin{table}\n    \\centering\n    \\begin{tabular}{ccc}\n    \\hline \\hline\n   \nParameter &  & $\\Lambda_{\\text{param}}$ \\\\ \\hline     \nR\t&\t&\t0.97\t\\\\\nL\t&\t&\t0.96\t\\\\\n$X_c$\t&\t&\t0.94\t\\\\\n$\\tau_{\\text{MS}}$\t&\t&\t0.93\t\\\\\nM\t&\t&\t0.91\t\\\\\n$\\tau$\t&\t&\t0.79\t\\\\\n$Z_0$\t&\t&\t0.73\t\\\\\nM$_{cc}$\t&\t&\t0.61\t\\\\\n$Y_{\\text{surf}}$\t&\t&\t0.50\t\\\\\nX$_{\\text{surf}}$\t&\t&\t0.48\t\\\\\n$\\alpha_{\\text{MLT}}$\t&\t&\t0.38\t\\\\\n$Y_0$\t&\t&\t0.31\t\\\\\nD\t&\t&\t0.29\t\\\\\n$\\alpha_{\\text{ov}}$\t&\t&\t0.08\t\\\\\n \\hline\n    \\end{tabular}\n    \\caption{The $\\Lambda$ score is a sum of the squares of  $r_{\\text{PC, param}}$. Any parameter with high $\\Lambda$ is explained well by a linear model and can be confidently inferred. We have insufficient information to constrain those parameters with the lowest $\\Lambda$.}\n    \\label{tab:corrL}\n\\end{table}\n\n\n\n\\section{Quantifying the Utility of Stellar Observables} \n\\label{sec:qu}\n\nThere is certainly value and a degree of intuition in dimensionality reduction.\nPCA has demonstrated the significant information redundancy in our data. \nIt has also allowed us to identify information from the model parameters manifested in the observables, and indicated to what extent those parameters can be extracted.  \nWe now turn to another strategy of exploratory data science, which is to let machine learning algorithms fit complicated models to the data. As we shift our focus from \\emph{what} information is present to \\emph{how} it can be exploited, we transition from unsupervised to supervised learning methods. \n\n\nIn the PCA we determined orthogonal vectors that are the best fit to the observables. \nHere we utilize a RF to perform non-parametric, multiple regression in order to create the best functions capable of inferring each stellar parameter. With this particular form of supervised learning \nthe relationships between observables and model parameters remain hidden. Though some insight into the regression function can be gained through examination of the feature importances, the tree topology makes further interpretation difficult. \nWe thus seek to elucidate the RF's decision making processes by appraising\nhow well different combinations of parameters can predict the quantities in Table~\\ref{tab:parmdefs}. \n \n This approach not only illustrates the RF's ability to recover missing observational data, say for a rapid stellar evolution calculation, but also systematically \\emph{quantifies} the usefulness of each parameter in predicting all other quantities in the limit of perfect information. It is analogous to a seismic inversion in that it demonstrates the inherent uncertainty with which information can be reconstructed from the available observations. \nWhereas PCA serves to remove the redundant stellar information in the parameters, the analysis here is designed to highlight them. \n\nUsing the full grid of BA1 models, we perform multiple regression on every unique combination of observables in Table~\\ref{tab:parmdefs}. We omit those combinations that contain the quantity we are training for and include models with $R$ and $L$ as observables, resulting in the calculation of $49,153$ RFs. \n\n\nWe divide the full grid into a testing (${\\approx 15,000}$ models) and training set as per the method ascribed in Appendix D of BA1 so not to over-estimate the performance of the regression. \nWe perform two-fold cross-validation on each RF and, as in BA1, measure their success on the test data with an explained variance score, V$_{\\text{e}}$:\n\\begin{equation}\n\\label{eqn:ve}\n  \\text{V}_{\\text{e}} = 1 - \\frac{\\text{Var}\\{ y - \\hat y \\}}{\\text{Var}\\{ y \\}}.\n\\end{equation}\nHere $y$ is the \\emph{true} value we want to predict, $\\hat{y}$ is the predicted value from the random forest, and Var is the variance. This score tells us the extent to which the regressor has reduced the variance in the parameter it is predicting with a score of one implying that the model predicts all values with zero error. This is a different but equivalent definition by which to measure the same quantity in Equation~(\\ref{eqn:pcaev}). We have adopted the same notation as BA1 for evaluating the RF which we use to distinguish from the definition used in the PCA (Section~\\ref{sec:PCA}). We also provide a measure of the `typical' error in the predictions, ${\\mu (\\epsilon)}$,  which is calculated by averaging the absolute difference ($\\epsilon$) between the predicted and true values for each parameter. More formally: \n\\begin{equation}\n\\label{eqn:mu}\n    \\mu (\\epsilon) = \\frac{1}{n} \\sum^n_{i=1} | \\hat y_i - y_i |,\n\\end{equation}\nwhere $n$ is the number of models in the test data. Through ${\\mu (\\epsilon)}$  we provide an indicative error associated with the regression model, over the whole parameter space, and  in units of the quantity of interest.  \n\nThe best combinations of parameters for inferring each quantity of interest are listed in Table~\\ref{tab:regparms}. \nWe present combinations of up to five parameters after which there is negligible improvement to the predictions. \nWe mark with a dash the occasions where the regressor is unable to produce a positive $V_e$ score.  \nIt is important to remember that while a score of one implies a perfect predictor, any ${V_e < 1}$ implies there is still \\emph{some} error in the model.  We thus opt for truncation rather than rounding when listing the scores. \nPredictions of the seismic quantities are omitted here.  They strongly co-vary and are easily recovered when other seismic parameters are known; they are discussed separately in  Section~\\ref{sec:seispr}. \nTheir strong covariances also mean that many of the ratios and separations used in the regression models are interchangeable (e.g., ${\\langle r_{02}\\rangle}$ for \n${\\langle r_{13}\\rangle}$ or ${\\langle r_{01}\\rangle}$ for ${\\langle r_{10}\\rangle}$) resulting in negligible differences to our two scores. \n\n%\\clearpage\n\\afterpage{\n\\clearpage% To flush out all floats, might not be what you want\n\\begin{landscape}\n\\thispagestyle{lscape}\n\\pagestyle{lscape}\n%\\vspace*{5.5cm}\n%\\hspace*{-1.25cm}\n\\begin{table} \\scriptsize\n%\\begin{rotatetable}\n%\\begin{table}\n%\\tablewidth{700pt}\n%\\tabletypesize{\\scriptsize}\n%\\tabletypesize{\\tiny}\n\\caption{The best combinations of observables for constraining the non-seismic parameters in Table~\\ref{tab:parmdefs}. For each combination we provide the ${V_e}$ score (Equation~\\ref{eqn:ve}) and ${\\mu (\\epsilon)}$ score (Equation~\\ref{eqn:mu}, given in the units indicated by the predicted quantity column).\\label{tab:regparms}}\n\\iffalse\n\\tablehead{\n           \\colhead{Predicted}                                    &\n           \\multicolumn{3}{c}{One Parameter}               &\n           \\multicolumn{4}{c}{Two Parameters}               &\n           \\multicolumn{4}{c}{Three Parameters}               &\n           \\multicolumn{4}{c}{Four Parameters}               &\n           \\multicolumn{4}{c}{Five Parameters}        \\\\        \n           \\colhead{Quantity}                                          &        \n           \\colhead{Observable}    &  \n           \\colhead{$V_e$}    & \n           \\colhead{$\\mu (\\epsilon)$}    & \n           \\multicolumn{2}{c}{Observables} &\n           \\colhead{$V_e$}    & \n           \\colhead{$\\mu (\\epsilon)$}    & \n            \\multicolumn{2}{c}{Observables} &\n           \\colhead{$V_e$}    & \n           \\colhead{$\\mu (\\epsilon)$}    & \n            \\multicolumn{2}{c}{Observables} &\n           \\colhead{$V_e$}    & \n           \\colhead{$\\mu (\\epsilon)$}    & \n            \\multicolumn{2}{c}{Observables} &\n           \\colhead{$V_e$}    & \n           \\colhead{$\\mu (\\epsilon)$}     \n           }\n\\startdata\n\\fi\n\\hspace*{-1.25cm}\n\\begin{tabular}{  l | l  l  l | l  l  l  l | l  l  l  l | l  l  l  l | l  l  l  l   }\nPredicted   &\n\\multicolumn{3}{c|}{One Parameter}    &\n\\multicolumn{4}{c|}{Two Parameters}    &\n\\multicolumn{4}{c|}{Three Parameters}    &\n\\multicolumn{4}{c|}{Four Parameters}    &\n\\multicolumn{4}{c}{Five Parameters}        \\\\ \\cline{2-20}\nQuantity         &        \nObservable    &  \n$V_e$    & \n$\\mu (\\epsilon)$    & \n\\multicolumn{2}{c}{Observables} &\n$V_e$    & \n$\\mu (\\epsilon)$    & \n \\multicolumn{2}{c}{Observables} &\n$V_e$    & \n$\\mu (\\epsilon)$    & \n \\multicolumn{2}{c}{Observables} &\n$V_e$    & \n$\\mu (\\epsilon)$    & \n \\multicolumn{2}{c}{Observables} &\n$V_e$    & \n$\\mu (\\epsilon)$ \\\\ \\hline\\hline\n  $R/R_\\odot$ & $\\langle\\Delta\\nu_0\\rangle$ & 0.955 & 0.046 & $\\langle\\Delta\\nu_0\\rangle$, $\\nu_{\\max}$ && 0.985 & 0.027 & $\\langle\\Delta\\nu_0\\rangle$, $\\nu_{\\max}$, && 0.999 & 0.009 & $\\langle\\Delta\\nu_0\\rangle$, $\\nu_{\\max}$, && 0.999 & 0.008 & $\\langle\\Delta\\nu_0\\rangle$, $\\nu_{\\max}$, $T_{\\text{eff}}$, && 0.999 & 0.008\\\\\n  &  &  &  &  &  &  &  &  $T_{\\text{eff}}$ &  &  &  & $T_{\\text{eff}}$, $\\log{} g$ &&  & & $\\log{} g$, $\\langle r_{10}\\rangle$ &  &  &\\\\[3pt]\n  $\\log{} g$ & $\\langle\\Delta\\nu_0\\rangle$ & 0.86 & 0.046 & $T_{\\text{eff}}$, $\\nu_{\\max}$ && 0.999 & 0.004 & $T_{\\text{eff}}$, $\\nu_{\\max}$, && 0.999 & 0.003 & $T_{\\text{eff}}$, $\\nu_{\\max}$, && 0.999 & 0.002 & $T_{\\text{eff}}$, $\\nu_{\\max}$, $[\\text{Fe/H}]$, && 0.999 & 0.002\\\\\n  &  &  &  &  &  &  &  &  $[\\text{Fe/H}]$ &  &  &  & $[\\text{Fe/H}]$, $\\langle r_{13}\\rangle$ & & & & $\\langle r_{02}\\rangle$, $\\langle r_{13}\\rangle$ &  &  &\\\\[3pt]\n  $L/L_\\odot$ & $T_{\\text{eff}}$ & 0.739 & 1.583 & $T_{\\text{eff}}$, $\\langle\\Delta\\nu_0\\rangle$ && 0.993 & 0.254 & $T_{\\text{eff}}$, $\\langle\\Delta\\nu_0\\rangle$, &&0.999 & 0.13 & $T_{\\text{eff}}$, $\\langle\\Delta\\nu_0\\rangle$, && 0.999 & 0.136 & $T_{\\text{eff}}$, $\\langle\\Delta\\nu_0\\rangle$, $\\nu_{\\max}$, && 0.999 & 0.135\\\\\n  &  &  &  &  &  &  &  &  $\\nu_{\\max}$ &  &  &  & $\\nu_{\\max}$, $\\langle r_{10}\\rangle$ &&  & & $\\log{} g$, $\\langle r_{10}\\rangle$ &  &  &\\\\[3pt]   \n $T_{\\text{eff}}$/K & $[\\text{Fe/H}]$ & 0.298 & 1216 & $\\log{} g$, $\\nu_{\\max}$ && 0.989 & 104 & $\\log{} g$, $\\nu_{\\max}$, && 0.991 & 95 & $\\log{} g$, $\\nu_{\\max}$, && 0.992 & 96 & $\\log{} g$, $\\nu_{\\max}$, $\\langle r_{01}\\rangle$, && 0.992 & 96\\\\\n  &  &  &  &  &  &  &  &  $\\langle r_{01}\\rangle$ &  &  &  & $\\langle r_{01}\\rangle$, $\\langle\\delta\\nu_{13}\\rangle$ &&  & & $\\langle\\Delta\\nu_0\\rangle$, $\\langle\\delta\\nu_{13}\\rangle$ &  &  &\\\\[3pt]\n    $Z_0$ & $[\\text{Fe/H}]$ & 0.927 & 0.003 & $[\\text{Fe/H}]$, $\\langle\\delta\\nu_{02}\\rangle$ && 0.96 & 0.002 & $[\\text{Fe/H}]$, $T_{\\text{eff}}$, && 0.982 & 0.001 & $[\\text{Fe/H}]$, $T_{\\text{eff}}$, && 0.986 & 0.001 & $[\\text{Fe/H}]$, $T_{\\text{eff}}$, $\\langle\\Delta\\nu_0\\rangle$, && 0.987 & 0.001\\\\\n  &  &  &  &  &  &  &  &  $\\langle\\Delta\\nu_0\\rangle$ &  &  &  & $\\langle\\Delta\\nu_0\\rangle$, $\\langle r_{13}\\rangle$ &&  & & $\\langle r_{01}\\rangle$, $\\langle r_{13}\\rangle$ &  &  &\\\\[3pt]\n  $M/M_\\odot$ & $\\langle\\Delta\\nu_0\\rangle$ & 0.348 & 0.157 & $\\langle\\Delta\\nu_0\\rangle$, $\\log{} g$ && 0.857 & 0.072 & $\\langle\\Delta\\nu_0\\rangle$, $T_{\\text{eff}}$, && 0.982 & 0.022 & $\\langle\\Delta\\nu_0\\rangle$, $\\log{} g$, && 0.986 & 0.02 & $\\langle\\Delta\\nu_0\\rangle$, $\\log{} g$, $\\nu_{\\max}$, && 0.982 & 0.024\\\\\n  &  &  &  &  &  &  &  &  $\\nu_{\\max}$ &  &  &  & $\\nu_{\\max}$, $T_{\\text{eff}}$ &&  & & $T_{\\text{eff}}$, $\\langle r_{10}\\rangle$ &  &  &\\\\[3pt] \n    $\\tau_{\\text{MS}}$ & $\\langle\\delta\\nu_{02}\\rangle$ & 0.543 & 0.147 & $\\langle r_{02}\\rangle$, $\\langle r_{01}\\rangle$ && 0.846 & 0.077 & $\\langle\\Delta\\nu_0\\rangle$, $\\nu_{\\max}$, && 0.957 & 0.038 & $\\langle r_{02}\\rangle$, $\\nu_{\\max}$, && 0.977 & 0.025 & $\\langle r_{02}\\rangle$, $\\nu_{\\max}$, $\\langle r_{10}\\rangle$, && 0.981 & 0.021\\\\\n  &  &  &  &  &  &  &  &  $\\langle r_{13}\\rangle$ &  &  &  & $\\langle r_{10}\\rangle$, $T_{\\text{eff}}$ &&  & & $T_{\\text{eff}}$, $[\\text{Fe/H}]$ &  &  &\\\\[3pt] \n   X$_c$ & $\\langle\\delta\\nu_{02}\\rangle$ & 0.508 & 0.113 & $\\nu_{\\max}$, $\\langle r_{13}\\rangle$ && 0.842 & 0.062 & $\\nu_{\\max}$, $\\langle r_{13}\\rangle$, && 0.958 & 0.031 & $\\nu_{\\max}$,  $\\langle r_{13}\\rangle$,& & 0.978 & 0.023 & $\\nu_{\\max}$, $\\langle r_{13}\\rangle$, $\\langle\\Delta\\nu_0\\rangle$, && 0.979 & 0.022\\\\\n  &  &  &  &  &  &  &  &  $\\langle\\Delta\\nu_0\\rangle$ &  &  &  & $\\langle\\Delta\\nu_0\\rangle$, $\\langle r_{10}\\rangle$ &&  & & $\\log{} g$, $\\langle r_{10}\\rangle$ &  &  &\\\\[3pt]\n  $\\tau$ (Gyr)& $\\langle r_{02}\\rangle$ & 0.645 & 0.995 & $\\langle r_{02}\\rangle$, $\\nu_{\\max}$ && 0.844 & 0.642 & $\\langle r_{13}\\rangle$, $\\nu_{\\max}$, && 0.907 & 0.468 & $\\langle r_{02}\\rangle$,  $T_{\\text{eff}}$, && 0.931 & 0.332 & $\\langle r_{02}\\rangle$, $\\nu_{\\max}$, $\\langle r_{01}\\rangle$, && 0.943 & 0.282\\\\\n  &  &  &  &  &  &  &  &  $\\langle r_{10}\\rangle$ &  &  &  & $\\langle r_{01}\\rangle$, $\\langle\\Delta\\nu_0\\rangle$ &&  & & $T_{\\text{eff}}$, $[\\text{Fe/H}]$ &  &  &\\\\[3pt] \n   X$_{\\text{surf}}$ & $[\\text{Fe/H}]$ & 0.655 & 0.051 & $[\\text{Fe/H}]$, $\\log{} g$ && 0.772 & 0.041 & $[\\text{Fe/H}]$, $\\langle\\Delta\\nu_0\\rangle$, && 0.895 & 0.027 & $[\\text{Fe/H}]$, $\\langle\\Delta\\nu_0\\rangle$, && 0.928 & 0.024 & $[\\text{Fe/H}]$, $\\langle\\Delta\\nu_0\\rangle$, $T_{\\text{eff}}$, && 0.936 & 0.022\\\\\n  &  &  &  &  &  &  &  &  $\\nu_{\\max}$ &  &  &  & $T_{\\text{eff}}$, $\\langle r_{02}\\rangle$ &&  & & $\\langle r_{02}\\rangle$, $\\nu_{\\max}$ &  &  &\\\\[3pt] \n  $M_{\\text{cc}}/M_\\odot$ & --- & --- & --- & $\\langle r_{13}\\rangle$, $\\langle\\delta\\nu_{02}\\rangle$ && 0.679 & 0.015 & $\\langle r_{13}\\rangle$, $\\nu_{\\max}$, & &0.862 & 0.009 & $\\langle r_{13}\\rangle$, $\\nu_{\\max}$, && 0.908 & 0.007 & $\\langle r_{13}\\rangle$, $\\nu_{\\max}$, $\\langle r_{10}\\rangle$, && 0.928 & 0.006\\\\\n  &  &  &  &  &  &  &  &  $\\langle r_{10}\\rangle$ &  &  &  & $\\langle r_{10}\\rangle$, $T_{\\text{eff}}$ &&  & & $T_{\\text{eff}}$, $[\\text{Fe/H}]$ &  &  &\\\\[3pt]\n   $Y_{\\text{surf}}$ & $[\\text{Fe/H}]$ & 0.597 & 0.052 & $[\\text{Fe/H}]$, $\\log{} g$ && 0.736 & 0.041 & $[\\text{Fe/H}]$, $\\langle\\Delta\\nu_0\\rangle$, && 0.887 & 0.025 & $[\\text{Fe/H}]$, $\\langle\\Delta\\nu_0\\rangle$, && 0.916 & 0.024 & $[\\text{Fe/H}]$, $\\langle\\Delta\\nu_0\\rangle$, $\\langle r_{02}\\rangle$, && 0.927 & 0.022\\\\\n  &  &  &  &  &  &  &  &  $\\nu_{\\max}$ &  &  &  & $\\langle r_{02}\\rangle$, $T_{\\text{eff}}$ &&  & & $T_{\\text{eff}}$, $\\nu_{\\max}$ &  &  &\\\\[3pt] \n   $Y_0$ & --- & --- & --- & $\\langle\\Delta\\nu_0\\rangle$, $\\nu_{\\max}$ && 0.077 & 0.027 & $\\langle\\Delta\\nu_0\\rangle$, $\\nu_{\\max}$, && 0.471 & 0.02 & $\\langle\\Delta\\nu_0\\rangle$, $\\nu_{\\max}$, && 0.536 & 0.019 & $\\langle\\Delta\\nu_0\\rangle$, $\\nu_{\\max}$, $[\\text{Fe/H}]$, && 0.625 & 0.017\\\\\n  &  &  &  &  &  &  &  &  $[\\text{Fe/H}]$ &  &  &  & $[\\text{Fe/H}]$, $\\log{} g$ &&  & & $\\log{} g$, $\\langle\\delta\\nu_{13}\\rangle$ &  &  &\\\\[3pt] \n    $\\alpha_{\\text{ov}}$ & --- & --- & --- & $\\langle r_{13}\\rangle$, $\\langle r_{02}\\rangle$ && 0.231 & 0.089 & $\\langle r_{13}\\rangle$, $\\langle r_{10}\\rangle$, && 0.44 & 0.075 & $\\langle r_{13}\\rangle$,  $\\langle r_{10}\\rangle$, && 0.524 & 0.068 & $\\langle r_{13}\\rangle$, $\\langle r_{10}\\rangle$, $\\nu_{\\max}$, && 0.55 & 0.067\\\\\n  &  &  &  &  &  &  &  &  $\\nu_{\\max}$ &  &  &  & $\\nu_{\\max}$, $T_{\\text{eff}}$ &&  & & $T_{\\text{eff}}$, $[\\text{Fe/H}]$ &  &  &\\\\[3pt] \n   D & --- & --- & --- & $[\\text{Fe/H}]$, $\\langle\\delta\\nu_{02}\\rangle$ && 0.022 & 5.393 & $[\\text{Fe/H}]$, $T_{\\text{eff}}$, && 0.295 & 4.483 & $[\\text{Fe/H}]$, $T_{\\text{eff}}$, && 0.446 & 3.706 & $[\\text{Fe/H}]$,  $T_{\\text{eff}}$, $\\langle r_{02}\\rangle$, && 0.519 & 3.333\\\\\n  &  &  &  &  &  &  &  &  $\\langle\\Delta\\nu_0\\rangle$ &  &  &  & $\\langle r_{02}\\rangle$, $\\langle\\Delta\\nu_0\\rangle$ &&  & & $\\log{} g$, $\\langle r_{10}\\rangle$ &  &  &\\\\[3pt] \n  $[\\text{Fe/H}]$ &--- & --- & --- & $\\nu_{\\max}$, $\\log{} g$ && 0.179 & 2.777 & $\\nu_{\\max}$, $\\log{} g$, && 0.273 & 2.439 & $\\nu_{\\max}$, $\\log{} g$, && 0.309 & 2.312 & $\\nu_{\\max}$, $\\log{} g$, $\\langle r_{02}\\rangle$, && 0.312 & 2.277\\\\\n  &  &  &  &  &  &  &  &  $\\langle r_{02}\\rangle$ &  &  &  & $\\langle r_{02}\\rangle$, $\\langle r_{10}\\rangle$ &&  & & $\\langle r_{01}\\rangle$, $\\langle r_{13}\\rangle$ &  &  &\\\\[3pt] \n  $\\alpha_{\\text{MLT}}$ & --- & --- & --- & --- --- && --- & --- & $T_{\\text{eff}}$, $\\nu_{\\max}$, && 0.069 & 0.234 & $T_{\\text{eff}}$, $\\nu_{\\max}$, && 0.201 & 0.211 & $T_{\\text{eff}}$, $\\nu_{\\max}$, $\\langle r_{01}\\rangle$, && 0.229 & 0.207\\\\\n  &  &  &  &  &  &  &  &  $\\langle\\delta\\nu_{13}\\rangle$ &  &  &  & $[\\text{Fe/H}]$, $\\langle r_{02}\\rangle$ &&  & & $[\\text{Fe/H}]$, $\\langle r_{13}\\rangle$ &  &  &\\\\[3pt] \n%\\enddata\n \\end{tabular} \n \\end{table}\n%\\end{rotatetable}\n%\\end{figure}\n\\end{landscape}\n}\n%\\clearpage\n\nMany of the RFs we trained do not provide a satisfactory regression model for the quantity we are training for. Below we provide a deeper analysis for some of the more interesting results, focusing primarily on the predictions of ages and surface abundances. \n\n\\subsection{Ages}\n\\label{sec:sages}\nThe current exercise allows us to evaluate the theoretical limit in which parameter pairs, such as those used in the C--D diagram, can constrain stellar ages. \nRecall that there are six initial model parameters varied simultaneously in the BA1 grid. \nDescribing a six dimensional parameter space with two quantities invariably leads to degenerate solutions for age and necessarily high uncertainties.\nThe parameter pairs that offer similarly the best constraints on $\\tau$ are listed in Table~\\ref{tab:cd}. The combination of ${\\langle r_{02}\\rangle}$ and $\\nu_{\\max}$  marginally provide the best probe, explaining the largest fraction of the variance and inferring ages with uncertainty ${\\mu (\\epsilon) = \\pm 642}$~Myr.  \n\n\\begin{table}\n\\centering\n\\caption{The best two-parameter combinations of observables for constraining stellar age. Below the dividing horizontal line we include the best spectroscopic pair for comparison as well as ${\\log{} g}$ -- ${\\langle\\Delta\\nu_0\\rangle}$ to highlight the necessity of the small frequency separation in determining stellar ages. The BA1 grid is varied in six dimensions and with such a high-dimensional parameter space the quantities in the C--D diagram (fifth row) constrain age with `typical' uncertainty of $701$~Myr.}\n    \\begin{tabular}{cccc}\n    \\hline \\hline\n\\multicolumn{2}{c}{Parameters} & $V_e$ & $\\mu (\\epsilon)$ [Gyr] \\\\ \\hline \n$\\langle r_{02}\\rangle$     & $\\nu_{\\max}$               &0.844  & 0.642\\\\\n$\\langle r_{02}\\rangle$     & $\\log{} g$                  &0.833  & 0.683\\\\\n$\\langle r_{13}\\rangle$     &$\\nu_{\\max}$                &0.827  & 0.711\\\\\n$\\langle r_{02}\\rangle$     & $\\langle\\Delta\\nu_0\\rangle$    &0.825  & 0.694\\\\\n$\\langle\\Delta\\nu_0\\rangle$ &$\\langle\\delta\\nu_{02}\\rangle$  &0.824  & 0.701\\\\\n$\\langle r_{02}\\rangle$     & $\\langle\\delta\\nu_{02}\\rangle$ &0.821  & 0.701\\\\\nPC$_2$ & PC$_8$ & 0.788 & 0.767 \\\\\nPC$_2$ & PC$_4$ & 0.776 & 0.762 \\\\\n\\hline\n $\\log{} g$ & $\\langle\\Delta\\nu_0\\rangle$ & 0.481 & 1.29 \\\\\n $\\log{} g$ & $T_{\\text{eff}}$ & 0.321 & 1.53 \\\\\n \\hline\n    \\end{tabular}\n    \\label{tab:cd}\n\\end{table}\n\nThis is in comparison to ${\\mu (\\epsilon) = \\pm 701}$~Myr for ${\\langle\\Delta\\nu_0\\rangle}$ and ${\\langle\\delta\\nu_{02}\\rangle}$  as per the C--D diagram. \nIn Table~\\ref{tab:cd} we also include results from regression calculated with the PCs and find they perform comparably well. The results here omit any uncertainty stemming from the surface effect suggesting that the ${\\langle r_{02}\\rangle}$ and $\\nu_{\\max}$ pair are indeed the preferable choice. \n\n\n\nIt is clear from Tables~\\ref{tab:regparms} and \\ref{tab:cd}  how important the small frequency separation and frequency ratios are for the determination of stellar ages on the MS. \nIf we limit the combinations to the classical observables, we find that  ${\\log{} g}$ and $T_{\\text{eff}}$ can explain just $32.1\\%$ of the variance in $\\tau$ with uncertainty ${\\mu (\\epsilon) = \\pm 1.5}$~Gyr across the whole grid. The introduction of the large separation offers little improvement. The parameter pair ${\\log{} g}$ and ${\\langle\\Delta\\nu_0\\rangle}$  explain $48.1\\%$ of the variance with  ${\\mu (\\epsilon) = \\pm 1.29}$~Gyr.\nIf we permit the RF to draw upon five observables for its regression model, some of the degeneracy in $\\tau$ is lifted.  The last column in Table~\\ref{tab:regparms}\nindicates that the RF can reduce the average uncertainty in predicting  $\\tau$ such that  ${\\mu (\\epsilon) =\\pm 282}$~Myr.\n\n\\subsection{Abundances}\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=0.9\\linewidth]{hehist2.pdf}\n    \\caption[Distributions of initial and surface helium abundances in the generated stellar models]{Distributions of $Y_{\\text{surf}}$ and $Y_0$ in the BA1 grid.}\n    \\label{fig:Hehist}\n\\end{figure}\nThe small frequency separations and separation ratios are integral for the determination of ages. \nHowever, the feature importances in BA1 (their Figure~5) indicate that the RF relies predominately on  $T_{\\text{eff}}$ and $[\\text{Fe/H}]$ to infer other model parameters. \nTable~\\ref{tab:regparms} confirms how important measuring $[\\text{Fe/H}]$ is for characterizing stars. This quantity is preferentially selected in the many RFs and their regression models, whilst $[\\text{Fe/H}]$ itself cannot be determined from the other observables with any degree of confidence.   \n$[\\text{Fe/H}]$ is an indispensable piece of independent information.\n\nAccurate determination of $[\\text{Fe/H}]$ is paramount for inferring many of the current-age stellar attributes. $[\\text{Fe/H}]$ also features prominently in the retrodiction of the initial model parameters but these quantities are characterized by large uncertainties. Foremost, we have no observable that satisfactorily constrains diffusion; $D$ demonstrates an average uncertainty spanning three orders of magnitude. This in turn introduces uncertainty in retrodicting the initial metal content. \n\nPredictions for $Z_0$ at first glace appear to be robust; we report $V_e$ and  ${\\mu (\\epsilon) = \\pm 0.001}$. However we contend that a reported error of  ${\\mu (\\epsilon) = \\pm 0.001}$ is not all that insightful given that the grid is sampled down to ${Z_0 = 10^{-5}}$. $Z_0$ is sampled logarithmically and takes a small (linear) range in values. In such cases   a relative error is a more useful measure of performance than an absolute difference. \n\n\nIn Table~\\ref{tab:relabunds} we devise a series of measures that better appraise the performance of the RF in predicting abundances. We report the average absolute difference as per Table~\\ref{tab:regparms} [${\\mu (\\epsilon)}$], the maximum absolute difference [${\\max(\\epsilon)}$] and the median absolute difference [${\\tilde{\\epsilon}}$]. We also consider the average relative error [${\\mu (\\eta)}$], the maximum relative error [${\\max(\\eta)}$] and median relative error [$\\tilde{\\eta}$], where the relative error is a percentage defined as\n\\begin{equation}\n  \\eta= \\frac{| \\hat y_i - y_i |}{|y_i|} \\cdot 100.\n\\end{equation}\n\n\n\\begin{table}\n\\centering\n\\caption{Different measures of uncertainty in predicting stellar abundances with the RF. See text for definitions and motivations.}\n    \\begin{tabular}{lccc}\n \\hline \\hline\n Error Measure& $Y_{\\text{surf}}$ & $Y_0$ & $Z_0$ \\\\ \\hline\n $\\mu (\\epsilon)$                 & 0.02 &0.017 & 0.001 \\\\\n Max($\\epsilon$)             & 0.25 &0.09   & 0.037\\\\    \n$\\tilde {\\epsilon}$          & 0.016  &0.02     &0.00019\\\\\n$\\mu (\\eta)$ [\\%]       & $10^{13}$ &8.92& 124.5 \\\\ \n  Max($\\eta$) [\\%]   & $10^{14}$ &40.34  & 9052 \\\\\n$\\tilde {\\eta}$  [\\%] & 10.88 &7.68  & 13.5 \\\\\n\\hline\n\\end{tabular}\n\\label{tab:relabunds}\n\\end{table}\n\n\nWe find  ${\\mu (\\eta) = 125\\%}$ in the retrodiction of metallicity. We attribute the seemingly large uncertainty to the bias imparted by extreme models that have undergone significant diffusion -- we report a maximum relative error of $9000\\%$. With less sensitivity to the outlying metal-depleted models, the median relative uncertainty, ${\\tilde{\\eta} = 13.5\\%}$, offers the most appropriate measure of error in the regression. \nLikewise, the extreme ${\\mu (\\eta)}$ and $\\max(\\eta)$ scores for $Y_{\\text{surf}}$ also stem from models with high diffusion leading to very small non-zero abundances by which we normalize. \n\nIt is interesting to compare the regressor's ability to infer $Y_{\\text{surf}}$ and $Y_0$ abundances. We find that  $Y_{\\text{surf}}$ can be well fit (${V_e = 0.927}$) with ${\\mu (\\epsilon) = \\pm 0.022}$. In contrast, the initial abundance, $Y_0$, cannot be confidently retrodicted  (${V_e=0.625}$) yet results in a smaller average error [${\\mu (\\epsilon) = \\pm 0.017}$]. \nThis initially surprising result can be understood through examination of the respective parameter distributions in the BA1 grid (Figure~\\ref{fig:Hehist}).\nThe grid is uniformly sampled in initial helium with ${Y_0 \\in [0.22, 0.34]}$. \nAtomic diffusion acts to drain helium from the surface layers and in fact, in some models, completely depletes this species from the envelope. \nThe surface helium abundance of a stellar model can thus attain values in the larger range\n${Y_{\\text{surf}} \\in [0.0, 0.34]}$.  %As discussed in Bellinger et al. (submitted) \nIn a  uniform distribution, such as we have for $Y_0$, the largest theoretical uncertainty  is \n\\begin{equation}\n    \\max \\left( \\frac{\\sigma^2(Y_0)}{Y_0} \\right) = \\frac{|b-a|}{|a|} \\cdot 100 = 54.51\\%,\n\\end{equation}\nwhere $a$ and $b$ are the respective minimum and maximum values in our parameter range.  \nThis means that if the regressor was unable to explain \\emph{any} of the variance in this quantity and was randomly choosing $Y_0$ values from the initial distribution, the worst relative uncertainty we would expect is $54.51\\%$. The fact that we do go someway to predicting this quantity results in ${\\mu (\\eta) \\approx 8\\% }$ and more accurate inferences than for $Y_{\\text{surf}}$. \n\n\n\n\n\n\n\n\\subsection{Other Results}\nWe mention briefly other interesting results from the approximately $50,000$ RFs not necessarily reported in Table~\\ref{tab:regparms}.\nStellar masses can be accurately inferred from spectroscopic measurements. The combination of  ${\\log{} g}$, $T_{\\text{eff}}$ and $[\\text{Fe/H}]$ constrains mass equally well as the pair ${\\langle\\Delta\\nu_0\\rangle}$ -- ${\\log{} g}$. Both combinations explain \n $86\\%$ of the variance in mass with ${\\mu (\\epsilon) = \\pm 0.07 \\; M_{\\odot}}$. With six degrees of freedom in the BA1 grid, we cannot determine mass to an accuracy better than  ${\\mu (\\epsilon) = \\pm 0.02\\;M_{\\odot}}$.  \n Whilst all observables correlate with $M$, they do not contain sufficient information to separate out the redundant structures that are possible by tweaking the other initial model parameters. We in fact find no improvement in our regression for $M$ beyond three parameters\\footnote{Numerics accounts for the differences in the third decimal place for scores in Table~\\ref{tab:regparms}.}. \n\nIf required, the RF can determine $T_{\\text{eff}}$ with high accuracy. \nAlthough this is almost certainly always an input for the RF, with two or more observables $T_{\\text{eff}}$ can be determined with  ${\\mu (\\epsilon) \\approx 100}$~K -- an uncertainty comparable to typical spectroscopic errors. If one of $L$ or $R$ are provided as an input to the RF, a factor of two reduction in the uncertainty is achieved with ${\\mu (\\epsilon) \\lesssim 50}$~K. Furthermore, our testing of the RF (not included here) indicates that if both $L$ and $R$ are provided as observables the Stefan-Boltzmann law is recovered with ${\\mu (\\epsilon) = 4}$~K. \n \n\n\n\\subsection{Seismic Quantities} \\label{sec:seispr}\nWe did not include the predictions for the seismic parameters in Table~\\ref{tab:regparms} as they often carry redundant information. Indeed we accomplish little \nby reporting how the different combinations of ratios and separations can be used to recover each other. \nWe thus opt to analyze the seismic parameters separately, where we can employ discretion to present useful comparisons and highlight noteworthy results. \n\n\\subsubsection*{The large frequency separation -- $\\langle\\Delta\\nu_0\\rangle$}\n\n\n\nIn lieu of a direct measurement, ${\\langle\\Delta\\nu_0\\rangle}$ can be estimated from stellar models via an asteroseismic scaling relation (Equation~\\ref{equ:dnu}). Alternatively, it may be inferred from the observables through an empirical power law that relates ${\\langle\\Delta\\nu_0\\rangle}$ to $\\nu_{\\max}$ \\citep{2009A&A...506..465H,2009MNRAS.400L..80S}. \nThe power law estimates ${\\langle\\Delta\\nu_0\\rangle}$ within  $15\\%$ of its measured value \\citep{2009MNRAS.400L..80S}.\nWe compare the RF's ability to likewise predict ${\\langle\\Delta\\nu_0\\rangle}$ from $\\nu_{\\max}$ in Table~\\ref{tab:dnu}. We also consider two and three parameter combinations for inferring ${\\langle\\Delta\\nu_0\\rangle}$ with the requirement that they do not comprise the remaining seismic observables. \n\n\\begin{table}\n\\centering\n\\caption{Combinations of observables that best constrain $\\langle\\Delta\\nu_0\\rangle$.}\n    \\label{tab:dnu}\n    \\begin{tabular}{ccccccc}\n    \\hline \\hline\n\\multicolumn{3}{c}{Parameters} && $V_e$ & $\\mu (\\epsilon)$ & $\\mu (\\eta)$  \\\\  \n&&&&&[$\\mu$Hz] & [\\%] \\\\ \\hline\n$\\nu_{\\max}$ &  &   &&0.930 & 7.815 & 6.11 \\\\ \n$T_{\\text{eff}}$     & $\\nu_{\\max}$&     &&0.990  & 3.09 & 2.46 \\\\\n$\\log{} g$     &$\\nu_{\\max}$ &               &&0.990  & 2.95 & 2.34 \\\\\n$\\log{} g$     &  $T_{\\text{eff}}$&                 & &0.990  & 2.92 & 2.31\\\\\n$[\\text{Fe/H}]$  & $\\nu_{\\max}$ &                 &&0.991  & 2.81 & 2.24\\\\\n$T_{\\text{eff}}$ & $[\\text{Fe/H}]$ & $\\nu_{\\max}$ && 0.995 & 1.67 & 2.13 \\\\\n$\\log{} g$ & $[\\text{Fe/H}]$ & $\\nu_{\\max}$ && 0.995 & 1.65 & 2.11\\\\\n\\hline\n    \\end{tabular}\n\\end{table}\n\nWe find that the RF predicts ${\\langle\\Delta\\nu_0\\rangle}$  from $\\nu_{\\max}$  with ${\\mu (\\eta) \\approx 6\\%}$. These results are based on error free information (cross-validation hence no measurement noise) and the inclusion of $\\nu_{\\max}$ from a scaling law. \nIn order to conduct a more faithful comparison with \\citet{2009MNRAS.400L..80S}, we analyze the same data used in the derivation of their power law.  \nTheir Table~1 is a compilation of  $\\nu_{\\max}$ and ${\\langle\\Delta\\nu_0\\rangle}$ values from the literature. The data are predominately from radial velocity studies and measured with less precision than we have come to expect from \\emph{Kepler} timeseries; they provide a robust test of the RF. \nWe feed the RF the quoted $\\nu_{\\max}$ measurements and predict associated ${\\langle\\Delta\\nu_0\\rangle}$ values. We compare our predictions to the ${\\langle\\Delta\\nu_0\\rangle}$ values from the literature which are used to calculate corresponding \n$\\epsilon$ and $\\eta$ scores. Our results are presented in Table~\\ref{tab:stello}. \nWe omit entries from  the \\citet{2009MNRAS.400L..80S} dataset that are outside the parameter ranges of our training grid.\nFor the remaining $17$ stars we find ${\\mu (\\eta) \\approx 8\\%}$ which is comparable to  ${\\mu (\\eta) \\approx 6\\%}$ accuracy achieved from cross-validation test (approximately $15,000$ stars).  \n\n\\begin{table}\n\\centering\n\\caption{Predictions of ${\\langle\\Delta\\nu_0\\rangle}$ for stars listed in \\citet{2009MNRAS.400L..80S}. Results pertain to a random forest trained with $\\nu_{\\max}$ as the only input. Predictions are compared to literature values from the sources listed in Table~1 of  \\citet{2009MNRAS.400L..80S}. The RF performs as well as the power-law relation ($10$-$15\\%$) even on data measured with less precision than stars observed by \\emph{Kepler}.}\n\\label{tab:stello}\n\\begin{tabular}{llllll}\n\\hline  \\hline\nStar & $\\nu_{\\max}$ & $\\langle\\Delta\\nu_0\\rangle_{\\text{lit}}$ & $\\langle\\Delta\\nu_0\\rangle_{\\text{pred}}$ & $\\epsilon$ & $\\eta$  \\\\ \n& ($\\mu$Hz) & ($\\mu$Hz)  &($\\mu$Hz) &($\\mu$Hz) & (\\%) \\\\ \\hline\n$\\tau\\;$Cet &4500 & 170 & 171 & 1  & 1  \\\\\n$\\alpha\\;$Cen B &4100 & 161 & 184 & 22& 14  \\\\\nSun &3100 & 135 & 138 & 3 & 2    \\\\\n$\\iota\\;$Hor &2700 & 120   & 136 &  16&14  \\\\\n$\\gamma\\;$Pav  &2600 & 120 & 122 & 1  & 1  \\\\\n$\\alpha\\;$Cen A &2400 & 106 & 124 & 18 & 17  \\\\\nHD 175726 &2000 & 97    & 100 & 3  & 3  \\\\\n$\\mu\\;$Ara &2000 & 90    & 100 & 10 & 11  \\\\\nHD 181906 &1900 & 88  & 97  & 10 & 11 \\\\\nHD 49933 &1760 & 86  & 101 & 15 & 18  \\\\\nHD 181420 &1500 & 75    & 76  & 1  & 1  \\\\\n$\\beta\\;$Vir &1400 & 72    & 77   & 5 & 8  \\\\\n$\\mu\\;$Her  &1200 & 57  & 63   & 7 & 12  \\\\\n$\\beta\\;$Hyi &1000 & 57  & 57  & 0  & 0  \\\\\nProcyon &1000 & 55    & 57 & 2 & 4    \\\\\n$\\eta\\;$Boo &750  & 40  & 45   & 5 & 13  \\\\\n$\\nu\\;$Ind &320  & 25  & 23  & 3 & 10  \\\\ \\hline\n\\end{tabular}\n\\end{table}\n\n\nThe last column in Table~\\ref{tab:stello} indicates that the accuracy from the RF is similar to that of the power law. In addition, we find that parameterizing the RF regression as a function of two observables reduces the uncertainty by a factor of $2$--$3$   (Table~\\ref{tab:dnu}).\nThis hints that the inclusion of a temperature or metallicity dependence may also improve the fit offered by the power law\\footnote{Symbolic regression will help determine whether, in this case, the fitting by the RF has a sensible functional form that can be straightforwardly expressed by two independent variables. This result seems reasonable as the additional information is likely providing a better handle on the stellar mass.}. \n \nAnalysis of recent \\emph{Kepler} data yields a similar result. In Figure~\\ref{fig:chap} we present the percentage error in our predictions of $467$ stars measured by \\emph{Kepler} as reported in Table~1 of \\citet{2014ApJS..210....1C}. We analyze stars for which $\\nu_{\\max}$, ${\\langle\\Delta\\nu_0\\rangle}$ have been measured from the oscillation spectra along with  $T_{\\text{eff}}$ as determined by \\citet{2012ApJS..199...30P} based on Sloan Digital Sky Survey (SDSS) photometry. Results from the \\emph{Kepler} sample confirm that predictions for ${\\langle\\Delta\\nu_0\\rangle}$ are improved with the inclusion of $T_{\\text{eff}}$ (lavender distribution). The blue distribution indicates that ${\\langle\\Delta\\nu_0\\rangle}$ is systematically overestimated when the RF only has access to information from $\\nu_{\\max}$ -- a bias that may very well be present in the power-law fit. With the inclusion of $T_{\\text{eff}}$ our predictions become more accurate and precise with the bias from the single parameter function mitigated. We do not quite reproduce the accuracy achieved in the cross validation (Table~\\ref{tab:dnu}) using error free information.  Unsurprisingly,  measurement uncertainty, which we do not consider here, does not permit the accuracy attained in the ideal case.\n\n\n\\begin{figure}\n\\centering\n\\includegraphics[width=0.9\\linewidth]{chaplin.pdf}\n\\caption[Relative error in predictions for $\\Delta\\nu$]{Relative error (\\%) in the predictions for ${\\langle\\Delta\\nu_0\\rangle}$ for $467$ stars reported in \\citet{2014ApJS..210....1C}. The blue colored distribution indicates the error in the predictions from the random forest using $\\nu_{\\max}$ as the only input observation whilst the distribution marked in lavender are the results from providing $\\nu_{\\max}$ and $T_{\\text{eff}}$. In the calculations we employ the effective temperatures determined from \\citet{2012ApJS..199...30P} based on  SDSS photometry.} \n\\label{fig:chap}\n\\end{figure}\n\n\n\n\\subsubsection*{The frequency of maximum oscillation power -- $\\nu_{\\max}$} \n\n\nCurrently we are unable to predict the frequency of maximum oscillation power from first principles. \\citet{1991ApJ...368..599B} and \\citet{1995A&A...293...87K} showed that this quantity does scale with the acoustic cut-off frequency and can thus be estimated via the Equation~(\\ref{equ:nmax}) scaling relation. It is therefore expected that Table~\\ref{tab:nmx} indicates that  $\\nu_{\\max}$ is best inferred from ${\\log{} g}$  and $T_{\\text{eff}}$. These are the two observables that correlate strongest those parameters used to calculate $\\nu_{\\max}$ in the training grid. \n\n\\begin{table}\n\\centering\n\\caption{Combinations of observables that  best constrain $\\nu_{\\max}$.}\n    \\begin{tabular}{ccccc}\n\\hline    \\hline\n\\multicolumn{2}{c}{Parameters} && $V_e$ &$\\mu (\\epsilon)$ [$\\mu$Hz] \\\\ \\hline \n$\\langle\\Delta\\nu_0\\rangle$ &&&0.923  & 7.88 \\\\\n$\\log{} g$ & $[\\text{Fe/H}]$ && 0.888 & 9.99 \\\\\n$\\log{} g$     & $\\langle\\Delta\\nu_0\\rangle$     &&0.954  & 5.38\\\\\n$T_{\\text{eff}}$     & $\\langle r_{10}\\rangle$ &   &0.960  & 5.11\\\\\n$[\\text{Fe/H}]$    &$\\langle\\Delta\\nu_0\\rangle$        &       &0.992  & 2.90\\\\\n$T_{\\text{eff}}$     & $\\langle\\Delta\\nu_0\\rangle$    &  &0.992  & 2.84\\\\\n$\\log{} g$  & $T_{\\text{eff}}$                 &&0.999  & 0.83\\\\\n\\hline\n    \\end{tabular}\n    \\label{tab:nmx}\n\\end{table}\n\n\n\\subsubsection*{The small frequency separation -- $\\langle\\delta\\nu_{02}\\rangle$}\nThe small frequency separation is an indispensable piece of independent information for determining stellar age. In the asymptotic limit \\citep{1980ApJS...43..469T}\n\\begin{equation}\n\\langle\\delta\\nu_{13}\\rangle = \\frac{5}{3} \\langle\\delta\\nu_{02}\\rangle \n\\end{equation}\nand as Table~\\ref{tab:d02} demonstrates, the RF recovers  ${\\langle\\delta\\nu_{02}\\rangle}$ in the unlikely case that it is not extracted but ${\\langle\\delta\\nu_{13}\\rangle}$ is.\nIf we disregard combinations that include the seismic ratios, which also contain information of the local small frequency separation, we lack sufficient information to satisfactorily constrain ${\\langle\\delta\\nu_{02}\\rangle}$. \nClearly much of the evolutionary aspect of this quantity can be explained though parameters \nthat correlate with main-sequence lifetime e.g.,  ${\\log{} g}$, ${\\langle\\Delta\\nu_0\\rangle}$,   $\\nu_{\\max}$ and  $T_{\\text{eff}}$. However the associated errors of ${\\mu (\\epsilon) > 1.0 \\; \\mu}$Hz can correspond to large age uncertainties for main sequence stars (${\\eta > 10\\%}$). \n\n\n\n\n\\begin{table}\n\\centering\n\\caption{Combinations of observables, without the asteroseismic ratios, that best constrain $\\langle\\delta\\nu_{02}\\rangle$.}\n    \\begin{tabular}{cccccc}\n    \\hline\n\\multicolumn{3}{c}{Parameters} && $V_e$ & $\\mu (\\epsilon)$ [$\\mu$Hz] \\\\ \\hline \\hline\n$\\langle\\delta\\nu_{13}\\rangle$ &  &   &&0.944 & 0.66 \\\\ \n$\\log{} g$ &  &   &&0.542 & 2.08 \\\\ \n$\\langle\\delta\\nu_{13}\\rangle$ &  $\\langle r_{10}\\rangle$  &   &&0.987 & 0.320 \\\\ \n$T_{\\text{eff}}$     & $\\nu_{\\max}$&     &&0.776  & 1.40\\\\\n$\\log{} g$     &  $T_{\\text{eff}}$&                 & &0.775  & 1.40\\\\\n$\\log{} g$     &$\\nu_{\\max}$ &               &&0.772  & 1.41\\\\\n$\\log{} g$     &$\\langle\\Delta\\nu_0\\rangle$ &               &&0.723  & 1.54\\\\\n$T_{\\text{eff}}$     & $\\langle\\Delta\\nu_0\\rangle$&     &&0.720  & 1.58\\\\\n$\\log{} g$ & $[\\text{Fe/H}]$ &  && 0.720 & 1.59 \\\\\n$\\log{} g$ & $[\\text{Fe/H}]$ & $\\langle\\Delta\\nu_0\\rangle$ && 0.861 & 1.06 \\\\\n$\\log{} g$ & $\\nu_{\\max}$ & $\\langle\\Delta\\nu_0\\rangle$ && 0.860 & 1.09 \\\\\n\\hline\n    \\end{tabular}\n    \\label{tab:d02}\n\\end{table}\n\n\n\n\n%\\section{Quantifying the Required Measurement Accuracy of Stellar Observables}\n\\section[Quantifying the Required Measurement Accuracy]{Quantifying the Required Measurement Accuracy of Stellar Observables}\n\\label{sec:accu}\nIn the previous section we used RF regression to appraise how well combinations of observables constrain other stellar parameters. The ${\\approx 50,000}$ RFs were   \nevaluated using cross-validation. The tests are a pure measure of the regressor's performance as we have error-free information that we attempt to reproduce (withheld models).\n As we have already alluded to, like all procedures that seek to infer stellar parameters, we must also consider the consequences of measurement uncertainty in our method. \n\n \nMeasurement uncertainty will impact the RF results in a manner that is different to model finding algorithms. Consider an iterative model finding procedure in which we seek an  optimum model for a set of observations. We can typically expect $T_{\\text{eff}}$ as a constraint with an associated  uncertainty of ${\\sigma = 100}$~K.  The minimization algorithm will identify a set of candidate models, many with quite different structures. Hence the uncertainty in $T_{\\text{eff}}$  will impact %on the outcome of\nall stellar quantities simultaneously.  The  RF, on the other hand,\n builds a statistical description of stellar evolution by calculating a regression model for each individual parameter from the training data. \n The BA1 method requires that each input observable is perturbed with random Gaussian noise according to its measurement uncertainty. Monte Carlo perturbations are performed $10,000$ times and each instantiation evaluated by the RF to yield individual density distributions for each stellar parameter. Thus the uncertainty in $T_{\\text{eff}}$, or any observable for that matter, will only impact on the predictions \n of each parameter in proportion to the degree to which it features in that parameter's regression model.  \n\n \n The methodology, combined with the speed of the RF, provides a tractable means to \n asses how the individual measurement uncertainty of an observable will impact upon each predicted stellar quantity. We hence determine  how accurately the observables must be measured in order to achieve a desired precision from the RF.\n \n \n \nWe train a RF on the observables listed in Table~\\ref{tab:sun}.\nWe take the (approximate) solar value of each observable as our measurement and consider\n`observational uncertainties' ($\\sigma$) within the ranges specified in Table~\\ref{tab:sun}. \nWe first perturb the measurement values with Gaussian noise assuming the minimum $\\sigma$ values listed. We produce $10,000$ instantiations for that set of $\\sigma$ values, ensuring each perturbed observable remains within the limits of our training grid.\nWe evaluate stellar parameters and determine detailed distributions for that set of uncertainties. We repeat the process increasing the $\\sigma$ for a single observable  always keeping the  $\\sigma$ values of the other observables at their minimum. \nWe draw $50$ $\\sigma$ values for each observable sampling their specified ranges evenly.  We produce  probability density distributions for $250$ sets of $\\sigma$ values, the results of which are summarized in Figure~\\ref{fig:uncert1}.  \n\n\n \n \\begin{table}\n \\centering\n    \\caption{Central values and uncertainty ranges used for predicting the Sun in Figure~\\ref{fig:uncert1}.}\n    \\begin{tabular}{lccc}\n    \\hline \\hline\nQuantity & Value & Min($\\sigma$) & Max($\\sigma$) \\\\ \\hline \n$T_{\\text{eff}}$ (K)  & 5777 & 10  & 500\\\\\n$\\log{} g$ &  4.43812 & 0.00013 & 1.0\\\\\n$[\\text{Fe/H}]$ & 0.0 & 0.05 & 0.2 \\\\\n%$\\nu_{\\max}$ & 3050 & 30  \\\\\n$\\langle\\Delta\\nu_0\\rangle$ ($\\mu$Hz) & 136.0 & 0.5 & 10\\\\\n$\\langle\\delta\\nu_{02}\\rangle$ ($\\mu$Hz)& 9.0 & 0.5 & 5 \\\\\n\\hline\n    \\end{tabular}\n    \\label{tab:sun}\n\\end{table}\n\n \nIn Figure~\\ref{fig:uncert1} we plot the median value (solid line) and the $68\\%$  confidence interval (shaded region)\n for $M$, $\\tau$, $L$ and $R$ as a function of the uncertainty applied to each observable. The figure is organised such that each row (and color) corresponds to the observable that has had its uncertainty increased and each column corresponds to the model parameter of interest. In this Figure, the left axis indicates the predicted value from the RF and the right axis indicates the relative error with reference to the true values of the Sun.  The horizontal dotted grey lines mark the reference value in each case whilst the dotted vertical lines indicate a typical uncertainty for the perturbed observable. \n\nThe particular RF we have trained does not significantly rely on $T_{\\text{eff}}$ in its regression model for $M$, $\\tau$ or $R$. As the radius is supplemented by the seismic quantities, any uncertainty in $T_{\\text{eff}}$ is propagated as uncertainty in the luminosity. We find a typical uncertainty of $100$~K corresponds to an error of ${\\pm 0.2}$ $L$/L$_{\\odot}$ at the $68\\%$ confidence level.\n\nThe inference on solar mass is affected once ${\\delta \\, \\log{} g > 0.03}$. \nHowever, even at unreasonably large values of  ${\\delta \\, \\log{} g = 1}$, the uncertainties for mass and age remained relatively constrained by additional seismic information. We find \nthat $L$ and $R$ are far more reliant on ${\\log{} g}$ in their regression function with uncertainties in these quantities growing significantly once  ${\\delta \\, \\log{} g > 0.1}$.\n\nThe feature importances in BA1 indicate that ${[\\text{Fe/H}]}$ is used most often by the RF in  crafting its decision rules.  The four stellar parameters we investigate here indeed all rely on information from ${[\\text{Fe/H}]}$, however, they are supplemented by seismic information which helps to constrain the uncertainty in their predictions. It is the model parameters such as the mixing length, degree of overshoot and initial metallicty  that become much less certain as we increase ${\\sigma([\\text{Fe/H}])}$ (not shown here).  \n\n \n\nThe seismic diagnostics are very sensitive to the stellar structure, and hence also those  parameters we use to characterize a star ($M$, $\\tau$, $L$ and $R$). We have seen how reliant the RF is on the seismic diagnostics in the  regression models, allowing us to still predict the structural properties with relatively good precision in the face of large spectroscopic uncertainties. Without accurate measurement of ${\\langle\\Delta\\nu_0\\rangle}$ the uncertainty in structure parameters increase significantly. Whilst the uncertainty in ${\\langle\\delta\\nu_{02}\\rangle}$ does introduce some small uncertainty in $M$, $L$ and $R$, as expected, its accuracy significantly impacts upon our ability constrain stellar age. \n\n\n\n\n\n%\\afterpage{\n%\\clearpage\n%\\cleartoleftpage%\\cleardoublepage\n    %\\clearpage% flush all other floats\n    %\\ifodd\\value{page}\n    %\\else% uncomment this else to get odd/even instead of even/odd\n    %    \\expandafter\\afterpage% put it on the next page if this one is odd\n    %\\fi\n\\begin{landscape}\n%\\pagestyle{lscape}\n\\begin{figure}\n    \\centering\\vspace*{-0.75cm}\n    \\includegraphics[width=0.9\\linewidth,keepaspectratio]{sununcert.pdf}\n    \\caption[Impact of uncertainties on predictions of mass, age, luminosity and radius]{(Caption on other page.) \\label{fig:uncert1}}\n        %\\includegraphics[width=0.95\\textheight,height=0.95\\textwidth,keepaspectratio, angle=90]{stest.pdf}\n    %\\caption{(Continued on the following page.) \\label{fig:uncert1}}\n    %\\caption{Predictions for the solar mass, age, luminosity and radius as a function of the uncertainties applied to key observables. In each panel we have perturbed the quantity on the abscissa in isolation, centred around the measured value listed in  Table~\\ref{tab:sun} and with the uncertainties in the ranges specified therein. We indicate the median predicted value (solid line) and the 68\\%  confidence interval (shaded region). The dotted horizontal lines mark the zero point or true value in each panel and the vertical line indicates a typical observational uncertainty for the perturbed quantity.}\n    %Predictions for the mass, age, luminosity and radius of the Sun each as a function of the uncertainty applied to a key observable.} \n\\end{figure}\n\\end{landscape}\n%}\n\\begin{figure}\n  \\contcaption{Predictions for the solar mass, age, luminosity and radius as a function of the uncertainties applied to key observables. In each panel we have perturbed the quantity on the abscissa in isolation, centred around the measured value listed in  Table~\\ref{tab:sun} and with the uncertainties in the ranges specified therein. We indicate the median predicted value (solid line) and the  $68\\%$  confidence interval (shaded region). The dotted horizontal lines mark the zero point or true value in each panel and the vertical line indicates a typical observational uncertainty for the perturbed quantity.}% Continued caption\n\\end{figure}\n%\\end{landscape}\n%}\n\n\n\n\\section{Discussion}\n\\label{sec:disc}\n\n\nAdvances in stellar evolution theory are usually sought through refinement of the standard canonical model.  In this classical approach, observations reveal  behaviour that cannot be explained by the current stellar theory, a model is constructed, analysis of the resultant predictions are carried out and conclusions on the efficacy of that model drawn. In this study we adopted a complementary approach: an exploratory based method whereby we performed statistical analysis of models covering a large range of known physics. Rather than first develop a new model to evaluate, we explored the current paradigm to quantify existing relationships and draw new conclusions.  \n\nSome of the techniques employed in this analysis are over $100$ years old and in many areas of research are powerful standalone tools. They have rarely featured in the field of stellar modelling. Here we comment briefly on the timing of our manuscript which we attribute to two main factors: the advent of supervised machine learning techniques and modern computing resources.  \n\nRandom forests are an integral part of the present analysis and are a modern technology.\nThey help place the use of statistical methods in stellar evolution in a wider practical context.  Elucidating both the relationships found by RF and the exploitable information inherent in the model data provided motivation for the use of techniques such as PCA and correlation analysis.  The RF further facilitated the application of these methods due to the requirement that the models be cast  into a comprehensive evolutionary matrix; something that is not strictly necessary for grid based searches.     \n\nOur approach shares similarities to that taken by \\citet{1994ApJ...427.1013B} although we differ in methodology. Since their work, we have seen the necessary increase in computing power and the success of the \\emph{Kepler} and CoRoT space missions.  The statistical analysis here requires a well sampled grid of stellar models both with structure and oscillations computed. It cost a week of modern supercomputing time to generate the matrix upon which these operations are performed. Evaluating and training approximately $50,000$  RFs itself is also a computationally expensive endeavour.\n\n\n\\subsection{Features of the Dataset}\nIt is not clear \\emph{a priori} through inspection of the equations of stellar structure, if and how any two emergent quantities of the models co-vary. \nThere are, of course, combinations of parameters whose covariances are well-founded in stellar theory, but there exist quantities whose diagnostic power remain underutilized and could in fact offer additional insight into the underlying models.\nBringing such relationships to light over the collective lower main sequence is a key aim of our statistical investigation. \nThe correlations in the truncated grid (Figure~\\ref{fig:filt_corr}) and full BA1 grid (\\ref{fig:corr}) reveal the relationships that can be utilized to constrain each of the quantities listed in Table~\\ref{tab:parmdefs}.\nMany of the model properties that we wish to infer correlate with several observables simultaneously.  This indicates that the observables carry redundant information about the star. \nIn addition, observables co-vary amongst themselves. During  iterative model searches some of the covariances, such as between the seismic ratios, are taken into account.  However, for example, it is possible to obtain independent measurements of $\\nu_{\\max}$, ${\\langle\\Delta\\nu_0\\rangle}$, and ${\\log{} g}$. Treating these as independent degrees of freedom without considering model covariances then biases the fit towards the parameters to which these quantities pertain and can result in a solution that is overfit. \n\nWe determined the degree of degeneracy in the observables through PCA dimensionality reduction. \nAs mentioned previously, RF regression falls under the umbrella of \\emph{supervised} learning, whereas PCA is a form of \\emph{unsupervised} learning. \nThe difference is that in supervised learning, there is a correct answer that the algorithm is trying to understand how to reproduce.\nIn the case of unsupervised learning, the machine attempts to directly infer properties of data without any help from the supervisor. Hence, regression and classification analyses are forms of supervised learning, whereas cluster and factor analyses are examples of unsupervised learning.\nIn the case of supervised learning there is a clear measure of success in the resultant model. \nThere is a desired output that the inputs try to match. \nThe efficacy can be quantified and evaluated via, say, cross-validation or information-theoretic metrics. \nUnsupervised learning methods simply try to identify features and in the case of PCA these features are not necessarily interpretable. \n\nThe PCA in Section~\\ref{sec:PCA} focused on the truncated grid. It comprises $11$ stellar observables of all which carry information on the model properties to varying degrees. \n We found that $99.2\\%$ of the variance in the observables could be explained by five components with\nnearly $98\\%$ of the data are explained by four components. It could be argued that PC$_5$ explains noise rather than features, however, we found that PC$_5$ displays distinct enough correlations (i.e., with near surface physics) that it warrants inclusion in our analysis. \nThe clear dimensionality reduction, from $11$ observables to five PCs,  highlights the value in performing PCA: had we found comparable contributions from each component, we would have instead confirmed a clear dominance from higher order relations and an inadequacy of an approach based on linear analysis. \n\n\nOur primary goal in Section~\\ref{sec:PCA} was to reduce the dimensionality of the observables.\nWe initially considered regions of the parameter space where observations have shown stars to occupy. \nFollowing on from the rank correlation tests in Section~\\ref{sec:RCT} we applied PCA to a truncated version of the BA1 grid.  \nHowever, the results of the PCA depend on the properties of the data and will change depending on features such as the parameter ranges and number of models in the grid. \nFor example performing PCA on the full set of evolutionary tracks ($340,800$ models) demands that components are dedicated to explaining variance in (wider) unobserved regions of the parameter space. \nIn order to demonstrate that our interpretations of the PCs are robust, we repeated the PCA on four different subsets of the BA1 grid. \n We made cuts to the mass and metallicity ranges on the training data the results of which are included in Appendix \\ref{sec:PCAg} by means of qualitative correlation plots. \n \nThe PCs of the respective grids explain a similar percentage of the variance in each grid: PC$_1$ accounts for approximately  $40\\%$ of the variance,  PC$_2$  approximately  $35\\%$  etc.,  with more than  $75\\%$ of the variance in the observables explained by the first two PCs. \nWe interpret this result as the PCA capturing essentially the same five inherent `features' in the observables. \nIt follows that the choices in grid size and parameter range have only a small effect on the explained variances.\nAnalysis of all four grids helps further illustrate that there is redundant information carried in some observables, particularly the seismic separations and ratios. \nVarying the parameter ranges changes the correlations between the PCs and observables (loadings) yet the PCs still explain a similar percentage of the variance in each case.  \nDue to the information redundancies the PCs can be constructed such that same features are captured with different linear combinations of the observables.\nHow exactly a PC is constructed in a particular grid will depend on the amount of variance in the observables imparted by the chosen parameter ranges. \n\n\nWith respect to the independent model parameters, it is no surprise that in general PC$_1$ is strongly correlated with the stellar mass ($M$) and  and PC$_2$ with initial metallicity ($Z_0$). \nThese are the principal determinants of stellar evolution in that order and both impact upon the stellar structure independently.\nIn the two grids where we have cut the mass and metallicity ranges we find that the loading of $T_{\\text{eff}}$ is larger in PC$_1$.\nThis is because in the more solar-like tracks $T_{\\text{eff}}$ is a strongly monotonic function of evolution.\nThe surface aspect of PC$_2$ is then supplemented with some information from  ${\\log{} g}$ and ${[\\text{Fe/H}]}$.\n\nReducing the dimensionality of the observables and relating them back to the model parameters without redundancy aided with the interpretation of the PCs. \nWhilst it is useful to have the observables so succinctly described, it does not provide insight into the model parameters we wish to infer. \nWe thus condensed the information from the correlation plots into a $\\Lambda$ score which \nis the sum of the square of the correlation coefficients  between the model parameters and the PCs (determined for the observables). Squaring the correlation coefficients is equivalent to the squaring the PC loadings of the centered and scaled observables. \nThe score is a means to quantify the extent to which information from the model parameters, dependent and independent, are encoded in the observables.\nWe calculated $\\Lambda$ scores for all four grids upon which PCA was performed (Appendix \\ref{sec:lambdaa}) and indeed found mostly consistent results. We note some differences arise in the initial model parameters such as $\\alpha_{\\text{MLT}}$ and $\\alpha_{\\text{OV}}$ which reflect their underlying \ndistributions from the choices in grid truncation. The above analyses can be applied to any combination of observables and model parameters to gauge their utility.\n\n\n\n\\subsection{Exploiting the Inherent Relationships}\n\nUnderstanding the inherent properties of the collective lower main sequence is the first step in elucidating the BA1 RF regression. The statistical analysis quantified what information was present in the training data for the RF to exploit. We illustrated why the available data permit BA1 to predict parameters such as $M$, $R$ and $L$ with such high precision and why initial model parameters such as $D$ and $\\alpha_{\\text{MLT}}$ remain uncertain in comparison. Whilst  Section~\\ref{sec:RCT} and Section~\\ref{sec:PCA} demonstrated the breadth of information available to the RF, in Section~\\ref{sec:qu} we determined how the information could best be used. \n\nRFs are amongst the most powerful tools in mathematics for non-linear regression. \nThe BA1 RF uses the observables, creating a set of decision rules that reduce the variance in the parameter it is fitting.\nWhilst feature importances provide some insight into this process as a whole it does not provide specific details for the individual parameters. \nBy performing non-parametric multiple regression with every combination of observable in our grid,  \nwe demonstrated how the correlations in Figure~\\ref{fig:filt_corr} could best be exploited and best combined to reveal the most information about each stellar quantity.\nTwo of the observables, ${[\\text{Fe/H}]}$ and ${\\langle\\delta\\nu_{02}\\rangle}$ (or as a ratio),  are of vital importance in model fitting procedures as they provide indispensable pieces of independent information that cannot be inferred from other quantities.  \n\nWe in effect invert the observations for the model parameters based on functions learnt from the training data. \nThus we can determine the relative importance of each observable for inferring the model parameters. We, in addition, provide a precision with which we can determine each model parameter \\emph{directly} from the information contained in the observables. \nThe attainable precision is a function of the number of initial model parameters that are varied and the model degeneracy in the data. \nFor example, with perfect information from the observables, the six dimensions in the BA1 grid limits our inference on mass to \n${\\mu (\\epsilon) =0.02 \\ \\Mo}$. \n\n\nMany of the Tables in Section~\\ref{sec:qu} demonstrated an important property of the RF. \nIn the case of missing or unreliable measurements of an observable, the RF can draw upon information redundancies in the data to determine new regression rules for the model parameters.\nIn principle, such redundancies can lead to biases and overfitting in iterative model finding methods.\nDuring such search procedures the best fitting stellar model is the one that best matches all of the observations but each observation only bares on some parts of the model, and observations can contain redundant information.\n%In practise, procedures that match oscillation modes will be dominated by the precision of the individual frequencies and the accurate constraints they place on the stellar interior.\n\n\nThrough statistical bagging and multiple regression the RF is less likely to overfit. %avoids the problem of overfitting. \nThese underlying methodologies are the reason why in Section~\\ref{sec:accu} many of the parameters we inferred remained well constrained despite large uncertainties in some of the observables.   \nIn statistical bagging different subsets of the training grid are sent to different nodes. Each node will use information theory to create a set of decision trees to explain the parameter of interest. The nodes will differ in their rules and choice of parameters. Thus the uncertainty in an observable will only impact on the parameter we infer to the extent to which the observable is used in the rules.  \nTake the example from Figure~\\ref{fig:uncert1} where with a ${5\\;\\mu}$Hz uncertainty in ${\\langle\\Delta\\nu_0\\rangle}$ the RF still predicts the solar properties albeit with slightly less confidence.\nThe other observables help constrain the predictions. \n\nPart of the analysis in Section~\\ref{sec:qu} demonstrated the best possible (average) precision in which we can hope to infer stellar parameters. Our error analysis in Section~\\ref{sec:accu} is an extension of this. Rather than assume perfect information we determined  \n the measurement accuracy required of the observables to attain a desired precision from the RF.\nOur analysis focused on the Sun and is indicative of solar-like analogues.\nIn Table~\\ref{tab:relabunds} we saw some of the large uncertainties associated with retrodicting abundances in low-metallicity stars. We have greater degeneracy with the efficiency of diffusion and the initial abundances. These large error scores by no means indicate that the RF is incapable of characterizing low-metallicity stars. Rather it is an honest appraisal of stellar uncertainties when we do not make assumptions of the initial abundance say through a dY/dZ  chemical evolution ``law\"  or a fixed diffusion efficiency. Our error analysis here does not take into account covariances and was designed to investigate the impact on an observable-by-observable basis.\nA more detailed error analysis and the associated issues at low metallicity form the focus of a forthcoming paper.  \n\n\n\\subsection{Implications for the TESS and PLATO missions}\n\nThe NASA TESS mission \\citep{2015JATIS...1a4003R} and ESA's PLATO \\citep{2014ExA....38..249R} herald a new age for the space-based photometry and the detection of planetary transits. Due to launch in 2018 and 2025 respectively, their common primary science mission is to identify terrestrial planets around bright stars. The pre-selection of bright targets will ensure that the stellar hosts can be further analyzed with spectroscopy and it is expected that many of the planet candidates will be suitable for atmospheric follow-up (ideally) with the James Webb Space Telescope. As was the case with the \\emph{Kepler} and \\emph{CoRoT} missions, the photometric time-series observations will prove useful to asteroseismology. In the case of PLATO the study of the stellar structure through asteroseismology is a key science goal in the mission design \\citep{2014ExA....38..249R}.  \n\nTESS will monitor photometric variations of ${> 10^5}$ low-mass main-sequence stars. Under its `step and stare' pointing strategy, fields will be monitored for periods ranging from one month to one year depending primarily on their ecliptic latitude. With its two minute and $30$ minute cadences, TESS will be able to detect small rocky planets around solar like stars at $\\le$ 7th magnitude. It is expected to detect of the order $1,700$ planets with sub-Neptune masses \\citep{2016ApJ...830..138C} and will identify many more larger planets around dimmer targets.  The asteroseismic potential of TESS has been rigorously investigated by \\citet{2016ApJ...830..138C}. Their analysis of the expected TESS photometry indicates the presence of an oscillation power excess \nin low-mass main-sequence stars when there is no systematic noise present in the data. With an expected systematic noise level of  $60$ ppm hr$^{1/2}$ from the mission, their analysis indicates a detectable power-excess in F-dwarfs as well as sub giants and red giants -- this owing to the higher luminosity and hence larger mode amplitudes in these stars. For a majority of stars the $27$ day pointing is insufficient to extract detailed asteroseismic diagnostics such as mode frequencies or separations. Rather, the seismic information will be limited to the determination of $\\nu_{\\max}$ in stars where the power-excess is detected. As a consequence, masses and radii for the TESS targets are to be determined using a combination of  GAIA data, the  $\\nu_{\\max}$ -- ${\\langle\\Delta\\nu_0\\rangle}$ power law \\citep{2009A&A...506..465H,2009MNRAS.400L..80S} , asteroseismic scaling relations and grid-based searches.  \n \n\nThe number of small planet detections from the PLATO mission is expected to eclipse the number found by \\emph{Kepler}\nand TESS by up to three orders of magnitude. In addition, the PLATO pointing strategy will allow for the measurement of oscillation frequencies in $> 80,000$ dwarf and subgiant stars with magnitudes less than $11$.  In total the mission will provide approximately one million light curves for stars with brightness $\\le$ 13th magnitude \\citep{2014ExA....38..249R}. In many stars modes up to spherical degree ${\\ell =3}$ will be detected with typical frequency uncertainties in the range  $0.1$ -- $0.3\\;\\mu$Hz. The second major science goal of PLATO is to \nprobe stellar structure and evolution by asteroseismology and provide support to exoplanet science through determining\n\\begin{itemize}\n\\item stellar masses with an accuracy of better than  $10\\%$,\n\\item stellar radii accurate to $1$--$2\\%$, and\n\\item ages of solar-like stars accurate to  $10\\%$.\n\\end{itemize}\n\nHere we treat the `Sun as a star' in order to quantify how well we can characterize target systems observed by the \nupcoming space missions and to determine the prospect of meeting the accuracy requirements.  \nIn Table~\\ref{tab:tpl} we indicate the observables the missions are likely to provide. \nWe degrade the corresponding solar data according to the expected uncertainty from the respective measurements.   \nAs GAIA is complete down to 20th magnitude we have assumed that distances and hence luminosities will be available for all targets in these missions. We consider data for TESS targets assuming both $60$~ppm~hr$^{1/2}$ and no systematic noise in the photometry. Thus in the case of the latter we anticipate that an oscillation power excess can be extracted for a solar-like star and $\\nu_{\\max}$ determined. The large and small frequency separations for the PLATO data are determined by degrading a subset of solar frequencies using the method described in BA1. We take a conservative approach in this calculation and assume that the ${\\ell=3}$ modes are not extracted.\n\n\n\n\n\\afterpage{\n\\cleardoublepage\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=\\textwidth,height=1.02\\textheight, keepaspectratio ]{tess_plato3.pdf}\n    \\caption[Recovering solar parameters using observations expected for targets from TESS and PLATO]{(Caption on other page.)  \\label{fig:TessPlato}}\n\\end{figure}\n\\begin{landscape}\n\\begin{figure}\n    \\contcaption{Predictions for the `Sun as a star' using observations expected for targets from TESS (assuming two different systematic noise levels) and PLATO space missions. In each panel we list the median with uncertainties ($84\\%$--$50\\%$ confidence intervals and $50\\%$--$16\\%$ confidence intervals)   for the quantities as well as the relative error in our prediction.} \n\\end{figure}\n%\\begin{deluxetable*}{lccccccccc}\n\\begin{table} %\\scriptsize\n\\centering\n%\\tablewidth{0pt}\n\\caption{Solar data degraded to the level expected for sun-like stars in: the TESS catalogue assuming systematic  noise of $60$~ppm~hr$^{1/2}$ from the mission, TESS assuming no systematic noise and from PLATO. For each set of observables we include the feature importances from the random forest used in characterizing the `Sun as a star.' Note that in the case of the expected PLATO data we have perturbed a subset of frequencies according to their distance from $\\nu_{\\max}$. The numbers reported for the separations and ratios are thus the respective means and standard deviations of $10,000$ perturbations to the data which we evaluate to determine our parameter distributions. \\label{tab:tpl}} \n%\\hspace*{-1.1cm}\n\\begin{tabular}{l|ccc|ccc|ccc}\n\\multicolumn{1}{c}{} &\n\\multicolumn{3}{c}{TESS ($60$~ppm~hr$^{1/2}$)}   &\n\\multicolumn{3}{|c|}{TESS ($0$~ppm~hr$^{1/2}$)}   &\n\\multicolumn{3}{c}{PLATO} \\\\\\hline\nParameter  &\nValue &\nUncertainty &  \nImportance &\nValue &\nUncertainty &\nImportance &\nValue &\nUncertainty &\nImportance \\\\\\hline\n$T_{\\text{eff}}$ (K) & 5778 &100 &29.3\\% & 5778 &100 &26.7\\%& 5778 &100 &16.2\\%\\\\\n$[\\text{Fe/H}]$ &-0.014 &0.021 &34.3\\% &-0.014 &0.021 &33.4\\% &-0.014 &0.021 &27.9\\%\\\\\n$\\log{} g$ &4.43 &0.07 &18.5\\% &4.43 &0.07 &12.4\\% &4.43 &0.07 &8.8\\\\\n$L \\ (L/\\text{L}_{\\odot})$   &0.98  &0.04 &18.0\\% &0.98  &0.04  &16.7\\% &0.98  &0.04  &7.8\\%\\\\\n$\\nu_{\\max} \\ (\\mu \\text{Hz})$  & -- & -- & -- &3093 &100 &10.8\\% & -- &-- & --\\\\\n$\\langle\\Delta\\nu_0\\rangle  \\ (\\mu \\text{Hz})$  & -- & -- & -- & -- & -- & -- &134.81 &0.05 &6.4\\%\\\\\n$\\langle\\delta\\nu_{02}\\rangle  \\ (\\mu \\text{Hz})$  & -- & -- & -- & -- & -- & -- &9.02 &0.15 &7.1\\% \\\\\n$\\langle r_{01}\\rangle$ & -- & -- & -- & -- & -- & -- &0.0226 &0.0005 &7.4\\%\\\\\n$\\langle r_{10}\\rangle$ & -- & -- & -- & -- & -- & -- &0.0227 &0.0005 &7.3\\% \\\\\n$\\langle r_{02}\\rangle$& -- & -- & -- & -- & -- & -- &0.0668 &0.0011 & 11.1\\%\n\\end{tabular}\n\\end{table}\n%\\enddata\n%\\end{deluxetable*}\n\\end{landscape}\n%\\newpage\n%\\afterpage{\n}\n%}\n\n\nFigure~\\ref{fig:TessPlato} shows our predictions for masses, radii, ages, initial helium and metallicity for a `Sun-as-a-star' exercise. In each panel we indicate the median of the probability density distribution and the corresponding  uncertainty from the $16\\%$ and $84\\%$ confidence intervals for the parameter we are predicting. In addition we determine the relative error which we define as ${\\epsilon = 100 \\cdot \\sigma/\\mu}$  where $\\mu$ is the mean and $\\sigma$ is the standard deviation of the distributions. In Appendix \\ref{sec:PSM} we further demonstrate the impact of the measurement uncertainty on the prediction of each quantity as per Figure~\\ref{fig:uncert1}.\n\n\nAlthough we can expect accurate mass determinations for targets in both missions, the supplementary seismic data from PLATO allows us to improve the precision with which we determine mass by approximately a factor of two. This is despite the fact the RF has identified a less-likely but not impossible (slightly) younger, higher-mass, higher-metallicity solution from the  PLATO  data (we find bimodalities for most quantities predicted with the PLATO observables). In the case of TESS, the absence of the large frequency separation leads to greater uncertainty. One of the methods discussed  by \\citet{2016ApJ...830..138C} for the mass determination of TESS targets is to use the power law linking $\\nu_{\\max}$ to ${\\langle\\Delta\\nu_0\\rangle}$ (which has been shown to be accurate to $10$--$15\\%$) and apply the asteroseismic scaling laws (Equations \\ref{equ:nmax} and \\ref{equ:dnu}).  In Section~\\ref{sec:seispr} we demonstrated that the random forest exploits further information from  temperature or metallicity measurements to improve the accuracy of the $\\nu_{\\max}$ -- ${\\langle\\Delta\\nu_0\\rangle}$ relation.  Thus we expect the accuracy with which we predict mass from TESS data to represent an upper limit to that attainable by  applying the power-law and scaling relations. \n\nThe assumption of GAIA distances and hence stellar luminosities ensure that radii can be determined for targets in both missions; the seismology is essentially redundant for the inference of the stellar radius.  We note that the relative error for  PLATO in our `Sun-as-a-star' test  is a factor of two higher than the $1$--$2\\%$ expected by the consortium. This is a consequence of having identified bimodal solutions. Their target accuracy can likely be met if the uncertainties in the measurements are further reduced and a unimodal solution found. \n\nThe analysis in Section~\\ref{sec:seispr} has highlighted the necessity of the small frequency separation  in order to \ntightly constrain the ages of field stars. The predictions for age in Figure~\\ref{fig:TessPlato} are therefore as expected. \nThe inclusion of oscillation frequencies and determination of the small frequency separation (and ratios) from PLATO data result in age uncertainties for solar-like stars to within the  $10\\%$ level.  Without information from the core, ages for TESS targets remain largely unconstrained and consistent with the accuracy typically expected when dating field stars spectroscopically. \n\n\n\n\n\n\\section{Conclusions}\nIn this work we examined the processes that allow random forest regression to rapidly and accurately infer stellar parameters \\citep{2016apj...830...31b}. We shed light on the inherent properties of the model training data that the algorithm can exploit. \n\n\\begin{itemize}\n   \n             \\item We demonstrated that there is a large amount of information redundancy in the stellar parameters which is integral to the efficacy of the random forest algorithm. Through statistical bagging, the random forest  creates sets of decision rules using different combinations of observables to infer a given quantity. The methodology results in  robust predictions and includes the ability to compensate for data that are missing or unreliable. \n             \n          \\item We illustrated the behaviour of parameters across the collective lower main sequence with the relationships that arise (e.g., age -- luminosity) different to those that develop internally along an evolutionary track. This is the inherent information the random forest draws upon in its regression.\n     \n         \\item  We found the parameter pairs that exhibit the strongest correlations correspond to well known asteroseismic and main-sequence relations.        \n         \n \n\n\n   \\item The random forest works well in cases when there is sufficient information and sufficient redundancy.\n   Through principal component analysis we quantified the degree of degeneracy in the observables. \n   Our analysis demonstrated that $99.2\\%$ of the variance in the $11$ stellar observables could be explained by five principal components.\n       \n             \n \\item The observables we have considered only carry five pieces of independent information.\n             During  iterative model searches it is common that independently determined parameters such as $\\nu_{\\max}$, ${\\langle\\Delta\\nu_0\\rangle}$, and ${\\log{} g}$ are treated as independent degrees of freedom. The composition of the principal components indicate that by not considering their model covariances, any fit is biased towards the common stellar information to which these parameters pertain.\n   \n\n  \\item We devised a score  which  allows us to rank the degree to which model parameters can be inferred from the observables.  Radius, luminosity, and main-sequence lifetime can be extracted  with confidence, however, the initial model parameters such as $\\alpha_{\\text{MLT}}$, $Y_0$ and $\\alpha_{\\text{ov}}$ are not sufficiently constrained by the observables and cannot be inferred directly from the data.  Our analysis can be extended in a straightforward manner to model parameters and observables not considered here.  \n  \n  \n  \\item Having elucidated the statistical properties of the training data, we sought to better understand how the random forest uses the data in its decision making rules.\nBy performing non-parametric multiple regression with every combination of observable in our grid we determined:\n\\begin{enumerate}\n    \\item  which observables are the most important/useful for each model parameter,\n    \\item  the minimum set of observables that satisfactorily constrain each model parameter, and\n    \\item  the precision with which we can determine each model parameter \\emph{directly} from the information contained in the observables. \n\\end{enumerate}\n\n\n\n\\item We examined the quantities on a parameter by parameter basis and here highlight the results for mass and age.  In a grid of stellar evolution models varied in six initial parameters we find that the average error in predicting mass across the grid is ${\\pm 0.02 \\ \\Mo}$ and  ${\\pm 282}$ Myr for age. The average error in age increases by a factor of three when we are limited to information from only two observables such as in the Christensen-Dalsgaard diagram. Three parameters are sufficient for constraining mass whereas we require five observables to determine age.  \n\n\n\\item We determined whether the random forest could reproduce the well-known power law that relates ${\\langle\\Delta\\nu_0\\rangle}$ to $\\nu_{\\max}$ and found that additional information from  $T_{\\text{eff}}$ or  $[\\text{Fe/H}]$ reduces the average error in the relation by a factor of two. \n\n\\item We investigated the measurement accuracy required of the observables to attain a desired precision from the random forest. \nThe processes of statistical bagging and multiple regression help mitigate the impact of large spectroscopic errors as the random draws upon complementary seismic information when devising its decision rules. \nThe results confirm that $[\\text{Fe/H}]$  and  ${\\langle\\delta\\nu_{02}\\rangle}$ are indispensable independent pieces of information for model fitting algorithms.\n\n\\item Finally, we determined the accuracy and precision with which we can expect to characterize solar-like stars observed by the upcoming TESS and PLATO space missions. In both cases masses can be accurately inferred and measurements from GAIA will ensure that radii are well constrained. Oscillation frequencies will not be detectable in most low-mass main sequence stars observed by TESS. In contrast, the availability of the small frequency separation for PLATO targets will permit accurately determined stellar ages. \n\\end{itemize}\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Acknowledgements %%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\\acknowledgments \n\\paragraph*{Acknowledgements}\n\\noindent The research leading to the presented results has received funding from the European Research Council under the European Community's Seventh Framework Programme (FP7/2007-2013) / ERC grant agreement no 338251 (StellarAges). E.B.\\ undertook this research in the context of the International Max Planck Research School for Solar System Research. S.B.\\ acknowledges partial support from NSF grant AST-1514676 and NASA grant NNX13AE70G. We thank Alexey Mints and the anonymous referee for their useful comments and discussions which helped improve this manuscript. \n\n\n%\\software \n\\paragraph*{Software} \n\\noindent Stellar models were calculated with  \\emph{Modules for Experiments in Stellar Astrophysics} r8118 \\citep[MESA,][]{2011apjs..192....3p} and stellar oscillations with the ADIPLS pulsation package 0.2 \\citep{2008Ap&SS.316..113C}. \nAnalysis in this manuscript was performed with python 3.5.1 libraries scikit-learn 0.17.1 \\citep{scikit-learn}, NumPy 1.11.0 \\citep{van2011numpy}, matplotlib 1.5.1  \\citep{Hunter:2007}, biokit 0.3.2 \\citep{biokit} and pandas 0.19.0 \\citep{mckinney2010data} as well as R 3.3.2 \\citep{R} and the R libraries magicaxis 2.0.0 \\citep{magicaxis}, RColorBrewer 1.1-2 \\citep{RColorBrewer}, parallelMap 1.3 \\citep{parallelMap}, data.table 1.9.6 \\citep{data.table}, ggplot2 2.1.0 \\citep{ggplot2}, GGally 1.2.0 \\citep{GGally}, scales 0.4.0 \\citep{scales} and  Corrplot 0.77. \n\n%\\bibliographystyle{aasjournal.bst}\n%\\bibliography{statistical_relations}\n\n\n\n\n\n\n\n\n\n\\section{Appendix}\n\n\n\\subsection{Seismic Definitions} \n\\label{sec:sdefs}\nWe denote any frequency separation $S$ as the difference between a frequency $\\nu$ of spherical degree $\\ell$ and radial order $n$ and another frequency: \n\\begin{equation} \n  S_{(\\ell_1, \\ell_2)}(n_1, n_2) \\equiv \\nu_{\\ell_1}(n_1) - \\nu_{\\ell_2}(n_2).\n\\end{equation}\nThe large-frequency separation is defined as\n\\begin{equation} \n  \\Delta\\nu_\\ell(n) \\equiv S_{(\\ell, \\ell)}(n, n-1)\n\\end{equation}\nand the small-frequency separation is\n\\begin{equation}\n  \\delta\\nu_{(\\ell, \\ell+2)}(n) \\equiv S_{(\\ell, \\ell+2)}(n, n-1).\n\\end{equation}\n\\citet{2003A&A...411..215R} have demonstrated that taking the ratio of the \\emph{local} large and small-frequency separations reduces the systematic offset introduced from improper modelling of the near-surface super-adiabatic region. This ratio is defined as: \n\\begin{equation}    %\\label{eqn:LSratio}\n  \\mathrm{r}_{(\\ell,\\ell +2)}(n) \\equiv \\frac{\\delta\\nu_{(\\ell, \\ell+2)}(n)}{\\Delta\\nu_{(1-\\ell)}(n+\\ell)}.\n\\end{equation}\nIn addition, it was shown that the frequency-dependent offset can be somewhat mitigated by constructing ratios from five-point frequency separations and the \\emph{local} large separation:\n\\begin{equation} \n  \\mathrm{r}_{(\\ell, 1-\\ell)}(n) \\equiv \\frac{\\mathrm{dd}_{(\\ell,1-\\ell)}(n)}{\\Delta\\nu_{(1-\\ell)}(n+\\ell)} %\\label{eqn:rnl}\n\\end{equation}\nwhere the five point separations are defined as:\n\\begin{align} \n  \\mathrm{dd}_{0,1} \\equiv \\frac{1}{8} \\big[&\\nu_0(n-1) - 4\\nu_1(n-1) \\notag\\\\\n                                 &+6\\nu_0(n) - 4\\nu_1(n) + \\nu_0(n+1)\\big]\\\\ \n  \\mathrm{dd}_{1,0} \\equiv -\\frac{1}{8} \\big[&\\nu_1(n-1) - 4\\nu_0(n) \\notag\\\\\n                                &+6\\nu_1(n) - 4\\nu_0(n+1) + \\nu_1(n+1)\\big]. \\label{eqn:dlast}\n\\end{align}\nWe calculate dozens of oscillation frequencies per star with the mode sets available dependent on the internal structure of an individual model. We thus determine a single representative value \nby following the prescription of \\citet{2012A&A...537A..30M}. In order to mimic how the oscillation spectra would appear in an observational data, we weight all frequencies by their position in a Gaussian envelope with  full-width at half-maximum of ${0.66\\cdot\\nu_{\\max}{}^{0.88}}$ and centered at the predicted frequency of maximum oscillation power $\\nu_{\\max}$.  We then calculate the weighted median of each variable, which we denote with angled parentheses (e.g.\\ ${\\langle r_{1,0}\\rangle}$).\n\n\n\n\n\n\\subsection{Asteroseismic Scaling Relations}\n\n\n\\begin{equation}\n\\nu_{\\max} \\approx \\frac{ M/M_{\\odot}(T_{\\text{eff}}/T_{\\text{eff},\\odot})^{3.5}}{L/L_{\\odot}} \\nu_{\\max,\\odot} \\: \n\\label{equ:nmax}\n\\end{equation}\n\n\\begin{equation}\n\\Delta\\nu \\approx \\frac{(M/M_{\\odot})^{0.5}(T_{\\text{eff}}/T_{\\text{eff},\\odot})^{3}}{(L/L_{\\odot})^{0.75}}\n\\Delta\\nu_{\\odot} \\: \n\\label{equ:dnu}\n\\end{equation}\n\n\\citet{2016MNRAS.460.4277G} have shown that a metallicity-dependent correction is required for the Equation~(\\ref{equ:dnu}) scaling relation.\nThe ${\\Delta\\nu_{\\odot}}$ term can be replaced with a more appropriate reference value which can be calcuated according to:\n\n\n\\begin{equation}\n\\Delta\\nu_{\\text{ref}}= A \\cdot e^{\\lambda T_{\\text{eff}}/10^4K} \\cdot (\\cos(\\omega \\cdot T_{\\text{eff}}/10^4K+\\phi))+B,\n\\label{eq:corrfunc2}\n\\end{equation}\nand where the unkown terms are listed in Table~\\ref{tab:pars2}. \n\n \n\\begin{table}\n\t\\centering\n\t\\caption{Parameters of the correction function.}\n\t\\label{tab:pars2}\n\t\\begin{tabular}{lc} % four columns, alignment for each\n\t\t\\hline\n\t\tA & 0.64$\\cdot$[Fe/H] + 1.78  $\\mu Hz$ \\\\\n\t\t$\\lambda$ & $-$0.55$\\cdot$[Fe/H] + 1.23  \\\\\n\t\t$\\omega$ & 22.21 rad/K \\\\\n\t\t$\\phi$ & 0.48$\\cdot$[Fe/H] + 0.12 \\\\\n\t\tB & 0.66$\\cdot$[Fe/H] + 134.92 $\\mu Hz$ \\\\\n\t\t\\hline\n\t\\end{tabular}\n\\end{table}\n\n\n\n\n\\subsection{Correlation Plot} \n\\label{sec:fullcorr}\n\n\nThe full BA1 grid introduces some biases in our correlation analysis, particularly from tracks with calculated with  high-mass and/or high-diffusion. Correlation analysis with all models included are presented in Figure~\\ref{fig:corr}. \n\\begin{figure*}\n    \\centering\n    \\includegraphics[trim={1cm 0 2cm 1cm},clip,\n    width=\\textwidth]{corr-spearman.pdf}\n    \\caption[]{Spearman rank correlation matrix comprising various stellar and asteroseismic parameters. The quantities are as described in Table~\\ref{tab:parmdefs}\n    with model input parameters marked in purple above. The complete grid of models are considered here. The size and color of each circle indicates the sign and magnitude of the Spearman rank coefficient, $\\rho$, between two variables.  All correlations are significant excepting the entries indicated with a cross. The variables are ordered by the first principal component of the correlation matrix. }\n    \\label{fig:corr}\n\\end{figure*}\n\nA major difference that arises between Figure~\\ref{fig:filt_corr} and Figure~\\ref{fig:corr} is in the ordering of variables. Recall that we report the quantities according to the first principal component of the correlation matrix. Different combinations of variables are required to maximise the variance of each principal component in the new parameter space. Although the PCA analysis in Figures \\ref{fig:corr-pcaobs} and Figures \\ref{fig:corr-pcamods} rely on Pearson rather than Spearman correlations, they do demonstrate the difference in the composition of the PCs in each grid. \n\nWe also find differences in the correlations that pertain to current surface abundance parameters. Consider the pair M -- $Y_{\\text{surf}}$. In Figure~\\ref{fig:corr} we find a small but non-negligible negative correlation. The reason being that higher mass tracks diffuse the helium from their surface more efficiently than low-mass stars.  Without the influence of these stars in our sample, our significance test yields a null correlation in Figure~\\ref{fig:filt_corr}; the expected result from a quasi-random distribution of initial abundances. \n\nTwo interesting features emanating from our grid selection relates to the parameter pairs ${\\langle\\delta\\nu_{02}\\rangle}$ -- $T_{\\text{eff}}$ and ${\\langle r_{02}\\rangle}$ -- ${\\log{} g}$. \nWe find a null correlation  between ${\\langle\\delta\\nu_{02}\\rangle}$ -- $T_{\\text{eff}}$ in truncated grid however this emerges as a small positive correlation when the full grid is considered. \nIn Section~\\ref{sec:sages} we discussed the redundancy in the C--D diagram when projecting stellar models varied in six dimensions into a two-dimensional parameter space.  Thus the  null correlation \narising from the truncated grid reflects the fact there many combinations of (primarily) mass and metallicity and hence temperature at a given age.  \nThe full grid, however, consists of a large number of hot short-lived stars that impart a noticeable trend. \n\nA similar argument applies to ${\\langle r_{02}\\rangle}$ -- ${\\log{} g}$. There are a great number of combinations of ${\\langle\\Delta\\nu_0\\rangle}$ and\n${\\langle\\delta\\nu_{02}\\rangle}$ for a given ${\\langle r_{02}\\rangle}$ thus in the truncated grid no correlation with ${\\log{} g}$ is registered. \nOnce again the number of massive short-lived stars bias this previous null correlation. \n\n\nFinally we note two minor results. Some pairs of parameters in the truncated grid which report null correlations in  Figure~\\ref{fig:filt_corr},  show very weak correlations in Figure~\\ref{fig:corr}. \nWe refer to  L -- $\\alpha_{\\text{ov}}$ and $\\alpha_{\\text{MLT}}$ -- ${\\langle\\delta\\nu_{02}\\rangle}$ as cases in point. The correlations remain very weak in the current analysis and the larger sample size has introduced a minor trend that in this case passes our conservative significance criterion. We note also that most variables display a much stronger correlation with age in the full grid. \n \n\n\n\n\n\n\n\\subsection{Principal Component Analysis Explained Variance} \n\\label{sec:fullPCA}\n%\\iffalse\n\nThe PCs and their correlations will change depending on the number of dimensions included in the grid and the range of values each parameter takes; the PCs identify vectors of maximal variance. \nOur aim is to determine whether the PCs capture fundamental features ubiquitously encoded in the observables. \nThus, we wish to investigate the information inherent to the dimensions and mitigate the impact of parameter ranges on our PCs. \nIn order to provide a more robust interpretation we have calculated the PCs and their correlations with four different considerations given to the BA1 grid:\n\\begin{description}\n    \\item[\\textbf{Grid A}] The full BA1 training grid;\n    \\item[\\textbf{Grid B}] The truncated grid;\n    \\item[\\textbf{Grid C}] A grid where more than half the models in each track possess metallicities of [Fe/H] $> -2$; and\n     \\item[\\textbf{Grid D}] A grid with masses limited to ${M < 1.2}$~M$_{\\odot}$.\n\\end{description}\nQualitative correlations between the stellar parameters and the PCs in each grid are presented in Figures \\ref{fig:corr-pcaobs} and Figures \\ref{fig:corr-pcamods}.\n\n\n%\\begin{deluxetable*}{ccccccc}\n\\begin{table}\n\\centering\n%\\tablewidth{0pt}\n\\caption{Percentage of the variance explained by each principal component. We report the explained variance percentages for the complete grid of training models (Grid A) and for the truncated set (Grid B, see Section~\\ref{sec:RCT}) that better encompasses the observational parameter space. In each case we consider the grid with and without the inclusion of $\\nu_{\\max}$ which is estimated using the \\citet{1995A&A...293...87K} scaling relations rather than calculated from first principle equations. We also consider the explained variances when limits are placed on the metallicity (Grid C) and mass (Grid D) ranges of the models.  These grids are used in Section~\\ref{sec:disc} to help interpret the PCs. \\label{tab:PCAEV}} \n\\iffalse\n\\tablehead{\n        \\colhead{}  &\n        \\multicolumn{4}{c}{$\\nu_{\\max}$ Included}               &\n        \\multicolumn{2}{c}{$\\nu_{\\max}$ Excluded}\\\\\n        \\colhead{Component}  &\n        \\colhead{Grid A} &\n        \\colhead{Grid B} &\n        \\colhead{Grid C} &\n        \\colhead{Grid D} &\n        \\colhead{Grid A} &\n        \\colhead{Grid B} \n}\n\\startdata\n\\fi\n\\begin{tabular}{c|cccc|cc}\n        \\multicolumn{1}{c}{}  &\n        \\multicolumn{4}{c|}{$\\nu_{\\max}$ Included}               &\n        \\multicolumn{2}{c}{$\\nu_{\\max}$ Excluded}\\\\\\hline\n        Component  &\n        Grid A &\n        Grid B &\n        Grid C &\n        Grid D &\n        Grid A &\n        Grid B \\\\\\hline\nPC$_1$ \t&\t41.79\t&\t42.36\t& 42.49 & 42.74 &\t40.89\t&\t41.47\t\\\\\nPC$_2$ \t&\t36.12\t&\t34.18\t& 37.49 & 35.89 &\t36.52\t&\t33.65\t\\\\\nPC$_3$\t&\t9.17\t&\t11.65\t& 9.39  & 10.25 &\t8.99\t&\t12.21\t\\\\\nPC$_4$\t&\t7.69\t&\t9.79\t& 7.69  &  6.89 &\t8.27\t&\t10.58\t\\\\\nPC$_5$ \t&\t4.23\t&\t1.23\t& 2.14  &  3.36 &\t4.55\t&\t1.36\t\\\\\nPC$_6$\t&\t0.54\t&\t0.48\t&0.41    & 0.53   &\t0.48\t&\t0.51\t\\\\\nPC$_7$\t&\t0.25\t&\t0.18\t&0.24    &0.18    &\t0.16\t&\t0.12\t\\\\\nPC$_8$ \t&\t0.12\t&\t0.08\t&0.09    &0.10    &\t0.10\t&\t0.09\t\\\\\nPC$_9$\t&\t0.05\t&\t0.03\t&0.04    &0.04    &\t0.03\t&\t0.02\t\\\\\nPC$_{10}$ \t&\t0.02\t&\t0.01 &0.01   &0.01\t&\t0.01\t&\t0.00\t\\\\\nPC$_{11}$\t&\t0.01\t&\t0.00 &0.00   &0.00     &\t--\t    &\t--\t\n%\\enddata\n% \\end{deluxetable*} \n\\end{tabular}\n\\end{table}\n\n\\subsection{PCA Correlation Analysis} \\label{sec:ccoefs}\nFigures \\ref{fig:GCA-pcabar} and \\ref{fig:GCA-pcabarb} demonstrate the correlation strengths between our stellar parameters and the first five PCs. In Tables \\ref{tab:ocoefs} and \\ref{tab:ocoefs} we list the coefficients between all parameters and all PCs. The table is useful for  determining whether the transitive criterion applies to parameters within a given PC. It also aids in the calculation of the $\\Lambda$ scores in Section~\\ref{sec:ISP}.\n\n\n\\afterpage{\n\\clearpage\n\\begin{landscape}\n\\begin{table}\n\\centering\n\\caption{Pearson's~$r$ coefficients between the principal components and observables in the truncated grid.}\n\\label{tab:ocoefs}\n\\begin{tabular}{c|ccccccccccc}\n& $\\log{} g$ &$T_{\\text{eff}}$  & $[\\text{Fe/H}]$ & $\\langle\\Delta\\nu_0\\rangle$  & $\\langle\\delta\\nu_{02}\\rangle$ & $\\langle r_{02}\\rangle$    & $\\langle r_{01}\\rangle$    & $\\langle\\delta\\nu_{13}\\rangle$ &  $\\langle r_{13}\\rangle$   &  $\\langle r_{10}\\rangle$   & $\\nu_{\\max}$        \\\\ \\hline \\hline\nPC$_1$    & 0.93  & -0.20 & -0.35 & 0.92  & 0.93  & 0.38  & -0.07 & 0.95  & 0.32  & -0.07   & 0.87  \\\\\nPC$_2$    & -0.30 & 0.73  & -0.29 & -0.33 & 0.34  & 0.85  & 0.81  & 0.22  & 0.76  & 0.81    & -0.42 \\\\\nPC$_3$    & 0.00  & -0.60 & 0.63  & 0.04  & 0.06  & 0.15  & 0.45  & -0.13 & -0.17 & 0.45    & 0.22  \\\\\nPC$_4$    & 0.08  & 0.08  & -0.60 & 0.19  & -0.08 & -0.30 & 0.37  & -0.13 & -0.52 & 0.37    & 0.10  \\\\\nPC$_5$    & 0.14  & 0.25  & 0.20  & 0.06  & -0.02 & -0.05 & 0.03  & 0.00  & -0.07 & 0.03    & 0.01  \\\\\nPC$_6$    & 0.11  & -0.01 & -0.04 & 0.01  & -0.11 & 0.09  & 0.00  & -0.12 & 0.06  & 0.00    & 0.04  \\\\\nPC$_7$    & -0.09 & 0.03  & 0.01  & 0.05  & -0.03 & -0.01 & 0.00  & -0.01 & 0.03  & 0.00    & 0.09  \\\\\nPC$_8$    & 0.02  & -0.02 & 0.00  & 0.00  & -0.04 & -0.05 & 0.02  & 0.03  & 0.05  & 0.02    & -0.01 \\\\\nPC$_9$    & 0.01  & 0.01  & 0.00  & -0.04 & 0.02  & -0.02 & 0.00  & -0.02 & 0.01  & 0.00    & 0.03  \\\\\nPC$_{10}$   & 0.00  & 0.00  & 0.00  & 0.02  & 0.02  & -0.01 & 0.00  & -0.02 & 0.01  & 0.00    & -0.01 \\\\\nPC$_{11}$   & 0.00  & 0.00  & 0.00  & 0.00  & 0.00  & 0.00  & 0.01  & 0.00  & 0.00  & -0.01   & 0.00  \\\\ \\hline\n\\end{tabular}\n\\end{table}\n\n\n\n\\begin{table} %\\scriptsize\n\\centering\n\\caption{Pearson's~$r$ coefficients between the principal components and model parameters in the truncated grid.}\n\\label{tab:mcoefs}\n\\hspace*{-0.5cm}\n\\begin{tabular}{c|cccccccccccccc}\n    &$M$   & $Y$         & $Z$         & $\\alpha_{\\text{MLT}}$     & $\\alpha_{\\text{ov}}$ & $D$ & $\\tau$      & $\\tau_{\\text{MS}}$     & $X_c$      & $M_{\\text{cc}}$  & $X_{\\text{surf}}$   & $Y_{\\text{surf}}$   & $R$    & $L$                  \\\\ \\hline \\hline\nPC$_1$  & -0.67 & -0.08 & -0.30 & 0.06      & -0.05     & -0.12 & -0.19 & -0.72 & 0.77     & -0.45   & -0.04   & 0.16   & -0.86 & -0.69 \\\\\nPC$_2$  & 0.29  & 0.10  & -0.41 & -0.15     & -0.04     & -0.17 & -0.56 & -0.26 & 0.14     & 0.17    & 0.05    & 0.11   & 0.30  & 0.55  \\\\\nPC$_3$  & 0.13  & 0.04  & 0.48  & -0.10     & -0.07     & -0.03 & -0.01 & -0.04 & 0.14     & -0.11   & -0.33   & 0.17   & 0.09  & -0.04 \\\\\nPC$_4$  & -0.51 & -0.17 & -0.40 & 0.03      & -0.09     & -0.08 & 0.51  & 0.48  & -0.49    & -0.34   & 0.29    & -0.17  & -0.23 & -0.13 \\\\\nPC$_5$  & -0.02 & 0.17  & -0.09 & 0.44      & -0.16     & -0.43 & 0.13  & 0.13  & -0.17    & -0.29   & -0.50   & 0.59   & -0.14 & -0.03 \\\\\nPC$_6$  & -0.02 & -0.20 & 0.08  & -0.01     & -0.15     & -0.10 & 0.28  & 0.07  & -0.02    & -0.25   & 0.05    & -0.10  & -0.14 & -0.03 \\\\\nPC$_7$  & 0.09  & 0.05  & -0.05 & 0.14      & 0.11      & -0.15 & -0.10 & 0.03  & 0.10     & 0.30    & -0.14   & 0.17   & 0.18  & 0.38  \\\\\nPC$_8$  & -0.11 & 0.08  & -0.06 & -0.25     & 0.05      & -0.07 & 0.03  & -0.03 & -0.02    & -0.12   & -0.05   & 0.08   & -0.07 & -0.09 \\\\\nPC$_9$  & 0.21  & -0.35 & 0.22  & 0.20      & -0.06     & -0.08 & -0.22 & -0.12 & 0.15     & 0.04    & -0.01   & -0.10  & 0.06  & 0.07  \\\\\nPC$_{10}$ & -0.17 & 0.26  & -0.14 & -0.15     & 0.02      & 0.06  & 0.17  & 0.12  & -0.10    & -0.01   & 0.01    & 0.06   & -0.09 & -0.04 \\\\\nPC$_{11}$ & -0.01 & -0.01 & -0.01 & 0.01      & 0.01      & 0.00  & 0.00  & 0.00  & 0.00     & -0.02   & 0.01    & -0.01  & 0.00  & -0.01 \\\\ \\hline\n\\end{tabular} \n\\end{table}\n\\end{landscape}\n}\n\n\n\\subsection{PC correlations with different grids}\n\\label{sec:PCAg}\nIn Section~\\ref{sec:intPC}  we presented the correlation strengths between the PCs and observables (Figure~\\ref{fig:GCA-pcabar}) and the PCs and the model parameters (\\ref{fig:GCA-pcabarb}). \n Here we perform the same analysis with the different subsets of the BA1 grid described in Appendix \\ref{sec:fullPCA}. In order to compare the results for each grid, in Figures \\ref{fig:corr-pcaobs} and \\ref{fig:corr-pcamods} we employ a correlation plot rather than the quantitative bar chart used in Section~\\ref{sec:intPC}. This allows an inspection of the qualitative behaviour of the PCs in each case. We find a similar explained variance from the corresponding PCs in each grid. This suggests that the PCs capture essentially the same inherent features in model data and that the PCs are not due to the number of models in our analysis or the chosen parameter ranges.\n\n\\afterpage{\n\\clearpage\n\\begin{landscape}\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=\\linewidth]{PCAObs4.pdf}\n    \\caption[]{Pearson correlation matrices relating the principal components back to the stellar observables in each of the four grids described in Appendix \\ref{sec:fullPCA}. \\label{fig:corr-pcaobs}}\n\\end{figure}\n\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=\\linewidth]{PCAMod4.pdf}\n    \\caption[]{Pearson correlation matrices relating the principal components back to the model quantities in each of the four grids described in Appendix \\ref{sec:fullPCA}. \\label{fig:corr-pcamods}} \n\\end{figure}\n\\end{landscape}\n}\n\n\\subsection{$\\Lambda$ Analysis}\n\\label{sec:lambdaa}\n\nThe data matrix of observables $\\mathbf{X}$ is size ${n \\times p}$ where n is the number of training models and p the number of parameters.\nWe centre and scale the entries according to the mean and standard deviation of each parameter.\nThe resultant matrix,  $\\mathbf{\\bar{X}}$, therefore has the property that for each parameter, $p$, ${\\mu(p) =0}$ and ${\\sigma(p) =1}$. \nWe compute the correlation matrix, $R$, for the matrix  $\\mathbf{\\bar{X}}$ :\n\\begin{eqnarray}\n    \\mathbf{R}  &= \\text{Corr}(\\mathbf{\\bar{X}}) \\\\[3pt] \\nonumber\n                &= \\mathbf{\\bar{X}}\\mathbf{\\bar{X}^\\top}.  \n\\end{eqnarray}\nAs the correlation and covariance matrices are symmetric we calculate the eigendecomposition of R such that:\n\\begin{equation}\n\\mathbf{R}=\\mathbf{VLV^\\top},\n\\end{equation}  \nwhere \\textbf{V} a matrix of eigenvector columns and \\textbf{L} a diagonal matrix of eigenvalues.\nThe eigenvectors specify the principal axes of the data and the eigenvalues indicate the amount of variance there is in the data in the direction of the corresponding eigenvector.\nWe can define the projection matrix \\textbf{P} such that we project/transform our data into the new space    \n\\begin{equation}\n\\mathbf{P} = \\mathbf{\\bar{X}}  \\mathbf{V}.\n\\end{equation}\n\n\nThe correlation matrix is a special case of the covariance matrix in that the former is normalised.\nFor generality let us consider the covariance matrix, such that the original data matrix was centred but not scaled ($\\mathbf{\\hat{X}}$), then\n\\begin{eqnarray}\n    \\mathbf{C}  &= \\text{Cov}(\\mathbf{\\hat{X}}) \\\\[3pt] \\nonumber\n                &= \\frac{1}{n-1}\\mathbf{\\hat{X}}\\mathbf{\\hat{X}^\\top}\\\\[3pt] \\nonumber\n                &= \\mathbf{V} \\mathbf{L} \\mathbf{V^\\top},\n\\end{eqnarray}\nwhere we divide by (n-1) to unbias to covariance (the covariance entries will have different scales).\n\nAlternatively and equivalently, we may extract our PCs through SVD of  $\\mathbf{\\hat{X}}$ such that: \n\\begin{equation}\n    \\mathbf{\\hat{X}} = \\mathbf{U}  \\mathbf{\\Sigma} \\mathbf{ V^\\top}\n\\end{equation}\nwhere \\textbf{U} is the left matrix of singular orthogonal vectors with dimensions ${n \\times n}$,\n$\\mathbf{\\Sigma}$ is a diagonal matrix of singular values with dimensions $n \\times p$, \nand $\\mathbf{V^{\\top}}$ is the right matrix of singular  orthogonal vectors with diemsnions ${p \\times p}$. \nThe diagonal elements of $\\mathbf{\\Sigma}$ assign a  relative  importance  to  each  vector whereas the vectors of \\textbf{V} are the principal directions/axes.\nAs the matricies \\textbf{U} and \\textbf{V} comprise orthogonal components they have the property\n\\begin{eqnarray}\n\\label{eqn:ident}\n\\mathbf{U^{\\top}U}=\\mathbf I_{n \\times n} \\\\ \\nonumber\n\\mathbf{V^{\\top}V}=\\mathbf I_{p \\times p}.\n\\end{eqnarray}\nWe note also that \n\\begin{align}\n    \\left(\\mathbf {A \\cdot B \\cdot C }\\right)^\\top &= \\mathbf{C^\\top \\cdot B^\\top \\cdot A^\\top} \\\\\n    \\implies  (\\mathbf U\\mathbf \\Sigma\\mathbf V^\\top)^\\top &= (\\mathbf V\\mathbf \\Sigma\\mathbf U^\\top)\n\\end{align}\nas $\\mathbf{\\Sigma}$ is a diagonal matrix.\n\n\nWe can reconstruct the eigendecomposition of the covariance matrix from the SVD: \n\\begin{eqnarray}\n \\frac{1}{n-1}\\mathbf{\\hat{X}}\\mathbf{\\hat{X}}^\\top &= \\frac{1}{n-1} (\\mathbf U\\mathbf \\Sigma\\mathbf V^\\top)(\\mathbf U\\mathbf \\Sigma\\mathbf V^\\top)^\\top\\\\[3pt] \\nonumber\n&= \\frac{1}{n-1}(\\mathbf U\\mathbf \\Sigma\\mathbf V^\\top)(\\mathbf V\\mathbf \\Sigma\\mathbf U^\\top)\n\\end{eqnarray}\nand from our identities in Equation~(\\ref{eqn:ident})\n\\begin{equation}\n \\frac{1}{n-1}\\mathbf{\\hat{X}}\\mathbf{\\hat{X}}^\\top=\\mathbf U \\frac{\\mathbf \\Sigma^2}{n-1} \\mathbf U^\\top.\n\\end{equation}\nWe therefore find that the square roots of the eigenvalues of $\\mathbf{C}$ are the singular values of  $\\mathbf{\\bar{X}}$ and that the vectors in the right singular matrix, \\textbf{V}, are the principal directions/axes. The projection matrix can be calculated from the SVD such that \n\\begin{align}\n\\mathbf{P} &= \\mathbf{\\hat{X}}  \\mathbf{V} \\\\[3pt] \\nonumber\n           &= \\mathbf U \\mathbf \\Sigma \\mathbf V^\\top \\mathbf{V}  \\\\[3pt] \\nonumber\n           &= \\mathbf U \\mathbf \\Sigma.\n\\end{align}\n\nThe PCA loadings are the columns of \\textbf{L} which implies that \n\\begin{equation}\n\\mathbf{L}=\\mathbf{V}\\frac{\\mathbf \\Sigma}{\\sqrt{n-1}}.\n\\end{equation}\nWe can see that the loadings are the eigenvectors scaled by the square roots of the respective eigenvalues.\nWith these definitions we can compute the cross-covariance matrix between original variables and the standardized projection matrix. \nTo calculate the standardized PC scores for \\textbf{P} we require each column of \\textbf{U} to have unit variance. As $\\mathbf{\\Sigma}$ is diagonal it is simply a scaling matrix and can be dropped here yielding: \n\\begin{align}\n\\frac{1}{n-1}\\mathbf{X}^\\top(\\sqrt{n-1}\\mathbf{U}) &=\\frac{1}{\\sqrt{n-1}}\\mathbf{V}\\mathbf{\\Sigma}\\mathbf{U}^\\top\\mathbf{U} \\\\&=\\frac{1}{\\sqrt{n-1}}\\mathbf{V}\\mathbf{\\Sigma}\n\\\\&=\\mathbf{L}.\n\\end{align}\nWe find that the covariance matrix between the standardized PCs and original variables is in fact given by the loadings. \nIn  Section~\\ref{sec:ev} we computed the \\emph{correlations} between the observables and their PCs rather than the covariances, requiring that the observables are normalized by their standard deviation. As we centred and scaled our data prior to performing the PCA, their values are unity and our correlation analysis is therefore equivalent to reporting the loadings. \n\nThe correlation analysis allowed us to project the model data onto the PC space and determine the `equivalent' loadings for each parameter. Through the $\\lambda$ score we can therefore determine to what extent the variance in the model data is captured by the PCs.  In Table~\\ref{tab:corrLFull} we compare the results of the analysis for each grid. We find similar results for most parameters \nwith differences in some of the initial model parameters due to their underlying distributions as a result of the grid truncations.\n\n\n\n\n\\subsection{Impact of Uncertainties for Upcoming Photometric Space Missions} \nBelow we demonstrate the impact of measurement uncertainty on the prediction of parameters from the upcoming TESS (Figure~\\ref{fig:uncerttess}) and PLATO (Figure~\\ref{fig:uncertplato}) space missions.  We produce  probability density distributions for $250$ sets of $\\sigma$ values for each parameter we predict. The ranges for each parameter from which we draw our $\\sigma$ values are listed in Table~\\ref{tab:sunstar}. We restrict out observables to those we are likely to possess from the respective missions. \nIn each figure we plot the median value (solid line) and the  $68\\%$  confidence interval (shaded region).\n\n\\afterpage{\n\\begin{table}\n    \\centering\n    \\caption{The $\\Lambda$ score is a sum of the squares of  ${r(X, PC_i)}$ indicating the variance explained for a given parameter. These scores are by definition unity for our observables.}\n    \\label{tab:corrLFull}\n    \\begin{tabular}{ccccc}\n    \\hline \\hline\n    & \\multicolumn{4}{c}{$\\Lambda_{\\text{param}}$} \\\\\nParameter & Grid A & Grid B & Grid C & Grid D \\\\ \\hline     \nR\t&\t0.97\t&\t0.97\t&\t0.98\t&\t0.97\t\\\\\nL\t&\t0.93\t&\t0.96\t&\t0.93\t&\t0.95\t\\\\\n$X_c$\t&\t0.93\t&\t0.94\t&\t0.93\t&\t0.94\t\\\\\n$\\tau_{\\text{MS}}$\t&\t0.93\t&\t0.93\t&\t0.93\t&\t0.94\t\\\\\nM\t&\t0.91\t&\t0.91\t&\t0.92\t&\t0.88\t\\\\\n$\\tau$\t&\t0.74\t&\t0.79\t&\t0.78\t&\t0.76\t\\\\\n$Z_0$\t&\t0.76\t&\t0.73\t&\t0.78\t&\t0.80\t\\\\\nM$_{cc}$\t&\t0.58\t&\t0.61\t&\t0.68\t&\t0.41\t\\\\\n$Y_{\\text{surf}}$\t&\t0.48\t&\t0.50\t&\t0.55\t&\t0.54\t\\\\\nX$_{\\text{surf}}$\t&\t0.50\t&\t0.48\t&\t0.53\t&\t0.55\t\\\\\n$\\alpha_{\\text{MLT}}$\t&\t0.02\t&\t0.38\t&\t0.04\t&\t0.06\t\\\\\n$Y_0$\t&\t0.10\t&\t0.31\t&\t0.27\t&\t0.09\t\\\\\nD\t&\t0.13\t&\t0.29\t&\t0.22\t&\t0.21\t\\\\\n$\\alpha_{\\text{ov}}$\t&\t0.10\t&\t0.08\t&\t0.11\t&\t0.12\t\\\\\n\n \\hline\n    \\end{tabular}\n\\end{table}\n\n \\begin{table}\n    \\centering\n    \\caption{Central solar values and uncertainty ranges used for predictions in Figures \\ref{fig:uncerttess} and \\ref{fig:uncertplato}.}\n    \\begin{tabular}{lcccccc}\n    \\hline \\hline\n \\multicolumn{1}{c}{} & \\multicolumn{3}{c}{TESS}& \\multicolumn{3}{c}{PLATO}  \\\\\nQuantity & Value & Min($\\sigma$) & Max($\\sigma$) & Value & Min($\\sigma$) & Max($\\sigma$)\\\\ \\hline \n$T_{\\text{eff}}$ (K)  & 5777 & 10  & 500& 5777 & 10  & 500\\\\\n$\\log{} g$ &  4.44 & 0.0001 & 1.0&  4.44 & 0.0001 & 1.0\\\\\n$[\\text{Fe/H}]$ & 0.0 & 0.05 & 0.5 & 0.0 & 0.05 & 0.5\\\\\n$L$ & 1.0 & 0.001 & 10 & 1.0 & 0.001 & 10 \\\\\n$\\nu_{\\max}$ & 3050 & 10 & 500 & -- & -- & --\\\\\n$\\langle\\Delta\\nu_0\\rangle$ ($\\mu$Hz) & -- & -- & --& 136.0 & 0.5 & 50\\\\\n$\\langle\\delta\\nu_{02}\\rangle$ ($\\mu$Hz)& -- & -- & -- & 9.0 & 0.5 & 5 \\\\\n\\hline\n    \\end{tabular}\n    \\label{tab:sunstar}\n\\end{table}\n}\n\n\\clearpage\n\n\\label{sec:PSM}\n\n\n\n\n\n\\afterpage{\n%\\clearpage\n%\\cleartoleftpage%\\cleardoublepage\n    %\\clearpage% flush all other floats\n    %\\ifodd\\value{page}\n    %\\else% uncomment this else to get odd/even instead of even/odd\n    %    \\expandafter\\afterpage% put it on the next page if this one is odd\n    %\\fi\n\\begin{landscape}\n%\\pagestyle{lscape}\n\\begin{figure}\\vspace*{-0.75cm}\n    \\centering\n    \\includegraphics[width=0.9\\linewidth,keepaspectratio]{tess2.pdf}\n    \\caption[]{(Caption on other page.)\\label{fig:uncerttess}}\n\\end{figure}\n\\end{landscape}\n\n\\begin{figure}\n  \\contcaption{Predictions for the solar mass, age, luminosity and radius as a function of the uncertainties applied to key observables. In each panel we have perturbed the quantity on the abscissa in isolation, centred around the measured value listed in  Table~\\ref{tab:sunstar} and with the uncertainties in the ranges specified therein. We indicate the median predicted value (solid line) and the  $68\\%$  confidence interval (shaded region). Here the observables comprise those expected from the TESS space mission assuming that the p-mode power excess can be extracted.} \n\\end{figure}\n%\\end{landscape}\n%}\n\n\n\n\n%\\afterpage{\n\n\\afterpage{\n%\\clearpage\n%\\cleartoleftpage%\\cleardoublepage\n    %\\clearpage% flush all other floats\n    %\\ifodd\\value{page}\n    %\\else% uncomment this else to get odd/even instead of even/odd\n    %    \\expandafter\\afterpage% put it on the next page if this one is odd\n    %\\fi\n\\begin{landscape}\n%\\cleartoleftpage%\\cleardoublepage\n%\\begin{landscape}\n%\\pagestyle{lscape}\n\\begin{figure}\\vspace*{-0.75cm}\n    \\centering\n    \\includegraphics[width=0.9\\linewidth,keepaspectratio]{plato2.pdf}\n    \\caption[]{The same as Figure~\\ref{fig:uncerttess}, but for PLATO. \\label{fig:uncertplato}} %(Caption on other page.) \\label{fig:uncertplato}}\n\\end{figure}\n\\end{landscape}\n}\n%\\begin{figure}\n  %\\contcaption{}{Predictions for the solar mass, age, luminosity and radius as a function of the uncertainties applied to key observables. In each panel we have perturbed the quantity on the abscissa in isolation, centred around the measured value listed in  Table~\\ref{tab:sunstar} and with the uncertainties in the ranges specified therein. We indicate the median predicted value (solid line) and the  $68\\%$  confidence interval (shaded region). Here the observables comprise those expected from the PLATO space mission.} \n%\\end{figure}\n}\n\\clearpage\n\n\n\n\n\n\\iffalse\n\\begin{figure*}\n    \\centering\n    \\includegraphics[width=0.95\\textheight,height=0.95\\textwidth,keepaspectratio, angle=90]{tess2.pdf}\n    \\caption{Predictions for the solar mass, age, luminosity and radius as a function of the uncertainties applied to key observables. In each panel we have perturbed the quantity on the abscissa in isolation, centred around the measured value listed in  Table~\\ref{tab:sunstar} and with the uncertainties in the ranges specified therein. We indicate the median predicted value (solid line) and the  $68\\%$  confidence interval (shaded region). Here the observables comprise those expected from the TESS space mission assuming that the p-mode power excess can be extracted.} \n    \\label{fig:uncerttess}\n\\end{figure*}\n\n\\begin{figure*}\n    \\centering\n    \\includegraphics[width=0.95\\textheight,height=0.95\\textwidth,keepaspectratio, angle=90]{plato2.pdf}\n    \\caption{Predictions for the solar mass, age, luminosity and radius as a function of the uncertainties applied to key observables. In each panel we have perturbed the quantity on the abscissa in isolation, centred around the measured value listed in  Table~\\ref{tab:sunstar} and with the uncertainties in the ranges specified therein. We indicate the median predicted value (solid line) and the  $68\\%$  confidence interval (shaded region). Here the observables comprise those expected from the PLATO space mission.} \n    \\label{fig:uncertplato}\n\\end{figure*}\n\\fi\n\n%\\listofchanges\n%\\end{document}\n\n\n", "meta": {"hexsha": "845e9033da5830f718c17a5b11b3bbaaa5fb81ef", "size": 166086, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/ch3_stats/statistical_relations.tex", "max_stars_repo_name": "earlbellinger/Ph.D.-Thesis", "max_stars_repo_head_hexsha": "101c3f822b505c9e62beeb41ca30fe46c279ad79", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tex/ch3_stats/statistical_relations.tex", "max_issues_repo_name": "earlbellinger/Ph.D.-Thesis", "max_issues_repo_head_hexsha": "101c3f822b505c9e62beeb41ca30fe46c279ad79", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/ch3_stats/statistical_relations.tex", "max_forks_repo_name": "earlbellinger/Ph.D.-Thesis", "max_forks_repo_head_hexsha": "101c3f822b505c9e62beeb41ca30fe46c279ad79", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 86.8650627615, "max_line_length": 1284, "alphanum_fraction": 0.7299531568, "num_tokens": 45787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.34278523380354553}}
{"text": "\\title{Tendon Robot Statics Model Variants}\n\\author{John Till}\n\\date{}\n\n\\documentclass[12pt]{article}\n\n\\usepackage[a4paper, margin=0.75in]{geometry}\n\\usepackage[colorlinks=true,urlcolor=blue]{hyperref}\n\\usepackage{amsmath,amssymb}\n\\usepackage{graphicx}\n\n\\usepackage{xcolor}\n\\definecolor{OffWhite}{rgb}{0.93,0.93,0.93}\n\\definecolor{QtCommentColor}{rgb}{0,0.5,0}\n\\definecolor{QtKeywordColor}{rgb}{0.5,0.5,0}\n\\definecolor{QtPurpleColor}{rgb}{0.5,0,0.5}\n\\definecolor{QtGlobal}{rgb}{0.808,0.361,0}\n\\definecolor{QtFunctionColor}{rgb}{0,0.404,0.486}\n\n\\usepackage[T1]{fontenc} %for upquotes in listings\n\\usepackage{textcomp} %for upquotes in listings\n\\usepackage{listings}\n\\lstset{\n\t\tlanguage=C++,\n\t\tescapeinside={!-}{-!},\n\t\tupquote=true,\n\t\t%\n\t\totherkeywords={Vector3d, DiagonalMatrix, VectorXd, Matrix3d, Map, MatrixXd, Vector6d, Vector4d,\n\t\t              Matrix6d, Eigen, Upper, std, fstream, Matrix3Xd,\n\t\t\t\t\t\t\t\t\tUnitX, pow, inverse, transposeMultiply, segment, data, UnitZ, cross, hat_squared,\n\t\t\t\t\t\t\t\t\that_postmultiply, hat_premultiply, normalized,\n\t\t\t\t\t\t\t\t\tZero, Identity, UnitY, cosseratRodOde, ode4, cols, row, main, shootingFunction,\n\t\t\t\t\t\t\t\t\tblock, rotation_error, solveLevenbergMarquardt, cos, sin, toDenseMatrix,\n\t\t\t\t\t\t\t\t\tselfadjointView, llt, close, kirchhoffTendonRobotOde, cwiseProduct, cwiseMin,\n\t\t\t\t\t\t\t\t\tcwiseMax, getRouting},\n    morekeywords=[2]{Vector3d, DiagonalMatrix, VectorXd, Matrix3d, Map, MatrixXd, Vector6d, Vector4d,\n\t\t                 Matrix6d, Eigen, Upper, std, fstream, Matrix3Xd},\n\t\tmorekeywords=[3]{UnitX, UnitZ, pow, inverse, transposeMultiply, segment, data, cross, hat_squared,\n\t\t                 hat_postmultiply, hat_premultiply, normalized,\n\t\t                 Zero, Identity, UnitY, cosseratRodOde, ode4, cols, row, main, shootingFunction,\n\t\t\t\t\t\t\t\t\t\t block, rotation_error, solveLevenbergMarquardt, cos, sin, toDenseMatrix,\n\t\t\t\t\t\t\t\t\t\t selfadjointView, llt, close, kirchhoffTendonRobotOde, cwiseProduct, cwiseMin,\n\t\t\t\t\t\t\t\t\t\t cwiseMax, getRouting},\n    %\n\t\tframe = single,\n\t\trulecolor=\\color{black},\n    tabsize=4, % tab space width\n    showstringspaces=false, % don't mark spaces in strings\n\t\t%\n\t\tbasicstyle=\\footnotesize,%\\color{QtIdentifier},\n\t\tbackgroundcolor=\\color{OffWhite},\n    commentstyle=\\color{QtCommentColor}, % comment color\n    keywordstyle=\\color{QtKeywordColor}, % keyword color\n\t\tkeywordstyle=[2]{\\color{QtPurpleColor}},\n\t\tkeywordstyle=[3]{\\color{QtFunctionColor}},\n    stringstyle=\\color{QtCommentColor} % string color\n}\n\n\\begin{document}\n\n\\makeatletter\n\\renewcommand{\\@maketitle}{\n\\newpage\n\\null\n\\vskip 2em\n\\begin{center}\n{\\LARGE \\@title \\par}\n\\end{center}\n\\par\n} \\makeatother\n\n\\maketitle\n\nIn the last example we implemented a relatively simple tendon robot model where the backbone was modeled as a Cosserat rod and the tendons were routed in parallel with the backbone. There is a plethora of potential modifications to the model, and three potential variations are considered in different sections here.\n\n\\section{Kirchhoff Rod Backbone}\n\nThere are significant simplifications to the model if we neglect the shear and extension modes as described in \\href{https://ieeexplore.ieee.org/document/5957337}{``Statics and Dynamics of Continuum Robots With General Tendon Routing and External Loading''}. This results in $\\boldsymbol{v} = \\boldsymbol{e}_3$, which is the elastic rod problem as studied by Gustav Kirchhoff prior to the Cosserat brothers. The result for the tendon robot is that one only needs to solve a 3x3 linear system for $\\dot{\\boldsymbol{u}}$ instead of the 6x6 linear system considered previously for $\\dot{\\boldsymbol{v}}$ and $\\dot{\\boldsymbol{u}}$.\n\nThe state vector has $\\boldsymbol{n}^b$ instead of $\\boldsymbol{v}$, and the ODE function is changed accordingly:\n\\begin{lstlisting}\nvoid kirchhoffTendonRobotOde(VectorXd& y_s_out, VectorXd& y){\n    //Unpack state vector\n    Matrix3d R = Map<Matrix3d>(&y[3]);\n    Vector3d nb = Map<Vector3d>(&y[12]);\n    Vector3d u = Map<Vector3d>(&y[15]);\n\\end{lstlisting}\nOf course calculations involving shear or extension are modified so that $\\boldsymbol{v} = \\boldsymbol{e}_3$. The ODEs are also changed so that there is only a 3x3 linear system as in Equation (17):\n\\begin{lstlisting}\n    //Pack state vector derivative\n    Map<Vector3d> p_s(&y_s_out[0]);\n    Map<Matrix3d> R_s(&y_s_out[3]);\n    Map<Vector3d> nb_s(&y_s_out[12]);\n    Map<Vector3d> u_s(&y_s_out[15]);\n\n    //ODEs\n    p_s = R.col(2);\n    R_s = hat_postmultiply(R,u);\n    u_s = H.inverse()*(-u.cross(Kbt*u) - Vector3d::UnitZ().cross(nb) - b);\n    nb_s = -u.cross(nb) - G*u_s - a - transposeMultiply(R,rho*area*g);\n}\n\\end{lstlisting}\nAn inverse is used instead of a linear solver because Eigen has specialized methods to take efficient inverses of small fixed-size matrices.\nWe also make some minor changes to the objective function since $\\boldsymbol{n}^b$ is a state variable instead of $\\boldsymbol{v}$:\n\\begin{lstlisting}\ny0 << p0, Map<VectorXd>(Matrix3d(R0).data(), 9), guess;\n\n//Numerically integrate the Cosserat rod equations\nY = ode4<kirchhoffTendonRobotOde>(y0, L);\n\n//Find the internal forces in the backbone prior to the final plate\nVector3d nb = Y.block<3,1>(12,Y.cols()-1);\nVector3d uL = Y.block<3,1>(15,Y.cols()-1);\nVector3d mb = Kbt*uL;\n\\end{lstlisting}\nIf we rendered the solution, we would see no visible difference compared the Cosserat model.\n\n\\section{Non-parallel Tendon Routing}\n\nThe examples so far have assumed the tendons are routed parallel with the backbone. However, the model in\n\\href{https://ieeexplore.ieee.org/document/5957337}{``Statics and Dynamics of Continuum Robots With General Tendon Routing and External Loading''} is formulated for any general routing path, and helical routing strategies are demonstrated. The Cosserat backbone model is altered to have a helical routing strategy here.\n\nThere are a multitude of options for how to represent the tendon routing functions. Lambda functions might be the most straightforward way, and if we were willing to implement our own numerical integration function, the most efficient way would be to precompute all the values at grid points. The approach here is somewhere in between; we'll calculate all the vectors at a given point on the backbone:\n\\begin{lstlisting}\n//Helical routing\nconst double offset = 0.01506;\nvoid getRouting(double arclength, Vector3d* r, Vector3d* r_s, Vector3d* r_ss){\n    const double f = 2*pi/L; //tendons make a full revolution\n\n    double c = offset*cos(f*arclength);\n    double s = offset*sin(f*arclength);\n    double fc = f*c;\n    double fs = f*s;\n    double ffc = f*fc;\n    double ffs = f*fs;\n\n    r[0] = Vector3d(c, s, 0);\n    r[1] = Vector3d(-s, c, 0);\n    r[2] = Vector3d(-c, -s, 0);\n    r[3] = Vector3d(s, -c, 0);\n\n    r_s[0] = Vector3d(-fs, fc, 0);\n    r_s[1] = Vector3d(-fc, -fs, 0);\n    r_s[2] = Vector3d(fs, -fc, 0);\n    r_s[3] = Vector3d(fc, fs, 0);\n\n    r_ss[0] = Vector3d(-ffc, -ffs, 0);\n    r_ss[1] = Vector3d(ffs, -ffc, 0);\n    r_ss[2] = Vector3d(ffc, ffs, 0);\n    r_ss[3] = Vector3d(-ffs, ffc, 0);\n}\n\\end{lstlisting}\nThe tendons are still separated by $90^\\circ$, but they are routed in helices around the backbone with a frequency ``f''. There are three arrays passed in having four vectors each. ``r'', ``r\\_s'', and ``r\\_ss'' are set based on the arc length. The ODE includes the derivatives of $\\boldsymbol{r}$:\n\\begin{lstlisting}\nVector3d r[num_tendons], r_s[num_tendons], r_ss[num_tendons];\ngetRouting(s, r, r_s, r_ss);\n\nfor(int i = 0; i < num_tendons; i++){\n    Vector3d ri = r[i];\n    Vector3d ri_s = r_s[i];\n    Vector3d ri_ss = r_ss[i];\n\n    Vector3d pb_si = u.cross(ri) + ri_s + v;\n    double pb_s_norm = pb_si.!-\\textcolor{QtFunctionColor}{norm}-!();\n    Matrix3d A_i = -hat_squared(pb_si)*(tau(i)/pow(pb_s_norm,3));\n    Matrix3d G_i = -hat_postmultiply(A_i,ri);\n    Vector3d a_i = A_i*(u.cross(pb_si + ri_s) + ri_ss);\n\\end{lstlisting}\nThe tendon routing vectors are calculated for the current arclength ``s'' before setting up the linear system. Over in the objective function, we also need to use the tendon routing vectors at the tip when finding the equilibrium error:\n\\begin{lstlisting}\n//Find the equilibrium error at the tip, considering tendon forces\nVector3d force_error = -nb;\nVector3d moment_error = -mb;\nVector3d r[num_tendons], r_s[num_tendons], r_ss[num_tendons];\ngetRouting(L, r, r_s, r_ss);\nfor(int i = 0; i < num_tendons; i++){\n    Vector3d pb_si = uL.cross(r[i]) + r_s[i] + vL;\n    Vector3d Fb_i = -tau(i)*pb_si.normalized();\n    force_error += Fb_i;\n    moment_error += r[i].cross(Fb_i);\n}\n\\end{lstlisting}\nThen we can solve the problem and visualize the effects of helical routing:\n\\begin{figure}[h]\n\t\\centering\n\t\t\\includegraphics[width=0.8\\textwidth]{fig/Helical.jpg}\n\\end{figure}\n\nWe could also implement a converging tendon strategy like in the paper \\href{https://ieeexplore.ieee.org/document/8606257}{``Continuum Robot Stiffness Under External Loads and Prescribed Tendon Displacements''}. We revise the tendon function:\n\\begin{lstlisting}\n//Converging routing\nconst double offset = 0.01506;\nconst double routing_slope = -offset/L;\nvoid getRouting(double s, Vector3d* r, Vector3d* r_s, Vector3d* r_ss){\n    double b = (1 - s/L)*offset;\n\n    r[0] = Vector3d(b, 0, 0);\n    r[1] = Vector3d(0, b, 0);\n    r[2] = Vector3d(-b, 0, 0);\n    r[3] = Vector3d(0, -b, 0);\n\n    r_s[0] = Vector3d(routing_slope, 0, 0);\n    r_s[1] = Vector3d(0, routing_slope, 0);\n    r_s[2] = Vector3d(-routing_slope, 0, 0);\n    r_s[3] = Vector3d(0, -routing_slope, 0);\n\n    r_ss[0] = r_ss[1] = r_ss[2] = r_ss[3] = Vector3d(0, 0, 0);\n}\n\\end{lstlisting}\nThen solving with converging routing yields the following solution:\n\\begin{figure}[h]\n\t\\centering\n\t\t\\includegraphics[width=0.8\\textwidth]{fig/Converging.jpg}\n\\end{figure}\n\n\\section{Tendon Displacement Control}\n\nIn the examples so far, the forward kinematics input has been the tendon tensions. However, most actuator control position instead of force. This scenario is also considered in the paper \\href{https://ieeexplore.ieee.org/document/8606257}{``Continuum Robot Stiffness Under External Loads and Prescribed Tendon Displacements''}. There are additional unknowns since the tendon tensions are not given, and additional constraints since the backbone must take a shape so that the tendon lengths are correct. For example, increasing the distance $q_i$ the tendon extends below the baseplate will cause the backbone to bend so that the arc length of the tendon above the baseplate is reduced, and the total tendon length remains constant (assuming an inextensible tendon).\n\n\\begin{figure}[h]\n\t\\centering\n\t\t\\includegraphics[width=0.5\\textwidth]{fig/DisplacementControl.jpg}\n\\end{figure}\n\nWe declare additional independent parameters for the displacement control:\n\\begin{lstlisting}\nconst VectorXd q = Vector4d(5e-3, 0, -5e-3, 0);\nconst VectorXd l_star = Vector4d(L,L,L,L);\n\\end{lstlisting}\nThe length a tendon extends behind the baseplate is $q_i$, and the total length of a tendon before stretching is $l_i^*$. We're careful when setting the actuator displacements because it is especially easy to have an \\emph{ill-posed} problem. For instance, pulling all the tendons back by half the length of the backbone is simply not realistic, and the solver would probably fail to find a solution.\nThe tendon tensions are now dependent variables, so they are declared as static:\n\\begin{lstlisting}\nstatic VectorXd tau;\n\\end{lstlisting}\nThese tensions will be guessed, so we change the guess initialization in the main function:\n\\begin{lstlisting}\nVectorXd init_guess = VectorXd::Zero(6 + num_tendons); //nb, u, and tau\n\\end{lstlisting}\nand we unpack the last elements of the guess as the tendon tensions:\n\\begin{lstlisting}\ntau = guess.segment<num_tendons>(6);\n\\end{lstlisting}\nBased on how the backbone deforms, each tendon will have some arc length it is routed along the backbone, with errors resulting from incorrect lengths. Calculating the errors requires modifying the ODE function to also integrate the tendon arc lengths. We extend the state vector so that the last entries are the tendon arc lengths: \n\\begin{lstlisting}\nMap<VectorXd> pb_s_norm(&y_s_out[18], num_tendons);\n\\end{lstlisting}\nNow the change in tendon arc length with respect to the change in reference arc length is stored as part of the state vector derivative:\n\\begin{lstlisting}\npb_s_norm(i) = pb_si.!-\\textcolor{QtFunctionColor}{norm}-!();\nMatrix3d A_i = -hat_squared(pb_si)*(tau(i)/pow(pb_s_norm(i),3));\n\\end{lstlisting}\nWe modify the initial conditions to include the arc lengths of the tendons behind the base plate:\n\\begin{lstlisting}\nVectorXd y0(18+num_tendons);\ny0 << p0, Map<VectorXd>(Matrix3d(R0).data(),9), v0, u0, q;\n\\end{lstlisting}\nThen we have some error in the integrated lengths of the tendons versus the known lengths specified as design parameters:\n\\begin{lstlisting}\n//Find the length violation error\nVectorXd integrated_lengths = Y.block<num_tendons,1>(18,Y.cols()-1);\nVectorXd length_error = integrated_lengths - l_star;\n\nVectorXd distal_error(6 + num_tendons);\ndistal_error << force_error, moment_error, length_error;\n\\end{lstlisting}\n\nNow if we run the program, the robot is solved using tendon displacement as the forward kinematics input. However, our approach currently assumes the tendons are inextensible and capable of supporting compression. We address the former first by adding compliance as an independent variable:\n\\begin{lstlisting}\nconst VectorXd C = Vector4d(1e-4,1e-4,1e-4,1e-4);\n\\end{lstlisting}\nThen the length error is revised to include the tendon stretch, which is calculated from Hooke's law:\n\\begin{lstlisting}\nVectorXd stretch = l_star.cwiseProduct( C.cwiseProduct(tau) );\nVectorXd length_error = integrated_lengths - (l_star + stretch);\n\\end{lstlisting}\nNow the tendons will stretch under tension. Unfortunately, they will also contract under compression. \nTo disallow compression, we include the effects of slack. Since slack and tension are mutually exclusive effects, we use a single variable to represent them both when we unpack the guess:\n\\begin{lstlisting}\ntau = guess.segment<num_tendons>(6).cwiseMax(0);\nVectorXd slack = -(guess.segment<num_tendons>(6).cwiseMin(0));\n\\end{lstlisting}\nDepending on the sign, we have either tension or slack. Hopefully the shooting method optimization space is smooth around the transition; it seems to work well. Then the length error is revised to include slack:\n\\begin{lstlisting}\nVectorXd length_error = integrated_lengths + slack - (l_star + stretch);\n\\end{lstlisting}\nNow we have a model with displacement controlled tendons which stretch under tension and go slack when necessary.\n\n\\end{document}", "meta": {"hexsha": "2ada42bb8a1adb928a3d620df736d0e694c4e618", "size": 14628, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "01_Statics/06_Tendon_Robot_Variants/LaTeX/TendonRobotVariants.tex", "max_stars_repo_name": "matthiastummers/ContinuumRobotExamples", "max_stars_repo_head_hexsha": "2575fa71075c8867f7be78c112695de2f9b6c403", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 73, "max_stars_repo_stars_event_min_datetime": "2019-03-21T04:59:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T18:44:50.000Z", "max_issues_repo_path": "01_Statics/06_Tendon_Robot_Variants/LaTeX/TendonRobotVariants.tex", "max_issues_repo_name": "matthiastummers/ContinuumRobotExamples", "max_issues_repo_head_hexsha": "2575fa71075c8867f7be78c112695de2f9b6c403", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2019-04-23T18:22:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T07:05:29.000Z", "max_forks_repo_path": "01_Statics/06_Tendon_Robot_Variants/LaTeX/TendonRobotVariants.tex", "max_forks_repo_name": "matthiastummers/ContinuumRobotExamples", "max_forks_repo_head_hexsha": "2575fa71075c8867f7be78c112695de2f9b6c403", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28, "max_forks_repo_forks_event_min_datetime": "2019-04-02T04:01:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T06:59:02.000Z", "avg_line_length": 50.7916666667, "max_line_length": 765, "alphanum_fraction": 0.7407027618, "num_tokens": 4166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3427852275917898}}
{"text": "\\documentclass[p.tex]{subfiles}\n\\begin{document}\n\\section{Background}\\label{sec:background}\n\n\\subsection{Target Language}\\label{sec:language}\n\n\\begin{figure}\n\\begin{spreadlines}{5pt}\n\\begin{gather*}\n  \\inference[\\textsc{E-Assert}]{%\n    \\eeval{b}{\\sigma}{\\btrue}\n  }{%\n    \\ceval{\\cassert{b}}{\\sigma}{\\sigma}\n  }\n  \\qquad\n  \\inference[\\textsc{E-SumLeft}]{%\n    \\ceval{c_0}{\\sigma_0}{\\sigma_1}\n  }{%\n    \\ceval{\\csum{c_0}{c_1}}{\\sigma_0}{\\sigma_1}\n  }\n  \\qquad\n  \\inference[\\textsc{E-SumRight}]{%\n    \\ceval{c_1}{\\sigma_0}{\\sigma_1}\n  }{%\n    \\ceval{\\csum{c_0}{c_1}}{\\sigma_0}{\\sigma_1}\n  }\n  \\\\\n  \\inference[\\textsc{E-Assign}]{%\n  }{%\n    \\ceval{\\cassign{x}{a}}{\\sigma}{\\subst{x}{a}{(\\sigma)}}\n  }\n  \\qquad\n  \\inference[\\textsc{E-Sequence}]{%\n    \\ceval{c_0}{\\sigma_0}{\\sigma_1}&\n    \\ceval{c_1}{\\sigma_1}{\\sigma_2}&\n  }{%\n    \\ceval{\\cseq{c_0}{c_1}}{\\sigma_0}{\\sigma_2}\n  }\n  \\\\\n  \\inference[\\textsc{E-Skip}]{%\n  }{%\n    \\ceval{\\cskip}{\\sigma}{\\sigma}\n  }\n  \\qquad\n  \\inference[\\textsc{E-Loop}]{%\n    \\ceval{c}{\\sigma_0}{\\sigma_1}&\n    \\ceval{\\cloop{c}}{\\sigma_1}{\\sigma_2}\n  }{%\n    \\ceval{\\cloop{c}}{\\sigma_0}{\\sigma_2}\n  }\n  \\qquad\n  \\inference[\\textsc{E-Break}]{%\n  }{%\n    \\ceval{\\cloop{c}}{\\sigma}{\\sigma}\n  }\n\\end{gather*}\n\\end{spreadlines}\n  \\caption{%\n    The formal semantics of the target language $\\lang$, defined in\n    terms of the constituent imperative commands in \\com.\n    Metavariables $\\sigma, \\sigma_0, \\ldots$ denote program states in\n    \\state, metavariable $x$ denotes a variable in \\var, metavariables\n    $c, c_0, \\ldots$ denote commands in \\com, $a$ denotes an\n    integer-valued expression in $\\aexpr$, and $b$ denotes a\n    boolean-valued expression in $\\bexpr$.\n  }\\label{fig:semantics}\n\\end{figure}\n\nIn this section we present the imperative language, $\\lang$, that we will extend\nand analyze for the remainder of this paper.\n$\\lang$ includes\nassignments, branches, loops, and assertions.\n%\n$\\lang$ makes use of expressions with boolean and integer\nvalue, denoted $\\bexpr$ and $\\aexpr$ respectively.\n%\nWe denote the space of program variables as \\var.\n%\nEach program in $\\lang$ is an imperative command.\nWe define the space of imperative commands inductively:\n\\begin{align*}\n  \\com ::=&~\\cskip\\\\\n         |&~\\cassign{\\var}{\\aexpr}\\\\\n         |&~\\cassert{\\bexpr}\\\\\n         |&~\\cseq{\\com}{\\com}\\\\\n         |&~\\csum{\\com}{\\com}\\\\\n         |&~\\cloop{\\com}\n\\end{align*}\n\nThe command $\\cseq{c_0}{c_1}$ is the command which first executes\n$c_0$ and then executes $c_1$ and the command $\\cskip$ is a no-op. The\ncommand $\\cassert{b}$ is a static claim that the boolean expression\n$b$ evaluates to true in every possible run of the command. We define\nthe formal semantics of the space of commands in \\cref{fig:semantics}.\n%\nThe program semantics are defined with reference to members of the\nspace of program states, which we denote $\\state$. A state\nis a map from a variables to integer values:\n%\n\\[\\state ::= \\var \\rightarrow \\mathbb{Z}\\]\n\n\\subsection{Hoare Logic}\n\\begin{figure}\n\\begin{spreadlines}{5pt}\n\\begin{gather*}\n  \\inference[\\textsc{Skip}]{%\n  }{%\n    \\hoare{P}{\\cskip}{P}\n  }\n  \\qquad\n  \\inference[\\textsc{Assign}]{%\n  }{%\n    \\hoare{\\subst{x}{a}{P}}{\\cassign{x}{a}}{P}\n  }\n  \\qquad\n  \\inference[\\textsc{Assert}]{%\n  }{%\n    \\hoare{P}{\\cassert{b}}{P \\land b}\n  }\n  \\\\\n  \\inference[\\textsc{Seq}]{%\n    \\hoare{P}{c_0}{R}&\n    \\hoare{R}{c_1}{Q}\n  }{%\n    \\hoare{P}{\\cseq{c_0}{c_1}}{Q}\n  }\n  \\qquad\n  \\inference[\\textsc{Sum}]{%\n    \\hoare{P}{c_0}{Q}&\n    \\hoare{P}{c_1}{Q}\n  }{%\n    \\hoare{P}{\\csum{c_0}{c_1}}{Q}\n  }\n  \\\\\n  \\inference[\\textsc{Loop}]{%\n    \\hoare{P}{c}{P}\n  }{%\n    \\hoare{P}{\\cloop{c}}{P}\n  }\n  \\qquad\n  \\inference[\\textsc{Cons}]{%\n    P \\Rightarrow P'&\n    \\hoare{P'}{c}{Q'}&\n    Q' \\Rightarrow Q\n  }{%\n    \\hoare{P}{c}{Q}\n  }\n  \\end{gather*}\n\\end{spreadlines}\n\\caption{%\n  Hoare Logic judgements over $\\lang$.\n  Metavariables $P, Q, R\\ldots$ represent program\n  assertions. Other metavariables are consistent with\n  \\cref{fig:semantics}\n}\\label{fig:base-proof-system}\n\\end{figure}\n\nHoare Logic is a framework for reasoning about imperative commands by\nrelating them to program \\emph{assertions}.\nAn assertion is a proposition over a program state. Formally, we\ndefine the space of assertions as functions from program states to\npropositions.\n\\[ \\textsf{Assert} ::= \\state \\rightarrow \\textsf{Prop} \\]\nTypically, a Hoare logic system provides a set of judgements over\n\\emph{Hoare Triples}.\nIf $P, Q \\in \\textsf{Assert}$ are assertions and $c \\in \\com$ is a\ncommand, then \\hoare{P}{c}{Q} is a Hoare Triple.\n%\nInformally, this triple can be interpreted as stating \\textbf{(1)} if\nthe assertion $P$ holds over some program state $\\sigma$ and\n\\textbf{(2)} the command $c$ takes $\\sigma$ to $\\sigma'$, then\n\\textbf{(3)} the assertion $Q$ must hold over $\\sigma'$.\n%\nThis definition can be formalized as follows:\n\\[\n  \\hoare{P}{c}{Q} ::= \\forall \\sigma,\n  \\sigma'.~\\ceval{c_0}{\\sigma}{\\sigma'} \\Rightarrow P~\\sigma \\Rightarrow Q~\\sigma'\n\\]\nBy establishing a set of sound rules, a Hoare logic system provides a\ncomposable framework for structuring program proofs.\nWe provide a set of typical Hoare logic rules for $\\lang$ in\n\\Cref{fig:base-proof-system}.\n\n\n\n\\end{document}\n", "meta": {"hexsha": "8c1f6e4a2b2ec9114524b5f530cb5a5be536328b", "size": 5215, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/background.tex", "max_stars_repo_name": "DAHeath/self-relational", "max_stars_repo_head_hexsha": "f230a31945e35119c7bf571d40e5bfc991e89ce1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paper/background.tex", "max_issues_repo_name": "DAHeath/self-relational", "max_issues_repo_head_hexsha": "f230a31945e35119c7bf571d40e5bfc991e89ce1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/background.tex", "max_forks_repo_name": "DAHeath/self-relational", "max_forks_repo_head_hexsha": "f230a31945e35119c7bf571d40e5bfc991e89ce1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8877005348, "max_line_length": 82, "alphanum_fraction": 0.6504314477, "num_tokens": 1846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3427852275917898}}
{"text": "\\chapter{\\label{ch1-intro}Introduction} \n\n\\minitoc\n\n\\section{Cherenkov Radiation}\n\n\\begin{figure}\n  \\begin{subfigure}[b]{0.49\\textwidth}\n    \\includegraphics[width=\\textwidth]{dipole_slow}\n    \\caption{$v < \\frac{c}{n}$}\n    \\label{fig:dipole_slow}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[b]{0.49\\textwidth}\n    \\includegraphics[width=\\textwidth]{dipole_fast}\n    \\caption{$v \\ge \\frac{c}{n}$}\n    \\label{fig:dipole_fast}\n  \\end{subfigure}\n  \\caption[Polarisation produced in a dielectric medium due to the presence of a charged particle.]{Polarisation produced in a dielectric medium due to the presence of a charged particle, for the cases of a non-relativistic (a) and relativistic particle (b). Where $v$ is the speed of the particle and $c/n$ is the speed light travels in a medium with refractive index $n$.}\n\\end{figure}\n\n\\begin{figure}\n\t\\centering\\includegraphics[width=0.5\\textwidth]{cherenkov_geom} \n\t\\caption[Geometry of the wavefronts involved in Cherenkov radiation production.]{Geometry of the wavefronts involved in Cherenkov radiation production. The particle travels at a greater speed than the wavefronts propagate.}\n\t\\label{fig:cherenkov_geom}\n\\end{figure}\n\nWhen a charged particle moves slowly through a dielectric medium, the electric field of the particle distorts the nearby atoms. Momentarily, these atoms are transformed into elementary dipoles where the charged particles that constitute the atom are aligned with respect to the electric field of the travelling particle (Figure~\\ref{fig:dipole_slow}). Due to the complete symmetry of this polarisation around the travelling particle, no net field is produced by the dielectric medium. However, if instead the velocity of the charged particle is faster than the speed light travels in that medium, an asymmetry along the particle trajectory is formed in the polarisation of the surrounding atoms (Figure~\\ref{fig:dipole_fast}), resulting in a net dipole field. As the particle continues through the medium, elements of the polarised medium will release a brief burst of electromagnetic radiation. Generally these electromagnetic waves interfere destructively, except in the forward direction along the particle's trajectory in an opening angle $\\theta$. Although the full characterisation of this relativistic effect is complex, a simple consideration of the geometry involved, shown in Figure~\\ref{fig:cherenkov_geom}, can be used to describe $\\theta$ \\cite{Jelley1958a}. In a time $\\Delta t$ a particle travels a distance $\\beta c \\Delta t$ where $\\beta = \\frac{v}{c}$, while the emitted light will travel a distance $\\frac{c}{n} \\Delta t$ in a medium with refractive index $n$. This results in the relation:\n\\begin{equation} \\label{eq:cherenkov_angle}\n\\cos \\theta = \\frac{c}{vn}.\n\\end{equation}\nThe blue light emitted in this constrained opening angle, via this phenomena, is known as Cherenkov radiation.\n\n\\section{Atmospheric Cherenkov Showers} \\label{section:cherenkov_shower_intro}\n\n\\begin{figure}\n\t\\centering\\includegraphics[width=\\textwidth]{cascade} \n\t\\caption[Production of an extended electromagnetic particle cascade.]{Production of a extended electromagnetic particle cascade, demonstrating the different components and interactions.}\n\t\\label{fig:cascade}\n\\end{figure}\n\nThe Earth's atmosphere is effectively opaque to photons with energy above \\SI{10}{eV} \\cite{Weekes2003}. To conduct astronomical observations at higher energies, one must usually leave the Earth's atmosphere, as was done by the Fermi Gamma-ray Space Telescope. However, at energies above \\SI{\\ge 10}{GeV}, a ``gamma-ray window'' in the atmosphere exists where the pursuit of gamma-ray observations can be performed using the Cherenkov radiation produced by the cascade of particles resulting from the interaction between the gamma ray and the atmosphere.\n\nTwo electromagnetic interactions are responsible for the creation of this cascade:\n\\begin{description}\n\\item [Pair Production] The conversion of a photon into an electron-positron pair in the presence of an atom (such as an atmospheric particle). The energy of the photon must exceed the sum of the rest masses of an electron and positron (\\SI{1.022}{MeV}). The electron-positron pair share the energy of the progenitor photon, and continue on a similar trajectory. This is the dominating interaction process for photons above \\SI{\\ge 10}{MeV} \\cite{Weekes2003}.\n\\item [Bremsstrahlung Radiation] The emission of a photon due to the interaction of a charged particle with the electric field of an atom (such as an atmospheric particle). This process allows further gamma rays to be produced.\n\\end{description}\nThe interplay between these two processes, occurring after each traversal of a radiation length, produces an extensive cascade of energetic electromagnetic particles. This is illustrated in Figure~\\ref{fig:cascade}. The charged particles produced in this cascade are responsible for the generation of the Cherenkov light. This cascade is often known as a ``Cherenkov shower''.\n\nThis cascade continues until the ionisation energy losses are equal to the radiation losses. The number of remaining particles after this point, known as the ``shower maximum'', begins to diminish. For a \\SI{1}{TeV} shower, this occurs at \\SI{\\sim 8.4}{km} altitude~\\cite{Weekes2003}. The produced Cherenkov light is collimated along the progenitor gamma ray trajectory, and produces a pool of blue light on the ground, with a radius of \\SI{\\sim 120}{m}~\\cite{Hillas1996a}. If the direction of the Cherenkov shower is extrapolated back to the cosmic sphere, the location of the source that produced the gamma ray can be inferred. Although the amount of energy that goes into Cherenkov photon production is a tiny fraction of the total energy, the atmosphere acts as a consistent calorimeter, therefore allowing an accurate reconstruction of the progenitor's energy from the amount of Cherenkov photons produced. \n\nA further characteristic of the Cherenkov shower is the time profile. The total Cherenkov light observed from the entire shower has a duration of \\SI{\\sim 5}{ns}. Therefore, despite the abundance of showers in the sky, and the visible wavelength of the Cherenkov light, they are imperceivable by the human eye. Furthermore, due to the faster-than-light velocities of the particles inside the cascade, the last Cherenkov photons produced at the end of the shower reach the ground before the first Cherenkov photons produced at the start of the shower. With different sections of the showers arriving at different times, the Cherenkov shower measurements display a time gradient across the image. \n\n\\section{Imaging Atmospheric Cherenkov Telescopes}\n\n\\begin{figure}\n\t\\centering\\includegraphics[width=\\textwidth]{nsb} \n\t\\caption[Comparison of Cherenkov and NSB spectrum.]{Comparison of Cherenkov and NSB spectrum. The Cherenkov spectrum shown is expected at an altitude of \\SI{2200}{m}. The NSB spectrum shown was measured at La Palma \\cite{Bouvier2013}.}\n\t\\label{fig:nsb}\n\\end{figure}\n\n\\begin{figure}\n\t\\centering\n\t\\begin{subfigure}[b]{0.35\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{hess}\n\t\t\\caption{H.E.S.S.}\n\t\t\\label{fig:hess}\n\t\\end{subfigure}\n\t~\n\t\\begin{subfigure}[b]{0.35\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{magic}\n\t\t\\caption{MAGIC}\n\t\t\\label{fig:magic}\n\t\\end{subfigure}\n\t~\n\t\\begin{subfigure}[b]{0.45\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{veritas}\n\t\t\\caption{VERITAS}\n\t\t\\label{fig:veritas}\n\t\\end{subfigure}\n\t\\caption{Images of modern IACTs.}\n\t\\label{fig:iacts}\n\\end{figure}\n\nA primary issue in \\gls{vhe} astronomy is the low flux (${\\sim} 0.2$ per \\si{m \\squared} per year \\cite{Franco2016}), requiring a collection area that is not feasible for space telescopes. If instead the Cherenkov showers are used to detect the gamma rays, large arrays of optical telescopes can be built to provide stereoscopic imaging of the Cherenkov showers. These telescopes are known as \\glspl{iact}. The multiple stereoscopic views of individual showers provided by arrays of \\glspl{iact} allow accurate reconstruction of the properties of the shower, such as direction and energy. The topic of reconstruction is discussed in Chapter~\\ref{ch6-reduction}.\n\nAs the \\gls{iact} technique involves imaging the Cherenkov showers, which are much larger than typical astronomy targets, \\glspl{iact} do not require the resolving power of typical optical telescopes. Instead, the priorities of an \\gls{iact} optical system are to maximise: \n\\begin{itemize}\n\\item Mirror collection area, such that more photons can be collected. This enables fainter showers to be detected, thereby lowering the energy threshold.\n\\item \\gls{fov}, which improves the surveying capabilities and eases the study of extended sources.\n\\end{itemize}\nFurthermore, the large collection area provided by the light pool of the Cherenkov shower enables a modest telescope to still make a large amount of gamma ray detections, enabling this technique to be viable despite the small flux.\n\nTwo major background components need to be accounted for in \\glspl{iact}:\n\\begin{description}\n\\item [Cosmic Ray Background] Protons (and heavier hadronic nuclei) are also capable of producing Cherenkov showers that are not entirely dissimilar to electromagnetic showers. As these particles are charged, they have been deflected by interstellar magnetic fields on their journey from their source, and therefore cannot be used to reconstruct the location of its source on the sky. These showers provide an isotropic background whose rate is $10^3$~-~$10^4$ times as numerous than the shower rate received from the discreet gamma-ray sources. However, a hadronic shower exhibits a morphology that is broader and less symmetric than that obtained from gamma-ray showers. Additionally, distinct features such as ``muon rings'', produced by highly penetrating muons reaching low altitudes such that the full Cherenkov cone is visible in a single telescope, accompany hadronic showers. Parametrisations of the Cherenkov shower image therefore enable the discrimination between the hadronic and gamma-induced showers (see Chapter~\\ref{ch6-reduction}).\n\\item [Night Sky Background] Due to the optical sensitivity of the cameras used by \\glspl{iact}, the measurements taken are susceptible to starlight, moonlight, and artificial light pollution. To minimise this interference, \\glspl{iact} are built in locations with minimal light pollution. One such location is La Palma, for which the \\gls{nsb} spectrum, compared to the expected Cherenkov spectrum at an altitude of \\SI{2200}{m}, is displayed in Figure~\\ref{fig:nsb}. This background is also excluded from signal readout in three ways. Firstly, smart trigger logic and strict thresholds (such as the one described in Chapter~\\ref{ch2-mechanics}) prevent triggering on \\gls{nsb} photons. Secondly, unbiased charge extraction techniques (described in Chapter~\\ref{ch6-reduction}) exclude this noise from the signal.\n\\end{description}\n\nThe application of the \\gls{iact} technique was first attempted in the 1960s. The first large optical reflector built with the purpose of gamma-ray astronomy was the Whipple 10 m telescope in southern Arizona, 1968. At first, gamma-ray astronomy suffered from a number of unsubstantial claims of transient signals from a variety of pulsars and binaries, but these signals had marginal statistical significance \\cite[][p.~9]{Weekes2003}. It wasn't until 20 years later, after further refinement of the technique, that the Crab Nebula was detected by Whipple in 1989, thus reigniting interest in gamma-ray astronomy.\n\n\\begin{figure}\n\t\\centering\\includegraphics[width=\\textwidth]{sensitivity} \n\t\\caption[Differential sensitivity of CTA.]{Differential sensitivity of CTA predicted by Monte Carlo simulations, compared to the performance of other gamma-ray instruments. Obtained from the CTA website \\cite{cta-performance}. ``LAT'' refers to the Fermi Large Area Telescope, a gamma-ray space telescope. HAWC is the High-Altitude Water Cherenkov array. The differential sensitivity has been defined as the minimum flux needed by CTA to obtain a 5-standard-deviation detection of a point-like source.}\n\t\\label{fig:sensitivity}\n\\end{figure}\n\nModern \\glspl{iact} include \\gls{magic}, \\gls{veritas}, and the most recent, \\gls{hess} (Figure~\\ref{fig:iacts}). All three of these telescope systems operate with the advantage of stereoscopic collaboration. \n\n\\section{The Cherenkov Telescope Array}\n\nIn order to improve on the current \\glspl{iact}, an array of ${\\sim} 100$ telescopes was proposed, called the \\gls{cta}. This array will have \\cite{Acharya2013}:\n\\begin{itemize}\n\\item an improved sensitivity of 10 times over previous \\glspl{iact} ,\n\\item an observable gamma-ray energy range of \\SI{20}{GeV} to \\SI{300}{TeV},\n\\item a large (\\SI{\\sim 8}{\\degree}) field of view for surveys,\n\\item improved angular and energy resolution,\n\\item and will be the first \\gls{iact} to operate as an open observatory.\n\\end{itemize}\n\nFigure~\\ref{fig:sensitivity} highlights the improvements in sensitivity \\gls{cta} aims to provide, relative to existing gamma-ray instruments. Non-\\gls{iact} instruments are included in the comparison, such as the Fermi LAT (Large Area Telescope) and \\gls{hawc}. Fermi LAT is the principle instrument on the Fermi Gamma-Ray Satellite, providing direct detection of gamma rays in the energy range of \\SIrange{0.02}{300}{GeV} \\cite{Atwood2009}. \\gls{hawc} is a facility which utilises the water Cherenkov technique, an alternative to \\glspl{iact}, to detect the particle showers produced by gamma rays within the energy range of \\SIrange{0.1}{100}{TeV} \\cite{Abeysekara2018}.\n\n\\begin{figure}\n\t\\centering\\includegraphics[width=\\textwidth]{sensitivity_tel} \n\t\\caption[Differential sensitivity of the different CTA telescope types.]{Contribution of each telescope type within \\gls{cta} to the total differential sensitivity, obtained from \\textcite{Marano2014}.}\n\t\\label{fig:sensitivity_tel}\n\\end{figure}\n\n\\gls{cta} will consist of three different sized telescopes:\n\\begin{itemize}\n\\item The \\gls{lst}, with a mirror diameter of about \\SI{23}{m} to enable the collection of as many photons as possible from the low energy showers (\\SIrange{20}{150}{GeV}). Only a few \\glspl{lst} are needed, as these low-energy showers are relatively frequent.\n\\item The \\gls{mst}, covering the mid-range energies between \\SIrange{0.1}{10}{TeV}, with mirror diameters of \\SI{12}{m}. \n\\item The \\gls{sst}, measuring the high energies of \\SIrange{1}{300}{TeV}, with mirror diameters of around \\SI{4}{m}. Only a small mirror area is necessary as the showers at these energies are very bright. However, due to the rarity of higher energy showers, many \\glspl{sst} need to be spread over an area of several square kilometres, to increase the chance of a detection \\cite{Acharya2013}.\n\\end{itemize}\nThe contributions of each telescope type to the sensitivity of \\gls{cta} is shown in Figure~\\ref{fig:sensitivity_tel}.\n\n\\begin{figure}\n\t\\centering\\includegraphics[width=\\textwidth]{cta_south} \n\t\\caption[The southern-hemisphere Cherenkov Telescope Array.]{Computer-rendered graphic of the southern hemisphere site for CTA, obtained from the CTA website \\cite{cta-south}.}\n\t\\label{fig:cta_south}\n\\end{figure}\n\n\\gls{cta} will be hosted at two different sites. A northern hemisphere site for extragalactic observations will be built at La Palma, and is planned to contain 4 \\glspl{lst} and 16 \\glspl{mst}. As this site will focus on the energy range from \\SI{20}{GeV} to \\SI{20}{TeV}, no \\glspl{sst} are included on the northern site. A southern hemisphere site will provide observations of the galactic plane, spanning the full energy range of \\gls{cta}. Planned to be built nearby the Paranal Observatory in the Atacama Desert in Chile, the southern array is intended to feature 4 \\glspl{lst}, 15 \\glspl{mst}, and 70 \\glspl{sst}, spread over \\SI{4}{km \\squared}. A visualisation of the \\gls{cta} southern array is shown in Figure~\\ref{fig:cta_south}.\n\n\\section{Small-Sized Telescopes}\n\n\\begin{figure}\n\t\\centering\\includegraphics[width=\\textwidth]{ssts} \n\t\\caption[The three SST designs.]{Computer-rendered graphics of the three SST designs: GCT, ASTRI and SST-1M. Obtained from the CTA website \\cite{cta-sst}.}\n\t\\label{fig:ssts}\n\\end{figure}\n\nThree designs for an \\gls{sst} have been proposed:\n\\begin{itemize}\n\\item The SST-1M design, a single-mirror Davies-Cotton telescope developed in collaboration between the Czech Republic, Ireland, Poland, Switzerland and Ukraine \\cite{cta-sst}. The prototype structure was installed at the Institute of Nuclear Physics in Kraków, Poland in November 2013.\n\\item The \\gls{astri} design features a dual-mirror Schwarzschild-Couder telescope structure. \\gls{astri} is predominantly developed by Italy, however contributions were provided from Brazil and South Africa \\cite{cta-sst}. The \\gls{astri} prototype completed construction on Mt. Etna, Italy in 2014.\n\\item The \\gls{gct} design also features a dual-mirror Schwarzschild-Couder telescope structure. \\gls{gct} is being developed through collaboration between Australia, France, Germany, Japan, the Netherlands and the United Kingdom \\cite{cta-sst}. The prototype telescope structure was inaugurated at the Observatoire de Paris-Meudon, France in November 2015. \\gls{gct} is the telescope which I have been associated with during my DPhil study. The focus of this thesis is on the cameras designed for the \\gls{gct}.\n\\end{itemize}\nPictures of all three telescopes are shown in Figure~\\ref{fig:ssts}.\n\nThe Schwarzschild-Couder optical design was first proposed by German astrophysicist Karl Schwarzschild to eliminate optical aberrations across the \\gls{fov} \\cite{Scharzschild1905}. This optical design has since gone through many iterations, however it was never utilised for a reflector telescope due to the complexity and cost required to construct the mirrors \\cite{Giro2017}. However, interest in this optical design was recently reawaken by \\textcite{Vassiliev2007}, especially as it enables the utilisation of novel compact photosensors. Due to the adoption of similar Schwarzschild-Couder optics, the telescopes of \\gls{astri} and \\gls{gct} have been specifically designed to accommodate the cameras from both dual-mirror \\glspl{sst}. This increases the possibilities for the final \\gls{sst} design for \\gls{cta}.\n\n\\section{Science with the SSTs}\n\nAs shown in Figures~\\ref{fig:sensitivity}~and~\\ref{fig:sensitivity_tel}, the \\glspl{sst} are responsible for exploring beyond the current energy frontier in gamma-ray astronomy. Within 50 hours of observation time, the \\glspl{sst} will be able provide the same sensitivity as five years of observations with the \\gls{hawc} observatory \\cite{Consortium2018}. This enables \\gls{cta} to provide insights into the most energetic processes in the universe, and address prevalent topics of debate in \\gls{vhe} astronomy and particle physics.\n\nThe high energy science cases of \\gls{cta} are mostly concerned with the acceleration mechanisms that produce high energy cosmic rays. This has been an active topic of discussion in the past 100 years since their initial detection. It is therefore hoped that the \\gls{cta} \\glspl{sst} can provide new insight into these mechanisms. The different investigations related to this topic can be loosely consolidated into the following categories:\n\\begin{description}\n\\item [Supernova Remnants] It is known that the galactic population of \\glspl{snr} plays an important role in the acceleration of cosmic rays to high energies. The detection of \\si{TeV} photons from \\glspl{snr} (suggesting an efficient acceleration mechanism), and the description of the diffusive shock acceleration mechanism, both corroborate with the detection of high-energy cosmic rays in the Earth's atmosphere \\cite{Cristofari2017}. However, the detection of \\si{TeV} photons from \\glspl{snr} could instead be explained by the inverse-Compton scattering between accelerated electrons and the ambient photon background. Therefore, the debate between a leptonic or hadronic origin is still ongoing \\cite{Acharya2013}. While studies of individual \\glspl{snr} have improved our understanding of the acceleration mechanisms, a population wide study may help constrain the parameters involved \\cite{Cristofari2017}. The probe into higher energies with the \\glspl{sst} will provide further information about the spectral energy distribution of the currently known \\glspl{snr}, and the enhanced sensitivity of \\gls{cta} will increase the population of \\glspl{snr} known to emit at these energies.\n\\item [Origin of Cosmic Rays] Another important question regarding the locally measured flux of high-energy cosmic rays is their origin \\cite{Bigongiari2016}. As just described, \\glspl{snr} appear to be a dominant source for these particles, but are they the only major contributor to the galactic cosmic rays? Expanding on the discovered \\gls{vhe} galactic source population is the key to answering this question.\n\\item [Pevatrons] A further capability of \\gls{cta} (provided by the \\glspl{sst}) is the detection of extreme accelerators that power particles up to the \\si{PeV} scale. As a result of the acceleration of hadronic cosmic rays to these energies, gamma rays with energies of \\SI{100}{TeV} should be detectable from the accelerator. However, as the cross-section for inverse-Compton electron-photon interactions decreases very quickly above a few tens of \\si{TeV} \\cite{Consortium2018}, the absence of \\SI{100}{TeV} gamma rays from these accelerators would suggest a leptonic origin. The identification of even one Pevatron accelerator would therefore provide a huge breakthrough in the investigations into the origins of \\gls{vhe} gamma rays.\n\\end{description}\n\n\\section{Thesis Outline}\n\nThe focus of this thesis is on the camera for the \\gls{gct} \\gls{sst}. I begin with a detailed description of the camera's components and waveform readout in Chapter~\\ref{ch2-mechanics}. Specific focus is given to the Silicon Photomultiplier (SiPM), the photosensor utilised in the latest camera implementation. This photosensor exhibits high photoelectron counting resolution for a large dynamic range, but suffers from a phenomena known as optical crosstalk, which degrades the ability to resolve the number of incident photons detected with the photosensor.\n\nI provide background on the \\gls{cta} system architecture in Chapter~\\ref{ch3-architecture} in order to introduce the performance requirements the camera must meet. The most important requirement in the context of this thesis is the Charge Resolution, a measure of how accurately the signal contained in waveform can be resolved.\n\nChapter~\\ref{ch4-software} outlines the software packages relevant to the processing pipeline for the Cherenkov shower data recorded by the camera, many of which I have been actively involved in developing. This includes the low-level \\cpp~libraries used to read out and calibrate the waveforms from the camera, the Python packages responsible for reconstructing the Cherenkov shower parameters from the waveforms, and finally the science tools developed to analyse the reduced photon event lists provided by the \\gls{cta} Observatory to the public.\n\nThe calibration procedures I have developed for the camera are described in Chapter~\\ref{ch5-calibration}. These procedures remove the artefacts that are particular to the camera's electronics, transforming the waveform readout into a state ready for common signal processing techniques. The calibration procedures for the photosensor are also covered, which act to unify the illumination response between the different pixels in the camera.\n\nChapter~\\ref{ch6-reduction} describes the signal processing techniques commonly utilised by \\glspl{iact} to extract the Cherenkov shower signal from the waveforms. The \\textit{cross-correlation} approach I have developed and adopted for signal extraction is also described. Within this chapter I continue on to describe how the information extracted from the waveform is used to reconstruct the properties of the Cherenkov shower progenitor. \n\nI assess the cumulative performance of the camera (resulting from its components, calibration, and waveform processing) in Chapter~\\ref{ch7-performance}. The requirements introduced in Chapter~\\ref{ch3-architecture} are used as the benchmarks to assess the performance against, as the requirements must be met for the camera to be accepted as a contribution to \\gls{cta}. I also highlight the significance of the optical crosstalk on the Charge Resolution, and explore the impact of future improvements to the photosensor.\n\nIn Chapter~\\ref{ch8-onsky} I report on the on-telescope campaigns performed with an earlier iteration of the \\gls{gct} camera, demonstrating the application of Cherenkov shower parametrisation techniques introduced in Chapter~\\ref{ch6-reduction}.\n", "meta": {"hexsha": "0c3405c0369ba77a929346dac5246d4af16223d0", "size": 24889, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/text/ch1-intro.tex", "max_stars_repo_name": "watsonjj/Thesis", "max_stars_repo_head_hexsha": "6b0a0869b9a9a8abbc2ab74b367f7a9d7d741644", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-16T14:30:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T14:30:06.000Z", "max_issues_repo_path": "thesis/text/ch1-intro.tex", "max_issues_repo_name": "watsonjj/Thesis", "max_issues_repo_head_hexsha": "6b0a0869b9a9a8abbc2ab74b367f7a9d7d741644", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis/text/ch1-intro.tex", "max_forks_repo_name": "watsonjj/Thesis", "max_forks_repo_head_hexsha": "6b0a0869b9a9a8abbc2ab74b367f7a9d7d741644", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 130.9947368421, "max_line_length": 1509, "alphanum_fraction": 0.797500904, "num_tokens": 5967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.34273068479335117}}
{"text": "\\section{(Initial) Causal Graph Construction}\n\\label{sec:graph-construction}\n\nConstruction of an initial causal graph typically proceeds as follows.\nAt a high level, we\n\\begin{enumerate}\n   \\item adopt a population perspective,\n   \\item brainstorm all variables that we think affect the system that generates our observations,\n   \\item remove any variables that could cause bias in our causal inferences,\n   \\item connect all variables in our graph according to our a-priori beliefs about causal relations amongst them\n   \\item consider how the graph structure may differ between individuals and subgroups within the population.\n\\end{enumerate}\nThe following paragraphs describe these steps in detail.\n\nTo begin, we adopt the position of a researcher concerned about population level relationships.\nThis means we will think through what is a likely generative model for all individuals.\nLater in this section, we will devote time to thinking about how subgroups and individual heterogeneity may affect our causal graphs.\n\nNow, we add our first variable(s) to our graph, the outcome variable(s) of interest in our problem.\nNote that we should consider relations and dependencies between these outcomes, and we should draw these onto our graphs.\nSuch inter-outcome dependencies may be of great relevance or even focus.\nRecall, for example, the case of activity-based modellers that was mentioned in Section \\ref{sec:choice-graphs}.\nSimilarly, medical researchers with data on multiple health measures or companies with multiple business metrics may all be interested in how the outcomes cause each other.\n\nAfter adding our outcomes to our graph, we list all the variables we believe to cause them.\nWe refer to these influencing variables as our initial explanatory variables.\n\nNext, we iterate through these initial explanatory variables.\nFor each current explanatory variable in the iteration, we think of variables that may modify the effect of the current explanatory variable on the outcome(s) of interest.\nWe refer to these variables as effect modifiers\\footnote{Note, effect modifiers and confounders are easily confused. Both variables cause the outcome. The difference is that effect modifiers do not cause the explanatory / treatment variables. Confounders do. For discussion and classification of the different types of effect modification, based on one's causal graph, see \\citet{vanderweele_2007_four}}.\nNote that some effect modifiers may be a part of our list of initial explanatory variables.\nFor any effect modifiers that we think of, outside of the list of initial explanatory variables, we add them to our causal graph.\n\nOverall, modifiers are important because our treatment effects systematically vary with them.\nAccordingly, if we better understand when our treatments will be effective, then we can better target them.\n% For instance, the effect of a transit voucher on increasing an individual's probability of using transit is likely modified by the recipients income.\n% We expect a smaller treatment effect on wealthy individual's than on individual's with low income\nFor instance, imagine that a region-wide lockdown reduces the 14-day rolling average of new COVID-19 cases by X\\% (on average).\nOf course, we know that a lockdown's effectiveness is modified by the percentage of workers who must continue going out to work.\nIf most residents in an area are essential workers, then a lockdown will be less effective there, as compared with other locales.\nWe might wish to target other interventions for that region, as a replacement or supplement for the lockdown.\nTargeting aside, knowledge of modifiers is also crucial to generalizing treatment effect inferences from one population to another.\nTo credibly transport our inferences, we must know what variables cause the treatment effects to differ between populations, and we must know how the distributions of those variables differs across populations \\citep{pearl_2014_external}.\nIn general, see \\citet{zheng_2018_automated} for a thorough introduction to moderation, its differences from other variables in one's causal graph, and for instructions on how to find moderators through data analysis alone.\n\nAfter adding explanatory and effect modifying variables to the graph, we turn our attention to mediating variables.\nA mediating variable is one through which an explanatory variable influences our outcome(s) of interest.\nSuch variables have multiple uses.\nUnder certain instances of confounding, mediators enable the ``front-door'' criterion to identify one's causal effect \\citep{glynn_2018_front, bellemare_2019_paper, gupta_2020_estimating}.\nSimilarly, subject to particular causal assumptions, mediating variables permit inference on long-term outcomes of a selected intervention, given only its short-term proxies \\citep{athey_2019_estimating, yang_2020_targeting}.\n\nTo find these mediators, we again iterate through each explanatory variable.\nOn each iteration, we brainstorm variables along paths of influence from our explanatory variable to our outcome.\nFor instance, consider how the presence of a bike lane influences bicycle mode choice.\nWe hypothesize that an individual's subjective perception of safety is the primary (or sole) mediator through which bicycle lane presence influences mode choice.\nAccordingly, we add subjective perception of safety to our causal graph for travel mode choice.\n\nAfter considering the variables above, we turn our attention to variables that complicate our analyses.\nTo begin with, we think of confounding variables.\nThe process is similar to how we generated effect modifying variables.\nWe iterate through each of the explanatory, mediating, and effect modifying variables, thinking specifically of any variables that both cause the current variable in the iteration and cause the outcome variable(s).\nWe call these variables, which cause our outcome and current variables in the iteration, confounding variables \\citep{elwert_2013_graphical, greenland_1999_confounding}.\nAs an example, consider a person's attitude towards environmental conservation.\nThis attitude may cause both that individual's observed distance to their workplace (another explanatory variable) and that individual's choice of travel mode.\nBoth in this example and in general, we should add such confounding variables to our causal graph.\n\nNext, we consider the effects of selection.\nAs noted by \\citet{greenland_2020_causal}, all datasets have a causal graph that implicitly conditions on a selection node.\nI.e., we only analyze data that has been selected to be a part of our dataset.\nWe should therefore consider how all of the other nodes in our causal graph relate to the selection node.\nIn particular, will we suffer any selection bias due to the outcomes influencing whether an observation is selected for inclusion in our dataset?\nSelection bias, if present, can cause our estimated causal effects to differ greatly from their population counterparts.\nThis stems from systematic differences between the observations that have been selected into our dataset and the observations in our population of interest.\nFor more details, see \\citet{heckman_1979_sample} and \\citet{hernan_2004_structural} as canonical references.\n\nAnother universally implied yet only implicitly described element of one's causal graph is the prior data and code that led to one's dataset \\citep[Pg.7]{greenland_2020_causal}.\nPresumably, prior data and potentially code-enabled-analysis influenced the sample design that led to your dataset.\nPerhaps some data transformations and code to implement those transformations was used to convert a raw dataset into the dataset being used for causal inference.\nAnd at all times, one uses computer programs to compute your reported results.\nIn each case, the prior data is variable that influences your current data, and your code is computational (sub)graph that is implicit in your causal graph.\nThese elements should perhaps be made explicit, and their influence on your causal effect estimates should definitely be assessed and reported.\n\nNext, we should explicitly consider the role of time, even in research that may be cross-sectional due to the data that is available to us or due to the problem itself.\nIn reality, how do we think our system evolves over time?\nIf we consider multiple observations of a given decision maker, how does that decision maker's observed variables at time $t$ partially cause future variables important to the context or outcome(s) for that decision maker at time $t' > t$?\nHow do the actions of a decision maker $i$ at time $t$ partially cause the future context or outcomes of a decision maker $j$?\nWe should add explicit nodes to our graph, subscripted or denoted by time, to show the cross-time causal relationships in our system.\nFor in-depth discussion of time-related causal inference topics, see papers such as \\citet{gill_2001_causal}, \\citet{eichler_2007_granger}, and \\citet{peters_2013_causal}.\nPlease note that the literature on this topic is vast, and the cited authors are not at all exhaustive or representative of all papers in this space.\nInterested readers are encouraged to perform further literature searches on their own.\n\nSimilarly, we will frequently want to consider the role of space.\nIn the context of choice modelling, this includes questions such as ``how does a decision maker's existence in a particular geographical area shape their choices?''\nFor example, consider multinational corporations where the business operates differently across state borders.\nHere, the borders associated with space directly causes a difference in the causal graph of how these businesses deliver their goods and services to customers.\nIn other instances, one can consider space as a noisy proxy for unobserved confounders, such as cultural attitudes of a region's inhabitants \\citep{paciorek_2010_importance}.\nRooted in the causal problem of unobserved confounding, this results in known statistical issues for choice modellers such as spatial correlation of model residuals \\citep{fleming_2004_techniques}.\nFortunately, some progress has been made in dealing with such problems.\nFor general discussion of recent techniques in causal inference for spatial-causal modelling to deal with such issues, see \\citet{osama_2019_inferring}.\n\nAt this point, we have added to our causal graph all the\noutcome, explanatory, effect modifying, mediating, confounding, selection, data/code, time-indexed, and space-indexed variables that we believe are relevant for our problem.\nHowever, many of these variables may be disconnected nodes, i.e., singletons in the graph.\nWe now focus on pruning nodes from this graph, before drawing our final hypothesized connections.\nIn particular, we focus on pruning ``post-outcome'' variables that are not part of the causal graph for future time periods or other observations.\nThe reason for this is that conditioning on such post-outcome variables would bias our causal effect estimates.\nOur pruning exception is the selection variable which we have no choice but to condition on.\nIt may unfortunately be a post-outcome.\n\nTo remove the problematic variables, we iterate through each of the non-outcome variables in our graph, and we assess whether each variable is actually a result of the outcome (perhaps in combination with other variables in our graph).\nThese post-outcome variables temporally follow the outcome variable(s) but do not cause variables in the causal graph for other observations.\nWe remove all such post-outcome variables from our graph.\n\nNow is a good time to step back and consider what other researchers have thought about our problem.\nSpecifically, we should conduct a literature review to see how other researchers have conceptualized the topic that we are working on.\nHave they included variables that we have not?\nWere those variables related our outcomes of interest?\nIf so, should we add these variables to our causal graph? How should these variables enter our graph?\nDo the included variables of other researchers suggest the existence of confounders in their work that we should include in our graph?\nHave other researchers ascribed differing roles to our graph's current variables than we have?\nFor example, have other researchers judged a variable to be a confounder, when we solely thought of the variable as an effect modifier?\nAs we answer these questions, we should critically examine the evidence for these alternative decisions to see if we should also reconsider how we're judging our variables.\n\nFinally, we need to connect the variables in our graph.\n\\begin{enumerate}\n   \\item Draw direct arrows from our explanatory variables, confounders, and effect modifiers to the outcomes.\n   \\item Draw arrows from the explanatory variables to the mediators, and then draw arrows from the mediators to the outcomes.\n   \\item Draw arrows from the confounders to the explanatory variables and mediators that they may cause.\n   \\item Draw arrows from the variables in time $t$ to the variables that they cause in time $t+1$.\n   \\item Draw arrows from the variables that cause one's location in space to spatial variable nodes, and draw arrows to variables that are caused by one's location in space.\n   \\item Draw arrows from all other nodes in one's graph to the selection node, based on which variables cause inclusion in one's dataset.\n\\end{enumerate}\nAfter drawing in all arrows, we should now have a fully connected causal graph.\nPause.\nLook over the graph to ensure there are no remaining singletons, and ensure that we have not drawn any spurious connections.\nThen, stop briefly to celebrate.\nDrawing a project's first causal graph is hard work!\n\nAfter celebrating, take a moment to pursue the following graph editing exercises.\nFirst, think about how the graph might differ across sub-populations.\nWhat sub-populations, if any, exist in your population of interest?\nAre there any causal relationships that should, or should not, not exist for a given sub-population?\nFor instance, are the outcomes in some sub-populations independent of a given explanatory variable?\nCan you think of any inverted causal relationships that are specific to this sub-population?\n(I.e., for a given sub-population, does $B \\rightarrow A$ instead of $A \\rightarrow B$?)\nAs explained in \\citet[Sec. 4]{druzdzel_2003_combining},\nadd these sub-populations to one's initial causal graph via a ``selection node,''\nor if this is not clear enough,\ndraw modified causal graphs for each sub-population of interest.\nNow, one can actually relax.\nThis concludes the ``purely mental'' drafting of one's causal graph.\nIn the next section, we'll look at testing this graph against data, and making any edits deemed empirically necessary.\n", "meta": {"hexsha": "5af0d12ef67c70da0f91df97e7fdc25c9b2027af", "size": 14739, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "article/sections/_4_graph_construction.tex", "max_stars_repo_name": "hassanobeid1994/tr_b_causal_2020", "max_stars_repo_head_hexsha": "1ffaeb7dcefccf5e1f24c459e9a2f140b2a052a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "article/sections/_4_graph_construction.tex", "max_issues_repo_name": "hassanobeid1994/tr_b_causal_2020", "max_issues_repo_head_hexsha": "1ffaeb7dcefccf5e1f24c459e9a2f140b2a052a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 89, "max_issues_repo_issues_event_min_datetime": "2020-02-10T02:52:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-23T03:50:27.000Z", "max_forks_repo_path": "article/sections/_4_graph_construction.tex", "max_forks_repo_name": "hassan-obeid/tr_b_causal_2020", "max_forks_repo_head_hexsha": "1ffaeb7dcefccf5e1f24c459e9a2f140b2a052a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 96.3333333333, "max_line_length": 404, "alphanum_fraction": 0.8146414275, "num_tokens": 2931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.34273068332553475}}
{"text": "\\chapter{DNA Models}\n\\label{chap:dna}\n\n\n\\section{3SPN.2C}\n\\label{sec:dna_3spn2c}\n\nThe series of the 3SPN.x DNA models have been developed by de Pablo's\ngroup~\\cite{Freeman2011, Hinckley2013, Freeman2014}.  The 3SPN.2C model is the\none for modeling sequence-dependent curvature of double-stranded DNA\n(dsDNA)~\\cite{Freeman2014}.  Particularly, the model has been well-tuned to\nreproduce both mechanical and geometrical properties, such as persistent length\nand major/minor groove widths~\\cite{Hinckley2013, Freeman2014}. \n\n\\subsection{Topology}\n\\label{subsec:dna_3spn2c_top}\n\nIn this model, each nucleotide is represented by three CG particles, P\n(phosphate), S (sugar), and B (base), as shown in \\autoref{fig:dna_3spn2c_top}.\nB has four types: A (adenine), C (cytosine), G (guanine), and T (thymine).  The\nCG particles are put at the center-of-mass of each chemical moiety.\n\n\\begin{figure}[ht]\n  \\centering\n  \\includegraphics[width=0.3\\textwidth]{figures/DNA_3spn2c_top.png}\n  \\caption{Topology of the 3SPN.2C DNA model: each nucleotide is represented by\n    3 sites corresponding to phosphate (P), deoxyribose sugar (S), and\n    nitrogenous base (B).  A typical nucleotide ``residue'' is enclosed by the\n    dashed line.}\n  \\label{fig:dna_3spn2c_top}\n\\end{figure}\n\n\n\\begin{table}[ht]\n  \\centering\n  \\begin{tabular}{lc}\n    \\toprule\n    Particle Type    & Mass (amu) \\\\\n    \\midrule\n    P  &  94.97 \\\\\n    S  &  83.11 \\\\\n    A  &  134.1 \\\\\n    C  &  110.1 \\\\\n    G  &  150.1 \\\\\n    T  &  125.1 \\\\\n    \\bottomrule\n  \\end{tabular}\n  \\caption{Mass of the 3SPN.2C DNA particles.}\n  \\label{tab:dna_3spn2c_top_mass}\n\\end{table}\n\n\\subsection{Potentials}\n\\label{subsec:dna_3spn2c_potential}\n\nThe 3SPN.2C potentials can be devided into two parts, as usual, bonded, and\nnonbonded:\n\\begin{displaymath}\n  U = U_b + U_{nb}.\n\\end{displaymath}\n\nThe bonded potentials include the following terms:\n\\begin{itemize}\n\\item bonds ($U_{bond}$),\n\\item angles ($U_{ang}$),\n\\item dihedral angles ($U_{dih}$).\n\\end{itemize}\n\\begin{equation}\n  \\label{eq:dna_3spn2c_local}\n  U_b = U_{bond} + U_{ang} + U_{dih}.\n\\end{equation}\n\nThe nonbonded potentials include these terms:\n\\begin{itemize}\n\\item base-base interactions:\n  \\begin{itemize}\n  \\item base stacking ($U_{bstk}$),\n  \\item base pairing ($U_{bp}$),\n  \\item cross base stacking ($U_{cstk}$),\n  \\end{itemize}\n\\item excluded volume interactions ($U_{exv}$),\n\\item electrostatic interactions ($U_{ele}$).\n\\end{itemize}\n\\begin{equation}\n  \\label{eq:dna_3spn2c_nonlocal}\n  U_{nb} = U_{bstk} + U_{bp} + U_{cstk} + U_{exv} + U_{ele}.\n\\end{equation}\n\n\n\\subsubsection{Bond}\n\\label{sec:dna_3spn2c_potential_bond}\n\n\\begin{smallpage}{3SPN.2C bond potential}<white>\n  \\begin{equation}\n    \\label{eq:dna_3spn2c_local_bond}\n    U_{bond} = \\sum_{i}^{bonds} k_b (r_i - r_{i,0})^2 + 100 k_b (r_i - r_{i,0})^4.\n  \\end{equation}\n  \\tcblower\n  \\begin{itemize}\n  \\item Bonds involved:\n    \\begin{itemize}\n    \\item P-S\n    \\item S-B\n    \\item S-P\n    \\end{itemize}\n  \\item $r_{i, 0}$: based on the structure of B-form DNA.\n  \\item $k_b = 0.6\\ \\mathrm{kJ/mol/\\angstrom^2}$.\n  \\end{itemize}\n\\end{smallpage}\n\n\n\n\\subsubsection{Angle}\n\\label{sec:dna_3spn2c_potential_angle}\n\n\\begin{smallpage}{3SPN.2C bond angle potential}<white>\n  \\begin{equation}\n    \\label{eq:dna_3spn2c_local_angle}\n    U_{ang} = \\sum_{i}^{angles} k_\\theta (\\theta_i - \\theta_{i,0})^2.\n  \\end{equation}\n  \\tcblower\n  \\begin{itemize}\n  \\item Angles involved:\n    \\begin{itemize}\n    \\item P-S-P\n    \\item S-P-S\n    \\item P-S-B\n    \\item B-S-P\n    \\end{itemize}\n  \\item $\\theta_{i, 0}$: based on the structure of B-form DNA.\n  \\item $k_\\theta$: see the table below: (unit: $\\mathrm{kJ/mol/rad^2}$)\n  \\end{itemize}\n  \\begin{center}\n    \\begin{tabular}{l|cl|cl|cl|cl}\n      \\toprule\n      \\emph{PSP} & all & \\multicolumn{7}{l}{300}\\\\\n      \\midrule\n      \\multirow{4}{*}{\\emph{SPS}} &\n                                    AA & 355 & AT & 147 & AC & 464 & AG & 368 \\\\\n                 & TA & 230 & TT & 355 & TC & 442 & TG & 273 \\\\\n                 & CA & 273 & CT & 368 & CC & 165 & CG & 478 \\\\\n                 & GA & 442 & GT & 464 & GC & 228 & GG & 165 \\\\\n      \\midrule\n      \\multirow{4}{*}{\\emph{PSB}} &\n                                    AA & 460 & TA & 120 & CA & 206 & GA & 383 \\\\\n                 & AT & 370 & TT & 460 & CT & 358 & GT & 442 \\\\\n                 & AC & 442 & TC & 383 & CC & 278 & GC & 336 \\\\\n                 & AG & 358 & TG & 206 & CG & 278 & GG & 278 \\\\\n      \\midrule\n      \\multirow{4}{*}{\\emph{BSP}} &\n                                    AA & 460 & AT & 370 & AC & 442 & AG & 358 \\\\\n                 & TA & 120 & TT & 460 & TC & 383 & TG & 206 \\\\\n                 & CA & 206 & CT & 358 & CC & 278 & CG & 278 \\\\\n                 & GA & 383 & GT & 442 & GC & 336 & GG & 278 \\\\\n      \\bottomrule\n    \\end{tabular}\n  \\end{center}\n\\end{smallpage}\n\n\\subsubsection{Dihedral Angle}\n\\label{sec:dna_3spn2c_potential_dihedral_angle}\n\nThe dihedral angle potential in the 3SPN.2C model contains two parts:\n\\begin{enumerate}\n\\item A strong Gaussian type potential applied on the backbone dihedrals\n  ($U_{dih, Gaussian}$);\n\\item A weak periodic potential applied on all dihedral angles ($U_{dih, periodic}$).\n\\end{enumerate}\n\\begin{equation}\n  \\label{eq:dna_3spn2c_local_dihedral}\n  U_{dih} = U_{dih, Gaussian} + U_{dih, periodic}.\n\\end{equation}\n\n\\begin{smallpage}{3SPN.2C dihedral angle potential (Gaussian)}<white>\n  \\begin{equation}\n    \\label{eq:dna_3spn2c_local_dihedral_Gaussian}\n    U_{dih, Gaussian} = \\sum_{i}^{dihedrals} -k_{ \\phi, Gaussian } \\exp\\big( \\frac{-(\\phi_i - \\phi_{i,0})^2}{2\\sigma_{\\phi}^2} \\big).\n  \\end{equation}\n  \\tcblower\n  \\begin{itemize}\n  \\item Dihedral angles involved:\n    \\begin{itemize}\n    \\item P-S-P-S\n    \\item S-P-S-P\n    \\end{itemize}\n  \\item $\\phi_{i, 0}$: based on the structure of B-form DNA.\n  \\item $k_{\\phi, Gaussian} = 7.0\\ \\mathrm{kJ/mol}$.\n  \\item $\\sigma_\\phi = 0.3$.\n  \\end{itemize}\n\\end{smallpage}\n\n\\begin{smallpage}{3SPN.2C dihedral angle potential (periodic)}<white>\n  \\begin{equation}\n    \\label{eq:dna_3spn2c_local_dihedral_periodic}\n    U_{dih, periodic} = \\sum_{i}^{dihedrals} k_{\\phi, periodic} \\big[ 1+\\cos(\\phi_i - \\phi_{ i,0 }) \\big].\n  \\end{equation}\n  \\tcblower\n  \\begin{itemize}\n  \\item Dihedral angles involved:\n    \\begin{itemize}\n    \\item P-S-P-S\n    \\item S-P-S-P\n    \\item S-P-S-B\n    \\item B-S-P-S\n    \\end{itemize}\n  \\item $\\phi_{i, 0}$: based on the structure of B-form DNA.\n  \\item $k_{\\phi, periodic} = 2.0\\ \\mathrm{kJ/mol}$.\n  \\end{itemize}\n\\end{smallpage}\n\n\n\\subsubsection{Base Stacking}\n\\label{sec:dna_3spn2c_potential_bstk}\n\nBefore we introduce the nonbonded terms, we would like to first show the\ntopology of the double stranded DNA and clarify the CG particles involved in the\nbase-base interaction terms (see \\autoref{fig:DNA_3spn2c_nonbonded_all}).\n\n\\begin{figure}[ht]\n  \\centering\n  \\includegraphics[width=0.45\\textwidth]{figures/DNA_3spn2c_nonbonded_all.png}\n  \\caption{The base-related nonbonded interactions among DNA CG particles.  Here\n    we introduce local indices (circled numbers) for easy understanding.  The\n    base-stacking interactinos are calculated for the neighboring bases\n    ($U_{bstk}$).  The base-pairing interactions are considered for Watson-Crick\n    pairs, namely, the A-T and G-C pairs ($U_{bp}$).  Whereas the cross-stacking\n    terms are only considered for bases next to the pairsing bases ($U_{cstk}$).}\n  \\label{fig:DNA_3spn2c_nonbonded_all}\n\\end{figure}\n\nWe would like to also define several common functions used by the\nbase-interaction potentials:\n\\begin{equation}\n  \\label{eq:dna_3spn2c_nonlocal_base_rep}\n  U_m^{rep}(\\epsilon_{ij}, \\alpha_{ij}, r_{ij}) =\n  \\begin{cases}\n    \\epsilon_{ij} \\Big( 1-e^{\\big(-\\alpha_{ij}(r_{ij}-r_{ij,0})\\big)} \\Big)^2 & r_{ij} < r_{ij, 0}, \\\\[.5em]\n    0 & r_{ij} \\ge r_{ij, 0}.\n  \\end{cases}\n\\end{equation}\n\n\\begin{equation}\n  \\label{eq:dna_3spn2c_nonlocal_base_attr}\n  U_m^{attr}(\\epsilon_{ij}, \\alpha_{ij}, r_{ij}) =\n  \\begin{cases}\n    -\\epsilon_{ij} & r_{ij} < r_{ij, 0}, \\\\[.5em]\n    \\epsilon_{ij} \\Big(1-e^{\\big(-\\alpha_{ij}(r_{ij}-r_{ij,0})\\big)} \\Big)^2 - \\epsilon_{ij} & r_{ij} \\ge r_{ij, 0}.\n  \\end{cases}\n\\end{equation}\n\nIn ~\\autoref{eq:dna_3spn2c_nonlocal_base_rep} and\n\\autoref{eq:dna_3spn2c_nonlocal_base_attr}, $r_{ij}$ is the distance between\nparticle $i$ and $j$, whereas $\\epsilon_{ij}$ and $\\alpha_{ij}$ are sequence\ndependent parameters.\n\n\\begin{equation}\n  \\label{eq:dna_3spn2c_nonlocal_base_angle_mod}\n  f(K, \\Delta \\theta) =\n  \\begin{cases}\n    1 & \\displaystyle -\\frac{\\pi}{2K} < \\Delta \\theta < \\frac{\\pi}{2K}, \\\\[.7em]\n    1 - \\cos^2(K\\Delta\\theta) & \\displaystyle -\\frac{\\pi}{K} < \\Delta \\theta < -\\frac{\\pi}{2K} \\textrm{ or } \\frac{\\pi}{2K} < \\Delta \\theta < \\frac{\\pi}{K}, \\\\[.7em]\n    0 & \\displaystyle \\Delta \\theta < -\\frac{\\pi}{K} \\textrm{ or }  \\Delta \\theta > \\frac{\\pi}{K}. \\\\\n  \\end{cases}\n\\end{equation}\n\nThe $\\theta$ in \\autoref{eq:dna_3spn2c_nonlocal_base_angle_mod} has\ndifferent definitions in $U_{bstk}$, $U_{bp}$, and $U_{cstk}$.\n\nFor the base-stacking interactions, $\\theta_{BS}$ is the angle formed by\n\\circled{1}-\\circled{2}-\\circled{6}\n(\\autoref{fig:DNA_3spn2c_nonbonded_bstk}).\n\nPractically, we treat the $U_{bstk}$ as a ``local'' potential, because all the\ninteractions can be determined by the topology, regardless of the conformation.\nBesides, the order of magnitude of computational cost of $U_{bstk}$ is only\n$\\mathcal{O}(n)$, where $n$ is the number of basepairs in DNA.\n\n\\begin{figure}[ht]\n  \\centering\n  \\includegraphics[width=0.2\\textwidth]{figures/DNA_3spn2c_nonbonded_bstk.png}\n  \\caption{Definition of $\\theta_{BS}$ in the base-stacking interactions.}\n  \\label{fig:DNA_3spn2c_nonbonded_bstk}\n\\end{figure}\n\n\\begin{smallpage}{3SPN.2C base-stacking potential}<white>\n  \\begin{equation}\n    \\label{eq:dna_3spn2c_nonlocal_base_stacking}\n    U_{bstk} = \\sum^{n_{bstk}} U_m^{rep}(\\epsilon_{BS}, \\alpha_{BS}, r_{ij}) +\n    f(K_{BS}, \\Delta\\theta_{BS})\n    U_m^{attr} (\\epsilon_{BS}, \\alpha_{BS}, r_{ij}).\n  \\end{equation}\n  \\tcblower\n  \\begin{itemize}\n  \\item Particles involved (see \\autoref{fig:DNA_3spn2c_nonbonded_bstk}):\n    \\begin{itemize}\n    \\item $r_{ij}$: \\circled{2}-\\circled{6}\n    \\item $\\theta_{BS}$: \\circled{1}-\\circled{2}-\\circled{6}\n    \\end{itemize}\n  \\item $\\alpha_{BS} = 3.0$.\n  \\item $K_{BS} = 6.0$.\n  \\item $\\epsilon_{BS}$, $r_{ij, 0}$, and $\\theta_{BS, 0}$: see the table below:\n  \\end{itemize}\n  \\begin{center}\n    \\begin{footnotesize}\n      \\begin{tabular}{ll|rrrr|rrrr|rrrr}\n        \\toprule\n        & &  \\multicolumn{12}{c}{\\circled{6}}\\\\\n        & & A & T & G & C & A & T & G & C & A & T & G & C \\\\\n        \\midrule\n        & &  \\multicolumn{4}{c|}{$\\epsilon_{BS}$ (kJ/mol)} & \\multicolumn{4}{c|}{$r_{ij, 0}$ (\\angstrom)} & \\multicolumn{4}{c}{$\\theta_{BS, 0}$ ($^\\circ$)}\\\\\n        \\multirow{4}{*}{\\circled{2}}\n        & A & 13.82 & 15.05 & 13.32 & 15.82 & 3.58 & 3.56 & 3.85 & 3.45 & 100.13 & 90.48 & 104.39 &  93.23  \\\\\n        & T &  9.15 & 12.44 &  9.58 & 13.11 & 4.15 & 3.93 & 4.32 & 3.87 & 102.59 & 93.32 & 103.70 &  94.55  \\\\\n        & G & 13.76 & 14.59 & 14.77 & 15.17 & 3.51 & 3.47 & 3.67 & 3.42 &  95.45 & 87.63 & 106.36 &  83.12  \\\\\n        & C &  9.25 & 12.42 &  8.83 & 14.01 & 4.15 & 3.99 & 4.34 & 3.84 & 102.69 & 96.05 & 100.46 & 100.68 \\\\\n        \\bottomrule\n      \\end{tabular}\n    \\end{footnotesize}\n  \\end{center}\n\\end{smallpage}\n\n\n\n\\subsubsection{Base Pairing and Cross-Stacking}\n\\label{sec:dna_3spn2c_potential_bp_cstk}\n\nIt is convenient to consider the $U_{bp}$ and $U_{cstk}$ potentials at the same\ntime, since $U_{cstk}$ only applies to bases next to the pairsing bases.  There\nare also several angles and dihedral angles involved in the calculation of these\npotentials (\\autoref{fig:DNA_3spn2c_nonbonded_bp_cstk}).\n\n\n\\begin{figure}[ht]\n  \\centering\n  \\includegraphics[width=0.4\\textwidth]{figures/DNA_3spn2c_nonbonded_bp_cstk.png}\n  \\caption{Angles and dihedral angles involved in the $U_{bp}$ (red terms) and\n    $U_{cstk}$ (blue terms) calculations.}\n  \\label{fig:DNA_3spn2c_nonbonded_bp_cstk}\n\\end{figure}\n\nNote that the base pairsing interactions are considered when two bases satisfy\nthe following conditions:\n\\begin{itemize}\n\\item Base types can form Watson-Crick pairs: A-T, T-A, C-G, or G-C;\n\\item Base indices $i$ and $j$ are ``nonlocal'':\n  \\begin{itemize}\n  \\item $i$ and $j$ are in different strands;\n  \\item $i$ and $j$ are in the same strand, but $| i - j | > 10$.\n  \\end{itemize}\n\\end{itemize}\n\n\n\\begin{smallpage}{3SPN.2C base-pairing and cross-stacking potential}<white>\n  \\vspace{-1em}\n  \\begin{align}\n    U_{bp} &= \\sum^{n_{bp}} U_m^{rep}(\\epsilon_{BP}, \\alpha_{BP}, r_{ij}) \\nonumber \\\\\n           &+ \\frac{1}{2} \\big( 1+\\cos(\\Delta \\phi_1) \\big)\n             f(K_{BP}, \\Delta\\theta_{1})\n             f(K_{BP}, \\Delta\\theta_{2})\n             U_m^{attr} (\\epsilon_{BP}, \\alpha_{BP}, r_{ij}).\n             \\label{eq:dna_3spn2c_nonlocal_base_pairing} \\\\[.5em]\n    U_{cstk} &= \\sum^{n_{cstk}} f(K_{BP}, \\Delta\\theta_{3})\n               f(K_{CS}, \\Delta\\theta_{CS})\n               U_m^{attr} (\\epsilon_{CS}, \\alpha_{CS}, r_{kl}).\n               \\label{eq:dna_3spn2c_nonlocal_cross_stacking}\n  \\end{align}\n  \\tcblower\n  \\begin{itemize}\n  \\item Particles involved (see \\autoref{fig:DNA_3spn2c_nonbonded_bp_cstk}):\n    \\begin{itemize}\n    \\item $r_{ij}$: \\circled{2}-\\circled{4}\n    \\item $r_{kl}$: \\circled{2}-\\circled{5} and \\circled{4}-\\circled{6}, if available\n    \\item $\\theta_{1}$: \\circled{1}-\\circled{2}-\\circled{4}\n    \\item $\\theta_{2}$: \\circled{3}-\\circled{4}-\\circled{2}\n    \\item $\\theta_{3}$: angle between vectors conecting \\circled{1}-\\circled{2} and \\circled{3}-\\circled{4}\n    \\item $\\phi_{1}$: dihedral angle \\circled{1}-\\circled{2}-\\circled{4}-\\circled{3}\n    \\item $\\theta_{CS}$: \\circled{1}-\\circled{2}-\\circled{5} or \\circled{3}-\\circled{4}-\\circled{6}\n    \\end{itemize}\n  \\item $\\alpha_{BP} = 2.0$.\n  \\item $K_{BP} = 12.0$.\n  \\item $\\alpha_{CS} = 4.0$.\n  \\item $K_{CS} = 8.0$.\n  \\item All the other parameters are listed in the table below:\n  \\end{itemize}\n  \\begin{center}\n    \\begin{footnotesize}\n      \\begin{tabular}{l|rrrrrr}\n        \\toprule\n        \\circled{2}-\\circled{4} & $\\theta_{1, 0}$ ($^\\circ$) & $\\theta_{2, 0}$  ($^\\circ$) & $\\theta_{3, 0}$  ($^\\circ$) & $\\phi_{1, 0}$  ($^\\circ$) & $r_{ij, 0}$ ($\\angstrom$) & $\\epsilon_{BP}$ (kJ/mol) \\\\\n        \\midrule\n        A-T & 153.17 & 133.51 & 110.92 & -38.18 & 5.82 & 14.41 \\\\\n        T-A & 133.51 & 153.17 & 110.92 & -38.18 & 5.82 & 14.41 \\\\\n        G-C & 159.50 & 138.08 & 120.45 & -35.75 & 5.52 & 18.24 \\\\\n        C-G & 138.08 & 159.50 & 120.45 & -35.75 & 5.52 & 18.24 \\\\\n        \\bottomrule\n      \\end{tabular}\n    \\end{footnotesize}\n  \\end{center}\n\n  \\begin{center}\n    \\begin{footnotesize}\n      \\begin{tabular}{ll|rrrr|rrrr|rrrr}\n        \\toprule\n        & &  \\multicolumn{12}{c}{\\circled{5}}\\\\\n        & & A & T & G & C & A & T & G & C & A & T & G & C \\\\\n        \\midrule\n        & &  \\multicolumn{4}{c|}{$\\epsilon_{CS}$ (kJ/mol)} & \\multicolumn{4}{c|}{$r_{kl, 0}$ (\\angstrom)} & \\multicolumn{4}{c}{$\\theta_{CS, 0}$ ($^\\circ$)}\\\\\n        \\multirow{4}{*}{\\circled{2}}\n        & A & 1.882 & 2.388 & 2.439 & 1.680 & 6.42 & 6.77 & 6.27 & 6.84 & 154.04 & 158.77 & 153.88 & 157.69 \\\\\n        & T & 2.388 & 1.882 & 2.187 & 2.566 & 6.77 & 7.21 & 6.53 & 7.08 & 148.62 & 155.05 & 147.54 & 153.61 \\\\\n        & G & 2.439 & 2.187 & 3.250 & 0.972 & 6.27 & 6.53 & 5.74 & 6.86 & 153.91 & 155.72 & 151.84 & 157.80 \\\\\n        & C & 1.680 & 2.566 & 0.972 & 4.135 & 6.84 & 7.08 & 6.86 & 6.79 & 152.04 & 157.72 & 151.65 & 154.49 \\\\\n        \\bottomrule\n      \\end{tabular}\n    \\end{footnotesize}\n  \\end{center}\n\n  \\begin{center}\n    \\begin{footnotesize}\n      \\begin{tabular}{ll|rrrr|rrrr|rrrr}\n        \\toprule\n        & &  \\multicolumn{12}{c}{\\circled{6}}\\\\\n        & & A & T & G & C & A & T & G & C & A & T & G & C \\\\\n        \\midrule\n        & &  \\multicolumn{4}{c|}{$\\epsilon_{CS}$ (kJ/mol)} & \\multicolumn{4}{c|}{$r_{kl, 0}$ (\\angstrom)} & \\multicolumn{4}{c}{$\\theta_{CS, 0}$ ($^\\circ$)}\\\\\n        \\multirow{4}{*}{\\circled{4}}\n        & A & 1.882 & 2.388 & 2.566 & 2.187 & 5.58 & 6.14 & 5.63 & 6.18 & 116.34 & 119.61 & 115.19 & 120.92 \\\\\n        & T & 2.388 & 1.882 & 1.680 & 2.439 & 6.14 & 6.80 & 6.07 & 6.64 & 107.40 & 110.76 & 106.33 & 111.57 \\\\\n        & G & 2.566 & 1.680 & 4.135 & 0.972 & 5.63 & 6.07 & 5.87 & 5.66 & 121.61 & 124.92 & 120.52 & 124.88 \\\\\n        & C & 2.187 & 2.439 & 0.972 & 3.250 & 6.18 & 6.64 & 5.66 & 6.80 & 112.45 & 115.43 & 110.51 & 115.80 \\\\\n        \\bottomrule\n      \\end{tabular}\n    \\end{footnotesize}\n  \\end{center}\n\\end{smallpage}\n\n\n\n\n\\subsubsection{Excluded-Volume Interactions}\n\\label{sec:dna_3spn2c_potential_exv}\n\n\n\\begin{smallpage}{3SPN.2C excluded volume interaction}<white>\n  \\begin{equation}\n    \\label{eq:dna_3spn2c_nonlocal_exv}\n    U_{exv} = \\sum_{i<j}\n    \\begin{cases}\\displaystyle\n      \\epsilon_r\\bigg[ \\Big(\\frac{\\sigma_{ij}}{r_{ij}} \\Big)^{12} - 2 \\Big(\\frac{\\sigma_{ij}}{r_{ij}} \\Big)^6 \\bigg]+ \\epsilon_r & r_{ij} < \\sigma_{ij},  \\\\\n      0 & r_{ij} > \\sigma_{ij}.\n    \\end{cases}\n  \\end{equation}\n  \\tcblower\n  \\begin{itemize}\n  \\item $i, j$ are all pairs of CG particles that are \\emph{not} in the\n    following list:\n    \\begin{itemize}\n    \\item bonded (involved in bonds, angles, or dihedrals);\n    \\item particles in the neighboring nucleotides;\n    \\item Watson-Crick base pairs.\n    \\end{itemize}\n  \\item $\\epsilon_{r} = 1.0$ kJ/mol.\n  \\item $\\displaystyle \\sigma_{ij} = \\frac{1}{2}\\big( \\sigma_i + \\sigma_j\n    \\big)$, where $\\sigma_i$ ($\\sigma_j$) is listed below:\n  \\end{itemize}\n  \\begin{center}\n    \\begin{tabular}{lc}\n      \\toprule\n      Particle Type    & $\\sigma$ ($\\angstrom$) \\\\\n      \\midrule\n      P  &  4.5 \\\\\n      S  &  6.2 \\\\\n      A  &  5.4 \\\\\n      C  &  6.4 \\\\\n      G  &  4.9 \\\\\n      T  &  7.1 \\\\\n      \\bottomrule\n    \\end{tabular}\n  \\end{center}\n\\end{smallpage}\n\n\n\n\\subsubsection{Electrostatic Interactions}\n\\label{sec:dna_3spn2c_potential_ele}\n\n\n\\begin{smallpage}{3SPN.2C electrostatic interaction}<white>\n  \\begin{equation}\n    \\label{eq:dna_3spn2c_nonlocal_ele}\n    U_{ele} = \\sum_{i<j}^{n_{ele}}\\frac{q_i q_j e^{-r_{ij}/\\lambda_D}}{4\\pi \\epsilon_0 \\epsilon(T, C) r_{ij}}.\n  \\end{equation}\n  \\tcblower\n  \\begin{itemize}\n  \\item Particles involved:\n    \\begin{itemize}\n    \\item all non-neighboring phosphates.\n    \\end{itemize}\n  \\item $q_{i} = -0.6 e_c$.\n  \\item The Debye length $\\displaystyle \\lambda_D = \\sqrt{\\frac{\\epsilon_0 \\epsilon(T, C)}{2\\beta\n        N_A e_c^2 I}}$, where $\\beta=( k_B T )^{-1}$, $N_A$ is Avogadro's\n    number, $I$ is ionic strength, $T$ is temperature, and $C$ is the molarity of NaCl.\n  \\item The solution dieletric permittivity $\\displaystyle \\epsilon(T, C) = \\epsilon(T)a(C)  $, where:\n    \\begin{itemize}\n    \\item $\\epsilon(T) = 249.4 - 0.788T + 7.20\\times10^{-4} T^2 $.\n    \\item $a(C) = 1.000 - 0.2551 C + 5.151\\times10^{-2} C^2 - 6.889\\times 10^{-3} C^3 $.\n    \\end{itemize}\n  \\end{itemize}\n\\end{smallpage}\n", "meta": {"hexsha": "392bfce7defd627c94173b375d7c7848709f0c77", "size": 18969, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/dna.tex", "max_stars_repo_name": "noinil/genesis_cg_document", "max_stars_repo_head_hexsha": "2c128f7d9792d7642f5576254d97792874154f0b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tex/dna.tex", "max_issues_repo_name": "noinil/genesis_cg_document", "max_issues_repo_head_hexsha": "2c128f7d9792d7642f5576254d97792874154f0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/dna.tex", "max_forks_repo_name": "noinil/genesis_cg_document", "max_forks_repo_head_hexsha": "2c128f7d9792d7642f5576254d97792874154f0b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2671905697, "max_line_length": 206, "alphanum_fraction": 0.6123148295, "num_tokens": 7354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.3426129218184735}}
{"text": "% This file describes the general structure of some of our sm_sir models.\n% Note that it is possible to construct models in many different ways using the sm_sir code.\n% Therefore, this description should be used with caution, because it only describes one possible model configuration.\n\n\\section{Model Structure}\n\n\\subsection{General features}\n\nOur COVID-19 model is a series of compartments representing transitions between states relevant to infection with SARS-CoV-2 and onward transmission of this virus.\nUnlike previous iterations of this model (including our past publications on the epidemics in the Philippines \\cite{caldwell-2021-a}, Malaysia \\cite{jayasundara-2021} and Victoria, Australia \\cite{trauer-2021-a}), our current model considers only states relevant to transmission.\nHospitalisation, admission to ICU and death are no longer represented as explicit model states, but are now calculated from model outputs through a convolution process.\nThe rationale for this approach is that the explicitly modelled states are reserved for the representation of processes relevant to epidemic transmission dynamics only.\nAny other relevant outcomes are then calculated from the quantities that are tracked during the process of numerically solving the dynamic system (``derived outputs''), including through convolutions.\nIt should be noted that the process of calculating derived outputs is done after each model iteration, such that these quantities can still be compared to empirically observed outcomes and so used for calibration.\n\n\\subsection{Compartments}\nModel compartments represent sequential progressions through the processes of infection with, progression through and recovery from the phases of SARS-CoV-2.\nReinfection is permitted in our model code structure, which is represented as transition from the recovered compartments back to the first infected compartment.\nThe following compartments are implemented:\n\\begin{itemize}\n    \\item Susceptible\n    \\begin{itemize}\n        \\item Persons never previously infected with SARS-CoV-2 during the model simulation period\n    \\end{itemize}\n    \\item Latent\n    \\begin{itemize}\n        \\item Persons recently infected with SARS-CoV-2, but not yet infectious\n        \\item This phase is divided into two sequential compartments\n    \\end{itemize}\n    \\item Infectious\n    \\begin{itemize}\n        \\item Persons with active COVID-19 who are potentially infectious to others\n        \\item This phase is divided into two sequential compartments\n        \\item The second of these two sequential compartments includes any persons who are identified through the health system and asked to isolate\n        \\item The infectiousness of the second compartment will be reduced to capture the effect of case isolation\n    \\end{itemize}\n    \\item Recovered\n    \\begin{itemize}\n        \\item Persons recovered from COVID-19 during the model simulation period\n        \\item This phase is divided into two sequential compartments\n        \\item Reinfection from these compartments is permitted and occurs at a different rate for the two sequential phases (if the reinfection rate is greater than zero)\n        \\item This compartment retains the stratification by strain (or variant of concern (``VoC'')), with the strain of the last infection episode used for classification\n    \\end{itemize}\n\\end{itemize}\n", "meta": {"hexsha": "18b2b949cee239dd5967140a5a43dc5013f5ec4e", "size": 3353, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/tex/tex_descriptions/models/sm_sir/model_description.tex", "max_stars_repo_name": "emmamcbryde/AuTuMN-1", "max_stars_repo_head_hexsha": "b1e7de15ac6ef6bed95a80efab17f0780ec9ff6f", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/tex/tex_descriptions/models/sm_sir/model_description.tex", "max_issues_repo_name": "emmamcbryde/AuTuMN-1", "max_issues_repo_head_hexsha": "b1e7de15ac6ef6bed95a80efab17f0780ec9ff6f", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/tex/tex_descriptions/models/sm_sir/model_description.tex", "max_forks_repo_name": "emmamcbryde/AuTuMN-1", "max_forks_repo_head_hexsha": "b1e7de15ac6ef6bed95a80efab17f0780ec9ff6f", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 74.5111111111, "max_line_length": 279, "alphanum_fraction": 0.7891440501, "num_tokens": 669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.4765796510636759, "lm_q1q2_score": 0.3424674648677327}}
{"text": "\\section{Event Selection}\n\\label{sec:eventselection}\n\nThe baseline dataset for the lep-had and had-had channels is taken from the \\htt coupling analysis with full Run 2 data, where the event selection is performed level by level. First at preselection level, events are selected by High-level Trigger (HLT) requirements according to the $\\tau$ decay channels (\\taulh and \\tauhh), where HLT is a refined trigger that conducts a very detailed analysis using the data in specific layers or regions of the detector\\footnote{\\url{https://atlas.cern/discover/detector/trigger-daq}}. After preselection, events are categorized by the signal region and control region. \n\nThe MMC is an advanced likelihood-based algorithm taking the unmeasurable mass of neutrinos into account using the missing transverse energy (MET, \\MET)[Elagin:2010aw]. The reconstructed mass \\MMC distribution in \\ditau system peaks at 125 GeV and 82 GeV approximately, corresponding to the mass of Higgs and Z boson respectively (Fig.~\\ref{fig:selection:MMC}). \n\nSignal region (SR) is defined to be in a window in window 110 GeV < \\MMC < 150 GeV to select the Higgs boson produced by vector boson fusion (VBF) and the other three main production modes (ggF, VH and ttH). The VBF category in signal region requires that there are at least two jets with $p_T$> 30 GeV and > 70 GeV respectively. A cut point of BDT (Boost Decision Tree) is set for enhancing the ratio of VBF process over ggF and \\ztt +jets processes, and VBF region is therefore separated into VBF\\_0 (BDT > -0.1) and VBF\\_1 (BDT(VBF) < -0.1) regions. The boost category in SR selects the events that failed the VBF requirements, that is, the events from other three main Higgs production modes. Two boost categories are defined to target topologies where the Higgs boson is recoiling from a jet. The boost tight category is defined by requiring $\\Delta R<= 1.5$ and $p_T(H) >$140GeV. Events failing this criteria are assigned to the boost loose category ($\\Delta R > 1.5$ and $p_T(H) < $140GeV).\n\nControl region for \\ztt (ZCR) selects the events in window 60 GeV < \\MMC < 110 GeV, which is used for extracting the \\ztt normalisation in the fit (ZCR 0), as well as for estimating the \\phistarCP shape uncertainty in \\ztt events (ZCR 1). The preselection, VBF and boost regions for ZCR share the same requirements except with the \\MMC window. \n%\n\\begin{figure}[h!]\n\t\\begin{center}\n\t\t\\begin{tabular}{ccc}\n\t\t\t\\subfigure[hh]{\\includegraphics[width=.3\\textwidth]{plot_ditau_mmc_mlm_m_hh_preselection.pdf}} \\subfigure[lh]{\\includegraphics[width=.3\\textwidth]{plot_ditau_mmc_mlm_m_l1p_preselection.pdf}}\n\t\t\\end{tabular}\n\t\\end{center}\n\t\\caption{MMC distributions in the preselection region in the hadhad and lephad channels.}\n\t\\label{fig:selection:MMC}\n\\end{figure}\n%\n", "meta": {"hexsha": "203506caba78d58073ca60d056fbf97edd48564e", "size": 2788, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "eventselection.tex", "max_stars_repo_name": "beatrice-pan/ResearchProposal_TongPan", "max_stars_repo_head_hexsha": "29b94ac443c04e26301dd351c857ce1abe9780fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "eventselection.tex", "max_issues_repo_name": "beatrice-pan/ResearchProposal_TongPan", "max_issues_repo_head_hexsha": "29b94ac443c04e26301dd351c857ce1abe9780fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eventselection.tex", "max_forks_repo_name": "beatrice-pan/ResearchProposal_TongPan", "max_forks_repo_head_hexsha": "29b94ac443c04e26301dd351c857ce1abe9780fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 126.7272727273, "max_line_length": 997, "alphanum_fraction": 0.775107604, "num_tokens": 753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.34246745912349813}}
{"text": "\\documentclass{beamer}\n\\usepackage{blindtext}\n\\usepackage{graphicx}\n\n\\title[Short Title]{Longer Full Sample Title}\n\\subtitle{Sample Subtitle}\n\\author{Ben Morcos}\n\\date{October 15, 2018}\n\n\\usetheme{SimplePurple}\n\\begin{document}\n\n\t\\frame {\n\t\t\\titlepage\n\t}\n\n\t\\section{First Section}\n\n\t\\frame {\n\t\t\\frametitle{Mathmode}\n\t\tThis is the quadratic equation:\n\t\t\\begin{align}\n\t\t\t\\frac{-b \\pm \\sqrt{b^2 - c}}{2a}\n\t\t\\end{align}\n\t}\n\t\\frame{\n\t\t\\frametitle{Some bullet points}\n\t\t\\framesubtitle{And a list!}\n\t\t\\begin{itemize}\n\t\t\t\\item 1\n\t\t\t\\begin{itemize}\n\t\t\t\t\\item 1.1\n\t\t\t\\end{itemize}\n\t\t\t\\item 2\n\t\t\t\\item 3\n\t\t\\end{itemize}\n\n\t\tText between? \\\\\n\n\t\tWhy not.\n\n\t\t\\begin{enumerate}\n\t\t\t\\item A thing\n\t\t\t\\begin{enumerate}\n\t\t\t\t\\item A related thing\n\t\t\t\t\\item \\alert{An important thing}\n\t\t\t\\end{enumerate}\n\t\t\t\\item Another thing\n\t\t\\end{enumerate}\n\t}\n\n\t\\section{Another Section}\n\n\t\\frame{\n\t    \\frametitle{Paragraph Content}\n\t    \\framesubtitle{Latin is cool}\n\t    \\blindtext\n\t}\n\n\t\\frame{\n\t\t\\frametitle{Figures}\n\t\t\\framesubtitle{With caption}\n\t\t\\begin{figure}\n\t\t\t\\centering\n\t    \t\\includegraphics[height=0.6\\textheight]{example-image}\n\t    \t\\vspace{-10pt}\n\t    \t\\caption{Built in examples are \\alert{\\textbf{genius}}}\n\t    \\end{figure}\n\t}\n\\end{document}\n", "meta": {"hexsha": "8163731b891b4c0c732f34283c2c4f28597b0e72", "size": 1229, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "sample.tex", "max_stars_repo_name": "bmorcos/beamer-SimplePurple", "max_stars_repo_head_hexsha": "a5f3f30c7d7299e8e1da45e3b6673ec4f38d64dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sample.tex", "max_issues_repo_name": "bmorcos/beamer-SimplePurple", "max_issues_repo_head_hexsha": "a5f3f30c7d7299e8e1da45e3b6673ec4f38d64dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sample.tex", "max_forks_repo_name": "bmorcos/beamer-SimplePurple", "max_forks_repo_head_hexsha": "a5f3f30c7d7299e8e1da45e3b6673ec4f38d64dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.3098591549, "max_line_length": 61, "alphanum_fraction": 0.6647681041, "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.34232597557068944}}
{"text": "\\section{The output of the simulator}\n\\label{sec:mskoutput}\n\nAny report produced by the simulator contains the following elements:\n\\begin{itemize}\n\\item General information about the experiment\n\\item Statistics for each selected performance measure\n\\end{itemize}\n\n\\subsection{The contents of a report}\n\nGeneral information includes the names of the parameter files, the\ndate at which the experiment started, the CPU time required to carry\nout the complete simulation, the sample size, etc.  This information\nis presented in the form of one (key: value) pair per line.\nThe main part of the report contains statistics for performance\nmeasures.\n\nSeveral quantities are computed during the simulation: event\ncounts, average times, and integrals.  Each time a call exits\nthe system, counters are updated to keep track of various quantities.\nAll these random variables can be regrouped into a random vector\n$\\boldX=(X_0,\\ldots,X_{d-1})$ we will call\nan \\emph{observation}.  Using some experimental techniques\npresented in section~\\ref{sec:mskexp}, the simulator can obtain $n$\ncopies of $\\boldX$ which is called a \\emph{sample}.  Statistics are\ncomputed by applying some functions on this sample\n$\\boldX_0,\\ldots,\\boldX_{n-1}$, where $\\boldX_r=(X_{0, r}, \\ldots,\nX_{d-1, r})$ is the $r$th observation.\nLet\n\\[\\bar{\\boldX}_n=(\\bar X_{0, n}, \\ldots, \\bar X_{d-1, n})=\\frac1n\\sum_{r=0}^{n-1}\\boldX_r\\]\nthe \\emph{average} of $\\boldX_r$,\nwhich is used to estimate the expected value of $\\boldX$, denoted as\n\\[\\E[\\boldX]=(\\E[X_0], \\ldots, \\E[X_{d-1}]).\\]\nThe vector\n$\\bar{\\boldX}_n$ is an unbiased estimator of $\\E[\\boldX]$ if the\nobservations are independent and identically distributed (i.i.d.).\nWe are also interested in functions $g(\\boldX)$ such as ratios.\nThe function of averages $g(\\bar{\\boldX}_n)$ is used to estimate the\nfunction\nof expectations $g(\\E[\\boldX])$.  This estimator is biased, unless\n$g(\\boldX)$ is a linear function of $\\boldX$.\nSubsection~\\ref{javadoc:umontreal.iro.lecuyer.contactcenters.app.PerformanceMeasureType}\nexplains how these quantities are regrouped in matrices for easier reporting.\n\nFor each performance measure, i.e., element $\\E[X_j]$ or function\n$g(\\E[\\boldX])$, the simulator outputs the following\nstatistics (all statistics are of course undefined when $n=0$):\n\\begin{description}\n\\item[Minimum] The minimal value of $X_j$ among all observations.  No\n  minimum is available for functions of multiple averages.\n\\item[Maximum] The maximal value of $X_j$ among all observations.  No\n  maximum is available for functions of multiple averages.\n\\item[Average] The average $\\bar X_{j, n}$, or function of averages\n  $g(\\bar{\\boldX}_n)$, of the\n  observations.\n\\item[Standard deviation] The sample standard deviation of the observations,\n  i.e., $\\sqrt{\\Var[X_j]}$ or $\\sqrt{n\\Var[g(\\bar{\\boldX}_n)]}$.  This\n  corresponds to the asymptotic standard deviation in the case of a\n  function of several averages.\n  The value is undefined if $n<2$.\n\\item[Confidence interval] An interval $[a, b]$ containing $\\E[X_j]$ (or\n  $g(\\E[\\boldX])$) with probability $1-\\alpha$, where $1-\\alpha$\n  is a \\emph{confidence level} that can be adjusted via a simulation\n  parameter.\n  The interval is computed using the normality assumption.\n  The value is undefined if $n<2$.\n\\end{description}\nUsing the element \\texttt{printed\\-Stat\\-Params} in the parameters of\nthe report, %(see\n%section~\\ref{javadoc:umontreal.iro.lecuyer.contactcenters.app.PrintedStatParams})\none can decide which performance measures appear in the report, and\ndetermine if all the statistics or only the averages are needed.\n\nWe now explain the last two statistics in more details.\nLet\n\\[\n\\boldS_n = \\frac1{n-1}\\sum_{r=0}^{n-1} (\\boldX_r -\n\\bar{\\boldX}_n)^\\tr(\\boldX_r - \\bar{\\boldX}_n),\n\\]\nbe the \\emph{sample covariance} of the $\\boldX_r$'s,\nwhich is used to estimate the covariance matrix\n\\[\\boldSigma = \\E[(\\boldX - \\E[\\boldX])^\\tr(\\boldX - \\E[\\boldX])].\\]\nThe simulator computes only parts of this sample covariance matrix, in\nparticular\nelements $(j, j)$ estimating $\\Var[X_j]=n\\Var[\\bar X_{j, n}]$,\nwhich can be used to estimate the error on $\\bar X_{j,\n  n}$.\n% To estimate the error on $\\bar X_{j, n}$ for $j=0,\\ldots,d-1$, the\n% simulator computes the \\emph{sample variance}\n% \\[S_{X_j, n}^2=\\frac1{n-1}\\sum_{r=0}^{n-1} (X_{j, r} - \\bar X_{j,\n%   n})^2\\]\n% which estimates the variance of the random variate $X_j$, defined as\n% \\[\\Var(X_j)=\\E[X_j^2] - \\E[X_j]^2.\\]\n\nThe sample variance is used to compute a confidence interval on the\ntrue mean $\\E[X_j]$ for any $j\\in\\{0, \\ldots, d-1\\}$.  Assuming that\n$X_{j, r}$ follows the normal distribution,\n\\[\\sqrt{n}(\\bar X_{j, n} - \\E[X_j])/S_{X_j, n}\\]\nfollows the Student-$t$ distribution with $n-1$ degrees of freedom.\nHere, $S_{X_j, n}$ is the sample standard deviation of $X_j$.\nIf the desired probability that this (random)\ninterval covers the true mean $\\E[X_j]$ (a constant) is $1-\\alpha$,\nthe interval is given by $\\bar X_{j, n}\\pm t_{n-1, 1-\\alpha/2}S_{X_j,\n  n}/\\sqrt{n}$, where $t_{n-1,1-\\alpha/2}$ is the inverse of the\nStudent-$t$ distribution function with $n-1$ degrees of freedom,\nevaluated at $1-\\alpha/2$.\n\nConfidence intervals on functions of means are computed\nusing the delta theorem \\cite{tSER80a}.\nHere, we explain the special case of ratios used by the simulator.\nOne can refer to \\cite{tSER80a,sLEC06a,iBUI05b} for the general case.\nLet $(X,Y)$ be a random vector for which the simulator can\ngenerate a sample $((X_0, Y_0), \\ldots, (X_{n-1}, Y_{n-1}))$.  Let\n$\\bar X_n$ be the average for $X$ and $\\bar Y_n$ the average for $Y$;\nthese quantities estimate $\\mu_1=\\E[X]$, and $\\mu_2=\\E[Y]$,\nrespectively.\nThen, the function $\\bar\\nu_n=\\bar X_n/\\bar Y_n$\nestimates the ratio of means $\\nu=\\mu_1/\\mu_2$.  By a Taylor expansion\nof the ratio of averages,\n%if $(\\bar X_n, \\bar Y_n)$ is a multinormal vector,\nthe asymptotic variance of $\\bar X_n/\\bar Y_n$, i.e., the variance\nwhen $n$ is large, is given by $\\sigma^2/n$, where\n\\[\\sigma^2=(\\Var[X] + \\nu^2\\Var[Y] - 2\\nu\\Cov[X, Y])/\\mu_2^2.\\]\nThe variance\n$\\sigma^2$ can be estimated by using sample means, variances and covariance.\n%as follows:\n%\\[\\hat\\sigma_n^2=(S_{X,n}^2+\\bar\\nu_n^2S_{Y,n}^2\n%-2\\bar\\nu_nS_{XY, n})/\\bar Y_n^2\\]\n%where $S_{X, n}$ estimates the variance of $X$, $S_{Y, n}$ estimates\n%the variance of $Y$, and $S_{XY, n}$ estimates the covariance of $X$\n%and $Y$.\n%\\[S_{XY, n}=\\frac1{n-1}\\sum_{r=0}^{n-1} (X_r - \\bar X_n)(Y_r - \\bar\n%Y_n).\\]\n\nAssuming that $(\\bar X_n, \\bar Y_n)$ follows the multinormal\ndistribution,\nthe confidence interval on the ratio of expectations with confidence\nlevel $1-\\alpha$ is given by $\\bar\\nu_n\\pm\nz_{1-\\alpha/2}\\sigma_n/\\sqrt{n}$, where\n$\\Phi(z_{1-\\alpha/2})=1-\\alpha/2$, $\\Phi(x)$ being the distribution\nfunction of a standard normal variable.\n\nNote that each confidence interval is computed for a single mean or\nratio of means, independently of other performance measures of the\nsystem.  As a result, if $d>1$ output values are analyzed\nsimultaneously, the confidence level of the $d$ intervals\nis $1-d\\alpha<1-\\alpha$.\nThe confidence level for individual performance measures must then be\nhigher to get the same overall confidence level.\n\nThe value of $0/0$ is usually undefined and assigned the NaN (Not a Number) flag.\nHowever, in some ratios, $0/0$ can have some meaning.\nIn our simulator, $0/0$ is defined as 0 for most performance measures except service level.\nFor example, if there is no arrival, it is sensible to set the\nabandonment ratio and the average waiting time to 0, and\nthe service level to 1.\n\nFor expectations of ratios, $0/0$ observations are not collected,\nbecause fixing an arbitrary value would result in biased estimators.  As a\nresult, the average is made on less observations, and the average is\nNaN if all observations are rejected.\n\n\\subsection{The format of the report}\n\\label{sec:reportformat}\n\nAt this moment, four file formats are supported for reports:\nXML, plain text, \\LaTeX, and\nMicrosoft Excel.\nThe first format is intended to be readable by programs while\nthe last three formats are human-readable.\n\n\\subsubsection{Program-readable format}\n\nThe XML format is intended to be parsed by Java programs\nusing the ContactCenters library.\nIt could also be parsed and processed by any other program\ncompatible with XML.\nProduced XML output files have root element\n\\texttt{Contact\\-Center\\-Sim\\-Results}, in\nnamespace URI\n\\path{http://www.iro.umontreal.ca/lecuyer/contactcenters/app}.\nThe XML schema for output files can be found in the \\texttt{schemas}\nsubdirectory of ContactCenters, and HTML documentation is available\nin \\path{doc/schemas}.\n%The binary format, using Java\n%serialization, may be faster to read, but the XML format may be\n%more easily\n%reusable by other programs not using ContactCenters, even not using\n%Java.\n\nAlternatively, the program can export to a XML file\nand compress the file using GZip to save\ndisk space.\nThis can be done by giving a file name with the \\texttt{.xml.gz}\nextension rather than \\texttt{.xml}.\n\n\\subsubsection{Plain text}\n\nWhen exporting to plain text, the simulator uses the\nplatform-default character encoding and line separator.\nAs a result, the created text file can be opened in any text editor\nsuch as Notepad, GNU Emacs, etc.\nAfter the general information, the report contains a table of summary\nresults, e.g., the performance measures concerning every call type,\nagent group, and period.  Then, for each group of performance\nmeasures, a table of detailed results appear in the report.\nNote that the formatting of numbers is locale-specific.  For example,\nif the current locale is set to French, the decimal separator\nis the comma while the separator is a period for the US locale.\n\nThe \\LaTeX\\ output, which is also plain text but with formatting\ninstructions,\nis intended to be processed by \\LaTeX\\ to generate printable tables of\nresults.\n\n\\subsubsection{Microsoft Excel}\n\nThe Microsoft Excel format is used to transfer results to spreadsheets\nfor further analysis and reporting.\nOne is not restricted to Microsoft Excel since\nmany other spreadsheets, e.g., OpenOffice.org and KOffice,\ncan read and write Excel files.\n\nThe Excel report is divided in at most three sheets.\nThe first sheet provides summary information only: the general\ninformation, and summary statistics, i.e., statistics for aggregate\nperformance measures.\nThe latter are split in two groups: source-related (or call-related)\nstatistics and destination-related (agent-related and waiting\nqueue-related) statistics.\nThe second sheet provides a detailed report for all time-aggregate\nperformance measures.  This includes, e.g., the service level for\neach individual call type but not for each period.\nThe last sheet contains a detailed report for all performance\nmeasures, including statistics for individual periods.\n\n\\subsubsection{Localized format for reports}\n\nSome aspects of the reports produced by \\texttt{mskcallcentersim}\ndepend on the host environment of the JVM.\nThese aspects include the character encoding of the report,\nthe line delimiters, strings describing types of performance measures,\nand the format of the numbers.\nThe last two elements are influenced by the locale of the virtual\nmachine which executes the simulator, which corresponds to the default\nlocale of the host environment.\nAt this moment, only English and French are supported as languages for\nreports. If the current locale corresponds to another language,\nall text in the report will be in English, with locale-specific\nformatting for numbers.\n\nSome of these aspects can be customized using OS-specific options.\nFor example, calling \\texttt{LC\\_ALL=en\\_US.UTF-8 mskcallcentersim}\nlaunches the simulator with the US English locale, and UTF-8 encoding;\nthis is the default for most UNIX/Linux distributions.\nHowever, on other operating systems, such as Microsoft's Windows,\nthere is no built-in way to alter the default locale for a given\nprogram without changing the system-wide regional settings.\nHowever, Java properties can be changed to alter the default locale,\nand other parameters, in a platform-independent way.\nTable~\\ref{tab:repjavaprop} lists such properties.\nThe properties can be modified through the \\texttt{-D} JVM option.\nFor example, setting the \\texttt{CCJVMOPT} environment variable\nto \\texttt{-Duser.language=en} sets the language of reports to\nEnglish.\n\n\\begin{table}\n\\caption{Most common Java properties affecting reporting}\n\\label{tab:repjavaprop}\n\n\\centering\\begin{tabular}{|l|ll|}\\hline\nProperty & Action & Sample value \\\\ \\hline\n\\texttt{user.language} & Language of strings in reports & \\texttt{en}\n\\\\\n\\texttt{user.region} & Region affecting number and date format &\n\\texttt{US} \\\\\n\\texttt{file.encoding}  & Character encoding for reports &\n\\texttt{UTF-8} \\\\\n\\hline\n\\end{tabular}\n\\end{table}\n", "meta": {"hexsha": "168b17ea1889433be19dba461863415235399d73", "size": 12799, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/msk/mskoutput.tex", "max_stars_repo_name": "umontreal-simul/contactcenters", "max_stars_repo_head_hexsha": "f5ddb4a0a4b30dbf436ac36e6d97facce2f3576d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/msk/mskoutput.tex", "max_issues_repo_name": "umontreal-simul/contactcenters", "max_issues_repo_head_hexsha": "f5ddb4a0a4b30dbf436ac36e6d97facce2f3576d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/msk/mskoutput.tex", "max_forks_repo_name": "umontreal-simul/contactcenters", "max_forks_repo_head_hexsha": "f5ddb4a0a4b30dbf436ac36e6d97facce2f3576d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.2261484099, "max_line_length": 91, "alphanum_fraction": 0.7541214157, "num_tokens": 3485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.34232597557068944}}
{"text": "% Created 2021-07-06 Tue 08:01\n% Intended LaTeX compiler: pdflatex\n\\documentclass[presentation,aspectratio=169]{beamer}\n\\usepackage[utf8]{inputenc}\n\\usepackage[T1]{fontenc}\n\\usepackage{graphicx}\n\\usepackage{grffile}\n\\usepackage{longtable}\n\\usepackage{wrapfig}\n\\usepackage{rotating}\n\\usepackage[normalem]{ulem}\n\\usepackage{amsmath}\n\\usepackage{textcomp}\n\\usepackage{amssymb}\n\\usepackage{capt-of}\n\\usepackage{hyperref}\n\\usepackage{khpreamble}\n\\usepackage{amssymb}\n\\DeclareMathOperator{\\shift}{q}\n\\DeclareMathOperator{\\diff}{p}\n\\usetheme{default}\n\\author{Kjartan Halvorsen}\n\\date{2019-09-05}\n\\title{Computerized Control - analysis of discrete-time systems}\n\\hypersetup{\n pdfauthor={Kjartan Halvorsen},\n pdftitle={Computerized Control - analysis of discrete-time systems},\n pdfkeywords={},\n pdfsubject={},\n pdfcreator={Emacs 26.3 (Org mode 9.4.6)}, \n pdflang={English}}\n\\begin{document}\n\n\\maketitle\n\n\\section{Intro}\n\\label{sec:org06d2c71}\n\\begin{frame}[label={sec:org53fc2d8}]{Result from quizz}\n\\begin{itemize}\n\\item Very good results!\n\\item Nyquist plot + criterion\n\\item Robustness\n\\end{itemize}\n\\end{frame}\n\\section{Pole placement}\n\\label{sec:orgc540c2c}\n\\begin{frame}[label={sec:org88d54f5}]{Pole-placement and time-response}\nPair the pole-placement with the correct time-response (from HW1)\n\\begin{columns}\n\\begin{column}{0.4\\columnwidth}\n\\begin{center}\n\\includegraphics[width=\\linewidth]{../../figures/pzmap-apollo}\n\\end{center}\n\\end{column}\n\\begin{column}{0.6\\columnwidth}\n\\begin{center}\n\\includegraphics[width=\\linewidth]{../../figures/step-response-apollo}\n\\end{center}\n\\end{column}\n\\end{columns}\n\\end{frame}\n\n\\begin{frame}[label={sec:org75a559f}]{Mapping of poles from continuous time to discrete time}\n\\begin{center}\n\\begin{tabular}{ll}\nContinuous time & Discrete time\\\\\n\\hline\n\\(Y(s) \\triangleq \\laplace{y(t)}\\) & \\(Y(z) \\triangleq \\ztrf{y(kh)}\\)\\\\\n\\(Y(s) = G(s)U(s) = \\frac{b}{s+a}U(s)\\) & \\(Y(z) = H(z)U(z) = \\frac{\\beta}{z+\\alpha}U(z)\\)\\\\\nPole of the system: \\(s+a=0 \\; \\Rightarrow \\; s = -a\\) & Pole of the system: \\(z+\\alpha = 0 \\; \\Rightarrow \\; z = -\\alpha\\)\\\\\n\\includegraphics[width=0.22\\linewidth]{../../figures/cont-stable} & \\includegraphics[width=0.22\\linewidth]{../../figures/discrete-stable}\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\nThe \\alert{s-domain} of continuous-time systems is related to the \\alert{z-domain} of discrete-time systems as  \\[z = \\mathrm{e}^{sh}\\]\n\\end{frame}\n\n\\begin{frame}[label={sec:org4177f6b}]{Mapping of poles from continuous time to discrete time}\nDo excercise on paper!\n\\end{frame}\n\n\\section{Root locus}\n\\label{sec:org1da210f}\n\n\n\\begin{frame}[label={sec:org2d36761}]{Root locus: A brief review}\n\\begin{LaTeX}\n\\begin{center}\n  \\begin{tikzpicture}[node distance=22mm, block/.style={rectangle, draw, minimum width=15mm}, sumnode/.style={circle, draw, inner sep=2pt}]\n\n    \\node[coordinate] (input) {};\n    \\node[sumnode, right of=input, node distance=16mm] (sum) {\\tiny $\\Sigma$};\n    \\node[block, right of=sum, node distance=20mm] (plant)  {$H(z)=\\frac{B(z)}{A(z)}$};\n    \\node[block, below of=plant, node distance=12mm] (controller)  {$F(z)=K\\frac{D(z)}{C(z)}$};\n    \\node[coordinate, right of=plant, node distance=30mm] (output) {};\n\n    \\draw[->] (input) -- node[above, pos=0.3] {} (sum);\n    \\draw[->] (sum) -- node[above] {} (plant);\n    \\draw[->] (plant) -- node[coordinate] (measure) {} node[above, near end] {} (output);\n    \\draw[->] (measure) |- (controller);\n    \\draw[->] (controller) -| (sum);\n  \\end{tikzpicture}\n\\end{center}\n\\end{LaTeX}\n\n\\begin{itemize}\n\\item The loop pulse-transfer function (loop gain) becomes \\(L(z) = H(z)F(z) = K\\frac{\\overbrace{B(z)D(z)}^{Q(z)}}{\\underbrace{A(z)C(z)}_{P(z)}} = K \\frac{Q(z)}{P(z)}\\).\n\\item The roots of \\(Q(z)\\) are called the \\alert{open loop zeros}.\n\\item The roots of \\(P(z)\\) are called the \\alert{open loop poles}.\n\\item The characteristic equation for the closed-loop system is \\[ 1 + K\\frac{Q(z)}{P(z)} = 0 \\quad \\Leftrightarrow \\quad P(z) + KQ(z) = 0\\]\n\\end{itemize}\n\\end{frame}\n\n\n\\begin{frame}[label={sec:org0e0a1d3}]{Root locus: Definition}\nLet\n\\[\\begin{cases} P(z)&=z^n+a_1z^{n-1}+\\dots+a_n = (z-p_1)(z-p_2)\\cdots(z-p_n)\\\\ \nQ(z)&=z^m+b_1 z^{m-1}+\\dots+b_m=(s-q_1)(z-q_2)\\cdots(z-q_m) \\end{cases},\\ \\ \\ n\\ge m \\]\n\nThe root locus shows how the \\alert{solution} to the characteristic equation\n\\begin{equation}\n\\label{eq:P(z)+KQ(z)=0}\nP(z)+K\\cdot Q(z)=0,\\ \\ \\ 0\\le K<\\infty\n\\end{equation}\ndepend on the parameter \\(K\\). The root locus consists of the set of all points in the complex plane that are solutions to \\eqref{eq:P(z)+KQ(z)=0} for some non-negative value of \\(K\\).\n\\end{frame}\n\n\\begin{frame}[label={sec:org1e38a16}]{Root locus: Characteristics}\n\\begin{description}\n\\item[{Start points}] The \\(n\\) roots of \\(P(z)\\), marked by crosses\n\\item[{End points}] The \\(m\\) roots of \\(Q(z)\\), marked  by circles\n\\item[{Asymptotes}] Number equal to the \\emph{pole excess} \\(n-m\\)\n\\item[{Real axis}] Some segments of the real axis belong to the root locus\n\\end{description}\n\\end{frame}\n\n\\begin{frame}[label={sec:org4d84931}]{Root locus: Direction of the asymptotes}\nThe characteristic equation \\(P(z)+K Q(z)=0\\) can be written \\(\\frac{P(z)}{Q(z)} = -K\\) and for large \\(z\\) it can be approximated as \n\\[ \\frac{z^n}{z^m} = -K \\quad \\Leftrightarrow \\quad z^{n-m} = -K.\\]\n\nTaking the argument of both sides of the equation gives \n\\((n-m)\\arg z = \\pi + k2\\pi, \\; k \\in  \\mathbb{Z}\\)\nSo, the \\alert{directions} of the asymptotes are given by the expression\n\\[ \\theta_k = \\arg z = \\frac{(2k+1)\\pi}{n-m}, \\; k \\in \\mathbb{Z} \\]\n\\end{frame}\n\n\\begin{frame}[label={sec:orgd3d871c}]{Root locus: The asymptotes' intersection with the real axis}\n\\[ z_{ip} = \\frac{ \\sum_{i=0}^n p_i - \\sum_{i=0}^m q_i}{n-m}, \\]\nwhere \\(\\{p_i\\}\\) are the starting points (open-loop poles) and \\(\\{q_i\\}\\) are the end points (open-loop zeros). \n\\end{frame}\n\n\\begin{frame}[label={sec:org7ea8274}]{Root locus exerise: Pair the pulse-trf fcn and root locus}\n\\begin{columns}\n\\begin{column}{0.35\\columnwidth}\n\\begin{LaTeX}\n\\small\n\\begin{align*}\n  G_1(z) &= K\\frac{(z+2.9)(z+0.2)}{(z-1)^2(z-0.3)}\\\\[3mm]\n  G_2(z) &= K\\frac{(z-0.5)(z+0.4)}{(z-1)(z-0.3)(z-0.1)}\\\\[3mm]\n  G_3(z) &= K\\frac{(z-0.5)(z+0.8)}{(z-1)^2(z-0.3)}\\\\[3mm]\n  G_4(z) &= K \\frac{z-0.6}{(z-1)(z-0.3)}\n\\end{align*}\n\\end{LaTeX}\n\\end{column}\n\n\\begin{column}{0.65\\columnwidth}\n\\begin{center}\n\\includegraphics[width=1.04\\linewidth]{../../matlab/rlocus_2x2-crop}\n\\end{center}\n\\end{column}\n\\end{columns}\n\\end{frame}\n\n\n\\begin{frame}[label={sec:orgaba0adc}]{Draw a root locus}\nLevel control in a hydro power plant dam\n\n\\begin{center}\n\\small\n\\def\\svgwidth{0.5\\linewidth}\n\\input{hydroplant.pdf_tex}\n\\end{center}\n\nDiscrete-time model: \\(y(k+1) - y(k) = \\frac{h}{A} u(k) + \\frac{h}{A}v(k)\\), where \\(y(k)\\) is the deviation in water level from a standard level, \\(u(k)\\) is the (negative) deviation in flow through the dam ports and \\(v(k)\\) is a deviation in other flows (disturbance). \n\\end{frame}\n\n\\begin{frame}[label={sec:org0713314}]{What happens if the poles are \\alert{on the} unit circle?}\nSay, in \\(z = \\mathrm{e}^{\\pm i \\omega_0}\\)\n\\begin{center}\n\\includegraphics[width=0.3\\linewidth]{../../figures/rlocusA.png}\n\\end{center}\n\n\\[H_c(z) = \\frac{k z}{(z-\\mathrm{e}^{i \\omega_0})(z-\\mathrm{e}^{-i \\omega_0})} \\overbrace{+ \\cdots}^{\\text{stable term}}\\].\n\\end{frame}\n\n\\begin{frame}[label={sec:orgb1ee06f}]{What happens if the poles are \\alert{on the} unit circle?}\nSay, in \\(z = \\mathrm{e}^{\\pm i \\omega_0}\\)\n\\begin{center}\n\\includegraphics[width=0.3\\linewidth]{../../figures/rlocusA.png}\n\\includegraphics[height=0.34\\textheight]{../../figures/zgrid-crop}\\\\\n\\end{center}\n\n\\begin{align*}\nH_c(z) &= \\frac{k z}{(z-\\mathrm{e}^{i \\omega_0})(z-\\mathrm{e}^{-i \\omega_0})} + \\cdots\\\\\n       &= \\frac{k z}{z^2 -2\\cos\\omega_0 z + 1} + \\cdots\n\\end{align*}\n\nIf \\(\\omega_0 = \\frac{\\pi}{6}\\) and the sampling period is \\unit{0.4}{\\second}, what is the \\alert{frequency} (in \\unit{}{\\radian\\per\\second} and in Hz) of the oscillations in the pulse response?\n\\end{frame}\n\n\\section{Bode diagrams and Nyquist plots}\n\\label{sec:org25d4b12}\n\\begin{frame}[label={sec:org291269e}]{Bode diagram and Nyquist plots}\n\\end{frame}\n\n\\begin{frame}[label={sec:orgfc87a48}]{Sine in --- sine out}\n\\begin{LaTeX}\n\\begin{center}\n  \\begin{tikzpicture}[node distance=22mm, block/.style={rectangle, draw, minimum width=15mm}, sumnode/.style={circle, draw, inner sep=2pt}]\n\n    \\node[coordinate] (input) {};\n    \\node[block, right of=sum, node distance=25mm] (plant)  {$H(z)$};\n    \\node[coordinate, right of=plant, node distance=40mm] (output) {};\n\n    \\draw[->] (input) -- node[above, pos=0.3] {$u(kh) = \\sin(\\omega kh)$} (plant);\n    \\draw[->] (plant) -- node [above, pos=1.1] {$y(kh) = |H(\\mathrm{e}^{i\\omega h})|\\sin(\\omega kh + \\arg H(\\mathrm{e}^{i\\omega h}))$} (output);\n  \\end{tikzpicture}\n\\end{center}\n\\end{LaTeX}\n\\end{frame}\n\\begin{frame}[label={sec:orgceaa23e}]{Sine in --- sine out}\n\\begin{LaTeX}\n\\begin{center}\n  \\begin{tikzpicture}[node distance=22mm, block/.style={rectangle, draw, minimum width=15mm}, sumnode/.style={circle, draw, inner sep=2pt}]\n\n    \\node[coordinate] (input) {};\n    \\node[block, right of=sum, node distance=25mm] (plant)  {$H(z)$};\n    \\node[coordinate, right of=plant, node distance=40mm] (output) {};\n\n    \\draw[->] (input) -- node[above, pos=0.3] {$u(kh) = \\sin(\\omega kh)$} (plant);\n    \\draw[->] (plant) -- node [above, pos=1.1] {$y(kh) = |H(\\mathrm{e}^{i\\omega h})|\\sin(\\omega kh + \\arg H(\\mathrm{e}^{i\\omega h}))$} (output);\n  \\end{tikzpicture}\n\\end{center}\n\\end{LaTeX}\n\\alert{Prove it!} Some hints:\n\\begin{itemize}\n\\item Write \\(\\sin(\\omega kh) = \\mathrm{Im}\\{\\mathrm{e}^{i\\omega kh}\\}\\).\n\\item Use \\(H(z)U(z) \\stackrel{\\mathcal{Z}}{\\leftrightarrow} h(k)\\ast u(k)\\), and write out the discrete-time convolution \\(h \\ast u = \\sum_{n=-\\infty}^\\infty h(n)u(k-n) = \\sum_{n=0}^\\infty h(n)u(k-n)\\)\n\\item Try to rewrite to obtain as a factor \\(\\sum_{n=0}^\\infty h(n) \\mathrm{e}^{-i\\omega nh} = H(\\mathrm{e}^{i\\omega h})\\).\n\\end{itemize}\n\\end{frame}\n\n\n\\section{Relative stability}\n\\label{sec:org218756b}\n\n\\begin{frame}[label={sec:orgfe84823}]{The Nyquist plot}\nExample of a \\alert{Nyquist plot} or \\alert{frequency curve}.\n\\begin{LaTeX}\n\\begin{center}\n  \\begin{tikzpicture}\n    \\node at (0,0) {\\includegraphics[width=0.4\\linewidth]{../../figures/fig3-3.png}};\n    \\node[pin=120:{$H(z)$ evaluated at $z=\\mathrm{e}^{i\\omega h}$, $0<\\omega<\\frac{\\pi}{h}$}] at (-1,1) {};\n    \\node[pin=40:{$G(s)$ evaluated at $s=i\\omega$, $0<\\omega<\\infty$}] at (-0.98,0.4) {};\n  \\end{tikzpicture}\n\\end{center}\n\\end{LaTeX}\n\n\n\nThe system \\(G(s) = \\frac{1}{s^2 + 1.4s + 1}\\) is sampled with ZOH-sampling (\\(h=\\unit{0.4}{\\second}\\)) to get \\(H(z) = \\frac{0.066z + 0.055}{z^2 - 1.45 z + 0.571}\\)\n\\end{frame}\n\n\\begin{frame}[label={sec:orgbad54b5}]{Simplified Nyquist criterion}\n\\begin{center}\n\\includegraphics[width=0.4\\linewidth]{../../figures/fig3-3.png}\n\\end{center}\n\nConsider the loop pulse-transfer function \\(L(z)\\) of a closed-loop system. If \\(L(z)\\) is stable (no poles outside the unit circle), then the closed-loop system with characteristic equation \\(1 + L(z) = 0\\) will be stable iff \\(L(z)\\) evaluated on the unit circle (i.e, the Nyquist plot of \\(L\\)) has the point \\alert{-1 to the left}.\n\\end{frame}\n\n\\begin{frame}[label={sec:org75821a8}]{Stability margins - phase margin}\n\\begin{center}\n\\includegraphics[width=0.38\\linewidth]{../../figures/implane-nyquist-margins}\n\\end{center}\n\\begin{itemize}\n\\item Cross-over frequency: The frequency \\(\\omega_c\\) for which \\(|L(\\mathrm{e}^{i\\omega h})| = 1\\).\n\\item Phase margin: The angle \\(\\varphi_m\\) to the negative real axis for the point where the Nyquist curve intersects the unit circle. \\[\\varphi_m = \\arg L(\\mathrm{e}^{i\\omega_c h}) - (-180\\degree) = \\arg L(\\mathrm{e}^{i\\omega_c h}) + 180\\degree\\]\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}[label={sec:orgb16d58a}]{Stability margins - gain margin}\n\\begin{center}\n\\includegraphics[width=0.34\\linewidth]{../../figures/implane-nyquist-margins}\n\\end{center}\n\\begin{itemize}\n\\item phase-cross-over frequency: The frequency \\(\\omega_p\\) for which \\(\\arg L(\\mathrm{e}^{i\\omega h}) = -180\\degree\\).\n\\item Gain margin: The gain \\(K=A\\) that would make the Nyquist curve of \\(K L(\\mathrm{e}^{i\\omega h})\\) go through the point \\(-1 + i0\\). This means that \\[ |L(\\mathrm{e}^{i\\omega_p h})| = \\frac{1}{A}. \\]\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}[label={sec:orge210cb8}]{The relationship between Bode diagrams and frequency curves (Nyquist plots)}\nThey are both showing the value of a pulse-transfer function \\(H(z)\\) evaluated for \\(z = \\mathrm{e}^{i\\omega h}\\), \\(0<\\omega \\le \\frac{\\pi}{h}\\).\n\n\\begin{center}\n\\includegraphics[width=\\linewidth]{../../figures/fig3-3-4.png}\n\\end{center}\n\\end{frame}\n\\end{document}", "meta": {"hexsha": "b0eb3bf682f881313462642ae602eadd42a67ec6", "size": 12715, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "discrete-time-systems/slides/discrete-time-sys-analysis.tex", "max_stars_repo_name": "kjartan-at-tec/mr2007-computerized-control", "max_stars_repo_head_hexsha": "16e35f5007f53870eaf344eea1165507505ab4aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-11-07T05:20:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-22T09:46:13.000Z", "max_issues_repo_path": "discrete-time-systems/slides/discrete-time-sys-analysis.tex", "max_issues_repo_name": "kjartan-at-tec/mr2007-computerized-control", "max_issues_repo_head_hexsha": "16e35f5007f53870eaf344eea1165507505ab4aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-06-12T20:44:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-12T20:49:00.000Z", "max_forks_repo_path": "discrete-time-systems/slides/discrete-time-sys-analysis.tex", "max_forks_repo_name": "kjartan-at-tec/mr2007-computerized-control", "max_forks_repo_head_hexsha": "16e35f5007f53870eaf344eea1165507505ab4aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-14T03:55:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-14T03:55:27.000Z", "avg_line_length": 41.0161290323, "max_line_length": 335, "alphanum_fraction": 0.6675580024, "num_tokens": 4594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.34232597557068944}}
{"text": "%!TEX root = /home/renaud/Documents/EPL/tfe/latex/tfe.tex\n\\chapter{From clusters to compartments: the method} \\label{chap:method}\nIn this chapter, we formalize the method used to go from the numerical implementation of the particle trajectories to the clustering allowing to delineate the compartments in a box model. In other words, it is explained how to use a clustering algorithm on an advection-diffusion problem, and then how to choose which communities found by the stability method to use as compartments in a box model. \n\nThe underpinning idea of the method is that communities found on the dynamic of the flow could be relevant compartments for the box model. The idea makes sense although it is far from being obvious that the communities are indeed the compartments that we seek. In a first instance, we should only check that, at least in some cases, community detection leads to relevant partitions. In the next chapter, a test problem is build for which we know in advances what compartments to expect, and the method is tested on that problem.\n%Then we apply the method on the less obvious, though still very naive overturner model of the Atlantic ocean.\n\n\\paragraph{Remark} \\label{remark:straightboundaries} In the context of interpreting the communities as compartments for a box model, we should require that the communities have vertical and horizontal boundaries. For example, when dealing with marine problems, the goal of a box model is to provide a simple and intuitive description of the problem. Complex shaped compartments are neither simple nor intuitive for marine models, hence the requirement.\n\n\\input{inputs/method/generalmethod}\n% \\input{inputs/method/overturner_clustering}\n", "meta": {"hexsha": "381ba7a49f02d9ad179f455c61cabd31f03cb119", "size": 1708, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "inputs/method/method.tex", "max_stars_repo_name": "dufaysr/tfe", "max_stars_repo_head_hexsha": "75c6191e1533da84233d4a38dea3cc3f3884a286", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inputs/method/method.tex", "max_issues_repo_name": "dufaysr/tfe", "max_issues_repo_head_hexsha": "75c6191e1533da84233d4a38dea3cc3f3884a286", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inputs/method/method.tex", "max_forks_repo_name": "dufaysr/tfe", "max_forks_repo_head_hexsha": "75c6191e1533da84233d4a38dea3cc3f3884a286", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 142.3333333333, "max_line_length": 528, "alphanum_fraction": 0.8120608899, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3423230803052945}}
{"text": "%\\chapter{Advanced Techniques V:  Ferns-based miniKanren}\\label{fernschapter}\n\\chapter{Techniques IV:  Ferns}\\label{fernschapter}\n\nIn this chapter we provide a bottom-avoiding generalization of core\nminiKanren using \\emph{ferns} \\cite{ferns81}, a shareable data\nstructure designed to avoid divergence.\n\nThe chapter is organized as follows. Section~\\ref{fernsintro}\nintroduces the ferns data structure and shows examples of familiar\nrecursive functions using ferns.  Section~\\ref{Sharing} describes the\npromotion algorithm \\cite{Friedman79b} that characterizes the\nnecessary sharing properties of ferns.  Section~\\ref{lp-system}\ndefines bottom-avoiding logic programming goal constructors,\ncorresponding to core miniKanren with non-interleaving search.\nChapter~\\ref{fernsimpl} presents a complete \\emph{shallow\n  embedding} \\cite{Boulton92tassel.experience} of the ferns data\nstructure and related operators.\n\n\\section{Introduction to Ferns}\\label{fernsintro}\n\nFerns are constructed with \\scheme|cons| and \\scheme|frons|,\noriginally called \\textbf{frons} \\cite{DFried80}, and accessed by\n\\scheme|fcar| and \\scheme|fcdr|, generalizations of \\scheme|car| and\n\\scheme|cdr|, respectively.  Ferns built with \\scheme|frons| are like\nstreams in that the \\emph{evaluation} of elements is delayed,\npermitting unbounded data structures.  In contrast to streams, the\n\\emph{ordering} of elements is also delayed: convergent values form\nthe prefix in some unspecified order, while divergent values form the\nsuffix.\n\nWe begin with several examples that illustrate the\nproperties of ferns, showing their similarities to\nand differences from traditional lists and streams.  Later, we include\nexamples that show that a natural recursive style can be used when\nprogramming with ferns and point out the advantages ferns afford the\nuser.\n\n\\subsection{Two Simple Programs}\n\nConvergent elements of a fern form its prefix in some unspecified\norder. For example, evaluating the expression\n\n\\schemedisplayspace\n\\schemeinput{fernscode/intro-1}\n\n\\noindent \nprints either \\schemeresult|010| or \\schemeresult|101|,\ndemonstrating that the order of values within a fern is not specified in\nadvance but remains consistent once determined, while\n\n\\schemedisplayspace\n\\schemeinput{fernscode/intro-2}\n\n\\noindent returns \\mbox{\\schemeresult|(720 . 120)|}, demonstrating\nthat accessing a fern avoids divergence as much as possible.\n(\\scheme|bottom| is any expression whose evaluation diverges.)  In the\nlatter example, each fern contains only one convergent value; taking\nthe \\scheme|fcdr| of \\scheme|s1| or the \\scheme|fcadr| of \\scheme|s2|\nresults in divergence.\n\nFerns are \\emph{shareable} data structures; sharing, combined with\ndelayed ordering of values, can result in surprising behavior.  For\nexample, consider these expressions:\n\n\\schemedisplayspace\n\\schemeinput{fernscode/not-so-weird-sharing}\n\n\\noindent and\n\n\n\\schemedisplayspace\n\\schemeinput{fernscode/weird-sharing-1}\n\n\\noindent\nThe first expression must evaluate to \\mbox{\\schemeresult|(1 2\n  2)|}.  The second expression may also return this value---as\nexpected, the car of \\scheme|b| would then be equal to the cadr of\n\\scheme|a|.  The second expression might instead return\n\\mbox{\\schemeresult|(2 1 2)|} however; in this case, the car of \\scheme|b|\nwould be equal to the car of \\scheme|a| rather than to its cadr.\nSection~\\ref{Sharing} discusses sharing in detail.\n\n\\subsection{Recursion}\\label{fernsRecursiveExamples}\n\nWe now present examples of the use of ferns in simple recursive\nfunctions. Consider the definition of \\scheme|ints-bottom|\\footnote{\\scheme|timed-lambda| is identical to\n  \\scheme|lambda|, except it creates preemptible procedures. \n(See Appendix~\\ref{nestable-engines}.)}.\n\n\\schemedisplayspace\n\\schemeinput{fernscode/ints}\n\n\\noindent Then \\mbox{\\scheme|(fcaddr (ints-bottom 0))|} \ncould return any non-negative integer, whereas a\nstream version would return \\schemeresult|2|.\n\n%But wait---there's more!\n\n% \\schemedisplayspace\n%\\schemeinput{fernscode/code/ints-bottom}\n\nThere is a tight relationship between ferns and lists, since every\ncons pair is a fern.  The empty\nfern is also represented by \\scheme|`()|, and\n\\mbox{\\scheme|(pair? (frons e1 e2))|} returns \\schemeresult|#t| for\nall \\scheme|e1| and \\scheme|e2|.  After replacing the list constructor\n\\scheme|cons| with the fern constructor \\scheme|frons|, many recursive\nfunctions operating on lists avoid divergence.  For example,\n\\scheme|map-bottom| is defined\nby replacing \\scheme|cons| with \\scheme|frons|, \\scheme|car| with\n\\scheme|fcar|, and \\scheme|cdr| with \\scheme|fcdr| in the definition of\n\\scheme|map|, and can map a function over an unbounded fern:\n% inlined this from code/map-example.ss\nthe value of \\mbox{\\scheme|(fcaddr (map-bottom add1 (ints-bottom 0)))|} can be any positive integer.\n\n\n%The similarities between ferns and the more traditional list and\n%stream data structures make it possible to write bottom-avoiding\n%functions in the natural recursive style---indeed, this ability to\n%define functions in a familiar style is one of the advantages of using\n%ferns.\n\nFerns work especially well with \\emph{annihilators}. True values are\nannihilators for \\scheme|or-bottom|\n\n\\schemedisplayspace\n\\schemeinput{fernscode/or-fn}\n\n\\noindent which searches in a fern for a true convergent value\nand avoids divergence if it finds one:\n\\mbox{\\scheme|(or-bottom (fern bottom (odd? 1) (! 5) bottom (odd? 0)))|}\nreturns some true value, where \\scheme|fern| is defined as follows.\n\n\\schemedisplayspace\n\\schemeinput{fernscode/fern}\n\n% We get additional benefit when annihilators are common. Scheme's\n% \\scheme|or|, for example, uses any true value as an annihilator. We\n% can define \\scheme|or-bottom|, similar to \\scheme|or|, that takes any\n% number of expressions and returns a true value nondeterministically.\n% Thus, \\scheme|(or-bottom (odd? 0) bottom (! 5) (odd? 1) bottom)|\n% returns either \\scheme|#t| or \\scheme|120|, both of which\n% are true values in Scheme. \\scheme|or-bottom| is defined as a macro\n% that wraps its arguments in \\scheme|fern| before passing them to a\n% recursive auxiliary for two reasons: first, to make the auxiliary\n% lazy, and second, to allow the auxiliary to choose convergent\n% arguments before divergent ones.  This strategy will be used again in\n% Section~\\ref{mplus-bottom-and-bind-bottom} to define \\scheme|mplus-bottom|.\n\n%\\schemedisplayspace\n%\\schemeinput{fernscode/code/or-fn}\n\n\\noindent\nLet us define \\scheme|append-bottom| for ferns. \n\n\\schemedisplayspace\n\\schemeinput{fernscode/append}\n\n\\noindent\nTo observe the behavior of \\scheme|append-bottom|, we define \\scheme|take-bottom| whose\nfirst argument is either \\scheme|#f| (all results) or $n > 0$ (no more than $n$ results).\n\n\\schemedisplayspace\n\\schemeinput{fernscode/take}\n\n\\noindent \nWhen determining the $n$th value, it is necessary to avoid taking the\n\\scheme|fcdr| after the $n$th value is determined, since it is that \\scheme|fcdr|\nthat might not terminate and we already have $n$ results.\n\nThe definition of \\scheme|append-bottom| appears to work as expected:\n\n\\wspace\n\\noindent\n\\scheme|(take-bottom 2 (append-bottom (fern 1) (fern bottom 2)))| \\schemeresult|=> (1 2)|.\n\\wspace\n\n\\noindent Moving \\scheme|bottom| from the second argument to the\nfirst, however, reveals a problem:\n\n\\wspace\n\\noindent\n\\scheme|(take-bottom 2 (append-bottom (fern bottom 1) (fern 2)))| \\schemeresult|=> bottom|.\n\\wspace\n\n\\noindent\nEven though the result of the call to\n\\scheme|append-bottom| should contain two convergent elements, taking the first\ntwo elements of that result diverges. This is because the\ndefinition of \\scheme|append-bottom| requires that \\scheme|s1| be completely\nexhausted before any elements from \\scheme|s2| can appear in the result.\nIf one of the elements of \\scheme|s1| is \\scheme|bottom|, then no\nelement from \\scheme|s2| will ever appear.  The same is true if\n\\scheme|s1| contains an unbounded number of convergent elements: since\n\\scheme|s1| is never null, the result will never contain elements from\n\\scheme|s2|.  With the definition of \\scheme|mplus-bottom| in\nSection~\\ref{mplus-bottom-and-bind-bottom}, it becomes clear that the solution to these problems is to\ninterleave the elements from \\scheme|s1| and \\scheme|s2| in the\nresulting fern as in the next example.\n\nFunctional programs often share rather than copy data, and ferns are\ndesigned to encourage this programming style. Consider a procedure to\ncompute the Cartesian product of two ferns:\n\n\\schemedisplayspace\n\\schemeinput{fernscode/cartesian}\n\n\\schemeinput{fernscode/cartesian-example}\\schemeresult|~> `((a . x) (a . y) (b . x) (a . z) (b . y) (b . z))|\n\\belowcodeskip \\medskipamount\n\\medskip\n\n\\noindent\nwhere \\schemeresult|~>| indicates \\emph{one} of the possible values.\nThis definition ensures that the resulting fern shares\nelements with the ferns passed as arguments. Many references to a\nparticular element may be made without repeating computations, hence the\nexpression\n\n\\wspace\n\n\\noindent\n\\scheme|(take-bottom 2 (Cartesian-product-bottom (fern (begin (display #t) 5)) (fern 'a bottom 'b)))|\n\n\\tspace\n\n\\noindent\n\\schemeresult|~> `((5 . a) (5 . b))|\n\\belowcodeskip \\medskipamount\n\\medskip\n\n\\noindent prints \\schemeresult|#t| \\emph{exactly once}.\n(There are more examples of the use of ferns in~\\citet{Johnson-83}, \\citet{Filman-Friedman-84}, and~\\citet{Jeschke-PHD-95}.)\n\nIn the next section we look at how the sharing properties of ferns are\nmaintained alongside bottom-avoidance.\n\n\\section{Sharing and Promotion}\\label{Sharing}\n\nIn this section, we provide examples and a high-level description of\nthe \\emph{promotion algorithm} of Friedman and Wise~\\cite{Friedman79b}. \nThe values in a fern are computed and\n\\emph{promoted} across the fern while ensuring that the correct values\nare available from each subfern, \\scheme|bottom|'s are avoided, and\nnon-\\scheme|bottom| values are computed only once.\n% A proper fern is either the empty list or a pair whose cdr is another fern. \nFerns have structure, and there may be references to more than one\nsubfern of a particular fern. Consider the example expression\n\n\\schemedisplayspace\n\\schemeinput{fernscode/sharing-1}\n\n\\begin{schemeresponse}~> `((6 120 720) (6 120 720) (6 720) (720))\n\\end{schemeresponse}\n\n\\noindent assuming \\scheme|list| evaluates its arguments\nleft-to-right.  Importantly,\naccessing \\scheme|delta| cannot retrieve values in the prefix of the\nenclosing fern \\scheme|alpha|. We now describe in detail how the\nresult of \\mbox{\\scheme|(take-bottom 3 alpha)|} is determined along with\nthe necessary changes to the fern data structure during this\nprocess. Whenever we encounter a choice, we shall assume a choice\nconsistent with the value returned in the example.\n\nDuring the first access of \\scheme|alpha| the cdrs are evaluated, as\nindicated by the arrows in Figure~\\ref{fig:solid}a.\nFigure~\\ref{fig:solid}b depicts the data structure after\n\\mbox{\\scheme|(fcar alpha)|} is evaluated. We assume that, of the\npossible values for \\mbox{\\scheme|(fcar alpha)|}, namely\n\\scheme|bottom| (which is never chosen), \\mbox{\\scheme|(! 5)|},\n\\mbox{\\scheme|(! 3)|}, and \\mbox{\\scheme|(! 6)|}, the value of\n\\mbox{\\scheme|(! 3)|} is chosen and promoted. Since the value\nof \\mbox{\\scheme|(! 3)|} might be a value for \\mbox{\\scheme|(fcar beta)|}\n and \\mbox{\\scheme|(fcar gamma)|}, we replace the cars of all\nthree pairs with the value of \\mbox{\\scheme|(! 3)|}, which\nis \\schemeresult|6|. We replace the cdrs of \\scheme|alpha| and\n\\scheme|beta| with new frons pairs containing \\scheme|bottom| and\n\\mbox{\\scheme|(! 5)|}, which were not chosen. The new frons pairs are\nlinked together, and linked at the end to the old cdr of\n\\scheme|gamma|. Thus \\scheme|alpha|, \\scheme|beta|, and \\scheme|gamma|\nbecome a fern with \\schemeresult|6| in the car and a fern of the\nrest of their original possible values in their cdrs.  As a result of\nthe promotion, $\\alpha$, $\\beta$, and $\\gamma$ become cons pairs,\nrepresented in the figures by rectangles.\n\nFigure~\\ref{fig:solid}c depicts the data structure after\n\\mbox{\\scheme|(fcadr alpha)|} is evaluated. This time,\n\\mbox{\\scheme|(! 5)|} is chosen from \\scheme|bottom|, \\mbox{\\scheme|(! 5)|}, \nand \\mbox{\\scheme|(! 6)|}.  Since the value of \\mbox{\\scheme|(! 5)|} is\nalso a possible value for \\mbox{\\scheme|(fcadr beta)|}, we replace\nthe cadrs of both \\scheme|alpha| and \\scheme|beta| with the value of\n\\mbox{\\scheme|(! 5)|}, which is \\schemeresult|120|, and replace the cddr of\n\\scheme|alpha| with a frons pair containing the \\scheme|bottom| that\nwas not chosen and a pointer to \\scheme|delta|. The cddr of \\scheme|beta| points to \\scheme|delta|; no\nnew fern with remaining possible values is needed because the value\nchosen for \\mbox{\\scheme|(fcadr beta)|} was the first value\navailable. As before, the pairs containing values become cons pairs.\n\n% \\renewcommand{\\figurename}{Program}\n\n% \\begin{figure}[H]\n% \\begin{schemeregion}\n% \\schemeinput{fernscode/code/sharing-1}\n% \\end{schemeregion}\n% \\caption{Program that constructs and accesses fern $\\alpha$.\\label{fig:code/sharing-1}}\n% \\end{figure}\n\n\\renewcommand{\\figurename}{Figure}\n\\addtocounter{figure}{0}\n\n% \\newcommand{\\ahwd}{4}\n% \\newcommand{\\ahht}{3}\n% \\newcommand{\\dahwd}{5}\n% \\newcommand{\\hahht}{2}\n% \\newcommand{\\thahht}{1}\n% \\newcommand{\\dahht}{6}\n% \\newcommand{\\namegap}{8}\n% \\newcommand{\\ftxht}{12}\n% \\newcommand{\\ctxht}{10}\n% \\newcommand{\\ebxwd}{3}\n% \\newcommand{\\qbxwd}{10}\n% \\newcommand{\\hbxwd}{20}\n% \\newcommand{\\sbxwd}{6}\n% \\newcommand{\\fbxwd}{40}\n\n\\newcommand{\\ahwd}{4}\n\\newcommand{\\ahht}{3}\n\\newcommand{\\dahwd}{5}\n\\newcommand{\\hahht}{2}\n\\newcommand{\\thahht}{1}\n\\newcommand{\\dahht}{6}\n\\newcommand{\\namegap}{8}\n\\newcommand{\\ftxht}{10}\n\\newcommand{\\ctxht}{8}\n\\newcommand{\\ebxwd}{2}\n\\newcommand{\\qbxwd}{7}\n\\newcommand{\\hbxwd}{14}\n\\newcommand{\\sbxwd}{4}\n\\newcommand{\\fbxwd}{28}\n\n\n\\Define\\namebox(1) {\n  \\Move(0,\\hbxwd) \n  \\Move(0,\\namegap) \n  \\Text(--#1--) \n  \\Move(0,-\\namegap) \n  \\Move(0,-\\hbxwd)\n}\n\n\\Define\\namefig(3) { % name, half width, height\n  \\Move(#2,-#3)\n  \\Move(0,-\\namegap)\n  \\Text(--$\\mbox{(#1)}$--)\n  \\Move(0,\\namegap)\n  \\Move(-#2,#3)\n}\n\n\\newcommand{\\boxtext}{Z}\n\n\\Define\\fronsbox {\n  \\Line(0,\\hbxwd) \n  \\MarkLoc(p1)\n  \\Move(\\qbxwd,\\qbxwd)\n  \\MarkLoc(q1)\n  \\Move(\\hbxwd,-\\hbxwd)\n  \\MarkLoc(q2)\n  \\Move(\\qbxwd,\\qbxwd)\n  \\MarkLoc(p2) \n  \\Curve(p1,q1,q2,p2) \n  \\Line(0,-\\hbxwd)\n  \\MarkLoc(p1)\n  \\Move(-\\qbxwd,-\\qbxwd)\n  \\MarkLoc(q1)\n  \\Move(-\\hbxwd,\\hbxwd)\n  \\MarkLoc(q2)\n  \\Move(-\\qbxwd,-\\qbxwd)\n  \\MarkLoc(p2)\n  \\Curve(p1,q1,q2,p2)\n  \\Move(\\qbxwd,\\ftxht)\n  \\Text(--\\boxtext--)\n  \\Move(\\qbxwd,-\\ftxht)\n  \\Line(0,\\hbxwd)\n  \\Move(\\qbxwd,-\\qbxwd)\n}\n\n\\Define\\arrowhead {\n  \\Move(-\\ahwd,-\\ahht) \\Line(\\ahwd,\\ahht)\n  \\Move(-\\ahwd,\\ahht) \\Line(\\ahwd,-\\ahht)\n  \\Move(1,0)\n}\n\n\\Define\\rightdotted {\n  \\Do(0,\\qbxwd){\\Line(1,0)\\Move(2,0)}\n  \\arrowhead\n  \\Move(0,-\\qbxwd)\n}\n\n\\Define\\rightsolid {\n  \\Do(0,\\qbxwd){\\Line(3,0)}\n  \\arrowhead\n  \\Move(0,-\\qbxwd)\n}\n\n\\Define\\boxnil {\n  \\Move(-\\qbxwd,-\\qbxwd)\n  \\Line(\\hbxwd,\\hbxwd)\n  \\Move(0,-\\qbxwd)\n}\n\n\\Define\\dottednil {\n  \\Move(-\\qbxwd,-\\qbxwd)\n  \\Do(0,\\sbxwd){\\Line(1,1)\\Move(2,2)}\n  \\Move(0,-\\qbxwd)\n}\n\n\\Define\\blankbox {\n  \\Move(\\hbxwd,0)\n  \\Move(\\qbxwd,0)\n  \\Do(0,\\qbxwd){\\Move(3,0)}\n  \\Move(1,0)\n}\n\n\\Define\\consbox {\n  \\Line(0,\\hbxwd) \n  \\Line(\\fbxwd,0)\n  \\Line(0,-\\hbxwd)\n  \\Line(-\\fbxwd,0)\n  \\Move(\\qbxwd,\\ctxht)\n  \\Text(--\\boxtext--)\n  \\Move(\\qbxwd,-\\ctxht)\n  \\Line(0,\\hbxwd)\n  \\Move(\\qbxwd,-\\qbxwd)\n}\n\n\\Define\\downhead {\n  \\Move(-\\ahht,\\ahwd) \\Line(\\ahht,-\\ahwd)\n  \\Move(\\ahht,\\ahwd) \\Line(-\\ahht,-\\ahwd)\n  \\Move(0,-1)\n}\n\n\\Define\\downsolid {\n  \\Line(0,-\\hbxwd)\n  \\Line(0,-\\qbxwd)\n  \\downhead\n  \\Move(\\qbxwd,0)\n  \\Move(-\\fbxwd,-\\hbxwd)\n}\n\n\\Define\\longdownsolid {\n  \\Line(0,-\\hbxwd)\n  \\Line(0,-\\qbxwd)\n  \\Line(0,-\\ebxwd)\n  \\downhead\n  \\Move(\\qbxwd,\\ebxwd)\n  \\Move(-\\fbxwd,-\\hbxwd)\n}\n\n\\Define\\blankleft {\n  \\Move(-\\hbxwd,0)\n  \\Move(-\\qbxwd,0)\n  \\Do(0,\\qbxwd){\\Move(-3,0)}\n  \\Move(-1,0)\n}\n\n\\Define\\blankup {\n  \\Move(0,\\fbxwd)\n  \\Move(0,1)\n}\n\n\\Define\\rightuphead {\n  \\Move(-\\dahwd,-\\hahht) \\Line(\\dahwd,\\hahht)\n  \\Move(0,-\\dahht) \\Line(0,\\dahht)\n}\n\n\\Define\\tiltedrightuphead {\n  \\Move(-\\dahwd,-\\thahht) \\Line(\\dahwd,\\thahht)\n  \\Move(-1,-\\dahht) \\Line(1,\\dahht)\n}\n\n\\Define\\rightupdoublesolid {\n  \\MarkLoc(p1)\n  \\Move(\\fbxwd,0)\n  \\MarkLoc(q1)\n  \\Move(\\fbxwd,0)\n  \\MarkLoc(q2)\n  \\blankup\n  \\Move(\\hbxwd,-\\qbxwd)\n  \\Move(-1,-1)\n  \\MarkLoc(p2)\n  \\Curve(p1,q1,q2,p2)\n  \\rightuphead\n  \\Move(1,1)\n}\n\n\\Define\\rightupdoublelonger {\n  \\MarkLoc(p1)\n  \\Move(\\fbxwd,0)\n  \\MarkLoc(q1)\n  \\Move(\\fbxwd,0)\n  \\MarkLoc(q2)\n  \\blankup\n  \\Move(\\hbxwd,-\\qbxwd)\n  \\Move(4,4)\n  \\MarkLoc(p2)\n  \\Curve(p1,q1,q2,p2)\n  \\rightuphead\n  \\Move(-4,-4)\n}\n\n\\Define\\blankdown {\n  \\Move(0,-\\fbxwd)\n}\n\n\\Define\\rightuptriplesolid {\n  \\MarkLoc(p1)\n  \\blankbox\n  \\blankbox\n  \\MarkLoc(q1)\n  \\MarkLoc(q2)\n  \\Do(0,\\qbxwd){\\Move(3,0)}\n  \\Move(1,0)\n  \\blankup\n  \\Move(0,\\hbxwd)\n  \\Move(0,\\qbxwd)\n  \\Move(-3,0)\n  \\MarkLoc(p2)\n  \\Curve(p1,q1,q2,p2)\n% \\rightuphead\n  \\Move(3,0)\n  \\blankleft \\blankleft \\blankdown\n}\n\n\n\\vspace{20pt}\n\n\\Define\\edown {\n% \\Line(0,-\\hbxwd)\n% \\Line(0,-\\qbxwd)\n  \\Do(0,\\qbxwd){\\Line(0,-2)}\n  \\downhead\n  \\Move(0,-1)\n}\n\n\\Define\\unedown {\n  \\Move(0,1)\n  \\Move(0,1)\n  \\Do(0,\\qbxwd){\\Move(0,2)}\n% \\Move(0,\\qbxwd)\n% \\Move(0,\\hbxwd)\n}\n\n\\newcommand\\egap{3}\n\n\\Define\\lengine {\n  \\edown\n  \\Move(\\egap,0)\n  \\Line(-\\hbxwd,0)\n  \\Line(0,-\\hbxwd)\n  \\Line(\\qbxwd,0)\n  \\Move(0,\\qbxwd)\n  \\Text(--\\boxtext--)\n  \\Move(0,-\\qbxwd)\n  \\Line(\\qbxwd,0)\n  \\Line(0,\\hbxwd)\n  \\Move(-\\egap,0)\n  \\unedown\n}\n\n\\Define\\rengine {\n  \\edown\n  \\Move(-\\egap,0)\n  \\Line(\\hbxwd,0)\n  \\Line(0,-\\hbxwd)\n  \\Line(-\\qbxwd,0)\n  \\Move(0,\\qbxwd)\n  \\Text(--\\boxtext--)\n  \\Move(0,-\\qbxwd)\n  \\Line(-\\qbxwd,0)\n  \\Line(0,\\hbxwd)\n  \\Move(\\egap,0)\n  \\unedown\n}\n\n\\Define\\nodownrengine {\n  \\Move(0,-\\hbxwd)\n  \\Move(0,-\\qbxwd)\n  \\Move(0,-2)\n  \\Move(-\\egap,0)\n  \\Line(\\hbxwd,0)\n  \\Line(0,-\\hbxwd)\n  \\Line(-\\qbxwd,0)\n  \\Move(0,\\qbxwd)\n  \\Text(--\\boxtext--)\n  \\Move(0,-\\qbxwd)\n  \\Line(-\\qbxwd,0)\n  \\Line(0,\\hbxwd)\n  \\Move(\\egap,0)\n  \\Move(0,2)\n  \\Move(0,\\qbxwd)\n  \\Move(0,\\hbxwd)\n}\n\n\\Define\\efronsbox {\n  \\Line(0,\\hbxwd) \n  \\MarkLoc(p1)\n  \\Move(\\qbxwd,\\qbxwd)\n  \\MarkLoc(q1)\n  \\Move(\\hbxwd,-\\hbxwd)\n  \\MarkLoc(q2)\n  \\Move(\\qbxwd,\\qbxwd)\n  \\MarkLoc(p2) \n  \\Curve(p1,q1,q2,p2) \n  \\Line(0,-\\hbxwd)\n  \\MarkLoc(p1)\n  \\Move(-\\qbxwd,-\\qbxwd)\n  \\MarkLoc(q1)\n  \\Move(-\\hbxwd,\\hbxwd)\n  \\MarkLoc(q2)\n  \\Move(-\\qbxwd,-\\qbxwd)\n  \\MarkLoc(p2)\n  \\Curve(p1,q1,q2,p2)\n  \\Move(\\qbxwd, \\qbxwd)\n  \\lengine\n  \\Move(\\qbxwd, -\\qbxwd)\n  \\Line(0,\\hbxwd)\n  \\Move(\\qbxwd,-\\qbxwd)\n}\n\n\\Define\\rightunright{\n  \\Do(0,\\qbxwd){\\Line(3,0)}\n  \\arrowhead\n  \\Move(-1,0)\n  \\Do(0,\\qbxwd){\\Move(-3,0)}\n}\n\n%%\\enlargethispage{20pt}\n\n\\renewcommand\\egap{7}\n\n\\begin{figure}[h]\n\n  \\wspace\n\n  \\wspace  \n\n  \\wspace\n  \n\\begin{schemeregion}\n\\begin{picture}(160,60)(0,-60)\n\\Draw\\PenSize(1pt)\n\\namefig(a,80,45)\n\\namebox(\\scheme|alpha|)\n\\renewcommand{\\boxtext}{\\scheme|bottom|}\n\\efronsbox\\rightsolid\n\\namebox(\\scheme|beta|)\n\\renewcommand{\\boxtext}{\\scheme|! 5|}\n\\efronsbox\\rightsolid\n\\namebox(\\scheme|gamma|)\n\\renewcommand{\\boxtext}{\\scheme|! 3|}\n\\efronsbox\\rightsolid\n\\namebox(\\scheme|delta|)\n\\renewcommand{\\boxtext}{\\scheme|! 6|}\n\\efronsbox\\boxnil\n\\EndDraw\n\\end{picture}\n\\end{schemeregion}\n\n\\begin{schemeregion}\n\\begin{picture}(160,0)(-180,-70)\n\\Draw\\PenSize(1pt)\n\\namefig(b,80,45)\n\\namebox(\\scheme|alpha|)\n\\renewcommand{\\boxtext}{\\schemeresult|six|}\n\\consbox\\longdownsolid\n\\renewcommand{\\boxtext}{\\scheme|bottom|}\n\\efronsbox\\rightsolid\n\\renewcommand{\\boxtext}{\\scheme|! 5|}\n\\efronsbox\\rightupdoublesolid\n\\blankleft \\blankleft \\Move(-1,0)\n\\namebox(\\scheme|beta|)\n\\renewcommand{\\boxtext}{\\schemeresult|six|}\n\\consbox\\longdownsolid\n\\blankup \\blankbox\n\\namebox(\\scheme|gamma|)\n\\renewcommand{\\boxtext}{\\schemeresult|six|}\n\\consbox\\rightsolid\n\\namebox(\\scheme|delta|)\n\\renewcommand{\\boxtext}{\\scheme|! 6|}\n\\efronsbox\\boxnil\n\\EndDraw\n\\end{picture}\n\\end{schemeregion}\n\n\\begin{schemeregion}\n\\begin{picture}(160,110)(0,-90)\n\\Draw\\PenSize(1pt)\n\\namefig(c,80,95)\n\\namebox(\\scheme|alpha|)\n\\renewcommand{\\boxtext}{\\schemeresult|six|}\n\\consbox\\downsolid\n\\renewcommand{\\boxtext}{\\schemeresult|onetwenty|}\n\\consbox\\longdownsolid\n\\renewcommand{\\boxtext}{\\scheme|bottom|}\n\\efronsbox\\rightuptriplesolid\n\\renewcommand{\\boxtext}{\\schemeresult|onetwenty|}\n\\consbox\\rightupdoublesolid\n\\blankleft \\blankleft\n\\namebox(\\scheme|beta|)\n\\renewcommand{\\boxtext}{\\schemeresult|six|}\n\\consbox\\downsolid\n\\blankup \\blankbox\n\\namebox(\\scheme|gamma|)\n\\renewcommand{\\boxtext}{\\schemeresult|six|}\n\\consbox\\rightsolid\n\\namebox(\\scheme|delta|)\n\\renewcommand{\\boxtext}{\\scheme|! 6|}\n\\efronsbox\\boxnil\n\\EndDraw\n\\end{picture}\n\\end{schemeregion}\n\n\\begin{schemeregion}\n\\begin{picture}(160,0)(-180,-100)\n\\Draw\\PenSize(1pt)\n\\namefig(d,80,95)\n\\namebox(\\scheme|alpha|)\n\\renewcommand{\\boxtext}{\\schemeresult|six|}\n\\consbox\\downsolid\n\\renewcommand{\\boxtext}{\\schemeresult|onetwenty|}\n\\consbox\\downsolid\n%\\renewcommand{\\boxtext}{\\schemeresult|720|}\n\\renewcommand{\\boxtext}{\\schemeresult|seventwenty|}\n\\consbox\\longdownsolid\n\\renewcommand{\\boxtext}{\\scheme|bottom|}\n\\efronsbox\\boxnil\n\\blankup\n\\Move(\\hbxwd,\\hbxwd)\n\\Move(\\qbxwd,\\qbxwd)\n\\Move(-3,1)\n\\renewcommand{\\boxtext}{\\schemeresult|onetwenty|}\n\\consbox\\rightupdoublesolid\n\\blankleft \\blankleft\n\\namebox(\\scheme|beta|)\n\\renewcommand{\\boxtext}{\\schemeresult|six|}\n\\consbox\\downsolid\n\\blankup \\blankbox\n\\namebox(\\scheme|gamma|)\n\\renewcommand{\\boxtext}{\\schemeresult|six|}\n\\consbox\\rightsolid\n\\namebox(\\scheme|delta|)\n\\renewcommand{\\boxtext}{\\schemeresult|seventwenty|}\n\\consbox\\boxnil\n\\EndDraw\n\\end{picture}\n\\end{schemeregion}\n\n\\vspace{20pt}\n\n\\caption{Fern $\\alpha$ immediately after evaluation of cdrs, but before any cars have finished evaluation (a) and after the values, $6$ (b), $120$ (c), and $720$ (d) have been promoted.\\label{fig:solid}}\n\\end{figure}\n\n\\renewcommand\\egap{3}\n\nFigure~\\ref{fig:solid}d depicts the data structure after\n\\mbox{\\scheme|(fcaddr alpha)|} is evaluated. Of \\scheme|bottom| and\n\\mbox{\\scheme|(! 6)|}, it comes as no surprise that \\mbox{\\scheme|(!\n  6)|} is chosen. Since the value of \\mbox{\\scheme|(! 6)|}, which is\n\\schemeresult|720|, is also a possible value for \\mbox{\\scheme|(fcar\n  delta)|} (and in fact the only one), we update the car of\n\\scheme|delta| and the car of the cddr of \\mbox{\\scheme|alpha|} with\n\\schemeresult|720|.  The cdr of \\scheme|delta| remains as the empty\nlist, and the cdr of the cddr of \\mbox{\\scheme|alpha|} becomes a new\nfrons pair containing \\scheme|bottom|. The cdr of the new frons pair\nis the empty list copied from the cdr of \\scheme|delta|.  The\nremaining values are obvious given the final state of the data\nstructure. No further manipulation of the data structure is necessary\nto evaluate the three remaining calls to \\scheme|take-bottom|.\n\nIn Figure~\\ref{fig:solid}d  each of the ferns\n\\scheme|alpha|, \\scheme|beta|, \\scheme|gamma|, and \\scheme|delta|\ncontains some permutation of its original possible values, and\n\\scheme|bottom| has been pushed to the end of\n\\scheme|alpha|. Furthermore, if there are no shared references to\n\\scheme|beta|, \\scheme|gamma|, and \\scheme|delta|, the number of\naccessible pairs is linear in the length of the fern.  If there are\nreferences to subferns, for a fern of size $n$, the worst case is\n$(n^2+n)/2$.  But, as these shared references vanish, so do the\nadditional cons pairs.\n\nIf \\scheme|list| evaluated from right-to-left instead of evaluating\nfrom left-to-right, the example expression would return\n\\mbox{\\scheme|`((720 6 120) (720 6 120) (720 6) (720))|}.  Each list\nwould be independent of the others and the last pair of\n\\scheme|alpha| would be a frons pair with \\scheme|bottom| in the car\nand the empty list in the cdr.  This demonstrates that if there is\nsharing of these lists, the lists contain four pairs, three pairs, two\npairs, and one pair, respectively.  If the example expression just\nreturned \\scheme|alpha|, then only four pairs would be accessible.\n\n%\\caption{Final state of fern $\\alpha$ after promotion of $120$ (top) and $720$ (bottom). \\label{fig:p3}}\n\n%\\begin{figure}[H]\n%\\end{figure}\n\n\n\n\n%\\begin{figure}[H]\n%\\end{figure}\n%%%%%\n\n%\\vspace{10pt}\n\n% In our implementation, it is the requesting of a value from a fern that\n% provokes evaluation of the potential values. Therefore changing the\n% order of requests affects how the data structure is manipulated.\n% Program~\\ref{fig:code/sharing-2} is a variation of\n% Program~\\ref{fig:code/sharing-1}, with the same initial data structure\n% but with the \\scheme|display| lines in reverse order; this code might,\n% on a particular run, print:\n% \\begin{schemeresponse}\n% (720)\n% (720 6)\n% (720 6 120)\n% (720 6 120)\n% \\end{schemeresponse}\n\n% Figures~\\ref{fig:dotted}, \\ref{fig:singles} and \\ref{fig:bottom}\n% depict some milestones in the evolution of the fern $\\alpha$ during\n% the evaluation of Program~\\ref{fig:code/sharing-2}.\n% Figure~\\ref{fig:dotted} is still applicable because\n% Programs~\\ref{fig:code/sharing-1} and \\ref{fig:code/sharing-2} differ\n% only in the bodies of their innermost \\scheme|let| expressions.\n% The bottom part of Figure~\\ref{fig:bottom} shows that if there are references to\n% \\scheme|beta|, \\scheme|gamma|, and \\scheme|delta|, then there are\n% respectively three additional cons pairs if $\\beta$ is referenced;\n% two additional cons pairs if $\\gamma$ is referenced; and one additional \n% cons pair if $\\delta$ is referenced.  Thus, for a fern\n% of size $n$, the worst case is $(n^2+n)/2$.  But, as these sharings\n% vanish, the number of additional cons pairs approaches zero.\n\n% is not applicable,\n% since Program~\\ref{fig:code/sharing-2} evaluates \\mbox{\\scheme|(fcar\n%   delta)|} first, and the links between previous pairs remain\n% dotted. Figure~\\ref{fig:singles} depicts the changes to $\\alpha$ as\n% \\mbox{\\scheme|(take-bottom 1 delta)|}, \\mbox{\\scheme|(take-bottom 2 gamma)|}, and\n% \\mbox{\\scheme|(take-bottom 3 beta)|} are evaluated: in each case the first\n% frons pair of the respective subfern contains the only potential\n% value, so that frons pair is simply turned into a cons pair.\n\n% \\addtocounter{figure}{-4}\n% \\renewcommand{\\figurename}{Program}\n\n% \\begin{figure}[H]\n% \\begin{schemeregion}\n% \\schemeinput{fernscode/code/sharing-2}\n% \\end{schemeregion}\n% \\caption{Variant of Program~\\ref{fig:code/sharing-1} with \\textit{displays} reversed.\\label{fig:code/sharing-2}}\n% \\end{figure}\n\n% \\renewcommand{\\figurename}{Figure}\n% \\addtocounter{figure}{3}\n\n% \\begin{figure}[H]\n% \\begin{schemeregion}\n% \\begin{picture}(160,40)(0,-8)\n% \\Draw\\PenSize(1pt)\n% \\namebox(\\scheme|alpha|)\n% \\renewcommand{\\boxtext}{\\scheme|bottom|}\n% \\fronsbox\\rightdotted\n% \\namebox(\\scheme|beta|)\n% \\renewcommand{\\boxtext}{\\scheme|(!! 5)|}\n% \\fronsbox\\rightdotted\n% \\namebox(\\scheme|gamma|)\n% \\renewcommand{\\boxtext}{\\scheme|(!! 3)|}\n% \\fronsbox\\rightdotted\n% \\namebox(\\scheme|delta|)\n% \\renewcommand{\\boxtext}{\\schemeresult|720|}\n% \\consbox\\boxnil\n% \\EndDraw\n% \\end{picture}\n% \\end{schemeregion}\n% \\caption{Fern $\\alpha$ after promotion of the first value, 720. (See Program~\\ref{fig:code/sharing-2}.)\\label{fig:singles}}\n% \\end{figure}\n\n\n% \\begin{schemeregion}\n% \\begin{picture}(160,40)(0,-10)\n% \\Draw\\PenSize(1pt)\n% \\namebox(\\scheme|alpha|)\n% \\renewcommand{\\boxtext}{\\scheme|bottom|}\n% \\fronsbox\\rightdotted\n% \\namebox(\\scheme|beta|)\n% \\renewcommand{\\boxtext}{\\scheme|(!! 5)|}\n% \\fronsbox\\rightdotted\n% \\namebox(\\scheme|gamma|)\n% \\renewcommand{\\boxtext}{\\scheme|6|}\n% \\consbox\\rightsolid\n% \\namebox(\\scheme|delta|)\n% \\renewcommand{\\boxtext}{\\schemeresult|720|}\n% \\consbox\\boxnil\n% \\EndDraw\n% \\end{picture}\n% \\end{schemeregion}\n\n% \\begin{schemeregion}\n% \\begin{picture}(160,40)(0,-10)\n% \\Draw\\PenSize(1pt)\n% \\namebox(\\scheme|alpha|)\n% \\renewcommand{\\boxtext}{\\scheme|bottom|}\n% \\fronsbox\\rightdotted\n% \\namebox(\\scheme|beta|)\n% \\renewcommand{\\boxtext}{\\scheme|120|}\n% \\consbox\\rightsolid\n% \\namebox(\\scheme|gamma|)\n% \\renewcommand{\\boxtext}{\\scheme|6|}\n% \\consbox\\rightsolid\n% \\namebox(\\scheme|delta|)\n% \\renewcommand{\\boxtext}{\\schemeresult|720|}\n% \\consbox\\boxnil\n% \\EndDraw\n% \\end{picture}\n% \\end{schemeregion}\n\n% Figure~\\ref{fig:singles} shows that \\mbox{\\scheme|(take-bottom 1 delta)|},\n% which is the same as \\mbox{\\scheme|(fcar delta)|}, evaluates only\n% \\mbox{\\scheme|(! 7)|}, accounting for \\scheme|720| in\n% $\\delta$. Once we have a cons pair in a fern, its car will generally\n% dominate any frons pairs that refer to it directly or indirectly, so\n% we end up in turn with \\mbox{\\scheme|(fcar gamma)|},\n% \\mbox{\\scheme|(fcar beta)|}, and \\mbox{\\scheme|(fcar alpha)|} also\n% being \\scheme|720|.  The values in the other pairs dominate for\n% similar reasons, but then it is for the \\scheme|fcadr| and finally for\n% the \\scheme|fcaddr|. These lead to the before and after figures\n% for the last promotion that corresponds to taking \\mbox{\\scheme|(fcaddr alpha)|}\n% as shown in the top diagram of Figure~\\ref{fig:bottom}.\n\n \\Define\\rightdoubleupsolid {\n   \\MarkLoc(p1)\n   \\blankbox\n   \\MarkLoc(q1)\n   \\MarkLoc(q2)\n   \\Do(0,\\qbxwd){\\Move(3,0)}\n   \\Move(1,-\\qbxwd)\n   \\blankup\n   \\MarkLoc(p2)\n   \\Curve(p1,q1,q2,p2)\n   \\tiltedrightuphead\n   \\blankleft\n }\n\n \\Define\\righttripleupsolid {\n   \\MarkLoc(p1)\n   \\blankbox\n   \\blankbox\n   \\blankup\n   \\MarkLoc(q1)\n   \\MarkLoc(q2)\n   \\Do(0,\\qbxwd){\\Move(3,0)}\n   \\Move(1,-\\qbxwd)\n   \\blankup\n   \\MarkLoc(p2)\n   \\Curve(p1,q1,q2,p2)\n   \\tiltedrightuphead\n   \\blankleft\n   \\blankleft\n}\n\n%\\begin{figure}[H]\n% \\begin{schemeregion}\n% \\begin{picture}(160,80)(0,-50)\n% \\Draw\\PenSize(1pt)\n% \\namebox(\\scheme|alpha|)\n% \\renewcommand{\\boxtext}{\\schemeresult|120|}\n% \\consbox\\longdownsolid\n% \\renewcommand{\\boxtext}{\\scheme|bottom|}\n% \\fronsbox\\rightdoubleupsolid\n% \\namebox(\\scheme|beta|)\n% \\renewcommand{\\boxtext}{\\scheme|120|}\n% \\consbox\\rightsolid\n% \\namebox(\\scheme|gamma|)\n% \\renewcommand{\\boxtext}{\\scheme|6|}\n% \\consbox\\rightsolid\n% \\namebox(\\scheme|delta|)\n% \\renewcommand{\\boxtext}{\\schemeresult|720|}\n% \\consbox\\boxnil\n% \\EndDraw\n% \\end{picture}\n% \\end{schemeregion}\n\n% \\begin{schemeregion}\n% \\begin{picture}(160,120)(0,-90)\n% \\Draw\\PenSize(1pt)\n% \\namebox(\\scheme|alpha|)\n% \\renewcommand{\\boxtext}{\\schemeresult|120|}\n% \\consbox\\downsolid\n% \\renewcommand{\\boxtext}{\\scheme|6|}\n% \\consbox\\longdownsolid\n% \\renewcommand{\\boxtext}{\\scheme|bottom|}\n% \\fronsbox\\righttripleupsolid\n% \\namebox(\\scheme|beta|)\n% \\renewcommand{\\boxtext}{\\scheme|120|}\n% \\consbox\\rightsolid\n% \\namebox(\\scheme|gamma|)\n% \\renewcommand{\\boxtext}{\\scheme|6|}\n% \\consbox\\rightsolid\n% \\namebox(\\scheme|delta|)\n% \\renewcommand{\\boxtext}{\\schemeresult|720|}\n% \\consbox\\boxnil\n% \\EndDraw\n% \\end{picture}\n% \\end{schemeregion}\n\n%%%% penultimate promotion.\n% \\begin{figure}[H]\n% \\begin{schemeregion}\n% \\begin{picture}(160,160)(0,-130)\n% \\Draw\\PenSize(1pt)\n% \\namebox(\\scheme|alpha|)\n% \\renewcommand{\\boxtext}{\\schemeresult|720|}\n% \\consbox\\downsolid\n% \\renewcommand{\\boxtext}{\\scheme|6|}\n% %\\consbox\\downsolid\n% %\\renewcommand{\\boxtext}{\\schemeresult|120|}\n% \\consbox\\longdownsolid\n% \\renewcommand{\\boxtext}{\\scheme|bottom|}\n% %\\fronsbox\\boxnil\\blankup\\blankup\n% \\fronsbox\\rightsolid\\blankup\\blankup\n% %\\Move(\\hbxwd,-\\qbxwd)\n% \\Move(3,0)\n% \\namebox(\\scheme|beta|)\n% \\renewcommand{\\boxtext}{\\scheme|720|}\n% %%%\n% \\consbox\\downsolid\n% \\renewcommand{\\boxtext}{\\scheme|6|}\n% \\consbox\\downsolid\n% \\renewcommand{\\boxtext}{\\schemeresult|120|}\n% \\consbox\\boxnil\\blankup\\blankup\n% \\Move(\\hbxwd,-\\qbxwd)\\Move(3,0)\n% %\\consbox\\downsolid\n% %%%\n% \\namebox(\\scheme|gamma|)\n% \\renewcommand{\\boxtext}{\\scheme|720|}\n% \\consbox\\downsolid\n% \\renewcommand{\\boxtext}{\\scheme|6|}\n% \\consbox\\boxnil\\blankup\n% \\Move(\\hbxwd,-\\qbxwd)\\Move(3,0)\n% \\namebox(\\scheme|delta|)\n% \\renewcommand{\\boxtext}{\\schemeresult|720|}\n% \\consbox\\boxnil\n% \\EndDraw\n% \\end{picture}\n% \\end{schemeregion}\n\n% \\begin{schemeregion}\n% \\begin{picture}(160,160)(0,-130)\n% \\Draw\\PenSize(1pt)\n% \\namebox(\\scheme|alpha|)\n% \\renewcommand{\\boxtext}{\\schemeresult|720|}\n% \\consbox\\downsolid\n% \\renewcommand{\\boxtext}{\\scheme|6|}\n% \\consbox\\downsolid\n% \\renewcommand{\\boxtext}{\\schemeresult|120|}\n% \\consbox\\longdownsolid\n% \\renewcommand{\\boxtext}{\\scheme|bottom|}\n% \\fronsbox\\boxnil\\blankup\\blankup\\blankup\n% \\Move(\\hbxwd,-\\qbxwd)\\Move(3,0)\n% \\namebox(\\scheme|beta|)\n% \\renewcommand{\\boxtext}{\\scheme|720|}\n%%%\n% \\consbox\\downsolid\n% \\renewcommand{\\boxtext}{\\scheme|6|}\n% \\consbox\\downsolid\n% \\renewcommand{\\boxtext}{\\schemeresult|120|}\n% \\consbox\\boxnil\\blankup\\blankup\n% \\Move(\\hbxwd,-\\qbxwd)\\Move(3,0)\n% %\\consbox\\downsolid\n% %%%\n% \\namebox(\\scheme|gamma|)\n% \\renewcommand{\\boxtext}{\\scheme|720|}\n% \\consbox\\downsolid\n% \\renewcommand{\\boxtext}{\\scheme|6|}\n% \\consbox\\boxnil\\blankup\n% \\Move(\\hbxwd,-\\qbxwd)\\Move(3,0)\n% \\namebox(\\scheme|delta|)\n% \\renewcommand{\\boxtext}{\\schemeresult|720|}\n% \\consbox\\boxnil\n% \\EndDraw\n% \\end{picture}\n% \\end{schemeregion}\n% \\caption{Final promotion within fern $\\alpha$ from Program~\\ref{fig:code/sharing-2}.\\label{fig:bottom}}\n% \\end{figure}\n\nThe example presented in this section provides a direct view of\npromotion. When a fern is accessed by multiple computations, the\npromotion algorithm must be able to handle various issues such as\nmultiple values becoming available for promotion at once. The code\npresented in Chapter~\\ref{fernsimpl} handles these details.\n\nWe are now ready to consider a ferns-based implementation of\nminiKanren.\n\n\\section{Ferns-based miniKanren}\\label{lp-system}\n\nIn this section we describe a simple bottom-avoiding logic programming\nlanguage, which corresponds to core miniKanren with non-interleaving\nsearch.\n% In this section, we use the task of logic programming as an extended\n% example of the use of ferns in avoiding bottom while maintaining a\n% natural recursive style. \n%We compare two sets of goal constructors, one\n%using streams and the other using ferns.  \nWe begin by describing and\nimplementing operators \\scheme|mplus-bottom| and \\scheme|bind-bottom| over ferns,\nand go on to implement goal constructors in terms of these\noperators.  The fern-based goal constructors are shown to be more\ngeneral than the standard stream-based ones presented in Chapter~\\ref{mkimplchapter}\\footnote{See~\\citet{Wand04relatingmodels} for a historical account of logic combinators.}.\n\n\\subsection{\\protect\\scheme|mplus-bottom| and \\protect\\scheme|bind-bottom|}\\label{mplus-bottom-and-bind-bottom}\n\nSince we are developing goal constructors in Scheme, a call-by-value language,\nwe make \\scheme|mplus-bottom| itself lazy to avoid diverging when one or\nmore of its arguments diverge. This is accomplished by defining \\scheme|mplus-bottom| as a\nmacro that wraps its two arguments in \\scheme|fern| before passing\nthem to \\scheme|mplus-fn-bottom|. In addition, \\scheme|mplus-bottom| must interleave\nelements from both of its arguments so that a fern of unbounded length\nin the first argument will not cause the second argument to be\nignored.\n\n%% TODO: bind should be lazy!\n%% Bind should not need to be lazy, since its arguments are streams\n%% and functions and we know all the places it is called.\n\n%% TODO: examples of why we need frons?\n\n% The \\scheme|mplus-func-bottom| procedure does exactly that, returning a fern\n% that is guaranteed to contain all the convergent elements of both\n% \\scheme|s1| and \\scheme|s2|, even if both contain divergent elements\n% or are infinite in length.\n\n% \\noindent Because \\scheme|mplus-func-bottom| immediately returns a fern,\n% \\mbox{\\scheme|(mplus-func-bottom s1 s2) converges|} for all ferns \\scheme|s1| and\n% \\scheme|s2|. In addition, since the results are interleaved, divergent\n% values are pushed to the end of the resulting fern. Thus,\n\n% \\belowcodeskip 0pt\n% \\schemeinput{fernscode/code/mplus-example-1}\\schemeresult|=> `(5 6)|\n% \\belowcodeskip \\medskipamount\n\n% \\medskip\n\n% \\noindent \\scheme|mplus-func-bottom| even works on infinite ferns, interleaving\n% them:\n\n% \\belowcodeskip 0pt\n% \\schemeinput{fernscode/code/mplus-example-2}\\schemeresult|=> `(1 200 201 2)|\n% \\belowcodeskip \\medskipamount\n\n% \\medskip\n\n% Unfortunately, this definition of \\scheme|mplus-func-bottom| can handle only one\n% type of divergence: while \\mbox{\\scheme|(mplus-func-bottom s1 s2) converges|} when\n% \\mbox{\\scheme|s1| \\scheme|converges|} and \\mbox{\\scheme|s2| \\scheme|converges|}, \n% \\mbox{\\scheme|(mplus-func-bottom s1 bottom) => bottom|}. \n% Since \\scheme|s1| may have non-\\scheme|bottom|\n% values, we would prefer that \\scheme|mplus-func-bottom| avoid this type of\n% divergence by waiting to evaluate its arguments until necessary. We can\n% accomplish this by writing \\scheme|mplus-func-bottom| as a macro that creates a\n% two-value fern of its arguments before passing that fern to the\n% \\scheme|mplus-fn-bottom| procedure.  $\n\n\\schemedisplayspace\n\\schemeinput{fernscode/mplus-fn}\n\n\\schemeinput{fernscode/bind}\n\n% We use a fern constructor to make \\scheme|mplus-bottom| lazy: if one of the ferns in the \n% argument to \\scheme|mplus-fn-bottom| is divergent, it can select the other\n% one. For example, consider \\mbox{\\scheme|(fcar (mplus-bottom bottom (fern 5)))|},\n% which evaluates to \\schemeresult|5|. \n\\noindent\n\\scheme|bind-bottom| avoids the same types of\ndivergence as \\scheme|map-bottom| described in Section~\\ref{fernsRecursiveExamples} but\nuses \\scheme|mplus-bottom| to merge the results of the calls to \\scheme|f|.\nThus, \\mbox{\\scheme|(bind-bottom (ints-bottom 0) ints-bottom)|} is an unbounded fern of\nintegers; for every (nonnegative) integer $n$, it contains the\nintegers starting from $n$ and therefore every nonnegative integer $n$\nis contained $n+1$ times.  The interleaving leads to\nduplicates in the following example:\n\n\\wspace\n\\noindent\\scheme|(take-bottom 13 (bind-bottom (ints-bottom 0) ints-bottom))| \\schemeresult|~> `(0 1 2 1 3 4 5 6 7 8 9 2 10)|.\n\\wspace\n\n\\noindent\nThe addition of \\scheme|unit-bottom| and \\scheme|mzero-bottom| rounds out the set of\noperators we need to implement a minimal miniKanren-like language.\n\n\\schemedisplayspace\n\\schemeinput{fernscode/mzerounit}\n\n\\noindent Using these definitions, we can run programs that require\nmultiple unbounded ferns, such as this program inspired by Seres and\nSpivey~\\cite{CombinatorsforLP} that searches for a pair $a$ and $b$ of\ndivisors of $9$ by enumerating the integers from $2$ in a fern of\npossible values for $a$ and similarly for $b$:\n\n\\schemedisplayspace\n\\belowcodeskip 0pt\n\\schemeinput{fernscode/spivey}\\schemeresult|=> `(3 3)|.\n\\belowcodeskip \\medskipamount\n\\medskip\n\n\\noindent Using streams instead of ferns in this example, which would be\nlike nesting ``for'' loops, would result in divergence since $2$ does\nnot evenly divide $9$.\n\n\\subsection{Goal Constructors}\n\n%\\enlargethispage{30pt}\nWe are now ready to define three goal constructors:\n\\scheme|==-bottom|, which unifies terms; \\scheme|disj-bottom|, which\nperforms disjunction over goals; and \\scheme|conj-bottom|, which\nperforms conjunction over goals\\footnote{\\scheme|disj-bottom| is just a simplified version of \\scheme|conde|, while \\scheme|conj-bottom| is just a simplified version of \\scheme|exist|.}. These goal constructors are required\nto terminate, and they always return a goal.  A \\emph{goal} is a\nprocedure that takes a substitution and returns a fern of\nsubstitutions (rather than a stream of substitutions, as in\nChapter~\\ref{mkimplchapter}).\n\n\\schemedisplayspace\n\\schemeinput{fernscode/mk-without-run}\n\nA logic program evaluates to a goal; to obtain answers, this goal is\napplied to the empty substitution. The result is a fern of\nsubstitutions representing answers.  We define \\scheme|run-bottom| in terms\nof \\scheme|take-bottom|, described in Section \\ref{fernsRecursiveExamples}, to\nobtain a list of answers from the fern of substitutions\n\n\\schemedisplayspace\n\\schemeinput{fernscode/mk-run}\n\\noindent where \\scheme|n| is a non-negative integer (or \\scheme|#f|) and \n\\scheme|g| is a goal.  \n% (See Section~\\ref{lp-helpers} for the rest of the definitions used in this section.)\n\nGiven two logic variables \\scheme|x| and \\scheme|y|, here are\nsome simple logic programs that produce the same answers using both\nfern-based and stream-based goal constructors.\n\n\\medskip\n\n\\indent \\scheme|(run-bottom #f (==-bottom 1 x))| \\schemeresult|=> `($\\{x/1\\}$)| \\\\\n\\indent \\scheme|(run-bottom 1 (conj-bottom (==-bottom y 3) (==-bottom x y)))| %$\n\\schemeresult|=> `($\\{x/3, y/3\\}$)| \\\\\n\\indent \\scheme|(run-bottom 1 (disj-bottom (==-bottom x y) (==-bottom y 3)))| %$\n\\schemeresult|=> `($\\{x/y\\}$)| \\\\\n \\indent \\scheme|(run-bottom 5 (disj-bottom (==-bottom x y) (==-bottom y 3)))| %$\n\\schemeresult|=> `($\\{x/y\\}$ $\\{y/3\\}$)| \\\\\n \\indent \\scheme|(run-bottom 1 (conj-bottom (==-bottom x 5) (conj-bottom (==-bottom x y) (==-bottom y 4))))|\n\\schemeresult|=> `()| \\\\\n\\indent \\scheme|(run-bottom #f (conj-bottom (==-bottom x 5) (disj-bottom (==-bottom x 5) (==-bottom x 6))))|\n\\schemeresult|=> `($\\{x/5\\}$)|\n\n\\medskip\n\n\\noindent It is not difficult, however, to find examples of logic\nprograms that diverge when using stream-based goal constructors but\nconverge using fern-based constructors:\n\n\\medskip\n\n\\scheme|(run-bottom 1 (disj-bottom bottom (==-bottom x 3)))| \\schemeresult|=> `($\\{x/3\\}$)| \\\\\n\\indent \\scheme|(run-bottom 1 (disj-bottom (==-bottom bottom x) (==-bottom x 5)))| \\schemeresult|=> `($\\{x/5\\}$)|\n\n\\medskip\n\n\\noindent and given idempotent substitutions \\cite{lloyd:lp}, the\nfern-based operators can even avoid some circularity-based divergence\nwithout the occurs-check, while stream-based operators cannot:\n\n\\wspace\n\n\\scheme|(run-bottom 1 (disj-bottom (==-bottom (list x) x) (==-bottom x 6)))| \\schemeresult|=> `($\\{x/6\\}$)|\n\n\\wspace\n\nThere are functions that represent relations. The relation\n\\scheme|always-five-bottom| associates 5 with its argument an unbounded number of times:\n\n\\schemedisplayspace\n\\schemeinput{fernscode/always-five}\n\n\\noindent Because both stream and fern constructors\ndo not evaluate their arguments,\nwe may safely evaluate the goal \\mbox{\\scheme|(always-five-bottom x)|}, %$\nobtaining an unbounded collection of answers.  Using\n\\scheme|run-bottom|, we can ask for a finite number of these answers. Because\nthe ordering of streams is determined at construction time, however, the\nstream-based operators cannot even determine the first answer in that\ncollection. This is because the definition of \\scheme|always-five-bottom| is left recursive.  The fern-based operators, however, compute as many answers \nas desired:\n\n\\medskip\n\n\\mbox{\\scheme|(run-bottom 4 (always-five-bottom x))| \\schemeresult|=> `($\\{x/5\\}$ $\\{x/5\\}$ $\\{x/5\\}$ $\\{x/5\\}$)|}.\n\n\\medskip\n\n\n% \\scheme|(take-bottom #f ((==-bottom 1 x) empty-s)) =>| \\schemeresult|`($\\{x/1\\}$)|\n\n% \\scheme|(take-bottom #f ((conj-bottom (==-bottom 1 x) (==-bottom 2 x)) empty-s) =>|\n% \\schemeresult|`()|\n\n% \\scheme|(take-bottom #f ((disj-bottom (==-bottom 2 x) (==-bottom 3 x)) empty-s)) =>| \\schemeresult|`($\\{x/2\\}$ $\\{x/3\\}$)|\n\n% \\noindent With \\scheme|cons| instead of \\scheme|frons|, the following examples diverge:\n\n% \\scheme|(take-bottom 1 ((disj-bottom bottom (==-bottom 4 x)) empty-s)) =>| \\schemeresult|`($\\{x/4\\}$)|\n\n% \\scheme|(take-bottom 1 ((disj-bottom (==-bottom bottom x) (==-bottom 5 x)) empty-s)) =>| \\schemeresult|`($\\{x/5\\}$)|\n\n% \\noindent Without the occurs check, the following example also diverges\n% with \\scheme|cons| instead of \\scheme|frons|:\n\n% \\scheme|(take-bottom 1 ((disj-bottom (==-bottom `(,x) x) (==-bottom x 6)) empty-s)) =>|\n% \\schemeresult|`($\\{x/6\\}$)|\n\n% \\section{Helper Functions}\\label{lp-helpers}\n\n% To complete the implementation of the bottom-avoiding logic\n% programming operators presented in Section~\\ref{lp-system}, we provide\n% a logic variable constructor \\scheme|make-var|, a unification\n% algorithm \\scheme|unify|, and substitution helpers \\scheme|empty-s|,\n% \\scheme|ext-s|, and \\scheme|walk|. We represent logic variables by\n% R$^6$RS~\\cite{r6rs} records (syntactic layer); defining the record\n% type \\scheme|var| creates the constructor \\scheme|make-var|\n% automatically. We represent substitutions as association lists, and\n% use the triangular substitution model~\\cite{FBaade01}.\n\n% \\schemedisplayspace\n% \\schemeinput{fernscode/subst}\n", "meta": {"hexsha": "636263e7c5ef8a9b0e0a783bdc90d3035baece66", "size": 43870, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ferns.tex", "max_stars_repo_name": "holtzermann17/dissertation-single-spaced", "max_stars_repo_head_hexsha": "aca0e56a33916596c98709308342d9ccabd4718b", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 50, "max_stars_repo_stars_event_min_datetime": "2015-01-11T21:22:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T12:49:11.000Z", "max_issues_repo_path": "ferns.tex", "max_issues_repo_name": "holtzermann17/dissertation-single-spaced", "max_issues_repo_head_hexsha": "aca0e56a33916596c98709308342d9ccabd4718b", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-08-08T18:10:18.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-09T02:33:25.000Z", "max_forks_repo_path": "ferns.tex", "max_forks_repo_name": "holtzermann17/dissertation-single-spaced", "max_forks_repo_head_hexsha": "aca0e56a33916596c98709308342d9ccabd4718b", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-07-29T13:58:01.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-14T05:01:31.000Z", "avg_line_length": 32.7143922446, "max_line_length": 223, "alphanum_fraction": 0.7229541828, "num_tokens": 14376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.34232308015050855}}
{"text": "\\chapter{``Zfh'' and ``Zfhmin'' Standard Extensions for Half-Precision Floating-Point,\n  Version 1.0}\n\nThis chapter describes the Zfh standard extension for 16-bit half-precision\nbinary floating-point instructions compliant with the IEEE 754-2008 arithmetic\nstandard.\nThe Zfh extension depends on the single-precision floating-point extension, F.\nThe NaN-boxing scheme described in Section~\\ref{nanboxing} is extended to\nallow a half-precision value to be NaN-boxed inside a single-precision value\n(which may be recursively NaN-boxed inside a double- or quad-precision value\nwhen the D or Q extension is present).\n\n\\begin{commentary}\nThis extension primarily provides instructions that consume half-precision\noperands and produce half-precision results.\nHowever, it is also common to compute on half-precision data using higher\nintermediate precision.\nAlthough this extension provides explicit conversion instructions that suffice\nto implement that pattern, future extensions might further accelerate such\ncomputation with additional instructions that implicitly widen their\noperands---e.g., half$\\times$half$+$single$\\rightarrow$single---or implicitly\nnarrow their results---e.g., half$+$single$\\rightarrow$half.\n\\end{commentary}\n\n\\section{Half-Precision Load and Store Instructions}\n\nNew 16-bit variants of LOAD-FP and STORE-FP instructions are added,\nencoded with a new value for the funct3 width field.\n\n\\vspace{-0.2in}\n\\begin{center}\n\\begin{tabular}{M@{}R@{}F@{}R@{}O}\n\\\\\n\\instbitrange{31}{20} &\n\\instbitrange{19}{15} &\n\\instbitrange{14}{12} &\n\\instbitrange{11}{7} &\n\\instbitrange{6}{0} \\\\\n\\hline\n\\multicolumn{1}{|c|}{imm[11:0]} &\n\\multicolumn{1}{c|}{rs1} &\n\\multicolumn{1}{c|}{width} &\n\\multicolumn{1}{c|}{rd} &\n\\multicolumn{1}{c|}{opcode} \\\\\n\\hline\n12 & 5 & 3 & 5 & 7 \\\\\noffset[11:0] & base & H & dest & LOAD-FP \\\\\n\\end{tabular}\n\\end{center}\n\n\\vspace{-0.2in}\n\\begin{center}\n\\begin{tabular}{O@{}R@{}R@{}F@{}R@{}O}\n\\\\\n\\instbitrange{31}{25} &\n\\instbitrange{24}{20} &\n\\instbitrange{19}{15} &\n\\instbitrange{14}{12} &\n\\instbitrange{11}{7} &\n\\instbitrange{6}{0} \\\\\n\\hline\n\\multicolumn{1}{|c|}{imm[11:5]} &\n\\multicolumn{1}{c|}{rs2} &\n\\multicolumn{1}{c|}{rs1} &\n\\multicolumn{1}{c|}{width} &\n\\multicolumn{1}{c|}{imm[4:0]} &\n\\multicolumn{1}{c|}{opcode} \\\\\n\\hline\n7 & 5 & 5 & 3 & 5 & 7 \\\\\noffset[11:5] & src & base & H & offset[4:0] & STORE-FP \\\\\n\\end{tabular}\n\\end{center}\n\nFLH and FSH are only guaranteed to execute atomically if the effective address\nis naturally aligned.\n\nFLH and FSH do not modify the bits being transferred; in particular, the\npayloads of non-canonical NaNs are preserved.\nFLH NaN-boxes the result written to {\\em rd}, whereas FSH ignores all but\nthe lower 16 bits in {\\em rs2}.\n\n\\section{Half-Precision Computational Instructions}\n\nA new supported format is added to the format field of most\ninstructions, as shown in Table~\\ref{tab:fpextfmth}.\n\n\\begin{table}[htp]\n\\begin{center}\n\\begin{tabular}{|c|c|l|}\n\\hline\n{\\em fmt} field &\nMnemonic &\nMeaning \\\\\n\\hline\n00 & S & 32-bit single-precision \\\\\n01 & D & 64-bit double-precision \\\\\n10 & H & 16-bit half-precision \\\\\n11 & Q & 128-bit quad-precision \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\caption{Format field encoding.}\n\\label{tab:fpextfmth}\n\\end{table}\n\nThe half-precision floating-point computational instructions are\ndefined analogously to their single-precision counterparts, but operate on\nhalf-precision operands and produce half-precision results.\n\n\\vspace{-0.2in}\n\\begin{center}\n\\begin{tabular}{R@{}F@{}R@{}R@{}F@{}R@{}O}\n\\\\\n\\instbitrange{31}{27} &\n\\instbitrange{26}{25} &\n\\instbitrange{24}{20} &\n\\instbitrange{19}{15} &\n\\instbitrange{14}{12} &\n\\instbitrange{11}{7} &\n\\instbitrange{6}{0} \\\\\n\\hline\n\\multicolumn{1}{|c|}{funct5} &\n\\multicolumn{1}{c|}{fmt} &\n\\multicolumn{1}{c|}{rs2} &\n\\multicolumn{1}{c|}{rs1} &\n\\multicolumn{1}{c|}{rm} &\n\\multicolumn{1}{c|}{rd} &\n\\multicolumn{1}{c|}{opcode} \\\\\n\\hline\n5 & 2 & 5 & 5 & 3 & 5 & 7 \\\\\nFADD/FSUB & H & src2 & src1 & RM  & dest & OP-FP  \\\\\nFMUL/FDIV & H & src2 & src1 & RM  & dest & OP-FP  \\\\\nFMIN-MAX  & H & src2 & src1 & MIN/MAX & dest & OP-FP  \\\\\nFSQRT     & H & 0    & src  & RM  & dest & OP-FP  \\\\\n\\end{tabular}\n\\end{center}\n\n\\vspace{-0.2in}\n\\begin{center}\n\\begin{tabular}{R@{}F@{}R@{}R@{}F@{}R@{}O}\n\\\\\n\\instbitrange{31}{27} &\n\\instbitrange{26}{25} &\n\\instbitrange{24}{20} &\n\\instbitrange{19}{15} &\n\\instbitrange{14}{12} &\n\\instbitrange{11}{7} &\n\\instbitrange{6}{0} \\\\\n\\hline\n\\multicolumn{1}{|c|}{rs3} &\n\\multicolumn{1}{c|}{fmt} &\n\\multicolumn{1}{c|}{rs2} &\n\\multicolumn{1}{c|}{rs1} &\n\\multicolumn{1}{c|}{rm} &\n\\multicolumn{1}{c|}{rd} &\n\\multicolumn{1}{c|}{opcode} \\\\\n\\hline\n5 & 2 & 5 & 5 & 3 & 5 & 7 \\\\\nsrc3 & H & src2 & src1 & RM  & dest & F[N]MADD/F[N]MSUB  \\\\\n\\end{tabular}\n\\end{center}\n\n\\section{Half-Precision Conversion and Move Instructions}\n\nNew floating-point-to-integer and integer-to-floating-point conversion\ninstructions are added.  These instructions are defined analogously to the\nsingle-precision-to-integer and integer-to-single-precision conversion\ninstructions.  FCVT.W.H or FCVT.L.H converts a half-precision floating-point\nnumber to a signed 32-bit or 64-bit integer, respectively.  FCVT.H.W or\nFCVT.H.L converts a 32-bit or 64-bit signed integer, respectively, into a\nhalf-precision floating-point number. FCVT.WU.H, FCVT.LU.H, FCVT.H.WU, and\nFCVT.H.LU variants convert to or from unsigned integer values.  FCVT.L[U].H and\nFCVT.H.L[U] are RV64-only instructions.\n\n\\vspace{-0.2in}\n\\begin{center}\n\\begin{tabular}{R@{}F@{}R@{}R@{}F@{}R@{}O}\n\\\\\n\\instbitrange{31}{27} &\n\\instbitrange{26}{25} &\n\\instbitrange{24}{20} &\n\\instbitrange{19}{15} &\n\\instbitrange{14}{12} &\n\\instbitrange{11}{7} &\n\\instbitrange{6}{0} \\\\\n\\hline\n\\multicolumn{1}{|c|}{funct5} &\n\\multicolumn{1}{c|}{fmt} &\n\\multicolumn{1}{c|}{rs2} &\n\\multicolumn{1}{c|}{rs1} &\n\\multicolumn{1}{c|}{rm} &\n\\multicolumn{1}{c|}{rd} &\n\\multicolumn{1}{c|}{opcode} \\\\\n\\hline\n5 & 2 & 5 & 5 & 3 & 5 & 7 \\\\\nFCVT.{\\em int}.H & H & W[U]/L[U] & src & RM  & dest & OP-FP  \\\\\nFCVT.H.{\\em int} & H & W[U]/L[U] & src & RM  & dest & OP-FP  \\\\\n\\end{tabular}\n\\end{center}\n\nNew floating-point-to-floating-point conversion instructions are added.  These\ninstructions are defined analogously to the double-precision\nfloating-point-to-floating-point conversion instructions.\nFCVT.S.H or FCVT.H.S converts a half-precision floating-point number to\na single-precision floating-point number, or vice-versa, respectively.\nIf the D extension is present, FCVT.D.H or FCVT.H.D converts a half-precision\nfloating-point number to a double-precision floating-point number, or\nvice-versa, respectively.\nIf the Q extension is present, FCVT.Q.H or FCVT.H.Q converts a half-precision\nfloating-point number to a quad-precision floating-point number, or\nvice-versa, respectively.\n\n\\vspace{-0.2in}\n\\begin{center}\n\\begin{tabular}{R@{}F@{}R@{}R@{}F@{}R@{}O}\n\\\\\n\\instbitrange{31}{27} &\n\\instbitrange{26}{25} &\n\\instbitrange{24}{20} &\n\\instbitrange{19}{15} &\n\\instbitrange{14}{12} &\n\\instbitrange{11}{7} &\n\\instbitrange{6}{0} \\\\\n\\hline\n\\multicolumn{1}{|c|}{funct5} &\n\\multicolumn{1}{c|}{fmt} &\n\\multicolumn{1}{c|}{rs2} &\n\\multicolumn{1}{c|}{rs1} &\n\\multicolumn{1}{c|}{rm} &\n\\multicolumn{1}{c|}{rd} &\n\\multicolumn{1}{c|}{opcode} \\\\\n\\hline\n5 & 2 & 5 & 5 & 3 & 5 & 7 \\\\\nFCVT.S.H & S & H & src & RM  & dest & OP-FP  \\\\\nFCVT.H.S & H & S & src & RM  & dest & OP-FP  \\\\\nFCVT.D.H & D & H & src & RM  & dest & OP-FP  \\\\\nFCVT.H.D & H & D & src & RM  & dest & OP-FP  \\\\\nFCVT.Q.H & Q & H & src & RM  & dest & OP-FP  \\\\\nFCVT.H.Q & H & Q & src & RM  & dest & OP-FP  \\\\\n\\end{tabular}\n\\end{center}\n\nFloating-point to floating-point sign-injection instructions, FSGNJ.H,\nFSGNJN.H, and FSGNJX.H are defined analogously to the single-precision\nsign-injection instruction.\n\n\\vspace{-0.2in}\n\\begin{center}\n\\begin{tabular}{R@{}F@{}R@{}R@{}F@{}R@{}O}\n\\\\\n\\instbitrange{31}{27} &\n\\instbitrange{26}{25} &\n\\instbitrange{24}{20} &\n\\instbitrange{19}{15} &\n\\instbitrange{14}{12} &\n\\instbitrange{11}{7} &\n\\instbitrange{6}{0} \\\\\n\\hline\n\\multicolumn{1}{|c|}{funct5} &\n\\multicolumn{1}{c|}{fmt} &\n\\multicolumn{1}{c|}{rs2} &\n\\multicolumn{1}{c|}{rs1} &\n\\multicolumn{1}{c|}{rm} &\n\\multicolumn{1}{c|}{rd} &\n\\multicolumn{1}{c|}{opcode} \\\\\n\\hline\n5 & 2 & 5 & 5 & 3 & 5 & 7 \\\\\nFSGNJ & H & src2 & src1 & J[N]/JX & dest & OP-FP  \\\\\n\\end{tabular}\n\\end{center}\n\n\nInstructions are provided to move bit patterns between the floating-point and\ninteger registers.\nFMV.X.H moves the half-precision value in floating-point register {\\em rs1} to\na representation in IEEE 754-2008 standard encoding in integer register {\\em\nrd}, filling the upper XLEN-16 bits with copies of the floating-point number's\nsign bit.\n\nFMV.H.X moves the half-precision value encoded in IEEE 754-2008 standard\nencoding from the lower 16 bits of integer register {\\em rs1} to the\nfloating-point register {\\em rd}, NaN-boxing the result.\n\nFMV.X.H and FMV.H.X do not modify the bits being transferred; in particular,\nthe payloads of non-canonical NaNs are preserved.\n\n\\vspace{-0.2in}\n\\begin{center}\n\\begin{tabular}{R@{}F@{}R@{}R@{}F@{}R@{}O}\n\\\\\n\\instbitrange{31}{27} &\n\\instbitrange{26}{25} &\n\\instbitrange{24}{20} &\n\\instbitrange{19}{15} &\n\\instbitrange{14}{12} &\n\\instbitrange{11}{7} &\n\\instbitrange{6}{0} \\\\\n\\hline\n\\multicolumn{1}{|c|}{funct5} &\n\\multicolumn{1}{c|}{fmt} &\n\\multicolumn{1}{c|}{rs2} &\n\\multicolumn{1}{c|}{rs1} &\n\\multicolumn{1}{c|}{rm} &\n\\multicolumn{1}{c|}{rd} &\n\\multicolumn{1}{c|}{opcode} \\\\\n\\hline\n5 & 2 & 5 & 5 & 3 & 5 & 7 \\\\\nFMV.X.H & H & 0    & src  & 000  & dest & OP-FP  \\\\\nFMV.H.X & H & 0    & src  & 000  & dest & OP-FP  \\\\\n\\end{tabular}\n\\end{center}\n\n\\section{Half-Precision Floating-Point Compare Instructions}\n\nThe half-precision floating-point compare instructions are\ndefined analogously to their single-precision counterparts, but operate on\nhalf-precision operands.\n\n\\vspace{-0.2in}\n\\begin{center}\n\\begin{tabular}{S@{}F@{}R@{}R@{}F@{}R@{}O}\n\\\\\n\\instbitrange{31}{27} &\n\\instbitrange{26}{25} &\n\\instbitrange{24}{20} &\n\\instbitrange{19}{15} &\n\\instbitrange{14}{12} &\n\\instbitrange{11}{7} &\n\\instbitrange{6}{0} \\\\\n\\hline\n\\multicolumn{1}{|c|}{funct5} &\n\\multicolumn{1}{c|}{fmt} &\n\\multicolumn{1}{c|}{rs2} &\n\\multicolumn{1}{c|}{rs1} &\n\\multicolumn{1}{c|}{rm} &\n\\multicolumn{1}{c|}{rd} &\n\\multicolumn{1}{c|}{opcode} \\\\\n\\hline\n5 & 2 & 5 & 5 & 3 & 5 & 7 \\\\\nFCMP & H & src2 & src1 & EQ/LT/LE & dest & OP-FP  \\\\\n\\end{tabular}\n\\end{center}\n\n\\section{Half-Precision Floating-Point Classify Instruction}\n\nThe half-precision floating-point classify instruction, FCLASS.H, is\ndefined analogously to its single-precision counterpart, but operates on\nhalf-precision operands.\n\n\\vspace{-0.2in}\n\\begin{center}\n\\begin{tabular}{S@{}F@{}R@{}R@{}F@{}R@{}O}\n\\\\\n\\instbitrange{31}{27} &\n\\instbitrange{26}{25} &\n\\instbitrange{24}{20} &\n\\instbitrange{19}{15} &\n\\instbitrange{14}{12} &\n\\instbitrange{11}{7} &\n\\instbitrange{6}{0} \\\\\n\\hline\n\\multicolumn{1}{|c|}{funct5} &\n\\multicolumn{1}{c|}{fmt} &\n\\multicolumn{1}{c|}{rs2} &\n\\multicolumn{1}{c|}{rs1} &\n\\multicolumn{1}{c|}{rm} &\n\\multicolumn{1}{c|}{rd} &\n\\multicolumn{1}{c|}{opcode} \\\\\n\\hline\n5 & 2 & 5 & 5 & 3 & 5 & 7 \\\\\nFCLASS & H & 0 & src & 001 & dest & OP-FP  \\\\\n\\end{tabular}\n\\end{center}\n\n\\section{``Zfhmin'' Standard Extension for Minimal Half-Precision Floating-Point Support}\n\nThis section describes the Zfhmin standard extension, which provides minimal\nsupport for 16-bit half-precision binary floating-point instructions.\nThe Zfhmin extension is a subset of the Zfh extension, consisting only\nof data transfer and conversion instructions.\nLike Zfh, the Zfhmin extension depends on the single-precision floating-point\nextension, F.\nThe expectation is that Zfhmin software primarily uses the half-precision\nformat for storage, performing most computation in higher precision.\n\nThe Zfhmin extension includes the following instructions from the Zfh\nextension: FLH, FSH, FMV.X.H, FMV.H.X, FCVT.S.H, and FCVT.H.S.\nIf the D extension is present, the FCVT.D.H and FCVT.H.D instructions are\nalso included.\nIf the Q extension is present, the FCVT.Q.H and FCVT.H.Q instructions are\nadditionally included.\n\n\\begin{commentary}\nZfhmin does not include the FSGNJ.H instruction, because it suffices to\ninstead use the FSGNJ.S instruction to move half-precision values between\nfloating-point registers.\n\\end{commentary}\n\n\\begin{commentary}\nHalf-precision addition, subtraction, multiplication, division, and\nsquare-root operations can be faithfully emulated by converting the\nhalf-precision operands to single-precision, performing the operation\nusing single-precision arithmetic, then converting back to\nhalf-precision~\\cite{roux:hal-01091186}.\nPerforming half-precision fused multiply-addition using this method incurs\na 1-ulp error on some inputs for the RNE and RMM rounding modes.\n\nConversion from 8- or 16-bit integers to half-precision can be emulated by\nfirst converting to single-precision, then converting to half-precision.\nConversion from 32-bit integer can be emulated by first converting to\ndouble-precision.\nIf the D extension is not present and a 1-ulp error under RNE or RMM is\ntolerable, 32-bit integers can be first converted to single-precision instead.\nThe same remark applies to conversions from 64-bit integers without the Q\nextension.\n\\end{commentary}\n", "meta": {"hexsha": "e215ed415b6c22cdf620a03899e0c851269b0f02", "size": 13192, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/zfh.tex", "max_stars_repo_name": "frantony/riscv-isa-manual", "max_stars_repo_head_hexsha": "25d7fc01be062b052759627333a2cb3241730910", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/zfh.tex", "max_issues_repo_name": "frantony/riscv-isa-manual", "max_issues_repo_head_hexsha": "25d7fc01be062b052759627333a2cb3241730910", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/zfh.tex", "max_forks_repo_name": "frantony/riscv-isa-manual", "max_forks_repo_head_hexsha": "25d7fc01be062b052759627333a2cb3241730910", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6354916067, "max_line_length": 89, "alphanum_fraction": 0.6976955731, "num_tokens": 4533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.34232307176218396}}
{"text": "\\documentclass[11pt, oneside]{article}   \t% use \"amsart\" instead of \"article\" for AMSLaTeX format\n\\usepackage{geometry}                \t\t% See geometry.pdf to learn the layout options. There are lots.\n\\geometry{letterpaper}                   \t\t% ... or a4paper or a5paper or ... \n%\\geometry{landscape}                \t\t% Activate for rotated page geometry\n%\\usepackage[parfill]{parskip}    \t\t% Activate to begin paragraphs with an empty line rather than an indent\n\\usepackage{graphicx}\t\t\t\t% Use pdf, png, jpg, or eps§ with pdflatex; use eps in DVI mode\n\t\t\t\t\t\t\t\t% TeX will automatically convert eps --> pdf in pdflatex\t\t\n\\usepackage{amssymb}\n\n%SetFonts\n\n%SetFonts\n\n%\\newcommand{\\vectr}[1]{\\mathbf{#1}}\n\\newcommand{\\vectr}[1]{\\hbox{\\boldmath$#1$}}\n\\newcommand{\\tensor}[1]{\\hbox{\\boldmath$#1$}}\n\n\n\\title{Turbulent Inflow Tool}\n\\author{Jay and Peter}\n%\\date{}\t\t\t\t\t\t\t% Activate to display a given date or no date\n\n\\begin{document}\n\\maketitle\n\n\\section{Abstract}\n\nThis tool helps you to create all necessary input to utilize the turbulent inflow boundary condition in OpenFOAM.\n\n\\section{Theory}\n\nWait for Jay's write-up.\n\n\\subsection{Uniform model}\n\n\\begin{equation}\n   u = \\bar\\phi\n   \\label{Eq1}\n\\end{equation}\n\n\\begin{equation}\n   \\vectr{u} = u\\,\\vectr{N}\n   \\label{Eq2}\n\\end{equation}\n\n\\subsection{Exponential model}\n\n\\begin{equation}\n   \\phi = \\bar\\phi \\left( \\frac{\\vectr{n} \\cdot \\vectr{x} }{d_0} \\right)^\\alpha\n   \\label{Eq11}\n\\end{equation}\n\n\\begin{equation}\n   \\ell_{u,y} = R_{uy:ux} \\, \\ell_{u,x}   \\qquad   \\ell_{u,z} = R_{uz:ux} \\, \\ell_{u,x}\n   \\label{Eq12}\n\\end{equation}\n\\begin{equation}\n   \\ell_{v,y} = R_{vy:vx} \\, \\ell_{v,x}   \\qquad   \\ell_{v,z} = R_{vz:vx} \\, \\ell_{v,x}\n   \\label{Eq13}\n\\end{equation}\n\\begin{equation}\n   \\ell_{w,y} = R_{wy:wx} \\, \\ell_{w,x}   \\qquad   \\ell_{w,z} = R_{wz:wx} \\, \\ell_{w,x}\n   \\label{Eq14}\n\\end{equation}\n\n\n\n\\end{document}  ", "meta": {"hexsha": "92e3d9e6e1fddeb5dadfe7bdfa880f6a13b24b9c", "size": 1873, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/help/theory.tex", "max_stars_repo_name": "moreff/TurbulenceInflowTool", "max_stars_repo_head_hexsha": "c2885a3a8c93736f6af93bc51caf33fb0e6506c7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2020-04-05T22:06:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:28:43.000Z", "max_issues_repo_path": "docs/help/theory.tex", "max_issues_repo_name": "moreff/TurbulenceInflowTool", "max_issues_repo_head_hexsha": "c2885a3a8c93736f6af93bc51caf33fb0e6506c7", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-06-08T13:32:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-14T08:45:08.000Z", "max_forks_repo_path": "docs/help/theory.tex", "max_forks_repo_name": "moreff/TurbulenceInflowTool", "max_forks_repo_head_hexsha": "c2885a3a8c93736f6af93bc51caf33fb0e6506c7", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2020-07-01T13:27:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-24T04:33:07.000Z", "avg_line_length": 27.5441176471, "max_line_length": 113, "alphanum_fraction": 0.6486919381, "num_tokens": 656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3423230717621839}}
{"text": "\\documentclass[10pt]{book}\n\\usepackage[german]{babel}\n\\usepackage[utf8]{inputenc}\n\\usepackage{fancyhdr}\n\\usepackage{amsmath}\n\\usepackage{calc}\n\\usepackage{listings}\n\\usepackage{hyperref}\n\\usepackage{tikz-network}\n\\usetikzlibrary{decorations.pathreplacing,calc}\n\\usepackage{multicol}\n\n\\newcommand{\\ueberschrift}{How does a neural net, work?}\n\n\\title{\\ueberschrift}\n\\author{Philipp Zettl}\n\n\\begin{document}\n    \\pagestyle{fancy}\n    \\maketitle\n\n    At some point one can write a preamble to explain what a NN is, what to use it for\n    and why it's actually better for us to use them then old numerical methods like the euler method to\n    calculate the root(s) of a function\n\n    \\chapter{Neural Networks}\n    Neural networks are a widely used technique to solve complex problems in a very simplified mathematical\n    way. There are many different implementations of neural networks, but they all share the same core idea.\n\n    \\textbf{F}eed \\textbf{f}orward \\textbf{n}eural \\textbf{n}etworks, a type or neural network, are a great entry point to start discovering\n    neural networks. The following chapter will introduce the idea of general neural networks and use this motivation\n    to discover the first type of neural networks.\n    \\section{Motivation}\n    Unlike us humans computers have rather a hard time recognizing handwritten characters, digits or even full words.\n    Humans taught themselves over millions of years of evolution how to recognize things.\\\\\n    Since handwriting is mostly unique to a person one will have a hard time implementing an algorithm to detect digits from handwritten text,\n    using an enormous amount of \\lstinline{if/else} conditions will be the least problem, but figuring out how to provide a stable algorithmically solution\n    to this problem seems impossible.\n    Nowadays we can use neural networks to mock this behavior and create models to do that task for us.\n    In the following chapter I will describe how to create such model as well as how to train it using real live\n    examples.\n\n    To train a NN one uses a so called \\dq Training-Set\\dq of data to \\dq teach\\dq the network what prediction to give for a given input. In some way we can assume\n    achieving similar results using equal training data sets.\\\\\n    But wait, how does a neural net, work?\\\\    \n    Now let us construct a basic neural network.\n    \\section{General NN}\n    To define the structure of Neural Networks we need to define a bunch of\n    technical terms. In biology we differentiate between different types of neurons.\n    Perceptrons, a type of neuron, are basically binary decision makers having \\(n\\) input values and a single output value.\n    We can illustrate them using the following notation.\n    \\begin{figure}[h]\n        \\begin{center}\n            \\begin{tikzpicture}\n                \\Vertex[x=0,y=0,label=$x_1$]{A}\n                \\Vertex[x=0,y=-1,label=$x_2$]{B}\n                \\Vertex[x=0,y=-2,label=$x_3$]{C}\n                \\Vertex[x=2,y=-1,label=$p_1$]{D}\n                \\Vertex[x=4,y=-1,label=$o_1$]{F}\n                \\Edge(A)(D)\n                \\Edge(B)(D)\n                \\Edge(C)(D)\n                \\Edge(D)(F)\n            \\end{tikzpicture}\n        \\end{center}\n        \\caption{Simple illustration of a single perceptron.\\label{fig:Perceptron}}\n    \\end{figure}\n    This model was introduced in 1958 by Frank Rosenblatt. He proposed a simple, yet complicate,\n    rule to compute the output value of a perceptron. He introduced weights \\(w_i\\) to express the importance\n    of an input value \\(x_i\\) to compute the output value \\(o_i\\).\n    \\begin{align}\n        o_i =\n        \\left\\{\n            \\begin{matrix}\n                0 & \\text{if } \\sum_j w_ix_i \\leq t\\\\\n                1 & \\text{if } \\sum_j w_ix_i > t\n            \\end{matrix}\n        \\right.\n        \\label{eq:perceptron}\n    \\end{align}\n    with \\(t\\) a threshold.\n    Obviously a single perceptron is not even close to real human decision making and building\n    a neural net out of a single perceptron seems simply too unflexible and stiff.\n    But it works great to illustrate the idea behind a complex model without using too complicated notations,\n    we can imagine a perceptron being a single element of a complex model to make a more detailed decision.\\\\\n    Hence a NN in the from\\\\\n    \\begin{figure}[h]\n        \\begin{center}\n            \\begin{tikzpicture}\n                \\Vertex[x=-4,y=-0.5,Pseudo,label=$i_1$]{i1}\n                \\Vertex[x=-4,y=-1.5,Pseudo,label=$i_2$]{i2}\n\n                \\Vertex[x=-2,y=0]{A}\n                \\Vertex[x=-2,y=-1]{B}\n                \\Vertex[x=-2,y=-2]{C}\n\n                \\Vertex[x=0,y=1]{a}\n                \\Vertex[x=0,y=0]{b}\n                \\Vertex[x=0,y=-1]{c}\n                \\Vertex[x=0,y=-2]{d}\n                \\Vertex[x=0,y=-3]{e}\n\n                \\Vertex[x=2,y=-1]{D}\n                \\Vertex[x=4,y=-1,Pseudo,label=$o_1$]{F}\n\n                \\Edge(i1)(A)\n                \\Edge(i1)(B)\n                \\Edge(i1)(C)\n                \\Edge(i2)(A)\n                \\Edge(i2)(B)\n                \\Edge(i2)(C)\n\n                \\Edge(A)(a)\n                \\Edge(B)(a)\n                \\Edge(C)(a)\n\n                \\Edge(A)(b)\n                \\Edge(B)(b)\n                \\Edge(C)(b)\n\n                \\Edge(A)(c)\n                \\Edge(B)(c)\n                \\Edge(C)(c)\n\n                \\Edge(A)(d)\n                \\Edge(B)(d)\n                \\Edge(C)(d)\n\n                \\Edge(A)(e)\n                \\Edge(B)(e)\n                \\Edge(C)(e)\n\n                \\Edge(a)(D)\n                \\Edge(b)(D)\n                \\Edge(c)(D)\n                \\Edge(d)(D)\n                \\Edge(e)(D)\n                \\Edge(D)(F)\n            \\end{tikzpicture}\n        \\end{center}\n        \\caption{Simple illustration of a NN using multiple perceptrons.\\label{fig:simpleNN}}\n    \\end{figure}\\\\\n    will perform a more detailed analysis then (Figure \\ref{fig:Perceptron}).\\\\\n    A network consists of the input values \\(i_j\\), several columns of perceptrons – we will call them from now on layers – and the output \\(o_j\\).\n    The above illustrated network contains 3 layers of perceptrons. The first layer is making three simple decisions out of the input data,\n    then forwards these decisions to the second layer of perceptrons, which will make 5 decisions out of each of the previous 3 decisions by weighting their\n    outputs. Before we can analyse the above displayed network in more detail we need to introduce a good notation, how to call a single perceptron.\n    Say we have \\(l > 0\\) layers in our network and use \\(n\\) input values \\(i_1, i_2, ..., i_n\\) to predict \\(m\\) output values \\(o_1, o_2, ..., o_m\\).\n    Then we call the \\(i^{\\text{th}}\\) perceptron of the \\(l^{\\text{th}}\\) layer\n    \\begin{align}\n        p_i^l\n    \\end{align}\n    \n    Now let's take a more detailed look at our network and calculate the amount of decisions we actually perform.\\\\\n    We have two input values \\(i_1\\) and \\(i_2\\), based on each we perform 3 decisions, so after processing the first layer \\(l=1\\) of perceptrons we made\n    \\begin{align}\n        n_l\\cdot \\underbrace{n_{l-1}}_{=n} = 3\\cdot 2 = 6\n    \\end{align}\n    decisions. Moving on to the second layer we again count the number of perceptrons in the current layer \\(n_2 = 5\\) and\n    multiply it with the amount of perceptrons in the previous layer\n    \\begin{align}\n        \\Rightarrow n_2 \\cdot n_1 = 5 \\cdot 3 = 15\n    \\end{align}\n    And for the third layer \\(l=3\\) with one perceptron we perform \\(5\\) decision.\\\\\n    We also need to include the last layer into the calculation with a single perceptron.\n    Adding those values together \\(6+15+5+1 = 27\\), we actually perform 27 decisions for a single output.\n\n    This makes us assume that increasing the amount of layers and perceptrons per layer will increase the complexity\n    behind a decision and therefor a big neural network the way to compute complex and sophisticated decisions.\n\n    In \\eqref{eq:perceptron} we introduced a way how to calculate the output of a perceptron, we will change this notation\n    a bit to achieve a way to calculate the outcome of a whole NN, not just a single perceptron of it.\n    The previous notation of \\(\\sum_j w_jx_j > t\\) can be written as a dot product \\(w \\cdot x\\), where \\(w\\) and \\(x\\) are \n    vectors whose components are the weights and input values respectively. The second change is to move the \n    threshold from the right side of the inequality. But before we do that we rename it to its widely used name \\dq Bias\\dq, \\(b = -t\\)\n    using these changes we can write a perceptron now using\n    \\begin{align}\n        o_i =\n        \\left\\{\n            \\begin{matrix}\n                0 & \\text{if } w\\cdot x + b \\leq 0\\\\\n                1 & \\text{if } w\\cdot x + b > 0\n            \\end{matrix}\n        \\right.\n        \\label{eq:firstNN}\n    \\end{align}\n    Think of the bias as how easy it is to get 1 out of the perceptron. Or in a more biological\n    way, the bias is a measure of how easy it is to get the perceptron to \\textit{fire}.\\newline\n    Previous descriptions of perceptrons were based on the idea that a perceptron implements a method of weighting\n    input values to make decisions. A more CS way to use perceptrons would be to compute elementary logical functions\n    such as \\lstinline{AND, OR, NOR, XOR, ...} So we can for example build a network having the weights \\(-2\\) and the bias of \\(3\\), like this \n    \\begin{figure}[h]\n        \\begin{center}\n            \\begin{tikzpicture}\n                \\Vertex[x=0,y=0,label=$x_1$]{A}\n                \\Vertex[x=0,y=-2,label=$x_2$]{B}\n                \\Vertex[x=2,y=-1,label=$p_1$]{D}\n                \\Vertex[x=4,y=-1,label=$o_1$]{F}\n                \\Edge[label=$-2$](A)(D)\n                \\Edge[label=$-2$](B)(D)\n                \\Edge(D)(F)\n            \\end{tikzpicture}\n        \\end{center}\n        \\caption{Logical \\lstinline{NAND} gate.\\label{fig:NANDGate}}\n    \\end{figure}\n    The above displayed NN \\ref{fig:NANDGate} implements a so called \\lstinline{NAND}-Gate.\n    An input of \\(x = \\begin{pmatrix}0, 0\\end{pmatrix}^T\\) results in \\((-2)\\cdot 0 + (-2) \\cdot 0 + 3 = 3 \\Rightarrow o_1 = 1\\).\n    Similar calculations reveal that the inputs \\(\\begin{pmatrix}0, 1\\end{pmatrix}^T, \\begin{pmatrix}1, 0\\end{pmatrix}^T\\) produce the output\n    \\(1\\), but \\(\\begin{pmatrix}1, 1\\end{pmatrix}^T\\) results in \\((-2)\\cdot 1 + (-2)\\cdot 1 + 3 = -1\\) therefor \\(o_1 = 0\\).\n    To make it even more obvious lets take a look at a simple truth table from the first semester, some of you might even know that stuff since their born, anyway.\n    \\begin{center}\n        \\begin{tabular}{c|c|c|c}\n            A & B & A\\&B & !(A\\&B)\\\\\n            \\hline\n            1 & 0 & 0 & 1\\\\\n            1 & 1 & 1 & 0\\\\\n            0 & 0 & 0 & 1\\\\\n            0 & 1 & 0 & 1\\\\\n        \\end{tabular}\n    \\end{center}\n    as we can see the above mentioned results of our NN are equal to a regular \\lstinline{NAND} operation.\n\n    This \\lstinline{NAND} example shows that we can use perceptrons to compute simple logical functions. In fact we can use \n    perceptrons to compute \\textbf{any} logical function. But the reason for this is not the flexibility or any other aspect of neural networks\n    or perceptrons per se, this is due to the universal definition of logical operations.\n    Since we can recreate these universal definitions it follows that a perceptron is a similar universal definition of an operation.\n    This fact is actually quite disappointing because it seems it's merely possible achieve something more complex then combinations of \\lstinline{NAND}\n    gates and other logical operations. But on the other hand it might be reassuring to know that NNs are as powerful as modern computers.\n\n    But don't take this introduction too serious, keep in mind we did not cover learning algorithms yet. Which open up\n    a whole new world. We will use these learning algorithms to adjust weights and biases automatically within a network of\n    artificial neurons. There are several methods of training all respond to external stimuli and do not require manual adjustments by\n    a programmer. These algorithms allow us to use artificial neurons in a way which is radically different from\n    logical gates. Instead of explicitly laying out a logical function our networks can simply learn to solve problems, which are way beyond\n    simple conventional logical gates.\n    \n    \\section{Activated Neurons}\n    Writing a learning algorithm sounds scary on first glance, but how can one achieve such behavior for a neural network?\n    Suppose we have a network of perceptrons as previously described which we want to use to solve a problem. For example, the inputs\n    to the network might be raw pixels from a scanned, handwritten image of a digit. And we'd like our network to learn it's weights and biases so that the\n    output correctly classifies the digit within the image. To illustrate how learning might work we make small adjustments to the weights (or biases) of the network.\n    We want those changes in the weights to be small to cause only small changes in the corresponding output from the network. Those changes will be called\n    \\(\\Delta w, \\Delta b\\) and \\(\\Delta o\\). Suppose we input an image of a 9 and the network classifies this input as a 8, we then could figure out how to make a small\n    change to the weights or biases so the network gets a bit closer to classify the image as a 9. We then repeat this process over and over again. The network is learning.\n\n    Unfortunately our current definition of neural networks is not able to achieve this behavior using the perceptron model. Doing small adjustments on their weights and values\n    will cause big changes in the networks output. This is due to the restriction in the binary output of perceptrons. Sometimes a change in a single weight flips a perceptrons output\n    and the results in a complete different output of the network. So while the expected 9 might be classified correctly the behavior of the network in respect to other inputs\n    might vary drastically. That makes it difficult to see how to gradually modify the weights and biases so the network achieves expected results.\n\n    We simply overcome this issue with introducing a new type of neuron, the sigmoid neuron. Sigmoids are similar to perceptrons, with the small difference that small changes in their weights and biases cause only\n    small changes in the networks output. That's a necessary feature to allow networks of sigmoids to learn. We depict sigmoids the same way as perceptrons. \n\n    \\begin{figure}[h]\n        \\begin{center}\n            \\begin{tikzpicture}\n                \\Vertex[x=0,y=0,label=$x_1$]{A}\n                \\Vertex[x=0,y=-1,label=$x_2$]{B}\n                \\Vertex[x=0,y=-2,label=$x_3$]{C}\n                \\Vertex[x=2,y=-1,label=$p_1$]{D}\n                \\Vertex[x=4,y=-1,label=$o_1$]{F}\n                \\Edge(A)(D)\n                \\Edge(B)(D)\n                \\Edge(C)(D)\n                \\Edge(D)(F)\n            \\end{tikzpicture}\n        \\end{center}\n        \\caption{Illustration of a Sigmoid Neuron.\\label{fig:Sigmoid}}\n    \\end{figure}\n    Just like the perceptron the sigmoid neuron gets \\(n\\) input values \\(x_i, i=1, ...,n\\) but instead of forcing those values to be binary,\n    they can be any number between \\(0\\) and \\(0\\), so \\(x_i \\in [0, 1]\\) as well as the perceptron the sigmoid neuron has a weight \\(w\\) for each input and overall biases \\(b\\). But it's output is\n    again not binary. Instead it's \\(\\sigma(w \\cdot x + b)\\), where \\(\\sigma\\) is the \\textit{sigmoid} function (also called logistical function),\n    \\begin{multicols}{2}\n        \\includegraphics[width=.45\\textwidth]{sigmoid.eps}\n        \n        \\columnbreak\n        \\vspace*{.6cm}\n\n        \\begin{align}\n            \\sigma(z) = \\frac{1}{1+e^{-z}}\n        \\end{align}\n\n    \\end{multicols}\n    to be more precise the output of a sigmoid neuron is\n    \\begin{align}\n        \\frac{1}{1+e^{-w \\cdot x - b}}\n    \\end{align}\n    To understand the similarity between the previously discussed perceptron neuron and the sigmoid neuron, suppose\n    \\(z = w \\cdot x + b\\) is a large positive number. Then \\(e^{-z} \\approx 0\\) so \\(\\sigma(z) \\approx 1\\). Or just\n    \\dq Is \\(z\\) large and positive, the output is approximately 1\\dq, just like for the perceptron. So \\(\\sigma\\) is a way\n    to enforce values being \\(\\in [0, 1]\\). One can achieve the behavior of perceptrons by redefining \\(\\sigma\\) as in \\eqref{eq:firstNN}.\n    So Sigmoid Neurons are \\dq just\\dq smoothened perceptrons. But exactly this smoothening is the crucial fact which allows learning.\n    This smoothness means that small changes in weights \\(\\Delta w\\) and biases \\(\\Delta b\\) will produce a small change in the output \\(\\Delta o\\).\n    Hence we achieve the same behavior of perceptrons with the additional effect of being able to predict the change in output which will occur while\n    modifying a weight or bias within the network.\n    In fact, calculus tells us how to calculate that change as\n    \\begin{align}\n        \\Delta o \\approx \\sum \\limits_{j=1}^n \\frac{\\partial o}{\\partial w_j} \\Delta w_j + \\frac{\\partial o}{\\partial b} \\Delta b\n    \\end{align}\n    where \\(\\frac{\\partial o}{\\partial w_j}\\) denote partial derivatives of the output with respect to \\(w_j\\) and \\(b\\) respectively.\n    This might sound overwhelming in the beginning and partial derivatives aren't that easy to understand. But what we can see from here\n    is that \\(\\Delta o\\) is a linear function, since it's a combination of the linear function \\(\\Delta w\\) and \\(\\Delta b\\). Therefor\n    a small change in weights or biases will cause only a small change in the output. So while sigmoid neurons have much of the same quality\n    as perceptrons, they make it easier to figure out which weights and biases to adjust in order to achieve a small change of the output\n    into a desired direction.\\newline\n    \n    \\section{Summary}\n    We've discussed two types of neurons in this chapter. The perceptron which is ideal to reconstruct logical\n    functions and the sigmoid neuron, which has exactly the same features as the perceptron\n    with the addition that we can perform small adjustments to modify the used weights and biases in order\n    to \\dq train \\dq the model. This brings one big conclusion. When we talk about neurons we can assume these given values:\n    \\begin{enumerate}\n        \\item \\(n:=\\) Number input elements\n        \\item \\(m:=\\) Number output elements\n        \\item \\(n_l:=\\) Number desired \\dq layers\\dq of neurons\n        \\item Type of neurons in layer \\(l\\)\n    \\end{enumerate}\n    Depending on the type of neuron, the behavior differs. But what is the actual difference between the sigmoid neuron and the perceptron?\n    The answer is quite easy. The main and mostly only difference is their activation function.\n    \\begin{figure}[h]\n        \\includegraphics[width=\\textwidth]{activation_functions.eps}\n    \\end{figure}\n    Both clamp the values \\(o \\in [0,1]\\), but the smoothness of the sigmoid function allows learning behavior.\n    \n    \\subsection{Important things to remember}\n    Imagine having a big network of perceptrons. Multiplying every weight and bias within this network with a constant \\(c > 0\\) will \\underline{\\textbf{not}} change the overall network output.\n\n    \\section{Network architecture}\n    Over the next section we will introduce a neural network that can do a pretty good job classifying handwritten digits. It helps to first introduce some terminology\n    that lets us name different parts of the network.\n    Suppose we have the previously mentioned network\n\n    \\begin{figure}[h]\n        \\begin{center}\n            \\begin{tikzpicture}\n                \\Vertex[x=-4,y=-0.5,Pseudo,label=$i_1$]{i1}\n                \\Vertex[x=-4,y=-1.5,Pseudo,label=$i_2$]{i2}\n\n                \\Vertex[x=-4,y=-4,Pseudo]{B0}\n\n                \\Vertex[x=-2,y=0]{A}\n                \\Vertex[x=-2,y=-1]{B}\n                \\Vertex[x=-2,y=-2]{C}\n\n\n                \\Vertex[x=-2,y=-4,Pseudo]{B1}\n\n                \\Vertex[x=0,y=1]{a}\n                \\Vertex[x=0,y=0]{b}\n                \\Vertex[x=0,y=-1]{c}\n                \\Vertex[x=0,y=-2]{d}\n                \\Vertex[x=0,y=-3]{e}\n\n\n                \\Vertex[x=0,y=-4,Pseudo]{B2}\n\n                \\Vertex[x=2,y=-1]{D}\n                \\Vertex[x=2,y=-4,Pseudo]{B3}\n                \\Vertex[x=4,y=-1,Pseudo,label=$o_1$]{F}\n                \\Vertex[x=4,y=-4,Pseudo]{B4}\n\n                \\Edge(i1)(A)\n                \\Edge(i1)(B)\n                \\Edge(i1)(C)\n                \\Edge(i2)(A)\n                \\Edge(i2)(B)\n                \\Edge(i2)(C)\n\n                \\Edge(A)(a)\n                \\Edge(B)(a)\n                \\Edge(C)(a)\n\n                \\Edge(A)(b)\n                \\Edge(B)(b)\n                \\Edge(C)(b)\n\n                \\Edge(A)(c)\n                \\Edge(B)(c)\n                \\Edge(C)(c)\n\n                \\Edge(A)(d)\n                \\Edge(B)(d)\n                \\Edge(C)(d)\n\n                \\Edge(A)(e)\n                \\Edge(B)(e)\n                \\Edge(C)(e)\n\n                \\Edge(a)(D)\n                \\Edge(b)(D)\n                \\Edge(c)(D)\n                \\Edge(d)(D)\n                \\Edge(e)(D)\n                \\Edge(D)(F)\n                \\draw[-,decorate,decoration={brace,mirror}] (B0)-- node[below]{Input layer} (B0);\n                \\draw[-,decorate,decoration={brace,mirror}] (B1)-- node[below]{Hidden layers} (B3);\n                \\draw[-,decorate,decoration={brace,mirror}] (B4)-- node[below]{Output layer} (B4);\n            \\end{tikzpicture}\n        \\end{center}\n        \\caption{Simple illustration of a NN.\\label{fig:NN}}\n    \\end{figure}\n    The most left layer is called the input layer and the neurons within this layer are called \\textit{input neurons}.\n    The outermost right layer is called the output layer, and as you can guess it's neurons are called \\textit{output neurons}, in this case a single neuron.\n    The layers in between are called \\textit{hidden} layers since their neurons are neither input nor output neurons. The term \\dq hidden\\dq might sound magical or\n    deeply philosophical the first time you hear about it, but it's nothing else then another word for \\dq not an input/output\\dq.\n    This might be somewhat confusion, and I just mention it for historical reason, some people call these networks\n    MLPs, multiple layer perceptron networks, despite the fact that some of them hold sigmoid neurons, this should be mentioned\n    so you're aware of that term.\\newline\n    \\textbf{Important to note, I might call sigmoid neurons every now and then activated neurons, this is due to the nature of sigmoid neurons which use the sigmoid function as activation function.\n    Whenever this activation function differs I will explicitly name this activation function. Other then that activated neurons are sigmoid neurons.}\n    \n    \\subsection{Input and output layers}\n    The design for input and output layers is straight forward. Depending on the problem we want to solve we\n    figure out the number of input values. For the example of classifying handwritten digits we have a dataset of 64x64 px images\n    therefor we have \\(n = 64 \\cdot 64 = 4096\\) input parameters, which need to be clamped into \\([0,1]\\). To normalize the data we can use\n    \\begin{align}\n        \\tilde{x_i} = \\frac{x_i - \\min(x)}{\\max(x)-\\min(x)}\n    \\end{align}\n    The output layer will contain \\(m\\) neurons, to simplify for now we want to classify if a picture shows a 9 or not, so a single neuron with values\n    \\(o \\leq 0.5\\) indicating it is \\underline{not} a 9 and \\(o > 0.5\\) that the input image is a 9.\n\n    \\subsection{Hidden Layers}\n    Albeit the design of input- and output layers is straight forward, it is kind of an art to architect hidden layers.\n    To be more precise it is impossible to state a rule of thumb for hidden layer architectures. Instead researchers have found\n    several heuristics to describe models which help solving different problems.\n    As an example for the use of these heuristics they can be used to determine how to trade off hidden layers against the time required training the model.\n    We'll meet several such design heuristics later.\n    \n    \\subsection{Prospects}\n    For now we learned about networks of layers of neurons where the output of one layer is used as the input of the next layer.\n    These networks are called \\textbf{Feed Forward Neural Networks} (FFNNs). The net works in a single operation forward feeding the input\n    values to gain output values. No loops are involved. Actually it would be very hard to achieve loops with this design, so we don't allow them.\n    However there are other designs of neural networks which allow these kind of designs.\n\n    These models are called \\textbf{Recurrent Neural Networks} (RNNs).\n    The idea in these models is to have neurons which fire for some limited duration of time, before becoming quiescent. That firing can stimulate other neurons, which may fire a little while later, also for a limited duration. That causes still more neurons to fire, and so over time we get a cascade of neurons firing. Loops don't cause problems in such a model, since a neuron's output only affects its input at some later time, not instantaneously.\n    Recurrent neural nets have been less influential than feedforward networks, in part because the learning algorithms for recurrent nets are (at least to date) less powerful. But recurrent networks are still extremely interesting. They're much closer in spirit to how our brains work than feedforward networks. And it's possible that recurrent networks can solve important problems which can only be solved with great difficulty by feedforward networks.\n    However, to limit our scope, we're going to concentrate for now on the more widely-used feedforward networks.\n\n    \\chapter{NN to classifying handwritten digits}\n    After this long and very dry introduction to neural networks, lets get our hands dirty and build something fun!\n    In the following chapter we will implement the example we previously used to motivate the idea behind NNs. Classifying \n    handwritten digits.\n    \\section{Problem description}\n    We can split the problem of recognizing handwritten digits into two sub-problems.\n    First we want to split an image of multiple\n    handwritten digits into separate images, each containing a single digit.\n\n    \\begin{multicols}{2}\n        So for example we want this number\\\\\n        \\begin{center}\n            \\includegraphics{digits-complete.eps}\n        \\end{center}\n        \\columnbreak\n\n        To be split into 3 seperate images like\\\\\n        \\begin{center}\n            \\includegraphics{digits-split.eps}\n        \\end{center}\n    \\end{multicols}\n    A human solves this quite easily, but we want to solve this using the computer.\n    Once the image has been segmented, the program then needs to classify each digit individually.\n    So for example we'd like the program to recognize the first digit in the image above to be 4.\n\n    For now we focus on writing a program to solve the second problem. There are many approaches to solve\n    the segmentation problem, but after we discussed the classification you will have a good idea how to tackle\n    the segmentation. One method can be to generate many \\dq trial\\dq \\; segmentations and use an individually trained\n    classifier to score each segmentation. A trial gets a higher score when the classifier is more certain about the classification\n    and a lower score whenever it is uncertain about the classification. The idea is that if the classifier has trouble classifying then\n    the segmentation is not good enough. So instead of worrying about the first problem in the beginning, we assume for now that we have\n    in fact already segmented training sets and can come back to the segmentation model later.\n\n    To solve the more interesting problem, to namely classify handwritten digits we will use a three-layer neural network.\n    It consists of one input layer having \\(784\\) input neurons (one for each pixel of a 28x28 px image), a hidden layer with \\(15\\) neurons and an output layer with \\(10\\) output neurons (one for each digit 0-9 ;-) )\n\n    The input pixels are greyscale, with values of \\(0.0\\) representing white and \\(1.0\\) black. Values in between are different shades of grey.\n\n    You might wonder why the output layer consists of 10 neurons and not the minimum amount required being 4. In fact using 4 neurons can be a lightweight solution\n    here since we can encode the output as a binary value since \\lstinline{111}\\({}_2=7< n_o <13=\\) \\lstinline{1111}\\({}_2\\). The ultimate justification is empirical\n    so let's try out both approaches later on and compare the results, but it will turn out that the network with 10 output values will achieve better results then the \n    network using 4 output values. That leaves us with the big question: Does the number of output values influence the general behavior of the network?\n    Is there maybe some heuristic which gives us a direction to chose the number of output values?\n    And can this heuristic possibly tell us upfront which solution fits better?\n\n    Many resources online and books start now to describe how NNs work by using a explicit example. Most of them start splitting the image of a\n    digit into several parts and justify the way how the neurons \\dq learn\\dq their weights/biases by using these segments and saying \\dq This weight is for the top arch of this digit...\\dq but\n    that's just a useless simplification. Imagine that in fact weights represent features of the images fed into the network during the training period. But the odds that you will chose the right weight\n    which actually describes this particular feature is very low. Imagine weights and biases as feature parts of the fed data. This can be a line, a cloud of pixels anything within the data.\n    But their explanation motivates the decision to chose 10 output neurons, by claiming\n    \\begin{quote}\n        If the combination of hidden neurons is responsible to classify multiple digits it will get very hard for the output neuron to figure out\n        which digit do chose from, since \\lstinline{1000} and \\lstinline{1001} aren't that different. But \\lstinline{0000000001} and \\lstinline{0000000010} do very much.\n    \\end{quote}\n    This description works as an heuristic and is widely used. Although I disagree with the detailed description it is a nice simplification to remember.\n\n    Note that in case you want to achieve the same results as the 10 output neuron model, you can add an additional layer to the end of your model having 4 output neurons.\n    You can use the perceptron neurons for that and manually precalculate the weights for it.\n\n    \\section{Gradient decent}\n    After we defined the design of our network, how can we train it?\\\\\n    Hold your horses, first we need a dataset which we want to use to train our model. For this purpose we use\n    the dataset provided by MNIST for \\href{http://yann.lecun.com/exdb/mnist/}{handwritten digits}.\n    The MNIST dataset comes in split into two parts, training with 60k images of handwritten digits by 25 individuals. The images are greyscaled and 28 by 28 pixel in size.\n    The second part is a test set containing 10k images with the same features.\n    We will use the test set to validate the quality of our network. To make it a good test set it has been acquired by\n    250 individuals. This helps building confidence in the current state during the training phase.\n    \n    What we'd like is an algorithm which lets us find the weights and biases so that the output approximates \\(o(x)\\) for all training inputs \\(x\\). To quantify how well\n    we're achieving this goal at the moment we define the \\textit{cost}-function:\n    \\begin{align}\n        C(w,b) = \\frac{1}{2n}\\sum \\limits_x^n || o(x) - a ||^2\n        \\label{eq:cost}\n    \\end{align}\n    \\(w\\) denotes the collection of all weights in the network, \\(b\\) all the biases, \\(n\\) the total number of training inputs, \\(a\\) is a vector of outputs from the network when \\(x\\) is input (so the current estimation)\n    and the sum is over all training inputs \\(x\\). We call \\(C\\) the quadratic cost function or mean square error (MSE). Nice to see is that for \\(o(x) \\approx a\\) we get \\(C\\approx 0\\) and for big differences between \\(o(x)\\) and \\(a\\)\n    we get big values for \\(C\\). This is nice! Whenever the model is good the cost is significantly lower then whenever we do a bad prediction.\n    So the aim of training is to minimize \\(C\\), in other words we want the weights and biases that produce the least possible \\(C\\).\n    We do that using the \\textbf{gradient decent} algorithm.\n\n    Why introduce the quadratic cost? After all, aren't we primarily interested in the number of images correctly classified by the network? Why not try to maximize that number directly, rather than minimizing a proxy measure like the quadratic cost? The problem with that is that the number of images correctly classified is not a smooth function of the weights and biases in the network. For the most part, making small changes to the weights and biases won't cause any change at all in the number of training images classified correctly. That makes it difficult to figure out how to change the weights and biases to get improved performance. If we instead use a smooth cost function like the quadratic cost it turns out to be easy to figure out how to make small changes in the weights and biases so as to get an improvement in the cost. That's why we focus first on minimizing the quadratic cost, and only after that will we examine the classification accuracy.\n\n    It turns out that we can understand a tremendous amount by ignoring most of that structure, and just concentrating on the minimization aspect. So for now we're going to forget all about the specific form of the cost function, the connection to neural networks, and so on. Instead, we're going to imagine that we've simply been given a function of many variables and we want to minimize that function. We're going to develop a technique called gradient descent which can be used to solve such minimization problems. Then we'll come back to the specific function we want to minimize for neural networks.\n\n    Gradient decent is an algorithm which you can imagine the following.\n    You have a plane with minima and maxima in it, some places are higher some are lower, now you place a ball on that plane and gradient decent will find for you the minima of your plane. It uses\n    derivatives of the function on which to calculate the extreme on to ensure convergence into the direction of the minima.\n\n    So how can we apply it to neural networks? The idea is to use it to fit the models weights \\(w_k\\) and biases \\(b_l\\) during the training phase and therefor to minimize the cost function \\(C\\).\n    Writing the gradient decent update rule in terms of components we get\n    \\begin{align}\n        w_k' &= w_k - \\eta \\frac{\\partial C}{\\partial w_k}\\\\\n        b_l' &= b_l - \\eta \\frac{\\partial C}{\\partial b_l}\n        \\label{eq:gradient-decent}\n    \\end{align}\n    By repeatedly applying this update rule we can \"roll down the hill\", and hopefully find a minimum of the cost function. In other words, this is a rule which can be used to learn in a neural network.\\newline\n    There are several challenges applying the gradient decent rule. In following chapters we will take a look at some of them in depth.\n    But for now I just want to mention one problem. To understand the problem we need to take a look at \\eqref{eq:cost} again.\n    To compute the proper gradient of \\(C\\), \\(\\nabla C\\), we need to compute the gradients \\(\\nabla C_x\\), separately the cost for each input \\(x\\). This will become a big problem\n    for big training sets. Hence we need to use a different approach to calculate \\(\\nabla C\\).\n\n    The solution for this problem is simple, we use statistical tools to calculate the gradient, to be precise we use the stochastic gradient decent.\n    The idea is to make a proper estimation of \\(\\nabla C\\) by computing \\(\\nabla C_x\\) for a small, random, subset of the training set.\n    By averaging over the small subset we can achieve a pretty well result for the true gradient \\(\\nabla C\\), which helps speeding up the computation of the gradient as well as the time spent to train the model.\n\n    To give a proper explanation, stochastic gradient decent is using a small subset of the training set with \\(m\\) randomly chosen elements \\(X_1, X_2, ..., X_m\\), we refer to them as a mini-batch. For a sample size\n    \\(m\\), which needs to be large enough, but not too large, we expect that the average value for \\(\\nabla C_{X_j}\\) will be roughly equal to the over all average of \\(\\nabla C_x\\), or\n    \\begin{align}\n        \\underbrace{\\frac{\\sum_{j=1}^m \\nabla C_x}{m}}_{\\text{Gradient of mini batch}}\n        \\approx \\underbrace{\\frac{\\sum_x \\nabla C_x}{n}}_{\\text{Gradient of complete training set}}\n        = \\underbrace{\\nabla C}_{\\text{overall gradient}}\n    \\end{align}\n    Hence we can use the gradient of the mini-batch to estimate the overall gradient!\n    Applied to the cost calculation for weights and biases \\eqref{eq:gradient-decent} we get\n    \n    \\begin{align}\n        w_k' &= w_k - \\frac{\\eta}{m} \\sum_j \\frac{\\partial C_{X_j}}{\\partial w_k}\\\\\n        b_l' &= b_l - \\frac{\\eta}{m} \\sum_j \\frac{\\partial C_{X_j}}{\\partial b_l}\n    \\end{align}\n    where the sums are over all the training examples \\(X_j\\) of the mini-batch. Then we pick out the next \\(m\\)\n    elements for the next mini-batch. And so on, until we exhausted the whole dataset, which then completes an \\textit{epoch}.\n    At that point we start over with a new training epoch.\\newline\n    It's worth noting that the implementation of \\eqref{eq:cost} might vary. We scaled the cost function using the factor \\(\\frac{1}{n}\\) people sometimes\n    omit this scaling and compute the sum of cost of the current mini-batch. In a similar way the equations \\eqref{eq:gradient-decent} sometimes omit the term \\(\\frac{1}{m}\\).\n    Conceptually this makes little difference in the result, since it's equivalent of scaling the learning rate \\(\\eta\\).\n\n    \\section{Implementation}\n    Alright, lets get them hands dirty and implement a program which learns how to recognize handwritten digits using gradient decision and the MNIST dataset.\n    \n    Download the repository\n\n    \\begin{lstlisting}[basicstyle=\\tiny]{language=bash}\ngit clone https://github.com/MichalDanielDobrzanski/DeepLearningPython35\n    \\end{lstlisting}\n    which contains python 3 compatible code for a neural network as well as the training dataset by MNIST.\n    Initially I stated that we split the training set into 60k training and 10k testing sets, but that's the official\n    dataset form. We'll do it a bit different and keep the test set as is and split the training set into 50k training and 10k\n    validation sets. We won't use the validation set for now, but later on it will come in handy.\n\n    Check out the code in the repository, II will only explain certain features of it, so it's quite necessary that you understand how to read python code.\n    The heavy lifting in form of mathematical operations is mostly lifted by the library \\lstinline{numpy}. But no worries, I will explain implementation parts of the code whenever it's necessary and\n    will provide the mathematical representation in those cases to enable the reader to implement the example in any programming language.\n\n    So without any further ado, here goes nothing!\n\n    For now the main focus is on \\lstinline{network.py}. Let's run the statistic gradient decent training algorithm.\n    In order to do so, include the \\lstinline{network} and \\lstinline{mnist_loader} scripts into  a python shell.\n    Afterwards use \\lstinline{lnist_loader.load_data_wrapper()} method to \n\\begin{lstlisting}{language=Python}\n>>> import network\n>>> import mnist_loader\n>>> training_data, validation_data, test_data \\\n = mnist_loader.load_data_wrapper()\n>>> nn=network.Network([784,30,10])\n>>> nn.SGD(training_data, 30, 10, 3.0, test_data=test_data)\n\\end{lstlisting}\n%http://neuralnetworksanddeeplearning.com/chap1.html#MathJax-Span-788\n    \n    \\section{Backpropagation}\n    \\subsection{Notation}\n\n    Das Gewicht \\(w\\), welches die Verbindung zwischen dem \\(k\\)-ten Neuron des \\(l-1\\)-ten Layers und dem \\(j\\)-ten Neuron des \\(l\\)-ten Layers\n    wird geschrieben als\n\n\n\\end{document}\n", "meta": {"hexsha": "a017f79135399788114777f2461aede6046b06af", "size": 40567, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "include/math/ds/docs/Backpropagation.tex", "max_stars_repo_name": "philsupertramp/game-math", "max_stars_repo_head_hexsha": "56526b673bfc9c71515c8402b5ffa237f1819a39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/math/ds/docs/Backpropagation.tex", "max_issues_repo_name": "philsupertramp/game-math", "max_issues_repo_head_hexsha": "56526b673bfc9c71515c8402b5ffa237f1819a39", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34, "max_issues_repo_issues_event_min_datetime": "2020-11-27T13:33:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T13:40:39.000Z", "max_forks_repo_path": "include/math/ds/docs/Backpropagation.tex", "max_forks_repo_name": "philsupertramp/game-math", "max_forks_repo_head_hexsha": "56526b673bfc9c71515c8402b5ffa237f1819a39", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 66.9422442244, "max_line_length": 965, "alphanum_fraction": 0.689082259, "num_tokens": 9935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.3423230633738592}}
{"text": "\\documentclass[12pt, fullpage,letterpaper]{article}\n\n\\usepackage[margin=1in]{geometry}\n\\usepackage{url}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{xspace}\n\\usepackage{graphicx}\n\\usepackage{hyperref}\n\\usepackage{cancel}\n%\\usepackage{graphicx}\n%\\usepackage{subfig}\n\n\\newcommand{\\semester}{Spring 2022}\n\\newcommand{\\assignmentId}{4}\n\\newcommand{\\releaseDate}{31 March, 2022}\n\\newcommand{\\dueDate}{11:59pm, 15 April, 2022}\n\\newcommand\\independent{\\protect\\mathpalette{\\protect\\independenT}{\\perp}}\n\\def\\independenT#1#2{\\mathrel{\\rlap{$#1#2$}\\mkern2mu{#1#2}}}\n\n\\newcommand{\\bx}{{\\bf x}}\n\\newcommand{\\bw}{{\\bf w}}\n\n\\title{CS 6190: Probabilistic Machine Learning \\semester}\n\\author{Homework \\assignmentId}\n\\date{Handed out: \\releaseDate\\\\\n  Due: \\dueDate}\n\n\\begin{document}\n\\maketitle\n\n\\input{emacscomm}\n\\footnotesize\n\t\\begin{itemize}\n\t\t\\item You are welcome to talk to other members of the class about\n\t\tthe homework. I am more concerned that you understand the\n\t\tunderlying concepts. However, you should write down your own\n\t\tsolution. Please keep the class collaboration policy in mind.\n\t\t\n\t\t\\item Feel free discuss the homework with the instructor or the TAs.\n\t\t\n\t\t\\item Your written solutions should be brief and clear. You need to\n\t\tshow your work, not just the final answer, but you do \\emph{not}\n\t\tneed to write it in gory detail. Your assignment should be {\\bf no\n\t\t\tmore than 10 pages}. Every extra page will cost a point.\n\t\t\n\t\t\\item Handwritten solutions will not be accepted.\n\t\t\n\t\t\\item The homework is due by \\textbf{midnight of the due date}. Please submit\n\t\tthe homework on Canvas.\n\t\\end{itemize}\n\n%GMM\n%Bayes logistic regression, VB, Laplace, Laplace Hession, \n%LDA \n\n\\section*{Practice  [100 points + 100 bonus]}\t\n\\label{sec:q1}\n\\begin{enumerate}\n\t\\item~[20 points] Suppose we have a scalar distribution, \n\t\\[\n\tp(z) \\propto \\exp(-z^2)\\sigma(10z + 3).\n\t\\]\n\t\\begin{enumerate}\n\t\t\\item~[3 points] Although the normalization constant is not analytical, we can use Gauss-Hermite quadrature to calculate an accurate approximation. Please base on the example in ``data/example-code/gmq\\_example.py'', calculate the numerical approximation of the normalization constant, and report its value. With the normalization constant, please draw the density curve of $p(z)$, in the range $z \\in [-5, 5]$. \n\t\t\\item~[5 points] Implement the Laplace approximation of $p(z)$, and report the mean and variance of your Gaussian distribution. Draw the density of your Laplace approximation in the same plot as in (a). \n\t\t\\item~[10 points] Use the local variational inference method and EM-style updates as we discussed in the class (for logistic regression) to implement the variational approximation to $p(z)$. Report the form of your approximate distribution, and draw its density in the same plot as above.\n\t\t\\item~[2 points] By comparing the ``ground-truth'' (from (a)) and the approximations (from (b,c)), what do you observe and conclude?\n\t\\end{enumerate}\n\n\t\\item~[50 points] Let us work on a real-world dataset we have met before. Please download the data from the folder``data/bank-note''. The features and labels are listed in the file ``data-desc.txt''. The training data are stored in the file ``train.csv'', consisting of $872$ examples. The test data are stored in ``test.csv'', and comprise of $500$ examples. In both the training and testing datasets, feature values and labels are separated by commas. We assign the feature weight vector $\\w$ a standard normal prior $\\N(\\0, \\I)$.  \n\t\\begin{enumerate}\n\t\t\\item~[7 points] Implement the standard Laplace approximation to the posterior distribution of the feature weight vector. Report your approximate posterior. Now, use Gauss-Hermite quadrature to implement the calculation of the predictive distribution. Please be careful: \\textbf{you need to do a proper variable transformation in the integral before applying the Gauss-Hermite quadrature because you integrate  with a Gaussian like $\\N(x|\\mu, \\sigma^2)$ rather than $\\exp(-x^2)$!} Now we test the performance with two measures. First, we calculate the inner-product between the posterior mean of the weight vector and the feature vector of each test example, and throw the inner-product into the sigmoid function to calculate the probability that the test example is positive. If the probability is no less than 0.5, we classify the example to be positive (\\ie 1) otherwise we classify the example to be negative (\\ie 0). Report the prediction accuracy. Second, we calculate the average predictive likelihood of the test samples, namely we evaluate the predictive density value of each test sample based on the predictive distribution and then take an average.  Note that in Bayesian learning, the predictive likelihood includes all the information of the (approximate) posterior distribution, hence is more preferred in the evaluation. \n\t\t\\item~[3 points] Implement Laplace approximation with the diagonal Hessian. Report the approximate posterior distribution of the feature weights, the prediction accuracy and average predictive likelihood. \n\t\t\\item~[20 points] Implement variational logistic regression we introduced in the class. Use EM-style updates. Report the variational posterior of the feature weight vector you obtained (\\ie a multivariate Gaussian). Report the prediction accuracy and average predictive likelihood. \n\t\t\\item~[15 points] Implement variational logistic regression we introduced in the class.  But this time, you will use the fully factorized posterior,   $q(\\w)= \\prod_i q(w_i)$ where $w_i$ is $i$-th element in the weight vector $\\w$. In the E step, please use the standard mean-field update to alternatively optimize each $q(w_i)$ given all the others fixed. Report your variational posterior (\\ie diagonal Gaussian), the prediction accuracy and average predictive likelihood on the test data.  \n\t\t\n\t\t\\item~[5 points] Compare the results of the above four approximations. What do you observe and conclude?\n\t\\end{enumerate}\n\n\t\\item~[30 points] Gaussian Mixture Model (GMM). Please download the data ``data/faithful/faithful.txt''  from Canvas. Each row is a sample, including 2 features. Please normalize the features in each column to be in [-1, 1]. Specifically, denote the column by $\\x$; then we compute for each $x_i \\leftarrow (x_i - \\mathrm{mean}(\\x))/(\\max(\\x) - \\min(\\x))$. \n\t\\begin{enumerate}\n\t\t\\item~[20 points] Implement EM algorithm for GMM. Set the number of clusters to $2$. Initialize the cluster centers to be [-1, 1] and [1,-1], and the covariance matrix to be $0.1\\cdot\\I$ for both clusters. Run your EM algorithm for $100$ iterations. For iteration $1$, $2$, $5$, $100$, please draw the figures showing the corresponding cluster centers and memberships. Specifically, for each figure, first draw the scatter plots of the data points and your cluster centers. Each data point is assigned to the cluster that has a great posterior probability to include that data point. Please draw the cluster memberships with different colors. \n\t\t\\item~[7 points] Now initialize the cluster centers to be [-1, -1] and [1, 1] and covariance matrix to be $0.5 \\cdot \\I$ for both clusters. Run your EM algorithm for $100$ iterations. Draw the figures showing the cluster centers and memberships for iteration $1$, $2$, $5$, $100$. \n\t\t\\item~[3 points] Compare the results in (a) and (b), what do you observe and conclude?\n\t\\end{enumerate}\n\n\t\\item~[100 points][\\textbf{Bonus}] Latent Dirichlet Allocation (LDA). Please download the pre-processed corpus from ``data/lda''. From ``ap.txt'', you can see the original Associated Press corpus. ``ap.dat'' are the processed data which you will work on. Each row in ``ap.dat'' represents a document. In total, we have $2,246$ documents. The first number in each row is the number of words in the document. The following are a list of  \\textbf{word-id}:\\textbf{count} items. Word-id starts with 0. The corresponding word list is given in ``vocab.txt''. The first row correspond to Word-id 0, second, Word-id 1, and continue. \n\t\n\t\\begin{enumerate}\n\t\t\\item~[70 points] Implement the mean-field variational EM algorithm for LDA inference as we discussed in the class. Following the orignal LDA paper ( \\url{http://www.cs.columbia.edu/~blei/papers/BleiNgJordan2003.pdf}) to implement the perplexity calculation on test documents (Sec. 7.1). Please randomly select $10\\%$ documents as the test set, and run your LDA inference algorithm on the remaining $90\\%$ documents. Vary the number of topics from \\{5, 10, 15, 20, 50, 100, 200\\}. Run your algorithm until convergence or $500$ iterations have achieved. Draw a figure to show how the perplexity vary along with the growth of the topic numbers. What do you observe and conclude?\n\t\t\\item~[30 points] Set the number of topics to $20$ and run your variational inference algorithm. Examine the top 15 words (\\ie with the largest probability) in each learned topic distribution. List a few topics which you think is semantically meaningful and explain why. \n\t\\end{enumerate}\n\\end{enumerate}\n\n\n\\end{document}\n", "meta": {"hexsha": "7660dfae55fd4fa257142a8a2a2abd46708fc1df", "size": 9038, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "assignments/a4/hw4.tex", "max_stars_repo_name": "tgautam03/CS6190-ProbabilisticML", "max_stars_repo_head_hexsha": "f000f571d1068ab640a360b490a40f0f15d8502b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-08T06:17:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T06:17:05.000Z", "max_issues_repo_path": "assignments/a4/hw4.tex", "max_issues_repo_name": "tgautam03/CS6190-ProbabilisticML", "max_issues_repo_head_hexsha": "f000f571d1068ab640a360b490a40f0f15d8502b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignments/a4/hw4.tex", "max_forks_repo_name": "tgautam03/CS6190-ProbabilisticML", "max_forks_repo_head_hexsha": "f000f571d1068ab640a360b490a40f0f15d8502b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 92.2244897959, "max_line_length": 1339, "alphanum_fraction": 0.7621155123, "num_tokens": 2283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166195971441, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.3422771423746722}}
{"text": "\\documentclass{article}\n\\usepackage{fullpage}\n\\usepackage{nopageno}\n\\usepackage{amsmath}\n\\allowdisplaybreaks\n\n\\newcommand{\\abs}[1]{\\left\\lvert #1 \\right\\rvert}\n\n\\begin{document}\n\\title{Notes}\n\\date{February 3, 2014}\n\\maketitle\n\\section*{last time}\n\\section*{lesson 7}\n\\subsection*{step 1}\nsolve pde for fundamental solutions\n\\begin{align*}\n  u&=T(t)X(x)\\\\\n  \\frac{T'(t)}{\\alpha^2T(t)}&=\\frac{X'(x)}{X(x)}=\\text{separation constant}\\\\\n  \\intertext{phyysical considerationsindicatethat solutionsdeca to 0. simplify by assigning sep constant $\\leq0$}\\\\\n  \\frac{T'(t)}{\\alpha^2T(t)}&=\\frac{X''(x)}{X(x)}=-\\lambda^2\\leq0 &T(x)X(x)=e^{-\\alpha^2\\lambda^2t}\\\\\n\\end{align*}\n\\subsection*{step 2}\nsolve pde and bc. solve $X''(x)+\\lambda^2X(x)=0 with X(0)=0$.\n\n\\subsubsection*{case $\\lambda=0$}\n\\begin{align*}\n  X''(x)&=0\\\\\n  X&=ax+b\\\\\n  X(0)&=0 \\text{ gives} b=0\\\\\n  X'(1)+hX^{(1)}&=0\\\\\n  \\intertext{only trivial solution$X=0$}\n  X&=ax\n  \\intertext{ohter BC gives $a(h+1)=0$ give $a=0$}\n\\end{align*}\n\\subsubsection*{case $\\lambda>0$}\n\\begin{align*}\n  X(x)&=a\\sin(\\lambda x)+b\\cos(\\lambda x)\\\\\n  X(0)&=0\\to b=0\\\\\n  &=a\\sin(\\lambda x)\\\\\n  X'(1)+hX(1)&=0\\\\\n  \\lambda\\cos(\\lambda)+h\\sin(\\lambda)&=0\\\\\n  X'(x)&=a\\lambda\\cos(\\lambda x)\\\\\n  \\intertext{this is on page 52}\n  a\\lambda\\cos(\\lambda)+ha\\sin(\\lambda&=0\\\\\n  a(\\lambda\\cos(\\lambda)+h\\sin(\\lambda))&=0\\\\\n\\end{align*}\nquestion: can $\\cos(\\lambda)=0$? no! then $\\sin(\\lambda)=0$. but $\\cos^2+\\sin^2=1$. Sothe equation becomes $\\tan\\lambda)=-\\frac{\\lambda}{h}$. And from the graph we see that there are infinitely many positively roots $0<\\lambda<\\lambda_2<\\lambda_3<\\dots$.\n\\begin{align*}\n  \\frac{\\pi}{2}&<\\lambda_1<\\pi\\\\\n  \\frac{3\\pi}{2}&<\\lambda_2<2\\pi\\\\\n  n\\pi-\\pi/2&<y_n<n\\pi\\\\\n  \\lambda_n-(n\\pi-\\pi/2)&\\to0 \\text{ as } n\\to\\infty\n\\end{align*}\nso back to the case:\n\\begin{align*}\n  X(x)=a_n\\sin(\\lambda_nx)\\\\\n  \\intertext{where $\\lambda_n$ is positive root to $\\tan(\\lambda)=-\\lambda/h$}\n  \\intertext{find solutions}\n  u_n&=e^{-\\alpha^2{\\lambda_n}^2t}a_n\\sin(\\lambda_nx)\\text{ with }\\tan(\\lambda_n)=-\\lambda_n/h\\\\\n  \\text{so }&\\sum\\limits_{n=1}^\\infty{a_ne^{-\\alpha^2{\\lambda_n}^2t}\\sin(\\lambda_nx)}\n\\end{align*}\n\\subsection*{step 3}\nfind the coefficients $a_n$: want $\\sum\\limits_{n=1}^\\infty{a_n\\sin(\\lambda_nx)}=\\phi(x)$ on $0<x<1$.\n\nrecall in lesson 5: $\\sum\\limits_{n=1}^\\infty{a_sin(n\\pi x)=\\phi(x)}\\left\\{\\begin{aligned}u(0,t)=0\\\\u(1,t)=0\\end{aligned}\\right\\}$.\nUsed othagonality $\\int_0^1{\\sin(m\\pi x)\\sin(n\\pi x)\\,\\mathrm{d}x}$ for $m\\neq n$\n\\begin{align*}\n  \\int_0^1{\\sin(m\\pi x)\\sin(n\\pi x\\,\\mathrm{d}x}&=0, m\\neq n\\\\\n  \\int_0^1{(\\sin(n\\pi x))^2\\,\\mathrm{d}x}&=\\frac{1}{2}, m=n\\\\\n  &\\left\\{\\begin{aligned}\n    \\cos(a+b)&=\\cos(a)\\cos(b)-\\sin(a)\\sin(b)\\\\\n    \\cos(a-b)&=\\cos(a)\\cos(b)+\\sin(a)\\sin(b)\\\\\n    \\sin(a)\\sin(b)&=\\frac{1}{2}(-\\cos(a+b)+\\cos(a-b))\n  \\end{aligned}\\right.\n\\end{align*}\n\\subsubsection*{sturn-liouville theory}\n\\begin{align*}\n  X_n(x)&=\\sin(\\lambda_n x)\\\\\n  \\text{claim }&\\int_0^1{X_m(x)X_n(x)\\mathrm{d}x}\\text{ for } m\\neq n\\\\\n  \\intertext{use $X_n(x)$ solve $X''(x)+\\lambda^2X(x), X(0)=0, X'(1)+hX(1)=0$}\n  \\text{set }& I=\\int_0^1{X_m(x)X_n(x)\\mathrm{d}x}\\\\\n  \\lambda_n^2I&=\\int_0^1{X_m(x)\\left(\\lambda_n^2X_n\\right)\\mathrm{d}x}=\n\\end{align*}\n\n\\end{document}\n", "meta": {"hexsha": "02d4075279efc1d9437e11edb90584a875e492ff", "size": 3233, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "partial differential equations/pde-notes-2014-02-03.tex", "max_stars_repo_name": "ylixir/school", "max_stars_repo_head_hexsha": "66d433f2090b6396c8dd2a53a733c25dbe7bc90f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "partial differential equations/pde-notes-2014-02-03.tex", "max_issues_repo_name": "ylixir/school", "max_issues_repo_head_hexsha": "66d433f2090b6396c8dd2a53a733c25dbe7bc90f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "partial differential equations/pde-notes-2014-02-03.tex", "max_forks_repo_name": "ylixir/school", "max_forks_repo_head_hexsha": "66d433f2090b6396c8dd2a53a733c25dbe7bc90f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1609195402, "max_line_length": 254, "alphanum_fraction": 0.6235694401, "num_tokens": 1426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.3422771357906906}}
{"text": "\\documentclass[a4paper]{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage[english]{babel}\n\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{amsthm}\n\\usepackage{bbold}\n\\usepackage{csquotes}\n\\usepackage[framemethod=TikZ]{mdframed}\n\\usepackage[pdfborder={0 0 0}]{hyperref}\n\\usepackage{xcolor}\n\n\\makeatletter\n\\def\\moverlay{\\mathpalette\\mov@rlay}\n\\def\\mov@rlay#1#2{\\leavevmode\\vtop{%\n   \\baselineskip\\z@skip \\lineskiplimit-\\maxdimen\n   \\ialign{\\hfil$\\m@th#1##$\\hfil\\cr#2\\crcr}}}\n\\newcommand{\\charfusion}[3][\\mathord]{\n    #1{\\ifx#1\\mathop\\vphantom{#2}\\fi\n        \\mathpalette\\mov@rlay{#2\\cr#3}\n      }\n    \\ifx#1\\mathop\\expandafter\\displaylimits\\fi}\n\\makeatother\n\n\\newcommand\\dotcup{\\charfusion[\\mathbin]{\\cup}{\\cdot}}\n\\newcommand\\bigdotcup{\\charfusion[\\mathop]{\\bigcup}{\\cdot}}\n\\newcommand\\p{\\mathcal{P}}\n\n\\newcommand\\op[2][P]{\\mathbb{#1}\\left(#2\\right)}\n\\newcommand\\os[2][P]{\\mathbb{#1}\\left[#2\\right]}\n\\newcommand\\cond[3][P]{\\mathbb{#1}\\left(#2 \\left|\\:#3\\right)\\right.}\n\\newcommand\\cons[3][P]{\\mathbb{#1}\\left[#2 \\left|\\:#3\\right]\\right.}\n\\newcommand\\kld[3][D]{\\mathbb{#1}\\left(#2 \\left\\|\\:#3\\right)\\right.}\n\n\\newcommand\\fall{\\:\\forall\\:}\n\\newcommand\\ex{\\:\\exists\\:}\n\\newcommand\\dt{\\,\\text{d}}\n\\newcommand\\set[1]{\\left\\{#1\\right\\}}\n\\newcommand\\key[1]{\\textit{#1}}\n\\newcommand\\card[1]{\\left|#1\\right|}\n\\newcommand\\ind{\\mathbb{1}}\n\\newcommand\\converges{\\rightarrow}\n\\newcommand\\Perr{\\mathbb{P}_{\\text{err}}}\n\n\\DeclareMathOperator{\\Capacity}{Cap}\n\\DeclareMathOperator{\\Ex}{\\mathbb{E}}\n\\DeclareMathOperator{\\Va}{\\mathbb{V}}\n\n\\theoremstyle{definition}\n\\newtheorem{thm}{Theorem}\n\n\\parindent0pt\n\\setlength\\parskip{8pt}\n\n\\makeatletter\n\\DeclareRobustCommand{\\em}{%\n  \\@nomath\\em \\if b\\expandafter\\@car\\f@series\\@nil\n  \\normalfont \\else \\bfseries \\fi}\n\\makeatother\n\n\\title{\n  Discrete Stochastics and Information Theory  \\\\\n  \\small{Elaboration on Prof. Wöss' course}\n}\n\\author{Lukas Prokop}\n\n\\begin{document}\n\\maketitle\n\\tableofcontents\n\\clearpage\n\n% questions of high  importance: 29\n% question of medium importance: 18\n% questions of low   importance: 3\n\n\\section{Definitions and axioms of probability theory}\n\n\\subsection[Basic definitions]{Explain the basic definitions of probability theory. What is $\\Omega$? What is $\\sigma$?}\n%\n\\begin{description}\n  \\item[Event space $\\Omega$] \\hfill{} \\\\\n    Defines the event space. A coin toss results in head or tail. So we could define an event space of $\\{h, t\\}$. Or we could consider sequences of coin tosses: $\\{\\text{hhh}, \\text{hht}, \\text{hth}, \\text{thh}, \\text{htt}, \\text{tth}, \\text{tht}, \\text{ttt}\\}$. $\\Omega$ contains all possible outcomes. Events are (reasonable) subsets.\n\n  \\item[Subset $\\mathcal{A}$] \\hfill{} \\\\\n    Defines a subset of possible outcomes of $\\Omega$ with $\\mathcal{A} \\subset \\op{\\Omega}$.\n    An example is a throw of the dice with result \\enquote{even number} ($\\mathcal{A} = \\set{2, 4, 6}$) or \\enquote{number 6} ($\\mathcal{A} = \\set{6}$).\n\n  \\item[$\\sigma$ algebra on a set $\\mathcal{A}$] \\hfill{} \\\\\n    A set closed under complement, union and intersection. The following axioms hold:\n    \\begin{enumerate}\n      \\item $\\varnothing \\in \\mathcal{A}$\n      \\item $A \\in \\mathcal{A} \\Rightarrow A^C \\in \\mathcal{A}$\n      \\item If $A_n \\in \\mathcal{A}$ with $n = 1, 2, \\ldots$ then $\\bigcup_{n=1}^\\infty A_n \\in \\mathcal{A}$\n    \\end{enumerate}\n\n  \\item[Probability measure] \\hfill{} \\\\\n    Assigns a real number between 0 and 1 (inclusive) to every event.\n    $P: \\mathcal{A} \\rightarrow [0, 1]$.\n    It satisfies $P(\\varnothing) = 0$ and $P(\\Omega) = 1$ where $P$ with a set parameter means \\enquote{one of}.\n\n  \\item[Probability space $(\\Omega, \\mathcal{A}, P)$] \\hfill{} \\\\\n    Defines a probability space $(\\Omega, \\mathcal{A}, P)$ consisting of an event space, the possible outcomes $\\mathcal{A}$ and some probability measure.\n\\end{description}\n\n\\subsection{What does $\\sigma$ additivity mean?}\n\n\\[\n  A_n \\in \\mathcal{A} \\land A_n \\cap A_m = \\varnothing \\quad\\fall n \\in \\mathbb{N}^+, n \\neq m\n\\] \\[\n  \\Rightarrow\n  \\op{\\bigcup_{n=1}^\\infty A_n} = \\sum_{n=1}^\\infty \\op{A_n}\n\\]\n\n\\subsection{What does the \\enquote{Law of continuity} tell?}\n\nThe law can be derived from the definition of $\\sigma$ algebras:\n\\begin{align*}\n  A_n \\in \\mathcal{A}, A_1 \\subset A_2 \\subset A_3 \\subset \\ldots & \\Rightarrow \\lim_{n\\rightarrow\\infty} \\os A_n = \\op{\\bigcup_{n=1}^\\infty A_n} \\\\\n  B_n \\in \\mathcal{B}, B_1 \\supset B_2 \\supset B_3 \\supset \\ldots & \\Rightarrow \\lim_{n\\rightarrow\\infty} \\os B_n = \\op{\\bigcap_{n=1}^\\infty B_n}\n\\end{align*}\n\n\\subsection{What is a random variable?}\n\nA random variable $X$ is a function associating an event with a real value. It maps the probability space to real world values.\n\\[ X: \\Omega \\rightarrow \\mathbb{R} \\]\n\n\\subsection{What is distribution, density, expected value, absolute convergence, continuity and monotonicity?}\n%\nA \\key{probability distribution} assigns a probability to each subset of possible outcomes of a random experiment. It can be defined by a probability mass function, probability density function, cumulative distribution function, survival function, hazard function, characteristic function or a rule to create a new random variable with a known joint probability distribution.\n\nThe \\key{probability density function} (PDF) of a continuous random variable $X: \\Omega \\rightarrow \\mathbb{R}$ is a function that describes the relative likelihood for this random variable to take on a given value. So there exists some $f: \\mathbb{R} \\rightarrow [0, \\infty)$ such that\n\\[\n  \\os{X \\in B} = \\p^X(B) = \\int_B f(x) \\dt x\n\\]\n\nLet $X$ be a random variable defined on a probability space ($\\Omega, \\Sigma, \\p$) then the \\key{expected value} is defined as\n\\[\n  \\mathbb{E}(X) = \\int_{\\Omega} X \\dt \\p\n\\]\n\nLet $P^X$ operate on ($\\mathbb{R}, \\mathcal{B}$) which is the smallest $\\sigma$ algebra containing all intervals. $P^X(B)$ is the probability that $B$ occurs with respect to a random variable $X$ defined as\n\\[\n  P^X(B) = \\os{X \\in \\mathcal{B}} = \\op{\\set{\\omega \\in \\Omega: X(\\omega) \\in \\mathcal{B}}}\n\\]\n\nConvergence is a property of a sequence of random variables. \\key{Absolute convergence} means that even the sum of absolute values of the series converges as well.\n\nA \\key{continuous probability distribution} associates a probability to a continuous range of values. Only continuous probability distributions have a probability density function. The PDF can be \\key{monotonic} meaning that it is a function between ordered sets that preserves the given order.\n\n\\subsection{What is conditional probability and independence of events?}\n%\nConditional probability is defined as division of joint probability divided by marginal probability:\n\\begin{align}\n  \\cond AB = \\begin{cases}\n    \\frac{\\op{A \\cap B}}{\\op{B}}  & \\op{B} > 0 \\\\\n    0                                 & \\op{B} = 0\n  \\end{cases}\n\\end{align}\n$\\cond AB$ semantically asks \\enquote{assuming $B$ to happen with certainty, what is the probability that $A$ will happen}.\n$A$ and $B$ are independent if and only if $\\cond AB = \\op{A}$. Or in general $A_1, A_2, \\ldots, A_n \\in \\mathcal{A}$ is independent if $\\forall\\: 1 \\leq i_1 < i_2 < \\ldots < i_k \\leq n$\n\n\\[\n  \\op{A_{i_1} \\cap A_{i_2} \\cap \\ldots \\cap A_{i_k}}\n  = \\op{A_{i_1}} \\op{A_{i_2}} \\cdot \\ldots \\cdot \\op{A_{i_k}}\n\\]\n\n\\subsection{What is marginal/joint distribution? What's their relation?}\n%\nLet $A$ and $B$ be two events occuring with \\key{marginal} probability $\\op{A}$ and $\\op{B}$. The \\key{joint probability} is intuitively defined as probability that $A$ \\emph{and} $B$ will happen. Formally $\\op{A, B}$, defined as the intersection $\\op{A \\cap B}$.\n\n\\begin{align*}\n  \\text{marginal probability: }   && p_{X,Y}(x, y) &= \\os{X=x, Y=y} \\\\\n  \\text{joint probability: }      && p_X(x_1, x_2, \\ldots, x_n) &= \\os{X = (x_1, x_2, \\ldots, x_n)}\n\\end{align*}\n\nThen the following relation holds:\n\\[\n  \\cond AB = \\begin{cases}\n    \\frac{\\op{A \\cap B}}{\\op{B}}  & \\text{if } \\op{B} > 0 \\\\\n    0 & \\text{if } \\op{B} = 0\n  \\end{cases}\n\\]\n\nBayes' Theorem is given by\n\\[\n  \\cond AB = \\frac{\\cond BA \\cdot \\op A}{\\op B}\n\\]\n\n\\subsection{Prove $\\mathbb{E}(X\\cdot Y) = \\mathbb{E}(X) \\cdot \\mathbb{E}(Y)$ for independent variables in the discrete case}\n\n\\begin{align*}\n  \\Ex(X)         &= \\sum_x x \\cdot p_X(x) \\\\\n  \\Ex(Y)         &= \\sum_y y \\cdot p_Y(y) \\\\\n  \\Ex(X \\cdot Y) &= \\sum_{x,y} xy \\cdot p_{X,Y}(x,y) \\\\\n                 &= \\sum_x \\sum_y xy \\cdot p_X(x) \\cdot p_Y(y) \\\\\n                 &= \\left(\\sum_x x \\cdot p_X(x)\\right) \\cdot \\left(\\sum_y y \\cdot p_Y(y)\\right) \\\\\n                 &= \\Ex(X) \\cdot \\Ex(Y)\n\\end{align*}\n\n\\subsection{How is covariance and variance defined?}\n\nThe expected value $\\Ex(X)$ of a random variable $X$ is also known as mean $\\mu$.\n\nCovariance is a measure of how much two random variables change together. If the greater values of one variable primarily correspond with the greater values of the other variable (and vice versa for small values), the covariance is positive. If they are linearly disproportional, it is negative.\n\n\\[ \\sigma(X, Y) = \\Ex((X - \\Ex(X))(Y - \\Ex(Y))) = \\Ex(XY) - \\Ex(X) \\Ex(Y) \\]\n\nVariance is a special case of covariance with only one parameter. Variance is the covariance of a variable with itself: $\\sigma^2(X) = \\sigma(X, X)$. It measures how far a set of numbers is spread out. A variance of zero indicates that all the values are identical. Variance is always non-negative.\n\n\\[ \\sigma^2(X) = \\Va(X) = \\Ex((X - \\Ex(X))^2) \\]\n\\begin{align*}\n  \\text{discrete:}   && \\Va(X) &= \\sum_{i=1}^n (p_i \\cdot x_i^2) - \\mu^2 \\\\\n  \\text{continuous:} && \\Va(X) &= \\int x^2 p(x) \\dt x - \\mu^2\n\\end{align*}\n\nCovariance is symmetrical: $\\sigma(X, Y) = \\sigma(Y, X)$. If $X$ and $Y$ are independent, then $\\sigma(X, Y) = 0$.\n\n\\subsection{Derive Bienaymé's equation for $\\Va(\\overline{X_n})$}\n\nBienaymé's equation states that\n%\n\\[\n  \\Va\\left(\\sum_{i=1}^n X_i\\right) = \\sum_{i=1}^n \\Va(X_i)\n\\]\n%\n\\dots which makes variance preferrable in many applications. Furthermore it implies that \n%\n\\begin{align*}\n  \\overline{X_n}                 &= \\frac{X_1 + \\ldots + X_n}{n} \\\\\n%  \\Ex(\\overline{X_n})            &= \\frac{\\Ex(X_1) + \\ldots + \\Ex(X_n)}{n} = \\mu \\\\\n  \\Va\\left(\\overline{X_n}\\right) &= \\Va\\left(\\frac1n \\sum_{i=1}^n X_i\\right) \\\\\n                                 &= \\frac1{n^2} \\sum_{i=1}^n \\Va(X_i) \\\\\n                                 &= \\frac1{n^2} n \\Va(X) \\\\\n                                 &= \\frac1n \\Va(X) \\\\\n                                 &= \\frac{\\sigma^2}{n}\n\\end{align*}\n\n\\subsection{Distinguish between convergence \\enquote{almost surely} and \\enquote{in probability}}\n\nLet $\\left(X_n\\right)_{n \\in \\mathbb{N}}$ be a sequence of random variables.\n\n\\begin{align*}\n  \\lim_{n \\rightarrow \\infty} X_n = X \\text{ almost surely if }\n      & \\mathbb{P}[\\exists \\lim X_n \\land \\lim X_n = X] = 1 \\\\\n  \\lim_{n \\rightarrow \\infty} X_n = X \\text{ in probability if }\n      & \\forall\\: a > 0, \\lim_{n \\rightarrow \\infty} \\mathbb{P}[\\left|X_n - X\\right| \\geq a] = 0\n\\end{align*}\n\nIntuitively almost surely means convergence is given until infinity. In probability means $n$ converges until a fixed constant (not necessarily infinity).\n\n\\subsection{In our notation, what is the difference between $x$, $X$, $X_n$ and $\\mathcal{X}$?}\n% source: 10\n\n\\begin{description}\n  \\item[$x$] \\hfill{} \\\\\n    A specific value (realization) of a random value. For example we iterate over all values of the discrete domain. The $x$ is typically used as iterator $x \\in X$.\n\n  \\item[$X$] \\hfill{} \\\\\n    $X$ denotes a random variable used in an equation. Often $Y$ accompanies $X$ as second random variable to discuss joint probability.\n\n  \\item[$X_n$] \\hfill{} \\\\\n    $X_n$ denotes a sequence of random variables.\n\n  \\item[$\\mathcal{X}$] \\hfill{} \\\\\n    $\\mathcal{X}$ is used with two different meanings:\n    \\begin{itemize}\n      \\item In the context of Markov chains or information channels, we used $\\mathcal{X}$ as the given input values for the Markov process.\n      \\item In the context of probability theory, $\\mathcal{X}$ denotes the domain of a random variable $X$ or the sequence $X_n$ (if they all use the same domain).\n      \\item In the context of codes, $\\mathcal{X}$ denotes the alphabet before encoding.\n    \\end{itemize}\n\\end{description}\n\n\\subsection{Define and prove Markov's inequality}\n\n\\begin{mdframed}\n  Let $X \\geq 0$ be a random variable with $0 < \\Ex(X) < \\infty$, then \n  \\[ \\os{X > a \\cdot \\Ex(X)} \\leq \\frac1a \\quad\\forall\\: a > 0 \\]\n\\end{mdframed}\n\n\\begin{align*}\n  A                     &= [X \\geq a \\Ex(X)] \\\\\n                        &= \\set{w \\in \\Omega: X(w) \\geq a \\cdot \\Ex(X)} \\\\\n  X                     &\\geq X \\ind_A \\\\\n                        &\\geq \\underbrace{a \\Ex(X)}_{\\text{constant } c} \\cdot \\ind_A \\Leftrightarrow \\\\\n  X(w)                  &\\geq X(w) \\ind_A(w) \\\\\n                        &\\geq c \\cdot \\ind_A(w) \\Rightarrow \\\\\n  \\Ex(X)                &\\geq \\Ex(c \\cdot \\ind_A) \\\\\n                        &= a\\Ex(X) \\os A \\Rightarrow \\\\\n  \\frac{\\Ex(X)}{\\Ex(X)} &\\geq a \\os A \\Rightarrow \\\\\n  \\os A                 &\\leq \\frac 1a\n\\end{align*}\n\n\\subsection{Define and prove Chebyshev's inequality}\n\n\\begin{mdframed}\n  Let $X$ be a random variable with finite $\\Ex(X)$ and $\\Va(X)$, then $\\forall\\: a > 0$\n  \\[ \\os{\\card{X - \\Ex(X)} \\geq a} \\leq \\frac{\\Va(X)}{a^2} \\]\n\\end{mdframed}\n\n\\begin{align*}\n  Y      &= (X - \\Ex(X))^2 \\geq 0 \\\\\n  \\Ex(Y) &= \\Va(X) \\\\\n  \\os{\\card{X - \\Ex(X)} \\geq a}\n         &= \\os{Y \\geq a^2} \\\\\n         &= \\os{Y \\geq \\frac{a^2}{\\Va(X)} \\Ex(Y)} \\\\\n         &\\leq \\frac{1}{\\frac{a^2}{\\Va(X)}}  && \\text{[apply Markov inequality]} \\\\\n         & = \\frac{\\Va(X)}{a^2}\n\\end{align*}\n\n\n\n\\subsection{Distinguish between the Weak and Strong Law of Large Numbers}\n\nThe Weak Law of Large Numbers derives from Chebyshev's inequality and states,\n\n\\begin{mdframed}\n  Given $X_n$ as sequence of iid random variables, $\\mu = \\Ex(X_n)$ and $\\sigma^2 = \\Va(X_n) < \\infty$, then\n  \\[ \\overline{X_n} \\converges \\mu \\text{ in probability} \\]\n\\end{mdframed}\n\nThe Strong Law of Large Numbers states,\n\n\\begin{mdframed}\n  Given $X_n$ as sequence of iid random variables then there exists a finite random variable $Y$ such that\n  \\[ \\overline{X_n} \\converges Y \\text{ almost surely} \\]\n\\end{mdframed}\n\nThe Strong Law of Large Numbers can be equivalently defined as $\\Ex(X_n)$ being finite and in this case $Y = \\Ex(X_n)$ almost surely.\n\n\\subsection{Prove the Weak Law of Large Numbers}\n% source: Patrick\n\n\\begin{align*}\n  \\os{\\card{\\overline{X_n} - \\mu} \\geq a} &\\leq \\frac{\\Va(\\overline{X_n})}{a^2}  && \\text{[Chebyshev inequality must hold]} \\\\\n    &= \\frac{\\sigma^2}{na^2} \\\\\n    &\\converges 0\n\\end{align*}\n\n\\section{Entropy}\n\n\\subsection{Give Hartley's definition of information value}\n%\n\\begin{quote}\n  The answer to a question that can assume the two values \\enquote{yes} and \\enquote{no} (without taking into account the meaning of the question) contains one unit of information.\n\\end{quote}\n\nLet $U_N$ be a set of $N$ elements of uniform probability; hence the information amount to identify an element is\n\\[ \\op[H]{U_N} = \\log_2(N) \\in \\mathbb{R} \\]\n\nIt holds that\n\\begin{itemize}\n  \\item $\\op[H]{U_2} = 1$\n  \\item $\\op[H]{U_N} \\leq \\op[H]{U_{N+1}}$\n  \\item $\\op[H]{U_{M\\cdot N}} = \\op[H]{U_M} + \\op[H]{U_N}$\n\\end{itemize}\n\n\\subsection{Derive Shannon's entropy definition from Hartley's information value}\n\nAs can be seen by the third corollary of Hartley, we can group information into (not necessarily equally large) groups of values:\n\n\\[ U_N = U_{N_1} \\dotcup U_{N_2} \\dotcup \\ldots \\dotcup U_{N_n} \\]\n\nIf we want to identify the value in those groups, we need to ask two questions:\n\\begin{enumerate}\n  \\item In which group?\n  \\item Which element in the group?\n\\end{enumerate}\n\nIf the value can be found in group $k$, then $\\log_2{N_k}$ questions are needed to identify the value.\nThe average number of questions for the second question is:\n\n\\[ H_2 = \\sum_{k=1}^n \\frac{N_k}{N} \\log_2{N_k} \\]\n\nWhat about $H_1$?\n\n\\begin{align*}\n  \\op[H]{U_N} &= H_1 + H_2 \\\\\n  \\log_2{N}     &= H_1 + \\sum_{k=1}^n \\frac{N_k}{N} \\log_2{N_k} \\\\\n  H_1           &= \\log_2{N} - \\sum_{k=1}^n \\frac{N_k}{N} \\log_2{N_k} \\\\\n                &= \\sum_{k=1}^n \\frac{N_k}{N} \\log_2{N} - \\sum_{k=1}^n \\frac{N_k}{N} \\log_2{N_k} \\\\\n                &= -\\sum_{k=1}^n \\frac{N_k}{N} \\log_2{\\frac{N_k}{N}} \\\\\n                &= -\\sum_{k=1}^n p_k \\log_2{p_k} && \\text{with } p_k = \\frac{N_k}{N}\n\\end{align*}\n\n\\subsection{Give Shannon's definition of \\key{entropy} and provide examples for small/large entropy}\n\n\\key{Entropy} is a measure of uncertainty of a random variable. Let $X$ be a discrete random variable with alphabet $\\mathcal{X}$ and probability mass function $p_X(x) = \\os{X = x}$ for $x \\in \\mathcal{X}$. The entropy $\\op[H]{X}$ of a discrete random variable $X$ is defined by\n\\[ \\op[H]{X} = -\\sum_{x \\in \\mathcal{X}} p_X(x) \\log_2{p_X(x)} = -\\Ex(\\log_2 p_X(x)) \\]\n$\\op[H]{X} \\geq 0$ holds for all $X$. Furthermore we define\n\\[\n  0 \\log 0 = 0              \\quad \\forall\\, b \\geq 0 \\qquad\n  a \\log \\frac a0 = \\infty  \\quad \\forall\\, a > 0\n\\]\n\nFor example a uniform distribution of two discrete values gives\n\\[ \\op[H]{X} = - \\left(\\frac12 \\log_2{\\frac12} + \\frac12 \\log_2{\\frac12} \\right) = 1 \\]\nUniform distribution always provides a \\key{large} value of entropy. Certain events provide a \\key{small} value. For example consider two events, where only event $A$ always happens:\n\\[ \\op[H]{X} = - \\left(0\\cdot\\log_2{0} + 1\\cdot\\log_2{1}\\right) = \\left(1\\cdot0\\right) = 0 \\]\n\nThe following holds:\n\\begin{itemize}\n  \\item $\\op[H]{X}$ depends only on the probabilities; not on the specific interpretation.\n        \\[ f: \\mathcal{X} \\rightarrow \\mathcal{X}' \\land X' = f(X) \\Rightarrow \\op[H]{X'} = \\op[H]{X} \\]\n  \\item $p_0 \\mapsto \\op[H]{p_0, 1 - p_0}$ is continuous. The maximum is attained at $\\frac12$:\n        \\[ \\op[H]{p_0, 1 - p_0} = -p_0 \\log_2(p_0) - (1 - p_0) \\log_2(1 - p_0) \\]\n        \\[\n           -\\frac12 \\log_2\\left(\\frac12\\right)\n           - \\left(1 - \\frac12\\right) \\log_2 \\left(1 - \\frac12\\right)\n           = +\\frac12 - \\left(-\\frac12\\right)\n           = 1\n        \\]\n  \\item For some fixed $n$,\n        \\[ \\op[H]{p_1, \\ldots, p_n} \\leq \\op[H]{\\frac1n, \\ldots, \\frac1n} = \\log_2(n) \\]\n\\end{itemize}\n\n\\subsection{What is joint entropy? What is the entropy of conditional distribution aka. conditional entropy?}\n\nGiven a pair of discrete random variable ($X, Y$). The joint entropy of $X$ and $Y$ is defined as:\n\\begin{align*}\n  \\op[H]{X, Y} &= -\\sum_{x \\in \\mathcal{X}} \\sum_{y \\in \\mathcal{Y}} p(x, y) \\log_2 p(x, y) \\\\\n                 &= -\\Ex\\left(\\log_2{p(X, Y)}\\right)\n\\end{align*}\n\nEntropy of conditional distribution:\n\\begin{align*}\n  \\cond[H]YX &= \\sum_{x \\in \\mathcal X} p_X(x) \\cond[H]{Y}{X=x} \\\\\n             &= \\sum_{x \\in \\mathcal X} \\op{X=x} \\left(-\\sum_{y \\in \\mathcal Y} \\cond{Y=y}{X=x} \\log_2 \\cond{Y=y}{X=x} \\right) \\\\\n             &= -\\sum_{x \\in \\mathcal X} \\sum_{y \\in \\mathcal Y} \\op{X=x} \\cond{Y=y}{X=x} \\log_2 \\cond{Y=y}{X=x}\n                    & \\left[\\op x \\cdot \\cond yx = \\op{y,x}\\right] \\\\\n             &= -\\sum_{x \\in \\mathcal X} \\sum_{y \\in \\mathcal Y} \\op{Y=y,X=x} \\log_2 \\frac{\\op{Y=y,X=x}}{\\op{Y=y}} \\\\\n             &= \\sum_{x \\in \\mathcal X} \\sum_{y \\in \\mathcal Y} \\op{Y=y,X=x} \\log_2 \\frac{\\op{Y=y}}{\\op{Y=y,X=x}} \\\\\n             &= \\sum_{x \\in \\mathcal X} \\sum_{y \\in \\mathcal Y} p_{X,Y}(x,y) \\log_2 \\frac{p_Y(y)}{p_{X,Y}(x,y)}\n\\end{align*}\n\n\\subsection{Prove that $\\cond[H] YX = \\op[H]{X, Y} - \\op[H]{X}$}\n\n\\begin{align*}\n  \\cond[H] YX &= -\\sum_x \\sum_y p_X(x) p_{X,Y}(y\\,|\\,x) \\log_2 p_{X,Y}(y,x) \\\\\n            &= -\\sum_x \\sum_y p_{X,Y}(x,y) \\left[\\log_2 p_{X,Y}(x,y) - \\log_2 p_X(x)\\right] \\\\\n            &= \\op[H]{X,Y} + \\sum_x \\log_2 p_X(x) \\sum_y p_{X,Y}(x,y) \\\\\n            &= \\op[H]{X,Y} - \\op[H]{X}\n\\end{align*}\n\n\\subsection{What is the Kullback-Leibler distance? Are the parameters symmetrical?}\n\nLet $p$ and $q$ be two probability distributions on the finite set $\\mathcal{X}$.\n$X$ is a random variable with distance probability $p$.\nThe \\key{relative entropy} or \\key{Kullback-Leibler distance} of $p$ with respect to $q$ is\n\\[ \\kld{p}{q}  = \\sum_x p(x) \\log_2 \\frac{p(x)}{q(x)} = \\Ex\\left(\\log_2 \\frac{p(x)}{q(x)}\\right) \\]\n\n\\begin{itemize}\n  \\item Be aware that for $p(x) > 0$ and $q(x) = 0$: $\\kld pq  = \\infty$.\n  \\item $\\kld pq $ is always non-negative.\n  \\item From $\\kld pq = 0$ it follows that $p(x) = q(x) \\: \\forall x \\in \\mathcal{X}$.\n  \\item $\\kld pq \\neq \\kld qp$\n  \\item Intuitively it is a measure of the information lost when $q$ is used to approximate $p$.\n\\end{itemize}\n\n\\subsection{What is mutual information? What is conditional mutual information? What is the chain rule?}\n\nLet $X$ and $Y$ be a pair of random variables. \\key{Conditional mutual information} is defined as,\n\n\\begin{align*}\n  \\op[I]{X, Y} &= \\kld{p_{(X,Y)}}{p_X \\bigotimes p_Y} \\\\\n               &= \\sum_{x,y} p(x,y) \\log_2 \\frac{p(x,y)}{p_X(x)\\cdot p_Y(y)} \\\\\n               &= \\op[H]{X} - \\cond[H] XY = \\op[H]{Y} - \\cond[H] YX\n\\end{align*}\n\nIntuitively, mutual information measures the information that X and Y share. It measures how much knowing one of these variables reduces uncertainty about the other.\n\nSpecifically it holds that $\\op[I]{X, X} = \\op[H]{X}$. The \\key{chain rule} states that\n\\[\n  \\op[H]{X_1, \\dotsc, X_n} = \\sum_{k=1}^n \\cond[H]{X_k}{X_{k-1}, \\dotsc, X_{1}}\n\\]\n\nThe chain rule of mutual information is defined as,\n\\[\n  \\op[I]{(X_1, \\dotsc, X_k); Y} = \\sum_{k=1}^n \\cond[I]{X_k; Y}{X_{k-1},\\dotsc,X_{1}}\n\\]\n\n\\key{Conditional mutual information} of $X$ and $Y$ given $Z$:\n\n\\begin{align*}\n  \\cond[I]{X;Y}{Z} &= \\sum_z p_Z(z) \\cond[I]{X;Y}{Z=z} \\\\\n    &= \\begin{cases}\n      \\cond[H]YZ - \\cond[H]Y{X,Z} \\\\\n      \\cond[H]XZ - \\cond[H]X{Y,Z}\n    \\end{cases}\n\\end{align*}\n\n\\subsection{What is Jensen's inequality?}\n%\nGiven a continuous, convex function $f: I \\rightarrow \\mathbb{R}$ (with $I$ as open interval) and $X$ as random variable,\n\\[  \\Ex(f(X)) \\geq f(\\Ex(X))  \\]\n\n\\subsection{What is information inequality?}\n\nLet $p(x)$ and $q(x)$ be a pair of probability distributions with $x \\in \\mathcal{X}$, then $\\kld{p}{q} \\geq 0$.\n\nEquality holds if and only if $p(x) = q(x) \\quad\\fall x$.\n\nCorollaries:\n\\begin{itemize}\n  \\item $\\op[I]{X;Y} \\geq 0$\n  \\item $\\cond[H]XY \\leq \\op[H]{X}$\n  \\item $\\cond[I]{X;Y}{Z} \\geq 0$\n  \\item $\\op[H]{X_1, \\dotsc, X_n} \\leq \\sum_{k=1}^n \\op[H]{X_k}$\n\\end{itemize}\n\n\\subsection{What is the log-sum inequality?}\n\nGiven $a_1, \\dotsc, a_n$ and $b_1, \\dotsc, b_n \\geq 0$, then\n\\[\n  \\sum_{i=1}^n a_i \\log{\\frac{a_i}{b_i}}\n    \\geq \\left(\\sum_{i=1}^n a_i\\right) \\log{\\frac{\\sum_{i=1}^n a_i}{\\sum_{i=1}^n b_i}}\n\\]\n\nGiven $p^{(1)}(\\cdot), p^{(2)}(\\cdot)$ and $q^{(1)}(\\cdot), q^{(2)}(\\cdot)$\nas probability densities on $\\mathcal{X}$ with $0 \\leq \\lambda \\leq 1$\n\\begin{multline*}\n  \\Rightarrow\n    \\kld{\\lambda \\cdot p^{(1)} + (1 - \\lambda) p^{(2)}}%\n    {\\lambda \\cdot q^{(1)} + (1 - \\lambda) \\cdot q^{(2)}} \\\\\n  \\leq\n    \\lambda \\kld{p^{(1)}}{q^{(1)}} +\n    (1 - \\lambda) \\kld{p^{(2)}}{q^{(2)}}\n\\end{multline*}\n\n\\subsection{What is a Markov chain?}\n%\nA \\key{Markov chain} is a random process satisfying the Markov property which means transitions happen memoryless.\nGiven a state space, transitions can happen between any two states with associated probabilities. Transition probabilities are stored in the so-called \\enquote{stochastic matrix}.\n\nHence a Markov chain is a sequence of random variables $X_1, X_2, X_3, \\dotsc$ with the Markov property, namely that, given the present state, the future and past states are independent. Formally $\\cond{X_{n+1}}{X_1 = x_1, X_2 = x_2, \\dotsc, X_n = x_n} = \\cond{X_{n+1} = x}{X_n = x_n}$.\n\nA Markov chain is ergodic iff every transition probability is greater zero. A Markov triple is a Markov chain of three states.\n\n\\subsection{Define Data Processing inequality}\n\nLet $X \\rightarrow Y \\rightarrow Z$ be a Markov triple \\emph{in that order} meaning $X$ and $Z$ are independent but conditional on $Y$. Hence\n\\[ \\cons{X=x, Z=z}{Y=y} = \\cons{X=x}{Y=y} \\cdot \\cons{Z=z}{Y=y} \\]\n\nIt holds that\n\\[  \\op[I]{X;Y} \\geq \\op[I]{X;Z}  \\]\n\nThe information that $Y$ knows about $X$ cannot be increased by manipulating (processing) $Y$ deterministically or at random.\n\n\\subsection{Prove Data Processing inequality}\n\nThe chain rule tells\n\\[  \\op[I]{(Y, Z); X} = \\op[I]{Y;X} + \\cond[I]{Z;X}{Y}  \\]\n\nSo,\n\\begin{align*}\n  \\op[I]{X;Y,Z} &= \\op[I]{X;Y,Z} \\\\\n  \\op[I]{X;Y} + \\underbrace{\\cond[I]{X;Z}{Y}}_{\\geq0} &= \\op[I]{X;Z} + \\underbrace{\\cond[I]{X;Y}{Z}}_{=0} \\\\\n  \\op[I]{X;Y} &\\geq \\op[I]{X;Z}\n\\end{align*}\n\n\\subsection{Define and prove Fano's inequality}\n% source: 10, Felix\n\n\\begin{mdframed}\n  Define a Markov triple $X \\rightarrow Y \\rightarrow \\hat X$\n  with $\\mathbb{P}_{\\text{err}}$ as the error that $X \\neq \\hat X$.\n  \\[\n    H(\\Perr) + \\Perr \\log{\\card{\\mathcal{X}}}\n      \\geq \\cond[H]{X}{\\hat X}\n      \\geq \\cond[H]XY\n  \\]\n\n  Equivalently\n  \\[ 1 + \\Perr \\log{\\card{\\mathcal{X}}} \\geq \\cond[H]XY \\]\n  \\[ \\Perr \\geq \\frac{\\cond[H]XY - 1}{\\log_2\\card{\\mathcal{X}}} \\]\n\\end{mdframed}\n\n\\[\n  E = \\begin{cases}\n    1 & \\text{if } \\hat X \\neq X \\\\\n    0 & \\text{if } \\hat X = X\n  \\end{cases}\n\\]\n\n\\begin{align*}\n  \\cond[H]{E,X}{\\hat X} &= \\cond[H]{E,X}{\\hat X} \\\\\n  \\underbrace{\\cond[H]{E}{\\hat X}}_{\\leq \\op[H]{\\Perr}} + \\underbrace{\\cond[H]{X}{E,\\hat X}}_{\\leq \\Perr \\log\\card{\\mathcal{X}}}  &= \\cond[H]{X}{\\hat X} + \\underbrace{\\cond[H]{E}{X,\\hat X}}_{=0} \\\\\n\\end{align*}\n\n$\\cond[H]{X}{E,\\hat X}$ is bounded by\n\\begin{align*}\n  \\cond[H]{X}{E,\\hat X} &= \\os{E = 0}\\cond[H]{X}{\\hat X, E = 0} + \\os{E = 1}\\cond[H]{X}{\\hat X, E = 1} \\\\\n                        &\\leq (1 - \\Perr) \\cdot 0 + \\Perr \\log \\card{\\mathcal{X}}\n\\end{align*}\n\nHence, we obtain Fano's inequality. Intuitively it relates the probability of error in guessing the random variable $X$ to its conditional entropy $\\cond[H]XY$. Given $X$ as a function of $Y$. Iff $X$ can estimate $Y$ with zero probability of error, then $\\cond[H]XY = 0$. Fano's inequality uses this fact: Estimate $X$ with a low probability of error if the conditional entropy $\\cond[H]XY$ is small.\n\n\\section{Asymptotic entropy}\n\n\\subsection{What does iid mean?}\n\niid is a property of a set of random variables. A set of random variables can be \\enquote{independent, identically distributed} meaning that they all utilize the same probability distribution, but are independent in every possible form.\n\n\\subsection{What is a stochastic process?}\n\nA stochastic process (in discrete time) is a sequence of random variables\n\\[  \\left(X_n\\right)_{n\\geq1} \\]\n\n\\subsection{What is asymptotic entropy?}\n\nGiven $X_n$ as discrete random variables and its values in some finite/countable set $\\mathcal{X}$.\nThe \\key{asymptotic entropy} or \\key{asymptotic rate} $h$ of the stochastic process is defined as\n\\[ h = \\lim_{n \\rightarrow \\infty} \\frac1n \\op[H]{X_1,\\dotsc,X_n} \\]\n\nFurthermore\n\\[ h' = \\lim_{n \\rightarrow \\infty} \\cond[H]{X_n}{X_{n-1},\\dotsc,X_1} \\]\nif the limit exists. If $h'$ exists, then $h$ exists and $h = h'$.\n\nConvergence is interpreted as\n\\[\n  \\lim_{n\\rightarrow\\infty} a_n = a\n    \\Leftrightarrow\n      \\fall \\varepsilon > 0\n      \\ex N_\\varepsilon:\n      \\fall n > N_\\varepsilon:\n      \\card{a_n - a} < \\varepsilon\n\\]\n\n\\subsection{What is a stationary distribution?}\n\nA distribution $\\left(X_n\\right)_{n\\geq1}$ is stationary if $\\fall n, l \\in \\mathbb{N}:$ $(X_1,\\dotsc,X_n)$ and $(X_{l+1},\\dotsc,X_{l+n})$ have the same joint distribution.\n\n\\[ \\fall x_1, \\dotsc, x_n \\in \\mathcal{X}: \\os{X_1=x_1,\\dotsc,X_n=x_n} = \\os{X_{l+1}=x_1,\\dotsc,X_{l+n}=x_n} \\]\n\nIf $\\left(X_n\\right)_{n\\geq1}$ is stationary, $h'$ exists.\n\n\\subsection{What is time homogeneity?}\n\nA Markov chain is called time-homogeneous if\n\\[ p_n(y\\,|\\,x) = p_m(y\\,|\\,x) \\qquad \\fall m,n \\]\n\nHence, transition probability do not depend on time.\n\n\\subsection{Prove that at least one stationary distribution exists for every stochastic matrix.}\n\nFormally, a distribution at time $n$ is given as\n\\[\n  \\os{X_n=y}\n    = \\sum_{x\\in\\mathcal{X}} \\cons{X_n=y}{X_0=x} \\cdot \\os{X_0=x}\n    = \\sum_x p_{x,y}^{(n)} \\mu_x\n    = \\left(\\mu P^n\\right)_x\n\\]\n\nNow for an arbitrary stochastic matrix $P = \\left(p_{x,y}\\right)_{x,y \\in \\mathcal{X}}$ at least one stationary distribution $\\nu$ exists.\n\nConsider an initial distribution $\\mu = \\mu_0$.\n\\[ \\left( \\mu + \\mu P + \\mu P^2 + \\dotsb + \\mu P^{n-1} \\right) \\frac1n = \\mu_n \\]\n$\\mu_n$ is a probability vector on $\\mathcal{X}$ for various $n$. A subsequence $\\left(\\mu_{n_k}\\right)_{k \\in \\mathbb{N}}$ exists which converges to some vector $\\nu$.\n\n\\begin{align*}\n  \\sum_{x \\in \\mathcal{X}} \\nu_X &= \\sum_{x \\in \\mathcal{X}} \\lim \\mu_{n_k} \\\\\n                                 &= \\lim \\sum_{x \\in \\mathcal{X}} \\mu_{n_k} && \\text{[because $\\mathcal{X}$ is finite]} \\\\\n                                 &= 1 \\\\\n  \\mu_n^P - \\mu_n &= \\frac1n \\left(\\mu P + \\mu P^2 + \\dotsb + \\mu P^n\\right) \\\\\n                  &= \\frac1n \\left(\\mu + \\mu P + \\dotsb + \\mu P^{n+1}\\right) \\\\\n                  &= \\frac1n \\underbrace{\\left(\\mu - \\mu P^n\\right)}_{\\text{bounded by } 1} \\\\\n                  &\\converges 0\n\\end{align*}\n\\[\n \\begin{array}{ccccc}\n   \\mu_{n_k} P & - & \\mu_{n_k}  & \\rightarrow & 0 \\\\\n   \\downarrow  &   & \\downarrow &             & \\\\\n   \\nu P       & - & \\nu        & =           & 0\n \\end{array}\n\\]\n\n\\subsection{What does irreducibility of $(\\mathcal{X}, P)$ mean?}\n\n$(\\mathcal{X}, P)$ is called irreducible\\footnote{for finite $\\mathcal{X}$ it is called ergodic} if $\\fall x,y \\in \\mathcal{X}: \\exists n = n_{x,y}: p_{x,y}^n > 0$. Graph theoretically irreducibility means strongly connectedness.\n\nIf $(\\mathcal{X}, P)$ is finite and irreducible then there is a unique stationary distribution $\\mu$ and\n\\[\n  \\nu_x = \\frac{1}{\\Ex_X(t^x)}\n\\]\nwhere $\\Ex_X(t^x)$ denotes the expected return time to $x$ with $t_{(w)}^x = \\inf\\set{n \\geq 1: X_n^{(w)} = x}$.\n$t^x$ is almost surely finite: $\\os{t^x < \\infty} = 1$ and $\\Ex_X(t^x) < \\infty$.\n\n\\subsection{How can we compute the stationary distribution for a given irreducible distribution?}\n\n\\subsection{Discuss a random walk.}\n\n\\subsection{Under which circumstances does a unique stationary initial distribution exist? Prove it.}\n\nA unique stationary initial distribution $\\nu$ exists, if $(\\mathcal{X}, P)$ is irreducible.\n\nProof: missing\n% TODO: lecture of 2014.05.07\n\n\\section{Asymptotic equipartition}\n\n\\subsection{What is asymptotic equipartition?}\n\nSuppose that $(X_n)_{n \\geq 1}$ is an $\\mathcal{X}$-valued stochastic process with entropy rate $h$. Then the process is said to have asymptotic equipartition property (AEP), if\n\\[ -\\frac1n \\log_2 p_n(X_1, \\dotsc, X_n) \\converges h \\text{ almost surely} \\]\n(Sometimes convergence in probability suffices)\n\n\\subsection{Under which conditions does the asymptotic equipartition property hold? What is it good for?}\n\n\\[ -\\frac1n \\log_2 p_n(X_1, \\dotsc, X_n) \\converges h \\text{ almost surely} \\]\nmust hold. Furthermore the AEP is good for data compression.\n\n\\subsection{What is a typical set?}\n\nThe typical set is defined as\n\\[\n  A_\\varepsilon^{(n)}\n    = \\left\\{\n      (x_1, \\dotsc, x_n) \\in \\mathcal{X}^n:\n      \\left|-\\frac1n \\log_2 p_n(x_1,\\dotsc,x_n) - h\\right| < \\varepsilon\n    \\right\\}\n\\]\nwhere $\\varepsilon > 0$. The following theorems hold for typical sets\n\\begin{itemize}\n  \\item $2^{-n(h+\\varepsilon)} < p_n(x_1,\\dotsc,x_n) < 2^{-n(h - \\varepsilon)} \\quad\\fall (x_1,\\dotsc,x_n) \\in A_\\varepsilon^{(n)}$\n  \\item $\\os{(X_1,\\dotsc,X_n) \\in A_\\varepsilon^{(n)}} > 1 - \\varepsilon \\quad \\fall n \\geq N_\\varepsilon$\n  \\item $(1 - \\varepsilon) 2^{n(h-\\varepsilon)} \\leq \\card{A_\\varepsilon^{(n)}} \\leq 2^{n(h + \\varepsilon)}$\n\\end{itemize}\nThose theorems follow from the definition of typical sets.\n\n\\section{Coding and compression}\n\n\\subsection{How is expected and average code length defined?}\n\n\\begin{description}\n  \\item[\\key{Expected code length}] \\hfill{} \\\\\n    $\\sum_{(x_1,\\dotsc,x_n)} l(C(x_1,\\dotsc,x_n)) p_n(x_1,\\dotsc,x_n)$\n  \\item[\\key{Average code length}] \\hfill{} \\\\\n    $\\frac1n \\Ex\\left(l(x_1,\\dotsc,x_n)\\right) \\leq h + \\varepsilon' \\qquad\\fall n > N_\\varepsilon$\n\\end{description}\n\n\\subsection{What does the Ergodic theorem state?}\n\nFor finite irreducible Markov chains $(\\mathcal{X}, P)$ it holds that for any $f: \\mathcal{X} \\rightarrow \\mathbb{R}$\n\\begin{align*}\n  \\frac1n\\left(f(X_0) + f(X_1) + \\dotsb + f(X_{n-1})\\right)\n    &= \\sum_{x \\in \\mathcal{X}} f(X) \\nu_x \\text{ almost surely}   && \\text{ [discrete case]} \\\\\n    &= \\int_\\mathcal{X} f \\dt\\nu                                   && \\text{ [continuous case]} \\\\\n\\end{align*}\n\n\\section{Codes}\n\n\\subsection{Define the properties non-singularity, unique decodability and prefix-freedom.}\n\n\\begin{description}\n  \\item[\\key{nonsingular}]\n    $C: \\mathcal{X} \\rightarrow \\Sigma^+$ is injective\n  \\item[\\key{uniquely decodable}]\n    $C: \\mathcal{X}^* \\rightarrow \\Sigma^*$ is injective\n  \\item[\\key{instantaneous or prefix-free}]\n    $\\fall x,y \\in \\mathcal{X}: C(x)$ is not a prefix of $C(y)$\n\\end{description}\n\n\\subsection{What is the Theorem Kraft Inequality?}\n\nLet $D = \\card{\\Sigma}$ and $C: \\mathcal{X} \\rightarrow \\Sigma$ is a prefix-free code. It holds that\n\\[\n  \\sum_{x \\in \\mathcal{X}} D^{-l(C(x))} \\leq 1\n\\]\n\nConversely if $l_X \\in \\mathbb{N}$ ($x \\in \\mathcal{X}$) are such that $\\sum_{x \\in \\mathcal{X}} D^{-l_x} \\leq 1$\nthen there is a prefix-free code $C$ with $C(L(x)) = L_x \\fall x \\in \\mathcal{X}$.\n\n\\subsection{Define a general integer optimization problem.}\n\n\\subsection{What are Lagrange multipliers and what are they used for?}\n\n\\subsection{Which theorem regarding code length holds for every prefix-free code?}\n\nFor every prefix-free code $C: \\mathcal{X} \\rightarrow \\Sigma^+$ the expected code length satisfies $L_C \\geq H_D(X)$.\nIf equality holds, then $p(x) = D^{-l(C(x))}$. Remember that $D = \\card{\\Sigma}$.\n\nIt follows that if $p$ is D-adic\\footnote{meaning $p(x) \\in \\set{D^{-n}: n \\in \\mathbb{N}}$} then the minimum value $H_D(X)$ is attained. We can set $l_X = -\\log_D p(x)$ satisfy Kraft equality.\n\nOtherwise minimise $\\log_D{B} + \\frac{1}{\\log_2 D} \\kld pr$.\n\n\\subsection{Which theorem holds for optimal code lengths?}\n\nOptimal code lengths $l_x^*$ with $x \\in \\mathcal{X}$ are such that the expected code length satisfies $H_D(X) \\leq L^* < H_D(X) + 1$.\n\n\\subsection{How does the Huffman algorithm work?}\n\n\\subsection{Prove that Huffman codes are optimal.}\n\n\\subsection{Which codes are canonical? Are Huffman codes canonical?}\n\nCanonical codes satisfy the following properties:\n\n\\begin{enumerate}\n  \\item if $p(x) > p(y)$ then $l(C(x)) \\leq l(C(y))$\n  \\item If $v,w \\in C(\\mathcal{X})$ are longest code words, then $l(v) = l(w)$\n  \\item $C$ can be modified into another optimal prefix-free code $C'$. $C'$ satisfies:\n    Let $v, w$ be the least likely symbols\n    \\begin{itemize}\n      \\item $v$ and $w$ are siblings in the coding tree\n      \\item $\\fall z \\in \\mathcal{X} \\setminus \\set{x,y}: p(z) \\geq p(x) \\geq p(y)$\n    \\end{itemize}\n\\end{enumerate}\n\nHuffman codes are canonical.\n\n\\section{Information channels}\n\n\\subsection{Define discrete channels. What distinguishes a memoryless channel and the $n$-th extension of $\\mathcal{C}$ without feedback?}\n\nInput alphabet $\\mathcal X$ \\\\\nOutput alphabet $\\mathcal Y$ \\\\\nProbability transition matrix $\\cond yx$\n\nThe channel is \\key{memoryless} iff the probability distribution of the output depends only on the current input and is conditionally independent of previous channel inputs or outputs.\n\n%A \\key{discrete memoryless channel} $\\mathcal{C} = (\\mathcal{X}, P, Y)$ with $P = (p(y\\,|\\,x))_{x \\in \\mathcal{X}}$ with $p(y\\,|\\,x)$ is the probability that the outcome is $y$ given that the input is $x$.\n\nThe \\key{n-th extension of $\\mathcal{C}$ without feedback} is the channel\n\\[ \\mathcal{C}^n = (\\mathcal{X}^n, P_n, Y^n) \\]\n\nWithout feedback means than input symbol are conditionally independent of previous output values.\nIn this case the transition function satisfies\n\\[ \\cond{y^n}{x^n} = \\prod_{i=1}^n \\cond{y_i}{x_i} \\]\n\n\\subsection{How is capacity of a channel defined?}\n\n\\[ \\Capacity(\\mathcal C) = \\max_{p(x)}\\set{\\op[I]{X;Y}: p_X \\in M(\\mathcal{X})} \\]\nwhere $M(\\mathcal{X}) = \\set{p(\\cdot) \\text{ probability distributions on } \\mathcal{X}}$\ngiven $P = (p(y\\,|\\,x))_{x\\in\\mathcal{X}}$ and $p_X$. This defines \\key{information channel capacity}.\n\nFrom Shannon's second theorem it follows that information channel capacity equals to operational channel capacity.\n\n\\subsection{Give examples for channels and their capacity}\n\n\\begin{itemize}\n  \\item Noise-less binary channel\n  \\item Channel with non-overlapping outputs\n  \\item Noisy typewriter\n  \\item Binary symmetric channel\n  \\item Binary erasure channel\n\\end{itemize}\n\n\\paragraph{A noise-less binary channel}\ntransmits both bits always without error.\nIf we want to compute the capacity\n\\begin{align*}\n  C &= \\max\\left\\{\\op[I]{X;Y}\\right\\} \\\\\n    &= \\op[H]{X} - \\cond[H]XY \\\\\n    &= -2\\left(\\frac12 \\log_2 \\frac12\\right) + \\left(2 \\cdot 0 \\log_2 0 + 2 \\cdot 1 \\log_2 1\\right) \\\\\n    &= 1 + 0 = 1\n\\end{align*}\n\n\\paragraph{A noisy typewriter} transmits a letter of the latin alphabet correctly with probability $\\frac12$. With probability $\\frac12$ the next letter of the alphabet will be transmitted instead.\n\n\\[ \\Capacity(\\mathcal C) = \\max\\left\\{\\op[I]{X;Y}\\right\\} = \\op[H]{X} - \\cond[H]{X}{Y} \\]\n\n\\begin{align*}\n  \\cond[H]{X}{Y} &= \\sum_{y \\in \\mathcal Y} \\sum_{x \\in \\mathcal X} \\op{X=x,Y=y} \\log_2 \\frac{\\op{Y=y}}{\\cond{X=x}{Y=y}} \\\\\n                 &= \\sum_{y \\in \\mathcal Y} \\sum_{x \\in \\mathcal X} \\frac1{2\\cdot 26} \\log_2 \\frac{\\frac{1}{26}}{\\frac{1}{52}} \\\\\n                 &= \\sum_{y \\in \\mathcal Y} \\sum_{x \\in \\mathcal X} \\frac{1}{2\\cdot 26} \\log_2 2 \\\\\n                 &= 26 \\cdot 2 \\cdot \\frac{1}{2\\cdot 26} \\cdot 1 \\\\\n                 &= 1\n\\end{align*}\n\nor\n\n\\begin{align*}\n  \\cond[H]{X}{Y} &= \\sum_{y \\in \\mathcal Y} \\op{Y=y} \\cond[H]{X}{Y=y} \\\\\n                 &= \\sum_{y \\in \\mathcal Y} \\frac1{26} \\cdot 1 \\\\\n                 &= 26 \\cdot \\frac1{26} \\\\\n                 &= 1\n\\end{align*}\n\nwith\n\n\\begin{align*}\n  H(X) &= -\\sum_{x \\in \\mathcal X} \\op{X=x} \\log_2 \\op{X=x} \\\\\n       &= -\\sum_{x \\in \\mathcal X} \\frac{1}{26} \\log_2 \\frac{1}{26} \\\\\n       &= -26 \\cdot \\frac{1}{26} \\log_2 \\frac{1}{26} \\\\\n       &= \\log_2 \\frac1{26}\n\\end{align*}\n\n\\paragraph{A binary symmetric channel} transmits a bit correctly\nwith probability $(1-p)$. The wrong bit is sent with probability $p$.\n\n\\begin{align*}\n  \\Capacity(\\mathcal{C}) &= \\op[H]{X} - \\sum_{y \\in \\mathcal Y} \\op{Y=y} \\cond[H]{X}{Y=y} \\\\\n                         &= \\op[H]{\\frac12, \\frac12} - \\op[H]{p, 1-p} \\\\\n                         &= 1 - \\op[H]{p}\n\\end{align*}\n\n\\paragraph{A binary erasure channel} transmits a bit correctly with probability\n$1 - \\alpha$. With probability $\\alpha$ a bit will be transmitted as detectable\nerror bit.\n\n\\begin{align*}\n  \\Capacity(\\mathcal C) &= \\max_{p(x)}\\left(\\op[H]{X} - \\sum_{y \\in \\mathcal Y} \\op{Y=y} \\cond[H]{X}{Y=y}\\right) \\\\\n                        &= \\max_{p(x)}\\left(\\op[H]{X} - \\alpha \\op[H]{X}\\right) \\\\\n                        &= \\max_{\\op[H]{X}}\\left(\\op[H]{X} - \\alpha \\op[H]{X}\\right) \\\\\n                        &= \\left(1 - \\alpha \\cdot 1\\right) \\\\\n                        &= 1 - \\alpha\n\\end{align*}\n\n\\subsection{When is $P$ of an information channel called (weakly) symmetric? Which associated theorem exists?}\n\n$P = (p(y\\,|\\,x))_{x \\in \\mathcal{X}, y \\in \\mathcal{Y}}$ is called \\key{symmetric} iff\n\\begin{enumerate}\n  \\item rows are permutations of each other\n  \\item columns are permutations of each other\n\\end{enumerate}\n\n$P = (p(y\\,|\\,x))_{x \\in \\mathcal{X}, y \\in \\mathcal{Y}}$ is called \\key{weakly symmetric} if\n\\begin{enumerate}\n  \\item rows are permutations of each other\n  \\item all columns yield the same sum\n    \\[ \\exists c: \\sum_x p(y\\,|\\,x) = c \\qquad \\fall y \\in Y \\]\n\\end{enumerate}\n\nThe theorem states,\n\\begin{quote}\n  If $P$ is weakly symmetric, then $\\Capacity(\\mathcal{C}) = \\log_2\\card{Y} - \\op[H]{p(\\cdot\\,|\\,x)}$ and the maximum is achieved when $X$ is uniform on $\\mathcal{X}$.\n\\end{quote}\n\n\\subsection{Prove $\\Capacity(\\mathcal{C}^n) = n \\cdot \\Capacity(\\mathcal{C})$}\n\n\\subsection{What is a $(M, n)$ code? What is the average and maximum error of it?}\n\nAn $(M, n)$ code for the channel $C = (\\mathcal{X}, P, Y)$ consists of the following:\n\\begin{enumerate}\n  \\item An input set $W$ with $\\card{W} = M$ or wlog. $W = \\set{1,\\dotsc,M}$\n  \\item The codebook $B$ (set of codewords)\n  \\item A decoding function $g: Y^n \\rightarrow \\hat W$\n\\end{enumerate}\n\nThe average error is defined as\n\\begin{align*}\n  \\lambda_w^{(n)} &= \\cons{g(Y^{(n)}) \\neq w}{X^{(n)} = x^{(n)}(w)} \\\\\n                  &= \\sum_{y \\in Y} p(y \\,|\\, x(w))\n\\end{align*}\n\nThe maximum probability of the error is $\\lambda^{(n)} = \\max_w \\lambda_w^{(n)}$.\n\n\\subsection{What is the rate of a code?}\n\n\\[ R = \\frac{\\log_2 M}{n} \\]\n\n%A rate $R$ is said to be \\key{achievable} if there exists a sequence of $\\left(\\lceil 2^{nR} \\rceil, n\\right)$ codes such that the maximal probability of error $\\lambda^{(n)}$ converges towards $0$ as $n \\to \\infty$.\n\n\\subsection{What is an achievable rate? What is an achievable capacity?}\n\nA rate $R > 0$ is achievable if there is a sequence of $(M_n, n)$ codes such that\n\\[ R_n = \\frac{\\log_2 M_n}{n} \\converges R \\]\nand\n\\[ \\lambda^{(n)} \\converges 0 \\]\n\nThe achievable capacity $R^*$ of a channel is the supremum of all achievable rates:\n\\[\n  \\fall \\varepsilon > 0 \\qquad\n  \\exists (M,n) \\text{ code with rate } R > R^* - \\varepsilon \\land \\lambda^{(n)} < \\varepsilon\n\\]\n\n\\subsection{What is the set of jointly typical sequences?}\n\nIntuitively, we decode a channel output $Y^n$ as the $i$-th index iff the codeword $X^n(i)$ is in the jointly typical set of the received signal $Y^n$.\n\nThe set $A_\\varepsilon^{(n)}$ of \\key{jointly typical} sequences $\\set{(x^n, y^n)}$ with respect to the distribution $\\op{x,y}$ is the set of $n$-sequences with empirical entropies $\\varepsilon$-close to the true entropies:\n\\[\n\tA_\\varepsilon^{(n)} = \\set{\n\t\t(x^n, y^n) \\in \\mathcal X^n \\times \\mathcal Y^n:\n\t\t\\card{-\\frac1{n} \\log_2 \\op{x^n} - \\op[H]{X}} < \\varepsilon\n\t}\n\\]\n\nThe following statements hold for jointly typical sequences:\n\\begin{enumerate}\n  \\item $\\op{(X^{(n)}, Y^{(n)}) \\in A_\\varepsilon^{(n)}} \\to 1$ as $n \\to \\infty$\n  \\item $(1 - \\varepsilon) 2^{n(\\op[H]{X,Y} - \\varepsilon)} \\leq \\card{A_n^\\varepsilon} \\leq \\varepsilon 2^{n(\\op[H]{X,Y} - \\varepsilon)}$\n  \\item $(X'_1, \\ldots, X'_n), (Y'_1, \\ldots, Y'_n)$ are independent. Then\n    \\[\n\t\t\\op{(X'_1, \\ldots, X'_n, Y'_1, \\ldots, Y'_n) \\in A_\\varepsilon^{(n)}} =\n\t\t\\begin{cases}\n\t\t  \\leq 2^{-n(\\op[I]{X,Y} - 3\\varepsilon)} & \\text{else} \\\\\n\t\t  \\geq (1 - \\varepsilon) 2^{-n (\\op[I]{X,Y} + 3\\varepsilon)} & n \\geq N_\\varepsilon\n\t\t\\end{cases}\n    \\]\n\\end{enumerate}\n\n\\subsection{Define Shannon's 2nd theorem and give an overview over the proof.}\n\nAlso called ``Channel coding theorem''.\n\n\\begin{quote}\n  For a discrete memoryless channel, all rates below capacity C are achievable.\n  Specifically for every rate $R < C$, there exists a sequence of $(2^{nR}, n)$ codes with maximum probability of error $\\lambda^n \\to 0$.\n\n  Conversely any sequence of $(2^{nR}, n)$ codes with $\\lambda^{(n)} \\to 0$ must have $R \\leq C$.\n\\end{quote}\n\n\\[ R^* = \\Capacity(\\mathcal{C}) \\]\n\n\\section{List of theorems}\n\nSee also\n\\begin{itemize}\n  \\item Markov inequality\n  \\item Chebyshev inequality\n  \\item Weak and Strong Law of Large Numbers\n\\end{itemize}\n\n\\begin{thm}\n  If $X,Y$ are independent random variables with finite $\\Ex(X)$ and $\\Ex(Y)$, then\n  \\[ \\Ex(X\\cdot Y) = \\Ex(X) \\cdot \\Ex(Y) \\]\n\\end{thm}\n\n\\begin{thm}\n  If $X_n \\rightarrow X$ almost surely then $X_n \\rightarrow X$ in probability.\n\\end{thm}\n\n\\begin{thm}\n  $X_n \\rightarrow X$ almost surely $\\Leftrightarrow$ $U_k \\rightarrow 0$ in probability with\n  $ U_k = \\sup\\set{\\card{X_n - X}: n \\geq k} $\n\\end{thm}\n\n\\begin{thm}\n  If $\\lim X_n = X$ almost surely and $\\lim X_n = X'$ almost surely, then $X = X'$ almost surely.\n  If $\\lim X_n = X$ in probability and $\\lim X_n = X'$ in probability, then $X = X'$ almost surely.\n\\end{thm}\n\n\\begin{thm}\n  The function $N \\mapsto H(U_N) = \\log_2{N}$ is the \\emph{unique} function satisfying the associated 3~axioms to Hartley formula:\n  \\begin{itemize}\n    \\itemsep0pt\n    \\item $H(U_2) = 1$\n    \\item $H(U_N) \\leq H(U_{N+1})$ (\\enquote{monotonicity})\n    \\item $H(U_{M\\cdot N}) = H(U_M) + H(U_N)$\n  \\end{itemize}\n  It is also the \\emph{unique} function satisfying\n  \\begin{itemize}\n    \\itemsep0pt\n    \\item $H(U_{N+1}) - H(U_N) \\xrightarrow{N \\rightarrow \\infty} 0$\n  \\end{itemize}\n\\end{thm}\n\n\\begin{thm}\n  \\begin{align*}\n    & \\cond[H] YX = \\op[H]{X,Y} - \\op[H]{X} \\\\\n    \\Leftrightarrow{ } & \\op[H]{X,Y} = \\op[H]{X} + \\cond[H] YX\n  \\end{align*}\n\\end{thm}\n\n\\end{document}\n", "meta": {"hexsha": "9cb6b9a698463d85295f10f865e3139ee6ea0059", "size": 44757, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "pub/dsit_elaboration.tex", "max_stars_repo_name": "meisterluk/tug_lp", "max_stars_repo_head_hexsha": "eaf7e0a9bfaa91400248f7231c6891531ee71275", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pub/dsit_elaboration.tex", "max_issues_repo_name": "meisterluk/tug_lp", "max_issues_repo_head_hexsha": "eaf7e0a9bfaa91400248f7231c6891531ee71275", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pub/dsit_elaboration.tex", "max_forks_repo_name": "meisterluk/tug_lp", "max_forks_repo_head_hexsha": "eaf7e0a9bfaa91400248f7231c6891531ee71275", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.3434247871, "max_line_length": 401, "alphanum_fraction": 0.6346269857, "num_tokens": 15647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.34227713241305274}}
{"text": "\n\\subsection{Recap of Hidden Markov Models (HMMs)}\n\nWe don’t see state\n\nEach state produces a visible output. this output is drawn from a distribution for each state.\n\nWe observe a sequence of outputs, not states.\n\n", "meta": {"hexsha": "1d9e50fb166c1edc56946863f33e01a131de90f8", "size": 215, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/pug/theory/statistics/markovHMMEstimation/01-01-HMM.tex", "max_stars_repo_name": "adamdboult/nodeHomePage", "max_stars_repo_head_hexsha": "266bfc6865bb8f6b1530499dde3aa6206bb09b93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pug/theory/statistics/markovHMMEstimation/01-01-HMM.tex", "max_issues_repo_name": "adamdboult/nodeHomePage", "max_issues_repo_head_hexsha": "266bfc6865bb8f6b1530499dde3aa6206bb09b93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-03-03T12:36:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-01T22:16:09.000Z", "max_forks_repo_path": "src/pug/theory/statistics/markovHMMEstimation/01-01-HMM.tex", "max_forks_repo_name": "adamdboult/nodeHomePage", "max_forks_repo_head_hexsha": "266bfc6865bb8f6b1530499dde3aa6206bb09b93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5, "max_line_length": 94, "alphanum_fraction": 0.7720930233, "num_tokens": 50, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.342277129035415}}
{"text": "% appendices are not necessary and should aid understanding, not reproduce results from elsewhere\n\n\\chapter{Stability of degenerate internal squeezing}\n\\label{app:dIS_stability}\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.95\\textwidth]{dIS_stability.pdf}\n    \\caption{Degenerate internal squeezing's stability for lossless (left panel) and lossy (right panel) cases. The different colours indicate different poles found numerically.\n    % The squeezer parameter is normalised to the appropriate threshold in each case.\n    A positive imaginary part of a pole indicates instability.\n    Both cases are stable below singularity threshold. I use the parameters in Table~\\ref{tab:dIS_parameters}.}\n    \\label{fig:dIS_stability}\n\\end{figure}\n\nI determine the stability of degenerate internal squeezing via the poles of its noise and signal responses. These responses are related fractions of polynomials.\nThe denominator of the noise response squared is $\\Omega^4 q(\\Omega,\\chi)$ where $q$ is a polynomial in $\\Omega,\\chi$~\\cite{korobkoQuantumExpanderGravitationalwave2019}.\nSince the zero $\\Omega=0$ comes from the horizontally free-falling mass assumption, the remaining zeros of the noise denominator are the zeros of $q$ (which are shared with the signal response~\\cite{korobkoQuantumExpanderGravitationalwave2019}). In the complex $\\Omega$ plane, if any of these poles~\\footnote{I check that the numerator is not also zero at that point.} have a positive imaginary part, then the system is unstable\\jam{(check this, IFT suggests other sign?)}~\\cite{nise_2019}. %~\\footnote{This result is often expressed instead with respect to the Laplace Transform variable $s=i\\Omega$, where a positive real part of $s$ indicates instability~\\cite{}.}. %This condition is equivalent to others such as\\jam{(... the Nyquist criterion?)}.\nAs shown in Fig.~\\ref{fig:dIS_stability}, therefore, degenerate internal squeezing is stable in the lossless case below threshold and the lossy case below the singularity threshold determined in Section~\\ref{sec:singularity_threshold}.\n\n\\chapter{Comparison of abstract mode structures}\n\\label{app:mode_structure}\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[angle=-90,width=1\\textwidth]{all_mode_structures.pdf}\n    \\caption{Abstract mode diagrams of the different configurations considered in this thesis. The modes and coupling rates are explained in Sections~\\ref{sec:Hamiltonian_modelling}, \\ref{sec:dIS_results}, \\ref{sec:sWLC}, and~\\ref{sec:modal_equivalence}. Whenever the arm mode $\\hat a$ is shown, it is implicitly connected to the test mass mechanical mode $\\hat x$ and the gravitational wave signal $h(t)$. Losses are not shown. The photodetector shows the possibility for idler (optical or mechanical) or signal readout.}\n    \\label{fig:mode_diagram}\n\\end{figure}\n\nIn Fig.~\\ref{fig:mode_diagram}, I compare the abstract mode structure of each of the configurations in this thesis. The parallels between the OPOs and the internal squeezing configurations can be seen. Nondegenerate internal squeezing and stable optomechanical filtering are modally equivalent but are optomechanical and all-optical, respectively, which means that their performance might be different given the different losses they encounter. When idler readout is used, although the internal mode structure is the same as signal readout, the photodetector ``sees'' the structure differently because it measures a different mode. %Idler readout of the mechanical idler mode is more difficult but potentially possible~\\cite{liEnhancingInterferometerSensitivity2021}.\n\n\n\\chapter{Singularity threshold for degenerate internal squeezing}\n\\label{app:dIS_singularity_thr}\n\n% \\renewcommand{\\thefigure}{A\\arabic{figure}}\n% \\setcounter{figure}{0}\n\\begin{figure}[h!]\n    \\centering\n    \\includegraphics[width=0.8\\textwidth]{dIS_threshold_traj_compressed.pdf}\n    \\caption{Degenerate internal squeezing trajectories of the singularities of the anti-squeezed quadrature of the noise and the extrema of the squeezed quadrature in $(\\Omega, \\chi)$ space as the arm loss is changed from $T_{l,a}\\in(0,1)$. I assume that the extrema are minima because of the shape of the noise response in Fig.~\\ref{fig:dIS_sensitivity}.\n    The singularities and minima both achieve the same (a) lossless and (d) high arm loss limits, where neither reaches (d) because of limited numerical sampling. However, the singularities and minima diverge at high arm losses (e.g.\\ $T_{l,a}>0.1$) and merge with their counterparts moving in from infinity at different squeezer parameters shown at (b) and (c), respectively. I use the parameters in Table~\\ref{tab:signal_RO_parameters} and zero signal loss. %\\jam{(rest of explanation moved into text, does it still make sense?)}\n    }\n    \\label{fig:dIS_threshold_traj} % frequency scale is not logarithmic\n\\end{figure}\n\n\\newpage\nThe singularity threshold, see Section~\\ref{sec:singularity_threshold}, for degenerate internal squeezing shows that maximising the anti-squeezed quadrature is not the same as minimising the squeezed quadrature.\nAs shown in Fig.~\\ref{fig:dIS_threshold_traj}, in the lossless case, the singularities $(\\Omega,\\chi)$ are at $(0,\\infty)$ and $(\\omega_s,\\gamma^b_\\text{tot})$ which recovers threshold from Section~\\ref{sec:dIS_results}. %$(\\Omega_\\text{thr},\\chi_\\text{thr})\\xrightarrow[\\gamma_a\\rightarrow0]{}(\\omega_s,\\gamma^b_\\mathrm{tot})$\nAs the arm loss $\\gamma_a$ is increased from zero, the singularities move and merge at the $\\Omega=0$ axis when $\\gamma_a=\\omega_s$, and then the remaining singularity converges to the degenerate OPO threshold $(\\Omega_\\text{thr},\\chi_\\text{thr})\\xrightarrow[\\gamma_a\\rightarrow\\infty]{}(0,\\gamma^b_\\mathrm{tot})$ in the high arm loss limit as expected.\n% \\subsubsection{Disagreement between squeezed and anti-squeezed quadratures}\n% Degenerate internal squeezing - different notions of threshold\n%shouldn't this be in the dIS sub-chapter? no.\n% make clear that knowing threshold just gives the physical bounds of the parameter space, it doesn't correspond to the optimal squeezing (see results section) for sensitivity improvement -- just as minimising N does not necessarily maximise SNR if signal is not considered. \n%\\jam{(One explanation for the difference between position of the singularity of the anti-squeezed quadrature and the minimum of the squeezed quadrature is that the expression for the sloshing frequency in Korobko et al, 2019 is not valid at large arm losses. If this is so, then what does this fixed--sloshing frequency Hamiltonian correspond to? And for that system, why does the supposedly Gaussian squeezing not maximise antisqz at the frequency that it minimises squeezing? --> Look at pump phase and/or covariance matrix)}\n% plot: both quadratures comparison (black-green plot -- what is this?)\n% \\begin{figure}\n%   \\centering\n%   \\includegraphics[width=\\textwidth]{dIS_threshold_quadratures.pdf}\n%   \\caption{\\jam{(Purpose: show problem with singularity threshold. Check if this section is staying in before fixing plot. Cut this plot even if moving to an appendix since the trajectories show this already.)}\\jam{(Normalise legend to threshold)} Degenerate internal squeeing noise quadratures (anti-squeezed in the top panel and squeezed in the bottom panel) and the difference between singularity threshold (that maximises the anti-squeezing peak) and the squeezing parameter that minimises the squeezing peak. This difference is only significant in the high arm loss regime that is unlike\\jam{(word choice?)} future detectors.\\jam{(Answer why squeezing is so small -- see Bram's question (it is just down to the parameters chosen, sloshing frequency and bandwidth, being poorly suited to dIS))}}\n%   \\label{fig:dIS_on_threshold}\n% \\end{figure}\nHowever, where the anti-squeezed quadrature is divergent does not necessarily correspond to where the squeezed quadrature has the minimum value. This is unlike the degenerate OPO in Eq.~\\ref{eq:dOPO_fixed_phase} where the squeezed quadrature is minimised on threshold.\nIf the minima~\\footnote{Since the zeros of the squeezed quadrature are not robust to losses, as shown for the OPO in Fig.~\\ref{fig:dOPO_variances}, I consider the minima instead.} of the squeezed quadrature were used to define threshold, then their trajectories in (real) $(\\Omega,\\chi)$ space would be as shown in Fig.~\\ref{fig:dIS_threshold_traj}. Although they achieve the same limits, these trajectories are not the same as the singularity trajectories.\nThis does not violate the Heisenberg Uncertainty Principle because the losses increase the uncertainty product. %, i.e.\\ the anti-squeezed variance is increased more than the squeezed variance is decreased. %~\\footnote{The squeezing remains Gaussian~\\cite{}, i.e.\\ the squeezed noise ellipse's area is increased but remains an ellipse with semi-axes that represent the standard deviations of the Gaussian noise in each quadrature.\\jam{(check this)}}.  \nMoreover, the difference between the minima and singularities is only significant with high arm losses that are far above the realistic loss $100~\\text{ppm}$ expected for future gravitational-wave detectors (e.g.\\ the squeezing curves only diverge by more than 0.1~dB around $T_{l,a}=0.1$).\n% e.g.\\\\jam{in Fig.~\\ref{fig:dIS_on_threshold} (quantify without plot)} uses $T_{l,a}=800000~\\text{ppm}$ compared to $100~\\text{ppm}$ predicted for future gravitational-wave detectors.\nTherefore, this difference is not of concern for future work involving singularity threshold.\n% because of this and that I am studying nondegenerate squeezing, this problem is not of concern for using singularity threshold in nondegenerate internal squeezing\\jam{(what about combined readout?)}.\n% Although I do not understand why this difference occurs\\jam{(check this)},\nFor completeness, two possible explanations for this behaviour are that it comes from the different DC behaviour of the limiting degenerate OPO's quadratures in Fig.~\\ref{fig:dOPO_variances} or that the approximation to the sloshing frequency in Section~\\ref{sec:nIS_model} breaks down in the high arm loss limit~\\footnote{In which case, this model would not represent the physical system in that limit.}~\\cite{korobkoQuantumExpanderGravitationalwave2019}. This might be understood better if the singularity threshold is verified against a pump-depletion model in future work.\n\n% This is shown\\jam{in Fig.~\\ref{fig:dIS_on_threshold} (explain without plot)} where the minimum squeezing occurs at $76\\%$\\jam{(check this)} singularity threshold and the relative difference is only large (above a percent threshold) in the high arm loss limit\\jam{(quantify this)}.\n% The extrema, of which there are a maximum of two at any point, start at the same points, but have different trajectories, e.g.\\ the first point moving initially into the $\\Omega>\\omega_s$ region instead, and merge at the different point on the y-axis, but converge to the same OPO limit (although the numerical sampling does not show it here). This difference does not violate the Heisenberg Uncertainty Principle\\jam{(but why does it occur?)}.\n% Singularity threshold uses singularities of the anti-squeezed quadrature rather than zeroes of the squeezed quadrature because the former are robust to losses, as shown for the OPO in Fig.~\\ref{fig:dOPO_variances}. \n% Since this problem\\jam{(is it even a problem?)} is not relevant to nondegenerate internal squeezing, ...\n\n\n\n\\begin{comment}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Appendix: Nondegenerate internal squeezing, 2x2 matrix model}\n\n\\jam{(For reference only, delete this from the thesis after checking that all information is in the nIS model given)}\n\nThis derivation is based on the lossless model in Ref.~\\cite{liBroadbandSensitivityImprovement2020} with the differential mode $\\hat{a}$, the signal mode in the signal-recycling cavity $\\hat{b}$, and the idler mode in the signal-recycling cavity $\\hat{c}$.\\jam{Approximations have already been made: single mode and semi-classical pump}. In that model, the only source of vacuum is into the $\\hat{b}$ mode from the readout -- i.e. behind the signal-recycling mirror.\nTo that model, I add in optical loss: (1) intra-cavity to each of the three modes $\\hat{a}, \\hat{b}, \\hat{c}$ through loss ports\\jam{(explain loss port, give a picture)} with transmissivity $T_{l,a}, T_{l,b}, T_{l,c}$, respectively; and (2) at the photodetector, through a beamsplitter with reflectivity $R_{PD}$\\jam{shown in fig}.\nTo study the low-frequency quantum noise, I introduce radiation pressure effects through coupling the gravitational-wave signal $h(t)$ to the end test-mass mirror motion $\\hat{x}$ with associated momentum $\\hat{p}$.\nFollowing the advice\\jam{(word choice)} in Ref.~\\cite{liBroadbandSensitivityImprovement2020}, I also couple the $\\hat{c}$ mode to a back-action evading mechanical mode $\\hat{y}$ with momentum $\\hat{q}$ and negative effective mass $-\\mu$. This is done to retain the PT-symmetry of the system with the P symmetry now exchanging $\\hat{a}\\leftrightarrow\\hat{c}$ and $\\hat{x}\\leftrightarrow\\hat{y}$.\n\nThe full Hamiltonian of the system is given by: $$\\hat{H}=\\hat{H}_0+\\hat{H}_\\mathrm{I}+\\hat{H}_{\\mathrm{GW}}+\\hat{H}_{\\mathrm{BAE}}+\\hat{H}_{\\gamma_R}+\\hat{H}_{\\gamma_a}+\\hat{H}_{\\gamma_b}+\\hat{H}_{\\gamma_c}.$$ Where each term describes:\n\\begin{itemize}\n\\item $\\hat{H}_0=\\hbar\\omega_0(\\hat{a}^\\dagger\\hat{a}+\\frac{1}{2})+\\hbar\\omega_0(\\hat{b}^\\dagger\\hat{b}+\\frac{1}{2})+\\hbar\\omega_\\mathrm{idler}(\\hat{c}^\\dagger\\hat{c}+\\frac{1}{2})$, the uncoupled behaviour of the optical modes, in the Interaction Picture, the model can ignore this behaviour (moving it from the operators onto the states)\\jam{(is RWA also used?)} % and uses a rotating frame at the carrier frequency in order to ignore the evolution of the optical modes from $\\hat{H}_0$\\jam{(be careful, are we? -- also, is RWA used?)}\n\\item $\\hat{H}_\\mathrm{I}=i\\hbar\\omega_s(\\hat{a}\\hat{b}^\\dag-\\hat{a}^\\dag\\hat{b})+i\\hbar\\chi(\\hat{b}^\\dag\\hat{c}^\\dag-\\hat{b}\\hat{c})$, the interaction of the three optical modes $\\hat{a}, \\hat{b}, \\hat{c}$, where a semi-classical approximation has been taken to the pump field\\jam{(spell out what this means for $\\chi$)} and a single-mode approximation to each of the cavity modes which are assumed to be on resonance\\jam{(this needs more discussion, do more in deg. int. sqz. section)}\n\\item $\\hat{H}_\\mathrm{GW}=-\\alpha (\\hat{x}-L_\\mathrm{arm}h)(\\frac{\\hat{a}+\\hat{a}^\\dag}{\\sqrt{2}})+\\frac{1}{2\\mu}\\hat{p}^2$,\\jam{($\\alpha$ is $\\alpha_\\mathrm{GW}$, not the alpha in Li)} the coupling to the gravitational-wave signal $h(t)$\\jam{(Mention that authors disagree on the exact form of the RP term -- there are many equivalent methods to couple the GW signal, mirror mode, and optical mode~\\cite{})}\n\\item $\\hat{H}_{\\mathrm{BAE}}=-\\alpha \\hat{y}(\\frac{\\hat{c}+\\hat{c}^\\dag}{\\sqrt{2}})-\\frac{1}{2\\mu}\\hat{q}^2$, the PT-symmetry enabling, back-action evasion\\jam{(clarify, what is BAE?)} mode\n\\item $\\hat{H}_{\\gamma_R}$\\jam{(formula, state but just use Langevin terms)}, the readout of the $\\hat{b}$ mode\n\\item $\\hat{H}_{\\gamma_i}$ for $i=a,b,c$, the intra-cavity loss ports, these and $\\hat{H}_{\\gamma_R}$ give the standard\\jam{(word choice)} Langevin terms in the Heisenberg-Langevin equations of motion\\jam{(cite Gardiner and Collete?)}.\n\\end{itemize}\n\nFrom this Hamiltonian $\\hat{H}$, I find the Heisenberg-Langevin equations of motion in the Interaction Picture (separating away the evolution with respect to $\\hat{H}_0$):\n$$\\begin{cases}\n\\dot{\\hat{a}}=-\\omega_s\\hat{b} - \\gamma_a \\hat{a} + \\sqrt{2\\gamma_a}\\hat{n}^L_a+\\frac{i}{\\hbar}\\alpha(\\hat{x}-L_\\mathrm{arm}h)\\frac{1}{\\sqrt{2}}\\\\\n\\dot{\\hat{b}}=\\omega_s\\hat{a} + \\chi\\hat{c}^\\dagger - \\gamma^b_\\mathrm{tot} \\hat{b} + \\sqrt{2\\gamma_R}\\hat{B}_\\mathrm{in} + \\sqrt{2\\gamma_b}\\hat{n}^L_b\\\\\n\\dot{\\hat{c}}=\\chi\\hat{b}^\\dagger - \\gamma_c \\hat{c} + \\sqrt{2\\gamma_c}\\hat{n}^L_c + \\frac{i}{\\hbar}\\alpha \\hat{y}\\frac{1}{\\sqrt{2}}\\\\\n\\dot{\\hat{x}}=\\frac{1}{\\mu}\\hat{p},\\quad \\dot{\\hat{p}}=\\alpha(\\frac{\\hat{a}+\\hat{a}^\\dag}{\\sqrt{2}})\\\\\n\\dot{\\hat{y}}=-\\frac{1}{\\mu}\\hat{q},\\quad \\dot{\\hat{q}}=\\alpha(\\frac{\\hat{c}+\\hat{c}^\\dag}{\\sqrt{2}})\n\\end{cases}$$\nI separate out the fluctuating part of each mode $\\hat{a}(t)=\\langle\\hat{a}\\rangle+\\delta\\hat{a}(t)$ from its time average (or large classical motion) $\\langle\\hat{a}\\rangle$. This does not change the form of the equations.\\jam{(Why? This is not clear, the LHS does not change but the time-averages remain)} \n% solving the equations\nIn Fourier space, these equations become (with the simplified notation $\\tilde{\\delta\\hat{Q}}(\\Omega)\\mapsto\\hat{Q}(\\Omega)$ and sign convention $\\partial_t\\mapsto-i\\Omega$):\n\\begin{equation}\n\\begin{cases}\n\\label{eq:nIS-2}\n-i\\Omega\\hat{a}(\\Omega)=-\\omega_s\\hat{b}(\\Omega) - \\gamma_a \\hat{a}(\\Omega) + \\sqrt{2\\gamma_a}\\hat{n}^L_a(\\Omega)+i(\\frac{1}{-\\Omega^2}\\rho_\\mathrm{RP}(\\frac{\\hat{a}(\\Omega)+\\hat{a}^\\dag(-\\Omega)}{\\sqrt{2}})-\\beta\\tilde{h}(\\Omega))\\\\\n-i\\Omega\\hat{b}(\\Omega)=\\omega_s\\hat{a}(\\Omega) + \\chi\\hat{c}^\\dagger(-\\Omega) - \\gamma^b_\\mathrm{tot} \\hat{b}(\\Omega) + \\sqrt{2\\gamma_R}\\hat{B}_\\mathrm{in}(\\Omega) + \\sqrt{2\\gamma_b}\\hat{n}^L_b(\\Omega)\\\\\n-i\\Omega\\hat{c}(\\Omega)=\\chi\\hat{b}^\\dagger(-\\Omega) - \\gamma_c \\hat{c}(\\Omega) + \\sqrt{2\\gamma_c}\\hat{n}^L_c(\\Omega) + \\frac{-i}{-\\Omega^2}\\rho_\\mathrm{BAE}(\\frac{\\hat{c}(\\Omega)+\\hat{c}^\\dag(-\\Omega)}{\\sqrt{2}}).\n\\end{cases}\n\\end{equation}\n\nWhere $\\beta=\\frac{\\alpha L_\\mathrm{arm}}{\\sqrt{2}\\hbar}$ and $\\rho_\\mathrm{RP}=\\rho_\\mathrm{BAE}=\\frac{\\alpha^2}{\\sqrt{2}\\hbar\\mu}$ where the radiation pressure (RP) and back-action evasion (BAE) effects have been separated even though the coupling constant is the same, for PT-symmetry.\n\nSolving these Equations~\\ref{eq:nIS-2} for simultaneous solutions of the $\\hat{Q}(\\Omega)$ and $\\hat{Q}^\\dag(-\\Omega)$ fields is easier when expressed in matrix form. Let $\\vec{\\hat{Q}}(\\Omega)=[\\hat{Q}(\\Omega),\\hat{Q}^\\dag(-\\Omega)]^T$, then the above equations can be re-written as:\n$$\\begin{cases}\n\\label{eq:nIS-3}\n((\\gamma_a-i\\Omega)\\mathrm{I}+\\frac{i\\rho_\\mathrm{RP}}{\\Omega^2 \\sqrt{2}}\\begin{bsmallmatrix}\n1 & 1 \\\\ \n-1 & -1\n\\end{bsmallmatrix})\\vec{\\hat{a}}(\\Omega)=-\\omega_s\\vec{\\hat{b}}(\\Omega) + \\sqrt{2\\gamma_a}\\vec{\\hat{n}}^L_a(\\Omega)-i\\beta\\begin{bsmallmatrix}\n1 & 0 \\\\ \n0 & -1\n\\end{bsmallmatrix}\\vec{\\tilde{h}}(\\Omega)\\\\\n(\\gamma^b_\\mathrm{tot}-i\\Omega)\\vec{\\hat{b}}(\\Omega)=\\omega_s\\vec{\\hat{a}}(\\Omega) + \\chi\\begin{bsmallmatrix}\n0 & 1 \\\\ \n1 & 0\n\\end{bsmallmatrix}\\vec{\\hat{c}}(\\Omega) + \\sqrt{2\\gamma_R}\\vec{\\hat{B}}_\\mathrm{in}(\\Omega) + \\sqrt{2\\gamma_b}\\vec{\\hat{n}}^L_b(\\Omega)\\\\\n((\\gamma_c-i\\Omega)\\mathrm{I}-\\frac{i\\rho_\\mathrm{BAE}}{\\Omega^2\\sqrt{2}}\\begin{bsmallmatrix}\n1 & 1 \\\\ \n-1 & -1\n\\end{bsmallmatrix})\\vec{\\hat{c}}(\\Omega)=\\chi\\begin{bsmallmatrix}\n0 & 1 \\\\ \n1 & 0\n\\end{bsmallmatrix}\\vec{\\hat{b}}(\\Omega) + \\sqrt{2\\gamma_c}\\vec{\\hat{n}}^L_c(\\Omega).\n\\end{cases}$$\n\nWhere $\\mathrm{I}$ is the $2\\times2$ identity matrix. Solving for $\\vec{\\hat{b}}(\\Omega)$, these give\n\\begin{align}\n\\vec{\\hat{b}}(\\Omega)=\\mathrm{M}_b^{-1}( &\\omega_s\\mathrm{M}_a^{-1}(\\sqrt{2\\gamma_a}\\vec{\\hat{n}}^L_a(\\Omega)-i\\beta\\begin{bsmallmatrix}\n1 & 0 \\\\ \n0 & -1\n\\end{bsmallmatrix}\\vec{\\tilde{h}}(\\Omega)) + \\chi\\begin{bsmallmatrix}\n0 & 1 \\\\ \n1 & 0\n\\end{bsmallmatrix}\\mathrm{M}_c^{-1}\\sqrt{2\\gamma_c}\\vec{\\hat{n}}^L_c(\\Omega)\\\\&+ \\sqrt{2\\gamma_R}\\vec{\\hat{B}}_\\mathrm{in}(\\Omega) + \\sqrt{2\\gamma_b}\\vec{\\hat{n}}^L_b(\\Omega)).\n\\end{align}\nWhere the matrices $\\mathrm{M}_i,\\; i=a,b,c$ are given by:\n\\begin{equation}\n\\begin{cases}\n\\mathrm{M}_a = (\\gamma_a-i\\Omega)\\mathrm{I}+\\frac{i\\rho_\\mathrm{RP}}{\\Omega^2 \\sqrt{2}}\\begin{bsmallmatrix}\n1 & 1 \\\\ \n-1 & -1\n\\end{bsmallmatrix}\\\\\n\\mathrm{M}_b = (\\gamma^b_\\mathrm{tot}-i\\Omega)\\mathrm{I} + \\omega_s^2 \\mathrm{M}_a^{-1} - \\chi^2\\begin{bsmallmatrix}\n0 & 1 \\\\ \n1 & 0\n\\end{bsmallmatrix} \\mathrm{M}_c^{-1} \\begin{bsmallmatrix}\n0 & 1 \\\\ \n1 & 0\n\\end{bsmallmatrix}\\\\\n\\mathrm{M}_c = (\\gamma_c-i\\Omega)\\mathrm{I}-\\frac{i\\rho_\\mathrm{BAE}}{\\Omega^2\\sqrt{2}}\\begin{bsmallmatrix}\n1 & 1 \\\\ \n-1 & -1\n\\end{bsmallmatrix}.\n\\end{cases}\n\\end{equation}\n\nHaving found the light inside the cavities, I want to find the light at the photodetector. The light right outside and travelling away from the signal-recycling mirror is given by the Input/Output (I/O) relation: $\\hat{B}_\\mathrm{out}=\\hat{B}_\\mathrm{in}-\\sqrt{2\\gamma_R}\\hat{b}$. Using the beamsplitter model of detection loss at the photodiode, for a beamsplitter of reflectivity $R_\\mathrm{PD}$, the quadratures of light at the photodetector are given by: $\\vec{\\hat{X}}_\\mathrm{PD}=\\sqrt{R_\\mathrm{PD}} \\vec{\\hat{X}}_\\mathrm{PD}^L + \\sqrt{1-R_\\mathrm{PD}} \\vec{\\hat{X}}_{B_\\mathrm{out}}$. Where $\\vec{\\hat{X}}_Q=\\Gamma \\vec{\\hat{Q}}=[\\hat{X}_{1,Q},\\hat{X}_{2,Q}]^T$ for $\\hat{X}_{i,Q}$ the ith quadrature of $Q$ and $\\Gamma=\\frac{1}{\\sqrt{2}}\\begin{bsmallmatrix}\n1 & 1 \\\\ \n-i & i\\end{bsmallmatrix}$ the quadrature matrix.\nPutting everything together, I find the quadratures of the light at the photodetector to be given by:\n\\begin{align}\n\\vec{\\hat{X}}_\\mathrm{PD}(\\Omega)&=\n% \\sqrt{R_\\mathrm{PD}} \\vec{\\hat{X}}_\\mathrm{PD}^L(\\Omega) + \\sqrt{1-R_\\mathrm{PD}} \\Gamma(\\hat{B}_\\mathrm{in}(\\Omega)-\\sqrt{2\\gamma_R}\\hat{b}(\\Omega))\\\\\n% &=  \\sqrt{R_\\mathrm{PD}} \\vec{\\hat{X}}_\\mathrm{PD}^L(\\Omega) + \\sqrt{1-R_\\mathrm{PD}} \\Gamma(\\mathrm{I}-2\\gamma_R\\mathrm{M}_b^{-1})\\Gamma^{-1}\\vec{\\hat{X}}_{B_\\mathrm{in}}(\\Omega)\\\\\n% &-\\sqrt{1-R_\\mathrm{PD}} \\Gamma\\sqrt{2\\gamma_R}\\mathrm{M}_b^{-1}\n% (\\omega_s\\mathrm{M}_a^{-1}\\sqrt{2\\gamma_a}\\vec{\\hat{n}}^L_a(\\Omega)\n% -\\omega_s\\mathrm{M}_a^{-1}i\\beta\\begin{bsmallmatrix}\n% 1 & 0 \\\\ \n% 0 & -1\n% \\end{bsmallmatrix}\\vec{\\tilde{h}}(\\Omega) \\\\& \\hspace{5cm}+ \\chi\\begin{bsmallmatrix}\n% 0 & 1 \\\\ \n% 1 & 0\n% \\end{bsmallmatrix}\\mathrm{M}_c^{-1}\\sqrt{2\\gamma_c}\\vec{\\hat{n}}^L_c(\\Omega) + \\sqrt{2\\gamma_b}\\vec{\\hat{n}}^L_b(\\Omega))\\\\&=\n\\mathrm{R_{in}}\\vec{\\hat{X}}_{B_\\mathrm{in}}(\\Omega)\n+ \\mathrm{R}^L_a\\vec{\\hat{X}}^L_a(\\Omega)\n+ \\mathrm{R}^L_b\\vec{\\hat{X}}^L_b(\\Omega)\n+ \\mathrm{R}^L_c\\vec{\\hat{X}}^L_c(\\Omega)\n+ \\mathrm{R}^L_\\mathrm{PD}\\vec{\\hat{X}}_\\mathrm{PD}^L(\\Omega)\n+ \\mathrm{T}\\vec{\\tilde{h}}(\\Omega).\n\\end{align}\n\nWhere $\\vec{\\hat{X}}_{B_\\mathrm{in}}(\\Omega)$ is the quadrature vector of the vacuum from the main vacuum port behind the signal-recycling mirror, $\\vec{\\hat{X}}^L_a(\\Omega)$ is the vacuum from the $\\hat{a}$ intra-cavity loss, etc.. And where the transfer function matrices $\\mathrm{R}_i, \\mathrm{T}$ for the noises and signal, respectively, are given by the following (where the frequency dependence is inside each $\\mathrm{M}_i^{-1}$):\n\\begin{equation}\n\\begin{cases}\n\\mathrm{R_{in}}=\\sqrt{1-R_\\mathrm{PD}} \\Gamma(\\mathrm{I}-2\\gamma_R\\mathrm{M}_b^{-1})\\Gamma^{-1}\\\\\n\\mathrm{R}^L_a=-\\sqrt{1-R_\\mathrm{PD}} 2\\sqrt{\\gamma_R\\gamma_c}\\omega_s\\Gamma\\mathrm{M}_b^{-1}\\mathrm{M}_a^{-1}\\Gamma^{-1}\\\\\n\\mathrm{R}^L_b=-\\sqrt{1-R_\\mathrm{PD}} 2\\sqrt{\\gamma_R\\gamma_b}\\Gamma\\mathrm{M}_b^{-1}\\Gamma^{-1}\\\\\n\\mathrm{R}^L_c=-\\sqrt{1-R_\\mathrm{PD}} 2\\sqrt{\\gamma_R\\gamma_c}\\chi\\Gamma\\mathrm{M}_b^{-1}\\begin{bsmallmatrix}\n0 & 1 \\\\ \n1 & 0\n\\end{bsmallmatrix}\\mathrm{M}_c^{-1}\\Gamma^{-1}\\\\\n\\mathrm{R}^L_\\mathrm{PD}=\\sqrt{R_\\mathrm{PD}}\\\\\n\\mathrm{T}=\\sqrt{1-R_\\mathrm{PD}} \\sqrt{2\\gamma_R}i\\omega_s\\beta \\Gamma\\mathrm{M}_b^{-1}\\mathrm{M}_a^{-1}\\begin{bsmallmatrix}\n1 & 0 \\\\ \n0 & -1\n\\end{bsmallmatrix}.\n\\end{cases}\n\\end{equation} \n\n\n\\jam{(set up the combined noise, spectral densities matrix Sx)}\n\n\\begin{equation}\n\\mathrm{S}_X(\\Omega)2\\pi\\delta(\\Omega-\\Omega')=\\ev{\\vec{\\hat{X}}_\\mathrm{PD}(\\Omega)\\cdot\\vec{\\hat{X}}_\\mathrm{PD}(\\Omega')^\\dag}\n\\end{equation}\n\n\\jam{(explain uncorrelated vacuum assumption -- i and j are not indices of vectors)}\n\n\\begin{equation}\n\\ev{\\vec{\\hat{X}}_{(i)}(\\Omega)\\cdot\\vec{\\hat{X}}_{(j)}(\\Omega')^\\dag}=\\delta_{i,j}\\mathrm{I}\\,2\\pi\\delta(\\Omega-\\Omega'),\\quad \\mathrm{S_{vac}}=\\mathrm{I}=\\begin{bsmallmatrix}\n1 &  &  &  \\\\ \n & 1 &  &  \\\\\n &  & 1 &  \\\\ \n &  &  & 1\n\\end{bsmallmatrix}\n\\end{equation}\n\n\\jam{(versus single-sided power spectral density of single function, not a vector: $A\\circ B=\\frac{1}{2}(A\\cdot B+B\\cdot A)$, check factors of two again --> single sided, vac=1, quadratures normalised as 1/rt2, quadrature is Hermitian and therefore commutes with its dagger)}\n\n\n\\begin{equation}\n\\mathcal{S}_X(\\Omega)2\\pi\\delta(\\Omega-\\Omega')=(\\text{S}_X)_{2,2}(\\Omega)2\\pi\\delta(\\Omega-\\Omega')=\\ev{\\hat{X}_{\\mathrm{PD},2}(\\Omega)\\circ\\hat{X}_{\\mathrm{PD},2}(\\Omega')^\\dag},\\quad \\mathcal{S}_\\mathrm{vac}=1\n\\end{equation}\n\n\\begin{equation}\n\\mathcal{T}(\\Omega)=(\\mathrm{T}.\\begin{bsmallmatrix}\n1\\\\ \n1\n\\end{bsmallmatrix})_2\n\\end{equation}\n\nI define the sensitivity of the detector to be the noise-to-signal ratio, i.e. the ratio of the noise and signal transfer functions (or, the signal-normalised noise).\nAssuming that we measure the second quadrature, e.g. via balanced homodyne readout\\jam{(address optimisation of quadrature angle, might not be 2 just because signal is only there. Also, need to describe homodyne readout somewhere)}, this gives:\n$$S_h(\\Omega)=\\frac{(\\mathrm{S}_X(\\Omega))_{2,2}}{\\abs{\\mathcal{T}(\\Omega)}^2}.$$\n\\end{comment}\n\n", "meta": {"hexsha": "528c2a3493ea9fe63ff98afa4d2f6e0413741923", "size": 25111, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/appendixA.tex", "max_stars_repo_name": "daccordeon/nondegDog", "max_stars_repo_head_hexsha": "570598b59ac8c70dee6387088698ed768a2d1247", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-02-22T05:25:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T23:42:29.000Z", "max_issues_repo_path": "thesis/appendixA.tex", "max_issues_repo_name": "daccordeon/nondegDog", "max_issues_repo_head_hexsha": "570598b59ac8c70dee6387088698ed768a2d1247", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis/appendixA.tex", "max_forks_repo_name": "daccordeon/nondegDog", "max_forks_repo_head_hexsha": "570598b59ac8c70dee6387088698ed768a2d1247", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 97.3294573643, "max_line_length": 801, "alphanum_fraction": 0.7284855243, "num_tokens": 7766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926666143434, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.3422622228836804}}
{"text": "\\documentclass{article}\n\\usepackage{amsmath}\n\\usepackage{amsfonts} \n\\usepackage{graphicx}\n\\usepackage{biblatex} \n\\usepackage{authblk}\n\\usepackage{mathtools}\n\\usepackage{xurl} %see https://tex.stackexchange.com/questions/23394/url-linebreak-in-footnote for why we use xurl to get line breaks instead of regular url\n\\usepackage[hidelinks]{hyperref}\n\\usepackage{listings}\n\\usepackage{cancel}\n\\usepackage{enumitem}\n\\usepackage[bb=boondox]{mathalfa}\n\\addbibresource{three_books.bib}\n\\DeclareMathOperator*{\\argmax}{arg\\,max}\n\\DeclareMathOperator*{\\argmin}{arg\\,min}\n\\usepackage{fancyhdr}\n\\usepackage{textcomp}\n\n\n\\setlist[description]{leftmargin=2cm,labelindent=1cm}\n\n\\lstdefinestyle{mystyle}{\n    % backgroundcolor=\\color{backcolour},   \n    % commentstyle=\\color{codegreen},\n    % keywordstyle=\\color{magenta},\n    % numberstyle=\\tiny\\color{codegray},\n    % stringstyle=\\color{codepurple},\n    % basicstyle=\\ttfamily\\footnotesize,\n    % breakatwhitespace=false,         \n    % breaklines=true,                 \n    captionpos=b,                    \n    keepspaces=true,                 \n    % numbers=left,                    \n    % numbersep=5pt,                  \n    % showspaces=false,                \n    % showstringspaces=false,\n    % showtabs=false,                  \n    tabsize=2,\n    frame=single,\n}\n\\lstset{style=mystyle}\n\n\\title{Blueprints for building reinforcement learning algorithms in customer-facing applications}\n\\author[1]{Douglas Mason}\n\\affil[1]{Koyote Science, LLC \\footnote{\\href{http://www.koyotescience.com}{\\texttt{http://www.koyotescience.com}}}}\n\\date{November 2021}\n\n\\begin{document}\n\n\\maketitle\n\n\\tableofcontents\n\n\\pagestyle{fancy}\n% \\fancyhf{}\n\\cfoot{\\\\\n\\\\\n\\includegraphics[scale=0.15,valign=c]{koyote_science_logo.png}\n}\n\\lhead{Page \\thepage}\n\\rhead{Section \\thesection}\n\n\n\\section{Introduction}\nThis document outlines primary considerations for designing production-worthy reinforcement learning algorithms in customer-facing settings. We will (1) establish the notation, (2) discuss how policies are evaluated, (3) show how policies can be defined by evaluation functions alone, (4) demonstrate how we train an evaluation for our policy, even from customer interactions driven by another policy, known as off-policy training, (5) show how we can train the policy directly from customer interactions, and (6) demonstrate how we can combine both approaches for the current state-of-the-art in the field. We also (7) provide practical considerations under the hood for building our policies and evaluation functions, as well as (8) additional resources to help the reader dive more deeply into the field, as well as discover implementations that can be used right now. This document attempts to be brief but mathematically thorough. Please write to the author at \\href{mailto:douglas@koyotescience.com}{douglas@koyotescience.com} for questions or feedback. We provide a quick schematic of the algorithms we will cover in Figure \\ref{fig:rl_schematic}.\n\\begin{figure}\\label{fig:rl_schematic}\n    \\begin{center}\n    \\includegraphics[width=0.75\\linewidth]{rl_schematic}\n    \\caption{Schematic for the reinforcement learning approaches covered in this document.\\footnotemark}\n    \\end{center}\n\\end{figure}\n\\footnotetext{ Source: \\url{https://towardsdatascience.com/an-overview-of-classic-reinforcement-learning-algorithms-part-1-f79c8b87e5af}}\n\nAt a high-level overview, reinforcement learning algorithms consist of up to three primary components:\n\\begin{enumerate}\n\\item A \\textit{policy evaluator}, which can be used to define the policy on its own. This is often referred to as the state- or action-value function.\n\\item A \\textit{policy function}, which defines the policy on its own, and can use a policy evaluator to improve its performance\n\\item A \\textit{rollout planning} system for using the policy evaluator and policy function to fine-tune performance\n\\end{enumerate}\nThis documents covers the first two components, and lightly touches on the third, since it is the riskiest to implement in a production system, and requires the ability to predict future states of the system, known as the \\textit{environment model}. Moreover, the policy evaluator is a development of the multi-armed bandit formalism, allowing it to act as a stepping stone between optimization, such as hyperparameter tuning, and sequential planning that uses an explicit policy function.\n\n\\section{Notation and policy evaluation}\n\nWhen designing products that take users through a sequence of actions to get to a desired goal, it’s a natural instinct to look at the field of reinforcement learning to optimize your design. In this formulation, we have a state vector $\\mathbf{s}$ (e.g., the current page a user is on) which may also incorporate a context vector $\\mathbf{c}$ (e.g., user demographics), an action vector $\\mathbf{a}$ that represents a decision that the system can take (e.g., presenting different options along the way), and a reward for taking an action at a given state $r(\\mathbf{s},\\mathbf{a})$ (e.g., whether a user signs up at the end of a sign-up flow). Note that we can also define the reward without considering the action, $r(\\mathbf{s})$, which is identical except that it is defined by the state you end up in to get the reward rather than the state and action you take to get it. \n\nWe are interested in learning a policy $\\pi(\\mathbf{a}| \\mathbf{s})\\in [0,1]$ that gives us the probability of choosing a given action $\\mathbf{a}$ with a given state $\\mathbf{s}$. Note that when implemented, such a function depends on both $\\mathbf{a}$ and $\\mathbf{s}$. The policy is normalized so that its returns for all available actions at a given state add up to one, i.e., \\begin{equation}\\label{eq:normalization}\n\\sum_\\mathbf{a}\\pi(\\mathbf{a}|\\mathbf{s})=1\n\\end{equation} When learning this policy, our goal is to maximize the discounted sum of future rewards $G_t(\\boldsymbol{\\tau})$\\footnote{The letter $G$ is chosen for historical reasons, while $J(\\pi_{\\boldsymbol{\\theta}})=\\mathop{\\mathbb{E}}_{\\boldsymbol{\\tau}\\sim\\pi_{\\boldsymbol{\\theta}}}[G_0({\\boldsymbol{\\tau}})]$ is used later in Equation \\ref{eq:J}} from time step $t$ through the problem horizon $H$, as we step through a given trajectory of states $\\boldsymbol{\\tau}$ which we write out as\n\\begin{equation}\n\\boldsymbol{\\tau}=(\\mathbf{s}_0,\\mathbf{a}_0,\\mathbf{s}_1,\\mathbf{a}_1,\\dots,\\mathbf{s}_H,\\mathbf{a}_H)\n\\end{equation} and where the discount factor $\\gamma\\in(0,1]$. We write this quantity out as\n\\begin{equation}\n    G_t(\\boldsymbol{\\tau})=\\sum_{t'=t}^{H}r(\\mathbf{s}_{t'},\\mathbf{a}_{t'})\\gamma^{t'-t}\n\\end{equation}\nWe can accomplish this by learning a Q-value or action-value function for each state and action, which returns the expected discounted sum of future rewards assuming we follow a policy $\\pi$ starting from state $\\mathbf{s}$ and action $\\mathbf{a}$, and can be written as\n\\begin{equation}\n\\begin{split}\nQ_\\pi(\\mathbf{s},\\mathbf{a})&=\\mathop{\\mathbb{E}}_{\\boldsymbol{\\tau}\\sim\\pi}[G_t({\\boldsymbol{\\tau}})|\\mathbf{s}_t=\\mathbf{s},\\mathbf{a}_t=\\mathbf{a}]\\\\&=\\sum_{t'=t}^{H}\\pi(\\mathbf{a}_{t'}|\\mathbf{s}_{t'})r(\\mathbf{s}_{t'},\\mathbf{a}_{t'})\\gamma^{t'-t}\n\\end{split}\n\\end{equation} Other formulations may work with a state-value function \\begin{equation}\\begin{split}V_{\\pi}(\\mathbf{s})&=\\sum_{\\mathbf{a}\\sim\\mathcal{A}}\\pi(\\mathbf{a}|\\mathbf{s})Q_\\pi(\\mathbf{s},\\mathbf{a})\\\\&=\\mathop{\\mathbb{E}}_{\\boldsymbol{\\tau}\\sim\\pi}[G_t({\\boldsymbol{\\tau}})|\\mathbf{s}_t=\\mathbf{s}]\\\\&=\\sum_{t'=t}^{H}\\sum_{\\mathbf{a}\\sim\\mathcal{A}}\\pi(\\mathbf{a}_{t'}|\\mathbf{s}_{t'})r(\\mathbf{s}_{t'},\\mathbf{a}_{t'})\\gamma^{t'-t}\\end{split}\\end{equation}which only depends on the state.\n\n\\section{Deriving the policy from the evaluation}\nThe policy can be determined by the $Q$-value using a greedy strategy\n\\begin{equation}\\label{eq:greedy_policy}\n    \\pi(\\mathbf{a}|\\mathbf{s})=\\mathbb{1}\\left[\\mathbf{a}=\\argmax_\\mathbf{a}Q(\\mathbf{s},\\mathbf{a}))\\right]\n\\end{equation}where $\\mathbb{1}[\\cdot]$ returns a 1 when the argument is true and 0 otherwise. This policy is deterministic, but we can make a stochastic policy using a variety of other strategies. In $\\epsilon$-greedy, the greedy action is chosen with a fixed probability (say, 75\\%), and other actions are chosen at random for the remaining 25\\% of the time. Another strategy is to use the softmax function\n\\begin{equation}\n  \\pi(\\mathbf{a}|\\mathbf{s})=\\frac{\\exp(\\beta Q(\\mathbf{s},\\mathbf{a}))}{\\sum_\\mathbf{a}\\exp(\\beta Q(\\mathbf{s},\\mathbf{a}))}\n\\end{equation}which becomes the greedy policy as $\\beta\\rightarrow\\infty$. And yet another strategy is to perform gradient ascent against the $Q$-value (when such gradients are available) to maximize it over the action space, which is used in the \"deterministic policy gradient\" algorithm\\cite{DDPG}.\n\nIf we use the state-value instead of the action-value, then we need to know how actions lead to state transitions, which is known as environment model $p(\\mathbf{s}_{t+1}|\\mathbf{s},\\mathbf{a}$), and is distinguished from the models used for policy function or state- and action-value function approximation. How do we learn the environment model? Given transitions observed by the environment, $p_\\text{obs.}(\\mathbf{s}'|\\mathbf{s},\\mathbf{a})$ which sum to one over all possible states $\\mathbf{s}'$, we can sample transitions using any policy $\\pi$ by storing or learning a function approximator to \\begin{equation}p(\\mathbf{s}'|\\mathbf{s},\\mathbf{a})=\\mathop{\\mathbb{E}}_{\\boldsymbol{\\tau}\\sim\\pi}\\left[\\text{IPW}(\\mathbf{a}_t|\\mathbf{s}_t)p_\\text{obs.}(\\mathbf{s}_{t+1}|\\mathbf{s_t},\\mathbf{a}_t)\\mathbb{1}\\left[\\mathbf{s}_t=\\mathbf{s},\\mathbf{a}_t=\\mathbf{a},\\mathbf{s}_{t+1}=\\mathbf{s}'\\right]\\right]\\end{equation}where the \\textit{inverse probability weighting}\n\\begin{equation}\\text{IPW}(\\mathbf{a}|\\mathbf{s})=\\frac{1}{\\pi(\\mathbf{a}|\\mathbf{s})}\\end{equation}is the inverse likelihood of choosing the given action with the policy used to sample trajectories $\\pi$.  The IPW allows us to rectify the bias in the data distribution determined by the policy and used to train our environment model. Sometimes the word \"propensity\" is used instead, as a rarer synonym for \"probability\" to help distinguish it from other probabilities. While IPW will be used later in this document, the topic of environment \"model-based\" reinforcement learning \\cite{model_based_rl_survey} will remain outside our scope.\n\nAnother strategy makes use of Bayesian models that possess the ability to sample their parameters according to their epistemic uncertainty \\cite{GP_BLR}, and is called Thompson sampling \\cite{thompson_sampling}. In this strategy, the model parameters are sampled, the $Q$-value is calculated from this sampled model for each available action, and the strategy chooses the action with the highest score. This approach has been shown to optimize the exploration-exploitation trade-off in bandits\\cite{thompson_sampling,bootstrap_DQN}. The use of Bootstrap Thompson Sampling (BTS), which approximates the Bayesian distribution by training an ensemble of non-Bayesian models on different bootstrap samples of the training data, was popularized by the algorithm group at Facebook for its engineering benefits, among them that prediction only requires one non-Bayesian model from the ensemble at a time, and debugging is straightforward\\cite{bootstrap_facebook}. Further developments, such as Randomized Least Squares Value Iteration, use epistemic uncertainty sampling even when determining the next-state maximizing action in the $Q$-learning phase\\cite{RLSVI} to encourage exploration.\n\nLastly, a recent and amazingly-successful strategy, called Monte Carlo Tree Search (MCTS), performs simulations during each planning stage, using a simplified policy and an environment model, where the simplified policy is guided by state- and/or value-functions that are also trained. These strategies have been very successful in perfect-information, adversarial games, but they are outside the scope of this overview. Read Section 8.11 of \\cite{sutton_barto_rl} as well as \\cite{go1} and \\cite{go2} to learn more.\n\n\\section{Training the state- and value-function policy evaluators\\label{sec:value_training}}\n\nWith this notation secured, we can finally bring in the \\textbf{Bellman equation}, which is a major foundation of both reinforcement learning and dynamic programming. It states that the best choices we make now can be determined greedily by assuming we continue to make the best possible choices later, and we can write it out mathematically as\n\\begin{equation}\\label{eq:bellman}\nQ^\\ast(\\mathbf{s},\\mathbf{a})=r(\\mathbf{s},\\mathbf{a})+\\gamma \\argmax_{a'}Q^\\ast(\\mathbf{s}',\\mathbf{a}')\n\\end{equation}where we assume that action $\\mathbf{a}$ leads us from state $\\mathbf{s}$ to state $\\mathbf{s}'$. We denote $Q^\\ast$ as the optimal Q-value (which can then be used to define the optimal policy $\\pi^\\ast$), and any function approximation for the $Q$-value, using model parameters $\\boldsymbol{\\phi}$, as $Q_{\\boldsymbol{\\phi}}$ with the associated policy $\\pi_{\\boldsymbol{\\phi}}$.\n\n\\subsection{Elaboration on the Bellman equation}\n\nWe can update the $Q$-value using \\textbf{temporal-difference} (TD) update rules that use the fact that we can always improve our estimates of the $Q$-value by iterating over our trajectories, at each time step updating our function approximator of the $Q$-value to predict targets that increment against the old estimate. The incremental value, or target, is supplied by the difference between the  reward returned by the environment for the current state and action pair ($\\mathbf{s}$, $\\mathbf{a}$) and the reward for the current time step predicted by our function approximator. We then multiply it by a learning rate $\\alpha\\in(0,1]$ in the explicit update rules, or use the learning rate in the computed policy gradient update rules (more on this later). \n\nSince the approximator covers the discounted sum of future rewards $G_t$, rather than specific rewards at each time step, we use the Bellman equation to predict the reward for the current time step as the temporal difference $G_{t+1}-G_t$ predicted by the function approximator. We can also look at higher-order approxiamtions using more than one time step, and define these quantities as \\begin{equation}\\begin{split}\nG_t^{(1)}=G_{t:t+1}^\\text{(state)}&=r(\\mathbf{s}_t,\\mathbf{a}_t)+\\gamma V (\\mathbf{s}_{t+1})\\\\G_t^{(2)}=G_{t:t+2}^\\text{(state)}&=r(\\mathbf{s}_t,\\mathbf{a}_t)+\\gamma r(\\mathbf{s}_{t+1},\\mathbf{a}_{t+1})+\\gamma^2 V (\\mathbf{s}_{t+2})\\\\G_t^{(n)}=G_{t:t+n}^\\text{(state)}&=r(\\mathbf{s}_t,\\mathbf{a}_t)+\\gamma r(\\mathbf{s}_{t+1},\\mathbf{a}_{t+1})+\\cdots\\\\&\\nobreakspace\\nobreakspace\\nobreakspace\\nobreakspace+\\gamma^{n-1}r(\\mathbf{s}_{t+n-1},\\mathbf{a}_{t+n-1})+\\gamma^n V (\\mathbf{s}_{t+n})\\end{split}\\end{equation} where we have dropped the explicit policy markers for clarity.  The analogous expression using the action-value function is \\begin{equation}\\begin{split}G_{t:t+n}^\\text{(action)}&=r(\\mathbf{s}_t,\\mathbf{a}_t)+\\gamma r(\\mathbf{s}_{t+1},\\mathbf{a}_{t+1})+\\cdots\\\\&\\nobreakspace\\nobreakspace\\nobreakspace\\nobreakspace+\\gamma^{n-1}r(\\mathbf{s}_{t+n-1},\\mathbf{a}_{t+n-1})+\\gamma^n Q (\\mathbf{s}_{t+n},\\mathbf{a}_{t+n})\\end{split}\\end{equation} where the use of the action- or state-value versions is implied by context. The analagous expression when using expectations is \\begin{equation}\\begin{split}\nG_{t:t+n}^{(\\text{expected})}&=r(\\mathbf{s}_t,\\mathbf{a}_t)+\\gamma r(\\mathbf{s}_{t+1},\\mathbf{a}_{t+1})+\\cdots\\\\&\\nobreakspace\\nobreakspace\\nobreakspace\\nobreakspace+\\gamma^{n-1}r(\\mathbf{s}_{t+n-1},\\mathbf{a}_{t+n-1})+\\gamma^n \\mathop{\\mathbb{E}}_{\\boldsymbol{\\tau}\\sim\\pi}[Q (\\mathbf{s}_{t+n},\\mathbf{a}_{t+n})|\\mathbf{s}_{t+n}]\\\\&=r(\\mathbf{s}_t,\\mathbf{a}_t)+\\gamma r(\\mathbf{s}_{t+1},\\mathbf{a}_{t+1})+\\cdots\\\\&\\nobreakspace\\nobreakspace\\nobreakspace\\nobreakspace+\\gamma^{n-1}r(\\mathbf{s}_{t+n-1},\\mathbf{a}_{t+n-1})+\\gamma^n \\sum_\\mathbf{a}\\pi(\\mathbf{a}|\\mathbf{s}_{t+1})Q (\\mathbf{s}_{t+n},\\mathbf{a}_{t+n})\\\\\\end{split}\\end{equation} and the analogous expression when using the argmax is \\begin{equation}\\begin{split}\nG_{t:t+n}^{(\\text{argmax})}&=r(\\mathbf{s}_t,\\mathbf{a}_t)+\\gamma r(\\mathbf{s}_{t+1},\\mathbf{a}_{t+1})+\\cdots\\\\&\\nobreakspace\\nobreakspace\\nobreakspace\\nobreakspace+\\gamma^{n-1}r(\\mathbf{s}_{t+n-1},\\mathbf{a}_{t+n-1})+\\gamma^n \\argmax_{\\mathbf{a}'}Q (\\mathbf{s}_{t+n},\\mathbf{a}_{t+n})\\\\\\end{split}\\end{equation}Since the action- or $Q$-value is preferred for policies that depend on the evaluators, that is what we focus on in this section, while the state-value is preferred for the policy gradients presented in the next section.\n\nOne more common elaboration, featured in the TD($\\lambda$) algorithm (discussed later), is to work with a weighted sum of discounted sums of future rewards defined as:\n\\begin{equation}\\begin{split}\\\nG_{t:h}^{(\\lambda,\\text{action})} &=(1-\\lambda)\\sum_{n=1}^{h-t-1}\\lambda^{n-1}G_{t:t+n}^\\text{(action)}+\\lambda^{h-t-1}G_{t:h}^\\text{(action)} \\\\G_{t:h}^{(\\lambda,\\text{state})} &=(1-\\lambda)\\sum_{n=1}^{h-t-1}\\lambda^{n-1}G_{t:t+n}^\\text{(state)}+\\lambda^{h-t-1}G_{t:h}^\\text{(state)} \n\\end{split}\\end{equation} where $0\\leq t<h\\leq T$ and $0\\leq \\lambda \\leq 1$.\n\n\\subsection{On- and off-policy update rules for a given state-action pair}\n\nWe can either update according to the current policy, which is slow, or by using counter-factuals, also known as \"off-policy learning\". For example, the one-step on-policy SARSA update rule for TD(0) can be written as\n\\begin{equation}\n\\label{eq:SARSA_update}\n\\begin{split}\nQ(\\mathbf{s},\\mathbf{a})&\\leftarrow Q(\\mathbf{s},\\mathbf{a})+\\alpha\\underbrace{\\left[G_{t:t+1}^\\text{(action)}-Q(\\mathbf{s},\\mathbf{a})\\right]}_\\text{$\\delta_t^\\text{(action)}$}\\\\\n&\\leftarrow Q(\\mathbf{s},\\mathbf{a})+\\alpha\\underbrace{\\left[r(\\mathbf{s},\\mathbf{a})+\\gamma Q(\\mathbf{s}',\\mathbf{a}')-Q(\\mathbf{s},\\mathbf{a})\\right]}_\\text{$\\delta_t^\\text{(action)}$}\\\\\n\\end{split}\n\\end{equation}and the one-step off-policy $Q$-learning update rule for TD(0) can be written as\n\\begin{equation}\\begin{split}\\label{eq:q_learning_update}\nQ(\\mathbf{s},\\mathbf{a})&\\leftarrow Q(\\mathbf{s},\\mathbf{a})+\\alpha\\underbrace{\\left[G_{t:t+1}^{(\\text{argmax})}-Q(\\mathbf{s},\\mathbf{a})\\right]}_{\\delta_t^{(\\text{argmax})}}\\\\&\\leftarrow Q(\\mathbf{s},\\mathbf{a})+\\alpha\\underbrace{\\left[r(\\mathbf{s},\\mathbf{a})+\\gamma \\argmax_{a'}Q_\\text{target}(\\mathbf{s}',\\mathbf{a}')-Q(\\mathbf{s},\\mathbf{a})\\right]}_{\\delta_t^{(\\text{argmax})}}\n\\end{split}\\end{equation}with the main difference that we update according the best possible next action for $Q$-learning, rather than just the one that happens to be taken by the current policy for SARSA. We have marked the TD error by $\\delta_t^\\text{(action)}$ and the Bellman error by $\\delta_t^\\text{(argmax)}$. \n\nGiven  $Q_\\text{target}$, which represents a target action-value evaluated using a different policy $\\pi_\\text{target}$, and the $n$-step  \\textit{importance sampling ratio} $\\rho$ between the target policy $\\pi_\\text{target}$ and the training policy $\\pi$ defined as \\begin{equation}\\rho^{(\\text{target})}_{t:h}(\\boldsymbol{\\tau})=\\prod_{t'=t}^{\\min(h,T-1)}\\frac{\\pi(\\mathbf{a}_{t'}|\\mathbf{s}_{t'})}{\\pi_\\text{target}(\\mathbf{a}_{t'}|\\mathbf{s}_{t'})}\\end{equation}\nwe can extend our notation to accommodate the $n$-step off-policy $Q$-learning update rule for TD($n$), writing it as\n\\begin{equation}\\label{eq:n_step_q_learning_update}\nQ(\\mathbf{s},\\mathbf{a})\\leftarrow Q(\\mathbf{s},\\mathbf{a})+\\alpha\\rho^{(\\text{target})}_{ t+1:t+n}(\\boldsymbol{\\tau})\\left[G_{t:t+n}^{(\\text{argmax})}-Q(\\mathbf{s},\\mathbf{a})\\right]\\end{equation}All TD(0) update rules add a hyperparameter $\\alpha\\in(0,1]$ that determines how quickly the $Q$-values are updated and which must be tuned to the task at hand. The equivalent formulation for the state-value function $V(\\mathbf{s})$ used in policy-gradient training covered in the next section is \n\\begin{equation}\\label{eq:n_step_q_learning_update}\nV(\\mathbf{s})\\leftarrow V(\\mathbf{s})+\\alpha\\rho^{(\\text{target})}_{ t:t+n-1}(\\boldsymbol{\\tau})\\left[G_{t:t+n}^{(\\text{argmax})}-V(\\mathbf{s})\\right]\\end{equation}\nwhere we have shifted the subindices of the importance sampling ratio by one, since for the $Q$-value, the action for the first step is defined by the arguments, and for the state-value, the final step is not considered since it's not an argument to the function. To learn more, see Equations 7.9 and 7.11 in \\cite{sutton_barto_rl}.\n\nFor on-policy SARSA algorithms, the target policy is treated as the same as the training policy, so that some presentations assume $\\rho^{(\\text{target})}_{ t+1:t+n}(\\boldsymbol{\\tau})$ to be identical to one and ignore it. Moreover, because the action is given, the one-step off-policy TD(0) update rule has no importance sampling either. \n\nSince small values for $\\pi_\\text{target}(\\mathbf{a}|\\mathbf{s})$ can introduce numerical instabilities, and small values for $\\pi(\\mathbf{a}|\\mathbf{s})$ will be a waste of calculation, how do we define $Q_\\text{target}$ so that it is as close as possible to $Q$ while also allowing us to explore other trajectories our policy may miss? The obvious choice is to use a frozen copy of the model made before each update is processed. If we denote the model parameters for our function approximation at update step $k$  as $\\boldsymbol{\\phi}_k$, and the model parameters used to predict our targets as  $\\boldsymbol{\\phi}_{k,\\text{target}}$, then this strategy can be written as $\\boldsymbol{\\phi}_{k,\\text{target}}\\leftarrow\\boldsymbol{\\phi}_{k-1}$.  Another is to store up targets over a given number of updates and then batch update the model at regular intervals. And yet another is to use both agents simultaneously with a linear (polyak) interpolation so that $\\boldsymbol{\\phi}_{k,\\text{target}}\\leftarrow \\rho\\boldsymbol{\\phi}_{k,\\text{target}}+(1-\\rho)\\boldsymbol{\\phi}$ with $\\rho\\in[0,1]$, which is also known as \"soft updating\". Note that the smoothing hyperparameter $\\rho$ should not be confused with the importance sampling ratio $\\rho(\\mathbf{a}|\\mathbf{s})$.\n\n\\subsection{The connection between multi-armed bandits and $Q$-learning}\n\nIn the case of Thompson sampling in a multi-armed bandit, a reinforcement learning problem with only one time step, the policy is greedy over the available actions with respect to a Bayesian sample of the model parameter distribution used to predict the immediate reward, while the full model it is drawn from is expected to produce a prediction of immediate reward unbiased by the data distribution used to train it. For this reason, inverse probability weighting\n\\begin{equation}\\text{IPW}_\\text{target}( \\mathbf{a}|\\mathbf{s})=\\frac{1}{\\pi_\\text{target}(\\mathbf{a}|\\mathbf{s})}\\end{equation}is used to undo the bias introduced by the target data distribution, similar to what we saw with learning the environment model earlier. \n\nHowever, we could train a Thompson-sampling policy multi-armed bandit using the sum of future rewards. In this case, we combine inverse probability weighting with importance sampling such that we arrive at traditional $Q$-learning with a twist:\n\\begin{equation}\\label{eq:n_step_q_learning_update}\nQ_\\text{TS}(\\mathbf{s},\\mathbf{a})\\leftarrow Q_\\text{TS}(\\mathbf{s},\\mathbf{a})+\\alpha\\text{IPW}_\\text{target}( \\mathbf{a}|\\mathbf{s})\\rho^{(\\text{target})}_{ t+1:t+n}(\\boldsymbol{\\tau})\\left[G_{t:t+n}^{(\\text{argmax})}-Q_\\text{TS}(\\mathbf{s},\\mathbf{a})\\right]\\end{equation}In other words, we weight our update step by the inverse probability of choosing the given action-state pair using the target policy, which is used to both estimate the update size as well as sample the states and actions used to perform the update rule. At the same time, the update rules are proportional to the product of the importance sampling ratios for all subsequent steps used to estimate the $Q$-value using the target policy. \n\nAt this point, $Q$-learning and a bandit trained on the sum of future rewards, possibly estimated after $n$ steps, appear identical except for the inverse propensity weighting, which is the same as the sampling ratio except that it replaces the numerator $\\pi(\\mathbf{a}|\\mathbf{s})$ with 1. The appearance doesn't deceive: in fact, they are equivalent. So why doesn't $\\rho_\\text{target}(\\mathbf{a}|\\mathbf{s})$ appear in the $Q$-value update rule in Equation \\ref{eq:n_step_q_learning_update}? There, we were only looking at a \\textit{given} action-state pair, assuming that we are visiting them randomly, but if we update our $Q$-value function at action-value pairs produced by another policy, then we must include inverse probability weighting to compensate for the biased data distribution used to update the model. Thus, if we use a different policy $\\pi_\\text{sample}$ to sample our state-action pairs than the policy $\\pi_\\text{target}$ used to perform the $n$-step estimate or Monte Carlo simulation, then we replace $\\text{IPW}_{\\text{target}}$ with $\\text{IPW}_{\\text{sample}}$ and the apparent similarity between the inverse propensity weighting and importance sampling terms goes away.\n\n\\subsection{Expressing the update rules through the loss function and semi-gradient methods}\n\nWe define the loss that we attempt to minimize as the negative log of the likelihood. For the normal distribution likelihood\n\\begin{equation}\n\\mathcal{L}(\\mathbf{y}_\\text{predicted},\\mathbf{y}_\\text{target})=\\frac{1}{\\sigma\\sqrt{2\\pi}}\\exp[-\\frac{(y_{i,\\text{target}}-y_{i,\\text{predicted}})^2}{2\\sigma^2}]\n\\end{equation}\nthe negative log-likelihood term in the loss, $L=-\\log\\mathcal{L}$, can be written as \\begin{equation}\\begin{split}\\label{eq:likelihood_trajectory}&L_\\text{NLL}(\\boldsymbol{\\phi},\\mathcal{D})=\\frac{1}{2}\\times\\\\&\\mathop{\\mathbb{E}}_{(\\mathbf{s},\\mathbf{a},r,\\mathbf{s}',d)\\sim\\mathcal{D}}\\left[\\rho_\\text{target}(\\mathbf{a}'|\\mathbf{s}')\\left(\\underbrace{r(\\mathbf{s},\\mathbf{a})+\\gamma(1-d)\\argmax_{\\mathbf{a}'}Q_{\\text{target}}(\\mathbf{s}',\\mathbf{a}')}_\\text{target}-\\underbrace{Q(\\mathbf{s},\\mathbf{a})}_\\text{predicted}\\right)^2\\right]\\end{split}\\end{equation}where $d=1$ when state $\\mathbf{s}'$ is terminal,  $\\sigma$ is a nuisance parameter that can be set to 1, and where we have dropped the explicit dependence on $\\boldsymbol{\\phi}$.  The dataset \\begin{equation}\\mathcal{D}=[(\\mathbf{s}_0,\\mathbf{a}_0,r_0,\\mathbf{s}'_0,d_0),(\\mathbf{s}_1,\\mathbf{a}_1,r_1,\\mathbf{s}'_1,d_1),\\dots,(\\mathbf{s}_H,\\mathbf{a}_H,r_H,\\mathbf{s}'_H,d_H)]\\end{equation}is known as the \\textit{replay buffer} and provides us with samples of transitions that have been previously encountered so that we can obtain accurate rewards, and we may discard older trajectories as our estimations improve. The inverse probability weighting $\\text{IPW}_\\text{target}$ can be ignored (assumed equal to one) if the target and training parameters are sufficiently close to each other, which can be achieved by aggressively dropping older trajectories.\n\nWe note that gradient updates of the form \n\\begin{equation}\\label{eq:simple_gradient_update}\n\\boldsymbol{\\phi}_{k}=\\boldsymbol{\\phi}_{k-1}-\\alpha \\boldsymbol{\\nabla}_{\\boldsymbol{\\phi}}L(\\boldsymbol{\\phi},\\mathbf{v})\n\\end{equation}where $L(\\boldsymbol{\\phi},\\mathbf{v})$ is the loss function of the parameters $\\boldsymbol{\\phi}$ and additional values, collected into $\\mathbf{v}$, can be performed using stochastic gradient descent using batch samples to evaluate the loss function, which means we can simplify Equation \\ref{eq:likelihood_trajectory} by considering individual samples one at a time. Working with the negative log-likelihood loss, we obtain \\begin{equation}\\begin{split}\\label{eq:semi_gradient}\n\\boldsymbol{\\phi}^{(k+1)}&=\\boldsymbol{\\phi}^{(k)}-\\frac{1}{2}\\alpha \\boldsymbol{\\nabla}_{\\boldsymbol{\\phi}}L_\\text{NLL}(\\boldsymbol{\\phi},\\mathbf{v})\\\\&=\\boldsymbol{\\phi}^{(k)}-\\frac{1}{2}\\alpha \\boldsymbol{\\nabla}_{\\boldsymbol{\\phi}}\\left(U_t-Q(\\mathbf{s},\\mathbf{a})\\right)^2\\\\&=\\boldsymbol{\\phi}^{(k)}+\\alpha \\underbrace{\\left(U_t-Q(\\mathbf{s},\\mathbf{a})\\right)}_{\\delta_t^\\text{(action)}}\\boldsymbol{\\nabla}_{\\boldsymbol{\\phi}}Q(\\mathbf{s},\\mathbf{a})\\end{split}\\end{equation} where we have replaced the term in underbrace labeled \"target\" in Eq. \\ref{eq:likelihood_trajectory} with the simpler term $U_t$ which we assume doesn't depend on $\\boldsymbol{\\phi}$, even though it may, and where we have applied the chain rule for derivatives. We drop the dependency on the state and action in the target since that will change based on whether we are working with the state-value ($V(\\mathbf{s})$) or action-value ($Q(\\mathbf{s},\\mathbf{a})$) functions. We've indicated the TD error $\\delta_t$ in the underbrace, which has imperfect analogs to dopamin in the brain (see Section 15.4 of \\cite{sutton_barto_rl}).\n\nEven though it's possible to calculate the true gradient -- it ends up being a difference between two derivatives evaluated at different state and action inputs. However, this fact actually causes gradient descent to no longer reach an equilibrium, but rather to smooth the values between the different inputs (see Section 11.5 and Example 11.2 in \\cite{sutton_barto_rl}). Moreover, keeping the the target and training models separate allows us to use the replay buffer and has been integral to breakthroughs such as the DDPG algorithm\\cite{DDPG}. \n\n\\subsection{Common varieties of policy evaluator-based algorithms}\n\nThe target $U_t$ can take on many forms, primarily by the valid entries in the cross product between the target estimator \\{SARSA, Expected SARSA, $Q$-learning, off-policy\\}, and the manner of time-difference bootstrapping \\{TD(1), TD(0), TD(n), TD($\\lambda$)\\}, giving rise to the following possibilities:\n \\begin{description}\n\\item[TD(1) (a.k.a. Monte Carlo):]\\hfill \\\\ \n$U_t=G_t$\n\\item[TD(0) SARSA:]\\hfill \\\\ \n$U_t=G_{t:t+1}^\\text{(action)}$\\\\\n$U_t=G_{t:t+1}^\\text{(state)}$\n\\item[TD(0) Expected SARSA:]\\hfill \\\\ \n$U_t=G_{t:t+1}^\\text{(expected)}$\n\\item[TD(0) $Q$-learning:]\\hfill \\\\ \n$U_t=G_{t:t+1}^{(\\text{argmax})}$\n\\item[TD(0) off-policy:]\\hfill \\\\ \n$U_t=\\rho^\\text{(target)}_{t}G_{t:t+1}^\\text{(action)}$\n\\item[TD(n) SARSA:]\\hfill \\\\\n$U_t=G_{t:t+n}^\\text{(action)}$\\\\\n$U_t=G_{t:t+n}^\\text{(state)}$\n\\item[TD(n) Expected SARSA:]\\hfill \\\\\n$U_t=G_{t:t+n}^\\text{(expected)}$\n\\item[TD(n) $Q$-learning:]\\hfill \\\\\n$U_t=G_{t:t+n}^{(\\text{argmax})}$\n\\item[TD(n) off-policy:]\\hfill \\\\ \n$U_t=\\rho_{t:t+n}^{(\\text{target})}G_{t:t+n}^\\text{(action)}$\n\\item[TD($\\lambda$) SARSA:]\\hfill \\\\ \n$U_t=G_{t:h}^{(\\lambda,\\text{action})}$\\\\\n$U_t=G_{t:h}^{(\\lambda,\\text{state})}$\n\\item[TD($\\lambda$) $Q$-learning:]\\hfill \\\\ \n$U_t=G_{t:h}^{(\\lambda,\\text{argmax})}$\n\\item[Dynamic Programming (DP):]\\hfill \\\\ \n$U_t=\\sum_{\\mathbf{a},\\mathbf{s}',r}\\pi(\\mathbf{a}|\\mathbf{s}')p(\\mathbf{s}',r|\\mathbf{s}_t,\\mathbf{a})\\left(r(\\mathbf{s}_t,\\mathbf{a})+\\gamma Q_\\text{target}(\\mathbf{s}',\\mathbf{a})\\right)$\n\\end{description}Note that the DP target requires a model of the environment $p(\\mathbf{s}',r|\\mathbf{s}_t,\\mathbf{a})$. The back-up diagrams for these targets are shown in Figure \\ref{fig:back_up_diagrams}\n\n\\begin{figure}\n\\label{fig:back_up_diagrams}\n    \\begin{center}\n    \\includegraphics[width=0.75\\linewidth]{stacked_backups_1_of_3}\n    \\includegraphics[width=0.75\\linewidth]{stacked_backups_2_of_3}\n    \\includegraphics[width=0.75\\linewidth]{stacked_backups_3_of_3}\n    \\caption{Backup diagrams for the following algorithms: Monte Carlo (top), TD(0) (middle), and DP (bottom)\\ref{david_silver_lecture_4}}\n    \\label{fig:basis_small_width}\n    \\end{center}\n\\end{figure}\n\nOf course, in all cases except for TD(1), $U_t$ depends on $\\boldsymbol{\\phi}$, but we treat it as if doesn't, which is why we call methods that use Equation \\ref{eq:semi_gradient} \\textit{semi-gradient} methods. Note that we often replace $\\boldsymbol{\\phi}$ with $\\boldsymbol{\\phi}_\\text{target}$ in our notation for the target to make this distinction, even though ideally we want to work with just one set of parameters  $\\boldsymbol{\\phi}$. However, it is insanely hard to calculate the gradient of $U_t$ with respect to $\\boldsymbol{\\phi}$, so the dependency is ignored. At this moment, we only have convergence guarantees to the local optimum for TD(1), as long as Equation 2.7 from \\cite{sutton_barto_rl} is satisfied ($\\alpha$ is properly reduced during traing). However, semi-gradients methods lie at the heart of the current state-of-the-art algorithms such as TD(0), DQN\\cite{bootstrap_DQN}, and DDPG\\cite{ddpg} anyways. \n\nWhen looking at linear functions of the form $Q_{\\boldsymbol{\\phi}}(\\mathbf{s},\\mathbf{a})=\\boldsymbol{\\phi}^\\top\\mathbf{x}(\\mathbf{s},\\mathbf{a})$, where $\\mathbf{x}(\\mathbf{s},\\mathbf{a})$ is a feature vector dependent on the state and action, this is a convex optimization problem, so that the local optimum we find is also the global one. In this case, TD(1) also has convergence guarantees, but only to a point close to the optimum called the \\textit{TD fixed point}. See sections 9.3 and 9.4 in \\cite{sutton_barto_rl} for more details.\n\nWe can connect the tabular update rules in Equation \\ref{eq:SARSA_update} to the function approximation parameter update rules in Equation \\ref{eq:semi_gradient} by observing that a linear model using categorical variables encodes them as one-hot vectors, with a 1 for any element matching the category, and a 0 for all other elements. In this case, $\\phi_i=Q(\\mathbf{s}_i,\\mathbf{a}_i)$ where the index $i$ refers to a unique state-and-action pair. In this case, we obtain \n\\begin{equation}\n\\begin{split}\n\\phi_i^{(k+1)}&\\leftarrow\\phi_i^{(k)}+\\alpha(U_t-\\phi_i^{(k)})\\cancelto{1}{\\frac{\\partial Q(\\mathbf{s}_i,\\mathbf{a}_i)}{\\partial \\phi_i}}\\\\&\\leftarrow\\phi_i^{(k)}+\\alpha(U_t-\\phi_i^{(k)})\\end{split}\\end{equation}which lines up nicely with Equations \\ref{eq:semi_gradient} and \\ref{eq:SARSA_update} when $U_t=G_{t:t+1}^\\text{(action)}$. \n\n\\section{Training the policy function itself}\n\nSome approaches learn a function approximator of the $Q$-value using parameters $\\boldsymbol{\\phi}$, and then choose the action at a given state from a pool of candidates based on their predicted $Q$-values. Others instead work with an explicit policy function $\\pi_{\\boldsymbol{\\theta}}(\\mathbf{a}|\\mathbf{s})$, dependent on parameters $\\boldsymbol{\\theta}$, which can either output probabilities for a discrete set of actions or which can output a single probability for a joint input $\\mathbf{x}(\\mathbf{s}, \\mathbf{a})$. Others still can use both approaches simultaneously.\n\nThere are many reasons to desire a policy function that is separate from the state- or value-functions. For some problems, direct policy optimization outperforms the alternative, possibly because the policy may be easier to learn and require fewer model parameters than the state- and value-functions. For another, we may want to have independent control over the stocahsticity of our policy. For example, we may want to learn a deterministic policy even though there may be multiple actions that could lead to high rewards with similar action values. Conversely, we may want to learn a stochastic policy with specified action probabilities that differ from their action values or whatever transformation we use on them.  Read Section 13.1 of \\cite{sutton_barto_rl} to learn more.\n\nTo see how the loss function works for an explicit policy model, as opposed to an action- or value-function model, we first observe the expected discounted sum of returns can be written as \\begin{equation}R(\\boldsymbol{\\tau})=G_0(\\boldsymbol{\\tau})=\\sum_{t=0}^H\\gamma^t r_t\\end{equation} Given a distribution of initial states $p(\\mathbf{s}_0)$, we write out the probability of a trajectory for a given policy as  \\begin{equation}p(\\boldsymbol{\\tau}|\\pi)=p(\\mathbf{s}_0)\\prod_{t=0}^{H-1}p(\\mathbf{s}_{t+1}|\\mathbf{s}_t,\\mathbf{a}_t)\\pi(\\mathbf{a}_t|\\mathbf{s}_t)\\end{equation}for which the expected return is written as  \\begin{equation}\\label{eq:J}J(\\pi)=\\int_{\\boldsymbol{\\tau}}p(\\boldsymbol{\\tau}|\\pi)R(\\boldsymbol{\\tau})=\\mathop{\\mathbb{E}}_{\\boldsymbol{\\tau}\\sim\\pi}[G_0(\\boldsymbol{\\tau})]=\\mathop{\\mathbb{E}}_{\\boldsymbol{\\tau}\\sim\\pi}[V(\\mathbf{s}_0)]\\end{equation}where the letter $J$, like the letter $G$, is chosen for historical reasons, in this case to relate to other equations involving loss or cost function. We thus write out our policy gradient update rule as \\begin{equation}\\label{eq:gradient_update}\n\\boldsymbol{\\theta}_{k}=\\boldsymbol{\\theta}_{k-1}+\\alpha \\boldsymbol{\\nabla}_{\\boldsymbol{\\theta}}J(\\pi_{\\boldsymbol{\\theta}})|_{\\boldsymbol{\\theta}_{k-1}}\n\\end{equation} which you'll notice looks just like Equation \\ref{eq:simple_gradient_update}, except that it uses plus sign instead of a minus sign before $\\alpha$, meaning that $J=-L$ is the \\textit{negative} loss function, or the (positive) log-likelihood, for any stochastic gradient descent algorithm. The confusion around negative signs never goes away, and is something we just have to keep in mind: gradient \\textit{ascent} maximizes the reward, and gradient \\textit{descent} minimizes the loss or cost.\n\nThe last niggling detail is to numerically compute the policy gradient. Among other issues, our current formulation contains the model of the environment $p(\\mathbf{s}_{t+1}|\\mathbf{s}t,\\mathbf{a}_t)$. For the action- and state-value functions, we used the semi-gradient approach to approximate the gradient, but in this case we can solve it exactly. This is accomplished using the proofs presented in \\cite{openAI_part3} and Sections 13.1-13.3 in \\cite{sutton_barto_rl}, which are summarized in the Policy Gradient Theorem (PGT):\n\\begin{equation}\\label{eq:policy_gradient_theorem}\n\\boldsymbol{\\nabla}_{\\boldsymbol{\\theta}}J(\\pi_{\\boldsymbol{\\theta}})=\\mathop{\\mathbb{E}}_{\\boldsymbol{\\tau}\\sim\\pi_{\\boldsymbol{\\theta}}}\\left[\\sum_{t=0}^H\\boldsymbol{\\nabla}_{\\boldsymbol{\\theta}}\\log\\pi_{\\boldsymbol{\\theta}}(\\mathbf{a}_t|\\mathbf{s}_t)\\Psi_t\\right]\n\\end{equation} where, like $U_t$ earlier, $\\Psi_t$ can take on many forms: \\begin{description}\\label{description:policy_gradient_algorithms}\n\\item[not used, but easiest to prove]\\hfill \\\\ \n$\\Psi_t =G_0$\n\\item[REINFORCE:]\\hfill \\\\ \n$\\Psi_t =G_t$\n\\item[REINFORCE with baseline:]\\hfill \\\\ \n$\\Psi_t =\\sum_{t'=t}^H\\gamma^{t'-t} r(\\mathbf{s}_{t'},\\mathbf{a}_{t'})-b(\\mathbf{s}_{t'})$\n\\item[time-difference (TD):]\\hfill \\\\ \n$\\Psi_t =G_{t:t+n}^\\text{(action)}$ for any $n$\n\\item[$Q$-Actor Critic (AC):]\\hfill \\\\ \n$\\Psi_t =Q(\\mathbf{s}_{t},\\mathbf{a}_{t})$\n\\item[$Q$-Actor Critic (AC) off-policy:]\\hfill \\\\ \n$\\Psi_t =\\rho^{\\text{(target)}}_{t}Q(\\mathbf{s}_t,\\mathbf{a}_t)$\n\\item[Advantage Actor Critic (A2C) :]\\hfill \\\\ \n$\\Psi_t =A(\\mathbf{s}_{t},\\mathbf{a}_{t})\\coloneqq Q(\\mathbf{s}_{t},\\mathbf{a}_{t})-V(\\mathbf{s}_{t})$\n\n\\end{description}\nwhere $b(\\mathbf{s})$ is any baseline function that depends only on the state $\\mathbf{s}$. The baseline function allows us to reduce the variance in our gradients, since it doesn't affect the gradient due to the normalization condition (Equation \\ref{eq:normalization}) and the logarithm. Note that we do not use any of the $Q$-learning targets such as $G_t^{(\\text{argmax})}$, since our gradients must reflect the policy we are training and don't use the Bellman equation. Also note that we drop the implicit dependency on the action and state of $\\Psi_t(\\mathbf{s}_t,\\mathbf{a}_t)$ for brevity and alignment with equations using $U_t$. \n\nCombining Equations \\ref{eq:gradient_update} and \\ref{eq:policy_gradient_theorem}, we thus obtain the policy gradient ascent update rule\n\\begin{equation}\\label{eq:policty_gradient_update}\n\\boldsymbol{\\theta}_{k}=\\boldsymbol{\\theta}_{k-1}+\\alpha \\mathop{\\mathbb{E}}_{\\boldsymbol{\\tau}\\sim\\pi_{\\boldsymbol{\\theta}}}\\left[\\sum_{t=0}^H\\boldsymbol{\\nabla}_{\\boldsymbol{\\theta}}\\log\\pi_{\\boldsymbol{\\theta}}(\\mathbf{a}_t|\\mathbf{s}_t)\\Psi_t\\right]\n\\end{equation}. One simple formula to rule over many named algorithms: REINFORCE\\cite{REINFORCE}, AC\\cite{AC}, A2C \\cite{A3C}, RG, and  GAE \\cite{GAE}\\footnote{See also \\url{https://ai.stackexchange.com/questions/10049/why-are-lambda-returns-so-rarely-used-in-policy-gradients/10061}}\n\n\nThe more-recent Proximal Policy Optimization (PPO) algorithm\\cite{ppo} has a somewhat complex-looking target but with a simple interpretation. It is \\begin{equation}\\Psi_t^\\text{(PPO)}=\\begin{cases}\\min\\left(\\frac{\\pi_{\\boldsymbol{\\theta}}(\\mathbf{a}|\\mathbf{s})}{\\pi_{\\boldsymbol{\\theta}_k}(\\mathbf{a}|\\mathbf{s})},1+\\epsilon\\right)A_{\\pi_{\\boldsymbol{\\theta}_k}}(\\mathbf{s},\\mathbf{a}), &A_{\\pi_{\\boldsymbol{\\theta}_k}}(\\mathbf{s},\\mathbf{a})>0\\\\\\min\\left(\\frac{\\pi_{\\boldsymbol{\\theta}}(\\mathbf{a}|\\mathbf{s})}{\\pi_{\\boldsymbol{\\theta}_k}(\\mathbf{a}|\\mathbf{s})},1-\\epsilon\\right)A_{\\pi_{\\boldsymbol{\\theta}_k}}(\\mathbf{s},\\mathbf{a}), &A_{\\pi_{\\boldsymbol{\\theta}_k}}(\\mathbf{s},\\mathbf{a})<0\\end{cases}\\end{equation}. In other words, it is off-policy Advantage Actor Critic (A2C) algorithm but clipped so that the target never exceeds the range of \\begin{equation}\\Psi_t^\\text{(PPO)}\\in\\left[(1-\\epsilon)\\left|A_{\\pi_{\\boldsymbol{\\theta}_k}}(\\mathbf{s},\\mathbf{a})\\right|,(1+\\epsilon)\\left|A_{\\pi_{\\boldsymbol{\\theta}_k}}(\\mathbf{s},\\mathbf{a})\\right|\\right] \\end{equation}\n\n\\section{Derivation of the policy gradient theorem and building intuition}\n\nAt first, the surprising introduction of logarithm makes one ask: why $\\boldsymbol{\\nabla}_{\\boldsymbol{\\theta}}\\log\\pi_{\\boldsymbol{\\theta}}$ instead of $\\boldsymbol{\\nabla}_{\\boldsymbol{\\theta}}\\pi_{\\boldsymbol{\\theta}}$? To cultivate intuition for the PGT, we first note that our goal is to relate the gradient of an expectation over trajectories to the expectation over trajectories of a gradient, in order to make it possible to compute. This comes up because the value we are attempting to maximize, the state-value function for a given policy at the start of all trajectories made by the policy, is the expectation of action-values over all actions. Meanwhile, the policy itself is a function of individual actions. We can relate this back to the expectation over trajectories formed by the policy by observing that since \\begin{equation}\\begin{split}\\mathop{\\mathbb{E}}_{\\boldsymbol{\\tau}\\sim\\pi_{\\boldsymbol{\\theta}}}f(\\mathbf{a}_t,\\mathbf{s}_t)&=\\sum_{\\mathbf{a}\\sim\\mathcal{A}}\\pi(\\mathbf{a}|\\mathbf{s}_t)f(\\mathbf{a},\\mathbf{s}_t)\\\\\\mathop{\\mathbb{E}}_{\\boldsymbol{\\tau}\\sim\\pi_{\\boldsymbol{\\theta}}}f(\\boldsymbol{\\tau})&=\\int_{\\boldsymbol{\\tau}}p(\\boldsymbol{\\tau})f(\\boldsymbol{\\tau})\\end{split}\\end{equation} and \\begin{equation}\\frac{\\partial f(x)}{\\partial x}=f(x)\\frac{\\partial \\log f(x)}{\\partial x}\\end{equation}and \\begin{equation}\\log p(\\boldsymbol{\\tau}|\\pi_{\\boldsymbol{\\theta}})=p(\\mathbf{s}_0)\\sum_{t=0}^H \\pi(\\mathbf{a}_t|\\mathbf{s}_t)p(\\mathbf{s}_{t+1}|\\mathbf{s}_t,\\mathbf{a}_t)\\end{equation} we have \\begin{equation}\\begin{split}\\boldsymbol{\\nabla}_{\\boldsymbol{\\theta}}J(\\pi_{\\boldsymbol{\\theta}})&=\\boldsymbol{\\nabla}_{\\boldsymbol{\\theta}}\\int_{\\boldsymbol{\\tau}}p(\\boldsymbol{\\tau},\\boldsymbol{\\theta})R(\\boldsymbol{\\tau})\\\\&=\\int_{\\boldsymbol{\\tau}}\\boldsymbol{\\nabla}_{\\boldsymbol{\\theta}}p(\\boldsymbol{\\tau},\\boldsymbol{\\theta})R(\\boldsymbol{\\tau})\\\\&=\\int_{\\boldsymbol{\\tau}}p(\\boldsymbol{\\tau},\\boldsymbol{\\theta})\\boldsymbol{\\nabla}_{\\boldsymbol{\\theta}}\\log p(\\boldsymbol{\\tau},\\boldsymbol{\\theta})R(\\boldsymbol{\\tau})\\\\&=\\mathop{\\mathbb{E}}_{\\boldsymbol{\\tau}\\sim\\pi_{\\boldsymbol{\\theta}}}\\left[\\boldsymbol{\\nabla}_{\\boldsymbol{\\theta}}\\log p(\\boldsymbol{\\tau},\\boldsymbol{\\theta})R(\\boldsymbol{\\tau})\\right]\\\\&=\\mathop{\\mathbb{E}}_{\\boldsymbol{\\tau}\\sim\\pi_{\\boldsymbol{\\theta}}}\\left[\\sum_{t=0}^{H}\\boldsymbol{\\nabla}_{\\boldsymbol{\\theta}}\\log \\pi_{\\boldsymbol{\\theta}}(\\mathbf{a}|\\mathbf{s})R(\\boldsymbol{\\tau})\\right]\\end{split}\\end{equation}where we can replace $R(\\boldsymbol{\\tau})$ with $\\Psi_t$. You'll also see, as in \\cite{sutton_barto_rl}, the policy gradient written as\\begin{equation}\\begin{split}\\boldsymbol{\\nabla}_{\\boldsymbol{\\theta}}J(\\pi_{\\boldsymbol{\\theta}})&=\\boldsymbol{\\nabla}_{\\boldsymbol{\\theta}}\\mathop{\\mathbb{E}}_{\\boldsymbol{\\tau}\\sim\\pi_{\\boldsymbol{\\theta}}}[V(\\mathbf{s}_0)]\\\\&\\propto\\sum_\\mathbf{s}p_{\\pi_{\\boldsymbol{\\theta}}}(\\mathbf{s})\\sum_\\mathbf{a}\\boldsymbol{\\nabla}_{\\boldsymbol{\\theta}}\\pi_{\\boldsymbol{\\theta}}(\\mathbf{a}|\\mathbf{s})Q_{\\pi_{\\boldsymbol{\\theta}}}(\\mathbf{s},\\mathbf{a})\\\\&=\\mathop{\\mathbb{E}}_{\\boldsymbol{\\tau}\\sim\\pi_{\\boldsymbol{\\theta}}}\\left[\\sum_\\mathbf{a}Q(\\mathbf{s}_t, \\mathbf{a})\\boldsymbol{\\nabla}_{\\boldsymbol{\\theta}}\\pi_{\\boldsymbol{\\theta}}(\\mathbf{a}|\\mathbf{s}_t)\\right]\\\\&=\\mathop{\\mathbb{E}}_{\\boldsymbol{\\tau}\\sim\\pi_{\\boldsymbol{\\theta}}}\\left[Q(\\mathbf{s}_t, \\mathbf{a}_t)\\boldsymbol{\\nabla}_{\\boldsymbol{\\theta}}\\log\\pi_{\\boldsymbol{\\theta}}(\\mathbf{a}_t|\\mathbf{s}_t)\\right]\\end{split}\\end{equation}where we can replace $Q(\\mathbf{s}_t,\\mathbf{a}_t)$ with $\\Psi_t$.\n\nThe reader may have noticed that the PGT is written like the commonly-used cross-entropy loss function, and there is a good reason for that: they come from the same derivation! The cross entropy of normalized distribution $\\boldsymbol{\\pi}$ relative to normalized distribution $\\boldsymbol{\\pi}'$ is written as \\begin{equation}\\label{eq:cross-entropy}\nH(\\boldsymbol{\\pi},\\boldsymbol{\\pi}')=-\\sum_{\\mathbf{x}\\sim\\mathcal{X}}\\pi'(\\mathbf{x})\\log\\pi(\\mathbf{x})\n\\end{equation}This means that, in a standard supervised learning setting, the parameters fitting a loss function using cross-entropy to match a normalized predicted distribution to a target distribution can be written as \n\\begin{equation}\n\\boldsymbol{\\theta}=\\argmin_{\\boldsymbol{\\theta}}\\mathop{\\mathbb{E}}_{\\mathbf{x},\\pi_\\text{target}\\sim\\mathcal{D}}\\left[\\pi_\\text{target}(\\mathbf{x})\\log \\pi_{\\boldsymbol{\\theta}}(\\mathbf{x})\\right]   \n\\end{equation} \n\nNote that with the cross-entropy loss, we are looking at the expectation over a dataset, and unlike the PGT, we are summing over all possible actions, or discrete entries in a probability distribution. However, the individual contribution of each action or discrete entry is treated the same in both distributions, and for certain model architectures, we may only have access to the outcomes of one action or discrete entry at a time. In this case, the formalisms line up exactly, except for the fact that in supervised learning, the target $\\pi'(\\mathbf{x})$ is a fixed quantity, while in the PGT, the target $\\Psi_t$ is dependent on the policy itself, we just pretend that it isn't when updating our model parameters, which means that our targets will change as soon as we update our parameters. For this reason, we never want to actually minimize our parameters over the loss function of a fixed dataset, so be aware if you see an abuse of notation writing the gradient update for policy evaluators as \\begin{equation}\\boldsymbol{\\phi}=\\argmin_{\\boldsymbol{\\phi}}\\mathop{\\mathbb{E}}_{\\boldsymbol{\\tau}\\sim\\pi_{\\boldsymbol{\\phi}}}\\left[\\left(U_t-Q(\\mathbf{s}_t,\\mathbf{a}_t)\\right)^2\\right]\\end{equation} and similarly for policy gradients \\begin{equation}\\boldsymbol{\\theta}=\\argmin_{\\boldsymbol{\\theta}}\\mathop{\\mathbb{E}}_{\\boldsymbol{\\tau}\\sim\\pi_{\\boldsymbol{\\theta}}}\\left[\\log\\pi_{\\boldsymbol{\\theta}}(\\mathbf{a}_t,\\mathbf{s}_t)\\Psi_t\\right]\\end{equation}\nHowever, the regressions that we use to train our policy evaluators do use the above notation, and assume that as we add more data to our dataset, we will approximate to the final distributions we want to optimize over. But there are stronger reasons to avoid using this notation. As von Neumann once famously quipped, \"no one understands entropy very well\"\\cite{no_one_understands_entropy}, so building a greater intuition for cross-entropy will help our intuition for the PGT.  \n\nThe form of cross-entropy loss can be grasped at a high level by first considering the likelihood of any normalized distribution prediction. For a binomial distribution of multiple coin flips with the individual probability of returning heads set to $p$, the likelihood of receiving $k$ heads over $n$ coin flips is \\begin{equation}\\mathcal{L}(n,k,p)=\\underbrace{\\frac{n!}{k!(n-k)!}}_{C(n,k)}p^k(1-p)^{n-k}\\end{equation}where the exponents come from the interchangeability of each equivalent coin flip, and the binomial coefficient $C(n,k)$ comes from the total number of such combinations. Taking the negative log of the likelihood to produce a loss function gives us \\begin{equation}L=-\\log(\\mathcal{L})=-\\log(C(n,k))-k\\log p -(n-k)\\log (1-p)\\end{equation}The single-trial case, coming from the Bernoulli distribution, takes $k\\rightarrow 1$, and the single-trial continuous case, which we need in order to compute derivatives, takes $k\\rightarrow \\infty$. This is why the continuous beta distribution takes a similar form.\n\nFor example, the targets $\\Psi_t$ \\textit{represent} a target distribution, but this distribution is not normalized nor is it the distribution we hope to ultimately approximate, since any movement to our model parameters will change the targets themselves. Rather, the targets only show us how to nudge our parameters to get to our desired policy, and this is related to why there are so many options available to us to define them. But the cross-entropy is a monotonically-increasing function that is maximized when the two distributions are identical, and which increases with the magnitude of their deviation. It can also be interpreted as the number of bits required to encode the targets using our current policy, but if the target distribution in unnormalized, the number of bits required to encode it goes to infinity, which means that minimizing the PGT loss over a static dataset will produce negative infinity loss.\n\nLastly, we observe that just like the PGT allows us to improve our model parameters using observations corresponding to the subset of actions taken during our data-collection trajectories, rather than over all possible actions, the standard supervised learning cross-entropy loss allows us to consider contributions from subsets of the possible actions rather than summing over all possible actions. However,  this leaves open the challenge of properly normalizing the targets, which requires data for all possible actions to perform.\n\n\\section{Combining policy evaluation and policy function training in actor-critic algorithms}\nActor-critic algorithms like the $Q$-Actor Critic and the Advantage Actor Critic train the value function policy evaluator along with the policy itself. Among the A2C class of algorithms there are different estimators of the advantage function for the policy part of the training process (while the the state-value or policy evaluator part is handled according to Section \\ref{sec:value_training}):\n\\begin{description}\n\\item[MC advantage or Vanilla Policy Gradient (VPG):]\\hfill \\\\\n$\\Psi_t =G_t-V(\\mathbf{s}_t)$\n\\item[TD advantage]\\hfill \\\\\n$\\Psi_t =\\delta_t^\\text{(state)}\\coloneqq G_{t:t+1}^\\text{(state)}-V(\\mathbf{s}_t)= r_t+\\gamma V(\\mathbf{s}_{t+1})-V(\\mathbf{s}_t)$\n\\item[$n$-step advantage:]\\hfill \\\\\n$\\Psi_t =G_{t:t+n}^\\text{(state)}-V(\\mathbf{s}_t)$ for any $n$\n\\item[$Q$-advantage:]\\hfill \\\\\n$\\Psi_t =Q(\\mathbf{s}_t,\\mathbf{a}_t)-V(\\mathbf{s}_t)$ for any $n$\n\\item[Generalized Advantage Estimator (GAE) :]\\hfill \\\\ \n$\\Psi_t=\\sum_{i=0}^\\infty(\\lambda\\gamma)^i\\delta_{t+i}=G^{(\\lambda,\\text{state})}_t-V(\\mathbf{s}_{t})$\n\\end{description}\n\nWhen implementing policy gradient algorithms, in practice the training process waits until the end of each episode $t=H$ to the beginning at $t=0$ to propagate information, although for some choices we can update within an episode after a given number of time steps. (Another formulation called \\textit{eligibility traces} allows us to update immediately, but requires storing additional information and applying additional update rules, see Chapter 12 of \\cite{sutton_barto_rl}.) In this setting, the REINFORCE and TD algorithms use the returns from the episode that just played out, making them on-policy algorithms, while AC and A2C use the expected returns provided by an action-value or $Q$-value function, requiring us to optimize the $Q$ function in addition to the policy. In this case, the action that is \"played out\" is the $Q$-value-maximizing action, not necessarily the action that the policy would have used during the episode, making it an off-policy algorithm.  We note the relationship between these algorithms and their constituent parts in Figure \\ref{fig:rl_venn_diagram}.\n\n\\begin{figure}\n\\label{fig:rl_venn_diagram}\n    \\begin{center}\n    \\includegraphics[width=0.75\\linewidth]{rl_venn_diagram}\n    \\caption{Venn diagram relating the value-based algorithms like TD variants of $Q$-learning and SARSA, and policy-based algorithms like REINFORCE covered in this document. \\footnotemark}\n    \\label{fig:basis_small_width}\n    \\end{center}\n\\end{figure}\n\\footnotetext{Source: \\url{https://www.davidsilver.uk/wp-content/uploads/2020/03/pg.pdf}}\n\nActor-critic algorithms require us to a compute a state-value function, possibly in addition to an action-value $Q$-function, and certainly in addition to the policy function, which opens the question of how do we organize our algorithm to accomplish this goal? We can either learn the state-value function separately, or jointly in multi-task models with the action-value and/or policy functions. In fact, any splitting between the state-value, action-value, and policy functions is available to us, so that we may not have separate sets of parameters like $\\boldsymbol{\\theta}$ for the policy and $\\boldsymbol{\\phi}$ for the action- or state-value, but rather some parameters will be shared between them and other will not. \n\nNote that multi-task models are generally limited to neural networks and bespoke implementations. Moreover, they minimize a total loss \\begin{equation}L_\\text{total}=L_\\text{actor}+L_\\text{critic}+L_\\text{regularizer}\\end{equation} according to batch updates of Equation \\ref{eq:simple_gradient_update}\\cite{online_policy_gradient_review,openAI_part3}. For the critic, which predicts action- or state-values or both, the loss function depends on the difference between our predictions and the results returned from the environment, optionally bootstrapped off of prior predictions. For the normal distribution likelihood, we can use the squared error as in \\begin{equation}\\begin{split}L_\\text{critic}^{\\text{(state)}}&=\\frac{1}{2}\\mathop{\\mathbb{E}}_{\\boldsymbol{\\tau}\\sim\\pi_{\\boldsymbol{\\theta}}}\\left[\\left(U_t-V(\\mathbf{s}_{t})\\right)^2\\right]\\\\L_\\text{critic}^{\\text{(action)}}&=\\frac{1}{2}\\mathop{\\mathbb{E}}_{\\boldsymbol{\\tau}\\sim\\pi_{\\boldsymbol{\\theta}}}\\left[\\left(U_t-Q(\\mathbf{s}_{t},\\mathbf{a}_t)\\right)^2\\right]\\\\L_\\text{critic}^\\text{(both)}&=L_\\text{critic}^{\\text{(state)}}+L_\\text{critic}^{\\text{(action)}}\\end{split}\\end{equation} Some variations may use the absolute error or the Huber loss. \n\nFor the actor, i.e., the policy gradient, our loss function, according to Equations  \\ref{eq:simple_gradient_update}, \\ref{eq:policy_gradient_theorem}, and \\ref{eq:policty_gradient_update}, is \\begin{equation}L_\\text{actor}=-\\mathop{\\mathbb{E}}_{\\boldsymbol{\\tau}\\sim\\pi_{\\boldsymbol{\\theta}}}\\left[\\sum_{t=0}^H\\log\\pi_{\\boldsymbol{\\theta}}(\\mathbf{a}_t|\\mathbf{s}_t)\\Psi_t\\right]\\end{equation} Lastly, we can also add additional losses to our final optimized quantity, such as regularization losses to reduce the model complexity, or a self-entropy term \\begin{equation}L_\\text{regularizer}^\\text{(entropy)}=\\beta H(\\pi, \\mathbf{s})=-\\beta \\sum_a\\pi(\\mathbf{a}|\\mathbf{s})\\log\\pi(\\mathbf{a}|\\mathbf{s})\\end{equation} weighted (multiplied) by a chosen positive or negative hyperparameter $\\beta$, to encourage more or less exploration as desired.  L1 and L2 regularizer losses are always available, written as \\begin{equation}L_\\text{regularizer}^{\\text{(L2)}}=\\beta\\boldsymbol{\\theta}^\\top\\boldsymbol{\\theta}=\\frac{\\sigma^2}{\\sigma_p^2}\\boldsymbol{\\theta}^\\top\\boldsymbol{\\theta}\\end{equation} where $\\beta$ is the $L2$ regularization hyperparameter and $\\sigma_p$ is a noise parameter scale hyperparameter which is equivalent to the average noise parameter for the prior, where the model parameters are all set to zero, or $\\boldsymbol{\\theta}=\\mathbf{0}$. In addition, losses that allow us to simultaneously optimize either the homoskedastic the noise parameter $\\sigma$, or the heteroskedastic noise parameter $\\sigma(\\mathbf{a},\\mathbf{s})$, can be included, derived from the negative log of the normalization constant in a normal distribution, and which we can write as \\begin{equation}L_\\sigma=N_\\text{data}\\log\\sigma\\end{equation}such that $L_\\text{regularizer}^\\text{(L2)}$ and $L_\\sigma$ balance each other out against the data fit term $L_\\text{critic}$ and/or the policy gradient loss $L_\\text{actor}$.\n\n\\section{Training with custom loss functions}\n\nStochastic gradient descent has the benefit of only ever needing to store and compute as many components as there are parameters in the model, as opposed to least squares methods that require storage of the square of the number of model parameters and computation of the cube. But the parameter update rules for the action- and state-value functions can be performed using any regression technique against the target $U_t$, including memory-based techniques. One such method, K-nearest neighbors regression, requires prediction order complexity $\\mathcal{O}(k\\times N_\\text{data}\\times N_\\text{features})$ using brute force, or $\\mathcal{O}(k\\times \\log(N_\\text{data}))$ using a k-d tree or ball tree data structure. Another, Gaussian process regression (GPR), requires prediction order complexity $\\mathcal{O}(N_\\text{data}^3)$, which is much higher. Techniques for reducing the order complexity of the GPR revolve around selecting subsets of the training points, such as the Nystrom approximation\\cite{nystrom}. \n\nFor direct policy optimization, however, we are required to craft a custom loss function, which limits our techniques to methods with explicitly-defined loss functions. For example, almost all policy gradient implementations found online use neural networks, which come with infrastructure for defining a custom loss function and computing its gradient, but any algorithm that performs stochastic gradient descent over a custom loss function will also work. In special cases, the gradients can be analytically derived and programmed explicitly. \n\nFor example, if we use a linear model for action preferences $h_{\\boldsymbol{\\theta}}(\\mathbf{s},\\mathbf{a})=\\boldsymbol{\\theta}^\\top\\mathbf{x}(\\mathbf{s},\\mathbf{a})$, where $\\mathbf{x}(\\mathbf{s},\\mathbf{a})$ represents our observations or features covering both the state and the action, we can use the softmax function to define the policy as \\begin{equation}\\pi_{\\boldsymbol{\\theta}}(\\mathbf{a}|\\mathbf{s})=\\frac{\\exp[\\beta h_{\\boldsymbol{\\theta}}(\\mathbf{s},\\mathbf{a})]}{\\sum_{\\mathbf{a}'\\sim\\mathcal{A}}\\exp[\\beta h_{\\boldsymbol{\\theta}}(\\mathbf{s},\\mathbf{a}')]}=\\frac{\\exp[\\beta \\boldsymbol{\\theta}^\\top\\mathbf{x}(\\mathbf{s},\\mathbf{a})]}{\\sum_{\\mathbf{a}'\\sim\\mathcal{A}}\\exp[\\beta \\boldsymbol{\\theta}^\\top\\mathbf{x}(\\mathbf{s},\\mathbf{a}')]}=S(\\beta \\boldsymbol{\\theta}^\\top\\mathbf{x})\\end{equation}which becomes the greedy policy as $\\beta\\rightarrow \\infty$. We can use the analytical expression to programmatically derive the gradient with respect to the weights $\\boldsymbol{\\theta}$, but it will be unique to each problem as it depends on the number of actions in the action space $\\mathcal{A}$. For more complex model loss functions, such as those for neural networks, it becomes unwieldy to programmatically define the gradients without a robust automation process. In these cases, Tensorflow, PyTorch, or a stand-alone automatic differentiator like Python's \\textit{autograd}, or its more-efficient successor \\textit{JAX}, can be used. These last two libraries work with regular functions that use a special imported version of \\textit{NumPy} to help it keep track of the operations, although it can only handle certain operations and patterns that the user must be aware of. Unfortunately, problems that require any degree of simulation, or are undifferentiable, are not well suited to analytical automatic differentiation, and instead need numerical automatic differentiation methods, which are far slower and therefore rarely used. One such solution, if the reader should pursue it, is to use the Python \\textit{numdifftools} to perform the differentiation. Fortunately for policy gradients, interaction with the environment tends to be greater overhead than calculating derivatives, since only one gradient step is taken at a time, so that \\textit{numdifftools} is viable solution.\n\nWhile it would be possible to employ function optimization methods like SciPy 's minimize package to optimize either policy evaluators or the policy itself, or to use any other non-gradient based function optimizer, these will drive the loss to its optimum over a fixed dataset and this can produce poor results. This is because, unlike in supervised learning, we do not have a fixed distribution of data, but rather the data distribution changes as the parameters change. We can see that this is the case since our actor and critic losses and their gradients are defined as expectations over trajectories produced by the policies we are optimizing, rather than sums over all possibilities. In fact, it is because we measure our policies through the data distribution that they return to us that we can slowly learn optimal policies without any reinforcement learning tricks at all. \n\nThis is a major achievement of both semi-gradient and policy gradient methods, since it brings us back to earth by allowing us to sample these expectations using the most recent policy, and with importance sampling, we can account for the data distribution drift in off-policy training. However, we must keep in mind that the loss functions we compute at any step of optimization are limited by the expectations over trajectories we had to compute using a different policy than the one we end up with because it didn't exist yet. In other words, our goal is not to optimize the loss at any given stage of training, but to optimize the rewards of the system, which the losses help us achieve at each step. \n\nWe can gain greater intuition for why we use gradient descent in training the policy function by observing that the similarity between the Policy Gradient Theorem and cross-entropy loss used to train models that predict normalized distributions can be used to build a \"ladder of certainty\" when developing your algorithm. For example, a policy function can be trained using targets defined by the softmax function over the $Q$-values of another model, and targets for all possible actions don't need to be trained simultaneously in the policy function. This procedure becomes equivalent to learning a softmax policy over the $Q$-value and can form a bridge to training against other targets like the advantage function. However, when we learn a softmax policy over $Q$-values, we aim to strictly minimize our loss as in traditional supervised machine learning, which will fail dramatically when using non-normalized targets, or when the learning $\\alpha$ is too large, since the loss will overflow to negative infinity.\n\nAs a result, one rarely sees solutions that don't use gradient descent or require the tuning of a learning rate $\\alpha$ hyperparameter. For exact, online methods, like Bayesian linear regression, we account for the changing data distribution of the loss function because each step of training amounts to adding new rows of data, so that we are ultimately minimizing or maximizing the average of the expectations over the history of the parameters, similar to stochastic gradient descent. It is up to numerical experiments to fine-tune $\\alpha$, or the decay factor we use to drop out old rows of data, to see how the different methods compare. When using neural networks with gradient descent, it is also important to scale the inputs to the standard normal where the model has the most capacity, and to be aware that the model interpolates linearly through gaps of data, and extrapolates linearly outside the domain of the standard normal. This can be addressed by either stalling training until a data sample has been made, or one can apply batch normalization\\cite{batch_normalization} as a regularization technique.\n\n\n\n\\section{Engineering considerations and pitfalls}\n\nFrom an engineering perspective, note that the formalism for training the state- and value-functions, regardless of the target $U_t$, is equivalent to the formalism for \\textit{contextual multi-armed bandits} (CMABs), and both align between versions with discrete and continuous actions. While both policy evaluator learning and bandits may train against targets compiled during a loop at the end of each episode that rewinds the previous actions, states, and rewards, only $Q$-learning incorporates the $\\argmax_\\mathbf{a}$ over future steps before it is reflected in the policy being trained thanks to the Bellman equation. This allows information about successful policies to propagate back to earlier steps before they are reflected in the policy used to collect data, making training in situations where planning is relevant much faster. Since we incorporate the unique qualities of $Q$-learning entirely during the collection loop that passes targets to the function approximator, we can use a CMAB under the hood for both training and prediction in the collection loop.  Direct policy optimization, meanwhile, enjoys a similar structure, except with a different loss function that doesn't strictly fit the regression structure.\n\nJust as properties of the update algorithm made true gradient methods using the state- or action-value functions unstable, requiring the development of semi-gradient methods, certain combinations of algorithm properties can produce other instabilities. One particular combination, known as the \\textit{deadly triad}, must be particularly avoided:\n\\begin{enumerate}\n\\item Bootstrapping the target $U_t$, i.e., using any target besides Monte Carlo such as TD\n\\item Off-policy training\n\\item Non-linear function approximation\n\\end{enumerate}\nTo learn more, see Section 11.3 in \\cite{sutton_barto_rl}.\n\nUsing function approximation for both the policy evaluation and the policy itself necessarily implies partial observability of our environment, and while losing observations can kill our ability to learn a successful policy, the methods described here will do as well as we possibly can given the handicap. However, we can go the other way and add observations, too, and an obvious choice is to add historical data from earlier the trajectory. This can be accommodated by either encoding them as truncated and padded concatenations to the original feature vector, or by using sequential models like RNNs and LSTMs to encode the historical data into a fluid representation. In addition, there are a host of feature extraction, kernel approximation, convolution, and dimensionality reduction methods that can be employed, in parallel, serial, or along any directed acyclic graph (DAG) that defines your feature pipeline, as shown in Figure \\ref{fig:ml_map}. But remember, as we add more expressiveness and/or features to our models, that is, as we add more parameters, we increase our model capacity but also dramatically reduce the speed at which it learns. A general rule of thumb is that by using $M$ times more features, it takes $M^2$ more samples to move out of exploration into exploitation.\n\\begin{figure}\n\\label{fig:ml_map}\n    \\begin{center}\n    \\includegraphics[width=0.75\\linewidth]{ml_map.png}\n    \\caption{Building a feature extraction and transformation pipeline can be a challenge, and this flowchart is a terrific way to explore your options. The online version provides links to implementations in the Python package \\textit{scikit-learn} \\footnotemark}\n    \\end{center}\n\\end{figure}\n\\footnotetext{Source: \\url{https://scikit-learn.org/stable/tutorial/machine_learning_map/index.html}}\n\nMoreover, policy and action-value functions generally only work when we incorporate interaction features between the state and action features, except for decision-tree based algorithms like random forests and gradient-boosted trees, whereas neural networks are designed to learn which interactions are most useful at the cost of extensive hyperparameter tuning. Since there are so many ways to add features, we can bring down the complexity of these computations and to help our agents learn faster by applying randomized projections onto any subset of our feature space, but this also introduces additional hyperparameters to tune. We recommend randomized projections over Principle Component Analysis (PCA) since random projections to not require an input data sample before we can train our function approximators, and because there is no particular reason to expect the signal to be insensitive to the low-variance features that are filtered out in PCA. Other options for dimensionality reduction include manifold learning, which also require data sampling, and for which there are many options, including VAE, t-SNE, and spectral embedding. See \\url{https://scikit-learn.org/stable/modules/manifold.html#spectral-embedding} for a list of well-implemented options.\n\nInterestingly, there is a parallel for randomized projections in the kernel space for problems that are better served that way. As covered in \\cite{GP_BLR}, we can project our inputs into basis functions that allow us to use a linear regression to approximate an equivalent Gaussian. This allows us to perform regressions in the feature space, for example, by using Bayesian linear regression, with order complexity $\\mathcal{O}(N_\\text{basis})$ for gradient methods and  $\\mathcal{O}(N_\\text{basis}^3)$ for exact methods, as opposed to Gaussian process regression with order complexity $\\mathcal{O}(N_\\text{data}^3)$, all while approximating the kernel regression. Popular choices here include the Nystrom approximation, which amounts to using the top $N$ principle components of the kernel function evaluated between each data point by simply dropping data points at random, and Random Fourier Features.\n\nWhen computing the $\\argmax_\\mathbf{a}$ for $Q$-learning style algorithms, we may run into difficulties for problem spaces with continuous or large action spaces. However, we have several options at play. The first is to simply sample the action space randomly and rank the predicted $Q$-values for all of them. This is a popular approach in derivative-free Bayesian optimization. If the action space is continuous, another option is to apply gradient ascent, but this can be computationally expensive. And lastly, we can encourage exploration by using Thompson sampling when sampling for the $\\argmax$, as in \\cite{RLSVI}.\n\n\\section{Additional resources}\nAdditional resources can be found below:\n\\begin{itemize}\n\\item RLlib from Ray covers different algorithms and whether they can accept discrete or continuous actions, as well as additional support such as sequential models, multi-agent implementations, and multi-GPU training. See \\url{https://docs.ray.io/en/latest/rllib-algorithms.html}\n\\item Lilian Wang has created one of the most thorough overview of policy gradient based algorithms at \\url{https://lilianweng.github.io/lil-log/2018/04/08/policy-gradient-algorithms.html}\n\\item Spinning Up from OpenAI offers a terrific overview of reinforcement learning concepts as well as deep dives (and implementations) of some of the more advanced algorithms such as Proximal Policy Optimization (PPO), Deep Deterministic Policy Gradient (DDPG), and Soft Actor-Critic (SAC). However, some of their explanations, such as around the policy gradient, can be obscure and needlessly confusing. See \\url{https://spinningup.openai.com/en/latest/}\n\\item David Silver's lecture slides at University College London are a legendary resource for succinct coverage of the main concepts in reinforcement learning. See \\url{https://www.davidsilver.uk/teaching/}\n\\item Julien Vitay provides a sprawling overview of deep reinforcement learning at \\url{https://julien-vitay.net/deeprl/Introduction.html}\n\\end{itemize}\n\n\\printbibliography\n\\end{document}\n", "meta": {"hexsha": "dd60f98a31a0749ac2dc9e129c9dc0e13155f30a", "size": 72408, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "main.tex", "max_stars_repo_name": "KoyoteScience/real-world-reinforcement-learning", "max_stars_repo_head_hexsha": "120e071a27dd0ad6b1cf05bd18a8f6b4d8d82f32", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.tex", "max_issues_repo_name": "KoyoteScience/real-world-reinforcement-learning", "max_issues_repo_head_hexsha": "120e071a27dd0ad6b1cf05bd18a8f6b4d8d82f32", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.tex", "max_forks_repo_name": "KoyoteScience/real-world-reinforcement-learning", "max_forks_repo_head_hexsha": "120e071a27dd0ad6b1cf05bd18a8f6b4d8d82f32", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 182.3879093199, "max_line_length": 3591, "alphanum_fraction": 0.7604546459, "num_tokens": 19707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.34226221457390893}}
{"text": "\\section{An Extended Model}\n\nAfter asserting that a deep reinforcement learning agent can navigate the environment, the model is extended to address the issues with the simple model. The first issue that should be addressed is that women should not permanently withdraw from the labour force. Secondly, the log-function used for the sub-utilities caps the utility very hard, which implies that very small perturbations of $\\beta_L$ makes the agent substitute into one of the extremes. The agent end up working either 45 hours exclusively or working 0 hours exclusively, de facto making leisure and consumption perfect substitutes. The agent should ideally be more balanced, implying the functional form of the sub-utilities should have a steeper curvature. This leads to a new expression of the utility function:\n\n\\begin{equation}\n    U_t = \\beta_L L_{t}^\\zeta + \\beta_Y Y_t^{\\zeta}\n\\end{equation}\n\nThe fertility process should also be extended. I now assume that each household can have a maximum of four children. The environment tracks how many children the family has, and the associated age. In each period the number of children in the household can potentially increment by one.\n\n\\begin{equation}\n    K_{t+1} = K_t+ \\psi_t, \\qquad \\psi_t \\mid Q_t \\sim Bernoulli (p_\\psi(Q_t))\n\\end{equation}\n\nI let $B$ be a vector of size 4 equal to the maximum number of children. Furthermore, I let the vector $C$ denote the individual age of the children also of size 4. This implies that for index $i$ of vector $B$ corresponds to the $k$'th child, index $i$ of vector $C$ implies the same child's corresponding age.\n\n\\begin{equation}\n    B_t[i]  = \\begin{cases}\n        1 & \\text{if }  i \\leq K_t \\\\\n        0 & \\text{else}\n    \\end{cases}\n\\end{equation}\n\nThe age vector is defined as:\n\n\\begin{equation}\n    C_{t+1} = C_t + B_{t+1}\n\\end{equation}\n\nThe formulation ensures the age of a child increments if and only if the child is born.\n\nFinally, the leisure component of the model needs to be adjusted to take into account the number of hours used per child. Let $J$ denote the number of hours used on children. Children below age 3 takes 10 hours per week, children in the age 3 up to age 15 takes 3.5 hours per week, and children above does not reduce the leisure time of women,  using the numbers found by \\textcite{ekert-jaffe_time_2015}. \n\n\\begin{equation}\n    J_t = \\sum_{i=1}^4 \\begin{cases}\n        0.0 & \\text{if } B_t[i] = 0 \\\\\n        10.0 & \\text{if } B_t[i] = 1 \\land C_t[i] < 3 \\\\\n        3.5 & \\text{if } B_t[i] = 1 \\land 3 \\leq C_t[i] < 16 \\\\\n        0 & \\text{if } B_t[i] = 1 \\land  16 \\leq  C_t[i] \n    \\end{cases}\n\\end{equation}\n\nAnother thing to address is, that empirically women tend to work less when they are young (in the age of 18 to 30), gradually increasing the number of working hours as shown in figure \\ref{fig:dqi_model1_average_path_sim_vs_empirical}.  Looking to figure \\ref{fig:educ_empirical}, it could appear to be a consequence of women doing full time education, not having the time to work (more than a few hours a week). To address this problem I add an education variable to the model. In this setup the education does not add to higher salary instead it only goes in the model as additional time spent. Education is assumed to be exogenous, and over the life cycle the women will with some probability be done with education, not to return ever again to the education system. Using \\textbf{FOLK1A} from Statistics Denmark I find the total number of women in a given age group. The total number of women for a given age group doing full time education is found in the source \\textbf{UDDAKT10} also from Statistics Denmark. I fit this with a linear regression and let the number of women doing full time education decrease linearly from age 18 to 30. This can be seen in Figure \\ref{fig:prob_educ_full_time}. I model the education the following way:\n\n\\begin{figure}[ht]\n\\begin{subfigure}{.5\\textwidth}\n  \\centering\n  \\includegraphics[width=1\\linewidth]{figures/total_women_vs_education.png}\n  \\caption{FTE vs. Total Number of Women}\n  \\label{fig:educ_empirical}\n\\end{subfigure}%\n\\begin{subfigure}{.5\\textwidth}\n  \\centering\n  \\includegraphics[width=1\\linewidth]{figures/prop_women_doing_full_time_education.png}\n  \\caption{Fraction of Women in FTE vs. Linear Fit}\n  \\label{fig:prob_educ_full_time}\n\\end{subfigure}\n    \\caption{Women and Full Time Education (FTE)}\n    \\label{fig:educ_women}\n\\end{figure}\n\n\\begin{equation}\n    E_{t+1} = E_{t} \\cdot \\iota_t, \\qquad \\iota_t \\mid Q_t \\sim  Binomial(p_{\\iota}(Q_t))\n\\end{equation}\n\nSo in each period with some probability $E^{prob}_t \\equiv p_{\\iota}(Q_T)$ the women will end full time education. Both $E$ and $E^{prob}_t$ is part of the state space. Since women do full time education, I assume time used is 37 hours per week.\n\nIt is assumed for simplicity that human capital accumulation does not depreciate or accumulate when the agent is under full time education:\n\n\\begin{equation}\n    G_{t+1} = \n    \\begin{cases}\n        G_t(1 - \\delta) + \\frac{H_t}{37}, & \\text{if } E_t > 0 \\\\\n        G_t & \\text{else}\n    \\end{cases}\n\\end{equation}\n\n\nFinally, note that the utility is calculated on a weekly basis instead of on an annual basis. This is again done, such that the sub utilities, do not squeeze the values too hard, as was the case in model 1, making estimating of the model very hard, due to small perturbations of $\\beta_L$ having too large effect. Compared to the original model $f^M(Q_t)$ now represents the total income per week of the husband rather than the annual total income.\n\n\\begin{equation}\n    L_t = 24 \\cdot 7 - H_t - J_t - E_t \\cdot 37\n\\end{equation}\n\nIn Denmark education is coupled with a transfer from the state. This transfer is added as well, such that the household will receive a transfer of $tr = \\frac{6000 DKK \\times 12}{52} \\approx 1400 DKK$ each week from the government, while the women is studying. This ratio is approximately doubled if the women gets a child during the education \\parencite{noauthor_satser_nodate-1}. The total income of the household is equal to:\n\n\\begin{equation}\n    Y_t = H_t \\cdot W_t + f^M(Q_t) + E_t (tr + \\mathbf{1} \\{ K_t > 0 \\} \\cdot tr)  \n\\end{equation}\n\n\nSummarizing the model; using a lot of the framework from the simple model a couple of extensions is made. The state space is now of 14 dimensions containing $(Q)$ age, $(G)$ human capital, $(Z)$ idiosyncratic wage path, $(K)$ the number of children in at time $t$ in the household, a vector of size four $(B)$ corresponding to the number of children the household contain, a vector of size four $(C)$ containing the age of the individual children, a dummy $(E)$ that indicates if the women is under education, and lastly $(E^{prob})$ a number between 0 and 1 that indicates the probability of being enrolled in full time education next period. The action space is slightly tweaked to contain $\\{ 0, 15, 25, 37\\}$ representing the discreet choices of hours the woman can choose to work. This formulation is closer to that of \\textcite{francesconi_joint_2002}, where he only considers the choices: \\textit{no work}, \\textit{part-time}, \\textit{full-time}. In contrast with \\textcite{francesconi_joint_2002} this model distinguishes between two types of part-time work; 15 and 25 hours a week. The model specification is:\n\n\\begin{equation}\n    \\textbf{State space: }\\statespace = \\R^2 \\times \\{0, 1, 2, 3, 4\\} \\times \\{18, 19, \\cdots , 60\\} \\times \\{0, 1\\}^4 \\times \\{0, 1, \\cdots, 18\\}^4 \\times \\{0,1\\} \\times [0, 1]\n\\end{equation}\n\n\\begin{equation}\n    \\textbf{Action space: }\\actionspace = \\{0, 15, 25, 37\\}\n\\end{equation}\n\nAdditionally, the model contains the following parameters: $\\alpha=4.609, \\eta_G = 0.164, \\eta_{G^{2}}=0.015, \\delta=0.209, \\sigma_\\epsilon = 15.11, \\beta_L, \\beta_Y = 1, W_{min} = 120, tr = 1600, \\zeta=0.5$, using the values of the Mincer equation from the parameter calibration performed earlier! A recursive formulation of the model is presented below:\n\n\\begin{align}\n    U_t(L_t, Y_t) &= \\beta_L L_t^{\\zeta} + \\beta_Y Y_t^{\\zeta}\\\\\n    L_t(K_t, H_t, J_t, E_t) &= 24 \\cdot 7 - H_t - J_t - E_t \\cdot 37\\\\\n    \\log \\tilde{W}_t (G_t) &= \\alpha + \\eta_G G_t + \\eta_{G^2} G_t^2 \\\\\n    W_t(\\tilde{W}_t, Z_t) &= \\max(W_{min} , \\tilde{W}_t  + Z_t)  \\\\\n    Y_t(Q_t,H_t, W_t, E_t, K_t) &= 46 \\cdot H_t \\cdot W_t + f^M(Q_t) +  E_t (tr + \\mathbf{1} \\{ K_t > 0 \\} \\cdot tr)\\\\\n    J_t (B_t, C_t) &= \\sum_{i=1}^4 \\begin{cases}\n        0.0 & \\text{if } B_t[i] = 0 \\\\\n        10.0 & \\text{if } B_t[i] = 1 \\land C_t[i] < 3 \\\\\n        3.5 & \\text{if } B_t[i] = 1 \\land 3 \\geq C_t[i] < 16 \\\\\n        0.0 & \\text{if } B_t[i] = 1 \\land  16 \\geq  C_t[i] \n    \\end{cases} \\\\\n    B_t[i] (K_t) &= \\begin{cases}\n        1 & \\text{if }  i \\leq K_t \\\\\n        0 & \\text{else}\n    \\end{cases}\n\\end{align}\n\nLaw of motion:\n\n\\begin{align}\n    Q_{t+1}(Q_t) &= Q_t \\\\\n    K_{t+1}(K_t, Q_t)  &= K_{t} + \\psi_t, \\qquad \\psi_t \\mid Q_t \\sim Bernoulli(p_\\psi(Q_t))  \\\\\n    Z_{t+1}(Z_t) &= Z_t + \\epsilon_t, \\qquad \\epsilon_t \\sim \\ndist(0, \\sigma_\\epsilon)\\\\\n    G_{t+1}(G_t, H_t, E_t) &= \n    \\begin{cases}\n        G_t(1 - \\delta) + \\frac{H_t}{37}, & \\text{if } E_t > 0 \\\\\n        G_t & \\text{else}\n    \\end{cases} \\\\\n    C_{t+1}(C_t, B_{t+1}) &= C_{t} + B_{t+1} \\\\\n    E_{t+1}(E_t, Q_t) &= E_t \\cdot \\iota_t, \\qquad \\iota_t \\mid Q_t \\sim Binomial(p_\\iota(Q_t))\n\\end{align}\n\n\n", "meta": {"hexsha": "c97efe43dcd92e4b0e51813374a8e6fd41bbc410", "size": 9371, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/model2.tex", "max_stars_repo_name": "JakartaLaw/speciale", "max_stars_repo_head_hexsha": "95d89c281b9d8f73065a823cba97a5bedcbf129d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/model2.tex", "max_issues_repo_name": "JakartaLaw/speciale", "max_issues_repo_head_hexsha": "95d89c281b9d8f73065a823cba97a5bedcbf129d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/model2.tex", "max_forks_repo_name": "JakartaLaw/speciale", "max_forks_repo_head_hexsha": "95d89c281b9d8f73065a823cba97a5bedcbf129d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 67.9057971014, "max_line_length": 1241, "alphanum_fraction": 0.702379682, "num_tokens": 2904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.34226221457390893}}
{"text": "% ****** Start of file response.tex ****** %\n\\documentclass{article}\n\n%===============================================================================\n% Import packages\n%===============================================================================\n\n\\usepackage[top=0.8in,bottom=1in,left=1in,right=1in]{geometry}\n% Physics package\n\\usepackage{physics}\n% Paragraph skip package\n\\usepackage[parfill]{parskip}\n% AMS packages\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{mathtools}\n% Color package\n\\usepackage[dvipsnames]{xcolor}\n% Acronym package\n\\usepackage[acronym]{glossaries}\n% SI units package\n\\usepackage{siunitx}\n% Hypertext package\n\\usepackage[hidelinks]{hyperref}\n% Bold math\n\\usepackage{bm}\n% Other packages\n\\usepackage{graphicx}\n\\usepackage{textcomp}\n\\usepackage{float}\n\\usepackage{cite}\n\\usepackage{multicol}\n\\usepackage{multirow}\n% \\usepackage{kpfonts}\n\n% Bibliography style\n\\usepackage[numbers,sort&compress]{natbib}\n\\bibliographystyle{apsrev4-1}\n\n\\begin{document}\n\n% Define acronyms\n\\newacronym{tls}{TLS}{two-level system}\n\n%===============================================================================\n% Add date\n%===============================================================================\n\\today\\\\\n\nAshot Melikyan,\\\\\nAssociate Editor,\\\\\nPhysical Review B.\\\\\n\nDear Professor Melikyan,\n\nThank you very much for your effort in managing the review process of our manuscript. We are also thankful for the reviewer comments, and believe the second version of the manuscript we submit herewith has been significantly improved by the constructive criticism we received. Additionally, the subsequent sections of this document discuss the reviewer comments and our responses to them.\n\nPlease note that in the following sections, the statements in {\\color{RoyalBlue} \\textbf{blue}} are the comments of the reviewers. Our responses are shown in black letters, and the modifications we have done to the manuscript are given in {\\color{Red} red}.\n\n\\subsection*{General changes to the manuscript}\n\n\nWe have made some minor changes in language and presentation to improve the clarity and organization of the manuscript.\n\\begin{itemize}\n    \\item Section I - seventh paragraph (page 2): \\\\\n        {\\color{Red} In Sec. VII, we discuss the physical significance of our theoretical results and their possible use in future nanoelectronic devices.\n        Finally, we summarize our findings and present our conclusions in Sec. VIII.}\n    \\item Section VI - fourth paragraph (page 8): \\\\\n        {\\color{Red} Considering the effects of the applied dressing field on the longitudinal conductivity of 2DEG, we can identify that the dressing field has sharpened the conductivity peaks.}\n    \\item Section VIII - first paragraph (page 10): \\\\\n        {\\color{Red} Finally, we derived analytical expressions for the diagonal components of the electric conductivity tensor concerning the 2DEG quantum Hall system operates at low temperatures.}\n\\end{itemize}\n\n\\subsection*{Response to the comments of Reviewer 1}\n\nWe would like to thank the reviewer for bringing the deficiencies of our manuscript to our attention and providing constructive feedback to improve the quality of our work. We have considered all of your suggestions seriously and revised our manuscript as described below.\n\n\\subsubsection*{Comment 1 -\n\\color{RoyalBlue} My concern is that the manuscript is heavily skewed towards a purely mathematical formulation of the problem. It has a minimal connection to realistic two-dimensional electron systems. The manuscript does not discuss how the results can be applied to understanding mechanisms of charge transport in nanoelectronic devices and can be used to optimize device performance. Without such discussion, the manuscript will have a minimal impact on the community working on developing nanoelectronics.}\n\nWe agree that our work has a theoretical bias, and the reader may benefit from some application perspective from our theoretical results to characterize or design nanoelectronic devices. Therefore, we have discussed the physical significance of our theoretical results and their possible use in optimizing nanoelectronic device performance. First, we added a detailed comparison between our theoretical results and experiment observations when no radiation is present.  We also added a new section (Section VII) on this very aspect.\n\n\\begin{itemize}\n  \\item Section VI - third paragraph (page 8):\\\\\n  {\\color{Red}\n  By comparing the theoretical \\cite{ando72,ando74_1,ando74_2,ando74_3,ando74_4,ando82,endo09} and experimental \\cite{endo09,wakabayashi78,ochiai190,mancoff96,arapov02,grbic04,caviglia10} studies on the magnetoresistance of 2DEG quantum Hall systems when no radiation is present against our results, we can identify that longitudinal conductivity oscillations in Fig. 4 are a repetition of the Shubnikov–de Haas(SdH) oscillations.\n  As observed in the experimental work of Caviglia \\textit{et al.} \\cite{caviglia10}, the period of SdH oscillations depends only on the perpendicular component of the magnetic field to the plane of the 2DEG.\n  Therefore, we can identify that many experiments on different types of 2DEGs at low-temperatures \\cite{endo09,ochiai190,mancoff96,arapov02,grbic04,caviglia10} have analyzed these SdH oscillations against the applied magnetic field's amplitude.\n  The cyclotron frequency ($\\omega_0$) of the system depends on the magnetic field's perpendicular component to the plane of the 2DEG.\n  The gate voltage modifies the Fermi level of the system.\n  Since the Landau level energy is only dependent on the cyclotron frequency, this gate voltage variation under a constant magnetic field amplitude generates the same SdH oscillations.\n  Interestingly, this oscillatory behavior against applied gate voltage has been observed experimentally by Wakabayashi \\textit{et al.} \\cite{wakabayashi78} in an inversion layer on a silicon surface at low temperature.\n  By comparing these observations against our results in Fig. 4, we can identify that our oscillations also show the same characteristic behavior; i.e  $\\hbar\\omega_0$ periodic SdH oscillations against the Fermi energy.\n  Furthermore, when we increase the gate voltage, the Fermi level rises. As illustrated in Fig. 4, this will result in a higher conductivity peak value at the higher-order Landau levels. This same behavior was also observed in the experimental observations presented in Ref. \\cite{wakabayashi78}.\n  In our work, we provide analytical results describing the controllability of these conductivity regions using a dressing field.\n  }\n  \\item Section VII (page 9):\\\\\n  {\\color{Red}\n  \\subsection*{VII. PHYSICAL SIGNIFICANCE OF THE OUTCOMES}\n\n  With the realization of 2DEGs in Si-MOSFETs (Metal Oxide Semiconductor Field Effect Transistors) \\citep{fowler66}, Klitzing \\textit{et al.} \\cite{klitzing80} made the first transport measurements on such systems to reveal the quantum Hall effect. The empirical discovery of these unusual properties marked the beginning of a whole new realm in condensed matter physics that continues to produce phenomenal advancements in electronic systems. The quantum Hall effects in a 2DEG under a static magnetic field are described by plateaus quantized to integer values of the conductivity quantum ($\\flatfrac{e^2}{\\hbar}$) in the off-diagonal conductivity, with simultaneous peaks at inter-plateau transition for the diagonal conductivity \\cite{endo09}. This is due to the applied magnetic field and it changes the energy spectrum of 2DEG dramatically. The magnetic field causes the density of states in 2DEG to split up into a sequence of delta functions, separated by an energy $\\hbar\\omega_0$, with $\\omega_0$ the cyclotron frequency which depends on the applied magnetic field.\n  However, experimental results demonstrate that these Landau levels are broadened and the main source of these broadening at low temperatures is the disorders in materials \\cite{ando85,dial07}. The broaden sequence of delta functions of the density of states implies the oscillating behavior in the experimental measurements of longitudinal conductivity which is known as SdH oscillations \\cite{endo09,wakabayashi78}.\n\n  Our theoretical analysis on longitudinal conductivity behavior of dressed quantum Hall system was developed by considering low-temperature limit with Gaussian impurity broadening assumptions.\n  As illustrated in Fig. 4, we can describe the experimentally observed SdH oscillation results in Refs.\\cite{endo09,wakabayashi78} through our model.\n  Under the undressed condition, our results overlap with the conductivity measurement of quantum Hall systems \\cite{endo09}. Strikingly, we show in Fig. 5 that we can manipulate the broadening of these conductivity peaks using an external dressing field. At low temperatures, the principal cause of broadening of these conductivity peaks is impurity-induced scattering. Using an external dressing field, we can suppress the impurity-induced scattering and this results a reduction of both the scattering-induced broadening and the longitudinal conductivity peaks.\n\n  Research on novel states of matter has driven the evolution of present-day nanoelectronic devices. In particular, controllable manipulation of material properties through a gate electric field has revolutionized the development of material science and technology \\cite{ahn03,deng18}.\n  The charge carrier concentration of a system is an imperative parameter that defines its conductivity properties.\n  As we can manipulate the charge carrier concentration using an electrostatic field-effect, we exert significant control over the conductivity externally.\n  A 2DEG under static magnetic field with quantum Hall effects is an excellent example that illustrates how the gate electric field controls conductivity.\n  We also observed that a considerable number of studies exist on charge transport in the quantum limit that employed different types of 2D field-effect transistors (FETs) subjected to magnetic fields \\cite{wakabayashi78,yang18,long20,li14}. Yang \\textit{et al.} \\cite{yang18} study shows quantized Hall plateaus and SdH oscillations for longitudinal conductivity against gate voltage in black phosphorus FET under static magnetic fields at low temperatures. Since the Fermi level of a system can be altered with the applied gate voltage, our Fig. 4 depicts this result.\n  In particular, our analysis shows that we can manipulate the broadening of the conductivity regions using an external dressing field. Although Yang \\textit{et al.} \\cite{yang18}, achieved broadening in longitudinal conductivity peaks by changing the temperature in a low range, in this study we presented a general theory on manipulating longitudinal conductivity broadening using a high-intensity electromagnetic field.\n\n  The realization of the underlying mechanism of 2D FETs in the quantum realm promises its potential in next-generation nanoelectronic applications. In a particular application that uses the switching mechanism of the above-discussed FETs with quantum Hall effects, we can achieve high and low output conductivities by changing the input gate voltage. As a result of manipulating the broadening of conductivity regions, we can limit the broadening of conductivity peaks around Landau levels using a dressing high-intensity electromagnetic field. This will enhance the sensitivity of FETs which provides the ability to observe narrow changes in gate voltage.\n  Furthermore, adopting the mechanism presented in Ref. \\cite{hirakawa01}, we can manipulate conductivity peaks into very sensitive, narrowband high-frequency radiation detectors.\n  We envision these advances in nanoelectronics from our theoretical model and knowledge generated from the insight it provides to the underlying dependencies.\n  Furthermore, this theoretical model will aid in the development of simulation tools that will design the quantum effects in\n  magneto-transport properties of 2D nanostructures.\n  }\n\\end{itemize}\n\n\\subsubsection*{Comment 2 -\n\\color{RoyalBlue} Moreover, this current research direction has a significant overlap with previous experimental and theoretical studies of quantum Hall systems that started with the observation of zero-resistance states in high mobility systems [Zudov et al, Phys. Rev. B 64, 201311 (2001), Mani et al, Phys. Rev. Lett. 92, 146801 (2004)] and gave rise to theoretical models for the phenomenon [Durst et al, Phys. Rev. Lett. 91, 086803 (2003), Dmitriev et al., Phys. Rev. B 71, 115316 (2005), Dmitriev et al, Phys. Rev. B 80, 165327 (2009)]. The present manuscript needs to connect to various known phenomena discussed earlier in the literature on quantum Hall systems.}\n\nWe agree with the reviewer that it is useful to have a discussion comparing  our theoretical model and previous work on the transport properties of quantum Hall systems.\nAmong the mentioned studies we can identify that experimental work reported in Refs. \\cite{zudov01,mani02,zudov03,mani04} are specifically aimed at the unusual oscillations of the magnetoresistance induced by the microwave (millimeter-wave) radiation in 2DEG quantum Hall systems.\nThese oscillations are known as \\textit{microwave-induced resistance oscillations} (MIROs).\nTo describe these behaviors Durst \\textit{et al.} \\cite{durst03} introduced a simple theoretical model assuming that the experimentally observed oscillations are a consequence of photoexcited disorder-scattered electrons.\nHowever, later Refs. \\cite{dmitriev03,dmitriev05,dmitriev09} proposed a novel model considering the changes were made on\nthe electron distribution function by the microwave field.\nThese more generalized models \\cite{dmitriev03,dmitriev05,dmitriev09} have successfully described the behavior of MIROs at experimentally relevant temperatures that were missed in the previous model \\cite{durst03}.\nFurthermore, we can recognize that the underlying mechanism of all these models \\cite{durst03,dmitriev03,dmitriev05,dmitriev09} is microwave photon absorption by an electron in the associated system. In our theoretical model, we take into account higher frequencies than microwaves as the dressing electromagnetic field.\nTherefore we can identify and quantify significant dissimilarities between our system and MIRO systems \\cite{zudov01,mani02,zudov03,mani04,durst03,dmitriev03,dmitriev05,dmitriev09}. They are:\n\\begin{itemize}\n  \\item\n  the experiments on magnetoresistance oscillations on 2DEG quantum Hall systems \\cite{zudov01,mani02,zudov03,mani04} were performed in the microwave frequency range ($30 -\\SI{150}{\\giga\\hertz}$). This leads to building the theoretical models presented in Refs. \\cite{durst03,dmitriev03} by assuming that these oscillations are caused by photoexcited electrons. Since these models consider on a relevant frequency range (microwave radiation), it will allow us to acknowledge the photon absorption by electrons. In contrast to that, our consideration is only focused on the systems with high-frequency range dressing fields which will not be associated with any photon absorption.\n  \\item\n  the applied microwave radiation power on the MIRO experiments \\cite{mani02,zudov03} varies around the  $\\SI{1}{\\milli\\watt\\per\\square\\centi\\metre}$ range. However, in our analysis, we take the dressing field as a high-intensity electromagnetic field, where we cannot consider the dressing field as a perturbation in our analysis. This leads us to recognize the formation of Floquet states together with conventional Landau levels. As we mentioned in our results, we used dressing high-intensity electromagnetic fields of magnitude around the $\\SI{100}{\\watt\\per\\square\\centi\\metre}$ range in our numerical calculations.\n  \\item\n  these fascinating MIROs are only observed under the influence of weak magnetic fields ($B < \\SI{0.2}{\\tesla}$) in experiments performed in Refs. \\cite{zudov01,mani02,zudov03,mani04}. In this range of weak magnetic fields,  we can only observe MIROs as Shubnikov–de Haas (SdH) oscillations reveal only with high-intensity magnetic fields. In comparison to our analysis, we are  interested in the SdH oscillations and manipulation of their characteristics. Therefore in our analysis, we aim at the effects induced by higher intensity magnetic fields ($B \\sim \\SI{1}{\\tesla}$) than the MIRO experiments.\n  \\item\n  in our work, we analyzed the 2DEG quantum Hall system with a dressing high-intensity electromagnetic field which does not contribute to energy exchange between the high-frequency dressing field and electrons. Therefore we have assumed the applied electromagnetic radiation as a pure dressing field. There are two possible absorption mechanisms in a 2DEG quantum Hall system; namely electron transitions between distinct Landau levels and electron transitions between distinct states of the same broadened Landau level. To avoid these absorptions, we have tuned the dressing field into a high-frequency range in our system under the analysis. Furthermore, due to the dressing high-intensity electromagnetic field, the entire electronic states of the conventional 2DEG quantum Hall system will be restructured. We have addressed these modifications through the Floquet theory. However, the MIRO models \\cite{durst03,dmitriev03} are based on low-frequency cases where the system can absorb low-frequency photons from the field.\n\\end{itemize}\n\nBased on the above discussion, we can identify that the high-frequency and low-frequency illumination of 2DEG quantum Hall systems leads to two distinguishable\nmagneto-transport scenarios.\n\n\\begin{itemize}\n  \\item Section I - fifth paragraph (page 1):\\\\\n  {\\color{Red}\n  Recently, experimental research on the effects of microwave illumination of 2DEG systems revealed microwave-induced resistance oscillations (MIROs) under weak magnetic fields \\cite{zudov01,mani02,zudov03,mani04}.\n  This inspired investigations on the theoretical description of MIROs, and several semiclassical and quantum kinetic equation formalisms have been proposed to address the underlying mechanism of MIROs \\cite{durst03,dmitriev03,dmitriev05,dmitriev09}. These formalisms provide a proper explanation for the experimental observations of MIROs. However, these experimental and theoretical works have been linked to photon absorption from low-frequency (microwave) electromagnetic fields.\n  In contrast to that, high-frequency external illumination on a 2DEG quantum Hall system needs to be studied as a pure dressing (nonabsorbable) field.\n  The influence induced by a pure dressing field on\n  magneto-transport properties of 2DEG quantum Hall system needs to be described by a non-absorption mechanism, and it has escaped the researchers’ attention before.\n  Lately, Dini \\textit{et al.} \\cite{dini16} have investigated the one-directional conductivity behavior of dressed quantum Hall system subjected to a high-frequency field.\n  }\n  \\item Section VI - sixth paragraph (page 9):\\\\\n  {\\color{Red}\n  Lately, several experimental \\cite{zudov01,mani02,zudov03,mani04} and theoretical \\cite{durst03,dmitriev03,dmitriev05,dmitriev09} studies have uncovered various remarkable\n  magneto-transport properties induced by microwave radiation on 2DEG quantum Hall systems. However, these experiments and theoretical models only analyzed the behavior of MIROs in 2DEG systems which are based on photon absorption from the applied low-frequency field.\n  It is important to state that the difference between our SdH oscillations and MIROs \\cite{zudov01,mani02,zudov03,mani04} by considering the frequency range of the applied electromagnetic field. In our case, the applied dressing field is in the off-resonant range, and it will only change the broadening of Landau levels, but avoid any contribution towards the photon absorptions. This will clearly describe the crucial difference between low-frequency illumination and high-frequency illumination effects on 2DEG quantum Hall systems. Therefore, our theoretical analysis can help to fill the gap in knowledge of the high-frequency dressing field effects on 2DEG quantum Hall systems.\n  }\n\\end{itemize}\n\n\\subsubsection*{Comment 3 -\n\\color{RoyalBlue} The manuscript will also provide more impact if it demonstrates how the new results can help to improve the future development of nanoelectronic devices. After these questions are addressed, the manuscript will be suitable for publication in Physical Review B. Otherwise, it will fit better to a more mathematically oriented journal.\n}\n\nThis is a valid comment. As we mentioned in comment 1, considering the importance of discussing the physical significance of our results, we included a new section (Section VII) to address this comment.\n\n\\begin{itemize}\n  \\item Section VII (page 8):\\\\\n  {\\color{Red}\n  \\subsection*{VII. PHYSICAL SIGNIFICANCE OF THE OUTCOMES}\n\n  With the realization of 2DEGs in Si-MOSFETs (Metal Oxide Semiconductor Field Effect Transistors) \\citep{fowler66}, Klitzing \\textit{et al.} \\cite{klitzing80} made the first transport measurements on such systems to reveal the quantum Hall effect. The empirical discovery of these unusual properties marked the beginning of a whole new realm in condensed matter physics that continues to produce phenomenal advancements in electronic systems. The quantum Hall effects in a 2DEG under a static magnetic field are described by plateaus quantized to integer values of the conductivity quantum ($\\flatfrac{e^2}{\\hbar}$) in the off-diagonal conductivity, with simultaneous peaks at inter-plateau transition for the diagonal conductivity \\cite{endo09}. This is due to the applied magnetic field and it changes the energy spectrum of 2DEG dramatically. The magnetic field causes the density of states in 2DEG to split up into a sequence of delta functions, separated by an energy $\\hbar\\omega_0$, with $\\omega_0$ the cyclotron frequency which depends on the applied magnetic field.\n  However, experimental results demonstrate that these Landau levels are broadened and the main source of these broadening at low temperatures is the disorders in materials \\cite{ando85,dial07}. The broaden sequence of delta functions of the density of states implies the oscillating behavior in the experimental measurements of longitudinal conductivity which is known as SdH oscillations \\cite{endo09,wakabayashi78}.\n\n  Our theoretical analysis on longitudinal conductivity behavior of dressed quantum Hall system was developed by considering low-temperature limit with Gaussian impurity broadening assumptions.\n  As illustrated in Fig. 4, we can describe the experimentally observed SdH oscillation results in Refs.\\cite{endo09,wakabayashi78} through our model.\n  Under the undressed condition, our results overlap with the conductivity measurement of quantum Hall systems \\cite{endo09}. Strikingly, we show in Fig. 5 that we can manipulate the broadening of these conductivity peaks using an external dressing field. At low temperatures, the principal cause of broadening of these conductivity peaks is impurity-induced scattering. Using an external dressing field, we can suppress the impurity-induced scattering and this results a reduction of both the scattering-induced broadening and the longitudinal conductivity peaks.\n\n  Research on novel states of matter has driven the evolution of present-day nanoelectronic devices. In particular, controllable manipulation of material properties through a gate electric field has revolutionized the development of material science and technology \\cite{ahn03,deng18}.\n  The charge carrier concentration of a system is an imperative parameter that defines its conductivity properties.\n  As we can manipulate the charge carrier concentration using an electrostatic field-effect, we exert significant control over the conductivity externally.\n  A 2DEG under static magnetic field with quantum Hall effects is an excellent example that illustrates how the gate electric field controls conductivity.\n  We also observed that a considerable number of studies exist on charge transport in the quantum limit that employed different types of 2D field-effect transistors (FETs) subjected to magnetic fields \\cite{wakabayashi78,yang18,long20,li14}. Yang \\textit{et al.} \\cite{yang18} study shows quantized Hall plateaus and SdH oscillations for longitudinal conductivity against gate voltage in black phosphorus FET under static magnetic fields at low temperatures. Since the Fermi level of a system can be altered with the applied gate voltage, our Fig. 4 depicts this result.\n  In particular, our analysis shows that we can manipulate the broadening of the conductivity regions using an external dressing field. Although Yang \\textit{et al.} \\cite{yang18}, achieved broadening in longitudinal conductivity peaks by changing the temperature in a low range, in this study we presented a general theory on manipulating longitudinal conductivity broadening using a high-intensity electromagnetic field.\n\n  The realization of the underlying mechanism of 2D FETs in the quantum realm promises its potential in next-generation nanoelectronic applications. In a particular application that uses the switching mechanism of the above-discussed FETs with quantum Hall effects, we can achieve high and low output conductivities by changing the input gate voltage. As a result of manipulating the broadening of conductivity regions, we can limit the broadening of conductivity peaks around Landau levels using a dressing high-intensity electromagnetic field. This will enhance the sensitivity of FETs which provides the ability to observe narrow changes in gate voltage.\n  Furthermore, adopting the mechanism presented in Ref. \\cite{hirakawa01}, we can manipulate conductivity peaks into very sensitive, narrowband high-frequency radiation detectors.\n  We envision these advances in nanoelectronics from our theoretical model and knowledge generated from the insight it provides to the underlying dependencies.\n  Furthermore, this theoretical model will aid in the development of simulation tools that will design the quantum effects in\n  magneto-transport properties of 2D nanostructures.\n  }\n\\end{itemize}\n\n\\subsubsection*{Comment 4 -\n\\color{RoyalBlue} The quantum Quantum Hall effect requires high mobility samples. In these samples, the structure of the disorder is usually complicated and combines both short-length potentials of impurities and long-length electrostatic inhomogeneities. The interplay of these components of disorder opens exciting questions about the transport properties of 2DEGs. What is the structure of disorder considered in the present manuscript and hidden in the notations for Vimp? What are the conditions for validity of eq. (15)?\n}\n\nWe thank the reviewer for raising this important question. In our previous manuscript, we have presented the detailed derivation of Eq.~[15] with a discussion on models of disorder under Appendix C. However, here we again elucidate our disorder model and approximations made to derive the Eq.~[15] for clarity and to respond to this question.\n\nWe modeled the effect caused by impurities in the considered system as a single perturbation potential. Analyzing the electric properties for a specific impurity distribution is a rather formidable task. We do not consider a specific impurity distribution here as it is unlikely to represent a measured impurity configuration in an experiment. Therefore, in this study, we consider the statistically averaged properties of 2DEG over impurity configurations.\nWe start our analysis by considering a static disorder that corresponds only to elastic electron scattering processes.\nWe adapt the Edwards model \\cite{akkermans10} to represent the randomly distributed impurities over the associated system and we approximate this into a Gaussian white noise.\n\nSince we are presenting the perturbation potential $V(\\vb{r})$ by a group of randomly localized impurities, we assume $N_{imp}$ number of identical single impurity potentials distributed randomly but in fixed positions $\\vb{r}_i$. Thus, we can describe the perturbation potential $V(\\vb{r})$ as the sum of uncorrelated single impurity potentials $\\upsilon(\\vb{r})$,\n\\begin{equation} \\label{eq:1}\n  V(\\vb{r}) =\n  \\sum_{i=1}^{N_{imp}}\n  \\upsilon (\\vb{r}-\\vb{r}_i).\n\\end{equation}\nFurthermore, we approximate this perturbation potential as a Gaussian random potential where one can choose the zero of energy such that the potential is zero on average. This model is characterized by the following two equations \\cite{akkermans10}\n\\begin{subequations}\n\\begin{equation} \\label{eq:2}\n  \\expval{\\upsilon(\\vb{r})}_{imp} =0,\n\\end{equation}\n\\begin{equation} \\label{eq:3}\n  \\expval{\\upsilon(\\vb{r})\\upsilon(\\vb{r'})}_{imp} = \\Upsilon(\\vb{r}-\\vb{r'}),\n\\end{equation}\n\\end{subequations}\nwhere $\\expval{\\cdot}_{imp}$ represents the average over the impurity disorder and $\\Upsilon(\\vb{r}-\\vb{r'})$ is any decaying function that solely depends only on $\\vb{r}-\\vb{r'}$, and decays with a characteristic length $r_c$. Since this study considers the case where the wavelength of radiation or a scattering electron is much greater than $r_c$, it is reasonable to approximate its two-point correlation function by\n\\begin{equation} \\label{eq:4}\n  \\expval{\\upsilon(\\vb{r})\\upsilon(\\vb{r'})}_{imp} = \\Upsilon_{imp}^2\\delta(\\vb{r}-\\vb{r'}),\n\\end{equation}\nwhere $\\Upsilon_{imp}^2$ is a positive constant. A random potential $V(\\vb{r})$ with this property is called white noise \\cite{akkermans10}. Then we can approximately write the total scattering potential as\n\\begin{equation} \\label{eq:5}\n  V(\\vb{r}) =\n  \\sum_{i=1}^{N_{imp}}\n  \\Upsilon_{imp} \\delta(\\vb{r}-\\vb{r}_i).\n\\end{equation}\n\nUsing this expression, we can evaluate the Floquet-Fermi golden rule for a dressed quantum Hall system. Furthermore, considering the properties of a Gaussian white noise impurity distribution \\cite{wackerl20,akkermans10}, we assume $V_{imp}$ is a constant in the momentum space.\nHere $V_{imp} = \\expval{|V_{{k'}_x,k_x}|^2}_{imp}$ with $V_{{k'}_x,k_x} = \\mel**{k'_x}{\\upsilon(x) }{k_x}$, and $\\braket{x}{k_x} = e^{-ik_x x}$.\nAll the detailed steps for the derivation of the Floquet-Fermi golden rule for a dressed quantum Hall system are included in Appendix C.\nHowever, throughout the derivation, we use only the first-order contribution (Born approximation) of the impurity potential.\n\nSince previous studies on Floquet-Drude conductivity \\cite{wackerl20}, and magneto-transport properties in undressed \\cite{endo09} and dressed \\cite{dini16} quantum Hall systems have used this particular Gaussian white noise potential, we also selected this particular impurity model to describe our system. Such a choice enables us to compare our analytical results with these previous models. As you have mentioned in the comment, consideration of other impurity disorder models and their impact on the\nmagneto-transport properties of dressed quantum Hall system would be an intriguing future research possibility.\n\nSince we have only mentioned the validity conditions we used to derive the Eq.~[15] in Appendix C and not in the main text of the previous manuscript, we have added these validity conditions to the main text of the revised manuscript.\n\n\\begin{itemize}\n  \\item Section IV - first paragraph (page 4):\\\\\n  {\\color{Red}\n  We have modeled the effect caused by impurities as a single short-range perturbation potential. Analyzing the electric properties for a specific impurity distribution is a rather formidable task. We do not consider a specific impurity distribution here as it is unlikely to represent a measured impurity configuration in an experiment.\n  Therefore, in this study, we consider the statistically averaged properties of 2DEG over impurity configurations.\n  Furthermore, we have assumed that a group of randomly distributed impurities forms our perturbation potential under the Edwards impurity model  \\cite{akkermans10,wackerl20}.\n  Essentially, all these assumptions mean that we can write the total scattering potential in the 2DEG as a sum of uncorrelated single impurity potentials $\\upsilon(\\vb{r})$. This enables us to approximate the impurity potential as a Gaussian white noise \\cite{akkermans10,wackerl20}.\n  Here $\\eta_{imp}$ is the number of impurities in a unit area, $V_{imp} = \\expval{|V_{{k'}_x,k_x}|^2}_{imp}$ with $V_{{k'}_x,k_x} = \\mel**{k'_x}{\\upsilon(x) }{k_x}$, and $\\braket{x}{k_x} = e^{-ik_x x}$.\n  Moreover, in this analysis, $\\expval{\\cdot}_{imp}$ represents the average over the impurity disorder. In this derivation, we only considered the first order (the Born approximation) contribution from the impurity potential.\n  }\n\\end{itemize}\n\n\\subsubsection*{Comment 5 -\n\\color{RoyalBlue} If continuous illumination is applied to an electron system, the system will heat indefinitely. The distribution function is stabilized when the electron-electron and electron-phonon scattering mechanisms are included. What are the conditions of validity for eqs. (33-34)? The deviations of the distribution function from its equilibrium result in effects that can significantly overcome the equilibrium contributions, see Dmitriev et al, Phys. Rev. B 80, 165327 (2009). However, to capture these effects, a treatment within Floquet-Drude formalism is insufficient and a complete quantum kinetic equation has to be analyzed. Can the authors argue why their results still present some interest to the community even if they potentially disregard more significant contributions?\n}\n\nThis is a good, valid question. First, we discuss the validity of the Eq.~[33] and Eq.~[34]. Our analysis derived the longitudinal conductivity of a dressed quantum Hall system without any partial distribution function specification until Eq.~[31].\nIn contrast to the MIRO analysis \\cite{dmitriev03,dmitriev05,dmitriev09}, we consider the dressed quantum Hall system under the off-resonant condition, where the photon absorption does not happen. Therefore, we can select the Fermi-Dirac distribution as our particle distribution function for Eq.~[31]\n\\begin{equation} \\tag{5}\n  f(\\varepsilon) = \\frac{1}{\\exp[(\\varepsilon - \\varepsilon_F)/k_B T]+1}.\n\\end{equation}\nHere, $k_B$ is the Boltzmann constant, $T$ is the absolute temperature, and $\\varepsilon_F$ is the Fermi energy of the system.\nThen we consider a special scenario where the system operates at a low-temperature limit, i.e., the condition $k_BT \\ll \\varepsilon_F$.\nSince previous theoretical studies \\cite{wackerl20,dini16,endo09} on magneto-transport properties of 2DEG quantum Hall systems were derived under this assumption, we also adopted the same conditions as it enables us to compare results with those studies.\nIn addition, as mentioned in previous experimental studies on SdH oscillations \\cite{zudov03,mani02,arapov02} in 2DEG undressed quantum Hall systems with increasing temperature, we can identify the decaying behavior of SdH oscillations.\nTherefore, if we need to maintain a good oscillatory behavior, we need to operate in low temperatures.\nSince in our analysis, we study the manipulation of SdH oscillations using a dressing field, it is reasonable to simplify our general derivation given in  Eq.~[31] for low-temperature limit. Under these assumptions, the derivative of the Fermi-Dirac distribution is sharply peaked around the Fermi energy, and  can be represented by the delta function \\cite{endo09}\n\\begin{equation} \\tag{6}\n  - \\pdv{f(\\varepsilon)}{\\varepsilon} \\approx \\delta(\\varepsilon - \\varepsilon_F).\n\\end{equation}\nApplying these adequate conditions, we can simplify our derivation into a single expression that can be compared with previous studies \\cite{wackerl20,dini16,endo09} on\nmagneto-transport in dressed quantum Hall systems. We have added clarification on the above assumptions in the revised manuscript.\n\\begin{itemize}\n  \\item Section V - second paragraph (page 7):\\\\\n  {\\color{Red}\n  We consider a dressed quantum Hall system under off-resonant condition, where photon absorption does not happen. Therefore, we can select the Fermi-Dirac distribution as our partial distribution function ($f$) for our system\n  \\begin{equation} \\tag{33}\n    f(\\varepsilon) = \\frac{1}{\\exp[(\\varepsilon - \\varepsilon_F)/k_B T]+1},\n  \\end{equation}\n  where $k_B$ is the Boltzmann constant, $T$ is the absolute temperature, and $\\varepsilon_F$ is the Fermi energy of the system. At low-temperatures, i.e., $k_BT \\ll \\varepsilon_F$, the derivative of this distribution is sharply peaked around the Fermi energy, and can be approximated by a delta function \\cite{endo09}\n  \\begin{equation} \\tag{34}\n    - \\pdv{f(\\varepsilon)}{\\varepsilon} \\approx \\delta(\\varepsilon - \\varepsilon_F).\n  \\end{equation}\n  }\n\\end{itemize}\n\nYes, indeed, experiments on quantum hall systems subject to a strong dressing field show elevated temperatures. However, as demonstrated in previous studies by Dini \\textit{et al.} \\cite{dini16} and Kibis \\textit{et al.} \\cite{kibis15}, it is possible to maintain low system temperature by limiting the dressing field to narrow pulses.\n\nAlthough we have restricted our general derivation given in Eq.~[31] into a particular instance for comparison, there is no fundemental restriction in extending our theoretical model into different types of particle distribution functions. As presented in the previous work of Dmitriev \\textit{et al.} \\cite{dmitriev05}, a well-defined analytical discussion needs to address the changes in distribution functions in our derived general longitudinal conductivity formula, and this would be a noteworthy extension to our study.\n\n\\subsubsection*{Comment 6 -\n\\color{RoyalBlue} The authors presented the results for the conductivity tensor's xx- and yy-components. They seem to be identical, apart of a dimensional factor $(eB)^2$ in the denominator. The equality of these two components is expected for isotropic systems. Does the polarization of the electromagnetic field break the isotropy? Do the two components of the conductivity remain equal even for an arbitrary direction of a linearly polarized field? Is there a non-Hall contribution to the xy-component?\n}\n\nWe express our gratitude towards the reviewer for pointing out this inadvertent oversight done in the $yy$-component of the current operator calculation. This has led to an unexpected normalization factor in the yy-component of the  conductivity expression. Since we have only used the normalized $xx$-component of the conductivity tensor for subsequent analysis, this oversight has no impact on the analysis reported in the  manuscript. With this correction, we observe that both xx-component and $yy$-component show the same conductivity behaviors. We added these amendments to the current operator calculations done in Appendix D and the longitudinal conductivity calculation under Section V.\n\n\\begin{itemize}\n  \\item Appendix D (page 16):\\\\\n  {\\color{Red}\n  \\subsection*{\\label{appendix_d}Appendix D: Current operators for a dressed quantum Hall system}\n\n  In this section, we derive the current density operator for the $N$-th Landau level in a dressed quantum Hall system. We already found the exact solution for the time-dependent Schrödinger equation with the Hamiltonian give in Eq.~(1) and we identified them as the Floquet states in Eq.~(14). For the simplicity of notation, we can represent the Floquet modes derived in Eq.~(10) as quantum states using their corresponding quantum numbers as follows\n  \\begin{equation} \\tag{D1}\n    \\ket{\\phi_{n,m}} = \\ket{n,k_x}.\n  \\end{equation}\n  Using this complete set of quantum states \\cite{wackerl20,holthaus15,grifoni98}, we can represent the single particle current operator's matrix element as\n  \\begin{equation} \\tag{D2}\n    \\left(\\vb{j} \\right)_{nm,n'm'} = \\mel{n,k_x}{\\;\\hat{\\vb{j}}\\;}{n',k'_x}.\n  \\end{equation}\n  Next, we can identify the particle current operator for our system \\cite{mahan00,bruus04} as\n  \\begin{equation} \\tag{D3}\n    \\hat{\\vb{j}} = \\frac{1}{\\widetilde{m}} \\left\\{\\hat{\\vb{p}} - e\\left[\\vb{A}_s + \\vb{A}_d(t) \\right]\\right\\},\n  \\end{equation}\n  where $\\widetilde{m}$ is the mass of the associated particle.\n\n  First, we consider the $x$-directional particle current operator component, and we can identify that as\n  \\begin{equation} \\tag{D4}\n    \\hat{j}_x = \\frac{1}{\\widetilde{m}} \\left(-i\\hbar\\pdv{x} + eBy \\right).\n  \\end{equation}\n  Next, we calculate the matrix elements of $x$-directional current operator against our Floquet mode basis\n  \\begin{equation} \\tag{D5}\n    \\left({j}_x \\right)_{nm,n'm'} =\n    \\mel{n,k_x}{\\;\\frac{1}{\\widetilde{m}} \\left(-i\\hbar\\pdv{x} + eBy \\right)}{n',k'_x},\n  \\end{equation}\n  and we evaluate these using the Floquet modes derived in Eq.~(7) as follows\n  \\begin{equation} \\tag{D6}\n    \\begin{aligned}\n      \\left({j}_x \\right)_{nm,n'm'} = &\n      \\frac{1}{{\\widetilde{m}}}\n      \\delta_{k_x,k'_x}\n      \\int\n      \\left(\\hbar k'_x + eBy\\right) \\\\\n      & \\times\n       \\chi_{n}\\bm{\\left(}y - y_0 - \\zeta(t)\\bm{\\right)}\n      \\chi_{n'}\\bm{\\left(}y - y_0 - \\zeta(t)\\bm{\\right)}\n      dy.\n    \\end{aligned}\n  \\end{equation}\n  Let $[y - y_0 - \\zeta(t)] = \\bar{y}$, and we can obtain\n  \\begin{equation} \\tag{D7}\n    \\begin{aligned}\n      \\left({j}_x \\right)_{nm,n'm'} =\n      \\frac{1}{{\\widetilde{m}}}\n      \\delta_{k_x,k'_x}\n      \\int &\n      \\left[ \\hbar k'_x + eB\\bar{y} -\\hbar k'_x + eB\\zeta(t)\\right]\n      \\chi_{n}(\\bar{y})\n      \\chi_{n'}(\\bar{y})\n      d\\bar{y}.\n    \\end{aligned}\n  \\end{equation}\n  Using the following integral identities of the Floquet modes that are made of Gauss-Hermite functions \\cite{vedenyapin11,szego59}\n  \\begin{equation} \\tag{D8}\n    \\int\n    \\chi_{n}({y})\n    \\chi_{n'}({y}) d{y} =\n    \\delta_{n',n},\n  \\end{equation}\n  \\begin{equation} \\tag{D9}\n    \\int\n    y \\chi_{n}({y})\\chi_{n'}({y}) d{y} =\n    \\frac{1}{\\kappa}\n    \\left(\\sqrt{\\frac{n+1}{2}} \\delta_{n',n+1} + \\sqrt{\\frac{n}{2}}\n    \\delta_{n',n-1} \\right),\n  \\end{equation}\n  we simplify the matrix elements of $x$-directional current operator to obtain\n  \\begin{equation} \\tag{D10}\n    \\begin{aligned}\n      &\\left({j}_x \\right)_{nm,n'm'} =\n      \\frac{eB}{{\\widetilde{m}\\kappa}}\n      \\delta_{k_x,k'_x}\n      \\left[\n      \\left(\\sqrt{\\frac{n+1}{2}} \\delta_{n',n+1} + \\sqrt{\\frac{n}{2}}\n      \\delta_{n',n-1}\\right)\n      + \\zeta(t) \\delta_{n',n}\n      \\right].\n    \\end{aligned}\n  \\end{equation}\n  Due to high complexity of extract solution, in this study we only consider the constant contribution from the Fourier series components of the above expression. Therefore, we can identify the $0$-th component of the Fourier series as\n  \\begin{equation} \\tag{D11}\n    \\begin{aligned}\n        \\left({j}_x \\right)_{nm,n'm'} =&\n        \\frac{eB}{\\widetilde{m}\\kappa}\n        \\delta_{k_x,k'_x}\n        \\left(\\sqrt{\\frac{n+1}{2}} \\delta_{n',n+1} + \\sqrt{\\frac{n}{2}}\n        \\delta_{n',n-1} \\right).\n    \\end{aligned}\n  \\end{equation}\n  To calculate the electric current operator, we substitute the electron's charge and effective mass to the above derived equation. This leads to\n  \\begin{equation} \\tag{D12}\n    \\begin{aligned}\n        \\Big({j}^x_{s=0}\\Big)_{nm,n'm'}^{electron}  =&\n        \\frac{e\\hbar}{{m_e}l_0}\n        \\delta_{k_x,k'_x}\n        \\left(\\sqrt{\\frac{n+1}{2}} \\delta_{n',n+1} + \\sqrt{\\frac{n}{2}}\n        \\delta_{n',n-1} \\right).\n    \\end{aligned}\n  \\end{equation}\n  where $l_0 = \\sqrt{\\flatfrac{\\hbar}{eB}}$ is the magnetic length.\n\n  Moreover, we can identify the $y$-directional current operator component as\n  \\begin{equation} \\tag{D13}\n    \\hat{j}_y = \\frac{1}{\\widetilde{m}} \\left(-i\\hbar\\pdv{y} - \\frac{eE}{\\omega}\\cos(\\omega t) \\right).\n  \\end{equation}\n  Using this operator, we can represent the matrix elements of $y$-directional current operator in Floquet mode basis as\n  \\begin{equation} \\tag{D14}\n    \\left({j}_y \\right)_{nm,n'm'} =\n    \\mel{n,k_x}{\\;\\frac{-1}{\\widetilde{m}} \\left(i\\hbar\\pdv{y} + \\frac{eE}{\\omega}\\cos(\\omega t) \\right)}{n',k'_x}.\n  \\end{equation}\n  After following the same steps done for the $x$-directional current operator, and recursion relation of the first derivative of Gauss-Hermite functions\n  \\begin{equation} \\tag{D15}\n    \\begin{aligned}\n      \\pdv{\\chi_{n}({y})}{y} =\n      \\kappa\\left[\n      -  \\sqrt{\\frac{n+1}{2}} \\chi_{n+1}({y})\n      +  \\sqrt{\\frac{n}{2}} \\chi_{n - 1}({y})\n      \\right],\n    \\end{aligned}\n  \\end{equation}\n  we can identify the $0$-th component of matrix elements for $y$-directional electric current operator as\n  \\begin{equation} \\tag{D16}\n    \\begin{aligned}\n      \\Big({j}^y_{s=0}\\Big)_{nm,n'm'}^{electron} = &\n      \\frac{ie\\hbar\\kappa}{m_e}\n      \\delta_{k_x,k'_x}\n      \\left(\n      \\sqrt{\\frac{n}{2}} \\delta_{n',n-1}\n      - \\sqrt{\\frac{n+1}{2}} \\delta_{n',n+1}\n      \\right).\n    \\end{aligned}\n  \\end{equation}\n  \\begin{equation} \\tag{D17}\n    \\begin{aligned}\n      \\Big({j}^y_{s=0}\\Big)_{nm,n'm'}^{electron} = &\n      \\frac{ie \\hbar}{m_e l_0}\n      \\delta_{k_x,k'_x}\n      \\left(\n      \\sqrt{\\frac{n}{2}} \\delta_{n',n-1}\n      - \\sqrt{\\frac{n+1}{2}} \\delta_{n',n+1}\n      \\right).\n    \\end{aligned}\n  \\end{equation}\n  }\n  \\item Section V - second paragraph (page 7):\\\\\n  {\\color{Red}\n  Moreover, let $\\Pi = \\varepsilon_F$ and the derived expression in Eq.~(31) leads to\n  \\begin{equation} \\tag{35}\n    \\begin{aligned}\n      \\sigma^{xx}  =\n      \\frac{e^2l_0^2}{\\pi\\hbar A}\n      \\sum_{n}\n      \\frac{(n+1)}{\\gamma_{n}\\gamma_{n+1}}\n      \\left[\n        \\frac{1}\n        {\n          1 + \\left(\\frac{X_F - n -1}{\\gamma_{n+1}}\\right)^2\n        }\n      \\right]\n      \\left[\n        \\frac{1}\n        {\n          1 + \\left(\\frac{X_F - n}{\\gamma_{n}}\\right)^2\n        }\n      \\right],\n    \\end{aligned}\n  \\end{equation}\n  where $X_F = \\left[\\flatfrac{\\varepsilon_F}{(\\hbar \\omega_0)} - \\flatfrac{1}{2}\\right]$,\n  $\\gamma_n = \\flatfrac{\\widetilde{{\\Gamma}}(\\varepsilon_n)}{(\\hbar \\omega_0)}$, and $l_0 = \\sqrt{\\flatfrac{\\hbar}{eB}}$.\n  Following the same steps as above derivation, we can derive the longitudinal conductivity in the $y$-direction by applying the electric current operator for $y$-direction derived in Appendix D\n  \\begin{equation} \\tag{36}\n    \\begin{aligned}\n      {\\sigma}^{yy} =\n      \\frac{e^2l_0^2}{\\pi\\hbar A}\n      \\sum_{n}\n      \\frac{(n+1)}{\\gamma_{n}\\gamma_{n+1}}\n      \\left[\n        \\frac{1}\n        {\n          1 + \\left(\\frac{X_F - n -1}{\\gamma_{n+1}}\\right)^2\n        }\n      \\right]\n      \\left[\n        \\frac{1}\n        {\n          1 + \\left(\\frac{X_F - n}{\\gamma_{n}}\\right)^2\n        }\n      \\right].\n    \\end{aligned}\n  \\end{equation}\n  }\n\\end{itemize}\n\nSuppose we apply an arbitrary directional polarized dressing field. In that case, we could derive an expression for the longitudinal conductivity components by considering dressing field contribution for each direction ($x$ and $y$) with the same steps presented in our analysis. This would change the amplitude of the associated dressing field ($E$) in each direction. There will be a new component in parallel to the conductivity component of interest, which will modify the time-dependent Hamiltonian given in Eq.~[2]. Then, we need to solve the Schrödinger equation with the modified Hamiltonian to find the new Floquet modes for the new system. These will define the effect on the inverse scattering time matrix components. As mentioned in Ref. \\cite{wackerl20} and our work, applied strong dressing field tends to change the quantum state of the considered system and creates novel states called Floquet states. The properties of these states depend on the characteristics of the applied dressing field. Therefore, the polarization method also changes the behavior of the Floquet states. These polarization-dependent conductivity behaviors in 2DEG systems can be found in references \\cite{wackerl20,morina15} and in their work authors have illustrated the conductivity behavior with circular and linear polarized dressing fields. However, in a dressed quantum Hall system with a $y$-directional linear polarized field, we predict the same longitudinal conductivity behaviors in diagonal components of the conductivity tensor.\n\nFor analyzing our system, we mainly employ the diagonal components of the Floquet-Drude conductivity tensor introduced by Wackerl \\textit{et al.} \\cite{wackerl20}. As we mainly focus on SdH oscillations in longitudinal conductivity components, we limit our analysis to the dressing field influence on two diagonal components of the conductivity tensor. Therefore we are unable to predict the off-diagonal component behavior of the system.\n%\n% As mentioned in Ref.\\cite{wackerl20} and our work, applied strong dressing field tends to change the quantum state of the consideirng system and creates novel states called Floquet states. The properties of these states are depends on the characteristics of applied dressing field. Therefore, the polarization method also change the behavior of the Floquet states.\n% These polarization dependent conductivity behaviors in 2DEG systems can be found in references \\cite{wackerl20,morina15} and in their work authors have illustrated the conductivity behavior with circular and linear polarized dressing fields. In addition, they have mentioned the impact on the direction of the linearly polarization dressing field and this will break the isotropy behavior of the longitudinal conductivities in the consideirng system.\n%\n% We also followed the same formalism of Floquet states for 2DEG quantum Hall systems. In our work also we were able to identify that the applied dressing field's polarization direction can be effect the magnitude of the longitudinal conductivity component. A detailed derivation of these two longitudinal conductivity component's current operators are given in Appendix D. If we applied a arbitary directional polarized dressing field, we can derive a expression for the longitudinal conductivity components by considering dressing field contribution for each direction ($x$ and $y$) with same steps in this analysis. This would change the amplitude of the considering dressing field ($E$) in each direction. However, now there will be a new conponent in parallel to the considering conductivity component and we need to solve the Schrödinger equation with the modified Hamiltonian in Eq.~[2] for the new system with these changes.\n% However in our analysis, our main objective was to identify the manipulation capabilities of SdH oscillations using dressing field intensity. In addition, we only consider the longitudinal components in this analysis by extending the Floquet-Drude conductivity formula that derived only for the diagonal components in conductivity tensor. Therefore we are unable to predict the off-diagonal component behavior of the system through our analysis and we need a novel formalism to handle these type of behaviors of dressed 2DEG quantum Hall systems.\n\n\\subsection*{Response to the comments of Reviewer 2}\n\nWe want to thank the reviewer for his/her insightful comments on our work. To address your comments, we had to add new materials and reorganize our text. As a result, we have been able to considerably improve our discussion on the underlying assumptions and corresponding physical significance of our analysis. We hope our response and the corresponding changes we incorporated into the manuscript will be sufficient to clarify the issues raised.\n\n\n\\subsubsection*{Comment 1 -\n\\color{RoyalBlue} The paper is very low on comparison with experiments, for which there is a large amount of data available for the zero radiation case. I would like to see detailed analysis of how Figs 4 and 5 compare with available\nexperimental data. Without this addition, physical relevance of such\ndetailed calculations is questionable.\n}\n\nWe thank the reviewer for pointing out the importance of this fact. In the revised manuscript, we have included a detailed analysis of our results against the undressed 2DEG quantum Hall system behavior.\n\n\\begin{itemize}\n  \\item Section VI - third paragraph (page 8):\\\\\n  {\\color{Red}\n  By comparing the theoretical \\cite{ando72,ando74_1,ando74_2,ando74_3,ando74_4,ando82,endo09} and experimental \\cite{endo09,wakabayashi78,ochiai190,mancoff96,arapov02,grbic04,caviglia10} studies on the magnetoresistance of 2DEG quantum Hall systems when no radiation is present against our results, we can identify that longitudinal conductivity oscillations in Fig. 4 are a repetition of the Shubnikov–de Haas(SdH) oscillations.\n  As observed in the experimental work of Caviglia \\textit{et al.} \\cite{caviglia10}, the period of SdH oscillations depends only on the perpendicular component of the magnetic field to the plane of the 2DEG.\n  Therefore, we can identify that many experiments on different types of 2DEGs at low-temperatures \\cite{endo09,ochiai190,mancoff96,arapov02,grbic04,caviglia10} have analyzed these SdH oscillations against the applied magnetic field's amplitude.\n  The cyclotron frequency ($\\omega_0$) of the system depends on the magnetic field's perpendicular component to the plane of the 2DEG.\n  The gate voltage modifies the Fermi level of the system.\n  Since the Landau level energy is only dependent on the cyclotron frequency, this gate voltage variation under a constant magnetic field amplitude generates the same SdH oscillations.\n  Interestingly, this oscillatory behavior against applied gate voltage has been observed experimentally by Wakabayashi \\textit{et al.} \\cite{wakabayashi78} in an inversion layer on a silicon surface at low temperature.\n  By comparing these observations against our results in Fig. 4, we can identify that our oscillations also show the same characteristic behavior; i.e  $\\hbar\\omega_0$ periodic SdH oscillations against the Fermi energy.\n  Furthermore, when we increase the gate voltage, the Fermi level rises. As illustrated in Fig. 4, this will result in a higher conductivity peak value at the higher-order Landau levels. This same behavior was also observed in the experimental observations presented in Ref. \\cite{wakabayashi78}.\n  In our work, we provide analytical results describing the controllability of these conductivity regions using a dressing field.\n  }\n\\end{itemize}\n\n\\subsubsection*{Comment 2 -\n\\color{RoyalBlue} In the presence of disorder, Anderson localization and topologically protected edge modes are dominant considerations when calculating DC transport coefficients. How are these factors taken into account?\n}\n\nWe omitted a discussion on the Anderson localization and topologically protected edge modes as we neglected them in our work.\nWhile deriving Eq.~[31], we have assumed that the applied static magnetic field is placed in a lower intensity range where we can neglect several effects known to appear in a 2DEG quantum Hall system. Under this condition, we can neglect the localization in the tails of Landau level peaks, the formation of the edge states, the electron-electron interactions, and the spin splitting as well. As mentioned in the work of Endo \\textit{et al.} \\cite{endo09}, within the magnetic field range of interest, the undressed\nmagneto-transport properties of GaAs/AlGaAs 2DEG quantum Hall system provide an excellent agreement between the experimental observations and theory that was developed by neglecting the above-mentioned effects. Our work is very similar to theirs with an additional dressing field. Our results for the undressed system agree with the results in Ref. \\cite{endo09}, while we provide a better description to manipulate the width of the Landau level conductivity peaks. We have added this clarification in the manuscript.\n\n\\begin{itemize}\n  \\item Section I - sixth paragraph (page 2):\\\\\n  {\\color{Red}\n  It is important to note that, we limit the applied magnetic field to a range where we can neglect effects such as Anderson localization, formation of the edge states, spin splitting, and the electron-electron interactions. These are not overly restrictive assumptions, and other have successfully used same assumptions in their work, e.g see Endo \\textit{et al.} \\cite{endo09}.\n  }\n  \\item Section VIII - first paragraph (page 10):\\\\\n  {\\color{Red}\n  We modeled the impurities in the material as a Gaussian random scattering potential, and restricted the applied magnetic field to a range where we can neglect effects of Anderson localization, formation of the edge states, spin splitting, and electron-electron interactions.\n  }\n\\end{itemize}\n\n\n\\subsubsection*{Comment 3 -\n\\color{RoyalBlue} Can the authors reproduce the quantized Hall conductance of filled Landau levels in the presence of disorder? Please discuss.\n}\n\nFor analyzing our system, we mainly employ the diagonal components of the Floquet-Drude conductivity tensor introduced by Wackerl \\textit{et al.} \\cite{wackerl20}. As we mainly focus on SdH oscillations in longitudinal conductivity components, we limit our analysis to the dressing field influence on two diagonal components of the conductivity tensor.\nTherefore we cannot predict the off-diagonal component behavior of the system. However, we can use the already established formalism introduced by Endo \\textit{et al.} \\cite{endo09} to predict the behavior of off-diagonal components of the conductivity tensor. As mentioned in Ref. \\cite{endo09}, this theory on the relation between longitudinal and transverse conductivities highly agree with  experiment observations\n\\begin{equation} \\tag{1}\n  \\dv{\\widetilde{\\sigma}^{xy}(X_F,I)}{B} \\approx\n    \\pi\\mu \\frac{\\hbar \\omega_0}{\\varepsilon_F} [\\widetilde{\\sigma}^{xx}(X_F,I)]^2.\n\\end{equation}\nBy examining the connection between longitudinal and transverse conductivities in the 2DEG quantum Hall system, we can expect the same Hall conductivity behavior in a dressed quantum Hall system. However, using the dressing field, we can squeeze the conductivity peaks on Landau levels, i.e., squeeze the region of longitudinal conductivity peaks placed near the Landau levels. This  implies sudden Hall conductivity transitions between one plateau to another near a Landau level. As in Refs.  \\cite{klitzing80,gusynin06}, we can also predict a staircase behavior of quantum Hall conductivity against the gate voltage. With an external dressing field, we will be able to get rapid transitions than the undressed system. However, to derive an analytical expression for the quantum Hall conductivity through Floquet-Drude conductivity needs to be reformulated from the beginning. It will be the subject of our future study.\n\n\\subsubsection*{Comment 4 -\n\\color{RoyalBlue} The way some previous works are cited is disappointing. Example from page 8: “Despite this behavior being identified in previous works, their results did not coincide with the more accurate description of conductivity components in undressed quantum Hall systems.” This is not informative. Where, specifically, did results from earlier works fall short of reality, which have been better addressed in this work?\n}\n\nWe made the following changes in language and presentation to improve the clarity of our manuscript.\n\n\\begin{itemize}\n  \\item Section VIII (page 8):\\\\\n  {\\color{Red}\n  Despite this behavior being identified in the previous work of Dini \\textit{et al.}  \\cite{dini16}, they cannot fully account for the experimental observations of longitudinal conductivity components in undressed quantum Hall systems presented in Ref. \\cite{endo09}. The authors of Ref. \\cite{dini16} have used the conventional expression of longitudinal conductivity from Refs. \\cite{ando74_1,ando82} and this theory yields a semi-elliptical broadening for the Landau levels. These predictions significantly deviate from the experimentally observed Landau level broadening \\cite{endo09}.\n  However, our generalized analysis on the conductivity of dressed quantum Hall systems provides a well-suited description for empirically observed behaviors of undressed quantum Hall systems as well.\n  }\n  \\item Section III - first paragraph (page 3):\\\\\n  {\\color{Red}\n  In their study \\cite{wackerl20}, the authors have presented more accurate results than the former theoretical descriptions \\cite{morina15,pervishko15} for the conductivity of nanoscale systems in the  presence of a dressing field.\n  }\n  \\item Section I - fifth paragraph (page 2):\\\\\n  {\\color{Red}\n  The authors of Ref. \\cite{dini16} used the conductivity models from Refs. \\cite{ando74_1,ando82}, and as mentioned in Endo \\textit{et al.} \\cite{endo09}, those models predict a semi-elliptical broadening against Fermi level for each Landau level and provide less agreement with the empirical results.\n  }\n  \\item Section IV - third paragraph (page 5):\\\\\n  {\\color{Red}\n  In the study presented in Ref. \\cite{endo09}, the authors have assumed that the effective mass of an electron in GaAs-based quantum well system is $m_e \\approx 0.07\\widetilde{m}_e$ where $\\widetilde{m}_e$ is the mass of the electron \\cite{endo09,winkler03,wackerl20}.\n  }\n\\end{itemize}\n\n\\subsubsection*{Comment 5 -\n\\color{RoyalBlue} Adding some physical insight into the remarkable observation of radiation-induced narrowing of lineshapes (Figs 4, 5) will help elevate\nthis work.\n}\n\nWe agree with the reviewer that a discussion on our theoretical results and their physical significance in modern nanoelectronic devices is a vital requirement. We have added a new Section VII to overcome the above-mentioned deficiency of our manuscript. The total content of the section is given below,\n\n\\begin{itemize}\n  \\item Section VII (page 8):\\\\\n  {\\color{Red}\n  \\subsection*{VII. PHYSICAL SIGNIFICANCE OF THE OUTCOMES}\n\n  With the realization of 2DEGs in Si-MOSFETs (Metal Oxide Semiconductor Field Effect Transistors) \\citep{fowler66}, Klitzing \\textit{et al.} \\cite{klitzing80} made the first transport measurements on such systems to reveal the quantum Hall effect. The empirical discovery of these unusual properties marked the beginning of a whole new realm in condensed matter physics that continues to produce phenomenal advancements in electronic systems. The quantum Hall effects in a 2DEG under a static magnetic field are described by plateaus quantized to integer values of the conductivity quantum ($\\flatfrac{e^2}{\\hbar}$) in the off-diagonal conductivity, with simultaneous peaks at inter-plateau transition for the diagonal conductivity \\cite{endo09}. This is due to the applied magnetic field and it changes the energy spectrum of 2DEG dramatically. The magnetic field causes the density of states in 2DEG to split up into a sequence of delta functions, separated by an energy $\\hbar\\omega_0$, with $\\omega_0$ the cyclotron frequency which depends on the applied magnetic field.\n  However, experimental results demonstrate that these Landau levels are broadened and the main source of these broadening at low temperatures is the disorders in materials \\cite{ando85,dial07}. The broaden sequence of delta functions of the density of states implies the oscillating behavior in the experimental measurements of longitudinal conductivity which is known as SdH oscillations \\cite{endo09,wakabayashi78}.\n\n  Our theoretical analysis on longitudinal conductivity behavior of dressed quantum Hall system was developed by considering low-temperature limit with Gaussian impurity broadening assumptions.\n  As illustrated in Fig. 4, we can describe the experimentally observed SdH oscillation results in Refs.\\cite{endo09,wakabayashi78} through our model.\n  Under the undressed condition, our results overlap with the conductivity measurement of quantum Hall systems \\cite{endo09}. Strikingly, we show in Fig. 5 that we can manipulate the broadening of these conductivity peaks using an external dressing field. At low temperatures, the principal cause of broadening of these conductivity peaks is impurity-induced scattering. Using an external dressing field, we can suppress the impurity-induced scattering and this results a reduction of both the scattering-induced broadening and the longitudinal conductivity peaks.\n\n  Research on novel states of matter has driven the evolution of present-day nanoelectronic devices. In particular, controllable manipulation of material properties through a gate electric field has revolutionized the development of material science and technology \\cite{ahn03,deng18}.\n  The charge carrier concentration of a system is an imperative parameter that defines its conductivity properties.\n  As we can manipulate the charge carrier concentration using an electrostatic field-effect, we exert significant control over the conductivity externally.\n  A 2DEG under static magnetic field with quantum Hall effects is an excellent example that illustrates how the gate electric field controls conductivity.\n  We also observed that a considerable number of studies exist on charge transport in the quantum limit that employed different types of 2D field-effect transistors (FETs) subjected to magnetic fields \\cite{wakabayashi78,yang18,long20,li14}. Yang \\textit{et al.} \\cite{yang18} study shows quantized Hall plateaus and SdH oscillations for longitudinal conductivity against gate voltage in black phosphorus FET under static magnetic fields at low temperatures. Since the Fermi level of a system can be altered with the applied gate voltage, our Fig. 4 depicts this result.\n  In particular, our analysis shows that we can manipulate the broadening of the conductivity regions using an external dressing field. Although Yang \\textit{et al.} \\cite{yang18}, achieved broadening in longitudinal conductivity peaks by changing the temperature in a low range, in this study we presented a general theory on manipulating longitudinal conductivity broadening using a high-intensity electromagnetic field.\n\n  The realization of the underlying mechanism of 2D FETs in the quantum realm promises its potential in next-generation nanoelectronic applications. In a particular application that uses the switching mechanism of the above-discussed FETs with quantum Hall effects, we can achieve high and low output conductivities by changing the input gate voltage. As a result of manipulating the broadening of conductivity regions, we can limit the broadening of conductivity peaks around Landau levels using a dressing high-intensity electromagnetic field. This will enhance the sensitivity of FETs which provides the ability to observe narrow changes in gate voltage.\n  Furthermore, adopting the mechanism presented in Ref. \\cite{hirakawa01}, we can manipulate conductivity peaks into very sensitive, narrowband high-frequency radiation detectors.\n  We envision these advances in nanoelectronics from our theoretical model and knowledge generated from the insight it provides to the underlying dependencies.\n  Furthermore, this theoretical model will aid in the development of simulation tools that will design the quantum effects in\n  magneto-transport properties of 2D nanostructures.\n  }\n\\end{itemize}\n\n\\bibliography{response}\n\\medskip\nSincerely yours,\n\n\\def\\s#1#2#3{\\vbox{\\hsize=4.5cm\n\t\t\\kern2cm\n\t\t\\hrule\\kern1ex\n\t\t\\hbox to \\hsize{\\strut\\hfil #1 \\hfil}\n\t\t\\hbox to \\hsize{\\strut\\hfil #2 \\hfil}\n\t\t\\hbox to \\hsize{\\strut\\hfil #3 \\hfil}}}\n\n\\hbox to \\hsize{\\s{Malin Premaratne}{(Corresponding Author)}{\\href{malin.premaratne@monash.edu}{malin.premaratne@monash.edu}}}\n\n\n\\end{document}\n\n% ****** End of file dressed_quantum_hall.tex ****** %\n", "meta": {"hexsha": "d7d0ecdf487c9f7781629affdfaa0e0ff54c83ac", "size": 67130, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "response/response.tex", "max_stars_repo_name": "KosalaHerath/magnetic-2DEG-conductivity", "max_stars_repo_head_hexsha": "91c5df1b018579b4b9c91d84f2d60ee482a001de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "response/response.tex", "max_issues_repo_name": "KosalaHerath/magnetic-2DEG-conductivity", "max_issues_repo_head_hexsha": "91c5df1b018579b4b9c91d84f2d60ee482a001de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "response/response.tex", "max_forks_repo_name": "KosalaHerath/magnetic-2DEG-conductivity", "max_forks_repo_head_hexsha": "91c5df1b018579b4b9c91d84f2d60ee482a001de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 103.9164086687, "max_line_length": 1531, "alphanum_fraction": 0.7795471473, "num_tokens": 15954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.34226221457390893}}
{"text": "\\chapter{Solving the De Novo Genome Assembly}\n\n\nIn this last chapter, we approach the genome assembly problem with the use of quantum annealing. Let us first understand what this problem is, and then translate it to a QUBO model and solve it using quantum annealing.\n\n\n\\section{The Genome Assembly Problem}\n\n\nThe genome of an organism is all its genetic material \\cite{Roth2019}. The deoxyribonucleic acid (DNA) is the carrier of that genetic information. It consists of two long chains twisted to form a double helix \\cite{Alberts2007}. Each of these chains is composed of a series of nucleotides or bases: adenine (A), guanine (G), cytosine (C), and thymine (T). Since these bases are matched in pairs in the DNA double helix, they are called base pairs (bp).\n\nA genome sequence is the complete list of nucleotides of every chromosome of an organism. With today's technology, automated sequence machines can read up to $10.000$ bp at a time \\cite{Reinert1015} while the human genome contains 3 Mbp, so we cannot simply read the whole genome. This is where genome assembly comes in.\n\nGenome assembly refers to the process of, given a large number of short DNA reads, stitch them together to form a large representation of the original chromosome where the reads came from. The two main techniques used to reconstruct these sequences are the ab initio reference-free alignment and the de novo reference-based assembly.\n\n\n\\subsection{Ab initio reference-based alignment}\n\n\nIn this method, the DNA reads are matched against a known trusted reference of the same organism. This is essentially a pattern matching problem, where we find the index of a given sub-string in a larger string. However, after the reconstruction is complete the result is compared to the reference in order to identify implications; therefore introducing bias based on the reference \\cite{Sarkar2020}.\n\nIn the naive approach, the short sub-string is compared to the reference starting at the first index. If the end of the sub-string is reached with a positive, a match is obtained. Otherwise, the sub-string is shifted a single position and we compare again. Heuristic methods that improve on this idea are based on shifting a greater number of spaces after a mismatch.\n\nDifferent number of strategies have been developed in this direction. For instance, the classic Boyer-Moore and Knuth-Pratt-Morris algorithms \\cite{Holmes1999}. However, these in particular are not adequate for genome assembly since these are exact string matching algorithms and DNA reads usually need approximate matches due to reads errors. Other algorithms worth mentioning are the Needleman-Wunsch algorithm \\cite{Needleman1970} and the Smith-Waterman algorithm \\cite{Smith1981}, for global and local alignment respectively. These are dynamic programming algorithms designed specifically with DNA reads in mind. \n\nState of the art algorithms trades off accuracy for speed and memory. Given enough computational power, the de novo reference-free method yields better results without introducing any reference bias.\n\n\n\\subsection{De novo reference-free assembly}\n\\label{sec:de-novo-genome-assembly}\n\nOn the other hand, the de novo reference-free method is, as its name suggests, reference free. Meaning, it is based only on the DNA reads. Thus, it has no reference bias but it is more computationally complex. It is usually used the first time a species DNA is read.\n\nIn this technique, multiple copies of the same DNA are made before slicing it. After chopping each copy at random places the data is redundant and the different reads overlap, making the assembly easier. There are multiple methods for de novo assembly based on different tools: Overlap-Layout Consensus (OLC) methods, de Bruijn graph (DBG) methods, string graphs, greedy and hybrid methods are some of the most famous examples (for a review see \\cite{Sohn2018}). Depending on the reading method and the number and length of the DNA reads, different methods excel from the rest. For instance, short-read technologies with a large number of reads favor DBG methods while high-quality long reads favor OCL methods. For our purposes, we will focus on the OCL method.\n\nIn the OLC graph used for the de novo whole-genome assembly, each node represents a different DNA read. Directed edges are associated a weight depending on how well these two reads are stitched together in a certain order. For example, the directed edge going from reading $r_1$ to read $r_2$ will be assigned a weight depending on how well $r_1r_2$ can be stiched.\n\nThe weights computation depends on the implementation. For the purpose of this thesis, we will use exact matches, no taking reading errors into consideration. Then, the weight assigned to an edge is the length of the overlap between both reads without any errors, with a change of sign. For example, given the reads $r_1 = AATT$ and $r_2 = TTCC$, the perfect stitching will produce $AATTCC$, so the overlap between both reads is $2$, giving a weight of $-2$. We may call this the \\emph{distance} between reads $r_1$ and $r_2$ (in that order). It does not fulfill the mathematical definition of distance since it is not even symmetric, but it will be useful for us anyway.\n\nA Hamiltonian path in our overlap graph will represent a series of reads in a certain order. By minimizing the total cost of our Hamiltonian path, we maximize the overlap between reads, resulting in the shortest possible final chain. This is exactly the same as solving the Travelling Salesman problem associated with our overlap graph.\n\nFigure \\ref{de-novo-process} shows the whole problem resolution \\cite{Boev2020}. Given the DNA reads (a) we compute the overlap graph (b) using a distance between the reads. We continue by viewing this problem as a traveling salesman and transforming it into a QUBO model (c). Then, either a simulated annealer (e) or the D-Wave quantum annealer (d) are used to obtain the Hamiltonian path/cycle of minimum cost (f). Finally, we traverse the cycle and build the resulting genome sequence.\n\n\\begin{figure}[H]\n\t\\includegraphics[scale=0.4]{de-novo-process.png}\n\t\\centering\n\t\\caption{Resolution diagram for the genome assembly using quantum annealing \\cite{Boev2020}}\n\t\\label{de-novo-process}\n\\end{figure}\n\n\n\\newparagraph{Numerical example}\n\n\nLet us study a final numerical example based on \\cite{Sarkar2020} that shows the whole process. Suppose we are given the following reads:\n\n\\begin{itemize}\n\t\\item $r_0 = ATGGCGTGCA$\n\t\\item $r_1 = GCGTGCAATG$\n\t\\item $r_2 = TGCAATGGCG$\n\t\\item $r_3 = AATGGCGTGC$\n\\end{itemize}\n\nWe may compute the overlap between the different reads. This results in the overlap graph from figure \\ref{fig:overlap-graph}.\n\n\\begin{figure}[h]\n\t\\includegraphics[scale=1.1]{graphs/salesman-example.pdf}\n\t\\centering\n\t\\caption{OLC graph}\n\t\\label{fig:overlap-graph}\n\\end{figure}\n\nWhich is the same graph studied in the traveling salesman section, \\ref{sec:salesman-example}. From the study done in that section, we know that there are six types of cycles in the graph. They are displayedin table \\ref{tbl:salesman-cycles}. In figure \\ref{fig:overlap-cycles}, we see how these types of cycles represent different ordinations of our DNA reads, as well as their overlaps and the total length of the resulting chain.\n\n\\begin{figure}[h]\n\t\\makebox[\\textwidth][c]{\n\t\t\\includegraphics[scale=0.35]{overlap-cycles.png}\n\t}\n\t\\centering\n\t\\caption{Type of cycles and their corresponding overlap analysis \\cite{Sarkar2020}}\n\t\\label{fig:overlap-cycles}\n\\end{figure}\n\nAs we know, the type of Hamiltonian cycle that minimizes the cost is type A. This type translates into the shortest chain, with a total length of $19$. We can easily compute the resulting assembly by traversing the graph and weaving the reads together.\n\n\n\\section{Experimentation}\n\\label{sec:experimentation}\n\n\nIn this last section, we will explain the experiments reproduced using the D-Wave systems.\n\n\n\\subsection{How to reproduce the experiments}\n\n\nIn order to configure the samplers and submit jobs to D-Wave quantum annealers we used the \\emph{D-Wave Ocean Software}, a suite of tools provided by D-Wave to use their quantum systems \\cite{DWave-OceanDoc}. Using python and the provided packages we may connect to \\emph{Leap}, a 'quantum' cloud service that provides access the quantum computers \\cite{DWave-Leap}.\n\nLeap provides a minute of free QPU time with the (free) developer plan. We may extend this time by obtaining either commercial or research access. This can be done by contacting the Leap team.\n\nFor the pourpose of this thesis I used the developer plan. In total, I submitted $104$ jobs to Leap, out of the allowed $106$. I consumed $59.064$ QPU seconds, as can bee seen in Leap's breakdown in figure \\ref{fig:leap-breakdown}. The number of jobs and QPU time used in each system can be seen in table \\ref{tab:leap-breakdown}.\n\n\\begin{table}[H]\n\t\\centering\n\t\\begin{tabular}{lrr}\n\t\t\\textbf{System} & \\textbf{Number of jobs} & \\textbf{QPU time (s)} \\\\\n\t\t\\hline\n\t\tD-Wave 2000Q\t& 26\t& 11.015\t\\\\\n\t\tAdvantage\t\t& 77\t& 46.681\t\\\\\n\t\tTotal\t\t\t& 104\t& 59.064                     \n\t\\end{tabular}\n\t\\caption{Leap usage summary breakdown between systems.}\n\t\\label{tab:leap-breakdown}\n\\end{table}\n\nApart from Leap, in order to reproduce these experiments you will need to install tthe following Python packages, available thorugh \\emph{pip}: \\textbf{\\emph{dimod}}, \\textbf{\\emph{neal}}, \\textbf{\\emph{minorminer}}, \\textbf{\\emph{dwave}} and \\textbf{\\emph{dwave\\_networkx}}. The code I used for these experiments can be found in \\cite{thesis-code}, which are inspired on \\cite{Sarkar2020}.\n\n\\begin{figure}[H]\n\t\\includegraphics[scale=0.5]{experiments/leap-breakdown.png}\n\t\\centering\n\t\\caption{Leap monthly usage summary.}\n\t\\label{fig:leap-breakdown}\n\\end{figure}\n\n\n\\subsection{Experiment 1: Data preparation and exact solving}\n\n\nThe first experiment aims to solve the previously discussed example using an exact solver provided by the Ocean's \\emph{dimod} library \\cite{Dimod}. The steps taken to transform the given reads to the QUBO matrix that Ocean's classes and functions use will be shared between the simulated annealer and the real quantum solvers. Therefore, the data preparation applied will be shared between experiments. The pseudocode of the experiment can be seen in the following snippet.\n\n\\begin{algorithm}\n\t\\caption*{\\textbf{Experiment 1}}\n\t\n\tData preparation:\n\t\\begin{itemize}\n\t\t\\item Compute the distance between every two reads, creating an adjacency matrix.\n\t\t\\item Transform the TSP adjancency matrix into a QUBO $Q$ matrix, as explained in section \\ref{sec:tsp-qubo}.\n\t\t\\item Transform the QUBO matrix into an adjacency dictionary.\n\t\\end{itemize}\n\n\tSolving:\n\t\\begin{itemize}\n\t\t\\item Initiaize a sampler: \\textbf{\\emph{dimod.ExactSolver}}.\n\t\t\\item Solve the prepared QUBO model using the selected solver.\n\t\\end{itemize}\n\t\n\tPresent the results.\n\\end{algorithm}\n\nAs we already know, using quantum annealing does not guarantee that we will obtain the optimal solution for a given cost function. In order to overcome this problem we use multi-sampling: running the experiment multiple times and and look at the best obtained solutions. Ocean already implements different types of \\emph{samplers} to facilitate this task \\cite{DWave-OceanDoc-Samplers}. In this first experiment we use an \\emph{ExactSolver}, which simply check every possible solution. Although time-costly, this method will let us know if our data manipulation before solving the experiment is correct, and how the solutions landscape looks like.\n\nThe third step in data preparation is a formatting step. Ocean requires the QUBO and Ising models to be in an adjacency dictionary instead of a matrix. Let us look at an example of this transformation in order to better understand it. Consider a 2-reads, the associated TSP will have $2^2 = 4$ nodes: $n0t0$, $n0t1$, $n1t0$ and $n1t1$. Suppose the following (inconsistency) matrix is the associated $Q$ matrix:\n\n$$\nQ = \n\\left(\n\\begin{array}{cccc}\n\t1 & 2 & 3 & 4 \\\\\n\t5 & 6 & 7 & 8 \\\\\n\t9 & 10 & 11 & 12 \\\\\n\t13 & 14 & 15 & 16 \n\\end{array}\n\\right)\n$$\n\nThen, it will be transformed into the dictionary, with $11$ missing entries: \n\n\\begin{minted}[bgcolor=bg]{python}\nquboDict: {\n\t('n0t0', 'n0t0'): 1,\n\t('n0t0', 'n0t1'): 2,\n\t('n0t0', 'n1t0'): 3,\n\t('n0t0', 'n1t1'): 4,\n\t...\n\t('n1t1', 'n1t1'): 16,\n}\n\\end{minted}\n\nIn particular, this experiment is applied to the already studied example with the following four reads:\n\n\\begin{itemize}\n\t\\item $r_0 = ATGGCGTGCA$\n\t\\item $r_1 = GCGTGCAATG$\n\t\\item $r_2 = TGCAATGGCG$\n\t\\item $r_3 = AATGGCGTGC$\n\\end{itemize}\n\nThe pair-wise distances are computed, providing a direct measure of much two reads overlap. Then, these values are normalized for easier use. The resulting normalized TSP matrix is transformed into a QUBO matrix using $1.6$ as multi-location and repetition penalties, and $-1.6$ for self-bias, as done in \\cite{Sarkar2020}. Finally, we initialize an \\emph{ExactSolver} and use it to sample every possible solution.\n\nAfter the execution is completed, we find the lowest energy in the obtained solutions and print every solution with that energy:\n\n\\begin{minted}[bgcolor=bg]{python}\n{'n0t0': 0, 'n0t1': 0, 'n0t2': 1, 'n0t3': 0,\n 'n1t0': 0, 'n1t1': 0, 'n1t2': 0, 'n1t3': 1,\n 'n2t0': 1, 'n2t1': 0, 'n2t2': 0, 'n2t3': 0,\n 'n3t0': 0, 'n3t1': 1, 'n3t2': 0, 'n3t3': 0} --> -7.9811\n\n{'n0t0': 0, 'n0t1': 1, 'n0t2': 0, 'n0t3': 0,\n 'n1t0': 0, 'n1t1': 0, 'n1t2': 1, 'n1t3': 0, \n 'n2t0': 0, 'n2t1': 0, 'n2t2': 0, 'n2t3': 1, \n 'n3t0': 1, 'n3t1': 0, 'n3t2': 0, 'n3t3': 0} --> -7.9811\n\n{'n0t0': 1, 'n0t1': 0, 'n0t2': 0, 'n0t3': 0,\n 'n1t0': 0, 'n1t1': 1, 'n1t2': 0, 'n1t3': 0, \n 'n2t0': 0, 'n2t1': 0, 'n2t2': 1, 'n2t3': 0, \n 'n3t0': 0, 'n3t1': 0, 'n3t2': 0, 'n3t3': 1} --> -7.9811\n\n{'n0t0': 0, 'n0t1': 0, 'n0t2': 0, 'n0t3': 1,\n 'n1t0': 1, 'n1t1': 0, 'n1t2': 0, 'n1t3': 0,\n 'n2t0': 0, 'n2t1': 1, 'n2t2': 0, 'n2t3': 0,\n 'n3t0': 0, 'n3t1': 0, 'n3t2': 1, 'n3t3': 0} --> -7.9811\n\\end{minted}\n\nAs expected, these are the four minimums of the cost functions, representing the four ways of describing a type A loop in the used codification.\n\nFinally, let us plot the landscape of solutions for the given reads. We sort the solutions by increasing energy and simply plot their energy, as seen in figure \\ref{fig:exp1-landscape}.\n\n\\begin{figure}[H]\n\t\\makebox[\\textwidth][c]{\n\t\t\\includegraphics[scale=0.7]{experiments/experiment1.png}\n\t}\n\t\\centering\n\t\\caption{Landscape of solutions}\n\t\\label{fig:exp1-landscape}\n\\end{figure}\n\n\n\\subsection{Experiment 2: Simulated Quantum Annealing}\n\nFor our second experiment, we aim to solve our example using Simulated Annealing. Although \\emph{dimod} provides a simulated annealing sampler, we use for our final experiments the  \\emph{SimulatedAnnealingSampler} from \\emph{Ocean}'s \\emph{Neal} package as it yields more distributed results and has far better computing time. The same experiment was reproduced $10$ times using both samplers in my machine. Dimod's sampler run in a mean time of $11.76$ seconds while \\emph{Neal}'s run in a mean time of $0.0610$ seconds.\n\nThe pseudo-code does not change much from the first experiment to the second one, we simply change the annealer:\n\n\\begin{algorithm}\n\t\\caption*{\\textbf{Experiment 2}}\n\t\n\tData preparation:\n\t\\begin{itemize}\n\t\t\\item Compute the distance between every two reads, creating an adjacency matrix.\n\t\t\\item Transform the TSP adjancency matrix into a QUBO $Q$ matrix, as explained in section \\ref{sec:tsp-qubo}.\n\t\t\\item Transform the QUBO matrix into an adjacency dictionary.\n\t\\end{itemize}\n\t\n\tSolving:\n\t\\begin{itemize}\n\t\t\\item Initiaize a sampler: \\textbf{\\emph{neal.SimulatedAnnealingSampler}}.\n\t\t\\item \\textbf{Sample from} the prepared QUBO model using the selected \\textbf{sampler}.\n\t\\end{itemize}\n\t\n\tPresent the obtained samples.\n\\end{algorithm}\n\nIt is worth mentioning that we do not \\emph{solve} the QUBO model in these experiments, we \\emph{sample} different results using simulated annealing.\n\nSince \\emph{Neal}'s sampler is quite efficient we were able to execute experiments with up to $10.000$ repetitions of the experiment, also called \\emph{sample reads} or simply \\emph{reads}. We developed an automated and scalable way to check whether a given cycle returned by the annealer was valid, and to recover its associated type. Using these tools we can easily check the number of occurrences each type of cycle appeared in the obtained sample reads. These results are presented, along with the associated energy to each result, in table \\ref{tab:exp2} and figure \\ref{fig:exp2-occ}. See figure \\ref{fig:overlap-cycles} to recall the cycle types and cost computing.\n\n\\begin{table}[H]\n\t\\centering\n\t\\begin{tabular}{lrr}\n\t\t\\textbf{Cycle type} & \\textbf{Occurences} & \\textbf{Energy} \\\\\n\t\t\\hline\n\t\tType A\t& 3722\t& -7.9811\t\\\\\n\t\tType C\t& 1474\t& -7.4541\t\\\\\n\t\tType D\t& 1469\t& -7.4541\t\\\\\n\t\tType F\t& 1458\t& -7.4541\t\\\\\n\t\tType E\t& 1431\t& -7.4541\t\\\\\n\t\tType B\t& 446\t& -6.927                             \n\t\\end{tabular}\n\t\\caption{Results of experiment 2}\n\t\\label{tab:exp2}\n\\end{table}\n\n\\begin{figure}[H]\n\t\\includegraphics[scale=0.8]{experiments/experiment2.png}\n\t\\centering\n\t\\caption{Ocurrences of each type in a $10.000$ reads experiment using Simulated Annealing}\n\t\\label{fig:exp2-occ}\n\\end{figure}\n\nWe can appreciate in figure \\ref{fig:exp2-occ} that the best type of cycle agglomerates most of the samples, $37.22\\%$. In the second place, the four types of cycles that have the exact same energy also have almost exactly the same number of samples. This matches our quantum annealing theory: the physical system has an equal probability of ending in eigenstates with equal eigenenergies.\n\nIt is worth mentioning that there was not a single sample that encoded an invalid cycle. This means that the penalties values used for the experiment ($1.6$ for multi-location and repetition, and $-1.6$ for self-bias) are working to prevent invalid cycles.\n\nNow that we are familiar with the type of results and codifications we may find, let us jump to the quantum realm by using the D-Wave's Quantum Computer Systems.\n\n\n\\subsection{Experiment 3: Quantum Annealing using D-Wave}\n\n\nFor our third experiment, we aim to solve our example using D-Wave's quantum annealers. For this purpose, we need to add some extra steps to our data processing. Section \\ref{sec:embeddings} explained how not every graph can be directly mapped to the existing Chimera / Pegasus topologies that D-Wave systems use, and how we can overcome this problem by embedding our problems graphs into these topologies. The extra steps in our data processing are related to these embeddings: we will need to embed our graph into the fixed topology that will be used. Then, after the anneal takes place, we will translate the solutions from the embedded graph. Ocean provides a set of utilities to deal with these embeddings \\cite{DWave-OceanDoc-Embedding}.\n\nAdditionally, we will need to connect to Leap to send our jobs to the quantum annealers using a \\emph{client}. First, a configuration file is created, which includes your API key and some extra configuration details:\n\n\\begin{minted}[bgcolor=bg]{bash}\n[ocete]\nsolver = {\"qpu\": true}\ntoken = DEV-<api key goes here>\nendpoint = https://cloud.dwavesys.com/sapi\n\\end{minted}\n\nIn our code we initialize a \\emph{client} and a \\emph{solver} using the configuration file. These are objects that encapsulate the connection functionality and solving problems in the associated machine respectively. We also initialize a sampler as we did before, but this time a production sampler is used: a \\emph{DWaveSampler} that also needs our configuration file. The pseudo-code for this experiment can be found below. Each new step will be explained in detail below.\n\n\\begin{algorithm}\n\t\\caption*{\\textbf{Experiment 3}}\n\t\n\tInitialization:\n\t\\begin{itemize}\n\t\t\\item Initiaize a sampler: \\textbf{\\emph{system.samplers.DWaveSampler}}.\n\t\t\\item \\textbf{Initialize a client and obtain an associated solver}.\n\t\\end{itemize}\n\t\n\tData preparation:\n\t\\begin{itemize}\n\t\t\\item Compute the distance between every two reads, creating an adjacency matrix.\n\t\t\\item Transform the TSP adjacency matrix into a QUBO $Q$ matrix, as explained in section \\ref{sec:tsp-qubo}.\n\t\t\\item Transform the QUBO matrix into an adjacency dictionary.\n\t\t\\item \\textbf{Find an embedding from our graph to the selected machine's topology (either Chimera or Pegasus)}.\n\t\t\\item \\textbf{Use the previous embedding to create a new QUBO model equivalent for the embedded graph}.\n\t\\end{itemize}\n\t\n\tSolving:\n\t\\begin{itemize}\n\t\t\\item Use the solver to send a job to the client. This job samples from the prepared QUBO model multiple times.\n\t\\end{itemize}\n\t\n\tFormat the results:\n\t\\begin{itemize}\n\t\t\\item \\textbf{Use the computed embedding to translate our answers}.\n\t\\end{itemize}\n\\end{algorithm}\n\nThe first thing to be noticed is that the initialization now needs to be done before the data preparation. This is because, in order to find the embedding, we need to know which exact topology the quantum system will have. This information is provided through the \\emph{solver}, previously initialized. The initialization step is as simple as follows:\n\n\\begin{minted}[bgcolor=bg]{python}\nimport dwave\n\n# Create the solver (connecting to D-Wave) and the Sampler\nconfig_file='../dwave.conf'\nclient = cloud.Client.from_config(config_file, profile='ocete')\nsolver = client.get_solver()\ndwsampler = system.samplers.DWaveSampler(config_file=config_file)\n\\end{minted}\n\nSuppose $Q$ already holds our computed QUBO model. We can compute an embedding and obtained the new associated model as follows:\n\n\\begin{minted}[bgcolor=bg]{python}\nadjacency_dict = embedding.utils.edgelist_to_adjacency(solver.edges)\nembedding = minorminer.find_embedding(Q, solver.edges)\nQ_embedded = embed_qubo(Q, embedding, adjacency_dict)\n\\end{minted}\n\nBy using the same configuration file, the sampler already knows what machine it is associated to. We will sample from it, with the same syntax as in the second experiment:\n\n\\begin{minted}[bgcolor=bg]{python}\nresponse = dwsampler.sample_qubo(Q_embedded, num_reads=num_reads)\n\\end{minted}\n\nWhere $num\\_reads$ is a parameter that sets the number of samples to be read. However, these solutions are associated to the $Q\\_embedded$, not to our original $Q$ model. We need to translate the responses to understand them:\n\n\\begin{minted}[bgcolor=bg]{python}\nbqm = dimod.BinaryQuadraticModel.from_qubo(Q)\nunembedded_response = embedding.unembed_sampleset(response, embedding, bqm)\n\\end{minted}\n\nFor this experiment, the D-Wave 2000Q was used (see section \\ref{sec:d-wave-systems} to see its characteristics), since it was the default solver. After running the experiment with the same parameters as the simulated annealing experiment ($10.000$ reads and $(-1.6; 1.6; 1.6)$ for the QUBO parameters), we obtained that more than $90\\%$ of the samples were invalid, a huge difference with the astonishing $0\\%$ obtained in the second experiment.\n\nMy initial hypothesis was that the QUBO parameters were well adjusted for SA but not for QA, and thus allowed further tunning. After many attempts with different parameters values, this hypothesis was discarded. The only other set of parameters worth presenting is $(-1.5; 1.5; 1.5)$. These results are presented in table \\ref{tab:exp3}.\n\n\\begin{table}[H]\n\t\\centering\n\t\\begin{tabular}{lrrr}\n\t\t\\textbf{Cycle type} & \\textbf{Occurences (param=1.5)} & \\textbf{Occurences (param=1.6)} & \\textbf{Energy} \\\\\n\t\t\\hline\n\t\tType A\t& 131\t& 50\t& -7.9811\t\\\\\n\t\tType C\t& 124\t& 46\t& -7.4541\t\\\\\n\t\tType D\t& 40\t& 91\t& -7.4541\t\\\\\n\t\tType F\t& 55\t& 117\t& -7.4541\t\\\\\n\t\tType E\t& 112\t& 118\t& -7.4541\t\\\\\n\t\tType B\t& 99\t& 64\t& -7.4541\t\\\\    \n\t\tInvalid & 9221\t& 9194\t& $>$ -5.6433                         \n\t\\end{tabular}\n\t\\caption{Results of experiment 3, $10.000$ reads using the quantum annealer.}\n\t\\label{tab:exp3}\n\\end{table}\n\nIn figures \\ref{fig:exp3-occ1} and \\ref{fig:exp3-occ2} we see a comparison of the distribution between the different type of cycles in both experiments. We cannot see a distribution as we did in \\ref{fig:exp2-occ}, potentially due to the low numbers of reads that actually represent a valid cycle. In fact, such distribution between the cycle types is not needed: a single sample with the lowest energy solution will completely solve our genome assembly problem.\n\n\\begin{figure}[H]\n\t\\includegraphics[scale=0.75]{experiments/experiment3 (1.5).png}\n\t\\centering\n\t\\caption{Ocurrences of each cycle type in a $10.000$ reads experiment using Quantum Annealing, filtering out invalid cycles, with QUBO parameters $(-1.5; 1.5; 1.5)$}\n\t\\label{fig:exp3-occ1}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\includegraphics[scale=0.75]{experiments/experiment3 (1.6).png}\n\t\\centering\n\t\\caption{Ocurrences of each cycle type in a $10.000$ reads experiment using Quantum Annealing, filtering out invalid cycles, with QUBO parameters $(-1.6; 1.6; 1.6)$}\n\t\\label{fig:exp3-occ2}\n\\end{figure}\n\nWith these results in mind, is it possible that we are sampling completely random solutions? In a 4-reads problem, we obtain a 16 binary variables QUBO model. That means there are up to $2^{16}$ possible solutions using our encoding, even more after we embed it in the Chimera topology. If we were to randomly sample from that solution space, we will never get almost $10\\%$ of samples from a subset of $24$ solutions that represent our $6$ valid cycles. So we do know that the quantum system is working, just not as good as expected.\n\nWe have not found a clear improvement precision-wise in our small example, although QA does solve the problem. What about time-wise? In figure \\ref{fig:exp3-time} we see the time breakdown provided by Leap after our last experiment. We can see a total QPU sampling time of $2.389$ seconds, while if we repeat the experiment with the same parameters using SA we obtain a mean of $2.525$ sampling seconds, over $10$ experiment repetitions. Keeping in mind that our QA time data comes from a single execution and the small difference between both time measures, we cannot conclude that either approach has any time advantage in such small problems.\n\nHowever, does QA actually scales better than SA with the problem size? In the next experiment, we will study the Pegasus topology to understand what is the maximum problem size that can be tackled using the Advantage system. Finally, the last couple of experiments will try to answer the scalability comparison inquiry.\n\n\\begin{figure}[h]\n\t\\includegraphics[scale=0.5]{experiments/exp3-time.png}\n\t\\centering\n\t\\caption{Time breakdown provided by Leap after the last experiment.}\n\t\\label{fig:exp3-time}\n\\end{figure}\n\n\n\\subsection{Displaying chimera embeddings}\n\n\nLet us plot some logical embeddings using the D-Wave 2000Q system, with relies on a Chimera graph. In figure \\ref{fig:exp2_4reads} we see the embedding of a 4-nodes complete graph into the Chimera topology. The grey nodes represent unused nodes while nodes with the same color represent a single logical qubit mapped into multiple physical qubits.\n\n\\begin{figure}[h]\n\t\\includegraphics[scale=0.6]{experiments/exp2_4reads.png}\n\t\\centering\n\t\\caption{Embedding of a 4-nodes complete graph into a Chimera topology.}\n\t\\label{fig:exp2_4reads}\n\\end{figure}\n\nThe last embedding had a \\emph{maximum chain length} of $2$. That is, the longest chain in a logical qubit is 2 physical qubits. This is a critical parameter to be minimized in embeddings: the longer the qubit chain is, the more probable it is for the qubits in a logical qubit to be desynchronized and end up in different states. Thus, the more difficult it is for the system to stay in the ground state.\n\nIn figure \\ref{fig:exp2_13reads} we see an embedding of a 13-nodes complete graph into a Chimera topology. In this case, the maximum chain length is $5$, obtained by both the dark blue, purple, red, dark green, lime, and cyan logical qubits. In the rest of the experiments, I looked at the maximum chain length obtained in the pegasus embeddings, obtained lengths up to $15$ qubits. Since I did not have the time to study this characteristic in-depth, it will be a future line of work.\n\n\\begin{figure}[h]\n\t\\includegraphics[scale=0.6]{experiments/exp2_13reads.png}\n\t\\centering\n\t\\caption{Embedding of a complete 13-nodes complete graph into a Chimera topology.}\n\t\\label{fig:exp2_13reads}\n\\end{figure}\n\nRecall that in every 16-nodes chimera cell, every node in the vertical axis is connected to every node in the horizontal axis, and to no other node from the vertical axis. For example, take the blue logical qubit, represented by 3 nodes at the very bottom in figure \\ref{fig:exp2_13reads}. In the first cell, it connects with lime, pink, dark green, and cyan. In the second cell, it connects with light green, purple, red, and dark blue. In the third cell, it connects to brown, light blue, pink, and yellow. That makes a total of 12 connections, as expected since the embedded started with a complete 13-nodes graph.\n\n\n\\FloatBarrier\n\\subsection{Experiment 4: D-Wave's Advantage limits}\n\n\nFor our fourth experiment, we aim to test the limits of the Advantage architecture for our problem. That is, given a number of DNA reads, we will compute the associated QUBO problem and try to embed the obtained graph into the Advantage architecture. We will test these embeddings against a Pegasus 16 ($P_{16}$) topology since that is the one supported by the Advantage system.\n\nIn fact, given a set of $n$ reads, this is simply finding if a $n^2$-nodes complete graph ($K_{n^2}$) can be embedded into a $P_{16}$. The reads themselves are not relevant for the embedding. However, I have developed an automated way of creating fake tests, originally for a general-purpose, but it can also be used here.\n\nThis automated test production works as follows: Given a number of reads, the size of each chain (default value $150$), and the required overlap between adjacent chains (default value $50$), it randomly creates the original DNA chain, and then chop it using the given parameters. This makes sure that adjacent reads have enough overlap so it is basically impossible for two random reads to overlap more than $50$ bps.\n\nUsing these random tests we created graphs of an increasing number of reads until we were unable to find an embedding from $K_{n^2}$ to $P_{16}$. The results of the experiment can be seen in table \\ref{tab:exp4}. We can see that a valid embedding was found to problem size up to 14 reads ($K_{196}$ associated graph). The embedding time, as well as the test generation time, are also displayed. I decided to display both since, as time grew larger and larger, I was not sure whether the test generation was adding too much of an overload.\n\n\\begin{table}[H]\n\t\\centering\n\t\\makebox[\\textwidth][c]{\n\t\t\\begin{tabular}{ccccc}\n\t\t\t\\textbf{Number of reads} & \\textbf{Nodes in graph} & \\textbf{Test generation time} & \\textbf{Embedding time} & \\textbf{Total time} \\\\\n\t\t\t\\hline\n\t\t\t2   & 4   &  0.000157   &  0.081310   &  0.081708 \\\\\n\t\t\t3   & 9   &  0.000216   &  0.108525   &  0.109205 \\\\\n\t\t\t4   & 16   &  0.000269   &  0.194807   &  0.196045 \\\\\n\t\t\t5   & 25   &  0.000335   &  0.377673   &  0.379814 \\\\\n\t\t\t6   & 36   &  0.000392   &  1.147603   &  1.154559 \\\\\n\t\t\t7   & 49   &  0.000433   &  3.514801   &  3.523473 \\\\\n\t\t\t8   & 64   &  0.000497   &  11.876785   &  11.888235 \\\\\n\t\t\t9   & 81   &  0.000558   &  19.226392   &  19.244367 \\\\\n\t\t\t10   & 100   &  0.000610   &  43.457666   &  43.477268 \\\\\n\t\t\t11   & 121   &  0.000676   &  62.499896   &  62.528545 \\\\\n\t\t\t12   & 144   &  0.000724   &  89.277396   &  89.313831 \\\\\n\t\t\t13   & 169   &  0.000812   &  63.782066   &  63.827706 \\\\\n\t\t\t14   & 196   &  0.000840   &  152.262340   &  152.316223\n\t\t\\end{tabular}\n\t}\n\t\\caption{Results of experiment 4}\n\t\\label{tab:exp4}\n\\end{table}\n\nIt is worth noting that the algorithm used to find the embeddings does not guarantee to find a valid one if it exists. I tried to run the algorithm $50$ times with $15$ reads and could not find a valid embedding.\n\nThe reader might have already noticed that the embeddings are quite time-consuming. In fact, this is an NP problem itself and time will grow exponentially on input size. However, keep in mind that this embedding does not depend on the reads. Once a single embedding from a $K_{196}$ to a $P_{16}$ has been pre-computed it can be used -or further optimized- for different problems.\n\nNow that we know the maximum number of reads that the Advantage system may tackle, let us put it to the test with 'big' input problems in the next experiment.\n\n\n\\subsection{Experiment 5: Scalability comparison between Simulated Annealing and Quantum Annealing}\n\n\nIn our fifth experiment, we put the D-Wave's quantum annealers to the test with bigger input problems and study how they behave compared with the simulated annealing experiments. We will start with a $3$ reads and then progressively increase this value, creating tests of this size and trying to solve them using both the simulated annealer and the Advantage system.\n\nFor each fixed number of reads, we will sample $10.000$ times using the annealers, with the same set of parameters used for the previous experiments. The number of valid solutions (i.e. valid cycles) will be displayed, along with the number of cycles that reached the real solution, which we know in advance since we created the test.\n\nWe will also display the energy of the best sample obtained, along with the difference between the real solution energy and the best sample obtained, which I called \\emph{energy delta}. Finally, we will also display the sampling time, not including the time it took to create the test nor to prepare the data.\n\nThe results of this experiment using the simulated annealer can be seen in table \\ref{tab:exp5_1}. \n\n\\begin{table}[H]\n\t\\centering\n\t\\makebox[\\textwidth][c]{\n\t\t\\begin{tabular}{cccccc}\n\t\t\t\\textbf{N. reads} & \\textbf{Valid cycles} & \\textbf{Times sol. reached} & \\textbf{Energy delta} & \\textbf{Solution energy} & \\textbf{Sampling time} \\\\\n\t\t\t\\hline\n\t\t\t3\t& 10000\t\t& 9564\t\t\t& 0\t\t\t\t& -6.214214\t\t& 1.881374 \\\\\n\t\t\t4\t& 10000\t\t& 6852\t\t\t& 0\t\t\t\t& -8.131935\t\t& 2.178147 \\\\\n\t\t\t5\t& 10000\t\t& 3427\t\t\t& 0\t\t\t\t& -9.999001\t\t& 3.487972 \\\\\n\t\t\t6\t& 10000\t\t& 1308\t\t\t& 0\t\t\t\t& -11.834192\t& 5.121054 \\\\\n\t\t\t7\t& 10000\t\t& 351\t\t\t& 0\t\t\t\t& -13.656181\t& 7.057235 \\\\\n\t\t\t8\t& 10000\t\t& 108\t\t\t& 0\t\t\t\t& -15.443562\t& 9.680610 \\\\\n\t\t\t9\t& 10000\t\t& 21\t\t\t& 0\t\t\t\t& -17.232667\t& 12.797996 \\\\\n\t\t\t10\t& 10000\t\t& 3\t\t\t\t& 0\t\t\t\t& -18.995278\t& 16.080461 \\\\\n\t\t\t11\t& 10000\t\t& 0\t\t\t\t& 0.625356\t\t& -20.764680\t& 20.118828 \\\\\n\t\t\t12\t& 10000\t\t& 0\t\t\t\t& 0.601820\t\t& -22.510011\t& 25.351562 \\\\\n\t\t\t13\t& 10000\t\t& 0\t\t\t\t& 0.570361\t\t& -24.256735\t& 30.612547 \\\\\n\t\t\t14\t& 10000\t\t& 0\t\t\t\t& 1.378872\t\t& -26.005003\t& 34.897780\n\t\t\\end{tabular}\n\t}\n\t\\caption{Results of experiment 5, $10.000$ reads using the simulated annealer.}\n\t\\label{tab:exp5_1}\n\\end{table}\n\nWe stopped at 15 reads since that is the maximum value that will be able to compare with using the quantum annealer. In the experiment results, we see how the number of valid cycles out of $10.000$, which turns out to be every single cycle up to 14 reads. However, the number of samples that reached the best solution go down from $95\\%$ to ground cero from $11$ reads onward. Although we do not obtain the real solution, how close are these samples to it? \n\nThe columns related to the energy of the solutions try to answer this question. We may see how the solution's energy goes down to around $-26$, which is totally normal: the more reads in our graph, the higher the number of reads overlap, and the lower is the resulting solution energy. As soon as we cannot find the solution, the energy delta starts to increase, going up to around $1.37$. This means the energy of the best sample is quite close to the actual value. Is this enough?\n\nWhen we tackle a classic TSP, a near-optimal solution is a really valid and useful solution. We do not necessarily need the actual minimum. However, although a valid cycle with low energy represents a valid way of sorting and sewing the genome reads, it does not provide the real genome the reads came originally from. It has some value since it could be further tuned to obtain the solution, but it does not solve our problem.\n\nLastly, the sampling time seems to grow linearly with the number of reads. However, using this simple simulated annealer for a real case with up to 3 Mbps would be simply impossible.\n\nFor the second part of this experiment, I run the same experiment but using the quantum annealer. Some extra steps come with it, like computing the embedding and connecting to Leap, but they have all been explained in previous experiments. We again sample $10.000$ times a maintain the same values for the annealing schedule self-bias, multi-location, and repetition parameters. The results of this experiment can be seen in table \\ref{tab:exp5_2}.\n\n\\begin{table}[H]\n\t\\centering\n\t\\makebox[\\textwidth][c]{\n\t\t\\begin{tabular}{cccccc}\n\t\t\t\\textbf{N. reads} & \\textbf{Valid cycles} & \\textbf{Times sol. reached} & \\textbf{Energy delta} & \\textbf{Solution energy} & \\textbf{Sampling QPU time} \\\\\n\t\t\t\\hline\n\t\t\t3\t& 4574\t\t& 3295\t\t& 0\t\t\t\t& -6.214214\t\t& 1.035 \\\\\n\t\t\t4\t& 683\t\t& 156\t\t& 0\t\t\t\t& -8.131935\t\t& 0.962 \\\\\n\t\t\t5\t& 88\t\t& 6\t\t\t& 0\t\t\t\t& -9.999900\t\t& 1.272 \\\\\n\t\t\t6\t& 2\t\t\t& 0\t\t\t& -1.322536\t\t& -11.834014\t& 1.272 \\\\\n\t\t\t7\t& 1\t\t\t& 0\t\t\t& -1.647457\t\t& -13.671186\t& 1.206 \\\\\n\t\t\t8\t& 0\t\t\t& 0\t\t\t& -3.867139\t\t& -15.444996\t& 1.339 \\\\\n\t\t\t9\t& 0\t\t\t& 0\t\t\t& -36.592409\t& -17.227226\t& 1.570 \\\\\n\t\t\t10\t& 0\t\t\t& 0\t\t\t& -50.03568\t\t& -18.468571\t& 1.276\n\t\t\\end{tabular}\n\t}\n\t\\caption{Results of experiment 5, $10.000$ reads using the quantum annealer.}\n\t\\label{tab:exp5_2}\n\\end{table}\n\nThe first thing we may notice is that the experiment did not reach 14 reads. That is because I manually stopped it before it finished. The available QPU time was quite tight at the moment, and seeing the results of the experiment with a number of reads up to $10$ showed that we were not going to learn anything new by letting the experiment finished and wasting our remaining QPU time.\n\nBack to the results, we can appreciate the number of valid cycles rapidly goes down to $0$, and even quicker the number of reads that reached the solution. At 4 reads we see similar results to what we saw in experiment 3: around $700$ valid cycles and $150$ times the real solution (type A cycle in the third experiment) was reached. Although we have developed this experiment in different machines, D-Wave 2000Q and Advantage, keep in mind that the improvements from one generation to another are size-related: we may tackle bigger (and thus harder) problems by using the Advantage system. It does not mean that its computation is somehow better.\n\nNot only the responses are not valid, but they are also quite far from the solution. We can see that in how the delta grows hugely as we increase the number of reads. Leap provides a graph for each submitted experiment displaying the samples' distribution. In figures \\ref{fig:exp5_1} and \\ref{fig:exp5_2} we see this distribution for $4$ and $10$ reads respectively. \n\n\\begin{figure}[H]\n\t\\includegraphics[scale=0.5]{experiments/exp5_1.png}\n\t\\centering\n\t\\caption{$10.000$ samples' distribuition for $4$ reads using the quantum annealer.}\n\t\\label{fig:exp5_1}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\includegraphics[scale=0.5]{experiments/exp5_2.png}\n\t\\centering\n\t\\caption{$10.000$ samples' distribuition for $10$ reads using the quantum annealer.}\n\t\\label{fig:exp5_2}\n\\end{figure}\n\nWe can see how in the $4$ reads experiment, most of the samples group around $0$ energy, and only a very few are close to the solution, which is actually reached in this execution. However, in the $10$ reads experiment, most of the samples are gathered around $100/150$ energy, these solutions are not only invalid but really far from being so.\n\nLastly, let us comment on the QPU sampling time. This value is provided directly by Leap. From our code, we cannot separate the connection overload and other computations from the actual QPU sampling time. We may appreciate how time does not grow with the input. This is because the time it takes for the annealer to converge is fixed by the annealing schedule.\n\nIn conclusion, these results are astonishingly awful. The simulated annealing sampler not only provides closer samples to the solution, but in every seen case it reaches valid samples. My current hypothesis is that either the annealing schedule is not optimal, or that the values of the parameters can be improved for our specific problem. In our last experiment, I will spend all our remaining QPU time checking these two hypotheses.\n\n\n\\subsection{Experiment 6: Advantage tunning}\n\n\nFor our last experiment, we aim to test our previous hypothesis and try to solve a $10$ reads problem using the Advantage system. In the first set of iterations, I tried to increase the multi-location and repetition penalties in order to increase the number of valid cycles sampled. For this experiment, a single test with $10$ reads was created. Its solution energy was  $-18.994150$. The results of the experiment can be found in table \\ref{tab:exp6_1}, where the mentioned parameters are \\emph{(self-bias, multi-location, repetition)}.\n\n\\begin{table}[H]\n\t\\centering\n\t\\makebox[\\textwidth][c]{\n\t\t\\begin{tabular}{ccccc}\n\t\t\t\\textbf{Parameters} & \\textbf{Valid cycles} & \\textbf{Times sol. reached} & \\textbf{Energy delta} & \\textbf{Sampling QPU time} \\\\\n\t\t\t\\hline\n\t\t\t(-1.6, 1.6, 1.6)\t& 0\t\t& 0\t\t\t& -76.344431\t&\t1.500 \\\\\n\t\t\t(-3, 3, 3)\t\t\t& 0\t\t& 0\t\t\t& -87.263801\t&\t1.624 \\\\\n\t\t\t(-5, 5, 5)\t\t\t& 0\t\t& 0\t\t\t& -83.657639\t&\t1.272 \\\\\n\t\t\t(-10, 10, 10)\t\t& 0\t\t& 0\t\t\t& -258.290739\t&\t1.248 \\\\\n\t\t\t(-20, 20, 20)\t\t& 0\t\t& 0\t\t\t& -357.917063\t&\t1.311 \\\\\n\t\t\t(-50, 50, 50)\t\t& 0\t\t& 0\t\t\t& -1017.605383 \t&\t1.441 \\\\\n\t\t\t(-100, 100, 100)\t& 0\t\t& 0\t\t\t& -1418.541757 \t&\t1.261\n\t\t\\end{tabular}\n\t}\n\t\\caption{Results of experiment 6, $10.000$ reads using the quantum annealer for different parameters configurations.}\n\t\\label{tab:exp6_1}\n\\end{table}\n\nAs we can see in the table, we did not find a single valid cycle in these iterations. The energy delta naturally increases as we increase the parameter values: every single penalty is greater penalized. However, the energy delta barely increases until our parameters get a value of $10$. This could show how the responses for \\emph{parameters} $= (-5, 5, 5)$ incurred in a lower number of penalties. In figure \\ref{fig:exp6_1} we find the samples distribution for \\emph{parameters} $= (-5, 5, 5)$. The overall energy is much higher than what we saw for \\emph{parameters} $= (-1.6, 1.6, 1.6)$ in figure \\ref{fig:exp5_2}, which occurs due to the higher penalty. This experiment concludes that either we have not been able to find the correct values for the parameters, or the values of the parameters are not the problem.\n\n\\begin{figure}[H]\n\t\\includegraphics[scale=0.5]{experiments/exp6_1.png}\n\t\\centering\n\t\\caption{$10.000$ samples distribuition for \\emph{parameters} $= (-5, 5, 5)$.}\n\t\\label{fig:exp6_1}\n\\end{figure}\n\nFinally, we try changing the annealing schedule. There are two possible parameters that we may modify in this sense: the \\emph{annealing time} -time let for the annealer to converge-, or the \\emph{annealing schedule} -which modifies the annealing functions as defined in figure \\ref{fig:dwave-annealing-functions}. Since my initial hypothesis was that the annealer did not have enough time to find good solutions, let us focussed on the former for our last experiment.\n\nThe anneal time is meassured in microseconds, with a default value of $20$. Although the initial idea was to start with that value and make it progressively higher, at this point I was able to submit only one more worthy experiment, with a anneal time of $40$ microseconds. This was due to a bug in the D-Wave $get\\_solver()$ function, which did not read the annealing time correctly and led to some invalid experiments at the last minute. We can see the obtained results in table \\ref{tab:exp6_2}.\n\n\\begin{table}[H]\n\t\\centering\n\t\\makebox[\\textwidth][c]{\n\t\t\\begin{tabular}{ccccc}\n\t\t\t\\textbf{Annealing time ($\\mu$s)} & \\textbf{Valid cycles} & \\textbf{Times sol. reached} & \\textbf{Energy delta} & \\textbf{Sampling QPU time} \\\\\n\t\t\t\\hline\n\t\t\t20\t& 0\t\t& 0\t\t\t& -76.344431\t& 1.500 \\\\\n\t\t\t40\t& 0\t\t& 0\t\t\t& -57.944162\t& 1.573\n\t\t\\end{tabular}\n\t}\n\t\\caption{Results of experiment 6, $10.000$ reads using different annealing times.}\n\t\\label{tab:exp6_2}\n\\end{table}\n\nAlthough the energy delta is reduced, the improvement is marginal: we still find no valid cycles and the responses have a high penalty. Probably with even more annealing time we will obtain further refined results.\n", "meta": {"hexsha": "ff9146d597d2405916bb972fbbd4d427981a4ba5", "size": 44568, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/chapters/chapter3_GenomeAssembly.tex", "max_stars_repo_name": "Ocete/TFG", "max_stars_repo_head_hexsha": "baf0853276aef8f6fd6c5cccbe69ede7ca7987c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-05T22:40:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-05T22:40:37.000Z", "max_issues_repo_path": "thesis/chapters/chapter3_GenomeAssembly.tex", "max_issues_repo_name": "Ocete/TFG", "max_issues_repo_head_hexsha": "baf0853276aef8f6fd6c5cccbe69ede7ca7987c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis/chapters/chapter3_GenomeAssembly.tex", "max_forks_repo_name": "Ocete/TFG", "max_forks_repo_head_hexsha": "baf0853276aef8f6fd6c5cccbe69ede7ca7987c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-29T18:23:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-29T18:23:25.000Z", "avg_line_length": 70.7428571429, "max_line_length": 819, "alphanum_fraction": 0.7474645486, "num_tokens": 12611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.34226221457390893}}
{"text": "\\section{Preliminaries}\\label{sec:prelim}\n%\n{\\sc First Pass: assume fixed Godel T norm -- we can extend to other\n  tnorms and to distribution semantics later.  \n}\n\nThroughout this paper, we assume a general knowledge of logic\nprogramming terminology, including tabled resolution and the\nwell-founded semantics including both default and explicit negation as\nin \\cite{AlDP95}.  Here, we include notation and definitions that will\nbe used for our proof of the correctness of Plow.\n\nAn {\\em annotated atom} is an atom $A$ associated with an annotation\n$n$ that is either a variable or $0 \\leq n \\leq 1$, denoted $A:n$.\nFrom an annotated atom {\\em A:n}, an {\\em objective literal} $O$ is\nformed as either $O = A:n$, termed a positive objective literal with\n$sign(O) = pos$; or aa $O = \\ourneg A:n$, termed a negative objective\nliteral with $sign(O) = \\ourneg$, and the \\ourneg{} symbol denotes\n{\\em explicit negation}.  In either case the annotation, $n$, is\ndenoted as $ annotation(O)$, while the underlying atom, $A$, is\n$atom(A)$.\n%\nTwo objective literals $O_1$ and $O_2$ with the same underlying atom\nare {\\em homologs} if they have the same sign and {\\em conjugates}\notherwise.  An objective literal $A:n$ is ground if both $A$ and $n$\nare ground.\n%\n% = A:n$ and $O_2 = \\neg A:m$ are termed {\\em conjugates}.\n%denoted as $O_1 = conjugate(O_2)$ or $O_2 = conjugate(O_1)$; \n%Otherwise if $atom(O_1) = atom(O_2)$ $O_1$ and $O_2$ are termed {\\em\n%  homologs}.\n%\n%, denoted as $O_1 = homolog(O_2)$ or $O_2 = homolog(O_1)$.\nFrom an objective literal $O$ a default literal is formed as either a\npositive default literal $O$ or as a negative default literal $\\naf\nO$, where \\naf{} denotes {\\em default negation}.  A default literal is\nsometimes simply called a {\\em literal}.\n\\footnote{\nWhen convenient, an objective literal $A:1$ ($\\neg A:1$) is denoted\nsimply as $A$ ($\\neg A$).}\n\nA rule has the form\n\\[r = O \\mif{} L_1,\\ldots,L_n\\]\nwhere $O$ is an objective literal and $L_0,\\ldots,L_n$ are default\nliterals.\n\nA rule $R$ is ground if all literals in $R$ are ground; a program\n$\\cP$ is ground if all rules in $\\cP$ are ground.\n\n\n%An objective literal $O$ is undefined in $\\cI$ if $O \\neg \\hat{\\in}\n\n%\\subsection{Three-Valued Models for Annotated Atoms} \n\nOur attention is restricted to three-valued (partial) interpretations\nand models such as those extending the well-founded model.  Each such\ninterpretation $\\cI$ is represented as a pair of sets of ground\nobjective literals: ($\\cT$,$za\\cF$).\n\n%{\\sc TES: In the following, I dont yet feel confident about my $>$'s and my\n%$\\geq$'s.  ... conflicting truth values are mapped to U, but in the\n%edge case, I'd like true to outweigh false (as with $r$ below).}\n\n\\begin{definition} \\label{def:satisfiable}\nLet $P$ be a ground objective literal $O$ with\n% $atom(O) = A$ and \n$annotation(O) = n$, and $\\cI$ an interpretation.\n\n$O$ is true in $\\cI$ if\n\\begin{itemize}\n\\item $\\cT$ contains an $O_T$ such that $O_T$ is a homolog of\n  $O$ and $annotation(O_T) \\geq n$; and\n\\item $\\cT$ does not contain a conjugate $O_C$ of $O$ with\n  $annotation(O_C) \\geq (1-n)$; and\n\\item $\\cF$ does not contain a homolog $O_F$ of $O$ with\n  $annotation(O_F) \\geq (1-n)$.\n\\end{itemize}\n\n%----------------------------------------------------------------                \n$O$ is false in $\\cI$ if \n\\begin{itemize}\n\\item $\\cT$ does not contain a homolog $O_T$ of $O$ with\n  $annotation(O_T) \\geq (1-n)$; and either\n\\begin{itemize}  \n\\item $\\cF$ contains a homolog $O_F$ of $O$ with $annotation(O_F) \\geq\n  n$; or \n\\item $\\cT$ contains a conjugate $O_C$ of $O$ with $annotation(O_C) \\geq n$.\n%Either $A:n_1 \\in \\cF$ for $n_1 \\geq m$ or $\\ourneg A:n_2 \\in \\cT$ for\n%$m_2 \\geq m$; and\n\\end{itemize}\n\\end{itemize}\n$O$ is $\\ourU$ in $\\cI$ if it is neither true nor false in $\\cI$.\n\nA positive literal $O$ is true (false) in $\\cI$ if $O$ is true (false)\nin $\\cI$; a negative literal $naf O$ is true in $\\cI$ if $O$ is false\nin $\\cI$ and is false in $\\cL$ if $O$ is true in $\\cI$.  A literal is\n$\\ourU$ in $\\cI$ if it is neither true nore false in $\\cI$.\n\\end{definition}\n%----------------------------------------------------------------              \n\n%\\begin{definition} \\label{def:satisfiable}\n%A ground annotated atom $A:m$ is true in $\\cI$ if \n%\\begin{itemize}\n%\\item There exists an $A:n_1 \\in \\cT$ with $n_1\\geq m$, and \n%\\begin{itemize}\n%\\item $\\cT$ does not contain $\\ourneg A:n_2$ with $n_2 > (1-m)$ and\n%\\item   $\\cF$ does not contain $A:n_3$ with $n_3 > (1-m)$.\n%\\end{itemize}\n%\\end{itemize}\n%A ground annotated atom $A:m$ is false in $\\cI$ if \n%\\begin{itemize}\n%\\item Either $A:n_1 \\in \\cF$ for $n_1 \\geq m$ or $\\ourneg A:n_2 \\in \\cT$\n%  for $m_2 \\geq m$; and\n%\\item $\\cT$ does not contain $A:n_3$ for $n_3 \\geq (1-m)$.\n%\\end{itemize}\n%\\end{definition}\n\nNote that in the above definition the truth value \\ourU{} captures\nboth the traditional case where a literal is undefined, along with the\ncase where a literal is overdefined.\n\n\\begin{example} \n  Consider the interpretation $\\cI_1$ where\n\\begin{itemize}\n\\item  $\\cT = \\{p:0.7,q:0.5, r:0.6,\\ourneg r:0.5\\}$\n\\item $\\cF = \\{p:0.4, q:0.5\\}$.\n\\end{itemize}\n$p:0.6$ is true in $\\cI$ and $p:0.8$ false, but $p:0.7$ is \\ourU ;\n$q:0.5$ is \\ourU{} in $\\cI$. $r:0.4$ is true in $\\cI$ but $r:0.7$ is\nfalse; $r:n$ is \\ourU{} for $0.5 \\leq n \\leq 0.6$.\n\\end{example}\n\n%\\cT$ and $O \\neg \\hat{\\in} \\cF$.\n\n%----------------------------------------------------------------\n\n%----------------------------------------------------------------                 \n\\subsubsection{Well-Founded Model}\n\nMotivation: consider the program\n\\begin{verbatim}\np:0.8:- not p:0.8.\np:0.5.\nneg p:0.3.\n\\end{verbatim}\nWe want a model with p:0.5 as true, p:0.7 as false and p:0.6 as u.\nHowever, if the rule {\\tt p:0.8:- not p:0.8.} were removed, p:0.6\nwould be false.\n\n\\comment{\n%For two interpretations, $\\cI$ and $\\cJ$, $\\cI\n%\\subseteq \\cJ$ iff $true(\\cI) \\subseteq true(\\cJ)$ and $false(\\cI)\n%%\\subseteq false(\\cJ)$.  Alternatively, a three-value interpretation\n%can be represented as a set of literals.\n\nA program $P$ is {\\em safe} if each rule $r$ in $P$ is such that every\nvariable in $r$ occurs in a positive literal in the body of $r$.  \n\nSymbols within a term may be represented through {\\em positions} which\nare members of the set $\\Pi$.  A {\\em position\\/} in a term is either\nthe empty string $\\Lambda$ that reaches the root of the term, or the\nstring $\\pi.i$ that reaches the $i$th child of the term reached by\n$\\pi$, where $\\pi$ is a position and $i$ an integer.  For a term $t$\nwe denote the symbol at position $\\pi$ in $t$ by $t_\\pi$.  For\nexample, $p(a,f(X))_{2.1} = X$.  We assume that a program $P$ is\ndefined over a language $\\cL$, containing a finite set $\\functions$ of\npredicate and function symbols, and a countable set of variables from\nthe set ${\\cal V} \\cup \\posvar$.  Elements of the set $\\cal V$ are\nreferred to as {\\em program variables}.  Elements of the set\n$\\posvar$, called {\\em position variables}, are of the form $X_\\pi$,\nwhere $\\pi$ is a position.\n%\nThese variables are used when it is convenient to mark certain\npositions of interest in a term.  The Herbrand Universe of $\\cL$ is\ndenoted $\\cH_{\\cL}$, or as $\\cH_{P}$ if $\\cL$ consists of the\npredicate and function symbols in $P$; similarly the Herbrand Base is\ndenoted as $\\cB_{\\cL}$ or as $\\cB_P$.  Throughout the paper variant\nterms are considered to be equal.\n}\n\nOne of the most important formulations of stratification is that of\n{\\em dynamic} stratification \\cite{Przy89d}, which shows that a\nprogram has a 2-valued well-founded model iff it is dynamically\nstratified, so that it is the weakest notion of stratification\nconsistent with the well-founded semantics.  The original definition\nof dynamic stratification included neither explicit negation (neg) nor\nannotations; however the encapsulation of these features within the\ninterpretations of Definition~\\ref{def:satisfiable} allows the\ndefinitions in this section to be mostly unchanged from their original\nformulation.\n\n%\nAs presented in~\\cite{Przy89d}, dynamic stratification computes strata\nvia operators on interpretations of the form ($\\cT$,$\\cF$) where $\\cT$\nand $\\cF$ are subsets of $\\cH_P$.  Given a set $\\cS$ of ground\nobjective literals, a ground objective literal $A:m \\hat{\\in} \\cS$ if\n$A:n \\in \\cS$ with $n \\geq m$.\n\n%-----------------------------------------------------------------------\nDynamic stratification is based on a series of reduction of a program\nin the usual manner.\n\n\\begin{definition}[Reduction of $\\cP$ modulo $\\cI$] \\label{def:reduction}\n%                                                                                \nLet $\\cI$ be an interpretation and $\\cP$ a program, both over the same\nlangage $\\cL$.  By the {\\em reduction of $P$ modulo $\\cI$} we mean a\nnew program $\\frac{P}{\\cI}$ obtained from $P$ by performing the\nfollowing operations:\n\\begin{enumerate}\n\\item Remove from $\\cP$ all rules that contain a literal that is false\n  in $\\cI$.\n\\item Remove from all the remaining rules those literals that are true\n  in $\\cI$\n\\end{enumerate}\n\\end{definition}\n\nEach stratum is then based on the intepretation of the previous\nstratum if it exists commbined with a reduction.\n\n%-----------------------------------------------------------------------\n\\begin{definition} \\label{def:dyn-ops}\nFor a normal program $P$, sets $\\cT$ and $\\cF$ of ground atoms and a\n3-valued interpretation $I = (\\cT,\\cF)$ (sometimes called a pre-interpretation):\n\\begin{description} \\item[$True^P_I(\\cT) =$]\n    $\\{A|A$ is true in $I$; or there is a clause $B \\leftarrow\n  L_1,...,L_n$ in $P$, a grounding substitution $\\theta$ such that $A\n  = B\\theta$ and for every $1 \\leq i \\leq n$ either $L_i\\theta$ is\n  true in $I$, or $L_i\\theta \\hat{\\in} \\cT$\\};\n  \\item[$False^P_I(\\cF) =$] \n%$\\{A : val_I(A) \\neq {\\tt f}$ \n$\\{A|A$ is false in $I$; or for every clause $B \\leftarrow\n    L_1,...,L_n$ in $P$ and grounding substitution $\\theta$ such that\n    $A = B\\theta$ there is some $i$ $(1 \\leq i \\leq n)$ such that\n    $L_i\\theta$ is false in $I$ or $L_i\\theta \\hat{\\in} \\cF\\}$.\n\\end{description}\n\\end{definition}\n%------------------------------------------------------------------------()     \n%\n\\cite{Przy89d} shows that $True^P_I$ and $False^P_I$ are both\nmonotonic, and defines $\\kcaltrue^P_I$ as the least fixed point of $True^P_I(\\emptyset)$\nand $\\calfalse^P_I$ as the greatest fixed point of\n$False^P_I(\\cH_P)$.\n%\\footnote{Below, we will sometimes omit the program $P$ in\n%  these operators when the context is clear.}.\n%, along with an\n%operator $\\cal I$ that assigns to every interpretation $I$ of $P$ a\n%new interpretation ${\\cal I}(I) = I \\cup \\langle \\cT_I ; \\cF_I \\rangle$.\n%\nIn words, the operator $\\kcaltrue^P_I$ extends the interpretation $I$ to add\nthe new atomic facts that can be derived from $P$ knowing $I$; $\\calfalse^P_I$\nadds the new negations of atomic facts that can be shown false in $P$\nby knowing $I$ (via the uncovering of unfounded sets).  An iterated\nfixed point operator builds up dynamic strata by constructing\nsuccessive partial interpretations as follows.\n%----------------------------------------------------------------------          \n\\begin{definition}[Iterated Fixed Point and Dynamic Strata] \\label{def:wfm}\n\\label{def:IFP}\nFor a normal program $P$ let \n\n\\begin{center}\n$  \\begin{array}{rcl}\n          WFM_0 & = & \\langle \\emptyset ; \\emptyset \\rangle;      \\\\\n WFM_{\\alpha+1} & = &       WFM_{\\alpha} \\cup\n                                \\langle \\kcaltrue^P_{WFM_\\alpha};\\calfalse^P_{WFM_\\alpha} \\rangle; \\\\\n     WFM_\\alpha & = & \\bigcup_{\\beta < \\alpha} WFM_\\beta, \\mbox{ for limit ordinal }\\alpha.\n  \\end{array}\n$\n\\end{center}\n\n\\noindent\n  $WFM(P)$ denotes the fixed point interpretation $WFM_\\delta$,\n  where $\\delta$ is the smallest (countable) ordinal such that both\n  sets $\\kcaltrue^P_{WFM_\\delta}$ and $\\calfalse^P_{WFM_\\delta}$ are empty.\n%($\\delta$ exists, and is\n%  a countable ordinal because both $\\kcaltrue_I$ and $\\calfalse^P_I$ are monotonically\n%  increasing).  \n% We refer to $\\delta$ as the {\\em depth} of program $P$.  \nThe {\\em stratum} of atom $A$, is the least ordinal $\\beta$ such that\n   $A \\in WFM_{\\beta}$.\n% (where $A$ may be either in the true or false\n%   component of $WFM_{\\beta}$).\n\\end{definition}\n%------------------------------------------------------------------------()      \n%\n\\cite{Przy89d} shows that %the iterated fixed point \n$WFM(P)$ is in fact the well-founded model and that any undefined\natoms of the well-founded model do not belong to any stratum --\ni.e. they are not added to $WFM_{\\delta}$ for any ordinal\n$\\delta$. Thus, a program is \\emph{dynamically stratified} if every\natom belongs to at least one stratum.\n\nThis section has considered normal logic programs extended both with\nexplicit negation.  We note that if all atoms in a program $\\cP$ have\nthe annotation 1, Definition~\\ref{def:wfm} reduces to the definition\nof the Well0founded Semantics with Explicit Negation~\\cite{AlDP95},\nand if $\\cP$ also does not contain explicit negation, the definition\nreduces to the definition of Well-Founded Semantics in \\cite{Przy89d}.\n\n%------------------------------------------------------------------------\n% taking out fixed-order stuff until we put LPADs in (though maybe we\n% wont even need it then )\n\n%\\input{fixed-order-dynstrat}\n\n\n", "meta": {"hexsha": "a3002bce70d6bd0b0bea9329e1b516c11d3ab9a8", "size": 13315, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/paper/prelim.tex", "max_stars_repo_name": "theresasturn/plow", "max_stars_repo_head_hexsha": "0999214f33d71413ed9a029eb9dccbf4e6d35dbb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-03-26T21:41:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-03T22:22:06.000Z", "max_issues_repo_path": "docs/paper/prelim.tex", "max_issues_repo_name": "theresasturn/plow", "max_issues_repo_head_hexsha": "0999214f33d71413ed9a029eb9dccbf4e6d35dbb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/paper/prelim.tex", "max_forks_repo_name": "theresasturn/plow", "max_forks_repo_head_hexsha": "0999214f33d71413ed9a029eb9dccbf4e6d35dbb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-23T15:26:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-23T15:26:21.000Z", "avg_line_length": 43.5130718954, "max_line_length": 101, "alphanum_fraction": 0.6513706346, "num_tokens": 4099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.34226221457390893}}
{"text": "\\documentclass[12pt, a4paper]{article}\n\n\\include{preamble}\n\\usepackage{lipsum} % <---------- remove me\n\n\\title{My lovely paper}\n\\include{author_vincent}\n\\date{\\today}\n\n\\begin{document}\n\n\\maketitle\n\n\\begin{abstract}\nShort introduction to subject of the paper \\ldots\n\\end{abstract}\n\n\\section{Introduction}\nThis is a reference \\citep{Vincent:2015dh}\n\n\\lipsum[1-2] % <---------- remove me\n\n\\begin{equation}\n\\label{eq1}\n  y = mx+c\n\\end{equation}\n\n\\lipsum[2] % <---------- remove me\n\n\\begin{figure}[t!] \n\t\\centering\n\t\\includegraphics[]{bayes_net_general.pdf} \n\t\\caption{This is a caption}\n\t\\label{fig:first_figure}\n\\end{figure}\n\n\\lipsum[3-5] % <---------- remove me\n\n% REFERENCE SECTION\n\\clearpage\n\\bibliographystyle{apacite}\n\\bibliography{my_references}\n\n\\end{document}\n", "meta": {"hexsha": "508c93c90632a0f9edf2077bb792b4cd009dc5d8", "size": 765, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "latex templates/paper/paper.tex", "max_stars_repo_name": "drbenvincent/document_templates", "max_stars_repo_head_hexsha": "75b426d7a110026a48f2dc36a596258c64a66617", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "latex templates/paper/paper.tex", "max_issues_repo_name": "drbenvincent/document_templates", "max_issues_repo_head_hexsha": "75b426d7a110026a48f2dc36a596258c64a66617", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "latex templates/paper/paper.tex", "max_forks_repo_name": "drbenvincent/document_templates", "max_forks_repo_head_hexsha": "75b426d7a110026a48f2dc36a596258c64a66617", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.0, "max_line_length": 49, "alphanum_fraction": 0.6954248366, "num_tokens": 245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.34224234067864884}}
{"text": "\\chapter{Exponentials and Logarithms}\n\n\\section{Properties of the exponential function}\n\n\\section{Gradient of \\(e^{kx}\\)} % TODO: Typeset better\n\\section{Properties of the logarithm}\n\\section{Laws of logarithms}\n\\section{Equations involving exponentials}\n\\section{Reduction to linear form}\n\\section{Modelling using exponential functions}\n", "meta": {"hexsha": "fac99468ff3f597e226cc8012f7c584cd1a8d2ab", "size": 338, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "corpus/a-level-notes/math/content/pure/exp_log.tex", "max_stars_repo_name": "aDotInTheVoid/ltxmk", "max_stars_repo_head_hexsha": "ee461679e51e92a0e4b121f28ae5fe17d5e5319e", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "corpus/a-level-notes/math/content/pure/exp_log.tex", "max_issues_repo_name": "aDotInTheVoid/ltxmk", "max_issues_repo_head_hexsha": "ee461679e51e92a0e4b121f28ae5fe17d5e5319e", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "corpus/a-level-notes/math/content/pure/exp_log.tex", "max_forks_repo_name": "aDotInTheVoid/ltxmk", "max_forks_repo_head_hexsha": "ee461679e51e92a0e4b121f28ae5fe17d5e5319e", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7272727273, "max_line_length": 55, "alphanum_fraction": 0.798816568, "num_tokens": 84, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.34224233740639465}}
{"text": "%!TEX root = main.tex\n\nThis chapter describes the technical details of the implementation of signature-based partition refinement.\nIt contains a condensed version of several sections from~\\cite{DBLP:conf/tacas/DijkP16}.\n\n\n\\section{Decision diagram algorithms in Sylvan}\n\n\nIn {symbolic model checking}, sets of states and transitions are represented by their characteristic function, rather than stored individually.\nWith states described by $N$ Boolean variables,\na set $S\\subseteq \\mathbb{B}^N$ can be represented by its characteristic function $f\\colon \\mathbb{B}^N\\rightarrow \\mathbb{B}$, where $S=\\{s\\mid f(s)\\}$.\n%\n%\n%\nBinary decision diagrams (BDDs) are a concise and canonical representation of Boolean functions.\n\nAn (ordered) BDD is a directed acyclic graph with leaves $0$ and $1$. Each internal node has a variable label $x_i$ and two outgoing edges labeled $0$ and $1$. Variables are encountered along each path according to a fixed variable ordering. Duplicate nodes and nodes with two identical outgoing edges are forbidden.\n%\n%\\begin{definition}\n%An (ordered) BDD is a directed acyclic graph with the following properties:\n%\\begin{compactenum}\n%\\item There is a single root node and two terminal nodes 0 and 1.\n%\\item Each non-terminal node $p$ has a variable label $x_i$ and two outgoing edges, labeled 0 and 1; we write $\\text{lvl}(p)=i$ and use $p[0]$ and $p[1]$ for the children.\n%\\item For each edge from node $p$ to non-terminal node $q$, $\\text{lvl}(p)<\\text{lvl}(q)$.\n%%\\item There are no {duplicate} nodes, i.e.,\\\\$\\forall p\\forall q\\cdot(\\text{lvl}(p)=\\text{lvl}(q)\\wedge p[0]=q[0]\\wedge p[1]=q[1])\\rightarrow p=q$.\n%\\item There are no duplicate nodes $\\langle x_i,p[0],p[1]\\rangle$ (i.e., maximum sharing)\n%\\item There are no redundant nodes (nodes with $p[0]=p[1]$)\n%\\end{compactenum}\n%\\end{definition}\n%\n%\n%%\nIt is well known that for a fixed variable ordering, every Boolean function is represented by a unique BDD.\n\n\nIn addition to BDDs with leaves $0$ and $1$, multi-terminal binary decision diagrams have been proposed with leaves other than $0$ and $1$, representing functions from the Boolean space $\\mathbb{B}^N$ onto any finite set. For example, MTBDDs can have leaves representing integers (encoding $\\mathbb{B}^N\\rightarrow\\mathbb{N}$), floating-point numbers (encoding $\\mathbb{B}^N\\rightarrow\\mathbb{R}$) and rational numbers (encoding $\\mathbb{B}^N\\rightarrow\\mathbb{Q}$).\nPartial functions are supported using a terminal leaf $\\bot$.% (in practice we use the Boolean leaf $0$ for non-Boolean codomains).\n\n\n\nSylvan~\\cite{DBLP:conf/tacas/DijkP15} implements parallelized operations on decision diagrams using parallel data structures and work-stealing.\nWork-stealing is a load balancing method for task-based parallelism.\nRecursive operations, such as most BDD operations, implicitly form a tree of tasks.\nIndependent subtasks are stored in queues and idle processors steal tasks from the queues of busy processors.\n\n\n\\begin{algorithm}[t!]\n\\Def{\\Apply{$x$, $y$, $\\textsf{F}$}}{\n    \\lIf{$(x,y,\\textsf{F})\\in\\textsf{cache}$}{\n        \\Return{$\\textsf{cache}[(x,y,\\textsf{F})]$}\\tcc*[f]{get from cache}    \n    }\n    \\lIf{$x$ and $y$ are terminals}{\n        \\Return{$\\textsf{F}(x,y)$}\\tcc*[f]{apply operator \\textsf{F}}\n    }\n    $v$ = topVar($x$,$y$) \\;\n    low $\\leftarrow$ \\Apply{$x_{v=0}$, $y_{v=0}$, $\\textsf{F}$} \\tcc*[r]{execute in parallel}\n    high $\\leftarrow$ \\Apply{$x_{v=1}$, $y_{v=1}$, $\\textsf{F}$} \\;\n    result $\\leftarrow$ \\BDDnode{$v$, low, high} \\tcc*[r]{compute result}\n    $\\textsf{cache}[(x,y,\\textsf{F})]$ $\\leftarrow$ result \\tcc*[r]{put in cache}\n    \\Return{result}\n}\n\\caption{Generic algorithm that applies a binary operator \\textsf{F} to BDDs $x$ and $y$.}\n\\label{alg:generic}\n\\end{algorithm}\n\n\n\nAlgorithm~\\ref{alg:generic} describes the implementation of a generic binary operation $\\textsf{F}$.\n%\n%\n%\nBDD operations mainly consist of consulting an operation cache, performing some recursive step, and creating new BDD nodes using a unique table.\nThe operation cache is required to reduce the time complexity of BDD operations from exponential to polynomial in the size of the BDDs.\nSylvan uses a single shared unique table for all BDD nodes and a single shared operation cache for all operations.\nTo obtain high performance in a multi-core environment, the datastructures for the BDD nodes and the operation cache must be highly scalable.\nSylvan implements several non-blocking datastructures to enable good speedups.\n\n\n\nTo compute symbolic signature-based partition refinement, several basic operations must be supported by the BDD package (see also \\cite{DBLP:conf/atva/WimmerHHSB06}).\n%\n%\n%\nSylvan implements basic operations such as $\\wedge$ and \\texttt{if-then-else}, and existential quantification $\\exists$.\nNegation $\\neg$ is performed in constant time using complement edges.\nTo compute relational products of transition systems, there are operations \\texttt{relnext} (to compute successors) and \\texttt{relprev} (to compute predecessors and to concatenate relations), which combine the relational product with variable renaming.\nThe operation \\texttt{and\\_exists} computes the traditional relational product without variable renaming.\nSimilar operations are also implemented for MTBDDs.\n%\n%\n%\nSylvan is designed to support custom BDD algorithms.\nWe present two custom algorithms below.\n%We also use custom extensions of traditional BDD algorithms to avoid variable renaming.\n\n\n\n\\section{Encoding of signature refinement}\n\nWe implement symbolic signature refinement similar to~\\cite{DBLP:conf/atva/WimmerHHSB06}.\n%\n%\nUnlike~\\cite{DBLP:conf/atva/WimmerHHSB06}, we do not refine the partition with respect to a single block, but with respect to all blocks simultaneously.\n% like in~\\cite{DBLP:journals/entcs/BlomO03,DBLP:conf/qest/Derisavi07}.\n%\n%\n%\nWe use a binary encoding with variables $s$ for the current state, $s'$ for the next state, $a$ for the action labels and $b$ for the blocks.\nWe order BDD variables $a$ and $b$ after $s$ and $s'$, since this is required\nto efficiently replace signatures $(a,b)$ by new block numbers $b$ (see below).\nVariables $s$ and $s'$ are interleaved, which is common in the context of transition systems.\n\n\n\n\\begin{figure}[tp]\n\\begin{center}\n\\scalebox{0.9}{\n\\begin{tikzpicture}\n\\coordinate (a) at (250:2);\n\\coordinate (b) at (290:2);\n\\coordinate (c) at (250:3);\n\\coordinate (d) at (290:3);\n\\draw (0,0) -- (c);\n\\draw (0,0) -- (d);\n\\draw (a) -- (b);\n\\draw (c) -- (d);\n\\draw (0,-1.5) node {$s,s'$};\n\\draw (0,-2.35) node {$a$};\n\\draw (0,-4.5) node {BDD $\\mathcal{T}(s,s',a)$};\n\n\\coordinate (a0) at (3,0);\n\\coordinate (aa) at ($(a0) + (250:2)$);\n\\coordinate (ab) at ($(a0) + (290:2)$);\n\\coordinate (ac) at ($(a0) + (250:3)$);\n\\coordinate (ad) at ($(a0) + (290:3)$);\n\\coordinate (ae) at ($(a0) + (250:4)$);\n\\coordinate (af) at ($(a0) + (290:4)$);\n\\draw (a0) -- (ae);\n\\draw (a0) -- (af);\n\\draw (aa) -- (ab);\n%\\draw (ac) -- (ae);\n\\%draw (ad) -- (af);\n\\draw (ac) -- (ad);\n\\draw (ae) -- (af);\n\\draw (3,-1.5) node {$s$};\n\\draw (3,-2.35) node {$a$};\n\\draw (3,-3.25) node {$b$};\n\\draw (3,-4.5) node {BDD $\\sigma_T(s,a,b)$};\n\n\\coordinate (b0) at (6.5,0);\n\\coordinate (ba) at ($(b0) + (250:2)$);\n\\coordinate (bb) at ($(b0) + (290:2)$);\n\\coordinate (bc) at ($(b0) + (250:3)$);\n\\coordinate (bd) at ($(b0) + (290:3)$);\n\\coordinate (be) at ($(b0) + (250:4)$);\n\\coordinate (bf) at ($(b0) + (290:4)$);\n\\draw (b0) -- (ba);\n\\draw (b0) -- (bb);\n\\draw (ba) -- (bb);\n\\draw (bc) -- (be);\n\\draw (bd) -- (bf);\n\\draw (bc) -- (bd);\n\\draw (be) -- (bf);\n\\draw ($(b0) + (0,-1.5)$) node {$s$};\n\\draw ($(b0) + (0,-3.25)$) node {$b$};\n\\draw ($(b0) + (0,-4.5)$) node {MTBDD $\\sigma_R(s,b)$};\n\n\\coordinate (c0) at (-3,0);\n\\coordinate (ca) at ($(c0) + (250:2)$);\n\\coordinate (cb) at ($(c0) + (290:2)$);\n\\coordinate (cc) at ($(c0) + (250:3)$);\n\\coordinate (cd) at ($(c0) + (290:3)$);\n\\coordinate (ce) at ($(c0) + (250:4)$);\n\\coordinate (cf) at ($(c0) + (290:4)$);\n\\draw (c0) -- (ca);\n\\draw (c0) -- (cb);\n\\draw (ca) -- (cb);\n\\draw (cc) -- (ce);\n\\draw (cd) -- (cf);\n\\draw (cc) -- (cd);\n\\draw (ce) -- (cf);\n\\draw ($(c0) + (0,-1.5)$) node {$s$};\n\\draw ($(c0) + (0,-3.25)$) node {$b$};\n\\draw ($(c0) + (0,-4.5)$) node {BDD $\\mathcal{P}(s,b)$};\n\\end{tikzpicture}\n}\n\\end{center}\n\\caption{Schematic overview of the BDDs in signature refinement}\n\\label{fig:bdds}\n\\end{figure}\n\n\n\nTo perform symbolic bisimulation we represent a number of sets by their characteristic functions. See also Figure~\\ref{fig:bdds}.\n\\begin{itemize}\n\\item A set of states is represented by a BDD $\\mathcal{S}(s)$;\n% with $\\mathcal{S}(s)=1\\Leftrightarrow s\\in S$\n\\item Transitions are represented by a BDD $\\mathcal{T}(s,s',a)$;\n\\item Markovian transitions are represented by an MTBDD $\\mathcal{R}(s,s')$, with leaves containing rational numbers ($\\mathbb{Q}$);\n\\item Signatures $\\textbf{T}$ and $\\textbf{B}$ are represented by a BDD $\\sigma_T(s,a,b)$;\n\\item Signatures $\\textbf{R}^s$ and $\\textbf{R}^b$ are represented by an MTBDD $\\sigma_R(s,b)$.\n\\end{itemize}\n\n\n\n\nIn the literature,\n%~\\cite{DBLP:conf/cav/BoualiS92,DBLP:conf/tacas/Derisavi07,DBLP:conf/qest/Derisavi07,DBLP:conf/atva/WimmerHHSB06}, \nthree methods have been proposed to represent $\\pi$.\n%\n%\n%\n\\begin{enumerate}\n\\item As an equivalence relation, using a BDD $\\mathcal{E}(s,s')=1$ iff $s\\equiv_{\\pi} s'$.\n\\item As a partition, by assigning each block a unique number, encoded with variables $b$, using a BDD $\\mathcal{P}(s,b)=1$ iff $s\\in C_b$.\n\\item Using $k=\\ceil{\\log_2 n}$ BDDs $\\mathcal{P}_{0},\\dotsc,\\mathcal{P}_{k-1}$ such that $\\mathcal{P}_i(s)=1$ iff $s\\in C_b$ and the $i^\\text{th}$ bit of $b$ is 1. This requires significant time to restore blocks for the refinement procedure, but can require less memory.\n\\end{enumerate}\n\n%We use variables $t$ and $b$ instead of $s$ and $b$ in $\\mathcal{P}$ to avoid creating a custom BDD operation for computing $\\exists t\\colon \\mathcal{T}(s,t,a) \\wedge \\mathcal{P}(t,b)$.\n%Also, \\cite{DBLP:conf/atva/WimmerHHSB06} often requires renaming operations to get $\\mathcal{P}(t,b)$ from $\\mathcal{P}(s,b)$, which is unnecessary and expensive.\n\n%Furthermore, the encoding of block numbers is such that the the lowest significant bit comes first...\n\n%We represent the partition by the assignment to a block number.\n%An alternative method to represent the partition, used by \\cite{DBLP:conf/cav/BoualiS92} and \\cite{DBLP:journals/ijfcs/MummeC13}, stores the equivalence relation in a BDD $\\mathcal{R}(s,t)$.\nWe choose to use method 2, since in practice the BDD of $\\mathcal{P}(s,b)$ is smaller than the BDD of $\\mathcal{E}(s,s')$.\nUsing $\\mathcal{P}(s,b)$ also has the advantage of straight-forward signature computation.\n%In cases where only few blocks contain multiple states, $\\mathcal{P}(s,b)$ blows up to a large tree, assigning each state to a different block.\n%In such cases, the BDD for $\\mathcal{E}(s,t)$ would be much smaller, since less states are equivalent.\n%\n%\nThe logarithmic representation is incompatible with our approach, since we refine all blocks simultaneously. Their approach involves restoring individual blocks to the $\\mathcal{P}(s,b)$ representation, performing a refinement step, and compacting the result to the logarithmic representation. Restoring all blocks simply computes the full $\\mathcal{P}(s,b)$.\n\nWe represent Markovian transitions using rational numbers, since they offer better precision than floating-point numbers.\nThe manipulation of floating-point numbers typically introduces tiny rounding errors, resulting in different results of similar computations.\nThis significantly affects bisimulation reduction, often resulting in finer partitions than the maximal bisimulation~\\cite{DBLP:conf/mmb/WimmerB10}.\n\n\n\\section{The \\texttt{refine} algorithm}\n\\label{sec:refine}\n\\input{refine}\n\n\\section{Computing inert transitions}\n\\label{sec:inert}\n\\input{inert}\n", "meta": {"hexsha": "3ba78608c09d4a40518debb87f0d2e937e995091", "size": 11840, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/implementation.tex", "max_stars_repo_name": "alaarman/sigrefmc", "max_stars_repo_head_hexsha": "5afc0cc5d7f45260f71279289f2c1db67bfb04e1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/implementation.tex", "max_issues_repo_name": "alaarman/sigrefmc", "max_issues_repo_head_hexsha": "5afc0cc5d7f45260f71279289f2c1db67bfb04e1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-20T13:11:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-20T13:11:59.000Z", "max_forks_repo_path": "doc/implementation.tex", "max_forks_repo_name": "alaarman/sigrefmc", "max_forks_repo_head_hexsha": "5afc0cc5d7f45260f71279289f2c1db67bfb04e1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-16T08:45:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-16T08:45:51.000Z", "avg_line_length": 47.9352226721, "max_line_length": 466, "alphanum_fraction": 0.7024493243, "num_tokens": 3580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.5039061705290806, "lm_q1q2_score": 0.3422423308618862}}
{"text": "\\documentclass[12pt]{beamer}\n\n\\usepackage{tikz}\n\\usepackage{graphicx}\n\\usepackage[T1]{fontenc}\n\\usepackage{amsmath}\n\\usepackage{multicol}\n\\usepackage{booktabs, braket} % For formal tables\n\\usepackage{cleveref}\n\\usepackage{graphicx}\n\\usepackage{blkarray}\n\\usetikzlibrary{graphs, graphs.standard}\n\n\\DeclareMathOperator{\\E}{\\textrm{E}}\t\t     % expected value\n\\DeclareMathOperator{\\pr}{\\mathrm{P}}\t\t     % probability \n\\DeclareMathOperator{\\cov}{t_{cov}}\t             % cover time\n\n\\DeclareMathOperator{\\X}{\\mathbb{X}}\t\t     % expected value\n\\DeclareMathOperator{\\tr}{\\text{tr}}\t\t     % trace\n\\DeclareMathOperator{\\Ap}{$A$ ^\\prime} \t\t     % A'\n\\DeclareMathOperator{\\bp}{$b$ ^\\prime} \t\t     % b'\n\\DeclareMathOperator{\\Xb}{\\mathcal{X}}\t\t     % big X\n\n\\title{Semidefinite Programming and Quantum Algorithms}\n\\author{Michael Czekanski \\& R. Teal Witter}\n\\institute{Middlebury College}\n\\date{November 5, 2019}\n\n\\begin{document}\n\\graphicspath{{./../figures/}}\n\n\\frame{\\titlepage}\n\n\\begin{frame}{Overview}\n\\tableofcontents\n\\end{frame}\n\n\\section{Query Complexity}\n\\begin{frame}{Query Complexity}\n\\begin{center}\nThe number of times an algorithm queries the input.\n\\end{center}\n\\begin{table}[]\n\\begin{tabular}{cc}\n\\hline\n\\textbf{Input} & \\textbf{Output} \\\\ \\hline\n00             & 0               \\\\\n01             & 1               \\\\\n10             & 1               \\\\\n11             & 1               \\\\ \\hline\n\\end{tabular}\n\\end{table}\n\\end{frame}\n\n\\section{Semidefinite Programming}\n\n\\begin{frame}{Quantum Query Complexity as SDP: Reichardt \\cite{reichardt2009span}}\n\\begin{align} \\label{eq:reichardtObj} \n    f_{\\text{bound}} = \\min_{\\X} M(\\X) = \\max_{y \\in D} \\sum_{j \\in [n]}\n    \\bra{y,j}\\X\\ket{y,j} \n\\end{align}\nSubject to\n\\begin{align}\\label{Eq:reichardtSemi}\n    \\X \\succcurlyeq 0 \n\\end{align}\n\\begin{align}\\label{Eq:reichardtOffDiag}\n    \\forall (y,z) \\in F \\sum_{j \\in [n]: y_j \\ne z_j} \n    \\bra{y,j} \\X \\ket{z, j} = 1.\n\\end{align}\n\\end{frame}\n\n\\begin{frame}{A Standard Form: Boyd\\cite{boyd2004convex}}\nMinimize\n\\begin{align}\\label{Eq:boyd_obj}\n    M(\\X) = \\tr(C\\X) \n\\end{align}\nSubject to\n\\begin{align} \\label{Eq:boydSemi}\n    \\X \\succcurlyeq 0   \n\\end{align}\n\n\\begin{align} \\label{Eq:boydTraceCon}\n    \\tr(A_i \\X) = b_i  \\text{$\\qquad$ for $i \\in \\{1,...,p\\}$}\n\\end{align}\n\\end{frame}\n\n\\section{Alternating Direction Methods}\n\\begin{frame}{We use ADM \\cite{adm}}\n\\centering\n\\includegraphics[scale=.15]{figures/adm_algorithm}\n\\bigskip\n\\begin{itemize}\n    \\item Easy to implement\n    \\item Exploits sparsity (yay zeroes!)\n    \\item Exploits constraint orthogonality\n\\end{itemize}\n\\end{frame}\n\n\\section{Our Work}\n\\begin{frame}{Numerial Results: Our Algorithm is Good.}\n\\centering\n\\includegraphics[scale=.5]{figure_all_or_complexity.eps}\n\\end{frame}\n\n\\begin{frame}{Run Time Results: Our Algorithm is Bad.}\n\\centering\n\\includegraphics[scale=.5]{figure_all_or_time.eps}\n\\end{frame}\n\n\\begin{frame}{We Have Plans (For the Future)}\n\\begin{itemize}\n    \\item Document\n    \\item More optimization\n    \\item Span program\n\\end{itemize} \n\\end{frame}\n\n\\begin{frame}{Thank you!}\n\\bibliographystyle{abbrv}\n\\bibliography{main}\n\\end{frame}\n\n\\end{document}", "meta": {"hexsha": "7bf1f3e834bd4cf933db7072182a37df636a99ce", "size": 3140, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/sneakpeek.tex", "max_stars_repo_name": "rtealwitter/QuantumQueryOptimizer", "max_stars_repo_head_hexsha": "64f68110ab088c271fad96976f2fa06af88d5a2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paper/sneakpeek.tex", "max_issues_repo_name": "rtealwitter/QuantumQueryOptimizer", "max_issues_repo_head_hexsha": "64f68110ab088c271fad96976f2fa06af88d5a2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/sneakpeek.tex", "max_forks_repo_name": "rtealwitter/QuantumQueryOptimizer", "max_forks_repo_head_hexsha": "64f68110ab088c271fad96976f2fa06af88d5a2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5284552846, "max_line_length": 82, "alphanum_fraction": 0.6732484076, "num_tokens": 1055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3422423308618861}}
{"text": "% Add a bit of space between paragraphs (copied from Karl Broman)\n\\setlength{\\parskip}{0.5\\baselineskip}\n\n% Add abstract (copied from Karl Broman)\n\\begin{quote}\n\\small\n\\articleABSTRACT\n\\end{quote}\n\n\\section{Introduction}\n\n\\subsection{Historical context}\n\n%Summarize the scientific question that your code was written to explore.\nThis paper aims to computationally reproduce my own statistical analysis from 16~years ago as part of the 10-year reproducibility challenge \\supercite{Hinsen2019}. The analysis examined seasonal patterns in coronary heart disease in multiple countries \\supercite{Barnett2004}. In most countries coronary heart disease deaths and emergency admissions to hospital have a strong seasonal pattern with a peak in winter and nadir in summer \\supercite{Stewart2017}. There is an interesting variability between-countries in the size and timing of the winter peak. A better understanding of the differences between countries could help our understanding of the underlying causes of the winter peak in disease.\n\nThe analysis examined monthly time series of coronary  events (fatal and non-fatal) from 35~locations in 21~countries. The time series were 8 to 14 years in length and the earliest year of data was 1980. The analysis aimed to split the time series into a long-term trend, seasonal pattern(s) and remaining noise. There were two approaches, one that used a two-stage approach by first removing the trend, and another that estimated the trend and season together. The trend was estimated using the Kalman filter and the seasonal patterns were estimated using sinusoids. The estimates were made using Markov chain Monte Carlo. \n\n%Describe the computational context: Which hardware was used to run the code? Which software infrastructure? Which constraints existed on software development? Which technical choices (language, libraries, ...) were made? Were reproducibility and/or re-usability important criteria?\n\n\\subsection{Original source code}\n\nThe original code was written in SAS (version~8.00 for Windows) and chain convergence was checked using the ``coda'' package (version unknown) in R \\supercite{coda}. The code was based on Matlab code that I wrote during my PhD \\supercite{Barnett2003} at The University of Queensland. I converted the code to SAS because I did not have access to Matlab after finishing my PhD and I hoped that more people would be able to re-use my SAS code to apply to their own time series data. \n%It was not common practice at the time to share code and data in order to allow others to reproduce results. \nThe SAS code was first published in November 2004 with an update in August 2006, but I did not record what changes were made. \nThe paper states the code was published in September 2002 but this is likely a typo in the year given that the paper was not submitted until January 2004. \n\n%About the original source code: Was it published? Was it archived somewhere? Was there a license for it?\nThe original code was published in an online appendix to the paper that was separate from the journal in November 2004 at this address: \\url{http://www4.ktl.fi/publications/monica/chd_seasonal/appendix.htm}. However, the site has since moved to: \\url{https://www.thl.fi/publications/monica/chd_seasonal/appendix.htm} (accessed 25 January 2020). The web site was created by the WHO MONICA Project specifically for appendices to papers that used the MONICA data. MONICA stands for monitoring trends and determinants in cardiovascular disease. The MONICA Project was a large multi-country study that aimed to examine several aspects of coronary heart disease \\supercite{Tunstall2003}. It was a well-managed project that had staff who assisted with access to the data and helped add my code to the web.  \n\n%Please provide only information you are certain about. It's OK to forget technical details after many years.\n\n\\section{Results}\n\n%Retrieval of the software\n%Was it easy to find a copy of your source code?\n%Was it easy to locate and setup the dependencies?\n%Provide a list of all dependencies (libraries but also tools such as compilers).\n\n\\subsection{Retrieval of the software}\n\nMost of my SAS code was easy to find, both on the web and on an old compact disc in a desk draw. I made this compact disc of my files when I moved jobs. I did not keep the data because I was more interested in other people using my code for their own data rather than replicating our published results. I believe that another reason for deleting the data was to save space, as the files were relatively large by the standards of the day (around 31,000~kilobytes for data in text format and 70,000~kilobytes for data in SAS format). Luckily the original data files were available in text files in fixed-width format on a compact disc attached to the MONICA monograph published in 2003 \\supercite{Tunstall2003}.\n\nMy SAS code contained the macros needed to run the two statistical analyses. There was also SAS code to simulate a seasonal time series as an example data set. I found SAS code to read the MONICA data on my compact disc, but not on the web. I could not find the SAS code that applied the two methods to each location.\n\n%Execution\n%Describe what you did in order to run the software today.\n%Did you succeed in running the software in a modern computational environment? Or did you have to search for old versions of tools and libraries?\n%Describe the computational environment of the reproduction: hardware, operating system, compiler versions etc.\n%Did you have to modify the software in order to make it run today?\n%Were the original instructions that came with the software sufficient, or did you have to modify or extend them?\n\n\\subsection{Replication execution}\n\nI used SAS version~9.4 for Windows (Microsoft Windows~10) to replicate the results; there was no need to use an earlier version of SAS. \n\nMy SAS files had relatively good instructions with a detailed header at the top of every file and comments throughout. However, some files had been adapted from the original analysis to secondary analyses, making the code a palimpsest with some commands commented out with notes such as, ``changed for weather analysis'' and ``sensitivity analysis of Ghent''. The correct data set was also ambiguous because alternative data sets had also been used (e.g., fatal vs non-fatal events).  In hindsight I should have kept the exact data and syntax files needed to re-create the published results.\n%Mix of SAS files from different projects in the same folder.\n\nThe macros to run the analyses mainly needed only cosmetic edits, and I also put each macro in its own file rather than one overall file of macros. I also moved part of one macro, that estimated the standard deviation of the noise, into the macro that tested the periodogram for remaining seasonal structure. The largest change was having to re-write the files that applied the macros to the MONICA data. My SAS programming was rusty and I could not automate the process for each centre, so instead I created a new file for each analysis in each of three centres.\n\nI did not repeat my analysis in all 35 locations, but instead did the three locations in the first figure as this felt sufficient to test the code.\n\nThe code to estimate the trend without the seasonal pattern used a slightly different parameterisation with ``tau'' as a ratio rather than an absolute value. ``tau'' controls the amount of change over time in the trend, with smaller values creating more linear trends. I cannot be sure that this version was the same code as the original.\n\n\\subsection{Closeness of the replicated results to the original}\n\n%How close were the results you got to the originally published ones? Include the replicated data table and figure, as we do in other ReScience articles.\nThe original figure is shown in Figure~\\ref{fig:original} and my replication in Figure~\\ref{fig}. The figures show the estimates of the trend and season for three locations.\nThe results are similar except for the confidence intervals for the trend for the two-stage method, which are much narrower for the replication, but are centred on a similar mean.\nThis may be because I could not be certain that I had found the original code to perform the Kalman filter smoothing because of the difference in how ``tau'' was parameterised. \nI also needed some trial-and-error to select ``tau'' which controls the smoothness of the trend and is defined by the user rather than being estimated by an algorithm.\n%However, the estimates do look remarkably similar to my replicated estimates of the trend using the combined method. Hence another possibility is that the original figures were mislabeled as being from the two-stage method when in fact they came from the combined method.\n\n\\begin{figure}[!h]\n    \\centerline{\\includegraphics[scale=0.9]{figures/original_figure.eps}}\n\n\\caption{Original results for three locations using the two-stage method (left and centre column) and combined method (right column). The left column shows the observed data, estimated trend and 95\\% confidence interval. The middle column shows the periodogram of the de-trended data and limit for the test of seasonal structure (dotted line). The right column shows the observed data, estimated trend, and estimated annual seasonal pattern.}\n\t\\label{fig:original}\n\\end{figure}\n\n\\begin{figure}[!h]\n\\centerline{Perth, Australia}\n\t\\centerline{\n    \\includegraphics[scale=0.2]{figures/trend_twostage_perth.eps}\n    \\includegraphics[scale=0.2]{figures/periodogram_twostage_perth.eps}\n    \\includegraphics[scale=0.2]{figures/estimates_combined_perth.eps}\n    }\n\n\\centerline{Belfast, UK}\n    \\centerline{\n    \\includegraphics[scale=0.2]{figures/trend_twostage_belfast.eps}\n    \\includegraphics[scale=0.2]{figures/periodogram_twostage_belfast.eps}\n    \\includegraphics[scale=0.2]{figures/estimates_combined_belfast.eps}\n    }\n\n\\centerline{Warsaw, Poland}\n    \\centerline{\n    \\includegraphics[scale=0.2]{figures/trend_twostage_warsaw.eps}\n    \\includegraphics[scale=0.2]{figures/periodogram_twostage_warsaw.eps}\n    \\includegraphics[scale=0.2]{figures/estimates_combined_warsaw.eps}\n    }\n\n\\caption{Replicated results for Figure~\\ref{fig:original}}\n\t\\label{fig}\n\\end{figure}\n\nThe estimates of the seasonal patterns for the three locations are replicated in Table~\\ref{tab:season} which also shows the original results. The results are similar for the two-stage method, with most differences being within $\\pm$~0.1. The biggest difference being for the estimate of the noise standard deviation in Belfast (9.0 versus 8.8).\n\n\\begin{table}[!h]\n  \\centering\n  \\begin{tabular}{rccc}\\hline\n & Frequency,  & Amplitude,  &  Noise \\\\ \nLocation & months & rate per 100,000 &  SD \\\\ \\hline\n\\multicolumn{4}{c}{Two-stage method} \\\\ \\hline\nPerth, Australia & 2.3 & 2.0 (2.0) & 4.3 (4.2)\\\\\n & 12 & 2.6 (2.6) \\\\\nBelfast, UK & 12 & 7.0 (7.0) & 8.7 (8.7) \\\\ \nWarsaw, Poland & 3.4 & 3.3 (3.3) & 7.5 (7.5)\\\\\n               & 6  & 3.6 (3.6)\\\\ \n               & 12 & 3.2 (3.2)\\\\\n\\hline\n\\multicolumn{4}{c}{Combined method}  \\\\ \\hline\nPerth, Australia & 2.3 & 1.0 (1.0) & 3.9 (3.9)\\\\\n & 2.7 & ---- (0.8) \\\\\n & 3.8 & 1.3 (1.3)\\\\\n & 5.5 & 1.5 (1.4)\\\\\n & 12 & 2.7 (2.7)\\\\\nBelfast, UK & 2.8 & ---- (1.6) & 9.0 (8.8) \\\\\n            & 12 & 7.1 (7.0) &  \\\\ \nWarsaw, Poland & 3.4 & 3.4 (3.4) & 7.9 (7.8)\\\\\n               & 6  & 3.7 (3.7)\\\\ \n               & 12 & 3.3 (3.3)\\\\\n\\hline\n\\end{tabular}\n \\caption{Estimates of seasonal patterns using the two-stage and combined methods for three locations. The original results are in brackets. Each row in the table corresponds to a seasonal frequency at a location. SD = standard deviation.}\n  \\label{tab:season}  \n\\end{table}\n\nThere were differences in the frequencies for the combined method, as two seasonal frequencies were not included in the new results, one in Perth and one in Belfast. Although the amplitudes were relatively small (1.6 or less), hence these are smaller seasonal patterns that are marginally important.\n\nThe difference in seasonal frequencies could be because of a key ambiguity in the original paper regarding the decision to add additional seasonal components for the combined approach. After fitting a candidate model, the residuals were tested to look for additional seasonal structure. If structure existed, then the model was modified to add an additional seasonal component as necessary, followed by another test of the residuals. The code produced both the periodogram and the spectrum, which is a smoothed version of the periodogram. The periodogram tended to flag significant seasonal patterns when the spectrum did not, and I used the spectrum to make the decisions because some of the statistically significant patterns found by the periodogram were only just above the 0.05 threshold used to judge statistical significance. This part of the replication was therefore somewhat subjective.\n\nSome of the discrepancy in results in Table~\\ref{tab:season} could be because the estimates are made using Markov chain Monte Carlo which uses random steps to make estimates. Hence the estimates will depend on the original random number seed. However, I used 5,000 estimates with a burn-in of 500, so these differences should be minor and may explain some of the small differences in the first decimal place for the amplitude and noise estimates. This potential discrepancy would have been avoided if the original code had specified the random number seed.\n\n%If you had to make any modifications to the software or to the instructions that were supplied with it, try to describe which competence another researcher would need in order to do the same work. Would a general familiarity with your programming language and environment have been sufficient?\n\nOverall the replication took about 21~hours. This was mostly the fiddly task of working out which macros to run and re-creating the figures and tables. Given the amount of code that had to be re-created, I think that only someone  familiar with SAS would have been able to replicate the results. My familiarity with the MONICA Project also helped me create the new code, hence I am not certain that an outsider could have replicated the results, perhaps only by trial-and-error.\n\n%Software\n%If the licenses applying to the original software allow, please make your old software available as a repository on GitHub or an equivalent site. In the best case scenario, in which the old code is publishable, here is the procedure:\n\n%Add your old software as a single commit (ideally the initial one) of a new source repository.\n%Edit the code as necessary to reproduce the results in today's computational environment, committing the changes in logical units in the process. Include the additional tools (scripts, makefiles, ...) that you wrote for re-running your software and the additional instructions.\n%Make sure your repository contains a license.\n%Finally, submit your repository to Software Heritage for archiving.\n\n\\section{Discussion}\n\n%In addition to the content covered below, we are interested in the insight resulting from the reproducibility experience in relation to the choice of technology, and in your opinion on the original source code (clarity, documentation, etc).\n\nIt was an interesting exercise to bring this old code back to life. It would have been easier and faster if my original code had been properly arranged and prepared solely to repeat the original analyses. However, I was not aware of guidelines for curating code back in 2004. My original code had many comments which were useful, but there were problems with the overall file structure and how the files related to one another. There were also ambiguities with the dates of the code, and the changes I made after posting the original files. This is now solved by sites that track and date-stamp all changes, such as \\textit{GitHub}.\n\nMy main reason for sharing the original code was so that others could adapt it to their own data. However, of the 21 papers that cited the original paper which I could access, none of them stated that they re-used my SAS code. \n%I was not focused on the nitty-gritty of reproducing the original results and my code was in bad shape to do this.\n\n% One instead cited the available R code to run the same analysis.\n% Not confident it was exactly the same, but broadly similar.\n\nOverall the replication was broadly successful in terms of re-creating the key figure and estimates for three locations. There was subjectivity in modelling decisions concerning the smoothness of the trend and number of seasonal components, which made perfect replication difficult.\n\n%The ``combined'' model in the SAS files are available in the ``season'' package in R \\supercite{season} using the ``nscosinor`` command.", "meta": {"hexsha": "6bc0268153a4a4def74ee0cc538970318295cd3f", "size": 16753, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "article/content.tex", "max_stars_repo_name": "khinsen/tenyears", "max_stars_repo_head_hexsha": "c6b4da5f298888c5f0f488ad0231713f1d11204b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "article/content.tex", "max_issues_repo_name": "khinsen/tenyears", "max_issues_repo_head_hexsha": "c6b4da5f298888c5f0f488ad0231713f1d11204b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "article/content.tex", "max_forks_repo_name": "khinsen/tenyears", "max_forks_repo_head_hexsha": "c6b4da5f298888c5f0f488ad0231713f1d11204b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-25T16:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-25T16:47:52.000Z", "avg_line_length": 97.4011627907, "max_line_length": 896, "alphanum_fraction": 0.782427028, "num_tokens": 3848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.34221842238529343}}
{"text": "\\chapter{Machine Learning and Random Forests}\n\\label{ch:ML}\n%\nThe analysis tasks described in \\autoref{ch:iact} make strong use of machine\nlearning tools to be performed in the most efficient way. There are a lot of\ndifferent machine learning techniques that find increasingly many and\nsuccessfull applications in modern physics. The following overview is based on\nthe works \\cite{bagging, goodfellow, mitchell}.\n\n\\section{Machine Learning}\n%\nMachine learning describes the field of applied statistics that uses computers\nto learn to solve certain problems. The \\textit{learning} is defined by Tom\nMitchell~\\cite{mitchell} as: \\enquote{A computer program is said to learn from\nexperience $E$ with respect to some class of tasks $T$ and performance measure\n$P$, if its performance at tasks in $T$, as measured by $P$, improves with\nexperience $E$.} There is a wide variety of different tasks this can be applied\nto and many performance measures. The most important preposition for well\nsuited problems is the available experience or in this case the amount of data\nto learn from.\n\nMachine learning aims at solving problems that profit from the computing power\nof modern technology but are not the kind of problem to be solved by a typical\nprogram written by a human \\cite{goodfellow}.\n\n\\subsection{The Experience}\n%\nTo make a generic machine learning algorithm work for a specific task it has to\nbe \\textit{trained} on data. Just like a human, it needs to be given\ninformation to base a decision on and to be shown how that decision based on\nthe information is supposed to look. The kind of data suitable for learning\ndepends on the kind of algorithm to be used and vice versa. Generally, machine\nlearning algorithms can be divided into \\textbf{supervised} and\n\\textbf{unsupervised} algorithms, both of which will be used in this work.\n\nData to derive experience from for supervised algorithms consists of data points\nwith a certain feature set and a specific label or true value. The data sets for\nthe \\textit{separation} of two classes for example contain a certain feature\nset for every data point and a label for the corresponding class each of these\npoints belongs to. Supervised learning therefore aims at learning to predict\na certain target value (or multiple) from a given feature set including this\nvalue. The used learning data in this analysis is provided by simulations, so\nthat the true values for the machine learning tasks are known. Unsupervised\nlearning, however, works on unlabelled data and is used in this work in form of\na clustering algorithm.\n\n\\subsection{The Task}\n%\nThe task a machine learning algorithm is supposed to do is the solution of a\nspecific problem in the best possible way. To reach this solution the process\nof learning is used. A machine learning algorithm uses data to adapt to a specific task upon the given data. The three desired tasks\nwithin the analysis of Cherenkov telescope images are the \\textit{separation} of\ngamma-rays from hadronic cosmic rays, as well as the \\textit{estimation} of the\nenergy and source position of cosmic gamma-rays. The kind of task already\ndetermines what machine learning techniques are best to be used or which ones\ndo not suit the problem and how working architectures have to look. A\nclassification like the separation of gamma-rays from hadronic cosmic rays\nrequires a different output and therefore network structure than a regression\ntask.\n\n\\subsection{The Performance Measure}\n%\nAs described above, machine learning is about improving on certain tasks.\nTherefore, it is essential to quantify the performance during, but also after the\nlearning process. This already implicates that performance measures are very\nspecific to the task. During the training of a machine learning algorithm a\nloss is being minimalized. This loss is dependant on the task at hand and improved during the training epochs until a saturation is reached. The performance of a classification task is naturally\nmeasured by the \\textbf{accuracy} of the model, because it simply describes how\nmany of the model's outputs are correct. When validating continuous outputs\nrather than discrete classifications an accuracy is not appropriate. The\nestimation of the energy, e.g., requires a continuous-valued metric.\n\nThe models are trained on specific, simulated data but only to be applied on\ndata sets they have \\textit{not} been trained on. Thus, the interesting metrics\nare those calculated on data sets complementary to the training data sets,\nbecause they resemble the real use case. To do so, the whole data set is divided\ninto a fraction determined for training and a test set on which the metrics can\nbe calculated. A frequently used method for this is the\n\\textbf{cross-validation}. The data set is divided into $n$ equaly sized, random\nsubsamples; $n-1$ samples are used for training whereas the single excluded\nsample is used for validation. This is done $n$ times for each one of the\nsubsamples and the metrics are calculated as the mean value of all the single\nvalidations.\n\n\\section{Random Forests}\n%\nOne of the most frequently used machine learning algorithms and the one used\nfor the tasks in this analysis is the so called random forest. This is a\nsupervised learning algorithm based on the so called \\textit{decision tree}.\n\n\\subsection{Decision Trees}\n%\nDecision trees classify data points based on consecutive binary decisions. The\ndecisions are based on the single features of the data point and result in a\npoint specific result that is being returned. The number of single binary\ndecisions (also called \\textit{node}) preceding the final classification is\ncalled \\textit{depth} of the tree. Decision trees are trained on labelled data\nand determine thresholds for every feature to classify the data point.\n%\n\\begin{figure}[H]\n  \\centering\n  \\begin{tikzpicture}[node distance = 3cm, auto]\n    \\node (f1) [feature] {\\texttt{feature\\_1}};\n    \\node (f2) [feature, below of=f1, xshift=-2.4cm] {\\texttt{feature\\_2}};\n    \\node (f3) [feature, below of=f1, xshift=2.4cm] {\\texttt{feature\\_3}};\n\n    \\node (c1) [class1, below of=f2, xshift=-1.2cm] {\\texttt{class 1}};\n    \\node (c2) [class2, below of=f2, xshift=1.2cm] {\\texttt{class 2}};\n\n    \\node (c3) [class1, below of=f3, xshift=-1.2cm] {\\texttt{class 1}};\n    \\node (c4) [class2, below of=f3, xshift=1.2cm] {\\texttt{class 2}};\n\n    \\draw [pil] (f1) -- node[anchor=east] {$\\mathbf{>15}$\\;} (f2);\n    \\draw [pil] (f1) -- node[anchor=west] {\\;$\\mathbf{\\leq15}$} (f3);\n    \\draw [pil] (f2) -- node[anchor=east] {$\\mathbf{<100}$\\;} (c1);\n    \\draw [pil] (f2) -- node[anchor=west] {\\;$\\mathbf{\\geq100}$} (c2);\n    \\draw [pil] (f3) -- node[anchor=east] {$\\symbf{<-\\sfrac{\\pi}{2}}$\\;} (c3);\n    \\draw [pil] (f3) -- node[anchor=west] {\\;$\\symbf{\\geq-\\sfrac{\\pi}{2}}$} (c4);\n  \\end{tikzpicture}\n  \\caption{Example sketch of a decision tree. The tree decides whether an input data point is of class 1 or class 2. The available features are \\texttt{feature\\_1}, \\texttt{feature\\_2} and \\texttt{feature\\_3}. This decision tree has a depth of 2 and solves the task of a binary separation by performing binary decisions at each node (green boxes). The decision thresholds are written next to the respective connecting lines.}\n  \\label{fig:tree}\n\\end{figure}\n%\nTo determine the best decision threshold for each node, a specific loss function\nto be minimalized is necessary. For a classification task the required\nloss would be the information gain. The thresholds are thus optimized to get the best gain in information at the respective node. This way the decision tree is build from the\ntop node downwards until a perfect classification is achieved or until a set\nmaximum depth is reached.\n\nDecision trees can also be used for regression tasks. The only difference when\nsolving such tasks is the metric to find the best thresholds at each node.\nWhile for classification tasks the information gain is the natural choice, regression\ntasks require a metric describing the error of the single result. Thus, the\nthresholds are determined by minimizing the variance of the target variable.\n\n\\subsection{Random forests}\n%\nA decision tree that is fitted to the data too extensively will reach\nvery high accuracies, but will suffer from a very bad generalization. At some\npoint the tree starts to adapt to the training data's specifics too much and\nwill not work on other data that does not have these specific characteristics.\nThis phenomenon is called \\textit{overfitting} and generally is represented by\na large gap between training and test errors \\cite{goodfellow}. A way to\nprevent this from happening is to constrain the complexity of the decision tree\nwhile using a large number of different trees. This way the trees are not\noverfitted but the complete model is still complex enough.\n\nRandom forests are generated by a process called\n\\textit{bagging}~\\cite{bagging}. Every tree within the forest is trained on a\nsubset of the data randomly sampled with replacement. This way, a large number\nof slightly different trees is generated. While every single decision tree is\nstill prone to overfitting to fluctuations in its respective data set, averaging over\nall of them is not, as long as the trees are not correlated. To prevent such\ncorrelations and further generalize the model, additionally every decision node\ninside a single tree is only given a random subset of all available features.\nRandom forests therefore have two additional parameters: the number of trees\n$n$ and the number $k$ of available features at each node.\n\nThe output of the model consisting of such a forest is then generated\nby counting trees with a specific decision. A confidence for a multi-class\nseparation, e.g., can be generated by counting the fraction of trees that\ndecided for the specific class. The output of a random forest therefore is generated by averaging over all decision trees. Thus, the output score for a classification lies between \\num{0} and \\num{1}, representing the average class decision of the trees. By setting a threshold on this confidence\nclassification, decisions can be performed. In case of regression tasks the\noutput of the forest is the mean of the regression results of the single trees,\nas well.\n\n\\section{Performance Measures}\n%\nAs mentioned earlier, the right performance measure depends on the task to be\nvalidated. Since there are several different tasks to be performed during this\nanalysis a number of performance measures is needed for the evaluation.\n\n\\textbf{Accuracy.} The accuracy of a model describes the proportion of input\nexamples for which the model computes the right output. This performance\nmeasure can be used for models with discrete outputs, such as classifications\nbecause it only takes perfect matches as the right output.\n\n\\textbf{Receiver Operating Characteristic.} For every classification task solved via the above mentioned forest output the\nso called \\textit{receiver operating characteristic} curve (ROC) can be\ndetermined. For a given class this represents the rate of correctly classified\nexamples dependant on the rate of falsely classified ones. The area under this\ncurve (AUC) can be used to quantify the performance of a classification model.\nWhen randomly deciding on an equally distributed data set of two classes, the\nAUC is expected to be about \\num{0.5}, representing the worst possible\nclassification performance. A perfect classification yields an AUC of \\num{1}.\n\n\\textbf{Confusion Matrix.} The confusion matrix shows the results of a machine\nlearning algorithm against the true values. It therefore shows how well the\nalgorithm performs by showing where mismatches occur and with what effect. For\nclassifications this matrix shows what classes are most frequently confused\nwith each other, while for a regression task it shows how big the spread of\nreconstructed values around the true value is.\n\n% \\textbf{Precision.} For a classification the precision describes the fraction\n% of events correctly classified as signal events over all events labelled as\n% signal events.\n% %\n% \\begin{equation}\n%   \\text{precision} = \\frac{T_{\\text{p}}}{T_{\\text{p}} + F_{\\text{p}}}\n% \\end{equation}\n% %\n% \\textbf{Recall.} The recall of a classification model describes the fraction\n% of events correctly classified as signal events over all true signal events.\n% %\n% \\begin{equation}\n%   \\text{recall} = \\frac{T_{\\text{p}}}{T_{\\text{p}} + F_{\\text{n}}}\n% \\end{equation}\n% %\n% \\textbf{$F_\\beta$ score.} The $F_\\beta$ score of a classification model describes the harmonic mean of the precision and recall.\n% %\n% \\begin{equation}\n%   F_\\beta = (1 + \\beta^2)\\frac{\\text{precision} \\cdot \\text{recall}}{\\text{precision} + \\text{recall}}\n% \\end{equation}\n%\n\\textbf{$\\symbf{R^2}$ Score.} This metric quantifies the goodness of fit for a\nchosen model. For a regression task, the $\\symbf{R^2}$ score or sometimes\ncalled \\textit{coefficient of determination} measures how well the input data\npoints are approximated by the model. A regression perfectly describing the\ninput data is indicated by an $\\symbf{R^2}$ score of 1, whereas an\n$\\symbf{R^2}$ score closer to \\num{0} characterizes a decreasing quality of the\nmodel. Models with scores below zero can be interpreted as not suitable to the\ndata.\n", "meta": {"hexsha": "1782c1e481b4b45893e44e8f4b819676c8debe4f", "size": 13238, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "content/04_ML.tex", "max_stars_repo_name": "KevSed/Master-Thesis", "max_stars_repo_head_hexsha": "89175c8acef3c982a6c79ab641cd150f1cd91621", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "content/04_ML.tex", "max_issues_repo_name": "KevSed/Master-Thesis", "max_issues_repo_head_hexsha": "89175c8acef3c982a6c79ab641cd150f1cd91621", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "content/04_ML.tex", "max_forks_repo_name": "KevSed/Master-Thesis", "max_forks_repo_head_hexsha": "89175c8acef3c982a6c79ab641cd150f1cd91621", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.3632286996, "max_line_length": 425, "alphanum_fraction": 0.7813113763, "num_tokens": 3150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.34221842238529343}}
{"text": "\\chapter{A Drift-Kinetic Model for Scrape-off Layer Plasma Dynamics}\n\\label{ch:dk}\n\nA physical theory describing the dynamics of magnetized plasma systems is considered to be closed and, more fundamentally, predictive, if it provides a constitutional relation for the sources of Maxwell's equations, namely the charge density $\\rho$ and current density $\\mathbf{J}$, in terms of the electromagnetic fields $(\\phi, \\mathbf{A})$.\n%\nKinetic theory achieves this goal by providing a distribution function $f_a$ for each species $a$ in the plasma, where $f_a$ is a measure of the number of particles of species $a$ near point $\\mathbf x$, having velocity $\\mathbf v$, at time $t$ per unit volume and is normalized such that $\\int f d\\mathbf x d\\mathbf v=N$ with $N$ the total number of particles in the system.\n%\nWhen $f_a$ is known, the charge density and current density can be obtained by taking velocity moments of $f_a$, namely with $\\rho=\\sum_a q_a \\int f_a d\\mathbf v$ and $\\mathbf{J}= \\sum_a q_a \\int \\mathbf v f_a d \\mathbf v$ where $q_a$ is the charge of the species $a$.\n\nThe equation for the evolution of $f_a$ is derived from the analysis of the trajectories of the particles in the plasma.\n%\nWhen the details of particular temporal or spatial scales can be neglected, the equation for the evolution of $f_a$ can be greatly simplified.\n%\nThis is the case of drift-kinetic theory, where the description of the charged particles inside the plasma is reduced to the behavior of its guiding-centers \\citep{Hazeltine2003}.\n%\nThis is particularly useful in the SOL, where fluctuations are characterized by frequencies lower than the ion gyrofrequency \\citep{Endler1995,Agostini2011,Carralero2014,Garcia2015}, and the turbulent eddies, which include coherent radial propagation of filamentary structures \\citep{DIppolito2002,DIppolito2011,Carreras2005,Serianni2007}, have a radial extension comparable to the time-averaged SOL pressure gradient length $L_p$ \\citep{Zweben2007}.\n\n{In recent years, there has been a significant development of first-principles simulations of the SOL dynamics} with both kinetic \\citep{Tskhakaya2012} and gyrokinetic \\citep{Xu2007, Shi2015, Chang2017,Shi2017} codes.\n%\nHowever, as kinetic simulations {of the SOL and edge regions} remain prohibitive as they still are computationally extremely expensive, the less demanding fluid simulations are the standard of reference.\n%\nThe fluid simulations are usually based on the drift-reduced Braginskii \\citep{Braginskii1965,Zeiler1997} or gyrofluid \\citep{Ribeiro2008a,Held2016} models to evolve plasma density, fluid velocity and temperature. Fluid models assume that the distribution function is close to a local Maxwellian, and that scale lengths along the magnetic field are longer than the mean free path.\n%\nHowever, kinetic simulations show that the plasma distribution function is far from Maxwellian in the SOL region \\citep{Tskhakaya2008,Lonnroth2006,Battaglia2014} and that collisionless effects in the SOL might become important \\citep{Batishchev1997}.\n%\nThis is expected to be particularly true in ITER and other future devices that will be operated in the high confinement mode (H-mode) regime \\citep{Martin2008}.\n%\nIn such cases, a transport barrier is formed that creates a steep pressure gradient at the plasma edge.\n%\nIf the pressure gradient exceeds a threshold value, ELMs are destabilized \\citep{Leonard2014}, expelling large amounts of heat and particles to the wall.\n%\nDescribing structures with such high temperatures (and therefore low collisionality) with respect to the background SOL plasma requires therefore a model that allows for the treatment of arbitrary collision frequencies.\n%\nA kinetic full-F description is therefore needed for a proper SOL description \\citep{Hazeltine1998}.\n\nLeveraging the development of previous models {\\citep{Hammett1993,Dorland1993,Beer1996,Sugama2001,Ji2010,Zocco2011,Schekochihin2016,Hatch2016,Parker2016,Hirvijoki2016,Mandell2018}}, we construct here a moment-hierarchy to evolve the SOL plasma dynamics.\n%\nOur model is valid in arbitrary magnetic field geometries and, making use of the full Coulomb collision operator, at arbitrary collision frequencies.\n%\nThe model is derived within a full-F framework, as the amplitude of the background and fluctuating components of the plasma parameters in the SOL have comparable amplitude. We work within the drift approximation \\citep{Hinton1976, Cary2009}, which assumes that plasma quantities have typical frequencies that are small compared to the ion gyrofrequency $\\Omega_i=e B /m_i$, and their perpendicular spatial scale is small compared to the ion sound Larmor radius $\\rho_s=c_s/\\Omega_i$, with $c_s^2 = T_e/m_i$, $T_e$ the electron temperature, $B$ the magnitude of the magnetic field, $e$ the electron charge, and $m_i$ the ion mass.\n\nIn this chapter, we use the methods of Lagrangian mechanics to derive the equations of motion of a charged particle in an electromagnetic field in the drift-kinetic approximation, that is, when the magnetic field is slowly varying with respect to the gyroradius, and when fluctuations occur on spatial scales larger than the ion gyroradius.\n%\nA detailed description of the drift-kinetic ordering is provided in \\cref{sec:ordering}.\n%\nIn \\cref{sec:solparticle}, we derive the drift-kinetic Lagrangian and state the equations governing the particle position and velocity in the drift-kinetic approximation, together with the equation for the evolution of the distribution function, the so-called drift-kinetic equation.\n%\nThe drift-kinetic equation, when coupled to Maxwell's equations, yields a system of equations describing the dynamics of the plasma system that is, in principle, closed.\n%\nHowever, the numerical solution of kinetic models such as the drift-kinetic one still remains computationally extremely demanding.\n%\nFor this reason, the drift-kinetic equation is converted into a moment-hierarchy equation for the evolution of the velocity moments of the distribution function $f_a$ using a suitable polynomial expansion of $f_a$ i.e., using a Hermite-Laguerre polynomial basis.\n%\nThe expansion of the distribution function in a Hermite-Laguerre basis is performed in \\cref{sec:momentexpansion}, while the moment-hierarchy equation is derived in \\cref{sec:momenthierarchy}.\n%\nA shifted-velocity formulation, which retains the presence of a finite flow velocity in the Hermite-Laguerre basis and better captures strong near-Maxwellian flows with fewer expansion coefficients, is used.\n%\nA particular novelty of the framework derived here is the inclusion of collisions by evaluating explicitly the velocity moments of the full Coulomb nonlinear collision operator (the prefix full is used here to state that both like-particle and unlike-particle collisions are included).\n%\nThis allows us to describe turbulent systems arbitrarily far from equilibrium using a model that is particularly efficient for numerical implementation.\n%\nIn \\cref{sec:poisson}, the system of equations is closed by deriving Poisson's equation in terms of coefficients of the Hermite-Laguerre expansion of the distribution function.\n%\nFinally, a a fluid model based on the truncation of the Hermite-Laguerre expansion in the high collisionality regime is presented, which allows the comparison to well-known fluid models used to describe the plasma dynamics in the SOL.\n%\nThe conclusions follow.\n%\nWe note that the results described in the present chapter have been published in \\citet{Jorge2017}.\n\n\\section{Ordering}\n\\label{sec:ordering}\n\nDenoting {$k_\\perp \\sim |\\nabla_\\perp \\log \\phi|\\sim |\\nabla_\\perp \\log n|\\sim |\\nabla_\\perp \\log T_{e}|$ and $\\omega \\sim |\\partial_t \\log \\phi| \\sim |\\partial_t \\log n| \\sim |\\partial_t \\log T_e|$}, with $\\phi$ the electrostatic potential, we introduce the drift-kinetic ordering parameter $\\epsilon$ such that\\footnote[1]\n%\n{\\label{note1}We note that while this ordering differs from the one presented in \\citet{Jorge2017}, the set of equations presented to describe SOL plasmas remains unchanged.\n%\nWe also point out that the ordering $\\omega \\sim k_\\parallel c_s$ may become marginal near separatrix where $k_\\parallel$ decreases to values below than $\\omega/c_s$.\n}\n\n\\begin{equation}\n    \\epsilon \\sim k_\\perp \\rho_s \\sim \\frac{k_\\parallel}{k_\\perp} \\ll 1.\n    \\label{eq:ordering}\n\\end{equation}\n\n\\noindent {On the other hand, we let $k_\\perp L_p \\sim 1$ since turbulent eddies {are observed to have} an extension comparable to the scale lengths of the {time}-averaged quantities.}\nThese assumptions are in agreement with experimental measurements of SOL plasmas \\citep{LaBombard2001,Zweben2004,Myra2013,Carralero2014}.\n%\nWe set turbulence to be correlated along the magnetic field lines by ordering $\\omega \\sim k_\\parallel c_s$ (see \\cref{note1}), such that\n%\n\\begin{equation}\n    \\frac{\\omega}{\\Omega_i} \\sim \\epsilon^2,\n\\label{eq:ordering2}\n\\end{equation}\n%\nan ordering in agreement with previous drift-reduced fluid models for the SOL \\citep{Zeiler1997,Catto2004}.\n%\nWe also order the electron collision frequency $\\nu_{ei}$ as\n\n\\begin{equation}\n\t\\frac{\\nu_{ei}}{ \\Omega_i} \\sim \\epsilon_\\nu < \\epsilon,\n\t\\label{eq:orderingnu}\n\\end{equation}\n%\nIn addition, the ion collision frequency ${\\nu_i =} \\nu_{ii}$ is ordered as $\\nu_{ii} < \\epsilon^2 \\Omega_i$ that, noticing $\\nu_i \\sim  \\sqrt{{m_e}/{m_i}}(T_e/T_i)^{3/2} \\nu_e$ {(with $\\nu_e = \\nu_{ei}$)}, yields\n\\begin{equation}\n    \\left(\\frac{\\epsilon_\\nu}{\\epsilon^2}\\right)^{2/3}\\left(\\frac{m_e}{m_i}\\right)^{1/3}\\lesssim\\frac{T_i}{T_e}\\lesssim 1.\n    \\label{eq:titebound}\n\\end{equation}\nThe ordering in \\cref{eq:titebound} can be used to justify applying our model in the cold ion limit, $T_i \\ll T_e$, {but allows for $T_i \\sim T_e$}.\nWe note that in the SOL the ratio $T_i/T_e$ is typically in the range $1 < T_i/T_e < 4$ \\citep{Kocan2011}. Furthermore, it is seen that the ion temperature in this range of values plays a negligible role in determining the SOL turbulent dynamics, usually due to a steeper electron temperature profile compared with the ion one, which is usually below the threshold limit of the ion temperature gradient instability \\citep{Mosetto2015}.\n\nThe ordering in Eqs. (\\ref{eq:ordering})-(\\ref{eq:titebound}) is justified in a wide variety of experimental conditions. For example, for a typical JET discharge \\citep{Erents2000,Liang2007,Xu2009} with the SOL parameters $B_T = 2.5$ T, $T_e \\sim T_i \\sim 20$ eV, $n_e \\simeq 10^{19}$ m$^{-3}$, and $k_\\perp \\sim 1$ cm$^{-1}$, we obtain $\\epsilon_\\nu \\sim 0.016$ and $\\epsilon \\sim 0.0182$. For a medium-size tokamak such as TCV \\citep{Rossel2012,Nespoli2017}, estimating  $B_T = 1.5$ T, $T_e \\sim T_i \\sim 40$ eV, $n_e \\simeq 6 \\times 10^{18}$, and $k_\\perp \\sim 1$ cm$^{-1}$, we obtain $\\epsilon_\\nu \\sim 6.2 \\times 10^{-3}$ and $\\epsilon \\sim 0.043$. Finally, for small-size tokamaks such as ISTTOK \\citep{Silva2011a,Jorge2016}, with $B_T = 0.5$ T, $T_e \\sim T_i \\sim 20$ eV, $n_e \\simeq 0.8 \\times 10^{18}$, and $k_\\perp \\sim 1$ cm$^{-1}$, we obtain $\\epsilon_\\nu \\sim 0.0072$ and $\\epsilon \\sim 0.091$. Lower values of $\\epsilon_\\nu$, as in the presence of ELMs where temperatures can reach up to $100$ eV \\citep{Pitts2003}, are also included in the ordering considered here.\n%\n%Following typical SOL experimental measurements (see, e.g. \\citet{Zweben2007,Terry2009,Grulke2014}), we order $k_{\\parallel} \\sim 1/L_B \\sim 1/R$, with $L_B$ the background magnetic field spatial gradient scale and $R$ the tokamak major radius, and take $k_\\parallel \\rho_s \\sim \\epsilon^3$. This yields\n%\n%\\begin{equation}\n    %\\frac{k_\\parallel}{k_\\perp} \\sim \\epsilon^2,\n    %\\label{eq:kpar1}\n%\\end{equation}\n%\n%\\noindent a lower ratio than the ones used in most drift-kinetic and gyrokinetic deductions \\citep{Hahm1988a,Hazeltine2003,Abel2013}.\n%\nWe note that the orderings in \\cref{eq:orderingnu,eq:ordering,eq:ordering2} imply that\n\n\\begin{equation}\n    k_\\parallel \\lambda_{mfp} \\sim \\sqrt{\\frac{m_i}{m_e}}\\frac{\\epsilon^2}{\\epsilon_\\nu},\n    \\label{eq:kparlmfp}\n\\end{equation}\n%\nwhich includes both the collisional regime $k_{\\parallel} \\lambda_{mfp} \\ll 1$, when $\\epsilon_\\nu \\sim \\epsilon$, and the collisionless regime $(k_{\\parallel} \\lambda_{mfp})^{-1} \\ll 1$, when $\\epsilon_\\nu \\ll \\epsilon$.\n%\nFinally, the plasma parameter $\\beta = n T_e/(B^2/2\\mu_0)$ is ordered as $\\beta \\sim \\epsilon^3$, {implying that our equations describe plasma dynamics in an electrostatic regime}.\n%\nAlthough electromagnetic effects can lead to a non-negligible enhancement on heat and particle transport in the SOL \\citep{LaBombard2005}, we focus on devices with low-enough $\\beta$ such that the value of the MHD ballooning parameter $\\alpha_{\\text{MHD}} = \\beta R/L_p$ stays below the electromagnetic balloning instability threshold.\n%\nWe refer the reader to \\citet{Halpern2013a} for a detailed treatment of electromagnetic effects in the SOL within the drift-reduced fluid description and here we consider the electrostatic limit.\n\n\\section{SOL Guiding-Center Model}\n\\label{sec:solparticle}\n\n\\subsection{Single-Particle Motion}\n\nTo derive a convenient equation of motion in the presence of a strong magnetic field $\\mathbf B$, we start with the Hamiltonian of a charged particle of species $a$ \\citep{Jackson1999},\n%\n\\be\n    H_a(\\mathbf q, \\mathbf p)=\\frac{[\\mathbf p - q_a \\mathbf A(\\mathbf q)]^2}{2m_a}+q_a \\phi(\\mathbf q),\n    \\label{eq:hamiltonian}\n\\ee\n%\nand its associated Lagrangian,\n%\n\\begin{equation}\n    L_a(\\mathbf x, \\mathbf v)=\\left[q_a \\mathbf A(\\mathbf x) + m_a \\mathbf v\\right]\\cdot \\dot{\\mathbf x}-\\left[\\frac{m_a v^2}{2}+q_a \\phi(\\mathbf x)\\right],\n    \\label{eq:lagrangian}\n\\end{equation}\n%\nwhere $\\mathbf p = q_a \\mathbf A + m _a\\mathbf v$ is the canonical momentum conjugated to $\\mathbf q = \\mathbf x$, $\\mathbf v$ is the particle velocity, $\\mathbf A$ is the magnetic vector potential, $\\phi$ is the electrostatic potential, $m_a$ is the mass of the particle and $q_a$ its charge.\n\nWe now perform a coordinate transformation from the phase-space coordinates $\\mathbf z = (\\mathbf x, \\mathbf v)$ to the guiding-center coordinates $\\mathbf Z = (\\mathbf R, v_\\parallel, \\mu, \\theta)$ by writing the particle velocity as [see, e.g., \\citet{Littlejohn1983a}]\n%\n\\begin{align}\n    \\mathbf v &= \\mathbf U+ v_\\perp' \\mathbf c,\n    \\label{eq:GCcoordinates}\n\\end{align}\n%\nwith\n%\n\\begin{equation}\n    \\mathbf U = \\mathbf v_E(\\mathbf R) + v_\\parallel \\mathbf b(\\mathbf R),\n\\end{equation}\n%\nand $\\mathbf v_E = \\mathbf E \\times \\mathbf B/B^2$ the $\\mathbf E \\times \\mathbf B$ velocity. The gyroangle $\\theta$, defined as\n%\n\\begin{equation}\n    \\theta = \\tan^{-1} \\left[\\frac{\\left(\\mathbf v - \\mathbf U \\right)\\cdot \\mathbf e_2}{\\left(\\mathbf v - \\mathbf U \\right)\\cdot \\mathbf e_1} \\right]\n\\end{equation}\n%\nis introduced by defining the right-handed coordinate set $(\\mathbf e_1, \\mathbf e_2, \\mathbf b)$, such that $\\mathbf c = -\\mathbf a \\times \\mathbf b=\\mathbf d a(\\theta)/d\\theta$, with $\\mathbf a = \\cos \\theta \\mathbf e_1 + \\sin \\theta \\mathbf e_2$.\nThe decomposition in \\cref{eq:GCcoordinates} allows us to isolate the high-frequency gyromotion contained in the $v_\\perp' \\mathbf c$ term, from the dominant guiding-center velocity $\\mathbf U$.\nThe adiabatic invariant $\\mu$ is defined as\n%\n\\begin{equation}\n    \\mu = \\frac{m_a v_\\perp^{'2}}{2B}\n\\label{eq:gcmu}\n\\end{equation}\n%\nwhereas the guiding-center position is\n%\n\\begin{equation}\n    \\mathbf R = \\mathbf x - \\rho_a \\mathbf a,\n    \\label{eq:GCx}\n\\end{equation}\n%\nwith $\\rho_a = \\sqrt{2 m_a  \\mu/(q_a^2 B)}$ the Larmor radius. Incidentally, for the case of weakly varying magnetic fields, \\cref{eq:GCx} describes the circular motion of a particle around its guiding-center $\\mathbf R$ with radius $\\rho_a$, i.e., $(\\mathbf x - \\mathbf R)^2 = \\rho_a^2$.\n\nAs our goal is to develop a model that describes turbulent fluctuations occurring on a spatial scale longer than the sound Larmor radius $\\rho_s$, and a time scale larger than the gyromotion one, we keep terms in the Lagrangian up to $O(\\epsilon)$ and order $T_i \\sim T_e$, which implies\n%\n\\begin{equation}\n    k_{\\perp} \\rho_i \\sim \\epsilon.\n    \\label{eq:tiordering}\n\\end{equation}\n%\nWe therefore expand the electromagnetic fields around $\\mathbf R$, to first order in $\\epsilon$, i.e.,\n%\n\\begin{equation}\n    \\phi(\\mathbf x) \\simeq \\phi(\\mathbf R) + \\rho_a \\mathbf a \\cdot \\nabla_{\\mathbf R} \\phi(\\mathbf R),\n    \\label{eq:FLRexp}\n\\end{equation}\n%\nand similarly for $\\mathbf A$. In the following, if not specified, the electromagnetic fields and potentials are evaluated at the guiding-center position $\\mathbf R$, and we denote $\\nabla=\\nabla_{\\mathbf R}$.\nIn addition, to take advantage of the difference between the turbulent and gyromotion time scales, we use the gyroaveraged Lagrangian $\\lb L_a \\rb_{\\mathbf R}$ to evaluate the plasma particle motion, where the gyroaveraging operator $\\lb \\chi \\rb_{\\mathbf R}$ acting on a quantity $\\chi(\\theta)$ is defined as\n%\n\\begin{equation}\n    \\lb \\chi \\rb_{\\mathbf R} = \\frac{1}{2\\pi}\\int_0^{2\\pi} \\chi (\\theta) d\\theta,\n\\label{gyaveroperator}\n\\end{equation}\n%\nwhich is performed at fixed guiding-center coordinates $\\mathbf R$, $v_\\parallel$ and $\\mu$.\n\nTo evaluate $\\lb L_a \\rb_{\\mathbf R}$ we note that, with the expansion for $\\phi$ and $\\mathbf A$, the Lagrangian in \\cref{eq:lagrangian} can be expressed as $L_a=L_{0a}+L_{1a}+\\tilde L_a$ where $L_{0a}$ is gyroangle independent,\n%\n\\begin{equation}\n    \\begin{split}\n        L_{0a} &= \\left(q_a \\mathbf A + m_a \\mathbf U\\right)\\cdot \\dot{\\mathbf R}-\\left(\\frac{m_a v_\\parallel^2}{2}+\\frac{m_a v_E^2}{2}+\\mu B+q_a \\phi\\right),\n    \\end{split}\n    \\label{eq:L0}\n\\end{equation}\n%\n$L_{1a}$ is proportional to $\\rho_a^2$ (and hence to $\\mu$) and is order $\\epsilon^0$\n%\n\\begin{equation}\n    \\begin{split}\n        &L_{1a} = \\rho_a^2 q_a \\dot \\theta \\left(\\mathbf a \\cdot \\nabla\\right) \\left(\\mathbf A \\cdot \\mathbf c\\right)+m_a \\rho_a^2 \\Omega \\dot \\theta+{\\rho_a \\dot \\rho_a}\\left[q_a \\left(\\mathbf a \\cdot \\nabla\\right)\\left(\\mathbf A \\cdot \\mathbf a\\right)\\right],\n    \\end{split}\n    \\label{eq:L2}\n\\end{equation}\n%\nand the $\\tilde L_{a}$ contribution contains the terms {linearly proportional to $\\cos \\theta$ or $\\sin \\theta$} \\citep{Cary2009} {which are not present in $\\lb L_a \\rb_{\\mathbf R}$, as $\\lb \\tilde L_a \\rb_{\\mathbf R} = 0$}.\n\nWe note that $\\lb L_{1a} \\rb_{\\mathbf R}$ can be simplified since $\\lb \\left(\\mathbf a \\cdot \\nabla\\right) \\mathbf A \\cdot \\mathbf c \\rb_{\\mathbf R} = -\\mathbf b \\cdot (\\nabla \\times \\mathbf A) /2$, and $\\lb \\left(\\mathbf a \\cdot \\nabla\\right) \\mathbf A \\cdot \\mathbf a \\rb_{\\mathbf R} = \\nabla_\\perp\\cdot\\mathbf{A}/2$. Subtracting the total derivative $-q_a d/dt(\\rho_a^2 \\nabla_\\perp \\mathbf A)/4$ from $\\lb L_a \\rb_{\\mathbf R}$, which does not alter the resulting equations of motion, we redefine the gyroaveraged Lagrangian as\n%\n\\begin{equation}\n    \\begin{split}\n        \\lb L_a \\rb_{\\mathbf R} &= \\left(q_a\\mathbf A + m_a{\\mathbf U}\\right) \\cdot \\dot{\\mathbf R}  - \\left(\\frac{m_a v_\\parallel^2}{2}+\\frac{m_a v_E^2}{2} + q_a \\phi\\right)-\\mu B\\left(1- \\frac{\\dot \\theta}{\\Omega_a}\\right)\n        -\\frac{\\rho_a^2}{4}\\frac{d }{dt}\\left[\\nabla_\\perp\\cdot\\left(q_a \\mathbf A\\right)\\right].\n    \\end{split}\n    \\label{eq:gyroLag}\n\\end{equation}\n%\nWe now order the terms appearing in $\\lb L_a \\rb_{\\mathbf R}$.\nAs imposed by the Bohm sheath conditions \\citep{Stangeby2000}, both electrons and ions stream along the field lines with parallel velocities comparable to the sound speed $c_s = \\sqrt{T_e/m_i}$ in the SOL.\nThe Bohm boundary conditions at the sheath also set the electrostatic potential $e \\phi \\sim \\Lambda T_e$ across the SOL, where $\\Lambda = \\ln \\sqrt{m_i/(m_e 2\\pi)}\\simeq 3$.\nTherefore, we keep the $m_a v_E^2/2$ term in the Lagrangian in \\cref{eq:gyroLag}, as to take into account the presence of the numerically large factor $\\Lambda^2$ in $v_E^2 \\sim \\epsilon^2 \\Lambda^2 c_s^2$.\n\nBy neglecting the higher-order terms in \\cref{eq:gyroLag}, i.e., $-(\\rho_a^2/4){d }\\left[\\nabla_\\perp\\cdot\\left(q_a \\mathbf A\\right)\\right]/{dt}$, the expression for the gyroaveraged Lagrangian describing SOL single-particle dynamics, up to $O(\\epsilon)$, can be written as\n%\n\\begin{equation}\n    \\lb L_a \\rb_{\\mathbf R} = q_a \\mathbf A^* \\cdot \\dot{\\mathbf R} - q_a \\phi^* -\\frac{m_a v_\\parallel^2}{2}+ \\mu \\frac{m_a \\dot \\theta}{q_a}.\n    \\label{eq:lagSOL}\n\\end{equation}\n%\nwhere\n%\n\\begin{equation}\n    q_a\\phi^* = q_a\\phi+ m_a v_E^2/2+\\mu B\n\\label{eq:phis}\n\\end{equation}\n%\nand\n%\n\\begin{equation}\n    q_a\\mathbf A^* = q_a \\mathbf A  + m_a v_\\parallel \\mathbf b + m_a \\mathbf v_E.\n\\label{eq:As}\n\\end{equation}\n%\nThe Euler-Lagrange equations applied to the Lagrangian in \\cref{eq:lagSOL} for the coordinates $\\theta$, $v_\\parallel$, and $\\mu$, yield, respectively, $\\dot \\mu = 0$, $v_\\parallel = \\mathbf b \\cdot \\dot{\\mathbf R}$, and $\\dot \\theta = \\Omega_a$. For the ${\\mathbf R}$ coordinate, we obtain\n%\n\\begin{equation}\n    m_a \\dot v_\\parallel \\mathbf b = q_a (\\mathbf E^* + \\dot{\\mathbf R}\\times \\mathbf B^*),\n    \\label{eq:motLag}\n\\end{equation}\n%\nwhere the relation $[\\nabla \\mathbf A - (\\nabla \\mathbf A)^T] \\cdot \\dot{\\mathbf R} = \\dot{\\mathbf R}\\times (\\nabla \\times \\mathbf A)$ has been used, and we defined $\\mathbf E^* = -\\nabla \\phi^* - \\partial_t \\mathbf A^*$, and $\\mathbf B^* = \\nabla \\times \\mathbf A^*$, with the parallel component of $\\mathbf B^{*}$ given by\n%\n\\begin{equation}\n    B_{\\parallel}^* = \\mathbf B^* \\cdot \\mathbf b = B + \\frac{m_a}{q_a}\\mathbf b \\cdot \\nabla \\times \\left(v_\\parallel \\mathbf b + \\mathbf v_E\\right).\n\\label{eq:defbpars}    \n\\end{equation}\n%\nBy projecting \\cref{eq:motLag} along $\\mathbf B^*$, we derive $m \\dot v_\\parallel B_\\parallel^*= e \\mathbf E^* \\cdot \\mathbf B^*$, while crossing with $\\mathbf b$ yields the guiding-center velocity $\\dot{\\mathbf R} B_\\parallel^* = v_\\parallel \\mathbf B^* + \\mathbf E^* \\times \\mathbf B/B$. Using the expressions for the fields $\\mathbf E^{*}$ and $\\mathbf B^{*}$, we obtain \n%\n\\be\n    \\dot{\\mathbf R}  = \\mathbf U+\\frac{\\mathbf B}{\\Omega_a B_\\parallel^*}\\times\\left(\\frac{d \\mathbf U}{dt}+\\frac{\\mu\\nabla B}{m_a}\\right),\n    \\label{eq:GC1}\n\\ee\n%\nand\n%\n\\be\n    m_a \\dot v_\\parallel = q_a E_\\parallel - \\mu \\nabla_\\parallel B + m_a \\mathbf v_E \\cdot \\frac{d \\mathbf b}{dt}-m_a\\mathcal{A},\n    \\label{eq:GC2}\n\\ee\n%\nIn \\cref{eq:GC1,eq:GC2}, {in addition to the time derivatives of the phase-space coordinates $\\dot{\\mathbf R}, \\dot v_{\\parallel}$, that only have an explicit time dependence, we define the total derivative $d/dt$ of a field $\\phi(\\mathbf R, t)$ that has an explicit time and $\\mathbf R$ dependence as\n%\n\\begin{equation}\n    \\frac{d\\phi}{dt} = \\frac{\\partial \\phi}{\\partial t} + \\mathbf U \\cdot \\nabla \\phi.\n\\end{equation}\n%\nThe $\\mathcal{A}$ term represents the higher-order nonlinear terms in $\\dot v_\\parallel$ that ensure phase-space conservation properties \\citep{Cary2009}, and it is given by\n%\n\\begin{equation}\n    \\mathcal{A}=\\frac{B}{B_\\parallel^*}\\left(\\left.\\frac{d \\mathbf U}{dt}\\right|_\\perp + \\mu \\nabla_\\perp B\\right)\\cdot \\frac{\\nabla \\times \\mathbf U}{\\Omega_a},\n\\end{equation}\n%\nwith $d_t\\mathbf U|_\\perp=-\\mathbf b \\times (\\mathbf b \\times d_t\\mathbf U)$.\n\nThe guiding-center equations of motion (\\ref{eq:GC1}) and (\\ref{eq:GC2}) satisfy the energy, $E_{gc} = q_a \\phi^*+m_a v_\\parallel^2/2$ \\citep{Cary2009}, and momentum, $\\mathbf P_{gc} = e \\mathbf A^*$ \\citep{Cary2009}, conservation laws, given by\n%\n\\begin{equation}\n    \\frac{d E_{gc}}{dt} = q_a \\frac{\\partial \\phi^*}{\\partial t}- q_a \\frac{\\partial \\mathbf A^*}{\\partial t}\\cdot \\dot{\\mathbf R},\n    \\label{eq:enconservation}\n\\end{equation}\n%\nand\n%\n\\begin{equation}\n    \\frac{\\partial \\mathbf P_{gc}}{\\partial t} = -q_a \\nabla \\phi^* + q_a \\nabla \\mathbf A^* \\cdot \\dot{\\mathbf R}.\n    \\label{eq:moconservation}\n\\end{equation}\n%\nIn addition, we note that using \\cref{eq:GC1,eq:GC2} and Maxwell's equations, a conservation equation for $B_{\\parallel}^*$ can be derived\n%\n\\begin{equation}\n    \\frac{\\partial B_{\\parallel}^*}{\\partial t} + \\nabla \\cdot (\\dot{\\mathbf R} B_{\\parallel}^*) + \\frac{\\partial}{\\partial v_\\parallel}\\left(\\dot v_\\parallel B_{\\parallel}^* \\right)=0.\n    \\label{eq:liouvilleGC}\n\\end{equation}\n%\nSince $B_{\\parallel}^*$ is the Jacobian of the guiding-center transformation, \\cref{eq:liouvilleGC} is in fact the phase-space volume conservation law for the guiding-center system of equations (also called Liouville's theorem), reflecting therefore their Hamiltonian nature.\n\n\\subsection{The Guiding-Center Boltzmann Equation}\n\\label{subsec:gcboltzmann}\n\nThe Boltzmann equation for the evolution of the distribution function $f_a(\\mathbf x, \\mathbf v)$ of the particles in $(\\mathbf x, \\mathbf v)$ coordinates is\n%\n\\be\n     \\frac{\\partial f_a}{\\partial t}+\\dot{\\mathbf x}\\cdot \\nabla_{\\mathbf x} f_a + \\dot{\\mathbf v}\\cdot \\nabla_{\\mathbf v} f_a = C(f_a),\n     \\label{eq:boltzmann}\n\\ee\n%\nwhere $C(f_a)=\\sum_b C(f_a,f_b) = \\sum_b C_{ab}$ is the collision operator.\n%\nBecause $f_a$ can significantly deviate from a Maxwellian distribution function in the SOL \\citep{Battaglia2014}, we consider the {bilinear} Coulomb operator $C_{ab}$ \\citep{Balescu1988}, to model collisions between particles of species $a$ and $b$\n%\n\\be\n    \\begin{split}\n        C_{ab}&=L_{ab} \\frac{\\partial}{\\partial v_i}\\left[\\frac{\\partial^2 G_b}{\\partial v_i \\partial v_j}\\frac{\\partial f_a}{\\partial v_j}-\\frac{m_a}{m_b}\\frac{\\partial H_b}{\\partial v_i}f_a\\right],\n    \\end{split}\n    \\label{eq:coulombop}\n\\ee\n%\nwith\n%\n\\be\n    \\begin{split}\n        H_b&=2\\int \\frac{f_b(\\mathbf v')}{|\\mathbf v - \\mathbf v'|}d\\mathbf v',\n    \\end{split}\n\\label{eq:roshb}\n\\ee\n%\nand\n%\n\\be\n    \\begin{split}\n        G_b=\\int f_b(\\mathbf v')|\\mathbf v - \\mathbf v'|d\\mathbf v',\n    \\end{split}\n\\ee\n%\nthe Rosenbluth potentials satisfying $\\nabla^2_v G_b = H_b$. In \\cref{eq:coulombop} we introduced $L_{ab}=q_a^2 q_b^2 \\lambda/(4 \\pi \\epsilon_0^2 m_a^2)=\\nu_{ab} v_{tha}^3/n_b$, where $\\lambda$ is the Coulomb logarithm, $\\nu_{ab}$ the collision frequency between species $a$ and $b$, and $v_{tha}^2=2 T_a/m_a$.\n\nTaking advantage of the small electron to ion mass ratio, the collision operator between unlike-species can be simplified [see, e.g. \\citet{Balescu1988,Helander2002}]. \nThe electron-ion collision operator, to first order in $m_e/m_i$, is given by the operator $C_{ei}(f_e)=C_{ei}^0+C_{ei}^1$, where $C_{ei}^0$ is the Lorentz pitch-angle scattering operator\n\\be\n    \\begin{split}\n        C_{ei}^0&=\\frac{n_i L_{ei}}{v_{the}^3}\\frac{\\partial}{\\partial \\mathbf c_e}\\cdot\\left[\\frac{1}{c_e}\\frac{\\partial f_e}{\\partial \\mathbf c_e}-\\frac{\\mathbf c_e}{c_e^3}\\left(\\mathbf c_e \\cdot \\frac{\\partial f_e}{\\partial \\mathbf c_e}\\right)\\right],\n    \\end{split}\n    \\label{eq:cei0}\n\\ee\n%\nand $C_{ei}^1$ the momentum-conserving term\n%\n\\be\n    \\begin{split}\n        C_{ei}^1&={\\frac{2 n_i L_{ei}}{v_{the}^4 c_e^3}f_{Me}{\\mathbf u_{i}} \\cdot \\mathbf c_e}.\n    \\end{split}\n    \\label{eq:cei1}\n\\ee\n%\nwith $\\mathbf c_a = (\\mathbf v - \\mathbf u_a)/v_{tha}$.\n%\nIon-electron collisions, to first order in $m_e/m_i$, are desribed using the operator\n%\n\\begin{equation}\n    \\begin{split}\n        C_{ie}&=\\frac{ \\mathbf R_{ei}}{m_i n_i v_{thi}}\\cdot \\frac{\\partial f_i}{\\partial \\mathbf c_i}%,\\\\\n        %C_{ie}^1&=\n        +\\nu_{ei}\\frac{n_e}{n_i}\\frac{m_e}{m_i}\\frac{\\partial}{\\partial \\mathbf c_i}\\cdot\\left(\\mathbf c_i f_i%,\\\\\n        %C_{ie}^2&=\\nu_{ei}\\frac{m_e}{m_i}%\n        +\\frac{T_e}{T_i}\n        %\\frac{T_e}{m_i}\n        \\frac{\\partial f_i}{\\partial \\mathbf c_i} \n        \\right),\n    \\end{split}\n    \\label{eq:cie}\n\\end{equation}\n%\nwhere $\\mathbf R_{ei}=\\int m_e \\mathbf v C_{ei} d\\mathbf v$ is the electron-ion friction force.\n%\nWe take advantage of \\cref{eq:orderingnu} to order the electron collision frequency $\\nu_e$ and the ion collision frequency $\\nu_i$ as\n%\n\\begin{equation}\n    \\frac{\\nu_i}{\\Omega_i} \\sim \\sqrt{\\frac{m_e}{m_i}}\\left(\\frac{T_e}{T_i}\\right)^{3/2}\\epsilon_{\\nu} < \\epsilon^2,\n    \\label{eq:orderingnu2}\n\\end{equation}\n%\nwhere we used the relation $\\nu_i \\sim  \\sqrt{{m_e}/{m_i}}(T_e/T_i)^{3/2} \\nu_e$. The orderings in \\cref{eq:orderingnu2,eq:FLRexp} yield the lower bound in \\cref{eq:titebound} for the ion to electron temperature ratio.\n\nWe now express the particle distribution function $f_a$ in terms of the guiding-center coordinates {by defining $F_a$, a function of guiding-center coordinates, as}\n%\n\\begin{equation}\n    F_a(\\mathbf R, v_\\parallel, \\mu, \\theta) = f_a(\\mathbf x(\\mathbf R, v_\\parallel, \\mu, \\theta), \\mathbf v(\\mathbf R, v_\\parallel, \\mu, \\theta)).\n    \\label{eq:fguidF}\n\\end{equation}\n%\nUsing the chain rule to rewrite \\cref{eq:boltzmann} in guiding-center coordinates, we obtain\n%\n\\be\n     \\frac{\\partial F_a}{\\partial t}+\\dot{\\mathbf R}\\cdot \\nabla F_a + \\dot{v_\\parallel}\\frac{\\partial F_a}{\\partial v_\\parallel} + \\dot \\mu \\frac{\\partial F_a}{\\partial \\mu}+ \\dot \\theta \\frac{\\partial F_a}{\\partial \\theta} = C(F_a),\n     \\label{eq:boltzmannSS}\n\\ee\n%\nwhere $\\dot{\\mathbf R}$ and $\\dot v_\\parallel$ are given by \\cref{eq:GC1} and \\cref{eq:GC2} respectively, $\\dot \\theta = \\Omega_a$, and $\\dot \\mu = 0$.\nEquation (\\ref{eq:boltzmannSS}) can be simplified by applying the gyroaveraging operator in \\cref{gyaveroperator}. This results in the drift-kinetic equation\n%\n\\begin{equation}\n    \\frac{\\partial \\lb F_a \\rb_{\\mathbf R}}{\\partial t}+ \\dot{\\mathbf R} \\cdot \\nabla\\lb F_a \\rb_{\\mathbf R} + \\dot v_{\\parallel}\\frac{\\partial \\lb F_a \\rb_{\\mathbf R}}{\\partial v_\\parallel} = \\lb C(F_a)\\rb_{\\mathbf R}.\n    \\label{eq:boltzmannGC1}\n\\end{equation}\n%\nWe now write \\cref{eq:boltzmannGC1} in a form useful to take gyrofluid moments of the form $\\int \\lb F_a \\rb_{\\mathbf R} B dv_\\parallel d\\mu d\\theta$ (see \\cref{sec:momenthierarchy}). Using the conservation law in \\cref{eq:liouvilleGC} for $B_{\\parallel}^{*}$, we can write the guiding-center Boltzmann equation in conservative form as\n%\n\\begin{equation}\n    \\begin{split}\n        &\\frac{\\partial (B_{\\parallel}^*\\lb F_a \\rb_{\\mathbf R})}{\\partial t}+ \\nabla \\cdot ( \\dot{\\mathbf R} B_{\\parallel}^*\\lb F_a \\rb_{\\mathbf R}) + \\frac{\\partial( \\dot v_{\\parallel a} B_{\\parallel}^*\\lb F_a \\rb_{\\mathbf R})}{\\partial v_\\parallel} = B_{\\parallel}^*\\lb C(F_a)\\rb_{\\mathbf R}. \n    \\end{split}\n    \\label{eq:boltzmannGC}\n\\end{equation}\n%\nMoreover, in order to relate the gyrofluid moments $\\int \\lb F_a \\rb_{\\mathbf R} B dv_\\parallel d\\mu d\\theta$ with the usual fluid moments $\\int f_a d^3 v$, we estimate the order of magnitude of the gyrophase dependent part of the distribution function $\\tilde F_a = F_a - \\lb F_a \\rb_{\\mathbf R}$ where $\\lb F_a \\rb_{\\mathbf R}$ obeys \\cref{eq:boltzmannGC1}. The equation for the evolution of $\\tilde F_a$ is obtained by subtracting \\cref{eq:boltzmannGC1} from the Boltzmann equation, \\cref{eq:boltzmannSS}, that is\n%\n\\begin{equation}\n    \\frac{\\partial \\tilde F_a}{\\partial t}+\\dot{\\mathbf R}\\cdot \\nabla \\tilde F_a + \\dot{v_\\parallel}\\frac{\\partial \\tilde F_a}{\\partial v_\\parallel} + \\Omega_a \\frac{\\partial \\tilde F_a}{\\partial \\theta} = C(F_a)-\\lb C(F_a)\\rb_{\\mathbf R}.\n    \\label{eq:boltztilde}\n\\end{equation}\n\nUsing the orderings in \\cref{eq:orderingnu,eq:orderingnu2}, as well as $\\partial_t \\sim \\dot{\\mathbf R} \\cdot \\nabla \\sim \\dot v_\\parallel \\partial_{v_\\parallel} \\sim \\epsilon \\Omega_i$ and $\n\\partial_\\theta \\sim 1$, the comparison of the leading-order term on the left-hand side of \\cref{eq:boltztilde} with the right-hand side of the same equation imply the following ordering for $\\tilde F_e$\n%\n\\begin{equation}\n    \\frac{\\tilde F_e}{\\lb F_e \\rb_{\\mathbf R}} \\sim \\frac{m_e}{m_i}\\epsilon_\\nu< \\epsilon^2,\n    \\label{eq:orderingftildee}\n\\end{equation}\n%\nand $\\tilde F_i$\n%\n\\begin{equation}\n    \\frac{\\tilde F_i}{\\lb F_i \\rb_{\\mathbf R}} \\sim \\sqrt{\\frac{m_e}{m_i}}\\left(\\frac{T_e}{T_i}\\right)^{3/2}\\epsilon_\\nu < \\epsilon^2.\n    \\label{eq:orderingftildei}\n\\end{equation}\n%\nTo evaluate the leading-order term of $\\tilde F_a$, we expand the collision operator $C(F_a) = C_0(\\lb F_a\\rb_{\\mathbf R}) + \\epsilon C_1(F_a) + ...$, such that\n%\n\\begin{equation}\n    \\tilde F_a \\simeq \\frac{1}{\\Omega_a}\\int_0^\\theta\\left[C_0(\\lb F_a \\rb_{\\mathbf R} )-\\lb C_0( \\lb F_a \\rb_{\\mathbf R})\\rb_{\\mathbf R}\\right]d\\theta' + O( \\epsilon^3 \\lb F_a \\rb_{\\mathbf R}).\n    \\label{eq:tildefapp}\n\\end{equation}\n%\nThe relation in \\cref{eq:tildefapp} can be further simplified by expanding the $\\theta$ dependence of $F_a$ in Fourier harmonics, \n%\n\\begin{equation}\n    F_a=\\sum_m e^{i m \\theta} F_{m a},\n    \\label{eq:fourftilde}\n\\end{equation}\n%\nso that for $m=0$ we have $\\lb F_a \\rb_{\\mathbf R} = F_{0a}$, and similarly for $C_0(\\lb F_a \\rb_{\\mathbf R})$\n%\n\\begin{equation}\n    C_0(\\lb F_a \\rb_{\\mathbf R}) = \\sum_{m'} e^{i m' \\theta} C_{m' a}.\n\\end{equation}\n%\nWe can then write \\cref{eq:tildefapp} as\n%\n\\begin{equation}\n    \\tilde F_{m a} = \\frac{C_{m a}}{i m \\Omega_a},\n    \\label{eq:fmacmafourier}\n\\end{equation}\n%\nfor $m \\not=0$.\n\n\\section{Moment Expansion}\n\\label{sec:momentexpansion}\n\nWe now derive a polynomial expansion for the distribution function $\\lb F_a \\rb_{\\mathbf R}$ that simplifies the solution of \\cref{eq:boltzmannGC}, with the collision operators in Eqs. (\\ref{eq:coulombop}) - (\\ref{eq:cie}).\nThis section is organized as follows.\nIn \\cref{section:gcmoment} the Hermite-Laguerre basis is introduced, relating the corresponding expansion coefficients for $\\lb F_a \\rb_{\\mathbf R}$ with its usual gyrofluid moments.\nIn \\cref{section:jifluidexpansion}, we briefly review the fluid moment expansion of the Coulomb collision operator presented in \\citet{Ji2006, Ji2008}.\nIn \\cref{section:cabmomentexpansion}, leveraging the work in  \\citet{Ji2006, Ji2008}, we expand $C_{ab}$ in terms of the product of the gyrofluid moments, for both like- and unlike-species collisions which, ultimately, allows us to solve \\cref{eq:boltzmannGC} in terms of gyrofluid moments.\n\n\\subsection{Guiding-Center Moment Expansion of \\texorpdfstring{$\\lb F_a \\rb_{\\mathbf R}$}{}}\n\\label{section:gcmoment}\n\nTo take advantage of the anisotropy introduced by a strong magnetic field, and efficiently treat the left-hand side of \\cref{eq:boltzmannGC} where the parallel and perpendicular directions appear decoupled, we express $\\lb F_a \\rb_{\\mathbf R}$ by using {a Hermite polynomial basis expansion for the parallel velocity coordinate \\citep{Grad1949,Armstrong1967a,Grant1967,Ng1999,Zocco2011,Loureiro2013a,Parker2015,Schekochihin2016,Tassi2016} and a Laguerre polynomial basis for the perpendicular velocity coordinate {\\citep{Zocco2015,Omotani2015,Mandell2018}}. More precisely, we use the following expansion\n%\n\\be\n    \\begin{split}\n        \\lb F_a \\rb_{\\mathbf R} &=\\sum_{p,j=0}^{\\infty} \\frac{N_a^{pj}}{\\sqrt{2^p p!}}F_{Ma}  H_p(s_{\\parallel a})L_j(s_{\\perp a}^2),\n    \\end{split}\n    \\label{eq:gyrof}\n\\ee\n%\nwhere the {\\textit{physicists'}} Hermite polynomials $H_p$ of order $p$ are defined by the Rodrigues' formula \\citep{Abramowitz1972}\n%\n\\begin{equation}\n    H_p(x)=(-1)^p e^{x^2}\\frac{d^p}{dx^p}e^{-x^2},\n\\end{equation}\n%\nand normalized via\n%\n\\begin{equation}\n    \\int_{-\\infty}^{\\infty} dx H_p(x) H_{p'}(x) e^{-x^2} = 2^p p! \\sqrt{\\pi} \\delta_{p{p'}},\n\\end{equation}\n%\nand the Laguerre polynomials  $L_j$ of order $j$ are defined by the Rodrigues' formula \\citep{Abramowitz1972} \n%\n\\begin{equation}\n    L_j(x)=\\frac{e^x}{j!}\\frac{d^j}{dx^j}(e^{-x}x^j),\n\\end{equation}\n%\nwhich are orthonormal with respect to the weight $e^{-x}$\n%\n\\begin{equation}\n    \\int_{0}^{\\infty} dx L_j(x) L_{j'}(x) e^{-x} = \\delta_{jj'}.\n\\end{equation}\n%\nBecause of the orthogonality of the Hermite-Laguerre basis, the coefficients $N_a^{pj}$ of the expansion in \\cref{eq:gyrof} are\n%\n\\be\n    N_a^{pj}=\\frac{1}{N_{a}}\\int \\frac{H_p(s_{\\parallel a}) L_j(s_{\\perp a}^2) \\lb F_a \\rb_{\\mathbf R} }{\\sqrt{2^p p!}}\\frac{B}{m_a} d\\mu dv_\\parallel d\\theta,\n    \\label{eq:gyromoments}\n\\ee\n%\nand correspond to the guiding-center moments of $\\lb F_a \\rb_{\\mathbf R}$.\n\nIn \\cref{eq:gyrof}, the shifted bi-Maxwellian is introduced\n%\n\\be\n\tF_{Ma}=N_a\\frac{e^{-{s_{\\parallel a}^2}-s_{\\perp a}^2}}{{\\pi}^{3/2}v_{th\\parallel a} v_{th\\perp a}^2},\n\t\\label{eq:bimax}\n\\ee\n%\nwhere $s_{\\parallel a}$ and $s_{\\perp a}$ are the normalized parallel and perpendicular shifted velocities respectively, defined by\n%\n\\begin{equation}\n    s_{\\parallel a} = \\frac{v_\\parallel-u_{\\parallel a}}{v_{th\\parallel a}},~v_{th\\parallel a}^2=\\frac{2 T_{\\parallel a}}{m_a},\n    \\label{eq:sparallela}\n\\end{equation}\n%\nand\n%\n\\begin{equation}\n    s_{\\perp a}^2 = \\frac{v_\\perp^{'2}}{v_{th\\perp a}^{2}}=\\frac{\\mu B}{T_{\\perp a}},~v_{th\\perp a}^2=\\frac{2 T_{\\perp a}}{m_a},\n    \\label{eq:sperpa}\n\\end{equation}\n%\n{which provide an efficient representation of the distribution function in both the weak ($u_{\\parallel a} \\ll v_{th a})$ and strong flow ($u_{\\parallel a} \\sim v_{th a}$) regimes by better capturing strong near-Maxwellian flows with fewer expansion coefficients \\citep{Hirvijoki2016}.}\n%\n\n\nThe guiding-center density $N_a$, appearing in \\cref{eq:bimax}, the guiding-center fluid velocity $u_{\\parallel a}$, in \\cref{eq:sparallela}, and the guiding-center parallel $T_{\\parallel a}=P_{\\parallel a}/N_a$ and perpendicular $T_{\\perp a}=P_{\\perp a}/N_a$ temperatures in \\cref{eq:sparallela,eq:sperpa} are defined as $N_a = ||1||_a$, $N_a u_{\\parallel a} = || v_{\\parallel}||_a$, $P_{\\parallel a} = m_a ||(v_\\parallel-u_{\\parallel a})^2||_a$, and $P_{\\perp a} = ||\\mu B ||_a$, where\n%\n\\begin{equation}\n    ||\\chi||_a \\equiv \\int \\chi \\lb F_a \\rb_{\\mathbf R} \\frac{B}{m_a} d\\mu dv_\\parallel d\\theta.\n\\end{equation}\n%\nThe definition of $N_a$, $u_{\\parallel a}$, $P_{\\parallel a}$, and $P_{\\perp a}$ implies that $N_a^{00}=1,~N_a^{10}=0,~N_a^{20}=0,~N_a^{01}=0,$ respectively.\nLater, we will consider the parallel and perpendicular heat fluxes, defined as\n%\n\\begin{align}\n        Q_{\\parallel a} &= m_a ||(v_\\parallel-u_{\\parallel a})^3||_a,~Q_{\\perp a} = ||(v_\\parallel-u_{\\parallel a}) \\mu B||_a,\n        \\label{eq:fluidmoments1}\n\\end{align}\n%\nwhich are related to the coefficients $N_a^{30}$ and $N_a^{11}$ by %, N_a^{02}, N_a^{21},$ and $N_a^{40}$ by\n%\n\\be\n    \\begin{split}\n        N_a^{30}&=\\frac{Q_{\\parallel a}}{\\sqrt{3}P_{\\parallel a} v_{tha \\parallel}},\n        ~N_a^{11}=-\\frac{\\sqrt{2} Q_{\\perp a}}{P_{\\perp a} v_{tha \\parallel}}.\n    \\end{split}\n    \\label{eq:kineticmoments1}\n\\ee\n\n\n\\subsection{Fluid Moment Expansion of the Collision Operator}\n\\label{section:jifluidexpansion}\n\nA polynomial expansion of the nonlinear Coulomb collision operator in \\cref{eq:coulombop} was carried out in \\citet{Ji2009}, while the treatment of finite fluid velocity and unlike-species collisions is described in \\citet{Ji2008}.\n%\nThis allowed expressing $C_{ab}$ as products of fluid moments of $f_a$ and $f_b$. \n%\nWe summarize here the main steps of \\citet{Ji2006, Ji2008}.\n%\nFor an alternative derivation of the fluid moment expansion in terms of multipole moments of the Coulomb operator, see \\cref{ch:op}.\n\nSimilarly to \\cref{eq:gyrof}, the particle distribution function $f_a$ is expanded as\n%\n\\be\n    f_a = f_{aM} \\sum_{l,k=0}^{\\infty}\\frac{L_k^{l+1/2}(c_a^2) \\mathbf P^{l}(\\mathbf c_a) \\cdot {\\mathbf M_a}^{lk}}{\\sqrt{\\sigma_k^l}},\n    \\label{eq:faji}\n\\ee\n\n\\noindent where  \n%\n\\begin{equation}\n    f_{aM}=\\frac{n_a}{\\pi^{3/2} v_{tha}^3} e^{-c_a^2}\n\\end{equation}\n%\nis a shifted Maxwell-Boltzmann distribution function, and $\\mathbf c_a$ the shifted velocity defined as $\\mathbf c_a=(\\mathbf v - \\mathbf U_a)/v_{tha}$, with $\\mathbf U_a=u_{\\parallel a}\\mathbf b+\\mathbf u_{\\perp a}$ the fluid velocity. The fluid variables $n_a, \\mathbf U_a,$ and $T_a$ are defined as the usual moments of the particle distribution function $f_a$, i.e. $n_a = \\int f_a d^3 \\mathbf v$, $n_a \\mathbf U_a = \\int f_a \\mathbf v d^3v$, $n_a T_a = \\int m f_a (\\mathbf v - \\mathbf u_a)^2 d^3v/3$.\n\nThe tensors $\\mathbf P_a^{lk}(\\mathbf c_a)=\\mathbf P^{l}(\\mathbf c_a)L_k^{l+1/2}(c_a^2)$ constitute an orthogonal basis, where $\\mathbf P^l(\\mathbf c_a)$ is the symmetric and traceless tensor\n%\n\\be\n    \\begin{split}\n    \\mathbf P^l(\\mathbf c_a) &= \\sum_{i=0}^{\\floor{l/2}}d_i^l S_i^l c_a^{2i}\\left\\{\\mathbf I^i \\hat c_a^{l-2i}\\right\\},\n    \\end{split}\n\\ee\n%\nwith $\\mathbf I$ denoting the identity matrix, $\\{\\mathbf A^i\\}$ denoting the symmetrization of the tensor $\\mathbf A^i$, ${\\floor{l/2}}$ denoting the largest integer less than or equal to $l/2$, and the coefficients $d_i^l$ and $S_i^l$ defined by\n%\n\\begin{equation}\n    d_i^l=\\frac{(-2)^i(2l-2i)!l!}{(2l)!(l-i)!},\n\\end{equation}\n%\nand\n%\n\\begin{equation}\n    S_i^l=\\frac{l!}{(l-2i)!2^i i!}.\n\\end{equation}\n%\nThe tensor $\\mathbf P^l(\\mathbf c_a)$ is can be also computed using the recursion relation\n%\n\\begin{equation}\n    \\mathbf P^{l+1}(\\mathbf c)=\\mathbf c \\mathbf P^l(\\mathbf c)-\\frac{c^2}{2l+1}\\frac{\\partial \\mathbf P^{l}(\\mathbf c)}{\\partial \\mathbf c}\n\\end{equation}\n%\nand is normalized via\n%\n\\begin{equation}\n    \\int d \\mathbf v \\mathbf P^{n}(\\mathbf v)\\mathbf P^l(\\mathbf v) \\cdot \\mathbf M^l g(v) = \\mathbf M^n \\delta_{n,l} \\sigma_n \\int d \\mathbf v v^{2n} g(v),\n\\label{eq:normplk}\n\\end{equation}\n%\nwith $\\sigma_l = l!/[2^l (l+1/2)!]$.\n%\nWe note that the tensor $\\mathbf A^i$ is formed by $i$ multiplications of the $\\mathbf A$ elements (e.g., if $\\mathbf A$ is a {rank-2 tensor}, $\\mathbf A^3 \\equiv \\mathbf A \\mathbf A \\mathbf A$, which in index notation can be written as $(\\mathbf A^3)_{ijlkmn} = A_{ij}A_{lk}A_{mn}$).\n\nIn the expansion in \\cref{eq:faji}, $L_k^{l+1/2}(x)$ are the associated Laguerre polynomials\n%\n\\be\n    \\begin{split}\n        L_{k}^{l+1/2}(x)&=\\sum_{m=0}^{k}L_{km}^{l} x^m,\n    \\end{split}\n    \\label{eq:asslaguerre}\n\\ee\n%\nnormalized via\n%\n\\begin{equation}\n    \\int_0^\\infty e^{-x} x^{l+1/2} L_k^{l+1/2}(x) L_{k'}^{l+1/2}(x) dx = \\lambda_{k}^l\\delta_{k,k'}.\n\\label{eq:normlkl}\n\\end{equation}\n%\nwith $\\lambda_{k}^l={(l+k+1/2)!}/{k!}$ and $L_{km}^{l}=[{(-1)^m(l+k+1/2)!}]/[{(k-m)!(l+m+1/2)!m!}]$. The $\\sigma_k^l=\\sigma_l \\lambda_k^l$ term is a normalization factor from the orthogonality relations in \\cref{eq:normplk,eq:normlkl}.\n%\nFinally, the coefficients of the expansion in \\cref{eq:faji} $\\mathbf M_a^{lk}$ are\n%\n\\be\n    \\mathbf M_a^{lk} = \\frac{1}{n_a}\\int d \\mathbf v f_a \\frac{L_k^{l+1/2}(c_a^2) \\mathbf P^{l}(\\mathbf c_a)}{\\sqrt{\\sigma_k^l}},\n    \\label{eq:MlkCoulomb}\n\\ee\n%\nwhich correspond to the moments of $f_a$  due to the orthogonality relations in \\cref{eq:normplk,eq:normlkl}.\n\nBy using the expansion in \\cref{eq:faji} in the collision operator in \\cref{eq:coulombop}, a closed form for $C_{ab}$ in terms of products of $\\mathbf M_a^{lk}$ can be obtained. For like-species collisions it reads\n%\n\\be\n    C_{aa}=\\sum_{l,k=0}^{\\infty}\\sum_{n,q=0}^{\\infty}\\sum_{m=0}^k\\sum_{r=0}^q\\frac{L_{km}^lL_{qr}^n}{\\sqrt{\\sigma_k^l \\sigma_q^n}}c\\left(f_a^{lkm},f_a^{nqr}\\right),\n    \\label{eq:JiCab}\n\\ee\n%\nwith\n%\n\\be\n\\begin{split}\n    c\\left(f_a^{lkm},f_a^{nqr}\\right)&=f_{aM}\\sum_{u=0}^{\\text{min}(2,l,n)}\\nu_{*aau}^{lm,nr}(c_a^2)\\sum_{i=0}^{\\text{min}(l,n)-u}d_i^{l-u,n-u}\\mathbf P^{l+n-2(i+u)}(\\hat{\\mathbf c_a})\\cdot ({\\mathbf M_a^{lk}\\cdot^{i+u}\\mathbf M_a^{nq}})_{TS},\n\\end{split}\n    \\label{eq:ccjiheld}\n\\ee\n%\nwhere $\\hat{\\mathbf c_a} = \\mathbf c_a/c_a$, $\\cdot^n$ is the $n$-fold inner product (e.g., for the matrix $\\mathbf A = A_{ij}$, $(\\mathbf A \\cdot^1 \\mathbf A)_{ij} = \\sum_k A_{ki}A_{kj}$), and $({\\mathbf A})_{TS}$ the traceless symmetrization of $\\mathbf A$ (e.g., $({\\mathbf A})_{TS} = (A_{ij}+A_{ji})/2-\\delta_{ij}\\sum_k A_{kk}/3$).\n%\nWe refer the reader to \\citet{Ji2009} for the explicit form of the $\\nu_{*abu}^{lm,nr}$ coefficients.\n\n\\subsection{Guiding-Center Moment Expansion of the Collision Operator}\n\\label{section:cabmomentexpansion}\n\nIn order to apply the gyroaveraging operator to the like-species collision operator $C_{aa}$ in \\cref{eq:JiCab}, we expand the fluid moments as $\\mathbf M_{a}^{lk}=\\mathbf M_{a0}^{lk} + \\epsilon \\mathbf M_{a1}^{lk} + ...$, aiming at representing the collision operator up to $O(\\epsilon_\\nu \\epsilon)$.\nAn analytical expression for the leading-order $\\mathbf M_{a0}^{lk}$ in terms of guiding-center moments $N_{a}^{pj}$ can be obtained as follows.\nBy splitting $f_a = \\lb f_a \\rb_{\\mathbf R} + \\tilde f_a$ when evaluating the fluid moments $\\mathbf M_a^{lk}$ according to \\cref{eq:MlkCoulomb}, we obtain\n%\n\\begin{equation}\n    \\mathbf M_a^{lk} = \\frac{1}{n_a}\\int d^3 x' d^3 v' \\delta(\\mathbf x' - \\mathbf x)\\frac{L_k^{l+1/2}(c_a^{'2}) \\mathbf P^{l}(\\mathbf c'_a)}{\\sqrt{\\sigma_k^l}}\\left(\\lb f_a \\rb_{\\mathbf R} + \\tilde f_a\\right).\n    \\label{eq:malkexact1}\n\\end{equation}\n%\nwhere the Dirac delta function was introduced to convert the velocity integral into an $(\\mathbf x, \\mathbf v)$ integral that encompasses the full phase-space.\nSince the volume element in phase space can be written as $d^3 \\mathbf x d^3\\mathbf v = (B_\\parallel^*/m)d \\mathbf R dv_\\parallel d \\mu d\\theta$ \\citep{Cary2009}, and defining $\\mathbf x' = \\mathbf R + \\rho_a \\mathbf a$, we can write the fluid moments in \\cref{eq:malkexact1} as\n%\n\\begin{equation}\n\\begin{split}\n    \\mathbf M_a^{lk} &= \\frac{1}{n_a}\\int d \\mathbf R  d v_\\parallel d\\mu d\\theta\\frac{B_\\parallel^*}{m_a} \\delta(\\mathbf x-\\mathbf R -  \\rho_a \\mathbf a)\\frac{L_k^{l+1/2}(c_a^{'2}) \\mathbf P^{l}(\\mathbf c'_a)}{\\sqrt{\\sigma_k^l}}\\left( \\lb F_a \\rb_{\\mathbf R} + \\tilde F_a\\right).    \n\\end{split}\n\\label{eq:malkexact}\n\\end{equation}\n%\nwhere $\\lb f_a \\rb_{\\mathbf R}$ and $\\tilde f_a$ in \\cref{eq:malkexact1} are written in terms of guiding-center coordinates using \\cref{eq:fguidF}.\nNeglecting the higher-order $\\mathbf \\rho_a$ and $\\tilde F_a$ terms, the leading-order fluid moments $\\mathbf M_{a0}^{lk}$ are given by\n%\n\\begin{equation}\n    \\mathbf M_{a0}^{lk} = \\frac{1}{n_a}\\int d v_\\parallel d\\mu d\\theta\\frac{B_\\parallel^*}{m_a} \\frac{L_k^{l+1/2}(c_a^{'2}) \\mathbf P^{l}(\\mathbf c'_a)}{\\sqrt{\\sigma_k^l}}\\lb F_a \\rb_{\\mathbf R} .\n    \\label{eq:malk0exact}\n\\end{equation}\n%\nThe $\\theta$ integration can be performed by making use of the gyroaveraging formula of the $\\mathbf P^l$ tensor\n%\n\\be\n    \\lb \\mathbf P^l(\\mathbf c_a) \\rb_{\\mathbf R} = c_a^{l} P_l\\left(\\xi_a\\right) \\mathbf P^l(\\mathbf b),\n    \\label{eq:Pgyro}\n\\ee\n%\nwhere $\\xi_a=\\mathbf c_a \\cdot \\mathbf b/c_a$ is the pitch angle velocity coordinate, and $P_l$ is a Legendre polynomial defined by\n%\n\\begin{equation}\n    P_l(x)=\\frac{1}{2^ll!}\\frac{d^l}{dx^l}\\left[(x^2-1)^l\\right],\n\\end{equation}\n%\nand normalized via\n%\n\\begin{equation}\n    \\int_{-1}^1 P_l(x)P_{l'}(x)dx=\\frac{\\delta_{ll'}}{l+1/2},\n\\end{equation}\n%\nyielding\n%\n\\begin{equation}\n    \\mathbf M_{a0}^{lk} = \\frac{\\mathbf P^l(\\mathbf b)}{n_a}\\int d v_\\parallel d\\mu  d\\theta \\frac{B_\\parallel^*}{m_a} \\frac{L_k^{l+1/2}(c_a^{'2}) c_a^{l} P_l\\left(\\xi_a\\right) }{\\sqrt{\\sigma_k^l}}\\lb F_a \\rb_{\\mathbf R}.\n    \\label{eq:malk0exact1}\n\\end{equation}\n%\nFor the derivation of \\cref{eq:Pgyro}, see \\cref{sec:gudingcentertransf}.\n%\nFinally, we use the basis transformation\n%\n\\be\n    \\begin{split}\n        c_a^l P_l(\\xi_a)L_k^{l+1/2}(c_a^2)=&\\sum_{p=0}^{l+2k}\\sum_{j=0}^{k+\\floor{l/2}}T_{alk}^{pj}\n        H_p(s_{\\parallel a})L_j(s_{\\perp a}^2),\n    \\end{split}\n    \\label{eq:tlkpj}\n\\ee\n%\nwith the inverse\n%\n\\be\n    \\begin{split}\n        H_p(s_{\\parallel a})L_j(s_{\\perp a}^2) =& \\sum_{l=0}^{p+2j}\\sum_{k=0}^{j+\\floor{p/2}}\\left(T_a^{-1}\\right)_{pj}^{lk}\n        c_a^l P_l(\\xi_a)L_k^{l+1/2}(c_a^2),\n    \\end{split}\n    \\label{eq:tminus1pjlk}\n\\ee\n%\nto obtain an expression for the integrand in \\cref{eq:malk0exact1} in terms of the Hermite-Laguerre basis.\nA numerical evaluation of  $T_{alk}^{pj}$ and $\\left(T_a^{-1}\\right)_{pj}^{lk}$ was carried out in \\citet{Omotani2015}.\n%\nInstead, in Appendix \\ref{app:tlkpj}, we derive {the} analytic expressions {of both $T_{alk}^{pj}$ and $\\left(T_a^{-1}\\right)_{pj}^{lk}$}.\n%\nUsing the definition of guiding-center moments $N_a^{pj}$ in \\cref{eq:gyromoments}, the leading-order fluid moment $\\mathbf M_{a0}^{lk}$ is then given by\n%\n\\be\n    n_a \\mathbf M_{a0}^{lk} = N_a \\mathbf P^l(\\mathbf b) \\mathcal{N}_a^{lk},\n    \\label{eq:CoulDKmom}\n\\ee\n%\nwhere we define\n%\n\\begin{equation}\n    \\mathcal{N}_a^{lk} = \\sum_{p=0}^{l+2k}\\sum_{j=0}^{k+\\floor{l/2}}T_{alk}^{pj}{N}_a^{pj}\\sqrt{\\frac{2^p p!}{\\sigma_k^l}}.\n\\label{eq:CoulDKmom1}\n\\end{equation}\n\nThe leading-order part $C_{aa0}$ of the collision operator $C_{aa}$ can be calculated by approximating $\\mathbf M_{a}^{lk}$ appearing in \\cref{eq:ccjiheld} with $\\mathbf M_{a0}^{lk}$.\nFor the ions, the largest contribution to $\\mathbf M_{i}^{lk}-\\mathbf M_{i0}^{lk}$ is of order $\\epsilon$ and it is given by the $\\rho_i$ appearing in \\cref{eq:malkexact} [the $\\tilde F_i$ correction is smaller since $\\tilde F_i < \\epsilon^2 \\lb F_i \\rb_{\\mathbf R}$, see \\cref{eq:orderingftildei}]. Therefore, by using the ordering in \\cref{eq:orderingnu2}, the largest correction to $C_{ii0}$ is $O(\\sqrt{m_e/m_i} \\epsilon \\epsilon_\\nu)$. The correction to $C_{ee0}$ is of the same order. It follows that we can approximate $C_{aa}$ appearing in \\cref{eq:ccjiheld} with $C_{aa0}$ to represent the collision operator up to $O(\\epsilon_{\\nu} \\epsilon)$.\n\nAs an aside, we note that the relationship between the guiding-center and fluid moments in \\cref{eq:CoulDKmom} provides, for the indices $(l,k)=(0,0)$,\n%\n\\begin{align}\n    n_a &= N_a,\n\\end{align}\n%\nwhile, for $(l,k)=(0,1)$, yields\n%\n\\begin{align}\n    T_a = \\frac{T_{\\parallel a}+2 T_{\\perp a}}{3}.\n\\end{align}\n%\nMoreover, the $(l,k)=(2,0)$ moment provides a relationship useful to express the viscosity tensor $\\mathbf \\Pi_a = \\int (\\mathbf c_a \\mathbf c_a - c_a^2 \\mathbf I) f_a d\\mathbf v$ as\n%\n\\begin{align}\n    \\mathbf \\Pi_a = \\mathbf b \\mathbf b N (T_{\\parallel a} - T_{\\perp a}),\n\\label{eq:stressdk}\n\\end{align}\n%\nwhile for $(l,k)=(1,1)$ gives\n%\n\\begin{align}\n    \\mathbf q_a &= \\left(\\frac{Q_{\\parallel a}}{2}+Q_{\\perp a}\\right)\\mathbf b,\n\\label{eq:heatfluxdk}\n\\end{align}\n%\nwith $\\mathbf q_a$ the heat flux density $\\mathbf q_a = m \\int \\mathbf c_a c_a^2 f_a d \\mathbf v/2$.\n\nIn order to express the Boltzmann equation, \\cref{eq:boltzmannGC}, in terms of the guiding-center moments $N_a^{pj}$, we evaluate the guiding-center moments of $\\lb C_{aa} \\rb_{\\mathbf R}$ which, up to $O(\\epsilon^2)$, are given by\n\\be\n    \\begin{split}\n         C_{aa}^{pj}=\\frac{1}{N_a} \\int \\lb C_{aa0} \\rb_{\\mathbf R}  \\frac{H_p(s_{\\parallel a}) L_j(s_{\\perp a}^2)}{\\sqrt{2^p p!}} \\frac{B}{m_a} dv_{\\parallel} d\\mu d\\theta.\n        \\label{eq:CoulIntGyro}\n    \\end{split}\n\\ee\n%\nBy using the gyroaveraging property of $\\mathbf P^{l}(\\mathbf c_a)$ in \\cref{eq:Pgyro} in the like-species operator in \\cref{eq:JiCab,eq:ccjiheld} (with $\\mathbf M_{a}^{lk} = \\mathbf M_{a0}^{lk}$), and the relation between $\\mathbf M_{a0}^{lk}$ and $N_{a}^{pj}$ in \\cref{eq:CoulDKmom}, the gyroaveraged collision operator coefficients $\\lb c\\left(f_a^{lkm},f_a^{nqr}\\right) \\rb_{\\mathbf R}$ are given by\n%\n\\be\n    \\begin{split}\n    &\\lb c(f_a^{lkm},f_a^{nqr})\\rb_{\\mathbf R}=f_{aM}\\sum_{u=0}^{\\text{min}(2,l,n)}\\nu_{*aau}^{lm,nr}(c_a^2)\\sum_{i=0}^{\\text{min}(l,n)-u}d_i^{l-u,n-u} P_{l+n-2(i+u)}(\\xi) \\mathcal{N}_a^{lk}\\mathcal{N}_a^{nq}\\mathcal{P}^{l,n}_{i+u},\n    \\end{split}\n    \\label{eq:JiCabGyro}\n\\ee\n%\nwith $\\mathcal{P}^{l,n}_{i+u}=\\mathbf{P}^{l+n-2(i+u)}\\cdot ({\\mathbf P^{l}\\cdot^{i+u}{\\mathbf P}^{n}})_{TS}$.\n%\nUsing the basis transformation of \\cref{eq:tminus1pjlk} to express ${H_p(s_{\\parallel a}) L_j(s_{\\perp a}^2)}$ in \\cref{eq:CoulIntGyro} in terms of $c_a^l P_l(\\xi_a)L_k^{l+1/2}(c_a^2)$, and performing the resulting integral, we obtain\n%\n\\be\n    \\begin{split}\n        C_{aa}^{pj}=&\\sum_{l,k}\\sum_{n,q}\\sum_{u=0}^{\\text{min}(2,l,n)}\\sum_{i=0}^{\\text{min}(l,n)-u}\\sum_{e=0}^{p+2j}\\sum_{f=0}^{j+\\floor{p/2}}\\sum_{g=0}^f\\sum_{m=0}^k\\sum_{r=0}^q\\\\\n        &\\frac{L_{km}^lL_{qr}^n L_{fg}^e d_i^{l-u,n-u}}{\\sqrt{\\sigma_k^l \\sigma_q^n} (e+1/2)4 \\pi}\\frac{C_{*aau}^{eg,lm,nr}}{\\sqrt{2^p p!}}\\delta_{e,l+n-2(i+u)}{\\left(T^{-1}\\right)}_{pj}^{ef} \\mathcal{N}_a^{lk}\\mathcal{N}_a^{nq}\\mathcal{P}^{l,n}_{i+u},\n    \\end{split}\n    \\label{eq:caapjexact}\n\\ee\n%\nwith $C_{*aabu}^{jw,lm,nr}=\\int d\\mathbf v c_a^{2w+j}f_{Ma}\\nu_{*aau}^{lm,nr}$ [for an efficient algorithmic representation of $C_{*aabu}^{jw,lm,nr}$ see \\citet{Ji2009}].\n\nWe now turn to the electron-ion collision operator, $C_{ei} = C_{ei}^0 + C_{ei}^1$, with $C_{ei}^0$ given by \\cref{eq:cei0} and $C_{ei}^1$ given by \\cref{eq:cei1}.\nAs the basis $ L_k^{l+1/2} \\mathbf P^l(\\mathbf c_a)$ is an eigenfunction of the Lorentz pitch-angle scattering operator $C_{ei}^0$ with eigenvalue $-l(l+1)$ \\citep{Ji2008}, we write $C_{ei}^0$ as\n%\n\\be\n    C_{ei}^0=-\\sum_{l,k}\\frac{n_i L_{ei}}{v_{the}^3 c_e^3}\\frac{l(l+1)f_{eM}}{\\sqrt{\\sigma_k^l}}L_k^{l+1/2}(c_e^2) \\mathbf P^l(\\mathbf c_e) \\cdot {\\mathbf M_e}^{lk}.\n    \\label{eq:cei0eig}\n\\ee\n%\nSimilarly to like-species collisions, we approximate $\\mathbf M_{e}^{lk} \\simeq \\mathbf M_{e0}^{lk}$ in \\cref{eq:cei0eig}, representing $C_{ei}^0$ accurately up to $O(\\epsilon_\\nu \\epsilon)$.\nUsing the basis transformation in \\cref{eq:tminus1pjlk} and the gyroaverage property of $\\mathbf P^l (\\mathbf c_a)$ in \\cref{eq:Pgyro}, we take guiding-center moments of $C_{ei}$ of the form (\\ref{eq:CoulIntGyro}), and obtain\n%\n\\be\n\\begin{split}\n    C_{ei}^{pj} = -\\frac{\\nu_{ei}}{8 \\pi^{3/2}}&\n    \\sum_{l=0}^{p+2j}\\sum_{f=0}^{j+\\floor{p/2}}\n    \\frac{{\\left(T^{-1}_e\\right)}_{pj}^{lf}}{\\sqrt{2^p p!}}\\left[\\sum_{k=0}^\\infty A_{ei}^{lf,k} \\mathcal{N}_e^{lk} -\\delta_{l,1}\\frac{{u_{\\parallel i}}}{v_{the}}\\frac{{16}}{3 } \\frac{\\Gamma(f+3/2)}{f!\\sqrt{\\pi}}\\right],\n\\end{split}\n\\label{eq:ceipj}\n\\ee\n%\nwhere the $A_{ei}$ coefficients are given by\n%\n\\be\n    \\begin{split}\n        A_{ei,0}^{lf,k}=&\\frac{l(l+1)}{l+1/2}\\frac{(l!)^2 2^l}{(2l)!} \\sum_{m=0}^f \\sum_{n=0}^k \\frac{L_{fm}^l L_{kn}^l}{\\sqrt{\\sigma_k^l}} {(l+m+n-1)!},\n    \\end{split}\n\\ee\n%\nwhere we used the identity $|\\mathbf P^l(\\mathbf b)|^2=2^l (l!)^2/(2l)!$ \\citep{Snider2018}.\n\nFinally, for the ion-electron collision operator, $C_{ie}$, we neglect $O(\\sqrt{m_e/m_i}\\epsilon_\\nu \\epsilon)$ corrections by approximating $F_i \\simeq \\lb F_i \\rb_{\\mathbf R}$, and use the transformation in \\cref{eq:GCcoordinates} to convert the $C_{ie}$ operator in \\cref{eq:cie} to guiding-center variables, yielding\n%\n\\begin{align}\n    C_{ie} &= \\frac{\\mathbf R_{ei}}{m_i n_i v_{th i }}\\cdot\\left[\\mathbf c_\\perp \\frac{m_i v_{thi}^2}{B}\\frac{\\partial \\lb F_i \\rb_{\\mathbf R}}{\\partial \\mu}+\\mathbf b \\frac{\\partial \\lb F_i \\rb_{\\mathbf R}}{\\partial c_{\\parallel i}}\\right]+\\nu_{ei}\\frac{m_e}{m_i}\\frac{n_e}{n_i}\\bigg[3 \\lb F_i \\rb_{\\mathbf R}\\nonumber\\\\\n    &\\l. + c_{\\parallel i} \\frac{\\partial \\lb F_i \\rb_{\\mathbf R}}{\\partial c_{\\parallel i}} +2\\mu \\frac{\\partial \\lb F_i \\rb_{\\mathbf R}}{\\partial \\mu}+ \\frac{T_e}{2T_i}\\frac{\\partial^2 \\lb F_i \\rb_{\\mathbf R}}{\\partial c_{\\parallel i }^2}+\\frac{2 T_e}{B} \\frac{\\partial}{\\partial \\mu}\\left(\\mu \\frac{\\partial \\lb F_i \\rb_{\\mathbf R}}{\\partial \\mu}\\right)\\right].\n    \\label{eq:cie11}\n\\end{align}\n%\nBy evaluating $\\mathbf R_{ei}$ at the guiding-center position $\\mathbf R$ (neglecting higher order $\\epsilon$ effects), we write $\\mathbf R_{ei} \\cdot \\mathbf b = N_e m_e v_{th\\parallel e} C_{ei}^{10}/\\sqrt{2} + O(\\sqrt{m_e/m_i}\\epsilon_\\nu \\epsilon)$ and gyroaverage \\cref{eq:cie11}, yielding\n%\n\\begin{equation}\n    \\begin{split}\n        \\lb C_{ie} \\rb_{\\mathbf R}&=\\frac{C_{ei}^{10}}{\\sqrt{2}}\\frac{m_e}{m_i} \\frac{N_e}{n_i} \\frac{v_{th\\parallel e}}{v_{th\\parallel i}} \\frac{\\partial \\lb F_i\\rb_{\\mathbf R} }{\\partial s_{\\parallel}}+\\nu_{ei}\\frac{m_e}{m_i}\\frac{n_e}{n_i}\\bigg[3 \\lb F_i \\rb_{\\mathbf R}\\\\\n        %\\lb C_{ie}^1 \\rb_{\\mathbf R}&=\n        &\\l.+ s_{\\parallel i} \\frac{\\partial \\lb F_i \\rb_{\\mathbf R}}{\\partial s_{\\parallel i}}+2\\mu \\frac{\\partial \\lb F_i \\rb_{\\mathbf R}}{\\partial \\mu}+ \\frac{T_e}{2 T_{\\parallel i}}\\frac{\\partial^2 \\lb F_i \\rb_{\\mathbf R}}{\\partial s_{\\parallel i}^2} +\\frac{2 T_e }{B}\\frac{\\partial}{\\partial \\mu}\\left(\\mu \\frac{\\partial \\lb F_i \\rb_{\\mathbf R}}{\\partial \\mu}\\right) \\right],\n    \\end{split}\n    \\label{eq:gyrocie}\n\\end{equation}\n%\nwhere we used $c_{\\parallel i}^2 = s_{\\parallel i}^2 T_{\\parallel i}/T_{i}$.\nTaking guiding-center moments of the form (\\ref{eq:CoulIntGyro}) of $\\lb C_{ie} \\rb_{\\mathbf R}$ in \\cref{eq:gyrocie}, we obtain\n%\n\\begin{equation}\n    C_{ie}^{pj}=\\nu_{ei}\\frac{m_e}{m_i}\\sum_{lk}B_{lk}^{pj}N_{i}^{lk},\n    \\label{eq:ciepj}\n\\end{equation}\n%\nwith\n%\n\\begin{equation}\n\\begin{split}\n    B_{lk}^{pj}&=2j\\delta_{lp}\\delta_{kj-1}\\left(1-\\frac{T_e}{T_{\\perp i}}\\right)-\\sqrt{ p}\\frac{v_{th\\parallel e}}{v_{th\\parallel i}}\\frac{C_{ei}^{10}}{\\nu_{ei}}\\delta_{lp-1}\\delta_{kj}\\\\\n    &-(p+2j)\\delta_{lp}\\delta_{kj}+\\sqrt{ p (p-1)}\\delta_{l p-2}\\delta_{kj}\\left(\\frac{T_e}{T_{\\parallel i}}-1\\right).\n\\end{split}\n\\end{equation}\n\n\\section{Drift-Kinetic Moment-Hierarchy}\n\\label{sec:momenthierarchy}\n\nIn this section, we derive a set of equations that describe the evolution of  the guiding-center moments $N_a^{pj}$, by integrating in guiding-center velocity space the conservative form of the Boltzmann equation, \\cref{eq:boltzmannGC}, with the weights $H_p(s_{\\parallel a})L_j(s_{\\perp a}^2)$.\nFirst, we highlight the dependence of $\\dot{\\mathbf R}$ and $\\dot v_{\\parallel}$ on $s_{\\parallel a}$ and $s_{\\perp a}^2$ by rewriting the equations of motion as\n%\n\\begin{equation}\n\\begin{split}\n    \\dot{\\mathbf R} &= \\mathbf U_{0 a} + \\mathbf U_{p a}^* + s_{\\perp a}^2 \\mathbf U_{\\nabla B a}^* + s_{\\parallel a}^2 \\mathbf U_{k a}^* + s_{\\parallel a}(v_{th\\parallel a} \\mathbf b + \\mathbf U_{p a}^{*th}),\n\\end{split}\n\\label{eq:rdotGCform}\n\\end{equation}\n%\nand\n%\n\\begin{equation}\n\\begin{split}\n    m_a \\dot{v}_\\parallel &= F_{\\parallel a}-s_{\\perp a}^2 F_{M a} +s_{\\parallel a} F_{p a}^{th}-m_a \\mathcal{A}.\n\\end{split}\n\\label{eq:vparGCform}\n\\end{equation}\n%\nIn \\cref{eq:rdotGCform,eq:vparGCform}, $\\mathbf U_{0 a} = \\mathbf v_E + u_{\\parallel a} \\mathbf b$ is the lowest-order guiding-center fluid velocity, $\\mathbf U_{\\nabla B a}^* = (T_{\\perp a}/m_a)(\\mathbf b \\times \\nabla B/\\Omega_a^{*} B)$ is the fluid grad-B drift, with $\\Omega_a^{*} = q_a B_{\\parallel}^* / m_a$, $\\mathbf U_{ka}^{*} = (2 T_{\\parallel a}/m_a)(\\mathbf b \\times \\mathbf k/\\Omega_a^*)$ is the fluid curvature drift with $\\mathbf k = \\mathbf b \\cdot \\nabla \\mathbf b$, $\\mathbf U_{pa}^* = ({\\mathbf b}/{\\Omega_a^*})\\times d_0 \\mathbf U_{0 a}/dt$ is the fluid polarization drift, $F_{\\parallel a} = q_a E_\\parallel+m_a\\mathbf v_E \\cdot d_0 \\mathbf b/{dt}$, $F_{M a} = {T_{\\perp a}}{}\\nabla_\\parallel \\ln B$ is the fluid mirror force, and both $\\mathbf U_{p a}^{*th}$ and $F_{p a}^{th}$ are related to gradients of the electromagnetic fields\n%\n\\begin{equation}\n\\begin{split}\n    \\mathbf U_{p a}^{*th} &= v_{th\\parallel a}\\frac{\\mathbf b}{\\Omega_a^*}\\times \\left(\\mathbf b \\cdot \\nabla \\mathbf v_E+\\mathbf v_E \\cdot \\nabla \\mathbf b + 2 u_{\\parallel a} \\mathbf k\\right),\\\\\n    F_{p a}^{th} &=  m_a v_{th\\parallel a} \\mathbf E \\cdot \\left(\\frac{\\mathbf b \\times \\mathbf k}{B}\\right).\n\\end{split}\n\\end{equation}\n%\nThe fluid convective derivative operator is defined as \n%\n\\begin{equation}\n    \\frac{d_{0 a}}{dt} = \\partial_t + \\mathbf U_{0 a} \\cdot \\nabla.  \n    \\label{eq:convdev0}\n\\end{equation}\n\nNext, to obtain an equation for the moment $N_a^{pj}$, we apply the guiding-center moment operator\n%\n\\begin{equation}\n\\begin{split}\n    ||\\chi||_a^{*pj} &=\\frac{1}{N_a B} ||\\chi H_p(s_{\\parallel a}) L_j(s_{\\perp a}^2) B_{\\parallel}^*||\\\\\n    &= \\frac{1}{N_a}\\int \\chi \\frac{B_\\parallel^*}{m_a} \\lb F_a \\rb_{\\mathbf R} \\frac{H_p(s_{\\parallel a}) L_j(s_{\\perp a}^2)}{\\sqrt{2^p p!}}  dv_\\parallel d\\mu d\\theta,\n\\end{split}\n\\end{equation}\n%\nto Boltzmann's equation, \\cref{eq:boltzmannGC}. By defining $|| 1 ||_a^{*pj} = {N}_a^{*pj}$ such that\n%\n\\begin{equation}\n\\begin{split}\n    {N}_a^{*pj} &= N_a^{pj}\\left(1+\\frac{\\mathbf b \\cdot \\nabla \\times \\mathbf v_E}{\\Omega_a}+u_{\\parallel a} \\frac{\\mathbf b \\cdot \\nabla \\times \\mathbf b}{\\Omega_a}\\right)\\\\\n    &+ v_{th\\parallel a}\\frac{\\mathbf b \\cdot \\nabla \\times \\mathbf b}{\\sqrt{2}\\Omega_a}\\left(\\sqrt{p+1}N_a^{p+1~j}+\\sqrt{p}N_a^{p-1~j}\\right),\n\\end{split}\n\\label{eq:overlinenapj}\n\\end{equation}\n%\nand\n%\n\\begin{equation}\n\\begin{split}\n    \\frac{d_a^{*pj}}{dt}={N}_a^{*pj}\\frac{\\partial}{\\partial t}+\\left|\\left|\\dot{\\mathbf R}\\right|\\right|_a^{*pj} \\cdot \\nabla,\n\\end{split}\n\\end{equation}\n%\nthe drift-kinetic moment-hierarchy conservation equation for species $a$ is\n%\n\\be\n    \\begin{split}\n        \\frac{\\partial {N}_a^{*pj}}{\\partial t} + \\nabla \\cdot \\left|\\left|{\\dot{\\mathbf R}}\\right|\\right|_a^{*pj}-\\frac{\\sqrt{2 p}}{v_{th\\parallel a}} \\left|\\left|\\dot v_\\parallel\\right|\\right|_a^{*p-1j} +\\mathcal{F}_a^{pj}= \\sum_b C_{ab}^{pj},\n    \\end{split}\n    \\label{eq:finalDKE}\n\\ee\n%\nwhere we define the fluid operator\n%\n\\be\n    \\begin{split}\n        \\mathcal{F}_a^{pj} &= \\frac{d_a^{*pj}}{dt}\\ln\\left(N_a T_{\\parallel a}^{p/2} T_{\\perp a}^jB^{-j}\\right)+\\frac{\\sqrt{2p}}{v_{th\\parallel a}}\\frac{d^{*p-1 j}u_{\\parallel a}}{dt}\\\\\n        &+\\frac{\\sqrt{p(p-1)}}{2}\\frac{d_a^{*p-2 j}}{dt}\\ln T_{\\parallel a}-j\\frac{d_a^{*pj-1}}{dt}\\ln\\left(\\frac{ T_{\\perp a}}{B}\\right),\n    \\end{split}\n    \\label{eq:finalDKEF}\n\\ee\n%\nsince it is the key term that describes the evolution of the guiding-center fluid properties $N_a, u_{\\parallel a}, P_{\\perp a},$ and $P_{\\parallel a}$ (see \\cref{sec:fluidmodel}).\n%\nThe guiding-center moments of the particle's equations of motion are given by\n%\n\\be\n    \\begin{split}\n        \\left|\\left|{\\dot{\\mathbf R}}\\right|\\right|_a^{*pj}&= \\sum_{l,k}\\left(\\mathbf U_{0 a}\\delta_{pl}\\delta_{jk}  + v_{th\\parallel a}\\mathbf b\\mathcal{V}_{lk}^{1pj}\\right){N}_a^{*lk}\\\\\n        & +\\left(\\mathbf U_{pa}\\delta_{pl}\\delta_{jk} + \\mathbf U_{pa}^{th} \\mathcal{V}_{lk}^{1pj}+ \\mathbf U_{\\nabla B a}\\mathcal{M}_{lk}^{pj} + \\mathbf U_{k a}\\mathcal{V}_{lk}^{2pj}\\right) N_a^{lk},\n    \\end{split}\n    \\label{eq:finalDKE3}\n\\ee\n\\be\n    \\begin{split}\n        m_a\\left|\\left|{\\dot v_\\parallel}{}\\right|\\right|_a^{*pj}&=\\sum_{l,k}\\left[F_{\\parallel a} \\delta_{p,l}\\delta_{j,k} +  F_{p a}^{th} \\mathcal{V}_{lk}^{1pj} +F_{M a}\\mathcal{M}_{lk}^{pj}\\right] {N}_a^{*lk}+m_a\\left|\\left| \\mathcal{A}\\right|\\right|_a^{*pj}.\n    \\end{split}\n    \\label{eq:finalDKE4}\n\\ee\n%\nwhere the phase-mixing operators read\n%\n\\begin{align}\n    \\mathcal{V}_{lk}^{1pj}&=\\left(\\sqrt{\\frac{p+1}{2}}\\delta_{p+1, l}+\\sqrt{\\frac{p}{2}}\\delta_{p-1 ,l}\\right)\\delta_{k,j},\\label{eq:finalDKE5}\\\\\n    \\mathcal{V}_{lk}^{2pj}&=\\left[\\delta_{p,l}\\left(p+\\frac{1}{2}\\right)+\\frac{\\sqrt{(p+2)(p+1)}}{2}{\\delta_{p+2 ,l}}{}+ \\frac{\\sqrt{p(p-1)}}{2}\\delta_{p-2,l} \\right]\\delta_{j,k},\\label{eq:finalDKE6}\\\\\n    \\mathcal{M}_{lk}^{pj}&=(2j+1)\\delta_{p,l}\\delta_{j,k}-(j+1)\\delta_{p,l}\\delta_{j+1, k}-j\\delta_{p,l}\\delta_{j-1 ,k}.\\label{eq:finalDKE7}\n\\end{align}\n%\nThe expressions of $\\mathbf U_{p a}, U_{\\nabla B_a}, U_{p a}^{th}$, and $\\mathbf U_{k a}$ are derived from $\\mathbf U_{p a}^{*}, U_{\\nabla B a}^{*}, U_{p a}^{*th}$, and $\\mathbf U_{k a}^{*}$ by replacing $\\Omega_a^*$ with $\\Omega_a$.\n\nThe expression of $\\left|\\left| \\mathcal{A}\\right|\\right|^{*pj}$ \nIn \\cref{eq:finalDKE4} is given by\n%\n\\begin{equation}\n\\begin{split}\n    || \\mathcal{A}||_a^{*pj} &= \\frac{1}{N_a \\Omega_a} \\sum_{l,k}\\left(A_{1 a}\\mathcal{V}_{lk}^{3pj}+A_{2 a} \\mathcal{V}_{lk}^{2pj}+A_{3 a} \\mathcal{V}_{lk}^{1pj}\\right.\\\\\n    &\\left.+A_{4 a} \\mathcal{V}_{lk}^{1p'j'}\\mathcal{M}_{p'j'}^{pj}+A_{5 a} \\mathcal{M}_{lk}^{pj}+A_{6 a} \\delta_{pl}\\delta_{jk}\\right)N_a^{lk},\n\\end{split}\n\\label{eq:mathavv}\n\\end{equation}\n%\nwith the phase-mixing term\n%\n\\be\n    \\begin{split}\n        \\mathcal{V}_{lk}^{3pj}=&\\left[\\sqrt{(p+3)(p+2)(p+1)}\\delta_{p+3,l}+3\\sqrt{(p+1)^3}{\\delta_{p+1 ,l}}\\right.\\\\\n        &\\left.+ 3\\sqrt{p^3}{\\delta_{p-1 ,l}}+\\sqrt{p(p-1)(p-2)}\\delta_{p-3,l} \\right]\\frac{\\delta_{j,k}}{\\sqrt{8}},\n    \\end{split}\n    \\label{eq:vv3pjlk}\n\\ee\n%\nand the coefficients $A_{ia}$\n%\n\\begin{align}\n        A_{1 a}&= v_{th\\parallel a}^3 \\nabla_\\perp \\cdot \\nabla \\times \\mathbf b,\\\\\n        A_{2 a} &= v_{th\\parallel a}^2 \\left[\\nabla_\\perp \\cdot (u_{\\parallel a} \\nabla \\times \\mathbf b + \\nabla \\times \\mathbf v_E) +  \\nabla \\times \\mathbf b \\cdot \\mathbf A_a\\right],\\\\\n        A_{3 a} &=v_{th\\parallel a} (u_{\\parallel a} \\nabla \\times \\mathbf b + \\nabla \\times \\mathbf v_E) \\cdot \\mathbf A_a + v_{th\\parallel a}^2 \\nabla \\times \\mathbf b \\cdot \\mathbf C,\\\\\n        A_{4 a} &= v_{th\\parallel a} \\frac{T_\\perp}{m_a B}\\nabla_\\perp B \\cdot \\nabla \\times \\mathbf b,\\\\\n        A_{5 a} &= \\frac{T_{\\perp a}}{m_a B}\\nabla_\\perp B \\cdot (u_{\\parallel a} \\nabla \\times \\mathbf b + \\nabla \\times \\mathbf v_E),\\\\\n        A_{6 a} &= (v_{th\\parallel a} u_{\\parallel a} \\nabla \\times \\mathbf b + \\nabla \\times \\mathbf v_E) \\cdot \\mathbf C\n\\end{align}\n%\nwith\n%\n\\begin{align}\n        \\mathbf A_a &= \\bm b \\times \\left[ \\frac{\\partial \\mathbf b}{\\partial t} + (\\mathbf b \\cdot \\nabla) \\mathbf v_E + (\\mathbf v_E \\cdot \\nabla) \\mathbf b +2 u_{\\parallel a} v_{th\\parallel a} \\mathbf k\\right]\\times \\bm b,\\\\\n        \\mathbf C &= \\frac{\\bm b \\times}{v_{th\\parallel a}}\\left[\\frac{\\partial \\mathbf v_E}{\\partial t}+(\\mathbf v_E \\cdot \\nabla)\\mathbf v_E + u_{\\parallel a}^2 \\mathbf k\\right]\\times \\bm b.\n\\end{align}\n\n{Similar moment-hierarchy models (with uniform magnetic fields) have been numerically implemented, and successfully compared with their kinetic counterpart \\citep{Paskauskas2009,Loureiro2015,Schekochihin2016,Groselj2017}, and even shown to be more efficient than other velocity discretization techniques in the same region of validity \\citep{Camporeale2016}. Equation (\\ref{eq:finalDKE}) generalizes such models to spatially varying fields and full Coulomb collisions, while retaining phase-mixing operators that couple nearby Hermite and Laguerre moments and providing a close form for the projection of the Coulomb operator in velocity space. We also note that the use of shifted velocity polynomials in the Hermite-Laguerre basis, which gives rise to the fluid operator $\\mathcal{F}_a^{pj}$, allows us to have an efficient representation of the distribution function both in the weak ($u_{\\parallel a} \\ll v_{th a})$ and strong flow ($u_{\\parallel a} \\sim v_{th a}$) regimes. As we will see in \\cref{sec:fluidmodel}, the fluid operator $\\mathcal{F}_a^{pj}$ generates the lowest order fluid equations, as it is present even if all kinetic moments $N_a^{pj}$ (except $N_a^{00}$) are set to zero.}\n\n\\section{Drift-Kinetic Poisson's Equation}\n\\label{sec:poisson}\n\nWe use Poisson's equation to evaluate the electric field appearing in the moment-hierarchy equation, \\cref{eq:finalDKE}.\nIn $(\\mathbf x, \\mathbf v)$ coordinates, Poisson's equation reads\n%\n\\begin{equation}\n\\begin{split}\n        \\epsilon_0 \\nabla \\cdot \\mathbf E &= \\sum_a q_a n_a=\\sum_a q_a \\int f_a d^3 v.\n\\end{split}\n\\label{eq:fmoment}\n\\end{equation}\n%\nFollowing the same steps used to derive \\cref{eq:malkexact} from \\cref{eq:MlkCoulomb}, we can write Poisson's equation, \\cref{eq:fmoment}, as\n%\n\\begin{equation}\n    \\epsilon_0 \\nabla \\cdot \\mathbf E = \\sum_a q_a \\int d^3 \\mathbf R dv_\\parallel d\\mu d\\theta \\frac{B_\\parallel^*}{m} \\delta(\\mathbf R + \\rho_a \\mathbf a - \\mathbf x)F_a(\\mathbf R, v_\\parallel, \\mu, \\theta).\n    \\label{eq:poissonexact1}\n\\end{equation}\n%\nEquation (\\ref{eq:poissonexact1}) shows that all particles that have a Larmor orbit crossing a given point $\\mathbf x$, give a contribution to the charge density at this location.\n\nPerforming the integral over $\\mathbf R$ and introducing the Fourier transform $F_a(\\mathbf x - \\rho_a \\mathbf a,v_\\parallel, \\mu, \\theta) = \\int d^3\\mathbf k F_a(\\mathbf k,v_\\parallel, \\mu, \\theta) e^{-i \\mathbf k \\cdot \\mathbf x} e^{i \\rho_a \\mathbf k \\cdot \\mathbf a}$, \\cref{eq:poissonexact1} can be rewritten as\n%\n\\begin{equation}\n    \\epsilon_0 \\nabla \\cdot \\mathbf E = \\sum_a q_a \\int  dv_\\parallel d\\mu d^3 \\mathbf k d\\theta \\frac{B_\\parallel^*}{m_a} F_a(\\mathbf k, v_\\parallel, \\mu, \\theta)e^{-i \\mathbf k \\cdot \\mathbf x} e^{i \\rho_a \\mathbf k \\cdot \\mathbf a}.\n    \\label{eq:poissonexact2}\n\\end{equation}\n%\nTo perform the $\\mathbf k$ integration, we use the cylindrical coordinate system $(k_{\\perp}, \\alpha, k_\\parallel)$, expressing $\\mathbf k = k_\\perp \\cos \\theta \\mathbf e_1+k_\\parallel \\mathbf b$, such that $\\mathbf k \\cdot \\mathbf a = k_\\perp \\cos \\theta$. This coordinate system allows us to express $e^{i  \\rho_a \\mathbf k \\cdot \\mathbf a}$ in \\cref{eq:poissonexact2} in terms of Bessel functions using the Jacobi-Anger expansion \\citep{Andrews1992}\n%\n\\begin{equation}\n    e^{i k_\\perp \\rho_a \\cos \\theta} = J_0(k_\\perp \\rho_a) + 2 \\sum_{l=1}^{\\infty} J_l(k_\\perp \\rho_a) i^l \\cos (l \\theta) = \\sum_{l=-\\infty}^{\\infty}i^l J_l(k_\\perp \\rho_a)e^{i l \\theta},\n\\label{eq:jacobianger}\n\\end{equation}\n%\nwhere $J_l(k_\\perp \\rho_a)$ is the Bessel function of the first kind of order $l$. We can then write\n%\n\\begin{equation}\n\\begin{split}\n    \\epsilon_0 \\nabla \\cdot \\mathbf E = \\sum_a &q_a \\int  dv_\\parallel d\\mu d\\theta \\frac{B_\\parallel^*}{m_a}  \\left(  \\Gamma_0[F_a]+  2\\sum_{l=1}^{\\infty} i^l \\Gamma_l[F_a \\cos(l\\theta) ]\\right).    \n\\end{split}\n\\label{eq:poissonotexact3}\n\\end{equation}\n%\nwhere the Fourier-Bessel operator $\\Gamma_l[f]$ is defined as\n%\n\\begin{equation}\n    \\Gamma_l[F_a(\\mathbf k, v_\\parallel, \\mu, \\theta)] \\equiv \\int d^3 \\mathbf k J_l(k_\\perp \\rho_a) F_a(\\mathbf k, v_\\parallel, \\mu, \\theta) e^{-i \\mathbf k \\cdot \\mathbf x}.\n\\label{eq:fourbesseloperator}\n\\end{equation}\n%\nIntroducing the Fourier decomposition of $\\tilde F_a$, \\cref{eq:fmacmafourier}, in  \\cref{eq:poissonotexact3}, we obtain\n%\n\\begin{equation}\n\\begin{split}\n    \\epsilon_0 \\nabla \\cdot \\mathbf E =& \\sum_a q_a \\int  dv_\\parallel d\\mu \\frac{B_\\parallel^*}{m}  \\left( \\Gamma_0[\\lb F_a \\rb_{\\mathbf R}] +  2\\pi\\sum_{l=1}^{\\infty} \\frac{i^{l-1}}{l\\Omega_a}\\Gamma_l[C_{l a}+C_{-l a}]\\right),\n\\end{split}\n\\label{eq:poissonpresqueexact}\n\\end{equation}\n%\nwhere the $\\theta$ integration was performed by using the identity $\\int_0^{2\\pi} e^{i\\theta(l-m)} d\\theta = 2\\pi \\delta(l-m)$.\nNotice that $\\int_0^{2\\pi}\\Gamma_0[F_a]d\\theta/2\\pi = \\Gamma_0(\\lb F_a \\rb_{\\mathbf R})$, and corresponds to the $J_0(k_\\perp \\rho_a)$ operator used in most gyrofluid closures \\citep{Hammett1992a,Dorland1993,Snyder2001,Madsen2013}, and in the gyrokinetic Poisson equation \\citep{Lee1983,Dubin1983a}.\n\nWe now order the terms appearing in \\cref{eq:poissonpresqueexact}. Using the Taylor series expansion of a Bessel function $J_l(x)$ of order $l$ \\citep{Abramowitz1972}, we find\n%\n\\begin{equation}\n    \\Gamma_0[\\lb F_a \\rb_{\\mathbf R}] \\sim \\left[1 - \\frac{(k_{\\perp} \\rho_a)^2}{4} + O(\\epsilon^{4})\\right]\\lb F_a \\rb_{\\mathbf R},\n\\end{equation}\n%\nwhile using the orderings of $\\nu_e$ and $\\nu_i$ in \\cref{eq:orderingnu,eq:orderingnu2}\n%\n\\begin{equation}\n    \\frac{\\Gamma_l[C_{la}]}{\\Omega_a} < \\epsilon_\\nu\\epsilon^{l+1} \\lb F_a \\rb_{\\mathbf R}.\n\\end{equation}\n%\nfor $l \\ge 1$.\n%\nConsistently with \\cref{section:cabmomentexpansion}, we neglect the $l\\ge1$ collisional  terms, therefore representing Poisson's equation up to $O(\\epsilon_\\nu \\epsilon)$.\n%\nSuch terms are included in the gyrokinetic model in \\cref{ch:gk}.\n%\n%For the derivation of an higher-order Poisson equation, the treatment of finite $l\\ge1$ collisional effects are presented in Appendix \\ref{app:poisson}.\n%\nTaylor expanding $J_0(x) \\simeq 1-x^2/4$, Poisson's equation reads\n%\n\\begin{equation}\n\\begin{split}\n    \\epsilon_0 \\nabla \\cdot \\mathbf E=&\\sum_a q_a\\left[N_{a}\\left(1+\\frac{\\mathbf b \\cdot \\nabla \\times \\mathbf b}{\\Omega_a} u_{\\parallel a}+\\frac{\\mathbf b \\cdot \\nabla \\times \\mathbf v_E}{\\Omega_a}\\right) +\\frac{1}{2m_a}\\nabla_\\perp^2 \\left(\\frac{P_{\\perp a}}{\\Omega_a^2}\\right)\\right].\n\\end{split}\n    \\label{eq:poissonfin2}\n\\end{equation}\n\n\n\\section{Collisional Drift-Reduced Fluid Model}\n\\label{sec:fluidmodel}\n\nThe infinite set of equations that describe the evolution of the moments of the distribution function, \\cref{eq:finalDKE}, and Poisson's equation, \\cref{eq:poissonfin2}, constitute the drift-reduced model, which is valid for distribution functions arbitrarily far from equilibrium. For practical purposes, a closure scheme must be provided in order to reduce the model to a finite number of equations.\nIn this section, we derive a closure in the high collisionality regime. For this purpose, we first state in \\cref{sec:fluideqs} the evolution equations for the fluid moments (i.e. $n_a, u_{\\parallel a}, T_{\\parallel a}, T_{\\perp a}, Q_{\\parallel a}$ and $Q_{\\perp a}$), that correspond to the lowest-order indices of the moment-hierarchy equation. Then, in \\cref{sec:highcoll}, we apply a prescription for the higher-order parallel and perpendicular moment equations that allows a collisional closure for $Q_{\\parallel a}$ and $Q_{\\perp a}$ in terms of $n_a, u_{\\parallel a}, T_{\\parallel a}$ and $T_{\\perp a}$.\nThe nonlinear closure prescription used here, {sometimes called \\textit{semi-collisional closure} \\citep{Zocco2011}}, can be employed at arbitrary collisionalities by including a sufficiently high number of moments {[indeed, it was used in \\citet{Zocco2015,Loureiro2015} to consider low collisionality regimes]. It also allows us to retain the non-linear collision contributions inherent to a full-F description that may have the same size as its linear contributions, as pointed out in \\citet{Catto2004}.}\n\n\\subsection{Fluid Equations}\n\\label{sec:fluideqs}\n\nWe first look at the $(p,j)=(0,0)$ case of \\cref{eq:finalDKE}. Noting that $C_{ab}^{00}=0$, we obtain\n%\n\\begin{equation}\n    \\frac{\\partial N_a^{*00}}{\\partial t}+\\nabla \\cdot \\left|\\left|\\dot{\\mathbf R}\\right|\\right|^{*00}_a + \\mathcal{F}_a^{00}=0.\n    \\label{eq:cont1}\n\\end{equation}\n%\nEvaluating $\\left|\\left|\\dot{\\mathbf R}\\right|\\right|^{*pj}_a$ in \\cref{eq:finalDKE3} and $\\mathcal{F}_a^{pj}$ in \\cref{eq:finalDKEF}, for $(p,j)=(0,0)$, \\cref{eq:cont1} yields the continuity equation\n%\n\\begin{equation}\n    \\frac{d_a^0 N_a}{dt} + \\frac{d_{0 a}}{dt}\\left(\\frac{N_a\\nabla_\\perp^2 \\phi}{\\Omega_a B}\\right) = -N_a \\nabla \\cdot \\mathbf u_{0 a} - \\frac{N_a\\nabla_\\perp^2 \\phi}{\\Omega_a B}\\nabla \\cdot \\mathbf U_{0 a}.\n    \\label{eq:continuity}\n\\end{equation}\n%\nThe upper convective derivative ${d_a^0}/{dt}$, defined by\n%\n\\begin{equation}\n    \\frac{d_a^0}{dt}=\\frac{\\partial}{\\partial t} + \\mathbf u_{0a} \\cdot \\nabla,\n    \\label{eq:convectop0}\n\\end{equation}\n%\nis related to the guiding-center fluid velocity $\\mathbf u_{0a}$\n%\n\\begin{equation}\n    \\mathbf u_{0a} = \\mathbf U_{0a} + \\frac{T_{\\parallel a}+T_{\\perp a}}{m_a}\\frac{\\mathbf b \\times \\nabla B}{\\Omega_a B} +\\frac{\\mathbf b}{\\Omega_a}\\times \\frac{d_{0 a} \\mathbf U_{0 a}}{dt},\n    \\label{eq:guidvel}\n\\end{equation}\n%\nand it differs from the lower-convective derivative ${d_{0a}}/{dt}$ in \\cref{eq:convdev0} by the addition of the last two terms in \\cref{eq:guidvel}.\nThe vorticity $\\nabla_\\perp^2 \\phi$ is related to the $\\mathbf E \\times \\mathbf B$ drift by\n%\n\\begin{equation}\n    \\frac{\\mathbf b \\cdot \\nabla \\times \\mathbf v_E}{\\Omega_a} = \\frac{\\nabla_\\perp^2 \\phi}{B \\Omega_a} + O(\\epsilon^3),\n    \\label{eq:vorticityapprox}\n\\end{equation}\n%\nand it appears in \\cref{eq:continuity} due to the difference between $N_a^{*00}$ and $N_a^{00}$ [see \\cref{eq:overlinenapj}].\nTo derive \\cref{eq:continuity}, we use the low-$\\beta$ limit expression for $\\mathbf b \\times \\mathbf k \\simeq (\\mathbf b \\times \\nabla B)/B$ and neglect $u_{\\parallel a}\\mathbf b \\cdot \\nabla \\times \\mathbf b/\\Omega_a$ as\n%\n\\begin{equation}\n    \\frac{u_{\\parallel a} \\mathbf b \\cdot \\nabla \\times \\mathbf b}{\\Omega_a} \\sim \\frac{T_e}{T_i}\\beta \\sim \\epsilon^3,\n    \\label{eq:bcurlbapprox}\n\\end{equation}\n%\ntherefore keeping up to $O(\\epsilon^2)$ terms [namely the $\\nabla_\\perp^2 \\phi$ term in \\cref{eq:vorticityapprox}].\n%\nWe note that, although the particle Lagrangian is kept up to $O(\\epsilon)$, the Euler-Lagrange equations set the particle equations of motion and Botlzmann equation to be second order accurate in $\\epsilon$.\n\nThe parallel momentum equation is obtained by setting $(p,j)=(1,0)$ in \\cref{eq:finalDKE}, yielding\n%\n\\begin{equation}\n    \\begin{split}\n        m_a\\frac{d_a^0 u_{\\parallel a}}{dt} &=\\frac{m_a v_{th\\parallel a}}{\\sqrt 2}\\sum_b C_{ab}^{10}-\\frac{m_a \\nabla_\\perp^2 \\phi}{\\Omega_a B}\\frac{d_0 u_{\\parallel a}}{dt} - \\frac{m_a}{\\sqrt 2N_a}\\nabla \\cdot\\left(\\mathbf u_a^1 N_a v_{th\\parallel a} \\right) \\\\\n        &+m_a ||\\mathcal{A}||_a^{*00}+\\left(1+\\frac{\\nabla_\\perp^2 \\phi}{\\Omega_a B}\\right)\\left(q_a E_\\parallel - T_{\\perp a} \\frac{\\nabla_\\parallel B}{B}+m_a \\mathbf v_E \\cdot \\frac{d_{0 a} \\mathbf b}{dt}\\right),\n    \\end{split}\n    \\label{eq:parallelvelgc}\n\\end{equation}\n%\nwith \n%\n\\begin{equation}\n    \\begin{split}\n        \\mathbf u_a^1 &= \\frac{\\mathbf U_{p a}^{th}}{\\sqrt{2}}+\\frac{\\sqrt 2}{m_a}\\frac{\\mathbf b \\times \\nabla B}{\\Omega_a B}\\frac{Q_{\\parallel a}+Q_{\\perp a}}{N_a v_{th\\parallel a}}+v_{th\\parallel a}\\frac{\\mathbf b}{2}\\left(1+\\frac{\\nabla_\\perp^2 \\phi}{\\Omega_a B}\\right).\n    \\end{split}\n\\end{equation}\n%\nThe expression for $C_{ab}^{10}$ is given in Appendix \\ref{app:cabmoments}, as well as all the $C_{ab}^{pj}$ coefficients relevant for the present fluid model.\nThe left-hand side of \\cref{eq:parallelvelgc} describes the convection of $u_{\\parallel a}$, while the first term in the right-hand side is related to pressure and heat flux gradients, the second term to resistivity (collisional effects), the third term consists of high-order terms kept to ensure phase-space conservation properties, and the last term is the parallel fluid acceleration, namely due to parallel electric fields, mirror force, and inertia.\n\nThe parallel and perpendicular temperature equations are obtained by setting $(p,j)=(2,0)$ and $(0,1)$ respectively in \\cref{eq:finalDKE}. This yields for the parallel temperature\n%\n\\begin{equation}\n    \\begin{split}\n        \\frac{N_a}{\\sqrt{2}}\\frac{d_a^0 T_{\\parallel a}}{dt} &=\n        \\sqrt{2} Q_{\\perp a} \\frac{\\nabla_\\parallel B}{B}- \\frac{N_a \\nabla_\\perp^2 \\phi}{\\sqrt{2}\\Omega_a B}\\frac{d_{0a} T_{\\parallel a}}{dt}-2\\frac{N_a T_{\\parallel a}}{v_{th\\parallel a}}\\mathbf u_a^{1} \\cdot \\nabla u_{\\parallel a}\\\\\n        &-\\nabla \\cdot (N_a T_{\\parallel a} \\mathbf u_a^{2\\parallel})+ N_a T_{\\parallel a}\\frac{\\mathbf E}{B}\\cdot \\frac{\\mathbf b \\times \\nabla B}{B}\\left(1+\\frac{\\nabla_\\perp^2 \\phi}{\\Omega_a B}\\right)\\\\\n        &+\\sum_b C_{ab}^{20}N T_{\\parallel a} +\\frac{2 N_a T_{\\parallel a}}{v_{th\\parallel a}}||\\mathcal{A}||_a^{*10},\n    \\end{split}\n\\label{eq:paralleltempc}\n\\end{equation}\n%\nwhere\n%\n\\begin{equation}\n    \\begin{split}\n        \\mathbf u_a^{2\\parallel}&= \\frac{Q_\\parallel a}{2 N_a T_{\\parallel a}}\\frac{\\mathbf U_{pa}^{th}}{v_{th\\parallel a}}+\\frac{\\sqrt{2}T_{\\parallel a}}{m_a}\\frac{\\mathbf b \\times \\nabla B}{\\Omega_a B}+\\frac{\\mathbf b}{2}\\frac{Q_{\\parallel a} }{N_a T_{\\parallel a} }\\left(1+\\frac{\\nabla_\\perp^2 \\phi}{\\Omega_a B}\\right),\n    \\end{split}\n\\end{equation}\n%\nand for the perpendicular temperature\n%\n\\begin{equation}\n    \\begin{split}\n        &N_a\\frac{d_a^0 }{dt}\\left(\\frac{T_{\\perp a}}{B}\\right)+\\frac{N_a\\nabla_\\perp^2 \\phi}{\\Omega_a B}\\frac{d_{0 a} }{dt}\\left(\\frac{T_{\\perp a}}{B}\\right) =\\nabla \\cdot \\left(\\frac{N_a T_{\\perp a}}{B} \\mathbf u_a^{2\\perp}\\right)-\\frac{ N_a T_{\\perp a}}{B}\\sum_b  C_{ab}^{01},\n    \\end{split}\n    \\label{eq:perptempc}\n\\end{equation}\n%\nwith\n%\n\\begin{equation}\n    \\begin{split}\n        \\mathbf u_a^{2\\perp}&=-\\frac{Q_{\\perp a}}{N_a T_{\\perp a}}\\frac{\\mathbf U_{pa}^{th}}{v_{th\\parallel a}}-\\frac{T_{\\perp a}}{m_a}\\frac{\\mathbf b \\times \\nabla B}{\\Omega_a B}.\n    \\end{split}\n\\end{equation}\n%\nThe equations for the evolution of the parallel $Q_{\\parallel a}$ and perpendicular $Q_{\\perp a}$ heat fluxes are obtained by setting $(p,j)=(3,0)$ and $(1,1)$ respectively in \\cref{eq:finalDKE}, yielding\n%\n\\begin{equation}\n    \\begin{split}\n        \\frac{d_a^0 Q_{\\parallel a}}{dt} &=-  \\frac{d_{0 a}}{dt}\\left(Q_{\\parallel a}\\frac{\\nabla_\\perp^2 \\phi}{\\Omega_a B}\\right)+N_a T_{\\parallel a} \\sqrt{3} v_{th\\parallel a} \\sum_b C_{ab}^{30} \\\\\n        &-Q_{\\parallel a}\\nabla \\cdot \\mathbf u_a^0- \\frac{Q_{\\parallel a} \\nabla_\\perp^2 \\phi}{\\Omega_a B}\\nabla \\cdot \\mathbf U_{0 a} - 3 \\nabla \\cdot (\\mathbf u_{k a} Q_{\\parallel a})\\\\\n        &-\\frac{3}{\\sqrt{2}}\\left(1+\\frac{\\nabla_\\perp^2 \\phi}{\\Omega_a B}\\right)\\frac{\\mathbf E \\cdot \\mathbf b \\times \\nabla B}{B^2}Q_{\\parallel a}+3 \\sqrt{2}N_a T_{\\parallel a} ||\\mathcal{A}||_a^{*20}\\\\\n        &-3 \\sqrt{2}N_a T_{\\parallel a} \\mathbf u_a^{2\\parallel} \\cdot \\nabla u_{\\parallel a} - 3 \\sqrt{2}N_a v_{th\\parallel a} \\mathbf u_a^1 \\cdot \\nabla T_{\\parallel a},\n    \\end{split}\n    \\label{eq:qpar}\n\\end{equation}\n%\nand\n%\n\\begin{equation}\n    \\begin{split}\n        \\frac{d_a^0}{dt}\\left(\\frac{Q_\\perp a}{B}\\right)&=- \\frac{d_{0 a}}{dt}\\left(\\frac{Q_{\\perp a}}{B}\\frac{\\nabla_\\perp^2 \\phi}{\\Omega_a B}\\right)-\\frac{N_a v_{th\\parallel a}}{\\sqrt{2}}(\\mathbf u_a^1 \\cdot \\nabla) \\frac{T_{\\perp a}}{B}\\\\\n        &+\\frac{N_a T_{\\perp a}}{B}(\\mathbf u_a^{2\\perp} \\cdot \\nabla) u_{\\parallel a}-\\left(\\frac{Q_{\\perp a}}{B}\\right)\\left(\\nabla \\cdot \\mathbf u_a^0 + \\frac{\\nabla_\\perp^2 \\phi}{\\Omega B}\\nabla \\cdot \\mathbf U_{0 a}\\right)\\\\\n        &-(\\mathbf U_{k a} + 2 \\mathbf U_{\\nabla B})\\cdot \\nabla \\left(\\frac{Q_{\\perp a}}{B}\\right)-\\frac{\\sum_b C_{ab}^{11}}{\\sqrt{2}}\\frac{v_{th\\parallel a}N_a T_{\\perp a}}{B}\\\\\n        &+\\left(\\frac{N_a T_{\\perp a}^2}{m_a}\\frac{\\nabla_\\parallel B}{B^2}+\\frac{Q_{\\perp a}}{B}\\mathbf E \\cdot \\frac{\\mathbf b \\times \\nabla B}{B^2}\\right)\\left(1+\\frac{\\nabla_\\perp^2 \\phi}{\\Omega_a B}\\right).\n    \\end{split}\n    \\label{eq:qperp}\n\\end{equation}\n%\n{In \\cref{eq:qpar,eq:qperp} we neglected the higher-order moments with respect to $N^{30}$ and $N^{11}$, an approximation that we will scrutinize in the next section.}\nEquations (\\ref{eq:continuity})-(\\ref{eq:qperp}) constitute a closed set of six coupled non-linear partial differential equations for both the fluid variables $n_a, u_{\\parallel a}, T_{\\parallel a}, T_{\\perp a}$, and the kinetic variables $Q_{\\parallel a}$ and $Q_{\\perp a}$.\n\nWith respect to previous $\\delta$F \\citep{Dorland1993,Brizard1994} and full-F gyrofluid models \\citep{Madsen2013}, our fluid model, Eqs. (\\ref{eq:continuity}-\\ref{eq:qperp}), while neglecting $k_{\\perp} \\rho_i \\sim 1$ effects, {includes the velocity contributions from} the $B_{\\parallel}^*$ denominator in the equations of motion, \\cref{eq:GC1,eq:GC2}, and includes the effects of full Coulomb collisions up to order $\\epsilon_\\nu \\epsilon$.\n{Also, due to the choice of basis functions with shifted velocity arguments $H_p(s_{\\parallel a})$ instead of $H_p(v_\\parallel/v_{tha})$, we obtain a set of equations that can efficiently describe both weak flow ($u_{\\parallel a} \\ll v_{th a})$ and strong flow ($u_{\\parallel a} \\sim v_{th a}$) regimes}.\n\n\\subsection{High Collisionality Regime}\n\\label{sec:highcoll}\n\nWe now consider the high collisionality regime, where the characteristic fluctuation frequency{, $\\omega$,} of the {fluid} variables, {satisfies}\n%\n\\begin{equation}\n\\begin{split}\n\t&\\omega \\sim v_{tha} |\\nabla_\\parallel \\ln N_a| \\sim v_{tha} |\\nabla_\\parallel \\ln T_{\\parallel a}|\\sim v_{tha} |\\nabla_\\parallel \\ln T_{\\perp a}| \\sim |\\nabla_\\parallel \\ u_{\\parallel a}| \\sim v_{th a}/ L_{\\parallel a},\n\\end{split}\n\\end{equation}\n%\nis much smaller than the collision frequency $\\nu_a \\simeq \\nu_{aa}$, that is\n%\n\\begin{equation}\n    \\delta_a \\sim \\frac{\\omega}{\\nu_a} \\sim \\frac{\\lambda_{mfp a}}{L_{\\parallel a}} \\ll 1,\n\\label{eq:smallmfp}\n\\end{equation}\n%\nwhere the mean free path $\\lambda_{mfp a}$ in \\cref{eq:smallmfp} is defined as\n%\n\\begin{equation}\n    \\lambda_{mfp a} = v_{th a}/\\nu_{aa}.\n\\end{equation}\n%\nEquation (\\ref{eq:smallmfp}) describes the so-called linear transport regime \\citep{Balescu1988}.\nIn this case, the distribution function can be expanded around a Maxwell-Boltzmann equilibrium, according to the Chapman-Enskog asymptotic closure scheme \\citep{Chapman1962} and, to first order in $\\delta_a$, we have\n%\n\\begin{equation}\n    \\lb F_a \\rb_{\\mathbf R} \\simeq F_{Ma}\\left[1+\\delta_a f_{1 a}(\\mathbf R,v_{\\parallel},\\mu,t)\\right].\n\\label{eq:chapenskexpansion}\n\\end{equation}\n%\nAccording to \\cref{eq:chapenskexpansion}, all moments $N_a^{pj}$ in the Hermite-Laguerre expansion \\cref{eq:gyrof} with $(p,j)\\not=(0,0)$ are order $\\delta_a$. {Since $Q_{\\parallel a}$ and $Q_{\\perp a}$ are determined at first order in $\\delta_a$ only by the moments $(p,j)=(0,0),(3,0),(1,1)$, the truncation of Sec. (\\ref{sec:fluideqs}), i.e., neglecting $(p,j)\\not=(0,0),(3,0),(1,1)$ is justified. For a more detailed discussion {on this topic} see \\citet{Balescu1988}.\nMoreover, in the linear regime, a relationship between the hydrodynamical and kinetic variables can be obtained along the lines of the semi-collisional closure. This allows us to express $Q_{\\parallel a}$ and $Q_{\\perp a}$ as a function of $N_a, u_{\\parallel a}, T_{\\parallel a}$ and $T_{\\perp a}$, therefore reducing the number of equations.\nWe now derive this functional relationship.\n\nWe consider Eqs. (\\ref{eq:qpar})-(\\ref{eq:qperp}) in the linear regime, and neglect the polarization terms that are proportional to $\\nabla_\\perp^2 \\phi/(\\Omega_a B)$.\n{This yields $\\sqrt{{3}/{2}}{\\sum_b C_{ab}^{30}}/{v_{th\\parallel a}} \\simeq R_{\\parallel a}$ and ${\\sum_b C_{ab}^{11}}/(\\sqrt{{2}}{v_{th\\parallel a}}) \\simeq R_{\\perp a}$, with $R_{\\parallel a}$ and $R_{\\perp a}$ given by}\n%\n\\begin{equation}\n    R_{\\parallel a} = \\frac{\\nabla_{\\parallel} T_{\\parallel a}}{T_{\\parallel a}} +u_{\\parallel a} \\frac{\\mathbf b \\times \\nabla B}{\\Omega_a B}\\cdot \\left(\\frac{\\nabla u_{\\parallel a}}{u_{\\parallel a}}+\\frac{\\nabla T_{\\parallel a}}{T_{\\parallel a}}\\right),\n    \\label{eq:collimit1}\n\\end{equation}\n\\begin{equation}\n\\begin{split}\n    R_{\\perp a} &= \\frac{T_{\\perp a}}{T_{\\parallel a}}\\frac{\\nabla_{\\parallel} B}{B} - \\frac{1}{2\\sqrt{2}}\\nabla_{\\parallel} \\ln \\frac{T_{\\perp a}}{B}-u_{\\parallel a} \\frac{\\mathbf b \\times \\nabla B}{\\Omega_a B}\\cdot \\left(\\frac{T_{\\perp a}}{T_{\\parallel a}}\\frac{\\nabla u_{\\parallel a}}{u_{\\parallel a}}+\\nabla \\ln \\frac{T_{\\perp a}}{B}\\right),\n\\end{split}\n\\label{eq:collimit2}\n\\end{equation}\n%\nsince $d_a^0/dt \\sim d_{0 a}/dt \\sim \\omega{}$ and $(d^0 Q_{\\parallel, \\perp }/dt)/Q_{\\parallel,\\perp a} \\sim \\delta_a^2 \\nu_a$.\nWe compute the guiding-center moments of the collision operator $C_{ab}^{30}$ and $C_{ab}^{11}$ by truncating the series for the like-species collision operator in \\cref{eq:caapjexact} at $(l,k,n,q)=(2,1,2,1)$.\nThe resulting $C_{ab}^{pj}$ coefficients are presented in Appendix \\ref{app:cabmoments}.\n\nWith the expression of $C_{ab}^{30}$ and $C_{ab}^{11}$, we can solve for $Q_{\\parallel a}$ and $Q_{\\perp a}$. In the regime $(T_{\\parallel a}-T_{\\perp a})/T_a \\sim \\delta$, at lowest order, we obtain for the electron species\n%\n\\begin{equation}\n    \\frac{Q_{\\parallel e}}{N_e T_{ e} v_{th e}} =-0.362 \\frac{u_{\\parallel e}-u_{\\parallel i}}{v_{th e}}-10.6 \\lambda_{mfpe}\\frac{\\nabla_\\parallel T_e}{T_e},\n    \\label{eq:qpare}\n\\end{equation}\n%\nand\n%\n\\begin{equation}\n    \\frac{Q_{\\perp e}}{N_e T_{ e} v_{th e}} =-0.119 \\frac{u_{\\parallel e}-u_{\\parallel i}}{v_{th e}}-3.02 \\lambda_{mfpe}\\frac{\\nabla_\\parallel T_e}{T_e}.\n\\label{eq:qperpe}\n\\end{equation}\n%\nAnalogous expressions are obtained for the ion species.\n\nEquations (\\ref{eq:continuity}), (\\ref{eq:parallelvelgc}), (\\ref{eq:paralleltempc}), and (\\ref{eq:perptempc}), with $Q_{\\parallel a}$ and $Q_{\\perp a}$ given by \\cref{eq:qperpe,eq:qpare} are valid in the high collisionality regime, and can be compared with the drift-reduced Braginskii equations in \\citet{Zeiler1997}. We first rewrite the continuity equation, \\cref{eq:continuity}, in the form\n\\begin{equation}\n    \\frac{\\partial N_e}{\\partial t} + \\nabla \\cdot \\left[N_e\\left(\\mathbf v_E + u_{\\parallel e} \\mathbf b+  \\frac{T_{\\parallel e}+T_{\\perp e}}{m_e}\\frac{\\mathbf b \\times \\nabla B}{\\Omega_e B} \\right)\\right]\n    =0,\n\\end{equation}\n\\noindent where we expand the convective derivative $d^0{a}/dt$ using \\cref{eq:convectop0} and \\cref{eq:guidvel}, and neglect polarization terms proportional to the electron mass $m_e$. By noting that the diamagnetic drift $v_{de}$ can be written as \n\\begin{equation}\n    \\mathbf v_{de} = \\frac{1}{e N_e}\\nabla \\times \\frac{p_e \\mathbf b}{B}-2\\frac{T_e}{m_e}\\frac{\\mathbf b \\times \\nabla B}{\\Omega_e B},\n\\end{equation}\n\\noindent and by considering the isotropic regime $T_{\\parallel e} \\sim T_{\\perp e} \\sim T_{e}$, we obtain\n\\begin{equation}\n    \\frac{\\partial N_e}{\\partial t} + \\nabla \\cdot \\left[N_e\\left(\\mathbf v_E + u_{\\parallel e} \\mathbf b+  \\mathbf v_{de} \\right)\\right]\n    =0,\n\\end{equation}\n\\noindent which corresponds to the continuity equation in the drift-reduced Braginskii model in \\citet{Zeiler1997}. In {that model}, the polarization equation is obtained by subtracting both electron and ion continuity equations, using Poisson's equation $n_e \\simeq n_i$ with $n_e$ and $n_i$ the electron and ion particle densities respectively, and neglecting {terms proportional to} the electron to ion mass ratio. Applying the same procedure to the present fluid model, we obtain\n%\n\\begin{equation}\n\\begin{split}\n    0&=\\nabla \\cdot \\left(\\frac{\\nabla_\\perp^2 \\phi N_i u_{\\parallel i} \\mathbf b}{\\Omega_i B}\\right)-\\nabla \\cdot \\left[\\frac{\\mathbf v_E}{2 m_i}\\nabla_\\perp^2\\left(\\frac{N_i T_{\\perp i}}{\\Omega_i^2}\\right)\\right]-\\frac{1}{2m_i}\\frac{\\partial}{\\partial t}\\nabla_\\perp^2 \\left(\\frac{N_i T_{\\perp i}}{\\Omega_i^2}\\right)\\\\\n    &+\\nabla \\cdot \\left(\\frac{N_i}{\\Omega_i}\\mathbf b \\times \\frac{d_{0i}\\mathbf U_{0i}}{dt}\\right)+\\nabla \\cdot \\left[\\mathbf b\\left(N_i u_{\\parallel i} - N_e u_{\\parallel e}\\right)\\right]\\\\\n    &+\\nabla \\cdot \\left[\\left({N_i T_{\\parallel i}+N_eT_{\\parallel e}+N_i T_{\\perp i}+N_eT_{\\perp e}}\\right)\\frac{\\mathbf b \\times \\nabla B}{e B^2}\\right].\n\\end{split}\n\\label{eq:gcpolarizationeq}\n\\end{equation}\n\nIn \\cref{eq:gcpolarizationeq}, the first three terms, which are not present in the drift-reduced Braginskii model, correspond to the difference between ion guiding-center density $N_i$ and particle density $n_i$, proportional to both $\\nabla_\\perp^2 \\phi$ and $\\nabla_\\perp^2 P_i$.\nThe parallel momentum and temperature equations, \\cref{eq:parallelvelgc} and \\cref{eq:paralleltempc}, with respect to \\citep{Zeiler1997}, contain the higher-order term $\\mathcal{A}{\\sim O(\\epsilon^2)}$  that ensures phase-space conservation, mirror force terms proportional to $(\\nabla_\\parallel B)/B$, and polarization terms proportional to $\\nabla_\\perp^2 \\phi/(\\Omega_a B)$ due to the difference between guiding-center and particle fluid quantities.\n{This set of fluid equations constitute an improvement over the drift-reduced Braginskii model. With respect to the original Braginskii equations \\citep{Braginskii1965}, they include the non-linear terms that arise when retaining full Coulomb collisions, and the effect of ion-electron collisions.}\n\n\\section{Conclusion}\n\nIn this chapter, a drift-kinetic model is developed, suitable to describe the plasma dynamics in the SOL region of tokamak devices at arbitrary collisionality. Taking advantage of the separation between the turbulent and gyromotion scales, a gyroaveraged Lagrangian and its corresponding equations of motion are obtained. This is the starting point to deduce a drift-kinetic Boltzmann equation with full Coulomb collisions for the gyroaveraged distribution function.\n\nThe gyroaveraged distribution function is then expanded into an Hermite-Laguerre basis, and the coefficients of the expansion are related to the lowest-order gyrofluid moments. The fluid moment expansion of the Coulomb operator described in \\citet{Ji2009} is reviewed, and its respective particle moments are written in terms of coefficients of the Hermite-Laguerre expansion, relating both expansions. This allows us to express analytically the moments of the collision operator in terms of guiding-center moments.\nA moment-hierarchy that describes the evolution of the guiding-center moments is derived, together with a Poisson's equation accurate up to $\\epsilon^2$. These are then used to derive a fluid model in the high collisionality limit.\n\nThe drift-kinetic model derived herein {will be considered in \\cref{ch:gk} as} a starting point for the development of a gyrokinetic Boltzmann equation suitable for the SOL region (e.g. \\citet{Qin2007, Hahm2009}). Indeed, using a similar approach, a gyrokinetic moment-hierarchy may be derived, allowing for the use of perpendicular wave numbers satisfying $k_\\perp \\rho_s \\sim 1$.", "meta": {"hexsha": "827f200afcd6a0375ac1cf9a6fdaa0cc5eecd09e", "size": 92424, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "IST Version/main/ch2_drift_kinetic.tex", "max_stars_repo_name": "rogeriojorge/Rogerio_PhD_Thesis", "max_stars_repo_head_hexsha": "955be22ad75b54d44a3c2d1499098824e7500d38", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IST Version/main/ch2_drift_kinetic.tex", "max_issues_repo_name": "rogeriojorge/Rogerio_PhD_Thesis", "max_issues_repo_head_hexsha": "955be22ad75b54d44a3c2d1499098824e7500d38", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IST Version/main/ch2_drift_kinetic.tex", "max_forks_repo_name": "rogeriojorge/Rogerio_PhD_Thesis", "max_forks_repo_head_hexsha": "955be22ad75b54d44a3c2d1499098824e7500d38", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 63.8287292818, "max_line_length": 1197, "alphanum_fraction": 0.6930018177, "num_tokens": 32895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.3422184223852934}}
{"text": "%!TeX root = brillouin_pulse_math\n\\documentclass[paper.tex]{subfiles}\n\\begin{document}\n\n\\section{Dispersion Timothy and the Brillouin Precursors}\n\nUzunoglu \\cite{Theoretical2020} mention a handy way to circumvent the lossy-flesh problem: the Brillouin and Sommerfeld precursors\\footnotemark, and pulse or wavepacket dispersion in tissues in general. The original text of these papers are in German; translations can be found in Léon Brillouin's 1960 book\\cite{Wave1960} on the topic.\n\n\\footnotetext{\"precursor\" is perhaps a misnomer when single pulses are used rather than trapezoidally-modulated tones - Oughston and Najafabadi both call these \\textit{Brillouin pulses}.\\\\ \\cite{Optimal2015} \\cite{Optimal2017} \\cite{Heat2010}.}\n\n\n\nThese are fascinating structures somewhat similar to solitons, which arise as a result of an interplay between two aspects (Albanese \n\\cite{Shortrisetime1989}): \n\n\\begin{itemize}\n\t\\item The highly dispersive nature of tissue (the variation in speed of light with frequency), which causes a peculiar distortion of short pulses (which necessarily have a broadband spectral content).\n\t\\item The variation in loss (the imaginary part of the complex permittivity and the penetration depth) versus frequency. \\wikinote{add image from that mathematica code}\n\\end{itemize}\n\n\nA third aspect leads to the formation of the prototypical Brillouin precursor specifically: any sharp \nbeginning or end of a tone, or other sharply defined structure in a waveform, includes harmonics beyond the tone's carrier wave up to the rise time\\wikinote{add image}.\n\nThe aspect that makes the precursors useful is that they sidestep Bragg's Law decay, with an amplitude that decays as $1/\\sqrt{z}$ rather than $e^{-z}$. Note that Bragg's law is still strictly obeyed in the frequency domain (excepting second-order \"bleaching\" (Lukofsky \\cite{Can}) or induced transparency-like (\\cite{Electromagnetically1997}) effects).\n\nBased on Yang's inactivation thresholds, for instance, at 9 GHz, assuming that a torso is about 10 penetration depths in radius and the hypothetical Brillouin train drives the virus equally effectively as a pure sine, implementing a precursor would decrease the field required at the skin to a perfectly practicable 1 kV/m, rather than an air-ionizing 6.6 MV/m ($\\frac{1}{\\sqrt{10}}=0.316$ versus $e^{-10}=4.5e^{-5}$). \n\nPrecursors have been used in practice, by Ong \\cite{Detection2003}\\footnote{Well, Ong don't really observe the precursor itself directly, it seems.} using simple square waves to detect respiration\\footnotemark, Ossberger \\cite{Noninvasive2004} for the same purpose; and various techniques for tumor detection.\\footnote{TODO: Also another really good paper that I can't find}\n\nWhile it is clearly possible to produce this abnormal penetration (any sharp edge sufficiently distant from suffices to provoke dispersive distortion), it was not obvious to us that a waveform could be constructed that would be an effective driver for the 10 GHz normal modes in question. \n\nFirst, if dispersive pulses are too close together, they interfere as they propagate and diminish the precursor thus formed \\cite{Dynamical2005}.\n\nAs an example, despite the waveform from nonlinear transmission lines\\cite{NLTL6275} producing strong wideband components, in cursory simulations they did not appear to satisfy the requirements for usable Brillouin pulses\\wikinote{dubious-discuss}\\wikinote{citation-needed}. Our working hypothesis is that this is because of destructive interference from the falling edge that immediately follows; but this is mere speculation.\\wikinote{dubious-discuss}\n\nSecond, and most critically, while the pulse amplitude decays slowly, the total energy contained in such a precursor decays very quickly. The biological ramifications of this are discussed in detail by Adair in \\cite{Biophysics2000}.\n\n%temporal Soliton-producing nonlinear transmission lines, and NLTL oscillators constructed therefrom, particularly well suited \n%\n%At a depth of 8 cm in Cole-Cole muscle, an 8 GHz resonance, attack pattern alpha appears to achieve 4 picometers of oscillation amplitude, rather than 0.01 picometers with $\\sin(t\\ \\omega_{resonance})$. The sharp edges are at approx. 250 GHz. \n\nDispersive pulse propagation is easily modelled by a Fourier transform, propagation, and an inverse fourier transform (see Franzen \\cite{Wideband1999}, see also \\cite{Comments1993} and \\cite{Shortrisetime1989})\\footnote{implemented in\\ghfile{/home/arthurdent/Projects/covidinator/electronics/propagation/propagation_numerical_optimize.py}} \\footnote{This isn't truly a transient process, of course - the fourier integral is still periodic, wrapping around the window; it's just more transient than a steady-state}.\n\nThe loss and refractive index can be obtained from a four term Cole-Cole model\\cite{gabriel1996compilation}\\footnote{implemented in\\ghfile{/electronics/simple_fdtd/fdtd_PCB_extensions/fdtd_PCB_extensions/tissue.py}}. We used parameters from the IT.IS Foundation tissue database\\cite{Tissue2018a}. IT.IS Foundation computational phantom 'duke V3.0' was used, \\cite{Duke2014}.\n\n%http://web.physics.ucsb.edu/~fratus/phys103/LN/DHM.pdf\n% section on Greens functions\n% and also \n% and\n% https://www.int.washington.edu/users/dbkaplan/228_01/green.pdf\t\n\n\\pagebreak\nA qualitative statement of the problem we were trying to solve (which may not a useful formulation, especially if Q turns out to be < 1 and the virus exhibits only relaxational and non-resonant behavior):\n\n\\begin{toolchain}\nAn arbitrary waveform propagates through a dispersive, lossy medium with a certain analytic complex \npermittivity. \n\nIt then drives a damped harmonic oscillator that is initially at rest.\\\\\n\nWhat waveform produces the peak transient amplitude on the oscillator?\n\\end{toolchain}\n\n\nEach problem has been solved separately. There are some nearly equivalent but not mathematically identical formulations for optimal control of quantum systems with dispersion.\\footnotemark However, in the classical domain, this appears to be unprecedented in the literature.\n\n\n\\footnotetext{While not strictly related, \\cite{Wavepacket1989} tune a light pulse to match the wavefunction of the desired chemical products in a photo-reaction, which is just pretty darned awesome}\n\nOptimal pulses for several situations in Debye and Lorentz media have been determined by Oughstun's asymptotic method, which appears to be highly satisfactory in terms of physical intution, and also avoids truncation issues that befall fourier-transform techniques. In general, these optimal pulses are simple gaussian monopulses or higher-order gaussian derivatives \\cite{Optimal2017} \\cite{Optimal2015}. \n\nMacke \\cite{Simple2012} have come up with a number of analytic dispersion representations for various signals, such as chirped gaussian pulses; however, as it turns out, it was important that we not constrain ourselves to parameterized shapes.\n\n\n\\subsection{Analytic techniques}\n\n\n\\begin{fquote}[Wait][ \\cite{Propagation1965}]\n\tIn such cases, it may be feasible to evaluate the integral by a purely numerical procedure. With the wide availability of the digital computer, this is certainly fashionable at the moment. Consequently, one might say that the problem has been solved and no further discussion is needed. \\\\\n\t\n\tHowever, it would be a pity if one accepted this answer since all physical insight into the nature of transient processes has been ignored. \n\\end{fquote}\n\n\n\n\\begin{autem}\n\tautem: \nReflection from tissue interfaces?\n\nThermal noise will kick the oscillator around; it won't necessarily start at rest. Will this affect the \n\\end{autem}\n\nOne might suggest try to find the optimal transient solution first, and then try to build an input waveform deconvolved through the  transfer function of the tissue. This hardly seems liable to produce a truly optimal solution, however.\n\n\nAlso, this seems similar to a pulse propagating through the tissue's Cole medium and then dissipating the maximum power in a uniform Lorentz medium, which might be another route to attacking it.\n\nAnother route might be to set up two ODEs for the wave equation and the oscillator and solve them simultaneously.\n\n\\footnote{Progress was hindered by the number of conventions for Fourier normalization. It's all well and good for the signal processing specialists to make all sorts of excuses about brevity, but when crossing fields it's pretty annoying for such a fundamental concept to be so loosely defined. On the same topic, can we finally settle the i vs. j convention, and the choice of reduced units in molecular dynamics?}\n\n%\\printendnotes\n\n\\subsubsection{Attempt at analytical solution: Zhu et al 's dispersive waveform optimization propagation formulation}\n\nWe apologize in advance for the desecration of mathematics in this section.\n\nThe most promising analytical technique explored was a slight modification of a formulation for optimal-energy pulses, largely supplied by Prof. Costas Sarris in a yet-unpublished personal communication, based on Zhu, Hum, Costas formulation in \\cite{Microwave2012b}, previously discussed by Pozar \\cite{Waveform2003}. \n\nThis is based on lagrange multipliers and 'functional' or 'variational' calculus\\cite{Methods1989}. \n\nHere, rather than taking the derivative with respect to a small change in a variable, we take the derivative with respect to a small change in the function itself - a very useful technique \\footnote{that the author was not aware of!} which imposes little to no limitation on the form of the solution. For some intuition, the definition of the first variation and the Gateaux derivative may be of some use.\\footnote{The complex conjugate in Sarris' formulation, $\\nabla H() = H()^\\star$, seems to come from \\cite{Signal1969}, page 140 onwards; I cannot make heads or tails of his formulation. Pozar note that this complex conjugate arises from the concept of \"adjointness\".}\n\nA common setup for such a problem is to use the Euler-Lagrange equation; this is usually brought up in the case of the Brachistochrone problem, or the Principle of Least Action \\footnote{For background, see The Feynman Lectures, vol II chapter 19}. In these types of problems, it appears that the path of integration through space from endpoints a to b can be replaced by the whole frequency domain from -$\\infty$ to +$\\infty$. \n\n$$ e_x(z,t) = \\frac{1}{\\sqrt{2 \\pi}} \\int_{-\\infty}^{+\\infty}{F(\\omega) e^{- j (\\omega/c_0)n(\\omega)z}\\ e^{j\\omega t} d\\omega} $$\n\nwhere $\\int e^{j \\omega t} d\\omega$ is the inverse fourier transform. At this point, you could choose to perform a second integral over the time-domain Greens function solution to the harmonic oscillator\\cite{Complex2020} - or straightforwardly integrate over the frequency-domain Greens function.\n\n\\footnote{Many symbolic math tools have support for functional calculus. However, neither Maxima, SageMath, Mathematica's VariationalD, Matlab's Fundiff, nor Maple's functionalDerivative seem to yield any meaningful result for grad xi.}\\\\\n\n%$$W = \\frac{1}{\\eta_0} \\int_{-\\infty}^{+\\infty}{(n_r(\\omega))\\ |F(\\omega)|^2}\\ d\\omega$$\\\\\n%\n%Where $n(\\omega)$ is a complex refractive index per Debye relaxation equation, $n_r()$ is the real part of the same, everything else is a real constant. Set up a functional with a lagrange multiplier\\\\\n%\n%$$\\xi = -e_x(z,t) + \\lambda W$$\\\\\n%\n%Take the functional (\"variational\") gradient with respect to $F(\\omega)$.\n%\n%$$ \\nabla \\xi = -\\frac{1}{\\sqrt{2\\pi}} \\left(e^{- j (\\omega/c_0)n(\\omega)z}\\right)^\\star \\  e^{-j\\omega T} + \\lambda...$$\n%\n%At this point, you could choose to perform a second integral over the time-domain Greens function solution to the harmonic oscillator\\cite{Complex2020}, eq. 4 and 15, \n%\n%$$x(t) = \\int_{-\\infty}^{+\\infty}{G(t,t')\\ \\frac{q\\cdot e_x(z,t'))}{m}\\ } dt'$$\\\\\n%\n%(eq. 15, for the underdamped case)\n%\n%$$G(t,t') = UnitStep(t-t') \\frac{1}{\\sqrt{\\gamma^2-\\omega_0^2}  }\\sinh\\left({\\sqrt{\\gamma^2-\\omega_0^2}}\\ (t-t')\\right)$$\n%\n%But a much more straightforward \n%\n%Where * is the complex conjugate.\\\\\n\n\n\n\n%\n%Then set\n%\n%$$x(t) = \\int_{-\\infty}^{+\\infty}{G(t,t')\\ \\frac{q\\cdot e_x(z,t'))}{m}\\ } dt'$$\\\\\n%\n%Anyhow, then modify the lagrange multiplier,\n%\n%$$\\xi = -x(t) + \\lambda W$$\\\\\n%\n%And now,\n%\n%$$\\nabla \\xi = 0$$\n\nThis lagrange multiplier technique has, however, a fundamental limitation (noted by Tufts \\cite{Optimum1964}): for reasons that the author does not yet comprehend, only the pulse energy can be used as a constraint, rather than the value of the peak field. This seems to turn out to be of some importance.\n\n\n\\footnote{Note the ni specifically in the complex conjugate!}\n\n\n\\subsection{Laziness prevails; a return to numerical optimization}\n\nNumerically solving optimal control problems using conjugate-gradient was noted by Lasdon \\cite{conjugate1967} and \nrevisited by Kek \\cite{Conjugate}. They reduce the computational workload by first computing the \ngradient function by hand.\n\nUsing an energy constraint as above appears to tend towards a square step function or a sharp impulse, perhaps as a result of Pontryagin's maximum principle\\cite{Optimum1964}.\n\n\\ghfile{electronics/propagation/propagation_numerical_optimize.py}\n\nHowever, a maximum absolute value constraint appears to produce fantastic results.\n\n\n\\begin{figure}[H]\n\t%\t\\makebox[\\textwidth][c]{\n\t\\includesvg[width=\\textwidth]{muscle_pulse_8cm_minimize_test1}\n\t\\caption{}\n\\end{figure}\n\n\nThe (noisy) output of the optimization for z=0.08 m in muscle. The low-frequency component is believed to be due to the FFT window size. Increasing the window size with the same sample rate caused CG convergence to stall. However, it's interesting that this appears to result in a larger amplitude. \n\n\n%\\begin{figure}[H]\n%\t%\t\\makebox[\\textwidth][c]{\n%\t\\includesvg[width=\\textwidth]{muscle_pulse_8cm_minimize_test2}\n%\t\\caption{}\n%\\end{figure}\n\n\n\\begin{figure}[H]\n\t%\t\\makebox[\\textwidth][c]{\n\t\\includesvg[width=\\textwidth]{propagated_waveforms_detail}\n\t\\caption{\\\\\n\t\tSome input (left) and output (right) waves (without considering oscillator coupling) transmitted through 6 cm of muscle.\\\\\n\t\tX axis is time; Y axis is amplitude.\\\\\n\t\t(a) Gaussian monopulse with 16 ps FWHM.\\\\\n\t\t(b) Optimized 10 GHz sawtooth wave. Note the slight high-frequency ripple.\\\\ This has a frequency of approximately 1.5 GHz.\\\\\n\t\t(c) Prototypical precursor 10 GHz sine burst.\\\\\n\t\t(d) Continuous 10 GHz sine tone.\n}\n\\end{figure}\n\n\\begin{figure}[H]\n\t%\t\\makebox[\\textwidth][c]{\n\t\\includesvg[width=\\textwidth]{propagated_waveforms}\n\t\\caption{The same four pulses plotted against depth (Y axis) and amplitude (Z axis)}\n\\end{figure}\n\nOf course, 10x attenuation at 1 MV/m still takes us beyond safe levels at the skin. However, the loss that makes phased-array near-field focusing systems impractical at baseband is no longer as significant of a concern. A dispersive phased array with more than 10 elements may improve penetration further.\n\n\n\n\n\n\n\n\n\\end{document}", "meta": {"hexsha": "b28b2f32a0e7c890e6a6e6ad9eae3d5e6ededa62", "size": 14951, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "documents/brillouin_pulse_math.tex", "max_stars_repo_name": "0xDBFB7/covidinator", "max_stars_repo_head_hexsha": "e9c103e5e62bc128169400998df5f5cd13bd8949", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "documents/brillouin_pulse_math.tex", "max_issues_repo_name": "0xDBFB7/covidinator", "max_issues_repo_head_hexsha": "e9c103e5e62bc128169400998df5f5cd13bd8949", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "documents/brillouin_pulse_math.tex", "max_forks_repo_name": "0xDBFB7/covidinator", "max_forks_repo_head_hexsha": "e9c103e5e62bc128169400998df5f5cd13bd8949", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 66.4488888889, "max_line_length": 673, "alphanum_fraction": 0.780549796, "num_tokens": 3709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251201477015, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.3422184223852933}}
{"text": "\\documentclass[10pt,showpacs,preprintnumbers,footinbib,amsmath,amssymb,aps,prl,twocolumn,groupedaddress,superscriptaddress,showkeys]{revtex4-1}\n\\usepackage{graphicx}\n\\usepackage{dcolumn}\n\\usepackage{bm}\n\\usepackage[colorlinks=true,urlcolor=blue,citecolor=blue]{hyperref}\n\\usepackage{color}\n\\usepackage{listings}\n\n\n\\begin{document}\n\n\n\n\\title{Life  on Devaron, a forest planet with an ancient Jedi Temple.}\n\n\\author{S.~O.~Mebody}\n\\affiliation{Department of Procrastination, University of Akiva}\n\\author{A.~N.~Ybody} \n\\affiliation{Department of Odd Travels, University of Anoat}\n\\author{N.~O.~Body}\n\\affiliation{Department of Even Travels, University of Ambria}\n\n\\begin{abstract}\nWe present the first calculations for rodlike microswimmers from outer space.\n\\end{abstract}\n\n\n\n\\maketitle\n\n\n\n\\section{Introduction}\nThe aim of this project is to get familiar with various vector and matrix operations,\nfrom dynamic memory allocation to the usage of programs in the library\npackage of the course. \nFor Fortran users memory handling and most matrix and vector operations\nare included in the ANSI standard of Fortran 90/95. Array handling in Python is also rather trivial. For C++ user however,\nthere are several possible options. Two are listed here.\n\n\\begin{itemize}\n  \\item For this exercise we recommend that you make your own functions for dynamic memory allocation of a  vector and a matrix. You don't need to write a class for this operations.  Use then the  library package lib.cpp with its header file  lib.hpp for obtaining LU-decomposed matrices, solve linear equations etc.\n\n  \\item A very good and often recommended library for C++ handling of arrays is the library Armadillo, to be found at \\url{arma.sourceforge.net}.  We will discuss the usage of this library during the lab sessions and lectures. Armadillo has also an interface to Lapack functions for solving systems of linear equations.\n\\end{itemize}\n\n\\noindent\nYour program, whether it is written in C++, Python \nor Fortran2008, should include\ndynamic memory handling of matrices and vectors. \n\n\n\\section{Methods and algortihms}\n\n\nMany important differential equations in  Science can be written as \nlinear second-order differential equations\n\n\\begin{equation*}\n\\frac{d^2y}{dx^2}+k^2(x)y = f(x),\n\\end{equation*}\nwhere $f$ is normally called the inhomogeneous term and $k^2$ is a real function.\n\nA classical equation from electromagnetism is Poisson's equation.\nThe electrostatic potential $\\Phi$ is generated by a localized charge\ndistribution $\\rho (\\mathbf{r})$.   In three dimensions \nit reads\n\n\\begin{equation*}\n\\nabla^2 \\Phi = -4\\pi \\rho (\\mathbf{r}).\n\\end{equation*}\nWith a spherically symmetric $\\Phi$ and $\\rho (\\mathbf{r})$  the equations\nsimplifies to a one-dimensional equation in $r$, namely\n\n\\begin{equation*}\n\\frac{1}{r^2}\\frac{d}{dr}\\left(r^2\\frac{d\\Phi}{dr}\\right) = -4\\pi \\rho(r),\n\\end{equation*}\nwhich can be rewritten via a substitution $\\Phi(r)= \\phi(r)/r$ as\n\n\\begin{equation*}\n\\frac{d^2\\phi}{dr^2}= -4\\pi r\\rho(r).\n\\end{equation*}\nThe inhomogeneous term $f$ or source term is given by the charge distribution\n$\\rho$  multiplied by $r$ and the constant $-4\\pi$.\n\nWe will rewrite this equation by letting $\\phi\\rightarrow u$ and \n$r\\rightarrow x$. \nThe general one-dimensional Poisson equation reads then\n\n\\begin{equation*}\n-u''(x) = f(x).\n\\end{equation*}\n\n\nIn this project we will solve the one-dimensional Poisson equation\nwith Dirichlet boundary conditions by rewriting it as a set of linear equations.\n\n\nTo be more explicit we will solve the equation\n\n\\begin{equation*}\n-u''(x) = f(x), \\hspace{0.5cm} x\\in(0,1), \\hspace{0.5cm} u(0) = u(1) = 0.\n\\end{equation*}\nand we define the discretized approximation  to $u$ as $v_i$  with \ngrid points $x_i=ih$   in the interval from $x_0=0$ to $x_{n+1}=1$.\nThe step length or spacing is defined as $h=1/(n+1)$. \nWe have then the boundary conditions $v_0 = v_{n+1} = 0$.\nWe  approximate the second\nderivative of $u$ with\n\n\\begin{equation*}\n   -\\frac{v_{i+1}+v_{i-1}-2v_i}{h^2} = f_i  \\hspace{0.5cm} \\mathrm{for} \\hspace{0.1cm} i=1,\\dots, n,\n\\end{equation*}\nwhere $f_i=f(x_i)$.\nWe  can rewrite this equation as a linear set of equations of the form\n\n\\begin{equation*}\n   \\mathbf{A}\\mathbf{v} = \\tilde{\\mathbf{b}},\n\\end{equation*}\nwhere $\\mathbf{A}$ is an $n\\times n$  tridiagonal matrix which we rewrite as\n\n\\[\n    \\mathbf{A} = \\begin{bmatrix}\n                           2& -1& 0 &\\dots   & \\dots &0 \\\\\n                           -1 & 2 & -1 &0 &\\dots &\\dots \\\\\n                           0&-1 &2 & -1 & 0 & \\dots \\\\\n                           & \\dots   & \\dots &\\dots   &\\dots & \\dots \\\\\n                           0&\\dots   &  &-1 &2& -1 \\\\\n                           0&\\dots    &  & 0  &-1 & 2 \\\\\n                      \\end{bmatrix},\n\\]\nand $\\tilde{b}_i=h^2f_i$.\n\n\nIn our case we will assume  that the source term is \n$f(x) = 100e^{-10x}$, and keep the same interval and boundary \nconditions. Then the above differential equation\nhas a closed-form  solution given by $u(x) = 1-(1-e^{-10})x-e^{-10x}$ (convince yourself that this is correct by inserting the\nsolution in the Poisson equation).  We will compare\nour numerical solution with this result in the next exercise. \n\n\nWe can rewrite our matrix $\\mathbf{A}$ in terms of one-dimensional vectors $a,b,c$  \nof length $1:n$. \nOur linear equation reads\n\n\\[\n    \\mathbf{A} = \\begin{bmatrix}\n                           b_1& c_1 & 0 &\\dots   & \\dots &\\dots \\\\\n                           a_1 & b_2 & c_2 &\\dots &\\dots &\\dots \\\\\n                           & a_2 & b_3 & c_3 & \\dots & \\dots \\\\\n                           & \\dots   & \\dots &\\dots   &\\dots & \\dots \\\\\n                           &   &  &a_{n-2}  &b_{n-1}& c_{n-1} \\\\\n                           &    &  &   &a_{n-1} & b_n \\\\\n                      \\end{bmatrix}\\begin{bmatrix}\n                           v_1\\\\\n                           v_2\\\\\n                           \\dots \\\\\n                          \\dots  \\\\\n                          \\dots \\\\\n                           v_n\\\\\n                      \\end{bmatrix}\n  =\\begin{bmatrix}\n                           \\tilde{b}_1\\\\\n                           \\tilde{b}_2\\\\\n                           \\dots \\\\\n                           \\dots \\\\\n                          \\dots \\\\\n                           \\tilde{b}_n\\\\\n                      \\end{bmatrix}.\n\\]\nWe can compute the relative error  in the data set $i=1,\\dots, n$,by setting up\n\n\\[\n   \\epsilon_i=log_{10}\\left(\\left|\\frac{v_i-u_i}\n                 {u_i}\\right|\\right),\n\\]\nas function of $log_{10}(h)$ for the function values $u_i$ and $v_i$.\nFor each step length extract the max value of the relative error.  \nTry to increase $n$ to $n=10^7$.  Make a table of the results and \ncomment your results. You can use either the algorithm from b) or c). \n\nTo compute the elapsed time in c++ you can use the following statements\n\\begin{lstlisting}\n...\n#include \"time.h\"   //  you have to include the time.h header\nint main()\n{\n    // declarations of variables \n    ...\n    clock_t start, finish;  //  declare start and final time\n    start = clock();\n    // your code is here, do something and then get final time\n    finish = clock();\n    ( (finish - start)/CLOCKS_PER_SEC );\n...\n\\end{lstlisting}\n\n\\section{Our results}\n\nWe present our results in Fig.~\\ref{fig:figure1}.\n\n\\begin{figure} \\label{fig:figure1}\n%\\includegraphics[scale=0.4]{figure1.pdf}\n\\caption{Our results could not be better}\n\\end{figure}\n\n\\section{Conclusions and perspectives}\nWhat a wonderful world!\n\n\\begin{thebibliography}{99}\n\\bibitem{heisenberg} W. Heisenberg, Zeits. f. Physik {\\bf 77}, 1 (1932).\n\\bibitem{miller2006} G.~A.~Miller, A.~K.~Opper, and E.~J.~Stephenson, Annu.~Rev.~Nucl.~Sci.~{\\bf 56}, 253 (2006).\n\\bibitem{ekstrom2015} A.~Ekstr\\\"om, G.~R.~Jansen, K.~A.~Wendt, G.~Hagen, T.~Papenbrock, B.~D.~Carlsson, C.~Forssen, M.~Hjorth-Jensen, P.~Navratil, and W.~Nazarewicz, Phys.~Rev.~C {\\bf 91}, 051301(R) (2015).\n\\bibitem{brown1977} B. A. Brown, A. Arima and J. B. McGrory, Nucl. Phys. {\\bf A277}, 77 (1977) and references therein.\n\\end{thebibliography}\n\n\\end{document}\n\n\n\n", "meta": {"hexsha": "16c8faa99a26e6d52f8f9053c348c3cf49ac52f3", "size": 8086, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/Projects/2017/ReportExamplesLatexstyle/reportexample.tex", "max_stars_repo_name": "solisius/ComputationalPhysics", "max_stars_repo_head_hexsha": "94d32d177881695d443eea34af3410e886b8cb9a", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 220, "max_stars_repo_stars_event_min_datetime": "2016-08-25T09:18:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:09:16.000Z", "max_issues_repo_path": "doc/Projects/2017/ReportExamplesLatexstyle/reportexample.tex", "max_issues_repo_name": "cosmologist10/ComputationalPhysics", "max_issues_repo_head_hexsha": "c6642becb1036e2faaf4f1da78a31785b2033fe7", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-04T12:55:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-04T12:55:10.000Z", "max_forks_repo_path": "doc/Projects/2017/ReportExamplesLatexstyle/reportexample.tex", "max_forks_repo_name": "cosmologist10/ComputationalPhysics", "max_forks_repo_head_hexsha": "c6642becb1036e2faaf4f1da78a31785b2033fe7", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 136, "max_forks_repo_forks_event_min_datetime": "2016-08-25T09:04:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T09:54:21.000Z", "avg_line_length": 36.4234234234, "max_line_length": 319, "alphanum_fraction": 0.6377689834, "num_tokens": 2428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.3422184151282658}}
{"text": "\\documentclass[11pt]{article}\n\n\\usepackage{myreport}\n\\usepackage[american]{babel}\n\\usepackage[backend=biber, sorting=none]{biblatex}\n\\addbibresource{report.bib}\n\n\\begin{document}\n\\title{\\vspace{-2.5em} Excitation and Detection Efficiency Under Light-Sheet\n  Illumination \\vspace{-1.0em}} \\author{Talon Chandler}\n\\date{\\vspace{-1em}June 21, 2017\\\\ (Updated: June 26, 2017)\\vspace{-1em}}\n\\maketitle\n\\section{Introduction}\nIn these notes I will calculate the excitation and detection efficiency of a\nsingle fluorophore under polarized scanned light-sheet illumination. I will\nstart by finding the transverse and longitudinal fields at all positions in a\nGaussian beam using reasonable approximations. Next I will calculate the\nexcitation efficiency of a single fluorophore as the beam is scanned across the\nfluorophore. I will combine these results with the results from previous notes\nto write the complete forward model. Finally I will discuss the approximations\nwe may need to simplify reconstruction.\n\n\\section{Transverse and Longitudinal Fields In A Scanned Gaussian Beam}\nThe complex spatial electric field of a paraxial Gaussian beam propagating along the\n$\\mh{z}$ axis is \\cite{nov}\n\\begin{align}\n  \\mb{E}(x,y,z) &= \\mb{A}\\frac{w_0}{w(z)}\\text{exp}\\left\\{{-\\frac{(x^2+y^2)}{w^2(z)}}+i\\left[kz - \\eta(z) + \\frac{k(x^2+y^2)}{2R(z)}\\right]\\right\\}\\label{eq:gauss}\n\\end{align}\nwhere\n\\begin{alignat}{2}  \n  \\mb{A} &= \\cos\\phi_{\\text{pol}}\\mh{x} + \\sin\\phi_{\\text{pol}}\\mh{y}\\qquad &&\\text{is the input Jones vector in 3D},\\\\\n  w_0 &\\approx \\frac{2n}{k(\\text{NA})}\\qquad &&\\text{is the beam waist radius,}\\\\\n  z_0 &= \\frac{kw_0^2}{2} &&\\text{is the Rayleigh range,}\\\\\n  k &= \\frac{2\\pi n}{\\lambda}\\qquad &&\\text{is the wave number,}\\\\\n  w(z) &= w_0\\sqrt{1+\\frac{z^2}{z_0^2}}\\qquad &&\\text{is the beam radius,}\\\\  \n  R(z) &= z\\left(1+\\frac{z_0^2}{z^2}\\right)\\qquad &&\\text{is the wavefront radius,}\\\\\n  \\eta(z) &= \\text{arctan}\\left(\\frac{z}{z_0}\\right)\\qquad &&\\text{is the phase correction.}\n\\end{alignat}\nEquation \\ref{eq:gauss} uses the paraxial approximation, so it can only be used\nfor beams with a waist that is significantly larger than the reduced wavelength\n($w_0 \\gg \\lambda/n$). Notice that under the paraxial approximation the beam is uniformly polarized in the transverse plane.\n\nWe would like to calculate the longitudinal component of a Gaussian beam when\nthe beam waist approaches the reduced wavelength ($w_0 > \\lambda/n$). One\napproach is to numerically evaluate the Richards-Wolf diffraction integral\n\\cite{richards, biobeam}. This approach is time consuming and too\naccurate for our needs---we only want to model weak longitudinal\nfields. Instead, I will follow Novotny et. al. \\cite{nov} and use a longitudinal\ncorrection to equation \\ref{eq:gauss}.\n\nAs written, equation \\ref{eq:gauss} doesn't satisfy Gauss' law\n($\\nabla \\cdot \\mb{E} = 0$), so we will add a longitudinal field to correct\nit. If the input beam is polarized along the $\\mh{x}$ axis\n($\\phi_{\\text{pol}}=0$), then we can rearrange Gauss' law to relate the\nlongitudinal and transverse fields with\n\\begin{align}\n  E_z(x, y, z) = - \\int \\left[\\frac{\\partial}{\\partial x} E_x(x,y,z)\\right]dz. \n\\end{align}\nCarnicer et al. \\cite{carnicer} worked through this integral using the angular\nspectrum representation and found that\n\\begin{align}\n  E_z(x,y,z) = -i\\frac{2x}{kw_0^2}E_x(x,y,z) = -i\\frac{x}{z_0}E_x(x,y,z)\\label{eq:longit}. \n\\end{align}\n\nEquation \\ref{eq:longit} means that:\n\\begin{itemize}\n\\item There is no longitudinal polarization in the $\\mh{y}-\\mh{z}$ plane\n  because $E_z(0,y,z) = 0$.\n\\item There are longitudinal field lobes on both sides of the optical axis\n  along the transverse polarization direction.\n\\item The factor of $i$ means that the longitudinal fields are $90^{\\circ}$ out\n  of phase with the transverse fields which means that the total field is\n  elliptically polarized off axis.\n\\item The longitudinal field strength is proportional to\n  $\\lambda/w_0^2$---highly focused beams have the strongest longitudinal fields.\n\\end{itemize}\n\nIf the input is polarized along the $\\mh{x}$ axis, the corrected 3D Jones vector is\n\\begin{align}\n\\mb{A}(x,y,z) = \\mh{x}- i\\frac{x}{z_0}\\mh{z}.\n\\end{align}\n\nIf the input polarization is arbitrary then the corrected 3D Jones vector is\n\\begin{align}\n  \\mb{A}(x,y,z) = \\cos\\phi_{\\text{pol}}\\mh{x} + \\sin\\phi_{\\text{pol}}\\mh{y} - i\\frac{x\\cos\\phi_{\\text{pol}} + y\\sin\\phi_{\\text{pol}}}{z_0}\\mh{z}.\n\\end{align}\n\nIf the beam is scanned along the $\\mh{y}$ axis with velocity $v$ then the time\ndependent 3D Jones vector is\n\\begin{align}\n  \\mb{A}(x,y,z,t) = \\cos\\phi_{\\text{pol}}\\mh{x} + \\sin\\phi_{\\text{pol}}\\mh{y} - i\\frac{x\\cos\\phi_{\\text{pol}} + (y - vt)\\sin\\phi_{\\text{pol}}}{z_0}\\mh{z}\\label{eq:scanned_j}\n\\end{align}\nand the time-dependent electric field is\n\\begin{align}\n  \\mb{E}(x,y,z,t) &= \\mb{A}(x,y,z,t)\\frac{w_0}{w(z)}\\text{exp}\\left\\{{-\\frac{(x^2+(y-vt)^2)}{w^2(z)}}+i\\left[kz - \\eta(z) + \\frac{k(x^2+(y-vt)^2)}{2R(z)}\\right]\\right\\}\\label{eq:scanned_e}.\n\\end{align}\nWe will use equations \\ref{eq:scanned_j} and \\ref{eq:scanned_e} to calculate\nthe excitation efficiency of a single fluorophore. Notice that as the Rayleigh\nrange $z_0$ increases the longitudinal electric field decreases, so we can ignore the\nlongitudinal component when the beam is weakly focused.\n\n\\section{Scanned Beam Excitation Efficiency}\nWe define the excitation efficiency of a fluorophore as the fraction of \nincident power that excites the fluorophore. If a fluorophore with absorption\ndipole moment $\\bs{\\mu}_{\\text{abs}}$ is placed in a time-independent complex\nelectric field $\\mb{E}$, then the excitation efficiency is given by\n\\begin{align}\n  \\eta_{\\text{exc}} = \\frac{|\\bs{\\mu}_{\\text{abs}} \\cdot \\mb{E}(x,y,z)|^2}{|\\mb{E}(x,y,z) |^2}.\n\\end{align}\nIf the fluorophore is placed in the path of a scanned laser then the electric\nfield becomes time dependent. If the laser is scanned quickly we would need to\nconsider the coherence of the electric field, but we will only consider slow\nscanning here to simplify the calculation. Specifically, we require that\n$v \\ll w_0/\\tau_c$---the scan velocity must be much less than the beam width\ndivided by the coherence time. In this case the excitation efficiency is\n\\begin{align}\n  \\eta_{\\text{exc}} = \\frac{\\intinf|\\bs{\\mu}_{\\text{abs}} \\cdot \\mb{E}(x,y,z,t)|^2dt}{\\intinf|\\mb{E}(x,y,z,t)|^2dt}\\label{eq:excitationx}\n\\end{align}\nWe plug equation \\ref{eq:scanned_e} into equation \\ref{eq:excitationx}, express\n$\\bs{\\mu}_{\\text{abs}}$ in spherical coordinates\n\\begin{align}\n  \\bs{\\mu}_{\\text{abs}} = \\cos\\Phi\\sin\\Theta\\mh{x} + \\sin\\Phi\\sin\\Theta\\mh{y} + \\cos\\Theta\\mh{z},\n\\end{align}\nand evaluate the integrals (see Appendix for details) to write the\nexcitation efficiency as\n\\begin{align}\n  \\eta_{\\text{exc}} = \\frac{\\sin^2\\Theta\\cos^2(\\Phi-\\phi_{\\text{pol}}) + \\cos^2\\Theta\\frac{x^2\\cos^2\\phi_{\\text{pol}} + \\frac{1}{4}w^2(z)\\sin^2\\phi_{\\text{pol}}}{z_0^2}}{1+\\frac{x^2\\cos^2\\phi_{\\text{pol}} + \\frac{1}{4}w^2(z)\\sin^2\\phi_{\\text{pol}}}{z_0^2}}.\\label{eq:strong}\n\\end{align}\nIf the beam is weakly focused then we can ignore the longitudinal excitation and\nthe excitation efficiency simplifies to\n\\begin{align}\n  \\eta_{\\text{exc}} \\approx \\sin^2\\Theta\\cos^2(\\Phi-\\phi_{\\text{pol}}).\\label{eq:weak_approx}\n\\end{align}\n\n\\textbf{How good is the approximation in equation \\ref{eq:weak_approx}?}\n\nFor longitudinal fluorophores equation \\ref{eq:weak_approx} is a very bad\napproximation---it predicts that a longitudinal fluorophore will not be excited\nat all. We can't use a percentage error because the approximation completely\nignores the excitation of longitudinal dipoles.\n\nInstead, we can compare the size of signals from longitudinal and transverse\nfluorophores. If the signal from longitudinal fluorophores is less than the\nsignal from noise and background, then we can ignore the signal from\nlongitudinal fluorophores.\n\\begin{align}\n  \\text{Excitation Ratio} &= \\frac{\\text{Max Longitudinal Excitation}}{\\text{Max Transverse Excitation}}\\\\\n                          &= \\frac{\\eta_{\\text{exc}}(\\Theta = 0)}{\\eta_{\\text{exc}}(\\Theta = \\pi/2, \\Phi = \\phi_{\\text{pol}})}\\\\\n                          &= \\frac{x^2\\cos^2\\phi_{\\text{pol}} + \\frac{1}{4}w^2(z)\\sin^2\\phi_{\\text{pol}}}{z_0^2}\\label{eq:ratio}\n\\end{align}\n\nAt first glance equation \\ref{eq:ratio} looks bleak---the excitation ratio grows\nwithout bound in the $x$ direction which means that the longitudinal excitation\nbecomes a larger fraction of the total excitation as we move away from the plane\nof the light-sheet. Fortunately, we only care about regions of the beam with a\nhigh intensity, so we look at the intensity-weighted excitation ratio instead.\n\\begin{align*}\n    \\text{Intensity-Weighted Excitation Ratio} &= \\frac{w_0}{w(z)}e^{-\\frac{2x^2}{w^2(z)}}\\frac{x^2\\cos^2\\phi_{\\text{pol}} + \\frac{1}{4}w^2(z)\\sin^2\\phi_{\\text{pol}}}{z_0^2}\\label{eq:intratio} \\\\\n\\end{align*}\nWe can interpret the intensity-weighted excitation ratio as the fraction of the\nmaximum signal (created by a transverse fluorophore at the origin) that we\nignore by ignoring longitudinal excitation. Figure \\ref{fig:error} shows that\nthe intensity weighted excitation ratio is \\textless 2\\% for the imaging parameters used\nin Wu et. al. \\cite{wu2013}.\n\n\\fig{../figures/error.pdf}{1.0}{Intensity-weighted excitation ratio as a\n  function of position using the parameters in Wu et. al. \\cite{wu2013}:\n  $w_0 = 1.2\\ \\mu$m, $z_0 = 9\\ \\mu$m, $\\lambda = 488$ nm, FOV$\\approx$ 80$\\times$80\n  $\\mu$m${}^2$. The maximum values are at the edge of the FOV and are \\textless 2\\%.}{error}\n\nAs a rough heuristic, if the fraction of the signal from noise and background is\ngreater than the intensity-weighted excitation ratio we can justifiably ignore\nthe longitudinal component.\n\nFigure 2 shows the maximum intensity-weighted excitation ratio for an\n80$\\times$80 $\\mu$m${}^2$ FOV as a function of $w_0$. The maximum\nintensity-weighted excitation ratio decreases as $w_0$ increases because wider\nbeams have smaller longitudinal components.\n\n\\fig{../figures/max-error.pdf}{0.5}{Maximum intensity-weighted excitation ration (see equation \\ref{eq:intratio}) for an 80$\\times$80 $\\mu$m${}^2$ FOV with $\\lambda = 488$ nm.}{max-error}\n\n\\section{Detection Efficiency}\nIf we detect fluorescence in wide-field mode with an orthogonal arm and no\npolarizer then the detection efficiency is\n\\begin{align}\n  \\eta_{\\text{det}} = 2A + 2B\\sin^2\\Theta'\n\\end{align}\nwhere\n\\begin{align}\n  A &= \\frac{1}{4} - \\frac{3}{8}\\cos\\alpha + \\frac{1}{8}\\cos^3\\alpha,\\\\\n  B &= \\frac{3}{16}\\cos\\alpha - \\frac{3}{16}\\cos^3\\alpha, \n\\end{align}\n$\\alpha = \\text{arcsin(NA}/n)$ is the detection cone half angle, and $\\Theta'$\nis the angle between the dipole axis and the detection optical axis. See the\n2017-06-09 notes for the relationship between $\\Theta'$ and $\\Theta,\\Phi$. See\n\\cite{fourkas} and the 2017-04-25 notes for the derivation of the detection\nefficiencies and additional expression for detection arms that use a polarizer.\n\n\\section{Orientation Forward Model}\nThe detected intensity is proportional to the the product of the excitation and\ndetection efficiencies. Using a weakly focused excitation beam and an\nunpolarized detection arm gives us the following model\n\\begin{align}\n  I_{\\phi_{\\text{pol}}} &= I_{\\text{tot}}\\sin^2\\Theta\\cos^2(\\Phi - \\phi_{\\text{pol}})(2A+2B\\sin^2\\Theta')\\label{eq:forward}\n\\end{align}\nwhere $I_{\\text{tot}}$ is the intensity we would collect if we had an excitation and detection efficiency of 1.\n\n\\section{Discussion}\nEquation \\ref{eq:strong} shows that for strongly focused beams the excitation\nefficiency is a function of position. This couples the orientation and location\nof the fluorophore and complicates our reconstruction. For now we'll use only\nweakly focused beams so that we can ignore the longitudinal component.\n\nTo ignore the longitudinal component, we require that the fraction of the signal\nfrom noise and background is greater than the intensity weighted excitation\nratio (\\textless 2\\% with current imaging parameters). We'll need to be careful about\nlongitudinal excitation if we want to use beams that are more strongly focused.\n\nUnder the weak-focusing approximation the orientation and position of\nfluorophores are decoupled. This will allow us to split the reconstruction into\ntwo steps (1) estimate the position of the fluorophores using unpolarized frames\n(or the sum of orthogonally polarized frames) with established reconstruction\ntechniques then (2) estimate the orientation or the fluorophores using polarized\nframes and equation \\ref{eq:forward}.\n\nNote that we are working in a different regime than Agrawal et. al. \\cite{agrawal}. They\nare considering imaging systems with better resolution than ours, so the\nposition and orientation are coupled and must be estimated together. At our\nresolution, the position and orientation are decoupled so we can estimate them\nseparately.\n\n\\section{References}\n\\setlength\\biblabelsep{0.025\\textwidth}\n\\printbibliography[heading=none]\n\\pagebreak\n\n\\section{Appendix}\nWe will evaluate the following integrals to find the excitation efficiency\n\\begin{align}\n  \\eta_{\\text{exc}}(x,y,z) = \\frac{\\intinf|\\bs{\\mu}_{\\text{abs}} \\cdot \\mb{E}(x,y,z,t)|^2dt}{\\intinf|\\mb{E}(x,y,z,t)|^2dt}\\label{eq:excitation}\n\\end{align}\nwhere\n\\begin{align}\n  \\bs{\\mu}_{\\text{abs}} &= \\cos\\Phi\\sin\\Theta\\mh{x} + \\sin\\Phi\\sin\\Theta\\mh{y} + \\cos\\Theta\\mh{z}\\\\\n  \\mb{E}(x,y,z,t) &= \\mb{A}(x,y,z,t)\\frac{w_0}{w(z)}\\text{exp}\\left\\{{-\\frac{(x^2+(y-vt)^2)}{w^2(z)}}+i\\left[kz - \\eta(z) + \\frac{k(x^2+(y-vt)^2)}{2R(z)}\\right]\\right\\}\\\\\n  \\mb{A}(x,y,z,t) &= \\cos\\phi_{\\text{pol}}\\mh{x} + \\sin\\phi_{\\text{pol}}\\mh{y} - i\\frac{x\\cos\\phi_{\\text{pol}} + (y - vt)\\sin\\phi_{\\text{pol}}}{z_0}\\mh{z}.\\label{eq:scanned_jones}\n\\end{align}\n\nWe'll need the following facts\n\\begin{align}\n  \\intinf e^{-ax^2}dx &= \\sqrt{\\frac{\\pi}{a}}\\\\\n  \\intinf xe^{-ax^2}dx &= 0 \\label{eq:odd}\\\\ \n  \\intinf x^2e^{-ax^2}dx &= \\frac{1}{2a}\\sqrt{\\frac{\\pi}{a}}.\n\\end{align}\n\nThe numerator is\n\\begin{align}\n  = &\\intinf|\\bs{\\mu}_{\\text{abs}} \\cdot \\mb{E}(x,y,z,t)|^2dt\\\\\n  \\begin{split}\n  = &\\intinf\\Bigg |\\left[\\cos\\Phi\\sin\\Theta\\cos\\phi_{\\text{pol}} + \\sin\\Phi\\sin\\Theta\\sin\\phi_{\\text{pol}} - i\\cos\\Theta\\frac{x\\cos\\phi_{\\text{pol}} + (y - vt)\\sin\\phi_{\\text{pol}}}{z_0}\\right]\\\\\n    &\\ \\ \\ \\ \\ \\ \\ \\ \\frac{w_0}{w(z)}\\text{exp}\\left\\{{-\\frac{(x^2+(y-vt)^2)}{w^2(z)}}+i\\left[kz - \\eta(z) + \\frac{k(x^2+(y-vt)^2)}{2R(z)}\\right]\\right\\}\\Bigg |^2dt.\n  \\end{split}\\\\\n  \\intertext{After changing variables $y' = y - vt$ and moving constants outside the integral we get}\n  = &\\frac{w_0^2}{w^2(z)}e^{-\\frac{2x^2}{w^2(z)}}\\intinf\\left|\\left[\\cos\\Phi\\sin\\Theta\\cos\\phi_{\\text{pol}} + \\sin\\Phi\\sin\\Theta\\sin\\phi_{\\text{pol}} - i\\cos\\Theta\\frac{x\\cos\\phi_{\\text{pol}} + y'\\sin\\phi_{\\text{pol}}}{z_0}\\right]\\right|^2e^{-\\frac{2y'^2}{w^2(z)}}dy'.\n \\intertext{After expanding the square brackets we get}\n   = &\\frac{w_0^2}{w^2(z)}e^{-\\frac{2x^2}{w^2(z)}}\\intinf \\Bigg [(\\cos\\Phi\\sin\\Theta\\cos\\phi_{\\text{pol}} + \\sin\\Phi\\sin\\Theta\\sin\\phi_{\\text{pol}})^2 +\\cos^2\\Theta\\frac{(x\\cos\\phi_{\\text{pol}} +y'\\sin\\phi_{\\text{pol}})^2}{z_0^2} \\Bigg ]e^{-\\frac{2y'^2}{w^2(z)}}dy'\\\\\n   = &\\frac{w_0^2}{w(z)}e^{-\\frac{2x^2}{w^2(z)}}\\sqrt{\\frac{\\pi}{2}}\\Bigg [\\sin^2\\Theta\\cos^2(\\Phi - \\phi_{\\text{pol}})  + \\cos^2\\Theta\\frac{x^2\\cos^2\\phi_{\\text{pol}} + \\frac{1}{4}w^2(z)\\sin^2\\phi_{\\text{pol}}}{z_0^2}  \\Bigg ].\n\\end{align}\nThe denominator is\n\\begin{align}\n  = &\\intinf|\\mb{E}(x,y,z,t)|^2dt\\\\\n  = &\\frac{w_0^2}{w^2(z)}e^{-\\frac{2x^2}{w^2(z)}}\\intinf\\left|\\left[\\cos\\phi_{\\text{pol}}\\mh{x} + \\sin\\phi_{\\text{pol}}\\mh{y} - i\\frac{x\\cos\\phi_{\\text{pol}} + y'\\sin\\phi_{\\text{pol}}}{z_0}\\mh{z}\\right]\\right|^2e^{-\\frac{2y'^2}{w^2(z)}}dy'\\\\\n  = &\\frac{w_0^2}{w^2(z)}e^{-\\frac{2x^2}{w^2(z)}}\\intinf\\left[1 + \\frac{(x\\cos\\phi_{\\text{pol}} + y'\\sin\\phi_{\\text{pol}})^2}{z^2_0}\\right]e^{-\\frac{2y'^2}{w^2(z)}}dy'\\\\\n  = &\\frac{w_0^2}{w(z)}e^{-\\frac{2x^2}{w^2(z)}}\\sqrt{\\frac{\\pi}{2}}\\left[1 + \\frac{x^2\\cos^2\\phi_{\\text{pol}} + \\frac{1}{4}w^2(z)\\sin^2\\phi_{\\text{pol}}}{z^2_0}\\right].\n\\end{align}\nThe final excitation efficiency is\n\\begin{align*}\n\\eta_{\\text{exc}}(x,y,z) = \\frac{\\sin^2\\Theta\\cos^2(\\Phi - \\phi_{\\text{\\text{pol}}}) + \\cos^2\\Theta\\frac{x^2\\cos^2\\phi_{\\text{pol}} + \\frac{1}{4}w^2(z)\\sin^2\\phi_{\\text{pol}}}{z_0^2}}{1 + \\frac{x^2\\cos^2\\phi_{\\text{pol}} + \\frac{1}{4}w^2(z)\\sin^2\\phi_{\\text{pol}}}{z^2_0}}.\n\\end{align*}\n\n\\end{document}\n\n", "meta": {"hexsha": "9b36b4b5d7f7d5dde02fd6423c2cabd248df9110", "size": 16417, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "notes/2017-06-21-light-sheet-illumination/report/report.tex", "max_stars_repo_name": "talonchandler/dipsim", "max_stars_repo_head_hexsha": "04904871924276fd1662ca15b7224166d271c0d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notes/2017-06-21-light-sheet-illumination/report/report.tex", "max_issues_repo_name": "talonchandler/dipsim", "max_issues_repo_head_hexsha": "04904871924276fd1662ca15b7224166d271c0d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notes/2017-06-21-light-sheet-illumination/report/report.tex", "max_forks_repo_name": "talonchandler/dipsim", "max_forks_repo_head_hexsha": "04904871924276fd1662ca15b7224166d271c0d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 58.0106007067, "max_line_length": 274, "alphanum_fraction": 0.7057318633, "num_tokens": 5630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.3421608175009801}}
{"text": "\\chapter{Review of PDF determination}\n\\label{ch:pdfdet}\nUnderstanding the functional structure of parton distributions is a complex task that has been subject to a number of approaches over the years. As nonperturbative quantities describing the behaviour of QCD bound states, in principle they may be subject to analysis using Lattice QCD methods. While a great deal of effort and progress has been made in understanding PDFs through nonperturbative methods~\\cite{Dolgov:2000ca,Horsley:2004uq,Gockeler:2004wp,Schroers:2005rm}, results remain short of providing distributions for practical application at hadron colliders.\n\nThe majority of PDF analyses are therefore performed analogously to the determination of many other QCD parameters; via a fit to appropriate experimental data. The fundamental difficulty in PDF fits being that they are determinations of \\emph{functions} rather than single parameters and therefore one must attempt to find some optimum solution in an (in principle) infinite-dimensional functional parameter space. This is of course complicated by having only a finite set of experimental data points upon which to perform a fit. Moreover as the applications involving PDFs have become more precise, a detailed understanding of the uncertainties in the determination of PDFs has become vital. The problem of PDF fitting is therefore one of finding a reliable estimator for a probability distribution in a space of functions.\n\nThe complexity of the task, along with the inherent ambiguities in the QCD treatment of data, led to the emergence of several competing methodologies and determinations. Today there are a diverse array of fitting groups producing sets of parton distribution functions, the most important of which being the ABM~\\cite{Alekhin:2013nda,Alekhin:2012ig} (formerly ABKM~\\cite{Alekhin:2009ni}), CTEQ/CJ~\\cite{Gao:2013xoa,Lai:2010vv,Nadolsky:2008zw,Owens:2012bv}, JR/GJR~\\cite{JimenezDelgado:2008hf,Gluck:2007ck}, HERAPDF~\\cite{Aaron:2009aa,::2014uva}, MSTW~\\cite{Martin:2009iq,Martin:2012da} (formerly MRST~\\cite{Martin:1998sq,Martin:2001es,Martin:2002dr,Martin:2004dh}) and NNPDF~\\cite{Ball:2012cx,Ball:2011gg,Ball:2011uy,Ball:2011mu,Ball:2010de,Ball:2008by} groups. Typically PDF sets are provided for a variety of theory input parameters such as perturbative order, and value of the strong coupling. All modern PDF sets now include a quantitative assessment of their associated uncertainties. In this chapter we shall review the ingredients and methods utilised in a modern PDF determination, primarily focusing on the methodology of the three global PDF fits recommended for LHC phenomenology by the PDF4LHC working group~\\cite{Botje:2011sn}, namely the procedures of the CTEQ, MSTW and NNPDF collaborations.\n\nThese three groups produce PDF sets determined from a fit to a wide range of experimental data, including DIS, Drell-Yan and inclusive jet cross sections. The CTEQ and MSTW determinations follow a similar fitting procedure and method of uncertainty estimation, with the NNPDF group taking a rather different approach to both. We will now describe the basic fitting procedure of these groups, with an eye to detailing areas where the groups have different solutions.\n\n\\section{Experimental data on parton distributions before the LHC}\nThe most important ingredient in the determination of parton distributions is naturally the selection of the dataset from which to extract PDF constraints. The first step in performing a PDF fit is therefore to identify which datasets are most sensitive to input parton distributions, and offer precise and reliable data. As PDF determinations to date have relied only upon fixed-order perturbation theory, the dataset chosen should probe sufficiently inclusive observables which are therefore relatively insensitive to resummation effects. In general PDF fitting collaborations also require data to be taken at a sufficiently high scale that leading-twist factorisation remains reliable, although there are some exceptions which we shall discuss later in the section. Here we shall briefly discuss some of the most important processes in terms of PDF sensitivity, and review some of the most relevant experimental measurements. For this section we shall restrict ourselves to data available before the start of LHC operation in order to provide a background for the methodological developments made in the light of LHC data. \n\n\\subsubsection{Fixed-Target and collider DIS}\nDeep inelastic scattering data provides the backbone for much of a PDF analysis, and data is available from a wide array of sources. Precise electron-proton scattering data from HERA provides the cleanest probe of proton structure function data, while high-luminosity fixed-target experiments can provide important constraints, at the expense of potentially having to deal with additional data corrections due to nuclear and higher-twist effects. As DIS is one of the best understood scattering processes in QCD, precise theoretical predictions are available up to 3-loop order in the zero-mass scheme~\\cite{Vermaseren:2005qc,Moch:2008fj} and 2-loop order with full heavy quark masses intact~\\cite{Buza:1997mg,Buza:1996xr,Blumlein:2006mh,Bierenbaum:2007qe,Bierenbaum:2007dm,Bierenbaum:2009zt,Blumlein:2014fqa}.\n\nAt leading order, neutral current DIS measurements from a proton target directly probe the quark sea distributions $q_i+\\bar{q}_i$, with the relative power of each flavour contribution mediated via its coupling to $\\gamma,Z$. Charged current, and $Z$-mediated neutral current data can provide some constraint upon PDF flavour separation via the $F^3$ structure function. \n\nIn addition to proton structure function measurements, data obtained from scattering off deuterium targets can be important in constraining light quark flavour separation under the assumption of isospin symmetry. Data may be presented as direct measurements of $F_d$ structure functions or as the ratio $F_d/F_p$. A simultaneous fit to deuterium and proton data may therefore provide important constraints upon the $u-d$ and $u/d$ PDF combinations. Data determined via deuteron scattering are subject to nuclear corrections e.g. shadowing effects~\\cite{Badelek:1994qg} which may be estimated as part of the theoretical treatment or neglected; the corrections to be considered part of the theory uncertainty.\n\nAlongside the direct information on quark distributions, scaling violations present in structure function data provide constraints upon the gluon. While rather indirect, the wealth of DIS measurements available at a wide range of scales provides a great deal of information on the structure of the gluon distribution.\n\nDIS data may be presented either as experimental cross sections, or separated into structure functions. Fixed target structure function data on $F_2$ from muon scattering is available for both proton and deuteron targets from the BCDMS~\\cite{Benvenuti:1989rh,Benvenuti:1989fm}, NMC~\\cite{Arneodo:1996qe,Arneodo:1996kd} and Fermilab E665~\\cite{Adams:1996gu} experiments. Electron scattering $F_2$ data is also available from SLAC data on both proton and deuteron targets~\\cite{Whitlow:1991uw}. The longitudinal structure function $F_L$ is measured in fixed target experiments also by SLAC~\\cite{Whitlow:1990gk} , BCDMS~\\cite{Benvenuti:1989rh} and NMC~\\cite{Arneodo:1996qe}. \n\nIn addition to the large datasets available from fixed target experiments, HERA data provides a clean probe of DIS properties, although with HERA data the separation of cross-sections into structure functions is typically not performed. Neutral current cross-section data is provided by ZEUS~\\cite{Breitweg:1998dz,Chekanov:2001qu,Chekanov:2002ej,Chekanov:2003yv} and H1~\\cite{Adloff:2000qk,Adloff:2000qj,Adloff:2003uh}. Charged-current DIS data is also provided by the HERA collaborations \\cite{Chekanov:2003vw,Adloff:2003uh} along with information on the longitudinal structure function $F_L$~\\cite{Andreev:2013vha,Chekanov:2009na}. Information on charm hadroproduction in DIS is available via $F_2^{\\mathrm{charm}}$ measurements at HERA also~\\cite{Adloff:1996xq,Adloff:2001zj,Aktas:2005iw,Aktas:2004az,Breitweg:1999ad,Chekanov:2003rb,Chekanov:2007ch}. This data provides particular constraint upon the gluon PDF, and has been an important testing ground for heavy quark flavour schemes. The clean $ep$ environment means that data is unaffected by nuclear or deuteron corrections, although low energy datapoints may still suffer from substantial higher-twist corrections. These corrections are typically kept under control by kinematic cuts on the affected points, however some groups (notably the ABM/CJ groups) include the affected data and attempt to model the corrections.\n\nHERA measurements from the two collaborations have been examined as a combined analysis and dataset, so far resulting in two studies of direct interest to PDF determination; a combination of HERA-1 inclusive DIS data~\\cite{aaron:2009wt}, and of charm production cross-sections~\\cite{Abramowicz:1900rp}.\n\n\\begin{figure}[ht!]\n\\centering\n\\includegraphics[width=0.9\\textwidth]{3-PDFdet/figs/d12-172f3.pdf}\n\\caption[Combined reduced charm cross-section data from HERA]{Reduced charm cross-section data from the HERA combined measurement. Data from the measurements contained in the combination analysis is shown for comparison. Figure from \\cite{Abramowicz:1900rp}.}\n\\label{fig:HERAF2c}\n\\end{figure}\n\nThe very large quantity of deep-inelastic scattering measurements performed at a variety of experimental facilities means that generally DIS data forms the backbone for PDF fits, providing a substantial proportion of the experimental data points used in a fit.\n\n\\subsubsection{Neutrino DIS}\nThere are a number of measurements available for the scattering of neutrino beams from heavy nuclear targets. For example the NuTeV~\\cite{Tzanov:2005kr} and CHORUS~\\cite{Onengut:2005kv} data on neutrino $F_2$ and $F_3$. Assuming an approximately isoscalar target, and neglecting CKM factors, the PDF dependence of the neutrino structure function data at leading order is given by~\\cite{Forte:2013wc}\n\\begin{eqnarray}\n\tF_2^\\nu(x) &=& x\\left( u^+(x) + d^+(x) + 2s(x) + 2\\bar{c}(x)\\right), \\\\\n\tF_2^{\\bar{\\nu}}(x) &=& x\\left( u^+(x) + d^+(x) + 2\\bar{s}(x) + 2c(x)\\right),\n\\end{eqnarray}\nand for the $F_3$ structure function,\n\\ba\n\tF_3^\\nu(x) &=& x\\left( u^-(x) + d^-(x) + 2s - 2\\bar{c}\\right), \\\\\n\tF_3^{\\bar{\\nu}}(x) &=& x\\left( u^-(x) + d^-(x) - 2\\bar{s}(x) + 2c(x)\\right).\n\\ea\nA simultaneous fit of these data points therefore provides a good handle upon the valence quark distributions $q-\\bar{q}$. These datasets are relatively precise; however they are subject to potentially large nuclear corrections which introduce an uncertainty that is poorly understood.\n\nNeutrino DIS becomes particularly valuable for PDF determination when considering the semi-inclusive DIS dimuon production process $\\nu N \\to \\mu\\mu X$ illustrated in Figure \\ref{fig:dimuon}. In this process the contribution from initial state strangeness is Cabbibo favoured, therefore providing a direct handle on the strange distribution whose contribution is ordinarily difficult to discern from total structure function measurements. Measurements of this process are therefore commonly used as a strangeness probe, and data has been provided by the NuTeV/CCFR collaborations~\\cite{Goncharov:2001qe}.\n%\n\\begin{figure}[h]\n\\centering\n\\includegraphics[width=0.5\\textwidth]{3-PDFdet/figs/dimuon.pdf}\n\\caption[Leading order diagram for dimuon production in neutrino DIS]{Leading order diagram for dimuon production in neutrino DIS.}\n\\label{fig:dimuon}\n\\end{figure}\n%\n\\subsubsection{Fixed-target and collider Drell-Yan}\nAfter DIS measurements, the production of electroweak vector bosons in hadronic collisions provides the next most important contribution to the constraint of parton densities, with precise predictions available at NNLO in QCD~\\cite{Anastasiou:2003ds,Catani:2009sm,Catani:2010en}.  At leading order the neutral current Drell-Yan process is moderated by the PDF combination\n\t\t\\be q(x_1)\\bar{q}(x_2) +  \\bar{q}(x_1)q(x_2),\\ee\nand provides a direct probe of various partonic combinations depending upon the experimental configuration. In the Drell-Yan process the relevant kinematic variables are the invariant mass of the lepton pair\n\\be M_{ll}^2 = (E_1 + E_2)^2 - (\\mathbf{p}_1 + \\mathbf{p}_2)^2,\\ee\nand the intermediate boson's rapidity, given in the detector frame by\n\\be y = \\frac{1}{2}\\log \\frac{E+ p_L}{E-p_L},\\ee\nwhere $E$ is the detector frame energy of the intermediate boson, and $p_L$ its longitudinal momentum.  in terms of which the parton-$x$ is given by;\n\\be x_\\pm = M_{ll} e^{\\pm y} / \\sqrt{s}, \\ee\nwhere $s$ is the centre-of-mass energy squared of the reaction and the $\\pm$ denotes the parton direction with respect to the beam frame. High rapidity measurements therefore constrain PDFs at both high and low-$x$. \n\nAdditionally the charged-current process $qq^\\prime \\to l^\\pm \\nu_l$ provides information on quark flavour separation in the initial state hadrons. While the rapidity of the lepton pair resulting from $Z/\\gamma$ decay in neutral current Drell-Yan is experimentally straightforward to distinguish, the presence of a neutrino in the final state of $W$ production processes complicates the direct resolution of the $W$ rapidity. Therefore data is often presented in the pseudorapidity of the detected lepton,\n\\be \\eta = -\\log \\tan \\theta,\\ee\ndefined in terms of the angle $\\theta$ between the final state lepton and the beam axis. It can therefore be measured without knowledge of the particle mass and momentum. The pseudorapidity coincides with the standard rapidity in the case of massless particles where $E = |\\mathbf{\\bar{p}}|$.\n\nLepton asymmetries are another common form for experimental results in Drell-Yan, defined in terms of $W^{\\pm}\\to l^\\pm\\nu_l $ differential cross-sections $d\\sigma_{l^\\pm}/d\\eta_l$ as\n\\be \n  A^l_W=\\frac{d\\sigma_{l^{+}}/d\\eta_{l}-d\\sigma_{l^{-}}/d\\eta_{l}}\n  {d\\sigma_{l^{+}}/d\\eta_{l}+d\\sigma_{l^{-}}/d\\eta_{l}}, \n\\ee\nsuch measurements also benefit from the cancellation of shared systematic uncertainties. Measurements of lepton pair production from proton beams incident upon heavy nuclear targets, such as the E605\\cite{Moreno:1990sf} experiment determining dimuon production from a copper target are useful for the constraint of the light quark sea $q+\\bar{q}$. These measurements are typically very precise but suffer from poorly determined nuclear corrections. Several approaches have been performed to study the extent of these corrections~\\cite{deFlorian:2003qf,Hirai:2007sx,Kulagin:2007ju,Eskola:2009uj}, although the effects are typically small and may sometimes be discounted in comparison to experimental uncertainties~\\cite{Ball:2009mk}. Contributions from initial state heavy quarks and strangeness are typically suppressed in these measurements due to the relatively low scales.\n\n\\begin{figure}[ht]\n\\centering\n\\includegraphics[width=0.45\\textwidth]{3-PDFdet/figs/ncdy.pdf}\n\\includegraphics[width=0.45\\textwidth]{3-PDFdet/figs/ccdy.pdf}\n\\caption[Leading order diagram for the Drell-Yan process]{Drell-Yan process at leading order, initiated by beam protons with PDF $f_b$ and target protons with PDF $f_t$. The neutral current process is shown on the left, and the charged current process on the right.}\n\\label{fig:ncdy}\n\\end{figure}\n\nFixed target experiments upon hydrogen or deuterium targets provide a relatively clean probe and the ratio of Drell-Yan cross sections in proton to deuteron targets can provide crucial information on the $u/d$ PDF combination. While relatively free of nuclear effects, deuteron data still suffers from poorly understood corrections, which have been the subject of extensive study\\cite{Martin:2012da, Badelek:1994qg,Accardi:2011fa,Brady:2011hb}.\nExperimental measurements from the Fermilab NuSea/E866 collaboration are commonly used, providing data from $pp$~\\cite{Webb:2003bj} and $pd/pp$~\\cite{Towell:2001nh} experiments.  \n\nThe theoretically cleanest environment to examine the Drell-Yan process is at high scales at a collider. Several measurements are available from the Tevatron collaborations which provide information free of nuclear or deuteron corrections. As a $p\\bar{p}$ collider, neutral-current Drell-Yan at the Tevatron targets the quark valence contribution and asymmetry data provides information on the $u/d$ ratio. A measurement of the $Z$ rapidity distribution  is available from D0~\\cite{Abazov:2007jy}, and several measurements are available for $W$ lepton asymmetries from both Tevatron collaborations \\cite{Acosta:2005ud,Abazov:2007pm,Abazov:2008qv,Abe:1998rv}.\n\nIn order to obtain a handle on the contribution of initial state strange quarks to the Drell-Yan process it is once again necessary to examine less inclusive processes. Of particular interest are measurements of $W$ production in association with a charm jet, analogous to the usefulness of dimuon measurements in neutrino DIS where the strange contribution is favoured in terms of CKM elements. Measurements of this process were initially made at the Tevatron by both CDF~\\cite{Aaltonen:2007dm} and D0~\\cite{Abazov:2008qz}. More precise determinations can be obtained by normalisation with respect to the total $W+$ jets rate~\\cite{Stirling:2012vh}. \n\n\\subsubsection{Jet production data}\nWhile DIS data provides constraints upon the gluon distribution via scaling violations and contribution to heavy quark and longitudinal structure functions, DIS and Drell-Yan data do not provide a substantial direct constraint upon gluon densities. The most constraining datasets for the gluon, particularly in the uncertain large-$x$ region, are those of jet production measurements. The large strong coupling of the gluon combined with a high gluon luminosity in the proton at high scales results in $gg$ initiated diagrams being the dominant sub channels for the production of inclusive jet and dijet events.\n\nCross-section calculations for inclusive jet and dijet data in hadron-hadron collisions are available at NLO in QCD~\\cite{Ellis:1992en,Giele:1994gf,Nagy:2001fj,Nagy:2003tz}, however a great deal of progress has been made in the determination of the NNLO corrections~\\cite{Currie:2013dwa,Glover:2001af,Glover:2001rd}, with the exact gluon-gluon sub channel calculation recently determined~\\cite{Currie:2013dza}. For the full calculation however, only approximate NNLO results are available via threshold resummation techniques~\\cite{deFlorian:2013qia,Kidonakis:2000gi,Kumar:2013hia}. Jet data may therefore only be included into an NNLO PDF fit through an approximate treatment if at all.\n\nJet data must be included via some clustering algorithm which takes a QCD final state and identifies suitable jet-like structures. Earlier measurements were performed with so-called cone algorithms, although these are potentially very sensitive to infrared and collinear effects. More recent experiments typically utilise sequential-combination algorithms such as the Cambridge-Aachen~\\cite{Dokshitzer:1997in,Wobisch:1998wt}, $k_T$~\\cite{Ellis:1993tq} or anti$-k_T$~\\cite{Cacciari:2008gp} algorithms, often used as implemented in the efficient {\\tt FastJet}~\\cite{Cacciari:2011ma} package.\n\nThe CDF collaboration has published precise measurements of inclusive jet~\\cite{Abulencia:2007ez,Aaltonen:2008eq} and dijet~\\cite{Aaltonen:2008dn} cross sections. Data is also available from the D0 experiment, once again for inclusive~\\cite{Abazov:2008ae} and dijet~\\cite{Abazov:2010fr} quantities.\nFigure \\ref{fig:CDFkTJet} shows the results of an inclusive jet measurement at CDF using the $k_T$ clustering algorithm.\n\\begin{figure}[ht]\n\\centering\n\\includegraphics[width=0.6\\textwidth]{3-PDFdet/figs/CrossSectionAll.pdf}\n\\caption[Inclusive Jet data from the CDF experiment]{Inclusive jet data from CDF using the $k_T$ jet clustering algorithm, compared to predictions from the CTEQ6.1M PDF set. Figure from~\\cite{Abulencia:2007ez}. }\n\\label{fig:CDFkTJet}\n\\end{figure}\n\n\\subsubsection{Prompt photon measurements}\nComplementary to the data on jet production, measurements of prompt photon processes $pp/p\\bar{p} \\to \\gamma X$ can also provide an important handle on the gluon. The term \\emph{prompt} photon refers the production of a photon in the hard scatter rather than in subsequent emissions. Prompt photons in the final state can originate either from Compton scattering processes $gq \\to \\gamma q$ or annihilation events $q\\bar{q} \\to \\gamma g$, processes denoted \\emph{direct} photon production. Alternatively prompt photons may be produced via the fragmentation of final state hadrons into photons via so-called fragmentation functions\\cite{Bourhis:1997yu,Gluck:1992zx}. In $pp$ collisions the Compton scatter is typically the dominant process, particularly at higher scales where the fragmentation contribution is suppressed. For $p\\bar{p}$ events the annihilation contribution becomes more important due to the enhanced $q\\bar{q}$ PDF luminosity. Figure \\ref{fig:jrpromptphoton} demonstrates the relative fraction of these contributions to the cross-section for a range of photon transverse energy $E_T$.\n\\begin{figure}[ht]\n\\centering\n\\includegraphics[width=0.48\\textwidth]{3-PDFdet/figs/subproc_ppgamma_jetphox_lhc_inc_stack.pdf}\n\\includegraphics[width=0.48\\textwidth]{3-PDFdet/figs/subproc_ppgamma_jetphox_lhc_is_stack.pdf}\\\\\n\\includegraphics[width=0.48\\textwidth]{3-PDFdet/figs/subproc_ppgamma_jetphox_tevatron_inc_stack.pdf}\n\\includegraphics[width=0.48\\textwidth]{3-PDFdet/figs/subproc_ppgamma_jetphox_tevatron_is_stack.pdf}\n\\caption[Relative contribution of partonic subprocesses to $pp/p\\bar{p}\\to \\gamma X$]{Relative contribution of partonic subprocesses to $pp/p\\bar{p}\\to \\gamma X$. Figures on the left refer to the inclusive case, and on the right to the observable after isolation cuts on the final state photon. Figure from~\\cite{dEnterria:2012yj}. }\n\\label{fig:jrpromptphoton}\n\\end{figure}\n\nFor the purposes of PDF determination direct photon measurements which are free of the additional uncertainties introduced when performing calculations with photon fragmentation functions are the ideal measurement. While performing selection cuts to measure only the direct photon contribution is experimentally challenging, the relative contribution of fragmentation photons may be suppressed by making isolation cuts upon the final state photon. These cuts admit only photons with no hadronic material in close proximity. Smooth-cone cuts such as the Frixione isolation criterion~\\cite{Frixione:1998jh} in principle can remove entirely the fragmentation contribution. However these cuts remain challenging to implement experimentally, with experimental data usually obtained with simpler isolation cuts which aim to suppress rather than eliminate fragmentation photons.\n\nTheoretical predictions are available at NLO for the Compton process~\\cite{Owens:1987qy,Aurenche:1988vi} and commonly used as implemented in the {\\tt JETPHOX} program~\\cite{Catani:2002ny,Aurenche:2006vj,Belghobsi:2009hx}. While inclusive data is challenging to include in a PDF determination due to contamination by fragmentation photons, results are available from a wide range of isolated photon measurements. Isolated data is available from  UA1/UA2 at the Sp$\\bar{\\mathrm{p}}$S~\\cite{Albajar:1988im,Alitti:1992hn,Ansari:1988te}, PHENIX at RHIC~\\cite{Adler:2006yt}, CDF~\\cite{Aaltonen:2009ty,Abazov:2005wc,Abe:1994rra,Acosta:2002ya,Acosta:2004bg} and D0~\\cite{Abachi:1996qz,Abazov:2001af,Abbott:1999kd}.\n\n\\subsubsection{Top quark pair production data}\nThe production of top-antitop pairs is potentially a process of great interest in the determination of PDFs, with calculations available up to NNLO for the total cross-section~\\cite{Czakon:2013goa,Baernreuther:2012ws,Czakon:2012zr,Czakon:2012pz}. The impact of the total top pair production cross-section upon PDFs is quite sensitive to the kinematics of the collider, with Tevatron data probing directly the quark content of the proton, while data from colliders with higher centre of mass energies being dominated by the gluon-gluon channel. Precise data from the Tevatron is available in the form of a combined D0-CDF analysis~\\cite{Aaltonen:2012ttbar}.\n\n\\subsubsection{Experimental cuts}\n A simple cut is typically performed on the hard scale $Q^2$ and for DIS the final state invariant mass $W^2$ to ensure the reliability of perturbative predictions. The MSTW2008 parton fit uses an initial scale for evolution of $Q_0^2=1$ $\\mathrm{ GeV}^2$, CT10 uses $Q_0^2=1.3$ $\\mathrm{ GeV}^2$ and NNPDF2.3 $Q_0^2=2$ $\\mathrm{ GeV}^2$. Most of the data included in global parton fits has a minimum of $Q^2\\sim2$ to $5$ GeV$^2$\\cite{DeRoeck:2011na}.\n\n\\section{Methodological elements}\n\\subsection{Parametrisation} \nGiven an experimental dataset, one must choose a convenient and effective parametrisation of the parton distribution functions such that their predictions may be compared to data. Nominally there are a total of 13 PDFs, six quarks, six antiquarks and a gluon. However as mentioned in the previous section, the heavy quarks $c$, $b$, $t$ are determined perturbatively. There are therefore typically seven free PDFs remaining to be fitted. The parton parametrisation basis is chosen for ease of fitting and perturbative evolution; a basis close to the DGLAP basis in Eqn.~\\ref{eq:DGLAP} is desirable for efficiency. However often a different basis is chosen to avoid fitting quantities that are poorly defined by the experimental dataset. \n\nFor example, MSTW2008\\cite{Martin:2009iq} uses the following basis for their determination:\n\\ba\n\tg,&& \\nonumber\\\\\n        q_v &\\equiv & q - \\bar{q},\\nonumber \\\\\n\t\\Delta &\\equiv & \\bar{d} - \\bar{u},\\nonumber \\\\\n\tS &\\equiv & 2(\\bar{u}+\\bar{d})+s+\\bar{s}\\nonumber,\\\\\n\ts^\\pm &\\equiv & s \\pm \\bar{s},\n\t\\ea\t\nwhere g is the gluon PDF and the $q_v$ correspond to the $u$, $d$ quark valence PDFs. These fully parameterise the degrees of freedom to be determined. A functional form in $x$ is then chosen for each of the distributions (the value of $Q^2$ is kept fixed at the input scale for fitting). While all groups include the limiting-$x$ description of Eqn.~\\ref{eq:pdflimits}, the choice of parametrisation for the remainder function $r$ varies substantially between fitting groups. As an example, the valence quark PDF $q_v$ parametrisation in MSTW2008 is provided by the expression\n\\be xq_v(x,Q_0^2) = ax^{b}(1-x)^{c}(1+d\\sqrt{x}+e x),\\ee\nand the equivalent parametrisation in CT10\\cite{Lai:2010vv} is \n\\be xq_v(x,Q_0^2) = ax^b(1-x)^b \\exp{(cx + dx^2 + e\\sqrt{x})},\\ee\nwhere the $(a$,...,$e)$ are the parameters to be determined in the fit. In total the MSTW08 basis has 30 free parameters (taking into account sum rule constraints), the CT10 parametrisation is a little less flexible, having 26 free parameters. The problem is now reduced to finding the optimum parameters for the $7$ PDFs that minimise some measure of fit quality, the differing versions of which we shall discuss later in the chapter.\n\nThe NNPDF procedure is markedly different from that of the other PDF fitting groups and the first major difference lies in the choice of parametrisation. Unlike in the general procedure outlined above, neural networks are used to provide the functional $x$ dependence of the PDFs. Neural networks are a typical computational tool in machine learning environments, often used in regression applications where flexibility and a lack of bias with respect to a conventional fixed parametrisation are desired. A typical neural network in a fitting context will usually have considerably more functional freedom (and therefore parameters) than a normal parametric model, with the neural network compensating for its relative generality with respect to the problem by having much greater flexibility. \n\nThe use of neural networks as applied to the determination of the proton structure function $F_2^p$ was first suggested in Ref.~\\cite{Forte:2002fg} and subsequently developed in~\\cite{DelDebbio:2004qj}. The approach was later extended to the determination of quark distributions~\\cite{DelDebbio:2007ee} before becoming a global analysis of PDFs as of NNPDF2.0~\\cite{Ball:2010de} as part of the wider NNPDF methodology.\n\nIn the NNPDF approach the specific networks used in the parametrisation are multi-layer feed forward neural networks configured with 2-5-3-1 architecture. This architecture applied over seven PDFs results in a fit with a total of 259 free parameters, considerably more than in competing approaches. The architecture chosen in fact has considerable redundancy to minimise potential bias due to inflexibility or choice of architecture. The flexibility of the approach was demonstrated in Ref.~\\cite{Ball:2011eq} where the architecture was modified considerably, with no significant change in the fit results.\n\nDue to the redundant parametrisation provided by the neural networks, there is a great deal of freedom in the choice of the input parton distribution basis. In the more recent NNPDF analyses: sets NNPDF 2.1 and NNPDF 2.3, the basis is chosen for simplicity of evolution as:\n\\ba\n\\mathrm{gluon}\\quad \\quad&g,& \\nonumber \\\\\n\\mathrm{singlet}\\quad \\quad&\\Sigma &\\equiv  \\sum_{i=1}^{n_f} (q_i + \\bar{q_i}),\\nonumber \\\\\n\\mathrm{valence}\\quad\\quad &V &\\equiv  \\sum_{i=1}^{n_f} (q_i - \\bar{q_i}),\\nonumber \\\\\n\\mathrm{triplet}\\quad\\quad &T_3 &\\equiv   (u + \\bar{u}) - (d+\\bar{d}),\\nonumber \\\\\n\\mathrm{sea}\\; \\mathrm{asymmetry}\\quad\\quad &\\Delta &\\equiv  \\bar{d}-\\bar{u},\\nonumber \\\\\n\\text{strange sea/valence}\\quad\\quad &s\\pm &\\equiv  s \\pm \\bar{s}.\n\\ea\n\\clearpage\nThe equivalent functional forms for the fitting in terms of the Neural Networks are;\n\\ba \\Sigma(x,Q_0^2)&=&x^{-\\alpha_\\Sigma}(1-x)^{\\beta_\\Sigma} \\mathrm{NN}_\\Sigma(x), \\nonumber  \\\\\nV(x,Q_0^2)&=&A_V x^{-\\alpha_V} (1-x)^{\\beta_V} \\mathrm{NN}_V(x),\\nonumber \\\\\nT3(x,Q_0^2)&=&x^{-\\alpha_{T3}}(1-x)^{\\beta_{T3}} \\mathrm{NN}_{T3}(x),\\nonumber \\\\\n\\Delta(x,Q_0^2)&=&A_\\Delta x^{-\\alpha_\\Delta}(1-x)^{\\beta_\\Delta} \\mathrm{NN}_\\Delta(x),\\nonumber \\\\\ng(x,Q_0^2)&=&A_gx^{-\\alpha_g}(1-x)^{\\beta_g} \\mathrm{NN}_g(x)\\nonumber, \\\\\ns^+(x,Q_0^2)&=&x^{-\\alpha_{s^+}} (1-x)^{\\beta_{s^+}}\\mathrm{NN}_{s^+}(x),\\nonumber \\\\\ns^-(x,Q_0^2)&=&x^{-\\alpha_{s^-}}(1-x)^{\\beta_{s^-}} \\mathrm{NN}_{s^-}(x) - s_{\\mathrm{aux}}(x,Q_0^2), \\label{eq:NNPDF23param}\n\\ea\nwhere the NN denote the 2-5-3-1 neural network parametrisations and the $A$ are set by enforcing the appropriate sum rules. In the NNPDF approach the treatment of the limiting exponents $\\alpha$, $\\beta$ is rather different. These factors are introduced in order to speed up the convergence of the neural network fitting, with the intention of providing a rough preprocessing function as a backbone for the neural networks to deviate from, and ensuring that the functions have the correct behaviour under integration. These exponents are therefore randomised within an optimised range at the start of the fit and are not modified by the fitting procedure. The final results should therefore be reasonably independent of the preprocessing factor and of the coefficients involved. \n\\\\\nWhile determinations with fixed parametrisations typically design the strange valence functional form such that the strange valence sum rule is automatically satisfied, this cannot be done with a neural net parametrisation. In the determinations up to NNPDF2.3 the strange auxiliary term $s_{\\mathrm{aux}}(x,Q_0^2)$ in Eqn.~\\ref{eq:NNPDF23param} is therefore introduced to ensure the strange valence sum rule is followed, and has the form~\\cite{Ball:2009mk}:\n\\be s_{\\mathrm{aux}}(x,Q_0^2) = A_{s^-}(x^{r}(1-x))^s.\\ee\n\\subsection{Fit quality and minimisation}\nWith an experimental dataset selected and a choice made for the parametrisation of the PDFs, the optimal fit should be determined by varying fit parameters and attempting to minimise some measure of fit quality. Different groups make quite different choices not only in the minimisation method but also in the measure used to determine fit quality. The most general statement that can be made is that the global fit quality (generally denoted $\\chi^2$) is built from the quality of fit to individual datasets as\n\n\\be \\chi^2 = \\sum_k^{n} \\chi^2_k,\\ee\nfor a fit with $n$ data sets, each with a consistent normalisation. In the NNPDF approach the full covariance matrix of the data is used in determining the quality of fit, including all appropriate correlations within and between datasets. The $\\chi^2$ measure for a set of data with common correlations is then given by\n\\be \\chi^2_k=\\sum_{i,j=1}^{N_{\\mathrm{dat}}}\\frac{(D_{k,i}-T_{k,i})(D_{k,j}-T_{k,j})}{\\mathrm{Cov}[i,j]}.\\ee\nHere the $T$ are the theoretical predictions for the experimental data points $D$ calculated from the neural network parametrisation, and $\\mathrm{Cov}[i,j]$ is the covariance between data points $i$ and $j$. In practice there is a ensemble of neural networks each associated with a single Monte Carlo sample of the experimental data, for the purposes of error propagation. This point will be discussed in more detail later in the chapter.  In NNPDF determinations the full experimental correlations should be available for a dataset to be included into the determination.\nOther groups take a different strategy, often with the suggestion that correlation effects are small to negligible with the exception of overall normalisations. Adopting the same practice as earlier MRST fits, the MSTW2008 fit uses an uncorrelated $\\chi^2$ measure over much of its dataset~\\cite{Martin:2009iq}, with the normalisation of the theory predictions set by a fitted parameter $\\mathcal{N}$\n\\be \\chi^2_k=\\sum_{i=1}^{N_{\\mathrm{dat}}} \\frac{(D_{k,i}-T_{k,i}/\\mathcal{N}_k)^2}{\\mathrm{Var}[i]} + \\left(\\frac{1-\\mathcal{N}_k}{\\sigma_k^{\\mathcal{N}}}\\right)^4, \\label{eq:MSTWchi2}\\ee \nwhere the final quartic penalty is intended to prevent the normalisation deviating too far from the experimental normalisation uncertainty $\\sigma_{\\mathcal{N}}$, and the variance $\\mathrm{Var}[i]$ is constructed by the sum in quadrature of the statistical and uncorrelated systematic errors. The CT series of fits utilise a $\\chi^2$ measure that includes systematic uncertainties in terms of explicit shifts~\\cite{Stump:2001gu,Pumplin:2002vw}. In this arrangement, the fit quality measure is given by\n\\begin{equation} \\label{eq:CTchi2}\n\\chi^{2}_k =  \\sum_{i=1}^{N_{\\mathrm{dat}}} \\frac{1}{%\n\\mathrm{Var}[i]} \\left(D_{k,i}-T_{k,i}-\\sum_{n=1}^{N_{\\mathrm{corr}}}r_{n}\\sigma^{\\mathrm{corr}}_{k,n,i}\\right)^{2}\n+\\sum_{n=1}^{N_{\\mathrm{corr}}} r_{n}^{2},\n\\end{equation}\nwhere here the $\\sigma^{\\mathrm{corr}}$ are the $N_{\\mathrm{corr}}$ correlated systematic uncertainties. In this procedure the theory predictions $T$ are shifted parametrically by the variables $r$. The optimal shift values are found by minimising the $\\chi^2$ with respect to the $r$ analytically at each stage of the fit. This procedure was introduced to accommodate for overall shifts in the CT10 distributions. A similar method which was adopted in MSTW2008 for a limited number of datasets where correlations were deemed to be important, with the normalisations also determined in the fit as per the uncorrelated case.\n\n\\subsubsection{Normalisation uncertainty}\n\nA key point that must be addressed when constructing a measure of fit quality is the treatment of normalisation uncertainties, or multiplicative uncertainties in general. Even using the same definition of the fit quality measure, substantial deviations may be produced by defining the covariance matrix and therefore the breakdown into systematic errors, differently.\n\nThe full experimental uncertainty information is characterised by the sum of all uncorrelated errors for a datapoint $\\sigma^{\\mathrm{unc}}$; the set of $N_{\\mathrm{add}}$ correlated additive systematics $\\sigma^{\\mathrm{add}}$; and the set of $N_{\\mathrm{mul}}$ correlated multiplicative systematics $\\sigma^{\\mathrm{mul}}$.\nGiven this information one may naively define an \\emph{`experimental'} prescription~\\cite{Ball:2012wy} for constructing a covariance matrix as\n\\be\n\\label{eq:covmat}\n\\mathrm{Cov}[i,j]=\n\\delta_{ij}\\; \\sigma^{\\mathrm{unc}}_{i}\\sigma^{\\mathrm{unc}}_{j} + \n\\sum_{k=1}^{N_{\\mathrm{add}}}\\sigma^{\\mathrm{add}}_{i,k}\\sigma^{\\mathrm{add}}_{j,k}\n+ \\left( \\sum_{k=1}^{N_{\\mathrm{mul}}} \\sigma_{i,k}^{\\mathrm{mul}}\\sigma_{j,k}^{\\mathrm{mul}}\n\\right) D_{i} D_{j},\n\\ee\nwhere once again the $D$ represent the experimental data points. This method of constructing the covariance matrix is therefore unambiguously defined by the experimental results. While a perfectly valid definition for analysing the description of data after a PDF determination, it is unreliable for use directly within a fitting procedure. The use of the experimental definition has for some time been understood to result in a \\emph{d'Agostini bias}\\cite{DAgostini:1993uj}. That is, the theoretical values determined via a minimisation of a $\\chi^2$ function with the experimental covariance matrix are systematically shifted lower than the true value, an effect which only worsens as the number of data points subject to a common multiplicative error increases. The bias is generated by downward statistical fluctuations of data, if these low data points are used to generate the normalisation uncertainty, the result is a smaller uncertainty for the lower points, causing the fit to systematically undershoot the data. \n\nThe typical method employed to avoid the d'Agostini bias proceeds by including the normalisation as a fitted parameter and penalising large deviations as shown in Eqn. \\ref{eq:MSTWchi2}. This procedure largely corrects for the problem, although when applied to a dataset with several different normalisation uncertainties it still suffers from a bias. This effect was demonstrated by the NNPDF collaboration in Ref.~\\cite{Ball:2009qv}.  The bias can be avoided by using the so-called $t_0$ prescription~\\cite{Ball:2009qv} for defining the covariance matrix. In this method the covariance matrix is constructed using the predictions from a previous fit rather than the experimental data values, to multiply with the multiplicative uncertainties.\n\\be\n\\label{eq:covmat_t0}\n\\mathrm{Cov}^{t_0}[i,j]=\n\\delta_{ij}\\; \\sigma^{\\mathrm{unc}}_{i}\\sigma^{\\mathrm{unc}}_{j} + \n\\sum_{k=1}^{N_{\\mathrm{add}}}\\sigma^{\\mathrm{add}}_{i,k}\\sigma^{\\mathrm{add}}_{j,k}\n+ \\left( \\sum_{k=1}^{N_{\\mathrm{mul}}} \\sigma_{i,k}^{\\mathrm{mul}}\\sigma_{j,k}^{\\mathrm{mul}}\n\\right) T_{i}\\, T_{j},\n\\ee\nwhere here the $T$ are theory predictions for the associated datapoint, generated by some prior (fixed) PDF set. The prior, or $t_0$ set should be determined self-consistently via an iterative procedure in which the $t_0$ set is obtained from the previous result for the full fit. As the theory predictions are not subject to the same fluctuations as the data, the fit is not subject to the aforementioned bias. This effect can be seen explicitly in a fit to artificial pseudodata, performed with the experimental and $t_0$ covariance matrix definitions in Figure \\ref{fig:expbias}.\n\n\\begin{figure}[ht]\n\\centering\n\\includegraphics[width=0.8\\textwidth]{3-PDFdet/figs/t0plot.pdf}\n\\caption[Demonstration of d'Agostini bias in a fit to pseudodata generated according to the kinematics of CDF inclusive jet data]{Demonstration of d'Agostini bias in a fit to pseudodata generated according to the kinematics of CDF inclusive jet data. Fit results are shown as a ratio to the `true' value used to generate the pseudodata. The fit performed with the experimental definition of the covariance matrix results in predictions shifted systematically downwards with respect to the underlying law. The predictions from the fit using a $t_0$ covariance matrix do not suffer from such a bias.}\n\\label{fig:expbias}\n\\end{figure}\n\n\\subsubsection{Minimisation}\nWith a figure of merit constructed, the PDF determination now becomes a problem of varying the free parameters in the PDF basis to minimise said measure. Even for those groups utilising a fixed parametrisation, performing a minimisation of the global $\\chi^2$ for a large, $n\\sim\\mathcal{O}(1000)$ dataset with a fairly large number of free parameters (approximately $50$ in the MSTW analysis once normalisation uncertainties are added as free parameters) is a challenging numerical task. For performing the minimisation, the MINUIT~\\cite{MINUIT} package is a common choice, although other function minimisation methods are applied such as the Levenberg-Marquardt~\\cite{levenberg,marquardt} method as used in the MSTW fits.\n\nIn the NNPDF case the minimisation is complicated by the very large number of parameters and highly nonlocal behaviour in the error function, making conventional methods of minimisation difficult. These difficulties are overcome in the NNPDF methodology by the use of \\emph{genetic algorithms}, which are particularly efficient at exploring large parameter spaces. The implementation of the genetic algorithm is discussed in detail in Refs.~\\cite{Ball:2010de,DelDebbio:2007ee}.\n\nIn addition to the basic difficulty of minimisation in a large parameter space, there is a further issue that arises when considering the fitting of a function with a great deal of redundant flexibility. Because of the flexibility of the parametrisation, it is possible that training the neural networks so that each reaches the global minimum in the error function actually results in the networks fitting to statistical noise. This effect is known as \\emph{overlearning} and is a problem often encountered in the training of large neural networks~\\cite{bishopnn,nnoverlearn}. In previous NNPDF determinations, the widely used \\emph{cross-validation} technique~\\cite{Ball:2010de,bishopnn} was employed in order to identify when overlearning occurred. \n\n\\begin{figure}[t!]\n\\centering\n\\includegraphics[scale=0.5]{3-PDFdet/figs/chi2ite-1004-NMC-pd.pdf}\n\\caption[Demonstration of overlearning in the cross-validation of a neural network fit]{A typical signal of overlearning in a neural network fit. E$_{\\mathrm{tr}}$ and E$_{\\mathrm{val}}$ represent the training and validation figures of merit respectively. As the number of genetic algorithm generations proceeds, eventually the network begins to fit statistical noise in the training set and the validation fit quality begins to decrease. Figure from~\\cite{Ball:2010de}.}\n\\label{fig:crossval}\n\\end{figure}\n\nIn this method the experimental data set is split into two separate sets. The first, a fitting set which is used for the minimisation of the error function, and a second validation set which is not used directly in the fitting procedure. For each iteration in the genetic algorithm minimisation the error function is computed between the neural network predictions and both data sets. In the early stages of the training both error functions should decrease. However in the latter stages of the training where statistical noise begins to become an important contribution, the goodness-of-fit calculated to the fitting data set may continue to decrease while the same value calculated to the validation set has stopped decreasing or even begun to increase. This is a clear signal of overlearning, where fitting to statistical noise in the fitting set means that the fit to the validation set is no longer improving. At this stage the training of the neural networks is stopped. A typical signal of overlearning in a cross-validated fit can be seen in Figure~\\ref{fig:crossval} which compares the fit quality for both the training and validated sets over a number of fit iterations.\n\n\\subsection{Error propagation}\n\\label{sec:errors}\nIn order to undertake precision QCD studies, some estimate of the uncertainty on PDFs is required for a meaningful interpretation of the measured observables. The need for PDF sets with quantified uncertainties has been long recognised, and all modern determinations provide sets with at least experimental uncertainty estimation. While performing a comprehensive quantification of the theoretical uncertainty in a PDF fit is challenging, many methods have been developed in order to propagate the uncertainty from the dataset to the fitted PDFs. Ideally, one would like to determine a representation of the probability distribution in the whole functional space. That is given a dataset ${d}$, we would like to find the probability of a certain PDF candidate $f$ such that our fitted PDF central value is given by\n\\be \\left<f\\right>\\left(x\\right) = \\int \\mathcal{D}f \\;f\\left(x\\right)  \\mathcal{P}\\left(f \\middle| d \\right), \\ee\nand the uncertainty by\n\\be \\mathrm{Var}\\left[f\\right]\\left(x\\right) = \\int \\mathcal{D} f \\; \\left[ f\\left(x\\right) - \\left<f\\right>\\left(x\\right) \\right]^2   \\mathcal{P}\\left(f \\middle| d \\right). \\ee\nThe probability distribution for an observable $\\mathcal{O}$ is then simply $\\mathcal{O}\\left[f\\right]\\mathcal{P}\\left(f \\middle| d \\right)$, in terms of which an observable's central\nvalue and PDF uncertainty can be calculated by\n\\be \\left<O\\right> = \\int \\mathcal{D}f \\; \\mathcal{O}\\left[f\\right]  \\mathcal{P}\\left(f \\middle| d \\right), \\ee\n\\be \\mathrm{Var}\\left[\\mathcal{O}\\right] =  \\int \\mathcal{D}f \\; \\left(\\mathcal{O}\\left[f\\right] - \\left<\\mathcal{O}\\right> \\right)^2 \\;\\mathcal{P}\\left(f \\middle| d \\right). \\ee\nThe probability distribution $\\mathcal{P}\\left(f \\middle| d \\right)$ is however a difficult quantity to determine. In this section we shall examine a number of the methods used in the literature to provide an estimate of PDF uncertainties.\n\\subsubsection{The Hessian method}\nThe Hessian method is the most widely used method of uncertainty determination in PDFs. In essence, the method involves examining how the fit quality $\\chi^2$ varies when the $n$ fit parameters $a$ are perturbed about the values which minimise the $\\chi^2$, here denoted by $a^\\mathrm{min}$. A tolerance in the $\\chi^2$ variation is then chosen, and the error on an observable is determined geometrically from observables calculated with parameters perturbed by the selected tolerance. To examine this quantitatively, we first define the difference in $\\chi^2$ from the minimum value\n\\be \\Delta\\chi^2(a) \\equiv \\chi^2(a) - \\chi^2(a^\\mathrm{min}) = \\sum^n_{i,j=1}H_{ij}(a_i-a_i^\\mathrm{min})(a_j - a_j^\\mathrm{min}), \\ee\nwhere the $a_i$ represent the $i$th component of the parameter set $a$ (and likewise, for the minimised set $a^\\mathrm{min}$). Here we assume that the variation around the $\\chi^2$ minimum is approximately quadratic. The Hessian matrix $H$ has values determined by\n\\be H_{ij} = \\frac{1}{2}  \\frac{ \\partial^2 \\chi^2(a) }{\\partial a_i\\partial a_j}\\bigg|_{\\mathrm{min}},  \\ee\nwhere the \\emph{min} subscript refers to the parameters obtained at the $\\chi^2$ minimum Early Hessian uncertainty estimates~\\cite{Adloff:2000qk,Alekhin:2002fv} were based upon the standard formula for linear error propagation\n\\be (\\Delta F)^2 = T^2\\sum^n_{i,j=1}\\frac{\\partial F}{\\partial a_i}C_{ij}\\frac{\\partial F}{\\partial a_j}, \\ee\nwhere $T^2=\\Delta\\chi^2$ is the tolerance in $\\chi^2$ variation and $C=H^{-1}$ is the inverse Hessian matrix. This procedure is however a little inconvenient due to the requirement of the partial derivatives of the observable with respect to the fit parameters. There are also numerical issues relating to this method which give rise to peculiar uncertainty estimates~\\cite{DeRoeck:2011na}.  In order to overcome these issues the geometrical method outlined above was developed by the CTEQ collaboration~\\cite{Pumplin:2000vx,Pumplin:2001ct}.\n\nFor this method it is convenient to work in a rescaled orthogonal eigenbasis for the covariance matrix. The orthonormal eigenbasis is defined in the usual way\n\n\\be H v_i = \\lambda_i v_i, \\ee\nand the rescaled eigenbasis is defined as $e_{i}=1/\\sqrt{\\lambda_i} v_{i}$. The difference between a parameter set $a$ and $a^\\mathrm{min}$ can now be expanded as\n\\be a_i-a_i^\\mathrm{min} = \\sum^n_{k=1}e_{ik}z_k, \\ee\nwhere $e_{ik}$ is the $i$th component of the $k$th rescaled eigenvector, and the $z_k$ are the coefficients for the expansion of the parameter difference onto the rescaled eigenbasis.  Therefore the expression for $\\Delta\\chi^2$ reduces to\n\\be\\Delta\\chi^2(a) = \\sum_{k=1}^n z_k^2 \\quad\\quad \\mathrm{or,}\\quad\\quad \\chi^2(a) = \\chi^2(a^\\mathrm{min}) + \\sum^n_{k=1}z_k^2.\\ee\nThis defines a hypersphere in the parameter space of radius $\\Delta\\chi^2$ centred around $a^\\mathrm{min}$, which corresponds to the variation in the parameters that is consistent with the tolerance $T=\\sqrt{\\Delta\\chi^2}$ in the quadratic approximation. It is now possible to construct an ensemble of $2n$ PDF sets corresponding to the fits on the boundaries of the volume. A PDF set $S^\\pm_k$ therefore has the parameter set\n\\be a_i(S_k^\\pm) = a_i^\\mathrm{min} \\pm te^{ik},\\ee\ni.e. each parameter is perturbed by $t$ in the direction of the $e_{k}$ eigenvector. In the quadratic approximation $t=T$, when the approximation breaks down $t$ can be determined by an iterative procedure to obtain the desired $\\Delta\\chi^2$. The error on an observable $F$ is then given simply by Pythagoras' theorem on the hypersphere\n\\be(\\Delta F)^2=\\frac{1}{2}\\sum_i^n(F(S^+_i)-F(S^-_i))^2.\\ee \n\nIn this procedure there is something of an ambiguity in the determination of the tolerance (and hence, the volume of the sphere in parameter space). Ideally the difference in $\\chi^2$ values should be exactly one for a confidence level of one-sigma\\footnote{It should be noted that this is only the case when, either the data errors are uncorrelated, or when the correlations are included in the definition of the global goodness-of-fit $\\chi^2$\\cite{Stump:2001gu}}. In the case of PDF fits, this tolerance often leads to uncertainties far lower than expected. In practice, the CTEQ group uses a value of $\\Delta \\chi^2\\sim 100$ and MSTW uses a value $\\sim50$. The more recent MSTW PDF sets have uncertainties calculated with a dynamically determined tolerance. More specialised fits such as ABM11 or the HERAPDF series,  based upon relatively restrictive datasets may use the standard tolerance of $\\Delta\\chi^2=1$. Their use of a more restrictive dataset perhaps leading to fewer conflicts between experimental datasets that could require a more flexible tolerance.\n\nThe uncertainties produced via the Hessian procedure are difficult to analyse in a statistical sense due to the (occasional) inflation of the $\\Delta\\chi^2$ and the approximations made in the procedure. It is therefore difficult to find a representation in the Hessian approach of the full probability distribution $\\mathcal{P}\\left(f \\middle| d \\right)$. Furthermore the uncertainty in the choice of functional form, or estimation of parametrisation bias, is not typically take account of. The HERAPDF family of fits however do attempt to estimate this uncertainty by performing a series of fits with slightly modified parametrisations.\n\n\\subsubsection{Lagrange multiplier method}\nAnother method of error propagation that has been explored is the Lagrange multiplier method. The method has the advantage of not assuming that the $\\chi^2$ function is quadratic around the global minimum. We shall briefly discuss the method applied to the PDF error determination as suggested by Pumplin~\\cite{Pumplin:2000vx} and Stump~\\cite{Stump:2001gu}. A description of the process can also be found in~\\cite{DeRoeck:2011na,Martin:2009iq}.\n\nFirstly, a general global fit is performed to the data as described above. This yields a set of parameters ${a^\\mathrm{min}}$ which minimise the $\\chi^2$ measure. Using these parameters we calculate\nthe best fit prediction for the observable in question $F(a^\\mathrm{min})$. A new PDF fit can now be performed, where instead of minimising the $\\chi^2$ the following function is minimised\n\\be \\Psi= \\chi^2(a) + \\lambda (F(a)-F(a^\\mathrm{min}))\\ee\ni.e. we introduce the observable $F$ as a parameter in the fitting procedure and constrain the fit so that the minimal $\\Psi$ occurs when $F(a)=F(a^\\mathrm{min})$. The value $\\lambda$ in this function is the Lagrange multiplier. The fit above is performed for many values of $\\lambda$, each time leading to a parameter set that depends on that particular value of $\\lambda$, this parameter set will be denoted $a_\\lambda$. Using these parameters, we now calculate values for $\\chi^2(a_\\lambda )$ and $\\mathcal{O}(a_\\lambda )$.\n\nAt this stage we now have a set of values for $\\chi^2(a_\\lambda)$ and $\\mathcal{O}(a_\\lambda)$ over a large range of $\\lambda$ values. This allows a determination of the relationship between the goodness-of-fit and the prediction for $F$ via the parameter $\\lambda$. We obtain an approximate function $\\chi^2(F)$ over a range of observable values, with a minimum at $F=F(a^\\mathrm{min})$ i.e $\\lambda=0$ and $a_\\lambda=a^\\mathrm{min}$. Also we have a set of the $a$ parameters for every point on the curve which are optimised for the best fit to the observable $F$. This means that we have a set of fully optimised parameters for any arbitrary confidence level determined by the $\\Delta\\chi^2$ that we select as a tolerance. Uncertainties for the PDFs can therefore be given in a way that utilises the whole of the $a$ parameter space, rather than just perturbing around the global minimum as in the Hessian approach.\n\nOf course, the disadvantage of this method is that the PDF uncertainties must be calculated for each observable in a rather computationally intensive process. The errors are naturally optimised for the particular observable, but the process is inconvenient for a PDF end-user, and so it is not widely-used in error determination. In this sense the Lagrange multiplier approach suggests a method of estimating $\\mathcal{P}\\left(\\mathcal{O} \\middle| a \\right)$, or the probability density of an observable in the space of parameters. The Lagrange multiplier method also relies on the same somewhat arbitrary choice of tolerance in $\\chi^2$ as the Hessian method. The method has however been applied as a cross-check to the Hessian results~\\cite{Pumplin:2000vx,Martin:2002aw}.\n\n\\subsubsection{Monte Carlo method}\nAnother quite distinct method of PDF uncertainty determination is the Monte Carlo method, first suggested by Giele and Keller~\\cite{Giele:1998gw,Giele:2001mr} where a Monte Carlo procedure in the space of fit parameters was outlined. The NNPDF collaboration uses a similar method in all of its fits, although with the Monte Carlo performed in the space of experimental data. The method is designed to faithfully represent the uncertainties present in the initial data, and to propagate the errors in a way that does not assume anything of the nature of the error propagation. The Monte Carlo approach was also analysed and compared to the results of a Hessian fit by the MSTW group in~\\cite{Watt:2012tq}.\n\nIn the Monte Carlo procedure an ensemble of $N_{\\text{rep}}$ artificial data replicas is produced for every data point in the fit, generated according to the probability distribution of the initial data. Typically this distribution is multi-Gaussian with central values and variances provided by experimental results, but any probability distribution may be used if required. If we use $F_{p}^{(\\mathrm{art})(k)}$ to represent a single element $k$ of the pseudo-data sample (the \\emph{art} superscript designates the data as an artificial sample) of the observable $F$ at the kinematical point $\\left\\{ x_p,Q^2_p \\right\\} $. Then we can generate such a pseudo-data element as in~\\cite{Ball:2008by} by\n\\be F_{p}^{(\\mathrm{art})(k)}=S_{p,N}^{(k)}F_{p}^{(exp)}\\left( 1 + \\sum_{l=1}^{N_c}r_{p,l}^{(k)}\\sigma_{p,l} + r_{p}^{(k)}\\sigma_{p,s}\\right),\\ee\nwhere the $r$ are independent Gaussian random numbers centred upon the experimental central value. The $\\sigma_{p,s}$ term contains the uncorrelated systematic uncertainties and the statistical uncertainty added in quadrature. The $\\sigma_{p,l}$ are the correlated errors for the data provided by experiment. The normalisation of the probability distribution is fixed by the term $S_{p,N}$. Provided a large enough quantity of these artificial replicas ($N_{\\mathrm{rep}}$) is generated, this form of the generating distribution for the Monte Carlo ensemble reproduces all of the statistical qualities of the original experimental data. In Ref.~\\cite{Ball:2010de} it is demonstrated that $N_{\\mathrm{rep}}=1000$ is sufficient to reproduce the experimental central values and variances to an accuracy of better than one percent.\n\nNow that a good Monte Carlo sample of the experimental data is available, instead of performing just the one fit to the data, $N_{\\mathrm{rep}}$ independent fits are performed, one for each of the data replicas. At the end of the fitting procedure we obtain an ensemble of $N_{\\mathrm{rep}}$ equally probable PDFs which reliably describe the probability distribution of the PDFs based upon the original experimental uncertainties. The central values and uncertainties of an observable can be simply obtained by computing the average and the variance over the ensemble of PDFs.\n\\be \\left< F\\right> = \\frac{1}{N_{\\mathrm{rep}}}\\sum_i^{N_{\\mathrm{rep}}} F^{(k)}, \\label{eq:MCCV}\\ee\n \\be \\sigma^2[F] = \\frac{1}{N_{\\mathrm{rep}}-1} \\sum_{i=1}^{N_{\\mathrm{rep}}} (F^{(k)} - \\left< F\\right>)^2, \\label{eq:MCVAR}\\ee\n where $F^{(k)}$ denotes the observable $F$ computed using PDF replica $k$.\n\nThe Monte Carlo method therefore propagates the errors from the experimental data through to the PDFs in a natural way, without the need for a linear propagation of errors assumption, or the need for an inflated tolerance in the $\\chi^2$ distribution. Figure \\ref{fig:mcerror} demonstrates a Monte Carlo ensemble of PDF replicas for the gluon distribution.\n\n\\begin{figure}[ht]\n\\centering\n\\includegraphics[width=0.48\\textwidth]{3-PDFdet/figs/pdf_xg_log_rep.pdf}\n\\includegraphics[width=0.48\\textwidth]{3-PDFdet/figs/pdf_xg_rep.pdf}\n\\caption[A Monte Carlo representation of the gluon PDF probability distribution]{A Monte Carlo representation of the gluon PDF probability distribution. Individual PDF replicas are shown as green lines, and the ensemble average, standard deviation and 68\\% confidence level are shown.}\n\\label{fig:mcerror}\n\\end{figure}\n\n%\n%In the NNPDF approach the method has another benefit. Considering again the method of cross-validation used to prevent overfitting in the neural network parametrisation. At first glance, it would seem that separating the data sets into a fitting and validation set means that not all of the data is directly used in a fit. However, as the selection of data points for each set is done at randomly on a replica, by replica basis, for a large enough $N_{\\mathrm{rep}}$ the whole data set is used for fitting across the ensemble.  The use of an ensemble of replicas additionally helps with estimating the functional uncertainty present when determining a function from a finite set of data points. \n%\n%\\subsection{Sources of theoretical uncertainty}\n%\n%\n%Maybe have here a short summary of all the sources of theoretical uncertainty, and how they may be taken into account?\n%alphas, GM scheme, deuteron/nuclear corrections, fragmentation in prompt $\\gamma$, NP uncertainties e.g hadronisation/pileup.\n\n\\section{Status of PDF determination before the LHC}\nIn preparation for the application of parton distributions at the LHC, extensive studies were performed in order to benchmark and understand areas of agreement and discrepancy across fitting collaborations~\\cite{Watt:2011kp,Dittmar:2009ii}. While agreement had generally improved as the level of sophistication applied in parton fits increased, there were still notable regions where PDF fits from the widest datasets remained in disagreement at levels greater than their quoted uncertainties. Figure \\ref{fig:pdflumidiff} illustrates the situation for two important PDF luminosities before the LHC. These discrepancies extended not only to so far unmeasured quantities such as Higgs production cross sections, but also to PDF standard candle observables such as $W$ boson production (c.f. Figure \\ref{fig:standardcandleerror}).\n\n\\begin{figure}[t]\n\\centering\n\\includegraphics[width=0.48\\textwidth]{3-PDFdet/figs/ratiogglumi1_68cl.pdf}\n\\includegraphics[width=0.48\\textwidth]{3-PDFdet/figs/ratioqqbarlumi1_68cl.pdf}\n\\caption[Luminosities for $gg$ and $q\\bar{q}$ PDF combinations at the $7$ TeV LHC]{Luminosities for $gg$ (left) and $q\\bar{q}$ (right) PDF combinations at the $7$ TeV LHC. Figure from~\\cite{Watt:2011kp}.}\n\\label{fig:pdflumidiff}\n\\end{figure}\n\n\n\\begin{figure}[ht]\n\\centering\n\\includegraphics[width=0.48\\textwidth]{3-PDFdet/figs/ggH120GeVLHC7TeVnlo68cl.pdf}\n\\includegraphics[width=0.48\\textwidth]{3-PDFdet/figs/wpmLHC7TeVnlo68cl.pdf}\n\\caption[Predictions for example LHC processes based upon a number of PDF determinations]{Predictions for LHC processes based upon a number of PDF determinations. Left figure: cross section for Higgs production in gluon fusion. Right figure: cross section for the production of $W$ bosons. Figure from~\\cite{Watt:2011kp}.}\n\\label{fig:standardcandleerror}\n\\end{figure}\nThe Les Houches benchmark exercise~\\cite{Dittmar:2009ii} helped to elucidate the methodological source of many of these differences by testing fits from various methodologies to a standard dataset.\n\nMany of the observed discrepancies arise due to differences in the theoretical description of data, with the choice of flavour number scheme providing the largest differences. Dataset choice and methodological choices introducing significant differences also. These differences led to the conservative PDF4LHC recommendation for observables to be calculated as the central contour of the CTEQ-MSTW-NNPDF uncertainty envelope. Despite the differences, for the LHC Run-I the range of available sets allowed for experimental collaborations to effectively explore the differences in the resulting predictions.\n\nWhile providing accurate determinations for use at the LHC has been the primary concern in the years leading up to the LHC's first operation, there was substantial interest in the potential of the LHC to provide constraints upon PDFs and potentially provide discriminating power between sets. Data from the LHC provides the best opportunity for distinguishing the most effective approaches both theoretically and methodologically. Additionally LHC data provides particularly valuable input in the field of collider-only determinations, which aim to provide a cleaner description of data by avoiding the inclusion of nuclear-corrected and low energy data. The inclusion of a large LHC dataset into PDF fits is however a challenging problem, and one which has inspired a great deal of progress in the efficient calculation of collider observables. The remainder of this work will therefore deal with the both the technical inclusion of LHC data into parton distribution fits and the subsequent phenomenological results.\n\n", "meta": {"hexsha": "2631f34b7a0e527cbd543680ec7d0c05606d0545", "size": 62957, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "3-PDFdet/chapter3.tex", "max_stars_repo_name": "nhartland/thesis", "max_stars_repo_head_hexsha": "a58dc2b3d8b218b3893f4a8f0c1e6bcdcc545c55", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "3-PDFdet/chapter3.tex", "max_issues_repo_name": "nhartland/thesis", "max_issues_repo_head_hexsha": "a58dc2b3d8b218b3893f4a8f0c1e6bcdcc545c55", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3-PDFdet/chapter3.tex", "max_forks_repo_name": "nhartland/thesis", "max_forks_repo_head_hexsha": "a58dc2b3d8b218b3893f4a8f0c1e6bcdcc545c55", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 178.3484419263, "max_line_length": 1377, "alphanum_fraction": 0.7912543482, "num_tokens": 15870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.3421608092704867}}
{"text": "\\documentclass[11pt,oneside]{article}\t%use\"amsart\"insteadof\"article\"forAMSLaTeXformat\n\\usepackage{geometry}\t\t%Seegeometry.pdftolearnthelayoutoptions.Therearelots.\n\\geometry{letterpaper}\t\t%...ora4paperora5paperor...\n%\\geometry{landscape}\t\t%Activateforforrotatedpagegeometry\n%\\usepackage[parfill]{parskip}\t\t%Activatetobeginparagraphswithanemptylineratherthananindent\n\\usepackage{graphicx}\t\t\t\t%Usepdf,png,jpg,orepsßwithpdflatex;useepsinDVImode\n\t\t\t\t\t\t\t\t%TeXwillautomaticallyconverteps-->pdfinpdflatex\t\t\n\\usepackage{amssymb}\n\\usepackage[colorlinks]{hyperref}\n\n%----macros begin---------------------------------------------------------------\n\\usepackage{color}\n\\usepackage{amsthm}\n\n\\def\\conv{\\mbox{\\textrm{conv}\\,}}\n\\def\\aff{\\mbox{\\textrm{aff}\\,}}\n\\def\\E{\\mathbb{E}}\n\\def\\R{\\mathbb{R}}\n\\def\\Z{\\mathbb{Z}}\n\\def\\tex{\\TeX}\n\\def\\latex{\\LaTeX}\n\\def\\v#1{{\\bf #1}}\n\\def\\p#1{{\\bf #1}}\n\\def\\T#1{{\\bf #1}}\n\n\\def\\vet#1{{\\left(\\begin{array}{cccccccccccccccccccc}#1\\end{array}\\right)}}\n\\def\\mat#1{{\\left(\\begin{array}{cccccccccccccccccccc}#1\\end{array}\\right)}}\n\n\\def\\lin{\\mbox{\\rm lin}\\,}\n\\def\\aff{\\mbox{\\rm aff}\\,}\n\\def\\pos{\\mbox{\\rm pos}\\,}\n\\def\\cone{\\mbox{\\rm cone}\\,}\n\\def\\conv{\\mbox{\\rm conv}\\,}\n\\newcommand{\\homog}[0]{\\mbox{\\rm homog}\\,}\n\\newcommand{\\relint}[0]{\\mbox{\\rm relint}\\,}\n\n%----macros end-----------------------------------------------------------------\n\n\\title{Domain mapping with LAR\n\\footnote{This document is part of the \\emph{Linear Algebraic Representation with CoChains} (LAR-CC) framework~\\cite{cclar-proj:2013:00}. \\today}\n}\n\\author{Alberto Paoluzzi}\n%\\date{}\t\t\t\t\t\t\t%Activatetodisplayagivendateornodate\n\n\\begin{document}\n\\maketitle\n\\nonstopmode\n\n\\begin{abstract}\nIn this module a first implementation (no optimisations) is done of several \\texttt{LAR} operators, reproducing the behaviour of the plasm  \\texttt{STRUCT} and \\texttt{MAP} primitives, but with better handling of the topology, including the stitching of decomposed (simplicial domains) about their possible sewing. A definition of specialised classes \\texttt{Model}, \\texttt{Mat} and \\texttt{Verts} is also contained in this module, together with the design and the implementation of the \\emph{traversal} algorithms for networks of structures.\n\\end{abstract}\n\n\\tableofcontents\n\n%===============================================================================\n\\section{Introduction}\n%===============================================================================\n\nThe \\texttt{mapper} module, introduced here, aims to provide the tools needed to apply both dimension-independent affine transformations and general simplicial maps to geometric objects and assemblies developed within the LAR scheme. \n\nFor this purpose, a simplicial decomposition of the $[0,1]^d$ hypercube ($d \\geq 1$) with any possible \\texttt{shape} is firstly given, followed by its scaled version with any  according $\\texttt{size}\\in\\E^d$, being its position vector the mapped image of the point $\\mathbf{1}\\in\\E^d$. A general mapping mechanism is specified, to map any domain decomposition (either simplicial or not) with a given set of coordinate functions, providing a piecewise-linear approximation of any curved embedding of a $d$-dimensional domain in any $\\E^n$ space, with $n \\geq d$. \nA suitable function is also given to identify corresponding vertices when mapping a domain decomposition of the fundamental polygon (or polyhedron) of a closed manifold. \n\nThe geometric tools given in this chapter employ a normalised homogeneous representation of vertices of the represented shapes, where the added coordinate is the \\emph{last} of the ordered list of vertex coordinates. The homogeneous representation of vertices is used \\emph{implicitly}, by inserting the extra coordinate only when needed by the operation at hand, mainly for computing the product of the object's vertices times the matrix of an affine tensor. \n\nA set of primitive surface and solid shapes is also provided, via the mapping mechanism of a simplicial decomposition of a $d$-dimensional chart. A simplified version of the PLaSM specification of dimension-independent elementary affine transformation is given as well.\n\nThe second part of this module is dedicated to the development of a complete framework for the implementation of hierarchical assemblies of shapes and scene graphs, by using the simplest possible set of computing tools. In this case no hierarchical graphs or multigraph are employed, i.e.~no specialised data structures are produced. The ordered list model of hierarchical structures, inherited from PHIGS and PLaSM, is employed in this context. A recursive traversal is used to transform all the component parts of a hierarchical assembly into the reference frame of the first object of the assembly, i.e.~in world coordinates.\n\n\n%-------------------------------------------------------------------------------\n%===============================================================================\n\\section{Primitive objects}\n\\label{sec:generators}\n%===============================================================================\n\nA large number of primitive surfaces or solids is defined in this section, using the \\texttt{larMap} mechanism and the coordinate functions of a suitable chart.\n\n%-------------------------------------------------------------------------------\n\\subsection{1D primitives}\n%-------------------------------------------------------------------------------\n\n\\paragraph{Circle}\n%-------------------------------------------------------------------------------\n@D Circle centered in the origin\n@{def larCircle(radius=1.,angle=2*PI,dim=1):\n\tdef larCircle0(shape=36):\n\t\tdomain = larIntervals([shape])([angle])\n\t\tV,CV = domain\n\t\tx = lambda p : radius*COS(p[0])\n\t\ty = lambda p : radius*SIN(p[0])\n\t\treturn larMap([x,y])(domain,dim)\n\treturn larCircle0\n@}\n%-------------------------------------------------------------------------------\n\\paragraph{Helix curve}\n%-------------------------------------------------------------------------------\n@D Helix curve about the $z$ axis\n@{def larHelix(radius=1.,pitch=1.,nturns=2,dim=1):\n\tdef larHelix0(shape=36*nturns):\n\t\tangle = nturns*2*PI\n\t\tdomain = larIntervals([shape])([angle])\n\t\tV,CV = domain\n\t\tx = lambda p : radius*COS(p[0])\n\t\ty = lambda p : radius*SIN(p[0])\n\t\tz = lambda p : (pitch/(2*PI)) * p[0]\n\t\treturn larMap([x,y,z])(domain,dim)\n\treturn larHelix0\n@}\n%-------------------------------------------------------------------------------\n%-------------------------------------------------------------------------------\n\\subsection{2D primitives}\n%-------------------------------------------------------------------------------\nSome useful 2D primitive objects either in $\\E^2$ or embedded in $\\E^3$ are defined here, including 2D disks and rings, as well as cylindrical, spherical and toroidal surfaces.\n\n\\paragraph{Disk surface}\n%-------------------------------------------------------------------------------\n@D Disk centered in the origin\n@{def larDisk(radius=1.,angle=2*PI):\n\tdef larDisk0(shape=[36,1]):\n\t\tdomain = larIntervals(shape)([angle,radius])\n\t\tV,CV = domain\n\t\tx = lambda p : p[1]*COS(p[0])\n\t\ty = lambda p : p[1]*SIN(p[0])\n\t\treturn larMap([x,y])(domain)\n\treturn larDisk0\n@}\n%-------------------------------------------------------------------------------\n\\paragraph{Helicoid surface}\n%-------------------------------------------------------------------------------\n@D Helicoid about the $z$ axis\n@{def larHelicoid(R=1.,r=0.5,pitch=1.,nturns=2,dim=1):\n\tdef larHelicoid0(shape=[36*nturns,2]):\n\t\tangle = nturns*2*PI\n\t\tdomain = larIntervals(shape,'simplex')([angle,R-r])\n\t\tV,CV = domain\n\t\tV = larTranslate([0,r,0])(V)\n\t\tdomain = V,CV\n\t\tx = lambda p : p[1]*COS(p[0])\n\t\ty = lambda p : p[1]*SIN(p[0])\n\t\tz = lambda p : (pitch/(2*PI)) * p[0]\n\t\treturn larMap([x,y,z])(domain,dim)\n\treturn larHelicoid0\n@}\n%-------------------------------------------------------------------------------\n\n\\paragraph{Ring surface}\n%-------------------------------------------------------------------------------\n@D Ring centered in the origin\n@{def larRing(r1,r2,angle=2*PI):\n\tdef larRing0(shape=[36,1]):\n\t\tV,CV = larIntervals(shape)([angle,r2-r1])\n\t\tV = larTranslate([0,r1])(V)\n\t\tdomain = V,CV\n\t\tx = lambda p : p[1] * COS(p[0])\n\t\ty = lambda p : p[1] * SIN(p[0])\n\t\treturn larMap([x,y])(domain)\n\treturn larRing0\n@}\n%-------------------------------------------------------------------------------\n\\paragraph{Cylinder surface}\n%-------------------------------------------------------------------------------\n@D Cylinder surface with $z$ axis\n@{from scipy.linalg import det\n\"\"\"\ndef makeOriented(model):\n\tV,CV = model\n\tout = []\n\tfor cell in CV: \n\t\tmat = scipy.array([V[v]+[1] for v in cell]+[[0,0,0,1]])\n\t\tif det(mat) < 0.0:\n\t\t\tout.append(cell)\n\t\telse:\n\t\t\tout.append([cell[1]]+[cell[0]]+cell[2:])\n\treturn V,out\n\"\"\"\ndef larCylinder(radius,height,angle=2*PI):\n\tdef larCylinder0(shape=[36,1]):\n\t\tdomain = larIntervals(shape)([angle,1])\n\t\tV,CV = domain\n\t\tx = lambda p : radius*COS(p[0])\n\t\ty = lambda p : radius*SIN(p[0])\n\t\tz = lambda p : height*p[1]\n\t\tmapping = [x,y,z]\n\t\tmodel = larMap(mapping)(domain)\n\t\t# model = makeOriented(model)\n\t\treturn model\n\treturn larCylinder0\n@}\n%-------------------------------------------------------------------------------\n\\paragraph{Spherical surface of given radius}\n%-------------------------------------------------------------------------------\n@D Spherical surface of given radius\n@{def larSphere(radius=1,angle1=PI,angle2=2*PI):\n\tdef larSphere0(shape=[18,36]):\n\t\tV,CV = larIntervals(shape,'simplex')([angle1,angle2])\n\t\tV = larTranslate([-angle1/2,-angle2/2])(V)\n\t\tdomain = V,CV\n\t\tx = lambda p : radius*COS(p[0])*COS(p[1])\n\t\ty = lambda p : radius*COS(p[0])*SIN(p[1])\n\t\tz = lambda p : radius*SIN(p[0])\n\t\treturn larMap([x,y,z])(domain)\n\treturn larSphere0\n@}\n%-------------------------------------------------------------------------------\n\\paragraph{Toroidal surface}\n%-------------------------------------------------------------------------------\n@D Toroidal surface of given radiuses\n@{def larToroidal(r,R,angle1=2*PI,angle2=2*PI):\n\tdef larToroidal0(shape=[24,36]):\n\t\tdomain = larIntervals(shape,'simplex')([angle1,angle2])\n\t\tV,CV = domain\n\t\tx = lambda p : (R + r*COS(p[0])) * COS(p[1])\n\t\ty = lambda p : (R + r*COS(p[0])) * SIN(p[1])\n\t\tz = lambda p : -r * SIN(p[0])\n\t\treturn larMap([x,y,z])(domain)\n\treturn larToroidal0\n@}\n%-------------------------------------------------------------------------------\n\\paragraph{Crown surface}\n%-------------------------------------------------------------------------------\n@D Half-toroidal surface of given radiuses\n@{def larCrown(r,R,angle=2*PI):\n\tdef larCrown0(shape=[24,36]):\n\t\tV,CV = larIntervals(shape,'simplex')([PI,angle])\n\t\tV = larTranslate([-PI/2,0])(V)\n\t\tdomain = V,CV\n\t\tx = lambda p : (R + r*COS(p[0])) * COS(p[1])\n\t\ty = lambda p : (R + r*COS(p[0])) * SIN(p[1])\n\t\tz = lambda p : -r * SIN(p[0])\n\t\treturn larMap([x,y,z])(domain)\n\treturn larCrown0\n@}\n%-------------------------------------------------------------------------------\n\n%-------------------------------------------------------------------------------\n\\subsection{3D primitives}\n%-------------------------------------------------------------------------------\n\n\n\\paragraph{Solid Box}\n%-------------------------------------------------------------------------------\n@D Solid box of given extreme vectors\n@{def larBox(minVect,maxVect):\n\tsize = VECTDIFF([maxVect,minVect])\n\tprint \"size =\",size\n\tbox = larApply(s(*size))(larCuboids([1]*len(size)))\n\tprint \"box =\",box\n\treturn larApply(t(*minVect))(box)\n@}\n%-------------------------------------------------------------------------------\n\n\n\\paragraph{Solid Ball}\n%-------------------------------------------------------------------------------\n@D Solid Sphere of given radius\n@{def larBall(radius=1,angle1=PI,angle2=2*PI):\n\tdef larBall0(shape=[18,36]):\n\t\tV,CV = checkModel(larSphere(radius,angle1,angle2)(shape))\n\t\treturn V,[range(len(V))]\n\treturn larBall0\n@}\n%-------------------------------------------------------------------------------\n\n\\paragraph{Solid cylinder}\n%-------------------------------------------------------------------------------\n@D Solid cylinder of given radius and height\n@{def larRod(radius,height,angle=2*PI):\n\tdef larRod0(shape=[36,1]):\n\t\tV,CV = checkModel(larCylinder(radius,height,angle)(shape))\n\t\treturn V,[range(len(V))]\n\treturn larRod0\n@}\n%-------------------------------------------------------------------------------\n\n\\paragraph{Hollow cylinder}\n%-------------------------------------------------------------------------------\n@D Hollow cylinder of given radiuses and height\n@{def larHollowCyl(r,R,height,angle=2*PI):\n\tdef larHollowCyl0(shape=[36,1,1]):\n\t\tV,CV = larIntervals(shape)([angle,R-r,height])\n\t\tV = larTranslate([0,r,0])(V)\n\t\tdomain = V,CV\n\t\tx = lambda p : p[1] * COS(p[0])\n\t\ty = lambda p : p[1] * SIN(p[0])\n\t\tz = lambda p : p[2] * height\n\t\treturn larMap([x,y,z])(domain)\n\treturn larHollowCyl0\n@}\n%-------------------------------------------------------------------------------\n\n\\paragraph{Hollow sphere}\n%-------------------------------------------------------------------------------\n@D Hollow sphere of given radiuses\n@{def larHollowSphere(r,R,angle1=PI,angle2=2*PI):\n\tdef larHollowSphere0(shape=[36,1,1]):\n\t\tV,CV = larIntervals(shape)([angle1,angle2,R-r])\n\t\tV = larTranslate([-angle1/2,-angle2/2,r])(V)\n\t\tdomain = V,CV\n\t\tx = lambda p : p[2]*COS(p[0])*COS(p[1])\n\t\ty = lambda p : p[2]*COS(p[0])*SIN(p[1])\n\t\tz = lambda p : p[2]*SIN(p[0])\n\t\treturn larMap([x,y,z])(domain)\n\treturn larHollowSphere0\n@}\n%-------------------------------------------------------------------------------\n\n\n\\paragraph{Solid torus}\n%-------------------------------------------------------------------------------\n@D Solid torus of given radiuses\n@{def larTorus(r,R,angle1=2*PI,angle2=2*PI):\n\tdef larTorus0(shape=[24,36,1]):\n\t\tdomain = larIntervals(shape)([angle1,angle2,r])\n\t\tV,CV = domain\n\t\tx = lambda p : (R + p[2]*COS(p[0])) * COS(p[1])\n\t\ty = lambda p : (R + p[2]*COS(p[0])) * SIN(p[1])\n\t\tz = lambda p : -p[2] * SIN(p[0])\n\t\treturn larMap([x,y,z])(domain)\n\treturn larTorus0\n@}\n%-------------------------------------------------------------------------------\n\n\\paragraph{Solid pizza}\n%-------------------------------------------------------------------------------\n@D Solid pizza of given radiuses\n@{def larPizza(r,R,angle=2*PI):\n\tassert angle <= PI\n\tdef larPizza0(shape=[24,36]):\n\t\tV,CV = checkModel(larCrown(r,R,angle)(shape))\n\t\tV += [[0,0,-r],[0,0,r]]\n\t\treturn V,[range(len(V))]\n\treturn larPizza0\n@}\n%-------------------------------------------------------------------------------\n\n%===============================================================================\n\\section{Computational framework}\n%===============================================================================\n\\subsection{Exporting the library}\n%-------------------------------------------------------------------------------\n@O larlib/larlib/mapper.py\n@{\"\"\" Mapping functions and primitive objects \"\"\"\nfrom larlib import *\n\n@< Basic tests of mapper module @>\n@< Circle centered in the origin @>\n@< Helix curve about the $z$ axis @>\n@< Disk centered in the origin @>\n@< Helicoid about the $z$ axis @>\n@< Ring centered in the origin @>\n@< Spherical surface of given radius @>\n@< Cylinder surface with $z$ axis @>\n@< Toroidal surface of given radiuses @>\n@< Half-toroidal surface of given radiuses @>\n@< Solid box of given extreme vectors @>\n@< Solid Sphere of given radius @>\n@< Solid helicoid about the $z$ axis @>\n@< Solid cylinder of given radius and height @>\n@< Solid torus of given radiuses @>\n@< Solid pizza of given radiuses @>\n@< Hollow cylinder of given radiuses and height @>\n@< Hollow sphere of given radiuses @>\n@< Symbolic utility to represent points as strings @>\n@< Remove the unused vertices from a LAR model pair @>\n@}\n%-------------------------------------------------------------------------------\n%===============================================================================\n\\subsection{Examples}\n%===============================================================================\n\n\\paragraph{3D rotation about a general axis}\nThe approach used by \\texttt{lar-cc} to specify a general 3D rotation is shown in the following example,\nby passing the rotation function \\texttt{r} the components \\texttt{a,b,c} of the unit vector \\texttt{axis} scaled by the rotation \\texttt{angle}. \n\n%-------------------------------------------------------------------------------\n@O test/py/mapper/test02.py\n@{\"\"\" General 3D rotation of a toroidal surface \"\"\"\nfrom larlib import *\n\nmodel = checkModel(larToroidal([0.2,1])())\nangle = PI/2; axis = UNITVECT([1,1,0])\na,b,c = SCALARVECTPROD([ angle, axis ])\nmodel = larApply(r(a,b,c))(model)\nVIEW(STRUCT(MKPOLS(model)))\n@}\n%-------------------------------------------------------------------------------\n\n\n\\paragraph{3D elementary rotation of a 2D circle}\nA simpler specification is needed when the 3D rotation is about a coordinate axis. In this case the rotation angle can be directly given as the unique non-zero parameter of the the rotation function \\texttt{r}. The rotation axis (in this case the $x$ one) is specified by the non-zero (angle) position.\n\n%-------------------------------------------------------------------------------\n@O test/py/mapper/test03.py\n@{\"\"\" Elementary 3D rotation of a 2D circle \"\"\"\nfrom larlib import *\n\nmodel = checkModel(larCircle(1)(),1)\nmodel = larEmbed(1)(model)\nmodel = larApply(r(PI/2,0,0))(model)\nVIEW(STRUCT(MKPOLS(model)))\n@}\n%-------------------------------------------------------------------------------\n\n\n\n\n%===============================================================================\n\\subsection{Tests about domain}\n%===============================================================================\n\n\\paragraph{Mapping domains}\nThe generations of mapping domains of different dimension (1D, 2D, 3D) is shown below.\n\t\n%-------------------------------------------------------------------------------\n@D Basic tests of mapper module\n@{\"\"\" Basic tests of mapper module \"\"\"\nfrom larlib import *\n\nif __name__==\"__main__\":\n\tV,EV = larDomain([5])\n\tVIEW(EXPLODE(1.5,1.5,1.5)(MKPOLS((V,EV))))\n\tV,EV = larIntervals([24])([2*PI])\n\tVIEW(EXPLODE(1.5,1.5,1.5)(MKPOLS((V,EV))))\n\t\t\n\tV,FV = larDomain([5,3])\n\tVIEW(EXPLODE(1.5,1.5,1.5)(MKPOLS((V,FV))))\n\tV,FV = larIntervals([36,3])([2*PI,1.])\n\tVIEW(EXPLODE(1.5,1.5,1.5)(MKPOLS((V,FV))))\n\t\t\n\tV,CV = larDomain([5,3,1])\n\tVIEW(EXPLODE(1.5,1.5,1.5)(MKPOLS((V,CV))))\n\tV,CV = larIntervals([36,2,3])([2*PI,1.,1.])\n\tVIEW(EXPLODE(1.5,1.5,1.5)(MKPOLS((V,CV))))\n@}\n%-------------------------------------------------------------------------------\n\n\\paragraph{Testing some primitive object generators}\nThe various model generators given in Section~\\ref{sec:generators} are tested here, including LAR 2D circle, disk, and ring, as well as the 3D cylinder, sphere, and toroidal surfaces, and the solid objects ball, rod, crown, pizza, and torus.\n\n%-------------------------------------------------------------------------------\n@O test/py/mapper/test01.py\n@{\"\"\" Testing some primitive object generators \"\"\"\nfrom larlib import *\n\nmodel = larCircle(1)()\nVIEW(EXPLODE(1.2,1.2,1.2)(MKPOLS(model)))\nmodel = larHelix(1,0.5,4)()\nVIEW(EXPLODE(1.2,1.2,1.2)(MKPOLS(model)))\nmodel = larDisk(1)([36,4])\nVIEW(EXPLODE(1.2,1.2,1.2)(MKPOLS(model)))\nmodel = larHelicoid(1,0.5,0.1,10)()\nVIEW(EXPLODE(1.2,1.2,1.2)(MKPOLS(model)))\nmodel = larRing(.9, 1.)([36,2])\nVIEW(EXPLODE(1.2,1.2,1.2)(MKPOLS(model)))\nmodel = larCylinder(.5,2.)([32,1])\nVIEW(STRUCT(MKPOLS(model)))\nmodel = larSphere(1,PI/6,PI/4)([6,12])\nVIEW(STRUCT(MKPOLS(model)))\nmodel = larBall(1)()\nVIEW(EXPLODE(1.2,1.2,1.2)(MKPOLS(model)))\nmodel = larSolidHelicoid(0.2,1,0.5,0.5,10)()\nVIEW(STRUCT(MKPOLS(model)))\nmodel = larRod(.25,2.)([32,1])\nVIEW(STRUCT(MKPOLS(model)))\nmodel = larToroidal(0.5,2)()\nVIEW(STRUCT(MKPOLS(model)))\nmodel = larCrown(0.125,1)([8,48])\nVIEW(STRUCT(MKPOLS(model)))\nmodel = larPizza(0.05,1,PI/3)([8,48])\nVIEW(STRUCT(MKPOLS(model)))\nmodel = larTorus(0.5,1)()\nVIEW(STRUCT(MKPOLS(model)))\nmodel = larBox([-1,-1,-1],[1,1,1])\nVIEW(STRUCT(MKPOLS(model)))\nmodel = larHollowCyl(0.8,1,1,angle=PI/4)([12,2,2])\nVIEW(STRUCT(MKPOLS(model)))\nmodel = larHollowSphere(0.8,1,PI/6,PI/4)([6,12,2])\nVIEW(STRUCT(MKPOLS(model)))\n@}\n%-------------------------------------------------------------------------------\n\n\n\\subsection{Volumetric utilities}\n\n\n\\paragraph{Limits of a LAR Model}\n%-------------------------------------------------------------------------------\n@D Model limits\n@{def larLimits (model):\n\tif isinstance(model,tuple): \n\t\tV,CV = model\n\t\tverts = scipy.asarray(V)\n\telse: verts = model.verts\n\treturn scipy.amin(verts,axis=0).tolist(), scipy.amax(verts,axis=0).tolist()\n\t\nassert larLimits(larSphere()()) == ([-1.0, -1.0, -1.0], [1.0, 1.0, 1.0])\n@}\n%-------------------------------------------------------------------------------\n\n\\paragraph{Alignment}\n%-------------------------------------------------------------------------------\n@D Alignment primitive\n@{def larAlign (args):\n\tdef larAlign0 (args,pols):\n\t\tpol1, pol2 = pols\n\t\tbox1, box2 = (larLimits(pol1), larLimits(pol2))\n\t\tprint \"box1, box2 =\",(box1, box2)\n\t\t\n\treturn larAlign0\n@}\n%-------------------------------------------------------------------------------\n\n\n\\bibliographystyle{amsalpha}\n\\bibliography{mapper}\n\n\\end{document}", "meta": {"hexsha": "fa2aa9e8eb131924515e84e34f7db834437bdf76", "size": 21308, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/tex/mapper.tex", "max_stars_repo_name": "cvdlab/lar-cc", "max_stars_repo_head_hexsha": "7092965acf7c0c78a5fab4348cf2c2aa01c4b130", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-09-20T04:48:12.000Z", "max_stars_repo_stars_event_max_datetime": "2016-09-20T04:48:12.000Z", "max_issues_repo_path": "src/tex/mapper.tex", "max_issues_repo_name": "Ahdhn/lar-cc", "max_issues_repo_head_hexsha": "7092965acf7c0c78a5fab4348cf2c2aa01c4b130", "max_issues_repo_licenses": ["MIT", "Unlicense"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-02-20T21:57:07.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-21T07:18:11.000Z", "max_forks_repo_path": "src/tex/mapper.tex", "max_forks_repo_name": "Ahdhn/lar-cc", "max_forks_repo_head_hexsha": "7092965acf7c0c78a5fab4348cf2c2aa01c4b130", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2016-11-04T10:47:42.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-10T17:32:50.000Z", "avg_line_length": 41.1351351351, "max_line_length": 628, "alphanum_fraction": 0.5301295288, "num_tokens": 5516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.3421608092704867}}
{"text": "\\lstset{\n  captionpos=b,\n  language=Haskell,\n  basicstyle=\\scriptsize,\n  numbers=left,\n  numberstyle=\\tiny,\n  columns=fullflexible,\n  stepnumber=1,\n  escapechar=\\#,\n  keepspaces=true,\n  belowskip=-10pt,\n  literate={<}{{$\\langle$}}1 {>}{{$\\rangle$}}1,\n  morekeywords={function,rr,int,float,bool,isnull,partition,as,downregion,upregion,reads,writes,rdwrs,reduces,read,write,reduce,using,unpack,pack,coloring,multicoloring,color,newcolor,atomic,simultaneous},\n  deletekeywords={float,head,min,max}\n}\n\\begin{lstlisting}[float={t},label={lst:circuit_ex},caption={Circuit Simulation}]\n--                        <voltage,current,charge,capacitance>\ntype CircuitNode        = <float,float,float,float>\n--                     < owned node, owned or ghost node, resistance, current>\ntype CircuitWire<rn,rg>  = <CircuitNode@rn, CircuitNode@(rn,rg),float,float>\n\ntype node_list<rl,rn>       = < CircuitNode@rn, node_list<rl,rn>@rl >\ntype wire_list<rl,rw,rn,rg>= < CircuitWire<rn,rg>@rw, wire_list<rl,rw,rn,rg>@rl >\n\ntype CircuitPiece<rl,rw,rn> = rr[rpw,rpn,rg]\n                            < wire_list<rl,rpw,rpn,rg>@rl, node_list<rl,rpn>@rl >         \n                            where rpn #$\\le$# rn and rg #$\\le$# rn and rpw #$\\le$# rw and\n                                  rn * rw and rl * rn and rl * rw\n\n-- Simulation initialization and invocation\nfunction simulate_circuit[rl,rw,rn] ( all_nodes : node_list<rl,rn>@rl, \n                            all_wires : wire_list<rl,rw,rn,rn>@rl, steps : int ), \n      reads(rn,rw,rl), writes(rn,rw,rl) : bool = \n  let pc : <coloring(rn),multicoloring(rn),coloring(rw)> \n            = color_circuit[rn,rw,rl](all_nodes,all_wires) in\n  -- Disjoint partition for the owned nodes of each piece\n  partition rn using pc.1 as rn0,rn1 in\n  -- Aliased partition for ghost nodes of each piece\n  partition rn using pc.2 as rg0,rg1 in\n  -- Disjoint partition for the owned wires of each piece\n  partition rw using pc.3 as rw0,rw1 in\n  let lists0 : <wire_list<rl,rw0,rn0,rg0>@rl,node_list<rl,rn0>@rl> = \n        build_lists[rl,rw,rn,rw0,rn0,rg0](all_nodes,all_wires,pc.1,pc.2,pc.3,0) in\n  let piece0 : CircuitPiece<rl,rw,rn> = \n        pack lists0 as CircuitPiece<rl,rw,rn>[rw0,rn0,rg0] in\n  let lists1 : <wire_list<rl,rw1,rn1,rg1>@rl,node_list<rl,rn1>@rl> =\n        build_lists[rl,rw,rn,rw1,rn1,rg1](all_nodes,all_wires,pc.1,pc.2,pc.3,1) in\n  let piece1 : CircuitPiece<rl,rw,rn> = \n        pack lists1 as CircuitPiece<rl,rw,rn>[rw1,rn1,rg1] in\n      execute_time_steps[rl,rw,rn](piece0,piece1,steps)\n\n-- Time Step Loop\nfunction execute_time_steps[rl,rw,rn] ( p0 : CircuitPiece<rl,rw,rn>, \n      p1 : CircuitPiece<rl,rw,rn>, steps : int ) , reads(rn,rw,rl), writes(rn,rw) : bool = \n  if steps #$<$# 1 then true else\n  unpack p0 as piece0 : CircuitPiece<rl,rw,rn>[rw0,rn0,rg0] in \n  unpack p1 as piece1 : CircuitPiece<rl,rw,rn>[rw1,rn1,rg1] in\n  let _ : bool = calc_new_currents[rl,rw0,rn0,rg0](piece0.1) in\n  let _ : bool = calc_new_currents[rl,rw1,rn1,rg1](piece1.1) in\n  let _ : bool = distribute_charge[rl,rw0,rn0,rg0](piece0.1) in\n  let _ : bool = distribute_charge[rl,rw1,rn1,rg1](piece1.1) in\n  let _ : bool = update_voltage[rl,rn0](piece0.2) in\n  let _ : bool = update_voltage[rl,rn1](piece1.2) in\n      execute_time_steps[rl,rw,rn](p0,p1,steps-1)\n\nfunction color_circuit[rn,rw,rl] ( all_nodes : node_list<rl,rn>@rl, \n                               all_wires : wire_list<rl,rw,rn>@rl ), \n        reads(rn,rw,rl) : <coloring(rn), multicoloring(rn), coloring(rw)> =  \n  -- Invoke programmer chosen coloring algorithm (e.g. METIS)\n  -- return owned, ghost, wire colorings\n\n-- Helper method\nfunction build_lists[rl,rw,rn,rpw,rpn,rg] ( nodes : node_list<rl,rn>@rl, \n       wires : wire_list<rl,rw,rn>@rl, oc : coloring(rn), gc : multicoloring(rn), \n       wc : coloring(rw), c : int), reads(rn,rw,rl), writes(rl) \n       : < wire_list<rl,rpw,rpn,rg>@rl, node_list<rl,rpn>@rl > = \n  -- Construct lists of node and wire pointers for the given colorings\n\\end{lstlisting}\n\n\\section{Circuit Example}\n\\label{sec:example}\n\nListing~\\ref{lst:circuit_ex} shows a circuit simulation written\nin the core Legion language (see\nSection~\\ref{sec:legioncore}).  The input is a graph of circuit\nelements and connecting wires.  To perform parallel\nsimulation the graph is partitioned into pieces, after which the\nsimulation is run for a number of time steps.  Each time step has\nthree phases: calculation of each wire's current, distribution of charge to\nthe nodes connected to each wire, and updating of node voltages.\n\nThe entry function is {\\tt simulate\\_circuit} (line 15), which accepts a \nlinked list of nodes contained in region {\\tt rn} and a linked list of \nwires contained in region {\\tt rw}.  The linked list elements themselves\nare in region {\\tt rl}.\nWhen {\\tt simulate\\_circuit} is invoked it must have both read and\nwrite privileges for the regions {\\tt rl}, {\\tt rw}, and {\\tt rn}\n(line 17); the type system statically verifies that\n{\\tt simulate\\_circuit} only accesses these regions and their subregions.\n\nPartitioning of the graph is done using {\\em colorings} built in the\n{\\tt color\\_circuit} function (line 18-19).  A coloring maps region\nelements to colors (integers in Core Legion), with each color corresponding\n to a new subregion\nto be created.  Note that it is impossible to pick a single static\npartitioning scheme that would do well for all graphs.  Dynamic\npartitioning using colorings enables the programmer \nto make partitioning decisions based on input data.\n\nThe {\\tt color\\_circuit} function is responsible for specifying how the\ncircuit is to be partitioned.  The body of this function is not shown as the\nideal algorithm for partitioning data will be application specific.  The \nonly restriction imposed by the Legion programming model is that the result of\nthe algorithm be provided in the form of colorings.  For our circuit example,\nthere are three colorings.  The first maps each node to the graph piece that owns it.\nThe third maps each wire to a graph piece that\nowns one of its nodes.  The second coloring captures, for each piece $p$,\nthe nodes in other pieces on the boundary of $p$, often referred to as\n{\\em ghost nodes}.  \n%We describe how ghost node regions are used in\n%conjunction with the owned nodes shortly.  \nNote that \nghost nodes may be on the boundary of multiple pieces and therefore be included in\nmultiple ghost regions.  For conciseness, a bit of syntactic sugar is used here the\nform of a {\\em multicoloring}, which allows the mapping of an element to multiple \ncolors.  Although multicolorings are not part of the Core Legion described in \nSection~\\ref{sec:legioncore}, they can be easily implemented using a separate \ncoloring for each color in the multicoloring.\n\nAfter creating the colorings, the application partitions the node and wire\nregions into {\\em subregions} according to the colorings (lines 21-25).  For\nsimplicity, our example only partitions the circuit into two pieces.\nLine 21 uses coloring {\\tt pc.1} to partition {\\tt rn} into {\\tt rn0}, and {\\tt rn1}.\nSubregion {\\tt rn0} will contain all locations with a color of 0 in {\\tt pc.1},\nwhile {\\tt rn1} will contain all locations with a color of 1.  This\npartitioning results in {\\em disjoint} subpartitions.\nConstraints are introduced into the static environment describing both the\ndisjointness of the subregions (i.e. {\\tt rn0 $*$ rn1}) and the inclusion of\neach subregion in the original region (e.g. {\\tt rn0 $\\leq$ rn}).  Line\n23 is similar, but uses a multicoloring, so the subregions may be {\\em aliased},\nand only the inclusion constraints are introduced into the static environment.\n\nThe circuit simulation uses an {\\em allocate-then-partition} style of\ncomputation, where a large data structure is first allocated and then\npartitioned.  Legion also supports a {\\em partition-then-allocate} style,\nwhere empty regions are first partitioned and later populated with\ndata.  Both are useful; e.g., Sequoia \\cite{Fatahalian06} and DPJ\n\\cite{Bocchino09} support static forms of allocate-then-partition and\npartition-then-allocate, respectively.  Legion supports both\napproaches dynamically.\n\nAfter partitioning the circuit into pieces, the application creates\ninstances of {\\tt CircuitPiece} (defined on lines 9-12) for each piece\n(lines 28-33).  {\\tt CircuitPiece} is a {\\em region relationship}, a\nbounded existential type.  Region relationships allow the programmer\nto {\\em pack} a group of regions and pointers into those regions together\nand remember properties\nabout them such as disjointness and subregion relationships (lines 29\nand 33).  The type system verifies the properties hold statically when\npacking; when region relationships are {\\em unpacked} the same\nproperties are reintroduced into the static checking environment\n(lines 40-41).  A key feature underlying the soundness of the Legion\ntype system is that privileges cannot be packed in a region\nrelationship---privileges belong to functions. When a function unpacks\na region relationship it must already hold privileges for the unpacked regions. \n%new regions it finds in the packed value.  \nFor example, on line 40 the\nfunction {\\tt execute\\_time\\_steps} has read/write privileges for\nregion {\\tt rn0} because it has read/write privileges for {\\tt rn} and\nthe {\\tt CircuitPiece} region relationship constraints ensure $\\tt rn0\n\\leq rn$ (line 12).\n\nThe {\\tt execute\\_time\\_steps} function (lines 37-48)  \nalso illustrates the importance of using different partitions to give\nmultiple views onto the same logical region.  Both {\\tt\n  calc\\_new\\_currents} and {\\tt distribute\\_charge} \nuse the owned and ghost regions of a piece, which are from different partitions. In\n{\\tt calc\\_new\\_currents} these regions only need read\nprivileges, allowing both instances of {\\tt calc\\_new\\_currents} to be\nrun in parallel.  In {\\tt distribute\\_charge} the\nprivilege is for a reduction which can also be done in parallel\nbecause of the atomic and commutative nature of reductions.  Finally,\nthe {\\tt update\\_voltage} function modifies only the owned regions, permitting\neach piece to be updated in parallel.  No\nsingle partition of the nodes\ndescribes these data sharing patterns.\n\n%This function also demonstrates the benefit of being able to dynamically\n%(re-)discover disjointness.  Safely running both instances of \n%{\\tt calc\\_new\\_currents} in parallel depends on knowing that {\\tt rw0} and\n%{\\tt rw1} in {\\tt execute\\_time\\_steps} are disjoint.  Similarly, parallel\n%execution of the instances of {\\tt update\\_voltage} requires knowing that\n%{\\tt rn0} is disjoint from {\\tt rn1}.  In both cases, this knowledge was\n%statically available in {\\tt simulate\\_circuit} and could have been captured\n%in a region relationship, but it would have resulted in much more complicated\n%code.\n%Instead, an inexpensive dynamic disjointness check is performed by the Legion\n%runtime, and the safety of parallel execution follows from the soundness of\n%the type system.\nThe {\\tt execute\\_time\\_steps} function also demonstrates the benefit of dynamically\nbeing able to discover disjointness.  To run the two instances of \n{\\tt calc\\_new\\_currents} in parallel requires knowing that {\\tt rw0}\nand {\\tt rw1} are disjoint.  There is a similar requirement for parallel\nexecution of the two {\\tt update\\_voltage} calls with {\\tt rn0} and {\\tt rn1}.  In\nboth cases, this knowledge was statically available in {\\tt simulate\\_circuit}\nand could have been captured in a region relationship at the cost\nof much more complicated code.  Instead, an inexpensive dynamic disjointness\ncheck by the Legion runtime will (re)discover the parallelism.\n\nListing~\\ref{lst:circuit_leaf} shows the leaf functions for each phase.\nEach function iterates over the list of wires or\nnodes for its piece.  Each function specifies the region privileges it\nrequires (lines 2,14,23).  \n%These privileges\n%are statically checked to match the operations performed inside of\n%each function (e.g. read and write).  \nIn the case of {\\em reduce} the\nprivilege must also specify which reduction function is used\n(line 14).\n\nIn addition to privileges, functions can also specify {\\em coherence}\non regions.  Coherence specifies what updates the function may\nobserve from other functions using aliased regions.  \nIf not otherwise specified, coherence defaults to {\\em exclusive}, \nmeaning the function must appear to execute in program order relative to\nother function calls.  \nLine 14 in Listing~\\ref{lst:circuit_leaf} shows\nan example of {\\tt atomic}, a relaxed coherence mode requiring\nthat operations to {\\tt rn} and {\\tt rg} appear atomic relative\nto other functions using regions which may alias.  The most relaxed coherence\nmode is {\\tt simult}; simultaneous coherence allows concurrent access \nto the region by all functions that are using the region\nin a simultaneous mode.  The interaction between {\\em tasks} (which are functions chosen to execute in parallel) using the same\nregion with different coherence\nmodes is formalized in Section~\\ref{sec:coherence}.\n\n% This is a description of how the listings should be formatted.\n% It can go anywhere before the listings.\n\\lstset{\n  captionpos=b,\n  language=Haskell,\n  basicstyle=\\scriptsize,\n  numbers=left,\n  numberstyle=\\tiny,\n  columns=fullflexible,\n  stepnumber=1,\n  escapechar=\\#,\n  keepspaces=true,\n  belowskip=-10pt,\n  literate={<}{{$\\langle$}}1 {>}{{$\\rangle$}}1,\n  morekeywords={function,rr,int,float,bool,isnull,partition,as,downregion,upregion,reads,writes,rdwrs,reduces,read,write,reduce,using,unpack,pack,coloring,multicoloring,color,newcolor,atomic,simultaneous},\n  deletekeywords={float,head,min,max}\n}\n\n\\begin{lstlisting}[float={t},label={lst:circuit_leaf},caption={Circuit Leaf Functions}]\nfunction calc_new_currents[rl,rw,rn,rg] ( ptr_list : wire_list<rl,rw,rn,rg>@rl ), \n      reads(rl,rw,rn,rg), writes(rw) : bool =\n  if isnull(ptr_list) then true else\n  let wire_node : wire_list<rl,rw,rn,rg> = read(ptr_list) in\n  let wire : CircuitWire<rn,rg> = read(wire_node.1) in\n  let in_node : CircuitNode = read(wire.1) in\n  let out_node : CircuitNode = read(wire.2) in\n  let current : float = (in_node.1 - out_node.1) /  wire.3 in \n  let new_wire : CircuitWire<rn,rg> = <wire.1,wire.2,wire.3,current> in\n  let _ : CircuitWire<rn,rg>@rw = write(wire_node.1, new_wire) in\n      calc_new_currents[rl,rw,rn,rg](wire_node.2)\n\nfunction distribute_charge[rl,rw,rn,rg] ( ptr_list : wire_list<rl,rw,rn,rg>@rl ), \n      reads(rl,rw,rn), reduces(reduce_charge,rn,rg), atomic(rn,rg) : bool =\n  if isnull(ptr_list) then true else\n  let wire_node : wire_list<rl,rw,rn,rg> = read(ptr_list) in\n  let wire : CircuitWire<rn,rg> = read(wire_node.1) in\n  let _ : CircuitNode@rn = reduce(reduce_charge, wire.1, wire.4) in\n  let _ : CircuitNode@(rn,rg) = reduce(reduce_charge, wire.2, wire.4) in\n      distribute_charge[rl,rw,rn,rg](wire_node.2)\n\nfunction update_voltage[rl,rn] ( ptr_list : node_list<rl,rn>@rl ), \n      reads(rl,rn), writes(rn) : bool = \n  if isnull(ptr_list) then true else\n  let node_node : node_list<rl,rn> = read(ptr_list) in\n  let node : CircuitNode = read(node_node.1) in\n  let voltage : float = (node.3/node.4) in\n  let new_node : CircuitNode = <voltage,node.2,node.3,node.4> in\n  let _ : CircuitNode@rn = write(node_node.1, new_node) in\n      update_voltage[rl,rn](node_node.2)\n\n-- Reduction function for distribute charge\nfunction reduce_charge ( node : CircuitNode, current : float ) : CircuitNode =\n    let new_charge : float = node.3 + current in\n        < node.1,new_charge,node.3,node.4>\n\\end{lstlisting}\n\n\n", "meta": {"hexsha": "181681ceed5cc475470d3d4cdf55c102fbef4f1e", "size": 15535, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/types-pldi2013/example.tex", "max_stars_repo_name": "lightsighter/LegionOrigins", "max_stars_repo_head_hexsha": "0180bb3a8ee6efd0d2efdb743f75d3fba86f18f7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-11-10T06:29:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:56:13.000Z", "max_issues_repo_path": "doc/types-pldi2013/example.tex", "max_issues_repo_name": "lightsighter/LegionOrigins", "max_issues_repo_head_hexsha": "0180bb3a8ee6efd0d2efdb743f75d3fba86f18f7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/types-pldi2013/example.tex", "max_forks_repo_name": "lightsighter/LegionOrigins", "max_forks_repo_head_hexsha": "0180bb3a8ee6efd0d2efdb743f75d3fba86f18f7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.8401360544, "max_line_length": 205, "alphanum_fraction": 0.7401351786, "num_tokens": 4314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.3420619302881984}}
{"text": "\\chapter*{Abstract}\n\nMaximising the economic effectiveness of a wind farm is essential in making wind a more economic source of energy. This effectiveness can be increased through the reduction of operation and maintenance costs, which can be achieved through continuously monitoring the condition of wind turbines. An alternative to expensive condition monitoring systems, which can be uneconomical especially for older wind turbines, is to implement classification algorithms on supervisory control and data acquisition (SCADA) signals, which are collected in most wind turbines. Several publications were reviewed, which were all found to use separate algorithms to predict specific faults in advance. In reality, wind turbines tend to have multiple faults which may happen simultaneously and have correlations with one another. This project focusses on developing a methodology to predict multiple wind turbine faults in advance simultaneously by implementing classification algorithms on SCADA signals for a wind farm with 25 turbines rated at 2,500 kW, spanning a period of 30 months. The data, which included measurements of wind speed, active power and pitch angle, was labelled using corresponding downtime data to detect normal behaviour, faults and varying timescales before a fault occurs. Three different classification algorithms, namely decision trees, random forests and k nearest neighbours were tested using imbalanced and balanced training data, initially to optimise a number of hyperparameters. The random forest classifier produced the best results. Upon conducting a more detailed analysis on the performance of specific faults, it was found that the classifier was unable to detect the varying timescales before a fault with accuracy comparable to that of normal or faulty behaviour. This could have been due to the SCADA data, which are used as features, being unsuitable for detecting the faults, and there is potential to improve this by balancing only these classes.\n\\\\[.5cm]\n\\noindent\\textbf{\\textit{Keywords:}} \\keywords\n", "meta": {"hexsha": "bfb8a902622f582374fd84e422ad3694c9022d16", "size": 2051, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/abstract.tex", "max_stars_repo_name": "nmstreethran/WindTurbineClassification", "max_stars_repo_head_hexsha": "b0ea6de909ccd5bb425cee291ca3c252c11df4eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 34, "max_stars_repo_stars_event_min_datetime": "2019-03-01T21:24:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T09:59:17.000Z", "max_issues_repo_path": "docs/abstract.tex", "max_issues_repo_name": "nmstreethran/WindTurbineClassification", "max_issues_repo_head_hexsha": "b0ea6de909ccd5bb425cee291ca3c252c11df4eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/abstract.tex", "max_forks_repo_name": "nmstreethran/WindTurbineClassification", "max_forks_repo_head_hexsha": "b0ea6de909ccd5bb425cee291ca3c252c11df4eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2019-03-01T21:24:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-26T15:04:14.000Z", "avg_line_length": 341.8333333333, "max_line_length": 1973, "alphanum_fraction": 0.8298391029, "num_tokens": 373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3420189360228672}}
{"text": "\\chapter{parelm}\n\n\\section{Introduction}\n\nAn LPE may have parameters that do not affect the behavior of that process in any way.\nThese parameters are said to be \\emph{inert}.\nRemoving inert parameters from an LPE reduces the size of state vectors and the state space of that LPE, which both benefits performance.\n\n\\section{Algorithm}\n\nThe algorithm consists of the following steps \\cite{groote2001computer}:\n\n\\begin{enumerate}\n\n\\item Make it so that all parameters of the LPE are \\labeledas{inert}.\n\n\\item Consider the guards of all summands of the LPE, and \\removelabelfrom{inert} from all LPE parameters that occur in the guard of a summand.\n\n\\item Let $X$ be the set of all LPE parameters that are \\labeledas{inert}, and consider all expressions $v_s(p)$ that define the value of an LPE parameter $p$ after application of a summand $s$.\nFor each such expression, if $p$ is \\emph{not} \\labeledas{inert}, \\removelabelfrom{inert} all LPE parameters that occur in $v_s(p)$.\n\n\\item Repeat the previous step until the fixpoint of $X$ is reached.\nThen remove all LPE parameters that are still \\labeledas{inert} from the LPE, substituting references to those parameters by their initial values.\n\n\\end{enumerate}\n\n\\clearpage\n\\section{Example}\n\nConsider the following LPE:\n\n\\begin{lstlisting}\n//Process definition:\nPROCDEF example[A :: Int, B](x, y, z :: Int)\n  = A ? i [[x==0]] >-> example[A, B](i, y, z)\n  + A ? i [[x==1]] >-> example[A, B](0, i, z)\n  + B [[x==2]] >-> example[A, B](0, y, z)\n  + B [[true]] >-> example[A, B](z, y, x)\n  ;\n\n//Initialization:\nexample[A, B](0, 0, 0);\n\\end{lstlisting}\n\nFirst, the `inert' label is removed from $x$ because $x$ occurs in the guards of the first three summands.\n\nIn the fourth summand, $z$ is used in the expression of which the value is assigned to $x$.\nTherefore $z$ is also no longer \\labeledas{inert}.\n\n$y$ remains labeled with `inert': it does not occur in a guard, nor is it used in the assignment to a process parameter other than itself.\nRemoving $y$ gives\n\n\\begin{lstlisting}\n//Process definition:\nPROCDEF example[A :: Int, B](x, z :: Int)\n  = A ? i [[x==0]] >-> example[A, B](i, z)\n  + A ? i [[x==1]] >-> example[A, B](0, z)\n  + B [[x==2]] >-> example[A, B](0, z)\n  + B [[true]] >-> example[A, B](z, x)\n  ;\n\n//Initialization:\nexample[A, B](0, 0);\n\\end{lstlisting}\n\n\\section{Benchmark results}\n\nThe following durations were measured with a benchmark for several models:\n\\begin{itemize}\n\\item The average duration of \\txs{} to make 500 steps in a model after it has been converted to LPE form;\n\\item The average duration of \\txs{} to make 500 steps in a model after it has been converted to LPE form and after the \\texttt{parelm} operation has been applied.\n\\end{itemize}\n\nWhen plotting the second series of measurements against the first (see Figure~\\ref{parelm-vs-lpe-only:fig}), it is easy to see that the impact is insignificant in most cases.\nThe only model for which a significant performance increase has been measured is the \\texttt{ControlLoop} model, which has indeed lost part of its state vector.\n\n\\begin{figure}[!ht]\n\\begin{center}\n\\includegraphics[width=0.5\\linewidth]{charts/parelm-vs-lpe-only}\n\\caption{Benchmark results: parelm vs LPE transformation}\n\\label{parelm-vs-lpe-only:fig}\n\\end{center}\n\\end{figure}\n\n", "meta": {"hexsha": "6a3cc8f13509772064758cc549217a733963cd48", "size": 3273, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "sys/lpeops/tex/lpeopsDoc/parelm.tex", "max_stars_repo_name": "ikbendedjurre/TorXakis", "max_stars_repo_head_hexsha": "a791ce9960e88df576733404fe4d60114c35e50a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 44, "max_stars_repo_stars_event_min_datetime": "2017-06-09T08:17:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-08T02:17:01.000Z", "max_issues_repo_path": "sys/lpeops/tex/lpeopsDoc/parelm.tex", "max_issues_repo_name": "ikbendedjurre/TorXakis", "max_issues_repo_head_hexsha": "a791ce9960e88df576733404fe4d60114c35e50a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 746, "max_issues_repo_issues_event_min_datetime": "2017-06-13T07:36:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T19:14:31.000Z", "max_forks_repo_path": "sys/lpeops/tex/lpeopsDoc/parElm.tex", "max_forks_repo_name": "ikbendedjurre/txs-develop", "max_forks_repo_head_hexsha": "bc11f4b93a15e220bf6941d395d5b4cd361bfe74", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2017-11-16T11:33:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-26T16:33:36.000Z", "avg_line_length": 38.5058823529, "max_line_length": 194, "alphanum_fraction": 0.719217843, "num_tokens": 946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.34201892787234045}}
{"text": "\\section{Building NWAs from other NWAs (namespace \\texttt{opennwa::construct})}\n\\label{Se:Building NWAs}\n\nThe library provides functions for performing automata-theoretic operations upon\nNWAs. The supported operations are union, intersection, concatenation,\nreversal, Kleene star, complement, and determinization.\n\nThe library supports two interfaces to each of these operations. In one, the\noperation allocates an NWA with \\texttt{new}, performs the construction, and\nreturns a \\texttt{NwaRefPtr} to the result.  In the other, the operation takes\na reference to an NWA, clears it, and constructs the result in-place. The\nfirst form is usually more convenient to use, and creates a mini language for\nset expressions; the second form makes it possible to store the result of an\noperation in a subclass of \\texttt{Nwa}, or an existing \\texttt{Nwa} object.\n\nEach of these functions is in the namespace \\texttt{opennwa::construct}:\n\n\\begin{functionlist}\n\n  \\functionDefEarly{NwaRefPtr}{unionNwa}{Nwa const \\& a, Nwa const \\& b}{}\n  \\functionDef{void}{unionNwa}{Nwa \\& out, Nwa const \\& a, Nwa const \\& b}{}\n    Computes the union of the NWAs \\texttt{a} and \\texttt{b},\n    either returning the result or storing it in \\texttt{out}.\n    See Section\n    \\ref{Se:Union}. (This function is called \\texttt{unionNwa} instead of\n    \\texttt{union} because the latter is a C++ keyword.) The two NWAs must not\n    have any states in common, and the output will be nondeterministic even\n    if both input NWAs are deterministic. The running time\\footnote{We count\n      state lookups, additions, etc.\\ as constant time even though they are\n      actually logarithmic, and occasionally linear.} is\n    $O(|Q^a|+|Q^b|+|\\delta^a|+|\\delta^b|)$.\n\n  \\functionDefFirstEarly{NwaRefPtr}{intersect}{Nwa const \\& a, Nwa const \\& b}{}\n  \\functionDef{void}{intersect}{Nwa \\& out, Nwa const \\& a, Nwa const \\& b}{}\n    Computes the intersection of the NWAs \\texttt{a} and \\texttt{b},\n    either returning the result or storing it in \\texttt{out}.\n    See Section \\ref{Se:Intersection}. If both input NWAs are deterministic,\n    the output will be deterministic. The worst-case running time is\n    $O(|Q^a| |Q^b| d_a d_b)$, where $d_a$ is the maximum out-degree\n    of a state in \\texttt{a} and $d_b$ is the maximum out-degree of a state\n    in \\texttt{b}.\n\n  \\functionDefFirstEarly{NwaRefPtr}{concat}{Nwa const \\& left, Nwa const \\& right}{}\n  \\functionDef{void}{concat}{Nwa \\& out, Nwa const \\& left, Nwa const \\& right}{}\n    Computes the concatenation of the NWAs \\texttt{left} and\n    \\texttt{right}, either returning the result or storing it in\n    \\texttt{out}.\n    See Section \\ref{Se:Concatenation}. The output automaton will be\n    nondeterministic. The running time is\n    $O(|Q^a|+|Q^b|+|\\delta^a|+|\\delta^b|+|Q^a||\\delta_r^b|)$.\n\n  \\functionDefFirstEarly{NwaRefPtr}{star}{Nwa const \\& orig}{}\n  \\functionDef{void}{star}{Nwa \\& out, Nwa const \\& orig}{}\n    Computes the Kleene star of the NWA \\texttt{orig}, either\n    returning the result or storing it in \\texttt{out}. See Section\n    \\ref{Se:Star}. The output automaton will be nondeterministic. The\n    running time is $O(|Q|+|\\delta|+|Q_0||Q_f||\\delta_c|)$.\n\n  \\functionDefFirstEarly{NwaRefPtr}{reverse}{Nwa const \\& orig}{}\n  \\functionDef{void}{reverse}{Nwa \\& out, Nwa const \\& orig}{}\n    Computes the NWA that accepts the reverse of each nested word\n    accepted by the NWA \\texttt{orig}, either returning the result or\n    storing it in \\texttt{out}. See Section \\ref{Se:Reverse}. The running\n    time is $O(|Q|+|\\delta|)$.\n\n  \\functionDefFirstEarly{NwaRefPtr}{determinize}{Nwa const \\& orig}{}\n  \\functionDef{NwaRefPtr}{determinize}{Nwa \\& out, Nwa const \\& orig}{}\n    Computes a determinization of \\texttt{orig}, either returning the\n    result or storing it in \\texttt{out}.\n    See Section \\ref{Se:Determinize}. The worst-case running time for this\n    algorithm is at least $O({|Q|^3} \\cdot2^{|Q|^2})$.\n\n\\clearpage\n  \\functionDefFirstEarly{NwaRefPtr}{complement}{Nwa const \\& orig}{}\n  \\functionDef{void}{complement}{Nwa \\& out, Nwa const \\& orig}{}\n    Computes the complement of the determinization of \\texttt{orig},\n    either returning the result or storing it in \\texttt{out}.\n    See Section\n    \\ref{Se:Complement}. %For complementing the set of final states to work\n    %correctly, two things must hold: \\texttt{orig} must be deterministic and\n    %the transition functions must be total. (That is, for a given state $q$\n    %and symbol $\\sigma$, there must be exactly one internal transition $(q,\n    %5\\sigma, q') \\in\\delta_i$, exactly one call transition $(q, \\sigma,\n    %q')\\in\\delta_c$, and exactly one return transition $(q, p, \\sigma,\n    %q')\\in\\delta_r$ for each state $p$.)\n    \\texttt{complement()} determinizes \\texttt{orig}, so its worst-case\n    running time is also at least $O({|Q|^3} \\cdot2^{|Q|^2})$.\n\n    %\\vspace{0.5\\baselineskip}\n    %If \\texttt{determinize} is \\texttt{true}, it will\n    %automatically determinize the input NWA before complementation, which\n    %also guarantees the input machine will be total. If you\n    %know that \\texttt{orig} is already deterministic and total, you can set\n    %\\texttt{determinize} to\n    %\\texttt{false} to avoid this step. (Complementing a nondeterministic or\n    %non-total NWA can easily lead to an incorrect result.) If\n    %\\texttt{determinize} is \\texttt{true}, the worst-case running time is the\n    %same as for the \\texttt{determinize} function (roughly\n    %$O(2^{|Q|^2})$). If \\texttt{determinize} is \\texttt{false}, the running\n    %time is $O(|Q|+|\\delta|)$.\n\n\\end{functionlist}\n\nAs mentioned above, these functions create a small language of set\nexpressions. For instance, to compute an automaton \\texttt{M} whose language\nis $\\texttt{A} \\cup (\\texttt{B} \\cap \\texttt{C})*$ (where \\texttt{A},\n\\texttt{B}, and \\texttt{C} are \\texttt{NwaRefPtr}s), one can write\n\\begin{center}\n  \\texttt{NwaRefPtr M = unionNwa(*A, *star(*intersect(*B, *C)))}\n\\end{center}\n\n\n\\begin{figure}[tb]\n  \\centering\n  \\begin{minipage}{0.3\\textwidth}\n    \\centering\n    \\nwaimage[.6]{Figures/figure-1}\n    \\caption{An example NWA.}\n    \\label{Fi:Example1}\n  \\end{minipage}\n  \\hspace{0.025\\textwidth}\n  \\begin{minipage}{0.3\\textwidth}\n    \\centering\n    \\nwaimage[0.49]{Figures/union-other}\n    \\caption{A second example NWA.}\n    \\label{Fi:Union1}\n  \\end{minipage}\n  \\hspace{0.025\\textwidth}\n  \\begin{minipage}{0.3\\textwidth}\n    \\centering\n    \\nwaimage[0.8]{Figures/union-result}\n    \\caption{The NWA resulting from the union of the NWA in Figure\n      \\ref{Fi:Example1} and the NWA in Figure \\ref{Fi:Union1}. Note that there\n      are two initial states.}\n    \\label{Fi:Union2}\n  \\end{minipage}\n\\end{figure}\n\n\n\n\n\\subsection{Union}\n\\label{Se:Union}\nThe union of two NWAs is constructed by taking the union of each of the\ncomponents of the NWAs. (In\nparticular, it does \\textsl{not} do a cross-product construction, and will\n\\textsl{always} produce a nondeterministic automaton as a result as long as\nboth machines have at least one initial state.)\n\nFormally, the union of NWAs $N = (Q_N, \\Sigma_N, Q_{0,N}, \\delta_N, F_N)$\nand $M = (Q_M, \\Sigma_M,$ $Q_{0,M}, \\delta_M, F_M)$ is\n$N \\cup M = (Q_N \\cup Q_M, \\Sigma_N \\cup \\Sigma_M, Q_{0,N} \\cup\n   Q_{0,M}, \\delta_N \\cup \\delta_M, F_N \\cup F_M)$.\n\nAs an example, \\figref{Union2} illustrates the union of \\figref{Example1} and\n\\figref{Union1}.\n\n\nThe state sets of the NWAs must not overlap,\ni.e., $Q_1 \\cap Q_2 = \\emptyset$. \\textsl{Client code should not rely on\n  this condition being checked} or any particular behavior occurring if it\ndoes not hold.\n\nClient information is copied directly from the original NWAs using\n\\texttt{ClientInfo::clone()}.\n\n\n\\subsection{Intersection}\n\\label{Se:Intersection}\n\nThe intersection of two NWAs is computed in the standard cross-product\nfashion, using a worklist algorithm to only compute those states that\nare reachable.\n\nThe algorithm traverses the original NWAs starting at\nthe initial states and incrementally adds transitions for each pair of\n``intersectable'' transitions that are encountered. By default, transitions\nare intersectable when the transitions are the same kind (internal, call,\nor return) and the symbols on the edge are identical or one is wild.\n\nFor example, \\figref{Intersect1} shows the intersection of \\figref{Example1} and\n\\figref{Intersect1}, and \\figref{Intersect4} shows the intersection of the\ntwo NWAs in \\figref{Intersect3}.\n\n \n\\begin{figure}[tp]\n  \\centering\n  \\begin{minipage}{0.48\\textwidth}\n    \\centering\n    \\nwaimage[0.45]{Figures/intersection-simple-other}\n    \\caption{Simple NWA to intersect with the NWA in Figure \\ref{Fi:Example1}.}\n    \\label{Fi:Intersect1}\n  \\end{minipage}\\hspace{0.2cm}\n  \\begin{minipage}{0.49\\textwidth}\n    \\centering\n    \\nwaimage{Figures/intersection-simple-result}\n    \\caption{The NWA resulting from the intersection of the NWA in Figure\n      \\ref{Fi:Example1} and the NWA in Figure \\ref{Fi:Intersect1}. Note that\n      because each of the input NWAs only accepts a single word and those\n      words are different, the language of the intersection is empty. The NWA\n    built up by \\texttt{intersect()} got as far as it\n    could. \\texttt{(key\\#2,3)} is the pair of states \\texttt{(start,start)}\n    from the two input automata.}\n    \\label{Fi:Intersect2}\n  \\end{minipage}\n\\end{figure}\n\n\\begin{figure}[p]\n  \\centering\n    \\adjustbox{width=\\textwidth,height=\\textheight,keepaspectratio=true}{\n    \\nwaimage{Figures/intersection-complex-first}\n    \\nwaimage{Figures/intersection-complex-second}}\n  \\caption{Two complex NWAs to intersect.}\n  \\label{Fi:Intersect3}\n\\end{figure}\n\n\\begin{figure}[p]\n  \\centering\n    \\nwaimage[.45]{Figures/intersection-complex-result}\n  \\caption{The NWA resulting from the intersection of the NWAs in Figure \\ref{Fi:Intersect3}.}\n  \\label{Fi:Intersect4}\n\\end{figure}\n\n\\antistupidfloats\n\nIt is possible to customize what symbols are considered equivalent, or\notherwise impose constraints on what transitions can be intersected, by\noverriding the \\texttt{transitionIntersect} function in a subclass of\n\\texttt{Nwa}. In addition, it is possible to impose additional constraints on\nwhat states can be combined by overriding \\texttt{stateIntersect}. Both\nfunctions also produce the result of the intersection:\n\\texttt{transitionIntersect} produces the symbol that will be used on the\nresulting edge, and \\texttt{stateIntersect} produces the state that will be\nused as the target.\n\nThe default behavior of\n\\texttt{transitionIntersect} is that two transitions are intersectable if\nneither symbol is epsilon and either the symbols are the same or at least one of\nthe symbols is a wild. (Epsilon transitions are dealt with in\n\\texttt{intersect()} itself. If you override \\texttt{transitionIntersect}, it\nshould return \\texttt{false} if either input is epsilon.)\n\nThe default behavior of \\texttt{stateIntersect} is that any two\nstates can be combined, the resulting state is labeled with a\nkey that is uniquely generated from the pair of the keys of\nthe two states under consideration, and the client information associated\nwith the resulting state is \\texttt{null}.\n\n\nClient information is initially generated by the helper method \\texttt{stateIntersect},\nbut can be altered through the use of the helper methods\n\\texttt{intersectClientInfoInternal}, \\texttt{intersectClientInfoCall}, and\n\\texttt{intersect\\-Client\\-InfoReturn}, which are invoked by\n\\texttt{intersect()} as transitions of the three different kinds involving the\nassociated state are added.  The default behavior of these three functions is\nto perform no changes to the \\texttt{ClientInfo}.  These methods can be\noverridden in subclasses to specify alternative behaviors.\n\n\\goodbreak\nThe following operations are virtual functions in class \\texttt{Nwa} and are intended\nto be overridden to customize behavior:\n\n\\begin{functionlist}\n  \\functionDefNoCloseParen{bool}{stateIntersect}{%\n                  \\parbox[t]{4in}\n                              {Nwa const \\& first, State state1,\\\\ \n                               Nwa const \\& second, State state2,\\\\\n                               State \\& resSt, ref\\_ptr<ClientInfo> \\& resCI)}}\n    Determines whether the given states can be combined and,\n    if so, creates the combined state. If the two states are incompatable,\n    returns \\texttt{false}. If the two states are compatable, it computes the\n    key of the combined state (storing it in \\texttt{resSt} and the client\n    information (storing it in \\texttt{resCI}), then returns \\texttt{true}.\n\n  \\functionDefFirstNoCloseParen{bool}{transitionIntersect}{%\n                  \\parbox[t]{4in}\n                              {Nwa const \\& first, Symbol sym1,\\\\\n                               Nwa const \\& second, Symbol sym2,\\\\ \n                               Symbol \\& resSym )}}\n    Determines whether the given symbols are considered to be equivalent for\n    the purposes of intersection. If so, it computes the symbol that should\n    be associated with the combined transition (storing it in\n    \\texttt{resSym}) and returns true. If not, returns false.\n\n  \\functionDefFirstEarlyNoCloseParen{void}{intersectClientInfoInternal}{%\n                  \\parbox[t]{4in}\n                     {Nwa const \\& first, State src1, State tgt1,\\\\\n                      Nwa const \\& second, State src2, State tgt2,\\\\\n                      Symbol resSym, State resSt )}}\n    \\nopagebreak\n  \\functionDefEarlyNoCloseParen{void}{intersectClientInfoCall}{%\n                  \\parbox[t]{4in}\n                      {Nwa const \\& first ,State call1, State entry1,\\\\\n                       Nwa const \\& second, State call2, State entry2,\\\\\n                       Symbol resSym, State resSt )}} \\nopagebreak\n  \\functionDefNoCloseParen{\\small void}{\\small intersectClientInfoReturn}{%\n                  \\parbox[t]{4in}\n                      {\\small Nwa const \\& first, State exit1, State call1,State ret1,\\\\\n                       Nwa const \\& second, State exit2,State call2, State ret2,\\\\\n                       Symbol resSym, State resSt )}}\n    Called after a transition of the corresponding type is added to the\n    automaton. It is intended to be used to\n    alter the client information associated with \\texttt{resSt} given the\n    endpoints of the new transition.\n\n\\end{functionlist}\n\n\n\n\n\\subsection{Concatenation}\n\\label{Se:Concatenation}\n\nThe concatenation of two NWAs is constructed by taking the union of all\nstates and transitions of the two automata, and adding\ninternal epsilon transitions from each final state of the first NWA to each\ninitial state of the second NWA.  In the resulting NWA, the initial states\nare the initial states from the first NWA, and the final states are the final\nstates of the second NWA.\n\nHowever, the concatenation construction is a bit more complicated than just this,\nbecause we need to address the issue of an unbalanced-left\nword being concatenated with an unbalanced-right word.  (Recall the\ndefinition of what happens when an NWA reads a pending return: it is\nallowed to take a return transition where the call predecessor is an initial\nstate of the automaton.) \n\nTo deal properly with the case where the first operand generates strings with\npending calls and the second operand generates strings with pending returns,\nthe\ntransitions from the second automaton are augmented in the\nfollowing manner. When computing the concatenation of \\texttt{left} and\n\\texttt{right}, for each transition $(q, p_0, a, q')\n\\in\\delta_r^{\\texttt{right}}$ where $p_0 \\in Q_0^\\texttt{right}$ (these are\ntransitions that \\texttt{right} can take when reading a pending return) and\neach $p \\in Q^\\texttt{left}$, we add $(q, p, a, q')$ to $\\delta_r$ of the\nresult. (It is actually only necessary to add such a transition for states\n$p$ that either appear in the call position of a call transition in\n\\texttt{left} or are in $Q_0^\\texttt{left}$.)\n\n\n % If the original NWAs are $(Q_1, \\Sigma_1,\n%{Q_0}_1, \\delta_1, {Q_f}_1)$ and $(Q_2, \\Sigma_2, {Q_0}_2, \\delta_2,\n%{Q_f}_2)$, then the resulting NWA is $(Q, \\Sigma, Q_0, \\delta, Q_f)$ where $Q\n%= Q_1 \\cup Q_2$, $\\Sigma = \\Sigma_1 \\cup \\Sigma_2$, $Q_0 = {Q_0}_1$, $\\delta\n%= \\delta_1 \\cup \\delta_2 \\cup \\delta_\\epsilon$ (where $\\delta_\\epsilon =\n%\\{(q,\\epsilon,q') | q \\in {Q_f}_1, q' \\in {Q_0}_2\\}$, and $Q_f = {Q_f}_2$ .\n%The NWA resulting from the concatenation of the NWA in Figure\n%\\ref{Fi:Example1} and the NWA shown in Figure \\ref{Fi:Concat1} is shown in\n%Figure \\ref{Fi:Concat2}.\n\n\\begin{figure}[p]\n  \\centering\n  \\begin{minipage}{0.5\\textwidth}\n    \\begin{minipage}{\\textwidth}\n      \\centering\n      \\nwaimage[1]{Figures/concat-other}\n      \\caption{Simple NWA to concatenate onto the NWA in Figure \\ref{Fi:Example1}.}\n      \\label{Fi:Concat1}\n    \\end{minipage}\n\n    \\vspace{2\\baselineskip}\n    \\begin{minipage}{0.8\\textwidth}\n      \\centering\n      \\nwaimage[0.55]{Figures/reverse-of-figure-1}\n      \\caption{The NWA resulting from performing reverse on the NWA in Figure \\ref{Fi:Example1}.}\n      \\label{Fi:Reverse1}\n    \\end{minipage}\n  \\end{minipage}\n  \\begin{minipage}{0.49\\textwidth}\n    \\centering\n    \\nwaimage[0.75]{Figures/concat-result}\n    \\caption{The NWA resulting from the concatenation of the NWA in Figure\n      \\ref{Fi:Example1} with the NWA in Figure \\ref{Fi:Concat1}.}\n    \\label{Fi:Concat2}\n  \\end{minipage}\n\\end{figure}\n\n\\antistupidfloats\n\n\n\nThe state sets of the NWAs must not overlap,\ni.e., $Q_1 \\cap Q_2 = \\emptyset$. \\textsl{Client code should not rely on\n  this condition being checked.}\n\nClient information is copied directly from the original NWAs using\n\\texttt{ClientInfo::clone()}.\n\n\\figref{Concat2} shows the result of concatenating \\figref{Example1} and\n\\figref{Concat1}.\n\n\\subsection{Kleene star}\n\\label{Se:Star}\n\nLike concatenation, Kleene-star is complicated in the case of NWAs because of\nthe ability to have unbalanced words in the automaton's\nlanguage. Relative to standard FAs, in the concatenation construction we only needed\nto add extra transitions; in this construction, we must add additional states\nas well.\n\nThe NWA resulting from performing Kleene-Star on the NWA shown in\n\\figref{Star1} is shown in \\figref{Star2}.\n\nThe construction presented in \\cite{JACM:AM2009} has a minor error. The error is\nanalogous to not adding a distinguished start state in the traditional\nThompson construction,\\footnote{The initial state of the automaton $A^*$\n  must accept, because $\\epsilon$ is in $L^*$; and because of this property it is\n  incorrect to merely add epsilon transitions from the old final states to\n  the old initial states. If you do this and there is a cycle from the\n  initial state back to itself (for example, a self-loop on the initial\n  state), the word corresponding to that path would be accepted even though\n  it should not be.} and in\nfact can be exhibited using the same example (it is not necessary to use NWA\ncalls or returns). Alur confirmed that our interpretation of the construction\nin \\cite{JACM:AM2009} is\ncorrect~\\cite{AlurNwaStarBroken}. Below, we present\na version that uses $\\epsilon$-transitions, and thus it looks a bit\ndifferent from the version in \\cite{JACM:AM2009}.\n\nWhen computing $R = A^*$ for some\nNWA $A$, the resulting NWA has two ``copies'' of $A$. These are denoted by\nprimed and unprimed version of states from $A$ in the definition below. \n\n\\begin{figure}[p]\n  \\centering\n    \\nwaimage[.4]{Figures/star-simple}\n  \\caption{An NWA on which to perform Kleene-Star.}\n  \\label{Fi:Star1}\n\\end{figure}\n\n\\begin{figure}[p]\n  \\centering\n    \\nwaimage[1.1]{Figures/star-simple-result}\n  \\caption{The NWA resulting from performing Kleene-Star on the NWA in Figure \\ref{Fi:Star1}.}\n  \\label{Fi:Star2}\n\\end{figure}\n\\antistupidfloats\n\n\nSuppose that $R$ is reading a word $w=w_1w_2\\cdots w_n$, where each $w_i \\in\nL(A)$. $R$ begins in a start state of $A'$. Henceforth it maintains the\nfollowing invariant on the state that $R$ is in with respect to the portion\nof $w$ read so far: if the next symbol $\\sigma$ is in a return position, then\nthat\nsymbol is a \\emph{pending} return in the current $w_i$ iff $R$ is in the $A'$\nportion, i.e., if the current state is primed. (Note that this return only\nneeds to be\npending in the current $w_i$. In the full string $w$, $\\sigma$ may match a\ncall in an earlier $w_j$, or it may be pending in the whole string.)\n\nInternal transitions thus keep $R$ in the same copy of $A$, and call\ntransitions always take $R$ to the unprimed copy of $A$ (because if it then\nreads a return, the return will match that call). Return transitions can\ntarget either copy of $A$: if the call predecessor is unprimed, then the\ntarget will be unprimed; if the call predecessor is primed, then the target\nwill be primed.\n\nThe description above describes $R$'s operation under ``normal''\nconditions. If $R$ is in a final state (either primed or unprimed) of the\nautomaton $A$, it is also allowed to guess that it should ``restart'' by taking\nan epsilon transition to a distinguished start and final state $q_0$. This\nguess is correct if it just read the\nlast character in $w_i$ (making the next character the first one in\n$w_{i+1}$). Note that $q_0$ only has transitions to\nthe $A'$ portion of $R$, maintaining the invariant.\n\nThe reason for the two copies of $A$ comes into play when $R$ reads a return\n$\\sigma$ while in the $A'$ portion. By the invariant, $\\sigma$ is pending in the\ncurrent $w_i$. In the original automaton $A$, the transitions that the\nmachine can use are return transitions $(q,r,\\sigma,p)$ where the call predecessor\n$r$ is in $Q_0$. We need to make sure that $R$ can take those same\ntransitions. There are two cases we need to consider:\n\\begin{enumerate}\n\\item For the cases where\n$\\sigma$ is pending in the whole string $w$, we need to have a version of the\nreturn transition with $q_0$ in the call-predecessor position, so we add $(q',\nq_0, \\sigma, p')$.\n\\item For the cases where $\\sigma$ is matched with a call in some\nearlier $w_j$, it does not matter what state the machine was in before that\ncall; thus we add $(q', s, \\sigma, p')$ for each state $s$ in $Q \\cup Q'$.\n\\end{enumerate}\n\\vspace{0.25\\baselineskip}\n\n``Normal'' operation corresponds to the transitions introduced by the\n\\textsc{Internal}, \\textsc{Call}, and \\textsc{Locally-Matched-Return}\ninference rules given below. The source states of both transitions added by\n\\textsc{Locally-Matched-Return} are unprimed, because if the current symbol\nis a return that matches a call in the same $w_i$, $R$ will be in\nthe $A$ portion by the invariant.\nThe \\textsc{Restart} rule allows $R$ to restart, and the\n\\textsc{Start} rule allows $R$ to get from $q_0$ to the $A'$ portion; these\ntransitions target the $A'$ portion because there have been no calls read in\nthe current $w_i$, and thus a return symbol would be pending.\nThe \\textsc{Globally-Pending-Return} rule addresses the situation where the\ncurrent symbol is a return that is pending in the whole string $w$. (This is\nthe first case in the previous paragraph.) The \\textsc{Locally-Pending-Return} rule\naddresses the situation where the current symbol is a return that is pending\nin the current $w_i$ but matches a call from a previous $w_j$.\n\n\nFormally, if the original NWA is $(Q, \\Sigma, Q_0, \\delta, Q_f)$,\nthen the result of performing Kleene-Star on that NWA is $(Q^*, \\Sigma,\nQ_0^*, \\delta^*, Q_f^*)$. The sets of states are defined by $Q^* = Q \\cup\nQ' \\cup \\{q_0\\}$ (with $Q' = \\{q'\\, |\\, q \\in Q\\}$ and $q_0 \\not \\in Q$),\nand  $Q_0^* = Q_f^* = \\{q_0\\}$.\nThe transitions in $\\delta^*$ are defined by the following rules:\n\n\\begin{mathpar}\n{\\inferrule*[left=\\textsc{Internal}]\n             {(q,\\sigma,p) \\in \\delta_i }\n  { (q,\\sigma,p) \\in  \\delta_i^* \\\\ (q',\\sigma,p') \\in \\delta_i^*}\n}\n\\and\n{\\inferrule*[right=\\textsc{Call}]\n           { (q,\\sigma,p) \\in \\delta_c  }\n  { (q,\\sigma,p) \\in  \\delta_c^* \\\\ (q',\\sigma,p) \\in \\delta_c^*   }\n}\n\\and\n{\\inferrule*[left=\\textsc{Locally-Matched-Return}]\n              { (q,r,\\sigma,p) \\in \\delta_r }\n  {(q,r,\\sigma,p) \\in  \\delta_r^* \\\\ (q,r',\\sigma,p') \\in \\delta_r^* }\n}\n\\\\\n\\and\n{\\inferrule*[left=\\textsc{Start}]\n  { q \\in Q_0 }\n  {(q_0, \\epsilon, q') \\in \\delta_i^*}\n}\n\\and\n{\\inferrule*[right=\\textsc{Retart}]\n  { q \\in Q_f }\n  {(q, \\epsilon, q_0) \\in \\delta_i^* \\\\ (q', \\epsilon, q_0) \\in \\delta_i^* }\n}\n\\and\n{\\inferrule*[left=\\textsc{Globally-Pending-Return}]\n  { (q,r,\\sigma,p) \\in \\delta_r \\\\ r \\in Q_0 }\n  {(q',q_0,\\sigma,p') \\in  \\delta_r^* }\n}\n\\and\n{\\inferrule*[left=\\textsc{Locally-Pending-Return}]\n  { (q,r,\\sigma,p) \\in \\delta_r \\\\ r \\in Q_0 \\\\ s \\in Q \\cup Q' }\n  {(q',s,\\sigma,p') \\in \\delta_r^* }\n}\n\\end{mathpar}\n\n\nClient information is copied directly from the original NWA (using\n\\texttt{ClientInfo::clone()}) such that for each $q \\in Q$, $q$\nand $q'$ have (different copies of) the same client information.\n\n\\emph{Note:} The key for state $q'$ is generated from the key for state $q$\nusing the expression \\texttt{getKey(q, getKey(\"prime\"))}. The input automaton\nto the Kleene star function must not already contain both $q$ and $q'$ for\nany $q$.\n\n%Consider the slightly more complex example of computing the Kleene-Star of the NWA shown in Figure \\ref{Fi:Star3}.  The resulting NWA is shown in Figure \\ref{Fi:Star4}.\n\n%\\begin{figure}[htbp]\n%  \\centering\n%    \\includegraphics[angle=270,width=10cm]{Figures/Figure13.pdf}\n%  \\caption{Complex NWA on which to perform Kleene-Star.}\n%  \\label{Fi:Star3}\n%\\end{figure}\n\n%\\begin{figure}[htbp]\n%  \\centering\n%    \\includegraphics[angle=270,width=12cm]{Figures/Figure14.pdf}\n%  \\caption{The NWA resulting from performing Kleene-Star on the NWA in Figure \\ref{Fi:Star3}.}\n%  \\label{Fi:Star4}\n%\\end{figure}\n\n\\subsection{Reverse}\n\\label{Se:Reverse}\n\nA nested word $n = (w, \\rightsquigarrow)$ is reversed by reversing the linear\nword $w$ and exchanging calls and returns. Formally,\n$n^{rev} = (w^{rev}, \\{(|w|+1-r, |w|+1-c) | (c,r)\n\\in\\rightsquigarrow\\})$. (Pending calls and returns are handled by defining\n$|w|+1-(+\\infty) = -\\infty$ and $|w|+1-(-\\infty) = +\\infty$.) Roughly\nspeaking, call transitions in $A$ correspond to return transitions in\n$A^{rev}$ and vice versa, and we reverse the direction of all transitions as\nin the standard FA construction. We describe the construction from the\nperspective of $A^{rev}$ --- that is, a ``call transition'' is a call\ntransition in $A^{rev}$, and a ``call'' is a call in the reversed string.\n\nPerhaps unsurprisingly, pending returns pose a problem because the\nrole of initial and final states are exchanged. Because of this complication,\nthe algorithm for reversing an NWA has a similar flavor to that of the\nKleene-star procedure. The automaton $A^{rev}$ has two ``copies'' of $A$\n(primed and unprimed), and maintains the same invariant as the Kleene-star\nconstruction: if\nthe next symbol $\\sigma$ is in a return position, then that symbol is a\n\\emph{pending} return iff $A^{rev}$ is in the $A'$ portion.\n(For those familiar with the construction in \\cite{JACM:AM2009}, ours is more\ncomplicated because the version in \\cite{JACM:AM2009} will not work as stated\nwith a weakly-hierarchical NWA.)\n\nIf the original NWA is $(Q, \\Sigma, Q_0, \\delta, Q_f)$, then the result of\nreversing that NWA is $(Q \\cup Q', \\Sigma, Q_f', \\delta^{rev}, Q_0)$ obtained using\nthe following rules:\n\n\\begin{mathpar}\n{\\inferrule*[left=\\textsc{Internal}]\n     { (p,\\sigma,q) \\in \\delta_i  }\n  { (q,\\sigma,p)  \\in \\delta^{rev}_i \\\\ (q',\\sigma,p')  \\in \\delta^{rev}_i }\n} \n\\and\n{\\inferrule*[left=\\textsc{Call-Return}]\n       { (q_c,\\sigma_c,q_e) \\in  \\delta_c \\\\ (q_x,\\_\\!\\_\\,,\\sigma_r,q_r) \\in \\delta_r }\n  { (q_r, \\sigma_r, q_x), (q_r', \\sigma_r, q_x) \\in \\delta^{rev}_c \\\\\n    (q_e, q_r, \\sigma_c, q_c), (q_e, q_r', \\sigma_c, q_c') \\in \\delta^{rev}_c }\n}\n\\and\n{\\inferrule*[left=\\textsc{Pending-Return}]\n       { (q_c,\\sigma,q_e) \\in  \\delta_c \\\\ q_f \\in Q_f }\n  { (q_e', q_f, \\sigma, q_c') \\in \\delta^{rev}_R }\n}\n\\end{mathpar}\n%The \\textsc{Pending-Return} rule is the most perplexing one. The name\n%\\textsc{Pending-Return} is written from the perspective of the reversed\n%automaton -- in other words, the reversed automaton will take a transition\n%added by this rule when it reads a pending return, and that pending return\n%would have been a pending call in the original automaton. However, $q_f \\in\n%Q_f$ is written from the perspective of the original automaton: because\n%$q_f$ is a final state in the original it is an initial state in the\n%reversed automaton, and this is why the transition can be taken on a pending\n%return.\n\n\nThe NWA resulting from performing reverse on the NWA shown in\nFigure \\ref{Fi:Example1} is shown in Figure \\ref{Fi:Reverse1}.\n \n\nClient\ninformation is copied directly from the original NWA using\n\\texttt{ClientInfo::clone()}.\n\n\\subsection{Determinize}\n\\label{Se:Determinize}\n\n\\begin{definition}\nAn NWA, $(Q,\\Sigma,Q_0,\\delta,Q_f)$, is \\textbf{deterministic} iff \n\n\\begin{enumerate} \n\n\\item $|Q_0| \\leq 1$, \n\n\\item For all $q \\in Q$, there is never a choice between reading $\\sigma$ and\n  following a $\\sigma$ transition or following a wild (\\wild) transition:\n  \\begin{itemize}\n    \\item if $(q,\\wild,q') \\in \\delta_i$ then $|\\{q'|(q,\\sigma,q') \\in\n      \\delta_i, {\\sigma\\neq@}\\}| = 0$; \\\\ otherwise, for all $\\sigma \\in \\Sigma - \\{\\wild\\}$,\n      $|\\{q'|(q,\\sigma,q') \\in \\delta_i\\}| \\leq 1$,\n\n    \\item if $(q,\\wild,q') \\in \\delta_c$ then $ |\\{q'|(q,\\sigma,q') \\in\n      \\delta_c, {\\sigma\\neq@}\\}| = 0$;\\\\\n      otherwise, for all $\\sigma \\in \\Sigma - \\{\\wild\\}$,\n      $|\\{q'|(q,\\sigma,q') \\in \\delta_c\\}| \\leq 1$, and\n\n    \\item \\mbox{for $q' \\in Q$, if $(q,q',\\wild,q'') \\in \\delta_r$ then\n      $|\\{q''|(q,q',\\sigma,q'') \\in \\delta_r, {\\sigma\\neq@}\\}| = 0$;} \\\\\n      otherwise, for all\n      $\\sigma \\in \\Sigma - \\{\\wild\\}$, $|\\{q''|(q,q',\\sigma,q'') \\in \\delta_r\\}|\n      \\leq 1$,\n  \\end{itemize}\n\\item There are no $\\epsilon$ transitions:\n \\begin{itemize}\n   \\item for all $(q,\\sigma,q') \\in \\delta_i, \\sigma \\neq \\epsilon$,\n   \\item for all $(q,\\sigma,q') \\in \\delta_c, \\sigma \\neq \\epsilon$, and\n   \\item for all $(q,q',\\sigma,q'') \\in \\delta_r, \\sigma \\neq \\epsilon$.\n \\end{itemize}\n\\end{enumerate}\nIf an NWA is not deterministic, then it is \\textbf{non-deterministic}.\n\\end{definition}\n\nDeterminizing an NWA operates like a\ngeneralization of the classical subset construction.  Instead of the states\nin the determinized NWA being subsets of states in the original NWA, states of the\ndeterminized NWA are sets of state pairs (i.e., binary relations on states)\n\\cite{JACM:AM2009}.  To support determinization, the library provides a\ntypedef of \\texttt{std::set$<$pair$<$State, State$>>$} as \n\\texttt{Nwa::BinaryRelation}. See also \\texttt{opennwa/RelationOps.hpp}.\n\nWe present the algorithm we use for determinization in\n\\appref{DeterminizeAlgorithm}.\n\n%There is very experimental support for using the BuDDY\n\n\nThe result of determinizing the automaton in \\figref{Det1} is shown in\n\\figref{Det2}.\n\n\\begin{figure}[p]\n  \\centering\n    \\nwaimage[0.45]{Figures/determinize}\n  \\caption{Simple nondeterministic NWA.}\n  \\label{Fi:Det1}\n\\end{figure}\n\n\n\\begin{figure}[p]\n  \\centering\n    \\nwaimage[.75]{Figures/determinize-result}\n    \\caption{The NWA resulting from determinizing the NWA in Figure\n      \\ref{Fi:Det1}. As mentioned in the text, states in the determinized NWA\n      are relations on the states in the original NWA. The state\n      $\\varnothing$ has been removed from this diagram.} \n  \\label{Fi:Det2}\n\\end{figure}\n\n\nClient information is generated through the use of the helper method\n\\texttt{mergeClientInfo}, but can be altered through the use of the helper\nmethods \\texttt{mergeClientInfoInternal}, \\texttt{mergeClientInfoCall}, and\n\\texttt{mergeClientInfoReturn}, which are invoked by \\texttt{determinize} as\ntransitions of the three kinds involving the associated state are added.  The\ndefault behavior of \\texttt{mergeClientInfo} is that the \\texttt{ClientInfo}\nassociated with the resulting state is \\texttt{null}.  The default behavior\nof \\texttt{mergeClientInfoInternal}, \\texttt{mergeClientInfoCall}, and\n\\texttt{mergeClientInfoReturn} is to make no changes to the the\n\\texttt{ClientInfo}.  These methods can be overridden to specify alternative\nbehaviors.  As determinization is performed, \\texttt{mergeClientInfo} is\ncalled each time a new state is created.  Then, as each transition is added,\n\\texttt{mergeClientInfoInternal}, \\texttt{mergeClientInfoCall}, or\n\\texttt{mergeClientInfoReturn} is called (depending on the type of transition\nbeing added) to update the \\texttt{ClientInfo} associated with the target\nstate of the transition being added.\n\nThe following functions can be overridden in a subclass of \\texttt{Nwa} to\ncustomize the behavior of determinization:\n\\begin{functionlist}\n  \\functionDefNoCloseParen{void}{mergeClientInfo}{%\n     \\parbox[t]{4in}{\n       Nwa const \\& nondet, BinaryRelation const \\& binRel, \\\\\n       St resSt, ref\\_ptr<ClientInfo>\\& resCI)}}\n  Callback that gets called when a new state \\texttt{resSt} (representing the\n  binary relation \\texttt{binRel}) is added to the determinized automaton.\n  Intended to provide a hook for computing the client information that should\n  be associated with the new state; the client information should be set in\n  the output parameter \\texttt{resCI} (i.e., \\texttt{setClientInfo} should not\n  be called directly). \\texttt{nondet} is the NWA being determinized.\n\n  \\functionDefFirstEarlyNoCloseParen{void}{mergeClientInfoInternal}{%\n     \\parbox[t]{4in}{\n       Nwa const \\& nondet,\\\\\n       BinaryRelation const \\& binRelSource,\\\\\n       BinaryRelation const \\& binRelTarget,\\\\\n       State sourceSt, Symbol resSym, State resSt,\\\\\n       ref\\_ptr<ClientInfo>\\& resCI )}}\n  \\functionDefEarlyNoCloseParen{void}{mergeClientInfoCall}{%\n     \\parbox[t]{4in}{\n       Nwa const \\& nondet,\\\\\n       BinaryRelation const \\& binRelCall,\\\\\n       BinaryRelation const \\& binRelEntry,\\\\\n       State callSt, Symbol resSym, State resSt,\\\\\n       ref\\_ptr<ClientInfo>\\& resCI )}}\n  \\functionDefNoCloseParen{void}{mergeClientInfoReturn}{%\n     \\parbox[t]{4in}{\n       Nwa const \\& nondet,\\\\\n       BinaryRelation const \\& binRelExit,\\\\\n       BinaryRelation const \\& binRelCall,\\\\\n       BinaryRelation const \\& binRelReturn,\\\\\n       State exitSt, State callSt, Symbol resSym,\\\\\n       State resSt, ref\\_ptr<ClientInfo>\\& resCI )}}\n    Callbacks that get called when a new transition is added to the given\n    automaton. The endpoints and their associated binary relations are\n    given.\n    Alters the client information associated with \\texttt{resSt} given\n    information about the transition being added to the determinized\n    automaton.\n \\end{functionlist}\n\n%Consider the slightly more complex determinization of the NWA shown in Figure \\ref{Fi:Det3}.  The resulting NWA is shown in Figure \\ref{Fi:Det4}.\n\n%\\begin{figure}[htbp]\n%  \\centering\n%    \\includegraphics[angle=270,width=12cm]{Figures/Figure18.pdf}\n%  \\caption{Complex nondeterministic NWA.}\n%  \\label{Fi:Det3}\n%\\end{figure}\n\n%\\begin{figure}[htbp]\n%  \\centering\n%    \\includegraphics[angle=270,width=12cm]{Figures/Figure19.pdf}\n%  \\caption{The NWA resulting from determinizing the NWA in Figure \\ref{Fi:Det3}.}\n%  \\label{Fi:Det4}\n%\\end{figure}\n\n\\subsection{Complement}\n\\label{Se:Complement}\n\nComplementing an NWA is performed by determinizing the automaton and then\ncomplementing the set of final states.\n\\begin{comment}\n In our implementation, an extra flag\nto \\texttt{complement} controls whether the determinization step is to be\nperformed, so it can be bypassed if you have \\textsl{a priori} knowledge that\nthe input NWA must already be deterministic.\n\\end{comment}\nThe result of\ncomplementing the NWA shown in Figure \\ref{Fi:Det1} is\nshown in Figure \\ref{Fi:Comp1}.\n\nClient information is computed during determinization as described in the\nprevious section, then cloned during the complement step.\n\n\\begin{figure}[h]\n  \\centering\n    \\nwaimage[1]{Figures/complement-of-determinize}\n  \\caption{The complement of the NWA in Figure \\ref{Fi:Det1} (the\n    determinization of which is shown in Figure \\ref{Fi:Det2}).  We omit\n    transitions to the state $\\{\\}$; any action that does not appear in the\n    diagram goes to the state $\\{\\}$.\n  }\n  \\label{Fi:Comp1}\n\\end{figure}\n\n\n\n", "meta": {"hexsha": "275b426e8937606f8cd92730759e8a42872a3a52", "size": 36227, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Doc/opennwa/03-building-from-others.tex", "max_stars_repo_name": "jusito/WALi-OpenNWA", "max_stars_repo_head_hexsha": "2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2015-03-07T17:25:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T20:17:00.000Z", "max_issues_repo_path": "src/wpds/Doc/opennwa/03-building-from-others.tex", "max_issues_repo_name": "ucd-plse/mpi-error-prop", "max_issues_repo_head_hexsha": "4367df88bcdc4d82c9a65b181d0e639d04962503", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-03-03T05:58:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-03T12:26:10.000Z", "max_forks_repo_path": "src/wpds/Doc/opennwa/03-building-from-others.tex", "max_forks_repo_name": "ucd-plse/mpi-error-prop", "max_forks_repo_head_hexsha": "4367df88bcdc4d82c9a65b181d0e639d04962503", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2015-09-25T17:44:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-18T18:25:38.000Z", "avg_line_length": 44.12545676, "max_line_length": 169, "alphanum_fraction": 0.7123140199, "num_tokens": 10726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.34201892787234045}}
{"text": "\\documentclass[11pt, a4paper, oneside]{article}\n\n\\usepackage{color}\n\\usepackage{tikz}\n\\usepackage{showframe}\n\\usepackage{blindtext}\n\\usepackage{amsmath}\n\\usepackage{amsthm}\n\\usepackage{bm}\n\\usepackage{calc}  \n\\usepackage{enumitem} \n\\usepackage{xcolor}\n\\usepackage{lipsum}\n\\usepackage{setspace}\n\\usepackage{glossaries}\n\\usepackage{latexsym}\n\n\\tikzset{\n    vertex/.style = {\n        circle,\n        fill = black,\n        outer sep = 2pt,\n        inner sep = 1pt,\n    }\n}\n\n\\SetLabelAlign{parright}{\\parbox[t]{\\labelwidth}{\\raggedleft#1}}\n\\setstretch{0.5}\n\n\\DeclareMathOperator*{\\argmin}{argmin}\n\n\\begin{document}\n\n\\title{}\n\\author{}\n\\date{}\n\n%Dataset\n%name: LS3D-W.\n%download: https://www.adrianbulat.com/face-alignment/\n\n\\part*{Studies dependency}.\n\n\\section*{Face alignment 2D}\n\nCao, X., Wei, Y., Wen, F., Sun, J.: Face alignment by explicit shape regression. In: CVPR. (2012)\n\nXiong, X., De la Torre, F.: Supervised descent method and its applications to face alignment. In: CVPR. (2013) 532–539\n\nJourabloo, A., Liu, X.: Pose-invariant 3d face alignment. In: CVPR. (2015) 3694–3702\n\nZhu, S., Li, C., Change Loy, C., Tang, X.: Face alignment by coarse-to-fine shape searching. In: CVPR. (2015) 4998–5006\n\nBulat, A., Tzimiropoulos, G.: Convolutional aggregation of local evidence for large pose face alignment. In: BMVC. (2016)\n\n\\section*{Face alignment 3D}\n\nBulat, A.,Tzimiropoulos, G.: Two-stage Convolutional Part Heatmap Regression for the 1st 3D Face Alignment in the Wild (3DFAW) Challenge. ???? (2016)\n\n\n\\part*{Bulat 2017 Face Alignment}\n\n\\noindent\nNormalized Mean Error:\n\n\\begin{equation}\n\\text{NME}\n= \\frac{1}{N} \\sum_{k=1}^N \\frac{\\| \\mathbf{x}_k - \\mathbf{y}_k \\|^2}{d}\n\\tag{}\n\\end{equation}\n\n\\begin{description}[labelwidth=\\widthof{\\bfseries 123456789012345},align=parright]\n\t\\item[Input variable: ]\t$d = \\sqrt{w_{ \\mathit{bbox}} * h_{\\mathit{bbox}} }$\n\t\\item[$\\mathit{bbox}:$] bounding box.\n\\end{description}\n\n\\bigskip\n\n\\part*{Bulat 2016 Two stage 3D pose}\n\n\\begin{equation}\nl_2 = \\frac{1}{N} \\sum_{n=1}^N (\\tilde{z}_n - z_n) _2\n\\tag{}\n\\end{equation}\n\n\\bigskip\n\n\\noindent\nGround Truth Error(GTE):\n\n\\begin{equation}\nE( \\mathbf{X}, \\mathbf{Y})\n= \\frac{1}{N} \\sum_{n=1}^N \\frac{\\| \\mathbf{X}_n - \\mathbf{Y}_n \\|_2}{d_i}\n\\tag{}\n\\end{equation}\n\n\\begin{description}[labelwidth=\\widthof{\\bfseries 123456789012345},align=parright]\n\t\\item[$\\mathbf{X}$:] Predicted set of points.\n\t\\item[$\\mathbf{Y}$:] Corresponding ground truth.\n\t\\item[$d_i$:] Interocular distance for the $i$th image.\n\\end{description}\n\n\\bigskip\n\n\\noindent\nCross View Ground Truth Consistency Error(CVGTCE):\n\\begin{equation}\nE_{vc}( \\mathbf{X}, \\mathbf{Y}, T )\n=\\frac{1}{N} \\sum_{n=1}^1 \\frac{\\| s\\mathbf{Rx}_n - \\mathbf{y}_n \\|_2}{d_i}\n\\tag{}\n\\end{equation}\n\n\\begin{equation}\nP = \\{ s, \\mathbf{R}, \\mathbf{t} \\}\n\\tag{}\n\\end{equation}\n\n\\begin{equation}\n\\{ s, \\mathbf{R}, \\mathbf{t} \\}\n= \\argmin_{s, \\mathbf{R}, \\mathbf{t}}\n\\sum_{n=1}^N \\| \\mathbf{y}_k - (s \\mathbf{Rx} + \\mathbf{•}mathbf{t}) \\|_2 ^2\n\\end{equation}\n\n\n\n\\end{document}", "meta": {"hexsha": "d85b73f2b3fd404d421a11767c1234b03418d16d", "size": 3002, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "book_reviews/face_alignment.tex", "max_stars_repo_name": "booiljung/booiljung.github.io", "max_stars_repo_head_hexsha": "1a861660b4bf3c049ed8f47fc8f5346ee8de7823", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "book_reviews/face_alignment.tex", "max_issues_repo_name": "booiljung/booiljung.github.io", "max_issues_repo_head_hexsha": "1a861660b4bf3c049ed8f47fc8f5346ee8de7823", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "book_reviews/face_alignment.tex", "max_forks_repo_name": "booiljung/booiljung.github.io", "max_forks_repo_head_hexsha": "1a861660b4bf3c049ed8f47fc8f5346ee8de7823", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8253968254, "max_line_length": 149, "alphanum_fraction": 0.6805463025, "num_tokens": 1133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.6001883592602049, "lm_q1q2_score": 0.3420189278723404}}
{"text": "\\chapter[Agent Based Simulation]{Agent Based Simulation}\\label{chp:agent_based_simulation}\n\n\\chapterinitial{S}{ometimes} individual behaviours and interactions are well\nunderstood, and an understanding of how a whole population of such individuals\nmight behave needed. For example psychologists and economists may know a lot\nabout how individual spenders and vendors behave in response to given stimuli,\nbut an understanding of how these stimuli might effect the macro-economy is\nnecessary. Agent based\\index{agent based} simulation is a paradigm of thinking\nthat allows such emergent population level behaviour to be investigated from\nindividual rules and interactions.\n\n\\section{Problem}\\label{sec:agent_based_simulation_problem}\n\nConsider a city populated by two categories of household, for example a household\nmight be fans of Cardiff City FC or Swansea City AFC\\footnote{Swansea and\nCardiff are two cities in South Wales with rival football clubs.}.\nEach household has a preference for living close to households of the same kind,\nand will move around the city while their preferences are not satisfied.\nHow will these individual preferences affect the overall distribution of fans in\nthe city?\n\n\\section{Theory}\\label{sec:agent_based_simulation_theory}\n\nThe problem considered here is considered a `classic' one for the paradigm of\nagent based simulation, and is referred to as Schelling\\index{Schelling}'s\nsegregation model. It features in Thomas Schelling's book `Micromotives and\nMacrobehaviours'~\\cite{schelling2006micromotives}, whose title neatly summarises\nthe world view of agent based modelling: we know, understand, determine, or can\ncontrol individual micromotives; and from this we'd like to observe and\nunderstand macrobehaviours.\n\nIn general an agent based model consists of two components, agents, and an\nenvironment:\n\n\\begin{itemize}\n    \\item agents are autonomous entities that will periodically choose to take one\n        of a number of actions.\n        These are chosen in order to maximise that agent's own given utility\n        function;\n    \\item an environment contains a number of agents and defines how their\n        interactions affect each other.\n        The agents may be homogeneous or heterogeneous, and the\n        relationships may change over time, possibly due to the actions taken\n        by the agents.\n\\end{itemize}\n\nIn general, an agent will first observe a subset of its environment, for\nexample it will consider some information about the agents it is currently\nclose to.\nThen it will update some information about itself based on these observations.\nThis could be recording relevant information from the observations, but could\nalso include some learning, maybe considering its own previous actions.\nIt will then decide on an action to take, and carry out this action. This\ndecision may be deterministic or random and/or based on its own attributes from\nsome learning process\\index{learning process}; with the ultimate aim of\nmaximising its own utility. In practice, a utility\\index{utility} can be\nrepresented by a function that maps the environment to some numeric value.\nThis process happens to all agents in the environment, possibly simultaneously.\nThis is summarised in Figure~\\ref{fig:abm_diagram}\n\n\\begin{figure}\n    \\begin{center}\n        \\includestandalone[width=\\textwidth]{./assets/abm-diagram}\n    \\end{center}\n    \\caption{Representation of an agent interacting with its environment.}\n    \\label{fig:abm_diagram}\n\\end{figure}\n\nFor the football team supporters problem, each household is an agent.\nThe environment is the city.\nEach household's utility function is to satisfy their preference of living next\nto at least a given number of households supporting the same team as them.\nTheir choices of action are to move house or not to move house.\n\nAs a simplification the city will be modelled as a \\(50 \\times 50\\) grid.\nEach cell of the grid is a house that can either contain a household of Cardiff\nCity FC supporters, or contain a household of Swansea City AFC supporters.\nA house's neighbours are assumed to be the houses adjacent to it, horizontally,\nvertically, and diagonally.\nFor mathematical simplicity, it is also assumed that the grid is a torus,\nwhere houses in the top row are vertically adjacent to the bottom row, and\nhouses in the rightmost column are horizontally adjacent to the leftmost column.\n\nEvery household has a preference \\(p\\).\nThis corresponds to the minimum proportion of neighbours they are happy to live\nFigure~\\ref{fig:schelling_happyunhappy} shows a household of Cardiff City FC\nsupporters that are happy with their neighbours, and not happy with their\nneighbours, when \\(p=0.5\\). Households supporting Cardiff City FC are shaded\ngrey.\n\n\\begin{figure}\n    \\begin{center}\n        \\subfigure[A happy household, with 6 similar neighbours (\\(\\frac{6}{8} > p = 0.5\\))]{\\includestandalone[width=0.4\\textwidth]{./assets/schelling_happy}}\n        \\subfigure[An unhappy household, with 2 similar neighbours (\\(\\frac{2}{8} < p = 0.5\\))]{\\includestandalone[width=0.4\\textwidth]{./assets/schelling_unhappy}}\n    \\end{center}\n    \\caption{Example of a household happy and unhappy with its neighbours, when\n    \\(p=0.5\\). Households supporting Cardiff City FC are shaded grey, households\n    supporting Swansea City AFC are white.}\n    \\label{fig:schelling_happyunhappy}\n\\end{figure}\n\nThe original problem stated that households move around the city whenever they\nare unhappy with their neighbours.\nThis long process of selling, searching for, and buying houses can be simplified\nto randomly pairing two unhappy households and swapping their houses.\nIn fact, this can be simplified to consider the houses themselves as agents,\nwho swap households with each other.\n\nTherefore the model logic is:\n\n\\begin{enumerate}\n  \\item initialise the model: fill each house in the grid with either a\n  household of Cardiff City FC or Swansea City AFC supporters with\n  probability \\(0.5\\) each;\n  \\item at each discrete time step, for every house:\n  \\begin{enumerate}\n    \\item consider their household's neighbours (\\textit{observe});\n    \\item determine if the household is happy (\\textit{update});\n    \\item if unhappy (\\textit{decide}), swap household with another randomly\n    chosen house with an unhappy household (\\textit{action}).\n  \\end{enumerate}\n\\end{enumerate}\n\nAfter a number of time steps the overall structure of the city can be observed.\nThis agent based model only explicitly defines individual behaviours\nand interactions, therefore any population level behaviour that may have emerged\nwould occur without explicit definition.\n\n\\section{Solving with Python}\\label{sec:agent_based_simulation_solving-with-python}\n\nAgent based modelling lends itself well to a programming paradigm called\nobject-orientated programming\\index{object-orientated programming}.\nThis paradigm lets a number of \\textit{objects} from a set of instructions\ncalled a \\textit{class} to be built.\nThese objects can both store information (in Python these are called\n\\textit{attributes}\\index{attribute}), and do things (in Python these are called\n\\textit{methods}\\index{method}).\nObject-orientated programming allow for the creation of new classes which can be\nused to implement the individual behaviours of an agent based model.\n\nFor this problem two classes will be built: a\n\\mintinline{python}{House} and a \\mintinline{python}{City} for them to live in.\n\nThe following libraries will be used:\n\n\\begin{pyin}\nimport random\nimport itertools\nimport numpy as np\n\\end{pyin}\n\nNow to define the \\mintinline{python}{City}:\n\n\\begin{pyin}\nclass City:\n    def __init__(self, size, threshold):\n        \"\"\"Initialises the City object.\n\n        Args:\n            size: an integer number of rows and columns\n            threshold: float between 0 and 1 representing the\n            minimum acceptable proportion of similar neighbours\n        \"\"\"\n        self.size = size\n        sides = range(size)\n        self.coords = itertools.product(sides, sides)\n        self.houses = {\n            (x, y): House(x, y, threshold, self)\n            for x, y in self.coords\n        }\n\n    def run(self, n_steps):\n        \"\"\"Runs the simulation of a number of time steps.\n\n        Args:\n            n_steps: an integer number of steps\n        \"\"\"\n        for turn in range(n_steps):\n            self.take_turn()\n\n    def take_turn(self):\n        \"\"\"Swaps all sad households.\"\"\"\n        sad = [h for h in self.houses.values() if h.sad()]\n        random.shuffle(sad)\n        i = 0\n        while i <= len(sad) / 2:\n            sad[i].swap(sad[-i])\n            i += 1\n\n    def mean_satisfaction(self):\n        \"\"\"Finds the average household satisfaction.\n\n        Returns:\n            The average city's household satisfaction\n        \"\"\"\n        return np.mean(\n            [h.satisfaction() for h in self.houses.values()]\n        )\n\\end{pyin}\n\nThis defines a class, a template or a set of instructions that can be used to\ncreate instances, called objects.\nFor the considered problem only one instance of the \\mintinline{python}{City}\nclass will be needed.\nHowever, it is useful to be able to produce more in order to run multiple trials\nwith different random seeds.\nThis class contains four methods: \\mintinline{python}{__init__},\n\\mintinline{python}{run}, \\mintinline{python}{take_turn} and\n\\mintinline{python}{mean_satisfaction}.\n\nThe \\mintinline{python}{__init__} method is run whenever the object is first\ncreated, and initialises the object.\nIn this case it sets a number of attributes.\n\n\\begin{itemize}\n     \\item First the square grid's \\mintinline{python}{size} is defined, which\n           is the number of rows and columns of houses it contains;\n     \\item next the \\mintinline{python}{coords} are defined, a list of tuples\n           representing all the possible coordinates of the grid, this uses the\n           itertools library for efficient iteration;\n     \\item finally \\mintinline{python}{houses} is defined, a dictionary with\n           grid coordinates as keys, and instances of the\n           \\mintinline{python}{House} class.\n\\end{itemize}\n\n\nThe \\mintinline{python}{run} method runs the simulation. For each\n\\mintinline{python}{n_steps} number of discrete time steps, the city runs the\nmethod \\mintinline{python}{take_turn}.\nIn this method, first a list of all the houses is created with households that\nare unhappy with their neighbours; these are put in a random order using the\nrandom library; and then working inwards from the boundary\nhouses with sad households are paired up and swap households.\n\nThe last method defined here is the \\mintinline{python}{mean_satisfaction}\nmethod, which is only used to observe any emergent behaviour\\index{emergent behaviour}.\nThis calculates the average satisfaction of all the houses in the grid, using\nthe numpy library for convenience.\n\nIn order to be able to create an instance of the above class, we need to define\na \\mintinline{python}{House} class:\n\n\\begin{pyin}\nclass House:\n    def __init__(self, x, y, threshold, city):\n        \"\"\"Initialises the House object.\n\n        Args:\n            x: the integer x-coordinate\n            y: the integer y-coordinate\n            threshold: a number between 0 and 1 representing\n              the minimum acceptable proportion of similar\n              neighbours\n            city: an instance of the City class\n        \"\"\"\n        self.x = x\n        self.y = y\n        self.threshold = threshold\n        self.kind = random.choice([\"Cardiff\", \"Swansea\"])\n        self.city = city\n\n    def satisfaction(self):\n        \"\"\"Determines the household's satisfaction level.\n\n        Returns:\n            A proportion\n        \"\"\"\n        same = 0\n        for x, y in itertools.product([-1, 0, 1], [-1, 0, 1]):\n            ax = (self.x + x) % self.city.size\n            ay = (self.y + y) % self.city.size\n            same += self.city.houses[ax, ay].kind == self.kind\n        return (same - 1) / 8\n\n    def sad(self):\n        \"\"\"Determines if the household is sad.\n\n        Returns:\n            a Boolean\n        \"\"\"\n        return self.satisfaction() < self.threshold\n\n    def swap(self, house):\n        \"\"\"Swaps two households.\n\n        Args:\n            house: the house object to swap household with\n        \"\"\"\n        self.kind, house.kind = house.kind, self.kind\n\\end{pyin}\n\nIt contains four methods: \\mintinline{python}{__init__},\n\\mintinline{python}{satisfaction}, \\mintinline{python}{sad} and\n\\mintinline{python}{swap}.\n\nThe \\mintinline{python}{__init__} methods sets a number of attributes at the\ntime the object is created: the house's \\mintinline{python}{x} and\n\\mintinline{python}{y} coordinates (its column and row numbers on the grid);\nits \\mintinline{python}{threshold} which corresponds to \\(p\\); its\n\\mintinline{python}{kind} which is randomly chosen between having a Cardiff City\nFC supporting household or a Swansea City AFC supporting household; and finally\nits \\mintinline{python}{city}, an instance of the \\mintinline{python}{City}\nclass, shared by all the houses.\n\nThe \\mintinline{python}{satisfaction} method loops though each of the house's\nneighbouring cells in the city grid, counts the number of neighbours that are\nof the same kind as itself, and returns this as a proportion.\nThen the \\mintinline{python}{sad} method returns a boolean indicating if the\nhousehold's satisfaction is below the minimum threshold.\n\nFinally the \\mintinline{python}{swap} method takes another house object, and\nswaps their household kinds.\n\nA function to create and run one of these simulations will now be written\nwith a given random seed\\index{random seed}, threshold, and number of steps.\nThis function returns the resulting mean happiness:\n\n\\begin{pyin}\ndef find_mean_happiness(seed, size, threshold, n_steps):\n    \"\"\"Create and run an instance of the simulation.\n\n    Args:\n        seed: the random seed to use\n        size: an integer number of rows and columns\n        threshold: a number between 0 and 1 representing\n            the minimum acceptable proportion of similar\n            neighbours\n        n_steps: an integer number of steps\n\n    Returns:\n        The average city's household satisfaction after\n        n_steps\n    \"\"\"\n    random.seed(seed)\n    C = City(size, threshold)\n    C.run(n_steps)\n    return C.mean_satisfaction()\n\\end{pyin}\n\nNow consider each household with a threshold of\n0.65, and compare the mean happiness after 0 steps and 100 steps.\nFirst 0 steps:\n\n\\begin{pyin}\ninitial_happiness = find_mean_happiness(\n    seed=0, size=50, threshold=0.65, n_steps=0\n)\nprint(initial_happiness)\n\\end{pyin}\n\n\\begin{pyout}\n0.4998\n\\end{pyout}\n\nThis is well below the minimum threshold of \\(0.65\\), and so on average\nhouseholds are unhappy.\nAfter 100 steps:\n\n\\begin{pyin}\nfinal_happiness = find_mean_happiness(\n    seed=0, size=50, threshold=0.65, n_steps=100\n)\nprint(final_happiness)\n\\end{pyin}\n\n\\begin{pyout}\n0.9078\n\\end{pyout}\n\nAfter 100 time steps the average satisfaction level is much higher.\nIn fact, it is much higher than each individual household's threshold.\nNow consider that this satisfaction level is really a level of how similar\neach households' neighbours are, it is actually a level of segregation.\nThis was the central premise of Schelling's original\nmodel~\\cite{schelling2006micromotives}\nthat overall emergent segregation levels are much higher than any individuals'\npersonal preference for segregation.\n\nMore analysis methods can be added, including plotting functions.\nFigure~\\ref{fig:schelling_python_plot} shows the grid at the beginning, after 20\ntime steps, and after 100 time steps, with households supporting Cardiff City FC\nin grey, and those supporting Swansea City AFC in white.\nIt visually shows the households segregating over time.\n\n\\begin{figure}\n\\begin{center}\n\\subfigure[At the beginning.]{\\includegraphics[width=0.32\\textwidth]{./assets/python_schelling_0}}\n\\subfigure[After 20 time steps.]{\\includegraphics[width=0.32\\textwidth]{./assets/python_schelling_20}}\n\\subfigure[After 100 time steps.]{\\includegraphics[width=0.32\\textwidth]{./assets/python_schelling_100}}\n\\end{center}\n\\caption{Plotted results from the Python code.}\n\\label{fig:schelling_python_plot}\n\\end{figure}\n\n\\section{Solving with R}\\label{sec:agent_based_simulation_solving-with-R}\n\nAgent based modelling lends itself well to a programming paradigm called\nobject-orientated programming\\index{object-orientated programming}.\nThis paradigm lets a number of \\textit{objects} from a set of instructions\ncalled a \\textit{class} to be built.\nThese objects can both store information (in the R package used here these are called\n\\textit{fields}\\index{field}), and do things (in the R package used here these are called\n\\textit{methods}\\index{method}).\nObject-orientated programming allow for the creation of new classes which can be\nused to implement the individual behaviours of an agent based model.\n\nThere are a number of ways of doing object-orientated programming in R.\nIn this chapter, a package called R6\\index{R6} will be used here.\n\nFor this problem two classes will be built: a\n\\mintinline{R}{House} and a \\mintinline{R}{City} for them to live in.\n\nNow to define the \\mintinline{R}{City}\\footnote{\nNote that no documentation is included in the definition\nof the class and the style is inconsistent with the other chapters in this book.\nThe authors do not know of any widely accepted convention for documenting classes\nin R, furthermore the text of this chapter serves as detailed documentation in this\ncontext.\n}\n\n\\begin{Rin}\nlibrary(R6)\nCity <- R6Class(\"City\", list(\n  size = NA,\n  houses = NA,\n  initialize = function(size, threshold) {\n    self$size <- size\n    self$houses <- c()\n    for (x in 1:size) {\n      row <- c()\n      for (y in 1:size) {\n        row <- c(row, House$new(x, y, threshold, self))\n      }\n      self$houses <- rbind(self$houses, row)\n    }\n  },\n  run = function(n_steps) {\n    if (n_steps > 0) {\n      for (turn in 1:n_steps) {\n        self$take_turn()\n      }\n    }\n  },\n  take_turn = function() {\n    sad <- c()\n    for (house in self$houses) {\n      if (house$sad()) {\n        sad <- c(sad, house)\n      }\n    }\n    sad <- sample(sad)\n    num_sad <- length(sad)\n    i <- 1\n    while (i <= num_sad / 2) {\n      sad[[i]]$swap(sad[[num_sad - i]])\n      i <- i + 1\n    }\n  },\n  mean_satisfaction = function() {\n    mean(sapply(self$houses, function(x) x$satisfaction()))\n  }\n) )\n\\end{Rin}\n\nThis defines an R6 class, a template or a set of instructions that can be used\nto create instances of it, called objects.\nFor this model only one instance of the \\mintinline{R}{City} class is needed,\nalthough it may be useful to be able to produce more in order to run multiple\ntrials with different random seeds.\nThis class contains four methods: \\mintinline{R}{initialize},\n\\mintinline{R}{run}, \\mintinline{R}{take_turn} and\n\\mintinline{R}{mean_satisfaction}.\n\nThe \\mintinline{R}{initialize} method is run at the time the object is first\ncreated.\nIt initialises the object by setting a number of its fields:\n\n\\begin{itemize}\n     \\item First the square grid's \\mintinline{R}{size} is defined, which\n           is the number of rows and columns of houses it contains;\n     \\item then the \\mintinline{R}{houses} are defined by iteratively repeating\n           the \\mintinline{R}{rbind} function to create a two-dimensional vector\n           of instances of the, yet to be defined, \\mintinline{R}{House} class,\n           representing the houses themselves.\n\\end{itemize}\n\nThe \\mintinline{R}{run} method runs the simulation. For each discrete time\nstep from 1 to \\mintinline{R}{n_steps}, the world runs the method\n\\mintinline{R}{take_turn}.\nIn this method, a list of all the houses with households that\nare unhappy with their neighbours is created;\nthese are put in a random order and then working inwards from the boundary,\nhouses with sad households are paired up and swap households.\n\nThe last method defined here is the \\mintinline{R}{mean_satisfaction}\nmethod, which is used to observe the emergent behaviour\\index{emergent behaviour}.\nThis calculates the average satisfaction of all the houses in the grid.\n\nIn order to be able to create an instance of the above class,\na \\mintinline{R}{House} class is needed:\n\n\\begin{Rin}\nHouse <- R6Class(\"House\", list(\n  x = NA,\n  y = NA,\n  threshold = NA,\n  city = NA,\n  kind = NA,\n  initialize = function(x = NA,\n                        y = NA,\n                        threshold = NA,\n                        city = NA) {\n    self$x <- x\n    self$y <- y\n    self$threshold <- threshold\n    self$city <- city\n    self$kind <- sample(c(\"Cardiff\", \"Swansea\"), 1)\n  },\n  satisfaction = function() {\n    same <- 0\n    for (x in -1:1) {\n      for (y in -1:1) {\n        ax <- ( (self$x + x - 1) %% self$city$size) + 1\n        ay <- ( (self$y + y - 1) %% self$city$size) + 1\n        if (self$city$houses[[ax, ay]]$kind == self$kind) {\n          same <- same + 1\n        }\n      }\n    }\n    (same - 1) / 8\n  },\n  sad = function() {\n    self$satisfaction() < self$threshold\n  },\n  swap = function(house) {\n    old <- self$kind\n    self$kind <- house$kind\n    house$kind <- old\n  }\n) )\n\\end{Rin}\n\nIt contains four methods: \\mintinline{R}{initialize},\n\\mintinline{R}{satisfaction}, \\mintinline{R}{sad} and \\mintinline{R}{swap}.\n\nThe \\mintinline{R}{initialize} methods sets a number of the class' fields when\nthe object is created: the house's \\mintinline{R}{x} and \\mintinline{R}{y}\ncoordinates (its column and row numbers on the grid); its\n\\mintinline{R}{threshold} which corresponds to \\(p\\); its \\mintinline{R}{kind}\nwhich is randomly chosen between having a Cardiff City\nFC supporting household or a Swansea City AFC supporting household; and finally\nits \\mintinline{R}{city}, an instance of the \\mintinline{R}{City} class, shared\nby all the houses.\n\nThe \\mintinline{R}{satisfaction} method loops though each of the house's\nneighbouring cells in the city grid, counts the number of neighbours that are of\nthe same kind as itself, and returns this as a proportion.\nThe \\mintinline{R}{sad} method returns a boolean indicating of the\nhousehold's satisfaction is below its minimum threshold.\n\nFinally the \\mintinline{R}{swap} method takes another house object, and\nswaps their household kinds.\n\nA function to create and run one of these simulations will now be written\nwith a given random seed, threshold, and number of steps. This function return\nthe resulting mean happiness:\n\n\\begin{Rin}\n#' Create and run an instance of the simulation.\n#'\n#' @param seed: the random seed to use\n#' @param size: an integer number of rows and columns\n#' @param threshold: a number between 0 and 1 representing\n#'   the minimum acceptable proportion of similar neighbours\n#' @param n_steps: an integer number of steps\n#'\n#' @return The average city's household satisfaction\n#'   after n_steps\nfind_mean_happiness <- function(seed,\n                                size,\n                                threshold,\n                                n_steps){\n  set.seed(seed)\n  city <- City$new(size, threshold)\n  city$run(n_steps)\n  city$mean_satisfaction()\n}\n\\end{Rin}\n\nNow consider each household with a threshold of\n0.65, and compare the mean happiness after 0 steps and 100 steps.\nFirst 0 steps:\n\n\\begin{Rin}\ninitial_happiness <- find_mean_happiness(\n  seed = 0,\n  size = 50,\n  threshold = 0.65,\n  n_steps = 0\n)\nprint(initial_happiness)\n\\end{Rin}\n\n\\begin{Rout}\n[1] 0.4956\n\\end{Rout}\n\nThis is well below the minimum threshold of \\(0.65\\), and so on average\nhouseholds are unhappy here.\nLet's run the simulation for 100 generations and see how this changes:\n\n\\begin{Rin}\nfinal_happiness <- find_mean_happiness(\n  seed = 0,\n  size = 50,\n  threshold = 0.65,\n  n_steps = 100\n)\nprint(final_happiness)\n\\end{Rin}\n\n\\begin{Rout}\n[1] 0.9338\n\\end{Rout}\n\nAfter 100 time steps the average satisfaction has increased.\nIt is now actually much higher that each individual household's threshold.\nThis satisfaction level can be considered as a level of how similar each\nhouseholds' neighbours are, and so it is actually a level of segregation.\nThis was the central premise of Schelling's original\nmodel~\\cite{schelling2006micromotives}, that overall\nemergent segregation levels are much higher than any individuals' personal\npreference for segregation.\n\nMore analysis methods can be added, including plotting functions.\nFigure~\\ref{fig:schelling_R_plot} shows the grid at the beginning, after 20\ntime steps, and after 100 time steps, with households supporting Cardiff City FC\nin grey, and those supporting Swansea City AFC in white.\nIt shows the households segregating over time.\n\n\\begin{figure}\n\\begin{center}\n\\subfigure[At the beginning.]{\\includegraphics[width=0.32\\textwidth]{./assets/schelling_R_0}}\n\\subfigure[After 20 time steps.]{\\includegraphics[width=0.32\\textwidth]{./assets/schelling_R_20}}\n\\subfigure[After 100 time steps.]{\\includegraphics[width=0.32\\textwidth]{./assets/schelling_R_100}}\n\\end{center}\n\\caption{Plotted results from the R code.}\n\\label{fig:schelling_R_plot}\n\\end{figure}\n\n\\section{Wider context}\\label{sec:agent_based_simulation_wider_context}\n\nThe simulations described in this chapter come under the larger umbrella term of\nmulti agent systems, which discusses the theory of systems with multiple\nindependent agents interacting with one another. A good source on the topic\nis~\\cite{shoham2008multiagent}.\n\nThe model described here is called Schelling's\\index{Schelling} segregation\nmodel, and was first described in~\\cite{schelling2006micromotives}. Another model\nconsidered as classic in this domain is a model of a flock of birds presented\nin~\\cite{reynolds1987flocks}, otherwise referred to as Boids\\index{Boids}, where the\nbehaviours of flocks of birds are understood by capturing the individual\ninteractions between individual birds. Conway's Game of\nLife\\index{Conway's Game of Life}, described in~\\cite{gardener1970mathematical} is\nanother classic, which comes under the banner of cellular\nautomata\\index{cellular automata}. Here cells on a grid either become alive or\ndead depending on a certain simplistic set of rules. Emergent behaviours\nobserved due to these rules include self replicating as well as oscillating\nstructures. In the 1970s agent based tournaments were held by Robert\nAxelrod\\index{Axelrod}~\\cite{axelrod1990evolution},\nwhich was the first of a number of studies using agent based modelling and game\ntheory\\index{game theory} (see Chapter~\\ref{chp:game_theory}) to understand the\nemergence of cooperative behaviours.\n\nIn recent years, similar methodologies have been used in a variety of\napplications such as~\\cite{diaz2021agent} which models parents' choice of school,\nin~\\cite{romanowska2019agent} archaeological population migration and trade\ndynamics are modelled, and~\\cite{jing2020agent} offers a systematic\nliterature review for the use of agent based modelling of autonomous vehicles.\n\n", "meta": {"hexsha": "21060f6cd48f309fc19770befaecab42d7027cad", "size": 26828, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/chapters/07/main.tex", "max_stars_repo_name": "drvinceknight/amwoss", "max_stars_repo_head_hexsha": "8b0bf80f0a06dc5cf9bfeef4b9f9e174ccadf06d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-21T21:35:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T21:35:44.000Z", "max_issues_repo_path": "src/chapters/07/main.tex", "max_issues_repo_name": "drvinceknight/amwoss", "max_issues_repo_head_hexsha": "8b0bf80f0a06dc5cf9bfeef4b9f9e174ccadf06d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 71, "max_issues_repo_issues_event_min_datetime": "2019-11-18T11:00:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-21T22:49:40.000Z", "max_forks_repo_path": "src/chapters/07/main.tex", "max_forks_repo_name": "drvinceknight/amwoss", "max_forks_repo_head_hexsha": "8b0bf80f0a06dc5cf9bfeef4b9f9e174ccadf06d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-15T12:00:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-15T12:00:49.000Z", "avg_line_length": 39.3950073421, "max_line_length": 164, "alphanum_fraction": 0.7339346951, "num_tokens": 6501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.34201891910339244}}
{"text": "%===============================================================================\n% COVID-19 Reproduction Numbers in South Africa\n% Kevin Durant\n% May 2020\n%===============================================================================\n\n\\documentclass[12pt,a4paper]{article}\n\n% \\usepackage{booktabs} % better looking tables.\n\\usepackage{mathtools} % also loads amsmath.\n\\usepackage{microtype}\n\\usepackage{iftex}\n\\ifPDFTeX\n  \\usepackage[T1]{fontenc}\n  \\usepackage[utf8]{inputenc}\n  \\usepackage{amssymb}\n\\else\n  % Unicode-math should be loaded after other maths- or font-related packages.\n  % It loads amsmath and fontspec if necessary, and enables a custom version of\n  % the Latin Modern Math font by default.\n  \\usepackage{unicode-math}\n%   \\setmainfont{STIX Two Text}\n%   \\setmathfont{STIX Two Math}\n\\fi\n\\usepackage{biblatex}\n\\usepackage{svg}\n\\usepackage{hyperref}\n\\addbibresource{cvza.bib}\n\n% General maths commands %======================================================\n\n\\newcommand\\ds{\\displaystyle}                 % large maths.\n\\newcommand\\ts{\\textstyle}                    % small maths.\n\\newcommand\\mb[1]{\\mathbb{#1}}                % mathbb shorthand.\n\\newcommand\\mc[1]{\\mathcal{#1}}               % mathcal shorthand.\n\\newcommand\\ub[1]{\\symbf{#1}}                 % unicode-math symbf shorthand.\n\\newcommand\\ff[1]{^{\\underline{#1}}}          % falling factorial.\n\\newcommand\\rf[1]{^{\\overline{#1}}}           % rising factorial.\n\\newcommand\\ul[1]{\\underline{#1}}             % underline.\n\\newcommand\\ol[1]{\\overline{#1}}              % overline.\n\\DeclareMathOperator\\Pb{P}                    % probability.\n\\DeclareMathOperator\\Ex{E}                    % expected value.\n\\DeclareMathOperator\\Va{V}                    % variance.\n\\DeclarePairedDelimiter\\lr{\\lparen}{\\rparen}  % sized parentheses.\n\\DeclarePairedDelimiter\\lrb{\\lbrack}{\\rbrack} % sized brackets.\n\\DeclarePairedDelimiter\\abs{\\lvert}{\\rvert}   % absolute value symbol.\n\\DeclarePairedDelimiter\\cl{\\lceil}{\\rceil}    % ceiling symbol.\n\\DeclarePairedDelimiter\\fl{\\lfloor}{\\rfloor}  % floor symbol.\n\\DeclareMathOperator\\B{B}                     % beta distribution.\n\\DeclareMathOperator\\BP{BP}                   % beta prime distribution.\n\\DeclareMathOperator\\NB{NB}                   % negative binomial distribution.\n\n% Title %=======================================================================\n\n\\title{Estimating COVID-19 Reproduction Numbers}\n\\author{Kevin Durant}\n\\date{June 2020}\n\n% Document %====================================================================\n\n\\begin{document}\n\n\\maketitle\n\n\\begin{abstract}\nThis is a short description of an analytic, \\emph{almost} fully Bayesian\nsolution to the problem of inferring effective reproduction numbers for an\nepidemic from reported infection counts. Under the assumptions of a negative\nbinomial likelihood function and a simple beta prime distributed predictive\nprior, the posterior distribution of the daily infection rate follows a beta\nprime distribution whose parameters can be expressed in closed form. These\nposteriors can in turn be used to estimate effective reproduction numbers.\n\\end{abstract}\n\n\\section{Introduction} %========================================================\n\nThe effective reproduction number of an epidemic, $R_t$, refers to the expected\nnumber of new infections caused by a single infected individual at a given stage\nof the epidemic's course. Along with other, complementary measures, these\nnumbers can help give an indication of the rate at which the epidemic is\nspreading.\n\nThe method for estimating effective reproduction numbers discussed here is a\nslightly different take on one described elsewhere by Kevin\nSystrom~\\cite{systrom2020}, which is itself based on work\nby~\\citeauthor{bettencourt2008}~\\cite{bettencourt2008}. Unlike those two\napproaches, the solution described here is almost entirely analytic---the only\nnumerical computation required being that of percentiles of a beta prime\ndistribution. All three methods are based on a key point made by the latter\nauthors mentioned above: that under the assumptions of a standard epidemic\nsusceptible-infected~(SIR) model, the effective reproduction number of a virus\nat time~$t$ can be estimated from the number of new cases recorded between\ntimes~$t-1$ and~$t$, and~$t$ and~$t+1$.\n\nMore specifically, let~$R_t$ be the effective reproduction number at time~$t$,\nand assume that this number remains constant over the interval~$(t-1, t]$ (most\nlikely a single day)\\footnote{Note that our notation differs slightly from that\nused by~\\citeauthor{bettencourt2008}---our~$R_t$ and~$\\lambda_t$ correspond to\ntheir~$R_{t-1}$ and~$\\Delta T(t)$ respectively.}. Likewise, let~$\\lambda_t$ be\nthe average number of new infections that occur during this interval---i.e., the\ncurrent rate of infection. One then has the following\napproximation~\\cite{bettencourt2008}:\n\\begin{equation*}\n  \\lambda_t \\approx \\lambda_{t-1}\\exp(\\gamma(R_t - 1)),\n\\end{equation*}\nin which $\\gamma$ is the reciprocal of the infectious period of the virus.\nEquivalently,\n\\begin{equation}\\label{eqn:R_t}\n  R_t \\approx \\frac{1}{\\gamma} \\log\\lr*{\\frac{\\lambda_t}{\\lambda_{t-1}}} + 1.\n\\end{equation}\n\nThe approach outlined here involves modelling the number of observed\ninfections~$k_t$ as a stochastic process, assuming that $k_t$ depends on an\nunderlying rate of infection~$\\lambda_t$ via a negative binomial distribution (a\nPoisson distribution can also be used). One can then infer the infection\nrates~$\\lambda_t$ analytically, and use them to estimate effective reproduction\nnumbers by applying equation~\\eqref{eqn:R_t}.\n\nSpecifically, one finds that the posterior rate of infection~$\\lambda_t$ can be\ndescribed using a beta prime distribution:\n\\begin{equation*}\n  \\Pb\\lr*{\\frac{\\lambda_t}{r} \\Bigm\\vert k_1, \\dots, k_{t-1}}\n  = \\BP\\lr*{\\frac{\\lambda_t}{r} \\Bigm\\vert \\alpha_t, \\beta_t},\n\\end{equation*}\nin which\n\\begin{align}\\label{eqn:recursion}\n\\begin{split}    \n    \\alpha_t &= \\frac{a_1}{c^{t-1}} + \\sum_{i=0}^{t-1} \\frac{k_{t-i}}{c^i}, \\\\\n    \\beta_t &= \\frac{b_1}{c^{t-1}} + \\sum_{i=0}^{t-1} \\frac{r}{c^i}\n    = \\frac{b_1}{c^{t-1}} + r\\frac{1 - \\frac{1}{c^t}}{1 - \\frac{1}{c}}.\n\\end{split}\n\\end{align}\nBoth $r$ and $c$ are model parameters that can easily be optimised, because\ntheir marginal likelihood~$\\Pb(k_1, \\dots, k_{t-1} \\mid r, c)$ is available in\nclosed form. The constants $a_1$ and~$b_1$ are parameters of the initial prior\non $\\lambda_1$.\n\nWe apply this model to the estimation of reproduction numbers in\nsection~\\ref{sec:application}, by making use of a simplified version of\nequation~\\eqref{eqn:R_t} in which $\\lambda_{t-1}$ is replaced with a point\nestimate~$\\lambda_{t-1}^*$. We use, for example, the median value of\n$\\Pb(\\lambda_{t-1} \\mid k_1, \\dots, k_{t-2})$ as such an estimate.\n\n\\section{The stochastic process} %==============================================\n\nLet~$\\ub{k} = k_1, \\dots, k_{t-1}$ be a sequence of observed infection counts,\nand~$\\ub{\\lambda}$ the corresponding sequence of unknown infection rates. The\nprimary assumption is that each~$k$ and~$\\lambda$ are related via a negative\nbinomial distribution:\n\\begin{equation}\\label{eqn:likelihood}\n  \\Pb(k_t \\mid \\lambda_t, \\ub{k}) = \\Pb(k_t \\mid \\lambda_t)\n  \\sim \\NB\\lr*{k_t \\Bigm\\vert r, \\frac{\\lambda_t}{r + \\lambda_t} = p_t},\n\\end{equation}\nwhere $r$ is an unknown dispersion parameter and $p_t$ is a reparameterisation\nof $\\lambda_t$ as a `success' probability. Parameterised in this way, the\nnegative binomial distribution converges to a Poisson distribution of\nrate~$\\lambda_t$ as~$r \\to \\infty$, and by adjusting $r$ we can control the\nlevel of variance inherent to the distribution (smaller values of $r$ result in\nhigher variance).\n\nInference of the rate sequence~$\\ub{\\lambda}$ is performed iteratively, by\nrepeated application of Bayes' rule:\n\\begin{equation*}\n  \\Pb(\\lambda_t \\mid k_t, \\ub{k}) \\propto \\Pb(k_t \\mid \\lambda_t)\n    \\Pb(\\lambda_t \\mid \\ub{k}).\n\\end{equation*}\nThe first term on the right-hand side---the likelihood function---is simply the\nnegative binomial distribution given above. The second term is a predictive\nprior on~$\\lambda_t$ given only the \\emph{past} infection counts~$\\ub{k}$.\nTechnically the inference will be done with respect to $\\ub{p} = p_1, \\dots,\np_{t-1}$, not $\\ub{\\lambda}$, but with the right choice of prior the translation\nbetween the two is seamless.\n\nThe conjugate prior for the negative binomial likelihood function (with known\ndispersion) is the beta distribution, so our second assumption is that the prior\ndistribution on $p_t$ is of this form. Note that the change-of-variable formula\nfor probability density functions implies that when $p_t$ follows a beta\ndistribution, $\\lambda_t/r$ is distributed according to a beta prime\ndistribution with identical parameters:\n\\begin{equation*}\n  p_t \\sim \\B(p_t \\mid \\alpha, \\beta)\n  \\Rightarrow \\frac{\\lambda_t}{r}\n    \\sim \\BP\\lr*{\\frac{\\lambda_t}{r} \\Bigm\\vert \\alpha, \\beta}.\n\\end{equation*}\nAs mentioned above, this allows us to work with $p_t$ instead of $\\lambda_t$\nwhile deriving posteriors and marginal likelihoods, but still consider\n$\\lambda_t$ when computing $R_t$.\n\nThe third and final assumption we make involves the way in which the predictive\nprior $\\Pb(p_t \\mid \\ub{k})$ is derived from the previous posterior $\\Pb(p_{t-1}\n\\mid \\ub{k})$. In the case of a Gaussian stochastic process, one would derive\nthe prior by assuming additive Gaussian noise on the previous latent variable,\nresulting in a distribution that has the same mean as the previous posterior,\nbut higher variance. Doing so involves solving an integral of the form\n\\begin{equation*}\n  \\Pb(p_t \\mid \\ub{k}) = \\int \\Pb(p_t \\mid p_{t-1})\n    \\Pb(p_{t-1} \\mid \\ub{k})\\, dp_{t-1},\n\\end{equation*}\nwhich is tractable in the Gaussian case.\n\nAlthough the situation is not quite as straightforward here, we can achieve a\nsimilar outcome by simply assuming the relationship to the previous posterior\ndirectly: specifically, if\n\\begin{equation}\\label{eqn:posterior form}\n  \\Pb(p_{t-1} \\mid \\ub{k}) \\sim \\B(p_{t-1} \\mid \\alpha_{t-1}, \\beta_{t-1}),\n\\end{equation}\nwe might assume a predictive prior of the form\n\\begin{equation}\\label{eqn:prior}\n  \\Pb(p_t \\mid \\ub{k}) \\sim \\B(p_t \\mid \\alpha_{t-1}/c, \\beta_{t-1}/c)\n  = \\B\\lr*{p_t \\mid a_t, b_t}.\n\\end{equation}\nThis is a straightforward prior that has the same mean as the predictive\nposterior on~$p_{t-1}$, but a variance that is larger \\emph{roughly} by a\nfactor~$c$---since the mean and variance of a beta distribution with parameters\n$\\alpha$ and $\\beta$ are given by\n\\begin{equation*}\n  \\Ex[X] = \\frac{\\alpha}{\\alpha + \\beta}, \\quad\n  \\Va[X] = \\frac{\\alpha\\beta}{(\\alpha + \\beta)^2 (\\alpha + \\beta + 1)},\n\\end{equation*}\nand in general $c$ will be small relative to $\\alpha + \\beta$.\n\nOne could just as easily make use of a predictive prior that introduces additive\nnoise, unlike the multiplicative noise described above. The main reason for\nchoosing multiplicative noise here is that changes in scale made to~$p_t$ (and\n$\\lambda_t$) result in additive changes to~$R_t$, so in this way one is\neffectively introducing additive noise into the overarching reproduction number\nprocess.\n\nThe remaining details of the stochastic process now follow from\nassumptions~\\eqref{eqn:likelihood} and~\\eqref{eqn:prior}. Firstly--and most\nimportantly---the posterior on~$p_t$ is given by\n\\begin{align*}\n  \\Pb(p_t \\mid k_t, \\ub{k}) &\\propto \\Pb(k_t \\mid p_t) \\Pb(p_t \\mid \\ub{k}) \\\\\n  &= \\NB(k_t \\mid r, p_t)\\, \\B(p_t \\mid a_t, b_t) \\\\\n  &\\sim p_t^{k_t} (1 - p_t)^r \\cdot p_t^{a_t-1} (1 - p_t)^{b_t-1} \\\\\n  &\\Rightarrow \\B(p_t \\mid a_t + k_t, b_t + r).\n\\end{align*}\nThat is (extending equation~\\eqref{eqn:posterior form}):\n\\begin{equation}\\label{eqn:posterior}\n  \\Pb(p_t \\mid k_t, \\ub{k}) \\sim \\B(p_t \\mid a_t + k_t, b_t + r)\n  = \\B(p_t \\mid \\alpha_t, \\beta_t).\n\\end{equation}\nCombining this with equation~\\eqref{eqn:prior} one can solve for $\\alpha_t$\nand~$\\beta_t$ recursively, leading to equation~\\eqref{eqn:recursion}. Note\nhowever that these solutions presume that the time series of data points is\ncomplete; in the presence of a missing datum $k_t$ one will need to specify\n$\\alpha_t$ and~$\\beta_t$ explicitly---for example simply by setting them to\n$a_t$ and~$b_t$ respectively.\n\nSecondly, we can derive the marginal likelihood of observation~$k_t$ given the\nprevious observations:\n\\begin{align}\\label{eqn:marginal}\n  \\Pb(k_t \\mid \\ub{k}) &= \\int \\Pb(k_t, p_t \\mid \\ub{k})\\, dp_t \\nonumber \\\\\n  &= \\int \\NB(k_t \\mid r, p_t)\\, \\B(p_t \\mid a_t, b_t)\\, dp_t \\nonumber \\\\\n  &= \\binom{k_t + r - 1}{k_t} \\frac{1}{\\Beta(a_t, b_t)}\n    \\int p_t^{a_t+k_t-1} (1 - p_t)^{b_t+r-1}\\, dp_t \\nonumber \\\\\n  &= \\begin{dcases}\n    \\frac{\\Beta(a_t, b_t + r)}{\\Beta(a_t, b_t)} &\\text{if } k_t = 0, \\\\\n    \\frac{1}{k_t\\Beta(k_t, r)}\\frac{\\Beta(a_t + k_t, b_t + r)}{\\Beta(a_t, b_t)}\n      &\\text{if } k_t > 0,\n  \\end{dcases}\n\\end{align}\nwhere~$\\Beta(x, y)$ denotes the beta function. (The final expression can also be\nrephrased in terms of $\\alpha_t$ and $\\beta_t$ using\nequation~\\eqref{eqn:posterior}.) This allows us to compute the overall marginal\nlikelihood iteratively, since\n\\begin{equation*}\n  \\Pb(\\ub{k}) = \\prod_{i=1}^{t-1} \\Pb(k_i \\mid k_1, \\dots, k_{i-1}).\n\\end{equation*}\nThe overall marginal likelihood will in turn allow us to compare the relative\nlikelihoods of values of~$r$ and~$c$, which are the model's two tunable\nparameters.\n\nEquations~\\eqref{eqn:prior} and~\\eqref{eqn:posterior} allow us to derive,\nvia~$p_t$, a posterior distribution for each~$\\lambda_t$. Ideally one would hope\nfor a distribution on~$\\lambda_t/\\lambda_{t-1}$, since this is the ratio on\nwhich~$R_t$ depends (equation~\\eqref{eqn:R_t}), however this would require one\nto either specify~$\\Pb(p_t \\mid p_{t-1})$---something we explicitly avoiding\ndoing above to keep things tractable---or treat $\\lambda_t$ and~$\\lambda_{t-1}$\nas independent for the purposes of deriving $R_t$.\n\nHere we adopt a simpler approach: replace $\\lambda_{t-1}$ in\nequation~\\eqref{eqn:R_t} with a point estimate~$\\lambda_{t-1}^*$, resulting in\nthe approximation\n\\begin{equation}\\label{eqn:R_t approximation}\n  R_t \\approx \\frac{1}{\\gamma} \\log\\lr*{\\frac{\\lambda_t}{\\lambda_{t-1}}} + 1\n    \\approx \\frac{1}{\\gamma}\n    \\log\\lr*{\\frac{\\lambda_t}{r}\\frac{r}{\\lambda_{t-1}^*}} + 1,\n\\end{equation}\nto which our inferred posterior on $\\lambda_t/r$ can directly be applied. This\nis not unlike a simplification made by the other\nauthors~\\cite{bettencourt2008,systrom2020}, who set~$\\lambda_{t-1}^* = k_{t-1}$.\nIn what follows, we have set $\\lambda_{t-1}^*$ to the median of the posterior\ndistribution~$\\Pb(\\lambda_{t-1} \\mid k_1, \\dots k_{t-1})$ (which is simply $r$\ntimes the median of the posterior on $\\lambda_{t-1}/r$).\n\nBefore moving on, we note that~\\citeauthor{bettencourt2008} also describe a\nnegative binomial process in which $r$ is not constant, but rather $r_t =\nk_{t-1}$. We have briefly tested this approach, and in practice it performs\nsimilarly to the one we have described above; the main difference being that the\nprecision of the likelihood function (and thus posterior) varies with the\nobserved counts~$\\ub{k}$. The approach outlined in this section can still be\napplied, and the resulting analytic solution differs only slightly.\n\n\\subsection*{An application to South African data}\\label{sec:application} %=====\n\nIn this section we apply the steps described above to data stemming from the\nCOVID-19 epidemic in South Africa. The data set used here is obtained from South\nAfrica's National Institute for Communicable Diseases, via the University of\nPretoria~\\cite{dsfsi2020}. The data take the form of daily cumulative infection\ncounts per province, from which we derive new infection counts per day.\n\n\\begin{figure}[htb]\n  \\centering\n  \\includeinkscape{img/counts}\n  \\caption{Daily new infection counts for the COVID-19 epidemic in South Africa,\n    smoothed using a Gaussian window with a standard deviation of~$\\sigma =\n    3.5$. Shaded areas indicate different levels of the nationwide lockdown,\n    with the first, grey area depicting the period between the announcement of\n    the lockdown and its initiation.}\n  \\label{fig:counts}\n\\end{figure}\n\nBefore inferring daily infection rates, we first need to decide whether or not\nthe raw counts should be smoothed, and if so, to what extent (see\nfigure~\\ref{fig:counts}). The obvious argument against doing so is that the\nvariance of $R_t$ depends indirectly on the variance of the $k_t$, so smoothed\ninfection counts may result in artificially precise posteriors.\n\nOn the other hand, one might argue that the underlying assumption of the model\nis that $k_t$ represents the \\emph{true} number of infections on a given day, of\nwhich smoothed counts are likely a more appropriate indication. A second, more\ntechnical argument for reducing the variance of the reported infection counts is\nthe fact that the equation $\\lambda_t \\approx \\lambda_{t-1}\\exp(\\gamma(R_t -\n1))$ contains an implicit assumption: that $R_t \\ge 0$, and thus\n$\\lambda_t/\\lambda_{t-1} \\ge \\exp(-\\gamma)$.\n\n\\begin{figure}[htb]\n  \\centering\n  \\includeinkscape{img/ratio}\n  \\caption{Ratios of consecutive infection counts~$k_t/k_{t-1}$ for various\n    levels of Gaussian smoothing. The red line indicates the bound implied by\n    equation~\\eqref{eqn:R_t}.}\n  \\label{fig:ratio}\n\\end{figure}\n\nIn figure~\\ref{fig:ratio} we plot the ratio~$k_t/k_{t-1}$ for various levels of\nGaussian averaging---roughly corresponding to smoothing windows of 0.5, 1, and~2\nweeks (if one uses four standard deviations as a guide). One sees that in this\ncase, windows with scales greater than $\\sigma = 7/3$ appear both to respect the\nimplicit bound mentioned above, as well as alleviate much of the periodicity\nvisible in the raw count sequence.\n\nFor the remainder of this example we will counts that have been averaged using a\nGaussian window with standard deviation~$\\sigma = 3.5$. This value will not\nnecessarily be suitable for data sets from other regions or sources, however.\n\nThe rest of the application is straightforward: we apply\nequation~\\eqref{eqn:marginal} to select values for $r$ and~$c$ that maximise the\nmarginal likelihood (for the countrywide South African data this yields $r =\n1592$ and~$c \\approx 3.56$), and then use equation~\\ref{eqn:posterior} to\ncompute the parameters of the posteriors on $\\lambda_1, \\lambda_2, \\dots$. These\nposteriors, shown in figure~\\ref{fig:posterior}, track the smoothed $k_t$\nrelatively closely, as one might expect.\n\nFinally, equation~\\eqref{eqn:R_t approximation} allows us to plot the estimated\nevolution of $R_t$ over time, simply by mapping percentiles of $\\lambda_t/r$ to\nthose of~$R-t$. This plot is shown in figure~\\ref{fig:countrywide} for the\nentire country, and figure~\\ref{fig:provincial} on a provincial level.\n\n\\begin{figure}[htbp]\n  \\centering\n  \\includeinkscape{img/posterior}\n  \\caption{Daily posterior infection rates~$\\lambda_t$, plotted as a median and\n    5--95th percentile interval.}\n  \\label{fig:posterior}\n\\end{figure}\n\n\\begin{figure}[htbp]\n  \\centering\n  \\includeinkscape{img/countrywide}\n  \\caption{Estimated reproduction numbers~$R_t$ for the COVID-19 epidemic in\n    South Africa, plotted as a median and 5--95th percentile interval.}\n  \\label{fig:countrywide}\n\\end{figure}\n\n\\begin{figure}[htbp]\n  \\centering\n  \\includeinkscape{img/provincial}\n  \\caption{Reproduction numbers for the COVID-19 epidemic in South Africa,\n    estimated at a provincial level.}\n  \\label{fig:provincial}\n\\end{figure}\n\nThe only comment we will make on these figures is that the effect of the hard\nlockdown (implemented on 28 March) on the estimated reproduction numbers is\nclearly visible, as is---to a lesser extent---the slow relaxation of lockdown\nrestrictions and gradual reopening of economic activity that follows.\n\n% Bibliography %================================================================\n\n\\printbibliography\n\n\\end{document}", "meta": {"hexsha": "638e11f72d07f6180e6ef0e101d79ece9d7c0454", "size": 19928, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/cvza.tex", "max_stars_repo_name": "kevdur/covid", "max_stars_repo_head_hexsha": "5893b911afb974b9b00dc6af871a7c7129fd7952", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/cvza.tex", "max_issues_repo_name": "kevdur/covid", "max_issues_repo_head_hexsha": "5893b911afb974b9b00dc6af871a7c7129fd7952", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-06-11T10:04:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-21T21:39:26.000Z", "max_forks_repo_path": "doc/cvza.tex", "max_forks_repo_name": "kevdur/covid", "max_forks_repo_head_hexsha": "5893b911afb974b9b00dc6af871a7c7129fd7952", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.3267326733, "max_line_length": 80, "alphanum_fraction": 0.7147731835, "num_tokens": 5704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.629774621301746, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.34188151857858695}}
{"text": "\\documentclass[11pt, a4paper]{article}\n\n\\usepackage{tikz}\n\\usepackage{amsmath}\n\\usepackage{amsfonts}\n\\usepackage{mathtools}\n\\usepackage{graphicx}\n\\usepackage{multicol}\n\\usepackage{appendix}\n\\usepackage{pgfplots}\n\\usepackage{algorithm}\n\\usepackage{algpseudocode}\n\\usepackage[utf8]{inputenc}\n\\usepackage[english]{babel}\n\n\\pgfplotsset{compat=1.16}\n\n\\date{}\n\\title{Exoplanets detection using \\\\ Auto-Tuned Random Forest}\n\n\\author{Lorenzo Loconte \\\\ \\small Knowledge Engineering Project \\\\ \\small University of Bari Aldo Moro, Department of Informatics}\n\n\\begin{document}\n\n\\maketitle\n\\begin{abstract}\n  The \\texttt{NASA Kepler} project consists of discovering exoplanets (i.e. planets outside our solar system).\n  The data generated by the \\texttt{Kepler Space Telescope} is analyzed by humans and algorithms to discover new exoplanets.\n  The main problem is that a lot of exoplanets are revealed false positives.\n  This work consists of identifying exoplanets using random forest, a \\textit{Supervised Machine Learning} model.\n  Furthermore, the fitted model is analyzed in order to determine which features are relevant.\n  The hyperparameters are automatically optimized with techniques that come from the \\texttt{AutoML} research.\n  In fact, the hyperparameters of the model are optimized and cross-validated with \\texttt{Hyperband}, a simple yet effective and scalable method for hyperparameters optimization.\n\\end{abstract}\n\n\\clearpage\n\n\\section{Introduction}\n  \\paragraph{Kepler Object of Interest}\n    Exoplanets are particular planets that are situated outside our solar system which orbit around one star (sometimes even multiple stars).\n    The \\texttt{NASA Kepler} project aims to discover these objects by looking at some stars and observing their luminosity during time.\n    Basically suppose we are observing a star.\n    If a rapid decrease and consequently increase of its luminosity occurs it's most likely that an object passed the way between us and the star.\n    Analyzing the variation of luminosity for a certain amount of time we can extrapolate features like the radius and the orbit eccentricity of the object.\n    Sometimes these object are actually exoplanets but it's common they can be something else like asteroids or even another star.\n    Sometimes they are just false positives due to measurements noise.\n\n    The goal of this work is to build a model (using \\textit{Supervised Machine Learning}) that is capable to determinate if a hypothetical exoplanet can be confirmed or is just false positive.\n    The dataset used is the cumulative list of \\texttt{Kepler Object of Interest} (\\texttt{KOI}) tables that come from the \\texttt{NASA Kepler} project of discovering exoplanets.\n    The complete dataset can be found at \\texttt{https://exoplanetarchive.ipac.caltech.edu}.\n    The dataset is composed by a list of hypothetical exoplanets.\n    Each sample have a label indicating if the corresponding exoplanet is candidate, false positive or confirmed.\n    The provided dataset consists of a lot of heterogeneous features.\n    For the classification task the selected features can be found in Appendix \\ref{appendix:features}.\n    \n    The candidate exoplanets (i.e. the exoplanets which existence is uncertain) are discarded in order to reduce noise and improve the learning process.\n    For simplicity all the samples having null values are discarded from the dataset.\n    Furthermore, all the selected features are numeric and the preprocessing method applied to the dataset is the standard normalization.\n    The resulting dataset contains \\texttt{5860} samples, of which only \\textasciitilde \\texttt{38\\%} are confirmed and the remaining are false positives.\n\n  \\paragraph{Random Forests}\n    As described before, the classification task consists to determinate if some numerical characteristics can be attributed to an existing exoplanet.\n    The model used for the classification task is a random forest, a bagging ensemble of decision trees.\n    The prediction of the random forest is computed as the mode of the predictions made by the decision trees.\n    Note that each tree of the forest is trained on a subset of the features.\n    Random forests correct the habit of decision trees of overfitting on their training set.\n    In fact, decision trees tend to overfit their training sets because they have a low bias but an high variance.\n\n    In \\textit{Supervised Machine Learning}, bias consists of erroneous assumptions about the data and variance is a measure of sensitivity to the noise in the training data.\n    So, random forests generally obtain better performance.\n\n    The law that regulates the bias and variance is called \\texttt{Bias-Variance tradeoff} \\cite{biasvariance}.\n    This law states that models having low bias have an high variance and vice versa.\n    In \\textit{Machine Learning} bias and variance corresponds to the models behaviors that we want to regulate in order to minimize the error.\n    An high bias causes \\textit{underfitting} while an high variance causes \\textit{overfitting}.\n      \\[\\mathrm{Error}=\\mathrm{Bias}^{2}+\\mathrm{Variance}+\\mathrm{Irreducible\\:Error}\\]\n\n  \\paragraph{Hyperparameters}\n    Often it's difficult (or nearly impossible) to select the correct hyperparameters that guarantee good performance on some specific datasets.\n    \\texttt{AutoML} is a branch of \\textit{Machine Learning} that try to simplify the process of model selection and hyperparameters optimization.\n    This work focuses on solving the hyperparameters search problem for random forests.\n    The algorithm used is \\texttt{Hyperband} that, as it'll be shown in the next section, represents an evolution of random search designed especially for hyperparameters optimization.\n\n    For the hyperparameters optimization algorithm chosen, the number of trees in the random forest is not considered an hyperparameter.\n    Furthermore, the following hyperparameters are optimized:\n    \\begin{itemize}\n      \\item The split criterion (Gini Impurity or Information Gain, see Appendix \\ref{appendix:splitcriterions} for details)\n      \\item The fraction of features to use for each tree\n      \\item The fraction of samples used to train each tree\n      \\item The maximum depth of each tree\n      \\item The minimum number of samples required to split an internal node\n      \\item The minimum number of samples to be at a leaf node\n    \\end{itemize}\n\n\\clearpage\n\n\\section{Hyperparameters Optimization}\n  In this section it will be shown a formalization of the hyperparameters optimization task as a search problem.\n  In this work we refer to hyperparameters as the ones that cannot be trained (e.g. the ones described in the previous section).\n  After that we briefly introduce the hyperparameters optimizer used in this work, \\texttt{Hyperband}, as described in \\cite{hyperband}.\n\n  Given a training set $T$, a model $L$ and its hyperparameters search space $\\Omega$, the hyperparameters optimization task consists to find an hyperparameters configuration $\\omega \\in \\Omega$ such that the resulting model $L\\langle\\omega\\rangle$ maximizes a certain score $S$ using cross-validation on $T$.\n  Note that most search algorithms don't converge to the global maximum.\n  So, the goodness of the hyperparameters found is dependent of the amount of resources we have.\n\n  There are a lot of different techniques for hyperparameters optimization, some of them are the following:\n  \\begin{itemize}\n    \\item Random Search\n    \\item Grid Search\n    \\item Hyperband\n    \\item Bayesian Optimization\n    \\item Hybrid Approaches (like \\texttt{BOHB} \\cite{bohb})\n  \\end{itemize}\n\n  Of the techniques cited above only \\texttt{Bayesian Optimization} guarantees the convergence to the global maximum in the hyperparameters search space (see \\cite{bayesianoptimization} for details).\n  The simplest algorithm is \\texttt{Random Search} and it works well if the hyperparameters search space is not too big.\n  \\texttt{Random Search} is expensive because each evaluation of the score function is done on models completely built from scratch.\n  So, each evaluation of the score function on some randomly selected hyperparameters will use the same amount of computational resources, even if some hyperparameters of the search space obtain a very low score.\n  The idea behind \\texttt{Hyperband} is that it's better to save up resources on these hyperparameters configurations that doesn't obtain a sufficiently good score by gradually building more complex models over time.\n  \n  Note that we refer to budget as the computational cost of cross-validating a certain model.\n  For example, for neural networks the budget can be the number of training epochs, while for random forests it can be the number of trees.\n\n  Algorithm \\ref{algorithm:hyperband} shows an implementation of \\texttt{Hyperband} as described now.\n  Given a budget $R$, \\texttt{Hyperband} consists of random sampling some points (for example using the uniform distribution) in the hyperparameters space and cross-validating them using only a fraction of the budget $R$.\n\n  After that we pick a fraction $1/\\eta$ of the best models.\n  In this way we discard the models that didn't obtain a sufficiently good score saving up computational resources.\n\n  After that, we strengthen the previous models using a larger portion of $R$ and iterate in this way until we use the complete budget $R$.\n  The procedure of consequently eliminating hyperparameters samples that don't obtain a good score is called \\texttt{Successive Halving}.\n  The fraction of the budget to use for each iteration grows geometrically in respect of $\\eta$.\n  Furthermore, we execute the discussed algorithm multiple times using less and less initial random points and using an higher starting budget.\n  So, initially \\textit{exploration} is preferred and \\textit{exploitation} is performed later.\n\n  Even if \\texttt{Hyperband} is a simple algorithm, it is well scalable on multiple CPUs because we assume that every point in the hyperparameters space is independent from the others.\n\n  In our case the model $L$ is a random forest.\n  As said before, the budget $R$ is the maximum number of trees that the final random forest will have.\n  The choice of the score $S$ is dependent from the task.\n  For simplicity the $F_{1}$ score is used (i.e. we want to maximize both \\textit{Precision} and \\textit{Recall}).\n  In this work the hyperparameters search space can be defined formally as:\n  \\[\\Omega = \\overbrace{\\{gini, entropy\\}}^{\\text{Split criterion}} \\quad\\times \\overbrace{(0, 1]}^{\\text{Features fraction}} \\times \\overbrace{(0, 1]}^{\\text{Samples fraction}} \\times\\]\n  \\[\\times \\overbrace{\\mathbb{N}^{*}}^{\\text{Max depth}} \\times \\overbrace{\\mathbb{N}^{*}}^{\\text{Min samples to split}} \\times \\overbrace{\\mathbb{N}^{*}}^{\\text{Min samples at leaf}}\\]\n  For obvious reasons and for the hyperparameters optimization algorithm chosen, only a subset of this space can be explored.\n\n  \\begin{algorithm}\n    \\caption{Hyperband algorithm for hyperparameters optimization}\n    \\label{algorithm:hyperband}\n    \\begin{algorithmic}[1]\n      \\Procedure{Hyperband}{$T,L,S,\\Omega,R,\\eta$}\n        \\State $C \\gets \\emptyset$\n        \\State $s_{max} \\gets \\lfloor \\log_{\\eta}{R} \\rfloor, \\quad B \\gets (s_{max} + 1)R$\n        \\For{$s \\in \\{s_{max},s_{max}-1,...,0\\}$}\n          \\State $n \\gets \\lceil \\frac{B}{R}\\frac{\\eta^{s}}{(s+1)} \\rceil, \\quad r \\gets R\\eta^{-s}$\n          \\State $H \\gets getRandomHyperparameters(n,\\Omega)$\n          \\For{$i \\in \\{0,...,s\\}$}\n            \\State $n_{i} \\gets \\lfloor n\\eta^{-i} \\rfloor, \\quad r_{i} \\gets r\\eta^{i}$\n            \\State $H \\gets top_{\\lfloor n_{i}/\\eta \\rfloor} \\arg sort_{\\omega} \\{S(L\\langle\\omega \\cup \\{r_{i}\\}\\rangle, T) \\mid \\omega \\in H\\}$\n          \\EndFor\n          \\State $C \\gets C \\cup H$\n        \\EndFor\n        \\State \\textbf{return} $\\arg max_{\\omega} \\{S(L\\langle\\omega \\cup \\{R\\}\\rangle, T) \\mid \\omega \\in C\\}$\n      \\EndProcedure\n    \\end{algorithmic}\n  \\end{algorithm}\n\n\\clearpage\n\n\\section{Conclusion}\n  In this section we analyze the results of the model chosen comparing it to other models.\n  As you can see from Table \\ref{table:benchmark} the auto-tuned random forest used in this work obtained a way better \\textit{Recall}.\n\n  Furthermore, as you can see from Figure \\ref{figure:confusion} the false positives count (the number of examples, which are predicted as exoplanets, but that are not) and the false negatives count (the number of actual exoplanets not being discovered), are pretty low.\n\n  Models like neural networks and support vector machines are said \\textit{black-box} models.\n  It means that predictions cannot be explained and the features importance cannot be evaluated easily.\n  At contrary, random forests are said \\textit{white-box} models.\n  So, predictions can be explained deeply and it's possible to evaluate the importance of each feature used.\n  In \\textit{Artificial Intelligence} the explainability of a model is important because it guarantees transparency.\n  Furthermore, in \\textit{Machine Learning}, explainable models can reveal hidden knowledge about the data that isn't known at prior.\n  In the end we present Figure \\ref{figure:importances} that shows the importance of the five most important features.\n\n  \\begin{table}\n    \\centering\n    \\begin{tabular}{|c c c c|}\n      \\hline\n      Model & Precision & Recall & $F_{1} \\downarrow$  \\\\\n      \\hline\\hline\n      Random Forest & 0.940 & 0.916 & 0.927 \\\\\n      \\hline\n      \\textbf{Random Forest w/HB} & \\textbf{0.934} & \\textbf{0.935} & \\textbf{0.935} \\\\\n      \\hline\n    \\end{tabular}\n    \\caption{\\textit{Precision}, \\textit{Recall} and $F_{1}$ metrics of random forests with and without hyperparameters optimization (using the default ones in \\texttt{scikit-learn}). For \\texttt{Hyperband} $R=216$ and $\\eta=3$ are used.}\n    \\label{table:benchmark}\n  \\end{table}\n\n  \\begin{figure}\n    \\centering\n    \\begin{tikzpicture}[scale=1.85]\n      \\draw[thick] (0, 0) -- (2, 0);\n      \\draw[thick] (0, 0) -- (0, 2);\n      \\draw[thick] (2, 2) -- (2, 0);\n      \\draw[thick] (2, 2) -- (0, 2);\n      \\draw[thick] (0, 1) -- (2, 1);\n      \\draw[thick] (1, 0) -- (1, 2);\n      \\node[rotate=0] (h1) at (1, 2.5) {\\textbf{Actual}};\n        \\node[rotate=0] (h11) at (0.5, 2.25) {Positive};\n        \\node[rotate=0] (h12) at (1.5, 2.25) {Negative};\n      \\node[rotate=90] (h2) at (-0.5, 1) {\\textbf{Predicted}};\n        \\node[rotate=90] (h21) at (-0.25, 1.5) {Positive};\n        \\node[rotate=90] (h22) at (-0.25, 0.5) {Negative};\n      \\coordinate[label={\\textbf{412}}] (TP) at (0.5, 1.33);\n      \\coordinate[label={ 28}] (FN) at (0.5, 0.33);\n      \\coordinate[label={ 29}] (FP) at (1.5, 1.33);\n      \\coordinate[label={\\textbf{703}}] (TN) at (1.5, 0.33);\n    \\end{tikzpicture}\n    \\caption{Confusion matrix over the test set.}\n    \\label{figure:confusion}\n  \\end{figure}\n\n  In random forests the features importance are calculated by averaging the features importance in each decision tree.\n  For a decision tree the features importance are calculated during the fit and are computed as the normalized total reduction of the criterion brought by each feature. \n\n  The most important feature is PRF $\\Delta\\theta_{SQ}$ (\\texttt{Pixel Response Function}), that basically is the angular offset on the plane of the sky between the centroid of the star and the calculated centroid of the star during the passage of the object of interest.\n  It's very important because a lot of false positives are due to the transit of another star in binary systems.\n  So, if this value is big it's most likely that the object of interest is not an exoplanet.\n  For some reason, the planetary radius represents another discriminant feature to determinate if an hypothetical exoplanet is real or a false positive.\n  It is possible that objects that have a very small radius can be attributed to measurements noise.\n\n  In conclusion, we can say that most of the false positive occurrences are attributed to binary star systems and measurements noise.\n\n  \\begin{figure}\n    \\centering\n    \\begin{tikzpicture}\n      \\begin{axis}[\n        ybar,\n        ylabel=Importance,\n        xlabel=Feature \\#,\n        symbolic x coords={21, 5, 3, 6, 1},\n        bar width=16pt,\n        ymin=0.0, ymax=0.35,\n        ytick={0.0, 0.05, 0.10, 0.15, 0.20, 0.25, 0.30, 0.35},\n        yticklabel style={/pgf/number format/fixed, /pgf/number format/fixed zerofill}\n      ]\n        \\addplot[style={fill=white}] coordinates {\n          (21, 0.296)\n          (5, 0.24)\n          (3, 0.069)\n          (6, 0.052)\n          (1, 0.050)\n        };\n      \\end{axis}\n    \\end{tikzpicture}\n    \\caption{Five most important features importance.}\n    \\label{figure:importances}\n  \\end{figure}\n\n\\clearpage\n\\appendix\n\\appendixpage\n\n\\section{Exoplanet Selected Features}\n  The documentation of the following exoplanet selected features can be found at \\texttt{https://exoplanetarchive.ipac.caltech.edu}.\n  However most of them are auto-explicative.\n  The features used in this work are regarding the observed star, the processed features of the object of interest and various spectrometric metrics.\n  \\begin{multicols}{2}\n    \\label{appendix:features}\n    \\begin{enumerate}\n      \\item Orbital Period [$days$]\n      \\item Transit Duration [$hrs$]\n      \\item Transit Depth [$ppm$]\n      \\item Fitted Stellar Density [$g/cm^{3}$]\n      \\item Planetary Radius [$Earth\\:radii$]\n      \\item Inclination [$deg$]\n      \\item Equilibrium Temperature [$K$]\n      \\item Insolation Flux [$Earth\\:flux$]\n      \\item Stellar Effective Temperature [$K$]\n      \\item Stellar Surface Gravity [$\\log_{10}(cm/s^{2})$]\n      \\item Stellar Metallicity [$dex$]\n      \\item Stellar Radius [$Solar\\:radii$]\n      \\item Stellar Mass [$Solar\\:mass$]\n      \\item RA [$decimal\\:degrees$]\n      \\item Dec [$decimal\\:degrees$]\n      \\item Kepler-band [$mag$]\n      \\item FW $\\Delta\\alpha$ [$sec$]\n      \\item FW $\\Delta\\delta$ [$arcsec$]\n      \\item PRF $\\Delta\\alpha_{SQ}$ [$arcsec$]\n      \\item PRF $\\Delta\\delta_{SQ}$ [$arcsec$]\n      \\item PRF $\\Delta\\theta_{SQ}$ [$arcsec$]\n    \\end{enumerate}\n  \\end{multicols}\n\n\\section{Decision tree split criterions}\n  \\label{appendix:splitcriterions}\n  \\subsection{Gini impurity}\n    Citing \\texttt{wikipedia.org}, Gini impurity is a measure of how often a randomly chosen element from the set would be incorrectly labeled if it was randomly labeled according to the distribution of labels in the subset.\n    To compute Gini impurity for a set of items with $J$ classes, suppose $i\\in\\{1,2,...,J\\}$, and let $p_{i}$ be the faction of items labeled with class $i$ in the set.\n    \\[{I} _{G}(p)=\\sum _{i=1}^{J}p_{i}\\sum _{k\\neq i}p_{k}=\\sum _{i=1}^{J}p_{i}(1-p_{i})=1-\\sum _{i=1}^{J}{p_{i}}^{2}\\]\n  \\subsection{Information gain}\n    Information gain is based on the concept of entropy and information content from information theory.\n    For each node of the tree, the information value represents the expected amount of information that would be needed to specify whether a new instance should be classified yes or no, given the example reached that node.\n    Given $T$ the set of training examples and $X$ the selected feature.\n    \\[IG(T, X)=\\mathrm{H}(T)-\\mathrm{H}(T|X)=\\mathrm{H}(T)-\\sum_{x}{\\Pr(X=x)\\mathrm{H}(T|X=x)}\\]\n\n\\bibliography{biblio.bib}\n\\bibliographystyle{unsrt}\n\n\\end{document}\n", "meta": {"hexsha": "398856957d5f78883302ee63a274964614c47357", "size": 19346, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/doc.tex", "max_stars_repo_name": "loreloc/exoplanet-detection", "max_stars_repo_head_hexsha": "d28e51581443e05b408f9bd6e2d1055eb75d9a0d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-01-02T17:45:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T16:48:07.000Z", "max_issues_repo_path": "doc/doc.tex", "max_issues_repo_name": "loreloc/exoplanet-detection", "max_issues_repo_head_hexsha": "d28e51581443e05b408f9bd6e2d1055eb75d9a0d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/doc.tex", "max_forks_repo_name": "loreloc/exoplanet-detection", "max_forks_repo_head_hexsha": "d28e51581443e05b408f9bd6e2d1055eb75d9a0d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 62.2057877814, "max_line_length": 309, "alphanum_fraction": 0.7289879045, "num_tokens": 4995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3418815185785869}}
{"text": "\\subsection{Carrier trapping and Shockley-Read-Hall recombination}\n\n\n\\begin{figure}\nTo describe charge becoming trapping into trap states and recombination associated with those states the model uses Shockley-Read-Hall (SRH) theory. A 0D depiction of this SRH recombination and trapping is shown in figure \\ref{fig:dos_structure}, the free electron and hole carrier distributions are labeled as n free and p free respectively. The trapped carrier populations are denoted with n trap and p trap , they are depicted with filled red and blue boxes. SRH theory describes the rates at which electrons and holes become captured and escape from the carrier traps. If one considers a single electron trap, the change in population of this trap can be described by four carrier capture and escape rates as depicted in figure \\ref{fig:dos_structure}. The rate rec describes the rate at which electrons become captured into the electron trap, $r_{ee}$ is the rate which electrons can escape from the trap back to the free electron population, $r_{hc}$ is the rate at which free holes get trapped and $r_{he}$ is the rate at which holes escape back to the free hole population. Recombination is described by holes becoming captured into electron space slice through our 1D traps. Analogous processes are also defined for the hole traps.\n\n\\centering\n\\includegraphics[width=40mm]{./images/dos_structure.jpg}\n\\caption{Trap filling in both energy and position space as the solar cell is taken from a negative bias\nCarrier trapping, de-trapping, and recombination}\n\\label{fig:dos_structure}\n\\end{figure}\n\n\n\\begin{table}\n\\begin{center}\n  \\begin{tabular}{lll}\n  \\hline\n  Mechanism & Symbol & Description  \\\\\n  \\hline\nElectron capture rate & $r_{ec}$ & $n v_{th} \\sigma_{n} N_{t}(1-f)$ \\\\\nElectron escape rate & $r_{ee}$ & $e_{n} N_{t} f$ \\\\\nHole capture rate & $r_{hc}$ & $p v_{th} \\sigma_{p} N_{t} f$ \\\\\nHole escape rate & $r_{he}$ & $e_{p} N_{t} (1-f)$\\\\\n  \\hline\n\\end{tabular}\n\\end{center}\n\\caption{Shockley-Read-Hall trap capture and emission rates, where $f$ is the fermi-Dirac occupation function and $N_{t}$ is the trap density of a single carrier trap.}\n\\label{tab:rates}\n\\end{table}\n\n\nFor each trap level the carrier balance \\ref{eq:srhrate} is solved, giving each trap level an independent quasi-Fermi level. Each point in position space can be allocated between 10 and 160 independent trap states.  The rates of each process $r_{ec}$, $r_{ee}$, $r_{hc}$, and $r_{he}$ are give in table \\ref{tab:rates}.\n\n\\begin{equation}\n\\label{eq:srhrate}\n\\frac{\\delta n_t}{\\partial t}=r_{ec}-r_{ee}-r_{hc}+r_{he}\n\\end{equation}\n\nThe escape probabilities are given by:\n\n\\begin{equation}\n\\label{eq:taile}\ne_n=v_{th}\\sigma_{n} N_{c} exp \\left ( \\frac{E_t-E_c}{kT}\\right )\n\\end{equation}\n\nand\n\n\\begin{equation}\n\\label{eq:taile}\ne_p=v_{th}\\sigma_{p} N_{v} exp \\left ( \\frac{E_v-E_t}{kT}\\right )\n\\end{equation}\n\n where $\\sigma_{n,p}$ are the trap cross sections, $v_{th}$ is the thermal emission velocity of the carriers, and $N_{c,v}$ are the effective density of states for free electrons or holes.  The distribution of trapped states (DoS) is defined between the mobility edges as\n\n\\begin{equation}\n\\label{eq:taile}\n\\rho^{e/h}(E)=N^{e/h}exp(E/E_{u}^{e/h})\n\\end{equation}\n\nwhere , $N_{e/h}$ is the density of trap states at the LUMO or HOMO band edge\nin states/eV and where $E_{U}^{e/h}$ is slope energy of the density of states. \n\nThe value of $N_{t}$ for any given trap level is calculated by averaging the DoS function over the energy ($\\Delta E$ ) which a trap occupies:\n\n\\begin{equation}\n\\label{eq:taile}\nN_{t}(E)=\\frac{\\int^{E+\\Delta E/2}_{E-\\Delta E/2} \\rho^{e}{E} dE}{\\Delta E}\n\\end{equation}\n\nThe occupation function is given by the equation,\n\\begin{equation}\nf(E_{t},F_{t})=\\frac{1}{e^{\\frac{E_{t}-F_{t}}{kT}}+1}\n\\end{equation}\nWhere, $E_{t}$ is the trap level, and $F_{t}$ is the Fermi-Level of the trap.\nThe carrier escape rates for electrons and holes are given by\n\n\n\n\\subsubsection{Free-to-free carrier recombination}\nA free-carrier-to-free-carrier recombination pathway is also included in the model. However, most organic solar cells have a great deal of trap states and an ideality factor greater than 1.0 suggesting that free to free recombination is not the dominant mechanism.  It is also worth noting that since I included this recombination pathway in the model I have not found it useful to reproduce experimental results.\n\nFree-to-free recombination is described using equation \\ref{equ:freetofree}\n\n\\begin{equation}\nR_{free}=k_{r}(n_{f}p_{f}-n_{0}p_{0})\n\\label{equ:freetofree}\n\\end{equation}\n\n", "meta": {"hexsha": "92435275ef0fa685d5af5426cff14c73e5c5363d", "size": 4591, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "gpvdm_data/docs/man/electrical_srh.tex", "max_stars_repo_name": "roderickmackenzie/gpvdm", "max_stars_repo_head_hexsha": "914fd2ee93e7202339853acaec1d61d59b789987", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2016-09-13T08:58:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T07:04:52.000Z", "max_issues_repo_path": "gpvdm_data/docs/man/electrical_srh.tex", "max_issues_repo_name": "roderickmackenzie/gpvdm", "max_issues_repo_head_hexsha": "914fd2ee93e7202339853acaec1d61d59b789987", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2017-11-11T12:33:02.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-08T00:48:08.000Z", "max_forks_repo_path": "gpvdm_data/docs/man/electrical_srh.tex", "max_forks_repo_name": "roderickmackenzie/gpvdm", "max_forks_repo_head_hexsha": "914fd2ee93e7202339853acaec1d61d59b789987", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-01-03T06:17:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-01T15:59:00.000Z", "avg_line_length": 51.0111111111, "max_line_length": 1240, "alphanum_fraction": 0.7453713788, "num_tokens": 1316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.34188151103423536}}
{"text": "\\documentclass{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage{amsmath, amssymb}\n% \\usepackage{proof}\n\\usepackage{syntax}\n\\usepackage{listings}\n\\usepackage{xcolor}\n\\usepackage{hyperref}\n\n\n\\title{Pixy Semantics}\n\\author{Reed Mullanix, Finn Hackett}\n\\date{February 2018}\n\n\\begin{document}\n\n\\maketitle\n\n\\section{Introduction}\nThe semantics of Pixy can be divided up into 3 portions: The term language, how that term language is evaluated, and the type system.\n\\section{Term Language}\nThe term language of Pixy is (roughly) as follows:\n\\begin{grammar}\n<expr>  ::= <literal>\n    \\alt <var>\n    \\alt \"nil\"\n    \\alt \"?\" <expr>\n    \\alt \"if\" <expr> \"then\" <expr> \"else\" <expr>\n    \\alt <expr> \"fby\" <expr>\n    \\alt <expr> \"where\" (<var> \"=\" <expr>)*\n    \\alt \"fun\" <var> \"=>\" <expr>\n    \\alt <expr> <expr>\n\\end{grammar}\n\n{\\color{red} NOTE:} This is incomplete! We need to standardize on the term language.\n\n\\section{Evaluation}\nThe evaluation rules for Pixy are quite different from other languages.\nTo begin with, each expression can be seen as a taking a State and producing a value and a new State. This state is then fed back into the expression to produce a new State and value, and so on. However, some expressions pose some problems. For example, when evaluating \\lstinline{if ... then ... else} expression, we should only really evaluate one of the branches, but doing so may skip important stateful evaluation inside of the untaken branch. To reconcile this, we present a model of evaluation which we call \"Choked Evaluation\". Whenever we are presented with a branching construct, we still evaluate the branches, with the caveat that all variables \\textit{and} literals evaluate to \\lstinline{nil} on the branch that is not taken.\n\nAnother point we need to make is that evaluation is only valid on \\textbf{closed} expressions, or expressions that have no free variables.\n\n{\\color{red} NOTE:} Insert full evaluation semantics here.\n\n{\\color{red} NOTE:} We need to spec out when exactly evaluation terminates for a given step.\n\n\\section{Type Theory}\nTypically, type systems follow this general form:\n\\begin{itemize}\n    \\item The user declares the construction and elimination rules for a type.\n    \\item The user then uses theses construction rules to create programs.\n\\end{itemize}\nWe prefer to take a different approach, which has been strongly influenced \nby systems such as NuPRL. Generally speaking, our type system works as follows:\n\\begin{itemize}\n    \\item The user writes a program.\n    \\item The user then creates a proof that the program inhabits some type.\n\\end{itemize}\n\nThat of course raises the question: When does a program inhabit a type? To answer that, we must first answer what exactly a type is in Pixy. We define a type as having 2 components:\n\\begin{enumerate}\n    \\item A collection of canonical inhabitants.\n    \\item An equivalence relation over those inhabitants.\n\\end{enumerate}\n\nFor example, the canonical inhabitants of the type \\lstinline{Nat} are $0,1,2,3...$ and the equivalence relationship is just the equivalence relationship of natural numbers. When we say that $a \\in A$, what we are really saying is that $a = a$ under the equality relationship imposed by $A$. This point may seem slightly pedantic, but it has large implications. This can be extended to separate elements, so we could also propose that $a = b \\in A$, or that 2 terms $a$ and $b$ are equivalent under the equality relation of $A$. Note that the canonical inhabitants aren't the only members of a type. Any term that evaluates to a canonical inhabitant is also a member of the type. On top of that, if we have 2 terms $t, t'$ and they evaluate to $a, a'$ respectively, and $a = a' \\in A$, then $t, t' \\in A$ as well!\n\nContinuing in the spirit of NuPRL, what exactly is $a \\in A$? Well, if we use the logic of Propositions-as-Types, $a \\in A$ should really just be a type! We shall denote this type as $Eq\\ a\\ b\\ A$. We shall also include all of the standard portions of Martin-Löf Type Theory.\n\nTime is represented by using a the type $Next : \\star \\rightarrow \\star$. This type corresponds with the $\\circ$ operator in Linear Temporal logic. With this primitive type, we can begin to define the operators of Linear Temporal Logic using inductive and coinductive types.\n\\begin{align*}\n    &\\circ A \\text{ corresponds to } Next(A) \\\\\n    &\\square A \\text{ corresponds to } \\nu \\sigma . A \\times Next(\\sigma) \\\\\n    &\\lozenge A \\text{ corresponds to } \\mu \\sigma . A + Next(\\sigma) \\\\\n    &A \\triangleright B \\text{ corresponds to } \\mu \\sigma . A \\times Next(B + \\sigma) \\\\ \n\\end{align*}\n\nThere is an alternitave encoding by using temporally-indexed types, which makes quantification over time easier. This was not chosen, as the inductive/coinductive defintions make inductive/coinductive reasoning easier, which makes the kind of proofs we wish to do easier (For example, proving that 2 streams are in sync).\n\n% {\\color{red} NOTE:} This section is incomplete, as we have multiple ways of preceding. I have listed out the possible options.\n\n% \\begin{enumerate}\n%     \\item Use a temporally indexed dependent type. This allows us to encode\n%     certain properties such as \"$\\forall$ Times t, ...\" and \"$\\exists$ Time t, ...\" easily.\n%     \\item Use a co-inductive stream type. This would allow us to more easily\n%     prove relationships between 2 streams.\n% \\end{enumerate}\n\n\\section{Relating Programs to Types}\nNote again that we do not derive the types of programs from the bottom-up, as is the norm. Rather, we prove that programs inhabit types from the top-down, using a proof refinement system.\n\nTo begin, a proof is a tree of \\textbf{Judgments}, which consists of a number of \\textbf{hypotheses} of the form $x:A$ followed by a \\textbf{Goal}, which is of the form $term:T$. To proceed with the proof, we need to use refinement rules, which are ways of decomposing sub-goals. For example, say we had some term \\lstinline{fun x => x}, and we wanted to prove that this term is a member of $Bool \\rightarrow Bool$. An example proof would be as follows:\n\\begin{verbatim}\n    H >> (fun x => x) in Bool -> Bool by intro-function.\n        x:Bool, H >> x in Bool by hypothesis x.\n        H >> Bool in U by bool-intro-universe.\n\\end{verbatim}\nNote that we use 3 rules here, \\lstinline{intro-function}, \\lstinline{hypothesis}, and \\lstinline{intro-universe}. These correspond to the standard type inference rules, but there is a catch: We cannot infer the types. This is because a term can inhabit many potential types. For example, we could also prove that \\lstinline{fun x => x} inhabits the type $\\Pi_{A:U}.A \\rightarrow A$:\n\\begin{verbatim}\n    H >> (fun x => x) in (A:U) -> A -> A by intro-function-pi\n        A:U, x:A, H >> x in A by hypothesis x.\n\\end{verbatim}\n\n{\\color{red} NOTE:} The above rule needs some thinking about. As such, I have decided to not include it in the rule section yet.\n\n{\\color{red} NOTE:} Write some examples that show how to use the rules to prove nil-safety.\n\n\\section{Rules}\n\\subsection{Bool}\n\\begin{verbatim}\n    H >> true in Bool by intro-true.\n    H >> false in Bool by intro-false\n    H >> Bool in U1 by bool-intro-universe.\n\\end{verbatim}\n\\subsection{Nil}\n\\begin{verbatim}\n    H >> nil in Nil by intro-nil.\n    -- TODO: Write the choking type rules.\n    -- Needs clarification\n\\end{verbatim}\n\\subsection{Functions}\n\\begin{verbatim}\n    H >> (fun x => b) in (x:A) -> B by intro-function.\n        x:A, H >> b in B.\n        H >> A in Ui.\n        H >> B(x) in Ui. -- We may have to be careful about universe levels?\n    H >> (x:A) -> B in Ui by function-intro-universe.\n        H >> A in Ui.\n        H >> B in Ui.\n\\end{verbatim}\n\\subsection{Universes}\n\\begin{verbatim}\n    H >> Ui in Uj by universe-cumulative.\n        -- Note, i < j.\n\\end{verbatim}\n\n\\section{Bibliography}\n{\\color{red} NOTE:} This Section needs to be properly formatted, right now it is just a dumping ground for things that have influenced this work.\\\\\n\\url{http://www.nuprl.org/book/} \\\\\n\\url{http://www.nuprl.org/documents/Constable/naive.pdf} \\\\\n\\url{http://ect.bell-labs.com/who/ajeffrey/papers/plpv12.pdf} \\\\\n\n\\end{document}\n", "meta": {"hexsha": "ffacb6d48507b46fd11ad5bf67eae9e180f22be8", "size": 8136, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/semantics_v2.tex", "max_stars_repo_name": "fhackett/pixy-lang", "max_stars_repo_head_hexsha": "a697da339dfcc0c3d317a3a6448950f04a6c5e0d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2017-10-14T06:35:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-19T14:26:19.000Z", "max_issues_repo_path": "paper/semantics_v2.tex", "max_issues_repo_name": "fhackett/pixy-lang", "max_issues_repo_head_hexsha": "a697da339dfcc0c3d317a3a6448950f04a6c5e0d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-10-13T21:36:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-13T21:36:43.000Z", "max_forks_repo_path": "paper/semantics_v2.tex", "max_forks_repo_name": "fhackett/pixy-lang", "max_forks_repo_head_hexsha": "a697da339dfcc0c3d317a3a6448950f04a6c5e0d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-10-13T21:34:21.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-19T17:07:36.000Z", "avg_line_length": 56.5, "max_line_length": 813, "alphanum_fraction": 0.7223451327, "num_tokens": 2141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.34188150348988366}}
{"text": "%---------------------------------------------------------------------\n%  Writeup of the improved search of Run II data for single top quark\n%  production at DZero.\n%  Started: Oct 2006\n%  Authors: The Single Top Working Group\n%---------------------------------------------------------------------\n%\n\n\\appendix\n\\section*{Appendix 3 --- Normalization of Non-Top Backgrounds to Data}\n\\label{appendix-matrixmethod}\n\nWe use the matrix method~\\cite{mm_explained} to estimate how many\nevents in the preseleceted sample contain a fake lepton (originating\nfrom QCD-multijet production) and how many events have a real isolated\nlepton (like the ones originating from $W$+jets or $\\ttbar$). Two\ndata samples are defined: the \\emph{tight} sample, which is the signal\nsample after all selection cuts have been applied; and the\n\\emph{loose} sample, where the same selection has been applied but\nrequiring only loose lepton isolation, thus omitting the tight\nrequirements in the lepton isolation.\n\nThe tight data sample, with $N_{{\\rm tight}}$ events, is a subset of\nthe loose data sample with $N_{\\rm loose}$ events. The loose sample\ncontains $N_{\\rm loose}^{{\\rm real-}\\ell}$ events with a real lepton\n(signal-like events, mostly $W$+jets and $\\ttbar$) and $N_{\\rm\nloose}^{{\\rm fake-}\\ell}$ fake lepton events, which is the number of\nQCD events in the loose sample. We measure the efficiency for a real\nisolated lepton to pass the tight lepton isolation selection and call\nit $\\varepsilon_{{\\rm real-}\\ell}$; and the efficiency for a fake\nlepton to pass the tight lepton isolation criteria, $\\varepsilon_{{\\rm\nfake-}\\ell}$.\n\nWith these definitions, the matrix method is applied by using these\ntwo equations:\n\\begin{eqnarray*}\nN_{\\rm loose}   & = & N_{\\rm loose}^{{\\rm fake-}\\ell}\n                      + N_{\\rm loose}^{{\\rm real-}\\ell} \\\\\nN_{{\\rm tight}} & = & N_{{\\rm tight}}^{{\\rm fake-}\\ell}\n                      + N_{{\\rm tight}}^{{\\rm real-}\\ell} \n                      = \\varepsilon_{{\\rm fake-}\\ell} \\;\n                        N_{\\rm loose}^{{\\rm fake-}\\ell}\n                      + \\varepsilon_{{\\rm real-}\\ell} \\;\n                        N_{\\rm loose}^{{\\rm real-}\\ell} \n\\end{eqnarray*}\n\\noindent to solve for $N_{\\rm loose}^{{\\rm fake-}\\ell}$ and $N_{\\rm\nloose}^{{\\rm real-}\\ell}$ so that the QCD and the $W$-like\ncontributions in the tight sample $N_{\\rm tight}^{{\\rm fake-}\\ell}$\nand $N_{\\rm tight}^{{\\rm real-}\\ell}$ can be determined.\n\nThe results of the matrix method, which we apply separately in each\njet multiplicity bin, are shown in Table~\\ref{mm-numbers}. The\npretagged orthogonal sample is scaled to $N_{\\rm tight}^{{\\rm\nfake-}\\ell}$ and the $W$+jets MC samples\n($Wb\\bar{b}$+$Wc\\bar{c}$+$Wjj$) are scaled to $N_{\\rm tight}^{{\\rm\nreal-}\\ell}$, after subtracting the expected $\\ttbar$ events in each\nbin of the tight sample.\n\n\\vspace{0.2in}\n\\begin{table}[!h!tbp]\n\\begin{center}\n\\begin{minipage}{6.5in}\n\\begin{ruledtabular}\n\\begin{tabular}{l||ccccc|ccccc}\n\\multicolumn{11}{c}{\\hspace{1in}\\underline{Normalization of $W$+Jets and Multijets to Data}}\\vspace{0.1in} \\\\\n& \\multicolumn{5}{c|}{Electron Channel} & \\multicolumn{5}{c}{Muon Channel}    \\\\\n                               & 1 jet  & 2 jets & 3 jets & 4 jets & 5+ jets\n                               & 1 jet  & 2 jets & 3 jets & 4 jets & 5+ jets \\\\\n\\hline\n$N_{{\\rm loose}}$              & 38,935 & 15,213 &  7,118 &  2,191 &   654  & 18,714 &  7,092 &  3,054 &   878  &   221 \\\\\n$N_{{\\rm tight}}$              & 27,370 &  8,220 &  3,075 &    874 &   223  & 17,816 &  6,432 &  2,590 &   727  &   173 \\\\\n$N_{\\rm tight}^{{\\rm fake-}e}$ &  1,691 &  1,433 &    860 &    256 &    86  &    498 &    329 &    223 &    56  &    10 \\\\\n$N_{\\rm tight}^{{\\rm real-}e}$ & 25,679 &  6,787 &  2,215 &    618 &   137  & 17,319 &  6,105 &  2,369 &   669  &   162 \\\\\n$\\varepsilon_{{\\rm real-}e}$   &   0.87 &   0.87 &   0.87 &   0.87 &  0.87  &   0.99 &   0.99 &   0.99 &  0.96  &  0.88 \\\\\n$\\varepsilon_{{\\rm fake-}e}$   &   0.18 &   0.19 &   0.19 &   0.17 &  0.17  &   0.41 &   0.36 &   0.34 &  0.31  &  0.25\n\\end{tabular}\n\\end{ruledtabular}\n\\vspace{-0.1in}\n\\caption[mmnumbers]{Matrix method yields in the electron and muon channels:\nthe loose and tight selected events and the expected contribution from\nmultijet and $W$-like events.}\n\\label{mm-numbers}\n\\end{minipage}\n\\end{center}\n\\end{table}\n\n% from the old muon-only table:\n%$N_{\\rm tight}^{{\\rm real-}\\mu}$($W$+jets) & 17,313 &  6,064 &  2,276 &   563  &   116 \\\\\n%$N_{\\rm tight}^{{\\rm real-}\\mu}$($\\ttbar$) &      6 &     41 &     93 &   106  &    46 \\\\\n\n\n\\begin{figure}[!h!tbp]\n\\begin{center}\n\\includegraphics[width=0.32\\textwidth]{figures/electron/cc_EqOneJet_PreTag_WTransverseMass.eps\n\\includegraphics[width=0.32\\textwidth]{figures/electron/cc_EqTwoJet_PreTag_WTransverseMass.eps\n\\includegraphics[width=0.32\\textwidth]{figures/electron/cc_EqThreeJet_PreTag_WTransverseMass.eps\n\\includegraphics[width=0.32\\textwidth]{figures/muon/mu_EqOneJet_PreTag_WTransverseMass.eps  \n\\includegraphics[width=0.32\\textwidth]{figures/muon/mu_EqTwoJet_PreTag_WTransverseMass.eps  \n\\includegraphics[width=0.32\\textwidth]{figures/muon/mu_EqThreeJet_PreTag_WTransverseMass.eps\n\\end{center}\n\\vspace{-0.1in}\n\\caption[mu_2jet]{The leading jet $\\pt$, second leading jet $\\pt$, the muon\n$\\pt$, the $\\met$ and the $\\Delta R$(jet1,jet2) after selection but before tagging (first column), with 1\n$b$-tag (center column) and with 2 $b$-tags (right column).}\n\\label{fig:mu_2jet}\n\\end{figure}\n", "meta": {"hexsha": "248663a3bb7c9a1627891d31bd1945d0b733153e", "size": 5466, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "STnote/appendix_matrixmethod.tex", "max_stars_repo_name": "tgadf/thesis", "max_stars_repo_head_hexsha": "19d4a6bc7f7ac8660fce582322703d50e0d6bd31", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "STnote/appendix_matrixmethod.tex", "max_issues_repo_name": "tgadf/thesis", "max_issues_repo_head_hexsha": "19d4a6bc7f7ac8660fce582322703d50e0d6bd31", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "STnote/appendix_matrixmethod.tex", "max_forks_repo_name": "tgadf/thesis", "max_forks_repo_head_hexsha": "19d4a6bc7f7ac8660fce582322703d50e0d6bd31", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.0841121495, "max_line_length": 122, "alphanum_fraction": 0.6295279912, "num_tokens": 1920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.34183661995377096}}
{"text": "\\subsection{Controller Design using Dead-Time and PT1 element}\n\nNow that $T_u$, $T_g$, $K_{p,crit}$ and $\\tau_{crit}$ have been determined, we\nuse the formulas  in tables \\ref{tab:ziegler_nichols}, \\ref{tab:CHR_rejection}\nand \\ref{tab:CHR_tracking} to create various  P,  PI  and PID controllers. The\nresulting    closed   loop   step   functions   are   plotted    in    figures\n\\ref{fig:Tt_PT1_P},     \\ref{fig:Tt_PT1_PI}      and     \\ref{fig:Tt_PT1_PID}.\n\n\nThe  P-controller   obtained   from   the   Ziegler-Nichols  method  is  quite\nunbelievable. The motor requires about 30  seconds  to reach its end speed, so\nwhy is  it  able  to  reach  its  target  value  after  just three seconds? By\nsimulating what happens on the output of the controller (the voltage that gets\nfed   into    the    motor),    we   see   what's   going   on   (see   figure\n\\ref{fig:Tt_PT1_P_voltage}).\n\nThe  voltage  levels  being  used  to  control the motor  grossly  exceed  the\ncapabilities of the driver and the maximum rating of the motor. One would have\nto  decrease the $K_p$ parameter in this controller until the voltage  reaches\nacceptable levels again in order to make this controller feasible.  The  issue\nthen,  though,  is  that  the  target  value  doesn't  get  reached  any more.\n\n\\begin{figure}[h]\n    \\centering\n    \\includegraphics[width=\\imagewidth]{images/Tt_PT1_P}\n    \\caption{Various P controllers}\n    \\label{fig:Tt_PT1_P}\n\\end{figure}\n\n\\begin{figure}[h]\n    \\centering\n    \\includegraphics[width=\\imagewidth]{images/Tt_PT1_PI}\n    \\caption{Various PI controllers}\n    \\label{fig:Tt_PT1_PI}\n\\end{figure}\n\n\\begin{figure}[h]\n    \\centering\n    \\includegraphics[width=\\imagewidth]{images/Tt_PT1_PID}\n    \\caption{Various PID controllers}\n    \\label{fig:Tt_PT1_PID}\n\\end{figure}\n\n\\begin{figure}[t]\n    \\centering\n    \\includegraphics[width=\\imagewidth]{images/Tt_PT1_P_voltages}\n    \\caption{Simulated voltage on the input of the motor}\n    \\label{fig:Tt_PT1_P_voltage}\n\\end{figure}\n\n\\clearpage\n", "meta": {"hexsha": "6e4fb683ecd80dfea89895476965682ecef6fab0", "size": 2001, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "versuche/rtGL/labor2/sections/simulations/controllers_Tt_PT1.tex", "max_stars_repo_name": "TheComet93/laborjournal", "max_stars_repo_head_hexsha": "5b83c35ec2580a22106d755f466dc6371d7444ee", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "versuche/rtGL/labor2/sections/simulations/controllers_Tt_PT1.tex", "max_issues_repo_name": "TheComet93/laborjournal", "max_issues_repo_head_hexsha": "5b83c35ec2580a22106d755f466dc6371d7444ee", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "versuche/rtGL/labor2/sections/simulations/controllers_Tt_PT1.tex", "max_forks_repo_name": "TheComet93/laborjournal", "max_forks_repo_head_hexsha": "5b83c35ec2580a22106d755f466dc6371d7444ee", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4807692308, "max_line_length": 78, "alphanum_fraction": 0.7206396802, "num_tokens": 595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.3418366118838624}}
{"text": "\\documentclass[12pt]{article}\n%\\usepackage{a4wide}\n\\usepackage[margin=2.5cm,a4paper]{geometry}\n%\\usepackage[latin1]{inputenc}\n\\usepackage{amsmath}\n\\usepackage{amsthm}\n\\usepackage{paralist}\n\\usepackage{bbm}\n\\usepackage{amssymb}\n\\usepackage{pdfpages}\n\\usepackage[T1]{fontenc}\n\n\\usepackage[pdftex,bookmarks,colorlinks,breaklinks,pdfpagelabels]{hyperref} \n\n\\usepackage{epic,eepic,latexsym,verbatim}\n%\\usepackage{youngtab}\n%\\usepackage{bbm}\n\\newcommand{\\ket}[1]{|#1\\rangle}\n\\newcommand{\\bra}[1]{\\langle #1|}\n\\newcommand{\\bracket}[2]{\\langle #1|#2\\rangle}\n\\newcommand{\\ketbra}[1]{|#1\\rangle\\langle #1|}\n\\newcommand{\\average}[1]{\\langle #1\\rangle}\n\\newcommand{\\minus}{\\!-\\!}\n\n\\newcommand{\\om}{\\omega}\n%\\newcommand{\\th}{\\theta}\n\\newcommand{\\rn}{\\mathbb{R}^n}\n\\newcommand{\\R}{\\mathbb{R}}\n\\setlength{\\parindent}{0pt}\n\\newtheorem{theorem}{Theorem}\n\\newcommand{\\question}[2]{{\\bf #1} {\\em #2}\\\\}\n\\newcommand{\\problem}[3]{{\\bf #1} {\\em #2}\\\\[5\\lineskip]\n{#3}}\n\n\\newcounter{dummy}\n\\setcounter{dummy}{0}\n\\newtheorem{p}{Exercise}[dummy]\n\\renewcommand\\thep{\\arabic{p}}\n\\setcounter{secnumdepth}{0}\n\\overfullrule=5pt\n\n\\author{Joseph M.\\ Renes}\n\\title{Solutions to Baez and Muniain's \\\\\\emph{Gauge Fields, Knots and Gravity}}\n\\begin{document}\n\\renewcommand{\\abstractname}{\\vspace{-\\baselineskip}}\n\n\n\\hypersetup{pageanchor=true}\n\n\\maketitle\n\n\\begin{abstract}\nHere are my solutions to some of the problems in \\emph{Gauge Fields, Knots and Gravity}. \nAt some point I also wrote up a few notes on the Lie derivative in the style of the book.\\\\\n\nversion 1.0 --- Importing original writeup of solutions and Lie derivative.\n\\end{abstract}\n\n\\pdfbookmark[1]{\\contentsname}{Contents}\n\\tableofcontents\n\n\n\n\\newpage\n\n\\section{Part I}\n\\input{src/I1}\n\n\\input{src/I2}\n\n\\input{src/I3}\n\n\\input{src/I4}\n\n\\input{src/I5}\n\n\\input{src/I6}\n\n\n\\section{Part II}\n\\setcounter{dummy}{1}\n\\setcounter{p}{0}\n\n\\input{src/II1}\n\n\\setcounter{p}{54}\n\n\\input{src/II2}\n\n\\input{src/II3}\n\n%\\section{The Lie derivative}\n\n%\\pdfbookmark[1]{The Lie derivative}{lie}\n\\includepdf[pages=-,addtotoc={1,section,1,The Lie derivative,lie}\n]{src/lie.pdf}\n\n\\includepdf[pages=-]{src/expmap.pdf}\n\n\n\n\n\n\\end{document}", "meta": {"hexsha": "e7b4c326fad2809b80bc9e7100cfa47475a075d7", "size": 2139, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "gfkg.tex", "max_stars_repo_name": "joerenes/Baez-Muniain-solutions", "max_stars_repo_head_hexsha": "e1e38de9acab877bc4200af59c7910d42de748ca", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-04-13T12:10:03.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-19T18:18:34.000Z", "max_issues_repo_path": "gfkg.tex", "max_issues_repo_name": "joerenes/Baez-Muniain-solutions", "max_issues_repo_head_hexsha": "e1e38de9acab877bc4200af59c7910d42de748ca", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-04-13T12:15:30.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-13T20:19:44.000Z", "max_forks_repo_path": "gfkg.tex", "max_forks_repo_name": "joerenes/Baez-Muniain-solutions", "max_forks_repo_head_hexsha": "e1e38de9acab877bc4200af59c7910d42de748ca", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5673076923, "max_line_length": 91, "alphanum_fraction": 0.7223001403, "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.3418366118838624}}
{"text": "\\chapter*{Introduction}\n\nIn math, people prefer to use ``$ \\log_e $'' or just ``$ \\log $'' rather than ``$ \\ln $'', which is the opposite to many scientific fields. Due to its simplicity (especially when typing), I will also stick to the usage of ``$ \\ln $'' which is identical to ``$ \\log_e $''. But to avoid any confusion, I will always specify the base 10 (``$ \\lg $'').\n\nAt many places in physics and astronomy, people use $ \\equiv $ as ``is defined as'' or any kind of ``trivial by the definition'' cases. But I will use $ := $ for the definition and use $ \\equiv $ to mean ``equality holds trivially by the definition''. For example, under 1-D linear homogeneous isotropic matter, linear electric polarization is written as $ P \\equiv \\epsilon_0 \\chi E $ or $ \\chi := P/\\epsilon_0 E $. The latter is the \\textit{definition} of electric susceptability, while the former is \\textit{trivially true by the definition}. \n\nFor distributions, $ \\sim $ means ``follows'', i.e., $ X \\sim \\mathcal{N}(\\mu, \\sigma^2) $ means ``the random variable $ X $ follows the Gaussian (normal) distribution with mean $ \\mu $ and standard deviation $ \\sigma $ (thus variance $ \\sigma^2 $).'' When this is an approximation, the symbol with dot ``$ \\simdot $'' is used, such as $ X \\simdot \\mathcal{N}(\\mu, \\sigma^2) $. In this case, it is interpreted as ``approximately follows.''\n\nIn this note, I used some math-like notations like theorem (Thm). However, the theorem here is not necessarily the same as that of mathematics. I tried to put some important assumptions and summary notes to theorem.\n\nThe references are \n\\begin{itemize}\n\\item ``Walpole'' is Walpole et al. 2013, ``Essentials of Probabilities and Statistics''.\n\\item ``Sivia'' is Sivia and Skilling 2006, ``Data Analysis A Bayesian Tutorial'', 2/e.\n\\end{itemize}", "meta": {"hexsha": "219f954ff92ca9b0ff472699c4aadbb7372526f6", "size": 1808, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Books/chaps/00_intro.tex", "max_stars_repo_name": "ysBach/SNU_AOclass", "max_stars_repo_head_hexsha": "e2e364b08c2e6e129c267db9cbd76cfd0ab77527", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-03-23T06:14:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T01:49:51.000Z", "max_issues_repo_path": "Books/chaps/00_intro.tex", "max_issues_repo_name": "ysBach/SNU_AOclass", "max_issues_repo_head_hexsha": "e2e364b08c2e6e129c267db9cbd76cfd0ab77527", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-05-04T17:21:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-24T11:41:55.000Z", "max_forks_repo_path": "Books/chaps/00_intro.tex", "max_forks_repo_name": "ysBach/SNU_AOclass", "max_forks_repo_head_hexsha": "e2e364b08c2e6e129c267db9cbd76cfd0ab77527", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-05-10T14:19:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-14T09:18:08.000Z", "avg_line_length": 120.5333333333, "max_line_length": 546, "alphanum_fraction": 0.7101769912, "num_tokens": 478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.34183660381395375}}
{"text": "\\documentclass[10pt,journal,compsoc]{IEEEtran}\n\n\\usepackage[pdftex]{graphicx}    \n\\usepackage{cite}\n\\usepackage{subcaption} \n\\hyphenation{op-tical net-works semi-conduc-tor}\n\\graphicspath{ {../images/} }\n\n\\begin{document}\n\n\\title{Robotics Software Engineer Nanodegree: Deep RL Arm Manipulation}\n\\author{Manuel Huertas L\\'opez}\n\n\\markboth{Deep RL Arm Manipulation project, Robotic Nanodegree, Udacity}%\n{}\n\n\\IEEEtitleabstractindextext{%\n\n\\begin{abstract}\n\nReinforcement learning is an area of ​​machine learning. It instructs an agent to take actions in an environment in order to maximize a cumulative reward. In this project a DQN algorithm will be used to guide a robotic arm to touch a cylindrical object. The idea behind the algorithm is to find an action value function; this function will give the cumulative expected reward for every state and action pair values. Once this function is obtained the action for every state will be the one that maximizes the reward. DQN is a variation of the algorithm where this function is replaced with a Deep Neural Network.\n\n\\end{abstract}\n\n\\begin{IEEEkeywords}\nRobot, Udacity, Deep Reinforcemente Learning.\n\\end{IEEEkeywords}}\n\n\\maketitle\n\\IEEEdisplaynontitleabstractindextext\n\\IEEEpeerreviewmaketitle\n\\section{Introduction}\n\nIn this project a Robotic Arm with three degree of freedom will be taught in order to touch a cylindrical shape in the scene. Rather than using the forward and backward kinematic to calculate the position of the arm with respect to the joint angles or to move the arm to a goal position sending demands to the joints, the robot will try some random movements and it will receive a positive or negative reward. A video camera will be recording constatinualsy the robot movement and this information is used to train a neural network, the network will try to reproduce the sequence of movement that maximise the cumulative reward. As the final goal the robot will find the combination of joint movement, without a model, to approximate and finally touch the object in the scene.\n\nEvery Episodic finalized when the robot: touch the ground, touch the cylinder or the maximum number of iteration is reached. The final reward will be positive just in case the robot touch the cylinder, and there are some intermediate positive reward bases on smooth movement and when the robot is closer to the cylinder. The problem can be defined as a Markov Decision Process \\cite{udacity} where:\n\\begin{itemize}\n\\item a finite set of states: the image from the video camera and all the pixel value combinations.\n\\item a finite set of actions: the movement every joint.\n\\item a finite set of rewards: the positive and negative reward depending on the robot behaviour.\n\\item the one-step dynamics of the environment: given the current state and the action, the expected new state and new reward. The neural network will obtain this during thetrainingg process.\n\\item a discount rate between [0,1]: the discount rate.\n\\end{itemize}\n\n\\label{sec:introduction}\n\n\\section{Background / Formulation}\n\nOur goal is to find a function that for every state, the image in this case, tell use which action to take, the movement of the joint. This problem is not easy since there are a big number of states, pixel combination of the image, and sequences of movements. In this project an algorithm based in DQN have been used. In DQN a Deep Neural Network will build a function where the input will be the pixel of the image and the output the expected cumulative reward for every possible action. Selecting the action with the highest cumulative reward will give us the desired action. In addition, a Long Short Term Memory network have been used to use the information of the sequence of multiple images, instead of a single frame.\n\n\\subsection{Deep Q Network}\n\nThe Q-Learning algoritm is a model-free algoritm. The values for each state-action pair are estimated based on observation of the environment \\cite{deepreinforcementlearning}. The Q-Learning algoritm estimate the state action funcition using the following equation:\n\n\\begin{align}\nQ(s_{t},a_{t})=(1-\\alpha) \\cdot Q(s_{t},a_{t})+\\alpha \\cdot (r_{t}+\\gamma max_a\\cdot Q(s_{t+1},a))\n\\end{align}\n\nThe meaning of this parameter are:\n\n\\begin{itemize}\n\\item s: state value at time t, from the observation.\n\\item a: action value a time t.\n\\item alpha: learning rate, the way in which new values replaces old ones.\n\\item r: reward at time t.\n\\item gamma: discount factor.\n\\end{itemize}\n\nIn addition, the greedy policy is used to select between a current best action, exploit, or to select a random action, explore. If during the learning process we always select the action with currently the best reward we are never going to explore new solutions whose can give a better discounted future reward. On the other one, we need to select the current best action in order to use the knowledge we are acquiring iteratively. One way to accomplish this is to explore more at the beginning of the learning process, and gradually reduce the exploration favouring the exploitation of the current knowledge. For doing this the following parameters are defined:\n\n\\begin{itemize}\n\\item EPS\\_START: starging gready value.\n\\item EPS\\_END: ending gready value.\n\\item EPS\\_DECAY: gready decay rate\n\\end{itemize}\n\nFinally, the state action function is replaced with a deep neural network. The input of the network is the image from the video camera, and the output the reward or every action. The loss function, for the gradient descent algorithm, is defined as:\n\n\\begin{align}\nLoss=1/2 \\cdot [r_{t} + max_{a_{t+1}}\\cdot Q(s_{t+a},a_{t+1};\\theta_{t-1}}) - Q(s,a;\\theta}]^2\n\\end{align}\n\nTwo extra techniques are included to make the neural network converge to the final solution. Experience replay, where a memory of experience is used to store previous values; mini-batches of these values are used as input of the neural network during learning. This technique helps to break the temporal dependencies of the learning process. Since the target of the loss function and the predictions have parameters in common, the process of learning can not converge to the correct solution, fixed Q targets is used to update the Q function after several iterations, in this way the small changes in the Q function approximation are not affecting the learning process.\n\nThe following extra parameters are defined.\n\n\\begin{itemize}\n\\item  INPUT\\_WIDTH: Image from the camera, width\n\\item  INPUT\\_HEIGHT: Image from the camera, height\n\\item  OPTIMIZER: Optimizer for the gradient descent algorithm \n\\item  LEARNING\\_RATE: Neural Network learning rate.\n\\item  REPLAY\\_MEMORY: Size of the memory for the experience replay technique.\n\\item  BATCH\\_SIZE: Batch size for the experience replay technique.\n\\end{itemize}\n\n\\subsection{Long Short Term Memory}\n\nLSTM is a special Recurrent Neural Network, capable of learning long-term dependencies. The Long short-term memory adds memory to the DQN to remember the sequence of movements of the joint to find and touch the object in the scene \\cite{lstmnetwork}.\n\n\\section{Robotic Arm}\n\nIn a reinforcement learning problem, a temporary series of interactions are produced until the episodic ends: S_{0},A_{0},R_{1},S_{1},A_{1},R_{2},...,R_{T},S_{T}\n\nIn this project, an episode ends when: the robot's arm touches the ground, a maximum of iterations is reached, or the robot touches the object in the scene; the states are the image, captured by the video camera, of the scene; the actions can be to move the joints at random using position or speed control; finally, the reward strategy is defined as a negative number when the robot finishes the episodic without touching the object, the positive number when it touches the object and an incremental or decremental reward when the arm approaches the target or not.\n\nDifferent reward strategies were tested, the final choose solution was: a big number positive number when the robot touches the object; a negative number when the robot touch the ground or the maximum iterations are reached, to this negative number a 1\\% of the distance to the goal is added, in order to decrease the negative reward depending on the closest to the goal; a smooth reward when the robot is searching the object in function of the smoothest of the movement and the distance to the goal.\n\n\\subsection{Rewards}\n\nThe positive reward when the object is touched is 1000000.0. The negative base reward is -1.0. When the episodice ends without success to the negative base reward is added 1\\% the distance to the goal. Finally when the Robot is searching a soomoth average goal delta is added to the distance to the goal as follow:\n\nAverageGoalDelta  = ( AverageGoalDelta * 0.2 ) + (DistanceDelta * (1-0.2));\n\nReward Searching  = AverageGoalDelta + 0.01*exp(-pow(DistanceGoal,2));\n\nThe same rewards were used for both objectives. \n\n\\subsection{Hiper Paramters}\n\nFinally the hiper-parameters selecting were:\n\n\\begin{itemize}\n\\item  VELOCITY\\_CONTROL[false]: The position control was used.\n\\item  NUMBER\\_ACTIONS[6]: The number of actions was calculated as number of DOF x 2.\n\\item  ALLOW\\_RANDOM[true]: The learnning process allows random decisions to explore new solutions.\n\\item  GAMMA[0.9]: discount factor, selected was 0.9.\n\\item  EPS\\_START[0.9]: Starting greedy value.\n\\item  EPS\\_END[0.01] Ending greedy value.\n\\item  EPS\\_DECAY[200]: Greedy decay rate\n\\item  INPUT\\_WIDTH[64]: Image from the camera width\n\\item  INPUT\\_HEIGHT[64]: Image from the camera height\n\\item  OPTIMIZER[RMSprop]: Optimizer for the gradient descent algorithm \n\\item  LEARNING\\_RATE[0.01]: Neural Network learning rate.\n\\item  REPLAY\\_MEMORY[10000]: Size of the memory for the experience replay technique.\n\\item  BATCH\\_SIZE[64]: Batch size for the experience replay technique.\n\\item  USE\\_LSTM[true]: Uses Long Short Memory.\n\\item  LSTM\\_SIZE[512]: Sizes of the LSTM network.\n\\end{itemize}\n\nThe same Hiper Parameters were used for both objectives. \n\n\\section{Results}\n\nIn order to find the reward and hiper-parameters a trial and error strategy was used. At the beginning velocity control was used, but the desired accuracy of 80\\% of success touching the object with the gripper base was not achieve, for that reason the position control was selected. The reward strategy consists in give a high positive number when the robot touches the object, this big number was selected because the robot could accumulate small rewards during the searching process and it was important to stimulate the robot not to keep searching but to move toward the goal. During the searching process a small amount of the distance to goal was added to the reward to indicate the robot's arm that the action should move the arm in the object direction. Also, a factor depending on of the delta movement, was used to increase, when the movement was directing the robot to the goal, or decrease when the movement was in the other direction. This searching strategy was used to indicate the robot's arm to keep moving and to do it smoothly  to the goal direction. Finally, when the robot ends the episodic without success, a negative reward is given. To this negative reward a factor of the distance to the goal is added to indicate the robot how close was to the solution, even having failed.\n\n\\begin{figure}[h]\n\\centering\n\\begin{subfigure}[b]{0.4\\textwidth}\n\\includegraphics[scale=0.25]{Learnning_Collision_ARM}\n\\caption{Robot's Arm touching the object}\n\\end{subfigure}\n\\begin{subfigure}[b]{0.4\\textwidth}\n\\includegraphics[scale=0.27]{Learnning_Collision_Gripper}\n\\caption{Robot's Arm touching the object with the base gripper}\n\\end{subfigure}\n\\caption{Robot's Arm}\n\\end{figure}\n\n\\section{Discussion}\n\nThe project consists in completing eight tasks:\n\n\\begin{enumerate}\n\\item  Subscribe to camera and collision topics: This was easily achieved following the udacity instructions.\n\\item  Create the DQN Agent: Udacity provided the class, it was just necessary to create an instance.\n\\item  Velocity or position based control of arm joints: position control was selected because it was easier to define the rewards.\n\\item Reward for robot gripper hitting the ground: using a bounding box for the gripper it was detected when it was hitting the ground; a negative reward plus a 1\\% to the distance to the goal was used.\n\\item Issue an interim reward based on the distance to the object: an incremental, reward positive or negative, was used, depending on the robot movement to the goal or not.\n\\item Issue a reward based on collision between the arm and the object: a very high number was used to stimulate the robot to move to the goal.\n\\item Tuning the hyper parameters: a trail an error approach was used to find the final parameters.\n\\item  Issue a reward based on collision between the arm’s gripper base and the object: the same reward and hyper parameters were used for the two objectives.\n\\end{itemize}\n\n\n\\section{Conclusion / Future work}\n\nIn order to improve the project a deeper understating about how the reward affects the learning process will be needed. A way to do this can be to visualize the Q-Function using a 2D plot where the x-axis can be the actions, y-axis the state, and the coloured value of the graph the reward. The rewards were selected using some logic about how the human will learn to solve the problem. Different strategies will be needed to be explored in order to find a solution that converges quicklier to the final solution.\n\n% Bibliography\n\\begin{thebibliography}{9}\n\\bibliographystyle{ieeetr}\n\n\\bibitem{udacity} \nRobotics Software Engineer Nanodegree program\n\\textit{https://eu.udacity.com}\n\n\\bibitem{deepreinforcementlearning} \n\\textit{Human-level control through deep reinforcement learning}. \n\n\\bibitem{lstmnetwork} \nUnderstanding LSTM Networks\n\\textit{http://colah.github.io/posts/2015-08-Understanding-LSTMs}\n\n\\end{thebibliography}\n\n\\end{document}", "meta": {"hexsha": "11ae583a6b55b6fbf5f56c9e63fc8841e1383eeb", "size": 13867, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/udacity-deeprl.tex", "max_stars_repo_name": "mahulo2009/RoboND-DeepRL-Project", "max_stars_repo_head_hexsha": "de9318327edd2c13dd87284d35ee26edeba0db4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/udacity-deeprl.tex", "max_issues_repo_name": "mahulo2009/RoboND-DeepRL-Project", "max_issues_repo_head_hexsha": "de9318327edd2c13dd87284d35ee26edeba0db4f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/udacity-deeprl.tex", "max_forks_repo_name": "mahulo2009/RoboND-DeepRL-Project", "max_forks_repo_head_hexsha": "de9318327edd2c13dd87284d35ee26edeba0db4f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 70.75, "max_line_length": 1299, "alphanum_fraction": 0.7913030937, "num_tokens": 3194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.607663184043154, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.34161396252250303}}
{"text": "% Created 2022-05-03 Tue 11:38\n% Intended LaTeX compiler: pdflatex\n\\documentclass[t]{beamer}\n\\usepackage[utf8]{inputenc}\n\\usepackage[T1]{fontenc}\n\\usepackage{graphicx}\n\\usepackage{longtable}\n\\usepackage{wrapfig}\n\\usepackage{rotating}\n\\usepackage[normalem]{ulem}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{capt-of}\n\\usepackage{hyperref}\n\\mode<beamer>{\\usetheme{Amsterdam}}\n\\mode<beamer>{\\usecolortheme{rose}}\n\\usepackage{fontspec}\n\\usepackage{polyglossia}\n\\setmainlanguage[babelshorthands=true]{german}\n\\usepackage{hyperref}\n\\usepackage{color}\n\\usepackage{xcolor}\n\\usepackage[misc]{ifsym}\n\\definecolor{darkblue}{rgb}{0,0,.5}\n\\definecolor{darkgreen}{rgb}{0,.5,0}\n\\definecolor{islamicgreen}{rgb}{0.0, 0.56, 0.0}\n\\definecolor{darkred}{rgb}{0.5,0,0}\n\\definecolor{mintedbg}{rgb}{0.95,0.95,0.95}\n\\definecolor{arsenic}{rgb}{0.23, 0.27, 0.29}\n\\definecolor{prussianblue}{rgb}{0.0, 0.19, 0.33}\n\\definecolor{coolblack}{rgb}{0.0, 0.18, 0.39}\n\\hypersetup{colorlinks=true, breaklinks=true, anchorcolor=blue,linkcolor=white, citecolor=islamicgreen, filecolor=darkred,  urlcolor=darkblue}\n\\usepackage{booktabs}\n\\usepackage{pgf}\n\\usepackage{minted}\n\\RequirePackage{fancyvrb}\n\\DefineVerbatimEnvironment{verbatim}{Verbatim}{fontsize=\\scriptsize}\n\\usetheme{default}\n\\author{Göran Kirchner\\thanks{e\\_kirchnerg@doz.hwr-berlin.de}}\n\\date{2021-05-03}\n\\title{Funktionale Programmierung in F\\# (5)}\n\\subtitle{Parser Combinators}\n\\hypersetup{\n pdfauthor={Göran Kirchner},\n pdftitle={Funktionale Programmierung in F\\# (5)},\n pdfkeywords={},\n pdfsubject={},\n pdfcreator={Emacs 27.2 (Org mode 9.5.2)}, \n pdflang={English}}\n\\begin{document}\n\n\\maketitle\n\n\\section{Ziel }\n\\label{sec:org0ee434b}\n\\begin{frame}[label={sec:orgc9d6c29}]{Programm}\n\\begin{itemize}\n\\item Hausaufgaben\n\\item Test\n\\item Parser (Kombinatoren)\n\\end{itemize}\n\\end{frame}\n\n\\section{Hausaufgaben }\n\\label{sec:org62f30a3}\n\\begin{frame}[label={sec:orgfc210c3},fragile]{Accumulate}\n \\begin{minted}[bgcolor=mintedbg,frame=none,framesep=0pt,mathescape=true,fontsize=\\scriptsize,breaklines=true,linenos=false,numbersep=5pt,gobble=0]{fsharp}\nlet rec accumulateR func input acc = \n    match input with\n    | [] -> acc |> List.rev\n    | head::tail -> accumulateR func tail (func head :: acc)\nlet accumulate func input = accumulateR func input []\nlet test1 = accumulate (fun x -> x * x) [1; 2; 3]\nlet test2 = accumulate (fun (x:string) -> x.ToUpper()) [\"hello\"; \"world\"]\ntest2\n\\end{minted}\n\n\\begin{verbatim}\nval accumulateR: func: ('a -> 'b) -> input: 'a list -> acc: 'b list -> 'b list\nval accumulate: func: ('a -> 'b) -> input: 'a list -> 'b list\nval test1: int list = [1; 4; 9]\nval test2: string list = [\"HELLO\"; \"WORLD\"]\nval it: string list = [\"HELLO\"; \"WORLD\"]\n\\end{verbatim}\n\\end{frame}\n\n\\begin{frame}[label={sec:orgd3a40f9},fragile]{Space Age}\n \\begin{minted}[bgcolor=mintedbg,frame=none,framesep=0pt,mathescape=true,fontsize=\\scriptsize,breaklines=true,linenos=false,numbersep=5pt,gobble=0]{fsharp}\ntype Planet = \n    | Mercury\n    | Venus\n    | Earth\n    | Mars\n    | Jupiter\n    | Saturn\n    | Uranus\n    | Neptune\nlet orbitalPeriodRelativeToEarthOn planet = \n    match planet with\n    | Mercury -> 0.2408467\n    | Venus -> 0.61519726\n    | Earth -> 1.0\n    | Mars -> 1.8808158\n    | Jupiter -> 11.862615\n    | Saturn -> 29.447498\n    | Uranus -> 84.016846\n    | Neptune -> 164.79132\n\\end{minted}\n\n\\begin{verbatim}\ntype Planet =\n  | Mercury\n  | Venus\n  | Earth\n  | Mars\n  | Jupiter\n  | Saturn\n  | Uranus\n  | Neptune\nval orbitalPeriodRelativeToEarthOn: planet: Planet -> float\n\\end{verbatim}\n\\end{frame}\n\n\\begin{frame}[label={sec:org155f1d4},fragile]{Space Age (II)}\n \\begin{minted}[bgcolor=mintedbg,frame=none,framesep=0pt,mathescape=true,fontsize=\\scriptsize,breaklines=true,linenos=false,numbersep=5pt,gobble=0]{fsharp}\nopen System\n[<Literal>]\nlet SecondsInOneEarthYear = 31557600.0\nlet secondsInAYearOn planet =\n    SecondsInOneEarthYear * orbitalPeriodRelativeToEarthOn planet\nlet round (number : float) = Math.Round(number, 2)\nlet age (planet: Planet) (seconds: int64): float =\n    float seconds / (secondsInAYearOn planet)\n    |> round\nlet test1 = age Earth 1000000000L\n\\end{minted}\n\n\\begin{verbatim}\n[<Literal>]\nval SecondsInOneEarthYear: float = 31557600\nval secondsInAYearOn: planet: Planet -> float\nval round: number: float -> float\nval age: planet: Planet -> seconds: int64 -> float\nval test1: float = 31.69\n\\end{verbatim}\n\\end{frame}\n\n\\begin{frame}[label={sec:org48530c4},fragile]{Zusammenfassung}\n \\begin{itemize}\n\\item nutze \\href{https://exercism.io}{exercism.io}!\n\\item Formatierung (dotnet fantomas)\n\\item Vermeide \\texttt{mutable}!!\n\\item nur wichtiges verdient einen Namen\n\\item Vertraue der \\alert{Pipe} (\\texttt{>>}, \\texttt{|>}, \\ldots{})!!\n\\item If-Then-Else mit Boolean ist unnötig\n\\item Parametrisiere!\n\\item If-Then-Else vermeiden \\ldots{} besser \\texttt{match}!\n\\item Be lazy! (vermeide \\texttt{for}-loops)\n\\item \\href{https://fsharpforfunandprofit.com/troubleshooting-fsharp/}{Troubleshooting F\\#}\n\\item \\href{https://docs.microsoft.com/de-de/dotnet/fsharp/style-guide/}{F\\#-Styleguide}\n\\end{itemize}\n\\end{frame}\n\n\\section{Test }\n\\label{sec:org3061079}\n\\begin{frame}[label={sec:orgd6d78e6}]{Test}\n\\begin{itemize}\n\\item 90 Minuten\n\\item Ergebnis per \\href{mailto://e\\_kirchnerg@doz.hwr-berlin.de}{E-Mail} an \\href{mailto://e\\_kirchnerg@doz.hwr-berlin.de}{e\\_kirchnerg@doz.hwr-berlin.de}.\n\\end{itemize}\n\n\\(\\leadsto\\) \\href{../src/5/test.md}{Test}\n\\end{frame}\n\n\\section{Parser }\n\\label{sec:org0caa37e}\n\\begin{frame}[label={sec:orga6ffe1c},fragile]{Parser 1 (hard-coded character)}\n \\begin{minted}[bgcolor=mintedbg,frame=none,framesep=0pt,mathescape=true,fontsize=\\scriptsize,breaklines=true,linenos=false,numbersep=5pt,gobble=0]{fsharp}\nopen System\nlet A_Parser str =\n    if String.IsNullOrEmpty(str) then\n        (false,\"\")\n    else if str.[0] = 'A' then\n        let remaining = str.[1..]\n        (true,remaining)\n    else\n        (false,str)\nlet inputABC = \"ABCD\";;\nlet inputZBC = \"ZBCD\";;\nlet test11 = A_Parser inputABC\nlet test12 = A_Parser inputZBC\n\\end{minted}\n\n\\begin{verbatim}\nval test11: bool * string = (true, \"BCD\")\nval test12: bool * string = (false, \"ZBCD\")\n\\end{verbatim}\n\\end{frame}\n\n\\begin{frame}[label={sec:orgc4ae52c},fragile]{Parser 2 (match a specified character)}\n \\begin{minted}[bgcolor=mintedbg,frame=none,framesep=0pt,mathescape=true,fontsize=\\scriptsize,breaklines=true,linenos=false,numbersep=5pt,gobble=0]{fsharp}\nlet pchar (charToMatch,str) =\n    if String.IsNullOrEmpty(str) then\n        let msg = \"No more input\"\n        (msg,\"\")\n    else \n        let first = str.[0] \n        if first = charToMatch then\n            let remaining = str.[1..]\n            let msg = sprintf \"Found %c\" charToMatch\n            (msg,remaining)\n        else\n            let msg = sprintf \"Expecting '%c'. Got '%c'\" charToMatch first\n            (msg,str)\n\\end{minted}\n\n\\begin{verbatim}\nval pchar: charToMatch: char * str: string -> string * string\n\\end{verbatim}\n\\end{frame}\n\n\n\\begin{frame}[label={sec:org82f0e21},fragile]{Parser 2 (2)}\n \\begin{minted}[bgcolor=mintedbg,frame=none,framesep=0pt,mathescape=true,fontsize=\\scriptsize,breaklines=true,linenos=false,numbersep=5pt,gobble=0]{fsharp}\nlet inputABC = \"ABCD\";;\nlet inputZBC = \"ZBCD\";;\nlet test21 = pchar('A',inputABC) \nlet test22 = pchar('A',inputZBC)\n\\end{minted}\n\n\\begin{verbatim}\nval test21: string * string = (\"Found A\", \"BCD\")\nval test22: string * string = (\"Expecting 'A'. Got 'Z'\", \"ZBCD\")\n\\end{verbatim}\n\\end{frame}\n\n\\begin{frame}[label={sec:orgfd2993e},fragile]{Parser 3 (return a Result)}\n \\begin{minted}[bgcolor=mintedbg,frame=none,framesep=0pt,mathescape=true,fontsize=\\scriptsize,breaklines=true,linenos=false,numbersep=5pt,gobble=0]{fsharp}\nlet pchar (charToMatch, s) =\n    if String.IsNullOrEmpty(s) then\n        Error \"No more input\"\n    else\n        let first = s.[0]\n        if first = charToMatch then\n            let remaining = s.[1..]\n            Ok (charToMatch, remaining)\n        else\n            let msg = sprintf \"Expecting '%c'. Got '%c'\" charToMatch first\n            Error msg\n\\end{minted}\n\n\\begin{verbatim}\nval pchar: charToMatch: char * s: string -> Result<(char * string),string>\n\\end{verbatim}\n\\end{frame}\n\n\n\n\\begin{frame}[label={sec:org4f16965},fragile]{Parser 3 (2)}\n \\begin{minted}[bgcolor=mintedbg,frame=none,framesep=0pt,mathescape=true,fontsize=\\scriptsize,breaklines=true,linenos=false,numbersep=5pt,gobble=0]{fsharp}\nlet test31 = pchar('A',inputABC) \nlet test32 = pchar('A',inputZBC) \nlet test33 = pchar('Z',inputZBC)\n\\end{minted}\n\n\\begin{verbatim}\nval test31: Result<(char * string),string> = Ok ('A', \"BCD\")\nval test32: Result<(char * string),string> = Error \"Expecting 'A'. Got 'Z'\"\nval test33: Result<(char * string),string> = Ok ('Z', \"BCD\")\n\\end{verbatim}\n\\end{frame}\n\n\\begin{frame}[label={sec:orgf25d48e},fragile]{Parser 4 (use currying)}\n \\begin{minted}[bgcolor=mintedbg,frame=none,framesep=0pt,mathescape=true,fontsize=\\scriptsize,breaklines=true,linenos=false,numbersep=5pt,gobble=0]{fsharp}\nlet pchar charToMatch str = \n    if String.IsNullOrEmpty(str) then\n        Error \"No more input\"\n    else\n        let first = str.[0] \n        if first = charToMatch then\n            let remaining = str.[1..]\n            Ok (charToMatch,remaining)\n        else\n            let msg = sprintf \"Expecting '%c'. Got '%c'\" charToMatch first\n            Error msg\n\\end{minted}\n\n\\begin{verbatim}\nval pchar: charToMatch: char -> str: string -> Result<(char * string),string>\n\\end{verbatim}\n\\end{frame}\n\n\\begin{frame}[label={sec:org5144ddb},fragile]{Parser 4 (2)}\n \\begin{minted}[bgcolor=mintedbg,frame=none,framesep=0pt,mathescape=true,fontsize=\\scriptsize,breaklines=true,linenos=false,numbersep=5pt,gobble=0]{fsharp}\nlet parseA = pchar 'A'\nlet inputABC = \"ABC\"\nlet inputZBC = \"ZBC\"\nlet test41 = parseA inputABC\nlet test42 = parseA inputZBC\nlet parseZ = pchar 'Z' \nlet test43 = parseZ inputZBC\n\\end{minted}\n\n\\begin{verbatim}\nval parseA: (string -> Result<(char * string),string>)\nval inputABC: string = \"ABC\"\nval inputZBC: string = \"ZBC\"\nval test41: Result<(char * string),string> = Ok ('A', \"BC\")\nval test42: Result<(char * string),string> = Error \"Expecting 'A'. Got 'Z'\"\nval parseZ: (string -> Result<(char * string),string>)\nval test43: Result<(char * string),string> = Ok ('Z', \"BC\")\n\\end{verbatim}\n\\end{frame}\n\n\\begin{frame}[label={sec:orga7e56d5},fragile]{Parser 5 (type to wrap the parser function)}\n \\begin{minted}[bgcolor=mintedbg,frame=none,framesep=0pt,mathescape=true,fontsize=\\scriptsize,breaklines=true,linenos=false,numbersep=5pt,gobble=0]{fsharp}\ntype Parser<'T> =\n    | Parser of (string -> Result<'T , string>)\nlet pchar charToMatch = \n    let innerFn str =\n        if String.IsNullOrEmpty(str) then\n            Error \"No more input\"\n        else\n            let first = str.[0] \n            if first = charToMatch then\n                let remaining = str.[1..]\n                Ok (charToMatch, remaining)\n            else\n                let msg = sprintf \"Expecting '%c'. Got '%c'\" charToMatch first\n                Error msg\n    Parser innerFn\n\\end{minted}\n\n\\begin{verbatim}\ntype Parser<'T> = | Parser of (string -> Result<'T,string>)\nval pchar: charToMatch: char -> Parser<char * string>\n\\end{verbatim}\n\\end{frame}\n\n\\begin{frame}[label={sec:orgb7ce182},fragile]{Parser 5 (2)}\n \\begin{minted}[bgcolor=mintedbg,frame=none,framesep=0pt,mathescape=true,fontsize=\\scriptsize,breaklines=true,linenos=false,numbersep=5pt,gobble=0]{fsharp}\nlet parseA = pchar 'A'\nlet inputABC = \"ABC\"\nparseA inputABC\n\\end{minted}\n\n\\begin{verbatim}\nparseA inputABC;;\n  ^^^^^^\n\n...: error FS0003: This value is not a function and cannot be applied.\n\\end{verbatim}\n\\end{frame}\n\n\n\\begin{frame}[label={sec:org732898b},fragile]{Parser 5 (3)}\n \\begin{minted}[bgcolor=mintedbg,frame=none,framesep=0pt,mathescape=true,fontsize=\\scriptsize,breaklines=true,linenos=false,numbersep=5pt,gobble=0]{fsharp}\nlet run parser input = \n    let (Parser innerFn) = parser \n    innerFn input\nlet parseA = pchar 'A' \nlet inputABC = \"ABC\"\nlet test1 = run parseA inputABC\nlet inputZBC = \"ZBC\"\nlet test2 = run parseA inputZBC\n\\end{minted}\n\n\\begin{verbatim}\nval run: parser: Parser<'a> -> input: string -> Result<'a,string>\nval parseA: Parser<char * string> = Parser <fun:pchar@74-6>\nval inputABC: string = \"ABC\"\nval test1: Result<(char * string),string> = Ok ('A', \"BC\")\nval inputZBC: string = \"ZBC\"\nval test2: Result<(char * string),string> = Error \"Expecting 'A'. Got 'Z'\"\n\\end{verbatim}\n\\end{frame}\n\n\\section{Parser Kombinatoren }\n\\label{sec:org3348783}\n\\begin{frame}[label={sec:org7b54569}]{Understanding Parser Combinators}\n\\(\\leadsto\\) \\href{./5 Understanding parser combinators.pdf}{Understanding parser combinators} (Scott Wlashin)\n\\end{frame}\n\n\\begin{frame}[label={sec:orgb2e078e}]{FParsec Tutorial}\n\\begin{itemize}\n\\item \\href{http://www.quanttec.com/fparsec/tutorial.html\\#}{FParsec Tutorial}\n\\item \\href{http://www.quanttec.com/fparsec/users-guide/}{User’s Guide}\n\\item \\href{http://www.quanttec.com/fparsec/about/fparsec-vs-alternatives.html}{FParsec vs alternatives}\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}[label={sec:org84ac197},fragile]{Using FParsec (1)}\n \\begin{minted}[bgcolor=mintedbg,frame=none,framesep=0pt,mathescape=true,fontsize=\\scriptsize,breaklines=true,linenos=false,numbersep=5pt,gobble=0]{fsharp}\n#r \"../src/5/02-fparsec/lib/FParsecCS.dll\";; \n#r \"../src/5/02-fparsec/lib/FParsec.dll\";;\nopen FParsec\nlet test p str =\n    match run p str with\n    | Success(result, _, _)   -> printfn \"Success: %A\" result\n    | Failure(errorMsg, _, _) -> printfn \"Failure: %s\" errorMsg;;\ntest pfloat \"1.25\"\ntest pfloat \"1.25E 2\"\n\\end{minted}\n\n\\begin{verbatim}\nSuccess: 1.25                           \nFailure: Error in Ln: 1 Col: 6\n1.25E 2\n     ^\nExpecting: decimal digit\n\nval it: unit = ()\n\\end{verbatim}\n\\end{frame}\n\n\\begin{frame}[label={sec:org1359eae},fragile]{Using FParsec (2)}\n \\begin{minted}[bgcolor=mintedbg,frame=none,framesep=0pt,mathescape=true,fontsize=\\scriptsize,breaklines=true,linenos=false,numbersep=5pt,gobble=0]{fsharp}\nlet str s = pstring s\nlet floatBetweenBrackets:Parser<float, unit>  = str \"[\" >>. pfloat .>> str \"]\";;\n\ntest floatBetweenBrackets \"[1.0]\"\ntest floatBetweenBrackets \"[]\"\ntest floatBetweenBrackets \"[1.0]\"\n\\end{minted}\n\n\\begin{verbatim}\nSuccess: 1.0                            \nFailure: Error in Ln: 1 Col: 2\n[]\n ^\nExpecting: floating-point number\n\nSuccess: 1.0                            \nval it: unit = ()\n\\end{verbatim}\n\\end{frame}\n\n\\begin{frame}[label={sec:org9ef280b},fragile]{Using FParsec (3)}\n \\begin{minted}[bgcolor=mintedbg,frame=none,framesep=0pt,mathescape=true,fontsize=\\scriptsize,breaklines=true,linenos=false,numbersep=5pt,gobble=0]{fsharp}\nlet betweenStrings s1 s2 p = str s1 >>. p .>> str s2;;\nlet floatBetweenBrackets_:Parser<float, unit> = pfloat |> betweenStrings \"[\" \"]\";;\nlet floatBetweenDoubleBrackets_:Parser<float, unit> = pfloat |> betweenStrings \"[[\" \"]]\";;\ntest floatBetweenBrackets_ \"[1.0]\"\ntest floatBetweenDoubleBrackets_ \"[[1.0]]\"\nlet between_ pBegin pEnd p  = pBegin >>. p .>> pEnd;;\nlet betweenStrings_ s1 s2 p = p |> between_ (str s1) (str s2);;\ntest (many floatBetweenBrackets) \"\"\ntest (many floatBetweenBrackets) \"[1.0]\"\ntest (many floatBetweenBrackets) \"[2][3][4]\"\ntest (many floatBetweenBrackets) \"[1][2.0E]\"\n\\end{minted}\n\n\\begin{verbatim}\nSuccess: []                             \nSuccess: [1.0]                          \nSuccess: [2.0; 3.0; 4.0]                \nFailure: Error in Ln: 1 Col: 9\n[1][2.0E]\n        ^\nExpecting: decimal digit\n\nval it: unit = ()\n\\end{verbatim}\n\\end{frame}\n\n\\section{Ende }\n\\label{sec:orgd52857a}\n\\begin{frame}[label={sec:org00f27f4}]{Zusammenfassung (Kurs)}\n\\begin{itemize}\n\\item Wichtige Werkzeuge (git, dotnet, code)\n\\item Elementare Syntax\n\\item Funktionen, Pattern Matching, Discriminated Unions (DU)\n\\item Tuple, Record, List, Array, Seq\n\\item funktionale Operationen auf Listen (Tail-Rekursion)\n\\item funktionaler Umgang mit fehlenden Daten (Option)\n\\item funktionaler Umgang mit Fehlern (Result)\n\\item funktionales Design (statt Patterns: Funktionen \\& Verkettung)\n\\item funktionales Refactoring\n\\item funktionales Domain Modeling (DDD)\n\\item eigenschaftsbasiertes Testen (Property Based Testing) (cool!!)\n\\item funktionale Parser (Kombinatoren) (noch cooler!!)\n\\end{itemize}\n\\(\\leadsto\\) \\alert{\\alert{Was ist Funktionale Programmierung?}}\n\\end{frame}\n\n\\begin{frame}[label={sec:org36aba8b}]{Links}\n\\begin{itemize}\n\\item \\href{https://fsharp.org/}{fsharp.org}\n\\item \\href{https://docs.microsoft.com/de-de/dotnet/fsharp/}{docs.microsoft.com/../dotnet/fsharp}\n\\item \\href{https://sergeytihon.com/}{F\\# weekly}\n\\item \\href{https://fsharpforfunandprofit.com/}{fsharpforfunandprofit.com}\n\\item \\href{https://github.com/fsprojects/awesome-fsharp}{github.com/../awesome-fsharp}\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}[label={sec:org5528b6b}]{Ende}\n\\begin{itemize}\n\\item Wie geht es weiter?\n\\item \\href{https://exercism.io}{Exercism!}\n\\item Buchtipps\n\\begin{itemize}\n\\item \\href{https://pragprog.com/book/swdddf/domain-modeling-made-functional}{Domain Modeling Made Functional} (F\\#)\n\\item \\href{https://www.apress.com/gp/book/9781484239995}{Stylish F\\#} (F\\#)\n\\item \\href{https://www.cambridge.org/core/books/pearls-of-functional-algorithm-design/B0CF0AC5A205AF9491298684113B088F\\#}{Perls of Functional Algorithm Design} (Haskell)\n\\item \\href{https://www.cs.ox.ac.uk/publications/books/functional/}{Thinking Functional with Haskell} (Haskell)\n\\item \\href{http://www.paulgraham.com/onlisp.html}{On Lisp} (LISP)\n\\item \\href{http://www.iqool.de/FPMP.html}{Funktionale Programmierung und Metaprogrammierung} (LISP)\n\\item \\href{https://github.com/norvig/paip-lisp}{Paradigms of Artificial Intelligence Programming} (LISP)\n\\item \\href{https://adv-r.hadley.nz/}{Advanced R} (R)\n\\end{itemize}\n\\item Sprachen: \\href{https://www.r-project.org/}{R}, \\href{https://www.haskell.org/}{Haskell}, \\href{https://clojure.org/}{Clojure}, \\href{https://lisp-lang.org/}{Common Lisp}, \\href{https://elixir-lang.org/}{Elixir}, \\href{https://code.kx.com/q/}{q}\n\n\\item \\alert{\\alert{Have FUN!}}\n\\end{itemize}\n\\end{frame}\n\\end{document}", "meta": {"hexsha": "ad7d494a98a5d2d07f3a8e659f7048a7b0934957", "size": 18075, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "slides/slides-05.tex", "max_stars_repo_name": "kirchnergo/course.2022.hwr.fun", "max_stars_repo_head_hexsha": "47f14f58c50924fc794ce5e16aede83356d8ff02", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2022-03-04T12:08:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T13:43:19.000Z", "max_issues_repo_path": "slides/slides-05.tex", "max_issues_repo_name": "kirchnergo/course.2022.hwr.fun", "max_issues_repo_head_hexsha": "47f14f58c50924fc794ce5e16aede83356d8ff02", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slides/slides-05.tex", "max_forks_repo_name": "kirchnergo/course.2022.hwr.fun", "max_forks_repo_head_hexsha": "47f14f58c50924fc794ce5e16aede83356d8ff02", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-03-04T12:58:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T13:22:44.000Z", "avg_line_length": 35.0290697674, "max_line_length": 251, "alphanum_fraction": 0.7032365145, "num_tokens": 5935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.34161395453382754}}
{"text": "\\documentclass{article}\n\n\\usepackage{amssymb}\n\\usepackage{amsthm}\n\\usepackage[UKenglish]{babel}\n\\usepackage{enumitem}\n\\usepackage{fancyhdr}\n\\usepackage[margin=1in]{geometry}\n\\usepackage{graphicx}\n\\usepackage[utf8]{inputenc}\n\\usepackage{listings}\n\\usepackage{mathtools}\n\\usepackage{tikz-cd}\n\\usepackage{csquotes}\n\n\\newcommand{\\F}{\\mathbb{F}}\n\\newcommand{\\N}{\\mathbb{N}}\n\\newcommand{\\Z}{\\mathbb{Z}}\n\\newcommand{\\Q}{\\mathbb{Q}}\n\\newcommand{\\R}{\\mathbb{R}}\n\\newcommand{\\C}{\\mathbb{C}}\n\\newcommand{\\A}{\\mathbb{A}}\n\\renewcommand{\\P}{\\mathbb{P}}\n\n\\newcommand{\\val}[1]{\\left. #1 \\right\\rvert}\n\\newcommand{\\rb}[1]{\\left( #1 \\right)}\n\\renewcommand{\\sb}[1]{\\left[ #1 \\right]}\n\\newcommand{\\cb}[1]{\\left\\{ #1 \\right\\}}\n\\newcommand{\\ab}[1]{\\left\\langle #1 \\right\\rangle}\n\\newcommand{\\abs}[1]{\\left\\lvert #1 \\right\\rvert}\n\\newcommand{\\two}[2]{\\begin{pmatrix} #1 \\\\ #2 \\end{pmatrix}}\n\\newcommand{\\three}[3]{\\begin{pmatrix} #1 & #2 & #3 \\end{pmatrix}}\n\n\\theoremstyle{definition}\\newtheorem{definition}{Definition}[subsection]\n\\theoremstyle{definition}\\newtheorem{remark}[definition]{Remark}\n\\theoremstyle{definition}\\newtheorem*{example}{Example}\n\\theoremstyle{definition}\\newtheorem*{note}{Note}\n\\newtheorem{proposition}[definition]{Proposition}\n\\newtheorem{lemma}[definition]{Lemma}\n\\newtheorem{theorem}[definition]{Theorem}\n\\newtheorem{corollary}[definition]{Corollary}\n\n\\pagestyle{fancy}\n\\lhead{M3P8 Algebra III}\n\\rhead{Autumn 2018}\n\n\\title{M3P8 Algebra III}\n\\author{Lectured by Dr David Helm \\\\ Typeset by David Kurniadi Angdinata}\n\\date{Autumn 2018}\n\n\\setcounter{section}{-1}\n\n\\begin{document}\n\n\\maketitle\n\n\\vfill\n\n\\tableofcontents\n\n\\pagebreak\n\n\\marginpar{Lecture 1 \\\\ Friday \\\\ 05/10/18}\n\n\\section{Introduction}\n\nThis course is an introduction to ring theory. The topics covered will include ideals, factorisation, the theory of field extensions, finite fields, polynomial rings in several variables, and the theory of modules.\n\nIn addition to the lecture notes, the following will cover much of the material we will be studying.\n\n\\begin{enumerate}\n\\item M Artin, Algebra, 1991\n\\end{enumerate}\n\nRings are contexts in which it makes sense to add and multiply. For example, $ \\Z $, $ \\Q $, $ \\R $, $ \\C $, polynomials, functions $ \\cb{0, 1} \\to \\R $, and $ \\Z / n\\Z $ are rings. The goals of this course include\n\\begin{enumerate}\n\\item to unify arguments that apply in all of the above contexts, and\n\\item to study relationships between different rings.\n\\end{enumerate}\nThe applications of rings include\n\\begin{enumerate}\n\\item number theory, by studying extensions of $ \\Z $ in which particular Diophantine equations have solutions, for example $ n = x^2 + y^2 = \\rb{x + iy}\\rb{x - iy} $ to study solutions in $ \\Z\\cb{i} $ and pass to result about $ \\Z $,\n\\item algebraic geometry, by the study of zero sets of polynomials in several variables via rings of functions, and\n\\item topology, by cohomology classes of topological spaces.\n\\end{enumerate}\n\n\\section{Basic definitions and examples}\n\n\\subsection{Rings}\n\nRecall the definition of a commmutative ring.\n\n\\begin{definition}\nA \\textbf{commutative ring with identity} $ R $ is a set together with two binary operations $ +_R, \\cdot_R : R \\times R \\to R $, addition and multiplication, and two distinguished elements $ 0_R $ and $ 1_R $ such that the following holds.\n\\begin{enumerate}\n\\item The operation $ +_R $ makes $ R $ into an abelian group with identity $ 0_R $.\n\\begin{enumerate}\n\\item For all $ r \\in R $, $ 0_R +_R r = r +_R 0_R = 0_R $ (additive identity).\n\\item For all $ r, s, t \\in R $, $ \\rb{r +_R s} +_R t = r +_R \\rb{s +_R t} $  (associativity of $ +_R $).\n\\item For all $ r, s \\in R $, $ r +_R s = s +_R r $ (commutativity of $ +_R $).\n\\item For all $ r \\in R $, there exists $ -r \\in R $ such that $ r +_R \\rb{-r} = \\rb{-r} +_R r = 0_R $ (additive inverses).\n\\end{enumerate}\n\\item The operation $ \\cdot_R $ is associative and commutative with identity $ 1_R $.\n\\begin{enumerate}\n\\item For all $ r \\in R $, $ 1_R \\cdot_R r = r \\cdot_R 1_R = 1_R $ (multiplicative identity).\n\\item For all $ r, s, t \\in R $, $ \\rb{r \\cdot_R s} \\cdot_R t = r \\cdot_R \\rb{s \\cdot_R t} $ (associativity of $ \\cdot_R $).\n\\item For all $ r, s \\in R $, $ r \\cdot_R s = s \\cdot_R r $ (commutativity of $ \\cdot_R $).\n\\end{enumerate}\n\\item Multiplication distributes over addition.\n\\begin{enumerate}\n\\item For all $ r, s, t \\in R $, $ r \\cdot_R \\rb{s +_R t} = r \\cdot_R s +_R r \\cdot_R t $ and $ \\rb{s +_R t} \\cdot_R r = s \\cdot_R r +_R t \\cdot_R r $ (distributivity of $ \\cdot $ over $ + $).\n\\end{enumerate}\n\\end{enumerate}\n\\end{definition}\n\nThere is some redundancy here, of course. I have written things this way so that one obtains the definition of a noncommutative ring simply by removing the condition that multiplication is commutative. In this course, however, all rings will be commutative.\n\n\\begin{proposition}\nLet $ R $ be a ring. Then for all $ r \\in R $, $ r \\cdot_R 0_R = 0_R $.\n\\end{proposition}\n\n\\begin{proof}\n$ r \\cdot_R 0_R = r \\cdot_R \\rb{0_R +_R 0_R} = r \\cdot_R 0_R +_R r \\cdot_R 0_R $. Thus $ 0_R = -\\rb{r \\cdot_R 0_R} +_R \\rb{r \\cdot_R 0_R} = -\\rb{r \\cdot_R 0_R} +_R \\rb{r \\cdot_R 0_R +_R r \\cdot_R 0_R} = r \\cdot_R 0_R $.\n\\end{proof}\n\nSome people require $ 0_R \\ne 1_R $ in $ R $.\n\n\\begin{proposition}\nIf $ 0_R = 1_R $, then $ R = \\cb{0_R} $.\n\\end{proposition}\n\n\\begin{proof}\n$ 0_R = r \\cdot_R 0_R = r \\cdot_R 1_R = r $.\n\\end{proof}\n\nWhen it is clear from the context what ring we are working with, we will write $ 0_R $ and $ 1_R $ as $ 0 $ and $ 1 $, $ a +_R b $ as $ a + b $ and $ a \\cdot_R b $ as $ ab $.\n\n\\begin{definition}\nA ring $ R $ is a \\textbf{field} if $ R \\ne \\cb{0_R} $ and every nonzero element of $ R $ has a multiplicative inverse, that is for every $ r \\in R \\setminus \\cb{0_R} $ there exists $ r^{-1} \\in R $ such that $ rr^{-1} = r^{-1}r = 1_R $.\n\\end{definition}\n\nWe do not consider the zero ring $ \\cb{0_R} $ to be a field. We have seen many examples of rings at this point. The sets $ \\Z $, $ \\Q $, $ \\R $, $ \\C $ are all rings with their usual notion of addition and multiplication. All of them but $ \\Z $ are in fact fields. As another example, we have the ring $ \\Z / n\\Z $ of integers modulo $ n $. Let $ n \\in \\Z_{> 0} $, and recall that $ a $ and $ b $ are said to be congruent modulo $ n $ if $ a - b $ is divisible by $ n $. It is easy to check that this is an equivalence relation on $ \\Z $. Moreover, since any $ a \\in \\Z $ can uniquely be written as $ qn + r $ with $ q, r \\in \\Z $ and $ 0 \\le r < n $, the set $ \\cb{\\sb{0}_n, \\dots, \\sb{n - 1}_n} $ is a complete list of the equivalence classes under this relation, where $ \\sb{a}_n $ denotes the set of all integers congruent to $ a \\mod n $. We denote this $ n $-element set by $ \\Z / n\\Z $, and we can define addition and multiplication in $ \\Z / n\\Z $ by setting $ \\sb{a}_n + \\sb{b}_n = \\sb{a + b}_n $ and $ \\sb{a}_n\\sb{b}_n = \\sb{ab}_n $. This defines a ring structure on $ \\Z / n\\Z $ once one checks that it is well-defined. This is the first example of a general construction of the quotient of a ring by an ideal we will define later.\n\n\\marginpar{Lecture 2 \\\\ Monday \\\\ 08/10/18}\n\n\\subsection{Polynomial rings}\n\nA very important class of rings that we will study are the polynomial rings. Let $ R $ be any ring. Then we can form a new ring $ R\\sb{X} $, called the \\textbf{ring of polynomials in $ X $ with coefficients in $ R $}. Informally, a polynomial in $ R\\sb{X} $ is a finite sum of the form $ r_0 + \\dots + r_nX^n $ for some $ n \\in \\Z_{\\ge 0} $ and $ r_i \\in R $. If $ n > m $, we consider $ r_0 + \\dots + r_nX^n $ to represent the same polynomial of $ R\\sb{X} $ as $ s_0 + \\dots + s_mX^m $ if $ r_i = s_i $ for $ i \\le m $ and $ r_i = 0_R $ for $ i > m $. That is, you can pad out a polynomial with terms of the form $ 0_RX^i $ without changing it. From a formal standpoint, it is better to define a polynomial to be an infinite sum $ \\sum_{n = 0}^\\infty r_iX^i $ for $ r_i \\in R $ in which all but finitely many $ r_i $ are zero. This makes it easier to define addition and multiplication. The \\textbf{degree} of such an expression is the largest $ i $ such that $ r_i $ is nonzero. We add and multiply in $ R\\sb{X} $ just as we would any other polynomials, by\n$$ \\rb{\\sum_{i = 0}^\\infty r_iX^i} +_{R\\sb{X}} \\rb{\\sum_{i = 0}^\\infty s_iX^i} = \\sum_{i = 0}^\\infty \\rb{r_i +_R s_i} X^i, $$\n$$ \\rb{\\sum_{i = 0}^\\infty r_iX^i} \\cdot_{R\\sb{X}} \\rb{\\sum_{i = 0}^\\infty s_iX^i} = \\sum_{i = 0}^\\infty \\rb{\\sum_{j = 0}^i \\rb{r_j \\cdot_R s_{i - j}}} X^i. $$\nWhat about polynomial rings in more than one variable? Since the construction of polynomial rings takes an arbitrary ring as input, one can iterate it. Start with a ring $ R $, and consider first the ring $ R\\sb{X} $ and then the ring $ \\rb{R\\sb{X}}\\sb{Y} $. An polynomial of this has the form $ \\sum_{i = 0}^\\infty \\rb{\\sum_{j = 0}^\\infty r_{ij}X^j}Y^i $ for $ r_{ij} \\in R $. On the other hand, we can consider the ring $ \\rb{R\\sb{Y}}\\sb{X} $, whose polynomials have the form $ \\sum_{i = 0}^\\infty \\rb{\\sum_{j = 0}^\\infty s_{ij}Y^j}X^i $ for $ s_{ij} \\in R $. Alternatively, we could consider the ring $ R\\sb{X, Y} $ whose polynomials are formal expressions of the form $ \\sum_{i = 0}^\\infty \\rb{\\sum_{i = 0}^\\infty r_{ij}X^i}Y^j $ with only finitely many nonzero coefficients $ r_{ij} $ and define addition and multiplication in the usual way. It is not hard to see that all three approaches yield the same ring. There is a bijection between these expressions. We will therefore primarily use notation like $ R\\sb{X, Y} $ for polynomial rings in multiple variables, but we will occasionally need to know that this is the same as $ \\rb{R\\sb{X}}\\sb{Y} $ or $ \\rb{R\\sb{Y}}\\sb{X} $. The identification we have made here is an example of an isomorphism of rings, a notion we will make precise later.\n\n\\subsection{Subrings and extensions}\n\n\\begin{definition}\nLet $ R $ be a ring. A subset $ S $ of $ R $ is a \\textbf{subring} of $ R $ if\n\\begin{enumerate}\n\\item $ 0_R, 1_R, -1_R \\in S $.\n\\item $ S $ is closed under $ +_R $ and $ \\cdot_R $, so if $ r, s \\in S $, then so are $ r +_R s $ and $ r \\cdot_R s $.\n\\end{enumerate}\n\\end{definition}\n\nSubrings inherit the additive and multiplicative structures from the ring that contains them, and are thus themselves rings.\n\n\\begin{example}\n$ \\Z $ is a subring of $ \\R $, which is itself a subring of $ \\C $.\n\\end{example}\n\nIt is easy to see that the intersection of two subrings of $ R $, or even an arbitrary collection of subrings of $ R $, is also a subring of $ R $.\n\n\\begin{definition}\nLet $ S \\subseteq R $ be a subring of a ring $ R $, and let $ \\alpha $ be an element of $ R $. We can then form a subring $ S\\sb{\\alpha} $ of $ R $, called the \\textbf{subring of $ R $ generated by $ \\alpha $ over $ S $}, consisting of all elements of $ R $ that can be expressed as $ r_0 + \\dots + r_n\\alpha^n $ for some $ n \\in \\Z^* $, and $ r_i \\in S $.\n\\end{definition}\n\nThis operation is known as \\textbf{adjoining} the element $ \\alpha $ to the ring $ S $. An alternative way of defining the ring $ S\\sb{\\alpha} $ is to note that it is the smallest subring of $ R $ containing $ S $ and $ \\alpha $. In one direction, any such subring contains every expression of the form $ r_0 + \\dots + r_n\\alpha^n $, with $ r_i \\in S $, so any subring of $ R $ containing $ S $ and $ \\alpha $ contains $ S\\sb{\\alpha} $. One can thus construct $ S\\sb{\\alpha} $ as the intersection of every subring of $ R $ containing $ S $ and $ \\alpha $. Since the intersection of any collection of subrings of $ R $ is a subring of $ R $ it is clear that this intersection is equal to $ S\\sb{\\alpha} $ as defined above.\n\n\\begin{example}\nLet $ i $ denote a square root of $ -1 $ in $ \\C $. $ \\Z \\subseteq \\C $ and $ i $ form $ \\Z\\sb{i} $. Note $ -1 = i^2 = i^6 = i + i^3 + i^{10} $.\n\\end{example}\n\n\\begin{proposition}\nEvery element of $ \\Z\\sb{i} $ can be uniquely expressed as $ a + bi $ for $ a, b \\in \\Z $.\n\\end{proposition}\n\n\\begin{example}\nGiven $ \\sum_{n = 0}^\\infty a_ni^n $ with only finitely many $ a_n $ nonzero, set $ a = a_0 - a_2 + \\dots $ and $ b = a_1 - a_3 + \\dots $. Then $ \\sum_{n = 0}^\\infty a_ni^n = a + bi $. For uniqueness, if $ a + bi = c + di $ in $ \\C $ for $ a, b, c, d \\in \\Z $, then $ a = c $ or $ b = d $.\n\\end{example}\n\nIf $ \\alpha $ is more complicated then the elements of $ R\\sb{\\alpha} $ may well be harder to describe.\n\n\\begin{example}\nIf $ \\alpha $ is the real cube root of $ 2 $, then every element of $ \\Z\\sb{\\alpha} $ can be uniquely expressed as $ a + b\\alpha + c\\alpha^2 $ for $ a, b, c \\in \\Z $.\n\\end{example}\n\n\\begin{example}\nIn $ \\Z\\sb{\\pi} $, any element has a unique expression in the form $ \\sum_{n = 0}^\\infty a_n\\pi^n $ for all but finitely many $ a_n $ are zero. Suppose $ \\sum_{n = 0}^\\infty a_n\\pi^n = \\sum_{n = 0}^\\infty b_n\\pi^n $, then $ 0 = \\sum_{n = 0}^\\infty \\rb{a_n - b_n}\\pi^n $. Since $ \\pi $ is transcendental, this polynomial must be zero. Thus each $ a_n = b_n $.\n\\end{example}\n\n\\begin{example}\nThe elements of $ \\Z\\sb{\\tfrac{1}{2}} $ can be expressed uniquely as $ a / b $, where $ b $ is a power of $ 2 $ and $ a $ is odd unless $ b = 1 $.\n\\end{example}\n\n\\begin{example}\nLet $ \\alpha $ be a root of $ x^2 - \\tfrac{1}{2}x + 1 $. Then $ \\alpha^2 \\in \\Z\\sb{\\alpha} $ and $ \\alpha^2 = \\alpha / 2 - 1 $. Can show that every element of $ \\Z\\sb{\\alpha} $ can be expressed as $ a + b\\alpha $ for $ a, b \\in \\Z\\sb{\\tfrac{1}{2}} $, but not every $ a + b\\alpha $ arises $ a, b \\in \\Z\\sb{\\tfrac{1}{2}} $.\n\\end{example}\n\n\\marginpar{Lecture 3 \\\\ Wednesday \\\\ 10/10/18}\n\n\\subsection{Integral domains and rings of fractions}\n\n\\begin{definition}\nA \\textbf{zero divisor} in a ring $ R $ is a nonzero element $ r $ of $ R $ such that there exists a nonzero $ s \\in R $ with $ rs = 0 $. A ring $ R $ in which there are no zero divisors is called an \\textbf{integral domain}.\n\\end{definition}\n\n\\begin{example}\n$ \\Z $ is an integral domain and any subring of a field is an integral domain, but $ \\Z / 6\\Z $ is not an integral domain, as $ \\sb{2}\\sb{3} $ is zero modulo $ 6 $ even though neither $ \\sb{2} $ nor $ \\sb{3} $ is zero modulo $ 6 $.\n\\end{example}\n\nIf $ R $ is an integral domain, then we can form the field of fractions of $ R $ in analogy to the way we build $ \\Q $ from $ \\Z $.\n\n\\begin{definition}\nLet $ R $ be an integral domain. The \\textbf{field of fractions} $ K\\rb{R} $ is the set of equivalence classes of expressions of the form $ a / b $ for $ a, b \\in R $, $ b \\ne 0 $, where $ a / b \\sim a' / b' $ if and only if $ ab' = a'b $. We add and multiply elements of $ K\\rb{R} $ just as we do for fractions, by\n$$ \\dfrac{a}{b} + \\dfrac{a'}{b'} = \\dfrac{ab' + a'b}{bb'}, \\qquad \\dfrac{a}{b} \\cdot \\dfrac{a'}{b'} = \\dfrac{aa'}{bb'}, \\qquad 0_{K\\rb{R}} = \\dfrac{0_R}{1_R}, \\qquad 1_{K\\rb{R}} = \\dfrac{1_R}{1_R}. $$\nIf $ a \\ne 0 $ in $ R $, then $ b / a \\in K\\rb{R} $, so $ \\rb{a / b} \\cdot \\rb{b / a} = ab / ba \\sim 1 / 1 $.\n\\end{definition}\n\nThen $ K\\rb{R} $ is a field, and it contains $ R $ in a natural way as a subring if we identify $ r $ with $ r / 1_R \\in K\\rb{R} $. The field $ K\\rb{R} $ is in some sense the smallest field containing $ R $ as a subring. When we talk about homomorphisms and isomorphisms, we will be able to state this more precisely. More generally, a subset $ S $ of $ R $ is a \\textbf{multiplicative system} if $ 1 \\in S $ and $ 0 \\notin S $, and $ S $ is closed under multiplication, that is if $ a, b $ are in $ S $ then so is $ ab $. For any integral domain $ R $ and any multiplicative system $ S $, we can define $ S^{-1}R \\subseteq K\\rb{R} $ consisting of all fractions of the form $ a / b $ with $ b \\in S $. It is easy to see that his is closed under addition and multiplication, and defines a ring in between $ R $ and $ K\\rb{R} $.\n\n\\begin{example}\nIf $ R = \\Z $ and $ S $ is the set of powers of $ 2 $, then $ S^{-1}R = \\Z\\sb{\\tfrac{1}{2}} $. On the other hand, if $ S $ is the set of odd integers, then $ S^{-1}R $ is the set of all rational numbers of the form $ a / b $ with $ b $ odd.\n\\end{example}\n\nIn general $ S^{-1}R $ is the smallest subring of $ K\\rb{R} $ containing $ R $ in which every element of $ S $ has a multiplicative inverse, that is $ b^{-1} \\in S $ for all $ b \\in S $. The process of obtaining $ S^{-1}R $ from $ R $ is called \\textbf{localisation} and is an extremely powerful tool. One can even make sense of it when $ R $ is not an integral domain, but one has to be more careful. The equivalence relation on fractions is tricker, for example. We will not discuss this in this course but it will be quite useful in future courses.\n\n\\section{Homomorphisms, ideals, and quotients}\n\n\\subsection{Homomorphisms}\n\nLet $ R $ and $ S $ be rings. A ring homomorphism from $ R $ to $ S $ is, roughly, a way of interpreting elements of $ R $ as elements of $ S $, in a way that is compatible with the addition and multiplication laws on $ R $ and $ S $. More precisely is the following.\n\n\\begin{definition}\nA function $ f : R \\to S $ is a \\textbf{ring homomorphism} if\n\\begin{enumerate}\n\\item $ f\\rb{1_R} = 1_S $,\n\\item for all $ r, r' \\in R $, $ f\\rb{r +_R r'} = f\\rb{r} +_S f\\rb{r'} $, and\n\\item for all $ r, r' \\in R $, $ f\\rb{r \\cdot_R r'} = f\\rb{r} \\cdot_S f\\rb{r'} $.\n\\end{enumerate}\n\\end{definition}\n\n\\begin{note}\nIf $ f $ is a homomorphism then $ f\\rb{0_R} = f\\rb{0_R + 0_R} = f\\rb{0_R} +_S f\\rb{0_R} $ gives $ f\\rb{0_R} = 0_S $. Thus we do not need to require this as an axiom. On the other hand we do need to require $ f\\rb{1_R} = 1_S $. For certain $ R, S $ one can construct examples of maps $ f : R \\to S $ that satisfy properties $ 2 $ and $ 3 $ of the definition without satisfying property $ 1 $.\n\\end{note}\n\n\\begin{example}\nIf $ R $ is a subring of $ S $, then the inclusion of $ R $ into $ S $, such as $ \\Z \\subset \\Q \\subset \\R \\subset \\C $, is a homomorphism. This is just a fancy way of saying that the addition and multiplication on $ R $ are induced from the corresponding operations on $ S $.\n\\end{example}\n\n\\begin{example}\nThe composition of two homomorphisms is a homomorphism, as is easily checked from the definitions.\n\\end{example}\n\n\\begin{example}\nThe map $ \\Z \\to \\Z / n\\Z $ that takes an integer $ m $ into its congruence class modulo $ n $ is also a homomorphism. In fact, this is a special case of the following construction.\n\\end{example}\n\n\\begin{proposition}\nLet $ R $ be any ring. Then there is a unique ring homomorphism $ f : \\Z \\to R $ such that\n$$ f\\rb{n} = \\begin{cases} 1_R + \\dots + 1_R & n > 0 \\\\ -\\rb{1_R + \\dots + 1_R} & n < 0 \\\\ 0_R & n = 0 \\end{cases}. $$\n\\end{proposition}\n\n\\begin{proof}\nLet $ f : \\Z \\to R $ be a homomorphism. Then, directly from the definition, we have $ f\\rb{0} = 0_R $ and $ f\\rb{1} = 1_R $. In particular for all $ n > 0 $, $ f\\rb{n} = f\\rb{1 + \\dots + 1} = 1_R +_R \\dots +_R 1_R $, where there are $ n $ copies of $ 1_R $ in the sum. Moreover, $ 0_R = f\\rb{n + \\rb{-n}} = f\\rb{n} + f\\rb{-n} $, so $ f\\rb{-n} = -\\rb{1_R +_R \\dots +_R 1_R} $. Thus $ f\\rb{n} $ is determined, for all $ n $, completely by the fact that $ f $ is a homomorphism. In the converse direction, it is not hard to check that the map defined above is in fact a homomorphism.\n\\end{proof}\n\nThus, for any ring $ R $, we can regard an integer as an element of $ R $ via this homomorphism.\n\n\\begin{definition}\nA bijective homomorphism $ f : R \\to S $ is called an \\textbf{isomorphism}. Write $ S \\cong R $ for $ S $ is isomorphic to $ R $.\n\\end{definition}\n\nIn this case one verifies easily that the inverse map $ f^{-1} : S \\to R $ is also a bijective homomorphism.\n\n\\subsection{Evaluation homomorphisms}\n\nLet $ R $ be a ring, and consider the ring $ R\\sb{X} $ of polynomials in $ X $ with coefficients in $ R $. If $ s $ is an element of $ R $, then we can define a homomorphism $ R\\sb{X} \\to R $ by \\textbf{evaluation at $ s $}. More precisely, given an element of $ R\\sb{X} $ of the form $ P\\rb{X} = r_0 + \\dots + r_nX^n $ for some $ n $ and $ r_i \\in R $. Then $ P\\rb{s} $ for $ s \\in R $ is defined to be $ P\\rb{s} = r_0 + \\dots + r_ns^n \\in R $. Consider the map $ \\phi_s : R\\sb{X} \\to R $ that sends $ \\phi_s\\rb{P} $ to $ P\\rb{s} $. In effect, it substitutes $ s $ for $ X $. It is easy to check that this is in fact a ring homomorphism. More generally, if $ R $ and $ S $ are rings and $ f : R \\to S $ is a homomorphism, and $ s $ is an element of $ S $, then we can define a map\n$$ \\phi_{s, f} : R\\sb{X} \\to S, $$\nby setting\n$$ \\phi_{s, f}\\rb{r_0 + \\dots + r_nX^n} = f\\rb{r_0} + \\dots + f\\rb{r_n}s^n. $$\nThat is, by appling $ f $ to the coefficients and substituting $ s $ for $ X $. Again, this is clearly a homomorphism. The evaluation homomorphisms $ \\phi_{s, f} $ are a fundamental property of polynomial rings. In some sense, they are the reason polynomial rings are worth studying. In fact, the ring $ R\\sb{X} $ is uniquely characterised by the fact that homomorphisms from $ R\\sb{X} $ to $ S $ are in bijection with pairs $ \\rb{s, f} $, where $ f : R \\to S $ is a homomorphism and $ s $ is an element of $ S $.\n\n\\subsection{Images, kernels, and ideals}\n\n\\begin{definition}\nLet $ f : R \\to S $ be a homomorphism. The \\textbf{image} of $ f $ is $ Im\\rb{f} = \\cb{f\\rb{r} \\mid r \\in R} \\subseteq S $. The \\textbf{kernel} of $ f $ is $ Ker\\rb{f} = \\cb{r \\in R \\mid f\\rb{r} = 0} \\subseteq R $.\n\\end{definition}\n\nThe image of a homomorphism $ f : R \\to S $ is easily seen to be a subring of $ S $.\n\n\\begin{example}\nIf $ R $ is a subring of $ S $, $ f : R \\to S $ is the inclusion and $ s $ lies in $ S $, then the image of the map $ \\phi_{s, f} : R\\sb{X} \\to S $ is precisely the subring $ R\\sb{s} $ of $ S $.\n\\end{example}\n\nBy contrast, the kernel of a homomorphism $ f $ is almost never a subring of $ R $. For instance, subrings contain the identity. However, it is an ideal of $ R $.\n\n\\marginpar{Lecture 4 \\\\ Friday \\\\ 12/10/18}\n\n\\begin{definition}\nA nonempty subset $ I $ of $ R $ is an \\textbf{ideal} of $ R $ if $ I $ is closed under addition, that is for all $ i, j \\in I $, $ i + j \\in I $, and for all $ i \\in I $, $ r \\in R $, $ ri \\in I $.\n\\end{definition}\n\nThen one can verify, directly from the definition, that the kernel of any homomorphism $ f : R \\to S $ is an ideal of $ R $.\n\n\\begin{note}\nAny ideal of $ R $ contains $ 0_R $, and conversely the subset $ \\cb{0_R} $ of $ R $ is an ideal, called the \\textbf{zero ideal}. A homomorphism $ f : R \\to S $ is injective if and only if its kernel is the zero ideal. Forward direction is easy. Conversely, if $ f\\rb{x} = f\\rb{y} $, $ f\\rb{x - y} = 0 $, so $ x - y \\in Ker\\rb{f} $. If $ Ker\\rb{f} = \\cb{0} $, $ x = y $.\n\\end{note}\n\nThe kernel of the homomorphism $ \\Z \\to R $ is either the zero ideal, or the ideal of multiples of $ n $ in $ \\Z $ for some positive $ n $. We say that $ R $ has characteristic zero or characteristic $ n $, respectively. If not zero, the \\textbf{characteristic} of $ R $ is the smallest $ n $ such that the sum of $ n $ copies of $ 1_R $ is equal to zero.\n\n\\subsection{Ideals: examples and basic operations}\n\nIf $ r $ is an element of $ R $, then any ideal containing $ R $ contains any multiple $ sr $ of $ R $, for any $ r $ in $ S $. Conversely, one checks easily that the set $ \\cb{sr \\mid s \\in R} $ is an ideal of $ R $. It is known as the \\textbf{ideal of $ R $ generated by $ r $}, and denoted $ \\ab{r} $. An ideal generated by one element in this way is called a \\textbf{principal ideal}.\n\n\\begin{note}\nThe ideal generated by $ 1_R $, or more generally by any element of $ R $ with a multiplicative inverse, is all of $ R $. This ideal is called the \\textbf{unit ideal} of $ R $.\n\\end{note}\n\n\\begin{proposition}\n$ R $ is a \\textbf{field} if and only if the only ideals of $ R $ are the zero ideal $ \\cb{0} $ and the unit ideal $ R $.\n\\end{proposition}\n\n\\begin{proof}\nIf $ R $ is a field, let $ I \\subseteq R $ be a nonzero ideal. There exists $ r \\in I \\ne  0 $. Then for all $ s \\in R $, $ \\rb{sr^{-1}}\\rb{r} \\in I $, so $ s \\in I $ for all $ s \\in R $. Conversely, if $ R $ has only zero ideal, unit ideal, let $ r \\in R \\ne 0 $, let $ I \\cb{sr \\mid s \\in R} $. This is an ideal not zero ideal, so it is all of $ R $. In particular, $ 1 \\in I $, so there exists $ s \\in R $ such that $ sr = 1 $.\n\\end{proof}\n\nMore generally is the following.\n\n\\begin{definition}\nIf $ S $ is a subset of elements of $ R $, then any ideal containing $ S $ consists of all elements of $ R $ the form $ r_0s_0 + \\dots + r_ns_n $ for some $ n \\in \\Z_{\\ge 0} $, $ r_i \\in R $, and $ s_i \\in S $. The intersection of all these ideals is an ideal of $ R $, known as the \\textbf{ideal of $ R $ generated by $ S $}, and denoted $ \\ab{S} $. It is also the smallest ideal of $ R $ containing $ S $.\n\\end{definition}\n\nIf $ S $ has one element, $ \\ab{S} $ is a principal ideal. We will show soon that any ideal of $ \\Z $ is a principal ideal, as is any ideal of the ring $ k\\sb{X} $ for any field $ k $. On the other hand, there are rings in which not every ideal is principal.\n\n\\begin{example}\nThe ideal $ \\ab{X, Y} $ of $ k\\sb{X, Y} $ is not a principal ideal.\n\\end{example}\n\nGiven ideals $ I $ and $ J $ there are several ways to create new ideals.\n\\begin{enumerate}\n\\item If $ I, J $ are ideals, then the intersection $ I \\cap J $ is an ideal. If $ I $ and $ J $ are given by generators, it might be hard to find generators for the intersection. Certainly it is not enough to intersect the generating sets.\n\\item The union of ideals is not usually an ideal. Taking $ R = \\Z $, $ \\ab{3} \\cup \\ab{5} $ contains $ 3, 5 $ but not $ 3 + 5 $.\n\\item If $ I, J $ are ideals, then the sum $ I + J $ is an ideal, which are all expressions of the form $ i + j $ for $ i \\in I $, $ j \\in J $. It is the smallest ideal containing both $ I $ and $ J $, and also the ideal generated by $ I \\cup J $.\n\\item If $ I, J $ are ideals, the product $ I \\cdot J $ or $ IJ $ is the ideal generated by elements of the form $ ij $ for $ i \\in I $, $ j \\in J $. This may be strictly larger than the set of such products.\n\\end{enumerate}\n\n\\begin{example}\nConsider the product of the ideals $ I = \\ab{X, Y} $ and $ J = \\ab{Z, W} $ in $ R = k\\sb{X, Y, Z, W} $ for $ k $ a field. The product $ IJ = \\ab{XZ, XW, YZ, YW} $ contains $ XZ + YW $, but the latter is not a product of an element in $ I $ with an element in $ J $.\n\\end{example}\n\n\\begin{note}\nLet $ I, J $ be general ideals. The product of $ I $ and $ J $ is always contained in the intersection of $ I $ and $ J $, but the two need not be equal, even in simple rings like $ \\Z $. $ \\ab{3} \\cdot \\ab{3} = \\ab{9} \\subseteq \\Z $ and $ \\ab{3} \\cap \\ab{3} = \\ab{3} $.\n\\end{note}\n\n\\subsection{Quotients}\n\nLet $ R $ be a ring and let $ I $ be an ideal of $ R $. If $ x, y $ are elements of $ R $, we say that $ x $ is \\textbf{congruent to $ y $ modulo $ I $} if $ x - y $ is in $ I $. This is an equivalence relation on $ R $. We denote the equivalence class of $ r $ by $ r + I $, or the alternative notations $ \\sb{r}_I $, $ \\bar{r} $. It is the set $ \\cb{r + s \\mid s \\in I} $. Let $ R / I $ denote the set of equivalence classes on $ R $ modulo $ I $. This set has the natural structure of a ring. The additive and multiplicative identities are $ 0_R + I $ and $ 1_R + I $, respectively, and addition and multiplication are defined by $ \\rb{r + I} + \\rb{s + I} = \\rb{r + s} + I $ and $ \\rb{r + I} \\cdot \\rb{s + I} = \\rb{rs + I} $ respectively. One has to check that these are well-defined, but this is not difficult. The ring $ R / I $ is called the \\textbf{quotient of $ R $ by the ideal $ I $}.\n\n\\begin{example}\nIf $ R = \\Z $ and $ I $ is the ideal generated by $ n $, then $ R / I $ is the ring $ \\Z / n\\Z $ that we have already seen.\n\\end{example}\n\n\\begin{note}\nThere is a \\textbf{reduction modulo $ I $} or \\textbf{natural quotient} homomorphism $ R \\to R / I $ defined by taking $ r $ to $ r + I $. This homomorphism is surjective with kernel $ I $.\n\\end{note}\n\nWe then have the following.\n\n\\begin{proposition}[Universal property of the quotient]\nLet $ I \\subseteq R $ be an ideal and let $ f : R \\to S $ be a homomorphism, and suppose that the kernel of $ f $ contains $ I $. Then there is a unique homomorphism $ \\bar{f} : R / I \\to S $ such that for all $ r \\in R $, $ \\bar{f}\\rb{r + I} = f\\rb{r} $.\n\\end{proposition}\n\n\\begin{proof}\n$ \\bar{f} $ is necessarily unique, as every element of $ R / I $ has the form $ r + I $ for some $ r $. It thus suffices to show that it is well-defined and gives a homomorphism. If $ r + I = r' + I $, then $ r - r' \\in I $, so $ f\\rb{r - r'} = 0 $ gives $ f\\rb{r} = f\\rb{r'} $. Thus $ \\bar{f} $ is well-defined. Checking that it is a homomorphism follows from $ f $ is a homomorphism.\n\\end{proof}\n\n\\begin{note}\nThe kernel of $ \\bar{f} $ in the above proposition is just the image of the kernel of $ f $ in $ R / I $. If the kernel of $ f $ is equal to $ I $, this image is the zero ideal and $ \\bar{f} $ is injective. In particular, any homomorphism of $ R $ to $ S $ can be thought of as an isomorphism of some quotient of $ R $ with a subring of $ S $.\n\\end{note}\n\n\\begin{example}\nLet $ R \\subseteq S $ be a subring, $ \\alpha \\in S $, and $ \\iota : R \\to S $ be the inclusion map. Recall that we have an evaluation at $ \\alpha $ by $ \\phi_{\\iota, \\alpha} : R\\sb{X} \\to S $. Image of this is $ R\\sb{\\alpha} $. Let $ I = Ker\\rb{\\phi_{\\iota, \\alpha}} $. Then $ \\phi_{\\iota, \\alpha} $ descends to a map $ \\phi_{\\iota, \\alpha} : R\\sb{\\alpha} / I \\to S $ that is injective with image $ R\\sb{\\alpha} $. So $ R\\sb{\\alpha} $ is isomorphic to a quotient of $ R\\sb{X} $.\n\\end{example}\n\n\\marginpar{Lecture 5 \\\\ Monday \\\\ 15/10/18}\n\n\\subsection{Prime and maximal ideals}\n\n\\begin{definition}\nAn ideal $ I $ of $ R $ is \\textbf{prime} if the quotient $ R / I $ is an integral domain. It is \\textbf{maximal} if $ R / I $ is a field.\n\\end{definition}\n\n\\begin{note}\nAs fields are integral domains, every maximal ideal is prime. The converse need not hold, of course. The zero ideal in $ \\Z $ is prime but not maximal.\n\\end{note}\n\n\\begin{proposition}\nAn ideal $ I $ is prime if and only if for every pair of elements $ s, r $ in $ R $ such that $ rs $ is in $ I $, either $ r $ is in $ I $ or $ s $ is in $ I $.\n\\end{proposition}\n\n\\begin{proof}\nThis is just a restatement of the definition. $ R / I $ integral domain if and only if for all whenever two elements $ r + I $ and $ s + I $ in $ R / I $ satisfy $ \\rb{r + I}\\rb{s + I} = 0 + I $ in $ R / I $, either $ r + I = 0 + I $ or $ s + I = 0 + I $ in $ R / I $. This is the same as saying $ rs $ lies in $ I $ if and only if either $ r $ or $ s $ lies in $ I $.\n\\end{proof}\n\n\\begin{proposition}\nAn ideal $ I $ is maximal if and only if the only ideals of $ R $ containing $ I $ are $ I $ and the unit ideal $ R $.\n\\end{proposition}\n\nThis justifies the name maximal for such ideals.\n\n\\begin{proof}\nFirst suppose that $ R / I $ is a field. Recall that $ R / I $ is a field if and only if only ideals of $ R / I $ are $ \\cb{0} $ and $ R / I $. Given an ideal $ J \\subseteq R / I $, let $ \\widetilde{J} $ be the preimage of $ J $ under $ R \\to R / I $. $ \\widetilde{J} $ is an ideal containing $ I $ and contained in $ R $. Then $ J $ is either the zero ideal of $ R / I $, in which case $ \\widetilde{J} $ is contained in, and thus equal to, $ I $, or $ J $ is all of $ R / I $, in which case $ \\widetilde{J} $ contains $ I $ and an element of $ 1_R + I $, so $ \\widetilde{J} $ contains $ 1_R $ and is thus the unit ideal of $ R $. Conversely, if the only ideals of $ R $ containing $ I $ are $ I $ and the unit ideal, then for any $ r $ in $ R \\setminus I $, the ideal of $ R $ generated by $ I $ and $ r $ contains $ 1_R $. We can thus write $ 1_R = rs + i $, where $ i \\in I $ and $ s \\in R $. This means that $ s + I $ and $ r + I $ are multiplicative inverses of each other in $ R / I $, so $ R / I $ is a field.\n\\end{proof}\n\n\\section{Factorisation}\n\nIn these notes $ R $ always denotes an integral domain.\n\n\\subsection{Divisibility, units, associates, and irreducibles}\n\n\\begin{definition}\nLet $ r, s $ be elements of $ R $. We say $ r $ \\textbf{divides} $ s $, written $ r \\mid s $, if there exists $ r' \\in R $ with $ rr' = s $, or, equivalently, $ s $ lies in the principal ideal $ \\ab{r} $ generated by $ r $. An element $ r $ that divides $ 1_R $ is called a \\textbf{unit} of $ R $, or, equivalently, $ \\ab{r} = R $.\n\\end{definition}\n\nThe set of units in $ R $ forms a group under multiplication denoted $ R^* $. For any element $ r \\in R $ and any unit $ u $ of $ R $, both $ u $ and $ ur $ divide $ r $.\n\n\\begin{definition}\nThe set of elements of $ R $ of the form $ ur $, with $ r \\in R^* $ are called \\textbf{associates} of $ R $, that is $ r, r' $ are associates if $ r = ur' $ for a unit $ u \\in R^* $.\n\\end{definition}\n\nThis implies $ r \\mid r' $, that is there exists $ u' $ with $ u'u = 1 $ and $ u'r = r' $.\n\n\\begin{note}\nThe principal ideals $ \\ab{r} $ and $ \\ab{r'} $ are equal if and only if $ r $ and $ r' $ are associates.\n\\end{note}\n\n\\begin{definition}\nA nonzero element $ r $ of $ R $ is called \\textbf{irreducible} if $ r $ is not a unit and the only elements of $ R $ that divide $ r $ are the units and the associates of $ r $.\n\\end{definition}\n\n\\subsection{Unique factorisation domains}\n\nAn interesting question is when elements of rings admit unique factorisations into irreducibles. To that end we define the following.\n\n\\begin{definition}\nA \\textbf{unique factorisation domain} (UFD) is a ring $ R $ in which\n\\begin{enumerate}\n\\item every nonunit, nonzero element $ r \\in R $ admits a factorisation as a finite product of irreducibles in $ R $, and\n\\item if $ r = p_1 \\dots p_n = q_1 \\dots q_m \\in R $ are two factorisations of $ r $ as products of irreducibles $ p_i, q_i $, then $ n = m $ and, up to permuting the $ q_i $, each $ q_i $ is an associate of $ p_i $.\n\\end{enumerate}\n\\end{definition}\n\n\\begin{example}\nBoth conditions can fail.\n\\begin{enumerate}\n\\item There are certainly domains in which $ 1 $ can fail, although they are somewhat exotic. One example is to take the rational polynomial ring $ R = \\C\\sb{X^\\Q} $ with coefficients in $ \\C $, whose entries are finite formal sums $ \\sum_{i = 0}^N a_iX^{n_i} $ where the $ a_i $ are in $ \\C $ and the $ n_i $ are nonnegative rational numbers $ \\Q_{\\ge 0} $. Any element of $ R $ is a polynomial in $ X^{1 / n} $ for some $ n $. The element $ X $ of this ring is not a unit, and also not a finite product of irreducibles. In $ \\C\\sb{X^{1 / n}} $, $ X $ factors as $ \\rb{X^{1 / n}}^n $. $ X $ has no factorisation into irreducibles in $ R $. We will show later that a very mild finiteness condition on a domain $ R $, the condition that $ R $ is Noetherian, actually guarantees that $ 1 $ holds.\n\\item Even if $ 1 $ holds, $ 2 $ often fails. The classic example of this is $ R = \\Z\\sb{\\sqrt{-5}} $, in which $ 2, 3, 1 + \\sqrt{-5}, 1 - \\sqrt{-5} $ are all irreducibles, none are associates of each other, yet $ \\rb{2}\\rb{3} = \\rb{1 + \\sqrt{-5}}\\rb{1 - \\sqrt{-5}} $.\n\\end{enumerate}\n\\end{example}\n\nAnother way to interpret condition $ 2 $ is as follows.\n\n\\begin{definition}\nWe say an element $ r $ of $ R $ is \\textbf{prime} if the principal ideal $ \\ab{r} $ of $ R $ is a prime ideal. In other words, for any $ s, s' $ in $ R $, if $ r $ divides $ ss' $, then $ r \\mid s $ or $ r \\mid s' $.\n\\end{definition}\n\n\\begin{lemma}\nPrime elements are irreducible.\n\\end{lemma}\n\n\\begin{proof}\nIf $ r $ is prime and $ s $ divides $ r $, we can write $ r = ss' $. Then since $ r $ divides $ ss' $ we have that either $ r $ divides $ s $, in which case $ rs'' = s $, then $ ss's'' = s $ and $ s's'' = 1 $, so $ r $ is an associate of $ s $, or $ r $ divides $ s' $, in which case $ s' = rs'' $, then $ r = srs'' $ and $ ss'' = 1 $, so $ r $ is an associate of $ s' $ and $ s $ is a unit.\n\\end{proof}\n\nThe converse is not necessarily true, but we have the following observation as a criteria for $ R $ to be a UFD.\n\n\\begin{proposition}\nLet $ R $ be a domain in which condition $ 1 $ holds. Then condition $ 2 $ above holds for $ R $ if and only if every irreducible element of $ R $ is prime.\n\\end{proposition}\n\n\\begin{proof}\nFirst suppose condition $ 2 $ holds, and let $ r $ be an irreducible element of $ R $. If $ r $ divides $ ab $, we can write $ rs = ab $ for some $ s \\in R $. Expanding out $ s, a, b $ as products of irreducibles we see that $ r $ is an associate of some irreducible dividing $ a $ or $ b $, so $ r $ is prime. Conversely, if every irreducible element of $ R $ is prime, and we have $ p_1 \\dots p_n = q_1 \\dots q_m $ products of irreducibles, then, since $ p_1 $ is prime, it divides the product $ q_1 \\dots q_m $ and is thus an associate of some $ q_i $. We can thus cancel $ p_1 $ from the left and $ q_i $ from the right after introducing a unit on one side. This is possible because $ R $ is an integral domain. Repeating the process we find that, up to reordering the terms and multiplying by units, the two expressions coincide.\n\\end{proof}\n\n\\subsection{Principal ideal domains}\n\n\\begin{definition}\nAn integral domain $ R $ is a \\textbf{principal ideal domain} (PID) if every ideal of $ R $ is a principal ideal.\n\\end{definition}\n\n\\begin{theorem}\n\\label{thm:3.3.2}\nEvery PID is a UFD.\n\\end{theorem}\n\nWe first show $ 1 $. It is true for units trivially.\n\n\\begin{lemma}\nLet $ R $ be a PID. Then every nonzero nonunit $ r \\in R $ has a irreducible divisor.\n\\end{lemma}\n\n\\begin{proof}\nFix $ r = r_0 \\in R $. We first show $ r $ has an irreducible factor. If $ r_0 $ is irreducible we are done. Otherwise $ r_0 $ is not irreducible, we can choose an $ r_1 $, not a unit nor an associate of $ r_0 $, such that $ r_1 $ divides $ r_0 $, so $ r_0 = r_1s_1 $ with $ r_1, s_1 $ not units. If $ r_1 $ is not irreducible we choose $ r_2 $ similarly, and repeat. If this process ever terminates we have found an irreducible divisor of $ r $. Suffices to show this terminates. Suppose it does not terminate. We obtain an increasing tower of ideals\n$$ \\ab{r_0} \\subsetneq \\ab{r_1} \\subsetneq \\dots. $$\nLet $ I $ be the union of all these ideals generated by $ r_0, r_1, \\dots $. Then $ I $ is an ideal, so it is generated by some element $ s \\in I $. Thus $ s $ divides $ r_i $ for all $ i $. On the other hand, $ s $ lives in some $ \\ab{r_j} $, so $ r_j $ divides $ s $. Thus $ s $ is an associate of $ r_j $, and therefore an associate of $ r_i $ for all $ i > j $, that is $ I \\subseteq \\ab{r_j} $. This contradicts our construction because $ \\ab{r_{j + 1}} \\subseteq I $ and $ \\ab{r_{j + 1}} \\ne \\ab{r_j} $.\n\\end{proof}\n\nThus $ r $ has an irreducible divisor $ s_0 $.\n\n\\begin{lemma}\nLet $ R $ be a PID. Every nonzero nonunit $ r \\in R $ is a finite product of irreducibles.\n\\end{lemma}\n\n\\begin{proof}\nConsider $ rs_0^{-1} $. If this is a unit we are done. If not let $ s_1 $ be an irreducible divisor of $ rs_0^{-1} $. If $ r\\rb{s_0s_1}^{-1} $ is a unit we are done, otherwise repeat. We obtain a sequence of irreducibles $ s_0, s_1, \\dots $ such that $ s_0 \\dots s_i $ divides $ r $ for all $ i $, so $ r = r_0s_0 = r_0r_1s_1 = \\dots $ with $ r_0, r_1, \\dots $ irreducible. If this process ever terminates we are done. Suppose it does not. Then we have a strictly increasing tower of ideals\n$$ \\ab{r} \\subsetneq \\ab{s_0} \\subsetneq \\ab{s_1} \\subsetneq \\dots. $$\nThis cannot continue forever. Arguing as above we arrive at a contradiction.\n\\end{proof}\n\nNow we show $ 2 $.\n\n\\begin{proof}[Proof of Theorem \\ref{thm:3.3.2}]\nIt suffices to show that in a PID every irreducible is prime. Let $ r \\in R $ be irreducible, and suppose that $ r $ divides $ st $. Want $ r \\mid s $ or $ r \\mid t $. Let $ q $ be a generator of the ideal $ \\ab{r, s} $ of $ R $, so $ \\ab{r, s} = \\ab{q} $. Then $ q $ divides $ r $, so either $ q $ is a unit or $ q $ is an associate of $ r $. If $ q $ is an associate of $ r $, then since $ q $ divides $ s $, $ r $ divides $ s $. on the other hand, if $ q $ is a unit, then the ideal generated by $ r $ and $ s $ is the unit ideal and $ 1 \\in \\ab{r, s} $, so we can write $ 1 = xr + ys $ for $ x, y $ elements of $ R $. We then have $ t = xrt + yst $, and since $ r $ divides both $ yst $ and $ xrt $, $ r $ divides $ t $.\n\\end{proof}\n\n\\marginpar{Lecture 6 \\\\ Wednesday \\\\ 16/10/18}\n\n\\subsection{Euclidean domains}\n\nOne technique for proving that rings are PIDs is Euclid's algorithm. We formalise this in an abstract setting as follows.\n\n\\begin{definition}\nLet $ R $ be an integral domain.\n\\begin{enumerate}\n\\item A \\textbf{Euclidean norm} on $ R $ is a function $ N : R \\to \\Z_{\\ge 0} $ such that for all $ a, b \\in R $, with $ b \\ne 0 $, there exists $ q, r \\in R $ such that $ a = qb + r $, and either $ r = 0 $ or $ N\\rb{r} < N\\rb{b} $.\n\\item An integral domain $ R $ is called a \\textbf{Euclidean domain} if there is a Euclidean norm on $ R $.\n\\end{enumerate}\n\\end{definition}\n\n\\begin{theorem}\nAny Euclidean domain is a PID.\n\\end{theorem}\n\n\\begin{proof}\nLet $ R $ be a Euclidean domain, $ N $ be a Euclidean norm on $ R $, and $ I \\subseteq R $ a nonzero ideal of $ R $. Let $ a \\in I $ be a nonzero element such that $ N\\rb{a} $ is minimal, that is if $ b \\in I $, $ b \\ne 0 $, then $ N\\rb{b} \\ge N\\rb{a} $. Claim that $ I = \\ab{a} $. Let $ b \\in I $. Then there exist $ q, r $ such that $ b = aq + r $, with either $ r = 0 $ or $ N\\rb{r} \\ge N\\rb{a} $. So $ r = 0 $ gives $ b = aq $. Thus $ I = \\ab{a} $.\n\\end{proof}\n\n\\begin{proof}\nLet $ R $ be a Euclidean domain, $ N $ be a Euclidean norm on $ R $, and $ I \\subseteq R $ be a nonzero ideal of $ R $. Let $ n $ be the smallest integer such that there exists a nonzero element $ a \\in I $ with $ N\\rb{a} = n $ minimal, that is if $ b \\in I $ and $ b \\ne 0 $, then $ N\\rb{b} < N\\rb{a} $. Claim that $ I = \\ab{a} $. Then for any $ b \\in I $, we can write $ b = qa + r $ with $ N\\rb{r} < N\\rb{a} $ unless $ r = 0 $. But since $ N\\rb{a} $ is the smallest possible norm in $ I $, we must have $ r = 0 $, so $ b = qa $. Thus $ I $ is generated by $ a $ and we are done.\n\\end{proof}\n\n\\subsection{Examples}\n\n\\begin{example}\n\\hfill\n\\begin{enumerate}\n\\item The classic example of a Euclidean domain is $ \\Z $, with $ N\\rb{x} = \\abs{x} $ for $ x \\in \\Z $.\n\\item The ring $ \\Z\\sb{i} $ is a Euclidean domain, with $ N\\rb{z} = z\\bar{z} = \\abs{z}^2 $, so $ N\\rb{x + yi} = \\abs{x + yi}^2 = x^2 + y^2 $. To see this, note that given $ a $ and $ b $ in $ \\Z\\sb{i} $ for $ b \\ne 0 $, set $ q' = a / b \\in \\Q\\sb{i} $. Write $ q' = x' + iy' $ with $ x', y' \\in \\Q $. Let $ x $ and $ y $ be the closest integers to $ x' $ and $ y' $, such that $ \\abs{x - x'}, \\abs{y - y'} \\le 1 / 2 $, and set $ q = x + iy $ in $ \\Z\\sb{i} $ and $ r = a - bq $. Then\n$$ N\\rb{r} = \\abs{r}^2 = \\abs{a - bq}^2 = \\abs{a - b\\rb{\\dfrac{a}{b} + \\rb{q - q'}}}^2 = \\abs{b\\rb{q - q'}}^2 = \\abs{b}^2\\abs{q - q'}^2 \\le \\dfrac{N\\rb{b}}{2}. $$\nSimilar arguments can be used to prove that $ \\Z\\sb{\\alpha} $ is a Euclidean domain for\n$$ \\alpha = \\sqrt{-2}, \\qquad \\alpha = \\dfrac{-1 + \\sqrt{-3}}{2}, \\qquad \\alpha = \\dfrac{-1 + \\sqrt{-7}}{2}. $$\nBeyond this one needs other tricks and for most $ \\alpha $ unique factorisation fails.\n\\item A critical example is the polynomial ring $ K\\sb{X} $ for $ K $ a field. Here we can take $ N\\rb{P\\rb{X}} $ to be the degree of $ P\\rb{X} $. Then, given polynomials $ P\\rb{X}, T\\rb{X} \\in K\\sb{X} $ and $ T\\rb{X} \\ne 0 $, we can use polynomial long division to write $ P\\rb{X} = Q\\rb{X}T\\rb{X} + R\\rb{X} $ for some $ Q\\rb{X} $ with the degree of $ R $ strictly less than that of $ T $, unless $ T $ is constant, in which case we can make $ R = 0 $. To prove this, fix $ T\\rb{X} $. If $ \\deg\\rb{T\\rb{X}} = 0 $, $ T\\rb{X} $ is constant, so $ T\\rb{X} = c \\ne 0 \\in K $. Take $ Q\\rb{X} = c^{-1}P\\rb{X} $, so $ R\\rb{X} = 0 $. Otherwise induct on $ \\deg\\rb{P\\rb{X}} $. If $ \\deg\\rb{P\\rb{X}} < \\deg\\rb{T\\rb{X}} $, set $ R\\rb{X} = P\\rb{X} $ and $ Q\\rb{X} = 0 $. Suppose the claim is true for polynomials of degree $ n $ and $ P\\rb{X} $ has degree $ n + 1 $, so\n$$ P\\rb{X} = \\sum_{i = 0}^{n + 1} a_iX^i, \\qquad T\\rb{X} = \\sum_{i = 0}^d b_iX^i, $$\nfor $ d < n + 1 $. Then $ S\\rb{X} = P\\rb{X} - \\rb{a_{n + 1} / b_d}X^{n + 1 - d}T\\rb{X} $ has degree $ n $. By inductive hypothesis there exist $ Q\\rb{X}, R\\rb{X} $ with $ \\deg\\rb{R\\rb{X}} < \\deg\\rb{T\\rb{X}} $ such that\n$$ S\\rb{X} = Q\\rb{X}T\\rb{X} + R\\rb{X} \\qquad \\implies \\qquad P\\rb{X} = \\rb{\\dfrac{a_{n + 1}}{b_d}X^{n + 1 - d} + Q\\rb{X}}T\\rb{X} + R\\rb{X}. $$\n\\end{enumerate}\n\\end{example}\n\nLater, will show if $ R $ UFD, then $ R\\sb{X} $ is also a UFD.\n\n\\section{The Chinese remainder theorem}\n\nIn elementary number theory, let $ m_1, m_2 \\in \\Z $ be relatively prime and $ a_1, a_2 \\in \\Z $. Then there exists $ a \\in \\Z $ such that\n$$ a \\equiv a_1 \\mod m_1, \\qquad a \\equiv a_2 \\mod m_2. $$\nMoreover, $ a $ is unique up to congruence modulo $ m_1m_2 $. Question is given ideals $ I_1, \\dots, I_r $ and $ a_1, \\dots, a_r \\in \\R $, when can we find a $ a \\in R $ with $ a \\in a_1 + I_1, \\dots a_r + I_r $?\n\n\\subsection{Products}\n\n\\begin{definition}\nLet $ R_1, \\dots, R_n $ be rings. The \\textbf{direct product} $ R \\times \\dots \\times R_n $ is a ring whose elements are $ n $-tuples $ \\rb{r_1, \\dots, r_n} $ with $ r_i \\in R_i $ for all $ i $. The addition and multiplication are given componentwise.\n$$ \\rb{r_1, \\dots, r_n} + \\rb{r_1', \\dots, r_n'} = \\rb{r_1 + r_1', \\dots, r_n + r_n'}, \\qquad \\rb{r_1, \\dots, r_n}\\rb{r_1', \\dots, r_n'} = \\rb{r_1r_1', \\dots, r_nr_n'}. $$\n\\end{definition}\n\n\\begin{note}\nThe product comes with natural homomorphisms for all $ i $, $ \\pi_i $, \\textbf{projection} onto the $ i $-th factor, defined by\n$$ \\pi_i\\rb{r_1, \\dots, r_n} = r_i : R_1 \\times \\dots \\times R_n \\to R_i, $$\nand the following universal property.\n\\end{note}\n\n\\begin{theorem}[Universal property of the product]\nLet $ S, R_1, \\dots, R_n $ be any rings. For any homomorphisms $ f_1 : S \\to R_1, \\dots, f_n : S \\to R_n $, there exists a unique homomorphism $ f : S \\to R_1 \\times \\dots \\times R_n $ such that $ \\pi_i \\circ f = f $ for all $ i $.\n\\end{theorem}\n\n\\begin{proof}\nGiven $ f_i $, the homomorphism $ f $ is defined by $ f\\rb{s} = \\rb{f_1\\rb{t}, \\dots, f_n\\rb{t}} $. Then $ \\rb{\\pi_i \\circ f}\\rb{s} = f_i\\rb{s} $. For uniqueness, if $ \\rb{\\pi \\circ g}\\rb{s} = f_i\\rb{s} $ for all $ i $, then $ g\\rb{s} = \\rb{f_1\\rb{s}, \\dots, f_n\\rb{s}} = f\\rb{s} $.\n\\end{proof}\n\nMore generally, if $ I $ is any index set, and for each $ i \\in I $ we have a ring $ R_i $, we can define the product $ \\prod_i R_i $. An element $ r $ of this product is a choice, for each $ i \\in I $, of an element of $ R_i $. We write such an element as $ \\rb{r_i}_{i \\in I} $. For each $ j \\in I $ we have a map $ \\pi_j : \\prod_i R_i \\to R_j $ given by $ \\pi_j\\rb{\\rb{r_i}_{i \\in I}} = r_j $. Such a product satisfies a very similar universal property. For any collection $ f_i : S \\to R_i $ of maps for each $ i \\in I $, we get a unique map $ f : S \\to \\prod_i R_i $ such that $ \\pi_j \\circ f = f_j $.\n\n\\subsection{The Chinese remainder theorem}\n\nLet $ R $ be a ring, and let $ I_1, \\dots, I_r $ be a finite collection of ideals of $ R $. We have the natural maps $ R \\to R / I_1, \\dots, R \\to R / I_r $, which are surjective with kernel $ I_j $. Consider the product map\n$$ R \\to \\dfrac{R}{I_1} \\times \\dots \\times \\dfrac{R}{I_r}. $$\nIt is easy to see that the kernel of this map is the set of $ r \\in R $ such that $ r $ maps to zero in $ R / I_j $ for all $ j $. That is, the kernel is the intersection $ I_1 \\cap \\dots \\cap I_r $. Call this ideal $ J $. We thus have an injective embedding\n$$ \\dfrac{R}{J} \\hookrightarrow \\dfrac{R}{I_1} \\times \\dots \\times \\dfrac{R}{I_r}. $$\nA natural question to ask is, what can we say about the image? In other words, given congruence classes modulo $ I_1, \\dots, I_r $, when is there a single element of $ R $ that lives in all those congruence classes simultaneously?\n\n\\begin{note}\nBecause the above map is injective, if one such element exists, then there is a unique congruence class modulo $ J $ that satisfies all of the required congruences.\n\\end{note}\n\nOf course, without further hypotheses we cannot expect this map to be surjective. Think about what happens when $ I_1 = I_2 $, for instance. Nonetheless, we have the following.\n\n\\begin{definition}\nWe will say $ I_1, \\dots, I_r $ are \\textbf{pairwise relatively prime} if for each $ i \\ne j $, the sum $ I_i + I_j $ is the unit ideal in $ R $.\n\\end{definition}\n\n(TODO Exercise: if $ R = \\Z $, then $ I_i = \\ab{n_i} $, and $ \\cb{I_i} $ is pairwise relatively prime if and only if for all $ i \\ne j $, $ n_i $ and $ n_j $ are relatively prime)\n\n\\begin{theorem}\nLet $ R $ be a ring and $ I_1, \\dots, I_r $ be pairwise relatively prime ideals. Then the natural map\n$$ \\dfrac{R}{J} \\hookrightarrow \\dfrac{R}{I_1} \\times \\dots \\times \\dfrac{R}{I_r} $$\nis an isomorphism.\n\\end{theorem}\n\n\\begin{proof}\nWe have to prove it is surjective. Fix any tuple $ \\rb{c_1, \\dots, c_r} $ of elements of $ R $. We need to find $ c \\in R $ such that $ c \\in c_i + I_i $ for all $ i $. It suffices to construct, for each $ i $, an element $ e_i $ of $ R $ such that $ e_i \\equiv 1 \\mod I_i $ and $ e_i \\equiv 0 \\mod I_j $ for $ i \\ne j $. Suppose we have such an element. Then the element $ c = c_1e_1 + \\dots + c_re_r $ is such that $ c \\equiv c_j \\mod I_j $ for all $ j $. Given $ i, j $ with $ i \\ne j $, we know that $ I_i + I_j $ is the unit ideal. That is, we can write $ a_{ij} + b_{ij} = 1 $ with $ a_{ij} \\in I_i $ and $ b_{ij} \\in I_j $. Then $ a_{ij} \\equiv 1 \\mod I_j $ and $ a_{ij} \\equiv 0 \\mod I_i $ as an element of $ R / I_1 \\times \\dots \\times R / I_r $, so $ a_{ij} $ has zero in the $ i $-th place and one in the $ j $-th place. Then for any $ j $ we can take $ e_j = \\prod_{i \\ne j} a_{ij} $ and $ e_j \\equiv 1 \\mod I_j $ and $ e_j \\equiv 0 \\mod I_i $ for all $ i \\ne j $, so $ e_j $ has one only in the $ j $-th place. So $ R \\to R / I_1 \\times \\dots \\times R / I_r $ is surjective. The result follows.\n\\end{proof}\n\n\\subsection{Examples}\n\nWhen $ R = \\Z $, then every ideal is principal, so we can write $ I_j = \\ab{n_j} $ for all $ j $. The condition that $ I_i + I_j $ is the unit ideal becomes the condition that $ n_i \\in \\Z $ are pairwise relatively prime. In this case the ideal $ J $ is generated by the product $ n $ of the $ n_i $. Specialising, we find the version of the Chinese remainder theorem from elementary number theory.\n\n\\begin{theorem}\nIf $ \\cb{n_j \\in \\Z} $ is a finite collection of pairwise relatively prime integers, and $ n $ is their product, then for any $ c_1, \\dots, c_r \\in \\Z $, there exists $ c \\in \\Z $ unique up to congruence modulo $ n $ such that $ c $ is congruent to $ c_i \\mod n_i $ for all $ i $.\n\\end{theorem}\n\nNow let $ K $ be a field and take $ R = K\\sb{X} $. If $ c_1, \\dots, c_r \\in K $ are distinct elements of $ K $, the ideals $ I_i = \\ab{X - c_i} \\subseteq R $ are such that $ I_i + I_j = \\ab{X - c_i} + \\ab{X - c_j} $ contains $ c_i - c_j \\in K^* $, so contains $ 1 $. That is, $ I_i + I_j $ is the unit ideal in $ R $ and the ideals $ I_i $ are pairwise relatively prime. Moreover, for each $ i $, $ I_i $ is the kernel of the evaluation map $ f_i : R \\to K $ by that takes $ P\\rb{X} $ to $ P\\rb{c_i} $. Let $ f : R \\to K \\times \\dots \\times K $ by $ P\\rb{X} \\mapsto \\rb{P\\rb{c_1}, \\dots, P\\rb{c_r}} $. Then the following diagram commutes.\n$$\n\\begin{tikzcd}[column sep=1in]\nR \\arrow{r}{f} \\arrow[two heads]{d} & K \\times \\dots \\times K \\\\\n\\dfrac{R}{J} \\arrow[swap]{r}{\\sim} & \\dfrac{R}{I_1} \\times \\dots \\times \\dfrac{R}{I_r} \\arrow[swap]{u}{\\sim}\n\\end{tikzcd}\n$$\nChinese remainder theorem gives that $ f $ is surjective. We thus have an isomorphism of $ R / I_i $ with $ K $ that takes $ P\\rb{X} $ to $ P\\rb{c_i} $ for all polynomials $ P $. We thus obtain the following.\n\n\\begin{theorem}\nFor any $ c_1, \\dots, c_n \\in K $, there is a polynomial $ P\\rb{X} $ in $ R $, unique up to congruence modulo $ \\rb{X - a_1} \\dots \\rb{X - a_n} $ such that $ P\\rb{a_i} = c_i $ for all $ i $.\n\\end{theorem}\n\n\\marginpar{Lecture 7 \\\\ Friday \\\\ 19/10/18}\n\n\\section{Fields and field extensions}\n\nNext we will use $ K\\sb{X} $ is a PID for $ K $ a field to study fields systematically.\n\n\\subsection{Prime fields}\n\nLet $ K $ be a field. We have a unique ring homomorphism $ \\iota : \\Z \\to K $ by $ n \\ge 0 \\mapsto n_K = 1_K + \\dots + 1_K $. Let $ I $ be the kernel. Then $ \\Z / I \\hookrightarrow K $ so $ \\Z / I $ is an integral domain, so $ I $ is a prime ideal. Thus $ I $ is either the zero ideal $ \\cb{0} $, if $ K $ has characteristic zero, or the ideal $ \\ab{p} $ for some prime $ p $ of $ \\Z $. In the former case $ I = \\cb{0} $, the injection $ \\Z \\hookrightarrow K $ extends to an inclusion $ \\Q \\hookrightarrow K $ sending $ a / b \\mapsto \\rb{\\iota a}\\rb{\\iota b^{-1}} = a_K / b_K $. In the latter case $ I = \\ab{p} $, we get an injection $ \\Z / p\\Z \\hookrightarrow K $, which we often denote $ \\F_p $ when we think of it as a field. Upshot is that every field $ K $ contains exactly one of $ \\Q $, $ \\F_p $, for $ p $ prime, in exactly one way depending on its characteristic. This field is called the \\textbf{prime field} of $ K $, and it is contained in $ K $ in a unique way.\n\n\\subsection{Field extensions}\n\nThe prime fields are in some sense the smallest possible fields. Once we know they exist, it makes sense to study fields by studying pairs $ K, L $ of fields such that $ K \\subseteq L $ of fields, trying to relate $ L $ to $ K $.\n\n\\begin{definition}\nA \\textbf{field extension} is a pair of fields $ K, L $ with $ K \\subseteq L $, and is often denoted $ L / K $.\n\\end{definition}\n\n\\begin{note}\nSuch an inclusion of fields $ L / K $ makes $ L $ into a $ K $-vector space, that is a vector space over $ K $.\n\\end{note}\n\n\\begin{definition}\nWe say that a field extension $ L / K $ is \\textbf{finite} if $ L $ is finite-dimensional as a $ K $-vector space. If this is the case, the \\textbf{degree} of such an extension is the dimension of $ L $ as a $ K $-vector space $ \\dim_KL $, and is denoted $ \\sb{L : K} $.\n\\end{definition}\n\n\\begin{proposition}\nLet $ K \\subseteq L \\subseteq M $ be fields. Then $ M / K $ is finite if and only if $ M / L $ and $ L / K $ are both finite. If this is the case then $ \\sb{M : K} = \\sb{M : L}\\sb{L : K} $.\n\\end{proposition}\n\n\\begin{proof}\nFirst suppose that $ M / K $ is finite. Then $ L $ is a $ K $-subspace of $ M $, so finite dimensional as a $ K $-vector space. Moreover, there exists a $ K $-basis $ m_1, \\dots, m_r $, and this basis spans $ M $ over $ K $ and thus also over $ L $. Thus $ M $ is finite-dimensional as an $ L $-vector space, so $ M / L $ is finite. Conversely, suppose $ L / K $, $ M / L $ are finite. Let $ e_1, \\dots, e_n $ be a $ K $-basis for $ L $, and let $ f_1, \\dots, f_n $ be an $ L $-basis for $ M $. Then claim that\n$$ e_1f_1, \\dots, e_1f_m, \\dots, e_nf_1, \\dots, e_nf_m $$\nis a $ K $-basis for $ M $. Every element $ x $ of $ M $ can be expressed uniquely as $ c_1f_1 + \\dots + c_mf_m $ with $ c_i \\in L $. Each $ c_i $ in turn can be expressed as $ d_{1, i}e_1 + \\dots + d_{n, i}e_n $ with $ d_{j, i} \\in K $. Thus we can express $ x $ as\n$$ d_{1, 1}e_1f_1 + \\dots + d_{n, 1}e_nf_1 + \\dots + d_{1, m}e_1f_m + \\dots + d_{n, m}e_nf_m. $$\nIn particular the set $ \\cb{e_if_j} $ for $ 1 \\le i \\le n $ and $ 1 \\le j \\le m $ spans $ M $ over $ K $. In this case the degree of $ L $ over $ K $ is $ n $ and the degree of $ M $ over $ L $ is $ m $, so it remains to show that $ \\cb{e_if_j} $ is linearly independent over $ K $. Suppose we have elements $ d_{i, j} $ of $ K $ such that $ \\sum_{i, j} d_{i, j}e_if_j = 0 $. Then, regrouping, we find that $ \\sum_j \\rb{\\sum_i d_{i, j}e_i}f_j = 0 $ is an $ L $-linear combination of the $ f_j $ that is zero. Since the $ f_j $ are linearly independent over $ L $ we must have $ \\sum_i d_{i, j}e_i = 0 $ for all $ j $. Since the $ e_i $ are linearly independent over $ K $ we must have $ d_{i, j} = 0 $ for all $ i, j $.\n\\end{proof}\n\n\\marginpar{Lecture 8 \\\\ Monday \\\\ 22/10/18}\n\n\\subsection{Extensions generated by one element}\n\nLet $ L / K $ be a field extension, and let $ \\alpha $ be an element of $ L $.\n\n\\begin{definition}\nWe let $ K\\rb{\\alpha} $ denote the subfield of $ L $ consisting of all elements of $ L $ that can be expressed in the form $ P\\rb{\\alpha} / Q\\rb{\\alpha} $, where $ P $ and $ Q $ are polynomials with coefficients in $ K $ and $ Q\\rb{\\alpha} $ is not zero. This is the smallest subfield of $ L $ containing $ K $ and $ \\alpha $.\n\\end{definition}\n\nRecall that if $ R, S $ are rings, $ f : R \\to S $ is a homomorphism, and $ \\alpha \\in S $, then have $ \\phi_{f, a} : R\\sb{X} \\to S $ by $ \\phi_{f, a}\\rb{\\sum_{i = 1}^n r_iX^i} = \\sum_{i = 1}^n f\\rb{r_i}\\alpha^i $. We have a natural map $ K\\sb{X} \\to K\\rb{\\alpha} \\subseteq L. $, inclusion on $ K $, that takes a polynomial $ P\\rb{X} $ to $ P\\rb{\\alpha} $. It is a ring homomorphism. Let $ I $ be the kernel of this homomorphism. We then get an injection of $ K\\sb{X} / I $ into the field $ K\\rb{\\alpha} $. Thus $ K\\sb{X} / I $ is an integral domain, so $ I $ is a prime ideal of $ K\\sb{X} $. Since $ K\\sb{X} $ is a PID, every nonzero prime ideal is maximal. (TODO Exercise) There are thus two cases. In the first $ I $ is the zero ideal that is not maximal. That is, there is no nonzero polynomial $ Q $ in $ K\\sb{X} $ such that $ Q\\rb{\\alpha} $ is zero in $ L $. We say that $ \\alpha $ is \\textbf{transcendental} over $ K $ in this case. In the second $ I $ is an ideal $ \\ab{Q} $ for $ Q \\in K\\sb{X} $ a nonzero irreducible polynomial that is a maximal ideal of $ K\\sb{X} $. In this case we say $ \\alpha $ is \\textbf{algebraic} over $ K $.\n\n\\begin{definition}\n$ K\\rb{X} $ is the \\textbf{field of rational functions} on $ X $,\n$$ K\\rb{X} = \\cb{\\dfrac{P\\rb{X}}{Q\\rb{X}} \\ \\Bigg| \\ P, Q \\in K\\sb{X}, \\ Q \\ne 0} / \\sim. $$\n\\end{definition}\n\nAssume first that $ \\alpha $ is transcendental over $ K $, that is $ I = \\cb{0} $. Recall $ I = \\cb{P\\rb{X} \\in K\\sb{X} \\mid P\\rb{\\alpha} = 0} $. So in this case there is no nonzero polynomial $ P \\in K\\sb{X} $ with $ P\\rb{\\alpha} = 0 $. In this case the map taking $ P\\rb{X} $ to $ P\\rb{\\alpha} $ is an injection of $ K\\sb{X} $ into $ K\\rb{\\alpha} \\subseteq L $. In particular every nonzero element of $ K\\sb{X} $ gets sent to a nonzero, hence invertible, element of $ L $. Thus the map from $ K\\sb{X} $ to $ L $ extends to an injective map from the field of fractions of $ K\\sb{X} $, which we denote $ K\\rb{X} $, to $ L $. This map takes $ P\\rb{X} / Q\\rb{X} $ to $ P\\rb{\\alpha} / Q\\rb{\\alpha} $. By definition of $ K\\rb{\\alpha} $, this map is surjective so the image of this map is $ K\\rb{\\alpha} $. In particular $ K\\rb{X} $ and $ K\\rb{\\alpha} $ are isomorphic. Thus the following diagram holds.\n$$\n\\begin{tikzcd}[column sep=1in]\n& L \\\\\nK\\rb{X} \\arrow{r}{\\sim}[swap]{g} & K\\rb{\\alpha} \\arrow[hookrightarrow, swap]{u}{\\subseteq} \\\\\nK\\sb{X} \\arrow[hookrightarrow]{u}{\\subseteq} \\arrow[hookrightarrow, swap]{ur}{f}\n\\end{tikzcd}\n\\qquad f : P\\rb{X} \\mapsto P\\rb{\\alpha} \\qquad g : \\dfrac{P\\rb{X}}{Q\\rb{X}} \\mapsto \\dfrac{P\\rb{\\alpha}}{Q\\rb{\\alpha}}\n$$\n\n\\begin{note}\nIn this case $ K\\rb{\\alpha} $ is infinite dimensional as a $ K $-vector space. It contains a subspace isomorphic to $ K\\sb{X} $, for instance.\n\\end{note}\n\nIf $ \\alpha $ is algebraic over $ K $, then $ I $ is a nonzero maximal ideal of the PID $ K\\sb{X} $, so it is generated by a single irreducible polynomial $ Q\\rb{X} $ in $ K\\sb{X} $. As a consequence, since the units in $ K\\sb{X} $ are just the constant polynomials, the polynomial $ Q\\rb{X} $ is well-defined up to a constant factor. It is called the \\textbf{minimal polynomial} of $ \\alpha $. By definition, it divides every polynomial $ P\\rb{X} $ such that $ P\\rb{\\alpha} = 0 $. Since $ \\ab{Q\\rb{X}} $ is maximal, the ring $ K\\sb{X} / \\ab{Q\\rb{X}} $ is a field. Recall that for any $ P \\in K\\sb{X} $, can write $ P\\rb{X} $ uniquely as $ A\\rb{X}Q\\rb{X} + R\\rb{X} $ with $ \\deg\\rb{R} < \\deg\\rb{Q} $. So $ 1, \\dots, X^{\\deg\\rb{Q} - 1} $ are a $ K $-basis of $ K\\sb{X} / \\ab{Q\\rb{X}} $. So its dimension as a $ K $-vector space is equal to the degree of $ Q\\rb{X} $. The map $ K\\sb{X} \\to K\\rb{\\alpha} \\subseteq L $ descends to an injection of $ K\\sb{X} / \\ab{Q\\rb{X}} $ into $ L $. Since its image is a subfield of $ K\\rb{\\alpha} $ containing $ K $ and $ \\alpha $, this map is an isomorphism of $ K\\rb{\\alpha} $ with $ K\\sb{X} / \\ab{Q\\rb{X}} $. Thus in this case the extension $ K\\rb{\\alpha} / K $ is a finite extension, of degree equal to the degree of $ Q\\rb{X} $. Thus the following diagram holds.\n$$\n\\begin{tikzcd}[column sep=1in]\nK\\sb{X} \\arrow[twoheadrightarrow]{dr}{f} & L \\\\\n\\dfrac{K\\sb{X}}{\\ab{Q\\rb{X}}} \\arrow[hookrightarrow]{u}{\\subseteq} \\arrow{r}{g}[swap]{\\sim} & K\\rb{\\alpha} \\arrow[hookrightarrow, swap]{u}{\\subseteq}\n\\end{tikzcd}\n\\qquad f : P\\rb{X} \\mapsto P\\rb{\\alpha} \\qquad g : \\sb{R\\rb{X}}_{\\ab{Q\\rb{X}}} \\to R\\rb{\\alpha}\n$$\n\nTo summarise, extend $ K $ by a single element by\n\\begin{enumerate}\n\\item building $ K\\sb{X} $, and\n\\item either passing to field of fractions $ K\\rb{X} $ to form a transcendental extension, or choosing an irreducible polynomial $ Q $ to form an algebraic extension $ K\\sb{X} / \\ab{Q\\rb{X}} $.\n\\end{enumerate}\nSlightly informally, instead of $ K\\sb{X} / \\ab{Q\\rb{X}} $, we sometimes write $ K\\rb{\\alpha} $, where $ \\alpha $ is a root of $ Q\\rb{X} $.\n\n\\begin{definition}\nAn extension $ L / K $ is \\textbf{algebraic} if every element of $ L $ is algebraic over $ K $.\n\\end{definition}\n\nAn observation is that if $ L / K $ is finite, then $ L / K $ is algebraic. Suppose not. Let $ \\alpha \\in L $ be transcendental over $ K $. $ K\\sb{X} $ is a polynomial ring in $ K\\rb{\\alpha} $ contained in $ L $, so $ L / K $ is not finite.\n\n\\begin{corollary}\nLet $ L / K $ be a field extension for $ \\alpha, \\beta \\in L $ algebraic over $ K $. Then $ \\alpha + \\beta $, $ \\alpha\\beta $ are algebraic over $ K $.\n\\end{corollary}\n\n\\begin{proof}\n$ \\sb{K\\rb{\\alpha} : K} = \\deg\\rb{\\alpha} $ and $ \\sb{K\\rb{\\alpha, \\beta} : K\\rb{\\alpha}} \\le \\deg\\rb{\\beta} $, so $ \\sb{K\\rb{\\alpha, \\beta} : K} \\le \\rb{\\deg\\rb{\\alpha}}\\rb{\\deg\\rb{\\beta}} $. Now $ K \\subseteq K\\rb{\\alpha + \\beta} \\subseteq K\\rb{\\alpha, \\beta} $, so $ \\deg\\rb{\\alpha + \\beta} $ over $ K $ is at most $ \\rb{\\deg\\rb{\\alpha}}\\rb{\\deg\\rb{\\beta}} $. Similarly for $ \\alpha\\beta $.\n\\end{proof}\n\n\\begin{corollary}\nIf $ L / K $, then the subset $ L^{alg} $ of elements of $ L $ algebraic over $ K $ is a field.\n\\end{corollary}\n\n\\begin{proof}\nIf $ a_0 + \\dots + a_n\\alpha^n = 0 $ then $ a_0\\rb{\\alpha^{-1}}^n + \\dots + a_n = 0 $.\n\\end{proof}\n\n\\begin{example}\n$ \\bar{\\Q} \\subseteq \\C $ is the subfield of elements of $ \\C $ that are algebraic over $ \\Q $.\n\\end{example}\n\n\\subsection{Example}\n\n\\begin{example}\nConsider the polynomial $ X^2 + X + 1 $ in $ \\F_2\\sb{X} $. It has no roots in $ \\F2 $, so it is irreducible, as a polynomial of degree 2 any nontrivial factor would be linear. The other polynomials of degree two are $ X^2 $, $ X^2 + X = X\\rb{X + 1} $, $ X^2 + 1 = \\rb{X + 1}^2 $, so $ X^2 + X + 1 $ is the unique irreducible polynomial of degree two. Let $ \\F_4 = \\F_2\\sb{X} / \\ab{X^2 + X + 1} $. Thus the quotient $ \\F_2\\sb{X} = \\ab{X^2 + X + 1} $ is a field extension of degree two of $ \\F_2 $, which is denoted $ \\F_4 $. Its four elements are $ 0, 1, X, X + 1 $, or more precisely, their classes modulo $ \\ab{X^2 + X + 1} $.\n\\begin{center}\n\\begin{tabular}{|c|c|c|c|c|}\n\\hline\n$ \\cdot $ & $ 0 $ & $ 1 $ & $ X $ & $ X + 1 $ \\\\\n\\hline\n$ 0 $ & $ 0 $ & $ 0 $ & $ 0 $ & $ 0 $ \\\\\n\\hline\n$ 1 $ & $ 0 $ & $ 1 $ & $ X $ & $ X + 1 $ \\\\\n\\hline\n$ X $ & $ 0 $ & $ X $ & $ X + 1 $ & $ 1 $ \\\\\n\\hline\n$ X + 1 $ & $ 0 $ & $ X + 1 $ & $ 1 $ & $ X $ \\\\\n\\hline\n\\end{tabular}\n\\end{center}\nNote that $ X^2 = -X - 1 = X + 1 $, $ X^2 + X + 1 = 0 $, $ \\rb{X + 1}^2 = X $, and $ X^3 = X\\rb{X + 1} = 1 $ in $ \\F_4 $. In particular the multiplicative group of $ \\F_4 $ is cyclic of order three. This is not particularly surprising, as all groups of order three are cyclic. We will see later, though, that the multiplicative group of any finite field is cyclic.\n\\end{example}\n\n\\begin{proposition}\nLet $ K $ be a field with four elements. Then $ K \\cong \\F_4 $.\n\\end{proposition}\n\n\\begin{proof}\nLet $ \\alpha \\in K $ with $ \\alpha \\ne 0 $ and $ \\alpha \\ne 1 $. Consider $ 1, \\alpha, \\alpha^2 $. Since $ K $ has dimension two over $ \\F_2 $, there is a linear dependence. So there exists a polynomial $ P $ in $ \\F_2\\sb{X} $ of degree at most two such that $ P\\rb{\\alpha} = 0 $. In fact $ P $ must be irreducible of degree two. If it is divisible by something of degree one, then a polynomial of degree one vanishes on $ \\alpha $, so $ \\alpha = 0 $ or $ \\alpha = 1 $. So $ \\alpha^2 + \\alpha + 1 = 0 $. The map $ \\F_2\\sb{X} \\to K $ sending $ X $ to $ \\alpha $ descends to $ \\F_2\\sb{X} / \\ab{X^2 + X + 1} \\to K $. So $ \\F_4 $ embeds in $ K $. Thus the following diagram holds and $ K \\cong \\F_4 $.\n$$\n\\begin{tikzcd}[column sep=1in]\n\\F_2\\sb{X} \\arrow[twoheadrightarrow]{dr}{P\\rb{X} \\mapsto P\\rb{\\alpha}} & \\\\\n\\dfrac{\\F_2\\sb{X}}{\\ab{X^2 + X + 1}} \\arrow[hookrightarrow]{u}{\\subseteq} \\arrow[swap]{r}{\\sim} & K\n\\end{tikzcd}\n$$\n\\end{proof}\n\n\\marginpar{Lecture 9 \\\\ Wednesday \\\\ 24/10/18}\n\n\\section{Finite fields}\n\n\\subsection{Finite fields}\n\nLet $ K $ be a finite field. That is, a field with only finitely many elements. Then $ K $ has characteristic $ p $ for some prime $ p $, and is in particular a finite dimensional $ \\F_p $ vector space. Thus its order is a power $ p^r $ of $ p $ for $ r > 0 \\in \\Z $. If we fix a particular prime power $ p^r $, then two questions naturally arise. Does there exist a field of order $ p^r $? If so, can we classify fields of order $ p^r $ up to isomorphism? We will see that in fact, up to isomorphism, there is a unique field $ \\F_{p^r} $ of order $ p^r $.\n\n\\subsection{The Frobenius automorphism}\n\nLet $ p $ be a prime. For any ring $ R $, the map $ x \\mapsto x^p $ on $ R $ certainly satisfies $ \\rb{xy}^p = x^py^p $ for all $ x, y \\in R $. On the other hand,\n$$ \\rb{x + y}^p = x^p + \\two{p}{1}xy^{p - 1} + \\dots + \\two{p}{p - 1}x^{p - 1}y + y^p. $$\nNow the binomial coefficients satisfy\n$$ p \\ \\Bigg| \\ \\two{p}{i} = \\dfrac{p!}{i!\\rb{p - i}!}, $$\nfor $ 1 \\le i \\le p - 1 $, so if $ R $ has characteristic $ p $, we have $ \\rb{x + y}^p = x^p + y^p $. So $ x \\mapsto x^p : R \\to R $ is a ring homomorphism from $ R $ to $ R $, called the \\textbf{Frobenius endomorphism} of $ R $. If $ R $ is a field of characteristic $ p $, then the Frobenius endomorphism is injective. If in addition $ R $ is finite, then any injective map from $ R $ to $ R $ is surjective. In particular the Frobenius endomorphism is a bijective and an isomorphism from $ R $ to $ R $ when $ R $ is a finite field of characteristic $ p $. In this case we call the map $ x \\mapsto x^p $ the Frobenius \\textbf{automorphism}. Composing the Frobenius endomorphism with itself, we find that for any $ r $, $ x \\mapsto x^{p^r} $ is also an endomorphism of any ring $ R $ of characteristic $ p $.\n\n\\begin{example}\nLet $ R = \\F_4 $. $ y \\to y^2 $ gives $ 0 \\mapsto 0 $, $ 1 \\mapsto 1 $, $ X \\mapsto X + 1 $, and $ X + 1 \\mapsto X $.\n\\end{example}\n\n\\begin{note}\nLet $ K $ be a field of $ p^r $ elements. Then $ \\alpha^{p^r} = \\alpha $ for all $ \\alpha \\in K $. If $ \\alpha = 0 $, clear. Otherwise $ \\alpha \\in K^* $, $ K^* $ is an abelian group of order $ p^r - 1 $. Lagrange's theorem gives $ \\alpha^{p^r - 1} = 1 $, so $ \\alpha^{p^r} = \\alpha $.\n\\end{note}\n\nWe have the following.\n\n\\begin{proposition}\nLet $ K $ be a field of characteristic $ p $, such that $ \\alpha^{p^r} = \\alpha $ for all $ \\alpha \\in K $. Let $ P\\rb{X} \\in K\\sb{X} $ be an irreducible factor of $ X^{p^r} - X $ over $ K\\sb{X} $. Then every element $ \\beta $ of $ K\\sb{X} / \\ab{P\\rb{X}} $ satisfies $ \\beta^{p^r} = \\beta $.\n\\end{proposition}\n\n\\begin{proof}\nLet $ d = \\deg\\rb{P} $. Can write $ \\beta = c_0 + \\dots + c_{d - 1}X^{d - 1} $. Moreover, since $ P\\rb{X} = 0 $ in $ K\\sb{X} / \\ab{P\\rb{X}} $ and $ P\\rb{X} $ divides $ X^{p^r} - X $, we have $ X^{p^r} = X $ in $ K\\sb{X} / \\ab{P\\rb{X}} $. Thus\n$$ \\beta^{p^r} = c_0^{p^r} + \\dots + c_{d - 1}^{p^r}\\rb{X^{p^r}}^{d - 1} = c_0 + \\dots + c_{d - 1}\\rb{X^{p^r}}^{d - 1} = c_0 + \\dots + c_{d - 1}X^{d - 1} = \\beta. $$\n\\end{proof}\n\n\\begin{corollary}\nThere exists a field $ K $ of characteristic $ p $ such that\n\\begin{enumerate}\n\\item $ \\alpha^{p^r} = \\alpha $ for all $ \\alpha \\in K $, and\n\\item the polynomial $ X^{p^r} - X $ of $ K\\sb{X} $ factors into linear factors over $ K\\sb{X} $.\n\\end{enumerate}\n\\end{corollary}\n\n\\begin{proof}\nLet $ K_0 = \\F_p $. $ K_0 $ satisfies $ 1 $. We construct a tower of fields $ K_0 = \\F_p \\subsetneq K_1 \\subsetneq \\dots $ all satisfying $ 1 $ as follows. Suppose we have constructed $ K_i $ satisfying $ 1 $. If $ X^{p^r} - X $ factors into linear factors over $ K_i\\sb{X} $, we are done. Otherwise, choose a nonlinear irreducible factor $ P_i\\rb{X} $ of $ X^{p^r} - X $ in $ K_i\\sb{X} $ of degree at least two, and set $ K_{i + 1} = K_i\\sb{X} / \\ab{P_i\\rb{X}} $. Then $ K_{i + 1} $ is strictly larger than $ K_i $ and still satisfies $ 1 $. On the other hand, in any field $ K_i $ satisfying $ 1 $, every element is a root of $ X^{p^r} - X $, so $ \\#K_i \\le p^r $ for all $ i $. Since this polynomial can have at most $ p^r $ roots, this process must eventually terminate.\n\\end{proof}\n\nSince $ X^{p^r} - X $ has degree $ p^r $, we expect the field $ K $ constructed above to have $ p^r $ elements. So it suffices to show that over any field $ K $ of characteristic $ p $, $ X^{p^r} - X $ has no repeated roots. To prove this we need an additional tool.\n\n\\subsection{Derivatives}\n\n\\begin{definition}\nLet $ R $ be a ring, and let $ P\\rb{X} = r_0 + \\dots + r_dX^d $ be an element of $ R\\sb{X} $. The \\textbf{derivative} $ P'\\rb{X} $ of $ P\\rb{X} $ is the polynomial $ r_1 + \\dots + dr_dX^{d - 1} $.\n\\end{definition}\n\n\\begin{note}\nJust as for differentiation in calculus, we have a Leibniz rule. For $ P, Q \\in R\\sb{X} $, $ \\rb{PQ}'\\rb{X} = P\\rb{X}Q'\\rb{X} + P'\\rb{X}Q\\rb{X} $, by reducing to $ P, Q $ monomials.\n\\end{note}\n\nFrom this we deduce the following.\n\n\\begin{lemma}\nLet $ K $ be a field, and let $ P\\rb{X} $ be a polynomial in $ K\\sb{X} $ with a multiple root in $ K $. Then $ P\\rb{X} $ and $ P'\\rb{X} $ have a common factor of degree greater than zero.\n\\end{lemma}\n\n\\begin{proof}\nLet $ \\alpha \\in K $ be the multiple root. Then we can write $ P\\rb{X} = \\rb{X - \\alpha}^2Q\\rb{X} $. Applying the Leibniz rule we get $ P'\\rb{X} = 2\\rb{X - \\alpha}Q\\rb{X} + \\rb{X - \\alpha}^2Q'\\rb{X} $ and it is clear that $ X - \\alpha $ divides both $ P\\rb{X} $ and $ P'\\rb{X} $.\n\\end{proof}\n\n\\begin{corollary}\nLet $ K $ be a field of characteristic $ p $. Then $ X^{p^r} - X $ has no repeated roots in $ K $.\n\\end{corollary}\n\n\\begin{proof}\nLet $ P\\rb{X} = X^{p^r} - X $. Then $ P'\\rb{X} = -1 $, so $ P\\rb{X} $ and $ P'\\rb{X} $ have no common factor.\n\\end{proof}\n\n\\begin{corollary}\nThere exists a finite field of $ p^r $ elements.\n\\end{corollary}\n\n\\begin{proof}\nThe field $ K $ we constructed has $ p^r $ elements.\n\\end{proof}\n\n\\marginpar{Lecture 10 \\\\ Friday \\\\ 26/10/18}\n\n\\subsection{The multiplicative group}\n\nRather than show immediately that there is a unique finite field of $ p^r $ elements, we make a detour to study the multiplicative group of a finite field. This is not strictly necessary to prove uniqueness, but will simplify the proof, and is of interest in its own right. Let $ K $ denote a field of $ p^r $ elements. The goal of this section is to show that $ K^* $ is cyclic.\n\n\\begin{note}\nAs a multiplicative group, $ K^* $ is an abelian group of order $ p^r - 1 $, so by Lagrange's theorem, we have $ \\alpha^{p^r - 1} = 1 $ for all $ \\alpha \\in K^* $.\n\\end{note}\n\nRecall for an abelian group $ A $, operation written additively, that the order of an element $ a $ of $ A $ is the smallest $ d \\in \\Z_{> 0} $ such that $ da = 0 $.\n\\begin{enumerate}\n\\item The order of an element $ a $ of $ A $ divides the order of $ A $.\n\\item If $ d'a = 0 $ for some $ d' \\in \\Z $ then the order of $ a $ divides $ d' $.\n\\end{enumerate}\nThe order of an element $ a $ of $ K^* $ is the smallest $ d \\in \\Z_{> 0} $ such that $ a^d = 1 $. Since $ a^{p^r - 1} = 1 $, the order of $ a $ is a divisor of $ p^r - 1 $. On the other hand, if $ d $ is a divisor of $ p^r - 1 $, then any element of order dividing $ d $ is a root of the polynomial $ X^d - 1 $. Since $ K $ is a field, this polynomial has at most $ d $ roots, and we find that there are at most $ d $ elements of $ K^* $ of order dividing $ d $. Order of any element divides $ p^r - 1 $. Know $ X^{p^r - 1} - 1 $ has $ p^r - 1 $ distinct roots in $ K $. For $ d \\mid p^r - 1 $, $ X^d - 1 \\mid X^{p^r - 1} - 1 $, so $ X^d - 1 $ has exactly $ d $ roots in $ K $. That is, for all $ d \\mid p^r - 1 $, $ K^* $ has exactly $ d $ elements of order dividing $ d $. In fact, we have the following.\n\n\\begin{proposition}\n\\label{prop:6.4.1}\nLet $ A $ be a finite abelian group of order $ n $, and suppose that $ A $ has exactly $ d $ elements of order dividing $ d $, for all $ d $ dividing $ n $. Then $ A $ is cyclic.\n\\end{proposition}\n\nIn particular $ K^* $ is cyclic. The remainder of this section will be devoted to proving this proposition. As a corollary, we deduce that the multiplicative group of any finite field is cyclic. Consider the cyclic group $ \\Z / n\\Z $. The order of any element in this group is a divisor of $ n $.\n\n\\begin{definition}\nFor $ n \\in \\Z $, we let $ \\Phi\\rb{n} $ denote the number of elements in $ \\rb{\\Z / n\\Z, +} $ of exact order $ n $. This equals to the number of elements $ t \\in \\Z $ for $ 1 \\le t \\le n $ such that $ \\rb{t, n} = 1 $.\n\\end{definition}\n\n\\begin{note}\nSince $ \\sb{1} $ in $ \\Z / n\\Z $ has order $ n $, $ \\Phi\\rb{n} $ is nonzero for all $ n $.\n\\end{note}\n\n\\begin{lemma}\nFor any $ d $ dividing $ n $, the cyclic group $ \\Z / n\\Z $ contains a unique subgroup of order $ d $, and any element of $ \\Z / n\\Z $ of order dividing $ d $ is contained in this subgroup.\n\\end{lemma}\n\n\\begin{proof}\nThe cyclic subgroup $ C $ of $ \\Z / n\\Z $ generated by $ n / d $ is clearly a subgroup of order $ d $. This has $ d $ elements $ \\sb{0}, \\dots, \\rb{d - 1}\\sb{n / d} $. Conversely, if $ x $ is an element of a subgroup of $ \\Z / n\\Z $ of order $ d $, then the order of $ x $ divides $ d $, so $ dx $ is divisible by $ n $, and hence by unique factorisation $ x $ is divisible by $ n / d $. Thus $ x $ is in $ C $ and the claim follows.\n\\end{proof}\n\nAs a consequence, we deduce the following.\n\n\\begin{corollary}\nFor any $ d $ dividing $ n $, $ \\Phi\\rb{d} $ is the number of elements of $ \\Z / n\\Z $ of order $ d $.\n\\end{corollary}\n\n\\begin{corollary}\nFor any $ n \\in \\Z $, we have\n$$ \\sum_{d \\mid n} \\Phi\\rb{d} = n. $$\n\\end{corollary}\n\n\\begin{proof}\nSince every element of $ \\Z / n\\Z $ has order $ d $ for some $ d $ dividing $ n $, the sum over all possible $ d $ dividing $ n $ of the number of elements of order $ d $ is just the number of elements of $ \\Z / n\\Z $, which is $ n $.\n\\end{proof}\n\n\\begin{proof}[Proof of Proposition \\ref{prop:6.4.1}]\nLet $ A $ be as in the proposition. We must show that $ A $ contains an element of order $ n $. In fact, we will show, by induction on $ d $, that $ A $ contains exactly $ \\Phi\\rb{d} $ elements of order $ d $ for all $ d \\mid n $. In particular, $ A $ has $ \\Phi\\rb{n} > 0 $ elements of order $ n $, so it is cyclic. If $ d = 1 $, the only element of order one is the identity of $ A $. Since $ \\Phi\\rb{1} = 1 $ the base case holds. Assume the claim is true for all $ d' < d $. $ A $ has\n\\begin{enumerate}\n\\item $ d $ elements of order dividing $ d $, and\n\\item $ \\Phi\\rb{d} $ elements of order $ d' $ for $ d' \\mid d $ and $ d' < d $,\n\\end{enumerate}\nso the number of elements of exact order $ d $ is $ d - \\sum_{d' \\mid d, \\ d' < d} \\Phi\\rb{d'} $. By the corollary, this is precisely $ \\Phi\\rb{d} $.\n\\end{proof}\n\n\\subsection{Uniqueness}\n\nWe now turn to the question of showing that any two fields of $ p^r $ elements are isomorphic. Let $ K $ be such a field. The cyclicity of $ K^* $ immediately shows.\n\n\\begin{proposition}\nAny finite field $ K $ of characteristic $ p $ is generated over $ \\F_p $ by a single element $ \\alpha \\in K $.\n\\end{proposition}\n\n\\begin{proof}\nLet $ \\alpha $ be an element of $ K $, that generates $ K^* $ as an abelian group. Then $ \\F_p\\rb{\\alpha} $ is contained in $ K $, but contains $ \\alpha^n $ for all $ n $ so contains $ K^* $, hence $ K = \\F_p\\rb{\\alpha} $.\n\\end{proof}\n\nAs a corollary, we deduce the following.\n\n\\begin{proposition}\nFor any prime $ p $ and any $ r \\in \\Z_{> 0} $, there exists an irreducible polynomial $ P\\rb{X} \\in \\F_p\\sb{X} $ of degree $ r $ in $ \\F_p\\sb{X} $.\n\\end{proposition}\n\n\\begin{proof}\nLet $ K $ be a finite field of $ p^r $ elements, $ \\alpha $ be an element of $ K $ that generates $ K $ over $ \\F_p $, and $ P $ the minimal polynomial of $ \\alpha $ over $ \\F_p $. We then have a surjective map $ \\F_p\\sb{X} \\to K $ taking $ X $ to $ \\alpha $. It is kernel is generated by irreducible $ P $ of degree $ \\deg\\rb{P} = \\sb{\\F_p\\rb{\\alpha} : \\F_p} = r $. Thus the following diagram holds.\n$$\n\\begin{tikzcd}[column sep=1in]\n\\F_p\\sb{X} \\arrow[twoheadrightarrow]{dr}{Q\\rb{X} \\mapsto Q\\rb{\\alpha}} & \\\\\n\\dfrac{\\F_p\\sb{X}}{\\ab{P\\rb{X}}} \\arrow[hookrightarrow]{u}{\\subseteq} \\arrow[swap]{r}{\\sim} & K = \\F_p\\rb{\\alpha}\n\\end{tikzcd}\n$$\n\\end{proof}\n\nWe thus have the following.\n\n\\begin{lemma}\nEvery irreducible polynomial $ P\\rb{X} $ of degree $ r $ in $ \\F_p\\sb{X} $ is a divisor of $ X^{p^r - 1} - 1 $.\n\\end{lemma}\n\n\\begin{proof}\nLet $ K = \\F_p\\rb{\\alpha} $ where $ \\alpha $ is a root of $ P $. $ \\#K = p^r $ so $ \\alpha^{p^r} - \\alpha $ is zero in $ K $. So $ P\\rb{X} \\mid X^{p^r} - X $.\n\\end{proof}\n\n\\begin{corollary}\nAny two finite fields $ K, K' $ of cardinality $ p^r $ are isomorphic.\n\\end{corollary}\n\n\\begin{proof}\nChoose $ \\alpha \\in K $ such that $ \\alpha $ generates $ K $ over $ \\F_p $. We can then write $ K = \\F_p\\rb{\\alpha} \\cong \\F_p\\sb{X} / \\ab{P\\rb{X}} $, where $ P\\rb{X} $ is the minimal polynomial of $ \\alpha $ over $ \\F_p $. In particular $ P\\rb{X} $ is irreducible of degree $ r $. Since $ P\\rb{X} $ divides $ X^{p^r - 1} - 1 $ in $ \\F_p\\sb{X} $, it also divides $ X^{p^r - 1} - 1 $ in $ K'\\sb{X} $. Since in $ K'\\sb{X} $, $ X^{p^r - 1} - 1 $ factors into linear factors, $ P\\rb{X} $ also factors into linear factors over $ K' $. In particular there exists a root $ \\alpha' \\in K' $ of $ P\\rb{X} $ in $ K'\\sb{X} $ such that $ P\\rb{\\alpha'} = 0 $. Then the map $ \\F_p\\sb{X} \\to K' $ that sends $ X $ to $ \\alpha' $ has kernel $ \\ab{P\\rb{X}} $ and induces a map\n$$\n\\begin{tikzcd}[column sep=1in]\nK \\arrow{r}{Q\\rb{\\alpha} \\mapsto Q\\rb{X}}[swap]{\\sim} & \\dfrac{\\F_p\\sb{X}}{\\ab{P\\rb{X}}} \\arrow[hookrightarrow]{r}{Q\\rb{X} \\mapsto Q\\rb{\\alpha'}} & K'\n\\end{tikzcd}\n$$\nSince this is map of fields from $ K $ to $ K' $ that takes $ \\alpha $ to $ \\alpha' $ it is injective. Since both fields $ K, K' $ have the same cardinality $ p^r $, it is also surjective and an isomorphism.\n\\end{proof}\n\nIf $ k = \\Q $, $ \\Q\\sb{X} / \\ab{X^2 - p} $ are pairwise nonisomorphic extensions of degree $ \\alpha $ for every prime $ p $.\n\n\\marginpar{Lecture 11 \\\\ Monday \\\\ 29/10/18}\n\nLecture 11 is a problem class.\n\n\\marginpar{Lecture 12 \\\\ Wednesday \\\\ 31/10/18}\n\n\\section{$ R $-modules}\n\n\\subsection{Definitions}\n\n\\begin{definition}\nAn $ R $-module $ M $ is a set, together with two operations $ + : M \\times M \\to M $ and $ \\cdot : R \\times M \\to M $, such that\n\\begin{enumerate}\n\\item $ \\rb{M, +} $ makes $ M $ into an abelian group with identity $ 0_M $,\n\\item $ r\\rb{m + m'} = rm + rm' $ for all $ r \\in R $, $ m, m' \\in M $,\n\\item $ \\rb{r + r'} = rm + r'm $ for all $ r, r' \\in R $, $ m \\in M $,\n\\item $ \\rb{rr'}m = r\\rb{r'm} $ for all $ r, r' \\in R $, $ m \\in M $, and\n\\item $ 1_R \\cdot m = m $ for all $ m \\in M $.\n\\end{enumerate}\n\\end{definition}\n\n\\begin{note}\nFor an abelian group $ M $, let $ End\\rb{M} $ denote the set of homomorphisms $ M \\to M $ of abelian groups. $ End\\rb{M} $ is a noncommutative ring. $ 2 $ if and only if for all $ r \\in R $, $ \\cdot r : M \\to M $ lives in $ End\\rb{M} $. $ 3 $, $ 4 $, and $ 5 $ if and only if the map $ R \\to End\\rb{M} $ given by $ 2 $ is a homomorphism of rings.\n\\end{note}\n\n\\begin{example}\nThe usual addition and multiplication on $ R $ naturally makes $ R $ into an $ R $-module. More generally, any ideal $ I $ of $ R $ is an $ R $-module with the usual addition and multiplication.\n\\end{example}\n\n\\begin{example}\nIf $ f : R \\to S $, then $ f $ makes $ S $ into an $ R $-module, where the addition $ + $ is the usual addition in $ S $, and the multiplication law is defined by $ r \\cdot s = f\\rb{r} \\cdot_S s $ for all $ r \\in S $, $ s \\in S $. In particular any quotient $ R / I $ is an $ R $-module. More generally, if $ f : R \\to S $ is a homomorphism, and $ M $ is any $ S $-module, then $ M $ is also an $ R $-module via $ r \\cdot m = f\\rb{r} \\cdot m $. In particular, $ R \\to R / I $ lets us treat any $ R / I $-module $ M $ as an $ R $-module. Note that if $ M $ is an $ R / I $-module, then for all $ r \\in I $, $ m \\in M $, $ r \\cdot m = 0 $. We say that $ I $ \\textbf{annihilates} $ M $ in this situation. Conversely, if $ M $ is an $ R $-module and $ r \\cdot m = 0 $ for all $ r \\in I $, $ m \\in M $, then $ M $ naturally has the structure of an $ R / I $-module. Given $ r + I \\in R / I $, $ m \\in M $, we define $ \\rb{r + I} \\cdot m = rm $. If $ r + I = r' + I $, then $ r - r' \\in I $, so $ rm - r'm = \\rb{r - r'}m = 0 $ by assumption.\n\\end{example}\n\n\\begin{example}\nLet $ R = \\Z $, and let $ M $ be an abelian group. Then $ M $ has the unique natural structure of $ \\Z $-module, as follows. Property $ 3 $ from the module axioms shows that\n$$ n \\cdot m = \\begin{cases} m + \\dots + m & n > 0 \\\\ 0 & n = 0 \\\\ \\rb{-m} + \\dots + \\rb{-m} & n < 0 \\end{cases}. $$\nThus the multiplication law $ \\Z \\times M \\to M $ is forced on us, and one checks that it does satisfy properties $ 2 $ to $ 5 $ above. Informally, we say that abelian groups are $ \\Z $-modules.\n\\end{example}\n\n\\begin{example}\nIf $ R $ is a field, then $ R $-modules are just $ R $-vector spaces.\n\\end{example}\n\n\\begin{example}\nLet $ S $ be a set, and let $ M_S $ be the set of $ R $-valued functions $ f : S \\to R $. We add and multiply pointwise. For $ f, g \\in M_S $, we can define $ f + g $ as the function that takes $ s \\in S $ to $ f\\rb{s} + g\\rb{s} $, and $ rf $ as the function that takes $ s $ to $ r \\cdot f\\rb{s} $. $ M_S $ is clearly an $ R $-module. Also of interest is the $ R $-submodule $ F_S $ of $ M_S $ that consists of functions $ f : S \\to R $ such that $ f\\rb{s} = 0_R $ for all but finitely many $ s $. The $ R $-module $ F_S $ is called the \\textbf{free $ R $-module} on the set $ S $ and will be very important for us.\n\\end{example}\n\n\\subsection{Submodules, quotients, and direct sums}\n\n\\begin{definition}\nLet $ M $ be an $ R $-module. A subset $ N $ of $ M $ is an \\textbf{$ R $-submodule} of $ M $ if $ N $ is closed under addition and multiplication by elements of $ R $. That is, $ N $ is an additive subgroup of $ M $, and for all $ n \\in N $, $ r \\in R $, we have $ rN \\subseteq N $. In particular, the ideals of $ R $ are just the $ R $-submodules of $ R $.\n\\end{definition}\n\n\\begin{definition}\nIf $ S $ is any subset of $ M $, we define the \\textbf{$ R $-submodule of $ M $ generated by $ S $} to be the set of all elements of $ M $ of the form $ r_1s_1 + \\dots + r_ns_n $, where the $ r_i $ are elements of $ R $ and the $ s_i $ are elements of $ S $. It is the smallest $ R $-submodule of $ M $ containing $ S $.\n\\end{definition}\n\n\\begin{definition}\nAn $ R $-module $ M $ is a \\textbf{finitely generated} $ R $-module if $ M $ admits a finite subset $ S $ of $ M $ such that the $ R $-submodule of $ M $ generated by $ S $ is all of $ M $. We say $ S $ is a \\textbf{generating set} for $ M $.\n\\end{definition}\n\n\\begin{definition}\nLet $ M $ be an $ R $-module and $ N $ be an $ R $-submodule of $ M $. We say two elements $ m, m' $ of $ M $ are \\textbf{congruent modulo $ N $} if their difference $ m - m' $ lies in $ N $. This is easily seen to be an equivalence relation, and the equivalence classes are the cosets of the form $ m + N $, for $ m \\in M $. The set of equivalence classes is denoted $ M / N $. It has the natural structure of an $ R $-module, where $ \\rb{m + N} + \\rb{m' + N} = \\rb{m + m'} + N $ and $ r \\cdot \\rb{m + N} = rm + N $. This $ R $-module is called the \\textbf{quotient of $ M $ by $ N $}. If $ m + N = m' + N $, then $ m - m' \\in N $, so $ rm - rm' = r\\rb{m - m'} \\in N $. So well-defined. Have a natural map $ M \\to M / N $ taking $ m $ to $ m + N $.\n\\end{definition}\n\n\\begin{definition}\nGiven two $ R $-modules $ M_1 $ and $ M_2 $, the \\textbf{direct sum} $ M_1 \\oplus M_2 $ is the set of ordered pairs $ \\rb{m_1, m_2} $ with $ \\rb{m_1, m_2} + \\rb{m_1', m_2'} = \\rb{m_1 + m_1', m_2 + m_2'} $ and $ r\\rb{m_1, m_2} = \\rb{rm_1, rm_2} $ for $ m_1, m_1' \\in M_1 $, $ m_2, m_2' \\in M_2 $, and $ r \\in R $.\n\\end{definition}\n\n\\begin{example}\nLet $ M $ be an $ R $-module and $ I $ an ideal of $ R $. Then we can form the $ R $-submodule $ IM $ of $ M $ consisting of all elements of $ M $ of the form $ i_1m_1 + \\dots + i_rm_r $ where the $ i_j $ are in $ I $ and the $ m_j $ are in $ M $. This is an $ R $-submodule of $ M $, so we can form the quotient $ M / IM $. Then $ M / IM $ is certainly an $ R $-module, but it is also an $ R / I $-module. One can define multiplication $ R / I \\times M / IM \\to M / IM $ by $ \\rb{r + I}\\rb{m + IM} = rm + IM $. As always one has to check that this is well-defined, but this is straightforward. We need that if $ r - r' $ lies in $ I $, and $ m - m' $ lies in $ IM $, then $ rm - r'm' $ lies in $ IM $. But $ rm - r'm' = \\rb{r - r'}m + r'\\rb{m - m'} $ which is clearly in $ IM $.\n\\end{example}\n\n\\subsection{Module homomorphisms, kernels, and images}\n\n\\begin{definition}\nA map $ f : M \\to N $ of $ R $-modules is called a \\textbf{homomorphism of $ R $-modules} if\n\\begin{enumerate}\n\\item $ f $ is a homomorphism of the underlying abelian groups, and\n\\item $ f\\rb{rm} = rf\\rb{m} $ for all $ r \\in R $ and $ m \\in M $.\n\\end{enumerate}\n\\end{definition}\n\nWarning that a ring homomorphism $ R \\to R $ satisfies $ f\\rb{rr'} = f\\rb{r}f\\rb{r'} $, but an $ R $-module homomorphism $ R \\to R $ satisfies $ f\\rb{rr'} = rf\\rb{r'} $.\n\n\\begin{definition}\nThe kernel of $ f : M \\to N $ is the set $ \\cb{m \\in M \\mid f\\rb{m} = 0} $, an $ R $-submodule of $ M $. The image of $ f : M \\to N $ is the set $ \\cb{n \\in N \\mid \\exists m \\in M, \\ f\\rb{m} = n} $, an $ R $-submodule of $ N $.\n\\end{definition}\n\nIt is easy to see that the kernel and image of a homomorphism of $ R $-modules $ f : M \\to N $ are $ R $-submodules of $ M $ and $ N $, respectively.\n\n\\begin{note}\nIn particular there is a natural homomorphism from $ M $ to $ M / N $, taking $ m $ to $ m + N $. This homomorphism has the following universal property, exactly analogous to the universal property of the quotient construction for rings.\n\\end{note}\n\n\\begin{proposition}[Universal property of the quotient]\nLet $ N $ be an $ R $-submodule of $ M $, and let $ f : M \\to M' $ be an $ R $-module homomorphism whose kernel contains $ N $. Then there is unique homomorphism $ \\bar{f} : M / N \\to M' $ such that $ f\\rb{m + N} = f\\rb{m} $ for all $ m \\in M $. In particular the kernel of $ \\bar{f} $ is the image of $ Ker\\rb{f} $ in $ M / N $.\n\\end{proposition}\n\n\\begin{proof}\nThe proof is identical to that for quotient rings, and will be omitted.\n\\end{proof}\n\n\\subsection{Free modules}\n\n\\begin{definition}\nLet $ M $ be an $ R $-module. A subset $ S $ of $ M $ is a \\textbf{basis} for $ M $ if the following two conditions hold.\n\\begin{enumerate}\n\\item $ S $ \\textbf{spans $ M $ over $ R $}. For all $ m \\in M $, there exist $ s_1, \\dots, s_n \\in S $ finite and $ r_1, \\dots, r_n \\in R $ such that $ m = r_1s_1 + \\dots + r_ns_n $, that is the $ R $-submodule of $ M $ generated by $ S $ is all of $ M $.\n\\item $ S $ is \\textbf{$ R $-linearly independent}. For any collection $ s_1, \\dots, s_n $ of distinct elements of $ S $, and any $ r_1, \\dots, r_n \\in R $, $ r_1s_1 + \\dots + r_ns_n = 0 $ is nonzero in $ M $ unless all $ r_i $ are zero.\n\\end{enumerate}\n\\end{definition}\n\n\\begin{definition}\nAn $ R $-module $ M $ that has a basis $ S $ is called a \\textbf{free} $ R $-module. The cardinality $ n $ of the basis $ S $ is called the \\textbf{rank} of the free $ R $-module $ M $ over $ R $.\n\\end{definition}\n\n\\marginpar{Lecture 13 \\\\ Friday \\\\ 02/11/18}\n\n\\begin{remark}\nIf $ R $ is a field, then the notion of a basis for an $ R $-module coincides with the usual notion for vector spaces. In this case, at least if one assumes the axiom of choice, every $ R $-module has a basis. When $ R $ is not a field only very special modules have bases. For instance any quotient $ R / I $ of $ R $, for $ I $ a nonzero ideal, has no basis.\n\\end{remark}\n\n\\begin{example}\nThe ring $ R $ is a free module of rank one over $ R $, with basis $ \\cb{1_R} $. More generally any unit $ u \\in R^* $ gives a basis of $ R $ as an $ R $-module.\n\\end{example}\n\nRecall that the free module $ F_S $ on a set $ S $ was defined to be the set of functions $ f : S \\to R $ such that $ f\\rb{s} = 0 $ for all but finitely many $ s \\in S $. For each $ s \\in S $, we have an element $ e_s $ of $ F_S $ defined by $ e_s\\rb{t} = 0 $ for all $ t \\in S $ with $ t \\ne s $, $ e_s\\rb{s} = 1 $. Claim that the $ e_s $ form a basis for $ F_S $. In particular, given $ f : R \\to S $ with $ f\\rb{s} = 0 $ for all but finitely many $ s $, let $ s_1, \\dots, s_n $ be the set of elements in $ S $ on which $ f\\rb{s_i} $ is nonzero. Set $ r_i = f\\rb{s_i} $. Claim that $ f = r_1e_{s_1} + \\dots + r_ne_{s_n} $. If $ f\\rb{s} = 0 $, then $ s \\notin \\cb{s_1, \\dots, s_n} $ so $ e_{s_i}\\rb{s} = 0 $ for all $ i $. For any $ i $, $ e_{s_i}\\rb{s_j} = 0 $ if $ i \\ne j $ and $ e_{s_i}\\rb{s_i} = 1 $, so $ \\rb{\\sum_{i = 1}^n r_ie_{s_i}}\\rb{s_j} = r_j = f\\rb{s_j} $. Then $ f $ can be written as $ r_1e_{s_1} + \\dots + r_ne_{s_n} $, so the $ e_s $ span $ F_S $. On the other hand, for all $ s_1, \\dots, s_n \\in S $ distinct with $ \\sum_{i = 1}^n r_ie_{s_i} = 0 $, $ \\sum_{i = 1}^n r_ie_{s_i} $ takes the value $ r_i $ by evaluating at $ s_i $ for all $ i $, and thus is only the zero function when all $ r_i $ are zero for all $ i $, so we do have $ R $-linear independence. Thus $ F_S $ is free, justifying its name.\n\n\\begin{proposition}\nLet $ F_1, F_2 $ be free modules with basis $ S_1, S_2 $. Then $ F_1 \\oplus F_2 $ is free with basis\n$$ \\cb{\\rb{s, 0} \\mid s \\in S_1} \\cup \\cb{\\rb{0, s'} \\mid s' \\in S_2}. $$ Moreover, if $ F_1 $ and $ F_2 $ are free of finite ranks $ n_1 $ and $ n_2 $ respectively, then $ F_1 \\oplus F_2 $ is free of rank $ n_1 + n_2 $.\n\\end{proposition}\n\n\\begin{proof}\nFor linear independence, let $ s_1, \\dots, s_m \\in S_1 $ and $ s_1', \\dots, s_l' \\in S_2 $ be distinct. Suppose we have $ r_1, \\dots, r_m, r_1', \\dots, r_l' \\in R $ such that $ r_1\\rb{s_1, 0} + \\dots + r_m\\rb{s_m, 0} + r_1'\\rb{0, s_1'} + \\dots + r_l'\\rb{0, s_l'} = 0 $. Then $ r_1s_1 + \\dots + r_ms_m = 0 $ in $ M_1 $ and $ r_1's_1' + \\dots + r_l's_l' = 0 $ in $ M_2 $ gives all $ r_i, r_i' $ are zero. For spanning set, let $ \\rb{m, m'} \\in M_1 \\oplus M_2 $. Write $ m = r_1s_1 + \\dots + r_ms_m $ for $ s_i \\in S_1 $ and $ m' = r_1's_1' + \\dots + r_l's_l' $ for $ s_i' \\in S_2 $, then $ \\rb{m, m'} = r_1\\rb{s_1, 0} + \\dots + r_m\\rb{s_m, 0} + r_1'\\rb{0, s_1'} + \\dots + r_l'\\rb{0, s_l'} $. Thus $ S_1 \\cup S_2 $ is a basis for $ F_1 \\oplus F_2 $, which immediately proves the claim.\n\\end{proof}\n\nFree modules have the following universal property.\n\n\\begin{proposition}[Universal property of free modules]\nLet $ F_S $ be a free $ R $-module on a set $ S $. Then for any $ R $-module $ M $, and any map of sets $ f : S \\to M $, there is a unique homomorphism of $ R $-modules $ \\phi_f : F_S \\to M $ such that $ \\phi_f\\rb{e_s} = f\\rb{s} $ for all $ s \\in S $.\n\\end{proposition}\n\n\\begin{proof}\nDefine $ \\phi_f $ by $ \\phi_f\\rb{g} = \\sum_{s \\in S, \\ g\\rb{s} \\ne 0} g\\rb{s}f\\rb{s} $. Note that this is a finite sum since all but finitely many $ s $ have $ g\\rb{s} = 0 $. Then it is clear that this is a homomorphism of $ R $-modules. On the other hand suppose $ \\phi $ is any other map $ F_S \\to N $ with $ \\phi\\rb{e_s} = f\\rb{s} $ for all $ s $. Then we can write $ g = \\sum_{s \\in S, \\ g\\rb{s} \\ne 0} g\\rb{s}e_s $, again a finite sum, so\n$$ \\phi\\rb{g} = \\sum_{s \\in S, \\ g\\rb{s} \\ne 0} g\\rb{s}\\phi\\rb{e_s} = \\sum_{s \\in S, \\ g\\rb{s} \\ne 0} g\\rb{s}f\\rb{s}, $$\nso uniqueness is clear.\n\\end{proof}\n\nThe image of $ \\phi_f $ is the submodule of $ N $ generated by the elements $ f\\rb{s} $, for $ s \\in S $.\n\n\\begin{corollary}\nLet $ M $ be a free $ R $-module with a basis $ T $ for $ M $. Let $ S $ be any set of the same cardinality as $ T $, and let $ g : T \\to S $ be any bijection. Then the map $ \\phi_f : F_S \\to M $ is an isomorphism. In particular, any two free $ R $-modules of the same rank are isomorphic.\n\\end{corollary}\n\n\\begin{proof}\nThe map $ \\phi_f : F_S \\to M $ is such that $ \\phi_f\\rb{e_s} = f\\rb{s} $. Since elements of $ T $ are linearly independent, this map is injective. Suppose $ \\phi_f\\rb{g} = 0 $. Can write $ g = \\sum r_ie_{s_i} $ for $ s_i $ distinct, then $ \\phi_f\\rb{g} = \\sum r_if\\rb{s_i} $. Since $ s_i $ are distinct, $ f\\rb{s_i} $ are distinct elements of $ T $, so $ \\sum r_if\\rb{s_i} = 0 $ gives all $ r_i $ are zero, so $ g = 0 $. Since elements of $ T $ span $ M $, this map is surjective. Given $ m \\in M $, write $ m = \\sum r_it_i $. For all $ i $, find $ s_i $, with $ f\\rb{s_i} = t_i $. Then $ \\phi_f\\rb{\\sum r_ie_{s_i}} = \\sum r_it_i = m $. Thus $ M $ is isomorphic to $ F_S $. Since $ M $ was arbitrary, any module of rank equal to the cardinality of $ S $ is isomorphic to $ F_S $ and the result follows.\n\\end{proof}\n\n\\begin{note}\nIt is also true, but harder to prove, that if $ M, N $ are free of different ranks, then $ M \\ncong N $.\n\\end{note}\n\n\\subsection{Generators and relations}\n\nNow let $ M $ be any $ R $-module, and let $ S = \\cb{m_1, \\dots, m_t} $ be a finite subset of $ M $ generating $ M $. Then we have a natural map $ F_S \\to M $ taking $ e_i $ to $ m_i $ for all $ m_i \\in S $, and this map is surjective. In particular, let $ K $ be the kernel of this map, then $ M \\cong F_S / K $. Elements of the kernel $ K $ are called \\textbf{relations} among $ S $.\n\n\\marginpar{Lecture 14 \\\\ Monday \\\\ 05/11/18}\n\nExplicitly, an element of $ K $ is a map $ f : S \\to R $ such that $ f\\rb{s} = 0 $ for all but finitely many $ s $, and $ \\sum_{s \\in S} f\\rb{s}s = 0 $. In other words, each element of $ K $ encodes a linear relation among the elements of $ S $. It is a measure of how far the elements of $ S $ are from being linearly independent. Let $ T = \\cb{k_1, \\dots, k_s} $ be a subset of $ K $ that generates $ K $. Then in the same way as above, we get a surjection $ F_T \\twoheadrightarrow K $ taking $ e_i $ to $ k_i $, with $ F_T $ a free module of rank $ s $. Composing with the inclusion of $ K $ in $ F_S $ gives us a map $ \\phi : F_T \\to F_S $ whose image is $ K $. The map $ \\phi $ determines $ M $ up to isomorphism with the quotient $ F_S / K $, and hence with $ F_S / \\phi\\rb{F_T} $. A description of a module as a quotient of a free module by the image of a map of free modules is called a \\textbf{presentation} of $ M $. If both modules have finite rank the presentation is called \\textbf{finite}. A module that has a finite presentation is called \\textbf{finitely presented}. Put another way, a presentation is a description of a module $ M $ in terms of\n\\begin{enumerate}\n\\item a generating set $ S $ for $ M $, and\n\\item a generating set $ T $ for the linear relations satisfied by $ S $.\n\\end{enumerate}\nWhen $ S $ and $ T $ are finite we can encode a presentation in a matrix, called the \\textbf{presentation matrix}. Write $ S = \\cb{e_1, \\dots, e_t} $ and $ T = \\cb{f_1, \\dots, f_s} $. Then $ \\phi $ is determined by $ \\phi\\rb{f_1}, \\dots, \\phi\\rb{f_s} $. For each $ i $ we can write $ \\phi\\rb{f_i} $ as a sum $ \\sum_{j = 1}^t r_{ij}e_{s_j} $, and let $ A $ be the $ s $ by $ t $ matrix whose $ i, j $ entry is $ r_{ij} $. Then $ A $ gives a map from $ R^t $ to $ R^s $, and the quotient of $ R^s $ by the submodule $ AR^t $ of $ R^s $ is isomorphic to $ M $.\n\n\\begin{example}\nLet $ R = \\Z $ and $ M = \\Z / n\\Z $ generated by $ \\sb{1}_n $. Map $ \\Z \\to M $ is the quotient map with kernel $ \\ab{n} $. So presentation matrix is just $ \\rb{n} $.\n\\end{example}\n\n\\begin{example}\nLet $ R = \\Z\\sb{\\sqrt{-5}} $ and $ I = \\ab{2, 1 + \\sqrt{-5}} $. $ R^2 \\twoheadrightarrow I $ by $ e_1 \\mapsto 2 $ and $ e_2 \\mapsto 1 + \\sqrt{-5} $. $ 2e_2 - \\rb{1 + \\sqrt{-5}}e_1 \\mapsto 0 $ in $ I $, and since $ \\rb{2}\\rb{3} = \\rb{1 + \\sqrt{-5}}\\rb{1 - \\sqrt{-5}} $, $ 3e_1 - \\rb{1 - \\sqrt{-5}}e_2 \\mapsto 0 $ in $ I $. Claim that the two relations $ \\rb{1 + \\sqrt{-5}}e_1 - 2e_2 $ and $ 3e_1 - \\rb{1 - \\sqrt{-5}}e_2 $ generate $ K $. Let $ ae_1 + be_2 $ be a relation, so $ a, b \\in R $ and $ 2a + \\rb{1 - \\sqrt{-5}}b = 0 $, that is $ a = \\rb{\\rb{1 + \\sqrt{-5}} / 2}b $. Question is for which $ b $ does $ \\rb{\\rb{1 + \\sqrt{-5}} / 2}b $ lie in $ R $. Claim that the set of such $ b $ is an ideal $ J $ of $ R $. $ 2 \\in J $ and $ 1 - \\sqrt{-5} \\in J $ so $ J $ contains $ \\ab{2, 1 - \\sqrt{-5}} $. $ 1 \\notin J $, since $ \\ab{2, 1 - \\sqrt{-5}} $ is maximal, $ J = \\ab{2, 1 - \\sqrt{-5}} $. So we have a map $ R^2 \\to R^2 $ with matrix\n$$ \\two{1 + \\sqrt{-5} & 3}{-2 & -1 + \\sqrt{-5}} $$\npresenting $ I $.\n\\end{example}\n\nGeneral idea is if we have a presentation matrix $ A : R^t \\to R^s $ for $ M $, with $ s $ rows and $ t $ columns, then $ BAC $ is also a presentation matrix for $ M $, where $ B $ is $ s \\times s $ and $ C $ is $ t \\times t $, and $ B $ and $ C $ are invertible matrices with inverse matrix entries in $ R $.\n\n\\section{Noetherian rings and modules}\n\n\\subsection{Definitions and basic properties}\n\n\\begin{definition}\nLet $ R $ be a ring and let $ M $ be an $ R $-module. We say $ M $ is \\textbf{Noetherian} if every increasing infinite chain\n$$ M_1 \\subseteq M_2 \\subseteq \\dots $$\nof $ R $-submodules $ M_i $ of $ M $ is \\textbf{eventually constant}. That is, for any such chain, there exists $ N $ such that we have $ M_i = M_N $ for all $ i \\ge N $. A ring $ R $ is Noetherian if $ R $ is Noetherian as an $ R $-module over itself. Since the $ R $-submodules of $ R $ are just the ideals of $ R $, a ring $ R $ is Noetherian if every increasing infinite chain\n$$ I_1 \\subseteq I_2 \\subseteq \\dots $$\nof ideals $ I_j $ of $ R $ is eventually constant.\n\\end{definition}\n\nThe following result about Noetherian $ R $-modules is fundamental.\n\n\\begin{proposition}\nAn $ R $-module $ M $ is Noetherian if and only if every $ R $-submodule $ N $ of $ M $ is finitely generated.\n\\end{proposition}\n\n\\begin{proof}\nSuppose first that $ M $ is Noetherian, and let $ N $ be an $ R $-submodule of $ M $. Choose an element $ n_0 $ of $ N $, and let $ N_0 $ be the $ R $-submodule of $ N $ generated by $ n_0 $. If $ N_0 $ is all of $ N $, then $ N $ is finitely generated. Otherwise, choose $ n_1 $ in $ N \\setminus N_0 $, and let $ N_1 $ be the $ R $-submodule of $ N $ generated by $ n_0 $ and $ n_1 $. If $ N $ is not finitely generated, we may continue this process indefinitely, choosing for each $ i $ an $ n_i $ in $ N \\setminus N_{i - 1} $, which is nonempty since $ N $ is not finitely generated, and letting $ N_i $ be generated by $ n_0, \\dots, n_i $. In this way we obtain a strictly increasing infinite chain\n$$ N_0 \\subsetneq N_1 \\subsetneq \\dots $$\nof submodules of $ M $, contradicting the fact that $ M $ is Noetherian. Conversely, suppose that every $ R $-submodule of $ M $ is finitely generated, and let\n$$ M_0 \\subseteq M_1 \\subseteq \\dots $$\nbe an increasing chain. We must show that this chain is eventually constant. Let $ N $ be the union of the submodules $ M_i $. Note that $ N $ is an $ R $-submodule of $ M $. Thus $ N $ is finitely generated, say by $ n_1, \\dots, n_s $. If $ n_1, n_2 \\in N $, then there exist $ i, j $ with $ n_1 \\in M_i $, $ n_2 \\in M_j $. If $ d \\ge i, j $, $ n_1, n_2 \\in M_d $, so $ n_1 + n_2 \\in M_d $ gives $ n_1 + n_2 \\in N $. Since $ N $ is the union of the $ M_j $, there exist $ i_1, \\dots, i_s $ such that $ n_j $ is in $ M_{i_j} $ for all $ j $. Let $ d $ be the largest of the $ i_j $. Then $ M_d $ contains $ n_1, \\dots, n_s $ so it contains $ N $. In particular for any $ d' \\ge d $ we have $ N \\subseteq M_d \\subseteq M_{d'} \\subseteq N $, so $ N = M_d = M_{d'} $ for all such $ d' $ and the chain is constant after $ M_d $.\n\\end{proof}\n\n\\marginpar{Lecture 15 \\\\ Wednesday \\\\ 07/11/18}\n\n\\begin{corollary}\nLet $ R $ be a PID. Then $ R $ is Noetherian.\n\\end{corollary}\n\n\\begin{proof}\nEvery ideal of $ R $ is principal, hence finitely generated.\n\\end{proof}\n\n\\begin{example}\nAny field is Noetherian.\n\\end{example}\n\n\\begin{example}\nThe ring $ \\C\\sb{X^{\\Q_{\\ge 0}}} $ is not Noetherian. The ideal consisting of all elements with no constant term is not finitely generated.\n\\end{example}\n\n\\subsection{Finitely generated modules over Noetherian rings}\n\nPlan is\n\\begin{enumerate}\n\\item show that Noetherianness has strong consequences, and\n\\item use these properties to show $ R $ is Noetherian gives $ R\\sb{X} $ is Noetherian and other consequences.\n\\end{enumerate}\nThe goal of this section is to prove the following theorem.\n\n\\begin{theorem}\n\\label{thm:8.2.1}\nAny finitely generated $ R $-module $ M $ over a Noetherian ring $ R $ is Noetherian.\n\\end{theorem}\n\nWe proceed in several steps.\n\n\\begin{proposition}\nLet $ M $ be a Noetherian $ R $-module. Then for any submodule $ N $ of $ M $,\n\\begin{enumerate}\n\\item $ N $ is Noetherian, and\n\\item $ M / N $ is Noetherian.\n\\end{enumerate}\n\\end{proposition}\n\n\\begin{proof}\n\\hfill\n\\begin{enumerate}\n\\item Since $ M $ is Noetherian, any submodule of $ M $ is finitely generated, and thus any submodule of $ N $ is finitely generated.\n\\item Given a submodule $ N' $ of $ M / N $, let $ \\widetilde{N'} $ be its preimage in $ N $ under the canonical quotient map $ f : M \\to M / N $. We have a surjection from $ \\widetilde{N'} $ to $ N' $ induced by $ f $. $ \\widetilde{N'} \\subseteq M $, so $ \\widetilde{N'} $ is finitely generated, say by $ n_1, \\dots, n_s $. Claim that $ f\\rb{n_1}, \\dots, f\\rb{n_s} $ generate $ N' $. Given $ n \\in N' $, there exists $ \\widetilde{n} \\in \\widetilde{N'} $ such that $ f\\rb{\\widetilde{n}} = n $. Write $ \\widetilde{n} = r_1n_1 + \\dots + r_sn_s $ for $ r_i \\in R $. Then $ n = f\\rb{\\widetilde{n}} = r_1f\\rb{n_1} + \\dots + r_sf\\rb{n_s} $.\n\\end{enumerate}\n\\end{proof}\n\n\\begin{proposition}\nLet $ M $ be an $ R $-module, let $ N $ be a Noetherian submodule of $ M $, and suppose that $ M / N $ is Noetherian. Then $ M $ is Noetherian.\n\\end{proposition}\n\n\\begin{proof}\nLet $ M' $ be a submodule of $ M $. Then $ M' \\cap N $ is a submodule of $ M $, hence finitely generated. Let $ a_1, \\dots, a_s \\in M' \\cap N $ generate $ M' \\cap N $. Let $ \\bar{M'} $ denote the image of $ M' $ in $ M / N $. This is a submodule of $ M / N $ and thus finitely generated. Let $ \\bar{b_1}, \\dots, \\bar{b_t} \\in \\bar{M'} \\subseteq M / N $ generate $ \\bar{M'} $, and choose elements $ b_1, \\dots, b_t $ of $ M' $ mapping to $ \\bar{b_1}, \\dots, \\bar{b_t} $ in $ M / N $, respectively. We now show that $ a_1, \\dots, a_s, b_1, \\dots, b_t $ is a generating set for $ M' $, proving the claim. Given any $ m \\in M' $, let $ \\bar{m} $ be its image in $ M / N $ under $ f : M' \\to \\bar{M'} $. Then we can write $ \\bar{m} $ as a sum $ r_1\\bar{b_1} + \\dots + r_t\\bar{b_t} $ for some $ r_1, \\dots, r_t \\in R $. Let $ m' = m - r_1b_1 - \\dots - r_tb_t $. Then the image of $ m' $ in $ M / N $ is $ f\\rb{m'} = \\bar{m} - r_1\\bar{b_1} - \\dots - r_t\\bar{b_t} = 0 $. So $ m' $ lies in $ N $. $ m \\in M', r_1b_1 \\in M', \\dots, r_tb_t \\in M' $ so $ m' $ also lies in $ M' $. So it lies in $ M' \\cap N $. We can thus write $ m' $ as $ q_1a_1 + \\dots + q_sa_s $ for some $ q_1, \\dots, q_s \\in R $. We then have\n$$ m = q_1a_1 + \\dots + q_sa_s + r_1b_1 + \\dots + r_tb_t, $$\nproving the claim.\n\\end{proof}\n\n\\begin{corollary}\nLet $ M $ and $ N $ are Noetherian $ R $-modules, then so is $ M \\oplus N $.\n\\end{corollary}\n\n\\begin{proof}\nWe have a surjection $ M \\oplus N \\to M $ taking $ \\rb{m, n} $ to $ m $. Its kernel $ K $ is the set of pairs of $ M \\oplus N $ of the form $ \\rb{0, n} $, which is isomorphic to $ N $ by the map $ N \\to K $ taking $ n $ to $ \\rb{0, n} $, and hence Noetherian. The surjection $ M \\oplus N \\to M $ descends to an isomorphism $ \\rb{M \\oplus N} / K \\cong M $, so that $ \\rb{M \\oplus N} / K $ is Noetherian. Thus $ M \\oplus N $ is Noetherian.\n\\end{proof}\n\nNow assume $ R $ is Noetherian. Then $ R, R \\oplus R, \\dots $ are all Noetherian $ R $-modules, that is the following.\n\n\\begin{corollary}\nIf $ R $ is Noetherian, then any free $ R $-module of finite rank is Noetherian.\n\\end{corollary}\n\n\\begin{proof}\nA free $ R $-module of rank $ s $ is the direct sum of $ s $ copies of $ R $, each of which is Noetherian as an $ R $-module when $ R $ is Noetherian.\n\\end{proof}\n\n\\begin{proof}[Proof of Theorem \\ref{thm:8.2.1}]\nLet $ M $ be a finitely generated $ R $-module, and let $ m_1, \\dots, m_s $ be a set of generators for $ M $. Then if $ R^s $ is a free $ R $-module of rank $ s $, with generators $ e_1, \\dots, e_s $, we have a surjection of $ R^s $ onto $ M $ taking $ e_i $ to $ m_i $ for all $ i $. Let $ K $ be the kernel. Then $ M $ is isomorphic to $ R^s / K $, and $ R^s $ is a Noetherian $ R $-module, so $ M $ is Noetherian as well.\n\\end{proof}\n\n\\section{Polynomial rings in several variables}\n\n\\subsection{The Hilbert basis theorem}\n\nIn this section, we will use the ideas of the previous section to establish the following key result about polynomial rings, known as the Hilbert basis theorem.\n\n\\begin{theorem}[Hilbert basis theorem]\n\\label{thm:9.1.1}\nLet $ R $ be a Noetherian ring. Then $ R\\sb{X} $ is Noetherian.\n\\end{theorem}\n\n\\marginpar{Lecture 16 \\\\ Friday \\\\ 09/11/18}\n\nOver a field, if $ Q\\rb{X} = a_nX^n + \\dots $ and $ P\\rb{X} = b_mX^m + \\dots $ for $ m \\ge n $ and $ a_n, b_m \\ne 0 $, then\n$$ \\deg\\rb{P\\rb{X} - \\dfrac{b_m}{a_n}X^{m - n}Q\\rb{X}} < \\deg\\rb{P\\rb{X}}. $$\nOver a ring, this only goes so far. Over $ \\Z $, cannot use a multiple of $ 3X + 4 $ to reduce the degree of $ a_nX^n + \\dots $ unless $ 3 \\mid a_n $. Let $ P\\rb{X} = b_0 + \\dots + b_nX_n $, with $ b_n \\in R $ nonzero. We say that $ b_n $ is the \\textbf{leading coefficient} of $ P\\rb{X} $. In general, if I have $ Q_1\\rb{X}, \\dots, Q_r\\rb{X} $ with degrees $ d_1, \\dots, d_r $ and leading coefficients $ a_1, \\dots, a_r $ and $ P\\rb{X} $ of degree $ d \\ge d_1, \\dots, d_r $ then there exist $ n_1, \\dots, n_r \\in R $ such that\n$$ \\deg\\rb{P\\rb{X} - n_1X^{d - d_1}Q_1\\rb{X} - \\dots - n_rX^{d - d_r}Q_r\\rb{X}} < d, $$\nif and only if leading coefficient of $ P\\rb{X} $ is in the ideal generated by $ a_1, \\dots, a_r $. \n\n\\begin{lemma}\nLet $ R $ be Noetherian and $ I \\subseteq R\\sb{X} $ be an ideal. Let $ J \\subseteq R $ be the set of leading coefficients of polynomials in $ I $. That is, the set of $ a \\in R $ such that there exists a polynomial $ P\\rb{X} $ in $ I $ with leading coefficient $ a $. Then $ J $ is an ideal of $ R $.\n\\end{lemma}\n\n\\begin{proof}\nCertainly if $ a \\in J $ is the leading coefficient of $ P\\rb{X} \\in I $ such that $ P\\rb{X} = aX^n + \\dots $, then for any $ r \\in R $, $ ra $ is the leading coefficient of $ rP\\rb{X} = raX^n + \\dots $ so $ ra \\in J $, so $ J $ is closed under multiplication. On the other hand, if $ a, b \\in J $ are the leading coefficients of $ P\\rb{X} $ and $ Q\\rb{X} $ in $ I $, then let $ n, m $ be the degrees of $ P\\rb{X} = aX^n + \\dots $ and $ Q\\rb{X} = bX^m + \\dots $ respectively. Without loss of generality we may assume $ n \\ge m $. Then $ a + b $ is the leading coefficient of $ P\\rb{X} + X^{n - m}Q\\rb{X} = \\rb{a + b}X^{n + m} + \\dots $, and the latter polynomial is in $ I $ so $ a + b \\in J $. Thus $ J $ is closed under addition, and is therefore an ideal.\n\\end{proof}\n\nNow since $ R $ is Noetherian, $ J $ is finitely generated, say by $ a_1, \\dots, a_s \\in R $. By definition of $ J $, there are thus polynomials $ P_1, \\dots, P_s $ in $ I $, of degrees $ d_1, \\dots, d_n $, such that $ P_i = a_iX^{d_i} + \\dots $ has leading coefficient $ a_i $ for all $ i $. Let $ N $ be the largest of the $ d_i $.\n\n\\begin{lemma}\nGiven $ Q\\rb{X} \\in I $ of degree $ d \\ge N $. Then there exist $ R_1\\rb{X}, \\dots, R_s\\rb{X} \\in R\\sb{X} $ such that $ Q\\rb{X} - R_1\\rb{X}P_1\\rb{X} - \\dots - R_s\\rb{X}P_s\\rb{X} $ has degree less than $ N $.\n\\end{lemma}\n\n\\begin{proof}\nThe proof is by induction on $ d $ and the base case $ d < N $ is clear by setting $ R_i = 0 $ for all $ i $. Suppose the claim is true for polynomials of degree less than or equal to $ d - 1 $, with $ d \\ge N $. Let $ a \\in J $ be the leading coefficient of $ Q\\rb{X} = aX^d + \\dots $, so that $ Q\\rb{X} - aX^d $ has degree at most $ d - 1 $. Since $ a $ lies in $ J $ we can write $ a = r_1a_1 + \\dots + r_sa_s $. Then the leading term of the polynomial\n$$ r_1X^{d - d_1}P_1\\rb{X} + \\dots + r_sX^{d - d_s}P_s\\rb{X} $$\nis $ aX^d $, so the difference\n$$ Q\\rb{X} - r_1X^{d - d_1}P_1\\rb{X} - \\dots - r_sX^{d - d_s}P_s\\rb{X} $$\nhas degree at most $ d - 1 $ and lies in $ I $. By the inductive hypothesis this difference is an $ R\\sb{X} $-linear combination of the $ P_i\\rb{X} $,\n$$ R_1\\rb{X}P_1\\rb{X} + \\dots + R_s\\rb{X}P_s\\rb{X}. $$\nSo\n$$ Q\\rb{X} = \\rb{R_1\\rb{X} + r_1X^{d - d_1}}P_1\\rb{X} + \\dots + \\rb{R_s\\rb{X} + r_sX^{d - d_s}}P_s\\rb{X}. $$\n\\end{proof}\n\n\\begin{proof}[Proof of Theorem \\ref{thm:9.1.1}]\nThe following proof is due to Emmy Noether, and is a vast simplification of Hilbert's original proof. Let $ I $ be an ideal of $ R\\sb{X} $. We want to show that $ I $ is finitely generated. Let $ I_{\\le N} = I \\cap R\\sb{X}_{\\le N} $ be the subset of $ I $ consisting of all polynomials of degree at most $ N $. Then $ I_{\\le N} $ is an $ R $-submodule of the $ R $-module $ R\\sb{X}_{\\le N} $ of all polynomials of degree at most $ N $. The latter is free of rank $ N + 1 $ and generated by $ 1, \\dots, X^N $ as an $ R $-module, so it is finitely generated, hence Noetherian. In particular since $ R $ is Noetherian $ I_{\\le N} $ is also a finitely generated $ R $-module. Let $ T_1\\rb{X}, \\dots, T_k\\rb{X} $ generate $ I_{\\le N} $ as an $ R $-module. We will show that\n$$ P_1\\rb{X}, \\dots, P_s\\rb{X}, T_1\\rb{X}, \\dots, T_k\\rb{X} $$\ngenerate $ I $ as an $ R\\sb{X} $-module. More precisely, we will show that $ Q\\rb{X} $ is an $ R\\sb{X} $-linear combination of the $ P_i\\rb{X} $ and $ T_j\\rb{X} $. Given $ Q\\rb{X} \\in I $, there exist $ R_1\\rb{X}, \\dots, R_s\\rb{X} \\in R\\sb{X} $ such that\n$$ Q\\rb{X} = R_1\\rb{X}P_1\\rb{X} + \\dots + R_s\\rb{X}P_s\\rb{X} + T\\rb{X}, $$\nwith $ T\\rb{X} \\in I_{\\le N} $. There exist $ r_1, \\dots, r_k \\in R $ such that\n$$ T\\rb{X} = r_1T_1\\rb{X} + \\dots + r_kT_k\\rb{X}, $$\nso\n$$ Q\\rb{X} = R_1\\rb{X}P_1\\rb{X} + \\dots + R_s\\rb{X}P_s\\rb{X} + r_1T_1\\rb{X} + \\dots + r_kT_k\\rb{X}. $$\n\\end{proof}\n\nAs a corollary, we deduce the following.\n\n\\begin{corollary}\nLet $ R $ be any field or PID, or indeed any Noetherian ring. Then for any $ n $, the ring $ R\\sb{X_1, \\dots, X_n} $ is Noetherian.\n\\end{corollary}\n\nAn observation is that if $ R $ is Noetherian and $ I \\subseteq R $ is an ideal, then $ R / I $ is Noetherian. Let $ J $ be an ideal of $ R / I $ and $ \\widetilde{J} $ be preimage of $ J $ in $ R $. There exist $ \\widetilde{j_1}, \\dots, \\widetilde{j_n} $ generating $ \\widetilde{J} $ over $ R $. Let $ j_i = \\widetilde{j_i} + I \\in R / I $. These lie in $ J $ and generate $ J $ over $ R / I $. In particular, any quotient of polynomial ring over a field or PID is Noetherian. Indeed, since any quotient of a Noetherian ring is Noetherian, we can say more.\n\n\\begin{definition}\nLet $ R $ be a ring. An $ R $-algebra is a ring $ S $ together with a homomorphism $ f : R \\to S $. If $ S $ is an $ R $-algebra, we say that $ S $ is finitely generated as an $ R $-algebra over $ R $ if there exists a finite set of elements $ s_1, \\dots, s_n \\in S $ such that every element of $ S $ can be expressed as a polynomial in the $ s_i $ with coefficients in $ R $. Equivalently, $ S $ is generated over $ R $ by $ s_1, \\dots, s_n $ if the homomorphism $ R\\sb{X_1, \\dots, X_n} \\to S $ by $ f : R \\mapsto S $ and sending $ X_i $ to $ s_i $ is surjective.\n\\end{definition}\n\n\\begin{note}\nAny finitely generated $ R $-algebra $ S $ is isomorphic to a quotient $ R\\sb{X_1, \\dots, X_n} / I $ for some $ n $ and some ideal $ I $. Thus we can rephrase the Hilbert basis theorem as saying that if $ R $ is Noetherian, then any finitely generated $ R $-algebra is Noetherian.\n\\end{note}\n\n\\marginpar{Lecture 17 \\\\ Monday \\\\ 12/11/18}\n\nLecture 17 is a problem class.\n\n\\marginpar{Lecture 18 \\\\ Wednesday \\\\ 14/11/18}\n\n\\subsection{Polynomial rings over UFDs are UFDs}\n\nOur next goal is to study factorisation in polynomial rings of the form $ R\\sb{X} $. $ \\Z\\sb{X} $ is not a PID nor a UFD. Idea is relate factorisations in $ \\Z\\sb{X} $ to factorisations in $ \\Q\\sb{X} $. Warning that irreducibles in $ \\Q\\sb{X} $ does not give irreducibles in $ \\Z\\sb{X} $.\n\n\\begin{example}\n$ 3x + 15 $ irreducible in $ \\Q\\sb{X} $. In $ \\Z\\sb{X} $ $ 3x + 15 = 3\\rb{x + 15} $.\n\\end{example}\n\nCertainly if $ R $ is not a UFD then we cannot expect to have unique factorisation in $ R\\sb{X} $, since we do not even have it in $ R $. Assume $ R $ is a UFD. Then the ring $ R\\sb{X} $ might be quite complicated, but $ R\\sb{X} $ is contained in a much simpler ring where we do understand factorisation, the ring $ K\\sb{X} $, where $ K $ is the field of fractions of $ R $. Our goal will thus be to compare factorisations in $ K\\sb{X} $ with factorisations in $ R\\sb{X} $. Fundamental question is can we turn factorisations in $ K\\sb{X} $ of $ P\\rb{X} \\in R\\sb{X} $ into factorisations in $ R\\sb{X} $? The key to doing this is the following result, often called Gauss' lemma.\n\n\\begin{theorem}[Gauss' lemma]\n\\label{thm:9.2.1}\nLet $ R $ be a UFD and let $ K $ be its field of fractions. Let $ P\\rb{X} \\in R\\sb{X} $, and let $ Q\\rb{X} $ be a polynomial in $ K\\sb{X} $ that divides $ P\\rb{X} $ in $ K\\sb{X} $. Then there is an element $ \\alpha \\in K^* $ such that $ \\alpha Q\\sb{X} $ lies in $ R\\sb{X} $, and divides $ P\\rb{X} $ in $ R\\sb{X} $. In particular, if $ P\\rb{X} $ is reducible in $ K\\sb{X} $, then $ P\\rb{X} $ is also reducible in $ R\\sb{X} $.\n\\end{theorem}\n\n\\begin{proof}\nWrite $ P\\rb{X} = Q\\rb{X}T\\rb{X} \\in K\\sb{X} $, and choose nonzero elements $ e_1, e_2 \\in R $ such that $ e_1Q\\rb{X} $ and $ e_2T\\rb{X} $ have coefficients in $ R $, and so that the greatest common divisor of the coefficients of $ Q\\rb{X} $ is one, as is the greatest common divisor of the coefficients of $ T\\rb{X} $. Letting $ d = e_1e_2 $, we have $ dP\\rb{X} = Q'\\rb{X}T'\\rb{X} $ with $ Q'\\rb{X} = e_1Q\\rb{X} $ and $ T'\\rb{X} = e_2T\\rb{X} $. Suppose $ d $ is nota  unit in $ R $. Then $ d $ is divisible by an irreducible element $ q $ of $ R $. Since $ R $ is a UFD, irreducibles are prime, so the ideal of $ R $ generated by $ q $ is a prime ideal. Thus $ R / \\ab{q} $ is an integral domain, so $ R / \\ab{q}\\sb{X} $ is as well. Moreover, if $ \\bar{Q'}\\rb{X} $ and $ \\bar{T'}\\rb{X} $ are the images of $ Q'\\rb{X} $ and $ T'\\rb{X} $ modulo $ \\ab{q} $ in $ R / \\ab{q}\\sb{X} $, $ dP\\rb{X} = Q'\\rb{X}T'\\rb{X} $ becomes $ 0 = \\bar{Q'}\\rb{X}\\bar{T'}\\rb{X} $ in $ R / \\ab{q}\\sb{X} $. Since $ R / \\ab{q}\\sb{X} $ is an integral domain we must have either $ \\bar{Q'}\\rb{X} = 0 $ or $ \\bar{T'}\\rb{X} = 0 $ in $ R / \\ab{q}\\sb{X} $. Without loss of generality assume $ \\bar{Q'}\\rb{X} = 0 $. Then all the coefficients of $ Q'\\rb{X} $ are divisible by $ q $. Thus $ d_1P\\rb{X} = Q_1\\rb{X}T_1\\rb{X} $ for $ Q_1\\rb{X}, T_1\\rb{X} \\in R\\sb{X} $ and $ Q_1\\rb{X} $ is a multiple of $ Q\\rb{X} $ in $ K\\sb{X} $. If $ d_1 $ is a unit, done. Otherwise write $ d_1 = d_2q_1 $ for $ q_1 $ irreducible. Same trick gives $ d_2P\\rb{X} = Q_2\\rb{X}T_2\\rb{X} $ for $ Q_2\\rb{X}, T_2\\rb{X} \\in R\\sb{X} $ and $ Q_2\\rb{X} $ is a multiple of $ Q_1\\rb{X} $ in $ K\\sb{X} $. Repeat, contradicting our construction of $ Q'\\rb{X} $. Thus $ \\alpha = d $ is a unit in $ P\\rb{X} $, and we have $ P\\rb{X} = e_1Q\\rb{X}d^{-1}e_2T\\rb{X} $, with $ e_1Q\\rb{X} $ and $ d^{-1}e_2T\\rb{X} $ in $ R\\sb{X} $.\n\\end{proof}\n\n\\begin{note}\nThe converse to the last claim of Theorem \\ref{thm:9.2.1} is not true. if $ P\\rb{X} $ is reducible in $ R\\sb{X} $, it might be irreducible in $ K\\sb{X} $.\n\\begin{example}\nThe polynomial $ 7x $ factors into irreducibles as $ 7 \\cdot x $ in $ \\Z\\sb{X} $, but since $ 7 $ is a unit in $ \\Q\\sb{X} $, $ 7x $ is irreducible in $ \\Q\\sb{X} $.\n\\end{example}\nThe following lemma shows that this kind of thing is all that can happen, however.\n\\end{note}\n\n\\begin{proposition}\nLet $ P\\rb{X} $ in $ R\\sb{X} $ be a polynomial and suppose that the greatest common divisor of all of its coefficients is one. Then $ P\\rb{X} $ is irreducible in $ K\\sb{X} $ if and only if it is also irreducible in $ R\\sb{X} $.\n\\end{proposition}\n\n\\begin{proof}\nSuppose $ P\\rb{X} $ is irreducible in $ R\\sb{X} $, and write $ P\\rb{X} = Q\\rb{X}T\\rb{X} $, with $ Q\\rb{X} $ and $ T\\rb{X} $ nonunits in $ R\\sb{X} $. If $ Q\\rb{X} $ or $ T\\rb{X} $ were constant with degree zero then it would divide every coefficient of $ P\\rb{X} $ and thus divide the GCD of those coefficients, making it a unit. Thus $ Q\\rb{X} $ and $ T\\rb{X} $ are nonconstant with positive degree and the factorisation $ P\\rb{X} = Q\\rb{X}T\\rb{X} $ is also a nontrivial factorisation in $ K\\sb{X} $, so $ P\\rb{X} $ is reducible in $ K\\sb{X} $. Conversely suppose $ P $ is reducible in $ K\\sb{X} $. Then there exist $ Q\\rb{X} \\in K\\sb{X} $ with $ 0 < \\deg\\rb{Q} < \\deg\\rb{P} $ such that $ Q\\rb{X} \\mid P\\rb{X} $ in $ K\\sb{X} $. Gauss' lemma shows that there exist $ \\alpha \\in K^* $ such that $ \\alpha Q\\rb{X} \\in R\\sb{X} $ and $ \\alpha Q\\rb{X} \\mid P\\rb{X} $ in $ R\\sb{X} $.\n\\end{proof}\n\nWe are now in a position to prove the following.\n\n\\begin{theorem}\nIf $ R $ is a UFD, then $ R\\sb{X} $ is a UFD.\n\\end{theorem}\n\n\\begin{proof}\nFor existence of factorisations, let $ P\\rb{X} $ be an element of $ R\\sb{X} $. We must show that $ P\\rb{X} $ factors into irreducibles. Let $ d $ be the greatest common divisor of the coefficients of $ P\\rb{X} $, and write $ P\\rb{X} = dQ\\rb{X} $ where the greatest common divisor of the coefficients of $ Q\\rb{X} $ is one. Since $ R $ is a UFD, $ d $ factors into irreducibles $ q_1, \\dots, q_s $ in $ R $, and these remain irreducible in $ R\\sb{X} $, so it suffices to show that $ Q\\rb{X} $ factors into irreducibles. Factor $ Q\\rb{X} $ into irreducibles in $ K\\sb{X} $, $ Q\\rb{X} = Q_1\\rb{X}, \\dots Q_r\\rb{X} $. By Gauss' lemma, there exist scalars $ \\alpha_1, \\dots, \\alpha_r \\in K^* $ such that $ \\alpha_1 \\dots \\alpha_r = 1 $ and $ \\alpha_iQ_i\\rb{X} \\in R\\sb{X} $. Let $ Q'_i \\rb{X} = \\alpha_iQ_i\\rb{X} $. GCD of coefficients of $ Q'_1\\rb{X}, \\dots, Q'_r\\rb{X} $ is one gives $ Q'_1\\rb{X}, \\dots, Q'_r\\rb{X} $ are irreducible in $ R\\sb{X} $ since they are irreducible in $ K\\sb{X} $. For uniqueness of factorisations, it remains to show that if $ P\\rb{X} \\in R\\sb{X} $ is irreducible in $ R\\sb{X} $ and divides $ A\\rb{X}B\\rb{X} $ in $ R\\sb{X} $ for $ A\\rb{X}, B\\rb{X} \\in R\\sb{X} $, then $ P\\rb{X} $ divides either $ A\\rb{X} $ or $ B\\rb{X} $ in $ R\\sb{X} $.\n\\begin{enumerate}\n\\item If $ P\\rb{X} $ is constant, then $ P\\rb{X} = c $ is irreducible in $ R $. In $ R / \\ab{c}\\sb{X} $ a domain, $ 0 = \\bar{A}\\rb{X}\\bar{B}\\rb{X} $ so $ \\bar{A}\\rb{X} = 0 $ or $ \\bar{B}\\rb{X} = 0 $ gives $ c \\mid A\\rb{X} $ or $ c \\mid B\\rb{X} $.\n\\item If $ P\\rb{X} $ is nonconstant, since $ P\\rb{X} $ is irreducible in $ R\\sb{X} $ it is irreducible in $ K\\sb{X} $ by Gauss' lemma, and hence divides either $ A\\rb{X} $ or $ B\\rb{X} $ in $ K\\sb{X} $. Suppose $ P\\rb{X} $ divides $ A\\rb{X} $ in $ K\\sb{X} $. Then $ A\\rb{X} = P\\rb{X}Q\\rb{X} $ in $ K\\sb{X} $. Then there is an element $ \\alpha = r / s \\in K^* $ for $ r, s \\in R $ and $ r \\ne 0 $ such that $ \\alpha P\\rb{X} $ lies in $ R\\sb{X} $ and divides $ A\\rb{X} $ in $ R\\sb{X} $, and $ A\\rb{X} = \\alpha P\\rb{X}\\alpha^{-1} Q\\rb{X} $ in $ R\\sb{X} $ by Gauss' lemma. On the other hand, since $ P\\rb{X} $ is irreducible in $ R\\sb{X} $ the GCD of its coefficients is one, so the only way $ \\alpha P\\rb{X} $ lies in $ R\\sb{X} $ is if $ s $ is a unit and $ \\alpha $ lies in $ R $. Thus $ \\alpha^{-1}Q\\rb{X} \\in R\\sb{X} $, $ \\alpha \\in R $, and $ P\\rb{X} \\in R\\sb{X} $, so $ P\\rb{X} $ also divides $ A\\rb{X} $.\n\\end{enumerate}\n\\end{proof}\n\n\\begin{corollary}\nIf $ K $ is a UFD, a field, or a PID, then $ K\\sb{X_1, \\dots, X_n} $ is a UFD for any $ n $.\n\\end{corollary}\n\nWarning that quotients of UFDs are only rarely UFDs themselves.\n\n\\begin{example}\n$ \\Z\\sb{X} $ is a UFD. $ \\Z\\sb{X} / \\ab{X^2 + 5} = \\Z\\sb{\\sqrt{-5}} $ is not a UFD.\n\\end{example}\n\n\\end{document}", "meta": {"hexsha": "206ed1daf86a6dca7960fe13eda4ca3c5d1da194", "size": 120852, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "M3P8 Algebra III/M3P8.tex", "max_stars_repo_name": "kckennylau/JMC3", "max_stars_repo_head_hexsha": "1ef0265a73457e0d379c71f9de2218f217e89a8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "M3P8 Algebra III/M3P8.tex", "max_issues_repo_name": "kckennylau/JMC3", "max_issues_repo_head_hexsha": "1ef0265a73457e0d379c71f9de2218f217e89a8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "M3P8 Algebra III/M3P8.tex", "max_forks_repo_name": "kckennylau/JMC3", "max_forks_repo_head_hexsha": "1ef0265a73457e0d379c71f9de2218f217e89a8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 83.7505197505, "max_line_length": 1855, "alphanum_fraction": 0.6261708536, "num_tokens": 43462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.34159472093717047}}
{"text": "\\documentclass[dvisvgm,hypertex,aspectratio=169]{beamer}\n\\usefonttheme{serif}\n\n%\\usepackage[utf8]{inputenc}\n%\\usepackage[T1]{fontenc}\n\n%\\usepackage[draft]{animate}\n\\usepackage[final]{animate}\n\\usepackage{ifthen}\n\n\n%\\usepackage{pythontex} % <--\n\\usepackage{graphicx}\n\n\n\\usepackage{tikz}\n\\usepackage{pgfplots}\n\\usepackage{pgfplotstable}\n\\pgfplotsset{compat=1.16}\n\\usetikzlibrary{calc}\n\\usetikzlibrary{decorations.pathmorphing,patterns}\n\\usepackage{amsmath}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n% Define footer\n\\usepackage{ccicons}\n\n\\makeatletter\n\\setbeamertemplate{footline}\n{\n  \\leavevmode%\n  \\hbox{%\n  %\\begin{beamercolorbox}[wd=.333333\\paperwidth,ht=2.25ex,dp=1ex,center]{title in head/foot}%\n    %\\usebeamerfont{title in head/foot}\\insertsubsection\n  %\\end{beamercolorbox}%\n  %\\begin{beamercolorbox}[wd=.333333\\paperwidth,ht=2.25ex,dp=1ex,right]{date in head/foot}%\n  %  \\usebeamerfont{date in head/foot}\\insertshortdate{}\\hspace*{2em}\n  %  \\insertframenumber{} / \\inserttotalframenumber\\hspace*{2ex} \n  %\\end{beamercolorbox}}%\n  %\\vskip0pt%\n  \\begin{beamercolorbox}[wd=.92\\paperwidth,ht=2.25ex,dp=1ex,right]{author in head/foot}%\n    \\usebeamerfont{author in head/foot}\\insertauthor\n  \\end{beamercolorbox}%\n  \\begin{beamercolorbox}[wd=.08\\paperwidth,ht=2.25ex,dp=1ex,right]{date in head/foot}%\n    \\ccbysa\n  \\end{beamercolorbox}}%\n  \\vskip0pt%\n}\n\\makeatother\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\author{\\href{mailto:kjartan@tec.mx}{kjartan@tec.mx}}\n\n\\begin{document}\n\n\\section{Create animation}\n\n  \\def\\tend{30}\n  \\def\\nframes{24}\n  \\def\\nsamples{200}\n  \\def\\wexpstart{-2}\n  \\def\\wexpend{1}\n  \\def\\ttau{1}\n  \n\\begin{frame}[label=A]{First-order Bode plot}\n      \\begin{center}\n        \\begin{tikzpicture}[scale=0.7, transform shape,]\n          \\tiny\n          \\node[draw, minimum width=14mm, minimum height=12mm] (sys) {$G(s)=\\frac{1}{s\\tau + 1}$};\n          \\node[coordinate, left of=sys, node distance=46mm] (input) {};\n          \\node[coordinate, right of=sys, node distance=46mm] (output) {};\n          \\draw[->] (input) -- node[ above] { $\\textcolor{blue!80!green}{u(t)=\\sin(\\omega_1 t)}$} (sys);\n          \\draw[->] (sys) -- node[near end, above] { $\\textcolor{green!80!black}{y(t)=|G(i\\omega_1)|\\sin\\big(\\omega_1 t + \\arg G(i\\omega_1)\\big)}$} (output);\n        \\end{tikzpicture}\n      \\end{center}\n      \\begin{center}\n        \\begin{animateinline}[controls, loop, palindrome]{4}\n          \\multiframe{\\nframes}{n=0+1}{\n            \n            \\pgfmathsetmacro{\\wexp}{\\wexpstart + (\\wexpend-\\wexpstart)/\\nframes*\\n}\n            \\pgfmathsetmacro{\\ww}{pow(10, \\wexp)}\n            \\pgfmathsetmacro{\\wstart}{pow(10, \\wexpstart)}\n            \\pgfmathsetmacro{\\wend}{pow(10, \\wexpend)}\n            \\pgfmathsetmacro{\\gain}{1/sqrt(pow(\\ttau*\\ww,2) + 1)}\n            \\pgfmathsetmacro{\\phshift}{-atan2(\\ttau*\\ww,1)}\n\n            \\begin{tikzpicture}[scale=0.5, transform shape]\n\n            \\begin{loglogaxis} [\n            width=7cm,\n            height=5cm,\n            ylabel=$|G|$,\n            %xticklabels=\\empty,\n            xtick={0.01, 0.1, 1, 10},\n            xticklabels={$\\frac{0.01}{\\tau}$, $\\frac{0.1}{\\tau}$, $\\frac{1}{\\tau}$, $\\frac{10}{\\tau}$}, \n            grid=both,\n            minor y tick num=9,\n            % extra y ticks={.5}, % how to convert to fixed point tick label ?\n            % extra y tick style={log identify minor tick positions=true},\n            every major grid/.style={red, opacity=0.5},\n            ymin=0.01, ymax=2,\n            xmin = 0.01, xmax=10,\n            ]\n            \\addplot+[thick, orange!80!black, no marks, domain=\\wstart:\\wend, samples=100]\n                  {1/sqrt(pow((\\ttau*\\x),2) + 1)};\n            \\draw[black!90, ] (axis cs: \\ww, 0.01) -- (axis cs: \\ww, 10);\n            \\node[magenta!80!black, circle, draw, inner sep=2pt, thick,] at (axis cs: \\ww, \\gain) {};\n          \\end{loglogaxis}\n          \\begin{semilogxaxis} [\n            xlabel=$\\omega$,\n            ylabel=$\\arg G$,\n            xshift = 8cm, \n            width=7cm,\n            height=5cm,\n            grid=both,\n            ytick={0, -90},\n            ymin=-90, ymax = 0,\n            xtick={0.01, 0.1, 1, 10},\n            xticklabels={$\\frac{0.01}{\\tau}$, $\\frac{0.1}{\\tau}$, $\\frac{1}{\\tau}$, $\\frac{10}{\\tau}$},\n            xmin = 0.01, xmax = 10,\n            minor y tick num=2,\n            every major grid/.style={red, opacity=0.5},\n            %legend entries={Bessel filter, Delay of one},\n            %legend pos={south west},\n            ]\n            \\addplot+[thick, orange!80!black, no marks, domain=\\wstart:\\wend, samples=100]\n               {-atan2(\\x*\\ttau,1)};\n            \\draw[black!90,] (axis cs: \\ww, -90) -- (axis cs: \\ww, 10);\n            \\node[magenta!80!black, circle, draw, inner sep=2pt, thick,] at (axis cs: \\ww, \\phshift) {};\n          \\end{semilogxaxis}\n          \\begin{axis} [\n            width = 10cm,\n            height= 5cm,\n            yshift = -5cm,\n            xshift = 5cm,\n            xlabel = {$t$},\n            ymin=-1.2,\n            ymax = 1.2,\n            ]\n            \\addplot+[thick, blue!80!green, no marks, domain=0:\\tend, samples=\\nsamples, smooth] {sin(\\ww*180/3.14*x)};\n            \\addplot+[thick, green!80!black, no marks, domain=0:\\tend, samples=\\nsamples, smooth] {\\gain*sin(\\ww*180/3.14*x + \\phshift)};\n            \n          \\end{axis}\n          \\begin{scope}[yshift=-4cm, xshift=-4.5cm]\n            \\pgfmathsetmacro{\\www}{min(\\ww, 8)};\n            \\clip (-2, -1) rectangle (2, 10);\n            \\draw[->] (-2, 0) -- (0.3, 0) node[below] {Re};\n            \\draw[->] (0, -1) -- (0, 8) node[left] {Im};\n            \\node[red] at (-1/\\ttau, 0) {\\large $\\times$};\n            \\node[magenta!80!black, circle, draw, inner sep=2pt, thick,] at (0, \\www) {};\n            \\draw[<->, black!60] (-1/\\ttau, 0) to (0, \\www);\n            \\node at (0.9, \\www) {$\\frac{\\www}{\\tau}$};\n            \\node[]  at (-1/\\ttau, -0.5){$-\\frac{1}{\\tau}$};\n            \\node at (-1, 6) {$s$-plane}; \n          \\end{scope}\n          \\begin{scope}[yshift=-3cm, xshift=0cm, ]\n            \\pgfmathsetmacro{\\xx}{2*\\gain*cos(\\phshift)};\n            \\pgfmathsetmacro{\\yy}{2*\\gain*sin(\\phshift)};\n            \\draw[->] (-2, 0) -- (3, 0) node[below] {Re};\n            \\draw[->] (0, -2) -- (0, 1) node[left] {Im};\n            \\node[magenta!80!black, circle, draw, inner sep=2pt, thick,] at (\\xx, \\yy) {};\n            \\node at (1.5, 1) {$G(i\\omega)$-plane};\n            \\draw (2,0) -- (2, 0.2) node[above] {1};\n            \\draw[orange!80!black, domain=0:100, smooth, samples at={0, 0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.4, 0.64, 0.8, 1.0, 1.28, 2, 2.56, 3, 4,  5.12, 6, 8, 10.24, 20}, variable=\\t] plot ({2*(1/sqrt(1 + pow(\\ttau*\\t, 2)))*cos(-atan2(\\ttau*\\t, 1))}, {2*(1/sqrt(1 + pow(\\ttau*\\t, 2)))*sin(-atan2(\\ttau*\\t, 1))});\n          \\end{scope}\n        \\end{tikzpicture}\n      }\n    \\end{animateinline}\n  \\end{center}\n\\end{frame}\n\n\\end{document}\n\n\n", "meta": {"hexsha": "f7b04d4bbe1f8c6b4b4abba8e4de6ebed9d1c82e", "size": 6986, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "classic-control/slides/first-order-bode/first-order-bode.tex", "max_stars_repo_name": "kjartan-at-tec/mr2025", "max_stars_repo_head_hexsha": "88c28aa76e84890c25d252167e5bbcd25318463e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "classic-control/slides/first-order-bode/first-order-bode.tex", "max_issues_repo_name": "kjartan-at-tec/mr2025", "max_issues_repo_head_hexsha": "88c28aa76e84890c25d252167e5bbcd25318463e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "classic-control/slides/first-order-bode/first-order-bode.tex", "max_forks_repo_name": "kjartan-at-tec/mr2025", "max_forks_repo_head_hexsha": "88c28aa76e84890c25d252167e5bbcd25318463e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4689265537, "max_line_length": 316, "alphanum_fraction": 0.5302032637, "num_tokens": 2465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.341594704141986}}
{"text": "\n\n\nThis chapter details the proposed framework and implementation. I start by giving an overview of the proposed framework, and then five crucial components in the framework are carefully explained: Deep Denoising Autoencoders on audio-visual modalities, Fisher Vector Encoding, Document Embedding on textual modality, Tree-based Feature Selection and Multi-Task Learning. \n\n\n\n\n\n\\section{Overview}\n\nFigure \\ref{fig:pipeline} illustrates the framework of my proposed method for automatic Bipolar Disorder BD recognition. For acoustic modality, I extract 39-dimensional Mel-Frequency Cepstrum Coefficients (MFCCs)\\footnotemark as the Low-Level Descriptors (LLDs) with OpenSMILE and for visual modality, I extract the 132-dimensional facial landmarks, 6-dimensional head pose, 6-dimensional eye gaze, and 35-dimensional Facial Action Units (FAUs) as the LLDs with OpenFace. To discover the correlation across audio-visual modalities and produce robust representations, I propose a Deep Denoising Autoencoder (DDAE) that learns a shared and joint representation on different number of modalities. More specifically, according to the number of modalities on which DDAEs are built, I define uni-DDAE, bi-DDAE, and multi-DDAE. Before feeding multimodal features into DDAE, features must be aligned on frame-level first to ensure they are extracted from the same time interval. I then compute the dynamic changes of the latent representations in DDAE as each representation is regarded as a specific movement of the subject. After computing the velocity ($1^{st}$-order derivative) and the acceleration ($2^{nd}$-order derivative) of the latent representations, the three features are concatenated as frame-level descriptors. Because the video clips vary in length, I encode the frame-level descriptors with a Fisher Vector (FV), a fixed-length descriptor on session-level, by fitting them into a Gaussian Mixture Model (GMM). To reduce redundancy and select the most discriminative feature set, a tree-based model is used for feature selection by evaluating the feature importance.\n\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=13.5cm]{images/design/general_pipeline.png}\n    \\caption{Pipeline of the proposed framework that includes different learning architectures on different modalities}\n    \\label{fig:pipeline}\n\\end{figure}\n\nOn the other hand, I obtain the transcripts of video interviews and apply a document embedding model (doc2vec) to learn fixed-length representations of the transcripts on session-level. To boost the performance of the doc2vec model, the model is pre-trained on an additional Turkish corpus. \n\nWith both fixed-length FVs on audio-visual modalities and fixed-length document embeddings on textual modality, a Multi-Task Deep Neural Network (MT-DNN) is built to handle the overfitting due to the limited size of the BD corpus. The MT-DNN is learned with a weighted loss from the ternary classification task of Mania Level and the regression task of Young Mania Rating Scale (YMRS). Furthermore, to address the imbalance between three classes, I duplicate the training instances of the minority class and apply Unweighted Average Recall (UAR) as my metric for evaluation. Finally, with the best-performing MT-DNN, the final decision on each video interview is inferred: depression, hypo-mania, or mania.\n\n\n\\footnotetext{The 39-dimensional MFCC features are obtained by appending additional 13 delta and 13 acceleration coefficients to the conventional 13-dimensional MFCC features.}\n\n\n\n\n\n\n\n\n\n\\section{Deep Denoising Autoencoders}\n\\label{sec:DDAE}\n\nAutoencoders (AEs) are an unsupervised learning algorithm that learns a latent-space representation of given data with hidden layers constrained while reconstructing the data from the representation. The representations learnt from AEs generally have a lower dimensionality and have been proven effective as high-level features in the following classification tasks, which in many cases are competitive or even superior to the hand-engineered representations \\cite{ng2011}. Autoencoders are composed of two parts: a) encoder, which compresses the input into a latent representation with the function $h=f(x)$, and b) decoder, which reconstructs the input from the latent representation with the function $r=g(h)$, as shown in Figure \\ref{fig:unimodal_ae}. Therefore, autoencoders can be described by the function $g(f(x))=r$, and the reconstruction error $\\parallel x-r \\parallel ^ 2$ is minimized in the training processing. \n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[height=6.5cm]{images/design/autoencoder.png}\n    \\caption{Schematic for Unimodal Deep Denoising Autoencoders}\n    \\label{fig:unimodal_ae}\n\\end{figure}\n\n\nAutoencoders were first introduced as an approach to initialize the weights of neural networks \\cite{ballard1987}, and because of the \\textit{curse of dimensionality} \\cite{bellman1966}, the low-dimensional hidden layers enable AEs to be commonly employed in feature engineering and representation learning \\cite{charte2018}. Several variations of AEs have been developed with different constraints on the hidden layers, such as sparse AEs \\cite{ng2011}, denoising AEs \\cite{vincent2008}, and variational AEs \\cite{kingma2013}. \n\nDenoising AEs, proposed by \\cite{vincent2008}, stochastically corrupts part of the original input $x$ and reconstructs the original input $x$ with the corrupted version $\\tilde{x}$. The noise can be of different forms, such as additive isotropic Gaussian noise and masking noise \\cite{vincent2010}. The Gaussian noise $\\tilde{x}$ is obtained with $\\tilde{x}|x \\sim \\mathcal{x, \\sigma^2,I}$ and the masking noise is calculated by forcing a fraction $v$ of the elements of input $x$ to 0. Although the Gaussian noise is reported to be the natural choice for real-valued inputs \\cite{vincent2010}, I only consider the masking noise in the experiment as the Gaussian noise could introduce a small change in facial expressions, which could be interpreted as a misleading descriptor for the BD symptoms. The objective of denoising AEs accordingly becomes minimizing the reconstruction error $\\parallel \\tilde{x}-r \\parallel ^ 2$. The denoising AEs are reported to produce representations that are robust to small irrelevant changes in the input.\n\nWith the development of multimedia data processing, a more recent learning architecture is introduced for feature fusion: the multi-modal AEs \\cite{mangai2010}. Feature fusion aims to learn a shared representation cross modalities without redundant or irrelevant information, which is one of the biggest challenges in multi-modal data processing \\cite{mangai2010}. In the work of \\cite{hong2015}, authors aimed to perform multimodal fusion of 2D images and 3D human poses to obtain high-level representations. \nInspired by \\cite{vincent2008}, \\cite{mangai2010}, and \\cite{dibekliouglu2017}, I propose a series of 3-layer Deep Denoising Autoencoders (DDAEs) (i.e., DDAEs with 3 hidden layers) with different number of modalities to investigate the multimodal fusion in the BD detection task. \n\n\\subsection{Unimodal Deep Denoising Autoencoders}\n\nI first define the unimodal DDAEs on acoustic and visual features respectively as shown in Figure \\ref{fig:unimodal_ae}, where features of one modality are fed into DDAEs to learn a compact-size representation after adding masking noise. This architecture is considered as a baseline for the following architectures as it does not discover the correlation across modalities. \n\nIn many implementations of AEs, the binary cross-entropy (BCE) is set as the loss function, which measures the amount of information is preserved in the reconstruction compared to the original input \\cite{de2005}. BCE is calculated with Equation \\ref{eq:binarycrossentropy}, in which $x_k$ represents one node in the input layer and $r_k$ represents the corresponding node in the output layer. The input data must be therefore normalized to the range $[0,1]$ with the sigmoid activation function in the output layer. BCE could apply to binary-value image pixel intensities, such as MNIST dataset, because the range of original intensities lies in $[0, 255]$, but other features, like MFCC, rarely share the same range across the dataset and normalization could wrongly corrupt the correlation in features, thus hurting the extraction of emotion-related information. In my framework, instead, I define the loss function as the mean squared error (MSE) (Equation \\ref{eq:mse}) with the linear activation function in the output layer and no normalization. The DDAEs are trained on minimizing the distance between reconstructed input and original input, and the reconstruction could be easily interpreted and visualized in the evaluation.\n\n\\begin{equation}\n    J(x,r) = - \\sum_{k=1}^d x_k \\log(r_k) + (1-x_k) \\log(1-r_k)\n    \\label{eq:binarycrossentropy}\n\\end{equation}\n\n\\begin{equation}\n    J(x,r) = \\frac{1}{N} \\sum_{k=1}^d (x_k - r_k)^2\n    \\label{eq:mse}\n\\end{equation}\n\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[height=7.5cm]{images/design/bimodal_ae.png}\n    \\caption{Schematic for Bimodal Deep Denoising Autoencoders (Different colours indicate different modalities)}\n    \\label{fig:bimodal_ae}\n\\end{figure}\n\n\n\\subsection{Bimodal Deep Denoising Autoencoders}\n\nI continue to define the 3-layer bimodal DDAEs on acoustic and visual features altogether as displayed in Figure \\ref{fig:bimodal_ae}. The acoustic features are Low-Level Descriptors (LLDs), either MFCC or eGeMAPS features, and the visual features in this architecture are set as facial landmarks whose dynamics have been proven useful in depression detection \\cite{dibekliouglu2017}. As suggested in the work of \\cite{ngiam2011}, two separate encoders are merged into one shared hidden layer after one hidden layer, which outputs the first-order representations. From the shared hidden layer, two modalities are then reconstructed via their decoders with the sum of MSE on both reconstructed inputs as the loss function. \nAcoustic and visual modalities need to be aligned beforehand to ensure they are within the same window \\cite{ngiam2011}, and I concatenate 3 contiguous acoustic features as each input that has approximately the same duration as 1 visual feature. Because audio-visual modalities have different data formats and ranges, they are normalized and whitened separately.\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[height=7.5cm]{images/design/multimodal_ae.png}\n    \\caption{Schematic for Multimodal Deep Denoising Autoencoders (Different colours indicate different modalities)}\n    \\label{fig:multimodal_ae}\n\\end{figure}\n\n\\subsection{Multimodal Deep Denoising Autoencoders}\n\nGiven the importance of head pose, eye gaze, and action units in emotion recognition \\cite{adams2015, ekman2013}, the 3-layer multimodal DDAEs are defined on a total of five modalities, namely facial landmarks, MFCC / eGeMAPS, head pose, eye gaze, and action units (shown in Figure \\ref{fig:multimodal_ae}). Following the same design principle as the bimodal DDAEs, five modalities are merged into the shared representation layer with their ``mid-level\" representation output by their first hidden layer, and masking noise is added to modalities individually. The reconstruction loss of each modalities is assigned with equal weights in the joint reconstruction loss function. \n\n\\subsection{Implementation Details}\n\nThe list of investigated hyperparameters for all DDAEs is given in Table \\ref{tab:param_DDAE}, in which the hidden ratio is defined as the ratio between two consecutive hidden layers, and for instance, with hidden ratio 0.5, the dimensions of all hidden layers would be $\\{0.5d, 0.25d, 0.5d\\}$ where $d$ represents the input dimensionality. In addition, I evaluate the denoising effect in DDAEs by setting different masking noise levels.\n\n\n\\begin{table}[ht]\n    \\centering\n    \\caption{Hyperparameter settings to investigate for DDAEs}\n    \\begin{tabular}{l|l}\n        \\Xhline{2\\arrayrulewidth}\n        Hyperparameter & Values \\\\\n        \\hline\n        hidden ratio & \\{0.4, 0.5\\} \\\\\n        noise level & \\{0.1, 0.2, 0.4\\} \\\\\n        batch size & 1024 \\\\\n        learning rate & 0.01 \\\\\n        epochs & 100 \\\\\n        \\Xhline{2\\arrayrulewidth}\n    \\end{tabular}\n    \\label{tab:param_DDAE}\n\\end{table}\n\nThe dimensions of all input modalities are listed in Table \\ref{tab:dim_modality}. Because the shared representation is trained from only one acoustic features, either MFCC features or eGeMAPS features are input into bimodal DDAEs (Table \\ref{fig:bimodal_ae}) and multimodal DDAEs (Table \\ref{fig:multimodal_ae}). The sum of the input dimensions would thus be either 300 or 252, and the shared representation has four different dimensions with different hidden ratio settings (either 0.4 or 0.5), as shown in the last two row of Table \\ref{tab:dim_modality}. The dimension of facial landmarks is obtained by $x$ and $y$ coordinates of 68 landmarks, while to acoustic features, dimensions of MFCC and eGeMAPS are multiplied with 3 because of the alignment of audio-visual modalities.\n\nThe training of DDAEs can be considered as the unsupervised feature learning, in which more data benefit the encoding of DDAEs \\cite{ngiam2011}. All DDAEs are therefore trained with all available labelled (training set and development set) and unlabelled (test set) audio-visual data. \n\n\\begin{table}[ht]\n    \\centering\n    \\caption{Dimension of all five modalities. The two dimensions of representations in the last two rows are based on the different hidden ratios, defined in \\ref{tab:param_DDAE}}\n    \\begin{tabular}{l|l}\n        \\Xhline{2\\arrayrulewidth}\n        Modality & Dimension \\\\\n        \\hline\n        Facial Landmarks & 136 ($68 \\times 2$) \\\\\n        MFCC features & 117 ($39 \\times 3$) \\\\\n        eGeMAPS features & 69 ($23 \\times 3$) \\\\\n        Head Pose & 6 \\\\\n        Eye Gaze & 6 \\\\\n        Action Units & 35 \\\\\n        \\hline\n        Sum of input (MFCC) & 300 \\\\\n        Sum of input (eGeMAPS) & 252 \\\\\n        \\hline\n        Representation (MFCC) & 48 (0.4) / 75 (0.5) \\\\\n        Representation (eGeMAPS) & 40 (0.4) / 63 (0.5) \\\\\n        \\Xhline{2\\arrayrulewidth}\n    \\end{tabular}\n    \\label{tab:dim_modality}\n\\end{table}\n\n\\subsection{Computing Dynamics of Latent Representations}\n\nAfter training, each DDAE (unimodal, bimodal, or multimodal) learns a presentation for the per-frame extracted features. These representations, however, only encode the static element of the input, such as locations of facial landmarks or loudness of audio signal, but without any temporary information. Following the ideas proposed in \\cite{dibekliouglu2017}, I extend these representations with the dynamics. Considering DDAE-based representations as a matrix $H \\in \\mathcal{R}^{n \\times d}$, in which $n$ denotes the number of frames and $d$ the final dimension of representations. Each column in $H_i(i \\in \\{1,2...d\\})$ corresponds to one node in the representation layer, or for example, to one static point in unimodal DDAEs. I then compute the first-order dynamics, velocity $V$, of $H$ by the $1^{st}$ derivative $V_i = \\frac{d H_i}{dt}$, measuring the velocity of the change between per-frame representations. I continue to calculate the second-order dynamics, acceleration $A$, of $H$ by the $2^{nd}$ derivative $A_i = \\frac{d^2 H_i}{d^2 t}$, measuring the acceleration of the change. To align $H$, $V$, and $A$, I discard the first two frames in each video sessions, and I concatenate $H$, $V$, and $A$ for the final representations on frame-level.\n\n\n\n\n\n\n\\section{Fisher Vector Encoding}\n\\label{sec:fisher}\n\nFeature aggregation is an approach via which low-level descriptors (LLDs) can be summarised to produce fixed-length high-level descriptors on variable-length audio-visual recordings, which encodes more global information. Many approaches within feature aggregation exist, such as the Bag-of-Words (BoW) \\cite{csurka2004} and the Fisher Vector (FV) \\cite{perronnin2010}. In my framework, to encode the frame-level representations learnt from DDAEs into a fixed-length vector on session-level, I investigate and implement the improved Fisher Vector (FV) \\cite{perronnin2010, sanchez2013}. The BoW representations are briefly explained first as they are one of the baseline features used in Chapter \\ref{ch:evaluation}.\n\n\\subsection{Bag-of-Words Representation}\n\nBag-of-Words originates from natural language processing and as a semi-supervised representation learning, it represents the distribution of LLDs based on a dictionary or codebook learned from them \\cite{csurka2004, peng2016}. Generally, BoW is composed of five steps: a) feature extraction, b) feature-preprocessing, c) codebook generation, d) feature encoding, and e) pooling and normalization. According to the modality of representations, BoW can be categorised into Bag-of-Audio-Words (BoAW) and Bag-of-Visual-Words (BoVW). The feature extraction is completed as described in Chapter \\ref{ch:background} and these extracted LLDs are usually high dimensional and strong correlated. Principal Component Analysis (PCA), a statistical procedure, is therefore used in BoW to preprocess the LLDs to low-dimensional and de-correlated features \\cite{peng2016}. For codebook generation, two approaches are often considered, (i) partitioning the feature space into regions, each represented by its centre, such as $k$-means \\cite{bishop2006}, and (ii) using a generative model to capture the probability distribution of features, such as Gaussian Mixture Model (GMM) \\cite{bishop2006}. With parameters indicating either cluster centres or parameters for GMM, the LLDs extracted from one video are encoded into a fixed-length vector via voting-based or reconstruction-based encoding method \\cite{peng2016}. In the last step, a pooling operation is used to obtain a global per-video representation and normalization enables the representations to be invariant to the variable number of LLDs extracted from different videos \\cite{peng2016}.\n\n\\subsection{Fisher Vector}\n\nFisher Vector (FV) extends the bag-of-words (BoW) representations to learn the distribution of LLDs with their mean and variance, and it is commonly used as a global image descriptors in image classification \\cite{perronnin2010, krapac2011}. More recently, FV has become popular for a variety of applications in social signal processing, such as depression estimation \\cite{jain2014, dhall2015} and emotion recognition \\cite{kaya2015}, because it combines advantages of both the generative and discriminative approaches \\cite{sanchez2013} in machine learning. In the workflow of FV encoding, a generative model, typically Gaussian Mixture Model (GMM), is firstly built on LLDs and the Fisher kernel is then computed from this generative model. FVs are quantified using first and second order statistics of the gradient of the sample log-likelihood with respect to GMMs' parameters \\cite{sanchez2013}.\n\nFormally, let $X = \\{x_t; t=1...T\\}$ be an element in the time-series representations with the number of frames, $T$. Let $\\Theta = \\{\\mu_k, \\Sigma_k, \\pi_k; k=1...K\\}$ be the parameter of a Gaussian Mixture Model (GMM) fitting the distribution of the representations where $\\mu_i$ and $\\Sigma_i$ are respectively the mixture mean vector and covariance matrix and priors of GMM. GMM estimates a probability distribution of multiple multivariate Gaussian distributions and it is trained while maximizing the likelihood $p(X|\\Theta)$:\n\n\\begin{equation}\n    \\Theta^{*} = \\arg \\max_{\\Theta} p(X|\\Theta) = \\arg \\max_{\\Theta} \\prod_{i=1}^{N} p(x_i|\\Theta)\n\\end{equation}\n\nGMM associates each vector $x_t$ to a mode $k$ in the mixture with a strength given by the posterior probability:\n\n\\begin{equation}\n    q_{tk} = \\frac{\\exp [-1/2 (x_t-\\mu_k)^{T} \\Sigma_k^{-1}(x_t-\\mu_k)]}{\\sum_{i=1}^{K} \\exp [-1/2 (x_t-\\mu_i)^{T} \\Sigma_k^{-1}(x_t-\\mu_i)]}\n\\end{equation}\n\nFor each mode $k$, the mean and covariance deviation vectors are defined as \n\n\\begin{align}\n    u_{jk} &= \\frac{1}{N\\sqrt{\\pi_k}} \\sum_{t=1}^T q_{tk}\\frac{x_{jt}-\\mu_{jk}}{\\sigma_{jk}} \\\\\n    v_{jk} &= \\frac{1}{N\\sqrt{2\\pi_k}} \\sum_{t=1}^T q_{tk}[(\\frac{x_{jt}-\\mu_{jk}}{\\sigma_{jk}})^2 - 1]\n\\end{align}\n\nwhere $j=1,2...D$ spans the vector dimensions. The FV of the time-series representations is the stacking of the vector $u_k$ and $v_k$ for each of the K modes in the Gaussian mixtures:\n\n\\begin{equation}\n    \\Phi(X) = [...u_k...v_k...]^T\n\\end{equation}\n\n\\subsection{Improved Fisher Vectors}\n\nIn addition to the traditional FV, the improved FV was introduced by \\cite{perronnin2010} for better classification performance with the following ideas :\n\\begin{itemize}\n    \\item Power normalization. As the number of Gaussians increases, FV becomes sparser and the distribution of features becomes more ``peaky\" around zero. The kernel is therefore replaced with the Laplacian kernel, which is more robust on sparse vectors, by applying the function $|z| \\sign z$ to each dimension of the vector $\\Phi(X)$. \n    \\item $l_2$ normalization. Before using the representations in a linear model, the vector $\\Phi(X)$ is further by the $l_2$ normalization to discard the video-independent information, or descriptors which are likely to occur in any video. FV thus focus on video-specific features.\n\\end{itemize}\n\nI compute the Fisher Vectors using GMMs with empirically 16 or 32 Gaussian distributions \\cite{syed2018, dibekliouglu2017} to estimate the distribution on DDAE-based $d$-dimensional representations. The resulting feature vectors are $96 \\times d_{latent}$ dimensional ($16 \\times 2 \\times 3 \\times d_{latent}$) or $192 \\times d_{latent}$ dimensional ($32 \\times 2 \\times 3 \\times d_{latent}$), where $d_{latent}$ denotes the dimension of latent representation learnt from DDAEs.\n\n\n\n\n\n\\section{Tree-based Feature Selection}\n\nFeature selection is a key step to reduce redundancy and improve the accuracy of classifiers by selecting the most informative features \\cite{hira2015}. The reduced dimensional features should preserve as much information as the original high-dimensional features do. Considering the high dimension of the obtained Fisher Vectors with respect to the limited size of the dataset, feature selection is deemed necessary in my framework. Many approaches have been proposed to select the discriminative features, such as Min-Redundancy Max-Relevance (mRMR) algorithm \\cite{peng2005}, Analysis of Variance (ANOVA) \\cite{moran1918}, and correlation-based feature selection (CFS) \\cite{pudil1994}, I apply tree-based feature selection in my framework by evaluating and ranking the importance of each feature. More specifically, a Random Forest (RF) classifier is used to compute the information gain $(S,A)$ for a feature $A$ relative to a dataset $S$: \n\n\\begin{equation}\n    Gain(S,A) = Entropy(S) - \\sum_{v \\in values(A)} \\frac{|S_v|}{|S|} Entropy(S_v)\n\\end{equation}\n\nwhere $values(A)$ is the set of all possible values for feature $A$, and $S_v$ is the subset of $S$ for which feature $A$ has value $v$. As RF is robust to redundant features and insensitive to the irrelevant information, the resulting feature importance leads to a reliable and discriminative subset of features. The split criterion is preset as entropy, and the number of trees as 800, determined by the baseline system describe in Chapter \\ref{ch:evaluation}. I select the top 100 features in the Fisher Vector ranked with the importance, and in other words, the dimension for features in audio-visual modality is 100.\n\n\n\n\\section{Document Embedding}\n\nSince strong correlations have been found between interview contents and depression symptoms \\cite{morales2016, pampouchidou2016}, analyzing emotion-related textual modality has been emerged as a new approach in depression detection. More specifically, the use of negatively-valenced words and pronouns has been stressed in \\cite{morales2016}. To incorporate textural modality into my framework, I first transcribe the recordings from BD corpus into plain texts using Google Speech-To-Text API \\footnote{\\url{https://cloud.google.com/speech-to-text/}}, and then make use of Paragraph Vector (PV) \\cite{mikolov2014} to embed to session-level transcripts into textual features of the same size.\n\nThe PV model, or doc2vec, is an unsupervised learning algorithm to learn the distributed representations of a variable-length piece of texts \\cite{mikolov2014}, and it is usually considered as an extension of word2vec, which aims to learn the word representations \\cite{mikolov2013}.  \n\n\\subsection{word2vec}\n\nThe two architectures within word2vec, Continuous Bag-Of-Words (CBOW) and Skip-Gram (SG), are variants of neural networks with one hidden layer \\cite{mikolov2013}. While CBOW architecture takes the context words (multiple word vectors) as input and predicts the target word (one word vector), SG architecture infers the context words given the target word, as shown in Figure \\ref{fig:word2vec}. \n\nFormally, in word2vec-CBOW architecture, the objective is to maximize the log probability of the target word given context words with Equation \\ref{eq:cbow}.\n\n\\begin{equation}\n    \\frac{1}{T} \\sum_{t=c}^{T-c} \\log p(w_t | w_{t-c} ... w_{t+c})\n    \\label{eq:cbow}\n\\end{equation}\n\nwhere $c$ indicates the size of context windows (which equals to 2 in Figure \\ref{fig:word2vec}) and $T$ represents the length of the word sequence. On the other hand, in word2vec-SG architecture, the optimization function is based on the averaged log probability as Equation \\ref{eq:sg}, where $c$ and $T$ share the same notations as Equation \\ref{eq:cbow}.\n\n\\begin{equation}\n    \\frac{1}{T} \\sum_{t=i}^{T} \\sum_{-c\\leq j \\leq c} \\log p(w_{t+j}|w_t)\n    \\label{eq:sg}\n\\end{equation}\n\nA large $c$ means a broader context window and thus a higher probability to capture the semantics of the words, but it could also lead to more expensive computation \\cite{mikolov2013}. Furthermore, since the high dimensionality of input vectors can easily cause difficulties in the computation of condition probability $p(w_O|w_I)$ obtained by the softmax function, shown in Equation \\ref{eq:softmax}, where $w_O$ is denoted as the ``output vector\", $w_I$ as the ``input vector\", and $W$ as the weight matrix that is updated via backpropagation with loss function $E = -\\log p(w_O|w_I)$. Mikolov \\textit{et al.} \\cite{mikolov2013efficient} proposed three optimization techniques to improve the quality of output vectors and also the training speed: hierarchical softmax, negative sampling, and subsampling \\cite{mikolov2013, mikolov2013efficient}. \n\n\\begin{equation}\n    p(w_O|w_I) = \\frac{\\exp({v^{'}_{w_O}}^{T} v_{w_I})}{\\sum_{w=1}^{W} \\exp({v^{'}_w}^{T} v_{w_{I}})}\n    \\label{eq:softmax}\n\\end{equation}\n\nAs an efficient approach of computer softmax, the hierarchical softmax applies a binary tree to represent $W$ words in the output layer \\cite{mikolov2013}, and the evaluation of $W$ nodes in the output weight matrix is therefore reduced to $\\log_2 W$ nodes. An alternative to the hierarchical softmax is negative sampling: instead of updating the entire weight matrix, only a limited number of ``negative words\" are selected to update the weights \\cite{mikolov2013efficient}. The ideas underlying subsampling is straightforward: the most frequent words in a large corpus generally provides less semantic information, such as ``a\", ``the\" or ``some\" \\cite{mikolov2013efficient}. Subsampling of such words can decrease the number of training samples and also help the neural networks to assign higher weights to rare words, which reflects more emotion-related information.\n\n\\begin{figure}[ht]\n    \\centering\n    \\begin{minipage}{0.47\\textwidth}\n        \\centering\n        \\includegraphics[height=4.3cm]{images/design/word2vec_cbow.png} \\\\\n        (a) word2vec-CBOW\n    \\end{minipage}\n    \\begin{minipage}{0.48\\textwidth}\n        \\centering\n        \\includegraphics[height=4.3cm]{images/design/word2vec_sg.png} \\\\\n        (b) word2vec-SG\n    \\end{minipage}\n    \\caption{Schematic for two Word Vector (word2vec) architectures}\n    \\label{fig:word2vec}\n\\end{figure}\n\n\\subsection{doc2vec}\n\nTo extend the embeddings to a higher level, the Paragraph Vector (doc2vec) is proposed to learn the representation for a variable-length of texts: sentence, paragraph and document. There are also two architectures within doc2vec, Paragraph Vector with Distributed Memory (PV-DM), corresponding to word2vec-CBOW, and Paragraph Vector with Distributed Bag-Of-Words (PV-DBOW), corresponding to word2vec-SG. As displayed in Figure \\ref{fig:doc2vec}, both architectures introduce an additional document token that could be considered as the topic of each document (or in my framework, the mania level of transcript). The input in PV-DM is the concatenation of document vectors and word vectors, both of which are learned in the training process, but only the document vector is used for the inferring process. On the contrary, the PV-DBOW ignores the context words and predicts the words randomly sampled from the inferred document. It is obvious that PV-DBOW requires fewer data storage as it only saves softmax weights and PV-DM also needs to save the word vectors \\cite{mikolov2014}. \n\n\\begin{figure}[ht]\n    \\centering\n    \\begin{minipage}{0.55\\textwidth}\n        \\centering\n        \\includegraphics[height=5.4cm]{images/design/doc2vec_dm-m.png} \\\\\n        (a) doc2vec-DM\n    \\end{minipage}\n    \\begin{minipage}{0.43\\textwidth}\n        \\centering\n        \\includegraphics[height=5.4cm]{images/design/doc2vec_dbow.png} \\\\\n        (b) doc2vec-DBOW\n    \\end{minipage}\n    \\caption{Schematic for two Paragraph Vector (doc2vec) architectures}\n    \\label{fig:doc2vec}\n\\end{figure}\n\n\n\\subsection{Implementation Details}\nSome researchers have reported that PV-DBOW outperforms PV-DM in the sentiment analysis, contradictory results in the work of \\cite{mikolov2014}. In addition, Yang \\textit{et al.} only considers PV-DM architectures in their depression detection framework, and therefore, in my experiment, I investigate both PV-DM and PV-DBOW in the BD detection with different hyperparameter settings, as shown in Table \\ref{tab:param_doc2vec}.\n\n\n\\begin{table}[ht]\n    \\centering\n    \\caption{Hyperparameter settings to investigate for document embedding}\n    \\begin{tabular}{l|l}\n        \\Xhline{2\\arrayrulewidth}\n        Hyperparameter & Values \\\\\n        \\hline\n        model & \\{PV-DM, PV-DBOW\\} \\\\\n        vector size & \\{25, 50, 100\\} \\\\\n        window size & \\{5, 10\\} \\\\\n        negative words & \\{5, 10\\} \\\\\n        hierarchical softmax & \\{0, 1\\} \\\\\n        \\Xhline{2\\arrayrulewidth}\n    \\end{tabular}\n    \\label{tab:param_doc2vec}\n\\end{table}\n\nThe translation of transcripts to English prior to the document embedding has been considered as it might help to understand the transcripts and to evaluate the embeddings. Nonetheless, I apply the doc2vec model directly on the Turkish transcripts to ensure the completeness of semantic content, which could be compromised in the translation, and after learning process, the document embeddings are evaluated with translation for better understanding. \n\nDue to the limited size of the BD corpus, I pre-train the doc2vec models on an external, large-scale Turkish corpus,``trwiki\", to improve the performance of my models \\cite{lau2016}. The ``trwiki\" corpus is based on Wikimedia\\footnote{\\url{https://dumps.wikimedia.org/trwiki/}} dump service, which contains various kinds of texts in Turkish, such as articles, templates, media/file descriptions, and primary meta-pages. After training separate doc2vec models following the hyperparameter settings in Table \\ref{tab:param_doc2vec}, I first evaluate their performance with a simple Random Forest (RF) classifier, the same classifier used in the baseline, and select the best-performing doc2vec model to infer the document vector for each transcript. These document vectors are used in the final fusion stage to predict the mania level of each session. In addition, visualizing the similar groupings of transcripts via Embedding Projector\\footnote{\\url{http://projector.tensorflow.org}} and the similar words stored in PV-DM models are presented to qualitatively examine the embedding space inferred by the doc2vec models.\n\n\n\n\n\n\n\\section{Multi-Task Learning}\n\nIn the context of Deep Learning, the generalization of the model could be improved if representations being shared across related tasks \\cite{ruder2017}, and this approach is called Multi-Task Learning (MTL). There are two typical structures in MTL, hard parameter sharing and soft parameter sharing. Hard parameter sharing is applied by sharing the hidden layers between all tasks, with unchanged task-specific output layers (as shown in Figure \\ref{fig:mtl}). Soft parameter sharing, on the other hand, separate all tasks with their own model and parameters (as shown in Figure \\ref{fig:mtl}) with an objective to minimize the distance between parameters of different models.\n\n\\begin{figure}[ht]\n    \\centering\n    \\begin{minipage}[c]{0.42\\textwidth}\n    \\centering\n    \\includegraphics[height=4.2cm]{images/design/multitask_hard.png} \\\\\n    (a) Hard parameter sharing\n    \\end{minipage}\n    \\begin{minipage}[c]{0.55\\textwidth}\n    \\centering\n    \\includegraphics[height=4.2cm]{images/design/multitask_soft.png} \\\\\n    (b) Soft parameter sharing\n    \\end{minipage}\n    \\caption{Schematic for two architectures in Multi-Task Learning frameworks}\n    \\label{fig:mtl}\n\\end{figure}\n\nHard parameter sharing architecture greatly reduces the risk of overfitting \\cite{baxter1997} and more specifically, the risk of overfitting the shared parameters is an order N smaller than the risk of overfitting the task-specific parameters, where N which represents the number of tasks. I therefore adjust my deep neural network (DNN) classifier to learn on both classification task (mania levels) and regression task (YMRS scores). The joint loss function is defined as the weighted sum of cross entropy loss for classification and the Euclidean loss for regression, as shown in Equation \\ref{eq:multi_loss}.\n\n\\begin{equation} \n\\begin{split}\n \\mathcal{L} & = \\mathcal{W}_c \\mathcal{L}_c + \\mathcal{W}_r \\mathcal{L}_r \\\\\n             & = \\mathcal{W}_c (-\\sum_{c=1}^N y_c \\log(p_c)) + \\mathcal{W}_r (\\frac{1}{M} \\sum_{i=1}^M \\parallel y_r - p_r \\parallel ^ 2)\n\\end{split}\n\\label{eq:multi_loss}\n\\end{equation}\n\nwhere $\\mathcal{W}_c$ and $\\mathcal{W}_r$ represent the weight for two losses, $y_c$ and $y_r$ are values for two tasks while $p_c$ and $p_r$ are the predicted values, and $N$ is the number of classes and $M$ is the number of samples in the training set.\n", "meta": {"hexsha": "4c41d0ebe1e16bf1e2e66835fc7a7b8bcb42ca13", "size": 34618, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paperwork/dissertation_final/mainSections/4-design.tex", "max_stars_repo_name": "ZihengZZH/bipolar-disorder", "max_stars_repo_head_hexsha": "deef966d65014175d6cb8f35320b2b33bfadfd13", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2019-08-07T11:21:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T00:57:09.000Z", "max_issues_repo_path": "paperwork/dissertation_final/mainSections/4-design.tex", "max_issues_repo_name": "ZihengZZH/bipolar-disorder", "max_issues_repo_head_hexsha": "deef966d65014175d6cb8f35320b2b33bfadfd13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-01-28T22:56:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T00:15:53.000Z", "max_forks_repo_path": "paperwork/dissertation_final/mainSections/4-design.tex", "max_forks_repo_name": "ZihengZZH/bipolar-disorder", "max_forks_repo_head_hexsha": "deef966d65014175d6cb8f35320b2b33bfadfd13", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-11-22T07:10:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T08:20:48.000Z", "avg_line_length": 98.3465909091, "max_line_length": 1675, "alphanum_fraction": 0.7715061529, "num_tokens": 8577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.34159470414198595}}
{"text": "\\documentclass[10pt]{article}\n\\usepackage{a4wide}\n\\usepackage{listings}\n\\usepackage{listings}\n\\newcommand{\\be}{\\begin{equation}}\n\\newcommand{\\ee}{\\end{equation}}\n\\newcommand{\\OP}[1]{{\\bf\\widehat{#1}}}\n\n\\begin{document}\n\n\n\\section*{Project 3, Variational Monte Carlo studies of helium and beryllium}\n\nThe final aim of this project is to develop a variational Monte Carlo program which can be used to obtain ground state properties of atoms like He, Be, O, Ne, Si etc as well as diatomic molecules. \nfor important molecules \n\nThe final project builds on project 1 and 2 and adds the optimization procedure for the variational parameter $\\beta$ using for example Newton's methods, the steepest descent method or the conjugate gradient method. \nFurthermore, the single-particle wave functions used in the computation\nof the Slater determinant will be replaced by Gaussian type orbitals (GTO) using already optimized parameters. \n\nThus, in addition to these ingredients, the final project contains all the elements you have included inprojects 1 and 2. This means that you can include all results you have obtained in projects 1 and 2 in the wrap-up of the final report. It is the final report which counts for the final mark.\n\nYou will thus see that this report contains much of the same text as included in projects 1 and 2. \n\n{\\bf The deadline for project 3 is June 15, at noon}.  See below for delivery format.\n\n\n\n\\section*{Part 1: Variational Monte Carlo calculations of the helium atom}\n\nWe will start with the simplest possible system beyond hydrogen, namely the helium atom.\nWe label $r_1$ the distance from electron 1 to the nucleus and similarly \n$r_2$ the distance between electron 2 and the nucleus.\nThe contribution to the potential energy from the interactions between the \nelectrons and the nucleus is\n\\be\n   -\\frac{2}{r_1}-\\frac{2}{r_2},\n\\ee \nand if we add the electron-electron repulsion with\n$r_{12}=|{\\bf r}_1-{\\bf r}_2|$, the total potential energy \n$V(r_1, r_2)$ is\n\\be\n V(r_1, r_2)=-\\frac{2}{r_1}-\\frac{2}{r_2}+\n               \\frac{1}{r_{12}},\n\\ee\nyielding the total Hamiltonian\n\\be\n   \\OP{H}=-\\frac{\\nabla_1^2}{2}-\\frac{\\nabla_2^2}{2}\n          -\\frac{2}{r_1}-\\frac{2}{r_2}+\n               \\frac{1}{r_{12}},\n\\ee\nand Schr\\\"odinger's equation reads\n\\be\n   \\OP{H}\\psi=E\\psi.\n\\ee\nAll equations are in so-called atomic units. The distances\n$r_i$ and $r_{12}$ are dimensionless. To have energies in electronvolt\nyou need to multiply all results with \n$2\\times E_0$,\nwhere $E_0=13.6$ eV.\nThe experimental binding energy for helium in atomic units a.u. is $E_{\\mathrm{He}}=-2.9037$ a.u..\n\n\n\\begin{enumerate}\n\n\\item[1a)] We want to perform  a Variational Monte Carlo calculation of the ground state of the helium atom.\nIn our first attempt we will use a brute force Metropolis sampling with a trial wave function which has the following form\n\\begin{equation}\n   \\psi_{T}({\\bf r_1},{\\bf r_2}, {\\bf r_{12}}) = \n   \\exp{\\left(-\\alpha(r_1+r_2)\\right)}\n   \\exp{\\left(\\frac{r_{12}}{2(1+\\beta r_{12})}\\right)}, \n\\label{eq:trial}\n\\end{equation}\nwith $\\alpha$ and $\\beta$ as variational parameters.\n\nYour task is to perform a Variational Monte Carlo calculation\nusing the Metropolis algorithm to compute the integral\n\\begin{equation}\n   \\langle E \\rangle =\n   \\frac{\\int d{\\bf r_1}d{\\bf r_2}\\psi^{\\ast}_T({\\bf r_1},{\\bf r_2}, {\\bf r_{12}})\\OP{H}({\\bf r_1},{\\bf r_2}, {\\bf r_{12}})\\psi_T({\\bf r_1},{\\bf r_2}, {\\bf r_{12}})}\n        {\\int d{\\bf r_1}d{\\bf r_2}\\psi^{\\ast}_T({\\bf r_1},{\\bf r_2}, {\\bf r_{12}})\\psi_T({\\bf r_1},{\\bf r_2}, {\\bf r_{12}})}.\n\\end{equation}\nYou should parallelize your program.   Find the  energy minimum and compute also the mean distance\n$r_{12}$ between the two electrons for the optimal set of the variational parameters.\nA code for doing a VMC calculation for the helium atom can be \nfound on the webpage of the course, see under programs.\n\nYour Monte Carlo moves are determined by\n\\begin{equation}\n   {\\bf R}' = {\\bf R} +\\delta \\times r,\n\\end{equation}\nwhere $r$ is a random number from the uniform distribution and $\\delta$\na chosen step length.\nIn solving this exercise you need to devise an algorithm which finds\nan optimal value of $\\delta$ for the variational parameters $\\alpha$ and $\\beta$,\nresulting in roughly $50\\%$ accepted moves. \n\nGive a physical  interpretation of the best value of $\\alpha$.\nMake a plot of the variance as a function of the number of Monte Carlo\ncycles.\n\\item[1b)]\nFind closed form expressions for the local energy (see below) for the above \ntrial wave function and explain shortly how this \ntrial function satisfies \nthe cusp condition when $r_1\\rightarrow 0$ or\n$r_2\\rightarrow 0$ or  $r_{12}\\rightarrow 0$. Show that\nclosed-form expression for the trial wave function is\n\\[ \nE_{L2} = E_{L1}+\\frac{1}{2(1+\\beta r_{12})^2}\\left\\{\\frac{\\alpha(r_1+r_2)}{r_{12}}(1-\\frac{\\mathbf{r}_1\\mathbf{r}_2}{r_1r_2})-\\frac{1}{2(1+\\beta r_{12})^2}-\\frac{2}{r_{12}}+\\frac{2\\beta}{1+\\beta r_{12}}\\right\\},\n\\]\nwhere\n\\[ \nE_{L1} = \\left(\\alpha-Z\\right)\\left(\\frac{1}{r_1}+\\frac{1}{r_2}\\right)+\\frac{1}{r_{12}}-\\alpha^2.\n\\]\n\nCompare the results of with and without the closed-form expressions (in terms of CPU time).\n\\item[1c)] Introduce now importance sampling and study the dependence of the results as a function of the time step $\\delta t$.  \nCompare the results with those obtained under 1a) and comment eventual differences.\nIn performing the Monte Carlo analysis you should use blocking as a technique  to make the statistical analysis of the numerical data.\nThe code has to run in parallel. \n\\item[1d)]  With the optimal parameters for the ground state wave function, compute the onebody density. Discuss your results and compare the results with those obtained with a pure hydrogenic wave functions. Run a Monte Carlo calculations without the Jastrow factor as well\nand compute the same quantities. How important are the correlations induced by the Jastrow factor?\n\n\\item[1e)]  Repeat step 1c) by varying the energy using the \nconjugate gradient method or similar methods to obtain the best possible parameter\n$\\beta$.  Replace now the hydrogen-like single-particle wave functions with the 3-21G basis defined \nat the EMSL website \\url{https://bse.pnl.gov/bse/portal}. \n\n\\end{enumerate}\n\n\n\\section*{Part 2: Variational Monte Carlo calculations of the Beryllium and  Neon atoms}\nThe previous exercise has prepared you for extending your calculational machinery  to other systems.\nHere we will focus on the neon and beryllium atoms.\nIt is convenient to make modules or classes of trial wave functions, both many-body wave functions\nand single-particle wave functions  and the quantum numbers  involved, such as spin, orbital momentum and principal\nquantum numbers.\n\nThe new item you need to pay attention to is the calculation of the Slater Determinant. This is an additional complication\nto your VMC calculations.\nIf we stick to hydrogen-like wave functions,\nthe trial wave function for Beryllium can be written as \n\\begin{equation}\n   \\psi_{T}({\\bf r_1},{\\bf r_2}, {\\bf r_3}, {\\bf r_4}) = \n   Det\\left(\\phi_{1}({\\bf r_1}),\\phi_{2}({\\bf r_2}),\n   \\phi_{3}({\\bf r_3}),\\phi_{4}({\\bf r_4})\\right)\n   \\prod_{i<j}^{4}\\exp{\\left(\\frac{r_{ij}}{2(1+\\beta r_{ij})}\\right)}, \n\\end{equation}\nwhere $Det$ is a Slater determinant and the single-particle wave functions\nare the hydrogen wave functions for the $1s$ and $2s$ orbitals. Their form\nwithin the variational ansatz are given by\n\\begin{equation}\n\\phi_{1s}({\\bf r_i}) = e^{-\\alpha r_i},\n\\end{equation}\nand \n\\begin{equation}\n\\phi_{2s}({\\bf r_i}) = \\left(1-\\alpha r_i/2\\right)e^{-\\alpha r_i/2}.\n\\end{equation}\nFor neon, the trial wave function can take the form\n\\begin{equation}\n   \\psi_{T}({\\bf r_1},{\\bf r_2}, \\dots,{\\bf r_{10}}) = \n   Det\\left(\\phi_{1}({\\bf r_1}),\\phi_{2}({\\bf r_2}),\n   \\dots,\\phi_{10}({\\bf r_{10}})\\right)\n   \\prod_{i<j}^{10}\\exp{\\left(\\frac{r_{ij}}{2(1+\\beta r_{ij})}\\right)}, \n\\end{equation}\nIn this case you need to include the $2p$ wave function as well.\nIt is given as\n\\begin{equation} \n\\phi_{2p}({\\bf r_i}) = \\alpha {\\bf r_i}e^{-\\alpha r_i/2}.\n\\end{equation}\nObserve that $r_i = \\sqrt{r_{i_x}^2+r_{i_y}^2+r_{i_z}^2}$.\n\n\nYou can approximate the Slater determinant for the ground state of the Beryllium atom\nby writing it out as\n\\begin{equation}\n   \\psi_{T}({\\bf r_1},{\\bf r_2}, {\\bf r_3}, {\\bf r_4}) \\propto \n\\left(\\phi_{1s}({\\bf r_1})\\phi_{2s}({\\bf r_2})-\\phi_{1s}({\\bf r_2})\\phi_{2s}({\\bf r_1})\\right)\n\\left(\\phi_{1s}({\\bf r_3})\\phi_{2s}({\\bf r_4})-\\phi_{1s}({\\bf r_4})\\phi_{2s}({\\bf r_3})\\right).\n\\end{equation}\nHere you can see a simple code example which implements the above expression\n\\begin{lstlisting}\n for (i = 0; i < number_particles; i++) {\n    argument[i] = 0.0;\n    r_single_particle = 0;\n    for (j = 0; j < dimension; j++) {\n      r_single_particle  += r[i][j]*r[i][j];\n    }\n    argument[i] = sqrt(r_single_particle);\n  }\n// Slater determinant, no factors as they vanish in Metropolis ratio\nwf  = (psi1s(argument[0])*psi2s(argument[1])\n       -psi1s(argument[1])*psi2s(argument[0]))*\n      (psi1s(argument[2])*psi2s(argument[3])\n       -psi1s(argument[3])*psi2s(argument[2]));\n\\end{lstlisting}\nFor beryllium we can easily implement the explicit evaluation of the Slater determinant.  The above will serve as a useful check\nfor your function which computes the Slater determinat. \nThe derivatives of the single-particle wave functions can be computed analytically and you should consider\nusing the closed form expression for the local energy (not mandatory, you can use numerical derivatives as well although a closed form expressions speeds up your code).\n\nFor the correlation part \n\\[\n\\Psi_C=\\prod_{i< j}g(r_{ij})= \\exp{\\left\\{\\sum_{i<j}\\frac{ar_{ij}}{1+\\beta r_{ij}}\\right\\}},\n\\]\nwe need to take into account whether electrons have equal or opposite spins since we have to obey the\nelectron-electron cusp condition as well.  For Beryllium, as an example,  you can fix electrons 1 and 2 to have spin up while\nelectrons 3 and 4 have spin down.\nWhen the electrons have  equal spins \n\\[\na= 1/4,\n\\]\nwhile for opposite spins (as for the ground state of  helium)\n\\[\na= 1/2.\n\\] \n\n\\begin{enumerate}\n\\item[(2a)]   Write a function which sets up the Slater determinant for beryllium and neon and can be generalized to\nhandle larger systems as well. \nCompute the ground state energies of neon and beryllium as you did for the helium atom\nin 1d). \nThe calculations should include  parallelization, blocking, importance sampling and energy minimization using the conjugate gradient approach or related approaches like the steepest descent method or Newton's method.  You should also replace the hydrogen-like single-particle wave functions with the 3-21G basis set defined \nat the EMSL website \\url{https://bse.pnl.gov/bse/portal}. If you get time, you should also try the 6-311G basis set from the same website.\n\n\\item[2b)]  With the optimal parameters for the ground state wave function, compute again the onebody density. Discuss your results and compare the results with those obtained with a pure hydrogenic wave functions. Run a Monte Carlo calculations without the Jastrow factor as well\nand compute the same quantities. How important are the correlations induced by the Jastrow factor?\n\n\n\\end{enumerate}\n\n\n\n\\section*{Brief summary on how ot write a report}\n\nHere follows a brief recipe and recommendation on how to write a report for each\nproject.\n\\begin{itemize}\n\\item Give a short description of the nature of the problem and the eventual \nnumerical methods you have used.\n\\item Describe the algorithm you have used and/or developed. Here you may find it convenient\nto use pseudocoding. In many cases you can describe the algorithm\nin the program itself.\n\n\\item Include the source code of your program. Comment your program properly.\n\\item If possible, try to find analytic solutions, or known limits\nin order to test your program when developing the code.\n\\item Include your results either in figure form or in a table. Remember to\n       label your results. All tables and figures should have relevant captions\n       and labels on the axes.\n\\item Try to evaluate the reliabilty and numerical stability/precision\nof your results. If possible, include a qualitative and/or quantitative\ndiscussion of the numerical stability, eventual loss of precision etc. \n\n\\item Try to give an interpretation of you results in your answers to \nthe problems.\n\\item Critique: if possible include your comments and reflections about the \nexercise, whether you felt you learnt something, ideas for improvements and \nother thoughts you've made when solving the exercise.\nWe wish to keep this course at the interactive level and your comments can help\nus improve it. We do appreciate your comments. \n\\item Try to establish a practice where you log your work at the \ncomputerlab. You may find such a logbook very handy at later stages\nin your work, especially when you don't properly remember \nwhat a previous test version \nof your program did. Here you could also record \nthe time spent on solving the exercise, various algorithms you may have tested\nor other topics which you feel worthy of mentioning.\n\\end{itemize}\n\n\n\n\\section*{Format for electronic delivery of report and programs}\n%\nThe preferred format for the report is a PDF file. You can also\nuse DOC or postscript formats. \nAs programming language we prefer that you choose between C++, Fortran2008 or Python.\nFinally, \nwe recommend that you work together. Optimal working groups consist of \n2-3 students, but more people can collaborate. You can then hand in a common report. \n\n\n\n\n\n\\section*{Literature}\n\\begin{enumerate}\n\\item B.~L.~Hammond, W.~A.~Lester and P.~J.~Reynolds, Monte Carlo methods\nin Ab Inition Quantum Chemistry, World Scientific, Singapore, 1994, chapters\n2-5 and appendix B.\n\n\\item B.H.~Bransden and C.J.~Joachain, Physics of Atoms and molecules,\nLongman, 1986. Chapters 6, 7 and 9.\n\\item S.A.~Alexander and R.L.~Coldwell,\nInt.~Journal of Quantum Chemistry, {\\bf 63} (1997) 1001.  This article is available \nat the webpage of the course as the file jastrow.pdf under the project 1 link.\n\\item C.J.~Umrigar, K.G.~Wilson and J.W.~Wilkins, Phys.~Rev.~Lett.~{\\bf 60}\n(1988) 1719. \n\n\\item Moskowitz and Kalos, Int.~Journal of Quantum Chemistry {\\bf XX}, 1107 (1981).\nResults for He and H$_2$.\n\\item Filippi, Singh and Umrigar, J.~Chemical Physics {\\bf 105}, 123 (1996).   Useful results on\nBe$_2$ to which you can benchmark your results against.\n\n\n\\end{enumerate}\n\n\n\\end{document}\n\n\n\n\n\n\n\n\n\n\n\n\n\\section*{How to write the report}\nWhat should the report contain and how can I structure it? A typical structure follows here.\n\\begin{itemize}\n\\item An abstract with the main findings.\n\\item  An introduction where you explain the aims and rationale for the physics case and what you have done. At the end of the introduction you should give a brief summary of the structure of the report\n\\item Theoretical models and technicalities. This sections ends often being the methods section.\n\\item Results and discussion\n\\item Conclusions and perspectives\n\\item Appendix with extra material\n\\item Bibliography\n\\end{itemize}\nKeep always a good log of what you do.\n\n\\subsection*{What should I focus on? Introduction.}\nYou don't need to answer all questions in a chronological order. When you write the introduction you could focus on the following aspects\n\\begin{itemize}\n\\item Motivate the reader, the first part of the introduction gives always a motivation and tries to give the overarching ideas\n\\item What I have done\n\\item The structure of the report, how it is organized etc\n\\end{itemize}\n\\subsection*{What should I focus on? Methods sections.}\n\\begin{itemize}\n\\item Describe the methods and algorithms\n\\item You need to explain how you implemented the methods and also say something about the structure of your algorithm and present some parts of your code\n\\item You should plug in some calculations to demonstrate your code, such as selected runs used to validate and verify your results. The latter is extremely important!! A reader needs to understand that your code reproduces selected benchmarks and reproduces previous results, either numerical and/or well-known closed form expressions.\n\\end{itemize}\n\n\\subsection*{What should I focus on? Results sections.}\n\\begin{itemize}\n\\item Present your results\n\\item Give a critical discussion of your work and place it in the correct context.\n\\item Relate your work to other calculations/studies\n\\item An eventual reader should be able to reproduce your calculations if she/he wants to do so. All input variables should be properly explained.\n\\item Make sure that figures and tables contain enough information in their captions, axis labels etc so that an eventual reader can gain a first impression of your work by studying figures and tables only.\n\\end{itemize}\n\n\\subsection*{What should I focus on? Conclusions sections.}\n\\begin{itemize}\n\\item State your main findings and interpretations\n\\item Try as far as possible to present perspectives for future work\n\\item Try to discuss the pros and cons of the methods and possible improvements\n\\end{itemize}\n\n\\subsection*{What should I focus on? Additional material, appendices.}\n\\begin{itemize}\n\\item Additional calculations used to validate the codes\n\\item Selected calculations, these can be listed with few comments\n\\item Listing of the code if you feel this is necessary\n\\item You can consider moving parts of the material from the methods section to the appendix. You can also place additional material on your webpage.\n\\end{itemize}\n\\subsection*{What should I focus on? References.}\n\\begin{itemize}\n\\item Give always references to material you base your work on, either scientific articles/reports or books.\n\\item Refer to articles as: name(s) of author(s), journal, volume (boldfaced), page and year in parenthesis.\n\\item Refer to books as: name(s) of author(s), title of book, publisher, place and year, eventual page numbers\n\\end{itemize}\n\n\n\n\\section*{Format for electronic delivery of report and programs}\n%\nYour are free to choose your format for handing in. The simplest way is that you send us your github link that contains the report in your chosen format(pdf, ps, docx, ipython notebook etc) and the programs.\nAs programming language you have to choose either C++ or Fortran or Python. We recommend C++ or Fortran.\nFinally, \nwe recommend that you work together. Optimal working groups consist of \n2-3 students, but more people can collaborate. You can then hand in a common report. \n\n\n\n\n\n\\section*{Literature}\n\\begin{enumerate}\n\\item B.~L.~Hammond, W.~A.~Lester and P.~J.~Reynolds, Monte Carlo methods\nin Ab Inition Quantum Chemistry, World Scientific, Singapore, 1994, chapters\n2-5 and appendix B.\n\n\\item B.H.~Bransden and C.J.~Joachain, Physics of Atoms and molecules,\nLongman, 1986. Chapters 6, 7 and 9.\n\\item S.A.~Alexander and R.L.~Coldwell,\nInt.~Journal of Quantum Chemistry, {\\bf 63} (1997) 1001.  This article is available \nat the webpage of the course as the file jastrow.pdf under the project 1 link.\n\\item C.J.~Umrigar, K.G.~Wilson and J.W.~Wilkins, Phys.~Rev.~Lett.~{\\bf 60}\n(1988) 1719. \n\n\n\n\\end{enumerate}\n\n\\section*{Unit tests, how and why?}\nUnit Testing is the practice of testing the smallest testable parts, called units, of an application individually and independently to determine if they behave exactly as expected. Unit tests (short code fragments) are usually written such that they can be preformed at any time during the development to continually verify the behavior of the code. In this way, possible bugs will be identified early in the development cycle, making the debugging at later stage much easier. There are many benefits associated with Unit Testing, such as\n\\begin{itemize}\n\\item It increases confidence in changing and maintaining code. Big changes can be made to the code quickly, since the tests will ensure that everything still is working properly.\n\\item Since the code needs to be modular to make Unit Testing possible, the code will be easier to reuse. This improves the code design.\n\\item Debugging is easier, since when a test fails, only the latest changes need to be debugged.\n\\item Different parts of a project can be tested without the need to wait for the other parts to be available.\n\\item A unit test can serve as a documentation on the functionality of a unit of the code.\n\\end{itemize}\nHere follows a simple example, see the website of the course for more information on how to install unit test libraries.\n\\begin{verbatim}\n#include <unittest++/UnitTest++.h> \n\nclass MyMultiplyClass{ \npublic: \n   double multiply(double x, double y) { \n      return x * y; \n   } \n}; \nTEST(MyMath) { \n     MyMultiplyClass my; CHECK_EQUAL(56, my.multiply(7,8)); \n} \nint main() \n{ \nreturn UnitTest::RunAllTests(); \n}\n\\end{verbatim}\nFor Fortran users, the link at \\url{http://sourceforge.net/projects/fortranxunit/} contains a similar software for unit testing.\n\\end{document}\n\n\n", "meta": {"hexsha": "85715be0b22ad3fc150e8436ee0d7596be707302", "size": 20908, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/Projects/2015/project3_2015.tex", "max_stars_repo_name": "GabrielSCabrera/ComputationalPhysics2", "max_stars_repo_head_hexsha": "a840b97b651085090f99bf6a11abab57100c2e85", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 87, "max_stars_repo_stars_event_min_datetime": "2015-01-21T08:29:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T07:11:53.000Z", "max_issues_repo_path": "doc/Projects/2015/project3_2015.tex", "max_issues_repo_name": "GabrielSCabrera/ComputationalPhysics2", "max_issues_repo_head_hexsha": "a840b97b651085090f99bf6a11abab57100c2e85", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-01-18T10:43:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-08T13:15:42.000Z", "max_forks_repo_path": "doc/Projects/2015/project3_2015.tex", "max_forks_repo_name": "GabrielSCabrera/ComputationalPhysics2", "max_forks_repo_head_hexsha": "a840b97b651085090f99bf6a11abab57100c2e85", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 54, "max_forks_repo_forks_event_min_datetime": "2015-02-09T10:02:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T10:44:14.000Z", "avg_line_length": 47.3031674208, "max_line_length": 538, "alphanum_fraction": 0.751147886, "num_tokens": 5646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.3415946909323269}}
{"text": "\\chapter{Constraining the equation of state with astrophysics}\n%\\chapter{Astrophysics around neutrons stars}\n\\chapterimage[width=15cm]{wordcloud/chap3b.png}\n\n\\subsection{Accretion disks}\n\nGravitational potential energy release\n\\be\n\\Delta E_{\\mathrm{acc}} = \\frac{G M m}{R} \\sim 10^{20}  \\left( \\frac{10\\km}{R} \\right) \\left( \\frac{M}{\\Msun} \\right) \\unitspace\\erg\\unitspace\\g^{-1}\n\\ee\n\nRoche Lobe \\cite{PRP02} \\cite{LL15}\n\nLMXB \\cite{TH06}\n\nHard and soft state \\cite{HvdK89}\nAlternates between these two states \\cite{MDF14} \\cite{DGK07}\n\n\n\n\\subsection{Between the disk and the star: boundary layers}\n\n\\be\n\\Omega(R) \\approx \\Omega_{\\mathrm{K}}(R) = \\left( \\frac{G M}{R^3} \\right)^{1/2}\n\\ee\n\nLayer of thickness $b$ equals $\\Omega(R + b) \\approx \\Omega_{\\mathrm{K}}(R + b)$ that must slow down to $\\Omega_{*}$.\n\nEnergy difference\n\\be\n\\dot{E} = \\frac{1}{2} \\Mdot R^2 (\\Omega_{\\mathrm{K}}^2 - \\Omega_{*}^2) = \n\\frac{1}{2} \\Mdot \\frac{GM}{R} \\left[ 1 - \\left(\\frac{\\Omega_*}{\\Omega_{\\mathrm{K}}} \\right)^2 \\right] \n\\ee\n\nViscous torque $G_{\\mathrm{T}} = \\Mdot R^2 (\\Omega_{\\mathrm{K}} - \\Omega_*)$\nHence,\n\\be\n\\dot{E} = \\frac{1}{2} \\frac{G M \\Mdot}{R} \\left( 1 - \\frac{\\Omega_*}{\\Omega_{\\mathrm{K}}} \\right)^2\n\\ee\n\n\n\\section{X-ray bursts}\n\\subsection{Unstable thermonuclear burning on top of neutron stars}\n\n\\subsection{Constraining the size of bursting source}\n\n\n\n\n%--------------------------------------------------\n\\section{Accretion}\n%infalling matter leads to X-rays \\cite{Lewin93}\n\n\\subsection{Source of energy}\nIn the heart of this whole problem is an astrophysical process called accretion.\n\nGravitational potential energy release\n\\be\n\\Delta E_{\\mathrm{acc}} = \\frac{G M m}{R} \\sim 10^{20}  \\left( \\frac{10\\km}{R} \\right) \\left( \\frac{M}{\\Msun} \\right) \\unitspace\\erg\\unitspace\\g^{-1}\n\\ee\n\nEddington luminosity\n\\be\nL_{\\mathrm{Edd}} = \\frac{ 4 \\pi G M \\mproton c }{\\sigma_{\\mathrm{T}} } \\approx \\Ten{1.3}{38} \\left( \\frac{M}{\\Msun} \\right) \\ergs\n\\ee\n\nAccretion luminosity\n\\be\nL_{\\mathrm{acc}} = \\frac{G M \\Mdot}{R} \n\\ee\n\n\\subsection{Binary systems}\n\n\\begin{figure}[t]\n\\centering\n\\includegraphics[width=7.5cm]{figs/astro/roche.pdf}\n\\includegraphics[width=7.5cm]{figs/astro/roche.pdf}\n\\caption{\\label{fig:roche}\nRoche potential for binary systems.\n}\n\\end{figure}\n\n\\subsubsection{Roche lobes and mass transfer}\nRoche Lobe \\cite{PRP02} \\cite{LL15}\n\nA flow of gas between two stars can be described by the Euler equation.\nIt gives the time evolution of the velocity $\\vec{v}$ of the gas that has a pressure of $P$ and density $\\rho$.\nIn a reference frame rotating together with the binary system with angular velocity $\\omega$ the Euler equation takes the form \n\\be\n\\frac{ \\partial \\vec{v} }{\\partial t} + (\\vec{v} \\cdot \\nabla)\\vec{v} = -\\nabla \\Phi_{\\mathrm{R}} - 2 \\vec{ \\omega } \\times \\vec{v} - \\frac{1}{\\rho} \\nabla P,\n\\ee\nwhere the angular velocity of the binary is then\n\\be\n\\vec{ \\omega } = \\left( \\frac{ G M }{a^3} \\right)^{1/2} \\vec{e},\n\\ee\nas given with the unit vector $\\vec{e}$, normal to the orbital plane.\nHere $M$ is the total mass of the system, i.e. $M = M_1 + M_2$, where $M_1$ and $M_2$ are the individual masses of the two stars in the system, respectively, and $a$ is their orbital separation.\n\nThe effects originating from the gravitation and from the centrifugal forces are encapsulated in the so-called Roche potential, given as a function of radial vector $\\vec{r}$ as\n\\be\n\\Phi_{\\mathrm{R}}(\\vec{r}) = -\\frac{G M_1}{|\\vec{r} - \\vec{r_1}|} -\\frac{G M_2}{|\\vec{r} - \\vec{r_2}|} - \\frac{1}{2} ( \\vec{ \\omega } \\times \\vec{v} )^2,\n\\ee\nwhere the location of the stars is given with $\\vec{r_1}$ and $\\vec{r_2}$.\n\nBy studying the shape of the potential, we see that in between the stars, in the so-called $L_1$ point there exists a location where the individual gravitational pull from the stars is balanced.\nThis leads to a kinda of a nozzle in the system from which the material can leak from the less massive star to the more massive object.\nSuch a leaking, or a Roche lobe overflow, will then occur if the companion star's radius exceeds the size of its Roche lobe.\nTypically such a thing can happen when the star evolves and expands at the end of its life cycle. \n\nLMXB \\cite{TH06}\n\n\n\\subsection{Accretion disks}\nHard and soft state \\cite{HvdK89}\nAlternates between these two states \\cite{MDF14} \\cite{DGK07}\n\n\n\n\\section{Accretion to a neutron star}\n\n\\subsection{Boundary layers}\n\n\\be\n\\Omega(R) \\approx \\Omega_{\\mathrm{K}}(R) = \\left( \\frac{G M}{R^3} \\right)^{1/2}\n\\ee\n\nLayer of thickness $b$ equals $\\Omega(R + b) \\approx \\Omega_{\\mathrm{K}}(R + b)$ that must slow down to $\\Omega_{*}$.\n\nEnergy difference\n\\be\n\\dot{E} = \\frac{1}{2} \\Mdot R^2 (\\Omega_{\\mathrm{K}}^2 - \\Omega_{*}^2) = \n\\frac{1}{2} \\Mdot \\frac{GM}{R} \\left[ 1 - \\left(\\frac{\\Omega_*}{\\Omega_{\\mathrm{K}}} \\right)^2 \\right] \n\\ee\n\nViscous torque $G_{\\mathrm{T}} = \\Mdot R^2 (\\Omega_{\\mathrm{K}} - \\Omega_*)$\nHence,\n\\be\n\\dot{E} = \\frac{1}{2} \\frac{G M \\Mdot}{R} \\left( 1 - \\frac{\\Omega_*}{\\Omega_{\\mathrm{K}}} \\right)^2\n\\ee\n\n\n\\subsection{X-ray bursts}\nThermonuclear runaway.\n\n\\subsection{Constraining the size of the star}\nCooling tail method.\n\n\n\n\n\n% --------------------------------------------------\n\\newpage\n\\section{Appendix A: Real astrophysics}\n\n%\\begin{itemize}\n%    \\item Accretion\n%    \\item Disks \n%    \\item Soft and hard states\n%    \\item Boundary layers\n%    \\item Ignition?\n%    \\item X-ray bursts\n%    \\item Cooling tail method\n%\\end{itemize}\n%\n%Possible layout:\n%\n%v1\n%\\begin{enumerate}\n%    \\item Accretion\n%    \\begin{itemize}\n%        \\item Disks\n%        \\item Soft and hard states\n%        \\item Boundary layers\n%    \\end{itemize}\n%    \\item X-ray bursts\n%    \\begin{itemize}\n%        \\item Unstable thermonuclear burning\n%        \\item Cooling tail method\n%    \\end{itemize}\n%\\end{enumerate}\n%\n%v2\n%\\begin{enumerate}\n%    \\item Accretion disks\n%    \\begin{itemize}\n%        \\item Accretion\n%        \\item ?Roche lobe overflow\n%        \\item Soft and hard state\n%        \\item Boundary layers\n%    \\end{itemize}\n%    \\item X-ray bursts\n%    \\begin{itemize}\n%        \\item Unstable thermonuclear burning\n%        \\item Cooling tail method\n%    \\end{itemize}\n%\\end{enumerate}\n\n\n\\sect{Energetics}\nLet us try and estimate the energetics of different phenomena of what we can observe from neutron stars.\\mnote{Energy output}\nFew possible stable sources of energy exists: thermal, gravitational, rotational, and magnetic.\nIn addition, unstable fusion processes can also power some observable phenomena.\n\n\n\n", "meta": {"hexsha": "57267b04c4febce146dca075466df0b73123ff8a", "size": 6501, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "notes/roche_lobe_notes.tex", "max_stars_repo_name": "natj/thesis", "max_stars_repo_head_hexsha": "342586960e1d956ed6edf6aae4bfd0410747f011", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-16T20:30:36.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-16T20:30:36.000Z", "max_issues_repo_path": "notes/roche_lobe_notes.tex", "max_issues_repo_name": "natj/thesis", "max_issues_repo_head_hexsha": "342586960e1d956ed6edf6aae4bfd0410747f011", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notes/roche_lobe_notes.tex", "max_forks_repo_name": "natj/thesis", "max_forks_repo_head_hexsha": "342586960e1d956ed6edf6aae4bfd0410747f011", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4057971014, "max_line_length": 194, "alphanum_fraction": 0.6742039686, "num_tokens": 2162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.3414343290106885}}
{"text": "\\section{Interpretation of QM}\n\\subsection{Supporting definitions}\n\nTo provide our interpretation of quantum mechanics we need to develop\na number of supporting definitions. As the reader familiar with\nprocess algebraic systems can readily verify, these definitions make\n\\emph{essential} use of the reflective operations and as such identify\nthis calculus as uniquely suited to this particular task.\n\nAmong these operations we find a notion of \\emph{multiplication} of\nnames that interacts well with a notion of \\emph{tensor product} of\nprocesses. Even more intriguingly, we find a notion of a \\emph{dual}\nto a process in the form of maps from processes to names. While\nnotions of composite names have been investigated in the process\nalgebraic literature, it is the fact that names reflect process\nstructure that enables the collection of duals to enjoy an algebraic\nstructure dual to the collection of processes (i.e. there are\noperations available to duals that reflect the operations on\nprocesses). Moreover, it is this structure that enables an effective\ndefinition of inner product.\n\n\\subsubsection{Multiplication}\n\\begin{mathpar}\n  \\quotep{Q} \\cdot \\quotep{R} := \\quotep{Q|R}\n  \\and \\\\\n  \\quotep{Q} \\cdot P := P\\{ \\quotep{Q|R} / \\quotep{R} : \\quotep{R} \\in \\freenames{P} \\}\n\\end{mathpar}\n\n\\paragraph{Discussion}\nThe first equation needs little explanation; the second says that each\nfree name of the process is replaced with the multiplication of that\nname by the scalar. Multiplication of a scalar (name) by a state\n(process) results in a process all the names of which have been `moved\nover' by parallel composition with the process the scalar\nquotes. There is a subtlety that the bound names have to be\nmanipulated so that multiplied names aren't accidentally\ncaptured. There are many ways to achieve this.\n\n\\begin{remark}\\label{rem:multiplication_identities}\n  The reader is invited to verify that for all $x,y,z \\in \\QProc$ and $P \\in \\Proc$\n  \\begin{mathpar}\n    x \\cdot \\quotep{0} \\equiv x \n    \\and\n    x \\cdot y \\equiv y \\cdot x\n    \\and\n    x \\cdot (y \\cdot z) \\equiv (x \\cdot y) \\cdot z\n    \\and \\\\\n    \\quotep{0} \\cdot P \\equiv P\n    \\and \\\\\n    x \\cdot (y \\cdot P) \\equiv (x \\cdot y) \\cdot P\n    \\and \\\\\n    x \\cdot (P|Q) \\equiv (x \\cdot P) | (x \\cdot Q)\n    \\and \\\\    \n  \\end{mathpar}\n\\end{remark}\n\n\\subsubsection{Tensor product}\n\nWe define a tensor product on processes by structural induction.\n\n\\paragraph{Tensor of sums} First note that all summations, including\n$\\pzero$ and sequence, can be written $\\Sigma_{i} x_{i}.A_{i} +\n\\Sigma_{j} x_{j}.C_{j}$, where we have grouped input-guarded processes\ntogether and output-guarded processes together.\n\nThus, we can define the tensor product of two summations, $N_{1}\\otimes N_{2}$, where\n\n\\begin{mathpar}\n  N_{1} := \\Sigma_{i} x_{i}.A_{i} + \\Sigma_{j} x_{j}.C_{j}\n  \\and\n  N_{2} := \\Sigma_{i'} y_{i'}.B_{i'} + \\Sigma_{j'} y_{j'}.D_{j'} \n\\end{mathpar}\n\nas follows.\n\n\\begin{mathpar}\n  \\Sigma_{i} x_{i}.A_{i} + \\Sigma_{j} x_{j}.C_{j} \\otimes \\Sigma_{i'}\n  y_{i'}.B_{i'} + \\Sigma_{j'} y_{j'}.D_{j'} \n  \\and \\\\\n  := \\; \\Sigma_{i} \\Sigma_{i'} \\quotep{\\stackrel{\\vee}{x_{i}}| \\stackrel{\\vee}{y_{i'}}}.(A_{i}\\otimes B_{i'}) \\; | \\; \\Sigma_{i'} \\Sigma_{i} \\quotep{\\stackrel{\\vee}{y_{i'}}|\\stackrel{\\vee}{x_{i}}}.(B_{i'}\\otimes A_{i})\n  \\and\n  \\;\\; | \\;\\; \\Sigma_{j} \\Sigma_{j'} \\quotep{\\stackrel{\\vee}{x_{j}}|\\stackrel{\\vee}{y_{j'}}}.(A_{j}\\otimes B_{j'}) \\; | \\; \\Sigma_{j'} \\Sigma_{j} \\quotep{\\stackrel{\\vee}{y_{j'}}|\\stackrel{\\vee}{x_{j}}}.(B_{j'}\\otimes A_{j})\n\\end{mathpar}\n\n\\begin{remark}\n  Do we need to $x^{L}$ and $y^{R}$ for this construction as well?\n\\end{remark}\n\n\\paragraph{Tensor of parallel compositions} Next, we distribute tensor\nover par.\n\n\\begin{mathpar}\n  P_{1}|P_{2} \\otimes Q_{1}|Q_{2} := (P_{1} \\otimes Q_{1}) | (P_{1}\n  \\otimes Q_{2}) | (P_{2} \\otimes Q_{1}) | (P_{2} \\otimes Q_{2})\n\\end{mathpar}\n\n\\paragraph{Tensor with dropped names} We treat tensor of a\nprocess with a dropped name as parallel composition.\n\n\\begin{mathpar}\n  P \\otimes \\dropn{x} := P | \\dropn{x}\n\\end{mathpar}\n\n\\paragraph{Tensor of agents}\n\nFinally, we need to define tensor on agents. Note that the definition\nof tensor on summations only tensors inputs with inputs and outputs\nwith outputs. Thus, we only have to define the operation on\n``homogeneous'' pairings.\n\n\\begin{mathpar}\n  (\\vec{x})P \\otimes (\\vec{y})Q\n  \\and \\\\\n  := (x_{0}^{L}|y_{0}^{R},\\ldots,x_{0}^{L}|y_{n}^{R},\\ldots,x_{m}^{L}|y_{0}^{R},\\ldots,x_{m}^{L}|y_{n}^R)(P\\{ \\vec{x}^{L}/\\vec{x}\\} \\otimes Q \\{ \\vec{y}^{R}/\\vec{y}\\})\n  \\and \\\\\n  \\clift{\\vec{P}} \\otimes \\clift{\\vec{Q}}\n  \\and \\\\\n  := \\clift{P_{0}\\otimes Q_{0},\\ldots,P_{0}\\otimes Q_{n},\\ldots,P_{m}\\otimes Q_{0},\\ldots,P_{m}\\otimes Q_{n}}\n\\end{mathpar}\n\n\\begin{remark}\n  Observe that arities of tensored abstractions matches arities of\n  tensored concretions if the original arities matched. Note also that\n  the length of the arities corresponds to the increase in dimension\n  we see in ordinary vector space tensor product.\n\\end{remark}\n\n\\begin{remark}\n  Operationally, this definition distributes the tensor down to\n  components ``linked'' by summation. Tensor over summation is\n  intriguing in that it mixes names. Moreover, as a consequence of the\n  way it mixes names we have the identities for all $x \\in \\QProc$ and\n  $P,Q \\in \\Proc$\n\n  \\begin{mathpar}\n    (x \\cdot P) \\otimes Q \\equiv x \\cdot (P \\otimes Q) \\equiv P \\otimes (x \\cdot Q)\n    \\and \\\\\n    P \\otimes \\pzero \\equiv P\n  \\end{mathpar}\n\n  that the reader is invited to verify.\n\\end{remark}\n\n\\subsubsection{Annihilation}\n\\begin{mathpar}\n  P^{\\perp} := \\{ Q : \\forall R. P|Q \\red^{*} R \\Rightarrow R \\red^{*} \\pzero \\}\n  \\and \\\\\n  \\annihilate{P} := \\Sigma_{Q \\in P^{\\perp}} \\quotep{Q}?(y).(\\dropn{y}|Q) | \\Sigma_{Q \\in P^{\\perp}} \\quotep{Q}\\clift{\\Box}\n\\end{mathpar}\n\n\\paragraph{Discussion} The reader will note that $P^{\\perp}$ is a\n\\emph{set} of processes, while $\\annihilate{P}$ is a\n\\emph{context}. We call the set $P^{\\perp}$ the \\emph{annihilators} of\n$P$. The parallel composition of a process in the annihilators of $P$\nwith $P$ will result in a process, the state space of which has all\npaths eventually leading to $\\pzero$. Execution may endure loops; but\nunder reasonable conditions of fairness (naturally guaranteed under\nmost notions of bisimulation) such a composite process cannot get\nstuck in such a loop and will, eventually pop out and terminate.\n\nThe context $\\annihilate{P}$ is ready and willing to ``take the\n$P$ out of'' the process to which it is applied. It will effectively\ntransmit the code of the process to which it is applied to one of the\nannihilators and run the process against it.\n\n\\begin{remark}\n  Note that ${\\annihilate{P}}^*$ is the abstraction corresponding to\n  context $\\annihilate{P}$. We will set $\\dualize{P} := {\\annihilate{P}}^*$.\n\\end{remark}\n\n\\subsubsection{Evaluation}\nWe fix $M$ a domain of fully abstract interpretation with an equality\ncoincident with bisimulation. We take $\\meaningof{\\cdot} : \\Proc \\to\nM$ to be the map interpreting processes and $\\nmeaningof{\\cdot} : \\M\n\\to Proc$ to be the map running the other way. Then we define\n\n\\begin{mathpar}\n  \\int P := \\nmeaningof{\\meaningof{P}}\n\\end{mathpar}\n\n\\paragraph{Discussion}\nThere are many fully abstract interpretations of Milner's\n$\\pi$-calculus. Any of them can be used as a basis for interpreting\nthe reflective calculus here. Equipped with such a domain it is\nlargely a matter of grinding through to check that the Yoneda\nconstruction for the normalization-by-evaluation program can be\nextended to this setting.\n\n\\begin{remark}\n  The reader is invited to verify that $\\int (\\annihilate{P}[P]) = 0$,\n  and equivalently $(\\nu\\; x)\\int \\dualize{P}\\langle x \\rangle |\n  x\\clift{P} = 0$.\n\\end{remark}\n\n\\subsection{Quantum mechanics}\n\n\\subsubsection{What is the quantum mechanical notion of continuation?}\\label{sec:quantum_continuation}\n\nImagine the following experimental set-up. Alice, our intrepid quantum\ninvestigator, prepares a state by performing some operation on some\ninitial state. Then she performs some measurement to obtain an\nobservation. Using the information of the observation, she selects a\nnew initial state, operation and measurement and repeats the steps\nabove. She iterates this procedure until she obtains some desired\nobservation. What is the expression of this procedure in the language\nof quantum mechanics?\n\n\\begin{figure}[htp]\\label{fig:iterated_experiment}\n%  \\fbox{\n    \\begin{lstlisting}[mathescape]\n      $\\mathcal{E} ::=$\n      let S = $U \\state{L}$ in (* prepare state*)\n      let m = $\\innerprod{M}{S}^2$ in (* take measurement *)\n      match m with (* use m to decide next experiment *)\n      v$_0$ -> $\\mathcal{E}$\n      | $\\ldots$\n      | v$_N$ -> $\\mathcal{E}$\n      | v$_{Exit}$ -> m (* return observation *)\n    \\end{lstlisting}\n%    }\n  \\caption{Iterated experiment schematic}\n\\end{figure}\n\nFigure \\ref{fig:iterated_experiment} gives a schematic description of\nsuch an iterated experimental procedure. The question is how do we\nwrite down this iterated procedure without stepping outside the\nlanguage of quantum mechanics? Note that accounts of famous composite\nquantum experiments, like the Stern-Gerlach experiment leave the\nlanguage of quantum mechanics to describe the iterated experiment.\n\nWe ask this question for many reasons, but one of them is to help set\nup the exegesis of our interpretation. In our framework\n\\emph{everything} is a computation, both the quantum operations and\nprocesses (classical or quantum) that invoke those operations. There\nis no need to step out of the conceptual (and more pragmatically, the\ncomputational) framework to describe these kinds of experiments. More\nto the point, the framework we are proposing is -- like the hybrid\nfunctional language employed in the schema -- \\emph{compositional}:\nexperiments, computations are built out of experiments and\ncomputations. This is of enormous pragmatic value if we are to build\nand reason about systems of significant scale.\n\n\\begin{remark}\n  It is also worth noting in this connection that this schema is the\n  core of a wide range of recursive functions. Further, this\n  connection to calculations of fixpoints makes it a close neighbor of\n  search techniques like natural selection and the scientific\n  method. This is a theme to which we will return, for quantum\n  information seems very \\emph{unlife-like} in it's uncloneable,\n  undeleteable nature.\n\\end{remark}\n\nReturning the matter of the computational interpretation, our\ninterpretation will take the form of a map, written\n$\\meaningof{-}(-)$, from expressions in Dirac notation to expressions\nin our target reflective calculus. The map takes an \\emph{ancillary}\nargument, a channel along which to communicate results to subsequent\ncomputations. This is how we communicate, for example, the results of\ntaking a measurement to a subsequent step in an experiment.\n\n\\subsubsection{Interpretation}\n\nTable \\ref{tbl:core_qm_op_defns} gives the core operational\ncorrespondences. It is meant as an intuitive guide.\n\n\\begin{table}[htp]\\label{tbl:core_qm_op_defns}\n  \\center{\n    \\fbox{\n      \\begin{tabular}{c|c}\n        quantum mechanics & process calculus \\\\\n        \\hline\n        scalar & $x := \\quotep{P}$ \\\\\n        state vector & $\\state{P} := P$ \\\\\n        dual & $\\state{P}^{*} := \\event{\\annihilate{P}} := \\quotep{\\annihilate{P}}[-]$ \\\\\n        matrix & $ \\Sigma_{\\alpha} \\state{P_{\\alpha}}x_{\\alpha}\\event{Q_{\\alpha}}$ \\\\\n        vector addition & $\\state{P} + \\state{Q} := \\state{P | Q}$ \\\\\n        tensor product & $\\state{P} \\otimes \\state{Q} := \\state{P \\otimes Q}$ \\\\\n        inner product & $\\innerprod{P}{Q} := \\quotep{\\int \\annihilate{P}[Q]}$ \\\\\n      \\end{tabular}\n    }\n  }\n  \\caption{QM - operational definitions}\n\\end{table}\n\n\\paragraph{Discussion}\nThe process algebraic view of a state is called, ironically, a\nprocess, and that is what we map vectors to in our interpretation. It\nhas long been noted in the process algebraic community that names play\na role somewhat similar to scalars in a vector space. What is unique\nabout the reflective calculus, and makes it suitable for an\ninterpretation of this form is that with the structure of names\nreflecting the structure of processes we can both make this similarity\nin a precision instrument; and find a notion of \\emph{dual} to a\nstate. \n\nIf we posit names as scalars, then in perfect analogy with vector\nspaces a dual is a map from processes to names. We actually have two\ncandidates for this interpretation: nominal contexts, $\\quotep{M}$,\nand their corresponding abstraction, $\\quotep{M}^{*}$. The goal of\nsupporting a notion of continuation selects the latter of the two for\nour interpretation.\n\nTaking these as the basis of the interpretation together with the\nalgebraic identities required by the Dirac notation more or less fixes\nthe definitions of the rest of the operations. Among the interesting\nparticularities, the definition of inner product finds near perfect\nmirroring of the Feyman interpretation.\n\n\\begin{mathpar}\n  \\inferrule* [lab=states] {} {\\meaningof{\\state{P}}(c) = c?(l,r).r\\clift{P}}\n  \\and\n  \\inferrule* [lab=events] {} {\\meaningof{\\event{P}}(c) = (x)c?(l,r).l\\clift{\\dualize{P}\\langle x \\rangle} } \n  \\and\n  \\inferrule* [lab=vector addition] {} {\\meaningof{\\state{P} + \\state{Q}}(c) = \\meaningof{\\state{P | Q}}(c)}\n  \\and\n  \\inferrule* [lab=tensor product] {} {\\meaningof{\\state{P} \\otimes \\state{Q}}(c) = \\meaningof{\\state{P\\otimes Q}}(c)}\n  \\and\n  \\inferrule* [lab=inner product] {} {\\meaningof{\\innerprod{P}{Q}}(c) = (\\nu\\; x)c\\clift{\\int \\dualize{P}\\langle x \\rangle | x\\clift{Q}}}\n  \\and\n  \\inferrule* [lab=matrix] {} {\\meaningof{\\fprmatrix{P}{x}{Q}}(c) = \\\\\\\\ (u)(\\nu \\; lr) c!(l,r).(l?(e). (\\nu\\; y)\\meaningof{\\innerprod{\\dropn{e}}{Q}}(x) | x?(z).x?(a).c\\clift{(\\dualize{P}\\sigma(z,a))\\langle u \\rangle}|y!(x) \\\\\\\\\n    + r?(e). (\\nu\\; x)\\meaningof{\\innerprod{P}{\\dropn{e}}}(x) | x?(z).x?(a).c\\clift{Q\\sigma(z,a)}|x!(x_{\\alpha}))}  \n  \\and\n  \\inferrule* [lab=matrix application] {} {\\meaningof{(\\fprmatrix{P}{x}{Q})(\\state{S})}(c) = (\\nu\\; c'u)\\meaningof{\\fprmatrix{P}{x}{Q}}(c')\\langle u \\rangle | \\meaningof{\\state{S}}(c') | c'?(a).c!(a)\n  \\\\\\\\\n  \\meaningof{(\\fprmatrix{P}{x}{Q})(\\event{S})}(c) = (\\nu\\; c'u)\\meaningof{\\fprmatrix{P}{x}{Q}}(c')\\langle u \\rangle | \\meaningof{\\event{S}}(c') | c'?(a).c!(a)}\n\\end{mathpar}\n\nwhere\n\n\\begin{mathpar}\n  P\\sigma(z,a) := P\\{ z\\cdot a\\cdot r/r : r \\in \\freenames{P} \\}\n\\end{mathpar}\n\n\\begin{remark}\n  The reader is invited to verify that\n  \\begin{mathpar}\n    \\meaningof{\\innerprod{P}{Q}}(c)\n    \\and \\\\\n    \\wbbisim \n    \\and \\\\\n    %\\and\n    (\\nu\\; x)(\\nu c'lr)\\meaningof{\\event{P}}(c')\\langle x \\rangle \\;|\\; \\meaningof{\\state{Q}}(c')\n    %\\and\n    |\\; c'!(l,r).l?(p).r?(q).c\\clift{\\int \\dropn{p} | x!(q)}\n  \\end{mathpar}\n  This provides a (more) compositional definition of inner product. It\n  also illustrates an important point of the computational\n  interpretation. We have a notion of equivalence providing a crucial\n  proof method: bisimulation.\n\\end{remark}\n\n\\begin{remark}\n  Assuming $\\int (\\annihilate{P}[P]) = 0$, the reader is\n  invited to verify that $(\\fprmatrix{P}{x}{P})(\\state{P}) = x \\cdot \\state{P}$.\n\\end{remark}\n\n% \\begin{remark}\n%   The reader is invited to verify that $\\innerprod{P}{Q}$ could\n%   equally well have been written $\\quotep{\\int \\stackrel{\\vee}{x}}$\n%   where $x = \\event{\\annihilate{P}}(Q)$.\n\n%   One of the motivations for this remark is that there is another way\n%   to factor these operations. We could package up evaluation in the dual:\n\n%   \\begin{mathpar}\n%     \\state{P}^{*} := \\event{\\int \\annihilate{P}} := \\quotep{\\int \\annihilate{P}}[-]\n%   \\end{mathpar}\n\n%   and then have inner product defined by\n  \n%   \\begin{mathpar}\n%     \\innerprod{M}{Q} := \\event{M}(Q)\n%   \\end{mathpar}\n\n%   where we use $M$ to label the dual to emphasize that it is a context.\n\n%   Hopefully, experience with the calculations will provide guidance on\n%   the best factoring.\n% \\end{remark}\n\n\\begin{remark}\\label{rem:abstract_scalars}\n  Assuming $\\int (\\annihilate{P}[P]) = 0$, the reader is\n  invited to verify that $\\forall P,Q. (\\prmatrix{0}{Q})(\\state{0}) =\n  \\state{0}$ and dually $(\\prmatrix{P}{0})(\\event{0}) = \\event{0}$.\n\\end{remark}\n\n\\subsubsection{Interpreting continuations}\n\nAs promised, we can combine these interpretations with standard\nsemantics for conditionals and continuations to provide an\ninterpretation of the iterated experiment.\n\n\\begin{lstlisting}[mathescape]      \n  $\\ldb$ let S = $U \\state{L}$ in \n  let m = $\\innerprod{M}{S}^2$ in \n  match m with \n  v$_0$ -> $\\mathcal{E}$\n  | $\\ldots$\n  | v$_N$ -> $\\mathcal{E}$\n  | v$_{Exit}$ -> m $\\rdb(c)$\n  $=$\n  $(\\nu\\; c')\\meaningof{\\innerprod{M}{U\\state{L}}}(c')$\n  $| c'?(m).m!(m) | \\Sigma_{i=0}^{N}v_{i}?(m).\\meaningof{\\mathcal{E}} + v_{Exit}?(m).c!(m)$\n\\end{lstlisting}\n\n\\paragraph{A quick tally}\nAlready the interpretation is beginning to show signs of\npromise. First of all, it is no more notationally cumbersome than the\nnotation used in QM calculations. Beyond syntax, we have a new proof\nprinciple in hand and the ability to reason about more complex\nexperimental situations than is directly calculable in ordinary\nquantum mechanics.\n\n\\subsubsection{Adjointness}\n\nWe need to give a definition of $(\\cdot)^{\\dagger}$ for matrices. The\nobvious candidate definition is\n\\begin{mathpar}\n\\meaningof{(\\fprmatrix{P}{x}{Q})^{\\dagger}}(c)\n= (\\nu\\; u)\\meaningof{\\fprmatrix{\\dualize{Q}\\langle u \\rangle}{\\overline{x}}{\\dualize{P}\\langle u \\rangle}}(c) \n\\end{mathpar}\n\n% But, $(Q_{\\alpha}^{\\underline{\\perp}})^{*}$ requires a name along\n% which to communicate the process to achieve the context application.\n\n\\begin{remark}\n  i'm a little worried that i don't (yet) have proper support for\n  complex conjugacy. But, the observation above may give us a\n  clue. According to Abramsky, it must be the case that the scalars\n  are iso to the homset of the identity for the tensor -- which the\n  observation above (\\ref{rem:abstract_scalars}) characterizes. For\n  now, we will simply bookmark the notion with $\\overline{x}$.\n\\end{remark}\n\n\\subsubsection{Basis for a basis}\nIf processes label states and ``addition'' of states (a.k.a. vector\naddition) is interpreted as parallel composition, what corresponds to\nnotions of linear independence and basis? Here, we recall that Yoshida\nhas developed a set of \\emph{combinators} for an asynchronous verison\nof Milner's $\\pi$-calculus \\cite{DBLP:conf/concur/Yoshida98}. These\nare a finite set of processes such any process can be expressed as\nparallel composition of these combinators together with liberal uses\nof the new operator and replication. We can simply give a translation\nof these into the present calculus and have reasonable expectation\nthat the property carries over. That is, that the resultant set allows\nto express all processes via parallel composition. Note, however, that\nthere is no new operator or replication in this calculus. As a result,\nwe expect that the corresponding set is actually infinite. That is, we\nexpect that the space is actually infinite dimensional.\n\n\\begin{remark}\n  The reader familiar with the lambda calculus may reasonably object:\n  certainly, the collection $S$, $K$ and $I$ is a finite set of\n  combinators \\cite{Barendregt84}. Shouldn't we expect to see a finite\n  set of combinators for an effectively equivalent system? i am very\n  sympathetic to this critique and feel it warrants full attention. On\n  the other hand, i also have in mind the following analogy. The\n  natural numbers, as a monoid under addition, has exactly $1$\n  generator, while the natural numbers, as a monoid under\n  multiplication, has countably many generators (the primes). We\n  observe that the application of the lambda calculus is much less\n  resource sensitive than the parallel composition of the\n  $\\pi$-calculus. Could it be the case that we have an analogy of the\n  form\n  \n  \\begin{mathpar}\n    m + n : MN :: m*n : M|N\n  \\end{mathpar}\n\n  giving a similar blow up in the set of ``primes''?  This is such a\n  wonderful thought that, even if it's not true, i think it's worth\n  writing down.\n\\end{remark}\n", "meta": {"hexsha": "a6b58eb12e8ca99cc437be5e22c588e30944b0af", "size": 20141, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "qm2pi/qm2pi.qmops.tex", "max_stars_repo_name": "leithaus/pi4u", "max_stars_repo_head_hexsha": "c87163938857589153eb5225d0e4ac17597fd189", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2015-10-12T20:35:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T00:37:17.000Z", "max_issues_repo_path": "qm2pi/qm2pi.qmops.tex", "max_issues_repo_name": "leithaus/pi4u", "max_issues_repo_head_hexsha": "c87163938857589153eb5225d0e4ac17597fd189", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2018-07-06T19:01:06.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-19T22:39:58.000Z", "max_forks_repo_path": "qm2pi/qm2pi.qmops.tex", "max_forks_repo_name": "leithaus/pi4u", "max_forks_repo_head_hexsha": "c87163938857589153eb5225d0e4ac17597fd189", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2016-10-03T06:03:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-16T00:37:25.000Z", "avg_line_length": 42.4915611814, "max_line_length": 228, "alphanum_fraction": 0.7062707909, "num_tokens": 6053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.3414343228901938}}
{"text": "\\subsubsection{\\stid{3.05} Enabling Time Integrators for Exascale Through SUNDIALS} \r\n\r\n\\paragraph{Overview} \r\n\r\nThis project is enhancing the SUNDIALS library of numerical software packages for integrating differential systems in time using state-of-the-art adaptive time step technologies for use on exascale systems.  Through software infrastructure developments, this project is enabling the efficient and robust SUNDIALS time integrator packages to easily interoperate with external linear and nonlinear solver packages developed for exascale computing.  In addition, this project is providing a many-vector capability so that SUNDIALS time integrators can more easily operate on data divided over heterogeneous architectures.  Lastly, this project is supporting the deployment and use of SUNDIALS packages within ECP applications, mainly through incorporation into the discretization-based Co-Design Centers, AMReX and CEED.\r\n\r\nEfficient time integrators are essential for ECP because they are at the core of every time-dependent simulation application.  However, many applications do not use state-of-the-art methods, and if they do, they often do not yet use them fully on their systems.  For example, at the start of the ECP the astrophysics code, Nyx, used an adaptive integration package for solving individual reactions.  However, by applying a time integration package to a larger reaction system, the code is able to vectorize more of the calculations and get an accurate solution much faster.  By allowing for solvers tuned to exascale systems and vectors that are heterogeneous, SUNDIALS will be more applicable for use in multiphysics systems running on exascale platforms.\r\n\r\n\r\n\r\n\\paragraph{Key  Challenges}\r\n\r\nCurrent implementations of efficient time integrators face challenges on many fronts.  First, integrators typically have treated the full physical problem with a single step size or have relied on low order operator splitting methods to couple physical processes at different time scales. While research is moving forward within the time integration community on methods for multirate systems, the software infrastructure needs to be in place to accommodate these schemes once they are developed.   Second, typical integrators operate on problem data in the form of vectors.  These operations suffer from low arithmetic intensity, and their efficiency is often memory bandwidth limited.  Lastly, implicit integrators, which are required in many exascale systems, require efficient linear and nonlinear solvers to be highly effective.  In addition, by applying integrator-dependent controls on these solvers, their efficiency can be significantly increased.  Applying these controls, however, often requires that information about the integrator and its progress be passed to the solver, and software must be designed to effectively pass that information while ensuring adequate encapsulation to provide ease of maintenance and software extension.\r\n\r\n\\paragraph{Solution Strategy}\r\n\r\nThis project includes a number of implementation activities that will prepare the SUNDIALS suite of time integrators for exascale systems. The main activity is a redesign of all linear solver interfaces and encapsulation of the nonlinear solvers within the time integrators in SUNDIALS.  The new linear solver interfaces will make it much easier to interface external solver packages while maintaining the efficiency of SUNDIALS integrators. Encapsulating the nonlinear solvers, will reduce redundant code and allow the time integrators to better leverage common code thus lowering the code maintenance burden with SUNDIALS.  In addition, the integrators will be able to take advantage of outside nonlinear solvers.  \r\n\r\nThis project is also introducing a set of optional fused vector kernels into SUNDIALS.  The goal of these kernels is to execute multiple vector operations at once thereby reducing the number of kernel launches in GPU environments and also reducing the number of communications required for reduction operations.  These new kernels will be added to all supplied SUNDIALS vectors and will be invoked through optional interfaces.\r\n\r\nLastly, this project is developing a many-vector capability for SUNDIALS.  Due to the tight data encapsulation within SUNDIALS, users are able to supply any vector they would like underneath the integrators.  This project will supply the infrastructure needed to make it easy to place a vector of vectors underneath the integrators.  This vector of vectors is essential for later implementation of time integrators that will advance various parts of the system with different time step sizes.  This many-vector capability will also ease the use of different programming environments as differing vectors can be instantiated on different parts of a hybrid machine. \r\n\r\n\\paragraph{Recent Progress}\r\n\r\nIn September of 2017, SUNDIALS 3.0.0 including new linear solver and matrix interfaces, was released \\cite{SUNDIALSweb}.  Figure \\ref{fig:sunorg1} shows the new organization of SUNDIALS where separate linear solver interfaces are provided for direct and iterative linear solver methods.  These interfaces are shared across all SUNDIALS integrators.  Individual integrators have the freedom to supply specific information from the integrator that controls the linear solver.  In addition, a single interface to each external solver, such as SuperLU\\_MT or KLU, is shared across the suite, as opposed to the prior situation where each integrator included its own interface to each solver.  In addition, a SUNMATRIX class was developed that can be instantiated with a dense, banded, or sparse matrix.  Again, this class is shared by all integrators.  \r\n\r\n\\begin{figure}[htb]\r\n\t\\centering\r\n\t\\includegraphics[width=6in]{projects/2.3.3-MathLibs/2.3.3.05-SUNDIALS/sunorg1.pdf}\r\n\t\\caption{\\label{fig:sunorg1}New structure of SUNDIALS showing options for the new SUNLINEARSOLVER and SUNMATRIX classes.}\r\n\\end{figure}\r\n\r\n\\paragraph{Next Steps}\r\n\r\nDuring the remainder of FY18, this project team will:\r\n\\begin{enumerate}\r\n\\item Complete a release of SUNDIALS with the new fused vector routines implemented within each supplied vector and optionally used from the integrator packages.\r\n\\item Complete a release of SUNDIALS with all nonlinear solvers encapsulated and with implementations of the new nonlinear solver interfaces for both the Newton and fixed point solvers used in the integrator packages.\r\n\\end{enumerate}\r\n", "meta": {"hexsha": "fb03fd88bd78e363cc018646ada09cc488ef7ed3", "size": 6472, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "projects/2.3.3-MathLibs/2.3.3.05-SUNDIALS/2.3.3.05-SUNDIALS.tex", "max_stars_repo_name": "tgamblin/ECP-ST-CAR-PUBLIC", "max_stars_repo_head_hexsha": "74d6fb18bae7ff1c32b78dd8cd7ae29e91218c33", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "projects/2.3.3-MathLibs/2.3.3.05-SUNDIALS/2.3.3.05-SUNDIALS.tex", "max_issues_repo_name": "tgamblin/ECP-ST-CAR-PUBLIC", "max_issues_repo_head_hexsha": "74d6fb18bae7ff1c32b78dd8cd7ae29e91218c33", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "projects/2.3.3-MathLibs/2.3.3.05-SUNDIALS/2.3.3.05-SUNDIALS.tex", "max_forks_repo_name": "tgamblin/ECP-ST-CAR-PUBLIC", "max_forks_repo_head_hexsha": "74d6fb18bae7ff1c32b78dd8cd7ae29e91218c33", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 161.8, "max_line_length": 1247, "alphanum_fraction": 0.8204573548, "num_tokens": 1301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102955, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.34141802024232093}}
{"text": "\\def\\Arccosh{{\\rm Arccosh}}\n\\advance\\sectioncount by -1\n\\section{Introduction}\n\nThis paper documents a computer-assisted procedure\nfor rigorously analyzing small hyperbolic $3$-manifolds.\nBriefly, we will define a compact six-dimensional space ${\\cal P}$\nthat parameterizes pairs of elements of ${\\rm Isom}({\\bf H}^3)$,\nand then construct a regular binary space partition (BSP) tree\nwhich subdivides ${\\cal P}$ into subregions ${\\cal P_i}$\nand whose leaves are --- with a few exceptions --- labeled with killerwords.\nThese killerwords will encode miniature proofs that ${\\cal P_i}$\ncannot contain any points which correspond to\nparticular choices of pairs of generators of\nany torsion-free discrete group of ${\\rm Isom}({\\bf H}^3)$.\nThis tree of mini-proofs will then be used\nto exhaustively isolate all possible manifolds\nwhich can have properties related to the dimensions of ${\\cal P}$.\n\nThe first two applications of the procedure\nwere used to prove a proposition from [GMT]:\n\\proclaim{Proposition [GMT]}\nLet $M$ be an orientable hyperbolic $3$-manifold, and let $\\delta$ be\na shortest geodesic. Then, either ${\\it tuberadius}(\\delta) > \\ln(3)/2$,\nor $M$ lies within one of seven tightly constrained\nexceptional shortest-geodesic-geometry regions.\n\\endproclaim\nand a related proposition; both of which were used in the proof of\nthe main technical result of [GMT]:\n\\proclaim{Theorem [GMT]}\nEvery closed hyperbolic $3$-manifold\nhas a non-coalescible insulator family,\nindeed one coming from a shortest geodesic.\nAs a consequence,\nhomotopy hyperbolic $3$-manifolds are hyperbolic.\n\\endproclaim\nMore recently, the proposition has been sharpened:\n\\proclaim{Theorem}\nLet $M$ be an orientable hyperbolic $3$-manifold,\nand let $\\delta$ be a shortest geodesic.\nThen, either ${\\it tuberadius}(\\delta) > \\ln(3)/2$, or\n$M$ is isometric to one of seven specific manifolds.\n\\endproclaim\n\\demo{Proof}\nLet $X_0, \\cdots, X_6$ denote the exceptional regions of Theorem FIXME(2.XX),\nwith $N_i$ the corresponding conjectural manifold.\n[GMT] showed that $N_0$=Vol3 is the unique manifold in the region\nand [JR] showed that Vol3 covered no 3-manifold.\n[JR] also proved that $N_5$ and $N_6$ are isometric.\n[CLLMR] and [L] identify a manifold in each region\nand [CLLMR] show that these manifolds are the unique ones in its region.\n[CLLMR] show that $N_1$, $N_5$ and $N_6$ cover no manifold.\nIn [GT] the proof is completed by showing that $N_3$ covers no manifold\nand each of $N_2$ and $N_4$ 2-fold cover manifolds,\nhowever the quotients are all non exceptional,\ni.e. each shortest geodesic has a $ln(3)/2$ tube.\n\\enddemo\n\nOther applications of the procedure:\n\nTheorem [G]  (Smale conjecture of hyperbolic 3-manifolds)\nIf N is a closed hyperbolic 3-manifold,\nthen the natural inclusion ${\\rm Isom}(N)\\to {\\rm Diff}(N)$ is a homotopy equivalence.\n\nThe proof made essential use of the fact that a shortest geodesic\nof a closed hyperbolic 3-manifold satisfies the insulator condition [GMT].\n\nTheorem [GMM], [Mi] The Week's manifold\nis the unique closed orientable hyperbolic 3-manifold of minimal volume.\n\nThis result relies on \n\nLemma [ACS] Suppose that M is a closed, orientable hyperbolic 3-manifold,\nand that C is a shortest geodesic in M.\nSet $N = \\rm{drill}_C(M)$. If $\\rm{tuberad}(C) \\ge \\ln(3)/2$ then\n$\\rm{vol} N < 3:0177 \\rm{vol}M$.\n\nThis is based on a result of [ADST],\nthat makes essential use of Perelman's [Pe] monotonicty result.\na key element of his proof of geometrization and the $\\ln(3)/2$\ntheorem of [GMT].\nLemma [ACS] is used to prove other results such as \n\nTheorem [ACS] Suppose that M is a closed, orientable, hyperbolic\n3-manifold such that ${\\rm vol}(M) \\le 1.22$.\nThen $H_1(M:Zp)$ has dimension at most 3 for every prime p.\n\n(The statement is sharpened slightly to take into account [GT])\n\nTheorem [LM] Let M be a compact orientable 3-manifold with boundary a torus,\nand with interior admitting a complete finite-volume hyperbolic structure.\nThen the number of exceptional slopes on M is at most 10.\n\nThis result, known as the Gordon conjecture,\nrelies on rigorous computer assistance using the AffApprox technology.\n\nFinally, the procedure is currently in use\nby Gabai, Haraway, Meyerhoff, Thurston, and Yarmola\nto rigorously analyze small orientable cusped hyperbolic $3$-manifolds,\nand to rigorously analyze small non-orientable closed hyperbolic $3$-manifolds.\n\n\nThis paper is organized as follows.\n\nIn Section 1 we introduce [GMT; Proposition 2.8] as Theorem FIXME(2.19),\nand sketch its proof.\n\nIn Section 2 we provide a formal statement and proof of Theorem FIXME(2.19).\n\nIn Section 3,\nthe method for describing the decomposition\nof the parameter space ${\\cal W}$ into sub-regions is given,\nand the conditions used to eliminate sub-regions are discussed.\nNear the end of this section, the first part of a detailed example is given.\n\nEliminating \na sub-region requires that a certain function is shown to be bounded \nappropriately over the entire sub-region.  This is carried out by using a \nfirst-order Taylor approximation of the function together with a \nremainder \nbound.\nOur computer version of such a Taylor approximation with remainder bound \nis called an {\\it AffApprox} and in Section 4,\nthe relevant theory is developed.\nAt this point, the detailed example of Section 3 can be completed.\n\nIn Sections 5 and 6, round-off error analysis appropriate to our \nset-up is introduced.  Specifically, in Section 6, round-off error is \nincorporated \ninto the {\\it AffApprox} formulas introduced in Section 4.  The proofs here \nrequire an analysis of round-off error for complex numbers, which is carried \nout in Section 5.\n\nIn Section 7 we give some hints about the search for a atree,\nin the hope that they will help others endeavoring to apply these methods.\n\nFinally, in Section 8, we present an updated version of\nthe code used to check that the proof is valid,\nwith self-contained copies of the proofs required for the reader\nto check its own validity.\n\n{\\it Prior publication}\nSections 2 through 6 originally appeared in [GMT],\nand are reproduced here with only minor revision.\nSection 1 is an abridged version of the parts of the rest of [GMT].\nSection 7 borrows from material which originally appeared in remarks in [GMT].\n\n{\\it Acknowledgements}.\nFIXME\n", "meta": {"hexsha": "56b277acb017484f685d8eeaae088d7dd91bdc7b", "size": 6270, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/TeX_and_Figures_Files/Chapter_0.tex", "max_stars_repo_name": "njt99/findingkillerwords", "max_stars_repo_head_hexsha": "71271dca14a9986d631608929544bcd6d68813f0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thesis/TeX_and_Figures_Files/Chapter_0.tex", "max_issues_repo_name": "njt99/findingkillerwords", "max_issues_repo_head_hexsha": "71271dca14a9986d631608929544bcd6d68813f0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis/TeX_and_Figures_Files/Chapter_0.tex", "max_forks_repo_name": "njt99/findingkillerwords", "max_forks_repo_head_hexsha": "71271dca14a9986d631608929544bcd6d68813f0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.8, "max_line_length": 86, "alphanum_fraction": 0.7685805423, "num_tokens": 1686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3414180135742385}}
{"text": "% \\documentclass[a4paper, 10px]{ctexart}\n\\documentclass{ctexart}\n\\usepackage[left=1in, right=1in, top=1.2in, bottom=1.2in]{geometry}\n\\usepackage{ctex}\n\\usepackage[utf8]{inputenc}\n\\usepackage{boxproof}\n\\usepackage{fontspec}\n\\usepackage{a4wide}\n% \\setmainfont[Scale = 1]{SF Display}\n% \\setCJKmainfont{Songti SC}\n\\usepackage{fancyhdr}\n\n% Automata\n\\usepackage{tikz}\n\\usetikzlibrary{automata, positioning, arrows}\n\n\\pagestyle{fancy}\n\\fancypagestyle{plain}{\n    \\fancyhead[L]{East China Normal University}\n    \\fancyhead[R]{}\n    \\fancyfoot[C]{\\thepage}\n}\n\n\\tikzset{\n->, % makes the edges directed\n>=stealth, % makes the arrow heads bold\nnode distance=3cm, % specifies the minimum distance between two nodes. Change if necessary.\nevery state/.style={thick, fill=gray!10}, % sets the properties for each ’state’ node\ninitial text=$start$, % sets the text that appears on the start arrow\n}\n\n\\def\\premise{\\mathrm{premise}}\n\\def\\assumption{\\mathrm{assumption}}\n\\def\\MT{\\mathrm{MT\\ }}\n\\def\\LEM{\\mathrm{LEM}}\n\\def\\intro{\\mathrm{i\\ }}\n\\def\\elim{\\mathrm{e\\ }}\n\\def\\introa{\\mathrm{i_1\\ }}\n\\def\\elima{\\mathrm{e_1\\ }}\n\\def\\introb{\\mathrm{i_2\\ }}\n\\def\\elimb{\\mathrm{e_2\\ }}\n\n\\title{Computation Theory Assignment 4}\n\\author{10185101210 陈俊潼}\n\\date{September 2020}\n\n\\begin{document}\n\n\\maketitle\n\n\\section{Automata}\n\n\\subsection{This is an automata.}\n\nTo draw an automata, you need to first import \\texttt{tikz} package.\n\nFigure \\ref{aut1} is an example:\n\n\n\\begin{figure}[ht]\n    \\centering\n    \\begin{tikzpicture}[scale=2]\n        \\node[state, initial] (0) {$q_0$};\n        \\node[state, above right of=0] (1) {$q_1$};\n        \\node[state, right of=1] (2) {$q_2$};\n        \\node[state, above right of=2, accepting] (3) {$q_3$};\n        \\node[state, below right of=2, accepting] (4) {$q_4$};\n        \\node[state, below right of=0] (5) {$q_5$};\n        \\node[state, right of=5] (6) {$q_6$};\n        \\node[state, right of=6] (7) {$q_7$};\n        \\node[state, right of=7, accepting] (8) {$q_8$};\n        \\draw (0) edge[above] node{$a$} (1)\n                (1) edge[above] node{$b$} (2)\n                (2) edge[above] node{$c$} (3)\n                (2) edge[above] node{$d$} (4)\n                (0) edge[above] node{$c$} (5)\n                (5) edge[above] node{$c$} (6)\n                (6) edge[above] node{$c$} (7)\n                (7) edge[above] node{$c$} (8);\n    \\end{tikzpicture}\n    \\caption{An automata example}\n    \\label{aut1}\n\\end{figure}\n\\end{document}\n", "meta": {"hexsha": "5672a700775dedd251ac502e4f96fb16184a1022", "size": 2438, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Course/ComputationTheory/Assignment1/Assignment1.tex", "max_stars_repo_name": "AixMoon/LearnigRepo", "max_stars_repo_head_hexsha": "ee98fb352735e2b4f97304847b6c0311bc30195e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2020-05-02T20:06:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-24T10:01:29.000Z", "max_issues_repo_path": "Course/ComputationTheory/Assignment1/Assignment1.tex", "max_issues_repo_name": "AixMoon/LearnigRepo", "max_issues_repo_head_hexsha": "ee98fb352735e2b4f97304847b6c0311bc30195e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Course/ComputationTheory/Assignment1/Assignment1.tex", "max_forks_repo_name": "AixMoon/LearnigRepo", "max_forks_repo_head_hexsha": "ee98fb352735e2b4f97304847b6c0311bc30195e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-06-04T04:29:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-15T08:15:01.000Z", "avg_line_length": 28.6823529412, "max_line_length": 91, "alphanum_fraction": 0.6255127153, "num_tokens": 853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.34141801024019724}}
{"text": "\\documentclass{article}\n\\usepackage{a4wide}\n\\usepackage{amsmath}\n\\usepackage[colorlinks=true,linkcolor=blue,citecolor=blue]{hyperref}\n\\usepackage[sort&compress,comma,authoryear]{natbib}\n\\newcommand{\\Prob}[0]{\\mbox{Prob}}\n\\newcommand{\\ul}[1]{\\underline{#1}}\n\\newcommand{\\ol}[1]{\\overline{#1}}\n\\usepackage{bm}\n\\usepackage{latexsym}\n\n\n\\title{DEB model description: 'hex'}\n%\\author{S.A.L.M. Kooijman and K. Lika and S. Augustine and N. Marn and others?}\n\n\n\\begin{document}\n\n\\maketitle\n\nThis document specifies the standard DEB model 'hex'.\nThe {\\sc deb} model for holometabolic insects (and some other hexapods). Its characteristics are\n\\begin{description}\n  \\item[$\\circ$] morphological life stages: egg, larva, (pupa), imago; functional stages: embryo, adult, (pupa), imago\n\t\n  \\item[$\\circ$] the embryo still behaves like the std-model\n\t\n  \\item[$\\circ$] the larval stage accelerates (V1-morph) and behaves as adult, i.e. no maturation, allocation to reproduction and $E_H^b = E_H^p$.\n\t\n  \\item[$\\circ$] pupation occurs when reproduction buffer density hits a threshold, $E_R/ L^3 = [E_R^j]$\n\t\n  \\item[$\\circ$] pupa behaves like an isomorphic embryo of the std-model, emergence occurs at $E_H = E_H^e$\n\t  Larval structure rapidly transforms to pupal reserve just after start of pupation, and sets $E_H = 0$ at $j$.\n\t\t\n  \\item[$\\circ$] the reproduction buffer remains unchanged during the pupal stage\n\t\n  \\item[$\\circ$] the imago does not grow or allocate to reproduction. \n\t  Imago's reserve mobilisation matched somatic plus maturity maintenance $\\dot{p}_C = \\dot{p}_M + \\dot{p}_J$.\n\\end{description}\nHemi-metabolic insects skip the pupal stage, don't convert larval structure to reserve. \nImago structure equals larval structure when reproduction buffer density hits a threshold.\nThe model is discussed in the comments for Section 7.8.\n\nFor $\\dot{k}_E = \\dot{v}/ L_b$, reserve mobilisation prior to pupation (i.e. during acceleration) is $\\dot{p}_C = E (\\dot{k}_E - \\dot{r})$ \n  with $\\dot{r} = \\frac{\\kappa [E] \\dot{k}_E - [\\dot{p}_M]} {\\kappa [E] + [E_G]} = g \\dot{k}_M \\frac{e/ l_b - 1} {e + g}$.\nThe larva allocates to reproduction as $\\dot{p}_R = (1- \\kappa) \\dot{p}_C - \\dot{p}_J$, with $\\dot{p}_J = \\dot{k}_J E_H^p$.\n$[E_R]$ has a maximum at $[E_R^m] = [E_R^{\\mbox{\\tiny ref}}] f \\frac{1 - l_b} {f - l_b}$ with$[E_R^{\\mbox{\\tiny ref}}] = (1 - \\kappa) [E_m] \\frac{g + l_b} {1 - l_b}$, so pupation occurs when $[E_R] = s_j [E_R^{\\mbox{\\tiny ref}}]$, with $s_j = [E_R^j]/ [E_R^{\\mbox{\\tiny ref}}]$.\n\nReserve mobilisation of the imago is $\\dot{p}_C = \\dot{p}_M^e + \\dot{p}_J^e$, where $\\dot{p}_M^e = [\\dot{p}_M] L_e^3$ and $\\dot{p}_J^e = \\dot{k}_J E_H^e$.\n\n\n\\section{Background}\n\n\\input{model_intro}\n\n\\input{std_description}\n\n\\bibliographystyle{apalike}\n\\bibliography{debmodels}\n\n\\end{document}", "meta": {"hexsha": "942c7303379e3be8cbed8e5f5f0bd1dbde36b58f", "size": 2798, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/models/hex.tex", "max_stars_repo_name": "add-my-pet/AmPtool-new", "max_stars_repo_head_hexsha": "f60cdd10c65c0190ca41ba6fbd4d5018c5aea771", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/models/hex.tex", "max_issues_repo_name": "add-my-pet/AmPtool-new", "max_issues_repo_head_hexsha": "f60cdd10c65c0190ca41ba6fbd4d5018c5aea771", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/models/hex.tex", "max_forks_repo_name": "add-my-pet/AmPtool-new", "max_forks_repo_head_hexsha": "f60cdd10c65c0190ca41ba6fbd4d5018c5aea771", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.868852459, "max_line_length": 278, "alphanum_fraction": 0.6940671909, "num_tokens": 961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.341418006906156}}
{"text": "\\documentclass[10pt]{beamer} % aspect ratio 4:3, 128 mm by 96 mm\n%\\documentclass[10pt,aspectratio=169]{beamer} % aspect ratio 16:9\n\\graphicspath{{../journal_papers/Elsevier/figs/}}\n%\\includeonlyframes{frame1,frame2,frame3}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Packages\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\usepackage{appendixnumberbeamer}\n\\usepackage{booktabs}\n\\usepackage[scale=2]{ccicons}\n\\usepackage{pgfplots}\n\\usepackage{xspace}\n\\usepackage{amsmath}\n\\usepackage{totcount}\n\\usepackage{tikz}\n%\\usepackage{comment}\n%\\usetikzlibrary{external} % speedup compilation\n%\\tikzexternalize % activate!\n%\\usetikzlibrary{shapes,arrows}  \n\n%\\usepackage{bibentry}\n\n\\usepackage{caption}%\n\\captionsetup[figure]{labelformat=empty}%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Metropolis theme custom modification file\n\\input{metropolis_mods.tex}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Custom commands\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% matrix command \n\\newcommand{\\matr}[1]{\\mathbf{#1}} % bold upright (Elsevier, Springer)\n%\\newcommand{\\matr}[1]{#1}          % pure math version\n%\\newcommand{\\matr}[1]{\\bm{#1}}     % ISO complying version\n% vector command \n\\newcommand{\\vect}[1]{\\mathbf{#1}} % bold upright (Elsevier, Springer)\n\\newcommand{\\ud}{\\mathrm{d}}\n\\renewcommand{\\vec}[1]{\\mathbf{#1}}\n\\newcommand{\\veca}[2]{\\mathbf{#1}{#2}}\n\\newcommand{\\bm}[1]{\\mathbf{#1}}\n\\newcommand{\\bs}[1]{\\boldsymbol{#1}}\n% derivative upright command\n\\DeclareRobustCommand*{\\drv}{\\mathop{}\\!\\mathrm{d}}\n% \n\\newcommand{\\themename}{\\textbf{\\textsc{metropolis}}\\xspace}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%  Title page options\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% \\date{\\today}\n\\date{15.08.2019}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% option 1\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\\title{Parallel spectral element method for guided wave based structural health monitoring}\n%\\subtitle{}\n%\\author{\\textbf{Paweł Kudela}\\\\Jochen Moll \\\\Piotr Fiborek}\n% logo align to Institute \n%\\institute{Institute of Fluid Flow Machinery\\\\Polish Academy of Sciences \\\\ \\vspace{-1.5cm}\\flushright \\includegraphics[width=4cm]{../images/logo/logo_eng_40mm.eps}}\n%\\institute{Institute of Fluid Flow Machinery\\\\Polish Academy of Sciences \\\\ \\vspace{-1.5cm}}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% option 2 - authors in one line\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\t\\title{Parallel spectral element method for guided wave based structural health monitoring}\n%\t\\subtitle{Lamb-opt}\n\t\\author{\\textbf{Paweł Kudela}\\textsuperscript{1}, Jochen Moll\\textsuperscript{2}, Piotr Fiborek\\textsuperscript{1} }\n%\t% logo align to Institute \n%\t\\institute{\\textsuperscript{1}Xi'an Jiaotong University \\\\ \\textsuperscript{2}Institute of Fluid Flow Machinery\\\\ \\hspace*{1pt} Polish Academy of Sciences \\\\ \\vspace{-1.5cm}\\flushright \\includegraphics[width=4cm]{../images/logo/logo_eng_40mm.eps}}\n\t\\institute{ \\textsuperscript{1}Institute of Fluid Flow Machinery\\\\ \\hspace*{1pt} Polish Academy of Sciences \\\\ \\\\ \\textsuperscript{2}J.W. Goethe University\\\\ \\hspace*{1pt} Department of Physics \\vspace{-1.5cm}}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% option 3 - multilogo vertical\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\\title{Elastic constants identification of composite laminates by using Lamb wave dispersion curves and optimization methods}\n%\\subtitle{Lamb-opt}\n%\t\\author{\\textbf{Paweł Kudela}\\inst{1}, Maciej Radzieński\\inst{1}, Wiesław Ostachowicz\\inst{1}, Zhibo Yang\\inst{2} }\n%\t% logo under Institute \n%\t\\institute%\n%\t{ \n%\t\t\\inst{1}%\n%\t\tInstitute of Fluid Flow Machinery\\\\ \\hspace*{1pt} Polish Academy of Sciences \\\\ \\includegraphics[height=0.85cm]{../images/logo/logo_eng_40mm.eps} \\\\\n%\t\t\\and\n%\t\t\\inst{2}%\n%\t    Xi'an Jiaotong University \\\\ \\includegraphics[height=0.85cm]{../images/logo/logo_box.eps}\n%    }\n% end od option 3\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% option 4 - 3 Institutes and logos horizontal centered\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\\title{Elastic constants identification of composite laminates by using Lamb wave dispersion curves and optimization methods}\n%\\subtitle{Lamb-opt }\n%\\author{\\textbf{Paweł Kudela}\\textsuperscript{1}, Maciej Radzieński\\textsuperscript{1}, Marco Miniaci\\textsuperscript{2}, Zhibo Yang\\textsuperscript{3} }\n%\n%\\institute{ \n%\\begin{columns}[T,onlytextwidth]\n%\t\\column{0.39\\textwidth}\n%\t\\begin{center}\n%\t\t\\textsuperscript{1}Institute of Fluid Flow Machinery\\\\ \\hspace*{3pt}Polish Academy of Sciences\n%\t\\end{center}\n%\t\\column{0.3\\textwidth}\n%\t\\begin{center}\n%\t\t\\textsuperscript{2}Zurich University\n%\t\\end{center}\n%\t\\column{0.3\\textwidth}\n%\t\\begin{center}\n%\t\t\\textsuperscript{3}Xi'an Jiaotong University\n%\t\\end{center}\n%\\end{columns}\n%\\vspace{6pt}\n%% logos \n%\\begin{columns}[b,onlytextwidth]\n%\t\\column{0.39\\textwidth}\n%\t\t\\centering \n%\t\t\\includegraphics[width=\\textwidth,height=0.85cm,keepaspectratio]{../images/logo/logo_eng_40mm.eps}\n%\t\\column{0.3\\textwidth}\n%\t\t\\centering \n%\t\t\\includegraphics[width=\\textwidth,height=0.85cm,keepaspectratio]{../images/logo/logo_box.eps}\n%\t\\column{0.3\\textwidth}\n%\t\t\\centering \n%\t\t\\includegraphics[width=\\textwidth,height=0.85cm,keepaspectratio]{../images/logo/logo_box2.eps}\n%\\end{columns}\n%}\n%\\makeatletter\n%\\setbeamertemplate{title page}{\n%\t\\begin{minipage}[b][\\paperheight]{\\textwidth}\n%\t\t\\centering  % <-- Center here\n%\t\t\\ifx\\inserttitlegraphic\\@empty\\else\\usebeamertemplate*{title graphic}\\fi\n%\t\t\\vfill%\n%\t\t\\ifx\\inserttitle\\@empty\\else\\usebeamertemplate*{title}\\fi\n%\t\t\\ifx\\insertsubtitle\\@empty\\else\\usebeamertemplate*{subtitle}\\fi\n%\t\t\\usebeamertemplate*{title separator}\n%\t\t\\ifx\\beamer@shortauthor\\@empty\\else\\usebeamertemplate*{author}\\fi\n%\t\t\\ifx\\insertdate\\@empty\\else\\usebeamertemplate*{date}\\fi\n%\t\t\\ifx\\insertinstitute\\@empty\\else\\usebeamertemplate*{institute}\\fi\n%\t\t\\vfill\n%\t\t\\vspace*{1mm}\n%\t\\end{minipage}\n%}\n%\n%\\setbeamertemplate{title}{\n%\t%  \\raggedright%  % <-- Comment here\n%\t\\linespread{1.0}%\n%\t\\inserttitle%\n%\t\\par%\n%\t\\vspace*{0.5em}\n%}\n%\\setbeamertemplate{subtitle}{\n%\t%  \\raggedright%  % <-- Comment here\n%\t\\insertsubtitle%\n%\t\\par%\n%\t\\vspace*{0.5em}\n%}\n%\\makeatother\n% end of option 4\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% option 5 - 2 Institutes and logos horizontal centered\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\\title{Elastic constants identification of composite laminates by using Lamb wave dispersion curves and optimization methods}\n%\\subtitle{Lamb-opt }\n%\\author{\\textbf{Paweł Kudela}\\textsuperscript{1}, Maciej Radzieński\\textsuperscript{1}, Marco Miniaci\\textsuperscript{2}}\n%\n%\\institute{ \n%\t\\begin{columns}[T,onlytextwidth]\n%\t\t\\column{0.5\\textwidth}\n%\t\t\t\\centering\n%\t\t\t\\textsuperscript{1}Institute of Fluid Flow Machinery\\\\ \\hspace*{3pt}Polish Academy of Sciences\n%\t\t\\column{0.5\\textwidth}\n%\t\t\t\\centering\n%\t\t\t\\textsuperscript{2}Zurich University\n%\t\\end{columns}\n%\t\\vspace{6pt}\n%\t% logos \n%\t\\begin{columns}[b,onlytextwidth]\n%\t\t\\column{0.5\\textwidth}\n%\t\t\\centering \n%\t\t\\includegraphics[width=\\textwidth,height=0.85cm,keepaspectratio]{../images/logo/logo_eng_40mm.eps}\n%\t\t\\column{0.5\\textwidth}\n%\t\t\\centering \n%\t\t\\includegraphics[width=\\textwidth,height=0.85cm,keepaspectratio]{../images/logo/logo_box.eps}\n%\t\\end{columns}\n%}\n%\\makeatletter\n%\\setbeamertemplate{title page}{\n%\t\\begin{minipage}[b][\\paperheight]{\\textwidth}\n%\t\t\\centering  % <-- Center here\n%\t\t\\ifx\\inserttitlegraphic\\@empty\\else\\usebeamertemplate*{title graphic}\\fi\n%\t\t\\vfill%\n%\t\t\\ifx\\inserttitle\\@empty\\else\\usebeamertemplate*{title}\\fi\n%\t\t\\ifx\\insertsubtitle\\@empty\\else\\usebeamertemplate*{subtitle}\\fi\n%\t\t\\usebeamertemplate*{title separator}\n%\t\t\\ifx\\beamer@shortauthor\\@empty\\else\\usebeamertemplate*{author}\\fi\n%\t\t\\ifx\\insertdate\\@empty\\else\\usebeamertemplate*{date}\\fi\n%\t\t\\ifx\\insertinstitute\\@empty\\else\\usebeamertemplate*{institute}\\fi\n%\t\t\\vfill\n%\t\t\\vspace*{1mm}\n%\t\\end{minipage}\n%}\n%\n%\\setbeamertemplate{title}{\n%\t%  \\raggedright%  % <-- Comment here\n%\t\\linespread{1.0}%\n%\t\\inserttitle%\n%\t\\par%\n%\t\\vspace*{0.5em}\n%}\n%\\setbeamertemplate{subtitle}{\n%\t%  \\raggedright%  % <-- Comment here\n%\t\\insertsubtitle%\n%\t\\par%\n%\t\\vspace*{0.5em}\n%}\n%\\makeatother\n% end of option 5\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%  End of title page options\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% logo option - alternative manual insertion by modification of coordinates in \\put()\n%\\titlegraphic{%\n%\t%\\vspace{\\logoadheight}\n%\t\\begin{picture}(0,0)\n%\t\\put(305,-185){\\makebox(0,0)[rb]{\\includegraphics[width=4cm]{../images/logo/logo_eng_40mm.eps}}}\n%\t\\end{picture}}\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\\tikzexternalize % activate!\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{document}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\maketitle\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SLIDES\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}{Table of contents}\n  \\setbeamertemplate{section in toc}[sections numbered]\n  \\tableofcontents[hideallsubsections]\n\\end{frame}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Introduction}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}[fragile,label=frame1]{Funding}\n\t\n\tNAWA – Polish National Agency for Academic Exchange\n\t\n\tMobility project to carry out research at Johann Wolfgang Goethe University, Frankfurt am Main, Germany, 2019 (3 months)\n\t\n\t\\emph{Towards model assisted structural health monitoring}\n\t\n\\end{frame}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}[fragile,label=frame2]{Context}\n\t\n\tNational Science Centre, Poland\n\t\n\t2019--2021 (3 years)\n\t\n  \t\\emph{Feasibility studies of artificial intelligence-driven diagnostics}\n  \n\\end{frame}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}[label=frame3]{Small project within big project}\n\t\\begin{figure}\n\t\t\\centering\n\t\t\\only<1>{\n\t\t\\includegraphics[width=\\textwidth]{beamer_figs/Plan-scheme-nn-small-eng.png}\t\n\t\t\\label{fig:plan_scheme}\n\t\t}\n\t\t\\only<2>{\n\t\t\\includegraphics[width=\\textwidth]{beamer_figs/Plan-scheme-nn-small-eng2.png}\t\n\t\t\\label{fig:plan_scheme2}\n\t\t}\n\t\\end{figure}\t\n\\end{frame}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}[t]{Motivation}\n\t\\biblioref{C.A.C Leckey, K.R. Wheeler,V.N. Hafiychuk, H. Hafiychuk, D.A. Timucin}{2018}{Simulation of guided-wave ultrasound propagation in composite laminates: Benchmark comparisons of numerical codes and experiment}{Ultrasonics}\n\t\\begin{figure}\n\t\t\\includegraphics[width=\\textwidth]{beamer_figs/Leckey-2018-table.png}\n\t\t\\caption{Performance metrics of commercial software for wave propagation modelling}\n\t\\label{fig:Leckey_table}\n\t\\end{figure}\n\t\\begin{alertblock}{Potential Problems}\n\t\tShortest run time \\textbf{19.5 h} is for COMSOL but requires huge amount of~memory space\\\\\n\t\t19.5 h $\\times$ 1000 simulations $\\approx$ \\textbf{812 days}\n\t\\end{alertblock}\n\\end{frame}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Numerical modelling}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}[t]{Flat shell spectral element (theoretical background)}\n\t\\def\\myindenta{0.0\\textwidth} % define myindenta variable  for correcting caption placement\n\t\\only<1->{\n\t\\begin{columns}[T]\t\n\t\t\\column{0.5\\textwidth}\n\t\t\\begin{figure}\n\t\t\t\\includegraphics[width=\\textwidth]{shell.png}\n\t\t\t\\caption{\\hspace{\\myindenta}36--node spectral shell element.}\n\t\t\t\\label{fig:spectral_shell_element}\n\t\t\\end{figure}\n\t\t\\column{0.5\\textwidth}\n\t\tThe displacement field is based on Mindlin--Reissner theory:\n\t\t\\begin{equation*}\n\t\t\\begin{split}\n\t\t& u(x,y,z)=u_0(x,y) - \\varphi_x(x,y) \\cdot z\\\\\n\t\t& v(x,y,z)=v_0(x,y) - \\varphi_y(x,y) \\cdot z\\\\\n\t\t& w(x,y,z)=w_0(x,y) \\label{eq:delam_platedispl}\n\t\t\\end{split}\n\t\t\\end{equation*}\n\t\\end{columns}\n\t}\n\t\\only<2>{\n\t\t\\begin{alertblock}{Important properties}\n\t\t\t\\begin{itemize}\n\t\t\t\t\\item Non--uniform distribution of nodes which coincide with Gauss--Lobatto--Legendre integration points\n\t\t\t\t\\item Diagonality of mass matrix\n\t\t\t\t\\item Fast convergence (spectral, exponential)\n\t\t\t\\end{itemize}\n\t\t\\end{alertblock}\n\t}\n\\end{frame}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}[t]{Approximation}\n\t\\begin{equation*}\n\t\\left[\\begin{array}{l} u_0^e(\\xi, \\eta) \\\\ \\varphi_x^e(\\xi, \\eta)\\\\ v_0^e(\\xi, \\eta) \\\\ \\varphi_y^e(\\xi, \\eta)\\\\ w_0^e(\\xi, \\eta)\\\\ \\end{array}\\right] = \\bm{N}^e \\vec{\\hat{u}}^e = \\sum \\limits_{j=1}^{6} \\sum \\limits_{i=1}^{6} N^e_i(\\xi) N^e_i(\\eta)\\, \\bm{I} \\left[ \\begin{array}{l} {\\hat{u}_0}^e(\\xi_i,\\eta_j)\\\\\\hat{\\varphi}_x^e(\\xi_i,\\eta_j)\\\\{\\hat{v}_0}^e(\\xi_i,\\eta_j) \\\\\\hat{\\varphi}_y^e(\\xi_i,\\eta_j) \\\\ \\hat{w}_0^e(\\xi_i,\\eta_j)\\end{array} \\right]\\label{eq:delam_plateaproxim}\n\t\\end{equation*}  \n\twhere $\\bm{N}^e$ are shape functions, $\\vec{\\hat{u}}^e$ are nodal degrees of freedom in the element, $\\bm{I}$ is the unit matrix of the size 5x5.\t\n\t\\begin{equation*}\n\t\\left[\\begin{array}{l} x_0^e(\\xi, \\eta) \\\\ y_0^e(\\xi, \\eta)  \\end{array}\\right] = \\sum \\limits_{j=1}^{6} \\sum \\limits_{i=1}^{6} N^e_i(\\xi) N^e_j(\\eta)\\, \\left[ \\begin{array}{l} x^e(\\xi_i,\\eta_j)\\\\y^e(\\xi_i,\\eta_j)\\end{array} \\right]\\label{eq:delam_plategeom}\n\t\\end{equation*}  \n\t\\begin{alertblock}{Shape functions are orthogonal Lagrange polynomials}\n\t\\end{alertblock}\n\\end{frame}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}[t]{Equation of motion}\n\t\\only<1->{\n\t\\begin{equation*}\n\t\\bm{M} \\vec{\\ddot{U}} + \\bm{C} \\vec{\\dot{U}} + \\bm{K} \\vec{U} = \\vec{F} \\label{eq:motion}\n\t\\end{equation*} \n\t}\n\t\\vspace{0.4cm}\n\t\\only<2->{\n\t\\begin{equation*}\n\t\\ddot{\\vec{U}}\\simeq \\frac{1}{\\Delta t^2} \\left(\\vec{u}_{t+\\Delta t} - 2\\,\\vec{u}_t + \\vec{u}_{t-\\Delta t}\\right) \\label{eq:central_scheme}\n\t\\end{equation*}\n\t\\begin{equation*}\n\t\\dot{\\vec{U}}\\simeq \\frac{\\vec{u}_{t+\\Delta t} -\\vec{u}_{t-\\Delta t}}{2 \\Delta t}\n\t\\label{eq:first_derivative_scheme}\n\t\\end{equation*}\n\t}\n\t\\vspace{0.4cm}\n\t\\only<3>{\n\t\\begin{equation*}\n\t\\begin{split}\n\t\\underbrace{\\left(\\frac{1}{\\Delta t^2} \\,\\bm{M} + \\frac{1}{2 \\Delta t} \\bm{C}\\right)}_{\\vec{M}_0} \\vec{u}_{t+\\Delta t} &= \\vec{F}_t - \\underbrace{\\left(\\bm{K} \\vec{u}_t\\right)}_{\\vec{F}^i} + \\underbrace{\\left(\\frac{2}{\\Delta t^2} \\,\\bm{M} \\right)}_{\\vec{M}_1}\\vec{u}_t \\\\\n\t&+ \\underbrace{\\left(- \\frac{1}{\\Delta t^2} \\,\\bm{M} + \\frac{1}{2 \\Delta t} \\bm{C}\\right)}_{\\vec{M}_2} \\vec{u}_{t-\\Delta t}.\n\t\\label{eq:explicit_integration}\n\t\\end{split}\n\t\\end{equation*}\n}\n\\end{frame}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}[t]{Vectorization of the code}\n\t\\vspace{-0.4cm}\n\t\\begin{equation*}\n\t\t\\underbrace{\\left(\\bm{K} \\vec{u}_t\\right)}_{\\vec{F}^i} \n\t\\end{equation*}\n\t\\vspace{0.4cm}\n\t\\begin{equation*}\n\t\\begin{split}\n\t\\vec{F}_u^i&=\\bm{N},_{\\xi}^T \\left(\\bs{\\sigma}_{xx}\\,.*(\\vec{J}^{-1})_{11}\\,.*\\vec{W}\\right)+\\bm{N},_{\\eta}^T \\left(\\bs{\\sigma}_{xx}\\,.*(\\vec{J}^{-1})_{21}\\,.*\\vec{W}\\right)\\\\\n\t&+\\bm{N},_{\\xi}^T \\left(\\bs{\\sigma}_{xy}\\,.*(\\vec{J}^{-1})_{12}\\,.*\\vec{W}\\right)+\\bm{N},_{\\eta}^T \\left(\\bs{\\sigma}_{xy}\\,.*(\\vec{J}^{-1})_{22}\\,.*\\vec{W}\\right), \n\t\\label{eq:internal_forces_u}\n\t\\end{split}\n\t\\end{equation*}\n\t\\vspace{0.4cm}\n\t\\begin{equation*}\n\t\\begin{split}\n\t\\bs{\\sigma}_{xx}&=\\left((\\bm{N},_{\\xi}\\vec{U}_x).*(\\vec{J}^{-1})_{11}+(\\bm{N},_{\\eta}\\vec{U}_x).*(\\vec{J}^{-1})_{21}\\right).*\\vec{A}_{11}\\\\\n\t&+\\left((\\bm{N},_{\\xi}\\bs{\\Phi}_x).*(\\vec{J}^{-1})_{11}+(\\bm{N},_{\\eta}\\bs{\\Phi}_x).*(\\vec{J}^{-1})_{21}\\right).*\\vec{B}_{11}\\\\\n\t&+\\left((\\bm{N},_{\\xi}\\vec{U}_y).*(\\vec{J}^{-1})_{12}+(\\bm{N},_{\\eta}\\vec{U}_y).*(\\vec{J}^{-1})_{22}\\right).*\\vec{A}_{12}\\\\\n\t&+\\left((\\bm{N},_{\\xi}\\bs{\\Phi}_y).*(\\vec{J}^{-1})_{12}+(\\bm{N},_{\\eta}\\bs{\\Phi}_y).*(\\vec{J}^{-1})_{22}\\right).*\\vec{B}_{12}\\\\\n\t&+\\left((\\bm{N},_{\\xi}\\vec{U}_x).*(\\vec{J}^{-1})_{12}+(\\bm{N},_{\\eta}\\vec{U}_x).*(\\vec{J}^{-1})_{22}\\right).*\\vec{A}_{16}\\ldots,\n\t\\end{split}\n\t\\end{equation*}\n\t\n\twhere $.*$ denotes element-wise operation known as Hadamarad product (the same symbol for element-wise operation is used in Matlab).\n\\end{frame}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}{Mesh colouring}\n\t\\begin{figure}\n\t\t\\centering\n\t\t\t\\includegraphics[width=0.8\\textwidth]{beamer_figs/mesh_colouring_scheme4.jpg}\t\n\t\t\t\\label{fig:mesh_colouring}\n\t\\end{figure}\n\\end{frame}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}[t]{Delamination modelling}\n\t\\begin{figure} [h!]\n\t\t\\centering\n\t\t\\includegraphics[width=0.9\\textwidth]{delam_modelling_shell.png}\t\n\t\t\\caption{The concept of delamination modelling: cross-section through the composite laminate and delamination showing three regions: (I) undelaminated, (II) above delamination interface, and (III) below delamination interface and corresponding elements.}\n\t\t\\label{fig:delam_modelling_shell}\n\t\\end{figure}\n\\end{frame}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}{Computation speedup analysis}\n\t\\begin{table}\n\t\t\\renewcommand{\\arraystretch}{1.3}\n\t\t\\centering \\small\n\t\tComputation run times depending on the number of degrees of freedom (NDOF) for the wave propagation duration 400~$\\mu$s; GPU: Nvidia Tesla K20X; CPU: Intel Xeon X5660 2.8~GHz.\n\t\t\n\t\t\\begin{tabular}{ccccccc} \n\t\t\t%\\hline\n\t\t\t\\toprule\t\n\t\t\tplate size [cm] & 30$\\times$30  & 40$\\times$40 & 50$\\times$50 & 70$\\times$70 & 90$\\times$90 & 100$\\times$100 \\\\\n\t\t\tNDOF $\\cdot 10^6$ & 1.02  & 1.46 & 1.98 & 3.09 & 5.23 & 6.36 \\\\\n\t\t\t\\midrule\n\t\t\tCPU time [h]& 4.03& 5.71 & 8.42 & 13.13 & 22.37 & 27.33\\\\\n\t\t\t\\midrule\n\t\t\tGPU time [h]& 1.00& 1.19 & 1.26 & 1.50 & 2.00 & 2.28\\\\\n\t\t\t%\\hline \n\t\t\t\\bottomrule \n\t\t\\end{tabular} \n\t\t\\label{tab:run_time}\n\t\\end{table}\n\t\\begin{alertblock}{Run time}\n\t\tThe longest run time on GPU was \\textbf{2.28 h}\\\\\n\t\tThe typical run time for simulations performed next was about 3 hours ($t = 1300\\, \\mu$s, NDOF $= 2.23\\cdot 10^6$) \\\\\n\t\tThe GPU memory usage was about 925 MB\\\\\n\t\t3 h $\\times$ 1000 simulations $\\approx$ \\textbf{125 days}\n\t\\end{alertblock}\n\\end{frame}\n\\begin{frame}{Computation speedup analysis}\n\t\\begin{figure} [h!]\n\t\t\\centering\n\t\t\\includegraphics{speedup.png}\t\n\t\t\\caption{Computation speedup; NDOF - number of degrees of freedom.}\n\t\t\\label{fig:speedup}\n\t\\end{figure}\n\t\\begin{equation*}\n\tspeedup = \\frac{CPU_{time}}{GPU_{time}}\n\t\\label{eq:speedup}\n\t\\end{equation*}\n\\end{frame}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Experimental validation}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}{Open Guided Waves}\n\t\\begin{block}{\\url{http://www.open-guided-waves.de}}\n\t\tOpen Guided Waves is an extendable online platform where high--quality and well documented datasets for guided wave--based inspections are provided.\n\t\\end{block}\n\n\tCFRP plates [45/0/-45/90/-45/0/45/90]\\textsubscript{S}\n\t\n\t500 mm $\\times$ 500 mm, thickness of 2 mm. \n\t\n\tPiezoelectric transducers diameter 10 mm, thickness 0.2 mm.\n\t\n\t\\begin{table}\n\t\t\\renewcommand{\\arraystretch}{1.3}\n\t\t\\centering \\small\n\t\tMaterial properties of unidirectional Hexply M21/34\\%/UD134/T700/300; Units: GPa.\n\t\t\n\t\t\\begin{tabular}{cccccc} \n\t\t\t%\\hline\n\t\t\t\\toprule\n\t\t\t$Q_{11}$ & $Q_{12}$  & $Q_{22}$ & $Q_{44}$ & $Q_{55}$ & $Q_{66}$\\\\\n\t\t\t% \\cmidrule(lr){1-3} \\cmidrule(lr){4-6} \\cmidrule(lr){7-7}\n\t\t\t%\\hline\n\t\t\t\\midrule\n\t\t\t130& 6.1& 11.2 & 3.0 & 4.2 & 4.2\\\\\n\t\t\t%\\hline \n\t\t\t\\bottomrule \n\t\t\\end{tabular} \n\t\t\\label{tab:mat_prop}\n\t\\end{table}\n\\end{frame}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}{Open Guided Waves}\n\n\t\\begin{table}\n\t\t\\renewcommand{\\arraystretch}{1.3}\n\t\t\\centering \\small\n\t\tCoordinates of analysed defects; Units: [m].\n\t\t\n\t\t\\begin{tabular}{cccc} \n\t\t\t%\\hline\n\t\t\t\\toprule\n\t\t\t\\multicolumn{2}{c}{\\textbf{Data set I} }\t& \\multicolumn{2}{c}{\\textbf{Data set II} } \\\\\n\t\t\t\\multicolumn{2}{c}{\\textbf{(wavefield plate)} }\t& \\multicolumn{2}{c}{\\textbf{(SHM plate)} } \\\\\n\t\t\t%\\midrule\n\t\t\t\\cmidrule(lr){1-2} \\cmidrule(lr){3-4}\n\t\t\tx & y &  x &  y  \\\\\n\t\t\t% \\cmidrule(lr){1-3} \\cmidrule(lr){4-6} \\cmidrule(lr){7-7}\n\t\t\t%\\hline\n\t\t\t0.191 & 0.145 & 0.250  & 0.427 \\\\ \n\t\t\t%\\hline \n\t\t\t\\bottomrule \n\t\t\\end{tabular} \n\t\t\\label{tab:defect_coordinates}\n\t\\end{table}\t\t\n\t\\begin{block}{Wavefield plate}\n\t\tWavefield measured by scanning laser Doppler vibrometer\n\t\\end{block}\n\t\\begin{block}{SHM plate}\n\t\tSignals excited and registered by an array of piezoelectric transducers\n\t\\end{block}\n\\end{frame}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}[b]{Meshing - GMSH quadrilateral elements}\n\t\\begin{figure}\n\t\t\\centering\n\t\t\\includegraphics[width=0.7\\textwidth]{delam_Jochen_signals_D5_a_5mm_b_5mm_angle_0added_mass.png}\t\t\n\t\t\\caption{red -- piezoelectric transducers; green -- defect location}\n\t\t\\label{fig:quad_mesh}\n\t\\end{figure}\t\n\\end{frame}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}[t]{Meshing - spectral element mesh close up}\n\t\\begin{figure}\n\t\t\\centering\n\t\t\\includegraphics[width=0.7\\textwidth]{delam_Jochen_signals_D5_a_5mm_b_5mm_angle_0added_mass_spec_zoom.png}\t\n\t\t\\label{fig:spec_mesh_zoom}\n\t\\end{figure}\t\n\\end{frame}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}[t]{Wavefield plate: comparison of wavefields}\n%\\vspace{6pt}\n\\def\\myindenta{0.001\\textwidth} % define myindenta variable  for correcting caption placement\n\\begin{columns}[T]\n\t\\column{0.5\\textwidth}\n\t\t\\begin{figure}\n\t\t\t\\only<1>{\n\t\t\t\\includegraphics[width=\\textwidth]{exp_frame64.png}\n\t\t\t\\caption{\\hspace{\\myindenta}Experimental wavefield: $t=112.5\\, \\mu$s}\n\t\t\t}\n\t\t\t\\only<2>{\n\t\t\t\\includegraphics[width=\\textwidth]{exp_frame100.png}\n\t\t\t\\caption{\\hspace{\\myindenta}Experimental wavefield: $t=169\\, \\mu$s}\n\t\t\t}\n\t\t\t\\only<3>{\n\t\t\t\t\\includegraphics[width=\\textwidth]{exp_frame64.png}\n\t\t\t\t\\caption{\\hspace{\\myindenta}Experimental wavefield: $t=112.5\\, \\mu$s}\n\t\t\t}\n\t\t\t\\only<4>{\n\t\t\t\t\\includegraphics[width=\\textwidth]{exp_frame100.png}\n\t\t\t\t\\caption{\\hspace{\\myindenta}Experimental wavefield: $t=169\\, \\mu$s}\n\t\t\t}\n\t\t\t\\only<5>{\n\t\t\t\t\\includegraphics[width=\\textwidth]{cut_Vz_1_frame128_top.png}\n\t\t\t\t\\caption{\\hspace{\\myindenta}Simulation (delamination): $t=200\\, \\mu$s}\n\t\t\t}\n\t\t\\end{figure}\n\t\\column{0.5\\textwidth}\n\t\t\\begin{figure}\n\t\t\t\\only<1>{\n\t\t\t\\includegraphics[width=\\textwidth]{Vz_1_frame72_bottom.png}\n\t\t\t\\caption{\\hspace{\\myindenta}Simulation (\\textbf{delamination}): $t=112.5\\, \\mu$s}\n\t\t\t}\n\t\t\t\\only<2>{\n\t\t\t\\includegraphics[width=\\textwidth]{Vz_1_frame108_bottom.png}\n\t\t\t\\caption{\\hspace{\\myindenta}Simulation (\\textbf{delamination}): $t=169\\, \\mu$s}\n\t\t\t}\n\t\t\t\\only<3>{\n\t\t\t\t\\includegraphics[width=\\textwidth]{added_mass_Vz_1_frame72_bottom.png}\n\t\t\t\t\\caption{\\hspace{\\myindenta}Simulation (\\textbf{added mass}): $t=112.5\\, \\mu$s}\n\t\t\t}\n\t\t\t\\only<4>{\n\t\t\t\t\\includegraphics[width=\\textwidth]{added_mass_Vz_1_frame108_bottom.png}\n\t\t\t\t\\caption{\\hspace{\\myindenta}Simulation (\\textbf{added mass}): $t=169\\, \\mu$s}\n\t\t\t}\n\t\t\t\\only<5>{\n\t\t\t\t\\includegraphics[width=\\textwidth]{added_mass_cut_Vz_1_frame128_top.png}\n\t\t\t\t\\caption{\\hspace{\\myindenta}Simulation (added mass): $t=200\\, \\mu$s}\n\t\t\t}\n\t\t\t\\label{fig:wavefield}\n\t\t\\end{figure}\n\\end{columns}\n\t\\only<6>{\n\t\\begin{alertblock}{Remarks}\n\t\t\\begin{itemize}\n\t\t\t\\item Simulated wavefield patterns matches the experimental data very well.\n\t\t\t\\item The interaction of wave front with added mass is slightly different than with delamination.\n\t\t\t\\item The phenomenon of wave entrapment is visible for the case of delamination whereas it is not present in case of added mass.\n\t\t\t\\item A reversible damage in the form of added mass coupled to the structure by tacky tape is a good way for collecting benchmark data set. Such benchmark data set is a good starting point for development of algorithms based on full wavefield data for visualization of defect location even in the form of delamination.\n\t\t\\end{itemize}\n\t\\end{alertblock}\n\t}\n\\end{frame}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}[t]{SHM plate: comparison of signals}\n\t\\begin{figure}\n\t\t\\centering\n\t\t\\only<1>{\n\t\t\\includegraphics[width=0.9\\textwidth]{path_1_7.png}\t\n\t\t\\label{fig:path1_7}\n\t\t}\n\t\t\\only<2>{\n\t\t\t\\includegraphics[width=0.9\\textwidth]{path_2_4.png}\t\n\t\t\t\\label{fig:path2_4}\n\t\t}\n\t\t\\only<3>{\n\t\t\t\\includegraphics[width=0.9\\textwidth]{path_4_8.png}\t\n\t\t\t\\label{fig:path4_8}\n\t\t}\n\t\t\\only<4>{\n\t\t\t\\includegraphics[width=0.9\\textwidth]{path_2_4_diff.png}\t\n\t\t\t\\label{fig:path2_4_diff}\n\t\t}\n\t\\end{figure}\n\t\\only<5>{\n\t\t\\begin{alertblock}{Remarks}\n\t\t\t\\begin{itemize}\n\t\t\t\t\\item Differences between experimental and numerical signals are evident and are related to amplitude rather than wave velocity.\n\t\t\t\t\\item The amplitude difference can be attributed to the damping coefficient selected in numerical simulation.\n\t\t\t\t\\item The delamination affect signals more than added mass.\n\t\t\t\\end{itemize}\n\t\t\\end{alertblock}\n\t}\t\n\\end{frame}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Conclusions}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}{Summary}\n\t\\begin{itemize}\n\t\t\\item The developed code is highly parallel and enables GPU computation. It allows up to \\textbf{12$\\times$} computation speedup in comparison to CPU. It also \\textbf{does not require assembly of stiffness matrix}. Therefore, larger guided wave propagation problems can be solved than in case of conventional finite element approach.\n\t\t\\item The simulated wave propagation in composite laminates \\textbf{matches well the experimental data} from Open Guided Waves platform in terms of full wavefield patterns.\n\t\t\\item There are differences in wave packets' amplitudes -- proper \\textbf{wave attenuation modelling is still a challenge}.\n\t\t\\item The current implementation is very well suited for any parametric studies or \\textbf{model--assisted} approaches for structural health monitoring but is not feasible for \\textbf{model--based} approach in which numerical signals are directly compared to experimental one.\n\t\t\n\t\\end{itemize}\t\n\\end{frame}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Future works}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}{Random excitation}\n\t\\begin{figure}\n\t\t\\centering\t\n\t\t\\includegraphics[width=0.9\\textwidth]{beamer_figs/random_exc_sig.png}\t\n\t\t\\label{fig:random_exc_sig}  \n\t\\end{figure}\n      \\begin{alertblock}{Advantage}\n        Wide frequency range increases probability that the guided wave will interact with damage.\n      \\end{alertblock}\n\\end{frame}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}{Random excitation: full wavefield}\n\t\\begin{figure}\n\t\t\\centering\n\t\t\\only<1>{\n\t\t\t\\includegraphics[width=0.75\\textwidth]{beamer_figs/Vz_5_frame16_top.png}\t\n\t\t\t\\label{fig:random_exc_wavefield_16}\n\t\t}\n\t\t\\only<2>{\n\t\t\t\\includegraphics[width=0.75\\textwidth]{beamer_figs/Vz_5_frame32_top.png}\t\n\t\t\t\\label{fig:random_exc_wavefield_32}\n\t\t}\n\t\t\\only<3>{\n\t\t\t\\includegraphics[width=0.75\\textwidth]{beamer_figs/Vz_5_frame48_top.png}\t\n\t\t\t\\label{fig:random_exc_wavefield_48}\n\t\t}\n\t\t\\only<4>{\n\t\t\t\\includegraphics[width=0.75\\textwidth]{beamer_figs/Vz_5_frame64_top.png}\t\n\t\t\t\\label{fig:random_exc_wavefield_64}\n\t\t}\n\t\t\\only<5>{\n\t\t\t\\includegraphics[width=0.75\\textwidth]{beamer_figs/Vz_5_frame80_top.png}\t\n\t\t\t\\label{fig:random_exc_wavefield_80}\n\t\t}\n\t\\end{figure}\t\n\\end{frame}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}{Random excitation: RMS}\n\t\\begin{figure}\n\t\t\\centering\n\t\t\\only<1>{\n\t\t\t\\includegraphics[width=0.75\\textwidth]{beamer_figs/RMS5.png}\t\n\t\t\t\\label{fig:random_exc_wavefield_RMS5}\n\t\t}\n\t\t\\only<2>{\n\t\t\t\\includegraphics[width=0.75\\textwidth]{beamer_figs/RMS14.png}\t\n\t\t\t\\label{fig:random_exc_wavefield_RMS14}\n\t\t}\n\t\t\\only<3>{\n\t\t\t\\includegraphics[width=0.75\\textwidth]{beamer_figs/RMS22.png}\t\n\t\t\t\\label{fig:random_exc_wavefield_RMS22}\n\t\t}\n\t\\end{figure}\t\n\\end{frame}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n{\\setbeamercolor{palette primary}{fg=black, bg=white}\n\\begin{frame}[standout]\n  Thank you for your attention!\\\\ \\vspace{12pt}\n  Questions?\\\\ \\vspace{12pt}\n  \\url{pk@imp.gda.pl}\n\\end{frame}\n}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% END OF SLIDES\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\appendix\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}{Model--based vs model--assisted SHM}\n\t In the \\textbf{model--based} approach, numerical signals must match very well experimental signals. It is because numerical signals are used in an inverse method in which certain objective function include terms such as:\n\t\\begin{equation*}\n\tg(t) = \\sum_{i=1}^{N} \\left(s(t)_i^{exp} - s(t)_i^{num}\\right)^2,\n\t\\label{eq:obj_fun}\n\t\\end{equation*}\n\twhere $s(t)^{exp}$ and $s(t)^{num}$ are experimental and numerical signals (or damage indexes), respectively.\n\t\n\tIn the \\textbf{model--assisted} approach, on the other hand, the modelled phenomenon must reflect the real behaviour, e.g. the amplitude of transmitted wave packet decreases when the size of the damage increases. But in this case, the perfect match between numerical and experimental signals is not necessary. The aim of the presented method is model--assisted structural health monitoring.\n\\end{frame}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}{Backup slides}\n  \\begin{equation*}\n  \\begin{split}\n  \\bs{\\sigma}_{xx}&=\\left((\\bm{N},_{\\xi}\\vec{U}_x).*(\\vec{J}^{-1})_{11}+(\\bm{N},_{\\eta}\\vec{U}_x).*(\\vec{J}^{-1})_{21}\\right).*\\vec{A}_{11}\\\\\n  &+\\left((\\bm{N},_{\\xi}\\bs{\\Phi}_x).*(\\vec{J}^{-1})_{11}+(\\bm{N},_{\\eta}\\bs{\\Phi}_x).*(\\vec{J}^{-1})_{21}\\right).*\\vec{B}_{11}\\\\\n  &+\\left((\\bm{N},_{\\xi}\\vec{U}_y).*(\\vec{J}^{-1})_{12}+(\\bm{N},_{\\eta}\\vec{U}_y).*(\\vec{J}^{-1})_{22}\\right).*\\vec{A}_{12}\\\\\n  &+\\left((\\bm{N},_{\\xi}\\bs{\\Phi}_y).*(\\vec{J}^{-1})_{12}+(\\bm{N},_{\\eta}\\bs{\\Phi}_y).*(\\vec{J}^{-1})_{22}\\right).*\\vec{B}_{12}\\\\\n  &+\\left((\\bm{N},_{\\xi}\\vec{U}_x).*(\\vec{J}^{-1})_{12}+(\\bm{N},_{\\eta}\\vec{U}_x).*(\\vec{J}^{-1})_{22}\\right).*\\vec{A}_{16}\\\\\n  &+\\left((\\bm{N},_{\\xi}\\bs{\\Phi}_x).*(\\vec{J}^{-1})_{12}+(\\bm{N},_{\\eta}\\bs{\\Phi}_x).*(\\vec{J}^{-1})_{22}\\right).*\\vec{B}_{16}\\\\\n  &+\\left((\\bm{N},_{\\xi}\\vec{U}_y).*(\\vec{J}^{-1})_{11}+(\\bm{N},_{\\eta}\\vec{U}_y).*(\\vec{J}^{-1})_{21}\\right).*\\vec{A}_{16}\\\\\n  &+\\left((\\bm{N},_{\\xi}\\bs{\\Phi}_y).*(\\vec{J}^{-1})_{11}+(\\bm{N},_{\\eta}\\bs{\\Phi}_y).*(\\vec{J}^{-1})_{21}\\right).*\\vec{B}_{16},\n  \\end{split}\n  \\end{equation*}\n  where $.*$ denotes element-wise operation known as Hadamarad product (the same symbol for element-wise operation is used in Matlab). It should be noted that $\\vec{A}$, $\\vec{B}$, $\\vec{D}$ and $(\\vec{J}^{-1})$ with appropriate indexes are arranged in the form of vectors respective to GLL nodes of consecutive disjoint spectral elements.\n\\end{frame}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}{Backup slides}\n\t\\begin{equation*}\n\t\\vec{U}_x = \\left[\n\t\\begin{array}{c}  \n\t\\hat{\\vec{u}}_0^{e=1}  \\\\[2pt]\n\t\\hat{\\vec{u}}_0^{e=2} \\\\[2pt]\n\t\\vdots\\\\[2pt]\n\t\\hat{\\vec{u}}_0^{e=n}\\\\[2pt]\n\t\\end{array}\\right],\n\t\\quad\n\t\\vec{U}_y = \\left[\n\t\\begin{array}{c}  \n\t\\hat{\\vec{v}}_0^{e=1}  \\\\[2pt]\n\t\\hat{\\vec{v}}_0^{e=2} \\\\[2pt]\n\t\\vdots\\\\[2pt]\n\t\\hat{\\vec{v}}_0^{e=n}\\\\[2pt]\n\t\\end{array}\\right],\n\t\\quad\n\t\\vec{U}_z = \\left[\n\t\\begin{array}{c}  \n\t\\hat{\\vec{w}}_0^{e=1}  \\\\[2pt]\n\t\\hat{\\vec{w}}_0^{e=2} \\\\[2pt]\n\t\\vdots\\\\[2pt]\n\t\\hat{\\vec{w}}_0^{e=n}\\\\[2pt]\n\t\\end{array}\\right],\n\t\\end{equation*}\n\t\\begin{equation*}\n\t\\bs{\\Phi}_x = \\left[\n\t\\begin{array}{c}  \n\t\\hat{\\bs{\\varphi}}_x^{e=1}  \\\\[2pt]\n\t\\hat{\\bs{\\varphi}}_x^{e=2} \\\\[2pt]\n\t\\vdots\\\\[2pt]\n\t\\hat{\\bs{\\varphi}}_x^{e=n}\\\\[2pt]\n\t\\end{array}\\right],\n\t\\quad\n\t\\bs{\\Phi}_y = \\left[\n\t\\begin{array}{c}  \n\t\\hat{\\bs{\\varphi}}_y^{e=1}  \\\\[2pt]\n\t\\hat{\\bs{\\varphi}}_y^{e=2} \\\\[2pt]\n\t\\vdots\\\\[2pt]\n\t\\hat{\\bs{\\varphi}}_y^{e=n}\\\\[2pt]\n\t\\end{array}\\right],\n\t\\end{equation*}\n\t$n$ is the total number of elements.\\\\\t\n\\end{frame}\t\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}{Backup slides}\n\tSparse matrices of shape function derivatives:\n\t\\begin{equation*}\n\t\\bm{N},_{\\xi} = \\left[\n\t\\begin{array}{cccc}  \n\t\\bm{N},_{\\xi}^{e=1} & 0 & \\ldots & 0\\\\[2pt]\n\t0& \\bm{N},_{\\xi}^{e=2}  & \\ldots& 0\\\\[2pt]\n\t\\vdots&\\vdots&\\ddots&0\\\\[2pt]\n\t0& 0 &0&\\bm{N},_{\\xi}^{e=n}\\\\[2pt]\n\t\\end{array}\\right].\n\t\\end{equation*}\n\\end{frame}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}{Backup slides}\n\\begin{equation*}\n\\begin{split}\n\\vec{F}_u^i&=\\bm{N},_{\\xi}^T \\left(\\bs{\\sigma}_{xx}\\,.*(\\vec{J}^{-1})_{11}\\,.*\\vec{W}\\right)+\\bm{N},_{\\eta}^T \\left(\\bs{\\sigma}_{xx}\\,.*(\\vec{J}^{-1})_{21}\\,.*\\vec{W}\\right)\\\\\n&+\\bm{N},_{\\xi}^T \\left(\\bs{\\sigma}_{xy}\\,.*(\\vec{J}^{-1})_{12}\\,.*\\vec{W}\\right)+\\bm{N},_{\\eta}^T \\left(\\bs{\\sigma}_{xy}\\,.*(\\vec{J}^{-1})_{22}\\,.*\\vec{W}\\right), \\\\ \n\\vec{F}_v^i&=\\ldots ,\\\\\n\\vec{F}_w^i&=\\ldots ,\\\\\n\\vec{M}_x^i&=\\bm{N},_{\\xi}^T \\left(\\bs{\\sigma}_{xxz}\\,.*(\\vec{J}^{-1})_{11}\\,.*\\vec{W}\\right)+\\bm{N},_{\\eta}^T \\left(\\bs{\\sigma}_{xxz}\\,.*(\\vec{J}^{-1})_{21}\\,.*\\vec{W}\\right)\\\\\n&+\\bm{N},_{\\xi}^T \\left(\\bs{\\sigma}_{xyz}\\,.*(\\vec{J}^{-1})_{12}\\,.*\\vec{W}\\right)+\\bm{N},_{\\eta}^T \\left(\\bs{\\sigma}_{xyz}\\,.*(\\vec{J}^{-1})_{22}\\,.*\\vec{W}\\right)\\\\\n&+\\bs{\\sigma}_{xz}\\,.*\\vec{W},\\\\\n\\vec{M}_y^i&=\\ldots ,\n\\label{eq:internal_forces}\n\\end{split}\n\\end{equation*}\nwhere $^T$ is the matrix transpose and $\\vec{W}$ is the vector resulting from multiplication of integration weights and Jacobian determinant at appropriate GLL points:\n\\begin{equation*}\n\\vec{W} = \\vec{w}_{\\xi}\\,.*\\vec{w}_{\\eta}\\,.*\\left(\\det\\vec{J}\\right).\n\\end{equation*}\n\\end{frame}\n\\end{document}", "meta": {"hexsha": "74543121c1305af70fbb12404d68d6d1ea228ad2", "size": 33120, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "reports/beamer_presentations/seminar_Goethe_University.tex", "max_stars_repo_name": "pawelkudela/ma-shm", "max_stars_repo_head_hexsha": "b0403ba4e98e7d8176cbce00a6102b7deef82629", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-03T05:39:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T05:39:06.000Z", "max_issues_repo_path": "reports/beamer_presentations/seminar_Goethe_University.tex", "max_issues_repo_name": "pawelkudela/ma-shm", "max_issues_repo_head_hexsha": "b0403ba4e98e7d8176cbce00a6102b7deef82629", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "reports/beamer_presentations/seminar_Goethe_University.tex", "max_forks_repo_name": "pawelkudela/ma-shm", "max_forks_repo_head_hexsha": "b0403ba4e98e7d8176cbce00a6102b7deef82629", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.8384710234, "max_line_length": 483, "alphanum_fraction": 0.622192029, "num_tokens": 11492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832354982647, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.3413975133148912}}
{"text": "% !TeX root = ../main.tex\n\\section{Basic Conditional Narrowing}\nFrom the same motivations as in the unconditional narrowing case we pursuit the objective of define basic conditional narrowing derivations.\n\n\\begin{definition}\n    Let $T$ be a goal clause. A \\textit{position constraint} for $T$ is a mapping $B$ that assigns to every goal $e \\in T$ a subset of $\\basicPos{e}$. The position constraint that assigns to every $e \\in T$ the set $\\basicPos{e}$ will be denoted by $\\overline{T}$.\n\\end{definition}\n\n\\begin{definition}\n    \\begin{enumerate}\n        \\item A narrowing derivation\n        $$T \\narrow_{[e_1, p_1, l_1 \\contr r_1 \\Leftarrow c_1, \\sigma_1]} \\narrow \\cdots \\narrow_{[e_{n-1}, p_{n_1}, l_{n-1} \\contr r_{n-1} \\Leftarrow c_{n-1}, \\sigma_{n-1}]} T_n$$\n        is basic if $p_i \\in B_i(e_i)$ for $1 \\leq i \\leq n - 1$ where the position constraints $B_1, \\dots, B_n$ are inductively defined by $B_1 = \\overline{T}_1$ and\n        \\begin{displaymath}\n            B_{i+1}(e) =\n            \\begin{cases}\n                B_i(e') & \\text{ if } e' \\in T_i \\setminus \\{e_i\\} \\\\\n                \\mathcal{B}(B_i(e_i), p_i, r_i) & \\text{ if } e' = e_i[r_i]_{p_i} \\\\\n                \\basicPos{e'} & \\text{ if } e' \\in \\overline{c}_i\n            \\end{cases}\n        \\end{displaymath}\n        \\item A rewrite sequence\n        $$T \\rewriteOnGoals_{[e_1, p_1, l_1 \\contr r_1 \\Leftarrow c_1, \\sigma_1]} \\rewriteOnGoals \\cdots \\rewriteOnGoals_{[e_{n-1}, p_{n_1}, l_{n-1} \\contr r_{n-1} \\Leftarrow c_{n-1}, \\sigma_{n-1}]} T_n$$\n        is \\textit{based} on a position constraint $B_1$ for $T_1$ if $p_i \\in B_i$ for $1 \\leq i \\leq n - 1$ with $B_2, \\dots, B_n$ defined by\n        \\begin{displaymath}\n            B_{i+1}(e) =\n            \\begin{cases}\n                B_i(e) & \\text{ if } e' \\in T_i \\setminus \\{e_i\\} \\\\\n                \\mathcal{B}(B_i(e_i), p_i, r_i) & \\text{ if } e = e_i[r_i\\sigma_i]_{p_i} \\\\\n                \\basicPos{e'} & \\text{ if } e=e'\\sigma \\text{ with } e' \\in \\overline{c}_i\n            \\end{cases}\n        \\end{displaymath}\n        for all $1 \\leq i < n$ and $e \\in T_{i+1}$.\n    \\end{enumerate}\n\\end{definition}\n\nHolldobler \\cite{Holldobler:1989:FEL:76924}, showed that basic conditional narrowing is complete for complete 1-CTRSs. However, the following example shows that this result is indeed not valid.\n\n\\begin{example}\n    Consider the 1-CTRS\n    \\begin{displaymath}\n        \\trs =\n        \\begin{cases}\n            f(x) & \\contr a                               \\\\\n            d & \\contr b \\\\\n            d & \\contr c\\\\\n            b & \\contr c \\Leftarrow f(d) = a\n        \\end{cases}\n    \\end{displaymath}\n\\end{example}\n\nThe authors in \\cite{Middeldorp1994} have shown that $\\trs$ is complete. Note that basic conditional narrowing is not able to solve the goal $eq(f(d),a)$ as can be seen form the figure below.\n\n\\begin{figure}[!ht]\n    \\begin{displaymath}\n        \\xymatrix{\n            & & eq(f(d),a) \\ar@{~>}[dll] \\ar@{~>}[drr] \\ar@{~>}[d] &  & \\\\\n            eq(\\underline{d},b),eq(\\underline{d},c) \\ar@{~>}[d] & & eq(f(b),a) \\ar@{~>}[dl] \\ar@{~>}[dr] & & eq(f(c),a) \\ar@{~>}[d] \\\\\n            eq(\\underline{d},c), eq(f(d),a) &  eq(\\underline{b},c) &  & eq(f(c),a), eq(f(d),a) & eq(\\underline{c},b) \\ar@{~>}[d]\\\\\n            & & & & eq(f(d),a)\n        }\n    \\end{displaymath}\n    \\caption{Derivation tree for the objective $eq(f(d),a)$}\n    \\label{figure:counterexample-basic-conditional-narrowing}\n\\end{figure}\nNote that this derivation tree is basic-normalised, i.e., we explore all basic reductions. However, the following non-basic narrowing derivation shows that the goal can be solved:\n\\begin{align*}\n    eq(f(d),a) &\\narrow eq(a,a), eq(\\underline{d},b), eq(\\underline{d},c) \\\\\n    & \\narrow eq(a,a), eq(b,b), eq(\\underline{d},c) \\\\\n    & \\narrow eq(a,a), eq(b,b), eq(c,c) \\\\\n    & \\narrow^* \\top\n\\end{align*}\nNote further that basic conditional narrowing is unable to solve the normalised goal $eq(f(x),a)$. In \\cite{Middeldorp1994}, Holldobler himself has found the problem in his previous proof. The mistake was due to the incorrect assumption that the strong normalization of $\\rewriteOnGoals_\\trs$ is implied by the strong normalization of $\\trs$. We now show, following his own steps, that completeness of basic conditional narrowing can be ensured by strengthening strong normalization. We begin with a definition.\n\n\\begin{definition}\n    A 1-CTRS $\\trs$ is decreasing if there exists a well-founded extension $>$ of the rewrite relation $\\contr_\\trs$ with the following properties:\n    \\begin{enumerate}\n        \\item $>$ has the subterm property, i.e. $t > \\restr{t}{p}$ for all positions $p \\in \\pos{t} \\setminus \\{\\Lambda\\}$\n        \\item if $l \\contr r \\Leftarrow c \\in \\trs$ and $\\sigma$ is a substitution then $l\\sigma > s \\sigma$ for all $s = t \\in c$.\n    \\end{enumerate}\n\\end{definition}\n\nEvery decreasing 1-CTRS is strongly normlizing and moreover -- when the number of rewrite rules is finite -- its rewrite relation is decidable.\n\n\\begin{example}\n    The CTRS of the above example is not decreasing: as $f(d) \\contr a \\Leftarrow d = b, d = c$ is an instance of the first rewrite rule we must have $f(d) > b$, but the rule $b \\contr c \\Leftarrow f(d) = a$ requires $b > f(d)$.\n\\end{example}\n\nWith the decreasing hypothesys one can show:\n\\begin{lemma}\n    If $\\trs$ is a decreasing 1-CTRS then $\\rewriteOnGoals_\\trs$ is strongly normalizing.\n\\end{lemma}\n\nIs now standard to give statements as in the basic non-conditional case. That is the content of the next lemma.\n\\begin{lemma}\n    Let $\\trs$ be a 1-CTRS, $T$ a goal clause, and $\\sigma$ a normalized substitution. Every innermost $\\rewriteOnGoals_\\trs$-sequence starting from $T \\sigma$ is based on $\\overline{T}$.\n\\end{lemma}\n\nFinally, we have our desired completeness result for conditional basic narrowing.\n\\begin{theorem}\n    Basic conditional narrowing is complete for decreasing and confluent 1-CTRS.\n\\end{theorem}\n", "meta": {"hexsha": "c132b716c69f64b537ba7e0bffa30b013b767956", "size": 5935, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "sections/basic_conditional_narrowing.tex", "max_stars_repo_name": "deividrvale/report-narrowing", "max_stars_repo_head_hexsha": "1e3ce34a1afb5268b4307fcc9af9374d2e121a27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sections/basic_conditional_narrowing.tex", "max_issues_repo_name": "deividrvale/report-narrowing", "max_issues_repo_head_hexsha": "1e3ce34a1afb5268b4307fcc9af9374d2e121a27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sections/basic_conditional_narrowing.tex", "max_forks_repo_name": "deividrvale/report-narrowing", "max_forks_repo_head_hexsha": "1e3ce34a1afb5268b4307fcc9af9374d2e121a27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 57.6213592233, "max_line_length": 511, "alphanum_fraction": 0.6323504634, "num_tokens": 1881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.3413510595401536}}
{"text": "\\section{Background} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\label{sec:bg}\r\n\r\nPattern matching in the context of a programming language was first introduced \r\nin a string manipulation language SNOBOL\\cite{SNOBOL64}. Its fourth \r\nreincarnation SNOBOL4 had patterns as first-class data types providing \r\noperations of concatenation and alternation on them\\cite{SNOBOL71}. The first \r\nreference to a pattern-matching construct that resembles the one found in \r\nstatically typed functional languages today is usually attributed to Burstall \r\nand his work on structural induction\\cite{Burstall69provingproperties}.\r\n\r\nIn the context of object-oriented programming, pattern matching has been first \r\nexplored in Pizza programming language\\cite{Odersky97pizzainto}. These efforts \r\nhave been continued in Scala\\cite{Scala2nd} and together with notable work of \r\nBurak Emir on \\emph{Object-Oriented Pattern Matching}\\cite{EmirThesis} have \r\nresulted in incorporation of pattern matching into the language.\r\n\r\n%The first tree based pattern matching methods were found in Fred McBride's \r\n%extension of LISP in 1970.\r\n\r\n%ML and Haskell further popularized pattern matching ...\r\n\r\nPattern matching has been closely related to \\emph{algebraic data types} and \r\n\\emph{equational reasoning} since the early days of functional programming.\r\nIn languages like ML and Haskel an \\emph{Algebraic Data Type} is a data type \r\neach of whose values is picked from a disjoint sum of (possibly recursive) data \r\ntypes, called \\emph{variants}. Each of the variants is marked with a unique \r\nsymbolic constant called \\emph{constructor}, while the set of all constructors \r\nof a given type is called \\emph{signature}. Constructors provide a convenient \r\nway of creating a value of its variant type as well as a way of discriminating \r\nits variant type from the algebraic data type through pattern matching.\r\n\r\nAlgebraic data type \\codeocaml{expr} from Section~\\ref{sec:intro} consists of 5 \r\nvariants, marked with constructors \\codeocaml{Value}, \\codeocaml{Plus}, \r\n\\codeocaml{Minus}, \\codeocaml{Times} and \\codeocaml{Divide} respectively. \r\nConstructor \\codeocaml{Value} expects a value of type \\codeocaml{int} during \r\nconstruction, as well as any pattern that admits values of type \\codeocaml{int} \r\nduring decomposition through pattern matching. Similarly, the other four \r\nconstructors expect a value of a cartesian product of two \\codeocaml{expr} \r\ntypes during construction, as well as any pattern that would admit a value of \r\nsuch type during decomposition.\r\n\r\nAlgebraic data types can be parameterized and recursive, as demonstrated by the \r\nfollowing Haskell code that defines a binary tree parameterized on type \r\n\\codehaskell{k} of keys and type \\codehaskell{d} of data stored in the nodes:\r\n\r\n\\begin{lstlisting}[language=Haskell]\r\ndata Tree k d = Node k d (Tree k d) (Tree k d) | Leaf\r\n\\end{lstlisting}\r\n\r\n\\noindent\r\nNaturally, they can be decomposed in a generic algorithm like the function \r\n\\code{find} below, defined through case analysis on the tree's structure:\r\n\r\n\\begin{lstlisting}[language=Haskell]\r\nfind :: (Ord k) => k -> Tree k d -> Maybe d\r\nfind i Leaf = Nothing\r\nfind i (Node key item left right) = \r\n    if i == key \r\n    then Just item \r\n    else \r\n        if i [<] key \r\n        then find i left \r\n        else find i right\r\n\\end{lstlisting}\r\n\r\n\\noindent\r\nThe set of values described by such an algebraic data type is defined \r\ninductively as the least set closed under constructor functions of its variants.\r\nAlgebraic data types draw their name from the practice of using case distinction \r\nin mathematical function definitions and proofs that involve \\emph{algebraic \r\nterms}.\r\n\r\nOne of the main differences of algebraic data types from classes in \r\nobject-oriented languages is that an algebraic data type definition is \r\n\\emph{closed} because it fixes the structure of its instances once and for all. \r\nOnce we have listed all the variants a given algebraic data type may have we \r\ncannot extend it with new variants without modifying its definition. This is not \r\nthe case in object-oriented languages, where classes are \\emph{open} to \r\nextension through subclassing. Notable exceptions to this restriction in \r\nfunctional community are \\emph{polymorphic variants} in OCaml\\cite{garrigue-98} \r\nand \\emph{open data types} in Haskell\\cite{LohHinze2006}, which allow addition \r\nof new variants later. These extensions, however, are simpler than object-oriented \r\nextensions as neither polymorphic variants nor open data types form subtyping \r\nrelation between themselves: open data types do not introduce any subtyping \r\nrelation, while the subtyping relation on polymorphic variants is a \r\n\\emph{semantic subtyping} similar to that of XDuce\\cite{HosoyaPierce2000}, which \r\nis based on the subset relation between values of the type. In either case they \r\nmaintain the important property that each value of the underlying algebraic data \r\ntype belongs to exactly one disjoint subset tagged with a constructor. The \r\n\\emph{nominative subtyping} of object-oriented languages does not usually have \r\nthis disjointness making classes effectively have multiple types. In particular, \r\nthe case of disjoint constructors can be seen as a degenerated case of a flat \r\nclass hierarchy among the multitude of possible class hierarchies.\r\n\r\nClosedness of algebraic data types is particularly useful for reasoning about \r\nprograms by case analysis and allows the compiler to perform an automatic \r\n\\emph{incompleteness} check -- test of whether a given \\emph{match statement} \r\ncovers all possible cases. Similar reasoning about programs involving extensible \r\ndata types is more involved as we are dealing with potentially open set of \r\nvariants. \\emph{Completeness} check in such scenario reduces to checking presence \r\nof a case that handles the static type of the subject. Absence of such a case,\r\nhowever, does not necessarily imply incompleteness, only potential incompleteness, \r\nas the answer will depend on the actual set of variants available at run-time.\r\n\r\nA related notion of \\emph{redundancy} checking arises from the \r\ntradition of using \\emph{first-fit} strategy in pattern matching. It warns the \r\nuser of any \\emph{case clause} inside a match statement that will \r\nnever be entered because of a preceding one being more general. Object-oriented \r\nlanguages, especially C++, typically prefer \\emph{best-fit} strategy (e.g. for \r\noverload resolution and class template specialization) because it is not prone \r\nto errors where semantics of a statement might change depending on the ordering \r\nof preceding definitions. The notable exception in C++ semantics that prefers \r\nthe \\emph{first-fit} strategy is ordering of \\code{catch} handlers of a \r\n\\code{try}-block. Similarly to functional languages the C++ compiler will perform \r\n\\emph{redundancy} checking on catch handlers and issue a warning that lists the \r\nredundant cases. We use this property of the C++ type system to perform redundancy \r\nchecking of our match statements in \\textsection\\ref{sec:redun}.\r\n\r\nThe patterns that work with algebraic data types we have seen so far are \r\ngenerally called \\emph{tree patterns} or \\emph{constructor patterns}. Their \r\nanalog in object-oriented languages is often referred to as \\emph{type pattern} \r\nsince it may involve type testing and type casting. Special cases of these patterns \r\nare \\emph{list patterns} and \\emph{tuple patterns}. The former lets one split a \r\nlist into a sequence of elements in its beginning and a tail with the help of \r\nlist constructor \\codehaskell{:} and an empty list constructor \\codehaskell{[]} \r\ne.g. \\codehaskell{[x:y:rest]}. The latter does the same with tuples using tuple\r\nconstructor \\codehaskell{(,,...,)} e.g. \\codehaskell{([x:xs],'b',(1,2.0),\"hi\",True)}.\r\n\r\nPattern matching is not used solely with algebraic data types and can equally \r\nwell be applied to built-in types. The following Haskell code defines factorial \r\nfunction in the form of equations:\r\n\r\n\\begin{lstlisting}[language=Haskell]\r\nfactorial 0 = 1\r\nfactorial n = n * factorial (n-1)\r\n\\end{lstlisting}\r\n\r\n\\noindent\r\nHere 0 in the left hand side of the first \\emph{equation} is an example of a \r\n\\emph{value pattern} (also known as \\emph{constant pattern}) that will only \r\nmatch when the actual argument passed to the function factorial is 0. The \r\n\\emph{variable pattern} \\codehaskell{n} (also referred to as \\emph{identifier \r\npattern}) in the left hand side of the second equation will match any value, \r\n\\emph{binding} variable \\codehaskell{n} to that value in the right hand side of \r\nequation. Similarly to variable pattern, the \\emph{wildcard pattern} \\codehaskell{_} \r\nwill match any value, neither binding it to a variable nor even obtaining it. \r\nValue patterns, variable patterns and wildcard patterns are  \r\ngenerally called \\emph{primitive patterns}. Patterns like variable and wildcard \r\npatterns that never fail to match are called \\emph{irrefutable}, in contrast to \r\n\\emph{refutable} patterns like value patterns, which may fail to match.\r\n\r\nIn Haskell 98\\cite{Haskell98Book} the above definition of factorial could also \r\nbe written as:\r\n\r\n\\begin{lstlisting}[language=Haskell]\r\nfactorial 0 = 1\r\nfactorial (n+1) = (n+1) * factorial n\r\n\\end{lstlisting}\r\n\r\n\\noindent\r\nThe \\codehaskell{(n+1)} pattern in the left hand side of equation is an example of \r\n\\emph{n+k pattern}. According to its informal semantics ``Matching an $n+k$ \r\npattern (where $n$ is a variable and $k$ is a positive integer literal) against \r\na value $v$ succeeds if $v \\ge k$, resulting in the binding of $n$ to $v-k$, and \r\nfails otherwise''\\cite{haskell98}. n+k patterns were introduced into Haskell to \r\nlet users express inductive functions on natural numbers in much the same way as \r\nfunctions defined through case analysis on algebraic data types. Besides \r\nsuccinct notation, such language feature could facilitate automatic proof of \r\ntermination of such functions by compiler. Peano numbers, used as an analogy to \r\nalgebraic data type representation of natural numbers, is not always the best \r\nabstraction for representing other mathematical operations however. This,  \r\ntogether with numerous ways of defining semantics of generalized n+k patterns \r\nwere some of the reasons why the feature was never generalized in Haskell to \r\nother kinds of expressions, even though there were plenty of known applications. \r\nMoreover, numerous debates over semantics and usefulness of the feature \r\nresulted in n+k patterns being removed from the language altogether in Haskell \r\n2010 standard\\cite{haskell2010}. Generalization of n+k patterns, called \r\n\\emph{application patterns} has been studied by Nikolaas N. Oosterhof in his \r\nMaster's thesis\\cite{OosterhofThesis}. Application patterns essentially treat \r\nn+k patterns as equations, while matching against them attempts to solve or \r\nvalidate the equation.\r\n\r\nWhile n+k patterns were something very few languages had, another common feature of \r\nmany programming languages with pattern matching are guards. A \\emph{guard} \r\nis a predicate attached to a pattern that may make use of the variables bound in \r\nit. The result of its evaluation will determine whether the case clause and the \r\nbody associated with it will be \\emph{accepted} or \\emph{rejected}. The \r\nfollowing OCaml code for $exp$ language from Section~\\ref{sec:intro} defines the \r\nrules for factorizing expressions $e_1e_2+e_1e_3$ into $e_1(e_2+e_3)$ and \r\n$e_1e_2+e_3e_2$ into $(e_1+e_3)e_2$ with the help of guards spelled out after \r\nkeyword \\codeocaml{when}:\r\n\r\n\\begin{lstlisting}[language=Caml,keepspaces,columns=flexible]\r\nlet factorize e =\r\n    match e with\r\n      Plus(Times(e1,e2), Times(e3,e4)) when e1 = e3 \r\n          -> Times(e1, Plus(e2,e4))\r\n    | Plus(Times(e1,e2), Times(e3,e4)) when e2 = e4 \r\n          -> Times(Plus(e1,e3), e4)\r\n    |   e -> e\r\n    ;;\r\n\\end{lstlisting}\r\n\r\n\\noindent\r\nOne may wonder why we could not simply write the above case clause as \r\n\\codeocaml{Plus(Times(e,e2), Times(e,e4))} to avoid the guard? Patterns that \r\npermit use of the same variable in them multiple times are called \r\n\\emph{equivalence patterns}, while the requirement of absence of such patterns \r\nin a language is called \\emph{linearity}. Neither OCaml nor Haskell support such \r\npatterns, while Miranda\\cite{Miranda85} as well as Tom's pattern matching \r\nextension to C, Java and Eiffel\\cite{Moreau:2003} supports \\emph{non-linear \r\npatterns}.\r\n\r\nThe example above illustrates yet another common pattern-matching facility -- \r\n\\emph{nesting of patterns}. In general, a constructor pattern composed of a \r\nlinear vector of (distinct) variables is called a \\emph{simple pattern}. The \r\nsame pattern composed not only of variables is called \\emph{nested pattern}.\r\nUsing nested patterns, with a simple expression in the case clause we could\r\ndefine a predicate that tests the top-level expression to be tagged with a\r\n\\codeocaml{Plus} constructor, while both of its arguments to be marked with \r\n\\codeocaml{Times} constructor, binding their arguments (or potentially pattern \r\nmatching further) respectively. Note that the visitor design pattern does not \r\nprovide this level of flexibility and each of the nested tests might have \r\nrequired a new visitor to be written. Nesting of patterns like the one above is \r\ntypically where users resort to \\emph{type tests} and \\emph{type casts} that in \r\ncase of C++ can be combined into a single call to \\code{dynamic_cast}.\r\n\r\nRelated to nested patterns are \\emph{as-patterns} that help one take a value \r\napart while still maintaining its integrity. The following rule could have been \r\na part of a hypothetical rewriting system in OCaml similar to the one above. Its \r\nintention is to rewrite expressions of the form $\\frac{e_1/e_2}{e_3/e_4}$ into \r\n$\\frac{e_1}{e_2}\\frac{e_4}{e_3} \\wedge e_2\\neq0 \\wedge e_3\\neq0 \\wedge e_4\\neq0$.\r\n\r\n\\begin{lstlisting}[language=Caml]\r\n    | Divide(Divide(_,e2) as x, Divide(e3,e4))\r\n          -> Times(x, Divide(e4, e3))\r\n\\end{lstlisting}\r\n\r\n\\noindent\r\nWe introduced a name ``x'' as a synonym of the result of matching the \r\nentire sub-expression \\codeocaml{Divide(_,e2)} in order to refer it without \r\nrecomposing in the right-hand side of the case clause. We omitted the \r\nconjunction of relevant non-zero checks for brevity, one can see that we will \r\nneed access to \\codeocaml{e2} in it however.\r\n\r\nDecomposing algebraic data types through pattern matching has an important \r\ndrawback that was originally spotted by Wadler\\cite{Wadler87}: they expose \r\nconcrete representation of an abstract data type, which conflicts with the \r\nprinciple of \\emph{data abstraction}. To overcome the problem he proposed the \r\nnotion of \\emph{views} that represent conversions between different \r\nrepresentations that are implicitly applied during pattern matching. As an \r\nexample, imagine polar and cartesian representations of complex numbers. A user \r\nmight choose polar representation as a concrete representation for the abstract \r\ndata type \\codeocaml{complex}, treating cartesian representation as view or vice \r\nversa:\\footnote{We use the syntax from Wadler's original paper for this example}\r\n\r\n\\begin{lstlisting}[language=Haskell,columns=flexible]\r\ncomplex ::= Pole real real\r\nview complex ::= Cart real real\r\n  in  (Pole r t) = Cart (r * cos t) (r * sin t)\r\n  out (Cart x y) = Pole (sqrt(x^2 + y^2)) (atan2 x y)\r\n\\end{lstlisting}\r\n\r\n\\noindent\r\nThe operations then might be implemented in whatever representation is the most \r\nsuitable, while the compiler will implicitly convert representation if needed:\r\n\r\n\\begin{lstlisting}[language=Haskell,columns=flexible]\r\n  add  (Cart x1 y1) (Cart x2 y2) = Cart (x1 + x2) (y1 + y2)\r\n  mult (Pole r1 t1) (Pole r2 t2) = Pole (r1 * r2) (t1 + t2)\r\n\\end{lstlisting}\r\n\r\n\\noindent\r\nThe idea of views were later adopted in various forms in several languages: \r\nHaskell\\cite{views96}, Standard ML\\cite{views98}, Scala (in the form of \r\n\\emph{extractors}\\cite{EmirThesis}) and F$\\sharp$ (under the name of \r\n\\emph{active patterns}\\cite{Syme07}). We demonstrate our support of views in \r\n\\textsection\\ref{sec:view}.\r\n\r\n%Views in functional programming languages [92, 71] are conversions from one data type to\r\n%another that are implicitly applied in pattern matching. They play a role similar to extractors\r\n%in Scala, in that they permit to abstract from the concrete data-type of the matched objects.\r\n%However, unlike extractors, views are anonymous and are tied to a particular target data\r\n%type.\r\n\r\nLogic programming languages like Prolog take pattern matching to even greater \r\nlevel. The main difference between pattern matching in logic languages and \r\nfunctional languages is that functional pattern matching is a ``one-way'' \r\nmatching where patterns are matched against values, possibly binding some \r\nvariables in the pattern along the way. Pattern matching in logic programming is \r\n``two-way'' matching based on \\emph{unification} where patterns can be matched \r\nagainst other patterns, possibly binding some variables in both patterns and \r\npotentially leaving some variables \\emph{unbound} or partially bound -- i.e. \r\nbound to patterns. A hypothetical example of such functionality can be matching \r\na pattern \\codeocaml{Plus(x,Times(x,1))} against another pattern \r\n\\codeocaml{Plus(Divide(y,2),z)}, which will result in binding \\codeocaml{x} to a \r\n\\codeocaml{Divide(y,2)} and \\codeocaml{z} to \\codeocaml{Times(Divide(y,2),1)} \r\nwith \\codeocaml{y} left unbound, leaving both \\codeocaml{x} and \\codeocaml{z} \r\neffectively a pattern.\r\n\r\n\\subsection{Algebraic Data Types in C++}\r\n\\label{sec:adt}\r\n\r\nC++ does not have a direct support of algebraic data types, but they can usually \r\nbe emulated in a number of ways. A pattern-matching solution that strives to be \r\ngeneral will have to account for different encodings and be applicable to all of \r\nthem.\r\n\r\nConsider an ML data type of the form:\r\n\r\n\\begin{lstlisting}[language=ML,keepspaces,columns=flexible,escapechar=@]\r\ndatatype DT = @$C_1$@ of {@$L_{11}:T_{11},...,L_{1m}:T_{1m}$@} \r\n              | ...\r\n              | @$C_k$@ of {@$L_{k1}:T_{k1},...,L_{kn}:T_{kn}$@}\r\n\\end{lstlisting}\r\n\r\n\\noindent There are at least 3 different ways to represent it in C++. Following \r\nEmir, we will refer to them as \\emph{encodings}~\\cite{EmirThesis}:\r\n\r\n\\begin{itemize}\r\n\\setlength{\\itemsep}{0pt}\r\n\\setlength{\\parskip}{0pt}\r\n\\item Polymorphic Base Class (or \\emph{polymorphic encoding} for short)\r\n\\item Tagged Class (or \\emph{tagged encoding} for short)\r\n\\item Discriminated Union (or \\emph{union encoding} for short)\r\n\\end{itemize}\r\n\r\n\\noindent\r\nIn polymorphic and tagged encoding, base class \\code{DT} represents algebraic \r\ndata type, while derived classes represent variants. The only difference between \r\nthe two is that in polymorphic encoding base class has virtual functions, while \r\nin tagged encoding it has a dedicated member of integral type that uniquely \r\nidentifies the variant -- derived class. \r\n\r\nThe first two encodings are inherently \\emph{open} because the classes can be \r\narbitrarily extended through subclassing. The last encoding is inherently \r\n\\emph{closed} because we cannot add more members to the union without modifying \r\nits definition.\r\n\r\n%In order to be able to provide a common syntax for these representations, we \r\n%need to understand better similarities and differences between them. Before we \r\n%look into them let's fix some terminology.\r\n\r\nWhen we deal with pattern matching, the static type of the original expression \r\nwe are matching may not necessarily be the same as the type of expression we \r\nmatch it with. We call the original expression a \\emph{subject} and its static \r\ntype -- \\emph{subject type}. We call the type we are trying to match subject \r\nagainst -- a \\emph{target type}.\r\n\r\nIn the simplest case, detecting that the target type is a given type or a type \r\nderived from it, is everything we want to know. We refer to such a use-case as \r\n\\emph{type testing}. In the next simplest case, besides testing we might want to \r\nget a pointer or a reference to the target type of subject as casting it to such \r\na type may involve a non-trivial computation only a compiler can safely \r\ngenerate. We refer to such a use-case as \\emph{type identification}. Type \r\nidentification of a given subject against multiple target types is typically \r\nreferred to as \\emph{type switching}.\r\n\r\nOnce we uncovered the target type, we may want to be able to decompose it \r\n\\emph{structurally} (when the target type is a \\emph{structured} data type like \r\narray, tuple or class) or \\emph{algebraically} (when the target type is a scalar \r\ndata type like \\code{int} or \\code{double}). Structural decomposition in our \r\nlibrary can be performed with the help of \\emph{tree patterns}, while algebraic \r\ndecomposition can be done with the help of \\emph{generalized n+k patterns}.\r\n\r\n\\subsubsection{Polymorphic Base Class}\r\n\\label{sec:pbc}\r\n\r\nIn this encoding user declares a polymorphic base class \\code{DT} that will \r\nbe extended by classes representing all the variants. Base class might declare \r\nseveral virtual functions that will be overridden by derived classes, for example \r\n\\code{accept} used in a Visitor Design Pattern.\r\n\r\n\\begin{lstlisting}[keepspaces,columns=flexible]\r\nclass DT { virtual @$\\sim$@DT{} };\r\nclass @$C_1$@ : public DT {@$T_{11} L_{11}; ... T_{1m} L_{1m};$@} \r\n...\r\nclass @$C_k$@ : public DT {@$T_{k1} L_{k1}; ... T_{kn} L_{kn};$@} \r\n\\end{lstlisting}\r\n\r\nThe uncover the actual variant of such an algebraic data type, the user might \r\nuse \\code{dynamic_cast} to query one of the $k$ expected run-time types (an \r\napproach used by Rose\\cite{SQ03}) or she might employ a visitor design pattern \r\ndevised for this algebraic data type (an approach used by Pivot\\cite{Pivot09} \r\nand Phoenix\\cite{Phoenix}). The most attractive feature of this approach is that \r\nit is truly open as we can extend classes arbitrarily at will (leaving the \r\northogonal issues of visitors aside).\r\n\r\n\\subsubsection{Tagged Class}\r\n\\label{sec:tc}\r\n\r\nThis encoding is similar to the \\emph{Polymorphic Base Class} in that we use \r\nderived classes to encode the variants. The main difference is that the user \r\ndesignates a member in the base class, whose value will uniquely \r\ndetermine the most derived class a given object is an instance of. Constructors \r\nof each variant $C_i$ are responsible for properly initializing the dedicated \r\nmember with a unique value $c_i$ associated with that variant. Clang\\cite{Clang} \r\namong others uses this approach.\r\n\r\n\\begin{lstlisting}[keepspaces,columns=flexible]\r\nclass DT { enum kinds {@$c_1, ..., c_k$@} m_kind; };\r\nclass @$C_1$@ : public DT {@$T_{11} L_{11}; ... T_{1m} L_{1m};$@} \r\n...\r\nclass @$C_k$@ : public DT {@$T_{k1} L_{k1}; ... T_{kn} L_{kn};$@} \r\n\\end{lstlisting}\r\n\r\nIn such scenario the user might use a simple switch statement to uncover the \r\ntype of the variant combined with a \\code{static_cast} to properly cast the \r\npointer or reference to an object. People might prefer this encoding to the one \r\nabove for performance reasons as it is possible to avoid virtual dispatch with \r\nit altogether. Note, however, that once we allow for extensions and not limit \r\nourselves with encoding algebraic data types only it also has a significant \r\ndrawback in comparison to the previous approach: we can easily check that given \r\nobject belongs to the most derived class, but we cannot say much about whether \r\nit belongs to one of its base classes. A visitor design pattern can be \r\nimplemented to take care of this problem, but control inversion that comes along \r\nwith it will certainly diminish the convenience of having just a switch \r\nstatement. Besides, forwarding overhead might lose some of the performance \r\nbenefits gained originally by putting a dedicated member into the base class.\r\n\r\n\\subsubsection{Discriminated Union}\r\n\\label{sec:du}\r\n\r\nThis encoding is popular in projects that are either implemented in C or \r\noriginated from C before coming to C++. It involves a type that contains a union \r\nof its possible variants, discriminated with a dedicated value stored as a part \r\nof the structure. The approach is used by EDG front-end\\cite{EDG} and many others.\r\n\r\n\\begin{lstlisting}[keepspaces,columns=flexible]\r\nstruct DT\r\n{\r\n    enum kinds {@$c_1, ..., c_k$@} m_kind;\r\n    union {\r\n        struct @$C_1$@ {@$T_{11} L_{11}; ... T_{1m} L_{1m};$@} @$C_1$@;\r\n        ...\r\n        struct @$C_k$@ {@$T_{k1} L_{k1}; ... T_{kn} L_{kn};$@} @$C_k$@; \r\n    };\r\n};\r\n\\end{lstlisting}\r\n\r\nAs before, the user can use a switch statement to identify the variant $c_i$ and \r\nthen access its members via $C_i$ union member. This approach is truly closed, as \r\nwe cannot add new variants to the underlying union without modifying class \r\ndefinition. \r\n\r\nNote also that in this case both subject type and target types are the same and \r\nwe use an integral constant to distinguish which member(s) of the underlying union \r\nis active now. In the other two cases the type of a subject is a base class of \r\nthe target type and we use either run-time type information or the integral \r\nconstant associated by the user with the target type to uncover the target type. \r\n\r\n\\subsection{Expression Templates}\r\n\r\nInterestingly enough C++ has a pure functional sublanguage in it that has a \r\nstriking similarity to ML and Haskell. The sublanguage in question is template \r\nfacilities of C++ that has been shown to be Turing \r\ncomplete\\cite{veldhuizen:templates_turing_complete}. \r\n\r\nHaskell definition of \\code{factorial} we saw earlier can be rewritten in \r\ntemplate sublanguage of C++ as following:\r\n\r\n\\begin{lstlisting}\r\ntemplate <int N> \r\n    struct factorial { enum { result = N*factorial<N-1>::result }; };\r\ntemplate <>\r\n    struct factorial<0> { enum { result = 1 }; };\r\n\\end{lstlisting}\r\n\r\n\\noindent\r\nOne can easily see similarity with equational definitions in Haskell, with the \r\nexception that more specific cases (specialization for 0) have to follow the \r\ngeneral definition in C++. The main difference between Haskell definition and \r\nits C++ counterpart is that the former describes computations on \\emph{run-time \r\nvalues}, while the latter can only work with \\emph{compile-time values}.\r\n\r\nTurns out we can even express our $exp$ language using this functional \r\nsublanguage:\r\n\r\n\\begin{lstlisting}\r\ntemplate <class T>\r\nstruct value {\r\n    value(const T& t) : m_value(t) {}\r\n    T m_value;\r\n};\r\n\r\ntemplate <class T>\r\nstruct variable {\r\n    variable() : m_value() {}\r\n    T m_value;\r\n};\r\n\r\ntemplate <typename E1, typename E2>\r\nstruct plus {\r\n    plus(const E1& e1, const E2& e2) : m_e1(e1), m_e2(e2) {}\r\n    const E1 m_e1; const E2 m_e2;\r\n};\r\n\r\n// ... definitions of other expressions\r\n\\end{lstlisting}\r\n\r\n\\noindent The idea is that expressions can be composed out of subexpressions, \r\nwhose shape (type) is passed as arguments to above templates. Explicit \r\ndescription of such expressions is very tedious however and is thus never \r\nexpressed directly, but as a result of corresponding operations: \r\n\r\n\\begin{lstlisting}[keepspaces,columns=flexible]\r\ntemplate <typename T>\r\n    value<T> val(const T& t) { return value<T>(t); }\r\ntemplate <typename E1, typename E2>\r\n    plus<E1,E2> operator+(const E1& e1, const E2& e2)\r\n    { return plus<E1,E2>(e1,e2); }\r\n\\end{lstlisting}\r\n\r\n\\noindent With this, one can now capture various expressions as following:\r\n\r\n\\begin{lstlisting}\r\nvariable<int> v;\r\nauto x = v + val(3);\r\n\\end{lstlisting}\r\n\r\n\\noindent The type of variable \\code{x} -- \\code{plus<variable<int>,value<int>>}\r\n -- captures the structure of the expression, while the values inside of it \r\nrepresent various subexpressions the expression was created with. Such an \r\nexpression can be arbitrarily, but finitely nested. Note that value 3 is not \r\nadded to the value of variable \\code{v} here, but the expression \\code{v+3} is \r\nrecorded, while the meaning to such expression can be given differently in \r\ndifferent contexts. A general observation is that only the shape of the \r\nexpression becomes fixed at compile time, while the values of variables involved \r\nin it can be changed arbitrarily at run time, allowing for \\emph{lazy \r\nevaluation} of the expression. Polymorphic function \\code{eval} below implements \r\njust that:\r\n\r\n\\begin{lstlisting}[keepspaces,columns=flexible]\r\ntemplate <typename T> \r\n    T eval(const value<T>& e) { return e.m_value; }\r\ntemplate <typename T> \r\n    T eval(const variable<T>& e) { return e.m_value; }\r\ntemplate <typename E1, typename E2> \r\n    auto eval(const plus<E1,E2>& e) \r\n         -> decltype(eval(e.m_e1) + eval(e.m_e2))\r\n            { return eval(e.m_e1) + eval(e.m_e2); }\r\n\\end{lstlisting}\r\n\r\n\\noindent One can now modify value of the variable \\code{v} and re-evaluate \r\nexpression as following:\r\n\r\n\\begin{lstlisting}\r\nv = 7;           // assumes overloading of assignment\r\nint r = eval(x); // returns 10\r\n\\end{lstlisting}\r\n\r\n\\noindent The above technique for lazy evaluation of expressions was \r\nindependently invented by Todd Veldhuizen and David Vandevoorde and is generally \r\nknown in the C++ community by the name \\emph{Expression Templates} that Todd \r\ncoined\\cite{Veldhuizen95expressiontemplates, vandevoorde2003c++}.  \r\n\r\nNote again how implementation of \\code{eval} resembles equations in Haskell that \r\ndecompose an algebraic data type. The similarities are so striking that there \r\nwere attempts to use Haskell as a pseudo code language for template \r\nmetaprogramming in C++\\cite{Milewski11}. A key observation in this analogy is \r\nthat partial and explicit template specialization of C++ class templates are \r\nsimilar to defining equations for Haskell functions. Variables introduced via \r\ntemplate clause of each equation serve as \\emph{variable patterns}, while the \r\nnames of actual templates describing arguments serve as \\emph{variant \r\nconstructors}. An important difference between the two is that Haskell's \r\nequations use \\emph{first-fit} strategy making order of equations important, \r\nwhile C++ uses \\emph{best-fit} strategy, thus making the order irrelevant.\r\n\r\nPatterns expressed this way can be arbitrarily nested as long as they can be \r\nexpressed in terms of the types involved and not the values they store. Using \r\nthe above example, for instance, it is very easy to specialize \\code{eval} for \r\nan expression of form $c_1*x+c_2$ where $c_i$ are some (not known) constant \r\nvalues and $x$ is any variable. Specializing for a concrete instance of that \r\nexpression $2*x+3$ will be much harder, because in the representation we chose \r\nvalues 2 and 3 become run-time values and thus cannot participate in \r\ncompile-time computations anymore. In this case we could have devised a template \r\nthat allocates a dedicated type for each constant making such value part of the \r\ntype:\r\n\r\n\\begin{lstlisting}[keepspaces,columns=flexible]\r\ntemplate <class T, T t> struct constant {};\r\n\r\ntemplate <typename T, T t>\r\n    T eval(const constant<T,t>& e) { return t; }\r\ntemplate <typename E>\r\n    auto eval(const times<constant<int,0>,E>& e) \r\n        -> decltype(eval(e.m_e2)) \r\n            { return (decltype(eval(e.m_e2)))(0); }\r\ntemplate <typename E>\r\n    auto eval(const times<E,constant<int,0>>& e) \r\n        -> decltype(eval(e.m_e1)) \r\n            { return (decltype(eval(e.m_e1)))(0); }\r\n\\end{lstlisting}\r\n\r\n\\noindent Here the first equation for \\code{eval} describes the necessary general \r\ncase for handling expressions of type \\code{constant<T,t>}, while the other two \r\nare redundant cases that can be seen as an optimization detecting expressions of \r\nthe form $e*0$ and $0*e$ for any arbitrary expression $e$ and returning 0 \r\nwithout actually computing $e$.\r\n\r\nUnfortunately, a similar pattern to detect expressions of the form $x-x$ for any \r\nvariable $x$ cannot be expressed because expression templates are blind to \r\nobject identity and can only see their types. This means that expression \r\ntemplates of the form $x-y$ are indisthinguishable at compile time from \r\nexpressions of the form $x-x$ because their types are identical.\r\n\r\nNevertheless, with all the limitations, expression templates provide an \r\nextremely powerful abstraction mechanism, which we use to express a \r\npattern-language for our SELL. Coincidentally, we employ the compile-time \r\npattern-matching facility already supported by C++ as a meta-language to \r\nimplement its run-time counterpart.\r\n", "meta": {"hexsha": "56c366eb2a120e4011f89cc2b5a346c82c68d9f7", "size": 32449, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "media/papers/TR/sec-2-background.tex", "max_stars_repo_name": "akrzemi1/Mach7", "max_stars_repo_head_hexsha": "eef288eb9fe59712ff153dd70791365391b7b118", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1310, "max_stars_repo_stars_event_min_datetime": "2015-01-04T03:44:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T04:44:01.000Z", "max_issues_repo_path": "media/papers/TR/sec-2-background.tex", "max_issues_repo_name": "akrzemi1/Mach7", "max_issues_repo_head_hexsha": "eef288eb9fe59712ff153dd70791365391b7b118", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 62, "max_issues_repo_issues_event_min_datetime": "2015-01-12T07:59:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-14T22:02:14.000Z", "max_forks_repo_path": "media/papers/TR/sec-2-background.tex", "max_forks_repo_name": "akrzemi1/Mach7", "max_forks_repo_head_hexsha": "eef288eb9fe59712ff153dd70791365391b7b118", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 108, "max_forks_repo_forks_event_min_datetime": "2015-02-13T17:39:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-18T11:06:59.000Z", "avg_line_length": 52.9347471452, "max_line_length": 97, "alphanum_fraction": 0.7529661931, "num_tokens": 7885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6113819591324418, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.34135105163328894}}
{"text": "\\input{templates/lec_template.tex}\n\n\\begin{document}\n\n\\title[Recursion]{Week 10: Recursion}\n\\subtitle{Basic Programming in Python}\n\n\\date{\\today}\n\n\\begin{frame}[plain]\n     \\titlepage\n\\end{frame}\n\n\\begin{frame}\n    \\tableofcontents\n\\end{frame}\n\n\\section{Fibonacci}\n\n\\begin{frame}\n    \\sectionpage\n\\end{frame}\n\n\n\\begin{frame}{The Fibonacci Number}\n\n\\textbf{Definition:}\n\n\n$F_0 = 0, F_1 = 1$\n\n$F_n = F_{n-1} + F_{n-2}$\n\n\\vspace{1em}\n\\textbf{Example:}\n\n\n$F_2 = F_1 + F_0 = 0 + 1 = 1$\n\n$F_3 = F_2 + F_1 = 1 + 1 = 2$\n\n$F_{100} = ?$\n\n\\note{\n    \\begin{center}\n        \\includegraphics[height=0.8\\textheight]{10_Recursion/rabbits.png}\n    \\end{center}\n\n}\n\\end{frame}\n\n\\end{document}\n", "meta": {"hexsha": "7f0bffedfcb22d1dca2f7b86988ce2d98e66b488", "size": 676, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "2021/10_Recursion/10_Recursion_Lec.tex", "max_stars_repo_name": "lfrommelt/monty", "max_stars_repo_head_hexsha": "e8cabf0e4ac01ab3d97eecee5e699139076d6544", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2021/10_Recursion/10_Recursion_Lec.tex", "max_issues_repo_name": "lfrommelt/monty", "max_issues_repo_head_hexsha": "e8cabf0e4ac01ab3d97eecee5e699139076d6544", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2021/10_Recursion/10_Recursion_Lec.tex", "max_forks_repo_name": "lfrommelt/monty", "max_forks_repo_head_hexsha": "e8cabf0e4ac01ab3d97eecee5e699139076d6544", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.7547169811, "max_line_length": 73, "alphanum_fraction": 0.6420118343, "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.34130061746091017}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Short Sectioned Assignment\n% LaTeX Template\n% Version 1.0 (5/5/12)\n%\n% This template has been downloaded from:\n% http://www.LaTeXTemplates.com\n%\n% Original author:\n% Frits Wenneker (http://www.howtotex.com)\n%\n% License:\n% CC BY-NC-SA 3.0 (http://creativecommons.org/licenses/by-nc-sa/3.0/)\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%----------------------------------------------------------------------------------------\n%\tPACKAGES AND OTHER DOCUMENT CONFIGURATIONS\n%----------------------------------------------------------------------------------------\n\\documentclass[a4paper]{article}\n\n\\usepackage[hmarginratio=1:1,top=32mm,margin=20mm]{geometry} % Document margins\n\\usepackage{lmodern}\n\\usepackage[T1]{fontenc}\t% Use 8-bit encoding that has 256 glyphs\n\\usepackage[english]{babel}\t % English language/hyphenation\n%\\usepackage[utf8x]{inputenc}\n\\usepackage{amsmath,amsfonts,amsthm,bm} % AMS - Math, Fonts, Theorems, BoldMath\n\\usepackage{graphicx} % For putting pictures\n\\usepackage{booktabs} % Horizontal rules in tables\n\\usepackage{hyperref} % For hyperlinks in the PDF\n\n\\usepackage{fancyhdr} % Headers and footers\n\\pagestyle{fancy} % All pages have headers and footers\n\\fancyhead{} % Blank out the default header\n\\fancyfoot{} % Blank out the default footer\n\\fancyhead[C]{Thesis} % Custom header text\n\\fancyfoot[L]{MathMods $\\bullet$ 2015 Apr}\n\\fancyfoot[R]{Page \\huge{\\thepage}} % Custom footer text\n\n\\numberwithin{equation}{section} % Number equations within sections (i.e. 1.1, 1.2, 2.1, 2.2 instead of 1, 2, 3, 4)\n\\numberwithin{figure}{section} % Number figures within sections (i.e. 1.1, 1.2, 2.1, 2.2 instead of 1, 2, 3, 4)\n\\numberwithin{table}{section} % Number tables within sections (i.e. 1.1, 1.2, 2.1, 2.2 instead of 1, 2, 3, 4)\n\n\\setlength\\parindent{0pt} % Removes all indentation from paragraphs - comment this line for an assignment with lots of text\n\n\\newtheorem{thm}{Theorem}\n\\newtheorem{corr}{Corollary}\n\\newtheorem{lem}{Lemma}\n\\newtheorem{prop}{Proposition}\n\\newtheorem*{rem}{Remark}\n\\newtheorem{defn}{Definition}\n\n%----------------------------------------------------------------------------------------\n%\tTITLE SECTION\n%----------------------------------------------------------------------------------------\n\n\\newcommand{\\horrule}[1]{\\rule{\\linewidth}{#1}} % Create horizontal rule command with 1 argument of height\n\n\\title{\t\n\\normalfont \\normalsize \n\\textsc{Thesis} \\\\ [25pt]\n\\horrule{0.5pt} \\\\[0.4cm] % Thin top horizontal rule\n\\huge The Singular Points method for Asian American options for local volatility models % The assignment title\n\\horrule{2pt} \\\\[0.5cm] % Thick bottom horizontal rule\n}\n\n\\author{Sudip Sinha}\n\n\\date{\\normalsize\\today}\n\n\\begin{document}\n\n\\maketitle\t% Print the title\n\n%\\begin{abstract}\n%Your abstract.\n%\\end{abstract}\n\n%----------------------------------------------------------------------------------------\n%\tPROBLEM 1\n%----------------------------------------------------------------------------------------\n\n\n\\section{Introduction}\nThe Singular Points method for Asian American options for local volatility models.\n\n\n\\section{Notations}\n$[n] = \\{0, 1, 2, \\dots, n\\}$\n\n\n\\section{Basic formulae}\n\n\\begin{subequations} \\label{eq:arithmeticmean}\nArithmetic average\n\\begin{align}\nA_{n} &= \\frac{\\sum_{i=0}^n S_i}{n+1} \\\\\n\\implies (n+1) A_{n} &= \\sum_{i=0}^n S_i\n\\end{align}\n\\end{subequations}\n\n\n\\section{Results}\n\n\\begin{defn}[Path]\nA path is a sequence $(j_i)_{i \\in [n]}$ such that $j_{i+1} \\in \\{ j_i,j_i+1 \\}$.\n\\end{defn}\n\n\n\\begin{lem}\nLet there be two paths $\\alpha$ and $\\beta$, such that $S_{i,j_i^\\alpha} >= S_{i,j_i^\\beta} \\; \\forall i$. Then $A^\\alpha >= A^\\beta$.\n\\end{lem}\n\n\\begin{proof}\nClearly if $S_{i,j_i^\\alpha} = S_{i,j_i^\\beta} \\; \\forall i$, then $A^\\alpha = A^\\beta$.\n\nWe only need to show the case of inequality.\nLet $S_{i,j_i^\\alpha} = S_{i,j_i^\\beta} \\; \\forall i \\in [n] \\setminus \\{l\\}$. That is, $S_{l,j_l^\\alpha} > S_{l,j_l^\\beta}$.\n\nNow, from equation \\ref{eq:arithmeticmean}, we have:\n\\begin{align*}\n(n+1) A_{n,j}^\\alpha &= \\sum_{i=0}^{l-1} S_{i,j_i} + S_{l,j_l^\\alpha} + \\sum_{i=l+1}^{n} S_{i,j_i} \\\\\n(n+1) A_{n,j}^\\beta &= \\sum_{i=0}^{l-1} S_{i,j_i} + S_{l,j_l^\\beta} + \\sum_{i=l+1}^{n} S_{i,j_i} \\\\\n\\implies (n+1) \\left(A_{n,j}^\\alpha - A_{n,j}^\\beta\\right) &= S_{l,j_l^\\alpha} - S_{l,j_l^\\beta} \\\\\n\t&= S_{l-1,j_{l-1}} u_l - S_{l-1,j_{l-1}} d_l \\\\\n\t&= S_{l-1,j_{l-1}} (u_l - d_l) > 0 \\\\\n\\implies A_{n,j}^\\alpha > A_{n,j}^\\beta\n\\end{align*}\n\n\\end{proof}\n\n\n\\begin{rem}\nThe path $\\alpha$ signifies the path above and $\\beta$ signifies the path below. Thus, the path above always has a higher arithmetic mean.\n\\end{rem}\n\n\n\\begin{corr}\nAt each node $N(n,j)$, the average values vary between a minimum average $A_{n,j}^{\\mathrm{min}}$ (corresponding to the path with $(n-j)$ down movements followed by $j$ up movements) and a maximum average $A_{n,j}^{\\mathrm{max}}$ (corresponding to the path with $j$ up movements followed by $(n-j)$ down movements).\n\\end{corr}\n\n\\begin{proof}\nThe path 'min' is the bottom-most one and 'max' is the topmost one.\n\\end{proof}\n\n\n\\begin{lem}[Lemma 3]\nThe price function at maturity $v_{n,j}$ is convex and piecewise linear.\n\\end{lem}\n\\begin{proof}\nBy construction. See the paper.\n\\end{proof}\n\n\n\\begin{lem}[Lemma 4]\nThe price function $v_{i,j}$ is concave and non-linear.\n\\end{lem}\n\\begin{proof}\n\\ref{eq:arithmeticmean}\n\n\\end{proof}\n\n\\section{Conclusion}\nThe singular points method may not be used to price Geometric Asian options.\n\n\\end{document}\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: t\n%%% End:\n", "meta": {"hexsha": "b920f9b311c6bc607b6616aa30cf198806e93884", "size": 5568, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "MathMods/Thesis/docs/misc/tr_asian_singularpoints.tex", "max_stars_repo_name": "homdx/edu", "max_stars_repo_head_hexsha": "a32c9f1777f80a54c3d4a3fc8389748fe27739c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MathMods/Thesis/docs/misc/tr_asian_singularpoints.tex", "max_issues_repo_name": "homdx/edu", "max_issues_repo_head_hexsha": "a32c9f1777f80a54c3d4a3fc8389748fe27739c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MathMods/Thesis/docs/misc/tr_asian_singularpoints.tex", "max_forks_repo_name": "homdx/edu", "max_forks_repo_head_hexsha": "a32c9f1777f80a54c3d4a3fc8389748fe27739c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-09-15T21:30:43.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-15T21:30:43.000Z", "avg_line_length": 32.3720930233, "max_line_length": 315, "alphanum_fraction": 0.6154813218, "num_tokens": 1752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.3413006174609101}}
{"text": "\n\n\n\n\n\n\\chapter{Conclusions}\n\\label{chap:conclusions}\nWe have taken, over the course of this work, a tour through a rather wide expanse of material, so by way of conclusion we present a short summary of the main paradigms we have explored and the principal results we have uncovered.\n\n\n\n\\subsection*{Part I: Ionization}\n\n\\subsubsection[Analytical R-matrix Theory]{Analytical $R$-Matrix theory}\nIn chapter~\\ref{chap:R-matrix} we lay down the groundwork for the ionization parts of this thesis, reviewing in detail the construction of the Analytical $R$-Matrix theory of photoionization. We showed how one can split space into an inner and an outer region, using the inner region as a source term for the Schrödinger equation on the outer region, and how to employ the ionic and Coulomb-corrected continuum wavefunctions to produce a simple trajectory-based description of the photoionization, both on the single-active-electron direct channels as well as for the multi-electron correlation-driven mechanism. In addition, we presented in section~\\ref{sec:molecular-shape-factors} simple analytical formulas for a suitable model of a molecular orbital with nontrivial geometry.\n\n\n\n\n\\subsubsection{Multi-channel geometrical effects}\nIn chapter~\\ref{chap:multi-channel} we built on the multi-electron Analytical $R$-Matrix expressions for the direct and correlation-driven yields for photoelectrons that leave behind an excited ion, probing the ionization of a suitable model of an aligned carbon dioxide molecule, with a nontrivial combination of orbital geometries. There we showed how to implement a suitable modification of the saddle-point approximation for the correlation-driven geometrical factors, giving clean and physically transparent expressions. \n\nFinally, we showed how the nontrivial angular distributions obtained in this geometry admit a simple interpretation as double-slit diffraction fringes that originate in a pair of `slits' caused by the correlation-driven interaction with the ion inside the tunnelling~barrier.\n\n\n\\subsubsection{Analytical continuation of electrostatic potentials}\nIn chapter~\\ref{chap:complex-space-potentials} we examined in detail one of the crucial ingredients of the multi-electron ARM yield for correlation-driven ionization, the correlation interaction electrostatic potentials\n\\begin{equation}\n\\Vnm{\\vbr}=\\matrixel**{n}{\\sum_{j=1}^{N-1} \\frac{1-\\delta_{nm}}{\\| \\vbr - \\hat{\\vbr}_j\\|} }{m}\n,\n\\backtag{e4-correlation-interaction-potential-initial}\n\\end{equation}\nand their analytical continuations into complex positions $\\vbr$. We examined the naive analytical continuation for an elementary gaussian orbital via direct numerical integration, and we found it wanting, as it does not obey the Cauchy-Riemann equations.\n\nWe then focussed on the behaviour of simpler models -- exponential and gaussian type orbitals --, for which we can find exact expressions for the potentials, and therefore examine their analytical continuations directly. Here we find that, for points that are `real enough', in the sense that\n\\begin{equation}\n\\Re(\\vbr^2)>0,\n\\backtag{e4-re-r2-less-than-0}\n\\end{equation}\nthe different models agree surprisingly well, but that immediately upon leaving that region the potential for the gaussian-type orbital catastrophically diverges.\n\nThis means, then, that as long as we keep our evaluations of $\\Vnm{\\rl(t)}$ to trajectories that obey \\eqref{e4-re-r2-less-than-0} throughout, we can be rather confident that the analytical continuation is accurate, even if using gaussian-based quantum chemical calculations. Moreover, as we showed in chapter~\\ref{chap:quantum-orbits}, it is in fact possible to choose trajectories that adhere to this constraint.\n\nOn the other hand, the other region -- the points that are so imaginary that $\\Re(\\vbr^2)<0$~-- is much more challenging. As we argued, it is difficult to obtain any information, even of a qualitative type, about the behaviour of the potential in this region, even though there are formal existence theorems that guarantee us the existence of analytical continuations of  our interaction potential.\n\n\n\n\\subsubsection{Quantum orbits in complex time and complex space}\nIn chapter~\\ref{chap:quantum-orbits} we explored the origin and meaning of the imaginary part of the ARM trajectory, which is of the form\n\\begin{equation}\n\\rl(t) = \\int_{\\ts}^{t} \\left[\\vbp+\\vba(\\tau) \\right] \\: \\d\\tau\n,\n\\backtag{e5-laser-driven-trajectory}\n\\end{equation}\nand is generally complex-valued for real times $t$. This imaginary part emerges directly from the Schrödinger equation, and more particularly from the boundary matching of our eikonal Volkov states with the WKB asymptotic expressions for the states of the system in the inner ARM region, and it is a crucial ingredient in allowing ARM do describe the Coulomb enhancement of ionization.\n\nHowever, this imaginary part of the position also combines with the branch cut of the square root in the Coulomb potential,\n\\begin{equation}\nU(\\rl(t)) = -\\frac{1}{\\sqrt{\\rl(t)^2}},\n\\backtag{e5-coulomb-potential-at-the-trajectory}\n\\end{equation}\nto imprint a series of branch cuts on the complex time plane, which we need to integrate over to obtain the ARM yield. Moreover, these branch cuts can and do intersect the standard contour along the real axis, which needs to be accordingly modified, ideally in an algorithmic way which can be performed by a computer to calculate photoelectron spectra.\n\nThis modification is possible by hinging on the concept of a time of closest approach, that is, times $\\tca$ that obey equations of the type\n\\begin{equation}\n\\rl(\\tca)\\cdot\\vbv(\\tca)=0,\n\\backtag{e5-tca-equation}\n\\end{equation}\nand which are always present as saddle points in the middle of any gate formed by two branch cuts. These have a fascinatingly rich geometry, with the complex-valued quantum versions forming multiple sheets of a surface encasing the corresponding classical version, and they show interesting topological transitions -- with strong effects on the requirements for the ARM integration path -- at soft recollisions, where the laser-driven trajectory has a turning point close to the ion.\n\nMoreover, we were able to successfully and algorithmically choose the appropriate $\\tca$s to use as waypoints by requiring that they be `out of the tunnelling barrier', having positive real part of the kinetic energy $\\vbv(t)^2$, after which it is possible to programmatically choose appropriate integration paths that avoid complex, and fast-changing, configurations of branch cuts. In addition, this navigation algorithm is also automatically able to steer us clear of the problematic regions of chapter~\\ref{chap:complex-space-potentials}.\n\n\n\n\n\n\\subsubsection{Low-Energy Structures and Near-Zero Energy Structures}\nIn chapter~\\ref{chap:LES-NZES}, after a review of the available experimental evidence on the Low-Energy and Near-Zero Energy Structures of mid-IR photoionization, we brought our branch-cut navigation algorithm from chapter~\\ref{chap:quantum-orbits} to bear on experiment, by using it to analyse the LES regions, which emerge naturally from one of the unavoidable (but resolvable) difficulties of the algorithm: the soft recollisions, where multiple branch cuts come into close proximity, interact, and undergo topological transitions.\n\nFurther, these LES peaks, which are well understood to be associated with these soft recollisions, are joined within the ARM formalism by a dynamically equivalent set at much lower energy, which approaches the ion on a forwards turning point, after an integral number of periods, instead of the more usual backwards turning points after a half-integral number of laser cycles.\n\nWe study the peaks caused by this new series of trajectories, showing that it produces a peak at energies consistent with those observed for the NZES, and that it produces qualitatively similar transverse photoelectron to those observed in high-resolution experiments. Moreover, the identification of this series as a contributor to the NZES opens clear ways to test this mechanism experimentally: since the new series only needs to advance by the tunnel exit over a laser period, instead of by the laser oscillation quiver radius $\\zquiv=F/\\omega^2$, its momentum and energy scale as\n\\begin{equation}\n\\pzsr \n\\approx \\frac{\\zexit}{\\Delta t}\n= \\frac{I_p/F}{(n+1)\\pi/\\omega}\n\\propto \\frac{I_p\\omega}{F}\n%\n\\quad\\text{and}\\quad\n%\n\\frac12\\left(\\pzsr\\right)^2 \n\\sim \\frac{I_p^2}{U_p}\n\\sim I_p\\gamma^2,\n\\backtagtwo{e6-pzsr-odd-n-summary}{e6-odd-n-energy-scaling}\n\\end{equation}\nrespectively. Thus, the new series scales inversely with the ponderomotive potential $U_p$ (as opposed to the known series, which scales as $\\frac12\\left(\\pzsr\\right)^2 \\propto U_p$), which means that it should be possible to probe the role of the new series by using experiments in harder targets with higher ionization potentials.\n\n\n\n\n\\section*{Part II: High-order harmonic generation}\n\n\\subsubsection{Conservation of spin angular momentum in bicircular HHG}\nAfter reviewing the standard theory of high-order harmonic generation in chapter~\\ref{chap:HHG-intro}, we turned in chapter~\\ref{chap:spin-HHG} to the generation of high-order harmonics by bicircular fields -- counter-rotating circularly polarized fields, one at the fundamental at $\\SI{800}{nm}$ and one detuned from its second harmonic, at $\\SI{410}{nm}$. We reviewed the experimental evidence that establishes clear selection rules coming from the conservation of spin angular momentum, together with the breakdown of these selection rules when the polarization of one of the drivers is degraded from circular through linear.\n\nWe then provided a suitable photon-picture model that is able to explain the observed harmonic emission while retaining a parametric picture of harmonic generation which conserves spin angular momentum on a per-channel basis~-- and, indeed, while maintaining consistency with known results when applied to the lowest-order channel, which reduces to perturbative four-wave mixing. \n\nOur model, based essentially on arguments lowest-order perturbation theory by separating an elliptical driver into circular components and treating them separately, is surprisingly effective at predicting the dependence of the harmonic emission on the ellipticity of the driver. Moreover, it correctly matches the results of a numerical experiment, which in principle can also be experimentally realized, where the two circular components of an elliptical field are taken as separate and detuned independently\n\n\n\n\\subsubsection{Nondipole effects in HHG through noncollinear bicircular beams}\nFinally, in chapter~\\ref{chap:nondipole-HHG}, we turned to the generation of harmonics in fields that are particularly strong, or at a very long wavelength, or both, looking to extend the harmonic cutoff past the barrier posed by the magnetic field of the driving laser as the velocity of the continuum electron increases.\n\nHere we proposed a simple and flexible scheme for addressing the continuum electron's motion along the direction, by combining two counter-rotating circularly polarized fields of the same frequency in a non-collinear configuration to produce a field with a forwards ellipticity that acts in the same direction as the magnetic Lorentz force.\n\nWe then extended the existing beyond-dipole Strong-Field Approximation HHG formalism to deal with arbitrary beam configurations, showing that to do so one needs to use slightly more complex nondipole Volkov states, and related this to a nontrivial average force acting on charged particles across the focus.\n\nFinally, with this extended beyond-dipole SFA in hand, we showed that the field configuration can indeed help recover the harmonic emission from its exponential quenching at the hands of the magnetic Lorentz force, and, moreover, that it can be used at much lower intensities and wavelengths to produce even harmonics that can be used to demonstrate the presence of the effect, for the first time in HHG, using currently available laser sources.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n  ", "meta": {"hexsha": "6f146af50bb28daca4b881d62c8184c47ec5cd87", "size": 12064, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "10-Conclusions/Conclusions.tex", "max_stars_repo_name": "episanty/PhD-Thesis", "max_stars_repo_head_hexsha": "3347dfb59c11db5572a4139ee3b784ad56260e76", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2016-11-16T19:28:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T12:32:56.000Z", "max_issues_repo_path": "10-Conclusions/Conclusions.tex", "max_issues_repo_name": "episanty/PhD-Thesis", "max_issues_repo_head_hexsha": "3347dfb59c11db5572a4139ee3b784ad56260e76", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2017-02-22T19:26:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-31T16:38:58.000Z", "max_forks_repo_path": "10-Conclusions/Conclusions.tex", "max_forks_repo_name": "episanty/PhD-Thesis", "max_forks_repo_head_hexsha": "3347dfb59c11db5572a4139ee3b784ad56260e76", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-12-17T06:06:55.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-26T11:08:08.000Z", "avg_line_length": 84.9577464789, "max_line_length": 780, "alphanum_fraction": 0.8032990716, "num_tokens": 2654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.34129332163178366}}
{"text": "\\chapter{Astronomy}\n\n\\section{Reading sky map to find celestial objects}\n\n% https://en.wikipedia.org/wiki/Celestial_sphere\n\nCelestial sphere.\nThe sky looks as if it were projected to a spherical screen.\nIf a star is far enough, it will look as if it were fixed in the sky.\n\nYou find a star in the sky.\nYou write a letter to your friend.\nHow do you write where that star is?\nHow do you explain to him which direction he should look at?\n\nYou use the \\emph{equatorial coordinate system}.\n\n\\emph{Right ascension}, \\emph{declination}, and \\emph{epoch}.\n\nExample: Alpha Centauri A.\nRight ascension 14 h 39 m 35.06311 s.\nDeclination \\(-60\\deg\\) 50' 15.0992\".\nEpoch J2000.\n\n% https://en.wikipedia.org/wiki/Epoch_(astronomy)#Julian_years_and_J2000\nJ2000 is the Gregorian date 2000-01-01 12:00 TT (terrestrial time).\n\nStar chart, star map, sky map\n\n% https://en.wikipedia.org/wiki/Celestial_coordinate_system\n\nCelestial coordinate system\n\n% https://en.wikipedia.org/wiki/Star_chart\n\n% https://en.wikipedia.org/wiki/Celestial_coordinate_system\n\nEquatorial coordinate system\n\n% https://en.wikipedia.org/wiki/Alpha_Centauri\n\n\\section{Distance}\n\n% https://en.wikipedia.org/wiki/Parsec\n\n1 au (astronomical unit) is roughly the distance between the Sun and the Earth.\nIt is about 150 million km.\n\nParsec is a unit of length.\n\\( 648000/\\pi \\).\n1 pc is about 3.26 ly.\n\nA \\emph{light year} is the distance traveled by light in one year.\n\\emph{Light year} (ly) is a unit of \\emph{distance}, not time.\n1 au is about 6 light minutes.\n\n\\section{Objects}\n\nA \\emph{planet} is?\n\n% https://en.wikipedia.org/wiki/Stellar_evolution\nA \\emph{star} is a luminous sphere of plasma held together by its own gravity.\n(\"Star\", Wikipedia)\nEvery star begins from collapsing clouds of gas and dust.\nA \\emph{protostar} is ...\nA \\emph{main-sequence star} is ...\n\nA \\emph{solar system} is?\n\nA \\emph{galaxy} is?\n\nA \\emph{nebula} is?\n\nA \\emph{constellation} is?\n\nA \\emph{satellite} is?\n\nA \\emph{moon} is?\n\nA \\emph{comet} is?\n\nAn \\emph{asteroid} is?\n\nA \\emph{supernova} is?\n\nA \\emph{brown dwarf} is?\n\nA \\emph{white dwarf} is?\n\nA \\emph{black hole} is?\n\n\\section{Cosmology}\n\n\\section{Cosmogony}\n", "meta": {"hexsha": "b5fde2997c8b5ddc54c185c9be63fe0a54b93b87", "size": 2148, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "research/physics/astronomy.tex", "max_stars_repo_name": "edom/work", "max_stars_repo_head_hexsha": "df55868caa436efc631e145a43e833220b8da1d0", "max_stars_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "research/physics/astronomy.tex", "max_issues_repo_name": "edom/work", "max_issues_repo_head_hexsha": "df55868caa436efc631e145a43e833220b8da1d0", "max_issues_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-02T18:37:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T00:55:32.000Z", "max_forks_repo_path": "research/physics/astronomy.tex", "max_forks_repo_name": "edom/work", "max_forks_repo_head_hexsha": "df55868caa436efc631e145a43e833220b8da1d0", "max_forks_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-10-02T15:20:22.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T15:20:22.000Z", "avg_line_length": 22.6105263158, "max_line_length": 79, "alphanum_fraction": 0.7397579143, "num_tokens": 643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.341048057064018}}
{"text": "\\chapter{Actuator Disc Method}\n\n\\section{Coordinate Systems}\n\n\\subsection{Rotor Axis System}\n\nOrigin of the Rotor Axis System is coincident with the rotor hub center, the x-axis is positive in forward direction, the y-axis is positive right and z-axis is positive downward direction and it is coincident with the rotor shaft axis.\n\n\\begin{figure}[h!]\n  \\centering\n  \\includegraphics[width=110mm]{eps/coordinate_system_RAS.eps}\n  \\caption{Rotor Axis System}\n\\end{figure}\n\n\\subsection{Rotor-Wind Axis System}\n\nRotor-Wind Axis System is very much like Rotor Axis System, the only difference is that it is rotated about z-axis in such a manner that x-axis points directly into relative wind, so there is no lateral airspeed component.\n\n\\subsection{Control Axis System}\n\nFor most purposes, using the Rotor Axis System causes unnecessary complications. It is convenient to use no cyclic feathering axes system. \\cite{GessowMyers1985} Origin of the Control Axis System is coincident with the origin of the Rotor Axis System, but it is rotated by angles of the swashplate roll and pitch so there is no cyclic feathering in this coordinate system.\n\n\\begin{figure}[h!]\n  \\centering\n  \\includegraphics[width=120mm]{eps/rotor_planes.eps}\n  \\caption{Rotor reference planes}\n\\end{figure}\n\n\\subsection{Disc Axis System}\n\nOrigin of the Disc Axis System is coincident with the origin of the Rotor Axis System, but it is rotated by angles of the rotor cone roll and pitch in such a manner that z-axis is perpendicular to the tip path plane so there is no cyclic flapping in this coordinate system.\n\n\\subsection{Control-Wind Axis System}\n\nControl-Wind Axis System is very much like Control Axis System, the only difference is that it is rotated about z-axis in such a manner that x-axis points directly into relative wind, so there is no lateral airspeed component.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Assumptions}\n\nFollowing assumptions are made for the purpose of modeling helicopter rotor aerodynamics:\n\\begin{itemize}\n  \\item[---] forces and moments generated by the rotor are considered to be quasi-steady,\n  \\item[---] rotor lift force is a linear function of blade incidence angle and drag force is a quadratic function of lift, \\cite{Padfield2007}\n  \\item[---] rotor blades have 3 degrees of freedom movement,\n  \\item[---] inflow is uniformly distributed over rotor disc, \\cite{Padfield2007}\n  \\item[---] reversed flow effects are ignored,\n  \\item[---] airflow is considered to be quasi-steady and incompressible,\n  \\item[---] thrust is considered to be parallel to the z-axis of the Control Axis System and magnitude of the thrust is considered to be magnitude of the resulting rotor force. \\cite{GessowMyers1985}\n\\end{itemize}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Momentum Theory}\n\n\\subsection{Momentum Theory for Axial Flight}\n\nMass flow through the rotor disc, momentum change and change in kinetic energy are given by the following formulas. \\cite{Padfield2007}\n\\begin{align}\n  \\label{eq-aero-mass-flow}\n  \\dot m\n  &=\n  \\rho A_1 V_C = \\rho A_R \\left( V_C + V_i \\right)\n  =\n  \\rho A_{i \\infty} \\left( V_C + V_{i \\infty}  \\right) \\\\\n  \\label{eq-aero-thrust-1}\n  T\n  &=\n  \\dot m \\left( V_C + V_{i \\infty} \\right)\n  -\n  \\dot m V_C = \\dot m V_{ i \\infty } \\\\\n  T \\left( V_C + V_{ i \\infty } \\right)\n  &=\n  \\frac{1}{2} \\dot m \\left( V_C + V_{ i \\infty } \\right)^2\n  -\n  \\frac{1}{2} \\dot m V_C^2\n  =\n  \\frac{1}{2} \\dot m \\left( 2V_C V_{ i \\infty } + V_{ i \\infty }^2 \\right)\n\\end{align}\n\nWhere:\n\\begin{description}[align=right,labelwidth=3cm]\n  \\item [$A_1 = \\pi R_1^2$] [m\\textsuperscript{2}] control volume section area\n  \\item [$A_R = \\pi R^2$] [m\\textsuperscript{2}] rotor disc area\n  \\item [$A_{\\infty} = \\pi R_{\\infty}^2$] [m\\textsuperscript{2}] far wake slipstream section area\n  \\item [$\\dot m$] [kg/s] mass flow\n  \\item [$V_C$] [m/s] climb velocity\n  \\item [$V_i$] [m/s] induced velocity\n  \\item [$V_{i \\infty}$] [m/s] far wake induced velocity\n  \\item [$T$] [N] rotor thrust\n\\end{description}\n\n\\begin{figure}[h!]\n  \\centering\n  \\includegraphics[width=51mm]{eps/momentum_theory_axial.eps}\n  \\caption{Flow trough a rotor in axial flight}\n\\end{figure}\n\nFrom these relationships it can be deduced that induced velocity in the far wake is twice the rotor inflow. \\cite{Padfield2007}\n\\begin{equation}\n  \\label{eq-aero-indeced-vel}\n  V_{i \\infty} = 2 V_i\n\\end{equation}\n\nSubstituting equations (\\ref{eq-aero-mass-flow}) and (\\ref{eq-aero-indeced-vel}) into (\\ref{eq-aero-thrust-1}) rotor thrust is given as follows:\n\\begin{equation}\n  \\label{eq-aero-thrust-climb}\n  T = 2 \\rho A_R \\left( V_C + V_i \\right) V_i\n\\end{equation}\n\nIn hover flight, this equation can be expressed as:\n\\begin{equation}\n  \\label{eq-aero-thrust-hover}\n  T = 2 \\rho A_R V_{ih}^2\n\\end{equation}\n\nTransforming equations (\\ref{eq-aero-thrust-climb}) and (\\ref{eq-aero-thrust-hover}) gives:\n\\begin{align}\n  V_i    &= \\frac{T}{ 2 \\rho A_R \\left( V_C + V_i \\right) } \\\\\n  V_{ih} &= \\sqrt{ \\frac{T}{ 2 \\rho A_R } }\n\\end{align}\n\nWriting velocities in normalized form:\n\\begin{align}\n  \\label{eq-aero-lambda-i}\n  \\lambda_i    &= \\frac{ V_i }    { \\Omega_R R } \\\\\n  \\label{eq-aero-lambda-ih}\n  \\lambda_{ih} &= \\frac{ V_{ih} } { \\Omega_R R } \\\\\n  \\mu_C        &= \\frac{ V_C }    { \\Omega_R R }\n\\end{align}\n\nRotor thrust coefficient is:\n\\begin{equation}\n  \\label{eq-aero-thrust-coef}\n  C_T = \\frac{ T }{ \\rho A_R \\Omega_R^2 R^2 }\n\\end{equation}\n\nThen equations (\\ref{eq-aero-lambda-i}) and (\\ref{eq-aero-lambda-ih}) can be expressed as:\n\\begin{align}\n  \\lambda_i    &= \\frac{ C_T }{ 2 \\left( \\mu_C + \\lambda_i \\right) } \\\\\n  \\lambda_{ih} &= \\sqrt{ \\frac{ C_T }{ 2 } }\n\\end{align}\n\nCombining these equations gives:\n\\begin{equation}\n  \\lambda_{ih}^2 = \\lambda_i \\left( \\mu_C + \\lambda_i \\right)\n\\end{equation}\n\nThis equation can be transformed into following form:\n\\begin{equation}\n  \\label{eq-aero-lambda-i-2}\n  \\lambda_i\n  =\n  - \\frac{\\mu_C}{2}\n  +\n  \\sqrt{ \\left( \\frac{\\mu_C}{2} \\right)^2 + \\lambda_{ih}^2 }\n\\end{equation}\n\nFor descent velocity $V_D = - V_C$ formula (\\ref{eq-aero-lambda-i-2}) can be written as:\n\\begin{equation}\n  \\lambda_i\n  =\n  \\frac{\\mu_D}{2}\n  -\n  \\sqrt{ \\left( \\frac{\\mu_D}{2} \\right)^2 - \\lambda_{ih}^2 }\n\\end{equation}\n\nThis relationship is valid only in windmill brake state where the wake is fully established and the flow is upwards. \\cite{Padfield2007} It can be assumed that such a condition occurs when descent velocity is two times greater than induced velocity in hover. \\cite{Stepniewski1984}\n\nYoung’s approximation can be used to determine induced velocity outside range of momentum theory application. \\cite{Padfield2007}\n\\begin{align}\n  \\lambda_i\n  =\n  \\lambda_{ih} \\left( 1 + \\frac{\\mu_D}{\\lambda_{ih}} \\right)\n  &\\mathrm{~for~} 0 \\leq \\mu_D \\leq -1.5 \\lambda_{ih} \\\\\n  \\lambda_i\n  =\n  \\lambda_{ih} \\left( 7 - 3 \\frac{\\mu_D}{\\lambda_{ih}} \\right)\n  &\\mathrm{~for~} -1.5 \\lambda_{ih} < \\mu_D \\leq -2 \\lambda_{ih}\n\\end{align}\n\n\\subsection{Momentum Theory in Forward Flight}\n\nIn forward flight induced velocity in the far wake is twice the flow at the rotor. \\cite{Padfield2007} Expression for thrust is given as follows:\n\\begin{equation}\n  T = \\dot m 2 V_i = \\left( \\rho A_R V' \\right) 2 V_i\n\\end{equation}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=120mm]{eps/momentum_theory_forward.eps}\n  \\caption{Flow trough a rotor in forward flight}\n\\end{figure}\n\nTransforming this equation for induced velocity gives:\n\\begin{equation}\n  \\label{eq-aero-lambda-i-3}\n  V_i = \\frac{T}{ 2 \\rho A_R V' }\n\\end{equation}\n\nWhere $V'$ is the resultant velocity at the rotor.\n\\begin{equation}\n  \\label{eq-aero-vel-rotor}\n  V' = \\sqrt{\n    V^2 \\cos^2 \\alpha_R\n    + \\left( V \\sin \\alpha_R - V_i \\right)^2\n  }\n\\end{equation}\n\nWriting velocities in normalized form:\n\\begin{align}\n  \\label{eq-aero-lambda-i-4}\n  \\lambda_i &= \\frac{V_i}    { \\Omega_R R } \\\\\n  \\label{eq-aero-mu-x}\n  \\mu_X     &= \\frac{u_{rw}} { \\Omega_R R } \\\\\n  \\label{eq-aero-mu-z}\n  \\mu_Z     &= \\frac{w_{rw}} { \\Omega_R R }\n\\end{align}\n\nWhere:\n\\begin{align}\n  u_{rw} &= V \\cos \\alpha_R \\\\\n  w_{rw} &= V \\sin \\alpha_R\n\\end{align}\n\nSubstituting equations (\\ref{eq-aero-lambda-i-4}), (\\ref{eq-aero-mu-x}), (\\ref{eq-aero-mu-z}) and (\\ref{eq-aero-vel-rotor}) into (\\ref{eq-aero-lambda-i-3}) formula for the normalized induced velocity can be expressed as follows.\n\\begin{equation}\n  \\label{eq-aero-lambda-i-5}\n  \\lambda_i\n  =\n  \\frac{C_T}{ 2 \\sqrt{ \\mu_X^2 + \\left( \\mu_Z - \\lambda_i \\right)^2 } }\n\\end{equation}\n\nIn high speed flight summing helicopter translational velocity and velocity due to rotor shaft rotation causes strong non-uniformities of rotor induced velocity. Glauert’s model is used to describe this phenomena. \\cite{Padfield2007, Bramwell2001}\n\\begin{equation}\n  \\lambda_i \\left( r, \\Psi \\right)\n  =\n  \\lambda_{i0} + \\frac{r}{R} \\lambda_{1c} \\cos \\Psi\n\\end{equation}\n\nWhere:\n\\begin{align}\n  \\lambda_{1c} &= \\lambda_{i0} \\tan \\left( \\frac{\\chi}{2} \\right)\n  \\mathrm{~for~} \\chi < \\frac{\\pi}{2} \\\\\n  \\lambda_{1c} &= \\lambda_{i0} \\cot \\left( \\frac{\\chi}{2} \\right)\n  \\mathrm{~for~} \\chi > \\frac{\\pi}{2}\n\\end{align}\n\nThe wake angle is given by the following formula:\n\\begin{equation}\n  \\chi = \\arctan \\left( \\frac{\\mu}{ \\lambda_{i0} - \\mu_Z } \\right)\n\\end{equation}\n\nWhere $\\lambda_{i0}$ is given by formula (\\ref{eq-aero-lambda-i-5}).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Forces Acting on the Blade Segment}\n\nDetermining forces and moments acting on segment of the blade is made, assuming that blade is composed of aerodynamically independent, narrow strips of elements. \\cite{Stepniewski1984} High aspect ratio of the blade justifies usage of two-dimensional flow, while lift loss at the blade tip and root can be accounted by using tip-loss factor. \\cite{Padfield2007, Stepniewski1984, Bramwell2001}\n\nControl-Wind Axis System is used to determine forces and moments generated by the rotor, such computed forces and moments are the transformed to the Body Axis System.\n\n\\begin{figure}[h!]\n  \\centering\n  \\includegraphics[width=120mm]{eps/blade_element_theory_01.eps}\n  \\caption{Rotor blade element}\n\\end{figure}\n\nLift and drag acting on a blade section is given by the following expressions:\n\\begin{align}\n  \\label{eq-aero-blade-section-lift}\n  dL &= \\frac{1}{2} \\rho U^2 \\left( r, \\Psi \\right) C_L c_b dr \\\\\n  \\label{eq-aero-blade-section-drag}\n  dD &= \\frac{1}{2} \\rho U^2 \\left( r, \\Psi \\right) C_D c_b dr\n\\end{align}\n\nLift and drag coefficients are given as follows: \\cite{Padfield2007}\n\\begin{align}\n  \\label{eq-aero-blade-section-lift-coef}\n  C_L &= a \\alpha_{BE} \\left( r, \\Psi \\right) \\\\\n  C_D &= \\delta_0 + \\delta_2 C_T^2\n\\end{align}\n\nBlade section angle of attack is given by the following formula.\n\\begin{equation}\n  \\alpha_{BE} \\left( r , \\Psi \\right) = \\theta + \\phi \\left( r , \\Psi \\right) \n\\end{equation}\n\nWhere:\n\\begin{equation}\n  \\phi \\left( r , \\Psi \\right)\n  =\n  \\arctan \\frac{ U_P \\left( r, \\Psi \\right) }{ U_T \\left( r, \\Psi \\right) }\n\\end{equation}\n\nLinear velocity of the rotor hub and angular velocity expressed Rotor Axis System are given by the following formulas: \\cite{Stepniewski1984, Bramwell2001}\n\\begin{align}\n  {\\vec V}_{RH,r}\n  &=\n  {\\boldsymbol T} \\left( \\varepsilon \\right)\n  \\left(\n    {\\vec V}_{O,b} + {\\vec \\omega}_b \\times {\\vec r}_{RH,b}\n  \\right) \\\\\n  {\\vec \\omega}_r\n  &=\n  {\\boldsymbol T} \\left( \\varepsilon \\right)\n  {\\vec \\omega}_b\n\\end{align}\n\nRotattion matrix ${\\boldsymbol T} \\left( \\varepsilon \\right)$ is given as:\n\\begin{equation}\n  {\\boldsymbol T} \\left( \\varepsilon \\right)\n  =\n  \\left[\n    \\begin{matrix}\n       \\cos \\varepsilon & 0 & \\sin \\varepsilon \\\\\n                        0 & 1 &              0 \\\\\n      -\\sin \\varepsilon & 0 & \\cos \\varepsilon \\\\\n    \\end{matrix}\n  \\right]\n\\end{equation}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=100mm]{eps/blade_element_theory_02.eps}\n  \\caption{Velocity components at the blade element}\n\\end{figure}\n\nFollowing formulas can be used to transform this values to Control Axis System:\n\\begin{align}\n  {\\vec V}_{RH,c} \n  &=\n  {\\boldsymbol T} \\left( \\theta_{1c}, \\theta_{1s} \\right)\n  {\\vec V}_{RH,r} \\\\\n  {\\vec \\omega}_c\n  &=\n  {\\boldsymbol T} \\left( \\theta_{1c}, \\theta_{1s} \\right)\n  {\\vec \\omega}_r\n\\end{align}\n\nWhere rotation matrices are:\n\n--- for counterclockwise direction of rotor:\n\\begin{equation}\n  {\\boldsymbol T} \\left( \\theta_{1c}, \\theta_{1s} \\right)\n  =\n  \\left[\n    \\begin{matrix}\n      1 &                0 &                 0 \\\\\n      0 & \\cos \\theta_{1c} & -\\sin \\theta_{1c} \\\\\n      0 & \\sin \\theta_{1c} &  \\cos \\theta_{1c} \\\\\n    \\end{matrix}\n  \\right]\n  \\left[\n    \\begin{matrix}\n      \\cos \\theta_{1s} & 0 & -\\sin \\theta_{1s} \\\\\n                    0 & 1 &                 0 \\\\\n      \\sin \\theta_{1s} & 0 &  \\cos \\theta_{1s} \\\\\n    \\end{matrix}\n  \\right]\n\\end{equation}\n\n--- for clockwise direction of rotor:\n\\begin{equation}\n  {\\boldsymbol T} \\left( \\theta_{1c}, \\theta_{1s} \\right)\n  =\n  \\left[\n    \\begin{matrix}\n      1 &                 0 &                0 \\\\\n      0 &  \\cos \\theta_{1c} & \\sin \\theta_{1c} \\\\\n      0 & -\\sin \\theta_{1c} & \\cos \\theta_{1c} \\\\\n    \\end{matrix}\n  \\right]\n  \\left[\n    \\begin{matrix}\n      \\cos \\theta_{1s} & 0 & -\\sin \\theta_{1s} \\\\\n                    0 & 1 &                 0 \\\\\n      \\sin \\theta_{1s} & 0 &  \\cos \\theta_{1s} \\\\\n    \\end{matrix}\n  \\right]\n\\end{equation}\n\nFollowing formulas can be used to transform linear and angular velocity vector to Control-Wind Axis System:\n\\begin{align}\n  {\\vec V}_{RH,cw}\n  &=\n  {\\boldsymbol T} \\left( \\beta \\right) {\\vec V}_{RH,c} \\\\\n  {\\vec \\omega}_{cw}\n  &=\n  {\\boldsymbol T} \\left( \\beta \\right) {\\vec \\omega}_c\n\\end{align}\n\nRotation matrix ${\\boldsymbol T} \\left( \\beta \\right)$ is given by formula (\\ref{eq-aero-matrix-beta}).\n\nAssuming that flapping angle is positive upwards and writing velocity components as:\n\\begin{align}\n  {\\vec V}_{RH,cw} &= \\left[ u_{cw}, 0, w_{cw} \\right]^T \\\\\n  {\\vec \\omega}_{cw} &= \\left[ p_{cw}, q_{cw}, 0 \\right]^T\n\\end{align}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=120mm]{eps/blade_element_velocity.eps}\n  \\caption{Air velocities at the blade element}\n\\end{figure}\n\nAir velocity at the blade segment is:\n\n--- for counterclockwise direction of rotor:\n\\begin{gather}\n  U_T = \\Omega_R r \\cos \\beta + u_{cw} \\sin \\Psi \\\\\n  \\begin{multlined}[0.88\\textwidth]\n    U_P =\n    w_{cw} \\cos \\beta - V_i \\cos \\beta\n    - \\dot \\beta r - u_{cw} \\sin \\beta \\cos \\Psi \\\\\n    + p_{cw} r \\sin \\Psi + q_{cw} r \\cos \\Psi\n  \\end{multlined}\n\\end{gather}\n\n--- for clockwise direction of rotor:\n\\begin{gather}\n  U_T = \\Omega_R r \\cos \\beta + u_{cw} \\sin \\Psi \\\\\n  \\begin{multlined}[0.88\\textwidth]\n    U_P =\n    w_{cw} \\cos \\beta - V_i \\cos \\beta\n    - \\dot \\beta r - u_{cw} \\sin \\beta \\cos \\Psi \\\\\n    - p_{cw} r \\sin \\Psi + q_{cw} r \\cos \\Psi\n  \\end{multlined}\n\\end{gather}\n\nAssuming that for small angles:\n\\begin{align}\n  \\label{eq-aero-sin-beta-approx}\n  \\sin \\beta \\approx \\beta \\\\\n  \\label{eq-aero-cos-beta-approx}\n  \\cos \\beta \\approx 1\n\\end{align}\n\nThis expressions can be simplified to:\n\n--- for counterclockwise direction of rotor:\n\\begin{align}\n  U_T &= \\Omega_R r + u_{cw} \\sin \\Psi \\\\\n  U_P &=\n  w_{cw} - V_i - \\dot \\beta r - u_{cw} \\beta \\cos \\Psi\n  + p_{cw} r \\sin \\Psi + q_{cw} r \\cos \\Psi\n\\end{align}\n\n--- for clockwise direction of rotor:\n  \\begin{align}\n    U_T &= \\Omega_R r + u_{cw} \\sin \\Psi \\\\\n    U_P &=\n    w_{cw} - V_i - \\dot \\beta r - u_{cw} \\beta \\cos \\Psi\n    - p_{cw} r \\sin \\Psi + q_{cw} r \\cos \\Psi\n  \\end{align}\n\nUsing normalized velocities:\n\n\\begin{align}\n  \\mu     &= \\frac{u_{cw}}{\\Omega_R R} \\\\\n  \\lambda &= \\frac{w_{cw} - V_i}{\\Omega_R R}\n\\end{align}\n\nExpressions for air velocity at the blade segment can be written in the following form:\n\n--- for counterclockwise direction of rotor:\n\\begin{align}\n  U_T &= \\Omega_R r + \\mu \\Omega_R R \\sin \\Psi \\\\\n  U_P &=\n  \\lambda \\Omega_R R - \\dot \\beta r - \\mu \\Omega_R R \\beta \\cos \\Psi\n  + p_{cw} r \\sin \\Psi + q_{cw} r \\cos \\Psi\n\\end{align}\n\n--- for clockwise direction of rotor:\n\\begin{align}\n  U_T &= \\Omega_R r + \\mu \\Omega_R R \\sin \\Psi \\\\\n  U_P &=\n  \\lambda \\Omega_R R - \\dot \\beta r - \\mu \\Omega_R R \\beta \\cos \\Psi\n  - p_{cw} r \\sin \\Psi + q_{cw} r \\cos \\Psi\n\\end{align}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Rotor Thrust}\n\nAssuming that for small angles:\n\\begin{align}\n  \\label{eq-aero-approx-phi}\n  \\phi = \\arctan &\\frac{U_P}{U_T} \\approx \\frac{U_P}{U_T} \\\\\n  \\label{eq-aero-approx-u}\n  U  &\\approx U_T \\\\\n  \\label{eq-aero-approx-dt}\n  dT &\\approx dL\n\\end{align}\n\nExpression for the blade segment angle of attack is given as follows:\n\\begin{equation}\n  \\alpha_{BE} = \\theta + \\frac{U_P}{U_T}\n\\end{equation}\n\nThen expression (\\ref{eq-aero-blade-section-lift-coef}) can be written as. \\cite{GessowMyers1985}\n\\begin{equation}\n  \\label{eq-aero-rotor-list-coef}\n  C_L = a \\left( \\theta + \\frac{U_P}{U_T} \\right)\n\\end{equation}\n\nSubstituting expression (\\ref{eq-aero-blade-section-lift}) and taking into account simplifications (\\ref{eq-aero-approx-phi}), (\\ref{eq-aero-approx-u}) and (\\ref{eq-aero-approx-dt}) then rotor thrust is given by the following formula.\n\\begin{equation}\n  dT\n  \\approx\n  \\frac{1}{2} \\rho a c_b U_T^2 \\left( \\theta + \\frac{U_P}{U_T} \\right) dr\n\\end{equation}\n\nTransforming this relationship gives:\n\\begin{equation}\n  \\label{eq-aero-blade-section-thrust}\n  dT\n  \\approx\n  \\frac{1}{2} \\rho a c_b\n  \\left( \\theta U_T^2 + U_P U_T \\right) dr\n\\end{equation}\n\nTotal thrust generated by the rotor of $n_b$ blades can be determined by integrating differential equation (\\ref{eq-aero-blade-section-thrust}) first with respect to the azimuth then along the blade span. \\cite{GessowMyers1985} Total thrust is given as follows:\n\\begin{equation}\n  \\label{eq-aero-thrust-2}\n  T = \\frac{ n_b }{ 2 \\pi } \\int_{0}^{2 \\pi} \\int_{0}^{BR}\n  \\frac{dT}{dr} dr d\\Psi\n\\end{equation}\n\nWhere $B$ is a tip loss factor.\n\nSubstituting (\\ref{eq-aero-blade-section-thrust}) into (\\ref{eq-aero-thrust-2}) gives:\n\\begin{equation}\n  T = \\frac{1}{2} \\rho a c_b n_b\n  \\left(\n  \\theta \\frac{1}{2 \\pi}\n  \\int_{0}^{2\\pi} \\int_{0}^{BR} \\frac{U_T^2}{dr} dr d\\Psi\n  +\n  \\frac{1}{2\\pi} \\int_{0}^{2\\pi} \\int_{0}^{BR} U_P U_T dr d\\Psi\n  \\right)\n\\end{equation}\n\nNeglecting helicopter angular velocity expressions for $U_T^2$ and $U_P U_T$ can be written as:\n\\begin{gather}\n  \\label{eq-aero-u-t-sq}\n  U_T^2 =\n  r^2 \\Omega_R^2 + 2 \\Omega_R^2 R r \\mu \\sin \\Psi\n  + \\mu^2 R^2 \\Omega_R^2 \\sin^2 \\Psi \\\\\n  \\label{eq-aero-u-p-u-t}\n  \\begin{multlined}[0.88\\textwidth]\n  U_P U_T =\n  \\lambda \\Omega_R^2 R r - \\dot \\beta \\Omega_R r^2\n  - \\beta \\mu \\Omega_R^2 R r \\cos \\Psi \\\\\n  + \\lambda \\mu \\Omega_R^2 R^2 \\sin \\Psi\n  - \\dot \\beta \\mu \\Omega_R R r \\sin \\Psi\n  - \\beta \\mu^2 \\Omega_R^2 R^2 \\sin \\Psi \\cos \\Psi\n  \\end{multlined}\n\\end{gather}\n\nExpression for the blade flapping angle can be written as follows: \\cite{GessowMyers1985, Padfield2007, NASA-TT-F-494}\n\\begin{equation}\n  \\label{eq-aero-blade-flapping-angle}\n  \\beta \\left( \\Psi \\right) = \n  \\beta_0 + \\beta_{1c} \\cos \\Psi + \\beta_{1s} \\sin \\Psi\n\\end{equation}\n\nAssuming constant rotor revolution speed, blade flapping angle derivatives with respect to time can be written as derivatives with respect to the azimuth. \\cite{GessowMyers1985}\n\\begin{gather}\n  \\dot \\beta = \\frac{d\\beta}{dt}\n  = \\frac{d\\beta}{d\\Psi} \\frac{d\\Psi}{dt} =\n  \\bar \\beta \\Omega_R =\n  \\Omega_R\n  \\left( \\beta_{1s} \\cos \\Psi - \\beta_{1c} \\sin \\Psi \\right) \\\\\n  \\ddot \\beta = \\frac{d^2\\beta}{dt^2}\n  = \\frac{d^2\\beta}{d\\Psi^2} \\left( \\frac{d\\Psi}{dt} \\right)^2 = \n  \\bar{\\bar \\beta} \\Omega_R^2\n  =\n  -\\Omega_R^2\n  \\left( \\beta_{1c} \\cos \\Psi + \\beta_{1s} \\sin \\Psi \\right)\n\\end{gather}\n\nThen expressions for $U_T^2$ and $U_P U_T$ can be written as:\n\\begin{gather}\n  U_T^2 = r^2 \\Omega_R^2 + 2 \\Omega_R^2 R r \\mu \\sin \\Psi\n  + \\mu^2 R^2 \\Omega_R^2 \\sin^2 \\Psi \\\\\n  \\begin{multlined}[0.88\\textwidth]\n    U_P U_T = \\lambda \\Omega_R^2 R r\n    - \\beta_{1s} \\Omega_R^2 r^2 \\cos \\Psi\n    + \\beta_{1c} \\Omega_R^2 r^2 \\sin \\Psi \\\\\n    - \\beta \\mu \\Omega_R^2 R r \\cos \\Psi\n    + \\lambda \\mu \\Omega_R^2 R^2 \\sin \\Psi\n    - \\beta_{1s} \\mu \\Omega_R^2 R r \\sin \\Psi \\cos \\Psi \\\\\n    + \\beta_{1c} \\mu \\Omega_R^2 R r \\sin^2 \\Psi\n    - \\beta \\mu^2 \\Omega_R^2 R^2 \\sin \\Psi \\cos \\Psi\n  \\end{multlined}\n\\end{gather}\n\nKnowing that: \\cite{GessowMyers1985}\n\\begin{gather}\n  \\frac{1}{2\\pi} \\int_{0}^{2\\pi} \\sin \\Psi d\\Psi =\n  \\frac{1}{2\\pi} \\int_{0}^{2\\pi} \\cos \\Psi d\\Psi = 0 \\\\\n  \\frac{1}{2\\pi} \\int_{0}^{2\\pi} \\sin^2 \\Psi d\\Psi =\n  \\frac{1}{2\\pi} \\int_{0}^{2\\pi} \\cos^2 \\Psi d\\Psi = \\frac{1}{2} \\\\\n  \\frac{1}{2\\pi} \\int_{0}^{2\\pi} \\sin \\Psi \\cos \\Psi d\\Psi = 0\n\\end{gather}\n\nRotor thrust can be written as:\n\\begin{equation}\n  T = \\frac{1}{2} \\rho a c_b n_b \\Omega_R^2 R^3 B\n  \\left[\n    \\frac{\\lambda B}{2} \n    +\n    \\frac{\\theta}{3} \\left( B^2 + \\frac{3}{2} \\mu^2 \\right)\n    +\n    \\frac{\\beta_{1c} B}{4} \\mu\n  \\right]\n\\end{equation}\n\nUsing expression (\\ref{eq-aero-thrust-coef}) rotor thrust coefficient is given by the following formula:\n\\begin{equation}\n  C_T = \\frac{1}{2} a s B\n  \\left[\n    \\frac{\\lambda B}{2}\n    +\n    \\frac{\\theta}{3} \\left( B^2 + \\frac{3}{2} \\mu^2 \\right)\n    +\n    \\frac{\\beta_{1c} B}{4} \\mu\n  \\right]\n\\end{equation}\n\nWhere $s$ is rotor solidity.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Rotor H Force}\n\n%TODO\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Rotor Y Force}\n\n%TODO\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Rotor Torque}\n\nThe torque on a blade element is given by the following formula. \\cite{GessowMyers1985, Bramwell2001}\n\\begin{equation}\n  \\label{eq-aero-blade-section-torque}\n  dQ = r \\left( dD \\cos \\phi - dL \\sin \\phi \\right) dr\n\\end{equation}\n\nAssuming that for small angles:\n\\begin{align}\n  \\sin \\phi &\\approx \\phi \\\\\n  \\cos \\phi &\\approx 1\n\\end{align}\n\nAnd assuming that drag coefficient is constant along blade span, expression (\\ref{eq-aero-blade-section-torque}) can be written as: \\cite{GessowMyers1985, Bramwell2001}\n\\begin{equation}\n  dQ =\n  \\frac{1}{2} \\rho U_T^2 C_D c_b r dr -\n  \\frac{1}{2} \\rho U_T^2 C_L c_b r \\phi dr\n\\end{equation}\n\nTorque due to the profile drag can be expressed as: \\cite{Bramwell2001}\n\\begin{equation}\n  Q_p = \\frac{n_b}{2\\pi}\n  \\int_{0}^{R} \\int_{0}^{2\\pi} \\frac{1}{2} \\rho U_T^2 C_D c_b r d \\Psi dr\n\\end{equation}\n\nSubstituting (\\ref{eq-aero-u-t-sq}) and integrating this equation first with respect to the azimuth then along the blade span gives:\n\\begin{equation}\n  Q_p = \\frac{1}{2} \\rho n_b c_b \\Omega_R^2 R^4 C_D\n  \\left( \\frac{1}{4} + \\frac{1}{4} \\mu^2 \\right)\n\\end{equation}\n\nInduced torque is given by the following formula: \\cite{Bramwell2001}\n\\begin{equation}\n  Q_i = \\frac{n_b}{2\\pi} \\int_{0}^{R} \\int_{0}^{2\\pi}\n  \\frac{1}{2} \\rho U_T^2 C_L c_b r \\phi d \\Psi dr\n\\end{equation}\n\nSubstituting (\\ref{eq-aero-approx-phi}) and (\\ref{eq-aero-rotor-list-coef}) gives:\n\\begin{equation}\n  \\label{eq-aero-q-i}\n  Q_i = \\frac{n_b}{2\\pi} \\frac{1}{2} \\rho a c_b\n  \\int_{0}^{R} \\int_{0}^{2\\pi}\n  \\left( \\theta U_P U_T r + U_P^2 r \\right) d \\Psi dr\n\\end{equation}\n\nNeglecting helicopter angular velocity expressions for $U_P^2$ can be written as:\n\\begin{multline}\n  \\label{eq-aero-u-p-sq}\n  U_P^2 = \\dot \\beta^2 r^2\n  + 2 \\beta \\dot \\beta \\mu \\Omega_R R r \\cos \\Psi\n  - 2 \\dot \\beta \\lambda \\Omega_R R r \\\\\n  + \\beta^2 \\mu^2 \\Omega_R^2 R^2 \\cos^2 \\Psi\n  - 2 \\beta \\lambda \\mu \\Omega_R^2 R^2 \\cos \\Psi\n  + \\lambda^2 \\Omega_R^2 R^2\n\\end{multline}\n\nSubstituting (\\ref{eq-aero-u-p-u-t}) and (\\ref{eq-aero-u-p-sq}) into (\\ref{eq-aero-q-i}) and integrating equation (\\ref{eq-aero-q-i}) first with respect to the azimuth then along the blade span gives:\n\\begin{multline}\nQ_i = \\frac{1}{2} \\rho a c_b n_b \\Omega_R^2 R^4\n\\left[\n    \\frac{1}{3} \\lambda \\theta\n  + \\frac{1}{2} \\lambda^2\n  - \\frac{1}{8} \\left( \\beta_{1c}^2 + \\beta_{1s}^2 \\right)\n  \\right.\n  \\\\\n  \\left.\n  + \\frac{1}{2} \\mu^2\n  \\left(\n    \\frac{\\beta_0^2}{2}\n    - \\frac{3}{8} \\beta_{1c}^2\n    - \\frac{1}{8} \\beta_{1s}^2\n  \\right)\n  - \\frac{1}{2} \\mu \\lambda \\beta_{1c}\n  + \\frac{1}{3} \\mu \\beta_0 \\beta_{1s}\n\\right]\n\\end{multline}\n\nThe total rotor torque is given as follows: \\cite{Bramwell2001, NASA-TT-F-494}\n\\begin{gather}\n  Q = Q_p - Q_i \\\\\n  \\begin{multlined}[0.88\\textwidth]\n    Q = \\frac{1}{2} \\rho a c_b n_b \\Omega_R^2 R^4\n    \\left[\n      \\frac{C_D}{4a} \\left( 1 + \\mu^2 \\right)\n      - \\frac{1}{3} \\lambda \\theta\n      - \\frac{1}{2} \\lambda^2\n      + \\frac{1}{8} \\left( \\beta_{1c}^2 + \\beta_{1s}^2 \\right)\n      \\right.\n      \\\\\n      \\left.\n      - \\frac{1}{2} \\mu^2\n      \\left(\n        \\frac{\\beta_0^2}{2}\n        - \\frac{3}{8} \\beta_{1c}^2\n        - \\frac{1}{8} \\beta_{1s}^2\n      \\right)\n      + \\frac{1}{2} \\mu \\lambda \\beta_{1c}\n      - \\frac{1}{3} \\mu \\beta_0 \\beta_{1s}\n    \\right]\n  \\end{multlined}\n\\end{gather}\n\nRotor torque coefficient can be written as:\n\\begin{multline}\n  C_Q = \\frac{1}{2} a s\n  \\left[\n    \\frac{C_D}{4a} \\left( 1 + \\mu^2 \\right)\n    - \\frac{1}{3} \\lambda \\theta\n    - \\frac{1}{2} \\lambda^2\n    + \\frac{1}{8} \\left( \\beta_{1c}^2 + \\beta_{1s}^2 \\right)\n    \\right.\n    \\\\\n    \\left.\n    - \\frac{1}{2} \\mu^2\n    \\left(\n      \\frac{\\beta_0^2}{2}\n      - \\frac{3}{8} \\beta_{1c}^2\n      - \\frac{1}{8} \\beta_{1s}^2\n    \\right)\n    + \\frac{1}{2} \\mu \\lambda \\beta_{1c}\n    - \\frac{1}{3} \\mu \\beta_0 \\beta_{1s}\n  \\right]\n\\end{multline}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Flapping Coefficients}\n\nExpressions for blades flapping coefficients can be derived from the equation of moments equilibrium about flapping hinge using method described in \\cite{NASA-TT-F-494}.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=100mm]{eps/blade_element_moments.eps}\n  \\caption{Forces acting on the blade element}\n\\end{figure}\n\n\\begin{minipage}{\\textwidth}\n  Moments equilibrium about flapping hinge can be written as follows: \\cite{GessowMyers1985}\n  \\begin{equation}\n    \\label{eq-aero-blade-moments-equilibrium}\n    M_I + M_{CF} + M_C + M_T + M_W = 0\n  \\end{equation}\n\n  Where:\n  \\begin{description}[align=right,labelwidth=1.5cm]\n    \\item [$M_I$]    [N$\\cdot$m] moment due to inertia forces of flapping\n    \\item [$M_{CF}$] [N$\\cdot$m] moment due to centrifugal force\n    \\item [$M_C$]    [N$\\cdot$m] moment due to Coriolis force\n    \\item [$M_T$]    [N$\\cdot$m] moment due to thrust\n    \\item [$M_W$]    [N$\\cdot$m] moment due to weight\n  \\end{description}\n\\end{minipage}\n\n\\subsection{Moments of Inertia Forces}\n\nAssuming that rotor revolution speed is constant, helicopter angular velocities are constant and rotor blades are able to move about flapping hinge axis while neglecting helicopter yaw motion and blades pitching and lagging motion then centrifugal force can be written as:\n\\begin{equation}\n  dF_{CF} = m_b \\Omega_R^2 r dr\n\\end{equation}\n\nComponent of the Coriolis force laying on the flapping plane is given:\n\n--- for counterclockwise direction of rotor:\n\\begin{equation}\n  dF_C =\n    2 m_b p_{cw} \\Omega_R r \\cos \\Psi dr\n  - 2 m_b q_{cw} \\Omega_R r \\sin \\Psi dr\n\\end{equation}\n\n--- for clockwise direction of rotor:\n\\begin{equation}\n  dF_C =\n  - 2 m_b p_{cw} \\Omega_R r \\cos \\Psi dr\n  - 2 m_b q_{cw} \\Omega_R r \\sin \\Psi dr\n\\end{equation}\n\nMoment of inertia forces of flapping is given by the following formula:\n\\begin{equation}\n  M_I = - \\ddot \\beta \\int_{0}^{R} m_b r^2 dr\n\\end{equation}\n\nAssuming that rotor blades are homogeneous rods blade first moment of mass and moment of inertia can be written as: \\cite{NASA-TT-F-494}\n\\begin{align}\n  \\label{eq-aero-j-b}\n  I_b &\\approx \\int_{0}^{R} m_b r^2 dr \\\\\n  \\label{eq-aero-s-b}\n  S_b &\\approx \\int_{0}^{R} m_b r dr\n\\end{align}\n\nHence:\n\\begin{equation}\n  M_I = - \\ddot \\beta I_b\n\\end{equation}\n\nTaking into account (\\ref{eq-aero-sin-beta-approx}) and (\\ref{eq-aero-cos-beta-approx}) moment of centrifugal forces is:\n\\begin{equation}\n  \\label{eq-aero-m-cf}\n  M_{CF} =\n  - \\int_{0}^{R} \\beta m_b \\Omega_R^2 r^2 dr =\n  - \\Omega_R^2 \\beta \\int_{0}^{R} m_b r^2 dr\n\\end{equation}\n\nSubstituting (\\ref{eq-aero-j-b}) into (\\ref{eq-aero-m-cf}) gives:\n\\begin{equation}\n  M_{CF} = - \\Omega_R^2 \\beta I_b\n\\end{equation}\n\nMoment of Coriolis forces can be writes as:\n\n--- for counterclockwise direction of rotor:\n\\begin{multline}\n  M_C =\n    2 \\int_{0}^{R} m_b p_{cw} \\Omega_R r^2 \\cos \\Psi dr\n  - 2 \\int_{0}^{R} m_b q_{cw} \\Omega_R r^2 \\sin \\Psi dr\n  = \\\\ =\n  2 p_{cw} \\Omega_R I_b \\cos \\Psi - 2 q_{cw} \\Omega_R I_b \\sin \\Psi\n\\end{multline}\n\n--- for clockwise direction of rotor:\n\\begin{multline}\n  M_C =\n  - 2 \\int_{0}^{R} m_b p_{cw} \\Omega_R r^2 \\cos \\Psi dr\n  - 2 \\int_{0}^{R} m_b q_{cw} \\Omega_R r^2 \\sin \\Psi dr\n  = \\\\ =\n  -2 p_{cw} \\Omega_R I_b \\cos \\Psi - 2 q_{cw} \\Omega_R I_b \\sin \\Psi\n\\end{multline}\n\nUsing approximation (\\ref{eq-aero-s-b}) moment due to weight can expressed as:\n\\begin{equation}\n  M_W = -g \\int_{0}^{R} m_b r dr = -g S_b\n\\end{equation}\n\n\\subsection{Moment of Thrust}\n\nUsing equation (\\ref{eq-aero-blade-section-thrust}) expression for moment of thrust about flapping hinge can be written as follows:\n\\begin{equation}\n  M_T =\n  \\int_{0}^{BR} dT r = \n  \\frac{1}{2} \\rho a c_b\n  \\int_{0}^{BR} \\left( \\theta U_T^2 + U_P U_T \\right) dr\n\\end{equation}\n\n\\subsection{Equilibrium of Moments about Flapping Hinge}\n\nSubstituting into (\\ref{eq-aero-blade-moments-equilibrium}) expressions for moments of thrust, weight, inertia, centrifugal and Coriolis forces moments equilibrium equation is given as:\n\n--- for counterclockwise direction of rotor:\n\\begin{gather}\n  \\begin{multlined}[0.88\\textwidth]\n    \\int_{0}^{BR} dT r\n    - \\ddot \\beta I_b\n    - \\beta \\Omega_R^2 I_b\n    + 2 p_{cw} \\Omega_R I_b \\cos \\Psi \\\\\n    - 2 q_{cw} \\Omega_R I_b \\sin \\Psi\n    - g S_b\n    = 0\n  \\end{multlined}\n  \\\\\n  \\begin{multlined}[0.88\\textwidth]\n    \\label{eq-aero-equilibrium-blade-moments-ccw-1}\n    - I_b \\ddot \\beta\n    - I_b \\beta \\Omega_R^2\n    + \\int_{0}^{BR} dT r\n    = 2 I_b q_{cw} \\Omega_R \\sin \\Psi \\\\\n    - 2 I_b p_{cw} \\Omega_R \\cos \\Psi\n    + g S_b\n  \\end{multlined}\n\\end{gather}\n  \n--- for clockwise direction of rotor:\n\\begin{gather}\n  \\begin{multlined}[0.88\\textwidth]\n    \\int_{0}^{BR} dT r\n    - \\ddot \\beta I_b\n    - \\beta \\Omega_R^2 I_b\n    - 2 p_{cw} \\Omega_R I_b \\cos \\Psi \\\\\n    - 2 q_{cw} \\Omega_R I_b \\sin \\Psi\n    - g S_b\n    = 0\n  \\end{multlined}\n  \\\\\n  \\begin{multlined}[0.88\\textwidth]\n    \\label{eq-aero-equilibrium-blade-moments-cw-1}\n    - I_b \\ddot \\beta\n    - I_b \\beta \\Omega_R^2\n    + \\int_{0}^{BR} dT r\n    = 2 I_b q_{cw} \\Omega_R \\sin \\Psi \\\\\n    + 2 I_b p_{cw} \\Omega_R \\cos \\Psi\n    + g S_b\n  \\end{multlined}\n\\end{gather}\n\nDividing both sides of equations (\\ref{eq-aero-equilibrium-blade-moments-ccw-1}) and (\\ref{eq-aero-equilibrium-blade-moments-cw-1}) by $I_b \\Omega_R^2$ gives:\n\\begin{gather}\n  \\label{eq-aero-equilibrium-blade-moments-ccw-2}\n  \\bar{\\bar \\beta} + \\beta\n  = \\frac{1}{ I_b \\Omega_R^2 } \\int_{0}^{BR} dT r\n  - 2 \\frac{q_{cw}}{\\Omega_R} \\sin \\Psi\n  + 2 \\frac{p_{cw}}{\\Omega_R} \\cos \\Psi\n  - \\frac{g S_b}{I_b \\Omega_R^2} \\\\\n  \\label{eq-aero-equilibrium-blade-moments-cw-2}\n    \\bar{\\bar \\beta} + \\beta\n  = \\frac{1}{ I_b \\Omega_R^2 } \\int_{0}^{BR} dT r\n  - 2 \\frac{q_{cw}}{\\Omega_R} \\sin \\Psi\n  - 2 \\frac{p_{cw}}{\\Omega_R} \\cos \\Psi\n  - \\frac{g S_b}{I_b \\Omega_R^2}\n\\end{gather}\n\nSubstituting expressions (\\ref{eq-aero-u-t-sq}) and (\\ref{eq-aero-u-p-u-t}) into (\\ref{eq-aero-equilibrium-blade-moments-ccw-2}) and (\\ref{eq-aero-equilibrium-blade-moments-cw-2}) gives:\n\\begin{multline}\n  \\label{eq-aero-blade-moment-thrust-ccw}\n  M_T =\n  \\int_{0}^{BR} dT r =\n  \\frac{1}{2} \\rho a c_b\n  \\int_{0}^{BR} \\left( \\theta U_T^2 + U_P U_T \\right) r dr = \\\\\n  =\n  \\frac{1}{2} \\rho a c_b R^4 \\Omega_R^2\n  \\left(\n    \\frac{B^4}{4} \\theta\n  + \\frac{2}{3} B^3 \\theta \\mu \\sin \\Psi\n  + \\frac{B^2}{2} \\theta \\mu^2 \\sin^2 \\Psi\n  \\right.\n  \\\\\n  + \\frac{B^3}{3} \\lambda\n  - \\frac{B^4}{4} \\bar \\beta\n  - \\frac{B^3}{3} \\beta \\mu \\cos \\Psi\n  + \\frac{B^4}{4} \\frac{p_{cw}}{\\Omega_R} \\sin \\Psi \\\\\n  + \\frac{B^2}{2} \\lambda \\mu \\sin \\Psi\n  - \\frac{B^2}{2} \\beta \\mu^2 \\sin \\Psi \\cos \\Psi\n  - \\frac{B^3}{3} \\bar \\beta \\mu \\sin \\Psi\n  \\\\\n  \\left.\n  + \\frac{B^3}{3} \\frac{p_{cw}}{\\Omega_R} \\mu \\sin^2 \\Psi\n  + \\frac{B^4}{4} \\frac{q_{cw}}{\\Omega_R} \\cos \\Psi\n  + \\frac{B^3}{3} \\frac{q_{cw}}{\\Omega_R} \\mu \\sin \\Psi \\cos \\Psi\n  \\right)\n\\end{multline}\n\\begin{multline}\n  \\label{eq-aero-blade-moment-thrust-cw}\n  M_T =\n  \\int_{0}^{BR} dT r =\n  \\frac{1}{2} \\rho a c_b\n  \\int_{0}^{BR} \\left( \\theta U_T^2 + U_P U_T \\right) r dr = \\\\\n  =\n  \\frac{1}{2} \\rho a c_b R^4 \\Omega_R^2\n  \\left(\n    \\frac{B^4}{4} \\theta\n  + \\frac{2}{3} B^3 \\theta \\mu \\sin \\Psi\n  + \\frac{B^2}{2} \\theta \\mu^2 \\sin^2 \\Psi\n  \\right.\n  \\\\\n  + \\frac{B^3}{3} \\lambda\n  - \\frac{B^4}{4} \\bar \\beta\n  - \\frac{B^3}{3} \\beta \\mu \\cos \\Psi\n  - \\frac{B^4}{4} \\frac{p_{cw}}{\\Omega_R} \\sin \\Psi \\\\\n  + \\frac{B^2}{2} \\lambda \\mu \\sin \\Psi\n  - \\frac{B^2}{2} \\beta \\mu^2 \\sin \\Psi \\cos \\Psi\n  - \\frac{B^3}{3} \\bar \\beta \\mu \\sin \\Psi\n  \\\\\n  \\left.\n  - \\frac{B^3}{3} \\frac{p_{cw}}{\\Omega_R} \\mu \\sin^2 \\Psi\n  + \\frac{B^4}{4} \\frac{q_{cw}}{\\Omega_R} \\cos \\Psi\n  + \\frac{B^3}{3} \\frac{q_{cw}}{\\Omega_R} \\mu \\sin \\Psi \\cos \\Psi\n  \\right)\n\\end{multline}\n\nKnowing that:\n\\begin{align}\n  \\label{eq-aero-trigonometric-4}\n  \\sin \\Psi \\cos \\Psi &= \\frac{ \\sin \\left( 2 \\Psi \\right) }{2} \\\\\n  \\label{eq-aero-trigonometric-5}\n  \\sin^2 \\Psi &= \\frac{ 1 - \\cos \\left( 2 \\Psi \\right) }{2} \\\\\n  \\label{eq-aero-trigonometric-6}\n  \\cos^2 \\Psi &= \\frac{ 1 + \\cos \\left( 2 \\Psi \\right) }{2} \\\\\n  \\label{eq-aero-trigonometric-7}\n  \\cos \\Psi \\sin \\left( 2 \\Psi \\right) &=\n  \\frac{ \\sin \\Psi + \\sin \\left( 3 \\Psi \\right) }{2} \\\\\n  \\label{eq-aero-trigonometric-8}\n  \\sin \\Psi \\sin \\left( 2 \\Psi \\right) &=\n  \\frac{ \\cos \\Psi - \\cos \\left( 3 \\Psi \\right) }{2}\n\\end{align}\n\nSubstituting (\\ref{eq-aero-blade-moment-thrust-ccw}) into (\\ref{eq-aero-equilibrium-blade-moments-ccw-2}) and (\\ref{eq-aero-blade-moment-thrust-cw}) into (\\ref{eq-aero-equilibrium-blade-moments-cw-2}) gives:\n\\begin{multline}\n  \\label{eq-aero-flapping-coefs-ccw-1}\n  \\bar{\\bar \\beta} + \\bar \\beta \\frac{\\gamma}{2}\n  \\left( \\frac{B^4}{4} + \\frac{B^3}{3} \\mu \\sin \\Psi \\right)\n  + \\beta \\left(\n    1 + \\frac{B^3}{6} \\gamma \\mu \\cos \\Psi\n    + \\frac{B^2}{8} \\gamma \\mu^2 \\sin \\left( 2 \\Psi \\right)\n  \\right)\n  = \\\\ =\n  \\frac{\\gamma}{2}\n  \\left(\n      \\frac{B^3}{3} \\lambda\n    + \\frac{B^4}{4} \\frac{p_{cw}}{\\Omega_R} \\sin \\Psi\n    + \\frac{B^2}{2} \\lambda \\mu \\sin \\Psi\n    + \\frac{B^3}{6} \\frac{p_{cw}}{\\Omega_R} \\mu\n    - \\frac{B^3}{6} \\frac{p_{cw}}{\\Omega_R} \\mu \\cos \\left( 2 \\Psi \\right)\n    \\right.\n    \\\\\n    + \\frac{B^4}{4} \\frac{q_{cw}}{\\Omega_R} \\cos \\Psi\n    + \\frac{B^3}{6} \\frac{q_{cw}}{\\Omega_R} \\mu \\sin \\left( 2 \\Psi \\right)\n    + \\frac{B^4}{4} \\theta\n    \\\\\n    \\left.\n    + \\frac{2}{3} B^3 \\theta \\mu \\sin \\Psi\n    + \\frac{B^2}{4} \\theta \\mu^2\n    - \\frac{B^2}{4} \\theta \\mu^2 \\cos \\left( 2 \\Psi \\right)\n  \\right)\n  \\\\\n  - 2 \\frac{q_{cw}}{\\Omega_R} \\sin \\Psi\n  + 2 \\frac{p_{cw}}{\\Omega_R} \\cos \\Psi\n  - \\frac{ g S_b }{ I_b \\Omega_R^2 }\n\\end{multline}\n\\begin{multline}\n  \\label{eq-aero-flapping-coefs-cw-1}\n  \\bar{\\bar \\beta} + \\bar \\beta \\frac{\\gamma}{2}\n  \\left( \\frac{B^4}{4} + \\frac{B^3}{3} \\mu \\sin \\Psi \\right)\n  + \\beta \\left(\n    1 + \\frac{B^3}{6} \\gamma \\mu \\cos \\Psi\n    + \\frac{B^2}{8} \\gamma \\mu^2 \\sin \\left( 2 \\Psi \\right)\n  \\right)\n  = \\\\ =\n  \\frac{\\gamma}{2}\n  \\left(\n      \\frac{B^3}{3} \\lambda\n    - \\frac{B^4}{4} \\frac{p_{cw}}{\\Omega_R} \\sin \\Psi\n    + \\frac{B^2}{2} \\lambda \\mu \\sin \\Psi\n    - \\frac{B^3}{6} \\frac{p_{cw}}{\\Omega_R} \\mu\n    + \\frac{B^3}{6} \\frac{p_{cw}}{\\Omega_R} \\mu \\cos \\left( 2 \\Psi \\right)\n    \\right.\n    \\\\\n    + \\frac{B^4}{4} \\frac{q_{cw}}{\\Omega_R} \\cos \\Psi\n    + \\frac{B^3}{6} \\frac{q_{cw}}{\\Omega_R} \\mu \\sin \\left( 2 \\Psi \\right)\n    + \\frac{B^4}{4} \\theta\n    \\\\\n    \\left.\n    + \\frac{2}{3} B^3 \\theta \\mu \\sin \\Psi\n    + \\frac{B^2}{4} \\theta \\mu^2\n    - \\frac{B^2}{4} \\theta \\mu^2 \\cos \\left( 2 \\Psi \\right)\n  \\right)\n  \\\\\n  - 2 \\frac{q_{cw}}{\\Omega_R} \\sin \\Psi\n  - 2 \\frac{p_{cw}}{\\Omega_R} \\cos \\Psi\n  - \\frac{ g S_b }{ I_b \\Omega_R^2 }\n\\end{multline}\n\nWhere $\\gamma$ is a blade Lock number.\n\nTransforming equations (\\ref{eq-aero-flapping-coefs-ccw-1}) and (\\ref{eq-aero-flapping-coefs-cw-1}) gives:\n\\begin{multline}\n  \\label{eq-aero-flapping-coefs-ccw-2}\n  \\bar{\\bar \\beta} + \\bar \\beta \\frac{\\gamma}{2}\n  \\left( \\frac{B^4}{4} + \\frac{B^3}{3} \\mu \\sin \\Psi \\right)\n  + \\beta \\left(\n    1 + \\frac{B^3}{6} \\gamma \\mu \\cos \\Psi\n    + \\frac{B^2}{8} \\gamma \\mu^2 \\sin \\left( 2 \\Psi \\right)\n  \\right)\n  = \\\\ =\n  \\left[\n    \\frac{\\gamma}{2}\n    \\left(\n        \\frac{B^3}{3} \\lambda\n      + \\frac{B^3}{6} \\frac{p_{cw}}{\\Omega_R} \\mu\n      + \\frac{B^4}{4} \\theta\n      + \\frac{B^2}{4} \\theta \\mu^2\n    \\right)\n    - \\frac{ g S_b }{ I_b \\Omega_R^2 }\n  \\right]\n  \\\\\n  + \\left[\n    \\frac{\\gamma}{2}\n    \\left( \\frac{B^4}{4} \\frac{q_{cw}}{\\Omega_R} \\right)\n    + 2 \\frac{p_{cw}}{\\Omega_R}\n  \\right] \\cos \\Psi\n  \\\\\n  + \\left[\n    \\frac{\\gamma}{2}\n    \\left(\n        \\frac{B^4}{4} \\frac{p_{cw}}{\\Omega_R}\n      + \\frac{B^2}{2} \\lambda \\mu\n      + \\frac{2}{3} B^3 \\theta \\mu\n    \\right)\n    - 2 \\frac{q_{cw}}{\\Omega_R}\n  \\right] \\sin \\Psi\n  \\\\\n  + \\left[\n    \\frac{\\gamma}{2}\n    \\left(\n      - \\frac{B^3}{6} \\frac{p_{cw}}{\\Omega_R} \\mu\n      - \\frac{B^2}{4} \\theta \\mu^2\n    \\right)\n  \\right] \\cos \\left( 2 \\Psi \\right)\n  \\\\\n  + \\left[\n    \\frac{\\gamma}{2}\n    \\left( \\frac{B^3}{6} \\frac{q_{cw}}{\\Omega_R} \\mu \\right)\n  \\right] \\sin \\left( 2 \\Psi \\right)\n\\end{multline}\n\n\\vfill\n\n\\begin{multline}\n  \\label{eq-aero-flapping-coefs-cw-2}\n  \\bar{\\bar \\beta} + \\bar \\beta \\frac{\\gamma}{2}\n  \\left( \\frac{B^4}{4} + \\frac{B^3}{3} \\mu \\sin \\Psi \\right)\n  + \\beta \\left(\n    1 + \\frac{B^3}{6} \\gamma \\mu \\cos \\Psi\n    + \\frac{B^2}{8} \\gamma \\mu^2 \\sin \\left( 2 \\Psi \\right)\n  \\right)\n  = \\\\ =\n  \\left[\n    \\frac{\\gamma}{2}\n    \\left(\n        \\frac{B^3}{3} \\lambda\n      - \\frac{B^3}{6} \\frac{p_{cw}}{\\Omega_R} \\mu\n      + \\frac{B^4}{4} \\theta\n      + \\frac{B^2}{4} \\theta \\mu^2\n    \\right)\n    - \\frac{ g S_b }{ I_b \\Omega_R^2 }\n  \\right]\n  \\\\\n  + \\left[\n    \\frac{\\gamma}{2}\n    \\left( \\frac{B^4}{4} \\frac{q_{cw}}{\\Omega_R} \\right)\n    - 2 \\frac{p_{cw}}{\\Omega_R}\n  \\right] \\cos \\Psi\n  \\\\\n  + \\left[\n    \\frac{\\gamma}{2}\n    \\left(\n      - \\frac{B^4}{4} \\frac{p_{cw}}{\\Omega_R}\n      + \\frac{B^2}{2} \\lambda \\mu\n      + \\frac{2}{3} B^3 \\theta \\mu\n    \\right)\n    - 2 \\frac{q_{cw}}{\\Omega_R}\n  \\right] \\sin \\Psi\n  \\\\\n  + \\left[\n    \\frac{\\gamma}{2}\n    \\left(\n        \\frac{B^3}{6} \\frac{p_{cw}}{\\Omega_R} \\mu\n      - \\frac{B^2}{4} \\theta \\mu^2\n    \\right)\n  \\right] \\cos \\left( 2 \\Psi \\right)\n  \\\\\n  + \\left[\n    \\frac{\\gamma}{2}\n    \\left( \\frac{B^3}{6} \\frac{q_{cw}}{\\Omega_R} \\mu \\right)\n  \\right] \\sin \\left( 2 \\Psi \\right)\n\\end{multline}\n\n\\vfill\n\nDifferentiating equation (\\ref{eq-aero-blade-flapping-angle}) gives:\n\\begin{align}\n  \\label{eq-aero-beta-prim}\n  \\bar \\beta &=\n  \\left( \\beta_{1s} \\cos \\Psi - \\beta_{1c} \\sin \\Psi \\right) \\\\\n  \\label{eq-aero-beta-bis}\n  \\bar{\\bar \\beta} &= -\n  \\left( \\beta_{1c} \\cos \\Psi + \\beta_{1s} \\sin \\Psi  \\right)\n\\end{align}\n\nSubstituting expressions (\\ref{eq-aero-beta-prim}) and (\\ref{eq-aero-beta-bis}) into equations (\\ref{eq-aero-flapping-coefs-ccw-2}) and (\\ref{eq-aero-flapping-coefs-cw-2}) as well as using trigonometric identities (\\ref{eq-aero-trigonometric-4}), (\\ref{eq-aero-trigonometric-5}), (\\ref{eq-aero-trigonometric-6}), (\\ref{eq-aero-trigonometric-7}) and (\\ref{eq-aero-trigonometric-8}) gives:\n\\begin{gather}\n  \\label{eq-aero-flapping-coefs-ccw-3}\n  \\begin{multlined}[0.88\\textwidth]\n    \\beta_0\n    + \n    \\beta_{1s} \\gamma \\frac{B^2}{8}\n    \\left( \\frac{\\mu^2}{2} + B^2 \\right) \\cos \\Psi\n    +\n    \\beta_{1c} \\gamma \\frac{B^2}{8}\n    \\left( \\frac{\\mu^2}{2} - B^2 \\right) \\sin \\Psi\n    \\\\\n    +\n    \\beta_{1c} \\gamma \\frac{B^3}{6} \\mu \\cos \\left( 2 \\Psi \\right)\n    +\n    \\left(\n        \\beta_{1s} \\gamma \\frac{B^3}{6} \\mu\n      + \\beta_0 \\gamma \\frac{B^2}{8} \\mu^2\n    \\right) \\sin \\left( 2 \\Psi \\right)\n    \\\\\n    +\n    \\beta_{1c} \\gamma \\frac{B^2}{16} \\mu^2 \\sin \\left( 3 \\Psi \\right)\n    -\n    \\beta_{1s} \\gamma \\frac{B^2}{16} \\mu^2 \\cos \\left( 3 \\Psi \\right)\n    = \\\\ =\n    \\left[\n      \\frac{\\gamma}{2}\n      \\left(\n          \\frac{B^3}{3} \\lambda\n        + \\frac{B^3}{6} \\frac{p_{cw}}{\\Omega_R} \\mu\n        + \\frac{B^4}{4} \\theta\n        + \\frac{B^2}{4} \\theta \\mu^2\n      \\right) - \\frac{ g S_b }{ I_b \\Omega_R^2 }\n    \\right]\n    \\\\\n    + \\left[\n      \\frac{\\gamma}{2}\n      \\left(\n          \\frac{B^4}{4} \\frac{q_{cw}}{\\Omega_R}\n        - \\frac{B^3}{3} \\beta_0 \\mu\n      \\right) + 2 \\frac{p_{cw}}{\\Omega_R}\n    \\right] \\cos \\Psi\n    \\\\\n    + \\left[\n      \\frac{\\gamma}{2}\n      \\left(\n          \\frac{B^4}{4} \\frac{p_{cw}}{\\Omega_R}\n        + \\frac{B^2}{2} \\lambda \\mu\n        + \\frac{2}{3} B^3 \\theta \\mu\n        \\right) - 2 \\frac{q_{cw}}{\\Omega_R}\n    \\right] \\sin \\Psi\n    \\\\\n    + \\left[\n      \\frac{\\gamma}{2}\n      \\left(\n        - \\frac{B^3}{6} \\frac{p_{cw}}{\\Omega_R} \\mu\n        - \\frac{B^2}{4} \\theta \\mu^2\n      \\right)\n    \\right] \\cos \\left( 2 \\Psi \\right)\n    \\\\\n    + \\left[\n      \\frac{\\gamma}{2}\n      \\left( \\frac{B^3}{6} \\frac{q_{cw}}{\\Omega_R} \\mu \\right)\n    \\right] \\sin \\left( 2 \\Psi \\right)\n  \\end{multlined}\n  \\\\\n  \\label{eq-aero-flapping-coefs-cw-3}\n  \\begin{multlined}[0.88\\textwidth]\n    \\beta_0\n    + \n    \\beta_{1s} \\gamma \\frac{B^2}{8}\n    \\left( \\frac{\\mu^2}{2} + B^2 \\right) \\cos \\Psi\n    +\n    \\beta_{1c} \\gamma \\frac{B^2}{8}\n    \\left( \\frac{\\mu^2}{2} - B^2 \\right) \\sin \\Psi\n    \\\\\n    +\n    \\beta_{1c} \\gamma \\frac{B^3}{6} \\mu \\cos \\left( 2 \\Psi \\right)\n    +\n    \\left(\n        \\beta_{1s} \\gamma \\frac{B^3}{6} \\mu\n      + \\beta_0 \\gamma \\frac{B^2}{8} \\mu^2\n    \\right) \\sin \\left( 2 \\Psi \\right)\n    \\\\\n    -\n    \\beta_{1s} \\gamma \\frac{B^2}{16} \\mu^2 \\cos \\left( 3 \\Psi \\right)\n    +\n    \\beta_{1c} \\gamma \\frac{B^2}{16} \\mu^2 \\sin \\left( 3 \\Psi \\right)\n    = \\\\ =\n    \\left[\n      \\frac{\\gamma}{2}\n      \\left(\n          \\frac{B^3}{3} \\lambda\n        - \\frac{B^3}{6} \\frac{p_{cw}}{\\Omega_R} \\mu\n        + \\frac{B^4}{4} \\theta\n        + \\frac{B^2}{4} \\theta \\mu^2\n      \\right) - \\frac{ g S_b }{ I_b \\Omega_R^2 }\n    \\right]\n    \\\\\n    + \\left[\n      \\frac{\\gamma}{2}\n      \\left(\n          \\frac{B^4}{4} \\frac{q_{cw}}{\\Omega_R}\n        - \\frac{B^3}{3} \\beta_0 \\mu\n      \\right) - 2 \\frac{p_{cw}}{\\Omega_R}\n    \\right] \\cos \\Psi\n    \\\\\n    + \\left[\n      \\frac{\\gamma}{2}\n      \\left(\n        - \\frac{B^4}{4} \\frac{p_{cw}}{\\Omega_R}\n        + \\frac{B^2}{2} \\lambda \\mu\n        + \\frac{2}{3} B^3 \\theta \\mu\n        \\right) - 2 \\frac{q_{cw}}{\\Omega_R}\n    \\right] \\sin \\Psi\n    \\\\\n    + \\left[\n      \\frac{\\gamma}{2}\n      \\left(\n          \\frac{B^3}{6} \\frac{p_{cw}}{\\Omega_R} \\mu\n        - \\frac{B^2}{4} \\theta \\mu^2\n      \\right)\n    \\right] \\cos \\left( 2 \\Psi \\right)\n    \\\\\n    + \\left[\n      \\frac{\\gamma}{2}\n      \\left( \\frac{B^3}{6} \\frac{q_{cw}}{\\Omega_R} \\mu \\right)\n    \\right] \\sin \\left( 2 \\Psi \\right)\n  \\end{multlined}\n\\end{gather}\n\nNeglecting all blade flapping harmonics above the first \\cite{GessowMyers1985} equations (\\ref{eq-aero-flapping-coefs-ccw-3}) and (\\ref{eq-aero-flapping-coefs-cw-3}) can be simplified as follows:\n\n\\begin{multline}\n  \\label{eq-aero-flapping-coefs-ccw-4}\n  \\beta_0\n  +\n  \\beta_{1s} \\gamma \\frac{B^2}{8}\n  \\left( \\frac{\\mu^2}{2} + B^2 \\right) \\cos \\Psi\n  +\n  \\beta_{1c} \\gamma \\frac{B^2}{8}\n  \\left( \\frac{\\mu^2}{2} - B^2 \\right) \\sin \\Psi\n  = \\\\ =\n  \\left[\n    \\frac{\\gamma}{2}\n    \\left(\n        \\frac{B^3}{3} \\lambda\n      + \\frac{B^3}{6} \\frac{p_{cw}}{\\Omega_R} \\mu\n      + \\frac{B^4}{4} \\theta\n      + \\frac{B^2}{4} \\theta \\mu^2\n    \\right) - \\frac{ g S_b }{ I_b \\Omega_R^2 }\n  \\right]\n  \\\\\n  + \\left[\n    \\frac{\\gamma}{2}\n    \\left(\n      \\frac{B^4}{4} \\frac{q_{cw}}{\\Omega_R}\n      - \\frac{B^3}{3} \\beta_0 \\mu\n    \\right) + 2 \\frac{p_{cw}}{\\Omega_R}\n  \\right] \\cos \\Psi\n  \\\\\n  + \\left[\n    \\frac{\\gamma}{2}\n    \\left(\n        \\frac{B^4}{4} \\frac{p_{cw}}{\\Omega_R}\n      + \\frac{B^2}{2} \\lambda \\mu\n      + \\frac{2}{3} B^3 \\theta \\mu\n    \\right) - 2 \\frac{q_{cw}}{\\Omega_R}\n  \\right] \\sin \\Psi\n\\end{multline}\n\n\\begin{multline}\n  \\label{eq-aero-flapping-coefs-cw-4}\n  \\beta_0\n  +\n  \\beta_{1s} \\gamma \\frac{B^2}{8}\n  \\left( \\frac{\\mu^2}{2} + B^2 \\right) \\cos \\Psi\n  +\n  \\beta_{1c} \\gamma \\frac{B^2}{8}\n  \\left( \\frac{\\mu^2}{2} - B^2 \\right) \\sin \\Psi\n  = \\\\ =\n  \\left[\n    \\frac{\\gamma}{2}\n    \\left(\n        \\frac{B^3}{3} \\lambda\n      - \\frac{B^3}{6} \\frac{p_{cw}}{\\Omega_R} \\mu\n      + \\frac{B^4}{4} \\theta\n      + \\frac{B^2}{4} \\theta \\mu^2\n    \\right) - \\frac{ g S_b }{ I_b \\Omega_R^2 }\n  \\right]\n  \\\\\n  + \\left[\n    \\frac{\\gamma}{2}\n    \\left(\n      \\frac{B^4}{4} \\frac{q_{cw}}{\\Omega_R}\n      - \\frac{B^3}{3} \\beta_0 \\mu\n    \\right) - 2 \\frac{p_{cw}}{\\Omega_R}\n  \\right] \\cos \\Psi\n  \\\\\n  + \\left[\n    \\frac{\\gamma}{2}\n    \\left(\n      - \\frac{B^4}{4} \\frac{p_{cw}}{\\Omega_R}\n      + \\frac{B^2}{2} \\lambda \\mu\n      + \\frac{2}{3} B^3 \\theta \\mu\n    \\right) - 2 \\frac{q_{cw}}{\\Omega_R}\n  \\right] \\sin \\Psi\n\\end{multline}\n\n\\clearpage\n\n\\subsection{Final Form}\n\nEquations (\\ref{eq-aero-flapping-coefs-ccw-4}) and (\\ref{eq-aero-flapping-coefs-cw-4}) can be transformed to get blade flapping coefficients:\n\n--- for counterclockwise direction of rotor:\n\\begin{align}\n  \\beta_0 &=\n  \\frac{\\gamma}{2}\n  \\left(\n      \\frac{B^3}{3} \\lambda \n    + \\frac{B^3}{6} \\frac{p_{cw}}{\\Omega_R} \\mu\n    + \\frac{B^4}{4} \\theta\n    + \\frac{B^2}{4} \\theta \\mu^2\n  \\right) - \\frac{ g S_b }{ I_b \\Omega_R^2 }\n  \\\\\n  \\beta_{1c} &=\n  2 \\mu \\left( \\lambda + \\frac{4}{3} B \\theta \\right)\n  \\cfrac{1}{\\cfrac{\\mu^2}{2} - B^2}\n  +\n  \\left(\n      B^4 \\frac{p_{cw}}{\\Omega_R}\n    - 16 \\frac{q_{cw}}{\\gamma \\Omega_R}\n  \\right)\n  \\cfrac{1}{B^2\\left(\\cfrac{\\mu^2}{2}-B^2\\right)}\n  \\\\\n  \\beta_{1s} &=\n  - \\frac{4}{3} \\beta_0 \\mu\n  \\cfrac{B}{\\cfrac{\\mu^2}{2} + B^2}\n  +\n  \\left(\n      B^4 \\frac{q_{cw}}{\\Omega_R} \n    + 16 \\frac{p_{cw}}{\\gamma \\Omega_R}\n  \\right)\n  \\cfrac{1}{B^2 \\left(\\cfrac{\\mu^2}{2}+B^2\\right)}\n\\end{align}\n\n--- for clockwise direction of rotor:\n\\begin{align}\n  \\beta_0 &=\n  \\frac{\\gamma}{2}\n  \\left(\n      \\frac{B^3}{3} \\lambda \n    - \\frac{B^3}{6} \\frac{p_{cw}}{\\Omega_R} \\mu\n    + \\frac{B^4}{4} \\theta\n    + \\frac{B^2}{4} \\theta \\mu^2\n  \\right) - \\frac{ g S_b }{ I_b \\Omega_R^2 }\n  \\\\\n  \\beta_{1c} &=\n  2 \\mu \\left( \\lambda + \\frac{4}{3} B \\theta \\right)\n  \\cfrac{1}{\\cfrac{\\mu^2}{2} - B^2}\n  -\n  \\left(\n      B^4 \\frac{p_{cw}}{\\Omega_R}\n    + 16 \\frac{q_{cw}}{\\gamma \\Omega_R}\n  \\right)\n  \\cfrac{1}{B^2\\left(\\cfrac{\\mu^2}{2}-B^2\\right)}\n  \\\\\n  \\beta_{1s} &=\n  - \\frac{4}{3} \\beta_0 \\mu\n  \\cfrac{B}{\\cfrac{\\mu^2}{2} + B^2}\n  +\n  \\left(\n      B^4 \\frac{q_{cw}}{\\Omega_R} \n    - 16 \\frac{p_{cw}}{\\gamma \\Omega_R}\n  \\right)\n  \\cfrac{1}{B^2 \\left(\\cfrac{\\mu^2}{2}+B^2\\right)}\n\\end{align}\n", "meta": {"hexsha": "f05f1b36a611d4e7e28ccd62ae1a55ad512022f1", "size": 46896, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/rotor_2.tex", "max_stars_repo_name": "marek-cel/mscsim-docs", "max_stars_repo_head_hexsha": "9984f33c84787c4420f11f2834bb35e040e1f36f", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-12-01T02:27:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T07:02:20.000Z", "max_issues_repo_path": "tex/rotor_2.tex", "max_issues_repo_name": "marek-cel/mscsim-docs", "max_issues_repo_head_hexsha": "9984f33c84787c4420f11f2834bb35e040e1f36f", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/rotor_2.tex", "max_forks_repo_name": "marek-cel/mscsim-docs", "max_forks_repo_head_hexsha": "9984f33c84787c4420f11f2834bb35e040e1f36f", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-12-01T10:56:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-01T19:41:05.000Z", "avg_line_length": 31.4105827194, "max_line_length": 392, "alphanum_fraction": 0.5997952917, "num_tokens": 18074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3410480492395055}}
{"text": "\\graphicspath{ {imgs/} }\n\\documentclass[main.tex]{subfiles}\n\\externaldocument{02data.tex}\n\\externaldocument{04methods.tex}\n\\begin{document}\n\\chapter{Model}\\label{chap:model}\nWith the building blocks defined in the previous chapter it is possible to construct a complete model for the task of lung nodule detection. This section describes in detail the used model and the learning process that was used to train it.\n\n\\section{Network Architecture}\nThe model is inspired by the network presented by Huang~\\cite{huang2017lung}. It has three 3D convolutional layers and three dense layers. The full architecture can be seen in Figure~\\ref{fig:net_struct} and is in the following sections explained from the input to output.\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[scale=0.5]{net_struct.png}\n\\end{center}\n\\caption{Architecture of the neural network. Each of the convolutional layers is composed of a 3D convolution layer with the respective filter size followed by a batch normalization and a pooling layer. The pool size is $(2,2,2)$ with a stride of $(1,1,1)$. The structure of the neural network resembles the one described by Huang~\\cite{huang2017lung}.}\n\\label{fig:net_struct}\n\\end{figure}\n\n\\subsection{Input} \nThe input to the network are the patches that have been cut and stored from the complete lung scan as described in Chapter~\\ref{chap:data} with a shape of $(50x50x5)$. The patches are randomly augmented by flipping them in x and y plane (examples can be seen in \\ref{fig:input}). The augmentation is applied to make the learned classification more robust against distortions in the input and aiding in generalization. This makes sense in the specific scenario since the nodules are growing in different shapes and locations in the lung and flipping them is not producing an impossible input to the network. There is also an additional parameter that allows for scaling the input in the $x,y$ plane.\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[scale=0.25]{patches-health.png}\n\\includegraphics[scale=0.25]{patches-nodule.png}\n\\end{center}\n\\caption{Input data for the cases of healthy and nodule patches. The image is taken from Tensorboard and shows in the case of nodules the random permutation of the input data.}\n\\label{fig:input}\n\\end{figure}\n\n\\subsection{Hidden Layers}\nThe convolutional part has three convolutional layers with $40$, $20$ and $20$ kernels each. The kernel size is $(3,3,3)$. This is in accordance with Huang et al.'s~\\cite{huang2017lung} implementation. Each of them is followed by a batch normalization layer. Batch normalization is in TensorFlow implemented as described by Ioffe and Szegedy~\\cite{ioffe2015batch}. The input of it is fed into a max-pooling layer with a pool size of $(2,2,2)$. The output of the last convolutional layer is flattened and fed to the dense layers. Two dense layers with $64$ neurons each and a ReLU activation function are used in this model. Their output is finally combined in two neurons, forming a 2D output of the network. \n\n\n\\subsection{Output}\nThe output of the network is the activation of the final two neurons. The class of the input is determined by the neuron with the higher activation in an one-hot design. Given the index of the maximum, is $0$ encoding a healthy $1$ encoding a nodule patch.\n\n\n\\section{Training}\nDuring training, the network is operated with batches of the input data. Regularization methods used for this network include batch normalization and dropout. Batch normalization is already described in Section~\\ref{ss:convlayer}. Dropout is another regularization method which during training drops random neurons of the network - training effectively several models at once, as discovered by Srivastava et al.~\\cite{srivastava2014dropout}, which should increase the overall performance of the network. During training, no improved performance could be observed when applying dropout throughout the whole network. It was rather harmful if applied to the convolutional layers. Thus, the final model uses dropout only in the fully connected layers. The loss of the network is then computed by the softmax cross-entropy between the labels in their one-hot form and the output of the two neurons at the end of the network. The Adam Optimizer is used on this loss for adapting the network parameters. For each epoch, the training is done on the complete training set with randomly permuted batches of size $10$. The training time is set to 3 full days.\n                                                 \n\n\n\\end{document}\n", "meta": {"hexsha": "7399559281746d6b1f9100c5ef9028e1aee97cff", "size": 4522, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/chapters/05model.tex", "max_stars_repo_name": "AndreaSuckro/acts_thesis", "max_stars_repo_head_hexsha": "24ed8d2d85d246d30b15e3f98a9f0b0f7da77f65", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/chapters/05model.tex", "max_issues_repo_name": "AndreaSuckro/acts_thesis", "max_issues_repo_head_hexsha": "24ed8d2d85d246d30b15e3f98a9f0b0f7da77f65", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/chapters/05model.tex", "max_forks_repo_name": "AndreaSuckro/acts_thesis", "max_forks_repo_head_hexsha": "24ed8d2d85d246d30b15e3f98a9f0b0f7da77f65", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 98.3043478261, "max_line_length": 1148, "alphanum_fraction": 0.7872622733, "num_tokens": 1021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3410480492395055}}
{"text": "\\documentclass{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage{amssymb,amsfonts,amsmath}\n\\usepackage{graphicx}\n\\usepackage{caption}\n\\usepackage{subfig}\n\\usepackage{color}\n\\usepackage[affil-it]{authblk}\n\\usepackage{multirow}\n\\usepackage{fullpage}\n\\usepackage{booktabs}\n\\usepackage{pdfsync}\n\n%\\usepackage[nofiglist, notablist, nomarkers]{endfloat}\n\\input{utils.tex}\n%\\title{Probabilistic learning of confounding factors in genetical\n%genomics studies}\n\\title{Derivations and mathematical details of GPmix}\n\\author[1]{Christoph Lippert, Oliver Stegle}\n\n\\affil[1]{Department Empirical Inference,\nMax Planck Institutes T\\\"ubingen, Germany}\n\\date{}\n\n\\captionsetup[subfloat]{listofformat=parens}\n\\newcommand{\\OLI}[1]{{\\color{blue}\\fbox{OLI} #1}}\n\\makeatletter\n\\newcommand{\\rmnum}[1]{\\romannumeral #1}\n\\newcommand{\\Rmnum}[1]{\\expandafter\\@slowromancap\\romannumeral #1@}\n\\makeatother\n\n\\newcommand{\\fix}{\\marginpar{FIX}}\n\\newcommand{\\new}{\\marginpar{NEW}}\n\n%\\nipsfinalcopy % Uncomment for camera-ready version\n%\\newcommand{\\B}[1]{\\bm{#1}} Christoph:removed this to make things consistent\n\\newcommand{\\B}[1]{{\\bf{#1}}}\n\\newcommand{\\Exp}{\\mathbb{E}}\n\\newcommand{\\norma}[1]{\\mathcal{N}\\left(#1\\right)}\n\\newcommand{\\eref}[1]{(\\ref{#1})}\n\\renewcommand{\\R}{\\mathbb{R}}\n\\newcommand\\norm[1]{\\left\\Vert {#1} \\right\\Vert}\n\\newcommand\\rank{\\mathrm{rank}}\n\\newcommand\\tr{\\mathrm{Tr}}\n\\newcommand\\Normal[3]{\\normal{#1}{{#2}\\;;\\;{#3}}}\n\\newcommand\\ve[1]{\\text{vec}\\left(#1\\right)}\n\\newcommand\\Real{\\mathbb{R}}\n\\newcommand{\\Ykron}{\\B{U}_R^\\T\\B{Y}\\B{U}_C}\n\\newcommand{\\XWAkron}[1]{\\B{U}_R^\\T\\B{X}_{#1}\\B{W}_{#1}\\B{A}_{#1}\\B{U}_C}\n\\newcommand{\\XWAkronT}[1]{\\B{U}_C^\\T\\B{A}_{#1}^\\T\\B{W}_{#1}^{\\T}\\B{X}_{#1}^{\\T}\\B{U}_R}\n\\begin{document}\n\\maketitle\n\n\n\\section{Some definitions}\n\\begin{itemize}\n\\item $\\B{A}=\\B{U}\\B{S}\\B{U}^{\\T}$ is the eigenvalue decomposition of\n  the symmetric $D$-by-$D$ matrix $\\B{A}$, where $\\B{U}$ is an\n  $D$-by-$D$ orthonormal matrix, holding the $D$ eigenvectors of\n  $\\B{A}$ and $\\B{S}$ is an $D$-by-$D$ diagonal matrix, holding the\n  corresponding eigenvalues of $\\B{A}$ as diagonal entries. \n\\item $\\B{A}\\odot\\B{B}$ is the pointwise or Hadamard product of $\\B{A}$ and $\\B{B}$.\n\\item $\\B{A}\\otimes\\B{B}$ is the Kronecker product of $\\B{A}$ and $\\B{B}$.\n\\item $\\B{Y}\\in\\mathbb{R}^{N\\times G}$ is the matrix holding all samples, having $N$ rows and $G$ columns.\n\\end{itemize}\n\n\n\\section{Kronecker testing strategies and models}\n$\\B{A}_j\\in\\Real^{C\\times M_j}$ is a matrix, that replicates the\n$j$-th fixed effects matrix $\\B{X}_j\\in\\Real^{R\\times D_j}$. $\\B{A}_j^\\T$\ntypically would be a binary matrix, but could in principle be\nanything. Using different versions of $\\B{A}_j^\\T$ corresponds to chosing\na testing strategy. For example, when $\\B{A}_j^\\T$ is the $C\\times C$\nIdentity matrix, then one would fit an independent weight to every\ncolumn of $\\B{Y}$, when $\\B{A}^\\T_j$ is a row-vector of ones, then one\nwould fit a single joint weight to all columns of $\\B{Y}$.\n\\begin{equation}\n\\Normal{\\ve{\\B{Y}}}{\\sum_j\\B{A}^{\\T}_j\\otimes\\B{X}_j\\ve{\\B{W}_j}}{\\B{C}\\otimes\\B{R}\n+ \\sigma^2\\B{I}}\n\\end{equation}\nAs long as $D_j\\leq R$, $M_j\\leq C$, the rank of $\\B{X}_j$ is $D_j$\nand the rank of $\\B{A}_j$ is $M_j$, and the rank of\n$\\left[\\B{X}_1...\\B{X}_J\\right]$ is $\\sum_{j=1}^JM_j$ the number of\ndegrees of freedom of a single $\\B{W}_j$ is $D_j \\cdot M_j$\n(sufficient condition).\n\\section{Efficient computation of tensor GP models}\n\\begin{equation}\n\\log\\Normal{\\ve{\\B{Y}}}{\\sum_{j=1}^J\\B{A}^{\\T}_j\\otimes\\B{X}_j\\ve{\\B{W}_j}}{\\B{C}\\otimes\\B{R}\n+ \\sigma^2\\B{I}}\n\\end{equation}\nApply the vec-trick to the mean term:\n\\begin{equation}\n\\log\\Normal{\\ve{\\B{Y}}}{\\ve{\\sum_{j=1}^J\\B{X}_j\\B{W}_j\\B{A}_j}}{\\B{C}\\otimes\\B{R}\n+ \\sigma^2\\B{I}}\n\\end{equation}\n\\begin{equation}\n-\\frac{C\\cdot R}{2}\\log(2\\pi)-\\frac{1}{2}\\log|\\B{C}\\otimes\\B{R} +\n\\sigma^2\\B{I}|\n-\\frac{1}{2}\\ve{\\B{Y} -\\sum_{j=1}^J\\B{X}_j\\B{W}_j\\B{A}_j}^\\T\\left(\\B{C}\\otimes\\B{R} +\n\\sigma^2\\B{I}\\right)^{-1}\\ve{\\B{Y} -\\sum_{j=1}^J\\B{X}_j\\B{W}_j\\B{A}_j}\n\\end{equation}\n\\subsection{Derivative of the squared form wrt. $\\B{W}$}\n\\begin{equation}\n\\frac{\\partial}{\\partial [\\B{W}_k]_{ab}}\\left(-\\frac{1}{2}\\ve{\\B{Y} -\\sum_{j=1}^J\\B{X}_j\\B{W}_j\\B{A}_j}^\\T\\left(\\B{C}\\otimes\\B{R} +\n\\sigma^2\\B{I}\\right)^{-1}\\ve{\\B{Y} -\\sum_{j=1}^J\\B{X}_j\\B{W}_j\\B{A}_j}\\right)\n\\end{equation}\nWe define matrix $\\B{D}\\in\\Real^{R\\times C}$, such that $\\ve{\\B{D}} = \\diag\\left(\\B{S}_C\\otimes\\B{S}_R +\n\\sigma^2\\B{I}\\right)^{-1}$ and rotate the data:\n\\begin{equation}\n\\frac{\\partial}{\\partial [\\B{W}_k]_{ab}}\n-\\frac{1}{2}\\tr\\left(\\left(\\Ykron\n    -\\sum_{j=1}^J\\XWAkron{j}\\right)^\\T\\left(\\left(\\Ykron\n      -\\sum_{j=1}^J\\XWAkron{j}\\right)\\odot \\B{D}\\right)\\right)\n\\end{equation}\n\\begin{eqnarray}\\nonumber\n\\frac{\\partial}{\\partial [\\B{W}_k]_{ab}}\n-\\frac{1}{2}\\tr\\left(\\Ykron^\\T (\\Ykron \\odot \\B{D})\\right)\n    +\\tr\\left( \\sum_{j=1}^J\\XWAkronT{j}(\\Ykron \\odot \\B{D})\\right) \\\\\n-\\tr\\left( \\sum_{j=1}^J\\sum_{i=j+1}^J\\XWAkronT{j}(\\XWAkron{i} \\odot\n  \\B{D}) \\right) \n-\\frac{1}{2}\\tr\\left(\\sum_{j=1}^J\\XWAkronT{j}(\\XWAkron{j} \\odot \\B{D}) \\right)\n\\end{eqnarray}\nLeaving out all terms without $\\B{W}_k$:\n\\begin{eqnarray}\\nonumber\n\\frac{\\partial}{\\partial [\\B{W}_k]_{ab}}\n    \\tr\\left( \\XWAkronT{k}(\\Ykron \\odot \\B{D})\\right) \\\\\n-\\tr\\left( \\sum_{j\\neq k}\\XWAkronT{k}(\\XWAkron{j} \\odot\n  \\B{D}) \\right) \n-\\frac{1}{2}\\tr\\left(\\XWAkronT{k}(\\XWAkron{k} \\odot \\B{D}) \\right)\n\\end{eqnarray}\n\n\\begin{eqnarray}\\nonumber\n    \\tr\\left( {\\B{U}_C^\\T[\\B{A}_{k}]_{b:}^{\\T}[\\B{X}_{k}]_{:a}^{\\T}\\B{U}_R} (\\Ykron \\odot \\B{D})\\right) \\\\\n-\\tr\\left( \\sum_{j\\neq k}{\\B{U}_C^\\T[\\B{A}_{k}]_{b:}^{\\T}[\\B{X}_{k}]_{:a}^{\\T}\\B{U}_R} (\\XWAkron{j} \\odot\n  \\B{D}) \\right) \n-\\tr\\left({\\B{U}_C^\\T[\\B{A}_{k}]_{b:}^{\\T}[\\B{X}_{k}]_{:a}^{\\T}\\B{U}_R} (\\XWAkron{k} \\odot \\B{D}) \\right)\n\\end{eqnarray}\nMoving around the terms in the trace and combining the last two traces\ninto one sum:\n\\begin{eqnarray}\\nonumber\n    \\tr\\left( [\\B{X}_{k}]_{:a}^{\\T}\\B{U}_R (\\Ykron \\odot \\B{D}) \\B{U}_C^\\T[\\B{A}_{k}]_{b:}^{\\T}\\right) \\\\\n-\\tr\\left( \\sum_{j=1}^J{[\\B{X}_{k}]_{:a}^{\\T}\\B{U}_R} (\\XWAkron{j} \\odot\n  \\B{D}) \\B{U}_C^\\T[\\B{A}_{k}]_{b:}^{\\T}\\right) \n\\end{eqnarray}\nObserving that this is a scalar, we can eliminate the trace and re-arrange:\n\\begin{eqnarray}\n    [\\B{X}_{k}]_{:a}^{\\T}\\B{U}_R ((\\Ykron-\\sum_{j=1}^J \\XWAkron{j}) \\odot \\B{D}) \\B{U}_C^\\T[\\B{A}_{k}]_{b:}^{\\T} \\\\\n\\end{eqnarray}\nStacking together these terms for all $a$ and $b$, the gradient becomes\n\\begin{eqnarray}\n    \\B{X}_{k}^{\\T}\\B{U}_R ((\\Ykron-\\sum_{j=1}^J \\XWAkron{j}) \\odot \\B{D}) \\B{U}_C^\\T\\B{A}_{k}^{\\T} \\\\\n\\end{eqnarray}\n\n\\newpage\n\\end{document}\n", "meta": {"hexsha": "a14342e2a29d0ede4534e69646e124e1554e0483", "size": 6571, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "svca_limix/derivations/derivations.tex", "max_stars_repo_name": "DenisSch/svca", "max_stars_repo_head_hexsha": "bd029c120ca8310f43311253e4d7ce19bc08350c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 65, "max_stars_repo_stars_event_min_datetime": "2015-01-20T20:46:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-27T14:40:35.000Z", "max_issues_repo_path": "svca_limix/derivations/derivations.tex", "max_issues_repo_name": "DenisSch/svca", "max_issues_repo_head_hexsha": "bd029c120ca8310f43311253e4d7ce19bc08350c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2015-02-01T22:35:17.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-07T08:18:23.000Z", "max_forks_repo_path": "svca_limix/derivations/derivations.tex", "max_forks_repo_name": "DenisSch/svca", "max_forks_repo_head_hexsha": "bd029c120ca8310f43311253e4d7ce19bc08350c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 35, "max_forks_repo_forks_event_min_datetime": "2015-02-01T17:26:50.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-13T07:06:16.000Z", "avg_line_length": 42.1217948718, "max_line_length": 131, "alphanum_fraction": 0.6399330391, "num_tokens": 2950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.3410480492395055}}
{"text": "\\documentclass[american,ignorenonframetext,notheorems,aspectratio=1610]{beamer}\n\\usetheme[compress]{Madrid}\n\\usecolortheme{albatross}\n\\usepackage{tikz,tikzscale}\n\\usetikzlibrary{snakes}\n\\input{mixed/fig/tikzsettings}\n\\def\\restrict{r}\n\\def\\prolongate{p}\n\n\\usepackage{../mathsim}\n\\usepackage{times}\n\\usepackage{xr}\n\\externaldocument{main}\n\\usepackage{mfirstuc}\n\\usepackage{mathtools}  \n\\mathtoolsset{showonlyrefs}\n\n\\def\\footnote#1{}\n\\def\\putindex#1{#1}\n\\title{Finite Elements}\n\\author{Guido Kanschat}\n\\date{\\today}\n\\begin{document}\n\\frame{\\maketitle}\n\\frame{\\frametitle{Overview}\\tableofcontents[hideallsubsections]}\n\\section{Elliptic PDE and Their Weak Formulation}\n\\frame{\\sectoc}\n\\subsection{Elliptic boundary value problems}\n\n\\frame {\\input{blocks/Notation-coordinates.tex}}\n\\frame {\\input{blocks/Notation-partial-derivative.tex}}\n\\frame {\\input{blocks/Notation-elim-coord.tex}\n  \\input{blocks/Definition-lin-pde-2order.tex}}\n\\frame {\\input{blocks/Definition-poisson-eqn.tex}}\n\\frame {\\input{blocks/Definition-domain.tex}}\n\\frame {\\input{blocks/Definition-boundary-conditions.tex}}\n\\frame {\\input{blocks/Definition-dirichlet-problem-differential.tex}}\n\\frame {\\input{blocks/Theorem-Dirichlet-principle.tex}}\n\\frame {\\input{blocks/Theorem-Dirichlet-variational-principle.tex}\n  \\input{blocks/Corollary-Dirichlet-uniqueness.tex}}\n\\frame {\\input{blocks/Lemma-reduction-to-zero-bc.tex}}\n\\frame {\\input{blocks/Notation-l2.tex}}\n\\frame {\\input{blocks/Lemma-Friedrichs-continuous.tex}\n  \\input{blocks/Problem-Friedrichs.tex}}\n\\frame {\\input{blocks/Lemma-h1-norm.tex}}\n\\frame {\\input{blocks/Lemma-Dirichlet-energy-boundedness.tex}\n  \\input{blocks/Lemma-minimizing-sequence.tex}}\n\\frame {\\input{blocks/Definition-h10.tex}\n  \\input{blocks/Lemma-Friedrichs-h1.tex}}\n\\frame {\\input{blocks/Definition-weak-formulation.tex}\n  \\input{blocks/Theorem-weak-unique-solution-1.tex}}\n\n\\frame {\\input{blocks/Lemma-neumann-weak.tex}}\n\\frame {\\input{blocks/Definition-natural-bc.tex}}\n\\frame {\\input{blocks/Lemma-mixed-bc-weak.tex}}\n\n\\subsection{Hilbert Spaces and Bilinear Forms}\n\\frame{\\tableofcontents[currentsection,subsectionstyle=show/shaded/hide]}\n\n\\frame {\\input{blocks/Definition-inner-product.tex}}\n\\frame {\\input{blocks/Theorem-bcs-inequality.tex}\n  \\input{blocks/Lemma-inner-product-norm.tex}}\n\\frame {\\input{blocks/Definition-complete.tex}}\n\\frame {\\input{blocks/Definition-Banach-hilbert.tex}}\n\\frame {\\input{blocks/Definition-orthogonal.tex}}\n\\frame {\\input{blocks/Definition-orthogonal-complement.tex}}\n\\frame {\\input{blocks/Lemma-orthogonal-closed.tex}}\n\\frame {\\input{blocks/Theorem-orthogonal-complement.tex}}\n% \\frame {\\input{blocks/Corollary-ortho-density.tex}}\n\\frame {\\input{blocks/Definition-ortho-projection.tex}}\n\\frame {\\input{blocks/Definition-dual-space.tex}}\n\\frame {\\input{blocks/Theorem-Riesz-representation.tex}}\n\\frame {\\input{blocks/Definition-bilinear-form.tex}}\n\\frame {\\input{blocks/Lemma-pde-bilinear.tex}}\n\\frame {\\input{blocks/Lemma-lax-milgram.tex}}\n\\frame {\\input{blocks/Lemma-weak-well-posed.tex}\n  \\input{blocks/Definition-elliptic.tex}}\n\n\\subsection{Fast facts on Sobolev spaces}\n\\frame{\\tableofcontents[currentsection,subsectionstyle=show/shaded/hide]}\n\n\\frame {\\input{blocks/Notation-multi-index.tex}}\n\\frame {\\input{blocks/Definition-distributional-derivative.tex}}\n\\frame {\\input{blocks/Definition-Wkp.tex}\n  \\input{blocks/Corollary-wkp-embedding.tex}}\n\\frame {\\input{blocks/Definition-hkp.tex}\n  \\input{blocks/Theorem-meyers-serrin.tex}}\n\n\\frame {\\input{blocks/Definition-boundary-smoothness.tex}}\n\\frame {\\input{blocks/Definition-continuous-embedding.tex}}\n\\frame {\\input{blocks/Theorem-sobolev-embedding.tex}}\n\\frame {\\input{blocks/Lemma-trace-continuous.tex}\n  \\input{blocks/Theorem-trace.tex}}\n\\frame {\\input{blocks/Definition-hoelder-spaces.tex}}\n\\frame {\\input{blocks/Theorem-hoelder-embedding.tex}\n  \\input{blocks/Corollary-sobolev-continuous.tex}}\n\n\\subsection{Properties of solutions}\n\\frame{\\tableofcontents[currentsection,subsectionstyle=show/shaded/hide]}\n\n\\frame {\\input{blocks/Definition-wkp-loc.tex}\n  \\input{blocks/Theorem-gt-8-8.tex}\n  \\input{blocks/Theorem-gt-8-10.tex}\n  \\input{blocks/Corollary-gt-8-10.tex}}\n\\frame {\\input{blocks/Theorem-gt-8-13.tex}\n  \\input{blocks/Corollary-h2-solution-bvp.tex}\n  \\input{blocks/Remark-classical-smooth.tex}\n  \\input{blocks/Remark-classical-convex.tex}}\n\\frame {\\input{blocks/Theorem-kondratev.tex}}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Conforming Finite Element Methods}\n\\frame{\\sectoc}\n\\subsection{Meshes, shape functions, and degrees of freedom}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame {\\input{blocks/Definition-facets.tex}\n  \\input{blocks/Definition-mesh.tex}}\n\\frame {\\input{blocks/Definition-finite-element.tex}\n\\input{blocks/Notation-dofs.tex}}\n\\frame {\\input{blocks/Definition-node-topology.tex}\n  \\input{blocks/Definition-fe-space.tex}}\n\\frame {\\input{blocks/Notation-global-local.tex}}\n\\frame {\\input{blocks/Definition-local-global.tex}}\n\\frame {\\input{blocks/Lemma-fe-support.tex}}\n\\frame {\\input{blocks/Lemma-mesh-continuity.tex}\n  \\input{blocks/Lemma-nodal-continuity.tex}}\n\n\\frame {\\input{blocks/Definition-barycentric-coordinates.tex}}\n\\frame {\\input{blocks/Lemma-barycentric-affine.tex}\n  \\input{blocks/Corollary-barycentric-interpolation.tex}}\n\n\\begin{frame}\n  \\frametitle{The $P_1$ element in barycentric coordinates}\n  \\begin{columns}\n    \\begin{column}{.5\\textwidth}\n      \\begin{center}\n        \\includegraphics[width=.6\\textwidth]{mixed/fig/p1-p.tikz}\n      \\end{center}\n    \\end{column}\n    \\begin{column}{.5\\textwidth}\n      \\begin{gather*}\n        \\phi_i = \\lambda_i,\n        \\quad i=0,1,2\n      \\end{gather*}\n    \\end{column}\n  \\end{columns}\n\\end{frame}\n\n\\begin{frame}\n  \\frametitle{The $P_2$ element in barycentric coordinates}\n  \\begin{columns}\n    \\begin{column}{.5\\textwidth}\n      \\begin{center}\n        \\includegraphics[width=.6\\textwidth]{mixed/fig/p2-p.tikz}\n      \\end{center}\n    \\end{column}\n    \\begin{column}{.5\\textwidth}\n      \\begin{xalignat*}2\n        \\phi_{ii} &= 2\\lambda_i^2 - \\lambda_i,\n        &i&=0,1,2\\\\\n        \\phi_{ij} &= 4\\lambda_i\\lambda_j\n        &j&\\neq i\n      \\end{xalignat*}\n    \\end{column}\n  \\end{columns}\n\\end{frame}\n\n\\begin{frame}\n  \\frametitle{The $P_3$ element in barycentric coordinates}\n  \\begin{columns}\n    \\begin{column}{.5\\textwidth}\n      \\begin{center}\n        \\includegraphics[width=.6\\textwidth]{mixed/fig/p3-p.tikz}\n      \\end{center}\n    \\end{column}\n    \\begin{column}{.5\\textwidth}\n      \\begin{xalignat*}2\n        \\phi_{iii} &= \\tfrac12 \\lambda_i(3\\lambda_i-1)(3\\lambda_i-2)\n        &i&=0,1,2\\\\\n        \\phi_{ij} &= \\tfrac92\\lambda_i\\lambda_j(3\\lambda_j-1)\n        &j&\\neq i\\\\\n        \\phi_0 &= 27\\lambda_0\\lambda_1\\lambda_2\n      \\end{xalignat*}\n    \\end{column}\n  \\end{columns}\n\\end{frame}\n\n\\frame {\\input{blocks/Definition-galerkin-approximation.tex}}\n\\frame {\\input{blocks/Corollary-galerkin-equations.tex}}\n\\frame {\\input{blocks/Lemma-discrete-lax-milgram.tex}\n  \\input{blocks/Lemma-cea.tex}}\n\\frame {\\input{blocks/Lemma-fe-matrix.tex}}\n\\frame {\\input{blocks/Algorithm-matrix-assembling.tex}}\n\n\\frame {\\input{blocks/Definition-tensor-product-polynomials.tex}}\n\\frame {\\input{blocks/Lemma-tensor-product-node-functionals.tex}}\n\n\\begin{frame}\n  \\frametitle{Example: $Q_2$ shape functions}\n  \\begin{center}\n    \\includegraphics[height=.27\\textheight]{graph/shape0}\n    \\includegraphics[height=.27\\textheight]{graph/shape1}\n    \\includegraphics[height=.27\\textheight]{graph/shape2}\n\n    \\includegraphics[height=.27\\textheight]{graph/shape3}\n    \\includegraphics[height=.27\\textheight]{graph/shape4}\n    \\includegraphics[height=.27\\textheight]{graph/shape5}\n\n    \\includegraphics[height=.27\\textheight]{graph/shape6}\n    \\includegraphics[height=.27\\textheight]{graph/shape7}\n    \\includegraphics[height=.27\\textheight]{graph/shape8}\n  \\end{center}\n\\end{frame}\n\n\\frame {\\input{blocks/Lemma-tensor-product-trace.tex}}\n\n\\begin{frame}\n  \\frametitle{Example: $Q_2$ continuous basis (selection)}\n  \\begin{center}\n    \\includegraphics[height=.27\\textheight]{graph/cgbasis1-02}\n    \\includegraphics[height=.27\\textheight]{graph/cgbasis1-03}\n    \\includegraphics[height=.27\\textheight]{graph/cgbasis1-15}\n    \\includegraphics[height=.27\\textheight]{graph/cgbasis1-16}\n\n    \\includegraphics[height=.27\\textheight]{graph/cgbasis1-07}\n    \\includegraphics[height=.27\\textheight]{graph/cgbasis1-13}\n    \\includegraphics[height=.27\\textheight]{graph/cgbasis1-18}\n    \\includegraphics[height=.27\\textheight]{graph/cgbasis1-22}\n\n    \\includegraphics[height=.27\\textheight]{graph/cgbasis1-17}\n    \\includegraphics[height=.27\\textheight]{graph/cgbasis1-23}\n    \\includegraphics[height=.27\\textheight]{graph/cgbasis1-20}\n    \\includegraphics[height=.27\\textheight]{graph/cgbasis1-24}\n  \\end{center}\n\\end{frame}\n\n\\begin{frame}\n  \\frametitle{Example: $Q_2$ discontinuous basis (selection)}\n  \\begin{center}\n    \\includegraphics[height=.27\\textheight]{graph/dgbasis1-08}\n    \\includegraphics[height=.27\\textheight]{graph/dgbasis1-15}\n    \\includegraphics[height=.27\\textheight]{graph/dgbasis1-20}\n    \\includegraphics[height=.27\\textheight]{graph/dgbasis1-27}\n\n    \\includegraphics[height=.27\\textheight]{graph/dgbasis1-07}\n    \\includegraphics[height=.27\\textheight]{graph/dgbasis1-19}\n    \\includegraphics[height=.27\\textheight]{graph/dgbasis1-23}\n    \\includegraphics[height=.27\\textheight]{graph/dgbasis1-30}\n\n    \\includegraphics[height=.27\\textheight]{graph/dgbasis1-26}\n    \\includegraphics[height=.27\\textheight]{graph/dgbasis1-33}\n    \\includegraphics[height=.27\\textheight]{graph/dgbasis1-24}\n    \\includegraphics[height=.27\\textheight]{graph/dgbasis1-22}\n  \\end{center}\n\\end{frame}\n\n\\subsubsection{Mapped finite elements}\n\n\\frame {\\input{blocks/Definition-mapped-mesh.tex}}\n\\frame {\\input{blocks/Example-mapping-linear.tex}}\n\\frame {\\input{blocks/Example-mapping-bilinear.tex}}\n\\frame {\\input{blocks/Definition-mapped-fe.tex}}\n\\frame {\\input{blocks/Lemma-mapped-norms-affine.tex}}\n\\frame {\\input{blocks/Lemma-shape-regular-transformation.tex}}\n\\frame {\\input{blocks/Assumption-mapping-decomposition.tex}}\n\\frame {\\input{blocks/Lemma-scaling-1.tex}}\n\n\\subsection{A priori error analysis}\n\\frame{\\subtoc}\n\n\\frame {\\input{blocks/Lemma-poincare.tex}}\n\\frame {\\input{blocks/Lemma-bramble-hilbert.tex}}\n%\\frame {\\input{blocks/Lemma-b-h-projector.tex}}\n\\frame {\\input{blocks/Definition-mesh-family.tex}}\n\\frame {\\input{blocks/Definition-nodal-interpolation.tex}\n  \\input{blocks/Lemma-nodal-interpolation.tex}}\n\\frame {\\input{blocks/Definition-broken-sobolev-norm.tex}}\n\\frame {\\input{blocks/Theorem-fe-interpolation.tex}\n  \\input{blocks/Corollary-fe-approximation.tex}}\n\\frame {\\input{blocks/Theorem-fe-convergence.tex}}\n\n\\subsubsection{Estimates of stronger norms}\n\n\\frame {\\input{blocks/Definition-stronger-norm.tex}}\n\\frame {\\input{blocks/Lemma-inverse-estimate.tex}}\n\\frame {\\input{blocks/Theorem-h2-error.tex}}\n\n\\subsubsection{Estimates of weaker norms}\n\n\\frame {\\input{blocks/Definition-dual-problem.tex}}\n\\frame {\\input{blocks/Lemma-poisson-dual.tex}}\n\\frame {\\input{blocks/Assumption-elliptic-regularity.tex}}\n\\frame {\\input{blocks/Theorem-fe-l2.tex}\n  \\input {blocks/Corollary-fe-functional.tex}}\n\n\\subsubsection{Green's function and maximum norm estimates}\n\n\\frame {\\input {blocks/Definition-greens-function.tex}\n  \\input {blocks/Theorem-greens-function-rd.tex}}\n\\frame {\\input {blocks/Lemma-greens-function-domain.tex}}\n\\frame {\\input {blocks/Theorem-greens-function-representation.tex}}\n\\frame {\\input {blocks/Theorem-linfty-error.tex}}\n\n\\subsection{A posteriori error analysis}\n\\frame{\\subtoc}\n\n\\frame {\\input {blocks/Definition-a-posteriori.tex}}\n\\frame {\\input {blocks/Definition-locally-quasi-uniform.tex}}\n\\frame {\\input {blocks/Definition-fem-neighborhood.tex}}\n\\frame {\\input {blocks/Theorem-clement.tex}}\n\\frame {\\input {blocks/Theorem-scott-zhang.tex}}\n\\frame {\\input {blocks/Theorem-schoeberl-interpolation.tex}}\n\\frame {\\input {blocks/Definition-residual.tex}}\n\\frame {\\input {blocks/Lemma-residual-hm1.tex}}\n\\frame {\\input {blocks/Definition-mvl-jmp.tex}}\n\\frame {\\input {blocks/Definition-residual-strong.tex}}\n\\frame {\\input {blocks/Lemma-residual-upper-bound.tex}}\n\\frame {\\input {blocks/Definition-osc.tex}}\n\\frame {\\input {blocks/Definition-residual-estimator.tex}}\n\\frame {\\input {blocks/Theorem-residual-estimate.tex}}\n\n\\section{Variational Crimes}\n\\frame{\\sectoc}\n\\subsection{Numerical quadrature}\n\\frame {\\input {blocks/Lemma-strang-1.tex}}\n\\frame {\\input {blocks/Definition-tensor-product-quadrature.tex}\n  \\input {blocks/Lemma-tensor-product-gauss.tex}}\n\\frame {\\input {blocks/Assumption-bilinear-form-quadrature.tex}}\n\\frame {\\input {blocks/Definition-bilinear-quadrature.tex}}\n\\frame {\\input {blocks/Lemma-quadrature-stability.tex}}\n\\frame {\\input {blocks/Theorem-quadrature-error-bilinear.tex}}\n\\frame {\\input {blocks/Lemma-product-sobolev-norm.tex}}\n\\frame {\\input {blocks/Theorem-quadrature-error-rhs.tex}}\n\n\\section{Solving the Discrete Problem}\n\\frame{\\sectoc}\n\\subsection{Richardson's method}\n\\frame {\\input {blocks/Definition-spd-condition-number.tex}}\n\\frame {\\input {blocks/Definition-matrix-condition-number.tex}}\n\\frame {\\input {blocks/Lemma-richardson-error-step.tex}}\n\\frame {\\input {blocks/Theorem-richardson-convergence1.tex}}\n\\frame {\\input {blocks/Definition-richardson-method.tex}}\n\\frame {\\input {blocks/Theorem-richardson-convergence2.tex}}\n\\frame {\\input {blocks/Definition-riesz-isomorphism.tex}}\n\\frame {\\input {blocks/Definition-p-richardson-method.tex}}\n\\subsection{The conjugate gradient method}\n\\frame{\\subtoc}\n\\frame {\\input {blocks/Definition-steepest-descent.tex}}\n\\frame {\\input {blocks/Lemma-steepest-descent.tex}}\n\\frame {\\input {blocks/Definition-cg-method.tex}}\n\\frame {\\input {blocks/Definition-pcg-method.tex}}\n\\frame {\\input {blocks/Definition-krylov-space.tex}}\n\\frame {\\input {blocks/Lemma-cg-orthogonality.tex}}\n\\frame {\\input {blocks/Lemma-cg-minimization.tex}}\n\\frame {\\input {blocks/Theorem-cg-convergence.tex}}\n\n\\subsection{Condition numbers of finite element matrices}\n\\frame{\\subtoc}\n\\frame {\\input {blocks/Notation-up-to-a-constant.tex}}\n\\frame {\\input {blocks/Definition-mass-stiffness.tex}}\n\\frame {\\input {blocks/Lemma-condition-number-mass-matrix.tex}}\n\\frame {\\input {blocks/Corollary-refined-condition-number.tex}}\n\\frame {\\input {blocks/Theorem-condition-number-stiffness-matrix.tex}}\n\n\\subsection{Multigrid methods}\n\\frame {\\input {blocks/Algorithm-mgm.tex}}\n\n\\section{Bibliography}\n\\frame{\\bibliographystyle{alpha}\n\\bibliography{all}}\n\\end{document}\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: t\n%%% End:\n", "meta": {"hexsha": "4b122e5433bd526970d6db6e6577321ed59ad1b3", "size": 14780, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "fem/slides.tex", "max_stars_repo_name": "arimiftari/notes", "max_stars_repo_head_hexsha": "737b95ed6a4163bd1d395c0379410513dcb03ef1", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fem/slides.tex", "max_issues_repo_name": "arimiftari/notes", "max_issues_repo_head_hexsha": "737b95ed6a4163bd1d395c0379410513dcb03ef1", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-05-24T07:31:37.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-31T12:58:14.000Z", "max_forks_repo_path": "fem/slides.tex", "max_forks_repo_name": "arimiftari/notes", "max_forks_repo_head_hexsha": "737b95ed6a4163bd1d395c0379410513dcb03ef1", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2018-05-15T19:28:53.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-05T19:07:29.000Z", "avg_line_length": 38.9973614776, "max_line_length": 79, "alphanum_fraction": 0.7352503383, "num_tokens": 4312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704502361149, "lm_q2_score": 0.6150878555160666, "lm_q1q2_score": 0.3410480401827598}}
{"text": "\n\\section{Language}~\\label{sec:language}\n\nCopilot is embedded into the functional programming language Haskell\n\\cite{PeytonJones02}, and a working knowledge of Haskell is necessary to use\nCopilot effectively. Copilot is a pure declarative language; i.e., expressions\nare free of side-effects and are referentially transparent.  A program written\nin Copilot, which from now on will be referred to as a \\emph{specification}, has\na cyclic behavior, where each cycle consists of a fixed series of steps:\n\n\\begin{itemize}\n\\item Sample external variables and arrays.\n\\item Update internal variables.\n\\item Fire external triggers. (In case the specification is violated.)\n\\item Update observers (for debugging purpose).\n\\end{itemize}\n\n\\noindent We refer to a single cycle as an \\emph{iteration} or a \\emph{step}.\n\nAll transformation of data in Copilot is propagated through streams.\nA stream is an infinite, ordered sequence of values which must conform to the same type.\nE.g., we have the stream of Fibonacci numbers:\n\n\\begin{center}\n$s_{fib} = \\{0, 1, 1, 2, 3, 5, 8, 13, 21, \\dots \\}$\n\\end{center}\n\n\\noindent We denote the $n$th value of the stream $s$ as $s(n)$, and the first\nvalue in a sequence $s$ as $s(0)$. For example, for $s_{fib}$ we have that $s_{fib}(0) = 0$,\n$s_{fib}(1) = 1$, $s_{fib}(2) = 1$, and so forth.\n\nConstants as well as arithmetic, boolean, and relational operators are\nlifted to work pointwise on streams:\n\n\\noindent\n%\\begin{minipage}{0.3\\textwidth}\n\\begin{lstlisting}[language = Copilot, frame = single]\nx :: Stream Int32\nx = 5 + 5\n\ny :: Stream Int32\ny = x * x\n\nz :: Stream Bool\nz = x == 10 && y < 200\n\\end{lstlisting}\n%\\end{minipage}\n\n\n\\noindent Here the streams {\\tt x}, {\\tt y}, and {\\tt z} are simply\n\\emph{constant streams}:\n\n\\begin{center}\n$\\mathtt{x} \\leadsto \\{10, 10, 10, \\dots \\}$,\n$\\mathtt{y} \\leadsto \\{100, 100, 100,  \\dots \\}$,\n$\\mathtt{z} \\leadsto \\{\\mbox{T},\\; \\mbox{T},\\; \\mbox{T},\\; \\dots \\}$\n\\end{center}\n\nTwo types of \\emph{temporal} operators are provided, one for delaying streams and one for\nlooking into the future of streams:\n%\n\\begin{lstlisting}[language = Copilot, frame = single]\n(++) :: [a] -> Stream a -> Stream a\ndrop :: Int -> Stream a -> Stream a\n\\end{lstlisting}\n%\nHere {\\tt xs ++ s} prepends the list {\\tt xs} at the front of the stream {\\tt s}.\nFor example the stream {\\tt w} defined as follows, given our previous definition\nof {\\tt x}:\n%\n\\begin{lstlisting}[language = Copilot, frame = single]\nw = [5,6,7] ++ x\n\\end{lstlisting}\n%\nevaluates to the sequence\n$\\mathtt{w} \\leadsto \\{5, 6, 7, 10, 10, 10, \\dots\\}$.\nThe expression {\\tt drop k s} skips the first {\\tt k} values of the stream {\\tt\n  s}, returning the remainder of the stream.\nFor example we can skip the first two values of {\\tt w}:\n%\n\\begin{lstlisting}[language = Copilot, frame = single]\nu = drop 2 w\n\\end{lstlisting}\n%\nwhich yields the sequence\n$\\mathtt{u} \\leadsto \\{7, 10, 10, 10, \\dots\\}$.\n\n\\subsection{Streams as Lazy-Lists} \\label{sec:stream}\n\nA key design choice in Copilot is that streams should mimic \\emph{lazy lists}.\nIn Haskell, the lazy-list of natural numbers can be programmed like this:\n%\n\\begin{lstlisting}[language = Copilot, frame = single]\nnats_ll :: [Int32]\nnats_ll = [0] ++ zipWith (+) (repeat 1) nats_ll\n\\end{lstlisting}\n%\nAs both constants and arithmetic operators are lifted to work pointwise on\nstreams in Copilot, there is no need for {\\tt zipWith} and {\\tt repeat} when\nspecifying the stream of natural numbers:\n%\n\\begin{lstlisting}[language = Copilot, frame = single]\nnats :: Stream Int32\nnats = [0] ++ (1 + nats)\n\\end{lstlisting}\n%\nIn the same manner, the lazy-list of Fibonacci numbers can be specified  in Haskell as follows:\n%\n\\begin{lstlisting}[language = Copilot, frame = single]\nfib_ll :: [Int32]\nfib_ll = [1, 1] ++ zipWith (+) fib_ll (drop 1 fib_ll)\n\\end{lstlisting}\n%\nIn Copilot we simply throw away {\\tt zipWith}:\n\\begin{lstlisting}[language = Copilot, frame = single]\nfib :: Stream Int32\nfib = [1, 1] ++ (fib + drop 1 fib)\n\\end{lstlisting}\n\nCopilot specifications must be \\emph{causal}, informally meaning that\nstream values cannot depend on future values.  For example, the following stream\ndefinition is allowed:\n%\n\\begin{lstlisting}[language = Copilot, frame = single]\nf :: Stream Word64\nf = [0,1,2] ++ f\n\ng :: Stream Word64\ng = drop 2 f\n\\end{lstlisting}\n%\n\nBut if instead {\\tt g} is defined as {\\tt g = drop 4 f}, then the definition is\ndisallowed.  While an analogous stream is definable in a lazy language, we bar\nit in Copilot, since it requires future values of {\\tt f} to be\ngenerated before producing values for {\\tt g}.  This is not possible since\nCopilot programs may take inputs in real-time from the environment (see\nSection~\\ref{subsec:interacting}).\n\n\n\\subsection{Structs}\nStructs require some special attentation in Copilot, as we cannot magically\nimport the definition of the struct in Copilot. In this section we discuss the\nsteps that need to be taken by following the code of \\texttt{Struct.hs} in the\n\\texttt{Examples} directory of the Copilot distribution, or the repository\n\\footnote{\\url{https://github.com/Copilot-Language/Copilot/blob/master/Examples/Struct.hs}}.\n\nLet's assume that we have defined a 2d-vector type in our C code:\n\\begin{lstlisting}\nstruct vec {\n\tfloat x;\n\tfloat y;\n};\n\\end{lstlisting}\nFor us to be able to use this vector inside Copilot, we need to follow a number\nof steps:\n\\begin{enumerate}\n  \\item Enable \\texttt{DataKinds} compiler extension.\n  \\item Define a datatype to mimic the C definition.\n  \\item Write an instance of the \\texttt{Struct} class, containing a definition\n  for the struct name and function to translate the fields to a heterogeneous\n    list.\n  \\item Write an instance of the \\texttt{Typed} class.\n\\end{enumerate}\n\n\\subsubsection*{Enabling compiler extensions}\nFirst and foremost, we need to enable the \\texttt{DataKinds} extension to GHC,\nby putting:\n\\begin{lstlisting}[language=Copilot]\n{-# LANGUAGE DataKinds #-}\n\\end{lstlisting}\nat the top of our specification file. This allows us to define \\emph{kinds},\nwhich are the types of types. Our datatype needs to carry the names of the\nfields in C as well. Using the \\texttt{DataKinds} extension we are able to\nwrite the names of the fields as part of our types.\n\n\n\\subsubsection*{Defining the datatype}\nA suitable representation of structs in Haskell is provided by the\n\\emph{record-syntax}, this allows us to use named fields as part of the\ndatatype. For Copilot this is not enough though: we still need to define the\nnames of the fields in our C code. Therefore we introduce new \\texttt{Field}\ndatatype, which takes two arguments: the name of field, and it's type. Now we\ncan mimic our vector struct in Copilot as follows:\n\\begin{lstlisting}[language=Copilot]\ndata Vec = Vec\n  { x :: Field \"x\" Float\n  , y :: Field \"y\" Float\n  }\n\\end{lstlisting}\nHere we created two fields, $x$ and $y$, each with their corresponding C names\nand types. Note that the name inside Haskell and the C names do not necessarily\nneed to match, nor is it always possible to have them match. For type-safety,\ninside Copilot we will typically only use the Haskell level names (i.e. the\nunquoted ones). The C names are only used by Copilot internally.\n\n\n\\subsubsection*{Instance of \\texttt{Struct}}\nOur next task is to inform Copilot about our new type, therefore we need to\nwrite and instance of the \\texttt{Struct}-class. This class has the purpose of\ndefining the datatype as a struct, it provides the code generator of Copilot the\nname of struct in C, and provides a function to translate the struct to a list\nof values:\n\\begin{lstlisting}[language=Copilot]\ninstance Struct Vec where\n  -- typename :: Vec -> String\n  typename _ = \"vec\"  -- Name of the type in C\n\n  -- Function to translate Vec to list of Value's, order should match struct.\n  -- tovalues :: Vec -> [Value Vec]\n  toValues v = [ Value Float (x v)\n               , Value Float (y v)\n               ]\n\\end{lstlisting}\nBoth definitions should be pretty self-explanatory. Note however that\n\\texttt{Value a} is a wrapper around the \\texttt{Field} datatype to hide the\nactual type of \\texttt{Field}. It takes the type of the field, and the field\nitself as its arguments. The elements in the list should be in the same order\nas the fields in the struct.\n\nBoth \\texttt{typename} and \\texttt{toValues} have to be defined by the user,\nbut neither should ever be used by the user. Both functions are only used by\nthe code generator of Copilot.\n\n\n\\subsubsection*{Instance of \\texttt{Typed}}\nIn Copilot, streams can only of types that are instances of the \\texttt{Typed}\nclass. To be able to create streams of vectors, \\texttt{Vec} needs to be an\ninstance of \\texttt{Typed} as well. The class only provides a \\texttt{typeOf}\nfunction, returning the type:\n\\begin{lstlisting}[language=Copilot]\ninstance Typed Vec where\n  typeOf = Struct (Vec (Field 0) (Field 0))\n\\end{lstlisting}\nFor \\texttt{Vec} this means we need to return something of the \\texttt{Vec}\ntype wrapped in the \\texttt{Struct} constructor. In this case it does not\nmatter what the values of the fields are, we just need to return something of\nthe correct type.\n\n\n\\subsubsection*{Simple operations}\nBuilding streams of structs works like building any other stream, but we need\nto wrap the values of a struct using the \\texttt{Field} constructor. The reason\nfor this is quite straightforward: the fields of our struct are defined in\nterms of \\texttt{Field}:\n\\begin{lstlisting}[language=Copilot]\nv :: Stream Vec\nv = [ Vec (Field 0) (Field 1) ] ++ v\n\\end{lstlisting}\n\nWe can also turn a field of a struct into its own stream using the\n\\texttt{(\\#)}-operator:\n\\begin{lstlisting}[language=Copilot]\nvx :: Stream Float\nvx = v # x\n\\end{lstlisting}\nNote the we use the Haskell level accessor \\texttt{x} to retrieve the field\nfrom the stream of vectors.\n\n\n\\subsubsection*{Example code}\n\\begin{example}\n\\label{exm:struct}\nNow that we defined all there is, we can make streams of structs. The following\ncode has been taken from the \\texttt{Struct.hs} example, and shows the basic\nusage of structs.\n\n\\begin{lstlisting}[language=Copilot]\n{-# LANGUAGE DataKinds #-}\n\nmodule Struct where\n\nimport Language.Copilot\nimport Copilot.Compile.C99\n\nimport Prelude hiding ((>), (<), div, (++))\n\n\ndata Vec = Vec\n  { x :: Field \"x\" Float\n  , y :: Field \"y\" Float\n  }\n\ninstance Struct Vec where\n  typename _ = \"vec\"  -- Name of the type in C\n\n  -- Function to translate Vec to list of Value's, order should match struct.\n  toValues v = [ Value Float (x v)\n               , Value Float (y v)\n               ]\n\n-- We need to provide an instance to Typed with a bogus Vec\ninstance Typed Vec where\n  typeOf = Struct (Vec (Field 0) (Field 0))\n\n\nvecs :: Stream Vec\nvecs = [ Vec (Field 1) (Field 2)\n       , Vec (Field 12) (Field 8)\n       ] ++ vecs\n\n\nspec = do\n  -- Trigger that always executes, splits the vec into seperate args.\n  trigger \"split\" true [arg $ vecs # x, arg $ vecs # y]\n\\end{lstlisting}\n\\end{example}\n\n\\subsection{Functions on Streams} \\label{sec:FnOnStreams}\n\nGiven that constants and operators work pointwise on streams, we can use Haskell\nas a macro-language for defining functions on streams.  The idea of using\nHaskell as a macro language is powerful since Haskell is a\ngeneral-purpose higher-order functional language.\n\n\\begin{example}\nWe define the function {\\tt even}, which given a stream of\nintegers returns a boolean stream which is true whenever the input stream\ncontains an even number, as follows:\n%\n\\begin{lstlisting}[language = Copilot, frame = single]\neven :: Stream Int32 -> Stream Bool\neven x = x `mod` 2 == 0\n\\end{lstlisting}\n%\nApplying {\\tt even} on {\\tt nats} (defined above) yields the sequence\n$\\{T, F, T, F, T, F, \\dots\\}$.\n\\end{example}\n\nIf a function is required to return multiple results, we simply use plain\nHaskell tuples:\n\n\\begin{example}\nWe define complex multiplication as follows:\n%\n\\begin{lstlisting}[language = Copilot, frame = single]\nmul_comp\n  :: (Stream Double, Stream Double)\n  -> (Stream Double, Stream Double)\n  -> (Stream Double, Stream Double)\n(a, b) `mul_comp` (c, d) = (a * c - b * d, a * d + b * c)\n\\end{lstlisting}\n%\nHere {\\tt a} and {\\tt b} represent the real and imaginary part of the left\noperand, and {\\tt c} and {\\tt d} represent the real and imaginary part\nof the right operand.\n\\end{example}\n\n\\subsection{Stateful Functions} \\label{sec:stateful}\n\nIn addition to pure functions, such as {\\tt even} and {\\tt mul\\_comp},\nCopilot also facilitates \\emph{stateful} functions. A \\emph{stateful} function\nis a function which has an internal state, e.g. as a latch (as in electronic\ncircuits) or a low/high-pass filter (as in a DSP).\n\n\\begin{figure*}\n\\begin{minipage}{0.25\\linewidth}\n\\begin{tabular}{c|c||c}\n$\\mathtt{x}_i$: & $\\mathtt{y}_{i-1}$: & $\\mathtt{y}_i$:\\\\\n\\hline\n$F$ & $F$ & $F$ \\\\\n\\hline\n$F$ & $T$ & $T$ \\\\\n\\hline\n$T$ & $F$ & $T$ \\\\\n\\hline\n$T$ & $T$ & $F$\n\\end{tabular}\n\\end{minipage}\n\\begin{minipage}{0.35\\linewidth}\n\\begin{lstlisting}[frame=none]\nlatch :: Stream Bool -> Stream Bool\nlatch x = y\n  where\n  y = if x then not z else z\n  z = [False] ++ y\n\\end{lstlisting}\n\\end{minipage}\n\\hspace{1cm}\n\\begin{minipage}{0.3\\linewidth}\n\\begin{tabular}{c|c|c|c|c|c}\n   & 0 & 1 & 2 & 3 & 4\\\\\n\\hline\nx & $F$ & $T$ & $T$ & $F$ & $F$ \\\\\n\\hline\ny & $F$ & $T$ & $F$ & $F$ & $F$ \\\\\n\\end{tabular}\n\\end{minipage}\n\\caption{A latch [Example 3]. The specification function is provided at the left and the\nimplementation in copilot is provided in the middle. The right shows an example of\nthe latch, where x is $\\{F, T, T, F, F, \\dots \\}$ and the initial value of y (used with $x_0$ to find\n$y_0$ since there is no $y_{-1}$) is False.}\n\\label{fig:jk_latch}\n\\end{figure*}\n\n\\begin{example}\nWe consider a simple latch, as described in \\cite{Farhat2004}, with a single\ninput and a boolean state. A latch is a way of simulating memory in circuits by feeding\nback output gates as inputs.  Whenever the input is true the internal state is reversed.\nThe operational behavior and the implementation of the latch is shown in Figure\n\\ref{fig:jk_latch}.\\footnote\n{In order\nto use conditionals (i.e., if-then-else) in Copilot specifications,\nas in Figures~\\ref{fig:jk_latch} and~\\ref{fig:counter}, the GHC\nlanguage extension {\\tt RebindableSyntax} must be set on.}\n\\end{example}\n\n\\begin{figure*}\n\\begin{minipage}{0.4\\linewidth}\n\\begin{tabular}{c|c||c}\n$\\mathtt{inc}_i$: & $\\mathtt{reset}_i$: & $\\mathtt{cnt}_i$: \\\\\n\\hline\n$F$ & $F$ & $\\mathtt{cnt}_{i-1}$ \\\\\n\\hline\n* & $T$ & $0$ \\\\\n\\hline\n$T$ & $F$ & $\\mathtt{cnt}_{i-1} + 1$ \\\\\n\\hline\n\\end{tabular}\n\\end{minipage}\n\\hspace{1cm}\n\\begin{minipage}{0.6\\linewidth}\n\\begin{lstlisting}[language = Copilot, frame = none]\ncounter :: Stream Bool -> Stream Bool\n        -> Stream Int32\ncounter inc reset = cnt\n  where\n  cnt = if reset then 0\n          else if inc then z + 1\n                 else z\n  z = [0] ++ cnt\n\\end{lstlisting}\n\\end{minipage}\n\\caption{A resettable counter. The specification is provided at the left and the\nimplementation is provided at the right.\n}\n\\label{fig:counter}\n\\end{figure*}\n\n\\begin{example}\nWe consider a resettable counter with two inputs, {\\tt inc} and {\\tt reset}.\nThe input {\\tt inc} increments the counter and the input {\\tt reset} resets the\ncounter. The internal state of the counter, {\\tt cnt}, represents the value of the\ncounter and is initially set to zero. At each cycle, $i$, the value of\n$\\mathtt{cnt}_i$ is determined as shown in the left table in Figure\n\\ref{fig:counter}.\n\\end{example}\n\n%\\begin{figure}\n%\\begin{code}\n%fir2pole :: Double -> Double -> Double -> Double\n%  -> Double -> Sig Double -> Sig Double\n%fir2pole a1 a2 b0 b1 b2 x0 = y0\n%  where\n%    y0 = - (constant a1)*y1 - (constant a2)*y2\n%         + (constant b0)*x0 + (constant b1)*x1 + (constant b2)*x2\n%    x2 = [0, 0] ++ x0 ; x1 = drop 1 x2\n%    y2 = [0, 0] ++ y0 ; y1 = drop 1 y2\n%\\end{code}\n%\\caption{A $2$-pole IIR filter.}\n%\\label{fig:2_pole_iir_filter}\n%\\end{figure}\n\n\\subsection{Types} \\label{sec:types}\n\nCopilot is a typed language, where types are enforced by the Haskell type system\nto ensure generated C programs are well-typed.  Copilot is \\emph{strongly typed}\n(i.e., type-incorrect function application is not possible) and \\emph{statically\n  typed} (i.e., type-checking is done at compile-time).  The base types are\nBooleans, unsigned and signed words of width 8, 16, 32, and 64, floats, and\ndoubles.  All elements of a stream must belong to the same base\ntype.  These types have instances for the class {\\tt Typed a}, used to constrain\nCopilot programs.\n\nWe provide a {\\tt cast} operator\n%\n\\begin{lstlisting}[language = Copilot, frame = single]\ncast :: (Typed a, Typed b) => Stream a -> Stream b\n\\end{lstlisting}\n%\nthat casts from one type to another.  The cast operator is only defined for\ncasts that do not lose information, so an unsigned word type {\\tt a} can only be\ncast to another unsigned  type at least as large as {\\tt a} or to a signed word\ntype strictly larger than {\\tt a}.  Signed types cannot be cast to unsigned\ntypes but can be cast to signed types at least as large.\n\nThere also exists an {\\tt unsafeCast} operator which allows casting from any\ntype to any other (except from floating point numbers to integer types):\n\n\\begin{lstlisting}[language = Copilot, frame = single]\nunsafeCast :: (Typed a, Typed b) => Stream a -> Stream b\n\\end{lstlisting}\n\n\\subsection{Interacting With the Target Program}\n\\label{subsec:interacting}\n\nAll interaction with the outside world is done by sampling \\emph{external\n  symbols} and by evoking \\emph{triggers}.  External symbols are symbols that\nare defined outside Copilot and which reflect the visible state of the target\nprogram that we are monitoring.  They include variables and arrays.\nAnalogously, triggers are functions that are defined outside Copilot and which\nare evoked when Copilot needs to report that the target program has violated a\nspecification constraint.\n\n\\paragraph{External Variables.}\n\n\nAs discussed in Section~\\ref{sampling}, \\emph{sampling} is an approach\nfor monitoring the state of an executing system based on sampling\nstate-variables, while assuming synchrony between the monitor and the\nobserved software. Copilot targets hard real-time embedded C programs\nso the state variables that are observed by the monitors are variables\nof C programs. Copilot monitors run either in the same thread or a\nseparate thread as the system under observation and the only variables\nthat can be observed are those that are made available through shared\nmemory. This means local variables cannot be observed. Currently,\nCopilot supports basic C datatypes, arrays and structs. Combinations of each of\nthose work as well: nested arrays, arrays of structs, structs containg arrays\netc. All of these variables containing actual data; pointers to data are not\nsupported by design.\n\n\nCopilot has both an interpreter and a compiler.The compiler must be\nused to monitor an executing program. The Copilot reification process\ngenerates a C monitor from a Copilot specification. The variables that\nare observed in the C code must be declared as \\emph{external}\nvariables in the monitor. The external variables have the same name as\nthe variables being monitored in the C code are treated as shared\nmemory. The interpreter is intended for exploring ideas and algorithms\nand is not intended to monitor executing  C\nprograms. It may seem external variables would have no meaning if the\nmonitor was run in the interpreter, but Copilot gives the user the\nability to specify default stream values for an external variable that\nget used when the monitor interpreted.\n\n A Copilot specification is \\emph{open} if defined with external symbols in the\nsense that values must be provided externally at runtime.  To simplify writing\nCopilot specifications that can be interpreted and tested, constructs for\nexternal symbols take an optional environment for interpretation.\n\nExternal variables are similar to global variables in other languages. They\nare defined by using the {\\tt extern} construct:\n%\n\\begin{lstlisting}[language = Copilot, frame = single]\nextern :: Typed a => String -> Maybe [a] -> Stream a\n\\end{lstlisting}\n%\n\\noindent\nIt takes the name of an external variable, a possible Haskell list to serve as\nthe environment for the interpreter, and generates a stream by sampling the\nvariable at each clock cycle.  For example,\n%\n\\begin{lstlisting}[language = Copilot, frame = single]\nsumExterns :: Stream Word64\nsumExterns = let ex1 = extern \"e1\" (Just [0..])\n                 ex2 = extern \"e2\" Nothing\n             in  ex1 + ex2\n\\end{lstlisting}\n%\nis a stream that takes two external variables {\\tt e1} and {\\tt e2} and adds\nthem.  The first external variable contains the infinite list {\\tt [0,1,2,...]}\nof values for use when interpreting a Copilot specification containing the\nstream.  The other variable contains no environment ({\\tt sumExterns} must have\nan environment for both of its variables to be interpreted).\n\nSometimes, type inference cannot infer the type of an external variable.  For\nexample, in the stream definition\n%\n\\begin{lstlisting}[language = Copilot, frame = single]\nextEven :: Stream Bool\nextEven = e0 `mod` 2 == 0\n  where e0 = externW8 \"x\" Nothing\n\\end{lstlisting}\n%\n\\noindent\nthe type of {\\tt extern \"x\"} is ambiguous, since it cannot be inferred from a\nBoolean stream and we have not given an explicit type signature.  For\nconvenience, typed {\\tt extern} functions are provided, e.g., {\\tt externW8} or\n{\\tt externI64} denoting an external unsigned 8-bit word or signed 64-bit word,\nrespectively.\n% Please see the grammar in Appendix~\\ref{sec:BNF} for the list of\n% all sampling functions.\n\nIn general it is best practice to define external symbols with\ntop-level definitions, e.g.,\n%\n\\begin{lstlisting}[language = Copilot, frame = single]\ne0 :: Stream Word8\ne0 = extern  \"e0\" (Just [2,4..])\n\\end{lstlisting}\n\n\\noindent\nso that the symbol name and its environment can be shared between streams.\n\nJust like regular variables, arrays can be sampled as well. Copilot threats\narrays in the same way as it does for scalars. \n\\begin{example}\n\\label{exmp:pitot}\nLets take the example where we\nhave the readouts of four pitot tubes, giving us the measured airspeed:\n\\begin{code}[frame=single]\n/* Array containing readouts of 4 pitot tubes. */\ndouble airspeeds[4] = ... ;\n\\end{code}\nIn our Copilot specification, we need to provide the type of our array, because\nCopilot need to know the length of the array we refer to. Apart from that,\nreferring to an external array is like referring to any other variable:\n\\begin{lstlisting}[language=Copilot, frame=single]\nairspeeds :: Stream (Array 4 Double)\nairspeeds = extern \"airspeeds\" Nothing\n\\end{lstlisting}\n\\end{example}\n\n\n\\paragraph{Triggers.}\nTriggers, the only mechanism for Copilot streams to effect the outside world,\nare defined by using the {\\tt trigger construct}:\n%\n\\begin{lstlisting}[language = Copilot, frame = single]\ntrigger :: String -> Stream Bool -> [TriggerArg] -> Spec\n\\end{lstlisting}\n%\nThe first parameter is the name of the external function, the second parameter is the\nguard which determines when the trigger should be evoked, and the third parameter\nis a list of arguments which is passed to the trigger when evoked.\nTriggers can be combined into a specification by using the \\emph{do}-notation:\n%\n\\begin{lstlisting}[language = Copilot, frame = single]\nspec :: Spec\nspec = do\n  trigger \"f\" (even nats) [arg fib, arg (nats * nats)]\n  trigger \"g\" (fib > 10) []\n  let x = externW64 \"x\" (Just [1..])\n  trigger \"h\" (x < 10) [arg x]\n\\end{lstlisting}\n%\nThe order in which the triggers are defined is irrelevant. To interpret this spec we run:\n%\n\\begin{lstlisting}[language = Copilot, frame = single]\ninterpret 10 spec\n\\end{lstlisting}\n%\nwhich will yield the following output:\n%\n\\begin{code}\nf:        g:\t h:\n(1,0)     ()        (1)\n--        ()        (2)\n(2,4)     ()        (3)\n--        ()        (4)\n(5,16)    ()        (5)\n--        ()        (6)\n(13,36)   --\t(7)\n--        --        (8)\n(34,64)   --\t(9)\n--        --         --\n\\end{code}\n%\n\n\\begin{example}\n\\label{exm:engine}\nWe consider an engine controller with the following property: If the temperature\nrises more than 2.3 degrees within 0.2 seconds, then the fuel injector should\nnot be running.  Assuming that the global sample rate is 0.1 seconds, we can\ndefine a monitor that surveys the above property:\n%\n\\begin{lstlisting}[language = Copilot, frame = single]\npropTempRiseShutOff :: Spec\npropTempRiseShutOff =\n  trigger \"over_temp_rise\"\n    (overTempRise && running) []\n\n  where\n  max = 500 -- maximum engine temperature\n\n  temps :: Stream Float\n  temps = [max, max, max] ++ temp\n\n  temp = extern \"temp\" Nothing\n\n  overTempRise :: Stream Bool\n  overTempRise = drop 2 temps > (2.3 + temps)\n\n  running :: Stream Bool\n  running = extern \"running\" Nothing\n\\end{lstlisting}\n%\n\nHere, we assume that the external variable {\\tt temp} denotes the temperature of\nthe engine and the external variable {\\tt running} indicates whether the fuel\ninjector is running.  The external function {\\tt over\\_temp\\_rise} is called\nwithout any arguments if the temperature rises more than 2.3 degrees within 0.2\nseconds and the engine is not shut off.  Notice there is a latency of one tick between when the property is violated and when the guard becomes true.\n\\end{example}\n", "meta": {"hexsha": "f571b1cf9b537db8354b4cfea39dbe672a9208c6", "size": 25297, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "TutorialAndDevGuide/Tutorial/Language.tex", "max_stars_repo_name": "Copilot-Language/copilot-discussion", "max_stars_repo_head_hexsha": "caccad918b23dae991095344a845827ddccd6047", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-06-10T00:44:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-17T13:20:09.000Z", "max_issues_repo_path": "TutorialAndDevGuide/Tutorial/Language.tex", "max_issues_repo_name": "Copilot-Language/copilot-discussion", "max_issues_repo_head_hexsha": "caccad918b23dae991095344a845827ddccd6047", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2019-04-01T20:24:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-07T22:34:17.000Z", "max_forks_repo_path": "TutorialAndDevGuide/Tutorial/Language.tex", "max_forks_repo_name": "Copilot-Language/copilot-discussion", "max_forks_repo_head_hexsha": "caccad918b23dae991095344a845827ddccd6047", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3985611511, "max_line_length": 149, "alphanum_fraction": 0.7264497767, "num_tokens": 7048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6513548782017746, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.34093239762974975}}
{"text": "\\documentclass{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage[T1]{fontenc}\n\\usepackage{lmodern,textcomp}\n\\usepackage[frenchb]{babel}\n\\usepackage{amsmath,amsfonts}\n\\usepackage{graphicx}\n\\title{Machine Learning - Lesson nÂ°11}\n\\author{ChloÃ©-Agathe Azencott}\n\\date{December 2016}\n\\DeclareMathOperator*{\\argmax}{arg\\,max}\n\\begin{document}\n\n\\maketitle\n\nScribes : RÃ©mi Lalanne, Adam Hotait and Devang Thakkar\n\n\\section{Introduction}\nIn Machine Learning, it appears necessary to reduce the dimensionality of data set. There are various reasons to do so :\n\n\\begin{itemize}\n    \\item Computational complexity : the goal is to reduce the computational cost in time and space and therefore to avoid data overfitting.\n    \n    \\item Interpretability, so that models are easier to interpret by human users.\n    \n    \\item To simplify the models and make them more robust since there is less variance.\n    \n    \\item Data visualization : the goal is to make this visualization easier for a human, for instance doctors who want to visualize plenty of data of their patients.\n    \n    \\item To curb the cost of data acquisition, that can be very high in some cases.\n    \n    \\item To keep only relevant and non-redundant attributes, since irrelevant and redundant attributes can prevent the algorithm from being efficient.\n    \n\\end{itemize}\n\n\\bigskip\n\n\\textbf{Feature selection and feature extraction} are two ways of accomplishing dimensionality reduction.\n\nOn the one hand, the idea of feature selection is to select $m<p$ features among the $p$ existing features, and to ignore the remaining $(p-m)$ features. There are three ways to proceed :\n\\begin{enumerate}\n    \\item \\textbf{Filtering approaches} that calculate a feature relevance score thanks to a statistical measure. Low-scoring features are then removed. These methods have a low computational cost and are independent of the classification algorithm but each feature is considered separately, so they ignore features dependencies.\n    \n    \\item \\textbf{Wrapper approaches} that aim at finding the best set of features for a given predictive model but that can be computationally very expensive.\n    \n    \\item \\textbf{Embedded approaches} that simultaneously fit a model and learn which features should be included. They are specific to a model.\n\\end{enumerate}\n\nAll these approaches are supervised.\n\n\\bigskip\nOn the other hand, the idea of feature extraction is to project the $p$ features on $m<p$ new dimensions. There are several approaches, such as linear approaches (Principal Components Analysis, Factor Analysis, MultiDimensional Scaling), supervised approaches (Linear Discriminant Analysis), non linear approaches (Isometric feature mapping, Locally Linear Embedding, Autoencoders).\n\n\n\\section{Feature selection : subset selection}\nIn a feature subset selection problem, the issue is to select a subset of features, so that all the attention concerns this subset and that the rest can be ignored.\n\n\n\\subsection{Wrappers approaches}\n\nThe goal is to find the subset of features that leads to the best-performing algorithm, knowing that there are $2^p$ subsets of p features. Indeed, if we consider p features, each feature can be present or  absent in the remaining features, so there are two choices for each future, hence $2^p$ such sets at the end.\nTherefore, it is almost impossible to search the whole space exhaustively, except in the cases where $n$ is very small, since complexity is $O(2^p)$.\n\\bigskip\n\nTo solve this problem, we can use a greedy approach (\"algorithme glouton\" in French) : the forward search.\nWe proceed  by adding the \"best\" feature at each step. Let $E(F)$ be the error on held-out validation set of a predictor trained only using the features in $F$.\n\\begin{itemize}\n\n    \\item Initially, $F = \\emptyset $\n    \n    \\item Then, we find a new best feature : $j*= arg \\ min_{j \\in \\{1,...,p\\}} E(F\\cup \\{j\\})$\n    \n    \\item If $E(F)<E(F \\cup \\{j\\})$ : the algorithm stops.\n    \n    \\item Else : $F \\leftarrow F \\cup \\{j\\}$.\n    \n\\end{itemize}\n\nThe error is therefore minimal and the complexity is $O(p^2)$, which is way better than $O(2^p)$.\n\n\n\\subsection{Embedded approaches}\nWe have seen algorithms which simultaneously optimize a cost/loss function and the features that should be uses.\nAmong them, the $L1$ regularization, with an approach called the Lasso. For a parameter $\\lambda \\geq 0 $, this approach finds $\\widehat{\\beta}_{lasso} = arg \\ min_{\\beta} \\| y-X\\beta \\|_{2}^{2} + \\lambda \\| \\beta \\|_2 $.\n\n\\section{Feature extraction : Principal Components Analysis}\n\nAnother way of reducing the dimensionality of the data is use to Principal Component Analysis. The primary objective that we need to achieve is the minimization of information loss after the data has been projected onto a lower dimensional space using a linear mapping. In other words, we need to find a lower dimensional space, where the variance of the projection is maximised.\n\n\\bigskip\n\nA few things to be noted here are:\n\\begin{itemize}\n    \\item PCA is an unsupervised method, in the sense that when project our values, we only consider the data points without paying any heed to the labels that pertain to those points.\n    \\item In PCA, one of our early assumptions is that the data that we have is centred; that is to say, the mean of our data is 0.\n    \\item PCA is a variance maximising exercise, hence it requires the data to be normalized before we can apply it correctly.\n\\end{itemize}\n\n\\bigskip\n\n\\subsection{Finding the Principal Components}\nThe goal is to find a space which maximizes the variance of the data that is projected on it. Before we begin, we define a certain terms that would enable us to understand better the derivation process. Let $w$ be a unit vector on which we wish to project our matrix of data points $X$.\nThis would imply that the projection of $X$ in the direction $w$ is given by $z = w^T X$. The variance of $z$, as calculated in the slides, comes out to be $w^T(\\Sigma)w$ where $\\Sigma$ is the covariance of X under the assumptions of a centred dataset.\n\n\\subsubsection{Finding the first component}\nWe need to begin by finding a vector that maximizes the variance of the projection $z$ and has unit magnitude. A problem of this type takes the form of a Lagrangian optimisation that can be solved easily by introducing a Lagrangian multiplier. Putting it mathematically, the problem is transformed from $(1)$ to $(2)$:\n\n\\begin{gather}\n    w_1 = \\argmax_ { w \\in R_p} Var(w^T x) \\\\\n    w_1 = \\argmax_ { w \\in R_p} (w^T \\Sigma w - \\alpha (w^Tw \\ - \\ 1))\n\\end{gather}\n\nAs with any ordinary Lagrangian problem, we derive the resulting equation and set it to 0. Doing this leads us to a couple of astonishing results. We find out that:\n\n\\begin{itemize}\n    \\item The system has been reduced to an eigen value problem\n    \\item The multiplier $\\alpha$ is an eigen value of the matrix $\\Sigma$\n    \\item The direction vector $w_1$ is an eigen vector of the matrix $\\Sigma$\n\\end{itemize}\n\nUsing this results, we find out that the desired direction vector is the eigen vector with the largest eigen value.\n\n\\subsubsection{Finding the remaining components}\nOnce we have the first principal component, we proceed to find the remaining components. The process is really similar to the previous case, except for the fact that we have one more condition on our vector $w_i$, that is, the new vector $w_i$ must be orthogonal to all the previously found components. This algorithm leads to the discovery that the $i^{th}$ component is the eigen vector with the $i^{th}$ largest eigen value.\n\n\\bigskip\n\nOnce we have all the principal components of the data, we can choose to keep the top $m$ components and discard the rest. An important variable to decide here is $m$, i.e., how many principal components do we retain. One way to decide is to plot a scree graph of the variance explained by the components and select as many variables as required as long as the addition of one more components seems useful to the total variance explained.\n\n\\section{Feature extraction : Autoencoders}\n\nA third way to do dimensionality reduction is to use neural networks, with the use of Autoencoders. Autoencoders try to reconstruct its input. However, and that is where it uses neural networks, the interest of autoencoders is the hidden layer(s) it constructs. Autoencoders are a non linear, unsupervised approach to dimensionality reduction.\n\n\\subsection{General presentation}\n\nThe goal is to select fewer features than there are in the train set to then reconstruct the train set. This is done on several points of data to find the weights that minimize the reconstruction error.\n\n\\begin{figure}[!h]\n    \\center\n    \\includegraphics[scale=0.5]{./figures/autoencoder_general.png}\n    \\caption{Diagram of a generic autoencoder}\n\\end{figure}\n\n\\subsection{Restricted Boltzmann Machines}\n\nRBM are stochastic neural networks, where the activation of a unit is probabilistic, with : \\[P(o_i = 1) = \\frac{1}{1+e^{-a_i+\\sum_j o_j w_{ij}}}\\]\n\n\\begin{figure}[!h]\n    \\center\n    \\includegraphics[scale=0.5]{./figures/autoencoder_stochastic.png}\n    \\caption{Diagram of a stochastic neural network}\n\\end{figure}\n\nA RBM has two layers, with bidirectional connections. The term \"restricted\" comes from the fact that there are no connection between the hidden units.\n\nThe main property of a RBM is the energy of the RBM, defined by : \\[E(\\textbf{x},\\textbf{z}) = - \\sum\\limits_{j=1}^p a_jx_j - \\sum\\limits_{h=1}^H b_hz_h - \\sum\\limits_{j=1}^p\\sum\\limits_{h=1}^H x_jw_{jh}z_h\\]\n\nwhere $a_j$ is the offset for the visible unit j and $b_h$ is the offset for the hidden unit h.\n\n\\begin{figure}[!h]\n    \\center\n    \\includegraphics[scale=0.5]{./figures/autoencoder_rbm.png}\n    \\caption{Diagram of a RBM}\n\\end{figure}\n\nThe goal is to model the probability distribution $P(\\textbf{x})$, with : \\[P(\\textbf{x}) = \\frac{\\exp(-\\mathcal{F}(\\textbf{x}))}{Z}\\]\n\nwhere $\\mathcal{F}$ and $Z$ are respectively the free energy and the partition function (which is a normalizing factor), with :\n\\[ \n\\left\\{\n  \\begin{array}{rcc}\n    \\mathcal{F} & = & - \\log\\sum\\limits_{\\textbf{z}}\\exp(-E(\\textbf{x},\\textbf{z})) = - \\sum\\limits_{j=1}^p a_jx_j - \\sum\\limits_{h=1}^H\\log\\sum\\limits_{z_h}e^{z_h(b_h+\\sum_{j=1}^pw_{jh}x_j)}\\\\\n    Z & = & \\sum\\limits_{\\textbf{x}\\in\\omega}\\exp(\\mathcal{F}(\\textbf{x}))\\\\\n  \\end{array}\n\\right.\n\\]\n\n\\subsection{Deep architectures}\nIt should be noted that by stacking RBM (outputs of RBM become inputs for other subsequent RBM), we get Deep belief networks.\n\n\\begin{figure}[!h]\n    \\center\n    \\includegraphics[scale=0.5]{./figures/autoencoder_deepbelief.png}\n    \\caption{Diagram of a deep belief network}\n\\end{figure}\n\n\\end{document}\n", "meta": {"hexsha": "9eee99f9f84c7c4a222c16b3c69a22473cabe70c", "size": 10708, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "lecture_notes/chap11_dimred.tex", "max_stars_repo_name": "chagaz/ma2823_2016", "max_stars_repo_head_hexsha": "9a963f800b4eb35ccee4f8fe347f11ea221cad58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2016-09-13T16:35:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T02:16:53.000Z", "max_issues_repo_path": "lecture_notes/chap11_dimred.tex", "max_issues_repo_name": "chagaz/ma2823_2016", "max_issues_repo_head_hexsha": "9a963f800b4eb35ccee4f8fe347f11ea221cad58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-10-03T10:42:43.000Z", "max_issues_repo_issues_event_max_datetime": "2016-10-03T10:43:16.000Z", "max_forks_repo_path": "lecture_notes/chap11_dimred.tex", "max_forks_repo_name": "chagaz/ma2823_2016", "max_forks_repo_head_hexsha": "9a963f800b4eb35ccee4f8fe347f11ea221cad58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 62, "max_forks_repo_forks_event_min_datetime": "2016-09-07T06:25:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-30T13:21:05.000Z", "avg_line_length": 56.9574468085, "max_line_length": 437, "alphanum_fraction": 0.7506537168, "num_tokens": 2710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.34093239668709086}}
{"text": "\\subsection{Identification of Informative Variants for the Chip Array}\n\nFor identification of informative variants on the chip array, we will utilise a hybrid algorithm with cycles of LD based pairwise tagging, and imputation, as has been previously described.\\cite{Hoffmann2011422} Only populations with at least 50 samples will be included in the chip design process, as pairwise LD evaluation would be difficult in smaller samples. Because different sample sizes affects LD calculations,\\cite{Jorde2000}\\cite{Peer2006} we randomly downsample populations to a maximum size of 100 samples. Here, the term ‘population’ should be considered distinct from an ethno-linguistic group/project, and constitutes a group of individuals/samples that appear genetically homogeneous, without any significant substructure or clustering. In order to account for different sample sizes and LD differentiation among populations, we will carry out multi-population pairwise tagging, as described below. We seek only to tag common SNPs (MAF\\textgreater5\\%) for generation of this array.\n\nWe have developed a multi-population tagging algorithm based on the algorithm TAGster for WGS data.\\cite{Xu2007} The methods we used for tagging were identical to those used by TAGster; however, by using seeking and indexing approaches we were able to optimise the computational efficiency of the algorithm by an order of magnitude (unpublished data, Carstensen et al.). We briefly outline the tagging algorithm as follows (Figure 2):\n\n\\begin{enumerate}\n\\item Calculate LD (\\textit{r}\\textsuperscript{2}) between each SNP and all other SNPs in the flanking 250 KB region for each population separately. MAF thresholds are imposed at this stage, and only pairs of SNPs where both exceed the MAF threshold are included.\n\\item For each SNP not already in the tagging set, a count of SNPs in the target set that are in LD exceeding a given threshold \\textit{r}\\textsuperscript{2} with it is generated across the genome and summed across all populations.\n\\item The most informative SNP (the SNP with most target SNPs in LD with it summed across population) is chosen as the tagging SNP and added to the set of tagging SNPs. If two SNPs have the same ranking, then a SNP is chosen by one or all of the following parameters in order of preference: 1) presence on existing SNP arrays (count), 2) presence in 1000G and/or dbSNP (binary), 3) location within a gene region (binary), 4) binned genotyping score provided by the vendor, 5) rate of heterozygosity across all populations (continuous).\n%We do not take the vicinity to existing tag SNPs into account, despite  SNPs in close proximity being able to interfere with each other when assayed.\\cite{21535878} We expect the algorithm to avoid this problem, because SNPs in proximity of each other are also likely to be in LD with each other.\n\\item This tagging SNP and SNPs in LD with it are now removed from the set of target SNPs. This process is carried out separately for each population, so that a separate set of target SNPs is maintained for each population set. However, SNPs in LD with the tagging SNP can still be picked up as tagging SNPs themselves if they independently tag the maximum no. of SNPs in any iteration.\nSteps 2-3 are repeated until either a specified number of SNPs or all target SNPs (chosen as SNPs above a specific MAF threshold per-population) are tagged across all population sets, or until a specific number of SNPs is reached, as specified.\n\\end{enumerate}\n\nAlthough this method works well across populations, it only carries out pairwise single-marker tagging. Haplotype based, or multi-marker tagging would potentially be more efficient, and select fewer tagging sites. In order to incorporate haplotype based tagging into our model, we use a hybrid method, with cycles of tagging and imputation, as has been described before.\\cite{Hoffmann2011422}\n\n\\begin{figure}[!htbp]\n\\centering\n\\includegraphics[width=0.8\\textwidth]{tagSNPselection}\n\\caption{Hybrid tagging and imputation algorithm for chip design.}\n\\end{figure}\n\nWe implement this method by selecting a maximum number of pre-defined tagging SNPs in the first cycle. With these tagging SNPs we simulate a chip for each population, and imputation is carried out using a reference panel, to identify additional sites in each population that are tagged at an $r^{2}$ threshold above 0.80 by the tagging sites. These sites are removed from the target set for each population, and do not contribute to the next cycle, thereby making the process more efficient. To maximise imputation accuracy we use all samples in table \\ref{tab:samples} for the reference panel and merge this reference panel with haplotypes from all of the 1000G samples from Europe, Asia and the Americas not already present in the reference panel. However, for imputation into each population, all samples from the given population are removed from the reference panel. This ‘leave one population out’ approach would produce relatively conservative results for tagging, with more variants being tagged than if a subsample of the population was included in the reference panel. This is a more realistic scenario, as it is not necessary that any given population genotyped on the chip in future would be represented in the reference panel.\n\nAdditionally, pre-selected known biologically relevant variants, valuable to the studies planned for consortia can be included on the array, to replace certain tag SNPs. We have previously shown that a 1M tagging variants chosen using the described algorithm can produce \\textgreater80\\% coverage across diverse populations in Africa. Based on this, we plan to carry out approximately 10 cycles to capture 1.2M tagging variants, in order to prioritise variants to include in the design of a 1M chip array. Following this, we will further validate our tagging algorithm among populations with smaller sample sizes that were not included in the development in the chip array, by selecting tagging variants among these and imputing with the reference panel, excluding these populations. We estimate coverage of each population by such a chip array using imputation. Coverage is defined as the proportion of common variation captured at a correlation greater than 0.80 across the genome in a given population with the combined reference panel (excluding the population being evaluated). $r^{2}$, here, is calculated as the correlation between the sequence data and imputed data on a hypothetical 1M chip array for common variation. \n\n%Instead of random choice do 1) chip overlap, 2) quality score (VQSLOD and MVNcall posterior), 3) white/black list", "meta": {"hexsha": "670241f516f4c19e921073e12226363a5db06de7", "size": 6652, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ADRP/sections/4tagSNPselection.tex", "max_stars_repo_name": "tommycarstensen/first_year_report", "max_stars_repo_head_hexsha": "348a4cf3e796b617360fa28138b425b5818226be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ADRP/sections/4tagSNPselection.tex", "max_issues_repo_name": "tommycarstensen/first_year_report", "max_issues_repo_head_hexsha": "348a4cf3e796b617360fa28138b425b5818226be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ADRP/sections/4tagSNPselection.tex", "max_forks_repo_name": "tommycarstensen/first_year_report", "max_forks_repo_head_hexsha": "348a4cf3e796b617360fa28138b425b5818226be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 237.5714285714, "max_line_length": 1239, "alphanum_fraction": 0.8102826218, "num_tokens": 1422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.34091017264650286}}
{"text": "%!TEX root = ../main.tex\n%TODO: Redo the flowchart with updated and more specific steps\n\nThe input to our problem is a fiducial marker $F$ that provides the object position in the real world, and a 3D mesh $M$ that will be rendered in Augmented Reality. The method will calculate the properties of a set of light sources $L_i$, specifically position, rotation, intensity and color. In order to analyze the luminance ($L()$), a $360^{\\circ}$ panoramic image is required, generated as a pre-processing step as explained in chapter \\ref{theory}. The complete process is depicted in the flowchart in Figure \\ref{flowch}, and each step is consequently described in more detail according to the mentioned sections.\n\\begin{figure}[H] \n  \\centering\n  \\setlength{\\unitlength}{\\textwidth} \n    \\begin{picture}(1,0.5)\n       \\put(-0.1,0){\\includegraphics[width=1.3\\unitlength]{Figures/Flowchart.png}}\n       \n    \\end{picture}\n    \\caption{Our method in a nutshell.}\n    \\label{flowch}\n\\end{figure} \n\n\\section{Capture $360^{\\circ}$ panoramic image}\nWe use panoramic images as a pre-process. As such it's not within the scope of the method to define a new way of capturing $360^{\\circ}$ images. The application we used to procure a spherical panoramic image within the device itself is Google Street View. This application guides the user through the process of generating the $360^{\\circ}$ panorama. In total 44 photos are necessary and the application shows an orange dot on the screen on the point where the user has to point the camera next. This functionality was originally conceived to capture outdoors scenes, but if the user stands roughly in the middle of a room it works to capture indoors scenes as well.\\newline\nWe ask the user to provide the origin of the virtual world by rotating the virtual reflective sphere so that the view of the room aligns with that of the section of the real room that the camera is facing. This also simplifies calculations of light orientations later on.\n\n\\section{Light source filtering}\\label{lsf}\nWe factor out the luminance from the RGB representation of the panorama. This is achieved by the following equation:\n\\begin{equation}\n  \\forall \\  P_{ij}; L(P_{ij}) = 0,2126 \\cdot R_{ij} + 0,7152 \\cdot G_{ij} + 0,0722 \\cdot B_{ij} ,\n\\end{equation}\nwhere $L$ is the luminance obtained at D65 white point and $P$ is the pixel in the $i,j$ position of the image and $R,G,B$ are the red, green and blue components of the pixel, respectively. \\newline\nThe contrast ratio has to be adjusted, so that the regions with high luminance are more clearly separated.\n\n\\begin{equation}\n     g(i,j) = \\alpha \\cdot L(P_{ij}) + \\beta\n\\end{equation}\n\nWhere $g(i,j)$ is the adjusted image, $L(i,j)$ is the original grayscale image and $\\alpha$ and $\\beta$ are the brightness and contrast constants respectively, determined by parameter tuning. We carried out the parameter tuning in a trial-and-error basis, by using initial extreme values and run the program, and varying the values in order to achieve the best result. The values that worked in the implementation were $\\alpha = 220$ and $\\beta = 255$.\nIn order to prevent outlier pixels and noise from causing false positives, we normalize $g(i,j)$ as follows:\n\\begin{equation}\n    N(g_{ij}) = \\frac{ 2 \\cdot g_{ij} }{min(L) + max(L)},\n\\end{equation}\nWhere $min(L)$ and $max(L)$ are the overall minimum and maximum luminance values in the image. \n\\newline\nThe result of these steps is a black and white image with the rough shape of the light source. We call these shapes \\emph{regions of high luminance}. If there are no regions of high luminance in the image at all it means that no relevant light sources were found. A region of high luminance in the image is formally defined as follows:\n\\begin{equation}\n    R(H) = \\{p_{00}, p_{01}, ... , p_{mn}\\},\n\\end{equation}\n where $p_{ij}$ is the pixel in the i,j position of the image, so that \n\\[\n    L(p_{ij}) \\leq 0.9 \\cdot max(L(p_{ij})) \n\\]\nThe region must also be connected side-by-side, so the pixels must be adjacent.\\newline\nRegions of high luminance are for the most part characterized by much noise and artifacts. These are caused by clear objects, reflections of light sources on polished surfaces, and even light sources that are far away, but don't contribute an important amount of light to the area of interest. Therefore, it's necessary to also add further filtering to the pipeline. \\newline\nThe amount of light that a lighting source contributes to a given scene is directly proportional to the emission area of that source. When analyzing a photograph this area translates to the pixel size of the light source in the image. So we consider this to be a good measure for filtering. Figuring what constitutes an acceptable region size to determine if we have to filter a the light source is a challenging problem for which we couldn't find an existing solution. The approach we took is to define a percentage of the width and height of the overall image as a threshold in search for the best solution. The size filter is then:\n\\begin{equation}\n    width(R(H)) \\cdot height(R(H)) \\geq k \\cdot W \\cdot H\n\\end{equation}\nWhere $k$ is the threshold, in the implementation the value that yielded the best results was $k = 0.004$; $W$ and $H$ are the total image width and height.\\newline\nEach identified region of high luminance that passes all the filters is a light source used at runtime. We capped the maximum amount of light to 8 in practice. We decided to use a maximum of 8 for a few reasons. With more than 8 light sources it becomes challenging to keep the scene from being too lit, even normalizing the intensities. Since we're calculating shadows for each light source, we found that doing it for more than 8 light sources made this process a bottleneck that caused the whole application performance to drop. \\newline\n\n\\section{Calculate light properties}\nWe need to calculate position, orientation, intensity, and color for each light, remembering that we have the original full color image available.  \\newline\n\\begin{enumerate}\n\\item  \\textbf{Orientation}: This process is carried out with an array $P_i$ of points containing the pixel coordinates $(x,y)$ of the regions of high luminance; the normalized luminance analysis image $N(g_{ij})$ mapped on a sphere $S$ and a camera $C$ facing the sphere from four different points of view (in order to cover a full revolution). The orientation of the pth light source $O(L_p)$ is calculated as follows:\n\\begin{algorithm}[H]\n\\caption{Light source orientation calculation}\\label{alg:orientAl}\n\\begin{algorithmic}[1]\n\\For{\\texttt{i $\\in[1,4]$}}\n    \\For{\\texttt{each pixel in camera view}}\n        \\State \\texttt{Cast ray to $S$}\n        \\If {Color at hit point $H$ is white AND $H=P_p$}\n            \\State \\texttt{Calculate $O(L_p)$:}\n            \\begin{equation}\n            O(L_p) = -2 \\cdot (N_h \\cdot C_r) N_h + C_r,\n            \\end{equation}\n            \\NoNumber{ $N_h$: normal of $S$ at $H$.}\n            \\NoNumber{$C_r$: camera ray direction.}\n\n            \\State \\texttt{Normalize $O(L_p)$:}\n            \\begin{equation}\n            O(L_p)_N = (\\frac{O(L_P)_x}{|O(L_P)|}, \\frac{O(L_P)_y}{|O(L_P)|}, \\frac{O(L_P)_z}{|O(L_P)|})\n            \\end{equation}\n        \\EndIf\n    \\EndFor\n    \\State \\texttt{Obtain the next camera view by rotating $C$ $90^{\\circ}$ clockwise around the $y$ axis of $S$}\n\\EndFor\n\\end{algorithmic}\n\\end{algorithm}\nThis process is depicted in Figure \\ref{camMov} for further clarification. The figure shows the vectors $N_h$ and $C_r$, the $C$ orbiting $S$ and the four distinct points of view with which $C$ reconstructs the entire $360^{\\circ}$ environment.\n\\begin{figure}[H] \n  \\centering\n  \\setlength{\\unitlength}{\\textwidth} \n    \\begin{picture}(0.75,0.5)\n       \\put(-0.1,0){\\includegraphics[width=1.0\\unitlength]{Figures/camMov.png}}\n       \n    \\end{picture}\n    \\caption{Illustration of the computation of the light orientations based on the virtual reflective sphere.}\n    \\label{camMov}\n\\end{figure} \n\\item \\textbf{Position}: With the orientation calculated in the previous step we know the angles of the light source with respect to the marker $F$. What we don't know is how far away along that vector the light actually is. In order to approximate the distance from a camera to an object in a photograph we can use triangle similarity, the device's known camera parameters and a known object size. The ratio of the size of the object on the camera sensor and the size of the object in real life is the same as the ratio between the focal length of the lens and distance to the object.\nWe use the average of a light source's height to approximate the desired distance:\n\\begin{equation}\n   D = \\frac{f \\cdot h(O_r) \\cdot h(L)}{h(O_p) \\cdot h(s)},\n\\end{equation}\nwhere $f$ is the camera aperture size, $h(O_r)$ and $h(O_p)$ are the real object height in millimeters (the value we used is 200 mm) and the image object height in pixels, respectively; $h(L)$ is the height of the full image and $h(s)$ is the camera sensor height.\n\n\\item \\textbf{Color}: Storing both versions of the panorama, one in full color and another one after processing, allows us to have both the color and the luminance information. Once a light source is detected, the equivalent area in the color image is averaged to determine the color of the light source. We obtain the linear average of each individual color channel and use the combined results.\n\\item \\textbf{Intensity}: There are two factors that influence the intensity of a light as perceived by a camera, the light size and the color temperature. The light's color temperature in Kelvin is calculated using the approximation proposed by \\citep{mccamy1992}, as follows:\n\\begin{equation}\n    T(C_p) = -949.86315 + 6253.80338 ^ {\\frac{-n}{0.92159} } + 28.70599 ^{\\frac{-n}{0.20039} } + 0.00004 ^ {\\frac{-n}{0.07125} }\n\\end{equation}\n\\begin{equation}\nn = {\\frac{0.23881\\cdot R + 0.25449\\cdot G - 0.58291\\cdot B}{0.11109\\cdot R - 0.85406\\cdot G + 0.52289\\cdot B} }\n\\end{equation}\n\nWhere $R, G, B$ are the red, green and blue components of the light color.\\newline \nThe other significant factor to determine the light intensity is the size. In our method the size is given by the integral of the region of high luminance with respect to the full image.\\newline\nThe light intensity is finally expressed by:\n\\begin{equation}\nI(L_p) = T(C_p) \\cdot \\int_{R(L_p)} N(g_{ij}) \\,d\\mu\n\\end{equation}\nWhere $N(g_{ij})$ is the output image of the luminance analysis and $R(L_p)$ is the $p^{th}$ region of high luminance. $I(L_p)$ is the scalar value that denotes the intensity of the light source at runtime.\\newline \n\n\\end{enumerate}\n\n\\section{Calculate ambient light}\nSince a panoramic image of the environment is already available, we can use it to implement environment mapping. However, asking the user to capture the environment more than once in order to carry out the Tone Mapping would have a bad impact on user friendliness. It is also highly unlikely that the produced image would have the exact same framing every time. Alternatively, we produce the different exposure values for the Tone Mapping by altering the brightness and contrast values of the base image using equation 4.2 once again. Afterwards, we produce the HDR image using the \\citet{Debevec} weighting algorithm.\\newline\n\n\\section{Real-time Phase}\nWe use the original spherical panoramic image to create a cubemap of the real environment for ambient lighting, to calculate the ambient contribution of the diffuse shaders and to use as reflections for the specular shaders.\n\\begin{enumerate}\n\n\\item \\textbf{Cubemap:} We take the polar coordinates of a unit sphere $(1,\\theta,\\phi)$. The image coordinates are divided into four regions by latitude $-\\pi/4 < \\theta < \\pi/4 , \\pi/4 < \\theta < 3\\pi/4, 3\\pi/4 < \\theta < 5\\pi/4, 5\\pi/4 < \\theta < 7\\pi/4$. These represent either one of the four faces of the cube, top or bottom. The projected coordinates are given by:\n\\begin{equation}\nP_c = (1, tan(\\phi), \\frac{cot(\\theta)}{cos(\\phi)}),\n\\end{equation}\n The process is further explained in Figure \\ref{cubeMap}.\n \\begin{figure}\n  \\centering\n  \\setlength{\\unitlength}{\\textwidth} \n    \\begin{picture}(0.75,0.5)\n       \\put(-0.1,0){\\includegraphics[width=1.0\\unitlength]{Figures/cubemapping.png}}\n       \n    \\end{picture}\n    \\caption{The cubemap creation process.}\n    \\label{cubeMap}\n\\end{figure} \n \n The projected points for each face of the cube are composed into an image and each image stitched together to create a cross cube map.\n \n \\item \\textbf{Ambient contribution:} The environment lighting contribution is done with a shader. The ambient contribution is reduced to a single value in the range of $0$ and $1$ and applied to the diffuse color component. The result is a dimmer color when the ambient light is low. \n The ambient contribution value $A_c$ for each region of high luminance $R(L(P_{ij}))$ in the luminance analisys image $N(g_{ij})$ is given by:\n \\begin{equation}\n \\forall R(L(P_{ij}));A_c = \\frac {\\sum_{i=1,j=i} R(L(P_{ij}))}{width(R(L(P_{ij}))) \\cdot height(R(L(P_{ij})))}\n \\end{equation}\n \n \\item \\textbf{Reflections:} The cubemap from step 1 is also used to for reflections. A vector is cast from every vertex of the object along its normal and intersected with the cubemap generated from the panoramic image. The texture color is mixed with the diffuse color according to the specularity defined for the material to simulate reflection, this information is calculated in advance and used at runtime. \n \n \\item \\textbf{Shadows:} During early experiments it became clear that one of the bigger differences between real and virtual object were a product of the shadows as well as the light. A problem when it comes to casting shadows for virtual objects in AR is the fact that there has to be an object underneath $M$ to cast the shadow on. But this object has to be as unobtrusive as possible. We worked around this issue by using a transparent material on a plane that receives shadows. $M$ is projected on the plane from each light source and rendered flat in black color.\n \n\\end{enumerate}", "meta": {"hexsha": "8caac48efb769d7560d99ef772334c19316758eb", "size": 14130, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Handins/Thesis/method.tex", "max_stars_repo_name": "samssonart/gmtThesisAR", "max_stars_repo_head_hexsha": "14813a2efb2e7fcf0aaf753ca68ab3ed7edcbd2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Handins/Thesis/method.tex", "max_issues_repo_name": "samssonart/gmtThesisAR", "max_issues_repo_head_hexsha": "14813a2efb2e7fcf0aaf753ca68ab3ed7edcbd2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Handins/Thesis/method.tex", "max_forks_repo_name": "samssonart/gmtThesisAR", "max_forks_repo_head_hexsha": "14813a2efb2e7fcf0aaf753ca68ab3ed7edcbd2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 90.5769230769, "max_line_length": 674, "alphanum_fraction": 0.744373673, "num_tokens": 3616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.34091016640104055}}
{"text": "\\documentclass[12pt,a4paper,titlepage,final]{article}\n\n\\usepackage[czech,english]{babel}\n\\usepackage[utf8]{inputenc}\n\\usepackage{dirtytalk}\n\\usepackage[bookmarksopen,colorlinks,plainpages=false,urlcolor=blue,unicode]{hyperref}\n\\usepackage{url}\n\\usepackage{amsthm}\n\\usepackage[dvipdf]{graphicx}\n\\usepackage[top=3.5cm, left=2.5cm, text={17cm, 24cm}, ignorefoot]{geometry}\n\\everymath{\\displaystyle}\n\n\\begin{document}\n\n\\def\\author{Attila Večerek}\n\\def\\email{xvecer17@stud.fit.vutbr.cz}\n\\def\\projname{Demonstartion of Basic Fuzzy Set Operations }\n\n\\input{title.tex}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% obsah\n\\pagestyle{plain}\n\\pagenumbering{Roman}\n\\setcounter{page}{1}\n\\tableofcontents\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% textova zprava\n\\newpage\n\\pagestyle{plain}\n\\pagenumbering{arabic}\n\\setcounter{page}{1}\n\n%=============================================================================\n\n\\section{Introduction} \\label{introduction}\nThis report discusses and presents the design and implementation of a desktop application capable of demonstrating the 3 basic erations over fuzzy sets:\n\n\\begin{itemize}\n\\item union,\n\\item intersection,\n\\item and complement.\n\\end{itemize}\n\nThe assignment has stated to demonstrated these operations over \\textit{discrete} fuzzy sets. However, this report discusses the solution of operations over \\textbf{continuous} fuzzy sets.\n\n%=============================================================================\n\n\\section{Theory} \\label{theory}\nIn this section, we will briefly cover the theoretical knowledge needed for this project.\n\n\\subsection{Fuzzy set}\nA \\textbf{fuzzy set} is a generalization of an ordinary set by allowing a \\textbf{degree} (or \\textbf{grade}) \\textbf{of membership} for each element. A membership degree is a real number on [0, 1] \\cite{fuzzy}.\n\n\\subsection{Membership function}\nThe \\textbf{membership function} of a set maps each element to its degree. Having the elements of the set being associated with a degree of membership is the foundation of fuzzy sets as well as fuzzy systems \\cite{fuzzy}.\n\n\\subsection{Universe}\nThe \\textbf{universe} represents a regular set of elements that have an associated degree of membership in a given fuzzy set.\n\n%=============================================================================\n\\section{Design} \\label{design}\nThe application has been designed to satisfy the following requirements from the perspective of a user:\n\n\\begin{enumerate}\n\\item it should be possible to define a common universe to the fuzzy sets,\n\\item it should be possible to define upto 2 fuzzy sets by their respective names (optionally) and membership functions,\n\\item it should be possible to define the membership function as a mathematical expression,\n\\item and it should be possible to run the operations only in cases, when all the necessary input has been given.\n\\end{enumerate}\n\n\\subsection{Logic} \\label{logic}\nThe logic of the application is responsible for all the computation required for parsing the user input as well as processing the fuzzy operations. The fuzzy model consists of 3 main classes: \\texttt{FuzzySet}, \\texttt{FuzzyMember} and \\texttt{MembershipFunction}. The MembershipFunction class is dependant on the \\texttt{Math} subpackage which is responsible for parsing the membership function input by the user. In order to parse and evaluate math expressions, the \\textbf{com.scireum.Parsii} open-source module has been chosen as a project dependency \\cite{parsii}.\n\n\\noindent\n\\begin{figure}[h]\n\\centering\n\\includegraphics[width=1.0\\textwidth]{img/model-UML}\n\\caption{The logic of the application}\n\\label{fig:model}\n\\end{figure}\n\nParsii has been chosen because of its ease of use and integration as well as it is one of the fastest expression evaluators implemented in Java based on an article published by \\url{http://www.javacodegeeks.com/} \\cite{performanceTest}.\n\nTo define a discrete universe to the fuzzy sets, the user needs to specify a range or several ranges of decimal numbers, i.e. the range \\texttt{1..10} stands for a left-closed and right-open interval between 1 and 10, whereas \\texttt{1...10} marks a closed interval. Notice the difference in the number of dots in the respective examples. The universe can also be defined by a list of ranges separated by a sequence of characters described by the regular expression \\verb|,\\\\s^{+}|.\n\n\\subsection{Front-end} \\label{ui}\nThe application follows the design pattern called MVC which stands for Model-View-Controller. The Figure \\ref{fig:guiUML} represents the dependencies between the packages and the communication flow between the instances of the respective classes. The \\texttt{MainController} consists of an instance of \\texttt{FuzzyLineChart} to be able to operate with it (\\verb|initialize| and \\verb|update| operations). It also communicates with the \\texttt{ApplicationHelper} class which is responsible for creating the user-defined universe. Both the \\texttt{MainController} and \\texttt{ApplicationController} utilize the \\texttt{Model} package described in the above section to be able to create the necessary fuzzy sets and run the user-selected operations above them. The \\texttt{FuzzyLineChart} class wraps a \\textbf{JavaFX LineChart} and populates it with the required datapoints obtained by the \\texttt{MainController}, thus rendering the expected chart output.\n\n\\noindent\n\\begin{figure}[h]\n\\centering\n\\includegraphics[width=0.7\\textwidth]{img/gui-UML}\n\\caption{Frontend design}\n\\label{fig:guiUML}\n\\end{figure}\n\n\\subsubsection{User Experience}\nA good user experience is never bad. With that and the best practices in mind, the user interface has been divided into two integral parts as it is seen in Figure \\ref{fig:gui}. The bigger part of the screen is assigned to the description of the fuzzy operation and its result. On the right side of the screen, there is the pane that serves the purpose of inputting all the information in relation to the fuzzy sets and the operations to be done over them.\n\n\\noindent\n\\begin{figure}[h]\n\\centering\n\\includegraphics[width=1.0\\textwidth]{img/gui}\n\\caption{The graphical user interface}\n\\label{fig:gui}\n\\end{figure}\n\n\\paragraph{Error messages}\nThere are 4 possible error messages in relation to invalid input:\n\\begin{enumerate}\n\\item the definition of the universe is not parsable,\n\\item the membership function is not parsable,\n\\item the membership function cannot be evaluated,\n\\item the same name has been given to the fuzzy sets.\n\\end{enumerate}\n\nA valid universe definition can be either a range, list of several ranges or an enumeration of decimal numbers. In all other cases it invokes an error message which is a hyperlink leading to the Git repository of the project and its \\texttt{README} file as seen in Figure \\ref{fig:universeDefinitionError}.\n\nThe membership function is parsable and evaluable if it is an expression parsable by the \\texttt{com.scireum.Parsii} module and it contains exactly one variable, i.e. the \\verb|x| in expression \\verb|abd(sin(x))|. Otherwise the respective errors would rise up as seen in Figure \\ref{fig:membershipParseError} and \\ref{fig:membershipEvalError}.\n\n\\begin{figure}[!htb]\n\\minipage{0.32\\textwidth}\n  \\includegraphics[width=\\linewidth]{img/universe-definition-error}\n  \\caption{Parse error U}\\label{fig:universeDefinitionError}\n\\endminipage\\hfill\n\\minipage{0.32\\textwidth}\n  \\includegraphics[width=\\linewidth]{img/membership-parse-error}\n  \\caption{Parse error memb()}\\label{fig:membershipParseError}\n\\endminipage\\hfill\n\\minipage{0.32\\textwidth}\n  \\includegraphics[width=\\linewidth]{img/membership-evaluation-error}\n  \\caption{Eval error memb()}\\label{fig:membershipEvalError}\n\\endminipage\n\\end{figure}\n\nThe fourth error message occurs when both fuzzy sets have been assigned with the same name as it is shown in Figure \\ref{fig:setNameError}.\n\n\\begin{figure}[!htb]\n\\minipage{0.45\\textwidth}\n  \\includegraphics[width=\\linewidth]{img/set-name-error}\n  \\caption{Identical set name error} \\label{fig:setNameError}\n\\endminipage\\hfill\n\\minipage{0.45\\textwidth}\n  \\includegraphics[width=\\linewidth]{img/buttons-disabled}\n  \\caption{Eval error memb()}\\label{fig:disabledButtons}\n\\endminipage\n\\end{figure}\n\n\\paragraph{Action Buttons}\nIn order to prevent any further errors, the respective action buttons are enabled only in case that all the required fields have been filled out and the input information is valid. The Figure \\ref{fig:disabledButtons} shows that the binary operations are disabled when only the first fuzzy set has been set up.\n\n\\noindent\n\\begin{figure}[!h]\n\\centering\n\\includegraphics[width=0.7\\textwidth]{img/line-chart}\n\\caption{The line chart}\n\\label{fig:lineChart}\n\\end{figure}\n\n\\paragraph{Line Chart}\nThe line chart is the most important element of the UI. It presents the result of the basic operations over the specified fuzzy sets. The following information are always shown to the user, so he is always aware of the currently presented fuzzy operation and its details: \\textit{title of the operation}, the \\textit{line chart} and the \\textit{legend}. An example can be seen in Figures \\ref{fig:gui} and \\ref{fig:lineChart}.\n%=============================================================================\n\\section{Implementation} \\label{implementation}\nThe desktop application has been implemented in Java 8. It uses the \\texttt{com.scireum.Parsii} module to parse and evaluate mathematical expressions. The GUI is implemented using the \\texttt{JavaFX 8} library. The tests are written in \\texttt{Groovy} using the \\texttt{Spock} framework. \n\nAs it has already been mentioned, the application is capable of operating with fuzzy sets defined by a \\textit{continuous} universe. In this section we will describe and discuss the implementation of exactly this issue.\n\n\\subsection{Discrete vs. continuous}\nA digital computer is not able to work with continuous data in their raw form. It uses sampling with an approriate sampling rate to create a set of discrete data it can finally process and operate with. However, the sampling frequency can be set very high, so the produced discrete data may seem for the human eye as continuous. That is exactly the same procedure our desktop application has adopted.\n\n When a user specifies the universe with a range, e.g. \\texttt{0...1}, the application has to decide about the appropriate sampling rate. Too high sampling could be very memory inefficient. On the other hand, too low sampling rate would cause a non-linear member function to loose its \\say{curviness}. To find an optimum, the application examines the width of the linechart in pixels. That number is considered as the maximal number of datapoints presented on the chart. Assume the formerly defined universe with the range of \\texttt{0...1} and a line chart of a 100 pixels width. It means that the specified interval needs to be discretized into 100 evenly distributed data points across that interval.\n \n The next step is to compute the \\textit{precision}. In the above example of a closed range the computation would look as following. Let us assume an unrealistic case of a 5 pixels wide linechart to make the example trivial. The step would be then equal to $\\frac{1 - 0}{5 - 1} = 0.25$. If it were a left-closed and right-open range, the computation would be as follows: $\\frac{1 - 0}{5} = 0.2$.\n \n \\subsection{The algorithm}\n The application operates with only as many datapoints as needed in order to be memory and computation efficient. The following steps describe the workflow that takes place since the start until the end which in our case means that the line chart is populated with data and presented to the user.\n \n \\begin{enumerate}\n \\item The user enters a \\texttt{String} as an input in the universe definition text field.\n \t\\begin{enumerate}\n \t\\item The \\verb|ApplicationHelper| class checks, whether the input matches an acceptable format.\n \t\\item If the given input has been evaluated as invalid, the \\verb|MainController| sets the error message visible. Otherwise, it does not do anything.\n \t\\end{enumerate}\n\\item The user fills out the member function text field.\n\t\\begin{enumerate}\n\t\\item The \\verb|MainController| invokes a method chain leading to the \\texttt{Parsii} module which parses the member function.\n\t\\item If the given input is not parsable or contains more than 1 variable, an appropriate error message will be set visible.\n\t\\end{enumerate}\n\\item The user clicks the Complement operation action button.\n\t\\begin{enumerate}\n\t\\item The \\verb|MainController| obtains the width of the line chart and sets the \\texttt{precision} accordingly.\n\t\\item Then, it creates the universe which is  a \\verb|Set| of \\verb|FuzzyMember|s generated by the \\verb|Range| class.\n\t\\item After the universe is created, the user-specified \\verb|FuzzySet| is instantiated.\n\t\\item In the following step, the complement of the instantiated \\verb|FuzzySet| is created.\n\t\\item Lastly, the \\verb|MainController| populates the line chart with the created fuzzy sets in the exact same order as they have been created. It assures that the data points of the complement fuzzy set will overwrite the data points of the user-specified fuzzy set in the chart.\n\t\\end{enumerate}\n \\end{enumerate}\n \n \\noindent\n\\begin{figure}[!h]\n\\centering\n\\includegraphics[width=1.0\\textwidth]{img/discontinuous-ranges}\n\\caption{Line chart lacking discontinuity}\n\\label{fig:discontinuousRanges}\n\\end{figure}\n\n\\subsection{Known issues}\nThe application is able to present fuzzy sets defined by continuous universes. However, it cannot handle disconinuity. Assume a case when multiple ranges have been specified as the universe by the user, e.g. \\verb|1...10, 20...30|. The LineChart of the JavaFX library does not offer any tool to handle such situations. It connects the specified datapoints with a straight line. Having said that, such definitions of the universe may lead to results as seen in Figure \\ref{fig:discontinuousRanges}. A possible solution would be to inject another datapoint before the start and after the end of each range with a membership degree of \\verb|Double.NaN|. This way the last point of a range and the first point of the following would be connected somewhere outside - in the undefined part of the line chart.\n\n%=============================================================================\n\\section{Conclusion} \\label{conclusion}\nThis report introduced a desktop application capable of operating with fuzzy sets defined by a continuous univers and a member function as a mathematical expression and demonstrate the 3 basic fuzzy operations over them. We presented the design of the application along with the implementation details and had a more in-depth discussion about challanges met during the development of the project regarding the representation of continuous data sets on a discrete system.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% seznam citovana literatury: kaada poloaka je definovana paakazem\n% \\bibitem{xyz}, kde xyz je identifikator citace (v textu pouaij: \\cite{xyz})\n\\newpage\n\\begin{thebibliography}{1}\n\\bibitem{fuzzy}\nT. Munakata. Fundamentals of the New Artificial Intelligence. Springer Science, 2008\n\\bibitem{parsii}\nAndreas Haufler. scireum/parsii. \\url{https://github.com/scireum/parsii}\n\\bibitem{performanceTest}\nAndreas Haufler. How to write one of the fastest expression evaluators in Java? \\url{https://www.javacodegeeks.com/2014/01/how-to-write-one-of-the-fastest-expression-evaluators-in-java.html}\n\\end{thebibliography}\n\n\\end{document}\n", "meta": {"hexsha": "4f0a39148fcac72cbb2066ab1018f4b845eb8b41", "size": 15590, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/technical-report.tex", "max_stars_repo_name": "vecerek/fuzzy_set_operations", "max_stars_repo_head_hexsha": "d59e31ecfa32b03c6f062a9d5777c67835430d79", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/technical-report.tex", "max_issues_repo_name": "vecerek/fuzzy_set_operations", "max_issues_repo_head_hexsha": "d59e31ecfa32b03c6f062a9d5777c67835430d79", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/technical-report.tex", "max_forks_repo_name": "vecerek/fuzzy_set_operations", "max_forks_repo_head_hexsha": "d59e31ecfa32b03c6f062a9d5777c67835430d79", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 68.0786026201, "max_line_length": 955, "alphanum_fraction": 0.7611930725, "num_tokens": 3681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.340874177113215}}
{"text": "%!TEX root = ../../dissertation.tex\n\n\\section{Properties of the exchange economy}\n\\label{sec:properties}\n\nWe compute an accurate global solution to the scaled Pareto problem\nby methods described in Appendix \\ref{app:computation_BCFL}.\nWe  describe its properties here.\nWe start with the Pareto weight, then go on to explore\nthe dynamics of the Pareto weight,\nthe connection between consumption and the real exchange rate,\nand the responses of consumption and other variables to changes in various state variables.\n\n\n{\\textit The Pareto frontier.\\/}\nOne of the outputs of the numerical solution is the value function $J$, a function of\npromised utility $U$ and the exogenous state variables.\nGiven values for the exogenous state variables, this gives us the Pareto frontier:\nthe highest utility of agent 1 ($J$) consistent with a given level of utility\nfor agent 2 ($U$) and the productive capacity of the economy.\n\nWe describe the Pareto frontier in Figure \\ref{fig:pareto-frontier}\nwith state variables $z_{1t} = z_{2t} = \\wh{z}_t = 1$ and $v_t = v$.\nThe outer curve in the figure is the consumption frontier,\nwhich echoes Figure \\ref{fig:consumption-frontier}.\nThe inner curve is the Pareto frontier.\nWe see that it has much the same shape.\nIt's inside the consumption frontier largely because of risk:\nutility is below consumption because risk reduces utility.\nIf we increase risk aversion to 50 ($\\alpha = -49$, not shown),\nit shifts in further.\n\nChanges in the state variables change both frontiers.\nMovements in productivity and output shift the frontiers --- both of them ---\nin and out ($\\bar{z}_t$, which affects the two intermediate goods proportionately)\nor twist them ($\\wh{z}_t$, which affects the two goods differently).\nChanges in risk twist the Pareto frontier, since risk affects the two goods differently,\nbut not the consumption frontier, since it has no effect on quantities of intermediate goods.\n\n\n{\\textit Dynamics of the Pareto weight.\\/}\nWe see the impact of recursive preferences in Figure \\ref{fig:exchange-pareto-weight-two},\nwhere we graph $\\log \\lambda^*_t $ against time for a (very long) simulation of the model.\nThe flat horizontal line refers to the additive case ($\\alpha = \\rho = -1$).\nAs we know, the Pareto weight doesn't change in this case.\nThe other line refers to the recursive case, and we see clear variation in the Pareto weight.\nWe also see that the variation is both large and very persistent.\n%Persistence is important, as we'll see, in producing persistent movements in\n%the real exchange rate.\n\nThis touches on a question that's been discussed extensively:\nIs the Pareto weight stable, or does one agent eventually consume everything?\n\\citet{Anderson2005-of} and \\citet{Borovicka2016-rr} document some of the difficulties\nof establishing stability in similar one-good settings.\n\\citet{Colacito2011-zp} prove stability in a two-good\nworld with elasticities of substitution between goods and over time equal to one.\n\\citet{Colacito2013-yq}, \\citet{Kollmann2015-sy}, and \\citet{Tretvoll2011-lo,Tretvoll2015-lo,Tretvoll2018-dj}\nsolve similar models numerically and report that the solutions are stable.\nWe also find that they're stable, but extremely persistent.\n\nWe get a sense of how stability works in Figure \\ref{fig:change-pareto-weight-ra},\nwhere we plot the expected change in the log Pareto weight against its level.\nThe exogenous state variables here have been set equal to their means.\nIn the additive case, the expected (and actual) change is zero.\nThe log Pareto weight is a martingale with no variance.\nWith greater risk aversion, mean reversion becomes evident.\nIf the Pareto weight is below its steady state value of one ($\\log \\lambda_t^* = 0$),\nit's expected to increase.\nIf above, it's expected to decrease.\nThe effect is stronger when we increase risk aversion to 50.\nThere is also an evident nonlinearity in the solution,\nas there is in \\citet[Figure 5]{Colacito2011-zp},\nbut most of it occurs in regions of the state space we rarely reach.\n\n\nThe elasticity of substitution between foreign and domestic intermediate goods\nalso plays a role in persistence.\nSee Figure \\ref{fig:change-pareto-weight-arm}.\nWith smaller values, mean reversion is slower.\nAnd with larger values, it's faster.\nAs the elasticity increases, the line flattens out and we approach\nthe one-good world with a constant Pareto weight.\n\nThe intertemporal elasticity of substitution also has an effect,\nbut with the numbers we've chosen the effect is smaller.\nSee Figure \\ref{fig:change-pareto-weight-ies}.\nEvidently smaller values of $\\rho$, and larger values of the IES [$1/(1-\\rho)$],\nlead to flatter lines.\n\n\n{\\textit Consumption and exchange rate.\\/}\nWe noted earlier that the relation between the log consumption ratio [$\\log (c_{2t}/c_{1t})$]\nand the log of the real exchange rate [$ \\log e_t = \\log (p_{2t}/p_{1t}) $]\nis mediated by the log Pareto weight ($\\log \\lambda^*_t$).\nSee equation (\\ref{eq:cons-rer}).\nIn the additive case, the Pareto weight is constant and we have a\nperfect linear relationship between the two variables.\nWe see exactly this in the line in Figure \\ref{fig:exchange-cons-rer-two}.\n\n\nThe scatter of points in the same figure represents the recursive case,\nwhere the Pareto weight acts like a wedge from the perspective of the additive model.\nWith our numbers, the variation in the Pareto weight is enough to change\na negative correlation of minus one between the consumption ratio and exchange rate\nto a slight positive correlation.\n\\citet{Colacito2013-yq}, \\citet{Kollmann2015-sy}, and \\citet{Tretvoll2011-lo} show the same.\nIf we increase risk aversion $1-\\alpha$ to 50,\nthe correlation becomes strongly positive.\nIn the recursive model,\nwe can produce any correlation we like by varying the risk aversion\nparameter.\n\n\nRecursive preferences also have an impact on exchange rate dynamics\nas the persistence in the Pareto weight is reflected in the real exchange rate.\nWe see in Figure \\ref{fig:rer-acfs} that the additive model is much less persistent:\nThe half-life (where the autocorrelation function equals one-half) is about a year.\nBy five years, the autocorrelation is essentially zero.\nExchange rate dynamics reflect, in this case, the modest persistence of relative productivity $\\wh{z}_t$.\nWith recursive preferences, the exchange rate is much more persistent.\nIn fact with these parameter values, it's virtually a martingale.\nWe can reproduce any level of persistence we like by varying risk aversion\nbetween the two cases.\nThere's a range of opinion, summarized nicely by \\citet{Crucini2008-mi},\nabout how much persistence we need for the model to be realistic.\nThe larger point is that recursive preferences are a device that can deliver\npersistence in real exchange rates and macroeconomic variables in general.\nIt's what an older literature would call a propagation mechanism.\n\n\n{\\textit Responses to productivity and volatility shocks.\\/}\nWe get another perspective on the model's dynamics from impulse responses.\nStarting at the steady state, we increase one of the exogenous state variables\nby one standard deviation at date one, simulate the model for several periods,\nand compute the mean dynamics of all the variables in the model.\nThis goes somewhat beyond traditional impulse responses in linear models in\nwhich the subsequent innovations are turned off.\n\nIn Figure \\ref{fig:irf-zhat}\nwe describe responses to an increase in (the log of) relative productivity $\\wh{z}_t$.\nThe effect on future values of $\\log \\wh{z}_t$ declines at a constant rate\nas described by equation (\\ref{eq:lom-zhat}).\nNeither average productivity $\\bar{z}_t$ nor volatility $v_t$ change,\nso this implies an increase in $\\log z_{1t}$ and an equal decrease in $\\log z_{2t}$.\nThe quantity of apples goes up, and the quantity of bananas goes down.\nBecause of home bias, consumption goes up in country 1 (the apple eaters)\nand down in country 2 (banana eaters).\nThe exchange rate rises as scarce bananas become more expensive.\n\nAll of this would be true in the additive case as well.\nWhat's different is the response of the Pareto weight.\nIt goes up as we compensate the agent in country 2 with promises of higher future consumption.\nThis effect eventually wears off, but it does so very slowly.\n\n\nIn Figure \\ref{fig:irf-v}\nwe describe the responses to an increase in volatility $v_t$.\nHere there's no change in the quantities of intermediate goods.\nIn the additive case, there would be virtually no effect.\nIn the recursive case, utility falls, but it falls more for country 1 because\nof its home bias in favor of the good whose supply has become riskier.\nThe social planner responds by decreasing the Pareto weight\non agent 2.\nConsumption therefore rises in country 1 and falls in country 2.\nThe real exchange rate falls.\nThis is entirely a demand-side effect.\nBy increasing the weight on agent 1, the demand for apples goes up\nand the demand for bananas goes down.\nThe magnitudes are small, but it's an interesting effect that we would like to explore\nfurther in a production economy, where supply can respond to\nchanges in market conditions.\n", "meta": {"hexsha": "74c2a8ccb39d1fa6f64515c98665a0fe4d64c560", "size": 9105, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ms/sections/BCFL/equilibrium.tex", "max_stars_repo_name": "cc7768/Dissertation", "max_stars_repo_head_hexsha": "813210c2f92122bb0c05f6ad7f5a9ede04993781", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ms/sections/BCFL/equilibrium.tex", "max_issues_repo_name": "cc7768/Dissertation", "max_issues_repo_head_hexsha": "813210c2f92122bb0c05f6ad7f5a9ede04993781", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ms/sections/BCFL/equilibrium.tex", "max_forks_repo_name": "cc7768/Dissertation", "max_forks_repo_head_hexsha": "813210c2f92122bb0c05f6ad7f5a9ede04993781", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-12-31T22:54:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-03T18:48:22.000Z", "avg_line_length": 52.9360465116, "max_line_length": 109, "alphanum_fraction": 0.7871499176, "num_tokens": 2116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.34087417711321494}}
{"text": "\\chapter{Darwin Library}\n\\label{sec:darwin_lib}\n\nDarwin is a simple library written in Python for BN modeling and inference.\nThe main purpose of the library is teaching BNs and quick prototyping or testing small networks.\nIn order to achieve these goals, the library has a simplistic approach of implementation, using native Python data structure and light usage of object oriented programming.\nThe structure of Darwin is basically divided into two categories: potentials and graph manipulations.\nThe features are also split into two main categories: inference and modeling tools.\nLater, in this section, we also present a guide for getting started using Darwin.\n\n\\section{Structure}\n\\label{sec:system:sec1}\n\nIn order to work with BNs, Darwin has two main set of implementations: potential and graph manipulations.\nThese two categories form individually or together the tree structure of the library as presented in Figure \\ref{fig:tree_darwin}.\n\n\\begin{figure}[hbt]\n    \\begin{center}\n        \\includegraphics[width=\\textwidth]{img/structure_darwin}\n    \\end{center}\n    \\caption{Three structure of Darwin.}\n    \\label{fig:tree_darwin}\n\\end{figure}\n\nAt the root, the class \\emph{Potential} is a data structure for modeling a probability table.\nThe \\emph{NetworkX} \\cite{hagberg-2008-exploring} is set of data structures for graph manipulation and is also included at the root of the library.\nSimilarly, \\emph{GraphWithPotential} is a class which basically maps nodes in a graph with a set of potentials, besides providing manipulations on the graph and the potentials on it.\n\\emph{BayesianNetwork} is a class that inherits from \\emph{GraphWithPotential} but maps only one potential per node.\nThis data structure is used for modeling a BN.\nIn the same way, the class \\emph{MarkovNetwork} entirely inherits the behaviour and properties of \\emph{GraphWithPotential}, therefore it can be used for MN modeling.\n\nThe \\emph{Utils} branch is formed by a set of standalone functions which implement core procedures for the other classes.\nMainly, these functions are defined by numerical operations on lists of probabilities.\nOne advantage of having those implementations as standalone functions is that future optimized code can be included or modified without disturbing the other classes, since the other classes only makes a function call to those utilities functions.\nBasically, there are three main utilities: \\emph{BnUtils}, \\emph{MnUtils}, and \\emph{PotentialUtils}.\nThe BnUtils has a set of functions for BN manipulations and operations, such as moralization, triangulization, join tree construction, among others.\nIn MnUtils, we have utilities for MN propagation such as finding an optimal path for propagating in a tree.\nLastly, PotentialUtils is formed by a set of procedures for numerical operations such as multiplication, division and marginalization of tables.\nAll potential manipulations in PotentialUtils is implemented according to the efficient implementation proposed in \\cite{koll09}.\n\nIn the \\emph{Modeling} brach, there is an implementation of d-Separation as proposed in Algorithm 3.1 of \\cite{koll09}.\nWhile in the branch \\emph{Inference} there are few data structures useful for exact inference in BNs.\nThe \\emph{Barren} function is used for identifying barren potentials in factorizations.\n\\emph{SumOut} is a function which systematically removes a set of variables from a factorization by multiplying potentials with the variables and them marginalizing the variables out.\nThe class \\emph{VariableElimination} implements the exact inference algorithm VE as originally proposed by \\cite{zhan94}.\nFinally, the \\emph{Test} branch has a set of unit tests which assure the correct functioning of core functions in the whole library.\n\n\\section{Features}\n\\label{sec:system:sec2}\n\nHere, we highlight some feature of the library.\nIn general, the features are tools to facilitate the use of Darwin in teaching and prototyping of small system.\nThe library is not intended for fast inference, neither high accuracy.\nTherefore, all numerical operations are implemented using native Python code, instead of high performance libraries such as \\emph{numpy} \\cite{van2011numpy}.\nThe graph manipulations are done by an external library called \\emph{NetworkX}, a robust and well known library with high performance and large set of tools.\n\nFor modeling, Darwin has the testing of d-Separation implemented using a reachability algorithm.\nAlso, the library has built in tools for converting a BN into a MN, including the join tree construction by moralization, triangulization and the assignment of potentials.\nThe triangulization step, specifically, has implemented 4 different heuristics, the same as implemented in \\emph{PgmPy} \\footnote{http://pgmpy.org}.\n\nFor inference, the library provides a basic function for eliminating variables in a factorization, called \\emph{SumOut}.\nBut for faster inference, it is recommended to use the VE implementation which absorb evidence, removes barren and independent by evidence potentials, perform inference by summing out non relevant variables and, finally, normalize the final result.\n\n\\section{Usage}\n\\label{sec:system:sec3}\n\nIn order to get started with Darwin, we now present a quick overview of the most common classes and functions.\nThe main classes are \\emph{Potential}, \\emph{GraphWithPotential}, \\emph{BayesianNetwork}, and \\emph{MarkovNetwork}.\n\nThe Potential class is defined by the given arguments: \\emph{variables} which is a list with strings, \\emph{cardinalities} corresponding to the variables which is a list with integers in the same order than the variables, probabilities \\emph{values} in a list with floating numbers, \\emph{left hand side} which is a list with the variables in the LHS of the potential, and similarly the \\emph{right hand side} is defined.\nFor example, considering a CPT $P(a|b)$ with binary variables and probability values 0.4, 0.5, 0.6, 0.5, we can use Darwin to represent this potential as:\n\\begin{verbatim}\n    Potential([\"a\", \"b\"], [2, 2], [0.4, 0.5, 0.6, 0.5], [\"b\"], [\"a\"])\n\\end{verbatim}\n\nThe GraphWithPotential class contains basically a list with potentials, a graph defined using NetworkX, and a dictionary mapping nodes in the graph to a list of potentials.\nAfter declaring a GraphWithPotential, the user can add potentials to a node using the \\emph{add\\_potential} method.\nFor example, the following code creates a graph with two nodes $\\{a\\}$ and $\\{a,b\\}$ and assign $P(a)$ to $\\{a\\}$ and $P(b|a)$ to $\\{a,b\\}$ in a GraphWithPotential.\n\\begin{verbatim}\n    p1 = Potential([\"a\"], [2], [0.2, 0.8], [\"a\"], [])\n    p2 = Potential([\"a\", \"b\"], [2, 2], [0.4, 0.5, 0.6, 0.5], [\"b\"], [\"a\"])\n    \n    G = networkx.Graph()\n    G.add_nodes([\"a\", \"ab\"])\n    \n    GwP = GraphWithPotential()\n    GwP.add_potential(\"a\", p1)\n    GwP.add_potential(\"ab\", p2)\n\\end{verbatim}\n\nThe MarkovNetwork inherits from GraphWithPotential, therefore modeling a MN is simply using the GraphWithPotential like in the code above.\nIn the same way, modeling a BN uses the BayesianNetwork class which also inherits from GraphWithPotential.\nThe difference for a BN is that only one potential is assigned at one node and the graph used is a DAG.\nFor instance, the code above can be used to declare a BN with two nodes $a \\rightarrow ab$ just by changing the definition of $G$ to the below code, which is a directed graph.\n\\begin{verbatim}\n    G = networkx.DiGraph()\n    G.add_edge(\"a\", \"ab\")\n\\end{verbatim}\n", "meta": {"hexsha": "3342554b9ba59c68cdf2cc9a6df615f67c889ece", "size": 7465, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "FINAL PROJECT/section/chapter-darwin.tex", "max_stars_repo_name": "andreeds/cs807-research-tasks", "max_stars_repo_head_hexsha": "6e05e548cfc76302af36cdb81096822b19c84c99", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FINAL PROJECT/section/chapter-darwin.tex", "max_issues_repo_name": "andreeds/cs807-research-tasks", "max_issues_repo_head_hexsha": "6e05e548cfc76302af36cdb81096822b19c84c99", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FINAL PROJECT/section/chapter-darwin.tex", "max_forks_repo_name": "andreeds/cs807-research-tasks", "max_forks_repo_head_hexsha": "6e05e548cfc76302af36cdb81096822b19c84c99", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 75.404040404, "max_line_length": 421, "alphanum_fraction": 0.7807099799, "num_tokens": 1769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.34070507359454244}}
{"text": "\\documentclass{article}\n\\usepackage[minionint,mathlf,textlf]{MinionPro} % To gussy up a bit\n\\usepackage[margin=1in]{geometry}\n\\usepackage{graphicx} % For .eps inclusion\n%\\usepackage{indentfirst} % Controls indentation\n\\usepackage[compact]{titlesec} % For regulating spacing before section titles\n\\usepackage{adjustbox} % For vertically-aligned side-by-side minipages\n\\usepackage{array, mathrsfs, mhchem, amsmath} % For centering of tabulars with text-wrapping columns\n\\usepackage{hyper ref}\n\\usepackage[autolinebreaks,framed,numbered]{mcode}\n\\pagenumbering{gobble} \n\\setlength\\parindent{0 cm}\n\\begin{document}\n\\large\n\n\\section*{Recap of \\textit{Synechococcus} post-translational oscillator}\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=0.5\\textwidth]{pto.png}\n\\caption{Model for the post-translational oscillator, from Rust 2007.}\n\\end{center}\n\\end{figure}\n\n\\begin{itemize}\n\\item Recall that the post-translational oscillator at the heart of the cyanobacterial clock cycles through four states characterized by peaks in four phosphorylation states of the protein KaiC:\n\\begin{enumerate}\n\\item U-KaiC: no phosphorylation (``dawn\")\n\\item T-KaiC: threonine phosphorylated (``noon\")\n\\item D-KaiC: both phosphorylated (``dusk\")\n\\item S-KaiC: serine phosphorylated (``midnight\")\n\\end{enumerate}\n\\item KaiA promotes KaiC's kinase activity. The accumulation of S-KaiC (in conjunction with KaiB) inhibits KaiA.\n\\item A general model for this clock is described by:\n\n\\begin{eqnarray*}\n\\frac{dT}{dt} & = & k_{UT} U + k_{DT} D -\\left(  k_{TD} + k_{TU} \\right) T\\\\ \n\\frac{dD}{dt} & = & k_{TD} T + k_{SD} S - \\left(k_{DT} + k_{DS} \\right) D\\\\\n\\frac{dS}{dt} & = &k_{DS} D +  k_{US} U - \\left( k_{SU} + k_{SD} \\right) S\\\\\nk_{xy} & = & k_{xy}^0 + \\frac{k_{xy}^A A(S)}{K + A(S)}\\\\\nA(S) & = & \\max \\left(0, \\left[ \\textrm{KaiA} \\right] - 2 S \\right)\n\\end{eqnarray*}\n\nThis includes every forward and backward reaction along the loop (though some rate constants are measured to be very low). First-order kinetics are assumed for all phosphorylation and dephosphorylation reactions.\n\n\\item A few features seen here that are very common in oscillators:\n\\begin{itemize}\n\\item A process driving forward progression.\n\\item A negative feedback loop that kicks in after a delay (either explicity temporal or resulting from nonlinearity)\n\\end{itemize}\n\\item The model presented does not include a positive feedback loop. Notice that most oscillations are relatively sinusoidal, like a harmonic oscillator. Later in this lecture, we will argue that oscillators which contain both positive and feedback loops behave like relaxation oscillators, with strikingly fast transitions.\n\\end{itemize}\n\n\\section*{Entrainment}\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=\\textwidth]{adp_falling.png}\n\\caption{Change in ATP:ADP ratio upon a dark pulse, from Rust 2011.}\n\\end{center}\n\\end{figure}\n\n\\begin{itemize}\n\\item Unexpected periods of darkness during the subjective day lead to decreases in the ATP:ADP ratio. Typically, ATP makes up 90\\% of the combined pool of these two molecules; after an eight-hour pulse of darkness, the ratio falls to about 40\\%.\n\n\\item Since ATP serves as the phosphate group donor for KaiC's phosphorylation reactions, this increases the tendency for KaiC to be in an unphosphorylated state.\n\n\\item The dependence on the ATP:ADP ratio is easily studied in vitro, where more ADP can be spiked in (or ATP can be regenerated by adding pyruvate kinase). The phase of the clock is reset to a lower overall phosphorylation (primarily U-KaiC and S-KaiC) after a period when the ATP:ADP ratio is low. This is sensible because that phosphorylation pattern corresponds to the period between midnight and dawn.\n\n\\end{itemize}\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=0.5\\textwidth]{adp_feedback.png}\n\\caption{Model for the effect of ATP:ADP ratio on the PTO, from Rust 2011.}\n\\end{center}\n\\end{figure}\n\\begin{itemize}\n\n\\item The model described above was modified to account for the entrainment system as follows:\n\n\\[k_{phos} = k_{phos}^A \\left( \\frac{A(S)}{K + A(S)} \\right) \\left( \\frac{[\\textrm{ATP}]}{[\\textrm{ATP] + $K_{rel}$[ADP}]} \\right) \\]\n\nThe dephosphorylation reactions do not appear to depend on the ATP:ADP ratio when observed experimentally, so they remain dependent only on $A(S)$.\n\n\\item This model follows a limit cycle that maintains the appropriate period for various steady-state daylight ATP:ADP ratios, but shifts phase in response to sudden changes in the ratio.\n\n\\item If the dark pulse is delivered around subjective dusk, the phase is modestly advanced; if delivered around subjective dawn, the phase lags. The magnitude of the phase shift is largest around mid-day, when kinase activity would otherwise have peaked: this results in a large phase advance.\n\\end{itemize}\n\n\\section*{Phase response curve (PRC)}\n\n\\begin{itemize}\n\\item One way to quantify the phase shift due to perturbation is with a \\textit{phase response curve}. The change in phase (positive if advanced, negative if retarded) is plotted against the timing of the perturbation. These plots are rather popular because they can be made even if nothing mechanistic is understood about the system.\n\n\\item Example for circadian rhythm and ``light therapy\" illumination common for seasonal affective disorder. Effect on the cycle shifts sharply overnight (exposure in the evening retards the cycle, and exposure in the early morning advances it; little effect during the day).\n\n\\item This example emphasizes that the ideal phase response curve is not necessarily flat at zero; entrainment requires the ability to shift phase and a PRC can be more or less well-suited to adjusting the phase in response to stimuli.\n\n\\end{itemize}\n\n\n\\section*{\\textit{Synechococcus elongatus} transcriptional-translational feedback loop}\n\n\\begin{itemize}\n\\item The mechanism for entrainment described above provides a means for response to natural fluctuations in the ATP:ADP ratio presumably caused by increased availability of ATP during photosynthetic periods.\n\\item Others have also proposed that the clock could entrain on temperature (another environmental cue that reflects recent lighting conditions). The cyanobacterial clock period is fairly robust to changes in temperature ($\\pm 5$ degrees Celsius, a wider range than most marine varieties encounter during the circadian cycle; \\textit{Synechococcus elongatus} is a freshwater cyanobacterium, however); the phase, however, can be shifted by abrupt temperature changes of the same range.\n\\item When temperature and light-dark cycling are offset in phase by 12 hours, the cyanobacterial clock syncs to the light-dark cycling, suggesting that illumination (via ATP:ADP ratios?) is the physiologically-predominant form of entrainment.\n\\item Unfortunately, the cyanobacterial clock can also be phase-shifted by means which are presumed to be unintentional. For example, overexpression of KaiC for a few hours can reset the phase to subjective dawn. Indeed the in vitro post-translational oscillator can be broken by varying the stoichiometry of the components.\n\\item KaiA and KaiBC are transcribed from two different operons. KaiA's rate of translation is effectively constant; however, KaiBC transcription and translation vary with the circadian cycle. The problem of keeping ratios constant is therefore exacerbated by the variation in cyanobacterial growth rate with media conditions (e.g. division times ranging from 14-34 hours in common media).\n\\item A response regulator, RpaA, is activated through phosphorylation by a histidine kinase (SasA) downstream of the PTO. It then binds at hundreds of genes throughout the genome to drive expression of its targets, including \\textit{kaiBC}.\n\\item In $\\Delta$rpaA strains, \\textit{kaiBC} expression is four-fold lower than normal, breaking the PTO.\n\\end{itemize}\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=\\textwidth]{rpa.png}\n\\caption{Role of RpaA in regulation of kaiBC and other targets, from Markson 2013.}\n\\end{center}\n\\end{figure}\n\n\\begin{itemize}\n\\item The RpaA loop helps to maintain stoichiometry because RpaA is activated through phosphorylation just before the majority of KaiC is double-phosphorylated, a condition that occurs around dusk normally, but could also reflect an aberrantly high KaiA:KaiC ratio. Under this condition RpaA would help restore the normal stoichiometry by causing more KaiBC to be expressed.\n\\item In an upcoming discussion paper (after the break), you'll find that in addition to keeping the clock operational, the transcriptional feedback loop helps prevent phase drift of the PTO.\n\n\\end{itemize}\n\n\\section*{Simple harmonic oscillator}\n\n\\begin{itemize}\n\\item We now return to the notion that there are two general categories of oscillators driving biological clocks. The first characterizes oscillators that lack a positive feedback loop and show oscillatory patterns similar to harmonic oscillators.\n\n\\item Some oscillators have greater stability in amplitude, phase, and/or frequency against likely perturbations than others.\n\n\\item Consider the harmonic oscillator system:\n\n\\[  \\frac{d^2 x}{dt^2} + a \\frac{dx}{dt} + bx = 0 \\]\n\n\\item In order to apply stability analysis techniques we already know, we could e.g. convert this into a linear system by substitutition:\n\n\\begin{eqnarray*}\n\\frac{dx}{dt}  & = & y\\\\\n\\frac{dy}{dt} + a y + b x & = & 0\\\\\n\\frac{dy}{dt} & = & -b x - a y\\\\\n\\frac{d}{dt} \\begin{pmatrix} x \\\\ y \\end{pmatrix} & = & \\begin{pmatrix} 0 & 1  \\\\ -b & -a \\end{pmatrix} \\begin{pmatrix} x \\\\ y \\end{pmatrix}\n\\end{eqnarray*}\n\n\\item If $a=0$, we have stable oscillations. Arbitrarily choosing $b=1$ and initial conditions of $x(0)=0$ and $y(0)=1$ gives a pair of sinusoidal functions with a phase offset of 90 degrees, e.g.\n\\[ x(t) = \\sin t \\hspace{3 cm} y(t) = \\cos(t) \\]\n\n\\item Consider what happens when we perturb $x$, say, by decreasing its magnitude soon after $x$ reaches its nadir. This will cause the slope of $y$ to decrease prematurely, and though the system will continue to oscillate at the same frequency, its magnitude will be permanently decreased and its phase will be shifted.\n\n\\item Even worse, a non-zero value of $a$ would cause these oscillations to either grow or decay.\n\\end{itemize}\n\n\\section*{van der Pol oscillator}\n\\begin{itemize}\n\\item Not all oscillators suffer from these problems. Consider the van der Pol oscillator with $\\mu \\gg 1$:\n\n\\[ \\frac{d^2 x}{dt^2} + \\mu \\left( x^2 -1 \\right)\\frac{dx}{dt} + x = 0 \\]\n\n\\item Notice that\n\n\\[ \\frac{d^2 x}{dt^2} + \\mu \\left( x^2 -1 \\right)\\frac{dx}{dt} = \\frac{d}{dt} \\left[ \\frac{dx}{dt} + \\mu \\left( \\frac{x^3}{3} - x \\right) \\right] \\]\n\n\\item To simplify this system, we substitute\\footnote{Following Strogatz example 7.5.1}:\n\n\\begin{eqnarray*}\n&F(x) = \\frac{x^3}{3} - x \\hspace{3 cm} w = \\frac{dx}{dt} + \\mu F(x)&\\\\\n&\\frac{dx}{dt} = \\mu F(x) - w&\\\\\n& \\frac{dw}{dt} =  \\frac{d^2 x}{dt^2} + \\mu \\left( x^2 -1 \\right)\\frac{dx}{dt} = -x&\n\\end{eqnarray*}\n\n\\item Finally, substituting $y=w/\\mu$:\n\\begin{eqnarray*}\n\\frac{dx}{dt} & = & \\mu \\left(F(x) - y \\right)\\\\\n \\frac{dy}{dt} & = & -\\frac{x}{\\mu}\n\\end{eqnarray*}\n\n\\item By plotting we can see that the system will spend the majority of its time along the cubic nullcline $y=F(x)$, where it moves slowly, then zap quickly to the other half of the plane. This builds intuition that the oscillator functions on two distinct time scales, which indeed we can see from a simulation of the time evolution of the system.\n\n\\item It is possible to show that perturbations do not change the amplitude (or frequency) of the oscillations, unlike the simple harmonic oscillator studied above.\n\n\\item Perturbations of $x$ will still cause a phase shift. Intuitively, however, we predict that the impact on phase will be small unless the sign of $x$ changes during the perturbation. (Otherwise the oscillator will quickly snap back to a similar position along the nullcline.)\n\n\\item Conceptually-similar biological models include the Fitzhugh-Nagumo simplification of Hodgkin and Huxley's action potential model.\n\n\\item In general, oscillators based on a fast positive feedback and slow negative feedback loop will behave like relaxation oscillators, while oscillators based on negative feedback loops with a long delay are more smoother (``sinusoidal\").\n\n\\end{itemize}\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=0.7\\textwidth]{gonze.png}\n\\caption{Image taken directly from the \\href{http://homepages.ulb.ac.be/~dgonze/TEACHING/osc_design.pdf}{lecture notes} of Didier Gonze.}\n\\end{center}\n\\end{figure}\n\n\\begin{itemize}\n\n\n\\item Another interesting feature of the vdPo and oscillators that combine positive and negative feedback loops is that their frequencies can be tuned while maintaining constant amplitude (Tsai et al., 2008).\n\\end{itemize}\n\n\\section*{Isochrons}\n\\begin{itemize}\n\\item To explore the notion that perturbations will have less impact on phase for van der Pol oscillators, we introduce the concept of \\textit{isochrons} (some authors call them isochrones).\n\n\\item Consider a point $x_0$ which does not lie on the limit cycle, but whose trajectory will approach the limit cycle as $t \\to \\infty$. Since $x_0$ is not on the limit cycle, its trajectory is not periodic, formally speaking.\n\n\\item However. there is some corresponding point $y_0$ on the limit cycle whose trajectory will be indistinguishable from that of $x_0$ as $t \\to \\infty$. We could define $x_0$ to have the ``same phase\" as $y_0$.\n\n\\item Using this definition, we can define the \\textit{isochrons} of $y_0$ as the set of all points that have the same phase as $y_0$. Finding isochrons analytically is a daunting task, but MATLAB is pleased to oblige us.\n\n\\item What we see for the van der Pol oscillator is that in most parts of the cycle, the isochrons are almost horizontal. (The more so as $\\mu$ increases.) This suggests that perturbations of $x$ will not greatly change the phase of the oscillator unless the $y$-axis is crossed, or the perturbations come at one of the few points in the cycle where the isochrons are nearly vertical.\n\n\\end{itemize}\n\n\\section*{Coupled oscillators and phase stabilization}\n\n\\begin{itemize}\n\\item Christiaan Huygens is credited with performing the first analysis of coupled oscillators in 1665. He discovered that two pendulums mounted on the same support beam would synchronzie, evidently through vibrations of the beam.\n\\item Synchronization is an effective means to overcome error in frequency and phase of otherwise-independent oscillators. If you are a former MA 19a student, you have likely seen examples, including synchronization of firefly flashing.\n\\item One rather humorous example are male Japanese tree frogs, which ribbit periodically.When two frogs are close to one another, they coordinate their calls to be approximately 180 degrees out of phase from one another. Adding a third frog results in one of two stable patterns: two frogs calling at the same time, or all three frogs calling at phases offset by 120 degrees.\n\\item We'll model the change in phases over time with $\\omega$ as the innate frequency and phase differences $\\phi = \\theta_1 - \\theta_2$ and $\\psi = \\theta_2 - \\theta_3$.\n\\begin{eqnarray*}\n\\frac{d\\theta_1}{dt} & = & \\omega + H(- \\phi) + H(- \\phi - \\psi) = \\omega - H(\\phi) - H(\\phi + \\psi)\\\\\n\\frac{d\\theta_2}{dt} & = & \\omega + H(\\phi) + H(-\\psi) =  \\omega + H(\\phi) - H(\\psi)\\\\\n\\frac{d\\theta_3}{dt} & = & \\omega + H(\\phi + \\psi) + H(\\psi)\\\\\n\\frac{d\\phi}{dt} & = & -2 H(\\phi) - H(\\phi + \\psi) + H(\\phi)\\\\\n\\frac{d\\psi}{dt} & = & H(\\phi) - H(\\phi + \\psi)  - 2 H(\\phi)\\\\\n\\end{eqnarray*}\nwhere $H(\\theta)$ describes the change of phase due to a phase difference, which is assumed to be $2\\pi$ periodic and odd (so that the phase changes go in opposite direction if the phase difference changes sign).\n\n\\item  $H(\\theta)= a \\sin x + b \\sin 2x$ fulfills our requirements for $H$: if we plot the trajectories for this system, we'll see that the frogs can be made to ribbit at equal intervals (either thirds or halfs, depending on the initial conditions.\n\\end{itemize}\n\n\\begin{lstlisting}\nfunction [] = frogs()\n    initial_phases = [0.1, 0.2];\n    time_interval = [0, 20];\n    global a b\n    a = -1;\n    b = -0.1;\n    [timepoints, concentrations] = ode45(@chain1ddt, ...\n        time_interval, initial_phases);\n    plot(timepoints, concentrations(:,1), '-b', 'LineWidth', 3); hold on;\n    plot(timepoints, concentrations(:,2), '-r', 'LineWidth', 3);\n    title(sprintf('phi_0=%0.2f, psi=%0.2f',initial_phases(1),initial_phases(2)));\n    xlabel('Time');\n    ylabel('Phase differences');\n    h = legend('\\phi','\\psi','Location','SouthEast');\n    set(gca, 'FontSize', 24);\n    set(h, 'FontSize', 24);\nend\n\nfunction changes_in_values = chain1ddt(time, current_values)\n    phi = current_values(1);\n    psi = current_values(2);\n    change_in_phi = - 2*H(phi) + H(psi) - H(phi+psi);\n    change_in_psi = - 2*H(psi) + H(phi) - H(phi+psi);\n    changes_in_values = [change_in_phi; change_in_psi];\nend\n\nfunction returned_value = H(phase_difference)\n    global a b\n    returned_value = a * sin(phase_difference) + b * sin(2*phase_difference);\nend\n\\end{lstlisting}\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=0.7\\textwidth]{frogs.pdf}\n\\caption{Timecourse of $\\phi=\\theta_2 - \\theta_1$ and $\\psi = \\theta_3 - \\theta_2$ for $a=-1$, $b=-1$ and (left) $\\phi(0) = 0$ and $\\psi(0) = 1.7$ or (right) $\\phi(0)=0.1$ and $\\psi(0) = 0.2$.}\n\\end{center}\n\\end{figure}\n\\begin{itemize}\n\\item If we perturb the phase of one frog, the system will tend to restore its relative phase (unless the perturbation is so large that the system approaches the other stable solution).\n\\item Similar models can also explain synchronization between coupled oscillators with slightly different frequencies. Some fireflies, for example, can sync to artificial light pulses with $\\pm$15\\% differences in period. (Fireflies of one species can even tune their baseline frequency for improved long-term matching.)\n\\item In this case the coupling was negative (driving the frog's timing apart), but for positive coupling we'd expect synchronization and stabilization of phase.\n\\end{itemize}\n\n\n\\section*{\\textit{Dictyostelium discoideum} aggregation}\n\n\\begin{itemize}\n\n\\item Another example of a system of coupled oscillators is a cellular slime mold community coordinating aggregation. While the phase of this clock does not appear to be linked to an external environmental cue, individual cells can entrain on the extracellular products of already-oscillating neighbors, establishing synchrony between cells in the population.\n\\item \\textit{Dictyostelium} normally live as individual amoebae, but when they begin to run out of food, these amoeba aggregate together to form a motile slug that can travel much faster than any cell alone. The goal of this movement is for the cells to reach a position from which their spores could be disbursed, hopefully to germinate in more favorable conditions. The slug is capable of traveling a few millimeters upward through the leaf litter, where it forms an upright stalk, at the tip of which will form a ball of spores.\n\\item One issue with this life strategy is that it requires cells to signal to one another that they are starving, identify the center of their community, and move toward that point to form an aggregate. \n\\item The major chemical player in communication between cells in this system is cAMP. The external concentration of cAMP is found to oscillate in aggregating populations, and with each peak, cells exhibit contractions toward the center of the group.\n\\item After each peak, both intracellular and extracellular cAMP are hydrolyzed. Inside the cell, this process is carried out by the phosphodiesterase REG A.\n\\item When cAMP is added exogenously at the incorrect phase of the cycle, the phase is shifted; when it is continuously kept high, the cycle is eliminated entirely.\n\\item Cells detect cAMP through a high affinity receptor called CAR1. There are two main effects of signalling through CAR1: activation of ACA, an adenylyl cyclase, and activation of ERK2, which inhibits REG A.\n\\end{itemize}\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=0.5\\textwidth]{maeda.png}\n\\caption{cAMP-based oscillator in \\textit{Dictyostelium}, from Maeda 2004.}\n\\end{center}\n\\end{figure}\n\\begin{itemize}\n\\item What I have described so far is a positive feedback loop that would tend to increase intra- and extracellular cAMP indefinitely. The negative feedback loop in this case is that cAMP activates a protein called protein kinase A (PKA), which represses both ERK2 and ACA.\n\\item The following set of differential equations, modified from Laub and Loomis (1998) by Maeda et al. (2004), produce an oscillating system for an appropriate choice of parameter values:\n\n\\begin{eqnarray*}\n\\frac{d [\\textrm{ACA}]}{dt} & = & k_1  [\\textrm{CAR1}] - k_2 [\\textrm{PKA}]  [\\textrm{ACA}]\\\\\n\\frac{d [\\textrm{PKA}]}{dt} & = & k_3  [\\textrm{cAMPint}] - k_4 [\\textrm{PKA}] \\\\\n\\frac{d[ \\textrm{ERK2}]}{dt} & = & k_5  [\\textrm{CAR1}] - k_6 [\\textrm{PKA}]  [\\textrm{ERK2}]\\\\\n\\frac{d [\\textrm{REG A}]}{dt} & = & k_7  - k_8 [\\textrm{REG A}]  [\\textrm{ERK2}]\\\\\n\\frac{d [\\textrm{cAMPint}]}{dt} & = & k_9  [\\textrm{ACA}] - k_{10} [\\textrm{REG A}] [\\textrm{cAMPint}]\\\\\n\\frac{d[ \\textrm{cAMPext}]}{dt} & = & k_{11}  [\\textrm{ACA}] - k_{12}  [\\textrm{cAMPext}]\\\\\n\\frac{d [\\textrm{CAR1}]}{dt} & = & k_{13}  [\\textrm{cAMPext}]  - k_{14} [\\textrm{CAR1}] \\\\\n\\end{eqnarray*}\n\n\\end{itemize}\n\n\\begin{center}\n\\includegraphics[width=0.7\\textwidth]{slime.pdf}\n\\end{center}\n\n\\begin{itemize}\n\n\\item Although neighboring cells can phase-lock, on the larger scale of the population, moving fronts of external cAMP appear, ultimately forming spirals. Cells within the field of one spiral will ultimately form a slug together.\n\\item External cAMP also binds to a different G protein receptor to ultimately activate phospholipase C, which will produce IP$_3$, causing calcium oscillations that lead to directional pseudopod extension.\n\\end{itemize}\n\n\\section*{Summary}\n\n\\begin{itemize}\n\\item When we return after break, we'll continue our discussion of clocks and oscillations, launching into natural clocks whose oscillators depend on transcriptional feedback loops.\n\\item A majority of synthetic clocks rely on such feedback loops, which have been easier to construct than protein-protein interactions.\n\\item However, you will see that coupling has also been used to synchronize synthetic clocks such as the one developed in Jeff Hasty's group at UCSD.\n\\end{itemize}\n\n\\end{document}", "meta": {"hexsha": "73a9288e6615cc78a5ab4ef596a2543593c025c7", "size": 22577, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "lectures/Lecture 19 - Smooth, Relaxation, and Coupled Oscillators/lecture notes/lecture 19 notes.tex", "max_stars_repo_name": "mewahl/intro-systems-biology", "max_stars_repo_head_hexsha": "95ad58ec50ef79d084e71f4380fbfbf5e1603836", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-01-20T17:43:31.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-31T17:23:09.000Z", "max_issues_repo_path": "lectures/Lecture 19 - Smooth, Relaxation, and Coupled Oscillators/lecture notes/lecture 19 notes.tex", "max_issues_repo_name": "mewahl/intro-systems-biology", "max_issues_repo_head_hexsha": "95ad58ec50ef79d084e71f4380fbfbf5e1603836", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lectures/Lecture 19 - Smooth, Relaxation, and Coupled Oscillators/lecture notes/lecture 19 notes.tex", "max_forks_repo_name": "mewahl/intro-systems-biology", "max_forks_repo_head_hexsha": "95ad58ec50ef79d084e71f4380fbfbf5e1603836", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-01-20T17:43:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-25T14:42:10.000Z", "avg_line_length": 67.3940298507, "max_line_length": 532, "alphanum_fraction": 0.7550161669, "num_tokens": 6130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3407050644684546}}
{"text": "% Like most advanced LaTeX files, this one begins with a lot of\n% boilerplate. You don't need to understand (or even read) most of it.\n% All you need to do is fill in your name, UMN ID, email address,\n% and the number of the pset. (Search for \"METADATA\" to find the place\n% for this.) Then, you can go straight to the \"EXERCISE 1\"\n% section and start writing your solutions.\n% The \"VARIOUS USEFUL COMMANDS\" section is probably worth taking a\n% look at at some point.\n\n%----------------------------------------------------------------------------------------\n%\tPACKAGES AND OTHER DOCUMENT CONFIGURATIONS\n%----------------------------------------------------------------------------------------\n\\documentclass[paper=a4, fontsize=12pt]{scrartcl} % A4 paper and 12pt font size\n\\usepackage[T1]{fontenc} % Use 8-bit encoding that has 256 glyphs\n\\usepackage[english]{babel} % English language/hyphenation\n\\usepackage{amsmath,amsfonts,amsthm,amssymb} % Math packages\n\\usepackage{mathrsfs}    % More math packages\n\\usepackage{sectsty}  % Allows customizing section commands\n\\allsectionsfont{\\centering \\normalfont\\scshape} % Make all section titles centered, the default font and small caps %remove this to left align section tites\n\\usepackage{hyperref} % Turns cross-references into hyperlinks,\n                      % and defines \\url and \\href commands.\n\\usepackage{graphicx} % For embedding graphics files.\n\\usepackage{framed}   % For the \"leftbar\" environment used below.\n\\usepackage{ifthen}   % Used for the \\powset command below.\n\\usepackage{lastpage} % for counting the number of pages\n\\usepackage[headsepline,footsepline,manualmark]{scrlayer-scrpage}\n\\usepackage[height=10in,a4paper,hmargin={1in,0.8in}]{geometry}\n\\usepackage[usenames,dvipsnames]{xcolor}\n\\usepackage{tikz}     % This is a powerful tool to draw vector\n                      % graphics inside LaTeX. In particular, you can\n                      % use it to draw graphs.\n\\usepackage{verbatim} % For the \"verbatim\" environment, in which\n                      % special symbols can be used freely without\n                      % confusing the compiler. (And it's typeset in\n                      % a constant-width font.)\n                      % Useful, e.g., for quoting code (or ASCII art).\n\n%\\numberwithin{table}{section} % Number tables within sections (i.e. 1.1, 1.2, 2.1, 2.2 instead of 1, 2, 3, 4)\n\n\\setlength\\parindent{20pt} % Makes indentation for paragraphs longer.\n                           % This makes paragraphs stand out more.\n\n%----------------------------------------------------------------------------------------\n%\tVARIOUS USEFUL COMMANDS\n%----------------------------------------------------------------------------------------\n% The commands below might be convenient. For example, you probably\n% prefer to write $\\powset[2]{V}$ for the set of $2$-element subsets\n% of $V$, rather than writing $\\mathcal{P}_2(V)$.\n% Notice that you can easily define your own commands like this.\n% Caveat: Some of these commands need to be properly \"guarded\" when\n% they occur in subscripts or superscripts. So you should not write\n% $K_\\CC$, but rather $K_{\\CC}$.\n\\newcommand{\\CC}{\\mathbb{C}} % complex numbers\n\\newcommand{\\RR}{\\mathbb{R}} % real numbers\n\\newcommand{\\QQ}{\\mathbb{Q}} % rational numbers\n\\newcommand{\\NN}{\\mathbb{N}} % nonnegative integers\n\\newcommand{\\PP}{\\mathbb{P}} % positive integers\n\\newcommand{\\Z}[1]{\\mathbb{Z}/#1\\mathbb{Z}} % integers modulo k\n                                            % (syntax: \"\\Z{k}\")\n\\newcommand{\\ZZ}{\\mathbb{Z}} % integers\n\\newcommand{\\id}{\\operatorname{id}} % identity map\n\\newcommand{\\lcm}{\\operatorname{lcm}}\n% Lowest common multiple. For historical reasons, LaTeX has a \\gcd\n% command built in, but not an \\lcm command. The preceding line\n% rectifies that.\n\\newcommand{\\set}[1]{\\left\\{ #1 \\right\\}}\n% $\\set{...}$ compiles to {...} (set-brackets).\n\\newcommand{\\abs}[1]{\\left| #1 \\right|}\n% $\\abs{...}$ compiles to |...| (absolute value, or size of a set).\n\\newcommand{\\tup}[1]{\\left( #1 \\right)}\n% $\\tup{...}$ compiles to (...) (parentheses, or tuple-brackets).\n\\newcommand{\\ive}[1]{\\left[ #1 \\right]}\n% $\\ive{...}$ compiles to [...] (Iverson bracket, aka truth value; also, set of first n integers).\n\\newcommand{\\floor}[1]{\\left\\lfloor #1 \\right\\rfloor}\n% $\\floor{...}$ compiles to |_..._| (floor function).\n\\newcommand{\\underbrack}[2]{\\underbrace{#1}_{\\substack{#2}}}\n% $\\underbrack{...1}{...2}$ yields\n% $\\underbrace{...1}_{\\substack{...2}}$. This is useful for doing\n% local rewriting transformations on mathematical expressions with\n% justifications. For example, try this out:\n% $ \\underbrack{(a+b)^2}{= a^2 + 2ab + b^2 \\\\ \\text{(by the binomial formula)}} $\n\\newcommand{\\powset}[2][]{\\ifthenelse{\\equal{#2}{}}{\\mathcal{P}\\left(#1\\right)}{\\mathcal{P}_{#1}\\left(#2\\right)}}\n% $\\powset[k]{S}$ stands for the set of all $k$-element subsets of\n% $S$. The argument $k$ is optional, and if not provided, the result\n% is the whole powerset of $S$.\n\\newcommand{\\horrule}[1]{\\rule{\\linewidth}{#1}} % Create horizontal rule command with 1 argument of height\n\\newcommand{\\nnn}{\\nonumber\\\\} % Don't number this line in an \"align\" environment, and move on to the next line.\n\n%----------------------------------------------------------------------------------------\n%\tMAKING SUMMATION SIGNS ALWAYS PUT THEIR BOUNDS ABOVE AND BELOW\n%\tTHE SIGN\n%----------------------------------------------------------------------------------------\n% The following are hacks to ensure that sums (such as\n% $\\sum_{k=1}^n k$) always put their bounds (i.e., the $k=1$ and the\n% $n$) underneath and above the sign, as opposed to on its right.\n% Same for products (\\prod), set unions (\\bigcup) and set\n% intersections (\\bigcap). Remove the 8 lines below if you do not want\n% this behavior.\n\\let\\sumnonlimits\\sum\n\\let\\prodnonlimits\\prod\n\\let\\cupnonlimits\\bigcup\n\\let\\capnonlimits\\bigcap\n\\renewcommand{\\sum}{\\sumnonlimits\\limits}\n\\renewcommand{\\prod}{\\prodnonlimits\\limits}\n\\renewcommand{\\bigcup}{\\cupnonlimits\\limits}\n\\renewcommand{\\bigcap}{\\capnonlimits\\limits}\n\n%----------------------------------------------------------------------------------------\n%\tENVIRONMENTS\n%----------------------------------------------------------------------------------------\n% The incantations below define how theorem environments\n% (\\begin{theorem} ... \\end{theorem}) and their likes will look like.\n\\newtheoremstyle{plainsl}% <name>\n  {8pt plus 2pt minus 4pt}% <Space above>\n  {8pt plus 2pt minus 4pt}% <Space below>\n  {\\slshape}% <Body font>\n  {0pt}% <Indent amount>\n  {\\bfseries}% <Theorem head font>\n  {.}% <Punctuation after theorem head>\n  {5pt plus 1pt minus 1pt}% <Space after theorem headi>\n  {}% <Theorem head spec (can be left empty, meaning `normal')>\n\n% Environments which make the text inside them slanted:\n\\theoremstyle{plainsl}\n  \\newtheorem{theorem}{Theorem}[section]\n  \\newtheorem{proposition}[theorem]{Proposition}\n  \\newtheorem{lemma}[theorem]{Lemma}\n  \\newtheorem{corollary}[theorem]{Corollary}\n  \\newtheorem{conjecture}[theorem]{Conjecture}\n% Environments that don't:\n\\theoremstyle{definition}\n  \\newtheorem{definition}[theorem]{Definition}\n  \\newtheorem{example}[theorem]{Example}\n  \\newtheorem{exercise}[theorem]{Exercise}\n  \\newtheorem{examples}[theorem]{Examples}\n  \\newtheorem{algorithm}[theorem]{Algorithm}\n  \\newtheorem{question}[theorem]{Question}\n \\theoremstyle{remark}\n  \\newtheorem{remark}[theorem]{Remark}\n\\newenvironment{statement}{\\begin{quote}}{\\end{quote}}\n\\newenvironment{fineprint}{\\begin{small}}{\\end{small}}\n\n%----------------------------------------------------------------------------------------\n%\tMETADATA\n%----------------------------------------------------------------------------------------\n\\newcommand{\\myname}{Darij Grinberg} % ENTER YOUR NAME HERE\n\\newcommand{\\myid}{00000000} % ENTER YOUR UMN ID HERE\n\\newcommand{\\mymail}{dgrinber@umn.edu} % ENTER YOUR EMAIL HERE\n\\newcommand{\\psetnumber}{1} % ENTER THE NUMBER OF THIS PSET HERE\n\n%----------------------------------------------------------------------------------------\n%\tHEADER AND FOOTER\n%----------------------------------------------------------------------------------------\n\\ihead{Solutions to homework set \\#\\psetnumber} % Page header left\n\\ohead{page \\thepage\\ of \\pageref{LastPage}} % Page header right\n\\ifoot{\\myname, \\myid} % left footer\n\\ofoot{\\mymail} % right footer\n\n%----------------------------------------------------------------------------------------\n%\tTITLE SECTION\n%----------------------------------------------------------------------------------------\n\\title{\t\n\\normalfont \\normalsize \n\\textsc{University of Minnesota, School of Mathematics} \\\\ [25pt] % Your university, school and/or department name(s)\n\\horrule{0.5pt} \\\\[0.4cm] % Thin top horizontal rule\n\\huge Math 4281: Introduction to Modern Algebra, \\\\\nSpring 2019:\nHomework \\psetnumber\\\\% The assignment title\n\\horrule{2pt} \\\\[0.5cm] % Thick bottom horizontal rule\n}\n\\author{\\myname}\n\n\\begin{document}\n\n\\maketitle % Print the title\n\n\\begin{center} % Delete this if you want to save space!\n{\\large due date: \\textbf{Friday, 8 February 2019} at the beginning of class, \\\\\nor before that by email or canvas.\n\nPlease solve \\textbf{at most 4 of the 6 exercises}!}\n\\end{center}\n\n%----------------------------------------------------------------------------------------\n%\tEXERCISE 1\n%----------------------------------------------------------------------------------------\n\\horrule{0.3pt} \\\\[0.4cm]\n\n\\section{Exercise 1: Mutual divisibility is rare}\n\n\\subsection{Problem}\n\nLet $a$ and $b$ be two integers such that $a \\mid b$ and\n$b \\mid a$.\nProve that $\\abs{a} = \\abs{b}$.\n\n\\subsection{Solution}\n\n[...]\n\n%----------------------------------------------------------------------------------------\n%\tEXERCISE 2\n%----------------------------------------------------------------------------------------\n\\horrule{0.3pt} \\\\[0.4cm]\n\n\\section{Exercise 2: Congruence means equal remainders}\n\n\\subsection{Problem}\n\nLet $n$ be a positive integer.\nLet $u$ and $v$ be two integers.\nProve that $u \\equiv v \\mod n$\n        % While it's called \"congruent\", the LaTeX command for\n        % the symbol is \"\\equiv\".\nif and only if $u \\% n = v \\% n$.\n        % To get the \"%\" sign, you need to type \"\\%\".\n        % Just typing \"%\" starts a comment.\n\n\\subsection{Solution}\n\n[...]\n\n%----------------------------------------------------------------------------------------\n%\tEXERCISE 2\n%----------------------------------------------------------------------------------------\n\\horrule{0.3pt} \\\\[0.4cm]\n\n\\section{Exercise 3: Even and odd}\n\n\\subsection{Problem}\n\nLet $u$ be an integer.\n\n\\begin{enumerate}\n\n\\item[\\textbf{(a)}]\nProve that $u$ is even if and only if $u \\% 2 = 0$.\n\n\\item[\\textbf{(b)}]\nProve that $u$ is odd if and only if $u \\% 2 = 1$.\n\n\\item[\\textbf{(c)}]\nProve that $u$ is even if and only if $u \\equiv 0 \\mod 2$.\n\n\\item[\\textbf{(d)}]\nProve that $u$ is odd if and only if $u \\equiv 1 \\mod 2$.\n\n\\item[\\textbf{(e)}]\nProve that $u$ is odd if and only if $u + 1$ is even.\n\n\\item[\\textbf{(f)}]\nProve that exactly one of the two numbers $u$ and $u + 1$ is even.\n\n\\item[\\textbf{(g)}]\nProve that $u \\tup{u+1} \\equiv 0 \\mod 2$.\n\n\\item[\\textbf{(h)}]\nProve that $u^2 \\equiv -u \\equiv u \\mod 2$.\n\n\\end{enumerate}\n\n\\subsection{Solution}\n\n[...]\n\n%----------------------------------------------------------------------------------------\n%\tEXERCISE 4\n%----------------------------------------------------------------------------------------\n\\horrule{0.3pt} \\\\[0.4cm]\n\n\\section{Exercise 4: Factorials 102}\n\n\\subsection{Problem}\n\n\\begin{enumerate}\n\n\\item[\\textbf{(a)}]\nProve that\n\\[\n\\dfrac{1! \\cdot 2! \\cdot \\cdots \\cdot \\tup{2n}!}{n!}\n= 2^n \\cdot \\prod_{i=1}^n \\tup{\\tup{2i-1}!}^2\n\\qquad \\text{for each } n \\in \\NN .\n\\]\n\n\\item[\\textbf{(b)}]\nProve that\n\\[\n\\sum_{k=0}^n \\dfrac{1}{k! \\cdot \\tup{k+2}}\n= 1 - \\dfrac{1}{\\tup{n+2}!}\n\\qquad \\text{for each } n \\in \\NN .\n\\]\n\n\\end{enumerate}\n\n\\subsection{Solution}\n\n[...]\n\n%----------------------------------------------------------------------------------------\n%\tEXERCISE 5\n%----------------------------------------------------------------------------------------\n\\horrule{0.3pt} \\\\[0.4cm]\n\n\\section{Exercise 5: Binomial coefficients 102}\n\n\\subsection{Problem}\n\nProve that\n\\[\n\\dfrac{\\tup{ab}!}{a! \\tup{b!}^a}\n= \\prod_{k=1}^a \\dbinom{kb-1}{b-1}\n\\]\nfor all $a \\in \\NN$ and all positive integers $b$.\n\n\\subsection{Solution}\n\n[...]\n\n%----------------------------------------------------------------------------------------\n%\tEXERCISE 6\n%----------------------------------------------------------------------------------------\n\\horrule{0.3pt} \\\\[0.4cm]\n\n\\section{Exercise 6: Binomial coefficients and coprimality}\n\n\\subsection{Problem}\n\nIt is well-known (see, e.g., \\cite[Proposition 3.20]{detnotes})\nthat $\\dbinom{n}{k} \\in \\ZZ$ for all $n \\in \\ZZ$ and $k \\in \\NN$.\n(This is not at all clear from the definition of $\\dbinom{n}{k}$;\nit is saying that the product of any $k$ consecutive integers\nis divisible by $k!$.\nThe case of $k = 2$ is the statement of Exercise 3 \\textbf{(g)}.)\nThus, we can study the divisibility of binomial coefficients\nby various integers.\nThere are hundreds of theorems about this; this exercise is\nabout one of them.\n\nLet $a$ and $b$ be two coprime positive integers.\n\n\\begin{enumerate}\n\n\\item[\\textbf{(a)}]\nProve that $\\dfrac{a}{a+b} \\dbinom{a+b}{a} = \\dbinom{a+b-1}{a-1}$\nand $\\dfrac{b}{a+b} \\dbinom{a+b}{a} = \\dbinom{a+b-1}{b-1}$.\n\n\\item[\\textbf{(b)}]\nProve that if $h \\in \\QQ$ satisfies $ah \\in \\ZZ$ and $bh \\in \\ZZ$,\nthen $h \\in \\ZZ$.\n(This is where the coprimality of $a$ and $b$ comes into play.)\n\n\\item[\\textbf{(c)}]\nProve that $a+b \\mid \\dbinom{a+b}{a}$.\n\n\\item[\\textbf{(d)}]\nFind a counterexample to the claim of part \\textbf{(c)} if\n$a$ and $b$ are allowed to not be coprime.\n\n\\end{enumerate}\n\n\\subsection{Solution}\n\n[...]\n\n\\begin{thebibliography}{99999999}                                                                                         %\n\n% Feel free to add your sources -- or copy some from the source code\n% of the class notes ( http://www.cip.ifi.lmu.de/~grinberg/t/19s/notes.tex ).\n\n% This is the bibliography: The list of papers/books/articles/blogs/...\n% cited. The syntax is: \"\\bibitem[name]{tag}Reference\",\n% where \"name\" is the name that will appear in the compiled\n% bibliography, and \"tag\" is the tag by which you will refer to\n% the source in the TeX file. For example, the following source\n% has name \"GrKnPa94\" (so you will see it referenced as\n% \"[GrKnPa94]\" in the compiled PDF) and tag \"GKP\" (so you\n% can cite it by writing \"\\cite{GKP}\").\n\n\\bibitem[GrKnPa94]{GKP}Ronald L. Graham, Donald E. Knuth, Oren Patashnik,\n\\textit{Concrete Mathematics, Second Edition}, Addison-Wesley 1994.\\\\\nSee \\url{https://www-cs-faculty.stanford.edu/~knuth/gkp.html} for errata.\n\n\\bibitem[Grinbe19]{detnotes}Darij Grinberg,\n\\textit{Notes on the combinatorial fundamentals of algebra},\n10 January 2019. \\\\\n\\url{http://www.cip.ifi.lmu.de/~grinberg/primes2015/sols.pdf}\n\\\\\nThe numbering of theorems and formulas in this link might shift\nwhen the project gets updated; for a ``frozen'' version whose\nnumbering is guaranteed to match that in the citations above, see\n\\url{https://github.com/darijgr/detnotes/releases/tag/2019-01-10} .\n\n\\end{thebibliography}\n\n\\end{document}\n\n", "meta": {"hexsha": "cee7d2a442a1b8cdfd8667479955ed7091d7307e", "size": 15281, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "hw1.tex", "max_stars_repo_name": "darijgr/algebra19s", "max_stars_repo_head_hexsha": "16476909502a4566bd33b4f11ade52829ef9b16f", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-03-21T05:38:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-17T00:48:51.000Z", "max_issues_repo_path": "hw1.tex", "max_issues_repo_name": "darijgr/algebra19s", "max_issues_repo_head_hexsha": "16476909502a4566bd33b4f11ade52829ef9b16f", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw1.tex", "max_forks_repo_name": "darijgr/algebra19s", "max_forks_repo_head_hexsha": "16476909502a4566bd33b4f11ade52829ef9b16f", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4911838791, "max_line_length": 157, "alphanum_fraction": 0.580459394, "num_tokens": 4221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.3405219588595255}}
{"text": "%\\documentclass{emulateapj}\n%\\documentclass[letterpaper,12pt,preprint]{aastex}\n\\documentclass[usenatbib]{mn2e}\n\\bibliographystyle{mn2e}\n\n\n% packages\n\\usepackage{amssymb,amsmath,amsbsy}\n\\usepackage{booktabs}\n\\usepackage[caption=false]{subfig}\n\\usepackage{color}\n\n% commands\n\\newcommand{\\given}{\\,|\\,}\n\\newcommand{\\dd}{\\mathrm{d}}\n\\newcommand{\\transpose}[1]{{#1}^{\\mathsf{T}}}\n\\newcommand{\\inverse}[1]{{#1}^{-1}}\n\\newcommand{\\msun}{\\mathrm{M}_\\odot}\n\n\\newcommand{\\project}[1]{\\textsl{#1}}\n\\newcommand{\\superfreq}{\\project{SuperFreq}}\n\n% TO DO\n\\usepackage{graphicx} \n\\newcommand{\\apwtodo}[1]{{\\color{red} APW: (\\MakeUppercase{#1})}}\n\\newcommand{\\djdtodo}[1]{{\\color{green} DJD: (\\MakeUppercase{#1})}}\n\n%Dan's Math Definitions\n\\newcommand{\\scripty}[1]{\\ensuremath{\\mathcalligra{#1}}}\n\\def\\sr{\\scripty{r}}\n\\def\\Mach{\\mathcal{M}}\n\\def\\bin{\\rm{bin}}\n\\def\\Mdot{\\dot{M}}\n\\def\\Msun{ M_{ \\rm{\\odot} } }\n\n\\def\\xb{\\bar{x}}\n\\def\\yb{\\bar{y}}\n\n\n\n\n\n\n\n\n\\begin{document}\n\n\\title{Cavity search: a parameter study of the importance of chaos for feeding black hole binaries}\n\\author[D. J. D'Orazio, Adrian M. Price-Whelan]{Daniel J. D'Orazio$^1$, Adrian M. Price-Whelan$^1$  \n    \\thanks{dorazio@astro.columbia.edu; adrn@astro.columbia.edu}\\\\\n     $^1$Department of Astronomy, Columbia University, 550 West 120th Street, New York, NY 10027 \n}\n\n%\\author{\n%Daniel J. D'Orazio\\altaffilmark{\\colum},\n%Adrian M. Price-Whelan\\altaffilmark{\\colum}\n%}\n\n% Affiliations\n%\\newcommand{\\colum}{1}\n% \\newcommand{\\adrn}{2}\n\n%\\altaffiltext{\\colum}{Department of Astronomy,\n   %                   Columbia University,\n      %                550 W 120th St.,\n         %             New York, NY 10027, USA}\n% \\altaffiltext{\\adrn}{To whom correspondence should be addressed: adrn@astro.columbia.edu}\n\n\\maketitle\n\n\n\\begin{abstract}\n%Danny boy\n% Context\nThe interaction of a binary and a thin gasesous disk lies at the heart\nof a number of important astrophysical phenomena. These include the\nformation of planetary systems and the fate of massive black hole\nbinaries at the centers of galactic nuclei.\n%The masses and orbital distributions of planetary systems are\n%dictated by the interaction of a planet-star binary with a\n%proto-planetery disk. The\n%merger rates and electromagnetic signatures of massive black hole\n%binares are influenced by gas which is torqued to the centers of\n%galactic nuclei upon merger. Their fate is tied to the level\n%of orbital evolution and mass feeding influenced by the coupled nature\n%of binary+disk evolution. \nThe salient features of binary+disk interactions are captured largley\nby the gravitaitonal dynamics of a disk of particles in the plane of\nthe binary.\n%Aims\nHere we gain insight into binary+disk dynamics by studying orbits of\ntest particles in the binary plane via the restricted three body\nproblem.\n%Methods\nWe investigate the resonant structure of orbits over a range of binary\nmass ratios and orbital eccentricities relvant to astrophysical\nsystems.\n% Results\nWe find some cool chaos crap related to Dan's other paper on CBD\ntransitions and also some dynamics stuff related to Adrian's work.\n% Conclusions\n\n\n\\end{abstract}\n\n%\\keywords{ \n%stuff\n%}\n\n\\section{Introduction}\\label{sec:introduction}\n\n\\section{Methods}\\label{sec:methods}\n\n\\subsection{Equations of Motions}\n%\\section{Equations of Motions}\nThe equations of motion for a test particle in the plane of an\neccentric binary are described by the elliptical, restricted three\nbody problem (ER3Bp). We write the ER3Bp as two coupled second order\nODE's in the non-uniformly rotating, isotropically pulsating, frame of\nthe eccentric binary ($\\bar{x}$, $\\bar{y}$),\n\\begin{equation}\n\\begin{array}{c}\n\\ddot{\\xb} - 2\\dot{\\yb} = \\frac{\\partial{U}}{\\partial{\\xb}}  \\left( 1 + e \\cos{f} \\right)^{-1} \\nonumber \\\\ \\nonumber \\\\ \n\\ddot{\\yb} + 2\\dot{\\xb} = \\frac{\\partial{U}}{\\partial{\\yb}}  \\left( 1 + e \\cos{f} \\right)^{-1}\n\\label{Eqmotion}\n\\end{array}\n\\end{equation}\nfor binary with true anomaly $f$, eccentricity $e$, mean motion $\\equiv 1$,\nand $ \\ \\dot{} \\ \\equiv d/df$. Because the independent variable is\n$f$, there is no need to solve for $f$ in terms of the time $t$ unless\nconverting the solution back to the non-rotating frame.\n\nThe ($\\bar{x}$, $\\bar{y}$) are dimensionless coordinates of the\nmassless third particle which are constructed by dividing the\ndimensional coordinates by the time changing binary separation\n\\begin{equation}\n\\begin{array}{c}\n\\xb = \\xb^* \\frac{1 + e \\cos{f}}{a ( 1-e^2) } \\nonumber \\\\ \\nonumber \\\\ \n\\yb = \\yb^* \\frac{1 + e \\cos{f}}{a ( 1-e^2) } \n\\end{array}\n\\end{equation}\nwhere $*$ denotes the dimensional variable.\n\nThe position of the primaries is found from dividing the dimensional\nposition over time by the binary position and is always fixed at the\nsame values as in the circular R3B, \\textit{i.e.}\n\\begin{equation} \\nonumber\n\\xb_2 = \\xb^*_2 \\frac{1+e \\cos{f}}{a (1-e^2)} =   \\frac{a}{1+q} \\frac{(1-e^2)}{1+e \\cos{f}}  \\frac{1+e \\cos{f}}{a (1-e^2)}  = \\frac{1}{1+q}\n\\end{equation}\nwhere $q = M_2/M_1$, $M_2 < M_1$.Similarly $\\xb_p = -q/(1+q)$.\n\nThere is no longer a conserved quantity in the ER3B, but there is an\nanalogue to the Jacobi constant which is time dependent,\n\\begin{equation}\nC_{eJ} = \\frac{2 U}{1 + e \\cos{f}} - \\left( \\dot{\\xb}^2 + \\dot{\\yb}^2 \\right) - 2 e \\int^f_{f_0}{\\frac{ U \\sin{f} }{(1 + e \\cos{f})^2 } \\ df}\n\\end{equation}\nand can be used to check the accuracy of the integrator (not yet\nimplemented).\n\n\\subsection{Set-up}\nTo set up initial velocity profiles recall that the independent\nvariable is no longer the time, but the true anomaly $f$. This can be\ntaken into account most simply by using the Virial theorem with the\npseudo potential of Eq. \\ref{Eqmotion}. Assuming only azimuthal\ninitial velocities,\n\\begin{equation}\n\\begin{array}{c}\n\\bar{v_x} = -v_{\\phi} \\frac{\\yb_0}{R} \\quad \\bar{v_x} = v_{\\phi} \\frac{\\xb_0}{R} \\\\ \\nonumber \\\\ \\nonumber\nv_{\\phi} =   \\left[ \\sqrt{ \\frac{\\mu_1}{\\bar{r}_1}  +  \\frac{\\mu_2}{\\bar{r}_2} }  \\right] \\left( 1 + e \\frac{\\xb}{R} \\right)^{-1}  - R\\\\ \\nonumber \\\\ \\nonumber\n\\bar{r}^2_1 =  (\\xb + \\mu_2)^2 + \\yb^2  \\qquad \\bar{r}^2_2 =  (\\xb - \\mu_1)^2 + \\yb^2  \\\\ \\nonumber \\\\ \\nonumber\nR^2 = \\xb^2 + \\yb^2 \\\\ \\nonumber \\\\ \\nonumber\n\\mu_1 = \\frac{1}{1+q} = 1-\\mu_2  \\qquad \\mu_2 = \\frac{q}{1+q}\n\\end{array}\n\\end{equation}\nwhere we subtract the speed of the rotating frame from the azimuthal\nvelocity. Since the angular frequency of the rotating frame is unity\nin our coordinates we need only subtract the particle specific\nvelocity $R$.\n\n%If we were going to convert back into the time coordinate, we would need to use\n%\\begin{equation}\n%df  = n \\sqrt{1-e^2} \\left( \\frac{a}{r}\\right)^2 dt = \\frac{n (1 + e \\cos{f})^2}{(1-e^2)^{3/2}}  dt\n%\\end{equation}\n%where the last line substitutes the time dependent binary separation $r$. \n\nTo convert back to time t, and unscaled distances we multiply the\ncoordinates by the time dependent binary separation and solve for\n$t(f)$ in the usual manner.\n\n\n\nDescribe potential and things varied (mass ratio, viscosity,\neccentricity, what else?)\\\\ Lets start with mass ratio - look for\nLinblad resonances, and see what happens when linear stability is\nlost.\n\nOrbits are integrated with ...\n\n\\subsection{Numerical determination of the fundamental frequencies}\\label{sec:freqs}\n\nRegular orbits in Hamiltonian systems may be represented in a special set of coordinates known as angle-action variables \\citep[e.g.,][]{goldstein80}: in these coordinates, the position variables---the angles---increase linearly with time with rates set by a set of fundamental frequencies, and the momentum variables---the actions---are integrals of motion. More specifically, for a regular orbit represented in coordinates $(x_n, v_n)$, there exists a transformation $(x_n, v_n)\\rightarrow(\\theta_n, J_n)$ such that\n\\begin{align}\n\t\\theta_n(t) &= \\theta_n(0) + \\Omega_n\\,t\\\\\n\tJ_n &= {\\rm const.}\n\\end{align}\nThe $\\Omega_n$ are known as the fundamental frequencies and there are $N$ such frequencies for non-resonant orbits in systems with $N$ degrees of freedom.\n\n\\apwtodo{Need to use a different symbol here for integer vector}\nA resonant orbit is an orbit for which there exists at least one relation such that\\footnote{The repeated indices imply summation.} $n_n\\,\\Omega_n = 0$ where $n_n$ is a vector of integers. \\apwtodo{More theory-speakery here methinks...}\n\n[How to numerically determine the frequencies using:]\n\\begin{equation}\n\tx(t) = \\sum a_k\\,e^{i \\, \\omega_k \\, t}\n\\end{equation}\n\n[How to detect chaos with this shite and measure rate of frequency diffusion]\n\n\\section{Conclusions}\\label{sec:conclusions}\n\n%\\acknowledgements\n\\section{Acknowledgments}\nAPW is supported by a National Science Foundation Graduate Research Fellowship under Grant No.\\ 11-44155. DJD is supported by a National Science Foundation Graduate Research Fellowship under Grant No. DGE1144155\nThis work was supported in part by the National Science Foundation under Grant No. PHYS-1066293.\nThis research made use of Astropy, a community-developed core Python package for Astronomy \\citep{astropy13}.\nThis work additionally relied on Columbia University's \\emph{Hotfoot} and \\emph{Yeti} compute clusters, and we acknowledge the Columbia HPC support staff for assistance, especially Mr. Alex Bergier. \n\n%\\bibliographystyle{apj}\n%\\bibliography{refs}\n\n\\end{document}\n", "meta": {"hexsha": "0de9316d0da1c51e36524830ee5881ec574bed87", "size": 9311, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/ms.tex", "max_stars_repo_name": "adrn/triforce", "max_stars_repo_head_hexsha": "2ece7a689c11dc4c39cc52f0bc2b3933a475fbf8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paper/ms.tex", "max_issues_repo_name": "adrn/triforce", "max_issues_repo_head_hexsha": "2ece7a689c11dc4c39cc52f0bc2b3933a475fbf8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/ms.tex", "max_forks_repo_name": "adrn/triforce", "max_forks_repo_head_hexsha": "2ece7a689c11dc4c39cc52f0bc2b3933a475fbf8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3073593074, "max_line_length": 517, "alphanum_fraction": 0.7248415852, "num_tokens": 2828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3405219522786202}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\section{Sheet 7}\n\n\\subsection{Photons travelling in the Schwarzschild metric}\n\n\\subsubsection{A different proof for the conservation of the component of the velocity of a geodesic along a Killing vector field (complement)}\n\nHere I present a different proof to what was done in the lectures for the fact that the component of the 4-velocity along the Killing vector field is conserved. \nThis is not necessary to know for the exam, do skip this section if it does not interest you. \n\nIf the metric does not depend on the coordinate \\(\\widetilde{\\alpha }\\), then \\(\\partial_{\\widetilde{\\alpha }} g_{\\mu \\nu } = 0\\). So, let us differentiate covariantly the vector \\(\\xi_{\\mu } = g_{\\mu \\nu } \\delta^{\\nu}_{\\widetilde{\\alpha }}\\).\nIt will be apparent later that differentiating the lower-index vector field gives us the interesting property.\nWe get \n%\n\\begin{align}\n  \\nabla_{\\mu } \\xi_{\\nu } =\n  g_{\\nu \\sigma } \\nabla_{\\mu } \\xi^{\\sigma }\n  =  g_{\\nu \\sigma }\n  \\qty(\\cancelto{}{\\partial_{\\mu } \\xi^{\\sigma }} + \\Gamma^{\\sigma }_{\\mu \\rho } \\xi^{\\rho })\n  = \\Gamma_{\\nu \\mu \\widetilde{\\alpha }}\n\\,,\n\\end{align}\n%\nsince the only component which survives the contraction with \\(\\xi \\) is the one along \\(\\widetilde{\\alpha} \\); also, we lowered an index of the Christoffel symbols with the metric. \n\nThe explicit expression for the lower indices Christoffel symbols is \n%\n\\begin{align}\n  \\Gamma_{\\nu \\mu \\widetilde{\\alpha }}\n  = \\frac{1}{2} \\qty(\\cancelto{}{g_{\\mu \\nu , \\widetilde{\\alpha }}} +\n  g_{\\mu \\widetilde{\\alpha }, \\nu }\n  - g_{\\mu \\widetilde{\\alpha }, \\nu })\n\\,,\n\\end{align}\n%\nsince by hypothesis any derivative of the metric along \\(\\widetilde{\\alpha}\\) is zero. So, we can directly see that the object \\(\\nabla_{\\mu } \\xi_{\\nu }\\) is antisymmetric in its indices: this can be written as \n%\n\\begin{align}\n  \\nabla_{(\\mu } \\xi_{\\nu )} = 0\n\\,,\n\\end{align}\n%\nand is called \\emph{Killing's equation}. We have shown that is equivalent to the metric not depending on the coordinate \\(x^{\\widetilde{\\alpha}}\\).\n\nNow, we can quickly prove the conservation a component of the 4-velocity of a geodesic along the Killing vector field: we just need to differentiate \\(u^{\\mu } \\xi_{\\mu }\\) with respect to the arc parameter. \nRecall that geodesics are defined by the equation \n%\n\\begin{align}\n a^{\\mu } =  \\dv[]{}{s} u^{\\mu } = u^{\\nu } \\nabla_{\\nu } u^{\\mu } = 0 \n\\,.\n\\end{align}\n%\n\nWe find \n%\n\\begin{align}\n  u^{\\nu }\\nabla_{\\nu }\\qty(u^{\\mu } \\xi_{\\mu })\n  = u^{\\nu } u^{\\mu } \\nabla_{\\nu } \\xi_{\\mu } + \\xi_{\\mu } u^{\\nu } \\nabla_{\\nu } u^{\\mu } = 0\n\\,,\n\\end{align}\n%\nwhere both terms are zero: the first because it is the contraction of an antisymmetric object with a symmetric one, and the second one because of the geodesic equation. \n\n\\subsubsection{Conserved quantities in Schwarzschild motion}\n\nThe Schwarzschild metric is given by \n%\n\\begin{subequations}\n\\begin{align}\n  g_{\\mu \\nu } = \\left[\\begin{array}{cccc}\n  -(1-\\frac{2GM}{r}) & 0 & 0 & 0 \\\\ \n  0 & (1-\\frac{2GM}{r})^{-1} & 0 & 0 \\\\ \n  0 & 0 & r^2 & 0 \\\\ \n  0 & 0 & 0 & r^2 \\sin^2\\theta \n  \\end{array}\\right]\n\\,\n\\end{align}\n\\end{subequations}\n%\nin the coordinates \\((t, r, \\theta , \\varphi )\\). The vector fields \\(\\xi_{(t)}^{\\mu } = (1, \\vec{0})\\) and \\(\\xi_{(\\varphi )}^{\\mu } = (0,0,0,1)\\) in these coordinates are Killing vector fields, since the metric does not depend on \\(t\\) or \\(\\varphi \\). \n\nSo, the following quantities are conserved in geodesic motion parametrized as \\(x^{\\mu }(\\lambda )\\): \\footnote{There is a typo in the exercise sheet: a \\(G\\) is missing in the definition of \\(e\\).}\n%\n\\begin{align}\n  e = -u^{\\mu } g_{\\mu \\nu } \\xi^{\\nu }_{(t)}\n  = -u^{t} g_{tt } \\times 1\n  = \\dv{t}{\\lambda } \\qty(1 - \\frac{2GM}{r})\n\\,\n\\end{align}\n%\nand \n%\n\\begin{align}\n  l = u^{\\mu } g_{\\mu \\nu } \\xi^{\\nu }_{(\\varphi )}\n  = u^{\\varphi } g_{\\varphi \\varphi } \\times 1\n  = \\dv{\\varphi }{\\lambda } r^2 \\sin^2\\theta \n\\,,\n\\end{align}\n%\nwhich for motion on the \\(xy\\) plane, for which \\(\\theta = \\pi /2\\), reduces to \\(l = r^2 \\dv*{\\varphi }{\\lambda }\\).\n\n\\subsubsection{Photons escaping a black hole}\n\nThe equation of motion can be derived from the normalization of the photon's four velocity: The equation \\(u^{ \\mu } u_{\\mu }= 0 \\) can be  written as \n%\n\\begin{align}\n    \\qty(\\dv{t}{\\lambda })^2 g_{tt} +\n    \\qty(\\dv{r}{\\lambda })^2 g_{rr} +\n    \\qty(\\dv{\\theta }{\\lambda })^2 g_{\\theta \\theta } +\n    \\qty(\\dv{\\varphi }{\\lambda })^2 g_{\\varphi \\varphi } = 0\n\\,,\n\\end{align}\n%\nbut the term \\(\\dv*{\\theta }{\\lambda }\\) is zero if we assume the motion to be in the \\(xy \\) plane, while the velocity components along \\(t\\) and \\(\\varphi \\) can be written in terms of the integrals of motion: \\(\\dv*{t}{\\lambda } = e \\qty(1 - 2GM/r)^{-1}\\) and \\(\\dv*{\\varphi }{\\lambda } = l r^{-2}\\). So, we find \n%\n\\begin{align}\n  - \\qty(1 - \\frac{2GM}{r})^{-2+1} e^2 + \\qty(1 - \\frac{2GM}{r})^{-1} \\qty(\\dv{r}{\\lambda })^2 + l^2 r^{-4} r^2 = 0\n\\,,\n\\end{align}\n%\nwe divide through by \\(-g_{tt}\\) and find: \n%\n\\begin{align}\n    -e^2 + \\qty(\\dv{r}{\\lambda })^2+ \\frac{l^2}{r^2} \\qty(1 - \\frac{2GM}{r}) = 0\n    \\,,\n\\end{align}\n%\nor, dividing through by \\(l\\):\n%\n\\begin{align}\n    -\\frac{e^2}{l^2} + \\frac{1}{l^2}\\qty(\\dv{r}{\\lambda })^2+ \\frac{1}{r^2} - \\frac{2GM}{r^3} = 0\n\\,.\n\\end{align}\n\nWe can give names to the terms in this equation: we call \n%\n\\begin{align}\n  V _{\\text{eff}} (r) \\equiv \\frac{1}{r^2} - \\frac{2GM}{r^3}\n\\,\n\\end{align}\n%\nthe \\emph{effective potential}, and \n%\n\\begin{align}\n  b^2 = \\frac{l^2}{e^2}\n\\,\n\\end{align}\n%\nthe \\emph{impact parameter} (unjustified for now). Then, the equation is in the form \n%\n\\begin{align}\n  \\frac{\\dot{r}^2}{l^2}  + V _{\\text{eff}} (r) = \\frac{1}{b^2}\n\\,,\n\\end{align}\n%\nwhere we denoted derivation with respect to \\(\\lambda \\) with a dot. \nSo, we can study the motion of the photon as if it were 1-dimensional. \n\nTo study the problem, it is convenient to use the rescaled adimensional radial coordinate \\(R = r / 2GM\\). In this variable, the effective potential (which I will denote as just \\(V\\) hereafter) looks like: \n%\n\\begin{align}\n  V (R) = (2GM)^{-2} \\qty(R^{-2} - R^{-3})\n\\,,\n\\end{align}\n%\nso we can readily differentiate it to find its stationary points: there is only one, the equation is  \\(V^{\\prime }(R) \\propto -2R^{-1} + 3R^{-2} =0 \\), which is satisfied by \\(R = 3 / 2\\).\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.7\\textwidth]{figures/photon_effective_potential.pdf}\n    \\caption{Plot of the function \\(R^{-2} - R^{-3}\\).}\n    \\label{fig:effective-potential}\n\\end{figure}\n\nThe term \\(b^{-2}\\) is the maximum value which can be attained by the LHS: we can call it the total energy, the kinetic and potential contributions must add up to it. \nAlso, the kinetic term is always positive. \nSo, if the total energy is less than the maximum of the potential, the photon is constrained to stay on either side of the potential barrier around \\(R = 3/2\\). The potential there equals \n%\n\\begin{align}\n  V(3/2) = (2GM)^{-2} \\qty((3/2)^{-2} - (3/2)^{-3}) \n  = \\frac{4/27}{(2GM)^2} = \\frac{1}{27 (GM)^2}\n\\,,\n\\end{align} \n%\nso the condition of the photon being above the potential barrier is \n%\n\\begin{subequations}\n\\begin{align}\n  E _{\\text{tot}} &> V _{\\text{max}}  \\\\\n  \\frac{e^2}{l^2} &> \\frac{1}{27 G^2M^2}  \\\\\n  \\frac{l^2}{e ^2} &< 27G^2M^2\n\\,,\n\\end{align}\n\\end{subequations}\n%\nand under this condition, if the photon initially has positive \\(\\dv*{r}{\\lambda }\\) it will remain as such, since everything is continuous and (if the strict inequality is satisfied) we can never have \\(\\dv*{r}{\\lambda }=0\\). \n\nIf instead we had \\(l^2/e^2 < 27G^2M^2\\) and the photon was initially travelling away from the black hole, there would come a point for which \\(\\dv*{r}{\\lambda }\\) would equal zero, and then it would become negative, since the photon could not go away from the center anymore. \n\nThis can be understood graphically by drawing horizontal lines of constant total energy in the potential diagram. \n\n\\subsubsection{A basis for a stationary observer}\n\nIf our observer's coordinates are \\((t, r_{*}, \\pi /2 , \\varphi_{*} )\\), that is, it is at rest with respect to our spatial coordinates but it is not following geodesic motion, then it will have nonzero 4-acceleration. So, since we know that velocity and acceleration are orthogonal, we can form our coordinate system as \\((u^{\\mu }, a^{\\mu } / \\sqrt{ a^{\\rho } a_{\\rho }}, e_{\\theta }, e_{\\varphi })\\), where the angular basis vectors are simply normalized vectors in the \\(\\theta \\) and \\(\\varphi \\) directions.\n\nThis method has the advantage of being easily generalizable to find a comoving basis for any non-geodesic motion of our observer. \n\nTheir 4-velocity must be normalized so that \\(u^{\\mu } u_{\\mu }= -1\\): so \n%\n\\begin{subequations}\n\\begin{align}\n  u^{\\mu } = \\left[\\begin{array}{c}\n  \\dv{t}{\\tau } \\\\ \n  0 \\\\ \n  0 \\\\ \n  0\n  \\end{array}\\right]\n  = \n  \\left[\\begin{array}{c}\n  1/\\sqrt{1 - \\frac{2GM}{r}} \\\\ \n  0 \\\\ \n  0 \\\\ \n  0\n  \\end{array}\\right]\n\\,,\n\\end{align}\n\\end{subequations}\n%\nthen we can compute the 4-acceleration: it will be \n%\n\\begin{subequations}\n\\begin{align}\n  a^{\\mu } &= u^{\\nu } \\nabla_{\\nu } u^{\\mu }\n  = u^{\\nu } \\qty(\\partial_{\\nu } u^{\\mu } + \\Gamma^{\\mu }_{\\nu \\rho } u^{\\rho })  \\\\\n  &= \\frac{1}{\\sqrt{1 - \\frac{2GM}{r}}} \\qty(\\cancelto{}{\\partial_{t} u^{\\mu }} + \\Gamma^{\\mu }_{tt} u^{t})  \\\\\n  &= \\frac{1}{\\sqrt{1-\\frac{2GM}{r}}}\n  \\frac{1}{\\sqrt{1-\\frac{2GM}{r}}} \\frac{A'}{2B} \\delta^{\\mu }_{r}\n\\,,\n\\end{align}\n\\end{subequations}\n%\nwhere \\(A = 1/B = (1 - 2GM/r)\\) are the coefficients of the Schwarzschild metric, with respect to which the Christoffel symbols are expressed in \\eqref{eq:schwarzschild-christoffel}. \nThe \\(\\delta^{\\mu }_{r}\\) signifies that the only component which survives is the radial one.\nThe two square root terms simplify the \\(B\\), so we get that the only nonzero component of the 4-acceleration is:\n%\n\\begin{align}\n  a^{r} = \\frac{A^{\\prime }}{2} =\n  \\frac{1}{2} \\dv{}{r} \\qty(1 - \\frac{2GM}{r})\n  = \\frac{GM}{r^2}\n\\,.\n\\end{align}\n%\nThe actual value of this component is not actually useful to us, since we need a normalized basis.\nIt can, however, be used to illustrate the equivalence principle: in the weak-field limit where the metric is approximately the Minkowski one the value of this component approaches the modulus of the 3-acceleration. \n\nTherefore, we will use a vector parallel to \\(a^{\\mu }\\) but of length defined by the normalization \\(e_{r} \\cdot e_{r} = 1\\). So, we get for our basis: \n%\n\\begin{subequations}\n\\begin{align}\n  \\begin{cases}\n    (e_{t})^{\\mu } = u^{\\mu } = \\left[\\begin{array}{cccc}\n    (1-2GM/r)^{-1/2}, & 0, & 0, & 0\n  \\end{array}\\right]^{\\top} \\\\ \n    (e_{r})^{\\mu } = a^{\\mu } / \\sqrt{a_{\\rho } a^{\\rho }}\n  = \\left[\\begin{array}{cccc}\n    0, & (1-2GM/r)^{1/2}, & 0, & 0\n  \\end{array}\\right]^{\\top}  \\\\\n  (e_{\\theta })^{\\mu } = \\left[\\begin{array}{cccc}\n  0, & 0, & 1/r, & 0\n  \\end{array}\\right]^{\\top} \\\\\n  (e_{\\varphi })^{\\mu } = \\left[\\begin{array}{cccc}\n  0, & 0, & 0, & 1/(r \\sin \\theta )\n  \\end{array}\\right]^{\\top}\n\\end{cases} \n\\,,\n\\end{align}\n\\end{subequations}\n%\nwhere the last vector is written for a generic angle \\(\\theta \\), but the sine is equal to one if \\(\\theta = \\pi /2\\). \nThis basis satisfies the property \\(e_{\\alpha } \\cdot e_{\\beta } = \\eta_{\\alpha \\beta }\\). \n\nWe will denote vectors written with respect to this basis with a subscript \\(c\\). \n\n\\subsubsection{Critical angle of launch}\n\nIn the flat frame, the 4-velocity of the photon launched at \\(\\theta = \\pi /2\\) looks like: \n%\n\\begin{subequations}\n\\begin{align}\n  u^{\\mu } _{\\text{ph}} = \\left[\\begin{array}{c}\n  1 \\\\ \n  \\cos \\psi  \\\\ \n  0 \\\\ \n  \\sin \\psi \n  \\end{array}\\right]_c\n\\,,\n\\end{align}\n\\end{subequations}\n%\nwhich means that in the Schwarzschild frame it looks like \n%\n\\begin{subequations}\n\\begin{align}\n  u^{\\mu }_{\\text{ph}} = \\left[\\begin{array}{c}\n  \\frac{1}{\\sqrt{1-\\frac{2GM}{r}}} \\\\ \n  \\cos \\psi \\sqrt{1 - \\frac{2GM}{r}} \\\\ \n  0 \\\\ \n  \\frac{\\sin \\psi}{r} \n  \\end{array}\\right]\n\\,.\n\\end{align}\n\\end{subequations}\n\nThis means that the parameter \\(l = r \\sin \\psi \\), while \\(e = \\sqrt{1-2GM/r}\\). \n\nThe inequality to satisfy for the photon to be able to escape is: \n%\n\\begin{align}\n  \\qty[\\frac{e^2}{l^2}]_{r_{*}} \\geq \\frac{1}{27G^2M^2}\n\\,,\n\\end{align}\n%\nwhich translates to \n%\n\\begin{align}\n  \\frac{1 - \\frac{2GM}{r_{*}}}{r_{*}^2 \\sin^2 \\psi } \\geq \\frac{1}{27G^2M^2}\n\\,,\n\\end{align}\n%\nor \n%\n\\begin{align}\n  r_{*}^2 \\sin^2 \\psi \\leq 27G^2M^2 \\qty(1 - 2GM/r_{*}) \n  \\,,\n\\end{align}\n%\n\\begin{figure}[ht]\n  \\centering\n  \\includegraphics[width=0.7\\textwidth]{figures/critical_psi.pdf}\n  \\caption{Critical angle \\(\\psi \\) in terms of the adimensional radial coordinate \\(R = r/ 2GM\\).}\n  \\label{fig:critical-psi}\n\\end{figure}\n%\nwhich once again can be expressed in terms of the adimensional radial coordinate \\(R = r/2GM\\): we find \n%\n\\begin{align}\n  \\sin^2 \\psi \\leq \\frac{27}{4 R_{*}^2} \\qty(1 - \\frac{1}{R_{*}})\n  \\,,\n\\end{align}\n%\nso the critical angle can be computed by making the relation explicitly in terms of \\(\\psi \\), which gives the plot shown in figure \\ref{fig:critical-psi}, for the equation \n%\n\\begin{align}\n  \\psi = \\arcsin \\sqrt{\\frac{27}{4 R_{*}^2} \\qty(1 - \\frac{1}{R_{*}})}\n\\,.\n\\end{align}\n%\n\nSo, as we move closer to the horizon, the range of angles at which we can throw our photon and still have it escape decreases, until finally we can only throw it straight forward otherwise it will fall back in. After \\(r = 2GM\\), not even that is enough.  \n\nAll communication with the outside world is lost. \n\n\\subsection{Light motion in a Schwarzschild geometry}\n\n\\subsubsection{Equation of motion}\n\nThis was done during the lectures, but I will recall it here. \n\nWe start from the equation of motion of a photon, a reframing of \\(u^2=0\\): \n%\n\\begin{align}\n  \\frac{1}{l^2} \\qty(\\dv{r}{\\lambda })^2 + V _{\\text{eff}} (r) = \\frac{1}{b^2} = \\frac{e^2}{l^2}\n\\,.\n\\end{align}\n\nWe want to write this as a differential equation for the radius in terms of the angle \\(\\varphi \\): so, we use the expression of the first integral \n%\n\\begin{align}\n  l = \\dv{\\varphi }{\\lambda } r^2 \\implies \\dv{\\varphi }{\\lambda } = \\frac{l}{r^2} \\implies \\dv{}{\\lambda } = \\frac{l}{r^2} \\dv{}{\\varphi }\n\\,.\n\\end{align}\n%\n\nSo, we can rewrite \n%\n\\begin{align}\n  \\qty(\\dv{r}{\\lambda })^2= \\frac{l^2}{r^{4}} \\qty(\\dv{r}{\\varphi })^2\n\\,,\n\\end{align}\n%\nwhich allows us to write the equation as \n%\n\\begin{align}\n  \\frac{1}{r^{4}} \\qty(\\dv{r}{\\varphi })^2 + V _{\\text{eff}}(r) = \\frac{1}{b^2}\n\\,,\n\\end{align}\n%\nsince the \\(l^2\\) simplifies. \n\nNow, notice that if we define \\(u = 1/r\\) we find\n%\n\\begin{align}\n  \\dv{u}{\\varphi } = - \\frac{1}{r^2} \\dv{r}{\\varphi }\n\\,,\n\\end{align}\n%\nwhich conveniently simplifies the \\(r^{-4}\\): expressing everything with respect to \\(u\\) we get \n%\n\\begin{align}\n  \\qty(\\dv{u}{\\varphi })^2 +  \\qty(u^2-2GMu^3) = \\frac{1}{b^2}\n\\,.\n\\end{align}\n\nNow, we just need to differentiate everything to eliminate the constant term and find \n%\n\\begin{align}\n  2 u' u'' + 2 u u' - 6 GM u^2 u' = 0\n\\,,\n\\end{align}\n%\nwhere we denoted derivatives with respect to \\(\\varphi \\) with primes.\nOne solution is \\(u'=0\\): a circular orbit, which we are not interested in now (and which is unstable\\dots).\n\nOtherwise, we can simplify a factor \\(2 u'\\): we find \n%\n\\begin{align}\n  u'' + u = 3 GMu^2\n\\,\n\\end{align}\n%\nas we wanted to show. \n\n\\subsubsection{Zero black hole mass solution}\n\nIf \\(M=0\\), our diffential equation is simply \\(u''+u=0\\), a harmonic oscillator.\nOur boundary condition is \\(r (\\varphi = 0, \\pi ) \\rightarrow \\infty \\), which means \\(u \\rightarrow 0\\) in those cases. \n\nAlso, one can geometrically see that at any radius \\(\\sin \\varphi = b/r\\) where \\(b\\) is the impact parameter.\nTherefore, \\(bu = \\sin \\varphi \\) or \\(u = \\sin(\\varphi ) / b \\). This actually is already a solution to our differential equation! \n\nWe are giving two boundary conditions, therefore the solution \\(u = \\sin(\\varphi ) / b \\) is unique. \n\n\\subsubsection{Small mass deflection}\n\nWe now insert a mass \\(M\\), and consider a solution which is a perturbation to the sinusoidal one: our proposed solution is \\(u = b^{-1} (\\sin \\varphi + w)\\), and we will only look at the first order in \\(w\\). Substituting into \\(u'' + u = 3GM u^2\\) we get \n%\n\\begin{align}\n  - \\sin \\varphi + w'' + \\sin \\varphi + w = \\frac{3GM}{b} \\qty(\\sin^2 \\varphi + \\cancelto{}{2w  \\sin \\varphi} + \\cancelto{}{w^2})\n\\,,\n\\end{align}\n%\nwhere we kept only terms which are of first order in either \\(GM\\) or \\(w\\), since both are small relative to the scale of the problem. Also, we simplified a common factor of \\(b\\).\nSo the differential equation for \\(w\\) is \n%\n\\begin{align}\n  w'' + w = \\frac{3GM}{b} \\sin^2 \\varphi \n\\,.\n\\end{align}\n\nThis can be solved with an \\emph{ansatz} in the form \\(w = A + B \\sin^2\\varphi\\).\nIts derivatives are \\(w' = 2B \\sin \\varphi \\cos \\varphi = B \\sin(2\\varphi )\\), and \\(w'' = 2B \\cos(2 \\varphi )= 2 B \\qty(1 - 2\\sin^2\\varphi )\\). \n\nPlugging this in we find \n%\n\\begin{align}\n  2 B (1 - 2 \\sin^2 \\varphi) + A + B \\sin^2 \\varphi = \\frac{3GM}{b} \\sin^2 \\varphi \n\\,,\n\\end{align}\n%\nso equating the terms in \\(\\sin^2\\varphi  \\) and the constant ones we get \n%\n\\begin{subequations}\n\\begin{align}\n  \\begin{cases}\n    2B+A = 0 \\\\\n    -3B = 3GMb^{-1}\n  \\end{cases}\n\\,,\n\\end{align}\n\\end{subequations}\n%\nso our perturbation is \\(w = 2 GM b^{-1} (1- \\sin^2 \\varphi / 2)\\), therefore the full solution is \n%\n\\begin{align}\n  u(\\varphi ) = \\frac{1}{b} \\qty(\\sin \\varphi + \\frac{2GM}{b} \\qty(1 - \\frac{\\sin^2 \\varphi }{2}))\n\\,.\n\\end{align}\n%\n\nWhat follows is an alternative derivation, more complicated than plainly discarding the second-order \\(\\sin^2  \\varphi  \\) term and expanding the sine to first order, which gives \\(\\varphi \\sim -2GM/b\\) right away. I did it in this way mostly to check that it still works. \n\nWe want to solve the equation of the particle coming in from radial infinity at an angle \\(\\varphi _{\\text{in}}\\), and leaving at an angle \\(\\varphi _{\\text{out}}\\) towards radial infinity. This means that we are seeking two solutions to \\(r = \\infty \\implies u = 0\\), respectively near \\(\\varphi = 0\\) and \\(\\varphi = \\pi \\). This can be written as a second degree equation in terms of the variable \\(x = \\sin \\varphi \\), and the adimensionalized impact parameter \\(b/ 2GM = d\\), by which we multiply everything to get:  \n%\n\\begin{align}\n  x^2 - 2dx - 2 = 0\n\\,,\n\\end{align}\n%\nwhich can be solved as \n%\n\\begin{align}\n  x =d \\pm \\sqrt{d^2 + 2}\n  = d \\qty(1 \\pm \\sqrt{1 + \\frac{2}{d^2}})\n\\,,\n\\end{align}\n%\nso we have two solutions: one near \\(x=0\\), one near \\(x=2d\\). The second is meaningless, since \\(d \\gg 1 \\) but \\(x \\leq 1\\). Expanding around \\(d = \\infty\\) we find: \n%\n\\begin{align}\n  x = d \\qty(1 - \\qty(1 + \\frac{1}{2} \\frac{2}{d^2})) = -\\frac{d}{2}  \\frac{2}{d^2} = -\\frac{1}{d} = - \\frac{2GM}{b} = \\sin \\varphi \n\\,. \n\\end{align}\n%\n\nSo, we want solutions to this near \\(\\varphi = 0\\) and \\(\\varphi = \\pi \\), and we are working up to first order in \\(\\varphi \\). Then, we have \n%\n\\begin{align}\n  \\varphi _{\\text{in}} = - \\arcsin \\qty(\\frac{2GM}{b}) \n  \\sim - \\frac{2GM}{b}\n\\,\n\\end{align}\n%\nand  \n%\n\\begin{align}\n  \\varphi _{\\text{out}}  = \\pi + \\arcsin \\qty( \\frac{2GM}{b}) \\sim \\pi + \\frac{2GM}{b}\n\\,.\n\\end{align}\n%\nThe deflection can be calculated by assuming \\( \\varphi _{\\text{out}} - \\varphi _{\\text{in}} = \\pi + \\delta \\varphi \\), which gives \n%\n\\begin{align}\n  \\delta \\varphi \\approx \\frac{4GM}{b}\n\\,.\n\\end{align}\n%\n\n\\subsubsection{Newtonian prediciton and Eddington observations (complement)}\n\nThe Newtonian prediction, which is computed using the Keplerian formula for eccentricity (and, notably, simplifying the ``mass'' of a light particle) is instead:\\footnote{\\url{https://arxiv.org/pdf/physics/0508030.pdf}}\n%\n\\begin{align}\n  \\delta \\varphi \\approx \\frac{2GM}{b}\n\\,.\n\\end{align}\n\nDuring the solar eclipse of 1919, Sir Eddington\\footnote{\\url{https://royalsocietypublishing.org/doi/abs/10.1098/rsta.1920.0009}} made two observations: one gave \n%\n\\begin{align}\n  \\delta \\varphi = \\qty(\\SI{4.5(3)}{}) \\frac{GM}{b}\n\\,,\n\\end{align}\n%\nand another gave \n%\n\\begin{align}\n  \\delta \\varphi = \\qty(\\SI{3.7(7)}{}) \\frac{GM}{b}\n\\,.\n\\end{align}\n%\n\n\\subsection{Orbit at 7GM}\n\n\\subsubsection{Orbital radius}\n\nThe radius of a \\(7G M_{\\odot}\\) orbit is equal to \n%\n\\begin{subequations}\n\\begin{align}\n  7GM_{\\odot}/c^2 \\approx\\\\\n  7 \\times \\SI{6.67e-11}{kg m^{3} s^{-2}} \\times \\SI{2e30}{kg} \\times \\qty(\\SI{3e8}{ms^{-1}})^{-2} \\approx \\\\\n  \\approx \\SI{1.0e4}{m}\n\\,,\n\\end{align}\n\\end{subequations}\n%\nor around \\SI{10}{km}. \n\n\\subsubsection{Proper period}\n\nThe equation governing a circular orbit around a BH can be derived from the normalization of the 4-velocity \\(u \\cdot u = -1\\): in terms of \\(u = 1/r\\) it is \n%\n\\begin{align}\n  u_c = \\frac{GM}{l^2} + 3 GM u_c^2\n\\,,\n\\end{align}\n%\nand in our case we know that \\(u_c = 1/7GM\\), substituting in we find \n%\n\\begin{align}\n  \\frac{1}{7GM} = \\frac{GM}{l^2} + \\frac{3GM}{49 (GM)^2}\n\\,,\n\\end{align}\n%\nor \n%\n\\begin{align}\n  l^2 = (GM)^2 \\qty(\\frac{1}{7} - \\frac{3}{49})^{-1}\n  = 7 (GM)^2 \\qty(1 - \\frac{3}{7})^{-1} = \\frac{49}{4} (GM)^2\n\\,, \n\\end{align}\n%\nso \\(l = 7GM/2\\). Now, recall the definition of this first integral: \n%\n\\begin{align}\n  l = \\dv{\\varphi }{\\tau } r^2\n\\,,\n\\end{align}\n%\ninto which we can substitute the expression we found: \n%\n\\begin{align}\n  \\frac{7GM}{2} (7GM)^{-2} = \\frac{1}{14GM} =  \\dv{\\varphi }{\\tau } = \\omega_{\\text{proper}}\n\\,,\n\\end{align}\n%\nwhich gives us the angular velocity as measured by the orbiting observer. We actually have it in units of $1/\\SI{}{m^3 s^{-2}}$, so we will need to multiply by \\(c^3\\) to get inverse seconds.\n\nThis gives us a pulsation of \n%\n\\begin{align}\n  \\omega _{\\text{proper}} = \\frac{c^3}{14GM_{\\odot}} \\approx \n  \\SI{1.44e4}{rad/s}\n\\,,\n\\end{align}\n%\nwhich corresponds to a period of \n%\n\\begin{align}\n  T _{\\text{proper}} = \\frac{2\\pi}{\\omega _{\\text{proper}}} \\approx \\SI{4.36e-4}{s} = \\SI{436}{\\micro s}\n\\,.\n\\end{align}\n\n\\subsubsection{Period at infinity}\n\nNow, to compute the period for an observer at infinity: from the regular equation of motion of a massive observer we have \n%\n\\begin{align}\n  \\frac{e^2-1}{2} = \\frac{1}{2} \\qty(\\dv{r}{\\tau })^2+ \\underbrace{\\qty(-\\frac{GM}{r} + \\frac{l^2}{2r^2} - \\frac{GMl^2}{r^3})}_{V _{\\text{eff}}}\n\\,,\n\\end{align}\n%\nbut since the orbit is circular \\(r\\) is constant so the derivative vanishes, and we can substitute in our expressions for \\(r\\) and \\(l\\) to find out what \\(e\\) is: we get \n%\n\\begin{subequations}\n\\begin{align}\n  \\frac{e^2-1}{2} &= - \\frac{GM}{7GM} + \\frac{(7GM/2)^2}{2\\times (7GM)^2} - \\frac{GM (7GM/2)^2}{(7GM)^3}  \\\\\n&= - \\frac{1}{7}+ \\qty(\\frac{7}{2})^2 \\frac{1}{2\\times 7^2} - \\qty(\\frac{7}{2})^2 \\frac{1}{7^3}  \\\\\n&= -\\frac{3}{56}\n\\,,\n\\end{align}\n\\end{subequations}\n%\ntherefore \\(e = 5 \\sqrt{7} / 14\\). Now recall the definition of \\(e\\): \n%\n\\begin{align}\n  e = \\dv{t}{\\tau } \\qty(1 - \\frac{2GM}{r}) \n\\,,\n\\end{align}\n%\nso \n%\n\\begin{align}\n  \\frac{T_{ \\infty }}{T _{\\text{proper}}} = \n  \\dv{t}{\\tau } = \\frac{5 \\sqrt{7}}{14} \\qty(1 - \\frac{2GM}{7GM})^{-1} = \\frac{\\sqrt{7}}{2} \\approx 1.323 \n\\,,\n\\end{align}\n%\ntherefore the period as measured by the outside observer is \n%\n\\begin{align}\n  T_{ \\infty } \\approx \\SI{577}{\\micro s}\n\\,.\n\\end{align}\n%\n\nDo note that this is \\emph{not} the same as plainly applying the gravitational redshift formula as \\(T_1 / T_2 = \\sqrt{ g_{tt}^{1}/ g_{tt}^{2}}\\): that gives a smaller ratio. The Doppler effects of the orbital speed do not average out over a period: this is treated in more depth in section \\ref{sec:general-time-dilation}. \n\nAn alternative way to derive \\(\\dv*{t}{\\tau }\\) is to use \\(\\Omega \\): we defined it as \\(\\dv*{\\varphi }{t}\\), and proved that it is given by \n%\n\\begin{align}\n  \\Omega^2 = \\qty(\\dv{\\varphi }{\\tau } \\dv{\\tau }{t})^2\n  = \\frac{GM}{r^3}\n\\,.\n\\end{align}\n\nIt allows us to write the 4-velocity as \n%\n\\begin{align}\n  u^{\\alpha } = \\qty(\\dv{t}{\\tau }, 0, 0, \\dv{\\varphi}{\\tau })^{\\top} = \\dv{t}{\\tau } \\qty(1, 0, 0, \\Omega )^{\\top}\n\\,.\n\\end{align}\n\nNow, we can write the proper time interval starting from the line element: \n%\n\\begin{align}\n  - \\dd{s^2} = \\dd{\\tau^2} \n  = g_{00} \\dd{t^2} - g_{33} \\dd{\\varphi^2}\n  = \\dd{t^2} \\qty(g_{00} - g_{33} \\Omega^2)\n\\,,\n\\end{align}\n%\nwhich we can calculate, since we know all the parameters: we find\n%\n\\begin{align}\n  \\frac{\\dd{\\tau^2 }}{ \\dd{t^2}} = \\qty(1 - \\frac{2GM}{r} - r^2 \\frac{GM}{r^3})\n  = \\qty(1 - \\frac{3GM}{r})\n\\,.\n\\end{align}\n\nThis gives \n%\n\\begin{align}\n  \\dd{t}  = \\frac{\\dd{\\tau }}{\\sqrt{1 - \\frac{3GM}{r}}}\n  \\sim \\dd{\\tau } \\qty(1 + \\frac{3GM}{2r})\n\\,.\n\\end{align}\n%\n\n\n\\subsubsection{Proper acceleration}\n\nThe orbit is a geodesic, so a pointlike observer feels no acceleration. \n\n\\subsubsection{Adimensionalized parameters of motion and a general formula for time dilation (complement)} \\label{sec:general-time-dilation}\n\nWe can make the expressions above more clear in terms of adimensionalized coordinates: we will use \\(R = r/(2GM)\\), \\(L = l / (2GM)\\), while \\(e\\) is already adimensional. \nUnder the assumption of circularity for the orbit, the expression for \\(L\\) can be calculated to be:\n%\n\\begin{align}\n  L  =\\frac{R}{\\sqrt{2 R - 3}}\n\\,,\n\\end{align}\n%\nwhile the one for \\(e\\) is: \n%\n\\begin{align}\n  e^2 = \\qty(1 + \\frac{L^2}{R^2}) \\qty(1 - \\frac{1}{R})\n\\,.\n\\end{align}\n\nAlso, the definition for \\(e\\) is \n%\n\\begin{align}\n  e = \\dv{t}{\\tau } \\qty(1 - \\frac{1}{R})\n\\,,\n\\end{align}\n%\ntherefore we can write \n%\n\\begin{subequations}\n\\begin{align}\n  \\dv{t}{ \\tau } = e \\qty(1-\\frac{1}{R})^{-1} &= \\qty(1 - \\frac{1}{R})^{-1+1/2} \\qty(1+ \\frac{1}{2 R - 3})^{1/2} \\\\\n  &= \\frac{\\sqrt{1 + \\displaystyle \\frac{1}{2R-3}}}{\\sqrt{ 1- \\displaystyle \\frac{1}{R}}}\n  = \\sqrt{ \\frac{2R-3+1}{2R-3} \\frac{R}{R-1}} \n  = \\sqrt{\\frac{R}{R - 3/2}}\n\\,.\n\\end{align}\n\\end{subequations}\n\nWith this, we can see that in the limit of \\(R \\rightarrow \\infty\\) we have the following effect: \n%\n\\begin{align}\n  \\dv{t}{\\tau } \\sim \\sqrt{1 + \\frac{1}{R} + \\frac{1}{2R-3} }\n  \\sim 1 + \\frac{1}{2} \\bigg( \\underbrace{\\frac{1}{2R}}_{\\text{gravitational}} + \\underbrace{\\frac{1}{R}}_{\\text{Doppler}} \\bigg)  = 1 + \\frac{3}{4R}\n\\,,\n\\end{align}\n%\nwhere we have a contribution both from the angular momentum, and from the gravitational redshift; the gravitational contribution is larger than the Doppler one in the limit (specifically for any \\(R>2\\)), and the ratio between the contributions approaches \\(2\\).\n\nAlso, we can see that we have a divergence of this time dilation at \\(R \\rightarrow 3/2\\): \nI suspect that this corresponds to the velocity needed to stay in orbit at constant \\(R\\) diverges towards 1 as \\(R \\rightarrow 3/2\\).\n\nIn our specific case, the formula comes out to be \n%\n\\begin{align}\n  \\dv{t}{\\tau } = \\underbrace{\\sqrt{\\frac{7}{5}}}_{\\text{grav}} \\underbrace{\\sqrt{\\frac{5}{4}}}_{\\text{Dopp}} = \\sqrt{\\frac{7}{4}}\n\\,.\n\\end{align}\n\n\\subsubsection{Tidal acceleration (complement)}\n\nA pointlike particle would feel no acceleration, however it would be quite unconfortable to be in that orbit if one happens not to be pointlike. \nAs for the first part of the exercise, this is not in the exercise sheet, so do skip it if you are in a hurry. I think it is quite interesing though.\n\nLet us compute the tidal effects on an extended observer. \n\nThey are described by the equation \n%\n\\begin{align}\n  \\dv[2]{\\xi^{\\mu }}{\\tau } = R^{\\mu }_{\\nu \\rho \\sigma } u^{\\nu } u^{\\rho } \\xi^{\\sigma }\n\\,,\n\\end{align}\n%\nwhere \\(u^{\\mu }\\) is the 4-velocity of a geodesic, \\(\\xi^{ \\mu } \\) is a small deviation in starting position for the geodesic such that the geodesic starting from there almost has the same tangent vector. For now we assume it to be true, in the next section we give justification for it. \n\nWe can restrict ourselves to radial geodesic deviation: then we only need to compute the \\(R^{r}_{\\nu \\rho r}\\) components of the Riemann tensor. \nI might do the full computation, but I found a source\\footnote{\\url{https://physics.stackexchange.com/questions/295814/non-zero-components-of-the-riemann-tensor-of-the-schwarzschild-metric}} which gives the nonzero components: \n%\n\\begin{subequations}\n\\begin{align}\n  R^{r}_{ttr} &= \\frac{2GM}{r^3} \\qty(1 - \\frac{2GM}{r}) \\\\\n  R^{r}_{\\theta \\theta r} &= \\frac{GM}{r} \\\\\n  R^{r}_{\\varphi \\varphi r} &= \\frac{G M \\sin^2\\theta}{r} \n\\,,\n\\end{align}\n\\end{subequations}\n%\nand since the orbital motion is assumed to happen on the \\(\\theta = \\pi /2\\) plane, the formula simplifies to \n%\n\\begin{subequations}\n\\begin{align}\n  \\dv[2]{\\xi^{r}}{\\tau } &= R^{r}_{ttr} u^{t} u^{t} \\xi^{r} \n  + R^{r }_{\\varphi \\varphi r} u^{\\varphi } u^{\\varphi } \\xi^{r}  \\\\\n  &= \\qty(\\frac{e^2}{(1-2GM/r)^2} \\frac{2GM}{r^{3}}\\qty(1 - \\frac{2GM}{r}) +  \\frac{l^2}{r^{4}} \\frac{GM}{r}) \\xi^{r}  \\\\\n  &= \\qty(\\frac{e^2}{1-2GM/r} + \\frac{l^2}{r^2} ) \\frac{2GM}{r^3} \\xi^{r}\n\\,,\n\\end{align}\n\\end{subequations}\n%\nwhich holds in general: in our specific case, at \\(r = 7GM \\) we find \n%\n\\begin{subequations}\n\\begin{align}\n  \\dv[2]{\\xi^{r}}{\\tau } &= \\qty(\\frac{7}{5} \\qty(\\frac{5 \\sqrt{7}}{14})^2 + \\qty(\\frac{7GM/2}{7GM})^2 ) \\frac{2GM}{(7GM)^3}  \\xi^{r}  \\\\\n  &= \\frac{3}{343} \\frac{1}{(GM)^2} \\xi^{r}\n\\,,\n\\end{align}\n\\end{subequations}\n%\nso the object multiplying \\(\\xi^{r}\\), in units of inverse square seconds, is \n%\n\\begin{align}\n  \\frac{3}{343} \\frac{c^{6}}{(GM)^2} \\approx \\SI{356e6}{s^{-2}}\n  \\approx \\qty(\\SI{18.9}{kHz})^2\n\\,. \n\\end{align}\n\nThe acceleration which would be experienced from one side of the other of a meter-long observer would then be of around \\SI{36}{M}\\(g\\). \n\n\\subsubsection{A proof for the geodesic deviation formula (complement)}\n\nThe starting separation between geodesics is not, properly speaking, a \\emph{vector} since it does not belong to the tangent space, however we can be sloppy and approximate it as a tangent vector.\nThen it is a fact from differential geometry that under an assumption of vanishing torsion (which we always make anyways in GR) and if the vector fields \\(u^{\\mu }\\) and \\(\\xi^{\\mu }\\) commute (which they do) the following holds: \n%\n\\begin{align} \\label{eq:lie-bracket-commutation}\n  \\xi^{\\mu } \\nabla_{\\mu } u^{\\nu } = u^{\\mu } \\nabla_{\\mu } \\xi^{\\nu }\n\\,.\n\\end{align}\n\nSo, we want to see by how much the two initially-close geodesics diverge: in order to do this, we compute the second derivative of \\(\\xi^{\\mu }\\) with respect to proper time: recall that the derivative with respect to proper time is also the Lie derivative along the 4-velocity: \\(\\dv*{}{\\tau } = u^{\\mu } \\nabla_{\\mu }\\). \n\nSo, this second derivative looks like \n%\n\\begin{align}\n  \\dv[2]{\\xi^{ \\mu } }{\\tau } = u^{\\alpha } \\nabla_{\\alpha } \\qty(u^{\\beta } \\nabla_{\\beta } \\xi^{\\mu })\n  = u^{\\alpha } \\nabla_{\\alpha } \\qty( \\xi^{\\beta }\\nabla_{\\beta } u^{\\mu } )\n\\,\n\\end{align}\n%\nby the formula shown above. Now, we can apply the Leibniz rule: we find \n%\n\\begin{align}\n  \\dv[2]{\\xi^{\\mu }}{\\tau } = u^{\\alpha } \\qty( \\qty(\\nabla_{\\alpha } \\xi^{\\beta }) \\qty(\\nabla_{\\beta } u^{\\mu })  \n  + \\xi^{\\beta } \\nabla_{\\alpha } \\nabla_{\\beta } u^{\\mu } )\n\\,,\n\\end{align}\n%\nand using the fact that\\footnote{A trick for remembering this: it would be intuitive to just write the lower indices as \\(\\alpha \\beta \\gamma \\), but the last two are antisymmetric and must correspond to the antisymmetrization of the covariant derivatives in the LHS.} \\([\\nabla_{\\alpha }, \\nabla_{\\beta }] V^{\\mu } = R^{\\mu }_{ \\gamma \\alpha \\beta  } V^{\\gamma }\\) we can commute the covariant derivatives by inserting a Riemann tensor: we get \n%\n\\begin{align}\n  \\dv[2]{\\xi^{\\mu }}{\\tau } = u^{\\alpha } \\qty( \\qty(\\nabla_{\\alpha } \\xi^{\\beta }) \\qty(\\nabla_{\\beta } u^{\\mu })  \n  + \\xi^{\\beta } \\nabla_{\\beta }\\nabla_{\\alpha } u^{\\mu }\n  + \\xi^{\\beta } R^{\\mu }_{ \\gamma \\alpha \\beta  } u^{\\gamma } )\n\\,,\n\\end{align}\n%\nand now we have gotten the term which will remain in the end: let us bring it to the front, then we will show that the rest of the expression is null. We get \n%\n\\begin{align}\n  \\dv[2]{\\xi^{\\mu }}{\\tau } =\n  R^{\\mu }_{ \\gamma \\alpha \\beta  } u^{\\gamma } u^{\\alpha } \\xi^{\\beta } \n  + \n  u^{\\alpha } \\qty( \\qty(\\nabla_{\\alpha } \\xi^{\\beta }) \\qty(\\nabla_{\\beta } u^{\\mu })  \n  + \\xi^{\\beta } \\nabla_{\\beta }\\nabla_{\\alpha } u^{\\mu } )\n\\,.\n\\end{align}\n%\n\nTo show that the rest of the expression is zero, the thing to remember is that we want to use the fact that our curve is a geodesic, which is expressed as \n%\n\\begin{align}\n  u^{\\alpha } \\nabla_{\\alpha } u^{\\mu } = \\dv{}{\\tau } u^{\\mu } = 0 \n\\,,\n\\end{align}\n%\nso we apply the Leibniz rule backward, to find: \n%\n\\begin{subequations}\n\\begin{align}\n  & u^{\\alpha } \\qty( \\qty(\\nabla_{\\alpha } \\xi^{\\beta }) \\qty(\\nabla_{\\beta } u^{\\mu })  \n  + \\xi^{\\beta } \\nabla_{\\beta }\\nabla_{\\alpha } u^{\\mu } )= \\\\\n  =& u^{\\alpha } \\qty(\\nabla_{\\alpha } \\xi^{\\beta }) \\qty(\\nabla_{\\beta } u^{\\mu }) \n  + \\xi^{\\beta } \\nabla_{ \\beta } \\qty( \\cancelto{}{u^{\\alpha } \\nabla_{\\alpha } u^{\\mu }}) \n  - \\xi^{\\beta } \\qty(\\nabla_{\\alpha } u^{\\mu } ) (\\nabla_{\\beta } u^{\\alpha })  \\\\\n  =& u^{\\alpha } \\qty(\\nabla_{\\alpha } \\xi^{\\beta }) \\qty(\\nabla_{\\beta } u^{\\mu }) \n  - u^{\\beta } \\nabla_{\\beta }\\xi^{\\alpha } ( \\nabla_{\\alpha } u^{\\mu }) = 0\n\\,,\n\\end{align}\n\\end{subequations}\n%\nwhere in the last step we applied again the commutation relation \\eqref{eq:lie-bracket-commutation}, and finally recognised that the terms were equal up to a relabeling of indices. \n\n\n\n\\end{document}\n", "meta": {"hexsha": "0e2b274aec0a8c1d0f49a5de7d35ffd62dadcc07", "size": 33329, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ap_first_semester/gr_exercises/sheet7.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "ap_first_semester/gr_exercises/sheet7.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ap_first_semester/gr_exercises/sheet7.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 36.266594124, "max_line_length": 522, "alphanum_fraction": 0.6333223319, "num_tokens": 12058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.3405219522786202}}
{"text": "% chapter included in vclmanual.tex\n\\documentclass[vcl_manual.tex]{subfiles}\n\\begin{document}\n\n\n\\chapter{Permute, blend, lookup, gather and scatter functions}\\label{chap:PermuteBlendEtc}\n\n\\section{Permute functions}\\label{PermuteFunctions}\n\\flushleft\n\n\\vspacesmall\n\\begin{tabular}{|p{30mm}|p{120mm}|}\n\\hline\n\\bfseries Function & permute..\\textless i0, i1, ...\\textgreater(vector) \\\\ \\hline\n\\bfseries Defined for & all integer and floating point vector classes \\\\ \\hline\n\\bfseries Description & permutes vector elements \\\\ \\hline\n\\bfseries Efficiency & depends on parameters and instruction set \\\\ \\hline\n\\end{tabular}\n\\vspacesmall\n\nThe permute functions can move any element of a vector into any position, copy the same element to multiple positions, and set any element to zero.\n\\vspacesmall\n\nThe name of the permute function is \"permute\" followed by the number of vector elements, for example permute4 for Vec4i. The permute function for a vector of $n$ elements has $n$ indexes, which are entered as template parameters in angle brackets. Each index indicates the desired contents of the corresponding element in the result vector. An index $i$ in the interval\n$0 \\leq i \\leq n-1$ indicates that element number $i$ from the input vector should be placed in the corresponding position in the result vector. An index $i = -1$ gives a zero in the corresponding position. An index $i$ = V\\_DC means don't care. This will give whatever implementation is fastest, regardless of what value it puts in this position. The value you get with \"don't care\" may be different for different implementations or different instruction sets.\n\\vspacesmall\n\n\\begin{lstlisting}[frame=none]\n// Example:\nVec4i a(10, 11, 12, 13);\nVec4i b = permute4<2,2,3,0>(a);   // b = (12, 12, 13, 10)\nVec4i c = permute4<-1,-1,1,1>(a); // c = ( 0,  0, 11, 11)\n\\end{lstlisting}\n\\vspacesmall\n\nThe indexes in angle brackets must be compile-time constants, they cannot contain variables or function calls. If you need variable indexes then use the lookup functions instead (see page \\pageref{LookupFunctions}).\n\\vspacesmall\n\nThe permute functions contain a lot of metaprogramming code which is used for finding the best instructions for the given set of indexes and the specified instruction set. The metaprogramming may produce extra code when compiling in debug mode, but this extra code is eliminated when compiling for release mode with optimization on. The call to a permute function is reduced to just one or a few machine instructions in favorable cases. \n\\vspacesmall\n\nThe performance is generally good when the instruction set SSSE3 or higher is enabled. The performance for permuting vectors of 16-bit integers is medium, and the performance for permuting vectors of 8-bit integers is poor for instruction sets lower than SSSE3. You may get the best performance with instruction set AVX2 or AVX512VL.\n\\vspacesmall\n\n\n\\section{Blend functions}\\label{BlendFunctions}\n\n\\vspacesmall\n\\begin{tabular}{|p{30mm}|p{120mm}|}\n\\hline\n\\bfseries Function & blend..\\textless i0, i1, ...\\textgreater(vector, vector) \\\\ \\hline\n\\bfseries Defined for & all integer and floating point vector classes \\\\ \\hline\n\\bfseries Description & permutes and blends elements from two vectors \\\\ \\hline\n\\bfseries Efficiency & depends on parameters and instruction set \\\\ \\hline\n\\end{tabular}\n\\vspacesmall\n\nThe blend functions are similar to the permute functions, but with two input vectors. \nThe name of the permute function is \"blend\" followed by the number of vector elements, for example blend4 for Vec4i. The blend function for a vector of $n$ elements has $n$ indexes, which are entered as template parameters in angle brackets. Each index indicates the desired contents of the corresponding element in the result vector. The indexes must be compile-time constants.\nAn index $i$ in the interval $0 \\leq i \\leq n-1$ indicates that element number $i$ from the first input vector should be placed in the corresponding position in the result vector. An index $i$ in the interval $n \\leq i \\leq 2 \\cdot n-1$ indicates that element number $i-n$ from the second input vector should be placed in the corresponding position in the result vector. An index $i$ = -1 gives a zero in the corresponding position. An index $i$ = V\\_DC means don't care.\n\n\\begin{lstlisting}[frame=none]\n// Example:\nVec4i a(10, 11, 12, 13);\nVec4i b(20, 21, 22, 23);\nVec4i c = blend4<4,0,4,3>(a, b); // c = (20, 10, 20, 13)\n\\end{lstlisting}\n\\vspacesmall\n\nThere are different methods you can use if you want to blend inputs from more than two vectors: \n\\vspacesmall\n\n1. A binary tree of blend calls, where unused values are set to V\\_DC meaning don't care.\n\\begin{lstlisting}[frame=none]\n// Example:\nVec4i a(10, 11, 12, 13);\nVec4i b(20, 21, 22, 23);\nVec4i c(30, 31, 32, 33);\nVec4i d(40, 41, 42, 43);\nVec4i r = blend4<0,5,V_DC,V_DC>(a, b);// r = (10,21,?,?)\nVec4i s = blend4<V_DC,V_DC,2,7>(c, d);// s = (?,?,32,43)\nVec4i t = blend4<0,1,6,7>(r, s);      // t = (10,21,32,43)\n\\end{lstlisting}\n\\vspacesmall\n\n2. Set unused values to zero, then OR the results.\n\\begin{lstlisting}[frame=none]\n// Example:\nVec4i a(10, 11, 12, 13);\nVec4i b(20, 21, 22, 23);\nVec4i c(30, 31, 32, 33);\nVec4i d(40, 41, 42, 43);\nVec4i r = blend4<0,5,-1,-1>(a, b);// r = (10,21,0,0)\nVec4i s = blend4<-1,-1,2,7>(c, d);// s = (0,0,32,43)\nVec4i t = r | s;                  // t = (10,21,32,43)\n\\end{lstlisting}\n\\vspacesmall\n\n3. If the input vectors are stored sequentially in memory then use the lookup functions shown below.\n\\vspacesmall\n\n\n\\section{Lookup functions}\\label{LookupFunctions}\n\\vspacesmall\n\n\\begin{tabular}{|p{30mm}|p{120mm}|}\n\\hline\n\\bfseries Function & Vec16c lookup16(Vec16c, Vec16c) \\newline\nVec32c lookup32(Vec32c, Vec32c) \\newline\nVec64c lookup64(Vec64c, Vec64c) \\newline\nVec8s lookup8(Vec8s, Vec8s) \\newline\nVec16s lookup16(Vec16s, Vec16s) \\newline\nVec32s lookup32(Vec32s, Vec32s) \\newline\nVec4i lookup4(Vec4i, Vec4i) \\newline\nVec8i lookup8(Vec8i, Vec8i) \\newline\nVec16i lookup16(Vec16i, Vec16i) \\newline\nVec4q lookup4(Vec4q, Vec4q) \\newline\nVec8q lookup8(Vec8q, Vec8q) \\\\ \\hline\n\\bfseries Defined for & Vec16c, Vec32c, Vec64c, Vec8s, Vec16s, Vec32s, Vec4i, Vec8i, Vec16i, Vec4q, Vec8q \\\\ \\hline\n\\bfseries Description & Permutation with variable indexes. The first input vector contains the indexes, the second input vector is the data source. Each index must be in the range  $0 \\leq i \\leq n-1$ where n is the number of elements in a vector. \\\\ \\hline\n\\bfseries Efficiency & \nVec16i, Vec8q: Good for AVX512F, medium otherwise.  \\newline\nVec64c, Vec32s: Good for AVX512VBMI, medium for AVX512BW, poor otherwise. \\newline\nVec32c, Vec16s, Vec8i, Vec4i, Vec4q: Good for AVX2, medium otherwise. \\newline\nVec16c, Vec8s: Good for SSSE3, poor otherwise. \\\\ \\hline\n\\end{tabular}\n\\vspacebig\n\n\n\\begin{tabular}{|p{30mm}|p{120mm}|}\n\\hline\n\\bfseries Function & \nVec16c lookup32(Vec16c, Vec16c, Vec16c) \\newline\nVec64c lookup128(Vec64c, Vec64c, Vec64c) \\newline\nVec8s lookup16(Vec8s, Vec8s, Vec8s) \\newline\nVec32s lookup64(Vec32s, Vec32s, Vec32s) \\newline\nVec4i lookup8(Vec4i, Vec4i, Vec4i) \\newline\nVec16i lookup32(Vec16i, Vec16i, Vec16i) \\\\ \\hline\n\\bfseries Defined for & Vec16c, Vec64c, Vec8s, Vec32s, Vec4i, Vec16i \\\\ \\hline\n\\bfseries Description & Blend with variable indexes. The first input vector contains the indexes, the following two input vectors contain the data source. Each index must be in the range  $0 \\leq i \\leq 2\\cdot n - 1$ where n is the number of elements in each vector. \\\\ \\hline\n\\bfseries Efficiency & \nVec4i, Vec8s: Good for AVX2, medium or poor otherwise. \\newline\nVec16i: Good for AVX512, medium or poor otherwise. \\newline\nVec64c, Vec32s: Good for AVX512VBMI, medium for AVX512BW, poor otherwise. \\newline\nVec16c, Vec8s: Good for SSSE3, poor otherwise. \\\\ \\hline\n\\end{tabular}\n\\vspacebig\n\n\n\\begin{tabular}{|p{30mm}|p{120mm}|}\n\\hline\n\\bfseries Function & \nVec4i lookup16(Vec4i, Vec4i, Vec4i, Vec4i, Vec4i) \\newline\nVec16i lookup64(Vec16i, Vec16i, Vec16i, Vec16i, Vec16i) \\newline\nVec64c lookup256(Vec64c, Vec64c, Vec64c, Vec64c, Vec64c) \\newline\nVec32s lookup128(Vec32s, Vec32s, Vec32s, Vec32s, Vec32s) \\\\ \\hline\n\\bfseries Defined for & Vec4i, Vec32s, Vec64c \\\\ \\hline\n\\bfseries Description & Blend with variable indexes. The first input vector contains the indexes, the following four input vectors contain the data source. Each index must be in the range  $0 \\leq i \\leq 4\\cdot n - 1$ where n is the number of elements in each vector. \\\\ \\hline\n\\bfseries Efficiency & \nVec4i: Good for AVX2, medium otherwise. \\newline\nVec16i: Good for AVX512, medium or poor otherwise. \\newline\nVec64c, Vec32s: Good for AVX512VBMI, medium for AVX512BW, poor otherwise. \n\\\\ \\hline\n\\end{tabular}\n\\vspacebig\n\n\n\\begin{tabular}{|p{30mm}|p{120mm}|}\n\\hline\n\\bfseries Function & Vec4f lookup4(Vec4i, Vec4f) \\newline\nVec8f lookup8(Vec8i, Vec8f) \\newline\nVec16f lookup16(Vec16i, Vec16f) \\newline\nVec2d lookup2(Vec2q, Vec2d) \\newline\nVec4d lookup4(Vec4q, Vec4d) \\newline\nVec8d lookup8(Vec8q, Vec8d) \\\\ \\hline\n\\bfseries Defined for & all floating point vector classes \\\\ \\hline\n\\bfseries Description & Permutation of floating point vectors with integer indexes. Each index must be in the range  $0 \\leq i \\leq n-1$ where n is the number of elements in a vector. \\\\ \\hline\n\\bfseries Efficiency & good for AVX2 and later, medium for lower instruction sets \\\\ \\hline\n\\end{tabular}\n\\vspacebig\n\n\n\\begin{tabular}{|p{30mm}|p{120mm}|}\n\\hline\n\\bfseries Function & Vec4f lookup8(Vec4i, Vec4f, Vec4f) \\newline\nVec2d lookup4(Vec2q, Vec2d, Vec2d) \\\\ \\hline\n\\bfseries Defined for & Vec4f, Vec2d \\\\ \\hline\n\\bfseries Description & Blend of floating point vectors with integer indexes. Each index must be in the range  $0 \\leq i \\leq 2*n-1$ where n is the number of elements in a vector. \\\\ \\hline\n\\bfseries Efficiency & medium \\\\ \\hline\n\\end{tabular}\n\\vspacebig\n\n\n\\begin{tabular}{|p{30mm}|p{120mm}|}\n\\hline\n\\bfseries Function & Vec16c lookup\\textless n\\textgreater(Vec16c index, void const * table) \\newline\nVec32c lookup\\textless n\\textgreater(Vec32c index, void const * table) \\newline\nVec8s lookup\\textless n\\textgreater(Vec8s index, void const * table) \\newline\nVec16s lookup\\textless n\\textgreater(Vec16s index, void const * table) \\newline\nVec4i lookup\\textless n\\textgreater(Vec4i index, void const * table) \\newline\nVec8i lookup\\textless n\\textgreater(Vec8i index, void const * table) \\newline\nVec16i lookup\\textless n\\textgreater(Vec16i index, void const * table) \\newline\nVec4q lookup\\textless n\\textgreater(Vec4q index, void const * table) \\newline\nVec8q lookup\\textless n\\textgreater(Vec8q index, void const * table) \\newline\nVec4f lookup\\textless n\\textgreater(Vec4i index, float const * table) \\newline\nVec8f lookup\\textless n\\textgreater(Vec8i const \\& index, float const * table) \\newline\nVec16f lookup\\textless n\\textgreater(Vec16i const \\& index, float const * table) \\newline\nVec2d lookup\\textless n\\textgreater(Vec2q index, double const * table) \\newline\nVec4d lookup\\textless n\\textgreater(Vec4q const \\& i, double const * table) \\newline\nVec8d lookup\\textless n\\textgreater(Vec8q const \\& i, double const * table) \\\\ \\hline\n\\bfseries Defined for & all floating point and signed integer vector classes \\\\ \\hline\n\\bfseries Description & Permute, blend, table lookup or gather data from array with an integer vector of indexes.\\newline\nEach index must be in the range  $0 \\leq i \\leq n-1$, where $n$ is indicated as a template parameter. $n$ must be a positive compile-time constant. \\\\ \\hline\n\\bfseries Efficiency & good for AVX2 and later, medium for lower instruction sets \\\\ \\hline\n\\end{tabular}\n\\vspacebig\n\n\nThe lookup functions are similar to the permute and blend functions, but with variable indexes. They cannot be used for setting an element to zero, and there is no \"don't care\" option. The lookup functions can be used for several purposes:\n\n\\begin{enumerate}\n\\item permute with variable indexes\n\\item blend with variable indexes\n\\item blend from more than two sources\n\\item table lookup\n\\item gather non-contiguous data from an array\n\\end{enumerate}\n\\vspacesmall\n\nThe index is always an integer vector. The input can be one or more vectors or an array. The result is a vector of the same type as the input. All elements in the index vector must be in the specified range. The behavior for an index out of range is implementation-dependent and may give any value for the corresponding element. The function may in some cases read up to one vector size past the end of the table for the sake of efficient permutation.\n\\vspacesmall\n\nThe lookup functions are not defined for unsigned integer vector types, but the corresponding signed versions can be used. You don't have to worry about overflow when converting unsigned integers to signed here, as long as the result vector is converted back to unsigned.\n\\vspacebig\n\n\n\\begin{lstlisting}[frame=none]\n// Example of permutation with variable indexes:\nVec4f a(1.0, 1.1, 1.2, 1.3);\nVec4i b(2, 3, 3, 0);\nVec4f c = lookup4(b, a);  // c = (1.2, 1.3, 1.3, 1.0)\n\n// Example of blending with variable indexes:\nVec4f a(1.0, 1.1, 1.2, 1.3);\nVec4f b(2.0, 2.1, 2.2, 2.3);\nVec4i c(4, 3, 2, 7);\nVec4f d = lookup4(c,a,b); // d = (2.0, 1.3, 1.2, 2.3)\n\n// Example of blending from more than two sources:\nfloat sources[12] = {\n1.0,1.1,1.2,1.3,2.0,2.1,2.2,2.3,3.0,3.1,3.2,3.3};\nVec4i i(11, 0, 5, 5);\nVec4f c = lookup<12>(i, sources); // c = (3.3,1.0,2.1,2.1)\n\\end{lstlisting}\n\\vspacebig\n\n\nA function with a limited number of possible input values can be replaced by a lookup table. This is useful if table lookup is faster than calculating the function. The following example has a table of the function $y = x^2 - 1$\n\n\\begin{lstlisting}[frame=none]\n// Table of the function y = x*x-1\nint table[6] = {-1,0,3,8,15,24};\nVec4i x(4,2,0,5);\nVec4i y = lookup<6>(x, table);  // y = (15, 3, -1, 24)\n\n// Example of gathering non-contiguous data from an array:\nfloat x[16] = { ... };\nVec4i i(0,4,8,12);\nVec4f y = lookup<16>(i, x); // y = (x[0],x[4],x[8],x[12])\n\\end{lstlisting}\n\\vspacesmall\n\n\n\\section{Gather functions}\\label{GatherFunctions}\n\n\\vspacesmall\n\\begin{tabular}{|p{30mm}|p{120mm}|} \\hline\n\\bfseries Function & \nVec4i gather4i\\textless indexes\\textgreater(void const * table) \\newline\nVec8i gather8i\\textless indexes\\textgreater(void const * table) \\newline\nVec16i gather16i\\textless indexes\\textgreater(void const * table) \\newline\nVec2q gather2q\\textless indexes\\textgreater(void const * table) \\newline\nVec4q gather4q\\textless indexes\\textgreater(void const * table) \\newline\nVec8q gather8q\\textless indexes\\textgreater(void const * table) \\newline\nVec4f gather4f\\textless indexes\\textgreater(void const * table) \\newline\nVec8f gather8f\\textless indexes\\textgreater(void const * table) \\newline\nVec16f gather16f\\textless indexes\\textgreater(void const * table) \\newline\nVec2d gather2d\\textless indexes\\textgreater(void const * table) \\newline\nVec4d gather4d\\textless indexes\\textgreater(void const * table) \\newline\nVec8d gather8d\\textless indexes\\textgreater(void const * table) \\\\ \\hline\n\\bfseries Defined for & Vec4i, Vec8i, Vec16i, Vec2q, Vec4q, Vec8q, \\newline\nVec4f, Vec8f, Vec16f, Vec2d, Vec4d, Vec8d \\\\ \\hline\n\\bfseries Description & Load non-contiguous data from a table. Indexes cannot be negative. There is no option for zeroing or don't care.  \\newline\nIf you need variable indexes, then use the lookup functions instead. \\newline\nThe function may read a full vector and permute it if all indexes are smaller than the vector size.  \\\\ \\hline\n\\bfseries Efficiency & medium \\\\ \\hline\n\\end{tabular}\n\\vspacesmall\n\n\\begin{lstlisting}[frame=none]\n// Example:\nint tab[8] = {10,11,12,13,14,15,16,17};\nVec4i a = gather4i<6,4,4,0>(tab);\n// a = (16, 14, 14, 10);\n\\end{lstlisting}\n\\vspacesmall\n\n\n\\section{Scatter functions}\\label{Scatter functions}\n\n\\begin{tabular}{|p{30mm}|p{120mm}|} \\hline\n\\bfseries Function & scatter\\textless indexes\\textgreater(Vec4i data, void * array) \\newline\nscatter\\textless indexes\\textgreater(Vec8i data, void * array) \\newline\nscatter\\textless indexes\\textgreater(Vec16i data, void * array) \\newline\nscatter\\textless indexes\\textgreater(Vec2q data, void * array) \\newline\nscatter\\textless indexes\\textgreater(Vec4q data, void * array) \\newline\nscatter\\textless indexes\\textgreater(Vec8q data, void * array) \\newline\nscatter\\textless indexes\\textgreater(Vec4f data, float * array) \\newline\nscatter\\textless indexes\\textgreater(Vec8f data, float * array) \\newline\nscatter\\textless indexes\\textgreater(Vec16f data, float * array) \\newline\nscatter\\textless indexes\\textgreater(Vec2d data, double * array) \\newline\nscatter\\textless indexes\\textgreater(Vec4d data, double * array) \\newline\nscatter\\textless indexes\\textgreater(Vec8d data, double * array) \\\\ \\hline\n\\bfseries Defined for & \nVec4i, Vec8i, Vec16i, Vec2q, Vec4q, Vec8q, \\newline\nVec4f, Vec8f, Vec16f, Vec2d, Vec4d, Vec8d \\\\ \\hline\n\\bfseries Description & Store vector elements into non-contiguous positions in an array. Each vector element is stored in the array position indicated by the corresponding index. An element is not stored if the corresponding index is negative. \\\\ \\hline\n\\bfseries Efficiency & \nMedium for 512 bit vectors if AVX512F instruction set supported. \\newline\nMedium for 256 bit vectors if AVX512F, or better AVX512VL, supported. \\newline\nMedium for 128 bit vectors if AVX512VL supported. \\newline\nPoor otherwise. \\\\ \\hline\n\\end{tabular}\n\\vspacesmall\n\n\\begin{lstlisting}[frame=none]\n// Example:\nVec8i a(10,11,12,13,14,15,16,17);\nint array[10] = {0};\nscatter<5,4,3,2,-1,-1,7,0>(a, array);\n// array = (17,0,13,12,11,10,0,16,0,0)\n\\end{lstlisting}\n\\vspacebig\n\n\n\\begin{tabular}{|p{30mm}|p{120mm}|} \\hline\n\\bfseries Function & \nscatter(Vec4i index, uint32\\_t limit, Vec4i data, void * array) \\newline\nscatter(Vec8i index, uint32\\_t limit, Vec8i data, void * array) \\newline\nscatter(Vec16i index, uint32\\_t limit, Vec16i data, void * array) \\newline\nscatter(Vec2q index, uint32\\_t limit, Vec2q data, void * array) \\newline\nscatter(Vec4i index, uint32\\_t limit, Vec4q data, void * array) \\newline\nscatter(Vec4q index, uint32\\_t limit, Vec4q data, void * array) \\newline\nscatter(Vec8i index, uint32\\_t limit, Vec8q data, void * array) \\newline\nscatter(Vec8q index, uint32\\_t limit, Vec8q data, void * array) \\newline\nscatter(Vec4i index, uint32\\_t limit, Vec4f data, float * array) \\newline\nscatter(Vec8i index, uint32\\_t limit, Vec8f data, float * array) \\newline\nscatter(Vec16i index, uint32\\_t limit, Vec16f data, float * array) \\newline\nscatter(Vec2q index, uint32\\_t limit, Vec2d data, double * array) \\newline\nscatter(Vec4i index, uint32\\_t limit, Vec4d data, double * array) \\newline\nscatter(Vec4q index, uint32\\_t limit, Vec4d data, double * array) \\newline\nscatter(Vec8i index, uint32\\_t limit, Vec8d data, double * array) \\newline\nscatter(Vec8q index, uint32\\_t limit, Vec8d data, double * array) \\\\ \\hline\n\\bfseries Defined for & \nVec4i, Vec8i, Vec16i, Vec2q, Vec4q, Vec8q, \\newline\nVec4f, Vec8f, Vec16f, Vec2d, Vec4d, Vec8d \\\\ \\hline\n\\bfseries Description & Store vector elements into non-contiguous positions in an array. Each vector element is stored in the array position indicated by the corresponding element of the index vector. An element is not stored if the corresponding index is negative or bigger than or equal to the limit. The limit will typically be the size of the array. \\\\ \\hline\n\\bfseries Efficiency & \nMedium for 512 bit vectors if AVX512F instruction set supported. \\newline\nMedium for 256 bit vectors if AVX512F, or better AVX512VL, supported. \\newline\nMedium for 128 bit vectors if AVX512VL supported. \\newline\nPoor otherwise. \\\\ \\hline\n\\end{tabular}\n\\vspacesmall\n\n\\begin{lstlisting}[frame=none]\n// Example:\nVec8i a(10,11,12,13,14,15,16,17);\nVec8i x(5,4,3,2,-1,99,7,0);\nint array[10] = {0};\nscatter(x, 5, a, array);\n// array = (17,0,13,12,11,0,0,0,0,0)\n\\end{lstlisting}\n\\vspacebig\n\nThe scatter functions are useful for writing sparse arrays. If you have more dense arrays, then it may be more efficient to permute the vector and then store the whole vector into the array.\n\\vspacesmall\n\nIf you want to permute a dataset that is too big for the permute and blend functions, then it is better to use lookup or gather functions than to use scatter functions.\n\\vspacesmall\n\n\\end{document}", "meta": {"hexsha": "1de87737cf113c0016b66d7f204415e83b07c0d2", "size": 20247, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "vcl_permute_functions.tex", "max_stars_repo_name": "haferburg/manual", "max_stars_repo_head_hexsha": "c7b365e7a7bbd3c155ff85edf9c6084311b0c10d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2019-08-05T13:15:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T03:17:29.000Z", "max_issues_repo_path": "vcl_permute_functions.tex", "max_issues_repo_name": "haferburg/manual", "max_issues_repo_head_hexsha": "c7b365e7a7bbd3c155ff85edf9c6084311b0c10d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-03T05:13:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-03T05:13:02.000Z", "max_forks_repo_path": "vcl_permute_functions.tex", "max_forks_repo_name": "haferburg/manual", "max_forks_repo_head_hexsha": "c7b365e7a7bbd3c155ff85edf9c6084311b0c10d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-08-08T08:28:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T08:39:06.000Z", "avg_line_length": 51.6505102041, "max_line_length": 471, "alphanum_fraction": 0.7527041043, "num_tokens": 6394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.3405219522786202}}
{"text": "\u0001h33003\n\u0001s 01019/00000/00000\n\u0001d D 1.1 10/05/12 19:24:48 starck 1 0\n\u0001c date and time created 10/05/12 19:24:48 by starck\n\u0001e\n\u0001u\n\u0001U\n\u0001f e 0\n\u0001t\n\u0001T\n\u0001I 1\n\r\n\\chapter{Sparse Blind Source Separation}\r\n\\minitoc \r\n\r\n\\label{ch_gmca}\r\n\r\n% \\minitoc \\vskip1cm\r\n     \r\n\\section{Introduction}\r\n\\index{blind source separation}\r\n\\index{independent component analysis}\r\n\\index{BSS}\r\n\\index{ICA}\r\n\r\nOver the past few years, the development of multi-channel sensors has motivated interest in methods for the coherent processing of multivariate data. Areas of application include biomedical engineering, medical imaging, speech processing, astronomical imaging, remote sensing, communication systems, seismology, geophysics, econometrics.\r\n\r\nConsider a situation where there is a collection of signals emitted by some physical objects or sources. These physical sources could be, for example, different brain areas emitting electrical signals; people speaking in the same room (the classical cocktail party problem), thus emitting speech signals; or radiation sources emitting their electromagnetic waves. Assume further that there are several sensors or receivers. These sensors are in different positions, so that each records a mixture of the original source signals with different weights. It is assumed that the mixing weights are unknown, since knowledge of that entails knowing all the properties of the physical mixing system, which is not accessible in general. Of course, the source signals are unknown as well, since the primary problem is that they cannot be recorded directly. The {\\textit{blind source separation}} (BSS) problem is to find the original signals from their observed mixtures, without prior knowledge of the mixing weights, and by knowing very little about the original sources. In the classical example of the cocktail party, the BSS problem amounts to recovering the voices of the different speakers, from the mixtures recorded at several microphones. \r\n\\index{BSS}\r\n\\index{blind source separation}\r\n\r\nThere has been much recent research activity on BSS. Some specific issues have already been addressed using a blend of heuristic ideas and rigorous derivations. This is testified to by the extensive literature on the subject. As clearly emphasized by previous work, it is fundamental that the sources to be retrieved present some quantitatively measurable diversity (e.g.\\ decorrelation, independence, morphological diversity, etc.). Recently, sparsity and morphological diversity have emerged as a novel and effective source of diversity for BSS. \r\n\r\nIn the blind source separation setting, the instantaneous linear mixture model assumes that we are given $N_c$ observations or channels \r\n$\\parenth{y_1,\\cdots, y_{N_c}}$ where each $y_i$ is a vector of length $N$ (an image or higher-dimensional data is treated by reordering its samples in a 1D vector of length $N$); each measurement is the linear mixture of $N_s$ vectors $\\parenth{s_1,\\cdots, s_{N_s}}$ called sources, each one having the same length $N$. In the noisy case, this reads\r\n\\begin{equation}\r\n\\label{eq:bss_model}\r\ny_i[l] = \\sum_{j=1}^{N_s} \\A[i,j] s_j[l] + \\veps_i[l], \\quad \\forall i\\in\\{1,\\cdots,N_c\\},\\forall l\\in\\{1,\\cdots, N\\} ~,\r\n\\end{equation}\r\nwhere $\\A$ is the $N_c \\times N_s$ mixing matrix whose columns will be denoted $a_i$, and $\\veps_i$ is the noise vector in channel $i$ supposed to be bounded. ${\\A}$ defines the contribution of each source to each measurement. As the measurements are $N_c$ different mixtures, source separation techniques aim at recovering the original sources $\\parenth{s_i}_{i=1\\cdots,N_s}$ by taking advantage of some information contained in the way the signals are mixed in the observed channels. This mixing model is conveniently rewritten in matrix form:\r\n\\begin{equation}\r\n\\label{eq:mix_model}\r\n{\\bY} = {\\bf{AS}} + {\\bf E} ~,\r\n\\end{equation}\r\nwhere ${\\bY}$ is the $N_c \\times N$ measurement matrix whose rows are $y_i^\\Tr, i=1,\\cdots,N_c$ (i.e.\\ observed data), and $\\bf S$ is the $N_s \\times N$ source matrix with rows $s_i^\\Tr, i=1,\\cdots,N_s$. The $N_c \\times N$ matrix $\\bf E$, with rows $\\veps_i^\\Tr$, is added to account for instrumental noise and/or model imperfections. In this chapter, we will discuss the overdetermined case, which corresponds to $N_c \\ge N_s$ (i.e.\\ we have more channels than sources); the converse underdetermined case ($N_c  < N_s$) is an even more difficult problem (see \\citet{JRY00} or \\citet{ica:cichocki} for further details).\r\n\r\nIn the BSS problem, both the mixing matrix $\\A$ and the sources $\\bf S$ are unknown and must be estimated jointly. In general, without further a priori knowledge, decomposing a rectangular matrix $\\bY$ into a linear combination of $N_s$ rank-one matrices is clearly ill-posed. The goal of BSS is to understand the different cases in which this or that additional prior constraint allows us to reach the land of well-posed inverse problems and to devise separation methods that can handle the resulting models. \r\n\r\n\r\n\\index{independent component analysis!JADE}\r\n\\index{independent component analysis!FastICA}\r\n\r\nSource separation is overwhelmingly a question of contrast and diversity to disentangle the sources. Depending on the way the sources are distinguished, most BSS techniques can be categorized into two main classes:\r\n\\begin{itemize}\r\n\\item{Statistical approaches -- ICA:} the well-known independent component analysis (ICA) methods assume that the sources $\\parenth{s_i}_{i=1,\\cdots,N_s}$ (modeled as random processes) are statistically independent and non-Gaussian. These methods (for example JADE, \\citet{ica:jade}; FastICA and its derivatives, \\citet{miki:Aapo}; and \\citet{koldo06}, Infomax) already provided successful results in a wide range of applications. Moreover, even if the independence assumption is strong, it is in many cases physically plausible. Theoretically, \\citet{lee98unifying} focus on the equivalence of most ICA techniques with mutual information minimization processes. Then, in practice, ICA algorithms are about devising adequate contrast functions which are related to approximations of mutual information. In terms of discernibility, statistical independence is a ``source of diversity\" between the sources.\r\n\\item{{Sparsity and morphological diversity:}}   \\citet{ica:zibu_pearl} introduced a  BSS method that focuses on sparsity to distinguish the sources.\r\n They assumed that the sources are sparse in a particular basis $\\W$ (for instance, the wavelet orthobasis). The sources $\\bf S$ and the mixing matrix $\\A$ are estimated by minimizing a maximum a posteriori criterion with a sparsity-promoting prior on the sources in $\\W$. They showed that sparsity clearly enhances the diversity between the sources. The extremal sparse case assumes that the sources have mutually disjoint supports in the original or transform domain (see \\citep{JRY00,ica:cicho06_1}). Nonetheless this simple case requires highly sparse signals. Unfortunately this is not the case for large classes of signals and especially in image processing.\r\n\\end{itemize}\r\n\r\nAnother approach based on the concept of morphological diversity developed in the previous chapter has been proposed in \\citet{starck:bobin06} which assumes that the $N_s$ sources $\\parenth{s_i}_{i=1,\\cdots,N_s}$ are sparse in different dictionaries. For instance, a piecewise smooth source $s_1$ (e.g. cartoon image) is well-sparsified in a curvelet tight frame while a warped globally oscillating source $s_2$ (oscillating texture) is better represented using the local DCT or the waveatom dictionary. This model takes advantage of the fact that the sources are morphologically distinct to differentiate between them with accuracy. The method has been extended to the more general case where each source $s_i$ is the sum of several components ($\\forall i, ~ s_i = \\sum_{k=1}^K x_{i,k}$), each of which is sparse in a given dictionary $\\W_k$ \\citep{starck:bobin07}. This in fact generalizes the MCA framework of Section~\\ref{sec:mca} to multichannel data. This sparsity and morphological diversity-based model has been shown to enjoy several advantages such as enhanced separation quality and robustness to noise.\r\n\r\nIn this chapter, we give some new and essential insights into the use of sparsity in BSS and we highlight the central role played by morphological diversity as a source of contrast between the sources. We provide fast and practical algorithms, and we describe extensions for analyzing hyperspectral data, as well as applications to denoising and inpainting.\r\n\r\n \r\n% In Section~\\ref{sec:ICA}, we give an overview of BSS methods that use statistical independence as the key assumption for separation. \r\n% Recently, sparsity has emerged as being a very effective way to distinguish the sources. These new approaches are introduced in Section~\\ref{sec:bss_sparse}.\r\n% We described how the morphological data analysis (MCA) concept (see Chapter~\\ref{ch_mca}) can be extended to multichannel\r\n% data. Then we show how the Generalized Morphological Component Analysis  method (GMCA) takes advantages of both morphological diversity and sparsity, using recent sparse overcomplete or redundant signal representations. GMCA is a  fast and efficient blind source separation method. \r\n\r\n\r\n%=============\r\n\r\n\\section{Independent Component Analysis}\r\n\\label{sec:ICA}\r\n\\index{ICA}\r\n\\index{independent component analysis}\r\n\r\n\\subsection{Independence as a Contrast Principle}\r\nThroughout this section, we consider the noiseless instantaneous linear mixture model assuming that $\\xbf{Y} = \\xbf{AS}$. This can be written equivalently in the following form:\r\n\\begin{equation}\r\n\\label{eq:bss}\r\n{\\bY} = \\sum_{i=1}^{N_s}   {\\bY}^{(i)}  = \\sum_{i=1}^{N_s}  a_i s_i^\\Tr ~ ,\r\n\\end{equation}\r\nwhere ${\\bY}^{(i)}$ is the contribution of the source $s_i$ to the data $\\bY$. Thus, BSS is equivalent to decomposing the matrix $\\bY$ of rank $N_s$ into a sum of $N_s$ rank-one matrices $\\{{\\bY}^{(i)} = a_i s_i^\\Tr\\}_{i=1,\\cdots,N_s}$. Obviously, there is no unique way to achieve such a decomposition. Further information is required to disentangle the sources.\r\n\r\nLet us assume that the sources are random vectors (of zero mean without loss of generality). These may be known a priori to be different in the sense of being simply decorrelated. A separation scheme will then look for sources $(s_i)_{i=1,\\cdots,N_s}$ such that their covariance matrix ${\\boldsymbol \\Sigma_{\\bf S}}$ is diagonal. Unfortunately, the covariance matrix ${\\boldsymbol \\Sigma_{\\bf S}}$ is invariant to orthonormal transformations such as rotations. Therefore an effective BSS method has to go beyond decorrelation (see \\citet{ica:jade} for further reflections about the need for stronger a priori constraints going beyond the decorrelation assumption).\r\n \r\nThe seminal work by \\citet{ica:comon94} paved the way for the outgrowth of \\textit{Independent Component Analysis} (ICA). \r\nIn the ICA framework, the sources are assumed to be independent random variables which is true if and only if the joint probability density function (PDF) $\\pdf_{\\bf S}$ obeys\r\n\\begin{equation}\r\n\\label{eq:bss_indep}\r\n\\pdf_{\\bf S}(s_1,\\cdots,s_{N_s}) = \\prod_{i=1}^{N_s}   \\pdf_{s_i}(s_i) ~ .\r\n\\end{equation}\r\n%Disentangling between sources requires a way to measure how separable sources are different. \r\nAs statistical independence is a property to be verified by the PDF of the sources, devising a good measure of independence is not trivial. In this setting, ICA then boils down to finding a multichannel representation/basis on which the estimated sources $\\tilde{\\xbf{S}}$ are as independent as possible. Equivalently, ICA looks for a \\textit{separating/demixing} matrix $\\xbf{B}$ such that the estimated sources $\\tilde{\\xbf{S}} = \\xbf{BAS}$ are independent. Until the end of this section devoted to ICA, we will assume that the mixing matrix $\\A$ is square and invertible.\r\n\r\nWe could ask if independence makes the sources identifiable. Under mild conditions, the Darmois theorem \\citep{darmois53} shows that statistical independence means separability \\citep{ica:comon94}. \r\nIt states that if at most one of the sources is generated from a Gaussian distribution then, if the entries of $\\tilde{\\xbf{S}} = \\xbf{BAS}$ are independent, $\\bf B$ is a separating matrix and $\\tilde{\\bf S}$ is equal to $\\bf S$ up to a scale factor (multiplication by a diagonal matrix with strictly positive diagonal entries) and permutation. As a consequence, if at most one source is Gaussian, maximizing independence between the estimated sources leads to perfect estimation of $\\bf S$ and $\\A = \\xbf{B}^{-1}$. The Darmois theorem then motivates the use of independence in BSS.\r\n \r\n\\subsection{Independence and Gaussianity}\r\nThe Kullback-Leibler (KL) divergence between two densities is defined as\r\n\\be\r\n\\mathrm{KL}\\parenth{\\pdf_{1}\\big{\\|}\\pdf_{2}} = \\int_\\xbf{u} \\pdf_{1}(\\xbf{u}) \\log \\left( \\frac{\\pdf_{1}(\\xbf{u})}{\\pdf_{2}(\\xbf{u})} \\right) d\\xbf{u}~ .\r\n\\ee\r\nThe mutual information (MI) in the form of the KL divergence between the joint density $\\pdf_{\\bf S}(s_1,\\cdots,s_{N_s})$ and the product of the marginal densities $\\pdf_{s_i}(s_i)$ is a popular measure of statistical independence:\r\n\\index{Kullback-Leibler}\r\n\\index{mutual information}\r\n\\begin{eqnarray}\r\n\\label{eq:KL_indep}\r\n\\mathrm{MI} \\left(\\xbf{S}\\right) & = \\mathrm{KL}\\parenth{\\pdf_{\\bf S}\\big{\\|}\\prod_{i=1}^{N_s}  \\pdf_{s_i}} ~,\r\n\\end{eqnarray}\r\nwhich is nonnegative and vanishes if and only if the sources $s_i$ are mutually independent. Using the Pythagorean identity of the KL divergence, the mutual information can be equivalently written \\citep{ica:geomindep,ica:comon94}:\r\n\\begin{multline}\r\n\\label{eq:KL_decomp}\r\n\\mathrm{MI} \\left( \\xbf{S} \\right)  =  \\mathrm{KL}\\parenth{\\upphi\\left(\\cdot;0,{{\\boldsymbol \\Sigma_{\\bf S}}}\\right)\\big{\\|} \\upphi\\left(\\cdot;0,\\diag\\left({{\\boldsymbol \\Sigma_{\\bf S}}}\\right)\\right)} \\\\ - \\sum_{i=1}^{N_s} \\mathrm{KL}\\parenth{\\mathrm{pdf}_{s_i}\\big{\\|} \\upphi\\left(\\cdot;0,\\sigma_{s_i}^2 \\right)} + \\mathrm{KL}\\parenth{\\mathrm{pdf}_{\\xbf{S}}\\big{\\|}\\upphi\\left(\\cdot;0,{{\\boldsymbol \\Sigma_{\\bf S}}}\\right)} ~ ,\r\n\\end{multline}\r\nwhere $\\sigma_{s_i}^2={{\\boldsymbol \\Sigma_{\\bf S}}}[i,i]$ is the variance of $s_i$, and $\\upphi\\left(.;0,\\boldsymbol{\\Sigma}\\right)$ is the multivariate Gaussian PDF with zero mean and covariance $\\boldsymbol{\\Sigma}$. The first term in \\eqref{eq:KL_decomp} vanishes when the sources are decorrelated. The second term measures the marginal non-Gaussianity of the sources. The last term measures the joint non-Gaussianity of the sources, and is invariant under affine transforms. As ICA looks for a demixing matrix $\\xbf{B}$ which minimizes $\\mathrm{MI}( \\tilde{\\bf S} = \\xbf{B Y})$, this term is a constant independent of all $\\xbf{B}$. Consequently, maximizing independence of the estimated sources $\\tilde{\\bf S}$ is equivalent to minimizing the correlation between the sources and maximizing their non-Gaussianity. Note that, with a taste of the Central Limit Theorem, intuition tells us that mixing independent signals should lead to a kind of Gaussianization. It then seems natural that demixing leads to processes that deviate from Gaussian processes.\r\n\\index{Gaussianity}\r\n\r\n\\subsection{ICA Algorithms}\r\n\\label{subsec:ICAHOS}\r\n\r\n\\index{independent component analysis!InfoMax}\r\n\\index{independent component analysis!higher order statistics}\r\n\r\n% In the ICA setting, the mixing matrix is square and invertible. Solving a BSS problem is equivalent to looking \r\n% for a demixing matrix $\\bf B$ that maximizes the independence of the estimated sources: $\\tilde{\\bf S} = \\xbf{BX}$. \r\n% As we have just seen, maximizing the independence of the estimated sources is equivalent to maximizing their non-Gaussianity. \r\nSince the seminal paper of  \\citet{ica:comon94}, a variety of ICA algorithms have been proposed. They all merely differ in the way they devise assessable measures of independence. \r\nSome popular approaches have given the following measures of independence:\r\n\\begin{itemize}\r\n\\item{{Information Maximization:}} \\citet{ica:infomax,ica:nadal} proposed the InfoMax principle implemented by maximizing with respect to $\\xbf{B}$ the differential entropy of an appropriate nonlinear function of $\\xbf{BY}$. They showed that information maximization is equivalent to minimizing a measure of independence based on the KL divergence.\r\n\\item{{Maximum Likelihood (ML):}} ML has also been proposed to solve the BSS problem \\citep{ica:cardo-ml,ica:pearlparra,ica:phamgarratjutten}. In the ICA framework, it was shown that the ML approach coincides with InfoMax provided that $\\xbf{B}$ is identified to $\\A^{-1}$ \\citep{ica:cardo-ml}.\r\n\\item{{Higher Order Statistics:}} As we pointed out above, maximizing the independence of the sources is equivalent to maximizing their non-Gaussianity under a strict decorrelation constraint. Because Gaussian random variables have vanishing higher order cumulants, devising a separation algorithm based on these higher order statistics should provide a way of accounting for the non-Gaussianity of the estimated sources. A wide range of ICA algorithms have been proposed along these lines, see \\citep{miki:Aapo,ica:sobi,ica:jade} and references therein. Historical papers \\citep{ica:comon94} proposed ICA algorithms that use approximations of the Kullback-Leibler divergence (based on truncated Edgeworth expansions). Those approximations explicitly involve higher order cumulants.\r\n\\end{itemize}\r\n\\citet{lee98unifying} showed that most ICA-based algorithms are similar in theory and in practice. \r\n\r\n\\subsection{Limits of ICA}\r\nDespite its theoretical strength and elegance, ICA suffers from several limitations:\r\n\\begin{itemize}\r\n\\item{{PDF assumption:}} While even implicit, the ICA algorithm requires information on the source distribution. \r\nAs stated in \\citet{lee98unifying}, whatever the contrast function to optimize, most ICA algorithms can be equivalently restated in a ``natural gradient'' form \\citep{Amari99I3SP,ica:cardoama}. In such a setting, the demixing matrix $\\bf B$ is estimated iteratively: ${\\bf B}^{(t+1)} = \\xbf{B}^{(t)} + \\mu \\boldsymbol{\\nabla}_\\xbf{B}(\\xbf{B}^{(t)})$. The ``natural gradient'' $\\boldsymbol{\\nabla}_\\xbf{B}$ at $\\xbf{B}$ is given by: % defined as follows:\r\n\\begin{equation}\r\n\\label{eq:ica_natgrad}\r\n\\boldsymbol{\\nabla}_\\xbf{B}(\\xbf{B}) \\propto \\parenth{\\xbf{I} - \\frac{1}{N}\\mathscr{H}(\\tilde{\\xbf{S}})\\tilde{\\xbf{S}}^\\Tr} \\xbf{B} ~,\r\n\\end{equation}\r\nwhere $\\tilde{\\xbf{S}}$ is the estimate of $\\bf S$: $ \\tilde{\\xbf{S}} = \\xbf{BY}$. The matrix $\\mathscr{H}(\\tilde{\\xbf{S}})$ in \\eqref{eq:ica_natgrad} is the so-called score function which is closely related to the PDF of the sources \\citep{miki:Amari,ica:cardoama}. Assuming that all the sources are generated from the same joint PDF $\\pdf_{\\bf S}$, the entries of $\\mathscr{H}(\\tilde{\\xbf{S}})$ are the partial derivatives of the log-likelihood function\r\n\\begin{equation}\r\n\\mathscr{H}(\\tilde{\\xbf{S}})[i,l] = - \\frac{\\partial \\log(\\pdf_{\\bf S}(\\tilde{\\xbf{S}}))}{\\partial \\tilde{\\xbf{S}}[i,l]}, \\quad \\forall (i,l) \\in \\{1,\\cdots,N_s\\} \\times \\{1,\\cdots,N\\} ~ .\r\n\\end{equation}\r\nAs expected, the way the demixing matrix (and thus the sources) is estimated closely depends on the way the sources are modeled (from a statistical point of view). For instance, separating platykurtic (distribution with negative kurtosis) or leptokurtic (distribution with positive kurtosis) sources will require completely different score functions. Even if ICA is shown in \\citet{ica:cardoama} to be quite  robust to ``mis-modeling'', the choice of the score function is crucial with respect to the convergence (and rate of convergence) of ICA algorithms. Some ICA-based techniques \\citep{koldo06} focus on adapting the popular FastICA algorithm to adjust the score function to the distribution of the sources. They particularly focus on modeling sources whose distribution belongs to specific parametric classes of distributions such as Generalized Gaussian Distribution (GGD).\r\n%$\\pdf_{\\bf S}(\\xbf{S}) \\propto \\prod_{ij} \\exp(-\\mu | \\xbf{S}[i,j] |^\\theta)$\\footnote{Note that the class of generalized Gaussian contains well-known distributions:  the Gaussian ($\\theta = 2$) and the Laplacian ($\\theta = 1$) distributions.}. \r\n\\item{{Noisy ICA:}} Only a few works have  investigated the problem of noisy ICA  \\citep{Davies04,koldo:noise}. As pointed out by  \\citet{Davies04}, noise clearly degenerates the ICA model: it is not fully identifiable. In the case of additive Gaussian noise as stated in \\eqref{eq:mix_model}, using higher order statistics yields an effective estimate of the mixing matrix $\\A = {\\bf B}^{-1}$ (higher order cumulants are indeed blind to additive Gaussian noise; this property does not hold for non-Gaussian noise). But in the noisy ICA setting, applying the demixing matrix to the data does not yield an effective estimate of the sources. Furthermore, most ICA algorithms assume the mixing matrix $\\A$ to be square. When there are more observations than sources ($N_c > N_s$), a dimension reduction step is first applied. When noise perturbs the data, this subspace projection step can dramatically deteriorate the performance of the separation stage.\r\n\\end{itemize}\r\nIn the following,  we will introduce a new way of modeling the data so as to avoid most of the aforementioned limitations of ICA.\r\n\r\n\\subsection{Towards Sparsity}\r\n\\label{subsec:towardsparsity}\r\n\\index{independent component analysis!sparsity}\r\n\r\nThe seminal paper of \\citet{ica:zibu_pearl} introduced sparsity as an alternative to standard contrast functions in ICA. \r\n%In this chapter, we estimate the mixing matrix $\\A$ and the sources $\\xbf{S}$ in a fully Bayesian framework. \r\nIn their work, each source $s_i$ was assumed to be sparsely represented in a dictionary $\\W$:\r\n\\begin{equation}\r\ns_i =  \\W \\alpha_i \\quad \\forall ~ i=1,\\cdots,N_s ~.\r\n\\end{equation}\r\nwhere the coefficients were assumed independent with a sharply-peaked (i.e. leptokurtic) and heavy-tailed PDF:\r\n\\begin{equation}\r\n\\pdf_{\\balpha}(\\alpha_1,\\ldots,\\alpha_{N_s}) \\propto \\prod_{i,l} e^{-\\lambda_i \\uppsi(\\alpha_i[l])} ~ ,\r\n\\end{equation}\r\nwhere $\\uppsi(\\alpha_i[l])$ is a sparsity-promoting penalty; e.g. the $\\ell_p$-norm corresponding to a GGD prior. \\citet{ica:zibu_pearl} used a convex smooth approximation of the $\\ell_1$ norm (Laplacian prior) and proposed to estimate $\\A$ and $\\bf S$ via a MAP estimator. The resulting optimization problem was solved with a Relative Newton Algorithm (RNA) \\citep{ica:zibu_relnewton}. This work paved the way for the use of sparsity in BSS. Note that several other works emphasized the use of sparsity in a parametric Bayesian approach (\\citet{Djafa06} and references therein). Recently, sparsity has emerged as an effective tool for solving underdetermined source separation problems; see \\citep{ica:cicho06_1,ica:cichocki,ica:zibu_bronst,LNCS46660430} and references therein.\r\n \r\n%This chapter concentrates on overdetermined Blind Source Separation ($N_c \\ge N_s$). We present a sparsity-based source separation framework providing new insights into BSS.\r\n\r\n\r\n%#################### Sparse multichannel signal representation ##################################################################################\r\n\r\n\\section{Sparsity and Multichannel Data}\r\n\\label{sec:bss_sparse}\r\nIn this section, will see how the story of monochannel sparse decomposition problem described and characterized in Section~\\ref{subsec:sparsedecomp} can be told in the language of multichannel data. This will be a consequence of a key observation dictated by \\eqref{eq:bss}.\r\n\r\n\\index{sparsity!blind source separation}\r\n\r\n% \\section{Morphological diversity in multichannel data}\r\n\\index{sparsity!multichannel data}\r\n\\index{multichannel dictionary}\r\n\r\n\\subsection{Morpho-Spectral Diversity}\r\nExtending the redundant representation framework to the multichannel case requires defining what a multichannel overcomplete representation is.\r\nLet us assume in this section that $\\A = [\\varphi_{\\nu,1}, \\cdots, \\varphi_{\\nu, N_c}] \\in \\RR^{N_c \\times N_s}$ is a \\textit{known spectral} dictionary, and $\\W = [ \\varphi_{1}, \\cdots, \\varphi_{T}] \\in \\RR^{N \\times T}$ is a \\textit{spatial} or \\textit{temporal} dictionary\\footnote{The adjectives \\textit{spectral} and \\textit{spatial} that characterize the dictionaries are not formal. Owing to the symmetry of the multichannel sparse decomposition problems, $\\A$ and $\\W$ have no formal difference. In practice and more particularly in multi/hyperspectral imaging, $\\A$ will refer to the dictionary of physical spectra and $\\W$ to the dictionary of image/signal waveforms. In the BSS problem, $\\A$ is unknown.}. We assume that each source $s_i$ can be  represented as a (sparse) linear combination of atoms in $\\W$; $s_i=\\W\\alpha_i$. Let $\\balpha$ the $N_s \\times T$ matrix whose rows are $\\alpha_i^\\Tr$.\r\n\r\nFrom \\eqref{eq:bss}, the multichannel noiseless data $\\bY$ can be written as\r\n\\be\r\n\\label{eq:tensor1}\r\n\\bY = \\A\\balpha\\W^\\Tr = \\sum_{i=1}^{N_s}\\sum_{j=1}^{T} \\parenth{\\varphi_{\\nu,i}\\varphi_{j}^\\Tr}\\alpha_i[j] ~.\r\n\\ee\r\nConsequently, each column in of $\\bY$ reads\r\n\\be\r\n\\label{eq:tensor2}\r\n\\bY[.,l] = \\parenth{\\A \\otimes \\W[l,.]} \\mathrm{vect}(\\balpha) ~, \\quad \\forall ~ l=1,\\cdots,N ~,\r\n\\ee\r\nand finally\r\n\\be\r\n\\label{eq:tensor3}\r\n\\mathrm{vect}(\\bY) = \\parenth{\\A \\otimes \\W} \\mathrm{vect}(\\balpha) ~,\r\n\\ee\r\nwhere $\\otimes$ is the tensor (Kronecker) product and the operator $\\mathrm{vect}$ stacks the columns of its argument in a long 1D vector. This latter equation brings a clear and simple insight: the sparsity of the sources in $\\W$ translates into sparsity of the multichannel data $\\bY$ in the multichannel tensor product dictionary ${\\bf \\Psi}=\\A \\otimes \\W$. This concept of multichannel dictionary has also been noted in \\citet{GN05}.\r\n\r\nThe multichannel dictionary $\\bf \\Psi$ can also be seen as concatenation of multichannel atoms ${\\bf \\Psi}^{(ij)}=\\varphi_{\\nu,i}\\varphi_{j}^\\Tr$ which are rank-one matrices obtained from each atomic spectrum $\\varphi_{\\nu,i}$ and each spatial elementary atom $\\varphi_{j}$ (see \\eqref{eq:tensor1}). \r\n\r\nIn Chapter \\ref{ch_mca}, we have seen that some of the popular sparse recovery results in the monochannel setting rely on the mutual coherence of the dictionary. In the multichannel case a similar quantity can be defined. In fact, by standard properties of the tensor product, one can easily show that the Gram matrix of a tensor product is the tensor product of the Gram matrices. Thus the mutual coherence of the multichannel dictionary $\\bf \\Psi$ is:\r\n\\index{coherence}\r\n\\begin{equation}\r\n\\label{eq:mmc}\r\n0 \\le \\mu_{\\bf \\Psi}  =  \\max\\left\\{\\mu_{\\A},\\mu_{\\W}\\right\\} < 1 ~ .\r\n\\end{equation}\r\n\r\nThis expression of mutual coherence is instructive as it tells us that multichannel atoms can be distinguished based on their spatial or spectral morphology. In other words, discriminating two multichannel atoms $\\Psi_{ij}$ and $\\Psi_{i'j'}$ may put on different faces:\r\n\\begin{itemize}\r\n\\item{Spatial or temporal (respectively spectral) diversity:} in this case $i=i'$ and $j \\neq j'$ (respectively $i \\neq i'$ and $j = j'$). These atoms have the same spectrum (respectively, spatial shape) but one can discriminate between them based on their spatial (respectively, spectral) diversity. From \\eqref{eq:mmc}, their coherence is lower than $\\mu_{{\\W}}$ (respectively $\\mu_{{\\A}}$). Disentangling these multichannel atoms can equivalently be done in the monochannel case.\r\n\r\n\\item{Both diversities:} $i \\neq i'$ and $j \\neq j'$, this seems to be a more favorable scenario to differentiate the atoms as they do not share neither the same spectrum nor the same spatial (or temporal) ``shape\". Note that from \\eqref{eq:mmc}, the coherence between these atoms in this case is lower than $\\mu_{{\\A}}\\mu_{{\\W}} \\le \\max\\left\\{\\mu_{\\A},\\mu_{\\W}\\right\\}$.\r\n\\end{itemize}\r\n\r\n\\subsection{Multichannel Sparse Decomposition}\r\n% Let's assume that the data $\\bf X$ are  sparse in $\\bf \\Psi$.  \r\n% Hence, $\\bf X$  are the linear combination of  multichannel atoms:\r\n% \\begin{equation}\r\n% \\label{eq:multi_spmodel}\r\n% {\\bf X} = \\sum_{ {\\bf \\gamma}  \\in \\Lambda} {\\psi}_{\\bf \\gamma}  \\alpha_{\\bf \\gamma}  ~ ,\r\n% \\end{equation}\r\n% where $\\Lambda$ is the set of index couples $(i,j)$.\r\n% This equation is clearly similar to the monochannel case. Owing to this key observation, we will see in the next section that most sparse decomposition results can be extended to the multichannel case.\r\n\r\nWe embark from \\eqref{eq:tensor1}, where the multichannel dictionary ${\\bf \\Psi}$ is supposed to be overcomplete, i.e. $NN_c < TN_s$. The goal is to recover the sparsest solution $\\balpha$ from $\\bY$ which requires solving:\r\n\\begin{equation}\r\n\\label{eq:multi_l0}\r\n\\min_{\\balpha \\in \\RR^{N_s \\times T}} \\sum_{i=1}^{N_s}\\norm{\\alpha_i}_{0} \\st \\bY  = \\A \\balpha \\W^\\Tr.\r\n\\end{equation}\r\nAs justified in Chapter~\\ref{ch_mca}, this combinatorial problem can be replaced by its convex relaxation substituting the $\\ell_1$ norm for the $\\ell_0$ pseudo-norm, hence giving:\r\n\\begin{equation}\r\n\\label{eq:multi_l1}\r\n\\min_{\\balpha \\in \\RR^{N_s \\times T}} \\sum_{i=1}^{N_s}\\norm{\\alpha_i}_{1} \\st \\bY  = \\A \\balpha \\W^\\Tr.\r\n\\end{equation}\r\n\r\nAs \\eqref{eq:tensor3} is a vectorized monochannel form of \\eqref{eq:tensor1}, what we are trying so do is actually to find the sparsest solution of a monochannel underdetermined system of linear equations where the solution is sparse in an overcomplete tensor product dictionary. Recovery properties of monochannel sparse decomposition by $\\ell_1$ minimization were overviewed in Section~\\ref{subsec:sparsedecomp}. Therefore, if one is able to translate those identifiability criteria in the language of tensor product dictionaries, then we are done.\r\n\r\nIn particular, the coherence-based sparse recovery criterion \\eqref{eq:mono_unique} is trivial to adapt owing to \\eqref{eq:mmc}. Indeed, if $\\bY$ is $k$-sparse in the multichannel dictionary ${\\bf \\Psi}$ with $k < C(\\mu_{{\\bf \\Psi}}^{-1}+1)$ for some $C > 0$ (typically $C=1/2$), and the dictionary is sufficiently incoherent (both spectrally and spatially), then the solution of \\eqref{eq:multi_l1} is unique, is a point of equivalence of \\eqref{eq:multi_l0} and \\eqref{eq:multi_l1}, and the recovery is stable to bounded noise on $\\bY$. \r\n\r\nAbove, we addressed the multichannel sparse decomposition problem without assuming any constraint on the sparsity pattern of the different channels. It is worth however pointing out that sparse recovery conditions from multichannel measurements can be refined if some structured sparsity is hypothesized. For instance, for structured multichannel representation (e.g. sources with disjoint supports) \\citet{GN05} provided coherence-based sufficient recovery conditions by solving \\eqref{eq:multi_l1}. One should note that despite apparent similarities, the multichannel sparse decomposition problem discussed here is conceptually different from the one targeting \\textit{simultaneous} sparse recovery of multiple measurements vectors (MMV) considered by several authors, see e.g.\\ \\citet{CREK05,MalioutovMMV05,TroppMMV06,ChenHuo06,ArgyriouMMVLearning08,BachMMVLearning08,GribonvalMMV08,EldarMMV08,LouniciMMVLearning09,WainwrightMMV09}. The latter are not aware of any mixing process via $\\A$, and their goal is to recover $\\balpha$ from MMV $\\bY=\\balpha\\W^\\Tr$ in which the vectors $\\alpha_i$, i.e. rows of $\\balpha$, have a common sparsity pattern. However the MMV model can also be written $\\mathrm{vect}(\\bY^\\Tr) = \\parenth{\\W \\otimes \\I} \\mathrm{vect}(\\balpha^\\Tr)$ as in \\eqref{eq:tensor3}. The most widely used approach to solve the simultaneous sparse recovery problem with joint sparsity is to minimize a mixed $\\ell_p-\\ell_q$ norm of the form $\\sum_{j=1}^T\\parenth{\\norm{\\balpha[.,j]}_p^q}^{1/q}$ for $p \\geq 1, 0 \\leq q \\leq +\\infty$.\r\n\r\n\r\n\\section{Morphological Diversity and Blind Source Separation}\r\n\\subsection{Generalized Morphological Component Analysis}\r\n\\label{subsec:gmca}\r\nWe now turn to the BSS problem and we highlight the role of sparsity and morphological diversity as a source of contrast to solve it. Towards this goal, we assume that the sources are sparse in the spatial dictionary $\\W$ that is the concatenation of $K$ orthonormal bases $\\parenth{{\\W}_{k}}_{k=1,\\cdots,K}$: $\\W = \\left[{\\W}_{1},\\cdots,{\\W}_{K} \\right]$. The restriction to orthonormal bases is only formal and the algorithms to be presented later still work in practice even with redundant sub-dictionaries $\\W_k$. \r\n\r\nThe Generalized Morphological Component Analysis framework assumes a priori that each source is modeled as the linear combination of $K$ morphological components where each component is sparse in a specific basis:\r\n\\begin{eqnarray}\r\n\\label{eq:sourcecomponents}\r\n\\forall i \\in \\{1,\\cdots,N_s\\}; \\qquad s_i & = & \\sum_{k=1}^K x_{i,k} = \\sum_{k=1}^K \\W_k\\alpha_{i,k} \\\\\r\n& = & \\W \\alpha_i \\qquad \\mbox{ where } \\alpha_i =  \\left[\\alpha_{i,1}^\\Tr,\\cdots,\\alpha_{i,K}^\\Tr \\right]^\\Tr ~. \\nonumber\r\n\\end{eqnarray}\r\nGMCA seeks an unmixing scheme, through the estimation of $\\A$, which leads to the sparsest sources $\\bf S$ in the dictionary $\\W$. This is expressed by the following optimization problem written in the augmented Lagrangian form\r\n\\begin{multline}\r\n\\label{eq:optimgmca}\r\n\\min_{{\\A},\\alpha_{1,1},\\cdots,\\alpha_{N_s,K}} \\frac{1}{2}\\norm{\\bY - {\\A}\\balpha\\W^\\Tr}^2_{\\mathrm{F}} + \\lambda \\sum_{i=1}^{N_s} \\sum_{k=1}^K \\norm{\\alpha_{i,k}}_p^p \\\\ \\st \\norm{a_i}_2 = 1 ~ \\forall i \\in \\{1,\\cdots,N_s\\} ~,\r\n\\end{multline} \r\nwhere typically $p=0$ or its relaxed convex version with $p=1$, and $\\norm{{\\bf X}}_{\\mathrm{F}}=\\parenth{\\trace({\\bf X}^\\Tr{\\bf X})}^{1/2}$ is the Frobenius norm. The unit $\\ell_2$-norm constraint on the columns of $\\A$ avoids the classical scale indeterminacy of the product $\\bf AS$ in \\eqref{eq:mix_model}. The reader may have noticed that the MCA problem \\eqref{eq:mcaoptim} in Chapter~\\ref{ch_mca} is a special case of the GMCA problem \\eqref{eq:optimgmca} when there is only one source $N_s=1$ and one channel $N_c=1$ (no mixing). Thus GMCA is indeed a multichannel generalization of MCA. \r\n\r\nThe program \\eqref{eq:optimgmca} is a notoriously difficult non-convex optimization problem even for convex penalties when $p \\geq 1$. More conveniently, following \\eqref{eq:bss}, the product $\\bf AS$ can be split into $N_s \\cdot K$ multichannel morphological components: ${\\bf AS} = \\sum_{i,k} a_i x_{i,k}^\\Tr = \\sum_{i,k} (a_i \\alpha_{i,k}^\\Tr) \\W_k^\\Tr$. Based on this decomposition, and inspired by the block-coordinate relaxation as for MCA, GMCA yields an alternating minimization algorithm to estimate iteratively one term at a time \\citep{starck:bobin07}. We will show shortly that the estimation of each morphological component $x_{i,k} = \\W_k\\alpha_{i,k}$ assuming $\\A$ and $x_{\\{i',k'\\} \\neq \\{i,k\\} }$ are fixed is obtained by simple hard or soft thresholding for $p=0$ and $p=1$.\r\n\r\nDefine the $(i,k)$th multichannel marginal residual by \r\n\\begin{equation}\r\n\\label{eq:gmca_resi}\r\n{\\bf R}_{i,k} = {\\bY} - \\sum_{i' \\neq i}   \\sum_{k'\\neq k}    a_{i'} x_{i',k'}^\\Tr ~.\r\n\\end{equation} \r\nas the part of the data $\\bY$ unexplained by the multichannel morphological component $a_i x_{i,k}^\\Tr$. Estimating $x_{i,k} =  \\W_{k}  \\alpha_{i,k}$, assuming $\\A$ and the other components $x_{(i',k') \\neq (i,k)}$ are fixed, leads to the component-wise optimization problem:\r\n\\begin{equation}\r\n\\label{eq:componentwisephi}\r\n\\min_{x_{i,k} \\in \\RR^{N}} \\frac{1}{2}\\norm{{\\bf R}_{i,k} - (a_i \\alpha_{i,k}^\\Tr)\\W^\\Tr}_{\\mathrm{F}}^2 +  \\lambda \\norm{\\alpha_{i,k}}_p^p ~ ,\r\n\\end{equation}\r\n\r\nSince here ${\\W}_k$ is an orthogonal matrix, with calculations similar to those of Sections~\\ref{subsubsec:proxpsi} and \\ref{sect_iht}\\footnote{The reasoning holds for $0 \\leq p \\leq 1$ from Section~\\ref{sect_iht}.}, it can be shown that the unique solution of \\eqref{eq:componentwisephi} is obtained by a hard ($p=0$) or soft ($p=1$) thresholding. Hence, the closed-form estimate of the morphological component $x_{i,k}$ is: \r\n\\begin{equation}\r\n\\label{eq:st_update}\r\n\\tilde{x}_{i,k} = \\Delta_{\\W_k,\\lambda^\\prime} \\parenth{\\frac{1}{\\norm{a_i}_2^2} {\\bf R}_{i,k}^\\Tr a_i} ~,\r\n\\end{equation}\r\nwhere $\\lambda^\\prime=\\lambda/\\norm{a_i}_2^2$ for soft thresholding and $\\lambda^\\prime=\\sqrt{2\\lambda}/{\\norm{a_i}_2}$ for hard thresholding. As described in Chapter~\\ref{ch_mca}, the operator $\\Delta_{{\\bf D}, \\lambda}(x)$ consists of (i) computing the coefficients of $x$ in the dictionary ${\\bf D}$, (ii)\r\nthresholding (soft or hard) the obtained coefficients with the threshold $\\lambda$, and (iii) reconstructing from thresholded coefficients: \r\n\\begin{equation}\r\n\\Delta_{{\\bf D},\\lambda}(x) = {\\bf D} \\Thres_{\\lambda} \\left( {\\bf D}^\\Tr x \\right).\r\n\\end{equation}\r\n$\\Thres_{\\lambda}$ is either a hard or a soft thresholding. When $\\W_k$ is redundant, \\eqref{eq:st_update} is only the first iteration of the forward-backward splitting recursion described in Chapter~\\ref{ch_inverse} (see \\eqref{eq:IST} and \\eqref{eq_it_IHT}), and which should be used when $\\W_k$ is overcomplete.\r\nHowever in practice \\eqref{eq:st_update} can still be used to save computation time.\r\n\\index{iterative!hard thresholding}\r\n\\index{iterative!soft thresholding}\r\n\r\nNow, considering $\\{a_{i'}\\}_{i' \\neq i}$ and all morphological components as fixed, and recalling that $N_c \\geq N_s$, updating the column $a_i$ is then just a least-squares estimate\r\n\\begin{equation}\r\n\\label{eq:a_update}\r\n\\tilde{a}_i = \\frac{1}{\\norm{s_i}^2_2} \\left({\\bf Y} - \\sum_{i' \\neq i} a_{i'} s_{i'}^\\Tr\\right) s_i ~.\r\n\\end{equation}\r\nwhere $s_i = \\sum_{k=1}^K x_{i,k}$. This estimate is then projected onto the unit sphere to meet the unit $\\ell_2$-norm constraint in \\eqref{eq:optimgmca}.\r\nThe GMCA algorithm is summarized in Algorithm~\\ref{algo_gmca}.\r\n\r\n{\\linespread{1}\r\n\\begin{algorithm}[htb]\r\n\\caption{GMCA algorithm.}\r\n\\label{algo_gmca}\r\n\\noindent{\\bf Task:} Sparse Blind Source Separation.\\\\\r\n\\noindent{\\bf Parameters:} The data $\\bY$, the dictionary $\\W=[\\W_1 \\cdots \\W_K]$, number of iterations $\\niter$, number of sources $N_s$ and channels $N_c$, stopping threshold $\\lambda_{\\min}$, threshold update schedule.\\\\\r\n\\noindent{\\bf Initialization:} $x_{i,k}^{(0)} = 0$ for all $(i,k)$, $\\A^{(0)}$ random and threshold $\\lambda_0$.\\\\\r\n\\noindent{\\bf Main iteration:} \\\\\r\n\\For{$t=1$ {\\bf to} $\\niter$}{\r\n    \\For{$i=1,\\cdots,N_s$ }{\r\n    \\For{$k=1,\\cdots,K$ }{\r\n       Compute the marginal residuals: $${\\bf R}_{i,k}^{(t)} = {\\bY}- \\sum_{(i',k') \\neq (i,k)} {a}_{i'}^{{(t-1)}}{x}_{i',k'}^{{(t-1)}^\\Tr}.$$\r\n       Estimate the current component ${x}_{i,k}^{(t)}$ via thresholding with threshold $\\lambda_t$:\r\n        \\qquad ${x}_{i,k}^{(t)} = \\Delta_{\\W_k, \\lambda_t}\\left({\\bf R}_{i,k}^{{(t)}^\\Tr}{a}_i^{{{(t-1)}}}\\right)$.\r\n    }\r\nUpdate $i$th source $s_i^{(t)}  =  \\sum_{k=1}^K x_{ik}^{(t)}$. \\\\\r\nUpdate $a_i$ assuming $a_{i' \\neq i}^{(t)}$ and the morphological components $ {x}_{i,k}^{(t)} $ are fixed~:\r\n $ {a}_i^{{(t)}} = \\frac{1}{\\|{s}_i^{(t)}\\|_2^2} \\left({\\bY} - \\sum_{i' \\neq i}^{N_s} {a}_{i'}^{(t-1)} {s}_{i'}^{{(t)}^\\Tr} \\right){s}_i^{{(t)}}$ and normalize to a unit $\\ell_2$ norm.\r\n}\r\nUpdate the threshold $\\lambda_t$ according to the given schedule.\\\\\r\n\\lIf{$\\lambda_t \\leq \\lambda_{\\min}$} stop.\r\n}\r\n\\noindent{\\bf Output:} Estimated sources $\\big(s^{(\\niter)}_i\\big)_{i=1,\\cdots,N_s}$ and mixing matrix ${\\A}^{(\\niter)}$.\r\n\\end{algorithm}}\r\n\r\nFor $p=1$ and fixed threshold $\\lambda$, Algorithm~\\ref{algo_gmca} can be shown to converge to a stationary point, see \\citet{Tseng01,bobin-gmca-cmb}. This point is not guaranteed to be even a local minimum of the energy, and this is even less clear for $p=0$. Thus, in the same vein as MCA, GMCA relies on a salient-to-fine strategy using a varying threshold to mitigate the problem of sensitivity to initialization. More precisely, GMCA first computes coarse versions of the morphological components for any fixed source $s_i$. These raw sources are estimated from their most significant coefficients in $\\W$. Then, the corresponding column $a_i$ is estimated from the most significant features of $s_i$. Each source and its corresponding column of $\\A$ are then alternately and progressively refined as the threshold decreases towards $\\lambda_{\\min}$. This particular iterative thresholding scheme provides robustness to noise and initialization by working first on the most significant features in the data and then progressively incorporating smaller details to finely tune the model parameters. GMCA can be used with either linear or exponential decrease of the threshold as for MCA in Chapter~\\ref{ch_mca}.\r\n\r\nIf $\\A$ were known and fixed, the GMCA would be equivalent to performing an MCA sparse decomposition of $\\bY$ in the tensor product multichannel dictionary ${\\A} \\otimes \\W$. But as GMCA also updates the mixing matrix at each iteration, it is able to learn the spectral part of the multichannel dictionary directly from the data.\r\n\r\n\\index{dictionary!learning}\r\n\r\n%\\subsubsection{The Dictionary ${\\W}$}\r\n% As an MCA-like algorithm (see previous chapter), the GMCA algorithm involves multiplications by matrices ${\\W}_k^\\Tr$ and ${\\W}_k$. Thus GMCA is attractive in large-scale problems as long as the redundant dictionary ${\\W}$ is a union of bases or tight frames. For such dictionaries, matrices ${\\W}_k^\\Tr$ and ${\\W}_k$ are never explicitly constructed, and fast implicit analysis and reconstruction operators are used instead (for instance, wavelet transforms, global or local discrete cosine transform, etc.\r\n\r\n%Recent advances in harmonic analysis have given rise to new effective sparse representations namely ridgelets \\citep{cur:candes99_1}, curvelets \\citep{cur:candes99_3,Demanet06,starck:sta01_3}, bandlets \\citep{PennecM05}, contourlets \\citep{cur:do05}, wave atoms \\citep{ld:wa}. Nevertheless, most of the aforementioned transforms {correspond to redundant tight frames}. At first sight, their use in GMCA is problematic as (\\eqref{eq:st_update}) is \\xx{no longer true} in that case. Fortunately, in \\citep{Elad:shrink}, {(\\eqref{eq:st_update1}) is shown to nearly solve (\\eqref{eq:componentwisealpha}) when $\\W_k$ is a tight frame}. In practice (see Section~\\ref{sec:results}) \\xx{building} a redundant dictionary ${\\bf {\\W} }$ by combining the \\xx{ discrete cosine and curvelet transforms } gives rather good results \\xx{for} large sets of natural images (see \\citep{starck:sta04} and \\citpe{starck:bobin06}). Note {also that} the choice of ${\\W} $ could be critical for specific applications.\r\n\r\n\\subsubsection{Complexity Analysis}\r\n\\label{sec:gmca_cc}\r\nWe begin by noting that the bulk of the computation is invested in the application of ${\\W}_k^\\Tr$ and ${\\W}_k$ at each iteration and for each of the $N_sK$ morphological components $x_{i,k}$. Hence, fast implicit operators associated with ${\\W}_k$ or its adjoint are of key importance in large-scale applications. Let $V_k$ denote the cost of one application of the analysis and synthesis operators ${\\W}_k^\\Tr$ and ${\\W}_k$. The computation of the multichannel residuals for all $(i,k)$ costs $O(N_s K N_c N)$ operations. Each step of the double ``For'' loop computes the correlation of this residual with $a_i$ costing $O(N_c N)$ operations. Next, it computes the residual correlations (application of ${\\W}_k^\\Tr$), thresholds them, and then reconstructs the morphological component $x_{i,k}$. This costs $O(2V_k + T)$ operations. The sources are then reconstructed with $O(N_s K N)$, and the update of each mixing matrix column involves $O(N_c N)$ operations. Noting that in our setting, $N_s \\approx N_c \\ll N$, and $V_k = O(N)$ or $O( N \\log N)$ for most popular transforms (see previous chapters for details), the whole GMCA algorithm then costs $O( \\niter N_s^2K  N)+O(2\\niter N_s \\sum_{k=1}^K  V_k + N_s K  T)$. Thus in practice GMCA could be computationally demanding for large-scale high dimensional problems. In Section~\\ref{fast_gmca}, we will see that under appropriate assumptions, GMCA can be accelerated yielding a simple and much faster algorithm that enables handling of very large-scale problems.\r\n\r\n\\subsubsection{The Thresholding Strategy}\r\n\r\n\\index{iterative!hard thresholding}\r\n\\index{iterative!soft thresholding}\r\n\r\n\\paragraph*{Hard or soft thresholding?} In practice, it was observed that hard thresholding leads to better results \\citep{starck:bobin06,starck:bobin07}. Furthermore, if $\\A$ is known and no noise contaminates the data, GMCA with hard thresholding will enjoy the sparse recovery guarantees given in Section~\\ref{subsec:mcaguarantees}, with the proviso that the morphological components are contrasted and sparse in a sufficiently incoherent multichannel dictionary ${\\A} \\otimes \\W$. \r\n%Furthermore in \\citet{starck:bobin_2}, it was shown empirically that the use of hard-thresholding is likely to provide the $\\ell_0$ sparse solution for the single channel sparse decomposition problem. By analogy, the use of a hard-thresholding operator is assumed to solve the multichannel $\\ell_0$ quasi-norm problem instead of \\eqref{eq:optim_l1}. Recent results give also theoretical support to iterative hard thresholding methods  \\citep{blumensath08,blumensath09,maleki09,donoho09}.\r\n\r\n\\paragraph*{Handling additive Gaussian noise.}\r\nThe GMCA algorithm is well suited to deal with data contaminated with additive Gaussian noise (see the next section for a Bayesian interpretation). For instance, assume that the noise $\\bf E$ in \\eqref{eq:mix_model} is additive white Gaussian in each channel, i.e. its covariance matrix ${\\boldsymbol \\Sigma}_{\\bf E}$ is diagonal, and let $\\sigma_{\\bf E}$ be its standard deviation supposed equal for all channels for simplicity. Then, Algorithm~\\ref{algo_gmca} can be applied as described above with $\\lambda_{\\min}=\\tau\\sigma_{\\bf E}$, where $\\tau$ is chosen as in denoising methods, typically taking its value in the range $[3,4]$. This attribute of GMCA makes it a suitable choice for use in noisy BSS. GMCA not only manages to separate the sources, but also succeeds in removing additive noise as a by-product.\r\n\r\n\\subsection{The Bayesian Perspective}\r\nGMCA can be interpreted from a Bayesian standpoint. For instance, let us assume that the entries of the mixtures $\\parenth{y_i}_{i=1,\\cdots,N_c}$, the mixing matrix $\\A$, the sources $\\parenth{s_i}_{i=1,\\cdots,N_s}$ and the noise matrix $\\bf E$ are random processes. We assume that the noise $\\bf E$ is zero-mean Gaussian where the noise vector $\\veps_i$ in each channel is white, but the noise between channels is possibly correlated with known covariance matrix ${\\boldsymbol \\Sigma}_{\\bf E}$. This means that the log-likelihood function takes the form:\r\n\\[\r\nLL(\\bY\\big|{\\bf S},{\\A},{\\boldsymbol \\Sigma}_{\\bf E}) = \\frac{1}{2} \\norm{{\\bY} - {\\bf{AS}}}_{{\\boldsymbol \\Sigma}_{\\bf E}}^2 ~, \\text{ where } \\norm{\\bf X}_{{\\boldsymbol \\Sigma}_{\\bf E}}^2 = \\trace\\big({\\bf X}^\\Tr{\\boldsymbol \\Sigma}_{\\bf E}^{-1}{\\bf X}\\big).\r\n\\]\r\n\r\nWe further assume that the uniform prior is imposed on entries of $\\A$. Other priors on $\\A$ could be imposed; e.g.\\ known fixed column for example. \r\nAs far as the sources are concerned, they are known from \\eqref{eq:sourcecomponents} to be sparse in the dictionary $\\W$. Thus their coefficients $\\balpha=[\\alpha_1,\\cdots,\\alpha_{N_s}]^\\Tr$ will be assumed as drawn independently from a leptokurtic PDF with heavy tails such as the generalized Gaussian distribution form:\r\n\\begin{multline}\r\n\\label{eq:indepas}\r\n\\qquad \\pdf_{\\balpha}(\\alpha_{1,1},\\ldots,\\alpha_{N_s,K}) \\propto \\prod_{i=1}^{N_s}\\prod_{k=1}^{K}\\exp\\parenth{-\\lambda_{i,k}\\norm{\\alpha_{i}}_{p_{i,k}}^{p_{i,k}}} ~, \\\\\r\n0 \\leq p_{i,k} < 2 ~ \\forall (i,k) \\in \\{1,\\cdots,N_s\\}\\times\\{1,\\cdots,K\\} ~.\r\n\\end{multline}\r\nPutting together the log-likelihood function and the priors on $\\A$ and $\\balpha$, the MAP estimator leads to the following optimization problem:\r\n\\begin{equation}\r\n\\label{eq:optim_bayes}\r\n\\min_{{\\A},\\alpha_{1,1},\\cdots,\\alpha_{N_s,K}} \\frac{1}{2}\\norm{\\bY - {\\A}\\balpha\\W^\\Tr}^2_{{\\boldsymbol \\Sigma}_{\\bf E}} + \\sum_{i=1}^{N_s} \\sum_{k=1}^K \\lambda_{i,k}\\norm{\\alpha_{i,k}}_{p_{i,k}}^{p_{i,k}} ~,\r\n\\end{equation}\r\nThis problem has strong similarity with that of \\eqref{eq:optimgmca}. More precisely, if the noise is homoscedastic and decorrelated between channels (i.e.\\ ${\\boldsymbol \\Sigma}_{\\bf E} = \\sigma_{\\bf E}^2 {{\\bf I}}$), if the shape parameters $p_{i,k}$ of the generalized Gaussian distribution prior are all equal to $p$ and the scale parameters are all taken as $\\lambda_{i,k}=\\lambda/\\sigma_{\\bf E}^2$, and if the columns of $\\A$ are assumed uniform on the unit sphere, then \\eqref{eq:optim_bayes} is exactly \\eqref{eq:optimgmca}. Note that in the development above, the independence assumption in \\eqref{eq:indepas} does not necessarily entail independence of the sources. Rather it means that there are no a priori assumptions that indicate any dependency between the sources. \r\n\r\n\r\n\\subsection{The Fast GMCA Algorithm}\r\n\\label{gmca_algo}\r\n\\label{fast_gmca}\r\nThe goal here is to speed up the GMCA algorithm. As a warm-up, assume that the dictionary ${\\W}$ is no longer redundant and reduces to a single orthobasis (i.e. $K=1$). \r\nLet us denote $\\Ya=\\bY\\W$ the matrix where each of its rows stores the coefficients of each channel $y_i$. The optimization problem \\eqref{eq:optimgmca} then becomes (we omit the $\\ell_2$ constraint on $\\A$ to lighten the notation):\r\n\\begin{equation}\r\n\\label{eq:optim2}\r\n\\min_{{\\A},{\\bf \\balpha}} \\frac{1}{2}\\norm{\\Ya - {\\A} \\balpha}_\\mathrm{F}^2 + \\lambda \\sum_{i=1}^{N_s} \\norm{\\alpha_{i}}_p^p ~.\r\n\\end{equation}\r\nwhere $p=0$ or $p=1$. The GMCA algorithm no longer needs to apply the analysis and synthesis operators at each iteration as only the channels $\\bY$ have to be transformed once in $\\W$. Clearly, this case is computationally much cheaper. \r\n\r\nHowever, this is rigorously valid only for an orthobasis dictionary, and no orthonormal basis is able to sparsely represent large variety of signals and yet we would like to use very sparse signal representations which motivated the use of redundancy in the first place. Arguments supporting the substitution of \\eqref{eq:optim2} for \\eqref{eq:optimgmca} for a redundant dictionary ${\\W}$ were given in \\citet{starck:bobin07,bobin08_aiep}. The idea is to first compute the sparsest representation of each channel $y_i$ in the redundant dictionary $\\W$ using an appropriate (non-linear) decomposition algorithm (e.g. BP, MCA). Now, $\\Ya$ denotes the matrix where each row contains the sparse decomposition of the corresponding channel. Because the channels are linear mixtures of the sources via the mixing matrix $\\A$, the key argument developed by \\citet{starck:bobin07} is that the sparse decomposition algorithm must preserve linear mixtures. Descriptively, the sparsest decomposition provided by the algorithm when applied to each channel must be equal to the linear combination of the sparsest decompositions of the sources. This statement is valid if the sources and the channels are identifiable, meaning that they verify sufficient conditions so that their unique sparsest representation can be recovered by the decomposition algorithm. For instance, if MCA is used, then following Section~\\ref{subsec:mcaguarantees}, it is sufficient that the channels and the sources be sparse enough in an incoherent dictionary $\\W$, and their morphological components be sufficiently contrasted. See \\citet{starck:bobin07,bobin08_aiep} for details.\r\n\r\nHence, under these circumstances, a fast GMCA algorithm can be designed to solve \\eqref{eq:optim2} by working in the transform domain after decomposing each observed channel $y_i$ in ${\\W}$ using a sparse decomposition algorithm such as MCA. There is an additional important simplification when substituting problem \\eqref{eq:optim2} for \\eqref{eq:optimgmca}. Indeed, since $N_c \\geq N_s$ (i.e. overdetermined BSS), it turns out that \\eqref{eq:optim2} is a multichannel overdetermined least-squares fit with $\\ell_0/\\ell_1$-sparsity penalization. We again use an alternating minimization scheme to solve for $\\A$ and $\\balpha$:\r\n\\index{iterative!hard thresholding}\r\n\\index{iterative!soft thresholding}\r\n\\begin{itemize}\r\n\\item Update the coefficients: when $\\A$ is fixed, since the quadratic term is strictly convex ($\\A$ has full column-rank), the marginal optimization problem can be solved by a general form of the forward-backward splitting iteration \\citep{ChenRockafellar97}:\r\n\\begin{equation}\r\n\\balpha^{(t+1)} = \\Thres_{\\mu\\lambda} \\parenth{\\balpha^{(t)} + \\mu{\\boldsymbol \\Xi} \\A^\\Tr(\\Ya - {\\A}\\balpha^{(t)})} ~,\r\n\\end{equation}\r\nwhere ${\\boldsymbol \\Xi}$ is a relaxation matrix such that the spectral radius of $({\\bf I} - \\mu{\\boldsymbol \\Xi}\\A^\\Tr\\A)$ is bounded above by 1, and the step-size $0 < \\mu \\leq 1/\\opnorm{{\\boldsymbol \\Xi}\\A\\A^\\Tr}$. Taking ${\\boldsymbol \\Xi} = (\\A^\\Tr\\A)^{-1}$ ($\\A^\\Tr\\A$ is non-singular and a kind of Newton's method ensues) yields the closed-form\r\n\\begin{equation}\r\n\\tilde{\\balpha}  =  \\Thres_{\\lambda}\\parenth{\\A^{+}\\Ya}, \r\n\\end{equation}\r\nwhere $\\Thres_{\\lambda}$ is a thresholding operator (hard for $p=0$ and soft for $p=1$).\r\n\\item If $\\balpha$ is fixed, and since $\\balpha$ is full row-rank, the mixing matrix $\\A$ is given by the least-squares estimate: \r\n\\begin{equation}\r\n{\\bf \\tilde{A}} = \\Ya\\balpha^\\Tr\\parenth{\\balpha\\balpha^\\Tr}^{-1} = \\Ya\\balpha^+ ~,\r\n\\end{equation}\r\nand the columns of ${\\bf \\tilde{A}}$ are then normalized.\r\n\\end{itemize}\r\nNote that the latter two-step estimation scheme has a flavor of the alternating sparse coding/dictionary learning algorithm presented by \\citet{ksvd:elad,fadili:peyrespie07} in a different framework.\r\n\r\nThis two-stage iterative process leads to the accelerated version of GMCA summarized in Algorithm \\ref{algo_fast_gmca}.\r\n{\\linespread{1}\r\n\\begin{algorithm}[htb]\r\n\\caption{Fast GMCA algorithm.}\r\n\\label{algo_fast_gmca}\r\n\\noindent{\\bf Task:} Sparse Blind Source Separation.\\\\\r\n\\noindent{\\bf Parameters:} The data $\\bY$, the dictionary $\\W=[\\W_1 \\cdots \\W_K]$, number of iterations $\\niter$, number of sources $N_s$ and channels $N_c$, stopping threshold $\\lambda_{\\min}$, threshold update schedule.\\\\\r\n\\noindent{\\bf Initialization:} \r\n\\begin{itemize}\r\n\\item $\\balpha^{(0)} = 0$,  $\\A^{(0)}$ a random matrix.\r\n\\item Apply the MCA Algorithm~\\ref{algo:mca} with $\\W$ to each data channel $y_i$ to get $\\Ya$.\r\n\\item Set threshold $\\lambda_0 = \\max_{i,l}\\abs{\\Ya[i,l]}$.\r\n\\end{itemize}\r\n\\noindent{\\bf Main iteration:} \\\\\r\n\\For{$t=1$ {\\bf to} $\\niter$}{\r\n\\begin{itemize}\r\n\\item  Update the coefficients $\\balpha$:\r\n      ${\\balpha}^{(t+1)} =  \\Thres_{\\lambda_t}\\big({\\A}^{(t)^+} \\Ya\\big)$.\r\n\\item  Update the mixing matrix $\\A$:\r\n      ${\\A}^{(t+1)} =   \\Ya\\balpha^{(t+1)^+}$, normalize columns to a unit $\\ell_2$ norm.\r\n\\item Update  the threshold $ \\lambda_t$ according to the given schedule.\r\n\\end{itemize}\r\n\\lIf{$\\lambda_t \\leq \\lambda_{\\min}$} stop.\r\n}\r\nReconstruct the sources: $\\tilde{s}_i   =    \\sum_{k=1}^K {\\W}_{k}  \\alpha^{(\\niter)}_{i,k}, i=1,\\cdots,N_s$.\\\\\r\n\\noindent{\\bf Output:} Estimated sources $\\big(\\tilde{s}_i\\big)_{i=1,\\cdots,N_s}$ and mixing matrix ${\\A}^{(\\niter)}$.\r\n\\end{algorithm}}\r\n\r\nIn the same vein as in Section \\ref{subsec:gmca}, the coarse-to-fine process is also at the heart of this fast version of GMCA with the threshold that decreases with increasing iteration count. This again brings robustness to noise and initialization.\r\n\r\n\\paragraph*{Complexity analysis.} \r\nWhen the assumptions discussed above for the redundant dictionary case are valid, the fast GMCA version requires only one application of MCA on each channel, which is faster than the first version of GMCA (see Section~\\ref{sec:gmca_cc}). Once MCA is applied to each channel, and assuming as before that $N_s \\approx N_c \\ll N \\leq T$, it can be easily shown that the rest of the algorithm requires $O(\\niter N_s^2T)$ operations. In the case where only one orthogonal dictionary is used (e.g.\\ Fourier orthogonal wavelet transform), the algorithm becomes even faster, since the MCA step is replaced by application of the fast analysis operator to each channel.\r\n\r\n \r\n\\subsection{Estimating the Number of Sources}\r\nIn BSS, the number of sources $N_s$ is assumed to be a fixed known parameter of the problem. In practical situations, this is rather an exception than a rule, and estimating $N_s$ from the data is a crucial and strenuous problem. \r\n\r\nAs we supposed $N_s \\leq N_c$, the number of sources is the dimension of the subspace of the whole $N_c$-dimensional space (recall that $N_c$ is the number of channels) in which the data lie. A mis-estimation of the number of sources $N_s$ may entail two difficulties:\r\n\\begin{itemize}\r\n\\item{{Under-estimation:}} in the GMCA algorithm, under-estimating the number of sources will clearly lead to poor unmixed solutions that are made of linear combinations of ``true\" sources. The solution may then be suboptimal with respect to the sparsity of the estimated sources.\r\n\\item{{Over-estimation:}} in such case, the GMCA algorithm may have to cope with a mixing matrix estimate that becomes ill-conditioned.\r\n\\end{itemize}\r\nRelatively little work has focused on the estimation of the number of sources $N_s$. One can think of using model selection criteria such as the minimum description length (MDL) devised in \\cite{LNCS46660333}. Such criteria, including AIC \\citep{akaike} and BIC \\citep{schwarz}, would provide a balance between the complexity of the model (here the number of sources) and its ability to faithfully represent the data. It would amount to adding a penalty term in \\eqref{eq:optimgmca}. This penalty term would merely prevent a high number of sources. But a sparsity-based method to estimate $N_s$ within the GMCA framework can be designed.\r\n\r\nFor a fixed number of sources $n_s < N_s$, the sparse BSS problem \\eqref{eq:optimgmca} can be written in the constrained from:\r\n\\begin{equation}\r\n\\label{eq:nbs_pb}\r\n(\\P_{n_s,\\sigma}): ~ \\min_{{\\A},\\balpha | \\rank\\parenth{\\A} = n_s} \\sum_{i=1}^{n_s}\\norm{\\alpha_i}_{p}^p \\st \\norm{{\\bY} - {\\A\\balpha\\W^\\Tr}}_\\mathrm{F} \\leq \\sigma ~ .\r\n\\end{equation}\r\nTo jointly estimate the ${\\bf S} = \\balpha \\W^\\Tr$, $\\A$ and the number of sources, the problem we would like to tackle is then:\r\n\\begin{equation*}\r\n\\label{eq:nbs_pb_all}\r\n\\min_{n_s \\in \\{1,\\cdots,N_c\\}} \\left\\{\\min_{{\\A},\\balpha | \\rank\\parenth{\\A} = n_s} \\sum_{i=1}^{n_s}\\norm{\\alpha_i}_{p}^p \\st \\norm{{\\bY} - {\\A\\balpha\\W^\\Tr}}_\\mathrm{F} \\leq \\sigma \\right\\} ~ .\r\n\\end{equation*}\r\nIf $n_s < N_s$, there exists a minimal value $\\sigma^\\star(n_s)$ such that if $\\sigma < \\sigma^\\star(n_s)$, $(\\P_{n_s,\\sigma})$ has no feasible solution in $\\A$ that satisfies the rank condition. For a fixed $n_s < N_s$, this minimal value $\\sigma^\\star(n_s)$ is the approximation error between $\\bY$ and its projection in the subspace spanned by its singular vectors corresponding to the $n_s$ largest singular values. Furthermore, in the noiseless case, for $n_s < N_s$, $\\sigma^\\star(n_s)$ is always strictly positive as the data lies in a subspace whose dimension is exactly $N_s$. When $n_s = N_s$, the problem $(\\P_{N_s,\\sigma})$ has at least one solution for $\\sigma = \\sigma^\\star(N_s) = 0$. \r\n\r\nThis discussion suggests a constructive approach to jointly estimate the number of sources $N_s$, ${\\bf S} = \\balpha \\W^\\Tr$ and $\\A$. This selection procedure uses GMCA to solve a sequence of problems $(\\P_{n_s,\\sigma(n_s)})$ for each constraint radius $\\sigma(n_s)$ with increasing $n_s$, $1 \\leq n_s \\leq N_c$. This is summarized in Algorithm~\\ref{algo_nbr_sources} \\citep{bobin08_aiep}.\r\n\r\n{\\linespread{1}\r\n\\begin{algorithm}[htb]\r\n\\caption{GMCA-based selection of the number of sources.}\r\n\\label{algo_nbr_sources}\r\n\\noindent{\\bf Task:} Jointly estimate the number of sources, source coefficients $\\balpha$ and mixing matrix $\\A$.\\\\\r\n\\noindent{\\bf Parameters:} The data $\\bY$, the dictionary $\\W=[\\W_1 \\cdots \\W_K]$, number of iterations $\\niter$, stopping threshold $\\lambda_{\\min}$, threshold update schedule.\\\\\r\n\\noindent{\\bf Main iteration:}\\\\ \r\n\\For{$n_s=1$ to $N_c$}{\r\n\\begin{enumerate}[1.]\r\n\\item Add a new column to $\\A$.\r\n\\item Solve $(\\P_{n_s,\\sigma^\\star(n_s)})$ with the GMCA algorithm using $(\\W,\\niter,n_s,N_c,\\lambda_{\\min})$ as its parameters.\r\n\\end{enumerate}\r\n\\lIf{$\\norm{{\\bY} - {\\A \\balpha\\W^\\Tr}}_\\mathrm{F} \\leq \\sigma^\\star(N_s)$} stop.\r\n}\r\n\\noindent{\\bf Output:} Estimated number of sources $n_s$.\r\n\\end{algorithm}\r\n}\r\n\r\n\\paragraph*{Choice of the new columns of $\\A$.}\r\nIn the aforementioned algorithm, Step 1 amounts to adding a column vector to the current mixing matrix $\\A$. The most simple choice would amount to choosing this vector at random. Wiser choices can also be made based on additional prior information:\r\n\\begin{itemize}\r\n\\item{\\bf Decorrelation:} if the mixing matrix is assumed to be orthogonal, the new column vector can be chosen as being orthogonal to the subspace spanned by the columns of $\\A$ with $\\rank\\parenth{\\A} = n_s-1$.\r\n\\item{\\bf Known spectra:} if a library of spectra is known a priori, the new column can be chosen amongst the set of unused ones. The new spectrum can be chosen based on its correlation with the residual. Let $\\mathcal{A}$ denote a library of spectra $\\{\\mathsf{a}_i\\}_{i = 1,\\cdots,\\mbox{Card}\\left(\\mathcal{A}\\right)}$ and let $\\mathcal{A}_{n_s}^c$ denote the set of spectra that have not been chosen yet, then the $n_s$th new column of $\\A$ is chosen such that:\r\n\\begin{equation}\r\n\\mathsf{a}_{i^\\star} = \\Argmax{\\mathsf{a}_i \\in \\mathcal{A}_{n_s}^c} \\abs{\\sum_{l=1}^{N} \\frac{1}{\\norm{\\mathsf{a}_i}_2^2}\\mathsf{a}_i^\\Tr\\parenth{{\\bY} - {\\A {\\bf S}}}[.,l]} ~ .\r\n\\end{equation}\r\n\\end{itemize}\r\nAny other prior information can be taken into account which will guide the choice of a new column vector of $\\A$.\r\n\r\n\\paragraph*{The noisy case.}\r\nIn the noiseless case, Step 2 of Algorithm~\\ref{algo_nbr_sources} amounts to running the GMCA algorithm to estimate $\\bf A$ and ${\\bf S} = \\balpha \\W^\\Tr$ for a fixed $n_s$ with a final threshold $\\lambda_{\\min} = 0$. In the noisy case, $\\sigma$ in $(\\P_{n_s,\\sigma})$ can be closely related to the noise level For instance, if the noise $\\bf E$ is additive Gaussian with ${\\boldsymbol \\Sigma}_{\\bf E}=\\sigma_{\\bf E}^2$, $\\lambda_{\\min}=\\tau\\sigma_{\\bf E}$ with $\\tau=\\text{3--4}$ as suggested throughout the chapter. If the GMCA algorithm recovers the correct sources and mixing matrix, this ensures that the residual mean-squares is bounded by $\\tau^2\\sigma_{\\bf E}^2$ with probability higher than $1 - \\exp(-\\tau^2/2)$.\r\n\r\n\\paragraph*{Illustrative example.}\r\nIn this experiment, 1D channels are generated following the instantaneous linear mixture model \\eqref{eq:mix_model} with $N_s$ sources, where $N_s$ varies from $2$ to $20$. The number of channels is $N_c= 64$, each having $N = 256$ samples. The dictionary $\\W$ is chosen as the Dirac basis, and the entries of $\\bf S$ have been independently drawn from a Laplacian PDF with unit scale parameter (i.e. $p=1$ and $\\lambda=1$ in \\eqref{eq:indepas}). The entries of the mixing matrix are independent and identically distributed $\\sim \\cN(0,1)$. The observations are not contaminated by noise.  \r\n\r\nThis experiment will focus on comparing the classical principal components analysis (PCA), the popular subspace selection method, and the GMCA algorithm assuming $N_s$ is unknown. In the absence of noise, only the $N_s$ highest eigenvalues provided by the PCA, which coincide with the Frobenius norm of the rank-one matrices $(a_i s_i^\\Tr)_{i=1\\cdots,N_s}$, are non-zero. PCA therefore provides the true number of sources. The GMCA-based selection procedure in Algorithm~\\ref{algo_nbr_sources} has been applied to the same data in order to estimate the number of sources $N_s$. Fig.\\ \\ref{fig:css_ns} depicts the mean number of sources estimated by GMCA. Each point has been averaged over $25$ random realizations of $\\bf S$ and $\\A$. The estimation variance was zero indicating that for each of the $25$ trials, GMCA provides exactly the true number of sources.\r\n\r\n\\begin{figure}[htb]\r\n\\begin{minipage}[b]{1\\linewidth}\r\n    \\centerline{\r\n    \\includegraphics[width=8cm]{CSS_EstNbSources.pdf}\r\n    }\r\n\\end{minipage}\r\n\\caption{Estimating the number of sources with GMCA. Each point is the average number of sources computed from $25$ trials. For each point, the estimation variance was zero.} \\label{fig:css_ns}\r\n\\end{figure} \r\n\r\nFig.\\ \\ref{fig:css_comp} reports the comparative performances of PCA and GMCA in recovering the true input sources. In this experiment, the number of channels is $N_c = 128$, and each channel has $N = 2048$ samples. The left panel of Fig.\\ \\ref{fig:css_comp} shows the mean (over 25 realizations) recovery SNR of the estimated sources. The SNR for both methods decreases as $N_s$ increases which is expected, but clearly the GMCA provides sources that are far closer to the true sources than PCA. We define the following $\\ell_1$-norm based error criterion between the original sources and mixing matrix and their estimates:\r\n\\begin{equation}\r\n\\label{eq:lambdal1}\r\n\\mathrm{C}_{\\ell_1} = \\frac{\\sum_{i=1}^{N_s}\\sum_{j=1}^{N_c}\\sum_{l=1}^N \\abs{(a_i s_i^\\Tr)[j,l] - (\\tilde{a}_i \\tilde{s}_i^\\Tr)[j,l]}}{\\sum_{i=1}^{N_s}\\sum_{j=1}^{N_c}\\sum_{l=1}^N \\abs{(a_i s_i^\\Tr)[j,l]}} ~ ,\r\n\\end{equation}\r\n$\\mathrm{C}_{\\ell_1}$ provides a sparsity-based criterion that quantifies the deviation between the estimated sources and the true sparsest sources. \r\nThe right panel of Fig.\\ \\ref{fig:css_comp} shows the evolution of $\\mathrm{C}_{\\ell_1}$ as $N_s$ varies. As expected, the GMCA-based algorithm also provides much sparser sources.\r\n\r\n\\begin{figure}[htb]\r\n% \\begin{minipage}[b]{1\\linewidth}\r\n \\centerline{  \r\n\\includegraphics[width=0.6\\textwidth]{CSS_L2Log.pdf}\r\n\\includegraphics[width=0.6\\textwidth]{CSS_L1Log.pdf}\r\n}\r\n% \\end{minipage}\r\n% \r\n\\caption{Comparison of GMCA (dots) to PCA (solid) in terms of source recovery. Left: recovery SNR in dB as $N_s$ increases. Right: source recovery criterion $\\mathrm{C}_{\\ell_1}$. Each point is an average over $25$ realizations.} \\label{fig:css_comp}\r\n\\end{figure} \r\n% These examples point to the fact that GMCA is able to find the true dimension \r\n% of the subspace in which the data lies (i.e.\\ the true number of sources). \r\n% Furthermore, GMCA provides far sparser solutions than PCA with much smaller recovery errors.  \r\n\r\n\r\n\\section{Illustrative Experiments}\r\n\\subsection{The Sparser, the Better}\r\n\\label{tstb}\r\nSo far in this chapter, sparsity and morphological diversity were claimed as the clue for good separation results. The role of morphological diversity is twofold:\r\n\\begin{itemize}\r\n\\item Separability:  the sparser and the more morphologically diverse the sources in the dictionary ${\\W}$, the more ``separable\" they are.  \r\n\\item Robustness to noise/model imperfections: the sparser the sources, the less dramatic the noise. This is the essence of sparsity-based denoising methods as discussed in Chapter~\\ref{chap:denoise}.\r\n%In fact, sparse sources are concentrated on very few significant coefficients in the sparse domain for which additive noise is a slight perturbation. As a sparsity-based method, GMCA should be less sensitive to noise.\r\n\\end{itemize}\r\n%Furthermore, from a signal processing point of view, dealing with highly sparse signals leads to easier and more robust models. \r\n\r\nTo illustrate these points, let us consider $N_s = 2$ 1D sources with $N = 1024$ samples. These sources are the \\texttt{Bump} and \\texttt{HeaviSine} signals available in \\citet{wave:wavelab}. The first column of Fig.\\ \\ref{fig:bgmca_tstb_signals}  shows the two synthetic sources. The sources are randomly mixed, and a white Gaussian noise with variance corresponding to SNR = $19$ dB is added so as to provide $N_c=2$ observations portrayed in the second column of Fig.\\ \\ref{fig:bgmca_tstb_signals}. To apply the fast GMCA Algorithm~\\ref{algo_fast_gmca}, MCA was assumed to preserve linearity with such sources and mixtures (see our choice of the dictionary later on). The mixing matrix is assumed to be unknown. The third and fourth columns of Fig.\\ \\ref{fig:bgmca_tstb_signals} depict the GMCA estimated sources computed with a dictionary containing respectively the OWT, and the DCT+OWT. Visually, GMCA performs quite well in both cases.\r\n\r\n\\begin{figure}[htb]\r\n\\begin{minipage}[b]{0.2\\linewidth}\r\n\\centerline{         \\includegraphics[width=3cm]{gmca_fig4a.pdf}}\r\n\\end{minipage}\r\n\\hfill\r\n\\begin{minipage}[b]{0.2\\linewidth}\r\n     \\centerline{         \\includegraphics[width=3cm]{gmca_fig4b.pdf}}\r\n\r\n\\end{minipage}\r\n\\hfill\r\n\\begin{minipage}[b]{0.2\\linewidth}\r\n      \\centerline{         \\includegraphics[width=3cm]{gmca_fig4c.pdf}}\r\n\\end{minipage}\r\n\\hfill\r\n\\begin{minipage}[b]{0.2\\linewidth}\r\n      \\centerline{         \\includegraphics[width=3cm]{gmca_fig4d.pdf}}\r\n \\end{minipage}\r\n\\vfill\r\n\\begin{minipage}[b]{0.2\\linewidth}\r\n       \\centerline{         \\includegraphics[width=3cm]{gmca_fig4e.pdf}}\r\n \\end{minipage}\r\n\\hfill\r\n\\begin{minipage}[b]{0.2\\linewidth}\r\n        \\centerline{         \\includegraphics[width=3cm]{gmca_fig4f.pdf}}\r\n \\end{minipage}\r\n\\hfill\r\n\\begin{minipage}[b]{0.2\\linewidth}\r\n        \\centerline{         \\includegraphics[width=3cm]{gmca_fig4g.pdf}}\r\n \\end{minipage}\r\n\\hfill\r\n\\begin{minipage}[b]{0.2\\linewidth}\r\n        \\centerline{         \\includegraphics[width=3cm]{gmca_fig4h.pdf}}\r\n \\end{minipage}\r\n\\caption{The sparser the better. First column: the original sources. Second column: mixtures with additive white Gaussian noise (SNR = $19$ dB). Third column: sources estimated with GMCA using only the OWT dictionary. Fourth column: Sources estimated with GMCA using a redundant dictionary made of the union of the DCT and the OWT.} \r\n\\label{fig:bgmca_tstb_signals}\r\n\\end{figure} \r\nWe define the mixing matrix criterion \r\n\\[\r\n\\mathrm{C}_{\\A} = \\sum_{i,j}|{\\bf I}[i,j] - ({\\bf P}{\\tilde{\\A}}^{+} {\\A})[i,j]|,\r\n\\] \r\nwhere $\\I$ is the identity matrix as usual, ${\\bf P}$ is a matrix that reduces the scale/permutation indeterminacy of the mixing model and ${\\tilde{\\A}}^+$ is the pseudo-inverse of the estimated mixing matrix. In the simulation experiments, the true sources and mixing matrix are obviously known and thus ${\\bf P}$ can be computed easily. The mixing matrix criterion is thus strictly positive unless the mixing matrix is perfectly estimated up to scale and permutation. This mixing matrix criterion is experimentally much more sensitive to separation errors.\r\n\r\nFig.\\ \\ref{fig:bgmca_tstb} portrays the evolution of the criterion $\\mathrm{C}_{\\A}$ as the SNR increases. The dashed line corresponds to the behavior of GMCA with the OWT dictionary, and the solid line to that when $\\W$ is the union of the DWT and the DCT. On the one hand, GMCA gives satisfactory results as $\\mathrm{C}_{\\A}$ is rather low for both experiments. On the other hand, the values of $\\mathrm{C}_{\\A}$ provided by the fast GMCA with the redundant dictionary are approximately $5$ times better than those achieved using solely the orthogonal dictionary OWT. In summary, this simple toy experiment clearly underlines the role of sparsity and overcompleteness for successful BSS.\r\n\r\n\\begin{figure}[htb]\r\n\\begin{minipage}[b]{1\\linewidth}\r\n             \\centerline{         \\includegraphics[width=8cm]{gmca_fig5.pdf}}\r\n\r\n\\end{minipage}\r\n\\caption{The sparser the better: behavior of the mixing matrix criterion $\\mathrm{C}_{\\A}$ with varying SNR. OWT--fast GMCA (dashed line) and (DCT+OWT)--fast GMCA (solid line).} \r\n\\label{fig:bgmca_tstb}\r\n\\end{figure}\r\n\r\n%This simple toy experiment clearly shows the benefits of sparsity for BSS. Furthermore it underlines the effectiveness of ``very\" sparse representations provided by nonlinear decompositions in overcomplete dictionaries. \r\n\r\n\r\n% \\subsection{GMCA is able to provide the sparsest solution}\r\n% In this paragraph, we have run a simple noiseless experiment. The data $\\bf X$ consists of $4$ mixtures (Figure~\\ref{fig:im_mixt}) each of which is the linear combination of $4$ sources (Figure~\\ref{fig:im_sources}). The mixing matrix has been chosen at random. The GMCA algorithm has been performed in the biorthogonal wavelet domain; see \\citep{mallatb08}. The estimated sources are shown in Figure~\\ref{fig:im_esources}. These results were obtained using the GMCALab toolbox \\citep{gmcalab}.\r\n\r\n% We previously emphasized on GMCA as being able to provide the sparsest sources in the sense  advocated by the sparse BSS framework. Figure~\\ref{fig:globl1} provides the evolution of the sparsity divergence $\\|\\tilde{\\bf S}\\|_1 - \\|{\\bf S}\\|_1$ along the $500$ GMCA iterations. Clearly, the GMCA algorithm tends to estimate sources with increasing sparsity. Furthermore, the GMCA solution has the same sparsity (with respect to the sparsity divergence ) as the true sources. This simple experiment then points out that GMCA is able to recover the solution having the correct sparsity level.\r\n\r\n% \\begin{figure}[htb]\r\n% \\begin{minipage}[b]{1\\linewidth}\r\n%     \\centerline{\\epsfig{figure=PS/gmca_simple_sources.png,width=8cm}}\r\n% \\end{minipage}\r\n%  \\caption{The $256 \\times 256$ source images.}  \\label{fig:im_sources}\r\n% \\end{figure}\r\n\r\n% \\begin{figure}[htb]\r\n% \\begin{minipage}[b]{1\\linewidth}\r\n%     \\centerline{\\epsfig{figure=PS/gmca_simple_mixt.png,width=8cm}}\r\n% \\end{minipage}\r\n%  \\caption{The $256 \\times 256$ noiseless mixtures.}  \\label{fig:im_mixt}\r\n% \\end{figure}\r\n\r\n% \\begin{figure}[htb]\r\n% \\begin{minipage}[b]{1\\linewidth}\r\n%     \\centerline{\\epsfig{figure=PS/gmca_simple_estim.png,width=8cm}}\r\n% \\end{minipage}\r\n%  \\caption{The sources estimated using GMCA.}  \\label{fig:im_esources}\r\n% \\end{figure}\r\n\r\n% \\begin{figure}[htb]\r\n% \\begin{minipage}[b]{1\\linewidth}\r\n%     \\centerline{\\epsfig{figure=PS/sp2.png,width=12cm}}\r\n% \\end{minipage}\r\n%  \\caption{\\textbf{GMCA provides the sparsest solution - Abscissa~:} Iteration number. \\textbf{Ordinate~:} Sparsity divergence $\\|\\tilde{\\bf S}\\|_1 - \\|{\\bf S}\\|_1$.}  \\label% {fig:globl1}\r\n% \\end{figure}\r\n\r\n\r\n\\subsection{GMCA and Noisy Data}\r\n\\begin{figure}[htb]\r\n\\begin{minipage}[b]{0.49\\linewidth}\r\n                  \\centerline{         \\includegraphics[width=5cm]{gmca_fig6a.pdf}}\r\n\\end{minipage}\r\n\\hfill\r\n\\begin{minipage}[b]{0.49\\linewidth}\r\n                  \\centerline{         \\includegraphics[width=5cm]{gmca_fig6b.pdf}}\r\n \\end{minipage}\r\n\\vfill\r\n\\begin{minipage}[b]{0.49\\linewidth}\r\n                  \\centerline{         \\includegraphics[width=5cm]{gmca_fig6c.pdf}}\r\n \\end{minipage}\r\n\\hfill\r\n\\begin{minipage}[b]{0.49\\linewidth}\r\n                  \\centerline{         \\includegraphics[width=5cm]{gmca_fig6d.pdf}}\r\n\\end{minipage}\r\n \r\n\\caption{Top: the $256 \\times 256$ source images. Bottom: two noisy mixtures SNR = $10$ dB.}  \r\n\\label{fig:im_source_mixt}\r\n\\index{data!boats}\r\n\\end{figure}\r\n\r\nThe goal here is to compare several BSS techniques with GMCA for image separation in a noisy environment. Three different reference BSS methods are chosen:\r\n\\begin{itemize}\r\n\\item JADE \\citep{ica:jade}: the well-known ICA based on fourth-order statistics, see Section~\\ref{subsec:ICAHOS}.\r\n\\item Relative Newton Algorithm (RNA) \\citep{ica:zibu_relnewton}: the seminal sparsity-based BSS technique described in Section~\\ref{subsec:towardsparsity}. In the experiments reported hereafter, we used the RNA on the channels transformed in the 2D OWT domain.\r\n\\item EFICA: this separation method improves the FastICA algorithm for sources following a GGD prior. We thus applied EFICA on the channels transformed by a 2D OWT to sparsify them and hence the leptokurticity assumption on the source marginal statistics becomes valid. \r\n\\end{itemize}\r\n\r\nFig.\\ \\ref{fig:im_source_mixt} shows the original $N_s=2$ sources (top) and $N_c=2$ mixtures (bottom). The sources $s_1$ and $s_2$ are normalized to a unit variance. The mixing matrix $\\A$ is such that $y_1 = 0.25 s_1 + 0.5 s_2 + \\veps_1$ and $y_2 = -0.75 s_1 + 0.5s_2 + \\veps_2$, where $\\veps_1$ and $\\veps_2$ are zero-mean white Gaussian noise vectors that are mutually independent.\r\n\r\nThe comparisons we carry out here are twofold: (i) we assess the separation quality in terms of the correlation between the original and estimated sources as the SNR varies; (ii) as the estimated sources are also perturbed by noise, we also quantify the performance of each method by computing the mixing matrix criterion $\\mathrm{C}_{\\A}$. The GMCA algorithm was applied using a dictionary containing the DCTG2 and the Local DCT.  \r\n\r\n\\begin{figure}[htb]\r\n\\centerline{\r\n\\includegraphics[width=0.6\\textwidth]{gmca_fig7a.pdf}\r\n\\includegraphics[width=0.6\\textwidth]{gmca_fig7b.pdf}}\r\n\\caption{Evolution of the correlation coefficient between the original and the estimated sources as a function of the SNR (left: source 1, right: source 2). Solid line: GMCA. Dashed line: JADE. $'\\star'$: EFICA. $'+'$: RNA.}  \r\n\\label{fig:crit_sources}\r\n\\end{figure}\r\nFig.\\ \\ref{fig:crit_sources} portrays the evolution of the correlation coefficient of source $1$ (left) and source $2$ (right) as a function of the SNR. At first glance, GMCA, RNA and EFICA are very robust to noise as they give correlation coefficients close to the optimal value $1$. On these images, JADE behaves rather poorly. It might be due to the correlation between these two sources. For higher noise levels (SNR lower than $10$ dB), EFICA tends to perform slightly worse than GMCA and RNA.\r\n\r\n\\begin{figure}[htb]\r\n\\begin{minipage}[b]{0.95\\linewidth}\r\n                       \\centerline{         \\includegraphics[width=9cm]{gmca_fig8.pdf}}\r\n\\end{minipage}\r\n\\caption{Evolution of the mixing matrix criterion $\\mathrm{C}_{\\A}$ as a function of the SNR. Solid line: GMCA. Dashed line: JADE. $'\\star'$: EFICA. $'+'$: RNA.}  \\label{fig:crit_mixmat}\r\n\\end{figure}\r\n\r\nThe mixing matrix-based criterion $\\mathrm{C}_{\\A}$ turns out to be more sensitive to separation errors and then better discriminates between the methods. Fig.\\ \\ref{fig:crit_mixmat} depicts the behavior of $\\mathrm{C}_{\\A}$ with increasing SNR. While the correlation coefficient was unable to discriminate between GMCA and RNA, $\\mathrm{C}_{\\A}$ clearly reveals their differences. First, it confirms the dramatic behavior of JADE on that set of mixtures. Secondly, RNA and EFICA behave rather similarly. Thirdly, GMCA  seems to provide far better results with $\\mathrm{C}_{\\A}$ values that are up to $10$ times better than JADE and approximately $2$ times better than with RNA or EFICA. \r\n\r\nIn summary, the findings of this experiment allow us to conclude safely that:\r\n\\begin{itemize}\r\n\\item Sparsity brings better results. Amongst the methods we used, only JADE is not a sparsity-based separation algorithm. Whatever the method, separating in a sparse representation-domain enhances the separation quality: RNA, EFICA and GMCA clearly outperform JADE.\r\n\\item GMCA takes better advantage of overcompleteness and morphological diversity. GMCA takes better advantage of overcomplete sparse representations than RNA and EFICA.\r\n\\end{itemize}\r\n%Other experiments have also shown that  GMCA computation time  is more sensitive to the number of iterations than to the number of sources, which is of major interest when dealing with higher dimensional problems such as hyperspectral data \\citep{bobin08_aiep}.\r\n\r\n \r\n\r\n\\subsection{Multichannel Image Inpainting}\r\n\\label{sec:inp}\r\n\r\n\\begin{figure}[htb]\r\n\\hbox{\r\n\\centerline{         \r\n\\includegraphics[width=0.4\\textwidth]{jmiv_barbara_colour.pdf}\r\n\\includegraphics[width=0.4\\textwidth]{jmiv_zoom_orig.pdf}}\r\n}\r\n\\hbox{\r\n\\centerline{         \r\n\\includegraphics[width=0.4\\textwidth]{jmiv_transmitted.pdf}\r\n\\includegraphics[width=0.4\\textwidth]{jmiv_zoom_trans.pdf}}\r\n}\r\n\\hbox{\r\n\\centerline{         \r\n\\includegraphics[width=0.4\\textwidth]{jmiv_reconstructed_cl_tv.pdf}\r\n\\includegraphics[width=0.4\\textwidth]{jmiv_zoom_yes.pdf}}\r\n}\r\n\r\n\\caption{Inpainting color images. Top, original \\texttt{Barbara} color image (left) and a zoom on the scarf (right). Middle, masked image -- $90$\\% of the color pixels are missing.  Bottom, inpainted image using the adaptive GMCA algorithm.} \r\n\\label{fig:col_inp}\r\n\\index{data!Barbara}\r\n\\end{figure} \r\n\r\nSimilarly to the MCA (see Section~\\eqref{par:mcainpaint}), GMCA can be readily extended to handle multichannel missing data. Although the rest of the section holds for any overdetermined multichannel data, without loss of generality, we consider color images where the observed data $\\bY$ consist of $N_c=3$ observed channels corresponding to each color layer (for instance red, green and blue), and the number of sources is also $N_s=3$. \r\n\r\nGMCA-inpainting seeks an unmixing scheme, through the estimation of $\\A$, which leads to the sparsest sources $\\bf S$ in the dictionary ${\\W}$, \r\ntaking into account the missing data mask ${ \\bf M}_j$ (the main diagonal of ${\\bf M}_j$ encodes the pixel status in channel $j$; see Section~\\ref{par:mcainpaint} for more details). The resulting optimization problem to be solved is then:\r\n\\begin{multline}\r\n\\label{eq:inp_optim_comp}\r\n\\min_{{\\A},\\alpha_{1,1},\\cdots,\\alpha_{N_s,K}} \\sum_{j=1}^{N_c}\\frac{1}{2}\\norm{y_j - {\\bf M}_j\\parenth{\\sum_{i=1}^{N_s} \\A[j,i]\\W\\alpha_i}}^2_2 + \\lambda \\sum_{i=1}^{N_s} \\sum_{k=1}^K \\norm{\\alpha_{i,k}}_p^p \\\\ \\st \\norm{a_i}_2 = 1 ~ \\forall i \\in \\{1,\\cdots,N_s\\} ~.\r\n\\end{multline}\r\nIf ${\\bf M}_j={\\bf M}$ for all channels, \\eqref{eq:inp_optim_comp} becomes\r\n\\begin{multline}\r\n\\label{eq:inp_optim_comp1}\r\n\\min_{{\\A},\\alpha_{1,1},\\cdots,\\alpha_{N_s,K}} \\frac{1}{2}\\norm{\\bY - \\A\\balpha\\W^\\Tr{\\bf M}}^2_{\\mathrm{F}} + \\lambda \\sum_{i=1}^{N_s} \\sum_{k=1}^K \\norm{\\alpha_{i,k}}_p^p \\\\ \\st \\norm{a_i}_2 = 1 ~ \\forall i \\in \\{1,\\cdots,N_s\\} ~.\r\n\\end{multline}\r\n\r\nThe GMCA-inpainting algorithm is similar to Algorithm \\ref{algo_gmca}, except that the update of the residual ${\\bf R}^{(t)}_{i,k}$ is modified to\r\n\\[\r\n{\\bf R}_{i,k}^{(t)} = \\bigg({\\bY}- \\sum_{(i',k') \\neq (i,k)} {a}_{i'}^{{(t-1)}}{x}_{i',k'}^{{(t-1)}^\\Tr}\\bigg){ \\bf M}.\r\n\\]\r\n\r\n% This has however the drawback that we cannot use anymore the fast version of GMCA because \r\n% we need to reconstruct  at each iteration the residual ${\\bf R}^{(t)}_{i,k}$  in order to take into account \r\n\r\n% the missing data mask ${ \\bf M}$.\r\n\r\nThe top panels of Fig.\\ \\ref{fig:col_inp} show the original \\texttt{Barbara} color image (in RGB space) and a zoom (on the right). The middle panels depict the masked color images where $90$\\% of the color pixels were missing. The bottom pictures portray the recovered images with the color space-adaptive GMCA algorithm, where $\\A$ was estimated along with the inpainted sources. It was shown in \\citet{BobinJMIV} that the adaptive color space GMCA inpainting performs much better than inpainting each color channel separately using the algorithms of Section~\\ref{sect_inpainting}.\r\n\r\n\r\n%========================================================================\r\n\r\n\\section{GMCA for Hyperspectral Data}\r\n\r\n\\index{hyperspectral data}\r\n\\index{multispectral data}\r\n\r\n\\label{sec:hypGMCA}\r\n%------------------------------------------------------------------------------------\r\n\\subsection{Specificity of Hyperspectral Data}\r\n%------------------------------------------------------------------------------------\r\n% Considering the objective function in the minimization problem~\\eqref{eq:optim_bayes} from a Bayesian perspective, the $\\ell_1$ penalty terms imposing sparsity are easily interpreted as coming from Laplacian prior distributions on the components $s_k$ and problem~\\eqref{eq:optim_bayes} is akin to a maximum a posteriori estimation of the model parameters $\\A$ and $\\bf S$. \r\nSo far, there was a striking asymmetry in the treatment of $\\A$ and $\\bf S$ and this is in fact a common feature of the great majority of BSS methods. Invoking a uniform prior distribution for $\\A$ is standard practice. On the one hand, this imbalanced treatment may not seem so unfair when $\\A$ and $\\bf S$ actually do have very different roles in the model and very different sizes. As mentioned earlier, $\\A$ is often simply seen as a mixing matrix of small and fixed size while each row $s_i^\\Tr$ of the source matrix $\\bf S$ is usually seen as a collection of $N$ samples from a process in time or pixels in an image, which can grow very much larger than the number of channels $N_c$ as more data is collected. On the other hand, there are applications in which one deals with data from instruments with a very large number of channels which are well organized according to some physically meaningful index. \r\nA typical example is hyperspectral data where images are collected in a large number of, what is more, contiguous regions of the electromagnetic spectrum.  \r\nIt then makes sense to consider the continuity, the regularity, etc.\\ of some physical property from one channel to its neighbor. For instance the spectral signatures of the objects in the scene may be known a priori to have a sparse representation in some specified possibly redundant dictionary of spectral waveforms. \r\n\r\nIn what follows, the term hyperspectral is used generically to identify data with the following specific properties regardless of other definitions or models existing in other scientific communities:   \r\n\\begin{enumerate}\r\n\\item High dimensionality: the number of channels $N_c$ in common hyperspectral imaging devices can be greater than a hundred. Consequently, problems involving hyperspectral data often have very high dimensions.\r\n\\item Contiguity: the large number of channels in the instrument achieve a regular/uniform sampling of some additional and meaningful physical index (e.g.\\ wavelength, space, time). We refer to this added dimension as the spectral dimension regardless of its actual physical meaning.\r\n\\item Morpho-spectral coherence: hyperspectral data are assumed to be structured a priori according to the instantaneous linear mixture model given in \\eqref{eq:bss}.\r\n\\end{enumerate}\r\nWe describe next an extension of the fast GMCA algorithm for hyperspectral data processing when it is known a priori that the underlying objects of interest ${\\bY^{(i)}} = a_i s_i^\\Tr$ exhibit sparse spectral signatures and sparse spatial morphologies in dictionaries of spectral and spatial waveforms specified a priori. \r\n%------------------------------------------------------------------------------------\r\n\r\n\\subsection{GMCA for Hyperspectral BSS}\r\n%------------------------------------------------------------------------------------\r\n\\subsubsection{The Principle}\r\n%------------------------------------------------------------------------------------\r\n\r\nWe now assume that each column $i$ of the mixing matrix $\\A$ is sparse in a given dictionary ${\\W_\\nu}$ (spectral dictionary):\r\n\\begin{equation}\r\na_i = {\\W_\\nu} \\nu_i ~.\r\n\\end{equation} \r\n\r\nLet $\\bnu=[\\nu_1,\\cdots,\\nu_{N_s}]$. If ${\\W_\\nu}$ is an orthobasis, then \\eqref{eq:optimgmca} can be equivalently written for $p=1$:\r\n\\begin{equation}\r\n\\min_{\\bnu,\\balpha} ~ \\frac{1}{2}\\norm{\\W_\\nu^\\Tr{\\bY} -  \\bigg(\\sum_{i=1}^{N_s} {\\nu}_i{\\alpha}_i^\\Tr\\bigg)\\W^\\Tr}_\\mathrm{F}^2 + \\lambda\\sum_{i=1}^{N_s} \\norm{\\alpha_{i}}_{1} ~.\r\n\\end{equation}\r\nFor a general redundant spectral dictionary, the solution in $\\bnu$ must be regularized. One can think of adding a sparsity-promoting penalty just as for the coefficients $\\balpha$ of the sources. But this will be awkward as explained shortly.\r\n \r\nA well known property of the linear mixture model~\\eqref{eq:bss} is its scale and permutation invariance:  without additional prior information, the indexing of the ${\\bY^{(i)}}=a_is_i^\\Tr$ (respectively ${\\nu}_i{\\alpha}_i^\\Tr$) in the decomposition of data $\\bY$ is not meaningful and $a_i, s_i$ (respectively $ \\nu_i , \\alpha_i$) can trade a scale factor with full impunity. A consequence is that, unless a priori specified otherwise, information on the separate scales of  $a_i$ and $s_i$ (respectively $ \\nu_i , \\alpha_i$) is lost, and solely a joint scale parameter for $a_i, s_i$ (respectively $ \\nu_i , \\alpha_i$)  can be estimated. \r\n\r\nIn a Bayesian perspective, this a priori knowledge of the multiplicative mixing process, and of the loss of information it entails, needs to be translated into a practical joint prior probability distribution for  $ \\nu_i , \\alpha_i$. Unfortunately, deriving the distribution of the product of two independent random vectors $\\nu_i$ and $\\alpha_i$ starting from assumptions on their marginals is notoriously cumbersome. \r\n\r\nIt was proposed instead in \\citet{bobin08_aiep} that the following $\\pdf_{\\nu_i,\\alpha_i}$ is a good candidate joint sparse prior distribution for  $\\nu_i$ and $\\alpha_i$  after the loss of information induced by multiplication: \r\n\\begin{equation}\r\n\\pdf_{\\nu_i,\\alpha_i}(\\nu_i, \\alpha_i) \\propto \\exp \\bigg( - \\lambda \\sum_{l,m} | \\nu_i[l] \\alpha_i[m] |\\bigg) ~ .\r\n\\end{equation} \r\nThe property $\\sum_{l,m}|(\\nu_i \\alpha_i^\\Tr)[l,m]| = \\norm{\\nu_i}_1 \\norm{\\alpha_i}_1$ is obvious. Thus the proposed distribution has the nice property, for subsequent derivations, that the conditional distribution of $\\nu_i$ given $\\alpha_i$ (and conversely) is Laplacian which is a convenient sparsity prior distribution. This distribution provides a convenient and formal expression for the prior knowledge of the sparsity of both $a_i$ and $s_i$ in dictionaries of spectral and spatial waveforms and of the multiplicative mixing process. \r\n\r\nInserting this prior distribution in a Bayesian MAP estimator leads to the following minimization problem:\r\n\\begin{equation}\r\n\\label{eq:hgmca}\r\n\\min_{(\\nu_i,\\alpha_i)_{i=1,\\cdots,N_s}} ~ \\frac{1}{2}\\norm{{\\bY} -  \\W_\\nu\\bigg(\\sum_{i=1}^{N_s} {\\nu}_i{\\alpha}_i^\\Tr\\bigg)\\W^\\Tr}_\\mathrm{F}^2   +   \\lambda \\sum_{i=1}^{N_s}    \\norm{\\nu_i}_1 \\norm{\\alpha_i}_1  ~ . \r\n\\end{equation}\r\nDenoting ${\\boldsymbol \\zeta}^{(i)} = \\nu_i \\alpha_i^\\Tr$, the above equation can be expressed slightly differently:\r\n\\begin{multline}\r\n\\min_{({\\boldsymbol \\zeta}^{(i)})_{i=1,\\cdots,N_s}} ~ \\frac{1}{2}\\norm{{\\bY} -  \\W_\\nu\\bigg(\\sum_{i=1}^{N_s} {\\boldsymbol \\zeta}^{(i)}\\bigg)\\W^\\Tr}_\\mathrm{F}^2   +   \\lambda \\sum_{i=1}^{N_s} \\sum_{l,m}\\abs{{\\boldsymbol \\zeta}^{(i)}[l,m]}  \\\\ \\st \\rank({\\boldsymbol \\zeta}^{(i)}) \\leq 1 ~ \\forall ~ i ~ .\r\n\\end{multline} \r\nwhich uncovers a nice interpretation as that of approximating $\\bY$ by the sum of rank-one matrices which are sparse in a specified dictionary of rank-one matrices (see also Section~\\ref{sec:bss_sparse}). Let us note that rescaling the parameters $\\A$ and $\\bf S$ is not as much a problem now as with GMCA, since \r\nthis is enforced mechanically in the parameterization of the prior, thus leaving the objective function~\\eqref{eq:hgmca} unchanged. This is why the normalization constraint of \\eqref{eq:optimgmca} is deliberately omitted in \\eqref{eq:hgmca}\r\n\r\n% it does not affect the objective function~\\eqref{eq:hgmca}. Indeed, rescaling the columns of the mixing matrix, ${\\A} \\leftarrow{\\rho {\\A}}$ while applying the proper inverse scaling to the rows of the source matrix, ${\\bf S} \\leftarrow \\frac{1}{\\rho} {\\bf S}$, leaves both the quadratic measure of fit and  the $\\ell_1$ sparsity measure in  \\eqref{eq:hgmca} unaltered. Although re-normalizing is still worthwhile numerically, it is no longer dictated by the lack of scale invariance of the objective function \r\n\r\n% In the next section, we  describe the extension of the fast-GMCA algorithm to the hyperspectral BSS issue \\citep{bobin08_aiep}.\r\n\r\n%------------------------------------------------------------------------------------\r\n\\subsubsection{Hypespectral GMCA Algorithm}\r\n \r\nThe minimization problem \\eqref{eq:hgmca} can be compactly written as\r\n\\begin{equation}\r\n\\label{eq:hgmca1}\r\n\\min_{\\bnu,\\balpha} ~ \\frac{1}{2}\\norm{{\\bY} -  \\W_\\nu\\bnu\\balpha\\W^\\Tr}_\\mathrm{F}^2 + \\lambda \\sum_{i=1}^{N_s} \\norm{\\nu_i}_1 \\norm{\\alpha_i}_1 ~ .\r\n\\end{equation}\r\nThis is a non-convex problem whose solutions have no explicit formulation. But, for fixed $\\bnu$ (respectively $\\balpha$), the marginal minimization problem over $\\balpha$ (respectively $\\bnu$) becomes convex and can be solved efficiently using the forward-backward splitting iteration (see Chapter~\\ref{ch_inverse}). Consequently, \\eqref{eq:hgmca1} is again to be solved by means of a block-coordinate relaxation by alternately minimizing with respect to $\\bnu$ holding $\\balpha$ fixed, and vice versa. \r\n\r\nThe solution to $\\bnu$ (respectively $\\balpha$) holding $\\balpha$ (respectively $\\bnu$) fixed is given by the general form of the forward-backward recursion:\r\n\\begin{equation}\r\n\\label{eq:fhgmca1}\r\n\\begin{split}\r\n\\balpha^{(t+1)} &=  \\ST_{\\lambda_{\\balpha}}\\parenth{\\balpha^{(t)} + \\mu_{\\balpha}{\\boldsymbol \\Xi}_{\\balpha}\\bnu^\\Tr\\W_\\nu^\\Tr\\parenth{\\bY - \\W_\\nu\\bnu\\balpha^{(t)}\\W^\\Tr}\\W} ~, \\\\\r\n\\bnu^{(t+1)}    &=  \\ST_{\\lambda_{\\bnu}}\\parenth{\\bnu^{(t)} + \\mu_{\\bnu}\\W_\\nu^\\Tr\\parenth{\\bY - \\W_\\nu\\bnu^{(t)}\\balpha\\W^\\Tr}\\W\\balpha^\\Tr{\\boldsymbol \\Xi}_{\\bnu}} ~,  \r\n\\end{split}\r\n\\end{equation}\r\nwhere ${\\boldsymbol \\Xi}_{\\balpha},{\\boldsymbol \\Xi}_{\\bnu}$ are relaxation matrices ensuring non-expansiveness and $\\mu_{\\balpha},\\mu_{\\bnu}$ is a descent step-size such that $0 < \\mu_{\\balpha} \\leq 1/(\\opnorm{\\W_\\nu}^2\\opnorm{\\W}^2\\opnorm{\\bnu}^2\\opnorm{{\\boldsymbol \\Xi}_{\\balpha}})$ and similarly for $\\mu_{\\bnu}$ by appropriate substitution \\citep{ChenRockafellar97}. The multichannel soft-thresholding operator $\\ST_{\\lambda_{\\balpha}}$ acts on each row $i$ with threshold $\\lambda_{\\balpha}[i]=\\lambda\\norm{\\nu_i}_1\\mu_{\\balpha}$ and $\\ST_{\\lambda_{\\bnu}}$ acts on each column $j$ of $\\bnu$ with threshold $\\lambda_{\\bnu}[j]=\\lambda\\norm{\\alpha_j}_1\\mu_{\\bnu}$.\r\n\r\nDenote $\\Yz = \\W_\\nu^\\Tr\\bY\\W$. Taking ${\\boldsymbol \\Xi}_{\\balpha} = (\\bnu^\\Tr\\bnu)^{-1}$, ${\\boldsymbol \\Xi}_{\\bnu} = (\\balpha\\balpha^\\Tr)^{-1}$ (both matrices are non-singular), assuming moreover that both dictionaries $\\W$ and $\\W_\\nu$ are normalized such that their upper frame bounds are $1$, and stopping the recursions \\eqref{eq:fhgmca1} at the first iteration yields the closed-form approximate solutions\r\n\\begin{equation}\r\n\\label{eq:fhgmca2}\r\n\\begin{split}\r\n\\tilde{\\balpha} &=  \\ST_{\\lambda_{\\balpha}}\\parenth{(\\bnu^\\Tr\\bnu)^{-1}\\bnu^\\Tr\\Yz} = \\ST_{\\lambda_{\\balpha}}\\parenth{\\bnu^+\\Yz}~, \\\\\r\n\\tilde{\\bnu}    &=  \\ST_{\\lambda_{\\bnu}}\\parenth{\\Yz\\balpha^\\Tr(\\balpha\\balpha^\\Tr)^{-1}} = \\ST_{\\lambda_{\\bnu}}\\parenth{\\Yz\\balpha^+}~.  \r\n\\end{split}\r\n\\end{equation}\r\n\r\n\\index{iterative!hard thresholding}\r\n\\index{iterative!soft thresholding}\r\n\r\nBoth update rules can be interpreted as a soft-thresholding operator applied to the result of a weighted least-squares regression in the ${\\W_\\nu}\\otimes {\\W}$ representation. In the spirit of the fast GMCA algorithm described in Section~\\ref{gmca_algo}, the transformation into ${\\W_\\nu}\\otimes {\\W}$ is applied only once which has a major impact on computation speed, especially when dealing with large hyperspectral datasets. The two stage iterative process leads to the fast hypGMCA summarized in Algorithm \\ref{algo_hyper_gmca} \\citep{moudden08}.\r\n%Finally, in the spirit of the fast GMCA algorithm described in Section~\\ref{gmca_algo}, it is proposed here that a solution to the above set of coupled  equations~\\eqref{eq:fhgmca1} can also be approached effectively using a symmetric iterative alternating least-squares scheme in conjunction with a shrinkage operator with a progressively decreasing threshold. \r\n\r\n{\\linespread{1}\r\n\\begin{algorithm}[htb]\r\n\\caption{hypGMCA algorithm.}\r\n\\label{algo_hyper_gmca}\r\n\\noindent{\\bf Task:} Sparse Blind Source Separation for hyperspectral data.\\\\\r\n\\noindent{\\bf Parameters:} The data $\\bY$, the spatial and spectral dictionaries $\\W,\\W_\\nu$, number of iterations $\\niter$, number of sources $N_s$ and channels $N_c$, stopping threshold $\\lambda_{\\min}$, threshold update schedule.\\\\\r\n\\noindent{\\bf Initialization:} $\\balpha^{(0)} = 0$,  $\\bnu^{(0)} = $ random matrix. Let $\\Yz = \\W_\\nu^\\Tr\\bY\\W$, set threshold $\\lambda_0 = \\max_{l,m}\\abs{\\Yz[l,m]}$.\r\n\\noindent{\\bf Main iteration:} \\\\\r\n\\For{$t=1$ {\\bf to} $\\niter$}{\r\n\\begin{itemize}\r\n     \\item  Update spatial coefficients $\\balpha$:\r\n     $ \\balpha^{(t+1)} = \\ST_{\\lambda_t}\\parenth{\\bnu^{(t)^+}\\Yz}$.\r\n     \\item  Update spectral coefficients $\\bnu$:\r\n     $ \\bnu^{(t+1)} = \\ST_{\\lambda_t}\\parenth{\\Yz\\balpha^{(t)^+}}$.\r\n     \\item Update  the threshold $ \\lambda_t$ according to the given schedule.\r\n\\end{itemize}\r\n\\lIf{$\\lambda_t \\leq \\lambda_{\\min}$} stop.\r\n}\r\nReconstruct the sources: $\\tilde{\\bf S} =  {\\W} \\balpha^{(\\niter)}$.\\\\\r\nReconstruct the mixing matrix: $\\tilde{\\A} =  {\\W_\\nu} \\bnu^{(\\niter)}$.\\\\\t\r\n\\noindent{\\bf Output:} Estimated sources $\\left(\\tilde{s}_{i}\\right)_{i=1, \\cdots, N_s}$, and mixing matrix $\\tilde{{\\bf{A}}}$.\r\n\\end{algorithm}\r\n}\r\n\r\nIt goes without saying that the coarse-to-fine process is again the core of hypGMCA. With the threshold successively decreasing, the current sparse approximation is progressively refined by including finer structures alternatingly in the different morphological components, both spatially and spectrally. Here again, soft thresholding results from the use of an $\\ell_1$ sparsity measure, which as explained earlier comes as a good approximation to the desired $\\ell_0$ quasi-norm solution. Towards the end of the iterative process, applying a hard threshold instead can lead to better results. The final threshold should vanish in the noiseless case or it may be set to a multiple of the noise standard deviation in the presence of noise as explained before. \r\n\r\n%-------------------------------------------------------------------------------------\r\n%-------------------------------------------------------------------------------------\r\n%-------------------------------------------------------------------------------------\r\n\r\n\\subsection{Illustrative Example}\r\n\\label{sec:expe_hyper}\r\n \r\nIn this toy example, the sources are drawn uniformly at random from a set of $128 \\times 128$ images featured in Fig.\\ \\ref{fig:allim}. The number of drawn sources is $N_s=5$. The number of channels is $ N_c =128$. The spectra are synthesized from OWT coefficients, and the latter are drawn from a Laplacian PDF with unit scale parameter. The spectra are to be positive; note that the GMCA algorithm is flexible enough to account for this constraint. In the next experiments, as the goal is to assess the impact of the spectral sparsity penalization, this positivity a priori information is not exploited. White Gaussian noise with covariance matrix ${\\boldsymbol \\Sigma}_{\\bf E} = \\sigma_{\\bf E}^2 \\bf I$ is added.\r\n\r\nThe fast GMCA algorithm is compared to hypGMCA. This first test will give emphasis to the enhancements brought by the spectral sparsity regularization when the SNR varies from $0$ to $40$ dB. Fig.\\ \\ref{fig:hypmixtures} portrays $6$ out of $128$ noisy channels with $\\mbox{SNR} = 20$ dB. The fast GMCA algorithm is applied in the curvelet domain, and hypGMCA is applied with the curvelet spatial dictionary $\\W$ and the OWT for the spectral dictionary $\\W_\\nu$. Fig.\\ \\ref{fig:hypsources} depicts the sources estimated by the fast GMCA algorithm (panels on the left) and by hypGMCA algorithm (panels on the right). Visual impression clearly favors the results provided by hypGMCA. More quantitative results are given in Fig.\\ \\ref{fig:hypcurv} which displays the evolution of the mixing matrix criterion $\\mathrm{C}_{\\A}$ as a function of the SNR. Clearly, accounting for additional prior information provides better recovery results. Furthermore, as shown in Fig.\\ \\ref{fig:hypcurv}, the morpho-spectral sparsity constraint provides more robustness to noise.\r\n\r\n \\begin{figure}[htb]\r\n\\begin{minipage}[b]{0.5\\linewidth}\r\n    \\centerline{ \\includegraphics[width=11cm]{HypGMCA_allimages.png}}\r\n\\end{minipage}\r\n\\begin{minipage}[b]{0.5\\linewidth}\r\n\\end{minipage}\r\n\\caption{Image data set used in the experiment.}\r\n \\label{fig:allim}\r\n\\end{figure} \r\n\r\n\\begin{figure}[htb]\r\n\\hbox{\r\n\\begin{minipage}[b]{0.3\\linewidth}\r\n\\centerline{         \\includegraphics[width=3.3cm]{HypGMCA_mixt0.png}}\r\n \\end{minipage}\r\n\\begin{minipage}[b]{0.3\\linewidth}\r\n\\centerline{         \\includegraphics[width=3.3cm]{HypGMCA_mixt1.png}}\r\n \\end{minipage}\r\n\\begin{minipage}[b]{0.3\\linewidth}\r\n\\centerline{         \\includegraphics[width=3.3cm]{HypGMCA_mixt2.png}}\r\n \\end{minipage}\r\n}\r\n\\hbox{\r\n\\begin{minipage}[b]{0.3\\linewidth}\r\n\\centerline{         \\includegraphics[width=3.3cm]{HypGMCA_mixt3.png}}\r\n \\end{minipage}\r\n\\begin{minipage}[b]{0.3\\linewidth}\r\n\\centerline{         \\includegraphics[width=3.3cm]{HypGMCA_mixt4.png}}\r\n \\end{minipage}\r\n\\begin{minipage}[b]{0.3\\linewidth}\r\n\\centerline{         \\includegraphics[width=3.3cm]{HypGMCA_mixt5.png}}\r\n \\end{minipage}\r\n}\r\n   \\caption{Six $128 \\times 128$ mixtures out of the 128 channels. The SNR is equal to $20$ dB.} \\label{fig:hypmixtures}\r\n\\index{data!boats}\r\n\\end{figure} \r\n\r\n\r\n\r\n\\begin{figure}[htb]\r\n\\hbox{\r\n\\begin{minipage}[b]{0.5\\linewidth}\r\n\\centerline{         \\includegraphics[width=3.3cm]{HypGMCA_estsource0.png}}\r\n \\end{minipage}\r\n\\hfill\r\n\\begin{minipage}[b]{0.5\\linewidth}\r\n\\centerline{         \\includegraphics[width=3.3cm]{HypGMCA_estsourceL10.png}}\r\n \r\n\\end{minipage}\r\n}\r\n\r\n\\hbox{\r\n\r\n\\begin{minipage}[b]{0.5\\linewidth}\r\n\\centerline{         \\includegraphics[width=3.3cm]{HypGMCA_estsource1.png}}\r\n \\end{minipage}\r\n\\hfill\r\n\r\n\\begin{minipage}[b]{0.5\\linewidth}\r\n\\centerline{         \\includegraphics[width=3.3cm]{HypGMCA_estsourceL11.png}}\r\n \\end{minipage}\r\n}\r\n\r\n \r\n\\hbox{\r\n\\begin{minipage}[b]{0.5\\linewidth}\r\n\\centerline{         \\includegraphics[width=3.3cm]{HypGMCA_estsource3.png}}\r\n \\end{minipage}\r\n\\hfill\r\n\\begin{minipage}[b]{0.5\\linewidth}\r\n\\centerline{         \\includegraphics[width=3.3cm]{HypGMCA_estsourceL13.png}}\r\n \\end{minipage}\r\n}\r\n\\hbox{\r\n\r\n\\begin{minipage}[b]{0.5\\linewidth}\r\n\\centerline{         \\includegraphics[width=3.3cm]{HypGMCA_estsource4.png}}\r\n \\end{minipage}\r\n \\hfill\r\n\r\n\\begin{minipage}[b]{0.5\\linewidth}\r\n\\centerline{         \\includegraphics[width=3.3cm]{HypGMCA_estsourceL14.png}}\r\n \\end{minipage}\r\n}\r\n  \\caption{Comparison of fast GMCA to hypGMCA. Left: Sources estimated by the fast GMCA algorithm. Right: Sources estimated by hypGMCA.} \\label{fig:hypsources}\r\n\\index{data!boats}\r\n\\index{data!Barbara}\r\n\\end{figure} \r\n\r\n\r\n\r\n\r\n\\begin{figure}[htb]\r\n\\begin{minipage}[b]{1\\linewidth}\r\n\\centerline{         \\includegraphics[width=8cm]{HypGMCA_MMCCurv.pdf}}\r\n\\end{minipage}\r\n\\caption{Evolution of the mixing matrix criterion $\\mathrm{C}_{\\A}$ as a function of the SNR in dB. Solid line: recovery results by the fast GMCA algorithm. '$\\bullet$': recovery results by hypGMCA.} \\label{fig:hypcurv}\r\n\\end{figure} \r\n\r\n\r\n\r\n%\\subsection{Other Constraints on the Mixing Matrix}\r\n%\\label{sec:pbss} \r\n%We have seen in the previous section that, for hyperspectral signals, a sparsity penalization on the mixing matrix improves the results. Very often, the separation task is only partly blind.  For example, in some applications, one (or more) columns of the mixing matrix may be known. This is the case for instance in the Cosmic Microwave Background separation (CMB) problem in cosmology. As for hyperspectral data, each column of the mixing matrix is related to the power spectrum of a given source. The CMB  power spectrum is perfectly known and is a perfect blackbody, while spectra of other  sources are unknown. In \\citet{bobin-gmca-cmb}, it is shown how to modify GMCA, so we can  constrain the column of the mixing matrix ${\\A}$ related to CMB to its known physical shape. This is equivalent to placing a strict prior on the CMB column of ${\\A}$; that is $\\pdf(a^\\mathrm{cmb})) = \\delta(a^\\mathrm{cmb} - a^\\mathrm{cmb}_0)$, $\\delta(.)$ is the Dirac distribution and $a^\\mathrm{cmb}_0$ is the true CMB emission law in the observed frequency range. \r\n\r\n%Another constraint of interest is the positivity of the mixing matrix. In many problems, we know that the matrix cannot contain negative values. In the framework of GMCA, such a constraint can be incorporated by projecting the columns of $\\A$ onto the positive orthant before normalization.  \r\n \r\n\r\n\\section{Guided Numerical Experiments}\r\n\\subsection{GMCAlab}\r\n\\label{sec:gmcalab}\r\nGMCALab is a library of Matlab routines that implements the algorithms described here for multichannel signal/image bind source separation. The GMCALab library provides open source tools for BSS, and may be used to reproduce the BSS experiment below and to redo the figures with variations in the parameters. The library is available at the book's web site: \r\n\r\n{\\centerline{\\texttt{http://www.SparseSignalRecipes.info}}}\r\n\r\nIt requires at least WaveLab (see Section~\\ref{sec:wavelabintro}) to avail of\r\nfull functionality. It has been successfully tested for all major \r\noperating systems, under Matlab 6.x and Matlab 7.x. \r\nGMCALab is distributed for non-commercial use. \r\n\r\n\\subsection{Reproducible Experiment}\r\nFig.~\\ref{fig:gmcalabexperiment} illustrates the results provided by the script {\\tt sparse\\_noisy\\_\\\\examples.m} which applies the fast GMCA Algorithm~\\ref{algo_fast_gmca} to a BSS problem with $N_s=4$ sources, $N_c=10$ noisy channels, and SNR = 10dB. The mixing matrix is randomly generated with entries independent and identically distributed $\\sim \\cN(0,1)$. The fast GMCA was applied using the OWT dictionary.\r\n \r\n\\begin{figure}[htb]\r\n\\centerline{\\includegraphics[width=\\textwidth]{gmcalabexperiment.pdf}}\r\n\\caption{Results of the BSS guided experiment: $N_s=4$ sources, $N_c=10$ noisy channels, with SNR = 10 dB. The mixing matrix is randomly generated with entries independent and identically distributed $\\sim \\cN(0,1)$. The dictionary used in GMCA contained the OWT. Left: original sources. Middle: four out of ten noisy mixtures. Right: sources estimated using the fast GMCA Algorithm~\\ref{algo_fast_gmca}.} \r\n\\label{fig:gmcalabexperiment}\r\n\\index{data!boats}\r\n\\index{data!harbor}\r\n\\index{data!drum}\r\n\\end{figure} \r\n\r\n\\section{Summary}\r\nIn this chapter, the role of sparsity and morphological diversity was highlighted to solve the blind source separation problem. Based on these key ingredients, a fast algorithmic approach coined GMCA was described together with variations to solve several problems including BSS. The conclusions that one has to keep in mind are essentially twofold: first, sparsity and morphological diversity lead to enhanced separation quality, and second, the GMCA algorithm takes better advantage of sparsity yielding better and robust-to-noise separation. When the number of sources is unknown, a GMCA-based method was described to objectively estimate the correct number of sources. This chapter also extends the GMCA framework to cope with the particular structure of hyperspectral data. The results are given that illustrate the reliability of morpho-spectral sparsity regularization. In a wider framework, GMCA is shown to provide an effective basis for solving classical multichannel restoration problems such as color image inpainting. \r\n\r\nNonetheless, this exciting field of sparse BSS still has many interesting open problems. Among them, one may cite for instance the extension to the underdetermined case with more sources than channels, and the theoretical guarantees of the sparsity-regularized BSS problem. \r\n\u0001E 1\n", "meta": {"hexsha": "eedc0f1a99cce03b9df60adae5665e0db62ebae4", "size": 107232, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/doc/doc_isap/SCCS/s.ch_gmca.tex", "max_stars_repo_name": "sfarrens/cosmostat", "max_stars_repo_head_hexsha": "a475315cda06dca346095a1e83cb6ad23979acae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/doc/doc_isap/SCCS/s.ch_gmca.tex", "max_issues_repo_name": "sfarrens/cosmostat", "max_issues_repo_head_hexsha": "a475315cda06dca346095a1e83cb6ad23979acae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/doc/doc_isap/SCCS/s.ch_gmca.tex", "max_forks_repo_name": "sfarrens/cosmostat", "max_forks_repo_head_hexsha": "a475315cda06dca346095a1e83cb6ad23979acae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 103.9069767442, "max_line_length": 1644, "alphanum_fraction": 0.735536034, "num_tokens": 29911, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.3405016352515477}}
{"text": "\\input{../header}\n\n\\newcommand\\eqspace{\\hspace{3mm}}\n\\newcommand\\eqvspace{\\vspace{1mm}}\n\\newcommand\\negListSpace{\\hspace{-4mm}}\n\n\\newcommand\\ev{u}\n\n\\mode<beamer>{\\usetheme{AnnArbor}}\n\\mode<beamer>{\\setbeamertemplate{footline}}\n\\mode<beamer>{\\setbeamertemplate{footline}[frame number]}\n\\mode<beamer>{\\setbeamertemplate{frametitle continuation}[from second][\\insertcontinuationcountroman]}\n\\mode<beamer>{\\setbeamertemplate{navigation symbols}{}}\n\n\\mode<handout>{\\pgfpagesuselayout{2 on 1}[letterpaper,border shrink=5mm]}\n\n\\newcommand\\CHAPTER{8}\n% \\newcommand\\answer[2]{\\textcolor{blue}{#2}} % to show answers\n% \\newcommand\\answer[2]{\\textcolor{red}{#2}} % to show answers\n \\newcommand\\answer[2]{#1} % to show blank space\n\\usepackage{bbm} % for blackboard bold 1\n\n\n\\title{\\vspace{2mm} \\link{https://ionides.github.io/531w22/}{Modeling and Analysis of Time Series Data}\\\\ \\vspace{2mm}\nChapter \\CHAPTER: Smoothing in the time and frequency domains}\n\\author{Edward L. Ionides}\n\\date{}\n\n\\setbeamertemplate{footline}[frame number]\n\n\n\n\n\\begin{document}\n\n\\maketitle\n\n\\mode<article>{\\tableofcontents}\n\n\\mode<presentation>{\n  \\begin{frame}{Outline}\n    \\tableofcontents\n  \\end{frame}\n}\n\n\n\n\n\\section{Smoothing a time series}\n%\\subsection{}\n\n\\begin{frame}{Introduction to smoothing in time series analysis}\n\n\n\n\\bi\n\\item   Estimating a nonparametric trend from a time series is known as smoothing. We will review some standard smoothing methods.\n\n\\item We also smooth the periodogram to estimate a spectral density.\n\n\\item Smoothers have convenient interpretation in the frequency domain. A smoother typically shrinks high frequency components and preserves low frequency components.\n\n\\ei\n\n\\end{frame}\n\n\n\\begin{frame}[fragile]\n\n\\frametitle{A motivating example}\n\n\\mode<presentation>{\n\\vspace{-2mm}\n}\n\n\\bi\n\\item The economy fluctuates between periods of rapid expansion and periods of slower growth or contraction. \n\n\\item High unemployment is one of the most visible signs of a dysfunctional economy, in which labor is under-utilized, leading to hardships for many individuals and communities.\n\n\\item Economists, politicians, businesspeople and the general public therefore have an interest in understanding fluctuations in unemployment.\n\n\\item Economists try to distinguish between fundamental structural changes in the economy and the shorter-term cyclical booms and busts that appear to be a natural part of capitalist business activity.\n\n\\item Monthly US unemployment figures are published by the \\link{https://data.bls.gov/timeseries/LNU04000000}{Bureau of Labor Statistics (BLS)}.\n\n\\item Measuring unemployment has subtleties, but these are not our immediate focus.\n\\ei\n\n\\end{frame}\n\\begin{frame}[fragile]\n\n\\vspace{-3mm}\n\n\\begin{knitrout}\\small\n\\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\\color{fgcolor}\\begin{kframe}\n\\begin{alltt}\n\\hlkwd{system}\\hlstd{(}\\hlstr{\"head unadjusted_unemployment.csv\"}\\hlstd{,}\\hlkwc{intern}\\hlstd{=}\\hlnum{TRUE}\\hlstd{)}\n\\end{alltt}\n\\end{kframe}\n\\end{knitrout}\n\n\\vspace{-3mm}\n\n\\begin{knitrout}\\small\n\\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\\color{fgcolor}\\begin{kframe}\n\\begin{verbatim}\n [1] \"# Data extracted on: February 3, 2022 (12:29:30 PM)\"        \n [2] \"# from http://data.bls.gov/timeseries/LNU04000000\"          \n [3] \"# Labor Force Statistics from the Current Population Survey\"\n [4] \"# Not Seasonally Adjusted\"                                  \n [5] \"# Series title:        (Unadj) Unemployment Rate\"           \n [6] \"# Series Id:           LNU04000000\"                         \n [7] \"# Labor force status:  Unemployment rate\"                   \n [8] \"# Type of data:        Percent or rate\"                     \n [9] \"# Age:                 16 years and over\"                   \n[10] \"Year,Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec\"       \n\\end{verbatim}\n\\end{kframe}\n\\end{knitrout}\n\n\\vspace{-3mm}\n\n\\begin{knitrout}\\small\n\\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\\color{fgcolor}\\begin{kframe}\n\\begin{alltt}\n\\hlstd{U1} \\hlkwb{<-} \\hlkwd{read.table}\\hlstd{(}\\hlkwc{file}\\hlstd{=}\\hlstr{\"unadjusted_unemployment.csv\"}\\hlstd{,}\n  \\hlkwc{sep}\\hlstd{=}\\hlstr{\",\"}\\hlstd{,}\\hlkwc{header}\\hlstd{=}\\hlnum{TRUE}\\hlstd{)}\n\\hlkwd{head}\\hlstd{(U1,}\\hlnum{3}\\hlstd{)}\n\\end{alltt}\n\\end{kframe}\n\\end{knitrout}\n\n\\vspace{-3mm}\n\n\\begin{knitrout}\\small\n\\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\\color{fgcolor}\\begin{kframe}\n\\begin{verbatim}\n Year Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec\n 1948 4.0 4.7 4.5 4.0 3.4 3.9 3.9 3.6 3.4 2.9 3.3 3.6\n 1949 5.0 5.8 5.6 5.4 5.7 6.4 7.0 6.3 5.9 6.1 5.7 6.0\n 1950 7.6 7.9 7.1 6.0 5.3 5.6 5.3 4.1 4.0 3.3 3.8 3.9\n\\end{verbatim}\n\\end{kframe}\n\\end{knitrout}\n\n\\end{frame}\n\n\\begin{frame}[fragile]\n\n\\vspace{-2mm}\n\n\\myquestion. A coding exercise: Explain how the tabulated data in \\code{U1} are converted to a time series, below.\n\n\\answer{\\vspace{15mm}}{todo}\n\n\n\\begin{knitrout}\\small\n\\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\\color{fgcolor}\\begin{kframe}\n\\begin{alltt}\n\\hlstd{u1} \\hlkwb{<-} \\hlkwd{t}\\hlstd{(}\\hlkwd{as.matrix}\\hlstd{(U1[}\\hlnum{2}\\hlopt{:}\\hlnum{13}\\hlstd{]))}\n\\hlkwd{dim}\\hlstd{(u1)} \\hlkwb{<-} \\hlkwa{NULL}\n\\hlstd{date} \\hlkwb{<-} \\hlkwd{seq}\\hlstd{(}\\hlkwc{from}\\hlstd{=}\\hlnum{1948}\\hlstd{,}\\hlkwc{length}\\hlstd{=}\\hlkwd{length}\\hlstd{(u1),}\\hlkwc{by}\\hlstd{=}\\hlnum{1}\\hlopt{/}\\hlnum{12}\\hlstd{)}\n\\hlkwd{plot}\\hlstd{(date,u1,}\\hlkwc{type}\\hlstd{=}\\hlstr{\"l\"}\\hlstd{,}\\hlkwc{ylab}\\hlstd{=}\\hlstr{\"Unemployment rate (unadjusted)\"}\\hlstd{)}\n\\end{alltt}\n\\end{kframe}\n\\end{knitrout}\n\n\\vspace{-3mm}\n\n\\begin{knitrout}\\small\n\\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\\color{fgcolor}\n\n{\\centering \\includegraphics[width=9cm]{tmp/figure/reshape-1} \n\n}\n\n\n\\end{knitrout}\n\n\n\\end{frame}\n\n\n\n\\begin{frame}[fragile]\n\n\\vspace{-3mm}\n\n\\bi\n\\item We see seasonal variation and economic cycles on top of a trend.\n\n\\item The seasonal variation looks like an additive effect, say an annual fluctation with amplitude around 1 percentage point. \n\n\\item Sometimes, we may prefer to look at monthly seasonally adjusted unemployment, \\link{https://data.bls.gov/timeseries/LNS14000000}{also provided by BLS}.\n\\ei\n\n\\vspace{-2mm}\n\n\\begin{knitrout}\\small\n\\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\\color{fgcolor}\\begin{kframe}\n\\begin{alltt}\n\\hlstd{U2} \\hlkwb{<-} \\hlkwd{read.table}\\hlstd{(}\\hlkwc{file}\\hlstd{=}\\hlstr{\"adjusted_unemployment.csv\"}\\hlstd{,}\\hlkwc{sep}\\hlstd{=}\\hlstr{\",\"}\\hlstd{,}\n  \\hlkwc{header}\\hlstd{=}\\hlnum{TRUE}\\hlstd{)}\n\\hlstd{u2} \\hlkwb{<-} \\hlkwd{t}\\hlstd{(}\\hlkwd{as.matrix}\\hlstd{(U2[}\\hlnum{2}\\hlopt{:}\\hlnum{13}\\hlstd{]))}\n\\end{alltt}\n\\end{kframe}\n\\end{knitrout}\n\n\\vspace{-4mm}\n\n\\begin{knitrout}\\small\n\\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\\color{fgcolor}\n\n{\\centering \\includegraphics[width=9cm]{tmp/figure/data_adj_code-1} \n\n}\n\n\n\\end{knitrout}\n\n\\vspace{-2mm}\n\n\\bi\n\\item\nWe can wonder how the BLS adjusts the data, and if this introduces any artifacts that a careful statistician should be aware of.\n\\ei\n\\end{frame}\n\n\n\\section{Seasonal adjustment in the frequency domain}\n\n\\begin{frame}[fragile]\n\n\n\\vspace{-2mm}\n\n\\bi\n\n\\item To help understand the seasonal adjustment, we look at what it does to the smoothed periodogram.\n\n\\item Using the \\code{ts} class we can tell R the units of time.\n\n\\ei\n\n\\vspace{-1mm}\n\n\\begin{knitrout}\\small\n\\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\\color{fgcolor}\\begin{kframe}\n\\begin{alltt}\n\\hlstd{u1_ts} \\hlkwb{<-} \\hlkwd{ts}\\hlstd{(u1,}\\hlkwc{start}\\hlstd{=}\\hlnum{1948}\\hlstd{,}\\hlkwc{frequency}\\hlstd{=}\\hlnum{12}\\hlstd{)}\n\\hlstd{u2_ts} \\hlkwb{<-} \\hlkwd{ts}\\hlstd{(u2,}\\hlkwc{start}\\hlstd{=}\\hlnum{1948}\\hlstd{,}\\hlkwc{frequency}\\hlstd{=}\\hlnum{12}\\hlstd{)}\n\\hlkwd{spectrum}\\hlstd{(}\\hlkwd{ts.union}\\hlstd{(u1_ts,u2_ts),}\\hlkwc{spans}\\hlstd{=}\\hlkwd{c}\\hlstd{(}\\hlnum{3}\\hlstd{,}\\hlnum{5}\\hlstd{,}\\hlnum{3}\\hlstd{),}\n  \\hlkwc{main}\\hlstd{=}\\hlstr{\"Unemployment: raw (black), seasonally adjusted (red)\"}\\hlstd{)}\n\\end{alltt}\n\\end{kframe}\n\\end{knitrout}\n\n\\vspace{-3mm}\n\n\\begin{knitrout}\\small\n\\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\\color{fgcolor}\n\n{\\centering \\includegraphics[width=11cm]{tmp/figure/adjustment_spectrum-1} \n\n}\n\n\n\\end{knitrout}\n\n\n\\end{frame}\n\n\\begin{frame}{Comments on the smoothed periodogram}\n\n\\bi\n\\item Note: For a report, we should add units to plots. Extra details (like \\code{bandwith} in the periodogram plot) should be explained or removed.\n\\ei\n\n\\vspace{1mm}\n\n\\myquestion. Why does the unadjusted spectrum have peaks at 2,3,4,5,6 cycles per year as well as 1 cycle per year?\n\n\\answer{\\vspace{20mm}}{todo}\n\n\n\\myquestion. Comment on what you learn from comparing these smoothed periodograms.\n\n\\answer{\\vspace{30mm}}{todo}\n\n\\end{frame}\n\n\\subsection{The frequency response function of a smoother}\n\n\\begin{frame}{The frequency response function}\n\n\\vspace{-2mm}\n\n\\bi\n\\item The ratio of the periodograms of the smoothed and unsmoothed time series is the \\myemph{frequency response} of the smoother.\n\n\\item The frequency response function tells us how much the smoother contracts (or inflates) the sine and cosine components at each frequency $\\omega$.\n\n\\item A frequency response may involve change in phase as well as magnitude, but here we consider only magnitude.\n\n\\item Linear, time invariant transformations do not move power between frequencies, so they are characterized by their frequency response function.\n\n\\item Smoothers are linear and time invariant, at least approximately. If we scale or shift the data, we expect the smoothed estimate to have the same scale or shift. We expect a smooth approximation to the sum of two time series to be approximately the sum of the two smoothed series.\n\n\\ei\n\n\\end{frame}\n\n\\begin{frame}[fragile]{Calculating a frequency response function}\n\n\\mode<presentation>{\n\\vspace{-2mm}\n}\n\n\\bi\n\\item We investigate the frequency response of the smoother used by Bureau of Labor Statistics to deseasonalize the unemployment data.\n\\ei\n\n\\begin{knitrout}\\small\n\\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\\color{fgcolor}\\begin{kframe}\n\\begin{alltt}\n\\hlstd{s} \\hlkwb{<-} \\hlkwd{spectrum}\\hlstd{(}\\hlkwd{ts.union}\\hlstd{(u1_ts,u2_ts),}\\hlkwc{plot}\\hlstd{=}\\hlnum{FALSE}\\hlstd{)}\n\\end{alltt}\n\\end{kframe}\n\\end{knitrout}\n\n\\bi\n\\item We find the parts of \\code{s} that we need to plot the frequency response.\n\\ei\n\n\\begin{knitrout}\\small\n\\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\\color{fgcolor}\\begin{kframe}\n\\begin{alltt}\n\\hlkwd{names}\\hlstd{(s)}\n\\end{alltt}\n\\end{kframe}\n\\end{knitrout}\n\n\\mode<presentation>{\n\\vspace{-3mm}\n}\n\n\\begin{knitrout}\\small\n\\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\\color{fgcolor}\\begin{kframe}\n\\begin{verbatim}\n [1] \"freq\"      \"spec\"      \"coh\"       \"phase\"     \"kernel\"   \n [6] \"df\"        \"bandwidth\" \"n.used\"    \"orig.n\"    \"series\"   \n[11] \"snames\"    \"method\"    \"taper\"     \"pad\"       \"detrend\"  \n[16] \"demean\"   \n\\end{verbatim}\n\\end{kframe}\n\\end{knitrout}\n\n\\mode<presentation>{\n\\vspace{-3mm}\n}\n\n\\begin{knitrout}\\small\n\\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\\color{fgcolor}\\begin{kframe}\n\\begin{alltt}\n\\hlkwd{plot}\\hlstd{(s}\\hlopt{$}\\hlstd{freq,s}\\hlopt{$}\\hlstd{spec[,}\\hlnum{2}\\hlstd{]}\\hlopt{/}\\hlstd{s}\\hlopt{$}\\hlstd{spec[,}\\hlnum{1}\\hlstd{],}\\hlkwc{type}\\hlstd{=}\\hlstr{\"l\"}\\hlstd{,}\\hlkwc{log}\\hlstd{=}\\hlstr{\"y\"}\\hlstd{,}\n  \\hlkwc{ylab}\\hlstd{=}\\hlstr{\"frequency ratio\"}\\hlstd{,} \\hlkwc{xlab}\\hlstd{=}\\hlstr{\"frequency\"}\\hlstd{,}\n  \\hlkwc{main}\\hlstd{=}\\hlstr{\"frequency response (red lines at 0.8 and 1.2)\"}\\hlstd{)}\n\\hlkwd{abline}\\hlstd{(}\\hlkwc{h}\\hlstd{=}\\hlkwd{c}\\hlstd{(}\\hlnum{0.8}\\hlstd{,}\\hlnum{1.2}\\hlstd{),}\\hlkwc{col}\\hlstd{=}\\hlstr{\"red\"}\\hlstd{)}\n\\end{alltt}\n\\end{kframe}\n\\end{knitrout}\n\n\n\n\\end{frame}\n\n\\begin{frame}[fragile]\n\n\\begin{knitrout}\\small\n\\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\\color{fgcolor}\n\n{\\centering \\includegraphics[width=10cm]{tmp/figure/s_transfer-1} \n\n}\n\n\n\\end{knitrout}\n\n\\vspace{-3mm}\n\n\\myquestion. What do you learn from this frequency response plot?\n\n\\answer{\\vspace{20mm}}{todo}\n\n\\end{frame}\n\n\\section{Loess smoothing}\n\n\\begin{frame}[fragile]\n\n\\frametitle{Estimating trend by Loess smoothing}\n\n\\bi\n\n\\item Loess is a \\myemph{Local linear regression} approach (perhaps an acronym for LOcal Estimation by Smoothing) also known as \\myemph{Lowess} (perhaps LOcallyWEighted Sum of Squares). \n\n\\item At each point in time, Loess computes a linear regression (a constant, linear or quadratic trend estimate) using only neighboring times. \n\n\\item We can imagine a moving window of points included in the regression.\n\n\\item \\code{loess} is an R implementation, with the fraction of points included in the moving window being scaled by the \\code{span} argument. \n\n\\item We can choose a value of the span that visually separates long term trend from business cycle.\n\n\\ei\n\n\\end{frame}\n\n\\begin{frame}[fragile]{A Loess smooth of unemployment}\n\n\\begin{knitrout}\\small\n\\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\\color{fgcolor}\\begin{kframe}\n\\begin{alltt}\n\\hlstd{u1_loess} \\hlkwb{<-} \\hlkwd{loess}\\hlstd{(u1}\\hlopt{~}\\hlstd{date,}\\hlkwc{span}\\hlstd{=}\\hlnum{0.5}\\hlstd{)}\n\\hlkwd{plot}\\hlstd{(date,u1,}\\hlkwc{type}\\hlstd{=}\\hlstr{\"l\"}\\hlstd{,}\\hlkwc{col}\\hlstd{=}\\hlstr{\"red\"}\\hlstd{)}\n\\hlkwd{lines}\\hlstd{(u1_loess}\\hlopt{$}\\hlstd{x,u1_loess}\\hlopt{$}\\hlstd{fitted,}\\hlkwc{type}\\hlstd{=}\\hlstr{\"l\"}\\hlstd{)}\n\\end{alltt}\n\\end{kframe}\n\\end{knitrout}\n\n\\begin{knitrout}\\small\n\\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\\color{fgcolor}\n\n{\\centering \\includegraphics[width=11cm]{tmp/figure/loess-1} \n\n}\n\n\n\\end{knitrout}\n\\end{frame}\n\n\\begin{frame}[fragile]\n\nNow, we compute the frequency response function for what we have done.\n\n\\mode<presentation>{\n\\vspace{-2mm}\n}\n\n\\begin{knitrout}\\small\n\\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\\color{fgcolor}\\begin{kframe}\n\\begin{alltt}\n\\hlstd{s2} \\hlkwb{<-} \\hlkwd{spectrum}\\hlstd{(}\\hlkwd{ts.union}\\hlstd{(}\n  \\hlstd{u1_ts,}\\hlkwd{ts}\\hlstd{(u1_loess}\\hlopt{$}\\hlstd{fitted,}\\hlkwc{start}\\hlstd{=}\\hlnum{1948}\\hlstd{,}\\hlkwc{frequency}\\hlstd{=}\\hlnum{12}\\hlstd{)),}\n  \\hlkwc{plot}\\hlstd{=}\\hlnum{FALSE}\\hlstd{)}\n\\hlkwd{plot}\\hlstd{(s2}\\hlopt{$}\\hlstd{freq,s2}\\hlopt{$}\\hlstd{spec[,}\\hlnum{2}\\hlstd{]}\\hlopt{/}\\hlstd{s}\\hlopt{$}\\hlstd{spec[,}\\hlnum{1}\\hlstd{],}\\hlkwc{type}\\hlstd{=}\\hlstr{\"l\"}\\hlstd{,}\\hlkwc{log}\\hlstd{=}\\hlstr{\"y\"}\\hlstd{,}\n  \\hlkwc{ylab}\\hlstd{=}\\hlstr{\"frequency ratio\"}\\hlstd{,} \\hlkwc{xlab}\\hlstd{=}\\hlstr{\"frequency\"}\\hlstd{,} \\hlkwc{xlim}\\hlstd{=}\\hlkwd{c}\\hlstd{(}\\hlnum{0}\\hlstd{,}\\hlnum{1.5}\\hlstd{),}\n  \\hlkwc{main}\\hlstd{=}\\hlstr{\"frequency response (red line at 1.0)\"}\\hlstd{)}\n\\hlkwd{abline}\\hlstd{(}\\hlkwc{h}\\hlstd{=}\\hlnum{1}\\hlstd{,}\\hlkwc{lty}\\hlstd{=}\\hlstr{\"dashed\"}\\hlstd{,}\\hlkwc{col}\\hlstd{=}\\hlstr{\"red\"}\\hlstd{)}\n\\end{alltt}\n\\end{kframe}\n\\end{knitrout}\n\n\n\\end{frame}\n\n\\begin{frame}[fragile]\n\n\\vspace{-2mm}\n\n\\begin{knitrout}\\small\n\\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\\color{fgcolor}\n\n{\\centering \\includegraphics[width=10cm]{tmp/figure/loess_transfer-1} \n\n}\n\n\n\\end{knitrout}\n\n\\myquestion. Describe the frequency domain behavior of this filter.\n\n\\answer{\\vspace{50mm}}{todo}\n\n\\end{frame}\n\n\\begin{frame}[fragile]\n\n\\frametitle{Extracting business cycles: A band pass filter}\n\n\\bi\n\n\\item For the unemployment data, high frequency variation might be considered ``noise'' and low frequency variation might be considered trend.\n\n\\item A band of mid-range frequencies might be considered to correspond to the business cycle.\n\n\\item We build a smoothing operation in the time domain to extract business cycles, and then look at its frequency response function.\n\\ei\n\n\\begin{knitrout}\\small\n\\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\\color{fgcolor}\\begin{kframe}\n\\begin{alltt}\n\\hlstd{u_low} \\hlkwb{<-} \\hlkwd{ts}\\hlstd{(}\\hlkwd{loess}\\hlstd{(u1}\\hlopt{~}\\hlstd{date,}\\hlkwc{span}\\hlstd{=}\\hlnum{0.5}\\hlstd{)}\\hlopt{$}\\hlstd{fitted,}\n  \\hlkwc{start}\\hlstd{=}\\hlnum{1948}\\hlstd{,}\\hlkwc{frequency}\\hlstd{=}\\hlnum{12}\\hlstd{)}\n\\hlstd{u_hi} \\hlkwb{<-} \\hlkwd{ts}\\hlstd{(u1} \\hlopt{-} \\hlkwd{loess}\\hlstd{(u1}\\hlopt{~}\\hlstd{date,}\\hlkwc{span}\\hlstd{=}\\hlnum{0.1}\\hlstd{)}\\hlopt{$}\\hlstd{fitted,}\n  \\hlkwc{start}\\hlstd{=}\\hlnum{1948}\\hlstd{,}\\hlkwc{frequency}\\hlstd{=}\\hlnum{12}\\hlstd{)}\n\\hlstd{u_cycles} \\hlkwb{<-} \\hlstd{u1} \\hlopt{-} \\hlstd{u_hi} \\hlopt{-} \\hlstd{u_low}\n\\hlkwd{plot}\\hlstd{(}\\hlkwd{ts.union}\\hlstd{(u1, u_low,u_hi,u_cycles),}\n  \\hlkwc{main}\\hlstd{=}\\hlstr{\"Decomposition of unemployment as trend + noise + cycles\"}\\hlstd{)}\n\\end{alltt}\n\\end{kframe}\n\\end{knitrout}\n\n\\vspace{10mm}\n\n\\end{frame}\n\n\n\\subsection{Business cycles in detrended economic data}\n\n\\begin{frame}[fragile]\n\n\\begin{knitrout}\\small\n\\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\\color{fgcolor}\n\n{\\centering \\includegraphics[width=11cm]{tmp/figure/cycles-1} \n\n}\n\n\n\\end{knitrout}\n\n\\end{frame}\n\n\\begin{frame}[fragile]\n\n\n\n\n\n\\begin{knitrout}\\small\n\\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\\color{fgcolor}\n\\begin{tabular}{l|r|r}\n\\hline\n  & low & hi\\\\\n\\hline\nfrequency range, region for ratio greater than 0.5 & 0.048 & 0.211\\\\\n\\hline\n\\end{tabular}\n\n\\end{knitrout}\n\n\\begin{knitrout}\\small\n\\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\\color{fgcolor}\n\n{\\centering \\includegraphics[width=10cm]{tmp/figure/show_range-1} \n\n}\n\n\n\\end{knitrout}\n\n\\myquestion. Describe the frequencies (and corresponding periods) that this decomposition identifies as business cycles. Note: units of frequency are omitted to give you an exercise!\n\n\\answer{\\vspace{15mm}}{todo}\n\n\\end{frame}\n\n\\begin{frame}[fragile]\n\n\\mode<presentation>{\n\\vspace{-2mm}\n}\n\nBelow is a smoothed periodogram for the raw unemployment data, plotted up to 0.7 cycles per year to focus on relevant frequencies.\n\n\\begin{knitrout}\\small\n\\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\\color{fgcolor}\n\n{\\centering \\includegraphics[width=9cm]{tmp/figure/zoomed_spectrum-1} \n\n}\n\n\n\\end{knitrout}\n\n\\vspace{-1mm}\n\n\\myquestion. Comment on the evidence for and against the concept of a business cycle in the above figure.\n\n\\answer{\\vspace{30mm}}{todo}\n\n\\end{frame}\n\n\\begin{frame}[fragile]\n\n\\frametitle{Common smoothers in R}\n\n\\bi\n\n\\item Above, we have used the \\myemph{local regression smoother} \\code{loess} but there are other similar options.\n\n\\item \\code{ksmooth} is a \\myemph{kernel smoother}. The default periodogram smoother in \\code{spectrum} is also a kernel smoother. See \\url{https://en.wikipedia.org/wiki/Kernel_smoother}\n\n\\item \\code{smooth.spline} is a \\myemph{spline smoother}.\n\\url{https://en.wikipedia.org/wiki/Smoothing_spline}\n\n\\item You can learn about alternative smoothers, and try them out if you like, but \\code{loess} is a good practical choice for many smoothing applications.\n\n\\ei\n\\end{frame}\n\n\\begin{frame}[fragile]\n\\frametitle{Bandwidth for a smoother}\n\\bi\n\\item All these smoothers have some concept of a \\myemph{bandwidth}, which is a measure of the size of the neighborhood of time points in which data affect the smoothed value at a particular time point. \n\n\\item The concept of bandwidth is most obvious for kernel smoothers, but exists for other smoothers.\n\n\\item We usually only interpret bandwidth up to a constant. For a particular smoothing algorithm and software implementation, you learn by experience to interpret the comparative value. Smaller bandwidth means less smoothing. \n\n\\item Typically, when writing reports, it makes sense to focus on the tuning parameter for the smoother in question, which is not the bandwidth unless you are doing kernel smoothing.\n\n\\ei\n\\end{frame}\n\n\\begin{frame}{Further reading} \n\n\\bi\n\n\\item Section~2.3 of \\citet{shumway17} discusses smoothing of time series, in the time domain.\n\n\\item Section~4.2 of \\citet{shumway17} presents a frequency response function for linear filters, related to this chapter but in a different context.\n\n\\ei\n\n\n\\end{frame}\n\n\n\\newcommand\\acknowledgments{\n\\begin{itemize}\n\\item   Compiled on {\\today} using \\Rlanguage version 4.1.2.\n\\item   \\parbox[t]{0.75\\textwidth}{Licensed under the \\link{http://creativecommons.org/licenses/by-nc/4.0/}{Creative Commons Attribution-NonCommercial license}.\n    Please share and remix non-commercially, mentioning its origin.}\n    \\parbox[c]{1.5cm}{\\includegraphics[height=12pt]{../cc-by-nc}}\n\\item We acknowledge \\link{https://ionides.github.io/531w22/acknowledge.html}{previous versions of this course}.\n\\end{itemize}\n}\n\n\\mode<presentation>{\n\\begin{frame}[allowframebreaks=0.8]{References and Acknowledgements}\n   \n\\bibliography{../bib531}\n\n\\vspace{3mm}\n\n\\acknowledgments\n\n\\end{frame}\n}\n\n\\mode<article>{\n\n{\\bf \\Large \\noindent Acknowledgments}\n\n\\acknowledgments\n\n  \\bibliography{../bib531}\n\n}\n\n\\end{document}\n", "meta": {"hexsha": "33c7bad34a66bd525bba9749d4d3eae04dcebaf9", "size": 20541, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "08/main.tex", "max_stars_repo_name": "ionides/531w22", "max_stars_repo_head_hexsha": "aed3c2187ab31938eec116d0d5b2345794c9c6da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-08T06:48:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T06:48:41.000Z", "max_issues_repo_path": "08/main.tex", "max_issues_repo_name": "ionides/531w22", "max_issues_repo_head_hexsha": "aed3c2187ab31938eec116d0d5b2345794c9c6da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "08/main.tex", "max_forks_repo_name": "ionides/531w22", "max_forks_repo_head_hexsha": "aed3c2187ab31938eec116d0d5b2345794c9c6da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-01-07T16:50:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T23:23:52.000Z", "avg_line_length": 30.4311111111, "max_line_length": 285, "alphanum_fraction": 0.7176378949, "num_tokens": 7139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.34050163185622123}}
{"text": "\\section{Discussion}\\label{sec:4}\nThis paper presents an \\oos\\ test statistic similar to \\poscw\\ that is\nasymptotically normal when comparing nested or non-nested models.\nNormality is achieved by estimating the alternative model using a\nfixed-length rolling window --- as do Clark and West --- but\nestimating the benchmark model with a recursive window.  Simulations\nindicate that the new statistic behaves similarly to Clark and West's\noriginal test when the \\dgp\\ is stable but can have much higher power\nwhen the \\dgp\\ has structural breaks. We also have presented an\nempirical study of the equity premium that demonstrates how to use\nthese results with several alternative models.\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: \"mixedwindow\"\n%%% TeX-command-extra-options: \"-shell-escape\"\n%%% End:\n", "meta": {"hexsha": "f0e72bc3ded5e40f7563a7495cdf5f13642deb25", "size": 809, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "S5-conclusion.tex", "max_stars_repo_name": "grayclhn-econ/mixedwindow", "max_stars_repo_head_hexsha": "3b25a5acad1da570bcd72806e6c32fbf9c54845d", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "S5-conclusion.tex", "max_issues_repo_name": "grayclhn-econ/mixedwindow", "max_issues_repo_head_hexsha": "3b25a5acad1da570bcd72806e6c32fbf9c54845d", "max_issues_repo_licenses": ["MIT", "Unlicense"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2015-01-07T16:44:10.000Z", "max_issues_repo_issues_event_max_datetime": "2016-02-08T21:21:38.000Z", "max_forks_repo_path": "S5-conclusion.tex", "max_forks_repo_name": "grayclhn-econ/mixedwindow", "max_forks_repo_head_hexsha": "3b25a5acad1da570bcd72806e6c32fbf9c54845d", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.9444444444, "max_line_length": 70, "alphanum_fraction": 0.7812113721, "num_tokens": 184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3403222720852129}}
{"text": "In this article we explore the connection between epistemic logic and game theory. In games of imperfect information, this connection arises naturally: The players need to reason about the knowledge of their teammates and opponents and epistemic logic seems like a natural choice.\n\nHowever, even in games of perfect information, there is also a connection to epistemic logic: In game theory, the standard assumption is that all players are rational and -- more crucially -- that this is \\emph{common knowledge} among all players. Is this assumption valid and can it be formalized? What are the implications of this assumption? Specifically, does backward induction actually follow? These are questions of epistemic nature and thus, they should be discussed using the terminology of epistemic logic.\n\n\\subsubsection*{Overview of this article}\n\nThe structure of this article is as follows: In \\secref{sec:imperfect-information}, we discuss games of imperfect information and in \\secref{sec:rationality} we consider the questions regarding common knowledge of rationality. Also, we define possible worlds models and epistemic logic as in \\cite{fagin1995a}.", "meta": {"hexsha": "68bea896aef8b42725979c1dd340fffbcf61fa0b", "size": 1153, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Report/introduction.tex", "max_stars_repo_name": "Andefar/LiarsDice", "max_stars_repo_head_hexsha": "f47123e80283a11500232d34102db2e894a4affb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Report/introduction.tex", "max_issues_repo_name": "Andefar/LiarsDice", "max_issues_repo_head_hexsha": "f47123e80283a11500232d34102db2e894a4affb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2016-11-24T13:56:28.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-01T17:21:52.000Z", "max_forks_repo_path": "Report/introduction.tex", "max_forks_repo_name": "Andefar/LiarsDice", "max_forks_repo_head_hexsha": "f47123e80283a11500232d34102db2e894a4affb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 164.7142857143, "max_line_length": 516, "alphanum_fraction": 0.81613183, "num_tokens": 239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3403222644268807}}
{"text": "\\documentclass[conference]{IEEEtran}\n\n\\usepackage{amsmath,amssymb}\n\\usepackage[all]{xy}\n\n\\newcommand{\\op}[1]{{\\textsc{#1}}}\n\\newcommand{\\DB}{\\mathbf{DB}}\n\\newcommand{\\DOC}{\\mathbf{DOC}}\n\\newcommand{\\attr}{\\mathrm{attr}}\n\\newcommand{\\textattr}{\\mathrm{attr}_\\mathrm{text}}\n\\newcommand{\\Val}{\\mathcal{V}}\n\\newcommand{\\dom}{\\mathrm{dom}}\n\\newcommand{\\Tables}{\\mathrm{tables}}\n\\newcommand{\\Words}{\\textsc{Words}}\n\\newcommand{\\todo}[1]{{\\em TODO: #1}}\n\n\n\\begin{document}\n\\title{Using Document Space For Relational Search}\n\\author{\n    \\IEEEauthorblockN{Richard Drake}\n    \\IEEEauthorblockA{\n        Faculty of Science\\\\\n        University of Ontario Inst of Technology\n    }\n    \\and\n    \\IEEEauthorblockN{Ken Pu}\n    \\IEEEauthorblockA{\n        Faculty of Science\\\\\n        University of Ontario Inst of Technology\n    }\n}\n\\maketitle\n\n\\begin{abstract}\nIn this paper, we present a family of methods and algorithms to efficiently integrate text indexing and keyword search from information retrieval to support search in relational databases.  We propose a bi-directional transformation that maps relational database instances to document collections.  The transformation is shown to be a homomorphism of keyword search.  Thus, any search of tuple networks by a keyword query can be efficiently executed as a search for documents, and vice versa.  By this construction, we demonstrate that indexing and search technologies developed for documents can naturally be reduced and integrated into relational database systems.\n\\end{abstract}\n\n\\section{Motivation}\n\nInformation retrieval has been an active and fruitful field of research since 1960's.  With\nseminal work by \\cite{jones72} and \\cite{salton75}, the\nIR community has laid the foundation of automatic text indexing and\nkeyword query processing of text documents.  The technology for document\nindexing continues to gain momentum with the growing presence of text data found\non the Web and in social media.  For instance, new techniques by\n\\cite{janu12} and \\cite{goyal13} improve on the traditional\nsimilarity measures by incorporating further (NLP) on the context of phrases and words.\n\nIn the last decade, there has been a tremendous interest from the database community to support keyword search queries for structured relational databases.  Systems such as {\\em Discover} \\cite{hris02}, {\\em DBxplorer} \\cite{agrawal2002dbxplorer} and {\\em BANKS} \\cite{bhalotia2002keyword} and many others \\cite{hristidis2003efficient,liu2006effective} model relational tuples as documents, and foreign key joins as links.  Thus, it's possible to derive IR-style scoring function for document similarity.  More recently, semantic information \\cite{zeng2013semantic}, schema and meta data \\cite{bergamaschi2011keyword} have been incorporated into the search algorithm.\n\nWe are motivated to explore the possibility of a unified framework to integrate and reuse indexing and search algorithms from IR system and databases.  In particular, our interest is to construct a pair of transformations:\n\n\\begin{eqnarray*}\nh &:& \\mathbf{DB} \\to \\mathbf{DOC} \\\\\ng &:& \\mathbf{DOC} \\to \\mathbf{DB}\n\\end{eqnarray*}\nwhere $\\mathbf{DB}$ is the domain of databases and $\\mathbf{DOC}$ is the domain of collections of documents.\n\nWe want to design $h$ and $g$ satisfying the following:\n\n\\begin{displaymath}\n\\xymatrix {\n    \\mathbf{DB} \\ar[r]^h\\ar[d]_{\\op{search}_\\mathbf{DB}} \n        & \\mathbf{DOC}\\ar[d]^{\\op{search}_\\mathbf{DOC}} \\\\\n    \\mathbf{DB} & \\mathbf{DOC}\\ar[l]^g\n}\n\\end{displaymath}\n\nwhere $\\op{search}_\\DB$ and $\\op{search}_\\DOC$ are the search functions for relational databases and documents respectively.\n\nPractical experiences have demonstrated that the state-of-the-art $\\op{search}_\\DOC$ has more performant implementations (\\cite{xapian,lucene}) compared to its relational database counter part.  Our interest is to construct efficient transformations $h$ and $g$ such that relational search $\\op{search}_\\DB$ can be efficiently implemented as a composition of $g\\circ \\op{search}_\\DOC\\circ h$, effectively taking advantage of the document search technology.\n\n\\section{Problem Definition}\n\nIn this section, we present the formal definition of relational databases and collections of documents.  We also formalize the notion of keyword search entity graphs and join networks of entity graphs in relational databases.\n\n\\subsection{Relational entities}\n\nA relational database consists of a collection of tables which are interconnected via joinable linkages.\n\nA table, $T$, has a number of attributes:\n\n$$ \\attr(T) $$\n\nA tuple in a table $r\\in T$ is defined as a mapping from attributes to values:\n\n$$ r:\\attr(T)\\to\\Val\\quad \\mbox{such that } r(\\alpha)\\in\\dom(\\alpha) $$\n\nGiven two tables $T$ and $T'$, a joinable linkage $L=\\left<A,B\\right>$, is defined as two lists of attributes of equal length.\n\n$$A = \\left<\\alpha_1, \\alpha_2, \\dots, \\alpha_n\\right>$$\n$$B = \\left<\\beta_1, \\beta_2, \\dots, \\beta_n\\right>$$\n\nsuch that $\\alpha_i\\in\\attr(T)$ and $\\beta_j\\in\\attr(T')$.  Furthermore,\n\n$$ \\forall\\ i\\leq n,\\quad \\dom(\\alpha_i) = \\dom(\\beta_i)$$\n\nThe set of all linkages are denoted as $\\mathcal{L}$.\n\nTwo tables $T$ and $T'$ are joinable by some link $L=\\left<A,B\\right>$, written $T\\sim_L T'$ if\n\n$$A\\subseteq\\attr(T)\\mbox{ and } B\\subseteq\\attr(T')$$\n\nTwo tuples $r\\in T$ and $r'\\in T'$ are joinable by some link $L=\\left<A,B\\right>$,\nwritten $r\\sim_L r'$ if\n\n$$ T\\sim_L T'\\quad\\mbox{and}\\quad r[A] = r[B] $$\n\n\\textbf{Entity groups: schema and instances}\n\nAn {entity group schema}, $G$, is characterized by a {\\em forest} of tables connected by joinable links.\n\n$$G = (V_G, E_G)$$\n\nwhere $V_G \\subseteq \\Tables(\\DB)$, and $E_G\\subseteq\\mathcal{L}$.\n\nA $G$-entity instance, $g$, is a forest of tuples \n\n$$\\{r_T : T\\in V_G\\} \\mbox{ where } r_T\\in T$$\n\nconnected by edges:\n\n$$\\left<r_T, r_{T'}\\right> \\mbox{ where } T\\sim T' \\mbox{ wrt } E_G$$\n\n{\\bf Networks of entity group instances}\n\nTwo entity group instances, $g$ and $g'$, are {\\em connected} if \n$$\\Tables(g)\\cap\\Tables(g')\\not=\\emptyset$$\nand for some $T\\in\\Tables(g)\\cap\\Tables(g')$, we have:\n\n$$\\exists\\alpha\\in\\attr(T), g_T(\\alpha) = g'_T(\\alpha)$$\n\n\\subsection{Keyword search queries}\n\nA {\\em keyword query} is a bag of words.\n\n$$ Q = \\{w_1, w_2, \\dots, w_n\\} $$\n\nA tuple $r\\in T$ in some table $T$ satisfies the keyword query if\n\n$$\\exists \\alpha\\in\\textattr(T),\\ \\Words(r(\\alpha))\\cap Q\\not=\\empty$$\n\n\\bibliographystyle{IEEEtran}\n\\bibliography{references}\n\\end{document}\n", "meta": {"hexsha": "e94d457a4182f37341c25e77ca647b399e999178", "size": 6467, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "iri2014/main.tex", "max_stars_repo_name": "rdrake/Molly", "max_stars_repo_head_hexsha": "f074ba926e6459d0074d980297d81dcad7f736d4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "iri2014/main.tex", "max_issues_repo_name": "rdrake/Molly", "max_issues_repo_head_hexsha": "f074ba926e6459d0074d980297d81dcad7f736d4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-13T19:40:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T19:40:08.000Z", "max_forks_repo_path": "iri2014/main.tex", "max_forks_repo_name": "rdrake/Molly", "max_forks_repo_head_hexsha": "f074ba926e6459d0074d980297d81dcad7f736d4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.9931972789, "max_line_length": 667, "alphanum_fraction": 0.7355806402, "num_tokens": 1801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3403222644268806}}
{"text": "%\n% $Id$\n%\n\\label{sec:rel}\nAll methods which include treatment of relativistic effects are ultimately\nbased on the Dirac equation, which has a four component wave function. The\nsolutions to the Dirac equation describe both positrons (the ``negative\nenergy'' states) and electrons (the ``positive energy'' states), as well as\nboth spin orientations, hence the four components. The wave function may be\nbroken down into two-component functions traditionally known as the large\nand small components; these may further be broken down into the spin\ncomponents. \n\nThe implementation of approximate all-electron relativistic methods in\nquantum chemical codes requires the removal of the negative energy states\nand the factoring out of the spin-free terms. Both of these may be achieved\nusing a transformation of the Dirac Hamiltonian known in general as a\nFoldy-Wouthuysen transformation. Unfortunately this transformation cannot be\nrepresented in closed form for a general potential, and must be\napproximated.  One popular approach is that originally formulated by Douglas\nand Kroll\\footnote{M.~Douglas and N.~M.~Kroll, Ann. Phys. (N.Y.)  {\\bf 82},\n89 (1974)} and developed by Hess\\footnote{B.A.~Hess, Phys.~Rev.~A~{\\bf 32},\n756 (1985); {\\bf 33}, 3742 (1986)}. This approach decouples the positive and\nnegative energy parts to second order in the external potential (and also\nfourth order in the fine structure constant, $\\alpha$). Other approaches include \nthe Zeroth Order Regular Approximation (ZORA)\\footnote{C.~Chang, M.~Pelissier, \nM.~Durand, Physica Scripta ~{\\bf 34}, 294 (1986); E.~van Lenthe, ~{\\it The ZORA Equation}, \ndoctoral thesis, Vrije Universiteit, Amsterdam (1996); S.~Faas, J.G.~Snijders, \nJ.H.~van Lenthe, E.~van Lenthe, and E.J.~Baerends, Chem.~Phys.~ Lett.~{\\bf 246}, 632 (1995).}\nand modification of the Dirac equation by Dyall\\footnote{K.~G.~Dyall,\nJ.~Chem.~Phys.~{\\bf 100}, 2118 (1994)}, and involves an exact FW\ntransformation on the atomic basis set level\\footnote{K.~G.~Dyall,\nJ.~Chem.~Phys.~{\\bf 106}, 9618 (1997); K.~G.~Dyall and T.~Enevoldsen,\nJ.~Chem.~Phys.~{\\bf 111}, 10000 (1999).}.\n\nSince these approximations only modify the integrals, they can in principle\nbe used at all levels of theory. At present the Douglas-Kroll and ZORA \nimplementations can be used at all levels of theory whereas \nDyall's approach is currently available at the Hartree-Fock level. \nThe derivatives have been implemented, allowing both methods to be used in \ngeometry optimizations and frequency calculations.\n\nThe \\verb+RELATIVISTIC+ directive provides input for the implemented relativistic \napproximations and is a compound directive that encloses additional directives \nspecific to the approximations:\n\\begin{verbatim}\n  RELATIVISTIC\n   [DOUGLAS-KROLL [<string (ON||OFF) default ON> \\\n                 <string (FPP||DKH||DKFULL||DK3||DK3FULL) default DKH>]  ||\n    ZORA [ (ON || OFF) default ON ] || \n    DYALL-MOD-DIRAC [ (ON || OFF) default ON ] \n                  [ (NESC1E || NESC2E) default NESC1E ] ]\n   [CLIGHT <real clight default 137.0359895>]\n  END\n\\end{verbatim}\n\nOnly one of the methods may be chosen at a time.  If both methods are found\nto be on in the input block, NWChem will stop and print an error message.\nThere is one general option for both methods, the definition of the speed \nof light in atomic units:\n\n\\begin{verbatim}\n  CLIGHT <real clight default 137.0359895>\n\\end{verbatim}\n\nThe following sections describe the optional sub-directives that\ncan be specified within the \\verb+RELATIVISTIC+ block.\n\n\\section{Douglas-Kroll approximation}\n\\label{sec:douglas-kroll}\n\nThe spin-free and spin-orbit one-electron Douglas-Kroll \napproximation have been implemented. The use of relativistic effects \nfrom this Douglas-Kroll approximation can be invoked by specifying:\n\n\\begin{verbatim}\n  DOUGLAS-KROLL [<string (ON||OFF) default ON> \\\n                 <string (FPP||DKH||DKFULL|DK3|DK3FULL) default DKH>]\n\\end{verbatim}\n\nThe \\verb+ON|OFF+ string is used to turn on or off the\nDouglas-Kroll approximation.  By default, if the \\verb+DOUGLAS-KROLL+\nkeyword is found, the approximation will be used in the calculation.\nIf the user wishes to calculate a non-relativistic quantity after turning\non Douglas-Kroll, the user will need to define a new \\verb+RELATIVISTIC+\nblock and turn the approximation \\verb+OFF+.  The user could also simply\nput a blank \\verb+RELATIVISTIC+ block in the input file and all options \nwill be turned off.\n\nThe \\verb+FPP+ is the approximation based on free-particle projection \noperators\\footnote{B.A.~Hess, Phys.~Rev.~A~{\\bf 32}, 756 (1985)} whereas the \n\\verb+DKH+ and \\verb+DKFULL+ approximations are based on external-field \nprojection operators\\footnote{B.A.~Hess, Phys.~Rev.~A~{\\bf 33}, 3742 (1986)}.\nThe latter two are considerably better approximations than the former. \\verb+DKH+ \nis the Douglas-Kroll-Hess approach and is the approach that is generally \nimplemented in quantum chemistry codes. \\verb+DKFULL+ includes certain \ncross-product integral terms ignored in the \\verb+DKH+ approach (see for example \nH\\\"{a}berlen and R\\\"{o}sch\\footnote{O.D.~H\\\"{a}berlen, N.~R\\\"{o}sch, \nChem.~Phys.~Lett.~{\\bf 199}, 491 (1992)}). The third-order Douglas-Kroll \napproximation has been implemented by T. Nakajima and K. Hirao\\footnote{T. Nakajima \nand K. Hirao, Chem.~Phys.~Lett.~{\\bf 329}, 5111 (2000); T. Nakajima and K. Hirao, \nJ.~Chem.~Phys.~{\\bf 113}, 7786 (2000)}. This approximation can be called using\n\\verb+DK3+ (DK3 without cross-product integral terms) or \\verb+DK3FULL+ (DK3 with\ncross-product integral terms).\n\nThe contracted basis sets used in the calculations should reflect the relativistic\neffects, i.e. one should use contracted basis sets which were generated using the \nDouglas-Kroll Hamiltonian. Basis sets that were contracted using the \nnon-relativistic (Sch\\\"{o}dinger) Hamiltonian WILL PRODUCE ERRONEOUS RESULTS for\nelements beyond the first row. See appendix \\ref{sec:knownbasis} for available\nbasis sets and their naming convention.\n\nNOTE: we suggest that spherical basis sets are used in the calculation. The use of \nhigh quality cartesian basis sets can lead to numerical inaccuracies.\n\nIn order to compute the integrals needed for the Douglas-Kroll approximation\nthe implementation makes use of a fitting basis set (see literature given\nabove for details). The current code will create this fitting basis set\nbased on the given {\\tt \"ao basis\"} by simply uncontracting that basis. This\nagain is what is commonly implemented in quantum chemistry codes that\ninclude the Douglas-Kroll method.  Additional flexibility is available to\nthe user by explicitly specifying a Douglas-Kroll fitting basis\nset. This basis set must be named {\\tt \"D-K basis\"} (see Chapter\n\\ref{sec:basis}).\n\n\\section{Zeroth Order regular approximation (ZORA)}\n\\label{sec:zora}\n\nThe spin-free and spin-orbit one-electron zeroth-order regular approximation (ZORA) \nhave been implemented. The use of relativistic effects with ZORA \ncan be invoked by specifying:\n\n\\begin{verbatim}\n  ZORA [<string (ON||OFF) default ON>\n\\end{verbatim}\n\nThe \\verb+ON|OFF+ string is used to turn on or off ZORA.  \nBy default, if the \\verb+ZORA+ keyword is found, the approximation \nwill be used in the calculation. If the user wishes to calculate \na non-relativistic quantity after turning on ZORA, the user \nwill need to define a new \\verb+RELATIVISTIC+ block and turn \nthe approximation \\verb+OFF+.  The user can also simply put \na blank \\verb+RELATIVISTIC+ block in the input file and all options \nwill be turned off.\n\n\\section{Dyall's Modified Dirac Hamitonian approximation}\n\\label{sec:dyall-mod-dir}\n\nThe approximate methods described in this section are all based on Dyall's\nmodified Dirac Hamiltonian. This Hamiltonian is entirely equivalent to the\noriginal Dirac Hamiltonian, and its solutions have the same properties.\nThe modification is achieved by a transformation on the small component,\nextracting out \\hbox{$\\sigma\\cdot{\\bf p}/2mc$}. This gives the modified small\ncomponent the same symmetry as the large component, and in fact it differs\nfrom the large component only at order $\\alpha^2$.  The advantage of the\nmodification is that the operators now resemble the operators of the\nBreit-Pauli Hamiltonian, and can be classified in a similar fashion into\nspin-free, spin-orbit and spin-spin terms. It is the spin-free terms which\nhave been implemented in NWChem, with a number of further approximations.\n\nThe first is that the negative energy states are removed by a normalized\nelimination of the small component (NESC), which is equivalent to an exact\nFoldy-Wouthuysen (EFW) transformation. The number of components in the wave\nfunction is thereby effectively reduced from 4 to 2. NESC on its own does\nnot provide any advantages, and in fact complicates things because the\ntransformation is energy-dependent. The second approximation therefore\nperforms the elimination on an atom-by-atom basis, which is equivalent to\nneglecting blocks which couple different atoms in the EFW transformation.\nThe advantage of this approximation is that all the energy dependence can be\nincluded in the contraction coefficients of the basis set.  The tests which\nhave been done show that this approximation gives results well within\nchemical accuracy. The third approximation neglects the commutator of the\nEFW transformation with the two-electron Coulomb interaction, so that the\nonly corrections that need to be made are in the one-electron integrals.\nThis is the equivalent of the Douglas-Kroll(-Hess) approximation as it is\nusually applied.\n\nThe use of these approximations can be invoked with the use of the\n\\verb+DYALL-MOD-DIRAC+ directive in the \\verb+RELATIVISTIC+ directive block.\nThe syntax is as follows.\n\n\\begin{verbatim}\n  DYALL-MOD-DIRAC [ (ON || OFF) default ON ] \n                  [ (NESC1E || NESC2E) default NESC1E ]\n\\end{verbatim}\n\nThe \\verb+ON|OFF+ string is used to turn on or off the\nDyall's modified Dirac approximation. By default, if the \\verb+DYALL-MOD-DIRAC+\nkeyword is found, the approximation will be used in the calculation.\nIf the user wishes to calculate a non-relativistic quantity after turning\non Dyall's modified Dirac, the user will need to define a new \n\\verb+RELATIVISTIC+\nblock and turn the approximation \\verb+OFF+.  The user could also simply\nput a blank \\verb+RELATIVISTIC+ block in the input file and all options \nwill be turned off.\n\nBoth one- and two-electron approximations are available\n\\verb+NESC1E || NESC2E+, and both have\nanalytic gradients. The one-electron approximation is the default.\nThe two-electron approximation specified by \\verb+NESC2E+ has some sub\noptions which are placed on the same logical line as the\n\\verb+DYALL-MOD-DIRAC+ directive, with the following syntax:\n\n\\begin{verbatim}\n  NESC2E [ (SS1CENT [ (ON || OFF) default ON ] || SSALL) default SSALL ]\n         [ (SSSS [ (ON || OFF) default ON ] || NOSSSS) default SSSS ]\n\\end{verbatim}\n\nThe first sub-option gives the capability to limit the two-electron\ncorrections to those in which the small components in any density must be on\nthe same center.  This reduces the $(LL|SS)$ contributions to at most\nthree-center integrals and the $(SS|SS)$ contributions to two centers. For a\ncase with only one relativistic atom this option is redundant. The second\ncontrols the inclusion of the $(SS|SS)$ integrals which are of order\n$\\alpha^4$. For light atoms they may safely be neglected, but for heavy\natoms they should be included. \n\nIn addition to the selection of this keyword in the \\verb+RELATIVISTIC+\ndirective block, it is necessary to supply basis sets in addition to the\n\\verb+ao basis+. For the one-electron approximation, three basis sets are\nneeded: the atomic FW basis set, the large component basis set and the small\ncomponent basis set. The atomic FW basis set should be included in the\n\\verb+ao basis+.\nThe large and small components should similarly be incorporated\nin basis sets named \\verb+large component+ and \\verb+small component+,\nrespectively. For the two-electron approximation, only two basis sets are\nneeded. These are the large component and the small component. The large component\nshould be included in the \\verb+ao basis+ and the small component\nis specified separately as \\verb+small component+, as for the one-electron\napproximation. This means that the two approximations can {\\it not} be run\ncorrectly without changing the \\verb+ao basis+, and it is up to the user to\nensure that the basis sets are correctly specified.\n\nThere is one further requirement in the specification of the basis sets. In\nthe \\verb+ao basis+, it is necessary to add the \\verb+rel+ keyword either to the\n\\verb+basis+ directive or the library tag line (See below for examples). \nThe former marks the basis\nfunctions specified by the tag as relativistic, the latter marks the whole\nbasis as relativistic. The marking is actually done at the unique shell\nlevel, so that it is possible not only to have relativistic and\nnonrelativistic atoms, it is also possible to have relativistic and\nnonrelativistic shells on a given atom. This would be useful, for example,\nfor diffuse functions or for high angular momentum correlating functions,\nwhere the influence of relativity was small. The marking of shells as\nrelativistic is necessary to set up a mapping between the ao basis and the\nlarge and/or small component basis sets. For the one-electron approximation\nthe large and small component basis sets MUST be of the same size and\nconstruction, i.e. differing only in the contraction coefficients.\n\nIt should also be noted that the relativistic code will NOT work with basis\nsets that contain sp shells, nor will it work with ECPs. Both of these are\ntested and flagged as an error.\n\nSome examples follow. The first example sets up the data for relativistic\ncalculations on water with the one-electron approximation and the\ntwo-electron approximation, using the library basis sets.\n\n\\begin{verbatim}\n  start h2o-dmd\n\n  geometry units bohr\n  symmetry c2v\n    O       0.000000000    0.000000000   -0.009000000\n    H       1.515260000    0.000000000   -1.058900000\n    H      -1.515260000    0.000000000   -1.058900000\n  end\n\n  basis \"fw\" rel\n    oxygen library cc-pvdz_pt_sf_fw\n    hydrogen library cc-pvdz_pt_sf_fw\n  end\n\n  basis \"large\"\n    oxygen library cc-pvdz_pt_sf_lc\n    hydrogen library cc-pvdz_pt_sf_lc\n  end\n\n  basis \"large2\" rel\n    oxygen library cc-pvdz_pt_sf_lc\n    hydrogen library cc-pvdz_pt_sf_lc\n  end\n\n  basis \"small\"\n    oxygen library cc-pvdz_pt_sf_sc\n    hydrogen library cc-pvdz_pt_sf_sc\n  end\n\n  set \"ao basis\" fw\n  set \"large component\" large\n  set \"small component\" small\n\n  relativistic\n    dyall-mod-dirac\n  end\n\n  task scf\n\n  set \"ao basis\" large2\n  unset \"large component\"\n  set \"small component\" small\n\n  relativistic\n    dyall-mod-dirac nesc2e\n  end\n\n  task scf\n\\end{verbatim}\n\nThe second example has oxygen as a relativistic atom and hydrogen nonrelativistic.\n\n\\begin{verbatim}\n  start h2o-dmd2\n\n  geometry units bohr\n  symmetry c2v\n    O       0.000000000    0.000000000   -0.009000000\n    H       1.515260000    0.000000000   -1.058900000\n    H      -1.515260000    0.000000000   -1.058900000\n  end\n\n  basis \"ao basis\"\n    oxygen library cc-pvdz_pt_sf_fw rel\n    hydrogen library cc-pvdz\n  end\n\n  basis \"large component\"\n    oxygen library cc-pvdz_pt_sf_lc\n  end\n\n  basis \"small component\"\n    oxygen library cc-pvdz_pt_sf_sc\n  end\n\n  relativistic\n    dyall-mod-dirac\n  end\n\n  task scf\n\\end{verbatim}\n", "meta": {"hexsha": "9cd0425a86036776084733381d7d08607fc208e6", "size": 15471, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/user/rel.tex", "max_stars_repo_name": "dinisAbranches/nwchem", "max_stars_repo_head_hexsha": "21cb07ff634475600ab687882652b823cad8c0cd", "max_stars_repo_licenses": ["ECL-2.0"], "max_stars_count": 317, "max_stars_repo_stars_event_min_datetime": "2017-11-20T21:29:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T11:48:24.000Z", "max_issues_repo_path": "doc/user/rel.tex", "max_issues_repo_name": "dinisAbranches/nwchem", "max_issues_repo_head_hexsha": "21cb07ff634475600ab687882652b823cad8c0cd", "max_issues_repo_licenses": ["ECL-2.0"], "max_issues_count": 356, "max_issues_repo_issues_event_min_datetime": "2017-12-05T01:38:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T02:28:21.000Z", "max_forks_repo_path": "doc/user/rel.tex", "max_forks_repo_name": "dinisAbranches/nwchem", "max_forks_repo_head_hexsha": "21cb07ff634475600ab687882652b823cad8c0cd", "max_forks_repo_licenses": ["ECL-2.0"], "max_forks_count": 135, "max_forks_repo_forks_event_min_datetime": "2017-11-19T18:36:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T02:28:49.000Z", "avg_line_length": 45.5029411765, "max_line_length": 93, "alphanum_fraction": 0.7675651218, "num_tokens": 4067, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3403222567685483}}
{"text": "\\documentclass[12pt]{article}\n\n\\usepackage[utf8]{inputenc}\n\n\n\\usepackage{amsmath, amssymb, amsfonts, amsthm, mathrsfs, bm}\n%\\usepackage{array, multirow}\b\n\\usepackage{color, float, graphicx, caption, subcaption}\n\\usepackage{comment}\n\n\\usepackage{mathtools}%for paired delimiters\n\n\\usepackage{hyperref}\n\n\\renewcommand{\\arraystretch}{1.0}\n\n\\captionsetup{font=small}\n\\usepackage{setspace}\n\\setstretch{1.0}\n%\\setlength\\topmargin{0in}\n%\\setlength\\textheight{8in}\n%\\setlength\\textwidth{5.5in}\n%\\setlength\\evensidemargin{.5in}\n%\\setlength\\oddsidemargin{.5in}\n\n\\setlength\\topmargin{-.45in}\n\\setlength\\textheight{8.5in}\n\\setlength\\textwidth{6in}\n\\setlength\\evensidemargin{.25in}\n\\setlength\\oddsidemargin{.25in}\n\n\n\\graphicspath{{InkscapePics/}}\n\n\\newcommand{\\executeiffilenewer}[3]{%\n \\ifnum\\pdfstrcmp{\\pdffilemoddate{#1}}%\n {\\pdffilemoddate{#2}}>0%\n {\\immediate\\write18{#3}}\\fi%\n}\n\\newcommand{\\includesvg}[1]{%\n \\executeiffilenewer{#1.svg}{#1.pdf}%\n {inkscape -z -D --file=#1.svg %\n --export-pdf=#1.pdf --export-latex}%\n \\input{#1.pdf_tex}%\n}\n\n\n\\DeclarePairedDelimiter\\ceil{\\lceil}{\\rceil}\n\n\n\\renewcommand{\\a}{\\alpha}\n\\renewcommand{\\b}{\\beta}\n\\renewcommand{\\d}{\\delta}\n\\newcommand{\\e}{\\varepsilon}\n\\newcommand{\\g}{\\gamma}\n\\renewcommand{\\k}{\\kappa}\n\\renewcommand{\\l}{\\lambda}\n\\newcommand{\\m}{\\mu}\n\\renewcommand{\\o}{\\omega}\n\\newcommand{\\p}{\\rho}\n\\newcommand{\\s}{\\sigma}\n\\renewcommand{\\t}{\\tau}\n\\renewcommand{\\th}{\\theta}\n\\newcommand{\\z}{\\zeta}\n\n\n\\newcommand{\\ba}{\\bm{a}}\n\\newcommand{\\bg}{\\bm{\\gamma}}\n\\newcommand{\\bp}{\\bm{p}}\n\\newcommand{\\bq}{\\bm{q}}\n\\newcommand{\\bmm}{\\bm{m}}\n\\newcommand{\\bmu}{\\bm{\\mu}}\n\\newcommand{\\bnu}{\\bm{\\nu}}\n\\newcommand{\\bw}{\\bm{w}}\n\\newcommand{\\bx}{\\bm{x}}\n\\newcommand{\\bpi}{\\bm{\\pi}}\n\\newcommand{\\bs}{\\bm{\\sigma}}\n\\newcommand{\\bS}{\\bm{\\Sigma}}\n\\newcommand{\\bth}{\\bm{\\theta}}\n\\newcommand{\\bu}{\\bm{u}}\n\\newcommand{\\bv}{\\bm{v}}\n\n\\newcommand{\\bA}{\\bm{A}}\n\\newcommand{\\bH}{\\bm{H}}\n\\newcommand{\\bM}{\\bm{M}}\n\\newcommand{\\bW}{\\bm{W}}\n\\newcommand{\\bX}{\\bm{X}}\n\n\\newcommand{\\rp}{{_{r}p}}\n\\newcommand{\\rD}{{_{r}\\D}}\n\\newcommand{\\sD}{{_{s}\\D}}\n\n\n\n\\newcommand{\\A}{\\mathcal{A}}\n\\newcommand{\\C}{\\mathcal{C}}\n\\newcommand{\\D}{\\Delta}\n\\newcommand{\\mD}{\\mathcal{D}}\n\\newcommand{\\E}{\\mathcal{E}}\n\\newcommand{\\F}{\\mathcal{F}}\n\\newcommand{\\G}{\\mathscr{G}}\n\\renewcommand{\\H}{\\mathcal{H}}\n\\newcommand{\\I}{\\mathcal{I}}\n\\newcommand{\\M}{\\mathcal{M}}\n\\renewcommand{\\O}{\\Omega}\n\\newcommand{\\Pt}{\\mathscr{P}}\n\\renewcommand{\\P}{\\mathcal{P}}\n\\newcommand{\\Q}{\\mathcal{Q}}\n\\newcommand{\\R}{\\mathbb{R}}\n\\renewcommand{\\S}{\\mathcal{S}}\n\\newcommand{\\T}{\\mathcal{T}}\n\\newcommand{\\Th}{\\Theta}\n\\newcommand{\\Y}{\\mathcal{Y}}\n\\newcommand{\\V}{\\mathscr{V}}\n\\newcommand{\\Z}{\\mathbb{Z}}\n\n\n\\newcommand{\\ol}{\\overline}\n\\newcommand{\\oll}[1]{\\overline{\\overline{ #1}}}\n\\newcommand{\\ul}{\\underline}\n\\newcommand{\\Ex}{\\mathbf{E}}\n\\renewcommand{\\Pr}{\\mathbf{P}}\n\\newcommand{\\td}{\\tilde}\n\\newcommand{\\tr}{\\triangleleft}\n\n\\newtheorem{lemma}{Lemma}\n\\newtheorem*{example}{Example}\n\\newtheorem{theorem}{Theorem}\n\\newtheorem{proposition}{Proposition}\n\\newtheorem*{definition}{Definition}\n\\newtheorem*{maxminrefinement}{Max-Min Threshold Refinement}\n\\newtheorem*{multimaxminrefinement}{Multi-Worker Max-Min Threshold Refinement}\n\\newtheorem*{refinement}{An Intuitive Credible Threats Refinement}\n\\newtheorem*{minrefinement}{Minimal Refinement}\n\\newtheorem{corollary}{Corollary}\n\\newtheorem{observation}{Observation}\n\\newtheorem{remark}{Remark}\n\\newtheorem{assumption}{Assumption}\n\\newtheorem*{efficiency}{Efficiency Wage Contract}\n\n\\DeclareMathOperator*{\\argmax}{arg\\,max}\n\\DeclareMathOperator*{\\argmin}{arg\\,min}\n\\DeclareMathOperator{\\sgn}{sgn}\n\n\n\n\\begin{document}\n\n\n\\begin{center}\n{\\Large Econ 780 \\hspace{0.5cm} HW Chapter 3}\\\\\n\\textbf{Minh Cao, Grant Smith, Ella Barnes, Alexander Erwin and Mark Coomes}\\\\ %You should put your name here\nDue:  %You should write the date here.\n\\end{center}\n\n\\vspace{0.2 cm}\n\n\n\\subsection*{Exercises for chapter 3}\n\n\n\\begin{enumerate}\n    \\item Recall the matrix $D$ from chapter 3. Introduce the matrix $\\ol{D}$: The first column is the date 0 price of the assets while the rest of the matrix is $D$. Assume as in the book $P(\\o_j) > 0$ for all $j$. Consider the following market:\n    \\begin{align*}\n    \\ol{D}=\n    \\left[\\begin{array}{llll}\n    1 & 2 & 2 & 3\\\\\n    1 & 0 & 3 & 3\n    \\end{array}\n    \\right],\n    \\end{align*}\n    As in the book, denote the two assets by $S^1$ and $S^2$. \n      \\begin{itemize}\n        \\item Is there a risk-free rate for this market?\n        \\begin{itemize}\n            \\item We found that the initial prices could be generated by $$(1/6-3/6 z_3, 1/3 - 3/3 z_3,z_3)$$\n            We require that all three be positive, which happens when $z_3$ is between 0 and $1/3$. This means the sum of the numbers is between $1/2$ and $1/3$ and $R$ must be between 1 and 2. \n        \\end{itemize}\n        \\item Fixing $S^1$ as numeraire, what are all the martingale measures?\n        \\begin{itemize}\n            \\item Not sure on this one.\n        \\end{itemize}\n        \\item Describe another asset $S^3$ such that the market $(S^1, S^2, S^3)$ is complete\n        \\emph{but not arbitrage free}.\n        \\begin{itemize}\n            \\item         An additional asset could be added to make the following matrix:\n            \\begin{align*}\n    \\ol{D}=\n    \\left[\\begin{array}{llll}\n    1 & 2 & 2 & 3\\\\\n    1 & 0 & 3 & 3 \\\\\n    1 & 0 & 0 & 1\n    \\end{array}\n    \\right]\n    \\end{align*}\n        \\end{itemize}\n\n        \\item Introduce the asset $X$ where $X_0 = 1$ and $X_1 = [3\\ 0\\ \\frac{8}{3}]$ and consider the market $(S^1, S^2, X)$. Fixing $S^1$ as numeraire, is there a martingale measure? If so what is it? If not, find an arbitrage portfolio.\n        \\begin{itemize}\n            \\item The new matrix is\n                        \\begin{align*}\n    D=\n    \\left[\\begin{array}{lll}\n    2 & 2 & 3\\\\\n     0 & 3 & 3 \\\\\n     3 & 0 & 8/3\n    \\end{array}\n    \\right]\n    \\end{align*}\n    Which is non-singular. Thus, any way to get $S_0$ from linear combinations of these columns is the only linear combination that works. We calculated that linear combination, and we got negative values for the first two vectors, which means there is arbitrage. We just need to find an arbitrage portfolio. Any holding vector whose components add to zero is free because the initial prices are all 1. So we need to find a holding vector whose components add to 1 and give positive or zero dot products with the columns of $D$ (with at least one being positive). We could do that with $h = (1,-.5,-.5)$ \n        \\end{itemize}\n        \n      \\end{itemize}\n      \\item Consider the following market\n\\begin{align*}\n\\ol{D} = \\begin{bmatrix}\n1\t& 2\t& 2\t& 2\\\\\n2\t& 8\t& 4\t& 2\n\\end{bmatrix}\n\\end{align*}\nAs in the book, denote the two assets by $S^1$ and $S^2$.\n\n\\begin{itemize}\n  \\item[a.] Create the normalized market by choosing $S^1$ as numeraire. Find all martingale measures. \n  \n  Express you answer in the following way: Let $q_1$ denote the probability of $\\o_1$ under an arbitrary martingale measure. Characterize the set of martingale measures by stating what values $q_1$ can take, and, for each such $q_1$, what are the corresponding probabilities for $\\o_2$ and $\\o_3$.\n  \n  For example, you could write: ``\\textit{the set of martingale measures is} $\\{(q_1, \\frac{1}{2} + q_1, \\frac{1}{2} - 2 q_1)\\ \\vert\\ q_1 \\in (0, \\frac{1}{4})\\}$.\" (This is the wrong answer of course).\n\n\\begin{itemize}\n    \\item the set of martingale measures is $\\{(q_1, 1-  3q_1, 2q_1)\\ \\vert\\ q_1 \\in (0, \\frac{1}{3})\\}$\n\\end{itemize}\n\n\\begin{comment}  \n  \\textit{Solution}: The normalized market is\n  \\begin{align*}\n  \\ol{Z} = \\begin{bmatrix}\n  1\t& 1\t& 1\t& 1\\\\\n  2\t& 4\t& 2\t& 1\n  \\end{bmatrix}\n  \\end{align*}\n  Let $(q_1, q_2, q_3)$ be a martingale measure. The conditions on the $q$'s are: $q_i \\in (0, 1)$ for all $i$, $1 = q_1 + q_2 + q_3$, and $2 = 4 q_1 + 2 q_2 + q_3$.\n  \n  This yields the condition $1 = 3 q_1 + q_2$ or, equivalently, $q_2 = 1 - 3 q_1$. Thus, the set of martingale measures is $\\{(q_1, 1 - 3 q_1, 2 q_1)\\ \\vert\\ q_1 \\in (0, \\frac{1}{3})\\}$.\n\\end{comment}\n  \n  \\item[b.] True of False. If we choose $S^2$ instead of $S^1$ as numeraire, we still generate the same set of martingale measures. (No need to show work.)\n  \\begin{itemize}\n      \\item True. It's just scaling the vectors, so our linear combination numbers would be different, but we scale those anyway to make the probability measure. This means the answer to this problem would be the same if we didn't scale at all or choose a numeraire.\n  \\end{itemize}\n  \n\\begin{comment}\n  \\textit{Solution}: False. The normalized market with $S^2$ as numeraire is\n  \\begin{align*}\n  \\ol{Z} = \\begin{bmatrix}\n  \\frac{1}{2}\t& \\frac{1}{4}\t& \\frac{1}{2}\t& 1\\\\\n  1\t\t\t& 1\t\t\t& 1\t\t\t& 1\n  \\end{bmatrix}\n  \\end{align*}\n  The probability $(\\frac{1}{4}, \\frac{1}{4}, \\frac{1}{2})$ is a martingale measure when $S^1$ is numeraire, but not when $S^2$ is numeraire.\n\\end{comment}\n\n  \\item[c.] A put option $PutK$ on $S^2$ with strike price $K$ maturing at date 1 is a contingent claim with date 1 payoff $PutK_1 = \\max\\{K - S^2, 0\\}$. What is $Put5_1(\\o_i)$ for $i = 1, 2, 3$?\n  \\begin{itemize}\n      \\item $Put5_1(\\o_i)=(0,1,3)$\n  \\end{itemize}\n\n\\begin{comment}  \n  \\textit{Solution}: $Put5_1 = \\begin{bmatrix} 0 & 1 & 3 \\end{bmatrix}$.\n\\end{comment}\n  \n  \\item[d.] Suppose the date 0 price of $Put5$ is $Put5_0 = \\frac{7}{8}$. Is the market $(S^1, S^2, Put5)$ arbitrage free?\n  \\begin{itemize}\n      \\item i THINK THERE IS SOMETHING WRONG WITH THIS ANSWER!!! \n      \\item No it is not. To prove this, we try to create $7/8$ with the dot product of our martingale measures above and $(0,1,3)$.  This gives us $7/8 = 1+3q_1$, but $q_1$ must be positive, so we have a contradiction.\n  \\end{itemize}\n\n\\begin{comment}  \n  \\textit{Solution}: To show $(S^1, S^2, Put5)$ is arbitrage free amounts to finding a martingale measure $Q$ of the normalized market $(1, S^2/S^1)$ with $S^1$ as numeraire such that, in addition, $\\frac{7}{8} = \\frac{1}{2} \\Ex^Q Put5_1$.\n  \n  The above equation plus the characterization of martingale measures for the normalized market $(1, S^2/S^1)$ from part (a) implies $\\frac{7}{4} = 1 \\cdot (1 - 3q_1) + 3 \\cdot (2 q_1)$, which yields $q_1 = \\frac{1}{4}$ and a probability $(\\frac{1}{4}, \\frac{1}{4}, \\frac{1}{2})$. Thus, $(S^1, S^2, Put5)$ is arbitrage free because $(\\frac{1}{4}, \\frac{1}{4}, \\frac{1}{2})$ is the unique martingale measure of the corresponding normalized market $(1, S^2/S^1, Put5/S^1)$ with $S^1$ as numeraire.\n\\end{comment}\n  \n  \n  \\item[e.] Continuing to assume the date 0 price of $Put5$ is $\\frac{7}{8}$. What is the arbitrage free date 0 price of $Put4$?\n  \\begin{itemize}\n      \\item The replicating holding vector is $(-4/3,1/3,4/3)$, and $hS_0$ is 0.5.\n  \\end{itemize}\n \n\\begin{comment} \n  \\textit{Solution}: The arbitrage free date 0 price of $Put4$ is $\\frac{1}{2} \\Ex^{(\\frac{1}{4}, \\frac{1}{4}, \\frac{1}{2})} Put4_1 = \\frac{1}{2} (\\frac{1}{2} \\cdot 2) = \\frac{1}{2}$.\n\\end{comment}\n\\end{itemize}\n  \\item Exercise 3.2.\n  \\begin{itemize}\n      \\item If $X$ is replicable, then:\n      $$\\exists h; hS_1 = X$$\n      \\item Now, using the definition of the value of a portfolio:\n      $$V_0^h = hS_0$$\n      \\item If there is no arbitrage, then there is a column vector, $z$ such that $S_0$ can be formed by $z$'s scaling of $S_1$'s columns. Thus,\n      $$\\exists z; S_0 = S_1z$$\n      \\item We can use this equation with the second bullet to get:\n      $$V_0^h = hS_0 = hS_1z$$\n      \\item If we want to turn z into a vector that scales to 1 (to make it a probability measure), we would want to divide its components by the sum of all the components, i.e. to normalize it. So to do this, we can multiply and divide by the sum, and we can call the new normalized z, q:\n      $$V_0^h = hS_0 = hS_1z \\frac{\\Sigma z_i}{\\Sigma z_i} = \\Sigma z_i * hS_1q $$\n      \\item But we know that $\\Sigma z_i$ has a name, and it is $\\beta$, which is also $1/1+R$. Thus,\n      $$V_0^h = hS_0 = hS_1z \\frac{\\Sigma z_i}{\\Sigma z_i} = \\Sigma z_i * hS_1q =  \\frac{1}{1+R}hS_1q$$\n      \\item Now we use our existence in the very first step, which is our replicating portfolio.  Thus, we get (and removing the intermediate steps):\n      $$V_0^h =  \\frac{1}{1+R}hS_1q = \\frac{1}{1+R}Xq $$\n      \\item And lastly, we say that $Xq$ is the expectation of $X$ under $S$:\n      $$V_0^h = \\frac{1}{1+R}Xq = \\frac{1}{1+R}\\mathbb{E}^Q[X]$$\n  \\end{itemize}\n  \\item Exercise 3.3.\n  \\begin{itemize}\n      \\item We want to prove that the arbitrage free price of an claim $X$ is given by:\n      $$\\Pi (0,X) = \\mathbb{E}^P[\\Lambda (\\omega) X(\\omega)]$$\n      \\item We start with the definition of $\\Lambda (\\omega)$:\n      $$\\Lambda (\\omega) = \\frac{1}{1+R} L(\\omega) = \\frac{1}{1+R} \\frac{q_i}{p_i}$$\n      \\item We now substitute this into the first equation:\n            $$\\Pi (0,X) = \\mathbb{E}^P[\\frac{1}{1+R} \\frac{q_i}{p_i} X(\\omega)] = \\frac{1}{1+R}\\mathbb{E}^P[ \\frac{q_i}{p_i} X(\\omega)]$$\n        \\item We now expand the expectation:\n        $$\\Pi (0,X)  = \\mathbb{E}^P[\\Lambda (\\omega) X(\\omega)] = \\frac{1}{1+R}\\mathbb{E}^Q [X] $$\n        Which was our goal.\n  \\end{itemize}\n\n\\end{enumerate}\n\n\n\\end{document}", "meta": {"hexsha": "5c13ad85337f9a80d33776d5c83004df48f9bced", "size": 13157, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "mainDelMe.tex", "max_stars_repo_name": "GSmithApps/ArbitrageTheory", "max_stars_repo_head_hexsha": "99f40e4315a0bc49243e2c4aaeb209fbdbb41079", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mainDelMe.tex", "max_issues_repo_name": "GSmithApps/ArbitrageTheory", "max_issues_repo_head_hexsha": "99f40e4315a0bc49243e2c4aaeb209fbdbb41079", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mainDelMe.tex", "max_forks_repo_name": "GSmithApps/ArbitrageTheory", "max_forks_repo_head_hexsha": "99f40e4315a0bc49243e2c4aaeb209fbdbb41079", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.990881459, "max_line_length": 604, "alphanum_fraction": 0.6494641636, "num_tokens": 4814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.3403117782996634}}
{"text": "\\subsection{Related Work}\nWe now review several related works that use secure computation techniques. With respect to functionality the closest related work is that of Blanton and Aguiar\\cite{ASIACCS:BlaAgu12} which describes a relatively complete set of protocols for performing intersections, unions, set difference, etc. and the corresponding SQL-like operations. Moreover, these operations are composable in that the inputs and outputs are secret shared between the parties. At the core of their technique is the use of a generic MPC protocol and an oblivious sorting algorithm that merges the two sets. This is followed by a linear pass over the sorted data where a relation is performed on adjacent items. Their technique has the advantage of being very general and flexible. However, the proposed sorting algorithm has complexity $O(n \\log^2 n)$ and is not constant round\\footnote{It is not constant round when the underlying MPC protocol is not constant round which is typically required for high throughput.}. \n\\iffullversion\nAs a result, the implementation from 2011 performed poorly by current standards, intersecting $2^{10}$ items in 12 seconds. The modern protocol \\cite{CCS:KKRT16} which is \\emph{not composable} can perform intersections of $2^{20}$ items in 4 seconds. While this difference of three orders of magnitude would narrow if reimplemented using modern techniques, the gap would remain large.\n\\else\nThis results in poor concrete performance as shown in \\sectionref{sec:eval}.\n\\fi\n\n\n\\iffullversion\n% Private Set Intersection:Are Garbled Circuits Better than Custom Protocols? \n%     https://ssltest.cs.umd.edu/~jkatz/papers/psi.pdf\n%\\item  \nHuang, Evans and Katz\\cite{HEK12} also described a set intersection protocol based on sorting. Unlike \\cite{ASIACCS:BlaAgu12}, this work considers the two party setting where each party holds a set in the clear.\nThis requirement prevents the protocol from being composable but allows the complexity to be reduced to $O(n\\log n)$. The key idea is that each party locally sorts their set followed by merging the sets within MPC. The protocol can then perform a single pass over the sorted data to construct the intersection. While this results in performance improvements the overall protocol requires  $O(n\\log n)$ operations and is not composable.\n\\fi\n\n\\iffullversion\n% (KS06) Privacy-Preserving Set Operations\n%     https://www.cs.cmu.edu/~leak/papers/set-tech-full.pdf\n% (MF06) Efficient Polynomial Operations in the Shared-Coefficients Setting \n%     https://pdfs.semanticscholar.org/80ca/9f56cffce534e047d049884736ff16204958.pdf\n%\\item \nAnother line of work was begun by Kissner and Song\\cite{KS06} and improved on by \\cite{MF06}. Their approach is based on the observation that set intersection and multi-set union have a correspondence to operations on polynomials. A set $S$ can be encoded as the polynomial $\\hat S(x)= \\prod_{s\\in S}(x-s)\\in \\mathbb{F}[x]$. That is, the polynomial $\\hat S(x)$ has a root at all $s\\in S$. Given two such polynomials, $\\hat S(x), \\hat T(x)$, the polynomial encoding the intersection is $\\hat S(x)+\\hat T(x)$ with overwhelming probability given a sufficiently large field $\\mathbb{F}$.\n\nMulti-set union can similarly be performed by multiplying the two polynomials together. Unlike with normal union, if an item $y$ is contained in $S$ and $T$ then $\\hat S(x)\\hat T(x)$ will contain two roots at $y$ which is often not the desired functionality. This general idea can be transformed into a secure multi-party protocol using oblivious polynomial evaluation\\cite{NP99} along with randomizing the result polynomial. The original computational overhead was $O(n^2)$ which can be reduced to the cost of polynomial interpolation $O(n\\log n)$ using techniques from \\cite{MF06}. The communication complexity is linear. In addition, this scheme assumes an ideal functionality to generate a shared Paillier key pair. We are unaware of any efficient protocol to realize this functionality except for \\cite{RSA:HMRT12} in the two party setting.\n\nThis general approach is also composable. However, due to randomization that is performed the degree of the polynomial after each operation doubles. This limits the practical ability of the protocol to compose more than a few operations. Moreover, it is not clear how this protocol can be extended to support SQL-like queries where elements are key-value tuples. This general approach is also composable but incurs a 2 times overhead for each successive operations and cannot be extended to SQL-like queries. \n\\fi\n\n\n\\iffullversion\n% C. Hazay and K. Nissim. Efficient set operations in the presence of malicious adversaries. In PKC, 2010.\n%   http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.454.1521&rep=rep1&type=pdf\n%\\item \nHazay and Nissim\\cite{HN12} introduce a pair of protocols computing set intersection and union which are also based on oblivious polynomial evaluation where the roots of the polynomial encode a set. However, these protocols are restricted to the two party case and are not composable. The non-composability comes from the fact that only one party constructs a polynomial $\\hat S(x)$ encoding their set $S$ while the other party obliviously evaluates it on each element in their set. The result of these evaluations are compared with zero\\footnote{The real protocol is slightly more complicated than this.}. These protocols have linear overhead and can achieve security in the malicious setting.\n\\fi\n\n%\\item \nPinkas, Schneider and Zohner \\cite{usenix:PSZ14} introduced a paradigm for set intersection that combines a hash table technique known as cuckoo hashing with a randomized encoding technique using oblivious transfer. Due to the hashing technique, the problem is reduced to comparing a single item $x$ to a small set $\\{y_1,...,y_m\\}$. Oblivious transfer is then used to interactively compute the randomized encoding $\\llbracket x\\rrbracket$ while the other party locally computes the encodings $\\{\\llbracket y_1\\rrbracket,...,\\llbracket y_m\\rrbracket \\}$. A plaintext intersection can then be perform directly on these encodings. With the use of several optimization\\cite{USENIX:PSSZ15,PSZ16,CCS:KKRT16,OOS17} this paradigm is extremely efficient and can perform a set intersection using $O(n)$ calls to a random oracle and $O(n)$ communication. These protocols are not composable.\n\\iffullversion\nMore recently this approach has also been extended to the malicious setting \\cite{CCS:RinRos17} and separately to have sublinear communication when one set is much larger than the other\\cite{CLR17} .\n\\fi\n\n% https://eprint.iacr.org/2011/429.pdf\n%\\item Laur, Willemson and Zhang\\cite{LWZ11} \\todo{....}\n\n% https://eprint.iacr.org/2013/203.pdf\n%\\item\nLaur, Talvista and Willemson\\cite{LTW13} present techniques in the honest majority setting for composable joins, unions and  many other operations at the expense of information leakage. Consider two parties each with a sets $X,Y$. The parties first generate secret shares of the sets and then use a generic MPC protocol to apply a pseudorandom function (PRF) $F$ to the shared sets to compute $X' = \\{F_k(x) \\mid x\\in X\\}, Y'=\\{F_k(y) \\mid y\\in Y\\}$ where the key $k$ is uniformly sampled by the MPC protocol (i.e. neither party knows $k$). $X'$ and $Y'$ are then revealed to both parties who use this information to infer the intersection, union and many other SQL-like operations. This basic approach dates back to the first PSI protocols \\cite{Mea86,HFH99} where the (oblivious) PRF was implemented using a special purpose Diffie-Hellman protocol. \\cite{LTW13} extended this paradigm to allow the input sets to be secret shared as opposed to being known in the clear.\n\nThe primary limitation of this approach is that all operations require all parties to know $X'$ and $Y'$. This prevents the protocol from being composable without significant information leakage. In particular, the cardinality of $X'\\cap Y'$ and the result of the \\texttt{where} clause for each row is revealed. This is of particular concern when several dataset are being combined. Learning the size of the intersection or the union can represent significant information. For instance, in the threat log application the union of many sets are taken. Each of these unions would reveal how many unique logs the new set has. Alternatively, taking the join between a set of hospital patients and a set of HIV positive patients would reveal how many have HIV. When combined with other information it could lead to the ability to identify some or all of these patients. Beyond this, the provided three party implementation achieved relatively poor performance. A join between two tables of a million records is estimated to require one hour on their three benchmark machines\\cite{LTW13}. Looking forward, our protocol can perform a similar join operation in 4 seconds while preventing all information leakage. \n\n\n%\\end{itemize}", "meta": {"hexsha": "1e5e52f5a5cbd4761b66a05356a881e45ac03f4a", "size": 8920, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/related.tex", "max_stars_repo_name": "vincehong/aby3", "max_stars_repo_head_hexsha": "1a5277b37249545e967fc58a9235666a2453c104", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-04T15:30:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-04T15:30:51.000Z", "max_issues_repo_path": "tex/related.tex", "max_issues_repo_name": "vincehong/aby3", "max_issues_repo_head_hexsha": "1a5277b37249545e967fc58a9235666a2453c104", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/related.tex", "max_forks_repo_name": "vincehong/aby3", "max_forks_repo_head_hexsha": "1a5277b37249545e967fc58a9235666a2453c104", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 162.1818181818, "max_line_length": 1205, "alphanum_fraction": 0.7926008969, "num_tokens": 2058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.34031177101026294}}
{"text": "Implements the \\emph{virtual substitution} method for a conjunction of constraints as described in \\cite{Article_Corzilius_FCT2011}. This module supports incremental calls, efficient backtracking and infeasible subset generation. Note, that the infeasible subsets are often very small but not necessarily minimal. The implemented approach is not complete, as it maybe cannot decide the satisfiability of a conjunction containing a constraint, which involves a variable with degree $3$ or more. Note, that even if no constraint of such form occurs in the received formula, this module might not be able to determine the consistency of its received formula, as it could create constraints of this form in its solving process. Nevertheless, the implemented approach is efficient compared to other approaches for non-linear real arithmetic conjunctions, and therefore well-suited to be used for solving conjunctions of non-linear real arithmetic constraints before complete approaches have their try. In combination with a backend, this module tries to solve the given problem and calls the backend on problems with less variables.\n\n\\paragraph{Efficiency} The worst case complexity of this approach is exponential in the number of real arithmetic variables occurring in the conjunction to solve. It performs especially good on almost linear instances and slightly prefers problems only containing constraints with the relation symbols $\\leq$, $\\geq$ and $=$. It is often the case, that even if the conjunction to solve contains many not suited constraints, this module can determine the consistency on the basis of a well suited subset of the constraints in this conjunction.", "meta": {"hexsha": "f12a09578b05448630bb24407b001240476d5bbd", "size": 1671, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/smtrat-modules/VSModule/VSModule.tex", "max_stars_repo_name": "minemebarsha/smtrat", "max_stars_repo_head_hexsha": "eaada50cdf9bbfe4dd4f6a54776387484c37b0f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/smtrat-modules/VSModule/VSModule.tex", "max_issues_repo_name": "minemebarsha/smtrat", "max_issues_repo_head_hexsha": "eaada50cdf9bbfe4dd4f6a54776387484c37b0f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/smtrat-modules/VSModule/VSModule.tex", "max_forks_repo_name": "minemebarsha/smtrat", "max_forks_repo_head_hexsha": "eaada50cdf9bbfe4dd4f6a54776387484c37b0f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 557.0, "max_line_length": 1127, "alphanum_fraction": 0.8252543387, "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.3403117710102629}}
{"text": "\\documentclass[acmtog]{acmart}\n\\usepackage{graphicx}\n\\usepackage{subfigure}\n\\usepackage{natbib}\n\\usepackage{listings}\n\\usepackage{bm}\n\n\\definecolor{blve}{rgb}{0.3372549 , 0.61176471, 0.83921569}\n\\definecolor{gr33n}{rgb}{0.29019608, 0.7372549, 0.64705882}\n\\makeatletter\n\\lst@InstallKeywords k{class}{classstyle}\\slshape{classstyle}{}ld\n\\makeatother\n\\lstset{language=C++,\n\tbasicstyle=\\ttfamily,\n\tkeywordstyle=\\color{blve}\\ttfamily,\n\tstringstyle=\\color{red}\\ttfamily,\n\tcommentstyle=\\color{magenta}\\ttfamily,\n\tmorecomment=[l][\\color{magenta}]{\\#},\n\tclassstyle = \\bfseries\\color{gr33n}, \n\tbreaklines=true, \n\ttabsize=2\n}\n\\lstset{basicstyle=\\ttfamily}\n\n% Title portion\n\\title{Assignment 4:\\\\ {Global Illumination}}\n\n\\author{Name:\\quad Yang Hongdi  \\\\ student number:\\ 2019533234\n\\\\email:\\quad yanghd@shanghaitech.edu.cn}\n\n% Document starts\n\\begin{document}\n\\maketitle\n\n\\vspace*{2 ex}\n\n\\section{Introduction}\nIn this project, ray tracing with direct and indirect lighting is performed using Monte-Carlo integration. BVH-tree is used for acceleration.\n\\section{Implementation Details}\n\\subsection{Acceleration : BVH}\n\tIn this project, to accelerate ray-triangle intersection, BVH is used. When building BVH, SAH is used for best space division.\\\\\n\tFirst, we sort the triangles by the coordinate of its center, then we save the result of all possible space division by the triangles. Then we compute the time cost of each space division\n\tby using the formula $$c(A,B) = t_{trav} + p_A\\sum_{i=1}^{N_A}t_{isect}(ai) + p_B\\sum_{i=1}^{N_B}t_{isect}(b_i)$$\n\twhere we set $p_A,p_B$ equal to the surface area of the AABB, $t_isect = 1, t_{trav} = 0$, and we choose the space division with the minimum time cost as the \n\tbest space division. We repeat this for all three axis and then choose the best axis to split the space.\\\\\n\tNow we get the best spcae division, we store the left AABB and the right AABB with their triangles, then we continue to split the space recursively.\n\tUntil we just have only a few triangles or enough recursion depth, the we store the node as leaf node and store the triangles.\n\t\\begin{lstlisting}\n\t\t// recursively build left and right\n    leftChild = new KdTreeNode(leftTriangles, leftSpace, depth + 1);\n    rightChild = new KdTreeNode(rightTriangles, rightSpace, depth + 1);\n\t\\end{lstlisting} \n\tFor intersection test, we just first check whether the ray hit the bouding box, if it does not, end checking directly and return false.\n\t\\begin{lstlisting}\n\t\tif (!this->box.rayIntersection(ray, tIn, tOut)) return false; // not intersect with bounding box, return false directly.\n\t\\end{lstlisting}\n\tIf it hits the bouding box, we then recursively check whether it hits the left and right child bouding box. When the hit the light hit the leaf node, we just\n\tviolently check if it hits the triangles inside the bouding box. Finally, we return true with the nearest triangle that has been hit.\n\\subsection{Path tracing with Monte-Carlo integration}\nIn this project, path tracing with Monte-Carlo integration is performed.\n\\subsubsection{Ideal Diffusion BRDF}\n\t\\quad For ideal diffusion BRDF, we use cos-weighted sampling. We first sample uniformly on a disk.\n\t\\begin{lstlisting}\n\t\tauto random_samples = unif(0.0, 1.0, 2);\n\n\t//sampling on a disk\n\tFloat x1 = random_samples[0];\n\tFloat y1 = random_samples[1];\n\t\\end{lstlisting}\n\tThen we transform (x,y) to $(r,\\theta_1)$, $$r = \\sqrt{x_1}, \\theta_1 = 2\\pi y_1 $$\n\tthen we project it onto the unit hemisphere. we need to transform $(r, \\theta_1)$ to $(\\theta, \\phi)$(Note: $\\theta$ is different from $\\theta_1$)\n\t$$\\sin\\theta = r = \\sqrt{x_1}, \\phi = \\theta_1 = 2\\pi y_1 $$\n\tthen we can compute $$ x = \\sin\\theta\\cos\\phi $$$$ y = \\sin\\theta\\sin\\phi $$$$ z = \\cos\\theta$$\n\tLast, we convert it from local coordinate to world coordinate using the normal.\n\t\\begin{lstlisting}\n\t\tvec3 rotation_axis = vec3(0,0,1).cross(interact.normal);\n\tEigen::AngleAxisf rotationVector(theta, rotation_axis);\n\tEigen::Matrix3f rotation_matrix = rotationVector.toRotationMatrix();\n\tinteract.wi = -(rotation_matrix * tmp_wi).normalized(); // from (0,0,1) system to world coordinate\n\t\\end{lstlisting}\n\tThen we get the sampled incoming ray. And the pdf equal to $\\frac{cos\\theta}{\\pi}$\n\\subsubsection{Ideal Specular BRDF}\n\t\\quad For Ideal Specular BRDF, it is quite easy. We simply sample the reflect light, which should have a pdf of 1.\n\tThe reflect direction can be computed by $$w_i = 2(w_o \\cdot n)n - w_o$$\n\\subsubsection{Ideal Transmission BRDF}\n\t\\quad For Ideal Transmission BRDF, similar as Ideal Specular, we sample the refraction light, which also have a pdf of 1.\n\tWe use $$w_i = \\frac{\\eta_1}{\\eta_2}w_o + (\\frac{\\eta_1}{\\eta_2}\\cos \\theta_i - \\sqrt{1 - \\sin^2 \\theta_t})n$$\n\tIf we find that $\\cos \\theta_i < 0$, that means the ray is inside the object, we will then let $\\cos \\theta_{i_1} = -\\cos \\theta_{i}, n_1 = -n, \\frac{\\eta_{1_1}}{\\eta_{2_1}} = \\frac{\\eta_2}{\\eta_1}$ to compute the next ray.\n\\subsubsection{Glossy Specular}\n\t\\quad For Glossy Specular, Disney principle BRDF is choosed to simulate Glossy surface BRDF. Multiple importance sampling is used.\n\tFirst, we calculate all angles as the graph shows.\n\t\\begin{figure}[H]\n\t\t\\centering\n\t\t\n\t\t\\subfigure[Scene0]{\n\t\t\\begin{minipage}[t]{0.45\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width=1.5in]{images/angles.png}\n\t\t%\\caption{original image}\n\t\t\\end{minipage}%\n\t\t}\n\t\\end{figure}\n\tWe let $$spec = D(\\theta_h)F(\\theta_d)G(\\theta_l,\\theta_v)$$\n\twhere $$D_{GTR}(\\theta_h) = \\frac{\\alpha}{\\pi}\\frac{1}{(1 + (\\alpha^2-1)\\cos^2\\theta_h)^2}$$ $$\\alpha = roughness^2$$\n\t$$F(\\theta_d) = 0.08 + (1- 0.08)(1-\\cos \\theta_d)^5$$\n\t$$G(v) = \\frac{n \\cdot v}{(n \\cdot b) + \\sqrt{\\alpha^2 + (1-\\alpha^2)(n \\cdot v)^2}}$$\n\tAnd we use BRDF weighted sampling to sample the reflect ray. i.e\n\t$$pdf_h = D(\\theta_h)\\cos\\theta_h, \\ pdf_l = \\frac{pdf_h}{4(l \\cdot h)}$$\n\twe sample both the light and brdf, then combine them with multiple importance sampling.\n\t$$dirlight = \\frac{pdf_{light}^2}{pdf_{light}^2 + pdf_{brdf}^2}L_{light} + \\frac{pdf_{brdf}^2}{pdf_{light}^2 + pdf_{brdf}^2}L_{brdf}$$\n\t\\subsubsection{Area light sampling}\n\tTo sample on the rectangle area light is quit easy. we just uniformly sample a point on the rectangle area light.\n\t\\begin{lstlisting}\n\t\tauto random_sample = unif(0.0, 1.0, 2);\n    Float x1 = random_sample[0];\n    Float z1 = random_sample[1];\n    vec3 sample_position = position + ((x1 - 0.5) * areaSize[0] * vec3(1, 0, 0)) + ((z1 - 0.5) * areaSize[1] * vec3(0, 0, 1));//uniformly ramdom choose a point on arealight\n\t\\end{lstlisting}\n\tand the pdf will be $\\frac{1}{A}$.\n\tHowever, as $$L_o(x,w_o) = \\int_{\\Omega}L_i(p,w_i)f_r(p,w_i,w_o)(n\\cdot w_i)dw_i$$\n\twe need to transform $dw_i$ to $d_A$. By the definition of solid angle, we have $dw = \\frac{dA \\cos\\theta^{'}}{||x^{'} - x||^2}$, where \n\t$\\cos\\theta^{'} = n_{light} \\cdot w_i$, $x^{'}$ is our sampled position on light, $x$ is the intersection point. Then we have\n\t$$L_o(x,w_o) = \\int_{\\Omega}L_i(p,w_i)f_r(p,w_i,w_o)\\frac{\\cos\\theta\\cos\\theta^{'}}{||x^{'} - x||^2}dA$$\n\there is the code for computing solid angle.\n\t\\begin{lstlisting}\n\tauto geom = geoms[0];\n    Float cos_theta1 = abs(geom.get()->getNormal().dot(ref_it.wi));\n    Float distance = (pos - ref_it.entryPoint).norm();\n    return cos_theta1 / (distance * distance); // solid angle of the tiny surface\n\t\\end{lstlisting}\n\t\\subsubsection{Integrator based on Monte-Carlo Path Tracing}\n\tFor each ray, we perform Monte-Carlo Path Tracing with following recursive procedure.\n\t\\begin{lstlisting}\n\tshade(p, wo, depth)\n\t\tCheck if depth > MAX_DEPTH return vec3(0,0,0)\n\t\tIf hit light, check (n * wo) return light emission\n\t\tIf hit object, sample the light at x1\n\t\tL_dir = L_i * f_r * cos_theta *cos_theta1/|x1-p|^2/pdf_light\n\t\tshoot another ray to compute indirect lighting\n\t\tRay r(p, wi)\n\t\tIf r hit anything at position q\n\t\tL_indir = shade(q, wi, depth + 1) * f_r * cos_theta/pdf\n\t\treturn L_dir + L_indir\n\t\\end{lstlisting}\n\t\\section{Results}\n\t\\begin{figure}[H]\n\t\t\\centering\n\t\t\n\t\t\\subfigure[Scene0]{\n\t\t\\begin{minipage}[t]{0.45\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width=1.5in]{images/output_256.png}\n\t\t%\\caption{original image}\n\t\t\\end{minipage}%\n\t\t}\n\t\t\\subfigure[Scene1]{\n\t\t\\begin{minipage}[t]{0.45\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width=1.5in]{images/output_bunny.png}\n\t\t%\\caption{ground truth}\n\t\t\\end{minipage}%\n\t\t}%\n\t\t\t\t\t\t\n\t\t\\subfigure[Scene2]{\n\t\t\\begin{minipage}[t]{0.45\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width=1.5in]{images/output_dragon1.png}\n\t\t%\\caption{depth prediction result}\n\t\t\\end{minipage}\n\t\t}\n\t\t\\subfigure[Scene3]{\n\t\t\\begin{minipage}[t]{0.45\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width=1.5in]{images/output_dragon_bunny.png}\n\t\t%\\caption{depth prediction result}\n\t\t\\end{minipage}\n\t\t}\n\t\t\\subfigure[Scene4]{\n\t\t\\begin{minipage}[t]{0.45\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width=1.5in]{images/output_all_dragon.png}\n\t\t%\\caption{depth prediction result}\n\t\t\\end{minipage}\n\t\t}\n\t\t\\subfigure[Scene0spp512]{\n\t\t\\begin{minipage}[t]{0.45\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width=1.5in]{images/output_birghter_512.png}\n\t\t%\\caption{depth prediction result}\n\t\t\\end{minipage}\n\t\t}\n\t\t\\subfigure[Scene1spp512]{\n\t\t\\begin{minipage}[t]{0.45\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width=1.5in]{images/output_bunny_512.png}\n\t\t%\\caption{depth prediction result}\n\t\t\\end{minipage}\n\t\t}\n\t\t\\subfigure[Scene1specular]{\n\t\t\\begin{minipage}[t]{0.45\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width=1.5in]{images/output_spec.png}\n\t\t%\\caption{depth prediction result}\n\t\t\\end{minipage}\n\t\t}\n\t\t\\subfigure[Scene2Transmission]{\n\t\t\\begin{minipage}[t]{0.45\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width=1.5in]{images/output_dragon_transmission_depth6.png}\n\t\t%\\caption{depth prediction result}\n\t\t\\end{minipage}\n\t\t}\n\t\t\\subfigure[Scene1Glossy]{\n\t\t\\begin{minipage}[t]{0.45\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width=1.5in]{images/output_glossy_box0.2_bunny0.1.png}\n\t\t%\\caption{depth prediction result}\n\t\t\\end{minipage}\n\t\t}\n\t\t\\end{figure}\n\\end{document}\n", "meta": {"hexsha": "53635259b786e67fc843dc20fb4f40e1daccef98", "size": 9983, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Assignment4/report/report.tex", "max_stars_repo_name": "Young2647/Computer-Graphics", "max_stars_repo_head_hexsha": "d52aafe16d1128dafaf349ac726c40bb6dab8758", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assignment4/report/report.tex", "max_issues_repo_name": "Young2647/Computer-Graphics", "max_issues_repo_head_hexsha": "d52aafe16d1128dafaf349ac726c40bb6dab8758", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assignment4/report/report.tex", "max_forks_repo_name": "Young2647/Computer-Graphics", "max_forks_repo_head_hexsha": "d52aafe16d1128dafaf349ac726c40bb6dab8758", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.9684684685, "max_line_length": 224, "alphanum_fraction": 0.7164179104, "num_tokens": 3341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.3403117710102629}}
{"text": "\\chapter{Molecular electrostatic potentials in complex space}\n\\label{chap:complex-space-potentials}\n\n\n\nAs we have seen in chapters \\ref{chap:R-matrix} and \\ref{chap:multi-channel}, the $R$-matrix correlation-driven yield can be written down as \\eqref{e3-correlation-driven-yield-reprise-with-full-derivatives}, which is essentially of the form\n\\begin{align}\na_{nm}^{(1)}(\\vb{p},\\tn)\n& =\n-i\ne^{-iE_n \\tn}\ne^{iI_{p,m} \\ts+\\frac{i}{2} \\int_T^{\\ts}\\left(\\vbp+\\vba(\\tau)\\right)^2\\d\\tau} \n\\int_{\\ts}^T\\!\ne^{+i(E_n-E_m)t''}\n\\Vnm{\\rl(t'')}\nR_m(\\vbp)\n\\d t''\n\\label{e4-correlation-driven-yield-recap}\n\\end{align}\nif we ignore for the moment our hard-won corrections from chapter~\\ref{chap:multi-channel} (which are nevertheless of an equivalent form) as well as the Coulomb corrections of chapter~\\ref{chap:R-matrix}. From this expression we know essentially everything we need to get some hard numbers, except for the correlation interaction potential\n\\begin{equation}\n\\Vnm{\\vbr}=\\matrixel**{n}{\\sum_{j=1}^{N-1} \\frac{1-\\delta_{nm}}{\\| \\vbr - \\hat{\\vbr}_j\\|} }{m}\n.\n\\label{e4-correlation-interaction-potential-initial}\n\\end{equation}\nThe purpose of this chapter is to examine this potential as a function of $\\vbr$. \n\nThis is in principle rather straightforward, as it is only the expectation value of a Coulomb kernel -- a bread-and-butter component of quantum chemistry -- but as we have seen before, we need to query this potential at the laser-driven trajectory\n\\begin{equation}\n\\rl(t) = \\int_{\\ts}^{t} \\left[ \\vbp+\\vba(\\tau) \\right] \\: \\d\\tau,\n\\end{equation}\nand in general this is complex: the ionization time $\\ts$ from \\eqref{e2-ts-equation} is complex, so the integration variable $\\tau$ must be complex, and this forces the analytical vector potential $\\vba(\\tau)=-\\frac{F}{\\omega}\\ue_{z} \\sin(\\omega \\tau)$ to also be complex. In chapter~\\ref{chap:quantum-orbits} we will explore the structure of this complex-valued trajectory -- how complex it can be, how that interacts with the correlation interaction potential and the mean-field Coulomb potential, and to what extent the imaginary parts of $\\rl(t)$ can be kept to a minimum -- but, for the moment, this chapter simply accepts that $\\Vnm{\\vbr}$ needs to be queried at complex-valued arguments, and studies the consequences.\n\n\nWe will find that for several common models of the orbitals that generate $\\Vnm{\\vbr}$, including models general enough to generate the state of the art numerical calculations for the orbitals, the corresponding analytical continuations for $\\Vnm{\\vbr}$ can agree surprisingly well (when $\\vbr$ is `real~enough'), but they can also differ catastrophically (when $\\vbr$ is `too~imaginary'), or even be impossible to generalize into a correct analytical continuation. \n\nThe result is a serious constraint on the positions at which we can reliably calculate $\\Vnm{\\vbr}$ (and indeed even know what behaviour to expect), and a strong argument can be made that we completely lack the tools to venture further. On the other side, this limit also increases our confidence in $\\Vnm{\\vbr}$ in the regions where we \\textit{can} calculate it, and, moreover, it gives us a clear goal to address in chapter~\\ref{chap:quantum-orbits}, where we will show that it is indeed possible to steer the complex trajectory $\\rl(t'')$ so that we never need to query $\\Vnm{\\rl(t'')}$ at the positions where the numerical methods fail and the analytical models disagree.\n\n\n\n\\section{Quantum chemical calculations of correlation interaction potentials for real positions}\n\nFor a real argument $\\vbr$, the correlation interaction potential in \\eqref{e4-correlation-interaction-potential-initial} is actually rather straightforward to calculate, since it is just the matrix element of a function of the $\\vbr_j$ between two well-defined ionic eigenstates. As such, one can simply insert a position-space resolution of the identity,\n\\begin{equation}\n1\n=\n\\int\\!\\d\\vbr_1\\cdots\\d\\vbr_{N-1} \\:\n\\ket{\\vbr_1,\\ldots,\\vbr_{N-1}}\\bra{\\vbr_1,\\ldots,\\vbr_{N-1}}\n,\n\\end{equation}\nto rephrase the potential as an $(N-1)$-dimensional integral:\n\\begin{equation}\n\\Vnm{\\vbr}\n=\n\\sum_{j=1}^{N-1} \n\\int\\!\n\\frac{\n  \\braket{n}{\\vbr_1,\\ldots,\\vbr_{N-1}} \\!\n  \\braket{\\vbr_1,\\ldots,\\vbr_{N-1}}{m}\n  }{\n  \\| \\vbr - \\vbr_j\\|\n  }\n\\d\\vbr_1\\cdots\\d\\vbr_{N-1} \n.\n\\label{e4-correlation-interaction-potential-integral}\n\\end{equation}\n(For convenience, we forget the factor of $\\delta_{mn}$, which requires us to remember to impose $n\\neq m$ on all uses of $\\Vnm{\\vbr}$.)\n\nIn general, for real $\\vbr$, these are are well-behaved integrals. They have integrable square-root singularities at $\\vbr_j=\\vbr$, where the Coulomb kernel is multiplied by the transition charge density $ \\braket{n}{\\vbr_1,\\ldots,\\vbr_{N-1}} \\!  \\braket{\\vbr_1,\\ldots,\\vbr_{N-1}}{m}$ (which is in principle complex-valued), and these are in generally smooth and rather well-behaved, with support confined to rather small regions around the molecule.\n\n\nWe can get a lot of intuition about the correlation interaction potentials of the form \\eqref{e4-correlation-interaction-potential-integral} by working in the simplest Hartree-Fock regime, in which the ground state\n\\begin{equation}\n\\ket{\\Psi_g} = \\mathbb{A}\\ket{\\phi_1}\\otimes \\cdots\\otimes \\ket{\\phi_N}\n\\end{equation}\nis a minimal Hartree-Fock determinant, a single antisymmetrized product of single-particle orbitals $\\ket{\\phi_j}$, and the ionic eigenstates can be approximated well by simply deleting the relevant orbitals from the ground state. In this case the correlation interaction potential simplifies to a one-particle integral of the form\n\\begin{equation}\n\\Vnm{\\vbr}\n=\n\\sum_{j=1}^{N-1} \n\\int\\!\n\\frac{\n  \\phi_n^*(\\vbr')\\phi_m(\\vbr')\n  }{\n  \\| \\vbr - \\vbr'\\|\n  }\n\\d\\vbr'\n\\label{e4-correlation-interaction-potential-hartree-fock}\n\\end{equation}\nor, in terms of a transition charge $\\rho_{mn}(\\vbr') = \\phi_n^*(\\vbr') \\phi_m(\\vbr')$, as \n\\begin{equation}\n\\Vnm{\\vbr}\n=\n\\int\\!\n\\frac{\n  \\rho_{mn}(\\vbr')\n  }{\n  \\| \\vbr - \\vbr'\\|\n  }\n\\d\\vbr'\n.\n\\label{e4-correlation-interaction-potential-with-transition-charge}\n\\end{equation}\nFor rigorous calculations, one should of course use the fullest form available, but the Hartree-Fock intuition is useful in predicting the overall behaviour of $\\Vnm{\\vbr}$. For example, this form justifies our use of a dipole model for the $\\X\\to\\B$ transition in $\\mathrm{CO}_2$ in chapter~\\ref{chap:multi-channel}.\n\n\nSimilarly, the full-form potential \\eqref{e4-correlation-interaction-potential-integral} can also be written down in the single-particle integral form \\eqref{e4-correlation-interaction-potential-with-transition-charge} by using the slightly more complicated transition charge density\n\\begin{align}\n\\rho_{mn}(\\vbr')\n =\n(N-1)\n\\int\\!\n\\d\\vbr_2 \\cdots \\d\\vbr_{N-1} \n&   \n\\braket{n}{\\vbr',\\vbr_2,\\ldots,\\vbr_{N-1}} \\!\n\\braket{\\vbr',\\vbr_2,\\ldots,\\vbr_{N-1}}{m}\n,\n\\label{e4-full-transition-charge-as-integral}\n\\end{align}\nwhich encapsulates the $\\vbr$-independent integration over all the other electrons.\n\nEither way, the correlation interaction potential can always be written down in the form \\eqref{e4-correlation-interaction-potential-with-transition-charge}, as a simple single three-dimensional integral of some transition charge $\\rho_{mn}(\\vbr')$ times a standard, perfectly integrable Coulomb kernel. As such, the correlation interaction potential can be thought of as the electrostatic field that would be produced by a charge density $\\rho_{mn}(\\vbr')$, complex-valued as it might be.\n\n\n\nIn practice, unfortunately, obtaining exact analytical expressions for $\\Vnm{\\vbr}$ for realistic cases is impossible, starting with the fact that there are no molecules for which we know exact analytical solutions for the electronic eigenstates. In fact, even for the simplest known molecular system, the hydrogen molecular ion H$_2^+$, with only a single electron responding to two clamped nuclei, the single-dimensional Schrödinger equation is separable but not exactly solvable. Similarly, as soon as there is more than one electron present -- starting with atomic helium -- exact analytical solutions of the Schrödinger equation simply do not exist.\n\nThe response to this over the past eight decades has been to develop numerical methods to solve the Schrödinger equation to as good a precision as one can reasonably ask for, by using some suitable discretization of the available state space and then numerically solving a finite-dimensional eigenvalue problem, and this is the core of the discipline of quantum chemistry. \n\nWithin this discipline, the prevailing methods to discretize the state space for the electron wavefunctions involve the postulation of some finite basis of single-electron functions,\n\\begin{equation}\nB=\\left\\{\\chi_1,\\ldots,\\chi_M\\right\\},\n\\end{equation}\npossibly optimized for the problem at hand in some variational way, and then working with $n$-electron wavefunctions built as linear combinations of Slater determinants of those basis functions. In general, these basis functions are mostly chosen to be so-called Slater-type orbitals of the form $e^{-r/\\alpha}$, depending exponentially on the distance $r$ to some fixed point in space, or even more commonly gaussian-type orbitals of the form $e^{-r^2/\\sigma^2}$, both of which can be modified by polynomial factors to give them better angular momentum properties.\n\nIn the end, though, what matters for our purposes is that the transition charge density $\\rho_{mn}(\\vbr')$, when calculated through quantum chemical means, will typically be completely constrained to be finite linear combinations of gaussian densities centred at some arbitrary location in the molecule, possibly multiplied by some polynomial. This then allows us to replace the arbitrary-looking $\\rho_{mn}(\\vbr')$ by a fixed gaussian charge density\n\\begin{equation}\n\\rhog(\\vbr')=\\normg \\exp(-r'^2/\\sigma^2)\n\\label{e4-gaussian-charge-density}\n\\end{equation}\nif it is necessary to build intuition for the behaviour of the potential \\eqref{e4-correlation-interaction-potential-with-transition-charge} when it is calculated via quantum chemical means, in the informal understanding that the full quantum chemical transition charge density is a linear superposition of such densities or polynomially related ones, and therefore so will the potential, which depends linearly on $\\rho_{mn}(\\vbr')$.\n\n\nHere it is important to note that the gaussian potential \\eqref{e4-gaussian-charge-density} is not quite a perfect model for a transition charge of the form \\eqref{e4-full-transition-charge-as-integral}, because transition charges must always integrate to zero:\n\\begin{align}\n\\int \\!\n\\rho_{mn}(\\vbr')\n\\, \\d\\vbr'\n& =\n(N-1)\n\\int\\!\n\\d\\vbr' \\,\n\\d\\vbr_2 \\cdots \\d\\vbr_{N-1} \n\\braket{n}{\\vbr',\\vbr_2,\\ldots,\\vbr_{N-1}} \\!\n\\braket{\\vbr',\\vbr_2,\\ldots,\\vbr_{N-1}}{m}\n\\nonumber \\\\ & =\n\\braket{n}{m}\n= 0\n.\n\\end{align}\nIn terms of simplified models, the gaussian potential \\eqref{e4-gaussian-charge-density} can easily be modified to have this property, with the simplest and most physically relevant example being a $p$-type gaussian of the form $\\rho_{\\mathrm{g}, z} (\\vbr')=z'\\rhog(\\vbr')$. The results in this chapter are essentially unchanged with this modification (which is most easily seen by noting that $\\rho_{\\mathrm{g}, z} (\\vbr')$ is the derivative of $\\rhog(\\vbr')$ with respect to shifts in the origin), though the loss of rotational symmetry makes the analysis more awkward.\n\nSimilarly, when quantum chemists use simple gaussians as a basis to represent a transition charge, the nature of the coefficients is always such that, although each term, as in \\eqref{e4-gaussian-charge-density} or multiplied by a polynomial, will have a nonzero charge, all these charges must add to zero.\n\n\n\n\\section{Quantum chemical potentials for complex positions}\n\\label{sec:quantum-chemical-potentials-complex}\nSomewhat more practically, even for simple gaussian charge densities of the form \\eqref{e4-gaussian-charge-density}, it is often cheap enough to simply perform the integral \\eqref{e4-correlation-interaction-potential-with-transition-charge} for $\\Vnm{\\vbr}$ numerically, since it is relatively well behaved (its integrable singularity aside) and can be computed relatively quickly. For a quantum chemical transition charge density, known numerically in terms of the eigenfunctions of a finite-dimensional problem, this certainly seems to be a rather reasonable route, and for real positions it tends to work well.\n\n\nWhat we want, of course, is to extend \\eqref{e4-correlation-interaction-potential-with-transition-charge} to complex positions, but at least as a first stab it is reasonable to simply put in a complex-valued $\\vbr$ and churn away at the numerical integral. In this case, then the integral is of the form\n\\begin{align}\n\\Vnm{\\vphantom{\\sum} \\Re(\\vbr)+i\\Im(\\vbr)}\n& =\n\\int\\!\n\\frac{\n  \\rho_{mn}(\\vbr')\n  \\: \\d\\vbr'\n  }{\n  \\sqrt{ \\left( \\Re(\\vbr)+i\\Im(\\vbr) - \\vbr' \\right)^2 }\n  }\n\\nonumber \\\\ & =\n\\int\\!\n\\frac{\n  \\rho_{mn}(\\vbr')\n  \\: \\d\\vbr'\n  }{\n  \\sqrt{ \\left( \\Re(\\vbr)-\\vbr' \\right)^2 - \\Im(\\vbr)^2 + 2i\\Im(\\vbr)\\cdot (\\Re(\\vbr)-\\vbr')}\n  }\n,\n\\label{e4-correlation-interaction-potential-with-complex-position}\n\\end{align}\nwhich is not all that problematic, at least at first glance.\n\nThere is, for sure, the issue of exactly what branch to take for the square root, but unless there are strong over-riding reasons this is settled by the fact that -- absent knowledge of $\\vbr$ and the support through $\\rho_{mn}(\\vbr')$ for the $\\vbr'$ that are relevant to the integral -- the argument of the square root is in general conjugate-symmetric with respect to inversion in $\\vbr'$ (i.e. inverting $\\vbr'$ roughly conjugates the square root argument), and this generally requests that the square root be taken in a conjugate-symmetric way. This requires, then, that we define the square root with a branch cut on the ray $(-\\infty,0]$, so\n\\begin{equation}\n\\sqrt{\\zeta}=\\sqrt{|\\zeta|e^{i\\theta}} = |\\zeta|^{1/2} e^{i\\theta/2}\n\\label{e4-square-root-definition}\n\\end{equation}\nwhenever the argument $\\zeta$ is written as $\\zeta=|\\zeta|e^{i\\theta}$ for $-\\pi< \\theta \\leq \\pi$. Throughout this work we will adhere strictly to this convention for the symbol $\\sqrt{\\phantom{zz}}$ unless otherwise noted.\n\n\n\\begin{subequations}\nIn addition to this, the change from real to complex $\\vbr$ does change the structure of the integrand, by changing the nature of the singularity in the denominator. More concretely, having a vanishing denominator now requires a \\textit{pair} of conditions,\n\\begin{align}\n\\left( \\Re(\\vbr)-\\vbr' \\right)^2 & = \\Im(\\vbr)^2 \\quad \\text{and} \\\\\n (\\vbr'-\\Re(\\vbr)) \\cdot \\Im(\\vbr) & =0,\n\\end{align}\nand this changes the dimensionality of the singularity from a point to (in general) a non-degenerate line. This singularity is now the intersection of a plane through the $\\Re(\\vbr)$ orthogonal to $\\Im(\\vbr)$ and a sphere of radius $\\|\\Im(\\vbr)\\|$ around $\\Re(\\vbr)$, and this means that whenever $\\Im(\\vbr)\\neq 0$ it is always a circle of radius $\\|\\Im(\\vbr)\\|$ centred at $\\Re(\\vbr)$, on a plane orthogonal to $\\Im(\\vbr)$.\n\\label{e4-circular-singularity}%\n\\end{subequations}%\n\nHere the added dimension does make the singularity less noble -- there's ``more singularity'' to handle -- but it is still perfectly manageable, since locally at the singularity it looks mostly like a straight line, so it is of the form\n\\begin{equation}\n\\int_\\mathrm{local}  \\frac{\\d x'\\d y'\\d z'}{\\sqrt{(x'-x_0)^2+(y'-y_0)^2}}\n\\end{equation}\n(i.e. with the $z$ dimension regularized out, but still a line singularity at $x'=x_0$, $y'=y_0$), and this is still regular when the area element in the $x',y'$ plane $\\d x'\\d y'=r'\\d r'\\d\\theta'$ is taken into account. Of course, if the integration is done numerically the ring singularity must still be specifically handled to obtain correct results, but it does not represent a significant impediment to the calculation.\n\n\n\\begin{figure}[htb]\n  \\centering\n  \\begin{tabular}{cc}\n  (a) $\\Re(\\Vg(\\vbr))$ & (b) $\\Im(\\Vg(\\vbr))$ \\\\[-2mm]\n  \\subfigure{\n    \\includegraphics[scale=1]{4-Potentials/Figures/figure4Aa.pdf}\n  }\n  &\n  \\subfigure{\n    \\includegraphics[scale=1]{4-Potentials/Figures/figure4Ab.pdf}\n  }\n  \\end{tabular}\n  \\caption[Numerically integrated electrostatic potential $\\Vg(\\vbr)$ of a gaussian charge distribution as a function of complex space coordinates]{\n  Electrostatic potential $\\Vg(\\vbr)$ of a gaussian charge distribution as a function of complex $z$ for fixed $x=3$ and $y=0$, with $\\sigma=1$, calculated using direct numerical integration as in \\eqref{e4-correlation-interaction-potential-numerically-gaussian}.}\n  \\label{f4-numerical-potential-from-gaussian}\n\\end{figure}\n\n\nWith all this in hand, then, we can now simply plug in a complex position into \\eqref{e4-correlation-interaction-potential-with-complex-position}, do the integral numerically, and see what comes out. As a starting example, to keep things simple, we can use a single gaussian charge distribution at the origin, $\\rhog(\\vbr)$ as in \\eqref{e4-gaussian-charge-density}, so we look to calculate\n\\begin{align}\n\\Vg\\left(\\vphantom{\\sum} \\Re(\\vbr)+i\\Im(\\vbr)\\right)\n& =\n\\int\\!\n\\frac{\n  \\normg \\exp(-r'^2/\\sigma^2)\n  \\: \\d\\vbr'\n  }{\n  \\sqrt{ \\left( \\Re(\\vbr)-\\vbr' \\right)^2 - \\Im(\\vbr)^2 + 2i\\Im(\\vbr)\\cdot (\\Re(\\vbr)-\\vbr')}\n  }\n.\n\\label{e4-correlation-interaction-potential-numerically-gaussian}\n\\end{align}\nThis single integral can readily be integrated numerically, and we show the results in \\reffig{f4-numerical-potential-from-gaussian}, fixing two components of $\\vbr$ and showing the variation of $\\Re(\\Vg(\\vbr))$ and $\\Im(\\Vg(\\vbr))$ as a function of complex $z$ while keeping $x$ and $y$ constant. (Because of the rotational symmetry of $\\rhog(\\vbr)$, of course, these results are essentially representative, up to the shape parameter $\\sqrt{x^2+y^2}/\\sigma$.)\n\n\n\n\nThis procedure, then, gives us a very workable electrostatic potential: it is continuous, with no poles, branch points, or other singularities, and it is bounded at infinity. More physically, it contains two large bumps when $z=i\\zeta$ is imaginary and of the same magnitude as $|x|$ because then the quadratic term $\\Re(\\vbr^2)=x^2-\\zeta^2$ in\n\\begin{align}\n\\Vg(x,0,i\\zeta)\n& =\n\\int\\!\n\\frac{\n  \\normg \\exp(-r'^2/\\sigma^2)\n  \\: \\d\\vbr'\n  }{\n  \\sqrt{r'^2-2(xx'+i\\zeta z')+(x^2-\\zeta^2)}\n  }\n,\n\\end{align}\nwhich effectively acts as softening, vanishes, and this leaves the Coulomb kernel at maximal amplitude. Moreover, the potential appears to be smooth and, if everything went right, it should be analytic.\n\n\n\n\n\nUnfortunately, this combination of features turns out to be too good for our electrostatic potential, because it makes it run afoul of one of the basic principles of complex analysis: the fact that if a function is continuous and differentiable everywhere, then either it diverges to infinity or it is absolutely constant.\n\n\n\n\n\n\\pagebreak\n\n\\begin{mathaside}{Any bounded entire function is constant}\n\\label{aside.entire-functions-bounded}\n\n\nTo be more precise, a function $f:\\mathbb{C} \\to \\mathbb{C}$ is called \\textit{analytic} at $z$ if its complex derivative $f'(z)$, in the sense of the Cauchy-Riemann equations, exists at $z$ and at all points in an open neighbourhood of $z$, and it is called \\textit{entire} if it is analytic (and therefore continuous) at all points $z\\in\\mathbb{C}$. Similarly, $f$ is bounded in a region $D$ if there exists $M>0$ such that $|f(z)|<M$ for all $z\\in D$. With this language, then, we have the simple theorem:\n\n\\begin{namedtheorem}[Liouville's]\nIf $f:\\mathbb{C} \\to \\mathbb{C}$ is entire and bounded for all values of $z$ in the complex plane, then $f(z)$ is constant.\n\\end{namedtheorem}\n\n\nFor a rigorous proof, we refer the reader to \\citer{churchill_complex_variables}. Nevertheless, given the rather far-reaching consequences of this principle, it is worth spending some time to justify it. In its essence, Liouville's theorem is deeply related to yet another core fact of complex analysis, the maximum principle:\n\n\\begin{theorem}[Maximum principle]\nIf $f:U\\subseteq \\mathbb{C}\\to\\mathbb{C}$ is analytic and not constant in the interior of a region, then $|f(z)|$ has no maximum value in that interior.\n\\end{theorem}\n\n\nBoth of these statements punch far above their weight in terms of the strength of their consequences versus the simplicity of their statements, but the main ingredient here is simply the fact that both the real and imaginary parts of $f$ are harmonic functions. Indeed, if we write $f(x+iy)=u(x,y)+v(x,y)$ in terms of real-valued $u$, $v$, $x$ and $y$, then the Cauchy-Riemann equations\n\\begin{subequations}\n\\begin{empheq}[left={\\empheqlbrace\\,}]{align}\n\\frac{\\partial u}{\\partial x} & = \\frac{\\partial v}{\\partial y} \\\\\n\\frac{\\partial u}{\\partial y} & = -\\frac{\\partial v}{\\partial x} \n\\end{empheq}\n\\label{e4-cauchy-riemann}\n\\end{subequations}\nimply that both $u$ and $v$ obey the Laplace equation,\n\\begin{equation}\n\\frac{\\partial^2 u}{\\partial x^2}+\\frac{\\partial^2 u}{\\partial y^2}\n=\n\\frac{\\partial^2 v}{\\partial x^2} + \\frac{\\partial^2 v}{\\partial y^2}\n= 0\n.\n\\end{equation}\nThus, if they are `winding down', with convex curvature, in one dimension, they must be `winding up' with concave curvature in the orthogonal dimension. This means that both $u$ and $v$ must obey the maximum principle -- no harmonic function can sustain a local maximum in the interior of its domain -- and, after some technical wrangling with the Cauchy-Riemann equations to extend the argument to $|f(z)|=\\sqrt{u^2+v^2}$, so does $f$.\n\\qed\n\n\\vspace{\\maskip}\n\nAt this level, we can already see that the numerical $\\Vg(\\vbr)$ shown in \\ref{f4-numerical-potential-from-gaussian} simply has no chance of being an analytical function, since both its real and imaginary parts are obviously not harmonic functions, and they both show obvious local maxima and minima.\n\n\nLiouville's theorem follows much of the same intuition -- if a function is entire, then it must keep growing for bigger and bigger circles -- but it requires an independent proof. More specifically, we take some arbitrary $z_0\\in \\mathbb{C}$, and we relate the value of the derivative $f'(z_0)$ there to the values of $f(z)$ on some arbitrary circle $C$ about $z_0$ of radius $r$ using Cauchy's integral formula,\n\\begin{equation}\nf'(z_0) = \\frac{1}{2\\pi i}\\int_C \\frac{f(z)\\d z}{(z-z_0)^{2}}\n.\n\\end{equation}\nSince we know that $|f(z)|$ is bounded everywhere by some constant $M>0$, we can take the absolute values of both sides to get an inequality\n\\begin{equation}\n|f'(z_0)|\\leq \\frac{1}{2\\pi} \\frac{M\\times 2\\pi r}{r^2} = \\frac{M}{r}\n.\n\\end{equation}\nHere $M$ was given and fixed, but $r$ can be chosen to be arbitrarily large, and this requires that $f'(z_0)=0$ for our arbitrary $z_0\\in\\mathbb{C}$; in other words, $f(z)$ is constant. \n\n\\hfill\\qedsymbol\n\n\\vspace{\\maskip}\nA bit away from the formal side, both of these principles express the fact that the theory of analytical functions is very, very rigid, and even more so when compared to the theory of smooth real functions in $C^\\infty$. This rigidity boils down to the fact that to be complex differentiable a function $f$ must not only be locally well approximated by a straight line, as in the real case; instead, it must also obey the the full-fledged pair of Cauchy-Riemann differential equations in~\\eqref{e4-cauchy-riemann}. The rigidity of the theory is, at least partly, inherited from the theory of differential equations, which is rigid enough that functions tend to inherit their values in the interior of a region from their behaviour at its boundary.\n\n\\vspace{\\maskip}\nOn a more positive note, Liouville's theorem is best seen as the statement that for a function to be analytic, it needs to be interesting: it needs to have poles, branch cuts, natural boundaries, or divergences at infinity. Our numerically integrated $\\Vg(\\vbr)$ from \\eqref{e4-correlation-interaction-potential-numerically-gaussian} and \\reffig{f4-numerical-potential-from-gaussian}, with its gentle bumps and bounded, continuous behaviour, does not qualify.\n\n\n\n\\end{mathaside}\n\n\n\nReturning to our numerically-integrated potential, we see that its features indicate that it cannot be an analytical function of $x$, $y$ and $z$. However, we do not need to take this for granted -- we can simply check to see whether it obeys the Cauchy-Riemann equations, which is shown in \\reffig{f4-cauchy-riemann-for-numerical-gaussian}. As expected from the above considerations, of course, the test fails, which means that our numerically-integrated $\\Vg(\\vbr)$ is not an analytical function.\n\n\n\n\\begin{figure}[htb]\n  \\centering\n  \\begin{tabular}{cc}\n  (a) $\\Im \\left( \\frac{\\partial \\Vg(\\vbr)}{\\partial \\Re(z)} \\right)$ & (b) $\\Im \\left( \\frac{\\partial \\Vg(\\vbr)}{i \\, \\partial \\Im(z)} \\right)$ \\\\[-2mm]\n  \\subfigure{\n    \\label{f4-cauchy-riemann-for-numerical-gaussian-a}\n    \\includegraphics[scale=1]{4-Potentials/Figures/figure4Ba.pdf}\n  }\n  &\n  \\subfigure{\n    \\label{f4-cauchy-riemann-for-numerical-gaussian-b}\n    \\includegraphics[scale=1]{4-Potentials/Figures/figure4Bb.pdf}\n  }\n  \\\\\n  (c) $\\Re \\left( \\frac{\\partial \\Vg(\\vbr)}{\\partial \\Re(z)} \\right) \\approx \\Re\\left( \\frac{\\partial \\Vg(\\vbr)}{i \\, \\partial \\Im(z)} \\right)$ &\n  (d) $\\left| \\frac{\\partial \\Vg(\\vbr)}{\\partial \\Re(z)} - \\frac{\\partial \\Vg(\\vbr)}{i \\, \\partial \\Im(z)} \\right|$ \\\\[-2mm]\n  \\subfigure{\n    \\label{f4-cauchy-riemann-for-numerical-gaussian-c}\n    \\includegraphics[scale=1]{4-Potentials/Figures/figure4Bc.pdf}\n  }\n  &\n  \\subfigure{\n    \\label{f4-cauchy-riemann-for-numerical-gaussian-d}\n    \\includegraphics[scale=1]{4-Potentials/Figures/figure4Bd.pdf}\n  }\n  \\end{tabular}\n  \\caption[Cauchy-Riemann equations for the numerically-integrated electrostatic potential $\\Vg(\\vbr)$ over complex coordinates]{\n  Cauchy-Riemann equations for the numerically-integrated electrostatic potential $\\Vg(\\vbr)$ of \\eqref{e4-correlation-interaction-potential-numerically-gaussian}, shown over the same slice of complex coordinate space as \\reffig{f4-numerical-potential-from-gaussian} ($x=3$, $y=0$, and complex $z$).\n  Panels~\\protect\\subref{f4-cauchy-riemann-for-numerical-gaussian-a} and~\\protect\\subref{f4-cauchy-riemann-for-numerical-gaussian-b} show the imaginary parts of the derivative of $\\Vg(\\vbr)$ with respect to the real and imaginary parts of $z$, respectively; for an analytical function they should match but instead they have immediately appreciable differences. The real parts, shown in~\\protect\\subref{f4-cauchy-riemann-for-numerical-gaussian-c}, do match, but the two derivatives are left with a strong difference, shown in~\\protect\\subref{f4-cauchy-riemann-for-numerical-gaussian-d}.\n  }\n  \\label{f4-cauchy-riemann-for-numerical-gaussian}\n\\end{figure}\n\n\n\nThe reason for why $\\Vg(\\vbr)$ fails to be analytical can be seen, at least after the fact, from its integral form \\eqref{e4-correlation-interaction-potential-with-complex-position}. There, when we write\n\\begin{align}\n\\Vg(\\vbr)\n& =\n\\int\\!\n\\frac{\n  \\normg \\exp(-r'^2/\\sigma^2)\n  }{\n  \\sqrt{ \\left( \\vbr-\\vbr' \\right)^2}\n  }\n\\d\\vbr'\n,\n\\label{e4-correlation-interaction-potential-for-analyticity}\n\\end{align}\nwe are expressing $\\Vg(\\vbr)$ as a continuous superposition of Coulombic point-charge potentials $1/\\sqrt{ \\left( \\vbr-\\vbr' \\right)^2}$, and these are not analytic when $\\vbr'$ lies in the circular singularity, as described by \\eqref{e4-circular-singularity}, with respect to $\\vbr$. Since the integral always includes points $\\vbr'$ at this singularity and its neighbourhood, the assumption of analyticity of the resulting integral should be seen as suspect from the~start.\n\n\n\n\n\n\n\n\\section{Exactly integrable potentials}\nWe see, then, that the formulation of our correlation interaction potential $\\Vnm{\\vbr}$ as an integral over the ionic electrons' positions must be reformulated from its foundations when the probe point $\\vbr$ is complex-valued. This is somewhat problematic, since we initially defined $\\Vnm{\\vbr}$ as the matrix element \n\\begin{equation}\n\\Vnm{\\vbr}=\\matrixel**{n}{\\sum_{j=1}^{N-1} \\frac{1-\\delta_{nm}}{\\| \\vbr - \\hat{\\vbr}_j\\|} }{m}\n\\backtag{e4-correlation-interaction-potential-initial}\n\\end{equation}\nat the start of this chapter, and there are few ways of evaluating such matrix elements that don't rely on an integral. \n\nHowever, a more careful analysis shows that the matrix element \\eqref{e4-correlation-interaction-potential-initial} is only needed when defining $\\Vnm{\\vbr}$ for real-valued positions, since that is what goes into the original temporal integral for the ionization yield in \\eqref{e2-correlation-driven-yield-separated} and \\eqref{e2-correlation-driven-yield-with-eva-states}, and the only thing we need is the analytical continuation of this $\\Vnm{\\vbr}$ -- obtained by any reasonable means~-- when we shift the endpoint of the temporal integral into the complex plane to arrive at~\\eqref{e2-correlation-driven-yield-semi-final}. \n\n\nThis would seem to offer a very small comfort, since constructive theorems on analytical continuation are few and far between, but fortunately for us our problem has plenty of structure that we can exploit. To begin with, for many of the charge densities $\\rho(\\vbr)$ that we care about, including gaussian and exponential charge densities, the electrostatic potential, obtained as\n\\begin{align}\nV(\\vbr)\n& =\n\\int\\!\n\\frac{\n  \\rho(\\vbr') \\:\\d\\vbr'\n  }{\n  \\sqrt{ \\left( \\vbr-\\vbr' \\right)^2}\n  }\n,\n\\label{e4-electrostatic-potential-as-integral}\n\\end{align}\ncan actually be integrated exactly in terms of a closed elementary expression -- and, when this is possible, the elementary expression gives an automatic analytical continuation. In fact, it isn't even necessary to do a full integration, since the integral electrostatic potential in \\eqref{e4-electrostatic-potential-as-integral} can  be described equally well, for real positions, as the unique solution of the Poisson equation\n\\begin{equation}\n\\nabla^2 V(\\vbr)=-4\\pi \\rho(\\vbr)\n\\label{e4-poisson-equation}\n\\end{equation}\nunder $V(\\vbr)\\to 0$ as $|\\vbr|\\to\\infty$. In fact, for spherically symmetric charge distributions, this reduces to a simple second-order ordinary differential equation, which is much easier to integrate, and additional angular-momentum polynomial factors can also be accommodated rather easily by suitable modifications of the spherically-symmetric case.\n\nThis means, then, that for the gaussian charge distribution \\eqref{e4-gaussian-charge-density} that proved so problematic earlier we can simply write down the potential as\n\\begin{subequations}\n\\label{e4-exact-gaussian-potential}\n\\begin{align}\n\\Vg(\\vbr) \n& = \n\\pi^{3/2} \\sigma^3 \\normg \\frac{ \\erf(r/\\alpha) }{ r }\n\\\\ & = \nQ \\frac{ \\erf(r/\\alpha) }{ r }\n,\n\\end{align}\n\\end{subequations}%\nin terms of a simple error function \\citenistchap{7} and the total charge $Q$. Similarly, with the other building block of quantum chemical bases, the Slater-type orbital with an exponential charge density\n\\begin{equation}\n\\rhoe(\\vbr) = \\norme \\exp(-r/\\sigma)\n,\n\\label{e4-exponential-charge-density}\n\\end{equation}\nthe radial Poisson equation can also be trivially solved to give the potential\n\\begin{subequations}\n\\label{e4-exact-exponential-potential}%\n\\begin{align}\n\\Ve(\\vbr) \n& = \n4\\pi \\alpha^2 \\norme \\left[ - \\left( 1 + \\frac{2\\alpha}{r} \\right) e^{-r/\\alpha} + \\frac{2\\alpha}{r} \\right]\n\\\\ & = \n \\frac{Q}{2\\alpha} \\left[ - \\left( 1 + \\frac{2\\alpha}{r} \\right) e^{-r/\\alpha} + \\frac{2\\alpha}{r} \\right]\n.\n\\end{align}%\n\\end{subequations} %\n\nIt is important to note that both of these exact potentials were obtained by integrating Poisson's equation \\eqref{e4-poisson-equation} for real coordinates, and they are only equal to the integrally-defined potential \\eqref{e4-electrostatic-potential-as-integral} when $\\vbr$ is real. However, both exact formulas \\eqref{e4-exact-gaussian-potential} and \\eqref{e4-exact-exponential-potential} \\textit{must} hold for the analytical continuation of \\eqref{e4-electrostatic-potential-as-integral} into complex-valued $\\vbr$, because for each coordinate they coincide on the real axis, and that is sufficient to ensure the uniqueness of the analytical continuation. Since the both \\eqref{e4-exact-gaussian-potential} and \\eqref{e4-exact-exponential-potential} are analytic, they are \\textit{the} unique extension of \\eqref{e4-electrostatic-potential-as-integral} to the complex plane \\cite[\\S108]{churchill_complex_variables}.\n\n\n\\vspace{5mm}\n\n\n\\begin{mathaside}{Analytical continuation}\n\\label{aside.analytical-continuation}\n\nAt this point, it is worth spending some time emphasizing this feature of the theory of complex variables. If we are given a function $f:\\mathbb{R}\\to \\mathbb{C}$ which is `nice enough', it is usual to speak of its analytical continuation as if this extension of $f$ to the complex plane can always be done, and can always be done uniquely. The possibility and uniqueness of analytical continuation in a multiply connected region is a complicated question, which reaches fruition in the theory of Riemann surfaces. (On the other hand, it is all too common to assume that, multivaluedness issues aside, any analytical function can always be extended as far as necessary, which need not be the case: many functions run into natural boundaries, which stop any kind of analytical continuation~\\cite[p.~191]{noguchi_complex_analysis}.)\n\n\\vspace{\\maskip}\nIn our context, it is worth emphasizing just how little is really necessary to ensure the uniqueness of an analytical continuation; the standard result \\cite[given e.g. in Ref.][pp.~283ff]{churchill_complex_variables} is usually stated in the form\n\n\\begin{theorem}\nA function that is analytic in a domain $D$ is uniquely determined over $D$ by its values over a subdomain, or along an arc, interior to $D$.\n\\end{theorem}\n\n\nwhere the key word is the concept of a \\textit{domain}, which is restricted to an open, singly connected subset $D$ of $\\mathbb{C}$. However, the hypotheses for this usual statement can be softened considerably \\cite[p.~95]{noguchi_complex_analysis}: the agreement over a line can be loosened to agreement over a sequence $(s_n)_{n=0}^\\infty \\subset D$ that converges to a point $s_n\\to s\\in D$, or, in other words,\n%%% also http://www.unc.edu/math/Faculty/met/complex.pdf\n\n\\begin{theorem}\nA function that is analytic in a domain $D$ is uniquely determined over $D$ by its values on any set $S\\subset D$ which has an accumulation point in $D$.\n\\end{theorem}\n\n\nThis is, again, an expression of the rigidity of the theory of analytical functions, especially when compared to the study of continuously differentiable real functions, where no similar result is even remotely true. Complex analytical functions, being the solutions of a differential equation, are much more constrained by their values on the boundary or subparts of a domain.\n\n\\end{mathaside}\n\n\n\n\nNow that we have suitable analytical continuations of at least some reasonable charge distributions, the next thing to investigate is their behaviour as functions of $\\vbr$. The first thing to try is to look at their behaviour over real coordinates, and here both potentials look remarkably similar (modulo some leeway on how to relate the $1/e$ widths $\\sigma$ and $\\alpha$ of the two charge distributions), as shown in \\reffig{f4-exact-gaussian-vs-exponential-real-coordinates}. \n\n\\begin{figure}[htb]\n  \\centering\n  \\begin{tabular}{c}\n  \\subfigure{  \n    \\includegraphics[scale=1]{4-Potentials/Figures/figure4Ca.pdf}\n    \\label{f4-potential-comparison} \n  }\n  \\\\[-5mm]\n  \\subfigure{\n    \\includegraphics[scale=1]{4-Potentials/Figures/figure4Cb.pdf}\n    \\label{f4-charge-density-comparison} \n  }\n  \\end{tabular}\n  \\caption[Exact electrostatic potentials $\\Vg(\\vbr)$ and $\\Ve(\\vbr)$, for gaussian and exponential charge densities, over real coordinates]{\n  Exact electrostatic potentials $\\Vg(\\vbr)$ (blue) and $\\Ve(\\vbr)$ (red) as a function of real coordinates, for equal total charges $Q=1$ and with the $1/e$ widths $\\sigma=1$ and $\\alpha=\\sqrt{\\pi}/4$ chosen so the potentials will match at the origin. The corresponding charge distributions are shown~in~\\protect\\subref{f4-charge-density-comparison}.}\n  \\label{f4-exact-gaussian-vs-exponential-real-coordinates}\n\\end{figure}\n\n\nIn general, gaussian distributions are rather different to Slater-type exponential orbitals, because they lack the latter's cusp at the origin, and they have markedly thinner tails at the edges. Nevertheless, if we relate the two widths by asking that the potential at the origin $V(\\mathbf 0)$ be the same for both distributions, we get relatively similar charge distributions, as shown in \\reffig{f4-charge-density-comparison}, and the remarkably similar electrostatic potentials of~\\reffig{f4-potential-comparison}. Since the charge distributions are relatively similar blobs for both cases, we can hope that their potentials will also have similar behaviour for complex coordinates.\n\n\n\n\n\n\nUnfortunately, the similarities between the two potentials end there, and when we look at their behaviour for complex coordinates we get completely different structure, shown in \\reffig{f4-exact-gaussian-vs-exponential-complex-coordinates}.\n\n\n\n\\begin{figure}[htb]\n  \\centering\n  \\begin{tabular}{cc}\n  (a) $\\Re(\\Vg(\\vbr))$ & (b) $\\Im(\\Vg(\\vbr))$ \\\\[-2mm]\n  \\subfigure{\n    \\label{f4-re-vg-over-complex-coords}\n    \\includegraphics[scale=1]{4-Potentials/Figures/figure4Da.pdf}\n  }\n  &\n  \\subfigure{\n    \\label{f4-im-vg-over-complex-coords}\n    \\includegraphics[scale=1]{4-Potentials/Figures/figure4Db.pdf}\n  }\n  \\\\\n  (c) $\\Re(\\Ve(\\vbr))$ & (d) $\\Im(\\Ve(\\vbr))$ \\\\[-2mm]\n  \\subfigure{\n    \\label{f4-re-ve-over-complex-coords}\n    \\includegraphics[scale=1]{4-Potentials/Figures/figure4Dc.pdf}\n  }\n  &\n  \\subfigure{\n    \\label{f4-im-ve-over-complex-coords}\n    \\includegraphics[scale=1]{4-Potentials/Figures/figure4Dd.pdf}\n  }\n  \\end{tabular}\n  \\caption[Exact electrostatic potentials $\\Vg(\\vbr)$ and $\\Ve(\\vbr)$, for gaussian and exponential charge distributions, over complex coordinates]{\n  Exact electrostatic potentials $\\Vg(\\vbr)$ and $\\Ve(\\vbr)$ over complex coordinates, with the same cut over complex space as Figs.~\\ref{f4-numerical-potential-from-gaussian} and \\ref{f4-cauchy-riemann-for-numerical-gaussian}. The potential $\\Vg(\\vbr)$ from a gaussian charge distribution diverges at imaginary coordinates, while the potential $\\Ve(\\vbr)$ from an exponential distribution has a branch cut there.\n  }\n  \\label{f4-exact-gaussian-vs-exponential-complex-coordinates}\n\\end{figure}\n\n\nPerhaps the most salient feature of both of these potentials is the stark divergence of the exact gaussian potential $\\Vg(\\vbr)$ as the imaginary part of $z$ increases, which immediately becomes unmanageable regardless of the scale on the vertical axis. This can be seen quite clearly from the asymptotic expansion for the error function \\citenisteq{7.12.1}, which at large and real argument describes a gaussian approach from below to 1, but inherits this $e^{-z^2}$ behaviour for the entire complex plane:\n\\begin{equation}\n\\erf(z) \\sim 1 - \\frac{e^{-z^2}}{\\sqrt{\\pi}} \\left( 1- \\frac{1}{z} + \\frac{1}{2z^2} - \\cdots \\right)\n\\label{e4-erf-asymptotic-expansion}\n\\end{equation}\nwhenever $|\\arg(z)| < \\frac{3\\pi}{4}$. In the potential $\\Vg(\\vbr)$ from \\eqref{e4-exact-gaussian-potential}, the error function is called with $r=\\sqrt{x^2+y^2+z^2}$ as an argument, which means that for large $|z|$ it behaves as $\\exp((\\Im(z)^2-\\Re(z)^2)/\\sigma^2)$, and if the imaginary part of $z$ is large enough then $\\Vg(\\vbr)$ will diverge in a super-gaussian fashion. This strong divergence is then responsible for the wall-like behaviour shown in Figs.~\\ref{f4-re-vg-over-complex-coords} and \\ref{f4-im-vg-over-complex-coords}. Finally, to add a slight insult to the injury, the complex exponential also oscillates ever more wildly in this region.\n\n\n\nThe potential for the exponential distribution, $\\Ve(\\vbr)$, on the other hand, has much more bounded behaviour, but instead of a divergence to infinity it now fills up its interestingness quota with a pair of branch cuts that stretch from $z=\\pm i x$ to imaginary infinity. These branch cuts are, in fact, rather natural, because the potential is a function of $r=\\sqrt{x^2+y^2+z^2}$, which itself has a sign-change branch cut when its argument is~negative.\n\n\nIt is worth asking at this stage why the gaussian potential $\\Vg(\\vbr)$ does not exhibit any branch cuts on its domain: after all, it is a function of $r$ just as much as $\\Ve(\\vbr)$. The reason for this is that the error function is a pure odd function, and it therefore has a Taylor expansion \\citenisteq{7.6.1} of the form\n\\begin{equation}\n\\erf(z)\n=\\frac{2}{\\sqrt{\\pi}}\\left( z - \\frac{z^3}{3} + \\frac{z^5}{10} - \\cdots \\right)\n.\n\\end{equation}\nThis means, in turn, that the gaussian potential \\eqref{e4-exact-gaussian-potential} also has a Taylor series of definite parity,\n\\begin{equation}\n\\Vg(\\vbr) \n=\nQ \\frac{ \\erf(r/\\sigma) }{ r }\n=\n\\frac{2Q}{\\sqrt{\\pi}\\sigma}\\left( 1 - \\frac{r^2}{3\\sigma^2} + \\frac{r^4}{10\\sigma^4} - \\cdots \\right)\n,\n\\end{equation}\nexcept that now $\\Vg(\\vbr)$ is a pure even function, so it is a function of $r^2$. Since $r^2$ has no branch cuts, $\\Vg(\\vbr)$ cannot have any either. It is this sort of subtle difference in the potentials' behaviour for real coordinates that causes the stark differences at complex coordinates shown in \\reffig{f4-exact-gaussian-vs-exponential-complex-coordinates}.\n\n\nThe divergence in behaviour of our two potentials at complex coordinates is definitely worrisome, since they are both more or less reasonable models for real-world charge distributions. Gaussian and exponential-type orbitals are the general building blocks of quantum chemistry, and while they are certainly not interchangeable (with a definite conceptual advantage to exponential charges, since the gaussian distributions lack the cusps and long tails expected of real-world orbitals), as far as real-coordinates electrostatics is concerned they are both essentially blobs of charge that produce very similar electrostatic potentials. \n\n\nIt is also important to note that this difference in behaviour is quite certain to persist through most of the common modifications to our model charge distributions. On the simplest level, the addition of polynomial factors to a gaussian charge is exactly equivalent to taking its derivatives, which means that the overall (super-)gaussian factor will always be present. A similar, more involved argument holds for exponential orbitals.\n\nOn a slightly higher level, it is also impossible to get radically different behaviour from any finite collection of gaussians, since the linearity of Poisson's equation implies that the potential will be the corresponding linear combination of $\\Vg(\\vbr)$'s, and it is essentially impossible for such a function to be well-behaved everywhere, since it is an entire function and we know it decays as $1/r$ or faster in all real directions, so it needs to diverge to infinity at large imaginary coordinates. \n\nMoreover, the behaviour at large imaginary coordinates will be dominated by the contributions from the tightest gaussians in the basis set, because these will have the shortest length scales $\\sigma$, and that means that their corresponding potentials $\\Vg(\\vbr)\\sim \\exp(+\\Im(\\vbr)^2/\\sigma^2)$ will be the fastest to explode. While there will probably be at least two of these at the same width, they are overwhelmingly unlikely to contribute in such a way that their divergences will cancel out, especially when probed over all possible lines on real space and all possible directions in the complex continuation of that real cut.  This argument, moreover, extends to transition charges that integrate to zero total charge.\n\n\n\nGiven that $\\Vg(\\vbr)$ and $\\Ve(\\vbr)$ produce wildly different potentials for complex coordinates, we are now left with the even bigger question of what should be the general features to expect of the complex-coordinates electrostatic potential $V(\\vbr)$ for a realistic charge distribution -- should it have branch cuts? should it diverge exponentially? super-exponentially? should it have poles, while we're at this? -- and we are left with precious few tools to answer this question.\n\n\n\n\\begin{figure}[!htbp]\n  \\centering\n  \\begin{tabular}{cc}\n  (a) $\\Re(\\Vg(\\vbr))$ & (b) $\\Im(\\Vg(\\vbr))$ \\\\[-1mm]\n  \\subfigure{\n    \\label{f4-potentials-comparison-restricted-complex-coordinates-a}\n    \\includegraphics[scale=1]{4-Potentials/Figures/figure4Ea.pdf}\n  }\n  &\n  \\subfigure{\n    \\label{f4-potentials-comparison-restricted-complex-coordinates-b}\n    \\includegraphics[scale=1]{4-Potentials/Figures/figure4Eb.pdf}\n  }\n  \\\\\n  (c) $\\Re(\\Ve(\\vbr))$ & (d) $\\Im(\\Ve(\\vbr))$ \\\\[-1mm]\n  \\subfigure{\n    \\label{f4-potentials-comparison-restricted-complex-coordinates-c}\n    \\includegraphics[scale=1]{4-Potentials/Figures/figure4Ec.pdf}\n  }\n  &\n  \\subfigure{\n    \\label{f4-potentials-comparison-restricted-complex-coordinates-d}\n    \\includegraphics[scale=1]{4-Potentials/Figures/figure4Ed.pdf}\n  }\n  \\\\\n  (e) $\\Re(\\Vgnum(\\vbr))$ & (f) $\\Im(\\Vgnum(\\vbr))$ \\\\[-1mm]\n  \\subfigure{\n    \\label{f4-potentials-comparison-restricted-complex-coordinates-e}\n    \\includegraphics[scale=1]{4-Potentials/Figures/figure4Ee.pdf}\n  }\n  &\n  \\subfigure{\n    \\label{f4-potentials-comparison-restricted-complex-coordinates-f}\n    \\includegraphics[scale=1]{4-Potentials/Figures/figure4Ef.pdf}\n  }\n  \\end{tabular}\n  \\caption[Electrostatic potentials $\\Vg(\\vbr)$, $\\Ve(\\vbr)$ and $\\Vgnum(\\vbr)$ over complex coordinates restricted to $\\Re(\\vbr^2)>0$]{\n  Exact electrostatic potentials $\\Vg(\\vbr)$ and $\\Ve(\\vbr)$ over complex coordinates (\\hyperref[f4-potentials-comparison-restricted-complex-coordinates-a]{a}-\\hyperref[f4-potentials-comparison-restricted-complex-coordinates-d]{d}), exactly as in \\reffig{f4-exact-gaussian-vs-exponential-complex-coordinates}, but restricted to the region $\\Re(\\vbr^2)>0$. Despite their disagreements in coordinates that are `too imaginary' (in the sense that $\\Re(\\vbr^2)=\\Re(\\vbr)^2-\\Im(\\vbr)^2<0$), both potentials agree quite well here. (We show their close quantitative agreement in \\reffig{f4-quantitative-agreements-between-potentials}.) In addition, they also agree relatively well (particularly when away from the boundary) with the numerically-integrated $\\Vgnum(\\vbr)$ of Section~\\ref{sec:quantum-chemical-potentials-complex}, shown in~\\subref{f4-potentials-comparison-restricted-complex-coordinates-e} and~\\subref{f4-potentials-comparison-restricted-complex-coordinates-f}; this means that $\\Vgnum(\\vbr)$ is also a relatively reasonable model in that~region, though its much higher computational cost and worse analyticity properties render it a bad choice.}\n  \\label{f4-potentials-comparison-restricted-complex-coordinates}\n\\end{figure}\n\n\nThe one saving grace of this problem is that the differences in behaviour are confined to very identifiable regions in complex $\\vbr$ space. The complex-coordinates electrostatic potentials shown in \\reffig{f4-exact-gaussian-vs-exponential-complex-coordinates} look very different, but this masks somewhat the fact that, if you ignore the regions where $\\Vg(\\vbr)$ behaves wildly, then the two potentials actually agree rather closely, both qualitatively and quantitatively. The regions where this happens are easily pointed out through the asymptotic expansion \\eqref{e4-erf-asymptotic-expansion} for $\\erf(r/\\sigma)$, which makes it clear that, as long as\n%\n\\begin{equation}\n\\Re(\\vbr^2)>0,\n\\label{e4-re-r2-less-than-0}\n\\end{equation}\n%\nthen the exponential term is decaying and $\\Vg(\\vbr)$ should be well-behaved. As we shall see, the restriction \\eqref{e4-re-r2-less-than-0} will be a driving consideration hereafter.\n\nIn the meantime, we can begin by looking at the potentials we have so far when restricted to this region, and these are shown in \\reffig{f4-potentials-comparison-restricted-complex-coordinates}. Once the region with the $\\Vg(\\vbr)$ divergence, and the $\\Ve(\\vbr)$ branch cut, is removed, both potentials have essentially the same shape, and indeed even quantitatively match to a remarkable degree, as shown in \\reffig{f4-quantitative-agreements-between-potentials}. Even more notably, both exact potentials also show a good match to the numerically-integrated $\\Vg(\\vbr)$ in this~region.\n\n\n\n\\begin{figure}[!htbp]\n  \\centering\n  \\begin{tabular}{cc}\n  (a) $|\\Ve(\\vbr)-\\Vg(\\vbr)|/|\\Vg(\\vbr)|$ & \n  (b) $|\\Vgnum(\\vbr)-\\Vg(\\vbr)|/|\\Vg(\\vbr)$ \\\\[-2mm]\n  \\subfigure{\n    \\includegraphics[scale=1]{4-Potentials/Figures/figure4Fa.png}\n  }\n  &\n  \\subfigure{\n    \\includegraphics[scale=1]{4-Potentials/Figures/figure4Fb.png}\n  }\n  \\end{tabular}\n  \\caption[Residuals between the electrostatic potentials $\\Ve(\\vbr)$ and $\\Vg(\\vbr)$, from exponential and gaussian charges, and $\\Vgnum(\\vbr)$ and $\\Vg(\\vbr)$ from numerical and exact integration for a gaussian charge, showing agreement where $\\Re(\\vbr^2)>0$]{\n  Normalized differences between the exponential-charge potential $\\Vg(\\vbr)$ and the exact gaussian potential $\\Vg(\\vbr)$ as a reference (a), and the numerically-integrated potential $\\Vgnum(\\vbr)$ of section \\ref{sec:quantum-chemical-potentials-complex}, against $\\Vg(\\vbr)$ (b), on a logarithmic scale. The plots use the same cut over complex space as Figs.~\\ref{f4-numerical-potential-from-gaussian}, \\ref{f4-cauchy-riemann-for-numerical-gaussian}, \\ref{f4-exact-gaussian-vs-exponential-complex-coordinates} and \\ref{f4-potentials-comparison-restricted-complex-coordinates} and are (roughly) restricted the allowed region $\\Re(\\vbr^2)>0$ of~\\eqref{e4-re-r2-less-than-0}. The agreement here is not only qualitatively good, as shown in \\reffig{f4-potentials-comparison-restricted-complex-coordinates}, but also quantitatively rather close, with the potentials agreeing to better than 1\\% over large regions. On the other hand, once the mostly-imaginary region $\\Re(\\vbr^2)<0$ is reached, the disagreement rises very steeply.\n  }\n  \\label{f4-quantitative-agreements-between-potentials}\n\\end{figure}\n\n\n\n\nOn the other hand, the close match between the potentials in the region $\\Re(\\vbr^2)>0$ is also a cause for concern, because it carries no warning of the wild disagreements that sprout between them with alarming speed upon leaving this region. If one is using some local method to extend the domain of the electrostatic potential, for example, how is one to detect and handle a sudden, catastrophic blow-up in the potential? It bears emphasizing that the remarkably similar surfaces shown in \\reffig{f4-quantitative-agreements-between-potentials} are solutions of the \\textit{same} rigid differential equation discussed in the Mathematical Aside~\\ref{aside.analytical-continuation} -- a differential equation which enforces the uniqueness of its solutions over their entire domains when given (exact) agreement even at a single accumulation point -- and yet these solutions can still depart from each other, suddenly and steeply, as in \\reffig{f4-exact-gaussian-vs-exponential-complex-coordinates}.\n\n\nGiven all of this, can we say that both $\\Vg(\\vbr)$ and $\\Ve(\\vbr)$ have the ``right'' shapes in the region where $\\Re(\\vbr^2)>0$, if their minute differences can lead to wildly different behaviour at a moment's notice? If it is possible to talk about a ``correct'' shape, which one is it? If both can be right depending on circumstances, which one should we use to set expectations for the physical charge density in a real-world molecule?\n\n\n\n\n\n\n\\section{Outlook}\nIn the end, unfortunately, none of these questions have any easy answers. Simply put, the theory of analytical functions is just too rigid, and depends too delicately on the initial boundary values, to say anything of consequence about the global behaviour of a general electrostatic potential $V(\\vbr)$ over the entirety of complex $\\vbr$ space, and the overall recommendation is to stay, whenever possible, in the `safe' region\n\\begin{equation}\n\\Re(\\vbr^2)>0,\n\\backtag{e4-re-r2-less-than-0}\n\\end{equation}\nwhere the different approaches agree.\n\nOne might also ask, at this point, for what evidence we have that the problem is even solvable: to what extent do we know that there even exists an analytical continuation for the electrostatic potential $V(\\vbr)$ of a generic real-world (transition) charge density $\\rho(\\vbr)$? Here (regardless of whether this is fortunate or unfortunate) the answer is positive: in general, this analytical continuation does exist, at least for some open set about the real~slice of complex $\\vbr$ space.\n\n\nThe reason for this is that the electrostatic potential $V(\\vbr)$ is a solution of the Poisson equation~\\eqref{e4-poisson-equation}, and it therefore gets many of its properties from the robust structure of the Laplacian operator; more specifically, the Laplacian is required to have analytic solutions whenever the right-hand side is analytic. Similarly, this right-hand-side function $\\rho(\\vbr)$ is obtained from the eigenfunctions of the time-independent Schrödinger equation on multiple dimensions,%\n\\footnote{%\nThis does entail a nontrivial step in showing that an analytical solution of the Schrödinger equation give an analytical charge density, since expressions of the form $\\phi_m(\\vbr)^* \\phi_n(\\vbr)$ include a complex conjugation that can destroy the analyticity if not done correctly. Fortunately, this can be done easily by extending functions of the form $\\phi_m(\\vbr)^*$ to the complex plane as $\\phi_m(\\vbr^*)^*$, which is analytic by the Schwarz reflection principle~\\cite[p.~119-120]{noguchi_complex_analysis}.\n}\nand again the Schrödinger multi-electron Hamiltonian is generally regular enough that its eigenfunctions are analytic.\n\n\n\n\\begin{mathaside}{Analytic regularity of elliptic operators}\n\\label{aside.elliptic-regularity}\n\nAs a final building block of the mathematics that underpins this chapter, it is also worth detailing the results that guarantee the existence of the analytical continuations of the electrostatic potentials $V(\\vbr)$ that we need. The main such result is the Elliptic Regularity Theorem, which governs the regularity of solutions of elliptic partial differential equations; it can be phrased in a number of ways but a suitably strong one is provided by L. Hörmander in \\citer{hormander_pdes}, p.~178, as the following theorem:\n\n\\begin{theorem}\nLet $P(x, D)$ be an elliptic differential operator in $D$ with coefficients that are analytic in $D$. If $u\\in \\mathscr D'(\\Omega)$ and \n\\begin{equation}\nP(x, D)u = f \n\\end{equation}\nwhere $f$ is also analytic in $\\Omega$, then $u$ is analytic in $\\Omega$. \n\\end{theorem}\n\n\nHere $\\mathscr D'(\\Omega)$ denotes the set of all distributions over $\\Omega$ (formally defined as a set of suitably bounded linear functionals $u\\colon C_0^\\infty(\\Omega) \\to \\mathbb{C}$), but the requirement that $f$ and $u$ be analytical turns them into regular functions over $\\Omega$ and fulfils the boundedness condition on the distribution. %\\\\[-8pt]\n\n%\n%Theorems of this form, guaranteeing differentiability properties of the solution $u$ to a partial differential equation $P(x,D)u=f$ with a well-behaved right-hand side $f$, are generally known as regularity theorems, and they typically hold strictly for elliptic operators. In particular, the Elliptic Regularity Theorem guarantees a smooth solution to elliptic PDEs whenever the right-hand side is smooth, and in general operators with this property are called hypoelliptic. Similarly, the stronger requirement of analytical solutions to analytical initial data is termed analytic hypoellipticity.\n\n\\vspace{\\maskip}\nIn particular, both the Schrödinger and the Poisson equations are of this form (once one excludes the Coulomb singularities), since they are both elliptic and have analytical coefficients and right-hand sides, so both are required to have analytical solutions.\n\n\\end{mathaside}\n\n\n\nWe have, then, the promise from an existence theorem that, given an idealized real-world (transition) charge density $\\rho(\\vbr)$, there should be a Platonic `true' analytical continuation of the relevant electrostatic potential $V(\\vbr)$: the multi-electron Hamiltonian has analytical true eigenfunctions, which combine into an analytical charge density, and this then gives an analytical electrostatic potential. However, we have no way to find this `true' potential (which is relatively reasonable, as we cannot even find the true eigenfunctions) or even have any idea of what it should behave like, let alone find reasonable approximations for it (and this does break the usual paradigms).\n\nOne could think, for example, that to find an analytical continuation it would hopefully be good enough to find chemical data for the charge density and the electrostatic potential for real coordinates which was accurate enough, and then if necessary perform a numerical solution of the Cauchy-Riemann equations for these data. Unfortunately, such an effort is doomed to fail: the numerical solution of the Cauchy-Riemann problem is likely to prove a stiff, unstable problem, because -- as demonstrated in Figs.~\\ref{f4-potentials-comparison-restricted-complex-coordinates} and \\ref{f4-exact-gaussian-vs-exponential-complex-coordinates} -- very similar initial conditions can lead to very sudden, unexpected divergences, even for exactly-known potentials.\n\nMoreover, even if we \\textit{could} somehow perform this numerical solution of the Cauchy-Riemann equations to arbitrary accuracy over the entire complex plane, we would still be left with the wrong solution. This is because the quantum chemical data, in the end, produces a charge density $\\rho(\\vbr)$ which is ultimately a sum of gaussian-type distributions. To be sure, these will come in many places and sizes, to approximate to high accuracy the long tails and the sharp cusps of the expected real-world distribution, but in the end it will still be a finite superposition of gaussians, and the exact solution will still be the corresponding finite superposition of~$\\Vg(\\vbr)$s. \n\nThus, it is conceivable that we could succeed in numerically solving the Cauchy-Riemann problem to accuracy close enough to the exact solution -- but we already know what this exact solution looks like: it is the relevant superposition of gaussian potentials $\\Vg(\\vbr)$ from \\eqref{e4-exact-gaussian-potential}, and we know that these potentials diverge when $\\Re(\\vbr^2)<0$ as shown in~\\reffig{f4-exact-gaussian-vs-exponential-complex-coordinates}, and that they do not match the exponential model which is more physically reasonable.\n\nSimilarly, one might hope that for a real molecule these divergences would cancel out in some way, but as we have seen, this is very unlikely. Instead, large $\\Im(\\vbr)$ any superposition-of-$\\Vg(\\vbr)$s potential will be dominated by the contribution from the smallest gaussians, which are typically used to approximate the cusps at the nuclei, since these will have the shortest length scales $\\sigma$, and therefore their corresponding potentials $\\Vg(\\vbr)\\sim \\exp(+\\Im(\\vbr)^2/\\sigma^2)$ will be the fastest to explode.\n\n\nEven worse, the close match between $\\Ve(\\vbr)$ and $\\Vg(\\vbr)$ in the allowed region bodes ill for any finitary approach to the potential through the charge distribution. To see this, suppose that we are given a guarantee of a uniform approximation to the Platonic charge density $\\rho(\\vbr)$, represented as a finite sum of manageable charge densities $\\rho_i(\\vbr)$. This is a rather reasonable thing to assume, and it is attained, for example, when solving for $\\rho(\\vbr)$ through Slater-type quantum chemical methods, which offer guarantees of the form $\\left|\\rho(\\vbr)-\\sum_i\\rho_i(\\vbr)\\right|<\\eps$, where $\\eps$ is a numerical precision that can be set arbitrarily small (with a corresponding increase in the size and complexity of $\\sum_i\\rho_i(\\vbr)$), and moreover the approximation is guaranteed for \\textit{all} positions $\\vbr$. Even a situation this ideal, however, fails to exclude the possibility that the Platonic charge density be equal to $\\rho(\\vbr) = \\sum_i\\rho_i(\\vbr) + \\eps'\\rho_g(\\vbr)$: the manageable numerical $\\sum_i\\rho_i(\\vbr)$, with a small gaussian addendum $\\eps'\\rho_g(\\vbr)$ which is bounded below $\\eps$ for all real positions, but which will still quickly dominate the potential at imaginary positions that are large enough.\n\n\n\nThis therefore means that, although exponential charge densities are probably the most physically correct models for the Platonic charge distribution -- the one obtained mathematically from the regularity of the Schrödinger equation --, there is still uncertainty as to how well they extend to the complex plane. \n\nMore mathematically, this means that while analytical continuation is possible and exact when we know the exact function we want to continue analytically, the use of finitely accurate data on a limited number of sample points to attempt an analytical continuation to the whole of the complex plane is, in the absence of very strict guarantees on the function we're approximating, bound to fail at least some of the time.\n\n\n\n\nWe see, then, that roughly half of complex $\\vbr$ space is closed to the means of inquiry we have available to us, and we need to stay in the allowed region if we want to have meaningful electrostatic potentials from our transition charges.\n\nHowever, in contrast with the bleak landscape presented above, the assumption of an exponential charge is in fact fairly reasonable, and the remarkably close agreement between the potentials as displayed in \\reffig{f4-potentials-comparison-restricted-complex-coordinates} is a very encouraging sign that, within the allowed region, it is actually quite reasonable to assume that we've got the correct potential, even if we're using gaussian-based quantum chemical charge distributions.\n\nMoreover, we also have a very clean criterion -- whether $\\Re(\\vbr^2)>0$ or not -- to tell whether we are in the allowed region, and we can use this information to help shape the complex-space trajectory $\\rl(t)$ that we will actually use to probe the potential. In addition to this clear bound, in the next chapter we will show that it is in fact possible to choose the integration path in the complex time plane in a way that keeps the position-space trajectory completely within the allowed region, and that therefore the problematic cases never arise. \n\nIn other words, the semiclassical quantum mechanics of complex-valued trajectories need to be handled carefully, and we have seen the serious breakdowns that can occur when one pushes too far, but we can also be fairly confident that within the bounds that we have described the behaviour will be manageable, and we will show in chapter~\\ref{chap:quantum-orbits} how to ensure that the trajectory remains within those bounds.\n\n\nFinally, and as an added bonus, we also get that as long as we stay in the allowed region, we can safely use the exact potentials $\\Vg(\\vbr)$ for each of the gaussian building blocks of any quantum chemical charge distributions, and this spares us the need of any numerical integration (which was ultimately doomed to produce non-analytical results in the first place), which therefore considerably speeds up the calculations of the ARM correlation-driven ionization yield, since we now require only a few queries of the $\\Vg(\\vbr)$ per temporal integration point, instead of iterating over a full numerical integration.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n   ", "meta": {"hexsha": "330665d3f685bcd5a5e102f6fec769e65fba9e09", "size": 63461, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "4-Potentials/Potentials.tex", "max_stars_repo_name": "episanty/PhD-Thesis", "max_stars_repo_head_hexsha": "3347dfb59c11db5572a4139ee3b784ad56260e76", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2016-11-16T19:28:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T12:32:56.000Z", "max_issues_repo_path": "4-Potentials/Potentials.tex", "max_issues_repo_name": "episanty/PhD-Thesis", "max_issues_repo_head_hexsha": "3347dfb59c11db5572a4139ee3b784ad56260e76", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2017-02-22T19:26:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-31T16:38:58.000Z", "max_forks_repo_path": "4-Potentials/Potentials.tex", "max_forks_repo_name": "episanty/PhD-Thesis", "max_forks_repo_head_hexsha": "3347dfb59c11db5572a4139ee3b784ad56260e76", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-12-17T06:06:55.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-26T11:08:08.000Z", "avg_line_length": 77.6756425949, "max_line_length": 1266, "alphanum_fraction": 0.7594585651, "num_tokens": 16855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.3402915684082043}}
{"text": "\n%!TEX root = ../PhD_thesis__Lilian_Besson\n\n% \\chapter{Non-Stationary MAB Models and Possible Applications for IoT Networks}\n% \\chapter{The Piece-wise Stationary MAB Model and the GLR-klUCB Algorithm}\n% \\chapter{Piece-Wise Stationary Multi-Armed Bandits}\n\\chapter{Piece-Wise Stationary Bandits}\n\\label{chapter:6}\n\n\\graphicspath{{2-Chapters/6-Chapter/Images/}}\n\n\\abstractStartChapter{}%\n%\nIn this last chapter, we are also interested in a more formal approach to the decentralized learning problem presented in Chapter~\\ref{chapter:4}.\nInstead of keeping the stationary hypothesis but considering $2 \\leq M \\leq K$ devices accessing a wireless networks with $K$ orthogonal frequency channels, as we did in Chapter~\\ref{chapter:5}, we are now interested in another direction of formal analysis of the intractable models of IoT networks of Chapter~\\ref{chapter:4}.\n%\nWe study a generalization of the single-player stationary bandit model,\nto account for possible non-stationarity of the rewards.\n% % that is, for problems that could be tackled with MAB algorithms.\n% Instead of dealing with changes happening possibly at every time step, like in adversarial models, we rather consider a finite small number $\\Upsilon_T$ of \\emph{change-points}, and we consider problems that are stationary on any interval between two consecutive change-points.\n%\nWe review existing works on piece-wise stationary MAB models,\n% for which the two main families of proposed solutions are either passively or actively adaptive. In practice, it was already observed that actively adaptive strategies usually greatly outperform the passively adaptive ones.\n% The more efficient strategies from the current state-of-the-art are based on a combination of an efficient algorithm for the stationary problem with an efficient online change detection algorithm, like CUSUM, PHT or the Generalized Likelihood Ratio Test (GLRT), and so we pursue on this direction.\n%\nthen we study the Generalized Likelihood Ratio Test (GLRT) for\n% Using finite-time results of a recent paper studying the GLRT for sub-Gaussian distributions, we then extend the results to the GLRT for any\nbounded or sub-Bernoulli distributions.\nWe are able to prove finite-time guarantees for our test,\n% its \\emph{false alarm probability}, meaning that in a stationary model, the test should not detect any change,\n% and its \\emph{detection delay}, meaning that in a model with a change-point, the test should detect within a reasonable delay.\n%\non its \\emph{false alarm probability} and \\emph{detection delay}, and can be combined with an efficient bandit policy (\\klUCB), to propose an efficient algorithm for piece-wise stationary problems, \\GLRklUCB.\n% Our policy takes ideas from the two most recent and most efficient policies, \\CUSUMUCB{} and \\MUCB, that enjoys good regret bounds of the order of $R_T = \\bigO{\\sqrt{\\Upsilon_T T \\log(T)}}$, if $T$ is the horizon and $\\Upsilon_T$ the number of change-points (known beforehand).\n% % \\MUCB{} restarts the underlying \\UCB{} bandit policy on all arms when a change is detected, while \\CUSUMUCB{} restarts the observations of only the arm on which a change is detected.\n%\n% We give the first unified analysis of a piece-wise stationary bandit algorithm for the two variants, and our analysis\nWe analyze its regret, and show that it achieves state-of-the-art finite-time regret bounds.\n% and yield regret bounds with explicit constants.\n% Moreover, our regret bounds are the first ones to be of the order $\\bigO{\\sqrt{\\Upsilon_T T \\log(T)}}$, when the algorithm runs with no prior knowledge of the problem other than the horizon $T$ and the number of change-points $\\Upsilon_T$ (both \\MUCB{} and \\CUSUMUCB{} require to know beforehand a certain measure $\\Delta^{\\text{change}}$ of the difficulty of the problem).\n%\nFinally, we showcase numerical experiments on which our approach outperform other state-of-the-art solutions.\n% , on different piece-wise stationary bandit problems.\n% % , of increasing difficulty.\n% %\n% We also include additional details about our policy \\GLRklUCB, including a sensitivity analysis of its two parameters, a numerical evaluation of its time and memory costs, as well as details on an easy but efficient way to speed up the B-GLRT test while not loosing too much in terms of regrets.\n\n\\minitocStartChapter{}\n\n% This chapter is basically a raw include from my paper ``The Generalized Likelihood Ratio Test meets klUCB: an Improved Algorithm for Piece-Wise Non-Stationary Bandits'', see https://hal.inria.fr/hal-02006471\n\n\\input{2-Chapters/6-Chapter/nonstatbandits/NonStatB.tex}\n\n\n% % ----------------------------------------------------------------------------\n% \\section{Conclusion}\n% \\label{sec:6:conclusion}\n\n% In this chapter, we saw...\n\n% Future works include...\n\n\n\\newpage\n% ----------------------------------------------------------------------------\n\\section{Appendix}\n\\label{sec:6:appendix}\n\nWe start by including figures as complementary illustrations to the numerical results presented in Section~\\ref{sec:6:NumericalExperiments} above.\nWe then give some additional useful results, along with their proofs, and then we give complementary numerical experiments to justify some choices made in the presentation of our proposal \\GLRklUCB.\n\n\\input{2-Chapters/6-Chapter/nonstatbandits/NonStatB_appendix.tex}\n\n\n\\vfill{}\n\n\\hr{}\n\\begin{small}\n    \\begin{quote}\n        % https://fr.wikiquote.org/wiki/Kaamelott/\n        \\emph{-- Par exemple, vous prenez aujourd’hui. Vous comptez sept jours. Ça vous emmène dans une semaine. Et bien on sera exactement le même jour qu’aujourd’hui\\dots{} À une vache près, hein… C’est pas une science exacte.}\\\\\n        Karadoc, interprété par Jean-Christophe Hembert,\\\\\n        \\emph{Kaamelott}, Livre II, ``Sept cent quarante-quatre''.\n\n        % \\emph{-- Les chiffres, c'est pas une science exacte figurez-vous !}\\\\\n        % Karadoc, interprété par Jean-Christophe Hembert,\\\\\n        % \\emph{Kaamelott}, Livre V, ``Le dernier recours''.\n    \\end{quote}\n\\end{small}\n", "meta": {"hexsha": "306951d0f4ccbe4aede4202df0b0541ecb04392b", "size": 6021, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "2-Chapters/6-Chapter/chapter6.tex", "max_stars_repo_name": "Naereen/phd-thesis", "max_stars_repo_head_hexsha": "0fa93ca0d738771f4215bc4aeb66157f2026ba00", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-11-18T12:22:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T19:29:48.000Z", "max_issues_repo_path": "2-Chapters/6-Chapter/chapter6.tex", "max_issues_repo_name": "Naereen/phd-thesis", "max_issues_repo_head_hexsha": "0fa93ca0d738771f4215bc4aeb66157f2026ba00", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-11-18T09:19:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-08T14:13:08.000Z", "max_forks_repo_path": "2-Chapters/6-Chapter/chapter6.tex", "max_forks_repo_name": "Naereen/phd-thesis", "max_forks_repo_head_hexsha": "0fa93ca0d738771f4215bc4aeb66157f2026ba00", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-05-28T20:56:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-13T11:11:57.000Z", "avg_line_length": 66.9, "max_line_length": 375, "alphanum_fraction": 0.7522006311, "num_tokens": 1422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.34023178236994955}}
{"text": "\\documentclass[letterpaper,10pt]{article}\n\\usepackage[margin=2cm]{geometry}\n\n\\usepackage{graphicx}\n\\usepackage{amsmath}\n\\usepackage{amsfonts}\n\\usepackage{amssymb}\n\\usepackage[colorlinks]{hyperref}\n\\usepackage{listings}\n\n\\newcommand{\\panhline}{\\begin{center}\\rule{\\textwidth}{1pt}\\end{center}}\n\n\\title{\\textbf{Linear Regression}}\n\\author{Aarti Singh (Instructor), HMW-Alexander (Noter)}\n\n\\begin{document}\n\n\\maketitle\n\n\\panhline\n\\href{../index.html}{Back to Index}\n\n\\panhline\n\\tableofcontents\n\n\\section*{Resources}\n\n\\begin{itemize}\n\t\\item \\href{../../Lectures/04_LinearRegression.pdf}{Lecture}\n\\end{itemize}\n\n\\panhline\n\n\\section{Discrete to Continuous Labels}\n\t\nFrom classification to regression\n\n\\subsection{Task}\n\nGiven $X\\in \\mathcal{X}$, predict $Y \\in \\mathcal{Y}$, Construct prediction rule $f:\\mathcal{X} \\rightarrow \\mathcal{Y}$\n\n\\subsection{Performance Measure}\n\n\\begin{itemize}\n\t\\item Quantifies knowledge gained.\n\t\\item Measure of closeness between true label Y and prediction f(X)\n\t\\begin{itemize}\n\t\t\\item 0/1 lose:$loss(Y,f(X))=1_{f(X)\\neq Y}$. Risk: probability of error \n\t\t\\item square loss: $loss(Y,f(X))=(f(X)-Y)^2$. Risk: mean square error\n\t\\end{itemize}\n\t\\item How well does the predictor perform on average?\n\t$$Risk~R(f)=\\mathbb{E}[loss(Y,f(X))],~(X,Y)\\sim P_{XY}$$\n\\end{itemize}\n\n\\subsection{Bayes Optimal Rule}\n\n\\begin{itemize}\n\t\\item ideal goal: Construct prediction rule $f^*:\\mathcal{X}\\rightarrow\\mathcal{Y}$\n\t$$f^*=\\arg\\min_f{E_{XY}[loss(Y,f(X))]}$$ (Bayes optimal rule)\n\t\\item Best possible performance:\n\t$$\\forall f,~R(f^*) \\leq R(f)$$ (Bayes Risk)\n\\end{itemize}\n\nProblem: $P_{XY}$ is unknown.\n\nSolution: Training data provides a glimpse of $P_{XY}$\n$$\\text{(observed)~}\\{(X_i,Y_i)\\} \\sim_{i.i.d} P_{XY}\\text{~unknown}$$\n\n\\section{Macine Learning Algortihm}\n\n\\begin{itemize}\n\t\\item Model based approach: use data to learn a model for $P_{XY}$\n\t\\item Model-free approach: use data to learn mapping directly\n\\end{itemize}\n\n\\subsection{Empirical Risk Minimization (model-free)}\n\n\\begin{itemize}\n\t\\item Optimal predictor: $$f^*=\\arg\\min_f{\\mathbb{E}[(f(X)-Y)^2]}$$\n\t\\item Empirical Minimizer: $$\\hat{f}_n=\\arg\\min_{f\\in\\mathcal{F}}\\frac{1}{n}\\sum_{i=1}^{n}(f(X)-Y)^2$$\n\\end{itemize}\n\n$\\mathcal{F}$ is the class of predictors:\n\\begin{itemize}\n\t\\item Linear\n\t\\item Polynomial\n\t\\item Nonlinear\n\\end{itemize}\n\n\\section{Linear Regression}\n\n$$f(\\vec{X})=\\sum_{i=0}^{p}{\\beta_0X^{i}}=\\vec{X}^T\\vec{\\beta},~where~X^0=1,~\\vec{\\beta}=[\\beta_0,\\dots,\\beta_p]^T$$\n\n$$\\hat{\\vec{\\beta}}=\\arg\\min_{\\vec{\\beta}}(A^T\\vec{\\beta}-\\vec{Y})^T(A^T\\vec{\\beta}-\\vec{Y}),~where~A=[\\vec{X_1},\\dots,\\vec{X_n}]$$\n\n$$J(\\beta)=(A^T\\vec{\\beta}-\\vec{Y})^T(A^T\\vec{\\beta}-\\vec{Y})$$\n\n\\begin{equation*}\n\\begin{array}{rcl}\n\\frac{\\partial J(\\vec{\\beta})}{\\partial \\vec{\\beta}} & = & \\frac{\\partial (A^T\\vec{\\beta}-\\vec{Y})^T(A^T\\vec{\\beta}-\\vec{Y})}{\\partial \\vec{\\beta}} \\\\\n& = & \\frac{\\partial (\\vec{\\beta}^TAA^T\\vec{\\beta}-\\vec{\\beta}^TA\\vec{Y}-\\vec{Y}^TA^T\\vec{\\beta}+\\vec{Y}^T\\vec{Y})}{\\vec{\\beta}} \\\\\n& = & (AA^T+(AA^T)^T)\\vec{\\beta}-A\\vec{Y}-A\\vec{Y} \\\\\n& = & 2AA^T\\vec{\\beta}-2A\\vec{Y} = 0 \\\\\n& \\Rightarrow & AA^T\\vec{\\beta}=A\\vec{Y} \\\\\n& \\Rightarrow & \\hat{\\vec{\\beta}}=(AA^T)^{-1}A\\vec{Y},~\\text{if $AA^T$ is invertible}\n\\end{array}\n\\end{equation*}\n\n\\subsection{Gradient Descent}\n\nEven when $AA^T$ is invertible, might be computationally expensive if $A$ is huge; however, $J(\\vec{\\beta})$ is convex\\footnote{A function is called convex if the line joining any two points on the function does not go below the function on the interval formed by these two points.} in $\\beta$.\n\nMinimum of a convex function can be reached by gradient descent algorithm:\n\\begin{itemize}\n\t\\item Initialize: pick $\\vec{w}$ at random\n\t\\item Gradient: $$\\nabla_{\\vec{w}} l(\\vec{w})=[\\frac{\\partial l(\\vec{w})}{\\partial w_0},\\dots,\\frac{\\partial l(\\vec{w})}{\\partial w_d}]^T$$\n\t\\item Update rule: $$\\Delta \\vec{w}=\\eta \\nabla_{\\vec{w}}l(\\vec{w})$$, $$w_i^{t+1} \\leftarrow w_i^t - \\eta \\frac{\\partial l(\\vec{w})}{\\partial w_i}|_t$$\n\t\\item Stop: when some criterion met $\\frac{\\partial l(\\vec{w})}{\\partial w_i}|_t < \\epsilon$\n\\end{itemize}\n\n\n\n\\subsection{If $AA^T$ is not invertible}\n\n$Rank(AA^T)$ = number of non-zero eigenvalues of $AA^T$ = number of non-zero singular values of A $\\leq \\min(n,p)$ since $A$ is $n\\times p$\n\n$$A=U \\Sigma V^T \\Rightarrow AA^T=U\\Sigma^2U^T \\Rightarrow AA^T U = U\\Sigma^2$$\n\n\\subsubsection{Regularized Leasts Squares}\n\nRidge Regression (L2 penalty)\n\n\\begin{equation}\n\\begin{array}{rcl}\n\\hat{\\vec{\\beta}}_{MAP} & = & \\arg\\min_{\\vec{\\beta}}(A^T\\vec{\\beta}-\\vec{Y})^T(A^T\\vec{\\beta}-\\vec{Y}) +\\lambda \\vec{\\beta}^T\\vec{\\beta}~~(\\lambda \\geq 0) \\\\\n& = & (AA^T + \\lambda I)^{-1} A\\vec{Y}\n\\end{array}\n\\end{equation}\n\n$(AA^T + \\lambda I)$ is invertible if $\\lambda > 0$. Proof:\n\\begin{itemize}\n\t\\item the symmetric matrix $AA^T$ is positive-semidefinite matrix, because a matrix is positive-semidefinite iff it arises as the Gram matrix of some set of vectors\\footnote{In contrast to the positive-definite case, these vectors need not be linearly independent.}.\n\t\\item $\\therefore \\forall \\lambda>0~and~\\vec{x}\\neq\\vec{0}$, \n\t$$\\vec{x}^T(AA^T)\\vec{x} = (A^T\\vec{x})^T(A^T\\vec{x}) \\geq 0$$\n\t$$\\vec{x}^T(AA^T+\\lambda I)\\vec{x} = \\vec{x}^T (AA^T) \\vec{x} + \\lambda \\vec{x}^T\\vec{x} >0$$\n\t\\item $\\therefore$ $(AA^T+\\lambda I)$ is positive definite.\n\t\\item $\\therefore$ the eigenvalues of $B=(AA^T+\\lambda I)$ are all positive. $$B\\vec{v}=\\lambda\\vec{v} \\Rightarrow \\vec{v}^T B \\vec{v} = \\lambda >0$$\n\t\\item $\\therefore$ $(AA^T + \\lambda I)$ is invertible if $\\lambda > 0$\n\\end{itemize}\n\n\\subsubsection{Understanding Regularized Least Squared}\n\nWhy we need constraints: r equations, p unknowns - underdetermined system of linear equations. \n\n$$\\min_{\\vec{\\beta}} J(\\beta)+\\lambda pen(\\vec{\\lambda})$$\n\\begin{itemize}\n\t\\item Ridge Regression: $pen(\\beta)=||\\beta||_2^2$\n\t\\item Lasso Regression: $pen(\\beta)=||\\beta||_1$. No closed form solution, but can optimize using sub-gradient descent.\n\t\\item $pen(\\beta)=||\\beta||_0=\\sum 1_{\\beta_i \\neq 0}$\n\\end{itemize}\n\n\\begin{figure}[!h]\n\t\\centering\n\t\\includegraphics[width=10cm]{./img/ridgeregression.png}\n\t\\caption{For Lasso regression, results are in sparse solution - vector with more zero coordinates. Good for high-dimenstional problems - don't have to store all coordinates, interpretable solution! }\n\\end{figure}\n\nMatlab code:\n\\begin{lstlisting}[language=Matlab]\n[B,FitInfo] = lasso(X,Y,Name,Value)\n\\end{lstlisting}\n\\begin{itemize}\n\t\\item X: Numeric matrix with n rows and p columns. Each row represents one observation, and each column represents one predictor (variable).\n\t\\item Y: Numeric vector of length n, where n is the number of rows of X. Y(i) is the response to row i of X.\n\t\\item 'Alpha': Scalar value from 0 to 1 (excluding 0) representing the weight of lasso (L1) versus ridge (L2) optimization. Alpha = 1 represents lasso regression, Alpha close to 0 approaches ridge regression, and other values represent elastic net optimization. See Definitions.\n\tDefault: 1\n\\end{itemize}\n\n\n\n\\subsection{Regularized Least Squares - Connection to MLE and MAP (Model-based Approaches)}\n\n\\subsubsection{Least Squares and M(C)LE (Maximum Conditional Likelihood Estimator)}\n\n$$Y=f^*(X)+\\epsilon=X\\beta^*+\\epsilon$$\n$$\\epsilon \\sim \\mathcal{N}(0,\\sigma^2I)~~Y\\sim\\mathcal{N}(X\\beta^*,\\sigma^2I)$$\n$$\\hat{\\beta}_{MLE} = \\arg\\max_\\beta (\\log p(\\{Y_i\\}|\\beta,\\sigma^2,\\{X_i\\}))=\\arg\\min_{\\beta}\\sum_i(X_i\\beta-Y_i)^2$$\n\\begin{itemize}\n\t\\item Model parameters: $\\beta,\\sigma^2$\n\t\\item Conditional log likelihood: $\\log p(\\{Y_i\\}|\\beta,\\sigma^2,\\{X_i\\})$\n\\end{itemize}\n\nLeast Square Estimator is same as Maximum Conditional Likelihood Estimator under a Gaussian model.\n\n\\subsubsection{Regularized Least Squares and M(C)AP (Maximum Conditional A Prior Estimator)}\n\nIf $AA^T$ is not invertible.\n\n$$Y=f^*(X)+\\epsilon=X\\beta^*+\\epsilon$$\n$$\\epsilon \\sim \\mathcal{N}(0,\\sigma^2I)~~Y\\sim\\mathcal{N}(X\\beta^*,\\sigma^2I)$$\n(1) Gaussian prior:\n$$\\beta \\sim \\mathcal{N}(0,\\tau^2 I)~~p(\\beta) \\propto \\exp(-\\beta^T\\beta/2\\tau^2)$$\n$$\\hat{\\beta}_{MAP} = \\arg\\max_\\beta \\log p(\\{Y_i\\}|\\beta,\\sigma^2,\\{X_i\\}) +\\log p(\\beta)=\\arg\\min_{\\beta}\\sum_i(X_i\\beta-Y_i)^2+\\lambda(\\sigma^2,\\tau^2)||\\beta||_2^2$$\n(2) Laplace prior:\n$$\\beta \\sim Laplace(0,t)~~p(\\beta_i) \\propto \\exp(-|\\beta_i|/t)$$\n$$\\hat{\\beta}_{MAP} = \\arg\\max_\\beta \\log p(\\{Y_i\\}|\\beta,\\sigma^2,\\{X_i\\}) +\\log p(\\beta)=\\arg\\min_{\\beta}\\sum_i(X_i\\beta-Y_i)^2+\\lambda(\\sigma^2,\\tau^2)||\\beta||_1$$\n\n\n\\begin{itemize}\n\t\\item Model parameters: $\\beta,\\sigma^2$\n\t\\item Conditional log likelihood: $\\log p(\\{Y_i\\}|\\beta,\\sigma^2,\\{X_i\\})$\n\t\\item Log prior: $\\log p(\\beta)$\n\\end{itemize}\n\n\\section{Polynomial Regression}\n\n\\begin{itemize}\n\t\\item Univariate: $f(X)=\\sum{\\beta_iX^i}=[1, X, X^2, \\dots, X^m]^T\\beta$\n\t$$\\hat{\\beta}=(AA^T)^{-1}AY~or~(AA^T+\\lambda I)^{-1}AY$$\n\t\\item Multivariate: $f(X) = \\sum_i{\\beta_i X^{(i)}} + \\sum_{i,j}{\\beta_{i,j} X^{(i)} X^{(j)}}+\\sum_{i,j,k}{\\beta_{i,j,k} X^{(i)} X^{(j)}X^{(k)}}+\\dots$\n\\end{itemize}\n\n\n\\subsection{Bias - Vairance Tradeoff}\n\\begin{itemize}\n\t\\item Large bias, small variance: poor approximation but robust/stable\n\t\\item Small bias, large variance: good approximation but unstable\n\\end{itemize}\n\nBias-Variance Decomposition:\n$$E[(f(X)-f^*(X))^2] = Bias^2 + Variance$$\n\\begin{itemize}\n\t\\item $Bias = E[f(X)] - f^*(X)$: How far is the model from best model.\n\t\\item $Variance = E[(f(X)-E[f(X)])^2]$: How variable is the model.\n\\end{itemize}\n\n\\begin{figure}[!h]\n\t\\centering\n\t\\includegraphics[width=8cm]{./img/testerror.png}\n\t\\includegraphics[width=8cm]{./img/trainerror.png}\n\\end{figure}\n\n\\section{Regression with Basis Functions or Nonlinear Features}\n\n$$f(X)=\\sum_i \\beta_i \\phi_i(X)$$\n\n\n\\end{document}\n\n\n\n", "meta": {"hexsha": "357a961a566d53be94849d007518fc7249e9aef1", "size": 9727, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Notes/04_LinearRegression/document.tex", "max_stars_repo_name": "MengwenHe-CMU/17S_10701_MachineLearning", "max_stars_repo_head_hexsha": "613a3087a57a206b83d79855cec359e04cb440f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-03-04T01:53:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-14T09:17:05.000Z", "max_issues_repo_path": "Notes/04_LinearRegression/document.tex", "max_issues_repo_name": "MengwenHe-CMU/17S_10701_MachineLearning", "max_issues_repo_head_hexsha": "613a3087a57a206b83d79855cec359e04cb440f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Notes/04_LinearRegression/document.tex", "max_forks_repo_name": "MengwenHe-CMU/17S_10701_MachineLearning", "max_forks_repo_head_hexsha": "613a3087a57a206b83d79855cec359e04cb440f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-10-20T15:07:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-20T15:07:29.000Z", "avg_line_length": 38.5992063492, "max_line_length": 294, "alphanum_fraction": 0.6757479182, "num_tokens": 3528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.3402317753714238}}
{"text": "\\documentclass{article}\n\\usepackage{amsmath,amssymb}\n\\usepackage{graphicx,color}\n\\usepackage{gensymb}\n\n\\title{\\bf{Mid-Project Review: C++ implementation of the Metropolis-Hasting Algorithm}}\n\\author{Nicholas Malaya \\\\ University of Texas at Austin} \\date{}\n\n\\begin{document}\n\\maketitle\n\n\\section{Introduction}\n\nBayesian Inference is a powerful statistical method that has found a\nvariety of applications in uncertainty quantification, decision theory,\nmodel selection and many others. These methods have been applied to\ndiverse fields such as epidemiology, spam filters, computer vision, as\nwell as assessments of the reliability of the readyness of the United\nStates nuclear weapon stockpiles.  \n\nHowever, Bayes' Theorem, despite existing since the 18th century, has\nonly recently become more prevalent in scientific applications. The\nrecent dramatic growth in Bayesian methods coincides with the\nexponential expansion of computational power. This is because for all\nbut a small set of models, the posterior distribution is unable to be\nanalytically determined, and must be statistically sampled, often\nrequiring far more samples than are humanly possible to generate. \n\nFor this project, we have developed a C++ implementation of the\nMetropolis-Hastings algorithm. This is a Markov Chain Monte Carlo (MCMC)\nmethod to sample from a probability distribution.  These samples will be\ngenerated in order to estimate the posterior of a distribution for a\nBayesian Inference problem. We will generate results for a few different\nmodels, in order to investigate the model against a known (analytic)\nconjugate prior, as well as more complicated (non-tracible without\nsampling) distributions.   \n\nThe code is written in C++, and will be parallelized with openMP. \n\\section{Methodology}\n%\n% 3-4 page report on the progess of the project \n%\n\nSuppose we have a posterior that we want to sample from, but:\n\\begin{itemize}\n \\item the posterior doesn't look like any distribution we know (no\n       conjugate model exists)\n \\item some (or all) of the full conditionals do not look like any\n      distributions we know (no Gibbs sampling) \n\\end{itemize}\nIn these cases, it is necessary to sample the underlying (and often\nquite complicted) distribution. The Metropolis-Hastings algorithm\naccomplishes this. \n\n\\subsection{Model Document: The Metropolis Hastings Algorithm}\n\nFor each Metropolis step, we begin with a guess for the starting point,\n$\\phi_1$. Afterward, we begin sampling. Each step of this so-called,\n``rejection sampling'' involves ``proposing'' a new value, which if it\nmeets a specified criterion, is accepted. The next step then begins. \n\nThus, we begin with a proposal step (in this case, for step two),\n\\begin{equation}\n q(\\tilde \\phi_2 | \\phi_1) = N(\\tilde \\phi_2 | \\phi_1, \\nu^2).\n\\end{equation}\nIn other words, our proposal step is correlated with the previous step,\nin that it is drawn from a Gaussian (Normal) distribution with mean of\nthe previous step, and standard deviation, $\\nu$. We will discuss our\nchoice of $\\nu$ more, later. In order to draw this proposal, we generate a \nproposal from a standard normal distribution, Z, and then transform it according to,\n\\begin{equation}\n X = \\phi_1 + \\nu*Z.\n\\end{equation}\n\nThus, with our new proposal $\\tilde \\phi_2$ drawn, we must evaluate\nwhether to accept this or reject it. In order to accomplish this, we\nnext draw from a uniform distribution, $u \\sim U(0,1)$. \n\nNow, we accept the new $\\tilde \\phi_2$ if it meets the following\ncriterion, \n\\begin{equation}\nu < \\frac{\\pi_n(\\tilde \\phi_2)}{\\pi_n(\\phi_1)}. \n\\end{equation}\nIf we accept, then $\\tilde \\phi_2$ becomes $\\phi_2$, and we begin the\nnext step. If we reject, then we keep our present value, e.g. $\\phi_2 =\n\\phi_1$. \n\nNow as we proceed, you might ask, what dictates whether we accept or\nreject? Well, after the ``burn-in'' period, where we move around looking\nfor the region where the distribution has non-zero probability, we\neventually start sampling the posterior. Here, we want to ``jump''\naround in each guess just enough that we will capture the tails of the\ndistribution, but simultaneously, we don't want to jump so far that we\nmove away from the areas of the distribution that has most of the\nprobability associated with it. This is where our $\\nu$ comes in. This\nis the variance of the proposal. If it is very large, then we will tend\nto make large jumps away from the mean for our proposal. These are great\nfor finding the distribution in the first place, and they will tend to\ncapture more of the tails, but simultaneously, too many large jumps will\nresult in more rejections by our sampling algorithm. Therefore, we need\nto balance $\\nu$ so that is jumps around, but not too far.\n\nIt turns out that mathematicians have shown that for various situations,\nan, ``acceptance ratio'' of right around 40\\% is just about right. This\nacceptance ratio is simply the ratio of accepted proposals to total MCMC\nsteps we have taken. Therefore, we have tried to tune our $\\nu$\nparameter for each situation to have an acceptance ratio around 40\\%. \n\n\n\n\\section{Report on Progress}\n\nThe metropolis algorithm as detailed above has now been implemented in a few hundred lines of C++. \nPresently, we are sampling from a Gaussian distribution, in order to analytically verify that \nour distribution matches a known posterior. A histogram from one thousand samples is provided in \nfigure one. \n\\begin{center}\n \\includegraphics[width=3.5in]{figs/hist}\n\\end{center}\n\nThis matches quite well, and implies the basic kernel is functioning. Our next objective will be to \nmove toward a few other distributions, with an eye on generating samples for a prior and posterior set of \ndistributions that do not have an analytical solution. \n\nThe codebase for this project has been developed on bitbucket, with logs\n for each commit. A fully functioning build system (a makefile) alongside a 'make  \n check' regression suite has been developed. At present, three\n regression tests are run, that perform simple checks on the\n distributions and sampling algorithm. The code has been tested on a local i7 quad core laptop, as well as TACC's\nlonestar supercomputer. \n\nFinally, a directory, ``postprocessing'' contains scripts used to\ngenerate all plots. These are routines using python with numpy+scipy and\nmatplotlib. \n\n\\section{Future Work}\n\nAs mentioned in the previous section, the we will expand to a few other distributions, in addition to \nsampling gaussians. This should not be a significant part of the work. These distributions will also be \nverified against conjugate priors (analytically known solution distributions) when available. \n\nThe largest remaining deliverable is to add OpenMP directives to the c++\nimplementation. Afterward, a detailed scaling study will be\nperformed. Due to the nature of MCMC, each markov chain should be\ncompletely independent, and the underlying algorithm is therefore\n``embarassingly parallel''. As a result, and we expect the routines to\nscale essentially perfectly. At least, we hope so!\n\n\\end{document}\n", "meta": {"hexsha": "48932042ec2db8d8e840307bf6c701a3fcf6594e", "size": 7044, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "metropolis-hastings/doc/review/report.tex", "max_stars_repo_name": "nicholasmalaya/paleologos", "max_stars_repo_head_hexsha": "11959056caa80d3c910759b714a0f8e42f986f0f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-04T17:49:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T17:49:42.000Z", "max_issues_repo_path": "metropolis-hastings/doc/review/report.tex", "max_issues_repo_name": "nicholasmalaya/paleologos", "max_issues_repo_head_hexsha": "11959056caa80d3c910759b714a0f8e42f986f0f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "metropolis-hastings/doc/review/report.tex", "max_forks_repo_name": "nicholasmalaya/paleologos", "max_forks_repo_head_hexsha": "11959056caa80d3c910759b714a0f8e42f986f0f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-01-04T16:08:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-16T19:34:24.000Z", "avg_line_length": 46.96, "max_line_length": 113, "alphanum_fraction": 0.7820840432, "num_tokens": 1670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.6548947223065754, "lm_q1q2_score": 0.3402317718721609}}
{"text": "%% LyX 2.0.3 created this file.  For more info, see http://www.lyx.org/.\n%% Do not edit unless you really know what you are doing.\n\\documentclass[twoside,english]{paper}\n\\usepackage{lmodern}\n\\renewcommand{\\ttdefault}{lmodern}\n\\usepackage[T1]{fontenc}\n\\usepackage[latin9]{inputenc}\n\\usepackage[a4paper]{geometry}\n\\geometry{verbose,tmargin=3cm,bmargin=2.5cm,lmargin=2cm,rmargin=2cm}\n\\usepackage{color}\n\\usepackage{babel}\n\\usepackage{float}\n\\usepackage{bm}\n\\usepackage{amsthm}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{graphicx}\n\\usepackage{esint}\n\\usepackage[unicode=true,pdfusetitle,\n bookmarks=true,bookmarksnumbered=false,bookmarksopen=false,\n breaklinks=false,pdfborder={0 0 0},backref=false,colorlinks=false]\n {hyperref}\n\\usepackage{breakurl}\n\\usepackage{mathrsfs}\n\n\\makeatletter\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LyX specific LaTeX commands.\n%% Because html converters don't know tabularnewline\n\\providecommand{\\tabularnewline}{\\\\}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Textclass specific LaTeX commands.\n\\numberwithin{equation}{section}\n\\numberwithin{figure}{section}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% User specified LaTeX commands.\n\\usepackage{babel}\n\n\\@ifundefined{showcaptionsetup}{}{%\n \\PassOptionsToPackage{caption=false}{subfig}}\n\\usepackage{subfig}\n\\makeatother\n\n\\begin{document}\n\n\\section{Structure of the observable}\n\nIn this document we report the relevant formulas for the computation\nof semi-inclusive deep-inelastic scattering (SIDIS) multiplicities\nunder the assumption that the (negative) virtuality of the $Q^2$ of\nthe exchanged vector boson is much smaller than the $Z$ mass. This\nallows us to neglect weak contributions and write the multiplicity\nas:\n\\begin{equation}\n\\frac{d\\sigma}{dxdQ^2 dz d p_T} = \\frac{2p_T\\pi \\alpha^2\n  }{z^2 x Q^4}\\left[1+(1-y)^2\\right] H(Q,\\mu) \\sum_q e_q^2\n  \\int_0^\\infty db \\,b J_0\\left(\\frac{bp_T}{z}\\right)\\overline{F}_q(x,b;\\mu,\\zeta) \\overline{D}_{q}(z,b;\\mu,\\zeta)\\,,\n\\end{equation}\nwhere:\n\\begin{equation}\n\\overline{F}_i(x,b;\\mu,\\zeta) =xF_i(x,b;\\mu,\\zeta) = R_q(\\mu_0,\\zeta_0\\rightarrow \\mu,\\zeta;b) \\sum_{j}\\int_x^1dy\\,\\mathcal{C}_{ij}(y;\\mu_0,\\zeta_0)\\left[\\frac{x}{y}f_j\\left(\\frac{x}{y},\\mu_0\\right)\\right]\\,,\n\\end{equation}\nand:\n\\begin{equation}\n\\overline{D}_{i}(z,b;\\mu,\\zeta) =z^3D_{i}(z,b;\\mu,\\zeta) = R_q(\\mu_0,\\zeta_0\\rightarrow \\mu,\\zeta;b) \\sum_{j}\\int_z^1dy\\,\\left[y^2\\mathbb{C}_{ij}(y;\\mu_0,\\zeta_0)\\right]\\left[\\frac{z}{y}d_j\\left(\\frac{z}{y},\\mu_0\\right)\\right]\\,.\n\\end{equation}\n\n\\begin{thebibliography}{alp}\n\n\\end{thebibliography}\n\n\\end{document}\n", "meta": {"hexsha": "0831c64f084ec145149fea020be818991c7f8365", "size": 2526, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/src/SIDISTMD.tex", "max_stars_repo_name": "intrepid42/apfelxx", "max_stars_repo_head_hexsha": "34b0bb4f134ddf42aa7eccceaa6c3b91b5414cd6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/src/SIDISTMD.tex", "max_issues_repo_name": "intrepid42/apfelxx", "max_issues_repo_head_hexsha": "34b0bb4f134ddf42aa7eccceaa6c3b91b5414cd6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/src/SIDISTMD.tex", "max_forks_repo_name": "intrepid42/apfelxx", "max_forks_repo_head_hexsha": "34b0bb4f134ddf42aa7eccceaa6c3b91b5414cd6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.602739726, "max_line_length": 229, "alphanum_fraction": 0.7157561362, "num_tokens": 868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947155710233, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.340231768372898}}
{"text": "%!TEX root = ../../dissertation.tex\n\n\\section{New Keynesian Model} \\label{app:NKModel}\n\nIn A1-A7, we provide a description of Bellman and Euler equation algorithms, which we use to solve\nthe neoclassical stochastic growth model with inelastic labor supply described in Section 2\nincluding i) envelope condition method iterating on value function (ECM-VF); ii) conventional value\nfunction interation (VFI); iii) endogenous grid method (EGM); iv) policy function iteration via\nenvelope condition (ECM-PI); v) conventional policy function iteration via FOC (PI); vi) envelope\ncondition method iterating on derivative of value function (ECM-DVF); vii) conventional Euler\nequation method (EE).\n\n\\paragraph{A1: Envelope condition method (ECM).}\n\n\\qquad\n\n\\qquad\n\n{\\small\n\\begin{tabular}{l}\n\\hline \\hline\n\\textbf{Algorithm 1. ECM.} \\\\ \\hline\n\\emph{Initialization.} \\\\\n\\quad a. Choose an approximating function $\\widehat{V}(\\cdot ;b)\\approx V$.\n\\\\\n\\quad b. Choose integration nodes, $\\varepsilon _{j}$, and weights, $\\omega\n_{j}$, $j=1,...,J$. \\\\\n\\quad c. Construct grid $\\Gamma =\\{k_{m},z_{m}\\}_{m=1}^{M}$. \\\\\n\\quad d. Make an initial guess on $b^{(1)}$. \\\\ \\hline\n\\emph{Iterative cycle. Computation of a solution.} \\\\ \\hline\n\\quad At iteration $i$, perform the following steps: \\\\\n\\emph{Step 1. Computation of values of }$V$ \\emph{on the grid.} \\\\\n\\quad For $m=1,...,M,$ \\\\\n\\quad a. Use $b^{\\left( i\\right) }$ to compute $\\widehat{V}_{1}\\left(\nk_{m},z_{m};b^{\\left( i\\right) }\\right) $. \\\\\n\\quad b. Compute the corresponding values of $c_{m}$ using \\\\\n\\quad $c_{m}=u^{\\prime -1}\\left[ \\frac{\\widehat{V}_{1}\\left(\nk_{m},z_{m};b^{\\left( i\\right) }\\right) }{1-\\delta +z_{m}f^{\\prime }\\left(\nk_{m}\\right) }\\right] .$ \\\\\n\\quad c. Find $k_{m}^{\\prime }$ using \\\\\n\\quad $k_{m}^{\\prime }=(1-\\delta )k_{m}+z_{m}f\\left( k_{m}\\right) -c_{m}$.\n\\\\\n\\quad d. Find value function on the grid \\\\\n\\quad $\\widehat{v}_{m}\\equiv u\\left( c_{m}\\right) +\\beta\n\\sum_{j=1}^{J}\\omega _{j}\\widehat{V}\\left( k_{m}^{\\prime },z_{m}^{\\rho }\\exp\n\\left( \\varepsilon _{j}\\right) ;b^{(i)}\\right) .$ \\\\ \\hline\n\\emph{Step 2. Computation of }$b$\\emph{\\ that fits the value function on the\ngrid. } \\\\\n\\quad Run a regression to find $\\widehat{b}:$ \\\\\n\\quad $\\widehat{b}=\\arg \\underset{b}{\\min }\\sum_{m=1}^{M}\\Vert \\widehat{v}\n_{m}-\\widehat{V}(k_{m},z_{m};b)\\Vert $. \\\\ \\hline\n\\emph{Step 3. Convergence check and fixed-point iteration.} \\\\\n\\quad a. Check for convergence for $i\\geq 2$: end Step 2 if \\\\\n\\quad $\\dfrac{1}{M}\\sum_{m=1}^{M}\\left \\vert \\dfrac{(k_{m}^{\\prime\n})^{\\left( i\\right) }-(k_{m}^{\\prime })^{\\left( i-1\\right) }}{(k_{m}^{\\prime\n})^{\\left( i-1\\right) }}\\right \\vert <10^{-9}.$ \\\\\n\\quad b. Use damping with $\\xi =1$ to compute $b^{\\left( i+1\\right) }=(1-\\xi\n)b^{\\left( i\\right) }+\\xi \\widehat{b}$. \\\\ \\hline \\hline\n\\end{tabular}\n}\n\n\\newpage\n\n\\paragraph{A2: Value function iteration (VFI).}\n\n\\qquad\n\n\\qquad\n\n{\\small\n\\begin{tabular}{l}\n\\hline \\hline\n\\textbf{Algorithm 2. VFI.} \\\\ \\hline\n\\emph{Initialization.} \\\\\n\\quad a. Choose an approximating function $\\widehat{V}(\\cdot ;b)\\approx V$.\n\\\\\n\\quad b. Choose integration nodes, $\\varepsilon _{j}$, and weights, $\\omega\n_{j}$, $j=1,...,J$. \\\\\n\\quad c. Construct a grid $\\Gamma =\\{k_{m},z_{m}\\}_{m=1}^{M}$. \\\\\n\\quad d. Make an initial guess on $b^{(1)}$. \\\\ \\hline\n\\emph{Iterative cycle. Computation of a solution.} \\\\ \\hline\n\\quad At iteration $i$, perform the following steps: \\\\\n\\emph{Step 1. Computation of values of }$V$\\emph{\\ on the grid.} \\\\\n\\quad For $m=1,...,M$, \\\\\n\\quad a. Solve for $k_{m}^{\\prime }$ satisfying \\\\\n\\quad $u^{\\prime }\\left( (1-\\delta )k_{m}+z_{m}f\\left( k_{m}\\right)\n-k_{m}^{\\prime }\\right) =\\beta \\sum_{j=1}^{J}\\omega _{j}\\widehat{V}\n_{1}\\left( k_{m}^{\\prime },z_{m}^{\\rho }\\exp \\left( \\varepsilon _{j}\\right)\n;b^{(i)}\\right) .$ \\\\\n\\quad b. Find $c_{m}$ satisfying \\\\\n\\quad $c_{m}=(1-\\delta )k_{m}+z_{m}f\\left( k_{m}\\right) -k_{m}^{\\prime }$.\n\\\\\n\\quad c. Find value function on the grid \\\\\n\\quad $\\widehat{v}_{m}\\equiv u\\left( c_{m}\\right) +\\beta\n\\sum_{j=1}^{J}\\omega _{j}\\widehat{V}\\left( k_{m}^{\\prime },z_{m}^{\\rho }\\exp\n\\left( \\varepsilon _{j}\\right) ;b^{(i)}\\right) .$ \\\\ \\hline\n\\emph{Step 2. Computation of }$b$\\emph{\\ that fits value function on the\ngrid. } \\\\\n\\quad Run a regression to find $\\widehat{b}:$ \\\\\n\\quad $\\widehat{b}=\\arg \\underset{b}{\\min }\\sum_{m=1}^{M}\\Vert \\widehat{v}\n_{m}-\\widehat{V}(k_{m},z_{m};b)\\Vert $. \\\\ \\hline\n\\emph{Step 3. Convergence check and fixed-point iteration.} \\\\\n\\quad a. Check for convergence for $i\\geq 2$: end Step 2 if \\\\\n\\quad $\\dfrac{1}{M}\\sum_{m=1}^{M}\\left \\vert \\dfrac{(k_{m}^{\\prime\n})^{\\left( i\\right) }-(k_{m}^{\\prime })^{\\left( i-1\\right) }}{(k_{m}^{\\prime\n})^{\\left( i-1\\right) }}\\right \\vert <10^{-9}.$ \\\\\n\\quad b. Use damping with $\\xi =1$ to compute $b^{\\left( i+1\\right) }=(1-\\xi\n)b^{\\left( i\\right) }+\\xi \\widehat{b}$. \\\\ \\hline \\hline\n\\end{tabular}\n}\n\n\\newpage\n\n\\paragraph{A3: Endogenous grid method (EGM).}\n\n\\qquad\n\n\\qquad\n\n{\\small\n\\begin{tabular}{l}\n\\hline \\hline\n\\textbf{Algorithm 3. EGM.} \\\\ \\hline\n\\emph{Initialization.} \\\\\n\\quad a. Choose an approximating function $\\widehat{V}(\\cdot ;b)\\approx V$.\n\\\\\n\\quad b. Choose integration nodes, $\\varepsilon _{j}$, and weights, $\\omega\n_{j}$, $j=1,...,J$. \\\\\n\\quad c. Construct grid $\\Gamma =\\{k_{m}^{\\prime },z_{m}\\}_{m=1}^{M}$. \\\\\n\\quad d. Make an initial guess on $b^{(1)}$. \\\\ \\hline\n\\emph{Iterative cycle. Computation of a solution.} \\\\ \\hline\n\\quad At iteration $i$, perform the following steps: \\\\\n\\emph{Step 1. Computation of values of }$V$\\emph{\\ on the grid.} \\\\\n\\quad For $m=1,...,M$, \\\\\n\\quad a. Compute $\\widehat{W}\\left( k_{m}^{\\prime },z_{m};b^{(i)}\\right)\n\\equiv \\sum_{j=1}^{J}\\omega _{j}\\widehat{V}\\left( k_{m}^{\\prime\n},z_{m}^{\\rho }\\exp \\left( \\varepsilon _{j}\\right) ;b^{(i)}\\right) $ \\\\\n\\quad and $\\widehat{W}_{1}\\left( k_{m}^{\\prime },z_{m};b^{(i)}\\right) \\equiv\n\\sum_{j=1}^{J}\\omega _{j}\\widehat{V}_{1}\\left( k_{m}^{\\prime },z_{m}^{\\rho\n}\\exp \\left( \\varepsilon _{j}\\right) ;b^{(i)}\\right) $. \\\\\n\\quad b. Find $c_{m}=u^{\\prime -1}\\left[ \\beta \\widehat{W}_{1}\\left(\nk_{m}^{\\prime },z_{m};b^{(i)}\\right) \\right] $. \\\\\n\\quad c. Use a solver to find $k_{m}$ satisfying \\\\\n\\quad $(1-\\delta )k_{m}+z_{m}f\\left( k_{m}\\right) =c_{m}+k_{m}^{\\prime }$.\n\\\\\n\\quad d. Find value function on the grid \\\\\n\\quad $\\widehat{v}_{m}\\equiv u(c_{m})+\\beta \\widehat{W}\\left( k_{m}^{\\prime\n},z_{m};b^{(i)}\\right) $. \\\\ \\hline\n\\emph{Step 2. Computation of }$b$\\emph{\\ that fits value function on the\ngrid. } \\\\\n\\quad Run a regression to find $\\widehat{b}:$ \\\\\n\\quad $\\widehat{b}=\\arg \\underset{b}{\\min }\\sum_{m=1}^{M}\\Vert \\widehat{v}\n_{m}-\\widehat{V}(k_{m},z_{m};b)\\Vert $. \\\\ \\hline\n\\emph{Step 3. Convergence check and fixed-point iteration.} \\\\\n\\quad a. Check for convergence for $i\\geq 2$: end Step 2 if \\\\\n\\quad $\\dfrac{1}{M}\\sum_{m=1}^{M}\\left \\vert \\dfrac{(k_{m})^{\\left( i\\right)\n}-(k_{m})^{\\left( i-1\\right) }}{(k_{m})^{\\left( i-1\\right) }}\\right \\vert\n<10^{-9}.$ \\\\\n\\quad b. Use damping with $\\xi =1$ to compute $b^{\\left( i+1\\right) }=(1-\\xi\n)b^{\\left( i\\right) }+\\xi \\widehat{b}$. \\\\ \\hline \\hline\n\\end{tabular}\n}\n\n\\newpage\n\n\\paragraph{A4: Policy function iteration using envelope condition (PI-ECM)}\n\n\\qquad\n\n\\qquad\n\n{\\small\n\\begin{tabular}{l}\n\\hline \\hline\n\\textbf{Algorithm 4. PI-ECM.} \\\\ \\hline\n\\emph{Initialization.} \\\\\n\\quad a. Choose an approximating function $\\widehat{V}(\\cdot ;b)\\approx V$\nand $\\widehat{K}(\\cdot ;v)\\approx K$. \\\\\n\\quad b. Choose integration nodes, $\\varepsilon _{j}$, and weights, $\\omega\n_{j}$, $j=1,...,J$. \\\\\n\\quad c. Construct grid $\\Gamma =\\{k_{m},z_{m}\\}_{m=1}^{M}$. \\\\\n\\quad d. Make an initial guess on $v^{(1)}$ and $b^{(1)}$. \\\\ \\hline\n\\emph{Iterative cycle. Computation of a solution.} \\\\ \\hline\n\\quad At iteration $i$, perform the following steps: \\\\\n\\emph{Step 1. Computation of values of }$V$ \\emph{on the grid.} \\\\\n\\quad For $m=1,...,M,$ \\\\\n\\quad a. Use $v^{\\left( i\\right) }$ to compute $k_{m}^{\\prime }=\\widehat{K}\n\\left( k_{m},z_{m};v^{\\left( i\\right) }\\right) $. \\\\\n\\quad b. Compute the corresponding values of $k_{m}^{\\prime }$ using \\\\\n\\quad $c_{m}=(1-\\delta )k_{m}+z_{m}f\\left( k_{m}\\right) -k_{m}^{\\prime }.$\n\\\\\n\\quad c. Iterate on $b^{\\left( i\\right) }$ to find an approximate solution to\n\\\\\n\\quad $\\widehat{V}\\left( k_{m},z_{m};b^{(i)}\\right) =u\\left( c_{m}\\right)\n+\\beta \\sum_{j=1}^{J}\\omega _{j}\\widehat{V}\\left( k_{m}^{\\prime\n},z_{m}^{\\rho }\\exp \\left( \\varepsilon _{j}\\right) ;b^{(i)}\\right) $. \\\\\n\\quad d. Find policy function on the grid \\\\\n\\quad $\\widehat{k}_{m}^{\\prime }=(1-\\delta )k_{m}+z_{m}f\\left( k_{m}\\right)\n-u^{\\prime -1}\\left[ \\frac{\\widehat{V}_{1}\\left( k_{m},z_{m};b^{\\left(\ni\\right) }\\right) }{1-\\delta +z_{m}f^{\\prime }\\left( k_{m}\\right) }\\right] .$\n\\\\ \\hline\n\\emph{Step 2. Computation of }$v$\\emph{\\ that fits the value function on the\ngrid. } \\\\\n\\quad Run a regression to find $\\widehat{v}:$ \\\\\n\\quad $\\widehat{v}=\\arg \\underset{v}{\\min }\\sum_{m=1}^{M}\\Vert \\widehat{k}\n_{m}^{\\prime }-\\widehat{K}(k_{m},z_{m};v)\\Vert $. \\\\ \\hline\n\\emph{Step 3. Convergence check and fixed-point iteration.} \\\\\n\\quad a. Check for convergence for $i\\geq 2$: end Step 2 if \\\\\n\\quad $\\dfrac{1}{M}\\sum_{m=1}^{M}\\left \\vert \\dfrac{(k_{m}^{\\prime\n})^{\\left( i\\right) }-(k_{m}^{\\prime })^{\\left( i-1\\right) }}{(k_{m}^{\\prime\n})^{\\left( i-1\\right) }}\\right \\vert <10^{-9}.$ \\\\\n\\quad b. Use damping with $\\xi =1$ to compute $v^{\\left( i+1\\right) }=(1-\\xi\n)v^{\\left( i\\right) }+\\xi \\widehat{v}$. \\\\ \\hline \\hline\n\\end{tabular}\n}\n\n\\newpage\n\n\\paragraph{A5: Policy function iteration using first-order condition (PI-FOC)\n}\n\n\\qquad\n\n\\qquad\n\n{\\small\n\\begin{tabular}{l}\n\\hline \\hline\n\\textbf{Algorithm 5. PI-FOC.} \\\\ \\hline\n\\emph{Initialization.} \\\\\n\\quad a. Choose an approximating function $\\widehat{V}(\\cdot ;b)\\approx V$\nand $\\widehat{K}(\\cdot ;v)\\approx K$. \\\\\n\\quad b. Choose integration nodes, $\\varepsilon _{j}$, and weights, $\\omega\n_{j}$, $j=1,...,J$. \\\\\n\\quad c. Construct grid $\\Gamma =\\{k_{m},z_{m}\\}_{m=1}^{M}$. \\\\\n\\quad d. Make an initial guess on $v^{(1)}$ and $b^{(1)}$. \\\\ \\hline\n\\emph{Iterative cycle. Computation of a solution.} \\\\ \\hline\n\\quad At iteration $i$, perform the following steps: \\\\\n\\emph{Step 1. Computation of values of }$V$ \\emph{on the grid.} \\\\\n\\quad For $m=1,...,M,$ \\\\\n\\quad a. Use $v^{\\left( i\\right) }$ to compute $k_{m}^{\\prime }=\\widehat{K}\n\\left( k_{m},z_{m};v^{\\left( i\\right) }\\right) $. \\\\\n\\quad b. Compute the corresponding values of $k_{m}^{\\prime }$ using \\\\\n\\quad $c_{m}=(1-\\delta )k_{m}+z_{m}f\\left( k_{m}\\right) -k_{m}^{\\prime }.$\n\\\\\n\\quad c. Iterate on $b^{\\left( i\\right) }$ to find an approximate solution to\n\\\\\n\\quad $\\widehat{V}\\left( k_{m},z_{m};b^{(i)}\\right) =u\\left( c_{m}\\right)\n+\\beta \\sum_{j=1}^{J}\\omega _{j}\\widehat{V}\\left( k_{m}^{\\prime\n},z_{m}^{\\rho }\\exp \\left( \\varepsilon _{j}\\right) ;b^{(i)}\\right) $. \\\\\n\\quad d. Find policy function on the grid \\\\\n$u^{\\prime }\\left( (1-\\delta )k_{m}+z_{m}f\\left( k_{m}\\right) -\\widehat{k}\n_{m}^{\\prime }\\right) =\\beta \\sum_{j=1}^{J}\\omega _{j}\\widehat{V_{1}}\\left(\n\\widehat{k}_{m}^{\\prime },z_{m}^{\\rho }\\exp \\left( \\varepsilon _{j}\\right)\n;b^{(i)}\\right) .$ \\\\ \\hline\n\\emph{Step 2. Computation of }$v$\\emph{\\ that fits the value function on the\ngrid. } \\\\\n\\quad Run a regression to find $\\widehat{v}:$ \\\\\n\\quad $\\widehat{v}=\\arg \\underset{v}{\\min }\\sum_{m=1}^{M}\\Vert \\widehat{k}\n_{m}^{\\prime }-\\widehat{K}(k_{m},z_{m};v)\\Vert $. \\\\ \\hline\n\\emph{Step 3. Convergence check and fixed-point iteration.} \\\\\n\\quad a. Check for convergence for $i\\geq 2$: end Step 2 if \\\\\n\\quad $\\dfrac{1}{M}\\sum_{m=1}^{M}\\left \\vert \\dfrac{(k_{m}^{\\prime\n})^{\\left( i\\right) }-(k_{m}^{\\prime })^{\\left( i-1\\right) }}{(k_{m}^{\\prime\n})^{\\left( i-1\\right) }}\\right \\vert <10^{-9}.$ \\\\\n\\quad b. Use damping with $\\xi =1$ to compute $v^{\\left( i+1\\right) }=(1-\\xi\n)v^{\\left( i\\right) }+\\xi \\widehat{v}$. \\\\ \\hline \\hline\n\\end{tabular}\n}\n\n\\newpage\n\n\\paragraph{A6: Euler equation algorithm parameterizing $Q$.}\n\n\\qquad\n\n{\\small\n\\begin{tabular}{l}\n\\hline \\hline\n\\textbf{Algorithm 6. Euler equation algorithm parameterizing }$V_{1}.$ \\\\\n\\hline\n\\emph{Initialization.} \\\\\n\\quad a. Choose an approximating function $\\widehat{V}_{1}(\\cdot ;b)\\approx\nV_{1}$. \\\\\n\\quad b. Choose integration nodes, $\\varepsilon _{j}$, and weights, $\\omega\n_{j}$, $j=1,...,J$. \\\\\n\\quad c. Construct grid $\\Gamma =\\{k_{m},z_{m}\\}_{m=1}^{M}$. \\\\\n\\quad d. Make an initial guess on $b^{(1)}$. \\\\ \\hline\n\\emph{Iterative cycle. Computation of a solution.} \\\\ \\hline\n\\quad At iteration $i$, perform the following steps: \\\\\n\\emph{Step 1. Computation of values of }$V_{1}$ \\emph{on the grid.} \\\\\n\\quad For $m=1,...,M,$ \\\\\n\\quad a. Use $b^{\\left( i\\right) }$ to compute $\\widehat{V}_{1}\\left(\nk_{m},z_{m};b^{\\left( i\\right) }\\right) $. \\\\\n\\quad b. Find $k_{m}^{\\prime }$ using \\\\\n\\quad $k_{m}^{\\prime }=\\left( 1-\\delta \\right) k_{m}+z_{m}f\\left(\nk_{m}\\right) -u^{\\prime -1}\\left( \\frac{\\widehat{V}_{1}\\left(\nk_{m},z_{m};b^{\\left( i\\right) }\\right) }{1-\\delta +z_{m}f\\left(\nk_{m}\\right) }\\right) $ \\\\\n\\quad c. Find the values of $v_{m}$ on the grid \\\\\n\\quad $\\widehat{v}_{1,m}\\equiv \\beta \\left[ 1-\\delta +zf^{\\prime }\\left(\nk_{m}\\right) \\right] \\sum_{j=1}^{J}\\omega _{j}\\widehat{V}_{1}\\left(\nk_{m}^{\\prime },z_{m}^{\\rho }\\exp \\left( \\varepsilon _{j}\\right)\n;b^{(i)}\\right) $. \\\\ \\hline\n\\emph{Step 2. Computation of }$b$\\emph{\\ that fits the V}$_{1}$\\emph{\\\nfunction on the grid. } \\\\\n\\quad Run a regression to find $\\widehat{b}:$ \\\\\n\\quad $\\widehat{b}=\\arg \\underset{b}{\\min }\\sum_{m=1}^{M}\\Vert \\widehat{v}\n_{1,m}-\\widehat{V}_{1}(k_{m},z_{m};b)\\Vert $. \\\\ \\hline\n\\emph{Step 3. Convergence check and fixed-point iteration.} \\\\\n\\quad a. Check for convergence for $i\\geq 2$: end Step 2 if \\\\\n\\quad $\\dfrac{1}{M}\\sum_{m=1}^{M}\\left \\vert \\dfrac{(k_{m}^{\\prime\n})^{\\left( i\\right) }-(k_{m}^{\\prime })^{\\left( i-1\\right) }}{(k_{m}^{\\prime\n})^{\\left( i-1\\right) }}\\right \\vert <10^{-9}.$ \\\\\n\\quad b. Use damping with $\\xi =1$ to compute $b^{\\left( i+1\\right) }=(1-\\xi\n)b^{\\left( i\\right) }+\\xi \\widehat{b}$. \\\\ \\hline \\hline\n\\end{tabular}\n}\n\n\\qquad \\newpage\n\n\\paragraph{A7. Euler equation algorithm parameterizing $K$}\n\n\\qquad\n\n{\\small\n\\begin{tabular}{l}\n\\hline \\hline\n\\textbf{Algorithm 7. Euler equation algorithm parameterizing } $K$\\textbf{.}\n\\\\ \\hline\n\\emph{Initialization.} \\\\\n\\quad a. Choose approximating functions $\\widehat{K}(\\cdot ;v)\\approx K$. \\\\\n\\quad b. Choose integration nodes, $\\varepsilon _{j}$, and weights, $\\omega\n_{j}$, $j=1,...,J$. \\\\\n\\quad c. Construct grid $\\Gamma =\\{k_{m},z_{m}\\}_{m=1}^{M}$. \\\\\n\\quad d. Make an initial guess on $v^{(1)}$. \\\\ \\hline\n\\emph{Step 1. Computation of values of }$\\widehat{k}^{\\prime }$ \\emph{on the\ngrid}. \\\\\n\\quad For $m=1,...,M$, \\\\\n\\quad a. Use $v^{\\left( i\\right) }$ to compute $\\widehat{K}\\left(\nk_{m},z_{m};v^{\\left( i\\right) }\\right) $ and \\\\\n\\quad $k_{m,j}^{\\prime \\prime }=\\widehat{K}\\left( \\widehat{K}\\left(\nk_{m},z_{m};v^{\\left( i\\right) }\\right) ,z_{m}^{\\rho }\\exp \\left( \\epsilon\n_{j}\\right) ;v^{\\left( i\\right) }\\right) $, $j=1,...,J$. \\\\\n\\quad b. Find $c_{m,j}^{\\prime }$ using \\\\\n\\quad $c_{m,j}^{\\prime }=(1-\\delta )\\widehat{K}\\left( k_{m},z_{m};v^{\\left(\ni\\right) }\\right) +z_{m}f\\left( \\widehat{K}\\left( k_{m},z_{m};v^{\\left(\ni\\right) }\\right) \\right) -k_{m,j}^{\\prime \\prime }$. \\\\\n\\quad c. Find the values of $c_{m}$ on the grid \\\\\n\\quad $u^{\\prime }\\left( c_{m}\\right) =\\beta \\sum_{j=1}^{J}\\omega\n_{j}u^{\\prime }\\left( c_{m,j}^{\\prime }\\right) \\left[ 1-\\delta +z_{m}^{\\rho\n}\\exp \\left( \\epsilon _{j}\\right) f^{\\prime }\\left( \\widehat{K}\\left(\nk_{m},z_{m};v^{\\left( i\\right) }\\right) \\right) \\right] .$ \\\\\n\\quad d. Find the values of $k_{m}^{\\prime }$ on the grid \\\\\n\\quad $\\widehat{k}_{m}^{\\prime }=(1-\\delta )k_{m}+z_{m}f\\left( k_{m}\\right)\n-c_{m}$. \\\\ \\hline\n\\emph{Step 2. Computation of }$v$\\emph{\\ that fits the capital function on\nthe grid. } \\\\\n\\quad a. Run a regression to find $\\widehat{v}:$ \\\\\n\\quad $\\widehat{v}=\\arg \\underset{v}{\\min }\\sum_{m=1}^{M}\\Vert \\widehat{k}\n_{m}^{\\prime }-\\widehat{K}\\left( k_{m},z_{m};v^{\\left( i\\right) }\\right)\n\\Vert $. \\\\\n\\quad b. Use damping with $\\xi =1$ to compute $v^{\\left( i+1\\right) }=(1-\\xi\n)v^{\\left( i\\right) }+\\xi \\widehat{v}$. \\\\ \\hline \\hline\n\\end{tabular}\n}\n\n\\qquad \\newpage\n\n\\begin{center}\n\\label{APNK}{\\Large Appendix B: An Euler equation algorithm for solving a\nnew Keynesian model}\n\\end{center}\n\nWe consider a new Keynesian model studied in Maliar and Maliar (2015). This is\na stylized new Keynesian model with Calvo-type price frictions and a Taylor\n(1993) rule.\n\n\\paragraph{The model.}\n\nThe economy is populated by households, final-good firms, intermediate-good\nfirms, monetary authority and government.\n\n\\textit{Households. }The representative household solves\n\n\\begin{gather}\n\\underset{\\left \\{ C_{t},L_{t},B_{t}\\right \\} _{t=0,...,\\infty }}{\\max }E_{0}\n\\overset{\\infty }{\\underset{t=0}{\\sum }}\\beta ^{t}\\exp \\left( \\eta\n_{u,t}\\right) \\left[ \\frac{C_{t}^{1-\\gamma }-1}{1-\\gamma }-\\exp \\left( \\eta\n_{L,t}\\right) \\frac{L_{t}^{1+\\vartheta }-1}{1+\\vartheta }\\right]  \\label{uNK}\n\\\\\n\\text{s.t. }P_{t}C_{t}+\\frac{B_{t}}{\\exp \\left( \\eta _{B,t}\\right) R_{t}}\n+T_{t}=B_{t-1}+W_{t}L_{t}+\\Pi _{t},  \\label{bcNK}\n\\end{gather}\n\nwhere $\\left( B_{0},\\eta _{u,0},\\eta _{L,0},\\eta _{B,0}\\right) $ is given; $\nC_{t}$, $L_{t}$, and $B_{t}$ are consumption, labor and nominal bond holdings,\nrespectively; $P_{t}$, $W_{t}$ and $R_{t}$ are the commodity price, nominal\nwage and (gross) nominal interest rate, respectively; $\\eta _{u,t}$ and $\\eta\n_{L,t}$ are exogenous preference shocks to the overall momentary utility and\ndisutility of labor, respectively; $\\eta _{B,t}$ is an exogenous premium in the\nreturn to bonds; $T_{t}$ is lump-sum taxes; $\\Pi _{t}$ is the profit of\nintermediate-good firms; $\\beta \\in \\left( 0,1\\right) $ is the discount factor;\n$\\gamma >0$ and $\\vartheta >0$ are the utility-function parameters. The\nprocesses for shocks are\n\n\\begin{gather}\n\\eta _{u,t+1}=\\rho _{u}\\eta _{u,t}+\\epsilon _{u,t+1},\\qquad \\epsilon\n_{u,t+1}\\sim \\mathcal{N}\\left( 0,\\sigma _{u}^{2}\\right) ,  \\label{nuu} \\\\\n\\eta _{L,t+1}=\\rho _{L}\\eta _{L,t}+\\epsilon _{L,t+1},\\qquad \\epsilon\n_{L,t+1}\\sim \\mathcal{N}\\left( 0,\\sigma _{L}^{2}\\right) ,  \\label{nuL} \\\\\n\\eta _{B,t+1}=\\rho _{B}\\eta _{B,t}+\\epsilon _{B,t+1},\\qquad \\epsilon\n_{B,t+1}\\sim \\mathcal{N}\\left( 0,\\sigma _{B}^{2}\\right) ,  \\label{nuB}\n\\end{gather}\n\nwhere $\\rho _{u}$, $\\rho _{L}$, $\\rho _{B}$ are the autocorrelation\ncoefficients, and $\\sigma _{u}$, $\\sigma _{L}$, $\\sigma _{B}$ are the standard\ndeviations of disturbances.\n\n\\textit{Final-good firms. }Perfectly competitive final-good firms produce final\ngoods using intermediate goods. A final-good firm buys $Y_{t}\\left( i\\right) $\nof an intermediate good $i\\in \\left[ 0,1\\right] $ at price $P_{t}\\left(\ni\\right) $ and sells $Y_{t}$ of the final good at price $P_{t}$ in a perfectly\ncompetitive market. The profit-maximization problem is\n\n\\begin{gather}\n\\underset{Y_{t}\\left( i\\right) }{\\max }\\quad\nP_{t}Y_{t}-\\int_{0}^{1}P_{t}\\left( i\\right) Y_{t}\\left( i\\right) di\n\\label{maxfin} \\\\\n\\text{s.t. }Y_{t}=\\left( \\int_{0}^{1}Y_{t}\\left( i\\right) ^{\\frac{\n\\varepsilon -1}{\\varepsilon }}di\\right) ^{\\frac{\\varepsilon }{\\varepsilon -1}\n},  \\label{bcfin}\n\\end{gather}\n\nwhere (\\ref{bcfin}) is a Dixit-Stiglitz aggregator function with $\\varepsilon\n\\geq 1$.\n\n\\textit{Intermediate-good firms. }Monopolistic intermediate-good firms produce\nintermediate goods using labor and are subject to sticky prices. The firm $i$\nproduces the intermediate good $i$. To choose labor in each period $ t$, the\nfirm $i$ minimizes the nominal total cost, TC (net of government subsidy $v$),\n\n\\begin{gather}\n\\underset{L_{t}\\left( i\\right) }{\\min }\\quad \\text{TC}\\left( Y_{t}\\left(\ni\\right) \\right) =\\left( 1-v\\right) W_{t}L_{t}\\left( i\\right)  \\label{tc} \\\\\n\\text{s.t. }Y_{t}\\left( i\\right) =\\exp \\left( \\eta _{a,t}\\right) L_{t}\\left(\ni\\right) ,  \\label{tech} \\\\\n\\eta _{a,t+1}=\\rho _{a}\\eta _{a,t}+\\epsilon _{a,t+1},\\qquad \\epsilon\n_{a,t+1}\\sim \\mathcal{N}\\left( 0,\\sigma _{a}^{2}\\right) ,  \\label{nua}\n\\end{gather}\n\nwhere $L_{t}\\left( i\\right) $ is the labor input; $\\exp \\left( \\eta\n_{a,t}\\right) $ is the productivity level; $\\rho _{a}$ is the autocorrelation\ncoefficient; and $\\sigma _{a}$ is the standard deviation of the disturbance.\nThe firms are subject to Calvo-type price setting: a fraction $1-\\theta $ of\nthe firms sets prices optimally, $P_{t}\\left( i\\right) =\\widetilde{P}_{t}$, for\n$i\\in \\left[ 0,1\\right] $, and the fraction $\\theta $ is not allowed to change\nthe price and maintains the same price as in the previous period, $P_{t}\\left(\ni\\right) =P_{t-1}\\left( i\\right) $, for $i\\in \\left[ 0,1\\right] $. A\nreoptimizing firm $i\\in \\left[ 0,1\\right] $ maximizes the current value of the\nprofit over the time when $ \\widetilde{P}_{t}$ remains effective,\n\n\\begin{gather}\n\\underset{\\widetilde{P}_{t}}{\\max }\\quad \\underset{j=0}{\\overset{\\infty }{\n\\mathop{\\displaystyle \\sum } }}\\beta ^{j}\\theta ^{j}E_{t}\\left \\{ \\Lambda\n_{t+j}\\left[ \\widetilde{P}_{t}Y_{t+j}\\left( i\\right) -P_{t+j}\\text{mc}\n_{t+j}Y_{t+j}\\left( i\\right) \\right] \\right \\}  \\label{maxmon} \\\\\n\\text{s.t. }Y_{t}\\left( i\\right) =Y_{t}\\left( \\frac{P_{t}\\left( i\\right) }{\nP_{t}}\\right) ^{-\\varepsilon },  \\label{bcmon}\n\\end{gather}\n\nwhere (\\ref{bcmon}) is the demand for an intermediate good $i$ following from\n(\\ref{maxfin}), (\\ref{bcfin}); $\\Lambda _{t+j}$ is the Lagrange multiplier on\nthe household's budget constraint (\\ref{bcNK}); mc$_{t+j}$ is the real marginal\ncost of output at time $t+j$ (which is identical across the firms).\n\n\\textit{Government. }Government finances a stochastic stream of public\nconsumption by levying lump-sum taxes and by issuing nominal debt. The\ngovernment budget constraint is\n\n\\begin{equation}\nT_{t}+\\frac{B_{t}}{\\exp \\left( \\eta _{B,t}\\right) R_{t}}=P_{t}\\frac{\n\\overline{G}Y_{t}}{\\exp \\left( \\eta _{G,t}\\right) }+B_{t-1}+vW_{t}L_{t},\n\\label{Gbc}\n\\end{equation}\n\nwhere $\\frac{\\overline{G}Y_{t}}{\\exp \\left( \\eta _{G,t}\\right) }=G_{t}$ is\ngovernment spending, $vW_{t}L_{t}$ is the subsidy to the intermediate-good\nfirms, and $\\eta _{G,t}$ is a government-spending shock,\n\n\\begin{equation}\n\\eta _{G,t+1}=\\rho _{G}\\eta _{G,t}+\\epsilon _{G,t+1},\\qquad \\epsilon\n_{G,t+1}\\sim \\mathcal{N}\\left( 0,\\sigma _{G}^{2}\\right) ,  \\label{nuG}\n\\end{equation}\n\nwhere $\\rho _{R}$ is the autocorrelation coefficient, and $\\sigma _{R}$ is the\nstandard deviation of disturbance.\n\n\\textit{Monetary authority. }The monetary authority follows a Taylor rule with\na zero lower bound (ZLB) on the nominal interest rate:\n\n\\begin{equation}\nR_{t}=\\max \\left \\{ R_{\\ast }\\left( \\frac{R_{t-1}}{R_{\\ast }}\\right) ^{\\mu }\n\\left[ \\left( \\frac{\\pi _{t}}{\\pi _{\\ast }}\\right) ^{\\phi _{\\pi }}\\left(\n\\frac{Y_{t}}{Y_{N,t}}\\right) ^{\\phi _{y}}\\right] ^{1-\\mu }\\exp \\left( \\eta\n_{R,t}\\right) ,1\\right \\} ,  \\label{Tr2}\n\\end{equation}\n\nwhere $R_{\\ast }$ is the long-run value of the gross nominal interest rate; $\n\\pi _{\\ast }$ is the target inflation; $Y_{N,t}$ is the natural level of\noutput; and $\\eta _{R,t}$ is a monetary shock,\n\n\\begin{equation}\n\\eta _{R,t+1}=\\rho _{R}\\eta _{R,t}+\\epsilon _{R,t+1},\\qquad \\epsilon\n_{R,t+1}\\sim \\mathcal{N}\\left( 0,\\sigma _{R}^{2}\\right) ,  \\label{nuR}\n\\end{equation}\n\nwhere $\\rho _{R}$ is the autocorrelation coefficient, and $\\sigma _{R}$ is the\nstandard deviation of disturbance.\n\n\\textit{Natural level of output. }The natural level of output $Y_{N,t}$ is the\nlevel of output in an otherwise identical economy but without distortions. It\nis a solution to the following planner's problem\n\n\\begin{gather}\n\\underset{\\left \\{ C_{t},L_{t}\\right \\} _{t=0,...,\\infty }}{\\max }E_{0}\n\\overset{\\infty }{\\underset{t=0}{\\sum }}\\beta ^{t}\\exp \\left( \\eta\n_{u,t}\\right) \\left[ \\frac{C_{t}^{1-\\gamma }-1}{1-\\gamma }-\\exp \\left( \\eta\n_{L,t}\\right) \\frac{L_{t}^{1+\\vartheta }-1}{1+\\vartheta }\\right]  \\label{Pob}\n\\\\\n\\text{s.t. }C_{t}=\\exp \\left( \\eta _{a,t}\\right) L_{t}-G_{t},  \\label{Pbc}\n\\end{gather}\n\nwhere $G_{t}=\\frac{\\overline{G}Y_{t}}{\\exp \\left( \\eta _{G,t}\\right) }$ is\ngiven, and $\\eta _{u,t+1}$, $\\eta _{L,t+1}$, $\\eta _{a,t+1}$, and $\\eta _{G,t}$\nfollow the processes (\\ref{nuu}), (\\ref{nuL}), (\\ref{nua}), and (\\ref {nuG}),\nrespectively.\n\n\\paragraph{Parameterization and implementation details}\n\nMost of the parameters are calibrated using the estimates of Del Negro et al.\n(2007, Table 1, column \"DSGE posterior\"); namely, we assume $\\gamma =1$ and\n$\\vartheta =2.09$ in the utility function (\\ref{uNK}); $\\phi _{y}=0.07$, $\\phi\n_{\\pi }=2.21$, and $\\mu =0.82$ in the Taylor rule (\\ref{Tr2}); $ \\varepsilon\n=4.45$ in the production function of the final-good firm (\\ref {bcfin});\n$\\theta =0.83$ (the fraction of the intermediate-good firms affected by price\nstickiness); $\\overline{G}=0.23$ in the government budget constraint\n(\\ref{Gbc}); and $\\rho _{u}=0.92$, $\\rho _{G}=0.95$, $\\rho _{L}=0.25$, $\\sigma\n_{u}=0.54\\%$, $\\sigma _{G}=0.38\\%$, $\\sigma _{L}=18.21\\%$ (the latter is a\nlower estimate of Del Negro et al., 2007, Table 1, column \"DSGE posterior\"),\nand $\\sigma _{L}=40.54\\%$ (an average estimate of Del Negro et al., 2007) in\nthe processes for shocks (\\ref{nuu}), (\\ref{nuG}) and (\\ref{nuL}). From Smets\nand Wouters (2007), we take the values of $\\rho _{a}=0.95$, $\\rho _{B}=0.22$,\n$\\rho _{R}=0.15$, $\\sigma _{a}=0.45\\%$, $ \\sigma _{B}=0.23\\%$ and $\\sigma\n_{R}=0.28\\%$ in the processes for shocks ( \\ref{nua}), (\\ref{nuB}) and\n(\\ref{nuR}). We set the discount factor at $ \\beta =0.99$. To parameterize the\nTaylor rule (\\ref{Tr2}), we use the steady-state interest rate $R_{\\ast\n}=\\frac{\\pi _{\\ast }}{\\beta }$, and we consider two alternative values of the\ntarget inflation, $\\pi _{\\ast }=1$ (a zero net inflation target) and $\\pi\n_{\\ast }=1.0598$ (this estimate comes from Del Negro et al., 2007).\n\nTo approximate the equilibrium policy rules, we use a family of ordinary\npolynomials. To compute conditional expectations in Euler equations (\\ref\n{NK1}), (\\ref{NK2}) and (\\ref{NK5}), we use a monomial integration rule (either\na formula with $2N$ nodes or the one with $2N^{2}+1$ nodes); see Judd, Maliar\nand Maliar (Quantitative Economics, 2011) for a detailed description of the\nmonomial integration formulas. To compute a solution, we use two alternative\ngrids: one is a random grid composed of uniformely distributed points (i.e., we\nmake independent random draws for all variables in the grid within the given\nrange), and the other is a quasi-Monte Carlo grid (namely, a Sobol grid that\nfills in a given multidimensional hypercube). In Step 2b, the damping parameter\nis set at $\\xi =0.1$, and the convergence parameter is set at $\\varpi\n=10^{-7}$. The solution algorithm is described in Appendix.\n\n\\paragraph{Computational method}\n\nIn Appendix B, we describe an Euler equation algorithm, which we use to solve\nthe new Keynesian model described in Section 3.\n\n{\\small\n\\begin{tabular}{l}\n\\hline \\hline\n\\textbf{An algorithm iterating on the Euler equation} \\\\ \\hline\n\\textit{Step 1. Initialization.} \\\\ \\hline\n{\\quad a. Choose }$\\left( {\\Delta }_{{-1}}{,R}_{{-1}}{,\\eta }_{{u,0}}{,\\eta }\n_{{L,0}}{,\\eta }_{{B,0}}{,\\eta }_{{a,0}}{,\\eta }_{{R,0}}{,\\eta }_{{G,0}\n}\\right) ${\\ and }${T}${.} \\\\\n{\\quad b. Draw }$\\left \\{ {\\epsilon }_{{u,t+1}}{,\\epsilon }_{{L,t+1}}{\n,\\epsilon }_{{B,t+1}}{,\\epsilon }_{{a,t+1}}{,\\epsilon }_{{R,t+1}}{,\\epsilon }\n_{{G,t+1}}\\right \\} _{{t=0,...,T-1}}${. } \\\\\n{\\quad \\quad Compute and fix }$\\left \\{ {\\eta }_{{u,t+1}}{,\\eta }_{{L,t+1}}{\n,\\eta }_{{B,t+1}}{,\\eta }_{{a,t+1}}{,\\eta }_{{R,t+1}}{,\\eta }_{{G,t+1}\n}\\right \\} _{{t=0,...,T-1}}${.} \\\\\n{\\quad c. Choose approximating functions }${S\\approx }\\widehat{{S}}\\left( {\n\\cdot ;b}^{{S}}\\right) ${, }${F\\approx }\\widehat{{F}}\\left( {\\cdot ;b}^{{F}\n}\\right) ${, MU}${\\approx }\\widehat{\\text{{MU}}}\\left( {\\cdot ;b}^{\\text{{MU}\n}}\\right) ${.} \\\\\n{\\quad d. Make initial guesses on }${b}^{{S}}${, }${b}^{{F}}${, }${b}^{\\text{\n{MU}}}${. } \\\\\n{\\quad e. Choose integration nodes, }$\\left \\{ {\\epsilon }_{{u,j}}{,\\epsilon\n}_{{L,j}}{,\\epsilon }_{{B,j}}{,\\epsilon }_{a,j}{,\\epsilon }_{{R,j}}{\n,\\epsilon }_{{G,j}}\\right \\} _{{j=1,...,J}}${\\ and weights, }$\\left \\{ {\n\\omega }_{{j}}\\right \\} _{{j=1,...,J}}${.} \\\\ \\hline\n{\\quad f. Constuct a grid }${\\Gamma }=\\left \\{ {\\Delta }_{{m}}{,R}_{{m}}{\n,\\eta }_{{u,m}}{,\\eta }_{{L,m}}{,\\eta }_{{B,m}}{,\\eta }_{{a,m}}{,\\eta }_{{R,m\n}}{,\\eta }_{{G,m}}\\right \\} _{{m=1,...,M}}\\equiv \\left \\{ {x}_{{m}}\\right \\}\n_{{m=1,...,M}}${\\ } \\\\ \\hline\n\\textit{Step 2. Computation of a solution for }$S$\\textit{, }$F$\\textit{, MU.\n} \\\\ \\hline\n{\\quad a. At iteration }${i}${, for }${m=1,...,M}${, compute} \\\\\n\\quad -- ${S}_{{m}}=\\widehat{{S}}\\left( {x}_{{m}}{;b}^{{S}}\\right) ${, }${F}\n_{{m}}=\\widehat{{F}}\\left( {x}_{{m}}{;b}^{{F}}\\right) ${, }${C}_{{m}}=\\left[\n\\widehat{\\text{{MU}}}\\left( {x}_{{m}}{;b}^{\\text{{MU}}}\\right) \\right] ^{{\n-1/\\gamma }}${;} \\\\\n\\quad -- ${\\pi }_{{m}}$ {from} $\\frac{{S}_{m}}{{F}_{m}}{=}\\left[ \\frac{{\n1-\\theta \\pi }_{m}^{\\varepsilon -1}}{{1-\\theta }}\\right] ^{\\frac{1}{\n1-\\varepsilon }}${\\ and }${\\Delta }_{{m}}^{\\prime }{=}\\left[ \\left( {\n1-\\theta }\\right) \\left[ \\frac{{1-\\theta \\pi }_{m}^{\\varepsilon -1}}{{\n1-\\theta }}\\right] ^{\\frac{\\varepsilon }{\\varepsilon -1}}{+\\theta }\\frac{{\n\\pi }_{m}^{\\varepsilon }}{{\\Delta }_{m}}\\right] ^{{-1}}${;} \\\\\n\\quad -- ${Y}_{{m}}=\\left( {1}-\\frac{\\overline{G}}{\\exp \\left( \\eta\n_{G,m}\\right) }\\right) ^{{-1}}{C}_{{m}}${, and }${L}_{{m}}={Y}_{{m}}\\left[ {\n\\exp }\\left( {\\eta }_{{a,m}}\\right) {\\Delta }_{{m}}^{{\\prime }}\\right] ^{-1}$\n{;} \\\\\n\\quad --{\\ }${Y}_{{N},{m}}=\\left[ \\frac{{\\exp }\\left( {\\eta }_{a,m}\\right)\n^{1+\\vartheta }}{\\left[ {\\exp }\\left( {\\eta }_{{G,m}}\\right) \\right]\n^{-\\gamma }{\\exp }\\left( {\\eta }_{{L,m}}\\right) }\\right] ^{\\frac{1}{\n\\vartheta +\\gamma }}${;} \\\\\n{\\quad }--{\\ }${R}_{{m}}^{{\\prime }}={\\max }\\left \\{ {1,}\\text{ }{\\Phi }_{{m}\n}\\right \\} ${, }${\\Phi }_{{m}}{=R}_{\\ast }\\left( \\frac{R_{m}}{R_{\\ast }}\n\\right) ^{{\\mu }}\\left[ \\left( \\frac{\\pi _{m}}{\\pi _{\\ast }}\\right) ^{{\\phi }\n_{\\pi }}\\left( \\frac{Y_{m}}{Y_{N,m}}\\right) ^{{\\phi }_{y}}\\right] ^{{1-\\mu }}\n{\\exp }\\left( {\\eta }_{{R,m}}\\right) ${;} \\\\\n{\\quad }--{\\ }${x}_{{m,j}}^{{\\prime }}=\\left( \\Delta _{{m}}^{{\\prime }},{R}_{\n{m}}^{{\\prime }},{\\eta }_{{u,m,j}}^{{\\prime }},\\eta _{{L,m,j}}^{{\\prime }\n},\\eta _{{B,m,j}}^{{\\prime }},\\eta _{{a,m,j}}^{{\\prime }},\\eta _{{R,m,j}}^{{\n\\prime }},\\eta _{{G,m,j}}^{{\\prime }}\\right) ${\\ for all }${j}${;} \\\\\n{\\quad }--{\\ }${S}_{{m,j}}^{{\\prime }}{=}\\widehat{{S}}\\left( {x}_{{m,j}}^{{\n\\prime }}{;b}^{{S}}\\right) ${, }${F}_{{m,j}}^{{\\prime }}=\\widehat{{F}}\\left(\n{x}_{{m,j}}^{{\\prime }}{;b}^{{F}}\\right) ${, }${C}_{{m,j}}^{{\\prime }}{=}\n\\left[ \\widehat{\\text{{MU}}}\\left( {x}_{{m,j}}^{{\\prime }}{;b}^{\\text{{MU}}\n}\\right) \\right] ^{{-1/\\gamma }}${;} \\\\\n{\\quad }-- ${\\pi }_{{m,j}}^{{\\prime }}${\\ from }$\\frac{{S}_{m,j}^{\\prime }}{{\nF}_{m,j}^{\\prime }}{=}\\left[ \\frac{{1-\\theta }\\left( \\pi _{m,j}^{^{\\prime\n}}\\right) ^{\\varepsilon -1}}{{1-\\theta }}\\right] ^{\\frac{{1}}{{1-\\varepsilon\n}}}${;} \\\\\n\\quad -- $\\widehat{{S}}_{{m}}{=}\\frac{{\\exp }\\left( {\\eta }_{{u,m}}{+\\eta }_{\n{L,m}}\\right) }{{\\exp }\\left( {\\eta }_{{a,m}}\\right) }{L}_{{m}}^{{\\vartheta }\n}{Y}_{{m}}{+\\beta \\theta }\\underset{{j=1}}{\\overset{{J}}{\\sum }}{\\omega }_{{j\n}}{\\cdot }\\left \\{ \\left( {\\pi }_{{m,j}}^{{\\prime }}\\right) ^{{\\varepsilon }}\n{S}_{{m,j}}^{{\\prime }}\\right \\} ,$ \\\\\n\\quad -- $\\widehat{{F}}_{{m}}={\\exp }\\left( {\\eta }_{{u,m}}\\right) {C}_{{m}\n}^{{-\\gamma }}{Y}_{{m}}{+\\beta \\theta }\\underset{{j=1}}{\\overset{{J}}{\\sum }}\n{\\omega }_{{j}}{\\cdot }\\left \\{ \\left( {\\pi }_{{m,j}}^{^{\\prime }}\\right) ^{{\n\\varepsilon -1}}{F}_{{m,j}}^{{\\prime }}\\right \\} {,}$ \\\\\n\\quad -- $\\widehat{{C}}_{{m}}^{{-\\gamma }}{=}\\frac{{\\beta \\exp }\\left( \\eta\n_{{B,m}}\\right) {R}_{{m}}^{{\\prime }}}{{\\exp }\\left( {\\eta }_{{u,m}}\\right) }\n\\underset{{j=1}}{\\overset{{J}}{\\sum }}{\\omega }_{{j}}\\cdot \\left[ \\frac{\n\\left( {C}_{{m,j}}^{\\prime }\\right) ^{{-\\gamma }}{\\exp }\\left( {\\eta }_{{\nu,m,j}}^{{\\prime }}\\right) }{{\\pi }_{{m,j}}^{{\\prime }}}\\right] .$ \\\\\n\\quad {b. Find }${b}^{{S}}$, ${b}^{{F}}$, ${b}^{\\text{{MU}}}$ {that solve\nthe system in Step 2a}. \\\\\n\\quad -- {Get: }$\\widehat{{b}}^{{S}}\\equiv {\\arg }\\underset{{b}^{{S}}}{{\\min\n}}\\sum_{{m=1}}^{{M}}\\left \\Vert \\widehat{{S}}_{{m}}-\\widehat{{S}}\\left( {x}_{\n{m}};{b}^{{S}}\\right) \\right \\Vert ${. Similarly, get }$\\widehat{{b}}^{{F}}${\n\\ and }$\\widehat{{b}}^{\\text{{MU}}}${.} \\\\\n\\quad -- {Use damping to compute }${b}^{\\left( {i+1}\\right) }=\\left( {1-\\xi }\n\\right) {b}^{\\left( {i}\\right) }{+\\xi }\\widehat{{b}} ${, where }${b}\\equiv\n\\left( \\widehat{{b}}^{{S}},\\widehat{{b}}^{{F}},\\widehat{{b}}^{\\text{{MU}}\n}\\right) ${.} \\\\\n\\quad -- {Check for convergence: end Step 2 if} \\\\ \\hline\n\\quad $\\frac{{1}}{{M}}{\\max }\\left \\{ \\mathop{\\displaystyle \\sum } \\limits_{{\nm=1}}^{{M}}\\left \\vert \\frac{\\left( {S}_{{m}}\\right) ^{\\left( {i+1}\\right)\n}-\\left( {S}_{{m}}\\right) ^{\\left( i\\right) }}{\\left( {S}_{{m}}\\right)\n^{\\left( i\\right) }}\\right \\vert {,}\\mathop{\\displaystyle \\sum } \\limits_{{\nm=1}}^{{M}}\\left \\vert \\frac{\\left( {F}_{{m}}\\right) ^{\\left( i+1\\right)\n}-\\left( {F}_{{m}}\\right) ^{\\left( i\\right) }}{\\left( {F}_{{m}}\\right)\n^{\\left( i\\right) }}\\right \\vert {,}\\mathop{\\displaystyle \\sum } \\limits_{{\nm=1}}^{{M}}\\left \\vert \\frac{\\left( \\text{{MU}}_{{m}}\\right) ^{\\left( {i+1}\n\\right) }-\\left( \\text{{MU}}_{{m}}\\right) ^{\\left( {i}\\right) }}{\\left(\n\\text{{MU}}_{{m}}\\right) ^{\\left( {i}\\right) }}\\right \\vert \\right \\} {\n<\\varpi }$. \\\\ \\hline\n\\textit{Iterate on Step 2 until convergence.} \\\\ \\hline \\hline\n\\end{tabular}\n}\n\nWe compute residuals on a stochastic simulation of $10,200$ observations (we\neliminate the first $200$ observations). In the test, we use a monomial rule\n$M2$ with $2\\cdot 6^{2}+1$ nodes which is more accurate than the other monomial\nrule $M1$.\n", "meta": {"hexsha": "9705cc29863e087a486ce5eb8cfb6c2acc442936", "size": 33610, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ms/sections/CLMM/appendix.tex", "max_stars_repo_name": "cc7768/Dissertation", "max_stars_repo_head_hexsha": "813210c2f92122bb0c05f6ad7f5a9ede04993781", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ms/sections/CLMM/appendix.tex", "max_issues_repo_name": "cc7768/Dissertation", "max_issues_repo_head_hexsha": "813210c2f92122bb0c05f6ad7f5a9ede04993781", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ms/sections/CLMM/appendix.tex", "max_forks_repo_name": "cc7768/Dissertation", "max_forks_repo_head_hexsha": "813210c2f92122bb0c05f6ad7f5a9ede04993781", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-12-31T22:54:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-03T18:48:22.000Z", "avg_line_length": 48.6396526773, "max_line_length": 99, "alphanum_fraction": 0.605980363, "num_tokens": 13408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.340121117766051}}
{"text": "\\chapter{Theoretical Background}\nAs seen in the related work section, many sophisticated ideas have already been proposed stating how the task of motion segmentation on RGB-D videos can be addressed. In this thesis, we aim to approach this issue by incorporating optical flow fields to track motion trajectories and then group them by running a spectral clustering. However, there exist many possibilities how to implement a spectral clustering on trajectories. \\\\ \\\\\nIn this chapter we give an introduction about various mathematical concepts which form the fundament to understand the implementation of our motion segmentation pipeline and how its results were computed. In particular, we will discuss the concepts of optical flow and spectral clustering, since they are essential concepts used throughout this thesis. \\\\ \\\\\nWe start by defining a general motion segmentation pipeline and elaborate on its stages, which later will be used as a blue print for our later pipeline implementation. Next we give a brief introduction in optical flow fields by offering the reader a basic definition, some insights about the pioneering motion estimation work of Horn and Schunck and summarize four modern flow methods. We will see that optical flow fields are particularly useful for tracking point trajectories. Since we determine motion by grouping trajectories, the quality of the optical flow affects the final outcome of the motion segmentation. \\\\ \\\\\nFinally, since our pipeline implements segmentation methods that are all based on spectral clustering variants, we wrote a dedicated section about clustering data points, in which we explain the idea behind clustering methods and how they can be implemented. Moreover, we state some important definitions about similarity graphs and their properties, how to form the Laplacian matrix from a similarity graphs and the differences between k-means and spectral clustering. We conclude this section by stating that optimizing for the minimum cut on a similarity graph is an equivalent to the problem of computing the spectral clustering on its Laplacian matrix. \n\n\\section{General Motion Segmentation Pipeline}\nIn this section, we conceptually describe how the task of motion segmentation can be approached. As mentioned earlier, motion segmentation is the task of decomposing a video sequence into its moving objects and into its background. The idea is to separate image regions that undergo different motion patterns. Therefore, we want to consider motion not independently for each frame but rather the whole history of a point to make a grouping decision. The history of a point can be represented by point trajectories which are the result of a point tracker. The point tracking is based on optical flow fields. \\\\ \\\\\nSince point trajectories have a temporal- (via the frames the capture) as well as a spatial (via image location in captured frames via the tracked points) component, they are an ideal intermediate representation for the motion of object parts.\n\\begin{figure}[H]\n\\begin{center}\n\\includegraphics[width=1\\linewidth] {background/general_pipeline}\n\\end{center}\n\\caption[General Motion Segmentation Pipeline]{A sketch of a motion segmentation pipeline$\\footnotemark$ consists of the two stages: track motion trajectories and group trajectories on their similarities. For a given RGB-D video sequence we first have to track motion trajectories on reliable features. By comparing the resulting trajectories according to a certain measure we can perform a grouping. Every group consists of similar trajectories. The final motion segmentation is directly represented by the grouped trajectories.}\n\\label{fig:general_moseg_pipeline}\n\\end{figure}\n\\footnotetext{To create Figure $\\ref{fig:general_moseg_pipeline}$ I used a frame of the Bonn Chairs dataset from: \\url{http://www.ais.uni-bonn.de/download/rigidmultibody/}}\nIn recent Computer Vision literature, various contributions have already successfully demonstrated that motion segmentations can be cast as the problem of clustering point trajectories from an image sequence with respect to their motion. For instance in $\\cite{OB14b}$, T.Brox et al implemented a motion segmentation based on a spectral clustering on motion trajectories. In particular, they described a certain similarity measure that can be used to form such a similarity matrix. In $\\cite{KB15b}$ the authors followed a similar approach but formed a similarity graph. The segmentation was generated by running a multi min-cut. \\\\ \\\\\nIn this thesis we want to follow a similar approach as described in those two contribution. For this purpose we compared their segmentation pipelines and derived a general motion segmentation pipeline as sketched in Figure $\\ref{fig:general_moseg_pipeline}$. In summary, a motion segmentation pipeline implements the following main stages:\n\\begin{enumerate}\n\t\\item Compute optical flow fields on the video sequence.\n\t\\item Extract meaningful motion feature locations in the video frames.\n\t\\item Track motion trajectories on feature locations using the flow fields.\n\t\\item Compute affinities between these trajectories and form a similarity matrix.\n\t\\item Group the trajectories via a spectral clustering on the affinity matrix.\n\\end{enumerate}\nHowever, keep in mind that this motion segmentation technique also suffers from some issues: Trajectories usually start and end in different frames due to occlusion and disocclusion. Therefore, it is crucial to know where points get occluded. Furthermore, there are various metrics that can be used to compute distances between trajectories, such as their spatial-, color- or motion-distance. Moreover, there are many mathematical variants to solve the problem of spectral clustering. Lastly, the used optical flow estimation method should be carefully chosen since it affects the quality of the final segmentation. \\\\ \\\\\nIn next chapter we describe how we implemented such a motion segmentation pipeline by following these main stages. In particular, we will address all issues described above and provide robust solutions.\n\n\\section{Optical Flow}\n\\label{sec:optical_flow}\nIn this section we, explain the principles and the idea behind optical flow. We motivate this concept by discussing an intuitive example, followed by stating a mathematical definition. Furthermore, we explain how such a flow field could be visually represented. Lastly, we summarize and elaborate on the pioneering formulation of Horn and Schnunck, which can be used to estimate flow fields.\n\n\\subsection{Motivation}\nThe optical flow ($\\textbf{OF}$) is a vector field that defines a point-to-point correspondence between two successive frames. Each vector acts as the displacement of a point in the first frame to match its corresponding point in the second frame. In other words, the OF represents the pixel motion field as observed in images and thus answers the question which pixel went where in its successor frame. Ideally, the optical flow is the projection of the three dimensional motion on an image. \\\\ \\\\\nFigure $\\ref{fig:optical_flow_math_def_eg}$ illustrates the idea of the point-to-point correspondence using optical flow fields.\n\\begin{figure}[H]\n\\begin{center}\n\\includegraphics[width=1\\linewidth] {background/of/rubiks_cube_frames}\n\\end{center}\n\\caption[Spinning Rubik's Cube]{An illustration$\\footnotemark$ of two frames of a spinning Rubik's Cube. The point-to-point correspondence of a sample point (the orange point) is given by the optical flow, depicted as a red arrow.}\n\\label{fig:optical_flow_math_def_eg}\n\\end{figure}\n\\footnotetext{The unprocessed image shown in this figure has been taken from: \\\\ \\url{http://robotics.eecs.berkeley.edu/~sastry/ee20/vision3/node2.html}}\nIn this figure two frames of a spinning Rubik's cube at different times are shown. The orange point $p = (x,y)$ at time $t$ is tracked to the position $(x+u, y+v)$ at time $t+dt$ by adding the optical flow $(u,v)$ (visualized by a red arrow) to $p$. This matter of a fact can mathematically be modelled via the brightness consistency assumption, stated in Equation $\\ref{eq:of_brightness_const}$.\n\\begin{equation}\n\tI_{t} \\left( x,y \\right) = I_{t+dt} \\left( x+u, y+v \\right)\n\\label{eq:of_brightness_const}\n\\end{equation}\nWhere $I_t$ depicts the brightness at frame $t$.\n\n\\subsection{Visualization of Flow Fields}\nFor visualizing flow fields we use the Middlebury$\\cite{Baker2011}$ flow color encoding$\\footnote{The corresponding visualizer script can be found at \\url{http://vision.middlebury.edu/flow/submit/}}$ shown in Subfigure $\\ref{fig:color_encoding_flows_a}$. The shown color plate provides color values for the normalized$\\footnote{One way to normalize a set of vectors is the following: Divide each vector by the maximal length of these vectors.}$ flow vectors. The angle in the circle corresponds to the flow direction and the distance to the center corresponds to the flow velocity. Moreover, Figure $\\ref{fig:color_encoding_flows}$ also contains an example of a flow visualization using these color codes. As we can see the cars are moving to the bottom-right direction at a intermediate velocity.\n\\begin{figure}[H]\n\\begin{center}\n\\subfigure[Flow Color Codes]{\n   \\includegraphics[width=0.40\\linewidth] {background/of/flowfield_color_encoding}\n   \\label{fig:color_encoding_flows_a}\n}\n~\n\\subfigure[Example flow visualization]{\n   \\includegraphics[width=0.535\\linewidth] {background/of/cars_fwf_1}\n   \\label{fig:color_encoding_flows_b}\n}\n\\end{center}\n\\caption[Visual Color Encoding of Flow Fields]{On the left a visualization of the color plate used to draw flow fields and on the right flow field visualized by this color scheme.}\n\\label{fig:color_encoding_flows}\n\\end{figure}\n\n\\subsection{Original Flow Estimation Method of H.S.}\n\\label{sec:hs_formulation}\nIn the pioneering work of $\\cite{Hs81}$, B. Horn and B. Schnunck describe a technique to estimate the optical flow. Their method assumes smoothness in the flow over the whole image. Their flow estimation is formulated as a global energy functional and can numerically be solved via the Jocobi method$\\footnote{The Jacobi method is an iterative method used to solve linear systems.}$. The advantage of their method is that it produces flow fields where the inner parts of homogeneous objects is filled in from the motion boundaries. However, its downside is that is very sensitive to noise. \\\\ \\\\\nBack then they defined the optical flow as \\textit{the distribution of apparent velocities of movement of brightness patterns in an image}. \\\\ \\\\\nMoreover, they already understood the potential of the optical flow and stated the following properties: It can arise from relative motion between objects and the viewer, provides information about the spatial arrangement of the viewed objects and the rate of change in that arrangement. Moreover, they mentioned that discontinuities in the optical flow can help to perform segmentation tasks. \\\\ \\\\\nSticking to their flow definition they derived an equation that relates the change in the image brightness at a point to the motion of the brightness. \\\\ \\\\\nTheir formulation is based on the following assumptions:\n\\begin{itemize}\n  \\item The surface is assumed to be flat. This avoids brightness variations due to shading effects.\n  \\item The incident illumination is uniform across the surface. Then, the brightness at a point in the image is proportional to the reflectance of the surface at the corresponding point on the object.\n  \\item The Reflectance varies smoothly and has no spatial discontinuities. Having no discontinuities assures that the image brightness is differentiable.\n  \\item Situations where objects occlude one another are excluded.\n\\end{itemize}\nThese assumptions allow to conclude, that in their model the brightness of a particular point in the pattern is constant. \\\\ \\\\\nLet the image brightness at a point $(x,y)$ in the image plane at time $t$ be denoted by $E(x,y,t)$. Since the brightness of any point is constant, the total derivative $\\frac{d E}{dt}$ is zero. Using the chain rule for differentiation, they derived the expression in Equation $\\ref{eq:flow_eq}$.  \n\\begin{equation}\n\\begin{aligned}\n0 &= \\frac{d E}{dt} \\\\\n&= \\frac{\\partial E}{\\partial x} \\frac{x}{dt} + \\frac{\\partial E}{\\partial y} \\frac{y}{dt} + \\frac{\\partial E}{\\partial t} \\\\\n&= E_{x} u + E_{y} v + E_{t}\n\\end{aligned}\n\\label{eq:flow_eq}\t\n\\end{equation}\nwhere we the following substitutions were used to derive the last identity of Equation $\\ref{eq:flow_eq}$:\n\\begin{equation}\n\\begin{aligned}\n\tu = \\frac{dx}{dt} \\text{ and } v = \\frac{dy}{dt}\n\\end{aligned}\n\\end{equation}\nBy re-ordering the terms of Equation $\\ref{eq:flow_eq}$ the same way like it has been done in Equation $\\ref{eq:reordered_flow_eq}$:\n\\begin{equation}\n\\begin{aligned}\n\t(E_x, E_y) \\cdot (u, v) &= -E_t \\\\\n\t\\underbrace{-\\frac{1}{E_t}\\left( E_x, E_y \\right)}_\\text{known} \\cdot \\underbrace{(u, v)}_\\text{unknown} &= 1\n\\end{aligned}\n\\label{eq:reordered_flow_eq}\n\\end{equation}\nHence, they could show that the change in image brightness can be formulated by a single linear equations with two unknowns $u$ and $v$, the so called $\\textit{flow velocity}$. As a consequence, such a flow velocity cannot be computed locally without introducing additional constraints. \\\\ \\\\\nIn their formulation they express their additional constraint by stating that the square of the magnitude of the gradient of the optical flow velocity, as defined in Equation $\\ref{eq:smoothness_constraints}$\n\\begin{equation}\n\t\\left( \\frac{\\partial u}{\\partial x} \\right)^2 + \\left( \\frac{\\partial u}{\\partial y} \\right)^2 \\text{ and } \\left( \\frac{\\partial v}{\\partial x} \\right)^2 + \\left( \\frac{\\partial v}{\\partial y} \\right)^2,\n\\label{eq:smoothness_constraints}\n\\end{equation}\nshould be minimal. The remaining problem is then to minimize the sum of the energies modelling the rate of image brightness change as stated in Equation $\\ref{eq:energy_brightness}$\n\\begin{equation}\n\tE_b = E_x u + E_y v + E_t\n\\label{eq:energy_brightness}\n\\end{equation}\nand the measure of the departure from smoothness in the velocity flow, as formulated in Equation $\\ref{eq:energy_constraint}$.\n\\begin{equation}\n\tE_c^2 = \\norm{\\nabla u}^2 + \\norm{\\nabla v}^2\n\\label{eq:energy_constraint}\n\\end{equation}\nThe total error to be minimized is therefore equal to the energy term formulated in Equation $\\ref{eq:final_hs_energy_term}$.\n\\begin{equation}\n\tE = \\int \\int \\left( E_b^2 + \\alpha^2 E_c^2 \\right) dx dy\n\\label{eq:final_hs_energy_term}\n\\end{equation}\nThis flow estimation formulation assumes smoothness in the flow over the whole image. Hence, minimzing this energy results in a minimization of distortions in the flow and thus prefers solutions which exhibit more smoothness. The scalar $\\alpha$ acts as a regularization constant, that weights the influence of the smoothness term. Hence, larger values for $\\alpha$ lead to soother flow estimations. \\\\ \\\\\nThis minimization can analytically be solved by formulating its multi-dimensional Euler-Lagrange equations as formulated in Equation $\\ref{eq:multi_dim_euler_lagrange}$.\n\\begin{equation}\n\\begin{aligned}\n \\frac{\\partial L}{\\partial u} - \\frac{\\partial}{\\partial x} \\frac{\\partial L}{\\partial u_x} - \\frac{\\partial}{\\partial y}\\frac{\\partial L}{\\partial u_y} &= 0 \\\\\n\\frac{\\partial L}{\\partial v} - \\frac{\\partial}{\\partial x} \\frac{\\partial L}{\\partial v_x} - \\frac{\\partial}{\\partial y}\\frac{\\partial L}{\\partial v_y} &= 0  \n\\end{aligned}\n\\label{eq:multi_dim_euler_lagrange}\n\\end{equation}\nwhere L denotes the integrand of the energy expression, given by Equation $\\ref{eq:def_l_euler_lag}$:\n\\begin{equation}\n\\begin{aligned}\nE_x E_b - \\alpha^2 \\Delta u &= 0 \\\\\nE_y E_b - \\alpha^2 \\Delta v &= 0 \\\\\n\\end{aligned}\n\\label{eq:def_l_euler_lag}\n\\end{equation}\nWhere $\\Delta$ denotes the Laplace$\\footnote{Definition of the Laplace operator in the two dimensional case: $\\Delta = \\frac{\\partial^2}{\\partial x^2} + \\frac{\\partial^2}{\\partial y^2}$}$ operator. When using a finite differences scheme for approximating the Laplacian equation\nas defined in Equation $\\ref{eq:finite_difference_laplacian}$\n\\begin{equation}\n\t\\Delta u(x,y) = \\bar{u} (x,y) - u(x,y)\n\\label{eq:finite_difference_laplacian}\n\\end{equation}\nwhere $\\bar{u} (x,y)$ denotes the weighted average of u computed by visiting the neighborhood around the pixel at location $(x,y)$, Equation $\\ref{eq:def_l_euler_lag}$ can be simplified to\n\\begin{equation}\n\\begin{aligned}\n(E_x^2 + \\alpha^2) u + E_x E_y v &= \\alpha^2 \\bar{u} - E_x E_t \\\\\n(E_x^2 + \\alpha^2) v + E_x E_y u &= \\alpha^2 \\bar{v} - E_y E_t\n\\end{aligned}\n\\label{eq:def_l_euler_lag_simplified}\n\\end{equation}\nThe equations from above (Eq. $\\ref{eq:def_l_euler_lag_simplified}$) became linear in $u$ and $v$. This allows to solve this minimization problem for each pixel in the image. However, keep in mind that the solution depends on the neighboring values of the flow field. Hence, the system must be solved iteratively. The following update rule can therefore be used:\n\\begin{equation}\n\\begin{aligned}\n u_{k+1} &= \\bar{u}_k - \\frac{E_x (E_x \\bar{u}_k + E_y \\bar{v}_k + E_t)}{\\alpha^2 + E_x^2 + E_y^2} \\\\\n  v_{k+1} &= \\bar{v}_k - \\frac{E_y (E_x \\bar{u}_k + E_y \\bar{v}_k + E_t)}{\\alpha^2 + E_x^2 + E_y^2}\n\\end{aligned}\n\\label{eq:hs_iteration}\n\\end{equation}\n\n\\subsection{Modern Flow Methods}\n\\label{sec:impl_optical_flow}\nIn this section we briefly introduce four modern flow methods by summarizing their corresponding papers and some main points stated in $\\cite{Sun2014}$. In particular, we state the main properties and drawbacks of these flow methods. Discussing those methods particularly makes sense since we use these flow estimation techniques later in our pipeline to generate flow fields (Sec. $\\ref{sec:generate_of}$). \n\n\\subsubsection{Enhanced H.S. Optical Flow Fields}\n\\label{sec:hs_flows}\nIn $\\cite{Deq10}$ Dequing Sun et al studied various flow methods and models and determined the most important factors that increase the quality of produced flow fields. They incorporated their findings in Horn and Schunck's original formulation and contributed a efficient implementation of their method. Additional information about their formulations can be found in Section $\\ref{sec:hs_formulation}$ on page $\\pageref{sec:hs_formulation}$. When using the abbreviation HS we strictly refer to their implementation. \\\\ \\\\\nThe original HS formulation combines a data term that assumes constancy of some image property with a spatial term that models how the flow is expected to vary across the image. The HS model relies on brightness constancy and spatial smoothness assumptions. Unfortunately it is not very robust to outliers. Therefore, the following main improvements were implemented in their methods:\n\\begin{itemize}\n  \\item The quadratic penalty function is replaced by the Charbonnier penalty $p\\left( x \\right) = \\sqrt{x^2 + \\epsilon^2}$. This penalty is supposed to be less error-prone to outliers.\n  \\item An incremental multi-resolution technique is applied to estimate flow fields with large displacements. The optical flow estimated at a coarse level is used to warp the second image toward the first at the next finer level and a flow increment is calculated between the first image and the warped second image. Each level is recursively downsampled by applying a Gaussian filter from its nearest lower level.\n  \\item An enhanced objective function is used, which includes a non-local term that robustly integrates flow estimates over large spatial neighborhoods. This is achieved by applying a median filtering to denoise the flow after every warping step to increase the accuracy.\n\\end{itemize}\n\n\\subsubsection{Large Displacement Optical Flows}\n\\label{sec:ldof_flows}\nBefore the work in $\\cite{Bro11a}$, there was no accurate method present to estimate fast motions of small objects, i.e. large motions. Most flow methods are based on a combination of HS flow formulation and the concept of coarse-to-fine image warping. However, both approaches have been extended by robust statistics to fight outliers and at the same time retain smoothness assumptions. \\\\ \\\\\nTwo fundamental ideas exist to address the issue of large motions. On one hand there are coarse-to-fine techniques. Such techniques, however, require a downsampling. Unfortunately, this also removes details that may be important for the flow accuracy. Consequently, the method cannot refine the flow of structures that are smaller than their displacement, because the structure is smoothed away. Flow Fields produced this way are often close to the motion of the larger scale structures. On the other hand descriptor matching techniques are well suited to match large displacements. However, their resulting correspondences are very sparse, have a limited accuracy and exhibit many outliers due to missing regularity constraints and lastly, there is only a pixel-level accuracy guaranteed. \\\\ \\\\\nIn their paper they propose a method how to combine both strategies. They direct a variational technique using correspondences from sparse descriptor matching. The correspondences determined by the descriptors are directly integrated into the variational approach. This allows to make use of all image information at every level and smoothly scales down the influence of descriptor keypoints as the grid gets finer.\n\n\\subsubsection{Semi Rigid Scene Flows}\n\\label{sec:srsf_flows}\nIn their paper $\\cite{Bro14}$, Quiroga et al. proposed an approach to estimate the scene flow$\\footnote{The term scene flow denotes a motion field in the 3D space, which can be computed from a single view when using RGB-D sensor data.}$ by exploiting the properties of motion in real world scenes. For that purpose they implemented an over-parameterized framework that estimates scene flows from RGBD images. \\\\ \\\\\nThis allows for piecewise smooth solutions using a total variation (TV) regularization$\\footnote{An image denoising technique, which is also known as \\textit{total variation denoising}.}$ on the parameterization. Most real world scenes can be modelled as locally or piecewise rigid. This means that the scene is composed of 3D independently rigid components. Moreover, their formulation offers a general formulation to solve for the local and global motion by jointly using intensity and depth data. \\\\ \\\\\nThey model the scene flow as a 3D vector field consisting of a global rigid motion plus a non-rigid residual. this is particularly useful, when estimating the motion of deformable objects in conjunction with a moving camera. A piecewise smooth solution is estimated using a total variation on the parameterization.\\\\ \\\\\nIn the following some details according to their implementation:\n\\begin{itemize}\n  \\item They represent motions as a 3D vector field of twists, which encourages piecewise-smooth solutions of rigid body motions.\n  \\item Instead of representing the flow vectors in the 3D space, they represent the scene structure in the image domain. Then, color and depth data can be coupled using a projective function. this way depth influences the motion in the image domain and consistency constraints can be formulated jointly over the color and depth images. \n  \\item However, scene flow estimation using intensity and depth is an ill-posed problem and regularization is needed. In their work they use an over-parameterization of the scene flow. Each scene point is allowed to follow a rigid body motion. this way, the regularization can be done on a field of rigid motion.\n  \\item Usually, the 3D motion vector of each point is solved to minimize color and intensity constraints in a data term and the whole 3D motion field is regularized to get spatially smooth solutions while preserving discontinuities. Since depth data is available a weighted regularization can be used to preserve motion discontinuities along depth edges. \n  \\item In order to formulate an efficient 3D motion exploration they use a parameterization provided by RGB-D sensors to formulate an efficient 3D motion exploration. Hence, they define a warping function to couple the twist motion and the optical flow. They use a warping function to locally constrain the rigid motion field in the image domain and define a depth consistency constraint to exploit the sensor data.\n\\end{itemize}\n\n\\subsubsection{Layered RGB-D Flow Fields}\n\\label{sec:lrgbd_flows}\nIn $\\cite{Deq10}$ Dequing Sun et al present a layered RGBD scene flow estimation  method. They make use of the fact that depth information allows to recover 3D motion from a single view. However, in that case, depth boundaries are not well aligned with RGB images. Especially in occluded regions methods produce large errors. As a remedy, they therefore, use the depth fields for occlusion reasoning and formulate a layered RGBD scene flow method that jointly solves for the scene segmentation and the motion. In their formulation, the depth fields are used to estimate the per-layer 3D rigid motion to constraint the motion of each layer. \\\\ \\\\\nThe implementation of their method is freely available on the authors website, written in Matlab. In the following we use the abbreviation LRGBD for flow fields produced by their implementation. \n\n\\section{On Data Clustering}\n\\label{sec:on_data_clustering}\nClustering is a technique for exploratory data analysis and allows to identify groups of similar behaviour. This is achieved by separating data points according to their similarities. \\\\ \\\\\nGenerally, clustering is a hard problem and yet no perfect method exists. As we show in our evaluation section, the choice of the segmentation method has a big influence on the quality of our motion segmentation pipeline. \\\\ \\\\\nIn this section we offer the reader definitions of various such techniques. For writing the content of this section we partially relied on the work of $\\cite{vonLuxburg2007}$. \\\\ \\\\\nIn the following we start by describing the k-means clustering which is a clustering method applied on point clouds and which is popular because of its speed, relative simplicity and robustness. However, a drawback of k-means is that it only works for relatively low-dimensional datasets. \\\\ \\\\ \nIn this thesis, we are mainly working with datasets consisting of point trajectories. This kind of data is not easily embeddable in an Euclidean space. Therefore, we present a more general clustering framework targeting at segmenting graphs. Regardless of the dimensionality of the input data, these method are general enough to work with any kind of data as long as it is possible to compute a distance between data point pairs\n\n\\subsection{K-Means Clustering}\n\\label{sec:k_means}\nThe idea of the k-means clustering algorithm is to partition $n$ observations into $k$ clusters in which each observation belongs to the cluster with the nearest mean. \\\\ \\\\\nGiven a set of observations $(\\textbf{x}_1, \\dots, \\textbf{x}_n)$, where any $\\textbf{x}_k \\in \\mathbb{R}^d$. k-means clustering tries to partition the $n$ observations into $k$ sets $\\textbf{S} = \\{ S_1, \\dots, S_k\\}$ to minimize the sum of distance functions of each point in the cluster to the $k$ centers. Mathematically, this can formulated as follows:\n\\begin{equation}\n\t\\argmin_{\\textbf{S}} \\sum_{i=1}^k \\sum_{\\textbf{x} \\in S_i} \\norm{\\textbf{x} - {\\boldsymbol {\\mu }}_{i}}^2\n\\label{eq:k_means_minimzation_formulation}\n\\end{equation}\nwhere ${\\boldsymbol {\\mu }}_{i}$ is the mean of points in $S_i$, the so called centroid. An example of the k-means algorithm is given in Figure $\\ref{fig:k_means_example}$.\n\\begin{figure}[H]\n\\begin{center}\n\\includegraphics[width=0.8\\linewidth] {background/clustering/k_means_steps}\n\\end{center}\n\\caption[K-Means Example]{An example$\\footnotemark$ of the k-means algorithm. Training examples are shown as dots, and cluster centroids are shown as crosses. (a) Original dataset. (b) Random initial cluster centroids. (c-f) Illustration of running two iterations of k-means. In each iteration, we assign each training example to the closest cluster centroid (shown by \"painting\" the training examples the same color as the cluster centroid to which is assigned); then we move each cluster centroid to the mean of the points assigned to it. Images courtesy of Michael Jordan.}\n\\label{fig:k_means_example}\n\\end{figure}\n\\footnotetext{The caption and the images in Figure $\\ref{fig:k_means_example}$ were taken from: \\\\ \\url{http://stanford.edu/~cpiech/cs221/handouts/kmeans.html}}\nThe k-means clustering equations (Eq. $\\ref{eq:k_means_minimzation_formulation}$) can be iteratively minimized, but without the guarantee of finding a global minimum. Given an initial set of $k$ means $m_1^{(1)}, \\dots, m_k^{(1)}$, the algorithm proceeds by alternating between two steps:\n\\begin{itemize}\n\\item \\textbf{Assignment step}: Assign each observation to the cluster whose mean yields the least sum of distance functions of each point in the cluster. Since the sum of squares is the squared Euclidean distance, this is intuitively the \\enquote{nearest} mean. \n\\begin{equation}\n  \tS_i^{(t)} = \\left\\{ x_p \\mid \\forall j: 1 \\leq j \\leq k: \\norm{x_p - m_i^{(t)}}^2 \\leq \\norm{x_p - m_j^{(t)}}^2 \\right\\}\n\\label{eq:k_means_step_1}\n\\end{equation} \nwhere each $x_p$ is assigned to exactly one $S^{(t)}$.\n\\item \\textbf{Update step}: Calculate the new means to be the centroids of the observations in the new clusters. \n\\begin{equation}\n\tm_i^{(t+1)} = \\frac{1}{\\left| S_i^{(t)} \\right| } \\sum_{x_j \\in S_i^{(t)}} x_j\n\\label{eq:k_means_step_2}\n\\end{equation}\n\\end{itemize}\nThese two steps (Eq. $\\ref{eq:k_means_step_1}$ and Eq. $\\ref{eq:k_means_step_2}$) are repeated until the assignments $\\{S_1, \\dots, S_m \\}$ no longer change. \\\\ \\\\\nThe k-means algorithm is guaranteed to converge to a local minimum because there are a finite number of possible data partitionings, and its objective function$\\footnote{The objective function of the k-means algorithm is to assign each observation to the cluster whose mean yields the least within-cluster sum of squares.}$ must decrease in every step. A corresponding proof of this convergence statement can be found in the paper $\\cite{Bottou95convergenceproperties}$. However, there is no guarantee that the global optimum is found using this algorithm.\\\\ \\\\\nCommonly, clusters are either initialized by using the \\textit{Random}$\\cite{1697556}$ or the \\textit{Forgy}$\\cite{Hamerly:2002:AKA:584792.584890}$ method. The Random method assigns each object a random cluster and then computes the initial centroid of each cluster. The Forgy method chooses k observations randomly from the data set and uses these as the initial means. The appropriate way of initializing the clusters depends on the given problem statement, which the k-means attempts to address. In general, the Random method places the clusters close to the center of the data points, whereas the Forgy method tends to spread the initial means out. However, different local minima are found depending on the chosen initialization of the cluster centers. One way to address this problem is to simply run this algorithm several times, using different initialization. Then, the minima with the lowest error is considered as the optimum.  \n\\subsection{Graph Definitions}\nIn the following we offer the reader some basic graph definitions which are broadly used in this thesis. \\\\ \\\\ \nLet $G = (V, E)$ denote an undirected graph, where $V$ is the set of vertices and $E$ the set of edges. In this work we work with weighted graphs. This means that each edge between two vertices $v_i$ and $v_j$ has a non-negative weight $w_{ij}$. \\\\ \\\\\nThe $\\textbf{weighted adjacency matrix}$ of the graph is the matrix \n\\begin{equation}\nW = \\left( w_{ij} \\right)_{i,j=1,\\dots, n}\n\\label{eq:def_adjacency_matrix}\n\\end{equation}\nIf $w_{ij} = 0$ then the vertices $v_i$ and $v_j$ are \\textbf{not connected} by an edges. \\\\ \\\\\nSince $G$ is assumed to be an \\textbf{undirected graph}, we require\n\\begin{equation}\n\t\\forall i,j : w_{ij} = w_{ji}\n\\end{equation}\nThe \\textbf{degree} of a vertex $v_i \\in V$ is defined as\n\\begin{equation}\n\td_i = \\sum_{j=1}^n w_{ij}\n\\label{eq:vertex_degree}\n\\end{equation}\nIn fact the sum accumulates only weights of edges adjacent to $v_i$, since all other vertices have a weight equals zero. \\\\ \\\\\nThe \\textbf{degree matrix} $D$ is defined as the diagonal matrix with the degrees $d_1,\\dots, d_n$ on the diagonal. \\\\ \\\\\nFor a given subset of vertices $A \\subset V$, its \\textbf{complement} is defined as\n\\begin{equation}\n\t\\bar{A} = V \\setminus A\n\\label{eq:set_complement}\n\\end{equation}\nThe \\textbf{indicator function} is defined as\n\\begin{equation}\n\\begin{aligned}\n& \\mathbbm{1}_A = \\left( f_1, \\dots, f_n \\right)^{T} \\in \\mathbb{R}^n \\\\\n& \\text{where } \\forall i: f_i= \n\\begin{cases}\n    1,& \\text{if } v_i\\in A\\\\\n    0,              & \\text{otherwise}\n\\end{cases}\n\\end{aligned}\n\\end{equation}\nFor the set of indices $\\{ i : v_i \\in A \\}$ we use the shorthand notation $i \\in A$. For two subsets $A, B \\subset V$, which are not necessarily disjoint, we define their \\textbf{set sum} as\n\\begin{equation}\n\tW(A,B) = \\sum_{i \\in A, j \\in B} w_{ij}\n\\label{eq:set_sum}\n\\end{equation}\nFor measuring the size of a subset $A \\subset V$, we either can \\textbf{count} the number of vertices in $A$, which is denoted by $\\left| A \\right|$ or measure the \\textbf{volume} of $A$ defined as\n\\begin{equation}\n\t\\text{vol}(A) = \\sum_{i \\in A} d_i\n\\label{eq:set_volume}\n\\end{equation}\nThe volume is the sum of weights of all edges attached to vertices in $A$.\n\n\\subsection{Similarity Graph}\n\\label{sec:similarity_graphs}\nGiven a set of data points $x_1, \\dots, x_n$ and some notion of similarity $s_{ij} \\geq 0$ between all pairs of data points $x_i$ and $x_j$. Then, our goal is to divide the data points into several groups such that points in the same group are similar and points in different groups are dissimilar to each other. To address this task we represent our data by a similarity graph $G = (V, E)$. \\\\ \\\\\nEach vertex $v_i$ in this graph represents a data point $x_i$. Two vertices are connected if the similarity $s_{ij}$ between the corresponding data point $x_i$ and $x_j$ is positive or larger than a certain threshold and the edge is weighted by $s_{ij}$. The data clustering reduces to the graph partitioning problem. The goal is then to find a partition of the graph such that the edges between different groups have very low weights$\\footnote{This means that points in different clusters are dissimilar from each other.}$ and edges within a group have high weights$\\footnote{which means that points within the same cluster are similar to each other}$. \\\\ \\\\\nThere are several constructions to transform a given set of data points with pairwise similarities $s_{ij}$ or pairwise distances $d_{ij}$ on the graph. The common goal of such a construction is to model the local neighborhood relationships between the data points. In the following several a list of different construction types.\n\\begin{itemize}\n\t\\item The \\textbf{$\\epsilon$-neighborhood graph}: All points whose pairwise distances are smaller than a given $\\epsilon$ are connected. In that case the distances between connected vertices is at the same scale (at most equals $\\epsilon$). Hence, the edge weights do not incorporate additional information about the data on the graph and thus, such a graph is usually considered as an unweighted graph.\n\t\\item The \\textbf{k-nearest neighbor graph}: Vertex $v_i$ is connected with $v_j$ if $v_j$ is among the k-nearest neighbors of $v_i$. This definition usually leads to a directed graph, since this neighborhood relationship is not symmetric. When interested in constructing a undirected graph, we can either ignore the induced edge directions (corresponds to an OR relationship) or connect the vertices if and only if both are nearest neighbors of each other (corresponds to an AND relationship).\n\t\\item The \\textbf{fully connected graph}: All points that exhibit a positive similarity are connected with each other. The edge weight corresponds to their similarity value.\n\\end{itemize}\nFor measuring the distances between data points any kind of metric$\\footnote{For example one could use the Euclidean distance or other kind of norms}$ can be used. \n\n\\subsection{Graph Laplacians}\nIn spectral clustering we are working with the so called graph Laplacian matrices, which can be defined based on the previously discussed adjacency matrix formulation. In this section, we therefore define different graph Laplacians and state some of their properties. \\\\ \\\\\nIn the following we assume that $G$ is an undirected, weighted graph with the positive weight matrix $W$ and $D$ denotes the degree matrix. \\\\ \\\\\nWhen discussing some properties of the eigenvectors of the Laplacian matrix, keep in mind that they do not necessarily have to be normalized. By conventions, we assume the eigenvectors being ordered increasingly. Additionally, when referring to the first $k$ eigenvectors, we mean the eigenvectors that correspond to the $k$ smallest eigenvectors.\n\n\\paragraph{Unnormalized Graph Laplacian}\nThe unnormalized graph Laplacian matrix $L$ of the graph $G$ is defined as\n\\begin{equation}\n\tL = D - W\n\\label{eq:unnormalized_graph_laplacian}\t\n\\end{equation}\nIt has the following properties: \n\\begin{itemize}\n\\item \\begin{equation}\n\t\\forall v \\in \\mathbb{R}^n: v^T L v = \\frac{1}{2\t} \\sum_{i,j=1}^n w_{ij} (v_i - v_j)^2\n\\end{equation}\n\\item L is symmetric and positive semi-defnite$\\footnote{A $n \\times n$ matrix $M$ is called positive semi-definite if and only if $\\forall x \\in \\mathbb{R}^n : x^T M x \\geq 0$ holds true.}$.\n\\item The smallest eigenvalue of L is equal to zero and the corresponding eigenvector is the constant one vector.\n\\end{itemize}\nThe unnormalized graph Laplacian does not depend on the diagonal elements of the matrix W. Each adjacency matrix which coincides with W on all off diagonal positions lead to the same Laplacian L. Moreover, the multiplicity of the eigenvalue zero of $L$ is equal the number of connected components in the graph. A proof of this property can be found in $\\cite{Lux07}$.\n\n\\paragraph{Normalied Graph Laplacian}\nThe symmetric, normalized graph Laplacian matrix $L^{\\text{sym}}$ of the graph $G$ is defined as\n\\begin{equation}\n\tL^{\\text{sym}} = D^{-\\frac{1}{2}} L D^{-\\frac{1}{2}}\n\\label{eq:normalized_graph_laplacian}\t\n\\end{equation}\nwhich has the following properties: \n\\begin{itemize}\n\\item \\begin{equation}\n\t\\forall v \\in \\mathbb{R}^n: v^T L^{\\text{sym}} v = \\frac{1}{2\t} \\sum_{i,j=1}^n w_{ij} \\left( \\frac{v_i}{\\sqrt{d_i}} - \\frac{v_j}{\\sqrt{d_j}} \\right)^2\n\\end{equation}\n\\item Zero is an eigenvalue of $L^{\\text{sym}}$ with the eigenvector $D^{\\frac{1}{2}} \\mathbbm{1}$\n\\item $L^{\\text{sym}}$ is positive semi-definite and has $n$ non-negative real-valued eigenvectors.\n\\end{itemize}\nPlease notice that the definition of Equation $\\ref{eq:normalized_graph_laplacian}$ relies on the definition of the unnormalized graph Laplacian, stated in Equation $\\ref{eq:unnormalized_graph_laplacian}$. Moreover, the multiplicity of the eigenvalue zero of L is equal the number of connected components $A_1, \\dots, A_k$ in the graph G. The Eigenspace of $L^{\\text{sym}}$ is spanned by the vectors $D^{\\frac{1}{2}} \\mathbbm{1}_{A_i}$\n\n\\subsection{Spectral Clustering}\n\\label{sec:spectral_clustering_bg}\nIn this section we describe a clustering technique for grouping data points by using the spectrum of the points' similarity matrix. More precisely, this method performs a dimensionality reduction and then separates the transformed data representation via k-means. \\\\ \\\\\nGiven $n$ data points $x_1, \\dots, x_n$ with their pairwise similarities $s_{ij}$ measured by some similarity function which is symmetric and non-negaitve. Then, the corresponding similarity matrix $S$ is defined as $S = (s_{ij})_{i,j=1,\\dots,n}$. \\\\ \\\\\nThe rationale of the spectral clustering algorithm is to change the abstract representation of the data points $x_i$ to points $y_i \\in \\mathbb{R}^k$, which are easy to cluster using k-means. Algorithm $\\ref{alg:spectral_clustering_algorithm}$ lists the actual step that have to performed to run the spectral clustering algorithm.\n\\begin{algorithm}[H]\n\\caption{Spectral Clustering Algorithm}\n\\begin{table}[H]\n  \\begin{tabular}{@{}lll@{}}\n    \\textbf{Input:} & Similarity matrix $S \\in \\mathbb{R}^{n \\times n}$ \\\\\n\t\t& Number $k$ of clusters to construct \\\\\n    \\textbf{Output:} & Clusters $A_1, \\dots, A_k$ with $A_i = \\{ j : y_j \\in C_i\\}$ \\\\\n  \\end{tabular} \n\\end{table}\n\\setlength{\\fboxrule}{0pt} \n\\begin{boxedminipage}{1.0\\textwidth}\n  \\begin{algorithmic}[1]\n  \t  \\State $\\text{Construct a similarity graph as described in Section }\\ref{sec:similarity_graphs}$\n  \t  \\State $\\text{Let } W \\text{ denote the corresponding weighted adjacency matrix}.$\n  \t  \\State $\\text{Compute the normalized graph Laplacian } L^{\\text{sym}} \\text{ as defined in Equation } \\ref{eq:normalized_graph_laplacian}$\n  \t  \\State $\\text{Compute the first k eigenvectors } u_1,\\dots,u_k \\text{ of } L^{\\text{sym}}$\n  \t  \\State $\\text{Let } U \\in \\mathbb{R}^{n \\times k} \\text{ be the matrix containing the vectors } u_1,\\dots,u_k \\text{ as columns}$\n  \t  \\State $\\text{Form a matrix } T \\in \\mathbb{R}^{n \\times k} \\text{ from U by normalizing the rows}$\n  \t  \\State $\\forall i \\in \\left[ 1, n \\right]: \\text{ Let } y_i \\in \\mathbb{R}^k \\text{ be the vector corresponding to the t-th row of T.}$\n  \t  \\State $\\text{Cluster the points } (y_i)_{i=1,\\dots,n} \\text{ via k-means as described in Section } \\ref{sec:k_means} \\text{ into clusters } C_1, \\dots, C_k$\n  \\end{algorithmic}\n  \\end{boxedminipage}\n  \\vskip1.5pt\n\\label{alg:spectral_clustering_algorithm}\n\\end{algorithm}\nThe actual choice of similarity graph we want to construct depends on the underlying problem statement. A simple spectral clustering example is shown in Figure $\\ref{fig:spectral_clustering_example}$.\n\\begin{figure}[H]\n\\begin{center}\n\\includegraphics[width=0.8\\linewidth] {background/clustering/spectral_clustering_example}\n\\end{center}\n\\caption[Spectral Clustering Example]{A simple spectral clustering example: We want to partition a similarity graph (as shown on the left), which consists of two disconnected subgraphs, into two clusters by running the spectral clustering algorithm (Algorithm $\\ref{alg:spectral_clustering_algorithm}$). The corresponding Laplacian matrix L that graph is a block diagonal matrix with each block defining a cluster (as shown in the center). The two smallest$\\footnotemark$ eigenvectors $u_1$ and $u_2$ directly represent the connected components of the two subgraphs (as shown on the right). The resulting clusters $A_1$ and $A_2$ are shown on the left.}\n\\label{fig:spectral_clustering_example}\n\\end{figure}\n\\footnotetext{By \\textit{smallest eigenvectors} we are referring to those eigenvectors that belong to the smallest eigenvalues $\\lambda$.}\n\n\\subsection{Graph Cut}\n\\label{sec:graph_cut}\nIn this section we relate the problem of clustering to graph partitioning problems. \\\\ \\\\\nFor a similarity graph, the problem of clustering can be reformulated to the task of finding a partition on the graph such that edges between different groups have low weights and edges within the same group have high weights. \\\\ \\\\\nLet $G = (V, E)$ denote a similarity graph and $W$ its corresponding adjacency matrix. Then, one way to obtain a partition of $G$ is to solve the mincut problem. For a given number $k$ of subsets, the mincut tries to find an optimal partition $A_1, \\dots, A_k$ of $G$ which minimizes\n\\begin{equation}\n\\text{cut} \\left( A_1, \\dots, A_k \\right) := \\frac{1}{2} \\sum_{i=1}^k W \\left( A_i, \\bar{A_i} \\right)\n\\label{eq:simple_mincut} \n\\end{equation}\nwhere $\\bar{A}$ denotes the complement of $A$ as defined in Equation $\\ref{eq:set_complement}$ and $W(A,B)$ is the set sum of the subsets $A$, $B$ as defined in Equation $\\ref{eq:set_sum}$. \\\\ \\\\\nThe minimum cut problem from Equation $\\ref{eq:simple_mincut}$ can be efficiently solved according to the method described in $\\cite{Stoer:1997:SMA:263867.263872}$. The idea is to reduce the graph by merging the vertices of an edge determined similar as in iteration of Prim's minimum spanning tree algorithm, until the graph only contains two combined vertex sets. After each shrinking, the weight of the merged cut would be stored in a list. Finally, the minimum weight cut in the list will be the minimum of the graph. \\\\ \\\\\nIn practice, the resulting graph partitions are not satisfactory. In many situations, the solution of such a mincut simply separates one individual vertex from the rest of the graph. However, we expect clusters to from reasonable large groups and hence, partitions into individual vertices are not what we want. The remedy of this issue is to introduce an additional constraint, that models the notion of cluster size. We explicitly request that the resulting partitions should be large enough. \nThe two common objective functions to encode the notion of size is the ratio cut \\textit{Rcut} $\\cite{Hagen:2006:NSM:2298571.2301769}$ and the normalized cut \\textit{Ncut} $\\cite{Shi:2000:NCI:351581.351611}$. They are defined as\n\\begin{equation}\n\\begin{aligned}\n&\\text{Rcut} = \\frac{1}{2} \\sum_{i=1}^k \\frac{W(A_i, \\bar{A_i})}{\\left| A_i\\right|} = \\sum_{i=1}^k \\frac{\\text{cut}(A_i, \\bar{A_i})}{\\left| A_i\\right|} \\\\\n&\\text{Ncut} = \\frac{1}{2} \\sum_{i=1}^k \\frac{W(A_i, \\bar{A_i})}{\\text{vol}(A_i)} = \\sum_{i=1}^k \\frac{\\text{cut}(A_i, \\bar{A_i})}{\\text{vol}(A_i)}\n\\end{aligned}\n\\end{equation}\nBoth objective functions try to achieve that the clusters are balanced in terms of either the number of vertices (Rcut) or edges (Ncut). The downside of this is that introducing balancing conditions make the previous simple mincut become NP hard, as discussed in $\\cite{Jeg09}$. Spectral clustering is a way to solve a relaxed version of those balanced mincut problems. In particular, in the paper $\\cite{vonLuxburg2007}$ the authors demonstrated that relaxing Ncut leads to the spectral clustering algorithm we mention in Section $\\ref{sec:spectral_clustering_bg}$. \\\\ \\\\\nIn literature, many sophisticated methods exist to optimize relaxed versions of this NP hard problem. Examples are the graph partition heuristic in $\\cite{Ker70}$, or by solving the multi-label CRF problem via max-flow as presented in $\\cite{Fulkerson2009}$.\n\n", "meta": {"hexsha": "5c571985eeaf61d0bf3a166fc3452119d59ab3db", "size": 46303, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Document/Source/Chapters/chapter2.tex", "max_stars_repo_name": "simplay/master_thesis", "max_stars_repo_head_hexsha": "d296c2befba97942765d87d40722105a26e4e97b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-04-18T05:17:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-11T04:28:28.000Z", "max_issues_repo_path": "Document/Source/Chapters/chapter2.tex", "max_issues_repo_name": "simplay/master_thesis", "max_issues_repo_head_hexsha": "d296c2befba97942765d87d40722105a26e4e97b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-05T00:08:25.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-05T00:08:25.000Z", "max_forks_repo_path": "Document/Source/Chapters/chapter2.tex", "max_forks_repo_name": "simplay/master_thesis", "max_forks_repo_head_hexsha": "d296c2befba97942765d87d40722105a26e4e97b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 113.487745098, "max_line_length": 939, "alphanum_fraction": 0.7751981513, "num_tokens": 11387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3401211092778933}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\marginpar{Monday\\\\ 2020-3-30, \\\\ compiled \\\\ \\today}\n\n% Last time we discussed: how can we distinguish what is a GW and what is not? \n\n% We do this by separating them by frequency. \n% We cannot really measure the nature of tensor perturbation of GWs, since we are only measuring integrated effects. \n\n% We can precisely map the effect of the GW in time, by sampling with a frequency which is much higher than the one of the GW.\n\nSo, let us do this formally: we consider \\(g = \\overline{g} + h\\) where \\(\\overline{g}\\) only contains low frequency components while \\(h\\) contains high frequency ones, we expand the Ricci tensor in powers of \\(h_{\\mu \\nu }\\) up to second order and rewrite the Einstein equations as \n%\n\\begin{align}\n\\frac{8 \\pi G}{c^{4}} \\qty(T_{\\mu \\nu } - \\frac{1}{2} g_{\\mu \\nu }T)\n= \\overline{R}_{\\mu \\nu } \n+ R^{(1)}_{\\mu \\nu } \n+ R^{(2)}_{\\mu \\nu } \n\\,,\n\\end{align}\n%\nwhere the second order in \\(h_{\\mu \\nu }\\) term, \\(R^{(2)}_{\\mu \\nu }\\), has both high and low frequency components, while the term \\(\\overline{R}_{\\mu \\nu }\\) is exclusively low frequency and \\(R_{\\mu \\nu }^{(1)}\\) is exclusively high frequency.\n\nLet us give a heuristic argument for this statement: the gravitational waves contained in \\(h_{\\mu \\nu } \\) will have several high frequencies; let us call two of them \\(\\omega_1  \\) and \\(\\omega_2 \\), so as we compute a term which is quadratic in \\(h\\) we will get\n%\n\\begin{align}\n\\qty(\\sin(\\omega_{1} t) + \\sin(\\omega_2 t))^2 \n= \\\\ =\n\\frac{1}{2} \\left(-\\cos \\left(2 t \\omega _1\\right)-\\cos \\left(2 t \\omega _2\\right)-2 \\cos \\left(t \\omega _1+t \\omega _2\\right)+2 \\cos \\left(t \\omega _1-t \\omega _2\\right)+2\\right)\n\\,,\n\\end{align}\n%\nwhere we used the prostapheresis formulas: we get terms oscillating with \\(\\omega_1 + \\omega_2 \\) as well as \\(\\omega_1 - \\omega_2 \\), one of which is high frequency while the other is low frequency, since we are considering a high-frequency wavepacket.\n\nSo, what we want to do is to separate the field equation into its low and high frequency parts: \n%\n\\begin{align} \\label{eq:low-frequency-ricci-tensor-contribution}\n\\overline{R}_{\\mu \\nu } &= - \\qty(R_{\\mu \\nu }^{(2)})^{\\text{low}} + \\frac{8 \\pi G}{c^{4}} \\qty(T_{\\mu \\nu } - \\frac{1}{2} g_{\\mu \\nu } T)^{\\text{low}} \\\\\nR_{\\mu \\nu }^{(1)} &= - \\qty(R_{\\mu \\nu }^{(2)})^{\\text{high}} + \\frac{8 \\pi G}{c^{4}} \\qty(T_{\\mu \\nu } - \\frac{1}{2} g_{\\mu \\nu } T)^{\\text{high}} \n\\,.\n\\end{align}\n\nHow might we define these formally?\nRecall, we expand in two parameters: \\(h\\) and \\(\\lambda / L_B \\sim  f_B / f\\). Then, in terms of orders of magnitude we have\\footnote{The fact that the derivatives correspond to divisions by lengths is justified since we are looking at harmonic expansions, the metric will be a sum of sinusoids around a characteristic frequency.} \n%\n\\begin{align}\n\\overline{R}_{\\mu \\nu } \\sim \\partial^2 \\overline{g}_{\\mu \\nu } \\sim \\frac{1}{L_B^2} \n\\,,\n\\end{align}\n%\nwhile \n%\n\\begin{align}\n\\qty[R^{(2)}_{\\mu \\nu }]^{\\text{low}} \\sim \\qty(\\partial h)^2\n \\sim \\qty(\\frac{h}{\\lambda })^2\n\\,.\n\\end{align}\n\nSee Maggiore \\cite[pag.\\ 31]{maggioreGravitationalWavesVolume2007} for more details. \nSo, inserting these order-of-magnitude estimates inside equation \\eqref{eq:low-frequency-ricci-tensor-contribution} we get\n%\n\\begin{align}\n\\frac{1}{L_B^2} \\sim \\frac{h^2}{\\lambda^2} + \\qty(T_{\\mu \\nu } \\text{ contribution})\n\\,.\n\\end{align}\n\nIf we are in a vacuum (\\(T_{\\mu \\nu }=0\\)) then\n%\n\\begin{align}\n\\frac{1}{L_B^2} \\sim \\qty(\\frac{h}{\\lambda })^2\n\\implies h \\sim \\frac{\\lambda }{L_B}\n\\,,\n\\end{align}\n%\nwhile if the stress-energy tensor is nonvanishing we get\n%\n\\begin{align}\n\\frac{1}{L_B^2} \\sim \\qty(\\frac{h}{\\lambda })^2 + (T_{\\mu \\nu } \\text{ contribution}) \\gg \\qty(\\frac{h}{\\lambda })^2\n\\,,\n\\end{align}\n%\nwhich means \\(h \\ll \\lambda / L_B\\). This shows that \\textbf{the linearized expansion cannot be extended beyond linear order} starting from a flat background: if we start from a flat metric then \\(1/L_B = 0\\), so any \\(h > 0\\) violates the condition \\(h \\lesssim \\lambda / L_B\\).\nWe can also see that the notion of a gravitational wave only makes sense as long as \\(h\\) is small: if \\(h\\) were close to 1, then we would have \\(\\lambda \\sim L_B\\), but our only way to distinguish GW from background is through their wavelength! \n\n\\todo[inline]{Unclear what the problem is: we cannot use the flat metric, but the real world's metric is not flat anyways! Why can we not go to second order with a curved background?}\n\nThe solution to this problem is to take averages on a scale \\(\\ell\\) such that \\(\\lambda_{GW} \\ll \\ell \\ll L_B\\), so that the gravitational wave is fully averaged out, while the background metric is approximately constant across the integration volume.\nThis low-frequency projection reads:\n%\n\\begin{align}\n\\overline{R}_{\\mu \\nu } =\n- \\expval{R^{(2)}_{\\mu \\nu }} + \\frac{8 \\pi G}{c^{4}} \\expval{T_{\\mu \\nu } - \\frac{1}{2} g_{\\mu \\nu } T} \n\\,.\n\\end{align}\n\nAfter some math (see Maggiore \\cite[eqs.\\ 1.122-1.123]{maggioreGravitationalWavesVolume2007}) we can define a stress tensor of the GW, which looks like \n%\n\\begin{align}\nt_{\\mu \\nu } = - \\frac{c^{4}}{8 \\pi G} \\expval{R^{(2)}_{\\mu \\nu } - \\frac{1}{2} \\overline{g}_{\\mu \\nu } R^{(2)}}\n\\,,\n\\end{align}\n%\nwhere the Ricci scalar is computed using the smoothed metric: \\(R^{(2)} = \\overline{g}^{\\mu \\nu } R_{\\mu \\nu }^{(2)}\\). \nAlso, we define a  ``smoothed out'' stress-energy tensor of matter: \n%\n\\begin{align}\n\\expval{T_{\\mu \\nu } - \\frac{1}{2} g_{\\mu \\nu } T}\n\\overset{\\text{def}}{=}\n\\overline{T}_{\\mu \\nu } - \\frac{1}{2} \\overline{g}_{\\mu \\nu } \\overline{T}\n\\,,\n\\end{align}\n%\nso the equation which will hold is the equivalence of the smoothed Einstein tensor with the sum of the smoothed and GW stress-energy tensors:\n%\n\\boxalign{\n\\begin{align}\n\\overline{R}_{\\mu \\nu } - \\frac{1}{2} \\overline{g}_{\\mu \\nu } \\overline{R} = \n\\frac{8 \\pi G}{c^{4}} \\qty(\\overline{T}_{\\mu \\nu } + t_{\\mu \\nu })\n\\,.\n\\end{align}}\n\nDo note that if we work with these, the stress-energy tensor which is conserved is \\(\\overline{T}_{\\mu \\nu } + t_{\\mu \\nu }\\): if we take the divergence of the equation we get, by the Bianchi identities,\n%\n\\begin{align}\n\\nabla^{\\mu } \\qty(\\overline{R}_{\\mu \\nu } - \\frac{1}{2} \\overline{g}_{\\mu \\nu }\\overline{R}) = 0 = \\nabla^{\\mu } \\qty(\\overline{T}_{\\mu \\nu } + t_{\\mu \\nu })\n\\,.\n\\end{align}\n\nThis means that gravitational waves and matter can exchange energy and momentum. If the stress-energy tensor is slowly-varying enough, as often happens practically, we can just use \\(\\overline{T}^{\\mu \\nu } \\approx T^{\\mu \\nu }\\).\n\nHow does this look like far from the source?\nThere, we can approximate \\(\\overline{g} \\approx \\eta_{\\mu \\nu }\\) and \\(\\nabla_{\\mu } \\approx \\partial_{\\mu }\\). \nThis \\(t_{\\mu \\nu }\\) only has 2 physical degrees of freedom (those of the gravitational wave): we need to gauge the others away.\n\nThe Lorentz gauge plus \\(h=0\\) eliminates \\(5\\) degrees of freedom. \n\nWhen we have terms like \\(h \\partial \\partial h\\), we can integrate by parts on a sufficiently large volume to turn them into \\(\\partial(h \\partial ) - \\partial h \\partial h\\). \nUsing the facts \\(\\partial^{\\mu }h_{\\mu \\nu } = h = \\square h_{\\mu \\nu } = 0\\) we can also simplify several terms: in the end we get \n%\n\\boxalign{\n\\begin{align}\nt_{\\mu \\nu } = \\frac{c^{4}}{32 \\pi G} \\expval{\\partial_{\\mu } h_{\\alpha \\beta } \\partial_{\\nu } h^{\\alpha \\beta }}\n\\,.\n\\end{align}}\n\nThis is invariant under the residual gauge transformations, and coordinate independent: we can compute it in any frame we like.\n\n\\subsubsection{Explicit TT-gauge expression}\n\nLet us compute this in the simplest case: a gravitational wave travelling along the \\(z\\) axis, described in the TT-gauge.\nThe 00 component will read: \n%\n\\begin{align}\nt^{00 } = \\frac{c^{4}}{32 \\pi G} \\expval{\\partial^{0} h_{\\alpha \\beta } \\partial^{0} h^{\\alpha \\beta }} = \\frac{c^2}{16 \\pi G} \\expval{\\dot{h}^2_{+} + \\dot{h}^2_{ \\times }}\n\\,,\n\\end{align}\n%\nsince: \n%\n\\begin{align}\n\\partial^{0} h_{\\alpha \\beta } \\partial^{0} h^{\\alpha \\beta } =\n\\frac{\\dot{h}^{TT}_{ij}}{c} \\frac{\\dot{h}^{TT}_{ij}}{c} \n= \\frac{1}{c^2}\\sum _{i, j =1}^{2} \\qty(\\dot{h}_{ij}^{TT})^2 \n= \\frac{2}{c^2} \\qty(\\dot{h}_{+}^2 + \\dot{h}_{ \\times }^2)\n\\,.\n\\end{align}\n\nAs for the other components, we will have \\(t^{01} = t^{02} =0 \\) by symmetry (they would represent momentum transfer in a direction orthogonal to the propagation, also formally \\(\\partial_{1,2} h_{ij}^{TT} = 0\\) since it only depends on \\(t\\) and \\(z\\)), and also \\(t^{03}= t^{00}\\), since the perturbation is a function of \\((t - z/c)\\): so, we have \n%\n\\begin{align}\n\\partial_{3} h_{ij}^{TT} = - \\partial_{0} h_{ij}^{TT} = + \\partial^{0} h_{ij}^{TT}\n\\,.\n\\end{align}\n\n\\subsection{Energy and momentum flux far from the source}\n\nIf we are far enough away from the source, we can compute the energy crossing a surface \\(\\dd{A}\\) in a time \\(\\dd{t}\\) as the spacetime density contained in a volume \\(\\dd{A} c \\dd{t}\\): if we are considering a specific direction (say, the flux coming the way of the Earth) then we can say that the wave's propagation is aligned with the \\(z\\) axis and so we can write \n%\n\\begin{align}\n\\dd{E} &= \\dd{A} c \\dd{t} \\frac{c^2}{32 \\pi G} \\expval{\\dot{h}^{TT}_{ij}\\dot{h}^{TT}_{ij}} \\\\\n\\frac{ \\dd{E}}{ \\dd{t} \\dd{A}} &= \\frac{c^3}{16 \\pi G} \\expval{\\dot{h}^2_{+} + \\dot{h}^2_{ \\times }}\n\\,.\n\\end{align}\n\nIn order to get the total power \\(\\dv*{E}{t}\\) which is emitted by the source we can integrate this expression in \\(R^2 \\dd{\\Omega }\\); however we will need to use the general expression \\(\\expval{\\dot{h}^{TT}_{ij}\\dot{h}^{TT}_{ij}}\\) since we cannot have alignment with the \\(z\\) axis across the whole sphere. \n\nTo get the momentum density the reasoning is similar: we start from \\(\\dd{P^{k}} = \\dd{A} c \\dd{t} t^{0k}/c\\) to get \n%\n\\begin{align}\n\\frac{ \\dd{P^{k}}}{ \\dd{A} \\dd{t}} = \\frac{c^{4}}{32 \\pi G} \\expval{ \\partial^{0} h_{\\alpha \\beta } \\partial^{ k} h^{\\alpha \\beta }} \n= - \\frac{c^3}{32 \\pi G} \\expval{\\dot{h}^{TT}_{ij} \\partial^{k} h_{ij}^{TT}}\n\\,,\n\\end{align}\n%\nwhere we used the fact that \\(\\partial^{0} = -\\partial_0  =-  \\pdv*{}{(ct)}\\). \n\nSo, the general expressions for the energy and momentum density emitted at a distance will be \n%\n\\begin{align}\n\\dv{E}{t} = \\frac{c^3}{32 \\pi G} r^2 \\int \n\\expval{\\dot{h}^{TT}_{ij}\\dot{h}^{TT}_{ij}} \\dd{\\Omega }\n\\qquad \\text{and} \\qquad\n\\dv{P^{k}}{t} = - \\frac{c^3}{32 \\pi G} r^2 \n\\int \\expval{\\dot{h}^{TT}_{ij} \\partial^{k} h_{ij}^{TT}} \\dd{\\Omega }\n\\,.\n\\end{align}\n\nWe want to express this explicitly in terms of the quadrupole moment. We start from the expression of the TT-gauge amplitude in terms of the quadrupole \\eqref{eq:traceless-transverse-amplitude-from-quadrupole}: its derivative reads \n%\n\\begin{align}\n\\dot{h}_{ij}^{TT} (t, \\vec{x}) = \\frac{1}{r} \\frac{2G}{c^{4}} \\Lambda_{ij, kl} \\dot{\\ddot{Q}}^{kl} (t - r/c)\n\\,.\n\\end{align}\n\nInserting this into the expression we get \n%\n\\begin{subequations}\n\\begin{align}\n\\dv{E}{t} &= \\frac{r^2c^{3}}{32 \\pi G} \\int \\dd{\\Omega }\n\\expval{\n\\frac{1}{r} \\frac{2G}{c^{4}} \\Lambda_{ij,kl} \\dot{\\ddot{Q}}^{kl}\n\\frac{1}{r} \\frac{2G}{c^{4}} \\Lambda_{ij,mn} \\dot{\\ddot{Q}}^{mn}\n}  \\\\\n&=\\frac{G}{8 \\pi c^{5}} \\int \\dd{\\Omega }\n\\Lambda_{ij, kl} \\expval{\\dot{\\ddot{Q}}^{ij} \\dot{\\ddot{Q}}^{kl}}\n\\marginnote{\\(\\Lambda \\) is idempotent and symmetric under swaps of index pairs: so \\(\\Lambda_{ij, kl} \\Lambda_{ij, mn} = \\Lambda_{kl, mn}\\).}\n\\,,\n\\end{align}\n\\end{subequations}\n%\nwhere the only expression depending on the angle is \\(\\Lambda_{ij, kl} \\), since the quadrupole only depends on the source, not on an observer's position. \n\n\\begin{claim}\nThe explicit expression for the projection tensor \\(\\Lambda_{ij,kl}(\\hat{n})\\) in terms of the unit vector \\(\\hat{n}\\) is: \n%\n\\begin{align}\n\\Lambda_{ij, kl} (\\hat{n}) = \\delta_{ik} \\delta_{jl} - \\frac{1}{2} \\delta_{ij} \\delta_{kl} - n_j n_l \\delta_{ik} - n_i n_k \\delta_{jl}\n+ \\frac{1}{2} n_k n_l \\delta_{ij} \n+ \\frac{1}{2} n_i n_j \\delta_{kl}\n+ \\frac{1}{2} n_i n_j n_k n_l\n\\,,\n\\end{align}\n%\nand its integral in \\(\\dd{\\Omega }\\) is given by \n%\n\\begin{align}\n\\int \\dd{\\Omega } \\Lambda_{ij, kl} = \\frac{4 \\pi }{30} \n\\qty(11 \\delta_{ik} \\delta_{jl} - 4 \\delta_{ij} \\delta_{kl} + \\delta_{il} \\delta_{jk} )\n\\,.\n\\end{align}\n\\end{claim}\n\nWith this result, we can write \n%\n\\begin{align}\n\\dv{E}{t} &= \\frac{G}{8 \\pi c^{5}} \\frac{2\\pi}{15} \\qty(11 \\delta_{ik} \\delta_{jl} - 4 \\delta_{ij} \\delta_{kl} + \\delta_{il} \\delta_{jk} )\n\\expval{\\dot{\\ddot{Q}}^{ij} \\dot{\\ddot{Q}}^{kl}}\n\\,,\n\\end{align}\n%\nbut since the quadrupole moment derivatives \\(\\dot{\\ddot{Q}}^{ij}\\) are both traceless and symmetric the first and third delta combinations are equal (so the factor multiplying them will be 12), while the second combination will vanish. So, we will get \n%\n\\boxalign{\n\\begin{align}\n\\label{eq:radiated-power-GW}\n\\dv{E}{t} = \\frac{G}{8 \\pi c^{5}} \\frac{2 \\pi }{15} 12 \n\\expval{\\dot{\\ddot{Q}}^{ij} \\dot{\\ddot{Q}}^{ij}}\n= \\frac{G }{5 c^{5}}\n\\expval{\\dot{\\ddot{Q}}^{ij} \\dot{\\ddot{Q}}^{ij}}\n= \\frac{G}{5 c^{5}} \n\\expval{\\dot{\\ddot{M}}_{ij} \\dot{\\ddot{M}}_{ij} - \\frac{1}{3} \\dot{\\ddot{M}}_{kk}^{2} }\n\\,.\n\\end{align}}\n%\n\n\nWhen we do the same from the \\textbf{momentum loss}, we get an integral in the form \n%\n\\begin{align}\n\\dv{P^{k}}{t} \\propto \\int \\dd{\\Omega } \\dot{\\ddot{Q}}^{TT}_{ij} \\partial^{k} \\ddot{Q}^{TT}_{ij}\n\\,,\n\\end{align}\n%\nwhich is odd under spatial inversion because of the spatial derivative, so there is no contribution!\n\nThis is not true if we go beyond the quadrupole approximation: full GR calculations/simulations show that there can be kicks at the merger. \n\nIn linearized gravity, we can calculate the power loss by energy conservation: \n%\n\\begin{align}\n\\dv{E _{\\text{source}}}{t} = - \\dv{E _{\\text{far-field}}}{t} = - \\frac{G}{5c^{5}} \\expval{\\dot{\\ddot{Q}}^{ij} \\dot{\\ddot{Q}}^{ij}}\n\\,,\n\\end{align}\n%\nalthough this is not exact moment-by-moment in full GR, since there some of the emission can be delayed. \nIn our approximation, the two sides of the equation should be calculated at the same retarded time: the power loss by the source at \\(t - r/c\\) will be the power detected a distance \\(r\\) away at a time \\(t\\). \n\n\\subsection{Angular momentum loss from GW}\n\n\\subsubsection{Effective back-action force}\n\n% We can calculate the angular distribution in a relatively simple way, since it is easy to go to TT gauge at a point. \n\nWe can model the back-action from GW as a force applied on the source \\cite[sec.\\ 3.3.4]{maggioreGravitationalWavesVolume2007}, whose power is the average of \\(\\vec{F} \\cdot \\vec{v}\\) as in classical mechanics; since we consider a continuous medium we have:\n%\n\\begin{align}\n- \\frac{G}{5 c^{5}} \\expval{\\dv[3]{Q_{ij}}{t} \\dv[3]{Q_{ij}}{t}}\n= \\dv{E _{\\text{source}}}{t} = \n\\expval{\\int  \\dd[3]{x} \\dv{F_i}{V} \\dot{x}_{i}} \n\\,.\n\\end{align}\n\nWe can integrate by parts twice to write the two third derivatives as \n%\n\\begin{align}\n\\expval{\\dv[3]{Q_{ij}}{t} \\dv[3]{Q_{ij}}{t}}\n= \\expval{\\dv{Q_{ij}}{t} \\dv[5]{Q_{ij}}{t}}\n\\,.\n\\end{align}\n\nAlso, the 0th component of the conservation of the stress-energy tensor \\(\\partial_{\\mu } T^{0 \\mu }\\) for a classical source reads \\(\\partial_{t} \\rho + \\partial_{i} \\qty(\\rho v_i) = 0 \\). Using this fact, we can rewrite the first derivative of \\(Q_{ij}\\) as \n%\n\\begin{align}\n\\dv{Q_{ij}}{t} &= \\dv{}{t} \\int  \\dd[3]{x} \n\\rho \\bigg( x_{i} x_{j} - \\underbrace{\\frac{1}{3} r^2 \\delta_{ij}}_{\\mathclap{\\text{contracted with traceless \\(\\dot{\\ddot{\\ddot{Q}}}_{ij}\\)}}}\\bigg) \n= - \\int \\dd[3]{x} \\partial_{k} \\qty(\\rho v_k) \n x_{i} x_{j}  \\\\\n&= + \\int \\dd[3]{x} \\rho v_k \\partial_{k} \\qty(x_i x_j) = \n2 \\int \\dd[3]{x} \\rho v_{(i } x_{j)}\n\\,.\n\\end{align}\n%\n\\todo[inline]{Missing symmetrization in the slides! Although it is implicit when contracting with \\(Q\\)\\dots}\n\nThen our equation reads: \n%\n\\begin{align}\n\\expval{\\int \\dd[3]{x} \\dv{F_i}{V} \\dot{x}_{i}} = - \\frac{2G}{5c^{5}}\\expval{\\int \\dd[3]{x} \\dv[5]{Q_{ij}}{t} \\rho \\dot{x}_{i} x_{j}}\n\\,,\n\\end{align}\n%\nso we can identify the terms to get\n%\n\\begin{align}\n\\dv{F_{i}}{V} = - \\frac{2G}{5c^{5}} \\dv[5]{Q_{ij}}{t} \\rho (t, \\vec{x}) x_{j}\n\\,,\n\\end{align}\n%\nso finally, since the only position-dependent terms on the right-hand side are the density and the position we get that the effective force is: \n%\n\\boxalign{\n\\begin{align}\nF_{i} = - \\frac{2G}{5c^{5}} \\dv[5]{Q_{ij}}{t} m \\overline{x}_{j}\n\\,,\n\\end{align}}\n%\nwhere \\(\\overline{x}_{j} \\) is the center-of-mass coordinate. \n\n\\subsubsection{Angular momentum}\n\nWith this effective force we can calculate the torque explicitly: in general it is given by \\(T_i = \\epsilon_{ijk} x_j F_k\\), which we can make into a local relation by substituting \\(T_i\\) and \\(F_k\\) with their densities. With this we can write \n%\n\\begin{align}\n\\dv{T_i}{V} = \\epsilon_{ijk} x_j  \\dv{F_k}{V} = -\n\\epsilon_{ijk} x_j  \\frac{2G}{5 c^{5}} \\dv[5]{Q_{kl}}{t} \\rho (t, \\vec{x}) x_l\n\\,,\n\\end{align}\n%\nso the total torque is given by\n%\n\\begin{align}\nT_{i} &= - \\frac{2G}{5 c^{5}} \\epsilon_{ijk} \\dv[5]{Q_{kl}}{t}\n\\int \\dd[3]{x} \\rho (t, \\vec{x}) x_l x_j \\underbrace{- \\frac{1}{3} r^2 \\delta_{lj}}_{\\mathclap{\\text{does not contribute, since \\(Q\\) is traceless}}} \\\\\n&= - \\frac{2G}{5 c^{5}} \\epsilon_{ijk} \\dv[5]{Q_{kl}}{t} Q_{lj} \n\\,,\n\\end{align}\n%\nso if we take the average, substituting the derivative of the angular momentum for the torque and integrating by parts twice to get a second and a third derivative, we find:\n%\n\\begin{align}\n\\expval{\\dv{L_{i}}{t}} = -\\frac{2G}{5c^{5}} \\epsilon_{ijk} \n\\expval{\\ddot{Q}_{jl} \\dot{\\ddot{Q}}_{kl}}\n\\,.\n\\end{align}\n\n\\section{Back-reaction and the evolution of binary systems}\n\n\\subsection{Compact circular inspiral}\n\nWe use the reduced mass formalism for a two-body problem: we define the total mass \\(M = m_1 +m_2 \\), the reduced mass \\(\\mu = m_1 m_2 / M\\), the relative coordinate \\(\\vec{x} = \\vec{x}_1 - \\vec{x}_2\\) whose modulus is \\(R = \\abs{\\vec{x}}\\). \nThe angular velocity of the circular motion is \\(\\omega_{s}\\), satisfying Kepler's law \\(\\omega_{s}^2 R^3 = GM\\).\n\nAs we saw, the amplitude of the emitted gravitational waves is given by \n%\n\\begin{align}\nA = \\frac{4 G^{5/3} \\omega_{s}^{2/3} \\mu M^{2/3}}{r c^{4}}\n\\,,\n\\end{align}\n%\nand the amplitudes of the two polarizations in time are given in terms of \\(A\\) by\n%\n\\begin{subequations}\n\\begin{align}\nh_{+} &= A \\frac{1 - \\cos^2\\theta   }{2} \\cos(2 \\omega_{s} t _{\\text{ret}} + 2 \\varphi ) \\\\ \nh_{\\times } &= A \\cos \\theta  \\sin(2 \\omega_{s} t _{\\text{ret}} + 2 \\varphi )  \n\\,.\n\\end{align}\n\\end{subequations}\n\nIn order to make these expressions easier to interpret, we define the chirp mass: \n%\n\\begin{align}\nM_c = \\mu ^{3/5} M^{2/5} = \\frac{\\qty(m_1 m_2 )^{3/5}}{(m_1 + m_2 )^{1/5}}\n\\,.\n\\end{align}\n\nAlso, since the frequency of the emitted GW is double that of the binary we define \\(f_{GW} = 2 f_s = 2 \\omega_{s} / (2 \\pi )\\), and \\(\\omega_{GW} = 2 \\pi f_{GW}\\).\nThe reduced wavelength corresponding to this frequency is \\(\\lambdabar = c / \\omega_{GW}\\); also we can define a Schwarzschild radius corresponding to the chirp mass: \\(R_C = 2GM_c / c^2\\). \n\nWith these definitions we can rewrite \\(A\\) as: \n%\n\\begin{align}\nA = \\frac{4}{r} \\qty( \\frac{G M_C}{c^2})^{5/3} \\qty( \\frac{\\pi f_{GW}}{c})^{2/3}\n= \\frac{1}{\\sqrt[3]{2}} \\frac{R_C}{r} \\qty( \\frac{R_C}{\\lambdabar})^{2/3}\n\\,,\n\\end{align}\n\nAs we have shown, in the quadrupole approximation the radiated power is: \n%\n\\begin{align}\n\\dv{E}{t} = \\frac{G}{5 c^{5}} \\expval{\\dot{\\ddot{M}}_{ij} \\dot{\\ddot{M}}_{ij} - \\frac{1}{3} \\qty(\\dot{\\ddot{M}}_{kk})^2}\n\\,,\n\\end{align}\n%\nwhich we can calculate explicitly for our binary.\nWe have already derived expressions for the second time derivatives of the second mass moment, \\(\\ddot{M}_{ij}\\) for motion in the \\(xy\\) plane \\eqref{eq:second-mass-moment-xy-components}; taking their derivative we get \n%\n\\begin{align}\n\\dot{\\ddot{M}}_{11} = - \\dot{\\ddot{M}}_{22} = \n- 4 \\mu R^2 \\omega_{s}^3 \\sin(2 \\omega_{s}t )\n\\qquad \\text{and} \\qquad\n\\dot{\\ddot{M}}_{12} = 4 \\mu R^2 \\omega_{s}^3 \\cos(\\omega_{s}t)\n\\,,\n\\end{align}\n%\nso the term \\(\\qty(\\dot{\\ddot{M}}_{ij})^2\\) vanishes (\\(\\dot{\\ddot{M}}_{ij}\\) is traceless) and \\(\\dot{\\ddot{M}}_{11}^2 = \\dot{\\ddot{M}}_{22}^2\\), so the contribution we get is \n%\n\\begin{align}\n\\dv{E}{t} &= \\frac{G}{5 c^{5}} \\expval{2 \\dot{\\ddot{M}}_{11}^2 + 2 \\dot{\\ddot{M}}_{12}^2 }  \\\\\n&= \\frac{G}{5 c^{5}} 2 \\qty(4 \\mu R^2 \\omega_{s}^3)^2 \\underbrace{\\qty(\\expval{\\sin^2(2 \\omega_{s}t)} + \\expval{\\cos^2(2\\omega_{s}t)})}_{= 1/2 + 1/2 = 1}\n\\,,\n\\end{align}\n%\nsince the average of the squared sine or cosine is \\(1/2\\). \nNow, we can simplify this expression by using \\(R^3 = GM / \\omega_{s}^2\\) and substituting in the GW angular velocity:\n%\n\\begin{align}\n\\dv{E_{GW}}{t} &= \\frac{32G}{5c^{5}} \\mu^2 R^{4} \\omega_{s}^{6}  \\\\\n&= \\frac{32G}{5c^{5}} \\mu^2 \\qty( \\frac{GM}{\\omega_{s}})^{4/3} \\omega_{s}^{6}  \\\\\n&= \\frac{32}{5c^{5}} \\mu^2 G^{7/3} M^{4/3} \\omega_{s}^{10/3} \\\\\n&= \\frac{32}{5} \\frac{c^{5}}{G} \\qty( \\frac{G M_c \\omega_{GW}}{2 c^{3}})^{10/3} \\label{eq:gravitational-wave-total-power-emitted}\n\\,.\n\\end{align}\n\nWe can apply a similar reasoning for the angular momentum loss (here \\(L = \\abs{\\vec{L}}\\)): \n%\n\\begin{align}\n\\dv{L}{t} = \n\\frac{32}{5} \\frac{c^{5}}{G} \\qty( \\frac{G M_c \\omega_{GW}}{2 c^{3}})^{10/3} \\frac{2}{\\omega_{GW}}\n= \\frac{32}{5} \\frac{c^{5}}{G} \\qty(\\frac{G M_c}{c^{3}})^{10/3} \\qty(\\frac{\\omega_{GW}}{2})^{7/3}\n\\,.\n\\end{align}\n\nIf we have masses in circular orbit, then by the virial theorem their total energy is given by half of the potential energy: \n%\n\\begin{align}\nE = - \\frac{1}{2} \\frac{G m_1 m_2  }{R}\n\\,,\n\\end{align}\n%\nwhich we can differentiate with respect to time to get \\(\\dot{E} = G m_1 m_2 / (2 R^2) \\dot{R}\\); this can be also written as\n%\n\\begin{align} \\label{eq:radius-evolution-binary}\n\\dot{R} = - \\frac{2R^2}{G m_1 m_2 } \\dot{E}_{GW}\n\\,,\n\\end{align}\n%\nas long as the orbital energy is only lost through gravitational wave emission. \n\nThis means that, as the GW carry away energy, the radius shrinks; this corresponds to an increase in frequency, and a corresponding increase in gravitational wave emission. \n\nIn all our calculations we assumed the orbits to be circular!\nThis is fine, as long as they are almost-circular: the condition to require is that the variation of the radius across a single orbit is very small: \n%\n\\begin{align}\n\\abs{\\frac{\\dot{R} T}{R}} \\ll 1\n\\,,\n\\end{align}\n%\nwhere \\(T\\) is the period.\nIn order to express this conditions in terms of the orbital angular velocity \\(\\omega_{s}\\) we use Kepler's law: if we differentiate \\(R = \\qty(GM / \\omega_{s}^2)^{1/3}\\) we get \n%\n\\begin{align} \\label{eq:derivative-radius-evolution-binary}\n\\dot{R} = - \\frac{2}{3} \\omega_{s}^{-5/3} \\qty(GM)^{1/3} \\dot{\\omega}_{s}\n= - \\frac{2}{3} \\frac{R}{\\omega_{s}} \\dot{\\omega}_{s}\n\\,.\n\\end{align}\n\nThis equality can also be written in terms of logarithmic derivatives as \n%\n\\begin{align} \\label{eq:log-derivatives-radius-angular-velocity-binary}\n\\frac{\\dot{R}}{R} + \\frac{2}{3} \\frac{\\dot{\\omega}_{s}}{\\omega_{s}} = 0\n\\,.\n\\end{align}\n\nStarting from this, and using \\(T = 2 \\pi / \\omega_{s}\\) we can write \n%\n\\begin{align}\n\\abs{\\frac{\\dot{R}T}{R}} = \\frac{2}{3} \\frac{R}{\\omega_{s}} \\dot{\\omega}_{s} \\frac{2\\pi}{\\omega_{s}} \\frac{1}{R} = \\frac{4 \\pi }{3} \\frac{\\dot{\\omega}_{s}}{\\omega_{s}^2} \n\\,,\n\\end{align}\n% \nwhich means that we need to require \\(\\dot{\\omega}_{s} \\ll \\omega_{s}^2\\).\n\nIn practice, this condition is quite well satisfied for most of the inspiral, right up until the merger phase. \nMotion satisfying this condition is called \\textbf{quasi-circular}. \n\n\\end{document}\n", "meta": {"hexsha": "fee20943dee5d17f6cd69a4169755bdc7de3f1d4", "size": 23489, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ap_second_semester/gravitational_physics/mar30.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "ap_second_semester/gravitational_physics/mar30.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ap_second_semester/gravitational_physics/mar30.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 44.3188679245, "max_line_length": 370, "alphanum_fraction": 0.6471965601, "num_tokens": 8524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.34012110927789324}}
{"text": "\\chapter{Exploring The Hopfield Model}\n% This is where we describe our experiments. We insert plots, images, ....\n\nWe started out the analysis by experimenting with converge of patterns. We shall present two experiments, that provide some interesting insight for the reader into the Hopfield Model.\n\n\\section{Facial Recognition for Police criminal records}\n\nThis experiment describes how the Hopfield network might be used by a Police Office, in order to identify criminals. Since the police has a big database that contains facial images of criminals, the network can perform identify, given an image, which criminal is depicted.\n\nBefore being sent to the Hopfield model, the image suffers a few normalising transformations:\n\\begin{enumerate}\n \\item the background is completely removed\n \\item the image is scaled to 25x25 pixels.\n \\item conversion first to grayscale, and then to only black or white pixels takes place\n\\end{enumerate}\n\nIn figure \\ref{fig:criminal}, we present the convergence series for the input image of a criminal. The network used for this experiment had 400 neurons, running on images of 20x20 pixels. It clearly illustrates the how efficient the networks can be in these scenarios. However, the network might also convert to to spurious patterns, which might create problems in certain situations. See section \\ref{spurious_patterns} for a more detailed description.\n\n\\begin{figure}[h]\n  \\centering\n\\includegraphics[scale=2]{images/convergence/all.png}\n\\caption{Convergence sequence for a criminal in the police database}\n\\label{fig:criminal}\n\\end{figure}\n\nFurthermore, we have developed a GUI, powered by the underlying recognition core, to provide a friendly user experience, in addition to providing interactive facilities (figure \\ref{fig:gui}). An overview of our the recognition system can be found in figure ~\\ref{fig:system}.\n\n\\begin{figure}[h]\n  \\centering\n\\includegraphics[scale=0.3]{screenshots-small/gui1.jpg}\n\\caption{GUI for a criminal record recognition system.}\n\\label{fig:gui}\n\\end{figure}\n\n\\begin{figure}[h]\n  \\centering\n\\includegraphics[scale=0.3]{recognition.jpg}\n\\caption{Outline of the Recognition System demonstrating how the various system components interact}\n\\label{fig:system}\n\\end{figure}\n\n\n\\section{Further analysis}\n\nOur initial aim was to explore various properties of the attractors in a Hopfield Network. We are interested in studying, testing or challenging several ideas about the neural network:\n\\begin{itemize}\n \\item Clusters of attractors: We are interested to see how the Hopfield network behaves when learning similarly correlated patterns. This implies training the network with a cluster of attractors, which will lower the capacity of the network. We believe that basin sizes will get smaller as the patterns get closer to each other.\n \\item Super-Attractors: Find out what happens if the network is trained several times with the same pattern. We believe this super-attractor will have a larger basin size compared to the other attractors.\n \\item Convergence: We plan to train the network with different types of attractors and find out to which ones patterns tend to converge.\n\\end{itemize}\n\n\\section{Basins of Attraction}\n%I think we should move the measurements for the basins of attraction in here.\nA basin of attraction for a particular attractor \\(\\alpha\\) is defined as the set of all states that will eventually converge to \\(\\alpha\\), under repeated update. Here, we are particularly interested in finding a way to measure the size of such a basin of attraction. A large basin size would provide stability for the attractor, since the states in the neighbourhood would converge to it. A small basin size for an attractor would mean that the network might never recall the pattern corresponding to that attractor.\n\n\\subsection{Measuring the Basin Size using the Storkey-Valabregue technique}\n\\label{storkey_basin_size}\n\n A large part of our experiments were thus dedicated to measuring basin sizes of different attractors, clusters of attractors and a newly introduced concept of \\emph{Super-Attractors}, in section ~\\ref{super_attractors}.\n\n A recognised scientific method for calculating the basin size is the Storkey-Valabregue measurement. This can be computed as follows:\n\n \\begin{enumerate}\n  \\item Initially n = 1\n  \\item Choose an initial fixed point corresponding to a stored pattern \\(\\mu\\)\n  \\item \\label{itm:choose radius} Choose some initial normalised Hamming radius \\(r=r_{0}\\)\n  \\item Let the set A be all the states Hamming-distant \\( nr \\) from the fixed point\n  \\item Sample 100 states from A\n  \\item Calculate how many of these states are attracted to the fixed point. Denote this number \\( t_{\\mu}(r) \\)\n  \\item If \\( t_{\\mu}(r) \\) is smaller than 90, stop and return \\(nr\\)\n  \\item Increment \\(n\\) by a suitable amount and repeat from (\\ref{itm:choose radius})\n  \\item Repeat for each attractor.\n \\end{enumerate}\n\n% TODO: This algorithm is implemented in the Haskell function ...\n\n\n\\section{Generating Clusters of Attractors}\n\nThere are various ways of generating clusters of attractors (i.e. attractors that have a low Hamming distance between each other). We shall present two different methodologies that can be used to generate them.\n\nOne way is to start with a root pattern and then reverse each bit with a probability p. The new patterns can be interpreted as noisy versions of the root pattern. We shall denote this procedure T1.\n\n\\subsection{Generating Gaussian-Distributed Clusters}\n\nAnother objective of this work was to analyse patterns that are extracted according to a Gaussian distribution with a specific mean and variance.\n\nSince the state space is \\( 2^N \\) for a network of N neurons, the Gaussian Distribution will have to be defined over a huge set of states. This is highly non-trivial, since we are dealing with binary patterns, that cannot be ordered in an easy way.\n\nIn this case, we will use Mancinelli's method for sampling Gaussian distributed patterns \\cite[p.~33]{federico}. We tackle this issue using the simplest possible approach: to draw numbers from a Normal Distribution and then translate them into patterns that will preserve the distance between them. Formally, if \\(x\\) and \\(y\\) were drawn and \\( |x-y|=\\delta\\), then the Hamming distance between the encoded patterns \\(x'\\) and \\(y'\\) would also be \\( d(x',y')=\\delta\\).\n\n\\subsubsection{Encoding of the patterns}\n\nIn order to encode a number into a binary pattern, we first round the number to the nearest integer. Let k be the integer obtained as such. Now, from left to right, we set to 1 all the bits in locations 1..k of our pattern. The remaining bits are set to -1.\n\nFor example, if the pattern size is 7 and the integer obtained is 4, we get the following pattern: [1,1,1,1,-1,-1,-1].\n\n\\subsubsection{Limitations of the encoding}\n\nAlthough the method has a big advantage for simplicity, we can only obtain N different patterns out of all \\( 2^N\\) patterns available in the state space. However, we can regain capacity if we start flipping bits, while at the same time keeping constant the hamming distance to some certain mean pattern \\(\\mu\\).\n\nAnother idea would be to extend our distribution to a multi-variate distribution. In this case, the capacity of the network would increase from \\(N\\) to \\(\\frac{n}{k}^k\\), where k is the number of dimensions.\n\nUnfortunately, we did not have enough time to implement these ideas, so we only experimented with the naive encoding of patterns described above.\n\n\n\\section{First experiments with basin sizes}\n\\label{sec:fexp}\n\nIn this section we shall introduce the experiments that we used to analyse various properties of the Hopfield Network. We remind the reader about the two methods that we are going to use for generating clusters of attractors:\n\\begin{itemize}\n \\item T1: We start with a root pattern \\(\\mu\\), and generate patterns by flipping each bit from \\(\\mu\\) with probability \\(p\\).\n \\item T2: This method is generating Gaussian-distributed patterns. We sample several numbers from a normal distribution with a certain mean and variance, and then encode each number into patterns of the form [1,1,1,-1,-1].\n\\end{itemize}\n\n\n\\subsection{Basin Size for One Cluster using T1}\n\nOur first experiment is showing us the basin sizes for increasing values of p, the probability of flipping a bit. Method T1 is used, for a Hopfield Network of N neurons.\n\n\\begin{easylist}[enumerate]\n\\ListProperties(Style2*=,Numbers=a,Numbers1=R,FinalMark=.)\n& We generate a random pattern \\(\\mu\\)\n\n& For all values of probability p from 0 to 0.5\n\n    && Starting from \\(\\mu\\) we generate P patterns using T1, and give them to the Hopfield network in order to be learned according to Hebb or Storkey rule.\n\n    && We measure the basin size for all the patterns learned using the Storkey-Valabregue measurement and take their mean.\n\\end{easylist}\n\n\\begin{figure}[h]\n  \\centering\n  \\input{plot-T1-onecluster-100}\n\\caption{Average Basin size of patterns belonging to one cluster generated using T1}\n\\label{fig:plot-T1-onecluster}\n\\end{figure}\n\n\\subsubsection{Comments}\n\nThe results are displayed in figure \\ref{fig:plot-T1-onecluster}. This initial experiment is confirming not only what Mancinelli obtained \\cite{federico}, but also what we already know from theory: A Hopfield network that is trained with similar patterns loses capacity. Although we are not measuring capacity here, the basin size is strongly correlated to that.\n\nInitially, when p is zero, we observe a huge value of 24 for the basin size. This is easily explained, since all the patterns generated are the the same as the root pattern. Subsequently, the network is trained with the same patterns that have the effect of creating a super-attractor with a huge basin size.\n\nWhen p is between 0 and a critical value of 0.35, the basin size is 0, since the patterns are too close to each other and don't have enough space to fit basins of attraction between them. As soon as p goes over 0.35, the basins start to increase until a maximum size of 11.\n\n\\subsubsection{Further explanation of the results}\n\nThe results can also be easily understood and visualised in figure \\ref{fig:basins}. For small p values, the attractors formed in the network are too close to each other to allow room for any basins of attraction (apart from the attractors lying at the edge of the cluster). When the p-value is high, the attractors become more disperse, leaving room for larger basins. It is also worth mentioning that the basin shapes are not necessarily hyper-spherical.\n\n\n\\begin{figure}[h]\n  \\centering\n\\includegraphics[scale=0.25]{images/basins_of_attraction.png}\n\\caption{Illustration of clusters of attractors generated using T1, with different p-values. }\n\\label{fig:basins}\n\\end{figure}\n\n\n\\subsection{Basin Size for Two Clusters using T1}\n\nThis experiment is similar to the previous one, however it contains two clusters this time. The value \\(p_{1}\\) for one cluster will stay the same (fixed at 0.45), while \\( p_{2}\\), corresponding to the second cluster, will vary in the range [0-0.5]. Method T1 is used, for a Hopfield Network of N neurons. The procedure is given below:\n\\newline\n\\begin{easylist}[enumerate]\n\\ListProperties(Style2*=,Numbers=a,Numbers1=R,FinalMark=.)\n& We generate 2 random patterns \\(\\mu_{1}\\) and \\(\\mu_{2}\\), corresponding to clusters \\( C_{1} \\) and \\( C_{2} \\).\n\n& We generate P patterns for \\( C_{1} \\), using T1 with associated probability \\( p_{1}=0.45\\).\n\n& For all values of probability \\( p_{2} \\) from 0 to 0.5\n\n    && Starting from \\(\\mu_{2}\\) we generate P patterns using T1 with associated probability \\( p_{2} \\), and give them to the Hopfield network in order to be learned according to Hebb or Storkey rule.\n\n    && For both sets of patterns, we measure the mean basin size using the Storkey-Valabregue measurement and plot the values on the graph.\n\\end{easylist}\n\nWe will be interested to observe how can the probability p influences the basin sizes. For this reason, we have run two experiments, in which we are outputting the basin sizes for cluster 1, in which p varies. The\n\n\\subsubsection{Comments}\n\n\\begin{figure}[h]\n  \\centering\n  \\input{plot-T1-twocluster-100}\n\\caption{Average Basin size of patterns belonging to Cluster 2, generated using T1}\n\\label{fig:plot-T1-twocluster}\n\\end{figure}\n\nThis latter experiment seems to suggest that the probability $p$ of flipping bits in the pattern doesn't actually influence the basin sizes of attractors in Cluster 1. The same behaviour has been observed in the previous graph, and this is the case especially when the root images, that are randomly generated, are far away from each other.\n\n\n\n\n\\subsubsection{Link to attachment theory}\nA network having been trained with two clusters of patterns can be interpreted, in attachment theory, with an infant that has been exposed to two different caregivers. The patterns can be for example, visual or auditory memories describing the 2 caregivers.\n\n\n\n\\section{Experiments with Gaussian-distributed patterns}\n\nIn this section we are testing clusters of patterns that have been generated using a normal distribution. We are expecting to get similar results to the T1 method, since by the Central Limit Theorem, the Binomial distribution ~ B(N, p) is nicely approximated by a Gaussian distribution with mean N(Np, Np(1-p)). Since in the previous experiments, we used to increase the probability p of flipping a bit, this now translates to increasing the standard deviation of the normal distribution.\n\n\n\\subsubsection{Comments}\n\n\\begin{figure}[h]\n  \\centering\n  \\input{plot-T2-onecluster-100}\n\\caption{Average basin sizes of one cluster generated using T2}\n\\label{fig:plot-T2-onecluster}\n\\end{figure}\n\nThe results here are quite surprising. The experiment with Gaussian-distributed patterns shows us that the basin sizes decrease exponentially as standard deviation increases. This might be the case because at low standard deviation, the patterns would repeat themselves and create small super-attractors that have big basin sizes.\nThis is in contradiction with what we obtained previously, when using method T1, and further details and possible explanations are given in section \\ref{inconsistencies}.\n\n\\subsection{Basin Size for Two Clusters using T2}\n\n\\subsubsection{Comments}\n\n\\begin{figure}[h]\n  \\centering\n  \\input{plot-T2-twocluster-100}\n\\caption{Average basin size for two clusters generated using T2}\n\\label{fig:plot-T2-twocluster}\n\\end{figure}\n\nThis experiment has been run on a network of 100 nodes, with 2 clusters of patterns:C1, with fixed standard deviation $\\sigma_{1}$, and C2, with varying standard deviation $\\sigma_{2}$. We have run two different trials, with $\\sigma_{1}$ = 5 or 10.\n\nAs it can be easily noticed in the graph, the standard deviation does not have any effect on the basin size of the clusters. This seems to suggest that a more disperse cluster will not be affected by neighbouring attractors.\n\n\n\\section{Super Attractors}\n\\label{super_attractors}\nIn the context of learning models such as the Hopfield model, we define a super attractor as an attractor resulting from training a model with multiple occurrences or instances of some stored pattern. The degree of a super attractor denotes the number of occurrences of its corresponding pattern in the training set.\n\n\nIn the context of modelling Attachment theory, a super attractor may represent repeated interactions with the primary care giver. Clearly, it is of interest to investigate the properties of such an attractor; in particular establishing the existence and, if existent, the type of relationship between the degree of the super attractor and the extent of its dominance, or stability, over the space of patterns.\n\n\n\\subsection{Single super attractor}\n\n% Define variables\n\\newcommand{\\psuper}{$p_{super}$}\n\\newcommand{\\prandom}{$\\overrightarrow{p}_{random}$}\n\n\\begin{enumerate}\n\n\n\\item Fix N, the number of neurons.\n\n\\item \\label{itm:choose pattern} Choose a random pattern \\psuper, which signifies the primary care giver.\n\n\\item Choose a number of random patterns \\prandom, such that the Hamming distance between \\psuper and each of \\prandom is between 25\\% and 75\\%.\n\nThe range forms a ball centred at 50\\% Hamming distance\\footnote{The percentage Hamming distance is simply the Hamming distance divided by the number of bits N} with an arbitrary radius, chosen such that the probability of a \\prandom falling into \\psuper's basin of attraction is small. This is done to avoid forming clusters of attractors, which we deal with separately in Recall that the Hopfield network is sign blind, and as a result the inverse of \\psuper, $p_{super}^{-1}$, forms a symmetric super attractor. It is for this reason that a symmetric range about 50\\% is chosen.\n\n\\item Choose a degree $d$ for \\psuper and train a Hopfield network using $\\overrightarrow{p}^d_{super}$ ($d$ instances of \\psuper) and \\prandom.\n\n\\item Measure the basin of attraction of \\psuper using the Storkey-Valabregue method.\n\n\\item Repeat from (\\ref{itm:choose pattern}) for various values of degree $d$.\n\n\\end{enumerate}\n\n\nIn our experiment 100 neurons are used, and the network is trained with 16 random patterns in addition to the super attractor. It is run with degree values {[}1, 2, 4, 8, 16, 32{]}. The entire procedure is repeated 800 times for various randomly chosen \\psuper and \\prandom. The average results obtained are summarised in ~\\ref{fig:one super plot}.\n\nThis experiment can be replicated by running \\texttt{Experiment.hs}.\n\n\\begin{figure}[h]\n  \\centering\n\\input{plot-one-super}\n\\caption{Average basin of attraction for a super attractor with varying degrees.}\n\\label{fig:one super plot}\n\\end{figure}\n\n\nThe results show that as the super attractor's degree is increased, its basin of attraction also increases. Also note that this increase appears to approach the singularity at 50\\% Hamming distance, which is consistent with our knowledge of \\psuper's symmetrical counterpart. The very fast initial growth also indicates that super attractors in general very stable and demonstrate strong dominance over the space of patterns.\n\n\nLinking back to the Attachment theory model, this may be interpreted as depicting the strong influence of repeated and consistent interaction with the child, represented by a super attractor of increasing degree. In particular, it exhibits its dominance over distantly scattered, unrelated influences, which are represented by the random patterns.\n\n\n\n\\subsection{Two super attractors}\n\n\n% Define variables\n\\newcommand{\\poriginsuper}{$p_{origin}$}\n\\newcommand{\\pnewsuper}{$p_{new}$}\n\\newcommand{\\dorigin}{$d_{origin}$}\n\\newcommand{\\dnew}{$d_{new}$}\n\n\\begin{enumerate}\n\n\\item Fix N, the number of neurons.\n\n\\item Fix a degree \\dorigin, for all chosen \\poriginsuper from (\\ref{itm:choose two super}).\n\n\\item \\label{itm:choose two super} Choose a random pattern \\poriginsuper, which signifies the primary care giver.\n\n\\item Choose a random pattern \\pnewsuper, such that the Hamming distance between \\poriginsuper and each of \\pnewsuper is between 25\\% and 75\\%. This could symbolise the training due to either an alternate and influential care giver, or that resulting from a retraining period.\n\n\n\\item Choose a number of random patterns \\prandom, such that the Hamming distance between \\poriginsuper and each of \\prandom is between 25\\% and 75\\%.\n\nNote that while this allows for the possibility of forming a cluster in the vicinity of \\pnewsuper, in practice the probability of this occurring is negligible.\n\n\n\\item Choose a degree \\dnew for \\pnewsuper and train a Hopfield network using \\prandom, \\dorigin instances of \\poriginsuper, and \\dnew instances of \\pnewsuper\n\n\\item Measure the basins of attraction for each of \\poriginsuper and \\pnewsuper using the Storkey-Valabregue method.\n\n\\item Repeat from (\\ref{itm:choose two super}) for different value of degree \\dnew.\n\n\\end{enumerate}\n\nIn our experiment 100 neurons are used, and the network was trained with 8 random patterns in addition to the original and new super attractors, \\poriginsuper and \\pnewsuper, respectively. \\poriginsuper is given a fixed degree, \\dorigin, of 8. This value was chosen as being the smallest point of stability from the previous experiment ~\\ref{fig:one super plot}, beyond which increasing the degree further does not greatly impact the basin of attraction. It is run with \\dnew degree values {[}1, 2, 4, 8, 16, 32{]}. The entire procedure is repeated 634 times for various randomly chosen \\poriginsuper, \\pnewsuper and \\prandom. The average results obtained are summarised in ~\\ref{fig:two super plot}.\n\nThis experiment can be replicated by running \\texttt{Experiment2SuperAttractors.hs}.\n\n\\begin{figure}[h]\n  \\centering\n\\input{plot-two-super}\n\\caption{Average basin of attraction for the two super attractors, \\poriginsuper having a fixed degree, \\dorigin, of 8, and varying the degree, \\dnew, of \\pnewsuper.}\n\\label{fig:two super plot}\n\\end{figure}\n\n\nThe results clearly reveal that increasing the degree of the new pattern increases its own basin of attraction, and decreases that of the original pattern. This relationship is symmetrical, as can be observed by the shape of the graph, in addition to the intersection point, which occurs (roughly) near the point (8 , 8) where both patterns have the same degree of 8. By random choice of original pattern, and random choice of new pattern (subject to a Hamming distance of 25\\% to 75\\% from the original pattern), we can claim that the basin of attraction depends solely on the relative degrees of the two patterns, and is independent of the actual patterns themselves. This is also consistent with the symmetry observed.\n\nThis also fits in nicely nicely with in the Attachment theory interpretation. The original pattern as before represents the consistent interactions with a primary care giver. The new pattern may represent the consistent, yet significantly different, interactions with an alternate and influential care giver, perhaps the other parent of the child or a relative with whom they have developed a close relationship. Intuitively, the care giver which has more interactions would exert a stronger influence, undermining the dominance of the other care giver, and indeed the impact of any other interactions.\n\nIn relation to retraining, the new pattern may also be taken to represent the influences arising due to the undertaken retraining phase. We find that, similar to the above, increasing the number of interactions due to retraining further ingrains its dominance, and dilutes that of the previous interactions due to the primary care giver or otherwise.\n\n\n% undefined variables\n\\let\\psuper\\undefined\n\\let\\poriginsuper\\undefined\n\\let\\pnewsuper\\undefined\n\\let\\dorigin\\undefined\n\\let\\dnew\\undefined\n\\let\\prandom\\undefined\n\n\n\n\n\n", "meta": {"hexsha": "92a59142f04adcc115ca9ef49eccd9eea031c065", "size": 22814, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/exploring_the_model.tex", "max_stars_repo_name": "imperialhopfield/hopfield", "max_stars_repo_head_hexsha": "d64e21b1c7b915755ae535685ffd7dfd25e3970f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2015-07-30T10:00:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-10T15:49:06.000Z", "max_issues_repo_path": "report/exploring_the_model.tex", "max_issues_repo_name": "imperialhopfield/hopfield", "max_issues_repo_head_hexsha": "d64e21b1c7b915755ae535685ffd7dfd25e3970f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/exploring_the_model.tex", "max_forks_repo_name": "imperialhopfield/hopfield", "max_forks_repo_head_hexsha": "d64e21b1c7b915755ae535685ffd7dfd25e3970f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-12-19T13:06:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-03T13:32:21.000Z", "avg_line_length": 65.5574712644, "max_line_length": 721, "alphanum_fraction": 0.7842552818, "num_tokens": 5290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011397337391, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.34012110086673275}}
{"text": "\\documentclass[10pt,conference,compsocconf]{IEEEtran}\n\n\n\\usepackage{amsmath}    % math\n\\usepackage{graphicx}   % For figure environment\n\\usepackage{todonotes}\n\\usepackage{subcaption}\n\n\\usepackage{hyperref}\n\\begin{document}\n\\title{Mini-project II}\n\n\\author{\n  Ada Pozo P\\'{e}rez, Luc\\'{i}a Montero Sanchis, Milica Novakovic\\\\\n  \\textit{Deep Learning 2018, EPFL Lausanne, Switzerland}\n}\n\n\\maketitle\n\n\\begin{abstract}\n  This report describes the implementation of a simple deep learning framework. Several different optimizers, activation functions, layers and loss functions are implemented, including fully connected, dropout, \\textit{ReLU}, \\textit{Tanh}, sequential and \\textit{MSE} loss among others. This framework is used for testing different architectures on a toy dataset, using different optimizers, in order to determine the effects that different activation functions and optimizers have in the training and accuracy.\n\\end{abstract}\n\n\\section{Introduction}\n\tIn this project we implement a deep learning framework using only \\textit{Pytorch} tensors and \\textit{numpy}.\n\t\n\tThe framework is built with two base classes: \\textit{Module} and \\textit{Optimizer}. The following containers are implemented as subclasses for them:\n\t\n\t\\begin{itemize}\n\t    \\item Layers: \\textit{Linear}, \\textit{Sequential} and \\textit{Dropout}.\n\t    \\item Activation functions: \\textit{ReLU}, \\textit{Leaky ReLU}, \\textit{Sigmoid} and \\textit{Tanh}.\n\t    \\item Loss functions: \\textit{Mean Squared Error (MSE)} and \\textit{Cross-entropy loss}.\n\t    \\item Optimizers: \\textit{Stochastic Gradient Descent} and \\textit{Adam}.\n\t\\end{itemize}\n\t\n    To test our framework we generate a toy dataset and run several experiments on it, comparing the performance of different combinations of modules, activations, optimizers and loss functions.\n    \n    The rest of this report is organized as follows: Section \\ref{sec:implementation} describes how the different containers were implemented while Section \\ref{sec:experiments} shows the results of the experiment to test the framework. Conclusions are drawn in Section \\ref{sec:summary}. \n\t\n\\section{Implementation} % (fold)\n\\label{sec:implementation}\n    We have defined two generic classes, \\textit{Module} and \\textit{Optimizer}, that are used as parent classes for the implementations. The optimizers are based on the structure of \\textit{Optimizer}, whereas the remaining implementations are based on \\textit{Module}.\n    \n    \\textit{Optimizer} has two methods: \n    \\begin{itemize}\n        \\item \\textit{step}: implements the update of the parameters.\n        \\item \\textit{adaptive\\_lr}: returns a generator that decays the learning rate by a factor with every optimization step.\n    \\end{itemize}\n    \n    In \\textit{Module} we can find the methods:\n    \\begin{itemize}\n        \\item \\textit{forward} and  \\textit{backward}: implement the forward and backward passes of backpropagation, respectively.\n        \\item \\textit{update}: updates the values of the parameters and resets the computed gradients to zero.\n        \\item \\textit{params}: returns the values and the last computed gradients of the parameters of the layer.\n    \\end{itemize}\n\n  \\subsection{Layers} % (fold)\n  \\label{sub:modules}\n    % Not sure about having ``modules'' as a title here\n    \\subsubsection{Linear} % (fold)\n    \\label{ssub:linear}\n        The fully connected layer is implemented in the \\textit{Linear} module. It is created specifying the number of input and output units. It is also possible to specify the default learning rate, which will be used to update the parameters. Nevertheless, this learning rate is only used when no learning rate is specified for the \\textit{update} function.\n        \n        Unless a specific standard deviation (std) is specified during initialization, the weights are initialized with the Xavier \\cite{Glorot10understandingthe} initialization adapted for ReLU \\cite{DBLP:journals/corr/HeZR015} -- following a zero-mean Gaussian distribution with standard deviation given by $\\text{std} = \\sqrt{2/n}$,\n        where $n$ is the number of input units.\n        If a value for parameter \\textit{std\\_w} is specified, then the weights are initialized according to the zero-mean Gaussian distribution whose std value is \\textit{std\\_w}. For instance, when using $\\tanh$ or sigmoid activation functions we recommend to specify a value for the parameter equal to $\\text{std} = 1\\sqrt{n}$.\n  \t\n        In addition to this, in the initialization it is also specified whether there is a bias -- in which case the bias values would be initialized following a Gaussian distribution with zero mean and standard deviation given by the parameter \\textit{std\\_b}. If the value of parameter \\textit{std\\_b} is not specified, they are initialized to 0. If there is no bias, in the backpropagation this parameter is ignored.\n  \t\n        During the forward pass, the input to the layer is saved for the subsequent gradient computation. The output of the layer $s^{(l)}$ is computed with the equation \\ref{eq:forward}, where $w^{(l)}$ and $b^{(l)}$ are the values of the weights and the bias respectively and $x^{(l-1)}$ is the input to the layer. The bias term is considered if it was specified to do so, otherwise it is ignored.\n        \\begin{equation}\n      \t    \\label{eq:forward}\n            s^{(l)} = w^{(l)}x^{(l-1)} + b^{(l)} \n        \\end{equation}\n     \n        The backward pass function receives as an argument the gradient of the loss with respect to the output of the layer ($\\partial l/\\partial s^{(l)}$) and returns the gradient of the loss with respect to the input of the layer, which is computed as given by equation \\ref{eq:backward_x}. The gradient of the loss with respect to the weights and with respect to the bias are computed with equations \\ref{eq:backward_w} and \\ref{eq:backward_s}, respectively:\n         \\begin{equation}\n      \t    \\label{eq:backward_x}\n            \\frac{\\partial l}{\\partial x^{(l-1)}} =\\frac{\\partial l}{\\partial s^{(l)}}  w^{(l)}\n         \\end{equation}\n         \\begin{equation}\n      \t    \\label{eq:backward_w}\n            \\frac{\\partial l}{\\partial w^{(l)}} =\\left(\\frac{\\partial l}{\\partial s^{(l)}}\\right)^T x^{(l-1)}\n         \\end{equation}\n         \\begin{equation}\n      \t    \\label{eq:backward_s}\n            \\frac{\\partial l}{\\partial b^{(l)}} =\\frac{\\partial l}{\\partial s^{(l)}}\n         \\end{equation}\n     \n        The update of the parameters is performed when the method \\textit{update} is called. If a learning rate is passed as a parameter it is used for the update, otherwise the one specified upon initialization is used. As will be explained in more detail in the optimizers section \\ref{sub:optimizers}, the update can be done directly on the derivatives of the bias and weights (for instance, when using SGD), or in the case when the parameter \\textit{values} is specified it will use these values instead (if Adam is used, the optimizer computes the parameter \\textit{values} that should be used). The equations used for the updates are therefore given by \\ref{eq:update_w} and \\ref{eq:update_b}, where $\\gamma$ is the learning rate:\n        \\begin{equation} \n            \\label{eq:update_w}\n            w^{(l)}\\leftarrow\n            \\begin{cases}\n              w^{(l)} -  \\gamma \\cdot \\partial l/\\partial w^{(l)}, & \\text{if SGD is used} \\\\\n              w^{(l)} -  \\gamma \\cdot \\text{value}_w, & \\text{if Adam is used}\n            \\end{cases}\n        \\end{equation}\n        \n        \\begin{equation}\n            \\label{eq:update_b}\n            b^{(l)}\\leftarrow\n            \\begin{cases}\n              b^{(l)} -  \\gamma \\cdot \\partial l/\\partial w^{(l)}, & \\text{if SGD is used} \\\\\n              b^{(l)} -  \\gamma \\cdot \\text{value}_b, & \\text{if Adam is used}\n            \\end{cases}\n        \\end{equation}\n        \n        When using \\textit{Adam}, $\\text{value}_w$ and $\\text{value}_b$ are computed as given by equation \\ref{eq:valueadam}.\n        \n        Lastly, the \\textit{Linear} module's method \\textit{params} returns a list of tuples containing a tuple with the weights and the gradient and, if bias is activated, a second tuple with the values of the bias and the gradient.\n    % subsubsection linear (end)\n\n  \t\\subsubsection{Sequential} % (fold)\n  \t\\label{ssub:sequential}\n        This class implements a container for a list of layers. Its parameters are the list of layers and a variable that indicates whether the model is in training or testing mode. In the forward pass, it simply calls the \\textit{forward} method of each layer, propagating the output through the layers. In the backward pass, it propagates the gradient calling the corresponding method of each layer iterating through them in reverse order.\n        \n        Likewise, the \\textit{params} method calls the \\textit{params} method of each layer and combines their outputs, returning a list of tuples containing the values and gradient for each parameter.\n        \n        The \\textit{update} method iterates over all the layers calling each layer's corresponding method. If a learning rate $\\gamma$ is specified, then it is used to update all parameters. It is also possible to specify the \\textit{values} parameter that should be used for the update, instead of using the gradient computed during the forward pass. As previously mentioned, this is useful for implementing the Adam optimizer and will be explained later.\n   \t% subsubsection sequential (end)\n\n  \t\\subsubsection{Dropout} % (fold)\n  \t\\label{ssub:dropout}\n        We implement a dropout layer by defining a class \\textit{Dropout}. This layer is created taking as parameters the probability of dropping a hidden unit ($p_{drop}$) and whether the model is training. If it is not training, the forward and backward passes simply return their respective inputs.\n        \n        The forward pass is implemented in the \\textit{forward} method. It creates a mask of hidden units to drop and saves it for the backward pass. The mask is used to shut down the corresponding units of the input data. Lastly, the result is normalized by $1-p_{drop}$. The \\textit{backward} method carries out the backward pass, using the mask saved in the forward pass to shut down the same units of the gradient of the next layer. The result is again normalized by $1-p_{drop}$.\n  \t% subsubsection dropout (end)\n  % subsection modules (end)\n\n  \\subsection{Activation functions} % (fold)\n  \\label{sub:activation_functions}\n    The following activation functions are implemented in our framework:\n  \t\\subsubsection{ReLU} % (fold)\n  \t\\label{ssub:relu}\n        In the forward pass this activation layer applies the non-linear function $f(x) = max(0,x)$ to the input \\cite{Nair:2010:RLU:3104322.3104425}. The backward pass is computed with the derivative:\n      \t\\begin{equation*} \n            f'(x)=\n            \\begin{cases}\n              1, & \\text{if}\\ x>0 \\\\\n              0, & \\text{otherwise}\n            \\end{cases}\n        \\end{equation*}\n  \t% subsubsection relu (end)\n\n  \t\\subsubsection{Leaky ReLU} % (fold)\n  \t\\label{ssub:leakyrelu}\n        We implement a parametric Leaky ReLU, which takes takes a parameter $\\alpha$ and computes the forward pass as:\n      \t\\begin{equation} \n            f(x)=\n            \\begin{cases}\n              x, & \\text{if}\\ x>0 \\\\\n              \\alpha\\cdot x, & \\text{otherwise}\n            \\end{cases}\n        \\end{equation}\n    \n        In the backward pass, the gradient is given by:\n      \t\\begin{equation} \n            f'(x)=\n            \\begin{cases}\n              1, & \\text{if}\\ x>0 \\\\\n               \\alpha, & \\text{otherwise}\n            \\end{cases}\n        \\end{equation}\n  \t\n  \t% subsubsection leakyrelu (end)\n  \t\\subsubsection{Tanh} % (fold)\n  \t\\label{ssub:tanh}\n        We implement the hyperbolic tangent activation function in the class \\textit{Tanh}. This class computes in the \\textit{forward} method the $\\tanh$ of the input, which is saved for the next step. In the backward pass step, we compute the gradient as $1-\\tanh^2{x}$\n  \t% subsubsection tanh (end)\n  \t\\subsubsection{Sigmoid} % (fold)\n  \t\\label{ssub:sigmoid}\n        We implement the forward pass of this function using the $\\tanh$ function to ensure that there is no overflow, according to the formula $\\sigma(x) = 0.5 + 0.5\\cdot\\tanh{(x/2)}$. We store the obtained value and then compute the derivative as $\\sigma(x) \\cdot (1-\\sigma(x))$. \n  \t% subsubsection sigmoid (end)\n  % subsection activation_functions (end)\n  \\subsection{Loss functions} % (fold)\n  \\label{sub:loss_functions}\n  \n  Two loss functions are implemented in this framework: the Mean Squared Error (MSE) and the Cross Entropy Loss.\n  \t\\subsubsection{Mean Squared Error (MSE)} % (fold)\n  \t\\label{ssub:mean_squared_error}\n        In the forward pass, this module computes the difference between the output of the network $f(x,w)$ and the ground truth $y$ and saves it for the backward pass. The loss returned is computed as:\n      \t\\begin{equation} \n      \tLoss = \\sum_{i=1}^{N}(y_i - f(x_i,w))^2\n      \t\\end{equation} \n      \t\n      \tThe backward pass returns the gradient of the loss, which is computed using the stored difference between the output of the network and the ground truth:\n      \t\\begin{equation} \n      \t    \\nabla_{Loss} = 2 (y - f(x,w))\n      \t\\end{equation} \n  \t% subsubsection mean_squared_error (end)\n  \t\\subsubsection{Cross-entropy loss} % (fold)\n  \t\\label{ssub:cross_entropy_loss}\n  \tThis module computes the loss of the network in the forward pass as: \n  \t\\begin{equation}  \n  \t    Loss = -\\sum_{i=1}^{N} y_i\\log (f(x_i,w)) + (1 - y_i)\\log(1 - f(x_i,w))\n  \t\\end{equation} \n  \t\n  \tIn the backward pass the gradient of the loss is computed with the following equation:\n  \t\\begin{equation}  \n  \t    \\nabla_{Loss} =  y - f(x,w)\n  \t\\end{equation} \n  \t% subsubsection cross_entropy_loss (end)\n  % subsection loss_functions (end)\n  \\subsection{Optimizers} % (fold)\n  \\label{sub:optimizers}\n  As explained in the beginning of Section \\ref{sec:implementation}, the optimizers are defined using a class with a \\textit{step} method that updates the parameters and a method \\textit{adaptive\\_lr} that implements a generator that yields decaying learning rates. The decay is controlled by parameters $\\kappa$ and $\\eta$ according to: \n    \\begin{equation}\n    \\label{eq:lr}\n  \t    \\gamma^{(t)} =  \\eta\\cdot t^ {-\\kappa}\n  \t\\end{equation} \n  \twhere $t$ is incremented every time the generator is called.\n  \t\\subsubsection{Stochastic Gradient Descent (SGD)} % (fold)\n  \t\\label{sub:stochastic_gradient_descent_}\n        The parameter update using Stochastic Gradient Descent calls the \\textit{update} method of the model (explained in Sections \\ref{ssub:linear} and \\ref{ssub:sequential}). This update can be done either with a fixed learning rate if $\\kappa$ and $\\eta$ are not passed as parameters when creating the optimizer, or with the described decaying learning rate if they are passed. In the second case, each time \\textit{step} is called the next learning rate is generated and passed to the \\textit{update} method of the model.\n  \t% subsection stochastic_gradient_descent_ (end)\n  \t\\subsubsection{Adam} % (fold)\n  \t\\label{ssub:adam}\n        This class is implemented as described in \\cite{kingma2014adam}.  Given the parameters of the optimizer settings $\\beta_1$, $\\beta_2$ and $\\epsilon$, at each timestep $t$ we first calculate the gradient with respect to the stochastic objective $g_t$ and then the first and second moment vectors are computed according to equations \\ref{eq:fmv} and \\ref{eq:smv} respectively:\n  \t\t\\begin{equation} \\label{eq:fmv}\n            m_t=\\beta_1\\cdot m_{t-1}+(1-\\beta_1)\\cdot g_t\n        \\end{equation}\n  \t\t\\begin{equation}\n  \t\t    \\label{eq:smv}\n            v_t=\\beta_2\\cdot v_{t-1}+(1-\\beta_2)\\cdot g_t^2\n        \\end{equation}\n\n        With the previously obtained results we compute the \\textit{value} argument that is used to update the parameter, as given by:\n        \\begin{equation}\n  \t\t    \\label{eq:valueadam}\n            \\text{value} = \\frac{m_t}{1 - \\beta_1^{t}}\\cdot \\frac{1}{\\epsilon+\\sqrt{v_t/(1-\\beta_2^t)}}\n        \\end{equation}\n        Then, each parameter $\\theta$ is updated as $\\theta_{t}=\\theta_{t-1}-lr\\cdot\\text{value}$.\\\\\n        It is worth mentioning that this optimizer has a \\textit{restart} method that resets the value of $t$ and the moments to $0$ (which are also the values with which the optimizer is initialized).\n        \n        The default values for the parameters are the ones used in   \\cite{kingma2014adam}, that is, a learning rate of $10^{-3}$, and $\\beta_1 = 0.9$ and $\\beta_2 = 0.999$.\n  \t% subsubsection adam (end)\n  % subsection optimizers (end)\n% section implementation (end)\n\n\\section{Experiments} % (fold)\n\n    \\label{sec:experiments}\n    \\begin{figure}[t]\n        \\centering\n        \\includegraphics[width=0.45\\textwidth]{figures/architecture_p2.png}\n        \\caption{Architecture of neural network}\n        \\label{fig:archi}\n    \\end{figure}\n    \n\n    \\subsection{Datasets} % (fold)\n    \\label{sub:dataset}\n    The train and test datasets are each composed of 1000 randomly generated samples. Each sample consists on two values chosen from a uniform distribution between 0 and 1, corresponding to a point in the 2D space. The samples that fall inside the disk of radius $1/\\sqrt{2\\pi}$ centered in $(0.5, 0.5)$ are labelled as 1's, whereas the rest are labelled as 0's.\n    \n    \\subsection{Architecture} % (fold)\n    \\label{sub:architecture}\n    \n    The architecture of the system in the experiments can be found in Figure \\ref{fig:archi}. It has 2 input and 2 output units and 3 fully connected layers with 25 units each. The fully connected layers are followed by a dropout layer, whose drop probability is set on the experiments. The two first hidden layers use the same activation, while the last one may use a different one. These activation functions vary depending on the experiment.\n\n\n    \\subsection{Results} % (fold)\n    \\label{sub:results}\n        \\begin{figure*}[t]\n            \\centering\n            \\begin{subfigure}{0.45\\linewidth}\n                \\centering\n                \\includegraphics[width=\\linewidth]{figures/res_circle_tr.png}\n                \\caption{Training set - 98.4\\% accuracy.}\n                \\label{fig:rescircletr}\n            \\end{subfigure}%\n            \\begin{subfigure}{0.45\\linewidth}\n            \\centering\n            \\includegraphics[width=\\linewidth]{figures/res_circle_te.png}\n            \\caption{Test set - 97.5\\% accuracy.}\n            \\label{fig:rescirclete}\n            \\end{subfigure}\n            \\caption{Classification results. Misclassified samples are shown in red, whereas correctly classified ones are shown in different gray levels depending on the class.}\n            \\label{fig:rescircle}\n        \\end{figure*}\n\n        \\begin{figure*}[t]\n        \\centering\n        \\begin{subfigure}{0.45\\linewidth}\n            \\centering\n            \\includegraphics[width=\\textwidth]{figures/adamsgdloss.png}\n            \\caption{Loss.}\n            \\label{fig:adamsgdloss}\n             \\end{subfigure}%\n            \\begin{subfigure}{0.45\\linewidth}\n            \\centering\n            \\includegraphics[width=\\textwidth]{figures/adamsgdaccuracy.png}\n            \\caption{Accuracy.}\n            \\label{fig:adamsgdaccuracy}\n             \\end{subfigure}\n             \\caption{Performance per epoch using SGD and Adam.}\n            \\label{fig:perf_optim}\n             \n        \\end{figure*}\n        To test our framework, we evaluate the performance with three different experiments:\n        \n        \\begin{enumerate}\n            \\item General performance: this experiment aims to compare the performance on the train and test sets, checking whether there is any overfitting and if dropout is needed.\n            \\item Comparison of the optimizers: this experiment compares the performance in terms of speed and accuracy when using \\textit{Adam} or \\textit{SGD} as optimizers.\n            \\item Comparison of the activation functions: similarly to the previous experiment, this one compares the performance with different activation functions (\\textit{Tanh}, \\textit{ReLU} and \\textit{Leaky ReLU}) for the first two layers.\n        \\end{enumerate}\n\n        All the experiments use a a batch size of 50 samples and train the model for 50 epochs.\n        \n        \\textbf{General performance.} For the first experiment, the model uses \\textit{ReLU} as the activation function for the first two fully connected layers and  \\textit{Sigmoid}  for the last one. No dropout is used - i.e. it has  0 drop probability. The optimizer used is \\textit{Adam} with a learning rate of $10^{-3}$, and $\\beta_1 = 0.9$ and $\\beta_2 = 0.999$.  The classification results obtained are shown in Figures \\ref{fig:rescircletr} and \\ref{fig:rescirclete}, for training and test respectively, with the misclassified samples in red. \n        \n\n        \n        The accuracy obtained for the test set is 97.5\\%, very similar to the 98.4\\% obtained for the training set. Hence, the model does not overfit, as could be expected since both sets are sampled from the same distribution. Therefore, we do not use dropout in any of the following experiments carried out.  It is also worth noting that all misclassified points are located in the border area.\n        \n        \\textbf{Comparison of the optimizers.} In the second experiment we use the same architecture as in the previous one, but we train the model both with \\textit{Adam} and \\textit{SGD}. Adam uses the same parameters as before, while for \\textit{SGD} we use the adaptive learning rate given by equation \\ref{eq:lr}, with $\\kappa=0.6$ and $\\eta=0.035$. In Figure \\ref{fig:perf_optim} can be found the loss and accuracy for the optimizers per epoch. From these figures one can observe that during the first 20 epochs, the training with SGD is faster, with a steeper slope than the one found using \\textit{Adam}. However, this changes in the following epochs and  by epoch 50 both accuracy and loss are slightly better when using \\textit{Adam}. Similarly to the previous experiment, there is no overfitting.\n        \n        \n\n  \n        \\textbf{Comparison of the activation functions.}\n        Lastly, we compare the results obtained using different activation functions (\\textit{Tanh}, \\textit{ReLU} and \\textit{Leaky ReLU}) for the first two hidden layers using \\textit{Adam} as optimizer. The results obtained can be observed in Figure \\ref{fig:activ1comp}. In this plot we have omitted the test accuracy curves for simplicity since they were very close to their corresponding training accuracies. The accuracies obtained after 50 epochs are quite similar and do not seem to be strongly affected by the activation functions chosen for the first two activation layers. However, it is worth mentioning that \\textit{Tanh} learns the fastest at first, while \\textit{Leaky ReLU} seems to be the slowest.\n        \\begin{figure}[htp!]\n            \\centering\n            \\includegraphics[width=0.45\\textwidth]{figures/activ1comp.png}\n            \\caption{Adam's accuracy with different activation functions.}\n            \\label{fig:activ1comp}\n        \\end{figure}\n\n\\section{Conclusions} % (fold)\n\\label{sec:summary}\n\tIn this project we have implemented and used a simple deep learning framework for classifying the points that fall inside and outside a disk. The performance obtained with the chosen architecture was higher than 95\\% in both train and test sets after 50 epochs. Since both sets were sampled from the same distribution, there was no overfitting in the train data. The misclassified points are located in the border area, which was to be expected because a small variation in these points results in a change of their label -- whereas small changes in points that are not in the border would not modify the labels. It should also be noted that by using a well-chosen learning rate -- in this case a decaying one -- \\textit{SGD} achieved a similar result to the one obtained with \\textit{Adam} width default parameters.\n% section summary (end)\n\n\\bibliographystyle{IEEEtran}\n\\bibliography{literature}\n\n\\end{document}\n", "meta": {"hexsha": "f3786d7fb037affe1286b3f6bbc8a679520e66c1", "size": 24114, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Projects/Project2/report_DL2/DL2.tex", "max_stars_repo_name": "lumosan/deeplearning2018", "max_stars_repo_head_hexsha": "303fb507fc6a756b4bfbb3c9fbd57230c866b39b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Projects/Project2/report_DL2/DL2.tex", "max_issues_repo_name": "lumosan/deeplearning2018", "max_issues_repo_head_hexsha": "303fb507fc6a756b4bfbb3c9fbd57230c866b39b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Projects/Project2/report_DL2/DL2.tex", "max_forks_repo_name": "lumosan/deeplearning2018", "max_forks_repo_head_hexsha": "303fb507fc6a756b4bfbb3c9fbd57230c866b39b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 71.1327433628, "max_line_length": 817, "alphanum_fraction": 0.7012938542, "num_tokens": 6099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3400807436267244}}
{"text": "\\documentclass[jou]{apa6}\n\n\\usepackage[american]{babel}\n\\usepackage{hyperref}\n\\usepackage{amsthm}\n\\usepackage{thmtools}\n\n\\usepackage{csquotes}\n\\usepackage[style=apa,sortcites=true,sorting=nyt,backend=biber]{biblatex}\n\\DeclareLanguageMapping{american}{american-apa}\n\\addbibresource{bibliography.bib}\n\n\\title{2019-12-14 Class Summary: Chinese Remainder Theorem}\n\n\\author{Kalvis Aps\\={\\i}tis, {\\small \\tt kalvis.apsitis}{\\small \\tt @gmail.com}}\n\\affiliation{Riga Business School (RBS), University of Latvia (LU)}\n\n\n\\leftheader{NMS Selection Training in Number Theory: 2019-12-14 Class Summary}\n\n\\declaretheoremstyle[headfont=\\normalfont\\bfseries,notefont=\\mdseries\\bfseries,bodyfont = \\normalfont,headpunct={:}]{normalhead}\n\\declaretheorem[name={Example}, style=normalhead,numberwithin=section]{problem}\n\n\\setcounter{section}{2}\n\n\\abstract{This document lists the key results from the December 14, 2019 class in \nNumber Theory. This training for competition math is aimed at 16\\textendash{}18 year \nolds (typically, Grades 10\\textendash{}12).\n}\n\n\\keywords{Chinese remainder theorem, Bezout's identity, Modular arithmetic.}\n\n\\begin{document}\n\\maketitle\n\n\n\\section{Examples}\n\nThese are {\\bf not} the homework problems; it is just a supplementary study material \nwith examples taken from the lecture; most of them were analyzed during the lecture.\nIn case you have forgotten something, hints for these examples are given at the end of this document.\nFull notes and solutions in Latvian: \\url{http://linen-tracer-682.appspot.com/numtheory-tales/tale-numtheory-jun03-crt/content.html#/section}\n\n\\begin{problem}\nFind integers $x,y$ such that $18x + 42y = 6$. \n(Here we have chosen $6 = \\mathit{gcd}(18,42)$.)\n\\end{problem}\n\n\\begin{problem} \nProve that the sequence $1,11,111,\\ldots$ contains\nan infinite subsequence such that any two members of that subsequence\nare mutually prime.\n\\end{problem}\n\n{\\bf Blankinship Algorithm:} Blankinship Algorithm can be \nused to find solutions for the \nBezout's identity: the integers $x,y$ such that $ax+by=d$.\nIt is explained here: \\url{http://mathworld.wolfram.com/BlankinshipAlgorithm.html}.\nIt applies Gaussian row operations to a $2 \\times 3$ matrix: you \nshould know how to subtract one row from another.\n\n{\\bf Inverse Congruence Class:} For a congruence class $a$ \nthat is mutually prime with modulo $m$, denote by $a^{-1}$ \na congruence class such that $a^{-1}\\cdot a \\equiv 1$ modulo $m$. \n(In other words: Given a number $a < m$, find some number $b$\nsuch that $a \\cdot b$ gives remainder $1$ when divided by $m$.)\n\n\n\\begin{problem} \nFind inverses $1^{-1}$, $3^{-1}$, $5^{-1}$, $7^{-1}$, $9^{-1}$, $11^{-1}$, $13^{-1}$, $15^{-1}$\n(all modulo $16$).\n\\end{problem}\n\n{\\bf Chinese Remainder Theorem:}\nFor multiple mutually prime modulos $m_1,m_2,\\ldots,m_k$ one can find $x$ that is \ncongruent to any numbers $a_1,a_2,\\ldots,a_k$ with respect to those modulos.\n\n\\begin{problem} \nFind a natural number $x$ that is a solution to this system of congruences:\n$$\\left\\{ \\begin{array}{l}\nx \\equiv 1\\;(\\mathit{mod}\\,3)\\\\\nx \\equiv 2\\;(\\mathit{mod}\\,5)\\\\\nx \\equiv 3\\;(\\mathit{mod}\\,7)\n\\end{array} \\right.$$\n\\end{problem}\n\n\n\\begin{problem} \nAssume that you want to find number $x$ that satisfies both congruences:\n$$\\left\\{ \\begin{array}{l}\nx \\equiv 4\\;(\\mathit{mod}\\,5)\\\\\nx \\equiv 6\\;(\\mathit{mod}\\,11)\n\\end{array} \\right.$$\nYou can solve this \"graphically\" - build a $5 \\times 11$ table representing\nall possible pairs of remainders, when you divide numbers by $5$ and by $11$. \nFill in this table by choosing $x=1,2,3,\\ldots$ until you find the necessary \ncombination of remainders $(4;6)$. \n\\end{problem}\n\n\\begin{problem} \nFind the smallest positive integer $n$, such that \nnumbers $\\sqrt[5]{5n}$, $\\sqrt[6]{6n}$, $\\sqrt[7]{7n}$ are all positive integers.\\\\\n(From {\\em Vilniaus universiteto Matematikos ir informatikos fakulteto olimpiadas} - \na Lithuanian olympiad for high school students by Vilnius university; 2016, \nGrade 10, P3.)\n\\end{problem}\n\n\\begin{problem} \nProve that for each positive integer n, there are pairwise relatively prime integers\n$k_0, k_1, \\ldots, k_n$ , all strictly greater than $1$, \nsuch that $k_0 k_1 \\ldots k_n - 1$ is the product of\ntwo consecutive integers.\n\\end{problem}\n\n\\begin{problem} \nProve that for every positive integer $n$, there exist integers $a$ and $b$ such that $4a^2 + 9b^2 - 1$ is divisible by $n$.\\\\\n({\\em Math Prize for Girls Olympiad, 2010, P2}). \n\\end{problem}\n\n\\begin{problem}\nAre there infinitely many Fibonacci numbers that give the following remainders when divided by $1001$:\\\\\n{\\bf (a)} remainder $0$; {\\bf (b)} remainder $900$; {\\bf (c)} remainder $1000$.\n\\end{problem}\n\n\\begin{problem}\nProve or disprove the following hypotheses.\\\\\n{\\bf (a)} For all $k \\geq  2,$ each sequence of $k$ consecutive positive integers contains a number that is not divisible by any prime number less than $k$.\\\\\n{\\bf (a)} For all $k\\geq 2,$ each sequence of $k$ consecutive positive integers contains a number that is relatively prime to all other members of the sequence.\\\\\n({\\em Baltic Way, 2016, P2}). \n\\end{problem}\n\n\\newpage\n\n\\section{Hints for Some Examples}\n\n{\\bf Hint 2.1:} You can find this by trial and error for small numbers. \nOr you can run Euclidean Algorithm to find the GCD (greatest common divisor) \nof numbers $18$ and $42$. It will tell you, how many times you should add \nor subtract $18$ and $42$ to get number $6$. (Blaninship's method is essentially \nthe same thing.)\n\n{\\bf Hint 2.2:} If you build the following sequence of mutual primes:\n$2,3,7,43,\\ldots$ (every next number equals the product of all the previous ones plus $1$), \nthen the corresponding numbers $11$, $111$, $1111111$, and so on will give remainder $1$\nevery time you divide them one by another.\n\n{\\bf Hint 2.3:} In order to find, say, $9^{-1}$ (modulo $16$), you can \ntry out all the odd remainders ($1,3,\\ldots,13,15$). Or you can solve the\nBezout's identity $9x - 16y = 1$. Blankinship's algorithm again.\n\n{\\bf Hint 2.4:} One can build such a number step by step - \nfirst write all the numbers congruent to $1$ (modulo $3$): \n$1,4,7,\\ldots$ until you find one that gives remainder $2$ when \ndivided by $5$, and so on. (Since $3,5,7$ are mutually prime, \nChinese remainder theorem promises that you will succeed.)\n\n{\\bf Hint 2.5:} Solution is shown in the table: \\url{https://bit.ly/2MCzMmf}. \nTry to locate numbers\n$0,1,2,3,\\ldots$ in this table and see the sequence how they fill up the table. \nSimilar ideas are used by problems that ask you to \"Measure exactly $4$ liters\nof water, given two jugs with volumes $5L$ and $11L$ respectively\". \n\n{\\bf Hint 2.6:} Search for $n$ in the form $n = 2^a3^b5^c7^d$. \nThen write the necessary conditions (as modular congruences) for all \nthe unknown powers $a,b,c,d$. \n\n{\\bf Hint 2.7:} Look at the polynomial $F(t) = t^2 + t + 1$ (it is \na product of two consecutive numbers $t$ and $t+1$ plus $1$).\\\\\nNote that all the remainders it gives, when divided by $2$, by $3$, etc. \nare periodic. And if $F(t)$ sometimes is divisible by a prime $p_1$ and\nsometimes by a prime $p_2$, then eventually $F(t)$ (for some special \narguments $t$) will be divisible by them both: $p_1 \\cdot p_2$.\\\\\nNow, all you need to show that there are infinitely many primes that \nsometimes divide the values of $F(t)$. At this point remember\nthe proof that there are infinitely many primes. Assume that this is not true - \ni.e. $F(t)$ is divisible by only finitely many primes. Then plug into \n$F(t)=t^2 + t + 1$ the number \n$t = p_1\\cdot{}p_2\\ldots{}\\cdot{}p_k+1$ their product plus $1$.\n\n{\\bf Hint 2.8:} Use Chinese remainder theorem to avoid looking at {\\em all} possible\n$n$. Just look at the prime powers $p^k$ (and all the remaining $n$ can be \nobtained by combining the solutions for $p^k$ in a certain way).\\\\\nNext, consider two separate cases: $n = 2^k$ (you can now pick $b$\nso that it is inverse of $3$ modulo $2^k$ - so that the term $9b^2 - 1$\nis congruent to $0$). On the other hand, if $n=p^k$ for some other $p \\neq 2$, \nthen pick $a$ equal to inverse of $2$ modulo $p^k$ for similar reasons.\n\n{\\bf Hint 2.9:} The remainders of Fibonacci numbers when divided by any fixed $d$\nare periodic (because the pairs of neighboring remainders eventually \nstart to repeat). What is more interesting: All the remainders of Fibonacci sequence\nare \"clean periodic\" (not just \"eventually periodic\") - every remainder belongs to \nthe period. If $F_0 = 0$ (divisible by any $d$), then it means that infinitely \noften $F_n$ will be divisible by that $d$.\\\\\n{\\bf (a)} is simple - since $F_0$ is divisible by $1001$, then the remainder $0$\nis clearly in the period (modulo $1001$).\\\\\nFor {\\bf (b)} and {\\bf (c)} you need to factorize $1001$ as a product of three prime\nfactors and search for the combinations of remainders (as per Chinese remainder\ntheorem). \n\n{\\bf Hint 2.10:} Statement {\\bf (a)} is clearly false. Just start from $2$ and you\nwill find a sequence, where every member is divisible by some small prime.\\\\\nFor {\\bf (b)} you need to express some segment of $k$ subsequent numbers as an overlap \nof several arithmetic progressions with prime differences $d < k$\n(so that every progression contains at least two members among these $k$ subsequent \nnumbers and all the $k$ numbers are covered at least by one sequence).\\\\\nThis is doable when $k=17$. See \\url{https://bit.ly/2Q2XASA}. Finally - use \nChinese remainder theorem to find an actual value $N$ such that the numbers\nfrom $N$ to $N+16$ (inclusive) give the remainders you need.\n\n\\end{document}\n\n\n", "meta": {"hexsha": "86cbdcc97a3f2073226d87421981d3cb7a054fd1", "size": 9537, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "problems/selection_problems_2019_2020/class-summary-chinese-remainder-theorem.tex", "max_stars_repo_name": "kapsitis/nms-numtheory", "max_stars_repo_head_hexsha": "aff61a99c5b3c2bdc9902eef6581d14f0699f5ea", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/selection_problems_2019_2020/class-summary-chinese-remainder-theorem.tex", "max_issues_repo_name": "kapsitis/nms-numtheory", "max_issues_repo_head_hexsha": "aff61a99c5b3c2bdc9902eef6581d14f0699f5ea", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2020-07-17T17:42:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-13T23:55:14.000Z", "max_forks_repo_path": "src/site/numtheory/static/selection_problems_2019_2020/class-summary-chinese-remainder-theorem.tex", "max_forks_repo_name": "kapsitis/math", "max_forks_repo_head_hexsha": "f21b172d4a58ec8ba25003626de02bfdda946cdc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.7746478873, "max_line_length": 162, "alphanum_fraction": 0.7215057146, "num_tokens": 2897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.34008074362672436}}
{"text": "%!TEX root = ../thesis.tex\n\n\\chapter{Adaptivity}\n\\label{adp_sec:main}\n\\section{Introduction}\n\\input{adaptivity/intro.tex}\n\n\\section{Error indicator}\n\\label{adap_sec:error_indicator}\n\\input{adaptivity/error_indicator.tex}\n\n\\section{Machine learning}\n\\input{adaptivity/machine_learning.tex}\n\n\n\\section{Merging triangle}\n\\label{adap_merge_triangle}\n\\input{adaptivity/merge_tri.tex}\n\n\n\n\\section{Matrix representation of NURBS Curves}\n\\label{adap_sec_mrep2d}\n\\input{adaptivity/mrep.tex}\n\n\n\\section{Numerical examples}\n\\input{adaptivity/ex_short_cantilever.tex}\n\\input{adaptivity/ex_chole_adap.tex}\n\\input{adaptivity/ex_bracket_adap.tex}\n\n\\section{Conclusions}\n\\paragraph{}\nIn this chapter, the machine learning algorithm is adopted to develop an extensible and flexible error indicator.\nAny other error estimators can be added to the existing framework and their effects can be detected based on the performance indicators in machine learning.\nA MLP trained error estimator that concludes expressions related to the eigenvalues of the SBFEM formulation and some key geometric properties of the scaled boundary finite element gives a higher convergence rate compared to the uniform refinement.\nIn order to improve the learning effectiveness of the MLP, regularization methods including bagging and dropout are utilized.\nDue to the lack of the eigenvalue error indicator in the first order triangular element, method that eliminates these situation is developed.\nA matrix representation of the NURBS curves is presented to achieve a higher efficiency and stability in calculating the intersections between edge of the element and the NURBS curve.\nStress analysis is conducted on 2D linear elasticity problems.", "meta": {"hexsha": "e7d7ab96af4c137a40d5e107336efed57a04114b", "size": 1702, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "adaptivity/index.tex", "max_stars_repo_name": "fa93hws/thesis", "max_stars_repo_head_hexsha": "c397ddc18e5ff5d6e9b8d6de2e53be4c9c7b7a2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-10-30T12:14:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-30T12:14:47.000Z", "max_issues_repo_path": "adaptivity/index.tex", "max_issues_repo_name": "fa93hws/thesis", "max_issues_repo_head_hexsha": "c397ddc18e5ff5d6e9b8d6de2e53be4c9c7b7a2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "adaptivity/index.tex", "max_forks_repo_name": "fa93hws/thesis", "max_forks_repo_head_hexsha": "c397ddc18e5ff5d6e9b8d6de2e53be4c9c7b7a2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.55, "max_line_length": 248, "alphanum_fraction": 0.8249118684, "num_tokens": 370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.34008074362672436}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\section{Electron scattering}\n\n\\subsection{Compton scattering onto an electron at rest}\n\n\\marginpar{Sunday\\\\ 2020-8-23, \\\\ compiled \\\\ \\today}\n\nWe need to account for the fact that light has a quantum nature, which is not addressed in the classical treatment of scattering. \nAlso, now we will account for the momentum of the photon. \n\nWe start of with an electron at rest, and a photon with energy \\(h \\nu \\) and momentum \\(h \\nu / c\\) impinging on it. \nAfter the scattering, the photon will have energy \\(h \\nu '\\) and momentum \\(h \\nu ' / c\\), while the electron will have momentum \\(m v \\gamma \\). \nLet us call the angle between the direction of the incoming photon and the direction of the outgoing one \\(\\theta \\). \n\nIn terms of four-vectors, we can express the momenta of the photon before and after as \n%\n\\begin{align}\nk^{\\mu } = \\frac{\\epsilon}{c} \\left[\\begin{array}{c}\n1 \\\\ \n\\vec{\\Omega}\n\\end{array}\\right]\n\\qquad \\text{and} \\qquad\nk^{\\prime \\mu } = \\frac{\\epsilon'}{c} \\left[\\begin{array}{c}\n1 \\\\ \n\\vec{\\Omega}'\n\\end{array}\\right]\n\\,,\n\\end{align}\n%\nwhere \\(\\vec{\\Omega}\\) and \\(\\vec{\\Omega}'\\) are unit vectors defining the propagation directions, such that \\(\\vec{\\Omega} \\cdot \\vec{\\Omega}' = \\cos \\theta \\). \nOn the other hand, the momenta of the electron will be \n%\n\\begin{align}\np^{\\mu }  = \\left[\\begin{array}{c}\nmc \\\\ \n\\vec{0}\n\\end{array}\\right]\n\\qquad \\text{and} \\qquad\np^{\\prime \\mu } = \\gamma \\left[\\begin{array}{c}\nmc \\\\ \nm \\vec{v}\n\\end{array}\\right]\n\\,.\n\\end{align}\n\nSince the particles are unchanged after the scattering, both the incoming and outgoing momenta must satisfy \\(p^{\\mu } p_{\\mu } = - m^2 c^2\\) and \\(k^{\\mu } k_{\\mu } = 0\\) (in any frame: they are Lorentz scalars). \nBecause of momentum conservation, we can also impose the four equations \n%\n\\begin{align}\np^{\\mu } + k^{\\mu } = p^{\\prime \\mu } + k^{\\prime \\mu }\n\\,.\n\\end{align}\n\nSolving the system of equations yields \n%\n\\begin{align}\n\\epsilon' = \\frac{\\epsilon }{1 + \\frac{\\epsilon }{mc^2} \\qty(1 - \\vec{\\Omega} \\cdot \\vec{\\Omega}')}\n\\,,\n\\end{align}\n%\nimplying that we must have \\(\\epsilon' \\leq \\epsilon \\): the photon will lose energy in the scattering. \nThe calculation which yields the differential cross section of the scattering is quite complicated and requires the full machinery of QED; here we just give the result: \n%\n\\begin{align}\n\\frac{ \\dd{\\sigma }  }{ \\dd{\\vec{\\Omega} }'} \n= \\frac{r_0^2}{2 } \\qty(\\frac{\\epsilon '}{\\epsilon })^2\n\\qty[ \\frac{\\epsilon}{\\epsilon '} + \\frac{\\epsilon'}{\\epsilon } - (1 - \\vec{\\Omega} \\cdot \\vec{\\Omega}')^2] \n\\,,\n\\end{align}\n%\nwhere \\(\\epsilon \\) is the energy divided by \\(m c^2\\) and \\(r_0 \\) is the classical electron radius. \n\\todo[inline]{Missing square for the \\(\\sin \\theta \\) term in the KN cross section! see \\cite[eq.\\ 7.4]{rybickiRadiativeProcessesAstrophysics1979}.}\n\nIf we substitute in our formula for the energy, using \\(\\xi = \\cos \\theta = \\vec{\\Omega} \\cdot \\vec{\\Omega}'\\), we find \n%\n\\begin{align}\n\\frac{ \\dd{\\sigma }}{ \\dd{\\Omega }' \\dd{\\epsilon }'} \n= \\frac{r_0^2}{2} \\frac{1 + \\xi^2}{\\qty(1 + \\epsilon (1 - \\xi ))^2}\n\\qty[1 + \\frac{\\epsilon^2 (1 - \\xi )^2}{(1 + \\xi )^2 (1 + \\epsilon (1 - \\xi ))}]\n\\delta \\qty(\\epsilon ' - \\frac{\\epsilon }{1 + \\epsilon (1 - \\xi )})\n\\,.\n\\end{align}\n\nWe have inserted a \\(\\dd{\\epsilon '}\\) differential for the outgoing photon energy, we are considering a density in one more variable but it is singular there, whence the \\(\\delta \\) function, which describes the distribution in \\(\\epsilon '\\) space --- concentrated at the only value allowed by 4-momentum conservation. \nNote that this makes sense dimensionally, as the dimension of a \\(\\delta \\) function is the inverse of the dimension of its argument. \n\nIn the low energy limit, \\(h \\nu \\ll m_e c^2 \\) or \\(\\epsilon \\to 0\\), we find \n%\n\\begin{align}\n\\frac{ \\dd{\\sigma }}{ \\dd{\\Omega }' \\dd{\\epsilon }'} \n=\n\\frac{r_0^2}{2} (1 + \\xi^2) \\delta (\\epsilon ' - \\epsilon )\n\\,,\n\\end{align}\n%\nwhich is the Thomson cross section. \n\nLet us now define the \\textbf{Compton scattering kernel} \\(\\sigma \\): it is the differential cross section times the electron density,\n%\n\\begin{align}\n\\sigma (\\epsilon \\to \\epsilon ', \\xi ) = n_e \\frac{ \\dd{\\sigma }}{ \\dd{\\Omega }' \\dd{\\epsilon }'}\n\\,.\n\\end{align}\n\nWe can integrate this in order to find the total cross section presented by the electrons to photons of an energy \\(\\epsilon \\): \n%\n\\begin{align}\n\\sigma (\\epsilon ) &= \\int \\dd{\\Omega '} \\dd{\\epsilon '} \\sigma (\\epsilon \\to \\epsilon ', \\xi ) \\\\\n&= \\frac{3}{4} n_e \\sigma_{T} \\qty[ \\qty(\\frac{1 + \\epsilon }{\\epsilon^3}) \n\\qty(\\frac{2 \\epsilon (1 + \\epsilon )}{1 + 2 \\epsilon }- \\log \\qty(1 + 2 \\epsilon ))\n+ \n\\frac{1}{2 \\epsilon } \\log \\qty(1 + 2 \\epsilon )\n- \n\\frac{1 + 3 \\epsilon }{(1 + 2 \\epsilon )^2}\n]\n\\,.\n\\end{align}\n\nHow does this differ from the Thomson cross section? For \\(\\log \\epsilon \\lesssim -1 \\) we have \\(\\sigma \\approx \\sigma_T\\), while as \\(\\epsilon \\) increases the cross section goes to zero. \n\n\\begin{figure}[ht]\n\\centering\n\\includegraphics[width=\\textwidth]{figures/compton-sigma.pdf}\n\\caption{Compton cross section as a function of \\(\\epsilon \\), photon energy by \\(m_e c^2\\). }\n\\label{fig:compton-sigma}\n\\end{figure}\n\nIn the low energy limit we have the expansion \n%\n\\begin{align}\n\\sigma (\\epsilon )\\approx \\sigma_T \\qty(1 -2 \\epsilon + \\frac{26}{5} \\epsilon^2)\n\\,.\n\\end{align}\n\nThe introduction of these nonconservative aspects complicates the radiative transfer equation for scattering.\nThe absorption term is \n%\n\\begin{align}\n- \\alpha _\\nu ^{(s)} I _\\nu =  \n- I (\\epsilon , \\Omega ) n_e \\int \\dd{\\Omega }' \\dd{\\epsilon }' \\frac{ \\dd{\\sigma }}{ \\dd{\\Omega }' \\dd{\\epsilon }' } =     - I (\\epsilon , \\Omega  ) \\sigma (\\epsilon )\n\\,,\n\\end{align}\n%\nwhile for the emission term the intensity must go inside the integral, so we have \n%\n\\begin{align}\nj_\\nu^{(s)} = \nn_e \\int \\dd{\\Omega }' \\dd{\\epsilon '} I(\\epsilon ', \\Omega ') \\frac{ \\dd{\\sigma }}{ \\dd{\\Omega }' \\dd{\\epsilon }' } = \\int \\dd{\\Omega }' \\dd{\\epsilon }'\nI(\\epsilon ', \\Omega ')\n \\sigma (\\epsilon \\to \\epsilon ', \\xi )\n\\,,\n\\end{align}\n%\nwhich cannot be expressed in terms of the integrated kernel \\(\\sigma (\\epsilon )\\). \n\nFor Thomson scattering the absorption term is similar, with \\(n_e \\sigma_T\\) instead of \\(\\sigma (\\epsilon )\\). \nThe emission term, on the other hand, can now be evaluated to yield  \n%\n\\begin{align}\n\\int \\dd{\\Omega }' \\dd{\\epsilon }' \\sigma (\\epsilon \\to \\epsilon ', \\xi )\n= \\frac{r_0^2}{2} n_e \\int \\dd{\\Omega '} \\dd{\\epsilon '} I(\\epsilon ', \\Omega ') (1 + \\xi^2) \\delta (\\epsilon ' - \\epsilon ) \\sim n_e \\sigma_T J(\\epsilon )\n\\,,\n\\end{align}\n%\nas long as we neglect the angular dependence of the intensity. \n\nWe are always restricting ourselves to electrons which are initially at rest. For them Thomson scattering is a good approximation; photons more energetic than a few tens of \\SI{}{keV} (hard X-rays) hardly scatter, since the Klein-Nishina cross section drops at high energies.\n\nSo, by using the Thomson limit we do not get it wrong by much. \n\nThe main conclusions we can draw from this is that we expect no spectral modifications (since Thomson scattering is conservative) but we do expect angular redistribution (since Thomson scattering is essentially isotropic).\n\n\\subsection{Scattering in plasmas}\n\nElectrons are not at rest in any realistic astrophysical setting. In order to have free electrons we need a plasma, which is made of (at least partially) ionized gas. \nSo, we need a way to describe the fractional ionization.\nLet us consider only hydrogen for simplicity: we define the collisional ionization fraction \\(x\\) (ionized atoms divided by total atoms), which can be expressed in terms of the temperature as \n%\n\\begin{align}\nx = \\frac{F}{1 + F} \n\\qquad \\text{where} \\qquad\nF = 2T \\exp(-\\frac{\\SI{1.58e5}{K}}{T})\n\\,.\n\\end{align}\n\nThe way \\(x\\) looks as a function of temperature is a kind of sigmoid: it is close to zero, then at \\(T\\) around \\SI{e4}{K} it quickly rises, and becomes close to 1 at a few times \\SI{e4}{K}. At temperatures larger than \\SI{e5}{K} the plasma is basically fully ionized (which makes sense: the first ionization energy of hydrogen is \\(\\SI{13.6}{eV} \\approx \\SI{1.6e5}{K}\\)). \n\nAt these temperatures, the electrons will be moving quite a lot because of thermal motion. \n\n\\subsection{Inverse Compton scattering}\n\nScattering onto moving electrons is often called \\textbf{inverse Compton scattering}, since in this case the photon might gain energy instead of losing it. \nWe start off with a photon with momentum \\(k^{\\mu } = (\\epsilon /c) (1, \\vec{\\Omega})\\) and an electron with momentum \\(p^{\\mu } = \\gamma (mc, m \\vec{v})\\); the outgoing electron and momentum momenta, energies and velocities will be denoted with a prime. \n\nWe know how to deal with scattering off a stationary electron, and stationarity is relative: if we boost to the electron's rest frame we can apply the results from regular Compton scattering, and then we will need to boost back to our frame. \n\nWe shall denote quantities calculated in the ERF (electron rest frame) with a pedix \\(e\\): for example the energy of the photon in the ERF before the scattering will be \\(\\epsilon_e\\).\nThis means that in the ERF we will have the equality \n%\n\\begin{align}\n\\epsilon_e' \n= \\frac{\\epsilon_e}{1 + \\frac{\\epsilon_e}{mc^2} (1 - \\cos \\Theta )} \n\\approx \\epsilon_e \\qty(1 - \\frac{\\epsilon_e}{mc^2} (1 - \\cos \\Theta )) \n\\approx \\epsilon_e \n\\qquad \\text{if } \\epsilon_e \\ll m c^2 \n\\,.\n\\end{align}\n\nWe are saying that in the rest frame the scattering will basically be conservative, this is for sure an approximation but, because of what we discussed earlier about the Klein-Nishina cross section dropping off at high energies, not a large one. \n\nThe Lorentz transform from the LAB frame to the ERF for the energy of the photon is: \n%\n\\begin{align}\n\\epsilon_e = \\gamma \\epsilon \\qty(1 - \\beta \\cos \\theta )\n\\,,\n\\end{align}\n%\nwhile the transform back from  the ERF to the LAB frame is \n%\n\\begin{align}\n\\epsilon' = \\gamma \\epsilon_e' \\qty(1 + \\beta \\cos \\theta _e )\n\\,.\n\\end{align}\n\nNote that the quantities \\(\\beta \\) and \\(\\gamma \\) refer to the velocity of the electron: since we are approximating the scattering as conservative in the ERF calculating them before or after the scattering is the same (the direction of the electron can change: this is accounted for by letting \\(\\theta\\) and \\(\\theta '\\) be different). \nSo, we can just insert these two multiplicative factors one after another to find the total change in energy of the photon: \n%\n\\begin{align}\n\\epsilon ' &\\approx \\gamma^2 \\epsilon \\qty(1 - \\beta \\cos \\theta ) \\qty(1 + \\beta \\cos \\theta'_e ) \n\\,.\n\\end{align}\n\n\\todo[inline]{Inaccuracy in the slides: the first formula does not really make sense, since the approximation of the nonconservativeness factor being equal to one has been made in part of it (\\(\\beta \\) and \\(\\gamma \\) being the same before and after), so it does not make sense to write it out.}\n\nLet us neglect the angular terms for now: generally they are of order unity. Instead, the main factor in the formula is \\(\\gamma^2>1\\): this means that in general the energy of the scattered photon is of the order \\(\\epsilon ' = \\gamma^2 \\epsilon > \\epsilon  \\). \nThe boost of the energy of the photon depends on how relativistic the electron is; if the electron is very relativistic the boost in energy for the photon can be quite large. \n\nIn order to make predictions about the effect of this for a population of electrons and photons, we can Lorentz transform the Compton Scattering Kernel: the final result of the manipulation is\n%\n\\begin{align}\n\\sigma (\\epsilon \\to \\epsilon ', \\xi ) = \\frac{D}{D'} \\sigma_e \\qty(\\epsilon _e \\to \\epsilon _e', \\xi _e)\n\\,,\n\\end{align}\n%\nwhere \\(D = 1 - \\vec{\\Omega} \\cdot \\vec{v} / c = 1 - \\beta \\cos \\theta \\) and \\(D' = 1 - \\vec{\\Omega}' \\cdot \\vec{v}' / c \\approx 1 + \\beta \\cos \\theta '_e\\) are the factors in the Lorentz transforms, which allow us to write \\(\\epsilon _e = \\gamma D \\epsilon \\) and \\(\\epsilon _e' = \\gamma D' \\epsilon '\\).\n\nThe transformation law for \\(\\xi = \\vec{\\Omega} \\cdot \\vec{\\Omega}\\) is \n%\n\\begin{align}\n1 - \\xi = \\frac{1 - \\xi _e}{\\gamma^2 D D'}\n\\,,\n\\end{align}\n%\nwhile the electron energy density transforms as \\(n = \\gamma n_e\\). \n\nThis allows us to write down an explicit expression for \\(\\sigma (\\epsilon \\to \\epsilon ', \\vec{\\Omega}, \\vec{\\Omega}')\\) in the lab frame for a population of single-speed electrons:\n%\n\\begin{align}\n\\sigma (\\epsilon \\to \\epsilon ', \\vec{\\Omega}, \\vec{\\Omega}', v) \n= \n\\frac{n r_0^2}{2 \\epsilon \\nu \\gamma } \n\\qty[1 + \\qty(1 + \\frac{1 - \\xi }{\\gamma^2 D D'})^2\n+ \\frac{\\epsilon \\epsilon ' (1 - \\xi )^2}{\\gamma^2 D D'}]\n\\delta \\qty(\\xi -1 + \\frac{\\gamma D}{\\epsilon'} - \\frac{\\gamma D'}{\\epsilon })\n\\,,\n\\end{align}\n%\nbut we must also consider the fact that the electrons are distributed with different velocities: if their distribution is isotropic, so that \\(\\dd{n} = n f(v) \\dd[3]{v}\\) then we can integrate across all velocity space, getting an expression like \n%\n\\begin{align}\n\\sigma (\\epsilon \\to \\epsilon ', \\xi )\n= \\int \\dd{v} \\sin \\theta_v \\dd{\\theta _v} \\dd{\\phi _v}\n v^2 n f(v) \n\\sigma (\\epsilon \\to \\epsilon ', \\vec{\\Omega}, \\vec{\\Omega}', v)  \n\\,.\n\\end{align}\n\n\n\n\\end{document}\n", "meta": {"hexsha": "911b5909d6741bfa5b2e48739eac4902a33b44f6", "size": 13268, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ap_second_semester/radiative_processes/apr09.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "ap_second_semester/radiative_processes/apr09.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ap_second_semester/radiative_processes/apr09.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 46.8833922261, "max_line_length": 374, "alphanum_fraction": 0.6839011155, "num_tokens": 3970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.3400807352933458}}
{"text": "\\chapter{Related work}\\label{relatedwork}\nState-space dimensionality reduction has been a topic of interest in RL for several years. In their 2015 paper, Curran et al. \\cite{mario} used PCA to reduce the dimensionality of the state-space in a Super Mario environment. They found that with the right number of principal components, an agent using PCA was able to converge to a better policy and needed less episodes than an agent using the full observation. Curran et al. corrobarated these results in more environments in later research in 2016 \\cite{pca_curran}. Similar results were found by Shah et al. in 2011 in the context of neuroscience \\cite{pca_neural}. Bitzer et al. also found similar results in 2010. \\cite{pca_bitzer}. Reducing the dimensionality using PCA led to better policies and quicker convergences; this was interpreted as ``[...] due to the higher dimensionality, learning in the full 4D state space requires far more exploration to cover the same proportion of space\" \\cite{pca_bitzer}.\n\nUnlike the Starcraft II environment used in our research having image/grid based observations, the states and observations used in these papers are comprised of non-spatial related variables, i.e. linear states; to, for instance, denote the presence of one or more enemies within one grid-cell distance of Mario's position, Curran et al. use one variable with $2^8$ possible values ($0$-$255$). Hence we are using PCA in a different setting, with an observation format more commonly used in modern RL. Furthermore they use the Q-learning algorithm (mentioned in section \\ref{pl-dqn}) which is not a state-of-the-art learning algorithm anymore and handles larger state-spaces badly due to using a lookup-table instead of a neural network for the Q-function.\n\nResearch has also been done with regards to using autoencoders for state-space-dimensionality reduction in RL. Lange and Riedmiller in 2010 \\cite{AE_2010} used visual data as observations and found that the agent was able to find an optimal policy using lower dimensional data from the autoencoder. They did not compare the performance of this agent with any other agent. Furthermore, their system only has $31$ possible states, which is very limited; in contrast, our Starcaft II environment has a total of $731.187$ possible states. \n\nIn 2016, Finn et al. successfully showed the possibility of training an RL agent on a latent representation given by an autoencoder on visual information \\cite{ae_visual}. The same year, Van Hoof et al. \\cite{AE_2016} used an autoencoder to project noisy sensor data unto a lower dimensional space. They found that the agent using the autoencoder was far better able to find a good policy than the agent using full observations. This was explained as the agent being too sensitive to noisy data, hence being unable to train even decently. Our research in contrast explores an environment where the baseline agent is able to train to a good policy.\n\nHa and Schmidhuber use a variational autoencoder (VAE) \\cite{vae} in their 2018 paper to train an agent in image based environments \\cite{rl_vae}. Through this method, their agent outperformed baseline agents. They did find that the VAE produced mixed results for the latent representation; in an environment where details are important, they were lost in the latent representation. Differently from our research, they do not compare different reduction methods. Furthermore they do not use deep reinforcement learning, but train the agent using \\textit{evolution strategies} \\cite{es}. Lee et al. also train an agent on a variational autoencoder and found similar results \\cite{rl_vaetwo}.\n\nKhan et al. used an autoencoder to project visual data to a latent space and were able to train a self-driving car in the CARLA environment \\cite{rl_carla}\\cite{carla}. However, no comparison to a baseline agent (or other reduction methods) was given.\n\nIn 2019, Prakash et al. \\cite{AE_2019} also used an autoencoder on visual data to project the observation data onto a lower dimensional space. They found that an agent using the autoencoder far outperformed the baseline agent. The baseline agent did not find a decent policy, though the authors claim that with enough episodes it would have.\n\nAnother paper in 2019 by Gelada et al. \\cite{deepmdp} compared using a DeepMDP with using an autoencoder for state-space dimensionality reduction. They found that in simpler environments a DeepMDP can find better representations on lower dimensionality space than an autoencoder. Simultaneously though, they also find that in more complex environments, like Atari games, DeepMDPs can have trouble finding a good representation and that its loss can be difficult to optimize. They also find that a DeepMDP agent generally outperforms a baseline agent. \n\n%project_matrix_2020\n%dimred_overview_2008\n\n\n", "meta": {"hexsha": "68788be8a51d8732656f6c61d9e536422d60750d", "size": 4841, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Thesis/relatedwork.tex", "max_stars_repo_name": "Niels-vv/Safe-RL-With-DR", "max_stars_repo_head_hexsha": "9f299661bb4cea9f0cd3121ea4b273cfb1016f9f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-23T15:13:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-23T15:13:26.000Z", "max_issues_repo_path": "Thesis/relatedwork.tex", "max_issues_repo_name": "Niels-vv/Safe-RL-With-DR", "max_issues_repo_head_hexsha": "9f299661bb4cea9f0cd3121ea4b273cfb1016f9f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Thesis/relatedwork.tex", "max_forks_repo_name": "Niels-vv/Safe-RL-With-DR", "max_forks_repo_head_hexsha": "9f299661bb4cea9f0cd3121ea4b273cfb1016f9f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 220.0454545455, "max_line_length": 967, "alphanum_fraction": 0.8066515183, "num_tokens": 1070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.3400807352933458}}
{"text": "\\section{Checking Property Preservation}\n\\label{sec:lts-transformation:proppres}\n\nIn this section, we show how property preservation of transformations can be checked by generating networks from rule systems and comparing the LTSs of these networks.\nFigure~\\ref{fig:lts-transformation:check-generation} gives an overview of the approach.\n\n\\begin{figure}[hbt]\n\\centering\n\\includegraphics[scale=0.6]{lts-transformation/figs/check-generation}\n\\caption{Checking property preservation by comparing LTSs}\n\\label{fig:lts-transformation:check-generation}\n\\end{figure}\n\nFirst, networks are generated based on the left and right-hand sides of transformation rules.\nThen, the network LTSs corresponding to these networks are generated, while applying maximal hiding regarding the property at hand.\nFinally, property preservation is checked by comparing the network LTSs generated from left-hand sides of transformation rules with the network LTSs of the corresponding right-hand sides.\nIf all pairs of LTSs are divergence-sensitive branching bisimilar, the rule system preserves the property at hand.\n\nMore formally, a terminating, confluent rule system $\\Sigma$ is $\\Sf$-preserving for a property~$\\Sf \\in \\dsbrLmu$ iff $\\models_{\\smodel} \\Sf \\iff \\models_{T_{\\Sigma} (\\smodel)} \\Sf$ for all networks~$\\smodel$.\nThus, if $\\Sigma$ is $\\Sf$-preserving and $\\models_{\\smodel} \\Sf$, we can conclude that~$\\models_{T_{\\Sigma} (\\smodel)} \\Sf$ without rechecking property~$\\Sf$ for network~$T_{\\Sigma} (\\smodel)$.\nSince $\\dsbrLmu$ is compatible with maximal hiding and DSBB, as discussed in Section~\\ref{subsec:lts-transformation:lmu}, $\\Sigma$ is $\\Sf$-preserving if $\\maxabstr(\\smodel) \\dsbbis \\maxabstr(T_{\\Sigma} (\\smodel))$.\nIn this section, we discuss under which conditions a rule system implies the bisimilarity of $\\maxabstr(\\smodel)$ and $\\maxabstr(T_{\\Sigma} (\\smodel))$.\nThe most important condition roughly boils down to checking whether, after some appropriate rewriting, the left and right patterns of the transformation rules are divergence-sensitive branching bisimilar after maximal hiding.\nIf this is the case, then applying the rules does not result in a network with structurally different behavior.\n\nWithout loss of generality, for each network~$\\smodel = \\networktuple$ and rule system~$\\Sigma = \\rulesystemtuple$, we assume that each $r \\in R$ has exactly one match to some $\\Pi[i]$ and that each $\\Pi[i]$ is matched on by exactly one $r$.\nThis is expressed by indexing the~$r \\in R$ such that rule~$r_i$ is matched on~$\\Pi[i]$.\nIf~$R$ contains only one rule, we omit its index.\nSince~$\\Sigma$ is confluent, the results of this section can be lifted to the more general case where rules may have an arbitrary number of matches.\nWith this assumption, it can also safely be assumed that all the $\\actions{i}$ are disjoint.\nIf this is not the case, some renaming of actions and a corresponding modification of the synchronization rules can resolve this.\n\n\\subsection{Extended Transformation Rules}\nTo show that a rule system~$\\Sigma$ preserves a property~$\\Sf$ for every network~\\smodel, we show that a divergence-sensitive branching bisimulation between the states of~$\\maxabstr(\\smodel)$ and~$\\maxabstr(T_{\\Sigma} (\\smodel))$ can be constructed based on the divergence-sensitive branching bisimulations between networks constructed from the transformation rules.\nTo construct these networks from the transformation rules, we extend the transformation rules with self-loops on the glue-states.\nThe matches of the glue-states of a given transformation rule may be part of transitions that are not present in the patterns of this rule.\nThe transformation rules are extended to make explicit that such transitions may exist.\nEach self-loop is labeled with an action uniquely related to the corresponding state.\n\n\\begin{definition}\n\\label{def:lts-transformation:extendedtransformationrule}\nGiven an LTS transformation rule $r = \\transruletuple{r}$, the corresponding extended transformation rule is defined as~$r_\\kappa = \\langle \\Llts^r_\\kappa, \\Rlts^r_\\kappa \\rangle$, where\n\\begin{itemize}\n\\item\n$\\Llts^r_\\kappa = \\langle \\states{\\Llts^r}, \\actions{\\Llts^r} \\cup \\{ \\kappa_s \\mid s \\in \\states{\\Llts^r} \\cap \\states{\\Rlts^r} \\}, \\transitions{\\Llts^r} \\cup \\{ \\langle s, \\kappa_s, s \\rangle \\mid s \\in \\states{\\Llts^r} \\cap \\states{\\Rlts^r} \\}, \\initialstates{\\Llts^r} \\rangle$;\n\\item\n$\\Rlts^r_\\kappa = \\langle \\states{\\Rlts^r}, \\actions{\\Rlts^r} \\cup \\{ \\kappa_s \\mid s \\in \\states{\\Llts^r} \\cap \\states{\\Rlts^r} \\}, \\transitions{\\Rlts^r} \\cup \\{ \\langle s, \\kappa_s, s \\rangle \\mid s \\in \\states{\\Llts^r} \\cap \\states{\\Rlts^r} \\}, \\initialstates{\\Rlts^r} \\rangle$.\n\\end{itemize}\n\\end{definition}\n\n\\noindent\nWe assume that the $\\kappa$-actions are not originally in $\\actions{\\Llts^r}$.\nWithout these loops, a DSBB check of patterns could consider two deadlock states to be bisimilar, while they are actually different glue-states that are possibly matched on states with different outgoing transitions not present in the patterns.\nFor example, without the dashed $\\kappa$-loops, states~$\\it{ii}$ and~$\\it{iii}$ in Figure~\\ref{fig:lts-transformation:kappa} would be related if~$a,b \\in h_{\\actions{}}(\\Sf)$.\nWith the $\\kappa$-loops, however, they are not related, as indicated by the cross.\nThus, the extra transitions ensure that $\\Llts^r_\\kappa \\dsbbis \\Rlts^r_\\kappa$ iff there exists a divergence-sensitive branching bisimulation that relates all the glue-states to themselves.\nA glue-state $s$ in $\\Llts^r_\\kappa$ (or $\\Rlts^r_\\kappa$) with self-loop $s\\ \\smash{\\xrightarrow{\\kappa_s}}\\ s$ must at least be related to itself in $\\Rlts^r_\\kappa$ (or $\\Llts^r_\\kappa$) since it is the only state where a $\\kappa_s$-transition is enabled.\n\n\\begin{figure}[hbt]\n\\centering\n\\includegraphics[scale=0.2]{lts-transformation/figs/kappa-loops}\n\\caption{An extended transformation rule}\n\\label{fig:lts-transformation:kappa}\n\\end{figure}\n\n\\subsection{Synchronizing Behavior}\nIf a rule system consists of multiple transformation rules, then multiple LTS transformations can be applied in a single transformation step.\nTo check $\\Sf$-preservation of such rule systems, we need to take possible synchronization between different rule patterns into~account.\n\n\\begin{figure}[hbt]\n\\centering\n\\includegraphics[scale=0.2]{lts-transformation/figs/comparison-network}\n\\caption{A network and the corresponding network LTS}\n\\label{fig:lts-transformation:comparison-network}\n\\end{figure}\n\nIn Figure~\\ref{fig:lts-transformation:comparison-network}, a network involving synchronization and the corresponding network LTS are shown.\nThe network LTS is obtained after hiding the actions in~$h$, shown in the middle of the figure, which is the hiding set for some property~$\\Sf$.\nThe rule system shown on the left of Figure~\\ref{fig:lts-transformation:preserving-rules} can be applied to the network of Figure~\\ref{fig:lts-transformation:comparison-network}.\nIndividually, the rules seem to fundamentally change the behavior of the process LTSs, as shown in the middle of Figure~\\ref{fig:lts-transformation:preserving-rules}.\nHowever, since the rule system also adds the new synchronization rules~$\\langle\\langle c1, e1 \\rangle, c1e1\\rangle$ and~$\\langle\\langle c2, \\bullet \\rangle, c2\\rangle$, and the actions~$\\it{c1e1}$ and~$\\it{c2}$ can be hidden,\nthe final network LTS, as shown on the right of the figure, is bisimilar to the one before transformation.\nTo incorporate such possible dependencies between rule patterns, we developed a $\\Sf$-preservation check involving networks of rule patterns.\n\n\\begin{figure}[hbt]\n\\centering\n\\includegraphics[scale=0.2]{lts-transformation/figs/preserving-rules}\n\\caption{A rule system and an example of its application}\n\\label{fig:lts-transformation:preserving-rules}\n\\end{figure}\n\nIn general, when considering transformation rules that affect synchronizing actions and thus involve multiple process LTSs, it cannot be determined whether a given rule system~$\\Sigma = \\rulesystemtuple$ involving such rules is $\\Sf$-preserving by just analyzing the $\\Llts^\\ri$ and $\\Rlts^\\ri$ of all $\\ri \\in R$.\nHowever, this can be done if $\\Sigma$ has a number of properties regarding synchronizing behavior of a network $\\smodel$, which we together call synchronization uniformity.\n\nBefore we can give a definition of synchronization uniformity, we need a number of auxiliary definitions.\nThe set of actions involved in synchronization vector~$\\vectornot{t}$ is ${\\actions{}}(\\vectornot{t}) = \\{ a \\mid \\exists i \\in 1..n. \\vectornot{t}[i] = a \\wedge a \\neq \\bullet \\}$,\nand the set of actions involved in synchronization rules in~\\synchrules with multiple processes is $\\syncactions (\\synchrules) = \\{a \\mid \\exists \\langle \\vectornot{t},a' \\rangle \\in \\synchrules. a \\in {\\actions{}}(\\vectornot{t}) \\wedge |{\\it Ac}(\\vectornot{t})|>1 \\}$.\nThe set of indices of process LTSs that can potentially synchronize with behavior in $\\Llts^\\ri$ according to a synchronization rule in \\synchrules is $\\inv(\\Llts^\\ri, \\synchrules) = \\bigcup \\{ {\\it Ac}(\\vectornot{t}) \\mid \\syncruletuple \\in \\synchrules \\wedge \\vectornot{t}[i] \\in \\actions{\\Llts^\\ri} \\}$.\nThis definition states that $j$ is in $\\inv(\\Llts^\\ri, \\synchrules)$ iff there exists a synchronization rule $\\syncruletuple$ in $\\synchrules$ such that both $i \\neq \\bullet$ and $j \\neq \\bullet$, i.e.\\ both $i$ and $j$ are active for that rule, and the behavior in $\\Pi[i]$ is matched on by transformation rule $\\ri = \\transruletuple{r_i}$.\nThe set of actions of process $j$ on which the actions in~$\\Llts^\\ri$ depend according to the synchronization rules in~\\synchrules is $\\dep^{\\Llts^\\ri}(j, \\synchrules) = \\{ \\vectornot{t}[j] \\mid \\syncruletuple \\in \\synchrules \\wedge \\vectornot{t}[i] \\in \\actions{\\Llts^\\ri} \\wedge \\vectornot{t}[j] \\neq \\bullet \\}$.\nIn other words, the set of all actions $\\bigcup_{t \\in F} \\{\\vectornot{t}[j] \\} \\setminus \\{\\bullet\\}$ constitutes $\\dep^{\\Llts^\\ri}(j, \\synchrules)$, where~$F$ represents the set of all synchronization rules applicable on $\\Llts^\\ri$.\nSets $\\inv(\\Rlts^\\ri, \\synchrules)$ and $\\dep^{\\Rlts^\\ri}(j, \\synchrules)$ are defined similarly.\nNow, synchronization uniformity can be defined.\n\n\\begin{definition}\n\\label{def:lts-transformation:uniformity}\nWe say that rule system~$\\Sigma = \\rulesystemtuple$ is synchronization uniform w.r.t.\\ network~$\\smodel = \\networktuple$ iff the following holds.\n\\begin{enumerate}\n\\item\n$\\forall a \\in \\actions{s} (\\synchrules). (\\exists \\ri \\in R. a \\in \\actions{\\Llts^\\ri}) \\implies \\forall s_1\\xrightarrow{a}_{i} s_2 . s_1, s_2 \\in m_\\ri(\\states{\\Llts^\\ri})$;\n\\item\n$\\forall \\ri \\in R, j \\in \\inv(\\Llts^\\ri, \\synchrules). \\dep^{\\Llts^\\ri}(j, \\synchrules) \\subseteq \\actions{\\Llts^\\rj}$;\n\\item\n$\\forall \\langle\\vectornot{t},a\\rangle \\in \\hat\\synchrules, i \\in 1..n. \\vectornot{t}[i] = \\bullet \\vee \\vectornot{t}[i] \\in \\actions{\\Rlts^\\ri}$.\n\\end{enumerate}\n\\end{definition}\n\nThe first condition states that if a transformation rule is applicable to a synchronizing transition, then it is applicable to all synchronizing transitions with the same label in~\\smodel.\nIf this is not guaranteed, it becomes very hard to reason about the model after transformation because it is difficult to determine a priori exactly which transitions in different process LTSs will be able to synchronize in the network.\nTherefore, predicting the effect of rewriting, for example, $a$-transitions in some places while keeping other $a$-transitions the same is as difficult.\nChecking this condition requires inspecting the process LTSs of a network, unless we impose an additional restriction on rule systems.\nIf we require that all left-hand patterns of rules that modify synchronizing transitions consist of a single transition, the first condition holds, regardless of the structure of the process LTSs of~\\smodel.\nThe second condition states that all actions that can synchronize with $\\Llts^\\ri$ are also transformed by $\\Sigma$.\nIf this does not hold, it becomes hard to analyze the synchronizing behavior as appearing in transformation patterns.\nIn such cases, some of the behavior that is relevant for this analysis is not present in any of the patterns, which makes analysis based only on the rule system impossible.\nFinally, the third condition states that each new synchronization rule~$\\langle\\vectornot{t},a\\rangle \\in \\hat\\synchrules$ involves actions from the $\\Rlts^\\ri$ of the corresponding rule~$\\ri$ only.\nIt is crucial to rule out the possibility of transforming merely by introducing synchronization rules, because this also prevents analysis solely based on rule systems.\nFor example, if we define a new synchronization rule involving existing actions~$a$ and~$b$, and these actions were previously not allowed to synchronize, then we clearly change the model without actually transforming anything.\n\nIn the remainder of this chapter, we only consider rule systems that are synchronization uniform regarding a given model.\nThis may seem a big assumption, but in practice, one tends to transform synchronizing behavior in a uniform way.\nUsually, synchronizing actions, say~$a$ and~$b$, represent communication.\nIf one wants to transform this behavior, it is natural to do this consistently in all places where~$a$ and~$b$ occur, and to transform the behavior of both communicating parties to keep them compatible with each other.\n\n\\subsection{Networks of transformation rules}\n\nFrom a rule system, networks of transformation rules can be constructed.\n\n\\begin{definition}\n\\label{def:lts-transformation:rule-network}\nFor a model~$\\smodel = \\networktuple$, rule system~$\\Sigma = \\rulesystemtuple$, and a rule~$\\ri \\in R$, the vector~$\\xi^\\ri$ of transformation rules relevant for the behavior in $\\Llts^\\ri$ is defined as follows, for all $j \\in 1..n$.\n\n\\[\n\\xi^\\ri[j] =\n\\left\\{\n\\begin{array}{ll}\n\\ast \\mapsto \\ast & {\\rm if} ~ j \\not\\in \\inv(\\Llts^\\ri, \\synchrules) \\\\\nr_{j,\\kappa}\t  & {\\rm if} ~ j \\in \\inv(\\Llts^\\ri, \\synchrules),\n\\end{array}\n\\right.\n\\]\n\\end{definition}\n\n\\noindent\nwhere $\\ast$ is a dummy state.\nFor a given vector $\\xi^\\ri$, $\\xi_{\\Llts}^\\ri$ is the vector of left patterns of the extended transformation rules in~$\\xi^\\ri$, and $\\xi_{\\Rlts}^\\ri$ is the vector of right patterns.\nThe networks~$\\Xi_\\Llts^\\ri = (\\xi_\\Llts^\\ri, \\synchrules)$ and $\\Xi_\\Rlts^\\ri = (\\xi_\\Rlts^\\ri, \\synchrules \\cup \\hat\\synchrules)$ allow comparing synchronizing behavior in rule patterns, before and after transformation according to $\\Sigma$, in particular involving~$\\ri$.\n\n\\begin{figure}[hbt]\n\\centering\n\\includegraphics[scale=0.2]{lts-transformation/figs/non-preserving-rules}\n\\caption{A non-preserving transformation and an example of its application}\n\\label{fig:lts-transformation:non-preserving-trafo}\n\\end{figure}\n\nOn the left of Figure~\\ref{fig:lts-transformation:non-preserving-trafo}, another example of a rule system is shown.\nIn general, this rule system is not $\\Sf$-preserving.\nApplying this rule system to the network in Figure~\\ref{fig:lts-transformation:comparison-network} results in the network shown in the middle of Figure~\\ref{fig:lts-transformation:non-preserving-trafo}.\nThe corresponding network LTS shown on the right of this figure is obtained after hiding the actions in~$h$.\nThe networks of the left and right patterns of the two transformation rules in this figure are shown in Figure~\\ref{fig:lts-transformation:subsets-ltss:middle}.\nActions in~$h$ are hidden.\nThe dotted lines in this figure illustrate that a divergence-sensitive branching bisimulation exists for these two networks.\n\n%%%\\begin{figure}[hbt]\n%%%\\centering\n%%%\\includegraphics[scale=0.2]{lts-transformation/figs/subsets-ltss}\n%%%\\caption{Network LTSs of networks of transformation rules}\n%%%\\label{fig:lts-transformation:subsets-ltss}\n%%%\\end{figure}\n\n\\begin{figure}[hbt]\n  \\hfill\n  \\begin{subfigure}[b]{102pt}\n    \\centering\n    \\includegraphics[scale=0.2]{lts-transformation/figs/subsets-ltss-left}\n    \\caption{}\n    \\label{fig:lts-transformation:subsets-ltss:left}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[b]{106pt}\n    \\centering\n    \\includegraphics[scale=0.2]{lts-transformation/figs/subsets-ltss-middle}\n    \\caption{}\n    \\label{fig:lts-transformation:subsets-ltss:middle}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[b]{102pt}\n    \\centering\n    \\includegraphics[scale=0.2]{lts-transformation/figs/subsets-ltss-right}\n    \\caption{}\n    \\label{fig:lts-transformation:subsets-ltss:right}\n  \\end{subfigure}\n  \\hfill\n  \\caption{Network LTSs of networks of transformation rules}\n\\end{figure}\n\nEven though a divergence-sensitive branching bisimulation exists between the networks of the left and right patterns of the transformation rules in Figure~\\ref{fig:lts-transformation:non-preserving-trafo}, the rule system is not \\Sf-preserving.\nThis clearly shows that it is not sufficient to only take successful synchronization in account.\nInstead, we also need to consider situations in which some parties are able to perform a synchronizing action whereas at least one other party involved in the synchronization is not.\nFor example, the state labeled (1 3) in Figure~\\ref{fig:lts-transformation:comparison-network} has a $\\tau$-loop that cannot be simulated by the network LTS in Figure~\\ref{fig:lts-transformation:non-preserving-trafo}.\nThis $\\tau$-loop is the result of hiding the $b$-loop of the leftmost process of Figure~\\ref{fig:lts-transformation:comparison-network}.\nThis process can perform action~$b$ independently.\nAfter transformation, however, a $\\tau$-cycle can only result from interaction between the transformed process LTSs shown in the middle of Figure~\\ref{fig:lts-transformation:non-preserving-trafo}.\nIn situations where both processes are able to interact successfully, an infinite number of $\\tau$-actions can be performed, as shown in Figure~\\ref{fig:lts-transformation:subsets-ltss:middle}.\nHowever, if the required synchronization between processes is impossible, as is the case in the state labeled (1 3) in Figure~\\ref{fig:lts-transformation:non-preserving-trafo}, only one $\\tau$-action can be performed.\n\nTo be able to consider such scenarios, we define a projection operator on networks of transformation rules.\n\n\\begin{definition}\n\\label{def:lts-transformation:projection}\nFor each vector of transformation rules~$\\xi^\\ri$ and~$j \\in 1..n$, the projection operator $/I$ ($I \\subseteq 1..n$) is defined as follows.\n\\[\n\\xi^\\ri/I[j] = \\left\\{\n\\begin{array}{ll}\n\\xi^\\ri[j]                    & {\\rm if} ~ j \\in I \\\\\n\\ast \\mapsto \\ast & {\\rm otherwise}\n\\end{array}\n\\right.\n\\]\n\\end{definition}\n\n\\noindent\nThis operator can similarly be applied on the vectors of patterns~$\\xi_{\\Llts}^\\ri$ and~$\\xi_{\\Rlts}^\\ri$, and we say that $\\Xi_\\Llts^\\ri/I = (\\xi_\\Llts^\\ri/I, \\synchrules)$ and $\\Xi_\\Rlts^\\ri/I = (\\xi_\\Rlts^\\ri/I, \\synchrules \\cup \\hat\\synchrules)$, for a given model~$\\smodel = \\networktuple$ and rule system~$\\Sigma = \\rulesystemtuple$ such that $\\ri \\in R$.\n\nFigure~\\ref{fig:lts-transformation:subsets-ltss:left} shows the left and right patterns of the rule network that contains only the topmost transformation rule of Figure~\\ref{fig:lts-transformation:non-preserving-trafo}.\nThe left pattern of this rule network is constructed from the left pattern of this transformation rule, using the synchronization rules and the hiding set of Figure~\\ref{fig:lts-transformation:comparison-network}.\nThe right pattern of this rule network is constructed from the right pattern of this transformation rule, using the synchronization rules and the hiding set of Figure~\\ref{fig:lts-transformation:non-preserving-trafo}.\nBecause these patterns are not divergence-sensitive branching bisimilar, as indicated by the cross, this rule system is not \\Sf-preserving.\nThe remaining patterns are shown in Figure~\\ref{fig:lts-transformation:subsets-ltss:right}.\n\n\\subsection{Constructing a Bisimulation Relation}\nThe following theorem formalizes our $\\Sf$-preservation check.\n\n\\begin{theorem}\n\\label{theo:lts-transformation:checkpreservation}\nLet $\\smodel = \\networktuple$ be a model and $\\Sf \\in \\dsbrLmu$ a temporal property such that $\\models_{\\smodel} \\Sf$.\nThen $\\Sigma = \\rulesystemtuple$ is $\\Sf$-preserving if the following holds, for all $\\ri \\in R$, $I \\subseteq \\inv(\\Llts^\\ri, \\synchrules)$.\n\\begin{equation}\n\\maxabstr(\\Xi_{\\Llts}^\\ri/I ) \\dsbbis \\maxabstr(\\Xi_{\\Rlts}^\\ri/I )\n\\label{eq:lts-transformation:maintheo}\n\\end{equation}\n\\end{theorem}\n\nProving this theorem for a rule system~$\\Sigma$ and a property~\\Sf entails constructing a relation between~$\\maxabstr(\\smodel)$ and~$\\maxabstr(T_{\\Sigma} (\\smodel))$ based on the divergence-sensitive branching bisimulations in equation~\\ref{eq:lts-transformation:maintheo}, for some model~\\smodel, and proving that this relation is a divergence-sensitive branching bisimulation too.\nTo describe the construction of this relation, we need a number of auxiliary definitions.\n\nFirst, a state in the network LTS of network~\\smodel is a vector $\\vectornot{s} = \\langle \\vectornot{s}[1],\\ldots, \\vectornot{s}[n] \\rangle$.\nAn arbitrary $\\vectornot{s} \\in \\states{\\smodel}$ can have up to $n$ elements that are matched on by some transformation rule.\nFor an LTS~$\\graph$ and a transformation rule~$r = \\transruletuple{r}$,\nmatching $m_r$ is extended to sets of states such that $m_r(\\states{\\Llts^r}) \\subseteq \\states{\\graph}$ refers to the set of states to which the states in $\\states{\\Llts^r}$ are matched,\nand $\\hat m_r(\\states{\\Llts^r}) = \\{ s \\in m_r(\\states{\\Llts^r}) \\mid m_r^{-1}(s) \\not\\in \\states{\\Rlts^r} \\}$ refers to the states in~\\states{\\graph} that relate to non-glue-states in $\\Llts^r$.\nBy definition, the latter states are those that are removed from~\\graph by rule~$r$.\nWe denote the set of indices of elements in $\\vectornot{s}$ matched on by the corresponding rule with $M(\\vectornot{s}) = \\{ i \\mid \\vectornot{s}[i] \\in m_\\ri(\\states{\\Llts^\\ri}) \\}$.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%In a similar way, $\\hat M(\\vectornot{s}) = \\{ i \\mid \\vectornot{s}[i] \\in \\hat m_\\ri(\\states{\\Llts^\\ri}) \\}$.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nAs indicated above, we assume that if $\\vectornot{s}[i]$ is matched on, then it is matched on by rule $r_i$.\nFurthermore, for a rule system~$\\Sigma = \\rulesystemtuple$ and a network~\\smodel, a simulation relation exists between the states in~\\smodel and those in the rule networks~$\\Xi_\\Llts^\\ri/I$ as well as between the states in~$T_{\\Sigma} (\\smodel)$ and those in~$\\Xi_\\Rlts^\\ri/I$.\nThis can be formalized as follows.\nFor a state vector $\\vectornot{s}^*$ in a rule network~$\\Xi_\\Llts^{\\ri}/I$ and a state vector $\\vectornot{s}$ in an LTS network~$\\smodel$, we say that $\\vectornot{s}$ simulates $\\vectornot{s}^*$, denoted $\\vectornot{s}^* \\vdash \\vectornot{s}$, iff $\\forall i \\in 1..n. \\vectornot{s}^*[i] \\neq \\ast \\implies \\vectornot{s}[i] = m_\\ri(\\vectornot{s}^*[i])$.\nIn other words, besides the $\\ast$-states, all process states in $\\vectornot{s}^*$ are matched on the corresponding states in $\\vectornot{s}$.\nNow, first of all, if $\\vectornot{s}^* \\vdash \\vectornot{s}$, and $\\vectornot{s}^*\\xrightarrow{a} \\vectornot{s}^*'$, then also $\\vectornot{s}\\xrightarrow{a} \\vectornot{s}'$ and $\\vectornot{s}^*' \\vdash \\vectornot{s}'$.\nSecond of all, in cases that $\\vectornot{s}\\xrightarrow{a} \\vectornot{s}'$ and some synchronization vector~$\\vectornot{t}$ enables transition~$\\vectornot{s}\\xrightarrow{a} \\vectornot{s}'$, with ${\\it Ac}(\\vectornot{t}) \\subseteq I$, ${\\it Ac}(\\vectornot{t}) \\subseteq M(\\vectornot{s})$, and ${\\it Ac}(\\vectornot{t}) \\subseteq M(\\vectornot{s}')$, then the involved behavior of every active $\\Pi[i]$ ($i \\in {\\it Ac}(\\vectornot{t})$) is matched on by $\\ri$.\nThe definition for~$\\Xi_\\Rlts^{\\ri}/I$ and~$T_{\\Sigma} (\\smodel)$ is similar.\nThese simulation relations are preserved after maximal hiding.\n\n\\begin{figure}[hbt]\n\\centering\n\\includegraphics[scale=0.2]{lts-transformation/figs/relations}\n\\caption{Constructing a divergence-sensitive branching bisimulation}\n\\label{fig:lts-transformation:relations}\n\\end{figure}\n\nA relation between two networks representing a model before and after transformation can be constructed by combining the bisimulations between pairs of rule networks with the simulation relations between model networks and rule networks.\nIn Figure~\\ref{fig:lts-transformation:relations}, the dashed lines connect some of the states in the LTSs of the rule networks with the states in the LTSs of the models that simulate them.\nThe dotted lines in the figure denote the divergence-sensitive branching bisimulations between pairs of rule networks.\nBy combining these relations, states in the LTS on the left of the figure are related to states in the LTS on the right.\nWe refer to the relation formed by combining these relations as~$D$.\nTo increase the readability of the figure, not all states that are related according to~$D$ are connected.\nFor states~$\\vectornot{s}$ of~$\\smodel$ and~$\\vectornot{p}$ of~$T_{\\Sigma} (\\smodel)$, we define $\\vectornot{s}\\ D'\\ \\vectornot{p}$ iff $\\forall i \\not \\in M(\\vectornot{s}) . \\vectornot{s}[i] = \\vectornot{p}[i]$.\nIn words, $D'$ relates all state vectors with exactly the same elements apart from those matched on by a transformation rule.\nIn a sense, $D'$ is a strong bisimulation for the behavior not subjected to transformation.\nAs mentioned above, not all states that are related according to~$D$ are connected in the figure.\nOnly those states of the LTS on the left of the figure are connected to states of the LTS on the right that are also related according to~$D'$.\nThus, the dashed and dotted lines together illustrate the relation~$(D \\cap D')$ by connecting some of the states that are related according to this relation.\nRelation~$D'' = \\{ (\\vectornot{s}, \\vectornot{s}) \\mid M(\\vectornot{s}) = \\emptyset \\}$ relates all states that are not subjected to transformation.\nThe grey lines in Figure~\\ref{fig:lts-transformation:relations} connect the states that are related according to~$D''$.\nGiven these relations, a relation~$C = (D \\cap D') \\cup D''$ can be constructed, which relates~$\\maxabstr(\\smodel)$ and~$\\maxabstr(T_{\\Sigma} (\\smodel))$.\nBy considering the cases of Definition~\\ref{def:lts-transformation:dsbbsim}, it can be shown that this relation is a divergence-sensitive branching bisimulation~\\cite{EngelenWijsPropPres2012}. ", "meta": {"hexsha": "00917a52de4f1b767b2dc841988eeb29da6d539e", "size": 26489, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "lts-transformation/property-preservation.tex", "max_stars_repo_name": "ljpengelen/latex-phd-thesis", "max_stars_repo_head_hexsha": "8cabcf160a6f06e12b5ced92bb5cec06983e5bb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-18T21:53:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-18T21:53:57.000Z", "max_issues_repo_path": "lts-transformation/property-preservation.tex", "max_issues_repo_name": "ljpengelen/latex-phd-thesis", "max_issues_repo_head_hexsha": "8cabcf160a6f06e12b5ced92bb5cec06983e5bb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lts-transformation/property-preservation.tex", "max_forks_repo_name": "ljpengelen/latex-phd-thesis", "max_forks_repo_head_hexsha": "8cabcf160a6f06e12b5ced92bb5cec06983e5bb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 87.4224422442, "max_line_length": 455, "alphanum_fraction": 0.7491034014, "num_tokens": 7220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784220301064, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.34000003985159905}}
{"text": "\\setlength{\\footskip}{8mm}\n\n\\chapter{Clustering Human Behaviors with Dynamic Time \nWarping and Hidden Markov Models}\n\\label{ch:clustering}\n\n\\textit{In this chapter, we propose and experimentally evaluate a new \nmethod for clustering human behaviors that is suitable for\nbootstrapping an anomaly detection module for intelligent video\nsurveillance systems. The method uses dynamic time warping,\nagglomerative hierarchical clustering, and hidden Markov models to\nprovide an initial partitioning of a set of observation sequences then\nautomatically identifies where to cut off the hierarchical clustering\ndendrogram. We show that the method is extremely effective, providing\n100\\% accuracy in separating anomalous from typical behaviors on\nreal-world testbed video surveillance data.}\n\n\\section{Introduction}\n\\label{sec:clustering-intro}\n\nHuman behavior understanding is an important component of a wide\nvariety of desirable intelligent systems.  However, the problem is\nvery difficult, due to the wide range of activities possible in any\ngiven context and the large amount of variability within any\nparticular activity. Many researchers have attempted to build systems\nable to interpret and understand human behaviors. The most classic\nwork is from \\shortciteA{yamato92hmm}, who model\ntennis actions using hidden Markov models (HMMs). \n\\shortciteA{du06activity} present an approach to recognize\ninteraction activities using dynamic Bayesian networks (DBNs) that\noutperforms conventional HMMs. \\shortciteA{gao04dining}\nuse a single mixture-of-Gaussian HMM, in which the states represent\nthe stages of dining activities, to monitor the eating behavior of\nelderly people in a nursing home.\n\nAs video monitoring is becoming more ubiquitous in our lives, research\non advanced video surveillance analysis is increasingly important.  To\nhelp security personnel work reliably and efficiently, we would like\nto filter out typical events, and in cases of anomalous events,\nautomatically raise an alarm or present the event to a human operator\nfor consideration as a security threat. Most existing work assumes\nthat the number of ``normal'' behavior patterns need to be known\nbeforehand. For example, \\shortciteA{nair02surveillance} built an\nautomated video surveillance system using HMMs, each modeling a\ncommon, predefined activity in a scene.\n\nIn more recent years, research has started to focus on unsupervised\nanalysis and clustering of behaviors in a particular scene for a\nvariety of purposes including anomaly detection, surveillance, and\nclassification. \\shortciteA{zhong04detection} treat video segments as\ndocuments and cluster the documents based on the co-occurrence\ninformation. \\shortciteA{li06behavior} cluster human gestures by\nconstructing an affinity matrix using dynamic time warping (DTW;\nSakoe, 1978)\\nocite{sakoe78dtw} then apply the normalized-cut approach\nto cluster the gestures. \\shortciteA{hautamaki08clustering} apply DTW\nand use the pairwise DTW distances as input to a hierarchical\nclustering process in which $k$-means is used to fine-tune the output.\n\nHere we use a combination of clustering and HMMs to group\nhuman behaviors in a scene. There is some recent related work using\ngraphical models such as HMMs to cluster behavior\npatterns. \\shortciteA{li99pattern} use the Bayesian information\ncriterion (BIC) for HMM model selection and construct a binary\nhierarchical clustering dendrogram to initialize data partitions based\non a sequence-to-model likelihood distance measure. They then compare\neach pair of clusters using a partition mutual information (PMI)\ncriterion \\shortcite{bahl86speech} to find the optimal number of\nclusters.\n\n\\shortciteA{xiang05profiling} model the distribution of\nactivity data in a scene using a Gaussian mixture model (GMM) and also\nemploy the BIC to select the optimal number of behavior classes prior\nto HMM training.\n\n\\shortciteA{swears08clustering} propose hierarchical HMM-based clustering\nto find and cluster motion trajectories and velocities in a highway\ninterchange scene. They build up a set of HMMs incrementally. For each\nnew trajectory, they first test the likelihood of the trajectory\naccording to each existing HMM model.  If the new observation is not\nfit by any existing model, it is considered deviant and is grouped\nwith other deviant observations to form a new HMM.\n\n\\shortciteA{alon03clustering} propose a method to discover groupings of\nsimilar object motions. They apply a finite mixture of HMMs where the\nnumber of mixture components is assumed to be known. They estimate the\nnumber of clusters using the minimum description length (MDL)\ncriterion \\shortcite{rissanen98mdl}, a penalized likelihood measure.\n\nIn this dissertation, we propose a new method for clustering human\nbehaviors in the context of video surveillance.  After extracting\nsequences of features representing individual human behaviors in a\ngiven scene, we use DTW to measure the pairwise similarity between\nsequences. Then we construct an agglomerative hierarchical clustering\ndendrogram based on the DTW similarity measure. To find the optimal\nset of behavior clusters, we start at the root of the tree, train a\nHMM on the patterns in that cluster, and determine how well the HMM\nmodels the set of patterns in the cluster.  When we find that a HMM is\nan insufficient representation of the patterns in a given cluster, we\nthrow away that HMM and recursively consider each of the child\nclusters according to the pre-calculated DTW-based dendrogram. Our\nmethod is able to automatically find the common human behaviors\noccurring in a given scene. In an experiment with a testbed video\nsurveillance data set, we find that the method separates typical\nbehaviors and abnormal behaviors into separate sets of clusters with\n100\\% accuracy.\n\nThe most similar related work is that\nof \\shortciteA{oates01clustering}, who first proposed the idea of\nusing the DTW with HMMs to cluster time series. They use the DTW\ndendrogram cut off at an arbitrary depth as an initial partition of\nthe training sequences, then they train HMMs on each partition\niteratively until they have a set of HMMs that models all of the\ntraining sequences.  They apply their method to simulated time series\nwith good results but report obtaining poor clustering results in an\nexperiment with real robot sensor data.\n\nAs we shall see in later chapters, the method improves upon the state\nof the art in intelligent video surveillance applications by\nbootstrapping human behavior classification and anomaly detection\nmodules in a given installation. Once a set of initial clusters and\ncorresponding HMMs representing typical behavior is determined, we can\neasily find which cluster a new sequence should fall into by\nperforming statistical tests on the sequence's likelihood according to\neach HMM model.  When the likelihood is low according to all of the\npre-existing clusters, we can consider the sequence to be anomalous\nand alert a human operator. When the likelihood is sufficiently high\nfor one of the pre-existing models, we can simply incrementally update\nthe sufficient statistics for that model.  This approach would allow\nraising alerts for behaviors inconsistent with the\nautomatically-derived typical behavior profile for the scene while\nproviding adaptation to gradual changes in typical behavior patterns\nover time. We do not focus on these incremental learning and anomaly\ndetection issues in this chapter. We consider these issues in later\nchapters.\n\nIn the rest of this chapter, I provide the details of our human\nbehavior clustering algorithm in\nSection \\ref{sec:clustering-algorithm}, demonstrate the feasibility of\nthe algorithm with an experimental evaluation in\nSection \\ref{sec:clustering-results}, and then conclude and point to\nfuture work in Section \\ref{sec:clustering-discussion}.\n\n\\section{Human Behavior Pattern Clustering}\n\\label{sec:clustering-algorithm}\n\n\\subsection{Overview}\n\n\\begin{figure}[t]\n  \\centering\n  \\subfloat[]{\\includegraphics[scale=0.4]{figures/blob-extraction-block-diagram}\n  \\label{fig:overview-blob}}\n  \\subfloat[]{\\includegraphics[scale=0.4]{figures/behavior-clustering-block-diagram}\n  \\label{fig:overview-clustering}}\n  \\caption[Block diagrams for the proposed method.]{\\small Block\n    diagrams for the proposed method.  (a) Blob extraction flow. (b)\n    Behavior clustering flow.}\n  \\label{fig:overview-blob-diagram}\n\\end{figure}\n\nFigure \\ref{fig:overview-blob-diagram} provides an overview of the\narchitecture of our proposed method.  The blob extraction phase\n(Figure \\ref{fig:overview-blob}) generates observation sequences from\nvideos as follows:\n\n\\begin{enumerate}\n  \\item Grab a few initial frames from an the input video to model the\n    background scene.\n  \\item Perform foreground extraction to get a list of blobs.\n  \\item Find the single largest blob in the scene, remove any pixels\n    likely to be shadow pixels, and extract feature vector $\\vec{f}_t$\n    for the blob at time $t$.\n  \\item Apply vector quantization using the $k$-means algorithm to\n    convert features into symbols.\n  \\item Aggregate symbol sequences and store for batch cluster\n    analysis.\n\\end{enumerate}\n\nIn the behavior clustering phase\n(Figure \\ref{fig:overview-clustering}), for the set of all discrete\nsymbol sequences, we perform the following steps:\n\n\\begin{enumerate}\n  \\item Apply DTW to the set of sequences to construct a\n    similarity-based distance matrix.\n  \\item Run agglomerative hierarchical clustering on the distance\n    matrix to get a dendrogram.\n  \\item Perform HMM-based hierarchical clustering using the set of\n    sequences and the dendrogram to get a set of HMMs modeling the\n    typical behaviors in the scene.\n\\end{enumerate}\n\n\\subsection{Blob Extraction}\n\\label{sec:clustering-blob-extraction}\n\nHere we use the motion detection and blob extraction methods\npreviously described in Sections \\ref{sec:blob-motion-detection}\nand \\ref{sec:blob-blob-extraction}, respectively.\n\nIn the work reported in this chapter, we use a simple normalized cross\ncorrelation (NCC) shadow elimination method described in\nChapter \\ref{ch:shadow} to eliminate shadows cast by moving objects.\nWe compute the grayscale correlation between the foreground pixels and\na background image constructed as the mean over each mixture of\nGaussian distribution. Any foreground pixels whose NCC with the\nbackground are above some threshold are removed. We choose this method\nbecause it works well in outdoor scenes where background texture\ninside shadows is visible.  The sample results from the foreground\nextraction and shadow removal procedures are shown in\nFigure \\ref{fig:shadow-result}. We use the NCC method for shadow\nremoval through the rest of this dissertation.\n\n\\begin{figure}\n  \\centering\n  \\subfloat[]{\\includegraphics[width=0.28\\linewidth]{figures/shadow-result01.png}\n  \\label{fig:shadow-result-original}}\n  \\hspace{0.1in}\n  \\subfloat[]{\\includegraphics[width=0.28\\linewidth]{figures/shadow-result02.png}}\n  \\hspace{0.1in}\n  \\subfloat[]{\\includegraphics[width=0.28\\linewidth]{figures/shadow-result03.png}}\n  \\caption[Sample foreground extraction and shadow removal\n    results.]{\\small Sample foreground extraction and shadow removal\n    results.  (a) Original image. (b) Foreground pixels according to\n    background model. (c) Foreground pixels after shadow removal.}\n  \\label{fig:shadow-result}\n\\end{figure}\n\nWe next apply morphological opening and closing operations to remove\nnoise and connect foreground regions, then we obtain the connected\nforeground components (blobs) and filter out any components whose size\nis below threshold. In this work, for simplicity, we evaluate our\nclustering method with videos containing a single moving blob.\n\nWe therefore follow the process previously described in\nSection \\ref{sec:blob-appearance-based-blob-tracking} for representing\na blob (connected foreground component) by a feature vector,\nnormalizing each feature independently, and quantizing the feature\nvectors into discrete symbols using $k$-means.\n\n%We therefore simply represent a blob (connected foreground component)\n%at time $t$ by the feature vector\n%\\[\n%  \\vec{f}_t = \\begin{bmatrix} x_t & y_t & s_t & r_t & dx_t & dy_t &\n%  v_t \\end{bmatrix},\n%\\]\n%where $(x_t,y_t)$ is the centroid of the blob, $s_t$ is the size of\n%the blob in pixels, $r_t$ is the aspect ratio of the blob's bounding\n%box, $(dx_t,dy_t)$ is the unit-normalized motion vector for the blob\n%compared to the previous frame, and $v_t$ is the blob's speed compared\n%to the previous frame, measured as\n%\\[\n%  v_t = \\frac{{\\sqrt {(x_t - x_{t - 1} )^2 + (y_t - y_{t - 1} )^2 }\n%  }}{{\\Delta t}},\n%\\]\n%where $\\Delta t$ is the capture time difference between the frames at\n%time $t$ and $t-1$. We increase the stability by using an average\n%velocity, measured as\n%\\[\n%  v_t  = rv_t  + (1 - r)v_{t - 1},\n%\\]\n%where $r$ is a constant. We use $r=0.5$ in our experiments.\n\n%After extracting the feature vectors $\\vec{f}_t$ over a training set,\n%we quantize them into discrete symbols using $k$-means. To prevent\n%differing numeric scales of the features from affecting the distance\n%metric, we normalize each feature independently by $z$-scaling to a\n%mean of 0 and standard deviation of 1 over the training set.  For the\n%vectors $(x_t,y_t)$ and $(dx_t,dy_t)$, rather than normalize the $x$\n%and $y$ components independently, we use a common isotropic scale\n%factor for the two dimensions to avoid overemphasizing small\n%deviations from typical trajectories in directions without much\n%deviation in the training data.\n\nCurrently, we empirically tune the free parameters (frame buffer\nlength, thresholds, and number of $k$-means clusters) to the training\ndata. We hope to automate the blob extraction parameter selection\nprocess in future work.\n\n\\subsection{Behavior Clustering}\n\\label{sec:clustering-behavior-clustering}\n\nWe model the common behaviors in a scene by clustering a set of\nobservation sequences acquired over some period of time. First, we\napply dynamic time warping (DTW) to estimate the similarity between\nevery pair of training sequences despite variations in length and\nspeed, to obtain a similarity matrix. Second, we use the similarity\nmatrix for hierarchical agglomerative clustering by first combining\nthe most similar two sequences into a single cluster then repeatedly\nmerging clusters until just one cluster is left at the root of the\ntree or dendrogram.  To determine the similarity of two clusters\nduring this step, we use the similarity of the most similar pair of\nsequences between the two clusters.\n\nThe resulting DTW dendrogram provides a convenient representation of\nthe similarity structure within a set of time sequences, but\nhierarchical clustering always comes with the practical issue of\ndetermining the optimal cutoff or number of clusters to use in a\nparticular application.  We solve this problem using HMMs as described\nbelow.\n\nThe flow of the algorithm is summarized in\nFigure \\ref{fig:flow-diagram}.  We begin at the root of the\nhierarchical clustering dendrogram and attempt to model the sequences\nin that cluster (all training sequences, for the root) using a\nHMM. When there are more than $N$ sequences in parent cluster $c$\nwhose per-observation log likelihood is less than a threshold $p_c$,\nwe consider the HMM to be inadequate, throw it away, and then\nrecursively attempt to model each of $c$'s children in the DTW\ndendrogram.  We use $N=10$ in our experiments. The per-observation log\nlikelihood of a sequence $\\vec{O}_i = \\{ O_{i, 1}, O_{i, 2} \\cdots\nO_{i, T_i} \\}$ is\n\\[\n  L_{i} = \\frac{\\log P( \\vec{O}_i \\mid M_c )}{T_i},\n\\]\nwhere $M_c$ is the HMM that models the sequences in cluster $c$, $T_i$\nis the number of observations in sequence $i$, and $P(\\vec{O}_i\n\\mid M_c)$ is calculated using the forward algorithm \\shortcite{rabiner89hmm}.\n\n%(calculated using the forward algorithm; Rabiner,\n%1989\\nocite{rabiner89hmm})\n\n\\begin{figure}[t]\n  \\begin{center} \\includegraphics[width=3.8in]{figures/clustering-flow-diagram} \\end{center} \\caption[Processing\n    flow of the use of HMM clustering method.]{\\small Processing flow\n    of the use of HMM clustering method.}  \\label{fig:flow-diagram}\n\\end{figure}\n\nTo determine the optimal rejection threshold $p_c$ for cluster $c$, we\nuse an approach similar to that of \\shortciteA{oates01clustering}.  We\ngenerate random sequences from the HMM and then calculate the mean\n$\\mu_c$ and standard deviation $\\sigma_c$ of the per-observation log\nlikelihood over the set of generated sequences.  For the lengths of\nthe generated sequences, we simply use the average length of the\ntraining patterns in cluster $c$.  After obtaining the statistics of\nthe per-observation log likelihood, we let $p_c$ be $\\mu_c -\nz \\sigma_c$, where $z$ is an experimentally tuned parameter that gives\nus convenient control over the probability of making Type I errors in\nclassifying a particular sequence as having been generated by a\nparticular HMM model.\n\n\\section{Experimental Results}\n\\label{sec:clustering-results}\n\nTo create a testbed data set, we mounted a CCTV camera to view the\nscene in front of an academic building, as seen in\nFigure \\ref{fig:shadow-result-original}. We recorded videos at a\nresolution of $320 \\times 240$ and 25 frames per second over one week\nduring working hours (9:00--17:00). To save disk space, we used a\nmotion detection technique that automatically segments a raw video\nstream into separate videos containing motion. We obtained videos\ncorresponding to over 500 motion events then manually selected the 298\nvideos containing only a single motion.\n\nWe found that there are at least four common behaviors in this scene:\npeople walking into the building, walking out of the building, parking\na bicycle, and riding a bicycle out. Figure \\ref{fig:example-behavior}\nshows examples of each of these behaviors. Other less common\nactivities include people walking into the scene then walking out or\npeople walking while telephoning and leaving the scene. For purposes\nof evaluating the results of our algorithm, we hand-labeled each of\nthe videos with the categories Walk-in, Walk-out, Cycle-in, Cycle-out,\nor Other.\n\n\\begin{figure}[t]\n  \\centering\n  \\subfloat[]{\\includegraphics[width=0.2\\linewidth]{figures/example-behavior01.pdf}}\n  \\hspace{0.05in}\n  \\subfloat[]{\\includegraphics[width=0.2\\linewidth]{figures/example-behavior02.pdf}}\n  \\hspace{0.05in}\n  \\subfloat[]{\\includegraphics[width=0.2\\linewidth]{figures/example-behavior03.pdf}}\n  \\hspace{0.05in}\n  \\subfloat[]{\\includegraphics[width=0.2\\linewidth]{figures/example-behavior04.pdf}}\n  \\caption[Examples of common human activities in our testbed\n    scene.]{\\small Examples of common human activities in our testbed\n    scene.  (a) Walking in. (b) Walking out.  (c) Cycling in. (d)\n    Cycling out.}\n  \\label{fig:example-behavior}\n\\end{figure}\n\nWe performed three experiments to evaluate our method. In Experiment\nI, we applied our proposed method, as previously described, to cluster\nthe 298 single-motion videos in our testbed data set. In Experiment\nII, we used an alternative clustering method that only uses recursive\nmodeling by HMMs, without DTW. In Experiment III, we used an\nalternative method combining HMMs with supervised learning. In every\nexperiment, we evaluated the clustering results (or classification\nresults in the case of the supervised system of Experiment III)\naccording to how well the induced categories separate the anomalous\nsequences (hand-labeled with the category ``Other'') from the typical\nsequences (Walk-in, Walk-out, Cycle-in, Cycle-out). Our main\nhypothesis was that \\textit{using DTW as a pre-process prior to\nHMM-based clustering should improve the quality of the clusters} in\nterms of separating anomalous from typical behaviors. One might also\nhave hypothesized that supervised learning (Experiment III) would be\nbetter than either of the unsupervised methods (Experiments I and II),\nbut as we shall see, we obtained a somewhat surprising result to the\ncontrary.\n\nIn all three experiments, we used linear HMMs with four states and\nbypass transitions. That is, each HMM had transitions from state 1 to\nstates 1, 2, and 3, from state 2 to states 2, 3, and 4, from state 3\nto states 3 and 4, and from state 4 to itself. We chose this model\nstructure based on our previous empirical\nexperience \\shortcite{kan08thesis}.\n\nTo find the distribution (parameters $\\mu_c$ and $\\sigma_c$) of the\nper-observation log likelihood for a particular HMM, we always\ngenerated 1000 sequences of 120 observations then used a $z$-threshold\nof 2.0, corresponding to a Type I error (probability of misclassifying\na sequence generated by the HMM as not generated by the HMM) of\n0.0228.  We fixed the parameter $N$ (the number of deviant patterns\nallowed in a cluster) to 10.\n\n\\subsection{Experiment I (DTW+HMMs)}\n\n\\begin{table}[t]\n  \\caption[Clustering results for Experiment I (DTW+HMMs).]{\\small\n    Clustering results for Experiment I (DTW+HMMs).}\n  \\label{tab:dtw-and-hmm-assoc-matrix}\n  \\begin{center}\n    \\begin{tabular}{c|c|c|c|c|c}\n      \\hline\n      Cluster \\# & Walk-in & Walk-out & Cycle-in & Cycle-out & Other \\\\ \n      \\hline \\hline\n      1  & 96 & 0  & 18 & 0 & 0 \\\\ \\hline\n      2  & 0  & 54 & 0  & 5 & 0 \\\\ \\hline\n      3  & 0  & 3  & 0  & 8 & 0 \\\\ \\hline\n      4  & 0  & 2  & 0  & 0 & 0 \\\\ \\hline\n      5  & 0  & 1  & 0  & 2 & 0 \\\\ \\hline\n      6  & 0  & 0  & 0  & 2 & 0 \\\\ \\hline\n      7  & 0  & 0  & 0  & 2 & 0 \\\\ \\hline\n      8  & 0  & 0  & 0  & 2 & 0 \\\\ \\hline\n      9  & 0  & 0  & 0  & 2 & 0 \\\\ \\hline\n      10 & 0  & 0  & 2  & 0 & 0 \\\\ \\hline\n      11 & 0  & 0  & 2  & 0 & 0 \\\\ \\hline\n      12 & 0  & 0  & 3  & 0 & 0 \\\\ \\hline\n      13 & 0  & 0  & 1  & 1 & 0 \\\\ \\hline\n      14 & 0  & 0  & 0  & 0 & 4 \\\\ \\hline\n      15 & 0  & 0  & 0  & 0 & 4 \\\\ \\hline\n      16 & 0  & 0  & 0  & 0 & 2 \\\\ \\hline\n      17 & 0  & 0  & 0  & 0 & 2 \\\\ \\hline\n      One-seq clusters & 4 & 17 & 34 & 21 & 4 \\\\ \\hline\n    \\end{tabular}\n  \\end{center}\n\\end{table}\n\nThe clustering results are shown in\nTable \\ref{tab:dtw-and-hmm-assoc-matrix}. The method obtained 97\nclusters. For the 17 clusters containing more than one sequence, we\nshow the distribution of the activities represented by each\nsequence. For the 80 clusters containing only a single sequence, we\nsummarize their distribution across the activity categories in the\nlast row of the table.\n\nIt is clear from the results that the separation of anomalous and\ntypical behaviors is excellent (100\\% accuracy), with the caveat that\n80 sequences (26.8\\% of the data set) fall into single-sequence\nclusters that would have to be manually examined by a human operator\nif the method was used to bootstrap a real-world surveillance system.\n\n\\subsection{Experiment II (HMMs only)}\n\nTo determine the extent to which our system benefits from\npreprocessing using DTW, in this experiment, we used the concept of\nrecursive modeling of the data using HMMs without using DTW as a\npre-process.  The method is similar to that\nof \\shortciteA{swears08clustering}.  We begin by training a single HMM\non all sequences and computing the distribution of the per-observation\nlog likelihood for that HMM as previously described.  We then assign\nevery sequence with a per-observation log likelihood above threshold\n$p_c$ to a cluster then repeat the process by training a new HMM on\nthe remaining sequences.  Similarly to the method of Experiment I, we\nstop splitting whenever the number of deviant sequences in the cluster\nis less than 10.\n\n\\begin{table}[t]\n  \\caption[Clustering results for Experiment II (HMMs only).]{\\small\n    Clustering results for Experiment II (HMMs only).}\n  \\label{tab:hmm-assoc-matrix}\n  \\begin{center}\n    \\begin{tabular}{c|c|c|c|c|c}\n      \\hline\n      Cluster \\# & Walk-in & Walk-out & Cycle-in & Cycle-out & Other \\\\ \n      \\hline \\hline\n      1 & 15 & 77 & 49 & 43 & 16 \\\\ \\hline\n      2 & 80 & 0 & 11 & 2 & 0 \\\\ \\hline\t\n      3 & 5 & 0 & 0 & 0 & 0 \\\\ \\hline\t\n    \\end{tabular}\n  \\end{center}\n\\end{table}\n\nThe results are shown in Table \\ref{tab:hmm-assoc-matrix}. The method\nobtains only three clusters, and the clusters are incapable of\nseparating anomalous behaviors from typical behaviors.  With manual\nassignment of all three clusters to the ``typical'' category, we would\nachieve a recall of 0, a precision of 100\\%, and an accuracy of\n94.6\\%.  By manually assigning cluster 1 to the anomalous category, we\nwould achieve a recall of 100\\%, a precision of 8\\%, and an accuracy\nof 38.3\\%.  These strikingly poor results confirm our main hypothesis,\nand we conclude that recursive HMM modeling without DTW-based\npreprocessing is useless for video surveillance.\n\n\\subsection{Experiment III (Supervised classification with HMMs)} \n\nAs an alternative approach to separating anomalous from typical\nbehaviors, in this experiment, we trained four HMMs on 80\\% of each of\nthe four typical behaviors observed in our testbed data set.  We\nretained 20\\% of each typical sequences and the 16 anomalous sequences\nas a test set. After HMM training, we manually determined the best\nper-observation log likelihood threshold for each HMM by maximizing\nthe F1 value (a measure combining both precision and recall) for the\nseparation between the positive and negative test patterns.  The\nanomalous pattern detection rate of the the combined classifier was\n50\\% (8 patterns) with a false alarm rate of 24.6\\% (16 out of 65\nnormal testing patterns).\n\nA priori, one might have hypothesized that supervised sequence\nclassification should outperform the unsupervised method we have\nproposed in this chapter.  To the contrary, we find that the\nsimple-minded approach of training a single HMM on each typical\nbehavior is far inferior.  Clearly, there is more variation within the\nbehavior categories than can be handled precisely by single simple\nHMMs.  These supervised results could presumably be improved by\napplying our clustering method within each behavior category, thus\nobtaining a collection of HMMs for each behavior category.  However,\nwe have already demonstrated that our method achieves perfect\nseparation of anomalous and typical behaviors \\textit{without any\ninformation about the labels}, so this approach would be unnecessarily\nlaborious.\n\n\\section{Discussion}\n\\label{sec:clustering-discussion}\n\nIn this chapter, we have proposed and evaluated a new method for\nclustering human behaviors.  As we shall see, the method can be used\nto bootstrap an anomaly detection module for intelligent video\nsurveillance systems.  The combination of DTW partitioning with linear\nHMM training turns out to be quite powerful; manual examination of the\nclusters obtained from our method shows a perfect separation between\ntypical and anomalous behaviors on a real-world testbed video\nsurveillance data set.\n\nThe combination of DTW with the type of linear HMMs we use in this\nwork is surprisingly effective. It is likely that the patterns DTW\ngroups together are perfectly suited for modeling by this type of HMM.\nWe plan to further explore this idea in future work.\n\nThere are two key limitations to our current method. The first is that\nwe limited the data to single motion events. The remaining chapters\nwill eliminate that constraint. The second is that although the method\nachieves 100\\% accuracy in separating typical from anomalous events,\nit does so at the cost of creating a fairly large number of\nsingle-sequence clusters that would have to be manually identified as\ntypical or anomalous by a human operator in a real surveillance\nsetting.\n\n\\FloatBarrier\n\n", "meta": {"hexsha": "3362ae0d4595036689f93521c955b218bfb78d0c", "size": 27493, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "first-revision/clustering.tex", "max_stars_repo_name": "zkan/dissertation", "max_stars_repo_head_hexsha": "458c5fce241973008bdcc3958bdf962b9197e593", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "first-revision/clustering.tex", "max_issues_repo_name": "zkan/dissertation", "max_issues_repo_head_hexsha": "458c5fce241973008bdcc3958bdf962b9197e593", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "first-revision/clustering.tex", "max_forks_repo_name": "zkan/dissertation", "max_forks_repo_head_hexsha": "458c5fce241973008bdcc3958bdf962b9197e593", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.270609319, "max_line_length": 112, "alphanum_fraction": 0.7771432728, "num_tokens": 6885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.3400000312119444}}
{"text": "\\chapter{Scientific Background}\n\nThis chapter can be used as your literature reveiw chapter and to include any\ninformation on scientific theories that are particularly relevant to your\nresearch. Here is an example of and equation.\n%\n\\begin{equation}\n    F_{es} = -\\frac{1}{2} \\int \\epsilon(\\mathbf{r}) \\mathbf{E}^2(\\mathbf{r}) dr\n    \\label{esfnrg}\n\\end{equation}\n%\nwhere $\\epsilon(\\mathbf{r})$ is the dielectric constant at position\n$\\mathbf{r}$ and $\\mathbf{E}(\\mathbf{r})$ is the electric field at the same\nposition. The equation can be referenced like this \\ref{esfnrg}.\n\nThe .bib file for this chapter is called ``literature.bib''.\n% this is where the bibliography is included. Just add your bibtex citations to\n% the literature.bib file and don't modify the code below unless you want to\n% use a different citation style instead of \"unsrtnat\".\n\\singlespacing\n\\bibliographystyle{unsrtnat}\n\\bibliography{body/published-papers-style/chapter2/literature}\n\\doublespacing\n", "meta": {"hexsha": "b14440dbf2e29c14874181d45f5a9ddf4e6991db", "size": 972, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "body/published-papers-style/chapter2/chapter2.tex", "max_stars_repo_name": "TJLW/UARK-Thesis-Disertation-LaTex-Template", "max_stars_repo_head_hexsha": "547fec9d24f9d81d31c8628ceabe499acb022443", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "body/published-papers-style/chapter2/chapter2.tex", "max_issues_repo_name": "TJLW/UARK-Thesis-Disertation-LaTex-Template", "max_issues_repo_head_hexsha": "547fec9d24f9d81d31c8628ceabe499acb022443", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "body/published-papers-style/chapter2/chapter2.tex", "max_forks_repo_name": "TJLW/UARK-Thesis-Disertation-LaTex-Template", "max_forks_repo_head_hexsha": "547fec9d24f9d81d31c8628ceabe499acb022443", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5, "max_line_length": 79, "alphanum_fraction": 0.762345679, "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.3400000312119444}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This is just an example/guide for you to refer to when producing your supplementary material for your Frontiers article.                                 %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%% Version 2.1 Generated 2015/05/22 %%%\n%%% You will need to have the following packages installed: datetime, fmtcount, etoolbox, fcprefix, which are normally inlcuded in WinEdt. %%%\n%%% In http://www.ctan.org/ you can find the packages and how to install them, if necessary. %%%\n\n\\documentclass{frontiers/frontiers_suppmat} % for all articles\n\\usepackage[toc,nomain,acronym,shortcuts,translate=false]{glossaries}\n\\usepackage{url,microtype}\n\\usepackage[colorlinks=true,linkcolor=black, citecolor=black!80, urlcolor=black!80]{hyperref}\n\\usepackage{doi}\n\\usepackage[onehalfspacing]{setspace}\n\n% Leave a blank line between paragraphs in stead of using \\\\\n\n\n\\def\\keyFont{\\fontsize{8}{11}\\helveticabold }\n\n\\def\\firstAuthorLast{Esteban {et~al.}} %use et al only if is more than 1 author\n\\def\\Authors{Oscar Esteban*, Emmanuel Caruyer, Alessandro Daducci, Meritxell Bach-Cuadra,%\nMar\\'ia-J. Ledesma-Carbayo and Andres Santos}\n\n% The Corresponding Author should be marked with an asterisk\n% Provide the exact contact address (this time including street name and city zip code) and email of the corresponding author\n\\def\\corrAuthor{Oscar Esteban}\n\\def\\corrAddress{Biomedical Image Technologies (BIT), ETSI Telecomunicaci\\'on, Av. Complutense 30, C203, E28040 Madrid, Spain}\n\\def\\corrEmail{phd@oscaresteban.es}\n\n\n\\input{abbreviations.tex}\n\n\\providecommand{\\diffantom}{\\emph{Diffantom}}\n\\providecommand{\\Diffantom}{\\emph{Diffantom}}\n\\newcommand{\\lowb}{\\textit{b0}}\n\\newcommand{\\e}[1]{\\ensuremath{\\;\\cdot\\,\\text{10}^\\text{#1}}}\n\\newcommand{\\vmaps}{\\ensuremath{\\{\\mathbf{V}_i \\,|\\, i \\in \\{1,2,3\\}\\}}}\n\\newcommand{\\fmaps}{\\ensuremath{\\{F_i \\,|\\, i \\in \\{1,2,3\\}\\}}}\n\\newcommand{\\tmaps}{\\ensuremath{\\{T_j \\,|\\, j \\in \\{1,\\ldots,5\\}\\}}}\n\\newcommand{\\diffunits}{\\ensuremath{\\text{mm}^2\\text{s}^{\\text{-1}}}}\n\n\n\\begin{document}\n\\onecolumn\n\\firstpage{1}\n\n\\title[Supplementary Material]{\\helvetica{Supplementary Material to: Diffantom}} %Please insert the title of your article here\n\n\\author[\\firstAuthorLast ]{\\Authors} %This field will be automatically populated\n\\correspondance{} %This field will be automatically populated\n\n\\extraAuth{}% If there are more than 1 corresponding author, comment this line and uncomment the next one.\n%\\extraAuth{Corresponding Author2: email2@uni2.edu}\n\n\\maketitle\n\n\\section*{Appendix}\\label{sec:appendix}\nLet $\\{T'_j\\}$ be the set of original fractions maps obtained with \\path{act_anat_prepare_fsl}, a\n  tool in \\emph{MRTrix} that combines \\gls*{fast} and \\gls*{first}\n  to generate the macrostructural 5TT map.\nFA denotes the \\gls*{fa} map obtained from the original \\gls*{dmri} data: the local fiber orientation maps\n  $\\{\\mathbf{V}_i\\}$ with their estimated volume fractions $\\{F'_i\\}$ calculated with \\gls*{bedpostx}.\nThe final $\\{T_j\\}$ maps of isotropic fractions are computed as follows:\n  \\begin{align*}\n  T_1 &= (1.0-f_{cgm}) \\cdot T'_1 \\\\\n  T_2 &= (1.0-f_{dgm}) \\cdot T'_2 \\\\\n  T_3 &= (1.0-f_{wm}) \\cdot T'_3 \\\\\n  T_4 &= T'_4 \\\\\n  T_5 &= 0.0\n  \\end{align*}\nwhere $f_{\\{cgm, dgm, wm\\}}$ are the fractions of restricted diffusion for each tissue.\n\\cite{sepehrband_brain_2015} found out that the fiber fraction ranges across the corpus\n  callosum from the 70$\\pm$8\\% in its body to an upper bound of 80$\\pm$11\\% in the splenium.\nTherefore, we choose $f_{wm} =$ 80\\% as default fraction of restricted diffusion in the\n  \\gls*{wm}.\nTo our knowledge, restricted diffusion fractions have been studied only for \\gls*{wm}.\nTherefore, we set $f_{cgm} =$ 25\\% and $f_{dgm} =$ 50\\% as they yield plausible \\gls*{fa}\n  and \\gls*{adc} maps, assessed visually.\nThe final $\\{F_i\\}$ maps are computed as follows:\n\\begin{align*}\nF_1 &= f_{wm} \\cdot T_2 \\cdot \\text{FA} + w_{f1} (f_{cgm} \\cdot T_1 + f_{dgm} \\cdot T_2) \\\\\nF_2 &= f_{wm} \\cdot T_2 - (F_1 + F_3) + w_{f2} (f_{cgm} \\cdot T_1 + f_{dgm} \\cdot T_2) \\\\\nF_3 &= f_{wm} \\cdot F'_3 + w_{f3} (f_{cgm} \\cdot T_1 + f_{dgm} \\cdot T_2)\n\\end{align*}\nwhere $w_{\\{f1, f2, f3\\}}$ are the contributions of the \\gls*{gm} compartments to each fiber population.\nBy default: $w_{f1} = $ 48\\%, $w_{f2} = $ 37\\%, $w_{f3} = $ 15\\%.\nFinally, the resulting maps are normalized to fulfill $\\sum_j T_j + \\sum_i F_i = 1.0$.\n\n\\newpage\n\\bibliographystyle{frontiers/frontiersinSCNS_ENG_HUMS}\n%\\bibliographystyle{frontiersinHLTH&FPHY} % for Health and Physics articles\n\\bibliography{Remote}\n\n\\end{document}\n\n\n% \\documentclass[english]{frontiers/frontiers_suppmat} % for Science, Engineering and Humanities and Social Sciences articles\n% \\usepackage{xifthen}\n% \\newboolean{review}\n% \\setboolean{review}{true}\n\n% \\usepackage[mode=buildnew]{standalone}\n% \\usepackage{tikz}\n% \\usepackage[framemethod=TikZ]{mdframed}\n% %\\setcitestyle{square}\n% \\usepackage{url,microtype}\n% \\usepackage[right]{lineno}\n% \\usepackage[toc,nomain,acronym,shortcuts,translate=false]{glossaries}\n% \\usepackage[colorlinks=true,linkcolor=black, citecolor=black!80, urlcolor=black!80]{hyperref}\n% \\usepackage{doi}\n% \\usepackage[onehalfspacing]{setspace}\n\n% \\def\\keyFont{\\fontsize{7}{9}\\helveticabold }\n\n\n% \\begin{document}\n% \\firstpage{1}\n% \\title[Diffantom]{Diffantom: whole-brain diffusion MRI phantoms derived from real datasets of the \\acrlong{hcp}}\n% \\maketitle\n\n\n% \\end{document}\n", "meta": {"hexsha": "4f82c18818fb9f44ab22a8b44cb27dbebbd937bb", "size": 5661, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/appendix.tex", "max_stars_repo_name": "oesteban/diffantom", "max_stars_repo_head_hexsha": "502ab3c29d66840b030f2bd277b11e9bdd33e297", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-09-25T18:25:35.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-20T03:41:39.000Z", "max_issues_repo_path": "paper/appendix.tex", "max_issues_repo_name": "oesteban/diffantom", "max_issues_repo_head_hexsha": "502ab3c29d66840b030f2bd277b11e9bdd33e297", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-06-12T16:03:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-12T16:03:43.000Z", "max_forks_repo_path": "paper/appendix.tex", "max_forks_repo_name": "oesteban/diffantom", "max_forks_repo_head_hexsha": "502ab3c29d66840b030f2bd277b11e9bdd33e297", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-02-04T16:37:40.000Z", "max_forks_repo_forks_event_max_datetime": "2016-02-04T16:37:40.000Z", "avg_line_length": 45.6532258065, "max_line_length": 156, "alphanum_fraction": 0.6822116234, "num_tokens": 1785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.33989981894926247}}
{"text": "\\documentclass[aspectratio=169]{beamer}\n\\usepackage[utf8]{inputenc}\n\\usepackage{hyperref}\n\\usepackage{amsmath,amsfonts,amsthm,bm}\n\\usepackage{color}\n\\usepackage{minted}\n\\usepackage{graphicx} % Allows including images\n\\usepackage{booktabs} % Allows the use of \\toprule, \\midrule and \\bottomrule in tables\n\\usepackage{tikz}\n\\usepackage[version=3]{mhchem}\n\\usepackage{pgfplots}\n\\pgfplotsset{compat=1.16} \n\\setminted{fontsize=\\scriptsize}\n\n\\hypersetup{\n    colorlinks=true,\n    linkcolor=red,\n    filecolor=magenta,      \n    urlcolor=red,\n}\n\n\\DeclareMathOperator*{\\argmax}{argmax}\n\\DeclareMathOperator*{\\argmin}{argmin}\n\\let \\vec \\mathbf\n\n\\mode<presentation> {\n    \\usetheme{CambridgeUS}\n    %\\setbeamertemplate{footline} % To remove the footer line in all slides uncomment this line\n    \\setbeamertemplate{footline}[page number] % To replace the footer line in all slides with a simple slide count uncomment this line\n    \\setbeamertemplate{navigation symbols}{} % To remove the navigation symbols from the bottom of all slides uncomment this line\n}\n\n\n\\title[Unsupervised Learning]{Unsupervised Learning}\n\n\\author{Shyue Ping Ong}\n\\institute[UCSD]{University of California, San Diego\\\\\n\\medskip\n}\n\\date{NANO281} % Date, can be changed to a custom date\n\n\\begin{document}\n\n\n\\begin{frame}\n    \\titlepage % Print the title page as the first slide\n\\end{frame}\n\n\n\\begin{frame}{Overview}\n    \\tableofcontents\n\\end{frame}\n\n\n\\section{Preliminaries}\n\n\\begin{frame}{Preliminaries}\n    \\begin{itemize}\n        \\item Here, we will take a digression from the \\textbf{supervised learning} that we have focused on so far, and go into \\textbf{unsupervised learning}.\n        \\item In supervised learning, model development is carried out with a set of input/output examples (training data). \n        \\item In unsupervised learning, the goal is to infer the properties of a set of data (e.g., its distribution) without training examples.\n        \\item We will include dimensionality reduction techniques within the umbrella of unsupervised learning.\n    \\end{itemize}\n\\end{frame}\n\n\\begin{frame}\n\\frametitle{Supervised vs Unsupervised Learning}\n\\begin{columns}\n\\column{0.5\\textwidth}\nSupervised learning\n\\begin{itemize}\n    \\item Learn from example inputs and outputs (labels).\n    \\item Clear metrics of success (e.g., maximum likelihood, MSE, MAE, etc.)\n    \\item Computationally efficient.\n\\end{itemize}\n\\column{0.5\\textwidth}\nUnsupervised Learning\n\\begin{itemize}\n    \\item Learn only from inputs.\n    \\item No rigorously-defined metric of success.\n    \\item Computationally complex.\n\\end{itemize}\n\n\\end{columns}\n\\end{frame} \n\n\n\\section{Principal Component Analysis}\n\n\n\\begin{frame}{Principal Component Analysis (PCA)}\n    \\begin{itemize}\n        \\item Briefly alluded to in lecture on Linear Methods (regressing on derived input directions).\n        \\item Consider a dataset that has dimension $p$. The principal components provide a sequence of best linear approximations to that data, of all ranks $q \\leq p$.\n        \\item Let the observations be $\\vec{x_1}, \\vec{x_2}, ..., \\vec{x_N}$. The rank $q$ linear model for representing this data is given by:\n        \\begin{equation*}\n            f(\\vec{\\lambda}) = \\vec{\\mu} + \\vec{V_q}\\vec{\\lambda}\n        \\end{equation*}\n        \\item $\\vec{\\mu}$ is a location vector, $\\vec{V_q}$ is a $p \\times q$ matrix with $q$ orthogonal vectors, $\\lambda$ is a length $q$ vector of parameters.\n        \\item We want to minimize the ``reconstruction error'',\n        \\begin{equation*}\n            \\min_{\\vec{\\mu}, \\vec{V_q}, \\vec{\\lambda}} \\sum_{i=1}^N ||\\vec{x_i} - \\vec{\\mu} - \\vec{V_q}\\vec{\\lambda_i}||^2\n        \\end{equation*}\n    \\end{itemize}\n\\end{frame} \n\n\\begin{frame}{Solution}\n    \\begin{itemize}\n        \\item Minimizing wrt to $\\vec{\\mu}$ and $\\vec{\\lambda_i}$ gives\n        \\begin{eqnarray*}\n        \\hat{\\vec{\\mu}} & = & \\bar{\\vec{x}}\\\\\n        \\vec{\\lambda_i} & = & \\vec{V_q}^T(\\vec{x_i}-\\bar{\\vec{x}})\\\\\n    \\end{eqnarray*}\n        \\item Need to solve:\n        \\begin{equation*}\n          \\min_{\\vec{V_q}} \\sum_{i=1}^N ||(\\vec{x_i}-\\bar{\\vec{x}}) - \\vec{V_q}\\vec{V_q}^T(\\vec{x_i}-\\bar{\\vec{x}})||^2\n        \\end{equation*}\n    \\end{itemize}\n\\end{frame} \n\n\\begin{frame}{Solution, contd.}\n    \\begin{itemize}\n        \\item Construct singular value decomposition (SVD) of $\\vec{X}$, the $N \\times p$ matrix of centered $\\vec{x_i}$.\n        \\begin{equation*}\n            \\vec{X} = \\vec{U}\\vec{D}\\vec{V}^T\n        \\end{equation*}\n        \\item $\\vec{U}$ is an $N \\times p$ orthogonal matrix, $\\vec{D}$ is a $p\\times p $ diagonal matrix with singular values $d_1 > d_2 > ... > d_p$ and $\\vec{V}$ is $p \\times p$ orthogonal matrix with right singular vectors $\\vec{v_1}, \\vec{v_2}, ...\\vec{v_p}$ as columns.\n        \\item $\\vec{UD}$ are the principal components. \n        \\item $\\vec{Xv_1}$ has highest variance among all linear combination of features, followed by $\\vec{Xv_2}$, $\\vec{Xv_3}$, etc.\n    \\end{itemize}\n\\end{frame} \n\n\n\\begin{frame}{Linear regression of bulk modulus on first two PCAs of elemental features}\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=0.47\\textwidth]{figures/pca-elements.png}\n    \\includegraphics[width=0.45\\textwidth]{figures/pca-regression.png}\n\\end{figure}\n\\end{frame} \n\n\n\\begin{frame}[fragile]{Code}\n\\inputminted{python}{example_sklearn_pca.py}\n\\end{frame} \n\n\n\\begin{frame}{Example of linear regression on PCA components}\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=0.45\\textwidth]{figures/pca-regression.png}\n\\end{figure}\n\\end{frame} \n\n\\begin{frame}{Extensions to PCA}\n    \\begin{itemize}\n        \\item Principal curves: smooth 1D curved approximation to data.\n        \\item Principal surfaces: curved 2D manifold approximation to data.\n    \\end{itemize}\n\\end{frame}\n\n\\section{Cluster Analysis}\n\n\\begin{frame}{Cluster Analysis}\n    \\begin{itemize}\n        \\item Cluster observations into groups so that pairwise differences within cluster tend to be smaller than differences between clusters.\n        \\begin{description}\n        \\item[Combinatorial algorithms] Model observed data with no underlying probability model.\n        \\item[Mixture modeling] Assumes samples are i.i.d. from some population with a probability density function.\n        \\item[Mode seekers] Estimate modes from PDF.\n        \\end{description}\n    \\end{itemize}\n\\end{frame}\n\n\\begin{frame}{K-means}\n    \\begin{itemize}\n        \\item One of the most popular iterative descent clustering methods.\n        \\item Often used with the Euclidean distance as the dissimlarity measure.\n        \\begin{equation*}\n            d(x_i, x_i') = ||x_i - x_i'||^2\n        \\end{equation*}\n        \\item Classic k-means measure distance to centroids of clusters.\n        \\item Other distance metrics are possible: weighted Euclidean, periodic boundary condition distance, etc.\n        \\item Variants:\n        \\begin{itemize}\n            \\item $K$-medoids: Use one of points as cluster center instead of centroid. Removes influence of large outliers that produce large distances.\n        \\end{itemize}\n    \\end{itemize}\n\\end{frame}\n\n\n\\begin{frame}{K-means Algorithm}\n    \\begin{enumerate}\n            \\item Initialize a set of $k$ means (centroids), e.g., choosing $k$ observations to be the initial means (Forgy algo) or randomly assigns a cluster to each observation (random partition).\n            \\item Assign each observation to the cluster with the smallest distance, i.e., partition the observations using the Voronoi diagram generated by means.\n            \\item Recalculate the new means of the observations in the new clusters.\n            \\item Algorithm is converged when assignment no longer changes.\n        \\end{enumerate}\n        \\begin{figure}\n            \\includegraphics[width=0.18\\textwidth]{figures/k-means-step-1.png}\n            \\includegraphics[width=0.18\\textwidth]{figures/k-means-step-2.png}\n            \\includegraphics[width=0.18\\textwidth]{figures/k-means-step-3.png}\n            \\includegraphics[width=0.18\\textwidth]{figures/k-means-step-4.png}\n            \\caption{Four steps of K-means algorithm. Source: Wikipedia}\n        \\end{figure}\n\\end{frame} \n\n\n\\begin{frame}{Practical considerations}\n    \\begin{itemize}\n        \\item K-means is often used for vector quantization, i.e., determining\n        \\item Determining $K$. Sometimes $K$ is based on goals, e.g., if you have a scientific / practical reason for having $K$ clusters, e.g., only $K$ instruments available or you want to bin the compounds in $K$ chemical classes.\n        \\item Gap analysis:\n        \\begin{figure}\n            \\centering\n            \\includegraphics[width=0.5\\textwidth]{figures/kmeans-gap-analysis.pdf}\n        \\end{figure}\n    \\end{itemize}\n\\end{frame}\n\n\n\\begin{frame}{Hierarchical Clustering}\n    \\begin{itemize}\n        \\item Does not require specific of number of clusters.\n        \\item Require dissimilarity measure.\n        \\item Produce hierarchical representations in which the clusters at each level of the hierarchy are created by merging clusters at the next lower level. \n        \\item Two paradigms: agglomerative (bottom-up merging) and divisive (top-down splitting).\n        \\item Typically shown in a dendrogram.\n    \\end{itemize}\n\\end{frame}\n\n\n\\begin{frame}{Recent application: Lithium Superionic Conductors}\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=0.8\\textwidth]{figures/hirerachicalclustering-superionicconductors.pdf}\n    \\caption{a. Dendrogram generated using the agglomerative hierarchical clustering method. The dashed line shows the position where all compounds are partitioned into seven groups, marked as I–VII from left to right and distinguished by different colors. b Mapping the dendrogram to the conductivity reveals the grouping of known solid-state Li-ion conductors in group V and VI. Reproduced from \\cite{zhangUnsupervisedDiscoverySolidstate2019}.}\n\\end{figure}\n\\end{frame}\n\n\n\\begin{frame}{Density-based Clustering}\n    \\begin{itemize}\n        \\item Clusters are defined as areas of higher density.\n        \\item Most popular variant is Density-based spatial clustering of applications with noise (DBSCAN).\\cite{esterDensityBasedAlgorithmDiscovering}\n        \\item DBSCAN groups together points that are closely packed together and marks points that lie alone in low-density regions as outliers. \n        \\item Key parameters of the DBSCAN algorithm are:\n        \\begin{itemize}\n            \\item eps: Max distance between two samples for one to be considered as in the neighborhood of the other. \n            \\item min\\_samples: No. of samples in a neighborhood for a point to be considered as a core point.\n        \\end{itemize}\n    \\end{itemize}\n\\end{frame}\n\n\n\\begin{frame}[fragile]{K-means and DBSCAN in scikit-learn}\n\\inputminted{python}{example_sklearn_clustering.py}\n\\end{frame}\n\n\n\n\\begin{frame}[allowframebreaks]{Bibliography}\n    \\bibliographystyle{unsrt}\n    \\bibliography{refs}\n\\end{frame}\n\n\n\n\n\\begin{frame}\n    \\Huge{\\centerline{The End}}\n\\end{frame}\n\n\\end{document}\n\n", "meta": {"hexsha": "eecfd7a2651638a686a1c7ae6aad4458607c8524", "size": 10991, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "lectures/slides_tex/05-Unsupervised_Learning.tex", "max_stars_repo_name": "materialsvirtuallab/nano281", "max_stars_repo_head_hexsha": "d527c5049aab3da99237cbff0cc749640b2c9c06", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 38, "max_stars_repo_stars_event_min_datetime": "2019-12-23T13:14:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T23:59:33.000Z", "max_issues_repo_path": "lectures/slides_tex/05-Unsupervised_Learning.tex", "max_issues_repo_name": "materialsvirtuallab/nano281", "max_issues_repo_head_hexsha": "d527c5049aab3da99237cbff0cc749640b2c9c06", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lectures/slides_tex/05-Unsupervised_Learning.tex", "max_forks_repo_name": "materialsvirtuallab/nano281", "max_forks_repo_head_hexsha": "d527c5049aab3da99237cbff0cc749640b2c9c06", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2020-02-10T20:43:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T13:45:36.000Z", "avg_line_length": 39.8224637681, "max_line_length": 446, "alphanum_fraction": 0.6985715585, "num_tokens": 2961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.33989981894926247}}
{"text": "\\chapter{Sound}\n\nWhen you set off a firecracker, it makes sound.\n\nLet's break that down a little more: Inside the cardboard wrapper of\nthe firecracker, there is potassium nitrate ($KNO_3$), sulfer ($S$),\nand carbon($C$).  These are all solids. When you trigger the chemical\nreactions with a little heat, these atoms rearrange themselves to be\npotassium carbonate ($K_2CO_3$), potassium sulfate ($K_2SO_4$), carbon\ndioxide ($CO_2$), and nitrogen ($N_2$). Note that the last two are\ngasses.\n\nThe molecules of a solid are much more tightly packed than the\nmolecules of a gas. So after the chemical reaction, the molecules\nexpand to fill a much bigger volume. The air molecules nearby get\npushed away from the firecracker.  They compress the molecules beyond\nthem, and those compress the molecules beyond them.\n\nThis compression wave radiates out as a sphere; its radius growing at\nabout 343 meters per second (``The speed of sound'').\n\nThe energy of the explosion is distributed around the surface of this\nsphere. As the radius increases, the energy is spread more and more\nthinly around. This is why the firecracker seems louder when you are\ncloser to it. (If you set off a firecracker in a sewer pipe, the sound\nwill travel much, much farther.)\n\nThis compression wave will bounce off of hard surfaces. If you set off\na firecracker 50 meters from a big wall, you will hear the explosion\ntwice. We call the second one ``an echo.''\n\nThe compression wave will be absorbed by soft surfaces. If you covered\nthat wall with pillows, there would be almost no echo.\n\nThe study of how these compression waves move and bounce is called\n\\newterm{accoustics}. Before you build a concert hall, you hire an\naccoustician to look at your plans and tell you how to make it sound\nbetter.\n\n\\section{Pitch and frequency}\n\nThe string on a guitar is very similar to the weighted spring\nexample. The farther the string is displaced, the more force it feels\npushing it back to equilibrium. Thus, it moves back and forth in a\nsine wave. (OK, it isn't a pure sine wave, but we will get to that later.)\n\nThe string is connected to the center of the boxy part of the guitar,\nwhich is pushed and pulled by the string. That creates compression\nwaves in the air around it.\n\nIf you are in the room with the guitar, those compression waves enter\nyour ear, push and pull your ear drum, which is attached to bones that\nmove a fluid that tickles tiny hairs, called \\newterm{cilia} in your\ninner ear. That is how you hear.\n\nWe sometimes see plots of sound waveforms.  The $x$-axis represents\ntime. The $y$-axis represents the amount the air is compressed at the\nmicrophone that converted the air pressure into an electrical signal.\n\n\\includegraphics[width=0.8\\linewidth]{soundwave.png}\n\nIf the guitar string is made tighter (by the tuning pegs) or shorter\n(by the guitarist's fingers on the strings), the string vibrates more\ntimes per second.  We measure the number of waves per second and we\ncall it the \\newterm{frequency} of the tone. The unit for frequency is\n\\newterm{Hertz}: cycles per second.\n\nMusicans have given the different frequencies names. If the guitarist\nplucks the lowest note on his guitar, it will vibrate at 82.4\nHertz. The guitarist will say ``That pitch is low E.'' If the string is made\nhalf as long (by a finger on the 12th fret), the frequency will be\ntwice as fast (164.8 Hertz), and the guitarist will say ``That is E an\noctave up.''\n\nFor any note, the note that has twice the frequency is one octave\nup. The note that has half the frequency is one octave down.\n\nThe octave is a very big jump in pitch, so musicians break it up into\n12 smaller steps. If the guitarist shortens the E string by one fret,\nthe frequency will be $82.4 \\times 1.059463 \\approx 87.3$ Hertz. \n\nShortening the string one fret always increases the frequency by a factor of 1.059463. Why?\n\nBecause $1.059463^12 = 2$. That is, if you take 12 of these hops, you\nend up an octave higher.\n\nThis, the smallest hop in western music, is referred to as \\newterm{half step}.\n\n\\begin{Exercise}[title={Notes and frequecies}, label=note_to_frequency]\n\nThe note A near the middle of the piano, is 440Hz. The note E is 7 half steps above A.  What is its frequency?\n \n\\end{Exercise}\n\\begin{Answer}[ref=note_to_frequency]\n\n  A is 440 Hz.  Each half-step is a multiplication by $\\sqrt[12]{2} = 1.059463094359295$\n  So the frequency of E is $(440)(2^{7/12}) = 659.255113825739859$\n\n\\end{Answer}\n\n\n\\section{Chords and harmonics}\n\nOf course, a guitarist seldom plays only one string at a\ntime. Instead, he uses the frets to pick a pitch for each string and\nstrums all six strings.\n\nSome combinations of frequencies sound better than others. We have\nalready talked about the octave: if one string vibrates twice for each\nvibration of another, they sound sweet together.\n\nMusicians speak of ``the fifth''.  If one string vibrates three times\nand the other vibrates twice in the same amount of time, they sound\nsweet together.\n\nIf one string vibrates 4 times while the other vibrates 3 times, they\nsound sweet together. Musicians call this ``the third.''\n\nEach of these different frequencies tickle different cilia in the\ninner ear, so you are able to hear all six notes at the same time when\nthe guitarist strums his guitar.\n\nWhen a string vibrates, it doesn't create a single sine wave. Yes, the\nstring vibrates from end-to-end and this generates a sine wave at what\nwe call \\newterm{the fundmental frequency}.However, there are also\n``standing waves'' on the string. One of these standing waves, is\nstill at the centerpoint of the string, but everything to the left of\nthe centerpoint is going up when everything to the right is going\ndown. This creates \\newterm{an overtone} that is twice the frequency\nof the fundamental.\n\n\\begin{tikzpicture}[\ntl/.style = {% tick labels\n    fill=white, inner sep=1pt, font=\\scriptsize,\n            },                        ]\n\n  \\draw[dashed,draw=black,\n      domain=-0:6.283,samples=300,variable=\\x] \n      plot (\\x,{0.7 * sin(deg{\\x}/2)});\n  \\draw[thick,draw=black,\n      domain=0:6.283,samples=300,variable=\\x] \n  plot (\\x,{0.7 * sin(deg{-1 * \\x}/2)});\n  \n  \\draw[dashed,draw=black,\n      domain=-0:6.283,samples=300,variable=\\x] \n      plot (\\x,{0.2 * sin(deg{\\x})});\n  \\draw[thick,draw=black,\n      domain=0:6.283,samples=300,variable=\\x] \n      plot (\\x,{0.2 * sin(deg{-1 * \\x})});\n\n \\filldraw[black] (0, 0)  circle(3pt);\n \\filldraw[black] (6.283, 0)  circle(3pt);\n\n\\end{tikzpicture}\n\nThe next overtone has two still points -- it divides the string into\nthree parts.  The outer parts are up while the inner part is\ndown. It's frequency is three times the fundamental frequency.\n\n\\begin{tikzpicture}[\ntl/.style = {% tick labels\n    fill=white, inner sep=1pt, font=\\scriptsize,\n            },                        ]\n\n  \\draw[dashed,draw=black,\n      domain=-0:6.283,samples=300,variable=\\x] \n      plot (\\x,{0.7 * sin(deg{\\x}/2)});\n  \\draw[thick,draw=black,\n      domain=0:6.283,samples=300,variable=\\x] \n  plot (\\x,{0.7 * sin(deg{-1 * \\x}/2)});\n  \n  \\draw[dashed,draw=black,\n      domain=-0:6.283,samples=300,variable=\\x] \n      plot (\\x,{0.2 * sin(1.5 * deg{\\x})});\n  \\draw[thick,draw=black,\n      domain=0:6.283,samples=300,variable=\\x] \n      plot (\\x,{0.2 * sin(1.5 * deg{-1 * \\x})});\n\n \\filldraw[black] (0, 0)  circle(3pt);\n \\filldraw[black] (6.283, 0)  circle(3pt);\n\n\\end{tikzpicture}\n\nAnd so on: 4 times the fundamental, 5 times the fundamental, etc.\n\nIn general, tones with a lot of overtones tend to sound bright. Tones\nwith just the fundamental sound thin.\n\nHumans can generally hear frequencies from 20Hz to 20,000Hz (or\n20kHz).  Young people tend to be able to hear very high sounds better\nthan older people.\n\nDogs can generally hear sounds in the 65Hz to 45kHz range.\n\n\\section{Making waves in Python}\n\nLet's make a sine wave and add some overtones to it.  Create a file \\filename{harmonics.py}\n\n\\begin{Verbatim}\nimport matplotlib.pyplot as plt\nimport math\n\n# Constants: frequency and amplitude\nfundamental_freq = 440.0 # A = 440 Hz\nfundamental_amp = 2.0\n\n# Up an octave\nfirst_freq = fundamental_freq * 2.0 # Hz\nfirst_amp = fundamental_amp * 0.5\n\n# Up a fifth more\nsecond_freq = fundamental_freq * 3.0 # Hz\nsecond_amp = fundamental_amp * 0.4\n\n# How much time to show\nmax_time = 0.0092 # seconds\n\n# Calculate the values 10,000 times per second\ntime_step = 0.00001 # seconds\n\n# Initialize \ntime = 0.0\ntimes = []\ntotals = []\nfundamentals = []\nfirsts = []\nseconds = []\n\nwhile time <= max_time:\n    # Store the time\n    times.append(time)\n    \n    # Compute value each harmonic\n    fundamental = fundamental_amp * math.sin(2.0 * math.pi * fundamental_freq * time)\n    first = first_amp * math.sin(2.0 * math.pi * first_freq * time)\n    second = second_amp * math.sin(2.0 * math.pi * second_freq * time)\n\n    # Sum them up\n    total = fundamental + first + second\n\n    # Store the values\n    fundamentals.append(fundamental)\n    firsts.append(first)\n    seconds.append(second)\n    totals.append(total)\n\n    # Increment time\n    time += time_step\n\n# Plot the data\nfig, ax = plt.subplots(2, 1)\n\n# Show each component\nax[0].plot(times, fundamentals)\nax[0].plot(times, firsts)\nax[0].plot(times, seconds)\nax[0].legend()\n\n# Show the totals\nax[1].plot(times, totals)\nax[1].set_xlabel(\"Time (s)\")\n\nplt.show()\n\\end{Verbatim}\n\nWhen you run it, you should see a plot of all three sine waves and another plot of their sum:\n\n\\includegraphics[width=0.9\\linewidth]{harmonicspy.png}\n\n\\subsection{Making a sound file}\n\nThe graph is pretty to look at, but make a file that we can listen to.\n\nThe WAV audio file format is supported on pretty much any device, and\na library for writing WAV files comes with Python.  Lets write some\nsine waves and some noise into a WAV file.\n\nCreate a file called \\filename{soundmaker.py}\n\n\\begin{Verbatim}\nimport wave\nimport math\nimport random\n\n# Constants\nframe_rate = 16000 # samples per second\nduration_per = 0.3 # seconds per sound\nfrequencies = [220, 440, 880, 392] # Hz\namplitudes = [20, 125]\nbaseline = 127 # Values will be between 0 and 255, so 127 is the baseline\nsamples_per = int(frame_rate * duration_per) # number of samples per sound\n\n# Open a file\nwave_writer = wave.open('sound.wav', 'wb')\n\n# Not stereo, just one channel\nwave_writer.setnchannels(1)\n\n# 1 byte audio means everything is in the range 0 to 255\nwave_writer.setsampwidth(1)\n\n# Set the frame rate\nwave_writer.setframerate(frame_rate)\n\n# Loop over the amplitudes and frequencies\nfor amplitude in amplitudes:\n    for frequency in frequencies:\n        time = 0.0\n        # Write a sine wave\n        for sample in range(samples_per):\n            s = baseline + int(amplitude * math.sin(2.0 * math.pi * frequency * time))\n            wave_writer.writeframes(bytes([s]))\n            time += 1.0 / frame_rate\n            \n        # Write some noise after each sine wave\n        for sample in range(samples_per):\n            s = baseline + random.randint(0, 15)\n            wave_writer.writeframes(bytes([s]))\n            \n# Close the file\nwave_writer.close()\n\\end{Verbatim}\n\nWhen you run it, it should create a sound file with several tones of\ndifferent frequencies and volumes. Each tone should be followed by\nsome noise.\n", "meta": {"hexsha": "b5902a0e1632bac33a82fb05288ad355aa436407", "size": 11198, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Modules/Oscillations/sound-en_US.tex", "max_stars_repo_name": "hillegass/sequence", "max_stars_repo_head_hexsha": "b7b4896d804c49cbc93fe86a0d2fce531afbcc1f", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-06-13T17:19:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T00:43:44.000Z", "max_issues_repo_path": "Modules/Oscillations/sound-en_US.tex", "max_issues_repo_name": "hillegass/sequence", "max_issues_repo_head_hexsha": "b7b4896d804c49cbc93fe86a0d2fce531afbcc1f", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Modules/Oscillations/sound-en_US.tex", "max_forks_repo_name": "hillegass/sequence", "max_forks_repo_head_hexsha": "b7b4896d804c49cbc93fe86a0d2fce531afbcc1f", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-05T00:43:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T00:43:58.000Z", "avg_line_length": 34.244648318, "max_line_length": 110, "alphanum_fraction": 0.7221825326, "num_tokens": 3044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.33987901850426766}}
{"text": "% declare document class and geometry\n%\\documentclass[12pt]{article} % use larger type; default would be 10pt\n%\\usepackage[margin=1in]{geometry} % handle page geometry\n\n\\input{../plaheader.tex}\n\n\\title{Astro 270 -- Astrophysical Dynamics -- The Orbits of Stars}\n\\author{UCLA, Fall 2014}\n%\\date{\\formatdate{02}{10}{2014}} % Activate to display a given date or no date (if empty),\n         % otherwise the current date is printed \n%\\date{\\formatdate{07}{10}{2014}} \n\n\\begin{document}\n\\setlength{\\unitlength}{1mm}\n\\maketitle\n\n\\section{Orbits in static spherical potentials}\nOur fundamental equation in this chapters are the equations of motion which are derived from the Lagrangian\n\\begin{equation}\nL = r^2 \\dot{\\phi}\n\\end{equation}\nOur equation of motion is:\n\\begin{equation}\nu^2 + \\frac{2[\\Phi (1/u) - E]}{L^2} = 0\n\\end{equation}\nwhere u is 1/r\n\nThe time that it takes a star to go from apocenter to pericenter back\nto apocenter is defined as the \\ref{radial period}. Since this is a\nspherical symmetric potential, pericenter and apocenter are always the\nsame for any orbit, though it may precess. The azimuthal period is the\namount of time a particle will take to complete one orbit (traverse\n2$\\pi$ of $\\phi$ if it travelled at the average speed. This will only\nbe a rational number if the orbit is closed, i.e. the beginning of an\norbit ends at the same position. There are two cases where all bound\norbits are closed. Note that \\textit{all} potentials have at least one\norbit that is bound - that of a circular orbit. \n\\subsection{Examples of Spherical Potentials}\n\\subsubsection{Spherical Harmonic Oscillator}\nIn this case, the radial period is $\\pi /\\Omega$. In order, the\nparticle only needs to traverse half of one orbit to reach back to the\nsame distance. This is because all of the orbits are ellipses centered\non the center of the potential. This is in contrast to the Kepler\npotential which has radial period of $2\\pi / \\Omega$, where the\nellipse has its \\textit{focus} at the center of the potential\n\n\\subsubsection{Kepler Potential}\n\\subsubsection{Isochrone Potential}\n\\subsubsection{Hyperbolic Encounters}\n\n\n\n\\subsection{Constants and integrals of motion}\nA \\textbf{constant of motion} is a quantity that \n\\begin{equation}\nC(\\v{x}(t_1) \\v{v}(t_1); t_1) = C(\\v x(t_2) \\v{v}(t_2); t_2)\n\\end{equation}\nThis is different from an integral of motion because you need an\ninitial condition in order to calculate one of these quantities,\ni.e. you need to know the value at some particular time in order to be\nable to get it at a different time. Generally any initial conditions\nor boundary conditions can be considered constants of\nmotion. Therefore, any orbit, which has six coordinates in phase space\nhas six constants of motion. From the current time and the six coordinates and\nphase space it is possible to determine the position in phase space. \n\nIntegrals of motion are determined solely by the potential, and are\ninvariant in time. They limit the amount of phase space that a\nparticle can inhabit. Thus the number of integrals of motion describe\nhow many coordinates are required to specify the location in phase\nspace. In other words, having n integrals of motion means that any\nparticle's orbit will lie on a 6-n dimensional subspace of x. A\nnon-isolating integral is one that does not limit the number of\ndimensions that the orbit can lie on. They're fucking useless. \n\n\\section{Orbits in Axisymmetric Potentials}\nEffective potential\n\\begin{equation}\n\\Phi_{eff} = \\Phi(R, z) + \\frac{L_z^2}{2R^2}\n\\end{equation}\n\n\n\\end{document}\n", "meta": {"hexsha": "873376757e014caef90f6fa6bf08892d12351601", "size": 3544, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "astrodynamics/chapter-3-galactic.tex", "max_stars_repo_name": "paulinearriaga/phys-ucla", "max_stars_repo_head_hexsha": "48084dbbac2f8a4748c1fdaaf63a4cebaae16809", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "astrodynamics/chapter-3-galactic.tex", "max_issues_repo_name": "paulinearriaga/phys-ucla", "max_issues_repo_head_hexsha": "48084dbbac2f8a4748c1fdaaf63a4cebaae16809", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "astrodynamics/chapter-3-galactic.tex", "max_forks_repo_name": "paulinearriaga/phys-ucla", "max_forks_repo_head_hexsha": "48084dbbac2f8a4748c1fdaaf63a4cebaae16809", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.1904761905, "max_line_length": 107, "alphanum_fraction": 0.769469526, "num_tokens": 937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.33987901850426766}}
{"text": "% !TEX root = ../thesis.tex\n\n\\chapter{Motivation}\n% \\label{cha:eva_motivation}\nThe most common method to reach degeneracy in a gas of ultracold atoms is by using evaporative cooling. Evaporative cooling works by selectively removing atoms from the trapped gas that are \\enquote{hot} compared to the rest of the sample. The remaining atoms then equilibrate and the new equilibrium temperature is lower. This is commonly also described as cutting off the tail of the Maxwell-Boltzmann distribution. \n\nIn many experiments, evaporative cooling is done in a magnetic trap, where an RF signal can be used to selectively pump atoms into an untrapped state and therefore expel them from the trap \\cite{PhysRevLett.74.3352}. However, magnetic traps have the disadvantage that magnetic offset fields cannot be used as easily, for example to tune the scattering length using a Feshbach resonance \\cite{PhysRevA.71.011602}.\n\nEvaporation can also be done in an optical dipole trap by lowering the laser intensity~\\cite{Chaudhuri_2007}. The disadvantage of optical evaporation compared to magnetic evaporation is that lowering the laser intensity is intrinsically coupled to a decrease in confinement strength for the optical trap \\cite{PhysRevA.79.061406}. This leads to a reduction in density and hence longer thermalisation times, resulting in less efficient evaporative cooling.\\\\[\\baselineskip]\n\\noindent\nOur research group is interested in Bose gases with uniform density distributions. To achieve this, a box potential is necessary. However, evaporative cooling in a stationary box potential is generally unfavourable as will be shown later. Therefore, evaporation is usually carried out in a different trap first and the atomic cloud is then transferred to a box potential. Transferring the cloud is accompanied with heating and atom loss \\cite{PhysRevLett.110.200406}. \n\nOur proposed solution is shown in \\cref{fig:evap_box_sketch}. The cloud is trapped in a box potential immediately after a MOT and a first sub-Doppler cooling stage (possibly grey molasses cooling \\cite{Rosi2018enhancedGM}). Forced evaporation is then carried out by lowering the trap depth as usual. Simultaneously, the box is compressed to dynamically control the density and therefore the elastic collision rate. This would give us the opportunity to avoid one transfer step, which would help us to reduce the cycle time of the experiment. \n\nIn order to probe the feasibility of such a system without having to build an entire experimental setup, a numerical simulation is performed. The following chapters describe the process of programming this simulation and show how this concept compares to traditional evaporative cooling processes.\n\\vfill\n\\begin{figure}[htbp]\n    \\centering\n    \\input{TexContents/Figures/Evap/BoxTrapEvaporation/BoxEvaporation.tikz}\n    \\caption[Evaporative cooling in a compressing box potential]{As atoms leave the trap, the box is compressed to control the density. Note: The graphs for the temperature and phase space density are for illustrative purposes only. It is desired that as the temperature decreases, the phase space density increases.}\n    \\label{fig:evap_box_sketch}\n\\end{figure}\n\\vfill", "meta": {"hexsha": "aacf30ba9e804cf0bb748a491eec2df444c7bf7e", "size": 3196, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "TexContents/21EVA-Motivation.tex", "max_stars_repo_name": "AvonHaaren/mphil-thesis", "max_stars_repo_head_hexsha": "f96a6c352420c34632b4d5e502a1b38024753a74", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TexContents/21EVA-Motivation.tex", "max_issues_repo_name": "AvonHaaren/mphil-thesis", "max_issues_repo_head_hexsha": "f96a6c352420c34632b4d5e502a1b38024753a74", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TexContents/21EVA-Motivation.tex", "max_forks_repo_name": "AvonHaaren/mphil-thesis", "max_forks_repo_head_hexsha": "f96a6c352420c34632b4d5e502a1b38024753a74", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 138.9565217391, "max_line_length": 542, "alphanum_fraction": 0.8141426783, "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.33987900979018454}}
{"text": "\\documentclass[12pt]{article}\n\\usepackage{makecell,amsmath}\n\\usepackage[a4paper, total={6.5in, 8in}]{geometry}\n\n\\DeclareMathAlphabet      {\\mathbfit}{OML}{cmm}{b}{it}\n\n\\title{A note on efficient automatic differentiation of array programs\n  in a pure language}\n\n\\author{Tom Ellis, Andrew Fitzgibbon, Simon Peyton Jones\\\\Microsoft Research}\n\n\\newcommand{\\dup}{\\mathrm{dup}}\n\n\\begin{document}\n\n\\maketitle\n\n\\begin{abstract}\nReverse mode automatic differentiation (AD) is an algorithm which can\nefficiently calculate the gradients of a numerical program.  When the\ninput program contains array indexing, standard AD algorithms will\nproduce a derivative program that involves array mutation.  In a\nlanguage that does not support mutation, a simple but inefficient\nalternative is to use vectors which contain zero everywhere except at\na single index.\n\nThis note suggests an another approach, through which efficient reverse mode AD\ncan be implemented for numerical array programs in a pure\nlanguage.\n\\end{abstract}\n\n\\section{Introduction}\n\nPresentations of reverse mode AD algorithms typically deal with the\naccumulation of sensitivities by using mutation.  This poses a problem\nfor the designers of a language that is intended to be pure.  In a\npure language it should not be possible to mutate data in one part of\na program and have the mutation be observed elsewhere.  How can a\nsource-to-source reverse mode AD pass be added to such a language?  In\nthis note we describe an approach for resolving the apparent tension.\n\n\\section{Recapitulating reverse mode AD}\n\nIn \\cite{adml} the authors demonstrate how to perform source-to-source\nreverse mode AD on program (\\ref{adml-program}), written in a\nfirst-order language\n\\begin{equation}\n\\label {adml-program}\ny = f(x_1, x_2) = \\ln(x_1)+x_1 x_2-\\sin(x_2)\n\\end{equation}\nIn standard mathematical notation the derivative is expressed by the\nequations\n\\begin{align*}\n  \\nabla{f}(x_1, x_2)\n  = \\left(\\frac{\\partial y}{\\partial x_1},\n  \\frac{\\partial y}{\\partial x_2} \\right)\n  = \\left(\\frac{1}{x_1} + x_2, ~x_2 - \\cos(x_2)\\right)\n\\end{align*}\nFigure \\ref{adml-diff} shows how the reverse mode derivative of\nprogram (\\ref{adml-program}) is generated.  Before differentiation the\nprogram is prepared into a normal form in which there are no compound\nexpressions. Instead, every function application is made to a variable\n(rather than a sub-expression).  This is achieved by the introduction\nof fresh variables.  The normal form is similar to administrative\nnormal form from functional programming and single static assignment\nfrom assembly languages.  The preparation step is a form of\nbook-keeping that allows the subsequent AD pass to be simpler.  If\nthis step were not performed explicitly then the AD pass would have to\nperform it implicitly.\n\n  \\newcommand{\\diff}[2]{\n    \\bar{v}_{#1} \\frac{\\partial v_{#1}}{\\partial v_{#2}}\n  }\n\n\\begin{figure}[t]\n\\center\n$\\left\\downarrow\n% The size of the parbox is how far apart the arrows are\n\\parbox{0.65\\linewidth}{%\n\\begin{tabular}[t]{ll|lll}\n\n  \\multicolumn{2}{l|}{primal code}\n  &\n  \\multicolumn{3}{l}{derivative code}\n  \\\\\n\n  \\hline\n\n  $v_{-1}$ & $= x_1$\n  &\n  $\\bar{x}_1$ & $= \\bar{v}_{-1}$\n  \\\\\n  \n  $v_{0}$ & $= x_2$\n  &\n  $\\bar{x}_2$ & $= \\bar{v}_{0}$\n  \\\\\n\n  \\hline\n\n  $v_1$ & $= \\ln{v_{-1}}$\n  &\n  \\(\\bar{v}_{-1}\\)\n  &\n  \\(= \\bar{v}_{-1} + \\diff{1}{-1}\\)\n  &\n  \\(= \\bar{v}_{-1} + \\bar{v}_1 / v_{-1}\n  \\) \\\\\n\n  $v_2$ & $= v_{-1} \\times v_0$\n  &\n  \\(\\bar{v}_0\\)\n  &\n  \\(= \\bar{v}_0 + \\diff{2}{0}\\)\n  &\n  \\(= \\bar{v}_0 + \\bar{v}_2 \\times v_{-1}\n  \\) \\\\\n\n  &\n  &\n  \\(\\bar{v}_{-1}\\)\n  &\n  \\(= \\diff{2}{-1}\\)\n  &\n  \\(\n  = \\bar{v}_2 \\times v_{0}\n  \\) \\\\\n\n  $v_3$ & $= \\sin{v_0}$\n  &\n  \\(\\bar{v}_0\\)\n  &\n  \\(= \\diff{3}{0}\\)\n  &\n  \\(\n  = \\bar{v}_3 \\times \\cos v_0\n  \\) \\\\\n\n  $v_4$ & $= v_1 + v_2$\n  &\n  \\(\\bar{v}_2\\)\n  &\n  \\(= \\diff{4}{2}\\)\n  &\n  \\(\n  = \\bar{v}_4 \\times 1\n  \\) \\\\\n\n  &\n  &\n  \\(\\bar{v}_1\\)\n  &\n  \\(= \\diff{4}{1}\\)\n  &\n  \\(\n  = \\bar{v}_4 \\times 1\n  \\) \\\\\n\n  $v_5$ & $= v_4 - v_3$\n  &\n  \\(\\bar{v}_3\\)\n  &\n  \\(= \\diff{5}{3}\\)\n  &\n  \\(\n  = \\bar{v}_5 \\times (-1)\n  \\) \\\\\n  \n  &\n  &\n  \\(\\bar{v}_4\\)\n  &\n  \\(= \\diff{5}{4}\\)\n  &\n  \\(\n  = \\bar{v}_5 \\times 1\n  \\) \\\\\n  \n  \\hline\n\n  $y$ & $= v_5$\n  &\n  $\\bar{v}_5$ & $= \\bar{y}$\n  \\\\\n\n\\end{tabular}\n}\\right\\uparrow$\n\\caption{\\label{adml-diff} The reverse mode derivative of program\n  (\\ref{adml-program}).  The arrows indicate that program statements\n  are executed in reverse for the derivative code.\n  }\n\\end{figure}\n\nThe left-hand column of Figure \\ref{adml-diff} contains the statements\nof program (\\ref{adml-program}) after preparation.  The right-hand\ncolumn contains the derivative statements, each of which corresponds\nto a statement on the left-hand side.  The reverse mode derivative\nprogram is formed by taking the statements in the left column in order\nfollowed by the statements in the right column in \\emph{reverse}\norder.  It takes as inputs $x_1$, $x_2$ and $\\bar{y}$ and returns as\noutputs $y$, $\\bar{x}_1$ and $\\bar{x}_2$.\n\n\\section{Explicit duplication}\n\nTo a pure functional programmer the derivative program might cause\nsome concern.  It seems to rely on the ability to modify the values of\nvariables after they have been assigned, in this case \\(\\bar{v}_{-1}\\)\nand \\(\\bar{v}_0\\).  Does efficient reverse mode AD inherently depend on\nmutability?  Perhaps, but as we shall see, we need not give up purity.\n\nNote that each update to a sensitivity variable $\\bar{v}$ occurs on a\nline corresponding to a use of the primal variable $v$ as an argument\n(other than the last such use where a direct assignment to $\\bar{v}$\noccurs). Thus, the recipe above mixes two concerns: that of\ndifferentiating each line of the source program and that of keeping\ntrack of each use site of each variable.  We can separate the concerns\nby performing an additional preparation pass which explicitly tracks\nreuse of each variable\\cite{minka}.\n\nFigure \\ref{adml-diff-dup} shows the reverse mode program generated\nusing ``explicit duplication form''. For every reused variable we\ninsert an explicit ``$\\dup$'' call into the program, replacing the\noriginal variable with two fresh variables.  The reverse derivative of\n``$\\dup$'' is $+$ so, in the reverse pass, lines corresponding to\nduplication perform the accumulation that was handled by mutation in\nthe earlier version.  The calculations performed in Figures\n\\ref{adml-diff} and \\ref{adml-diff-dup} are exactly the same; the\ndifference between them is is that the code of Figure\n\\ref{adml-diff-dup} is structured in a way which demonstrates that no\nmutation need happen.\n\n\\begin{figure}[t]\n\\center\n$\\left\\downarrow\n% The size of the parbox is how far apart the arrows are\n\\parbox{0.79\\linewidth}{%\n\\begin{tabular}[t]{ll|lll}\n\n  \\multicolumn{2}{l|}{primal code}\n  &\n  \\multicolumn{3}{l}{derivative code}\n  \\\\\n\n  \\hline\n\n  $v_{-1}$ & $= x_1$\n  &\n  $\\bar{x}_1$ & $= \\bar{v}_{-1}$\n  \\\\\n  \n  $v_{0}$ & $= x_2$\n  &\n  $\\bar{x}_2$ & $= \\bar{v}_{0}$\n  \\\\\n\n  \\hline\n\n  \\((\\mathbfit{v}_{-1,1}, \\mathbfit{v}_{-1,2})\\) & \\(= \\dup \\, v_{-1}\\)\n  &\n  \\(\\bar{v}_{-1}\\) & \\(= \\bar{\\mathbfit{v}}_{-1,1} + \\bar{\\mathbfit{v}}_{-1,2}\\)\n  \\\\\n\n  \\((\\mathbfit{v}_{0,1}, \\mathbfit{v}_{0,2})\\) & \\(= \\dup \\, v_0\\)\n  &\n  \\(\\bar{v}_{0}\\) & \\(= \\bar{\\mathbfit{v}}_{0,1} + \\bar{\\mathbfit{v}}_{0,2}\\)\n  \\\\\n\n  $v_1$ & $= \\ln{\\mathbfit{v}_{-1,1}}$\n  &\n  \\(\\bar{\\mathbfit{v}}_{-1,1}\\)\n  & \\(\n  = \\diff{1}{-1,1}\\)\n  & \\(\n  = \\bar{v}_1 / \\mathbfit{v}_{-1,1}\n  \\) \\\\\n\n  $v_2$ & $= \\mathbfit{v}_{-1,2} \\times \\mathbfit{v}_{0,1}$\n  &\n  \\(\\bar{\\mathbfit{v}}_{0,1}\\)\n  & \\(\n  = \\diff{2}{0,1}\\)\n  & \\(\n  = \\bar{v}_2 \\times \\mathbfit{v}_{-1,2}\n  \\) \\\\\n\n  & &\n  \\(\\bar{\\mathbfit{v}}_{-1,2}\\)\n  &\n  \\(= \\diff{2}{-1,2}\\)\n  & \\(\n  = \\bar{v}_2 \\times \\mathbfit{v}_{0,1}\n  \\) \\\\\n\n  $v_3$ & $= \\sin{\\mathbfit{v}_{0,2}}$\n  &\n  \\(\\bar{\\mathbfit{v}}_{0,2}\\)\n  & \\(\n  = \\diff{3}{0,2}\\)\n  & \\(\n  = \\bar{v}_3 \\times \\cos \\mathbfit{v}_{0,2}\n  \\) \\\\\n\n  $v_4$ & $= v_1 + v_2$\n  &\n  \\(\\bar{v}_2\\)\n  & \\(\n  = \\diff{4}{2}\\)\n  & \\(\n  = \\bar{v}_4 \\times 1\n  \\) \\\\\n\n  & &\n  \\(\\bar{v}_1\\)\n  &\n  \\(= \\diff{4}{1}\\)\n  & \\(\n  = \\bar{v}_4 \\times 1\n  \\) \\\\\n\n  $v_5$ & $= v_4 - v_3$\n  &\n  \\(\\bar{v}_3\\)\n  & \\(\n  = \\diff{5}{3}\\)\n  & \\(\n  = \\bar{v}_5 \\times (-1)\n  \\) \\\\\n  \n  & &\n  \\(\\bar{v}_4\\)\n  & \\(\n  = \\diff{5}{4}\\)\n  & \\(\n  = \\bar{v}_5 \\times 1\n  \\) \\\\\n  \n  \\hline\n\n  $y$ & $= v_5$\n  &\n  $\\bar{v}_5$ & $= \\bar{y}$\n  \\\\\n\n\\end{tabular}\n}\\right\\uparrow$\n\\caption{\\label{adml-diff-dup} The reverse mode derivative of program\n  (\\ref{adml-program}) in explicit duplication style.  The\n  newly-introduced variables appear in bold.}\n\\end{figure}\n\nAs an example of how the explicit duplication transformation is applied,\nconsider the variable $v_0$.  It was used twice in the primal code.\nThus we insert a statement\n\\[\n(v_{0,1}, v_{0,2}) = \\mathrm{dup} \\, v_0\n\\]\nwhich generates two fresh names with the same value as $v_0$.  We also\nupdate the use sites of $v_0$ so that each uses a unique one of these\nnames.  The same transformation is done for the variable $v_{-1}$.\n\nThe transformed input program has the vital property that every\nvariable is not only defined exactly once but also \\emph{used} exactly\nonce (except for the inputs and outputs).  This property is vital in\ntwo ways that we will take advantage of in the remainder of the paper.\nFirstly, our AD pass is simpler, because everything to do with keeping\ntrack of use sites is taken care of implicitly.  Secondly, pure\nfunctional programmers accept the output program as a pure functional\nprogram because it no longer looks like we are modifying variables\nafter they have been bound.\n\n\\section{Arrays}\n\nIn the previous section explicit duplication style was used as a\nconvenient preprocessing step to simplify the AD pass.  It also\nassuaged some of the fears of a pure functional programmer regarding\nmutation.  We will shortly describe how explicit duplication style can\nalso be turned to the goal of achieving efficient differentiation of\narray programs in a pure language but let us first demonstrate what\nthe difficulty is.\n\nThe problem we are trying to solve occurs when we differentiate\nprograms that contain the array index expression.  If a statement in\nour source program is of the form $e = v[i]$ then in a language that\nallows array mutation we could emit the reverse instruction\n$\\bar{v}[i] = \\bar{v}[i] + \\bar{e}$ which efficiently modifies\n$\\bar{v}$ in place.  In language that does not support mutation we do\nnot have this luxury.  Instead we would have to emit something like\n$\\bar{v} = \\bar{v} + \\textrm{deltaVec} \\, (\\textrm{size} \\, v) \\, i \\,\n\\bar{e}$, meaning that the variable $\\bar{v}$ is shadowed (the value\nthat it refers to is not modified) and the new $\\bar{v}$'s value is the old\n$\\bar{v}$'s value plus a ``delta'' array of the same size, where\n$\\textrm{deltaVec} \\, n \\, i \\, e$ is a vector of size $n$ satisfying\n\n\\[\n(\\textrm{deltaVec} \\, n \\, i \\, e)[j]\n= \\textrm{ if } i == j \\textrm{ then } e  \\textrm{ else } 0\n\\]\n\nThe mathematical value of the result is the same in each case.  On the\nother hand, the computations performed are very different.\nSpecifically, mutating a array at a single location has constant time\ncomplexity but adding two arrays has time complexity proportional to\ntheir size.  The reverse mode code containing the $\\textrm{deltaVec}$\nwastes a lot of time adding zeroes to elements of $\\bar{v}$.  The\nabsence of mutability in our language hurts us even in the cases where\nthe source program itself is pure!  Optimisations might solve the\nproblem in particular cases but there is no general solution.\n\n% It's a bit bold to claim there is no general solution.\n\n\\section{Purity}\n\nIt seems that mutation is essential for efficient reverse mode AD of\narray programs.  How do we reconcile this with our desire for purity?\nIt turns out that explicit duplication style can help.  Let's see how\nby examining what purity is, and more importantly, why we might want a\nlanguage to be pure.\n\nA pure language is one in which every function is pure.  According to\n\\cite{purity}, for a function to be pure the following conditions must\nhold\n\n\\begin{itemize}\n  \\item\n    Its return value is the same for the same arguments (no variation\n    with local static variables, non-local variables, mutable\n    reference arguments or input streams from I/O devices).\n\n  \\item\n    Its evaluation has no side effects (no mutation of local\n    static variables, non-local variables, mutable reference\n    arguments or I/O streams).\n\\end{itemize}\n\nThese purity conditions are desirable because the former permits a\nvery strong form of ``common sub-expression elimination'' and the latter permits a\nvery strong form of ``dead code elimination''.  Together\nthey allow freedom over the order in which function calls are\nevaluated.  Having these properties at one's disposal permits a large\nclass of behavior-preserving program transformations.  The\ntransformations can be used by a compiler author (for the purpose of\noptimisation) and a programmer (for the purpose of refactoring).\n\nIn a language which allows array mutation to be observed one does not\nhave the benefit of freely applying the above transformations.  On the\nother hand, if mutation happens but cannot be observed in other parts\nof the program then we \\emph{can} apply the above transformations and\nthe benefits of purity continue to hold.\n\nThis analysis of the benefits of purity gives us the clue we need to\nresolve the apparent tension between reverse mode AD and purity.  The\nexplicit duplication pass described above ensures that every variable\nis used only once.  If a variable referring to an array is used only\nonce then we can safely mutate it knowing that the mutation can never\nbe observed!\\footnote{assuming that no other variable also references\n  the same array, a condition that will indeed be satisfied by the\n  transformation pass we will describe} This might sound like a rhetorical\nsleight of hand, so let us proceed to immediately demonstrate that\nthis point of view is actually useful.\n\n\\newcommand{\\indexL}{\\mathrm{index}}\n\\newcommand{\\incL}{\\mathrm{inc}}\n\n\\begin{figure}[t]\n\\center\n\\begin{tabular}[t]{ll|ll}\n  \\multicolumn{2}{l|}{primal code}\n  &\n  \\multicolumn{2}{l}{derivative code}\n  \\\\\n\n  \\hline\n\n  $v_0$ & $= v[0]$\n  &\n  $\\bar{v}[0]$ & $ = \\bar{v}[0] + \\bar{v}_0$\n  \\\\\n  \n  $v_1$ & $ = v[1]$\n  &\n  $\\bar{v}[1]$ & $ = \\bar{v}[1] + \\bar{v}_1$\n  \\\\\n\n  $r$ & $= v_0 * v_1$\n  &\n  $\\bar{v}_0$ & $ = v_1 * \\bar{r}$\n  \\\\\n\n  & &\n  $\\bar{v}_1$ & $ = v_0 * \\bar{r}$\n  \\\\\n\\end{tabular}\n\\caption{\\label{array-program-mutating} The reverse mode derivative of\n  a pure array program, using mutation}\n\\end{figure}\n\nConsider a program, for example the one in the left-hand column of\nFigure \\ref{array-program-mutating}, in a pure first-order language\ncontaining the array index operation\n\\[\n\\cdot[\\cdot] : \\mathrm{Array} \\, a \\to \\mathrm{Int} \\to a\n\\]\nIts reverse derivative will contain array mutation whenever the primal\nprogram performed array indexing.  Now replace all array index calls\nin the primal program with calls to the function\n\\[\n\\indexL : \\mathrm{Array} \\, a \\to \\mathrm{Int} \\to (a, \\mathrm{Array}\n\\, a)\n\\]\nwhich returns the element of the array at the given index as well as\nthe original array unchanged.  This allows us to mention the original\narray later in the program, via the name given to the second component\nof the return tuple, without explicitly duplicating it.  Explicit\nduplication of an array in the primal code gives rise to the sum of\ntwo arrays in the derivative code, an expensive operation that\nreturning the original array unchanged allows us to avoid.  Reuses of\nscalar variables can then be removed by\ntransforming to explicit duplication style.\n\n\\begin{figure}[t]\n\\center\n\\begin{tabular}[t]{ll|ll}\n  \\multicolumn{2}{l|}{primal code}\n  &\n  \\multicolumn{2}{l}{derivative code}\n  \\\\\n\n  \\hline\n\n  $(v_0, v')$ & $ = \\indexL \\, v \\, 0$\n  &\n  $\\bar{v}$ & $ = \\mathrm{inc} \\, \\bar{v}' \\, 0 \\, \\bar{v}_0$\n  \\\\\n  \n  $(v_1, v'')$ & $ = \\indexL \\, v' \\, 1$\n  &\n  $\\bar{v}'$ & $ = \\mathrm{inc} \\, \\bar{v}'' \\, 1 \\, \\bar{v}_1$\n  \\\\\n\n  $r$ & $ = v_0 * v_1$\n  &\n  $\\bar{v}_0$ & $ = v_1 * \\bar{r}$\n  \\\\\n\n  & &\n  $\\bar{v}_1$ & $ = v_0 * \\bar{r}$\n  \\\\\n\\end{tabular}\n\\caption{\\label{array-program-dup} The reverse mode derivative of\n  a pure array program, in the explicit duplication style using\n  unobservable mutation}\n\\end{figure}\n\nAfter this transformation the primal program has the property that\nevery variable is used exactly once, implying that no\n\\emph{observable} in-place accumulation will be needed in the reverse\nprogram.  The reverse mode derivative of $\\indexL$ is $\\incL$ which\nperforms in-place accumulation to an array at a given index, returning the array\nafter accumulation.\n\\[\n\\incL : \\mathrm{Array} \\, a \\to \\mathrm{Int} \\to a \\to \\mathrm{Array}\n\\, a\n\\]\n% or just substitute Float instead of a\nRecall that the input array to $\\textrm{inc}$\ncannot subsequently be used in the program so the mutation that\n$\\incL$ performs cannot be observed.  Figure \\ref{array-program-dup}\nshows the program differentiated in terms of $\\incL$.\nWe hypothesise that any pure first-order program with array indexing\ncan be rewritten to use $\\indexL$ instead of $\\cdot[\\cdot]$.\n\nWe have generated two different programs, in Figures\n\\ref{array-program-mutating} and \\ref{array-program-dup}, which\nperform exactly the same calculation.  The former involves explicit\nmutation that could, in principle, be observed in the rest of the\nprogram.  The latter shows that the mutation can be made unobservable\nto the rest of the program, preserving the desirable properties of\npurity.\n\n\\section{Conclusion and further work}\n\nIn this note we presented an approach which, we hypothesise, can\nreconcile efficient reverse mode AD (which seems to inherently require mutation)\nwith a desire for purity (which facilitates a large class of useful\nprogram transformations).  We present only the details needed to\nhandle straight line programs (no loops or recursion, no branches, no\nhigher-order functions).  Explicit duplication style is a very weak\nform of linear typing and the ideas presented here extend in a natural\nway to the general case, taking further inspiration from the theory of\nlinear types.\n\n%% \\section{Leftover bits}\n\n%% Put differently with greater symmetry\n\n%% \\begin{itemize}\n%%  \\item Duplicating the result of a computation is the same as running\n%%    it twice\n\n%%  \\item Discarding the result of a computation is the same as not\n%%    running it at all\n%% \\end{itemize}\n\n%% The ability to mutate arrays implies that the duplication operation on\n%% arrays must perform a copy.  We need to avoid this copy otherwise we\n%% are back to square one!\n\n\\begin{thebibliography}{9}\n\n\\bibitem{adml}\n  Automatic differentiation in machine learning: a survey;\n  Atilim Gunes Baydin, Barak A. Pearlmutter, Alexey Andreyevich Radul, Jeffrey Mark Siskind\n  \nhttps://arxiv.org/abs/1502.05767\n  \n\\bibitem{purity}\n  https://en.wikipedia.org/wiki/Pure\\_function\n\n  %TODO: Really ought to find a better reference.  Maybe one of the two\n  %books that are referenced in Wikipedia\n\n\\bibitem{minka}\n  From automatic differentiation to message passing; Tom Minka\n\n  https://tminka.github.io/papers/acmll2019/\n\n\\end{thebibliography}\n\n\\end{document}\n", "meta": {"hexsha": "61880aed41e10695ef456dde798a7e1a0c268d8c", "size": 19218, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Linear-AD/linear-ad.tex", "max_stars_repo_name": "tomjaguarpaw/ad", "max_stars_repo_head_hexsha": "0cd0106b763b2bafc04718337868625e4b70ce50", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-16T15:05:37.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-16T15:05:37.000Z", "max_issues_repo_path": "Linear-AD/linear-ad.tex", "max_issues_repo_name": "tomjaguarpaw/ad", "max_issues_repo_head_hexsha": "0cd0106b763b2bafc04718337868625e4b70ce50", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-07-18T20:03:40.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-08T16:50:55.000Z", "max_forks_repo_path": "Linear-AD/linear-ad.tex", "max_forks_repo_name": "tomjaguarpaw/ad", "max_forks_repo_head_hexsha": "0cd0106b763b2bafc04718337868625e4b70ce50", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-18T23:02:11.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-18T23:02:11.000Z", "avg_line_length": 30.5047619048, "max_line_length": 91, "alphanum_fraction": 0.6932563222, "num_tokens": 5871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.33987900161457885}}
{"text": "\n\n    \\filetitle{simulate}{Simulate VAR model}{VAR/simulate}\n\n\t\\paragraph{Syntax}\\label{syntax}\n\n\\begin{verbatim}\nOutp = simulate(V,Inp,Range,...)\n\\end{verbatim}\n\n\\paragraph{Input arguments}\\label{input-arguments}\n\n\\begin{itemize}\n\\item\n  \\texttt{V} {[} VAR {]} - VAR object that will be simulated.\n\\item\n  \\texttt{Inp} {[} tseries \\textbar{} struct {]} - Input data from which\n  the initial condtions and residuals will be taken.\n\\item\n  \\texttt{Range} {[} numeric {]} - Simulation range; must not refer to\n  \\texttt{Inf}.\n\\end{itemize}\n\n\\paragraph{Output arguments}\\label{output-arguments}\n\n\\begin{itemize}\n\\itemsep1pt\\parskip0pt\\parsep0pt\n\\item\n  \\texttt{Outp} {[} tseries {]} - Simulated output data.\n\\end{itemize}\n\n\\paragraph{Options}\\label{options}\n\n\\begin{itemize}\n\\item\n  \\texttt{'contributions='} {[} \\texttt{true} \\textbar{}\n  \\emph{\\texttt{false}} {]} - Decompose the simulated paths into the\n  contributions of individual residuals, initial condition, the\n  constant, and exogenous inputs; see Description.\n\\item\n  \\texttt{'deviation='} {[} \\texttt{true} \\textbar{}\n  \\emph{\\texttt{false}} {]} - Treat input and output data as deviations\n  from unconditional mean.\n\\item\n  \\texttt{'output='} {[} \\emph{\\texttt{'auto'}} \\textbar{}\n  \\texttt{'dbase'} \\textbar{} \\texttt{'tseries'} {]} - Format of output\n  data.\n\\end{itemize}\n\n\\paragraph{Description}\\label{description}\n\n\\subparagraph{Backward simulation\n(backcast)}\\label{backward-simulation-backcast}\n\nIf the \\texttt{Range} is a vector of decreasing dates, the simulation is\nperformed backward. The VAR object is first converted to its backward\nrepresentation using the function\n\\href{VAR/backward}{\\texttt{backward}}, and then the data are simulated\nfrom the latest date to the earliest date.\n\n\\subparagraph{Simulation of\ncontributions}\\label{simulation-of-contributions}\n\nWith the option \\texttt{'contributions=' true}, the output database\ncontains Ne+2 columns for each variable, where Ne is the number of\nresiduals. The first Ne columns are the contributions of the individual\nshocks, the (Ne+1)-th column is the contribution of initial condition\nand the constant, and the last, (Ne+2)-th columns is the contribution of\nexogenous inputs.\n\nContribution simulations can be only run on VAR objects with one\nparameterization.\n\n\\paragraph{Example}\\label{example}\n\n\n", "meta": {"hexsha": "53287ef3a87479c091eb8f2634983e1706fca10b", "size": 2326, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "-help/VAR/simulate.tex", "max_stars_repo_name": "OGResearch/IRIS-Toolbox-For-Octave", "max_stars_repo_head_hexsha": "682ea1960229dc701e446137623b120688953cef", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-12-06T13:38:38.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-06T13:38:38.000Z", "max_issues_repo_path": "-help/VAR/simulate.tex", "max_issues_repo_name": "OGResearch/IRIS-Toolbox-For-Octave", "max_issues_repo_head_hexsha": "682ea1960229dc701e446137623b120688953cef", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-03-28T08:13:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-02T10:40:25.000Z", "max_forks_repo_path": "-help/VAR/simulate.tex", "max_forks_repo_name": "OGResearch/IRIS-Toolbox-For-Octave", "max_forks_repo_head_hexsha": "682ea1960229dc701e446137623b120688953cef", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-17T07:06:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T07:06:39.000Z", "avg_line_length": 30.2077922078, "max_line_length": 72, "alphanum_fraction": 0.7429062769, "num_tokens": 651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3397177440459006}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\marginpar{Wednesday\\\\ 2021-12-22}\n\nLast time we derived the transport equation in pitch angle: \n%\n\\begin{align}\n\\pdv{f}{t} + v \\mu \\pdv{f}{z} = \\pdv{}{\\mu } \\left(D_{\\mu \\mu } \\pdv{f}{\\mu }\\right)\n\\,,\n\\end{align}\n%\nwhere \\(D_{\\mu \\mu} = (1/2) \\expval{\\Delta \\mu \\Delta \\mu / \\Delta t}\\). \n\nThis already contains a lot of information about what scattering does to cosmic rays. \n\nIf we have the classic system with a ``gun'' of particle emitting them \ninto a plasma with Alfvén waves, those will be isotropized. \n\nBecause of this, after some time we expect to see the bulk velocity of the Alfvén waves and the cosmic rays to be the same. \n\nThis is not realistic in every situation: if the plasma is relativistic, the assumption of the particle velocity being much higher than that of the waves breaks down. \nThis can be treated, but we will not discuss it in the course; the professor can provide the necessary references upon request. \n\nAfter integrating the aforementioned equation between \\(-1\\) and \\(1\\), as well as between \\(-1\\) and \\(\\mu \\), we found \n%\n\\begin{align}\n\\pdv{M}{t} &= \\pdv{}{z} \\left( k_{zz} \\pdv{M}{z} \\right)  \\\\\nk_{zz} &= \\frac{v^2}{8} \\int \\dd{\\mu } \\frac{(1 - \\mu )^2}{D_{\\mu \\mu }} \n\\,,\n\\end{align}\n%\nwhere the first equation tells us that \\(M\\) changes in time due to a process of \\emph{spatial} diffusion, which is caused (as the second equation tells us) by diffusion in pitch angle.\n\nThe second-order nature of this equation is a trademark of a diffusive process.\nWith a heuristic line of reasoning we got a typical time for diffusion by \\SI{90}{\\degree}, called \n%\n\\begin{align}\n\\tau_{90} = \\frac{1}{D_{\\mu \\mu }} \n\\,,\n\\end{align}\n%\nwhich allows us to define \\(\\lambda = v \\tau_{90}\\), \nwhile the correct expression is the one for \\(k_{zz }\\) above. \n\nOne thing we are still missing is the effect of the plasma! \nThat is currently only described through the fact that the particles are diffusing in pitch angle due to Alfvén waves. \n\nCan we not ignore the bulk velocity if we move to the correct frame?\nYes! But, we cannot do the same if there are velocity \\emph{gradients}. \n\nSuppose we have a nonrelativistic plasma velocity \\(u(z)\\). \nThe change in the particle velocity term \\(v \\mu \\) can be approximated as \\(v \\mu \\to u + v \\mu \\).\n\n\\todo[inline]{Risky! \\(u + v \\mu \\) could be larger than \\(c\\)! Wouldn't a better approximation be \\(v \\mu \\)? }\n \nWhat about the momentum? We transform it as \n%\n\\begin{align}\n\\left[\\begin{array}{c}\nE' \\\\ \np_z'c\n\\end{array}\\right]\n=\n\\left[\\begin{array}{cc}\n\\gamma  & -\\beta \\gamma  \\\\ \n- \\beta \\gamma  & \\gamma \n\\end{array}\\right]\n\\left[\\begin{array}{c}\nE \\\\ \np_zc\n\\end{array}\\right]\n\\,.\n\\end{align}\n\nSo, the \\(z\\)-axis momentum \\(p_z\\) changes to \\(p_z'c = - \\beta \\gamma E + \\gamma p_z c\\), where \\(\\beta = u(z) / c\\). \n\nThe derivative of the phase space distribution changes to \n%\n\\begin{align}\n\\pdv{f}{z} \\to \\pdv{f'}{z'} &= \\pdv{f'}{p'_z} \\pdv{p'_z}{z'}  \\\\\n&= \\pdv{f'}{p_z'} \\left( - \\dv{u(z)}{c} \\right) \\frac{E'}{c}   \\\\\nv \\mu \\pdv{f}{z} &\\to - (u + v \\mu ) \\left( \\pdv{f'}{p'} \\frac{E'}{c} \\dv{u(z)}{c} \\right)  \\\\\n&= (u + v \\mu ) \\pdv{f'}{z'} - (u + v \\mu ) \\pdv{f'}{p'} \\frac{E'}{c^2} \\dv{u}{z'}  \\\\\n&\\approx (u + v \\mu ) \\pdv{f'}{z'} - v \\mu \\pdv{f'}{p'} \\frac{E'}{c^2} \\dv{u}{z'}\n\\marginnote{ \\(u \\ll v \\mu \\)}\n\\,.\n\\end{align}\n\nWe neglect the derivative of \\(\\gamma \\) since \\(\\gamma = 1 + \\order{\\beta^2}\\), and we are working to first order around 0 in the \\(\\beta \\) corresponding to the plasma. \n\nThe change of coordinates formulas read \n%\n\\begin{align}\n\\dd{\\mu } &= \\frac{1 - \\mu^2}{p} \\dd{p_z} - \\mu (1 - \\mu^2)^{1/2} \\dd{p_\\perp }  \\\\\n\\dd{p} &= \\mu \\dd{p_z} + (1 - \\mu^2)^{1/2} \\dd{p_\\perp}\n\\,,\n\\end{align}\n%\nwhich means we get \n%\n\\begin{align}\n\\pdv{f}{p_z} = \\pdv{f}{p} \\mu + \\pdv{f}{\\mu } \\frac{1 - \\mu^2}{p}\n\\,,\n\\end{align}\n%\ntherefore\n%\n\\begin{align}\nv \\mu \\pdv{f}{z} &\\approx (u + v \\mu ) \\pdv{f}{z}- v \\mu \\frac{E'}{c^2} \\dv{u}{z} \\left( \\pdv{f}{\\mu } p + \\pdv{f}{p} \\frac{1 - \\mu^2}{p} \\right)\n\\,.\n\\end{align}\n\nNow we can apply the exact same approach as before!\nWe just added the term \\(u \\pdv*{f}{z}\\). \n\nThe term \\(\\pdv*{f}{\\mu }\\) can be neglected, because \\(f\\) is assumed to be close to isotropy. If we do not neglect it, we only get higher order corrections. \n\nThis yields \n%\n\\begin{align}\n\\frac{v E'}{c^2} \\pdv{\\mu }{p } \\frac{1}{2} \\int_{-1}^{1} \\dd{\\mu } \\mu^2 = \\frac{1}{3} \\frac{ v E'}{c^2} \\pdv{\\mu}{p} \n\\,.\n\\end{align}\n\nThe object in front can be written in terms of the Lorentz factor of the particle \\(\\Gamma \\): \n%\n\\begin{align}\n\\frac{v E'}{c^2} = \\frac{v m_p c^2 \\Gamma }{c^2} = p\n\\,,\n\\end{align}\n%\nso the final result is \n%\n\\begin{align}\n\\pdv{M}{t} + u \\pdv{M}{z} - \\frac{1}{3} \\dv{u}{z} p \\pdv{M }{p }\n= \\pdv{}{z} \\left( k_{zz} \\pdv{M}{z} \\right)\n\\,.\n\\end{align}\n\nThis is the transport equation for any non-thermal particles. \nThe assumption of those being non-thermal is implicit in the assumption that \\(v \\gg u\\). \nThis is conceptually important, since we need to answer the mechanism by which these particles emerge out of the thermal distribution. \n\nThe \\emph{injection problem} is about how we go from a thermal distribution to a thermal distribution with non-thermal particles. \n\nThe effect of the particles on the plasma is also something which we should consider. \nThis would be a dependence of \\(u\\) and \\(k_{zz}\\) on the distribution of non-thermal particles. \n\nThe term \\(p \\pdv*{M}{p}\\) is sensitive to the \\emph{spectrum} of the particles! \nThis can change the distribution of particles in \\(p\\). \n\n\\begin{extracontent}\n    Exercise:  suppose we have a system with particles injected and removed from surfaces orthogonal to \\(k\\). \n    Further, suppose that \\(k_{zz}\\) is very small: this means that there is a lot of diffusion, since \\(D_{\\mu \\mu }\\) is very large.\n    \n    This basically means that the particles are ``glued'' to the plasma. \n    Therefore, we also get \\(\\pdv*{M}{t} = 0\\). \n    \n    What happens to the distribution function in this case? \n    Suppose there is a linear gradient in the plasma velocity, \n    %\n    \\begin{align}\n    u = u_0 + \\frac{\\Delta u}{L} z\n    \\,.\n    \\end{align}    \n    \n    Hint: using the method of characteristics. \n    \n    The expected result is to get adiabatic compression. \n    If the velocity decreases we get energy increasing, and vice versa. This is the same as cosmological redshift.   \n\\end{extracontent}\n\nThe way this works is that since there is a velocity gradient, in some reference frame we need to transform the magnetic field, therefore we also get an electric field which does the work. \n\n\\subsection{Particle transport}\n\nIn nature there are basically two acceleration mechanisms:\n\\begin{enumerate}\n    \\item when \\(\\expval{\\vec{E}} \\neq 0\\) --- \\emph{regular processes};\n    \\item when \\(\\expval{\\vec{E}} = 0\\) but \\(\\expval{E^2} = 0\\) --- \\emph{stochastic processes}. \n\\end{enumerate}\n\nUnipolar inductors are when we have a magnet spinning very fast generating an electric field. \nThis might happen, for example, near a pulsar! \nIn the ideal MHD approximation \\(E\\) is orthogonal to \\(B\\), but near a pulsar this can be broken! \nThen, we get a parallel component.\nAnother way this can happen is the accretion of a black hole. \n\nNear a neutron star the magnetic field is roughly dipolar; \nif \\(E \\parallel B\\) we get an electric field which is about 8 orders of magnitude larger than the gravitational field. \nSo, particles feeling this field are stripped off. \n\nWhen this happens, the particles still feel the very strong magnetic field. \nSo, electrons undergoing this process with a tilted dipolar magnetic field emit curvature radiation (bremsstrahlung). \n\nWe need to give a quantum description of such a magnetic field; \nthe virtual photons of this field can do pair production. \n\nThis process can repeat for \\(\\num{e4}\\) to \\num{e6} times: electrons stripped from the star are multiplied, and we get a lot of positrons as well. \nThese particles form a plasma of their own!\n\nThis will not be really discussed in this course, but there will be a short course about it. \n\nIdeal MHD is locally violated, giving rise to regular processes, in plasma reconnection as well. \n\nMagnetic flux is not conserved anymore, and we get heating of particles. \n\nThe rest of this course will mainly be about \\textbf{stochastic} processes. \nWe will discuss \\emph{second order Fermi acceleration}, the first investigation of particle acceleration historically. \n\nFermi, after getting the Nobel in '38, moved to Chicago and then worked on the Manhattan Project. \n\nAfter the war, he started to work on many new problems. \nThe professor has met the last student of Fermi, Simpson. \n\nAt uni Chicago there is a quadrangle, which in 1948 was used to hold important dinners. \nEnrico Fermi was not there a few minutes from midnight on New Year's, \nat which point he came running and sweaty, having understood how cosmic rays were accelerated. \nThe idea came to Fermi after Alfvén gave a talk about waves. \n\nThe model by Fermi does not really work, but it was important historically. \n\nThe momentum of the particles in an Alfvén wave will change by \\(\\Delta p / p \\sim v_A / c\\), but this will happen stochastically with \n%\n\\begin{align}\nD_{pp} = \\expval{\\frac{\\Delta p \\Delta p}{\\Delta t}} = \\frac{p^2}{T^2} \\left( \\frac{v_A}{c}\\right)^2\n\\,,\n\\end{align}\n%\nso the acceleration timescale is \\(\\tau _{\\text{acc}} =p^2 / D_{pp} = (c / v_A)^2 T\\). \nThis is too long to actually be the origin of cosmic rays, but in 1948  this was not clear. \n\nThis is called second-order because of two reasons: the square in \\((c / v_A)\\), and the fact that the diffusive motion can both increase and decrease the momentum. \n\nSuppose we have regions of plasma moving in different directions. \nAlso suppose we have an electric field \\(E\\) in the reference frame of the laboratory. \nA particle will sometimes ``interact'' with one of these magnetized regions, in a purely elastic way. \n\nWe introduce \\(\\beta \\) and \\(\\gamma \\) for the plasma clouds, with \\(\\beta \\ll 1\\). \n\nAfter the scattering with the cloud, the energy of the particle in the reference frame of the cloud will become \n%\n\\begin{align}\nE' = \\gamma E + \\beta \\gamma p \\mu \n\\,.\n\\end{align}\n\nSuppose that the scattering is purely elastic: \\(\\mu \\) is simply reversed. The cloud is acting like a mirror. \nThis is not really necessary, it is just a simplifying assumption. \n\nThe final energy in the lab frame will be \n%\n\\begin{align}\nE'' &= \\gamma E' + \\beta \\gamma p'_z \\mu  \n\\marginnote{The momentum is reversed, hence the plus sign.}  \\\\\n&= \\gamma^2 E \\left( 1 + p^2 + 2 \\beta \\mu  \\frac{p}{E} \\right)\n\\,,\n\\end{align}\n%\nwhere \\(p / E\\) is the velocity of the particle. \n\nThe quantity we are interested in is \n%\n\\begin{align}\n\\frac{E'' - E}{E} &= \\gamma^2 \\left(  1 + 2 p v \\mu + \\beta^2 \\right) - 1  \\\\\n&\\approx 2 \\beta^2 + 2 \\beta^2 + 2 \\beta v \\mu \n\\marginnote{In the relativistic approximation, \\(\\beta \\ll 1\\) but \\(v \\sim 1\\).}\n\\,.\n\\end{align}\n\nWhat is the mean value of this? \nIt can attain positive and negative values, depending on the scattering angle \\(\\mu \\). \nThis is the reason this process does not work! \n\nIf there is a situation for which \\(\\mu \\) is bound to only allow acceleration, that can work. \n\nWe need to average this, weighed by the probability to have an interaction with a given \\(\\mu \\). \nThe probability will be proportional to the relative velocity, \n\\todo[inline]{Why? If the particle is chasing the cloud it will catch it!}\n%\n\\begin{align}\n\\mathbb{P }(\\mu ) = A v _{\\text{rel}} = A \\frac{\\beta \\mu + v}{1 + v \\beta \\mu } \\approx A (1  + \\beta \\mu )\n\\,,\n\\end{align}\n%\nand \\(A\\) must be \\(1/2\\) for normalization. \nWe can then compute \n%\n\\begin{align}\n\\expval{\\frac{\\Delta E}{E}} = \\int_{-1}^{-1} \\dd{\\mu } \\frac{1}{2} \\left( 2 \\beta^2 + 2 \\beta^2 + 2 \\beta v \\mu  \\right) \\left(1 + \\beta \\mu \\right) = \\frac{8}{3} \\beta^2\n\\,,\n\\end{align}\n%\nso we have a mechanism for acceleration, but it is \\(\\propto \\beta^2\\). \nThe typical velocity, as we know now, is of a few tens of \\SI{}{km/s}, which means we have something of the order \\num{e-9}.\n\nIf the plasma is relativistic, even second order processes can be important, and actually for long gamma ray bursts they are believed to be the main mechanism. \n\nThe problem of injection, as mentioned by Fermi, is about the fact that we have nuclei as well as protons in cosmic rays. \nHow do we deal with ionization losses? \nThere is no solution to this problem, the mechanism does not really work. \n\nThis was understood about 30 years later.\nThe thing we need to discuss are explosions and shock waves.\n\n\\end{document}\n", "meta": {"hexsha": "01b39aaa408b468e329b4dc9beeeafbb3606ffc6", "size": 12662, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "phd_courses/theoretical_high_energy_astroparticle/dec22.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "phd_courses/theoretical_high_energy_astroparticle/dec22.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phd_courses/theoretical_high_energy_astroparticle/dec22.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 41.1103896104, "max_line_length": 189, "alphanum_fraction": 0.6848839046, "num_tokens": 3894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6001883592602049, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.33971773595021265}}
{"text": "%\\documentclass[12pt]{article}\n\\documentclass[12pt,landscape]{article}\n\n\n\\include{preamble}\n\n\\newcommand{\\instr}{\\small Your answer will consist of a string (e.g. \\texttt{aebgd}) where the order of the letters does not matter nor does upper / lowercase. \\normalsize}\n\n\\title{Math 368 / 621 Fall \\the\\year{} \\\\ Midterm Examination One}\n\\author{Professor Adam Kapelner}\n\n\\date{Wednesday, September 22, \\the\\year{}}\n\n\\begin{document}\n\\maketitle\n\n%\\noindent Full Name \\line(1,0){410}\n\n\\thispagestyle{empty}\n\n\\section*{Code of Academic Integrity}\n\n\\footnotesize\nSince the college is an academic community, its fundamental purpose is the pursuit of knowledge. Essential to the success of this educational mission is a commitment to the principles of academic integrity. Every member of the college community is responsible for upholding the highest standards of honesty at all times. Students, as members of the community, are also responsible for adhering to the principles and spirit of the following Code of Academic Integrity.\n\nActivities that have the effect or intention of interfering with education, pursuit of knowledge, or fair evaluation of a student's performance are prohibited. Examples of such activities include but are not limited to the following definitions:\n\n\\paragraph{Cheating} Using or attempting to use unauthorized assistance, material, or study aids in examinations or other academic work or preventing, or attempting to prevent, another from using authorized assistance, material, or study aids. Example: using an unauthorized cheat sheet in a quiz or exam, altering a graded exam and resubmitting it for a better grade, etc.\n\\\\\n\n\\noindent By taking this exam, you acknowledge and agree to uphold this Code of Academic Integrity. \\\\\n\n%\\begin{center}\n%\\line(1,0){250} ~~~ \\line(1,0){100}\\\\\n%~~~~~~~~~~~~~~~~~~~~~signature~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ date\n%\\end{center}\n\n\\normalsize\n\n\\section*{Instructions}\n\nThis exam is 75 minutes (variable time per question) and closed-book. You are allowed \\textbf{one} page (front and back) of a \\qu{cheat sheet}, blank scrap paper and a graphing calculator. Please read the questions carefully. No food is allowed, only drinks. %If the question reads \\qu{compute,} this means the solution will be a number otherwise you can leave the answer in \\textit{any} widely accepted mathematical notation which could be resolved to an exact or approximate number with the use of a computer. I advise you to skip problems marked \\qu{[Extra Credit]} until you have finished the other questions on the exam, then loop back and plug in all the holes. I also advise you to use pencil. The exam is 100 points total plus extra credit. Partial credit will be granted for incomplete answers on most of the questions. \\fbox{Box} in your final answers. Good luck!\n\n\\pagebreak\n\n\n\n\n\\problem\\timedsection{7} These are questions about indicator functions.\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{11} \n\n\\begin{enumerate}[(a)]\n%\\setcounter{enumi}{3}\n\\item $\\sum_{x \\in \\reals} \\indic{x \\in \\braces{17}} = 17$\n\\item $\\sum_{x \\in \\reals} \\indic{x \\in \\braces{17}} = 1$\n\\item $\\prod_{x \\in \\reals} \\indic{x \\in \\braces{17}} = 17$\n\\item $\\prod_{x \\in \\reals} \\indic{x \\in \\braces{17}} = 1$\n\\item $\\sum_{x \\in \\reals} h(x) \\indic{x \\in \\naturals} = \\sum_{x \\in \\naturals} h(x)$ where $h$ is a function. \\\\\n\nLet $X$ be a discrete rv with PMF $p(x)$, old-style PMF $p^{old}(x)$ and support $\\support{X}$. For any $X$,\n\\item $\\sum_{x \\in \\reals} \\indic{x \\in \\support{X}} = 1$\n\n\\item $\\sum_{x \\in \\reals} p^{old}(x) = 1$\n\\item $\\sum_{x \\in \\support{X}} p^{old}(x) = 1$\n\\item $\\sum_{x \\in \\reals} p^{old}(x) \\indic{x \\in \\support{X}} = 1$\n\n\\item $\\sum_{x \\in \\reals} p(x) = 1$\n\\item $\\sum_{x \\in \\reals} p(x) \\indic{x \\in \\support{X}} = 1$\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\problem\\timedsection{8} Let \n\n\\beqn\n\\X = \\twovec{X_1}{X_2} \\sim p_{\\X}(\\x), ~~ T := X_1 + X_2 \\sim p_{T}(t),  ~~\nX_1 \\sim p_{X_1}(x) := \\begin{cases}\n5 \\withprob 0.2 \\\\\n10 \\withprob 0.8\n\\end{cases}  \\text{independent of} ~~\n%\nX_2 \\sim p_{X_2}(x) :=\\begin{cases}\n-5 \\withprob 0.1 \\\\\n-10 \\withprob 0.9\n\\end{cases}\n\\eeqn\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{8} \n\n\\begin{enumerate}[(a)]\n%\\setcounter{enumi}{3}\n\\item $X_1, X_2$ are identically distributed\n\\item $\\var{\\X} = \\var{T}$\n\\item $T = \\a \\X$ where $\\a = [1~1]$\n\\item $p_{T}(t) = p_{X_1}(x) \\star p_{X_2}(x)$\n\\item $p_{T}(t) = \\sum_{x_1 \\in \\reals} \\sum_{x_2 \\in \\reals} p_{\\X}(x_1, x_2)$\n\\item $p_{T}(t) = \\sum_{x_1 \\in \\reals} \\sum_{x_2 \\in \\reals} p_{\\X}(x_1, x_2) \\indic{t = x_1 + x_2}$\n\\item $p_{T}(t) = \\sum_{x_1 \\in \\reals} \\sum_{x_2 \\in \\reals} p_{X_1}(x_1)p_{X_2}(x_2) \\indic{t = x_1 + x_2}$\n%\\item $p_{T}(t) = \\sum_{x \\in \\reals}  p_{\\X}(x, t - x)$\n\\item $p_{T}(t) = \\sum_{x \\in \\reals}  p_{X_1}(x)p_{X_2}(t - x)$\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\problem\\timedsection{10} Consider the same setup as the previous problem: \n\\beqn\n\\X = \\twovec{X_1}{X_2} \\sim p_{\\X}(\\x), ~~ T := X_1 + X_2 \\sim p_{T}(t),  ~~\nX_1 \\sim p_{X_1}(x) := \\begin{cases}\n5 \\withprob 0.2 \\\\\n10 \\withprob 0.8\n\\end{cases}  \\text{independent of} ~~\n%\nX_2 \\sim p_{X_2}(x) :=\\begin{cases}\n-5 \\withprob 0.1 \\\\\n-10 \\withprob 0.9\n\\end{cases}\n\\eeqn\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{10} \n\n\\begin{enumerate}[(a)]\n%\\setcounter{enumi}{3}\n\\item $T \\sim \\text{Deg}(0)$\n\\item $T \\sim \\binomial{2}{p}$ where $p$ can be computed from $p_{X_1}(x)$ and $p_{X_2}(x)$\n\\item $\\support{T} = \\braces{-10, -5, 5, 10}$\n\\item $p_{X_1}(x) = 0.2 \\indic{x = 5} + 0.8 \\indic{x = 10}$\n\\item $p_{X_1}(x) = 5 \\indic{x = 0.2} + 10 \\indic{x = 0.8}$\n\\item $p_{T}(t) = 0.2 \\indic{t = 5} + 0.8 \\indic{t = 10} + 0.1 \\indic{t = -5} + 0.9 \\indic{t = -10}$\n\\item $p_{T}(0) = p_{\\X}(0, 0)$\n\\item $p_{T}(0) = p_{\\X}(5, -5) + p_{\\X}(10, -10)$\n\\item $p_{T}(0) = p_{X_1}(5) + p_{X_2}(-5) + p_{X_1}(10) + p_{X_2}(-10)$\n\\item $p_{T}(0) = 0.74$\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n\\problem\\timedsection{8} These are questions about rv's we studied in class. Consider $X_1, X_2, X_3, \\ldots \\iid \\bernoulli{p}$.\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{9} \n\n\\begin{enumerate}[(a)]\n%\\setcounter{enumi}{3}\n\\item $X_1 + X_{17} \\sim \\binomial{17}{p}$\n\\item $X_1 + X_{17} \\sim \\binomial{2}{p}$\n\\item $X_1 + X_2 + X_3 + \\ldots$ is a geometric rv\n\\item $X_1 + X_2 + X_3 + \\ldots$ is a negative binomial rv\n\\item $\\bracks{X_1~ X_2~ X_3}^\\top$ is a multinomial rv\\\\\n\nLet $T_n := \\sum_{i=1}^n X_i$ where $n \\in \\naturals$\n\n\\item $T_n \\sim \\binomial{n}{p}$\n%\\item $T_n + T_n \\sim \\binomial{2n}{p}$\n\\item $T_n$ will be approximately distributed as a Poisson($np$) rv if $n$ is large and $p$ is small.\\\\\n\nLet $Y$ be the rv that counts the number of $X_t$'s that are realized to be zero before the first $X_t$ that is realized to be one i.e. $Y = \\min{t\\,:\\, X_t = 1} - 1$. \n\\item $Y$ is a geometric rv\n\\item Given that $Y = 4$, then $X_3$ is degenerate.\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%\\beqn\n%\\lim_{\\sigma \\rightarrow 0} POW(\\theta_0, \\theta_a, n, \\sigma, \\alpha) = \\lim_{\\sigma \\rightarrow 0} \\parens{1 - \\Phi\\parens{-\\frac{\\sqrt{n}}{\\sigma} (\\theta_a - \\theta_0) + z_{1 - \\alpha}}} = 1 - \\lim_{\\sigma \\rightarrow 0} \\parens{\\Phi\\parens{-\\frac{\\sqrt{n}}{\\sigma} (\\theta_a - \\theta_0) + z_{1 - \\alpha}}} = 1 - 0 = 1\n%\\eeqn\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\problem\\timedsection{7} Consider $X_1, X_2, X_3, \\ldots \\iid \\geometric{p}$. Let $T_n := \\sum_{i=1}^n X_i$ and $T_m := \\sum_{i=n+1}^{n+1+m} X_i$ where $n, m \\in \\naturals$.\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{7} \n\n\\begin{enumerate}[(a)]\n\\item $\\support{X_1} = \\support{X_1 + X_2}$\n\\item $T_n \\sim p_{T_n}(t) = p^2 \\sum_{x=0}^\\infty (1-p)^x (1-p)^{t-x} \\indic{t-x \\in \\braces{0,1,2,\\ldots}}$\n\\item $T_n \\sim p_{T_n}(t) = p^2 \\sum_{x=1}^\\infty (1-p)^x (1-p)^{t-x} \\indic{t-x \\in \\braces{1,2,\\ldots}}$\n\\item $T_n + T_n \\sim \\negbin{2n}{p}$\n\\item $T_m \\sim \\negbin{m}{p}$\n\\item $T_m \\sim \\negbin{n+m}{p}$\n\\item $T_n + T_m \\sim \\negbin{n+m}{p}$\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\problem\\timedsection{6} Let $X_1, X_2, \\ldots, X_n \\iid \\poisson{\\lambda}$, $T_n := \\sum_{i=1}^n X_i$ and $\\X = \\bracks{X_1 ~ X_2 ~ \\ldots~ X_n}^\\top \\sim p_{\\X}$.\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{9} \n\n\\begin{enumerate}[(a)]\n\\item $p_{X_1}(x) = \\frac{\\lambda^x e^{-\\lambda}}{x!}$\n\\item $p_{X_1}(x) = \\frac{\\lambda^x e^{-\\lambda}}{x!} \\indic{x \\in \\braces{1,2, ...}}$\n\\item $p_{X_1}(x) = \\frac{\\lambda^x e^{-\\lambda}}{x!} \\indic{x \\in \\braces{0,1,2, ...}}$\n\\item $p_{\\X}(\\x) = \\displaystyle\\prod_{i=1}^n \\displaystyle\\frac{\\lambda^{x_i} e^{-\\lambda}}{x_i!} \\indic{x_i \\in \\braces{0,1,2, ...}}$\n\\item $T_n \\sim \\poisson{n\\lambda}$\n\\item $T_n \\sim \\poisson{\\lambda / n}$\n\\item $T_n \\sim \\poisson{\\lambda}$\n\\item As $n \\rightarrow \\infty$, $T_n$ becomes more and more degenerate\n\\item As $n \\rightarrow \\infty$, $T_n$ becomes more and more like a $\\binomial{n}{\\lambda / n}$\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\problem\\timedsection{10} Consider a bag of marbles with 5 red marbles, 4 green marbles, 6 blue marbles and 3 purple marbles. You sample (pick) 19 marbles from the bag by picking one at a time, recording its color and then putting that marble bag into the bag. Let $X_1$ count the number of red marbles in your sample, let $X_2$ sample the number of green marbles in your sample, let $X_3$ sample the number of blue marbles in your sample and let $X_4$ count the number of purple marbles in your sample. Let $\\X = \\bracks{X_1 ~ X_2 ~ X_3~ X_4}^\\top \\sim p_{\\X}$.\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{11} \n\n\\begin{enumerate}[(a)]\n\\item $p_{\\X}(\\x) = p_{X_1}(x_1) p_{X_2}(x_2) p_{X_3}(x_3) p_{X_4}(x_4)$\n\\item $X_1$ is a binomial rv with $n = 19$\n\\item $X_1 + X_2 + X_3 + X_4$ is degenerate\n\\item $\\X \\sim \\multinomial{4}{18}{\\oneover{19}\\bracks{5 ~4 ~6 ~3}^\\top }$\n\\item $\\X \\sim \\multinomial{4}{19}{\\oneover{18}\\bracks{5 ~4 ~6 ~3}^\\top }$\n\\item $\\X \\sim \\multinomial{18}{19}{\\oneover{4}\\bracks{5 ~4 ~6 ~3}^\\top }$\n\\item $p_{\\X}(9,2,2,6) = \\oneover{18^4}\\binom{19}{9,2,2,5} 5^6 4^2 6^2 3^2$\n\\item $p_{\\X}(9,2,2,0) = \\oneover{18^4}\\binom{19}{9,2,2} 5^6 4^2 6^2$\n\\item $p_{\\X}(9,2,0,0) = \\oneover{18^4} \\frac{19!}{2!} 5^6 4^2 $\n\\item $p_{\\X}(19,0,0,0) = \\oneover{18^4} \\frac{19!}{19!} 5^{19}$\n\\item Given $X_1 = 3$ and $X_2 = 1$, $\\bracks{X_3~X_4}^\\top$ is a multinomial rv with $K=2$.\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\problem\\timedsection{8} Consider the same situation as the previous problem: \\ingray{a bag of marbles with 5 red marbles, 4 green marbles, 6 blue marbles and 3 purple marbles. You sample (pick) 19 marbles from the bag by picking one at a time, recording its color and then putting that marble bag into the bag. Let $X_1$ count the number of red marbles in your sample, let $X_2$ sample the number of green marbles in your sample, let $X_3$ sample the number of blue marbles in your sample and let $X_4$ count the number of purple marbles in your sample.} Thus, $\\X = \\bracks{X_1 ~ X_2 ~ X_3~ X_4}^\\top \\sim p_{\\X} = \\multinomial{4}{19}{\\oneover{18}\\bracks{5 ~4 ~6 ~3}^\\top}$.\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{8} \n\n\\begin{enumerate}[(a)]\n\\item $\\expe{X_1} = 5/19$\n\\item $\\expe{X_1} = 19 \\times 5/18  $\n\\item $\\expe{X_2 + X_3} = 19 \\times 5/18 + 19 \\times 4/18 $\n\\item $\\expe{X_2 + X_3} = 19 \\times 6/18  + 19 \\times 4/18  $ \\\\\n\nLet $\\c = [1 ~ 2 ~ 3 ~ 4]^\\top$ i.e. a 4-dimensional column vector of constants.\n\n\\item $\\expe{\\c + \\X} = \\frac{19}{18}\\bracks{1 \\times 5 ~~~ 2 \\times 4 ~~~ 3 \\times 6 ~~~ 4 \\times 3}^\\top$\n\\item $\\expe{\\c + \\X} = \\frac{19}{18}(1 \\times 5 + 2 \\times 4 + 3 \\times 6 + 4 \\times 3)$\n\n\\item $\\expe{\\c^\\top \\X} = \\frac{19}{18}\\bracks{1 \\times 5 ~~~ 2 \\times 4 ~~~ 3 \\times 6 ~~~ 4 \\times 3}^\\top$\n\\item $\\expe{\\c^\\top \\X} = \\frac{19}{18}(1 \\times 5 + 2 \\times 4 + 3 \\times 6 + 4 \\times 3)$\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\problem\\timedsection{11} Consider the same situation as the previous two problems: \\ingray{a bag of marbles with 5 red marbles, 4 green marbles, 6 blue marbles and 3 purple marbles. You sample (pick) 19 marbles from the bag by picking one at a time, recording its color and then putting that marble bag into the bag. Let $X_1$ count the number of red marbles in your sample, let $X_2$ sample the number of green marbles in your sample, let $X_3$ sample the number of blue marbles in your sample and let $X_4$ count the number of purple marbles in your sample. Thus, $\\X = \\bracks{X_1 ~ X_2 ~ X_3~ X_4}^\\top \\sim p_{\\X} = \\multinomial{4}{19}{\\oneover{18}\\bracks{5 ~4 ~6 ~3}^\\top}$.}\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{11} \n\n\\begin{enumerate}[(a)]\n\\item $\\var{\\X}$ is a symmetric and diagonal matrix\n\\item $\\cov{X_1}{X_2 + X_3} = 2\\cov{X_1}{X_2}$\n\\item $\\cov{X_1}{X_2 + X_3} = -19 (50) / 18^2$\n\\item $\\var{[1~1~1~1] \\X} = 0$\n\\item $\\var{[1~1~1~1] \\X} = [1~1~1~1] \\var{\\X} [1~1~1~1]^\\top$\n\\item $\\var{\\X} = \\displaystyle\\frac{19}{18^2}\\bracks{\\begin{array}{cccc} \na & e & f & g \\\\\ne & b & h & i \\\\\nf & h & c & j \\\\\ng & i & j & d\n\\end{array}}$ where $a, b, c, d, e, f, g, h, i, j$ are integers.\n\\item $\\var{\\X}$ is the matrix in the previous question and $e, f, g, h, i, j$ are negative integers.\n\\item $\\var{\\X}$ is the matrix in the previous question and $g = -15$.\n\\item $\\var{\\X}$ is the matrix in the previous question and $b = -60$.\n\\item The number of red marbles minus the number of purple marbles has variance $\\frac{19}{18^2}(5 \\times 14 + 2 (5 \\times 3) + 3 \\times 16)$\n\\item The number of red marbles minus the number of purple marbles has variance $\\frac{19}{18^2}(5 \\times 14 - 2 (5 \\times 3) + 3 \\times 16)$\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\end{document}", "meta": {"hexsha": "808abb6efd0975f3e08803d9b01994f712eb4fad", "size": 13872, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "exams/midterm1/midterm1.tex", "max_stars_repo_name": "kapelner/QC_Math_621_Fall_2020", "max_stars_repo_head_hexsha": "f71dc4901d46c4aaaea3ef4795a22046e754bb11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-08-25T01:46:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T01:21:21.000Z", "max_issues_repo_path": "exams/midterm1/midterm1.tex", "max_issues_repo_name": "kapelner/QC_Math_621_Fall_2020", "max_issues_repo_head_hexsha": "f71dc4901d46c4aaaea3ef4795a22046e754bb11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exams/midterm1/midterm1.tex", "max_forks_repo_name": "kapelner/QC_Math_621_Fall_2020", "max_forks_repo_head_hexsha": "f71dc4901d46c4aaaea3ef4795a22046e754bb11", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-09-02T18:47:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-17T19:42:31.000Z", "avg_line_length": 50.0794223827, "max_line_length": 873, "alphanum_fraction": 0.6462658593, "num_tokens": 5407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.33971055063006994}}
{"text": "\\chapter{High Performance Si Immersion Gratings Patterned with Electron Beam Lithography} \n\\label{chap_ebeam}\n\n\\section{INTRODUCTION}\n\\label{sec:intro}  % \\label{} allows reference to this section\n\nAt the 2012 SPIE Astronomical Telescopes and Instrumentation meeting (volume 8450) we described the detailed performance of the immersion grating (part number CA-1a \\cite{2012SPIE.8450E..2SG}) for the high resolution infrared spectrograph IGRINS \\cite{2010SPIE.7735E..54Y}.  IGRINS saw first light at McDonald Observatory in March 2014.  Papers describing its performance appear in the current volume\\cite{2014SPIE.CHANPARK.IGRINS,2014SPIE.9151E..1GB}.  The technical readiness of the immersion grating now rests on firm footing, and our group has now moved on to pushing the performance and design limitations of silicon diffractive optics.  The key limitation is phase coherence.  Phase coherence for a diffraction grating is the accuracy to which repeated grating facets are positioned to an integer multiple of $\\sigma$, the groove constant (the desired constant spacing from groove to groove).  Specifically, the position, $x$ of the $n^{th}$ facet in a sequence of $N$ total facets is distributed as: \n\n\\begin{eqnarray}\nx_n = n\\sigma + \\epsilon_n  \\label{eqn:Epsilon}\n\\end{eqnarray}\n\nwhere $\\epsilon_n$ is the position error for facet $n$.  Discussion of the phase performance can be broadly separated by the correlations  of errors, $\\epsilon_n$, and their impact on the monochromatic spectral purity.  \n\n\nThere are large scale, smooth correlations:\n\\begin{eqnarray}\n\\epsilon_n = \\epsilon_n(x, y) \\label{eqn:smooth}\n\\end{eqnarray}\nThese errors manifest as low order optical aberrations and degrade the PSF and Strehl.  Operationally these smooth errors correspond to the first $M$ Zernike polynomials in an orthonormal expansion of the wavefront, where $M < 200$.  There is the especially pernicious repetitive error:\n\\begin{eqnarray}\n\\epsilon_n = A\\sin{\\frac{2\\pi n\\sigma}{P} - \\phi} \\label{eqn:Periodic}\n\\end{eqnarray}\nwhere $n\\sigma$ is the desired position of the $n^{th}$ groove, $A$ is the amplitude of the error (e.g. in nm), and $P$ is the period of the error (e.g. in mm).  These errors manifest as sidelobes of the PSF called Rowland ghosts.  Although we have listed a single harmonic periodic error, any periodic structure can be broken into its Fourier components, so each of these Fourier components will be affiliated with a sidelobe Rowland ghost.  Lastly there are small scale random errors:\n\\begin{eqnarray}\n\\epsilon_n \\sim \\mathcal{N}(0, c)\n\\end{eqnarray}\nwhere $ \\sim \\mathcal{N}(0, c)$ denotes that the error is normally distributed with mean zero and standard deviation $c$.  This last type of error produces so-called spectral grass\\cite{2007ApOpt..46.3400M}, which is scattered light filling the blaze.\n\n\\section{On-sky performance of Si immersion grating}\n\nWith the commissioning of IGRINS \\cite{2010SPIE.7735E..54Y}, we have demonstrated that the immersion grating performance measured in the laboratory translates into performance in a real world instrument in the field.  IGRINS is a high resolution near-infrared astronomical spectrograph.  It employs an immersion grating as its primary dispersive element, and two cryogenic VPH gratings for cross-dispersion.  The instrument covers a wavelength range of 1.5$-$2.5 $\\mu$m in two channels.  The design and early performance of IGRINS is described in this volume [talk 9147-48]\\cite{2014SPIE.CHANPARK.IGRINS}.  The immersion grating for IGRINS is internal part number CA-1a.  Its lab-measured performance is summarized in Gully-Santiago et al. 2012\\cite{2012SPIE.8450E..2SG}.\n\nIGRINS has no measured performance limitation attributable to the immersion grating.  CA-1a is diffraction limited.  CA-1a has been thermally cycled $>10$ times at the time of writing, with no perceptible degradation in performance.  We expect no degradation from thermal cycling.  We have previously constrained the CA-1a blaze angle to $\\delta = 71.5\\pm 0.2^\\circ$.  The overall instrument throughput is consistent with the expected throughput including the laboratory-measured diffraction efficiency of CA-1a.\n\nOne major open question is whether CA-1a meets its spectral ghost level specification.  Spectral ghosts are secondary images that arise from periodic facet positioning errors\\cite{2007sdf..book.....J}. The ghosts in CA-1a where introduced from a cyclically varying position-dependent exposure dose in the UV photolithography patterning step.  The processing error causing the ghosts has since been eliminated.  As a result our most recent immersion grating prototypes show a dramatic reduction in high frequency spectral ghosts [this volume, talk number 9151-35]\\cite{2014SPIE.9151E..1GB}.  The ghost level depends on the amplitude of the error (cf. Equation 14 of Marsh et al. 2007\\cite{2007ApOpt..46.3400M}):\n\\begin{eqnarray}\n\t\\frac{I_g}{I_0}=[ \\frac{2\\pi n}{\\lambda}A \\sin{\\delta} ]^2\t \\label{eqn:GLevel}\n\\end{eqnarray}\nwhere $I_g/I_0$ is the ghost level relative to the main peak, $\\lambda/n$ is the wavelength scaled in the refractive index, and $A$ is defined in Equation \\ref{eqn:Periodic}.  We predicted an in-immersion ghost level of $I_g/I_0 \\sim2\\times10^{-3}$ at 1.5 $\\mu$m based on visible laser metrology\\cite{2012SPIE.8450E..2SG}.  At the time of writing the IGRINS commissioning team has constrained ghost levels at $\\lambda=1.5 \\; \\mu$m to $I_g/I_0 < 1\\times10^{-2}$.  The limitation of a direct ghost level measurement is the need to deconvolve the slit diffraction ringing from the spectral point spread function.\n\n\\section{Motivations for direct writing Si immersion gratings}\nWe have determined experimentally that the lithographic transfer step is the most important determinant of the optical quality of Si immersion gratings.  The prior steps: orienting, polishing, passivating and resist-coating the monolithic substrates is now routine and our process control for these steps is sufficient to limit their contribution to the error budget to the point where they have no effect on the quality of the final gratings\\cite{2007ApOpt..46.3400M,2014SPIE.9151E..1GB}.  The subsequent steps: development of the resist, reactive ion etching of the passivation layer, and anisotropic etching of the V-grooves similarly contribute little to the overall errors.  We therefore concentrate our efforts on finding more effective and accurate ways to carry out the transfer or patterning step.  \n\nThe JPL Microdevices Laboratory has an advanced electron beam writer (a JEOL model 9300FS) and has made an extensive effort to understand the nuances of using this device for precision patterning of small features over large spatial scales.  For the large-area immersion grating exposures we use the JEOL 9300FS at 100 kV accelerating voltage with 60 nA current, a spot size $\\sim 100-150$ nm and spot step spacing of 50 nm. Our typical groove frequency for echelle grating prototypes is 40 - 12.5 grooves/mm (25-80 $\\mu$m groove spacing) but groove frequencies higher than 1000 grooves/mm are possible. Experimental pattern sizes are up to 100 mm $\\times$ 40 mm, but could be as large as 200 mm diameter.\n\n\\subsection{Motivation \\#1: Higher precision than contact lithography}\n\\label{sec:Precis}\nElectron beam lithography is more precise than contact lithography.  One figure of merit for precision in e-beam lithography is the \\emph{spot size}, the typical diameter of the Gaussian e-beam current distribution at the location of the e-beam sensitive resist on the substrate surface.  E-beam spot sizes on the JEOL 9300FS tool can be as low as 4 nm at low currents (less than 1 nA).  To expose the required immersion spectrometer grating areas in reasonable times ($\\sim$50 hours), tens of nA of current are needed, and $\\sim 100 - 150$ nm spot sizes are typical.  The final precision is a small fraction of the spot size, since many adjacent spots are convolved together.  In later sections we directly compare the performance of immersion gratings produced with e-beam and contact lithography to show evidence that we have achieved much higher precision in e-beam lithography.  \n\n\\subsection{Motivation \\#2: Finer groove pitch capability}\nOwing to its small achievable spot size, electron beam lithography can reach finer groove spacings than contact photolithography can.  Fine pitches are required for high dispersion in low order.  Our group is currently designing a fine pitch ($\\sigma \\; \\sim$ 2 $\\mu$m, line frequency $\\sim 500$ lines/mm) pattern immersion grating for the NASA Earth Science Technology Office (ESTO) Advanced Component Technologies (ACT) program.  The ACT mission concept requires high spectral resolution at low order ($\\sim1-10$).  The desired first and second order gratings cannot be made with contact lithography.  Higher order devices can be made with contact lithography, but suffer from order overlap and reduced bandwidth.\n\n\n\\section{e-beam patterning strategies}\nE-beam patterning takes place within a hierarchy of increasing scale-sizes.  The relationships of these pattern scale sizes affect the relative power distributed among spectral and spatial scales in the delivered monochromatic PSF.\n\n\\subsection{e-beam patterning scale size hierarchy}\n\n\\begin{figure}\n\\begin{center}\n \\begin{tabular}{c}\n    \\includegraphics[width=0.8\\textwidth]{chSPIE_2014_ebeam/figs/Field_sizes_cascade_02.png}\n   \\end{tabular}\n  \\end{center}\n  \\caption[e-beam Hierarchy]{\\label{fig:Hierarchy} Hierarchy of e-beam pattern scale sizes- in the left panel the grooves are black and the fields are thin blue lines, the middle inset shows subfields, and the right inset shows spots at a regular step spacing, though the spots are not to scale.  Spot sizes are typically about 2-3 times their spacing.}\n\\end{figure}\n\n\nThere are a five key pattern scale sizes in e-beam lithography.  These scales are typical among e-beam tools, though we focus our discussion to the scales relevant to the JEOL 9300FS.  The scale sizes in order of small to large scales are 1) step size, 2) spot size, 3) subfield deflector size, 4) field deflector size, and 5) stage range of motion.  Figure \\ref{fig:Hierarchy} shows a cartoon of the hierarchy from left to right- field, subfields, and steps.\n\nTable \\ref{tab:D07andE12} lists the pattern size scales for two immersion grating prototypes, parts D07 and E12.  These prototypes are examples of successful pattern designs.  D07 and E12 were both patterned on 10 mm thick Si pucks.  A 10 mm thickness is sufficient for the piece to maintain its flatness after anisotropic etching of the grooves so that interferometric measurements will reflect accurately the effectiveness of the patterning step.\n\n\\begin{table}\n\t\\begin{center}\n\t\\caption{D07 and E12 e-beam pattern details. \\label{tab:D07andE12}}\n\t\\begin{tabular}{ccc}\n\t\\toprule\n\t   &D07 & E12  \\\\\n\t\\midrule\n\tsubstrate bias angle ($^\\circ$) & 6.1 & 71.5 \\\\\n\tpattern size (mm) & 39.0 x 39.664 & 29.696 x 84.816 \\\\\n\tpitch ($\\mu$m) & 7.8 & 27.36 \\\\\n\tline frequency (lines/mm) & 128.2 & 36.55 \\\\\n\ttop width ($\\mu$m) & 0.4 & 9.96 \\\\\n\tline width ($\\mu$m) & 7.4 & 17.40 \\\\\n\tstep size (nm) & 50 & 50 \\\\\n\tsteps per linewidth & 148 & 348 \\\\\n\tsubfield size ($\\mu$m) & 3.7 & 2.9 \\\\\n\tsubfields per linewidth & 2 & 6 \\\\\n\tsteps per subfield & 74 & 58 \\\\\n\t\\cline{1-1}\n\t \t\t\t      & 63: 491.4  & 17: 465.12 \\\\\n\tgrooves per $x-$field and & 61: 475.8 & 15: 410.4 \\\\\n\t$x-$field sizes ($\\mu$m) & 59: 460.2 & 13: 355.68 \\\\\n\t \t\t\t\t        & 55: 429.0 & 11: 300.96 \\\\\n\t\\cline{1-1}\t\t\t\t\t        \n\t \t\t\t      & 134: 495.8  &   \\\\\n\tsubfields per $y-$field and & 133: 492.1 &   \\\\\n\t$y-$field sizes ($\\mu$m) & 131: 484.7 & 160: 464.0 \\\\\n\t \t\t\t\t        & 127: 469.9 &   \\\\\t\n\t\\cline{1-1}\n\t\\bottomrule\n\t\\end{tabular}\n\t\\end{center}\n\\end{table}\t\n\n\n\\subsubsection{e-beam step size and spot size}\nThe e-beam step size is the center-to-center separation of the e-beam spots, controlled by the beam-deflection electronics of the writer.  Step sizes can range from roughly 2 to 100 nanometers.  We adopted a 50 nm step size for our immersion grating patterns.  The rationale for the step size depends on understanding the e-beam spot size.  \n\nThe spot size controls the smallest achievable feature size.  Our spot size of $\\sim 100 - 150$ nm is determined by operational properties of the electron gun and focusing column.  The spot size can be decreased by preferentially removing those electrons with large velocity components perpendicular to the bulk direction of motion.  This preferential removal of fast electrons is achieved with a grounded conductive circular aperture in the beam path prior to the spot formation.  The aperture is constricted to reduce the spot size.  The net current (e$^-$/s) consequently decreases, since the aperture has effectively thrown away electrons.  So there is a tradeoff between current and spot size.  This tradeoff is important in deciding optimal patterning strategies and sizes.  The economical need to limit the expensive e-beam write time necessitated a high current and hence the resulting large spot size.\n\nThe conductive aperture setting coarsely selects the range of spot size achievable, while the detailed spot size depends on fine adjustments made to the e-beam column before an exposure.  These adjustments are familiar for those who have used scanning electron microscopy- astigmatism, wobble, and focus, for example.  Poor calibration might deliver an elliptical, asymmetric spot shape.  In practice, a slightly asymmetric spot shape does not affect the performance of immersion gratings.\n\nA key idea is that the step size (50 nm) is much smaller than the spot size so that adjacent steps convolve to form a fairly uniform exposure area.  Another key assumption is that the e-beam spot does not change significantly over the course of an exposure.  We expect that the e-beam spot is unchanged, so long as the e-beam column is unperturbed.\n\n\\subsubsection{Subfield deflector}\nThe subfield deflector is a component of the e-beam gun that directs the e-beam spot within a box of up to 4 $\\mu$m $\\times$ 4 $\\mu$m, centered around a mean position set by the main field deflector.  For example we chose subfield sizes of 3.7 and 2.9 $\\mu$m for D07 and E12, respectively.  For recent work on fine pitch ($\\sim2\\; \\mu$m) gratings we have experimented with smaller subfield sizes.  The reason for these choices of subfield sizes of D07 and E12 is that these field sizes result in an integer number of subfield per linewidth, which avoids fractional e-beam spots at the boundaries.  Subfield boundaries are perceptible in the intentionally underexposed e-beam resist of sample TJ04, depicted in Figure \\ref{fig:TJ04Zeiss}.  In general we have found subfield stitching boundaries do not cause measurable ghosts unless the choice of subfield size results in fractional spots at the subfield/field boundaries.  \n\n\\subsubsection{Field deflector}\n\\label{sec:Field}\nThe field deflector, also sometimes called the main-field deflector, coarsely redirects the electron beam over a square up to 500 $\\mu$m in size.  The main-field deflector positions the center of the subfields.  For example, the choice of a 500 $\\mu$m square field size and 4 $\\mu$m square subfield size would result in 125 $\\times$ 125 subfields.\n\nThe fields are stitched together by the interferometrically controlled stage that steps between them once each field's pattern has been written.  The stage move speed is typically much slower than the field and subfield deflector speed, so small field sizes are inefficient in time-on-target compared to wall-clock time.  Even though the JEOL 9300FS dynamically corrects for beam position distortion (e.g. pincushion) and spot focus and astigmatism, the writing performance degrades slightly with distance from the center of the field.  So there is a tradeoff between write speed and performance.  \n\nThe choice of field size is multifaceted.  Field size choice is one of the key strategies for mitigation of ghosts (see Section \\ref{sec:Ghosts}).\n\n\\begin{figure}\n\\begin{center}\n \\begin{tabular}{c}\n    \\includegraphics[width=0.96\\textwidth]{chSPIE_2014_ebeam/figs/subfields_TJ04_Zeiss.pdf}\n   \\end{tabular}\n  \\end{center}\n  \\caption[TJ04 under Zeiss]{\\label{fig:TJ04Zeiss} Subfield and field boundaries directly perceptible in optical microscopy of the e-beam resist on an intentionally underexposed sample, TJ04.  The groove pitch for this sample is 100 $\\mu$m, with a 75 $\\mu$m written linewidth.  The blue area is the linewidth portion of the grating which has e-beam resist already exposed to e-beam.  The orange line is the groove top, where the e-beam resist was unexposed and would have served as the wet etch dam, had the linewidth actually developed out.  The minute color differences within the exposed linewidth are attributable to tiny thickness differences of the resist, which originate from tiny differences in delivered e-beam dose.  The cylindrically symmetric color difference of teal to dark blue is attributable to the proximity effect as described elsewhere\\cite{2005SPIE.5720...68W}.  The tiny boxes are subfields, which are only perceptible due to subtle subfield stitching errors.  Some subfields are more errant than others.  The thick horizontal stripe is a portion of a much larger field boundary, perceptible only because of main-field deflector stitching boundaries as discussed in the text.}\n\\end{figure}\n\n\\subsubsection{Interplay of hierarchy at boundaries and design rules}\n\\label{sec:Boundaries}\nUndesirable repetitive patterns that can cause ghosts arise when there are discontinuities as one steps up the field hierarchy.  The e-beam spots, subfields, and fields must match up at the boundaries.  We learned many subtle design rules unique to high performance immersion gratings.  The main theme in all of the design rules is to avoid fractional steps in the writing process.  The JEOL pattern generation software inserts patterns of spaces and spots when it reaches a command for a fractional step.  The specific design rules below are probably unique to the JEOL pattern generation software.  Other e-beam tool software is likely to have different design rules, but the general principle is the same.  \n\\begin{enumerate}\n  \\item Subfields must be an integer number of steps\n  \\item Fields should be an integer number of subfields.  \n  \\item Linewidth should be an integer number of subfields.\n  \\item Field sizes and linewidths can be non-integer number of subfields only if the remainder fractional subfield plus one subfield divided by two is an integer number of step sizes.\n\\end{enumerate}   \n\nThese rules ensure that all e-beam spots are equidistant.  Figure \\ref{fig:Hierarchy}  shows the JEOL \\emph{shot shape display} of a pattern that broke rules 2 and 4.  Metrology of a grating prototype that broke rules 2 and 4 resulted in cross-dispersion grating ghosts $>10^{-3}$.  The line-edge of contiguous spots lacked a solitary spot near the subfield boundary.  Such a periodic dearth in exposure manifested as a periodic divot along the length of the groove.  The detailed impact on optical phase depends on the relative step size, e-beam sensitive resist contrast, and sundry subsequent processing steps.  Rather than risk a performance degradation it is best practice to avoid the formation of subfield blips in the first place.  The main concern for a final application is probably scattered light, and not efficiency loss. \n\n\n\\subsection{Predicting the ghost level associated with field positioning errors}\n\\label{sec:Ghosts}\n\nThe field size is only a few times larger than our typical coarse echelle grating groove constants.  Figure \\ref{fig:FieldCartoon} shows an exaggerated cartoon of the field size relative to grooves.  In a hypothetically perfect e-beam field stitch, the line positions are exactly as desired.  In reality there is some finite distortion, which is repeated each time the field is written into the e-beam resist.  We define the ratio, $G$, as the field size, $F$, divided by the groove pitch size, $\\sigma$.  For example, there will be $G=500/100=5$ grooves per field for $\\sigma = 100 \\; \\mu$m and $F = 500 \\; \\mu$m.  The omnipresent field deformations will be imprinted into each field, repeating every 5 grooves.  The cyclically varying facet positions manifest as ghosts with G-fold symmetry. We expect $G-1$ inter-order ghosts, separated by a fraction $1/G$ of the inter-order separation.\n\n\n\\begin{figure}\n\\begin{center}\n \\begin{tabular}{c}\n    \\includegraphics[width=0.6\\textwidth]{chSPIE_2014_ebeam/figs/Field_stitching_errors_alt2.pdf}\n   \\end{tabular}\n  \\end{center}\n  \\caption[Field Stitching Error Cartoon]{\\label{fig:FieldCartoon} An exaggerated cartoon to demonstrate the repetitive nature of field stitching.  A typical field size is about 300-500 $\\mu$m on a side, and typical groove periods, $\\sigma$, are about 20-100 $\\mu$m (50-10 lines/mm groove frequencies).  Here we show 5 grooves per field.  The distortion shown in the cartoon is highly exaggerated, and in reality the calibration is much, much better than depicted.  The center positions in the distorted fields are distributed around the target, demonstrating field stitching errors.  The actual morphology of the distortion is not well characterized and should be mostly corrected by the 9300FS dynamic distortion correction system.  We have depicted a pincushion shape, though the realized morphology could be more like barrel distortion or a parallelogram.  The fields could also be perfectly square and simply misplaced in their center positions, still causing errors.  The details of the morphology give rise to differing relative levels of harmonics, in a Fourier sense.  To put the scale in perspective, we coarsely estimate the repetitive position error amplitude A (cf. eq. \\ref{eqn:Periodic}) as about 5-50 nm from experiments on e-beam wafers.  Compare this minuscule position error with the $\\sim500 \\; \\mu$m field size, to see that the fractional position error is 1 part in $10^4$ or better.}\n\\end{figure}\n\nIn principle it is possible to predict the ghost levels relative to the main diffraction peak, given some information about the magnitude and shape of the field distortion.  As the amplitude of the field distortion is dialed up, the grating ghost level increases approximately as Equation \\ref{eqn:GLevel}.  In practice, we have not directly mapped the field distortion, which we expect to be a function of both $x $ and $y$.\n\n\\subsection{Employ multiple field sizes rather than one field size}\n\\label{sec:MultipleFields}\nThere are two strategies for mitigating ghosts.  One is to reduce the overall power in ghosts, using a single field size.  The other is to redistribute the power into different spatial scales, by using a variety of field sizes.  The strategies can be combined.\n\nWe redistribute the field power into several different spatial scales following the method described in Wilson et al. 2005\\cite{2005SPIE.5720...68W}.  Rather than use a single field size, say 500 $\\mu$m, we break up the field into several fields, say 500, 450, 400, and 350 $\\mu$m.  We array the fields on the pattern in the following way.  We divide up the overall grating pattern, for example 30 mm $\\times$ 85 mm, into eight long thin stripes of 3.75 mm $\\times$ 85 mm.  We then array the long thin stripes on top of each other, cycling through the patterns twice.  So if we have patterns A, B, C, D, with unique field sizes, we cycle through from top to bottom: A, B, C, D, A, B, C, D.  The reason for this periodic boundary condition is to make sure that the circular beam samples the patterns in roughly equal proportions.  Specifically, if we had simply written four arrays of dimension 7.5 mm $\\times$ 30 mm, indexed as A, B, C, D, then the circular beam would underfill patterns A and D at the bottom and top.  The optimal strategy would probably be to randomly array fields, but in practice randomly arraying is non-trivial in existing software.\n\nOne way to reduce the overall power in a single field size is to select a small field size, say $F=$ 200 $\\mu$m.   We know that the e-beam field performance is better in the center, and deviates towards the edge of the field.  The tradeoff with this strategy is that the stage move time is long compared to the e-beam field deflector time, so the write duration increases.  Another strategy for reducing the power in ghosts attributable to a single field size is to improve the intra-field calibration.   We could remove, for example, the minute pincushion or barrel distortion familiar from cathode ray tube computer monitors.  In practice it is tricky to measure, and therefore correct for, these minuscule distortions.  The absolute best way to eliminate inter-order ghosts is to use a field size equal to the pitch.  The choice of $F= \\sigma$ is generally cost prohibitive for $\\sigma <100$.  If long, inefficient write times can be tolerated, then in principle there is no limit to this strategy.  It is conceivable that driving the stage so much would make the stage fail over time.\n\nAnother strategy for reducing the overall power in spatial distortions of e-beam fields is to experimentally determine the optimal height offset for the e-beam focus.  For an unknown reason, the JEOL 9300FS selects a default writing height which is offset from the optimal height.  We experimentally verified an offset which reduces the overall distortion in the fields.\n\nLastly, there are some slightly obscure JEOL e-beam commands relevant to ghost mitigation.  These are the ``overlay'', ``gather'', and other affiliated commands.  The main idea behind these writing strategies is to re-write over a patch of grating so that it sees different portions of the field, and therefore the field distortions average down.  We experimented with these techniques but found that they roughly double the write times with negligible performance benefit.  \n\n\n\\subsection{Strategies for mitigating facet position errors attributable to large scale stage drift}\n\nThe largest scale in the e-beam writing hierarchy is the stage motion.  Multiple tests have never revealed significant wander or runout error in the interferometrically controlled stage.  Secular drift of the e-beam stage, however, can cause large-scale facet position errors which manifest as optical aberrations.\n\n\\subsection{Characterization of e-beam stage drift}\nWe characterized the e-beam stage drift with built-in JEOL commands.  Specifically, we used the \\emph{DRIFT} and \\emph{CURRENT} commands.  The \\emph{DRIFT} command checks the position of the stage by scanning a precision gold cross mark mounted to the stage.  The process ties the actual position to the predicted position to the precision of the stage mark's centroid, which is a small fraction of the spot size.  We measured a precision of about 15 nm in the centroid process.  Having determined the amplitude and direction of the drift, the \\emph{DRIFT} command subtracts out the offset and continues writing with its updated coordinates.\n\nThe centroiding \\emph{DRIFT} process can be automatically repeated on a desired frequency.  We set a frequency of 10 minutes.  For a typical 20 hour write we achieve 120 drift corrections.  The JEOL software logs these corrections, so we can reconstruct the path of the drift, had we not taken action to correct it.  Figure \\ref{fig:ebeamDrift} shows one of these reconstructions for sample E12.  The amplitude of the drift is  $\\Delta x = $ 206 nm and $\\Delta y = $ 341 nm.  This amplitude is much larger than we can tolerate for diffraction limited performance in immersion the near-IR.  \n\n\\begin{figure}\n\\begin{center}\n \\begin{tabular}{c}\n    \\includegraphics[width=0.4\\textwidth]{chSPIE_2014_ebeam/figs/E12_drift_ebeam.png}\n   \\end{tabular}\n  \\end{center}\n  \\caption[Drift amplitude]{\\label{fig:ebeamDrift} The reconstructed drift of the JEOL 9300FS e-beam stage during the patterning of sample E12.  The write time was 20.9 hours, with drift samples every 10 minutes.  The $x$ and $y$ components are separated and plotted as a function of time.  The top curve is the $y$ drift.  The curves begin at 0 at time zero, and show a range of motion of $\\Delta x = $ 206 nm and $\\Delta y = $ 341 nm.  This amplitude of drift would have been catastrophic for a grating which has line edge specifications of $\\lambda/10 \\sim 60 $ nm for diffraction limited performance in $J-$ band.  The JEOL9300FS command \\emph{DRIFT} automatically corrects out this drift, so the maximum realized drift is merely the minuscule difference that occurs over the 10 minute interval between corrections.  Figures \\ref{fig:E12igram} and \\ref{fig:E09igram} show a direct comparison of prototype gratings patterned with and without drift correction.}\n\\end{figure}\n\nA possible explanation for the beam drift is that there is thermal expansion attributable to heat conduction from the warm Si puck and holder unit into the stage.  Specifically, there is some evidence that the drift rate is largest at the beginning of the writing, perhaps while thermal equilibration is still happening.  The thermal probes on the stage lend some credibility to this idea, since the probes asymptote to constant value after a few hours.  Owing to this possibility, we recommend delaying the start of a write until the sample and holder have come into thermal equilibrium with the stage.  Beyond this thermal explanation, there are many conceivable reasons why there could be drift.  At some level we do not care, as long as we can correct it out sufficiently well.  The cost of correction is merely a hit in extended write time for the same written area, i.e. a decrease in efficiency.  We found roughly a 10\\% overhead associated with drift checking.\n\n\\section{Results: Test gratings produced with e-beam patterning}\n\n\\subsection{Measurement of ghost levels for a variety of writing strategies}\n\\label{sec:MeasGhost}\nIn Figure \\ref{fig:GhostLevelFig} we show measurements of inter order ghosts for different trial runs of the writing process with internal designations TJ03 and TJ04.  Each grating received a different treatment for e-beam field and/or subfield sizes.  The grating pattern details are listed in Table \\ref{tab:TJ04details}.  The first thing to notice is that virtually all ghosts are below 10$^{-3}$ of the main peak.  Some ghosts were expected but not detected (denoted ND in the plot legend).  The non-detections are probably related to instrumental limitations, though upper limits are not available.  \n\n\\begin{landscape}\n\n\\begin{table}\n\t\\caption{Wafer TJ04 pattern details.  \\label{tab:TJ04details}}\n\t\\begin{tabular}{lllcccccccccc}\n\t\\toprule\n\t &   & & \\multicolumn{10}{c}{Grating Area} \\\\\n\t\\cmidrule(l){4-13}\n\tSize Scale & & Unit & A  & B & C & D & E & F & G &  H &  I & J\\\\\n\t\\midrule\n\t\\multirow{2}{*}{Pattern length}& (x) & mm &  \\multicolumn{10}{c}{15} \\\\\n\t & (y) & mm & \\multicolumn{10}{c}{10} \\\\\n\tPitch && $\\mu m$ & \\multicolumn{6}{c |}{100} &\\multicolumn{4}{c}{25}  \\\\\n\tLinewidth && $\\mu m$ & \\multicolumn{6}{c |}{75} & \\multicolumn{4}{c}{22.5}  \\\\\n\t\\multirow{2}{*}{Field}&(x) & $\\mu m$ & 100 &  200 & 200 & 200 & 500 & Multi & 100 & 200 & 500 & Multi \\\\\n\t&(y)& $\\mu m$ & 500 & 500 & 100 & 250 &  500 & 500 & 500 & 500 &500 & 500\\\\\n\tSubfield && $\\mu m$ & 2.5 & 2.5 & 4.0 & 4.0 & 2.5 & 2.5 & 2.5 & 2.5 & 2.5 & 2.5 \\\\\n\tSpot && nm & \\multicolumn{10}{c}{$\\sim300$} \\\\\n\tStep && nm & \\multicolumn{10}{c}{50} \\\\\n\t\\bottomrule\n\t\\end{tabular}\n\\end{table}\n\n\\end{landscape}\n\n\\begin{figure}\n\\begin{center}\n \\begin{tabular}{c}\n    \\includegraphics[width=0.8\\textwidth]{chSPIE_2014_ebeam/figs/TJ04_ghosts_pretty_alt.pdf}\n   \\end{tabular}\n  \\end{center}\n  \\caption[Ghost level measurements]{\\label{fig:GhostLevelFig} Measurements of the levels of inter-order ghosts for different trial runs of the writing process with internal designations TJ03 and TJ04.  The levels are normalized to the brightest order.  A full order is shown, with the $x-$axis units normalized to an order spacing.  The grating sub-areas of TJ04 are described in Table \\ref{tab:TJ04details}.  Some ghosts are not detected, noted as ND.  The non-detections are due to instrumental limitations or genuine absence of ghosts.  The key idea here is that field size choice determines the number of- and to some extent the intensity of- inter order ghosts.  The absolute best patterning strategy is to set your $x-$field size equal to your groove pitch $\\sigma$, as in TJ04A, which has no inter order ghosts.  All other patterns have a finite, albeit low, intensity ghost.  }\n\\end{figure}\n\n\n\\subsection{Improvement in wavefront performance from drift correction}\nIn Figures \\ref{fig:E09igram} and \\ref{fig:E12igram} we show the dramatic impact of drift correction on the performance of our Si gratings.  The stark difference in final wavefront error of the complete grating with drift correction and without drift correction is the ``smoking gun'' that the e-beam must have drift correction enabled to achieve high performance diffraction limited performance.  At the time of writing we have produced and tested another grating, G07, with even higher performance than E12.  Specifically, we perform interferometry at 632 nm in reflection with a 25 mm circular beam on a grating with a blaze angle of 71.6$^\\circ$.  The measured wavefront error is $<0.10$ waves peak to valley for G07.\n\n\\begin{figure}\n   \\subfloat[E12 Interferogram]{\\label{fig:E12igram}\\includegraphics[height=5cm]{chSPIE_2014_ebeam/figs/E12_fig_scl2.pdf}}\n   \\newline\n  \\subfloat[E09 Interferogram]{\\label{fig:E09igram}\\includegraphics[height=5cm]{chSPIE_2014_ebeam/figs/E09_fig_scl2.pdf}}\n  \\caption[Interferometry reveals dramatic improvement in performance of e-beam produced immersion gratings]{Comparison of immersion grating surfaces on samples E09 and E12 measured with $\\lambda = 632.8 $ nm interferometry.  These are both e-beam produced immersion grating surface prototypes.  The color scale is reported in fractions of waves of surface deviation.  The patterns on E09 and E12 are identical: $\\sigma = $ 27.36 $\\mu$m.  The groove top is not shadowed in these measurements which are taken in reflection in air.  The interferometry is performed with a 25 mm circular beam, which is projected over an 80 mm $\\times$ 25 mm ellipse at the R3 echelle blaze angle, $\\delta = 71.5 ^\\circ$.  The left panel is the measured interferometry.  The middle panel is a decomposition into the first $\\sim 80$ Zernike terms.  The right panel is the residual.  The only difference between the samples is that E12 was written with \\emph{DRIFT} and \\emph{CURRENT} check protocols with the JEOL e-beam writing software.  E09 was written without \\emph{DRIFT} and \\emph{CURRENT} check protocols.  The outcome is dramatic- E12 has $\\sim 4$ times lower surface deformation than E09.  Note that the vertical color bars are on the same scale to ease visual comparison.}\n  \\label{fig:igrams}\n\\end{figure}\n\n\n\\section{Limitations of direct writing Si immersion gratings}\nElectron beam lithography outperforms UV contact mask photolithography, at least in terms of the important metric of large scale phase coherence.  There are tradeoffs in pursuing e-beam lithography over UV contact mask photolithography.  We highlight some of these tradeoffs here.\n\n\\subsection{Serial write process yields long write times}\nOne key tradeoff is that e-beam lithography is a serial write process, whereas UV contact mask photolithography is a parallel write process.  A contact mask exposure takes about 1-2 minutes, whereas a e-beam exposure takes about 20 hours, for 30 mm $\\times$ 80 mm patterns.  The problem is even worse if you scale to larger areas, for the next generation immersion gratings.  The high hourly expense of e-beam time makes the writing process the dominant expense over all other preparation steps, despite the high per-part cost of the large precision-oriented and optically polished monolithic Si pucks.  \n\n\\subsection{Large per-part investment cost yields heightened process risk}\nIn reality, the expensive e-beam writing process is not more expensive than procuring a custom high precision vendor-provided photomask.  E-beam lithography simply has a higher per-part risk than UV contact mask photolithography.  Processes after the e-beam step better be low-risk.  Specifically, the processes after exposure include: discharge layer removal, development, plasma etching, wet etching, and shaping.  We find that plasma etching responds differently to thick samples, probably due to the large difference in strike height and dielectric differences between vacuum and Si.  In one case, an overactive plasma etch burned away all the e-beam resist on a 30 mm thick Si sample.\n\n\\subsection{Experiments with negative resist}\nThere is an steep tradeoff in precision and write time.  There is not much way around this tradeoff except for one recent idea of replacing positive tone resist with negative tone resist.  Recently we have experimented with low order Si immersion gratings with groove pitches on the order of $2 \\; \\mu$m (groove frequency $\\sim500$ lines/mm), and and groove tops on the order of 100 nm.   The small pitch and groove top require a small spot size, and therefore a small step size.  We decreased our step size from 50 nm to 10 nm.  This change alone drives up the write time by a factor of 25.  To counteract the otherwise impossibly high write time, we have experimented with negative tone resist.  Negative resist is cleared where the resist is unexposed, and remains only where the resist is exposed.  Since the fill factor of written to unwritten is a factor of 20, the negative resist makes possible the e-beam lithography of these fine pitch patterns.  \n\nIn principle these gains from negative resist could be extended to immersion echelles.  Specifically our typically modus operandi has been to clear about 65\\% of the open area for an R3 echelle, in order to avoid groove top shadowing in immersion \\cite{2012SPIE.8450E..2SG}.  However we could write an exceptionally thin line in negative resist, so long as the line is thick enough to survive wet etching without disintegration.  We estimate that this threshold is about 5\\% of the groove pitch.  \n\n\n\\section{Conclusions}\nElectron beam lithography is now the highest precision technique for producing diffraction limited silicon immersion gratings.  The one performance disadvantage is the high level Rowland ghosts attributable to field stitching.  These errors have been mitigated by breaking up the field sizes into several different field sizes, distributing the power among more inter-order ghosts of lower individual power.  We can achieve 10$^{-3}$ suppression with this multi-field technique.  Ultimately science requirements will have to drive the performance demand of immersion gratings to inform how low to push the inter-order ghost level.  The optimal sizes for e-beam fields, subfields, spots, and steps are nuanced- we lay out rules that avoid repetitive errors.  One key innovation is the e-beam stage drift characterization and compensation.  The correction of stage drift resulted in a $>4\\times$ reduction in peak to valley wavefront error in an R3 immersion echelle grating.  Future experiments with negative tone resists will probably decrease write time and increase performance.\n", "meta": {"hexsha": "193b3d0336a4b3bb1d3598de3118a66aa659f7bf", "size": 39314, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chSPIE_2014_ebeam/chapter-2014-ebeam.tex", "max_stars_repo_name": "BrownDwarf/gullyDiss", "max_stars_repo_head_hexsha": "2b5be79e4b05ea98f5748011e1e4a5df142e06f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chSPIE_2014_ebeam/chapter-2014-ebeam.tex", "max_issues_repo_name": "BrownDwarf/gullyDiss", "max_issues_repo_head_hexsha": "2b5be79e4b05ea98f5748011e1e4a5df142e06f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chSPIE_2014_ebeam/chapter-2014-ebeam.tex", "max_forks_repo_name": "BrownDwarf/gullyDiss", "max_forks_repo_head_hexsha": "2b5be79e4b05ea98f5748011e1e4a5df142e06f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 145.0701107011, "max_line_length": 1406, "alphanum_fraction": 0.7802563972, "num_tokens": 9673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.5273165233795672, "lm_q1q2_score": 0.3397105434262239}}
{"text": "\\vssub\n\\subsubsection{~Third-order scheme (UQ)}\n\\opthead{UQ}{\\ws}{H. L. Tolman}\n\n\\noindent\nThe \\uq\\ scheme for the $\\theta$-space is implemented similar to the scheme\nfor physical space, with the exception that the closed direction space does\nnot require boundary conditions. The variable grid spacing in $k$-space\nrequires some modifications to the scheme as outlined by\n\\cite[{Appendix}]{art:Leo79}. Equations~(\\ref{eq:quick_1}) through\n(\\ref{eq:quick_4}) then become\n\n% ------ QUICKEST scheme for k space---------- %\n% eq:quick_1k        Basic flux\n% eq:quick_2k        Boundary value\n% eq:quick_3k        Divergence\n% eq:quick_4k        CFL number\n\n\\begin{equation}\n\\cF_{m,-} = \\left [ \\dot{k}_{g,b} \\: N_b \\: \\right ]^n_{i,j,l}\n\\: , \\label{eq:quick_1k}\\end{equation} \\begin{equation}\n\\dot{k}_{g,b} = 0.5 \\: \\left ( \\dot{k}_{g,m-1} + \\dot{k}_{g,m} \n\\: \\right )  \\: , \\label{eq:quick_1ak}\n\\end{equation} \\begin{equation}\nN_b = \\frac{1}{2} \\left [ \\rule[0mm]{0mm}{\\baselineskip} \\: \n(1+C)N_{i-1} + (1-C)N_i \\: \\right ] - \\:\n\\frac{1-C^2}{6} \\: {\\cal CU} \\: \\Delta k^2_{m-1/2}, \\label{eq:quick_2k} \\end{equation} \\begin{equation}\n{\\cal CU} =  \\left \\{ \\begin{array}{ccc}\n\\frac{1}{\\Delta k_{m-1}}\n\\left [ \\frac{N_{ m }-N_{m-1}}{\\Delta k_{m-1/2}} - \n        \\frac{N_{m-1}-N_{m-2}}{\\Delta k_{m,-3/2}} \\right ]\n               & \\mbox{for} & \\dot{k}_b \\geq 0 \\\\\n\\frac{1}{\\Delta k_m}\n\\left [ \\frac{N_{m+1}-N_{ m }}{\\Delta k_{m+1/2}} -\n       \\frac{N_{ m }-N_{m-1}}{\\Delta k_{m-1/2}} \\right ]\n               & \\mbox{for} & \\dot{k}_b   <  0\n\\end{array} \\right . \\: , \\label{eq:quick_3k}\n\\end{equation} \\begin{equation}\nC = \\frac{\\dot{k}_{g,b} \\: \\Delta t}{\\Delta k_{m-1/2}}\n\\: , \\label{eq:quick_4k} \\end{equation}\n\n\\noindent\nwhere $\\Delta k_m$ is the discrete band or cell width at grid point $m$, and\nwhere $\\Delta k_{m-1/2}$ is the distance between grid points with counters $m$\nand $m-1$. The \\ult\\ limiter can be applied as in Eqs.~(\\ref{eq:ult_1})\nthrough (\\ref{eq:ult_4}), if the \\cfl\\ number of Eq.~(\\ref{eq:quick_4k}) is\nused. At the low- and high-wavenumber boundaries the fluxes again are\nestimated using a first-order upwind approach, with boundary conditions as\nabove defined for the first-order scheme. The final scheme in $k$-space\nbecomes\n\n% eq:1uq_k_tot\n\n\\begin{equation}\nN_{i,j,l,m}^{n+1} = N_{i,j,l,m}^n \n + \\frac{\\Delta t}{\\Delta k_m} \\left [ \\cF_{m,-} - \\cF_{m,+} \\right ]\n\\: , \\label{eq:uq_k_tot} \\end{equation}", "meta": {"hexsha": "874741788c7fc48889817259fba34953573a55a3", "size": 2424, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "WW3/manual/num/spec_uq.tex", "max_stars_repo_name": "minsukji/ci-debug", "max_stars_repo_head_hexsha": "3e8bbbe6652b702b61d2896612f6aa8e4aa6c803", "max_stars_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WW3/manual/num/spec_uq.tex", "max_issues_repo_name": "minsukji/ci-debug", "max_issues_repo_head_hexsha": "3e8bbbe6652b702b61d2896612f6aa8e4aa6c803", "max_issues_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-05-31T15:49:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-04T14:17:45.000Z", "max_forks_repo_path": "WW3/manual/num/spec_uq.tex", "max_forks_repo_name": "minsukji/ci-debug", "max_forks_repo_head_hexsha": "3e8bbbe6652b702b61d2896612f6aa8e4aa6c803", "max_forks_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-01T09:29:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T09:29:46.000Z", "avg_line_length": 42.5263157895, "max_line_length": 103, "alphanum_fraction": 0.6274752475, "num_tokens": 950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.33971054342622387}}
{"text": "\\section{Output Size}\n\\label{sec:value-size}\n\nIn Sophie, the protocol parameter $\\var{minUTxOValue}$ is used to\ndisincentivize attacking nodes by putting many small outputs on the\nUTxO, permanently blocking memory. Because members of the $\\Value$\ntype can be arbitrary large, the ledger requires a $\\UTxO$ entry to\ncontain a minimum amount of Bcc, proportional to its size.\n\nThere is also another $\\Value$ size consideration with respect to spendability\nof an output. The restriction on the total serialized size of the transaction (set\nby the parameter $\\var{maxTxSize}$) serves as an implicit upper bound on the\nsize of a $\\Value$ contained in an output of a transaction. Without tighter\nlimits on the output $\\Value$ size, one of the following situations could arise,\ncausing the output to be come unspendable (these are just a two examples) :\n\n\\begin{itemize}\n  \\item The script locking the very large $\\Value$-containing UTxO is too large\n  to fit inside the transaction alongside the $\\Value$ itself while still respecting\n  the max transaction size\n  \\item The large $\\Value$ cannot be split into several outputs, because the\n  outputs are impossible to fit inside a single transaction\n\\end{itemize}\n\nFigure \\ref{fig:size-helper} contains abstract and helper functions\nused in calculating the in-memory and serialized representation\nsizes of $\\Value$ terms.\n\n\\begin{figure*}[h]\n  \\emph{Abstract Functions}\n  %\n  \\begin{align*}\n    & \\fun{serSize} \\in \\Value \\to \\MemoryEstimate \\\\\n    & \\text{Gives the size of the serialized representation of a $\\Value$}\n    \\nextdef\n    & \\fun{anameLen} \\in \\AssetName \\to \\MemoryEstimate \\\\\n    & \\text{Returns the length (in bytes) of an asset name}\n  \\end{align*}\n  %\n  \\emph{Helper Functions}\n  \\begin{align*}\n    & \\fun{numAssets} \\in \\Value \\to \\N \\\\\n    & \\fun{numAssets}~{vl}~=~\\|~\\{~(pid, an)~\\vert~pid~(\\mapsto~(an~\\mapsto~\\wcard))~\\in~vl~\\}~\\| \\\\\n    & \\text{Returns the number of distinct asset IDs in a $\\Value$}\n    & \\nextdef\n    & \\fun{sumALs} \\in \\Value \\to \\N \\\\\n    & \\fun{sumALs}~{vl}~=~ \\sum_{\\{~an~\\vert~\\wcard~(\\mapsto~(an~\\mapsto~\\wcard))~\\in~vl~\\}} \\fun{anameLen}~an \\\\\n    & \\text{Returns the sum of the lengths (in bytes) of distinct asset names in a $\\Value$}\n    & \\nextdef\n    & \\fun{numPids} \\in \\Value \\to \\N \\\\\n    & \\fun{numPids}~{vl} ~=~ \\|~\\supp~{vl}~\\| \\\\\n    & \\text{The number of policy IDs in a $\\Value$}\n  \\end{align*}\n  \\caption{Value Size}\n  \\label{fig:size-helper}\n\\end{figure*}\n\nThe function $\\fun{serSize}$, unlike the functions $\\fun{size}$ and $\\fun{utxoEntrySize}$\n    (explained below), is left abstract. It returns the actual number of bytes a $\\Value$\n    occupies in the serialized transaction (and hence is implementation-dependent).\n\n    One reason for this design decision is that the $\\fun{serSize}$ function is used constrain\n    the serialized representation of the transaction (in particular, the size\n    of $\\Value$ terms in outputs), whereas the min-Bcc requirement is about\n    the in-memory representation size. Moreover, a transparently-calculated size estimate\n    is not necessary for limiting the size of values in outputs, since this size-bound\n    check does not place any additional accounting/monetary constranits on transaction construction,\n    unlike the min-Bcc requirement.\n\nFigure \\ref{fig:min-val-calc} gives the types of constants used in the estimation\nof the size of a UTxO entry, and the associated min-Bcc-value.\n\n\\begin{figure*}[h]\n  \\emph{Constants}\n  \\begin{equation*}\n    \\begin{array}{lcl}\n      (k_0, k_1, k_2, k_3, k_4) & \\in & \\N \\times \\N \\times \\N \\times \\N \\times \\N \\\\\n      \\mathsf{UtxoEntrySizeWithoutVal} & \\in & \\MemoryEstimate \\\\\n      \\mathsf{BccOnlyUTxOSize} & \\in & \\MemoryEstimate \\\\\n      \\mathsf{MaxValSize} & \\in & \\MemoryEstimate \\\\\n    \\end{array}\n  \\end{equation*}\n  %\n  \\emph{Size and Min-Bcc Functions}\n  \\begin{align*}\n    & \\fun{size} \\in \\Value \\to \\MemoryEstimate \\\\\n    & \\fun{size}~\\var{vl} ~=~\n    \\begin{cases}\n      k_0 & \\fun{bccOnly}~vl~=~vl \\\\\n      k_1 + \\lfloor~ (((\\fun{numAssets}~vl) * k_2) + (\\fun{sumALs}~vl) & \\\\\n      ~~~~~~ + ((\\fun{numPids}~vl) * k_3) + (k_4 - 1)))~ /~ k_4~\\rfloor & \\text{otherwise} \\\\\n    \\end{cases} \\\\\n    & \\text{Calculate the size of a $\\Value$}\n    \\nextdef\n    & \\fun{bccPerUTxOWord}~\\in \\PParams \\to \\Coin \\\\\n    & \\fun{bccPerUTxOWord}~pp = \\lfloor~ (\\fun{minUTxOValue}~pp~/~ \\mathsf{bccOnlyUTxOSize})~ \\rfloor \\\\\n    & \\text{Calculate the cost of storing a memory unit of data as a UTxO entry}\n    \\nextdef\n    & \\fun{utxoEntrySize} \\in \\TxOut \\to \\MemoryEstimate \\\\\n    & \\fun{utxoEntrySize}~\\var{out} = \\mathsf{utxoEntrySizeWithoutVal} + \\fun{size}~ (\\fun{getValue}~out) \\\\\n    & \\text{Calculate the size of a UTxO entry}\n\\end{align*}\n\\caption{Value Size}\n\\label{fig:min-val-calc}\n\\end{figure*}\n\nThe $\\fun{size}$ function returns the estimated size of a $\\Value$ term. It is constant in the\ncase where the value contains only Bcc. If there are other types of tokens in the\nterm, the size depends on\n\n\\begin{itemize}\n  \\item the number of distinct asset types (asset IDs)\n  \\item the number of distinct policy IDs, and\n  \\item the sum of the lengths of distinct asset names of the tokens.\n\\end{itemize}\n\nThe parameter $\\fun{minUTxOValue}$ specifies the min-Bcc value for a UTxO containing\nonly Bcc. This type of UTxO varies in size somewhat (eg. Cole style addresses\nmay be a different length than Sophie ones), but we estimate the size of the most commonly\nused type of Bcc-only UTxO as the constant value $\\mathsf{bccOnlyUTxOSize}$.\nThis constant is in fact an upper bound on UTxOs which have have only Sophie credentials.\n\nWe use this size estimate\nto calculate what $\\fun{minUTxOValue}$ implies to be the min-Bcc value requirement\n\\emph{per word} of UTxO data.\n\nThe function $\\fun{bccPerUTxOWord}$ performs this calculation by dividing the\nmin-Bcc value by the Bcc-only UTxO size.\n\nThe $\\mathsf{utxoEntrySizeWithoutVal}$ is the constant representing\nthe size of a UTxO entry, not counting the size of the $\\Value$ term it contains.\nHere, again, the actual size of a UTxO (excluding the $\\Value$) can vary, but\nwe use an upper bound on the size of Sophie-credential UTxOs.\n\nThe function $\\fun{utxoEntrySize}$ estimates the size of an arbitrary SophieMA-era\nUTxO. It adds the size estimate of the $\\Value$ term in a UTxO and the\n$\\mathsf{utxoEntrySizeWithoutVal}$ constant.\n\nThe constants used in the implementation of the Aurum era are as follows :\n\n\\begin{itemize}\n  \\item $(k_0, k_1, k_2, k_3, k_4) = (2, 6, 12, 28, 8)$\n  \\item $\\mathsf{utxoEntrySizeWithoutVal} = 27$ words (8 bytes)\n  \\item $\\mathsf{bccOnlyUTxOSize} = 27$ words (8 bytes)\n  \\item $\\mathsf{MaxValSize} = 4000$ bytes, ie. 500 words.\n\\end{itemize}\n", "meta": {"hexsha": "599cc98710b1aadb433543a80112978d643bc14b", "size": 6725, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "sophie-ma/formal-spec/value-size.tex", "max_stars_repo_name": "Quantum-One-DLT/bcc-ledger-specs", "max_stars_repo_head_hexsha": "e1109f35aee321bbf899a5e2cc4de3eec583f9b7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sophie-ma/formal-spec/value-size.tex", "max_issues_repo_name": "Quantum-One-DLT/bcc-ledger-specs", "max_issues_repo_head_hexsha": "e1109f35aee321bbf899a5e2cc4de3eec583f9b7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sophie-ma/formal-spec/value-size.tex", "max_forks_repo_name": "Quantum-One-DLT/bcc-ledger-specs", "max_forks_repo_head_hexsha": "e1109f35aee321bbf899a5e2cc4de3eec583f9b7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-11-13T21:20:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T16:37:19.000Z", "avg_line_length": 45.7482993197, "max_line_length": 113, "alphanum_fraction": 0.7042379182, "num_tokens": 2060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.3396676957603404}}
{"text": "\\section{Introduction}\r\n\\label{sec:intro}\r\n\\citet{Manson:2005:JMM:1047659.1040336} identify the central problem in the\r\ndesign of software relaxed memory models: ``The memory model must strike a\r\nbalance between ease-of-use for programmers and implementation flexibility\r\nfor system designers.''  \r\n\r\n%In order to sharpen the criteria to evaluate memory models, we first outline desiderata  that concretize the above prescription.  \r\n\r\nThere are two aspects to ``ease of use.''  First, programs should support\r\n\\emph{compositional} and \\emph{local} reasoning; in this paper, we emphasize\r\ntemporal safety\r\nproperties~\\cite{PnueliSafety,Misra:1981:PNP:1313338.1313770,StarkSafety,Abadi:1993:CS:151646.151649}.\r\nSecond, relaxing memory consistency should not change the behavior of correctly\r\nsynchronized programs; this property is known as \\emph{sequential consistency\r\n  for data race free programs} (\\drfsc)~\\cite{DBLP:journals/tpds/AdveH93,\r\n  DBLP:conf/isca/AdveH90}.\r\n % Second, the expectation of\r\n% \\emph{sequential consistency for data race free programs}\r\n% (\\drfsc)~\\cite{DBLP:journals/tpds/AdveH93, DBLP:conf/isca/AdveH90} permits\r\n% the programmer to forget about relaxed memory for correctly synchronized\r\n% programs.\r\n\r\n% There are two aspects to ``ease of use.''  First, programmers should be able\r\n% to reason about program fragments \\emph{compositionally} and \\emph{locally};\r\n% in this paper we emphasize compositional reasoning about temporal safety\r\n% properties~\\cite{PnueliSafety,Misra:1981:PNP:1313338.1313770,StarkSafety,Abadi:1993:CS:151646.151649}.\r\n% Second, programmers should be able to forget about relaxed memory in\r\n% correctly synchronized programs; this property is known as \\emph{sequential\r\n%   consistency for data race free programs}\r\n% (\\drfsc)~\\cite{DBLP:journals/tpds/AdveH93, DBLP:conf/isca/AdveH90}.\r\n\r\nThere are also two aspects of ``implementation flexibility.''  First, relaxed\r\natomic access should not require hardware synchronization (at least for the\r\nword size of the machine).  Second, the model\r\nshould facilitate compiler transformations, such as the reordering of independent\r\nstatements; ideally the model should support all %valid\r\noptimizations of\r\nsynchronization\\hyp{}free single\\hyp{}threaded code.\r\n% A\r\n% canonical example is that independent statements should commute.\r\n\r\nSailing between this Scylla and Charybdis has proven very difficult.  Three\r\nlines of code can leave the top experts in the field flabbergasted.  The\r\nsolutions that have been proposed are understandable to mechanical proof\r\nassistants, but humans have been left behind.\r\n\r\nIn this paper, we combine two ideas that humans can understand: \\emph{preconditions}\r\n\\cite{Hoare:1969:ABC:363235.363259} and \\emph{labelled partial orders} (aka \\emph{pomsets})\r\n\\cite{GISCHER1988199,Plotkin:1997:TSP:266557.266600}.  The resulting model\r\nmostly satisfies the desiderata.  We sacrifice only implementability on\r\n``non-\\mca'' processors, such as \\ppc\\ and \\armseven{}. As a result, however,\r\nthere is only one order relation to visualize.\r\n\r\nPerhaps you believe the problem has already been solved?  Let us try to\r\nconvince you otherwise.\r\n% Eventually,\r\n% the enthusiasm of proposing a new model yields to weariness as the\r\n% complications mount.\r\n\r\nTo get a sense of the difficulties involved,\r\n% \\citeauthor{DBLP:journals/toplas/Lochbihler13}'s example shows a surprising feature of\r\n% relaxed memory models: the presence of an execution may depend on code that was not executed. Consider:\r\nconsider that the existence of an execution in a relaxed memory model may\r\ndepend on code that was \\emph{not} executed. Let $r$--$s$ be registers and\r\n$b$, $x$--$z$ be shared memory locations.  Consider the following program, where\r\nall memory locations are initialized to $0$:\r\n\\begin{align*}\r\n  \\tag{\\ref{OOTA?}}\r\n    \\PW{y}{x}\r\n  \\PAR&\r\n  \\PR{y}{r}\\SEMI\\IF{r}\\THEN \r\n  \\PW{x}{r}\\SEMI \\PW{z}{r} \\ELSE \\PW{x}{1} \\FI\r\n\\intertext{Most programmers would be surprised to learn that this program allows an\r\nexecution that sets $z$ to $1$. To see why, imagine that a compiler does type\r\ninference and finds that $x$ and $y$ are booleans, with value either $0$ or\r\n$1$.  This enables the program to be optimized to the following:}\r\n  %\\taglabelp{OOTA?}\r\n    \\PW{y}{x}\r\n  \\PAR&\r\n  \\PR{y}{r}\\SEMI\\IF{r}\\THEN \r\n  \\PW{x}{1}\\SEMI \\PW{z}{1} \\ELSE \\PW{x}{1} \\FI\r\n\\intertext{Since $\\PW{x}{1}$ occurs in both branches of the conditional, the compiler can\r\nthen lift it, and reorder with the independent read of $y$, yielding:}\r\n  %\\taglabelpp{OOTA?}\r\n    \\PW{y}{x}\r\n  \\PAR&\r\n  \\PW{x}{1}\\SEMI\r\n  \\PR{y}{r}\\SEMI\\IF{r}\\THEN \\PW{z}{1} \\FI\r\n\\intertext{Then $z$ is $1$ at then end of an execution where the first thread is interleaved\r\nimmediately after executing $\\PW{x}{1}$.\r\nWithout the conditional in \\eqref{OOTA?}, it is obvious that the program should not write $1$:}\r\n  \\tag{\\ref{OOTA3}}\r\n  %\\PW{x}{0}\\SEMI \\PW{y}{0}\\SEMI\r\n  %(\\bLoc \\GETS \\aLoc \\PAR \\aLoc \\GETS \\bLoc)\r\n  \\PW{\\bLoc}{\\aLoc} \\PAR&\r\n  \\PR{y}{r}\\SEMI \\PW{x}{r}  \\SEMI \\PW{z}{r}\r\n\\end{align*}\r\nIn \\ref{OOTA3}, the constant $1$ arises ``Out Of Thin Air'' (\\oota)\r\n\\cite{DBLP:conf/esop/BattyMNPS15}.  As a result, any model of relaxed memory\r\nthat supports common compiler optimizations, as above, must take into account\r\ncode that was not executed.  This is why many models of relaxed memory\r\ninclude some form of speculative execution, with the goal of allowing the\r\noutcome $z{=}1$ for \\eqref{OOTA?}, but not \\ref{OOTA3}.\r\n\r\nThe control flow variant of \\ref{OOTA3} is:\r\n\\begin{displaymath}\r\n  \\label{cyc}\\tag{\\textsc{oota2}}\r\n  \\IF{x}\\THEN \\PW{y}{1} \\FI \\!\\PAR\\! \\IF{y}\\THEN \\PW{x}{1} \\SEMI \\PW{z}{1}\\FI\r\n\\end{displaymath}\r\nThis program is data-race-free. Thus, allowing an execution that writes $1$\r\nwould violate \\drfsc{}.\r\n\r\n\r\n\\oota{} behaviors can be quite subtle.\r\nConsider the following variants of \\eqref{OOTA?}:\r\n\\begin{align}\r\n  \\tag{\\ref{OOTA!}}\r\n    \\PW{y}{x}\r\n  \\PAR&\r\n  \\PR{y}{r}\\SEMI \\IF{r}\\THEN \r\n  \\PW{x}{r}\\SEMI \\PW{z}{r} \\ELSE \\PW{x}{2} \\FI\r\n  \\\\\r\n  \\tag{\\ref{OOTA4}}\r\n  \\PW{y}{x}\r\n  \\PAR&\r\n  \\PR{y}{r} \\SEMI \\IF{b}\\THEN  \\PW{x}{r} \\SEMI \\PW{z}{r} \\ELSE \\PW{x}{1} \\FI\r\n  \\PAR\r\n  \\PW{b}{1}\r\n\\end{align}\r\nFollowing the reasoning above, \\ref{OOTA!} has an execution where\r\n$z{=}2$, but it does not have an execution where $z{=}1$.   Neither does\r\n\\ref{OOTA4}.  In this case, it not sound to assume that  $1$ is\r\nwritten on both sides of the conditional, invalidating the first optimization\r\ngiven for \\eqref{OOTA?} above.\r\n% Note that the only\r\n% difference between \\eqref{OOTA?} and \\eqref{OOTA!} is the code in the branch\r\n% that was not taken.  \r\n  \r\n\r\n% Many models of relaxed\r\n% memory include some form of speculative execution in order to allow $1$ in\r\n% \\eqref{OOTA?}, but not \\eqref{OOTA!} and \\ref{OOTA3}.\r\n% Any model of relaxed memory that supports common compiler optimizations\r\n% (such as the transformations above) must take into account code that was\r\n% not executed. This is why many models of relaxed memory include some form\r\n% of speculative execution.\r\n\r\n% Any model of relaxed memory that supports common compiler optimizations, as\r\n% above, must take into account code that was not executed.  This is why many\r\n% models of relaxed memory include some form of speculative execution, with the\r\n% goal of allowing $1$ in \\eqref{OOTA?}, but not \\eqref{OOTA!} and\r\n% \\ref{OOTA3}.\r\n% Many models of relaxed memory include some form of speculative execution in\r\n% order to allow $1$ in \\eqref{OOTA?}, but not \\eqref{OOTA!} and\r\n% \\ref{OOTA3}.\r\n\r\n\r\n\\citeauthor{DBLP:conf/java/Pugh99} [\\citeyear{DBLP:conf/java/Pugh99},\r\n\\textsection2.3] initiated the modern study of relaxed memory by noting that\r\nJava 1.1 failed to validate Common Subexpression Elimination (CSE) in the\r\npresence of aliasing. For example, given that $\\aReg_2{\\neq}\\bReg$, is it valid\r\nto transform the program on the left to that on the right?\r\n\\begin{align*}\r\n  %\\tag{\\ref{CSE}}\r\n  ({r_1\\GETS \\aLoc \\SEMI\r\n  s\\GETS \\bLoc \\SEMI  \r\n  r_2\\GETS \\aLoc\\SEMI\\aCmd})\r\n&&\r\n  ({r_1\\GETS \\aLoc \\SEMI     \r\n    r_2\\GETS r_1\\SEMI\r\n    s\\GETS \\bLoc \\SEMI\\aCmd})\r\n\\end{align*}\r\nThe resulting Java Memory Model (JMM) \\cite{Manson:2005:JMM:1047659.1040336}\r\ngreatly advanced the state of the art.\r\n\r\n\r\n\\citeauthor{DBLP:journals/toplas/Lochbihler13}'s\r\nmonumental study of the JMM\r\nrevealed a surprising limitation. Consider the following program\r\n\\citep[Fig.~8]{DBLP:journals/toplas/Lochbihler13}, where again\r\nall memory locations are initialized to $0$:\r\n%\\vspace{-.5ex}\r\n\\begin{gather}\r\n  \\tag{\\textsc{oota5}}\\label{OOTA1}\r\n  \\PW{y}{x}\r\n  \\PAR\r\n  \\PR{y}{\\aReg} \\SEMI \\IF{b} \\THEN \\LET{\\aReg}{\\NEW \\classD} \\SEMI \\PW{x}{\\aReg} \\SEMI \\PW{z}{\\aReg} \\ELSE \\LET{\\bReg}{\\NEW \\classC} \\SEMI \\PW{x}{\\aReg} \\FI  \r\n  \\PAR %\\\\[-1ex] \\PAR&\r\n  \\PW{b}{1}\r\n\\end{gather}\r\n\\ref{OOTA1} ``is type correct if it declares $x$, $y$ and $r$ of type\r\n$\\classD$. However, it has a legal execution where they reference a $\\classC$\r\nobject.''  The JMM allows $(\\PR{y}{\\aReg})$ to see the object created by\r\n$\\NEW$, by bouncing it through $(\\PW{x}{\\aReg})$ and $(\\PW{y}{x})$.  In the\r\n\\emph{commitment order} of the JMM, this allows the address of the\r\nallocated object to be read $(\\PR{y}{\\aReg})$ before its type is determined\r\n$(\\IF{b})$.\r\n\r\n% See \\ref{OOTA4} in\r\n% \\textsection\\ref{sec:logic} for a simple variant of \\eqref{OOTA?} with this\r\n% behavior.\r\n\r\n% By allowing such \\emph{bait-and-switch} behaviors, the JMM fails to support\r\n% compositional reasoning for temporal safety properties:  the individual\r\n% threads of \\ref{OOTA1} satisfy the invariant\r\n% % \\emph{allocation at type $\\classD$ is preceded by reading zero for $b$}.\r\n% % They also satisfy:\r\n% \\emph{allocation at type $\\classC$ is preceded by reading $0$ for\r\n%   $b$}, but the composed program does not.  This lack of compositionality\r\n\r\nThis type of \\emph{bait-and-switch} behavior forced\r\n\\citeauthor{DBLP:journals/toplas/Lochbihler13} to partition memory by type in\r\norder to prove type safety.  This formal device means that memory cannot be\r\nused at different types over time, making practical memory reclamation\r\nimpossible.  Even partitioning memory to achieve type safety, there are\r\nimplications for the Java security architecture\r\n\\cite[\\textsection5.4]{DBLP:journals/toplas/Lochbihler13}.\r\n\r\nIn both \\ref{OOTA4} and \\ref{OOTA1}, the \\oota{} outcome occurs by\r\n\\emph{baiting} with the \\texttt{else} branch, then \\emph{switching} to the\r\n\\texttt{then} branch, based on a coin flip $(\\IF{b})$.  As confirmed by\r\n\\cite{kang,soham}, the promising semantics \\cite{DBLP:conf/popl/KangHLVD17}\r\nand related models\r\n\\citep{DBLP:conf/esop/JagadeesanPR10,DBLP:journals/pacmpl/ChakrabortyV19,Manson:2005:JMM:1047659.1040336}\r\nall allow \\oota{} behaviors of \\ref{OOTA4}.\\footnote{Call the threads\r\n  \\texttt{s}, \\texttt{t}, and \\texttt{u}.  To get the result in the promising\r\n  semantics, first execute \\texttt{u} to get message \\texttt{<b:1@1>}.  Then\r\n  \\texttt{t} promises \\texttt{<x:1@1>}, which it can fulfill by reading\r\n  \\texttt{b}$=$\\texttt{0}.  Then execute \\texttt{s} to get message \\texttt{<y:1@1>}.\r\n  Then execute \\texttt{t}, reading \\texttt{b}$=$\\texttt{1} and \\texttt{y}$=$\\texttt{1} and\r\n  fulfill the promise by writing \\texttt{<x:1@1>}. The execution is exactly\r\n  the same in our speculative semantics \\cite{DBLP:conf/esop/JagadeesanPR10},\r\n  removing timestamps and replacing the word \\emph{promise} by \\emph{speculation}.}  Due\r\nto the similarity of \\ref{OOTA4} and \\ref{OOTA1}, it is reasonable to\r\nconclude that these models \\emph{cannot support both type safety and\r\n  realistic memory reclamation}.\r\n\r\n% The JMM is defined using an operational model that incorporates the idea of\r\n% restarting executions.  Similar models have used speculation\r\n% \\cite{DBLP:conf/esop/JagadeesanPR10} or promises\r\n% \\cite{DBLP:conf/popl/KangHLVD17}.\r\n\r\n% % Whereas the JMM was designed with these two aims,\r\n% , invalidating compositional reasoning for temporal safety\r\n% properties.\r\n% % , as in\r\n% % \\ref{OOTA1}.  % (Specifically, they\r\n% % allow the variant \\ref{OOTA4} given in \\textsection\\ref{sec:logic}.)\r\n% % See\r\n% % \\textsection\\ref{sec:promising} for confirmation from the authors themselves.\r\n% This means that these models \\emph{cannot support both type safety and\r\n%   realistic memory reclamation}.\r\n\r\n\r\n% Due to the shortcomings of the JMM, many subsequent models preferred an\r\n% axiomatic approach.  \r\nThe C11 Memory Model \\cite{Batty:2011:MCC:1926385.1926394} does not attempt\r\nto validate CSE, at least not for relaxed atomic access (consider the case\r\nwhere $x$ and $y$ are aliased above).  C11 \\emph{does} allow the\r\ntransformation for \\emph{plain} access, but this comes with the threat of\r\n\\emph{undefined behavior} should any plain access ever possibly engage in a\r\ndata race \\cite{undefined}.  C11 also allows \\oota{} behaviors, exploiting\r\ncausality cycles.  Undefined/\\oota{} behavior is antithetical to the goals of\r\nsafe languages.\r\n% Thus the folklore belief that ``every substantial C program has\r\n% undefined behavior.''\r\n\r\n\r\n%to permit us to reason separately about individual threads validating safety properties. \r\n% ``Out Of Thin Air'' (\\oota) executions invalidate the \r\n% composability  of safety properties.\r\n\r\n% None of the extant memory models validate both\r\n% ``implementation flexibility'' and ``ease of use.''  This paper provides a\r\n% solution.  The solution is remarkably simple, enriching labelled partial\r\n% orders (aka \\emph{pomsets}) with preconditions.\r\n\r\nStrong models, including Sequential Consistency\r\n(SC)~\\citep{Lamport:1979:MMC:1311099.1311750}, RC11\r\n\\citep{DBLP:conf/pldi/LahavVKHD17}, and others\r\n\\citep{Dolan:2018:BDR:3192366.3192421,DBLP:conf/pldi/LahavVKHD17,DBLP:conf/lics/JeffreyR16,Boehm:2014:OGA:2618128.2618134},\r\nsupport compositional reasoning.  However, all of these models invalidate\r\nreordering of independent statements.  All require fences after relaxed\r\nreads, even on \\armeight.\r\n% \\cite{Dolan:2018:BDR:3192366.3192421,BoehmOOTA,DBLP:conf/lics/JeffreyR16} forbid breaking of the program order from reads to writes and thus require extra fences after read actions in hardware implementations.\r\n% \\citep{Boehm:2014:OGA:2618128.2618134} show that the RC11 model %\\cite{DBLP:conf/pldi/LahavVKHD17}\r\n% forces a dependency or a fence between a relaxed atomic read and a subsequent relaxed atomic write.  \r\n\r\n\r\n\\myparagraph{Our Model}\r\n\r\nIn our approach, a program is a set of executions.  Each execution is a\r\n\\emph{pomset}: a partial order over a set of read and write events.  The\r\norder is intended to be read as a \\emph{dependency} relation.  The dependency\r\nrelation is dynamic, varying between executions.  Events that are not related\r\nin an execution are \\emph{independent} and can be seen by a sequential\r\nobserver in either order.\r\n\r\nCross thread dependencies arise from conflicting actions on the same\r\nvariable: Roughly, we order any two actions on the same location, at least\r\none of which is a write.  In the parlance of hardware memory\r\nmodels~\\citep{alglave}: $\\rcoe$, $\\rfre$, and $\\rrfex$ are included in the\r\nglobal dependency ordering.  Thus, our model realizes \\emph{multi-copy\r\n  atomicity} (\\mca): when a write becomes visible to one thread it must\r\nbecome visible to all\\nofootnote{\\mca\\ is traditionally explored in hardware\r\n  memory models.  \\tso\\ (see, e.g.~\\cite{DBLP:journals/cacm/SewellSONM10})\r\n  and recent architectures, such as \\armeight\\ (see,\r\n  e.g.~\\cite{DBLP:journals/pacmpl/PulteFDFSS18}, RISC-V.  ), are \\mca, but\r\n  not older architectures, such as \\ppc\\ (see,\r\n  e.g.~\\cite{DBLP:conf/pldi/SarkarSAMW11}) or \\armseven\\ (see,\r\n  e.g.~\\cite{DBLP:conf/popl/AlglaveFIMSSN09}).}\r\n\\citep{DBLP:journals/pacmpl/PulteFDFSS18}.  As envisioned in\r\n\\cite[\\textsection3.3]{AlglaveThesis}, this allows us to capture cross-thread\r\ndependencies in a single partial order.\r\n\r\nOur key insight is that \\emph{\\mca{} permits a single, global notion of time,\r\n  manifest in the pomset order}.\r\n  \r\n\r\nWithin a thread, the dependency calculation can be viewed as the computation\r\nof \\emph{preserved program order}, called $\\rppo$ in hardware models.  In our\r\nsoftware model, $\\rppo$ captures the \\emph{essential dependencies} between\r\nevents in the same thread.  Consider the following program fragments:\r\n\\begin{align*}\r\n  & \\aCmd_1: \\PW{\\aLoc}{1} \\SEMI \\PW{\\bLoc}{1}\r\n  \\\\[-1ex] & \\aCmd_2: \\aReg \\GETS \\aLoc \\SEMI \\IF{\\aReg} \\THEN\\ \\PW{\\bLoc}{1} \\ELSE \\PW{\\bLoc}{1}  \\FI\r\n  \\\\[-1ex] & \\aCmd_3: \\PW{\\aLoc}{1} \\SEMI \\aReg \\GETS \\aLoc \\SEMI \\IF{\\aReg} \\THEN \\PW{\\bLoc}{1} \\FI\r\n  %\\\\[-1ex] &\\aCmd_4:  \\PW{\\bLoc}{1} \\SEMI \\PW{\\aLoc}{1}\r\n\\end{align*}\r\nEach of these fragments satisfy the \\citeauthor{Hoare:1969:ABC:363235.363259} triple $\\hoare{\\TRUE}{\\aCmd_i}{\\bLoc =1}$; thus, in each\r\ncase, the write of $y$ is independent of any code that precedes it in program\r\norder. While $\\aCmd_1$ reflects syntactic independence, $\\aCmd_2$ reflects\r\nthe independence derived by case analysis, and $\\aCmd_3$ reflects the\r\nindependence deduced from partial evaluation, in the restricted form of\r\nconstant propagation.\r\n\r\nOur key insight is to that \\emph{logic is better than syntax} to capture such\r\ndependencies.\r\n\r\nThe logical perspective provides a clear intuition as to why certain compiler\r\ntransformations should be valid.  Such intuitions are not always readily\r\navailable in relaxed memory models.  For example, \\emph{value range\r\n  analysis}---used in the discussion of \\eqref{OOTA?}---is difficult in many\r\nmodels.  As another example, models such as \\armeight{} distinguish\r\n\\emph{internal} reads, which are fulfilled by a write of the same thread,\r\nfrom \\emph{external} ones, which are fulfilled cross-thread.  Unlike\r\nexternal reads, internal reads are not necessarily recorded in\r\nthe dependency relation.  As exemplified by $\\aCmd_3$, this allows a compiler\r\nto reorder the fulfilling write with subsequent code that depends on the\r\nread.  Neither value range analysis nor internal reads require special\r\ntreatment in our model.\r\n\r\n\r\n\r\n% The logical perspective provides a clear intuition as to why our model validates\r\n% the compiler transformations discussed above \\eqref{OOTA?}.\r\n% reordering of independent statements, Irrelevant read introduction, RaR, RaW,\r\n% WaW and Read Reordering and motivates the expressivity wrt the \\jmm\\\r\n% causality test cases.  For example, consider Test Case 17 from Pugh.\r\n% \\[\r\n% \\begin{array}{ll}\r\n%  &\\aReg_3 \\GETS \\aLoc \\SEMI \\IF{\\aReg_3 \\neq 42} \\THEN \\PW{\\aLoc}{42}  \\FI \\SEMI \\aReg_1 \\GETS \\aLoc \\SEMI \\bLoc \\GETS \\aReg_1  \\\\\r\n%  \\PAR & \\aReg_2 \\GETS \\bLoc \\SEMI \\aLoc \\GETS \\aReg \r\n% \\end{array}\r\n% \\]\r\n% \\jmm\\ permits the behavior $\\aReg_1 = \\aReg_2 = \\aReg_3 =42$.\r\n\r\n% We deduce:\r\n% \\[\r\n% \\hoare{\\TRUE}{\\aReg_3 \\GETS \\aLoc \\SEMI \\IF{\\aReg_3 \\neq 42} \\THEN \\PW{\\aLoc}{42}  \\FI \\SEMI \\aReg_1 \\GETS \\aLoc }{\\aReg_1 =42}\r\n% \\]\r\n% and so:\r\n% \\[\r\n% \\hoare{\\TRUE}{\\aReg_3 \\GETS \\aLoc \\SEMI \\IF{\\aReg_3 \\neq 42} \\THEN \\PW{\\aLoc}{42}  \\FI \\SEMI \\aReg_1 \\GETS \\aLoc  \\SEMI \\bLoc \\GETS \\aReg_1  }{\\bLoc =42}\r\n% \\]\r\n% validating the transformation of the first thread to:\r\n% \\[ \\PW{\\bLoc}{42} \\SEMI \\aReg_3 \\GETS \\aLoc \\SEMI \\IF{\\aReg_3 \\neq 42} \\THEN \\PW{\\aLoc}{42}  \\FI \\SEMI \\aReg_1 \\GETS \\aLoc \\SEMI \\]\r\n% from which the required execution follows.\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n% Our approach has two key ingredients.  \r\n\r\n% First, we focus on \\emph{multi-copy atomicity} (\\mca), which holds that when\r\n% a write becomes visible to one thread it must become visible to\r\n% all\\nofootnote{\\mca\\ is traditionally explored in hardware memory models.\r\n%   \\tso\\ (see, e.g.~\\cite{DBLP:journals/cacm/SewellSONM10}) and recent\r\n%   architectures, such as \\armeight\\ (see,\r\n%   e.g.~\\cite{DBLP:journals/pacmpl/PulteFDFSS18}), are \\mca, but not older\r\n%   architectures, such as \\ppc\\ (see, e.g.~\\cite{DBLP:conf/pldi/SarkarSAMW11})\r\n%   or \\armseven\\ (see, e.g.~\\cite{DBLP:conf/popl/AlglaveFIMSSN09}).}\r\n% \\citep{DBLP:journals/pacmpl/PulteFDFSS18}.  As envisioned in\r\n% \\cite[\\textsection3.3]{AlglaveThesis}, this allows us to capture cross-thread\r\n% dependencies in a single partial order.  The key insight is that \\emph{\\mca{}\r\n%   permits a single, global notion of time, manifest in the pomset order}.\r\n% This is a dramatic simplification over other models.\r\n% % acyclicity of the pomset providing a global notion of time.  Just as \\mca{}\r\n% % dramatically simplifies the programmer model for\r\n% % hardware, % \\citep{DBLP:journals/pacmpl/PulteFDFSS18},\r\n% % this global notion of time dramatically simplifies our model for the language\r\n% % level.\r\n% % As far as we are aware, ours is the first language-level model to capture \\mca.   The appeal of \\mca{} in hardware is the dramatically simpler programmer model \\citep{DBLP:journals/pacmpl/PulteFDFSS18}.  We believe it has the same appeal at the language-level.  \r\n\r\n% Second, we weaken the program-order within a thread to capture only\r\n% \\emph{essential dependencies}.  These are represented in the pomset order.\r\n% This reduction from program order to pomset order is similar to the reduction\r\n% to \\emph{preserved} program order (\\textsf{ppo}) in hardware models.  However, rather\r\n% than calculating dependencies syntactically, we compute them using \r\n% %Previous language models have used syntactic notions of dependency \\cite{Batty:2011:MCC:1926385.1926394}.\r\n% classical Hoare logic. The key insight is that \\emph{logic is better than syntax}.\r\n% Consider the following program fragments: %\\begingroup \\allowdisplaybreaks\r\n% \\begin{align*}\r\n%   & \\aCmd_1: \\PW{\\aLoc}{1} \\SEMI \\PW{\\bLoc}{1}\r\n%   \\\\[-1ex] & \\aCmd_2: \\PR{\\aLoc}{\\aReg} \\SEMI \\IF{\\aReg} \\THEN\\ \\PW{\\bLoc}{1} \\ELSE \\PW{\\bLoc}{1}  \\FI\r\n%   \\\\[-1ex] & \\aCmd_3: \\PW{\\aLoc}{1} \\SEMI \\PR{\\aLoc}{\\aReg} \\SEMI \\IF{\\aReg} \\THEN \\PW{\\bLoc}{1} \\FI\r\n%   %\\\\[-1ex] &\\aCmd_4:  \\PW{\\bLoc}{1} \\SEMI \\PW{\\aLoc}{1}\r\n% \\end{align*}\r\n% %\\endgroup\r\n% All these fragments satisfy  $\\hoare{\\TRUE}{\\aCmd_i}{\\bLoc =1}$; thus, in each case, the write of $y$ is independent of\r\n% any code that precedes it in program order.  This allows a compiler or processor to reorder the write with respect to the code that precedes it\\nofootnote{IN RELATED Thus, the model fully reaps the benefits of viewing a memory model in terms of (sequential) program transformations, eg. see~\\citep{Saraswat:2007:TMM:1229428.1229469,DBLP:conf/fm/LahavV16,\r\n% DBLP:conf/popl/DemangeLZJPV13,DBLP:conf/esop/FerreiraFS10}, without explicitly being formalized as such.}.\r\n\r\n\r\nIn \\textsection\\ref{sec:model} and \\textsection\\ref{sec:refine}, we define the model.  We show that the model:\r\n\\begin{itemize}\r\n\\item validates expected litmus cases and compiler optimizations\r\n  (\\textsection\\ref{sec:props}-\\ref{sec:refine}).\r\n\r\n\\item captures all C11 concurrency features  %, including relaxed, release-acquire and SC atomics, fences, and RMW\r\n  (\\textsection\\ref{sec:variants}),\r\n\r\n\\item allows compositional reasoning for temporal safety, disallowing \\oota{} behavior %properties\r\n  (\\textsection\\ref{sec:logic}),\r\n\r\n\\item is implementable on \\armeight/\\tso\\ {\\em without} extra synchronization for\r\n  relaxed access\\nofootnote{Compilation to \\armseven\\ or \\ppc\\\r\n    requires extra synchronization.} (\\textsection\\ref{sec:arm}), and\r\n\r\n\\item  satisfies the \\emph{local} \\drfsc\\ criterion \\cite{Dolan:2018:BDR:3192366.3192421} (\\textsection\\ref{sec:sc}).\r\n\r\n\\end{itemize}\r\nWe conclude by discussing relating work (\\textsection\\ref{sec:related}) and limitations (\\textsection\\ref{sec:limits}).\r\n\r\n\r\n\\citet{Batty17} observed that ``the current crop of relaxed memory models can\r\nonly be used to calculate the behavior of a whole program\\ldots'' and argued\r\nthat instead, we should ``consider a program as an aggregate of components\r\nover different models, composed together.''  Our work is inspired by this\r\ncall for \\emph{compositionality} in models of relaxed concurrency.\r\n\r\nOur model is compositional in the normal sense of a denotational semantics:\r\nfor example, the denotation $\\sem{C_1\\!{\\PAR}\\! C_2}$ is computed from\r\n$\\sem{C_1}$ and $\\sem{C_2}$.  The model obeys laws such as scope\r\nextrusion---$\\sem{\\aCmd\\!{\\PAR}\\! \\VAR\\aLoc\\SEMI\\bCmd} =\r\n\\sem{\\VAR\\aLoc\\SEMI(\\aCmd\\!{\\PAR}\\!\\bCmd)}$ when $\\aLoc\\not\\in\\free(\\aCmd)$---and\r\ncase analysis---$\\sem{\\aCmd} = \\sem{\\IF{\\aExp}\\THEN\\aCmd\\ELSE\\aCmd\\FI}$.\r\nThis kind of algebraic reasoning is not supported by current models.\r\n\r\nOur model also supports compositional reasoning about \\emph{data races}\r\n(\\textsection\\ref{sec:sc}), isolating races in space and time.  Spatial\r\nseparation ensures that a race on one location does not invalidate \\drfsc{}\r\nat other locations.  Temporal separation ensures that \\drfsc{} can be applied\r\nwithin a properly synchronized region, unaffected by races that precede or\r\nfollow.\r\n\r\nFinally, our model supports compositional reasoning about \\emph{temporal\r\n  safety properties} (\\textsection\\ref{sec:logic}).  Consider that each\r\nthread of \\ref{OOTA4} satisfies the following invariant: \\emph{A write of $1$\r\n  to $y$ must be preceded by a read of $1$ from $x$, and if $1$ is written to\r\n  $z$ then a write of $1$ to $x$ must be preceded by a read of $1$ from $y$.}\r\nCompositionality allows us to conclude that whole program satisfies this\r\nproperty.  As noted above, this reasoning \\emph{fails} in models based on\r\npromises, speculations, or commitments.\r\n%\\cite{DBLP:conf/popl/KangHLVD17,DBLP:conf/esop/JagadeesanPR10,DBLP:journals/pacmpl/ChakrabortyV19}.\r\n% demonstrating a lack of compositionality\r\nCompositionality for temporal safety is a \\emph{verifiable} criterion for claiming that a model\r\nrejects \\oota{} executions.\r\n% define $\\notar$ to be the ability to combine thread local reasoning and\r\n% compositionally prove temporal safety properties.\r\n\r\n\r\n\r\n\r\n% The executions of a program are computed compositionally, by induction on the\r\n% structure of the program.  Thus, our model falls into the style of relaxed\r\n% memory models advocated by~\\citet{Batty17}.  Combined with a single global\r\n% order on events, compositionality helps explain how our model disallows\r\n% \\oota{} execution.  After all, compositionality states that parallel\r\n% composition does not create unexpected\r\n% behaviors.  % The fact that the dependency relation is a partial order forbids\r\n% % \\oota\\ behaviors.  \r\n% % The simplest \\oota{} litmus test is the following variant of \\eqref{OOTA?}\r\n% % and \\ref{OOTA1}---without $z$ or\r\n% % the conditional.  Again all memory locations are initialized to $0$:\r\n% % % asks whether either of the following threads\r\n% % % can see non-zero values:\r\n% % \\begin{gather*}\r\n% %   \\tag{\\ref{OOTA3}}\r\n% %   %\\PW{x}{0}\\SEMI \\PW{y}{0}\\SEMI\r\n% %   %(\\bLoc \\GETS \\aLoc \\PAR \\aLoc \\GETS \\bLoc)\r\n% %   \\bLoc \\GETS \\aLoc \\PAR \\PR{y}{r}\\SEMI \\PW{x}{r}  \r\n% % \\end{gather*}\r\n% We rule out $z=1$ in \\ref{OOTA3}--\\ref{OOTA4} as follows: The write of\r\n% $\\bLoc$ on the left hand side is dependent on the read to $\\aLoc$.  If the\r\n% program writes $z$, then the write of $\\aLoc$ on the right is dependent on\r\n% the read to $\\bLoc$.  Since a non-zero read can only be satisfied externally,\r\n% both reads are part of the dependency order, leading to a cycle.  Such a\r\n% cycle contradicts the assumption that dependency forms a partial order.  We\r\n% formalize this argument in \\textsection\\ref{sec:logic}.\r\n\r\n\r\n\r\n\r\n% In the main paper, we present the model, examples, the results concerning\r\n% compositional reasoning  and optimization, and a discussion of\r\n% related work.  \r\n%The details of \\armeight/\\tso-compilation may be found in the appendix.\r\n\r\n% On the last point, we demonstrate a further completeness result.  Whereas the JMM aims to validate {\\em all} sequential optimizations, it is clear that is impossible.  For example, the introduction of redundant reads  but not valid concurrently. Thus, $\\aReg \\GETS \\REF{\\aLoc} \\SEMI \\IF{\\aReg != \\aReg} \\PW{\\cLoc}{1} \\FI$ cannot be replaced by $\\PR{\\aLoc}{\\aReg} \\SEMI \\PR{\\aLoc}{\\bReg}  \\SEMI \r\n% \\IF{\\aReg != \\bReg} \\THEN \\PW{\\cLoc}{1} \\FI$.  \r\n\r\n% Our model does the best possible under these constraints.   Call a program fragment ``linear'' if it does at most one read and at most one write on any location in any execution.  Thus, the context is unable to interfere with the atomic execution of the command; dually, neither can the atomic execution of the command interfere with the context.  We show that if sequential and synchronization free $\\aCmd$ and $\\bCmd$ are sequentially equivalent, and furthermore $\\bCmd$ is ``'linear'' in this sense, then $\\aCmd$ can be validly replaced by $\\bCmd$.  \r\n% Similarly, for redundant writes; $\\PW{\\aLoc}{1}$ cannot be \r\n% replaced by $\\PW{\\aLoc}{1} \\SEMI \\PW{\\aLoc}{1} $ in a model \r\n% with coherence.\r\n\r\n\r\n\r\n\r\n\r\n%\\paragraph*{Rest of the paper. }  We begin with an informal introduction to the modeling ideas in \\textsection\\ref{sec:model:intro}, developing the precise formalities in \\textsection\\ref{sec:model}.   \\textsection\\ref{sec:sc} proves the DRF theorem, whereas \\textsection\\ref{sec:arm} provides a compilation into \\armeight\\ and \\tso.  Single threaded optimizations, and the associated completeness theorems are addressed in \\textsection\\ref{sec:opt}.  \\textsection\\ref{sec:logic} describes a temporal logic, and a compositional proof principle for proving safety properties.  \\textsection\\ref{sec:examples}.develops more illustrative examples.  We address related work in \\textsection\\ref{sec:ldrf} and conclude after.  An appendix contains details of proofs and further examples.\r\n\r\n% We give an informal introduction to the model in \\textsection\\ref{sec:model:intro} before presenting the precise formalities in \\textsection\\ref{sec:model}.\r\n% \\textsection\\ref{sec:sc} proves the DRF theorem, whereas \\textsection\\ref{sec:arm} provides a compilation into \\armeight\\ and \\tso.  Single threaded optimizations, and the associated completeness theorems are addressed in \\textsection\\ref{sec:opt}.  \\textsection\\ref{sec:logic} describes a temporal logic, and a compositional proof principle for proving safety properties.\r\n% We %present additional examples in \\textsection\\ref{sec:examples} and\r\n% end with\r\n% a discussion of related work in \\textsection\\ref{sec:ldrf}.\r\n% An appendix\r\n% contains details of proofs and further examples.\r\n\r\n\r\n\\endinput\r\n\r\nTo the reader interested in models that forbid load buffering, we provide a way to adapt our model to forbid the relaxing of the program order from reads to writes, thus modeling~\\cite{Dolan:2018:BDR:3192366.3192421,BoehmOOTA}.  Our new contributions for such a reader are an approach to validating data-sensitive compiler optimizations and compositional reasoning of temporal properties.   \r\n\r\n\r\nWe illustrate the last criterion with two examples.   \r\nFirst, consider the well-known ``Out Of Thin Air'' (\\oota) litmus test, with all variables initialized to $0$:\r\n\\begin{equation}\r\n  %\\PW{x}{0}\\SEMI \\PW{y}{0}\\SEMI\r\n  (\\PW{y}{x} \\PAR \\PW{x}{y})\r\n\\end{equation}\r\nInformally, both threads satisfy the invariant that conjoins ``A write of 1  to x  requires a prior read  of 1 from y'' and ``A write of 1  to y  requires a prior read  of 1 from x ''.  If composition holds, the full program satisfies the invariant.  Since the variable declaration closes the program from other writes to $x,y$, we  deduce the conjunction of  ``A write of 1  to x  requires a prior write  of 1 to x'' and ``A write of 1  to y  requires a prior write  of 1 from x'' . Thus, we deduce that ``A write of 1  to x  requires a prior write  of 1 to x'', and consequently ``there is no write of 1 to x''. \r\n\r\nprovides an  {\\em objectively  falsifiable} measurement of \\oota\\ in a memory model. \r\n\r\n\r\n\r\n", "meta": {"hexsha": "3250d8298d7500a5a58a231c4077304eecbea874", "size": 31618, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "intro.tex", "max_stars_repo_name": "chicago-relaxed-memory/memory-model", "max_stars_repo_head_hexsha": "fd606fdb6a04685d9bb0bee61a5641e4623b10be", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-08-13T02:36:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-25T12:46:13.000Z", "max_issues_repo_path": "intro.tex", "max_issues_repo_name": "chicago-relaxed-memory/memory-model", "max_issues_repo_head_hexsha": "fd606fdb6a04685d9bb0bee61a5641e4623b10be", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "intro.tex", "max_forks_repo_name": "chicago-relaxed-memory/memory-model", "max_forks_repo_head_hexsha": "fd606fdb6a04685d9bb0bee61a5641e4623b10be", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.9610619469, "max_line_length": 782, "alphanum_fraction": 0.7283825669, "num_tokens": 9399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3396653319985615}}
{"text": "\n\\chapter{Analysis}\n\nIn this section, we analyse \\zclaim from different perspectives.\nIn \\cref{sec:sec_analysis}, we show that the protocol fulfills certain properties under which we consider it to be secure.\n\nIn \\cref{sec:attack_vs}, we present several common attack vectors on blockchain protocols and discuss their (in-)feasibility on \\zclaim, providing thresh\\-old parameters guaranteeing the security of the system where appropriate.\n\nFinally, in \\cref{sec:privacy}, we analyse privacy concerns related to the vault intermediary system.\n\n\n\\section{Security analysis}\n\\label{sec:sec_analysis}\n\nIn this section, we present a set of properties under which \\zclaim is considered secure.\nWe specify the conditions that need to hold in order to attain each of these properties.\nFinally, we show that \\zclaim satisfies these conditions.\n\nWe presuppose the proper choice of security parameters $k^I$, $k^B$, $\\Delta^I$ and $\\Delta^B$ as discussed in \\cref{sec:setup} and the security of the Zcash/Zerocash protocol, which has been extensively shown in~\\cite{sasson2014zerocash}.\nWe also assume that the relay system is secure and that if a block header is accepted by the relay system, the possibility of a future chain reorganisation is vanishingly low.\n\n\\subsection{Notation}\n\nWe denote any participant in the protocol by $P \\in \\mathcal{P}$, who may be a vault $V \\in \\mathcal{V}$ or a user $U \\in \\mathcal{U}$ taking on the role of issuer or redeemer.\nThe amount of currency X of any of the backing currency Zcash (ZEC), the issuing chain's native currency (\\emph{ICN}) and the issued currency (\\emph{ICZ}) that a participant can spend is denoted by $X(P)$, e.g.\\ $ICN(U)$, to which we may refer to as $U$'s ICN \\emph{balance}.\nSpecifically, $ZEC(P)$ is the sum of the value of all unspent Zcash notes of which $P$ has knowledge containing $\\dpa_P$, the diversified payment address associated with $P$.\nSame goes for ICZ.\nFunds locked as collateral by participant $P$ are denoted by $X^{col}(P)$.\n\nIn addition to the aforementioned balances, $ZEC^{obl}(V)$ are the \\emph{ZEC obligations} associated with vault $V$ and is defined as the sum of the ZEC value of all (hidden) amounts of ICZ issued or redeemed in \\mint and \\burn transactions facilitated by $V$.\nThis also represents the amount that vaults can release to redeemers and does not reflect their ZEC balance, since $ZEC(V)$ includes the fees accumulated by $V$ in past transactions while $ZEC^{obl}(V)$ does not.\nFurthermore, it is not possible to verify that $ZEC(V)$ matches $ZEC^{obl}(V)$ in any way as $V$ may perform arbitrary shielded transactions at any time.\n\nUpon submission of a valid POB (or similarly for POCs), in which a vault proves in zero knowledge that $c \\geq ZEC^{obl}(V) \\cdot \\xr \\cdot \\sstd$ where $c \\leq ICN^{col}(V)$, $V$ is said to have some \\emph{blocked collateral} $ICN^{bcol}(V) = ZEC^{obl}(V) \\cdot \\xr \\cdot \\sstd$ and some free collateral $ICN^{fcol}(V) = c - ICN^{bcol}(V)$.\nThe vault's blocked collateral are the funds backing their ZEC obligations, which they can only decrease by releasing funds to users (or by burning ICZ, see discussion on rebalancing in \\cref{sec:rebalancing_exit}).\n\n$X_t(P)$ denotes P's balance at time $t$, where one step in time corresponds to a transaction on I.\n$ZEC_t(P)$ is not defined.\n\nFinally, $\\xr_t$ denotes the latest ZEC to ICN exchange rate as provided by the exchange rate oracle \\oxr at time $t$, where 1 ZEC = $\\xr_t$ ICN.\nWe assume a 1:1 peg between the issued currency and the backing currency, i.e.\\ 1 ZEC = 1 ICZ.\n\n\\subsection{Goals}\n\\label{sec:security_goals}\n\nWe deem \\zclaim \\emph{secure} if it achieves the following properties:\n\\begin{itemize}\n    \\item \\textbf{Soundness} The amount of issued currency in circulation is equal to the amount of ZEC obligations, i.e.\\ for all $t \\geq 0$\n    \\begin{equation}\\label{eq:icz_equals_obl}\n        \\sum_{U \\in \\mathcal{U}} ICZ_t(U) = \\sum_{V \\in \\mathcal{V}} ZEC^{obl}_t(V)\n    \\end{equation}\n    and $ZEC^{obl}(V)$ is derived from protocol transactions to and from $V$ on Zcash.\n    Specifically,\n    \\begin{lemma}\\label{le:lock_before_mint}\n        For every Mint transfer of (hidden) value $\\val_{IM}$ on I containing $\\dpa_V$ as the vault's diversified payment address, there is an Output transfer on Zcash creating a note of value $\\val_Z$ to $\\dpa_V$ s.t.\n        \\begin{equation}\n            \\left \\lfloor{\\val_Z \\cdot (1 - f)}\\right \\rfloor = \\val_{IM}\n        \\end{equation}\n    \\end{lemma}\n    and\n    \\begin{lemma}\\label{le:release_before_burn}\n        For every Burn transfer of value $\\val_{IB}$ on I containing $\\dpa_V$ as the vault's diversified payment address and $\\cm_Z$ as the requested release note commitment, there is an Output transfer on Zcash creating a note of value $\\val_Z$ with note commitment $\\cm_Z$ s.t.\n        \\begin{equation}\n            \\val_Z = \\left \\lfloor{\\val_{IB} \\cdot (1 - f)}\\right \\rfloor\n        \\end{equation}\n    \\end{lemma}\n    according to the fee policy defined in \\cref{sec:fees}.\n    \n    These are the transfers that make up a vault's ZEC obligations, and evidently the sum of all Mint transfers minus all Burn transfers is equal to the circulating supply.\n    Hence \\cref{eq:icz_equals_obl} is in fact satisfied by the definition of $ZEC^{obl}(V)$.\n   \n    \\item \\textbf{Coverage} The total amount of ZEC obligations are backed by a proportional amount of the issuing chain's native currency according to the prevailing exchange rate, i.e.\\ for all $t \\geq 0$\n    \\begin{equation}\\label{eq:coverage}\n        \\left(\\sum_{V \\in \\mathcal{V}} ZEC^{obl}_t(V)\\right) \\cdot \\xr_t \\cdot \\smin \\leq \\sum_{V \\in \\mathcal{V}} ICN^{bcol}_t(V)\n    \\end{equation}\n    where $\\smin$ is the minimum collateralisation ratio as defined in \\cref{sec:constants}.\n    \n    \\item \\textbf{Fairness} An honest participant following best practices will not incur any loss of funds as long as they can receive and broadcast transactions from and to chains Z and I.\n    \n    For the condition on this claim, availability of both chains must be guaranteed, which we derive from the security assumption of \\xclaim that transactions broadcast by users are received by (honest) consensus participants within a known maximum delay $\\Delta_{tx}$.\n    In case of network failure for a significant amount of time on the user/vault side, they may in effect incur loss of funds.\n    It is thus the participants' responsibility to ensure they remain online throughout the duration of a subprotocol.\n\n    As for the claim itself, we examine the cases where a participant may incur loss of funds.\n    This risk exists both in the issue and redeem subprotocols.\n    We concern ourselves with transactions that incur a change in any of the balances of the two parties involved (except for slashing, which we cover separately) i.e.\\ in which a monetary transaction takes place.\n    These are, on the one hand, \\lock and \\release transactions, and on the other, \\mint and \\burn transactions.\n    \n    Concerning the issue subprotocol, the following statements must be proven:\n    \\begin{lemma}\\label{le:mint_after_lock}\n        After executing a lock operation, a user is able to mint the locked amount minus fees of ICZ.\n    \\end{lemma}\n    \\begin{lemma}\\label{le:lock_before_mint2}\n        If a \\mint transaction involving a vault $V$ is confirmed on I (thus increasing their ZEC obligations), $V$ has received the amount being minted plus fees in a previous \\lock transaction.\n    \\end{lemma}\n    Note that \\cref{le:lock_before_mint2} is equivalent to \\cref{le:lock_before_mint} with the added requirement that $V$ must have knowledge of the note values.\n    \n    Analogously, for redeeming we must show that:\n    \\begin{lemma}\\label{le:burn_after_release}\n        After executing a release operation, a vault is able to trigger the inclusion of an associated pending \\burn transaction decreasing their ZEC obligations by the released amount plus fees.\n    \\end{lemma}\n    \\begin{lemma}\\label{le:release_before_burn2}\n        If a \\burn transaction involving a user $U$ is confirmed on I, $U$ has received the amount being burned minus fees in ZEC in a previous \\release transaction.\n    \\end{lemma}\n    Again, \\cref{le:release_before_burn2} is tantamount to \\cref{le:release_before_burn} with addition of the knowledge requirement.\n    \n    Consideration must additionally be paid to the slashing mechanism, in order to ensure that slashing of an honest party cannot be instigated by a malicious one.\n\n    Finally, we provide a set of practices that vaults may follow in order to prevent liquidation and hence loss of funds.\n\\end{itemize}\n\n\\subsection{Argumentation}\n\nWe show that \\cref{le:lock_before_mint,le:release_before_burn} are always satisfied and, furthermore, that the recipients of the Zcash notes referenced therein have knowledge of the note values, hence satisfying \\cref{le:lock_before_mint2,le:release_before_burn2}.\nFurther, we cover \\cref{le:mint_after_lock,le:burn_after_release}, and show the validity of \\cref{eq:coverage}.\nFinally we discuss slashing and liquidation.\n\n\\subsubsection{Issuing}\n\nThe zk-SNARK $\\pim$ in Mint transfers as defined in \\cref{sec:mint} guarantees that \\cref{le:lock_before_mint} holds through the \\textbf{Note commitment integrity} condition together with the Merkle path validity success requirement (there exists such a note on Zcash), and the \\textbf{Locked value}, \\textbf{Minted value} and \\textbf{Fee rounding commitment integrity} conditions (the note has the specified value).\n\nMint transfers also satisfy \\cref{le:mint_after_lock} through \\textbf{Trapdoor commitment integrity}, which guarantees that only the user that authored the \\lock transaction can create a \\mint transaction.\n\nFurthermore, the challenge mechanism guarantees that the vault has knowledge of the note values, satisfying \\cref{le:lock_before_mint2}, since \\mint transactions will only be included on I if they are not successfully challenged.\nThe vault can challenge the pending transaction through disclosure of the shared secret, proven to be correct in $\\pic$.\nIf the note values have not been correctly encrypted to the vault, the transaction will be discarded, which ensures \\textbf{Fairness}.\n\nSo far we have proven \\cref{le:lock_before_mint,le:mint_after_lock,le:lock_before_mint2}.\n\n\\subsubsection{Redeeming}\n\nEqually, the conjunction of $\\pib$ as defined in \\cref{sec:burn} and the \\confirmRedeem transaction guarantees that \\cref{le:release_before_burn} holds through the conditions in \\pib and the Merkle path validity success requirement of \\confirmRedeem transactions.\n\n\\Cref{le:burn_after_release} is rather trivial as all it takes is to provide a Merkle path showing the existence of the note commitment in the note commitment tree, which not only the vault but any participant can do.\n\nAs for redeeming, the challenge mechanism works somewhat differently: it is the recipient of the note (the redeemer) who constructs it, and the sender must have knowledge of the values in order to be able to create it.\nThus \\cref{le:release_before_burn2} is satisfied by construction, and we can move on to the challenge mechanism: in this case, it serves to ensure the vault has received the correct note values.\n\nA vault may successfully challenge the transaction if and only if the provided note commitment cannot be generated from the decrypted values, thus it cannot punish honest redeemers but also a redeemer cannot ask a vault to release a note it cannot create, causing it to be slashed.\nHence \\textbf{Fairness} is ensured when redeeming too.\n\nNow, we have also proven \\cref{le:release_before_burn,le:burn_after_release,le:release_before_burn2}, in addition to \\cref{le:lock_before_mint,le:mint_after_lock,le:lock_before_mint2} from before, which concludes the proof for \\textbf{Soundness}.\nIt remains to prove \\textbf{Coverage} and to discuss loss of funds in liquidations and challenge operations.\n\n\\subsubsection{Proofs of balance}\n\nFrom \\cref{eq:coverage} it is evident that if we can show that \n\\[\n    ZEC^{obl}_t(V) \\cdot \\xr_t \\cdot \\smin \\leq ICN^{bcol}_t(V)\n\\]\nfor any vault, then~\\eqref{eq:coverage} holds for the entire system.\n\nWe recall here that $ICN^{bcol}(V) = ZEC^{obl}(V) \\cdot \\xr \\cdot \\sstd$, which nevertheless only holds for some $\\xr$ used in the POB.\nWe shall denote this exchange rate by $\\xr_V$.\n\nTechnically, it also only holds for $ZEC^{obl}(V)$ at the time of its last POB, though the only problematic case is that in which a vault's ZEC obligations increase since that time, i.e.\\ they issue funds.\n\nHowever, vaults may only become available to issue by submitting a POC (and must provide POCs instead of POBs until issuing is completed), in which they prove collateralisation for their ZEC obligations plus the maximum amount they can issue in one round.\nThus we may assume without loss of generality that $ZEC^{obl}(V)$ stays constant.\n\nFor any $\\xr_t > \\xr_V$ then it must hold that\n\\[\n    ZEC^{obl}(V) \\cdot \\xr_t \\cdot \\smin \\leq ZEC^{obl}(V) \\cdot \\xr_V \\cdot \\sstd\n\\]\n\\[\n    \\xr_t \\cdot \\smin \\leq \\xr_V \\cdot \\sstd\n\\]\nwhich is the liquidation trigger as defined in \\cref{sec:liquidation}.\n\nLiquidation reduces $V$'s ZEC obligations until they meet \\sstd again as described in the aforementioned section.\n\nThus we see that~\\eqref{eq:coverage} does indeed always hold and is enforced by reducing the circulating supply if needed through liquidation auctions.\nThis concludes the proof for the \\textbf{Coverage} property.\n\n\\subsubsection{Challenging}\n\nChallenge operations result in the challenged party's warranty collateral $ICN_w$ being transferred to the challenging party if successful (for vaults, this amount is deducted from their staked collateral).\nHowever, by definition these are only successful if the note plaintext in the challenged transaction has not been correctly encrypted to the challenger.\nThus it is not possible to cause loss of funds through these operations to an honest participant that adheres to the protocol.\n\n\\subsubsection{Liquidation}\n\\label{sec:analysis_liquidation}\n\nIn the event of liquidation, vaults are effectively slashed the liquidation penalty on the funds sold through the liquidation auction.\nThe amount of funds sold depends on the collateralisation constants and is always a fixed fraction of the vault's total collateral.\n\nAs mentioned in \\cref{sec:liquidation}, with the collateralisation constants as suggested, liquidation is triggered on a vault if the exchange rate increases by 33\\% with respect to $\\xr_{V}$, the last exchange rate they used in a proof of balance.\n\nIn order to avoid liquidation, $V$ needs to provide a POB using a higher $\\xr$ before the aforementioned threshold is reached.\nIf at any time $t$ where $T_{p} < t < T_{liq}$ and $\\xr_{V} < \\xr_t < \\xr_{T_{liq}}$, it holds that\n\\begin{equation}\\label{eq:pob_requirement}\n    ZEC^{obl}_t(V) \\cdot \\xr_t \\cdot \\sstd \\leq ICN^{col}_t(V)\n\\end{equation}\nthe vault can submit a new POB using $\\xr_t$, hence avoiding liquidation at $T_{liq}$.\nNaturally, this holds for later steps in time: if the exchange rate further increases, the vault will need to continue providing POBs in order to protect themselves from liquidation.\nVaults should choose a sensible $\\xr_t > \\xr_{V}$ for which to submit a new POB before they approach the liquidation threshold.\n\nHowever, if \\cref{eq:pob_requirement} is no longer satisfied, i.e.\\ the change in the exchange rate at time $t$ has caused $V$'s collateralisation rate to fall below $\\sstd$, $V$ first needs to top up their collateral or rebalance in order to be able to submit a POB using $\\xr_t$.\n\nIf they hold ICN such that $ZEC^{obl}_t(V) \\cdot \\xr_t \\cdot \\sstd \\leq ICN^{col}_t(V) + ICN_t(V)$, this is straightforward (barring the case where the exchange rate further increases such that \\cref{eq:pob_requirement} again does not hold after collateral has been topped up) and is accomplished in the time it takes the vault to construct the two transactions and forward them to the network, which is negligible.\n\nHowever, if this is not the case, $V$ may first have to acquire some $ICN$ to top up their collateral such that they can again submit a POB.\nHow long it takes them to do so depends on many external factors, but it may plausibly be up to several days: they may first have to procure liquid assets, transfer them to an exchange, trade them for ICN, withdraw the ICN from the exchange and finally lock them as collateral.\nIn this case, it may be fair to say that all is lost and vaults should follow best practices in order to avoid this sort of situation.\n\nAnother option vaults have to satisfy \\cref{eq:pob_requirement} is to rebalance, but this is a strictly longer process than topping up their collateral since it also requires ICN and one further transaction on $I$, but also exchanging ICN for ICZ.\nThus if the goal is for them to protect themselves from liquidation as fast as possible, they should always choose to top up.\nIn addition to this, vaults may choose to start rebalancing such that they do not need to top up again if the exchange rate further increases or that they may unlock some collateral again.\n\nBest practices vaults can follow in order to protect themselves from liquidation may thus include:\n\\begin{itemize}\n    \\item Maintaining a collateralisation rate somewhat higher than $\\sstd$, i.e.\\ overcollateralising, by strategically advertising themselves only to issue or redeem, rebalancing or increasing their collateral when necessary.\n    For example, $\\sigma_{sft} = 2$.\n    \\item Holding some amount of ICN not locked as collateral that they may use to top up their collateral or rebalance, or ensuring that they may acquire such amount quickly in case of emergency.\n    \\item Submitting POBs to address changes in the exchange rate above a certain threshold $r_{\\xr} = \\frac{\\xr_t}{\\xr_V}$.\n    This should be a value close to $1.0$, e.g.\\ $r_{\\xr} \\leq 1.05$.\n\\end{itemize}\n\nVaults may modify these parameters according to their risk tolerance, but with the suggested values we observe that for liquidation to be triggered it would be necessary that $\\frac{\\xr_t}{\\xr_V} > \\frac{\\sigma_{sft}}{\\smin} - r_{\\xr} \\approx 1.62$ i.e.\\ the exchange rate increases by 62\\% before $V$ is able to acquire new funds or rebalance.\n\nSuch a dramatic increase is unlikely to happen in a short time window, but in the context of cryptocurrencies, where high volatility is the norm rather than the exception~\\cite{Lahmiri2018LongrangeMDvolatility,CAPORALE2019143volatility}, it is impossible to set a definite threshold for the increase in the exchange rate above which the likelihood of it taking place is insignificant.\nUltimately, it is left to vaults to assess the risks themselves.\n\nFinally, liquidation may also be triggered if a vault fails to comply with issue or redeem requests too often, which should however not happen under the availability assumptions of participants under which \\textbf{Fairness} applies.\n\nThus if we make the assumption that \\xr will not increase fast enough to trigger liquidation on vaults following best practices, this concludes the argumentation in favour of \\textbf{Fairness}.\n\n\\section{Attack vectors and points of failure}\n\\label{sec:attack_vs}\n\nWe discuss here a range of attacks and points of failure in \\zclaim and offer mitigation strategies.\nFamiliarity with the security analysis of \\xclaim~\\cite[Section~VII]{zamyatin2019xclaim} is assumed.\nWhere not specified otherwise, the discussion on specific vulnerabilities offered there also holds for \\zclaim.\n\n\\subsection{Inference attacks}\n\\label{sec:inference_attacks}\n\nAs discussed in \\cref{sec:privacy}, vaults may guess the users' identity through the amounts in \\lock and \\release transactions in which they are involved.\nThe knowledge of this amount is of course per se insufficient to this end, but it can lay the ground for an inference attack leading to de-anonymisation if combined with other information they may have access to.\n\nFor instance, if an easily identifiable amount a user locks with a vault matches a recent transparent-to-shielded transaction on Zcash, the vault may deduce that there is a high likelihood those two transactions were performed by the same user.\nThis is similar to the heuristic used by \\textcite{quesnelle2017linkability} to identify what he calls \\textcquote[1]{quesnelle2017linkability}{round-trip transactions, where the same, or nearly the same number of coins are sent from a transparent address, to a shielded address, and back again to a transparent address. [He argues that] such behavior exhibits high linkability, especially when they occur nearby temporally}.\nIf the vault is correct in their assumption, they may be able to infer the user's identity from previous and future activity associated with the disclosed transparent address.\n\nAnother possibility is the case where a vault has privileged access to other information on one or many users, such as through data from a cryptocurrency exchange.\nThis may render them capable of effortlessly matching the real-world identities of exchange users with specific \\lock or \\release transactions if, for example, the guessed/observed amount matches a recent withdrawal from the exchange.\n\nIn both of these scenarios, an attacker may leverage this information to attempt extortion or defamation of the involved parties.\n\nThe splitting strategy defined in \\cref{sec:splitting_strategy} aims to prevent this sort of attacks.\n\\zclaim's privacy has been analysed in this context in \\cref{sec:privacy}.\n\n\\subsection{Chain relay poisoning}\n\\label{sec:relay_poisoning}\n\nChain relay poisoning involves an adversary triggering a chain reorganisation, or \\emph{reorg} for short, of $N \\geq k^B$ such that a previously accepted transaction at depth $N$ is invalidated.\nThis is known as an $N$-confirmation double spend and yields similarities to selfish mining~\\cite{eyal2014majority} in that it involves misleading honest nodes through an amassing of computational power.\n\nWe recall here that the security parameter $k^B$ is based on the assumption that an adversary's computational power is bounded by $\\alpha \\leq 33\\%$ and denotes the depth at which the likelihood of an adversary triggering a reorg is negligible.\n\nHowever, in \\xclaim a poisoning attack may be successful well below this threshold $\\alpha$ if the relay system is deprived of recent block header data~\\cite[Section VII-A]{zamyatin2019xclaim}.\n\nWe expand here on this observation.\nThis is in fact a common vulnerability to cross-chain interoperability schemes and is not only the case if the relay system is devoid of real-world data~\\cite{2017hijackingbtc}, but may involve more intricate attacks in which \\emph{relayers} are isolated from the rest of their peers in the network and misled to accept the attacker's chain as the longest.\nThis is more commonly known as an eclipse attack~\\cite{heilman2015eclipse}.\n\nSuch attacks along with mitigation strategies have been discussed previously in the literature~\\cite{heilman2015eclipse,wust2016ethereum,xu2020eclipsed,alangot2020decentralized}, and we refer the reader in particular to analyses on Bitcoin and Bitcoin-based blockchains (such as Zcash is) for mitigation strategies~\\cite{heilman2015eclipse,alangot2020decentralized}.\n\n\\subsection{Exchange rate poisoning}\n\\label{sec:er_poisoning}\n\nSimilarly, if \\oxr is manipulated to provide an erroneous price feed, this may allow a prepared adversary to steal funds in several ways.\n\nFor instance, an exchange rate much higher than the actual value would allow vaults to issue ZEC or unlock collateral such that they become undercollateralised when the exchange rate returns to normal.\nAn economically rational vault would have no incentive to bring back their collateralisation rate above the safety value and may choose to undergo liquidation and retain the ZEC for which they hold obligations, effectively violating \\textbf{Soundness} and jeopardising the stability of the protocol.\n\nOn the other hand, an artificially low exchange rate may trigger mass liquidation and allow users to buy vaults' collateral at an unfair price, hence stealing funds from them.\n\nIt is thus of paramount importance to guarantee the reliability of the exchange rate oracle.\nBlockchain oracles aim to solve this exact problem~\\cite{peterson2015augur,8726819astraea,ellis2017chainlink}, aggregating exchange rates from different sources, leveraging economic incentives to reinforce the veracity of these sources and providing dispute mechanisms in case of discrepancies.\nThese systems are, without question, safer than relying on a single source to provide an exchange rate, though they may still fail under certain circumstances~\\cite{lo2020reliabilityoracles}.\n\nFurther measures can be taken to prevent such an attack, such as sanitising data provided by the oracle or employing so-called circuit breakers~\\cite{2019circuitbreakers}, which involve halting operations in case of unusual price movements.\n\nLastly, it must be noted that relying on a decentralised oracle constitutes a further cross-chain integration and as such opens another door to poisoning attacks as discussed in the previous section, which can be addressed through the same countermeasures.\n\n\\subsection{Replay attacks on inclusion proofs}\n\n\\zclaim prevents replay attacks on \\lock and \\release transaction inclusion proofs, in which a user reuses a past \\lock transaction to mint ICZ or a vault reuses a \\release transaction to decrease their ZEC obligations, stealing funds from the other party, as follows.\n\nThe nonce $\\nlock$ provided by the issuing chain in lock permits must be used to generate the note commitment trapdoor in \\lock transactions as specified in \\cref{sec:lock}, which is enforced in the zero knowledge proof in Mint transfers $\\pim$ through the \\textbf{Trapdoor commitment integrity} condition.\nThis ensures that every \\lock transaction is uniquely associated with the corresponding Issue procedure.\n\nAs for \\release transactions, protection from replay attacks is implicit since the note commitment is generated in advance by the redeemer.\nTherefore a vault can only replay a release inclusion proof if the redeemer has chosen the same note values, most notably the same note commitment trapdoor \\rcm as in a previous Burn transfer.\n\nHowever, the likelihood of the same trapdoor being sampled twice randomly from $\\ncm.\\gent$ as specified in \\cref{sec:release} is insignificant.\nIf a redeemer purposely reuses the same note values, they only derive negative utility from their actions.\n\n\\subsection{Counterfeiting}\n\\label{sec:counterfeiting}\n\nIn \\xclaim, counterfeiting is defined as the issuing of issued currency that is not backed by funds locked with vaults.\nThis is enforced through the principle of \\textbf{Auditability}.\nIn a nutshell, since the vaults' actions are observable by anyone, a vault removing funds from the pool of funds locked with them can be reported and will be punished by slashing their collateral as a consequence.\nThis also includes vaults reusing these funds to mint more issued currency.\n\nIt is here that a central difference between \\zclaim and \\xclaim arises: we do not make such restriction.\nInstead, \\textbf{Coverage} and \\textbf{Soundness} guarantee that the total amount of issued currency in circulation is always backed by an equivalent amount of the vaults' collateral.\nA vault may very well reuse ZEC locked with them to issue more ICZ; they will still be unable to unlock their collateral until they have released ZEC to redeemers or burnt ICZ themselves.\n\nCounterfeiting would hence imply issuing ICZ which is not locked by ICN, which is impossible as per the aforementioned properties.\n\n\n\\todo{%\\subsection{Composability attacks}\nWould like to get this in here}\n%~\\cite{zindros_2019summa,zamyatin2019sok}\n%higher potential gain extracted from attack\n%together w/ relay  poisoning attacks\n%k chosen with respect to financial cost of carrying out an attack larger than benefit?\n%consider case where \\zclaim is instantiated on two different chains\n\n\\subsection{Extortion}\nExtortion by vaults, which would involve vaults setting extreme fees to redeem hence making it unfeasible, is prevented in \\zclaim under the suggested fee policy, which defines a fixed fee for both the issue and redeem procedures.\n\n\\subsection{Black swan events}\n\\label{sec:black_swan}\nA black swan event is an extremely rare event with potentially catastrophic consequences for parties exposed to a previously unknown or neglected risk.\n\nIn a financial setting, this term is usually employed to describe a severe market-wide crash or extreme, sudden devaluation of an asset due to unforeseen circumstances.\n\nSuch events are a rather common occurrence in the cryptocurrency space~\\cite{fry2016negative,sophonex_2019blackswan}, perhaps challenging their definition.\nThis is due to several factors, foremost the speculative nature of cryptocurrencies~\\cite{cheah2015speculative} and the prevailing high volatility in their valuation.\nFurthermore, even though advances in blockchain technology are made at a rapid pace, the technology is still in its early stages and as such is susceptible to attacks and exploits of varying nature.\nFinally, the regulatory framework surrounding cryptocurrencies is still being developed in many countries~\\cite{loc2018regulation} and is a hot topic of debate~\\cite{yeung2019regulation}, as it may facilitate the widespread adoption of certain types of cryptocurrencies while hindering the development of others.\n\nThis is to say that the chance of sudden, extreme devaluation of either one of Zcash or the issuing currency is non-negligible and must be kept in mind.\nIn case of a drop in the valuation of Zcash, \\zclaim would continue to operate normally and it is quite clear what the consequences would be: any participant holding either ZEC or ICZ will suffer a loss unrelated to the protocol.\n\nIf, on the other hand, the issuing currency suffered this fate, the consequences would be similar to those discussed in \\cref{sec:er_poisoning} and \\zclaim would eventually no longer meet the security properties defined in \\cref{sec:security_goals}.\n\\textcite{zamyatin2019xclaim} hence assume a minimum exchange rate $\\xr_{min}$ \\textcquote[3]{zamyatin2019xclaim}{below which adhering to protocol rules no longer represents the equilibrium strategy of rational adversaries}, and a delay $\\Delta_{\\xr_{min}} < \\Delta^I$ such that honest participants can include a transaction on I before this threshold is reached.\nHowever, it remains unclear what strategy participants may follow in order to avoid financial loss in this situation.\n\n\n\\section{Privacy against vaults}\n\\label{sec:privacy}\n\nWe argue that the monetary values of transactions in which vaults are involved do not leak the total value prior to splitting.\nWe also consider the information they may learn by observing network traffic and the case where several vaults collude with each other or are operated by the same adversary.\n\nThe consequences of such information leakage are discussed in \\cref{sec:inference_attacks}.\n\n\\subsection{Adversarial model}\n\nWe assume an adversary $\\mathcal{A}$ constrained by the following assumptions:\n\\begin{itemize}\n    \\item $\\mathcal{A}$ has perfect knowledge of the \\zclaim protocol, i.e.\\ also of the splitting strategy.\n    \\item $\\mathcal{A}$ can observe transactions happening on both Zcash and $I$, but cannot filter network packets sent by individual users.\n    \\item $\\mathcal{A}$ controls no more than 1/3 of all vaults that are available to issue or redeem, independently of each other, at any given time.\n\\end{itemize}\n\n\\subsection{Obfuscation of total transacted value}\n\nUsing the splitting strategy defined in \\cref{sec:splitting_strategy}, knowledge of one or even several amounts reveals no information about the total \\vtot other than the evident fact that it is larger than the total observed value.\nIndeed, the individual amounts sent to vaults are independent of the total: the latter only determines which amounts out of the fixed set of possible values get sent.\nHence, as long as $\\mathcal{A}$ controls only a fraction of all vaults, the unknown amounts are equally distributed among all possible unobserved values.\n\nHowever, if $\\mathcal{A}$ learns the number of transactions $k$, this is no longer the case.\nWe have as per the splitting strategy that $k \\leq k_{max} = (b-1) (i_{max}-i_{min} + 1)$.\nNow, if $\\mathcal{A}$ not only has knowledge of $k_{obs}<k$ amounts but also of the value $k<k_{max}$, the odds of them deducing \\vtot increase from $(2^{k_{max}-k_{obs}})^{-1}$ to $\\left(\\binom{k_{max}-k_{obs}}{k-k_{obs}}\\right)^{-1}$, which is strictly larger and grows as $k$ approaches either $k_{max}$ or $k_{obs}$.\n\nOne approach to counter this issue is to split \\vtot into a small, random number of amounts and then apply the splitting strategy for each of these individually, such that $\\mathcal{A}$ has no knowledge of $k_{max}$ (across all amounts).\n\n\\subsection{Transaction linkability}\n\\label{sec:linkability}\n\nAs we have seen, if $\\mathcal{A}$ learns the number of transactions $k$ into which \\vtot has been split, they may gain a considerable advantage in their attempts to learn \\vtot.\n\nWe explore the circumstances under which $k$ could be leaked.\n\nThe first and most evident risk is low network traffic, as it may lead to the $k$ \\lock or \\burn transactions being submitted within a shorter delay with respect to other than other transactions on the network.\nWe note that if there is enough traffic across \\zclaim, this issue does not arise.\n\nFurthermore, this risk can be mitigated by not submitting all sub-transactions simultaneously but within a short random delay between one another.\n\nFurthermore, redeemers should use a different destination diversified payment address \\dpa per \\burn transaction, which may be derived from the same incoming viewing key.\nOtherwise, $\\mathcal{A}$ may easily link \\burn transactions with each other in which vaults controlled by $\\mathcal{A}$ are requested to redeem, hence allowing $\\mathcal{A}$ to learn the note values.\n\n\n% An adversary $\\mathcal{A}$ with perfect knowledge of the protocol (i.e.\\ also of our mitigation strategy) should not be able to guess the value \\vtot with a certain degree of confidence.\n% We assume that $\\mathcal{A}$ controls an unknown number of vaults and thus may learn any number of amounts $k_{obs} \\leq k$.\n% \\todo{Assume fraction of malicious vaults $<1/3$ and employ this assumption elsewhere in this section}\n\n% We now have to consider what it means for $\\mathcal{A}$ to guess the amount with a certain degree of confidence.\n% Assuming that $\\mathcal{A}$ knows the actual distribution of values sent through the system $P(v)$, we only care whether they can assign the original value a significantly higher probability than what could be guessed without evidence (i.e.\\ if most values sent are around $\\val_m$, and $\\mathcal{A}$ guesses a value around $\\val_m$, they will be right most of the time, but they still do not have any specific knowledge about the actual value).\n% \\todo{certain degree of confidence still not defined, significantly higher probability vague}\n\n% \\subsection{Approaches}\n\n% \\subsubsection{Uniform sampling}\n% \\todo[inline]{Shall I just get rid of the whole talk about distributions? Maybe remove uniform sampling section}\n\n% Taking a Bayesian approach, all $x_i$ that $\\mathcal{A}$ can ascribe to the same transaction constitute the evidence $X$.\n\n% The question now becomes what the distribution $P(X \\mid V)$ from which to sample the values should be, such that $P(V \\mid X) = \\frac{P(V) P(X \\mid V)}{P(X)}$ does not reveal significantly more information about the value than $P(V)$.\n\n% It is obvious that some information about the total will always be leaked through knowledge of even one of its parts; at the very least, $\\mathcal{A}$ will know that the total is equal or larger to the latter.\n% Thus the worst they can do is guessing that $P(V \\mid X = x) = P(V \\mid V \\ge x)$, i.e.\\ the prior distribution truncated to values greater than or equal to the observed value.\n\n% The larger the amount that $\\mathcal{A}$ has knowledge of, the narrower this distribution will be, revealing more information about the original value.\n% From these observations it follows that we need to set an upper bound $x_{max}$ for each term and also try to limit the number of terms $\\mathcal{A}$ may learn.\n% We suppose that we can split \\vtot into an arbitrary number of parts since the same vault can be sent multiple transactions.\n% In practice, the number of vaults should be much larger than the number of transactions into which the total is split.\n% We ignore the issue this causes with rising fees and possibly higher latency for larger amounts for the moment.\n\n% Thus we set $x_{max}$ small enough s.t.\\ $\\left. P(V) \\right|_{x}^{\\vmax} \\ge \\alpha$ for all values of $x$, where $\\alpha$ represents a significant fraction of all transactions that will always be above the observed value.\n\n% \\paragraph{Minimal example}\n\n% We assume $V$ to be distributed uniformly over the set of all possible values, i.e.\\ $V \\sim U((0, \\vmax])$, $k = 2$ and that $\\mathcal{A}$ learns one of the two values.\n\n% Now assuming $X_1$ is also sampled uniformly across all possible values s.t.\\ it is split at least once, i.e.~$X_1 \\sim U((0, v))$, we have that $X_2 = v - X_1 \\sim U((0, v))$ too and so this is a suitable distribution.\n% Here, $\\mathcal{A}$ can learn that\n% \\[\n%     P(V \\mid X_i) = \\frac{P(V) P(X_i \\mid V)}{P(X_i)} \\text{, for } i \\in \\{1, 2\\}\n% \\]\n% where $P(X_i \\mid V) = f(x_i) =\n% \\begin{cases} \n%     1/v & x_i < v\\\\ \n%     0 & x_i \\ge v\n% \\end{cases}\\,$\n% , thus\n% \\[\n%     P(V \\mid X_i)\n%     =\n%     \\frac{\\frac{1}{\\vmax} f(x_i)}{\\int_{0}^{\\vmax}\\frac{1}{\\vmax} f(x_i)dv}\n%     =\n%     \\begin{cases}\n%         \\frac{1}{v \\log{\\frac{\\vmax}{x_i}}} & v > x_i\\\\\n%         0 & v \\le x_i\n%     \\end{cases}\n% \\]\n\n% We can see that this means the total amount is always more likely to be closer to the observed value than it is to be much larger.\n% The posterior distribution also becomes flatter but narrower the larger the observed value.\n\n% This is exactly the kind of information we would like to prevent $\\mathcal{A}$ from learning.\n\n% \\paragraph{Multiple variables}\n\n% We try to answer the following question: how can we sample $k$ values from a uniform distribution such that their sum equals \\vtot?\n\n% The distribution that we are looking for is\n% \\[\n% P(X_i \\mid \\sum_{j=1}^{k} X_j = v) = \\frac{P(X_i) P(\\sum_{j=1}^{k} X_j = v \\mid X_i)}{P(\\sum_{j=1}^{k} X_j = v)}\n% \\]\n\n% If we set $X_i' = \\frac{X_i}{x_{max}}$ and $v' = \\frac{v}{x_{max}}$,\n% we can choose $X' \\sim U(0, 1)$ and this becomes for the first value\n% \\[\n%     P(X_1' = x_1' \\mid \\sum_{j=1}^{k} X_j' = v') = \\frac{P(\\sum_{j=1}^{k} X_j' = v' \\mid X_1' = x_1')}{P(\\sum_{j=1}^{k} X_j' = v')}\n% \\]\n% \\[\n%     = \\frac{P(\\sum_{j=2}^{k} X_j' = v' - x_1')}{P(\\sum_{j=1}^{k} X_j' = v')}\n% \\]\n\n% Both numerator and denominator follow an Irwin-Hall distribution, defined as the sum of a number of independent random variables each following a uniform distribution.\n% An Irwin-Hall distribution on $n$ random variables has probability density function\n% $\n%     f_X(x;n)=\\frac{1}{2(n-1)!}\\sum_{k=0}^n (-1)^k{\\binom{n}{k}} (x-k)^{n-1}\\text{sgn}(x-k)\n% $\n% thus the above distribution can be expressed as \n% \\[\n%     (k-1)\n%     \\frac{\n%         \\sum_{j=0}^{k-1} (-1)^j {\\binom{k-1}{j}} (v'-x_1'-j)^{k-2}\\text{sgn}(v'-x_1'-j)\n%     }{\n%         \\sum_{j=0}^{k} (-1)^j {\\binom{k}{j}} (v'-j)^{k-1}\\text{sgn}(v'-j)\n%     }\n% \\]\n\n% The denominator is just a normalising factor dependent on $v'$ and $k$.\n% The whole term is simply an Irwin-Hall distribution with mean $v' - \\frac{k-1}{2}$ truncated and normalised to values between 0 and 1.\n% A plot of this distribution for $v' = 5$ and different values of $k$ can be found on \\cref{fig:dists}.\\todo{Proper labels, more plots, discussion on v \\& k}\n\n\n% \\begin{figure}\n% \\centering\n% \\includegraphics[width=0.8\\textwidth]{img/distributions.png}\n% \\caption[Probability distribution of first sampled value]{Probability distribution of first sampled value $P(X_1 \\mid \\sum_{j=1}^{k} X_j = 5)$ for different values of $k$}\n% \\label{fig:dists}\n% \\end{figure}\n\n\n% For the $t$-th value, we obtain an Irwin-Hall distribution on $k-t$ random variables with mean $v' - \\sum_{j=1}^{t-1} x_j - \\frac{k-t}{2}$.\n% We have\n% \\[\n%     P(X_t' = x_t' \\mid \\sum_{j=1}^{k} X_j' = v', X_1'=x_1', ...,X_{t-1}'=x_{t-1})'\n% \\]\n% \\[\n%     = P(X_t' = x_t' \\mid \\sum_{j=t+1}^{k} X_j' = v' - \\sum_{j=1}^{t} x_j', X_1'=x_1', ..., X_{t-1}'=x_{t-1}')\n% \\]\n% \\[\n%     = \\frac{P(\\sum_{j=t+1}^{k} X_j' = v' - \\sum_{j=1}^{t} x_j')}{P(\\sum_{j=t}^{k} X_j' = v' - \\sum_{j=1}^{t-1} x_j')}\n% \\]\n\n% For $t = k$, $X_t$ converges to a single value, for $t = k-1$ it follows a uniform distribution and for $t = k-2$ a triangular distribution (as before all truncated and normalised).\n\n% \\todo[inline]{\\url{https://stackoverflow.com/a/8068956} looks like a much easier approach to this problem}\n\n% Naturally, if $\\mathcal{A}$ has knowledge of the number of transactions $k$, they will learn some information from the observed amount(s) since the distribution $P(V \\mid X)$ is a truncated Irwin-Hall distribution as discussed above.\n% \\todo{have some more work done on this but unsure whether to expand or remove altogether}\n\n%coordinate along line\n%sample from n-1-dimensional space\n%if value $k$ is unknown to adversary, the distribution of possible values would be $P(V=v) = %\\frac{\\sum_{k=m}^{n} P(\\sum_{i=1}^{k} X_i = v|X)}{n-m + 1}$, where $m=\\left %\\lceil{\\frac{v-\\sum_{x_i \\in X} x_i}{\\vmax}}\\right \\rceil + |X|$ and $n=\\left %\\lfloor{\\frac{v-\\sum_{x_i \\in X} x_i}{\\val_{min}}}\\right \\rfloor + |X|$, a sum of I-H %distributions across a larger set of possible values for \\vtot.\n%We do not try to analyse this distribution...\n", "meta": {"hexsha": "f45bf9a5cf5169f402a8aa508982ef4d70f0b0cb", "size": 41953, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "sections/analysis.tex", "max_stars_repo_name": "alxs/zclaim", "max_stars_repo_head_hexsha": "727b74ded4373c76e7e649b884d4c5ce650838e7", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-11-18T16:33:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T07:42:21.000Z", "max_issues_repo_path": "sections/analysis.tex", "max_issues_repo_name": "alxs/zclaim", "max_issues_repo_head_hexsha": "727b74ded4373c76e7e649b884d4c5ce650838e7", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sections/analysis.tex", "max_forks_repo_name": "alxs/zclaim", "max_forks_repo_head_hexsha": "727b74ded4373c76e7e649b884d4c5ce650838e7", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 80.9903474903, "max_line_length": 447, "alphanum_fraction": 0.762782161, "num_tokens": 10538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.33966532529483323}}
{"text": "% !TEX root =../thesis-letomes.tex\n\n\\chapter{Search Strategies}\n\\section{Evolution Strategies} \\label{sec:ES}\nOpenAI released a blog post \\cite{Karpathy} with accompanying paper \\cite{Salimans2017} in March 2017, where they announced ``Our finding continues the modern trend of achieving strong results with decades-old ideas''. Intuitively ES in a ``guess and check'' optimization process, where we start with some random parameters and then repeatedly 1) tweak the guess a bit randomly, and 2) move our guess slightly towards whatever tweaks worked better.\n\nThe team applied evolution strategies (ES) to two reinforcement learning (RL)\\footnote{Reinforcement learning is an area of machine learning concerned with how software agents ought to take actions in an environment so as to maximize some notion of cumulative reward.} scenarios and compared the performance with typical deep RL problems:\n\n\\begin{enumerate}\n    \\item MuJoCo\\footnote{MuJoCo stands for Multi-Joint dynamics with Contact, and is a ``\\textit{physics engine aiming to facilitate research and development in robotics, biomechanics, graphics and animation, and other areas where fast and accurate simulation is needed}''. See \\url{http://www.mujoco.org}} (see \\cref{fig:mujoco}) trained faster with ES than A3C\\footnote{Asynchronous Advantage Actor Critic (A3C), published in 2016 \\cite{Mnih2016}, is a class of deep RL algorithms that is still close to state of the art among deep RL algorithms.}.\n    \\item Atari game playing (see \\cref{fig:atari}) trained to similar performance with ES in 1 hour compared to 1 day with A3C. Atari games have also become a popular problem space for deep RP researchers\n\\end{enumerate}\n\n\\begin{figure}[H]\n    \\centering\n    \\subfloat[MuJoCo: Creatures resembling a dog, 4-legged spider and worm learn to move forward. (Source: \\cite{Karpathy})]{\n        \\includegraphics[width=0.46\\linewidth]{fig/MuJoCo}\n        \\label{fig:mujoco}\n    }\n    \\hfill\n    \\subfloat[Atari games are popular to RL algorithm research. Here: Breakout (left) and Space Invaders (right) (Source: \\cite{Deshpande}).]{\n        \\includegraphics[width=0.46\\linewidth]{fig/Atari}\n        \\label{fig:atari}\n    }\n    \\caption{Two Applications used for testing RL algorithms: MuJoCo and Atari.}\n    \\label{fig:rl}\n\\end{figure} \n\nTo achieve the signal needed for learning, i.e. exploration, noise must be somehow injected into the system:\n- For RL, noise is injected into the agent's \\emph{actions}.\n- For ES, noise is injected directly into the \\emph{parameters}.\n\nWe are basing our machine learning efforts on the Evolution Strategy (ES) algorithm outlined by Salimans et al. \\cite{Salimans2017} using ES -- it being a gradient estimator--makes sense in optimization scenarios where calculating an exact gradient is expensive, or even impossible. The idea is to sample around a starting point, and use a weighted average fitness score to pick a direction to move each cycle. It is generally applicable to unsupervised problems, such as ours; a reinforcement learning problem. There are several flavors of the concept under the ES umbrella term: Covariance Matrix Adaptation (CMA-ES), Natural Evolution Strategy (NES), and Exponential NES, to name a few. The one used in \\cite{Salimans2017} and by extension in our project is NES. Its exact implementation details will follow:\n\n\\subsection{Theoretical Advantages and Disadvantages of ES Compared to RL}\nThe advantages of ES is outlined in \\cite{Karpathy} and can be summarized as follows:\n\\begin{enumerate}\n    \\item No need for back propagation.\n    \\begin{itemize}\n        \\item Makes code shorter and 2-3x faster\n        \\item Memory saving: not necessary to keep episode recordings for later update.\n        \\item No need to worry about exploding gradients in recurrent neural networks.\n        \\item We can explore larger classes of policy functions, including networks that are not differentiable.\n    \\end{itemize}\n    \\item Highly parallelizable.\n    \\begin{itemize}\n        \\item ES workers communicate scalars, RL workers communicate entire parameter vectors $\\rightarrow$ easy to obtain linear speedups with more CPU cores.\n    \\end{itemize}\n    \\item Higher robustness.\n    \\begin{itemize}\n        \\item Has fewer hyperparameters. Several hyperparameters that are difficult to set in RL implementations are side-stepped in ES (although \\cite{Karpathy} does not go into so much detail with this).\n    \\end{itemize}\n\n    \\item Structured exploration.\n    \\begin{itemize}\n        \\item Due to the noise being injected in parameter space, not actions, ES can use deterministic policies and achieve consistent exploration (instead of \"jittering on the spot\"). \n    \\end{itemize}\n    \\item Credit assignment over long time scales\n    \\begin{itemize}\n        \\item By studying both ES and RL gradient estimators mathematically we can see that \\emph{ES is an attractive choice especially when the number of time steps in an episode is long, where actions have long-lasting effects}, or if no good value function estimates are available.\n    \\end{itemize}\n\\end{enumerate}\n\n\\subsubsection{ES Challanges}\n\nA core problem in ES is that adding noise in parameters must lead to different outcomes to obtain some gradient signal. It turns out that virtual batch normalization can help alleviate this problem \\cite{Karpathy}.\n\nAnother problem is that it doesn't really work on \\emph{supervised learning}, i.e. in settings where we know the/a solution/truth and want to use that to train a neural network. Supervised learning problems include image classification, speech recognition, or most other tasks in the industry, where one can compute the exact gradient of the loss function with backpropagation. For example, in the preliminary experiments it was found that using ES to estimate the gradient on the MNIST digit recognition task can be as much as 1,000 times slower than using backpropagation\\cite{Karpathy}.\n\nTherefore, \\emph{it is only in RL settings, where one has to estimate the gradient of the expected reward by sampling, where ES becomes competitive}.\n\n\\subsubsection{ES Advantages Summary}\nIn conclusion we are interested in ES as an optimization algorithm for LETO search mainly because it has advantages in:\n\\begin{itemize}\n    \\item Reduced code complexity\n    \\item Ease of scaling (to large-scale distributed settings)\n    \\item It does not suffer in settings with sparse rewards, such as is the case in searching for LETOs.\n\\end{itemize}\n\n\\subsection{NES Algorithm}\nIn formal terms: \\emph{``Let F denote the objective function acting on parameters θ. NES algorithms represent the population with a distribution over parameters \\(p_\\psi (\\theta)\\)—itself parameterized by $\\psi$—and proceed to maximize the average objective value \\(E_{\\theta \\sim p_\\psi}\\) over the population by searching for $\\psi$ with stochastic gradient ascent. Specifically, using the score function estimator for $\\nabla_\\psi E_{\\theta \\sim p_\\psi} F(\\theta)$, [...] NES algorithms take gradient steps on $\\psi$ with the following estimator:''} \\cite[p.~2]{Salimans2017}\n\\begin{equation}\n    \\nabla_\\psi E_{\\theta \\sim p_\\psi} F(\\theta)\n    = E_{\\theta \\sim p_\\psi} \\{F(\\theta)~\\nabla_\\psi~log~p_\\psi(\\theta)\\}\n\\end{equation}\nIn our problem, \\(F\\) is the score returned by our environment (the Earth-Moon or Earth-Mars-Sun system)(required $\\Delta v$ for our spacecraft's path) with \\(\\theta\\) representing a single path in the environment and \\(\\psi\\) being the parametrization of that path (example launch parameters: starting position of spacecraft, angle of burn vector at time of maneuver, and magnitude of that burn vector). The algorithm mutates the launch parameters \\(\\psi\\), checks how the resulting path \\(\\theta\\) performs in the environment \\(F\\) and moves around the resulting n-dimensional optimization space with gradient descent along its estimated gradient, defined by a normally distributed weighted point cloud \\(\\epsilon\\).\n\n\\begin{figure}\n    \\centering\n    \\subfloat[Starting at some random point, the first iteration computes the fitness of a surrounding point cloud ($\\epsilon$), and takes a step of size $\\alpha$ in the direction of the weighted mean of $\\epsilon$.]{\n        \\includegraphics[width=0.46\\linewidth]{fig/ES_basic_0}\n        \\label{fig:esbasic0}\n    }\n    \\hfill\n    \\subfloat[this process continues each iteration, until we find ourselves at a local maximum (this example version is doing gradient \\textit{ascent})]{\n        \\includegraphics[width=0.46\\linewidth]{fig/ES_basic_9}\n        \\label{fig:esbasic9}\n    }\n    \\caption{the fundamental ES algorithm illustrated in a toy problem. Generated from code based on \\cite{Salimans2017}}\n    \\label{fig:esbasic}\n\\end{figure}\n\nIn genetic algorithm terms, the input parameters $\\psi$ are the genotype, the resultant path $\\theta_\\psi$ is the phenotype, and the fitness is of course  $F(\\theta_\\psi)$. \\cite{Tomassini2005}. Since we simply input $\\psi$ to the simulator that delivers $F(\\theta_\\psi)$, and $\\theta$ is not really within the purview of the ES module, we will generally skip $\\theta_\\psi$, and simply write $F(\\psi)$ instead, unless the distinction between geno- and phenotype is relevant. This also reflects the reality more precisely, with regards to our code.\n\\subsection{Modifications}\nThere are a number of modifications to the core ES idea of gradient descent with an estimated gradient, that are required for the algorithm to actually work in anything but the most ideal context. \n\n\\subsubsection{Fitness Shaping}\nFitness shaping refers to the transformations one can perform on the output of $F$, generally in order to smoothen the optimization algorithm's movement. One such transformation that was particularly critical for our problem was rank transformation, i.e. for each gradient estimation distribution $F(\\psi_t + \\sigma\\epsilon_i)$, we replace the value of $F_i$ with its index in the sorted list of $F_{0..n}$. This shaping is to prevent outliers from overly influencing the gradient estimate. If a value is extreme in one way or the other, it would otherwise either pull or push the next iteration $\\psi_{t+1}$ proportionately. With rank transformation, this sensitivity to the random sampling of $\\sigma\\epsilon$ largely disappears. \\cite{Wierstra2011}. \n\nAnother fitness shaping approach that we tried was sub-par sample flattening. Since we are more interested in being pulled \\textit{towards} good solutions than being pushed away from bad ones, we ignore the half of the estimation distribution $\\sigma\\epsilon$ that performs worse than the mean. We tried this both in and out of conjunction with rank transformation, but it did not perform particularly in either case, having a negligible influence.\n\n\\subsubsection{Antithetical Sampling}\nAnother measure to reduce the impact of variance in the sampling of $\\sigma\\epsilon$ is antithetical sampling. This means that for every point $\\psi_t + \\sigma\\epsilon_i$ we sample, we evaluate its complement, $\\psi_t - \\sigma\\epsilon_i$ as well. \\cite{Salimans2017}. This means that there are always an equal number of points on either side of the distribution, and the estimated gradient is not thrown off by extreme stochastic outcomes in this regard.\n\n\n\\section{Fan Search}\nIn \\cite{Saxe2015}, the search strategy was significantly simpler than here, and it serves as the point of comparison for our search efforts. The way it was done is that the same three parameters contained in $\\psi$ were tested in a three-dimensional fan arrangement. For example, the starting position $\\psi_{pos}$ was defined from 0 to $2\\pi$, the burn angle $\\psi_{ang}$ was defined between 0 and $-\\frac{\\pi}{4}$, and the burn vector's magnitude $\\psi_{burn}$ was defined between 3 and 3.8. The search strategy was then to evaluate all superpositions of these three intervals, with e.g 100 values linearly spaced throughout each 'fan'. The set of values with the best score ($\\psi\\star$) would then be selected for refinement, where a smaller fan (tighter intervals) would be created, centered around $\\psi\\star$. The process would then repeat for some number of steps, constantly zeroing in on the best candidate.\n\nFor anyone with optimization experience it will be obvious that this method is very sensitive to local minimum issues. It doesn't multi-start, or compute any kind of gradient, definite or estimated. It relies heavily on empirically defined starting parameters for determining the initial search intervals, so it's very specific to this problem. It is, in short, not really universal, or particularly intelligent, and was thus seen as an obvious candidate for improvement in this project.\n\n\\section{Comparison of ES With Random Guessing Baseline}\nIn order to benchmark the performance of our ES implementation, we compared it with a baseline alternative; picking a random point within the problem space, and evaluating it, keeping it if it is the best we have seen. To find out which is best, there are two interesting metrics we can look at: \n\\begin{itemize}\n    \\item Given a fixed budget of fitness evaluations, which algorithm finds the lowest value.\n    \\item Given some threshold value that is considered \"good enough\", which algorithm reaches that in the shortest time..\n    \\item ..or in the case where it is interesting to have multiple good candidate solutions, which algorithm outputs most of them in a given time.\n\\end{itemize}\nSince the CPU-bound version of our algorithm takes several seconds to evaluate one fitness function, and the GPU version has had most of the pythonic\\footnote{``Pythonic'' is a term often thrown around in the python programming community meaning ``doing things the way that is considered best practice in the Python'' that are in harmony with \\href{https://www.python.org/dev/peps/pep-0020/}{The Zen of Python}, see \\url{https://docs.python-guide.org/writing/style/}} convenience compromised, we pre-computed the fitness values in a promising cutout of the problem space. The 1024x1024 grid seen in \\cref{fig:golf_course_s1024} took approximately 40 hours to compute on an HPC node, and with it, we were able to rapidly iterate our algorithm, both for the purpose of running it with multi-start to alleviate randomness, and to test the various potential accuracy and convergence-speed optimizations that have been applied in the literature.\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=\\linewidth]{fig/golf_course_s1024.png}\n    \\caption{1024x1024 resolution fitness map of the flattened problem space. burnDV is applied delta-v and position is the angular position around Earth ($\\text{position} = 0$ is the line between Earth to Moon). A certain fractal quality seems to be present, consistent with \\cite{Topputo2014}}\n    \\label{fig:golf_course_s1024}\n\\end{figure}", "meta": {"hexsha": "174ec2fca139b2b9366fd38843456b06dc5d0916", "size": 14802, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/chapters/4-Search-Strategies.tex", "max_stars_repo_name": "GandalfSaxe/letomes", "max_stars_repo_head_hexsha": "5f73a4066fcf69260cb538c105acf898b22e756d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "report/chapters/4-Search-Strategies.tex", "max_issues_repo_name": "GandalfSaxe/letomes", "max_issues_repo_head_hexsha": "5f73a4066fcf69260cb538c105acf898b22e756d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/chapters/4-Search-Strategies.tex", "max_forks_repo_name": "GandalfSaxe/letomes", "max_forks_repo_head_hexsha": "5f73a4066fcf69260cb538c105acf898b22e756d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 110.4626865672, "max_line_length": 940, "alphanum_fraction": 0.7745574922, "num_tokens": 3401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.3395162939177265}}
{"text": "\\documentclass{tufte-handout}\n\n\\title{Assignment 3: Extended Kalman Filter}\n\n\\author[Kautilya Chenna]{Kautilya Chenna}\n\n%\\date{28 March 2010} % without \\date command, current date is supplied\n\n%\\geometry{showframe} % display margins for debugging page layout\n\n\\usepackage{graphicx} % allow embedded images\n    \\setkeys{Gin}{width=\\linewidth,totalheight=\\textheight,keepaspectratio}\n    \\graphicspath{{graphics/}} % set of paths to search for images\n\\usepackage{amsmath}  % extended mathematics\n\\usepackage{booktabs} % book-quality tables\n\\usepackage{units}    % non-stacked fractions and better unit spacing\n\\usepackage{multicol} % multiple column layout facilities\n\\usepackage{lipsum}   % filler text\n\\usepackage{fancyvrb} % extended verbatim environments\n    \\fvset{fontsize=\\normalsize}% default font size for fancy-verbatim environments\n\n% Standardize command font styles and environments\n\\newcommand{\\doccmd}[1]{\\texttt{\\textbackslash#1}}% command name -- adds backslash automatically\n\\newcommand{\\docopt}[1]{\\ensuremath{\\langle}\\textrm{\\textit{#1}}\\ensuremath{\\rangle}}% optional command argument\n\\newcommand{\\docarg}[1]{\\textrm{\\textit{#1}}}% (required) command argument\n\\newcommand{\\docenv}[1]{\\textsf{#1}}% environment name\n\\newcommand{\\docpkg}[1]{\\texttt{#1}}% package name\n\\newcommand{\\doccls}[1]{\\texttt{#1}}% document class name\n\\newcommand{\\docclsopt}[1]{\\texttt{#1}}% document class option name\n\\newenvironment{docspec}{\\begin{quote}\\noindent}{\\end{quote}}% command specification environment\n\n\\begin{document}\n\n\\maketitle% this prints the handout title, author, and date\n\n\\section{Exercise 1: Bayes Filter and Extended Kalman Filter}\n\\begin{fullwidth}\n\\textsc{Question 1}: Describe briefly the two main steps of the Bayes filter in your own words.\n\\end{fullwidth}\n\nFirst step is the prediction step where we use the motion model to update our belief and then we have the correction step where we use the observation model or the sensor model to correct our belief about the state.\n\n\n\\begin{fullwidth}\n\\textsc{Question 2}: Describe briefly the meaning of the following probability density functions.\n\\end{fullwidth}\n\n$p(x_t \\mid x_{t-1},u_t)$: Motion model\n\n$p(z_t\\mid x_t)$: Sensor model\n\n$bel(x_t)$: belief of the state\n\n\\begin{fullwidth}\n\\textsc{Question 3}: Specify the distributions that correspond to the above mentioned three terms in the EKF.\n\\end{fullwidth}\n\nAll three distributions are Gaussian, since EKF assumes that the the distributions be Gaussian.\n\n\\begin{fullwidth}\n\t\\textsc{Question 4}: Explain in a few sentences all of the components of the EKF algorithm\n\\end{fullwidth}\n\n\\end{document}", "meta": {"hexsha": "54acafb32eb8415140c08c1976916c34817ac2b9", "size": 2620, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "03-extended_kalman_filter/answers.tex", "max_stars_repo_name": "hashb/robot_mapping", "max_stars_repo_head_hexsha": "4af70b0732f60a91a363d63edaa83e0e990122b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "03-extended_kalman_filter/answers.tex", "max_issues_repo_name": "hashb/robot_mapping", "max_issues_repo_head_hexsha": "4af70b0732f60a91a363d63edaa83e0e990122b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-06-17T11:15:03.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-17T11:15:03.000Z", "max_forks_repo_path": "03-extended_kalman_filter/answers.tex", "max_forks_repo_name": "hashb/robot-mapping", "max_forks_repo_head_hexsha": "4af70b0732f60a91a363d63edaa83e0e990122b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-28T09:06:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-28T09:06:07.000Z", "avg_line_length": 40.9375, "max_line_length": 215, "alphanum_fraction": 0.7709923664, "num_tokens": 715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.33951628505760284}}
{"text": "%!TEX program = lualatex\n\\documentclass[\n    paper=letter,\n    parskip=half-,\n    DIV=10,\n]{scrreprt}\n\n% WTF? UTF-8 is ignored without this!?? Should be the default on lualatex.\n\\usepackage[utf8]{luainputenc}\n\n\\usepackage{hyperref}\n\\usepackage{xspace}\n\\usepackage{mathtools}\n\\usepackage[final]{microtype}\n\n\\usepackage{tikz}\n\\usetikzlibrary{intersections,calc,arrows,positioning}\n\n\\newcommand{\\gratio}{\\emph{golden ratio}\\xspace}\n\n\\usepackage{minted}\n\\usemintedstyle{friendly}\n\n\\begin{document}\n\n\\subject{Reflection}\n\\title{Computing optimal borders for a print} \\subtitle{Optimal for myself!}\n\\author{Serge Émond}\n\\date{23th August 2014}\n\\maketitle\n\n\\chapter{Introduction}\n\n    I want to print some of my photos, and to frame them using a simple mat (no framing).\n\n    To do that, I need to choose a border size, and to center it “optically” so the image doesn’t give the impression of sinking into the frame. I also require the top border to be at least as big as the side borders.\n\n    Some people\\footnote{\\url{http://kombat.org/FrameMaking/step1.html} uses $\\phi$ to multiply the longest side and use that border for both sides} use the \\emph{golden ratio} ($\\phi$) as a multiplicator to the width and height of the size of the mat’s window. I personnally find it produces borders that are way too big.\n\n    Others\\footnote{\\url{http://www.phimatrix.com/matte-frame-golden-ratio/}} use $\\phi$ as a multiplicator to the \\emph{area} of the print surface to compute the surface of the mat.\n\n    It gives a size that I like, however it also means the shortest side has smaller borders, which is visually ugly if this happens to be a landscape.\n\n    I could simply use the longest side for all sides, but then I would have other problems:\n    \\begin{itemize}\n        \\item “visually centering” the window would still give a smaller top border than the edges,\n        \\item and on an image with a strong difference between the two dimensions, this could produces borders too big.\n    \\end{itemize}\n\n    So I decided to:\n\n    \\begin{itemize}\n        \\item use the golden ratio to compute the area of the mat size;\n        \\item keep the resulting border surface constant;\n        \\item compute the 4 borders so that the top equals the side borders, and the bottom is bigger accorging to the most common vertical centering rules.\n    \\end{itemize}\n\n\\chapter{Optical centering}\n\n    To center the print window on a mat, the most common technique (actually the only one I found aside “move the picture a big higher”) is:\n\n    \\begin{enumerate}\n        \\item align the top left corner of the print with the top left corner of the mat,\n        \\item draw a vertical line at the center of the remaining space on the right to produce the left and right borders,\n        \\item draw an horizontal line at the center of the remaining space on the bottom to produce the top and left borders before correction,\n        \\item draw a line from the bottom left corner of the print to a point placed on the absolute right side of the mat, and the lower left line,\n        \\item move the picture so the bottom right corner alligns with the diagonal line and the rightmost vertical line.\n    \\end{enumerate}\n\n    Visually, you get something like the figure \\ref{fig:mat}.\n\n    \\begin{figure}\n    \\caption{Centering a print on a mat}\\label{fig:mat}\n    \\centering\n    \\begin{tikzpicture}[x=1.5cm,y=1.5cm]\n        \\draw[help lines,very thin,color=blue!50!green!50,step=1] (-1, -1) grid (6, 5);\n\n        % Mat\n        \\draw[fill=gray,opacity=0.2] (0,4) rectangle +(5,-4);\n        % Window\n        \\draw[fill=white] (0,4) rectangle +(3,-2);\n        \\node (window) at (1.5,3) {print};\n\n        \\draw[-] (4.5,2.5) -- (5.25,3.5);\n        \\fill[black] (4.5,2.5) circle (2pt);\n        \\draw (5.6,3.7) node {mat};\n\n        % Border separators\n        \\draw[dashed,name path=bsepbt] (0,1) -- +(5,0);\n        \\draw[dashed,name path=bseplr] (4,0) -- +(0,4);\n\n        % diag line and helper line\n        \\draw[dashed,name path=diag] (0,2) -- (5,1);\n        \\fill[\n            name intersections={of=diag and bseplr,by=I},\n            red, opacity=0.5,\n            every node/.style={above right, black, opacity=1}\n        ]   (I) circle (2pt) node {\\footnotesize $A$};\n        \\coordinate (Ileft) at ($(I) + (-4,0)$);\n        \\coordinate (Iright) at ($(I) + (1,0)$);\n        \\draw[\n            densely dashed,name path=bsepi,\n        ]   (Ileft) -- (Iright);\n\n        % Border arrows\n        \\begin{scope}[<->,shift={(3,4.5)}]\n            \\draw (0,0) -- +(1,0) node [above,midway] {$b_l$};\n            \\draw (1,0) -- +(1,0) node [above,midway] {$b_r$};\n        \\end{scope}\n        \\begin{scope}[<->,shift={(-.5,0)}]\n            \\draw (0,0) -- +(0,1) node [left,midway] {$b'_b$};\n            \\draw (0,1) -- +(0,1) node [left,midway] {$b'_t$};\n        \\end{scope}\n        \\draw[<->] (5.5,0) -- ($(Ileft) + (5.5,0)$) node [right,midway] {$b_b$};\n        \\draw[<->] ($(Ileft) + (5.5,0)$) -- (5.5,2) node [right,midway] {$b_t$};\n\n        % And an action text..\n        % \\draw[->] (3,2) -- (I) node [midway,above,right] {\\footnotesize move};\n\n    \\end{tikzpicture}\n    \\end{figure}\n\n    On that figure, $b_l$, $b_r$, $b'_t$ and $b'_b$ represent the borders around a perfectly centered print. Normally we want the left and right borders to be the same size, and the top and bottom borders too.\n\n    So we can define $b_x = b_l = b_r$ as the size for the borders along the X axis, and $b_y = b'_t = b'_b$ for the top and bottom borders.\n\n    $b_t$ and $b_b$ represent the top and bottom border of an “optically centered”, obtained by sliding the print so its bottom right corner is set on point $A$. Their value is:\n\n    \\begin{align*}\n        b_t &= b'_t - A \\\\\n        b_b &= b'_b + A\n    \\end{align*}\n\n    Let say that $(w_x, w_y)$ are the width and height of the mat’s window (or print size), and $(w_x, w_y)$ the dimensions of the mat itself.\n\n    It can be shown that the amount of upward shift, $A$, is:\n\n    \\[\n        A = \\frac{b_x b_y}{m_x} = \\frac{b_x b_y}{w_x + 2b_x}\n    \\]\n\n    % where $b_x = \\frac{m_x - w_x}{2}$ and $b_y = \\frac{m_y - w_y}{2}$.\n\n    Personnally, what I want is to find the proper border sizes to that $b_x = b_y = b$, and $b_b = b + A$.\n\n\n\\section{Golden Ratio}\n\n    Let the golden ratio be $\\phi$, because I don’t intend on typing “golden ratio” more than I have to.\n\n    I want the mat's surface to be $\\phi$ the mat window's surface:\n\n    \\begin{equation*}\n        m_x m_y = \\phi w_x w_y\n    \\end{equation*}\n\n\n\\chapter{Finding the border sizes}\n\n    From a bit of trigonometry, we have\n    \\begin{align}\n        m_x &= w_x + 2b \\\\\n        m_y &= w_y + 2b + A = w_y + 2b + \\frac{b^2}{mx - b} \\\\\n        w_x &= m_x - 2b \\\\\n        w_y &= m_y - 2b - A = m_y - 2b - \\frac{b^2}{mx + b}\n    \\end{align}\n\n    The golden ratio of the area gives us:\n    \\begin{align}\n        0 &= \\phi w_x w_y - m_x m_y\n    \\end{align}\n\n    So if we mix those to compute $b$ from the window's dimensions:\n    \\begin{equation}\\label{eq:bwin}\n        0 = 6b^3 + (7w_x + 2w_y)b^2 + (2w_x^2 + (3 - \\phi)w_xw_y)b + (1 - \\phi)w_x^2w_y\n    \\end{equation}\n    And to compute $b$ from the mat's dimensions:\n    \\begin{equation}\\label{eq:bmat}\n        % 0 = -2\\phi b^3\\phi +b^2(5m_x + 2m_y)\\phi + b((1 - 3\\phi)m_y - 2m_x\\phi)m_x + (\\phi - 1)m_x^2m_y\n        0 = -2\\phi b^3 + (5m_x + 2m_y)\\phi b^2 + (m_y - 2m_x\\phi + 3m_y\\phi)m_xb + (\\phi - 1)m_x^2m_y\n    \\end{equation}\n\n\n\\chapter{Implementing}\n\nSolving symbolically is not really practical, producing way too much complexity for not much.\n\nIn the methods presented in table \\ref{tbl:times}, the methods producing the best precision should be \\texttt{mpmath}, because it's an arbitrary precision library, and \\texttt{sympy} because it keeps everything symbolically, and finally evaluates using \\texttt{mpmath}.\n\nThe least precise method should be \\texttt{scipy} because \\texttt{fsolve} is very general and doesn't even guarantee a proper result.\n\nThe fastest should be \\texttt{numpy} because it uses the CPU's floating point.\n\nTable \\ref{tbl:times} shows the processing times for a 9x6 print.\n\nPractically, the precision has no impact since any of these methods should produce way more than what I can achieve while cutting a mat sheet. Thus only speed has a meaning in this case.\n\nPure processing time should point to \\texttt{numpy}, however if we account for python’s startup time, \\texttt{numpy} takes on average $0.11$s on my computer to run, while \\texttt{mpmath} (with and without \\texttt{gmpy}) takes $0.06$s.\n\nThus my final choice is \\texttt{mpmath}. It also happens to be much simpler (at least in virtual environments) and faster to install than \\texttt{numpy}.\n\n\\begin{table}\n\\caption{Solving times, based on 1000 iterations (except sympy, which is based on 10)}\\label{tbl:times}\n\\centering\n\\begin{tabular}{llll}\n\\hline\nLibrary              & time / iteration  & $b$ & $b_b$ \\\\\n\\hline\nnumpy                & $0.000171954$s    & 0.956913776241981   & 1.04887841465701 \\\\\nscipy                & $0.000365011$s    & 0.956913776241981   & 1.04887841465701 \\\\\nmpmath (gmpy)        & $0.003560504$s    & 0.956913776241981   & 1.04887841465701 \\\\\nmpmath               & $0.005906222$s    & 0.956913776241981   & 1.04887841465701 \\\\\nsympy (gmpy)         & $1.134872603$s    & 0.956913776241981   & 1.04887841465701 \\\\\nsympy                & $1.259345698$s    & 0.956913776241981   & 1.04887841465701 \\\\\n\\hline\n\\end{tabular}\n\\end{table}\n\n\n\\chapter{Examples}\n\nUsing \\texttt{mpmath} with the python code from figure \\ref{code:solver1}, for a 9x6 print size, we obtain:\n\n    \\begin{align*}\n        b &= 0.95691 \\\\\n        b_{bot} &= 1.0489\n    \\end{align*}\n\n\\begin{figure}\n\\label{code:solver1}\n\\caption{A simple example of numerically solving $b$ from equation \\ref{eq:bwin}}\n\\begin{minted}[mathescape,\n               linenos,\n               numbersep=5pt,\n               frame=lines]{python}\nfrom mpmath import mp\n\nmp.dps = 5\n\nwx = mp.mpf('9'); wy = mp.mpf('6')\nphi = (1 + mp.sqrt(5)) / 2\ncoeffs = [\n    6,\n    7 * wx + 2 * wy,\n    wx * ((3 - phi)*wy + 2*wx),\n    (1 - phi) * mp.power(wx, 2) * wy\n]\n\nroots = mp.polyroots(coeffs, 15)\nb = [root for root in roots if mp.im(root) == mp.mpf(0)][0]\nbottom = b + mp.power(b, 2) / (wx + b)\n\nprint(\"Print dimensions: {wx!s} x {wy!s}\\n\"\n      \"Resulting border: {b!s}\\n\"\n      \"Resulting bottom border: {bottom!s}\"\n      .format(wx=wx, wy=wy, b=b, bottom=bottom))\n\\end{minted}\n\\end{figure}\n\n\nAssuming the lengths are in centimeters, you can find representation of this at scale in figure \\ref{fig:phi}.\n\nIf we want to compute the border area so we have the \\emph{lengths} (width and height) as $m_{(x|h)} = \\phi\\cdot w_{(x|h)}$, we use $\\phi' = \\phi^2$ and obtain the following borders, represented in figure \\ref{fig:phisquare}:\n\n\\begin{align*}\n    b &= 2.1285 \\\\\n    b_{bot} &= 2.5356\n\\end{align*}\n\n    \\begin{figure}\n    \\caption{Result for a 9x6cm print using $m_a = \\phi w_a$}\\label{fig:phi}\n    \\centering\n\\begin{tikzpicture}\n    \\draw[help lines,very thin,color=blue!50!green!50,step=1] (-1.0, 1.0) grid +(11.0, -9.0);\n    % Mat\n    \\draw[fill=black,opacity=0.5] (-0.95691,0.95691) rectangle +(10.914,-8.0058);\n    % Window\n    \\draw[fill=white] (0,0) rectangle +(9,-6);\n\\end{tikzpicture}\n    \\end{figure}\n\n\n    \\begin{figure}\n    \\caption{Result for a 9x6cm print using $m_a = \\phi^2 w_a$}\\label{fig:phisquare}\n    \\centering\n\\begin{tikzpicture}\n    \\draw[help lines,very thin,color=blue!50!green!50,step=1] (-3.0, 3.0) grid +(15.0, -12.0);\n    % Mat\n    \\draw[fill=black,opacity=0.5] (-2.1285,2.1285) rectangle +(13.257,-10.664);\n    % Window\n    \\draw[fill=white] (0,0) rectangle +(9,-6);\n\\end{tikzpicture}\n    \\end{figure}\n\n\n\n\\end{document}", "meta": {"hexsha": "7761e26963524644473ab142ccef597820faa295", "size": 11701, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "reflections/doc.tex", "max_stars_repo_name": "semond/golden-borders", "max_stars_repo_head_hexsha": "b15d2e22c0c76cdd3d017d7ae52d13e90a6e7aa6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "reflections/doc.tex", "max_issues_repo_name": "semond/golden-borders", "max_issues_repo_head_hexsha": "b15d2e22c0c76cdd3d017d7ae52d13e90a6e7aa6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "reflections/doc.tex", "max_forks_repo_name": "semond/golden-borders", "max_forks_repo_head_hexsha": "b15d2e22c0c76cdd3d017d7ae52d13e90a6e7aa6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.3973063973, "max_line_length": 322, "alphanum_fraction": 0.6402871549, "num_tokens": 3777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.33951628505760284}}
{"text": "\\documentclass{article}\n\\usepackage[utf8]{inputenc}\n\n\\title{PS8_Gillingham}\n\\author{Andrew Gillingham }\n\\date{March 2019}\n\n\\begin{document}\n\n\\section{OLS}\n\n\n% Table created by stargazer v.5.2.2 by Marek Hlavac, Harvard University. E-mail: hlavac at fas.harvard.edu\n% Date and time: Tue, Mar 26, 2019 - 12:52:23 PM\n\\begin{table}[!htbp] \\centering \n  \\caption{} \n  \\label{} \n\\begin{tabular}{@{\\extracolsep{5pt}}lc} \n\\\\[-1.8ex]\\hline \n\\hline \\\\[-1.8ex] \n & \\multicolumn{1}{c}{\\textit{Dependent variable:}} \\\\ \n\\cline{2-2} \n\\\\[-1.8ex] & y \\\\ \n\\hline \\\\[-1.8ex] \n X1 & 0.775$^{***}$ \\\\ \n  & (0.002) \\\\ \n  & \\\\ \n X2 & 0.248$^{***}$ \\\\ \n  & (0.002) \\\\ \n  & \\\\ \n X3 & 0.258$^{***}$ \\\\ \n  & (0.002) \\\\ \n  & \\\\ \n X4 & 0.300$^{***}$ \\\\ \n  & (0.002) \\\\ \n  & \\\\ \n X5 & 0.355$^{***}$ \\\\ \n  & (0.002) \\\\ \n  & \\\\ \n X6 & 0.483$^{***}$ \\\\ \n  & (0.002) \\\\ \n  & \\\\ \n X7 & 0.157$^{***}$ \\\\ \n  & (0.002) \\\\ \n  & \\\\ \n X8 & 0.018$^{***}$ \\\\ \n  & (0.002) \\\\ \n  & \\\\ \n X9 & 0.312$^{***}$ \\\\ \n  & (0.002) \\\\ \n  & \\\\ \n X10 & 0.429$^{***}$ \\\\ \n  & (0.002) \\\\ \n  & \\\\ \n\\hline \\\\[-1.8ex] \nObservations & 100,000 \\\\ \nR$^{2}$ & 0.856 \\\\ \nAdjusted R$^{2}$ & 0.856 \\\\ \nResidual Std. Error & 0.500 (df = 99990) \\\\ \nF Statistic & 59,605.040$^{***}$ (df = 10; 99990) \\\\ \n\\hline \n\\hline \\\\[-1.8ex] \n\\textit{Note:}  & \\multicolumn{1}{r}{$^{*}$p$<$0.1; $^{**}$p$<$0.05; $^{***}$p$<$0.01} \\\\ \n\\end{tabular} \n\\end{table} \n\\end{document}\n", "meta": {"hexsha": "a09f169148b61863969617462599b2123a17441a", "size": 1394, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ProblemSets/PS8/PS8_Gillingham.tex", "max_stars_repo_name": "agillingham15/DScourseS19", "max_stars_repo_head_hexsha": "ac055b70bb06ef413b0470c78a221dc3daa0c651", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProblemSets/PS8/PS8_Gillingham.tex", "max_issues_repo_name": "agillingham15/DScourseS19", "max_issues_repo_head_hexsha": "ac055b70bb06ef413b0470c78a221dc3daa0c651", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSets/PS8/PS8_Gillingham.tex", "max_forks_repo_name": "agillingham15/DScourseS19", "max_forks_repo_head_hexsha": "ac055b70bb06ef413b0470c78a221dc3daa0c651", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8059701493, "max_line_length": 107, "alphanum_fraction": 0.4662840746, "num_tokens": 659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.33951628505760284}}
{"text": "\\section{Introduction}\nWith the rapid expansion of computer power, data science is becomming an ever bigger part of modern society. Among the methods used to process data, some of the most popular are regression and classification. Through this paper we will look closely at the use of these methods when applied to data from the Ising model for spins. First of, we will use linear, ridge and lasso regression to estimate the coupling constant for the one-dimensional Ising model. Secondly, we move on to logistic regression and determining the phase of a spin matrix created by the two-dimensional Ising model. The latter problem is a classification problem and we will look further into it by creating a neural net. To learn more about the properties of a neural net, we will start by using the one-dimensional Ising model to find the optimal weights and biases in a regression case. Then we will apply what we learned by repeating the same classification as the logistic case, but this time we will train a neural net with a cross-entropy cost function to perform the task. \n\nOur work is heavily inspired by the work of Metha et al. \\cite{2018arXiv180308823M}, and therefore it is only natural to compare our results to theirs. Lastly, we will give a detailed and in-depth analyzis of the algorithms used and how our home-made algorithms compares to those of Metha et al. and similar calculations done by standard libraries such as scikit-learn or TensorFlow.", "meta": {"hexsha": "a466f7a05074838fd5e63ed15f1ac691b4b661b3", "size": 1462, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/introduction.tex", "max_stars_repo_name": "hmvege/FYSSTK4155-Project2", "max_stars_repo_head_hexsha": "3cf617399f99026cbcd79f8153d3196ebd86c7cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/introduction.tex", "max_issues_repo_name": "hmvege/FYSSTK4155-Project2", "max_issues_repo_head_hexsha": "3cf617399f99026cbcd79f8153d3196ebd86c7cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/introduction.tex", "max_forks_repo_name": "hmvege/FYSSTK4155-Project2", "max_forks_repo_head_hexsha": "3cf617399f99026cbcd79f8153d3196ebd86c7cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 365.5, "max_line_length": 1054, "alphanum_fraction": 0.8091655267, "num_tokens": 302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.6584175072643415, "lm_q1q2_score": 0.3394931796061978}}
{"text": "% !TEX root = report.tex\n\n\\section{Processing Pipeline}\n\\label{sec:processing_architecture}\n\nIn order to provide a complete overview of the approaches that can be followed during this kind of tasks, at a certain point the project will encounter two parallel branches:\n\\begin{itemize}\n\t\\itemsep0em\n\t\\item one following the more canonical path of classification according to high-level audio features extracted from the clips (used also in speech recognition tasks);\n\t\\item a second one instead moving onto an \"unconventional\" direction and exploiting Convolutional Neural Networks over the audio spectrograms, that, in recent years have, been found to outperform the canonical way for environmental sounds, even replacing it as the state of the art.\n\\end{itemize} \nSplitting the analysis into two parts, one is effectively able to compare the two methods in term of speed, stability and accuracy reached, but its implementation requires also the generation of two different new datasets.\\\\\nSo, for the first part, a vector of high-level audio features is extracted from the clips, and will represent them during the learning phase for the machine learning models implemented: the main advantage of this method is that each audio file can be simply replaced by a vector with just a few dozen of parameters, resulting in much less memory consumption; so, data are easier to handle and manipulate, at the expenses of some additional preprocessing steps (extraction, dimensionality reduction, regularization). For the second part, instead, the sounds are represented by their power spectrograms, and so the collection of audios leaves space to a set of images, that unfortunately occupy much more memory (obviously depending on their resolution). However this second approach seems to guarantee better performances with very high accuracies, and so it is the preferred one, even if it usually takes much more time to train.\\\\\nJust as a final remark for this part, it can be useful to say that the spectrograms in the second approach can be replaced by their \\textit{Melspectrograms}, that basically are the same power spectra, but represented in the Mel scale, which better approximates the human auditory system; however, in the results section it will be shown that both choices lead to similar performances over the dataset studied.\\\\\nThe whole procedure is possible thanks to the Python library \\textit{Librosa} \\cite{mcfee2015librosa}, that provides all the building blocks necessary for music and audio analysis. \n\n\n\\section{Signals and Features}\n\\label{sec:model}\n\nAs anticipated before, one of the main obstacles in research activities focused on environmental sound classification was the scarcity of large public datasets to analyze and exploit for training models. But it is for this reason that Karol J. Piczak \\cite{piczak2015dataset}, realized a collection of sound clips that became one of the two main datasets used to define the state of the art for this research field.\\\\\nThe \\textbf{ESC-50 dataset} is a labeled collection of 2000 environmental audio recordings suitable for benchmarking methods of environmental sound classification. The dataset consists of 5-second-long recordings \\footnote{44.1 kHz, mono, 431 frames, cropped or padded with zeros to reach exactly 5 seconds of duration} organized into 50 semantical classes (with 40 examples per class) loosely arranged into 5 major categories: animals, natural soundscapes and water, human non-speech, interior/domestic sounds and exterior/urban noises. All of these clips have been manually extracted from public field recordings gathered by the \\url{Freesound.org} project \\footnote{A more thorough description of the dataset is available in the original paper \\cite{piczak2015dataset}, while the main folder of the project can be found on github \\cite{piczakgithub}.}.\\\\\nAs presented in the previous section, one of the peculiarity of this work will be proceeding into two parallel directions, in order to analyze and compare the two main approaches developed and applied so far to solve the problem. For the method exploiting the CNNs, the only preparation required is normalizing the entries of the spectrogram images given in input  \\footnote{$(300\\times 600)$ .png images} in $[-1,1]$, that is a common step when working with neural networks. For the features' vector approach, instead, the biggest part of the work consist into defining an entire preprocessing procedure aimed to the construction of a reliable high-level representation of the clips. Those steps will be deepened in the following subsections.\n\n\\subsection{Features extraction}\n\\label{sec:features_extraction}\nThe objective is to define an high-level representation of each sound clip using just a few values, summarizing all the necessary information stored in each audio file. In particular, for this project, the choice fell on the following list of features:\n\\begin{itemize}\n\t\\itemsep0em\n\t\\item \\textbf{spectral centroid}: indicates at which frequency the energy of a spectrum is centered upon or, in other words, where the \"center of mass\" for a sound is located;\n\t\\item \\textbf{spectral roll off}: measure of the signal's shape, represents the frequency at which high frequencies decline to zero;\n\t\\item \\textbf{spectral bandwidth}: represents the portion of the spectrum which contains most of the energy of the signal;\n\t\\item \\textbf{zero-crossing rate}: rate at which a signal changes from positive to zero to negative or from negative to zero to positive;\n\t\\item \\textbf{MFCC}: the Mel-Frequency-Cepstral-Coefficient of a signal are a small set of features (usually about 10/20) which concisely describe the overall shape of a spectral envelope modeling the characteristics of the human voice (according to the Mel scale); only twelve of them are kept (discarding the first one, conventionally) together with their first (\\textbf{delta}) and second derivatives (\\textbf{delta-delta});\n\t\\item \\textbf{chromagram}: typically a 12-element features vector indicating how much energy of each pitch class, \\{C, C\\#, D, D\\#, E, ..., B\\}, is present in the signal (usually, it provides a way to describe a similarities between music pieces);\n\t\\item \\textbf{energy}: root-mean-square-energy (RMSE) value for each frame, together with the first (\\textbf{delta-energy}) and second derivatives (\\textbf{delta-delta-energy}) of their logarithms.\n\\end{itemize}\nOne could argue that some of them are redundant or even unsuitable for the main objective of the implementation, but later on a Principal Component Analysis will discard all the contribution that effectively are useless, and so computing them at the beginning results in just a negligible increment in the computational time. Moreover, looking at the correlation matrix among those features, and reported in appendix \\ref{app:correlation_matrix}, one can find additional justifications for this choice.\\\\\nNotice that the list above is constituted by \\textit{frame features}, in the sense that each quantity will contribute with one (or more) values for every frame in the clip (431), and so in the end one will have to deal with entire distributions, rather than single vectors. The first and also the most immediate solution, that one can think about, is representing each feature with its mean across all the frames, leading to vectors of overall size 55. But this will be shown to be a suboptimal attempt because there are many audio files whose features distributions are not very regular neither symmetric, like shown in figure \\ref{fig:ex_distrib}, and so the mean alone is no more representing a good estimator for them: to take into account the dispersion of the data, one should rely also on other statistical estimators like the standard deviation.\n\\begin{figure}[!h]\n\t\\centering\n\t\\includegraphics[width=0.47\\textwidth]{pictures/ex_distrib.pdf}\n\t\\caption{Spectral centroid distributions for two different sound clips.}\n\t\\label{fig:ex_distrib}\n\\end{figure}\nSo the final choice fell on constructing, for each clip, a vector containing the mean and the standard deviation across the frames, for all the features listed above, for a total of 110 elements.\n\n\\subsection{Silent Elimination}\n\\label{sec:windowing}\nA further preprocessing step that can be implemented is the detection of silent windows in the clips.\n\\begin{figure}[!h] \n\t\\centering\n\t\\includegraphics[width=0.47\\textwidth]{pictures/silent_ex.pdf}\n\t\\caption{Example of a clip with a large fraction of silence.}\n\t\\label{fig:silent_ex}\n\\end{figure}\nAs can be noticed in picture \\ref{fig:silent_ex}, there are some sounds which have been padded with zeros to reach the five second length, or maybe they just alternate parts of noises and parts of silence. This can be a problem in the final classification, because the features distributions, represented just by their mean and standard deviation, will result strongly shifted towards the zeros measured during those periods of silence, losing, then, much of their regularity. One possibility to deal with this problem could be \"forgetting\" about zeros when computing the statistical variables of the features: in this way the mean would result just re-scaled, while the standard deviation would be affected much more. Hence the final accuracy is effectively increased, but the problem is that we are improving the capability of the model when distinguishing among short sounds, but at the same time we are losing information about repetitive sounds, like some animal noises. A possible trade-off between the two situations has been found defining a further step, not on the clips, but directly on the features, according to which if the program is able to identify fix-sized windows of silence, using the energy of the spectrum as a discriminator, those (non-overlapping) windows can be \"forgotten\" during the calculation. After several tests, it turned out that the optimal windows' size was 0.5 seconds.\n\n\\subsection{Audio Augmentation}\n\\label{sec:audio_augmentation}\nThe dataset used in this analysis is composed just by 2000 clips for 50 different classes: not enough to train a good classifier nor to construct a reliable statistics of the results.\nOne possible solution to this is data augmentation, i.e. increasing the amount of clips available, adding slightly modified copies of already existing data or newly created ones. In this way, at least theoretically, the possibility of overfitting will be reduced, making the models able to generalize better. Starting from the original audio files, four new folders, each containing 2000 clips, have been generated, applying one of the available augmentation techniques (inspired by the ones suggested by Salomon and Bello \\cite{salamon_bello}, and by the work of Nanni, Maguolo and Paci \\cite{animal_augmentation}):\n\\begin{itemize}\n\t\\itemsep0em\n\t\\item \\textit{Background Noise}: mix the audio sample with some gaussian noise multiplied by a regularization factor, that is calibrated to avoid such noise to overcome too much the original sound.\n\t\\item \\textit{Time Shifting}: sounds should be invariant under time shifting, and so new clips are generated in this way, padding with zeros the part that has been moved.\n\t\\item \\textit{Pitch Shifting}: sound recording technique in which the original pitch of a sound is raised or lowered and, according to Salomon and Bello \\cite{salamon_bello}, is particularly beneficial for the augmentation and should deserve a separate analysis.\n\t\\item \\textit{Time Stretching}: just slowing down or speeding up the audio samples.\n\\end{itemize}\n\nHowever, even if the data augmentation step has been reported and implemented, its efficiency will be seriously questioned in the results section, since it will be shown that traditional audio augmentation techniques are not compatible with the approaches followed for environmental sound classification.\n\n\n\\section{Learning Framework}\n\\label{sec:learning_framework}\n\nAgain, this section is divided into two parts, following the two different approaches implemented: the first one exploiting several machine learning classifiers trained with the vectors constructed in section \\ref{sec:features_extraction}, and the second one utilizing CNNs to classify spectrograms. \n\n\\subsection{Features Classification}\n\\label{sec:features_classification}\nThere is a \"problem\" with the ESC-50 dataset: it composed by just 2000 clips, which is never enough to train properly a 50-classes classifier! Also splitting the clips in a train-validation-test sets is not so recommended, because there isn't enough data to construct a significative statistics. A possible solution to all these problems have been found in a technique (suggested also inside the library \\textit{sklearn}) called \\textbf{nested cross-validation}, presented in appendix \\ref{app:nested_CV}.\\\\\nThen, it's all about figuring out which kind of machine learning models can effectively be trained with success over the clips collected in ESC-50 (or, better, on the features vectors extracted from them). This project started studying the application of four different \"canonical\" classifiers (provided by \\textit{sklearn}) for some reasonable combinations of hyperparameters:\n\\begin{itemize}\n\t\\itemsep0em\n\t\\item a \\textbf{Random Forest};\n\t\\item a \\textbf{Multi-Layer Perceptron};\n\t\\item a \\textbf{K-Neighbors Classifier};\n\t\\item a \\textbf{Support Vector Machine}.\n\\end{itemize}\n\nMoreover, before feeding them with the (nested) folds created splitting the dataset, the vectors needed a final preprocessing step, made possible via a data-\\textit{pipeline} implementing the following three operations:\n\\begin{enumerate}\n\t\\item standardization of the features (via a \\textit{StandardScaler});\n\t\\item Principal Component Analysis (whose effects will be studied in appendix \\ref{app:dim_reduction});\n\t\\item label encoding (numerical or one-hot depending on the model).\n\\end{enumerate}\n\nIn addition to the four models listed above, also a feed-forward neural network has been built, with the purpose of having a more customizable architecture and the possibility of monitoring the behavior of the loss across the epochs. Such network is structured in the following way:\n\\begin{itemize}\n\t\\itemsep0em\n\t\\item 3 layers with $1024 \\to 512 \\to 50$ nodes;\n\t\\item \\textit{PreLU} as activation function;\n\t\\item Dropouts and BatchNormalizations;\n\t\\item \\textit{Categorical Cross-Entropy} as loss function.\n\\end{itemize}\n\nAnd now it's just about running the training procedure for several parameters/methods/models and complete all the studies necessary to find the combination that will guarantee the higher accuracy and stability.\n\n\n\\subsection{Spectrograms Classification}\n\\label{sec:spectrograms_classification}\nOne of the main differences between the previous methods and the spectrograms classification is the memory required: in the latter case, in fact, we need to store one image per clip, and an image is much bigger than a vector with just one hundred of samples. We will, usually have to deal with datasets larger than 1 Gb, with the consequent difficulties in loading and manipulating them. For this reason, using a binary file format for data storage can bring to a significant improvement in term of performances, and consequently also on the model's training time. Binary data, in fact, takes up less space on disk, especially when compressed, and can be read in a much more efficient way. \\textit{Tensorflow} has developed its own binary storage format, that is the \\textit{TFRecord} \\footnote{\\href{https://medium.com/mostly-ai/tensorflow-records-what-they-are-and-how-to-use-them-c46bc4bbb564}{Tensorflow Records? What they are and how to use them}} format, gifted of a lot of preprocessing functionalities and the possibility of loading from the disk and processing, only the data required at that particular time, allowing for an efficient way to deal with large datasets. Unfortunately, this way of proceeding forbid the usage of cross validation, but at the expenses of a small further preparation step (simply generating $k$ tfrecord files splitting the clips by label before loading them) one can still exploit the method to compensate the scarcity of data. After having determined how to handle such large quantity of images, is time to select the machine learning classifier, and the choice fell on Convolutional Neural Networks, whose high performances has already been proved by several other studies. Apparently, in fact, the possibility of learning local structures from a bidimensional input outperforms the previous approaches, mainly based on the extraction of vectors of features, directly from the raw audio files.\\\\\nThen it's all about selecting a proper architecture to fit the spectrograms of the clips. The following choices have been dictated by a long research phase to achieve the best performances in term of accuracy and stability:\n\\begin{itemize}\n\t\\itemsep0em\n\t\\item labels are one-hot encoded;\n\t\\item the loss function is the \\textit{Categorical Crossentropy} while the first metric is the \\textit{Categorical Accuracy};\n\t\\item the optimizer is \\textit{Adamax}, that apparently works better than \\textit{Adam} for almost any architecture studied;\n\t\\item the learning rate is quite small, $lr = 0.00005$, that turned out to represent a good tradeoff between training speed, stability and accuracy; an adaptive learning rate is possible, but apparently does not affect very well the stability of the convergence.\n\\end{itemize}\nThe architecture used is represented in figure \\ref{fig:cnn_architecture}, in which we can distinguish 3 convolutional blocks, characterized by an increasing number of filters and a progressive reduction of the kernel size, in order to simplify the learning of features that will be smaller and smaller as they pass through the network. In fact, at the end of each block there is a \\textit{MaxPooling} layer with the purpose of reducing the size of the input images: particularly relevant is the first pooling layer, which strides are set to $(2,4)$, in such a way that images can be reshaped from a rectangular to a square form. Then, there is a fourth fully-connected block that ends with a layer composed by exactly 50 neurons, corresponding to the 50 possible classes of the images. As activation function the \\textit{PReLU} has been selected for all the layers, since it helps the network to prevent vanishing gradients and does not increase too much the time necessary to process the epochs. This architecture has been inspired by several Convolutional models and canonical structures that have been used for this kind of problems, and in particular to AlexNet \\cite{alexnet} and VGG16 \\cite{vgg16}, even if those ones were mainly designed for the dataset ImageNet \\cite{imagenet}.\n\\begin{figure}[!h]\n\t\\centering\n\t\\includegraphics[width=0.45\\textwidth]{pictures/cnn_architecture.pdf}\n\t\\caption{Architecture of the Convolutional Neural Network.}\n\t\\label{fig:cnn_architecture}\n\\end{figure}\n\nAs last trial to reach a decent accuracy, a more complex architecture has been built merging a feedforward network and the convolutional described above. Its schematic representation is left at figure \\ref{fig:finalnet_architecture}: the idea is using for each clip a double input, made by the features vector and the spectrogram, that will proceed independently one of the other, trough the branches of the network, and the end a unique layer of 50 nodes will predict the class biased by both branches.\n\n\\begin{figure}[!h]\n\t\\centering\n\t\\includegraphics[width=0.45\\textwidth]{pictures/finalnet_architecture.pdf}\n\t\\caption{Architecture of the composite Neural Network (FFN + CNN).}\n\t\\label{fig:finalnet_architecture}\n\\end{figure}\n\n\n\n", "meta": {"hexsha": "9803f2999de4ee3fed7ac4d4336c29acf12d4a06", "size": 19684, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Report/model.tex", "max_stars_repo_name": "MattiaPujatti/Environmental-Sound-Classification", "max_stars_repo_head_hexsha": "8fc4ce6db6cb30bb2ba21e0d0ada93e340a5a71e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-11-04T08:26:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T13:53:43.000Z", "max_issues_repo_path": "Report/model.tex", "max_issues_repo_name": "MattiaPujatti/Environmental-Sound-Classification", "max_issues_repo_head_hexsha": "8fc4ce6db6cb30bb2ba21e0d0ada93e340a5a71e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Report/model.tex", "max_forks_repo_name": "MattiaPujatti/Environmental-Sound-Classification", "max_forks_repo_head_hexsha": "8fc4ce6db6cb30bb2ba21e0d0ada93e340a5a71e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 140.6, "max_line_length": 1936, "alphanum_fraction": 0.8056797399, "num_tokens": 4241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6584174871563662, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3394931692381252}}
{"text": "\\documentclass{article}\n\\input{preamble}\n\\myexternaldocument[apnd:]{appendix}\n\\title{Asymptotic Risk of B\\'ezier Simplex Fitting}\n\\begin{document}\n\\maketitle\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{abstract}\nThe B\\'ezier simplex fitting is a novel data modeling technique which exploits geometric structures of data to approximate the Pareto front of multi-objective optimization problems.\nThere are two fitting methods based on different sampling strategies.\nThe \\emph{inductive skeleton fitting} employs a stratified subsampling from each skeleton of a simplex, whereas the \\emph{all-at-once fitting} uses a non-stratified sampling which treats a simplex as a whole.\nIn this paper, we analyze the asymptotic risks of those B\\'ezier simplex fitting methods and derive the optimal subsample ratio for the inductive skeleton fitting.\nIt is shown that the inductive skeleton fitting with the optimal ratio has a smaller risk when the degree of a B\\'ezier simplex is less than three.\nThose results are verified numerically under small to moderate sample sizes.\nIn addition, we provide two complementary applications of our theory: a generalized location problem and a multi-objective hyper-parameter tuning of the group lasso.\nThe former can be represented by a B\\'ezier simplex of degree two where the inductive skeleton fitting outperforms.\nThe latter can be represented by a B\\'ezier simplex of degree three where the all-at-once fitting gets an advantage.\n\\end{abstract}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Introduction}\nGiven functions $f_1,\\dots,f_M: X \\to \\R$ on a subset $X$ of the Euclidean space $\\R^N$, consider the multi-objective optimization problem\n\\[\n\\text{minimize } f(x) := (f_1(x), \\dots, f_M(x)) \\text{ subject to } x \\in X (\\subseteq \\R^N)\n\\]\nwith respect to the Pareto ordering: $x \\prec y \\xLeftrightarrow{\\mathrm{def}} \\forall i \\sqbra{f_i(x) \\leq f_i(y)} \\land \\exists j \\sqbra{f_j(x) < f_j(y)}$.\nThe goal is to find the \\emph{Pareto set} and its image, called the \\emph{Pareto front}, which are denoted by\n\\[\nX^*(f) := \\Set{x \\in X | \\forall y \\in X \\sqbra{y \\not\\prec x}}\n\\quad \\text{and} \\quad\nf(X^*(f)) := \\Set{f(x) \\in \\R^M | x \\in X^*(f)},\n\\]\nrespectively.\nSince most numerical optimization approaches give a finite number of points as an approximation of those objects (e.g., goal programming \\cite{Miettinen1999,Eichfelder2008}, evolutionary computation \\cite{Deb2001,Zhang2007,Deb2014}, homotopy methods \\cite{Hillermeier2001,Harada2007}, Bayesian optimization \\cite{Hernandez-Lobato2016,Yang2019}), the complete shapes of them are usually not revealed.\nTo amplify the knowledge extracted from their point approximations, we consider in this paper a fitting problem of the Pareto set and front.\n\nIt is known that those objects often have skeleton structures that can be used to enhance fitting accuracy.\nAn $M$-objective problem is \\emph{simplicial} if the Pareto set and front are homeomorphic to an $(M-1)$-dimensional simplex and each $(m-1)$-dimensional subsimplex corresponds to the Pareto set of an $m$-objective subproblem for all $0 \\le m \\le M$ (see \\cite{Hamada2019} for precise definition and examples).\nThere are a lot of practical problems being simplicial: location problems \\cite{Kuhn1967} and a phenotypic divergence model in evolutionary biology \\cite{Shoval2012} are shown to be simplicial, and an airplane design \\cite{Mastroddi2013} and a hydrologic modeling \\cite{Vrugt2003} hold numerical solutions which imply those problems are simplicial.\nThe Pareto set and front of any simplicial problem can be approximated with arbitrary accuracy by a B\\'ezier simplex of an appropriate degree~\\cite{Kobayashi2019}.\nThere are two fitting algorithms for B\\'ezier simplices: the all-at-once fitting is a na\\\"ive extension of Borges-Pastva algorithm for B\\'ezier curves~\\cite{Borges2002}, and the inductive skeleton fitting~\\cite{Kobayashi2019} exploits the skeleton structure of simplicial problems discussed above.\n\nAn important problem class which is (generically) simplicial is the strongly convex problem.\nIt has been shown that many practical problems can be considered as strongly convex via appropriate transformations preserving the essential problem structure, i.e., the Pareto ordering and the topology~\\cite{Hamada2019}.\nFor example, the multi-objective location problem \\cite{Kuhn1967} can be strongly convex by squaring each objective function.\nThe resulting problem has a Pareto front that can be represented by a B\\'ezier simplex of degree two \\cite{Hamada2019}.\nAs we will show in this paper, the group lasso \\cite{Yuan2006} can be reformulated as a simplicial problem.\nIt has a cubic Pareto front that requires a B\\'ezier simplex of degree three.\nThe same transformation can be applied to a broad range of sparse learning methods, including the (original) lasso \\cite{Tibshirani1996}, the fused lasso \\cite{Tibshirani2005}, the smooth lasso \\cite{Hebiri2011}, and the elastic net \\cite{Zou2005}.\nSince the required degree is problem-dependent, we need to understand the performance of the two B\\'ezier simplex fittings with respect to the degree.\n\nIn this paper, we study the asymptotic risk of the two fitting methods of the B\\'ezier simplex: the all-at-once fitting and the inductive skeleton fitting, and compare their performance with respect to the degree.\n\nOur contributions are as follows:\n\\begin{itemize}\n\\item We have evaluated the asymptotic $\\ell_2$-risk, as the sample size tends to infinity, of two B\\'ezier simplex fitting methods: the all-at-once fitting and the inductive skeleton fitting.\n\\item In terms of minimizing the asymptotic risk, we have derived the optimal ratio of subsample sizes for the inductive skeleton fitting.\n\\item We have shown when the inductive skeleton fitting with optimal ratio outperforms the all-at-once fitting when the degree of a B\\'ezier simplex is two, whereas the all-at-once has an advantage at degree three.\n\\item We have demonstrated that the location problem and the group lasso are transformed into strongly convex problems, and their Pareto fronts are approximated by a B\\'ezier simplex, which numerically verifies the asymptotic results.\n\\end{itemize}\n\nThe rest of this paper is organized as follows:\n\\cref{sec:problem-definition} describes the problem definition.\n\\Cref{sec:asymptotic-risk} analyzes the asymptotic risks of the all-at-once fitting and the all-at-once fitting.\nFor the inductive skeleton fitting, the optimal subsample ratio in terms of minimizing the risk is derived.\nThose analyses are verified in \\cref{sec:numerical-examples} via numerical experiments.\n\\Cref{sec:conclusion} concludes the paper and addresses future work.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Problem definition}\\label{sec:problem-definition}\nLet $M$ be a non-negative integer.\nThe \\emph{standard $(M - 1)$-simplex} is defined by\n\\[\n\\Delta^{M - 1} = \\Set{(w_1, \\dots, w_M) \\in \\R^M | \\sum_{m = 1}^M w_m = 1,\\ w_m \\geq 0}.\n\\]\nFor an index set $I \\subseteq \\set{1, \\dots, M}$, we define the \\emph{$I$-subsimplex} of $\\Delta^{M - 1}$ by $\\Delta^I = \\set{(w_1, \\dots, w_M) \\in \\Delta^{M - 1} | w_m = 0\\ (m \\not \\in I)}$.\nFor an integer $0 \\leq m \\leq M$, the \\emph{$(m - 1)$-skeleton} of $\\Delta^{M - 1}$ is defined by\n\\[\n\\Delta^{(m-1)} = \\bigcup_{I \\subseteq \\set{1, \\dots, M} \\text{ s.t. } \\card{I}=m} \\Delta^{M-1}_I.\n\\]\n\n\\subsection{B\\'ezier simplex and its fitting methods}\\label{sec:bezier-simplex}\nLet $\\N$ be the set of non-negative integers (including zero!) and $M, D \\in \\N$.\nWe denote a simplex lattice by $\\N_D^M := \\set{(d_1,\\dots,d_M) \\in \\N^M | \\sum_{m=1}^M d_m = D}$.\nGiven the \\emph{control points} $\\bm p_{\\bm d} \\in \\R^L$ $(\\bm d \\in \\N_D^M)$, an \\emph{$(M - 1)$-B\\'ezier simplex of degree $D$} is a mapping $\\bm b(\\bm t): \\Delta^{M-1}\\to\\R^L$ defined by\n\\begin{equation}\\label{eqn:bezier-simplex}\n\\bm b(\\bm t) := \\sum_{\\bm d\\in\\N_D^M} \\binom{D}{\\bm d} \\bm t^{\\bm d} \\bm p_{\\bm d}\n\\end{equation}\nwhere $\\binom{D}{\\bm d} := \\frac{D!}{d_1! d_2! \\cdots d_M!}$, and for each $\\bm t := (t_1, \\dots, t_M) \\in \\R^M$ and $\\bm d := (d_1, \\dots, d_M) \\in \\N^M$, $\\bm t^{\\bm d}$ is a monomial $t^{d_1}_1 t^{d_2}_2 \\cdots t^{d_M}_M$.\n\nKobayashi \\text{et al.} \\cite{Kobayashi2019} proposed two B\\'ezier simplex fitting algorithms: the all-at-once fitting and the inductive skeleton fitting.\nThey are different in not only fitting algorithm but also sampling strategy.\nThe all-at-once fitting requires a training set $S_N:=\\set{(\\bm t_n, \\bm x_n) \\in \\Delta^{M-1} \\times \\R^L | n = 1, \\dots, N}$ and adjusts all control points at once by minimizing the ordinary least square loss: $\\frac{1}{N}\\sum_{n=1}^N \\norm{\\bm x_n - \\bm b(\\bm t_n^{(m)})}^2$.\n\nThe inductive skeleton fitting, on the other hand, requires skeleton-wise sampled training sets $S_{N^{(m)}} := \\set{(\\bm t^{(m)}_n, \\bm x^{(m)}_n) \\in \\Delta^{(m)} \\times \\R^L | n = 1, \\dots, N^{(m)}}~(m=0,\\ldots,M-1)$.\nIt also divides control points as $\\bm p_{\\bm d}^{(m)}$ such that $\\bm d$ has $m+1$ non-zero elements.\nSuch $\\bm p_{\\bm d}^{(m)}$ determine $m$-skeleton of a B\\'ezier simplex.\nThe inductive skeleton fitting inductively adjusts $\\bm p_{\\bm d}^{(m)}$ from $m = 0$ to $M - 1$ by minimizing the ordinary least square loss of the $m$-skeleton $\\frac{1}{N^{(m)}}\\sum_{n=1}^{N^{(m)}} \\norm{\\bm x^{(m)}_n - \\bm b(\\bm t_n)}^2$.\n\n\\subsection{The \\texorpdfstring{$\\ell_2$}{l2}-risk}\nThe fitting problem considered in this paper is as follows.\nThe sample is taken from an unknown B\\'ezier simplex $\\bm b(\\bm t): \\Delta^{M-1} \\to \\R^L$ with additive Gaussian noise $\\bm \\varepsilon \\sim N(\\bm 0, \\sigma^2 \\bm I)$, that is, $\\bm x = \\bm b(\\bm t) + \\bm \\varepsilon$.\nFor the all-at-once fitting, $S_N = \\set{(\\bm t_n, \\bm x_n)}$ follows the uniform distribution on the domain of the B\\'ezier simplex: $\\bm t_n \\sim U(\\Delta^{M-1})$ and $\\bm x_n = \\bm b(\\bm t_n) + \\bm \\varepsilon_n$.\nFor the inductive skeleton fitting, $S_{N^{(m)}} = \\set{(\\bm t_n^{(m)}, \\bm x_n^{(m)})}$ follows the uniform distribution on the $m$-skeleton of the domain of the B\\'ezier simplex: $\\bm t_n^{(m)} \\sim U(\\Delta^{(m)})$ and $\\bm x_n^{(m)} = \\bm b(\\bm t_n^{(m)}) + \\bm \\varepsilon_n^{(m)}$.\nA B\\'ezier simplex estimated from $S_N$ is denoted by $\\bm{\\hat b}(\\bm t | S_N)$.\nFor both method, we asymptotically evaluate the $\\ell_2$-risk below as $N \\to \\infty$.\n\\begin{equation}\\label{eqn:risk-def}\nR_N := \\E_{S_N}\\sqbra{\\E_{\\bm t \\sim U(\\Delta^{M-1})} \\norm{\\bm b(\\bm t) - \\hat{\\bm b}(\\bm t | S_N)}^2}.\n\\end{equation}\nHere, we put $S_N = S_{N^{(0)}} \\cup \\dots \\cup S_{N^{(M-1)}}$ for the inductive skeleton fitting.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Asymptotic risk of B\\'ezier simplex fitting}\\label{sec:asymptotic-risk}\nTo calculate the risk of each fitting scheme, let us first focus on the fact: the summation/subtraction of two B\\'ezier simplices is also B\\'ezier simplex.\nIn the definition \\cref{eqn:risk}, we have $\\bm b(\\bm t) - \\hat{\\bm b}(\\bm t | S_N)$ which measures the difference between the target B\\'ezier simplex and the model B\\'ezier simplex.\nBy using the above fact, $\\bm b(\\bm t) - \\hat{\\bm b}(\\bm t | S_N)$ is also B\\'ezier simplex.\nLet us call its control point as $\\bm p'$, and consider the following matrix,\n\\begin{align}\n\\bm P\n=\n\\begin{bmatrix}\n(\\bm p_1')_1 &\n(\\bm p_1')_2 & \n\\cdots &\n(\\bm p_1')_L \n\\\\\n(\\bm p_2')_1 &\n(\\bm p_2')_2 & \n\\cdots &\n(\\bm p_2')_L \n\\\\\n\\quad \\vdots&\n\\quad \\vdots & \n\\ddots &\n\\quad \\vdots\n\\\\\n(\\bm p_{\\card{\\N_D^M}}')_1 &\n(\\bm p_{\\card{\\N_D^M}}')_2 & \n\\cdots &\n(\\bm p_{\\card{\\N_D^M}}')_L \n\\end{bmatrix}\n,\n\\end{align}\nwhere $(\\bm p_A)_{l}$ means the $l$-th component of the $A$-th control point vector $\\bm p_A$.\n%%%\nThe asymptotic rick can be calculated by the following theorem.\n\\begin{theorem}\\label{thm:risk}\nThe risk of the B\\'ezier simplex fitting can be represented by\n\\begin{align}\nR_N\n=\n\\sum_{\\bm d_A, \\bm d_B \\in \\mathbb{N}_D^M}\n\\ZZ_{AB}\n\\E_{S_N} \\sqbra{({\\bm P} {\\bm P}^\\top)_{AB}}\n,\n\\label{eqn:risk}\n\\end{align}\nwhere the matrix $\\ZZ$ is defined by\n\\begin{align}\n\\ZZ_{AB}\n=\n\\frac{(2D)!(M-1)!}{(2D+M-1)!}\n  \\binom{D}{\\bm d_A}\n  \\binom{D}{\\bm d_B}\n  \\binom{2D}{\\bm d_A + \\bm d_B}^{-1}\n  \\label{eqn:ZZ-def}\n\\end{align}\n\\end{theorem}\nThe proof is provided in the supplementary materials (\\cref{apnd:sec:proof-of-main-theorem}).\nOnce the set of parameters of the system, including the simplex dimension $M$, degree of the B\\'esier simplex $D$, the dimension of the target data $L$, the amplitude of the noise $\\sigma$, is fixed, the equation \\cref{eqn:risk} says that the asymptotic value of this risk function depends only on how we choose the matrix $\\bm P$.\nWe calculate the asymptotic form of the risk \\cref{eqn:risk} with $\\bm P$ determined from the all-at-once (AAO) fitting and the inductive-skeleton (ISK) fitting.\nWe call them $\\bm P_\\mathrm{AAO}$ and $\\bm P_\\mathrm{ISK}$ respectively.\n\n\\subsection{All-at-once fitting}\\label{sec:all-at-once-fitting}\n\\paragraph{Samples and determined control points}\nLet us recall the sample $S_N$ consists of elements $(\\bm t_n, \\bm x_n) \\in \\Delta^{M-1} \\times \\R^L$ with $\\bm x_n = \\bm b(\\bm t_n) + \\bm \\varepsilon_n$ and $\\bm t_n \\sim U(\\Delta^{M-1})$, $\\bm \\varepsilon_n \\sim N(0, \\sigma^2 \\bm I)$ for $n = 1, \\dots, N$.\nThe matrix $\\bm P_\\mathrm{AAO}$ is determined by minimization of the OLS error below\n\\begin{align}\n\\frac 1 N \\sum_{n=1}^N \\norm{\\bm x_n - \\hat{\\bm b}(\\bm t_n)}^2 \n%&= \\frac 1 N \\sum_{n=1}^N \\norm{\\sum_{\\bm d\\in\\N_D^M} \\binom{D}{\\bm d}\\bm t_n^{\\bm d}  \\bm p'_{\\bm d} + \\bm \\varepsilon_n}^2\\notag\\\\\n&= \\frac 1 N \\norm{ \\bm Z \\bm P + \\bm Y }_{\\mathrm F}^2, \\label{eqn:rss}\n\\end{align}\nwhere $\\norm{\\cdot}_\\mathrm{F}$ means the Frobenius norm and\n$\\bm z_n = [\\text{a vector with component } \\binom{D}{\\bm d}\\bm t_n^{\\bm d}~(\\bm d\\in \\N_D^M)] \\in \\R^{\\card{\\N_D^M}}$, $\\bm Z = \\sqbra{\\bm z_1 \\bm z_2 \\cdots \\bm z_N}^\\top \\in \\R^{N \\times \\card{\\N_D^M}}$, $\\bm Y = \\sqbra{\\bm \\varepsilon_1 \\bm \\varepsilon_2\\cdots \\bm \\varepsilon_N}^\\top \\in \\R^{N \\times L}$.\nIn this notation, the optimum takes well known form: $\\bm P_\\mathrm{AAO} = -\\paren{\\bm Z^\\top \\bm Z}^{-1}\\bm Z^\\top \\bm Y$.\nNote that the regularity of the matrix $\\bm Z^\\top \\bm Z$ is guaranteed by taking a sufficiently large number of samples $S_N$, or more precisely $\\set{\\bm t_n}_{n = 1, \\dots, N}$.\n\n%%%\n\\paragraph{Calculation of the asymptotics}\nTo calculate the risk asymptotics \\cref{eqn:risk} in the all-at-once fitting, we need to calculate asymptotic values of expectation values of the matrix $\\bm P_\\mathrm{AAO} \\bm P_\\mathrm{AAO}^\\top$ over $S_N$.\n%\nThe first observation is that the contribution from the noise matrix $\\bm Y$ is only located at the middle of the sequence of matrix product $\\bm P_\\mathrm{AAO} \\bm P_\\mathrm{AAO}^\\top = \\paren{\\bm Z^\\top \\bm Z}^{-1}\\bm Z^\\top \\bm Y \\bm Y^\\top \\bm Z \\paren{\\bm Z^\\top \\bm Z}^{-1}$.\nIf $\\bm Y \\bm Y^\\top \\propto 1_N$, the calculation reduces very simple form.\nIn fact, we can perform it by decomposing $\\E_{S_N}$ to $\\E_{\\bm t_n} \\E_{\\bm \\varepsilon_n}$.\nAfter taking expectation value $\\E_{\\bm \\varepsilon_n}$,\nwe get\n\\begin{align}\n\\E_{S_N} \\sqbra{\\bm P_\\mathrm{AAO} \\bm P_\\mathrm{AAO}^\\top}\n&= %%%%\n\\sigma^2 L \\cdot\n\\E_{\\bm t_n} \\sqbra{\n\\paren{\\bm Z^\\top \\bm Z}^{-1}\n}\n.\n\\label{eqn:P_AAO-P_AAO}\n\\end{align}\nThe prefactor $\\sigma^2 L$ results from taking expectation over the noise.\nHere, $L$ is the dimension of the space control points lived in.\n%\nNow, the only remaining task is the estimation of the asymptotic behavior of the matrix $(\\bm Z^\\top \\bm Z)$.\n%\nA key observation is that each element of this matrix is an average over the samples $\\bm t_n$:\n\\begin{align}\n\\frac{1}{N}\n\\paren{\\bm Z^\\top \\bm Z}_{AB}\n=\n\\binom{D}{\\bm d_A}\n\\binom{D}{\\bm d_B}\n\\sum_{n=1}^N \n\\frac{1}{N}\n\\bm t_n^{\\bm d_A + \\bm d_B}\n.\n\\end{align}\nIn fact, it converges to the matrix $\\ZZ_{AB}$ defined in \\cref{eqn:ZZ-def} as $N \\to \\infty$.\nTherefore, by using the law of large numbers, we can get \n$\n\\paren{\\bm Z^\\top \\bm Z}_{AB}\n\\overset{p}{\\to}\nN \\ZZ_{AB}.\n$\nTo substitute it to \\cref{eqn:P_AAO-P_AAO}, we need to guarantee $\\ZZ_{AB}$ has the inverse matrix, i.e.\n\\begin{theorem}\\label{thm:sigma-is-non-singular}\nFor any $D, M$, the matrix $\\ZZ_{AB}$ in \\cref{eqn:ZZ-def} is non-singular.\n\\end{theorem}\nThe proof is given in the supplementary materials (\\cref{apnd:sec:proof-of-regularity}).\nJust by replacing $(\\bm Z^T \\bm Z)$ to $N \\ZZ$, we arrive at the asymptotic form of the risk.\nIn addition to it, we can further simplify the result by using: $\\sum_{AB} \\ZZ_{AB}\n\\ZZ^{-1}_{AB} = \\ _{D+M-1} C_D$, which is relatively easy to show (see \\cref{apnd:sec:derivation-of-sum} in the supplementary materials).\n\\if0\n\\footnote{\nLet $\\tilde{\\ZZ}$ be a cofactor matrix and $C_{AB}$ be a $(A, B)$ minor of $\\ZZ$.\n\\begin{equation*}\n\\begin{split}\n\\sum_{A, B} \\ZZ_{AB} \\ZZ_{AB}^{-1}\n    &= \\sum_{A,B} \\left(\\frac{1}{\\det(\\ZZ)}\\tilde{\\ZZ} \\circ \\ZZ\\right)_{AB} %\\\\\n    %&= \\frac{1}{\\det(A)}\\sum_{i, j = 1}^N (\\tilde{A}\\circ A)_{ij} \\\\\n    %&\n    = \\frac{1}{\\det(\\ZZ)}\\sum_{A,B} \\ZZ_{AB}C_{AB} \\\\\n    &= \\frac{1}{\\det(\\ZZ)}\\sum_{A}^{} \\det(\\ZZ)\n    =  \\ _{D+M-1} C_D.\n\\end{split}\n\\end{equation*}\nFrom 1st line to 2nd line, we use the definition of the determinant of $\\ZZ$.\n}\n\\fi\n\nIn summary, our formula for the asymptotic form of the risk for the all-at-once fitting is\n\\begin{align}\nR_N \\overset{p}{\\to}\n\\frac{\\sigma^2 L}{N}\n\\sum_{A, B}\n\\ZZ_{AB}\n\\ZZ^{-1}_{AB}\n=\n\\frac{\\sigma^2 L}{N}\n\\ _{D+M-1} C_D \\quad \\text{as $N \\to \\infty$}.\n\\label{eqn:risk-all-at-once}\n\\end{align}\n\n%%\n\\subsection{Inductive skeleton fitting}\\label{sec:inductive-skeleton-fitting}\nBefore showing the asymptotic form of the risk for the inductive skeleton fitting, it would be better to introduce some notations here.\nTo treat subsimplices of the simplex $\\Delta^{M-1}$, it is useful to notice that there is a one-to-one correspondence between a subsimplex and $M$-dimensional binary vector:\n\\begin{align}\n\\text{a subsimplex of $\\Delta^{M-1}$}\n\\quad\n\\Longleftrightarrow\n\\quad\n\\bm I = [I_1, I_2, \\dots, I_M], \\quad\nI_i \\in \\Set{0, 1}, \\quad\n\\bm I \\neq \\bm 0.\n\\end{align}\nIn this notation, $\\Delta^{M-1}$ itself is identified to $[1,1, \\dots, 1]$.\nThe sum $\\card{\\bm I} = \\sum_{i=1,2, \\dots, M} I_i$ provides the dimension + 1 of the corresponding subsimplex.\nWe call a subsimplex indexed by $\\bm I$ as $\\Delta^{\\bm I}$ from now on.\nIn addition, it is useful to define notation for the set of all $(m-1)$-dimensional subsimplices:\n\\begin{align}\n(m) = \\text{all $(m)$-dimensional subsimplices of $\\Delta^{M-1}$}\n=\n\\cup_{\\card{\\bm I} = m+1} \\Delta^{\\bm I}\n,\n\\end{align}\nand we call corresponding control point submatrices as $\\bm P^{(m)}$.\n%\n\n\\paragraph{Samples and determined control points}\nIn this notation, we can state that the inductive skeleton fitting is an inductive procedure of determining control points matrices $\\bm P^{(m)}$ from low $m=0, 1, \\dots, M-1$.\n%\nSuppose all $\\set{\\bm P^{(k)}}_{k < m}$ are already fixed and the samples on $\\cup_{\\card{\\bm I} = m} \\Delta^{\\bm I}$,\n$S_{N^{(m)}} = \\set{(\\bm t_1^{(m)}, \\bm x_1^{(m)}), \\dots, (\\bm t_{N^{(m)}}^{(m)}, \\bm x_{N^{(m)}}^{(m)})}$ are provided from\n${\\bm t}_n^{(m)} \\sim U(\\cup_{\\card{\\bm I} = m+1} \\Delta^{\\bm I})$.\nThe $m$-th submatrix $\\bm P^{(m)}$ is determined by minimizing the OLS error\n\\begin{align}\n%&\\frac{1}{N^{(m)}}\n%\\sum_{n = 1}^{N^{(m)}}\n%\\norm{ {\\bm x}_{n}^{(m)} - \n%\\hat{\\bm b} ({\\bm t}_{n}^{(m)}) }^2\n%\\notag \\\\\n%&= %%%%\n&\n\\frac{1}{N^{(m)}}\n\\sum_{n = 1}^{N^{(m)}}\n\\norm{\n\\bm x_n^{(m)}\n-\n\\hat{\\bm b}(\\bm t_n^{(m)})\n}^2\\label{eqn:OLS}\n\\end{align}\nNote that there is no need to take any control point on $\\Delta^{\\bm J}$ with $\\card{\\bm J} > m$ into account because each $\\bm t_n^{(m)}$ is on $\\Delta^{\\bm I}$ with $\\card{\\bm I} = m+1$ and there is no contribution to $\\hat{\\bm b}(\\bm t_n^{(m)})$ from such higher dimensional control point.\nIn addition, we regard lower dimensional control points already fixed, so the net objective control points are ones included in $\\bm P^{(m)}$.\nBy repeating similar procedure done in the all-at-once fitting, we can conclude $\\bm P^{(m)}$ is determined as\n\\begin{align}\n{\\bm P}_\\mathrm{OLS}^{(m)}\n= %%%%\n-\n[({\\bm Z}^{(m)})^\\top {\\bm Z}^{(m)}]^{-1}\n({\\bm Z}^{(m)})^\\top \n\\paren{\n{\\bm Y}^{(m)}\n+\n\\sum_{k < m}\n{\\bm Z}^{(m) [k]}\n{\\bm P}_\\mathrm{OLS}^{(k)}\n}\n\\label{eqn:P_OLS}\n\\end{align}\nwhere\n$\n{\\bm z}_{n}^{(m)[k]}\n=\n\\sqbra{\\text{a vector with component }\n({\\bm z}_{n}^{(m)})^{{\\bm d}^{(k)}}\n}$,\n$\n{\\bm Z}^{(m) [k]}\n=\n\\sqbra{{\\bm z}_1^{(m) [k]}\n \\bm{z}_2^{(m) [k]}\n \\cdots \n {\\bm z}_{N^{(m)}}^{(m) [k]}}^\\top$,\n$\n{\\bm Y}^{(m)}\n=\n\\sqbra{{\\bm \\varepsilon}_1^{(m)} \\bm{\\varepsilon}_2^{(m)} \\cdots {\\bm \\varepsilon}_{N^{(m)}}^{(m)}}^\\top\n.\n$\n%%%\n\n\\paragraph{Calculation of the asymptotics}\nWe get ${\\bm P_\\mathrm{ISK}} {\\bm P_\\mathrm{ISK}}^\\top\n=\n\\oplus_{i, j=0}^{M-1}\n{\\bm P}^{(i)}_\\mathrm{OLS}\n({\\bm P}^{(j)}_\\mathrm{OLS})^\\top\n$ which we need to compute the risk \\cref{eqn:risk}.\n%This matrix is determined from lower sub matrices.\n%\nAs one might notice, the risk for the inductive-skeleton fitting depends on each number of $(m)$-dimensional subsamples $N^{(m)}$.\nWe will determine the best combination of $N^{(m)}$ constrained on $\\sum_m N^{(m)} = N$ later.\nHere, we treat the risk depending not $N$ but every $N^{(m)}$ and call it as\n$\nR_{N^{(0)}, N^{(1)}, \\dots, N^{(M-1)}}\n$.\n%\nTo calculate $\\E_{S_N} [\\bm P_{ISK} \\bm P_{ISK}^\\top]$, we again take expectation over noise.\nThanks to $\\E [\\bm Y^{(m)} (\\bm Y^{(n)})^\\top ] = \\sigma^2 L \\bm 1_{N^{(m)}}$ or $\\bm 0$ depending on $m=n$ or not, and the central limit with respect to $\\bm z_n$, one can get\n\\begin{align}\n&\\E_{ S_N }\n\\sqbra{\n{\\bm P}^{(i)}_\\mathrm{OLS}\n({\\bm P}^{(j)}_\\mathrm{OLS})^\\top\n}\n\\notag \\\\\n&\\overset{p}{\\to}\n\\sigma^2 L\n\\sum_{\n\\substack{\nm \\leq i\n\\\\\nm \\leq j\n}}\n\\sum_{\n\\substack{\nm \\leq k_1 < \\dots < k_{\\heartsuit} < i\n\\\\\nm \\leq l_1 < \\dots < l_{\\spadesuit} < j\n}\n}\n\\frac{(-1)^{\\heartsuit + \\spadesuit}}{N^{(m)}}\n%\\notag \\\\ \\nline \\quad \\times %\\qquad %\\qquad\n{\\bm \\Lambda}_{(i)}\n{\\bm \\Lambda}^{(i)[k_{\\heartsuit}]}\n{\\bm \\Lambda}_{(k_{\\heartsuit} )}\n%\\hat{\\bm \\Lambda}^{(k_{\\#_i})[k_{\\#_i -1}]}\n\\cdots\n{\\bm \\Lambda}^{(k_1)[m]}\n{\\bm \\Lambda}_{(m)}\n{\\bm \\Lambda}^{[m](l_1)}\n\\cdots\n{\\bm \\Lambda}_{(l_{\\spadesuit} )}\n{\\bm \\Lambda}^{[l_{\\spadesuit}](j)}\n{\\bm \\Lambda}_{(j)}\n\\label{eqn:P_OLS-P_OLS}\n\\end{align}\nafter substituting the recursive formula \\cref{eqn:P_OLS} repeatedly, where\n\\begin{align}\n&({\\bm \\Lambda}^{(m)[k]})_{ \\bm d ^{(m)} \\bm d ^{(k)} }\n%\\notag \\\\\n= %%%%\n\\frac{(m-1)!}{\\ _{M} C_m}\n\\begin{pmatrix}\nD \\\\\n{\\bm d}^{(m)}\n\\end{pmatrix}\n%\n\\begin{pmatrix}\nD \\\\\n{\\bm d}^{(k)}\n\\end{pmatrix}\n%\n\\sum_{ \\card{I} = m }\n\\frac{\n\\delta_{{\\bm I}, (\\bm d ^{(m)} +  \\bm d ^{(k)} )_{01} }\n\\prod_{I_i = 1}( \\bm d ^{(m)} +  \\bm d ^{(k)}  )_i !}{\n[\\sum_{I_i = 1} ( \\bm d ^{(m)} +  \\bm d ^{(k)}  )_i \n+ m - 1]!\n},\n\\notag\n\\\\\n&\n{\\bm \\Lambda}^{[k](m)}\n=\n{\\bm \\Lambda}^{(m)[k]},\n\\quad\n{\\bm \\Lambda}_{(m)}\n%\\notag \\\\\n= \n({\\bm \\Lambda}^{(m)[m]})^{-1}\n\\label{eqn:Lamb}\n\\end{align}\nand\n\\begin{align}\n\\delta_{{\\bm I}, (\\bm d ^{(m)} +  \\bm d ^{(k)} )_{01} }\n&=\n\\left\\{ \\begin{array}{ll}\n1 & ( {\\bm I} = (\\bm d ^{(m)} +  \\bm d ^{(k)} )_{01}  ) \\\\\n0 & \\text{otherwise}\\\\\n\\end{array} \\right.\n\\end{align}\nFor the complete derivation, see \\cref{apnd:sec:risk-derivation} in the supplementary materials.\nWe stop here and leave to get a closed formula for the asymptotics of the risk on inductive-skeleton fitting as future work.\nInstead, we calculate the asymptotic risk numerically by using \\cref{eqn:P_OLS-P_OLS,eqn:risk} and obtain \\cref{tab:risk-inductive}.\n%%\n\\begin{table}[H]\n\\centering\n\\caption{Numerically computed asymptotic risks of the inductive skeleton fitting ($M$: dimension of B\\'ezier simplex, $D$: degree of B\\'ezier simplex, $N^{(m)}$: sample size of $(m)$-skeleton).}\\label{tab:risk-inductive}\n\\begin{tabular}{l|ll} \\toprule\n$R_{N^{(0)}, N^{(1)}, \\dots}$ &\n$D = 2$ &\n$D = 3$\n\\\\ \\midrule\n$M = 2$ &\n$1.0 / N^{(1)} + 0.5 / N^{(0)}$ &\n$2.0 / N^{(1)} + 0.2666 / N^{(0)}$\n\\\\\n$M = 3$ &\n$3.0 / N^{(1)} + 0.375 / N^{(0)}$ &\n$1.0 / N^{(2)} + 3.535 / N^{(1)} + 0.1464 / N^{(0)}$\n\\\\\n$M = 4$ &\n$5.142 / N^{(1)} + 0.4571 / N^{(0)}$ &\n$5.333 / N^{(2)} + 4.714 / N^{(1)} + 0.1650 / N^{(0)}$\n\\\\\n$M = 5$ &\n$7.142 / N^{(1)} + 0.625 / N^{(0)}$ &\n$13.33 / N^{(2)} + 6.666 / N^{(1)} + 0.2083 / N^{(0)}$\n\\\\\n$M = 6$ &\n$8.928 / N^{(1)} + 0.8214 / N^{(0)}$ &\n$24.24 / N^{(2)} + 9.740 / N^{(1)} + 0.2575 / N^{(0)}$\n\\\\\n$M = 7$ &\n$10.5 / N^{(1)} + 1.020 / N^{(0)}$ &\n$37.12 / N^{(2)} + 13.84 / N^{(1)} + 0.3119 / N^{(0)}$\n\\\\\n$M = 8$ &\n$11.87 / N^{(1)} + 1.212 / N^{(0)}$ &\n$51.17 / N^{(2)} + 18.73 / N^{(1)} + 0.3723 / N^{(0)}$\n\\\\ \\bottomrule\n\\end{tabular}\n\\end{table}\n\n%%\n\\subsection{All-at-once vs Inductive skeleton}\\label{sec:all-vs-inductive}\n\\Cref{tab:risk-inductive} tells the risk of the inductive skeleton fitting depends on subsample sizes $N^{(m)}$.\nGiven total sample size $N$, we can minimize the risk by finding the optimally-decoupled subsample sizes:\n\\begin{align}\n    R_N := \\min_{N^{(0)}, \\dots, N^{(M-1)}} \\Set{R_{N^{(0)}, \\dots, N^{(M-1)}}} \\text{ subject to } \\sum_{m=0}^{M-1} N^{(m)} = N.\n\\end{align}\nWe calculated optimal risks for all cases shown in \\cref{tab:risk-inductive} and compared them to the risks of the all-at-once fitting.\n\\Cref{tab:risk-comparison} shows the results.\n\\begin{table}[H]\n\\centering\n\\caption{Comparison of asymptotic risks of the all-at-once $R_N^\\mathrm{AAO}$ vs the inductive skeleton with the optimal subsample ratio $R_N^\\mathrm{ISK}$ ($M$: dimension of B\\'ezier simplex, $D$: degree of B\\'ezier simplex, $N$: sample size). The winner is shown in bold.}\\label{tab:risk-comparison}\n\\begin{tabular}{l|ll|ll} \\toprule\n& \\multicolumn{2}{c|}{$D = 2$} & \\multicolumn{2}{c}{$D = 3$} \\\\ \n& $R_{N}^\\mathrm{AAO}$ & $R_N^\\mathrm{ISK}$\n& $R_{N}^\\mathrm{AAO}$ & $R_N^\\mathrm{ISK}$\n\\\\ \\midrule\n$M = 2$ &\n$3.0 / N$ &\n$\\bm{2.91421} / N$ &\n$4.0 / N$ &\n$\\bm{3.72726} / N$\n\\\\\n$M = 3$ &\n$6.0 / N$ &\n$\\bm{5.49632} / N$ &\n$\\bm{10.0} / N$ &\n$10.6472 / N$\n\\\\\n$M = 4$ &\n$10.0 / N$ &\n$\\bm{8.66660} / N$ &\n$\\bm{20.0} / N$ &\n$23.8821 / N$\n\\\\\n$M = 5$ &\n$15.0 / N$ &\n$\\bm{11.9936} / N$ &\n$\\bm{35.0} / N$ &\n$44.7548 / N$\n\\\\\n$M = 6$ &\n$21.0 / N$ &\n$\\bm{15.1663} / N$ &\n$\\bm{56.0} / N$ &\n$73.1387 / N$\n\\\\\n$M = 7$ &\n$28.0 / N$ &\n$\\bm{18.0687} / N$ &\n$\\bm{84.0} / N$ &\n$107.570 / N$\n\\\\\n$M = 8$ &\n$36.0 / N$ &\n$\\bm{20.6799} / N$ &\n$\\bm{120.0} / N$ &\n$146.206 / N$\n\\\\ \\bottomrule\n\\end{tabular}\n\\end{table}\n\nAs one can see, the optimum inductive skeleton fitting outperforms the all-at-once fitting in $D = 2$, but it is not always correct in $D = 3$.\nOn $D = 2$, in fact, we can show that the minimum value of the inductive skeleton always less than the asymptotic risk of the corresponding all-at-one fitting.\n\n% \\begin{proposition}\n% Let $N$ be a natural number and $a, b$ be positive real numbers. Let $f(x) = \\frac{a}{x} + \\frac{b}{N - x}$.\n% Assume $a > b$ and $\\frac{a - \\sqrt{ab}}{a - b} < 1$.\n% Then $\\min \\set{f(x) | x \\in \\R, 0 < x < N} = \\frac{a + b + 2\\sqrt{ab}}{N}$.\n% \\end{proposition}\n\n% We notice that when $N$ is large, we can take an integer which is enough close to $\\frac{a - \\sqrt{ab}}{a - b}N$.\n\n\\section{Numerical examples}\\label{sec:numerical-examples}\nWe examine the empirical performances of the all-at-once fitting and the inductive skeleton fitting and verify the asymptotic risks derived in \\cref{sec:all-at-once-fitting,sec:inductive-skeleton-fitting} over synthetic instances and multi-objective optimization instances. \nExperiment programs were implemented in Python 3.7.1 and run on a Windows 7 PC with an Intel Core i7-4790CPU (3.60 GHz) and 16 GB RAM.\nAll experiments are reproducible by the source code and dependent libraries provided in the supplementary materials.\n\n\\subsection{Synthetic instances}\\label{sec:synthetic-instances}\nTo verify the asymptotic risks derived in \\cref{sec:all-at-once-fitting,sec:inductive-skeleton-fitting}, we consider the fitting problem where the true B\\'ezier simplex $\\bm b(\\bm{t})~(\\bm t \\in \\Delta^{M-1})$ is an $(M-1)$-dimensional unit simplex on $\\R^L$, and randomly generate $N$ training points $\\set{(\\bm t_n, \\bm x_n)}_{n = 1}^N$ as $\\bm x_n = \\bm b(\\bm t_n) + \\bm{\\varepsilon}_n~(\\bm \\varepsilon_n \\sim N(\\bm 0, 0.1^2 \\bm I))$.\nThis synthetic instance is parameterized by a tuple $(L, M, N)$. \n%A synthetic instance is generated as follows: given parameters $(\\sigma, L, M, N)$, we randomly generated $N$ %parameters $\\{\\bm t_n\\}_{n=1}^N$ on $\\Delta^M$ for the all-at-once fitting and the inductive skeleton fitting respectively, and construct \n%training points points , where $\\bm x_n$ are defined as .\nThe detailed data generation processes are shown in the supplementary materials (\\cref{apnd:sec:numerical-experiments}).\n\nIn this experiment, we estimated the B\\'ezier simplex with degree $D = 2$ and 3, and compared the following three fitting methods:\n\\begin{description}\n    \\item[all-at-once] the all-at-once fitting (\\cref{sec:all-at-once-fitting});\n    \\item[inductive skeleton (non-optimal)] the inductive skeleton fitting (\\cref{sec:inductive-skeleton-fitting}) with $N^{(0)} = \\dots = N^{(M - 1)} = N / M$, which does not provide the optimal value of the risk \\cref{tab:risk-inductive};\n    \\item[inductive skeleton (optimal)] the inductive skeleton fitting (\\cref{sec:inductive-skeleton-fitting}) where $N^{(0)}, \\dots, N^{(M - 1)}$ are determined by minimizing the risk \\cref{tab:risk-inductive} under the constraints $\\sum_{m = 0}^{M-1} N^{(m)} = N$ and $N^{(m)}\\geq 0~(m = 0, \\dots, M-1)$. The actual sample size $N^{(m)}$ for each $(D, M)$ are shown in \\cref{apnd:sec:numerical-experiments} (\\cref{apnd:tab:optimal-subsample-ratio}).\n\\end{description}\nWhen we calculated an approximation of the expected risk for each method, we randomly chose other 10000 parameters $\\set{\\bm{\\hat t}_n}_{n = 1}^{10000}$ from $U(\\Delta^{M - 1})$ as a test set and measured the mean squared error, $\\mathrm{MSE} := \\frac{1}{10000} \\sum_{n = 1}^{10000} \\norm{\\bm b(\\bm{\\hat{t}}_n) - \\bm{\\hat{b}}(\\bm{\\hat{t}}_n)}^2$, where $\\bm{\\hat{b}}$ is the estimated B\\'ezier simplex.\nWe ran 20 trials and measured MSEs for each $(L, M, N)$ with $D \\in \\set{2, 3}$.\n\nOwing to space limitations, we only present typical results here. The remaining results are provided in the supplementary materials (\\cref{apnd:sec:numerical-experiments}).\n\\Cref{fig:MSE-vs-N} shows box plots of MSEs over 20 trials and our theoretical risks \\cref{eqn:risk} and \\cref{tab:risk-inductive} for each $N \\in \\set{250, 500, 1000, 2000}$ with $(L, M) = (100, 8)$ and $D \\in \\set{2, 3}$.\nWe observe that these figures empirically show that our theoretical risks are correct for both $D = 2$ and 3, and the gap between the actual MSEs and the risks are sufficiently small at $N = 1000$. \nFor both $D = 2$ and 3, the inductive skeleton (optimal) always achieved lower MSEs than that of the inductive skeleton (non-optimal). \nThis result suggests the efficiency of minimizing the risk (\\cref{tab:risk-comparison}) with respect to the sample size of each dimension. \nIn addition, the inductive skeleton fitting (optimal) also outperformed the all-at-once fitting in the case of $D = 2$. \nThis result also supports the discussion described in \\cref{sec:all-vs-inductive}. \n\\begin{figure}[h]\n \\begin{minipage}{0.49\\hsize}\n        \\centering\n    \\includegraphics[width=1\\textwidth]{neurips2019/fig/D=2_M=8_L=100.pdf}\n    \\subcaption{D=2}\n    \\label{fig:MSE-vs-N-D=2}\n \\end{minipage}\n \\begin{minipage}{0.49\\hsize}\n        \\centering\n    \\includegraphics[width=1\\textwidth]{neurips2019/fig/D=3_M=8_L=100.pdf}\n    \\subcaption{D=3}\n    \\label{fig:MSE-vs-N-D=3}\n \\end{minipage}\n \\caption{Sample size $N$ vs. MSE with $(L, M) = (100, 8)$ (boxplots over 20 trials and theoretical risks).}\n \\label{fig:MSE-vs-N}\n\\end{figure}\n\n\\subsection{Multi-objective optimization instances}\\label{sec:MOP-instances}\nTo investigate our results practically, we provide two complementary multi-objective optimization problem instances: a generalized location problem called \\texttt{MED} \\cite{Harada2006,Hamada2010} and a multi-objective hyper-parameter tuning of the group lasso \\cite{Yuan2006} on the \\texttt{Birthwt} dataset \\cite{Hosmer1989,Venables2002}.\nBoth of them are strongly convex three-objective optimization problems and we consider fitting their two-dimensional (that is $M = L = 3$) Pareto fronts by a B\\'ezier simplex with degree $D = 2$ and 3. % and evaluated the performances.\nFor the location problem, its Pareto front can be represented by a B\\'ezier simplex with degree $D = 2$.\nFor the group lasso, on the other hand, the Pareto front cannot be represented with degree $D = 2$ but $D = 3$ (see \\cref{apnd:sec:Pareto-fronts}).\nThe detailed description of each problem is shown in \\cref{apnd:sec:numerical-experiments}.\n\nAs we conducted in the previous experiments, we generated a training set and a test set on a Pareto front randomly then fitted a B\\'ezier simplex to the training set and evaluated the MSE between the estimated B\\'ezier simplex and the test set. \nWe chose the number of training points to $N = 50$ and 100.\nWith regard to the test set, the number of sample points is 10000 and 1000 for the location problem and the group lasso respectively. \nWe repeated experiments 20 times for each $(D, N)$.\n\nFor each problem instance and method, the average and the standard deviation of the MSE are shown in \\cref{tab:MSE-MOP-instances}. \nIn \\cref{tab:MSE-MOP-instances}, we highlighted the best score of MSE out of all-at-once fitting and inductive skeleton fitting (optimal) and added the results of one-sided Student's t-test with significance level 0.05.\n\n\\begin{table}[h]\n\\caption{MSE (avg.\\ $\\pm$ s.d.\\ over 20 trials) for the location problem and the group lasso. The winners with significance level $p < 0.05$ are shown in bold.}\n\\label{tab:MSE-MOP-instances}\n\\begin{minipage}[t]{.5\\textwidth}\n    \\centering\n    \\subcaption{Location problem}\n    \\scriptsize\n    {\\tabcolsep = 1.5mm\n    \\begin{tabular}{ccll}\n    \\toprule\n$D$&$N$ & \\multicolumn{1}{c}{All-at-once} & \\multicolumn{1}{c}{Inductive-skeleton (optimal)}\\\\ \\midrule\n%2&25\t&3.582e-04 $\\pm$\t6.703e-05\t&\\textbf{3.126e-04 $\\pm$\t4.375e-05}$^{**}$\\\\\n2&50\t&2.855e-04 $\\pm$\t2.114e-05\t&\\textbf{2.691e-04 $\\pm$\t8.541e-06}\\\\\n&100 &2.660e-04 $\\pm$\t1.227e-05\t&\\textbf{2.608e-04 $\\pm$\t5.946e-06}\\\\ \\midrule\n%3&25\t&7.502e-04 $\\pm$\t5.352e-04\t&\\textbf{4.626e-04 $\\pm$\t1.786e-04}$^{**}$\\\\\n3&50\t&3.596e-04 $\\pm$\t7.935e-05\t&3.269e-04 $\\pm$\t3.969e-05\\\\ \n&100\t&2.810e-04 $\\pm$\t1.569e-05\t&2.796e-04 $\\pm$\t1.478e-05\\\\\n\\bottomrule\n    \\end{tabular}\n    }\n    \\label{tab:location-problem}\n\\end{minipage}\n\\begin{minipage}[t]{.5\\textwidth}\n    \\centering\n    \\subcaption{Group lasso}\n    \\scriptsize\n    {\\tabcolsep = 1.5mm\n    \\begin{tabular}{ccll}\n    \\toprule\n$D$&$N$ & \\multicolumn{1}{c}{All-at-once} & \\multicolumn{1}{c}{Inductive-skeleton (optimal)}\\\\ \\midrule\n%2&25\t&\\textbf{1.256e-04 $\\pm$\t 4.023e-05}$^{**}$\t&5.123e-04 $\\pm$\t3.546e-05\\\\\n2&50\t&\\textbf{1.041e-04 $\\pm$\t 1.614e-05}\t&4.966e-04 $\\pm$\t1.848e-05\\\\\n& 100 &\\textbf{8.949e-05 $\\pm$\t6.083e-06}\t&5.020e-04 $\\pm$\t1.276e-05\\\\ \\midrule\n%3&25\t&\\textbf{1.066e-04 $\\pm$\t1.182e-04}\t&1.813e-04 $\\pm$ \t2.132e-04\\\\\n3&50\t&\\textbf{4.354e-05 $\\pm$\t 1.526e-05}\t&1.206e-04 $\\pm$ \t9.440e-06\\\\\n& 100 &\\textbf{3.231e-05 $\\pm$\t8.058e-06}\t&1.141e-04 $\\pm$\t8.200e-06\\\\\n \\bottomrule\n    \\end{tabular}\n    }\n    \\label{tab:group-lasso}\n\\end{minipage}\n\\end{table}\n\nSince the Pareto front of the location problem can be represented by a B\\'ezier simplex of $D = 2$ and 3, we expected that the experimental results agree with our analysis discussed in \\cref{sec:all-vs-inductive}.\nIn fact, \\cref{tab:location-problem} shows that the inductive skeleton (optimal) outperformed for $D = 2$, which is consistent with our analysis.\nFor $D = 3$, the difference of MSEs is not significant.\n\\Cref{tab:risk-comparison} suggests that the difference of the risks between the two methods is very small for $(D, M) = (3, 3)$, and thus we did not observe significant differences of MSEs for $N = 50$ and 100.\n\n%In case of MED, the inductive skeleton (optimal) always achieved better MSEs than that of the all-at-once and the difference between the two methods is significant for $D=2$.\n%For $D=3$ however, there is no significant difference.\n\nIn case of the group lasso, on the other hand, \\cref{tab:group-lasso} shows that the all-at-once was better for both $D = 2$ and 3, and the differences are all significant.\nWhile our analysis assumes that the target hypersurface to be fitted can be represented by a B\\'ezier simplex, the Pareto front of the group lasso cannot for $D = 2$ but for $D = 3$.\nTherefore, the results for $D = 2$ does not contradict to our analysis.\nMoreover, the results for $D = 3$ that the all-at-once achieved better MSEs accords with our analysis.\n\n%The reason why the inductive skeleton (optimal) did not outperform for $D=2$ is that the Pareto front of Birthwt originally cannot be represented by a B\\'ezier simplex of degree two.\n\nFrom the above results, the validity of the analytic results is confirmed in practical situations.\n\n\\section{Conclusion}\\label{sec:conclusion}\nIn this paper, we have shown that the asymptotic $\\ell_2$-risk of the two B\\'ezier simplex fitting methods developed previously: the all-at-once fitting and the inductive skeleton fitting.\nFrom our risk analysis, the optimal ratio of subsamples for the inductive skeleton fitting has been derived, which is useful for design of experiments to maximize the goodness of fit.\nWe have discussed that superiority between the two fitting methods depends on the degree of a B\\'ezier simplex to be fit: the inductive skeleton fitting with optimally-decoupled subsamples outperforms for degree two whereas the all-at-once fitting becomes the better for degree three, independent of the dimensionality of the B\\'ezier simplex and its ambient space.\nThe above theoretical results have been confirmed via numerical experiments under small to moderate sample sizes.\nWe have demonstrated two applications of the analytic results in multi-objective optimization: a generalized location problem and a hyper-parameter tuning of the group lasso.\n\nAs a remark for future work, we point out two important cases which the current theory does not cover.\nThe first one is the case discussed in \\cref{sec:MOP-instances} that the true surface is not representable by a model.\nThe second one is presented in the literature \\cite{Kobayashi2019}.\nWhen the parameters of a B\\'ezier simplex are not given in a sample and to be estimated as well as the control points, the inductive skeleton fitting outperforms the all-at-once fitting even if the B\\'ezier simplex is of degree \\emph{three}.\nWe believe that those cases would offer insightful examples to extend the scope of the theory.\n\n\\bibliographystyle{plain}\n\\bibliography{reference}\n\\end{document}\n", "meta": {"hexsha": "96c8ae9b513f88ba0a67405ec981f97bbc972343", "size": 38932, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "neurips2019/main.tex", "max_stars_repo_name": "rafcc/neurips-19.6340", "max_stars_repo_head_hexsha": "746c84a727f45e0f082c8bed19359f803f3eba09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "neurips2019/main.tex", "max_issues_repo_name": "rafcc/neurips-19.6340", "max_issues_repo_head_hexsha": "746c84a727f45e0f082c8bed19359f803f3eba09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "neurips2019/main.tex", "max_forks_repo_name": "rafcc/neurips-19.6340", "max_forks_repo_head_hexsha": "746c84a727f45e0f082c8bed19359f803f3eba09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 54.603085554, "max_line_length": 451, "alphanum_fraction": 0.6772064112, "num_tokens": 13271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.3394379592786947}}
{"text": "\\chapter{Seiyuu Social Network}\nSocial networks consist of a finite set of actors and the relations between them. Usually represented as a graph; with actors or organizations as set of nodes and a defined relation between them as set of edges. This structures are useful to analyze complex social interactions and communities.\n\n\\section{Node and edge definitions}\nThis social network is of a particular kind called \\textit{two-mode networks} which consists of a set of actors (seiyuu) and events (anime). So there exists two ways of viewing it, one will be from seiyuu perspective, using anime in common for edges; the other being from anime perspective, using seiyuu in common for edges. We chose the former since we found more interesting they being actual people and using other information about them such as debut and gender.\n\nSo our social network consists of voice actors as nodes and co-workership between them as edges. It's important to notice that this social network is time dependant since each seiyuu has a debut year and each anime has an aired time; giving us freedom to choose different time frames to observe.\n\nAside from being time dependant there exists different possible definitions of relationship or co-workership between seiyuu. One could say two actors know each other if they have worked in at least one job together, or maybe it requires more than one. There's also a time frame to define, relationship could take into account all works of both of them or only from certain years.\\\\\n\n\\section{Construction}\nAs a first approach Gephi was used to build the network. Since the graph was big enough to bring performance problems and we needed to build the edges dynamically (which couldn't be done in Gephi) NetworkX was used instead.\n\nNetworkX was chosen because it's an easy yet powerful Python library, it doesn't get along with massive graphs but ours was not big enough to present a problem. \n\nOne can export the graph and open it on Gephi, for a more visual analysis.\n\nAnd also we needed to build the edges dynamically because according to our definition they depend on the time frame we are looking at. For example, for at least 10 works in common, if two actors worked together in 9 jobs between 1960 and 1970 we shouldn't see an edge between them; but if they worked together again in 1971 then looking at 1960-1971 they should be connected.\n\n\\section{Analysis}\nIn this section we are going to compare and analyze two definitions of relationship for our social network in order to understand more about it structure and decide on a definition:\n\\begin{itemize}\n\\item at least 1 work in common\n\\item at least 10 works in common\n\\end{itemize}\nBoth of them during the time frame between the first debut registered (1960) and the year of observation.\n\nIs easy to tell at first glance that this social network is really interconnected. With merely 2956 nodes it has 395887 edges when only one work in common is required and 13629 edges when asking for 10 or more. It shows a thightly interconnected cluster surrounded by poorly or not connected nodes. This cluster represents 99\\% of the nodes of one work in common graph and 23\\% of 10 works in common. In terms of modularity we can see at least four clear communities in each graph, Fig~\\ref{fig:graph1CommunityColoured} and Fig~\\ref{fig:graph10CommunityColoured}.\n\n\\begin{figure}[!hbt]\n\t\\begin{center}\n\t\\includegraphics[width=\\columnwidth]{graphics/atLeast1WorkCommunity.png}\n\t\\caption{At least one work in common graph coloured by community.}\n\t\\label{fig:graph1CommunityColoured}\n\t\\end{center}\n\\end{figure}\n\n\\begin{figure}[!hbt]\n\t\\begin{center}\n\t\\includegraphics[width=\\columnwidth]{graphics/atLeast10WorksCommunity.png}\n\t\\caption{At least ten works in common graph coloured by community. Big cluster at the center, surrounded by loosely connected nodes.}\n\t\\label{fig:graph10CommunityColoured}\n\t\\end{center}\n\\end{figure}\n\nTable~\\ref{tab:graphComparision} shows metrics about each graph. Requiring more works in common decreases average degree circumstantially but doesn't change much modularity or network diameter.\n\n\\begin{table}[!hbt]\n\t\\begin{center}\n\t\\caption{Graph analysis}\n\t\\label{tab:graphComparision}\n\t\\begin{tabular}{|l|c|c|c|}\n\t\t\\hline\n\t\tGraph & Avg Degree & Graph Density & Modularity \\\\\n\t\t\\hline\n\t\tOne work in common & 267 & 0.09 & 0.2 \\\\\n\t\t\\hline\n\t\tTen works in common & 9 & 0.003 & 0.29 \\\\\n\t\t\\hline\n\t\\end{tabular}\\\\\n\t\\smallskip\n\t\\begin{tabular}{|l|c|c|}\n\t\t\\hline\n\t\tGraph & Network Diameter & Connected Components \\\\\n\t\t\\hline\n\t\tOne work in common & 6 & 18 \\\\\n\t\t\\hline\n\t\tTen works in common & 7 & 2261 \\\\\n\t\t\\hline\n\t\\end{tabular}\n\t\\end{center}\n\\end{table}\n\n\\begin{figure}\n\t\\centering\n\t\\begin{subfigure}{.5\\columnwidth}\n\t\t\\centering\n\t\t\\includegraphics[scale=0.39]{graphics/accumulationEdges_1_1960-2018.png}\n\t\t\\caption{At least one work in common}\n\t\t\\label{fig:edgesOneWorkInCommon}\n\t\\end{subfigure}%\n\t\\begin{subfigure}{.5\\columnwidth}\n\t\t\\centering\n\t\t\\includegraphics[scale=0.39]{graphics/accumulationEdges_10_1960-2018.png}\n\t\t\\caption{At least ten works in common}\n\t\t\\label{fig:edgesTenWorskInCommon}\n\t\\end{subfigure}\n\t\\caption{Grouwth of edges over time. For 1 and 10 works in common graphs}\n\t\\label{fig:grouwthOfEdges}\n\\end{figure}\n\nAs proven by Fig.~\\ref{fig:grouwthOfEdges} grouwth of edges by year follows a similar distribution regardless of how many works in common are used to build the social network.\n\n\\begin{figure}[!hbt]\n\t\\begin{center}\n\t\\includegraphics[width=\\columnwidth]{graphics/nodesAccumulation.png}\n\t\\caption{Grouwth of nodes over time.}\n\t\\label{fig:grouwthOfNodes}\n\t\\end{center}\n\\end{figure}\n \nFig.~\\ref{fig:grouwthOfNodes} shows that more than half of the nodes are from last 18 years (2000 to 2018), giving us an idea of how much seiyuu industry is growing.\n\n\\FloatBarrier\nTable~\\ref{tab:top10atLeast1Work} shows top 10 nodes, for degree and betweenness centrality for \"at least 1 work in common\" definition. And Table~\\ref{tab:top10atLeast10Works} does the same for \"at least 10 works in common\".\n\n\\begin{table}[!htb]\n    \\begin{minipage}{.5\\textwidth}\n        \\centering\n            \\begin{tabular}{|l|c|}\n\t\t\t\t\\hline\n\t\t\t\tName & Degree \\\\ \n\t\t\t\t\\hline\n\t\t\t\tTakehito Koyasu & 1545 \\\\ \n\t\t\t\t\\hline\n\t\t\t\tAkira Ishida & 1488 \\\\ \n\t\t\t\t\\hline\n\t\t\t\tMamiko Noto & 1422 \\\\ \n\t\t\t\t\\hline\n\t\t\t\tNobuo Tobita & 1417 \\\\ \n\t\t\t\t\\hline\n\t\t\t\tDaisuke Namikawa & 1390 \\\\ \n\t\t\t\t\\hline\n\t\t\t\tNobuyuki Hiyama & 1358 \\\\ \n\t\t\t\t\\hline\n\t\t\t\tRikiya Koyama & 1331 \\\\ \n\t\t\t\t\\hline\n\t\t\t\tJūrōta Kosugi & 1322 \\\\ \n\t\t\t\t\\hline\n\t\t\t\tKeiji Fujiwara & 1312 \\\\ \n\t\t\t\t\\hline\n\t\t\t\tKazuhiko Inoue & 1309 \\\\ \n\t\t\t\t\\hline\n\t\t\t\\end{tabular}\n            \\caption{Top 10 degree}\n    \\end{minipage}%\n    \\begin{minipage}{.6\\textwidth}\n        \\centering\n        \\begin{tabular}{|l|c|}\n\t\t\t\t\\hline\n\t\t\t\tName & Betweenness Centrality \\\\\n\t\t\t\t\\hline\n\t\t\t\tTakehito Koyasu & 49982.52 \\\\\n\t\t\t\t\\hline\n\t\t\t\tAkira Ishida & 40221.50 \\\\\n\t\t\t\t\\hline\n\t\t\t\tDaisuke Namikawa & 30448.43 \\\\\n\t\t\t\t\\hline\n\t\t\t\tNobuo Tobita & 29363.25 \\\\\n\t\t\t\t\\hline\n\t\t\t\tMamiko Noto & 29168.18 \\\\\n\t\t\t\t\\hline\n\t\t\t\tRie Kugimiya & 29122.31 \\\\\n\t\t\t\t\\hline\n\t\t\t\tMiyuki Sawashiro & 28997.40 \\\\\n\t\t\t\t\\hline\n\t\t\t\tKazuhiko Inoue & 27693.88 \\\\\n\t\t\t\t\\hline\n\t\t\t\tDaisuke Ono & 27034.592 \\\\\n\t\t\t\t\\hline\n\t\t\t\tKeiji Fujiwara & 26802.69 \\\\\n\t\t\t\t\\hline\n\t\t\\end{tabular}\n        \\caption{Top 10 Betweenness centrality }\n    \\end{minipage}\n    \\caption{At least one work in common}\n    \\label{tab:top10atLeast1Work}\n\\end{table}\n\n\\begin{table}[!htb]\n    \\begin{minipage}{.5\\textwidth}\n        \\centering\n            \\begin{tabular}{|l|c|}\n\t\t\t\t\\hline\n\t\t\t\tName & Degree \\\\\n\t\t\t\t\\hline\n\t\t\t\tTakehito Koyasu & 311 \\\\\n\t\t\t\t\\hline\n\t\t\t\tAkira Ishida & 273 \\\\\n\t\t\t\t\\hline\n\t\t\t\tMamiko Noto & 258 \\\\\n\t\t\t\t\\hline\n\t\t\t\tDaisuke Namikawa & 232 \\\\\n\t\t\t\t\\hline\n\t\t\t\tKatsuyuki Konishi & 229 \\\\\n\t\t\t\t\\hline\n\t\t\t\tKeiji Fujiwara & 220 \\\\\n\t\t\t\t\\hline\n\t\t\t\tJunichi Suwabe & 216 \\\\\n\t\t\t\t\\hline\n\t\t\t\tToshiyuki Morikawa & 215 \\\\\n\t\t\t\t\\hline\n\t\t\t\tRie Kugimiya & 213 \\\\\n\t\t\t\t\\hline\n\t\t\t\tNobuyuki Hiyama & 201 \\\\\n\t\t\t\t\\hline\n\t\t\t\\end{tabular}\n            \\caption{Top 10 degree}\n    \\end{minipage}%\n    \\begin{minipage}{.6\\textwidth}\n        \\centering\n        \\begin{tabular}{|l|c|}\n\t\t\t\t\\hline\n\t\t\t\tName & Betweenness Centrality \\\\\n\t\t\t\t\\hline\n\t\t\t\tTakehito Koyasu & 18489.44 \\\\\n\t\t\t\t\\hline\n\t\t\t\tMamiko Noto & 10988.96 \\\\\n\t\t\t\t\\hline\n\t\t\t\tDaisuke Namikawa & 9570.48 \\\\\n\t\t\t\t\\hline\n\t\t\t\tAkira Ishida & 8299.19 \\\\\n\t\t\t\t\\hline\n\t\t\t\tRie Kugimiya & 7560.16 \\\\\n\t\t\t\t\\hline\n\t\t\t\tKatsuyuki Konishi & 7413.72 \\\\\n\t\t\t\t\\hline\n\t\t\t\tKenichi Ogata & 7160.54 \\\\\n\t\t\t\t\\hline\n\t\t\t\tHarumi Sakurai & 6775.76 \\\\\n\t\t\t\t\\hline\n\t\t\t\tKeiji Fujiwara & 5980.58 \\\\\n\t\t\t\t\\hline\n\t\t\t\tYoshimasa Hosoya & 5607.95 \\\\\n\t\t\t\t\\hline\n\t\t\\end{tabular}\n        \\caption{Top 10 Betweenness centrality }\n    \\end{minipage}\n    \\caption{At least ten works in common}\n    \\label{tab:top10atLeast10Works}\n\\end{table}\n\n\\section{Summarization}\nBoth networks have fairly similar top 10s so it points to them having similar structure and connections amoung their nodes, aside from actual values.\\\\\n\nFrom now on our definition for edges will be: \\textit{at least 10 works in common, during the time frame between the first debut registered (1960) and the year of observation}. Because requiring more jobs in common means less amount of edges, this leaves a more understandable graph and we verified it does without changing its structure so much.\\\\\n\nThere's also other interesting definitions of relationship, for example we can use only common works from the last x years or from all time. This options weren't explored; having into account our limited time.\\\\\n\nTable~\\ref{tab:moreInfoSeiyuu} shows a little more information about seiyuu that appear on top 10s.\n\\begin{table}[!hbt]\n\t\\begin{center}\n\t\\caption{More information about seiyuu appearing in top 10 lists}\n\t\\label{tab:moreInfoSeiyuu}\n\t\\begin{tabular}{|l|c|c|c|c|}\n\t\t\\hline\n\t\tName & Popularity & Debut & Gender & Birthyear \\\\\n\t\t\\hline\n\t\tTakehito Koyasu & 7235 & 1988 & Male & 1967 \\\\\n\t\t\\hline\n\t\tAkira Ishida & 7612 & 1989 & Male & 1967 \\\\\n\t\t\\hline\n\t\tMamiko Noto & 7544 & 1988 & Female & 1980 \\\\\n\t\t\\hline\n\t\tDaisuke Namikawa & 8304 & 1988 & Male & 1976 \\\\\n\t\t\\hline\n\t\tKatsuyuki Konishi & 3702 & 1996 & Male & 1973 \\\\\n\t\t\\hline\n\t\tKeiji Fujiwara & 2778 & 1986 & Male & 1964 \\\\\n\t\t\\hline\n\t\tJunichi Suwabe & 10838 & 1996 & Male & 1972 \\\\\n\t\t\\hline\n\t\tToshiyuki Morikawa & 2455 & 1981 & Male & 1967 \\\\\n\t\t\\hline\n\t\tRie Kugimiya & 31668 & 1996 & Female & 1979 \\\\\n\t\t\\hline\n\t\tJun Fukuyama & 26811 & 1981 & Male & 1978 \\\\\n\t\t\\hline\n\t\tKenichi Ogata & 52 & 1974 & Male & 1942 \\\\\n\t\t\\hline\n\t\tHarumi Sakurai & 341 & 2005 & Female & 1982 \\\\\n\t\t\\hline\n\t\tYoshimasa Hosoya & 4852 & 2006 & Male & 1982 \\\\\n\t\t\\hline\n\t\tNobuo Tobita & 139 & 1981 & Male & 1959 \\\\\n\t\t\\hline\n\t\tNobuyuki Hiyama & 1723 & 1988 & Male & 1967 \\\\\n\t\t\\hline\n\t\tRikiya Koyama & 2919 & 1996 & Male & 1963 \\\\\n\t\t\\hline\n\t\tJūrōta Kosugi & 114 & 1985 & Male & 1957 \\\\\n\t\t\\hline\n\t\tMiyuki Sawashiro & 26501 & 1988 & Female & 1985 \\\\\n\t\t\\hline\n\t\tKazuhiko Inoue & 2445 & 1974 & Male & 1954 \\\\\n\t\t\\hline\n\t\tDaisuke Ono & 24080 & 1996 & Male & 1978 \\\\\n\t\t\\hline\n\t\\end{tabular}\n\t\\end{center}\n\\end{table}\n\n\\section{Afterwork}\nBy the end of the research we were able to grab new information about seiyuu roles; we now know if it was a main role (mostly main character or villian) or not.\n\nGiving this new information we built another social network using the following definition of relationship:\\\\\n\n\\textit{At least one work in common, during the time frame between the first debut registered (1960) and the year of observation, \\textbf{using information from  main roles only}.}\\\\\n\nWe'll now present some characteristics of this network.\n\n\\begin{figure}[!hbt]\n\t\\begin{center}\n\t\\includegraphics[width=\\columnwidth]{graphics/atLeast1WorksOnlyMainRoleCommunity.png}\n\t\\caption{At least one \"main role\" work in common graph coloured by community. It also has a big cluster at the center.}\n\t\\label{fig:graph1MWCommunityColoured}\n\t\\end{center}\n\\end{figure}\n\nAs Fig.~\\ref{fig:graph1MWCommunityColoured} shows this graph's structure is also a strongly connected cluster surrounded by loosely or not connected nodes. Then Table~\\ref{tab:newGraphAnalysis} has some features of this network.\n\n\\begin{table}[!hbt]\n\t\\begin{center}\n\t\\caption{Graph analysis}\n\t\\label{tab:newGraphAnalysis}\n\t\\begin{tabular}{|l|c|c|c|}\n\t\t\\hline\n\t\tGraph & Avg Degree & Graph Density & Modularity \\\\\n\t\t\\hline\n\t\tOnly main works & 14 & 0.005 & 0.355 \\\\\n\t\t\\hline\n\t\\end{tabular}\\\\\n\t\\smallskip\n\t\\begin{tabular}{|l|c|c|}\n\t\t\\hline\n\t\tGraph & Network Diameter & Connected Components \\\\\n\t\t\\hline\n\t\tOnly main works & 8 & 1349 \\\\\n\t\t\\hline\n\t\\end{tabular}\n\t\\end{center}\n\\end{table}\n\n", "meta": {"hexsha": "b6bd0984b7c62aa5289b86e928a39390fabd0569", "size": 12553, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/SeiyuuSocialNetwork.tex", "max_stars_repo_name": "fzanollo/nii-internship", "max_stars_repo_head_hexsha": "8b622081122f90506dbb86815197a5ece3cce743", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "report/SeiyuuSocialNetwork.tex", "max_issues_repo_name": "fzanollo/nii-internship", "max_issues_repo_head_hexsha": "8b622081122f90506dbb86815197a5ece3cce743", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/SeiyuuSocialNetwork.tex", "max_forks_repo_name": "fzanollo/nii-internship", "max_forks_repo_head_hexsha": "8b622081122f90506dbb86815197a5ece3cce743", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5838323353, "max_line_length": 563, "alphanum_fraction": 0.7111447463, "num_tokens": 4020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.3394379536965816}}
{"text": "\\documentclass[]{article}\n\\usepackage{proceed2e}\n\\usepackage{amssymb,amsmath,amsthm}\n\\usepackage{graphicx}\n\\usepackage{preamble}\n\\usepackage{natbib}\n\\usepackage{hyperref}\n\\usepackage{color}\n\\definecolor{mydarkblue}{rgb}{0,0.08,0.45}\n\\hypersetup{ %\n    pdftitle={},\n    pdfauthor={},\n    pdfsubject={},\n    pdfkeywords={},\n    pdfborder=0 0 0,\n    pdfpagemode=UseNone,\n    colorlinks=true,\n    linkcolor=mydarkblue,\n    citecolor=mydarkblue,\n    filecolor=mydarkblue,\n    urlcolor=mydarkblue,\n    pdfview=FitH}\n\n\n\\title{Optimally-Weighted Herding is Bayesian Quadrature}\n\n%\\author{}\n\n\\author{\n {\\bf Ferenc Husz\\'{a}r} \\\\\nDepartment of Engineering\\\\\nCambridge University\\\\ \n\\texttt{fh277@cam.ac.uk}\n\\And \n{\\bf David Duvenaud } \\\\ %\\thanks{Both authors contributed qually.} \\\\ \nDepartment of Engineering\\\\ \nCambridge University \\\\\n\\texttt{dkd23@cam.ac.uk}\n} \n\n\n\\begin{document} \n \n\\maketitle \n \n\\begin{abstract} \nHerding and kernel herding are deterministic methods of choosing samples which summarise a probability distribution.  A related task is choosing samples for estimating integrals using Bayesian quadrature.  We show that the criterion minimised when selecting samples in kernel herding is equivalent to the posterior variance in Bayesian quadrature.  We then show that sequential Bayesian quadrature can be viewed as a weighted version of kernel herding which achieves performance superior to any other weighted herding method. We demonstrate empirically a rate of convergence faster than $\\mathcal{O}(1/N)$.  Our results also imply an upper bound on the empirical error of the Bayesian quadrature estimate.\n\\end{abstract} \n\n\\begin{figure}[h]\n\\centering\n\\includegraphics[width=\\columnwidth]{figures/fig1_v2}\n\\caption{The first 8 samples from sequential Bayesian quadrature, versus the first 20 samples from herding.  Only 8 weighted \\sbq{} samples are needed to give an estimator with the same maximum mean discrepancy as using 20 herding samples with uniform weights.  Relative sizes of samples indicate their relative weights.}\n\\label{fig:fig1}\n\\end{figure} \n\n\n\n \n\\section{INTRODUCTION}\n\\paragraph{The problem: Integrals} A common problem in statistical machine learning is to compute expectations of functions over probability distributions of the form:\n\\begin{equation}\n\tZ_{f,p} = \\int f(x) p(x) dx \\label{eqn:integral}\n\\end{equation}\nExamples include computing marginal distributions, making predictions marginalizing over parameters, or computing the Bayes risk in a decision problem. In this paper we assume that the distribution $p(x)$ is known in analytic form, and $f(x)$ can be evaluated at arbitrary locations.\n\nMonte Carlo methods produce random samples from the distribution $p$ and then approximate the integral by taking the empirical mean $\\hat{Z} = \\frac{1}{N}\\sum_{n=1}^{N}f_{x_n}$ of the function evaluated at those points. This non-deterministic estimate converges at a rate $\\mathcal{O}(\\frac{1}{\\sqrt{N}})$. When exact sampling from $p$ is impossible or impractical, Markov chain Monte Carlo (MCMC) methods are often used. MCMC methods can be applied to almost any problem but convergence of the estimate depends on several factors and is hard to estimate \\citep{CowlesCarlin96}. The focus of this paper is on quasi-Monte Carlo methods that -- instead of sampling randomly -- produce a set of pseudo-samples in a deterministic fashion. These methods operate by directly minimising some sort of discrepancy between the empirical distribution of pseudo-samples and the target distribution. Whenever these methods are applicable, they achieve convergence rates superior to the $\\mathcal{O}(\\frac{1}{\\sqrt{N}})$ rate typical of random sampling.\n\nIn this paper we highlight and explore the connections between two deterministic sampling and integration methods: Bayesian quadrature (\\bq{}) \\citep{BZHermiteQuadrature,BZMonteCarlo} (also known as Bayesian Monte Carlo) and kernel herding \\citep{chen2010super}. Bayesian quadrature estimates integral \\eqref{eqn:integral} by inferring a posterior distribution over $f$ conditioned on the observed evaluations $f_{x_n}$, and then computing the posterior expectation of $Z_{f,p}$. The points where the function should be evaluated can be found via Bayesian experimental design, providing a deterministic procedure for selecting sample locations.\n\nHerding, proposed recently by \\cite{chen2010super}, produces pseudosamples by minimising the discrepancy of moments between the sample set and the target distribution. Similarly to traditional Monte Carlo, an estimate is formed by taking the empirical mean over samples $\\hat{Z} = \\frac{1}{N}\\sum_{n=1}^{N}f_{x_n}$. Under certain assumptions, herding has provably fast, $\\mathcal{O}(\\frac{1}{N})$ convergence rates in the parametric case, and has demonstrated strong empirical performance in a variety of tasks.\n\n\\paragraph{Summary of contributions} In this paper, we make two main contributions.  First, we show that the Maximum Mean Discrepancy (MMD) criterion used to choose samples in kernel herding is identical to the expected error in the estimate of the integral $Z_{f,p}$ under a Gaussian process prior for $f$.  This expected error is the criterion being minimized when choosing samples for Bayesian quadrature.  Because Bayesian quadrature assigns different weights to each of the observed function values $f(\\vx)$, we can view Bayesian quadrature as a weighted version of kernel herding.  We show that these weights are optimal in a minimax sense over all functions in the Hilbert space defined by our kernel.  This implies that Bayesian quadrature dominates uniformly-weighted kernel herding and other non-optimally weighted herding in rate of convergence.\n\nSecond, we show that minimising the MMD, when using \\bq{} weights is closely related to the sparse dictionary selection problem studied in \\citep{KrauseCevher10}, and therefore is approximately submodular with respect to the samples chosen. This allows us to reason about the performance of greedy forward selection algorithms for Bayesian Quadrature. We call this greedy method Sequential Bayesian Quadrature (\\sbq{}).\n\nWe then demonstrate empirically the relative performance of herding, i.i.d random sampling, and \\sbq{}, and demonstrate that \\sbq{} attains a rate of convergence faster than $\\mathcal{O}(1/N)$.\n\n\n\n\\section{HERDING} \n\nHerding was introduced by \\cite{welling2009herding} as a method for generating pseudo-samples from a distribution in such a way that certain nonlinear moments of the sample set closely match those of the target distribution.  The empirical mean $\\frac{1}{N}\\sum_{n=1}^{N}f_{x_n}$ over these pseudosamples is then used to estimate integral \\eqref{eqn:integral}.\n\n\\subsection{Maximum Mean Discrepancy}\n\nFor selecting pseudosamples, herding relies on an objective based on the maximum mean discrepancy \\citep[MMD;\\ ][]{Sriperumbudur2010}. MMD measures the divergence between two distributions, $p$ and $q$ with respect to a class of integrand functions $\\mathcal{F}$ as follows:\n%\n\\begin{align}\n\t\\mmd_{\\mathcal{F}}\\left(p,q\\right) = \\sup_{f\\in\\mathcal{F}}\\left\\vert\\int f_x p(x) dx - \\int f_x q(x) dx \\right\\vert\n\\end{align}\n\nIntuitively, if two distributions are close in the MMD sense, then no matter which function $f$ we choose from $\\mathcal{F}$, the difference in its integral over $p$ or $q$ should be small. A particularly interesting case is when the function class $\\mathcal{F}$ is functions of unit norm from a reproducing kernel Hilbert space (RKHS) $\\He$. In this case, the MMD between two distributions can be conveniently expressed using expectations of the associated kernel $k(x, x')$ only \\citep{Sriperumbudur2010}:\n%\n\\begin{align}\nMMD^2_{\\He}(p,q) =& \\sup_{\\substack{f\\in\\He\\\\\\Hnorm{f}=1}}\\left\\vert\\int f_x p(x) dx - \\int f_x q(x) dx\\right\\vert^2\\label{eqn:rkhs-mmd}\\\\\n\t=& \\Hnorm{\\mu_{p} - \\mu_{q}}^2\\\\\n\\nonumber\t=&\\iint k(x,y) p(x) p(y) dx dy\\\\\n\\nonumber\t-2 &\\iint k(x,y) p(x) q(y) dx dy\\\\\n\t+ &\\iint k(x,y) q(x) q(y) dx dy,\n\\end{align}\n%\nwhere in the above formula $\\mu_{p}=\\int \\phi(\\vx)p(\\vx)d\\vx\\in\\He$ denotes the \\emph{mean element} associated with the distribution $p$. For characteristic kernels, such as the Gaussian kernel, the mapping between a distribution and its mean element is bijective. As a consequence $\\mmd_{\\He}(p,q)=0$ if and only if $p=q$, making it a powerful measure of divergence.\n\nHerding uses maximum mean discrepancy to evaluate of how well the sample set $\\{\\vx_1,\\ldots,\\vx_{N}\\}$ represents the target distribution $p$:\n\n\\begin{align}\n\t\\epsilon^2_{herding}&\\left(\\{\\vx_1,\\ldots,\\vx_{N}\\}\\right) = \\mmd^2_{\\He}\\left(p,\\frac{1}{N}\\sum_{n=1}^{N}\\delta_{x_n}\\right)\\\\\n\\nonumber\t=&\\iint k(x,y) p(x) p(y) dx dy\\\\\n\t\t- &\\frac{1}{N}\\sum_{n=1}^{N}\\int k(x,x_n) p(x) dx\n\t\t+ \\frac{1}{N^2}\\sum_{n,m=1}^{N} k(x_n,x_m)\n\\label{eq:mmd_assumption}\n\\end{align}\n%\nThe herding procedure greedily minimizes its objective $\\epsilon_{herding}\\left(\\{\\vx_1,\\ldots,\\vx_{N}\\}\\right)$ , adding pseudosamples $\\vx_n$ one at a time. When selecting the $n+1$-st pseudosample:\n%\n\\begin{align}\n\\vx_{n+1} &\\leftarrow \\argmin_{\\vx \\in \\mathcal{X}} \\label{eqn:herding_criterion} \\epsilon_{herding}\\left(\\{\\vx_1,\\ldots,\\vx_{n},\\vx\\}\\right)\\\\\n\t&= \\argmax_{\\vx \\in \\mathcal{X}} 2 \\expectargs{\\vx' \\sim p}{k(\\vx, \\vx')} - \\frac{1}{n+1}\\sum_{m=1}^{n} k(\\vx,\\vx_m)\\mbox{,}\\notag\n\\end{align}\n%\nassuming $k(\\vx,\\vx) = \\mbox{const}$.\nThe formula \\eqref{eqn:herding_criterion} admits an intuitive interpretation: the first term encourages sampling in areas with high mass under the target distribution $p(\\vx)$.  The second term discourages sampling at points close to existing samples. \n\nEvaluating \\eqref{eqn:herding_criterion} requires us to compute $\\expectargs{\\vx' \\sim p}{k(\\vx, \\vx')} $, that is to integrate the kernel against the target distribution. Throughout the paper we will assume that these integrals can be computed in closed form. Whilst the integration can indeed be carried out analytically in several cases \\citep{Song2008,chen2010super}, this requirement is the most pertinent limitation on applications of kernel herding, Bayesian quadrature and related algorithms.\n\n\\subsection{Complexity and Convergence Rates}\n\nCriterion \\eqref{eqn:herding_criterion} can be evaluated in only $\\mathcal{O}(n)$ time. Adding these up for all subsequent samples, and assuming that optimisation in each step has $\\mathcal{O}(1)$ complexity, producing $N$ pseudosamples via kernel herding costs $\\mathcal{O}(N^2)$ operations in total.\n\nIn finite dimensional Hilbert spaces, the herding algorithm has been shown to reduce $\\mmd$ at a rate $\\mathcal{O}(\\frac{1}{N})$, which compares favourably with the $\\mathcal{O}(\\frac{1}{\\sqrt{N}})$ rate obtained by non-deterministic Monte Carlo samplers. However, as pointed out by \\cite{bach2012equivalence}, this fast convergence is not guaranteed in infinite dimensional Hilbert spaces, such as the RKHS corresponding to the Gaussian kernel.\n\n\n\n\n\\section{BAYESIAN QUADRATURE} \n\n\\begin{figure}\n\\centering\n\\includegraphics[width=\\columnwidth]{figures/bq_intro4}\n\\caption{An illustration of Bayesian Quadrature.  The function $f(x)$ is sampled at a set of input locations.  This induces a Gaussian process posterior distribution on $f$, which is integrated in closed form against the target density, $p(\\vx)$.  Since the amount of volume under $f$ is uncertain, this gives rise to a (Gaussian) posterior distribution over $Z_{f,p}$.}\n\\label{fig:bq_intro}\n\\end{figure}\n\nSo far, we have only considered integration methods in which the integral \\eqref{eqn:integral} is approximated by the empirical mean of the function evaluated at some set of samples, or pseudo-samples.  Equivalently, we can say that Monte Carlo and herding both assign an equal $\\frac{1}{N}$ weight to each of the samples.\n\nIn \\citep{BZMonteCarlo}, an alternate method is proposed: Bayesian Monte Carlo, or Bayesian quadrature (\\bq).  \\bq{} puts a prior distribution on $\\vf$, then estimates integral \\eqref{eqn:integral} by inferring a posterior distribution over the function $\\vf$, conditioned on the observations $\\vf(\\vx_n)$ at some query points $\\vx_n$.  The posterior distribution over $f$ then implies a distribution over $Z_{f,p}$.  This method allows us to choose sample locations $\\vx_n$ in any desired manner. See Figure \\ref{fig:bq_intro} for an illustration of Bayesian Quadrature.\n\n%In \\cite{BZMonteCarlo}, an alternate method was proposed: Bayesian Monte Carlo, or Bayesian quadrature (\\bq).  \\bq{} puts a prior distribution on $\\vf$, then conditions on the observations $\\vf(\\vx_n)$ to obtain a posterior distribution over the function $\\vf$.  The posterior over $\\vf$ then implies a Then estimates integral \\eqref{eqn:integral} by \n\n\n\\subsection{ BQ Estimator}\n\nHere we derive the \\bq{} estimate of \\eqref{eqn:integral}, after conditioning on function evaluations $\\vf(\\vx_1) \\dots \\vf(\\vx_N)$, denoted as $f(\\vX)$.  The Bayesian solution implies a distribution over $Z_{f,p}$.  The mean of this distribution, $\\expectargs{}{Z}$ is the optimal Bayesian estimator for a squared loss.\n\nFor simplicity, $\\vf$ is assigned a Gaussian process prior with kernel function $k$ and mean $0$.  This assumption is very similar to the one made by kernel herding in Eqn.\\ \\eqref{eq:mmd_assumption}.\n\nAfter conditioning on $\\vf_{\\vx}$, we obtain a closed-form posterior over $\\vf$:\n%\n\\begin{align}\np(\\vf(\\vx\\st)|\\vf(\\vX)) = \\N{\\vf_{\\vx\\st}}{\\mf(\\vx\\st)}{\\cov(\\vx\\st,\\vx\\st')}\n\\end{align} \nwhere\n\\begin{align}\n\\mf(\\vx\\st) = & k(\\vx\\st, \\vX) K^{-1} \\vf(\\vX) \\\\\n\\cov(\\vx\\st, \\vx\\st') = & k(\\vx\\st,\\vx'\\st) - k(\\vx\\st, \\vX) K^{-1} k(\\vX, \\vx'\\st)\n\\end{align} \n%\nand $K = k(\\vX, \\vX)$. \n%\nConveniently, the \\gp{} posterior allows us to compute the expectation of \\eqref{eqn:integral} in closed form: \n%\n%\\begin{align}\n%Z & = \\int f(\\vx)p(\\vx)d\\vx\n%\\end{align} \n%so we integrate over functions to get:\n\\begin{align}\n\\expectargs{\\gp}{Z} & = \\expectargs{\\gp}{\\int f(\\vx)p(\\vx)d\\vx}\\\\\n & = \\int\\!\\!\\! \\int\\!\\! f(\\vx) p(f(\\vx)|\\vf(\\vX)) p(\\vx) d\\vx df\\\\\n & = \\int\\!\\!\\! \\mf(\\vx) p(\\vx) d\\vx \\\\\n & = \\left[ \\int\\!\\! k(\\vx, \\vX) p(\\vx) d\\vx \\right] K^{-1} \\vf(\\vX) \\\\\n & = \\vz^T K^{-1} \\vf(\\vX)\n\\label{eq:marg_mean_symbolic}\n\\end{align} \nwhere\n\\begin{align}\nz_n & = \\int\\!\\! k(\\vx, \\vx_n) p(\\vx) d\\vx = \\expectargs{\\vx' \\sim p}{k(\\vx_n, \\vx')}.\n\\end{align}\n%\nConveniently, as in kernel herding, the desired expectation of $Z_{f,p}$ is simply a linear combination of observed function values $\\vf(\\vx)$:\n%\n\\begin{align}\n\\expectargs{\\gp}{Z} & = \\vz^T K^{-1} \\vf(\\vX) \\\\\n    & = \\sum_n w_{\\bq}^{(n)} \\vf(\\vx_n)\n\\end{align}  \nwhere\n\\begin{align}  \nw_{\\bq}^{(n)} & = \\sum_m \\vz_m^T K^{-1}_{mn}\n\\label{eq:bq_weights}\n\\end{align}\n%\nThus, we can view the BQ estimate as a weighted version of the herding estimate.  Interestingly, the weights $\\vw_{\\bq}$ do not need to sum to 1, and are not even necessarily positive.\n\n\\subsubsection{Non-normalized and Negative Weights}\n\n\\begin{figure}\n\\centering\n\\includegraphics[width=\\columnwidth]{figures/weights_v1_n100}\n\\caption{A set of optimal weights given by \\bq{}, after 100 \\sbq{} samples were selected on the distribution shown in Figure \\ref{fig:fig1}.  Note that the optimal weights are spread away from the uniform weight ($\\frac{1}{N}$), and that some weights are even negative.  The sum of these weights is 0.93.}\n\\label{fig:weights100}\n\\end{figure}\n\nWhen weighting samples, it is often assumed, or enforced \\citep[as in][]{bach2012equivalence,Song2008}, that the weights $\\vw$ form a probability distribution.  However, there is no technical reason for this requirement, and in fact, the optimal weights do not have this property.  Figure \\ref{fig:weights100} shows a representative set of 100 \\bq{} weights chosen on samples representing the distribution in figure \\ref{fig:fig1}.  There are several negative weights, and the sum of all weights is 0.93.\n\nFigure \\ref{fig:weights_shrinkage} demonstrates that, in general, the sum of the Bayesian weights exhibits shrinkage when the number of samples is small.\n\n\\begin{figure}\n\\centering\n\\includegraphics[width=\\columnwidth]{figures/weights_shrinkage}\n\\caption{An example of Bayesian shrinkage in the sample weights.  In this example, the kernel width is approximately $\\nicefrac{1}{20}$ the width of the distribution being considered.  Because the prior over functions is zero mean, in the small sample case the weights are shrunk towards zero.  The weights given by simple Monte Carlo and herding do not exhibit shrinkage. }\n\\label{fig:weights_shrinkage}\n\\end{figure}\n\n%For a fixed kernel, the variance of the BQ estimate does not depend on the function values.\n\n%A natural criterion for selecting sample locations would be to choose locations which most reduce the variance of $Z_{f,p}$.\n\n\\subsection{Optimal sampling for BQ}\n\nBayesian quadrature provides not only a mean estimate of $Z_{f,p}$, but a full Gaussian posterior distribution. The variance of this distribution $\\varianceargs{}{Z_{f,p}|f_{x_1}, \\dots, f_{x_N}}$ quantifies our uncertainty in the estimate. When selecting locations to evaluate the function $f$, minimising the posterior variance is a sensible strategy. Below, we give a closed form formula for the posterior variance of $Z_{f,p}$, conditioned on the observations $f_{x_1} \\dots f_{x_N}$, which we will denote by $\\epsilon^2_{\\bq{}}$.  For a longer derivation, see \\cite{BZMonteCarlo}.\n\\begin{align}\n\\epsilon^{2}_{\\bq{}}(\\vx_1,\\ldots,\\vx_N) & = \n\\varianceargs{}{Z_{f,p}|f_{x_1}, \\dots, f_{x_N}} \\\\\n% \\nonumber & = \\expectargs{f \\sim \\gp, p\\sim p(x)}{ \\left( f(\\vx) - \\mf(\\vx) \\right)\\left( f(\\vx') - \\mf(\\vx') \\right)} \\\\ \n%\\nonumber & = \\int \\Bigg( \\!\\! \\left( \\int f(\\vx) p(\\vx) d\\vx - \\int \\mf(\\vx') p(\\vx') d\\vx' \\right) \\\\ \n%\\nonumber & \\quad \\times \\left( \\int f(\\vx) p(\\vx) d\\vx - \\int \\mf(\\vx') p(\\vx') d\\vx' \\right) \\!\\! \\Bigg) p(f) df \\\\ \n%\\nonumber & = \\int\\!\\!\\! \\int\\!\\! \\int\\!\\! \\left[ f(\\vx) - \\mf(\\vx) \\right] \\left[ f((\\vx') - \\mf(\\vx') \\right] p(f) df \\\\\n%\\nonumber & \\qquad \\times   p(\\vx) p(\\vx') d\\vx d\\vx' \\\\\n%\\nonumber & = \\int\\!\\! \\!\\int\\!\\! \\Cov \\left[ f((\\vx), f((\\vx') \\right] p(\\vx) p(\\vx') d\\vx d\\vx' \\\\\n%\\nonumber & = \\int\\!\\!\\! \\int\\!\\! \\left[ k(\\vx, \\vx') - k(\\vx, \\vX) K^{-1} k(\\vX, \\vx') \\right] \\\\\n%\\nonumber          & \\qquad \\times p(\\vx) p(\\vx') d\\vx d\\vx' \\\\ \n%\\nonumber & = \\int\\!\\!\\! \\int\\!\\! k(\\vx, \\vx') p(\\vx) p(\\vx') d\\vx d\\vx' \\\\\n%\\nonumber & \\quad - \\left[ \\int\\!\\! k(\\vx, \\vX) p(\\vx) d\\vx \\right] K^{-1} \\left[ \\int\\!\\! k(\\vX, \\vx') p(\\vx') d\\vx' \\right] \\\\\n& = \\expectargs{\\vx, \\vx' \\sim p}{k(\\vx, \\vx')} - \\vz^T K^{-1} \\vz\\mbox{,}\n\\label{eq:marg_var_symbolic}\n\\end{align}\nwhere $\\vz_n = \\expectargs{\\vx' \\sim p}{k(\\vx_n, \\vx')}$ as before. Perhaps surprisingly, the posterior variance of $Z_{f,p}$ does not depend on the observed function values, only on the location $x_n$ of samples. A similar independence is observed in other optimal experimental design problems involving Gaussian processes \\citep{guestrin1}. This allows the optimal samples to be computed ahead of time, before observing any values of $f$ at all \\citep{minka2000dqr}.\n%\\begin{align}\n%\\epsilon^{2}_{\\bq{}}(\\vx_1,\\ldots,\\vx_N) = \\expectargs{\\vx, \\vx' \\sim p}{k(\\vx, \\vx')} - \\vz^T K^{-1} \\vz\n%\\end{align}\n\nWe can contrast the \\bq{} objective $\\epsilon^{2}_{\\bq{}}$ in \\eqref{eq:marg_var_symbolic} to the objective being minimized in herding, $\\epsilon^{2}_{herding}$ of equation \\eqref{eq:mmd_assumption}. Just like $\\epsilon^{2}_{herding}$, $\\epsilon^{2}_{\\bq{}}$ expresses a trade-off between accuracy and diversity of samples. On the one hand, as samples get close to high density regions under $p$, the values in $\\vz$ increase, which results in decreasing variance. On the other hand, as samples get closer to each other, eigenvalues of $K$ increase, resulting in an increase in variance. \n\nIn a similar fashion to herding, we may use a greedy method to minimise $\\epsilon^{2}_{\\bq{}}$, adding one sample at a time. We will call this algorithm \\emph{Sequential Bayesian Quadrature} (\\sbq{}):\n\\begin{align}\n\\vx_{n+1} &\\leftarrow \\argmin_{\\vx \\in \\mathcal{X}} \\epsilon_{\\bq{}}\\left(\\{\\vx_1,\\ldots,\\vx_{n},\\vx\\}\\right)\n\\end{align}\nUsing incremental updates to the Cholesky factor, the criterion can be evaluated in $\\mathcal{O}(n^2)$ time. Iteratively selecting $N$ samples thus takes $\\mathcal{O}(N^3)$ time, assuming optimisation can be done on $\\mathcal{O}(1)$ time.\n\n\\section{RELATING $\\varianceargs{}{Z_{f,p}}$ TO $\\mmd$}\n\nThe similarity in the behaviour of $\\epsilon^{2}_{herding}$ and $\\epsilon^{2}_{\\bq{}}$ is not a coincidence, the two quantities are closely related to each other, and to \\mmd.\n\t\n\\begin{prop} The expected variance in the Bayesian quadrature $\\epsilon^{2}_{\\bq{}}$  is the maximum mean discrepancy between the target distribution $p$ and $q_{\\bq{}}(x) = \\sum_{n=1}^{N}w^{(n)}_{\\bq{}}\\delta_{x_n}(x)$\n\\end{prop}\n%\n\\begin{proof}\nThe proof involves invoking the representer theorem, using bilinearity of scalar products and the fact that if $f$ is a standard Gaussian process then $\\forall g\\in\\He: \\left\\langle f,g\\right\\rangle \\sim \\mathcal{N}(0,\\Hnorm{g}^2)$:\n\\begin{align}\n&\\varianceargs{}{Z_{f,p}\\vert f_{x_1}, \\dots, f_{x_N}}=\\\\\n\t&= \\mathbb{E}_{f\\sim GP} \\left( \\int f(x) p(x) dx - \\sum_{n=1}^{N}w^{(n)}_{\\bq{}} f(x_n)\\right)^2\\\\\n\t&= \\mathbb{E}_{f\\sim GP} \\left( \\int \\left\\langle f, \\phi (x)\\right\\rangle p(x) dx - \\sum_{n=1}^{N}w^{(n)}_{\\bq{}} \\left\\langle f, \\phi (x_n)\\right\\rangle\\right)^2\\\\\n\t&= \\mathbb{E}_{f\\sim GP} \\left\\langle f ,  \\int\\phi(x) p(x) dx - \\sum_{n=1}^{N}w^{(n)}_{\\bq{}}\\phi(x_n)\\right\\rangle^2\\\\\n\t&= \\Hnorm{\\mu_p - \\mu_{q_{\\bq{}}}}^2\\\\\n\t&= \\mmd^2(p,q_{\\bq{}})\n\\end{align}\n\\end{proof}\n\nWe know that the the posterior mean $\\expectargs{\\gp}{Z_{f,p}\\vert f_1,\\ldots,f_N}$ is a Bayes estimator and has therefore the minimal expected squared error amongst all estimators. This allows us to further rewrite $\\epsilon^{2}_{\\bq{}}$ into the following minimax forms:\n%\n\\begin{align}\n\\epsilon^{2}_{\\bq{}} &= \\sup_{\\substack{f\\in\\He\\\\\\Hnorm{f}=1}} \\left| \\int f_x p(x) dx - \\sum_{n=1}^{N}w^{(n)}_{\\bq{}} f_{x_n}\\right|^2\\\\\n\t&= \\inf_{\\hat{Z}:\\mathcal{X}^N\\mapsto\\mathbb{R}} \\sup_{\\substack{f\\in\\He\\\\\\Hnorm{f}=1}} \\left| Z - \\hat{Z}\\left(f_{x_1},\\ldots,f_{x_N}\\right)\\right|^2\\\\\n\t&= \\inf_{\\bm{w}\\in\\mathbb{R}^N} \\sup_{\\substack{f\\in\\He\\\\\\Hnorm{f}=1}} \\left| \\int f_x p(x) dx - \\sum_{n=1}^{N}w_n \tf_{x_n}\\right|^2\n\\end{align}\n%\nLooking at $\\epsilon^{2}_{\\bq{}}$  this way, we may discover the deep similarity to the criterion $\\epsilon^2_{herding}$ that kernel herding minimises. Optimal sampling for Bayesian quadrature minimises the same objective as kernel herding, but with the uniform $\\frac{1}{N}$ weights replaced by the optimal weights. As a corollary\n%\n\\begin{align}\n\\epsilon^{2}_{\\bq{}}(x_1,\\ldots,x_N)  \\leq \\epsilon^{2}_{KH} (x_1,\\ldots,x_N)\n\\end{align}\n\nIt is interesting that $\\epsilon^{2}_{\\bq{}}$ has both a Bayesian interpretation as posterior variance under a Gaussian process prior, and a frequentist interpretation as a minimax bound on estimation error with respect to an RKHS.\n\n\\section{SUBMODULARITY}\n\n\\label{sec:submodularity}\n\nIn this section, we use the concept of approximate submodularity \\citep{KrauseCevher10}, in order to study convergence properties of \\sbq{}.\n\nA set function $s:2^\\mathcal{X} \\mapsto \\mathbb{R}$ is \\textit{submodular} if, for all $A\\subseteq B\\subseteq \\mathcal{X}$ and $\\forall x \\in \\mathcal{X}$\n%\n\\begin{align}\ns(A\\cup\\{x\\})-s(A)\\geq s(B\\cup\\{x\\})-s(B)\n\\end{align}\n%\nIntuitively, submodularity is a diminishing returns property: adding an element to a smaller set has larger relative effect than adding it to a larger set. A key result \\cite[see e.\\,g.\\ ][and references therein]{KrauseCevher10} is that greedily maximising a submodular function is guaranteed not to differ from the optimal strategy by more than a constant factor of $(1-\\frac{1}{e})$.\n\nHerding and \\sbq{} are examples of greedy algorithms optimising set functions: they add each pseudosamples in such a way as to minimize the instantaneous reduction in $\\mmd$. So it is intuitive to check whether the objective functions these methods minimise are submodular. Unfortunately, neither $\\epsilon_{herding}$, nor $\\epsilon_{\\bq{}}$ satisfies all conditions necessary for submodularity. However, noting that \\sbq{} is identical to the sparse dictionary selection problem studied in detail by \\citet{KrauseCevher10}, we can conclude that \\sbq{} satisfies a weaker condition called \\emph{approximate submodularity}. \n\nA set function $s:2^\\mathcal{X} \\mapsto \\mathbb{R}$ is \\textit{approximately submodular} with constant $\\epsilon>0$, if for all $A\\subseteq B\\subseteq \\mathcal{X}$ and $\\forall x \\in \\mathcal{X}$\n%\n\\begin{align}\ns(A\\cup\\{x\\})-s(A)\\geq s(B\\cup\\{x\\})-s(B) - \\epsilon\n\\end{align}\n\n\\begin{prop}\\label{prop:submodularity_SBQ}\n$\\epsilon^{2}_{\\bq{}}(\\emptyset)-\\epsilon^{2}_{\\bq{}}(\\cdot)$ is a weakly submodular set function with constant $\\epsilon<4r$, where $r$ is the incoherency\n\\begin{equation}\n\tr = \\max_{x,x'\\in\\mathcal{P}\\subseteq\\mathcal{X}} \\frac{k(x,x')}{\\sqrt{k(x,x)k(x',x')}}\n\\end{equation}\n\\end{prop}\n\\begin{proof} By the definition of $\\mmd$ we can see that\n$-\\epsilon^{2}_{\\bq{}} = -\\inf_{w\\in\\mathbb{R}^N}\\Hnorm{\\mu_p - \\sum_{n=1}^N w^{(n)}_{\\bq{}}k(\\cdot,\\vx_n)}^2$ is the negative squared distance between the mean element $\\mu_p$ and its projection onto the subspace spanned by the elements $k(\\cdot,\\vx_n)$. Substituting $k=1$ into Theorem 1 of \\citet{KrauseCevher10} concludes the proof.\n\\end{proof}\n\nUnfortunately, weak submodularity does not provide the strong near-optimality guarantees as submodularity does . If $s:2^\\mathcal{X} \\mapsto \\mathbb{R}$ is a weakly submodular function with constant $\\epsilon$, and $\\vert\\mathcal{A}_n\\vert=n$ is the result of greedy optimisation of $s$, then\n\\begin{equation}\n\ts(\\mathcal{A}_n) \\geq \\left(1-\\frac{1}{e}\\right)\\max_{\\vert\\mathcal{A}\\vert\\leq n}s(\\mathcal{A}) - n\\epsilon\n\\end{equation}\n\nAs pointed out by \\citet{KrauseCevher10}, this guarantee is very weak, as in our case the objective function $\\epsilon^{2}_{\\bq{}}(\\emptyset)-\\epsilon^{2}_{\\bq{}}(\\cdot)$ is upper bounded by a constant. However, establishing a connection between \\sbq{} and sparse dictionary selection problem opens up interesting directions for future research, and it may be possible to apply algorithms and theory developed for sparse dictionary selection to kernel-based quasi-Monte Carlo methods.\n\n\\section{EXPERIMENTS}\n\\label{sec:experiments}\n\nIn this section, we examine empirically the rates of convergence of sequential Bayesian quadrature and herding.  We examine both the expected error rates, and the empirical error rates.\n\nIn all experiments, the target distribution $p$ is chosen a 2D mixture of 20 Gaussians, whose equiprobability contours are shown in Figure \\ref{fig:fig1}. To ensure a comparison fair to herding, the target distribution, and the kernel used by both methods, correspond exactly to the one used in \\citep[Fig. 1]{chen2010super}. %Herding and \\sbq{} used identical kernels for all experiments.\n%\nFor experimental simplicity, each of the sequential sampling algorithms minimizes the next sample location from a pool of 10000 locations randomly drawn from the base distribution. In practice, one would run a local optimizer from each of these candidate locations, however in our experiments we found that this did not make a significant difference in the sample locations chosen. \n\n\\subsection{Matching a distribution}\n\nWe first extend an experiment from \\citep{chen2010super} designed to illustrate the mode-seeking behavior of herding in comparison to random samples. In that experiment, %e first experiment of \\cite{chen2010super}, \nit is shown that a small number of i.\\,i.\\,d.\\ samples drawn from a multimodal distribution will tend to, by chance, assign too many samples to some modes, and too few to some other modes. In contrast, herding places `super-samples' in such a way as to avoid regions already well-represented, and seeks modes that are under-represented.\n\nWe demonstrate that although herding improves upon i.\\,i.\\,d.\\ sampling, the uniform weighting of super-samples leads to sub-optimal performance.  Figure \\ref{fig:fig1} shows the first 20 samples chosen by kernel herding, in comparison with the first 8 samples chosen by \\sbq{}.  By weighting the 8 \\sbq{} samples by the quadrature weights in \\eqref{eq:bq_weights}, we can obtain the same expected loss as by using the 20 uniformly-weighted herding samples.  \n%\n\\begin{figure}\n\\includegraphics[width=\\columnwidth]{figures/expected_variance_v7_400}\n\\caption{The maximum mean discrepancy, or expected error of several different quadrature methods.  Herding appears to approach a rate close to $\\mathcal{O}(1/N)$.  \\sbq{} appears to attain a faster, but unknown rate.}\n\\label{fig:mmd_curve}\n\\end{figure}\n%\nFigure \\ref{fig:mmd_curve} shows MMD versus the number of samples added, on the distribution shown in Figure \\ref{fig:fig1}.  We can see that in all cases, \\sbq{} dominates herding.  It appears that \\sbq{} converges at a faster rate than $\\mathcal{O}(1/N)$, although the form of this rate is unknown.\n\nThere are two differences between herding and \\sbq{}:  \\sbq{} chooses samples according to a different criterion, and also weights those samples differently.  We may ask whether the sample locations or the weights are contributing more to the faster convergence of \\sbq{}. Indeed, in Figure \\ref{fig:fig1} we observe that the samples selected by \\sbq{} are quite similar to the samples selected by kernel herding. To answer this question, we also plot in Figure \\ref{fig:mmd_curve} the performance of a fourth method, which selects samples using herding, but later re-weights the herding samples with \\bq{} weights.  Initially, this method attains similar performance to \\sbq{}, but as the number of samples increases, \\sbq{} attains a better rate of convergence.  This result indicates that the different sample locations chosen by \\sbq{}, and not only the optimal weights, are responsible for the increased convergence rate of \\sbq{}.\n\n\\subsection{Estimating Integrals}\n\n%\\subsubsection{Functions in the RKHS}\n\nWe then examined the empirical performance of the different estimators at estimating integrals of real functions.  To begin with, we looked at performance on 100 randomly drawn functions, of the form:\n%\n\\begin{align}\nf(\\vx) & = \\sum_{i=1}^{10} \\alpha_i k(\\vx, \\vc_i)\n\\end{align}\n%\nwhere\n\\begin{align}\n\\Hnorm{f}^2 = \\sum_{i=1}^{10} \\sum_{j=1}^{10} \\alpha_i \\alpha_j k(\\vc_i, \\vc_j) = 1\n\\end{align}\n%\nThat is, these functions belonged exactly to the unit ball of the RKHS defined by the kernel $k(\\vx, \\vx')$ used to model them.\n%\n\\begin{figure}\n\\includegraphics[width=\\columnwidth]{figures/error_curve_rkhs_400_v4}\n\\caption{Within-model error: The empirical error rate in estimating $Z_{f,p}$, for several different sampling methods, averaged over 250 functions randomly drawn from the RKHS corresponding to the kernel used.}\n\\label{fig:error_curve}\n\\end{figure}\n%\nFigure \\ref{fig:error_curve} shows the empirical error versus the number of samples, on the distribution shown in Figure \\ref{fig:fig1}.  The empirical rates attained by the method appear to be similar to the MMD rates in Figure \\ref{fig:mmd_curve}.\n\nBy definition, MMD provides a upper bound on the estimation error in the integral of any function in the unit ball of the RKHS (Eqn.\\ \\eqref{eqn:rkhs-mmd}), including the Bayesian estimator, \\sbq{}. Figure \\ref{fig:bound_curve} demonstrates this quickly decreasing bound on the \\sbq{} empirical error.\n\n\\begin{figure}\n\\includegraphics[width=\\columnwidth]{figures/bound_curve_rkhs}\n\\caption{The empirical error rate in estimating $Z_{f,p}$,  for the \\sbq{} estimator, on 10 random functions drawn from the RKHS corresponding to the kernel used.  Also shown is the upper bound on the error rate implied by the $\\mmd$.}\n\\label{fig:bound_curve}\n\\end{figure}\n\n\\subsection{Out-of-model performance}\n\nA central assumption underlying \\sbq{} is that the integrand function belongs to the RKHS specified by the kernel.  To see how performance is effected if this assumption is violated, we performed empirical tests with functions chosen from outside the RKHS.  We drew 100 functions of the form:\n%\n\\begin{align}\nf(\\vx) & = \\sum_{i=1}^{10} \\alpha_i \\exp(-\\frac{1}{2} (\\vx -\\vc_i)^T \\Sigma_i^{-1} (\\vx -\\vc_i)\n\\end{align}\n%\nwhere each $\\alpha_i$ $\\vc_i$ $\\Sigma_i$ were drawn from broad distributions.  This ensured that the drawn functions had features such as narrow bumps and ridges which would not be well modelled by functions belonging to the isotropic kernel defined by $k$.\n%\n\\begin{figure}\n\\includegraphics[width=\\columnwidth]{figures/error_curve_outmodel_400_v3}\n\\caption{Out-of-model error: The empirical error rates in estimating $Z_{f,p}$, for several different sampling methods, averaged over 250 functions drawn from outside the RKHS corresponding to the kernels used.}\n\\label{fig:error_curve_outmodel}\n\\end{figure}\n%\nFigure \\ref{fig:error_curve_outmodel} shows that, on functions drawn from outside the assumed RKHS, relative performance of all methods remains similar.\n\nCode to reproduce all results is available at \\texttt{github.com/duvenaud/herding-paper}\n\n\\section{DISCUSSION}\n\n\\subsection{Choice of Kernel}\n\nUsing herding techniques, we are able to achieve fast convergence on a Hilbert space of \\emph{well-behaved} functions, but this fast convergence is at the expense of the estimate not necessarily converging for functions outside this space.\nIf we use a characteristic kernel \\citep{Sriperumbudur2010}, such as the exponentiated-quadratic or Laplacian kernels, then convergence in MMD implies weak convergence of $q_N$ to the target distribution. \n%$p$\\footnote{this statement is analogous to Levy's continuity theorem [cite], and we plan to include a more precise theorem and proof of this in the final version of the paper and supplementary material}. \nThis means that the estimate converges for any bounded measurable function $f$. The speed of convergence, however, may not be as fast.\n\nTherefore it is crucial that the kernel we choose is representative of the function or functions $f$ we will integrate.  For example, in our experiments, the convergence of herding was sensitive to the width of the Gaussian kernel.  One of the major weaknesses of kernel methods in general is the difficulty of setting kernel parameters.  A key benefit of the Bayesian interpretation of herding and MMD presented in this paper is that it provides a recipe for adapting the Hilbert space to the observations $f(x_n)$.  To be precise, we can fit the kernel parameters by maximizing the marginal likelihood of Gaussian process conditioned on the observations.  Details can be found in \\citep{rasmussen38gaussian}.\n\n\\subsection{Computational Complexity}\n\nWhile we have shown that Bayesian Quadrature provides the optimal re-weighting of samples, computing the optimal weights comes at an increased computational cost relative to herding. \n%\nThe computational complexity of computing Bayesian quadrature weights for $N$ samples is $\\mathcal{O}(N^3)$, due to the necessity of inverting the Gram matrix $K(\\vx, \\vx)$.  Using the Woodbury identity, the cost of adding a new sample to an existing set is $\\mathcal{O}(N^2)$.  For herding, the computational complexity of evaluating a new sample is only $\\mathcal{O}(N)$, making the cost of choosing $N$ herding samples $\\mathcal{O}(N^2)$.  For Monte Carlo sampling, the cost of adding an i.i.d. sample from the target distribution is only $\\mathcal{O}(1)$.\n\n%\n\\begin{table*}[t]\n\\begin{center}\n\\begin{tabular}{c|ccc}\n%\\hline\nmethod & complexity & rate & guarantee\\\\\n%\\hline\n\\midrule\nMCMC & $\\mathcal{O}(N)$ & variable & ergodic theorem\\\\\ni.i.d. MC & $\\mathcal{O}(N)$ & $\\frac{1}{\\sqrt{N}}$ & law of large numbers\\\\\nherding & $\\mathcal{O}(N^2)$ & $\\frac{1}{\\sqrt{N}} \\geq \\cdot \\geq \\frac{1}{N}$ & \\citep{chen2010super,bach2012equivalence} \\\\\nSBQ & $\\mathcal{O}(N^3)$ & unknown & approximate submodularity\\\\\n%\\hline\n\\end{tabular}\n\\end{center}\n\\caption{A comparison of the rates of convergence and computational complexity of several integration methods.}\n\\label{tbl:rates}\n\\end{table*}\n%\n\n\nThe relative computational cost of computing samples and weights using \\bq{}, herding, and sampling must be weighed against the cost of evaluating $f$ at the sample locations.  Depending on this trade-off, the three sampling methods form a Pareto frontier over computational speed and estimator accuracy.  When computing $f$ is cheap, we may wish to use Monte Carlo methods.  In cases where $f$ is computationally costly, we would expect to choose the \\sbq{} method.  When $f$ is relatively expensive, but a very large number of samples are required, we may choose to use kernel herding instead.  However, because the rate of convergence of \\sbq{} is faster, there may be situations in which the $\\mathcal{O}(N^3)$ cost is relatively inexpensive, due to the smaller $N$ required by \\sbq{} to achieve the same accuracy as compared to using other methods.  \n\nThere also exists the possibility to switch to a less costly sampling algorithm as the number of samples increases.\nTable \\ref{tbl:rates} summarizes the rates of convergence of all the methods considered here.\n\n\\section{CONCLUSIONS}\n\nIn this paper, we have shown three main results:  First, we proved that the loss minimized by kernel herding is closely related to the loss minimized by Bayesian quadrature, when selecting sample locations. This implies that sequential Bayesian quadrature can viewed as an optimally-weighted version of kernel herding.\n\nSecond, we showed that the loss minimized by the Bayesian method is approximately submodular with respect to the samples chosen, and established connections to the submodular dictionary selection problem studied in \\citep{KrauseCevher10}.\n\nFinally, we empirically demonstrated a superior rate of convergence of \\sbq{} over herding, and demonstrated a bound on the empirical error of the Bayesian quadrature estimate.\n\n\\subsection{Future Work}\n\nIn section \\ref{sec:submodularity}, we showed that \\sbq{} is approximately submodular, which provides only weak sub-optimality guarantees of its performance. It would be of interest to further explore the connection between Bayesian Quadrature and the dictionary selection problem to see if algorithms developed for dictionary selection can provide further practical or theoretical developments. The results in section \\ref{sec:experiments}, specifically Figure \\ref{fig:mmd_curve}, suggest that the convergence rate of \\sbq{} is faster than $\\mathcal{O}(1/N)$. However, we are not aware of any work showing what the theoretically optimal rate is. It would be of great interest to determine this optimal rate of convergence for particular classes of kernels.\n\n\\subsection*{Acknowledgements}\n\nThe authors would like to thank Carl Rasmussen and Francis Bach for helpful discussions, and Yutian Chen for his help in reproducing experiments.\nWe also thank Simon Lacoste-Julien for many helpful comments.\n\n%\\appendix\n%\\section{Lemma on submodularity\t}\n%\\label{app:submo}\n%\n%\\begin{lem}\\label{lemma:submodular}\n%Let $\\Pi_A$ be the operator that projects any vector to the subspace $S(A)$ spanned by a set of elements $A\\subseteq\\He$. For a fixed vector $p\\in\\He$, the following set-function $f_{p}(A):2^\\He\\mapsto\\mathcal{R^{-}}$ is non-decreasing and submodular:\n%\\begin{align}\n%f_{p}(A) = -\\Hnorm{p-\\Pi_{A}p}^2\n%\\end{align}\n%\\end{lem}\n%\\begin{proof}\n%Submodularity of $f_p$ means that $\\forall A\\subseteq B\\subseteq\\He$ and $x\\notin B$:\n%\\begin{align}\n%\tf_{p}(A\\cup\\{x\\}) - f_{p}(A) \\stackrel{?}{\\geq} f_{p}(B\\cup\\{x\\}) - f_{p}(B)\n%\\end{align}\n%Spelling out the two quantities we get\n%\\begin{align}\n%\t-\\Hnorm{p-\\Pi_{A\\cup\\{x\\}}p}^2 +\\Hnorm{p-\\Pi_{A}p}^2 \\stackrel{?}{\\geq}\\\\\n%\t -\\Hnorm{p-\\Pi_{B\\cup\\{x\\}}p}^2 +\\Hnorm{p-\\Pi_{B}p}^2\n%\\end{align}\n%Using the Pythagorean theorem on both sides we get\n%\\begin{align}\n%\t-\\Hnorm{\\Pi_{A\\cup\\{x\\}}p - \\Pi_{A}p}^2 \\stackrel{?}{\\geq} -\\Hnorm{\\Pi_{B\\cup\\{x\\}}p - \\Pi_{B}p}^2\n%\\end{align}\n%We can use the following Pythagorean identities\n%\\begin{align}\n%\t&\\Hnorm{\\Pi_{B\\cup\\{x\\}}p - \\Pi_{A}p}^2  =\\\\\n%\t \t&= \\Hnorm{\\Pi_{B\\cup\\{x\\}}p - \\Pi_{A\\cup\\{x\\}}p}^2  + \\Hnorm{\\Pi_{A\\cup\\{x\\}}p - \\Pi_{A}p}^2 \\\\\t\n%\t&\\Hnorm{\\Pi_{B\\cup\\{x\\}}p - \\Pi_{A}p}^2 = \\\\\n%\t&= \\Hnorm{\\Pi_{B\\cup\\{x\\}}p - \\Pi_{B}p}^2  + \\Hnorm{\\Pi_{B}p - \\Pi_{A}p}^2 \n%\\end{align}\n%Then our inequality becomes\n%\\begin{align}\n%\t\\Hnorm{\\Pi_{B\\cup\\{x\\}}p - \\Pi_{A\\cup\\{x\\}}p}^2 \\stackrel{?}{\\geq} \\Hnorm{\\Pi_{B}p - \\Pi_{A}p}^2\n%\\end{align}\n%W.\\,l.\\,o.\\,g.\\ we can assume that $x\\perp S(B)$, in which case using that\n%\\begin{align}\n%\\Pi_{B}\\Pi_{B\\cup\\{x\\}} &= \\Pi_{B}\\\\\n%\\Pi_{B}\\Pi_{A\\cup\\{x\\}} &= \\Pi_{A}\\mbox{,}\n%\\end{align}\n%we can write\n%\\begin{align}\n%\t\\Hnorm{\\Pi_{B\\cup\\{x\\}}p - \\Pi_{A\\cup\\{x\\}}p}^2 \\geq \\Hnorm{\\Pi_{B}\\left(\\Pi_{B\\cup\\{x\\}}p - \\Pi_{A\\cup\\{x\\}}\\right)}^2\n%\\end{align}\n%Which is always true, as a projection of vectors is never longer than the vector itself.\n%\\end{proof}\n%\n%\\pagebreak\n\\bibliographystyle{icml2012}\n\\bibliography{herding}\n\n\\end{document} \n", "meta": {"hexsha": "cfdf8870a3c2f7dfa69194165dd0c61e78d2a02d", "size": 41079, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/herding-bmc.tex", "max_stars_repo_name": "duvenaud/herding-paper", "max_stars_repo_head_hexsha": "cecf8f1af028efd95c6262fb257f4ed9978a57e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2015-04-16T14:19:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T22:45:05.000Z", "max_issues_repo_path": "paper/herding-bmc.tex", "max_issues_repo_name": "duvenaud/herding-paper", "max_issues_repo_head_hexsha": "cecf8f1af028efd95c6262fb257f4ed9978a57e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/herding-bmc.tex", "max_forks_repo_name": "duvenaud/herding-paper", "max_forks_repo_head_hexsha": "cecf8f1af028efd95c6262fb257f4ed9978a57e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-11-23T13:45:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-25T04:31:47.000Z", "avg_line_length": 78.2457142857, "max_line_length": 1039, "alphanum_fraction": 0.7377248716, "num_tokens": 11931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.33943794436925384}}
{"text": "\\subsection{Task 4: Radius of Every Node}\n\n\\subsubsection{Experiment on large datasets}\nIn this experiment, we run our radius algorithm in several large datasets. The statistics of these datasets are presented in Table \\ref{t4:table1}\n\n\\begin{table}[!htbf]\n\\caption{Datasets Statistics}\n\\begin{center}\n\\begin{tabular}{|c|c|c|c|}\n\\hline \\hline\ndataset & number of vertices & number of edges & diameter \\\\\n\\hline\nDBLP co-authorship network & 317080  & 1049866  & 21  \\\\\nEpinions social network & 131828  & 841372  & 14  \\\\\nAmazon product co-purchasing network & 334863 & 925872 & 44 \\\\\nEU email communication network & 265214 & 420045 & 14 \\\\\nGoogle web graph & 875713 & 5105039 & 21 \\\\\nYoutube social network & 1134890 & 2987624 & 20 \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\label{t4:table1}\n\\end{table}%\n\n\n\\begin{figure}[!htbf]\n\\begin{center}\n     \\includegraphics[width=0.8\\textwidth]{FIG/t4_email.png} \n\\caption{EU Email Communication }\n\\label{t4:1}\n\\end{center}\n\\end{figure}\n\n\\begin{figure}[!htbf]\n\\begin{center}\n\\begin{tabular}{cc}\n     \\includegraphics[width=0.8\\textwidth]{FIG/t4_epinions.png} \n\\end{tabular}\n\\caption{Epinions social network}\n\\label{t4:2}\n\\end{center}\n\\end{figure}\n\n\n\\begin{figure}[!htbf]\n\\begin{center}\n     \\includegraphics[width=0.8\\textwidth]{FIG/t4_dblp.png} \n\\caption{DBLP co-authorship network}\n\\label{t4:3}\n\\end{center}\n\\end{figure}\n\n\n\\begin{figure}[!htbf]\n\\begin{center}\n     \\includegraphics[width=0.8\\textwidth]{FIG/t4_google.png} \n\\caption{Google Web Graph}\n\\label{t4:4}\n\\end{center}\n\\end{figure}\n\n\n\\begin{figure}[!htbf]\n\\begin{center}\n     \\includegraphics[width=0.8\\textwidth]{FIG/t4_youtube.png} \n\\caption{Youtube Social Network}\n\\label{t4:5}\n\\end{center}\n\\end{figure}\n\n\\begin{figure}[!htbf]\n\\begin{center}\n     \\includegraphics[width=0.8\\textwidth]{FIG/t4_amazon.png} \n\\caption{Amazon product co-purchasing networkk}\n\\label{t4:6}\n\\end{center}\n\\end{figure}\n\n\n \n\\subsubsection{Observation}\n1. Radius Distribution: From the above plot, we find radius distribution of these graphs either tend to be single-modal, for example, EU Email Communication graph in figure \\ref{t4:1} and Epinions Social Network in figure \\ref {t4:2}, or bi-modal like DBLP co-authorship network in figure \\ref{t4:3} and Youtube Social Network in figure \\ref{t4:5}.\n\n2. Relationship to the connected component: So why radius tend to be distributed like this, we guess it's somehow related to the connectivity of the graph. Therefore we take a look back to the statistics we got from task3. We find that the graphs that has a single-modal shape radius distribution are fully or almost fully connected. The graphs that has bi-modal radius distribution are not that well connected, For most nodes that appear in the Giant Connected Component(GCC), they tend to have a higher radius value, specifically the smaller radius value it has, the more centric it is in the GCC. On the other hand, The first peak in the radius distribution represent those disconnected components.\n\n\\subsubsection{Proof of Correctness}\nSince the algorithm we use is an approximate algorithm, it's hard for us to verify the validity of our algorithm accurately. But we still try the algorithm on both small, large and synthetic datasets to demonstrate its validity.  \nFirst we test the algorithm on the synthetic tiny dataset consisting of only 10 nodes and 8 edges. It accurately compute the radius of every node.\n \nThen we test our algorithm on small datasets of several thousands of nodes, the experiment result are showed in Table \\ref{table:small}, we can see that our algorithm can get a closer estimate of diameter.\n\n\\begin{table}[!htbf]\n\\caption{Radius Experiment on Small Datasets}\n\\begin{center}\n\\begin{tabular}{|c|c|c|c|c|}\n\\hline \\hline\ndataset & nodes & edges & real diameter & estimated diameter \\\\\n\\hline\nEnron email network & 36692 & 183831 & 11 & 11 \\\\\nHigh Energy Physics & 12008 & 118521 & 13 & 12 \\\\\nAdvogato Trust Network & 6551 & 51332 & 9 & 9 \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\label{table:small}\n\\end{table}%\n\nFor large dataset we run in last section, the estimated diameter is still bounded by real diameter, but the estimation is no longer that close. This can be explained by the approximation nature of the algorithm we use. The Flajolet-Martin string we generate for every node is not unique, and as the number of nodes grows larger, the uniqueness of a node that a Flajolet-Martin string can represent is weakened. Therefore, for graph with larger size, the estimation might become less accurate.\n\n\n\n\n\n", "meta": {"hexsha": "43484574b4a300547094e7f8b2802c61b5280b92", "size": 4512, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/phase-3/doc/t4_exp.tex", "max_stars_repo_name": "spininertia/graph-mining-rdbms", "max_stars_repo_head_hexsha": "3b7652a99c1c0e3f4e680e04bfd08fac9708ea3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/phase-3/doc/t4_exp.tex", "max_issues_repo_name": "spininertia/graph-mining-rdbms", "max_issues_repo_head_hexsha": "3b7652a99c1c0e3f4e680e04bfd08fac9708ea3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/phase-3/doc/t4_exp.tex", "max_forks_repo_name": "spininertia/graph-mining-rdbms", "max_forks_repo_head_hexsha": "3b7652a99c1c0e3f4e680e04bfd08fac9708ea3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-16T18:23:24.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-16T18:23:24.000Z", "avg_line_length": 39.5789473684, "max_line_length": 701, "alphanum_fraction": 0.7566489362, "num_tokens": 1252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.339437942460938}}
{"text": "\\documentclass[aps,pra,12pt,amsmath,notitlepage,letterpaper]{revtex4-1}\n\\usepackage[english]{babel}\n\\usepackage{blindtext}\n\n\\begin{document}\n\\title{Example Homework Document}\n\\author{Sam Student}\n\\date{\\today}\n\n\\begin{abstract}\nHere we do the professional ($E = m c^2$) \\LaTeX~document thing.\n\\end{abstract}\n\n\\maketitle\n\n\\section{Introduction}\n\\Blindtext\n\n\\section{Example 1}\n\\blindmathtrue\n\\subsection{Premise}\n\\blindtext\n\n\\subsection{Results}\n\\begin{align}\n  f(x) &= \\int_{-\\infty}^\\infty \\!\\! \\mathrm{d}t\\, g(x - t)\\,F(t) \\\\\n       &= (g \\ast F)(x) \\nonumber\n\\end{align}\n\\Blindtext\n\n\\section{Conclusion}\n\\blindmathfalse\n\n\\blindtext\n\n\\end{document}\n", "meta": {"hexsha": "553b08c9e4c11fe41a42ccda47a870731167c55b", "size": 651, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Example_LaTeX/Example_LaTeX.tex", "max_stars_repo_name": "chapman-phys227-2016s/Information", "max_stars_repo_head_hexsha": "7ade65a64df2362972adced37d4bc9040ae46e32", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Example_LaTeX/Example_LaTeX.tex", "max_issues_repo_name": "chapman-phys227-2016s/Information", "max_issues_repo_head_hexsha": "7ade65a64df2362972adced37d4bc9040ae46e32", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Example_LaTeX/Example_LaTeX.tex", "max_forks_repo_name": "chapman-phys227-2016s/Information", "max_forks_repo_head_hexsha": "7ade65a64df2362972adced37d4bc9040ae46e32", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.5945945946, "max_line_length": 71, "alphanum_fraction": 0.7142857143, "num_tokens": 223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.33927475118110456}}
{"text": "\\documentclass[a4paper,10pt]{article}\n\\usepackage{graphicx}\n\\usepackage{amssymb}\n\\usepackage{booktabs}\n\\usepackage{subcaption}\n\\usepackage{alphalph}\n\\usepackage{longtable}\n\\renewcommand{\\thesubfigure}{\\alphalph{\\value{subfigure}}}\n\\title{Comparison of IFS Similarity Measures - Report}\n\\author{IFSSimReporter 1.0.6250.29793}\n \\begin{document}\n \\maketitle\n\\section{Experiment Settings}\n\\subsection{Similarity Measures}\nThe following similarity measures for intuitionistic fuzzy sets were used through the experiment: \nAoD (\\cite{Loor2017}), VB-0.5 (\\cite{Loor2013}), H3D (\\cite{Szmidt2000}), E-3D (\\cite{Szmidt2000}), GGeo-3D-2 (\\cite{Xu2007}), GGeo-3D-1 (\\cite{Xu2007}), GGeo-3D-4 (\\cite{Xu2007}), X17-2 (\\cite{Xu2007}), X17-0.5 (\\cite{Xu2007}), X19 (\\cite{Xu2007}), X21 (\\cite{Xu2007}), CC (\\cite{Chen2016}), Ch (\\cite{Chen1997}), HK (\\cite{Hong1999}), HY15 (\\cite{Hung2004}), HY16 (\\cite{Hung2004}), BA-1-2 (\\cite{Boran2014}), BA-2-4 (\\cite{Boran2014}), N26 (\\cite{Nguyen2016}), XY19 (\\cite{Xu2009}), COS (\\cite{Szmidt2013}), SK1-2D (\\cite{Szmidt2004}), SK2-2D (\\cite{Szmidt2004}), SK3-2D (\\cite{Szmidt2004}), SK4-2D (\\cite{Szmidt2004}), XVB-0-0.05 (\\cite{Loor2017}), XVB-0-0.1 (\\cite{Loor2017}), XVBr-1-10 (\\cite{Loor2017}), XVBr-0.5-10 (\\cite{Loor2017}), XVBr-0-10 (\\cite{Loor2017}), XVBr-1-5 (\\cite{Loor2017}), XVBr-0.5-5 (\\cite{Loor2017}), XVBr-0-5 (\\cite{Loor2017}), XVBr-1 (\\cite{Loor2017}), XVBr-0.5 (\\cite{Loor2017}), XVBr-0 (\\cite{Loor2017}).\n\\subsection{Testing Data}\nThe following categories from the RCV1 data set were used in the experiment: \nE11, ECAT, GJOB.\n\\pagebreak\n\\section{Results}\n\\input{allcat_mIndices.tex}\n\\pagebreak\n\\subsection{Charts}\n\\begin{figure}[ht]{\\centering\n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_AoD.pdf}\n\\caption{AoD}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_VB-0_5.pdf}\n\\caption{VB-0.5}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_H3D.pdf}\n\\caption{H3D}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_E-3D.pdf}\n\\caption{E-3D}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_GGeo-3D-2.pdf}\n\\caption{GGeo-3D-2}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_GGeo-3D-1.pdf}\n\\caption{GGeo-3D-1}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_GGeo-3D-4.pdf}\n\\caption{GGeo-3D-4}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_X17-2.pdf}\n\\caption{X17-2}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_X17-0_5.pdf}\n\\caption{X17-0.5}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_X19.pdf}\n\\caption{X19}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_X21.pdf}\n\\caption{X21}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_CC.pdf}\n\\caption{CC}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_Ch.pdf}\n\\caption{Ch}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_HK.pdf}\n\\caption{HK}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_HY15.pdf}\n\\caption{HY15}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_HY16.pdf}\n\\caption{HY16}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_BA-1-2.pdf}\n\\caption{BA-1-2}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_BA-2-4.pdf}\n\\caption{BA-2-4}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_N26.pdf}\n\\caption{N26}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_XY19.pdf}\n\\caption{XY19}\n\\end{subfigure} \n\\caption{Averages of the similarity levels per scenario versus the percentage of opposites included in each scenario (Part 1).}\n}\\end{figure}\n\\begin{figure}[ht]{\\ContinuedFloat\\centering\n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_COS.pdf}\n\\caption{COS}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_SK1-2D.pdf}\n\\caption{SK1-2D}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_SK2-2D.pdf}\n\\caption{SK2-2D}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_SK3-2D.pdf}\n\\caption{SK3-2D}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_SK4-2D.pdf}\n\\caption{SK4-2D}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_XVB-0-0_05.pdf}\n\\caption{XVB-0-0.05}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_XVB-0-0_1.pdf}\n\\caption{XVB-0-0.1}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_XVBr-1-10.pdf}\n\\caption{XVBr-1-10}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_XVBr-0_5-10.pdf}\n\\caption{XVBr-0.5-10}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_XVBr-0-10.pdf}\n\\caption{XVBr-0-10}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_XVBr-1-5.pdf}\n\\caption{XVBr-1-5}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_XVBr-0_5-5.pdf}\n\\caption{XVBr-0.5-5}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_XVBr-0-5.pdf}\n\\caption{XVBr-0-5}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_XVBr-1.pdf}\n\\caption{XVBr-1}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_XVBr-0_5.pdf}\n\\caption{XVBr-0.5}\n\\end{subfigure} \n\\begin{subfigure}[b]{2.5cm}\n\\centering\n\\includegraphics[height=2cm]{allcat_XVBr-0.pdf}\n\\caption{XVBr-0}\n\\end{subfigure} \n\\caption{Averages of the similarity levels per scenario versus the percentage of opposites included in each scenario (Part 2).}\n}\\end{figure}\n\\pagebreak\n\\subsection{Linear models}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_AoD_LM.pdf}\n\\caption{AoD - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_VB-0_5_LM.pdf}\n\\caption{VB-0.5 - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_H3D_LM.pdf}\n\\caption{H3D - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_E-3D_LM.pdf}\n\\caption{E-3D - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_GGeo-3D-2_LM.pdf}\n\\caption{GGeo-3D-2 - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_GGeo-3D-1_LM.pdf}\n\\caption{GGeo-3D-1 - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_GGeo-3D-4_LM.pdf}\n\\caption{GGeo-3D-4 - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_X17-2_LM.pdf}\n\\caption{X17-2 - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_X17-0_5_LM.pdf}\n\\caption{X17-0.5 - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_X19_LM.pdf}\n\\caption{X19 - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_X21_LM.pdf}\n\\caption{X21 - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_CC_LM.pdf}\n\\caption{CC - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_Ch_LM.pdf}\n\\caption{Ch - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_HK_LM.pdf}\n\\caption{HK - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_HY15_LM.pdf}\n\\caption{HY15 - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_HY16_LM.pdf}\n\\caption{HY16 - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_BA-1-2_LM.pdf}\n\\caption{BA-1-2 - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_BA-2-4_LM.pdf}\n\\caption{BA-2-4 - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_N26_LM.pdf}\n\\caption{N26 - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_XY19_LM.pdf}\n\\caption{XY19 - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_COS_LM.pdf}\n\\caption{COS - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_SK1-2D_LM.pdf}\n\\caption{SK1-2D - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_SK2-2D_LM.pdf}\n\\caption{SK2-2D - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_SK3-2D_LM.pdf}\n\\caption{SK3-2D - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_SK4-2D_LM.pdf}\n\\caption{SK4-2D - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_XVB-0-0_05_LM.pdf}\n\\caption{XVB-0-0.05 - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_XVB-0-0_1_LM.pdf}\n\\caption{XVB-0-0.1 - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_XVBr-1-10_LM.pdf}\n\\caption{XVBr-1-10 - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_XVBr-0_5-10_LM.pdf}\n\\caption{XVBr-0.5-10 - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_XVBr-0-10_LM.pdf}\n\\caption{XVBr-0-10 - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_XVBr-1-5_LM.pdf}\n\\caption{XVBr-1-5 - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_XVBr-0_5-5_LM.pdf}\n\\caption{XVBr-0.5-5 - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_XVBr-0-5_LM.pdf}\n\\caption{XVBr-0-5 - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_XVBr-1_LM.pdf}\n\\caption{XVBr-1 - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_XVBr-0_5_LM.pdf}\n\\caption{XVBr-0.5 - Linear model}\n}\\end{figure}\n\\begin{figure}[ht]{\\centering\n\\includegraphics[height=5cm]{allcat_XVBr-0_LM.pdf}\n\\caption{XVBr-0 - Linear model}\n}\\end{figure}\n\\begin{thebibliography}{00}\n\\bibitem{Loor2017} Loor, M., De Tr{\\'e}, G.: In a Quest for Suitable Similarity Measures to Compare Experience-Based Evaluations. In: Computational Intelligence: International Joint Conference, IJCCI 2015 Lisbon, Portugal, November 12-14, 2015, Revised Selected Papers pp. 291-314 (2017)\n\\bibitem{Loor2013} M.~Loor and G.~De~Tr{\\'e}, ``{{Vector Based Similarity Measure for Intuitionistic Fuzzy Sets}},'' in \\emph{{{Modern Approaches in Fuzzy Sets, Intuitionistic Fuzzy Sets, Generalized Nets and Related Topics : Volume I: Foundations}}}, K.~T. Atanassov, M.~Baczy{\\'n}ski, J.~Drewniak, J.~Kacprzyk, M.~Krawczak, E.~Szmidt, M.~Wygralak, and S.~Zadro{\\.z}ny, Eds. SRI-PAS, 2014, pp. 105--127.\n\\bibitem{Szmidt2000} E.~Szmidt and J.~Kacprzyk, ``{Distances between intuitionistic fuzzy sets},'' \\emph{Fuzzy Sets and Systems}, vol. 114, no.~3, pp. 505--518, Sep. 2000.\n\\bibitem{Xu2007} Z.~Xu, ``Some similarity measures of intuitionistic fuzzy sets and their applications to multiple attribute decision making,'' \\emph{Fuzzy Optimization and Decision Making}, vol.~6, no.~2, pp. 109--121, 2007.\n\\bibitem{Chen2016} S.-M. Chen, S.-H. Cheng, and T.-C. Lan, ``A novel similarity measure between intuitionistic fuzzy sets based on the centroid points of transformed fuzzy numbers with applications to pattern recognition,'' \\emph{Information Sciences}, vol. 343--344, pp. 15 -- 40, 2016.\n\\bibitem{Chen1997} S.-M. Chen \\emph{et~al.}, ``Similarity measures between vague sets and between elements,'' \\emph{IEEE TRANSACTIONS ON SYSTEMS MAN AND CYBERNETICS PART B-CYBERNETICS}, vol.~27, no.~1, pp. 153--158, 1997.\n\\bibitem{Hong1999} D.~H. Hong and C.~Kim, ``A note on similarity measures between vague sets and between elements,'' \\emph{Information Sciences}, vol. 115, no.~1, pp. 83 --\n  96, 1999.\n\\bibitem{Hung2004} W.-L. Hung and M.-S. Yang, ``Similarity measures of intuitionistic fuzzy sets based on Hausdorff distance,'' \\emph{Pattern Recognition Letters}, vol.~25, no.~14, pp. 1603 -- 1611, 2004.\n\\bibitem{Boran2014} F.~E. Boran and D.~Akay, ``A biparametric similarity measure on intuitionistic fuzzy sets with applications to pattern recognition,'' \\emph{Information Sciences}, vol. 255, pp. 45 -- 57, 2014.\n\\bibitem{Nguyen2016} H.~Nguyen, ``A novel similarity/dissimilarity measure for intuitionistic fuzzy sets and its application in pattern recognition,'' \\emph{Expert Systems with Applications}, vol.~45, pp. 97 -- 107, 2016.\n\\bibitem{Xu2009} Z.~Xu and R.~R. Yager, ``Intuitionistic and interval-valued intutionistic fuzzy preference relations and their measures of similarity for the evaluation of agreement within a group,'' \\emph{Fuzzy Optimization and Decision Making},  vol.~8, no.~2, pp. 123--139, 2009.\n\\bibitem{Szmidt2013} ``Geometric similarity measures for the intuitionistic fuzzy sets,'' in \\emph{8th conference of the European Society for Fuzzy Logic and Technology  (EUSFLAT-13)}. Atlantis Press, 2013,  pp. 840--847.\n\\bibitem{Szmidt2004} E.~Szmidt and J.~Kacprzyk, ``A concept of similarity for intuitionistic fuzzy sets and its use in group decision making,'' in \\emph{IEEE International Conference on Fuzzy Systems}, 2004, pp. 1129--1134.\n\\end{thebibliography}\n \\end{document}\n", "meta": {"hexsha": "64b6304e96cb9ea5392c5e43bca817eee43c0f0a", "size": 14206, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "examples/reports/IFSReport.tex", "max_stars_repo_name": "ifsmetrics-lab/ifsmetrics", "max_stars_repo_head_hexsha": "37e67a493a9b0d3c63f1bca6795b97677471885c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/reports/IFSReport.tex", "max_issues_repo_name": "ifsmetrics-lab/ifsmetrics", "max_issues_repo_head_hexsha": "37e67a493a9b0d3c63f1bca6795b97677471885c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/reports/IFSReport.tex", "max_forks_repo_name": "ifsmetrics-lab/ifsmetrics", "max_forks_repo_head_hexsha": "37e67a493a9b0d3c63f1bca6795b97677471885c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9839572193, "max_line_length": 936, "alphanum_fraction": 0.7479938054, "num_tokens": 5329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.33927475118110456}}
{"text": "\\chapter{QMCPACK design and feature documentation}\n\\label{chap:design_features}\n\nThis section contains information on the overall design of QMCPACK.  Also included are detailed explanations/derivations of major features and algorithms present in the code.\n\n\n\\section{QMCPACK Design}\nTBD.\n\n\n\n\\newpage\n\\section{Feature: Optimized long-range breakup (Ewald)}\n\n% Written by Ken Esler as part of the Common codebase used in wfconvert\n% Originally titled ``Ewald Breakup for Long-Range Potentials in PIMC''\n% PIMC-specific portions have been commented out\n\nConsider a group of particles interacting with long-range central\npotentials, $v^{\\alpha \\beta}(|r^{\\alpha}_i - r^{\\beta}_j|)$, where the Greek superscripts\nrepresent the particle species (e.g., $\\alpha=\\text{electron}$,\n$\\beta=\\text{proton}$), and Roman subscripts refer to particle number\nwithin a species.  We can then write the total interaction energy for\nthe system as\n\\newcommand{\\vr}{\\mathbf{r}}\n\\newcommand{\\vR}{\\mathbf{R}}\n\\newcommand{\\vk}{\\mathbf{k}}\n\\newcommand{\\vq}{\\mathbf{q}}\n\\begin{equation}\nV = \\sum_\\alpha \\left\\{\\sum_{i<j} v^{\\alpha\\alpha}(|\\vr^\\alpha_i - \\vr^\\alpha_j|) +\n\\sum_{\\beta<\\alpha} \n\\sum_{i,j} v^{\\alpha \\beta}(|\\vr^{\\alpha}_i - \\vr^{\\beta}_j|) \\right\\}\n\\label{eq:Vperiodic}\\:.\n\\end{equation}\n\\newcommand{\\va}{\\mathbf{a}}\n\\newcommand{\\vb}{\\mathbf{b}}\n\\newcommand{\\vL}{\\mathbf{L}}\n\n\\subsection{The long-range problem}\nConsider such a system in periodic boundary conditions in a cell\ndefined by primitive lattice vectors $\\va_1$, $\\va_2$, and $\\va_3$.\nLet $\\vL \\equiv n_1 \\va_1 + n_2 \\va_2 + n_3\\va_3$ be a direct lattice\nvector.  Then the interaction energy per cell for the periodic system\nis given by\n\\begin{equation}\n\\begin{split}\nV = & \\sum_\\vL \\sum_\\alpha \\left\\{ \n\\overbrace{\\sum_{i<j} v^{\\alpha\\alpha}(|\\vr^\\alpha_i - \\vr^\\alpha_j + \\vL|)}^{\\text{homologous}} +\n\\overbrace{\\sum_{\\beta<\\alpha} \n\\sum_{i,j} v^{\\alpha \\beta}(|\\vr^{\\alpha}_i - \\vr^{\\beta}_j+\\vL|)}^{\\text{heterologous}}\n\\right\\}  \\\\\n& + \\underbrace{\\sum_{\\vL \\neq \\mathbf{0}} \\sum_\\alpha N^\\alpha v^{\\alpha \\alpha} (|\\vL|)}_\\text{Madelung}\\:.\n\\end{split}\n\\label{eq:direct}\\:,\n\\end{equation}\nwhere $N^\\alpha$ is the number particles of species $\\alpha$.\nIf the potentials $v^{\\alpha\\beta}(r)$ are indeed long-range, the\nsummation over direct lattice vectors will not converge in this naive\nform.  A solution to the problem was posited by Ewald.  We break the\ncentral potentials into two pieces---a short-range and a long-range\npart defined by\n\\begin{equation}\nv^{\\alpha \\beta}(r) = v_s^{\\alpha\\beta}(r) + v_l^{\\alpha \\beta}(r)\\:.\n\\end{equation}\nWe will perform the summation over images for the short-range part in\nreal space, while performing the sum for the long-range part in\nreciprocal space.  For simplicity, we choose $v^{\\alpha \\beta}_s(r)$\nso that it is identically zero at the half-the-box length.  This\neliminates the need to sum over images in real space.\n\n\n\\subsection{Reciprocal-space sums}\n\\subsubsection{Heterologous terms}\nWe begin with Equation~\\ref{eq:direct}, starting with the heterologous terms (i.e., the terms involving particles of different species).  The\nshort-range terms are trivial, so we neglect them here.\n\\begin{equation}\n\\text{heterologous} = \\frac{1}{2} \\sum_{\\alpha \\neq \\beta} \\sum_{i,j} \\sum_\\vL\nv^{\\alpha\\beta}_l(\\vr_i^\\alpha - \\vr_j^\\beta + \\vL)\\:.\n\\end{equation}\nWe insert the resolution of unity in real space twice:\n\\begin{eqnarray}\n\\text{heterologous} & = & \\frac{1}{2}\\sum_{\\alpha \\neq \\beta} \\int_\\text{cell} d\\vr \\, d\\vr' \\, \\sum_{i,j}\n\\delta(\\vr_i^\\alpha - \\vr) \\delta(\\vr_j^\\beta-\\vr') \\sum_\\vL\nv^{\\alpha\\beta}_l(|\\vr - \\vr' + \\vL|)\\:, \\\\\n& = & \\frac{1}{2\\Omega^2}\\sum_{\\alpha \\neq \\beta} \\int_\\text{cell} d\\vr \\, d\\vr' \\, \\sum_{\\vk, \\vk', i, j} e^{i\\vk\\cdot(\\vr_i^\\alpha\n  - \\vr)} e^{i\\vk'\\cdot(\\vr_j^\\beta - \\vr')} \\sum_\\vL\nv^{\\alpha\\beta}_l(|\\vr - \\vr' + \\vL|) \\nonumber\\:, \\\\\n& = & \\frac{1}{2\\Omega^2} \\sum_{\\alpha \\neq \\beta} \\int_\\text{cell} d\\vr \\, d\\vr'\\,\n\\sum_{\\vk, \\vk', \\vk'', i, j} e^{i\\vk\\cdot(\\vr_i^\\alpha - \\vr)}\ne^{i\\vk'\\cdot(\\vr_j^\\beta-\\vr')} e^{i\\vk''\\cdot(\\vr -\\vr')}\nv^{\\alpha\\beta}_{\\vk''}\\nonumber\\:.\n\\end{eqnarray}\nHere, the $\\vk$ summations are over reciprocal lattice vectors given\nby $\\vk = m_1 \\vb_1 + m_2\\vb_2 + m_3\\vb_3$, where\n\\begin{eqnarray}\n\\vb_1 & = & 2\\pi \\frac{\\va_2 \\times \\va_3}{\\va_1 \\cdot (\\va_2 \\times\n  \\va_3)} \\nonumber\\:, \\\\\n\\vb_2 & = & 2\\pi \\frac{\\va_3 \\times \\va_1}{\\va_1 \\cdot (\\va_2 \\times\n  \\va_3)}\\:, \\\\\n\\vb_3 & = & 2\\pi \\frac{\\va_1 \\times \\va_2}{\\va_1 \\cdot (\\va_2 \\times\n  \\va_3)} \\nonumber\\:.\n\\end{eqnarray}\nWe note that $\\vk \\cdot \\vL = 2\\pi(n_1 m_1 + n_2 m_2 + n_3 m_3)$. \n\\begin{eqnarray}\nv_{k''}^{\\alpha \\beta} & = & \n\\frac{1}{\\Omega} \\int_{\\text{cell}} d\\vr'' \\sum_\\vL\ne^{-i\\vk''\\cdot(|\\vr''+\\vL|)} v^{\\alpha\\beta}(|\\vr''+\\vL|)\\:, \\\\\n& = & \\frac{1}{\\Omega} \\int_\\text{all space} d\\tilde{\\vr} \\, \n    e^{-i\\vk'' \\cdot \\tilde{\\vr}} v^{\\alpha\\beta}(\\tilde{r})\\:, \\label{eq:vk}\n\\end{eqnarray}\nwhere $\\Omega$ is the volume of the cell. Here we have used the fact\nthat summing over all cells of the integral over the cell is\nequivalent to integrating over all space.\n\\begin{equation}\n\\text{hetero} = \\frac{1}{2\\Omega^2} \\sum_{\\alpha \\neq \\beta}\n\\int_\\text{cell} d\\vr \\, d\\vr' \\, \\sum_{\\vk, \\vk', \\vk'', i, j}\ne^{i(\\vk \\cdot \\vr_i^\\alpha + \\vk' \\cdot\\vr_j^\\beta)} e^{i(\\vk''-\\vk)\\cdot \\vr}\ne^{-i(\\vk'' + \\vk')\\cdot \\vr'} v^{\\alpha \\beta}_{\\vk''}\\:.\n\\end{equation}\nWe have\n\\begin{equation}\n\\frac{1}{\\Omega} \\int d\\vr \\  e^{i(\\vk -\\vk')\\cdot \\vr} =\n\\delta_{\\vk,\\vk'}\\:.\n\\end{equation}\nThen, performing the integrations we have\n\\begin{eqnarray}\n\\text{hetero} = \\frac{1}{2} \\sum_{\\alpha \\neq \\beta}\n\\sum_{\\vk, \\vk', \\vk'', i, j}\ne^{i(\\vk \\cdot \\vr_i^\\alpha + \\vk' \\cdot\\vr_j^\\beta)} \\delta_{\\vk,\\vk''}\n\\delta_{-\\vk', \\vk''} v^{\\alpha \\beta}_{\\vk''}\\:.\n\\end{eqnarray}\nWe now separate the summations, yielding\n\\begin{equation}\n\\text{hetero} = \\frac{1}{2} \\sum_{\\alpha \\neq \\beta} \\sum_{\\vk, \\vk'}\n\\underbrace{\\left[\\sum_i e^{i\\vk  \\cdot \\vr_i^\\alpha} \\rule{0cm}{0.705cm}\n    \\right]}_{\\rho_\\vk^\\alpha}\n\\underbrace{\\left[\\sum_j e^{i\\vk' \\cdot \\vr_j^\\beta} \\right]}_{\\rho_{\\vk'}^\\beta}\n \\delta_{\\vk,\\vk''} \\delta_{-\\vk', \\vk''} v^{\\alpha\n  \\beta}_{\\vk''}\\:.\n\\end{equation}\nSumming over $\\vk$ and $\\vk'$, we have\n\\begin{equation}\n\\text{hetero} = \\frac{1}{2} \\sum_{\\alpha \\neq \\beta} \\sum_{\\vk''}\n\\rho_{\\vk''}^\\alpha \\, \\rho_{-\\vk''}^\\beta v_{k''}^{\\alpha \\beta}\\:.\n\\end{equation}\nWe can simplify the calculation a bit further by rearranging the\nsums over species:\n\\begin{eqnarray}\n\\text{hetero} & = & \\frac{1}{2} \\sum_{\\alpha > \\beta} \\sum_{\\vk}\n\\left(\\rho^\\alpha_\\vk \\rho^\\beta_{-\\vk} + \\rho^\\alpha_{-\\vk}\n\\rho^\\beta_\\vk\\right) v_{k}^{\\alpha\\beta}\\:, \\\\\n& = & \\sum_{\\alpha > \\beta} \\sum_\\vk \\mathcal{R}e\\left(\\rho_\\vk^\\alpha\n\\rho_{-\\vk}^\\beta\\right)v_k^{\\alpha\\beta} .\n\\end{eqnarray}\n\\subsubsection{Homologous Terms}\nWe now consider the terms involving particles of the same species\ninteracting with each other.  The algebra is very similar to the\npreceding, with the slight difficulty of avoiding the self-interaction term.\n\\begin{eqnarray}\n\\text{homologous} & = & \\sum_\\alpha \\sum_L \\sum_{i<j} v_l^{\\alpha\n  \\alpha}(|\\vr_i^\\alpha - \\vr_j^\\alpha + \\vL|)\\:, \\\\\n & = & \\frac{1}{2} \\sum_\\alpha \\sum_L \\sum_{i\\neq j} v_l^{\\alpha\n  \\alpha}(|\\vr_i^\\alpha - \\vr_j^\\alpha + \\vL|)\\:. \n\\end{eqnarray}\n\\begin{eqnarray}\n\\text{homologous} & = & \\frac{1}{2} \\sum_\\alpha \\sum_L \n\\left[\n-N^\\alpha v_l^{\\alpha \\alpha}(|\\vL|)  + \\sum_{i,j} v^{\\alpha \\alpha}_l(|\\vr_i^\\alpha - \\vr_j^\\alpha + \\vL|)\n  \\right]\\:, \\\\\n& = & \\frac{1}{2} \\sum_\\alpha \\sum_\\vk \\left(|\\rho_k^\\alpha|^2 - N\n\\right) v_k^{\\alpha \\alpha}\\:.\n\\end{eqnarray}\n\\subsubsection{Madelung terms}\nLet us now consider the Madelung term for a single particle of species\n$\\alpha$.  This term corresponds to the interaction of a particle with\nall of its periodic images.  \n\\begin{eqnarray}\nv_M^{\\alpha} & = & \\frac{1}{2} \\sum_{\\vL \\neq \\mathbf{0}} v^{\\alpha\n  \\alpha}(|\\vL|)\\:, \\\\\n& = & \\frac{1}{2} \\left[ -v_l^{\\alpha \\alpha}(0) + \\sum_\\vL v^{\\alpha\n  \\alpha}(|\\vL|) \\right]\\:, \\\\\n& = & \\frac{1}{2} \\left[ -v_l^{\\alpha \\alpha}(0) + \\sum_\\vk v^{\\alpha\n  \\alpha}_\\vk \\right]\\:.  \n\\end{eqnarray}\n\\subsubsection{$\\vk=\\mathbf{0}$ terms}\nThus far, we have neglected what happens at the special point $\\vk =\n\\mathbf{0}$.  For many long-range potentials, such as the Coulomb\npotential, $v_k^{\\alpha \\alpha}$ diverges for $k=0$.  However, we\nrecognize that for a charge-neutral system, the divergent part of the\nterms cancel each other.  If all the potential in the system were\nprecisely Coulomb, the $\\vk=\\mathbf{0}$ terms would cancel precisely,\nyielding zero.  For systems involving PPs, however, it\nmay be that the resulting term is finite, but nonzero.  Consider\nthe terms from $\\vk=\\mathbf{0}$:\n\\begin{eqnarray}\nV_{k=0} & = & \\sum_{\\alpha>\\beta} N^\\alpha N^\\beta v^{\\alpha \\beta}_{k=0}\n+ \\frac{1}{2} \\sum_\\alpha \\left(N^{\\alpha}\\right)^2 v^{\\alpha\\alpha}_{k=0}\\:, \\\\\n& = & \\frac{1}{2} \\sum_{\\alpha,\\beta} N^\\alpha N^\\beta v^{\\alpha\n  \\beta}_{k=0}\\:.\n\\label{eq:kzero}\n\\end{eqnarray}\nNext, we must compute $v^{\\alpha \\beta}_{k=0}$.  \n\\begin{equation}\nv^{\\alpha \\beta}_{k=0} = \\frac{4 \\pi}{\\Omega} \\int_0^\\infty dr\\ r^2\nv_l^{\\alpha \\beta}(r)\\:.\n\\end{equation}\nWe recognize that this integral will not converge because of the\nlarge-$r$ behavior.  However, we recognize that when we do the sum in\nEquation~\\ref{eq:kzero}, the large-$r$ parts of the integrals will cancel\nprecisely.  Therefore, we define\n\\begin{equation}\n\\tilde{v}^{\\alpha \\beta}_{k=0} = \\frac{4 \\pi}{\\Omega} \n\\int_0^{r_\\text{end}} dr\\ r^2 v_l^{\\alpha \\beta}(r)\\:,\n\\end{equation}\nwhere $r_{\\text{end}}$ is some cutoff value after which the potential\ntails precisely cancel.\n\\subsubsection{Neutralizing background terms}\nFor systems with a net charge, such as the one-component plasma\n(jellium), we add a uniform background charge, which makes the system\nneutral.  When we do this, we must add a term that comes from the\ninteraction of the particle with the neutral background.  It is a\nconstant term, independent of the particle positions.  In general, we\nhave a compensating background for each species, which largely cancels\nout for neutral systems.\n\\begin{equation}\nV_\\text{background} = -\\frac{1}{2} \\sum_\\alpha \\left(N^\\alpha\\right)^2 \nv^{\\alpha \\alpha}_{s\\mathbf{0}}\n-\\sum_{\\alpha > \\beta} N_\\alpha N_\\beta\nv^{\\alpha\\beta}_{s\\mathbf{0}}\\:,\n\\end{equation}\nwhere $v^{\\alpha \\beta}_{s\\mathbf{0}}$ is given by\n\\begin{eqnarray}\nv^{\\alpha \\beta}_{s\\mathbf{0}} & = & \\frac{1}{\\Omega} \\int_0^{r_c} d^3 r\\ \nv^{\\alpha \\beta}_s(r)\\:, \\\\\n& = & \\frac{4 \\pi}{\\Omega} \\int_0^{r_c} r^2 v_s(r) \\ dr \\nonumber\\:.\n\\end{eqnarray}\n\n\n\\subsection{Combining terms}\nHere, we sum all of the terms we computed in the previous sections:\n\\begin{eqnarray}\nV & = & \\sum_{\\alpha > \\beta} \\left[\\sum_{i,j} v_s(|\\vr_i^\\alpha\n  -\\vr_j^\\beta|) + \\sum_\\vk \\mathcal{R}e\\left(\\rho_\\vk^\\alpha\n  \\rho_{-\\vk}^\\beta\\right)v^{\\alpha\\beta}_k  -N^\\alpha N^\\beta\n  v^{\\alpha \\beta}_{s\\mathbf{0}}  \\right] \\nonumber\\:, \\\\\n& + & \\sum_\\alpha \\left[ N^\\alpha v_M^\\alpha + \\sum_{i>j} v_s(|\\vr_i^\\alpha -\n  \\vr_j^\\alpha|) + \\frac{1}{2} \\sum_\\vk \\left( |\\rho_\\vk^\\alpha|^2 -\n  N\\right) v^{\\alpha\\alpha}_\\vk -\\frac{1}{2}\\left(N_\\alpha\\right)^2 v_{s\\mathbf{0}}^{\\alpha\\alpha}\\right] \\nonumber\\:, \\\\\n& = & \\sum_{\\alpha > \\beta} \\left[\\sum_{i,j} v_s(|\\vr_i^\\alpha\n  -\\vr_j^\\beta|) + \\sum_\\vk \\mathcal{R}e\\left(\\rho_\\vk^\\alpha\n  \\rho_{-\\vk}^\\beta\\right) v^{\\alpha \\beta}_k   -N^\\alpha N^\\beta\n  v^{\\alpha \\beta}_{s\\mathbf{0}}  +\\tilde{V}_{k=0} \\right]\\:, \\\\\n& + & \\sum_\\alpha \\left[ -\\frac{N^\\alpha v_l^{\\alpha \\alpha}(0)}{2}  + \\sum_{i>j} v_s(|\\vr_i^\\alpha -\n  \\vr_j^\\alpha|) + \\frac{1}{2} \\sum_\\vk |\\rho_\\vk^\\alpha|^2 v^{\\alpha\\alpha}_\\vk - \\frac{1}{2}\\left(N_\\alpha\\right)^2\n  v_{s\\mathbf{0}}^{\\alpha\\alpha} +\\tilde{V}_{k=0}\\right]  \\nonumber\\:.\n\\end{eqnarray}\n\n\\subsection {Computing the reciprocal potential}\nNow we return to Equation~\\ref{eq:vk}.  Without loss of generality, we define\nfor convenience $\\vk = k\\hat{\\mathbf{z}}$.\n\\begin{equation}\nv^{\\alpha \\beta}_k = \\frac{2\\pi}{\\Omega} \\int_0^\\infty dr \\int_{-1}^1\n  d\\cos(\\theta) \\ r^2 e^{-i k r \\cos(\\theta)} v_l^{\\alpha \\beta}(r)\\:.\n\\end{equation}\nWe do the angular integral first.  By inversion symmetry, the\nimaginary part of the integral vanishes, yielding\n\\begin{equation}\nv^{\\alpha \\beta}_k = \\frac{4\\pi}{\\Omega k}\\int _0^\\infty dr\\ r \\sin(kr)\nv^{\\alpha \\beta}_l(r)\\:.\n\\label{eq:vkint}\n\\end{equation}\n\\subsection{The Coulomb potential}\nFor the case of the Coulomb potential, the preceding integral is not\nformally convergent if we do the integral naively. We may remedy the\nsituation by including a convergence factor, $e^{-k_0 r}$.  For a\npotential of the form $v^{\\text{coul}}(r) = q_1 q_2/r$, this yields\n\\begin{eqnarray}\nv^{\\text{screened coul}}_k & = & \\frac{4\\pi q_1 q_2}{\\Omega k} \\int_0^\\infty dr\\ \\sin(kr)\ne^{-k_0r}\\:, \\\\ \n& = & \\frac{4\\pi q_1 q_2}{\\Omega (k^2 + k_0^2)}\\:.\n\\end{eqnarray}\nAllowing the convergence factor to tend to zero, we have\n\\begin{equation}\nv_k^\\text{coul} = \\frac{4 \\pi q_1 q_2}{\\Omega k^2}\\:.\n\\end{equation}\n\nFor more generalized potentials with a Coulomb tail, we cannot\nevaluate Equation~\\ref{eq:vkint} numerically but must handle the coulomb part\nanalytically.  In this case, we have\n\\begin{equation}\nv_k^{\\alpha \\beta} = \\frac{4\\pi}{\\Omega} \n\\left\\{ \\frac{q_1 q_2}{k^2} + \\int_0^\\infty dr \\ r \\sin(kr) \\left[ v_l^{\\alpha \\beta}(r) -\n  \\frac{q_1 q_2}{r} \\right] \\right\\}\\:.\n\\end{equation}\n\n\\subsection{Efficient calculation methods}\n\\subsubsection{Fast computation of $\\rho_\\vk$}\nWe wish to quickly calculate the quantity\n\\begin{equation}\n\\rho_\\vk^\\alpha \\equiv \\sum_i e^{i\\vk \\cdot r_i^\\alpha}\\:.\n\\end{equation}\nFirst, we write \n\\begin{eqnarray}\n\\vk & = & m_1 \\vb_1 + m_2 \\vb_2 + m_3 \\vb_3\\:, \\\\\n\\vk \\cdot \\vr_i^\\alpha & = &  m_1 \\vb_1 \\cdot \\vr_i^\\alpha + \nm_2 \\vb_2 \\cdot \\vr_i^\\alpha + m_3 \\vb_3 \\cdot \\vr_i^\\alpha\\:, \\\\\ne^{i\\vk \\cdot r_i^\\alpha} & = & \n{\\underbrace{\\left[e^{i \\vb_1 \\cdot\\vr_i^\\alpha}\\right]}_{C^{i\\alpha}_1}}^{m_1}\n{\\underbrace{\\left[e^{i \\vb_2 \\cdot\\vr_i^\\alpha}\\right]}_{C^{i\\alpha}_2}}^{m_2}\n{\\underbrace{\\left[e^{i \\vb_3 \\cdot\\vr_i^\\alpha}\\right]}_{C^{i\\alpha}_3}}^{m_3}\\:.\n\\end{eqnarray}\nNow, we note that\n\\begin{equation}\n[C^{i\\alpha}_1]^{m_1} = C^{i\\alpha}_1 [C^{i\\alpha}]^{(m_1-1)}\\:.\n\\end{equation}\nThis allows us to recursively build up an array of the $C^{i\\alpha}$s\nand then compute $\\rho_\\vk$ for all $\\vk$-vectors by looping over all\nk-vectors, requiring only two complex multiplies per particle per\n$\\vk$.\n\\begin{algorithm}\n\\caption{Algorithm to quickly calculate $\\rho_\\vk^\\alpha$.}\n\\begin{algorithmic}\n\\STATE Create list of $\\vk$-vectors and corresponding $(m_1, m_2,\nm_3)$ indices.\n\\FORALL{$\\alpha \\in $ species}\n  \\STATE Zero out $\\rho_\\vk^\\alpha$\n  \\FORALL{$i \\in $ particles}\n    \\FOR{$j \\in [1\\cdots3]$}\n      \\STATE Compute $C^{i \\alpha}_j \\equiv e^{i \\vb_j \\cdot\n        \\vr^{\\alpha}_i}$\n       \\FOR{$m \\in [-m_{\\text{max}}\\dots m_{\\text{max}}]$}\n         \\STATE Compute $[C^{i \\alpha}_j]^m$ and store in array\n       \\ENDFOR\n    \\ENDFOR\n     \\FORALL{$(m_1, m_2, m_3) \\in $ index list}\n       \\STATE Compute $e^{i \\vk \\cdot r^\\alpha_i} =\n         [C^{i\\alpha}_1]^{m_1} [C^{i\\alpha}_2]^{m_2}\n         [C^{i\\alpha}_3]^{m_3}$ from array\n    \\ENDFOR\n  \\ENDFOR\n\\ENDFOR\n\\end{algorithmic}\n\\end{algorithm}\n\n\\subsection{Gaussian charge screening breakup}\nThis original approach to the short- and long-range breakup adds an\nopposite screening charge of Gaussian shape around each point charge.\nIt then removes the charge in the long-range part of the potential.\nIn this potential,\n\\begin{equation}\nv_{\\text{long}}(r) = \\frac{q_1 q_2}{r} \\text{erf}(\\alpha r)\\:,\n\\end{equation}\nwhere $\\alpha$ is an adjustable parameter used to control how\nshort ranged the potential should be.  If the box size is $L$, a\ntypical value for $\\alpha$ might be $7/(Lq_1 q_2)$. We should note\nthat this form for the long-range potential should also work for any\ngeneral potential with a Coulomb tail (e.g., pseudo-Hamiltonian\npotentials.  For this form of the long-range potential, we have in $k$-space\n\\begin{equation}\nv_k = \\frac{4\\pi q_1 q_2 \\exp\\left[\\frac{-k^2}{4\\alpha^2}\\right]}{\\Omega k^2}\\:.\n\\end{equation}\n\n\\subsection{Optimized breakup method}\nIn this section, we undertake the task of choosing a\nlong-range/short-range partitioning of the potential, which is optimal\nin that it minimizes the error for given real and $k$-space cutoffs\n$r_c$ and $k_c$.  Here, we slightly modify the method introduced by\nNatoli and Ceperley\\cite{Natoli1995}. We choose $r_c =\n\\frac{1}{2}\\min\\{L_i\\}$ so that we require the nearest image in\nreal-space summation.  $k_c$ is then chosen to satisfy our\naccuracy requirements.\n\nHere we modify our notation slightly to accommodate details not previously required.  We restrict our discussion to the interaction of two\nparticle species (which may be the same), and drop our species\nindices.  Thus, we are looking for short- and long-range potentials\ndefined by\n\\renewcommand{\\vs}{v^s}\n\\newcommand{\\vl}{v^\\ell}\n\\begin{equation}\nv(r) = \\vs(r) + \\vl(r)\\:.\n\\end{equation}\nDefine $\\vs_k$ and $\\vl_k$ to be the respective Fourier transforms of\nthe previous equation.  The goal is to choose $v_s(r)$ such that its value and\nfirst two derivatives vanish at $r_c$, while making $\\vl(r)$ as smooth as\npossible so that $k$-space components, $\\vl_k$, are very small for\n$k>k_c$.  Here, we describe how to do this in an optimal way.\n\nDefine the periodic potential, $V_p$, as \n\\begin{equation}\nV_p(\\vr) = \\sum_l v(|\\vr + \\mathbf{l}|),\n\\end{equation}\nwhere $\\vr$ is the displacement between the two particles and\n$\\mathbf{l}$ is a lattice vector.  Let us then define our\napproximation to this potential, $V_a$, as\n\\begin{equation}\nV_a(\\vr) = \\vs(r) + \\sum_{|\\vk| < k_c} \\vl_k e^{i\\mathbf \\vk \\cdot \\vr}\\:.\n\\end{equation}\nNow, we seek to minimize the RMS error over the cell,\n\\begin{equation}\n\\chi^2 = \\frac{1}{\\Omega}\\int_\\Omega d^3 \\mathbf{r} \\ \n\\left| V_p(\\vr) - V_a(\\vr)\\right|^2\\:. \n\\end{equation}\nWe may write\n\\begin{equation}\nV_p(\\vr) = \\sum_{\\vk} v_k e^{i \\vk \\cdot \\vr}\\:,\n\\end{equation}\nwhere \n\\begin{equation}\nv_k = \\frac{1}{\\Omega} \\int d^3\\vr \\ e^{-i\\vk\\cdot\\vr}v(r)\\:.\n\\end{equation}\nWe now need a basis in which to represent the broken-up potential.  We\nmay choose to represent either $\\vs(r)$ or $\\vl(r)$ in a real-space\nbasis.  Natoli and Ceperley chose the former in their paper.  We choose\nthe latter for a number of reasons.  First, singular potentials are\ndifficult to represent in a linear basis unless the singularity is\nexplicitly included.  This requires a separate basis for each type of\nsingularity.  The short-range potential may have an arbitrary number\nof features for $r<r_c$ and still be a valid potential.  By\nconstruction, however, we desire that $\\vl(r)$ be smooth in real-space\nso that its Fourier transform falls off quickly with increasing $k$.\nWe therefore expect that, in general, $\\vl(r)$ should be\nwell represented by fewer basis functions than $\\vs(r)$.  Therefore,\nwe define\n\\begin{equation}\n\\vl(r) \\equiv\n\\begin{cases}\n \\sum_{n=0}^{J-1} t_n h_n(r) & \\text{for } r \\le r_c \\\\\n v(r) & \\text{for } r > r_c.\n\\end{cases}\\:,\n\\end{equation}\nwhere the $h_n(r)$ are a set of $J$ basis functions.  We require that\nthe two cases agree on the value and first two derivatives at $r_c$.\nWe may then define\n\\begin{equation}\nc_{nk} \\equiv \\frac{1}{\\Omega} \\int_0^{r_c} d^3 \\vr \\ e^{-i\\vk\\cdot\\vr} h_n(r)\\:.\n\\end{equation}\nSimilarly, we define\n\\begin{equation}\nx_k \\equiv -\\frac{1}{\\Omega} \\int_{r_c}^\\infty d^3\\vr \\ e^{-i\\vk\\cdot\\vr} v(r)\\:.\n\\end{equation}\nTherefore,\n\\begin{equation}\n\\vl_k = -x_k + \\sum_{n=0}^{J-1} t_n c_{nk}\\:. \n\\end{equation}\nBecause $\\vs(r)$ goes identically to zero at the box edge, inside the\ncell we may write\n\\begin{equation}\n\\vs(\\vr) = \\sum_\\vk \\vs_k e^{i\\vk \\cdot \\vr}\\:.\n\\end{equation}\nWe then write\n\\begin{equation}\n\\chi^2 = \\frac{1}{\\Omega} \\int_\\Omega d^3 \\vr \\ \n\\left| \\sum_\\vk e^{i\\vk \\cdot \\vr} \\left(v_k - \\vs_k \\right)\n-\\sum_{|\\vk| \\le k_c} \\vl_k \\right|^2\\:.\n\\end{equation}\nWe see that if we define\n\\begin{equation}\n\\vs(r) \\equiv v(r) - \\vl(r)\\:.\n\\end{equation}\nThen\n\\begin{equation}\n\\vl_k + \\vs_k = v_k\\:,\n\\end{equation}\nwhich then cancels out all terms for $|\\vk| < k_c$.  Then we have\n\\begin{eqnarray}\n\\chi^2 & = & \\frac{1}{\\Omega} \\int_\\Omega d^3 \\vr \\ \n\\left|\\sum_{|\\vk|>k_c} e^{i\\vk\\cdot\\vr} \n\\left(v_k -\\vs_k \\right)\\right|^2\\:, \\\\\n& = & \\frac{1}{\\Omega} \\int_\\Omega d^3 \\vr \\ \n\\left|\\sum_{|\\vk|>k_c} e^{i\\vk\\cdot\\vr} \\vl_k \\right|^2\\:, \\\\ \n& = & \n\\frac{1}{\\Omega} \\int_\\Omega d^3 \\vr\n\\left|\\sum_{|\\vk|>k_c} e^{i\\vk\\cdot\\vr}\\left( -x_k + \\sum_{n=0}^{J-1} t_n\nc_{nk}\\right) \\right|^2\\:.\n\\end{eqnarray}\nWe expand the summation,\n\\newcommand{\\ns}{\\negthickspace}\n\\begin{equation}\n\\chi^2 = \\frac{1}{\\Omega} \\int_\\Omega d^3 \\vr \\ns \\ns \\ns\n\\sum_{\\{|\\vk|,|\\vk'|\\}>k_c} \\ns\\ns\\ns\\ns\\ns\n e^{i(\\vk-\\vk')\\cdot \\vr}\n\\left(x_k -\\sum_{n=0}^{J-1} t_n c_{nk} \\right)\n\\left(x_k -\\sum_{m=0}^{J-1} t_{m} c_{mk'} \\right)\\:.\n\\end{equation}\nWe take the derivative w.r.t. $t_{m}$:\n\\begin{equation}\n\\frac{\\partial (\\chi^2)}{\\partial t_{m}} =\n\\frac{2}{\\Omega}\\int_\\Omega d^3 \\vr \\ns \\ns \\ns\n\\sum_{\\{|\\vk|,|\\vk'|\\}>k_c} \\ns\\ns\\ns\\ns\\ns\n e^{i(\\vk-\\vk')\\cdot \\vr}\n\\left(x_k -\\sum_{n=0}^{J-1} t_n c_{nk} \\right) c_{mk'}\\:.\n\\end{equation}\nWe integrate w.r.t. $\\vr$, yielding a Kronecker $\\delta$.\n\\begin{equation}\n\\frac{\\partial (\\chi^2)}{\\partial t_{m}} =\n2 \\ns\\ns\\ns\\ns\\ns\\ns\\ns \n\\sum_{\\ \\ \\ \\ \\{|\\vk|,|\\vk'|\\}>k_c} \\ns\\ns\\ns\\ns\\ns\\ns\\ns \\delta_{\\vk, \\vk'} \n\\left(x_k -\\sum_{n=0}^{J-1} t_n c_{nk} \\right) c_{mk'}\\:.\n\\end{equation}\nSumming over $\\vk'$ and equating the derivative to zero, we find the\nminimum of our error function is given by\n\\begin{equation}\n\\sum_{n=0}^{J-1} \\sum_{|\\vk|>k_c} c_{mk}c_{nk} t_n = \n\\sum_{|\\vk|>k_c} x_k c_{mk}\\:,\n\\end{equation}\nwhich is equivalent in form to Equation~19 in \\cite{Natoli1995}, where\nwe have $x_k$ instead of $V_k$.  Thus, we see that we can optimize\nthe short- or long-range potential simply by choosing to use\n$V_k$ or $x_k$ in the preceding equation.  We now define\n\\begin{eqnarray}\nA_{mn} & \\equiv & \\sum_{|\\vk|>k_c} c_{mk} c_{nk}\\:, \\\\\nb_{m} & \\equiv & \\sum_{|\\vk|>k_c} x_k c_{mk}\\:.\n\\end{eqnarray}\nThus, it becomes clear that our minimization equations can be cast in\nthe canonical linear form\n\\newcommand{\\bA}{\\mathbf{A}}\n\\newcommand{\\bU}{\\mathbf{U}}\n\\newcommand{\\bV}{\\mathbf{V}}\n\\newcommand{\\bb}{\\mathbf{b}}\n\\newcommand{\\bS}{\\mathbf{S}}\n\\begin{equation}\n\\bA\\mathbf{t} = \\mathbf{b}\\:.\n\\end{equation}\n\n\\subsubsection{Solution by SVD}\nIn practice, we note that the matrix $\\bA$ frequently becomes singular\nin practice.  For this reason, we use the singular value decomposition\nto solve for $t_n$.  This factorization decomposes $A$ as\n\\begin{equation}\n\\bA = \\bU \\bS \\bV^T\\:,\n\\end{equation}\nwhere $\\bU^T\\bU = \\bV^T\\bV = 1$ and $\\bS$ is diagonal.  In this form, we have\n\\begin{equation}\n\\mathbf{t} = \\sum_{i=0}^{J-1} \\left( \\frac{\\bU_{(i)} \\cdot\n  \\bb}{\\bS_{ii}} \\right) \\bV_{(i)}\\:,\n\\end{equation}\nwhere the parenthesized subscripts refer to columns.  The advantage of\nthis form is that if $\\bS_{ii}$ is zero or very near zero, the\ncontribution of the $i^{\\text{th}}$ of $\\bV$ may be neglected since\nit represents a numerical instability and has little physical\nmeaning.  It represents the fact that the system cannot distinguish\nbetween two linear combinations of the basis functions.  Using the SVD\nin this manner is guaranteed to be stable.  This decomposition is\navailable in LAPACK in the DGESVD subroutine.\n\n\\subsubsection{Constraining Values}\nOften, we wish to constrain the value of $t_n$ to have a fixed value\nto enforce a boundary condition, for example.  To do this, we define\n\\begin{equation}\n\\bb' \\equiv \\vb - t_n \\bA_{(n)}\\:.\n\\end{equation}\nWe then define $\\bA^*$ as $\\bA$ with the $n^{\\text{th}}$ row and column\nremoved and $\\bb^*$ as $\\vb'$ with the $n^{\\text{th}}$ element removed.  Then\nwe solve the reduced equation $\\bA^* \\mathbf{t}^* = \\bb^*$ and\nfinally insert $t_n$ back into the appropriate place in $\\mathbf{t}^*$\nto recover the complete, constrained vector $\\mathbf{t}$.  This may be\ntrivially generalized to an arbitrary number of constraints.\n\\label{sec:contraints}\n\n\\subsubsection{The LPQHI basis}\nThe preceding discussion is general and independent of the basis used to\nrepresent $\\vl(r)$.  In this section, we introduce a convenient basis\nof localized interpolant functions, similar to those used for\nsplines, which have a number of properties that are convenient for\nour purposes.  \n\nFirst, we divide the region from 0 to $r_c$ into $M-1$ subregions,\nbounded above and below by points we term {\\em knots}, defined by $r_j\n\\equiv j\\Delta$, where $\\Delta \\equiv r_c/(M-1)$.  We then define\ncompact basis elements, $h_{j\\alpha}$, which span the region\n$[r_{j-1},r_{j+1}]$, except for $j=0$ and $j=M$.  For $j=0$, only the\nregion $[r_0,r_1]$, while for $j=M$, only $[r_{M-1}, r_M]$.  Thus, the\nindex $j$ identifies the knot the element is centered on, while $\\alpha$\nis an integer from 0 to 2 indicating one of three function shapes.\nThe dual index can be mapped to the preceding single index by the\nrelation $n = 3j + \\alpha$.  The basis functions are then defined as\n\\begin{equation}\nh_{j\\alpha}(r) = \n\\begin{cases}\n\\ \\ \\ \\, \\Delta^\\alpha \\, \\, \\sum_{n=0}^5 S_{\\alpha n} \n\\left( \\frac{r-r_j}{\\Delta}\\right)^n,    & r_j < r \\le r_{j+1} \\\\\n(-\\Delta)^\\alpha \\sum_{n=0}^5 S_{\\alpha n} \n\\left( \\frac{r_j-r}{\\Delta}\\right)^n,    & r_{j-1} < r \\le r_j \\\\\n\\quad\\quad\\quad\\quad\\quad 0, & \\text{otherwise}\\:,\n\\end{cases}\n\\end{equation}\nwhere the matrix $S_{\\alpha n}$ is given by\n\\begin{equation}\nS = \n\\left[\\begin{matrix}\n1 & 0 & 0 & -10 & 15 & -6 \\\\\n0 & 1 & 0 & -6  &  8 & -3 \\\\\n0 & 0 & \\frac{1}{2} & -\\frac{3}{2} & \\frac{3}{2} & -\\frac{1}{2}\n\\end{matrix}\\right]\\:.\n\\end{equation}\n\\begin{figure}\n\\begin{center}\n  \\ifdefined\\HCode\n  \\includegraphics[width=3.5in]{./figures/LPQHI.dmn}\n  \\else\n  \\includegraphics[width=3.5in]{./figures/LPQHI.pdf}\n  \\fi\n\\caption{Basis functions $h_{j0}$, $h_{j1}$, and $h_{j2}$ are shown.\nWe note that at the left and right extremes, the values and first two\nderivatives of the functions are zero; while at the center, $h_{j0}$\nhas a value of 1, $h_{j1}$ has a first derivative of 1, and $h_{j2}$\nhas a second derivative of 1. }\n\\label{fig:LPQHI} \n\\end{center}\n\\end{figure}\nFigure~\\ref{fig:LPQHI} shows plots of these function shapes.\n\nThe basis functions have the property that at the left and right\nextremes (i.e., $r_{j-1}$ and $r_{j+1}$) their values and first two\nderivatives are zero.  At the center, $r_j$, we have the properties\n\\begin{eqnarray}\nh_{j0}(r_j)=1, & h'_{j0}(r_j)=0, & h''_{j0}(r_j)= 0\\:, \\\\\nh_{j1}(r_j)=0, & h'_{j1}(r_j)=1, & h''_{j1}(r_j)= 0\\:, \\\\\nh_{j2}(r_j)=0, & h'_{j2}(r_j)=0, & h''_{j2}(r_j)= 1\\:. \n\\end{eqnarray}\nThese properties allow the control of the value and first two derivatives\nof the represented function at any knot value simply by setting the\ncoefficients of the basis functions centered around that knot.  Used\nin combination with the method described in\nSection~\\ref{sec:contraints}, boundary conditions can easily be\nenforced.  In our case, we wish require that\n\\begin{equation}\nh_{M0} = v(r_c), \\ \\ h_{M1} = v'(r_c), \\ \\ \\text{and} \\ \\  h_{M2} = v''(r_c)\\:.\n\\end{equation}\nThis ensures that $\\vs$ and its first two derivatives vanish at $r_c$.\n\n\\subsubsection*{Fourier coefficients}\nWe wish now to calculate the Fourier transforms of the basis\nfunctions, defined as\n\\begin{equation}\nc_{j\\alpha k} \\equiv \\frac{1}{\\Omega} \\int_0^{r_c} d^3 \\vr \ne^{-i \\vk \\cdot \\vr} h_{j\\alpha}(r)\\:.\n\\end{equation}\nWe then may write,\n\\begin{equation}\nc_{j\\alpha k} = \n\\begin{cases}\n\\Delta^\\alpha \\sum_{n=0}^5 S_{\\alpha n} D^+_{0 k n}, & j = 0 \\\\\n\\Delta^\\alpha \\sum_{n=0}^5 S_{\\alpha n} (-1)^{\\alpha+n} D^-_{M k n}, &\nj = M \\\\\n\\Delta^\\alpha \\sum_{n=0}^5 S_{\\alpha n} \n\\left[ D^+_{j k n} + (-1)^{\\alpha+n}D^-_{j k n} \\right] & \\text{otherwise}\\:,\n\\end{cases}\n\\end{equation}\nwhere\n\\begin{equation}\nD^{\\pm}_{jkn} \\equiv \\frac{1}{\\Omega} \\int_{r_j}^{r_{j\\pm1}} d^3\\!\\vr \\ \ne^{-i\\vk \\cdot \\vr} \\left( \\frac{r-r_j}{\\Delta}\\right)^n\\:.\n\\end{equation}\nWe then further make the definition that\n\\renewcommand{\\Im}{\\text{Im}}\n\\begin{equation}\nD^{\\pm}_{jkn} = \\pm \\frac{4\\pi}{k \\Omega} \n\\left[ \\Delta \\Im \\left(E^{\\pm}_{jk(n+1)}\\right) + \nr_j \\Im \\left(E^{\\pm}_{jkn}\\right)\\right]\\:.\n\\end{equation}\nIt can then be shown that \n\\begin{equation}\nE^{\\pm}_{jkn} =\n\\begin{cases}\n-\\frac{i}{k} e^{ikr_j} \\left( e^{\\pm i k \\Delta} - 1 \\right) &\n\\text{if } n=0, \\\\\n-\\frac{i}{k} \n\\left[ \\left(\\pm1\\right)^n e^{i k (r_j \\pm \\Delta)} - \\frac{n}{\\Delta}\nE^\\pm_{jk(n-1)}  \\right] & \\text{otherwise}\\:.\n\\end{cases}\n\\end{equation}\nNote that these equations correct typographical errors present in \\cite{Natoli1995}.\n\\subsubsection{Enumerating $k$-points}\nWe note that the summations over $k$, which are ubiquitous in\nthis paper, require enumeration of the $k$-vectors.  In particular, we\nshould sum over all $|\\vk| > k_c$.  In practice, we must limit our\nsummation to some finite cutoff value $k_c < |\\vk| < k_{\\text{max}}$,\nwhere $k_{\\text{max}}$ should be on the order of $3,000/L$, where $L$ is the\nminimum box dimension.  Enumerating these vectors in a naive fashion\neven for this finite cutoff would prove quite prohibitive, as it would \nrequire $\\sim10^9$ vectors.\n\nOur first optimization comes in realizing that all quantities in this\ncalculation require only $|\\vk|$ and not $\\vk$ itself.  Thus, we may\ntake advantage of the great degeneracy of $|\\vk|$.  We create a list\nof $(k,N)$ pairs, where $N$ is the number of vectors with magnitude $k$.\nWe make nested loops over\n$n_1$, $n_2$, and $n_3$, yielding $\\vk = n_1 \\vb_1 + n_2 \\vb_2 + n_3\n\\vb_3$. If $|\\vk|$ is in the required range, we check to see whether there\nis already an entry with that magnitude on our list and incremente the\ncorresponding $N$ if there is, or create a new entry if not.  Doing\nso typically saves a factor of $\\sim200$ in storage and computation.\n\nThis reduction is not sufficient for large $k_max$ since it\nrequires that we still look over $10^9$ entries.  To further reduce\ncosts, we may pick an intermediate cutoff, $k_{\\text{cont}}$, above which\nwe will approximate the degeneracy assuming a continuum of\n$k$-points.  We stop our exact enumeration at $k_{\\text{cont}}$ and\nthen add $\\sim1,000$ points, $k_i$, uniformly spaced between $k_{\\text{cont}}$\nand $k_{\\text{max}}$. We then approximate the degeneracy by\n\\begin{equation}\nN_i = \\frac{4 \\pi}{3} \\frac{\\left( k_b^3 -k_a^3\\right)}{(2\\pi)^3/\\Omega}\\:,\n\\end{equation}\nwhere $k_b = (k_i + k_{i+1})/2$ and $k_a = (k_i + k_{i-1})$.  In doing\nso, we typically reduce our total number of k-points to sum more than $\\sim2,500$ from the $10^9$ we had to start.\n\n\\subsubsection{Calculating $x_k$'s}\n\\subsubsection*{The Coulomb potential}\nFor $v(r) = \\frac{1}{r}$, $x_k$ is given by\n\\begin{equation}\nx_k^{\\text{coulomb}} = -\\frac{4 \\pi}{\\Omega k^2} \\cos(k r_c)\\:.\n\\end{equation}\n\n\\subsection*{The $1/r^2$ potential}\nFor $v(r) = \\frac{1}{r^2}$, $x_k$ is given by\n\\begin{equation}\nx_k^{1/r^2} = \\frac{4 \\pi}{\\omega k} \n\\left[ \\text{Si}(k r_c) -\\frac{\\pi}{2}\\right],\n\\end{equation}\nwhere the {\\em sin integral}\\:, $\\text{Si}(z)$, is given by\n\\begin{equation}\n\\text{Si}(z) \\equiv \\int_0^z \\frac{\\sin \\ t}{t} dt\\:.\n\\end{equation}\n\n\\subsection*{The $1/r^3$ potential}\nFor $v(r) = \\frac{1}{r^3}$, $x_k$ is given by\n\\begin{equation}\nx_k^{1/r^3} = \\frac{4\\pi}{\\Omega k} \n\\left[k\\text{Ci}(k r_c) - \\frac{\\sin(k r_c)}{r_c} \\right]\\:,\n\\end{equation}\nwhere the {\\em cosine integral}, $\\text{Ci}(z)$, is given by\n\\begin{equation}\n\\text{Ci}(z) \\equiv -\\int_z^\\infty \\frac{\\cos t}{t} dt\\:.\n\\end{equation}\n\n\\subsection*{The $1/r^4$ potential}\nFor $v(r) = \\frac{1}{r^4}$, $x_k$ is given by\n\\begin{equation}\nx_k^{1/r^4} = -\\frac{4 \\pi}{\\Omega k} \n\\left\\{\n\\frac{k \\cos(k r_c)}{2 r_c} + \\frac{\\sin(k r_c)}{2r_c^2} + \\frac{k^2}{2} \\left[ \\text{Si}(k r_c) - \\frac{\\pi}{2}\\right]\\right\\}\\:.\n\\end{equation}\n\n\n%\\section{Adapting to PIMC}\n%\\subsection{Pair actions}\n%Let us begin by summarizing what we have done so far.  We began with the many-body Hamiltonian given by \n%\\begin{equation}\n%\\mathcal{H} = \\sum_i -\\lambda_i \\nabla_i^2 + V,\n%\\end{equation}\n%where $V$ is the periodic potential given by (\\ref{eq:Vperiodic}), and $\\lambda \\equiv \\frac{\\hbar^2}{2m_i}$. \n%\n%We approximately solved the action of this Hamiltonian by considering\n%the particles pairwise, and solving for the density matrix for the\n%density matrix of each pair exactly using the matrix squaring method.\n%This yields the the {\\em pair action}, defined by\n%\\begin{equation}\n%\\rho^{\\alpha \\beta}(\\vr, \\vr';\\tau) \\equiv \\rho_0(\\vr, \\vr';\\tau)\n%e^{-u^{\\alpha \\beta}(\\vr, \\vr';\\tau)},\n%\\end{equation}\n%where $\\rho_0$ is the {\\em free particle} density matrix for species\n%$\\alpha$ interacting with species $\\beta$.  $\\rho^{\\alpha \\beta}$ is\n%the density matrix for the pair Hamiltonian\n%\\begin{equation}\n%H^{\\alpha\\beta} = -\\lambda^{\\alpha\\beta} \\nabla^2 + v^{\\alpha\\beta}(|\\vr|),\n%\\end{equation}\n%where $\\vr \\equiv \\vr_i - \\vr_j$ and particles $i$ and $j$ are members\n%of species $\\alpha$ and $\\beta$, respectively, and\n%$\\lambda^{\\alpha\\beta}$ is given by\n%\\begin{equation}\n%\\lambda^{\\alpha \\beta} = \\frac{\\hbar^2}{2m_{\\alpha}} +\n%\\frac{\\hbar^2}{2m_\\beta}.\n%\\end{equation}\n%If the potential $v^{\\alpha \\beta}(r)$ is long range, then the action,\n%$u^{\\alpha \\beta}(\\vr, \\vr';\\beta)$, will also be long range.  We\n%note, however, that the action is not a simple function of the scalar\n%$r$, as the potential is.  Experience shows, however, that at large\n%distances, the action is well-approximated by\n%\\begin{eqnarray}\n%u^{\\alpha\\beta}(\\vr, \\vr';\\tau) & \\approx & \n%\\frac{1}{2} \\left[ u^{\\alpha\\beta}(\\vr,\\vr;\\tau) +\n%  u^{\\alpha\\beta}(\\vr',\\vr';\\tau)\\right] \\\\\n%& = & \\frac{1}{2} \\left[ u^{\\alpha\\beta}_\\text{diag}(r,\\tau)+\n%u^{\\alpha\\beta}_\\text{diag}(r',\\tau)\\right]\n%\\end{eqnarray}\n%This is known as the {\\em diagonal approximation}.  Thus, as long as\n%this approximation is valid at half the minimum box dimension, we may\n%break up the diagonal action as we did the potential.  This\n%effectively neglects the off-diagonal parts of the action for\n%particles more than a half-box length apart, but experience has shown\n%that these contributions are usually quite small.  The same\n%analysis follows for the $\\tau$-derivative the the action, which is\n%required to compute the total energy.  Note that PIMC simulation\n%requires the pair action at several values of $\\tau$, so that in\n%practice, we need to do several optimized breakups for each\n%$u_\\text{diag}^{\\alpha\\beta}$ and $\\dot{u}_\\text{diag}^{\\alpha\\beta}$ and a single breakup for\n%each $v^{\\alpha\\beta}$.\n%\n%\\subsection{Beyond the pair approximation: RPA improvements}\n%Consider the limit of a dense gas of charged particles.  We know from\n%solid state theory that collective density fluctuations, known as\n%plasmons, contribute significantly to the energy spectrum of such a system.\n%An approximation to the density matrix determined by considering only\n%pairs of particles will neglect these contributions at finite $\\tau$.\n%As $\\tau$ approaches zero, Trotter still guarantees we will approach\n%the right limit.\n%\n%Nonetheless, it is possible to significantly reduce the finite-$\\tau$\n%timestep error by utilizing a different approximation for the long\n%range part of the action.  We begin by defining our effective,\n%long-range potential.  As noted above, we may perform an optimized\n%breakup on the diagonal action, $u_\\text{diag}^{\\alpha\\beta}(r)$.\n%\\begin{equation}\n%u_\\text{diag}^{\\alpha\\beta}(r) = \\hat{u}^{\\alpha\\beta}_\\text{diag}(r) +\n%\\bar{u}^{\\alpha\\beta}_\\text{diag}(r),\n%\\end{equation}\n%where the $\\hat{u}$ and $\\bar{u}$ refer to the short and long range\n%diagonal actions, respectively, borrowing the notation for short and\n%long vowels.\n%We subtract the long range part form the total pair action in a\n%quasi-primitive approximation by defining\n%\\begin{equation}\n%\\bar{u}^{\\alpha\\beta}_\\text{diag}(r) \\equiv \\tau \\bar{v}^{\\alpha \\beta}(r).\n%\\end{equation}\n%Let $\\bar{v}^{\\alpha \\beta}_k$ represent the Fourier transform the the\n%effective potential, $\\bar{v}^{\\alpha\\beta}(r)$.  Finally, let its\n%short-range counterpart be defined by \n%\\begin{equation}\n%\\hat{v}^{\\alpha \\beta}_k \\equiv v^{\\alpha\\beta}_k - \\bar{v}^{\\alpha\\beta}_k\n%\\end{equation}\n%\n%Now, we wish to reintroduce a new long range action, which we will\n%calculate in $k$-space within the {\\em Random Phase Approximation\n%  (RPA)}.   We begin with the Bloch equation,\n%\\begin{equation}\n%\\dot{\\rho} = -\\mathcal{H} \\rho,\n%\\end{equation}\n%where the dot refers to differentiation w.r.t. $\\tau$.  The\n%Hamiltonian is given by\n%\\begin{equation}\n%\\mathcal{H} = \\left[\\sum_\\alpha \\sum_{i\\in \\alpha} -\\lambda_\\alpha\n%\\nabla_i^2\\right] + \\hat{V} + \\bar{V},\n%\\end{equation}\n%where $\\hat{V}$ and $\\bar{V}$ are the total short and long range\n%periodic potentials, respectively.\n%Let us now make the partitioning that\n%\\begin{equation}\n%\\rho(\\vR, \\vR';\\tau) = \\rho_0(\\vR, \\vR';\\tau) e^{-\\hat{U}(\\vR,\n%  \\vR';\\tau)} e^{-\\bar{U}(\\vR, \\vR';\\tau)},\n%\\end{equation}\n%We assume that $\\rho_s \\equiv \\rho_0 e^{-\\hat{U}}$ satisfies the Bloch\n%equation for the short-range Hamiltonian,\n%\\begin{equation}\n%\\mathcal{H}_s = \\left[\\sum_\\alpha \\sum_{i\\in \\alpha} -\\lambda_\\alpha\n%\\nabla_i^2\\right] + \\hat{V}.\n%\\end{equation}\n%In fact, this is only strictly true in the limit that $\\tau=0$, but\n%this relation will suffice for our present analysis.\n%\n%\n%Recall that $\\nabla^2(ab) = a\\nabla^2 b + b\\nabla^2a +2(\\nabla a)\n%\\cdot (\\nabla b)$.  Thus, we have for our Bloch equation,\n%\\begin{eqnarray}\n%-\\left [\\dot{\\rho_s} -\\rho_s\\dot{\\bar{U}}\\right] e^{-\\bar{U}} & = &\n%\\sum_{\\alpha,\\  i\\in\\alpha} -\\lambda_\\alpha\n%\\left[\\rho_s \\nabla^2_i e^{-\\bar{U}} + e^{-\\bar{U}} \\nabla^2_i \\rho_s\n%  + 2(\\nabla_i \\rho_s)\\cdot (\\nabla_i e^{-\\bar{U}}) \n%\\right] \\nonumber \\\\ & & + (\\hat{V} + \\bar{V}) \\rho_s e^{-\\bar{U}}.\n%\\end{eqnarray} \n%Subtracting the Bloch equation for the short range part,\n%we are left with\n%\\begin{equation}\n%\\left[\\dot{\\bar{U}}-\\bar{V}\\right] \\rho_s e^{-\\bar{U}}  = \n%\\sum_{\\alpha,\\  i\\in\\alpha} -\\lambda_\\alpha\n%\\left[\\rho_s \\nabla^2_i e^{-\\bar{U}}\n%  + 2(\\nabla_i \\rho_s)\\cdot (\\nabla_i e^{-\\bar{U}}) \n%\\right].\n%\\end{equation} \n%Recall that\n%\\begin{eqnarray}\n%\\nabla e^{-\\bar{U}} & = & -\\nabla\\bar{U}e^{-\\bar{U}} \\\\\n%\\nabla \\rho_0 & = & 0 \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\\n%\\ \\ \\ \\ \\ \\ \\ \\ \\ \n%\\text{ (for $\\vR = \\vR'$)} \\\\\n%\\nabla \\rho_s & = & -\\rho_s \\nabla \\hat{U} \\\\\n%\\nabla^2 e^{-\\bar{U}} & = & \n%\\left[(\\nabla \\bar{U})^2 - \\nabla^2 \\bar{U}\\right] e^{-\\bar{U}} \n%\\end{eqnarray} \n%We now attempt to solve the Bloch equation under the restriction that\n%$\\vR = \\vR'$, i.e. along the diagonal of the density matrix.  Hence\n%let us define\n%\\begin{eqnarray} \n%\\bar{U}(\\vR, \\vR';\\tau) & \\equiv &\n%  \\frac{1}{2}\\left[\\bar{\\mathcal{U}}(\\vR;\\tau) +\n%  \\bar{\\mathcal{U}}(\\vR';\\tau) \\right] \\\\ \n% \\hat{U}(\\vR,\\vR';\\tau) & \\equiv & \n%  \\frac{1}{2} \\left[\\hat{\\mathcal{U}}(\\vR;\\tau) +\n%  \\hat{\\mathcal{U}}(\\vR';\\tau) \\right] \n%\\end{eqnarray}\n%as the long and short range diagonal actions written as\n%functions of only one spatial argument.  Then we have, along the\n%diagonal,\n%\\begin{eqnarray}\n%\\nabla U   & = & \\frac{1}{2} \\nabla\\mathcal{U} \\\\\n%\\nabla^2 U & = & \\frac{1}{2} \\nabla^2\\mathcal{U}.\n%\\end{eqnarray}\n%Substituting back into out Bloch equation,\n%\\begin{equation}\n%\\dot{\\bar{\\mathcal{U}}} = \\sum_{\\alpha, \\ i\\in \\alpha} -\\lambda_\\alpha\n%\\left\\{ \\frac{1}{4} (\\nabla_i \\bar{\\mathcal{U}})^2 - \n%\\frac{1}{2}\\nabla_i^2 \\bar{\\mathcal{U}} + \\frac{1}{2} (\\nabla_i\\hat{\\mathcal{U}})\n%  \\cdot (\\nabla_i \\bar{\\mathcal{U}}) \\right\\} +\\bar{V}\n%\\end{equation}\n%\n%We recall that the long range potential, $\\bar{V}$, may be written as\n%\\begin{equation}\n%\\bar{V} = \\sum_\\vk \\sum_{\\alpha} \\left[ \n%\\frac{1}{2} \\left| \\rho^\\alpha_\\vk\\right|^2 \\bar{v}^{\\alpha\n%  \\alpha}_k + \n%\\sum_{\\beta < \\alpha} \\mathcal{R}e \\left( \\rho^{\\alpha}_\\vk\n%  \\rho^\\beta_{-\\vk} \\bar{v}^{\\alpha\\beta}_k \\right)\n%\\right] \n%\\end{equation}\n%When we wrote this expression above, we did so to optimize the speed\n%of computation.  For the following analysis, we will find it more\n%convenient to write\n%\\begin{equation}\n%\\bar{V} = \\frac{1}{2} \\sum_\\vk \\sum_{\\alpha, \\beta} \\rho_\\vk^\\alpha\n%\\rho_{-\\vk}^\\beta v^{\\alpha \\beta}_k.\n%\\end{equation}\n%The sum is guaranteed to be real since for every $\\vk$, we have a\n%corresponding $-\\vk$ in the sum.  Hence we need not be concerned by\n%taking the real part. We may similarly write $\\bar{\\mathcal{U}}$ and $\\hat{\\mathcal{U}}$ in\n%terms of $\\bar{u}_k^{\\alpha\\beta}$ and $\\hat{u}_k^{\\alpha\\beta}$.\n%\n%\n%We now proceed to calculate gradients and laplacians.\n%Recall that \n%\\begin{equation}\n%\\rho_\\vk^\\alpha = \\sum_{i\\in\\alpha} e^{i\\vk \\cdot \\vr_i}\n%\\end{equation}\n%\\begin{eqnarray}\n%\\nabla_i \\mathcal{U} & = & \\frac{1}{2}\\sum_\\vk \\left[ i\\vk e^{i\\vk \\cdot \\vr_i} \\sum_\\alpha\n%\\rho_{-\\vk}^\\alpha u^{\\alpha \\beta}_k + \\text{c.c.} \\right] \\\\\n%& = & \\frac{1}{2} \\sum_\\vk 2\\mathcal{R}e \\left[i\\vk e^{i\\vk \\cdot \\vr_i} \\sum_\\alpha\n%\\rho_{-\\vk}^\\alpha u^{\\alpha \\beta}_k\\right] \\\\ \n%& = & \\mathcal{R}e \\left[ \\sum_\\vk i\\vk e^{i\\vk \\cdot \\vr_i} \\sum_\\alpha\n%\\rho_{-\\vk}^\\alpha u^{\\alpha \\beta}_k \\right] \\\\\n%& = & \\sum_\\vk i\\vk e^{i\\vk \\cdot \\vr_i} \\sum_\\alpha\n%\\rho_{-\\vk}^\\alpha u^{\\alpha \\beta}_k.\n%\\end{eqnarray}\n%In the last line, we have again recognized that for every $\\vk$\n%there is a corresponding $-\\vk$, so that the sum is purely real.\n%\n%Next, we compute the Laplacian w.r.t. the $i^{\\text{th}}$ particle.\n%\\begin{eqnarray}\n%\\nabla^2_i \\mathcal{U} & = & \\nabla_i \\cdot \\nabla_i \\mathcal{U} \\\\\n%& = & \\nabla_i \\cdot \\sum_\\vk i\\vk e^{i\\vk \\cdot \\vr_i} \\sum_\\alpha\n%\\rho_{-\\vk}^\\alpha u^{\\alpha \\sigma_i}_k \\\\\n%& = & \\sum_\\vk i\\vk \\cdot \\nabla_i \\left[ e^{i\\vk \\cdot \\vr_i}\n%  \\sum_\\alpha \\rho_{-\\vk}^\\alpha u^{\\alpha\\sigma_i}_k \\right] \\\\\n%& = & \\sum_{\\vk} k^2 \\left[ u^{\\sigma_i \\sigma_i}_k - e^{i\\vk\\cdot\\vr_i}\\sum_\\alpha \\rho_{-\\vk}\n%u_k^{\\alpha \\sigma_i}\\right],\n%\\end{eqnarray}\n%where $\\sigma_i$ is the species of the $i^{\\text{th}}$ particle.  Now,\n%let us sum over all particles,\n%\\begin{eqnarray}\n%\\sum_i \\lambda_i \\nabla^2_i \\mathcal{U} & = & \\sum_\\vk k^2 \\left[\\sum_\\beta N_\\beta u_k^{\\beta\n%  \\beta} - \\rho_{\\vk}^\\beta \\sum_\\alpha \\rho_{-\\vk} u_k^{\\alpha \\beta}\n%  \\right] \\\\\n%& = & \\sum_{\\vk} k^2 \\sum_{\\alpha, \\beta}\n%  \\lambda_\\beta \\left[N^{\\alpha}\\delta_{\\alpha,\\beta} -\n%  \\rho_{-\\vk}^{\\alpha}\\rho_\\vk^\\beta \\right]u_k^{\\alpha \\beta} \n%%\\\\\n%%& = & \\sum_{\\vk} k^2 \\sum_{\\alpha, \\beta}\n%%  \\left(\\frac{\\lambda_\\alpha +\\lambda_\\beta}{2} \\right) \\left[N^{\\alpha}\\delta_{\\alpha,\\beta} -\n%%  \\rho_{-\\vk}^{\\alpha}\\rho_\\vk^\\beta \\right]u_k^{\\alpha \\beta}.\n%\\end{eqnarray}\n%%In the last step, we have added half the sum with $\\alpha$ and $\\beta$\n%%swapped so as to symmetrize the summation.\n%Now, let us consider the cross term,\n%\\begin{eqnarray}\n%(\\nabla_i \\hat{\\mathcal{U}}) \\cdot ( \\nabla_i \\bar{\\mathcal{U}} ) \n%& = & \\left[\\sum_\\vk i\\vk e^{i\\vk\\cdot \\vr_i} \\sum_\\alpha\n%  \\rho_{-\\vk}^\\alpha \\hat{u}^{\\sigma_i \\alpha}_k \\right] \\cdot\n%\\left[\\sum_\\vq i\\vq e^{i\\vq\\cdot \\vr_i} \\sum_\\beta\n%  \\rho_{-\\vk}^\\beta \\bar{u}^{\\sigma_i \\beta}_k \\right] \\nonumber \\\\\n%& = & -\\sum_{\\vk,\\vq} \\vk \\cdot \\vq e^{i(\\vk + \\vq)\\cdot \\vr_i}\n%\\sum_{\\alpha, \\beta} \\rho_{-\\vk}^\\alpha \\rho_{-\\vq}^\\beta \n%\\hat{u}^{\\alpha \\sigma_i}_k \\bar{u}^{\\beta \\sigma_i}_k\n%\\end{eqnarray}\n%Again, summing over all particles,\n%\\begin{equation}\n%\\sum_i (\\nabla_i \\hat{\\mathcal{U}}) \\cdot ( \\nabla_i \\bar{\\mathcal{U}} ) =\n%-\\sum_{\\vk, \\vq} \\vk \\cdot \\vq \\sum_{\\alpha, \\beta, \\gamma}\n%\\rho_{\\vk + \\vq}^\\gamma \\rho_{-\\vk}^{\\alpha} \\rho_{-\\vq}^\\beta\n%\\hat{u}^{\\alpha \\gamma}_k \\bar{u}^{\\beta \\gamma}_k\n%\\end{equation}\n%Similarly,\n%\\begin{equation}\n%\\sum_i (\\nabla_i \\bar{\\mathcal{U}})^2 = -\\sum_{\\vk, \\vq} \\vk \\cdot \\vq \n%\\sum_{\\alpha, \\beta, \\gamma} \\rho^\\gamma_{\\vk+\\vq} \\rho^\\alpha_{-\\vk}\n%\\rho^\\gamma_{-\\vq} \\bar{u}^{\\alpha \\gamma}_k \\bar{u}^{\\beta \\gamma}_k\n%\\end{equation}\n%\n%The {\\em Random Phase Approximation} (RPA) amounts to the assumption\n%that $\\rho^\\gamma_{\\vk + \\vq} \\approx N_\\gamma \\delta_{\\vk + \\vq}$. \n%Then we have,\n%\\begin{eqnarray}\n%\\sum_i (\\nabla_i \\hat{\\mathcal{U}}) \\cdot ( \\nabla_i \\bar{\\mathcal{U}}\n%) & \\overset{\\text{RPA}}{=} &\n%\\sum_\\vk k^2 \\sum_{\\alpha, \\beta, \\gamma} N_\\gamma \\rho^\\alpha_{-\\vk}\n%\\rho^\\beta_\\vk \\hat{u}^{\\alpha \\gamma}_k \\bar{u}^{\\beta \\gamma}_k \\\\\n%\\sum_i (\\nabla_i \\bar{\\mathcal{U}})^2 & \\overset{\\text{RPA}}{=} &\n%\\sum_\\vk k^2 \\sum_{\\alpha, \\beta, \\gamma} N_\\gamma\n%\\rho^{\\alpha}_{-\\vk} \\rho^\\beta_\\vk \\bar{u}_k^{\\alpha \\gamma}\n%\\bar{u}_k^{\\beta \\gamma}\n%\\end{eqnarray}\n%We now return to the Bloch equation\n%\\begin{equation}\n%\\begin{split}\n%\\sum_\\vk \\sum_{\\alpha,\\beta} & \\left\\{ \n%\\frac{1}{2} \\rho_\\vk^\\alpha\n%\\rho_{-\\vk}^\\beta \\left(\\dot{\\bar{u}}_k - \\bar{v}_k^{\\alpha \\beta} \\right)\n%+\\frac{1}{2} \\lambda_\\alpha k^2 \\bar{u}_k^{\\alpha \\beta}\n%\\left(\\rho_{-\\vk}^\\alpha \n%  \\rho_\\vk^\\beta - N_\\beta \\delta_{\\alpha,\\beta} \\right) \n%\\right. \\\\\n%& \\left. -\\sum_\\gamma k^2 N_\\gamma \\lambda_\\gamma \\rho_{-\\vk}^\\alpha\n%  \\rho_\\vk^\\beta \\left[ \n%\\frac{1}{4} \\hat{u}^{\\alpha \\gamma}_k \\bar{u}^{\\beta\\gamma}_k +\n%\\frac{1}{2} \\bar{u}^{\\alpha \\gamma}_k \\bar{u}^{\\beta \\gamma}\n%\\right]\\right\\} = 0\n%\\end{split}\n%\\end{equation}\n%Next, we symmetrize this equation w.r.t $\\alpha$ and $\\beta$.\n%\\begin{equation}\n%\\begin{split}\n%\\sum_{\\vk, \\alpha, \\beta} & \\left\\{ \\left( \\rho^\\alpha_{\\vk} \\rho^\\beta_{-\\vk} \n%+ \\rho^\\alpha_{-\\vk} \\rho^\\beta_{\\vk} \\right) \\left[\n%\\dot{\\bar{u}}_k^{\\alpha \\beta} - \\bar{v}_k^{\\alpha \\beta}\n% +k^2 \\left(\\frac{\\lambda_\\alpha+\\lambda_\\beta}{2}\\right) \n%\\bar{u}_k^{\\alpha \\beta} \\rule{0cm}{0.6cm} \\right.\\right. \\\\\n%& \\ \\ \\left.\\left.+\\sum_\\gamma \\frac{k^2}{2} N^\\gamma \\left(\n%\\bar{u}_k^{\\alpha \\gamma} \\bar{u}_k^{\\beta \\gamma} +\n%\\hat{u}_k^{\\alpha \\gamma} \\bar{u}_k^{\\beta \\gamma} +\n%\\bar{u}_k^{\\alpha \\gamma} \\hat{u}_k^{\\beta \\gamma}  \\right)\n%\\right]\n%- k^2 N^\\alpha \\delta_{\\alpha \\beta}\n%\\right\\} = 0\n%\\end{split}\n%\\end{equation}\n%We require that this expression hold independent of the positions of\n%the particles, i.e. independent of the values of $\\rho^\\alpha_{\\vk}$ and\n%$\\rho^\\beta_{\\vk}$.  Thus, the equations separate for each value of\n%$\\vk$, $\\alpha$, and $\\beta$.  For $\\vk \\neq 0$,\n%\\begin{equation}\n%\\dot{\\bar{u}}_k^{\\alpha \\beta} = \\bar{v}_k^{\\alpha \\beta} \n%- k^2 \\left(\\frac{\\lambda_\\alpha+\\lambda_\\beta}{2}\\right)\n%\\bar{u}_k^{\\alpha\\beta} -\\frac{k^2}{2} \\sum_\\gamma N_\\gamma\n%\\left(\n%\\bar{u}_k^{\\alpha \\gamma} \\bar{u}_k^{\\beta \\gamma} +\n%\\hat{u}_k^{\\alpha \\gamma} \\bar{u}_k^{\\beta \\gamma} +\n%\\bar{u}_k^{\\alpha \\gamma} \\hat{u}_k^{\\beta \\gamma}\n%\\right)\n%\\end{equation}\n%Next, we need an equation for the time propagation of\n%$\\hat{u}_k^{\\alpha \\beta}$.  Above, we assumed that $\\hat{U}$ was the\n%solution to the short-range problem.  Our Bloch equation for\n%$\\hat{mathcal{U}}$ is then given by\n%\\begin{equation}\n%\\dot{\\hat{\\mathcal{U}}} = \\sum_i -\\lambda_i\n%\\left\\{ \\frac{1}{4} (\\nabla_i \\hat{\\mathcal{U}} \n%-\\frac{1}{2} \\nabla_i^2 \\hat{\\mathcal{U}} \\right\\} + \\hat{V}\n%\\end{equation}\n%Following the RPA procedure above, we arrive at the following\n%equations for $\\hat{u}_k^{\\alpha\\beta}$.\n%\\begin{equation}\n%\\dot{\\hat{u}}^{\\alpha \\beta}_k = \\hat{v}^{\\alpha \\beta}_k\n%-k^2 \\left( \\frac{\\lambda_\\alpha + \\lambda_\\beta}{2} \\right)\n%\\hat{u}^{\\alpha \\beta}_k - \\frac{k^2}{2} \\sum_\\gamma N_\\gamma\n%\\hat{u}^{\\alpha \\gamma}_k \\hat{u}^{\\beta \\gamma}_k.\n%\\end{equation}\n%Hence, for each value of $k$, we have a coupled set of differential\n%equations we must solve.  We note that while the equations for\n%$\\bar{u}$ couple to $\\hat{u}$, those for $\\hat{u}$ do not couple to\n%$\\bar{u}$.\n%%% \\begin{equation}\n%%% \\begin{split}\n%%% \\sum_\\vk \\sum_{\\alpha,\\beta} \n%%%  & \\left\\{\n%%% \\rho_{-\\vk}^\\alpha \\rho_\\vk^\\beta \n%%% \\left[\n%%% \\dot{\\bar{u}}^{\\alpha \\beta}_k + k^2 \\sum_\\gamma \\lambda_\\gamma\n%%% N_\\gamma \n%%% \\left(\\frac{\\bar{u}^{\\alpha \\gamma}_k \\bar{u}^{\\beta \\gamma}_k}{4} -\n%%% \\frac{\\hat{u}^{\\alpha \\gamma}_k \\bar{u}^{\\beta \\gamma}_k}{2}\n%%% \\right) \n%%% \\frac{k^2}{2} \\lambda_\\beta \\bar{u}_k^{\\alpha \\beta} +\n%%% \\bar{v}_k^{\\alpha \\beta}\n%%% \\right] \\right.\\\\\n%%%  & \\left. \\rule{0pt}{0.6cm}\n%%% + \\frac{k^2}{2}\\lambda_\\beta N_\\beta \\delta_{\\alpha,\\beta}\n%%% \\bar{u}_k^{\\alpha \\beta}\n%%% \\right\\} = 0\n%%% \\end{split}\n%%% \\end{equation}\n%\n%\n%%% While this\n%%% is correct in the limit that the timestep, $\\tau$, goes to zero, it\n%%% may incur a substantial error for finite $\\tau$.  In this section, we\n%%% describe a method to reduce the timestep error of the long range part\n%%% of the action by using the Bloch equation combined with the Random\n%%% Phase Approximation (RPA).  \n%\n%%% The Bloch equation may be written,\n%%% \\begin{equation}\n%%% \\dot{\\rho} = -\\mathcal{H} \\rho,\n%%% \\end{equation}\n%%% where the dot indicates differentiation with respect to $\\tau$.  Now,\n%%% we define\n%%% \\begin{equation}\n%%% \\rho = \\rho_0 e^{-U_s}e^{-U_l}.\n%%% \\end{equation}\n%%% \\begin{equation}\n%%% \\mathcal{H} = \\left[ -\\lambda \\sum_i \\nabla_i^2 \\right] + V_s + V_l\n%%% \\end{equation}\n%%% The Bloch equation gives us \n\n\n\n\n%\n\\section{Feature: Optimized long-range breakup (Ewald) 2}\n\n% Written by Simone Chiesa for the FITPN code/tool (Ceperley)\n% Originally titled ``Notes on fitnp''\n\n\\newcommand{\\rv}{\\mathbf{r}}\n\\newcommand{\\kv}{\\mathbf{k}}\n\\newcommand{\\Rv}{\\mathbf{R}}\n\\newcommand{\\Lv}{\\mathbf{L}}\n\\newcommand{\\Rc}{\\mathcal{R}}\n\\newcommand{\\tV}{\\widetilde{V}}\n\\newcommand{\\tW}{\\widetilde{W}}\n\\newcommand{\\tc}{\\widetilde{c}}\n\\newcommand{\\tY}{\\widetilde{Y}}\n\\newcommand{\\Nk}{N_{\\text{knot}}}\n\\newcommand{\\wk}{w_{\\text{knot}}}\n\nGiven a lattice of vectors $\\Lv$, its associated reciprocal\nlattice of vectors $\\kv$ and a function $\\psi(\\rv)$ periodic\non the lattice we define its Fourier transform $\\widetilde{\\psi}(\\kv)$ as\n\\begin{equation}\n\\widetilde{\\psi}(\\kv)=\\frac{1}{\\Omega}\\int_\\Omega d\\rv \\psi(\\rv) e^{-i\\kv\\rv}\\:,\n\\end{equation}\nwhere we indicated both the cell domain and the cell volume by $\\Omega$. \n$\\psi(\\rv)$ can then be expressed as\n\\begin{equation}\n\\psi(\\rv)=\\sum_{\\kv} \\widetilde{\\psi}(\\kv)e^{i\\kv\\rv}\\:.\n\\end{equation}\nThe potential generated by charges sitting on the lattice positions\nat a particular point $\\rv$ inside the cell is given by\n\\begin{equation}\nV(\\rv)=\\sum_{\\Lv}v(|\\rv+\\Lv|)\\:,\n\\end{equation}\nand its Fourier transform can be explicitly written as a function of $V$ or $v$\n\\begin{equation}\n\\widetilde{V}(\\kv)=\\frac{1}{\\Omega}\\int_\\Omega d\\rv V(\\rv) e^{-i\\kv\\rv}=\n\\frac{1}{\\Omega}\\int_{\\mathbb{R}^3} d\\rv v(\\rv) e^{-i\\kv\\rv}\\:,\n\\end{equation}\nwhere $\\mathbb{R}^3$ denotes the whole 3D space.\nWe now want to find the best (``best'' to be defined later) approximate \npotential of the form\n\\begin{equation}\nV_a(\\rv)=\\sum_{k\\le k_c} \\widetilde{Y}(k) e^{i\\kv\\rv} + W(r)\\:,\n\\end{equation}\nwhere $W(r)$ has been chosen to go smoothly to $0$ when $r=r_c$, being\n$r_c$ lower or equal to the Wigner-Seitz radius of the cell. Note also\nthe cutoff $k_c$ on the momentum summation.\n\nThe best form of $\\widetilde{Y}(k)$ and $W(r)$ is given by minimizing\n\\begin{equation}\n  \\chi^2=\\frac{1}{\\Omega}\\int d\\rv \\left(V(\\rv)-W(\\rv)-\n  \\sum_{k\\le k_c}\\widetilde{Y}(k)e^{i\\kv\\rv}\\right)^2\n  \\label{chi2r}\\:,\n\\end{equation}\nor the reciprocal space equivalent\n\\begin{equation}\n  \\chi^2=\\sum_{k\\le k_c}(\\tV(k)-\\tW(k)-\\tY(k))^2+\\sum_{k>k_c}(\\tV(k)-\\tW(k))^2\n  \\label{chi2k}\\:.\n\\end{equation}\nEquation~\\ref{chi2k} follows from Equation~\\ref{chi2r} and the unitarity\n(norm conservation) of the Fourier transform.\n\nThis last condition is minimized by\n\\begin{equation}\n\\tY(k)=\\tV(k)-\\tW(k)\\qquad \\min_{\\tW(k)}\\sum_{k>k_c}(\\tV(k)-\\tW(k))^2\n\\label{mincond}\\:.\n\\end{equation}\nWe now use a set of basis function $c_i(r)$ vanishing smoothly at $r_c$\nto expand $W(r)$; that is,\n\\begin{equation}\nW(r)=\\sum_i t_i c_i(r)\\qquad\\text{or}\\qquad \\tW(k)=\\sum_i t_i \\tc_i(k)\\:.\n\\end{equation}\nInserting the reciprocal space expansion of $\\tW$ in the second condition of\nEquation~\\ref{mincond} and minimizing with respect to $t_i$ leads immediately\nto the linear system $\\mathbf{A}\\mathbf{t}=\\mathbf{b}$ where\n%\\begin{center}\n%\\vskip 3mm\n\\begin{eqnarray}\nA_{ij}=\\sum_{k>k_c}\\tc_i(k)\\tc_j(k)\\qquad b_j=\\sum_{k>k_c} V(k) \\tc_j(k)\n\\label{matrix_elements}\\:.\n\\end{eqnarray}\n%\\end{center}\n%\\vskip 3mm\n\n\\subsection{Basis functions}\nThe basis functions are splines. We define a uniform grid \nwith $\\Nk$ uniformly spaced knots at position $r_i=i\\frac{r_c}{\\Nk}$, \nwhere $i\\in[0,\\Nk-1]$. On each knot we center $m+1$ piecewise polynomials\n$c_{i\\alpha}(r)$ with $\\alpha\\in[0,m]$, defined as\n%\\vskip 3mm\n%\\begin{center}\n\\begin{eqnarray}\nc_{i\\alpha}(r)=\\begin{cases}\n\\Delta^\\alpha \\sum_{n=0}^\\mathcal{N} S_{\\alpha n}(\\frac{r-r_i}{\\Delta})^n & r_i<r\\le r_{i+1} \\\\\n\\Delta^{-\\alpha} \\sum_{n=0}^\\mathcal{N} S_{\\alpha n}(\\frac{r_i-r}{\\Delta})^n & r_{i-1}<r\\le r_i \\\\\n0 & |r-r_i| > \\Delta\n\\end{cases}\n\\label{basisdef}\\:.\n\\end{eqnarray}\n%\\end{center}\n%\\vskip 3mm\nThese functions and their derivatives are, by construction, continuous and odd (even)\n(with respect to $r-r_i\\rightarrow r_i-r$) when $\\alpha$ is odd (even).\nWe further ask them to satisfy\n\\begin{eqnarray}\n\\left.\\frac{d^\\beta}{dr^\\beta} c_{i\\alpha}(r)\\right|_{r=r_i}=\n\\delta_{\\alpha\\beta} \\quad \\beta\\in[0,m]\\:,\\\\\n\\left.\\frac{d^{\\beta}}{dr^{\\beta}} c_{i\\alpha}(r)\\right|_{r=r_{i+1}}=0\\quad \\beta\\in[0,m]\n\\label{constr}\\:.\n\\end{eqnarray}\n(The parity of the functions guarantees that the second constraint is satisfied\nat $r_{i-1}$ as well). These constraints have a simple interpretation: the basis functions\nand their first $m$ derivatives are $0$ on the boundary of the subinterval where they\nare defined; the only function to have a nonzero $\\beta$-th derivative in $r_i$ is $c_{i\\beta}$.\nThese $2(m+1)$ constraints therefore impose $\\mathcal{N}=2m+1$. \nInserting the definitions of Equation~\\ref{basisdef} in the constraints of Equation~\\ref{constr}\nleads to the set of $2(m+1)$ linear equation that fixes the value of $S_{\\alpha n}$: \n\\begin{eqnarray}\n\\Delta^{\\alpha-\\beta} S_{\\alpha\\beta} \\beta!=\\delta_{\\alpha\\beta}\n\\label{Smatrix1}\\\\\n\\Delta^{\\alpha-\\beta}\\sum_{n=\\beta}^{2m+1} S_{\\alpha n} \\frac{n!}{(n-\\beta)!}=0\\:.\n\\end{eqnarray}\nWe can further simplify inserting the first of these equations into the second and write\nthe linear system as\n\\begin{equation}\n\\sum_{n=m+1}^{2m+1} S_{\\alpha n} \\frac{n!}{(n-\\beta)!}=\\begin{cases}\n-\\frac{1}{(\\alpha-\\beta)!}& \\alpha\\ge \\beta \\\\\n0 & \\alpha < \\beta\n\\end{cases}\n\\label{Smatrix2}\\:.\n\\end{equation}\n\n\\subsection{Fourier components of the basis functions in 3D}\n\\subsubsection*{$k\\ne 0$, non-Coulomb case}\nWe now need to evaluate the Fourier transform $\\tc_{i\\alpha}(k)$. Let us start\nby writing the definition\n\\begin{equation}\n\\tc_{i\\alpha}(k)=\\frac{1}{\\omega}\\int_\\Omega d\\rv  e^{-i\\kv\\rv} c_{i\\alpha}(r)\\:.\n\\end{equation}\nBecause $c_{i\\alpha}$ is different from zero only inside the spherical crown\ndefined by $r_{i-1}<r<r_i$, we can conveniently compute the integral in spherical\ncoordinates as\n%\\begin{center}\n\\begin{eqnarray}\n\\tc_{i\\alpha}(k)=\\Delta^\\alpha\\sum_{n=0}^\\mathcal{N} S_{\\alpha n} \\left[\nD_{in}^+(k) +\\wk(-1)^{\\alpha+n}D_{in}^-(k)\\right]\\:,\n\\label{fourier_transform}\n\\end{eqnarray}\n%\\end{center}\nwhere we used the definition $\\wk=1-\\delta_{i0}$ and\n\\begin{equation}\nD_{in}^\\pm(k)=\\pm\\frac{4\\pi}{k\\Omega}\\Im\\left[\\int_{r_i}^{r_i\\pm\\Delta}\ndr\\left(\\frac{r-r_i}{\\Delta}\\right)^n r e^{ikr}\\right]\\:,\n\\label{D+-}\n\\end{equation}\nobtained by integrating the angular part of the Fourier transform.\nUsing the identity\n\\begin{equation}\n\\left(\\frac{r-r_i}{\\Delta}\\right)^n r=\\Delta\\left(\\frac{r-r_i}{\\Delta}\\right)^{n+1}+\\left(\\frac{r-r_i}{\\Delta}\\right)^n r_i\n\\end{equation}\nand the definition\n\\begin{equation}\nE_{in}^\\pm(k)=\\int_{r_i}^{r_i\\pm\\Delta}\ndr\\left(\\frac{r-r_i}{\\Delta}\\right)^n e^{ikr}\\:,\n\\end{equation}\nwe rewrite Equation~\\ref{D+-} as\n%\\begin{center}\n%\\vskip 3mm\n\\begin{eqnarray}\nD_{in}^\\pm(k)=\\pm\\frac{4\\pi}{k\\Omega}\\Im\\left[\\Delta E_{i(n+1)}^\\pm(k)+\nr_i E_{in}^\\pm(k)\\right]\\:.\n\\label{noncoulD+-}\n\\end{eqnarray}\n%\\end{center}\n%\\vskip 3mm\n\nFinally, using integration by part, we can define $E^\\pm_{in}$ recursively as\n%\\begin{center}\n%\\vskip 3mm\n\\begin{eqnarray}\nE^\\pm_{in}(k)=\\frac{1}{ik}\\left[(\\pm)^ne^{ik(r_i\\pm\\Delta)}-\\frac{n}{\\Delta}\nE^\\pm_{i(n-1)}(k)\\right]\\:.\n\\label{nthEpm}\n\\end{eqnarray}\n%\\end{center}\n%\\vskip 3mm\n\\noindent\nStarting from the $n=0$ term,\n%\\vskip 3mm\n%\\begin{center}\n\\begin{eqnarray}\nE^\\pm_{i0}(k)=\\frac{1}{ik}e^{ikr_i}\\left(e^{\\pm ik\\Delta}-1\\right)\\:.\n\\label{0thEpm}\n\\end{eqnarray}\n%\\end{center}\n%\\vskip 3mm\n\\subsubsection{$k\\ne 0$, Coulomb case}\nTo efficiently treat the Coulomb divergence at the origin, it is convenient to use\na basis set $c_{i\\alpha}^{\\text{coul}}$ of the form \n\\begin{equation}\nc_{i\\alpha}^{\\text{coul}}=\\frac{c_{i\\alpha}}{r}\\:.\n\\end{equation}\nAn equation identical to Equation~\\ref{D+-} holds but with the modified definition\n\\begin{equation}\nD_{in}^\\pm(k)=\\pm\\frac{4\\pi}{k\\Omega}\\Im\\left[\\int_{r_i}^{r_i\\pm\\Delta}\ndr\\left(\\frac{r-r_i}{\\Delta}\\right)^n e^{ikr}\\right]\\:,\n\\end{equation}\nwhich can be simply expressed using $E^\\pm_{in}(k)$ as\n%\\vskip 3mm\n%\\begin{center}\n\\begin{eqnarray}\nD_{in}^\\pm(k)=\\pm\\frac{4\\pi}{k\\Omega}\\Im\\left[E_{in}^\\pm(k)\\right]\\:.\n\\label{coulD+-}\n\\end{eqnarray}\n%\\end{center}\n%\\vskip 3mm\n\\subsubsection{$k=0$ Coulomb and non-Coulomb case}\nThe definitions of $D_{in}(k)$ given so far are clearly incompatible \nwith the choice $k=0$ (they involve division by $k$). For the non-Coulomb\ncase, the starting definition is\n\\begin{equation}\nD^\\pm_{in}(0)=\\pm\\frac{4\\pi}{\\Omega}\\int_{r_i}^{r_i\\pm\\Delta}r^2\n\\left(\\frac{r-r_i}{\\Delta}\\right)^ndr\\:.\n\\end{equation}\nUsing the definition $I_n^\\pm=(\\pm)^{n+1}\\Delta/(n+1)$, we can express this\nas\n%\\begin{center}\n%\\vskip 3mm\n\\begin{eqnarray}\nD^\\pm_{in}(0)=\\pm\\frac{4\\pi}{\\Omega}\\left[\\Delta^2 I_{n+2}^\\pm\n+2r_i\\Delta I_{n+1}^\\pm+2r_i^2I_n^\\pm\\right]\\:.\n\\label{noncoul_k=0D+-}\n\\end{eqnarray}\n%\\end{center}\n%\\vskip 3mm\nFor the Coulomb case, we get\n%\\vskip 3mm\n%\\begin{center}\n\\begin{eqnarray}\nD^\\pm_{in}(0)=\\pm\\frac{4\\pi}{\\Omega}\\left(\n\\Delta I^\\pm_{n+1} + r_i I^\\pm_n\\right)\\:.\n\\label{coul_k=0D+-}\n\\end{eqnarray}\n%\\end{center}\n%\\vskip 3mm\n\\subsection{Fourier components of the basis functions in 2D}\nEquation~\\ref{fourier_transform} still holds provided we define  \n\\begin{equation}\nD^\\pm_{in}(k)=\\pm\\frac{2\\pi}{\\Omega \\Delta^n} \\sum_{j=0}^n \\binom{n}{j}\n(-r_i)^{n-j}\\int_{r_i}^{r_i\\pm \\Delta}\\negthickspace \\negthickspace \n\\negthickspace \\negthickspace \\negthickspace \\negthickspace \\negthickspace \ndr r^{j+1-C} J_0(kr)\\:,\n\\label{2DD+-}\n\\end{equation}\nwhere $C=1(=0)$ for the Coulomb(non-Coulomb) case.\nEquation~\\ref{2DD+-} is obtained using the integral definition of the \nzero order Bessel function of the first kind: \n\\begin{equation}\nJ_0(z)=\\frac{1}{\\pi}\\int_0^\\pi e^{iz\\cos\\theta}d\\theta\\:,\n\\end{equation}\nand the binomial expansion for $(r-r_i)^n$.\nThe integrals can be computed recursively using the following identities:\n%\\begin{center}\n%\\begin{minipage}{0.7\\textwidth}\n\\begin{align}\n&\\int dz J_0(z)=\\frac{z}{2}\\left[\\pi J_1(z)H_0(z)+J_0(z)(2-\\pi H_1(z))\\right]\n\\label{0thmoment}\\:,\\\\\n&\\int dz z J_0(z)= z J_1(z)\n\\label{1stmoment}\\:,\\\\\n&\\int dz z^n J_0(z)= z^nJ_1(z)+(n-1)x^{n-1}J_0(z)\n-(n-1)^2\\int dz z^{n-2} J_0(z)\\:.\n\\label{nthmoment}\n\\end{align}\n%\\end{minipage}\n%\\end{center}\nEquation~\\ref{nthmoment} is obtained using Equation~\\ref{1stmoment}, integration by part, and \nthe identity $\\int J_1(z) dz =-J_0(z)$. In Equation~\\ref{0thmoment} $H_0$ and $H_1$ are Struve functions.\n\n\\subsection{Construction of the matrix elements}\nUsing the previous equations, we can construct the matrix elements in Equation~\\ref{matrix_elements}\nand proceed solving for $t_i$. It is sometimes desirable to put some constraints\non the value of $t_i$. For example, when the Coulomb potential is concerned, we might \nwant to set $t_{0}=1$. If the first $g$ variable is constrained by $t_{m}=\\gamma_m$ \nwith $m=[1,g]$, we can simply redefine Equation~\\ref{matrix_elements} as\n\\begin{equation}\n\\begin{split}\nA_{ij}=&\\sum_{k>k_c} \\tc_i(k)\\tc_j(k)  \\quad i,j\\notin[1,g]\\:, \\\\\nb_j=&\\sum_{k>k_c} \\left(\\tV(k)-\\sum_{m=1}^g \\gamma_m \\tc_m(k)\\right)\\tc_j(k)\\quad j\\notin[1,g]\\:.\n\\end{split}\n\\label{modified_matrix_elements}\n\\end{equation}\n\n\n\n% discussion below of (fortran) routines kept for now (18 Oct 2017)\n% possibly these map onto routines in qmcpack also\n\n%\\subsection*{The routines}\n%\\subsubsection*{fitpnnew}\n%This routine constructs the $t_i$ and $\\tY(k)$. Previously a routine, \n%let us call it {\\em shells}, generating a grid of $\\kv$ points has to\n%be called. {\\em shells} stores $\\kv$ vectors\n%in order of increasing magnitude and defines a shell as the \n%set of vectors having the same magnitude $k$ (in practice their difference \n%in magnitude must be below a given threshold). The total number of\n%shells $N_\\text{shell}$ has to be large enough to represents $V(\\rv)$\n%accurately using $\\tV(k)$. The number of vector\n%in a given shell is called $w(k)$. The following variables are passed as\n%input: $\\tV(k),k,w(k),N_\\text{shell},m,r_c,N_\\text{knot},\\Omega$ and are called\n%\\verb!v(0:nk),rk(0:nk),wt(0:nk),nk,m,rad,nknots!. Note that the vectors all\n%start from $0$ which corresponds to $k=0$. The number of shells such that\n%$k\\le k_c$ is also passed as input and called \\verb!nf!. Additional input variables \n%are  \\verb!coul! a logical variable specifying if the potential is coulombic; \n%\\verb!vmad! the exact value of the Madelung constant;\n%\\verb!t0,t1! logical variables specifying if a constraint has to be put\n%on element $t_0$ or $t_1$ and \\verb!vt0,vt1! the value at which $t_0$ and $t_1$\n%have to be set if corresponding constraints are active. \n%The routine works in this way:\n%\\begin{itemize}\n%\\item it calls {\\em basis} and gets the coefficients $S_{\\alpha n}$ (the $n$-th\n%      coefficient of the $\\alpha$-th polynomials) for the desired value of $m$.\n%\\item for every $k$ point, knot $i$ and polynomial $\\alpha$ compute $\\tc_{i\\alpha}(k)$\n%      using Eq.\\ref{fourier_transform}. $D^\\pm_{in}(k)$ is provided by {\\em splint3D}\n%      or {\\em splint2D}. The routine uses \\verb!ialpha!$=i(m+1)+\\alpha$ (the range of \n%      variability of $\\alpha$ and $i$ is specified above Eq.\\ref{basisdef}).\n%\\item Matrix elements are constructed according to Eq.\\ref{matrix_elements}\n%\\item Matrix elements are modified according to Eq.\\ref{modified_matrix_elements} \n%      if constraints are active\n%\\item $t_i$ are computed solving the linear system. $\\tY(k)$ are computed.\n%\\item A comparison with the exact Madelung constant is performed.\n%\\end{itemize}\n%\n%\\subsubsection*{splint3D}\n%Called by {\\em fitpnnew}. This routine compute $D^\\pm_{in}(k)$ for given \n%$k$ and $i$ and for all\n%$n$ (going from $0$ to $\\mathcal{N}=2m+1$). $D^\\pm_{in}(k)$ are called \n%\\verb!ddplus(0:maxn)! and \\verb!ddminus(0:maxn)! and are given as output\n%by the routine. In input one is required to specify $\\mathcal{N},r_i,\\Delta,k,\\Omega$,\n%respectively named \\verb!maxn,r,delta,k,vol!. A logical input flag called \n%\\verb!coul! specify if the potential is coulombic or not. The routine works\n%in this way:\n%\\begin{itemize}\n%\\item it checks if $k$ is equal to 0\n%\\item if $k\\ne 0$ then\n%  \\begin{itemize}\n%  \\item it computes $E^\\pm_{in}(k)$ for the specified $i$ and $k$ using Eqs.\\ref{nthEpm} and\n%      \\ref{0thEpm}. $E^\\pm_{in}(k)$ are called \\verb!ee(0:maxn,!$\\pm$\\verb!1)! \n%      (\\verb!ee(:,0)! are never used).\n%  \\item Depending on the value of \\verb!coul! either Eq.\\ref{noncoulD+-} or Eq.\\ref{coulD+-} \n%      is used to construct $D^\\pm_{in}(k)$. The prefactor $\\frac{4\\pi}{k \\Omega}$ \n%      is precomputed and called \\verb!dnorm!.\n%  \\end{itemize}\n%\\item if $k=0$ the code uses either Eq.\\ref{noncoul_k=0D+-} or Eq.\\ref{coul_k=0D+-}.\n%\\end{itemize}\n%\n%\\subsubsection*{splint2D}\n%Called by {\\em fitpnnew}. This routine compute $D^\\pm_{in}(k)$ in the 2D case.\n%The \\verb!i\\o! format is identical to {\\em splint3D}. Equations from \\ref{0thmoment}\n%to \\ref{nthmoment} are used to generate the required integrals.\n%\n%\n%\\subsubsection*{basis}\n%Called by {\\em fitpnnew}. It computes the coefficients $S_{\\alpha n}$ (the $n$-th \n%coefficient of the $\\alpha$-th polynomials) using Eqs.\\ref{Smatrix1} and \\ref{Smatrix2}.\n%These coefficients are stored in \\verb!s(0:m,0:2m+1)!. $m$ (called \\verb!m!) \n%is required in input.\n%\n%\\subsubsection*{computespl}\n%This compute $W(r)$ at any $r$. $r$ is named \\verb!rpos! internally. It requires\n%$m,2m+1,N_\\text{knot},S_{\\alpha n},r_i,t_i,\\Delta$. These are internally called\n%\\verb!m,maxn,nknots,s(0:m,0:maxn),r(0:nknots),t(0:nknots(m+1)-1),delta!. \n%\\verb!coul! is also needed: it is a logical variable \n%to specify if $c_{i\\alpha}^\\text{coul}(r)$ have to be used instead of $c_{i\\alpha}(r)$.\n%The value of $W(r)$ is stored in \\verb!w!.\n\n\n\n\n%\\newpage\n\\section{Feature: Cubic spline interpolation}\n% Written by Kenneth P .Esler Jr.\n% Originally titled ``Cubic Spline Interpolation in 1, 2 and 3 Dimensions''\n\n\\newenvironment{DMatrix}{\\begin{array}|{*{20}{c}}|}{\\end{array}}\n\\newenvironment{MyMatrix}{\\begin{array}({*{20}{c}})}{\\end{array}}\n\\newenvironment{LMatrix}{\\begin{array}({*{20}{l}})}{\\end{array}}\n\nWe present the basic equations and algorithms necessary to\nconstruct and evaluate cubic interpolating splines in one, two, and\nthree dimensions.  Equations are provided for both natural and\nperiodic boundary conditions.\n\n\\subsection{One dimension}\nLet us consider the problem in which we have a function $y(x)$\nspecified at a discrete set of points $x_i$, such that $y(x_i) = y_i$.\nWe wish to construct a piecewise cubic polynomial interpolating\nfunction, $f(x)$, which satisfies the following conditions:\n\\begin{itemize}\n\\item $f(x_i) = y_i$\\:.\n\\item $f'(x_i^-) = f'(x_i^+)$\\:.\n\\item $f''(x_i^-) = f''(x_i+)$\\:.\n\\end{itemize}\n\n\\subsubsection{Hermite interpolants}\nIn our piecewise representation, we wish to store only the values\n$y_i$ and first derivatives, $y'_i$, of our function at each point\n$x_i$, which we call {\\em knots}.  Given this data, we wish to\nconstruct the piecewise cubic function to use between $x_i$ and\n$x_{i+1}$, which satisfies the preceding conditions.  In particular, we\nwish to find the unique cubic polynomial, $P(x)$, satisfying\n\\begin{eqnarray}\nP(x_i)      & = & y_i      \\label{eq:c1}\\:, \\\\\nP(x_{i+1})  & = & y_{i+1}  \\label{eq:c2}\\:, \\\\\nP'(x_i)     & = & y'_i     \\label{eq:c3}\\:, \\\\\nP'(x_{i+1}) & = & y'_{i+1} \\label{eq:c4}\\:.\n\\end{eqnarray}\n\\begin{eqnarray}\nh_i & \\equiv & x_{i+1} - {x_i}\\:, \\\\\nt & \\equiv & \\frac{x-x_i}{h_i}\\:.\n\\end{eqnarray}\nWe then define the basis functions,\n\\begin{eqnarray}\np_1(t) & = & (1+2t)(t-1)^2  \\label{eq:p1}\\:, \\\\\nq_1(t) & = & t (t-1)^2\\:,       \\\\\np_2(t) & = & t^2(3-2t)\\:,       \\\\\nq_2(t) & = & t^2(t-1)\\:.       \\label{eq:q2}\n\\end{eqnarray}\nOn the interval, $(x_i, x_{i+1}]$, we define the interpolating\nfunction\n\\begin{equation}\nP(x) = y_i p_1(t) + y_{i+1}p_2(t) + h\\left[y'_i q_1(t) + y'_{i+1} q_2(t)\\right]\\:. \n\\end{equation}\nIt can be easily verified that $P(x)$ satisfies conditions of Equations~\\ref{eq:c1}\nthrough \\ref{eq:c4}.  It is now left to\ndetermine the proper values for the $y'_i\\,$s such that the continuity\nconditions given previously are satisfied.\n\nBy construction, the value of the function and derivative will match\nat the knots; that is,\n\\begin{equation}\nP(x_i^-) = P(x_i^+), \\ \\ \\ \\ P'(x_i^-) = P'(x_i^+)\\:. \n\\end{equation}\nThen we must now enforce only the second derivative continuity:\n\\begin{eqnarray}\nP''(x_i^-) & = & P''(x_i^+)\\:,  \\\\\n\\frac{1}{h_{i-1}^2}\\left[\\rule{0pt}{0.3cm}6 y_{i-1} -6 y_i + h_{i-1}\\left(2 y'_{i-1} +4 y'_i\\right) \\right]& = &\n\\frac{1}{h_i^2}\\left[\\rule{0pt}{0.3cm}-6 y_i + 6 y_{i+1} +h_i\\left( -4 y'_i -2 y'_{i+1} \\right)\\right] \\nonumber\\:. \n\\end{eqnarray}\nLet us define\n\\begin{eqnarray}\n\\lambda_i & \\equiv & \\frac{h_i}{2(h_i+h_{i-1})}\\:,  \\\\\n\\mu_i & \\equiv & \\frac{h_{i-1}}{2(h_i+h_{i-1})}  = \\frac{1}{2} - \\lambda_i\\:. \n\\end{eqnarray}\nThen we may rearrange\n\\begin{equation}\n\\lambda_i y'_{i-1} + y'_i + \\mu_i y'_{i+1} = \\underbrace{3 \\left[\\lambda_i \\frac{y_i - y_{i-1}}{h_{i-1}} + \\mu_i \\frac{y_{i+1}\n    - y_i}{h_i} \\right] }_{d_i}\\:. \n\\end{equation}\nThis equation holds for all $0<i<(N-1)$, so we have a tridiagonal set of\nequations.  The equations for $i=0$ and $i=N-1$ depend on the boundary\nconditions we are using.  \n\\subsubsection{Periodic boundary conditions}\nFor periodic boundary conditions, we have\n\\begin{equation}\n\\begin{matrix}\ny'_0           & +  & \\mu_0 y'_1     &   &                   &            & \\dots                   & +  \\lambda_0 y'_{N-1} & = & d_0\\:,  \\\\\n\\lambda_1 y'_0 & +  & y'_1           & + &  \\mu_1 y'_2       &            & \\dots                   &                       & = & d_1\\:,  \\\\\n               &    & \\lambda_2 y'_1 & + &  y'_2           + & \\mu_2 y'_3 & \\dots                   &                       & = & d_2\\:,  \\\\\n               &    &                &   &  \\vdots           &            &                         &                       &   &     \\\\\n\\mu_{N-1} y'_0 &    &                &   &                   &            & +\\lambda_{N-1} y'_{N-1} & +  y'_{N-2}           & = & d_3\\:.  \n\\end{matrix}\n\\end{equation}\nOr, in matrix form, we have\n\\begin{equation}\n\\begin{MyMatrix}\n1         & \\mu_0     &    0   &   0           & \\dots         &      0        & \\lambda_0 \\\\\n\\lambda_1 &  1        & \\mu_1  &   0           & \\dots         &      0        &     0     \\\\\n0         & \\lambda_2 &   1    & \\mu_2         & \\dots         &      0        &     0     \\\\\n\\vdots    & \\vdots    & \\vdots & \\vdots        & \\ddots        &   \\vdots      &  \\vdots   \\\\\n0         &   0       &   0    & \\lambda_{N-3} &      1        & \\mu_{N-3}     &    0      \\\\\n0         &   0       &   0    &   0           & \\lambda_{N-2} &      1        & \\mu_{N-2} \\\\\n\\mu_{N-1} &   0       &   0    &   0           &   0           & \\lambda_{N-1} &  1     \n\\end{MyMatrix}\n\\begin{MyMatrix} y'_0 \\\\ y'_1 \\\\ y'_2 \\\\ \\vdots \\\\ y'_{N-3} \\\\ y'_{N-2} \\\\ y'_{N-1} \\end{MyMatrix} =\n\\begin{MyMatrix} d_0  \\\\  d_1 \\\\  d_2 \\\\ \\vdots \\\\  d_{N-3} \\\\  d_{N-2} \\\\  d_{N-1} \\end{MyMatrix} .\n\\end{equation}\nThe system is tridiagonal except for the two elements in the upper\nright and lower left corners.  These terms complicate the solution a\nbit, although it can still be done in $\\mathcal{O}(N)$ time.  We first\nproceed down the rows, eliminating the the first non-zero term in each\nrow by subtracting the appropriate multiple of the previous row.  At\nthe same time, we eliminate the first element in the last row,\nshifting the position of the first non-zero element to the right with\neach iteration.  When we get to the final row, we will have the value\nfor $y'_{N-1}$.  We can then proceed back upward, backsubstituting\nvalues from the rows below to calculate all the derivatives.\n\n\\subsubsection{Complete boundary conditions}\nIf we specify the first derivatives of our function at the end points,\nwe have what is known as {\\em complete} boundary conditions.  The\nequations in that case are trivial to solve:\n\\begin{equation}\n\\begin{MyMatrix}\n1         &  0        &    0   &   0           & \\dots         &      0        &     0     \\\\\n\\lambda_1 &  1        & \\mu_1  &   0           & \\dots         &      0        &     0     \\\\\n0         & \\lambda_2 &   1    & \\mu_2         & \\dots         &      0        &     0     \\\\\n\\vdots    & \\vdots    & \\vdots & \\vdots        & \\ddots        &   \\vdots      &  \\vdots   \\\\\n0         &   0       &   0    & \\lambda_{N-3} &      1        & \\mu_{N-3}     &    0      \\\\\n0         &   0       &   0    &   0           & \\lambda_{N-2} &      1        & \\mu_{N-2} \\\\\n0         &   0       &   0    &   0           &   0           &      0        &  1     \n\\end{MyMatrix}\n\\begin{MyMatrix} y'_0 \\\\ y'_1 \\\\ y'_2 \\\\ \\vdots \\\\ y'_{N-3} \\\\ y'_{N-2} \\\\ y'_{N-1} \\end{MyMatrix} =\n\\begin{MyMatrix} d_0  \\\\  d_1 \\\\  d_2 \\\\ \\vdots \\\\  d_{N-3} \\\\  d_{N-2} \\\\  d_{N-1} \\end{MyMatrix} .\n\\end{equation}\nThis system is completely tridiagonal, and we may solve trivially by\nperforming row eliminations downward, then proceeding upward as\nbefore.\n\n\\subsubsection{Natural boundary conditions}\nIf we do not have information about the derivatives at the boundary\nconditions, we may construct a {\\em natural spline}, which assumes the second derivatives are zero at the end points of our spline.  In\nthis case our system of equations is the following:\n\\begin{equation}\n\\begin{MyMatrix}\n1         & \\frac{1}{2} &    0   &   0           & \\dots         &      0        &     0     \\\\\n\\lambda_1 &  1          & \\mu_1  &   0           & \\dots         &      0        &     0     \\\\\n0         & \\lambda_2   &   1    & \\mu_2         & \\dots         &      0        &     0     \\\\\n\\vdots    & \\vdots      & \\vdots & \\vdots        & \\ddots        &   \\vdots      &  \\vdots   \\\\\n0         &   0         &   0    & \\lambda_{N-3} &      1        & \\mu_{N-3}     &    0      \\\\\n0         &   0         &   0    &   0           & \\lambda_{N-2} &      1        & \\mu_{N-2} \\\\\n0         &   0         &   0    &   0           &   0           &  \\frac{1}{2}  &  1     \n\\end{MyMatrix}\n\\begin{MyMatrix} y'_0 \\\\ y'_1 \\\\ y'_2 \\\\ \\vdots \\\\ y'_{N-3} \\\\ y'_{N-2} \\\\ y'_{N-1} \\end{MyMatrix} =\n\\begin{MyMatrix} d_0  \\\\  d_1 \\\\  d_2 \\\\ \\vdots \\\\  d_{N-3} \\\\  d_{N-2} \\\\  d_{N-1} \\end{MyMatrix} ,\n\\end{equation}\nwith\n\\begin{equation}\nd_0 = \\frac{3}{2} \\frac{y_1-y_1}{h_0}\\:,  \\ \\ \\ \\ \\ d_{N-1} = \\frac{3}{2} \\frac{y_{N-1}-y_{N-2}}{h_{N-1}}\\:. \n\\end{equation}\n\n\\subsection{Bicubic splines}\nIt is possible to extend the cubic spline interpolation method to\nfunctions of two variables, that is, $F(x,y)$.  In this case, we have a\nrectangular mesh of points given by $F_{ij} \\equiv F(x_i,y_j)$.  In\nthe case of 1D splines, we needed to store the value of the first\nderivative of the function at each point, in addition to the value.\nIn the case of {\\em bicubic splines}, we need to store four\nquantities for each mesh point:  \n\\begin{eqnarray}\nF_{ij}    & \\equiv & F(x_i, y_i)\\:,             \\\\\nF^x_{ij}  & \\equiv & \\partial_x F(x_i, y_i)\\:,  \\\\\nF^y_{ij}  & \\equiv & \\partial_y F(x_i, y_i)\\:,  \\\\\nF^{xy}    & \\equiv & \\partial_x \\partial_y F(x_i, y_i)\\:. \n\\end{eqnarray}\n\nConsider the point $(x,y)$ at which we wish to interpolate $F$.  We\nlocate the rectangle that contains this point, such that $x_i <= x <\nx_{i+1}$ and $y_i <= x < y_{i+1}$.  Let \n\\begin{eqnarray}\nh & \\equiv & x_{i+1}-x_i\\:,  \\\\\nl & \\equiv & y_{i+1}-y_i\\:,  \\\\\nu & \\equiv & \\frac{x-x_i}{h}\\:,  \\\\\nv & \\equiv & \\frac{y-y_i}{l}\\:. \n\\end{eqnarray}\nThen, we calculate the interpolated value as\n\\begin{equation}\nF(x,y) = \n\\begin{MyMatrix}\np_1(u) \\\\ p_2(u) \\\\ h q_1(u) \\\\ h q_2(u) \n\\end{MyMatrix}^T\n\\begin{MyMatrix}\nF_{i,j}     & F_{i+1,j}     & F^y_{i,j}      & F^y_{i,j+1}     \\\\\nF_{i+1,j}   & F_{i+1,j+1}   & F^y_{i+1,j}    & F^y_{i+1,j+1}   \\\\\nF^x_{i,j}   & F^x_{i,j+1}   & F^{xy}_{i,j}   & F^{xy}_{i,j+1}  \\\\\nF^x_{i+1,j} & F^x_{i+1,j+1} & F^{xy}_{i+1,j} & F^{xy}_{i+1,j+1} \n\\end{MyMatrix}\n\\begin{MyMatrix}\np_1(v)\\\\ p_2(v)\\\\ k q_1(v) \\\\ k q_2(v) \n\\end{MyMatrix}\\:.\n\\end{equation}\n\\subsubsection{Construction bicubic splines}\nWe now address the issue of how to compute the derivatives that are\nneeded for the interpolation.  The algorithm is quite simple.  For\nevery $x_i$, we perform the tridiagonal solution as we did in the 1D\nsplines to compute $F^y_{ij}$.  Similarly, we perform a tridiagonal\nsolve for every value of $F^x_{ij}$.  Finally, to compute the\ncross-derivative we may {\\em either} to the tridiagonal solve in the $y$\ndirection of $F^x_{ij}$, {\\em or} solve in the $x$ direction for\n$F^y_{ij}$ to obtain the cross-derivatives $F^{xy}_{ij}$.  Hence,\nonly minor modifications to the $1D$ interpolations are necessary.\n\n\\subsection{Tricubic splines}\nBicubic interpolation required two 4-component vectors and a $4 \\times 4$\nmatrix.  By extension, tricubic interpolation requires three\n4-component vectors and a $4 \\times 4 \\times 4$ tensor.  We summarize the forms of\nthese vectors in the following:\n\\begin{eqnarray}\nh & \\equiv & x_{i+1}-x_i\\:, \\\\\nl & \\equiv & y_{i+1}-y_i\\:, \\\\\nm & \\equiv & z_{i+1}-z_i\\:, \\\\\nu & \\equiv & \\frac{x-x_i}{h}\\:, \\\\\nv & \\equiv & \\frac{y-y_i}{l}\\:, \\\\\nw & \\equiv & \\frac{z-z_i}{m}\\:.\n\\end{eqnarray}\n\\begin{eqnarray}\n\\vec{a} & = & \n\\begin{MyMatrix}\np_1(u) & p_2(u) & h q_1(u) & h q_2(u) \n\\end{MyMatrix}^T\\:, \\\\\n\\vec{b} & = & \n\\begin{MyMatrix}\np_1(v) & p_2(v) & k q_1(v) & k q_2(v) \n\\end{MyMatrix}^T\\:, \\\\\n\\vec{c} & = & \n\\begin{MyMatrix}\np_1(w) & p_2(w) & l q_1(w) & l q_2(w) \n\\end{MyMatrix}^T\\:. \n\\end{eqnarray}\n\\begin{equation}\n\\begin{LMatrix}\nA_{000} = F_{i,j,k}     & A_{001}=F_{i,j,k+1}     & A_{002}=F^z_{i,j,k}      & A_{003}=F^z_{i,j,k+1}      \\\\\nA_{010} = F_{i,j+1,k}   & A_{011}=F_{i,j+1,k+1}   & A_{012}=F^z_{i,j+1,k}    & A_{013}=F^z_{i,j+1,k+1}    \\\\\nA_{020} = F^y_{i,j,k}   & A_{021}=F^y_{i,j,k+1}   & A_{022}=F^{yz}_{i,j,k}   & A_{023}=F^{yz}_{i,j,k+1}   \\\\\nA_{030} = F^y_{i,j+1,k} & A_{031}=F^y_{i,j+1,k+1} & A_{032}=F^{yz}_{i,j+1,k} & A_{033}=F^{yz}_{i,j+1,k+1} \\\\\n                        &                         &                          &                            \\\\\nA_{100} = F_{i+1,j,k}     & A_{101}=F_{i+1,j,k+1}     & A_{102}=F^z_{i+1,j,k}      & A_{103}=F^z_{i+1,j,k+1}      \\\\\nA_{110} = F_{i+1,j+1,k}   & A_{111}=F_{i+1,j+1,k+1}   & A_{112}=F^z_{i+1,j+1,k}    & A_{113}=F^z_{i+1,j+1,k+1}    \\\\\nA_{120} = F^y_{i+1,j,k}   & A_{121}=F^y_{i+1,j,k+1}   & A_{122}=F^{yz}_{i+1,j,k}   & A_{123}=F^{yz}_{i+1,j,k+1}   \\\\\nA_{130} = F^y_{i+1,j+1,k} & A_{131}=F^y_{i+1,j+1,k+1} & A_{132}=F^{yz}_{i+1,j+1,k} & A_{133}=F^{yz}_{i+1,j+1,k+1} \\\\\n                        &                         &                          &                            \\\\\nA_{200} = F^x_{i,j,k}      & A_{201}=F^x_{i,j,k+1}      & A_{202}=F^{xz}_{i,j,k}      & A_{203}=F^{xz}_{i,j,k+1}    \\\\\nA_{210} = F^x_{i,j+1,k}    & A_{211}=F^x_{i,j+1,k+1}    & A_{212}=F^{xz}_{i,j+1,k}    & A_{213}=F^{xz}_{i,j+1,k+1}  \\\\\nA_{220} = F^{xy}_{i,j,k}   & A_{221}=F^{xy}_{i,j,k+1}   & A_{222}=F^{xyz}_{i,j,k}     & A_{223}=F^{xyz}_{i,j,k+1}   \\\\\nA_{230} = F^{xy}_{i,j+1,k} & A_{231}=F^{xy}_{i,j+1,k+1} & A_{232}=F^{xyz}_{i,j+1,k}   & A_{233}=F^{xyz}_{i,j+1,k+1} \\\\\n                        &                         &                          &                                      \\\\\nA_{300} = F^x_{i+1,j,k}      & A_{301}=F^x_{i+1,j,k+1}      & A_{302}=F^{xz}_{i+1,j,k}    & A_{303}=F^{xz}_{i+1,j,k+1}   \\\\\nA_{310} = F^x_{i+1,j+1,k}    & A_{311}=F^x_{i+1,j+1,k+1}    & A_{312}=F^{xz}_{i+1,j+1,k}  & A_{313}=F^{xz}_{i+1,j+1,k+1} \\\\\nA_{320} = F^{xy}_{i+1,j,k}   & A_{321}=F^{xy}_{i+1,j,k+1}   & A_{322}=F^{xyz}_{i+1,j,k}   & A_{323}=F^{xyz}_{i+1,j,k+1}  \\\\\nA_{330} = F^{xy}_{i+1,j+1,k} & A_{331}=F^{xy}_{i+1,j+1,k+1} & A_{332}=F^{xyz}_{i+1,j+1,k} & A_{333}=F^{xyz}_{i+1,j+1,k+1} \n\\end{LMatrix}\\:.\n\\end{equation}\nNow, we can write\n\\begin{equation}\nF(x,y,z) = \\sum_{i=0}^3 a_i \\sum_{j=0}^3 b_j \\sum_{k=0}^3 c_k \\ A_{i,j,k}\\:. \n\\end{equation}\nThe appropriate derivatives of $F$ may be computed by a generalization\nof the previous method used for bicubic splines.\n\n\n\\section{Feature: B-spline orbital tiling (band unfolding)}\n\n% Written by Kenneth P .Esler Jr.\n% Originally titled ``Generalized band unfolding for quantum Monte Carlo simulation of solids''\n\nIn continuum QMC simulations, it is necessary to\nevaluate the electronic orbitals of a system at real-space positions\nhundreds of millions of times.  It has been found that if\nthese orbitals are represented in a localized, B-spline basis, each\nevaluation takes a small, constant time that is independent of system\nsize.\n\nUnfortunately, the memory required for storing the B-spline grows with\nthe second power of the system size.  If we are studying perfect\ncrystals, however, this can be reduced to linear scaling if we {\\em\n  tile} the primitive cell.  In this approach, \n%implemented in the CASINO QMC simulation suite, \na supercell is constructed by tiling the\nprimitive cell $N_1 \\times N_2 \\times N_3$ in the three lattice\ndirections.  The orbitals are then represented in real space only in\nthe primitive cell and an $N_1 \\times N_2 \\times N_3$ k-point mesh.\nTo evaluate an orbital at any point in the supercell, it is only\nnecessary to wrap that point back into the primitive cell, evaluate\nthe spline, and then multiply the phase factor,\n$e^{-i\\mathbf{k}\\cdot\\mathbf{r}}$.  \n\nHere, we show that this approach can be generalized to a tiling\nconstructed with a $3\\times 3$ nonsingular matrix of integers, of which\nthe preceding approach is a special case.  This generalization brings with\nit a number of advantages.  The primary reason for performing\nsupercell calculations in QMC is to reduce finite-size errors.  These\nerrors result from three sources:  (1) the quantization of the crystal\nmomentum,  (2) the unphysical periodicity of the exchange-correlation (XC)\nhole of the electron, and (3) the kinetic-energy contribution from the\nperiodicity of the long-range Jastrow correlation functions.  The first\nsource of error can be largely eliminated by twist averaging.  If the\nsimulation cell is large enough that XC hole does not ``leak'' out of\nthe simulation cell, the second source can be eliminated either\nthrough use of the MPC interaction or the {\\em a postiori} correction\nof Chiesa et al.  \n\nThe satisfaction of the leakage requirement is controlled by whether\nthe minimum distance, $L_{\\text{min}}$, from one supercell image to the\nnext is greater than the width of the XC hole.  Therefore, given a\nchoice, it is best to use a cell that is as nearly cubic as possible\nsince this choice maximizes $L_{\\text{min}}$ for a given number of\natoms.  Most often, however, the primitive cell is not cubic.  In\nthese cases, if we wish to choose the optimal supercell to reduce\nfinite-size effects, we cannot use the simple primitive tiling\nscheme.  In the generalized scheme we present, it is possible to\nchoose far better supercells (from the standpoint of finite-size\nerrors), while retaining the storage efficiency of the original tiling\nscheme.\n\n\\subsection{The mathematics}\n\\renewcommand{\\vp}{\\mathbf{a}^{\\text{p}}}\n\\renewcommand{\\vs}{\\mathbf{a}^{\\text{s}}} \n\\renewcommand{\\Smat}{\\mathbf{S}}\nConsider the set of primitive lattice vectors, $\\{\\vp_1, \\vp_2,\n\\vp_3\\}$.  We may write these vectors in a matrix, $\\mathbf{L}_p$, whose\nrows are the primitive lattice vectors.  Consider a nonsingular\nmatrix of integers, $\\Smat$.  A corresponding set of supercell lattice\nvectors, $\\{\\vs_1, \\vs_2, \\vs_3\\}$, can be constructed by the matrix\nproduct \n\\begin{equation}\n\\vs_i = S_{ij} \\vp_j\\:.\n\\end{equation}\nIf the primitive cell contains $N_p$ atoms, the supercell will then\ncontain $N_s = |\\det(\\Smat)| N_p$ atoms.\n\n\\subsection{Example: FeO}\nAs an example, consider the primitive cell for antiferromagnetic FeO\n(wustite) in the rocksalt structure.  The primitive vectors, given in\nunits of the lattice constant, are given by\n\\newcommand{\\xv}{\\hat{\\mathbf{x}}} \n\\newcommand{\\yv}{\\hat{\\mathbf{y}}}\n\\newcommand{\\zv}{\\hat{\\mathbf{z}}}\n\\begin{eqnarray}\n\\vp_1 & = & \\frac{1}{2}\\xv + \\frac{1}{2}\\yv +      \\ \\   \\zv\\:, \\\\\n\\vp_2 & = & \\frac{1}{2}\\xv +      \\ \\   \\yv + \\frac{1}{2}\\zv\\:, \\\\\n\\vp_3 & = &   \\ \\      \\xv + \\frac{1}{2}\\yv + \\frac{1}{2}\\zv\\:. \n\\end{eqnarray}\nThis primitive cell contains two iron atoms and two oxygen atoms. It\nis a very elongated cell with acute angles and, thus, has a short\nminimum distance between adjacent images.\n\nThe smallest cubic cell consistent with the AFM ordering can be\nconstructed with the matrix\n\\begin{equation}\n\\Smat = \\left[\\begin{array}{rrr}\n  -1 & -1 &  3 \\\\\n  -1 &  3 & -1 \\\\\n   3 & -1 & -1 \n  \\end{array}\\right]\\:.\n\\end{equation}\nThis cell has $2|\\det(\\Smat)| = 32$ iron atoms and 32 oxygen atoms.  In\nthis example, we may perform the simulation in the 32-iron supercell,\nwhile storing the orbitals only in the 2-iron primitive cell, for a\nsavings of a factor of 16.  \n%On current multicore supercomputers, with\n%1-2GB RAM per core, this is literally the difference between be able\n%to perform the simulation or not.\n\n\\subsubsection{The k-point mesh}\nTo be able to use the generalized tiling scheme, we need to\nhave the appropriate number of bands to occupy in the supercell.\nThis may be achieved by appropriately choosing the k-point mesh.  In\nthis section, we explain how these points are chosen.  \n\nFor simplicity, let us assume that the supercell calculation will be\nperformed at the $\\Gamma$-point.  We can easily lift this restriction later.  The fact that supercell calculation is performed at\n$\\Gamma$ implies that the k-points used in the primitive-cell\ncalculation must be $\\mathbf{G}$-vectors of the superlattice.  This\nstill leaves us with an infinite set of vectors.  We may reduce this\nset to a finite number by considering that the orbitals must form a\nlinearly independent set.  Orbitals with k-vectors $\\mathbf{k}^p_1$\nand $\\mathbf{k}^p_2$ will differ by at most a constant factor of\n$\\mathbf{k}^p_1 - \\mathbf{k}^p_2 = \\mathbf{G}^p$, where $\\mathbf{G}^p$\nis a reciprocal lattice vector of the primitive cell.  \n\nCombining these two considerations gives us a prescription for\ngenerating our k-point mesh.  The mesh may be taken to be the set of\nk-point which are G-vectors of the superlattice, reside within the\nfirst Brillouin zone (FBZ) of the primitive lattice, whose members do\nnot differ a G-vector of the primitive lattice.  Upon constructing\nsuch a set, we find that the number of included k-points is equal to\n$|\\det(\\Smat)|$, precisely the number we need.  This can by considering\nthe fact that the supercell has a volume $|\\det(\\Smat)|$ times that of\nthe primitive cell.  This implies that the volume of the supercell's\nFBZ is $|\\det(\\Smat)|^{-1}$ times that of the primitive cell.  Hence,\n$|\\det(\\Smat)|$ G-vectors of the supercell will fit in the FBZ of the\nprimitive cell.  Removing duplicate k-vectors, which differ from\nanother by a reciprocal lattice vector, avoids double-counting vectors\nthat lie on zone faces.\n\n\\subsubsection{Formulae}\n\\newcommand{\\Amat}{\\mathbf{A}} \n\\newcommand{\\Bmat}{\\mathbf{B}} \n\\renewcommand{\\vk}{\\mathbf{k}}\n\\newcommand{\\vt}{\\mathbf{t}}\n\nLet $\\Amat$ be the matrix whose rows are the direct lattice vectors,\n$\\{\\mathbf{a}_i\\}$.  Then, let the matrix $\\Bmat$ be defined as\n$2\\pi(\\Amat^{-1})^\\dagger$.  Its rows are the primitive reciprocal\nlattice vectors.  Let $\\Amat_p$ and $\\Amat_s$ represent the primitive\nand superlattice matrices, respectively, and similarly for their\nreciprocals.  Then we have\n\\begin{eqnarray}\n\\Amat_s & = & \\Smat \\Amat_p\\:, \\\\\n\\Bmat_s & = & 2\\pi\\left[(\\Smat \\Amat_p)^{-1}\\right]^\\dagger\\:, \\\\\n        & = & 2\\pi\\left[\\Amat_p^{-1} \\Smat^{-1}\\right]^\\dagger\\:, \\\\\n        & = & 2\\pi(\\Smat^{-1})^\\dagger (\\Amat_p^{-1})^\\dagger\\:, \\\\\n        & = & (\\Smat^{-1})^\\dagger \\Bmat_p\\:.\n\\end{eqnarray}  \nConsider a k-vector, $\\vk$.  It may alternatively be written in\nbasis of reciprocal lattice vectors as $\\vt$.  \n\\begin{eqnarray}\n\\vk & = & (\\vt^\\dagger \\Bmat)^\\dagger\\:, \\\\\n    & = & \\Bmat^\\dagger \\vt\\:,           \\\\\n\\vt & = & (\\Bmat^\\dagger)^{-1} \\vk\\:,    \\\\\n    & = & (\\Bmat^{-1})^\\dagger \\vk\\:,    \\\\\n    & = & \\frac{\\Amat \\vk}{2\\pi}\\:.\n\\end{eqnarray}\nWe may then express a twist vector of the primitive lattice, $\\vt_p$, in terms\nof the superlattice.\n\\begin{eqnarray}\n\\vt_s & = & \\frac{\\Amat_s \\vk}{2\\pi}\\:,                           \\\\\n      & = & \\frac{\\Amat_s \\Bmat_p^\\dagger \\vt_p}{2\\pi}\\:,         \\\\\n      & = & \\frac{\\Smat \\Amat_p \\Bmat_p^\\dagger \\vt_p}{2\\pi}\\:,   \\\\\n      & = & \\frac{2\\pi \\Smat \\Amat_p \\Amat_p^{-1} \\vt_p}{2\\pi}\\:, \\\\\n      & = & \\Smat \\vt_p\\:.\n\\end{eqnarray}\nThis gives the simple result that twist vectors transform in precisely\nthe same way as direct lattice vectors.\n\n\n\\section{Feature: Hybrid orbital representation}\n\n% Written by Kenneth P. Esler, Jr.\n% Document originally included in QMCPACK at src/QMCWaveFunctions/AtomicOrbital.tex\n% Originally titled ``Hybrid orbital representation''\n\n\\renewcommand{\\vr}{\\mathbf{r}}\n\n\\begin{equation}\n\\phi(\\vr) = \\sum_{\\ell=0}^{\\ell_\\text{max}} \\sum_{m=-\\ell}^\\ell Y_\\ell^m (\\hat{\\Omega})\nu_{\\ell m}(r)\\:,\n\\end{equation}\nwhere $u_{lm}(r)$ are complex radial functions represented in some\nradial basis (e.g., splines).\n\n\\subsection{Real spherical harmonics}\n\\renewcommand{\\Re}{\\rm Re}\n\\renewcommand{\\Im}{\\rm Im}\nIf $\\phi(\\vr)$ can be written as purely real, we can change the\nrepresentation so that\n\\begin{equation}\n\\phi(\\vr) = \\sum_{l=0}^{l_\\text{max}} \\sum_{m=-\\ell}^\\ell Y_{\\ell m}(\\hat{\\Omega})\n\\bar{u}_{lm}(r)\\:,\n\\end{equation}\nwhere $\\bar{Y}_\\ell^m$ are the {\\em real} spherical harmonics defined by\n\\begin{equation}\nY_{\\ell m} = \\begin{cases}\nY_\\ell^0 & \\mbox{if } m=0\\\\\n{1\\over 2}\\left(Y_\\ell^m+(-1)^m \\, Y_\\ell^{-m}\\right) \\ = \\Re\\left[Y_\\ell^m\\right]\n%\\sqrt{2} N_{(\\ell,m)} P_\\ell^m(\\cos \\theta) \\cos m\\varphi \n& \\mbox{if } m>0 \\\\\n{1\\over i 2}\\left(Y_\\ell^{-m}-(-1)^{m}\\, Y_\\ell^{m}\\right) = \\Im\\left[Y_\\ell^{-m}\\right]\n%\\sqrt{2} N_{(\\ell,m)} P_\\ell^{-m}(\\cos \\theta) \\sin m\\varphi \n&\\mbox{if } m<0\\:.\n\\end{cases}\n\\end{equation}\nWe need then to relate $\\bar{u}_{\\ell m}$ to $u_{\\ell m}$.  We wish\nto express\n\\begin{equation}\n\\Re\\left[\\phi(\\vr)\\right] = \\sum_{\\ell=0}^{\\ell_\\text{max}} \\sum_{m=-\\ell}^\\ell\n\\Re\\left[Y_\\ell^m (\\hat{\\Omega}) u_{\\ell m}(r)\\right]\n\\end{equation}\nin terms of $\\bar{u}_{\\ell m}(r)$ and $Y_{\\ell m}$.\n\\begin{eqnarray}\n\\Re\\left[Y_\\ell^m u_{\\ell m}\\right] & = & \\Re\\left[Y_\\ell^m\\right]\n\\Re\\left[u_{\\ell m}\\right] - \\Im\\left[Y_\\ell^m\\right] \\Im\\left[u_{\\ell m}\\right]\\:.\n\\end{eqnarray}\nFor $m>0$,\n\\begin{equation}\n\\Re\\left[Y_\\ell^m\\right] = Y_{\\ell m} \\qquad \\text{and} \\qquad \\Im\\left[Y_\\ell^m\\right] = Y_{\\ell\\,-m}\\:.\n\\end{equation}\nFor $m<0$,\n\\begin{equation}\n\\Re\\left[Y_\\ell^m\\right] = (-1)^m Y_{\\ell\\, -m} \\qquad \\text and \\qquad \\Im\\left[Y_\\ell^m\\right] = -(-1)^m Y_{\\ell m}\\:.\n\\end{equation}\nThen for $m > 0$,\n\\begin{eqnarray}\n\\bar{u}_{\\ell m} & = & \\Re\\left[u_{\\ell m}\\right] + (-1)^m \\Re\\left[u_{\\ell\\,-m}\\right]\\:, \\\\\n\\bar{u}_{\\ell\\, -m} & = & -\\Im\\left[u_{\\ell m}\\right] + (-1)^m \\Im\\left[u_{\\ell\\,-m}\\right]\\:.\n\\end{eqnarray}\n\n\n\\subsection{Projecting to atomic orbitals}\n\n% Written by Ken Esler as part of the Common codebase used in wfconvert\n% Originally titled ``Notes on projecting to atomic orbitals''\n% Dated July 19, 2009\n\n\\renewcommand{\\vr}{\\mathbf{r}}\n\\newcommand{\\vI}{\\mathbf{I}}\n\\renewcommand{\\vk}{\\mathbf{k}}\n\\newcommand{\\vG}{\\mathbf{G}}\n\n%\\subsubsection{Form for orbitals}\nInside a muffin tin, orbitals are represented as products of spherical\nharmonics and 1D radial functions, primarily represented by splines.\nFor a muffin tin centered at $\\vI$, \n\\begin{equation}\n\\phi_n(\\vr) = \\sum_{\\ell,m} Y_\\ell^m(\\hat{\\vr -\\vI})\nu_{lm}\\left(\\left|\\vr - \\vI\\right|\\right) \\label{eq:ulm}\\:.\n\\end{equation}\nLet use consider the case that our original representation for\n$\\phi(\\vr)$ is of the form\n\\begin{equation}\n\\phi_{n,\\vk}(\\vr) = \\sum_\\vG c_{\\vG+\\vk}^n e^{i(\\vG + \\vk)\\cdot \\vr}\\:.\n\\end{equation}\nRecall that\n\\begin{equation}\ne^{i\\vk\\cdot\\vr} = 4\\pi \\sum_{\\ell,m} i^\\ell j_\\ell(|\\vr||\\vk|)\nY_\\ell^m(\\hat{\\vk}) \\left[Y_\\ell^m(\\hat{\\vr})\\right]^*\\:.\n\\end{equation}\nConjugating,\n\\begin{equation}\ne^{-i\\vk\\cdot\\vr} = 4\\pi\\sum_{\\ell,m} (-i)^\\ell j_\\ell(|\\vr||\\vk|)\n\\left[Y_\\ell^m(\\hat{\\vk})\\right]^* Y_\\ell^m(\\hat{\\vr})\\:.\n\\end{equation}\nSetting $\\vk \\rightarrow -k$,\n\\begin{equation}\ne^{i\\vk\\cdot\\vr} = 4\\pi\\sum_{\\ell,m} i^\\ell j_\\ell(|\\vr||\\vk|)\n\\left[Y_\\ell^m(\\hat{\\vk})\\right]^* Y_\\ell^m(\\hat{\\vr})\\:.\n\\end{equation}\n\nThen,\n\\begin{equation}\ne^{i\\vk\\cdot(\\vr-\\vI)} = 4\\pi\\sum_{\\ell,m} i^\\ell j_\\ell(|\\vr-\\vI||\\vk|)\n\\left[Y_\\ell^m(\\hat{\\vk})\\right]^* Y_\\ell^m(\\hat{\\vr-\\vI})\\:.\n\\end{equation}\n\n\\begin{equation}\ne^{i\\vk\\cdot\\vr} = 4\\pi e^{i\\vk\\cdot\\vI} \\-\\sum_{\\ell,m} i^\\ell j_\\ell(|\\vr-\\vI||\\vk|)\n\\left[Y_\\ell^m(\\hat{\\vk})\\right]^* Y_\\ell^m(\\hat{\\vr-\\vI})\\:.\n\\end{equation}\n\nThen\n\\begin{equation}\n\\phi_{n,\\vk}(\\vr) =  \\sum_\\vG 4\\pi c_{\\vG+\\vk}^n\ne^{i(\\vG+\\vk)\\cdot\\vI} \\sum_{\\ell,m}\n  i^\\ell j_\\ell(|\\vG +\\vk||\\vr-\\vI|)\n  \\left[Y_\\ell^m(\\hat{\\vG+\\vk})\\right]^*\nY_\\ell^m(\\hat{\\vr - \\vI})\\:.\n\\end{equation}\nComparing with Equation~\\ref{eq:ulm},\n\\begin{equation}\nu_{\\ell m}^n(r) = 4\\pi i^\\ell \\sum_G c_{\\vG+\\vk}^n e^{i(\\vG+\\vk)\\cdot\\vI}  j_\\ell\\left(|\\vG + \\vk|r|\\right)\n\\left[Y_\\ell^m(\\hat{\\vG + \\vk})\\right]^*\\:.\n\\end{equation}\nIf we had adopted the opposite sign convention for Fourier transforms\n(as is unfortunately the case in wfconvert), we would have\n\\begin{equation}\nu_{\\ell m}^n(r) = 4\\pi (-i)^\\ell \\sum_G c_{\\vG+\\vk}^n e^{-i(\\vG+\\vk)\\cdot\\vI}  j_\\ell\\left(|\\vG + \\vk|r|\\right)\n\\left[Y_\\ell^m(\\hat{\\vG + \\vk})\\right]^*\\:.\n\\end{equation}\n\n\n\n\\section{Feature: Electron-electron-ion Jastrow factor}\n\n% Written by Kenneth P. Esler, Jr.\n% Document originally included in QMCPACK at src/QMCWaveFunctions/Jastrow/eeI_Jastrow.tex\n% Originally titled ``Electron-electron-ion Jastrow factor''\n\n\\newcommand{\\riI}{r_{iI}}\n\\newcommand{\\briI}{\\mathbf{r}_{iI}}\n\\newcommand{\\rjI}{r_{jI}}\n\\newcommand{\\brjI}{\\mathbf{r}_{jI}}\n\\newcommand{\\rij}{r_{ij}}\n\\newcommand{\\brij}{\\mathbf{r}_{ij}}\n%\\section{Form of the Jastrow}\nThe general form of the 3-body Jastrow we describe here depends on the\nthree interparticle distances, $(\\rij, \\riI, \\rjI)$.\n\\begin{equation}\nJ_3 = \\sum_{I\\in\\text{ions}} \\sum_{i,j \\in\\text{elecs};i\\neq j} U(\\rij, \\riI,\n\\rjI)\\:.\n\\end{equation}\nNote that we constrain the form of $U$ such that\n$U(\\rij, \\riI,\\rjI) = U(\\rij, \\rjI,\\riI)$ to preserve the\nparticle symmetry of the wavefunction.  We then compute the gradient as\n\\begin{equation}\n\\nabla_i J_3 =  \\sum_{I\\in\\text{ions}} \\sum_{j \\neq i}\n\\left[\\frac{\\partial U(\\rij, \\riI,\\rjI)}{\\partial\\rij}\n  \\frac{\\mathbf{r}_i - \\mathbf{r}_j}{|\\mathbf{r}_i - \\mathbf{r}_j|} \n+ \\frac{\\partial U(\\rij, \\riI,\\rjI)}{\\partial\\riI}\n  \\frac{\\mathbf{r}_i - \\mathbf{I}}{|\\mathbf{r}_i - \\mathbf{I}|}  \\right]\\:.\n\\end{equation}\nTo compute the Laplacian, we take\n\\begin{eqnarray}\n\\nabla_i^2 J_3 & = & \\nabla_i \\cdot \\left(\\nabla_i J_3\\right)\\:, \\\\\n& = & \\sum_{I\\in\\text{ions}} \\sum_{j\\neq i } \\left[\n\\frac{\\partial^2 U}{\\partial \\rij^2} + \\frac{2}{\\rij} \\frac{\\partial\n  U}{\\partial \\rij} + 2 \\frac{\\partial^2 U}{\\partial \\rij \\partial\n  \\riI}\\frac{\\brij\\cdot\\briI}{\\rij\\riI} +\\frac{\\partial^2 U}{\\partial\n  \\riI^2}\n+ \\frac{2}{\\riI}\\frac{\\partial U}{\\partial \\riI} \\nonumber\n\\right]\\:.\n\\end{eqnarray}\nWe now wish to compute the gradient of these terms w.r.t. the ion position, $I$.\n\\begin{equation}\n\\nabla_I J_3 = -\\sum_{j\\neq i} \\left[ \\frac{\\partial U(\\rij, \\riI,\\rjI)}{\\partial\\riI}\n  \\frac{\\mathbf{r}_i - \\mathbf{I}}{|\\mathbf{r}_i - \\mathbf{I}|} \n+\\frac{\\partial U(\\rij, \\riI,\\rjI)}{\\partial\\rjI}\n  \\frac{\\mathbf{r}_j - \\mathbf{I}}{|\\mathbf{r}_j - \\mathbf{I}|} \\right]\\:.\n\\end{equation}\nFor the gradient w.r.t. $i$ of the gradient w.r.t. $I$, the result is a tensor:\n\\begin{eqnarray}\n\\nabla_I \\nabla_i J_3 & = & \\nabla_I \\sum_{j \\neq i}\n\\left[\\frac{\\partial U(\\rij, \\riI,\\rjI)}{\\partial\\rij}\n  \\frac{\\mathbf{r}_i - \\mathbf{r}_j}{|\\mathbf{r}_i - \\mathbf{r}_j|} \n+ \\frac{\\partial U(\\rij, \\riI,\\rjI)}{\\partial\\riI}\n  \\frac{\\mathbf{r}_i - \\mathbf{I}}{|\\mathbf{r}_i - \\mathbf{I}|}  \\right]\\:, \\\\\\nonumber \\\\\\nonumber\n& = & -\\sum_{j\\neq i} \\left[ \n\\frac{\\partial^2 U}{\\partial \\rij \\riI} \\hat{\\mathbf{r}}_{ij} \\otimes\n\\hat{\\mathbf{r}}_{iI} + \\left(\\frac{\\partial^2 U}{\\partial \\riI^2} -\n\\frac{1}{\\riI} \\frac{\\partial U}{\\partial \\riI}\\right)\n\\hat{\\mathbf{r}}_{iI} \\otimes \\hat{\\mathbf{r}}_{iI} \\right. + \\\\\\nonumber\n& & \\left. \\qquad \\ \\ \\  \\frac{\\partial^U}{\\partial \\rij \\rjI} \\hat{\\mathbf{r}}_{ij} \\otimes \\hat{\\mathbf{r}}_{jI} + \\frac{\\partial^2 U}{\\partial \\riI \\partial \\rjI}\n\\hat{\\mathbf{r}}_{iI}\\otimes \\hat{\\mathbf{r}}_{jI}  +\n\\frac{1}{\\riI} \\frac{\\partial U}{\\partial \\riI} \\overleftrightarrow{\\mathbf{1}}\\right]\\:.\n\\end{eqnarray}\n\n\\begin{eqnarray}\n\\nabla_I \\nabla_i J_3 & = & \\nabla_I \\sum_{j \\neq i}\n\\left[\\frac{\\partial U(\\rij, \\riI,\\rjI)}{\\partial\\rij}\n  \\frac{\\mathbf{r}_i - \\mathbf{r}_j}{|\\mathbf{r}_i - \\mathbf{r}_j|} \n+ \\frac{\\partial U(\\rij, \\riI,\\rjI)}{\\partial\\riI}\n  \\frac{\\mathbf{r}_i - \\mathbf{I}}{|\\mathbf{r}_i - \\mathbf{I}|}  \\right]\\:, \\\\\\nonumber \n& = & \\sum_{j\\neq i} \\left[ -\\frac{\\partial^2 U}{\\partial \\rij \\partial \\riI} \\hat{\\mathbf{r}}_{ij} \\otimes \\hat{\\mathbf{r}}_{iI} +\n\\left(-\\frac{\\partial^2 U}{\\partial \\riI^2}  + \\frac{1}{\\riI}\\frac{\\partial U}{\\partial \\riI} \\right) \n\\hat{\\mathbf{r}}_{iI} \\otimes \\hat{\\mathbf{r}}_{iI} - \\frac{1}{\\riI}\\frac{\\partial U}{\\partial \\riI} \\overleftrightarrow{\\mathbf{1}}\n\\right]\\:.\n\\end{eqnarray}\nFor the Laplacian,\n\\begin{eqnarray}\n\\nabla_I \\nabla_i^2 J_3 & = & \\nabla_I\\left[\\nabla_i \\cdot \\left(\\nabla_i J_3\\right)\\right]\\:, \\\\\n& = & \\nabla_I \\sum_{j\\neq i } \\left[\n\\frac{\\partial^2 U}{\\partial \\rij^2} + \\frac{2}{\\rij} \\frac{\\partial\n  U}{\\partial \\rij} + 2 \\frac{\\partial^2 U}{\\partial \\rij \\partial\n  \\riI}\\frac{\\brij\\cdot\\briI}{\\rij\\riI} +\\frac{\\partial^2 U}{\\partial\n  \\riI^2}\n+ \\frac{2}{\\riI}\\frac{\\partial U}{\\partial \\riI} \\nonumber\n\\right]\\:, \\\\\n& = & \\sum_{j\\neq i } \n\\left[ \\frac{\\partial^3 U}{\\partial r_{iI} \\partial^2 r_{ij}} +\n\\frac{2}{r_{ij}} \\frac{\\partial^2 U}{\\partial r_{iI} \\partial r_{ij}}\n+ 2\\left(\\frac{\\partial^3 U}{\\partial \\rij \\partial^2 \\riI} -\\frac{1}{\\riI} \\frac{\\partial^2 U}{\\partial \\rij \\partial \\riI}\\right)\\frac{\\brij\\cdot\\briI}{\\rij\\riI} + \\frac{\\partial^3 U}{\\partial^3 \\riI} - \\frac{2}{\\riI^2} \\frac{\\partial U}{ \\partial \\riI} + \\frac{2}{\\riI} \\frac{\\partial^2 U}{\\partial^2 \\riI}\n\\right] \\frac{\\mathbf{I} - \\mathbf{r}_i}{|\\mathbf{I} - \\mathbf{r}_i|} + \\nonumber \\\\\\nonumber \n & & \\sum_{j\\neq i } \\left[ \\frac{\\partial^3U}{\\partial \\rij^2 \\partial \\rjI} + \\frac{2}{\\rij}\\frac{\\partial^2 U}{\\partial \\rjI \\partial \\rij} \n+ 2\\frac{\\partial^3 U}{\\partial \\rij \\partial \\riI \\partial \\rjI}\\frac{\\brij\\cdot\\briI}{\\rij\\riI}\n+\\frac{\\partial^3 U}{\\partial \\riI^2 \\partial \\rjI} + \\frac{2}{\\riI}\\frac{\\partial^2 U}{\\partial \\riI \\partial \\rjI} \\right] \n\\frac{\\mathbf{I} - \\mathbf{r}_j}{|\\mathbf{r}_j - \\mathbf{I}|} + \\\\\\nonumber \n& & \\sum_{j\\neq i } \\left[ -\\frac{2}{\\riI}\\frac{\\partial^2 U}{\\partial \\rij \\partial \\riI}\\right] \\frac{\\mathbf{r}_{ij}}{r_{ij}}\\:.\n\\end{eqnarray}\n\n\n\n\\section{Feature: Reciprocal-space Jastrow factors}\n\\label{sec:feature_kspace_jastrow}\n\n% Written by Kenneth P. Esler, Jr.\n% Document originally included in QMCPACK at src/QMCWaveFunctions/Jastrow/kSpaceJastrowNotes.tex\n% Originally titled ``Notes on Reciprocal-Space Jastrow Factors''\n\n\\renewcommand{\\vG}{\\mathbf{G}}\n\\renewcommand{\\vr}{\\mathbf{r}}\n\\renewcommand{\\vI}{\\mathbf{I}}\n\n\\subsection{Two-body Jastrow}\n\\begin{equation}\nJ_2 = \\sum_{\\vG\\neq \\mathbf{0}}\\sum_{i\\neq j} a_\\vG e^{i\\vG\\cdot(\\vr_i-\\vr_j)}\\:.\n\\end{equation}\nThis may be rewritten as\n\\begin{eqnarray}\nJ_2 & = & \\sum_{\\vG\\neq \\mathbf{0}}\\sum_{i\\neq j} a_\\vG e^{i\\vG\\cdot\\vr_i}e^{-i\\vG\\cdot\\vr_j}\\:, \\\\\n& = & \\sum_{\\vG\\neq \\mathbf{0}} a_\\vG \\left\\{\n\\underbrace{\\left[\\sum_i e^{i\\vG\\cdot\\vr_i} \\right]}_{\\rho_\\vG}\n\\underbrace{\\left[\\sum_j e^{-i\\vG\\cdot\\vr_j} \\right]}_{\\rho_{-\\vG}}  -1 \\right\\}\\:.\n\\end{eqnarray}\nThe $-1$ is just a constant term and may be subsumed into the $a_\\vG$\ncoefficient by a simple redefinition.  This leaves a simple, but\ngeneral, form:\n\\begin{equation}\nJ_2 = \\sum_{\\vG\\neq\\mathbf{0}} a_\\vG \\rho_\\vG \\rho_{-\\vG}\\:.\n\\end{equation}\nWe may now further constrain this on physical grounds.  First, we\nrecognize that $J_2$ should be real.  Since $\\rho_{-\\vG} =\n\\rho_\\vG^*$, it follows that $\\rho_{\\vG}\\rho_{-\\vG} = |\\rho_\\vG|^2$ is\nreal, so that $a_\\vG$ must be real.  Furthermore, we group the $\\vG$'s\ninto $(+\\vG, -\\vG)$ pairs and sum over only the positive vectors to\nsave time.\n\n\\subsection{One-body Jastrow}\nThe 1-body Jastrow has a similar form but depends on the\ndisplacement from the electrons to the ions in the system.\n\\begin{equation}\nJ_1 = \\sum_{\\vG\\neq\\mathbf{0}} \\sum_{\\alpha}\n\\sum_{i\\in\\vI^\\alpha}\\sum_{j\\in\\text{elec.}} b^{\\alpha}_\\vG\n  e^{i\\vG\\cdot(\\vI^{\\alpha}_i - \\vr_j)}\\:,\n\\end{equation}\nwhere $\\alpha$ denotes the different ionic species.\nWe may rewrite this in terms of $\\rho^{\\alpha}_\\vG$: \n\\begin{equation}\nJ_1 = \\sum_{\\vG\\neq\\mathbf{0}} \\left[\\sum_\\alpha b^\\alpha_\\vG\n  \\rho_\\vG^\\alpha\\right] \\rho_{-\\vG}\\:,\n\\end{equation}\nwhere\n\\begin{equation}\n\\rho^\\alpha_\\vG = \\sum_{i\\in\\vI^\\alpha} e^{i\\vG\\cdot\\vI^\\alpha_i}\\:.\n\\end{equation}\nWe note that in the preceding equation, for a single configuration of the\nions, the sum in brackets can be rewritten as a single constant.  This\nimplies that the per-species 1-body coefficients, $b^\\alpha_\\vG$, are\nunderdetermined for single configuration of the ions.  In general, if\nwe have $N$ species, we need $N$ linearly independent ion\nconfigurations to uniquely determine $b^{\\alpha}_\\vG$.  For this\nreason, we will drop the $\\alpha$ superscript of $b_\\vG$ for now.  \n\nIf we do desire to find a reciprocal space 1-body Jastrow that is\ntransferable to systems with different ion positions and $N$ \nionic species, we must perform compute $b_\\vG$ for $N$ different ion\nconfigurations.  We may then construct $N$ equations at each value of\n$\\vG$ to solve for the $N$ unknown values, $b^\\alpha_\\vG$.\n\nIn the 2-body case, $a_\\vG$ was constrained to be real by the fact\nthat $\\rho_\\vG \\rho_{-\\vG}$ was real.  However, in the 1-body case,\nthere is no such guarantee about $\\rho^\\alpha_\\vG \\rho_\\vG$.\nTherefore, in general, $b_\\vG$ may be complex.\n\n\\subsection{Symmetry considerations}\nFor a crystal, many of the $\\vG$-vectors will be equivalent by\nsymmetry.  It is useful then to divide the $\\vG$-vectors into\nsymmetry-related groups and then require that they share a common\ncoefficient.  Two vectors, $\\vG$ and $\\vG'$, may be considered to be\nsymmetry related if, for all $\\alpha$ and $\\beta$\n\\begin{equation}\n\\rho^\\alpha_\\vG \\rho^\\beta_{-\\vG} = \\rho^\\alpha_{\\vG'} \\rho^\\beta_{-\\vG'}\\:. \n\\end{equation}\nFor the 1-body term, we may also omit from our list of $\\vG$-vectors\nthose for which all species structure factors are zero.  This is\nequivalent to saying that if we are tiling a primitive cell we\nshould include only the $\\vG$-vectors of the primitive cell and not\nthe supercell.  Note that this is not the case for the 2-body term\nsince the XC hole should not have the periodicity of\nthe primitive cell.\n\n\\subsection{Gradients and Laplacians}\n\\begin{eqnarray}\n\\nabla_{\\vr_i} J_2 & = & \\sum_{\\vG \\neq 0} a_\\vG \\left[\\left(\\nabla_{\\vr_i}\\rho_\\vG\\right) \\rho_{-\\vG} + \\text{c.c.}\\right]\\:, \\\\\n& = & \\sum_{\\vG\\neq \\mathbf{0}} 2\\vG a_\\vG \\mathbf{Re}\\left(i e^{i\\vG\\cdot\\vr_i} \\rho_{-\\vG} \\right)\\:, \\\\\n& = & \\sum_{\\vG\\neq \\mathbf{0}} -2\\vG a_\\vG\\mathbf{Im}\\left(e^{i\\vG\\cdot\\vr_i} \\rho_{-\\vG} \\right)\\:.\n\\end{eqnarray}\nThe Laplacian is then given by\n\\begin{eqnarray}\n  \\nabla^2 J_2 & = & \\sum_{\\vG\\neq\\mathbf{0}} a_\\vG \\left[\\left(\\nabla^2 \\rho_\\vG\\right) \\rho_{-\\vG} + \\text{c.c.} \n  + 2\\left(\\nabla \\rho_\\vG)\\cdot(\\nabla \\rho_{-\\vG}\\right)\\right]\\:, \\\\\n& = & \\sum_{\\vG\\neq\\mathbf{0}} a_\\vG \\left[ -2G^2\\mathbf{Re}(e^{i\\vG\\cdot\\vr_i}\\rho_{-\\vG}) + \n    2\\left(i\\vG e^{i\\vG\\cdot\\vr_i}\\right) \\cdot \\left(-i\\vG e^{-i\\vG\\cdot\\vr_i}\\right)\n\\right]\\:, \\\\\n& = & 2 \\sum_{\\vG\\neq\\mathbf{0}} G^2 a_\\vG  \\left[-\\mathbf{Re}\\left(e^{i\\vG\\cdot\\vr_i}\\rho_{-\\vG}\\right) + 1\\right]\\:. \n%  \\nabla^2_{\\vr_i} J_2 & = & \\nabla_{\\vr_i} \\cdot \\nabla_{\\vr_i} J_2 \\\\\n%  & = & -2\\sum_{\\vG \\neq \\mathbf{0}} a_\\vG \\vG \\cdot \\nabla_{\\vr_i} \\mathbf{Im}\\left(e^{i\\vG\\cdot\\vr_i} \\rho_{-\\vG}\\right)\n%  & = & -2\\sum_{\\vG \\neq \\mathbf{0}} a_\\vG \\vG \\cdot \\mathbf{Im}\\left(i\\vG e^{i\\vG\\cdot\\vr_i}\\rho_{-\\vG} -i\\vG \\right)\n\\end{eqnarray}\n\n", "meta": {"hexsha": "4aff256a05761f22fb4485ccc0b01c4ef505fb94", "size": 103330, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "legacy_manual/design_features.tex", "max_stars_repo_name": "djstaros/qmcpack", "max_stars_repo_head_hexsha": "280f67e638bae280448b47fa618f05b848c530d2", "max_stars_repo_licenses": ["NCSA"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "legacy_manual/design_features.tex", "max_issues_repo_name": "djstaros/qmcpack", "max_issues_repo_head_hexsha": "280f67e638bae280448b47fa618f05b848c530d2", "max_issues_repo_licenses": ["NCSA"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "legacy_manual/design_features.tex", "max_forks_repo_name": "djstaros/qmcpack", "max_forks_repo_head_hexsha": "280f67e638bae280448b47fa618f05b848c530d2", "max_forks_repo_licenses": ["NCSA"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.8675640469, "max_line_length": 309, "alphanum_fraction": 0.6497919288, "num_tokens": 38638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631556226292, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.33927474324713147}}
{"text": " \\begin{table}[!ht]\n  \\begin{tabular}{|l|l|}\n    \\hline\n    author  & O.Bonnefon, V. Acary\\\\\n    \\hline\n    date    & Sept, 07, 2007 \\\\ \n    last update        & Feb, 2011 \\\\\n                       & April, 2014 \\\\\n    \\hline\n    version &  \\\\\n    \\hline\n  \\end{tabular}\n\\end{table}\n\n\n\nThis section is devoted to the implementation and the study  of the algorithm. The interval of integration is $[0,T]$, $T>0$, and a grid $t_{0}=0$, $t_{k+1}=t_{k}+h$, $k \\geq 0$, $t_{N}=T$ is constructed. The approximation of a function $f(\\cdot)$ on $[0,T]$ is denoted as $f^{N}(\\cdot)$, and is a piecewise constant function, constant on the intervals $[t_{k},t_{k+1})$. We denote $f^{N}(t_{k})$ as $f_{k}$. The time-step is $h>0$. \n\n\n\\section{Various first order dynamical systems with input/output relations}\n\n\\paragraph{FirstOrderR. Fully nonlinear case}\nLet us introduce the following system, \n\\begin{equation}\n\\begin{array}{l}\nM \\dot{x}(t) = f(x(t),t) + r(t)  \\\\[2mm]\ny(t) = h(t,x(t),\\lambda (t)) \\\\[2mm]\nr(t) = g(t,x(t),\\lambda (t) ) \\\\[2mm]\n\\end{array}\n\\label{first-DS}\n\\end{equation}\nwhere $\\lambda(t) \\in \\RR^m$  and $y(t) \\in \\RR^m$ are  complementary variables related through a multi-valued mapping.   According to the class of systems, we are studying, the function $f$ and $g$ are defined by a fully nonlinear framework or by affine functions. We have decided to present the time-discretization in its full generality and specialize the algorithms for each cases in Section~\\ref{Sec:Spec}. This fully nonlinear case is not  implemented in Siconos yet. This fully general case is not yet implemented in Siconos.\n\nThis case is implemented in Siconos with the relation {\\tt FirstOrderR} using the subtype {NonLinearR}\n\n\\paragraph{FirstOrderType1R}\nLet us introduce a new notation,\n\\begin{equation}\n\\begin{array}{l}\nM \\dot{x}(t) = f(x(t),t) + r(t)  \\\\[2mm]\ny(t) = h(t,x(t)) \\\\[2mm]\nr(t) = g(t,\\lambda (t) ) \\\\[2mm]\n\\end{array}\n\\label{first-DS1}\n\\end{equation}\nThis case is implemented in Siconos with the relation {\\tt FirstOrderType1R}.\n\n\n\n\\paragraph{FirstOrderType2R}\nLet us introduce a new notation, \n\\begin{equation}\n\\begin{array}{l}\nM \\dot{x}(t) = f(x(t),t) + r(t)  \\\\[2mm]\ny(t) = h(t,x(t),\\lambda (t)) \\\\[2mm]\nr(t) = g(t,\\lambda (t) ) \\\\[2mm]\n\\end{array}\n\\label{first-DS2}\n\\end{equation}\nThis case is implemented in Siconos with the relation {\\tt FirstOrderType2R}.\n\n\n\n\n\\paragraph{Linear case }Let us introduce a new notation, \n\\begin{equation}\n\\begin{array}{l}\nM \\dot{x}(t) = Ax(t) + r(t)  +b(t)\\\\[2mm]\ny(t) = h(x(t),\\lambda (t),z) = Cx + Fz + D \\lambda  \\\\[2mm]\nr(t) = g(t,\\lambda (t) ) = B \\lambda \\\\[2mm]\n\\end{array}\n\\label{first-DS3}\n\\end{equation}\n\n\n\\section{Time--discretizations}\n\n\n\n\\subsection{Standard $\\theta-\\gamma$ scheme.}\nLet us now proceed with the time discretization of (\\ref{first-DS3}) by a fully implicit scheme : \n\\begin{equation}\n  \\begin{array}{l}\n    \\label{eq:toto1}\n     M x_{k+1} = M x_{k} +h\\theta f(x_{k+1},t_{k+1})+h(1-\\theta) f(x_k,t_k) + h \\gamma r(t_{k+1})\n     + h(1-\\gamma)r(t_k)  \\\\[2mm]\n     y_{k+1} =  h(t_{k+1},x_{k+1},\\lambda_{k+1}) \\\\[2mm]\n     r_{k+1} =  g(t_{k+1},x_{k+1},\\lambda_{k+1})\\\\[2mm]\n     \\mbox{NsLaw} ( y_{k+1} , \\lambda_{k+1})\n  \\end{array}\n\\end{equation}\nwhere $\\theta = [0,1]$ and $\\gamma \\in [0,1]$. As in \\cite{acary2008}, we call the problem \\eqref{eq:toto1} the ``one--step nonsmooth problem''.\n\nIn the Siconos/Kernel module, the use of $\\gamma$  is activated in the class {\\tt EulerMoreauOSI} by the boolean {\\tt \\_useGamma}.\n\n\n\n This time-discretization is slightly more general than a standard implicit Euler scheme. The main discrepancy lies in the choice of a $\\theta$-method to integrate the nonlinear term. For $\\theta=0$, we retrieve the explicit integration of the smooth and  single valued term $f$. Moreover for $\\gamma =0$, the term $g$ is explicitly evaluated. The flexibility in the choice of $\\theta$ and $\\gamma$ allows the user to improve and control the accuracy, the stability and the numerical damping of the proposed method. For instance, if the smooth dynamics given by $f$ is stiff, or if we have to use big step sizes for practical reasons, the choice of $\\theta > 1/2$ offers better stability with the respect to $h$.\n\n\\subsection{Full $\\theta-\\gamma$ scheme}\n\nAnother possible time--discretization is as follows.\n\\begin{equation}\n  \\begin{array}{l}\n    \\label{eq:toto1-ter}\n    M x_{k+1} = M x_{k} + h\\theta f(x_{k+1},t_{k+1})+h(1-\\theta) f(x_k,t_k) + h r(t_{k+\\gamma}) \\\\[2mm]\n    y_{k+\\gamma} = h(t_{k+\\gamma},x_{k+\\gamma},\\lambda _{k+\\gamma}) \\\\[2mm]\n    r_{k+\\gamma} = g(t_{k+\\gamma},x_{k+\\gamma},\\lambda _{k+\\gamma})\\\\[2mm]\n    \\mbox{NsLaw} ( y_{k+\\gamma} , \\lambda_{k+\\gamma})\n  \\end{array}\n\\end{equation}\nWe call the scheme~(\\ref{eq:toto1-ter}) the full $\\theta-\\gamma$ scheme since it uses also the evaluation at $t_{k+\\gamma}$ for the relation.\n\nIn the Siconos/Kernel module, the time--stepping scheme is activated in the class {\\tt EulerMoreauOSI} by the boolean {\\tt \\_useGammaForRelation}.\n\n\nAnother possibility for the time discretization in the nonlinear case would be\n\\begin{equation}\n  \\begin{array}{l}\n    \\label{eq:toto1-quat}\n    M x_{k+1} = M x_{k} +h f(x_{k+\\theta},t_{k+\\theta}) + h r(t_{k+\\gamma}) \\\\[2mm]\n    y_{k+\\gamma} =  h(t_{k+\\gamma},x_{k+\\gamma},\\lambda _{k+\\gamma}) \\\\[2mm]\n    r_{k+\\gamma} = g(t_{k+\\gamma},x_{k+\\gamma},\\lambda _{k+\\gamma})\\\\[2mm]\n    \\mbox{NsLaw} ( y_{k+\\gamma} , \\lambda_{k+\\gamma})\n  \\end{array}\n\\end{equation}\nThis scheme has not been yet implemented in Siconos/Kernel.\n\n\\clearpage\n\\section{Newton's linearization of~(\\ref{eq:toto1})} \n\n\\input{MCP_linearized.tex}\n%\\input{MCP_linearized_old.tex}\n\n\n\n\\input{MCP_linearized_2.tex}\n\\input{MCP_linearized_linear.tex}\n\n\n\n\\section{Newton's linearization of~ (\\ref{eq:toto1-ter}) }\n\n\\input{MCP-FullThetaGamma.tex}\n\n%%% Local Variables: \n%%% mode: latex\n%%% TeX-master: \"DevNotes\"\n%%% End: \n", "meta": {"hexsha": "39bb20830483d08278deef46562815b918f2e14c", "size": 5877, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/sphinx/devel_guide/notes/chapterNewton.tex", "max_stars_repo_name": "ljktest/siconos", "max_stars_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "docs/sphinx/devel_guide/notes/chapterNewton.tex", "max_issues_repo_name": "ljktest/siconos", "max_issues_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "docs/sphinx/devel_guide/notes/chapterNewton.tex", "max_forks_repo_name": "ljktest/siconos", "max_forks_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 39.18, "max_line_length": 712, "alphanum_fraction": 0.6639441892, "num_tokens": 2020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.339274742249438}}
{"text": "% File SDSS2020_SampleExtendedAbstract.tex\n\\documentclass[10pt]{article}\n\\usepackage{sdss2020} % Uses Times Roman font (either newtx or times package)\n\\usepackage{url}\n\\usepackage{latexsym}\n\\usepackage{amsmath, amsthm, amsfonts}\n\\usepackage{algorithm, algorithmic}  \n\\usepackage{graphicx}\n\n\\title{Sparse Bayesian Predictive Modelling of Tumor Response \n\tfrom Radiomic Data}\n\n\\author{\n  Shirin Golchi\\\\\n  Department of Biostatistics\\\\ McGill University \\\\\n  Purvis Hall, 1020 Pine Ave W\\\\\n  Montreal QC H3A 1A2 \\\\ \n  {\\tt shirin.golchi@mcgill.ca} \\\\\\And\n  Reza Forghani \\\\\n  Department of Diagnostic Radiology \\\\ McGill University \\\\\n  1650 Cedar Avenue \\\\\n  Montreal QC H3G 1A4 \\\\\n  {\\tt reza.forghani@mcgill.ca} \\\\\\And\n  Sahir Bhatnagar \\\\\n  Department of Biostatistics\\\\ Department of Diagnostic Radiology \\\\ McGill University \\\\\n  Purvis Hall, 1020 Pine Ave W\\\\\n  Montreal QC H3A 1A2 \\\\\n  {\\tt sahir.bhatnagar@mcgill.ca} \n}\n  \n\n\\date{}\n\n\\begin{document}\n\\maketitle\n\\begin{abstract}\nWe propose a Bayesian hierarchical model for the analysis of radiomic data for characterization of head and neck squamous cell carcinoma (HNSCC). The proposed model facilitates radiomic feature selection, dealing with missing values in key predictors as well as prediction in a unified framework. \n\n\n\\end{abstract}\n\n{\\bf Keywords:} Radiomics, Multilevel Modeling, Horseshoe prior, Missing Data\n\n\\section{Introduction}\n\nAn important objective in oncology is the creation of a standardized set of criteria to predict and monitor tumor response to treatment and for outcome prognosis based on objectively measured biomarkers. In addition to the traditional role of imaging for staging and post treatment follow-up of HNSCC, there is increasing interest in the use of quantitative image extracted or radiomic features for characterization of HNSCC. Image analysis algorithms extract mathematically defined features of the tumor's appearance giving rise to high-dimensional matrix covariates. \n\nMany challenges arise from the structure of radiomic data. Namely, an efficient and reliable variable selection technique is required to select a reasonable number of radiomic features to be used in prediction of key outcomes such as lymph node metastasis. Variable selection and prediction should reflect the heterogenity among tumor sites, however, site-stratified inference can result in low statistical power. In addition, there is a considerable amount of missing data among important predictors such as the presence/absence of human papilloma virus (HPV). \n\nWe propose a Bayesian hierarchical model that can address radiomic feature selection and prediction in a unified framework while dealing with complexities such as missing values in predictors. The hierarchical nature of the model enables information borrowing across tumor sites while allowing site-specific variable selection and parameter estimation. Integrating variable selection and missing data handling together with inference, results in predictions with adequate representation of uncertainty associated with each of these procedures. We present the results of the analysis as Bayesian feature selection outcomes across sites and the accuracy for predictions of lymph node metastasis.\n\n\\section{Methods}\n\nBelow we describe a Bayesian hierarchical model that takes advantage of regularized horseshoe priors \\cite{PiiVeh2017} to perform site-specific radiomic feature selection while borrowing information across sites.  Let $y_{1n}$ and $y_{2n}$ denote the binary outcomes lymph node metastasis and HPV for patient $n = 1, \\ldots, N$, respectively. While HPV may be predicted by a number of covariates such drinking and smoking habits, it is an important predictor for lymph node metastasis. Therefore, we define the model as follows,\n\\begin{equation}\n\\label{eqn:model}\ny_{1n} \\sim \\text{Bernoulli}(\\pi_{1n}),\\hskip 10pt y_{2n} \\sim \\text{Bernoulli}(\\pi_{2n})\n\\end{equation}\nwhere,\n\\begin{equation*}\n\\text{logit}(\\mathbf{\\pi}_{1n}) = \\phi \\pi_{2n} + \\mathbf{z}_n \\boldsymbol{\\eta}_1+ \\mathbf{x}_n\\boldsymbol{\\beta}_{1s_n}, \\hskip 20pt n = 1, \\ldots,N\n\\end{equation*}\nwhere $\\pi_{2n}$ is the risk of HPV for patient $n$ that is in turn modelled as,\n\\begin{equation*}\n\\text{logit}(\\pi_{2n}) = \\mathbf{z}_n \\boldsymbol{\\eta}_2+ \\mathbf{x}_n\\boldsymbol{\\beta}_{2s_n}, \\hskip 20pt n = 1, \\ldots,N\n\\end{equation*}\nwhere $s_n = 1,\\ldots, S$ are the tumor site, $ \\mathbf{z}_n$ are the set of covariates (drinking, smoking and T-stage group)  and  $\\mathbf{x}_n$ is the $F\\times 1$ vector of radiomic features for patient $n$.\n\nAllowing for the feature selection to be performed separately across the three sites introduces $F\\times S$ coefficients. The notation $\\boldsymbol{\\beta}_{s_n}$ is used to represent the site-specific set of the radiomic feature coefficients matrix.\n\nFollowing \\cite{PiiVeh2017} the coefficients, $\\beta_j$, $j = 1, \\ldots, J$, of the radiomic features are assigned the following prior distribution,\n\\begin{align*}\n&\\beta_{j,s_n} \\sim \\mathcal{N}(0, \\tau^2_{s_n}\\tilde{\\lambda}_j^2)\\\\\n& \\tilde{\\lambda}_j^2 = \\frac{c^2\\lambda_j^2}{c^2 + c^2\\lambda_j^2}\n\\end{align*}\nwhere \n\\begin{align*}\n&\\lambda_j \\sim \\mathcal{C}^+(0,1),\\\\\n& c^2\\sim \\mathcal{IG}(\\frac{\\nu}{2},\\frac{\\nu}{2}s^2),\\\\\n& \\tau_{s_n} \\sim \\mathcal{C}^+(0, \\tau_0).\n\\end{align*}\nwhere $\\nu = 20$, $s^2 = 4$ and $\\tau_0=0.001$. These values are chosen according to recommendations in \\cite{PiiVeh2017}. Note the subscript $s_n$ for parameter $\\tau$ that represents the site specific variance for $\\beta_{j,s_n}$. \n\nAs mentioned earlier, a considerable portion of the patients have a missing HPV outcome. The above model is dealing with this issue by augmenting the HPV data with the unknown values of HPV and estimating the missing values together with the rest of the model parameters. \n\nThe inference relies on the posterior distribution of parameters of interest, i.e., $(\\phi, \\boldsymbol{\\eta}_1, \\boldsymbol{\\eta}_2, \\boldsymbol{\\beta}_{1s_n}, \\boldsymbol{\\beta}_{2s_n})$. Sampling from the posterior is performed using Stan.\n\n\\section{Data/Results}\n\nThe data comprise 603 contrast enhanced pre-treatment neck CT scans evaluated from patients diagnosed with HNSCC, with tumors arising in three sites: 241 from the larynx or hypopharynx (LHP), 162 oral cavity (OC), and 200 oropharynx (OP), further stratified based on HPV status to avoid its confounding effects. HPV status was missing in 55\\% of the sample, with 175 missing from the LHC, 3 from the OPC and 155 from the OSCC. First order texture features with additional filtrations were extracted from each tumor using TexRAD software (TexRAD; University of Sussex, Falmer, England) and used in conjunction with patient age, smoking status, drinking status, and tumor T-stage to construct models for predicting lymph node metastasis, the presence of lymphovascular invasion (LVI) and perineural invasion (PNI).\n%***Can you please add a little more about the missing portions, etc?***\nWe apply the proposed model to the described data set. Figure~\\ref{fig1} shows the point estimates and 95\\% credible intervals of the radiomic features by tumor site. Only a handful of radiomic features are selected by the shrinkage prior to predict the lymph node metastasis and selected features vary by tumor site. \n\n\\begin{figure}[htbp]\n\t\\begin{center}\n\t\t\\centerline{\\includegraphics[width=\\columnwidth]{mv_NS_feat.png}}\n\t\t\\caption{Site-specific point estimates and 95\\% credible intervals for the radiomic feature coefficients in the predictive model for lymph node metastasis}\n\t\t\\label{fig1}\n\t\\end{center}\n\\end{figure}\n\nPrediction accuracy of the proposed model is illustrated in Figure~\\ref{fig2} in form of 100 draws from the posterior distribution of the Receiver Operating Curves (ROC). The Area Under the Curve (AUC) varies from 0.81 to 0.84.\n\n\n\n\\begin{figure}[htbp]\n\t\\begin{center}\n\t\t\\centerline{\\includegraphics[width=0.9\\columnwidth]{ROC.png}}\n\t\t\\caption{Posterior draws from the Receiver Operating Curve for prediction of lymph node metastasis; The Area Under the Curve varies from 0.81 to 0.84.}\n\t\t\\label{fig2}\n\t\\end{center}\n\\end{figure}\n\n\n\n\\section{Discussion/Conclusions}\n\nWe have proposed a Bayesian hierarchical predictive model to analyse complex and high dimensional radiomic data. The novelty of the proposed model is in dealing with multiple challenging issues within a unified framework.  Namely, variable selection, missing data imputation and prediction are performed simultaneously within the proposed model. The main advantage of integrating variable (feature) selection and missing data handling together with estimation and prediction over multi-step procedures, is adequate representation of uncertainty in the final results. We further compared our apporach to popular machine learning techniques often used in the radiomics literature. For example, the random forest method applied to this data achieved an AUC of 0.76, but there was no way to obtain a site specific feature importance measure and HPV status was ignored in the training due to missingness. \n%*** Any comments regarding the performance in compare to existing methods? ***\n\n\n\n\\bibliographystyle{sdss2020} % Please do not change the bibliography style\n\\bibliography{SampleReferencesForExtendedAbstract}\n\n\\end{document}\n", "meta": {"hexsha": "3256e2ee13cee8acfeab61f88e8a90e92e8e6e67", "size": 9288, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "sdss/SDSS2021-LaTEX/SampleExtendedAbstract_SDSS2020.tex", "max_stars_repo_name": "sahirbhatnagar/radbayes", "max_stars_repo_head_hexsha": "bdfad47eaa2841d06608b63c1e1cfe85609b91c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sdss/SDSS2021-LaTEX/SampleExtendedAbstract_SDSS2020.tex", "max_issues_repo_name": "sahirbhatnagar/radbayes", "max_issues_repo_head_hexsha": "bdfad47eaa2841d06608b63c1e1cfe85609b91c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdss/SDSS2021-LaTEX/SampleExtendedAbstract_SDSS2020.tex", "max_forks_repo_name": "sahirbhatnagar/radbayes", "max_forks_repo_head_hexsha": "bdfad47eaa2841d06608b63c1e1cfe85609b91c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 73.1338582677, "max_line_length": 900, "alphanum_fraction": 0.7812230835, "num_tokens": 2347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982315512488, "lm_q2_score": 0.5234203489363239, "lm_q1q2_score": 0.3390707763988882}}
{"text": "\\documentclass[12pt,letterpaper]{article}\n\\usepackage{fullpage}\n\\usepackage[top=2cm, bottom=4.5cm, left=2.5cm, right=2.5cm]{geometry}\n\\usepackage{amsmath,amsthm,amsfonts,amssymb,amscd}\n\\usepackage{hyperref}\n% \\usepackage{xcolor}\n\\usepackage[dvipsnames]{xcolor}\n\\usepackage{fancyhdr}\n\\usepackage{mathrsfs}\n\\usepackage{amsmath}\n\\usepackage{dsfont}\n\n\\usepackage{mathtools}\n\\DeclarePairedDelimiter{\\ceil}{\\lceil}{\\rceil}\n\\DeclarePairedDelimiter{\\set}{\\left\\{}{\\right\\}}\n\n\\usepackage{fontspec}\n\n\\setromanfont{PTSerif}[\n    Path=./fonts/,\n    Extension = .ttf,\n    UprightFont = *-Regular,\n    BoldFont = *-Bold,\n    ItalicFont = *-Italic,\n    BoldItalicFont = *-BoldItalic,\n]\n\n\\hypersetup{%\n  colorlinks=true,\n  linkcolor=blue,\n  linkbordercolor={0 0 1}\n}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Define Colors\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\definecolor{light-gray}{gray}{0.85}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\newcommand\\hwnumber{16}\n\\newcommand\\student{Ivan Zhytkevych}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\pagestyle{fancyplain}\n\\headheight 35pt\n\\lhead{\\textit{\\student}}\n\\chead{\\textbf{\\Large PT Homework \\hwnumber}}\n\\rhead{\\textit{\\today}}\n\\lfoot{}\n\\cfoot{}\n\\rfoot{\\small\\thepage}\n\\headsep 1.5em\n\n% \\usepackage{import}\n% \\usepackage{pdfpages}\n% \\usepackage{transparent}\n% \\usepackage{xcolor}\n\n% \\newcommand{\\incfig}[2][1]{%\n%     \\def\\svgwidth{#1\\columnwidth}\n%     \\import{./figures/}{#2.pdf_tex}\n% }\n\\usepackage{import}\n\\usepackage{xifthen}\n\\usepackage{pdfpages}\n\\usepackage{transparent}\n\n\\newcommand{\\incfig}[1]{%\n    \\def\\svgwidth{\\columnwidth}\n    \\import{./figures/}{#1.pdf_tex}\n}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{document}\n% \\tableofcontents\n% \\newpage\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section*{Problem 15.18}\n\n\\[ \\varphi_{S_n}(t) = \\varphi_{\\xi_1 + \\xi_2 + \\dots + \\xi_n}(t) = \\varphi_{\\xi_1}(t) \\dots \\varphi_{\\xi_n}(t) \\]\n\\[ \\varphi_{\\xi_i}(t) = \\sum_{k=1}^{\\infty} e^{itx_k} \\cdot P(\\xi = x_k) =\n\\frac{1}{2} e^{-it} + \\frac{1}{2} \\cdot e^{it} =  \\cos(t) \\]\n\\[ \\varphi_{S_n}(t) = \\cos^n (t) \\]\n\n\\begin{figure}[ht]\n    \\centering\n    \\incfig{graph}\n    \\caption{Graph}\n    \\label{fig:graph}\n\\end{figure}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section*{Problem 11.21}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section*{Problem 11.22}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section*{Problem 11.23}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section*{Problem 11.24}\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section*{Problem 11.25}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\end{document}\n\n", "meta": {"hexsha": "5ac2eaac4fcfe30f131f65cf74d2f24751718699", "size": 3027, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "homeworks/probability/hw16/master.tex", "max_stars_repo_name": "aipyth/notes", "max_stars_repo_head_hexsha": "59066a1110ea467b2aa43518da9295f23da89a32", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/probability/hw16/master.tex", "max_issues_repo_name": "aipyth/notes", "max_issues_repo_head_hexsha": "59066a1110ea467b2aa43518da9295f23da89a32", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/probability/hw16/master.tex", "max_forks_repo_name": "aipyth/notes", "max_forks_repo_head_hexsha": "59066a1110ea467b2aa43518da9295f23da89a32", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5526315789, "max_line_length": 113, "alphanum_fraction": 0.4648166501, "num_tokens": 838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.33907076320808865}}
{"text": "\\documentclass{article}\n\\usepackage{graphicx}\n\\usepackage[utf8]{inputenc}\n\\usepackage{amsmath, amssymb, latexsym}\n\n\\usepackage{pgfplots}\n\\usepackage{algorithm}\n\\usepackage[noend]{algpseudocode}\n\\usepackage{tikz}\n\\usepackage{nicefrac}\n\\usepackage{placeins}\n\\pgfplotsset{every axis legend/.append style={\nat={(0,0)},\nanchor=north east}}\n\\usetikzlibrary{shapes,positioning,intersections,quotes}\n\\usetikzlibrary{arrows.meta,\n                bending,\n                intersections,\n                quotes,\n                shapes.geometric}\n                \n\\definecolor{darkgreen}{rgb}{0.0, 0.6, 0.0}\n\\definecolor{darkred}{rgb}{0.7, 0.0, 0.0}\n\\makeatletter\n\\def\\BState{\\State\\hskip-\\ALG@thistlm}\n\\makeatother\n\\title{Week 17}\n\\begin{document}\n\\pagenumbering{gobble}\n\\maketitle\n\\newpage\n\\pagenumbering{arabic}\n\n\\section*{Learning with large datasets}\nTaking a low bias algorithm and training it on a large amount of data is one of the greatest approaches to get high performance.\n\n\\begin{itemize}\n  \\item Assume we have a data collection with m = 100,000, 000.\n  \\item On such a large system, how can we train a logistic regression model?\n\n        $$\\theta_j := \\theta_j - \\alpha \\frac{1}{m} \\sum_{i=1}^m(h_{\\theta}(x^{(i)})- y^{(i)})x_j^{(i)}$$\n\n  \\item As a result, for each gradient descent step, you must add up more than 100,000,000 terms.\n  \\item The first step is to inquire whether we may train on 1000 examples rather than 100 000 000.\n  \\item Pick a small sample at random. Can you build a system that performs well?\n\\end{itemize}\n\n~\\\\\n\\includegraphics[width=0.5\\textwidth]{resources/learning_curve}\n\n\\begin{itemize}\n  \\item If the gap is large, it is a high variance problem. More examples should lead to better results.\n  \\item If the gap is tiny, it is a high bias problem. More examples may not be beneficial.\n\\end{itemize}\n\n\\section*{Stochastic Gradient Descent}\n\nHypothesis:\n$$h_{\\theta}(x) = \\sum_{n}^{j=0}\\theta_jx_j$$\n\n~\\\\\nCost function:\n$$\\quad J_{train}(\\theta) = \\frac{1}{2m} \\sum_{m}^{i=1}(h_{\\theta}(x^{(i)}) - y^{(i)})^2$$\n\n~\\\\\nWe get bowl shape surface plots if we plot our two parameters against the cost function:\n\n\\includegraphics[width=0.5\\textwidth]{resources/surface_cost_function}\n\n~\\\\\nHow does gradient descent work?\n\n\\begin{algorithm}\n  \\caption{Gradient Descent}\\label{euclid}\n  \\begin{algorithmic}[1]\n    \\Large\n    \\While {not converged}\n    \\State $\\theta_j := \\theta_j - \\alpha \\frac{\\partial}{\\partial \\theta_j} J(\\theta_0, ..., \\theta_n)$\n    \\State $(for\\ j = 0, ..., n)$\n    \\EndWhile\n  \\end{algorithmic}\n\\end{algorithm}\n\n~\\\\\nAlthough we have just referred to it as gradient descent so far, this type of gradient descent is known as batch gradient descent. This simply implies that we examine all of the examples at the same time. Batch gradient descent is unsuitable for large datasets.\n\n~\\\\\nWhen discussing stochastic gradient descent, we will use linear regression as an algorithmic example, however the concepts apply to other algorithms as well, such as logistic regression and neural networks.\n\n~\\\\\nDefine our cost function in a slightly different way, as follows:\n$$\\quad J_{train}(\\theta) = \\frac{1}{m} \\sum_{m}^{i=1}cost(\\theta, (x^{(i)}, y^{(i)}))$$\n$$cost(\\theta, (x^{(i)}, y^{(i)}))=\\frac{1}{2}(h_{\\theta}(x^{(i)}) - y^{(i)})^2$$\n\n\\FloatBarrier\n\\begin{algorithm}\n  \\caption{Stochastic Gradient Descent}\\label{euclid}\n  \\begin{algorithmic}[1]\n    \\Large\n    \\State Randomly shuffle training examples\n    \\For{\\texttt{$i:=1,...,m$}}\n    \\State \\texttt{$\\theta_j := \\theta_j - \\alpha (h_{\\theta}(x^{(i)}) - y^{(i)})x_j^{(i)}$}\n    \\State \\texttt{$(for\\ j = 0, ..., n)$}\n    \\EndFor\n  \\end{algorithmic}\n\\end{algorithm}\n\\FloatBarrier\n\nThe random shuffling at the start ensures that the data is in a random sequence, preventing bias in the movement.\n\n~\\\\\nAlthough stochastic gradient descent is similar to batch gradient descent, instead of waiting for the gradient terms to be summed across all m examples, we pick only one example and make work on enhancing the parameters right away.\n\n~\\\\\nThis means that we change the parameters on EVERY step through the data, rather than at the end of each loop over all of the data.\n\n~\\\\\n\\includegraphics[width=0.6\\textwidth]{resources/stochastic}\n\n~\\\\\nFor our stochastic gradient descent, we might plot the cost function vs the number of iterations.\nWe should be able to see if convergence is occurring by looking at the graphs.\nA smoother curve may be obtained by averaging across many (e.g. 1000 and 5000) instances.\n\n\\includegraphics[width=0.45\\textwidth]{resources/stochastic_convergence}\n\n\\section*{Online learning}\n\n\\begin{itemize}\n  \\item Allows us to model problems in which there is a continuous stream of data from which an algorithm should learn.\n  \\item In the same way that stochastic gradient descent is used, slow updates are performed.\n  \\item To learn from traffic, web companies employ several sorts of online learning algorithms.\n\\end{itemize}\n\n\\subsection*{Example - product search}\n\\begin{itemize}\n  \\item Assume you own a cellphone-selling website.\n  \\item You have a user interface where the user may enter in a query such as \"Android phone 1080p camera.\"\n  \\item We want to provide the user ten phones per query, with the phones ranked from most appealing to the user.\n  \\item We generate a feature vector (x) for each phone based on a specific user query.\n  \\item We want to determine the likelihood of a user picking a phone.\n  \\item $y = 1$ if a user clicks on a link.\n  \\item $y = 0$ otherwise.\n  \\item We learn $p(y=1|x;\\theta)$ - this is the problem of learning the predicted click through rate (CTR).\n  \\item If you can estimate the CTR for any phone, we can utilize it to show the phones with the highest likelihood first.\n\\end{itemize}\n\n\\section*{Map reduce and data parallelism}\nSome problems are simply too large for a single CPU to handle.\n\n~\\\\\n\\includegraphics[width=0.6\\textwidth]{resources/map_reduce}\n\nParallelization can come from:\n\\begin{itemize}\n  \\item Multiple machines.\n  \\item Multiple CPUs.\n  \\item Multiple cores in each CPU.\n\\end{itemize}\n\n~\\\\\nCertain numerical linear algebra libraries can automatically parallelize your calculations over several cores, depending on the implementation details.\nSo, if this is the case and you have a decent vectorization implementation, you don't have to worry about local parallelization because the local libraries will handle optimization for you.\n\n~\\\\\nHadoop is an example of Map Reduce implementation.\n\n\\end{document}\n", "meta": {"hexsha": "8a7f283eb49562ef125ab903c61243a80f17f884", "size": 6492, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "slides/week_17.tex", "max_stars_repo_name": "djeada/Stanford-Machine-Learning", "max_stars_repo_head_hexsha": "e6ef77939b7c581aebb5e9454669ad2dbb4f98f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "slides/week_17.tex", "max_issues_repo_name": "djeada/Stanford-Machine-Learning", "max_issues_repo_head_hexsha": "e6ef77939b7c581aebb5e9454669ad2dbb4f98f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slides/week_17.tex", "max_forks_repo_name": "djeada/Stanford-Machine-Learning", "max_forks_repo_head_hexsha": "e6ef77939b7c581aebb5e9454669ad2dbb4f98f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4142011834, "max_line_length": 261, "alphanum_fraction": 0.7275107825, "num_tokens": 1784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6477982043529716, "lm_q1q2_score": 0.33907076216275656}}
{"text": "% paper # 3887, pw CF8FECE1\n% Note: the original submission was rev. 530... \n% submitted again at 539 before review..\n% Template for SLT-2006 paper; to be used with:\n%          spconf.sty  - ICASSP/ICIP LaTeX style file, and\n%          IEEEbib.bst - IEEE bibliography style file.\n% --------------------------------------------------------------------------\n\\documentclass{article}\n\\usepackage{spconf,amsmath,amssymb,bm,epsfig}\n\\usepackage{color}\n\\usepackage{multirow}\n\n\\definecolor{MidGray}{rgb}{0.3, 0.3, 0.3}\n\\definecolor{Pink}{rgb}{1.0, 0.4, 0.4}\n\\definecolor{Red}{rgb}{0.9, 0.1, 0.1}\n\n% Example definitions.\n% --------------------\n\n%%%%%%\n% Begin Dan's math definitions.\n%%%%%%\n\\def\\Re{{\\mathbb{R}}}\n\\def\\x{{\\mathbf x}}\n\\def\\a{{\\mathbf a}}\n\\def\\U{{\\mathbf U}}\n\\def\\HCLG{{\\mathit{HCLG}}}\n\\def\\bDelta{{\\mathbf \\Delta}}\n\\def\\V{{\\mathbf V}}\n\\def\\u{{\\mathbf u}}\n\\def\\s{{\\mathbf s}}\n\\def\\t{{\\mathbf t}}\n\\def\\G{{\\mathbf G}}\n\\def\\F{{\\mathbf F}}\n\\def\\r{{\\mathbf r}}\n\\def\\semicolonsep{\\,;\\,}\n\\def\\tr{{\\operatorname{tr}\\,}}\n\\def\\z{{\\mathbf z}}\n\\def\\y{{\\mathbf y}}\n\\def\\Y{{\\mathbf Y}}\n\\def\\Z{{\\mathbf Z}}\n\\def\\gammatilde{{\\gamma}}  %% This was \\tilde{\\gamma} in the tutorial, mapping to \\gamma2 to preserve the distinction in the latex source in case later I want to resurrect that.\n\\def\\R{{\\mathbf R}}\n\\def\\D{{\\mathbf D}}\n\\def\\half{ {\\textstyle {\\frac{1}{2}}} }\n\\def\\L{{\\mathbf L}}\n\\def\\P{{\\mathbf P}}\n\\def\\Q{{\\mathbf Q}}\n\\def\\B{{\\mathbf B}}\n\\def\\S{{\\mathbf S}}\n\\def\\T{{\\mathbf T}}\n\\def\\K{{\\mathbf K}}\n\\def\\H{{\\mathbf H}}\n\\def\\g{{\\mathbf g}}\n\\def\\I{{\\mathbf I}}\n\\def\\btheta{{\\mathbf\\theta}}\n\\def\\calN{{\\cal N}}\n\\def\\calQ{{\\cal Q}}\n\\def\\diag{{\\mathrm{diag}}}\n\\def\\pre{{\\mathrm{pre}}}\n\\def\\inv{{\\mathrm{inv}}}\n\\def\\calT{{\\cal T}}\n\\def\\bmu{{\\bm \\mu}} % mathbf does not work for lowercase greek letters!  But mathbf looks better than bm in most other cases so I only use bm here.\n\\def\\bSigma{{\\mathbf \\Sigma}}\n\\def\\M{{\\mathbf M}}\n\\def\\N{{\\mathbf N}}\n\\def\\bv{{\\mathbf v}}\n\\def\\w{{\\mathbf w}}\n\\def\\W{{\\mathbf W}}\n\\def\\A{{\\mathbf A}}\n\\def\\o{{\\mathbf o}}\n\\def\\b{{\\mathbf b}}\n\\def\\p{{\\mathbf p}}\n%%\\newcommand\\refeqn[1]{(\\ref{#1})}\n\n%%%%%%\n% End Dan's math definitions.\n%%%%%%\n\n\n% Title.\n% ------\n\\title{Generating exact lattices in the WFST framework}\n\n\n\\makeatletter\n\\def\\name#1{\\gdef\\@name{#1\\\\}}\n\\makeatother\n\n\\name{ \\em Daniel Povey$^1$, Mirko Hannemann$^{1,2}$,  \\\\\n \\em {Gilles Boulianne}$^3$, {Luk\\'{a}\\v{s} Burget}$^{2,4}$, {Arnab Ghoshal}$^5$, {Milo\\v{s} Janda}$^2$, {Martin Karafi\\'{a}t}$^2$, {Stefan Kombrink}$^2$, \\\\\n  \\em {Petr Motl\\'{i}\\v{c}ek}$^6$, {Yanmin Qian}$^7$, {Korbinian Riedhammer}$^9$, {Karel Vesel\\'{y}}$^2$, {Ngoc Thang Vu}$^8$\n    \\thanks{Thanks to Honza \\v{C}ernock\\'{y}, Renata Kohlov\\'{a}, and Tom\\'{a}\\v{s} Ka\\v{s}p\\'{a}rek for their help relating to the Kaldi'11 workshop at BUT, and to Sanjeev Khudanpur for his help in preparing the paper.  Researchers at BUT were partly supported by Technology Agency of the Czech Republic grant No. TA01011328, Czech Ministry of Education project No. MSM0021630528, and Grant Agency of the Czech Republic project No. 102/08/0707.  Arnab Ghoshal was supported by EC FP7 grant 213850 (SCALE), and by EPSRC grant EP/I031022/1 (NST).}}\n\n\n%%% TODO: fix thanks.\n%\\thanks{Arnab Ghoshal was supported by the European Community's Seventh Framework \n% Programme under grant agreement no. 213850 (SCALE); BUT researchers were partially \n%supported by Czech MPO project No. FR-TI1/034.}}\n       \n\\address{{ $^1$ Microsoft Research, Redmond, WA, {\\normalsize \\tt dpovey@microsoft.com} }\\\\ \n         { $^2$ Brno University of Technology, Czech Republic, {\\normalsize \\tt ihannema@fit.vutbr.cz}} \\\\ \n         { $^3$ CRIM, Montreal, Canada \\ \\  $^4$ SRI International, Menlo Park, CA, USA} \\\\ \n         { $^5$ University of Edinburgh, U.K. \\ \\  $^6$  IDIAP, Martigny, Switzerland } \\\\ \n         { $^7$ Tsinghua University, Beijing, China \\ \\ $^8$ Karlsruhe Institute of Technology, Germany} \\\\ \n         { $^9$ Pattern Recognition Lab, University of Erlangen-Nuremberg, Germany}}\n\n \n\\begin{document}\n\n\n\\ninept  \n%\n\\maketitle\n%\n%\\pagestyle{plain} % was set to empty in spconf.sty... this makes page number appear.\n\n\\begin{abstract}\nWe describe a lattice generation method that is exact, i.e. it satisfies all the \nnatural properties we would want from a lattice of alternative transcriptions of\nan utterance.  This method does not introduce substantial overhead above one-best decoding.  Our method is\nmost directly applicable when using WFST decoders where the WFST is\n``fully expanded'', i.e. where the arcs correspond to HMM transitions.  It outputs\nlattices that include HMM-state-level alignments as well as word labels.\nThe general idea is to create a state-level lattice during decoding, and to do\na special form of determinization that retains only the best-scoring path\nfor each word sequence.  \nThis special determinization algorithm is a solution to the following problem:\nGiven a WFST A, compute a WFST B that, for each input-symbol-sequence of A,\ncontains just the lowest-cost path through A.\n\\end{abstract}\n\n\\begin{keywords}\n  Speech Recognition, Lattice Generation\n\\end{keywords}\n\n\\vspace*{-0.075in}\n\\section{Introduction}\n\\vspace*{-0.05in}\n\nIn Section~\\ref{sec:wfst} we give a Weighted Finite State Transducer\n(WFST) interpretation of the speech-recognition decoding problem, in order\nto introduce notation for the rest of the paper.  In Section~\\ref{sec:lattices}\nwe define the lattice generation problem, and in Section~\\ref{sec:previous}\nwe review previous work.\nIn Section~\\ref{sec:overview} we give an overview of our method,\nand in Section~\\ref{sec:details} we summarize some aspects of a determinization\nalgorithm that we use in our method.  In Section~\\ref{sec:exp} we give\nexperimental results, and in Section~\\ref{sec:conc} we conclude.\n\n\\vspace*{-0.075in}\n\\section{WFSTs and the decoding problem}\n\\vspace*{-0.05in}\n\\label{sec:wfst}\n\nThe graph creation process we use in our toolkit, Kaldi~\\cite{kaldi_paper},\nis very close to the standard recipe described in~\\cite{wfst},\nwhere the Weighted Finite State Transducer (WFST) decoding graph is\n\\begin{equation}\n  \\HCLG = \\min(\\det(H \\circ C \\circ L \\circ G)),\n\\end{equation}\nwhere $H$, $C$, $L$ and $G$ represent the HMM structure, phonetic\ncontext-dependency, lexicon and grammar respectively, \nand $\\circ$ is WFST composition (note: view $\\HCLG$ as a single symbol).\nFor concreteness we will speak of ``costs'' rather\nthan weights, where a cost is a floating point number that typically represents a negated\nlog-probability.  A WFST has a set of states with one distinguished\nstart state\\footnote{This is the formulation that corresponds best with the toolkit we use.};\neach state has a final-cost (or $\\infty$ for non-final states);\nand there is a set of arcs between the states, where each arc has an\ninput label, an output label, and a weight\n(just think of this as a cost for now).\nIn $\\HCLG$, the input labels are the identifiers of context-dependent\nHMM states, and the output labels represent words.  For both the input and output\nlabels, the special symbol $\\epsilon$ may appear, meaning ``no label is present.''\n\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[height=2.1in,angle=270]{figures/acceptor_utterance.eps}\n\\vspace*{-0.03in}\n  \\caption{Acceptor $U$ describing the acoustic scores of an utterance}\n\\vspace*{-0.15in}\n\\label{fig:acceptor}\n\\end{center}\n\n\\end{figure}\n\nImagine we want to ``decode'' an utterance of $T$ frames, i.e. we want to\nfind the most likely word sequence and its corresponding state-level alignment.  A WFST\ninterpretation of the decoding problem is as follows.  We construct an\nacceptor, or WFSA, as in Fig.~\\ref{fig:acceptor} (an acceptor is represented as a\nWFST with identical input and output symbols).  It has $T{+}1$ states,\nwith an arc for each combination of (time, context-dependent HMM state).  The\ncosts on these arcs correspond to negated and scaled acoustic log-likelihoods.\nCall this acceptor $U$.  Define\n\\begin{equation}\n   S \\equiv U \\circ \\HCLG,\n\\end{equation}\nwhich we call the {\\em search graph} of the utterance.  It has approximately $T{+}1$ times\nmore states than $\\HCLG$ itself.  The decoding problem is equivalent to finding\nthe best path through $S$.  The input symbol sequence for this best path represents\nthe state-level alignment, and the output symbol sequence is the corresponding\nsentence.  In practice we do not do a full search of $S$, but use beam pruning.\nLet $B$ be the searched subset of $S$, containing a subset of the states and arcs\nof $S$ obtained by some heuristic pruning procedure.  \nWhen we do Viterbi decoding with beam-pruning, we are finding the best path through $B$. \n%\nSince the beam pruning is a part of any practical search procedure and cannot\neasily be avoided, we will define the desired outcome of lattice generation in terms\nof the visited subset $B$ of $S$.\n\n\\vspace*{-0.075in}\n\\section{The lattice generation problem}\n\\vspace*{-0.05in}\n\\label{sec:lattices}\n\n\nThere is no generally accepted single definition of a lattice.  In~\\cite{efficient_general}\nand~\\cite{sak2010fly}, it is defined as a labeled, weighted, directed acyclic graph\n(i.e. a WFSA, with word labels).  In~\\cite{ney_word_graph}, time information\nis also included.  In the HTK lattice format~\\cite{htkbook}, phone-level time alignments \nare also supported (along with separate language model, acoustic and pronunciation-probability \nscores), and in~\\cite{saon2005anatomy}, HMM-state-level alignments are also produced.\nIn our work here we will be producing state-level alignments; in fact, the input-symbols\non our graph, which we call {\\em transition-ids}, are slightly more fine-grained\nthan acoustic states and contain sufficient information to reconstruct the phone\nsequence.  \n\nThere is, as far as we know, no generally accepted problem statement\nfor lattice generation, but all the the authors we cited seem to\nbe concerned with the accuracy of the information in the lattice (e.g. that the\nscores and alignments are correct) and the completeness of such information (e.g.\nthat no high-scoring word-sequences are missing).  The simplest\nway to formalize these concerns is to express them in terms of a lattice \npruning beam $\\alpha > 0$ (interpret this as a log likelihood difference).\n\\begin{itemize}\n  \\item The lattice should have a path for every word sequence within $\\alpha$ of the best-scoring one.\n  \\item The scores and alignments in the lattice should be accurate.\n  \\item The lattice should not contain duplicate paths with the same word sequence.\n\\end{itemize}\nWe need to be a little more precise about what we mean by the scores\nand alignments being ``accurate''.  Let the lattice be $L$.  The \nway we would like to state this requirement is:\n\\begin{itemize}\n  \\item For every path in $L$, the score and alignment corresponds to \n   the best-scoring path in $B$ for the corresponding word\n   sequence\\footnote{Or one of the best-scoring paths, in case of a tie.}.\n\\end{itemize}\nThe way we actually have to state the requirement in order to get an efficient procedure is:\n\\begin{itemize}\n  \\item For every word-sequence in $B$ within $\\alpha$ of the best one, the score and alignment\n    for the corresponding path in $L$ is accurate.\n  \\item All scores and alignments in $L$ correspond to actual paths through $B$ (but not always\n   necessarily the best ones).\n\\end{itemize}\nThe issue is that we want to be able to prune $B$ before generating a lattice from it,\nbut doing so could cause paths not within $\\alpha$ of the best one to be lost, so we have\nto weaken the condition.  This is no great loss, since regardless\nof pruning, any word-sequence not within $\\alpha$ of the best one could be omitted altogether, \nwhich is the same as being assigned a cost of $\\infty$).\nBy ``word-sequence'' we mean a sequence of whatever symbols are on the\noutput of $\\HCLG$.  In our experiments these output symbols represent words, but\nsilences do not appear as output symbols (they are\nrepresented via alternative paths in $L$).\n\n\\vspace*{-0.075in}\n\\section{Previous lattice generation methods}\n\\vspace*{-0.05in}\n\\label{sec:previous}\n\nLattice generation algorithms tend to be closely linked to particular types of decoder,\nbut are often justified by the same kinds of ideas.\nA common assumption underlying lattice generation methods is the {\\em word-pair assumption}\nof~\\cite{ney_word_graph}.  This is the notion that the time boundary between a pair of words\nis not affected by the identity of any earlier words.  In a decoder in which there is\na different copy of the lexical tree for each preceding word, \nassuming the word-pair assumption holds, in order to generate an accurate lattice, it is\nsufficient to store a single Viterbi back-pointer at the word level; the entire set of\nsuch back-pointers contains enough information to generate the lattice.  Authors who have used\nthis type of lattice generation method~\\cite{ney_word_graph,odell_thesis} have generally\nnot been able to evaluate how correct the word-pair assumption is in practice, but it seems\nunlikely to cause problems.  Such methods are not applicable for WFST based decoders anyway.\n\nThe lattice generation method described in~\\cite{efficient_general} \nis applicable to decoders that use WFSTs~\\cite{wfst}\nexpanded down to the $C$ level (i.e. $CLG$), so the input symbols represent\ncontext-dependent phones.  In WFST based decoding networks, states normally do\nnot have a unique one-word history, but the authors of~\\cite{efficient_general}\nwere able to satisfy a similar condition at the phone level.  Their method was\nto store a single Viterbi back-pointer at the phone level; use this to \ncreate a phone-level latice; prune the resulting\nlattice; project it to leave only word labels; and then remove $\\epsilon$\nsymbols and determinize.\nNote that the form of pruning referred to here is not the same as beam pruning as\nit takes account of both the forward and backward parts of the cost.\nThe paper also reported experiments with an accurate, ``reference'' method that did not require any\nphone-pair assumption; these experiments showed that the main method they were describing\nhad almost the same lattice oracle error rate as the reference method.  However, the \nexperiments did not evaluate how much impact the assumption had on the accuracy of the scores, \nand this information could be important in some applications.\n\nThe lattice generation algorithm that was described in~\\cite{saon2005anatomy}\nis applicable to WFSTs expanded down to the $H$ level (i.e. $\\HCLG$),\nso the input symbols represent context-dependent states.  It keeps both scores and \nstate-level alignment information.  In some sense this algorithm also relies\non the word-pair assumption, but since the copies of the lexical tree in the decoding\ngraph do not have unique word histories, the resulting algorithm has to be quite\ndifferent.  Viterbi back-pointers at the word level are used, but the algorithm keeps track\nof not just a single back-pointer in each state, but the $N$ best back-pointers for the $N$ top-scoring distinct\nword histories.  Therefore, this algorithm has more in common with the sentence N-best\nalgorithm than with the Viterbi algorithm.  By limiting $N$ to be quite small (e.g. $N{=}5$),\nthe algorithm was made efficient, but at the cost of losing word sequences\nthat would be within the lattice-generation beam.\n\n\\vspace*{-0.075in}\n\\section{Overview of our algorithm}\n\\vspace*{-0.05in}\n\\label{sec:overview}\n\n\\subsection{Version without alignments}\n\\vspace*{-0.05in}\n\nIn order to explain our algorithm in the easiest way, we will first explain how it would\nbe if we did not keep the alignment information, and were storing only a single cost\n(i.e. the total acoustic plus language-model cost).  This is just for didactic purposes;\nwe have not implemented this simple version.\nIn this case, our algorithm would be quite similar\nto~\\cite{efficient_general}, except at the state level rather than the phone level.\nWe actually store forward rather than backward pointers: for each active state on each\nframe, we create a forward link record for each active arc out of that state; this points\nto the record for the destination state of the arc on the next frame (or on \nthe current frame, for $\\epsilon$-input\narcs).   As in~\\cite{efficient_general}, at the end of the utterance,\nwe prune the resulting graph to discard any paths that are not within the beam $\\alpha$ of the best cost. \nLet the pruned graph be $P$, i.e.\n\\begin{equation}\n  P = \\mathrm{prune}(B, \\alpha),\n\\end{equation}\nwhere $B$ is the un-pruned state-level lattice.\nWe project on the output labels (i.e. we keep only the word labels), then remove $\\epsilon$\narcs and determinize.  In fact, we use a determinization algorithm that does $\\epsilon$\nremoval itself.\n\nAs in~\\cite{efficient_general}, to save memory, we actually do the pruning\nperiodically rather than waiting for the end of the file (we do it every 25 frames).\nOur method is equivalent to their method of linking all currently active states to a ``dummy''\nfinal state and then pruning in the normal way.  However, we implement it in such a way\nthat the pruning algorithm does not always have to go back to the beginning of the utterance.\nFor each still-active state, we store the cost difference between the best path including that\nstate, and the best overall path.  This quantity does not always change between different\niterations of calling the pruning algorithm, and when we detect that these quantities are \nunchanged for a particular frame, the pruning algorithm can stop going backward in time.\n\nAfter the determinization phase, we prune again using the beam $\\alpha$.  This is needed because\nthe determinization process can introduce a lot of unlikely arcs.  In fact, for particular\nutterances, the determinization process can cause the lattice to expand enough to\nexhaust memory.  To deal with this, we currently just detect when determinization\nhas produced more than a pre-set maximum number of states, then we prune with a tighter\nbeam and try again.\n\nThis ``simple'' version of the algorithm produces an acyclic, deterministic\nWFSA with words as labels.  This is sufficient for applications such as language-model\nrescoring.\n\n\\vspace*{-0.075in}\n\\subsection{Keeping separate graph and acoustic costs}\n\\vspace*{-0.05in}\n\nA fairly trivial extension of the algorithm described above is to store separately\nthe acoustic costs and the costs arising from $\\HCLG$.  This enables us to do things\nlike generating output from the lattice with different acoustic scaling factors.\nWe refer to these two costs as the graph cost and the acoustic cost, since the cost\nin $\\HCLG$ is not just the language model cost but also contains components\narising from transition probabilities and pronunciation probabilities.  We implement\nthis by using a semiring that contains two real numbers, one for the graph and one\nfor the acoustic costs; it keeps track of the two costs separately, but its\n$\\oplus$ operation returns whichever pair has the lowest sum of costs (graph plus acoustic).\n\nFormally, if each weight is a pair $(a,b)$, then $(a,b) \\otimes (c,d) = (a{+}c, b{+}d)$,\nand $(a,b) \\oplus (c,d)$ is equal to $(a,b)$ if $a{+}b < c{+}d$ or if $a{+}b = c{+}d$ and $a{-}b < c{-}d$,\nand otherwise is equal to $(c,d)$.  This is equivalent to the normal lexicographic semiring (see~\\cite{roark2011lexicographic}) on the pair $((a{+}b),(a{-}b))$.\n\n\\vspace*{-0.075in}\n\\subsection{Keeping state-level alignments}\n\\vspace*{-0.05in}\n\nIt is useful for various purposes, e.g. discriminative training and certain kinds of\nacoustic rescoring, to keep the state-level alignments in the lattices.  We will now\nexplain how we can make the alignments ``piggyback'' on top of the computation\ndefined above, by encoding them in a special semiring.\n\nFirst, let us define $Q = \\inv(P)$, i.e. $Q$ is the inverted, pruned state-level lattice,\nwhere the input symbols are the words and the output symbols are the p.d.f. labels.\nWe want to process $Q$ in such a way that we keep only the best path through it\nfor each word sequence, and get the corresponding alignment.  This is possible\nby defining an appropriate semiring and then doing normal determinization.  We shall\nignore the fact that we are keeping track of separate graph and acoustic costs, \nto avoid complicating the present discussion.  \n\nWe will define a semiring in which symbol sequences are encoded into the weights.\nLet a weight be a pair $(c, s)$, where $c$ is a cost and $s$ is a sequence of symbols.\nWe define the $\\otimes$ operation as $(c, s) \\otimes (c', s') = (c+c', (s,s'))$, where\n$(s,s')$ is a concatenation of $s$ and $s'$.  We define the $\\oplus$ operation so that\nit returns whichever pair has the smallest cost: that is, $(c,s) \\oplus (c',s')$ \nequals $(c,s)$ if $c < c'$, and $(c',s')$ if $c > c'$.  If the costs are identical,\nwe cannot arbitrarily return the first pair because this would not satisfy the semiring\naxioms.  In this case, we return the pair with the shorter string part, and if\nthe lengths are the same, whichever string appears first in dictionary order. \n\nLet $E$ be an encoding of the inverted state-level lattice $Q$ \nas described above, with the same number of states and arcs; $E$ is an acceptor, with its symbols\nequal to the input symbol (word) on the corresponding arc of $Q$, and\nthe weights on the arcs of $E$ containing both the weight and the output symbol (p.d.f.),\nif any, on the corresponding arcs of $Q$.  Let $D = \\mathrm{det}(\\mathrm{rmeps}(E))$.\nDeterminization\nwill always succeed because $E$ is acyclic (as long as the original decoding\ngraph $\\HCLG$ has no $\\epsilon$-input cycles).  Because $D$ is deterministic\nand $\\epsilon$-free, it has only one path for each word sequence. \nDeterminization preserves equivalence,\nand equivalence is defined in such a way that the $\\oplus$-sum of the\nweights of all the paths through $E$ with a particular word-sequence, must be the same\nas the weight of the corresponding path through $D$ with that word-sequence.\nIt is clear from the definition of $\\oplus$ that this path through\n$D$ has the cost and alignment of the lowest-cost path through $E$ that has the\nsame word-sequence on it.  \n\n\\vspace*{-0.075in}\n\\subsection{Summary of our algorithm}\n\\vspace*{-0.05in}\n\nDuring decoding, we create a data-structure\ncorresponding to a full state-level lattice.  That is, for every arc of $\\HCLG$, we traverse\non every frame, we create a separate arc in the state-level lattice.  These arcs\ncontain the acoustic and graph costs separately.  We prune the state-level graph using\na beam $\\alpha$; we do this periodically (every 25 frames) but this is equivalent to\ndoing it just once at the end, as in~\\cite{efficient_general}.  Let the \nfinal pruned state-level lattice be $P$.\nLet $Q = \\inv(P)$, and let $E$ be an encoded version of $Q$ as described above (with the\nstate labels as part of the weights).  The final lattice is\n\\vspace*{-0.075in}\n\\begin{equation}\n   L = \\mathrm{prune}(\\mathrm{det}(\\mathrm{rmeps}(E)), \\alpha) . \\vspace*{-0.075in}\n\\end{equation}\nThe determinization and epsilon removal are done together by a single algorithm\nthat we will describe below.  $L$ is a deterministic, acyclic weighted acceptor with the \nwords as the labels, and the graph and acoustic costs and the alignments\nencoded into the weights.  The costs and alignments are not ``synchronized'' \nwith the words.\n\n\\vspace*{-0.075in}\n\\section{Details of our determinization algorithm}\n\\vspace*{-0.05in}\n\\label{sec:details}\n\nWe implemented $\\epsilon$ removal and determinization as a single algorithm \nbecause $\\epsilon$-removal using the traditional approach would greatly\nincrease the size of the state-level lattice (this is mentioned \nin~\\cite{efficient_general}).  Our algorithm uses data-structures\nspecialized for the particular type of weight we are using.  The issue\nis that the determinization process often has to append a single symbol to\na string of symbols, and the easiest way to\ndo this in ``generic'' code would involve copying the whole sequence each time.\nInstead we use a data structure that enables this to be done in linear\ntime (it involves a hash table).  \n\nWe will briefly describe another unique aspect of our\nalgorithm.  Determinization algorithms involve weighted subsets of states, e.g.:\n\\begin{equation}\n   S = \\{ (s_1, w_1), (s_2, w_2), \\ldots \\} .\n\\end{equation}\nLet this weighted subset, as it appears in a conventional determinization\nalgorithm with epsilon removal, be the {\\em canonical representation} of a state.\nA typical determinization algorithm would maintain a map from this representation\nto a state index.  We define a {\\em minimial representation} of a state\nto be like the canonical representation, but only keeping states that\nare either final, or have non-$\\epsilon$ arcs out of them.  We maintain\na map from the minimal representation to the state index.  We can\nshow that this algorithm is still correct (it will tend to give more\nminimal output).   As an optimization for speed, we also define\nthe {\\em initial representation} to be the same type of subset, but prior\nto following through the $\\epsilon$ arcs, i.e. it only contains the states\nthat we reached by following non-$\\epsilon$ arcs from a previous determinized\nstate.  We maintain a separate map from the initial representation to\nthe output state index; think of this as a ``lookaside buffer'' that helps us\navoid the expense of following $\\epsilon$ arcs. \n\n%Although we have not written a proof of correctness of this algorithm, we\n%have tested it thoroughly.  This is done by generating random WFSTS,\n%applying this algorithm, and if it terminates, checking that the result\n%is deterministic and is equivalent (in this semiring) to the original WFST\n%represented as an acceptor in this semiring.\n\nSince submitting this paper, we have become aware of~\\cite{shafran2011efficient},\nwhich solves the exact same problem for a different purpose.  They use a semiring\nwhich is more complicated than ours (the string part of the semiring becomes a\nstructured object with parentheses).  They use this semiring instead of the one\n we describe here, because in our semiring the $\\oplus$-sum of two weights \ndoes not necessarily left-divide the weights, and this is a problem for \na typical determinization algorithm.  We bypass\nthis problem by defining a ``common divisor'' operation $\\boxplus$ with the\nright properties (it $\\oplus$-adds the weight part and returns the longest\ncommon prefix of the string part).  We use this instead of\n$\\oplus$ when finding divisors in the determinization algorithm.\n\n\n%% The algorithm for $\\epsilon$-removal and determinization is also optimized\n%% for our particular case.  We will first explain what a generic $\\epsilon$-removal\n%% and determinization algorithm would look like.  We will explain this using\n%% generic weights.  Let us use the notation\n%% \\begin{equation}\n%%    S = \\{ (s_1, w_1), (s_2, w_2), \\ldots \\}\n%% \\end{equation}\n%% for a weighted subset of states in the original FST.  Each subset $S$ corresponds\n%% to a state in the determinized FST, i.e. we maintain a map $m(S) \\rightarrow s$\n%% where $s$ is a state number in the output (in practice there are tolerances\n%% involved in this map when the weights contain floating-point numbers).  We need\n%% to normalize these subsets to remove any ``common part'' of the weights.  We\n%% need to define an associative and commutative ``common divisor'' operation \n%% on weights (call this $\\boxplus$; it can be the same as $\\oplus$ for many semirings),\n%% that gives us the normalizer for a pair of weights.\n%% We must be able to  left-divide each individual weight by the result of this operation, i.e.\n%% if $c = a \\boxplus b$, then we need to be able to solve $a = c a'$ and $b = c b'$ for $a'$ and $b'$.\n%% Here, $a'$ and $b'$ become the ``normalized weights''.  Also $\\otimes$-multiplication\n%% must be left-distributive over this operation, which ensures the right kind of\n%% ``uniqueness'' of the normalization operation.  In the particular case of interest\n%% $w$ is a pair $(w', s)$ of a ``base-weight'' and a string $s$, and the \n%% operation $(a,s) \\boxplus (b,t)$ returns $(a\\oplus b, u)$ where $u$ is the longest\n%% common prefix of $s$ and $t$ and $a\\oplus b$ essentially returns the minimum cost.\n\n%% For the determinization algorithm, we define\n%% $\\mathrm{normalizer}(S)$ to be the $\\boxplus$-sum of the weights in the subset $S$,\n%% and $\\mathrm{normalize}(S)$ to be $S$ with each weight left-divided by \n%% $\\mathrm{normalizer}(S)$.  We also need to define an operation that ``follows through''\n%% $\\epsilon$ transitions.  Call this $\\mathrm{follow-eps}(S)$ \n\n\n\n\n%% The key characteristic of our method is that unlike all previously reported \n%% methods that we are aware of (with the sole exception of the inefficient method used \n%% as a baseline in~\\cite{efficient_general}), our method is exact even if the word-pair \n%% assumption is invalid.  In addition, we are able to generate a lattice with full\n%% state-level alignment information, which would not be possible using the approaches\n%% used in~\\cite{efficient_general}.  Our algorithm also does not need to store $N$\n%% back-pointers like the lattice-generation algorithm previously reported in~\\cite{saon2005anatomy}\n%% for $H$-level WFSTs (i.e. fully-expanded WFSTs).  \n\n\n\\vspace*{-0.1in}\n\\section{Experimental results}\n\\vspace*{-0.075in}\n\\label{sec:exp}\n\n\nWe do not compare with any other algorithms,\nas~\\cite{ney_word_graph,odell_thesis,efficient_general} are designed for\ndifferent types of decoders than ours, and the lattices contain less information,\nmaking comparisons hard to interpret; the algorithm of~\\cite{saon2005anatomy} has\nsimilar requirements and outputs as ours, but besides being inexact, it is bound\nto be slower due to the need to store $N$ back-pointers, so we did not view it as\nworthwhile to do the experiment.\n\nWe report experimental results on the Wall Street Journal database of\nread speech. \nOur system is a standard mixture-of-Gaussians system trained on the SI-284\ntraining data; we test on the November 1992 evaluation data.  \nWe generated lattices with the bigram language model\nsupplied with the WSJ database, and for rescoring experiments we\nuse the trigram language model.  The acoustic scale was $1/16$ for first-pass\ndecoding and $1/15$ for LM rescoring.  \nFor simplicity, we used a decoder that\ndoes not support a ``maximum active states'' option, so the only variables\nto consider are the beam used in the Viterbi beam search, and the separate\nbeam $\\alpha$ used for lattice generation.\n\n\\begin{figure}[t]\n\\centering\n   \\includegraphics[width=0.9\\columnwidth]{figures/latbeam.eps} \n \\vspace*{-0.1in}\n \n   \\caption{ { Lattice properties, varying lattice beam $\\alpha$ (Viterbi pruning beam fixed at 15)} }\n  \\vspace{-0.15in}\n  \\label{fig:latbeam}\n\\end{figure}\n\nFigure~\\ref{fig:latbeam} shows how the lattice properties change as we vary\n$\\alpha$, with the Viterbi beam fixed at 15; Figure~\\ref{fig:viterbibeam} varies\nthe Viterbi decoding beam, leaving $\\alpha$ fixed at 7.  Lattice density is\ndefined as the average number of arcs crossing each frame.  We get all the\nimprovement from LM rescoring by increasing $\\alpha$ to 4, and time taken\nincreases rapidly when $\\alpha > 8$, so we recommend roughly $4 < \\alpha < 8$ for\nLM rescoring purposes.  We do not display the real-time factor of the\nnon-lattice-generating decoder on this data (2.26xRT) as it was actually slower\nthan the lattice generating decoder; this is possibly due to the overhead of\nreference counting.  Out of vocabularly words (OOVs) provide a floor on the\nlattice oracle error rate: of 333 test utterances, 87 contained at least one OOV\nword, yet only 93 sentences (6 more) had oracle errors with $\\alpha=10$.\n\n\n\\begin{figure}[t]\n\\centering\n   \\includegraphics[width=0.9\\columnwidth]{figures/decodebeam.eps} \n \\vspace*{-0.1in}\n    \\caption{ {Lattice properties, varying Viterbi pruning beam (lattice beam $\\alpha$ fixed at 7)}}\n  \\label{fig:viterbibeam}\n  \\vspace{-0.15in}\n\\end{figure}\n\n\n\\vspace*{-0.1in}\n\\section{Conclusions}\n\\label{sec:conc}\n\\vspace*{-0.075in}\n\nWe have described a lattice generation method that is to our knowledge the first\nefficient method that does not rely on the word-pair assumption of~\\cite{ney_word_graph}.\nIt includes an ingenious way of obtaining HMM-state-level alignment information\nvia determinization in a specially designed semiring. \n\n\\vspace*{-0.04in}\n\\footnotesize {\n\\vspace*{-0.1in}\n\\bibliographystyle{IEEEbib}\n\\bibliography{refs}\n}\n\n\\end{document}\n\n\nsteps/decode_tri3a_latgen.sh\nacwt=0.0625\nbeam=[15.0-7.0]\nmax_active=15000\nlat_beam=[10.0-1.0]\nmax_arcs=50000 (75000 for lat_beam 10.0)\nmodel=exp/tri3a/final.mdl\ngraph=exp/graph_tri3a_bg_left/HCLG.fst\n\nscp=data/eval_nov92.scp\n\n333 utterances\n87 utterances contain OOV\n42 utterances contain annotated noise (actually some more, but listed as OOV utterances here)\n\n5641 tokens (some scripts count 5700 with 59 noise annotations)\n107 OOV tokens\n1.88% OOV token rate\n\n253204 frames (2532 seconds)\n\n19976 words in decoding vocabulary and LM (not counting <s>,</s>,<unk>)\n\naverage lattice link density per frame:\nhave a wide range over files: for example beam=15.0, lat_beam=9.0:\nranging from 1.5 to 167\n\nrunning on blades, using 64bit version with double float and lattice-simple-decoder\nrealtime factor running on pcburget, 22989 frames (decode3.sh)\n\ndecoding with bigram LM:\ndecoding WER:      11.51%\nins/del/sub:       118/57/474   \nutterances wrong:  227          \n\n1) experiment: changing lattice beam:\n(lattices 443c040w and 444c040i have been reduced from 10.0 to 8.1 because of determinization memory problems)\n\ndecoding beam:     15.0         15.0       15.0       15.0       15.0         15.0        15.0        15.0        15.0         15.0        15.0\nlattice beam:      10.0          9.0        8.0        7.0        6.0          5.0         4.0         3.0         2.0          1.0         0.0\navg. link density: 23.56        16.0       10.82       7.26       4.91         3.38        2.38        1.77        1.4          1.17        1.0\nrealtime factor:    2.317        2.114      2.006      1.941     1.900         1.855       1.835       1.797       1.769        1.737       ---\n\noracle WER:         2.62%        2.78%      2.85%      3.08%      3.35%        3.86%       4.52%       5.46%       6.98%        8.62%      11.51%\nins/del/sub:       22/0/126     25/0/132   29/0/132   31/1/142   38/5/146     51/11/156   57/15/183   64/20/224   76/32/286    89/40/357   118/57/474\noracle utt wrong:  93           96         96         101        105          116         129         147         168          191         227\n\nrescoring WER(15):  9.59%        9.59%      9.59%      9.59%      9.56%        9.59%       9.61%       9.70%       9.80%       10.21%      11.51%\nins/del/sub:       117/36/388                                    116/36/387   117/35/389  115/35/392  111/38/398  108/39/406   113/42/421  118/57/474\nrescore utt wrong: 205                                           204          204         204         202         205          212         227\n\n2) experiment: changing decoding beam:\n\ndecoding beam:     16.0        15.0          14.0          13.0         12.0         11.0         10.0          9.0 (1 utt partial) 8.0 (2 partial)\nlattice beam:       7.0         7.0           7.0           7.0          7.0          7.0          7.0          7.0                7.0\navg. link density:  7.4         7.26          7.04          6.74         6.33         5.71         4.9          4.08               3.09\nrealtime factor:    2.646       1.941         1.428         1.052        0.775        0.555        0.388        0.267              0.177\ndecoding WER:      11.51%       11.51%       11.54%        11.58%       11.75%       11.93%       12.32%        13.47%             15.41%\nins/del/sub:       118/57/474   118/57/474   118/57/476    119/56/478   124/57/482   131/58/484   140/58/497    164/56/540         197/61/611\nutterances wrong:  227          227          227           227          228          228          229           236                246\n\noracle WER:        3.03%        3.08%        3.24%         3.37%        3.56%        4.02%        4.72%         6.45%              9.18%\nins/del/sub:       30/1/140     31/1/142     35/2/146      38/2/150     42/3/156     54/6/167     55/7/204      73/13/278          118/22/378\noracle utt wrong:  100          101          105           108          112          119          128           153                184\n\nrescoring WER(15): 9.59%        9.59%        9.73%         9.80%        10.05%       10.26%       10.55%        11.82% (1 failed)  13.79% (2 failed)\nins/del/sub:       116/36/389   117/36/388   115/37/397    117/38/398   123/39/405   132/39/408   141/37/417    ---                ---\nrescore utt wrong: 205          205          206           206          207          209          208           220                235\n\n3) bigram vs. trigram decoding:\n\ndecoding lm:       bigram       trigram,pruned  bigram        trigram,pruned   bigram (just to see whether wider beams still help)\ndecoding beam:     15.0         15.0            13.0          13.0             16.0 \nlattice beam:       9.0          9.0             9.2           9.2             10.0 (already quite big for lattice-oracle - more than 6GB RAM used)\navg. link density: 16.0         14.98           14.86         13.58            24.84\nrt factor(old):     3.17         3.26            1.75         1.77              4.54\n\ndecoding WER:      11.51%       10.57%          11.58%        10.80%           11.51%\nins/del/sub:       118/57/474   116/44/436      119/56/478    120/47/442       118/57/474\nutterances wrong:  227          214             227           215              227\n\noracle WER:        2.78%        2.84%           3.05%         3.19%            2.61%\nins/del/sub:       25/0/132     30/0/130        30/2/140      33/1/146         21/0/126\noracle utt wrong:  96           96              103           107              92\n\nrescoring WER(15):  9.59%       9.64%           9.80%         9.87%            9.59%\nins/del/sub:       117/36/388   115/34/395      117/38/398    119/38/400       116/36/389\nrescore utt wrong: 205          205             206           209              205\n\n4) lattice vs. n-best lists\ndecoding with trigram, pruned\n\ndecoding:          lattice      n-best         n-best/beam\ndecoding beam:     13.0         13.0           13.0  \nlattice beam:      9.2          --             9.35 [6.0-12.5] (few outliers below/above)\nN best:            --           <=20           206.96 [2-1600] (according to beam range and utterance)\nmax tokens:        15000        150k,700k      150000-770000\navg. link density: 13.58        14?            231.05\nrealtime factor:   1.77         12             crap\n\ndecoding WER:      10.80%       12.78% (why?)  14.96% (probably too low max tokens)\nins/del/sub:       120/47/442\nutterances wrong:  215\n\noracle WER:        3.19%\nins/del/sub:       33/1/146\noracle utt wrong:  107\n\nrescoring WER(15):  9.87%\nins/del/sub:       119/38/400\nrescore utt wrong: 209\n\n2.259 is baseline RT factor w/ decoding beam of 15, with simple-decoder.\n\nnote: paper# is 3887\npasswd  CF8FECE1\n\n", "meta": {"hexsha": "3a49eec53cca1c9c88aa95d347b3d6e8614958e6", "size": 39279, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "misc/papers/icassp12_lat/paper.tex", "max_stars_repo_name": "shuipi100/kaldi", "max_stars_repo_head_hexsha": "8e30fddb300a87e7c79ef2c0b9c731a8a9fd23f0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 805, "max_stars_repo_stars_event_min_datetime": "2018-05-28T02:32:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T09:13:12.000Z", "max_issues_repo_path": "misc/papers/icassp12_lat/paper.tex", "max_issues_repo_name": "shuipi100/kaldi", "max_issues_repo_head_hexsha": "8e30fddb300a87e7c79ef2c0b9c731a8a9fd23f0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 49, "max_issues_repo_issues_event_min_datetime": "2015-10-24T22:06:28.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-24T11:13:34.000Z", "max_forks_repo_path": "misc/papers/icassp12_lat/paper.tex", "max_forks_repo_name": "shuipi100/kaldi", "max_forks_repo_head_hexsha": "8e30fddb300a87e7c79ef2c0b9c731a8a9fd23f0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 267, "max_forks_repo_forks_event_min_datetime": "2018-06-07T08:33:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T12:18:33.000Z", "avg_line_length": 52.5120320856, "max_line_length": 547, "alphanum_fraction": 0.7020036152, "num_tokens": 11049, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.33899325485308096}}
{"text": "% Abstract\n\n%\\renewcommand{\\abstractname}{Abstract} % Uncomment to change the name of the abstract\n\n\\pdfbookmark[1]{Abstract}{Abstract} % Bookmark name visible in a PDF viewer\n\n\\begingroup\n\\let\\clearpage\\relax\n\\let\\cleardoublepage\\relax\n\\let\\cleardoublepage\\relax\n\n\\chapter*{Abstract}\n\tRanking functions used in information retrieval are primarily used in the search engines and they are often adopted for various language processing applications.\nThis project introduces some novel heuristics combined with probabilistic retrieval functions and are employed in the domain of approximate string similarity problem.\nA lot of algorithms have been proposed in the literature to solve approximate string similarity problems, however none of them makes use of probabilistic retrieval functions.\nWe are the first to explore the intersection between these two areas and propose heuristic designs to resolve this problem.\nFirst we propose chunking heuristic function, BREAK. \nWe show the variants BREAK-1, 2, OFF which splits up the terms with the sequential notion.\nThen we propose BREAK-n which generalizes these variants and scales to larger datasets.\nIn order to relate these split ups, we propose a graphical error modelling heuristics MAKE over the BREAK variants.\nFinally, we propose TAKE curve, a novel feature engineering probabilistic distribution which replaces the prevalent normalization heuristics.\nTaking the advantage of flexibility over the choice of heuristics, we assess the variants on the cognate detection, mutant identification, and isolated spelling correction based problems.\nIn the extensive evaluation methods, we found that our designs perform better than prevalent heuristics and are robust against database characteristics.\n\n\\endgroup\t\t\t\n\n\\vfill", "meta": {"hexsha": "f6a7356be426ce373b3946665c2c6c6ce87cb9f7", "size": 1767, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "FrontBackMatter/Abstract.tex", "max_stars_repo_name": "pranav-ust/ir-heuristics", "max_stars_repo_head_hexsha": "7a031ad4aa46ed937f6b555f4e1367438cbbe2b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-08-07T02:01:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-30T21:44:25.000Z", "max_issues_repo_path": "FrontBackMatter/Abstract.tex", "max_issues_repo_name": "pranav-ust/ir-heuristics", "max_issues_repo_head_hexsha": "7a031ad4aa46ed937f6b555f4e1367438cbbe2b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FrontBackMatter/Abstract.tex", "max_forks_repo_name": "pranav-ust/ir-heuristics", "max_forks_repo_head_hexsha": "7a031ad4aa46ed937f6b555f4e1367438cbbe2b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 65.4444444444, "max_line_length": 187, "alphanum_fraction": 0.8273910583, "num_tokens": 343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5544704502361149, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.33899323799865233}}
{"text": "\\documentclass{documentation}\n\n\\title{ExceptionAlge Package}\n\n\\author{James B. Wilson}\n\\address{Colorado State University}\n\\email{james.wilson@colostate.edu}\n\n\\author{Joshua Maglione}\n\\address{Universit\\\"at Bielefeld}\n\\email{jmaglione@math.uni-bielefeld.de}\n\n\\version{2.1}\n\\date{\\today}\n\\copyrightyear{2016--2019}\n\n\\input{preamble.tex}\n\n%-----------------------------------------------------------------------------\n\\begin{document}\n\n\\frontmatter\n\n\\dominitoc\n\\maketitle\n\\tableofcontents\n\n\\mainmatter\n\n\\chapter{Introduction}\n\n\\subsection*{Citing ExceptionAlge} \n\n\\section{Overview}\n\n\\section{Version}\n\n\n\n\n\\chapter{Exceptional Algebras}\n\nMagma provides functionality with common exceptional tensors.  Many are used in the\nconstruction of nonassociative algebras.  A few supporting functions for nonassociative algebras\nare also provided.\n\n\\section{Generics for nonassociative algebras}\n\n\\subsection{Nonassociative algebras with involutions}~\n\n\\index{IsStarAlgebra}\n\\begin{intrinsics}\nIsStarAlgebra(A) : AlgGen -> BoolElt\n\\end{intrinsics}\n\nDecides if algebra has an involution, i.e. a $*$-algebra.\n\n\\index{Star}\n\\begin{intrinsics}\nStar(A) : AlgGen -> Map\n\\end{intrinsics}\n\nReturns involution of given $*$-algebra.\n\n\\begin{example}[StarAlgebra]\n\nWe demonstrate the functions dealing with involutions of nonassociative algebras.\n\\begin{code}\n> A := OctonionAlgebra(Rationals(),-1,-1,-1);\n> IsStarAlgebra(A);\ntrue\n> \n> s := Star(A);\n> A.1; // A.1 is the mult. id.\n(1 0 0 0 0 0 0 0)\n> A.1 @ s; \n(1 0 0 0 0 0 0 0)\n> \n> A.2;\n(0 1 0 0 0 0 0 0)\n> A.2 @ s;\n( 0 -1  0  0  0  0  0  0)\n\\end{code}\n\\end{example}\n\n\\subsection{Operations on power associative algebras}~\nThe following operations are defined for nonassociative algebras for which $x*(x*x)=(x*x)*x$.\n\n\\index{GenericMinimalPolynomial}\\index{GenericMinimumPolynomial}\n\\begin{intrinsics}\nGenericMinimalPolynomial(x) : AlgGenElt -> FldElt\nGenericMinimumPolynomial(x) : AlgGenElt -> FldElt\n\\end{intrinsics}\n\nThe generic minimum polynomial of an element in a power associative algebra.\n\n\\index{GenericNorm}\n\\begin{intrinsics}\nGenericNorm(x) : AlgGenElt -> FldElt\n\\end{intrinsics}\n\nThe generic norm of an element in a power associative algebra.\n\n\\index{GenericTrace}\n\\begin{intrinsics}\nGenericTrace(x) : AlgGenElt -> FldElt\n\\end{intrinsics}\n\nThe generic trace of an element in a power associative algebra.\n\n\\index{GenericTracelessSubspaceBasis}\n\\begin{intrinsics}\nGenericTracelessSubspaceBasis(A) : AlgGen -> Any\n\\end{intrinsics}\n\nGiven a power associative algebra return a basis for the elements of generic trace 0.\n\n\\begin{example}[TenGeneric]\n\nThe trace $x+\\bar{x}$ of a quaternion doubles the rational component, producing\ndegenerate behavior in characteristic $2$.  The generic trace avoids this.\n\\begin{code}\n> Q := QuaternionAlgebra(Rationals(), 1,1);\n> Trace(Q!1);        \n2\n> GenericTrace(Q!1);\n1\n> Q := QuaternionAlgebra(GF(2), 1,1);  \n> Trace(Q!1);\n0\n> GenericTrace(Q!1);\n1\n\\end{code}\n\nThe generic minimum polynomial of an element $x$ in power associative algebra\nneed only be a factor of the minimal polynomial of its right regular matrix $yR_x:=x*y$.\n\n\\begin{code}\n> J := ExceptionalJordanCSA(GF(5));\n> p := GenericMinimumPolynomial(J.3+J.12);\n> Rx := AsMatrices(Tensor(J), 2,0);     // yR_x = y*x.\n> q := MinimalPolynomial(Rx[3]+Rx[12]); \n> Degree(p);\n3\n> Degree(q);\n6\n> q mod p;\n0\n\\end{code}\n\\end{example}\n\n\\section{Compositions algebras}\n\n\\index{CompositionAlgebra}\n\\begin{intrinsics}\nCompositionAlgebra(K, a) : Fld, [FldElt] -> AlgGen\nCompositionAlgebra(K, a) : Fld, [RngIntElt] -> AlgGen\n\\end{intrinsics}\n\nConstructs the composition algebra with specified parameters.  The algebra returned\nhas an involution.  \nThe method is modestly intentional choosing Magma's favored representation of\nthe individually classified algebras according to Hurwitz's theorem.  In the case of\nfields the type returned is an algebra with involution, possibly the identity.\n\n\n\\index{OctonionAlgebra}\n\\begin{intrinsics}\nOctonionAlgebra(K, a, b, c) : Fld, FldElt, FldElt, FldElt -> AlgGen\nOctonionAlgebra(K, a, b, c) : Fld, RngIntElt, RngIntElt, RngIntElt -> AlgGen\n\\end{intrinsics}\n\nOctonion algebra with involution given by the specified parameters.\nThis builds the Cayley-Dickson algebra over the quaternion algebra\n$\\left(\\frac{a,b}{K}\\right)$.  In particular, Magma's implementation\nof quaternion algebras is applied.\n\n\\index{SplitOctonionAlgebra}\n\\begin{intrinsics}\nSplitOctonionAlgebra(K) : Fld -> AlgGen\n\\end{intrinsics}\n\nReturns the split octonion algebra over the field $F$.\n\n\n\\begin{example}[TenTriality]\nThe following example demonstrates some of the mechanics by exploring\nthe concept of triality \\cite{Schafer}*{III.8}.\n\nThe Cartan-Jacobson theorem asserts that for fields of characteristic other\nthan 2 and 3, the derivation algebra of an octonion algebra is of Lie type \n$G_2$.\n\n\\begin{code}\n> O := OctonionAlgebra(GF(7),-1,-1,-1);\n> L := DerivationAlgebra(O);   // Derivations as an algebra.\n> SemisimpleType(L);\nG2\n\\end{code}\n\nCartan's triality obtains $G_2$ from $D_4$ by relaxing to\nderivations of the octonions as a generic tensor, rather than as an \nalgebra.  \nThis is done computationally by changing the category of the octonion product\nfrom an algebra to a tensor.\n\n\\begin{code}\n> T := Tensor(O);\n> T := ChangeTensorCategory(T,HomotopismCategory(2)); \n> M := DerivationAlgebra(T);  // Derivations as a tensor.\n> SemisimpleType(M/SolvableRadical(M));\nD4\n\\end{code}\n\\end{example}\n\n\\section{Jordan algebras}\n\n\n\\index{JordanTripleProduct}\n\\begin{intrinsics}\nJordanTripleProduct(J) : AlgGen -> TenSpcElt\n\\end{intrinsics}\n\nReturns the tensor describing the Jordan triple product.\n\n\\index{JordanSpinAlgebra}\n\\begin{intrinsics}\nJordanSpinAlgebra(F) : TenSpcElt -> AlgGen\nJordanSpinAlgebra(F) : Mtrx -> AlgGen\n\\end{intrinsics}\n\nReturns the special Jordan algebra of spin type for given symmetric form.\n\n\\begin{example}[JordanBasic]\nJordan algebras have suggestive analogues of \ncommutative associative algebras, but experimenting shows serious \ndifferences.\n\n\\begin{code}\n> F := IdentityMatrix(Rationals(),2);\n> J := JordanSpinAlgebra(F);\n> T := Tensor(J); \n> R := AsMatrices( T, 2,0); \n> R[1];   // Is J.1 the identity?\n[1 0 0]\n[0 1 0]\n[0 0 1]\n> J.2*J.2 eq J.1;  // J.2^2=1?\ntrue\n> J.2*J.3 eq 0;  // Yet J.2 is a zero-divisor.\ntrue\n> e := (1/2)*(J.1+J.2);             \n> e^2 eq e;  // An idempotent of J?\ntrue\n\\end{code}\n\nPierce decompositions in Jordan algebras have the usual 0 and 1 eigenspaces\nbut an additional 1/2-eigenspace emerges as well.\n\n\\begin{code}\n> Re := (1/2)*(R[1]+R[2]);\n> Eigenvalues(Re);\n{ <1, 1>, <1/2, 1>, <0, 1> }\n\\end{code}\n\\end{example}\n\n\\index{ExceptionalJordanCSA}\n\\begin{intrinsics}\nExceptionalJordanCSA(O) : AlgGen -> AlgGen\nExceptionalJordanCSA(K) : Fld -> AlgGen\n\\end{intrinsics}\n\nThe exception central simple Jordan algebra over the given octonions.\nIf a field is supplied instead then the split octonion algebra over the\nfield is used.\n\n\\begin{example}[ChevalleyShaferF4]\nIn characteristic not $2$ or $3$, the exceptional central \nsimple Jordan algebra can be used to construct\nthe exceptional Lie algebra of type $F_4$.\n\n\\begin{code}\n> J := ExceptionalJordanCSA(Rationals());\n> T := Tensor(J);                                     \n> T := ChangeTensorCategory(T, HomotopismCategory(3));\n> D := DerivationAlgebra(T);\n> D2 := Codomain(Induce(D, 2));\t\t// Represent D on U2.\n> F4 := D2*D2;\t\t\t              // Commutator.\n> SemisimpleType(F4);\nF4\n> F4;                             // F4 represented on a 27-dim module.\nMatrix Lie Algebra of degree 27 over Rational Field\n\\end{code}\n\\end{example}\n\n\n\n\n\n\\backmatter\n\n\\begin{bibdiv}\n\\begin{biblist}\n\n\\bib{Schafer}{book}{\n   author={Schafer, Richard D.},\n   title={An introduction to nonassociative algebras},\n   series={Pure and Applied Mathematics, Vol. 22},\n   publisher={Academic Press, New York-London},\n   date={1966},\n   pages={x+166},\n   review={\\MR{0210757}},\n}\n\n\\end{biblist}\n\\end{bibdiv}\n\n\\printindex\n\n\n\\end{document}\n", "meta": {"hexsha": "4ca678ad3249b7d90b474f14dcfbf072cfd554a6", "size": 7953, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/ExceptionAlge.tex", "max_stars_repo_name": "thetensor-space/ExceptionAlge", "max_stars_repo_head_hexsha": "44564eb7535c63600aeba21312ca1c7d1c25f8cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/ExceptionAlge.tex", "max_issues_repo_name": "thetensor-space/ExceptionAlge", "max_issues_repo_head_hexsha": "44564eb7535c63600aeba21312ca1c7d1c25f8cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/ExceptionAlge.tex", "max_forks_repo_name": "thetensor-space/ExceptionAlge", "max_forks_repo_head_hexsha": "44564eb7535c63600aeba21312ca1c7d1c25f8cb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.698757764, "max_line_length": 96, "alphanum_fraction": 0.7187224947, "num_tokens": 2450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704502361149, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.33899323799865233}}
{"text": "This section covers basic performance tests, i.e. how specific algorithms scale\nwith grid resolution and with polynomial degree, on a \\emph{single compute node}.\n\n% --------------------------------------------------------------------------------\n\\section{Solver Performance - Poisson/Stokes problems}\n\\label{sec:SolverPerformancePoisson}\n% --------------------------------------------------------------------------------\nTwo groups of solver are compared:\n\\begin{itemize}\n\\item\nDirect Solvers: directs sparse methods, such as PARDISO\\footnote{\n\\url{http://www.pardiso-project.org/}}\nand MUMPS\\footnote{\n\\url{http://mumps.enseeiht.fr/}}\nare compared.\nTheir performance also serves as a comparative baseline.\n\n%\\item\n%Iterative Algorithms without preconditioning, resp. low-impact, generic preconditioning:\n%This includes solver libraries such as \\code{monkey} (BoSSS-specific, supports GPU)\n%as well as\n%HYPRE\\footnote{\n%\\url{https://computation.llnl.gov/projects/hypre-scalable-linear-solvers-multigrid-methods}}\n%(native library, used via wrappers).\n\n\\item\nIterative Algorithms with \\ac{dg}-specific preconditioners, such as aggregation multigrid\nand multi-level additive Schwarz\n\\end{itemize}\n\nThe scaling and performance is profiled subsequent sections. For Performance profiling we stick to our working horse: the kcycle-Schwarz algorithm (with optional p-two-grid as block solver).\nThe performance profile of the krylov V-cycle with Schwarz pre and post-smoother is investigated. A direct solver (PARDISO) is used to solve the deepest coarse system. One may choose another direct solver for the coarse system, e.g. MUMPS. In practise PARDISO is more robust to ill-conditioned system, therefore in this performance analysis investigation we will stick to PARDISO as solver, wherever a direct solver is needed.\nNOTE: the p-two-grid used in Schwarz or as a standalone preconditioner, the coarse system is solved by a direct solver.\n\nWe distinguish four phases of every solver-scenario: \n\\begin{itemize}\n\t\\item MatrixAssembly: assemble Block matrix\n\t\\item Aggregation basis init: create multigrid sequence, contains information about the transformation at the multigrid levels\n\t\\item Solver Init: hand over/assemble relevant data for the chosen solver, e.g. operator matrix etc.\n\t\\item Solver Run: solves the equation system: operator matrix, vector of dg coordinates and given RHS \n\\end{itemize}\nMatrix assembly and aggregation init is discritization specific, whereas, Solver init and run ist specific for the used solver.\n\n\\subsection{Introduction of solvers}\n\n\\subsubsection{linear Solver: p-two-grid}\n\\label{sec:ptg_gmres}\n\nThe p two grid algorithm can be used as left preconditioner for the well known GMRES-algorithm. Or as block solver of the Schwarz blocks in the Orthonormalization-multigrid algorithm, described in \\ref{alg:OrthoMG}.\n\n\\subsubsection{linear Solver: V-krylov-cycle with Schwarz smoother}\n\\label{sec:kcycle}\n\nThe orthonormalization multigrid is a combination of a v-cycle of a geometric multigrid (or algebraic as the agglomeration of cells is graph based) with an additive Schwarz smoother and a projection method onto the history of residual contributions of parts of the algorithm (smoother and coarse grid correction). A schematic of the solver can be checked out in \\ref{fig:SolverScheme}. \nFor more details on the solvers check \\cite{OpenSoftwarePDE}.\n\n\\begin{figure}[!h]\n\t\\begin{center}\n\t\t\\includegraphics[scale=0.65]{./apdx-NodeSolverPerformance/solver-scheme.png}\n\t\t\\input{./apdx-NodeSolverPerformance/solver-scheme.png}\n\t\\end{center}\n\t\\caption{\n\t\tscheme of Orthonormalization Multigrid. The block solver is usually a direct solver like PARDISO. Note: for the smoother it is sufficient to solve the system approximately. This gives rise to approximate solutions of the Schwarz blocks, like a ILU algorithm.  \n\t}\n\t\\label{fig:SolverScheme}\n\\end{figure}\n\n\\subsection{DG-Poisson test problem}\n\\label{sec:ConstantDiffusionCoefficient}\nThe stationary 3D-problem:\n\\begin{equation}\n\\left\\{ \\begin{array} {rclll}\n- \\Delta T   & = & g_{\\domain}                      \n& \\text{in}\\ \\Omega = (0,10) \\times (-1,1) \\times (-1,1)  &  \\\\\n% ----\nT   & = & g_D = 0                             \n& \\text{on}\\ \\Gamma_D = \\{ (x,y,z) \\in \\real^3; \\ x = 0 \\}\n& \\text{Dirichlet-boundary} \\\\\n% ----\n\\nabla T \\cdot \\vec{n}_{\\partial \\domain} & = & g_N \n& \\text{on}\\ \\Gamma_N = \\partial \\Omega \\setminus \\Gamma_D\n& \\text{Neumann-boundary}\n\\end{array} \\right.\n\\label{eq:ContantCoeffPoissonBenchmark}\n\\end{equation}\nwhere $g_{\\domain}=-sin(x)$.\nis investigated on a non-uniform, Cartesian grid\n(equidistant in $z$, sinus-spacing in $x$ and $y$ direction).\nThe large $\\Gamma_N$ makes the problem harder for non-preconditioned\niterative methods. See Figure \\ref{fig:ConstantCoeffRuntimes} for results.\n\n\\subsection{DG-Poisson: scaling of solvers}\n\n\\graphicspath{{./apdx-NodeSolverPerformance/PoissonConstCoeff/plots/}}\n\n\\begin{figure}[!h]\n\t\\begin{center}\n\t\t\\input{./apdx-NodeSolverPerformance/PoissonConstCoeff/plots/ConstCoeffPoissonScaling.tex}\n\t\\end{center}\n\t\\caption{\n\t\tSolver wallclock-time vs. degrees-of-freedom, for different polynomial degrees $k$,\n\t\tfor problem/Equation (\\ref{eq:ContantCoeffPoissonBenchmark}).\n\t}\n\t\\label{fig:ConstantCoeffRuntimes}\n\\end{figure}\n\n\\newpage\n\n\\subsubsection{DG-Poisson: krylov-cycle Profiling}\n\n\n\\begin{figure}[!h]\n\t\\begin{center}\n\t\t\\input{./apdx-NodeSolverPerformance/PoissonConstCoeff/plots/ConstCoeffPoissonexp_Kcycle_schwarz.tex}\n\t\\end{center}\n\t\\caption{\n\t\tInvestigation of runtime of different code parts of the V-kcycle with additive Schwarz (p-two-grid as block solver) smoother. wallclock-time vs. degrees-of-freedom, for different polynomial degrees $k$,\n\t\tfor problem/Equation (\\ref{eq:ContantCoeffPoissonBenchmark}).\n\t}\n\t\\label{fig:SIP_blockJacobianPCG}\n\\end{figure}\n\\newpage\n\n\\subsubsection{DG-Poisson: preconditioned GMRES Profiling}\n\n\\begin{figure}[!h]\n\t\\begin{center}\n\t\t\\input{./apdx-NodeSolverPerformance/PoissonConstCoeff/plots/ConstCoeffPoissonexp_gmres_levelpmg.tex}\n\t\\end{center}\n\t\\caption{\n\t\tInvestigation of runtime of different code parts of the preconditioned GMRES algorithm. Wallclock-time vs. degrees-of-freedom, for different polynomial degrees $k$,\n\t\tfor problem/Equation (\\ref{eq:ContantCoeffPoissonBenchmark}).\n\t}\n\t\\label{fig:SIP_SchwarzPGC}\n\\end{figure}\n\\newpage\n\n\\subsection{Xdg-Poisson test problem}\n\\label{sec:XdgPoisson}\n\n\\newcommand{\\frakA}{\\mathfrak{A}}\n\\newcommand{\\frakB}{\\mathfrak{B}}\n\\newcommand{\\nOmega}{\\vec{n}_{\\partial \\Omega } }\n%\\newcommand*{\\jump}[1]{\\left\\llbracket {#1} \\right\\rrbracket}\n\\newcommand{\\frakI}{\\mathfrak{I}}\n\\newcommand{\\nI}{\\vec{n}_\\frakI}\n\nThe test problem can be considered as stationary 3 dimensional heat equation with source-term and with two phases:\n\\begin{equation}\n\\left\\{ \\begin{array}{rll}\n- \\mu \\Delta u                   & = f               & \\text{ in } \\Omega \\setminus \\frakI , \\\\\n\\jump{u}                         & = 0               & \\text{ on } \\frakI ,                  \\\\\n\\jump{\\mu \\nabla u \\cdot \\nI}    & = 0               & \\text{ on } \\frakI ,                  \\\\\nu                                & = g_\\text{Diri}   & \\text{ on } \\Gamma_\\mathrm{Diri} ,    \\\\\n\\nabla u \\cdot \\nOmega           & = g_\\text{Neu}    & \\text{ on } \\Gamma_\\mathrm{Neu} .     \\\\\n\\end{array}\n\\right.\n\\label{eq:XdgPoissonBenchmark}\n\\end{equation}\nwith a constant diffusion coefficient in each subdomain\n\n\n\\begin{equation}\n\\mu (\\vec{x}) = \n\\left\\{ \\begin{array}{ll}\n\\mu_\\frakA & \\text{for } \\vec{x} \\in \\frakA, \\\\\n\\mu_\\frakB & \\text{for } \\vec{x} \\in \\frakB. \\\\\n\\end{array} \\right.\n\\label{eq:DiscDiffKoeff}\n\\end{equation}\n\nwhere $\\mu_1=1$ (inner) and $\\mu_2=1000$ (outer) characterize the two phases. is investigated on a uniform, equidistant Cartesian grid. See \\ref{fig:XdgRuntimes} for results.\n\n\\graphicspath{{./apdx-NodeSolverPerformance/XDGPoisson/plots/}}\n\n\\subsubsection{Xdg-Poisson: scaling of solvers}\n\n\\begin{figure}[!h]\n\t\\begin{center}\n\t\t\\input{./apdx-NodeSolverPerformance/XDGPoisson/plots/XdgPoissonScaling.tex}\n\t\\end{center}\n\t\\caption{\n\t\tSolver runtime vs. degrees-of-freedom, for different polynomial degrees $k$,\n\t\tfor problem/Equation (\\ref{eq:XdgPoissonBenchmark}).\n\t}\n\t\\label{fig:XdgRuntimes}\n\\end{figure}\n\\newpage\n\n\\subsubsection{Xdg-Poisson: krylov-cycle Profiling}\n\n\n\\begin{figure}[!h]\n\t\\begin{center}\n\t\t\\input{./apdx-NodeSolverPerformance/XDGPoisson/plots/XdgPoissonexp_Kcycle_schwarz.tex}\n\t\\end{center}\n\t\\caption{\n\t\tInvestigation of runtime of different code parts of the block Jacobian PCG. Solver runtime vs. degrees-of-freedom, for different polynomial degrees $k$,\n\t\tfor problem/Equation (\\ref{eq:XdgPoissonBenchmark}).\n\t}\n\t\\label{fig:Xdg_blockJacobianPCG}\n\\end{figure}\n\n\\subsubsection{Xdg-Poisson: preconditioned GMRES Profiling}\n\n\n\\newpage\n\\begin{figure}[!h]\n\t\\begin{center}\n\t\t\\input{./apdx-NodeSolverPerformance/XdgPoisson/plots/XdgPoissonexp_gmres_levelpmg.tex}\n\t\\end{center}\n\t\\caption{\n\t\tInvestigation of runtime of different code parts of the Schwarz PCG. Solver runtime vs. degrees-of-freedom, for different polynomial degrees $k$,\n\t\tfor problem/Equation (\\ref{eq:XdgPoissonBenchmark}).\n\t}\n\t\\label{fig:Xdg_SchwarzPGC}\n\\end{figure}\n\\newpage\n\n\\subsection{Xdg-Stokes test problem}\n\nAs a test case for a two-phase stokes problem with Xdg approach, we choose an ellipsoid within a closed cube. The body is not touching the cube. There is no gravitational force and the boundaries are considered as walls ($\\vec{u}_\\mathrm{Diri}=\\vec{0}$).\n\n\\newcommand{\\divergence}[1]{{\\mathrm{div}\\left({#1}\\right)}}\n\\newcommand{\\normI}{{\\vec{n}_{\\frakI}}}\n\n\\begin{equation}\n\\left\\{ \\begin{array}{rll}\n\n\\nabla p\n- \n\\divergence{\\mu ( \\nabla \\vec{u} + (   \\nabla \\vec{u})^T ) }  \n& = 0  \n& \\text{ in } \\Omega \\setminus \\frakI = (-1,1)^3 , \\\\\n\\textrm{div}(\\vec{u})  &=  0    \n& \\text{ in } \\Omega \\setminus \\frakI , \\\\\n\\jump{\\vec{u}} & =  0\n& \\text{ on } \\frakI \\\\ \n\\jump{\n\tp \\nI\n\t- \\mu ( \\nabla \\vec{u} + (   \\nabla \\vec{u})^T ) \\cdot \\nI\n}\n& = \n\\sigma \\kappa \\normI\n& \\text{ on } \\frakI(t), \\\\ \nu  & = \\vec{u}_\\mathrm{Diri}   \n& \\text{ on } \\Gamma_\\mathrm{Diri} .    \\\\\n\\end{array} \\right.\n\\label{eq:XdgStokes-Benchmark}\n\\end{equation}\nwith piece-wise constant density and viscosity for both phases, i.e.\n\\begin{equation}\n\\rho(\\vec{x}) = \\left\\{ \\begin{array}{ll}\n\\rho_\\frakA & \\textrm{for } \\vec{x} \\in \\frakA \\\\\n\\rho_\\frakB & \\textrm{for } \\vec{x} \\in \\frakB \\\\\n\\end{array} \\right.\n\\quad \\textrm{and} \\quad\n\\mu(\\vec{x}) = \\left\\{ \\begin{array}{ll}\n\\mu_\\frakA & \\textrm{for } \\vec{x} \\in \\frakA \\\\\n\\mu_\\frakB & \\textrm{for } \\vec{x} \\in \\frakB \\\\\n\\end{array} \\right.\n.\n\\label{eq:defRhoAndMu}\n\\end{equation}\nFurthermore, $\\sigma$ denotes surface tension and $\\kappa$ denotes the \nmean curvature of $\\frakI$. The body (ellipsoid) is defined by a level-set function:\n\n\\begin{equation}\n(x/(\\beta*r))^2 + (y/r)^2 +(z/r)^2-1=0\n\\end{equation} \n\nwhere $\\beta=0.5$ is the spherical aberration and $r=0.5$ the radius. The physical parameters are:\n\n\\begin{table}[h]\n\t\\centering\n\t\\begin{tabular}{l|c}\n\t\t$\\rho_A$ & 1e-3  $kg / cm^3$\\\\\n\t\t$\\rho_B$ & 1.2e-6  $kg / cm^3$\\\\\n\t\t$\\mu_A$ & 1e-5 $kg / cm / sec$\\\\\n\t\t$\\mu_B$ & 17.1e-8 $kg / cm / sec$\\\\\n\t\t$\\sigma$ & 72.75e-3 $kg / sec^2$\\\\\n\t\\end{tabular}\n\\end{table}\n\nThe surface tension is inducing a velocity field around the ellipsoid. This test case is non-physical due to the static body. A more realistic body would reshape to compensate the surface tension, which leads to oscillation of the body.\n\n\\graphicspath{{./apdx-NodeSolverPerformance/XDGStokes/plots/}}\n\n\\subsubsection{Xdg-Poisson: scaling of solvers}\n\n\\begin{figure}[!h]\n\t\\begin{center}\n\t\t\\input{./apdx-NodeSolverPerformance/XDGStokes/plots/XdgStokesScaling.tex}\n\t\\end{center}\n\t\\caption{\n\t\tSolver runtime vs. degrees-of-freedom, for different polynomial degrees $k$,\n\t\tfor problem/Equation (\\ref{eq:XdgStokes-Benchmark}).\n\t}\n\t\\label{fig:XdgStokes-scaling}\n\\end{figure}\n\nThe size of Schwarzblocks was set to 10.000 DOF. It is known, that this raises the number of iterations and therefore the number of Schwarz blocks shall be constant for next study ... \n\n\\newpage\n\n\\subsubsection{Xdg-Poisson: krylov-cycle Profiling}\n\n\n\\begin{figure}[!h]\n\t\\begin{center}\n\t\t\\input{./apdx-NodeSolverPerformance/XDGStokes/plots/XdgStokesexp_Kcycle_schwarz.tex}\n\t\\end{center}\n\t\\caption{\n\t\tInvestigation of runtime of different code parts of the block Jacobian PCG. Solver runtime vs. degrees-of-freedom, for different polynomial degrees $k$,\n\t\tfor problem/Equation (\\ref{eq:XdgStokes-Benchmark}).\n\t}\n\t\\label{fig:XdgStokes-kcylce}\n\\end{figure}\n\n\\cleardoublepage\n\n\\section{Solver Performance - Navier-Stokes problems}\n\\label{sec:SolverPerformanceNSE}\nDifferent solver strategies are conducted to solve the fully coupled incompressible Navier-Stokes equations. At the moment the following strategies can be examined:\n\\begin{itemize}\n\t\\item Linearizsation of the NSE with: Newton(Gmres) or Picard\n\t\\item Solving the linear problem with a Gmres approach or the direct solver MUMPS\n\t\\item Preconditioning with Additive-Schwarz domain decomposition (with coarse solve on the coarsest multigrid level) and direct solver MUMPS for the Blocks (Automatic)\n\t\\item Preconditioning with Additive-Schwarz kcycle Blocks on the coarsest multigrid level (with coarse solve on the coarsest multigrid level) and direct solver MUMPS for the Blocks\n\\end{itemize}\n\\subsection{Driven Cavity 3D}\nThe problem\n\\begin{equation}\n\\left\\{ \\begin{array} {rclll}\n\\rho_f\\Big(\\frac{\\partial \\vec{u}}{\\partial t}+ \\vec{u} \\cdot \\nabla \\vec{u}\\Big) +\\nabla p - \\mu_f \\Delta \\vec{u} & = & \\vec{f}\n& \\text{and}\\   &  \\\\\n% ----\n\\nabla \\cdot \\vec{u} & = & 0\n& \\text{in}\\ \\Omega = (-0.5,0.5) \\times (-0.5,0.5) \\times (-0.5,0.5)  & \\\\\n\\vec{u}_D & = & \\{1,0,0 \\}\n& \\text{on}\\ \\Gamma_D = \\{ (x,y,0z) \\in \\real^3; \\ z = 0.5 \\}\n& \\text{Dirichlet-boundary}\\\\\n\\vec{u}_W & = & 0\n& \\text{on}\\ \\Gamma_W = \\partial \\Omega \\setminus \\Gamma_D\n& \\text{Dirichlet-boundary}\\\\\n\\vec{u}_0(x,y,z) & = & \\{1,0,0\\}\n& \\text{in}\\ \\Omega = (-0.5,0.5) \\times (-0.5,0.5) \\times (-0.5,0.5)\n& \\text{Initial Condition}\n\\end{array} \\right.\n\\label{eq:NavierStokesCavityBenchmark}\n\\end{equation}\nis investigated on different cartesian grids. The physical parameters of the fluid are choosen to be $\\rho_f=1$ and $\\mu_f=0.0025$ which renders down to a Reynoldsnumber of 400.\n\n\\graphicspath{{./apdx-NodeSolverPerformance/NavierStokesDrivenCavity/plots/}}\n\n\\begin{figure}[h!]\n\t\\begin{center}\n\t\t\\input{./apdx-NodeSolverPerformance/NavierStokesDrivenCavity/plots/NodePerformance.tex}\n\t\\end{center}\n\t\\caption{\n\t\tSolver runtime vs. DoFs, for polynomial degree $k=2/1$,\n\t\tfor problem/Equation (\\ref{eq:NavierStokesCavityBenchmark}).\n\t}\n\t\\label{fig:DrivenCavity}\n\\end{figure}", "meta": {"hexsha": "ea3fe6f357106990f7e57ca8d501ebc031f36986", "size": 14687, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/handbook/apdx-NodeSolverPerformance/NodeSolverPerformance.tex", "max_stars_repo_name": "FDYdarmstadt/BoSSS", "max_stars_repo_head_hexsha": "974f3eee826424a213e68d8d456d380aeb7cd7e9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2017-06-08T05:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-25T13:12:17.000Z", "max_issues_repo_path": "doc/handbook/apdx-NodeSolverPerformance/NodeSolverPerformance.tex", "max_issues_repo_name": "FDYdarmstadt/BoSSS", "max_issues_repo_head_hexsha": "974f3eee826424a213e68d8d456d380aeb7cd7e9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-07-20T15:32:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-20T15:34:22.000Z", "max_forks_repo_path": "doc/handbook/apdx-NodeSolverPerformance/NodeSolverPerformance.tex", "max_forks_repo_name": "FDYdarmstadt/BoSSS", "max_forks_repo_head_hexsha": "974f3eee826424a213e68d8d456d380aeb7cd7e9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2018-01-05T19:52:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-07T07:49:27.000Z", "avg_line_length": 40.2383561644, "max_line_length": 426, "alphanum_fraction": 0.7155988289, "num_tokens": 4600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.33893683676997993}}
{"text": "\\chapter{Experiment preparation}\n\n\\epigraph{\\textit{On est trop souvent imprécis lorsqu'on fait une citation.}}{Quelqu'un, un jour.}\n\nGenerative part of all experiments\n\n\\section{Base Z cercle}\n\n\\begin{lstlisting}\ndef complex_cal(qc, statevector_sim):\n    statevector_job = execute(qc, statevector_sim)\n    statevector_result = statevector_job.result()\n    psi = statevector_result.get_statevector()\n    z0 = psi[0]\n    z1 = psi[1]\n    if z1.real != 0 or z1.imag != 0:\n        z = z0/z1\n        z = round(z.real, 2) + round(z.imag, 2) * 1j\n    else:\n        z = 0\n    return z\n\ninit_q = QuantumRegister(1, 'q')\nqc_cercle = QuantumCircuit(init_q)\n\ntab_cercle = [[], []]\nx_cercle = []\ny_cercle = []\ntab_temp = []\nz0 = 0+0j\nz1 = 0+0j\nz = 0+0j\n\nshots = 100\nmax_shots = 1\nqc_cercle.h(init_q)\nfor w in range(max_shots):\n    for i in range(shots):\n        qc_cercle.rz(pi/(shots/8), init_q)\n        z = complex_cal(qc_cercle, statevector_sim)\n        if z != 0:\n            tab_temp.append(z)\n    qc_cercle.barrier()\n    \n    if (w + 1) % 5 == 0:\n        print(\"Full circuit bloch :\", w+1, \"/\", max_shots)\n\nprint(\"Fini!\")\n\nfor i in tab_temp:\n    iteration = tab_temp.count(i)\n    if tab_cercle[0].count(i) < 1:\n        tab_cercle[0].append(i)\n        tab_cercle[1].append(iteration)\n\nfor i in range(len(tab_cercle[0])):\n    x_cercle.append(tab_cercle[0][i].real)\n    y_cercle.append(tab_cercle[0][i].imag)\n\nprint(\"Total of SV :\", len(tab_temp))\n\\end{lstlisting}\n\n\n\\section{Generical functions}\n\n\\subsection{Qubit and variable preparation}\n\\begin{lstlisting}\ninit_q = QuantumRegister(1, 'q')\nqc = QuantumCircuit(init_q)\n\ntab = [[], []]\nx = []\ny = []\nx_north = []\ny_north = []\nx_south = []\ny_south = []\ntab_temp = [[], [], []]\nz0 = 0+0j\nz1 = 0+0j\nz = 0+0j\nz_north = 0*0j\nz_south = 0*0j\n\nshots = 100   # Never change -> Concidere it as 1 full circuit\nmax_shots = 100   # Change in fonction of how many full block we want \n\\end{lstlisting}\n\n\\subsection{Transform spherical plan to 2d plan}\n\n\\begin{lstlisting}\ndef complex_cal(qc, statevector_sim):\n    statevector_job = execute(qc, statevector_sim)\n    statevector_result = statevector_job.result()\n    psi = statevector_result.get_statevector()\n    z0 = psi[0]\n    z1 = psi[1]\n    if z1.real != 0 or z1.imag != 0:\n        z = z0/z1\n        z = round(z.real, 2) + round(z.imag, 2) * 1j\n        if np.abs(z0.real) >= 1.0 / np.sqrt(2):\n            z_north = z0/z1\n            z_north = round(z_north.real, 2) + round(z_north.imag, 2) * 1j\n            z_south = 0\n            return z, z_north, z_south\n        if np.abs(z0.real) <= 1.0 / np.sqrt(2):\n            z_south = z0/z1\n            z_south = round(z_south.real, 2) + round(z_south.imag, 2) * 1j\n            z_north = 0\n            return z, z_north, z_south\n    else:\n        z = 0\n        z_north = 0\n        z_south = 0\n    return z, z_north, z_south\n\\end{lstlisting}\n\n\\subsection{Data analyse for plan}\n\n\\begin{lstlisting}\nfor i in tab_temp[0]:\n    iteration = tab_temp[0].count(i)\n    if tab[0].count(i) < 1:\n        tab[0].append(i)\n        tab[1].append(iteration)\n\n# the whole world\nfor i in range(len(tab[0])):\n    x.append(tab[0][i].real)\n    y.append(tab[0][i].imag)\n# northern hemisphere\nfor i in range(len(tab_temp[1])):\n    x_north.append(tab_temp[1][i].real)\n    y_north.append(tab_temp[1][i].imag)\n# southern hemisphere\nfor i in range(len(tab_temp[2])):\n    x_south.append(tab_temp[2][i].real)\n    y_south.append(tab_temp[2][i].imag)\n\nprint(\"Total of SV :\", len(tab_temp[0]))\n\\end{lstlisting}\n\n\\section{Graph}\n\n\\begin{lstlisting}\nplt.scatter(x_cercle, y_cercle, c=tab_cercle[1], s=1, cmap=\"coolwarm\")\nplt.scatter(x, y, c=tab[1], s=1, cmap=\"coolwarm\")\nplt.colorbar()\nprint(\"Number of different value : \", len(x))\n\\end{lstlisting}\n\n\\begin{lstlisting}\nprint(\"The whole world !\")\ngen_tab = [[], [], []]\nzoom_in = 4\n\nfor i in range(len(x)):\n    if (x[i] > -1.05 and x[i] < 2) and (y[i] > -1.05 and y[i] < 1.05):\n        gen_tab[0].append(x[i])\n        gen_tab[1].append(y[i])\n        gen_tab[2].append(tab[1][i])\n\n#plt.scatter(x_cercle, y_cercle, c=tab_cercle[1], s=2, cmap=\"coolwarm\")\nplt.scatter(gen_tab[0], gen_tab[1], c=gen_tab[2], s=2, cmap=\"coolwarm\")\n#plt.colorbar()\nprint(\"Number of different values in zoom : \", len(gen_tab[0]), \"/\", len(x))\n\\end{lstlisting}\n\n\n\n\n", "meta": {"hexsha": "f38da76fe2f7989089a4e1e5dc1fece8289b95cd", "size": 4277, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "qiskit/qfractals/latex_files/Chapitre0/chapitre0.tex", "max_stars_repo_name": "mickahell/quantum_experiences", "max_stars_repo_head_hexsha": "4f94d9e536f4906e798a00439e6927fd0a55f593", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-10T18:35:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T18:35:14.000Z", "max_issues_repo_path": "qiskit/qfractals/latex_files/Chapitre0/chapitre0.tex", "max_issues_repo_name": "mickahell/quantum_experiments", "max_issues_repo_head_hexsha": "4f94d9e536f4906e798a00439e6927fd0a55f593", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qiskit/qfractals/latex_files/Chapitre0/chapitre0.tex", "max_forks_repo_name": "mickahell/quantum_experiments", "max_forks_repo_head_hexsha": "4f94d9e536f4906e798a00439e6927fd0a55f593", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8662790698, "max_line_length": 98, "alphanum_fraction": 0.6200607903, "num_tokens": 1462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.33893683676997993}}
{"text": "\\documentclass[12pt]{article}\n\\usepackage{theorem}\n\\usepackage{amsmath,amssymb,latexsym,xspace,float,multirow,fancyvrb,xr-hyper,xr}\n\\usepackage{subfigure,epsfig,url}\n\\usepackage[breaklinks=true]{hyperref}\n\\usepackage{amsmath,latexsym,epsfig}\n\\floatstyle{ruled}\n\\newfloat{Algorithm}{tb}{lox}\n\\floatname{Algorithm}{Algorithm}\n\\usepackage{paralist}\n\\usepackage{afterpage}\n\\usepackage{natbib}\n\\usepackage{color}\n\n\\newfloat{Algorithm}{tb}{lox}\n\\floatname{Algorithm}{Algorithm}\n\n\n\\def\\bw{{\\boldsymbol w}}\n\\def\\balpha{{\\boldsymbol \\alpha}}\n\\def\\bd{{\\boldsymbol d}}\n\\def\\be{{\\boldsymbol e}}\n\\def\\bzero{{\\boldsymbol 0}}\n\\def\\bx{{\\boldsymbol x}}\n\\def\\by{{\\boldsymbol y}}\n\\def\\bxi{{\\boldsymbol \\xi}}\n\\def\\liblinear{{\\sf LIBLINEAR}\\xspace}\n\n\n\\begin{document}\n\\title{LIBLINEAR MKL Document}\n\\author{Ming-Hen Tsai \n  \\\\ Ph.D student, Columbia University\n  \\\\ mt2767@columbia.edu}\n\\maketitle\n\\section{Introduction to Multiple Kernel Learning SVM}\nThe original multiple kernel learning SVM has a dual form,\n\\begin{equation}\n\\label{eq:mkl_svm_dual}\n\\min_{\\bd} \\min_{\\balpha} \\frac{1}{2} \\balpha^T Q \\balpha + \\gamma \\balpha^T \\balpha - \\be^T \\balpha \n\\end{equation}\n, where \n\\begin{equation}\n\\label{eq:mkl_svm_dual_sum_kernel}\nQ = \\sum_{m=1}^M d_m Q_m \n\\end{equation}\n, subject to\n\\begin{align}\n\\label{eq:mkl_svm_dual_eq_constraint}\n\\balpha^T \\by = 0 \\\\\n\\sum_m \\|d_m\\| = 1\n\\end{align}\nand\n\\begin{align}\n\\label{eq:mkl_svm_dual_ineq_constraint}\nd_m \\ge 0 \\quad \\forall m\\\\\n0 \\le \\alpha_i \\le U \\quad \\forall i \\mbox{.}\n\\end{align}\n\nL2-regularized L1-loss SVM has $U = C$ and $\\gamma = 0$. While\nL2-regularized L2-loss SVM has $U = \\infty$ and $\\gamma = \\frac{1}{2C}$.\n\nIt has a corresponding primal form (without considering $\\bd$),\n\\begin{equation}\n\\label{eq:mkl_svm_primal}\n\\min_{\\bd} \\min_{\\bw,b} \\frac{1}{2} \\sum_m \\frac{1}{d_m} \\bw_m^T \\bw_m + \\sum_i \\xi^p\n\\end{equation}\n, subject to\n\\begin{align}\n\\label{eq:mkl_svm_primal_ineq_constraint}\n\\sum_m \\|d_m\\| = 1\\\\\nd_m \\ge 0 \\quad \\forall m\\\\\n\\xi_i \\ge 0 \\\\\n\\xi_i \\ge 1-y_i \\sum_m \\bw_m^T \\phi_m(\\bx_i) + b \\quad \\forall i \\mbox{.}\n\\end{align}\n\nThe primal-dual correspondence is\n\\begin{equation}\n\\label{eq:primal_dual_correspondence_w}\n\\bw_m = d_m \\sum_i y_i \\alpha_i \\phi_m(x_i) \n\\end{equation}\n, and\n\\begin{equation}\n\\label{eq:primal_dual_correspondence_Q}\nQ_m = \n[y_1\\phi_m(\\bx_1)  y_2\\phi_m(\\bx_2) \\ldots y_l\\phi_m(\\bx_l)]^T \n[y_1\\phi_m(\\bx_1)  y_2\\phi_m(\\bx_2) \\ldots y_l\\phi_m(\\bx_l)]\n\\end{equation}\n\nFor L2-regularized L1-loss SVM, $p=1$.\nFor L2-regularized L2-loss SVM, $p=2$.\n\n\\section{Dual Coordinate Descent for Multiple Kernel Learning SVM}\n\nIn practice, we can use a formulation without $b$, and obtaining similar performance. \nIf we want this $b$, we can add a dimension of all ones to all training instances $\\bx_i$ to get a similar formula. \nDetails can be found in \\liblinear document.\n\n\n\nBy not using $b$, we get a new primal formula that has \n$b=0$ in \\eqref{eq:mkl_svm_primal_ineq_constraint} \nand will not have \\eqref{eq:mkl_svm_dual_eq_constraint} in the dual form.\n\n\n\n\nBy letting $\\bd$ as constants, we let the dual objective function as\n$$ f(\\balpha) = \\frac{1}{2} \\balpha^T Q \\balpha + \\frac{1}{2} \\gamma \\balpha^T \\balpha - \\be^T \\balpha  $$\nIt has gradient \n$$ \\nabla f(\\balpha) = Q \\balpha + \\gamma \\balpha - \\be \\mbox{.} $$\nIn dimension $i$, it is\n\\begin{align}\n\\label{eq:gradient_one_dim}\n\\nabla_i f(\\balpha) & = \\sum_j \\alpha_j Q_{ij} \\balpha + \\gamma \\alpha_i  - 1 \\\\\n                    &  \\mbox{By \\eqref{eq:primal_dual_correspondence_Q}} \\\\\n                    & = \\sum_j \\alpha_j \\sum_m d_m y_i y_j \\phi_m(x_i) \\phi_m(x_j) \\balpha + \\gamma \\alpha_i  - 1 \\\\\n                     & \\mbox{By \\eqref{eq:primal_dual_correspondence_w}} \\\\\n                     & = y_i \\sum_m w_m^T \\phi_m(\\bx_i) + \\gamma \\alpha_i -1 \\mbox{.}\n\\end{align}\n\nLet $\\be_i$ be the vector with $i$-th dimension as one and all others zero.\nLet $g(d) = f(\\balpha + d\\be_i)$. \n\\begin{equation}\n\\label{eq:second_order_opt}\n\\arg \\inf_d g(d) =  \\nabla_i f(\\balpha) /(Q_{ii} + \\gamma)\n\\end{equation}\n  is the lowest point of the quadratic figure.\n\n\n\n\nFor notation convenience, we let $$\\bw = [\\bw_1^T \\bw_2^T \\ldots \\bw_M^T]^T$$\nand $$\\bar{\\bx_i} = [\\phi_1(\\bx_i)^T \\phi_2(\\bx_i)^T \\ldots \\phi_M(\\bx_i)^T]^T \\mbox{.}$$ \nSo \\eqref{eq:gradient_one_dim} becomes\n\\begin{equation}\n\\label{eq:gradient_one_dim_simplified}\n\\nabla_i f(\\balpha)  = y_i \\bw^T \\bar{\\bx_i} + \\gamma \\alpha_i  - 1 \\mbox{.}\n\\end{equation}\n\n\t\nHere comes a dual coordinate descent method for multiple kernel learning SVM in primal in Algorithm \\ref{alg:dual-cd-mkl}.\n\n\nNow, we can take $\\bd$ into consideration. By fixing other parameters, $\\bd$ can be solved by linear programming methods. Then, we can alternatively solve linear SVM and a linear programming problem. It is the core idea in \\liblinear MKL.\n\n\n\\begin{Algorithm}\n\t\\caption{A dual coordinate descent method for MKL SVM}\n\t\\label{alg:dual-cd-mkl}\n\\begin{compactitem}\n\t\t\\item Given $\\balpha = \\bzero$ and the corresponding $\\bw= \\sum_i y_i \\alpha_i \\bx_i$.\n\t\t\\item While $\\balpha$ is not optimal\n\t\t\t\\begin{description}\n\t\t\t\t\\item  Random choose instance $i$\n            \\begin{enumerate}[(a)]\n          \\item $G = y_i \\bw^T \\bar{\\bx_i} -1 + \\gamma\\alpha_i$ by \\eqref{eq:gradient_one_dim_simplified}\n          \\item \\begin{equation*}\n\t\t\t\t  \\hspace{-25pt}\n\t\t\t\t  PG = \\begin{cases}\n              \\min(G,0) & \\text{if $\\alpha_i = 0$},\\\\\n              \\max(G,0) & \\text{if $\\alpha_i = U$},\\\\\n              G & \\text{if $0<\\alpha_i < U$}\n            \\end{cases}\n          \\end{equation*}\n        \\item If $|PG| \\neq 0$, \\label{step:last}\n          \\begin{itemize}\n\n           \\item[] $\\bar{\\alpha}_i \\leftarrow \\alpha_i$ \n   \t\t  \\item[] $\\alpha_i \\leftarrow \\min (\\max (\\alpha_i - G/(Q_{ii} + \\gamma), 0),U )$ by \\eqref{eq:second_order_opt}\n\t\t\t\t\t\\item[]  $\\bw_m \\leftarrow \\bw_m + d_m (\\alpha_i - \\bar{\\alpha}_i) y_i \\bx_i \\quad \\forall m$\n          \\end{itemize}\n\n\t\t\t\\end{enumerate}\n\t\t\\end{description}\n\t\\end{compactitem}\n\\end{Algorithm}\n\n\n\n\\end{document}\n\n\n\n", "meta": {"hexsha": "133940cc044d5e8f9fba5256474cc03fdd702f10", "size": 6011, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "HCMF/codes/MKL/liblinear-mkl/doc/formula.tex", "max_stars_repo_name": "D-X-Y/MSPLD-2018", "max_stars_repo_head_hexsha": "71a6a75830ac84c7a861e63367ad3ace991fae77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 63, "max_stars_repo_stars_event_min_datetime": "2018-07-12T10:36:25.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-26T11:30:09.000Z", "max_issues_repo_path": "HCMF/codes/MKL/liblinear-mkl/doc/formula.tex", "max_issues_repo_name": "D-X-Y/MSPLD-2018", "max_issues_repo_head_hexsha": "71a6a75830ac84c7a861e63367ad3ace991fae77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HCMF/codes/MKL/liblinear-mkl/doc/formula.tex", "max_forks_repo_name": "D-X-Y/MSPLD-2018", "max_forks_repo_head_hexsha": "71a6a75830ac84c7a861e63367ad3ace991fae77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2018-07-14T02:47:12.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-03T07:39:13.000Z", "avg_line_length": 32.4918918919, "max_line_length": 238, "alphanum_fraction": 0.6704375312, "num_tokens": 2145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.33879209185874376}}
{"text": "\\documentclass[journal,12pt,twocolumn]{IEEEtran}\n\n\\usepackage{setspace}\n\\usepackage{gensymb}\n\n\n\\singlespacing\n\n\\usepackage[cmex10]{amsmath}\n%\\usepackage{amsthm}\n%\\interdisplaylinepenalty=2500\n%\\savesymbol{iint}\n%\\usepackage{txfonts}\n%\\restoresymbol{TXF}{iint}\n%\\usepackage{wasysym}\n\\usepackage{amsthm}\n\n\\usepackage{mathrsfs}\n\\usepackage{txfonts}\n\\usepackage{stfloats}\n\\usepackage{bm}\n\\usepackage{cite}\n\\usepackage{cases}\n\\usepackage{subfig}\n\n\\usepackage{longtable}\n\\usepackage{multirow}\n\n\\usepackage{enumitem}\n\\usepackage{mathtools}\n\\usepackage{steinmetz}\n\\usepackage{tikz}\n\\usepackage{circuitikz}\n\\usepackage{verbatim}\n\\usepackage{tfrupee}\n\\usepackage[breaklinks=true]{hyperref}\n\n\\usepackage{tkz-euclide} %loads TikZ and tkz-base\n\n\\usetikzlibrary{calc,math}\n\\usepackage{listings}\n    \\usepackage{color}                                          \n    \\usepackage{array}                                          \n    \\usepackage{longtable}                                      \n    \\usepackage{calc}                                           \n    \\usepackage{multirow}                                       \n    \\usepackage{hhline}                                         \n    \\usepackage{ifthen}\n    \\usepackage{lscape}     \n\\usepackage{multicol}\n\\usepackage{chngcntr}\n\n\\DeclareMathOperator*{\\Res}{Res}\n\n\\renewcommand\\thesection{\\arabic{section}}\n\\renewcommand\\thesubsection{\\thesection.\\arabic{subsection}}\n\\renewcommand\\thesubsubsection{\\thesubsection.\\arabic{subsubsection}}\n\n\\renewcommand\\thesectiondis{\\arabic{section}}\n\\renewcommand\\thesubsectiondis{\\thesectiondis.\\arabic{subsection}}\n\\renewcommand\\thesubsubsectiondis{\\thesubsectiondis.\\arabic{subsubsection}}\n\n\\hyphenation{op-tical net-works semi-conduc-tor}\n\\def\\inputGnumericTable{}                                 %%\n\n\\lstset{\n%language=C,\nframe=single, \nbreaklines=true,\ncolumns=fullflexible\n}\n\n\\begin{document}\n\n\\newtheorem{theorem}{Theorem}[section]\n\\newtheorem{problem}{Problem}\n\\newtheorem{proposition}{Proposition}[section]\n\\newtheorem{lemma}{Lemma}[section]\n\\newtheorem{corollary}[theorem]{Corollary}\n\\newtheorem{example}{Example}[section]\n\\newtheorem{definition}[problem]{Definition}\n\n\\newcommand{\\BEQA}{\\begin{eqnarray}}\n\\newcommand{\\EEQA}{\\end{eqnarray}}\n\\newcommand{\\define}{\\stackrel{\\triangle}{=}}\n\\bibliographystyle{IEEEtran}\n\\providecommand{\\mbf}{\\mathbf}\n\\providecommand{\\pr}[1]{\\ensuremath{\\Pr\\left(#1\\right)}}\n\\providecommand{\\qfunc}[1]{\\ensuremath{Q\\left(#1\\right)}}\n\\providecommand{\\sbrak}[1]{\\ensuremath{{}\\left[#1\\right]}}\n\\providecommand{\\lsbrak}[1]{\\ensuremath{{}\\left[#1\\right.}}\n\\providecommand{\\rsbrak}[1]{\\ensuremath{{}\\left.#1\\right]}}\n\\providecommand{\\brak}[1]{\\ensuremath{\\left(#1\\right)}}\n\\providecommand{\\lbrak}[1]{\\ensuremath{\\left(#1\\right.}}\n\\providecommand{\\rbrak}[1]{\\ensuremath{\\left.#1\\right)}}\n\\providecommand{\\cbrak}[1]{\\ensuremath{\\left\\{#1\\right\\}}}\n\\providecommand{\\lcbrak}[1]{\\ensuremath{\\left\\{#1\\right.}}\n\\providecommand{\\rcbrak}[1]{\\ensuremath{\\left.#1\\right\\}}}\n\\theoremstyle{remark}\n\\newtheorem{rem}{Remark}\n\\newcommand{\\sgn}{\\mathop{\\mathrm{sgn}}}\n\\providecommand{\\abs}[1]{\\left\\vert#1\\right\\vert}\n\\providecommand{\\res}[1]{\\Res\\displaylimits_{#1}} \n\\providecommand{\\norm}[1]{\\left\\lVert#1\\right\\rVert}\n%\\providecommand{\\norm}[1]{\\lVert#1\\rVert}\n\\providecommand{\\mtx}[1]{\\mathbf{#1}}\n\\providecommand{\\mean}[1]{E\\left[ #1 \\right]}\n\\providecommand{\\fourier}{\\overset{\\mathcal{F}}{ \\rightleftharpoons}}\n%\\providecommand{\\hilbert}{\\overset{\\mathcal{H}}{ \\rightleftharpoons}}\n\\providecommand{\\system}{\\overset{\\mathcal{H}}{ \\longleftrightarrow}}\n\t%\\newcommand{\\solution}[2]{\\textbf{Solution:}{#1}}\n\\newcommand{\\solution}{\\noindent \\textbf{Solution: }}\n\\newcommand{\\cosec}{\\,\\text{cosec}\\,}\n\\providecommand{\\dec}[2]{\\ensuremath{\\overset{#1}{\\underset{#2}{\\gtrless}}}}\n\\newcommand{\\myvec}[1]{\\ensuremath{\\begin{pmatrix}#1\\end{pmatrix}}}\n\\newcommand{\\mydet}[1]{\\ensuremath{\\begin{vmatrix}#1\\end{vmatrix}}}\n\\numberwithin{equation}{subsection}\n\\makeatletter\n\\@addtoreset{figure}{problem}\n\\makeatother\n\\let\\StandardTheFigure\\thefigure\n\\let\\vec\\mathbf\n\\renewcommand{\\thefigure}{\\theproblem}\n\\def\\putbox#1#2#3{\\makebox[0in][l]{\\makebox[#1][l]{}\\raisebox{\\baselineskip}[0in][0in]{\\raisebox{#2}[0in][0in]{#3}}}}\n     \\def\\rightbox#1{\\makebox[0in][r]{#1}}\n     \\def\\centbox#1{\\makebox[0in]{#1}}\n     \\def\\topbox#1{\\raisebox{-\\baselineskip}[0in][0in]{#1}}\n     \\def\\midbox#1{\\raisebox{-0.5\\baselineskip}[0in][0in]{#1}}\n\\vspace{3cm}\n\\title{Matrix Theory (EE5609) Challenging Problem}\n\\author{Arkadipta De\\\\MTech Artificial Intelligence\\\\AI20MTECH14002}\n\\maketitle\n\\newpage\n%\\tableofcontents\n\\bigskip\n\\renewcommand{\\thefigure}{\\theenumi}\n\\renewcommand{\\thetable}{\\theenumi}\n\\begin{abstract}\nThis document proves that $\\vec{A^TA}$ has positive eigen values.\n\\end{abstract}\nDownload latex codes from \n%\n\\begin{lstlisting}\nhttps://github.com/Arko98/EE5609/tree/master/Challenge_5\n\\end{lstlisting}\n%\n\\section{Problem}\nShow that the eigen values of $\\vec{A^TA}$ are positive. \n\\section{Proof}\nLet, $\\vec{A}$ is an arbitrary $m\\times n$ matrix. Now consider the symmetric matrix $\\vec{A^TA}$,\n\\begin{comment}\n\n\\begin{align}\n\\intertext{for any n dimensional vector $\\vec{z}$,}\n\\vec{z^T}(\\vec{A^TA})\\vec{z} &= \\vec{z^TA^T}\\vec{Az}\\\\\n\\implies\\vec{z^T}(\\vec{A^TA})\\vec{z} &= \\vec{({Az})^T}(\\vec{Az})\\\\\n\\implies\\vec{z^T}(\\vec{A^TA})\\vec{z} &= \\norm{\\vec{Az}}^2 \\geq0\\label{eq1}\n\\intertext{From \\eqref{eq1}, if $\\vec{z} \\not=0$, $\\vec{A^TA}$ is positive definite, i.e}\n\\norm{\\vec{Az}}^2 > 0\n\\intertext{Again, $\\vec{A^TA}$ is positive semi-definite, if $\\vec{z} = 0$,}\n\\norm{\\vec{Az}}^2 = 0\n\\end{align}\nHence, $\\vec{A^TA}$ is positive semi-definite if the columns of $\\vec{A}$ are linearly dependent and $\\vec{A^TA}$ is positive definite if columns of $\\vec{A}$ are linearly dependent.\\\\\nAgain,\n\\begin{align}\n\\vec{({A^TA})^T} = \\vec{(A^T)(A^T)^T} = \\vec{A^TA}\\label{eqSym}\n\\end{align}\nHence, $\\vec{A^TA}$ is symmetric. As every eigen value of a Hermitian matrix is real and every symmetric matrix is Hermitian then $\\vec{A^TA}$ (being a symmetric and hence Hermitian) has real eigen values.\\\\\n\n\\end{comment}\nLet $\\lambda$ be a (real) eigenvalue of $\\vec{B}=\\vec{A^TA}$ and let $\\vec{x}$ be a corresponding real eigen-vector hence,\n\\begin{align}\n\\vec{Bx} = \\lambda \\vec{x}\\label{eq2}\n\\intertext{Multiplying $\\vec{x^T}$ in \\eqref{eq2},}\n\\vec{x^TBx} &= \\lambda \\vec{x^T}\\vec{x}\\\\\n\\implies\\vec{x^TBx} &= \\lambda \\norm{\\vec{x}}^2\\\\\n\\implies\\vec{x^T(A^TA)x} &= \\lambda \\norm{\\vec{x}}^2 \\qqaud{\\text{[$\\because\\vec{B}=\\vec{A^TA}$]}}\\\\\n\\implies\\vec{(x^TA^T)Ax} &= \\lambda\\norm{\\vec{x}}^2\\\\\n\\implies\\vec{(Ax)^T(Ax)} &= \\lambda\\norm{\\vec{x}}^2\\\\\n\\implies\\norm{\\vec{Ax}}^2 &= \\lambda\\norm{\\vec{x}}^2\\label{eqFinal}\n\\intertext{In \\eqref{eqFinal} as $\\norm{\\vec{Ax}}^2 > 0$ then,}\n\\lambda > 0\n\\end{align}\n\\begin{comment}\n\nWhen $\\vec{A^TA}$ is positive definite (i.e columns of $\\vec{A}$ are linearly independent) then, the left hand side of \\eqref{eqFinal} is positive as $\\vec{A^TA}$ is positive-definite and $\\vec{x}$ is a nonzero vector as it is an eigen-vector.\\\\\nAlso if $\\vec{A}$ has linearly independent columns then $\\vec{A^TA}$ will be invertible and hence a non-singular matrix, so $\\norm{\\vec{x}}$ cannot be zero in \\eqref{eqFinal}. Since $\\norm{\\vec{Ax}}^2$ is positive, hence all eigen-values must be positive.\\\\\n\n\\end{comment}\nHence proved that all eigen values of $\\vec{A^TA}$ are positive.\n\\end{document}\n", "meta": {"hexsha": "02ad10e7502b6732894a66d1cebe7537ee9cc8e1", "size": 7388, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Challenge_5/Beamer.tex", "max_stars_repo_name": "Arko98/EE5609-Matrix-Theory", "max_stars_repo_head_hexsha": "7c72720b4e5241a9dc3b62b38d4537f2cdd67e07", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Challenge_5/Beamer.tex", "max_issues_repo_name": "Arko98/EE5609-Matrix-Theory", "max_issues_repo_head_hexsha": "7c72720b4e5241a9dc3b62b38d4537f2cdd67e07", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Challenge_5/Beamer.tex", "max_forks_repo_name": "Arko98/EE5609-Matrix-Theory", "max_forks_repo_head_hexsha": "7c72720b4e5241a9dc3b62b38d4537f2cdd67e07", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-09-02T11:29:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-01T17:05:21.000Z", "avg_line_length": 38.4791666667, "max_line_length": 257, "alphanum_fraction": 0.6884136437, "num_tokens": 2553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.33879208855034537}}
{"text": "\\documentclass[12pt]{article}\n\\usepackage[english]{babel}\n\\usepackage{natbib}\n\\usepackage{url}\n\\usepackage[utf8x]{inputenc}\n\\usepackage{amsmath}\n\\usepackage{graphicx}\n\\graphicspath{{img/}}\n\\usepackage{listings}\n\\usepackage{url}\n\\usepackage{parskip}\n\\usepackage{fancyhdr}\n\\usepackage{vmargin}\n\\setmarginsrb{3 cm}{2.5 cm}{3 cm}{2.5 cm}{1 cm}{1.5 cm}{1 cm}{1.5 cm}\n\n\\title{Lab Report on \\\\Image Enhancement Techniques.}\t\t\t\t\t\t\t\t% Title\n\\author{Rabi Raj Khadka}\t\t\t\t\t\t\t\t% Author\n\\date{June 27, 2017}\t\t\t\t\t\t\t\t\t\t\t% Date\n\n\n\\makeatletter\n\\let\\thetitle\\@title\n\\let\\theauthor\\@author\n\\let\\thedate\\@date\n\\makeatother\n\n\\pagestyle{fancy}\n\\fancyhf{}\n\\rhead{\\theauthor}\n\\lhead{\\thetitle}\n\\cfoot{\\thepage}\n\n\\begin{document}\n\\begin{titlepage}\n\t\\centering\n   % \\vspace*{0.5 cm}\n    \\includegraphics[scale = 0.3]{kheclogo.jpg}\\\\[1.0 cm]\t% University Logo\n    \\textsc{\\LARGE Khwopa Engineering College}\\\\[1.5 cm]\t% University Name\n\t\\textsc{\\Large Course Code :BEG 475 IP}\\\\[0.5 cm]\t\t\t\t% Course Code\n\t\\textsc{\\large Image Processing and Pattern recogntiion}\\\\[0.5 cm]\t\t\t\t% Course Name\n\t\\rule{\\linewidth}{0.2 mm} \\\\[0.4 cm]\n\t{ \\huge \\bfseries \\thetitle}\\\\\n\t\\rule{\\linewidth}{0.2 mm} \\\\[1.0 cm]\n\t\n\t% \\texttt{Lab Report \\#1}\n\t\n\t\\rule{\\linewidth}{0 mm} \\\\[1.0 cm]\n\n\t\\begin{minipage}{0.4\\textwidth}\n\t\t\\begin{flushleft} \\large\n\t\t\t\\emph{Author:}\\\\\n\t\t\t\\theauthor\n\t\t\t\\end{flushleft}\n\t\t\t\\end{minipage}~\n\t\t\t\\begin{minipage}{0.4\\textwidth}\n\t\t\t\\begin{flushright} \\large\n\t\t\t\\emph{Roll  Number:} \\\\\n\t\t\t700324\t\t\t\t\t\t\t\t\t% Your Student Number\n\t\t\\end{flushright}\n\t\\end{minipage}\\\\[2cm]\n\t\n\t{\\large \\thedate}\\\\[2 cm]\n \n\t\\vfill\n\t\n\\end{titlepage}\n\\tableofcontents\n\\pagebreak\n\\section{Theory}\n\\subsection{Histogram Equalization}\nHistogram equalization is the technique to change the histogram through the use of certain function into a histogram that is constant for a bright value. The probability of occurrence of gray level in an image is approximated by \\\\\n$$P(r_k) = \\frac{n_k}{N}$$  for k=0,1,2...L-1 \\\\\nThe discrete version of transformation is\\\\\n$$ S_k = T(r_k) = \\sum_{j=0}^k P_r(r_j) =  \\sum_{j=1}^k\\frac{n_j}{N}$$ for k=0,1,2,....L-1\\\\\n\n\nHistogram equalization has  a disadvantage that it can generate only one type of output image. But with histogram specification, it can specify the shape of histogram that we wish the output image to have.It does not have to be uniform histogram.\n\\subsection{Histogram Specification}\n\\texttt{ Process for Histogram specification}\n\\begin{enumerate}\n\\item Obtain the transformation function T(r) by calculating the histogram equalized on the input image \n$$ S = T(r) = \\sum_{j=0}^r P_r(r_j) $$\n\\item Obtain the transformation function G(z) by calculating the histogram equalization of desired image \n$$ Z = G(z) = \\sum_{i=0}^z P_z(r_i) $$\n\\item Obtain the inverse transformation function $G^{-1}$\\\\\n$$Z= G^{-1}(S) = G^{-1}[t(r)]$$\n\\item Obtain output image by applying the processed gray level from the inverse transformation function to all the pixels in the image.\n\\end{enumerate}\n\\subsection{Algorithm for Histogram Specification}\n1. Start \\\\\n2. Read source image and reference image\\\\\n3. Break down the picture elements R, G, B of both color image and reference image\\\\\n4. Make a histogram of each of the picture elements of the reference image\\\\\n5. Assign the equalized histogram of the individual picture elements of the source image with reference to the histogram of the reference image\\\\\n6. Merge the individual resultant individual picture elements to another variable ' histsp'  as $$ histsp(:,:,1) = outr; $$ $$ histsp(:,:,2) = outg; $$ $$ histsp(:,:,3) = outb; $$\n7. show the specialized image 'histsp'\\\\\n8. Stop\n\\pagebreak\n\\section{Code Description}\nmyimage = imread('\\path{C\\:\\Users\\rabiraj\\Desktop\\seventhsemester\\ImageProcessingLab\\img\\one.jpg}');\\\\\nreference = imread('\\path{C\\:\\Users\\rabiraj\\Desktop\\seventhsemester\\ImageProcessingLab\\img\\two.jpg}');\\\\\nmyimage\\_R=myimage(:,:,1);myimage\\_G=myimage(:,:,2);myimage\\_B=myimage(:,:,3);\\\\\nreference\\_R=reference(:,:,1);reference\\_G=reference(:,:,2);reference\\_B=reference(:,:,3);\\\\\nhist\\_myimage\\_R=imhist(myimage\\_R);\\\\\nhist\\_myimage\\_G=imhist(myimage\\_G);hist\\_myimage\\_B=imhist(myimage\\_B);\\\\\nhist\\_reference\\_R=imhist(reference\\_R);\\\\\nhist\\_reference\\_G=imhist(reference\\_G);hist\\_reference\\_B=imhist(reference\\_B);\\\\\noutr =histeq(myimage\\_R,hist\\_reference\\_R);\\\\\noutg=histeq(myimage\\_G,hist\\_reference\\_G);outb=histeq(myimage\\_B,hist\\_reference\\_B);\\\\\nhistsp(:,:,1)=outr;histsp(:,:,2)=outg;histsp(:,:,3)=outb;\\\\\nimg\\_lowcontrast=imadjust(rgb2gray(myimage),[0.0,1.0],[0.3,0.6]);  \\\\\nimg\\_equalization = histeq(rgb2gray(myimage));\\\\\nfigure;\\\\\nsubplot(2,3,1);imshow(myimage);title('Original');\\\\\nsubplot(2,3,4);imhist(rgb2gray(myimage));title('original histogram');\\\\\nsubplot(2,3,2);imshow(img\\_lowcontrast);title('lowcontrast image');\\\\\nsubplot(2,3,5);imhist(img\\_lowcontrast);title('lowcontrast histogram');\\\\\nsubplot(2,3,3);imshow(img\\_equalization);title('Equalized Image');\\\\\nsubplot(2,3,6);imhist(img\\_equalization);title('Equalized histogram');\\\\\nfigure;\\\\\nsubplot(1,3,1);imshow(myimage);title('Original Image');\\\\\nsubplot(1,3,2);imshow(reference);title('Reference image');\\\\\nsubplot(1,3,3);imshow(histsp);title('Output Image');\\\\\nfigure;\\\\\nsubplot(3,3,1);plot(hist\\_myimage\\_R);title('Red Input');\\\\\nsubplot(3,3,2);plot(hist\\_myimage\\_G);title('Green Input');\\\\\nsubplot(3,3,3);plot(hist\\_myimage\\_B);title('Blue Input');\\\\\nsubplot(3,3,4);plot(hist\\_reference\\_R);title('Red Reference');\\\\\nsubplot(3,3,5);plot(hist\\_reference\\_G);title('Green Reference');\\\\\nsubplot(3,3,6);plot(hist\\_reference\\_B);title('Blue Reference');\\\\\nsubplot(3,3,7);plot(imhist(outr));title('output R');\\\\\nsubplot(3,3,8);plot(imhist(outg));title('output G');\\\\\nsubplot(3,3,9);plot(imhist(outb));title('output B');\n%\\lstinputlisting[language=Matlab]{labfive.m}\n\\pagebreak\n\\section{Result and Discussion}\nThe histogram of an image can be adjusted as per the user requirement. IN the image we have used, the point to be stretched is calculated by dividing the current positions of the begin and end point of the histogram by 255. By this we can adjust/stretch the image histogram. The histogram of the image can also equalized using the histeq() function\\\\\n\nThe histogram of one image is specified / merged with another image to form a specific image. The merged image of the first image and second image can be seen in the third one as in the output Figure 2.\\\\\n\n\\emph{Outputs}\n\n\\includegraphics[scale = 0.6]{output_labfive_1.png}\\\\\n{\\centering\n\\texttt{Figure 1:  Equalized Specification and its Histogram}\\par}\n\\includegraphics[scale = 0.6]{output_labfive_2.png}\\\\\n{\\centering\n\\texttt{Figure 2:  Histogram Specification of two image}\\par}\n\\includegraphics[scale = 0.6]{output_labfive_3.png}\\\\\n{\\centering\n\\texttt{Figure 3:  Histogram of  input images and output images used in Histogram Specification}\\par}\n\\pagebreak\n\\section{Conclusion}\nHence, \\\\\nWe are familiarized with how the Histogram Stretching, Equalization and Specification of an image using the MATLAB application.\n\\end{document}", "meta": {"hexsha": "189d11b657b272b5c49f48e6991a683ed0ca5891", "size": 7036, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "IP_labfive.tex", "max_stars_repo_name": "NeuromanceRCreation/ImageProcessing", "max_stars_repo_head_hexsha": "b3eb9937bb8aa96d52c96afc30ed4c57059cc572", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-04T17:12:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-04T17:12:44.000Z", "max_issues_repo_path": "IP_labfive.tex", "max_issues_repo_name": "NeuromanceRCreation/ImageProcessing", "max_issues_repo_head_hexsha": "b3eb9937bb8aa96d52c96afc30ed4c57059cc572", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IP_labfive.tex", "max_forks_repo_name": "NeuromanceRCreation/ImageProcessing", "max_forks_repo_head_hexsha": "b3eb9937bb8aa96d52c96afc30ed4c57059cc572", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.1025641026, "max_line_length": 350, "alphanum_fraction": 0.7258385446, "num_tokens": 2208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.3387920852419469}}
{"text": "\\documentclass[nofootinbib,twocolumn]{revtex4-1}\n\n%%% properly deal with different font encodings\n\\usepackage[utf8]{inputenc}\n\\usepackage[T1]{fontenc}\n\n%%% linking references\n\\usepackage[dvipsnames]{xcolor}\n\\usepackage{hyperref}\n\\hypersetup{\n  breaklinks=true,\n  colorlinks=true,\n  allcolors=BlueViolet,\n}\n\n% use alphanumeric tags for footnotes\n\\renewcommand*{\\thefootnote}{\\alph{footnote}}\n\n%%% symbols, notations, etc.\n\\usepackage{physics,braket,bm} % physics and math\n\\renewcommand{\\t}{\\text} % text in math mode\n\\newcommand{\\f}[2]{\\dfrac{#1}{#2}} % shorthand for fractions\n\\newcommand{\\p}[1]{\\left(#1\\right)} % parenthesis\n\\renewcommand{\\sp}[1]{\\left[#1\\right]} % square parenthesis\n\\newcommand{\\bk}{\\Braket} % shorthand for braket notation\n\\newcommand{\\uv}[1]{\\bm{\\hat{#1}}} % unit vectors\n\\renewcommand{\\i}{\\mathrm{i}\\mkern1mu} % imaginary unit\n\n% curly brackets for a set\n\\renewcommand{\\set}[1]{\\{#1\\}} % curly parenthesis\n\\renewcommand{\\Set}[1]{\\left\\{#1\\right\\}} % curly parenthesis\n\n% double angle brackets\n\\newcommand{\\bbk}[1]{\\langle\\!\\langle #1 \\rangle\\!\\rangle}\n\\newcommand{\\Bbk}[1]\n{\\left\\langle\\!\\!\\left\\langle #1 \\right\\rangle\\!\\!\\right\\rangle}\n\n\\newcommand{\\x}{\\text{x}}\n\\newcommand{\\y}{\\text{y}}\n\\newcommand{\\z}{\\text{z}}\n\n\\newcommand{\\C}{\\mathcal{C}}\n\\newcommand{\\D}{\\mathcal{D}}\n\\newcommand{\\E}{\\mathcal{E}}\n\\newcommand{\\I}{\\mathcal{I}}\n\\newcommand{\\N}{\\mathcal{N}}\n\\renewcommand{\\O}{\\mathcal{O}}\n\\newcommand{\\Q}{\\mathcal{Q}}\n\\renewcommand{\\S}{\\mathcal{S}}\n\n\\def\\obra#1{\\mathinner{({#1}|}}\n\\def\\oket#1{\\mathinner{|{#1})}}\n\\def\\obk#1{\\mathinner{({#1})}}\n\\def\\oop#1#2{\\oket{#1}\\!\\obra{#2}}\n\n\\DeclareMathOperator{\\cov}{cov}\n\\DeclareMathOperator{\\diag}{diag}\n\n%%% figures\n\\usepackage{graphicx} % for figures\n\\graphicspath{{./figures/qudit_tomo/}} % set path for all figures\n\n\\usepackage[inline]{enumitem} % in-line lists\n\\setlist[enumerate,1]{label={(\\roman*)}} % default in-line numbering\n\n%%% text markup\n\\usepackage{color} % text color\n\\newcommand{\\red}[1]{{\\color{red} #1}}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{document}\n\n\\title{Spin qudit tomography and state reconstruction error}\n\\author{Michael A.~Perlin}\n\\email{mika.perlin@gmail.com}\n\\author{Diego Barberena}\n\\author{Ana Maria Rey}\n\\affiliation{JILA, National Institute of Standards and Technology and University of Colorado, 440 UCB, Boulder, Colorado 80309, USA}\n\\affiliation{Center for Theory of Quantum Matter, University of Colorado, Boulder, CO, 80309, USA}\n\n\\keywords{qudits; spin qudits; quantum state tomography}\n\n\\begin{abstract}\nWe consider the task of performing quantum state tomography on a $d$-level spin qudit, using only measurements of spin projection onto different quantization axes.\nAfter introducing a basis of operators closely related to the spherical harmonics, which obey the rotational symmetries of spin qudits, we map our quantum tomography task onto the classical problem of signal recovery on the sphere.\nWe then provide algorithms with $O\\p{rd^3}$ serial runtime, parallelizable down to $O\\p{rd^2}$, for (i) computing a priori upper bounds on the expected error with which spin projection measurements along $r$ given axes can reconstruct an unknown qudit state, and (ii) estimating a posteriori the statistical error in a reconstructed state.\nOur algorithms motivate a simple randomized tomography protocol, for which we find that using more measurement axes can yield substantial benefits that plateau after $r\\approx3d$.\n\\end{abstract}\n\n\\maketitle\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Introduction}\n\nQuantum state tomography, the task of reconstructing a quantum state by collecting and processing measurement data, is an essential primitive for quantum sensing, quantum simulation, and quantum information processing.\nThe central importance of quantum state tomography has led to the development of techniques based on least-squares inversion \\cite{opatrny1997leastsquares}, linear regression \\cite{qi2013quantum}, maximum likelihood estimation \\cite{teo2011quantumstate, smolin2012efficient}, Bayesian inference \\cite{huszar2012adaptive, ferrie2014quantum, granade2016practical}, compressed sensing \\cite{gross2010quantum, kalev2015quantum}, and neural networks \\cite{torlai2018neuralnetwork}, among others.\nThese techniques are typically developed in a general, information-theoretic setting, and make minimal assumptions about the physical medium of a quantum state.\nAs a consequence, even well-established techniques can be ill-suited for physical platforms with unique or limited capabilities.\n\nDue to advancements in experimental capabilities to address nuclear spin states (i.e.~hyperfine levels) in ultracold atomic systems \\cite{daley2011quantum, lu2011strongly, mischuck2012control, aikawa2012boseeinstein, smith2013quantum, cazalilla2014ultracold}, as well as developments in the control of ultracold molecular systems \\cite{bohn2017cold, takekoshi2014ultracold, zeppenfeld2012sisyphus, kozyryev2017sisyphus, puri2017synthesis, wu2017cryofuge, marco2019degenerate, liu2019molecular, anderegg2019optical, chou2020frequencycomb, lin2020quantum}, a particular setting of growing interest is the spin qudit, or a multilevel quantum angular momentum degree of freedom.\nSpin qudits can provide advantages over their qubit counterparts for quantum sensing \\cite{hemmer2018squeezing, evrard2019enhanced}, enable quantum simulations of SU($d$) magnetism \\cite{cazalilla2014ultracold, banerjee2013atomic, zhang2014spectroscopic, scazza2014observation, goban2018emergence, perlin2021engineering}, and offer unique capabilities for quantum computation and error correction \\cite{albert2020robust, gross2021designing, barnes2021assembly}.\nIn all cases, quantum state tomography is necessary to take full advantage of a spin qudit\\footnote{Note that the measurement of collective observables for quantum sensing or simulation can be recast as a single-spin tomography task.}.\n\nThe problem of qudit tomography is not new, with an extensive literature on a variety of techniques \\cite{newton1968measurability, hofmann2004quantumstate, filippov2010inverse, schmied2011tomographic, evrard2019enhanced, flammia2005minimal, thew2002qudit, salazar2012quantum, sosa-martinez2017quantum, ha2018minimal, stefano2019set, palici2020oam}.\nHowever, most existing protocols either rely on infinite-dimensional representations of a quantum spin \\cite{manko1997spin, schmied2011tomographic, evrard2019enhanced}, or require the capability to perform essentially arbitrary operations on a qudit \\cite{thew2002qudit, flammia2005minimal, salazar2012quantum, sosa-martinez2017quantum, ha2018minimal, stefano2019set, palici2020oam}, generally resulting in tomographic protocols that can be highly inefficient or unachievable in practice.\nThe protocols based on infinite-dimensional representations of a quantum spin have the advantage of reconstructing its state from measurements of spin projection onto different spatial axes, which are generally accessible with any spin qudit.\nNonetheless, these protocols obfuscate the minimal requirements for performing full state tomography, provide no straightforward error bounds or guarantees of accuracy, and (with the notable exception of Ref.~\\cite{schmied2011tomographic}) generally extract only a small fraction of the information contained in measurement data.\n\nIn this work, we consider the task of performing spin qubit tomography using only measurements of spin projection onto different spatial axes.\nThis sort of task was first considered in Ref.~\\cite{newton1968measurability}, as well as a few later works \\cite{hofmann2004quantumstate, filippov2010inverse, schmied2011tomographic}.\nSpecifically, Ref.~\\cite{newton1968measurability} provided an explicit protocol for reconstructing a $d$-level spin qudit state from measurements of spin projection along $2d-1$ axes, the minimum number necessary for full tomography of an arbitrary (possibly mixed) qudit state.\nHowever, the protocol in Ref.~\\cite{newton1968measurability} involves a choice of a single (arbitrary) angle $\\theta$, and provides no means for comparing different choices of $\\theta$, which may result in wildly different statistical errors (i.e.~precision) in a reconstructed state.\nOther works provide insightful discussions into the problem of spin qudit tomography, but either\n\\begin{enumerate*}\n\\item require making assumptions about the qudit state in question \\cite{schmied2011tomographic} (making the tomographic protocol only valid for a restricted set of possible states),\n\\item do not address the question of statistical error \\cite{hofmann2004quantumstate}, or\n\\item provide a measure of statistical error that is needlessly conservative and computationally demanding \\cite{filippov2010inverse}.\n\\end{enumerate*}\nWe address these shortcomings in this work, and identify remaining avenues for refining spin qudit tomography protocols.\n\nIn Section \\ref{sec:polarization_ops}, we introduce a set of qudit operators that are closely related to the spherical harmonics, and which play a central role in our work.\nWe then map the quantum problem of spin qudit tomography onto the classical problem of signal recovery on the sphere in Section \\ref{sec:signal_recovery}, thereby providing an intuitive perspective on spin qudit tomography.\nIn Section \\ref{sec:error} we provide a priori upper bounds and a posteriori estimates of the statistical error in a qudit state reconstructed from measurements of spin projection along a given set of $r$ measurement axes.\nThe capability to determine upper bounds on reconstruction error a priori motivates a simple randomized tomography protocol that we outline in Section \\ref{sec:protocol}, and for which we numerically find that using more measurement axes yields substantial benefits that plateau after $r\\approx3d$.\nTo facilitate the use of our protocols, we make all of our codes publicly available at Ref.~\\cite{tomo_codes}, which also contains the best measurement axes we found for $d\\le30$ and $r=3d$.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Polarization operators}\n\\label{sec:polarization_ops}\n\nWe begin by introducing a set of qudit operators that are closely related to the spherical harmonics (in a sense that will be clarified below), and which play a central role in our work.\nConsider a $d$-state spin qudit with total spin $s\\equiv\\frac{d-1}{2}$.\nThe defining property of a spin qudit, distinguishing it from other qudits, is that it describes an angular momentum degree of freedom, which has specific implications for how a spin qudit should transform under the group SO(3) of rotations in 3D space.\nDue to the central importance of these transformation rules for a spin qudit, we seek a basis of operators that transform nicely under 3D rotations\\footnote{Technically speaking, we seek a basis of operators that transform as an irreducible representation of SO(3).}.\nOne such basis is that of the {\\it polarization operators} \\cite{kryszewski2006positivity, bertlmann2008bloch}, defined by\n\\begin{align}\n  T_{\\ell m} \\equiv \\sqrt{\\f{2\\ell+1}{2s+1}} \\sum_{\\mu,\\nu=-s}^s\n  \\bk{s\\mu;\\ell m|s\\nu} \\op{\\nu}{\\mu},\n  \\label{eq:trans_op}\n\\end{align}\nwhere $\\ket\\mu$ is an eigenstate of the axial spin projection operator $S_\\z\\ket\\mu=\\mu\\ket\\mu$; and $\\bk{s\\mu;\\ell m|s\\nu}$ is a Clebsh-Gordan coefficient that enforces $\\ell\\in\\set{0,1,\\cdots,d-1}$ and $m\\in\\set{-\\ell,-\\ell+1,\\cdots,\\ell}$, such that there are $d^2$ polarization operators in total.\nFor brevity, we will generally treat the value of $d$ as constant but arbitrary throughout this work, and we will suppress any explicit dependence of quantities or operators such as $T_{\\ell m}$ on $d$.\nThe polarization operators are orthonormal with respect to the trace inner product, and transform nicely under conjugation:\n\\begin{align}\n  \\obk{T_{\\ell m }|T_{\\ell'm'}}\n  = \\delta_{\\ell\\ell'} \\delta_{mm'},\n  &&\n  T_{\\ell m}^\\dag = \\p{-1}^m T_{\\ell,-m},\n\\end{align}\nwhere for any $d\\times d$ matrix $X=\\sum_{\\mu,\\nu} X_{\\mu\\nu} \\op{\\mu}{\\nu}$ we define the $d^2$-component vector $\\oket{X} \\equiv \\sum_{\\mu,\\nu} X_{\\mu\\nu} \\ket{\\mu\\nu}$; $\\obra{X}$ is the conjugate transpose of $\\oket{X}$, such that $\\obk{X|Y}=\\tr\\p{X^\\dag Y}$; and $\\delta_{kk'}\\equiv 1$ if $k=k'$ and $0$ otherwise.\nThese properties of the polarization operators allow us to expand any density operator $\\rho$ in the polarization operator basis as\n\\begin{align}\n  \\rho = \\sum_{\\ell=0}^{d-1} \\sum_{m=-\\ell}^\\ell\n  \\rho_{\\ell m} T_{\\ell m},\n  &&\n  \\rho_{\\ell m} \\equiv \\bk{T_{\\ell m}^\\dag}_\\rho,\n  \\label{eq:trans_state}\n\\end{align}\nwhere $\\bk{X}_\\rho\\equiv\\tr\\p{\\rho X}=\\obk{\\rho|X}$, and $\\rho^\\dag=\\rho$ implies that $\\rho_{\\ell m}^*=\\p{-1}^m\\rho_{\\ell,-m}$.\nThe polarization operators can be interpreted in terms of an absorption process, whereby $T_{\\ell m}\\ket\\psi$ is (up to normalization) the state obtained after a spin-$s$ state $\\ket\\psi$ absorbs a particle with total spin $\\ell$ and spin projection $m$ onto a fixed quantization axis.\nSimilarly to the complex spherical harmonics $Y_{\\ell m}$, we will refer to $\\ell$ as the {\\it degree} and $m$ as the {\\it order} of $T_{\\ell m}$.\n\nThe polarization operators are spherical tensor operators, whose degree is preserved under 3D rotations generated by the spin operators $S_\\x,S_\\y,S_\\z$.\nMoreover, the degree-$\\ell$ polarization operators $T_{\\ell m}$ transform similarly to spin-$\\ell$ particles and spherical harmonics $Y_{\\ell m}$ under 3D rotations (see Appendix \\ref{sec:rotations}).\nSpecifically, for any triplet of angles $\\bm\\omega=\\p{\\alpha,\\beta,\\gamma}$, we can therefore define the rotation operator\n\\begin{align}\n  R\\p{\\bm\\omega} \\equiv e^{-\\i\\alpha S_\\z} e^{-\\i\\beta S_\\y} e^{-\\i\\gamma S_\\z},\n\\end{align}\nand expand rotated polarization operators as\n\\begin{align}\n  T_{\\bm\\omega\\ell m} \\equiv\n  R\\p{\\bm\\omega} T_{\\ell m} R\\p{\\bm\\omega}^\\dag\n  = \\sum_{n=-\\ell}^\\ell D_{mn}^\\ell\\p{\\bar{\\bm\\omega}}^* T_{\\ell n},\n  \\label{eq:trans_rot}\n\\end{align}\nwhere $\\bar{\\bm\\omega}=\\p{\\gamma,\\beta,\\alpha}$ is the reversal of $\\bm\\omega$, and\n\\begin{align}\n  D_{mn}^\\ell\\p{\\bar{\\bm\\omega}}\n  \\equiv \\bk{\\ell m|R\\p{\\bar{\\bm\\omega}}|\\ell n}\n  \\label{eq:wigner_D}\n\\end{align}\nare (Wigner) rotation matrix elements.\nFor reasons that will become clear shortly, throughout this work we will primarily consider rotations of the sphere that take the north pole to a point $\\bm v=\\p{\\alpha,\\beta}$ at azimuthal angle $\\alpha$ and polar angle $\\beta$.\nFor ease of notation, we therefore define $R\\p{\\bm v} \\equiv R\\p{\\alpha,\\beta,0}$, $T_{\\bm v\\ell m} \\equiv T_{\\p{\\alpha,\\beta,0},\\ell m}$, and $D^\\ell_{mn}\\p{\\bm v} \\equiv D^\\ell_{mn}\\p{0,\\beta,\\alpha}$.\n\nThe polarization operators $T_{\\ell m}$ share a connection to the spherical harmonics $Y_{\\ell m}$ that goes beyond the rules for their transformation under 3D rotations.\nIn fact, the phase-space representation of $T_{\\ell m}$ is proportional to $Y_{\\ell m}$.\nThe phase-space representation of a spin qudit operator $X$ assigns, to each point $\\bm v$ on the sphere, the complex number\n\\begin{align}\n  X^{\\t{PS}}\\p{\\bm v} \\equiv \\bk{s_{\\bm v}|X|s_{\\bm v}},\n\\end{align}\nwhere $\\ket{s_{\\bm v}}\\equiv R\\p{\\bm v}\\ket{s}$ is the state of a spin qudit polarized along $\\bm v$.\nThis representation is faithful in the sense that $X$ is uniquely determined by the phase-space values $X^{\\t{PS}}\\p{\\bm v}$ at all points $\\bm v$ on the sphere.\nThe transformation rules for polarization operators in Eq.~\\eqref{eq:trans_rot}, together with the fact that $\\bk{s|T_{\\ell m}|s}=0$ unless $m=0$, suffice to show that\n\\begin{align}\n  T_{\\ell m}^{\\t{PS}}\\p{\\bm v} = c_\\ell Y_{\\ell m}\\p{\\bm v},\n\\end{align}\nwhere the scalar $c_\\ell$ simply enforces $\\obk{T_{\\ell m}|T_{\\ell m}}=1$ (see Appendix \\ref{sec:rotations}).\nThe polarization operators $T_{\\ell m}$ are thus a quantum analogue of the spherical harmonics $Y_{\\ell m}$, and play an important role in phase-space formalisms for spin qudits \\cite{li2013weylwignermoyal}.\n\nAs a special case, the phase-space representation $\\rho^{\\t{PS}}$ of a spin qudit state $\\rho$ is commonly known as its Husimi distribution.\nPerforming tomography on an unknown qudit state $\\rho$ is therefore equivalent to reconstructing the unknown distribution $\\rho^{\\t{PS}}$ on the sphere.\nIn principle, the representation $\\rho^{\\t{PS}}$ of a finite-dimensional qudit state $\\rho$ can be reconstructed from the values $\\rho^{\\t{PS}}\\p{\\bm v}=\\bk{s_{\\bm v}|\\rho|s_{\\bm v}}$ at a finite number of points $\\bm v$.\nIn practice, the value $\\bk{s_{\\bm v}|\\rho|s_{\\bm v}}$ is determined by measuring spin projection along $\\bm v$, which also provides measurement data on all spin projections $\\bk{\\mu_{\\bm v}|\\rho|\\mu_{\\bm v}}$ with $\\mu\\in\\set{s,s-1,\\cdots,-s}$ and $\\ket{\\mu_{\\bm v}}\\equiv R\\p{\\bm v}\\ket{\\mu}$; one would like to make use of this additional data as well.\nWe clarify the connection between the quantum problem of reconstructing $\\rho$ from spin projection measurements and the classical problem of reconstructing $\\rho^{\\t{PS}}$ from its values $\\rho^{\\t{PS}}\\p{\\bm v}$ in the following section.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Spin tomography as signal recovery on the sphere}\n\\label{sec:signal_recovery}\n\nOur goal is to reconstruct an arbitrary state $\\rho$ of a spin qudit from measurements of spin projection onto different quantization axes.\nWe are thus nominally restricted to measuring projectors $\\Pi_{\\bm v\\mu} \\equiv \\op{\\mu_{\\bm v}}$, where $\\ket{\\mu_{\\bm v}}\\equiv R\\p{\\bm v}\\ket{\\mu}$ is a state with spin projection $\\mu$ onto the measurement axis $\\bm v$.\nFor any fixed axis $\\bm v$, the sets $\\set{\\Pi_{\\bm v\\mu}}$ and $\\set{T_{\\bm v\\ell,0}}$ (i.e.~all $T_{\\bm v\\ell m}$ with $m=0$) are both complete bases for the space of operators that are diagonal in the basis $\\set{\\ket{\\mu_{\\bm v}}}$.\nMeasuring the projectors $\\set{\\Pi_{\\bm v\\mu}}$ is therefore equivalent to measuring the polarization operators $\\set{T_{\\bm v\\ell,0}}$, and provides data on the expectation values $\\bk{T_{\\bm v\\ell,0}}_\\rho$.\n\nIn order to reconstruct an arbitrary density operator $\\rho$ from the expectation values $\\bk{T_{\\bm v\\ell,0}}_\\rho$, we essentially need to find a set of coefficients $C_{\\ell mk}\\p{\\bm v}$ that would allow us to recover any matrix element $\\rho_{\\ell m}$ of $\\rho$ through\n\\begin{align}\n  \\rho_{\\ell m}^* = \\bk{T_{\\ell m}}_\\rho\n  = \\sum_{\\bm v,k} C_{\\ell mk}\\p{\\bm v} \\bk{T_{\\bm vk,0}}_\\rho.\n  \\label{eq:state_recon}\n\\end{align}\nExpanding the rotated polarization operators $T_{\\bm vk,0}$ into a sum of un-rotated polarization operators $T_{\\ell n}$ according to Eq.~\\eqref{eq:trans_rot}, we find that the recovery condition in Eq.~\\eqref{eq:state_recon} is satisfied when\n\\begin{align}\n  T_{\\ell m}\n  = \\sum_{\\bm v,k,n} C_{\\ell mk}\\p{\\bm v} D^k_{0,n}\\p{\\bm v}^* T_{kn}.\n\\end{align}\nOrthogonality of the polarization operators then implies the decomposition $C_{\\ell mk}\\p{\\bm v}=\\delta_{\\ell k}C_{\\ell m}\\p{\\bm v}$, and in turn\n\\begin{align}\n  \\sum_{\\bm v} C_{\\ell m}\\p{\\bm v} D^\\ell_{0,n}\\p{\\bm v}^*\n  = \\delta_{mn}\n  \\label{eq:tomo_recovery}\n\\end{align}\nfor all $\\ell$.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=0.4\\columnwidth]{sphere_points.pdf}\n  \\caption{Signal recovery on the sphere is the problem of reconstructing an unknown function $f$ (red distribution) from its values $f\\p{\\bm v}$ at specific points $\\bm v\\in V$ (blue dots) on the sphere.\n    For almost all choices of $V$, reconstruction of $f$ is possible if there are at least as many points in $V$ as there are degrees of freedom in $f$.}\n  \\label{fig:sphere_points}\n\\end{figure}\n\nIn fact, the problem of finding suitable axes $V$ and coefficients $C_{\\ell m}\\p{\\bm v}$ to satisfy Eq.~\\eqref{eq:tomo_recovery} can be mapped onto the well-studied problem of signal recovery on the sphere (see Figure \\ref{fig:sphere_points}) \\cite{mcewen2011novel, rauhut2011sparse, alem2012sparse, khalid2014optimaldimensionality}.\nThe signal recovery problem can be stated as follows: given a square-integrable function $f$ on the sphere, with the spherical harmonic expansion\n\\begin{align}\n  f\\p{\\bm v} = \\sum_{\\ell,m} f_{\\ell m} Y_{\\ell m}\\p{\\bm v},\n\\end{align}\nwhere $f_{\\ell m}$ are complex coefficients, find a set of points $V=\\set{\\bm v}$ and associated coefficients $\\tilde C_{\\ell m}\\p{\\bm v}$ with which we can reconstruct $f$, or equivalently its coefficients $f_{\\ell m}$, from knowledge of the function's value $f\\p{\\bm v}$ at all points $\\bm v\\in V$; that is\n\\begin{align}\n  f_{\\ell m} = \\sum_{\\bm v} \\tilde C_{\\ell m}\\p{\\bm v} f\\p{\\bm v}\n  = \\sum_{\\bm v,k,n} \\tilde C_{\\ell m}\\p{\\bm v} Y_{kn}\\p{\\bm v} f_{kn}.\n\\end{align}\nReconstruction of functions with arbitrary coefficients $f_{\\ell m}$ implies that\n\\begin{align}\n  \\sum_{\\bm v} \\tilde C_{\\ell m}\\p{\\bm v} Y_{kn}\\p{\\bm v}\n  = \\delta_{\\ell k} \\delta_{mn},\n  \\label{eq:full_recovery}\n\\end{align}\nwhich is a stronger version of the condition that we found for the spin qudit tomography problem in Eq.~\\eqref{eq:tomo_recovery}.\nWe will refer to Eq.~\\eqref{eq:full_recovery} as the {\\it full recovery problem}, and Eq.~\\eqref{eq:tomo_recovery} as the the {\\it reduced recovery problem}.\nDue to the fact that $D^\\ell_{0,m}\\p{\\bm v} = \\sqrt{\\frac{4\\pi}{2\\ell+1}}\\, Y_{\\ell m}\\p{\\bm v}$, any solution to the full recovery problem automatically solves the reduced recovery problem by setting $C_{\\ell m}\\p{\\bm v} = \\sqrt{\\frac{2\\ell+1}{4\\pi}}\\, \\tilde C_{\\ell m}\\p{\\bm v}^*$.\nIn principle, this mapping allows us to import a host of existing signal recovery algorithms \\cite{mcewen2011novel, rauhut2011sparse, alem2012sparse, khalid2014optimaldimensionality} for the task of spin qudit tomography.\nIn practice, spin qudits typically have only a modest dimension $d$, which allows for simpler and optimized tomography protocols that are practical despite worse scaling with $d$ (see Section \\ref{sec:protocol}).\nA natural avenue to develop better spin qudit tomography protocols would therefore be to build on the existing classical signal recovery algorithms, tailoring them to solve the reduced recovery problem in Eq.~\\eqref{eq:tomo_recovery} rather than the full recovery problem in Eq.~\\eqref{eq:full_recovery}.\nWe leave these developments to future work.\n\nIf the function $f$ is {\\it band-limited} at degree $L$, which is to say that $f_{\\ell m}=0$ for all $\\ell\\ge L$, then the full recovery problem in Eq.~\\eqref{eq:full_recovery} is provably solvable with a suitable choice of $\\abs{V}=L^2$ points on the sphere \\cite{freeden2008spherical, freeden2018spherical}.\nThe existence of these solutions to the full recovery problem in turn implies the existence of $d^2$ measurement axes that suffice to reconstruct arbitrary states of $d$-level spin qudit, whose possible states (or rather, phase-space representations) are band-limited at degree $d$.\nMoreover, for any fixed degree $\\ell$, finding solutions to the reduced recovery problem in Eq.~\\eqref{eq:tomo_recovery} is equivalent to the recovery of a degree-$\\ell$ function $f_\\ell = \\sum_m f_{\\ell m} Y_{\\ell m}$, which is provably possible with $\\abs{V}=2\\ell+1$ samples \\cite{freeden2008spherical}.\nIn the case of spin qudit tomography, the degree $\\ell$ takes a maximal value of $\\ell_{\\t{max}}\\equiv d-1$, so state recovery requires as many measurement axes as there are polarization operators with degree $\\ell_{\\t{max}}$, namely $2\\ell_{\\t{max}}+1=2d-1$.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{State reconstruction error}\n\\label{sec:error}\n\nFor the practically minded, proving the existence of solutions to a problem is less interesting than the exposition of a particular solution.\nOn a high level, a spin qudit tomography protocol consists of\n\\begin{enumerate*}\n\\item selecting a set of measurement axes,\n\\item \\label{tomo:measure} collecting measurement data on spin projection onto these axes, and then\n\\item processing the collected data to reconstruct the state of the spin qudit.\n\\end{enumerate*}\nWhereas step \\ref{tomo:measure} can involve a host of platform-dependent technical challenges, in the following sections we discuss the steps to take before and after collecting measurement data.\n\nTo this end, we begin by asking a question: what is a ``good'' choice of measurement axes?\nIntuitively, a good choice of axes should minimize the error with which one can reconstruct an unknown quantum state from associated measurement data.\nIf we can quantify this intuition, then we can optimize over different choices of measurement axes to find a set that (approximately) minimizes the error in reconstructed states.\n\nA set of measurement axes $V=\\set{\\bm v}$ nominally induces a set of projectors $\\set{\\Pi_{\\bm v\\mu}}$ that will be measured in an experiment.\nBy a simple change of basis, measuring these projectors is equivalent to measuring the polarization operators $\\set{T_{\\bm v\\ell,0}}$.\nFlattening each $d\\times d$ matrix $T_{\\bm v\\ell,0}$ into the $d^2$-component column vector $\\oket{T_{\\bm v\\ell,0}}$, we construct the {\\it measurement matrix}\n\\begin{align}\n  M_V \\equiv \\sum_{\\bm v,\\ell} \\ket{\\bm v\\ell} \\obra{T_{\\bm v\\ell,0}}.\n  \\label{eq:meas_mat}\n\\end{align}\nHere $\\bm v$ and $\\ell$ label a row of $M_V$, or equivalently label a standard (``one-hot'') basis vector $\\ket{\\bm v\\ell}$ of a $\\p{\\abs{V}\\times d}$-dimensional vector space, and $\\obra{T_{\\bm v\\ell,0}}$ is the conjugate transpose of $\\oket{T_{\\bm v\\ell,0}}$.\nA necessary and sufficient condition for $V$ to allow for full state tomography is that the measured polarization operators $T_{\\bm v\\ell,0}$, or equivalently the rows of $M_V$, span the entire ($d^2$-dimensional) space of operators on a $d$-level spin qudit.\nIn this case $M_V$ must be full rank, with $d^2$ nonzero singular values.\nIndexing these singular values $M^V_k$ and the corresponding (normalized) left singular vectors $\\bm x^V_k\\equiv \\sum_j x^V_{kj} \\ket{j}$ by an integer $k\\in\\set{1,2,\\cdots,d^2}$, we can construct the orthonormal qudit operators\n\\begin{align}\n  Q^V_k \\equiv \\sum_j \\p{q^V_{kj}}^* T_j,\n  &&\n  q^V_{kj} \\equiv \\f{x^V_{kj}}{M^V_k},\n\\end{align}\nwhere for shorthand we use a combined index $j=\\p{\\bm v,\\ell}$ to specify both a measurement axis $\\bm v$ and a degree $\\ell$, which identify the polarization operator $T_j\\equiv T_{\\bm v\\ell,0}$.\nThese operators allow us to expand any state $\\rho$ of a $d$-level spin qudit in the form\n\\begin{align}\n  \\rho = \\sum_{k=1}^{d^2} \\rho_k^V Q_k^V,\n  &&\n  \\rho_k^V \\equiv \\bk{{Q^V_k}^\\dag}_\\rho.\n\\end{align}\nGiven empirical estimates $\\tilde T_j$ of the expectation values $\\bk{T_j}_\\rho$, an empirical estimate $\\tilde\\rho_V$ of $\\rho$ is then\n\\begin{align}\n  \\tilde\\rho_V \\equiv \\sum_k \\tilde\\rho^V_k Q^V_k,\n  \\label{eq:reconstructed_state}\n\\end{align}\nwhere, using the fact that $T_j=T_j^\\dag$ (because they are diagonal polarization operators with degree $m=0$),\n\\begin{align}\n  \\tilde\\rho^V_k \\equiv \\sum_j q^V_{kj} \\tilde T_j\n  \\approx \\sum_j q^V_{kj} \\bk{T_j}_\\rho\n  = \\bk{{Q^V_k}^\\dag}_\\rho\n  = \\rho^V_k.\n\\end{align}\nThe measurement matrix $M_V$ allows us to make concrete statements about the statistical error between the empirical estimate $\\tilde\\rho_V$ and the true state $\\rho$.\nAssume, for example, that the estimates $\\tilde T_j$ are equal to $\\bk{T_j}_\\rho$ up to uncorrelated noise with variance no grater than $\\epsilon^2$:\n\\begin{align}\n  \\tilde T_j = \\bk{T_j}_\\rho + \\epsilon_j,\n  &&\n  \\bbk{\\epsilon_j \\epsilon_{j'}} \\le \\epsilon^2 \\delta_{jj'}.\n  \\label{eq:error_assumption}\n\\end{align}\nHere $\\set{\\epsilon_j}$ are independent random variables, and we use the double brackets $\\bbk{\\cdot}$ to denote statistical averaging over experimental trials that estimate $\\bk{T_j}_\\rho$.\nIn this case, the mean squared error with which $\\tilde\\rho^V_k$ approximates $\\rho^V_k$ is\n\\begin{align}\n  \\Bbk{\\abs{\\tilde\\rho^V_k-\\rho^V_k}^2}\n  &= \\Bbk{\\p{\\tilde\\rho^V_k-\\rho^V_k}^*\\p{\\tilde\\rho^V_k-\\rho^V_k}} \\\\\n  &= \\sum_{j,j'} \\p{q^V_{kj}}^* q^V_{kj'} \\,\n  \\bbk{\\epsilon_j \\epsilon_{j'}} \\\\\n  &\\le \\sum_j \\abs{q^V_{kj}}^2 \\epsilon^2\n  = \\p{\\f{\\epsilon}{M^V_k}}^2.\n\\end{align}\nUsing the fact that the operators $Q^V_k$ are orthonormal, we can therefore bound the mean squared (Euclidean) distance between $\\tilde\\rho_V$ and $\\rho$ as\n\\begin{align}\n  \\E_V\\p{\\rho}^2\n  \\equiv \\Bbk{\\norm{\\tilde\\rho_V-\\rho}^2}\n  \\le \\epsilon^2 \\S_V^2,\n  \\label{eq:bound_eps}\n\\end{align}\nwhere $\\norm{X}^2 \\equiv \\obk{X|X} = \\tr\\p{X^\\dag X}$ is the squared (Euclidean, Frobenius, or Hilbert-Schmidt) norm of $X$, and the {\\it classical error scale} $\\S_V$ is defined by\n\\begin{align}\n  \\S_V^2 \\equiv \\sum_k \\p{M^V_k}^{-2} = \\norm{M_V^{-1}}^2,\n\\end{align}\nwhere $M_V^{-1}$ is the left inverse of $M_V$, satisfying $M_V^{-1} M_V = 1$.\nWe refer to the error scale $\\S_V$ as ``classical'' because the bound in Eq.~\\eqref{eq:bound_eps} applies in the presence of classical sources of measurement error.\nNote that the classical error scale $\\S_V$ diverges if the measurement matrix $M_V$ is singular, which indicates that measuring spin projections along all axes in $V$ does not provide sufficient information to reconstruct arbitrary quantum states.\n\nComputing the classical error scale $\\S_V$ and estimates $\\tilde\\rho^V_k\\approx\\rho^V_k$ requires building the measurement matrix $M_V$ and computing its singular value decomposition.\nThe complexity of this task can be greatly reduced by the fact that the degree $\\ell$ of a polarization operator $T_{\\ell m}$ is preserved under rotations, which implies that the unitary\n\\begin{align}\n  U \\equiv \\sum_{\\ell=0}^{d-1} \\sum_{m=-\\ell}^\\ell\n  \\oket{T_{\\ell m}} \\bra{\\ell m},\n  \\label{eq:trans_basis}\n\\end{align}\nwith vectors $\\oket{T_{\\ell m}}$ in a column indexed by integers $\\p{\\ell,m}$, block-diagonalizes the measurement matrix into $d$ blocks indexed by the degree $\\ell$:\n\\begin{align}\n  M_V U = \\sum_{\\ell=0}^{d-1} \\op{\\ell} \\otimes M_{V\\ell},\n\\end{align}\nwhere the $\\abs{V}\\times\\p{2\\ell+1}$-sized blocks are\n\\begin{align}\n  M_{V\\ell} \\equiv \\sum_{\\bm v,m} \\ket{\\bm v}\n  \\obk{T_{\\bm v\\ell,0}|T_{\\ell m}} \\bra{m}\n  = \\sum_{\\bm v,m} D^\\ell_{0,m}\\p{\\bm v} \\op{\\bm v}{m}.\n  \\label{eq:block}\n\\end{align}\nHere $D^\\ell_{0,m}\\p{\\bm v}$ is a Wigner rotation matrix element, defined in Eq.~\\eqref{eq:wigner_D}.\nAs the singular values of $M_V$ are invariant under unitary transformations, it follows that\n\\begin{align}\n  \\S_V^2 = \\sum_\\ell \\S_{V\\ell}^2,\n  &&\n  \\S_{V\\ell}^2 \\equiv \\norm{M_{V\\ell}^{-1}}^2,\n\\end{align}\nwhere $M_{V\\ell}^{-1}$ is the left inverse of $M_{V\\ell}$.\nConstructing the block $M_{V\\ell}$ and computing its singular value decomposition takes at most $O(\\abs{V}d^2)$ time.\nIf we assume that $\\abs{V}\\sim d$, then computing the classical error scale $\\S_V$ takes $O(d^4)$ serial or $O(d^3)$ parallel runtime (see Figure \\ref{fig:times}).\n\n\\begin{figure}\n  \\centering\n  \\includegraphics{qudit_times.pdf}\n  \\caption{Serial runtime to compute $\\S_V$, $\\epsilon_V$, or $\\E_V\\p{\\rho}$ with $\\abs{V}=2d-1$ randomly chosen measurement axes and a randomly chosen qudit state $\\rho$.\n    Each point is an average over $10^3$ calculations or 5 minutes of runtime, whichever comes first.\n    These results do not count fixed runtimes to pre-compute quantities that can be recycled for every new choice of $V$ and $\\rho$.\n    Dashed lines show fits to a runtime $t=c d^\\alpha$ for the 20 largest values of $d$, finding $\\alpha\\approx 3.8\\pm0.1$.}\n  \\label{fig:times}\n\\end{figure}\n\nThe assumption that observables can be estimated up to uncorrelated noise with maximal variance $\\epsilon^2$, summarized by Eq.~\\eqref{eq:error_assumption}, is reasonable when measurement error is dominated by classical sources of experimental noise.\nHowever, this assumption breaks down when measurement error is limited by fundamental quantum shot noise (i.e.~finite sampling error).\nWe relax the assumption of Eq.~\\eqref{eq:error_assumption} in Appendix \\ref{sec:bound}, where we instead assume that $\\tilde\\rho_V$ is built from $n$ independent measurements of spin projection along every axis $\\bm v\\in V$, with shot noise the dominant source of error.\nIn this case, the constraints that $\\tr\\p\\rho=1$ and $\\bk{\\Pi_{\\bm v\\mu}}_\\rho\\ge0$ allow us to bound the mean squared distance between $\\tilde\\rho_V$ and $\\rho$ as\n\\begin{align}\n  \\E_V\\p{\\rho}^2 < \\f{\\epsilon_V^2}{n},\n  &&\n  \\epsilon_V^2 \\equiv \\sum_\\ell \\Gamma_\\ell^2 \\S_{V\\ell}^2,\n  \\label{eq:bound}\n\\end{align}\nwhere the {\\it quantum error scale} $\\epsilon_V$ is defined in terms of the spectral range of $T_{\\ell,0}$:\n\\begin{align}\n  \\Gamma_\\ell \\equiv \\f{\\max_\\mu t_{\\ell\\mu} - \\min_\\mu t_{\\ell\\mu}}{2},\n  &&\n  t_{\\ell\\mu} \\equiv \\bk{\\mu|T_{\\ell,0}|\\mu}.\n\\end{align}\nIf $d$ is even or $\\ell$ is odd, then $\\Gamma_\\ell=\\max_\\mu t_{\\ell\\mu}$.\nFor comparison with the ``classical'' error bound in Eq.~\\eqref{eq:bound_eps}, we note that $\\epsilon_V^2<\\S_V^2/2$, so the previous bound still holds with the replacement $\\epsilon^2\\to1/2n$.\nThe factors $\\Gamma_\\ell^2$ are quick to compute and can be recycled for every new choice of axes $V$, so the complexity of computing $\\epsilon_V$ is the same as that of $\\S_V$ (see Figure \\ref{fig:times}).\n\nThough straightforward to compute, the bound in Eq.~\\eqref{eq:bound} is not tight, as it is acquired by bounding the statistical error $\\epsilon_{\\bm v\\ell}$ in the empirical estimate $\\tilde T_{\\bm v\\ell,0}$ of $\\bk{T_{\\bm v\\ell,0}}_\\rho$ by $\\bbk{\\epsilon_{\\bm v\\ell}^2}\\le\\Gamma_\\ell^2$.\nThe individual bounds on $\\bbk{\\epsilon_{\\bm v\\ell}^2}$ for each axis $\\bm v$ and degree $\\ell$ are tight, but these bounds cannot all be achieved simultaneously.\nThere is therefore still room for improvement on the bound in Eq.~\\eqref{eq:bound} by maximizing $\\E_V$ over the set of all physical qudit states $\\rho$.\nWe discuss this maximization problem in Appendix \\ref{sec:exact}, but leave its full solution to future work.\nWe also note that the reconstruction error bound in Eq.~\\eqref{eq:bound} obeys the ``standard quantum limit'' of $\\sim1/n$ scaling in the number of measurements.\nIn principle, this scaling can be improved to $\\sim1/n^2$ by preparing and measuring entangled copies of many qudits \\cite{giovannetti2006quantum}.\n\nThe error scales $\\S_V$ and $\\epsilon_V$ provide pessimistic upper bounds on statistical error, which can be calculated without prior knowledge of the true qudit state $\\rho$.\nThe actual error in the reconstruction $\\tilde\\rho_V$ of a particular state $\\rho$ may be considerably smaller, and may depend on $\\rho$ itself.\nWritten out in full, the mean squared distance between $\\tilde\\rho_V$ and $\\rho$ is (see Appendix \\ref{sec:bound})\n\\begin{align}\n  \\E_V\\p{\\rho}^2 = \\sum_{\\bm v,\\bm w,\\ell}\n  \\bk{\\bm v|\\p{M_{V\\ell}^{-1}}^\\dag M_{V\\ell}^{-1}|\\bm w}\n  \\bbk{\\epsilon_{\\bm v\\ell}\\epsilon_{\\bm w\\ell}}.\n  \\label{eq:error_cls}\n\\end{align}\nThe covariances $\\bbk{\\epsilon_{\\bm v\\ell}\\epsilon_{\\bm w\\ell}}$ are generally determined by the sources of measurement error in any given experiment, but will typically satisfy $\\bbk{\\epsilon_{\\bm v\\ell}\\epsilon_{\\bm w\\ell}} = \\delta_{\\bm v\\bm w}\\bbk{\\epsilon_{\\bm v\\ell}^2}$ because measurements along $\\bm v$ are independent of measurements along $\\bm w$.\nIf measurement error is limited by shot noise, then (see Appendix \\ref{sec:exact})\n\\begin{align}\n  \\E_V\\p{\\rho}^2 \\stackrel{\\t{SNL}}{=} \\f1n \\sum_\\ell\n  \\sp{\\bk{\\chi_{V\\ell}|\\rho_\\ell}\n    - \\bk{\\rho_\\ell|\\N_{V\\ell}|\\rho_\\ell}},\n  \\label{eq:error_qnt}\n\\end{align}\nwhere $\\stackrel{\\t{SNL}}{=}$ indicates equality in the ``shot-noise-limited'' regime; $\\ket{\\rho_\\ell} \\equiv \\sum_m \\rho_{\\ell m}\\ket{m}$ is a vector of the polarization operator components $\\rho_{\\ell m}$ of $\\rho$, defined in Eq.~\\eqref{eq:trans_state}; and the matrix $\\N_{V\\ell}$ and vector $\\ket{\\chi_{V\\ell}}$ are defined below.\nWhile the true shot-noise-limited error in $\\tilde\\rho_V$ cannot be known exactly without knowing $\\rho$, this error can be estimated a posteriori by $\\E_V\\p{\\rho}\\approx\\E_V\\p{\\tilde\\rho_V}$.\nAfter constructing an estimate $\\tilde\\rho_V$ of $\\rho$, the complexity of computing the error $\\E_V\\p{\\tilde\\rho_V}$ from Eq.~\\eqref{eq:error_qnt} is the same as that of computing $\\S_V$ or $\\epsilon_V$ (see Figure \\ref{fig:times}).\n\nWe now define $\\N_{V\\ell}$ and $\\ket{\\chi_{V\\ell}}$ for the sake of completion, but note that these definitions can be skipped without consequence for the remaining discussions in this paper.\nThe matrix $\\N_{V\\ell}$ is\n\\begin{align}\n  \\N_{V\\ell} \\equiv M_{V\\ell}^\\dag\n  \\diag\\sp{\\p{M_{V\\ell}^{-1}}^\\dag M_{V\\ell}^{-1}} M_{V\\ell},\n\\end{align}\nwhere $\\diag\\sp{X}$ sets the off-diagonal parts of $X$ to zero.\nThe vector $\\ket{\\chi_{V\\ell}}\\equiv\\sum_m \\chi^V_{\\ell m} \\ket{m}$ is defined by\n\\begin{align}\n  \\chi^V_{LM} &\\equiv\n  \\sum_\\ell \\obk{\\N_{V\\ell}|\\D_M|\\tilde g_{L\\ell}}, \\\\\n  \\tilde g_{L\\ell} &\\equiv \\sum_{m,m'}\n  \\obk{T_{L,m+m'}|T_{\\ell m}^\\dag T_{\\ell m'}} \\op{m}{m'}, \\\\\n  \\D_M &\\equiv \\sum_{m,m'} \\delta_{M,m'-m} \\op{mm'}.\n\\end{align}\nHere $\\tilde g_{L\\ell}$ is essentially a matrix of structure constants for the polarization operator algebra (see Appendix \\ref{sec:trans_prod}), and $\\D_M$ simply picks off the $M$-th diagonal of the matrix it acts on.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Tomography protocol}\n\\label{sec:protocol}\n\nThe ability to certify a statistical error bound on the empirical estimate $\\tilde\\rho_V$ of an unknown quantum state $\\rho$ motivates the following protocol for spin qudit tomography:\n\\begin{enumerate}\n\\item Select a random set of measurement axes $V$ by uniformly sampling points on the sphere\\footnote{To sample a point $\\p{\\alpha,\\beta}$ from the uniform distribution on the sphere (with azimuthal angle $\\alpha$ and polar angle $\\beta$), you can sample a point $\\p{a,b}\\in[0,1]\\times[0,1]$ from the uniform distribution on the unit square, and then set $\\alpha=2\\pi a$ and $\\beta=\\arccos\\p{1-2b}$.}, and use any standard minimization algorithm to optimize the $2\\abs{V}$ parameters in $V$ (two angles for each point $\\bm v\\in V$) by minimizing the quantum error scale $\\epsilon_V$ in Eq.~\\eqref{eq:bound}.\nIf $\\abs{V}$ is too large for such optimization, you can simply generate many sets of random measurement axes, and then choose the set with the smallest quantum error scale $\\epsilon_V$.\nNote that computing the error scale $\\epsilon_V$ requires, for each $\\ell\\in\\set{0,1,\\cdots,d-1}$, constructing the measurement matrix $M_{V\\ell}$ in Eq.~\\eqref{eq:block} and computing its singular value decomposition.\nSave all measurement matrix data associated with the final measurement axes $V$ for later use.\n\\item For each axis $\\bm v\\in V$, make $n$ measurements of spin projection, and set $\\tilde\\Pi_{\\bm v\\mu}\\approx\\bk{\\Pi_{\\bm v\\mu}}_\\rho$ to the fraction of times in which the measurement outcome was $\\mu$.\n\\item Use the the estimates $\\tilde\\Pi_{\\bm v\\mu}$ of $\\bk{\\Pi_{\\bm v\\mu}}_\\rho$ to compute estimates of $\\bk{T_{\\bm v\\ell,0}}_\\rho$,\n\\begin{align}\n  \\tilde T_{\\bm v\\ell,0}\n  \\equiv \\sum_\\mu \\bk{\\mu|T_{\\ell,0}|\\mu} \\tilde\\Pi_{\\bm v\\mu},\n\\end{align}\nwhere the matrix elements of $T_{\\ell,0}$ are provided in Eq.~\\eqref{eq:trans_op}.\n\\item Denoting the nonzero singular values of $M_{V\\ell}$ by $M^V_{\\ell k}$ and the corresponding left singular vectors by $\\bm x^V_{\\ell k} = \\sum_{\\bm v} x^V_{\\ell k \\bm v} \\ket{\\bm v}$, compute the  operators and coefficients\n\\begin{align}\n  Q_{\\ell k} &\\equiv \\f1{M^V_{\\ell k}} \\sum_{\\bm v}\n  \\p{x^V_{\\ell k\\bm v}}^* T_{\\bm v\\ell,0}, \\\\\n  \\tilde\\rho^V_{\\ell k} &\\equiv \\f1{M^V_{\\ell k}} \\sum_{\\bm v}\n  x^V_{\\ell k\\bm v} \\, \\tilde T_{\\bm v\\ell,0},\n\\end{align}\nand combine them into the estimate\n\\begin{align}\n  \\tilde\\rho_V = \\sum_{\\ell,k} \\tilde\\rho^V_{\\ell k} Q_{\\ell k}\n  \\approx \\rho.\n\\end{align}\n\\end{enumerate}\nThe expected reconstruction error in $\\tilde\\rho_V$, or its root-mean-square distance from $\\rho$, is provided by Eq.~\\eqref{eq:error_cls}.\nIf measurement error is shot-noise-limited, then the error in $\\tilde\\rho_V$ is approximately $\\E_V\\p{\\rho}\\approx\\E_V\\p{\\tilde\\rho_V}$ and can be computed from Eq.~\\eqref{eq:error_qnt}.\nIf $\\tilde\\rho_V$ has negative eigenvalues, its distance from $\\rho$ can be reduced with maximum-likelihood corrections \\cite{smolin2012efficient}, which will additionally guarantee that $\\tilde\\rho_V$ satisfies all requirements for being a physical state.\n\nThe tomography protocol outlined above leaves open the question of {\\it how many} measurement axes to use.\nThough $2d-1$ measurement axes may be sufficient to perform full state tomography, this is not necessarily the best choice of $\\abs{V}$.\nIncreasing the number of measurement axes generally decreases the quantum error scale $\\epsilon_V$, but comes at the cost of having to estimate more observables.\nAt a fixed total number of measurements, increasing $\\abs{V}$ reduces the number of measurements $n$ devoted to each axis $\\bm v\\in V$.\nThis trade-off begs the question: how should one choose the number of measurement axes, $\\abs{V}$?\n\n\\begin{figure}\n  \\centering\n  \\includegraphics{qudit_axes.pdf}\n  \\caption{Empirical measurement-adjusted error scales $\\tilde\\beta(p)$ with $p$ excess measurement axes, determined by minimizing over $10^3$ choices of measurement axes $V$ or 5 minutes of runtime (for each $p$), whichever comes first.\n    Color indicates the qudit dimension $d$.\n    The rapid initial drop in $\\tilde\\beta(p)$ implies that using more measurement axes can substantially lower the upper bound on reconstruction error provided in Eq.~\\eqref{eq:bound}, and that these benefits plateau after $p\\approx d$.\n    Horizontal reference lines mark the smallest measurement-adjusted error scales $\\min_\\theta\\beta_\\theta/\\tilde\\beta(0)$ achievable with the method in Ref.~\\cite{newton1968measurability}, which is parameterized by an arbitrarily chosen angle $\\theta$.}\n  \\label{fig:axes}\n\\end{figure}\n\nThe reconstruction error bound in Eq.~\\eqref{eq:bound} nominally provides a straightforward answer: at a fixed total number of measurements, $N=n\\abs{V}$, the number of measurement axes should be chosen to minimize the (squared) reconstruction error $\\E_V\\p{\\rho}^2<\\epsilon_V^2/n\\propto\\epsilon_V^2\\abs{V}$.\nWe therefore consider the measurement-adjusted error scale $\\beta(p)$ defined by\n\\begin{align}\n  \\beta(p)^2\n  \\equiv \\min_V\\Set{\\epsilon_V^2\\abs{V}:\\abs{V}=2d-1+p},\n\\end{align}\nwhere $p$ is the number of ``extra'' measurement axes exceeding $2d-1$.\nThough we cannot minimize over all suitable choices of measurement axes $V$ to compute $\\beta(p)$, we can compute an empirical upper bound $\\tilde\\beta(p)\\ge\\beta(p)$ by minimizing over a large number of randomly chosen $V$.\nFigure \\ref{fig:axes} shows the results of such empirical minimization, where we find that $\\tilde\\beta(p)$ drops substantially with $p$ before plateauing at $p\\approx d$, after which there are only minor benefits to using more measurement axes.\nIn the interest of reducing experimental complexity as well as the runtime of our randomized tomography protocol, which grow linearly in $\\abs{V}$, we therefore conclude that this protocol should be performed with $\\abs{V}\\approx3d$ measurement axes.\nWe provide the best measurement axes that we found for a randomized tomography protocol with $d\\le30$ and $\\abs{V}=3d$ in Ref.~\\cite{tomo_codes}.\n\nFor reference, Figure \\ref{fig:axes} also shows the smallest measurement-adjusted error scales $\\beta_\\theta$ achievable with the method of Ref.~\\cite{newton1968measurability}, which is comparable to those achieved with our randomized protocol at $\\abs{V}\\approx3d$.\nThe method of Ref.~\\cite{newton1968measurability} requires choosing an angle $\\theta$, namely the polar angle of all measurement axes, and provides no prescription for making this choice.\nWe therefore find the optimal choice of $\\theta$ by minimizing the error scale $\\beta_\\theta$ over all $\\theta$ (see Appendix \\ref{sec:angle_search}), and show $\\min\\beta_\\theta/\\tilde\\beta(0)$ in Figure \\ref{fig:axes}.\nEmpirically, we find that the optimal angle for the method of Ref.~\\cite{newton1968measurability} is $\\theta_{\\t{opt}}\\approx\\frac{\\pi}{2}(1-\\frac1{1.34d})$ (see Appendix \\ref{sec:angle_search}), which approaches $\\pi/2$ as $d\\to\\infty$.\nHowever, the error scale $\\beta_{\\pi/2}=\\infty$, reflecting the fact that full state tomography is impossible with measurement axes lying in a single plane.\nThe method of Ref.~\\cite{newton1968measurability} therefore requires extremely careful fine-tuning of measurement axis orientations for large spin dimensions.\nFor this reason, we expect our randomized tomography protocol be be more robust to errors in axis orientation.\nWe leave a detailed analysis of robustness to errors in axis orientation and the effect of these errors on state reconstruction to future work.\n\nAs a final point, we note that any information about an unknown qudit state $\\rho$, obtained from prior knowledge or preliminary measurement data, can be used to construct tailored or adaptive measurement protocols \\cite{huszar2012adaptive, ferrie2014selfguided, granade2016practical, pereira2018adaptive} that are more efficient in terms of the number of measurements required to estimate $\\rho$ to a fixed precision.\nWe leave the development of tailored and adaptive measurement protocols to future work as well.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{acknowledgments}\nWe thank Anthony M.~Polloreno and Jeremy T.~Young for helpful feedback.\nThis work is supported  by the DARPA DRINQs grant, the ARO single investigator award W911NF-19-1-0210, AFOSR grant FA9550-19-1-0275, NSF grant PHY-1820885, NSF grant PHY-1734006 (JILA-PFC), and by NIST.\n\\end{acknowledgments}\n\n\\bibliography{qudit_tomo.bib}\n\\onecolumngrid\n\\appendix\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Rotating polarization operators}\n\\label{sec:rotations}\n\nDenoting the state of a spin-$s$ particle spin spin projection $\\mu$ onto a quantization axis by $\\ket{s\\mu}$, we define\n\\begin{align}\n  S_\\z \\equiv \\sum_{\\mu=-s}^s \\mu \\op{s\\mu},\n  &&\n  S_\\pm \\equiv \\sum_{\\mu=-s}^s\n  \\sqrt{s\\p{s+1}-\\mu\\p{\\mu\\pm1}} \\op{s,\\mu\\pm1}{s\\mu},\n  \\label{eq:spin_ops}\n\\end{align}\nas well as\n\\begin{align}\n  S_\\x \\equiv \\f12\\p{S_+ + S_-},\n  &&\n  S_\\y \\equiv -\\f\\i2\\p{S_+-S_-},\n  &&\n  \\bm S \\equiv \\p{S_\\x,S_\\y,S_\\z}.\n\\end{align}\nThe spin vector $\\bm S$ generates rotations of a spin-$s$ system in 3D space.\nSpecifically, the operator $e^{-\\i\\theta\\bm S\\cdot\\uv n}$ rotates a spin-$s$ system by an angle $\\theta$ about the unit vector $\\uv n$.\n\nObserving that $S_\\z=T_{1,0}$ and $S_\\pm\\propto T_{1,\\pm1}$, we can use the operator product expansion of the polarization operators (see Appendix \\ref{sec:trans_prod}), the properties of Clebsch-Gordan coefficients, the properties of Wigner $6$-$j$ symbols, and a computer algebra system to simplify the commutators\n\\begin{align}\n  \\sp{S_\\z,T_{\\ell m}} = m\\, T_{\\ell m},\n  &&\n  \\sp{S_\\pm,T_{\\ell m}} = \\sqrt{\\ell\\p{\\ell+1}-m\\p{m\\pm 1}}\\, T_{\\ell,m\\pm1},\n  \\label{eq:spin_trans}\n\\end{align}\nwhich implies that $T_{\\ell m}$ is a spherical tensor operator, whose degree degree $\\ell$ is preserved under rotations generated by $\\bm S$.\nMoreover, by comparing Eqs.~\\eqref{eq:spin_ops} and \\eqref{eq:spin_trans} we see that the polarization operators $T_{\\ell m}$ transform identically to spin-$\\ell$ particles under the (adjoint) action of the spin operators $S_\\z$ and $S_\\pm$.\nFor any triplet of angles $\\bm\\omega=\\p{\\alpha,\\beta,\\gamma}$, we can therefore define the rotation operator\n\\begin{align}\n  R\\p{\\bm\\omega} \\equiv\n  e^{-\\i\\alpha S_\\z} e^{-\\i\\beta S_\\y} e^{-\\i\\gamma S_\\z},\n\\end{align}\nand expand rotated polarization operators as\n\\begin{align}\n  T_{\\bm\\omega\\ell m} \\equiv\n  R\\p{\\bm\\omega} T_{\\ell m} R\\p{\\bm\\omega}^\\dag\n  = \\sum_{n=-\\ell}^\\ell D_{mn}^\\ell\\p{\\bar{\\bm\\omega}}^* T_{\\ell n},\n  \\label{eq:trans_rot_apndx}\n\\end{align}\nwhere $\\bar{\\bm\\omega}=\\p{\\gamma,\\beta,\\alpha}$ is the reversal of $\\bm\\omega$, and\n\\begin{align}\n  D_{mn}^\\ell\\p{\\bar{\\bm\\omega}}\n  \\equiv \\bk{\\ell m|R\\p{\\bar{\\bm\\omega}}|\\ell n}\n  = \\obk{T_{\\ell n} | R\\p{\\bm\\omega}\n    \\otimes R\\p{\\bm\\omega}^* |T_{\\ell m}}^*\n  = \\obk{T_{\\ell m} | R\\p{-\\bar{\\bm\\omega}}\n    \\otimes R\\p{-\\bar{\\bm\\omega}}^* |T_{\\ell n}}\n\\end{align}\nare matrix elements of the rotation operator $R\\p{\\bm\\omega}$ for spin-$\\ell$ particles.\n\nFor any angle doublet $\\bm v=\\p{\\alpha,\\beta}$, we define $R\\p{\\bm v}\\equiv R\\p{\\alpha,\\beta,0}$ and $D^\\ell_{mn}\\p{\\bm v}=D^\\ell_{mn}\\p{0,\\beta,\\alpha}$ for shorthand.\nThe transformation rules in Eq.~\\eqref{eq:trans_rot_apndx} imply that we can expand the phase-space representation of $T_{\\ell m}$ as\n\\begin{align}\n  T_{\\ell m}^{\\t{PS}}\\p{\\bm v}\n  \\equiv \\bk{s_{\\bm v} | T_{\\ell m} | s_{\\bm v}}\n  = \\bk{s | R\\p{\\bm v}^\\dag T_{\\ell m} R\\p{\\bm v} | s}\n  = D^\\ell_{0,m}\\p{\\bm v} \\bk{s | T_{\\ell,0} | s},\n\\end{align}\nwhere\n\\begin{align}\n  \\bk{s | T_{\\ell,0} | s}\n  = \\sqrt{\\f{2\\ell+1}{2s+1}} \\, \\bk{ss;\\ell,0|ss}\n  = \\sqrt{\\f{2\\ell+1}{2s+\\ell+1}\n    \\p{\\f{\\p{2s}!}{\\p{2s+\\ell}!}}\n    \\p{\\f{\\p{2s}!}{\\p{2s-\\ell}!}}},\n\\end{align}\nand the properties of the rotation matrix elements $D^\\ell_{mn}$ imply that\n\\begin{align}\n  D^\\ell_{0,m}\\p{\\bm v} = \\sqrt{\\f{4\\pi}{2\\ell+1}} \\, Y_{\\ell m}\\p{\\bm v},\n\\end{align}\nso\n\\begin{align}\n  T_{\\ell m}^{\\t{PS}}\\p{\\bm v}\n  = \\sqrt{\\f{4\\pi}{2s+\\ell+1}\n    \\p{\\f{\\p{2s}!}{\\p{2s+\\ell}!}} \\p{\\f{\\p{2s}!}{\\p{2s-\\ell}!}}} \\,\n  Y_{\\ell m}\\p{\\bm v}.\n\\end{align}\nIn this way, the polarization operators are a quantum analogue of the spherical harmonics.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{An improved reconstruction error bound}\n\\label{sec:bound}\n\nIn Section \\ref{sec:error} of the main text, we provided a reconstruction error bound using the assumption of Eq.~\\eqref{eq:error_assumption}, namely that expectation values derived from spin projection measurements can be estimated up to uncorrelated errors with maximal variance $\\epsilon^2$.\nThis assumption is reasonable if measurement error is dominated by experimental sources of noise, and it yields a simple derivation of the reconstruction bound in Eq.~\\eqref{eq:bound_eps}.\nNonetheless, there are two problems with the assumption of Eq.~\\eqref{eq:error_assumption}:\n\\begin{enumerate*}\n\\item there is no a priori guarantee for the value of $\\epsilon$, which must be inferred from experimental outcomes, and\n\\item the assumption that all measurement errors are uncorrelated is unjustified (and generally false).\n\\end{enumerate*}\nHere, we relax the assumption of Eq.~\\eqref{eq:error_assumption} and derive an explicit error bound in terms of the qudit dimension $d$ and the number of spin projection measurements made along every measurement axis.\n\nTo this end, we fix a particular set of measurement axes $V$, and consider performing $n$ measurements of spin projection along every axis $\\bm v\\in V$, for a total of $N=\\abs{V}\\times n$ measurements.\nSuch a procedure is equivalent to making $N$ local measurements of the $N$-fold product state $\\rho^{\\otimes N}$.\nFor convenience, we index the tensor factors of $\\rho^{\\otimes N}$ by the integers $\\p{i,j}$, with $i\\in\\set{1,2,\\cdots,\\abs{V}}$ specifying a measurement axis $\\bm v_i\\in V$, and $j\\in\\set{1,2,\\cdots,n}$ specifying the copy of $\\rho$ prepared for the $j$-th measurement spin projection along a particular axis.\nWe then define the projectors $\\Pi_{i\\mu}\\equiv\\op{\\mu_{\\bm v_i}}$ onto single-qudit states $\\ket{\\mu_{\\bm v_i}}$ with definite spin projection $\\mu$ along axis $\\bm v_i\\in V$, and define $\\Pi_{i\\mu}^j$ to be an $N$-qudit operator with $\\Pi_{i\\mu}$ on the $\\p{i,j}$-th tensor factor and the identity elsewhere.\nWe denote the experimental outcome of measuring $\\Pi_{i\\mu}$ in the $\\p{i,j}$-th copy of $\\rho$ by $\\tilde\\Pi_{i\\mu}^j\\in\\set{0,1}$.\nIn other words, $\\tilde\\Pi_{i\\mu}^j$ is the ``single-shot estimate'' of $\\Pi_{i\\mu}$, with $\\tilde\\Pi_{i\\mu}^j=1$ if outcome $\\mu$ was observed on the $\\p{i,j}$-th experimental trial, and $\\tilde\\Pi_{i\\mu}^j=0$ otherwise.\nAn empirical estimate of the expectation value $\\bk{\\Pi_{i\\mu}}_\\rho$ is provided by the fraction of times that outcome $\\mu$ was observed when measuring spin projection along axis $\\bm v_i$, that is\n\\begin{align}\n  \\tilde\\Pi_{i\\mu} \\equiv \\f1n \\sum_{j=1}^n \\tilde\\Pi_{i\\mu}^j\n  \\approx \\f1n \\sum_{j=1}^n \\tr\\p{\\rho^{\\otimes N} \\Pi_{i\\mu}^j}\n  = \\tr\\p{\\rho \\Pi_{i\\mu}}.\n  \\label{eq:proj_estimate}\n\\end{align}\nFor reasons that will be clarified shortly, it will be useful to think of $\\tilde\\Pi_{i\\mu}$ as an empirical estimate of $\\bk{\\bar\\Pi_{i\\mu}}_{\\rho^{\\otimes N}}$, where\n\\begin{align}\n  \\bar\\Pi_{i\\mu} \\equiv \\f1n \\sum_{j=1}^n \\Pi_{i\\mu}^j\n  \\label{eq:mean_proj}\n\\end{align}\nis the average of $\\Pi_{i\\mu}$ applied to all copies of $\\rho$ for which spin projection is measured along the axis $\\bm v_i$.\nEq.~\\eqref{eq:proj_estimate} implies that\n\\begin{align}\n  \\tilde\\Pi_{i\\mu}\n  \\approx \\bk{\\bar\\Pi_{i\\mu}}_{\\rho^{\\otimes N}}\n  = \\bk{\\Pi_{i\\mu}}_\\rho.\n\\end{align}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Errors in the spin-projection basis}\n\nFinite sampling error (i.e.~shot noise) generally induces statistical error $\\epsilon_\\O$ into the empirical estimate $\\tilde\\O$ of an observable $\\O$:\n\\begin{align}\n  \\epsilon_\\O \\equiv \\tilde\\O - \\bk{\\O},\n\\end{align}\nwhere the single brackets $\\bk{\\cdot}$ denote an expectation value with respect to the measured quantum state.\nOn average, this statistical error will be zero, which is to say that\n\\begin{align}\n  \\bbk{\\epsilon_\\O} = \\bbk{\\tilde\\O - \\bk{\\O}}\n  = \\bk{\\O - \\bk{\\O}}\n  = 0,\n\\end{align}\nwhere the double brackets $\\bbk{\\cdot}$ to denote statistical averaging over experimental trials that estimate $\\bk{\\O}$.\nHowever, the covariance between statistical errors $\\epsilon_\\O$ and $\\epsilon_\\Q$ on the empirical estimates $\\tilde\\O$ and $\\tilde\\Q$ of observables $\\O$ and $\\Q$ is\n\\begin{align}\n  \\bbk{\\epsilon_\\O \\epsilon_\\Q}\n  = \\Bbk{\\p{\\tilde\\O - \\bk{\\O}} \\p{\\tilde\\Q - \\bk{\\Q}}}\n  = \\bk{\\p{\\O - \\bk{\\O}} \\p{\\Q - \\bk{\\Q}}}\n  = \\bk{\\O\\Q} - \\bk{\\O} \\bk{\\Q}.\n\\end{align}\nIn the context of spin qudit tomography, we can therefore define the statistical error\n\\begin{align}\n  \\epsilon_{i\\mu}\n  \\equiv \\tilde\\Pi_{i\\mu} - \\bk{\\Pi_{i\\mu}}_{\\rho}\n  = \\tilde\\Pi_{i\\mu} - \\bk{\\bar\\Pi_{i\\mu}}_{\\rho^{\\otimes N}}\n\\end{align}\nin the empirical estimate of $\\bk{\\Pi_{i\\mu}}_{\\rho}$, and use Eq.~\\eqref{eq:mean_proj} to expand\n\\begin{align}\n  \\bbk{\\epsilon_{i\\mu} \\epsilon_{i'\\mu'}}\n  = \\bk{\\bar\\Pi_{i\\mu} \\bar\\Pi_{i'\\mu'}}_{\\rho^{\\otimes N}}\n  - \\bk{\\bar\\Pi_{i\\mu}}_{\\rho^{\\otimes N}}\n  \\bk{\\bar\\Pi_{i'\\mu'}}_{\\rho^{\\otimes N}}\n  = \\f1{n^2} \\sum_{j,j'=1}^n\n  \\sp{\\bk{\\Pi_{i\\mu}^j \\Pi_{i'\\mu'}^{j'}}_{\\rho^{\\otimes N}}\n    - \\bk{\\Pi_{i\\mu}^j}_{\\rho^{\\otimes N}}\n    \\bk{\\Pi_{i'\\mu'}^{j'}}_{\\rho^{\\otimes N}}}.\n  \\label{eq:proj_cov_start}\n\\end{align}\nIf $\\p{i,j}\\ne\\p{i',j'}$, then $\\Pi_{i\\mu}^j$ and $\\Pi_{i'\\mu'}^{j'}$ address different tensor factors of the product state $\\rho^{\\otimes N}$, so the expectation value of their product factorizes due to the fact that $\\tr\\sp{\\p{A\\otimes B}\\p{A'\\otimes B'}} = \\tr\\p{AA'}\\times\\tr\\p{BB'}$.\nThis factorization can also be seen as a consequence of the fact that if $\\p{i,j}\\ne\\p{i',j'}$, then $\\Pi_{i\\mu}^j$ and $\\Pi_{i'\\mu'}^{j'}$ are ``spatially separated'' on $\\rho^{\\otimes N}$, which means that their expectation values cannot have quantum correlations.\nThe terms in Eq.~\\eqref{eq:proj_cov_start} with $\\p{i,j}\\ne\\p{i',j'}$ therefore vanish, so\n\\begin{align}\n  \\bbk{\\epsilon_{i\\mu} \\epsilon_{i'\\mu'}}\n  &= \\delta_{ii'} \\times \\f1{n^2} \\sum_{j=1}^n \\sp{\\bk{\\Pi_{i\\mu}^j \\Pi_{i\\mu'}^j}_{\\rho^{\\otimes N}}\n    - \\bk{\\Pi_{i\\mu}^j}_{\\rho^{\\otimes N}}\n    \\bk{\\Pi_{i\\mu'}^j}_{\\rho^{\\otimes N}}} \\\\\n  &= \\delta_{ii'} \\times \\f1n \\sp{\\bk{\\Pi_{i\\mu} \\Pi_{i\\mu'}}_\\rho\n    - \\bk{\\Pi_{i\\mu}}_\\rho \\bk{\\Pi_{i\\mu'}}_\\rho} \\\\\n  &= \\delta_{ii'} \\times \\f1n \\cov_\\rho\\p{\\Pi_{i\\mu}, \\Pi_{i\\mu'}},\n\\end{align}\nwhere $\\cov_\\rho\\p{X,Y} \\equiv \\bk{XY}_\\rho - \\bk{X}_\\rho \\bk{Y}_\\rho$.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Errors in the polarization operator basis}\n\nRather than the statistical errors $\\epsilon_{i\\mu} \\equiv \\tilde\\Pi_{i\\mu} - \\bk{\\Pi_{i\\mu}}_\\rho$ in the estimates $\\tilde\\Pi_{i\\mu}$ of the projectors $\\Pi_{i\\mu}$, we now consider the statistical errors $\\epsilon_{i\\ell} \\equiv \\tilde T_{i\\ell} - \\bk{T_{i\\ell}}_\\rho$ in the estimates $\\tilde T_{i\\ell}$ of the polarization operators $T_{i\\ell} \\equiv T_{\\bm v_i\\ell,0}$.\nWe can expand the polarization operators $T_{i\\ell}$ as a sum over projectors $\\Pi_{i\\mu}$ as\n\\begin{align}\n  T_{i\\ell} = \\sum_\\mu t_{\\ell\\mu} \\Pi_{i\\mu},\n  &&\n  t_{\\ell\\mu} \\equiv \\bk{\\mu|T_{\\ell,0}|\\mu}\n  = \\sqrt{\\f{2\\ell+1}{d}} \\bk{s\\mu;\\ell,0|s\\mu},\n\\end{align}\nand likewise $\\tilde T_{i\\ell} \\equiv \\sum_\\mu t_{\\ell\\mu} \\tilde\\Pi_{i\\mu}$.\nThe covariance between errors in the polarization operator basis is then\n\\begin{align}\n  \\bbk{\\epsilon_{i\\ell} \\epsilon_{i'\\ell'}}\n  = \\sum_{\\mu,\\mu'} t_{\\ell\\mu} t_{\\ell'\\mu'}\n  \\bbk{\\epsilon_{i\\mu} \\epsilon_{i'\\mu'}}\n  = \\delta_{ii'} \\times \\f1n\n  \\sum_{\\mu,\\mu'} t_{\\ell\\mu} t_{\\ell'\\mu'}\n  \\cov_\\rho\\p{\\Pi_{i\\mu}, \\Pi_{i\\mu'}}\n  = \\delta_{ii'} \\times \\f1n \\cov_\\rho\\p{T_{i\\ell}, T_{i\\ell'}},\n\\end{align}\nwhere we used the fact that the covariance $\\cov_\\rho\\p{X,Y}$ is linear in both $X$ and $Y$.\nDue to the appearance of $\\delta_{ii'}$ above and the orthogonality of polarization operators $T_{i\\ell}$ and $T_{i'\\ell'}$ with degrees $\\ell\\ne\\ell'$, it turns out that only the variances $\\bbk{\\epsilon_{i\\ell}^2}$ will ultimately contribute to reconstruction error (see Appendix \\ref{sec:revisiting}).\nWe therefore seek to find an upper bound on $\\bbk{\\epsilon_{i\\ell}^2}$.\n\nTo this end, we define the probability $p^i_\\mu\\equiv\\bk{\\Pi_{i\\mu}}_\\rho$, collect these probabilities into the classical probability distribution $p^i = \\sum_\\mu p^i_\\mu \\ket{\\mu}$, and define the vector $t_\\ell \\equiv \\sum_\\mu t_{\\ell\\mu} \\ket{\\mu}$.\nWe then observe that\n\\begin{align}\n  \\bbk{\\epsilon_{i\\ell}^2} = \\f1n \\times \\sigma_{p^i}^2\\p{t_\\ell},\n  &&\n  \\sigma_p^2\\p{X}\n  \\equiv \\sum_\\mu p_\\mu X_\\mu^2 - \\p{\\sum_\\mu p_\\mu X_\\mu}^2,\n\\end{align}\nwhere $\\sigma_p^2\\p{X}$ is the weighted variance of $X$.\nThis variance is maximal when $p$ has equal weight on the largest and smallest values of $X$, which implies that\n\\begin{align}\n  \\sigma_p^2\\p{t_\\ell} \\le \\Gamma_\\ell^2,\n  &&\n  \\Gamma_\\ell \\equiv \\f{\\max_\\mu t_{\\ell\\mu} - \\min_\\mu t_{\\ell\\mu}}{2},\n  &&\n  \\t{so}\n  &&\n  \\bbk{\\epsilon_{i\\ell}^2} \\le \\f1n \\times \\Gamma_\\ell^2.\n\\end{align}\nNote that this bound on $\\bbk{\\epsilon_{i\\ell}^2}$ is tight, as equality is achieved by the state\n\\begin{align}\n  \\rho_i^\\star = \\f12\\p{\\Pi_{i\\mu_{\\t{max}}} + \\Pi_{i\\mu_{\\t{min}}}},\n\\end{align}\nwhere $\\mu_{\\t{max}}$ ($\\mu_{\\t{min}}$) is the index that maximizes (minimizes) $t_{\\ell\\mu}$.\n\nTo find an analytical bound on $\\bbk{\\epsilon_{i\\ell}^2}$ that is easier to interpret, we can use normalization of the polarization operators, $\\obk{T_{i\\ell}|T_{i\\ell}}=\\sum_\\mu t_{\\ell\\mu}^2 = 1$, and the fact that all probabilities $p_\\mu\\le1$ to bound\n\\begin{align}\n  \\sigma_p^2\\p{t_\\ell} \\le \\sum_\\mu p_\\mu t_{\\ell\\mu}^2\n  \\le \\sum_\\mu t_{\\ell\\mu}^2 = 1,\n  &&\n  \\t{so}\n  &&\n  \\bbk{\\epsilon_{i\\ell}^2} < \\f1n.\n\\end{align}\nWe can get a tighter bound by considering the fact that $t_{\\ell\\mu}^2 = t_{\\ell,-\\mu}^2$ due to the symmetries of the Clebsch-Gordan coefficients.\nIt follows that if $\\mu_{\\t{max}}\\ne0$ then\n\\begin{align}\n  \\sigma_p^2\\p{t_\\ell} \\le \\sum_\\mu p_\\mu t_{\\ell\\mu}^2\n  \\le t_{\\ell\\mu_{\\t{max}}}^2\n  = \\f12 \\p{t_{\\ell\\mu_{\\t{max}}}^2 + t_{\\ell,-\\mu_{\\t{max}}}^2}\n  \\stackrel{\\mu_{\\t{max}}\\ne0}{\\le} \\f12 \\sum_\\mu t_{\\ell\\mu}^2\n  = \\f12.\n\\end{align}\nIf $\\mu_{\\t{max}}=0$, then similarly\n\\begin{align}\n  t_{\\ell\\mu_{\\t{max}}}^2 + 2 t_{\\ell\\mu_{\\t{min}}}^2\n  = t_{\\ell\\mu_{\\t{max}}}^2 + t_{\\ell\\mu_{\\t{min}}}^2\n  + t_{\\ell,-\\mu_{\\t{min}}}^2\n  \\stackrel{\\mu_{\\t{max}}=0}{\\le}\n  \\sum_\\mu t_{\\ell\\mu}^2 = 1,\n  &&\n  \\t{so}\n  &&\n  \\abs{t_{\\ell\\mu_{\\t{min}}}}\n  \\stackrel{\\mu_{\\t{max}}=0}{\\le}\n  \\sqrt{\\f{1 - t_{\\ell\\mu_{\\t{max}}}^2}{2}},\n\\end{align}\nwhich lets us bound\n\\begin{align}\n  \\Gamma_\\ell\n  = \\f12 \\p{t_{\\ell\\mu_{\\t{max}}} - t_{\\ell\\mu_{\\t{min}}}}\n  \\le \\f12 \\p{t_{\\ell\\mu_{\\t{max}}} + \\abs{t_{\\ell\\mu_{\\t{min}}}}}\n  \\stackrel{\\mu_{\\t{max}}=0}{\\le}\n  \\f12 t_{\\ell\\mu_{\\t{max}}}\n  + \\f12\\sqrt{\\f{1 - t_{\\ell\\mu_{\\t{max}}}^2}{2}}\n  \\equiv \\lambda\\p{t_{\\ell\\mu_{\\t{max}}}}.\n\\end{align}\nIt is straightforward to show that $\\lambda\\p{x}$ is maximally $\\lambda^\\star\\equiv \\max_x \\lambda\\p{x} = \\sqrt{3/8}$, so\n\\begin{align}\n  \\Gamma_\\ell^2\n  \\stackrel{\\mu_{\\t{max}}=0}{\\le} \\p{\\lambda^\\star}^2\n  = \\f38 < \\f12.\n\\end{align}\nAltogether, we thus find that in all cases\n\\begin{align}\n  \\sigma_p^2\\p{t_\\ell} \\le \\f12,\n  &&\n  \\t{so}\n  &&\n  \\bbk{\\epsilon_{i\\ell}^2} \\le \\f1{2n}.\n\\end{align}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Revisiting the reconstruction error bound}\n\\label{sec:revisiting}\n\nWe now revisit the derivation of reconstruction error in Section \\ref{sec:error} to make use of the bounds on variances $\\bbk{\\epsilon_{i\\ell}^2}$.\nTo recap, for a set of measurement axes $V=\\set{\\bm v}$ and degrees $\\ell\\in\\set{0,1,\\cdots,d-1}$ we construct the measurement matrix\n\\begin{align}\n  M_V \\equiv \\sum_{\\bm v,\\ell} \\ket{\\bm v\\ell} \\obra{T_{\\bm v\\ell,0}},\n\\end{align}\nwhich can be block diagonalized as\n\\begin{align}\n  M_V U = \\sum_\\ell \\op{\\ell} \\otimes M_{V\\ell},\n  &&\n  U \\equiv \\sum_{\\ell,m} \\oket{T_{\\ell m}} \\bra{\\ell m},\n  &&\n  M_{V\\ell} = \\sum_{m,\\bm v} D^\\ell_{m,0}\\p{\\bm v} \\op{\\bm v}{m},\n\\end{align}\nwhere $D^\\ell_{mn}\\p{\\bm v}\\equiv\\bk{\\ell m|R\\p{\\bm v}|\\ell n}$ is a (Wigner) rotation matrix element for a spin-$\\ell$ particle.\nThe block-diagonal structure of $M_V$ allows us to index its singular values $M^V_{\\ell m}$ and corresponding (normalized) left singular vectors $\\bm x^V_{\\ell m} = \\sum_i x^V_{\\ell m i} \\ket{\\bm v_i}$ by the indices $\\p{\\ell,m}$, where the integer $\\abs{m}\\le\\ell$.\nThese singular vectors and values define the orthonormal operators\n\\begin{align}\n  Q^V_{\\ell m} \\equiv \\sum_i \\p{q^V_{\\ell mi}}^* T_{i\\ell},\n  &&\n  q^V_{\\ell m i} \\equiv \\f{x^V_{\\ell m i}}{M^V_{\\ell m}},\n\\end{align}\nwhere $i\\in\\set{1,2,\\cdots,\\abs{V}}$ indexes an axis $\\bm v_i\\in V$, with $T_{i\\ell} \\equiv T_{\\bm v_i\\ell}$.\nThe state $\\rho$ can be expanded in the basis of these operators as\n\\begin{align}\n  \\rho = \\sum_{\\ell,m} \\bk{{Q^V_{\\ell m}}^\\dag}_\\rho Q^V_{\\ell m},\n\\end{align}\nand the estimates $\\tilde T_{i\\ell}$ of $\\bk{T_{i\\ell}}_\\rho$ can be used to construct the following estimate $\\tilde\\rho_V$ of $\\rho$:\n\\begin{align}\n  \\tilde\\rho_V \\equiv \\sum_{\\ell,m}\n  \\sp{\\sum_i q^V_{\\ell mi} \\tilde T_{i\\ell}} Q^V_{\\ell m}\n  \\approx \\sum_{\\ell,m}\n  \\sp{\\sum_i q^V_{\\ell mi} \\bk{T_{i\\ell}}_\\rho} Q^V_{\\ell m}\n  = \\sum_{\\ell,m} \\bk{Q^V_{\\ell m}}_\\rho Q^V_{\\ell m}\n  = \\rho.\n\\end{align}\nRecalling that $\\epsilon_{i\\ell} \\equiv \\tilde T_{i\\ell} - \\bk{T_{i\\ell}}_\\rho$, we can use orthonormality of all $Q^V_{\\ell m}$ to expand the mean squared distance between $\\tilde\\rho_V$ and $\\rho$ as\n\\begin{align}\n  \\E_V\\p{\\rho}^2 \\equiv \\Bbk{\\norm{\\tilde\\rho_V-\\rho}^2}\n  = \\sum_{\\ell,m,i,i'} \\p{q^V_{\\ell mi}}^* q^V_{\\ell mi'} \\bbk{\\epsilon_{i\\ell} \\epsilon_{i'\\ell}}\n  = \\sum_{\\ell,m,i} \\abs{q^V_{\\ell mi}}^2 \\bbk{\\epsilon_{i\\ell}^2}\n  < \\f1n \\sum_\\ell \\Gamma_\\ell^2 \\S_{V\\ell}^2,\n  \\label{eq:bound_apndx}\n\\end{align}\nwhere we used the fact that $\\bbk{\\epsilon_{i\\ell}^2}\\le\\Gamma_\\ell^2/n$, and\n\\begin{align}\n  \\sum_{m,i} \\abs{q^V_{\\ell mi}}^2\n  = \\sum_m \\p{M^V_{\\ell m}}^{-2}\n  = \\norm{M_{V\\ell}^{-1}}\n  = \\S_{V\\ell}^2.\n\\end{align}\nHere $M_{V\\ell}^{-1}$ is the left inverse of $M_{V\\ell}$.\nThe fact that $\\bbk{\\epsilon_{i\\ell}^2}<1/2n$ also implies that\n\\begin{align}\n  \\E_V\\p{\\rho}^2 < \\f1{2n} \\sum_\\ell \\S_{V\\ell}^2 = \\f{\\S_V^2}{2n}.\n\\end{align}\nNote that the bound in Eq.~\\eqref{eq:bound_apndx} is not tight, as the individual bounds on the variances $\\bbk{\\epsilon_{i\\ell}^2}$ cannot all be achieved simultaneously.\nThere is therefore still room for improvement on the bound in Eq.~\\eqref{eq:bound} by maximizing $\\E_V$ over the set of physically achievable qudit states $\\rho$.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Exact reconstruction error}\n\\label{sec:exact}\n\nHere we find exact expressions for reconstruction error, which can be used to estimate the error in a given reconstruction $\\tilde\\rho_V$ of an unknown state $\\rho$ after performing tomography.\nTo this end, we start with Eq.~\\eqref{eq:bound_apndx} from Appendix \\ref{sec:revisiting} to write\n\\begin{align}\n  \\E_V\\p{\\rho}^2\n  = \\sum_{\\ell,m,i,i'} \\p{q^V_{\\ell mi}}^* q^V_{\\ell mi'} \\bbk{\\epsilon_{i\\ell}\\epsilon_{i'\\ell}}\n  = \\f1n \\sum_{\\ell,i} \\abs{\\tilde{\\bm q}_{\\ell i}}^2 \\cov_\\rho\\p{T_{i\\ell},T_{i\\ell}},\n  &&\n  \\abs{\\tilde{\\bm q}_{\\ell i}}^2 = \\sum_m \\abs{q_{\\ell mi}}^2,\n  \\label{eq:error_SM_start}\n\\end{align}\nwhere $\\tilde{\\bm q}_{\\ell i} = \\sum_m \\p{q_{\\ell mi}}^* \\ket{m}$, and we used the fact that $\\bbk{\\epsilon_{i\\ell}\\epsilon_{i'\\ell}} = \\delta_{ii'}\\times\\cov_\\rho\\p{T_{i\\ell},T_{i\\ell}}/n$.\nIdentifying the singular value decomposition $M_{V\\ell} = U_{V\\ell} \\Sigma_{V\\ell} W_{V\\ell}^\\dag$, we then we observe that $\\tilde{\\bm q}_{\\ell i} = \\Sigma_{V\\ell}^{-1} U_{V\\ell}^\\dag \\ket{\\bm v_i}$, which allows us to simplify\n\\begin{align}\n  \\abs{\\tilde{\\bm q}_{\\ell i}}^2\n  = \\bk{\\bm v_i | U_{V\\ell} \\Sigma_{V\\ell}^{-2} U_{V\\ell}^\\dag | \\bm v_i}\n  = \\bk{\\bm v_i| \\p{M_{V\\ell}^{-1}}^\\dag M_{V\\ell}^{-1} | \\bm v_i}.\n\\end{align}\nUsing the fact that all $T_{i\\ell}=T_{i\\ell}^\\dag$, we can also expand\n\\begin{align}\n  \\cov_\\rho\\p{T_{i\\ell},T_{i\\ell}}\n  = \\cov_\\rho\\p{T_{i\\ell}^\\dag,T_{i\\ell}}\n  = \\sum_{m,m'} D^\\ell_{0,m}\\p{\\bm v_i} D^\\ell_{0,m'}\\p{\\bm v_i}^*\n  \\cov_\\rho\\p{T_{\\ell m}^\\dag, T_{\\ell m'}},\n\\end{align}\nwhich implies that\n\\begin{align}\n  \\E_V\\p{\\rho}^2\n  = \\f1n \\sum_{\\ell,i,m,m'}\n  D^\\ell_{0,m'}\\p{\\bm v_i}^* \\abs{\\tilde{\\bm q}_{\\ell i}}^2\n  D^\\ell_{0,m}\\p{\\bm v_i}\n  \\cov_\\rho\\p{T_{\\ell m}^\\dag, T_{\\ell m'}}.\n\\end{align}\nAltogether, this reconstruction error can be expressed more compactly by defining the {\\it covariance matrix}\n\\begin{align}\n  \\C_\\ell\\sp{\\rho} \\equiv\n  \\sum_{m,m'} \\cov_\\rho\\p{T_{\\ell m}^\\dag, T_{\\ell m'}} \\op{m}{m'},\n\\end{align}\nand the {\\it noise matrix}\n\\begin{align}\n  \\N_{V\\ell} \\equiv M_{V\\ell}^\\dag \\diag\\sp{\\p{M_{V\\ell}^{-1}}^\\dag\n    M_{V\\ell}^{-1}} M_{V\\ell},\n\\end{align}\nwhere $\\diag\\sp{X}$ sets all off-diagonal entries of $X$ to zero, in terms of which\n\\begin{align}\n  \\E_V\\p{\\rho}^2 = \\f1n \\sum_\\ell \\obk{\\N_{V\\ell}|\\C_\\ell\\sp{\\rho}},\n  \\label{eq:error_SM_mid}\n\\end{align}\nwhere $\\obk{X|Y}=\\tr\\p{X^\\dag Y}$ is a trace inner product.\n\nThe result in Eq.~\\eqref{eq:error_SM_mid} essentially expresses reconstruction error as a weighted sum of the covariances $\\cov_\\rho\\p{T_{\\ell m},T_{\\ell m'}}$, where the weights are given by the corresponding matrix elements of the noise matrix $\\N_{V\\ell}$.\nThis expression is perhaps the most physically meaningful form of the reconstruction error $\\E_V\\p{\\rho}$ that we will consider in this work, but in practice it turns out that Eq.~\\eqref{eq:error_SM_mid} is inconvenient and inefficient to evaluate for any given state $\\rho$.\nTo find a more practical expression of reconstruction error, we use the fact that\n\\begin{align}\n  \\bk{T_{\\ell m}^\\dag}_\\rho\n  = \\obk{\\rho|T_{\\ell m}^\\dag}\n  = \\tr\\p{\\rho T_{\\ell m}^\\dag}\n  = \\tr\\p{T_{\\ell m}^\\dag \\rho}\n  = \\obk{T_{\\ell m}|\\rho},\n\\end{align}\nto expand the covariance matrix as\n\\begin{align}\n  \\C_\\ell\\sp{\\rho}\n  &= \\sum_{m,m'} \\op{m}{m'} \\sp{\\obk{\\rho|T_{\\ell m}^\\dag T_{\\ell m'}}\n    - \\obk{\\rho|T_{\\ell m}^\\dag} \\obk{\\rho|T_{\\ell m'}}} \\\\\n  &= \\sum_{m,m'} \\op{m}{m'} \\sp{\\obk{T_{\\ell m'}^\\dag T_{\\ell m}|\\rho}\n    - \\obk{T_{\\ell m}|\\rho} \\obk{T_{\\ell m'}^\\dag|\\rho}} \\\\\n  &= \\sum_{m,m'} \\op{m}{m'}\\I \\sp{\\obk{T_{\\ell m'} T_{\\ell m}|\\rho}\n    - \\obk{T_{\\ell m}|\\rho} \\obk{T_{\\ell m'}|\\rho}}\n\\end{align}\nwhere we define the inversion operator $\\I\\equiv\\sum_m \\p{-1}^m\\op{-m}{m}$.\nWe then expand the product $T_{\\ell m'} T_{\\ell m}$ as\n\\begin{align}\n  \\obk{T_{\\ell m'} T_{\\ell m}|\\rho}\n  = \\sum_L g_{\\ell m'm}^L \\obk{T_{L,m'+m}|\\rho},\n  &&\n  g_{\\ell m'm}^L \\equiv \\obk{T_{L,m'+m} | T_{\\ell m'} T_{\\ell m}}\n  = f_{\\ell m';\\ell m}^{L,m'+m},\n\\end{align}\nwhere the (real) factors $f_{\\ell m';\\ell m}^{L,m'+m}$ are provided in Appendix \\ref{sec:trans_prod}.\nSubstituting the covariance matrix back into Eq.~\\eqref{eq:error_SM_mid} and replacing $\\obk{T_{\\ell m}|\\rho}\\to\\rho_{\\ell m}$, we get\n\\begin{align}\n  \\E_V\\p{\\rho}^2\n  = \\f1n \\sp{\\sum_{\\ell,m} \\p{\\chi^V_{\\ell m}}^* \\rho_{\\ell m}\n  - \\sum_{\\ell,m,m'} \\bk{m'|\\I\\N_{V\\ell}|m}\n  \\rho_{\\ell m} \\rho_{\\ell m'}},\n  \\label{eq:error_comps}\n\\end{align}\nwhere\n\\begin{align}\n  \\chi^V_{LM}\n  &\\equiv \\sum_{\\ell,m,m'} \\delta_{M,m'+m}\n  \\bk{m'|\\I\\N_{V\\ell}|m}^* g^L_{\\ell m'm} \\\\\n  &= \\sum_{\\ell,m,m'} \\delta_{M,-m'+m}\n  \\bk{m|\\N_{V\\ell}|m'} \\p{-1}^{m'} g^L_{\\ell,-m',m} \\\\\n  &= \\sum_\\ell \\obk{\\N_{V\\ell}|\\D_M|\\I g_{L\\ell}}\n\\end{align}\ncan be written in terms of the matrices\n\\begin{align}\n  g_{L\\ell} \\equiv \\sum_{m,m'} g^L_{\\ell m'm} \\op{m'}{m},\n  &&\n  \\D_M \\equiv \\sum_{m,m'} \\delta_{M,-m'+m} \\op{m'm}.\n\\end{align}\nHere $\\D_M$ simply picks off the $M$-th diagonal of the matrix it acts on, such that $\\obk{\\N_{V\\ell}|\\D_M|\\I g_{L\\ell}}$ is an inner product of the $M$-th diagonal of $\\I g_{L\\ell}$ with the $\\p{-M}$-th diagonal of $\\N_{V\\ell}$.\nDefining the $\\p{2\\ell+1}$-component vectors\n\\begin{align}\n  \\ket{\\rho_\\ell} \\equiv \\sum_m \\rho_{\\ell m} \\ket{m},\n  &&\n  \\ket{\\chi_{V\\ell}} \\equiv \\sum_{\\ell,m} \\chi^V_{\\ell m} \\ket{m},\n\\end{align}\nwe can write the expansion in Eq.~\\eqref{eq:error_comps} in the vectorized form\n\\begin{align}\n  \\E_V\\p{\\rho}^2\n  = \\f1n \\sum_\\ell \\sp{\\bk{\\chi_{V\\ell}|\\rho_\\ell}\n    - \\bk{\\rho_\\ell|\\N_{V\\ell}|\\rho_\\ell}}.\n  \\label{eq:error_SM}\n\\end{align}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection*{Comments on a tight reconstruction error bound}\n\nIn principle, maximizing the reconstruction error in Eq.~\\eqref{eq:error_SM} over all qudit states $\\rho$ would provide a tight upper bound on reconstruction error for any set of axes $V$.\nTo simplify this task somewhat, we first maximize Eq.~\\eqref{eq:error_SM} over all $\\rho$ with $\\tr\\p\\rho=1$: this maximum occurs at a ``state'' $\\sigma_V^\\star$ whose components are given by\n\\begin{align}\n  \\ket{\\sigma_{V\\ell}^\\star} \\stackrel{\\ell\\ne0}{\\equiv}\n  \\f12 \\N_{V\\ell}^{-1} \\ket{\\chi_{V\\ell}},\n  &&\n  \\ket{\\sigma_{V,0}^\\star} \\equiv \\f1{\\sqrt{d}} \\ket{0}.\n\\end{align}\nThe corresponding maximum of $\\E_V$ is given by\n\\begin{align}\n  \\E_V\\p{\\sigma_V^\\star}^2 = \\f1n \\sum_{\\ell>0}\n  \\sp{\\f14 \\bk{\\chi_{V\\ell}|\\N_{V\\ell}^{-1}|\\chi_{V\\ell}}\n  - \\f1d \\tr\\p{\\N_{V\\ell}}},\n\\end{align}\nwhere the $\\tr\\p{\\N_{V\\ell}}$ terms above come from simplifying the $\\ell=0$ terms of Eq.~\\eqref{eq:error_SM} with $\\rho\\to\\sigma_V^\\star$.\nWhile $\\E_V\\p{\\sigma_V^\\star}$ is a strict upper bound on $\\E_V\\p{\\rho}$ over all $\\rho$ with $\\tr\\p{\\rho}=1$, this bound turns out to be useless in practice, because $\\sigma_V^\\star$ will generally be a non-physical ``state'' with negative eigenvalues.\nTo find tight bound on $\\E_V\\p{\\rho}$ over the space of physical qudit states $\\rho$, we also need to constrain $\\rho$ to have no negative eigenvalues.\nEquipped with $\\sigma_V^\\star$ and $\\E_V\\p{\\sigma_V^\\star}$, we can expand\n\\begin{align}\n  \\E_V\\p{\\rho}^2 = \\E_V\\p{\\sigma_V^\\star}^2\n  - \\f1n \\norm{\\rho-\\sigma_V^\\star}_V^2,\n  &&\n  \\norm{X}_V^2 \\equiv \\sum_\\ell \\bk{X_\\ell|\\N_{V\\ell}|X_\\ell},\n\\end{align}\nwhere $X_\\ell\\equiv\\sum_m\\obk{T_{\\ell m}|X}\\ket{m}$ is a vector of the degree-$\\ell$ components of $X$ in the polarization operator basis, and $\\norm{X}_V$ is a noise-weighted norm of $X$.\nMaximizing $\\E_V$ over all qudit states $\\rho$ thus amounts to finding the closest physical qudit state $\\rho$ to $\\sigma_V^\\star$, with distance measured by the metric $D_V\\p{X,Y}\\equiv\\norm{X-Y}_V$.\nWe leave this minimization problem to future work, and note that solving it will likely require making use of the positivity conditions derived in Ref.~\\cite{kryszewski2006positivity}.\nA loose lower bound on $\\norm{\\rho-\\sigma_V^\\star}_V$ can be found by minimization under the constraint $\\norm{\\rho}\\le1$, which may provide a tighter upper bound on $\\E_V\\p{\\rho}$ than that in Eq.~\\eqref{eq:bound} of the main text.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Polarization operator product expansion}\n\\label{sec:trans_prod}\n\nThe polarization operators on the $d$-dimensional Hilbert space of a spin-$s$ system (with $s\\equiv\\frac{d-1}{2}$) are defined by\n\\begin{align}\n  T_{\\ell m} \\equiv \\sqrt{\\f{2\\ell+1}{2s+1}} \\sum_{\\mu,\\nu=-s}^s\n  \\bk{s\\mu;\\ell m|s\\nu} \\op{\\nu}{\\mu},\n\\end{align}\nwhere $\\bk{s\\mu;\\ell m|s\\nu}$ is a Clebsh-Gordan coefficient that enforces $\\ell\\in\\set{0,1,\\cdots,2s}$ and $m\\in\\set{-\\ell,-\\ell+1,\\cdots,\\ell}$.\nWe wish to compute the coefficients of the operator product expansion\n\\begin{align}\n  T_{\\ell_1 m_1} T_{\\ell_2 m_2}\n  = \\sum_{L,M} f_{\\ell_1 m_1;\\ell_2 m_2}^{LM} T_{LM},\n  &&\n  f_{\\ell_1 m_1;\\ell_2 m_2}^{LM}\n  \\equiv \\obk{T_{LM} | T_{\\ell_1 m_1} T_{\\ell_2 m_2}},\n\\end{align}\nwhich allow us to simplify the commutators in Eq.~\\eqref{eq:spin_trans} of Appendix \\ref{sec:rotations}.\nUsing the symmetry properties of Clebsch-Gordan coefficients, namely\n\\begin{align}\n  \\bk{\\ell_1 m_1; \\ell_2 m_2| L M}\n  &= \\p{-1}^{\\ell_2+m_2} \\sqrt{\\f{2L+1}{2\\ell_1+1}}\n  \\bk{L,-M; \\ell_2 m_2| \\ell_1,-m_1} \\\\\n  \\bk{\\ell_1 m_1; \\ell_2 m_2| L M}\n  &= \\p{-1}^{\\ell_1+\\ell_2-L}\n  \\bk{\\ell_1,-m_1; \\ell_2,-m_2| L,-M},\n\\end{align}\nwe can find that the polarization operators transform under conjugation as\n\\begin{align}\n  T_{\\ell m}^\\dag\n  = \\sqrt{\\f{2\\ell+1}{2s+1}}\n  \\sum_{\\mu,\\nu} \\p{-1}^m \\bk{s\\nu;\\ell,-m|s\\mu} \\op{\\mu}{\\nu}\n  = \\p{-1}^m T_{\\ell,-m},\n\\end{align}\nwhich implies that\n\\begin{align}\n  f_{\\ell_1 m_1;\\ell_2 m_2}^{LM}\n  = \\p{-1}^M \\sqrt{\\f{\\p{2L+1}\\p{2\\ell_1+1}\\p{2\\ell_2+1}}\n    {\\p{2s+1}\\p{2s+1}\\p{2s+1}}}\n  \\sum_{\\mu,\\nu,\\rho} \\bk{s\\nu;L,-M|s\\mu}\n  \\bk{s\\rho;\\ell_1m_1|s\\nu} \\bk{s\\mu;\\ell_2m_2|s\\rho}.\n\\end{align}\nReplacing Clebsch-Gordan coefficients by Wigner 3-$j$ symbols with the identity\n\\begin{align}\n  \\bk{\\ell_1 m_1; \\ell_2 m_2| L M}\n  = \\p{-1}^{2\\ell_2} \\p{-1}^{L-M} \\sqrt{2L+1}\n  \\begin{pmatrix}\n    L & \\ell_2 & \\ell_1 \\\\\n    -M & m_2 & m_1\n  \\end{pmatrix},\n\\end{align}\nwe can use the fact that $2\\ell_2$ is always even (because $\\ell_2$ is always an integer) to expand\n\\begin{multline}\n  f_{\\ell_1 m_1;\\ell_2 m_2}^{LM}\n  = \\p{-1}^M \\sqrt{\\p{2L+1}\\p{2\\ell_1+1}\\p{2\\ell_2+1}} \\\\\n  \\times \\sum_{\\mu,\\nu,\\rho} \\p{-1}^{3s-\\mu-\\nu-\\rho}\n  \\begin{pmatrix}\n    s & L & s \\\\\n    -\\mu & -M & \\nu\n  \\end{pmatrix}\n  \\begin{pmatrix}\n    s & \\ell_1 & s \\\\\n    -\\nu & m_1 & \\rho\n  \\end{pmatrix}\n  \\begin{pmatrix}\n    s & \\ell_2 & s \\\\\n    -\\rho & m_2 & \\mu\n  \\end{pmatrix}.\n\\end{multline}\nThis sum can be simplified by the introduction of Wigner 6-$j$ symbols, giving us\n\\begin{align}\n  f_{\\ell_1 m_1;\\ell_2 m_2}^{LM}\n  &= \\p{-1}^{2s+M} \\sqrt{\\p{2L+1}\\p{2\\ell_1+1}\\p{2\\ell_2+1}}\n  \\begin{pmatrix}\n    L & \\ell_1 & \\ell_2 \\\\\n    M & -m_1 & -m_2\n  \\end{pmatrix}\n  \\begin{Bmatrix}\n    L & \\ell_1 & \\ell_2 \\\\\n    s & s & s\n  \\end{Bmatrix} \\\\\n  &= \\p{-1}^{2s+L} \\sqrt{\\p{2\\ell_1+1}\\p{2\\ell_2+1}}\n  \\bk{\\ell_1 m_1; \\ell_2 m_2| LM}\n  \\begin{Bmatrix}\n    \\ell_1 & \\ell_2 & L \\\\\n    s & s & s\n  \\end{Bmatrix}.\n\\end{align}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Optimizing the method of Newton and Young}\n\\label{sec:angle_search}\n\nRef.~\\cite{newton1968measurability} constructs an explicit protocol for spin qudit tomography, which involves measuring spin projection along $2d-1$ axes equally spaced at a polar angle $\\theta$.\nHowever, this method does not provide any prescription for choosing $\\theta$.\nHere, we show the importance of making a good choice of $\\theta$, and empirically find the optimal value of $\\theta_{\\t{opt}}$ that minimizes the corresponding quantum error scale $\\epsilon_\\theta$, which controls state reconstruction error.\nTo this end, Figure \\ref{fig:angle_sweep} shows the quantum error scale $\\epsilon_\\theta$ as a function of the polar angle $\\theta$ in the tomography method of Ref.~\\cite{newton1968measurability} for a few qudit dimensions $d$.\nWhile a good choice of $\\theta$ yields an error scale $\\epsilon_\\theta\\approx d$ (for the dimensions shown), this error scale can increase by orders of magnitude for poor choices of $\\theta$.\nIn turn, Figure \\ref{fig:opt_angles} shows the optimal angle $\\theta_{\\t{opt}}$ as a function of the qudit dimension $d$, together with a fit to $\\theta_{\\t{opt}}=\\frac{\\pi}{2}(1-\\frac1{xd})$ finding $x\\approx1.34$.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics{angle_sweep.pdf}\n  \\caption{Quantum error scale $\\epsilon_\\theta$ as a function of the polar angle $\\theta$ in the tomography method of Ref.~\\cite{newton1968measurability} for a few qudit dimensions $d$.}\n  \\label{fig:angle_sweep}\n\\end{figure}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics{opt_angles.pdf}\n  \\caption{Optimum angle $\\theta_{\\t{opt}}$ as a function of qudit dimension $d$ for the tomography method of Ref.~\\cite{newton1968measurability}, and a fit to $\\theta_{\\t{opt}}=\\frac{\\pi}{2}(1-\\frac1{xd})$ finding $x\\approx1.34$.}\n  \\label{fig:opt_angles}\n\\end{figure}\n\n\\end{document}\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: t\n%%% End:\n\n\nsignal recovery literature:\n-- a $\\sim2d^2$ signaling theorem \\cite{mcewen2011novel}\n-- a nice review of these methods \\cite{mcewen2011sampling}\n-- an empirically accurate (albeit without rigorous proofs/guarantees) $d^2$ sampling method \\cite{khalid2014optimaldimensionality}\n-- current status of the theory behind sparse signal recovery with random sampling \\cite{rauhut2011sparse} (note: existing bounds are not believed to be tight)\n-- nice numerical method for sparse signal recovery \\cite{alem2012sparse}\n-- useful textbook references \\cite{freeden2008spherical, freeden2018spherical}\n", "meta": {"hexsha": "0b172cc821da1327e303ef194cb4ef1ccf45a8b0", "size": 78052, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "sun_phases/qudit_tomo.tex", "max_stars_repo_name": "perlinm/rey_research", "max_stars_repo_head_hexsha": "491d1d33cc8d20dc1b72de552ac7c1b65fb3ee63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sun_phases/qudit_tomo.tex", "max_issues_repo_name": "perlinm/rey_research", "max_issues_repo_head_hexsha": "491d1d33cc8d20dc1b72de552ac7c1b65fb3ee63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sun_phases/qudit_tomo.tex", "max_forks_repo_name": "perlinm/rey_research", "max_forks_repo_head_hexsha": "491d1d33cc8d20dc1b72de552ac7c1b65fb3ee63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 66.4272340426, "max_line_length": 674, "alphanum_fraction": 0.6961512838, "num_tokens": 25628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3387169266059758}}
{"text": "\n\\begin{figure}[H]\n  \\centering\n  \\includegraphics[width=0.7\\linewidth]{./chapters/exp1/methodology1_3.png}\n  \\caption[Third portion of the flowchart from Figure \\ref{fig:method1}]\n          {Third portion of the flowchart from Figure \\ref{fig:method1} being \n           described in this section.}\n\\end{figure}\n\nSince this work has yet to be benchmarked with simple algorithms, two\nstraightforward algorithms were chosen, \\textit{k}-nearest neighbors and\ndecision trees, and were introduced in Section \\ref{sec:algs}. Also covered in\nthat section is the mathematical framework of the \\gls{MLL} calculation method.\nThe implementation details of these three approaches are covered here. \n\n\\subsection{Scikit-learn Algorithms}\n\nThe machine learning toolkit chosen for this work is scikit-learn\n\\cite{scikit}, a package in python.  Virtually all modern \\gls{ML} toolkits\nwill have acceptably fast and reliable algorithms, but the use of python\nprovides a platform for seamless integration of all the tools in the workflow.\nThis section walks through the implementation of the two scikit algorithms. \n\nThe first step is splitting the training set into the features ($\\vec{X}$, with\n29 nuclide mass measurements), and a single set of labels ($\\vec{y}$, e.g.,\nburnup). After this, the set of features $\\vec{X}$ is scaled so that there is a\nzero mean and unit variance; this is done because the magnitude of the features\nvary widely and it can be either helpful or required for many scikit-learn\nalgorithms. Next, the two algorithms are initialized.  The labels that require\nregression analysis (burnup, enrichment, cooling time) are predicted using the\n\\texttt{KNeighborsRegressor} and \\texttt{DecisionTreeRegressor} in\nscikit-learn. The reactor type label uses classifiers:\n\\texttt{KNeighborsClassifier} and \\texttt{DecisionTreeClassifier}.  \n\nEach algorithm has a list of hyperparameters that impact the model complexity\nand prediction performance, as discussed in Section \\ref{sec:complexity}. Since\nthis work is a demonstrative investigation, many of the default choices are\nretained. However, some of these were tuned using hyperparameter optimization,\nshown in Table \\ref{tbl:exp1hypparam}.  Hyperparameter optimization involves\ncompleting the training, predicting, and error evaluation process for a list of\nparameters that are of a continuous nature.  This process is carried out with\n\\textit{k} for \\textit{k}-nearest neighbors, choosing the value that provides\nthe best results. For decision trees, the maximum features was chosen to be 29\nbecause the performance was highly variable otherwise, but this is not\nnecessarily ideal for the best performance. Instead, only the maximum depth was\ntuned via optimization.  There are also other parameters governing algorithm\nbehavior that have a discrete set of choices.  The selections made for each of\nthese algorithms is summarized below (note this is just a subset of all\navailable hyperparameters \\cite{scikit}):\n\\begin{enumerate}\n  \\item \\texttt{KNeighborsClassifier} \\& \\texttt{KNeighborsRegressor}\n    \\begin{itemize}\n      \\item Number of nearest neighbors (\\textit{k}) to include changes for \n            each prediction category and is in Table \\ref{tbl:exp1hypparam}.\n      \\item Distance metric is \"Manhattan\" (aka $L_1$ loss, or absolute \n            differences): $d_i = \\sum_{j=1}^{N_{feats}} \n            |x_{j,train} - x_{j,test}|$.\n      \\item Sample weighting is with respect to distance and not uniform : \n            $w_i = 1/d_i$.\n    \\end{itemize}\n  \\item \\texttt{DecisionTreeClassifier} \\& \\texttt{DecisionTreeRegressor}\n    \\begin{itemize}\n      \\item Maximum number of features included is the length of the feature \n            set: 29.\n      \\item Maximum depth of decision tree changes for each prediction category\n            and is in Table \\ref{tbl:exp1hypparam}.\n      \\item For both the classifier and regressor, the default splitting \n            criterion (function for measuring the quality of a split) is kept.\n            This is the Gini impurity for the former (see Equation \n            \\ref{eq:gini}), and mean squared error (aka $L_2$ loss, see \n            Equation \\ref{eq:mse}) for the latter.\n      \\item For the classifier, the \\texttt{class\\_weight} is \"balanced\", \n            meaning that the weights are inversely proportional to the frequency\n            of each class (\\gls{PWR}, \\gls{BWR}, \\gls{PHWR}) in the training set.\n    \\end{itemize}\n\\end{enumerate}\n\n\\begin{table}[!hbt]\n  \\centering\n  \\begin{tabular}{@{}lcll@{}}\n  \\toprule\n    \\textbf{\\begin{tabular}[c]{@{}l@{}}Prediction\\\\ Parameter\\end{tabular}}\n  & \\textbf{\\begin{tabular}[c]{@{}l@{}}\\textit{k} \\\\ (N neighbors)\\end{tabular}}\n  & \\textbf{\\begin{tabular}[c]{@{}l@{}}Max \\\\ Depth\\end{tabular}}\n  & \\textbf{\\begin{tabular}[c]{@{}l@{}}Max \\\\ Features\\end{tabular}} \\\\ \n  \\toprule\n  Reactor Type & 4                 & 56        & 29           \\\\\n  Burnup       & 1                 & 77        & 29           \\\\\n  Enrichment   & 2                 & 45        & 29           \\\\\n  Cooling Time & 1                 & 73        & 29           \\\\ \\bottomrule\n  \\end{tabular}\n  \\caption[Optimized algorithm hyperparameters for the 29 nuclide training set]\n          {Optimized algorithm hyperparameters for the 29 nuclide mass training \n           set.}\n  \\label{tbl:exp1hypparam}\n\\end{table}\n\nAfter the algorithms are initialized, the training set iteratively undergoes\nerror injection according to the method in Section \\ref{sec:inforeduc1}. Next,\nthe (information reduced) data set is preprocessed by scaling and normalization\nbecause the nuclide concentrations vary by many orders of magnitude. After\nthis, the training data features have a zero mean and unit variance. The\ninitialized algorithm is then used to fit the training set and is then ready\nfor prediction of \"unseen\" test samples.\n\nIntroduced in Section \\ref{sec:testerr}, these algorithms provide predictions\nbased on the \\textit{k}-fold \\gls{CV} approach (not to be confused with the\n\\textit{k} in \\textit{k}-nearest neighbors). Tested were 5, 10, and 15 \\gls{CV}\nfolds and they all performed similarly because the training set is large.  The\nresults shown in Table \\ref{tbl:cvdiff} show the percent change in the accuracy\nscore or \\gls{MAE} relative to when $k=5$.  This means that the accuracy score\nis under $0.5\\%$ higher for reactor type predictions for both\n\\textit{k}-nearest neighbors and decision trees changing \\textit{k} folds from\n5 to 10 or 15.  And the \\gls{MAE}s are slightly lower (under $7\\%$ difference)\nwhen changing \\textit{k} folds to 10 or 15.  Given the close performance, the\nnumber of \\gls{CV} folds was chosen to be 5 based on computational expediency.\nThe \\texttt{KFold} cross-validator with observation shuffling (i.e., the data\nset was shuffled prior to splitting) in the scikit package carried out this\ntask for the regression prediction cases.  For reactor type classification, the\n\\texttt{StratifiedKFold} cross-validator was used since there is an imbalance\nof classes in the training database.  \n\n\\begin{table}\n  \\centering\n  \\begin{tabular}{@{}lllll@{}}\n    \\toprule\n      & \\multicolumn{2}{l}{\\textbf{\\begin{tabular}[c]{@{}l@{}}\\% Difference, \\\\\n                                   \\textit{k}=5 to \\textit{k}=10\\end{tabular}}}\n      & \\multicolumn{2}{l}{\\textbf{\\begin{tabular}[c]{@{}l@{}}\\% Difference, \\\\ \n                                   \\textit{k}=5 to \\textit{k}=15\\end{tabular}}} \\\\\n        \\toprule\n                           & kNN    & DTree  & kNN    & DTree  \\\\ \\midrule\n    Reactor Type           & 0.4    & 0.2    & 0.4    & 0.4    \\\\\n    Burnup                 & -4.0   & -2.1   & -5.2   & -2.6   \\\\\n    Enrichment             & -5.1   & -6.1   & -6.6   & -6.7   \\\\\n    Time Since Irradiation & -1.8   & -3.1   & -2.3   & -3.8   \\\\ \\bottomrule\n  \\end{tabular}\n  \\caption[Comparison of different \\acrshort{CV} implementation errors]\n          {Comparison of prediction errors between different \\textit{k}-fold \n           \\acrshort{CV} implementations.}\n  \\label{tbl:cvdiff}\n\\end{table}\n\nBecause the performance needs to be compared to the \\gls{MLL} predictions, the\nscikit method \\texttt{cross\\_val\\_predict} was used, as it returns the\npredictions of each \\gls{CV} fold as it becomes the test set. Thus, the entire\ntraining set becomes a test case at some point, and the predictions return\nequal the number of entries in the training set.\n\nThe scripts written to run the scikit-learn algorithms were deployed using\n\\gls{UW}-Madison's \\gls{CHTC} resources and the \\gls{UW} campus grid. \n\n\\subsection{Maximum Log-Likelihood Calculations}\n\nThe \\gls{MLL} calculation method is implemented in python using the SciPy\nstatistics toolkit and NumPy functionality \\cite{scipy, numpy}. In this method,\none test sample is removed from the training set at a time, and the\nlog-likelihood calculation in Equation \\ref{eq:loglike} is performed between\nthe test sample and all the rows of the training set.  The observation with the\nlargest log-likelihood is returned as the predicted labels. Just like with the\nscikit-learn algorithm-based predictions, the entire training set becomes a\ntest sample at some point, so the predictions returned equal the number of\nentries in the training set.\n\nA key difference in how the \\gls{MLL} method provides predictions is that it\nreturns all the labels together, so it is not doing any generalizing on the\ncontinuous variable labels (burnup, enrichment, and cooling time). It is\nanalogous to \\textit{k}-nearest neighbors where $k = 1$, because there is no\nmodel being created, it just matches upon the call for prediction. Because of\nthis, the \\gls{MLL} method performing well is highly dependent on the training\nset being sufficiently large. \n\nThe scripts written to run the \\gls{MLL} calculations were deployed using\n\\gls{UW}--Madison's \\gls{CHTC} resources, the \\gls{UW} campus grid, and the \n\\gls{OSG} \\cite{osg07, osg09}. \n", "meta": {"hexsha": "64f04247193641d20cff371d695e965218594bab", "size": 9924, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "document/chapters/exp1/statmodels.tex", "max_stars_repo_name": "opotowsky/dissertation", "max_stars_repo_head_hexsha": "b42f24d1cbe8f8c9af00e5ba5b7585da7331f36f", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "document/chapters/exp1/statmodels.tex", "max_issues_repo_name": "opotowsky/dissertation", "max_issues_repo_head_hexsha": "b42f24d1cbe8f8c9af00e5ba5b7585da7331f36f", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2019-08-22T21:32:31.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-23T14:41:46.000Z", "max_forks_repo_path": "document/chapters/exp1/statmodels.tex", "max_forks_repo_name": "opotowsky/dissertation", "max_forks_repo_head_hexsha": "b42f24d1cbe8f8c9af00e5ba5b7585da7331f36f", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.3863636364, "max_line_length": 82, "alphanum_fraction": 0.7146311971, "num_tokens": 2623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.33870492147506315}}
{"text": "\\chapter{Cross Validation}\n\\section{Motivation}\n\nGenerally people train a neural network with the training set and obtain the test  accuracy after each epoch. After the training is finished, the highest ever or the last test  accuracy is reported in the paper. However, in our opinion, this may be not only abusing and polluting the test set, but also not generalizable. \n\nA test set, as its name tells, should be concealed and be tested only after all the model structures are set up and the training algorithm is fixed. In this way, the test set is never touched by the reseachers and serves as independent and fair comparison target. \n\nHowever, this is not the case in the field of deep learning. What people are doing is  first choosing a model and training algorithm, then evaluate the accuracy with the test set. If the test accuracy is not satisfactory, they turn to  choose a new combination of model structures and training algorithm in order to achieve a higher test accuracy. By doing so, the test set is evaluated many times or maybe thousands of times.  The test set is thus touched by the reseachers  and doesn't serves as independent and fair comparison any more. Instead, we say the original test set becomes part of the validation set. Without a proper framework or mechanism, such scenarios will be ongoing and  independent and fair comparison target will be missing. Therefore we want to propose a universal framework to evaluate the performance of the neural networks given a dataset. \n\n\\section{Universal framework}\nThe framework takes as input the proposed neural network, training algorithm and dateset.\n\nSuppose we are given a specific dataset such as CIFAR-10 with 50000 training data and 10000 validation data. \nIn each round, we randomly choose 6000 balanced data from CIFAR-10 as the test set, namely 600 data for each label. The remaining data are used as the training set. Then we evaluate the test accuracy after finishing training the neural network. \nAfter ten rounds, we take the average of the test accuracies as the metric reported. \n\nThe algorithm is as below.\n%\\begin{breakablealgorithm}%[!htb]\n\\begin{algorithm}%[!htb]\n\t\\caption{Overlapping CV training algorithm}\n\\hspace*{\\algorithmicindent} \\textbf{Input} Dataset $D$, neural network $N$\n\t\\begin{algorithmic}\n\t\\For{$i = 1:10$}\n\t\t\\State 1. Randomly choose 10\\% balanced data from $D$ and denote it as $V$, the validation set. The remaining data are  denoted as $T$, the training set.\n\t\t\\State 2. Train $N$ with $T$ with the stopping criterion $S$ \n\t\t\\State 3. When the training is finished, evaluate $N$ with $V$ and denote the validation accuracy as $A_i$\n\t\\EndFor\n\t\\end{algorithmic}\n\\hspace*{\\algorithmicindent} \\textbf{Output} $A(D,N)=\\sum_i A_i /10$\n\\end{algorithm}\n\nThe  standard  cross validation algorithm is as below.\n\\begin{algorithm}%[!htb]\n\t\\caption{Standard CV training algorithm}\n\\hspace*{\\algorithmicindent} \\textbf{Input} Dataset $D$, neural network $N$\\\\\n\\hspace*{\\algorithmicindent} \\textbf{Data split}  Randomly divide the dataset $D$ into 10 folds with numbers 1,2,..,10\n\t\\begin{algorithmic}\n\t\\For{$i = 1:10$}\n\t\t\\State 1. Choose the $i$-th fold and denote it as $V$, the validation set. The remaining data are  denoted as $T$, the training set.\n\t\t\\State 2. Train $N$ with $T$ with the stopping criterion $S$ \n\t\t\\State 3. When the training is finished, evaluate $N$ with $V$ and denote the validation accuracy as $A_i$\n\t\\EndFor\n\t\\end{algorithmic}\n\\hspace*{\\algorithmicindent} \\textbf{Output} $A(D,N)=\\sum_i A_i /10$\n\\end{algorithm}\n\nThe  leave-one-fold  cross validation algorithm is as below.\n\\begin{algorithm}%[!htb]\n\t\\caption{Leave-one-fold CV training algorithm}\n\\hspace*{\\algorithmicindent} \\textbf{Input} Dataset $D$, neural network $N$\\\\\n\\hspace*{\\algorithmicindent} \\textbf{Data split}  Randomly divide the dataset $D$ into 10 folds with numbers 1,2,..,10. Fix the $10$-th fold as the test set and denote it as $T_2$.\n\t\\begin{algorithmic}\n\t\\For{$i = 1:9$}\n\t\t\\State 1. Choose the $i$-th fold and denote it as $V$, the validation set. The remaining data are  denoted as $T$, the training set.\n\t\t\\State 2. Train $N$ with $T$ with the stopping criterion $S$ \n\t\t\\State 3. When the training is finished, evaluate $N$ with $T_2$ and denote the test accuracy as $A_i$\n\t\\EndFor\n\t\\end{algorithmic}\n\\hspace*{\\algorithmicindent} \\textbf{Output} $A(D,N)=\\sum_i A_i /9$\n\\end{algorithm}\n\nThings to discuss:\n\n1. If we randomly choose 10\\% data and do it 10 times, this is technically not the cross validation. \n\nCross validation is when we randomly divide the data into 10 folds of equal sizes. Then in each round, we take one fold  sequentially as the validation set, and use the remaining data as the training set.\n\n2. Does the stopping criterion $S$ depend on $D$ and $N$? We want to use the automative learning rate scheduling algorithm, but it doesn't have a stopping criterion. Moreover, based on the result on DenseNet, SASA by Lian Zhang depends on the initial parameter tuning.\n\nTherefore we will take different dataset splitting, learning rate scheduling, best validation accuracy vs last epoch with various models on popular dataset for comparison.\n\n\n\n\\section{ResNet-18 on CIFAR-10}\nIn this section, we will use test network ResNet-18 on CIFAR-10. Since the traditional training include the validation set to choose the model, therefore we split the original 54000 training data as training set with 48000 data and validation set with 6000 data. There are also two ways to choose the model, namely choosing the model after the last epoch or choosing the model with the highest validation accuracy. \n\n\n\\subsection{Fixed epoch and manual decreasing learning rate}\nWe choose to use fixed epoch training, namely 120 epochs, with changing the learning rate manually, i.e., decrease by 10 for every 30 epochs. The initial learning rate is 0.1, the momentum is 0.9 and the weight-dacay is 0.0001. The batch size is 128.\n\nThe time cost is around 17000 seconds.\n\nIf we split the sets randomly for 10 times, the results are listed in the table.\n\\begin{table}[!htbp]\n\t\\centering\n\t\\caption{Accuracy of different sets for model of last epoch and the one with best validation accuracy }\n\t\\label{table:cv1}\n\t\\begin{tabular}{|c|c|c|c|c|c|c|c|c|}\n\t\t\\hline\n\t\t% after \\\\: \\hline or \\cline{col1-col2} \\cline{col3-col4} ...\n%\t\tIteration &  \\multicolumn{2}{{|c|}}{SGD}  &    \\multicolumn{2}{{|c|}}{l1-prox}    \\\\\\cline{2-5}\n%\t\t\nfold\t&\ttrain accu(best\t&\ttrain accu(last\t&\tval accu(best\t&\tval accu(last\t&\ttest accu(best \t&\ttest accu(last\t\\\\\n\t&\t val model)\t&\t epoch model)\t&\tval model)\t&\t epoch model)\t&\tval model)\t&\t epoch model)\t\\\\\\hline\n1\t&\t99.92\t&\t99.91\t&\t93.13\t&\t92.48\t&\t93.40\t&\t93.20\t\\\\\\hline\n2\t&\t99.92\t&\t99.90\t&\t93.05\t&\t92.77\t&\t92.52\t&\t92.62\t\\\\\\hline\n3\t&\t99.93\t&\t99.89\t&\t93.17\t&\t92.58\t&\t93.35\t&\t93.12\t\\\\\\hline\n4\t&\t99.91\t&\t99.90\t&\t92.97\t&\t92.40\t&\t92.33\t&\t92.42\t\\\\\\hline\n5\t&\t99.91\t&\t99.91\t&\t93.30\t&\t93.05\t&\t92.63\t&\t92.70\t\\\\\\hline\n6\t&\t99.91\t&\t99.90\t&\t93.50\t&\t93.47\t&\t93.12\t&\t92.77\t\\\\\\hline\n7\t&\t99.92\t&\t99.88\t&\t93.32\t&\t93.00\t&\t93.47\t&\t93.12\t\\\\\\hline\n8\t&\t99.92\t&\t99.88\t&\t93.35\t&\t92.80\t&\t93.40\t&\t93.23\t\\\\\\hline\n9\t&\t99.90\t&\t99.87\t&\t93.78\t&\t93.45\t&\t92.53\t&\t92.17\t\\\\\\hline\n10\t&\t99.92\t&\t99.90\t&\t93.53\t&\t93.20\t&\t92.05\t&\t92.02\t\\\\\\hline\navg\t&\t99.92\t&\t99.89\t&\t93.31\t&\t92.92\t&\t92.88\t&\t92.74\t\\\\\\hline\n\t\\end{tabular}\n\\end{table}\n\n\nIf we split the sets into 10 folds and do the standard cross-validation, the results are listed in the table.\n\\begin{table}[!htbp]\n\t\\centering\n\t\\caption{Accuracy of different sets for model of last epoch and the one with best validation accuracy }\n\t\\label{table:cv2}\n\t\\begin{tabular}{|c|c|c|c|c|c|c|c|c|}\n\t\t\\hline\n\t\t% after \\\\: \\hline or \\cline{col1-col2} \\cline{col3-col4} ...\n%\t\tIteration &  \\multicolumn{2}{{|c|}}{SGD}  &    \\multicolumn{2}{{|c|}}{l1-prox}    \\\\\\cline{2-5}\n%\t\t\nfold\t&\ttrain accu(best\t&\ttrain accu(last\t&\tval accu(best\t&\tval accu(last\t&\ttest accu(best \t&\ttest accu(last\t\\\\\n\t&\t val model)\t&\t epoch model)\t&\tval model)\t&\t epoch model)\t&\tval model)\t&\t epoch model)\t\\\\\\hline\n1\t&\t99.93\t&\t99.92\t&\t94.00\t&\t93.52\t&\t93.07\t&\t93.43\t\\\\\\hline\n2\t&\t99.94\t&\t99.88\t&\t93.83\t&\t93.53\t&\t93.12\t&\t93.07\t\\\\\\hline\n3\t&\t99.91\t&\t99.90\t&\t93.23\t&\t92.92\t&\t93.42\t&\t93.32\t\\\\\\hline\n4\t&\t99.92\t&\t99.90\t&\t93.40\t&\t93.05\t&\t93.45\t&\t93.22\t\\\\\\hline\n5\t&\t99.91\t&\t99.89\t&\t93.42\t&\t92.93\t&\t92.65\t&\t92.67\t\\\\\\hline\n6\t&\t99.94\t&\t99.88\t&\t93.33\t&\t92.82\t&\t93.22\t&\t92.87\t\\\\\\hline\n7\t&\t99.92\t&\t99.90\t&\t93.55\t&\t93.17\t&\t93.17\t&\t93.40\t\\\\\\hline\n8\t&\t99.88\t&\t99.85\t&\t92.72\t&\t92.35\t&\t92.97\t&\t92.35\t\\\\\\hline\n9\t&\t99.90\t&\t99.86\t&\t93.22\t&\t92.65\t&\t92.40\t&\t92.27\t\\\\\\hline\n10\t&\t99.90\t&\t99.88\t&\t93.55\t&\t92.82\t&\t92.73\t&\t92.97\t\\\\\\hline\navg\t&\t99.92\t&\t99.89\t&\t93.43\t&\t92.98\t&\t93.02\t&\t92.96\t\\\\\\hline\n\t\\end{tabular}\n\\end{table}\n\nIf we split the sets into 10 folds, fix the first fold as the test set, take one fold as the validation set and the remaining as the training set, the results are listed in the table.\n\\begin{table}[!htbp]\n\t\\centering\n\t\\caption{Accuracy of different sets for model of last epoch and the one with best validation accuracy }\n\t\\label{table:cv1}\n\t\\begin{tabular}{|c|c|c|c|c|c|c|c|c|}\n\t\t\\hline\n\t\t% after \\\\: \\hline or \\cline{col1-col2} \\cline{col3-col4} ...\n%\t\tIteration &  \\multicolumn{2}{{|c|}}{SGD}  &    \\multicolumn{2}{{|c|}}{l1-prox}    \\\\\\cline{2-5}\n%\t\t\nfold\t&\ttrain accu(best\t&\ttrain accu(last\t&\tval accu(best\t&\tval accu(last\t&\ttest accu(best \t&\ttest accu(last\t\\\\\n\t&\t val model)\t&\t epoch model)\t&\tval model)\t&\t epoch model)\t&\tval model)\t&\t epoch model)\t\\\\\\hline\n1\t&\t99.93\t&\t99.93\t&\t93.58\t&\t93.13\t&\t92.55\t&\t92.65\t\\\\\\hline\n2\t&\t99.94\t&\t99.89\t&\t93.57\t&\t92.98\t&\t92.93\t&\t92.78\t\\\\\\hline\n3\t&\t99.93\t&\t99.89\t&\t93.48\t&\t93.03\t&\t92.85\t&\t93.20\t\\\\\\hline\n4\t&\t99.95\t&\t99.92\t&\t93.28\t&\t92.95\t&\t93.03\t&\t93.18\t\\\\\\hline\n5\t&\t99.92\t&\t99.90\t&\t93.12\t&\t92.75\t&\t92.92\t&\t92.50\t\\\\\\hline\n6\t&\t99.94\t&\t99.93\t&\t93.52\t&\t92.93\t&\t92.92\t&\t93.43\t\\\\\\hline\n7\t&\t99.93\t&\t99.92\t&\t93.40\t&\t93.10\t&\t93.00\t&\t93.15\t\\\\\\hline\n8\t&\t99.93\t&\t99.90\t&\t92.77\t&\t92.18\t&\t92.58\t&\t93.02\t\\\\\\hline\n9\t&\t99.93\t&\t99.90\t&\t92.80\t&\t92.22\t&\t92.52\t&\t92.37\t\\\\\\hline\navg\t&\t99.93\t&\t99.91\t&\t93.28\t&\t92.81\t&\t92.81\t&\t92.92\t\\\\\\hline\n\t\\end{tabular}\n\\end{table}\n\n\n\\newpage\n\\section{VGG-16 on CIFAR-10}\nIn this section, we will use test network VGG-16 on CIFAR-10. Since the traditional training include the validation set to choose the model, therefore we split the original 54000 training data as training set with 48000 data and validation set with 6000 data. There are also two ways to choose the model, namely choosing the model after the last epoch or choosing the model with the highest validation accuracy. \n\n\n\\subsection{Fixed epoch and manual decreasing learning rate}\nWe choose to use fixed epoch training, namely 160 epochs.\nThe initial learning rate is set to 0.1, and is divided by 10 at 50\\% and 75\\% of the total number of training epochs.\nThe momentum is 0.9 and the weight-dacay is 0.0001. The batch size is 128.\n\nThe time cost is around 22000 seconds.\n\nIf we split the sets randomly for 10 times, the results are listed in the table.\n\\begin{table}[!htbp]\n\t\\centering\n\t\\caption{Accuracy of different sets for model of  last epoch and the one with best validation accuracy }\n\t\\label{table:cv3}\n\t\\begin{tabular}{|c|c|c|c|c|c|c|c|c|}\n\t\t\\hline\n\t\t% after \\\\: \\hline or \\cline{col1-col2} \\cline{col3-col4} ...\n%\t\tIteration &  \\multicolumn{2}{{|c|}}{SGD}  &    \\multicolumn{2}{{|c|}}{l1-prox}    \\\\\\cline{2-5}\n%\t\t\nfold\t&\ttrain accu(best\t&\ttrain accu(last\t&\tval accu(best\t&\tval accu(last\t&\ttest accu(best \t&\ttest accu(last\t\\\\\n\t&\t val model)\t&\t epoch model)\t&\tval model)\t&\t epoch model)\t&\tval model)\t&\t epoch model)\t\\\\\\hline\n1\t&\t99.97\t&\t99.97\t&\t93.12\t&\t92.77\t&\t93.28\t&\t92.65\t\\\\\\hline\n2\t&\t99.97\t&\t99.96\t&\t92.85\t&\t92.65\t&\t92.92\t&\t93.18\t\\\\\\hline\n3\t&\t99.99\t&\t99.96\t&\t93.12\t&\t92.48\t&\t92.78\t&\t92.90\t\\\\\\hline\n4\t&\t99.97\t&\t99.95\t&\t92.98\t&\t92.72\t&\t92.07\t&\t92.40\t\\\\\\hline\n5\t&\t99.97\t&\t99.95\t&\t93.38\t&\t93.08\t&\t92.37\t&\t92.40\t\\\\\\hline\n6\t&\t99.97\t&\t99.95\t&\t93.10\t&\t92.80\t&\t92.35\t&\t92.57\t\\\\\\hline\n7\t&\t99.98\t&\t99.97\t&\t93.05\t&\t92.65\t&\t92.90\t&\t93.20\t\\\\\\hline\n8\t&\t99.97\t&\t99.97\t&\t93.03\t&\t92.72\t&\t93.07\t&\t92.82\t\\\\\\hline\n9\t&\t99.97\t&\t99.96\t&\t93.50\t&\t93.07\t&\t92.37\t&\t92.60\t\\\\\\hline\n10\t&\t99.98\t&\t99.96\t&\t93.43\t&\t93.18\t&\t92.20\t&\t92.57\t\\\\\\hline\navg\t&\t99.97\t&\t99.96\t&\t93.16\t&\t92.81\t&\t92.63\t&\t92.73\t\\\\\\hline\n\t\\end{tabular}\n\\end{table}\n\n\nIf we split the sets into 10 folds and do the standard cross-validation, the results are listed in the table.\n\\begin{table}[!htbp]\n\t\\centering\n\t\\caption{Accuracy of different sets for model of  last epoch and the one with best validation accuracy }\n\t\\label{table:cv4}\n\t\\begin{tabular}{|c|c|c|c|c|c|c|c|c|}\n\t\t\\hline\n\t\t% after \\\\: \\hline or \\cline{col1-col2} \\cline{col3-col4} ...\n%\t\tIteration &  \\multicolumn{2}{{|c|}}{SGD}  &    \\multicolumn{2}{{|c|}}{l1-prox}    \\\\\\cline{2-5}\n%\t\t\nfold\t&\ttrain accu(best\t&\ttrain accu(last\t&\tval accu(best\t&\tval accu(last\t&\ttest accu(best \t&\ttest accu(last\t\\\\\n\t&\t val model)\t&\t epoch model)\t&\tval model)\t&\t epoch model)\t&\tval model)\t&\t epoch model)\t\\\\\\hline\n1\t&\t99.98\t&\t99.96\t&\t93.45\t&\t92.92\t&\t92.68\t&\t92.92\t\\\\\\hline\n2\t&\t99.97\t&\t99.95\t&\t93.47\t&\t93.25\t&\t92.75\t&\t92.98\t\\\\\\hline\n3\t&\t99.97\t&\t99.97\t&\t93.08\t&\t92.55\t&\t92.65\t&\t93.38\t\\\\\\hline\n4\t&\t99.97\t&\t99.96\t&\t93.27\t&\t92.97\t&\t92.67\t&\t92.80\t\\\\\\hline\n5\t&\t99.97\t&\t99.95\t&\t92.92\t&\t92.42\t&\t92.53\t&\t92.40\t\\\\\\hline\n6\t&\t99.98\t&\t99.98\t&\t92.87\t&\t92.42\t&\t92.87\t&\t93.08\t\\\\\\hline\n7\t&\t99.97\t&\t99.96\t&\t93.28\t&\t93.13\t&\t93.07\t&\t93.22\t\\\\\\hline\n8\t&\t99.98\t&\t99.96\t&\t93.10\t&\t92.72\t&\t92.90\t&\t93.15\t\\\\\\hline\n9\t&\t99.97\t&\t99.96\t&\t93.38\t&\t93.02\t&\t92.48\t&\t92.83\t\\\\\\hline\n10\t&\t99.98\t&\t99.97\t&\t93.22\t&\t92.92\t&\t92.57\t&\t92.52\t\\\\\\hline\navg\t&\t99.97\t&\t99.96\t&\t93.20\t&\t92.83\t&\t92.72\t&\t92.93\t\\\\\\hline\t\\end{tabular}\n\\end{table}\n\nIf we split the sets into 10 folds, fix the first fold as the test set, take one fold as the validation set and the remaining as the training set, the results are listed in the table.\n\\begin{table}[!htbp]\n\t\\centering\n\t\\caption{Accuracy of different sets for model of last epoch and the one with best validation accuracy }\n\t\\label{table:cv1}\n\t\\begin{tabular}{|c|c|c|c|c|c|c|c|c|}\n\t\t\\hline\n\t\t% after \\\\: \\hline or \\cline{col1-col2} \\cline{col3-col4} ...\n%\t\tIteration &  \\multicolumn{2}{{|c|}}{SGD}  &    \\multicolumn{2}{{|c|}}{l1-prox}    \\\\\\cline{2-5}\n%\t\t\nfold\t&\ttrain accu(best\t&\ttrain accu(last\t&\tval accu(best\t&\tval accu(last\t&\ttest accu(best \t&\ttest accu(last\t\\\\\n\t&\t val model)\t&\t epoch model)\t&\tval model)\t&\t epoch model)\t&\tval model)\t&\t epoch model)\t\\\\\\hline\n1\t&\t99.98\t&\t99.98\t&\t93.40\t&\t93.40\t&\t93.13\t&\t93.10\t\\\\\\hline\n2\t&\t99.98\t&\t99.97\t&\t93.37\t&\t93.23\t&\t93.00\t&\t93.05\t\\\\\\hline\n3\t&\t99.98\t&\t99.97\t&\t93.47\t&\t92.85\t&\t92.67\t&\t93.25\t\\\\\\hline\n4\t&\t99.98\t&\t99.96\t&\t93.02\t&\t92.45\t&\t93.20\t&\t92.73\t\\\\\\hline\n5\t&\t99.98\t&\t99.95\t&\t93.57\t&\t93.18\t&\t92.70\t&\t93.00\t\\\\\\hline\n6\t&\t99.98\t&\t99.97\t&\t93.43\t&\t92.77\t&\t92.80\t&\t92.65\t\\\\\\hline\n7\t&\t99.97\t&\t99.96\t&\t93.18\t&\t92.78\t&\t92.95\t&\t92.55\t\\\\\\hline\n8\t&\t99.98\t&\t99.97\t&\t92.72\t&\t92.18\t&\t93.17\t&\t92.90\t\\\\\\hline\n9\t&\t99.97\t&\t99.96\t&\t93.47\t&\t92.95\t&\t92.72\t&\t92.63\t\\\\\\hline\navg\t&\t99.98\t&\t99.97\t&\t93.29\t&\t92.87\t&\t92.93\t&\t92.87\t\\\\\\hline\n\t\\end{tabular}\n\\end{table}\n\n\\newpage\n\\section{VGG-19 on CIFAR-10}\nIn this section, we will use test network VGG-16 on CIFAR-10. Since the traditional training include the validation set to choose the model, therefore we split the original 54000 training data as training set with 48000 data and validation set with 6000 data. There are also two ways to choose the model, namely choosing the model after the last epoch or choosing the model with the highest validation accuracy. \n\n\n\\subsection{Fixed epoch and manual decreasing learning rate}\nWe choose to use fixed epoch training, namely 160 epochs.\nThe initial learning rate is set to 0.1, and is divided by 10 at 50\\% and 75\\% of the total number of training epochs.\nThe momentum is 0.9 and the weight-dacay is 0.0001. The batch size is 128.\n\nThe time cost is around 27000 seconds.\n\nIf we split the sets randomly for 10 times, the results are listed in the table.\n\\begin{table}[!htbp]\n\t\\centering\n\t\\caption{Accuracy of different sets for model of  last epoch and the one with best validation accuracy }\n\t\\label{table:cv3}\n\t\\begin{tabular}{|c|c|c|c|c|c|c|c|c|}\n\t\t\\hline\n\t\t% after \\\\: \\hline or \\cline{col1-col2} \\cline{col3-col4} ...\n%\t\tIteration &  \\multicolumn{2}{{|c|}}{SGD}  &    \\multicolumn{2}{{|c|}}{l1-prox}    \\\\\\cline{2-5}\n%\t\t\nfold\t&\ttrain accu(best\t&\ttrain accu(last\t&\tval accu(best\t&\tval accu(last\t&\ttest accu(best \t&\ttest accu(last\t\\\\\n\t&\t val model)\t&\t epoch model)\t&\tval model)\t&\t epoch model)\t&\tval model)\t&\t epoch model)\t\\\\\\hline\n1\t&\t99.98\t&\t99.97\t&\t93.15\t&\t92.65\t&\t92.82\t&\t92.85\t\\\\\\hline\n2\t&\t99.98\t&\t99.97\t&\t93.38\t&\t92.78\t&\t92.35\t&\t92.85\t\\\\\\hline\n3\t&\t99.98\t&\t99.97\t&\t92.73\t&\t92.33\t&\t92.27\t&\t92.05\t\\\\\\hline\n4\t&\t99.97\t&\t99.96\t&\t92.73\t&\t92.40\t&\t92.22\t&\t92.82\t\\\\\\hline\n5\t&\t99.98\t&\t99.96\t&\t93.18\t&\t92.85\t&\t92.13\t&\t92.13\t\\\\\\hline\n6\t&\t99.99\t&\t99.99\t&\t92.82\t&\t92.45\t&\t92.30\t&\t91.90\t\\\\\\hline\n7\t&\t99.97\t&\t99.97\t&\t92.75\t&\t92.23\t&\t92.68\t&\t92.52\t\\\\\\hline\n8\t&\t99.98\t&\t99.96\t&\t92.70\t&\t92.62\t&\t93.02\t&\t92.92\t\\\\\\hline\n9\t&\t99.98\t&\t99.97\t&\t93.45\t&\t93.15\t&\t92.12\t&\t92.13\t\\\\\\hline\n10\t&\t99.98\t&\t99.97\t&\t93.18\t&\t92.83\t&\t91.93\t&\t91.82\t\\\\\\hline\navg\t&\t99.98\t&\t99.97\t&\t93.01\t&\t92.63\t&\t92.38\t&\t92.40\t\\\\\\hline\n\t\\end{tabular}\n\\end{table}\n\n\nIf we split the sets into 10 folds and do the standard cross-validation, the results are listed in the table.\n\n\\begin{table}[!htbp]\n\t\\centering\n\t\\caption{Accuracy of different sets for model of  last epoch and the one with best validation accuracy }\n\t\\label{table:cv3}\n\t\\begin{tabular}{|c|c|c|c|c|c|c|c|c|}\n\t\t\\hline\n\t\t% after \\\\: \\hline or \\cline{col1-col2} \\cline{col3-col4} ...\n%\t\tIteration &  \\multicolumn{2}{{|c|}}{SGD}  &    \\multicolumn{2}{{|c|}}{l1-prox}    \\\\\\cline{2-5}\n%\t\t\nfold\t&\ttrain accu(best\t&\ttrain accu(last\t&\tval accu(best\t&\tval accu(last\t&\ttest accu(best \t&\ttest accu(last\t\\\\\n\t&\t val model)\t&\t epoch model)\t&\tval model)\t&\t epoch model)\t&\tval model)\t&\t epoch model)\t\\\\\\hline\n1\t&\t99.98\t&\t99.98\t&\t93.38\t&\t92.75\t&\t92.70\t&\t92.78\t\\\\\\hline\n2\t&\t99.97\t&\t99.97\t&\t93.43\t&\t93.07\t&\t93.05\t&\t92.87\t\\\\\\hline\n3\t&\t99.98\t&\t99.96\t&\t93.27\t&\t93.08\t&\t93.03\t&\t92.70\t\\\\\\hline\n4\t&\t99.99\t&\t99.99\t&\t92.75\t&\t92.27\t&\t92.82\t&\t92.43\t\\\\\\hline\n5\t&\t99.98\t&\t99.98\t&\t92.93\t&\t92.53\t&\t91.67\t&\t92.08\t\\\\\\hline\n6\t&\t99.98\t&\t99.97\t&\t92.92\t&\t92.50\t&\t93.25\t&\t93.05\t\\\\\\hline\n7\t&\t99.98\t&\t99.97\t&\t93.00\t&\t92.65\t&\t92.55\t&\t92.30\t\\\\\\hline\n8\t&\t99.98\t&\t99.96\t&\t92.70\t&\t92.42\t&\t92.82\t&\t92.72\t\\\\\\hline\n9\t&\t99.98\t&\t99.98\t&\t93.22\t&\t93.05\t&\t92.48\t&\t92.70\t\\\\\\hline\n10\t&\t99.97\t&\t99.95\t&\t93.13\t&\t92.42\t&\t92.80\t&\t93.00\t\\\\\\hline\navg\t&\t99.98\t&\t99.97\t&\t93.07\t&\t92.67\t&\t92.72\t&\t92.66\t\\\\\\hline\n\t\\end{tabular}\n\\end{table}\n\n\nIf we split the sets into 10 folds, fix the first fold as the test set, take one fold as the validation set and the remaining as the training set, the results are listed in the table.\n\\begin{table}[!htbp]\n\t\\centering\n\t\\caption{Accuracy of different sets for model of last epoch and the one with best validation accuracy }\n\t\\label{table:cv1}\n\t\\begin{tabular}{|c|c|c|c|c|c|c|c|c|}\n\t\t\\hline\n\t\t% after \\\\: \\hline or \\cline{col1-col2} \\cline{col3-col4} ...\n%\t\tIteration &  \\multicolumn{2}{{|c|}}{SGD}  &    \\multicolumn{2}{{|c|}}{l1-prox}    \\\\\\cline{2-5}\n%\t\t\nfold\t&\ttrain accu(best\t&\ttrain accu(last\t&\tval accu(best\t&\tval accu(last\t&\ttest accu(best \t&\ttest accu(last\t\\\\\n\t&\t val model)\t&\t epoch model)\t&\tval model)\t&\t epoch model)\t&\tval model)\t&\t epoch model)\t\\\\\\hline\n1\t&\t99.98\t&\t99.98\t&\t93.37\t&\t92.87\t&\t92.42\t&\t92.88\t\\\\\\hline\n2\t&\t99.99\t&\t99.98\t&\t92.97\t&\t92.47\t&\t93.27\t&\t92.95\t\\\\\\hline\n3\t&\t99.98\t&\t99.97\t&\t93.27\t&\t92.75\t&\t92.60\t&\t93.02\t\\\\\\hline\n4\t&\t99.98\t&\t99.97\t&\t93.05\t&\t92.55\t&\t92.88\t&\t92.65\t\\\\\\hline\n5\t&\t99.99\t&\t99.97\t&\t93.63\t&\t92.85\t&\t92.70\t&\t92.87\t\\\\\\hline\n6\t&\t99.98\t&\t99.95\t&\t92.87\t&\t92.40\t&\t91.85\t&\t92.82\t\\\\\\hline\n7\t&\t99.98\t&\t99.97\t&\t93.32\t&\t92.77\t&\t92.93\t&\t93.07\t\\\\\\hline\n8\t&\t99.98\t&\t99.98\t&\t92.70\t&\t92.70\t&\t92.93\t&\t93.23\t\\\\\\hline\n9\t&\t99.99\t&\t99.99\t&\t93.07\t&\t92.82\t&\t92.70\t&\t92.17\t\\\\\\hline\navg\t&\t99.98\t&\t99.97\t&\t93.14\t&\t92.69\t&\t92.70\t&\t92.85\t\\\\\\hline\n\t\\end{tabular}\n\\end{table}\n\n\\newpage\n\\section{Discussion}\nWe find the test accuracy of the random splitting cross validation is consistently lower than that of the other two methods. This may happen due to the existence of the outliers.\n\n\\subsection{Outliers}\nThere can be some problems about the data labels.\n\n\\begin{enumerate}\n\\item Images with wrong labels: the label is wrong or there is a better label than given.\n\\item Multi-label images: There should be multiple labels to a image since it contains multiple objects. \n\\item Ontological issues: the class maillot appears twice, the existence of is-a relationships like bathtub is a tub, misnomers like projectile and missile, and unanticipated issues caused by words with multiple definitions like corn and ear. \n\\end{enumerate}\n\n\\subsection{Distribution}\nFor simplicity, we assume there are $N_0$ outliers out of 60000 over all images in CIFAR-10 dataset. Suppose we do a $k$-fold cross validation for the overlapping and standard one, we want to compared the total number of outliers in all the test folds, $X$. \n\nAs for the standard $k$-fold cross validation, since there are no overlapping among the test folds, each outlier will appear in a test fold once and only once. Therefore the total number of outliers in all the test folds is $N_0$.\n\nAs for the overlapping $k$-fold cross validation, things are little bit different. We state the procedure here to better understand the underlying distribution.\n\\begin{enumerate}\n\\item We choose $\\frac{60000}{k}$ balanced data from the dataset as the test set. Here we assume the distribution of outliers in different classes is uniform. Then this is a drawing of $N=\\frac{60000}{k}$ data without replacement. For each drawing, the probability of obtaining an  outlier is a constant $p=\\frac{N_0}{60000}$. Therefore the number of outliers in this test fold follows a binomial distribution $B_1(N,p)$. The mean is $\\mu=N*p=\\frac{N_0}{k}$ and the variance is $$\\sigma=N*p*(1-p)=\\frac{N_0*(60000-N_0)}{60000*k}.$$\n\\item Then we repeat the first step for k times. Since the setup is the same, we have the same binomial distributions $B_i(N,p), i=1,2,3,..,k$. By the property of binomials, $$X \\sim \\sum_{i=1}^{k}B_i(N,p)=B(N*k,p)=B(60000,\\frac{N_0}{60000}).$$ The mean is $\\mu=N*k*p=N_0$ and the variance is $$\\sigma=N*k*p*(1-p)=\\frac{N_0*(60000-N_0)}{60000}.$$\n\\end{enumerate}\n\nFrom the analysis, we can see the mean is also  $N_0$, but there is a large variance $\\frac{N_0*(60000-N_0)}{60000}$. It means in each experiment of the overlapping $k$-fold cross validation, the total number of outliers in all the test folds can be quite different. We may have encountered a bad case where $X$ is larger than $N_0$ such that the test accuracy is consistently lower than that of the other two methods. It contradicts to our original goal to use statistical methods to reduce randomness and improve the repeatability and substantivity. Therefore we would suggest to use the second and third method for better evaluation.\n\n\n\n\\section{Conclusion}\nBased on our numerical result, we can conclude the following things as for the framework and for the traditional training algorithms.\n\n\\begin{enumerate}\n\\item People use the test set multiple times. The best they can do is to run the same setup of the experiment multiple times to ensure the robustness and repeatability. With our cross-validation framework, we can fairly compare the performance of the proposed model and training algorithms.\n\\item As for the first two kinds of data splitting, the regular cross validation taking validation set and test set sequentially achieved better accuracy for all the experiments. We also prefer this way since we don't need to consider the problem of repeated data in different folds for the cross validation taking random validation set and test set. \n\\item As for the last two kinds of data splitting, the regular cross validation taking validation set and test set sequentially achieved comparable  accuracy with the leave-one-fold cross validation. It suggests that when the test data is already given, there is not much difference about the data splitting and model selection. \n\\item In the overlapping $k$-fold cross validation, the total number of outliers in all the test folds follows a binomial distribution and can be quite different. Therefore we don't want to use this method for evaluation.\n\\item The average test accuracy is comparable as for taking the model with best validation accuracy or the final model after training. This coincides with our observation that these two ways don't make a difference. It also explains why both ways exist when researchers are reporting their results. \n\\end{enumerate}\n\n\n\n", "meta": {"hexsha": "adf3af40fe4f43a76db29177b9a1f659ba966944", "size": 24553, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "6DL/crossvalidation.tex", "max_stars_repo_name": "liuzhengqi1996/math452", "max_stars_repo_head_hexsha": "635b6ce53cb792e316abf4f47396f2e4f0686815", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "6DL/crossvalidation.tex", "max_issues_repo_name": "liuzhengqi1996/math452", "max_issues_repo_head_hexsha": "635b6ce53cb792e316abf4f47396f2e4f0686815", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "6DL/crossvalidation.tex", "max_forks_repo_name": "liuzhengqi1996/math452", "max_forks_repo_head_hexsha": "635b6ce53cb792e316abf4f47396f2e4f0686815", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 63.9401041667, "max_line_length": 866, "alphanum_fraction": 0.6833788132, "num_tokens": 9576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.33867190369842193}}
{"text": "\\chapter{Fixed Parameters}\n\\label{appendix:fixed_parameters}\n\n\\begin{itemize}\n\\item \\textbf{Tournament size}: 4\n\\item \\textbf{Population size}: 100\n\\item \\textbf{Number of Generations}: 250\n\\item \\textbf{Maximum Program Tree Depth}: 17\n\\item \\textbf{Function set}: $\\{ +, -, *, /, \\log, \\exp, \\sin, \\cos, -x \\}$\n\\item \\textbf{Terminal set}: Only the features in the data set.\n\\end{itemize}", "meta": {"hexsha": "b851857d2c1bc3b4686cb90f06cedf14b1f6073c", "size": 389, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/thesis/fixed_parameters.tex", "max_stars_repo_name": "flexgp/BehavioralGP", "max_stars_repo_head_hexsha": "14cdb7dc2c1343a6405289ca2b046f01b4746d9b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/thesis/fixed_parameters.tex", "max_issues_repo_name": "flexgp/BehavioralGP", "max_issues_repo_head_hexsha": "14cdb7dc2c1343a6405289ca2b046f01b4746d9b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/thesis/fixed_parameters.tex", "max_forks_repo_name": "flexgp/BehavioralGP", "max_forks_repo_head_hexsha": "14cdb7dc2c1343a6405289ca2b046f01b4746d9b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3636363636, "max_line_length": 75, "alphanum_fraction": 0.7043701799, "num_tokens": 130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3386206242076053}}
{"text": "\\section{Kinky string decay simulation.}\n\n\\hspace{1.0em}\nFor kinky string decay simulation we have assumed the two steps process:\n\\begin{enumerate}\n\\item split gluon $g\\rightarrow q_1 \\bar{q}_1$ and create two longitudinal \nstrings;\n\\item decay longitudunal strings $q\\bar{q}_1 \\rightarrow h$ and\n $\\bar{q}q_1 \\rightarrow h$ into hadrons $h$.\n\\end{enumerate}\nThe production of $q_1\\bar{q}_1$ is considered similar (the same sampling of \nquark flavors and the same $p_t$-distribution for the quarks) as a production \nof $q\\bar{q}$-pairs during the longitudinal string decay. \nWe took the $g\\rightarrow q_1\\bar{q}_1$ splitting function \\cite{APKW80}:\n\\begin{equation}\n\\label{KSD1}f^{q}_{g}(z)=z^2+(1-z)^2,\n\\end{equation}\nwhere $z=\\frac{E_q+p^z_q}{E_g+p^z_g}$, derived by Altarelli and \nParisi \\cite{AP77}. \n", "meta": {"hexsha": "7c16b4ecd4b6d6bad95d34412bcba0cae72372cc", "size": 805, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "geant4/hadronic/theory_driven/PartonString/KinkyStringDecay.tex", "max_stars_repo_name": "berghaus/cernlib-docs", "max_stars_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-24T12:30:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-24T12:30:01.000Z", "max_issues_repo_path": "geant4/hadronic/theory_driven/PartonString/KinkyStringDecay.tex", "max_issues_repo_name": "berghaus/cernlib-docs", "max_issues_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geant4/hadronic/theory_driven/PartonString/KinkyStringDecay.tex", "max_forks_repo_name": "berghaus/cernlib-docs", "max_forks_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.25, "max_line_length": 78, "alphanum_fraction": 0.7416149068, "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.33850246138891843}}
{"text": "\\subsubsection{\\stid{3.06} PETSc-TAO} \\label{subsubsect:petsc}\r\n\\paragraph{Overview} \r\n\r\nAlgebraic solvers (generally nonlinear solvers that use sparse linear solvers via Newton's method) and ODE/DAE \r\nintegrators form the core computation of many numerical simulations. No scalable ``black box'' sparse solvers \r\nor integrators work for all applications, nor single implementations that work well for all scales of \r\nproblem size. Hence, algebraic solver packages provide a wide variety of algorithms and implementations \r\nthat can be customized for the application and range of problem sizes at hand. PETSc~\\cite{petsc:homepage,petsc-man} \r\nis a widely used software library for the scalable solution of linear, nonlinear, and ODE/DAE systems and \r\ncomputation of adjoints (sometimes called sensitivities) of ODE systems. We focus on three topics: (1) partially \r\nmatrix-free scalable solvers efficiently use many-core and GPU-based systems; (2) reduced synchronization \r\nalgorithms that can scale to larger concurrency than solvers with synchronization points; and (3) performance \r\nand data structure optimizations for all the core data structures to better utilize many-core and GPU-based \r\nsystems as well as provide scalability to the Exascale.\r\n\r\nThe availability of systems with over 100 times the processing power of today's machines compels the utilization \r\nof these systems not just for a single ``forward solve'' simulation (as discussed above) but rather within a \r\ntight loop of optimization, sensitivity analysis (SA), and uncertain quantification (UQ). This requires the \r\nimplementation of a new, scalable library for managing a dynamic hierarchical collection of running scalable \r\nsimulations, where the simulations directly feed results into the optimization, SA, and UQ solvers.  This library, \r\nwhich we call libEnsemble, directs the multiple concurrent ``function evaluations'' through the tight coupling \r\nand feedback described above. This work consist of two parts: (1) the development of libEnsemble and (2) the \r\ndevelopment of algorithms and software to utilize libEnsemble.\r\n\r\n\\paragraph{Key Challenges}\r\n\r\nA key challenge for for scaling the PETSc/TAO numerical libraries to Exascale systems is that \r\ntraditional ``sparse-matrix-based'' techniques for linear, nonlinear, and ODE solvers, as well \r\nas optimization algorithms, are memory-bandwidth limited.  Another difficulty is that any \r\nsynchronizations required across all compute units--for example, an inner product or a \r\nnorm--can dramatically affect the scaling of the solvers.\r\n\r\nRunning an ensemble of simulation requires a coordination layer that handles load balancing and\r\nallows the collection of running simulations to grow and shrink based on feedback. Thus, this \r\nlibrary must be able to dynamically start simulations with different parameters, resume \r\nsimulations to obtain more accurate results, prune running simulations that the solvers \r\ndetermine can no longer provide useful information, monitor the progress of the simulations, \r\nand stop failed or hung simulations, and collect data from the individual simulations both \r\nwhile they are running and at the end.\r\n\r\n\\paragraph{Solution Strategy}\r\n\r\nTo address the scalability of the numerical libraries, we are developing new solvers and data \r\nstructures including pipeline Krylov methods that delay the use of the results of inner products \r\nand norms, allowing overlapping of the reductions and other computation; partially matrix-free \r\nsolvers using high-order methods that have high floating-point-to-memory-access ratios and\r\ngood potential to use many-core and GPU-based systems; and in-node optimizations of sparse \r\nmatrix-matrix products needed by algebraic multigrid to better utilize many-core systems\r\nusing a thread neutral ``bypass MPI'' approach, which implements default interprocessor \r\ncommunication using MPI but bypasses the use of MPI in performance-critical regions \r\nfor higher performance and thereby maintains MPI portability.\r\n\r\nOur strategy for coordinating ensemble computations has been to develop libEnsemble\r\nto satisfy our needs.  This library should not be confused with workflow-based \r\nscripting systems; rather it is a library that, through the tight coupling and \r\nfeedback described above, directs the multiple concurrent ``function evaluations''\r\nneeded by optimization, SA, and UQ solvers.\r\n\r\n\\paragraph{Recent Progress}\r\n\r\nIn the past year, we have released PETSc/TAO 3.12 (available at \\url{http://www.mcs.anl.gov/petsc})\r\nthat features enhanced GPU support.  Perhaps the most important is the support for CUDA-aware \r\nMPI, which allows direct communication of data between Summit GPUs, bypassing the previously \r\nneeded step of first copying the data to the CPU memory. This enhancement reduces the latency \r\nof the communication and improves bandwidth. For example, on Summit for sparse matrix-vector \r\nproducts, this led to a speedup of 33\\% on one node and a speedup of 13\\% on on four nodes \r\nfor the same size problem. Another important addition is the ability to efficiently read \r\nin large meshes on thousands of nodes along with support for collect use of HDF5 calls. \r\nWith these additions, the algebraic multigrid solver GAMG is up to 12x faster at scale \r\non all of Summit when using the GPUs compared to using just the CPUs.\r\n\r\n\\begin{figure}\r\n\\centering\r\n\\includegraphics[width=0.5\\textwidth]{projects/2.3.3-MathLibs/2.3.3.06-PETSc-TAO/petsc_profile}\r\n\\caption{Profile information on the effect of vector size on vector operations compared with \r\nmemory throughput (one MPI rank per GPU) for PETSc/TAO 3.12. Note the log scale.}\r\n\\label{fig:petsc-tao-fig}\r\n\\end{figure}\r\n\r\nWe have also release libEnsemble 0.5.2 (available at \\url{https://github.com/Libensemble/libensemble}).\r\nNotably, this release includes several changes in progressing toward xSDK compliance had have added\r\nsupport for testing on MacOS to support more applications.  We also have improved I/O, logging, \r\nprofiling, as well as resource detection on Summit.\r\n\r\n\\paragraph{Next Steps}\r\n\r\nOur next efforts are:\r\n\\begin{enumerate}\r\n  \\item \\textbf{Enhanced application integration and performance optimization and benchmarking}:\r\n  Refresh the AMReX/PETSc interface and ensure that the PETSc linear solvers can be used with AMReX.\r\n  Consolidate the two MPI communication modules (VecScatter and PetscSF) to share the same code base \r\n  and implement two important communication optimizations in the unified code base: internode node-message \r\n  aggregation optimization, which is critical for scalability of GAMG, and intranode shared memory \r\n  optimization.  \r\n  Ensure that libEnsemble satisfies eight of the xSDK requirements.\r\n  Continue to produce benchmark results on Summit.\r\n  Engage with ECP applications and co-design centers to identify new capabilities that can result in \r\n  FY2021-2023 application integration activities.\r\n  \\item \\textbf{Harmonization, performance optimization, and software release}:\r\n  Harmonize the quasi-Newton and line search modules between SNES and TAO to improve maintainability.\r\n  Implement GPU optimizations of the quasi-Newton methods.\r\n  Ensure that libEnsemble satisfies all but one of the xSDK requirements.\r\n  Continue to produce benchmark results on Summit.\r\n  Continue to engage with ECP applications and co-design centers.\r\n  Release a new version of PETSc/TAO.\r\n  \\item \\textbf{Enhanced application support and software release}:\r\n  Implement and optimize the ability to use libCEED under PETSc.\r\n  Continue to produce benchmark results on Summit.\r\n  Continue to engage with ECP applications and co-design centers.\r\n  Release a new version of libEnsemble that is compatible with the xSDK community policy requirements and included in the xSDK.\r\n  \\item \\textbf{Benchmarking, performance optimization and software release}:\r\n  Demonstrate new libEnsemble functionality by having libEnsemble serve as the driver/outer process that \r\n  invokes another xSDK tool.\r\n  Complete benchmarking one or more of the PETSc based applications on Summit at scale including GAMG support \r\n  on the GPUs and identify performance bottlenecks.\r\n  Incorporate new desired capabilities resulting from our engagement with ECP applications and co-design centers into our FY2021 plans.\r\n  Release a new version of PETSc/TAO.\r\n\\end{enumerate}\r\n\r\n", "meta": {"hexsha": "0949fe7f487afff626f649e7b9f9361e2c95c00a", "size": 8362, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "projects/2.3.3-MathLibs/2.3.3.06-PETSc-TAO/2.3.3.06-PETSc-TAO.tex", "max_stars_repo_name": "mmwolf/ECP-ST-CAR-PUBLIC", "max_stars_repo_head_hexsha": "887cf30141c498bfc87631e038088b7b15df7cda", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "projects/2.3.3-MathLibs/2.3.3.06-PETSc-TAO/2.3.3.06-PETSc-TAO.tex", "max_issues_repo_name": "mmwolf/ECP-ST-CAR-PUBLIC", "max_issues_repo_head_hexsha": "887cf30141c498bfc87631e038088b7b15df7cda", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "projects/2.3.3-MathLibs/2.3.3.06-PETSc-TAO/2.3.3.06-PETSc-TAO.tex", "max_forks_repo_name": "mmwolf/ECP-ST-CAR-PUBLIC", "max_forks_repo_head_hexsha": "887cf30141c498bfc87631e038088b7b15df7cda", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 69.6833333333, "max_line_length": 136, "alphanum_fraction": 0.7983735948, "num_tokens": 1755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.33844141992180343}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n% \\section*{Thu Dec 19 2019}\n\n% The lessons on gravitational waves will be on the 8th and 9th of January, from 14:30 to 16:30, in rooms LUF2 and P2B respectively. \n\n\\subsection{The Chandrasekhar limit in more detail}\n\nWe want to derive the Chandrasekhar limit in a more precise manner. \n\n% The number density of electrions is given by \n% %\n% \\begin{align}\n% n_e = Y_{e} \\frac{\\rho_c}{m_H}\n% \\,,\n% \\end{align}\n% %\n% in the nonrelativistic case the pressure is given by \n% %\n% \\begin{align}\n% P_c = k _{\\text{NR}} n_e^{5/3} = k _{\\text{NR}} \\qty(\\frac{Y_e \\rho_{c}}{m_H})^{5/3}\n% \\,,\n% \\end{align}\n%\n% but we can also derive it by \n% %\n% \\begin{align}\n% P_c = k _{\\text{NR}} n_e^{5/3} = k _{\\text{NR}} \\qty(\\frac{Y_e \\rho_{c}}{m_H})^{5/3}\n% \\,,\n% \\end{align}\n% %\n% and equating these we find: \n%\n% \\begin{align}\n%  k _{\\text{NR}} \\qty(\\frac{Y_e \\rho_{c}}{m_H})^{5/3}\n%  = k _{\\text{NR}} n_e^{5/3} = k _{\\text{NR}} \\qty(\\frac{Y_e \\rho_{c}}{m_H})^{5/3}\n% \\,,\n% \\end{align}\n% %\n% which implies \n% %\n% \\begin{align}\n% \\rho_{c} = \\frac{3.1}{Y_e^{5}} \\qty(\\frac{M}{M_{*}})^2 \\frac{m_H}{(h / m_e c^2)^3}\n% \\,,\n% \\end{align}\n%\n% where \\(\\alpha_{G} = G m_H^2 / (\\hbar c) \\approx \\SI{5.9e-30}{}\\), while \n% %\n% \\begin{align}\n% m_{*} = \\alpha_{G}^{-3 /2 } m_H = 1.85 M_{\\odot}\n% \\,,\n% \\end{align}\n% %\n% while for the ultrarelativistic case we get \n% %\n% \\begin{align}\n% P_C = k _{\\text{UR}} n_e^{4/3} = k _{\\text{UR}} \\qty(\\frac{Y_e \\rho_{c} }{m_H})^{4/3}\n% \\,,\n% \\end{align}\n%\n% so in this particular case the density \\(\\rho_{c}\\) simplifies from the equations: we get a critical mass \n% %\n% \\begin{align}\n% M _{\\text{CHANDRA}} = \\qty(\\frac{36}{\\pi })^{1/2} \n% \\qty(\\frac{Y_e}{m_H})^2\n% \\qty(\\frac{k _{\\text{UR}}}{G})^{3/2} \\approx \n% 2.3 Y_e^2 m_{*} \\approx 4.3 Y_e^2 M_{\\odot}\n% \\,,\n% \\end{align}\n%\n% and we assume that we are in the fully degenerate case: in the integration over momenta of the phase space distribution we insert a cutoff at the Fermi energy.\n\n% We find: \nInstead of approximating the gas as either ultrarelativistic or nonrelativistic, we can use the correct expression for the particle energy in the integral for the momentum:\n%\n\\begin{align}\nP = \\frac{4 \\pi }{3 h^3} g_{*} \\int_{0}^{p_F} \\dd{p} p^2 \\frac{p^2 c^2}{\\epsilon_{p}}\n\\,,\n\\end{align}\n%\nwith \\(\\epsilon_{p} = \\qty(p^2c^2 + m^2c^{4})^{1/2}\\).\n\nWe change variables to the dimensionless \\(x = p / (m_e c)\\) and substitute \\(g_* = 2\\), since electrons have spin \\(1/2\\):\n%\n\\begin{align}\nP = \\frac{8 \\pi }{3 h^3} m_e^4 c^{5} \\int_{0}^{x_F} \\frac{x^{4}}{(1+x^2)^{1/2}} \\dd{x}\n\\,.\n\\end{align}\n\nThe variable \\(x_F\\) is given by:\n\\begin{align}\nx_F = \\frac{p_F}{m_ec} = \n\\qty(\\frac{3 n_e}{8 \\pi })^{1/3} \\frac{h}{m_e c} =\n\\qty(\\frac{3 Y_e \\rho_{c}}{8 \\pi m_H})^{1/3} \\frac{h}{m_e c}\n\\,,\n\\end{align}\n%\nand, since the electrons are fully degenerate, \\(x_F \\gg 1 \\) corresponds to the ultrarelativistic case while \\(x_F \\ll 1\\) corresponds to the nonrelativistic case.\n\nNow, as \\(x_F \\to \\infty \\) the integral is asymptotically \n%\n\\begin{align}\n\\int_0^{x_F} \\frac{x^{4}}{\\sqrt{1 + x^2}} \\dd{x} \\sim \\frac{x_F^{4}}{4}\n\\,,\n\\end{align}\n%\nso we define\n%\n\\begin{align}\nI(x_F) &= \\frac{4}{x_F^{4}}\\int_0^{x_F} \\frac{x^{4}}{(1 + x^2)^{1/2}} \\dd{x} \\\\\n&= \\frac{3}{2 x^{4}} \\qty( x (1+x^2)^{1/2} \\qty(\\frac{2x^2}{3} -1) + \\log \\qty(x + (1+x^2)^{1/2}))\n\\,,\n\\end{align}\n%\nwhich approaches 1 as \\(x_F \\to \\infty \\).\nThen, we can write the pressure as \n%\n\\begin{align}\nP &= \\frac{8 \\pi }{3 h^3} m_e^{4} c^{5} \\frac{x_F^{4}}{4} I(x_F)  \\\\\n&= k_{UR} n_e^{4/3} I(x_F)\n\\,.\n\\end{align}\n\nWe can see that this manipulation works by explicitly doing the calculation, but we can also just observe that the limiting case \\(x_F \\to \\infty \\) must reduce to the ultrarelativistic approximation, so the prefactor must be the same.\n\n% By comparison with the ultrare\n% so we get \\(P = k _{\\text{UR}} n_e^{4/3}I(x_F)\\), where we incorporated the integral in the term \\(I(x_F)\\): this is given by \n%\n\n% so if \\(x_F \\gg 1\\) we have \\(I(x_F) \\sim 1\\), the ultrarelativistic case,\nIn the nonrelativistic case, \\(x_F \\ll 1\\), we have \\(I(x_F) \\sim 4 x_F / 5\\), and since \\(x_F \\sim n_e^{1/3}\\) this yields \\(P \\sim n_e^{5/3}\\) as expected. \nThis expression \\emph{interpolates} between the two limits.\n\nThen, we can apply the same reasoning as before: we compare the pressure of the Fermi gas with the prediction of the Clayton model to find\n%\n\\begin{align}\nk _{\\text{UR}} \\qty(\\frac{Y_e \\rho_{c}}{m_H})^{4/3} I(x_F)\n\\approx \\qty(\\frac{\\pi }{36})^{1/3} G M^{4/3} \\rho_{c}^{4/3}\n\\,,\n\\end{align}\n%\nso we can extract the mass: \n%\n\\begin{align}\nM = I(x_F)^{3/2} M _{\\text{Ch}}\n\\,,\n\\end{align}\n%\nwhere \\(M _{\\text{Ch}} \\approx \\SI{1.4}{M_{\\odot}}\\) is the Chandrasekhar mass we defined earlier.\n% and the important thing is that \\(x_F \\propto n_e^{1/3} \\propto \\rho_{c}^{1/3}\\). \n\n% [Graph: on the \\(x\\) axis \\(M/ M _{\\text{CHANDRA}}\\), on the \\(y \\) axis \\(\\rho_{c}\\).]\n\\begin{figure}[ht]\n\\centering\n\\includegraphics[width=\\textwidth]{figures/chandrasekhar_limit.pdf}\n\\caption{A plot of \\(M / M _{\\text{Ch}}\\) against \\(x_F \\propto n_e^{1/3} \\propto \\rho _c^{1/3}\\).}\n\\label{fig:chandrasekhar}\n\\end{figure}\n\n% \\todo[inline]{Quick and dirty Mathematica plot, to update (and flip the axes maybe).}\n% If we increase the mass, the star is not able to support itself by the pressure due to being a gas of degenerate electrons. \n\nWe can see that as we increase the mass approaching \\(M _{\\text{Ch}}\\) the central density diverges: this is not physically possible, of course, so as it gets higher some usually-prohibited process takes over; typically for white dwarfs this is electron capture, by which electrons and protons combine into neutrons, forming a neutron star.\n\nWe have not used any particular characteristics of electrons beyond their being fermions, so this line of reasoning may be used to also bound the mass of a neutron star, since neutrons are fermions as well. \nThe issue, as we will see, is that general-relativistic corrections become important in that case, since neutron stars have a much higher density.\n\n% This gives us \n% %\n% \\begin{align}\n% M _{\\text{CHANDRA }} = 3.1 Y_e^2 m_{*}\n% = 5.8 Y_e^2 M_{\\odot} = 1.4 M_{\\odot}\n% \\,.\n% \\end{align}\n\n\\subsection{White dwarf characteristics}\n\n% It can be shown that the mean density is around \nNow that we have a model for the equation of state at the core of a fully degenerate object like a white dwarf, we can try to extract some of its characteristics: it is reasonable (from more complete studies of the object) to estimate the mean density as 1/6 of the central one,\n%\n\\begin{align}\n\\expval{\\rho } = \\frac{1}{6} \\rho_{c}\n= \\frac{\\num{.51}}{Y_e^2} \\qty(\\frac{M}{m_{*}})^2\n\\frac{m_H}{( h / m_e c)^3}\n\\,,\n\\end{align}\n%\nso we can estimate the radius as \n%\n\\begin{align}\nR = \\qty(\\frac{3 M }{4 \\pi \\expval{\\rho }})^{1/3} \n\\approx \\num{.77} Y_e^{5/3} \\qty(\\frac{M}{m_{*}})^{1/3} \\underbrace{\\alpha_{G}^{-1/2} \\frac{h}{m_e c} }_{\\ell_{WD}}\n\\,,\n\\end{align}\n%\n% and the object at the end is \nwhich is of the same order of magnitude as the characteristic length\n%\n\\begin{align}\n\\ell_{WD} = \\alpha_{G}^{-1/2} \\frac{h}{m_e c} \\approx \\SI{3e7}{m} \\approx \\num{0.04} R_{\\odot}\n\\,,\n\\end{align}\n%\nso, taking \\(Y_e = 0.5\\) we can express the radius as \n%\n\\begin{align}\nR = \\frac{R_{\\odot}}{74} \\qty(\\frac{M_{\\odot}}{M})^{1/3}\n\\,.\n\\end{align}\n\n% The luminosity is given by \nUsing the radius we can estimate the luminosity of the thermal radiation emitted by these bodies:\n%\n\\begin{align}\nL = 4 \\pi R^2 \\sigma T_E^{4}\n= \\frac{1}{74^2} \\qty(\\frac{M_{\\odot}}{M})^{4/3}\n\\qty(\\frac{T_E }{\\SI{6000}{K}}) L_{\\odot}\n\\,,\n\\end{align}\n%\nso if we take a typical effective temperature of around \\SI{e4}{K} (recall that white dwarfs are in the blue part of the HR diagram), \\(M = \\num{.4} M_{\\odot}\\) we get \\(L \\approx \\num{3e-3} L_{\\odot}\\): they are very dim. \n\n\\subsection{Neutron stars}\n\nThe first thing to consider when discussing neutron stars is the fact that neutrons, as we discussed, are usually unstable, with lifetimes on the order of \\SI{10}{min}. How can a neutron star be stable then?\n% We deal with degenerate stars: the Pauli exclusion principle plays a critical role, and the process \nThe process through which neutrons decay is:\n%\n\\begin{align}\n\\ce{n} \\rightarrow \\ce{p} + \\ce{e-} + \\overline{\\nu}_{e}\n\\,,\n\\end{align}\n%\nand the crucial fact is that neutron stars are composed of a degenerate neutron gas \\emph{as well as} a degenerate \\emph{ultrarelativistic} electron gas: the Fermi temperature is much higher than \\(m_e c^2/ k_B\\) \\cite[eq.\\ 1]{yakovlevNeutrinoEmissionNeutron}.\n% When a neutron decays \nWhile the electron gas is ultrarelativistic the neutron gas is not; the energy released by neutron decay is of the order of \\SI{800}{keV}, so the momentum an emitted electron would have would be well within the Fermi sphere, which is already full!\n\nThus, neutron decay is inhibited; on the other hand, electron capture, which looks like\n%\n\\begin{align}\n\\ce{e-} + \\ce{p} \\rightarrow \\ce{n} + \\nu_{e}\n\\,,\n\\end{align}\n%\nis favoured, and it can increase the number of neutrons.\n\nWe can look at the Saha formula to get numerical estimates for the equilibrium between these processes.\nThe chemical potential of neutrinos can be neglected, therefore we find \n%\n\\begin{align}\n\\mu_{\\ce{n}} = \\mu_{\\ce{p}} + \\mu_{\\ce{e}} \n\\,,\n\\end{align}\n%\nand, since as we saw earlier the chemical potential of a Fermi gas is its Fermi energy, the same equation holds for their Fermi energies: \n% This means that a certain point we will have only neutrons. \n% We need to exploit the Fermi exclusion principle. Why does the equation \n%\n\\begin{align}\n\\epsilon_{F, \\ce{n}} = \\epsilon_{F, \\ce{p}} + \\epsilon_{F, \\ce{e}}\n\\,.\n\\end{align}\n%\n% favour neutrons?\n\nHow does this translate into the number densities of the three constituents? We have the constraint that the number density of protons must equal the number density of electrons in order to ensure local neutrality, while there is no constraint on the ratio between neutrons and protons.\n% , but the Fermi energy depends on the number density of these.\n% typical numbers then become \n\nWe will not get into the calculation, but due to the slight mass imbalance \\(m_n > m_p\\) we have a large difference in the number densities: typically,\n%\n\\begin{align}\nn_{\\ce{p}} = n_{\\ce{e}} = \\frac{n_{\\ce{n}}}{200}\n\\,.\n\\end{align}\n\n% We will have \nSince the overwhelming majority of the particles in the neutron star are neutrons, we can make our calculations with the approximation that the number of neutrons per baryon is \\(Y_n \\approx 1\\): \n%\n\\begin{align}\nn_{\\ce{n}} = Y_n \\frac{\\rho_{c}}{m_{\\ce{n}}} \\approx \\frac{\\rho_{c}}{m_{\\ce{n}}}\n\\,.\n\\end{align}\n\nTypical values for these densities are \\(\\rho_c \\approx \\SI{2e17}{kg/m^3}\\) and \\(n_{\\ce{n}} \\approx \\SI{e44}{m^{-3}}\\).\n\n% For a neutron star we have \nWith a similar reasoning to the one we applied to white dwarfs we can calculate\n%\n\\begin{align}\n\\rho_{c}^{\\text{NS}} \\approx 3.1 \\qty(\\frac{M}{M_{*}})^2 \\frac{m_n}{\\qty(h / m_n c)^3}\n\\,,\n\\end{align}\n%\n% while for a white dwarf we have \nwhich, due to the fact that \\(m_{n} \\gg m_e\\), is much larger than the corresponding result for white dwarfs \n%\n\\begin{align}\n\\rho_{c}^{WD} \\approx \\frac{3.1}{Y_e^{5}} \\qty(\\frac{M}{M_{*}})^2 \\frac{m_H}{(h / m_e c^2)^{3}}\n\\,.\n\\end{align}\n% \\todo[inline]{why is the  \\(c\\), right?}\n\nIn both cases, we used the characteristic mass \\(M_{*} = \\alpha_{G}^{-3 /5 } m_n \\approx 1.85 M_{\\odot}\\).\n\nAs we did before, knowing the central density we can estimate the average one, which then allows us to calculate the radius:\n% and for the radius we get \n%\n\\begin{align}\nR = \\num{.77} \\qty(\\frac{M_{*}}{M})^{1/3} \\alpha_{G}^{-1/2}  \\frac{h}{m_n c}\n\\,,\n\\end{align}\n%\nwhere the characteristic length is given by \n%\n\\begin{align}\nL_n = \\alpha_{G}^{-1/2} \\frac{h}{m_n c} \\approx \\SI{17}{km} \\approx \\frac{1}{1200} L_e\n\\,,\n\\end{align}\n%\n1200 times smaller than the corresponding length scale for white dwarfs (denoted with an \\(e\\) for ``electron degeneracy'').\n% \\(L_n\\) is the characteristic length scale for a NS, \\(L_e\\) is the characteristic length for a white dwarf.\n\nFinally, we can compute a maximum mass: \\(M _{\\text{max}}^{\\text{NS}} = 3.1 M_{*} = 5.8 M_{\\odot}\\). \n% This is the mass of a star \\emph{remnant}, which encompasses mass from the core only: the initial star will be much larger. \n\n% Can this NS become a BH? we need to compute \nWe have neglected general-relativistic effects, but would they be relevant? The quantity we need to compute is the ratio of the Schwarzschild radius to the actual radius of the NS:\n%\n\\begin{align}\n\\frac{R_{\\text{Schw}}}{R} =\n\\frac{2GM}{Rc^2} \\approx \\num{.4} \\qty(\\frac{M}{M_{*}})^{4/3}\n\\,,\n\\end{align}\n%\nwhich is large, of order 1! We have not computed a minimum mass for a neutron star, but typically their mass is of the order of the Chandrasekhar mass, \\(M^{NS} \\approx 1.4 M_{\\odot}\\) because of how they form in supernovae (so, \\(M / M_{*} \\sim 1\\)).\n% qualitatively we can say that if it is too small then the degenerate electron gas may not be relativistic enough to stop neutron collapse.   \nThe neutron star might not be small enough to actually collapse into a black hole, but surely general relativity must be considered when describing its dynamics.\n% so if the mass is large enough we can reach the critical value of \\(GM / Rc^2 = 2\\). \n\nNeutron stars were first detected as very regular radio pulses: \\emph{pulsars}. These are due to the very strong (\\(\\sim \\SI{e8}{T}\\)) magnetic fields accelerating particles in beams aligned with the magnetic poles of the NS; these are not aligned with the rotation axis of the NS, so they constantly change the direction of emission, and the Earth can happen to be in this cone. \n\nIn order to estimate how fast these pulses can be (in a classical and rough way), let us assume that the NS is rotating barely below a speed which would disintegrate it, so that its binding energy equals its rotational energy: neglecting the order-1 numerical factors we have\n% We have \n%\n\\begin{align}\n\\frac{GM^2}{R} \\sim M R^2 \\omega^2 _{\\text{max}}\n\\,,\n\\end{align}\n%\n% the maximum angular velocity which can be supported gravitationally: it comes out to be \nwe can then compute the minimum period using the expression we have for the radius in terms of \\(M\\) and \\(M_{*}\\):\n%\n\\begin{align}\n\\tau _{\\text{min}} = \\frac{2 \\pi }{\\omega _{\\text{max}}} \n\\approx 2 \\pi \\qty(\\frac{R^3}{GM})^{1/2}\n\\approx \n11 \\qty(\\frac{M_{*}}{M}) \\alpha_{G}^{-1/2} \\frac{h}{m_n c^2}\n\\approx \\num{.6} \\frac{M_{*}}{M} \\SI{}{ms}\n\\,.\n\\end{align}\n\nThe signals produced by pulsars are of this order of magnitude --- we have observed ``millisecond pulsars'', so NSs do indeed rotate close to these extremely high rates.\n\nNeutron stars can also produce gravitational waves in their rotation, as long as they have a slight asymmetry (a ``mountain'', although their typical sizes are of the order of centimeters); these would have frequencies in the Hz range. We cannot detect these with ground-based detectors, but we might be able to do so with space-based ones. \n% This gives us a bound for gravitational waves of astrophysical origin. \n% \\todo[inline]{no comment on the GR corrections to this formula: however I'd expect them to be significant}\n\n\\subsection{Relativistic corrections to the equation of state}\n\n% We move on to \\emph{the GR issue}. \nBlack holes are objects which are so dense that their radius is smaller than the Schwarzschild radius:\n%\n\\begin{align}\nR < \\frac{2GM}{c^2} = R _{\\text{Sch}}\n\\,.\n\\end{align}\n\nGeneral Relativity predicts that when this is the case an \\textbf{event horizon} form, a surface which forms a causal boundary: as is almost cliché, \\emph{not even light can escape}.\n\nLet us see how the classical description of a star fails for objects with relativistic masses.\nThe equation of hydrostatic balance, derived under classical assumptions, reads:\n%\n\\begin{align}\n\\dv{P}{r} = - \\frac{Gm \\rho }{r^2}\n\\,.\n\\end{align}\n%\n% while the GR equations for this are the TOV equation: \n\nIf we seek a relativistic analogue under similar assumption (spherical symmetry and equilibrium) we find the \\textbf{Tolman-Oppenheimer-Volkov} equation: \n%\n\\begin{align}\n\\dv{P}{r} = - \\frac{Gm  \\rho }{r^2} \\qty(1 + \\frac{P}{\\rho c^2}) \\qty(1 + \\frac{4 \\pi r^3 P}{m c^2}) \\qty(1 - \\frac{2Gm}{rc^2})^{-1}\n\\,.\n\\end{align}\n%\n\nThis equation is exact under the assumptions we mentioned. \nIn the classical limit (\\(2Gm/ c^2 \\ll r\\) and \\(P \\ll \\rho c^2\\)) this reduces to the classical hydrostatic balance equation.\nThe first correction is reminiscent of the second Friedmann equation: \\emph{the pressure itself contributes to the inertia of the system}. \n\nLet us see how their predictions differ assuming constant density, \\(\\rho \\equiv \\rho_0 \\). In the Newtonian case the mass below a radius \\(r\\) is given by\n% If we have constant density, in the Newtonian case we get \n%\n\\begin{align}\nm(r) = \\frac{4 \\pi }{3} \\rho_0 r^3\n\\,,\n\\end{align}\n%\n% so than we can integrate and get \nusing which we can integrate the hydrostatic balance equation (from the surface, where the pressure vanishes) to find:\n%\n\\begin{align}\nP(r) \n= \\int_{R}^{r_0 } \\underbrace{\\qty(- \\frac{Gm \\rho }{r^2})}_{\\dv*{P}{r}} \\dd{r}\n= \\frac{2 \\pi G}{3}  \\rho_0^2 \\qty(R^2 - r_0^2)\n\\,.\n\\end{align}\n%\n% where we inserted the boundary condition \\(P(R) = 0\\).\n\nThen, the central pressure is given by \n%\n\\begin{align}\nP_c^{\\text{classical}} = \\frac{2 \\pi }{3} G \\rho_0^2 R^2 = \\qty(\\frac{\\pi }{6})^{1/3} G M^{2/3} \\rho_c^{4/3}\n\\,.\n\\end{align}\n\nKeeping the constant-density assumption, this can be done analytically in the relativistic case as well! We get \n%\n\\begin{align}\nP(r) &= \\rho_0 c^2 \\qty(\\frac{(1 - 2GM r^2 / R^3 c^2)^{1/2} - (1 - 2GM / Rc^2)^{1/2}}{3 \\qty(1 - 2GM / Rc^2)^{1/2} - \\qty(1 - 2GM r^2 / R^3c^2)^{1/2}})  \\\\\nP_c^{\\text{relativistic}} &= \\rho_0 c^2 \\frac{1 - \\sqrt{1 - \\frac{2GM}{Rc^2}}}{3 \\sqrt{1 - \\frac{2GM}{Rc^2}} - 1}\n\\,.\n\\end{align}\n\n%\n% \\todo[inline]{Check exponents}\n% so we get \n% %\n% \\begin{align}\n% P_c = \\frac{2 \\pi }{3} G \\rho_0^2R^2 = \\qty(\\frac{\\pi }{6})^{1/3} GM^{2/3} \\rho_{c}^{4/3}\n% \\,,\n% \\end{align}\n% %\n% so we can look at what happens when we consider \\(r=0\\): we get \n% %\n% \\begin{align}\n% P_c = \\rho_0 c^2 \\qty(\\frac{1 - \\sqrt{1 - 2GM / Rc^2}}{3 \\sqrt{1 - 2GM / Rc^2} - 1})\n% \\,,\n% \\end{align}\n% %\n\n% so we can see that the central pressure is finite as long as \nIn the classical model we had a finite central pressure for each value of the mass and density; now, instead, in order for the pressure to not diverge we must require\n%\n\\begin{align}\n% \\frac{2GM}{Rc^2} < \\frac{8}{9}\nR > \\frac{9}{8} \\frac{2GM}{c^2}\n\\,.\n\\end{align}\n%\n% which is not \\(1/2\\) since we have made some approximations. \n\nThis is known as the \\textbf{Buchdahl bound}; the radius of a non-black-hole (with constant density) cannot be arbitrarily close to the Schwarzschild radius, it must be at least \\SI{12.5}{\\percent} larger in order for the pressure to not diverge at the center.\\footnote{\nMore stringent bounds can also be derived --- in \\textcite[fig.\\ 2]{lattimerNeutronStarObservations2007} a plot is shown of possible equations of state of neutron stars in a mass versus radius plane.\nThe bound we derived is denoted as \\(P < \\infty \\), and we can also see a ``causality'' bound, which is related to the speed of sound in an ultrarelativistic medium.\nRealistic equations of state can reach approximately \\(R \\gtrsim 3GM /c^2\\).}\n\n% \\todo[inline]{A mass bound for neutron stars follows, both in Pacciani's notes and in the , but I don't follow the logic.}\nThis also yields a mass limit for neutron stars. Let us estimate the constant density \\(\\rho_0\\) by assuming that each neutron takes up a sphere of radius its Compton wavelength: \\(r_n \\approx h / m_n c\\), so \n%\n\\begin{align}\n\\rho_0 \\approx \\frac{m_n}{ \\frac{4 \\pi }{3} r_n^3}\n\\approx \\frac{3 m_n^4 c^3}{4 \\pi h^3}\n\\,.\n\\end{align}\n\nA more accurate estimate would be given by \\(r_n \\approx \\num{.7} h / m_n c\\).\n\nso that, using the fact that \\(\\rho_0 = M / ( 4 \\pi R^3 / 3)\\), we can start manipulating the Buchdahl bound:\n%\n\\begin{align}\nM &< \\frac{4 c^2}{9GR} = \\frac{4 c^2}{9 G} \\qty(\\frac{4 \\pi \\rho_0 }{3M})^{1/3}  \\\\\nM^{2/3} &< \\frac{4 c^2}{9G} \\qty(\\frac{4 \\pi }{3} \\frac{3 m_n^4 c^3}{4 \\pi h^3})^{1/3} \\\\\nM  &< \\qty(\\frac{8 \\pi}{9})^{3/2} M_{*}\n\\,.\n\\end{align}\n\nThis yields a bound on the order of \\(M \\lesssim 5 M_{\\odot}\\).\n% Then we have a bound \n% %\n% \\begin{align}\n\n% \\,,\n% \\end{align}\n% %\n% with \\(f \\sim 1\\).\n% This means than the objects becomes contained inside its Schwarzschild radius, \\(R = 2GM/c^2\\). \n\n% Tomorrow we will speak of galaxy formation. \n\n\\end{document}", "meta": {"hexsha": "7468bf656a70630c490f1b273b0feac96b9177ae", "size": 20664, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ap_first_semester/astrophysics_cosmology/19dec.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "ap_first_semester/astrophysics_cosmology/19dec.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ap_first_semester/astrophysics_cosmology/19dec.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 40.9188118812, "max_line_length": 380, "alphanum_fraction": 0.6761033682, "num_tokens": 7003, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.338396732816258}}
{"text": "% This file is part of the OWL project.\n% Copyright 2014 the authors.\n\n% ## notes:\n% - Use ``star'' not ``source'' for the target of the OWL.\n\n% ## to-do:\n% - Should I include detrendings like PDC and median filtering?\n% - Needs affiliations etc.\n% - Finish zeroth draft.\n% - Send for comments to Lupton, Carey, Wright, Brandner, Loredo\n% - Who is in charge of the PanSTARRS variability field?\n\n\\documentclass[12pt, letterpaper, preprint]{aastex}\n\n\\usepackage{color,hyperref}\n\\definecolor{linkcolor}{rgb}{0,0,0.5}\n\\hypersetup{colorlinks=true,linkcolor=linkcolor,citecolor=linkcolor,\n            filecolor=linkcolor,urlcolor=linkcolor}\n\n\\newcommand{\\documentname}{\\textsl{Article}}\n\\newcommand{\\project}[1]{\\textsl{#1}}\n\\newcommand{\\foreign}[1]{\\textsl{#1}}\n\\newcommand{\\etal}{\\foreign{et\\,al.}}\n\\newcommand{\\transpose}[1]{{#1}^{\\!\\mathsf T}}\n\\newcommand{\\inverse}[1]{{#1}^{-1}}\n\\newcommand{\\E}[1]{\\mathrm{E}[{#1}]}\n\\newcommand{\\Var}[1]{\\mathrm{Var}[{#1}]}\n\\newcommand{\\Covar}[1]{\\mathrm{Covar}[{#1}]}\n\\input{vc}\n\n% affils\n\\newcommand{\\ccpp}{1}\n\\newcommand{\\mpia}{2}\n\\newcommand{\\contact}{3}\n\\newcommand{\\courant}{4}\n\n\\begin{document}\\sloppy\\sloppypar\n\n\\title{\n  Optimized ``soft'' aperture photometry for time-domain astronomy\n}\n\\author{\n  David W. Hogg\\altaffilmark{\\ccpp,\\mpia,\\contact},\n  Dan Foreman-Mackey\\altaffilmark{\\mpia},\n  Jonathan Goodman\\altaffilmark{\\courant}\n}\n\\altaffiltext{\\ccpp}{%\n  Center for Cosmology and Particle Physics,\n  Department of Physics, New York University}\n\\altaffiltext{\\mpia}{%\n  Max-Planck-Institut f\\\"ur Astronomie}\n\\altaffiltext{\\contact}{%\n  \\texttt{david.hogg@nyu.edu}}\n\\altaffiltext{\\courant}{%\n  Courant Institute for Mathematical Sciences,\n  New York University}\n\n\\begin{abstract}\nPrecise stellar photometry campaigns by \\project{Kepler}, \\project{Spitzer}, and \\project{PanSTARRS}\n  (among many others)\n  create precise lightcurves by fixing the star in detector coordinates,\n  and estimating brightness with a fixed linear combination of background-subtracted pixel values.\nUnder any complete set of assumptions about the noise in the detector,\n  there is a particular choice of pixel weights for use in the brightness estimate\n  that maximizes signal-to-noise.\nWhen precision requirements are extremely high,\n  the noise model must necessarily include pointing and point-spread-function variations,\n  which introduce highly correlated noise at the pixel level.\nHere we generalize previous results on optimized photometric estimators\n  to include arbitrarily correlated pixels.\nAmusingly, the approach we advocate does not in the end\n  require any advance knowledge of any noise source;\n  once there are enough epochs observed,\n  the pixel-level data are sufficient to build an empirical data-driven correlated noise model.\nThe optimized pixel weights can be found analytically;\n  when they are used to perform photometry, they work extremely well.\nWe demonstrate enormous improvements to the \\project{Kepler} photometry of isolated stars.\nThe Optimized-Weight Linear (OWL) photometry produces photometric measurements so uniform that\n  they outperform or obviate much more heuristic (and much more scientifically damaging)\n  ``detrending'' schemes in many real cases.\nIn particular, OWL photometry minimizes instrument-induced variance\n  but preserves all intrinsic stellar variability.\nAll the OWL code is available under an open-source license.\n\\end{abstract}\n\n\\keywords{\n  instrumentation: photometers\n  ---\n  methods: data analysis\n  ---\n  methods: statistical\n  ---\n  techniques: photometric\n}\n\n\\section{Rules of the photometry game}\n\nPrecise photometry is the bread-and-butter of the exoplanet community.\nThe unprecedented precision of the \\project{Kepler} photometry has led to the discovery of\ndozens of Earth-radius planets (HOGG CITES).\n\\project{Kepler}-level (part in $10^5$) precise photometry is, no doubt,\n  going to be of great importance in many other areas as well.\n\nImagine you are trying to do very sensitive relative photometry on a variable source.\nThe most precise methodologies at present involve fixing the position of the source on the detector\n  (cite examples)\n  to reduce dependency of the results on the flat-field or flat-fielding errors.\nThey also often involve defocusing the telescope\n  (cite examples),\n  to illuminate the pixels more uniformly\n  (and hence reduce intra-pixel sensitivity issues),\n  avoid saturation,\n  and make the observations less atmosphere-dependent.\nThere are also strategies related to calibration or the choices of comparison stars\n  (cite examples).\nOnce all these choices are made,\n  the choice of methodology for actually photometering the source remains.\nMost projects choose something akin to aperture photometry\n  (cite examples),\n  in which the pixels within an aperture are co-added with unit weights,\n  and pixels outside the aperture are not used at all.\nHere we ask only about this last choice:\nWhat is the best way to measure the brightness of a nearly constant source,\n  given a set of precise images of the source taken over time?\n\nFOR THE ABOVE CHECK TWITTER FOR REFS AND THANK TWEEPS.\n\nWe are going to answer this question using optimization, of course;\n  we are going to find the ``best'' method.\nWe will assume that the investigator obeyed the usual rules,\n  so he or she fixed the position of the star on the detector,\n  possibly defocused the telescope,\n  and avoided saturation.\nHowever, we are also going to assume---%\n  as is \\emph{always the case}---%\n  that there are some residual,\n  unaccounted-for positional offsets (jitter) and point-spread-function changes.\nThese offsets and changes could be random or systematic over time,\n  but we will assume that they are unknown \\foreign{a priori}.\nThat is, the telescope house-keeping data are not good enough to track them at the level we care about.\nWe are trying to measure \\emph{extremely} precise photometry,\n  at the level of $10^{-4}$ or $10^{-5}$ or better.\n\nThe conditions we have assumed might seem strange,\n  but they are generic for the most precise photometry systems currently operating.\n\\project{Kepler}, for instance, has all of these problems,\n  as does [insert projects here, like Wright's].\n\nIt is possible to think of this problem as the problem of finding the best strategy in a single-player game.\n\\emph{The Rules} of this game are as follows:\n\\begin{itemize}\n\\item\n  There is copious multi-epoch single-band imaging,\n  with many epochs (many images),\n  and a known position in that imaging of a star of great interest (the ``object'' star).\n  There is also perhaps some ``pixel mask'' indicating what pixels are permitted for use\n  in the vicinity of that star.\n\\item\n  There may or may not be a list of ``comparison'' stars\n  that are used to calibrate or ratio the photometry of the object star.\n  If there aren't, then it can be assumed that the imaging is very well calibrated.\n\\item\n  The imaging is background- and foreground-subtracted,\n  such that the mean level of the smooth foregrounds and backgrounds in the imaging is zero.\n  The background level might vary or the subtraction of it might not be perfect,\n  but we can assume that it is has a mean of zero across pixels and epochs.\n\\item\n  It is expected that the star is fairly stationary in device coordinates (pixel location).\n  However, in each image it has been offset slightly by some amount from its fiducial position.\n  There are no reliable meta-data to help you understand those small offsets.\n  Any comparison stars are also subject to small offsets;\n  the comparison-star offsets are not necessarily the same as the object-star offsets,\n  because there is camera rotation, variable optical distortion, proper motion, and parallax.\n\\item\n  It is expected that the point-spread function (PSF) is fairly constant.\n  However, again, in each image it has a small difference from the fiducial point-spread function.\n  There are no reliable meta-data to help with this,\n  and the comparison star PSFs will also vary but not in precisely the same way,\n  though their variations might be non-trivially correlated.\n\\item\n  There are no reliable meta-data about read noise or gains,\n  so there is no precise noise estimate for any pixel at any epoch.\n\\item\n  When you photometer a star,\n  the only operation you are permitted is linear weighted sums of pixels in the images.\n  Furthermore, any weighted sums must be precisely identical from epoch to epoch.\n  That is, the ``aperture''\n  (which in fact may be some complicated set of pixel weights)\n  is required to be identical from image to image.\n\\end{itemize}\nThese rules are generic;\n  this is a common situation for precise, multi-epoch photometry.\n\nThe only rule to which we object is the last one:\nIn principle it should be better to do focal-plane modeling\n  and perform photometry as a maximum-likelihood value\n  or some statistics of a posterior PDF\n  based on a parameterized likelihood function (for example, \\citealt{hoggwhitepaper}).\nHowever, there are many applications in which\n  the physical information one would like for building such a model is not available.\nWe would parameterize and fit nonetheless,\n  but most astronomical projects don't take this approach at present.\nThere are also situations in which the output of full likelihood fitting for the data\n  shows correlations between the final photometry and nuisance parameters (such as PSF parameters).\nIn these cases, the investigator is left wondering if the residual photometric variance\n  has contributions from nuisance-parameter variance or fit residuals or model mismatch.\n\nThere have been some previous attempts to optimize photometric estimators subject to \\emph{The Rules},\n  in generic (but limiting) situations.\nWhen the pointing and point-spread function are both known precisely,\n  the pixel noise variance is known for every pixel,\n  and the pixel noise is independent (uncorrelated) pixel-to-pixel,\n  there are simple analytic results (\\citealt{naylor}).\nThese results reduce to the psf-as-matched-filter standard practice\n  in the further simplification of sky-dominated noise.\nThere are no previous results (to our knowledge) that take account of\n  the highly covariant noise created by variable pointing or optics.\nThis is the first primary novelty of this work.\nThe second primary novelty is the realization that the noise---%\n  even the covariant part created by optics and pointing---%\n  can be determined empirically from the data themselves,\n  with no prior knowledge of the characteristics of the detector,\n  telescope, or atmosphere.\n\n\\section{Well-calibrated data}\n\nIn the (possibly fantastical) situation in which the imaging data are all properly calibrated,\n  we have no need for comparison stars.\nWe are going do the photometry using nothing but the pixels near the object star.\n\nBefore we say what ``properly calibrated'' means,\n  it is necessary to specify what we mean by an ``image''.\nOrdinarily it is our view that\n  an image is a measurement of the smoothed intensity field\n  or smoothed photon phase-space density.\nIt ought to have units of energy per time per area per solid angle\n  or photons per time per area per solid angle.\nThe problem with this view of an image\n  is that if we do aperture photometry---%\n  that is, if we make linear weighted sums of image pixels---%\n  to get a total stellar flux,\n  the weights in the weighted sum must have units of \\emph{solid angle}.\nSmall changes to the optics or atmosphere will change the astrometric mapping of the camera,\n  changing the solid angles of the pixels.\nAperture photometry is the wrong thing to do in this formulation of an image;\n  or it is an okay thing to do if the weights are permitted to vary with the astrometric distortion.\nThat would violate \\emph{The Rules} above.\n\nSo the image we want for these purposes is not a measurement of the intensity field,\n  but rather a kind of ``flux map''.\nIt ought to have units of energy per time per area\n  or photons per time per area.\nThese values can be co-added with dimensionless weights to deliver a stellar flux.\nThe only difference between an intensity image and a flux map is a factor of\n  the angular size of the pixels.\nIn many imagers pixels are similar in size so these differences aren't apparent.\nHowever, at the levels of precision we care about here\n  ($10^{-4}$ or $10^{-5}$ or better)\n  these details matter.\n\nWhat is meant by ``properly calibrated''?\nThe image (flux map) is properly calibrated when it is can be treated as a measurement of---%\n  or is directly proportional to---%\n  a smoothed map of energy or photon number per time per area.\nIt is ``smoothed'' because it is convolved (or correlated) with some finite\n  and possibly spatially varying PSF\n  (which we don't know).\n\nAre any imaging data properly calibrated according to these criteria?\nWe don't know, but the \\project{Kepler} Satellite may be.\nThe standard data products of the \\project{Hubble Space Telescope}\n  are given in intensity units,\n  but the astrometric solution is known to high precision,\n  so (with a tiny bit of work)\n  these also can be properly calibrated for aperture photometry according to this definition.\n\nWe do not endorse the view that images should be presented as flux maps!\nWe are just sayin' that \\emph{if} you need to obey \\emph{The Rules},\n  then you need to convert your intensity maps into flux maps before playing the game.\n\n\\section{Optimized photometry}\n\nWe have at each of $N$ epochs $n$ a set of $D$ pixels in a small patch\n  that contains a star.\nThe set of measured, properly calibrated (see above),\n  correctly background-subtracted (see above)\n  pixel values at epoch $n$ form a $D$-dimensional column vector $y_n$.\nAccording to \\emph{The Rules}, all we are permitted to do at epoch $n$\n  is produce a weighted sum\n\\begin{eqnarray}\nq_n &\\leftarrow& \\transpose{w}\\, y_n\n\\quad ,\n\\end{eqnarray}\n  where $q_n$ is a scalar photometric measurement,\n  $w$ is a $D$-dimensional column vector of weights,\n  and (because of the transpose)\n  the product is effectively an inner (scalar or dot) product.\n\\emph{The Rules} state that the weight vector $w$ must not depend on $n$ or anything else;\n  the weights are the same at every epoch.\n\nWe can see $q_n$ as an estimator---a point estimate---of the stellar brightness.\nIf we knew the expectation value (mean) for the pixel data $y_n$ and also the\n  variance of those data around the mean,\n  we could predict the expectation and variance of the estimator.\nThe expectation value would be:\n\\begin{eqnarray}\n\\E{q_n} &=& \\transpose{w}\\, \\mu_n\n\\\\\n\\mu_n &\\equiv& \\E{y_n}\n\\\\\n\\Var{q_n} &=& \\transpose{w}\\, C_n\\, w\n\\\\\nC_n &\\equiv& \\Covar{y_n}\n\\quad ,\n\\end{eqnarray}\n  where $\\E{x}$ is the expectation value of $x$,\n  $\\Var{x}$ is the variance of (a scalar) $x$ around its expectation value,\n  and $\\Covar{x}$ is the $D\\times D$ symmetric, positive definite covariance matrix\n  of (a vector) $x$ around its expectation value.\nIn the simple case of independent noise from pixel-to-pixel,\n  $\\Covar{y_n}$ becomes diagonal,\n  and the variance $\\Var{q_n}$ becomes simply the sum of the diagonal variances,\n  weighted by the squared weights.\nThe expected squared signal-to-noise ratio $\\Sigma^2$ for $q_n$ is\n\\begin{eqnarray}\n\\Sigma^2 &=& \\frac{[\\transpose{w}\\, \\mu_n]^2}{\\transpose{w}\\, C_n\\, w}\n\\quad .\n\\end{eqnarray}\n\nIt is almost always assumed that the pixel-to-pixel noise is independent (diagonal);\n  why do we not assume this here?\nThe answer lies in \\emph{The Rules}:\nVariations of the pointing and point-spread function (and background),\n  which are all unknown,\n  correlate the pixels.\nThat is, they produce a kind of noise that is neither photon nor read noise in the detector.\nThey produce a jitter noise that leads to covariant variations of the individual pixel values.\n\nWe win the game if we find the weight vector $w$ that optimizes signal-to-noise.\nIt can't optimize the signal-to-noise at epoch $n$;\n  it must optimize the mean or typical signal-to-noise across epochs.\nThat is, we want to find the weight vector $w$ that optimizes\n\\begin{eqnarray}\n  \\Sigma^2 &=& \\frac{[\\transpose{w}\\, \\mu]^2}{\\transpose{w}\\, C\\, w}\n  \\quad ,\n\\end{eqnarray}\nwhere now $\\mu$ is the expectation value of the data vectors $y_n$ but now over \\emph{all} epochs,\n  and $C$ is the covariance matrix for the data but again over \\emph{all} epochs.\nThe signal-to-noise-optimized weight vector is simply\n\\begin{eqnarray}\n  w &\\leftarrow& \\inverse{C}\\, \\mu\n  \\quad ,\n\\end{eqnarray}\n  where the inverse operation is the full matrix inverse.\nThis optimized-weight result is the natural generalization to correlated noise\n  of the equivalent result (for independent pixel noise)\n  obtained previously (\\citealt{naylor}).\n\nPrevious work has called these weights ``optimal'' but they are only really ``optimized''.\nFor one, the word ``optimal'' always begs the question ``with respect to what?''\nFor another, we reserve the word ``optimal'' for estimators\n  that have some glimmer of hope of saturating the Cram\\'er--Rao bound (CITE).\nThe optimized estimators presented here will not do this in general\n  (and nor will those of \\citealt{naylor}),\n  because they are not based on any reasonable likelihood function.\n\nBy assumption, we don't know the point-spread function,\n  nor the noise model,\n  nor the pointing or PSF jitter.\nTherefore, we can't compute $\\mu$ and $C$ from first principles; we have to estimate them.\nFortunately, we have $N$ epochs of data;\n  we can compute a (suitably robustly estimated)\n  \\emph{empirical} mean $\\hat{\\mu}$ and \\emph{empirical} covariance $\\hat{C}$\n  of the original data vectors $y_n$.\nThat is, we will do something like\n\\begin{eqnarray}\n  \\hat{\\mu} &\\leftarrow& \\frac{1}{N}\\,\\sum_{n=1}^N y_n\n  \\\\\n  \\hat{C} &\\leftarrow& \\frac{1}{N-1}\\,\\sum_{n=1}^N [y_n - \\hat{\\mu}]\\,\\transpose{[y_n - \\hat{\\mu}]}\n  \\\\\n  \\hat{\\Sigma}^2 &=& \\frac{[\\transpose{w}\\, \\hat{\\mu}]^2}{\\transpose{w}\\, \\hat{C}\\, w}\n  \\\\\n  \\hat{w} &\\leftarrow& \\inverse{\\hat{C}}\\, \\hat{\\mu}\n  \\quad ,\n\\end{eqnarray}\n  where the operations are averages over the epochs,\n  the vector product is the outer or tensor product,\n  $\\hat{\\Sigma}^2$ is the \\emph{empirical} signal-to-noise,\n  and $\\hat{w}$ are the weights that maximize it.\nTechnically we require $N \\gg D$\n  (far more epochs than there are pixels in the tiny patch).\nIt turns out that with small modifications\n  (to make the means robust to outliers)\n  this works well, at least for \\project{Kepler} data (see below).\nThe Optimized-Weight Linear (OWL) photometry $q_n$ is then\n\\begin{eqnarray}\n  q_n &\\leftarrow& \\transpose{\\hat{w}}\\, y_n\n  \\quad ,\n\\end{eqnarray}\n  that is, one scalar $q_n$ per epoch $n$, obtained by a weighted sum of the $y_n$.\nWe have not just obeyed \\emph{The Rules},\n  we have come up with the best possible strategy in terms of empirical signal-to-noise.\n\nThere is one overall scale that is free;\n  any scalar multiple of the weight vector $\\hat{w}$ is identical in signal-to-noise\n  to any other scalar multiple.\nIn practice it doesn't matter how we choose this unless either machine precision is an issue,\n  or else some kind of absolute aspects of photometry are required.\n\n\\section{\\project{Kepler} data}\n\nFor each star in the Kepler data (identified by a KIC number),\n  there is a small patch of telemetered pixels,\n  and some 4000 epochs per quarter and up to 17 quarters of data.\nThe patch of pixels has an associated mask,\n  which indicates both which pixels are good data,\n  and also which were summed to make the official pipeline\n  Simple Aperture Photometry (SAP).\nThe weights used to generate the SAP photometry are constant within a quarter,\n  and all snapped to either zero or unity.\n\\figurename~\\ref{fig:pixels} shows time histories for the $D=19$ pixels relevant\n  to KIC~3335426 from the fifth quarter in which it was observed.\nAlso shown are the three pixels that got unit weight in the SAP photometry for this star.\n\nThe \\project{Kepler} data are extremely good, but there are some outliers,\n  presumably from cosmic rays.\nWe want to compute empirical means and covariances that are not overly drawn by these outliers.\nWe compute the empirical statistics with an iterated sigma-clipping.\nIn each iteration, we censor (remove from the sum)\n  any datum $y_n$ that is more than a ``4 sigma'' outlier\n  given the empirical mean $\\hat{\\mu}$ and covariance $\\hat{C}$ computed in the previous iteration.\nTo determine the 4-sigma criterion, we use the Gaussian approximation to the chi-squared distribution\n  with the appropriate number of degrees of freedom.\nWe iterate this sigma-clipping through five iterations,\n  which in practice seems to lead to convergence.\nImportantly, we sigma-clip at the epoch level, not the pixel level.\n\n\\figurename~\\ref{fig:images} shows the robustly estimated empirical mean image $\\hat{\\mu}$,\n  the diagonal elements of the empirical covariance matrix $\\hat{C}$,\n  the top eigenvector of the covariance matrix,\n  and the OWL weights, along with the weights used by the \\project{Kepler} pipeline,\n  and a few data examples.\nWe resolved the overall scale degeneracy for the weights (see above)\n  by requiring that the OWL and SAP photometry produce identical median flux.\nThe optimized weight vector shown in \\figurename~\\ref{fig:images} might seem counterintuitive;\n  it puts substantial weight off the peak of the mean intensity.\nThe fundamental reason is that the weight vector is trying to get as orthogonal as possible\n  to the high-variance eigenvectors of the variance tensor.\nIn the end, the highest-weight pixels do not all deliver significant signal;\n  in \\figurename~\\ref{fig:images} we also show\n  the pixel-wise product of the OWL weights with the empirical mean values,\n  which gives a sense of where the bulk of the photometric signal is coming from.\n\n\\figurename~\\ref{fig:results} shows the \\project{Kepler} SAP flux for KIC~3335426,\n  along with the OWL and some variants thereof (described below).\nThe OWL photometry very effectively  detrends the data,\n  even though it involves \\emph{no explicit detrending}.\nBy ``detrending'' we mean filtering or fitting-and-subtracting\n  the SAP photometry (as in the \\project{Kepler} PDC or median-filtered photometry).\nDetrendings remove intrinsic stellar variability and create artificial epoch-to-epoch correlations\n  in the photometric noise;\n  they are the bane of exoplaneteers.\nThat is, the OWL is just a soft-aperture aperture photometry, identical from epoch to epoch\n  that obviates detrending.\nIt is simply the weighting of the pixels that optimizes the empirical output signal-to-noise.\n\nIn detail, this first shot at OWL photometry is a tiny bit noisier\n  in an epoch-to-epoch sense\n  than the SAP photometry,\n  despite being far better in its overall trend.\nThis is coming from the fact that the OWL weights are trying to suppress the dominant\n  sources of variance,\n  which are entering the data on long time-scales.\nThe focus on the biggest variance components limits what the OWL can do.\nThis opens up the next area of discussion:\nHow do we estimate the covariance matrix $\\hat{C}$ so that it is dominated by the sources of variance\n  that we most want to suppress?\n\n\\section{Estimation of the covariance tensor}\n\nHOGG:\nSomething about what is really happening (trying to zero out dominant eigenvectors).\n\nHOGG:\nSomething about the lack of prior knowledge:\n\\begin{itemize}\n\\item\nWe aren't assuming \\emph{anything} about the sources of variance.\n\\item\nWe aren't doing \\emph{anything} about intrinsic variability of the source.\n\\item\nSome intrinsic variability we do care about, some we don't.\n\\item\nWe aren't using the time-ordering of the data at all;\n  different effects happen on different time scales.\n\\end{itemize}\nAll these issues turn into decisions or knobs that we can turn in variations.\nThe variations will fall into two categories:\nWe can change how we estimate the covariance matrix $C$,\n  or we can change how we constrain or regularize the weights $w$.\n\nHOGG:\nOn the covariance estimation, here are some basic ideas:\n\\begin{itemize}\n\\item\nUse local differences of pixel values instead of pixel values.\n\\item\nMix the dominant eigenvectors from the full set of pixel values\n  with the small-scale noise inferred from the local differences.\n\\item\nPerform some kind of factor analysis that splits the variance into\n  ``diagonal'' and ``covariant'' parts.\n\\item\nUse covariances across pixel patches from different stars\n  to identify extrinsic (rather than intrinsic)\n  sources of variances.\n\\end{itemize}\n\nHOGG:\n\\begin{eqnarray}\n\\hat{C}_S & \\leftarrow & \\frac{1}{N-1}\\,\\sum_{n=1}^N [y_n - \\hat{\\mu}]_\\perp\\,\\transpose{[y_n - \\hat{\\mu}]}_\\perp\n\\\\\nx_\\perp & \\equiv & x - \\sum_{k=1}^K u_k\\,\\transpose{u}_k\\,x\n\\\\\n\\delta_{kk'} &=& \\transpose{u}_k\\,u_{k'}\n\\quad ,\n\\end{eqnarray}\nwhere $S$ is a subspace of the full $D$-dimensional pixel space,\n  the $\\perp$ subscripts indicate that the vectors have been projected into the subspace $S$,\n  the $u_k$ vectors are orthonormal unit vectors that span the complement of subspace $S$,\n  and $\\delta_{kk'}$ is the integer (index) delta function.\n\n%% HOGG:\n%% In yet another variation, we estimated $\\hat{\\mu}$ and $\\hat{C}$ using not the\n%%   straight-up data, but the \\emph{differences} between each data point and\n%%   its time-ordered neighbor.\n%% Again with the sigma clipping.\n%% This leads to the DOWL, DOPW, and DTSA, shown in \\figurename~\\ref{fig:dresults}.\n\n\\section{Regularization of the weight vector}\n\nIt is also the case, in the above, that\n  we aren't putting in any prior knowledge about what the $w$ image ought to look like\n  in sane cases.\nOn the weight constraints and regularization, here are some basic ideas:\n\\begin{itemize}\n\\item\nRequire non-negativity.\n\\item\nRequire smoothness.\n\\item\nRequire similarity to the SAP aperture or some other sensible aperture.\n\\item\nRequire that the aperture be a circular top-hat or a smoothed version of that.\n\\end{itemize}\n\nAfter running the OWL on multiple \\project{Kepler} targets,\n  we developed a few intuitions that led to variations.\nIn one, we constrain the weights to be positive;\n  this protects against the optimizer finding locations in weight-space\n  that perform subtractions of large numbers to reduce variance.\nThis problem arises most strongly when the star being photometerd is intrisically variable\n  with a large amplitude:\nIn these cases, the largest variance can be from the star itself;\n  the OWL tries to find weights that cancel out the target star!\n\nThe Optimized Positive-Weight (OPW) photometry works still at the optimum of\n\\begin{eqnarray}\n\\hat{\\Sigma}^2 &=& \\frac{[\\transpose{w}\\, \\hat{\\mu}]^2}{\\transpose{w}\\, \\hat{C}\\, w}\n\\quad ,\n\\end{eqnarray}\nbut now subject to the constraint that every element of $w$ must be non-negative.\n\\figurename~\\ref{fig:images_opw} and \\figurename~\\ref{fig:results}\n show the results of the OPW for KIC~3335426,\n and \\figurename~\\ref{fig:results_variable} show the results of the OPW\n for a more variable star.\nThe positivity constraint seems salutory when the target star is somewhat variable.\n\nIn another variation, we looked at stars that saturate the \\project{Kepler} detectors.\nThese stars show bleed trails along the CCD columns,\n  although the \\project{Kepler} gains have been set cleverly\n  to ensure that precise photometry of these saturated stars is nonetheless possible with SAP photometry.\nIn the case of saturated stars, the OWL and OPW photometry do not work well\n  because the saturation leads to some pixels being exceedingly constant,\n  even if the source is intrinsically moving or varying.\nThat is, the saturated pixels do not show much empirical variance,\n  and get overly large weight in the optimization.\n\nFor these saturated cases we devised a Tweaked Simple Aperture (TSA) photometry,\n  which capitalizes on the clever apertures chosen by the \\project{Kepler} team\n  to capture saturated signal:\nIn the TSA, we lump together the SAP-coadded pixels into a single super-pixel.\nWe then perform the OWL methodology,\n  but now with the list of pixels not being the full list of pixels,\n  but rather the super-pixel plus the list of all the non-SAP pixels in the patch.\nThe TSA is a generalization of the OWL to non-square or non-uniform pixels.\n\nWe show the TSA results in \\figurename~\\ref{fig:results}.\nIt seems to be producing better epoch-to-epoch scatter;\n  this might because it represents an even stronger regularization of the weight image $\\hat{w}$.\n\nHOGG:\nIn yet another variation, we fix the aperture to be a circular top-hat,\n  and only permit its center and radius to be adjusted in the optimization...\n\nNOTE TO JASON WRIGHT: WE CAN HELP YOU!\n\n\\section{Comparison stars}\n\nHOGG:  GIVE THE SETUP\n\nHOGG:  You can operate the OWL for all $K$ stars.\nThen scale each star so it predicts as well as possible the object star.\nThen take robust means or medians of the $K$ predictors and divide them out.\n\nHOGG:  Or you can use all of the pixels in all the patches around all $K$ stars\n  to build a predictive model for the pixels in the object star's patch.\nThis permits creation of a very stable data-driven calibration of the data.\nWe are pursuing this in a separate project;\n  it is not even close to being ready for prime time.\n\n\\section{Discussion}\n\nWhat happened?\nWe permitted the aperture to be soft.\nWe optimized the aperture weighting.\nWe obviated detrending forever.\n\nIn the results shown in \\figurename~\\ref{fig:results},\n  the instrumental effects on the lightcurve were removed beautifully by the OWL,\n  but in detail\n  the adjacent epoch-to-epoch noise was inflated a tiny bit;\n  why?\nThe OWL knows nothing about time ordering of the data;\n  it makes no distinctions between slow and fast variations;\n  it is just trying to maximize signal-to-noise.\nSlow variations like those shown in \\figurename~\\ref{fig:results}\n  are just another source of total variance.\nIf a user knows a lot about what timescales are relevant,\n  the OWL can be improved enormously.\nTo demonstrate, we ran an experiment in which we filtered the \\project{Kepler} pixel-level data\n  for KIC~XXXX in quarter XXXX\n  with a 48-hour median filter to remove the long-timescale variability.\nWe subtracted the median filter output from each pixel lightcurve and added back in the mean.\nThe pixel lightcurves are shown in \\figurename~\\ref{fig:pixels_filter}\n  and the output of the OWL photometry is shown in \\figurename~\\ref{fig:results_filter}.\nBecause the pixels were partially ``detrended'' by this process,\n  the OWL weights are not putting as much effort into removing the large-scale trends.\n\nThis kind of detrending is common in the exoplanet community;\n  it has been valuable for finding exoplanets.\nIt brings many disadvantages;\n  one is that any detrending method that happens prior to exoplanet search\n  distorts the transit shapes and depths.\nAnother is that it removes stellar variability that might be of intrinsic interest.\nAnother is that it correlates data that are close in time;\n  it creates non-trivial noise for lightcurve fitting.\nThe OWL photometry---in its standard form shown in \\figurename~\\ref{fig:results}---%\n  produces independent photometry at every epoch\n  and preserves transit shapes and all intrinsic stellar variability.\n\nIn the end, a forward-modeling approach ought to win.\nIt won't obey \\emph{The Rules}, but it is the only approach that has a chance\n  of saturating the Cram\\'er--Rao bound.\nThe forward-modeling approach is not trivial, however,\n  because the usual methods of image modeling,\n  which make use of simple models for the flat-field, point-spread function,\n  and the ``scene''\n  have (in general) model mismatch issues that project residuals\n  in the calibration parameters onto the photometry of greatest interest.\nThat is, a forward-modeling approach that obtains photometry at the same\n  precision as the OWL would be expensive and complex.\nStill, it is the \\emph{Right Thing To Do (tm)} and thus the One True Path for the future.\nOne way to see this is to note that there is no obvious or simple generalization of the OWL\n  to the case of multi-instrument or multi-band imaging\n  (where pixel scale or bandpass vary from epoch to epoch).\n\nThe OWL, OPW, and TSA methods all depend very strongly on good background subtraction.\nThe reason is that it seeks to obtain high expectation value and low variance.\nIf there is a constant background that hasn't been subtracted,\n  the weights will choose to add in a lot of constant background\n  and possibly down-weight the pixels being hit by the variable object star.\nThe main requirement is that the background has been subtracted such\n  that the mean background level in all pixels at all epochs is negligible.\nThe background subtraction can be noisy and variable,\n  but it must be accurate in the mean.\n\nOn a related note, the image patch under consideration ought not be \\emph{far}\n  bigger than the region over which a normal would perform photometry.\nFor example, if the number of pixels in the object-star image patch becomes\n  much larger than the number of epochs,\n  the OWL will be able to find linear combinations of pixels that have\n  more-or-less perfectly constant flux.\nThis over-fitting issue is not a problem in what's shown above,\n  but could start to become a problem if large patches get used,\n  and would be exacerbated in the presence of non-zero mean background subtraction residuals.\nThis deserves further study.\n\nThe biggest (in our view) limitation of the OWL is that it cannot be used\n  to accurately measure the properties of stars\n  that are close enough that their point-spread functions overlap,\n  or stars in crowded fields.\nThe issue is that the optimization procedure has no knowledge or understanding\n  of the PSF or even of the fact that it is a star being observed.\nIn our view, the only justifiable solution to this problem is forward modeling,\n  in which there are parameterized beliefs about the PSF and the scene,\n  and in which the output photometry comes from analysis of a likelihood function.\nThe only conceivable generalizations of the OWL that might be relevant would either\n  \\textsl{(a)}~involve taking the optimum subject to the constraint that the weights must be\n  orthogonal to some estimate of the overlapping star point-spread functions, or else\n  \\textsl{(b)}~require modeling and subtraction of the confusing source or sources\n  in the field.\nThese are interesting ideas,\n  but probably no easier or more reliable than full forward modeling.\nAlthough we consider this non-isolated problem to be the most severe limitation of what we are doing,\n  we note that the tremendous discoveries and measurements of the \\project{Kepler} mission\n  have almost all been generated with straight-up aperture photometry,\n  followed by \\foreign{ex post facto} checks for blending.\nThere certainly is a great deal that can be done in the isolated-star limit.\n\nAll of the code used in this project is available\n  from \\url{http://github.com/davidwhogg/OWL/} (or forks thereof)\n  under the MIT open-source software license.\nThis code (plus some dependencies) can be run\n  to re-generate all of the figures and results in this \\documentname;\n  this version of the paper was generated with git hash\n  \\texttt{\\githash} (\\gitdate).\n\n\\acknowledgments\nIt is a pleasure to thank\n  Ruth Angus (Oxford),\n  Morgan Fouesneau (MPIA),\n  Fengji Hou (NYU), \n  Christian Knigge (Southampton),\n  Molei Tao (NYU), and\n  Jason Wright (PSU)\nfor valuable comments and suggestions.\nThis work was partially supported by the Moore--Sloan Data Science Environment at NYU,\n  by NASA (grant NNX08AJ48G).\n  and by the NSF (grant AST-0908357).\nThis research made use of the \\project{NASA Astrophysics Data System}.\n\n\\newcommand{\\arxiv}[1]{\\href{http://arxiv.org/abs/#1}{arXiv:#1}}\n\\begin{thebibliography}{}\\raggedright\n\\bibitem[Hogg \\etal(2013)]{hoggwhitepaper}\nHogg, D.~W., Angus, R., Barclay, T., et al.\\ 2013,\nMaximizing Kepler science return per telemetered pixel: Detailed models of the focal plane in the two-wheel era,\n\\arxiv{1309.0653}\n\\bibitem[Naylor(1998)]{naylor}\nNaylor, T.\\ 1998,\nAn optimal extraction algorithm for imaging photometry,\n\\mnras, 296, 339\n\\end{thebibliography}\n\n\\clearpage\n\\begin{figure}\n\\includegraphics[width=\\textwidth]{../py/kic_03335426_05_pixels.png}\n\\caption{\nThe ``lightcurves'' (flux \\foreign{vs} time) for 19 pixels near...HOGG\n\\label{fig:pixels}}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}\n\\includegraphics[width=\\textwidth]{../py/kic_03335426_05_images_owl.png}\n\\caption{\nThe top row shows example image patches (data $y_n$) from the \\project{Kepler} data on KIC XXXX in quarter XXXX.\nThe middle row shows the empirical mean image $\\hat{\\mu}$,\n  the diagonal elements of the empirical covariance matrix $\\hat{C}$,\n  and its dominant eigenvector.\nThe bottom row shows the pixel weights used in the official \\project{Kepler} SAP photometry,\n  and the OWL weights $\\hat{w}$.\nThe bottom-right panels shows the OWL weights times the empirical mean;\n  this shows the mean contributions of the individual pixels to the final OWL photometry.\n\\label{fig:images}}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}\n\\includegraphics[width=\\textwidth]{../py/kic_03335426_05_images_opw.png}\n\\caption{\nThe same as the bottom row of \\figurename~\\ref{fig:images}\n  but for the optimized positive-weight (OPW) photometry.\nIn this case, the positivity constraint does not make much difference.\n\\label{fig:images_opw}}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}\n\\includegraphics[width=\\textwidth]{../py/kic_03335426_05_photometry.png}\n\\caption{\nThe \\project{Kepler} SAP flux,\n  the Optimized-Weight Linear (OWL) photometry,\n  the Optimized Positive-Weight (OPW) photometry,\n  and the Tweaked Simple Aperture (TSA) photometry,\n  all for quarter 5 of KIC~3335426.\n\\label{fig:results}}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}\n\\includegraphics[width=\\textwidth]{../py/kic_03335426_05_diff_photometry.png}\n\\caption{\nThe \\project{Kepler} SAP flux,\n  the Difference-Optimized-Weight Linear (DOWL) photometry,\n  the Difference-Optimized Positive-Weight (DOPW) photometry,\n  and the Difference-Tweaked Simple Aperture (DTSA) photometry,\n  all for quarter 5 of KIC~3335426.\n\\label{fig:dresults}}\n\\end{figure}\n\n\\end{document}\n", "meta": {"hexsha": "e0e95e576a09d3313f45a24cd69069d7b319a9e8", "size": 38162, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/owl.tex", "max_stars_repo_name": "davidwhogg/OWL", "max_stars_repo_head_hexsha": "8b642885d374810908e3568923d76ca723afb56d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tex/owl.tex", "max_issues_repo_name": "davidwhogg/OWL", "max_issues_repo_head_hexsha": "8b642885d374810908e3568923d76ca723afb56d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-05-23T05:39:33.000Z", "max_issues_repo_issues_event_max_datetime": "2015-05-23T05:39:33.000Z", "max_forks_repo_path": "tex/owl.tex", "max_forks_repo_name": "davidwhogg/OWL", "max_forks_repo_head_hexsha": "8b642885d374810908e3568923d76ca723afb56d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.8820638821, "max_line_length": 113, "alphanum_fraction": 0.767962895, "num_tokens": 9441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3383967291557105}}
{"text": "\\section{Theorem proving using Isabelle}\n\\label{sec:background:theorem_proving_using_isabelle}\n\nAs mentioned before in \\cref{sec:introduction:validation} all formal proofs within this paper are verified within a theorem prover, sometimes also called a proof assistant. A theorem prover is a software solution to assist with the task of proving mathematical theorems. It achieves this goal by using automated reasoning and mathematical logic to provide the user with information on the correctness of the written proof. Furthermore, a theorem prover might have tools to prove simple theorems automatically.\n\nIn this thesis, the Isabelle proof assistant is used to prove the relevant theorems. Isabelle was chosen as theorem prover for several reasons:\n\\begin{itemize}\n    \\item Isabelle stays close to mathematical definitions while still maintaining much automation in the process, which is different from other theorem provers. A comparison of theorem provers has shown that most other theorem provers which stay close to the mathematical definition do not have much automation, and vice versa \\cite{wiedijk_comparing-provers}.\n    \\item Isabelle provides a plug-in to jEdit, a text editor, which deeply integrated Isabelle into the jEdit editor. This integration allows for interactively creating theories and checking proofs without the need to use the command-line application for this purpose.\n    \\item Isabelle has its own proof language Isar, which makes proofs more readable to the human reader, without giving up on automation and functionality for delivering proofs.\n    \\item One of the supervisors of this thesis has experience with Isabelle, meaning that there is local expertise available in case of problems.\n\\end{itemize}\n\nThe remaining part of this section will discuss different parts of Isabelle and its proof language Isar, to provide some background on theorem proofing in Isabelle.\n\n\\subsection{About Isabelle}\n\\label{subsec:background:theorem_proving_using_isabelle:about_isabelle}\nIsabelle \\cite{isabelle_2019} is a generic theorem prover written in \\textsc{ML}. It was originally developed at the University of Cambridge and Technische Universität München, but now includes numerous contributions from institutions and individuals worldwide. It has been designed to be able to support reasoning in several object-logics, which include but are not limited to:\n\\begin{itemize}\n    \\item first-order logic, constructive and classical versions (Isabelle/FOL)\n    \\item higher-order logic (Isabelle/HOL)\n    \\item Zermelo-Fraenkel set theory (Isabelle/ZF)\n\\end{itemize}\nIsabelle is distributed for free under a mix of open-source licenses, but the main code-base is subject to BSD-style regulations. More specifically, the binary distributions of Isabelle come with the 3-Clause BSD License \\cite{bsd3clause}.\n\nIsabelle has quite a large user base and a well-maintained community. Besides a mailing list for users, there is also a wiki \\cite{isabelle_wiki} and active support on StackOverflow, when questions are tagged under `isabelle' \\cite{isabelle_stack_overflow}.\n\nThe first release of Isabelle is published in 1986. Nowadays, it receives yearly releases with new updates. At the time of writing, Isabelle 2019 is the newest release, which is also the release used to prove the theorems in this thesis.\n\n\\subsection{Basics}\n\\label{subsec:background:theorem_proving_using_isabelle:basics}\nThis section will discuss some basics on Isabelle that are relevant for this thesis. The constructs mentioned here will not be discussed in much detail, as that would be a thesis on its own. The documentation provided with Isabelle does a decent job explaining all constructs in as much detail as possible.\n\n\\subsubsection{Theories}\nEach document in Isabelle is a \\textit{theory}, which can define a set of definitions, theorems and proofs. A theory can import other theories in order to reuse its definitions, theorems and proofs. An example of a theory is given in \\cref{appendix:example_isabelle_theory}. This theory is the actual formalisation of \\cref{defin:formalisations:global_definitions:multiplicity} in Isabelle used for this thesis. It will be used as an example throughout the remaining parts of this section.\n\n\\subsubsection{Datatypes}\nWithin an Isabelle theory, it is possible to define inductive datatypes. Inductive datatypes are the most used way to define new types in Isabelle. Famous data structures, such as lists, can be defined using datatypes.\n\nThe example provided in \\cref{appendix:example_isabelle_theory} defines a new datatype for the set $\\mathbb{N} \\cup {\\mstar}$. The definition is specified within the theory as:\n\\vspace{1em}\\begin{isabellebody}\n\\isacommand{datatype}\\isamarkupfalse%\n\\ {\\isasymM}\\ {\\isacharequal}\\ Star\\ {\\isacharbar}\\ Nr\\ nat\\isanewline\n\\end{isabellebody}\n\nThis example defines a datatype called \\isasymM{}, which can have two values: $Star$ and $Nr$. $Star$ and $Nr$ are called datatype constructors and can get arguments of different types. For example, the $Nr$ value gets an additional type, $nat$, which is Isabelle's type for representing natural numbers. On the other hand, the $Star$ constructor gets no additional arguments and is just a value for \\isasymM{} on itself.\n\nThe formalisation achieved here should be straightforward. $Star$ is used to denote $\\mstar$, the unbounded value, while $Nr\\ nat$ is used to denote a bounded value for a multiplicity.\n\n\\subsubsection{Record types}\nAnother way of defining new types within Isabelle is by using record types. A record can be defined using the \\textbf{record} keyword. The concept of a record is borrowed from programming languages, but it provides a way to define a named \\textit{n}-tuple. Effectively, a record type is a type consisting of multiple named fields that can each have a different type. Each field of a record can be accessed using its name.\n\nWithin this thesis, records are actively used to introduce types for type models, type graphs, instance models and instance graphs. These are all named-tuples which are easiest defined using records. Sadly, the example provided in \\cref{appendix:example_isabelle_theory} does not define such a record, therefore, we provide the record of an instance model (\\cref{defin:formalisations:ecore_formalisation:instance_models:instance_model}) here:\n\n\\vspace{1em}\\begin{isabellebody}\n\\isacommand{record}\\isamarkupfalse%\n\\ {\\isacharparenleft}{\\isacharprime}o{\\isacharcomma}\\ {\\isacharprime}nt{\\isacharparenright}\\ instance{\\isacharunderscore}model\\ {\\isacharequal}\\isanewline\n\\ \\ Tm\\ {\\isacharcolon}{\\isacharcolon}\\ {\\isachardoublequoteopen}{\\isacharparenleft}{\\isacharprime}nt{\\isacharparenright}\\ type{\\isacharunderscore}model{\\isachardoublequoteclose}\\isanewline\n\\ \\ Object\\ {\\isacharcolon}{\\isacharcolon}\\ {\\isachardoublequoteopen}{\\isacharprime}o\\ set{\\isachardoublequoteclose}\\isanewline\n\\ \\ ObjectClass\\ {\\isacharcolon}{\\isacharcolon}\\ {\\isachardoublequoteopen}{\\isacharprime}o\\ {\\isasymRightarrow}\\ {\\isacharprime}nt\\ Id{\\isachardoublequoteclose}\\isanewline\n\\ \\ ObjectId\\ {\\isacharcolon}{\\isacharcolon}\\ {\\isachardoublequoteopen}{\\isacharprime}o\\ {\\isasymRightarrow}\\ {\\isacharprime}nt{\\isachardoublequoteclose}\\isanewline\n\\ \\ FieldValue\\ {\\isacharcolon}{\\isacharcolon}\\ {\\isachardoublequoteopen}{\\isacharparenleft}{\\isacharprime}o\\ {\\isasymtimes}\\ {\\isacharparenleft}{\\isacharprime}nt\\ Id\\ {\\isasymtimes}\\ {\\isacharprime}nt{\\isacharparenright}{\\isacharparenright}\\ {\\isasymRightarrow}\\ {\\isacharparenleft}{\\isacharprime}o{\\isacharcomma}\\ {\\isacharprime}nt{\\isacharparenright}\\ ValueDef{\\isachardoublequoteclose}\\isanewline\n\\ \\ DefaultValue\\ {\\isacharcolon}{\\isacharcolon}\\ {\\isachardoublequoteopen}{\\isacharprime}nt\\ Id\\ {\\isasymRightarrow}\\ {\\isacharparenleft}{\\isacharprime}o{\\isacharcomma}\\ {\\isacharprime}nt{\\isacharparenright}\\ ValueDef{\\isachardoublequoteclose}%\n\\end{isabellebody}\n\nThe record of an instance model directly shows the structure. It has 6 named fields, the corresponding type model and the 5 elements defined in \\cref{defin:formalisations:ecore_formalisation:instance_models:instance_model}. Each of these fields has a corresponding type, corresponding to the type described within the definition of an instance model. This way, we have a direct formalisation of an instance graph in Isabelle.\n\n\\subsubsection{Type synonyms}\nIsabelle can form new types out of existing types by using generic types. For example, \\textit{list}s in Isabelle use this functionality. A list was created using a generic type that can be replaced with any concrete type on usage. For example `$nat\\ list$' would represent a list of natural numbers, and `\\isasymM$\\ list$' a list of elements of datatype \\isasymM.\n\nTo make it more convenient to use these types, it is possible to define these composed types as a type synonym. An example of such a type synonym is given in \\cref{appendix:example_isabelle_theory}:\n\n\\vspace{1em}\\begin{isabellebody}\n\\isacommand{type{\\isacharunderscore}synonym}\\isamarkupfalse%\n\\ multiplicity\\ {\\isacharequal}\\ {\\isachardoublequoteopen}{\\isasymM}\\ {\\isasymtimes}\\ {\\isasymM}{\\isachardoublequoteclose}\n\\end{isabellebody}\n\nThis type synonym defines the multiplicity type, effectively the formalisation of $\\mathbb{M}$ from \\cref{defin:formalisations:global_definitions:multiplicity}. It is a tuple of two elements of datatype \\isasymM, thus a tuple $\\mathbb{N} \\cup \\{\\mstar\\} \\times \\mathbb{N} \\cup \\{\\mstar\\}$. Using this type synonym, it is now possible to refer to the multiplicity type as `multiplicity'.\n\n\\subsubsection{Definitions and functions}\nIn an Isabelle theory, multiple definitions can be provided. The most basic definition can be created using the \\textbf{definition} keyword. Effectively, a \\textbf{definition} is simply an abbreviation, i.e. a new name for an existing construction.\n\nAn example of such a definition is the $upper$ definition in \\cref{appendix:example_isabelle_theory}:\n\\vspace{1em}\\begin{isabellebody}\n\\isacommand{definition}\\isamarkupfalse%\n\\ upper\\ {\\isacharcolon}{\\isacharcolon}\\ {\\isachardoublequoteopen}multiplicity\\ {\\isasymRightarrow}\\ {\\isasymM}{\\isachardoublequoteclose}\\ \\isakeyword{where}\\isanewline\n\\ \\ {\\isachardoublequoteopen}upper\\ m\\ {\\isasymequiv}\\ snd\\ m{\\isachardoublequoteclose}\n\\end{isabellebody}\n\nAs can be seen, the upper definition receives one argument $m$ of type `multiplicity', a multiplicity-tuple. It returns the upper bound of the multiplicity. In other words, it returns the second element of the tuple. This behaviour matches what the definition tells us, as $snd$ is the Isabelle function to return the second element of a tuple.\n\nBesides the \\textbf{definition} keyword, it is possible to give recursive function definitions using the \\textbf{fun} and \\textbf{function} keywords. An example of this is given as part of the linear order of \\isasymM{} in \\cref{appendix:example_isabelle_theory}:\n\\vspace{1em}\\begin{isabellebody}\n\\isacommand{fun}\\isamarkupfalse%\n\\ less{\\isacharunderscore}eq{\\isacharunderscore}{\\isasymM}\\ {\\isacharcolon}{\\isacharcolon}\\ {\\isachardoublequoteopen}{\\isasymM}\\ {\\isasymRightarrow}\\ {\\isasymM}\\ {\\isasymRightarrow}\\ bool{\\isachardoublequoteclose}\\ \\isakeyword{where}\\isanewline\n{\\isachardoublequoteopen}less{\\isacharunderscore}eq{\\isacharunderscore}{\\isasymM}\\ {\\isacharunderscore}\\ \\isactrlemph \\ {\\isacharequal}\\ True{\\isachardoublequoteclose}\\ {\\isacharbar}\\isanewline\n{\\isachardoublequoteopen}less{\\isacharunderscore}eq{\\isacharunderscore}{\\isasymM}\\ {\\isacharparenleft}\\isactrlbold a{\\isacharparenright}\\ {\\isacharparenleft}\\isactrlbold b{\\isacharparenright}\\ {\\isacharequal}\\ {\\isacharparenleft}a\\ {\\isasymle}\\ b{\\isacharparenright}{\\isachardoublequoteclose}\\ {\\isacharbar}\\ \\isanewline\n{\\isachardoublequoteopen}less{\\isacharunderscore}eq{\\isacharunderscore}{\\isasymM}\\ {\\isacharunderscore}\\ {\\isacharunderscore}\\ {\\isacharequal}\\ False{\\isachardoublequoteclose}\n\\end{isabellebody}\n\nThe function defined here, `less-eq-\\isasymM', defines the less than or equal to ($\\leq$) relation for \\isasymM. Effectively, the function describes that any value is always smaller or equal to $\\mstar$ and that two numbers (two instances of $Nr$) are only less or equal when the first number is less or equal to the second number.\n\nThe same function could also have been defined using the \\textbf{function} keyword, with the only difference that for the \\textbf{function} keyword, a proof for termination of the function must be provided manually. Using the \\textbf{fun} keyword, Isabelle will try to automatically proof termination of the function by using the specification. This automation is very powerful and works in a variety of functions (in fact, for all functions defined in this thesis, termination is proven automatically using \\textbf{fun}).\n\n\\subsubsection{Abbreviations and notation}\nAs can be seen from the `less-eq-\\isasymM' function in \\cref{appendix:example_isabelle_theory}, the $Nr$ and $Star$ constructors for \\isasymM{} are not used directly. Instead, numbers and a star symbol (\\isactrlemph) are used to respectively represent a value of $Nr$ and the $Star$ constructor. The use of these symbols has been achieved using the \\textbf{notation} keyword:\n\\vspace{1em}\\begin{isabellebody}\n\\isacommand{notation}\\isamarkupfalse%\n\\isanewline\n\\ \\ Star\\ {\\isacharparenleft}{\\isachardoublequoteopen}{\\isacharparenleft}\\isactrlemph {\\isacharparenright}{\\isachardoublequoteclose}\\ {\\isadigit{1}}{\\isadigit{0}}{\\isadigit{0}}{\\isadigit{0}}{\\isacharparenright}\\ \\isakeyword{and}\\isanewline\n\\ \\ Nr\\ {\\isacharparenleft}{\\isachardoublequoteopen}{\\isacharparenleft}\\isactrlbold {\\isacharunderscore}{\\isacharparenright}{\\isachardoublequoteclose}\\ {\\isacharbrackleft}{\\isadigit{1}}{\\isadigit{0}}{\\isadigit{0}}{\\isadigit{0}}{\\isacharbrackright}\\ {\\isadigit{1}}{\\isadigit{0}}{\\isadigit{0}}{\\isadigit{0}}{\\isacharparenright}\n\\end{isabellebody}\n\nThe notation keyword allows us to introduce a new notation for many different constructs, in this case, the $Star$ and $Nr$ constructors of \\isasymM. Custom notations are very powerful, as Isabelle automatically rewrites $Star$ and $Nr$ constructors back to this notation, so introducing this notation works in two ways. It can help to make theorems and proofs more readable, as can also be seen from the example in \\cref{appendix:example_isabelle_theory}.\n\nBesides the introduction of an alternative notation for existing constructs, it is also possible to introduce a new notation with the corresponding definition of what the notation means. Such a notation is achieved using the \\textbf{abbreviation} keyword. It has the same properties as the \\textbf{notation} keyword, but then for a newly defined definition. An example of this is given in \\cref{appendix:example_isabelle_theory}:\n\\vspace{1em}\\begin{isabellebody}\n\\isacommand{abbreviation}\\isamarkupfalse%\n\\ multiplicity{\\isacharunderscore}notation\\ {\\isacharcolon}{\\isacharcolon}\\ {\\isachardoublequoteopen}{\\isasymM}\\ {\\isasymRightarrow}\\ {\\isasymM}\\ {\\isasymRightarrow}\\ multiplicity{\\isachardoublequoteclose}\\ {\\isacharparenleft}{\\isachardoublequoteopen}{\\isacharparenleft}{\\isacharunderscore}{\\isacharslash}{\\isachardot}{\\isachardot}{\\isacharunderscore}{\\isacharparenright}{\\isachardoublequoteclose}\\ {\\isacharbrackleft}{\\isadigit{5}}{\\isadigit{2}}{\\isacharcomma}\\ {\\isadigit{5}}{\\isadigit{2}}{\\isacharbrackright}\\ {\\isadigit{5}}{\\isadigit{1}}{\\isacharparenright}\\ \\isakeyword{where}\\isanewline\n\\ \\ {\\isachardoublequoteopen}l{\\isachardot}{\\isachardot}u\\ {\\isasymequiv}\\ {\\isacharparenleft}l{\\isacharcomma}u{\\isacharparenright}{\\isachardoublequoteclose}\n\\end{isabellebody}\n\nThis example introduces a new notation for writing down a multiplicity tuple. It does so by writing the newly introduced notation on the left-hand side and writing the corresponding definition on the right-hand side. Although an \\textbf{abbreviation} looks the same as a \\textbf{definition}, they are different in the sense that \\textbf{abbreviation} only introduces a notation. To Isabelle, it is syntactic sugar, as internally, the notation does not exist. It is only used when representing constructs to the user. This behaviour is different from \\textbf{definition}, as definitions exist internally and are used by the proof reasoners.\n\nIt should be noted that there are shortcuts possible to introduce notations while defining a definition. An example of this is the `within{\\isacharunderscore}multiplicity' definition in \\cref{appendix:example_isabelle_theory}:\n\\vspace{1em}\\begin{isabellebody}\n\\isacommand{definition}\\isamarkupfalse%\n\\ within{\\isacharunderscore}multiplicity\\ {\\isacharcolon}{\\isacharcolon}\\ {\\isachardoublequoteopen}nat\\ {\\isasymRightarrow}\\ multiplicity\\ {\\isasymRightarrow}\\ bool{\\isachardoublequoteclose}\\ {\\isacharparenleft}\\isakeyword{infixl}\\ {\\isachardoublequoteopen}in{\\isachardoublequoteclose}\\ {\\isadigit{5}}{\\isadigit{0}}{\\isacharparenright}\\ \\isakeyword{where}\\isanewline\n\\ \\ {\\isachardoublequoteopen}n\\ in\\ m\\ {\\isasymequiv}\\ lower\\ m\\ {\\isasymle}\\ \\isactrlbold n\\ {\\isasymand}\\ \\isactrlbold n\\ {\\isasymle}\\ upper\\ m{\\isachardoublequoteclose}\\isanewline\n\\end{isabellebody}\n\nThis function uses the infix-left (\\textbf{infixl}) construction to define an infix notation for the definition. Just like the \\textbf{abbreviation} command, it is possible to use this definition on the left-hand side of the definition, for readability.\n\n\\subsubsection{Locales}\nWhen defining new types, there is no way to constrain the values for any of its elements. For example, for the `multiplicity' type, there is no way to prevent the second value of the tuple to be 0, since the natural numbers include 0. In Isabelle, functions and types are always total, and there is no way to exclude specific values of a type.\n\nA way to work around this is by using \\textbf{locale}s. Locales are Isabelle's approach for dealing with parametric theories. With locales, it is possible to define a context in which specific assumptions hold. An example of a locale is given in \\cref{appendix:example_isabelle_theory}:\n\\vspace{1em}\\begin{isabellebody}\n\\isacommand{locale}\\isamarkupfalse%\n\\ multiplicity\\ {\\isacharequal}\\ \\isakeyword{fixes}\\ mult\\ {\\isacharcolon}{\\isacharcolon}\\ {\\isachardoublequoteopen}multiplicity{\\isachardoublequoteclose}\\isanewline\n\\ \\ \\isakeyword{assumes}\\ lower{\\isacharunderscore}bound{\\isacharunderscore}valid{\\isacharbrackleft}simp{\\isacharbrackright}{\\isacharcolon}\\ {\\isachardoublequoteopen}lower\\ mult\\ {\\isasymnoteq}\\ \\isactrlemph {\\isachardoublequoteclose}\\isanewline\n\\ \\ \\isakeyword{assumes}\\ upper{\\isacharunderscore}bound{\\isacharunderscore}valid{\\isacharcolon}\\ {\\isachardoublequoteopen}upper\\ mult\\ {\\isasymnoteq}\\ \\isactrlbold {\\isadigit{0}}{\\isachardoublequoteclose}\\isanewline\n\\ \\ \\isakeyword{assumes}\\ properly{\\isacharunderscore}bounded{\\isacharbrackleft}simp{\\isacharbrackright}{\\isacharcolon}\\ {\\isachardoublequoteopen}lower\\ mult\\ {\\isasymle}\\ upper\\ mult{\\isachardoublequoteclose}\n\\end{isabellebody}\n\nThis example introduces the multiplicity locale. Within this locale, we introduce a named-construct `mult', which is a multiplicity. Then we make some assumptions which hold in the context of a multiplicity. In this case,  there are three assumptions. First of all, there are assumptions on the lower and upper bound, excluding specific (but invalid) values. The final assumption captures that the lower bound is always smaller or equal to the upper bound.\n\nWith this locale in place, it is possible to prove theorems and lemmas within the context of a multiplicity. That means that when proving theorems and lemmas within the multiplicity context, all introduced assumptions for `mult' hold:\n\\vspace{1em}\\begin{isabellebody}\n\\isacommand{context}\\isamarkupfalse%\n\\ multiplicity\\isanewline\n\\isakeyword{begin}\\isanewline\n\\isanewline\n\\isacommand{lemma}\\isamarkupfalse%\n\\ upper{\\isacharunderscore}bound{\\isacharunderscore}valid{\\isacharunderscore}alt{\\isacharbrackleft}simp{\\isacharbrackright}{\\isacharcolon}\\ {\\isachardoublequoteopen}upper\\ mult\\ {\\isasymge}\\ \\isactrlbold {\\isadigit{1}}{\\isachardoublequoteclose}\\isanewline\n%\n\\isadelimproof\n\\ \\ %\n\\endisadelimproof\n%\n\\isatagproof\n\\isacommand{using}\\isamarkupfalse%\n\\ less{\\isacharunderscore}{\\isasymM}{\\isachardot}elims\\ not{\\isacharunderscore}less\\ upper{\\isacharunderscore}bound{\\isacharunderscore}valid\\ \\isacommand{by}\\isamarkupfalse%\n\\ fastforce%\n\\endisatagproof\n{\\isafoldproof}%\n%\n\\isadelimproof\n\\isanewline\n%\n\\endisadelimproof\n\\isanewline\n\\isacommand{end}\\isamarkupfalse%\n\\end{isabellebody}\n\nIn above example, it is possible to prove that `$upper\\ mult \\geq 1$ because the assumptions ensure that `$upper\\ mult \\not= 0$'. Since natural numbers cannot be negative, we have that `$upper\\ mult \\geq 1$. This theorem can only be proven within the multiplicity context, as otherwise, the assumptions do not hold, and `$upper\\ mult$' might be $0$.\n\nWithin this thesis, \\textbf{locale}s are mostly used to denote valid constructs, such as a valid type graph, type model, instance graph or instance model. These locales limit the respective \\textbf{record} types for these constructs by assuming the validity constraints presented in their respective sections.\n\n\\subsubsection{Theorems and proofs}\nTheorems (also called lemmas) are statements that can be proven correct. For this thesis, all theorems are either defined using the \\textbf{theorem} or \\textbf{lemma} keywords in Isabelle. A theorem can be defined to be only valid under certain assumptions or can be defined to be true without any assumptions.\n\nAn example of a simple \\textbf{theorem} can be found in \\cref{appendix:example_isabelle_theory}:\n\\vspace{1em}\\begin{isabellebody}\n\\isacommand{theorem}\\isamarkupfalse%\n\\ mult{\\isacharunderscore}zero{\\isacharunderscore}unbounded{\\isacharunderscore}valid{\\isacharbrackleft}simp{\\isacharbrackright}{\\isacharcolon}\\ {\\isachardoublequoteopen}n\\ in\\ \\isactrlbold {\\isadigit{0}}{\\isachardot}{\\isachardot}\\isactrlemph {\\isachardoublequoteclose}\\isanewline\n%\n\\isadelimproof\n\\ \\ %\n\\endisadelimproof\n%\n\\isatagproof\n\\isacommand{unfolding}\\isamarkupfalse%\n\\ within{\\isacharunderscore}multiplicity{\\isacharunderscore}def\\isanewline\n\\ \\ \\isacommand{by}\\isamarkupfalse%\n\\ simp%\n\\endisatagproof\n{\\isafoldproof}%\n%\n\\isadelimproof\n\\end{isabellebody}\n\nThis theorem states that for a multiplicity $0..\\mstar$, any natural number is within bounds (any $n$ is in $0..\\mstar$). It can easily be proven using the definition of a natural number within a multiplicity.\n\nA proof for a theorem is written directly after the statement. It can either be a short proof using apply-scripts, or a proof within Isabelle's proof language Isar. In the example above, it is a short proof using apply-scripts. In this case, the proof is done within one step: by simplification of the definition.\n\nOnce lemmas or theorems are proven, they can be used in the proof of other lemmas and statements. Reusing them is done by referring to them manually, or by adding them to a set of lemmas and theorems that Isabelle will try by default. Adding theorems to a set of default rules is done by adding a specific keyword. For example, add $[simp]$ to add the theorem to the set of simplification rules, or add $[intro]$ or $[elim]$, to specify the theorem to be an introduction rule or elimination rule. Introduction and elimination rules will not be further specified here; more information on these can be found in the Isabelle documentation.\n\n\\subsubsection{Isar}\n\\textit{Isar} stands for \\textit{Intelligible semi-automated reasoning}, and is an interpreted language environment for structured formal proof documents. It allows to write down mostly humanly readable proofs in Isabelle while still getting the advantage of semi-automated reasoning. Isar is built on the principle of writing down multiple steps of the proof, doing less automation, in favour of readability. As a consequence, writing Isar proofs is more work for the writer of the proof but eventually results in better humanly readable proofs that also have value without the automated reasoning of a theorem prover.\n\nThis section will not discuss the full Isar environment in detail. The Isabelle/Isar Reference Manual \\cite{wenzel-isabelle_isar}, included with each copy of Isabelle, already contains a very detailed explanation of all features that Isar has to offer. Instead, we consider a small example of a proof written in Isar, picked directly from \\cref{appendix:example_isabelle_theory}:\n\\vspace{1em}\\begin{isabellebody}\n\\isatagproof\n\\isacommand{proof}\\isamarkupfalse%\n\\isanewline\n\\ \\ \\isacommand{fix}\\isamarkupfalse%\n\\ x\\ y\\ z\\ {\\isacharcolon}{\\isacharcolon}\\ {\\isasymM}\\isanewline\n\\ \\ \\isacommand{show}\\isamarkupfalse%\n\\ {\\isachardoublequoteopen}{\\isacharparenleft}x\\ {\\isacharless}\\ y{\\isacharparenright}\\ {\\isacharequal}\\ {\\isacharparenleft}x\\ {\\isasymle}\\ y\\ {\\isasymand}\\ {\\isasymnot}\\ y\\ {\\isasymle}\\ x{\\isacharparenright}{\\isachardoublequoteclose}\\isanewline\n\\ \\ \\isacommand{proof}\\isamarkupfalse%\n\\ {\\isacharparenleft}induction\\ x\\ arbitrary{\\isacharcolon}\\ y{\\isacharparenright}\\isanewline\n\\ \\ \\ \\ \\isacommand{case}\\isamarkupfalse%\n\\ Star\\isanewline\n\\ \\ \\ \\ \\isacommand{then}\\isamarkupfalse%\n\\ \\isacommand{show}\\isamarkupfalse%\n\\ {\\isacharquery}case\\ \\isacommand{by}\\isamarkupfalse%\n\\ simp{\\isacharunderscore}all\\isanewline\n\\ \\ \\isacommand{next}\\isamarkupfalse%\n\\isanewline\n\\ \\ \\ \\ \\isacommand{case}\\isamarkupfalse%\n\\ {\\isacharparenleft}Nr\\ x{\\isacharparenright}\\isanewline\n\\ \\ \\ \\ \\isacommand{then}\\isamarkupfalse%\n\\ \\isacommand{show}\\isamarkupfalse%\n\\ {\\isacharquery}case\\ \\isacommand{by}\\isamarkupfalse%\n\\ {\\isacharparenleft}cases\\ y{\\isacharparenright}\\ auto\\isanewline\n\\ \\ \\isacommand{qed}\\isamarkupfalse%\n\\isanewline\n\\isanewline\n\\ \\ \\isacommand{show}\\isamarkupfalse%\n\\ {\\isachardoublequoteopen}x\\ {\\isasymle}\\ x{\\isachardoublequoteclose}\\ \\isacommand{by}\\isamarkupfalse%\n\\ {\\isacharparenleft}induction\\ x{\\isacharparenright}\\ simp{\\isacharunderscore}all\\isanewline\n\\ \\ \\isacommand{then}\\isamarkupfalse%\n\\ \\isacommand{show}\\isamarkupfalse%\n\\ {\\isachardoublequoteopen}x\\ {\\isasymle}\\ y\\ {\\isasymLongrightarrow}\\ y\\ {\\isasymle}\\ x\\ {\\isasymLongrightarrow}\\ x\\ {\\isacharequal}\\ y{\\isachardoublequoteclose}\\isanewline\n\\ \\ \\isacommand{proof}\\isamarkupfalse%\n\\ {\\isacharparenleft}induction\\ x\\ arbitrary{\\isacharcolon}\\ y{\\isacharparenright}\\isanewline\n\\ \\ \\ \\ \\isacommand{case}\\isamarkupfalse%\n\\ Star\\isanewline\n\\ \\ \\ \\ \\isacommand{then}\\isamarkupfalse%\n\\ \\isacommand{show}\\isamarkupfalse%\n\\ {\\isacharquery}case\\ \\isacommand{by}\\isamarkupfalse%\n\\ {\\isacharparenleft}cases\\ y{\\isacharparenright}\\ simp{\\isacharunderscore}all\\isanewline\n\\ \\ \\isacommand{next}\\isamarkupfalse%\n\\isanewline\n\\ \\ \\ \\ \\isacommand{case}\\isamarkupfalse%\n\\ {\\isacharparenleft}Nr\\ x{\\isacharparenright}\\isanewline\n\\ \\ \\ \\ \\isacommand{then}\\isamarkupfalse%\n\\ \\isacommand{show}\\isamarkupfalse%\n\\ {\\isacharquery}case\\ \\isacommand{by}\\isamarkupfalse%\n\\ {\\isacharparenleft}cases\\ y{\\isacharparenright}\\ simp{\\isacharunderscore}all\\isanewline\n\\ \\ \\isacommand{qed}\\isamarkupfalse%\n\\isanewline\n\\isanewline\n\\ \\ \\isacommand{show}\\isamarkupfalse%\n\\ {\\isachardoublequoteopen}x\\ {\\isasymle}\\ y\\ {\\isasymLongrightarrow}\\ y\\ {\\isasymle}\\ z\\ {\\isasymLongrightarrow}\\ x\\ {\\isasymle}\\ z{\\isachardoublequoteclose}\\isanewline\n\\ \\ \\isacommand{proof}\\isamarkupfalse%\n\\ {\\isacharparenleft}induction\\ x\\ arbitrary{\\isacharcolon}\\ y\\ z{\\isacharparenright}\\isanewline\n\\ \\ \\ \\ \\isacommand{case}\\isamarkupfalse%\n\\ Star\\isanewline\n\\ \\ \\ \\ \\isacommand{then}\\isamarkupfalse%\n\\ \\isacommand{show}\\isamarkupfalse%\n\\ {\\isacharquery}case\\ \\isacommand{by}\\isamarkupfalse%\n\\ {\\isacharparenleft}cases\\ y{\\isacharparenright}\\ simp{\\isacharunderscore}all\\isanewline\n\\ \\ \\isacommand{next}\\isamarkupfalse%\n\\isanewline\n\\ \\ \\ \\ \\isacommand{case}\\isamarkupfalse%\n\\ {\\isacharparenleft}Nr\\ x{\\isacharparenright}\\isanewline\n\\ \\ \\ \\ \\isacommand{then}\\isamarkupfalse%\n\\ \\isacommand{show}\\isamarkupfalse%\n\\ {\\isacharquery}case\\isanewline\n\\ \\ \\ \\ \\isacommand{proof}\\isamarkupfalse%\n\\ {\\isacharparenleft}induction\\ y\\ arbitrary{\\isacharcolon}\\ z{\\isacharparenright}\\isanewline\n\\ \\ \\ \\ \\ \\ \\isacommand{case}\\isamarkupfalse%\n\\ Star\\isanewline\n\\ \\ \\ \\ \\ \\ \\isacommand{then}\\isamarkupfalse%\n\\ \\isacommand{show}\\isamarkupfalse%\n\\ {\\isacharquery}case\\ \\isacommand{by}\\isamarkupfalse%\n\\ {\\isacharparenleft}cases\\ z{\\isacharparenright}\\ simp{\\isacharunderscore}all\\isanewline\n\\ \\ \\ \\ \\isacommand{next}\\isamarkupfalse%\n\\isanewline\n\\ \\ \\ \\ \\ \\ \\isacommand{case}\\isamarkupfalse%\n\\ {\\isacharparenleft}Nr\\ x{\\isacharparenright}\\isanewline\n\\ \\ \\ \\ \\ \\ \\isacommand{then}\\isamarkupfalse%\n\\ \\isacommand{show}\\isamarkupfalse%\n\\ {\\isacharquery}case\\ \\isacommand{by}\\isamarkupfalse%\n\\ {\\isacharparenleft}cases\\ z{\\isacharparenright}\\ simp{\\isacharunderscore}all\\isanewline\n\\ \\ \\ \\ \\isacommand{qed}\\isamarkupfalse%\n\\isanewline\n\\ \\ \\isacommand{qed}\\isamarkupfalse%\n\\isanewline\n\\isanewline\n\\ \\ \\isacommand{show}\\isamarkupfalse%\n\\ {\\isachardoublequoteopen}x\\ {\\isasymle}\\ y\\ {\\isasymor}\\ y\\ {\\isasymle}\\ x{\\isachardoublequoteclose}\\isanewline\n\\ \\ \\isacommand{proof}\\isamarkupfalse%\n\\ {\\isacharparenleft}induction\\ x\\ arbitrary{\\isacharcolon}\\ y{\\isacharparenright}\\isanewline\n\\ \\ \\ \\ \\isacommand{case}\\isamarkupfalse%\n\\ Star\\isanewline\n\\ \\ \\ \\ \\isacommand{then}\\isamarkupfalse%\n\\ \\isacommand{show}\\isamarkupfalse%\n\\ {\\isacharquery}case\\ \\isacommand{by}\\isamarkupfalse%\n\\ simp\\isanewline\n\\ \\ \\isacommand{next}\\isamarkupfalse%\n\\isanewline\n\\ \\ \\ \\ \\isacommand{case}\\isamarkupfalse%\n\\ {\\isacharparenleft}Nr\\ x{\\isacharparenright}\\isanewline\n\\ \\ \\ \\ \\isacommand{then}\\isamarkupfalse%\n\\ \\isacommand{show}\\isamarkupfalse%\n\\ {\\isacharquery}case\\ \\isacommand{by}\\isamarkupfalse%\n\\ {\\isacharparenleft}cases\\ y{\\isacharparenright}\\ auto\\isanewline\n\\ \\ \\isacommand{qed}\\isamarkupfalse%\n\\isanewline\n\\isacommand{qed}\\isamarkupfalse%\n%\n\\endisatagproof\n{\\isafoldproof}%\n%\n\\isadelimproof\n%\n\\endisadelimproof\n\\end{isabellebody}\n\nIn this example, we see the proof that proves that type \\isasymM{} is an instantiation of a linear order. In order to show that type \\isasymM{} gives rise to a linear order, we have to proof multiple subgoals, which are:\n\\begin{itemize}\n    \\item Correctness of $<$: $(x < y) = (x \\leq y \\land \\lnot y \\leq x)$\n    \\item Reflexivity of $\\leq$: $(x \\leq x)$\n    \\item Transitivity of $\\leq$: $x \\leq y \\land y \\leq z \\implies x \\leq z$\n    \\item Correctness of the linear order: $x \\leq y \\lor y \\leq x$\n\\end{itemize}\nEach of these subgoals is proven separately within the Isar proof. The proof of each subgoal is defined by the \\textbf{show} keyword. Important to see from the example above is that each subgoal is proven using a nested subproof. Such subproofs can be written as apply-scripts, or using a nested Isar proof, as we see in the example above.\n\n\\subsubsection{Proof tactics}\nIn order to deliver proofs, we make use of automated reasoning. Essential aspects of automated reasoning are the different proof tactics in Isabelle. Proof tactics can be applied to a proof goal to either solve the proof goal entirely or to somehow make the goal simpler to solve.\n\nA vital proof tactic shown in the example above is `induction'. This tactic applies mathematical induction to the proof goal, splitting the goal into new subgoals that follow the structure of mathematical induction. \n\nThe following proof tactics are extensively used within this thesis:\n\\begin{itemize}\n    \\item `induction' (also called `induct'): Applies mathematical induction to the proof goal. Splits the subgoal into two or more subgoals that follow the structure of mathematical induction.\n    \\item `cases': Applies a case distinction to the proof goal. It will split the proof goal into multiple subgoals, one for each applicable case. This proof tactic works especially well for inductive definitions and datatypes with a finite set of possible values.\n    \\item `intro': Splits a proof goal and introduces new subgoals based on an introduction rule. An important example of an introduction rule is $conjI$, which splits a proof goal of $A \\land B$ into the two subgoals $A$ and $B$.\n    \\item `elim': Splits a proof goal by eliminating operations and relations and providing smaller subgoals instead of those. For example, the elimination rule $disjE$ splits a proof goal of the form $A \\lor B \\implies C$ into two subgoals, $A \\implies C$ and $B \\implies C$.\n    \\item `simp' (and `simp\\_all'): Apply simplification to a proof goal in order to solve the problem completely. It uses simplification rules to rewrite the statement until it arrives at `True', finishing the proof.\n    \\item `fastforce': Solves the proof goal by using a tactic similar to brute force. It tries all possible outcomes but tries to be smart by excluding similar cases.\n    \\item `fast': A classical solver which solves the proof goal by structurally checking cases based on a depth-first search algorithm. Not frequently used within this thesis.\n    \\item `auto': A combination of `simp' and `fastforce', which can also use introduction rules and elimination rules when rewriting. In general, this proof tactic more powerful than `simp' and `fastforce'.\n    \\item `blast': Solves the proof goal by using a semantic tableau. Frequently used for solving logic problems.\n    \\item `metis': Solves the proof goal by using resolution. Frequently used for more complex logic problems that cannot be solved by `blast'.\n\\end{itemize}\n\nIsabelle is not limited to the above-discussed proof tactics, but these tactics are the most important ones for this thesis. Other tactics are not used either because they apply to a different kind of problem (number arithmetic instead of logic, for example) or because they are not transparent in solving their problem. For example, the `smt' proof tactic solves a problem by using an external SMT solver. Although these proof tactics can solve many problems, it is not transparent to the reader what steps the SMT solver has taken to solve the problem, as opposed to the proof tactics described above. Therefore these tactics have been excluded.\n\n\\subsection{Archive of Formal Proofs}\nIsabelle has an Archive of Formal Proofs (AFP), which is a collection of proof libraries, examples, and larger scientific developments, mechanically checked in the theorem prover Isabelle. All theories within this archive are organised in the way of a scientific journal such that they can be referred to by new theories.\n\n\\subsubsection{Graph Theory}\nThe Isabelle AFP submission Graph Theory \\cite{noschinski-graph_theory} is used as part of this thesis. This submission to the Isabelle AFP is a formalization of directed graphs, supporting labelled multi-edges and infinite graphs. Theorems proven for these graphs include, but are not limited to, walks, cyclicity, connectedness and some properties of isomorphisms. All the theorems proven as part of this submission are discussed in \\cite{bang-jensen_gutin_2010}.\n\nWithin this thesis, the submission is used as part of the GROOVE formalisation within Isabelle. Within the GROOVE formalisation, GROOVE type graphs and instance graphs are extensions of the directed graph introduced by the Graph Theory submission. This allows Isabelle to apply theorems proven for graphs within this submission to GROOVE graphs presented in the theories of this thesis.\n\nWithin this thesis, only a small selected set of theorems from the submission is used. This set mostly includes theorems related to walks and cyclicity of graphs. These theorems are used to show the acyclicity of the containment relation for instance graphs.\n", "meta": {"hexsha": "5523d876a054f4b7c65588f810fc79b8a29367ff", "size": 35466, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/tex/02_background/03_theorem_proving_using_isabelle.tex", "max_stars_repo_name": "RemcodM/thesis-ecore-groove-formalisation", "max_stars_repo_head_hexsha": "a0e860c4b60deb2f3798ae2ffc09f18a98cf42ca", "max_stars_repo_licenses": ["AFL-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thesis/tex/02_background/03_theorem_proving_using_isabelle.tex", "max_issues_repo_name": "RemcodM/thesis-ecore-groove-formalisation", "max_issues_repo_head_hexsha": "a0e860c4b60deb2f3798ae2ffc09f18a98cf42ca", "max_issues_repo_licenses": ["AFL-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis/tex/02_background/03_theorem_proving_using_isabelle.tex", "max_forks_repo_name": "RemcodM/thesis-ecore-groove-formalisation", "max_forks_repo_head_hexsha": "a0e860c4b60deb2f3798ae2ffc09f18a98cf42ca", "max_forks_repo_licenses": ["AFL-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 95.3387096774, "max_line_length": 647, "alphanum_fraction": 0.7900242486, "num_tokens": 9831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.33839672183461544}}
{"text": "% Like most advanced LaTeX files, this one begins with a lot of\n% boilerplate. You don't need to understand (or even read) most of it.\n% All you need to do is fill in your name, UMN ID, email address,\n% and the number of the pset. (Search for \"METADATA\" to find the place\n% for this.) Then, you can go straight to the \"EXERCISE 1\"\n% section and start writing your solutions.\n% The \"VARIOUS USEFUL COMMANDS\" section is probably worth taking a\n% look at at some point.\n\n%----------------------------------------------------------------------------------------\n%\tPACKAGES AND OTHER DOCUMENT CONFIGURATIONS\n%----------------------------------------------------------------------------------------\n\\documentclass[paper=a4, fontsize=12pt]{scrartcl} % A4 paper and 12pt font size\n\\usepackage[T1]{fontenc} % Use 8-bit encoding that has 256 glyphs\n\\usepackage[english]{babel} % English language/hyphenation\n\\usepackage{amsmath,amsfonts,amsthm,amssymb} % Math packages\n\\usepackage{mathrsfs}    % More math packages\n\\usepackage{sectsty}  % Allows customizing section commands\n\\allsectionsfont{\\centering \\normalfont\\scshape} % Make all section titles centered, the default font and small caps %remove this to left align section tites\n\\usepackage{hyperref} % Turns cross-references into hyperlinks,\n                      % and defines \\url and \\href commands.\n\\usepackage{graphicx} % For embedding graphics files.\n\\usepackage{framed}   % For the \"leftbar\" environment used below.\n\\usepackage{ifthen}   % Used for the \\powset command below.\n\\usepackage{lastpage} % for counting the number of pages\n\\usepackage[headsepline,footsepline,manualmark]{scrlayer-scrpage}\n\\usepackage[height=10in,a4paper,hmargin={1in,0.8in}]{geometry}\n\\usepackage[usenames,dvipsnames]{xcolor}\n\\usepackage{tikz}     % This is a powerful tool to draw vector\n                      % graphics inside LaTeX. In particular, you can\n                      % use it to draw graphs.\n\\usepackage{verbatim} % For the \"verbatim\" environment, in which\n                      % special symbols can be used freely without\n                      % confusing the compiler. (And it's typeset in\n                      % a constant-width font.)\n                      % Useful, e.g., for quoting code (or ASCII art).\n\n%\\numberwithin{table}{section} % Number tables within sections (i.e. 1.1, 1.2, 2.1, 2.2 instead of 1, 2, 3, 4)\n\n\\setlength\\parindent{20pt} % Makes indentation for paragraphs longer.\n                           % This makes paragraphs stand out more.\n\n%----------------------------------------------------------------------------------------\n%\tVARIOUS USEFUL COMMANDS\n%----------------------------------------------------------------------------------------\n% The commands below might be convenient. For example, you probably\n% prefer to write $\\powset[2]{V}$ for the set of $2$-element subsets\n% of $V$, rather than writing $\\mathcal{P}_2(V)$.\n% Notice that you can easily define your own commands like this.\n% Caveat: Some of these commands need to be properly \"guarded\" when\n% they occur in subscripts or superscripts. So you should not write\n% $K_\\CC$, but rather $K_{\\CC}$.\n\\newcommand{\\CC}{\\mathbb{C}} % complex numbers\n\\newcommand{\\RR}{\\mathbb{R}} % real numbers\n\\newcommand{\\QQ}{\\mathbb{Q}} % rational numbers\n\\newcommand{\\NN}{\\mathbb{N}} % nonnegative integers\n\\newcommand{\\PP}{\\mathbb{P}} % positive integers\n\\newcommand{\\KK}{\\mathbb{K}} % my favorite notation for a commutative ring\n\\newcommand{\\Z}[1]{\\mathbb{Z}/#1\\mathbb{Z}} % integers modulo k\n                                            % (syntax: \"\\Z{k}\")\n\\newcommand{\\ZZ}{\\mathbb{Z}} % integers\n\\newcommand{\\id}{\\operatorname{id}} % identity map\n\\newcommand{\\lcm}{\\operatorname{lcm}}\n% Lowest common multiple. For historical reasons, LaTeX has a \\gcd\n% command built in, but not an \\lcm command. The preceding line\n% rectifies that.\n\\newcommand{\\set}[1]{\\left\\{ #1 \\right\\}}\n% $\\set{...}$ compiles to {...} (set-brackets).\n\\newcommand{\\abs}[1]{\\left| #1 \\right|}\n% $\\abs{...}$ compiles to |...| (absolute value, or size of a set).\n\\newcommand{\\tup}[1]{\\left( #1 \\right)}\n% $\\tup{...}$ compiles to (...) (parentheses, or tuple-brackets).\n\\newcommand{\\ive}[1]{\\left[ #1 \\right]}\n% $\\ive{...}$ compiles to [...] (Iverson bracket, aka truth value; also, set of first n integers).\n\\newcommand{\\floor}[1]{\\left\\lfloor #1 \\right\\rfloor}\n% $\\floor{...}$ compiles to |_..._| (floor function).\n\\newcommand{\\underbrack}[2]{\\underbrace{#1}_{\\substack{#2}}}\n% $\\underbrack{...1}{...2}$ yields\n% $\\underbrace{...1}_{\\substack{...2}}$. This is useful for doing\n% local rewriting transformations on mathematical expressions with\n% justifications. For example, try this out:\n% $ \\underbrack{(a+b)^2}{= a^2 + 2ab + b^2 \\\\ \\text{(by the binomial formula)}} $\n\\newcommand{\\powset}[2][]{\\ifthenelse{\\equal{#2}{}}{\\mathcal{P}\\left(#1\\right)}{\\mathcal{P}_{#1}\\left(#2\\right)}}\n% $\\powset[k]{S}$ stands for the set of all $k$-element subsets of\n% $S$. The argument $k$ is optional, and if not provided, the result\n% is the whole powerset of $S$.\n\\newcommand{\\calF}{\\mathcal{F}}\n\\newcommand{\\horrule}[1]{\\rule{\\linewidth}{#1}} % Create horizontal rule command with 1 argument of height\n\\newcommand{\\nnn}{\\nonumber\\\\} % Don't number this line in an \"align\" environment, and move on to the next line.\n\n%----------------------------------------------------------------------------------------\n%\tMAKING SUMMATION SIGNS ALWAYS PUT THEIR BOUNDS ABOVE AND BELOW\n%\tTHE SIGN\n%----------------------------------------------------------------------------------------\n% The following are hacks to ensure that sums (such as\n% $\\sum_{k=1}^n k$) always put their bounds (i.e., the $k=1$ and the\n% $n$) underneath and above the sign, as opposed to on its right.\n% Same for products (\\prod), set unions (\\bigcup) and set\n% intersections (\\bigcap). Remove the 8 lines below if you do not want\n% this behavior.\n\\let\\sumnonlimits\\sum\n\\let\\prodnonlimits\\prod\n\\let\\cupnonlimits\\bigcup\n\\let\\capnonlimits\\bigcap\n\\renewcommand{\\sum}{\\sumnonlimits\\limits}\n\\renewcommand{\\prod}{\\prodnonlimits\\limits}\n\\renewcommand{\\bigcup}{\\cupnonlimits\\limits}\n\\renewcommand{\\bigcap}{\\capnonlimits\\limits}\n\n%----------------------------------------------------------------------------------------\n%\tENVIRONMENTS\n%----------------------------------------------------------------------------------------\n% The incantations below define how theorem environments\n% (\\begin{theorem} ... \\end{theorem}) and their likes will look like.\n\\newtheoremstyle{plainsl}% <name>\n  {8pt plus 2pt minus 4pt}% <Space above>\n  {8pt plus 2pt minus 4pt}% <Space below>\n  {\\slshape}% <Body font>\n  {0pt}% <Indent amount>\n  {\\bfseries}% <Theorem head font>\n  {.}% <Punctuation after theorem head>\n  {5pt plus 1pt minus 1pt}% <Space after theorem headi>\n  {}% <Theorem head spec (can be left empty, meaning `normal')>\n\n% Environments which make the text inside them slanted:\n\\theoremstyle{plainsl}\n  \\newtheorem{theorem}{Theorem}[section]\n  \\newtheorem{proposition}[theorem]{Proposition}\n  \\newtheorem{lemma}[theorem]{Lemma}\n  \\newtheorem{corollary}[theorem]{Corollary}\n  \\newtheorem{conjecture}[theorem]{Conjecture}\n% Environments that don't:\n\\theoremstyle{definition}\n  \\newtheorem{definition}[theorem]{Definition}\n  \\newtheorem{example}[theorem]{Example}\n  \\newtheorem{exercise}[theorem]{Exercise}\n  \\newtheorem{examples}[theorem]{Examples}\n  \\newtheorem{algorithm}[theorem]{Algorithm}\n  \\newtheorem{question}[theorem]{Question}\n \\theoremstyle{remark}\n  \\newtheorem{remark}[theorem]{Remark}\n\\newenvironment{statement}{\\begin{quote}}{\\end{quote}}\n\\newenvironment{fineprint}{\\begin{small}}{\\end{small}}\n\n%----------------------------------------------------------------------------------------\n%\tMETADATA\n%----------------------------------------------------------------------------------------\n\\newcommand{\\myname}{Darij Grinberg} % ENTER YOUR NAME HERE\n\\newcommand{\\myid}{00000000} % ENTER YOUR UMN ID HERE\n\\newcommand{\\mymail}{dgrinber@umn.edu} % ENTER YOUR EMAIL HERE\n\\newcommand{\\psetnumber}{2} % ENTER THE NUMBER OF THIS PSET HERE\n\n%----------------------------------------------------------------------------------------\n%\tHEADER AND FOOTER\n%----------------------------------------------------------------------------------------\n\\ihead{Solutions to midterm \\#\\psetnumber} % Page header left\n\\ohead{page \\thepage\\ of \\pageref{LastPage}} % Page header right\n\\ifoot{\\myname, \\myid} % left footer\n\\ofoot{\\mymail} % right footer\n\n%----------------------------------------------------------------------------------------\n%\tTITLE SECTION\n%----------------------------------------------------------------------------------------\n\\title{\t\n\\normalfont \\normalsize \n\\textsc{University of Minnesota, School of Mathematics} \\\\ [25pt] % Your university, school and/or department name(s)\n\\horrule{0.5pt} \\\\[0.4cm] % Thin top horizontal rule\n\\huge Math 4281: Introduction to Modern Algebra, \\\\\nSpring 2019:\nMidterm \\psetnumber\\\\% The assignment title\n\\horrule{2pt} \\\\[0.5cm] % Thick bottom horizontal rule\n}\n\\author{\\myname}\n\n\\begin{document}\n\n\\maketitle % Print the title\n\n\\begin{center} % Delete this if you want to save space!\n{\\large due date: \\textbf{Friday, 12 April 2019} at the beginning of class, \\\\\nor before that through Canvas.\n\n\\textbf{No collaboration allowed} -- this is a midterm.\n\nPlease solve \\textbf{at most 3 of the 6 exercises}!}\n\\end{center}\n\n%----------------------------------------------------------------------------------------\n%\tEXERCISE 1\n%----------------------------------------------------------------------------------------\n\\horrule{0.3pt} \\\\[0.4cm]\n\n\\section{Exercise 1: Not-quite-all-rationals}\n\n\\subsection{Problem}\n\nFix an integer $m$.\nAn \\textit{$m$-integer} shall mean a rational number\n$r$ such that there exists a $k \\in \\NN$ satisfying\n$m^k r \\in \\ZZ$.\n\nFor example\\footnote{You don't need to prove these.}:\n\\begin{itemize}\n \\item Each integer $r$ is an $m$-integer (since $m^k r \\in \\ZZ$\n       for $k = 0$).\n \\item The rational number $\\dfrac{5}{12}$\n       is a $6$-integer (since $6^k \\cdot \\dfrac{5}{12} \\in \\ZZ$\n       for $k = 2$), but neither a $2$-integer nor a $3$-integer\n       (since multiplying it by a power of $2$ will not ``get\n       rid of'' the prime factor $3$ in the denominator, and\n       vice versa\\footnote{You would have to be more rigorous\n       than this in your solution, if you were to make an\n       argument like this.}).\n \\item The $1$-integers are the integers (since $1^k r = r$\n       for all $r$).\n \\item Every rational number $r$ is a $0$-integer (since\n       $0^k r \\in \\ZZ$ for $k = 1$).\n\\end{itemize}\n\nLet $R_m$ denote the set of all $m$-integers.\nProve the following:\n\n\\begin{enumerate}\n\n\\item[\\textbf{(a)}] The set $R_m$ (endowed with the usual\naddition, the usual multiplication, the usual integer $0$\nas zero, and the usual integer $1$ as unity) is a\ncommutative ring. \\\\\n(You don't need to prove axioms like commutativity of\nmultiplication, since these follow from the corresponding\nfacts about rational numbers, which are well-known.\nYou only need to check that $R_m$ is\nclosed under addition and multiplication\\footnote{This\nmeans that every $a, b \\in R_m$ satisfy $a + b \\in R_m$\nand $a b \\in R_m$.}, and contains\nadditive inverses of all its elements.)\n\n\\item[\\textbf{(b)}] Let $x \\in \\QQ$ be nonzero.\nThen, $x \\in R_m$ if and only if every prime $p$ satisfying\n$w_p\\tup{x} < 0$ satisfies $p \\mid m$.\nHere, we are using the notation $w_p\\tup{r}$ defined\nin Exercise 3.4.1 of the\n\\href{http://www.cip.ifi.lmu.de/~grinberg/t/19s/notes.pdf}{class notes}.\n\n\\end{enumerate}\n\n\\subsection{Remark}\n\nThe ring $R_m$ is an example of a ring ``between $\\ZZ$ and $\\QQ$''.\nNote that $R_1 = \\ZZ$ and $R_0 = \\QQ$, whereas $R_2 = R_4 = R_8 = \\cdots$\nis the ring of all rational numbers that can be written in the form\n$a / 2^k$ with $a \\in \\ZZ$ and $k \\in \\NN$.\n\n\\subsection{Solution}\n\n[...]\n\n%----------------------------------------------------------------------------------------\n%\tEXERCISE 2\n%----------------------------------------------------------------------------------------\n\\horrule{0.3pt} \\\\[0.4cm]\n\n\\section{Exercise 2: Rings with $x^2 = x$}\n\n\\subsection{Problem}\n\nLet $\\KK$ be a ring with the property that\n\\begin{align}\n u^2 = u \\qquad \\text{ for all } u \\in \\KK .\n \\label{eq.exe.ring.xx=x.cond}\n\\end{align}\n\n(Examples of such rings are $\\ZZ / 2$ as well as the\n``power set'' ring $\\tup{\\powset{S}, \\triangle, \\cap, \\varnothing, S}$\nconstructed from any given set $S$.)\n\nProve the following:\n\n\\begin{enumerate}\n\n\\item[\\textbf{(a)}]\nWe have $2x = 0$ for each $x \\in \\KK$.\n\n\\item[\\textbf{(b)}]\nWe have $-x = x$ for each $x \\in \\KK$.\n\n\\item[\\textbf{(c)}]\nWe have $xy = yx$ for all $x, y \\in \\KK$.\n(In other words, the ring $\\KK$ is commutative.)\n\n\\end{enumerate}\n\n(As usual, ``$0$'' stands for the zero of the ring $\\KK$.)\n\n[\\textbf{Hint:}\nFor part \\textbf{(a)},\napply \\eqref{eq.exe.ring.xx=x.cond} to $u = x$\nbut also to $u = 2x = x + x$, and see what comes out.\nFor part \\textbf{(c)},\napply \\eqref{eq.exe.ring.xx=x.cond} to $u = x + y$.]\n\n\\subsection{Remark}\n\nYou might wonder what happens if we replace\n\\eqref{eq.exe.ring.xx=x.cond} by\n\\begin{align}\n u^3 = u \\qquad \\text{ for all } u \\in \\KK .\n \\label{eq.exe.ring.xx=x.cube}\n\\end{align}\nThis no longer leads to $2x = 0$ (nor to $3x = 0$ as you\nmight perhaps expect).\nInstead, it can be shown that $6x = 0$ for all $x \\in \\KK$.\nIt can also be shown that it leads to $xy = yx$.\n\n\\subsection{Solution}\n\n[...]\n\n%----------------------------------------------------------------------------------------\n%\tEXERCISE 3\n%----------------------------------------------------------------------------------------\n\\horrule{0.3pt} \\\\[0.4cm]\n\n\\section{Exercise 3: A matrix of gcds}\n\n\\subsection{Problem}\n\nIn this exercise, we shall again use\n\\href{https://en.wikipedia.org/wiki/Iverson_bracket}{the \\textit{Iverson bracket notation}}:\n\nLet $n \\in \\NN$.\nLet $G$ be the $n \\times n$-matrix\n\\[\n \\tup{ \\gcd\\tup{i, j} }_{1 \\leq i \\leq n, \\ 1 \\leq j \\leq n }\n =\n \\begin{pmatrix}   % \"pmatrix\" stands for \"parenthesis-bounded matrix\".\n                   % That's how we write matrices in this class.\n  \\gcd\\tup{1, 1} & \\gcd\\tup{1, 2} & \\cdots & \\gcd\\tup{1, n} \\\\\n  \\gcd\\tup{2, 1} & \\gcd\\tup{2, 2} & \\cdots & \\gcd\\tup{2, n} \\\\\n  \\vdots & \\vdots & \\ddots & \\vdots \\\\\n  \\gcd\\tup{n, 1} & \\gcd\\tup{n, 2} & \\cdots & \\gcd\\tup{n, n}\n \\end{pmatrix} .\n\\]\n\nLet $L$ be the $n \\times n$-matrix\n\\[\n \\tup{ \\ive{j \\mid i} }_{1 \\leq i \\leq n, \\ 1 \\leq j \\leq n }\n =\n \\begin{pmatrix}\n  \\ive{1 \\mid 1} & \\ive{2 \\mid 1} & \\cdots & \\ive{n \\mid 1} \\\\\n  \\ive{1 \\mid 2} & \\ive{2 \\mid 2} & \\cdots & \\ive{n \\mid 2} \\\\\n  \\vdots & \\vdots & \\ddots & \\vdots \\\\\n  \\ive{1 \\mid n} & \\ive{2 \\mid n} & \\cdots & \\ive{n \\mid n}\n \\end{pmatrix} .\n\\]\n\nLet $D$ be the $n \\times n$-matrix\n\\[\n \\tup{ \\ive{i = j} \\phi\\tup{i} }_{1 \\leq i \\leq n, \\ 1 \\leq j \\leq n }\n =\n \\begin{pmatrix}\n  \\phi\\tup{1} & 0 & 0 & \\cdots & 0 \\\\\n  0 & \\phi\\tup{2} & 0 & \\cdots & 0 \\\\\n  0 & 0 & \\phi\\tup{3} & \\cdots & 0 \\\\\n  \\vdots & \\vdots & \\vdots & \\ddots & \\vdots \\\\\n  0 & 0 & 0 & \\cdots & \\phi\\tup{n}\n \\end{pmatrix} .\n\\]\n\nProve that\\footnote{We are using the standard notation $A^T$ for\nthe \\textit{transpose} of a matrix $A$. This transpose is defined\nas follows:\nIf $A = \\tup{ a_{i, j} }_{1 \\leq i \\leq n, \\ 1 \\leq j \\leq m }$,\nthen\n$A^T = \\tup{ a_{j, i} }_{1 \\leq i \\leq m, \\ 1 \\leq j \\leq n }$.}\n$G = LDL^T$.\n\n[\\textbf{Hint:} Diagonal matrices are particularly easy\nto multiply with other matrices. For example, given a\ndiagonal matrix\n$\\mathbf{D} = \\tup{ \\ive{i = j} d_i }_{1 \\leq i \\leq n, \\ 1 \\leq j \\leq n }$\n(where $d_1, d_2, \\ldots, d_n$ are $n$ elements of a ring $\\KK$)\nand an arbitrary matrix\n$\\mathbf{A} = \\tup{ a_{i, j} }_{1 \\leq i \\leq n, \\ 1 \\leq j \\leq m }$\n(over the same ring $\\KK$),\nthe product $\\mathbf{D} \\mathbf{A}$ is simply given by\n\\begin{align}\n \\mathbf{D} \\mathbf{A} =\n \\tup{ d_i a_{i, j} }_{1 \\leq i \\leq n, \\ 1 \\leq j \\leq m } .\n \\label{eq.matrix.gcd-LDU.row-mult}\n\\end{align}\n(That is, multiplying by a diagonal matrix on the left is tantamount\nto rescaling each row by the corresponding entry of the diagonal\nmatrix.)\nYou can use the formula \\eqref{eq.matrix.gcd-LDU.row-mult} without\nproof (though its easy proof is instructive).]\n\n\\subsection{Remark}\n\nAs the names suggest, the matrix $L$ is lower-triangular\n(so that the matrix $L^T$ is upper-triangular),\nand the matrix $D$ is diagonal.\nThus, $G = LDL^T$ is an instance of an\n\\href{https://en.wikipedia.org/wiki/LU_decomposition#LDU_decomposition}{\\textit{LDU decomposition}}.\n\n\\subsection{Solution}\n\n[...]\n\n%----------------------------------------------------------------------------------------\n%\tEXERCISE 4\n%----------------------------------------------------------------------------------------\n\\horrule{0.3pt} \\\\[0.4cm]\n\n\\section{Exercise 4: Idempotent and involutive elements}\n\n\\subsection{Problem}\n\nLet $\\KK$ be a ring.\n\nAn element $a$ of $\\KK$ is said to be \\textit{idempotent}\nif it satisfies $a^2 = a$.\n\nAn element $a$ of $\\KK$ is said to be \\textit{involutive}\nif it satisfies $a^2 = 1$.\n\n\\begin{enumerate}\n \\item[\\textbf{(a)}] Let $a \\in \\KK$.\n Prove that if $a$ is idempotent, then $1 - 2a$ is\n involutive.\n \n \\item[\\textbf{(b)}] Now, assume that $2$ is\n \\textit{cancellable} in $\\KK$; this means that if\n $u$ and $v$ are two elements of $\\KK$ satisfying\n $2u = 2v$, then $u = v$.\n Prove that the converse of the claim of part\n \\textbf{(a)} holds:\n If $a \\in \\KK$ is such that $1 - 2a$ is involutive,\n then $a$ is idempotent.\n \n \\item[\\textbf{(c)}] Now, let $\\KK = \\ZZ / 4$.\n Find an element $a \\in \\KK$ such that $1 - 2a$\n is involutive, but $a$ is not idempotent.\n\\end{enumerate}\n\n\\subsection{Remark}\n\nThe idempotent elements of $\\RR$ are $0$ and $1$.\nThe involutive elements of $\\RR$ are $1$ and $-1$.\nA matrix ring like $\\RR^{n \\times n}$ usually has\ninfinitely many idempotent elements (viz., all\nprojection matrices on subspaces of $\\RR^n$) and\ninfinitely many involutive elements (viz., all\nmatrices $A$ satisfying $A^2 = I_n$; for instance,\nall reflections across hyperplanes are represented\nby such matrices).\n\nPart \\textbf{(a)} of this exercise assigns an involutive\nelement to each idempotent element of $\\KK$.\nIf $2$ is invertible in $\\KK$ (that is, if the element\n$2 \\cdot 1_{\\KK}$ has a multiplicative inverse), then this\nassignment is a bijection (as can be easily derived from\npart \\textbf{(b)}).\nPart \\textbf{(c)} shows that we cannot drop the\n``$2$ is cancellable'' condition in part \\textbf{(b)}.\n\n\\subsection{Solution}\n\n[...]\n\n%----------------------------------------------------------------------------------------\n%\tEXERCISE 5\n%----------------------------------------------------------------------------------------\n\\horrule{0.3pt} \\\\[0.4cm]\n\n\\section{Exercise 5: The matrix approach to Fibonacci numbers}\n\n\\subsection{Problem}\n\nLet $A$ be the $2 \\times 2$-matrix\n$\\begin{pmatrix}\n  0 & 1 \\\\\n  1 & 1\n \\end{pmatrix}$\nover $\\ZZ$.\nConsider also the identity matrix $I_2 \\in \\ZZ^{2 \\times 2}$.\n\nLet $\\calF$ % I have defined \\calF to mean \\mathcal{F} for this problem.\nbe the subset\n\\[\n \\set{ aA + bI_2 \\mid a, b \\in \\ZZ }\n =\n \\set{ \\begin{pmatrix} b & a \\\\ a & a+b \\end{pmatrix} \\mid a, b \\in \\ZZ }\n\\]\nof the matrix ring $\\ZZ^{2 \\times 2}$.\n\n\\begin{enumerate}\n\n\\item[\\textbf{(a)}]\nProve that $A^2 = A + I_2$.\n\n\\item[\\textbf{(b)}]\nProve that the set $\\calF$ (equipped with the addition of matrices,\nthe multiplication of matrices, the zero $0_{2 \\times 2}$ and\nthe unity $I_2$) is a commutative ring. \\\\\n(Again, you don't need to check the ring axioms, as we already\nknow that they hold for arbitrary matrices and thus all the more\nfor matrices in $\\calF$.\nBut you do need to check commutativity of multiplication in\n$\\calF$, since it does not hold for arbitrary matrices.\nYou also need to check that $\\calF$ is closed under addition\nand multiplication and has additive inverses.)\n\n\\end{enumerate}\n\nLet $\\tup{f_0, f_1, f_2, \\ldots}$ be the Fibonacci sequence (which\nwe have already encountered on\n\\href{http://www.cip.ifi.lmu.de/~grinberg/t/19s/hw5s.pdf}{homework set \\#5}).\nRecall that it is defined recursively by\n\\[\nf_0 = 0, \\qquad\nf_1 = 1, \\qquad \\text{and} \\qquad\nf_n = f_{n-1} + f_{n-2} \\text{ for all } n \\geq 2 .\n\\]\n\n\\begin{enumerate}\n\n\\item[\\textbf{(c)}]\nProve that $A^n = f_n A + f_{n-1} I_2$ for all positive\nintegers $n$.\n\n\\item[\\textbf{(d)}]\nProve that\n$f_{n+m} = f_n f_{m+1} + f_{n-1} f_m$ for all positive\nintegers $n$ and all $m \\in \\NN$.\n\n\\end{enumerate}\n\nNow, define a further matrix $B \\in \\calF$ by\n$B = \\tup{-1}A + 1I_2 = I_2 - A$.\n\n\\begin{enumerate}\n\n\\item[\\textbf{(e)}]\nProve that $B^2 = B + I_2$ and\n$B^n = f_n B + f_{n-1} I_2$ for all positive\nintegers $n$.\n\n\\item[\\textbf{(f)}]\nProve that\n$A^n - B^n = f_n \\tup{A - B}$ for all $n \\in \\NN$.\n\n\\item[\\textbf{(g)}]\nProve (again!) that $f_d \\mid f_{dn}$ for any nonnegative\nintegers $d$ and $n$.\n\n% Prove that\n% \\[\n%  A^n \\begin{pmatrix} 0 \\\\ 1 \\end{pmatrix}\n%  = \\begin{pmatrix} f_n \\\\ f_{n+1} \\end{pmatrix}\n%  \\qquad \\text{ for all } n \\in \\NN .\n% \\]\n\\end{enumerate}\n\n[\\textbf{Hint:} One way to prove \\textbf{(d)} is by\ncomparing the $\\tup{1, 1}$-th entries of the two\n(equal) matrices $A^n A^{m+1}$ and $A^{n+m+1}$, after\nfirst using part \\textbf{(c)} to expand these matrices.\n\nFor part \\textbf{(g)}, compare the $\\tup{1, 1}$-th\nentries of the matrices $A^d - B^d$ and $A^{dn} - B^{dn}$,\nafter first proving that $A^d - B^d \\mid A^{dn} - B^{dn}$ in\nthe commutative ring $\\calF$.\nNote that divisibility is a tricky concept in general\nrings, but $\\calF$ is a commutative ring, which lets\nmany arguments from the integer setting go\nthrough unchanged.]\n\n\\subsection{Remark}\n\nContrast the ring $\\calF$ with the ring $\\ZZ\\ive{\\phi}$\nfrom Exercise 5 on\n\\href{http://www.cip.ifi.lmu.de/~grinberg/t/19s/hw5s.pdf}{homework set \\#5}.\nBoth of these rings, as we see, can be used to prove that $f_d \\mid f_{dn}$\nfor any nonnegative integers $d$ and $n$.\nWhat else do these rings have in common?\n\n\\subsection{Solution}\n\n[...]\n\n%----------------------------------------------------------------------------------------\n%\tEXERCISE 6\n%----------------------------------------------------------------------------------------\n\\horrule{0.3pt} \\\\[0.4cm]\n\n\\section{Exercise 6: ISBNs vs. fat fingers}\n\n\\subsection{Problem}\n\nAn \\textit{ISBN} shall mean a $10$-tuple\n$\\tup{a_1, a_2, \\ldots, a_{10}} \\in \\set{0, 1, \\ldots, 10}^{10}$\nsuch that\n\\[\n1 a_1 + 2 a_2 + \\cdots + 10 a_{10} \\equiv 0 \\mod 11 .\n\\]\n\n\\noindent\n(For example, the $10$-tuple $\\tup{1, 1, \\ldots, 1}$ is an ISBN.)\n\nProve the following:\n\n\\begin{enumerate}\n\n\\item[\\textbf{(a)}]\nIf $\\mathbf{a} = \\tup{a_1, a_2, \\ldots, a_{10}}$ and\n$\\mathbf{b} = \\tup{b_1, b_2, \\ldots, b_{10}}$ are two ISBNs\nthat are equal in all but one entry (i.e.,\nthere exists some $k \\in \\set{1, 2, \\ldots, 10}$\nsuch that $a_i = b_i$ for all $i \\neq k$),\nthen $\\mathbf{a} = \\mathbf{b}$.\n\n\\item[\\textbf{(b)}]\nIf an ISBN $\\mathbf{a} = \\tup{a_1, a_2, \\ldots, a_{10}}$ is\nobtained from an ISBN\n$\\mathbf{b} = \\tup{b_1, b_2, \\ldots, b_{10}}$ by swapping\ntwo entries (i.e., there exist $k, \\ell \\in \\set{1, 2, \\ldots, 10}$\nsuch that $a_k = b_\\ell$ and $a_\\ell = b_k$ and\n$a_i = b_i$ for all $i \\notin \\set{k, \\ell}$),\nthen $\\mathbf{a} = \\mathbf{b}$.\n\n\\end{enumerate}\n\n\\subsection{Remark}\n\nWhat we called ISBN here is essentially the definition\nof an \\href{https://en.wikipedia.org/wiki/International_Standard_Book_Number#ISBN-10_check_digits}{ISBN-10}\n-- an international standard for book identifiers used from the\n1970s until 2007.\nFor example, the ISBN-10 of the Graham/Knuth/Patashnik\nbook ``Concrete Mathematics'' is ``0-201-55802-5'', which corresponds\nto $\\tup{0, 2, 0, 1, 5, 5, 8, 0, 2, 5}$; you can check\nthat this is indeed an ISBN according to our definition.\n\n(An ``X'' in a real-life ISBN stands for an entry that\nis $10$.)\n\nAs this exercise shows, ISBNs have an error-detection\nproperty:\nIf you make a typo in a single digit or accidentally swap\ntwo digits, the result will not be an ISBN, so you will\nknow that something has gone wrong.\nThis helps you avoid ordering the wrong book from a bookstore\nor library.\n\\href{https://en.wikipedia.org/wiki/Luhn_algorithm}{Credit card numbers have a similar error-detection feature}.\n\nThis is one of the simplest examples of an\n\\href{https://en.wikipedia.org/wiki/Error_correction_code}{error correction code}.\nWe may or may not see more of them in class.\nFor now, you can think about how to define ``ISBNs''\n\\begin{itemize}\n\\item in $\\set{0, 1, \\ldots, 4}^4$;\n\\item in $\\set{0, 1, \\ldots, 6}^6$;\n\\item in $\\set{0, 1, \\ldots, 8}^8$ (this is harder!).\n\\end{itemize}\n\n\\subsection{Solution}\n\n[...]\n\n\\begin{thebibliography}{99999999}                                                                                         %\n\n% Feel free to add your sources -- or copy some from the source code\n% of the class notes ( http://www.cip.ifi.lmu.de/~grinberg/t/19s/notes.tex ).\n\n\\end{thebibliography}\n\n\\end{document}\n\n", "meta": {"hexsha": "b54a9d95368142534d47feaf9b595732045e57fe", "size": 24943, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "mt2.tex", "max_stars_repo_name": "darijgr/algebra19s", "max_stars_repo_head_hexsha": "16476909502a4566bd33b4f11ade52829ef9b16f", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-03-21T05:38:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-17T00:48:51.000Z", "max_issues_repo_path": "mt2.tex", "max_issues_repo_name": "darijgr/algebra19s", "max_issues_repo_head_hexsha": "16476909502a4566bd33b4f11ade52829ef9b16f", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mt2.tex", "max_forks_repo_name": "darijgr/algebra19s", "max_forks_repo_head_hexsha": "16476909502a4566bd33b4f11ade52829ef9b16f", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6808823529, "max_line_length": 157, "alphanum_fraction": 0.6087479453, "num_tokens": 7779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.3383927403512352}}
{"text": "% ****** Start of file apssamp.tex ******\n%\n%   This file is part of the APS files in the REVTeX 4.1 distribution.\n%   Version 4.1r of REVTeX, August 2010\n%\n%   Copyright (c) 2009, 2010 The American Physical Society.\n%\n%   See the REVTeX 4 README file for restrictions and more information.\n%\n% TeX'ing this file requires that you have AMS-LaTeX 2.0 installed\n% as well as the rest of the prerequisites for REVTeX 4.1\n%\n% See the REVTeX 4 README file\n% It also requires running BibTeX. The commands are as follows:\n%\n%  1)  latex apssamp.tex\n%  2)  bibtex apssamp\n%  3)  latex apssamp.tex\n%  4)  latex apssamp.tex\n%\n\\documentclass[%\n reprint,\n%superscriptaddress,\n%groupedaddress,\n%unsortedaddress,\n%runinaddress,\n%frontmatterverbose, \n%preprint,\n%showpacs,preprintnumbers,\n%nofootinbib,\n%nobibnotes,\n%bibnotes,\n amsmath,amssymb,\n aps,\n%pra,\n%prb,\n%rmp,\n%prstab,\n%prstper,\n%floatfix,\n]{revtex4-1}\n\n\\usepackage{graphicx}% Include figure files\n\\usepackage{dcolumn}% Align table columns on decimal point\n\\usepackage{bm}% bold math\n\\usepackage{amsmath}% better dot placment\n\\usepackage{systeme}% systemes of equations\n%\\usepackage{hyperref}% add hypertext capabilities\n%\\usepackage[mathlines]{lineno}% Enable numbering of text and display math\n%\\linenumbers\\relax % Commence numbering lines\n\n%\\usepackage[showframe,%Uncomment any one of the following lines to test \n%%scale=0.7, marginratio={1:1, 2:3}, ignoreall,% default settings\n%%text={7in,10in},centering,\n%%margin=1.5in,\n%%total={6.5in,8.75in}, top=1.2in, left=0.9in, includefoot,\n%%height=10in,a5paper,hmargin={3cm,0.8in},\n%]{geometry}\n\n% Personal definitions\n\\newcommand{\\dvec}[1]{\\dot{\\vec{#1}}}\n\\newcommand{\\grad}{\\vec{\\nabla}}\n\\newcommand{\\intV}[1]{\\int_{-\\infty}^{\\infty} #1 d^3x}\n\\newcommand{\\intVdot}[1]{\\int_{-\\infty}^{\\infty} #1 d^3\\dot{x}}\n\\newcommand{\\intVVdot}[1]{\\int_{-\\infty}^{\\infty}\\int_{-\\infty}^{\\infty} #1 d^3xd^3\\dot{x}}\n\n\n\\begin{document}\n\n\\title{A Derivation of Fluid Mechanics}% Force line breaks with \\\n\n\\author{L. Siemens}\n\\email{lsiemens@uvic.ca}\n\n\\date{\\today}\n\n\\begin{abstract}\nI derive a single PDE that describes the dynamics of fluids in state space. Then the similarity between that PDE and equations of fluid mechanics is demonstrated by using it to deriving a set of three equations analogous to the mass, internal energy and Navier-Stokes equations.  Finally I demonstrate that for a fluid with particles following the Maxwell-Boltzmann distribution the set of analogous equations reduces to the equations of inviscid flow.\n\\end{abstract}\n\n\\maketitle\n\n\\section{Introduction}\n\nFluids consist of a large number of interacting particles, presumably the fluid mechanics observed at a macroscopic level is a result of the interactions occurring at a microscopic level. If the dynamics of each particle was know it should be possible in principle to determine the macroscopic dynamics of the fluid from the collective motion of the particles. \n\n\\section{State space dynamics}\n\nAssuming the dynamics a particle is defined by the acceleration and that the acceleration of the particles is given by the potential $\\phi$ such that $\\vec{a} = \\vec{\\nabla}\\cdot\\phi$, then the equations of motion become\n\\[\n\\frac{d}{dt}\\begin{pmatrix} \\vec{x} \\\\ \\dvec{x} \\end{pmatrix}=\\begin{pmatrix} \\dvec{x} \\\\ -\\grad\\phi \\end{pmatrix}\n\\]\n\nFor a system of $n$ particles where the $i^{\\text{th}}$ particle is located at $\\vec{x}_i$, the potential can in principle depend on the location of all of the particles, such that the potential for the $i^{\\text{th}}$ particle is $\\phi_i = \\phi({\\vec{x}_i, \\vec{x}_1, \\vec{x}_2, ... \\vec{x}_i ... , \\vec{x}_{n-1}, \\vec{x}_n})$. Then for this system the equations of motion for each particle is given by the system of equations\n\\begin{equation}\n\\frac{d}{dt}\\begin{pmatrix} \\vec{x}_i \\\\ \\dvec{x}_i \\end{pmatrix}=\\begin{pmatrix} \\dvec{x}_i \\\\ -\\partial_{\\vec{x}_i}\\phi_i \\end{pmatrix}\n\\label{discrete_system_dynamics}\n\\end{equation}\n\nMoving over to a state space description of the system, the state space has six coordinates given by the orthogonal coordinate vectors $\\vec{x}$ and $\\dvec{x}$. Given a time dependent density distribution defined over state space $\\sigma=\\sigma(\\vec{x}, \\dvec{x}, t)$, such that the total mass at the time $t$ is $M(t)=\\intVVdot{\\sigma(\\vec{x}, \\dvec{x}, t)}$. The system of discrete particles described by equation \\eqref{discrete_system_dynamics} then be described by the distribution\n\\[\n\\sigma(\\vec{x}, \\dvec{x}, t) = m\\sum^n_{i=0}\\delta(\\vec{x} - \\vec{x}_i)\\cdot\\delta(\\dvec{x} - \\dvec{x}_i)\n\\]\nwhere $m$ is the mass of the particles, and $\\delta(\\vec{x})$ is the Dirac delta distribution in 3-space. For this system the six component state space velocity is $\\vec{v}=\\left\\langle\\dvec{x}, -\\grad\\phi(\\vec{x}, \\rho, t)\\right\\rangle$, where the potential $\\phi$ is defined as $\\phi(\\vec{x}_i, \\rho, t)=\\phi_i$ and $\\rho(\\vec{x}, t)=\\intVdot{\\sigma(\\vec{x}, \\dvec{x}, t)}$ . Assuming the number of particles in the distribution is constant, then $\\frac{dM}{dt}=0$. Since there are no sources or sinks for the particles, the density distribution is constrained by the continuity equation\n\\[\n\\frac{d}{dt}\\int_{V}\\sigma(\\vec{x}, \\dvec{x}, t)d^3xd^3\\dot{x}+\\oint_{\\partial V}\\sigma(\\vec{x}, \\dvec{x}, t)\\vec{v}\\cdot d\\vec{a}=0\n\\]\nwhere $V$ is an arbitrary volume in state space, $\\partial V$ is the surface of the arbitrary volume, $\\vec{v}$ is the state space velocity and $d\\vec{a}$ is a surface element in state space. Rearranging the terms and using the divergence theorem the continuity equation can be rewritten in the form\n\\[\n\\int_V\\left(\\partial_t\\sigma + \\grad\\cdot\\left(\\sigma\\vec{v}\\right)\\right)d^3xd^3\\dot{x}=0\n\\]\n\nSince the integral equals zero over any arbitrary volume $V$, then the integrand must be zero\n\\[\n\\partial_t \\sigma + \\grad\\cdot\\left(\\sigma\\vec{v}\\right)=0\n\\]\n\nFinally the independence of $\\vec{x}$ and $\\dvec{x}$ can be used to rewrite the continuity equation in the final form, in this case it is written using Einstein notation\n\\begin{equation}\n\\partial_t \\sigma + \\dot{x}_i\\partial_{x_i}\\sigma-\\left(\\partial_{x_i}\\phi\\right)\\partial_{\\dot{x}_i}\\sigma=0\n\\label{state_space_continuity}\n\\end{equation}\n\nWhile the derivation of equation \\eqref{state_space_continuity} was motivated using a discrete collection of particles the equation is not restricted to systems of discrete particles. As long as the dynamics in state space is determined by $\\vec{v}=\\left\\langle\\dvec{x}, \\grad\\phi(\\vec{x}, \\rho, t)\\right\\rangle$ and there are no sources or sinks for the state space density, then any state space density function or distribution is described by equation \\eqref{state_space_continuity}.\n\nAssuming the motion of individual particles, in a fluid described by fluid mechanics, is described by equation \\eqref{discrete_system_dynamics} and assuming that the number and mass of the particles is invariant, then the dynamics of the state space distribution is described by equation \\eqref{state_space_continuity}. If these assumptions are true for any fluid, then equation \\eqref{state_space_continuity} must be capable of reproducing the behavior of fluid mechanics.\n\n\\section{Fluid mechanics mass equation: Conservation of mass}\nThe state space density function $\\sigma$ is defined such that $M=\\intVVdot{\\sigma(\\vec{x}, \\dvec{x}, t)}$. Define the mass density $\\rho$ as $\\rho(\\vec{x}, t)=\\intVdot{\\sigma(\\vec{x}, \\dvec{x}, t)}$. Also define the bulk velocity $\\vec{u}$ as $u_i=\\frac{1}{\\rho(\\vec{x}, t)}\\intVdot{x_i\\sigma(\\vec{x}, \\dvec{x}, t)}=\\intVdot{x_i\\frac{\\sigma}{\\rho}}$. The integral of equation \\eqref{state_space_continuity} over velocity space is\n\\[\n\\intVdot{\\left(\\partial_t \\sigma + \\dot{x}_i\\partial_{x_i}\\sigma-\\left(\\partial_{x_i}\\phi\\right)\\partial_{\\dot{x}_i}\\sigma\\right)}=0\n\\]\n\nSplitting up the integral, pulling out factors and operations that are independent of $\\dot{x}_i$ puts the equation into a form where some terms can be evaluated. Then applying the divergence theorem and evaluating the simplified integrals results in the equation\n\\[\n\\partial_t\\rho + \\partial_{x_i}\\left(u_i\\rho\\right)-\\left(\\partial_{x_i}\\phi\\right)\\oint{\\sigma da_i}=0\n\\]\nwhere $da_i$ is the $i^{\\text{th}}$ component of the surface element, and $\\oint{\\sigma da_i}$ is the surface integral over all of velocity space. Assuming $\\sigma(\\vec{x}, \\dvec{x}, t)$ drops to zero faster than $\\lvert\\dvec{x}\\rvert^2$ then the surface integral converges to zero. Given the surface integral does converge to zero, the resulting equation is $\\partial_t\\rho + \\partial_{x_i}\\left(u_i\\rho\\right)=0$. When written in vector notation it becomes\n\\begin{equation}\n\\partial_t\\rho + \\grad\\cdot\\left(\\vec{u}\\rho\\right)=0\n\\label{conservation_of_mass}\n\\end{equation}\nwhich is the conservation of mass equation from fluid mechanics.\n\n\\section{Conservation of momentum}\nTo get an equation for the conservation of momentum, multiply equation \\eqref{state_space_continuity} by $\\dvec{x}$ before integrating over velocity space.\n\\[\n\\intVdot{\\dot{x}_i\\left(\\partial_t \\sigma + \\dot{x}_j\\partial_{x_j}\\sigma-\\left(\\partial_{x_j}\\phi\\right)\\partial_{\\dot{x}_j}\\sigma\\right)}=0\n\\]\n\nAfter simplifying the equation, applying the product rule and divergence theorem it can be written in the form\n\\[\n\\begin{split}\n& \\partial_t\\left(u_i\\rho\\right) + \\partial_{x_j}\\left(\\intVdot{\\dot{x}_i\\dot{x}_j\\sigma}\\right) \\\\ & - \\left(\\partial_{x_j}\\phi\\right)\\oint\\dot{x}_i\\sigma da_j + \\left(\\partial_{x_j}\\phi\\right)\\rho\\delta_{i j}=0\n\\end{split}\n\\]\nwhere $\\oint\\dot{x}_i\\sigma da_j$ is a surface integral over all of velocity space and $\\delta_{ij}$ is the Kronecker delta function. Assuming $\\sigma(\\vec{x}, \\dvec{x}, t)$ drops to zero faster than $\\lvert\\dvec{x}\\rvert^3$ then the surface integral converges to zero. Given the surface integral does converge to zero\n\\begin{equation}\n\\partial_t\\left(u_i\\rho\\right) + \\partial_{x_j}\\left(\\intVdot{\\dot{x}_i\\dot{x}_j\\sigma}\\right) + \\rho\\partial_{x_i}\\phi=0\n\\label{incomplete_conservation_of_momentum}\n\\end{equation}\n\n\\subsection{Integrating the velocity tensor product}\nThe velocity tensor product term is $\\intVdot{\\dot{x}_i\\dot{x}_j\\sigma}$. Since the bulk velocity is defined as $u_i=\\intVdot{\\dot{x}_i\\frac{\\sigma}{\\rho}}$ let\n\\[\n\\begin{split}\n& \\intVdot{\\dot{x}_i\\dot{x}_j\\sigma}=\\intVdot{\\dot{x}_i\\frac{\\sigma}{\\rho}}\\intVdot{\\dot{x}_j\\sigma} \\\\ & - \\intVdot{\\dot{x}_i\\frac{\\sigma}{\\rho}}\\intVdot{\\dot{x}_j\\sigma} + \\intVdot{\\dot{x}_i\\dot{x}_j\\sigma}\n\\end{split}\n\\]\n\nEvaluating the first term and combining the other two terms produces the equation\n\\[\n\\begin{split}\n& \\intVdot{\\dot{x}_i\\dot{x}_j\\sigma}=\\rho u_i u_j \\\\ & + \\frac{1}{2}\\left(\\intVdot{\\left(\\dot{x}_i - u_i\\right)\\dot{x}_j\\sigma} + \\intVdot{\\left(\\dot{x}_j - u_j\\right)\\dot{x}_i\\sigma}\\right)\n\\end{split}\n\\]\n\nIf we define a symmetric tensor $A$ such that $A_{ij} = -\\frac{1}{2}\\left(\\intVdot{\\left(\\dot{x}_i - u_i\\right)\\dot{x}_j\\sigma} + \\intVdot{\\left(\\dot{x}_j - u_j\\right)\\dot{x}_i\\sigma}\\right)$, then the integral of the velocity tensor product simplifies to the equation\n\\[\n\\intVdot{\\dot{x}_i\\dot{x}_j\\sigma}=\\rho u_i u_j - A_{ij}\n\\]\n\nLet $p=-\\frac{1}{3}A_{ii}$ and define the traceless tensor $B$ such that $B_{ij}=A_{ij}-\\frac{1}{3}A_{kk}\\delta_{ij}$, so the velocity tensor product term can be written as\n\\[\n\\intVdot{\\dot{x}_i\\dot{x}_j\\sigma}=\\rho u_i u_j + p\\delta_{ij} - B_{ij}\n\\]\n\n\\subsection{Fluid mechanics momentum equation: Navier-Stokes equations}\nSubstituting the integral of the velocity tensor product into equation \\eqref{incomplete_conservation_of_momentum}\n\\[\n\\partial_t\\left(u_i\\rho\\right) + \\partial_{x_j}\\left(\\rho u_i u_j + p\\delta_{ij}-B_{ij}\\right) + \\rho\\partial_{x_i}\\phi=0\n\\]\n\nExpand the partial derivatives involving the bulk velocity and canceling terms leading with $u_i$ by substituting in equation \\eqref{conservation_of_mass}. Then the equation can then be written in vector notation as\n\\begin{equation}\n\\rho\\left(\\partial_t \\vec{u} + \\vec{u}\\cdot\\grad\\vec{u}\\right) = - \\grad p + \\grad B - \\rho\\grad\\phi\n\\label{conservation_of_momentum}\n\\end{equation}\n\nAssuming that for a reasonable model of a fluid the tensor $A_{ij}$ evaluates to be the total stress tensor $\\sigma_{ij}$, then equation \\eqref{conservation_of_momentum} is the Navier-Stokes equations.\n\n\\pagebreak % ---------------------------------------------------------------\n\n\\section{Conservation of energy}\nThe total energy of the system is $E_{\\text{tot}}=\\intVVdot{\\left(\\frac{1}{2}\\dot{x}_i^2 + \\phi(\\vec{x}, \\rho)\\right)\\sigma(\\vec{x}, \\dvec{x}, t)}$. Let us define $\\vec{v} = \\dvec{x} - \\vec{u}$, so then $\\dot{x}_i^2 = v_i^2 + 2\\dot{x}_i u_i - u_i^2$. In order to derive an equation for the conservation of energy equation in position space, equation \\eqref{state_space_continuity} must be multiplied by $\\frac{1}{2}\\dot{x}_i^2 + \\phi$ before integrating. To make the derivation of the conservation of energy simpler we can use the linearity of integration to break the conservation of energy equation into a kinetic energy component and a potential energy component.\n\n\\subsection{The kinetic energy component}\nMultiplying equation \\eqref{state_space_continuity} by $\\frac{1}{2}\\dot{x}_i^2$ then integrating over velocity space, the resulting relation is\n\\[\n\\intVdot{\\frac{1}{2}\\dot{x}_i^2\\left(\\partial_t \\sigma + \\dot{x}_j\\partial_{x_j}\\sigma-\\left(\\partial_{x_j}\\phi\\right)\\partial_{\\dot{x}_j}\\sigma\\right)}=0\n\\]\n\nAfter simplifying the equation, applying the product rule and divergence theorem, it can be written in the form\n\\[\n\\begin{split}\n& \\partial_t\\left(\\intVdot{\\frac{1}{2}\\dot{x}_i^2\\sigma}\\right) + \\partial_{x_j}\\left(\\intVdot{\\frac{1}{2}\\dot{x}_i^2\\dot{x}_j\\sigma}\\right) \\\\ & -  \\left(\\partial_{x_j}\\phi\\right)\\left(\\oint\\left(\\frac{1}{2}\\dot{x}_i^2\\sigma\\right)da_j - \\intVdot{\\sigma\\dot{x}_j}\\right)=0\n\\end{split}\n\\]\nwhere $\\oint\\left(\\frac{1}{2}\\dot{x}_i^2\\sigma\\right)da_j$ is a surface integral over all of velocity space. Assuming $\\sigma(\\vec{x}, \\dvec{x}, t)$ drops to zero faster than $\\lvert\\dvec{x}\\rvert^4$ then the surface integral converges to zero. Evaluating integrals and rearranging the equation given the surface integral does converge to zero, results in the equation\n\\[\n\\partial_t\\left(\\intVdot{\\frac{1}{2}\\dot{x}_i^2\\sigma}\\right) + \\partial_{x_j}\\left(\\intVdot{\\frac{1}{2}\\dot{x}_i^2\\dot{x}_j\\sigma}\\right) + u_j\\rho\\partial_{x_j}\\phi=0\n\\]\n\nAfter expanding the equation by using the definition of $v_i$ and rearranging, use the result $\\intVdot{\\dot{x}_i\\dot{x}_j\\sigma}=\\rho u_i u_j + p\\delta_{ij} - B_{ij}$ from the momentum equation derivation to write the equation in the form\n\\begin{equation}\n\\begin{split}\n& \\partial_t\\left(\\intVdot{\\frac{1}{2}v_i^2\\sigma} + \\frac{1}{2}u_i^2\\rho\\right) + u_j\\rho\\partial_{x_j}\\phi \\\\ & + \\partial_{x_j}\\left(\\intVdot{\\frac{1}{2}v_i^2\\dot{x}_j\\sigma} + \\frac{1}{2}u_i^2 u_j\\rho + p u_j - u_i B_{ij}\\right)=0\n\\end{split}\n\\label{incomplete_conservation_of_energy_kinetic}\n\\end{equation}\n\n\\subsection{The potential energy component}\nMultiplying equation \\eqref{state_space_continuity} by $\\phi$ and then integrating over velocity space, the resulting relation is\n\\[\n\\intVdot{\\phi\\left(\\partial_t \\sigma + \\dot{x}_j\\partial_{x_j}\\sigma-\\left(\\partial_{x_j}\\phi\\right)\\partial_{\\dot{x}_j}\\sigma\\right)}=0\n\\]\n\nAfter rearranging and simplifying use the result that $\\intVdot{\\partial_{\\dot{x}_j}\\sigma}=\\oint\\sigma da_j = 0$, from the derivation for the conservation of mass equation, to get\n\\[\n\\phi\\partial_t\\rho + \\phi\\partial_{x_j}\\left(u_j\\rho\\right)=0\n\\]\n\nApplying the product rule produces the form\n\\begin{equation}\n\\partial_t\\left(\\phi\\rho\\right) - \\rho\\partial_t\\phi + \\partial_{x_j}\\left(u_j\\rho\\phi\\right) - u_j\\rho\\partial_{x_j}\\phi=0\n\\label{incomplete_conservation_of_energy_potential}\n\\end{equation}\n\n\n\\subsection{Total energy density dynamics}\nThe potential $\\phi$ can be split into two components, the internal potential $\\phi_{\\text{in}}$ and a potential due to the external environment $\\phi_{\\text{ext}}$, such that $\\phi = \\phi_{\\text{in}} + \\phi_{\\text{ext}}$. Let us define two energy densities, the internal energy density $e$ and the external energy density $\\eta$, such that $e(\\vec{x}, t)=\\intVdot{\\left(\\frac{1}{2}v_i^2 + \\phi_{\\text{in}}\\right)\\sigma}$ and $\\eta(\\vec{x}, t)=\\intVdot{\\left(\\frac{1}{2}u_i^2 + \\phi_{\\text{ext}}\\right)\\sigma}=\\left(\\frac{1}{2}u_i^2 + \\phi_{\\text{ext}}\\right)\\rho$. From these definitions the total energy is then $E_{\\text{tot}}=\\intV{\\left(e + \\eta\\right)}$. Adding the two energy components from equation \\eqref{incomplete_conservation_of_energy_kinetic} and equation \\eqref{incomplete_conservation_of_energy_potential} produces the equation\n\\[\n\\begin{split}\n& \\partial_t\\left(\\intVdot{\\frac{1}{2}v_i^2\\sigma} + \\frac{1}{2}u_i^2\\rho\\right) + u_j\\rho\\partial_{x_j}\\phi \\\\ & + \\partial_{x_j}\\left(\\intVdot{\\frac{1}{2}v_i^2\\dot{x}_j\\sigma} + \\frac{1}{2}u_i^2 u_j\\rho + p u_j - u_i B_{ij}\\right) \\\\ & + \\partial_t\\left(\\phi\\rho\\right) - \\rho\\partial_t\\phi + \\partial_{x_j}\\left(u_j\\rho\\phi\\right) - u_j\\rho\\partial_{x_j}\\phi=0\n\\end{split}\n\\]\n\nAfter simplifying and splitting $\\phi$ into its two components and evaluating terms using the energy density definitions the equation can be written as\n\\[\n\\begin{split}\n& \\partial_t\\left(e + \\eta\\right)  - \\rho\\partial_t\\phi + \\partial_{x_j}\\left(\\intVdot{\\frac{1}{2}v_i^2\\dot{x}_j\\sigma} \\right. \\\\ & \\left. \\vphantom{\\intVdot{.}} + u_j\\phi_{\\text{in}}\\rho + \\eta u_j + p u_j - u_i B_{ij}\\right)=0\n\\end{split}\n\\]\n\nUsing the definition of $v_i$ and applying the definition internal energy density the relation is\n\\[\n\\begin{split}\n& \\partial_t\\left(e + \\eta\\right) + \\partial_{x_j}\\left(e u_j + \\eta u_j\\right) \\\\ & + \\partial_{x_j}\\left(\\intVdot{\\frac{1}{2}v_i^2 v_j\\sigma} + p u_j - u_i B_{ij}\\right) - \\rho\\partial_t\\phi=0\n\\end{split}\n\\]\n\nDefining the vector $\\vec{C}$ as $C_j = \\intVdot{\\frac{1}{2}v_i^2 v_j\\sigma}$ and using it to simplify the equation results in the form\n\\begin{equation}\n\\begin{split}\n& \\partial_t\\left(e + \\eta\\right) + \\partial_{x_j}\\left(e u_j + \\eta u_j\\right) \\\\ & + \\partial_{x_j}\\left(C_j + p u_j - u_i B_{ij}\\right) - \\rho\\partial_t\\phi=0\n\\end{split}\n\\label{incomplete_conservation_of_energy}\n\\end{equation}\n\nEquation \\eqref{incomplete_conservation_of_energy} describes the dynamics of the total energy density. Using equation \\eqref{conservation_of_momentum} an equation for the external energy density can be derived. Which when combined with equation \\eqref{incomplete_conservation_of_energy} will produce an equation for the internal energy density.\n\n\\subsection{External energy density dynamics}\nTo generate an equation for the external energy density, let us multiply equation \\eqref{conservation_of_momentum} by $u_i$.\n\\[\nu_i\\left(\\rho\\partial_t u_i + \\rho u_j\\partial_{x_j}u_i + \\partial_{x_i}p - \\partial_{x_j}B_{ij} + \\rho\\partial_{x_i}\\phi\\right)=0\n\\]\n\nRearranging and applying the product rule, the equation becomes\n\\[\n\\begin{split}\n& \\partial_t\\left(\\frac{1}{2}u_i^2\\rho\\right) - \\frac{1}{2}u_i^2\\partial_t\\rho + \\partial_{x_j}\\left(\\frac{1}{2}u_i^2\\rho u_j\\right) - \\frac{1}{2}u_i^2\\partial_{x_j}\\left(\\rho u_j\\right) \\\\ & + u_i\\left(\\partial_{x_i}p - \\partial_{x_j}B_{ij} + \\rho\\partial_{x_i}\\phi\\right)=0\n\\end{split}\n\\]\n\nAfter collecting terms of $\\frac{1}{2}u_i^2$, adding a potential energy component $\\partial_t\\left(\\rho\\phi_{\\text{ext}} - \\rho\\phi_{\\text{ext}}\\right) + \\partial_{x_j}\\left(u_j\\rho\\phi_{\\text{ext}} - u_j\\rho\\phi_{\\text{ext}}\\right)=0$, applying the product rule and using the definition of $\\eta$ the equation can put in the form\n\\[\n\\begin{split}\n& \\partial_t\\eta - \\rho\\partial_t\\phi_{\\text{ext}} - \\left(\\frac{1}{2}u_i^2 + \\phi_{\\text{ext}}\\right)\\left(\\partial_t\\rho + \\partial_{x_j}\\left(\\rho u_j\\right)\\right)+ \\partial_{x_j}\\left(\\eta u_j\\right) \\\\ & - u_j\\rho\\partial_{x_j}\\phi_{\\text{ext}} + u_i\\left(\\partial_{x_i}p - \\partial_{x_j}B_{ij} + \\rho\\partial_{x_i}\\phi\\right)=0\n\\end{split}\n\\]\n\nCanceling terms by substituting in equation \\eqref{conservation_of_mass} and relabeling contracted indices results in the equation\n\\begin{equation}\n\\begin{split}\n& \\partial_t\\eta + \\partial_{x_j}\\left(\\eta u_j\\right) - \\rho\\partial_t\\phi_{\\text{ext}} \\\\ & + u_j\\partial_{x_j}p - u_i\\partial_{x_j}B_{ij} + u_j\\rho\\partial_{x_j}\\phi_{\\text{in}}=0\n\\end{split}\n\\label{incomplete_conservation_of_energy_external}\n\\end{equation}\n\n\\subsection{Fluid mechanics energy equation: Internal energy equation}\nTo remove the external energy density from equation \\eqref{incomplete_conservation_of_energy} subtract equation \\eqref{incomplete_conservation_of_energy_external} from it, resulting in the equation\n\\[\n\\begin{split}\n& \\partial_t\\left(e + \\eta\\right) + \\partial_{x_j}\\left(e u_j + \\eta u_j\\right) - \\rho\\partial_t\\phi \\\\ & + \\partial_{x_j}\\left(C_j + p u_j - u_i B_{ij}\\right) \\\\ & - \\partial_t\\eta - \\partial_{x_j}\\left(\\eta u_j\\right) + \\rho\\partial_t\\phi_{\\text{ext}} \\\\ & - u_j\\partial_{x_j}p + u_i\\partial_{x_j}B_{ij} - u_j\\rho\\partial_{x_j}\\phi_{\\text{in}}=0\n\\end{split}\n\\]\n\nAfter applying the product rule and simplifying, the equation can be written as\n\\[\n\\begin{split}\n& \\partial_te + \\partial_{x_j}\\left(e u_j\\right) - \\rho\\partial_t\\phi_{\\text{in}} - u_j\\rho\\partial_{x_j}\\phi_{\\text{in}} \\\\ & + \\partial_{x_j}C_j + p\\partial_{x_j}u_j - B_{ij}\\partial_{x_j}u_i=0\n\\end{split}\n\\]\nrearranging the equation and putting it in vector notation, the equation then can be written in the from\n\\begin{equation}\n\\begin{split}\n& \\partial_te + \\grad\\cdot\\left(e \\vec{u}\\right) = \\rho\\partial_t\\phi_{\\text{in}} + \\rho\\vec{u}\\cdot\\grad\\phi_{\\text{in}} \\\\ & - \\grad\\cdot\\vec{C} - p\\grad\\cdot\\vec{u} + B\\cdot\\grad\\vec{u}\n\\end{split}\n\\label{conservation_of_energy}\n\\end{equation}\n\nAssuming that for a reasonable model of a fluid the tensor $A_{ij}$ evaluates to be the total stress tensor $\\sigma_{ij}$ and the vector $C_j$ reduce a term including the gradient of the temperature, then equation \\eqref{conservation_of_energy} is a form of the fluid mechanics internal energy equation.\n\\linebreak %-----------------------------------------------------------\n\n\\section{Fluid model: Maxwell-Boltzmann distribution}\nAssuming the speed of particles in a fluid follow a Maxwell-Boltzmann distribution, then the velocity distribution of the fluid is a normalized Gaussian distribution in three dimensional velocity space. For a fluid element with a non-zero bulk velocity assume that the velocity distribution is simply a normalized Gaussian with a non-zero mean value. Given these assumptions the velocity distribution at any point is $\\sigma(\\vec{x}, \\dvec{x}) / \\rho(\\vec{x}) = \\left(\\frac{m}{2\\pi kT}\\right)^{3/2}e^{-\\frac{m\\left(x_i - u_i\\right)^2}{2kT}}$, where $m$ is the mass of the particles the fluid is made from, $k$ is Boltzmann's constant and $T=T(\\vec{x}, t)$ is the thermodynamic temperature. Also assume that the potential $\\phi$ only explicitly depends on $\\vec{x}$ and $\\rho$. So in this model $\\phi=\\phi(\\vec{x}, \\rho)$ and the state space density distribution is,\n\\begin{equation}\n\\sigma(\\vec{x}, \\dvec{x}) = \\rho(\\vec{x})\\left(\\frac{m}{2\\pi kT}\\right)^{3/2}e^{-\\frac{m\\left(x_i - u_i\\right)^2}{2kT}}\n\\label{distribution_maxwell_boltzmann}\n\\end{equation}\n\nAs defined earlier the tensor $A$ is\n\\[\nA_{ij} = -\\frac{1}{2}\\left(\\intVdot{\\left(\\dot{x}_i - u_i\\right)\\dot{x}_j\\sigma} + \\intVdot{\\left(\\dot{x}_j - u_j\\right)\\dot{x}_i\\sigma}\\right)\n\\]\n\nWhen $i$ is not equal to $j$ the integral is $A_{ij} = 0$, when $i$ is equal to $j$ the integral is $A_{ij} = -kT\\rho/m$, so the full tensor is $A_{ij}=-kT\\frac{\\rho}{m}\\delta_{ij}$. Using the ideal gas law $PV=NkT$, since $\\rho/m=N/V$ where $N$ is the number of particles and $V$ is the volume, then $A_{ij} = -P\\delta_{ij}$, $p=-\\frac{1}{3}A_{ii}=P$ and $B_{ij}=A_{ij}-\\frac{1}{3}A_{kk}\\delta_{ij} = 0$.\n\nThe vector $\\vec{C}$ is defined as $C_j = \\intVdot{\\frac{1}{2}v_i^2 v_j\\sigma}$, evaluating the integral results in the equation $C_j = 0$. So given the state space density function \\eqref{distribution_maxwell_boltzmann} the equations of fluid mechanics derived from equation \\eqref{state_space_continuity} are\n\\[\n\\partial_t\\rho + \\grad\\cdot\\left(\\vec{u}\\rho\\right)=0\n\\]\n\n\\[\n\\rho\\left(\\partial_t \\vec{u} + \\vec{u}\\cdot\\grad\\vec{u}\\right) = - \\grad P - \\rho\\grad\\phi\n\\]\n\n\\[\n\\partial_te + \\grad\\cdot\\left(e \\vec{u}\\right) = \\rho\\vec{u}\\cdot\\grad\\phi_{\\text{in}} - P\\grad\\cdot\\vec{u}\n\\]\n\nThese equations are equal to the conservation of mass, internal energy density and Navier-Stokes equations in the case of inviscid flow.\n\n\\end{document}\n%\n% ****** End of file apssamp.tex ******\n", "meta": {"hexsha": "8aadd06af8c8be3cc4a9b520a32f9dbd74c569b4", "size": 24516, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "theory/fluid_mechanics_from_particle_motion/fluid_mechanics.tex", "max_stars_repo_name": "lsiemens/lsiemens.github.io", "max_stars_repo_head_hexsha": "d93bf32c8e849b6514aea0f8eb582c42543a53d6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-16T18:16:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-16T18:16:07.000Z", "max_issues_repo_path": "theory/fluid_mechanics_from_particle_motion/fluid_mechanics.tex", "max_issues_repo_name": "lsiemens/lsiemens.github.io", "max_issues_repo_head_hexsha": "d93bf32c8e849b6514aea0f8eb582c42543a53d6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-03-08T23:16:36.000Z", "max_issues_repo_issues_event_max_datetime": "2015-12-29T02:17:16.000Z", "max_forks_repo_path": "theory/fluid_mechanics_from_particle_motion/fluid_mechanics.tex", "max_forks_repo_name": "lsiemens/lsiemens.github.io", "max_forks_repo_head_hexsha": "d93bf32c8e849b6514aea0f8eb582c42543a53d6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-16T18:16:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-16T18:16:10.000Z", "avg_line_length": 66.8010899183, "max_line_length": 865, "alphanum_fraction": 0.7238538098, "num_tokens": 7816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.3383108708293504}}
{"text": "\\documentclass[11pt,a4paper]{article}\n\\usepackage[left=1.1in,right=1.1in,bottom=1.3in,top=1.1in]{geometry}\n% Acepta tildes y eñes\n\\usepackage[utf8]{inputenc}\n% Para traducir los chapter a capítulos\n\\usepackage[spanish,mexico,english]{babel}\n\\usepackage{graphicx,amsfonts,amsmath,hyperref,tabularx}\n\\usepackage[x11names,table]{xcolor}\n%Para hacer tablas\n\\usepackage{tabularx}\n\\usepackage[labelfont=bf,justification=centering]{caption}\n\n\\raggedbottom % Los párrafos los mantiene juntos\n\\usepackage{fancyhdr}\n\\usepackage{setspace}\n\n\n\\usepackage{listings}\n\\lstdefinestyle{customc}{basicstyle=\\ttfamily,columns=fullflexible }\n\\lstset{style=customc}\n\n\\setstretch{1.3} % Line spacing of 1.3\n\n\n\\begin{document}\n\n\\title{Hazel - practical example}\n\\author{Carlos José Díaz Baso}\n\\maketitle\n%genera doble hoja en blanco\n%\\cleardoublepage\n\n\\section{The reference system}\n\n\n\\begin{figure}[ht!]\n\\centering\n\\includegraphics[width=0.4\\textwidth]{f1.pdf}\n\\includegraphics[width=0.5\\textwidth]{fig2a.pdf}\n\\caption{Left) Hazel reference system, rigth) diagram indicating the position of the LOS vector.}\n\\label{fig:figure1}\n\\end{figure}\n\n\nAs we can see in Fig. \\ref{fig:figure1}, the angle $\\chi$ is measured from $X$ to $Y$, and $\\theta$ is measured from $Z$ to $\\Omega$. We can choose the angle $\\chi$ in order to simplify the equations. If we choose $\\chi= 0$, then $\\Omega$ is between $Z$ and $X$. This configuration only happens when $X$ is radial and  points towards the disk center (DC). However, if we choose $\\chi= 180$, then $\\Omega$ is between $Z$ and $-X$. This configuration only happens when $X$ is radial and  points away from the disk center (DC). In the rigth panel we see where is $\\Omega$ if we choose the value of $\\chi$. \n\nThe consecuences of choosing one option are: the reference system itself and the equations to find all the posible solutions.\n\n\\clearpage\n\\section{Example 1.}\nWe have the following data from our observation and we choose $\\chi=$180d:\n\\begin{itemize}\n\\item Position [arcsec]: $x=-300.0$; $y=-200.0$ \\& Q$>$0: N-S\n\\end{itemize}\n\nWe can calculate the angle from the equator:\n\\begin{lstlisting}\nalpha = np.arctan(y/x)*180./(np.pi) = 33.7d\n\\end{lstlisting}\nThen we can calculate the heliocentric angle:\n\\begin{lstlisting}\ntheta = np.arcsin(np.sqrt(x**2.+y**2.)/960.)*180/np.pi = 22.1d\n\\end{lstlisting}\nNow we can calculate $\\gamma$ (must be measured from X to Y, anticlockwise). In Fig. \\ref{fig:example1} (right) you have two solutions: the purple and the blue one:\n\\begin{lstlisting}\nGamma(purple) = 360-(90+33.7)=236.3d    or     Gamma(blue) =(90-33.7) = 56.3\n\\end{lstlisting}\nQ$>$0 is a line, not  a direction. Gamma is defined [0,180º] (look the Hazel GUI) so in principle you can choose the direction of Q$>$0 which makes Gamma  inside the range. In order to check the result, you can execute the 3D plot to visualize the result (Fig. \\ref{fig:example1}).\n\n\\begin{figure}[ht!]\n\\centering\n\\includegraphics[width=0.35\\textwidth]{example1A.pdf}\n\\includegraphics[width=0.55\\textwidth]{example1B.pdf}\n\\includegraphics[width=0.55\\textwidth]{example1_3D.pdf}\n\\caption{Hazel reference system}\n\\label{fig:example1}\n\\end{figure}\n\\clearpage\nThen, the angles for this observation are:\n\\begin{lstlisting}\ntheta_OBS = 22.1d\nchi_OBS = 180.0d\nGamma_OBS =(90-33.7) = 56.3\n\\end{lstlisting}\n\n\n\\section{Example 2.}\nWe have the same observation but we choose $\\chi=$0d. Now, $\\gamma$ is again measured from $X$, and it is the same as before (Fig. \\ref{fig:example2}).\n\\begin{lstlisting}\nGamma(blue) =(90-33.7) = 56.3\n\\end{lstlisting}\n\n\\begin{figure}[ht!]\n\\centering\n\\includegraphics[width=0.35\\textwidth]{example2A.pdf}\n\\includegraphics[width=0.55\\textwidth]{example2B.pdf}\n\\includegraphics[width=0.55\\textwidth]{example2_3D.pdf}\n\\caption{Hazel reference system}\n\\label{fig:example2}\n\\end{figure}\n\n\nThen, the angles for this observation are:\n\\begin{lstlisting}\ntheta_OBS = 22.1d\nchi_OBS = 0.0d\nGamma_OBS =(90-33.7) = 56.3\n\\end{lstlisting}\n\n\n\n\n\n\\end{document}\n", "meta": {"hexsha": "bf221f56357e6bcff2843191abf5b93f765275f6", "size": 3964, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/main.tex", "max_stars_repo_name": "fluxtransport/hazel2", "max_stars_repo_head_hexsha": "4121df2fa6bf96bf8f193f287bbf11c70c5a519e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2018-08-31T11:13:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T02:30:56.000Z", "max_issues_repo_path": "docs/main.tex", "max_issues_repo_name": "fluxtransport/hazel2", "max_issues_repo_head_hexsha": "4121df2fa6bf96bf8f193f287bbf11c70c5a519e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 26, "max_issues_repo_issues_event_min_datetime": "2018-04-03T15:09:21.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-27T10:10:45.000Z", "max_forks_repo_path": "docs/main.tex", "max_forks_repo_name": "fluxtransport/hazel2", "max_forks_repo_head_hexsha": "4121df2fa6bf96bf8f193f287bbf11c70c5a519e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2016-02-25T19:35:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-01T17:12:52.000Z", "avg_line_length": 34.4695652174, "max_line_length": 603, "alphanum_fraction": 0.7429364279, "num_tokens": 1291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.33831087082935035}}
{"text": "\\documentclass[a4paper,11pt]{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage[margin=1cm]{geometry}\n\\usepackage{amsthm}\n%\\usepackage{fullpage}\n\n\\newtheorem{definition}{Definition}\n\\newtheorem{lemma}{Lemma}\n\\newtheorem{theorem}{Theorem}\n\\newtheorem{notation}{Notation}\n\n\\newcommand{\\Inv}{\\mathit{Inv}}\n\\newcommand{\\app}{\\mathit{\\,++\\,}}\n\\newcommand{\\Default}{\\mathit{Default}}\n\\newcommand{\\pc}{\\mathit{pc}}\n\\newcommand{\\ex}{\\mathit{ex}}\n\\newcommand{\\ar}{\\mathit{ar}}\n\\newcommand{\\WP}{\\mathit{WP}}\n\n\\newcommand{\\sect}[1]{\\noindent\\parbox{\\textwidth}{#1}}\n\\newcommand{\\sep}{\\hspace{-1.5707965cm}\\rule{\\paperwidth}{1pt}}\n\n\\newcommand{\\UNSHIFT}{\\mathit{unshift}}\n\\newcommand{\\SHIFT}{\\mathit{shift}}\n\\newcommand{\\Dom}{\\mathit{Dom}}\n\\newcommand{\\SELECT}{\\mbox{SELECT}}\n\\newcommand{\\Stack}{\\mathrm{s}}\n\\newcommand{\\TRUE}{\\mathit{tt}}\n\\newcommand{\\FALSE}{\\mathit{ff}}\n\\newcommand{\\IF}{\\mathrm{IF}}\n\\newcommand{\\ghost}[1]{{\\it #1}^g}\n\\newcommand{\\LockSet}{\\mathsf{Lck}}\n\n\\begin{document}\n\\pagestyle{empty}\n\n\\sep\n\n\\begin{notation}[$\\Inv$]\n$\\Inv$ will from now on denote the visible state invariant of the program in question.\n\\end{notation}\n\n\n\\sep\n\n\n\\begin{notation}[$\\Default$]\n$\\Default$ denotes an assertion specifying that all variables have their default values. ($\\Default$ is true at the initial configuration.)\n\\end{notation}\n\n\n\\sep\n\n\n\\begin{definition}[Calling / Returning / Visible Configuration]\n~\\\\[-5mm]\n\\begin{itemize}\n\\item A configuration $C=(h, (c, m, \\pc, s, l)::R)$ is \\emph{calling} if $C \\rightarrow C'$ for some $C' = (h', (c', m', \\pc', s', l')::(h, (c, m, \\pc, s, l))::R)$.\n\\item A configuration $C=(h, a::R)$ is \\emph{returning} if $C \\rightarrow (h', R)$.\n  \n  (Returning normally / exceptionally depending on shape of $a$ but I currently don't think it ever matters.)\n  \n%\\item A configuration $C=(h, (o)::R)$ is \\emph{returning exceptionally} if $C \\rightarrow C'$ for some $C' = (h', R)$.\n\\item A configuration is \\emph{visible} if it is calling or returning.\n\\end{itemize}\n\\end{definition}\n\n\n\\sep\n\n\n\\begin{definition}[Annotated Method / Program]\nAn \\emph{annotated method} is an ordinary method with an assertion attached to each instruction.\n\nAn \\emph{annotated program} is an ordinary program (whose methods are annotated) together with an $\\Inv$.\n\\end{definition}\n\n\n\\sep\n\n\n\\begin{definition}[$\\WP$]\\label{def:wp}\nSee figure \\ref{fig:wp}. Note that the figure suggests that any instruction may have an exceptional outcome. I think that this this would be quite heavy in the proofs and that we (at least in this formalization) should restrict it to {\\tt athrow} and {\\tt invoke}.\n\\begin{figure}\n\\[ \\WP_M(L) = \\WP_M^N(L) \\land \\WP_M^E(L) \\quad\\mbox{where~}M = (I, H, A)\\]\n\n\\[\n\\begin{array}{ll}\n\\hline\nI_L & \\WP_M^N(L) \\\\ \\hline\n\\mbox{\\tt aload}\\ n        & \\UNSHIFT(A_{L+1}[l_n/\\Stack_0]) \\\\[1pt]\n\\mbox{\\tt astore}\\ n       & (\\SHIFT(A_{L+1}))\\wedge \\Stack_0 = l_n \\\\[1pt]\n\\mbox{\\tt athrow}          & \\TRUE \\\\[1pt]\n\\mbox{\\tt goto}\\ L'        & A_{L'}  \\\\[1pt]\n\\mbox{\\tt if\\_icmpeq}~L'   & \\IF(\\Stack_0=\\Stack_1,\\SHIFT^2(A_{L'}),\\SHIFT^2(A_{L+1}))\\\\[1pt]\n\\mbox{\\tt ifeq}\\ L'        & \\IF(\\Stack_0=0,\\SHIFT(A_{L'}), \\SHIFT(A_{L+1})) \\\\[1pt]\n\\mbox{\\tt getstatic}\\ c.f  & \\left\\{\\begin{array}{@{}l}\n                                    c' \\in \\LockSet \\land \\UNSHIFT (A_{L+1}[c.f/\\Stack_0]) \\textrm{if $\\Gamma_\\mathrm{L}(c') = (F,a)$ and $(c.f) \\in F$}\\\\\n                                    \\forall x. \\UNSHIFT(A_{L+1}[x/\\Stack_0]) \\ \\ \\ \\mbox{otherwise}\n                                    \\end{array}\\right.\\\\[1pt]\n\\mbox{\\tt putstatic}\\ c.f  & \\left\\{\\begin{array}{@{}l}\n                                    c' \\in \\LockSet \\land \\SHIFT(A_{L+1})[\\Stack_0/c.f] \\textrm{if $\\Gamma_\\mathrm{L}(c') = (F,a)$ and $(c.f) \\in F$}\\\\\n                                    \\SHIFT(A_{L+1})[\\Stack_0/c.f] \\ \\ \\ \\mbox{otherwise}\n                                    \\end{array}\\right.\\\\[1pt]\n\\mbox{\\tt ldc}\\ v          & \\UNSHIFT(A_{L+1}[v/\\Stack_0]) \\\\[1pt]\n\\mbox{\\tt ldc\\ c}          & \\left\\{\\begin{array}{@{}l}\n                                    \\FALSE \\ \\ \\ \\ \\textrm{if $c \\in \\Dom(\\Gamma_L) \\land I_{L+1} \\neq \\mbox{\\tt monitor*}$}\\\\\n                                    \\UNSHIFT(A_{L+1}[c/\\Stack_0]) \\ \\ \\ \\ \\textrm{otherwise}\n                                    \\end{array}\\right.\\\\[1pt]\n\\mbox{\\tt monitorenter}    & \\left\\{\\begin{array}{@{}l}\n                                    \\lnot(s_0 \\in \\LockSet)\\> \\land \\forall\\mathbf{x}.(a \\Rightarrow \\SHIFT(A_{L+1})[\\LockSet\\cup\\{s_0\\}/\\LockSet])[\\mathbf{x}/F] \\\\\n                                    \\hspace*{1cm}\\textrm{if $I_{L-1} = \\mbox{\\tt LDC\\ $c$}$ and $(c, (F, a)) \\in \\Gamma_L$}\\\\\n                                    \\SHIFT(A_{L+1})[\\LockSet \\cup \\{s_0\\}/\\LockSet] \\ \\ \\ \\textrm{otherwise}\n                                    \\end{array}\\right.\\\\[1pt]\n\\mbox{\\tt monitorexit}     & \\left\\{\\begin{array}{@{}l}\n                                    a \\land (\\forall \\mathbf{x}. \\SHIFT(A_{L+1})[\\mathbf{x}/F][\\LockSet\\!\\setminus\\!\\{s_0\\}/\\LockSet]) \\\\ \n                                    \\hspace*{1cm} \\textrm{if $I_{L-1} = \\mbox{\\tt LDC\\ $c$}$ and $(c, (F, a)) \\in \\Gamma_L$}\\\\\n                                    A_{L+1}[\\LockSet \\setminus\\{s_0\\}/\\LockSet] \\ \\ \\  \\textrm{otherwise}\n                                    \\end{array}\\right.\\\\[1pt]\n\\begin{array}{@{}l@{}}\n\\mbox{\\tt invoke-} \\\\\n\\mbox{\\tt virtual}\\ c.m\n\\end{array}                & \\left\\{\\begin{array}{@{}ll}\n                                    A_{L+1} & \\mbox{if $c.m$ is a non-client-reentrant API method} \\\\\n                                    Inv    & \\textrm{if for each successor label $L'$, $A_{L'} = Inv$} \\\\\n                                    \\FALSE & \\mbox{otherwise}\n                                    \\end{array}\\right.\\\\[1pt]\n\\multicolumn{2}{l}{\\mbox{\\tt invokestatic System.exit}\\quad \\TRUE}\\\\[1pt]\n\n\\multicolumn{2}{l}{\\langle \\ghost{\\bf x} := a_1 \\rightarrow {\\bf e}_1 \\mid \\ldots \\mid a_n \\rightarrow {\\bf e}_n \\rangle} \\\\\n & \\begin{array}{@{}l@{}l@{}}\\SELECT(&\\langle a_1, \\ldots, a_n\\rangle,\\\\ & \\langle A_{L+1}\n[{\\bf e}_1/\\ghost{{\\bf x}}], \\ldots, A_{L+1}[{\\bf e}_n/\\ghost{{\\bf x}}]\\rangle,\\FALSE)\\end{array} \\\\ \n\n\\textrm{other}             & \\left\\{\\begin{array}{@{}ll}\n                                    Inv   & \\textrm{if for each successor label $L'$, $A_{L'} = Inv$} \\\\\n                                    \\FALSE & \\mbox{otherwise}\n                                    \\end{array}\\right. \\\\ \\hline\n\\end{array}\n\\]\n\n\n\n\n\n\\[\n\\begin{array}{l@{~=~}l}\n\\WP_M^E(L) & \\WP_M^E(L, H) \\\\\n\\WP_M^E(L, \\epsilon) & Inv \\\\\n\\WP_M^E(L, (b, e, L', \\mathit{Throwable}) :: H') & A_{L'} \\quad \\mbox{if $b \\leq L < e$} \\\\\n\\WP_M^E(L, (b, e, L', c) :: H') & A_{L'} \\land \\WP_M^E(L, H')\n\\end{array}\n\\]\n\n\\caption{\\label{fig:wp} Specification of the $\\WP_M$ function}\n\\end{figure}\n\\end{definition}\n\n\n\\sep\n\n\n\\begin{definition}[Valid Execution]\nAn execution $E = C_0C_1\\ldots$ of an annotated program is \\emph{valid} if for each $i: 0 \\leq i~(\\leq |E|)$ the following hold\n\\begin{itemize}\n\\item If $C_i$ is visible (calling or returning), then $\\Inv$ holds.\n\\item If $C_i$ is of the form $(h, (c, m, \\pc, s, l)::R)$, then $\\| A_{\\pc} \\| C_i$ holds.\n\\end{itemize}\nwhere $A$ denotes the array of assertions in method $c.m$.\n\\end{definition}\n\n\n\\sep\n\n\n\\begin{definition}[Global Validity]\nA program $P$ is \\emph{globally valid} if all possible executions of $P$ are valid.\n\\end{definition}\n\n\n\\sep\n\n\n\\sect{\\begin{definition}[Local Validity (Method)]\\label{def:local_validity_method}\nAn annotated method $M = (I, H, A)$ is \\emph{locally valid} if\n\\begin{enumerate}\n\\item $\\Inv \\Rightarrow A_0$\n\\item $A_L \\Rightarrow \\WP_M(L)$ for $L$ s.t. $0 \\leq L \\le |I|$\n\\end{enumerate}\n\n\\noindent\\framebox[\\linewidth]{\\parbox{\\linewidth}{Important note 1 (which we might have overlooked in original defs): The assertion at an execption handle target label may not mention anything but $\\Inv$ that depends on the heap, since $\\Inv$ is the only guarantee we can fulfill about the heap after having made a call to another method.}}\n\n\\noindent\\framebox[\\linewidth]{\\parbox{\\linewidth}{Important note 2 (which we definately overlooked in original defs): The assertion at an execption handle target label may not mention the stack since JLS }}\n\\end{definition}\n}\n\n\n\\sep\n\n\n\\begin{definition}[Local Validity (Program)]\\label{def:local_validity_program}\nAn annotated program is locally valid if\n\\begin{enumerate}\n\\item All its methods are locally valid\n\\item $\\Default \\Rightarrow Inv$\n\\end{enumerate}\n\\end{definition}\n\n\n\\sep\n\n\n\\begin{lemma}[Invoke Only Caller]\\label{lem:invoke_only_caller}\nIf a configuration $(h, (c, m, \\pc, s, l)::R)$ is calling, then the instruction at $\\pc$ in $c.m$ is an invoke instruction.\n\\end{lemma}\n\\begin{proof} By case analysis of the possible transitions. {\\bf (Partly formalized. Huge proof.)}\\end{proof}\n\n\n\\sep\n\n\\newpage\n\n\\begin{lemma}[$\\WP$ correct (normal)]\\label{lem:wp_correct_normal}\nLet $C = (h, (c, m, \\pc, s, l)::R)$ and $C' = (h', (c', m', \\pc', s', l')::R')$.\\\\\nIf $C \\rightarrow C'$, then $\\| \\WP_{c.m}(\\pc) \\| C \\Leftrightarrow \\| A_{\\pc'} \\| C'$.\n\\end{lemma}\n\n\\begin{proof}\nCase analysis on the instruction at $c.m[pc]$.\n\n\\begin{itemize}\n\\item {\\tt aload} $n$:\n  We know that\n  \\begin{itemize}\n  \\item $C' = (h, (c, m, \\pc+1, l(n) :: s, l)::R)$\n  \\item $\\WP_{c.m}(\\pc) = \\UNSHIFT(A_{\\pc+1}[l_n/\\Stack_0])$\n  \\end{itemize}\n  \n  Left to show: $ \\| \\UNSHIFT(A_{\\pc+1}[l_n/\\Stack_0]) \\| C \\Leftrightarrow \\| A_{\\pc+1} \\| C' $\n  \n  Proceeding with structural induction on $A_{\\pc+1}$.\n  \n  \\begin{itemize}\n  \\item $\\TRUE$: Applying substitution and $\\UNSHIFT$ yields $\\|\\TRUE\\|C \\Leftrightarrow \\| \\TRUE \\| C'$, which equals $\\TRUE \\Leftrightarrow \\TRUE$.\n  \\item $\\FALSE$: Applying substitution and $\\UNSHIFT$ yields $\\|\\FALSE\\|C \\Leftrightarrow \\| \\FALSE \\| C'$, which equals $\\FALSE \\Leftrightarrow \\FALSE$.\n  \\item $A_1 \\land A_2$:\n    \\begin{enumerate}\n    \\item IH$_1$: $ \\| \\UNSHIFT(A_1[l_n/\\Stack_0]) \\| C \\Leftrightarrow \\| A_1 \\| C'$\n    \\item IH$_2$: $ \\| \\UNSHIFT(A_2[l_n/\\Stack_0]) \\| C \\Leftrightarrow \\| A_2 \\| C'$\n    \\item Applying substitution yields $\\| \\UNSHIFT(A_1[l_n/\\Stack_0] \\land A_2[l_n/\\Stack_0]) \\| C \\Leftrightarrow \\| A_1 \\land A_2 \\| C'$\n    \\item Applying $\\UNSHIFT$ yields $\\| \\UNSHIFT(A_1[l_n/\\Stack_0]) \\land \\UNSHIFT(A_2[l_n/\\Stack_0]) \\| C \\Leftrightarrow \\| A_1 \\land A_2 \\| C'$\n    \\item Which equals $ \\| \\UNSHIFT(A_1[l_n/\\Stack_0]) \\| C$ and $\\| \\UNSHIFT(A_2[l_n/\\Stack_0]) \\| C \\Leftrightarrow \\| A_1 \\land A_2 \\| C'$\n    \\item By IH$_1$ and IH$_2$, we know $ \\| A_1 \\| C'$ and $\\| A_2 \\| C' \\Leftrightarrow \\| A_1 \\land A_2 \\| C'$\n    \\item Which equals, $\\| A_1 \\land A_2 \\| C' \\Leftrightarrow \\| A_1 \\land A_2 \\| C'$.\n    \\end{enumerate}\n  \\item $\\neg A_1$:\n    \\begin{enumerate}\n    \\item IH: $ \\| \\UNSHIFT(A_1[l_n/\\Stack_0]) \\| C \\Leftrightarrow \\| A_1 \\| C'$\n    \\item Applying substitution yields $ \\| \\UNSHIFT(\\neg (A_1[l_n/\\Stack_0])) \\| C \\Leftrightarrow \\| \\neg A_1 \\| C'$\n    \\item Applying $\\UNSHIFT$ yields $ \\| \\neg \\UNSHIFT(A_1[l_n/\\Stack_0]) \\| C \\Leftrightarrow \\| \\neg A_1 \\| C'$\n    \\item Which equals $ \\neg \\| \\UNSHIFT(A_1[l_n/\\Stack_0]) \\| C \\Leftrightarrow \\| \\neg A_1 \\| C'$\n    \\item Rewriting rhs yields $ \\neg \\| \\UNSHIFT(A_1[l_n/\\Stack_0]) \\| C \\Leftrightarrow \\neg \\| A_1 \\| C'$\n    \\item By lemma ? it is sufficient to show $\\| \\UNSHIFT(A_1[l_n/\\Stack_0]) \\| C \\Leftrightarrow \\| A_1 \\| C'$\n    \\item Which equals the IH.\n    \\end{enumerate}\n  \\item $A_1 \\lor A_2$, $\\IF(A_1, e_1, e_2)$ Similarly as above.\n  \\item $e_1 \\leq e_2$.\n    \\begin{enumerate}\n    \\item We need an auxillary lemma for expressions: $\\forall e, \\| \\UNSHIFT(e[l_n/\\Stack_0]) \\| C = \\| e \\| C' $\n      \n      Proceed with structural induction on $e$.\n      \\begin{itemize}\n      \\item $v$: $\\| \\UNSHIFT(v[l_n/\\Stack_0]) \\| C = \\| \\UNSHIFT(v) \\| C = \\| v \\| C = v = \\| v \\| C'$\n      \\item $\\Stack_k$: Case split on $k = 0$\n        \\begin{itemize}\n        \\item $k = 0$:    $\\| \\UNSHIFT(\\Stack_0[l_n/\\Stack_0]) \\| C = \\| \\UNSHIFT(l_n) \\| C = \\| l_n \\| C = ls(n) = \\| l_n \\| C'$\n        \\item $k \\neq 0$: $\\| \\UNSHIFT(\\Stack_k[l_n/\\Stack_0]) \\| C = \\| \\UNSHIFT(s_k) \\| C = \\| \\Stack_{k-1} \\| C = s(n-1) = (l(n)::s)(n) = \\| \\Stack_k \\| C'$\n        \\end{itemize}\n      \\item $e_1 + e_2$:\n        \\begin{enumerate}\n        \\item $\\| \\UNSHIFT((e_1 + e_2)[l_n/\\Stack_0]) \\| C$\n        \\item Applying substitution yields $\\| \\UNSHIFT(e_1[l_n/\\Stack_0] + e_2[l_n/\\Stack_0]) \\| C$\n        \\item Applying $\\UNSHIFT$ yields $\\| \\UNSHIFT(e_1[l_n/\\Stack_0]) + \\UNSHIFT(e_2[l_n/\\Stack_0]) \\| C$\n        \\item Which equals $\\| \\UNSHIFT(e_1[l_n/\\Stack_0]) \\| C + \\| \\UNSHIFT(e_2[l_n/\\Stack_0]) \\| C$\n        \\item By IH, we know that this equals $\\| e_1 \\| C' + \\| e_2 \\| C'$\n        \\item Which equals $\\| e_1 + e_2 \\| C'$\n        \\end{enumerate}\n      \\item $e_1.f$:\n        \\begin{enumerate}\n        \\item $\\| \\UNSHIFT(e_1.f[l_n/\\Stack_0]) \\| C$\n        \\item Applying substitution yields $\\| \\UNSHIFT(e_1[l_n/\\Stack_0].f) \\| C$\n        \\item Applying $\\UNSHIFT$ yields $\\| \\UNSHIFT(e_1[l_n/\\Stack_0])).f \\| C$\n        \\item Which equals $(\\| \\UNSHIFT(e_1[l_n/\\Stack_0]) \\| C)(f)$\n        \\item By IH, we know that this equals $(\\| e_1 \\| C')(f)$\n        \\item Which equals $\\| e_1.f \\| C'$\n        \\end{enumerate}\n\n      \\item $c.f$, $l_k$, $e_1 \\rightarrow e_2 \\mid e_3$, $\\bot$: treated similarly as above.\n      \\end{itemize}\n    \\item Applying substitution yields $ \\| \\UNSHIFT(e_1[l_n/\\Stack_0] \\leq e_2[l_n/\\Stack_0]) \\| C \\Leftrightarrow \\| e_1 \\leq e_2 \\| C'$.\n    \\item Applying $\\UNSHIFT$ yields $ \\| \\UNSHIFT(e_1[l_n/\\Stack_0]) \\leq \\UNSHIFT(e_2[l_n/\\Stack_0]) \\| C \\Leftrightarrow \\| e_1 \\leq e_2 \\| C'$.\n    \\item Which equals $ \\| \\UNSHIFT(e_1[l_n/\\Stack_0]) \\| C \\leq \\| \\UNSHIFT(e_2[l_n/\\Stack_0]) \\| C \\Leftrightarrow \\| e_1 \\leq e_2 \\| C'$.\n    \\item By lemma above, this equals $ \\| e_1 \\| C' \\leq \\| e_2 \\| C' \\Leftrightarrow \\| e_1 \\leq e_2 \\| C'$.\n    \\item Which equals $ \\| e_1 \\leq e_2 \\| C' \\Leftrightarrow \\| e_1 \\leq e_2 \\| C'$.\n    \\end{enumerate}\n  \\end{itemize}\n\n\\item {\\tt astore} $n$\n\\item {\\tt athrow}\n\\item {\\tt dup}\n\\item {\\tt getfield} $f$\n\\item {\\tt getstatic} $c''$ $f$\n\\item {\\tt goto} $L'$\n\\item {\\tt iadd}\n\\item {\\tt iconst} $i$\n\\item {\\tt ifeq} $L'$\n\\item {\\tt invoke} $c''$ $m''$\n\\item {\\tt putstatic} $c''$ $f$\n\\item {\\tt ldc} $v$\n\\item {\\tt exit}\n\\item {\\tt ret}\n\\item {\\tt nop}\n\\end{itemize}\n\\end{proof}\n\n\n\n\n\\sep\n\n\n\\sect{\\begin{lemma}[At most one exceptional frame]\\label{lem:at_most_one_exc_arec}\nThere can be at most one exceptional frame on the current activation record stack.\n\\end{lemma}\n\\begin{proof} Induction on the length of the execution.\n\\emph{Base case:} An initial configuration has no exceptional frame. \\emph{Inductive Step:} Case study of the transition rules.\n\\end{proof}}\n\n\\sep\n\n\n\\sect{\\begin{lemma}[$\\WP$ correct (exceptional)]\\label{lem:wp_correct_exceptional}\nIf\n\\begin{enumerate}\n  \\item $C = (h, (o)::(c, m, \\pc, s, l)::R)$,\n  \\item $C' = (h', (c', m', \\pc', s', l')::R')$,\n  \\item $C \\rightarrow C'$, and\n  \\item $\\|\\WP_{c.m}(\\pc) \\| (h'', (c, m, \\pc, s, l)::R)$ for some $h''$\n\\end{enumerate}\nthen $\\| A_{\\pc'} \\| C'$\n\\end{lemma}\n\\begin{proof}(Sketch)\n\\begin{enumerate}\n%\\item We know that the exception was thrown as a consequence of the instruction at $c.m[\\pc]$ directly ({\\tt athrow}, $C = C''$) or indirectly ({\\tt invoke}, $C \\neq C''$). (Needs to be shown.)\n%\\item In either way, we know that $c = c'$, $m = m'$, $s = \\epsilon$ and $l = l'$.\n\\item By the transition rules, we know that $\\pc'$ must be the target label of an exception handler.\n\\item From def \\ref{def:local_validity_method} we know that the only way $A_{\\pc'}$ references the heap is by $\\Inv$.\n\\item From def \\ref{def:local_validity_method} we know that $A_{\\pc'}$ does not mention the stack.\n\\item From def of $\\WP^E$ we know that $A_{\\pc'}$ held at $C''$ and that nothing $A_{\\pc'}$ mentiones has changed since then.\n\\end{enumerate}\n\\end{proof}}\n\n\\sep\n\n\\newpage\n\n%\\sect{\\begin{lemma}[At most one push to ar-stack]\\label{lem:most_one_ar_push}\n%If $(h, R) \\rightarrow (h', R'++R)$, then $R'$ is of the shape $nil$ or $a$ (single activation record). (Or, in words, a transition adds \\emph{at most one} activation record to the activation record stack.)\n%\\end{lemma}\n%\\paragraph{Proof} Case analysis of possible transitions.\n%}\n\n\\sect{\\begin{lemma}[Activation Record Suffixes]\\label{lem:ar_suffixes}\n%If $(h, R) \\rightarrow (h', R')$, and $R''$ is a proper suffix of $R'$, then $R''$ is a suffix of $R$.\nIf $(h, R) \\rightarrow (h', a::R')$ then $R'$ is a suffix of $R$.\n\\end{lemma}\n\\begin{proof} Case analysis of possible transitions.\\end{proof}\n}\n\n\n\\sep\n\n\n\\sect{\\begin{lemma}[All activation records in current ar-stack has been on top]\\label{lem:all_suffs_in_ex}\nIf $\\ex = (h_0, R_0)\\ldots (h,R)$ is an execution of $P$, then for all non-empty suffixes $R''$ of $R$, there exists a heap $h''$ such that $(h'', R'')$ is a configuration in $\\ex$.\n\\end{lemma}\n\\begin{proof} By induction on the structure of an execution.\n\\begin{itemize}\n\\item Base Case: $\\ex = (h_0, R_0)$ (an initial configuration)\n  \\begin{enumerate}\n  \\item Assume $\\ex$ is an execution of $P$.\n  \\item Since $(h_0, R_0)$ must be an initial configuration, we have $R_0 = \\ar :: nil$.\n  \\item The only non-empty suffix $R''$ of $\\ar::nil$ is $\\ar::nil$.\n  \\item Thus there exists an $h''$, namely $h_0$ such that $(h'', R'') \\in \\ex$.\n  \\end{enumerate}\n\\item Inductive Step: $\\ex = \\ex'(h,R)(h', R')$\n  \\begin{enumerate}\n  \\item Assume $\\ex$ is an execution of $P$.\n  \\item Assume $R''$ is a non-empty suffix of $R'$.\n  \\item We do a case split on the type of suffix:\n    \\begin{itemize}\n      \\item $R' = R''$ ($R''$ is a ``non-proper'' suffix):\n        \\begin{enumerate}\n        \\item There exists an $h''$, namely $h'$ such that $(h'', R'') \\in \\ex(h,R)(h', R')$\n        \\end{enumerate}\n      \\item $R' = a_0::...::a_k::R''$ ($R''$ is a proper suffix):\n        \\begin{enumerate}\n        \\item Since $\\ex(h,R)(h',R')$ is an execution, we have $(h, R) \\rightarrow (h', R')$.\n        \\item By lemma \\ref{lem:ar_suffixes} we know that $R''$ is a suffix of $R$.\n        \\item By IH we know that this lemma holds for $\\ex(h, R)$.\n        \\item Therefor there exists a $h''$ such that $(h'', R'') \\in \\ex (h, R)$\n        \\item Thus there exists a $h''$ such that $(h'', R'') \\in \\ex (h, R) (h', R')$\n        \\end{enumerate}\n    \\end{itemize}\n\n\n  \\end{enumerate}\n\\end{itemize}\n\\end{proof}\n}\n\n\n\\sep\n\n\n\\sect{\n\\begin{theorem}[Local Validity implies Global Validity]\n  For any annotated program $P$, if $P$ is locally valid, then $P$ is globally valid.\n\\end{theorem}\n\n\\begin{proof}\n\\begin{enumerate}\n\\item Assume that $P$ is locally valid.\n\\item Pick an arbitrary execution $\\ex$ of $P$ and show that it is valid.\n\\item Proceed by structural induction on $\\ex$. (Note that executions are not empty.)\n  \\begin{description}\n  \\item[Base Case:] $\\ex$ can be written as $C_0$ where $C_0$ denotes an initial configuration.\n    \n    \\begin{enumerate}\n    \\item By definition, $\\Default$ holds in $C_0$.\n    \\item By def \\ref{def:local_validity_program}.2 $\\Inv$ holds in $C_i$.\n    \\item To show that $\\ex$ is a valid execution, we show:\n      \\begin{itemize}\n      \\item If $C_0$ is visible (calling or returning), then $\\Inv$ holds.\n        \n        \\begin{enumerate}\n        \\item That $\\Inv$ holds in $C_0$ is established above.\n        \\end{enumerate}\n        \n      \\item If $C_0$ is of the form $(h, (c, m, \\pc, s, l)::R)$, then $\\| A_{\\pc} \\| C_i$ holds.\n        \n        \\begin{enumerate}\n        \\item That $\\Inv$ holds in $C_0$ is established above.\n        \\item By def \\ref{def:local_validity_method}.1 $\\|A_0\\|C_i$ holds.\n        \\end{enumerate}\n\n      \\end{itemize}\n    \\end{enumerate}\n    \n    \n  \\item[Inductive Case:] $\\ex$ can be written as $\\ex'C_i$ where $\\ex'$ is a valid execution.\n    \n    According to def of valid execution, we need to show that\n    \\begin{itemize} \n      \\item If $C_i$ is of the form $(h', (c', m', \\pc', s', l')::R')$, then $\\| A_{\\pc'} \\| C_i$ holds.\n      \n      Note that by IH, $\\ex'$ is a valid execution and thus of length at least 1. We split proof into two cases:\n      \\begin{itemize}\n      \\item Previous configuration is normal: $C_{i-1} = (h, (c, m, \\pc, s, l)::R)$\n\n        \\begin{enumerate}\n          \\item By IH we know that $\\| A_{\\pc} \\| C_{i-1}$ holds.\n          \\item By local validity we therefor know $\\| \\WP_{c.m}(\\pc) \\|C_{i-1}$.\n          \\item By lemma \\ref{lem:wp_correct_normal}, $\\| A_{\\pc'} \\| C_i$ holds.\n        \\end{enumerate}\n        \n      \\item Previous configuration is exceptional: $C_{i-1} = (h, (o)::R)$\n        \n        \\begin{enumerate}\n          \\item First note that $R$ may not be nil since we do have a successor.\n          \\item By lemma \\ref{lem:at_most_one_exc_arec} we know that $R$ can be written on the form $(c, m, \\pc, s, l)::R''$.\n          \\item Let $C''$ denote the configuration at which $(c, m, \\pc, s, l)$ was the top of the ar-stack. (Some such configuration exists according to lem \\ref{lem:all_suffs_in_ex}.)\n          \\item By IH we know that $\\| A_{\\pc} \\| C''$ hold.\n          \\item By local validity we thus know that $\\| \\WP_{c.m}(\\pc) \\| C''$ hold.\n          \\item By lemma \\ref{lem:wp_correct_exceptional}, $\\| A_{\\pc'} \\| C_i$ holds.\n        \\end{enumerate}\n        \n      \\end{itemize}\n      \n    \\item If $C_i$ is calling, then $\\Inv$ holds.\n      \\begin{enumerate}\n      \\item Due to lemma \\ref{lem:invoke_only_caller}, we know that the current instruction is an invoke.\n      \\item Since $\\WP$ of an invoke instruction is $\\Inv$ we know by def \\ref{def:local_validity_method}.2 that the current assertion implies $\\Inv$.\n      \\item By the same reasoning as above, we know that the current assertion holds, thus $\\Inv$ holds.\n      \\end{enumerate}\n    \\item If $C_i$ is returning, then $\\Inv$ holds.\n\n      (Sketch) Should be ensured by local validity + def of $\\WP$\n      \n      \\begin{itemize}\n      \\item Normal return: $\\WP^N$\n      \\item Exceptional return: $\\WP^E$\n      \\end{itemize}\n      \n      \n    \\end{itemize}\n    \n  \\end{description}\n\\end{enumerate}\n\\end{proof}\n}\n\n\n\\newpage\n\\section{EXISTS\\_EXEC\\_WITH\\_EQ\\_GUS}\n\\newcommand{\\ssus}{\\mathit{ssus}}\n\\newcommand{\\gus}{\\mathit{gus}}\n\\newcommand{\\sst}{\\mathit{sst}}\n\\renewcommand{\\ss}{\\mathit{ss}}\n\\newcommand{\\gv}{\\mathit{gv}}\n\\newcommand{\\pref}{\\mathit{pref}}\n\n\\begin{lemma}[before\\_gu\\_precedes\\_before\\_ssu]\\label{lem:before_gu_precedes_before_ssu}\nAn instruction that causes a sec-state-update of the shape {\\tt contract after c m} is always preceded by an instruction on the form {\\tt ghost\\_update (contract after c m)}.\n\\end{lemma}\n\\begin{proof}\nTBD.\n\\end{proof}\n\n\n\\begin{lemma}[gu\\_after\\_follows\\_ssu\\_after]\\label{lem:gu_after_follows_ssu_after}\nAn instruction causing a sec-state-update of the shape {\\tt contract after c m} may be followed by an instruction on the form {\\tt ghost\\_update (contract after c m)}.\n\\end{lemma}\n\\begin{proof}\nTBD.\n\\end{proof}\n\n\\begin{lemma}[after\\_su\\_precedes\\_after\\_gu]\\label{lem:after_su_precedes_after_gu}\nAn instruction on the form {\\tt ghost\\_update (contract before c m)} is always preceded by an instruction that causes a {\\tt before c m}-event (which in turn gives rise to a sec-state-update of the shape {\\tt contract before c m}).\n\\end{lemma}\n\\begin{proof}\nTBD.\n\\end{proof}\n\n\\begin{lemma}[exec\\_tail\\_cases]\\label{lem:exec_tail_cases}\nFor each execution $E$ of a ghost inlined program, that ends in a configuration $C$, we have:\n\\\\\\begin{tabular}{llll}\n1: & (1a) $C = $ {\\tt before-ghost-update gu}      & and (1b) {\\tt (ssus $E$) ++ gu = gus $E$}   & OR \\\\\n2: & (2a) $C = $ {\\tt before-sec-state-update}     & and (2b) {\\tt ssus $E$ = gus $E$}           & OR \\\\\n3: & (3a) $C = $ {\\tt after-sec-state-update ssu}  & and (3b) {\\tt ssus $E$ = (gus $E$) ++ ssu}  & OR \\\\\n4: & (4a) $C = $ {\\tt after-ghost-update gu}       & and (4b) {\\tt ssus $E$ = gus $E$}           & OR \\\\\n5: & (5a) $C = $ {\\tt none of the above}           & and (5b) {\\tt ssus $E$ = gus $E$}           &\n\\end{tabular}\n\\end{lemma}\n\n\\begin{proof}\nThis can be shown by induction over the length of $E$. The base case is trivial. Case 2 should follow from lemma \\ref{lem:before_gu_precedes_before_ssu}. Case 4 should follow from lemma \\ref{lem:after_su_precedes_after_gu}.\n\\end{proof}\n\n\\begin{lemma}[EXISTS\\_EXEC\\_WITH\\_EQ\\_GUS]\\label{lem:exists_exec_with_eq_gus}\nFor all executions $E$ of a ghost inlined program, there exists an extended execution $E'$ of $E$, such that the ghost state updates of $E'$ ($\\gus(E')$) equal the security state updates of $E$ ($\\ssus(E)$).\n\\end{lemma}\n\n\\begin{proof}\n  \\begin{enumerate}\n  \\item Pick an arbitrary $E$ (and show $\\exists E', \\ssus(E) = \\gus(E')$.\n  \\item The case in which $E = \\mathit{nil}$ is trivial, thus we assume that $E = E0 \\app C$.\n  \\item Thus we have left to show $\\exists E', \\ssus(E0 \\app C) = \\gus(E')$.\n  \\item We do a case-split on the type of $C$ according to lemma \\ref{lem:exec_tail_cases} above.\n    \n    \\begin{enumerate}\n    \\item[Case 1:]\n      \\begin{enumerate}\n      \\item We choose $E0$ as our $E'$ and show that $\\ssus(E0 \\app C) = \\gus(E0)$.\n      \\item (1b) gives $(\\ssus E0 \\app C) \\app \\mathit{gu} = \\gus(e0 \\app c)$.\n      \\item Using (1a) we rewrite it as $(\\ssus E0 \\app C) = \\gus(e0)$.\n      \\end{enumerate}\n    \\item[Case 2:]\n      \\begin{enumerate}\n      \\item We choose $E0 \\app C$ as our $E'$.\n      \\item $\\ssus(E0 \\app C) = \\gus(E0 \\app C)$ follows from (2b).\n      \\end{enumerate}\n    \\item[Case 3:]\n      \\begin{enumerate}\n      \\item According to (3a) the configuration $C$ points at a {\\tt ret}-instruction.\n      \\item Let $C'$ be the configuration that follows after executing the {\\tt ret} from $C$.\n      \\item We choose $E0 \\app C \\app C'$ as our $E'$ and show that $\\ssus(E0 \\app C) = \\gus (E0 \\app C \\app C')$.\n      \\item According to (3b) we have $\\ssus(E0 \\app C) = \\gus(E0 \\app C) \\app \\mathit{ssu}$.\n      \\item According to lemma \\ref{lem:gu_after_follows_ssu_after}, $C'$ points at the instruction {\\tt ghost\\_update ssu}.\n      \\item Thus we have $\\ssus(E0 \\app C) = \\gus(E0 \\app C \\app C')$.\n      \\end{enumerate}\n    \\item[Case 4:]\n      \\begin{enumerate}\n      \\item We choose $E0 \\app C$ as our $E'$.\n      \\item $\\ssus(E0 \\app C) = \\gus(E0 \\app C)$ follows from (4b).\n      \\end{enumerate}\n    \\item[Case 5:]\n      \\begin{enumerate}\n      \\item We choose $E0 \\app C$ as our $E'$.\n      \\item $\\ssus(E0 \\app C) = \\gus(E0 \\app C)$ follows from (4b).\n      \\end{enumerate}\n    \\end{enumerate}\n  \\end{enumerate}\n\\end{proof}\n\n\\sep\n\n\n\n\\newpage\n\\section{SST\\_SUBSET\\_GVS}\n\n\\begin{lemma}[EXISTS\\_SSUS\\_PREFIX]\\label{lem:exists_ssus_prefix}\nFor all executions $E$, if $\\sst$ is the security state trace of the sec-state updates $\\ssus(E)$ and $\\ss \\in \\sst$, then there exists a prefix $\\ssus_\\pref$ of $\\ssus(E)$ such that $\\ssus_\\pref$ takes the initial sec-state to $\\ss$.\n\\end{lemma}\n\\begin{proof}\nI'm guessing: By induction on the length of $\\ssus$. Try it out in Coq.\n\\end{proof}\n\n\\sep\n\n\\begin{lemma}[GUS\\_PREF\\_IMPLIES\\_EXEC\\_PREF]\\label{lem:gus_pref_implies_exec_pref}\nFor all executions $E$, If $\\gus_\\pref$ is a prefix of $\\gus(E)$, then there exists a prefix $E_\\pref$, such that $\\gus_\\pref = \\gus(E_\\pref)$.\n\\end{lemma}\n\\begin{proof}\nInversion on the prefix-predicate + induction. I have a Coq-proof outline for this.\n\\end{proof}\n\n\\sep\n\n\\begin{lemma}[SS\\_AFTER\\_EQUALS\\_GV\\_LAST]\\label{lem:ss_after_equals_gv_last}\nFor all executions on the form $E$, security update lists $\\ssus$ % Not neccesarily ssus of E!\nand security states $\\ss$, if $\\ssus$ takes the initial security state to $\\ss$, and $\\ssus = gus(E)$, then $E$ is on the form $E' \\app (\\ss, \\_, \\_)$.\n\\end{lemma}\n\\begin{proof}\nI'm guessing: Induction on $\\ssus$. Try it out in Coq.\n\nEDIT: Seems to work out!\n\\end{proof}\n\n\\sep\n\n\\begin{lemma}[SSUS\\_EQ\\_GUS\\_IMPLIES\\_SST\\_SUBSET\\_GVS]\\label{lem:ssus_eq_gus_implies_sst_subset_gvs}\nFor all executions $E$ and $E'$ of a program, such that $\\ssus(E) = \\gus(E')$, then $\\sst(E) \\subseteq \\{ \\gv \\mid (gv, \\_, \\_) \\in E'\\}$.\n\\end{lemma}\n\n\\begin{proof}\n\\begin{enumerate}\n\\item Pick an arbitrary $\\ss \\in \\sst(E)$ (and then show that $(\\ss, \\_, \\_) \\in E'$)\n\\item Let $\\pref$ denote the prefix of $\\ssus(E)$ which takes the initial sec-state to $ss$. (Such prefix exists due to lemma \\ref{lem:exists_ssus_prefix}).\n\\item Since $\\ssus(E) = \\gus(E')$, $\\pref$ is also a prefix of $\\gus(E')$.\n\\item By lemma \\ref{lem:gus_pref_implies_exec_pref}, there exists a prefix $E'_\\pref$ of $E'$, such that $\\gus(E'_\\pref) = \\pref$.\n\\item Since $\\pref$ takes the initial sec-state to $\\ss$, lemma \\ref{lem:ss_after_equals_gv_last} says that $E'_\\pref$ ends with $(\\ss, \\_, \\_)$.\n\\item Since $(\\ss, \\_, \\_) \\in E'_\\pref$ we have $(\\ss, \\_, \\_) \\in E'$\n\\end{enumerate}\n\\end{proof}\n\n\\sep\n\n\n\\begin{lemma}[SST\\_SUBSET\\_GVS]\nFor all ghost inlined programs $P^g = {\\cal I}^g(P, \\cal C)$, executions $E^g$ of $P^g$, let $\\sst$ denote the security automaton trace (under $\\cal C$), then there exists an execution $E'^g$ of $P^g$ such that $\\sst \\subseteq \\{ \\gv \\mid (gv, \\_, \\_) \\in E'^g \\}$.\n\\end{lemma}\n\n\\begin{proof}\n\\begin{enumerate}\n\\item Let $E'^g$ be the extended execution of $E^g$ such that $\\gus(E'^g) = \\ssus(E^g)$. (Such execution exists by lemma \\ref{lem:exists_exec_with_eq_gus}.\n\\item By lemma \\ref{lem:ssus_eq_gus_implies_sst_subset_gvs}, $\\sst \\subseteq \\{ \\gv \\mid (gv, \\_, \\_) \\in E'^g \\}$.\n\\end{enumerate}\n\\end{proof}\n\n\\sep\n\n\\end{document}\n", "meta": {"hexsha": "be57fc447ffbf5389c02fecfd2cc01c269971bc4", "size": 29514, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/outline.tex", "max_stars_repo_name": "palmskog/pcc", "max_stars_repo_head_hexsha": "2b16af3e282268e4f4adc9f6b7d3fda082b4a101", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-21T22:15:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T12:52:11.000Z", "max_issues_repo_path": "doc/outline.tex", "max_issues_repo_name": "palmskog/pcc", "max_issues_repo_head_hexsha": "2b16af3e282268e4f4adc9f6b7d3fda082b4a101", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/outline.tex", "max_forks_repo_name": "palmskog/pcc", "max_forks_repo_head_hexsha": "2b16af3e282268e4f4adc9f6b7d3fda082b4a101", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.7893175074, "max_line_length": 341, "alphanum_fraction": 0.6073727722, "num_tokens": 10076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.33831087082935035}}
{"text": "\\documentclass[11pt,a4paper]{report}\n\\usepackage{amsmath,amsfonts,amssymb,amsthm,epsfig,epstopdf,titling,url,array}\n\\usepackage{enumitem}\n\\usepackage{changepage}\n\\usepackage{graphicx}\n\\usepackage{caption}\n\\usepackage{listings}\n\\usepackage{color}\n\\usepackage[utf8]{inputenc}\n\\usepackage[english]{babel}\n\\usepackage{hyperref}\n\\hypersetup{\n\tcolorlinks=true,\n\tlinkcolor=blue,\n\tfilecolor=magenta,      \n\turlcolor=cyan,\n}\n\\urlstyle{same}\n\\theoremstyle{plain}\n\\newtheorem{thm}{Theorem}[section]\n\\newtheorem{lem}[thm]{Lemma}\n\\newtheorem{prop}[thm]{Proposition}\n\\newtheorem*{cor}{Corollary}\n\\theoremstyle{definition}\n\\newtheorem{defn}{Definition}[section]\n\\newtheorem{conj}{Conjecture}[section]\n\\newtheorem{exmp}{Example}[section]\n\\newtheorem{exercise}{Exercise}[section]\n\\theoremstyle{remark}\n\\newtheorem*{rem}{Remark}\n\\newtheorem*{note}{Note}\n\\def\\changemargin#1#2{\\list{}{\\rightmargin#2\\leftmargin#1}\\item[]}\n\\let\\endchangemargin=\\endlist \n\n\\definecolor{codegreen}{rgb}{0,0.6,0}\n\\definecolor{codegray}{rgb}{0.5,0.5,0.5}\n\\definecolor{codepurple}{rgb}{0.58,0,0.82}\n\\definecolor{backcolour}{rgb}{0.95,0.95,0.92}\n\n\\lstdefinestyle{mystyle}{\n\tbackgroundcolor=\\color{backcolour},   \n\tcommentstyle=\\color{codegreen},\n\tkeywordstyle=\\color{magenta},\n\tnumberstyle=\\tiny\\color{codegray},\n\tstringstyle=\\color{codepurple},\n\tbasicstyle=\\footnotesize,\n\tbreakatwhitespace=false,         \n\tbreaklines=true,                 \n\tcaptionpos=b,                    \n\tkeepspaces=true,                 \n\tnumbers=left,                    \n\tnumbersep=5pt,                  \n\tshowspaces=false,                \n\tshowstringspaces=false,\n\tshowtabs=false,                  \n\ttabsize=2\n}\n\n\\lstset{style=mystyle}\n\\begin{document}\n\n\\section*{Problem}\nFind the smallest number that is divisible by all of the digits 2, ..., 9.\n\\\\\\\\\nThis problem is from \\href{https://www.morningbrew.com} {The Morning Brew}.\n\n\\section*{Solution} Our strategy will be to keep track of the required\nprime factors and their highest exponents.  Suppose that $x$ is divisible by\neach number in \\\\ $D = \\{2, ..., 9\\}.$  Then for each $d$ in $D$, $x$'s prime\nfactorization must include all of the primes in $d$'s prime factorization with\nequal or greater exponents.  \\\\ Starting with 2, that adds $2^1$ to the required\nprimes in $x$.  Next is 3, where we add a similar term for 3.  Continuing, 4 ups\nthe required exponent on 2 to 2, 5 adds $5^1$, 6 is covered (already have 2 and\n3 required), 7 adds $7^1$, 8 ups the exponent on 2 to 3,  and 9 ups the exponent\non 3 to 2.  Putting this all together, to be divisible by each of the digits,\n$x$ must be at least $$ 2^{3}3^{2}5^{1}7^{1} = 2520 $$\n\n\\end{document}", "meta": {"hexsha": "95780582e5792d7c8f5ecfdbc9ec7953faac941f", "size": 2641, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "digits2/document.tex", "max_stars_repo_name": "psteitz/problems", "max_stars_repo_head_hexsha": "c231561593ef7de6264c21d2c78d736866c1b341", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "digits2/document.tex", "max_issues_repo_name": "psteitz/problems", "max_issues_repo_head_hexsha": "c231561593ef7de6264c21d2c78d736866c1b341", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-03T21:08:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T21:08:11.000Z", "max_forks_repo_path": "digits2/document.tex", "max_forks_repo_name": "psteitz/problems", "max_forks_repo_head_hexsha": "c231561593ef7de6264c21d2c78d736866c1b341", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.858974359, "max_line_length": 80, "alphanum_fraction": 0.7054146157, "num_tokens": 823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.33831087082935035}}
{"text": "\\documentclass[english,10pt,a4paper,twocolumn,colorscheme=green]{orarticle}\n\\usepackage{hyperref}\n\\usepackage{bbm}\n\n\\usepackage{listings}\n\\lstset{\n\tlanguage=C++,\n\tcommentstyle=\\color{darkgreen}\\textit,\n\tframe=single,\n\ttabsize=4,\n\tkeywordstyle=\\color{blue}\\bfseries,\n\tstringstyle=\\color[gray]{0.4},\n\tbasicstyle=\\lst@ifdisplaystyle\\scriptsize\\else\\ttfamily\\fi,\n\tmorekeywords={uint16, uint32, Vec2, Vec3}\n}\n\n\\begin{document}\n\n\t\\titlehead{\\begin{minipage}{0.5\\linewidth}\n\t\t\\begin{center}\n\t\tOtto-von-Guericke-University Magdeburg\\\\\n\t\tFaculty of Computer Science\\\\\n\t\tISG - Computational Visualistics\n\t\t\\end{center}\n\t\\end{minipage}}\n%\t\\subject{File Format Documentation}\n\t\\title{Fitting Minimal Bounding Ellipsoids}\n\t\\authors{Johannes Jendersie}\n\t\\abstract{Abstract}{\n\t\tBuilding a bounding volume hierarchy with axis aligned ellipsoids can be done with different fitting strategies. One could search the Löwner-John ellipsoid for the convex hull of the geometry in a subtree. This is complicated and relatively slow depending on the build method. I purpose an approximative and iterative solution which uses two operations: fit an ellipsoid with known center and a single point and fit an ellipsoid to two given ellipsoids.\n\t}\n\t\\thispagestyle{empty}\n\t\\maketitle\n\t\n\t\n\t% ************************************************************************ %\n\t\\section{Minimal Ellipsoid}\n\tThere are multiple representations of the ellipsoid: implicit (also in matrix form) and parametric.\n\t\\begin{align}\n\t\\left\\lVert\\frac{\\mathbbm{x}-\\mathbbm{c}}{\\mathbbm{a}}\\right\\rVert &= 1\\\\\n\t(\\mathbbm{x}-\\mathbbm{c})^T diag(\\mathbbm{a}) (\\mathbbm{x}-\\mathbbm{c}) &= 1\\\\\n\t\\mathbbm{a}\\cdot\\begin{pmatrix}\n\t\t\\cos(u) \\cos(v)\\\\\n\t\t\\cos(u) \\sin(v)\\\\\n\t\t\\sin(u)\n\t\\end{pmatrix} &= \\mathbbm{x}\n\t\\end{align}\n\twhere $\\mathbbm{c}$ is the center and $\\mathbbm{a}$ is the vector of radii. Each vector operation inclusive the division is component-wise.\n\t\n\tThe minimal ellipsoid is usually defined as the ellipsoid of minimal volume:\n\t\\begin{align}\n\t\tV = \\frac{4}{3}\\pi \\prod_{i=1}^d \\mathbbm{a}_i\n\t\\end{align}\n\tIn degenerated cases where some of the radii are 0, which may happen if fitting ellipsoids to axis aligned triangles, the volume becomes 0 too. In that case the minimal ellipses (smallest) area is searched.\n\t\n\t% ************************************************************************ %\n\t\\section{Point and Center Known}\n\t\n\tFinding a minimal ellipsoid with a known center $\\mathbbm{a}$ to contain a point is equivalent to find the minimal ellipsoid to a symmetric box with that point as one corner and the same center.\n\t\n\t\\begin{figure}[h]\n\t\\includegraphics[width=\\linewidth]{img/ellipsoidpointfitting}\n\t\\caption{Finding the best ellipsoid for a point is equivalent to that of a symmetric box. On the right side the space is rescaled such that the ellipsoid becomes a sphere.}\n\t\\end{figure}\n\tThe optimal bounding sphere for a cube with side length $s$ has $r = s\\frac{\\sqrt{3}}{2}$. The $\\sqrt{3}$ comes from the euclidean length from the center to one corner $\\sqrt{3\\cdot\\frac{s^2}{2^2}}$. In the general case for $d$ dimensions the factor is $\\frac{\\sqrt{d}}{2}$. In case of an ellipsoid the only difference is that the space must be scaled first which happens when use a vector of three side lengths $2\\lvert\\mathbbm{x}-\\mathbbm{c}\\rvert$ instead of $s$. In the degenerated case where one or more of that lengths are 0 the factor shrinks.\n\t\\begin{align}\n\t\t\\mathbbm{a} = \\lvert\\mathbbm{x}-\\mathbbm{c}\\rvert\\cdot\\sqrt{\\sum_{i=1}^d (\\mathbbm{x}_i-\\mathbbm{c}_i) \\neq 0}\n\t\\end{align}\n\t\n\t\\textbf{Proof} There are infinite many ellipsoid through the given point, which can be computed as:\n\t\\begin{align*}\n\t\t\\left\\{\\mathbbm{a}_0, \\mathbbm{a}_1, \\sqrt{\\frac{(\\mathbbm{x}_2-\\mathbbm{c}_2)^2}{1-\\frac{\\mathbbm{x}_0-\\mathbbm{c}_0}{\\mathbbm{a}_0}^2 - \\frac{\\mathbbm{x}_1-\\mathbbm{c}_1}{\\mathbbm{a}_1}^2}}\\right\\}\n\t\\end{align*}\n\twhere $\\mathbbm{a}_0, \\mathbbm{a}_1$ can be chosen freely.\n\tW.l.o.g. an ellipsoid with $\\mathbbm{a}_0 - \\epsilon$ which again contains the point $\\mathbbm{x}$ has a larger volume than the proposed solution.\n\t\n\t\\begin{align*}\n\t\tV(\\mathbbm{a}) &< V(\\mathbbm{a}')\\\\\n\t\ts_i &= \\lvert \\mathbbm{x}_i-\\mathbbm{c}_i \\rvert\\\\\n\t\t\\mathbbm{a}_0 \\cdot\\mathbbm{a}_1 \\cdot\\mathbbm{a}_2 &< (\\mathbbm{a}_0-\\epsilon) \\cdot\\mathbbm{a}_1 \\cdot\\sqrt{\\frac{s_2^2}{1-\\frac{s_0}{\\mathbbm{a}_0-\\epsilon}^2 - \\frac{s_1}{\\mathbbm{a}_1}^2}}\\\\\t\n\t\t3\\cdot s_0\\cdot s_2 &< (\\mathbbm{a}_0-\\epsilon) \\cdot\\sqrt{\\frac{s_2^2}{1-\\frac{s_0}{\\mathbbm{a}_0-\\epsilon}^2 - \\frac{1}{\\sqrt{3}}}}\\\\\n\t\t9\\cdot s_0^2 &< (\\sqrt{3}\\cdot s_0-\\epsilon)^2 \\cdot\\frac{1}{1-\\frac{s_0}{\\sqrt{3}s_0-\\epsilon}^2 - \\frac{1}{\\sqrt{3}}}\\\\\n\t\t9-\\frac{9}{\\sqrt{3}}\\cdot s_0^2 &- 9 \\cdot \\frac{s_0^4}{(\\sqrt{3}s_0-\\epsilon)^2} < (\\sqrt{3}\\cdot s_0-\\epsilon)^2\\\\\n\t%\t(\\sqrt{3}\\cdot s_0-\\epsilon)^2 &\\cdot (1-\\frac{1}{\\sqrt{3}}\\cdot s_0^2) - s_0^4 < \\frac{(\\sqrt{3}\\cdot s_0-\\epsilon)^4}{9}\\\\\n\t\\end{align*}\n\t\n\tWell I don't see how to simplify this... but testing it seemed ok.\n\t\n\\end{document}", "meta": {"hexsha": "7062d8059e1e8d661644694e083124ec809785ce", "size": 5006, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "documentation/ellipsoidfitting.tex", "max_stars_repo_name": "Wumpf/gpugi", "max_stars_repo_head_hexsha": "55fb5d9cf12b34b22e1df0d54c64c1c6e74d8e58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2015-06-22T06:36:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-23T20:56:44.000Z", "max_issues_repo_path": "documentation/ellipsoidfitting.tex", "max_issues_repo_name": "Wumpf/gpugi", "max_issues_repo_head_hexsha": "55fb5d9cf12b34b22e1df0d54c64c1c6e74d8e58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2015-02-20T14:21:53.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-20T14:22:02.000Z", "max_forks_repo_path": "documentation/ellipsoidfitting.tex", "max_forks_repo_name": "Wumpf/gpugi", "max_forks_repo_head_hexsha": "55fb5d9cf12b34b22e1df0d54c64c1c6e74d8e58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2016-04-30T13:53:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-20T14:52:57.000Z", "avg_line_length": 56.2471910112, "max_line_length": 551, "alphanum_fraction": 0.6927686776, "num_tokens": 1723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.33831087082935035}}
{"text": "\\documentclass[a4paper,12pt]{article} % This defines the style of your paper\n\n\\usepackage[top = 2.5cm, bottom = 2.5cm, left = 2.5cm, right = 2.5cm]{geometry} \n\\usepackage[utf8]{inputenc} %utf8 % lettere accentate da tastiera\n\\usepackage[english]{babel} % lingua del documento\n\\usepackage[T1]{fontenc} % codifica dei font\n\n\\usepackage{multirow} % Multirow is for tables with multiple rows within one \n%cell.\n\\usepackage{booktabs} % For even nicer tables.\n\n\\usepackage{graphicx} \n\n\\usepackage{setspace}\n\\setlength{\\parindent}{0in}\n\n\\usepackage{float}\n\n\\usepackage{fancyhdr}\n\n\\usepackage{caption}\n\\usepackage{amssymb}\n\\usepackage{amsmath}\n\\usepackage{mathtools}\n\\usepackage{color}\n\n\\usepackage[hidelinks]{hyperref}\n\\usepackage{csquotes}\n\\usepackage{subfigure}\n\n\\newcommand{\\footlabel}[2]{%\n\t\\addtocounter{footnote}{1}%\n\t\\footnotetext[\\thefootnote]{%\n\t\t\\addtocounter{footnote}{-1}%\n\t\t\\refstepcounter{footnote}\\label{#1}%\n\t\t#2%\n\t}%\n\t$^{\\ref{#1}}$%\n}\n\n\\newcommand{\\footref}[1]{%\n\t$^{\\ref{#1}}$%\n}\n\n\\pagestyle{fancy}\n\n\\setlength\\parindent{24pt}\n\n\\fancyhf{}\n\n\\lhead{\\footnotesize Deep Learning Lab: Assignment 2}\n\n\\rhead{\\footnotesize Giorgia Adorni}\n\n\\cfoot{\\footnotesize \\thepage} \n\n\\begin{document}\n\t\n\n\t\\thispagestyle{empty}  \n\t\\noindent{\n\t\\begin{tabular}{p{15cm}} \n\t\t{\\large \\bf Deep Learning Lab} \\\\\n\t\tUniversità della Svizzera Italiana \\\\ Faculty of Informatics \\\\ \\today  \\\\\n\t\t\\hline\n\t\t\\\\\n\t\\end{tabular} \n\t\n\t\\vspace*{0.3cm} \n\t\n\t\\begin{center}\n\t\t{\\Large \\bf Assignment 2: Convolutional Neural Network}\n\t\t\\vspace{2mm}\n\t\t\n\t\t{\\bf Giorgia Adorni (giorgia.adorni@usi.ch)}\n\t\t\n\t\\end{center}  \n}\n\t\\vspace{0.4cm}\n\n\t%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\t%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\t\n\t\\section{Introduction}\n\tThe scope of this project is to implement a convolutional neural network to \n\tclassify the images in the CIFAR-10 dataset.\n\t\n\tFirst of all, the original training set has been shuffled and divided into \n\ttrain and validation sets, with $49000$ and $1000$ images respectively. A \n\tseed has been used to reproduce the same sample split and use them in the \n\tdifferent models. Instead, the test set provided contains $10000$ images.\n\t\n\tA certain preprocessing has been applied to the data. The pixel values of \n\teach sample, initially comprised between 0 and 255, have been rescaled \n\tbetween 0 and 1. To represent the class assignments, which were integers \n\tbetween 0 and 9, three binary assignment matrices have been created, one \n\tfor each set of data. \n\t\n\tThe architecture of the convolutional neural network follows the \n\tinstructions provided, as well as the hyper-parameter values for the models \n\tpresented in Sections \\ref{section:model0} and \\ref{section:dropout}.\n\tIn the training phase, mini-es were used. In particular, each \n\tepoch splits the training set in different samples of data.\n\t\n\tAll the models were implemented using \\texttt{TensorFlow} and trained on an \n\tNVIDIA Tesla V100-PCIE-16GB GPU.\n\t\n\tNote: Since mini-batches are used during the training of the models, the \n\tloss and the accuracy of all samples are averaged, obtaining a less noisy \n\testimate.\n\t\n\t\\section{Performance of the initial model}\n\t\\label{section:model0}\n\tIn Table \\ref{tab:model0} is summarised the architecture of the network \n\tused in the first experiment.\t\n\t\n\t\\begin{figure}[H]\n\t\t\\centering\n\t\t\n\t\t\\begin{tabular}{cccccccc}\n\t\t\\toprule\n\t\t\\textbf{conv1} & \\textbf{conv2} & \\textbf{mpool1} & \\textbf{conv3} &\n\t\t\\textbf{conv4} & \\textbf{mpool1} &   \\textbf{fc} &\n\t\t\\textbf{softmax} \\\\\n\t\t\\midrule\n\t\t3$\\times$3,  32 & 3$\\times$3, 32 & 2$\\times$2 &3$\\times$3, 64 & \n\t\t3$\\times$3, 64  & 2$\\times$2  & 512 & 10\\\\\n\t\ts. 2$\\times$2 &   s. 2$\\times$2 &   s. 1$\\times$1 & s. 1$\\times$1  & s. \n\t\t2$\\times$2 & s. 2$\\times$2 && \\\\\n\t\tp. same & p. same & p. same  & p. same & p. same & p. same &&\\\\\n\t\t\\bottomrule\n\t\t\\end{tabular}\n\t\t\\captionof{table}{Network architecture}\n\t\t\\label{tab:model0}\n\t\\end{figure}\n\t\n\tThe model is trained for $50$ epochs and \\texttt{Adam} is used as \n\toptimiser with learning rate $0,001$.\n\tAs loss function, the Softmax Cross Entropy with Logits is used since the \n\tmodel is a multi-class classifier. Moreover, once per epoch, is documented \n\tthe classification accuracy on both the train and validation set.\n\tThe performance is shown in Figure \\ref{fig:model0-performance}.\n\t\n\t\\begin{figure}[H]\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/1-Accuracy.png}\n\t\t\t\\caption*{(a)}\n\t\t\\end{minipage}\n\t\t~\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/1-Loss.png}\n\t\t\t\\caption*{(b)}\n\t\t\\end{minipage}\n\t\t\\caption{Training and validation curves in the initial model}\n\t\t\\label{fig:model0-performance}\n\t\\end{figure}\n\t\n\tAs can be seen in Figure (a), the training accuracy rapidly grows up to \n\t$100\\%$, while the validation accuracy remains stable at $70\\%$.  \n\tThe final accuracy on the valid set is $70.30\\%$.\n\tFor what concerns the loss, it is clear that the model overfits the data. \n\tThe training loss is close to $0$ while the validation one \n\tdiverges.\n\t\n\t\\begin{table}[H]\n\t\t\\centering\n\t\t\\begin{tabular}{l@{\\hspace{.5cm}}cc|cc|c}\n\t\t\t\\toprule\n\t\t\t& \\multicolumn{2}{c}{\\textbf{Accuracy}} & \n\t\t\t\\multicolumn{2}{c}{\\textbf{Loss}} & \\multirow{2}*{\\textbf{Train \n\t\t\t\t\tTime}} \\\\\n\t\t\t& Train & Validation\n\t\t\t& Train & Validation\t& \t\t\t\t\t\t \t\t\\\\\n\t\t\t\\midrule\n\t\t\t\\textbf{Model 1} & 98.99\\% & 70.30\\%  & 0.05 & 4.20 & 406 sec \\\\\n\t\t\t\n\t\t\t\\bottomrule \n\t\t\\end{tabular}\n\t\t\\captionof{table}{Model performances}\n\t\t\\label{tab:performace-m1}\n\t\\end{table}\n\n\tFor this reason, in Section \\ref{section:dropout} is presented a new model \n\tthat has the aim of improving these results.\n\t\n\t\\section{Regularisation of the model with dropout}\n\t\\label{section:dropout}\n\tThe model proposed in this section involve the use of a model \n\tregularisation technique, that is the addition of a dropout layer after \n\teach max-pooling and fully-connected layer. In particular, during the \n\ttraining phase, the probability to keep each neuron is set to $0.5$, \n\twhile in the validation set should be $1$.\t\n\t\n\tThe architecture of the new network is presented in Table \\ref{tab:model1}.\t\n\t\n\t\\begin{figure}[H]\n\t\t\\centering\n\t\t\n\t\t\\begin{tabular}{cccccccc}\n\t\t\t\\toprule\n\t\t\t\\textbf{conv1} & \\textbf{conv2} & \\textbf{mpool1} & \n\t\t\t\\textbf{conv3} &\n\t\t\t\\textbf{conv4} & \\textbf{mpool2} &   \\textbf{fc} &\n\t\t\t\\textbf{softmax} \\\\\n\t\t\t\\midrule\n\t\t\t3$\\times$3,  32 & 3$\\times$3, 32 & 2$\\times$2 &3$\\times$3, 64 & \n\t\t\t3$\\times$3, 64  & 2$\\times$2  & 512 & 10\\\\\n\t\t\ts. 2$\\times$2 &   s. 2$\\times$2 &   s. 1$\\times$1 & s. 1$\\times$1  \n\t\t\t& s. \n\t\t\t2$\\times$2 & s. 2$\\times$2 && \\\\\n\t\t\tp. same & p. same & p. same  & p. same & p. same & p. same &&\\\\\n\t\t\t &  & dropout  &  &  & dropout & dropout & \\\\\n\t\t\t\\bottomrule\n\t\t\\end{tabular}\n\t\t\\captionof{table}{Network architecture}\n\t\t\\label{tab:model1}\n\t\\end{figure}\n\n\tThe actual performance is shown in Figure \\ref{fig:model1-performance}.\n\tThe performances legitimately improved as expected after the application of \n\tthe dropout. \n\n\tEven if the performance on the training worsen respect to the previous \n\tmodel, since the regularisation is applied only on this set, the \n\tperformance on the validation increased by $9.90\\%$. Now its value is \n\t$80.20\\%$, significantly better compared to the previous model.\n\t\n\t\\begin{figure}[htb]\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/2-Accuracy.png}\n\t\t\t\\caption*{(a)}\n\t\t\\end{minipage}\n\t\t~\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/2-Loss.png}\n\t\t\t\\caption*{(b)}\n\t\t\\end{minipage}\n\t\t\\caption{Training and validation curves in the regularised model}\n\t\t\\label{fig:model1-performance}\n\t\\end{figure}\n\t\n\tInstead, observing the loss curves, after the $30\\mathrm{th}$ epochs it is \n\tpossible to see some signs of overfitting.\n\t\n\t\\begin{table}[htb]\n\t\t\\centering\n\t\t\\begin{tabular}{l@{\\hspace{.5cm}}cc|cc|c}\n\t\t\t\\toprule\n\t\t\t& \\multicolumn{2}{c}{\\textbf{Accuracy}} & \n\t\t\t\\multicolumn{2}{c}{\\textbf{Loss}} & \\multirow{2}*{\\textbf{Train \n\t\t\t\t\tTime}} \\\\\n\t\t\t& Train & Validation & Train & Validation & \\\\\n\t\t\t\\midrule\n\t\t\t\\textbf{Model 2} & 79.32\\% & 80.20\\%  & 0.60 & 0.61 & 415 sec \\\\\n\t\t\t\\bottomrule \n\t\t\\end{tabular}\n\t\t\\captionof{table}{Model performances}\n\t\t\\label{tab:performace-m2}\n\t\\end{table}\n\n\tIn the following section will be attempted some additional experiments by \n\tmodifying the model's hyperparameters.\n\t  \n\t\\section{Hyperparameter settings}\n\t\\label{section:hyperparam}\n\t\n\tIn this section will be discussed $6$ different additional configurations \n\tfor the hyperparameters of the network, to improve the validation accuracy. \n\tIn particular, will be documented the performances according to the \n\tmodification of the following hyperparameters: learning rate, mini-batch \n\tsize, dropout and number of epochs. In this analysis, only the models with \n\tthe best performances will be included. In Table \\ref{tab:param1} are \n\tdocumented the different hyperparameter set for the models. \n\t\n\t\\begin{table}[htb]\n\t\t\\centering\n\t\t\\begin{tabular}{l@{\\hspace{.5cm}}ccc}\n\t\t\t\\toprule\n\t\t\t& \\textbf{learning rate} & \\textbf{batch size} & \\textbf{dropout}  \n\t\t\t\\\\\n\t\t\t\\midrule\n\t\t\t\\textbf{Model 1}  & {1e-3} & {32}  &  -  \\\\\n\t\t\t\\textbf{Model 2}  & {1e-3} & {32}  & 0.5 \\\\\n\t\t\t\\textbf{Model 3}  & {1e-4} & {32}  & 0.5 \\\\\n\t\t\t\\textbf{Model 4}  & {1e-3} & {128} & 0.6 \\\\\n\t\t\t\\textbf{Model 5}  & {1e-3} & {128} & 0.5 \\\\\n\t\t\t\\textbf{Model 6}  & {1e-4} & {128} & 0.5 \\\\\n\t\t\t%\\textbf{Model 7}  & {1e-4} & {256} & 0.5 \\\\\n\t\t\t%\\textbf{Model 8}  & {1e-3} & {256} & 0.5 \\\\\n\t\t\t\\textbf{Model 9}  & {1e-3} & {128} & 0.25 - 0.5\\\\\n\t\t\t\\bottomrule \n\t\t\\end{tabular}\n\t\t\\captionof{table}{Model hyperparameters}\n\t\t\\label{tab:param1}\n\t\\end{table}\n\n\tAll the models are trained for 50 epochs.\n\tThe other configurations tested, also those that include the modification \n\tof other hyperparameters, for example using the Gradient Descent as \n\toptimiser or adding the decay rate and other parameters to Adam optimizer  \n\twill not be presented in this report due to their mediocre results.\n\t\\newline\n\n\tThe first experiment performed simply consists in the reduction of the \n\tlearning rate from $0.001$ down to $0.0001$. \n\t\n\tIn Figure \\ref{fig:model3-performance} are visualised the performances of \n\tthe model. The accuracy, which now measures $80.80\\%$, increased only by \n\t$0.60\\%$ compared to the previous model. Furthermore, it is visible a \n\tdistance between the training and validation curves. \n\tThe loss curve rapidly decreases towards $0$, and there are no signs of \n\toverfitting.\n\n\t\\begin{figure}[htb]\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/3-Accuracy.png}\n\t\t\t\\caption*{(a)}\n\t\t\\end{minipage}\n\t\t~\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/3-Loss.png}\n\t\t\t\\caption*{(b)}\n\t\t\\end{minipage}\n\t\t\\caption{Training and validation curves in model 3}\n\t\t\\label{fig:model3-performance}\n\t\\end{figure}\n\t\t\n\tIn Section \\ref{subsection:epochs} will be discussed a further \n\tmodification to this model that consists of increasing the number of \n\tepochs, since the trend of the curve seems to be growing.\n\t\\newline \n\t\n\tIn Model 4, the training has been carried out using $128$ samples \n\tfor batch instead of $32$ and the learning rate has been restored to its \n\toriginal value of $0.001$. \n\tFurthermore, the dropout value is updated: the probability to keep each \n\tneuron is increased to $0.6$. \n\t\t\n\t\\begin{figure}[htb]\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/4-Accuracy.png}\n\t\t\t\\caption*{(a)}\n\t\t\\end{minipage}\n\t\t~\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/4-Loss.png}\n\t\t\t\\caption*{(b)}\n\t\t\\end{minipage}\n\t\t\\caption{Training and validation curves in model 4}\n\t\t\\label{fig:model4-performance}\n\t\\end{figure}\n\n\tIn this case, the performance is very similar to the previous experiment, \n\teven if slightly worse. The validation accuracy is reduced to \n\t$79.4\\%$ despite the validation loss is still the same, as can be seen in \n\tFigure \\ref*{fig:model5-performance}.\n\t\\newline\n\t\n\tIn Model 5, the number of samples for batches and the learning rate are \n\tkept \n\tequal to the previous experiment, while the dropout has been restored to \n\tits original value. \n\tThe current validation accuracy has begun to rise again, reaching $81.4\\%$ \n\tand improving the performance of model 3. However, as it can be seen in \n\tFigure \\ref{fig:model4-performance}, the validation curve, initially \n\tpromising, after the $30\\mathrm{th}$ epoch it falls below the training \n\tcurve.\n\n\t\\begin{figure}[htb]\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/5-Accuracy.png}\n\t\t\t\\caption*{(a)}\n\t\t\\end{minipage}\n\t\t~\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/5-Loss.png}\n\t\t\t\\caption*{(b)}\n\t\t\\end{minipage}\n\t\t\\caption{Training and validation curves in model 5}\n\t\t\\label{fig:model5-performance}\n\t\\end{figure}\n\n\tFor the next two experiments, it was decided to set the learning rate to \n\tthe previous value of $0.0001$ and restore the dropout to his original \n\tvalue of $0.5$. Instead, the number of examples in the batch for model 6 \n\thas been kept equal to the previous experiments, that is $128$ and increase \n\tup to $256$ for model 7. \n\n\tUnfortunately, in both cases, the performance has deteriorated compared to \n\tall the previous performances. The first model has a validation accuracy of \n\t$73.50\\%$, while the second fell to $68.40\\%$, that is the worst result\n\tmeasured so far.\n\t\\newline\n\t\n\tFor this reason, it was decided to retrain the model keeping the learning \n\trate value at $0.001$ and the number of examples per batch at $256$.\n\tAs shown in Figure \\ref{fig:model8-performance}, the final validation \n\taccuracy is $80.00\\%$, which is a nice result.\n\t\\newline\n\t\n\t\\begin{figure}[htb]\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/8-Accuracy.png}\n\t\t\t\\caption*{(a)}\n\t\t\\end{minipage}\n\t\t~\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/8-Loss.png}\n\t\t\t\\caption*{(b)}\n\t\t\\end{minipage}\n\t\t\\caption{Training and validation curves in model 8}\n\t\t\\label{fig:model8-performance}\n\t\\end{figure}\n\n\tIn the last experiment, a further attempted modification foresees in the \n\tuse \n\tof different dropouts based on its application after a max-pooling or a \n\tfully connected layer. In particular, the rate of the dropout is set to \n\t$0.25$ after the max-pooling layers and kept to $0.5$ after the fully \n\tconnected layer.\n\t\n\t\\begin{figure}[htb]\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/9-Accuracy.png}\n\t\t\t\\caption*{(a)}\n\t\t\\end{minipage}\n\t\t~\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/9-Loss.png}\n\t\t\t\\caption*{(b)}\n\t\t\\end{minipage}\n\t\t\\caption{Training and validation curves in model 9}\n\t\t\\label{fig:model9-performance}\n\t\\end{figure}\n\tThe performances of the model are shown in Figure \n\t\\ref{fig:model9-performance}. The validation accuracy obtained, that is \n\t$80.5\\%$, is among the best three.\n\t\\newline\n\t\n\tIn Table \\ref{tab:performace1} are summarised the performance of the \n\tpresented models. Among the documented model, the best achieved are model \n\t5, model 3 and model 2. \n\tIn the following section will be presented the performances of some \n\tmodels after the increase of training epochs.\n\t\n\t\\begin{table}[htb]\n\t\t\\centering\n\t\t\\begin{tabular}{l@{\\hspace{.5cm}}cc|cc|c}\n\t\t\t\\toprule\n\t\t\t& \\multicolumn{2}{c}{\\textbf{Accuracy}} & \n\t\t\t\\multicolumn{2}{c}{\\textbf{Loss}} & \\multirow{2}*{\\textbf{Train \n\t\t\t\t\tTime}} \\\\\n\t\t\t& Train & Validation\n\t\t\t& Train & Validation\t& \t\t\t\t\t\t \t\t\\\\\n\t\t\t\\midrule\n\t\t\t\\textbf{Model 1} & 98.99\\% & 70.30\\%  & 0.05 & 4.20 & 406 sec \\\\\n\t\t\t\\textbf{Model 2} & 79.32\\% & {80.20\\%}  & 0.60 & 0.61 & 415 \n\t\t\tsec \\\\\n\t\t\t\\textbf{Model 3} & 77.70\\% & \\textbf{80.80\\%}  & 0.63 & 0.61 & 445 \n\t\t\tsec \\\\\n\t\t\t\\textbf{Model 4} & 76.75\\% & 79.40\\%  & 0.65 & 0.61 & 148 sec \\\\\n\t\t\t\\textbf{Model 5} & 84.39\\% & \\textbf{81.40\\%}  & 0.44 & 0.57 & 185 \n\t\t\tsec \\\\\n\t\t\t\\textbf{Model 6} & 71.03\\% & 73.50\\%  & 0.82 & 0.77 & 149 sec \\\\\n\t\t\t\\textbf{Model 7} & 65.37\\% & 68.40\\%  & 0.98 & 0.88 & 119 sec \\\\\n\t\t\t\\textbf{Model 8} & 83.60\\% & {80.00\\%}  & 0.46 & 0.59 & 120 \n\t\t\tsec \\\\\n\t\t\t\\textbf{Model 9} & 93.91\\% & \\textbf{80.50\\%}  & 0.18 & 0.73 & 155 \n\t\t\tsec \\\\\n\t\t\t\\bottomrule \n\t\t\\end{tabular}\n\t\t\\captionof{table}{Model performances}\n\t\t\\label{tab:performace1}\n\t\\end{table}\n \n\t\\subsection{Modification of the number of hidden units}\n\t\\label{subsection:hidden units}\n\t\n\tIn this section will be discussed modification to the current best model, \n\twhich is the model 5, that consists in an increase of the number of \n\thidden units of the fully connected layer from $512$ up to $1024$.\n\t\n\tSince the learning curve of the network, shown in the previous section, \n\tseems to be underfitting, increasing the complexity of the network should \n\tbe a good idea. The new performances are shown in Figure \n\t\\ref{fig:model10-performance}.\n\t\n\t\\begin{figure}[htb]\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/10-Accuracy.png}\n\t\t\t\\caption*{(a)}\n\t\t\\end{minipage}\n\t\t~\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/10-Loss.png}\n\t\t\t\\caption*{(b)}\n\t\t\\end{minipage}\n\t\t\\caption{Training and validation curves in model 10}\n\t\t\\label{fig:model10-performance}\n\t\\end{figure}\n\t\n\tThe previous validation accuracy, that was $81.40\\%$, increases by \n\t$0.90\\%$, reaching $82.3\\%$.\n\t\n\t\t\n\t\\begin{table}[htb]\n\t\t\\centering\n\t\t\\begin{tabular}{l@{\\hspace{.5cm}}cc|cc|c}\n\t\t\t\\toprule\n\t\t\t& \\multicolumn{2}{c}{\\textbf{Accuracy}} & \n\t\t\t\\multicolumn{2}{c}{\\textbf{Loss}} & \\multirow{2}*{\\textbf{Train \n\t\t\t\t\tTime}} \\\\\n\t\t\t& Train & Validation\n\t\t\t& Train & Validation\t& \t\t\t\t\t\t \t\t\\\\\n\t\t\t\\midrule\n\t\t\t\\textbf{Model 10} & 87.47\\% & \\textbf{82.30\\%}  & 0.35 & 0.54 & 161 \n\t\t\tsec \\\\\n\t\t\t\\bottomrule \n\t\t\\end{tabular}\n\t\t\\captionof{table}{Model 10 performances}\n\t\t\\label{tab:performace10}\n\t\\end{table}\n\t\n\tFurther modifications to this model will be discussed in Section \n\t\\ref{subsection:batchnorm}.\n\t\n\t\\subsection{Increasing the number of epochs}\n\t\\label{subsection:epochs}\n\tIn this section are analysed the performances of the previous models \n\ttrained for a greater number of epochs. \n\t\n\tThese experiments have been carried out only on models 3, 4, 5, 8 and 9 \n\tsince they shown better accuracy values. \n\t\n\tThe models are trained on GPU which allows training without worsening the \n\ttime too much.\n\t\\newline\n\t\n\tThe first experiment were performed on model 3, which curves are shown in \n\tFigure \\ref{fig:model3b-performance}. \n\t\t\n\t\\begin{figure}[htb]\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/3b-Accuracy.png}\n\t\t\t\\caption*{(a)}\n\t\t\\end{minipage}\n\t\t~\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/3b-Loss.png}\n\t\t\t\\caption*{(b)}\n\t\t\\end{minipage}\n\t\t\\caption{Training and validation curves in model 3b}\n\t\t\\label{fig:model3b-performance}\n\t\\end{figure}\n\n \tCompared to the previous, this model has improved the validation accuracy \n \tof $4.9\\%$, reaching $85.7\\%$, which is the highest result achieved so far.\n\t\\newline\n\t\n\tThe following experiments was carried out on model 4. \n\t\t\n\t\\begin{figure}[H]\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/4b-Accuracy.png}\n\t\t\t\\caption*{(a)}\n\t\t\\end{minipage}\n\t\t~\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/4b-Loss.png}\n\t\t\t\\caption*{(b)}\n\t\t\\end{minipage}\n\t\t\\caption{Training and validation curves in model 4b}\n\t\t\\label{fig:model4b-performance}\n\t\\end{figure}\n\n\tThe results obtained, shown in Figure \\ref{fig:model4b-performance}, are \n\tworse than those obtained from the previous model. The validation accuracy \n\tis fallen to $81.60\\%$. In this case, the validation accuracy obtained \n\tis more or less the same as the one achieved with only $50$ epochs.\n\t\\newline\n\t\n\tContinuing, the results for the model 5b are shown in Figure \n\t\\ref{fig:model5b-performance}. Despite the performances of the model on \n\t$50$ epochs were the best, this model obtains exactly the same results, \n\thence it is no longer the best among the proposed models. \n\t\n\t\\begin{figure}[htb]\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/5b-Accuracy.png}\n\t\t\t\\caption*{(a)}\n\t\t\\end{minipage}\n\t\t~\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/5b-Loss.png}\n\t\t\t\\caption*{(b)}\n\t\t\\end{minipage}\n\t\t\\caption{Training and validation curves in model 5b}\n\t\t\\label{fig:model5b-performance}\n\t\\end{figure}\n\n\tIn fact, looking at the two curves, it is clearly visible that after few \n\tepochs the model stabilizes and stops improving its performance.\n\tThis result was predictable since the learning curve seemed to have already \n\tstabilized before $50$ epochs.\n\t\\newline\n\n\tThe next experiment was carried out on model 8, which presented a further \n\tincreasing equal to $0.40\\%$ of the performance respect to the last \n\texperiment.\n\t\n\t\\begin{figure}[htb]\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/8b-Accuracy.png}\n\t\t\t\\caption*{(a)}\n\t\t\\end{minipage}\n\t\t~\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/8b-Loss.png}\n\t\t\t\\caption*{(b)}\n\t\t\\end{minipage}\n\t\t\\caption{Training and validation curves in model 8b}\n\t\t\\label{fig:model8b-performance}\n\t\\end{figure}\n\n\tThe situation presented, in particular, the trend of the train and \n\tvalidation accuracy curve, shown in Figure \\ref{fig:model8b-performance}, \n\tis very similar to the one which occurred with model 5. This is because, \n\tafter a certain epoch, both the model have stopped or significantly slowed \n\tdown the learning.\n\t\\newline\n\n\tThe last experiment was performed on model 9. Despite the performance is \n\tbetter than the latest, it does not reveal a significant increase in \n\tperformance compared to the latest and, above all, respect to model 3b. \n\t\t\t\n\t\\begin{figure}[htb]\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/9b-Accuracy.png}\n\t\t\t\\caption*{(a)}\n\t\t\\end{minipage}\n\t\t~\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/9b-Loss.png}\n\t\t\t\\caption*{(b)}\n\t\t\\end{minipage}\n\t\t\\caption{Training and validation curves in model 9b}\n\t\t\\label{fig:model9b-performance}\n\t\\end{figure}\n\t\n\tThe current validation accuracy is equal to $82.20\\%$.\n\tThe curves are displayed in Figure \\ref{fig:model9b-performance}.\n\t\\newline\n\n\tIn Table \\ref{tab:performace2} are summarised the performance of the \n\tpresented models. Among these, the bests are the model 3b, \n\tmodel 8b and model 9b. \n\n\t\\begin{table}[H]\n\t\t\\centering\n\t\t\\begin{tabular}{l@{\\hspace{.5cm}}cc|cc|c}\n\t\t\t\\toprule\n\t\t\t& \\multicolumn{2}{c}{\\textbf{Accuracy}} & \n\t\t\t\\multicolumn{2}{c}{\\textbf{Loss}} & \\multirow{2}*{\\textbf{Train \n\t\t\t\t\tTime}} \\\\\n\t\t\t& Train & Validation\n\t\t\t& Train & Validation\t& \t\t\t\t\t\t \t\t\\\\\n\t\t\t\\midrule\n\t\n\t\t\t\\textbf{Model 3} & 77.70\\% & {80.80\\%}  & 0.63 & 0.61 & 445 \n\t\t\tsec \\\\\n\t\t\t\\textbf{Model 3b} & 93.47\\% & \\textbf{85.70\\%}  & 0.18 & 0.55 & \n\t\t\t2974 sec \\\\\n\t\t\t\\textbf{Model 4} & 76.75\\% & 79.40\\%  & 0.65 & 0.61 & 148 sec \\\\\n\t\t\t\\textbf{Model 4b}  & 84.60\\% & \\textbf{81.60\\%}  & 0.44 & 0.56 & \n\t\t\t1040 sec \\\\\n\t\t\t\\textbf{Model 5} & 84.39\\% & {81.40\\%}  & 0.44 & 0.57 & 185 \n\t\t\tsec \\\\\n\t\t\t\\textbf{Model 5b} & 91.91\\% & \\textbf{81.40\\%}  & 0.24 & 0.63 & 893 \n\t\t\tsec \\\\\n\t\t\t\\textbf{Model 8} & 83.60\\% & {80.00\\%}  & 0.46 & 0.59 & 120 \n\t\t\tsec \\\\\n\t\t\t\\textbf{Model 8b} & 93.40\\% & \\textbf{84.90\\%}  & 0.19 & 0.57 & 714 \n\t\t\tsec \\\\\n\t\t\t\\textbf{Model 9} & 93.91\\% & {80.50\\%}  & 0.18 & 0.73 & 155 \n\t\t\tsec \\\\\n\t\t\t\\textbf{Model 9b} & 97.55\\% & \\textbf{82.20\\%}  & 0.08 & 0.96 & 931 \n\t\t\tsec \\\\\n\t\t\t\\bottomrule \n\t\t\\end{tabular}\n\t\t\\captionof{table}{Model performances after increasing the number of \n\t\tepochs}\n\t\t\\label{tab:performace2}\n\t\\end{table}\n\n\tThe following section will present a further attempt to improve \n\tperformances that consists in the addition of batch normalisation to the \n\tbest models.\n\t\n\t\\subsection{Batch normalisation}\n\t\\label{subsection:batchnorm}\n\t\n\tIn this section are analysed the performances of the models 3c, 5c, 8c, 9c \n\tand 10c, after the addition of batch normalisation.\n\tThe main purpose of this change is to improve the performance and the \n\tstability of the network. \n\tThe transform is introduced immediately before each ReLU non-linearity, in \n\torder to normalise the layer inputs \n\t\\footlabel{note1}{Ioffe, S. and Szegedy, C., 2015. Batch normalization: \n\tAccelerating deep network training by reducing internal covariate shift. \n\tarXiv preprint arXiv:1502.03167.}.\n\t%\\footref{note1}. \n\t\n\tThis experiment has been carried out only on five models, which are the \n\tones that have obtained better performances, and for 300 epochs.\n\t\\newline\n\t\n\tThe first experiment is carried out on model 3b, that is the one with the \n\tbest performances so far. \n\t\n\t\\begin{figure}[htb]\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/3c-Accuracy.png}\n\t\t\t\\caption*{(a)}\n\t\t\\end{minipage}\n\t\t~\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/3c-Loss.png}\n\t\t\t\\caption*{(b)}\n\t\t\\end{minipage}\n\t\t\\caption{Training and validation curves in model 3c (with batch \n\t\t\tnormalisation)}\n\t\t\\label{fig:model3c-performance}\n\t\\end{figure}\n\n\tThe learning curves are displayed in Figure \\ref{fig:model3c-performance}. \n\tThe validation accuracy is slightly worst compared to that of the model \n\twithout batch normalisation. In fact, the current one is decreased by \n\t$0.20\\%$.\n\t\\newline\n\t\t\n\tThe next experiment is performed on model 5b. In this case, the batch \n\tnormalisation increases the validation accuracy of the previous model of \n\t$5.3\\%$, reaching the new best results of $86.5\\%$, as shown in Figure \n\t\\ref{fig:model5c-performance}.\n\n\t\\begin{figure}[htb]\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/5c-Accuracy.png}\n\t\t\t\\caption*{(a)}\n\t\t\\end{minipage}\n\t\t~\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/5c-Loss.png}\n\t\t\t\\caption*{(b)}\n\t\t\\end{minipage}\n\t\t\\caption{Training and validation curves in model 5c (with batch \n\t\t\tnormalisation)}\n\t\t\\label{fig:model5c-performance}\n\t\\end{figure}\n\t\n\tProbably, the reason why model 5c has better performance than 3c is that \n\tbatch normalisation works better with a higher learning rate.\n\t\\newline\n\t\n\tThe experiment performed on model 8c has achieved lower result respect to \n\tmodel 5c even if further increasing the validation accuracy of $0.20\\%$ of \n\tthe model without batch normalisation. \n\tThe performances are shown in Figure \\ref{fig:model8c-performance}.\n\t\\newline\n\n\t\\begin{figure}[htb]\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/8c-Accuracy.png}\n\t\t\t\\caption*{(a)}\n\t\t\\end{minipage}\n\t\t~\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/8c-Loss.png}\n\t\t\t\\caption*{(b)}\n\t\t\\end{minipage}\n\t\t\\caption{Training and validation curves in model 8c (with batch \n\t\t\tnormalisation)}\n\t\t\\label{fig:model8c-performance}\n\t\\end{figure}\n\t\n\tThe model 9c, which performances are shown in Figure \n\t\\ref{fig:model9c-performance}, performs slightly better compared to the \n\tprevious model. Moreover, the validation accuracy increases by $3.00\\%$ \n\trespect to the model without batch normalisation.\n\t\t\n\t\\begin{figure}[H]\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/9c-Accuracy.png}\n\t\t\t\\caption*{(a)}\n\t\t\\end{minipage}\n\t\t~\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/9c-Loss.png}\n\t\t\t\\caption*{(b)}\n\t\t\\end{minipage}\n\t\t\\caption{Training and validation curves in model 9c (with batch \n\t\t\tnormalisation)}\n\t\t\\label{fig:model9c-performance}\n\t\\end{figure}\n\t\n\tThe last experiment performed has achieved a good result, in particular \n\treaching a validation accuracy of $85.70\\%$. Despite these results, the \n\tmodel does not improve the performance of model 5c.\n\tThe performances are shown in Figure \\ref{fig:model10c-performance}.\n\t\\newline\n\t\n\t\\begin{figure}[htb]\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/10c-Accuracy.png}\n\t\t\t\\caption*{(a)}\n\t\t\\end{minipage}\n\t\t~\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/10c-Loss.png}\n\t\t\t\\caption*{(b)}\n\t\t\\end{minipage}\n\t\t\\caption{Training and validation curves in model 10c (with batch \n\t\t\tnormalisation)}\n\t\t\\label{fig:model10c-performance}\n\t\\end{figure}\n\n\n\tThe following table summarises the latest results obtained, highlighting \n\tmodel 5c is the best of all the experiments presented.\n\t\n\t\\begin{table}[H]\n\t\t\\centering\n\t\t\\begin{tabular}{l@{\\hspace{.5cm}}cc|cc|c}\n\t\t\t\\toprule\n\t\t\t& \\multicolumn{2}{c}{\\textbf{Accuracy}} & \n\t\t\t\\multicolumn{2}{c}{\\textbf{Loss}} & \\multirow{2}*{\\textbf{Train \n\t\t\t\t\tTime}} \\\\\n\t\t\t& Train & Validation\n\t\t\t& Train & Validation\t& \t\t\t\t\t\t \t\t\\\\\n\t\t\t\\midrule\n\t\t\t\\textbf{Model 3c} & 87.15\\% & {85.50\\%}  & 0.37 & 0.46 & 4254 sec \\\\\n\t\t\t\\textbf{Model 5c} & 94.20\\% & \\textbf{86.50\\%}  & 0.17 & 0.50 & \n\t\t\t1599 sec \\\\\n\t\t\t\\textbf{Model 8c} & 94.87\\% & {85.10\\%}  & 0.14 & 0.57 & 1215 sec \\\\\n\t\t\t\\textbf{Model 9c} & 94.74\\% & {85.20\\%}  & 0.15 & 0.57 & 279 \n\t\t\tsec \\\\\n\t\t\t\\textbf{Model 10c} & 96.67\\% & {85.70\\%}  & 0.10 & 0.60 & 1768 \n\t\t\tsec \\\\\n\t\t\t\\bottomrule \n\t\t\\end{tabular}\n\t\t\\captionof{table}{Model performances after the batch normalisation}\n\t\t\\label{tab:performace3}\n\t\\end{table}\n\n\t\\section{Test set accuracy} \n\t\\label{section:finalmodel}\n\tThe test set accuracy was measured on the model 5c, that was the one which \n\tpresents the best performance. As can be seen in Figure \n\t\\ref{fig:model5c-test-performance} and summarised in Table \n\t\\ref{tab:performace-m5c}, also on the test the performances of the model \n\tare high. The test accuracy reached $85.36\\%$, just $1.14\\%$ worse than the \n\tvalidation, and the test loss is $0.50$.\n\t\n\t\\begin{figure}[htb]\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/5c-test-Accuracy.png}\n\t\t\t\\caption*{(a)}\n\t\t\\end{minipage}\n\t\t~\n\t\t\\begin{minipage}[c]{.49\\textwidth}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{../src/out/img/5c-test-Loss.png}\n\t\t\t\\caption*{(b)}\n\t\t\\end{minipage}\n\t\t\\caption{Test curves of model 5c}\n\t\t\\label{fig:model5c-test-performance}\n\t\\end{figure}\n\n\t\\begin{table}[H]\n\t\t\\centering\n\t\t\\begin{tabular}{l@{\\hspace{.5cm}}ccc|ccc}\n\t\t\t\\toprule\n\t\t\t& \\multicolumn{3}{c}{\\textbf{Accuracy}} & \n\t\t\t\\multicolumn{3}{c}{\\textbf{Loss}} \\\\\n\t\t\t& Train & Validation & Test\t& Train & Validation & Test \\\\\n\t\t\t\\midrule\n\t\t\t\\textbf{Model 5c} & 94.20\\% & {86.50\\%} & \\textbf{85.36\\%} & 1.03 & \n\t\t\t0.47 & \\textbf{0.50} \\\\\n\t\t\t\\bottomrule \n\t\t\\end{tabular}\n\t\t\\captionof{table}{Test set performances of the chosen model}\n\t\t\\label{tab:performace-m5c}\n\t\\end{table}\n\n\n\\end{document}\n", "meta": {"hexsha": "9ab9c519ec1a14248ffacb1b62524572859abf5e", "size": 31583, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/report2.tex", "max_stars_repo_name": "GiorgiaAuroraAdorni/convolutional-neural-network", "max_stars_repo_head_hexsha": "546dd93b1bdfde03d0df90d3c82fa268586bf11b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "report/report2.tex", "max_issues_repo_name": "GiorgiaAuroraAdorni/convolutional-neural-network", "max_issues_repo_head_hexsha": "546dd93b1bdfde03d0df90d3c82fa268586bf11b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/report2.tex", "max_forks_repo_name": "GiorgiaAuroraAdorni/convolutional-neural-network", "max_forks_repo_head_hexsha": "546dd93b1bdfde03d0df90d3c82fa268586bf11b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8147751606, "max_line_length": 80, "alphanum_fraction": 0.6874901054, "num_tokens": 10645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.33831087082935035}}
{"text": " \n\n\n\\section{Standard Model}\n\\begin{itemize}\n\\item All fundamental particles and their interactions are described by quantum field theory known as the Standard Model.\n\\item The Standard Model is a gauge theory based on the symmetry group \\mbox{SU$(3)_{c}$ $\\otimes$ SU$(2)_{L}$ $\\otimes$ U$(1)_{Y}$}.\n\\item This group structure is broken by the vacuum, which triggers the spontaneous breaking of the SU$(2)_{L}$ $\\otimes$ U$(1)_{Y}$ group. It is believed that the Higgs mechanism is responsible for the spontaneous symmetry breaking. This mechanism generates masses for the weak gauge bosons (W and Z) as well as generating mass for all fermions. To achieve the symmetry breaking a neutral scalar boson must be introduced into the theory. This particle is called the Higgs boson and to date has not yet been observed.\n\\item This model describes the interactions of the strong, weak, and electromagnetic forces.\n\\item There are two types of particles in the SM: fermions (particles with fractional) and bosons (particles with integer spin).\n\\item Within the fermions, there are two more fundamental categories: quarks and leptons.\n\\item The first generation of the quarks and leptons are stable (do not decay) and makes up all the matter in the world. The second and third generations are not stable and will decay into the first generation.\n\\item Each quark generation comes in a doublet with one quark having a charge $+\\frac{2}{3}$e and the other having charge $-\\frac{1}{3}$e. The quarks with charge $+\\frac{2}{3}$e are commonly called the up-type quarks and quarks with charge $-\\frac{1}{3}$e are called the down-type quarks.\n\\item Each lepton generation also comes in a doublet, but this time one of the particles has unit charge and the other has no charge. The particles with unit charge are the electron, muon, and tau lepton. The particles with no charge are the associated neutrino for the previously listed leptons.\n\\item Particles with integer spin are the force carries within the SM framework. The four known spin 1 bosons in the SM: the photon, the gluon, and the W and Z particles. The photon is the carrier of the electromagnetic force which couples to particles with electromagnetic charge, such as the electron or the up quark. The gluon is the carrier of the strong force which couples particles with color charge which includes all the quarks as well as the gluon itself. The W and Z bosons are the carriers of the weak force which couples particles with weak charge, which is all quarks and leptons.\n\\item Within the SM framework, neutrinos required to have exactly zero mass; however recent experiments have shown that at least two the neutrinos must have a non-zero mass. There is no mechanism within the SM to give neutrinos mass and therefore this is evidence that the SM of particle interactions is not a complete theory. Even though the SM is not the full underlying theory of all particles and their interactions, it has been an extremely successful tool used to compute cross sections for particle collisions which is essential in high energy physics.\n\\item There are three types of interactions described in the SM: the strong interaction between objects with color such as quarks and gluons, the weak interaction between particles with weak charge, and electromagnetic interaction between charged particles.\n\\item The weak interaction is mediated by the charged W boson and the neutral Z boson. Interactions involving the Z boson are called neutral current interactions and only occur between members of the same family or generation. In contrast, interactions involving the charged W boson can  occur between members of the same generation, but also between generations. One interesting feature of the Standard Model Lagrangian is that the mass matrix and the weak matrix are can not be simultaneously diagnolized for weakly interacting particles. This mean that the weakly interacting fermions described in the Table.~\\ref{fermions} are not the same as the fermions that interact with the W boson. The relationship between the weak and mass eigenstates of the Standard Model Lagrangian is summarized by the Cabbibo-Kobayahski-Maskawa (CKM) unitary quark mixing matrix. The parameters in the CKM matrix can not calculated from first principles and must be determined from experiment.\n\\item The mass or strong eigenstates can be rotated into the weak eigenstates by the unitary CKM mixing matrix as shown in Eq.~\\ref{ckm}.\n\\item The magnitudes of the CKM matrix elements as determined from experiment can be found in Eq.~\\ref{ckmval}.\n\\item The strong interaction is mediated by 8 massless and neutral gauge bosons called gluons. Gluons interact with any particle that carries strong charge called color. In the Standard Model only quarks and gluons carry color charge. In the Standard Model there are three different color commonly called red (R), blue (B), and green (G). One interesting property of the strong interaction at low energies is that bare quarks can not travel long distances when they carry color charge. Instead, colored quarks combine with other quarks to form colorless bound states called mesons (q$\\bar{q}^{'}$) or baryons (qqq) depending on the number of constituent quarks. This phenomenon is called comfinement. Examples of mesons are pions (up and down quarks) and kaons (up and strange quarks) and examples of baryons are the proton (two up quarks and down quark) and the neutron (two down and one up quark). At higher energies the strong interaction becomes relatively weak and quarks are allowed to break their confined states and travel as a bare color charge. As the quark begins to propagate, it polarizes the vacuum until enough energy is built up to create a quark-antiquark pair. This process, called hadronization, can repeat itself many times and will produce many new strongly interacting particles. The effect of hadronization is the production of a large number of hadrons in the same direction as the originating colored quark or gluon. The top quark, discussed in the next section, is the only quark that does not undergo hadronization due its extremely short lifetime.\n\\end{itemize}\n\n\n\n\nThe electromagnetic (EM) interaction arises from the requirement that the EM Lagrangian is invariant under an arbitrary phase rotation (\\mbox{$\\Psi^{'}(x) \\rightarrow e^{i\\alpha\\Theta(x)}\\Psi(x)$}) of any particle wave function. This requirement means that EM Lagrangian obeys a U(1) local gauge symmetry. To make the Lagrangian invariant under this rotation, a new gauge field is added to the EM Lagrangian. This new field is interpreted as the photon field and mediates interactions between particles with electromagnetic charge with strength $\\alpha$. The weak interaction arises in a similar fashion except that the arbitrary phase, $\\Theta(x)$, is replace with a vector, $\\vec{\\sigma}(x)$. The requirement that the weak Lagrangian is invariant means that it obeys SU(2) local gauge symmetry. Similarly to the U(1) case, the weak Lagrangian is modified by the addition of the new gauge bosons, $\\vec{W}$, to preserve the SU(2) symmetry. The weak interactions are special in that they have been observed to maximally violate parity and thus are constructed in the Standard Model to only interact with left handed particles and right handed anti-particles.\n\nThe electromagnetic and weak interactions can be unified into a \\mbox{SU(2)$_{L}$ $\\otimes$ U(1)$_{Y}$} gauge group, where the subscript, L, refers to the left handed nature of the weak interactions and the subscript, Y, is called the weak hypercharge and is related to the electric charge. This unification produces the correct interaction structure of the electromagnetic and weak forces, however it fails to give masses to the gauge bosons of the weak interactions, the W and Z bosons, as well as the quarks and leptons. Therefore, the \\mbox{SU(2)$_{L}$ $\\otimes$ U(1)$_{Y}$} gauge group is said to be spontaneously broken. One possible solution to break electroweak symmetry is the Higgs mechanism. This mechanism generates masses for all quarks and leptons as well as the W and Z bosons by requiring a new scalar field, the Higgs field, in the Standard Model Lagrangian. To date, the Higgs particle has not been observed in any experiment designed for it's detection. \n\nThe strength of the particles interaction with the Higgs field determ\n\nFinally, the strong force arises from the requirement that strongly interacting particles, such as quarks, be invariant under a rotation by a unitary matrix (\\mbox{$\\vec{q_{f}}(x) \\rightarrow e^{i\\lambda_{\\alpha}\\Theta^{\\alpha}(x)}\\vec{q_{f}}(x)$}), where $\\lambda_{\\alpha}$ is one of the Gellman matrices. This requirement means that the strong interaction obeys SU(3) local gauge symmetry.\n\n\n\n\\subsection{Higgs Mechanism and Particle Masses}\nThe Standard Model is a gauge theory based on the symmetry group \\mbox{SU$(3)_{c}$ $\\otimes$ SU$(2)_{L}$ $\\otimes$ U$(1)_{Y}$}. This group structure is broken by the vacuum, which triggers the spontaneous breaking of the SU$(2)_{L}$ $\\otimes$ U$(1)_{Y}$ group. It is believed that the Higgs mechanism is responsible for the spontaneous symmetry breaking. This mechanism generates masses for the weak gauge bosons (W and Z) as well as generating mass for all fermions. To achieve the symmetry breaking a neutral scalar boson must be introduced into the theory. This particle is called the Higgs boson and to date has not yet been observed.\n\nIn the Standard Model all particle interactions are mediated by spin=1 guage bosons. There are three types of particle interactions described in this model that are mediated by four gauge bosons: the photon, the gluon, and the W and Z particles. The photon is the carrier of the electromagnetic force which couples to particles with electromagnetic charge, such as the electron or the up quark. The gluon is the carrier of the strong force which couples particles with color charge which includes all the quarks as well as the gluon itself. The W and Z bosons are the carriers of the weak force which couples particles with weak charge, which includes all quarks and leptons. A summary of the gauge bosons can be found in Table ~\\ref{bosons}\n\n\n\\begin{table}[!h!tbp]\n\\begin{center}\n\\begin{tabular}{c|c|c|c}\n\\multicolumn{4}{c}\n{\\underline{Summary of Fermion Gauge Interactions}} \\\\\n$1^{\\rm{st}}$ Generation\t\t&\t$2^{\\rm{nd}}$ Generation\t\t&\t$3^{\\rm{rd}}$ Generation\t\t&\tGauge Interactions\t\\\\\n\\hline\nUp (u)\t\t\t\t\t&\tCharm (c)\t\t\t\t\t&\tTop (t)\t\t\t\t\t&\tStrong, Weak, Electromagnetic\t\\\\\nDown (d)\t\t\t\t\t&\tStrange (s)\t\t\t\t&\tBottom (b)\t\t\t\t\t&\tStrong, Weak, Electromagnetic\t\\\\\nElectron ($e$)\t\t\t\t&\tMuon ($\\mu$)\t\t\t\t&\tTau ($\\tau$)\t\t\t\t&\tWeak, Electromagnetic\t\\\\\nElectron neutrino ($\\nu_{e}$)\t&\tMuon neutrino ($\\nu_{\\mu}$)\t&\tTau neutrino ($\\nu_{\\tau}$)\t&\tWeak\t\\\\\n\\end{tabular}\n\\vspace{-0.1 in}\n\\caption[interactions]{Summary of Fermion Gauge Interactions}\n\\label{interactions}\n\\end{center}\n\\end{table}\n\n\n\n\nOne interesting feature of the Standard Model Lagrangian is that the mass matrix and the weak matrix are can not be simultaneously diagnolized for weakly interacting particles. This mean that the weakly interacting fermions described in the Table.~\\ref{fermions} are not the same as the fermions that interact with the W boson. The relationship between the weak and mass eigenstates of the Standard Model Lagrangian is summarized by the Cabbibo-Kobayahski-Maskawa (CKM) unitary quark mixing matrix. The parameters in the CKM matrix can not calculated from first principles and must be determined from experiment.\n\nThe mass or strong eigenstates can be rotated into the weak eigenstates by the unitary CKM mixing matrix as shown in Eq.~\\ref{ckm}.\n\n\n", "meta": {"hexsha": "cfb732b93229c23a8986c0acdd21da4b1a89b6a1", "size": 11674, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Old/TheoryReference.tex", "max_stars_repo_name": "tgadf/thesis", "max_stars_repo_head_hexsha": "19d4a6bc7f7ac8660fce582322703d50e0d6bd31", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Old/TheoryReference.tex", "max_issues_repo_name": "tgadf/thesis", "max_issues_repo_head_hexsha": "19d4a6bc7f7ac8660fce582322703d50e0d6bd31", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Old/TheoryReference.tex", "max_forks_repo_name": "tgadf/thesis", "max_forks_repo_head_hexsha": "19d4a6bc7f7ac8660fce582322703d50e0d6bd31", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 169.1884057971, "max_line_length": 1575, "alphanum_fraction": 0.7846496488, "num_tokens": 2754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.3381963388574576}}
{"text": "\\subsubsection{\\stid{3.13} CLOVER Sub-project Ginkgo} \\label{subsubsect:peeks}\n\\paragraph{Overview} \nGinkgo~\\footnote{\\url{https://github.com/ginkgo-project/ginkgo}} is a modern\nlinear algebra library engineered towards performance portability, and\nproductivity. To achieve these goals, the library design is guided by combining\necosystem extensibility with heavy, architecture-specific kernel optimization\nusing the platform-native languages CUDA (NVIDIA GPUs), HIP (AMD GPUs), DPC++\n(Intel GPUs) and OpenMP (Intel/AMD/ARM multicore). Ginkgo is part of the\nextreme-scale Software development Kit (xSDK), part of the Extreme-Scale\nScientific Software Stack (E4S), and has already been integrated as a backend\ninto simulation libraries like deal.II, MFEM, and HyTeG.\n% SUNDIALS, and XGC.\n\n\n\n\\paragraph{Key Challenges}\n% There is a list of challenges to meet with the development of sparse linear\n% algebra functionality for the US flagship supercomputers deployed in ECP:\n\\begin{enumerate}\n  \\item The extreme levels of hardware concurrency available in the\n\t\tGPU-accelerated nodes need to be reflected in fine-grain parallelism in\n\t\tthe numerical building blocks.\n  \\item An increasing variety of hardware designs and hardware-native\n\t\tprogramming languages requires a library design that enables platform\n\t\tportability without sacrificing performance.\n  \\item The arithmetic performance of processors growing much faster than the\n\t\tmemory bandwidth and interconnect speed requires exploring innovative\n\t\tstrategies for reducing the pressure on all cache/memory levels.\n  \\item Applications that build upon the fast solution of many independent\n\t\tmoderate-sized sparse linear systems require batched sparse linear\n\t\talgebra functionality.\n  \\item Applications building upon matrix-free methods requires the flexibility\n\t\tto compose linear solvers out of library-native and customized external\n\t\tfunctionality.\n\\end{enumerate}\n\n\\begin{figure}[!h]\n\\centering\n\\includegraphics[width=.8\\columnwidth]{projects/2.3.3-MathLibs/2.3.3.13-CLOVER/ginkgo_portability_crop}\n\\caption{\\label{fig:ginkgoportability}The portability design of the Ginkgo math\n  library enables high performance kernel implementations in the vendor-supported\n  programming language.}\n\\end{figure}\n\n\n\\paragraph{Solution Strategy}\n\nThe Ginkgo team is addressing these challenges by striving for platform\nportability, modularity, extensibility, and hardware-aware algorithm design.\n\n\\begin{enumerate}\n  \\item \\textbf{Architecture-portable software design:}\n\t\tGinkgo~\\cite{anzt2020ginkgo} employs a design that decouples the\n\t\talgorithm implementations from the hardware-specific kernel\n\t\timplementations, thereby acknowledging the importance of platform\n\t\tportability and allowing for architecture-specific kernel optimization\n\t\tin the vendor language, see Figure~\\ref{fig:ginkgoportability}.\n  \\item \\textbf{Modularity, flexibility, and extensibility:} Ginkgo employs a\n\t\t``linear operator'' abstraction for all functionality, which allows for\n\t\tflexibility in combining functionality and interfacing external\n\t\toperators.\n  \\item \\textbf{Sustainability efforts:} Ginkgo adheres the Better Scientific\n\t\tSoftware (BSSw) design principles~\\cite{betterscientificsoftware} that\n\t\tensure production-quality code by featuring unit testing, automated\n\t\tconfiguration and installation, Doxygen code documentation, as well as a\n\t\tcontinuous integration and continuous benchmarking\n\t\tframework~\\cite{pasc_anzt}. Ginkgo is an open source effort licensed\n\t\tunder the BSD 3-clause and included in the xSDK and E4S software\n\t\tpackages.\n  \\item \\textbf{Fine-grain parallelism:} Ginkgo features linear algebra\n\t\tbuilding blocks and advanced algorithms for preconditioning and solving\n\t\tlinear systems that can efficiently leverage the concurrency of modern\n\t\tGPUs, including (incomplete) parallel factorizations, parallel sparse\n\t\ttriangular solves, parallel matrix operations, and parallel iterative\n\t\tmethods.\n  \\item \\textbf{Mixed precision methods:} Ginkgo features a memory accessor\n\t\tthat encapsulates on-the-fly compression for decoupling the memory\n\t\tprecision from the arithmetic precision. This allows accelerating\n\t\tmemory-bound algorithms that can compensate or tolerate some information\n\t\tloss in the memory operations. The memory accessor can also be used to\n\t\tincrease the result accuracy of memory-bound kernels that benefit from\n\t\tusing a more complex precision format in the arithmetic operations\n\t\twithout performance loss.\n  \\item \\textbf{Batched preconditioned iterative solvers:} Ginkgo contains high\n\t\tperformance batched iterative solvers that handle the concurrent\n\t\tsolution of a set of independent sparse linear systems of moderate size.\n\t\tThe batched iterative solvers allow for some flexibility in terms of the\n\t\tpreconditioner and monitor the system-individual convergence without\n\t\tperformance degradation.\n\\end{enumerate}\n\n\\paragraph{Recent Progress}\n\\begin{enumerate}\n  \\item The Ginkgo library realized native support for Intel GPUs (via\n\t\tDPC++)~\\cite{tsai2021porting}.\n  \\item MFEM treating Ginkgo as numerical backend allows accelerating MFEM\n\t\tsimulations with AMD GPUs, Intel GPUs, and NVIDIA GPUs.\n  \\item The Ginkgo library has been expanded with new advanced preconditioners\n\t\tsuch as ISAI and Multigrid, also supporting mixed-precision capabilities~\\cite{10.1007/978-3-030-85665-6_34}.\n  \\item Based on the memory accessor, the Ginkgo team deployed a Compressed\n\t\tBasis GMRES (CB-GMRES) solver that outperforms the standard GMRES solver\n\t\tby storing the Krylov basis vectors in lower precision, therewith\n\t\taccelerating the memory access~\\cite{DBLP:journals/corr/abs-2009-12101}.\n  \\item The Ginkgo team successfully employed the batched iterative solvers for\n\t\tthe hydrodynamic problems arising in the PeleLM\n\t\tsimulations and the gyrokinetic problems arising in the\n\t\tXGC simulations.\n\\end{enumerate}\n\n\n\\paragraph{Next Steps}\nOur next efforts are:\n\\begin{enumerate}\n  \\item \\textbf{Deployment of multi-node functionality:} Ginkgo already has\n\t\texperimental support for multi-node execution via an executor-agnostic\n\t\tMPI layer. We will extend the support and make it production-ready.\n  \\item \\textbf{Deployment of GPU-resident spare direct solvers:} In response to\n\t\tan urgent need of national power grid simulations, we will develop\n\t\tGPU-resident sparse direct solvers.\n  \\item \\textbf{Block-versions of the parallel Incomplete factorization\n\t\tpreconditioner:} To better reflect the properties of the ECP application\n\t\tprojects, we will deploy blocked versions of the ParILU and ParILUT\n\t\tparallel ILU and parallel threshold ILU preconditioners in the Ginkgo\n\t\tsoftware library.\n  \\item \\textbf{Problem-specific preconditioners for MFEM:} In collaboration\n\t\twith the ECP CEED cluster, we will design problem-specific mixed\n\t\tprecision preconditioners for matrix-free finite element simulations.\n\\end{enumerate}\n", "meta": {"hexsha": "3e4ea4b7f903f2df60a8ce1863330ad972e5aa0b", "size": 6905, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "projects/2.3.3-MathLibs/2.3.3.13-CLOVER/2.3.3.13-GINKGO.tex", "max_stars_repo_name": "egboman/ECP-ST-CAR-PUBLIC", "max_stars_repo_head_hexsha": "6ac85f302f3f5b1fbf51191f99392a5502a164fa", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "projects/2.3.3-MathLibs/2.3.3.13-CLOVER/2.3.3.13-GINKGO.tex", "max_issues_repo_name": "egboman/ECP-ST-CAR-PUBLIC", "max_issues_repo_head_hexsha": "6ac85f302f3f5b1fbf51191f99392a5502a164fa", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-12T19:39:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-12T19:39:54.000Z", "max_forks_repo_path": "projects/2.3.3-MathLibs/2.3.3.13-CLOVER/2.3.3.13-GINKGO.tex", "max_forks_repo_name": "egboman/ECP-ST-CAR-PUBLIC", "max_forks_repo_head_hexsha": "6ac85f302f3f5b1fbf51191f99392a5502a164fa", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-10-15T23:45:24.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-15T23:45:24.000Z", "avg_line_length": 53.5271317829, "max_line_length": 111, "alphanum_fraction": 0.8091238233, "num_tokens": 1628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.33816910158461405}}
{"text": "\\section{Shock wave simulation}\nWe studied the evolution of moderately relativistic shocks and spectrum of accelerated particles. We chose relativistic shocks with a low Lorentz factor because the maximum energy of the produced cosmic rays increases with the shock wave Lorentz factor, while the efficiency of acceleration decreases, \nbecause it is more difficult for particle to cross fast moving front many times \n%\n\\cite{Ellison2013}. So we assume that the intermediate case of moderately relativistic shocks provides the most efficient acceleration.\n\nWe developed the implicit particle-in-cell (PIC) code, presented in our previous paper \\cite{Romansky2016}, based on the scheme suggested by Lapenta et al.~\\cite{Lapenta2006} and improved for the relativistic case by Noguchi et al.\\cite{Noguchi2007}.\nOur code is fully three-dimensional and parallelized with MPI technology, which is adapted for distributed computing and can be executed on a wide class of computers. We use \n%cleaning divergence of electric field \nthe electric field divergence correction\nafter every several time steps and \n%Fourier filtering of shortwave harmonics \nthe shortwave harmonics Fourier filtering\nto suppress the numerical Cherenkov instability and improve the energy conservation.\n\nIn the modeling setup the homogeneous plasma flows in the simulation box through the right boundary\nand collides with the reflecting superconducting wall on the left boundary, launching the shock wave. It is a common way to initialize a shock wave, because the initialization using the Rankine–Hugoniot conditions does not take into account the microscopic distribution, and the shock wave, created in such way, will probably fall apart into several discontinuities.\n\n\\begin{figure}[h!]\n\t\\centering\n\t\\includegraphics[width=1.0\\textwidth]{fig/protons.eps} \n\t\\caption{Distribution of protons in the relativistic shock wave with Lorentz factor 1.5 with different inclination angle.}\n\t\\label{protons}\n\\end{figure} \n  \nThe simulations are one-dimensional and have the following parameters: the initial flow Lorentz factor $\\gamma = 1.5$, the number densities $n_e = 10^{-4} \\rm{cm}^{-3}$, $n_p = 10^{-4} \\rm{cm}^{-3}$ , the temperature $5\\cdot10^8 \\rm{K}$, the magnetic field $B = 10^{-4} \\rm{G}$, the full size of the box $L = 2\\cdot10^{12} \\rm{cm}$, the number of cells $N=2\\cdot10^4$. The electron mass is reduced to $m_e = \\frac{m_p}{20}$. The full time of simulation is $T = 5000 {\\omega_p}^{-1}$.This values gives the dimensionless parameter magnetization $\\sigma = \\frac{B^2}{4\\pi\\gamma (n_p m_p + n_e m_e) c^2} = 0.003$. Inclination angle $\\theta$ is the angle between the flow velocity and the magnetic field. We present the results for the particle spectrum in several simulations with different $\\theta$. The stable shock waves formed in all simulations and the total energy deviation is less than $3\\%$, and it proves that our code provides correct model of the shock waves. \n\n\n\\begin{figure}[h!]\n\t\\centering\n\t\\includegraphics[width=1.0\\textwidth]{fig/electrons.eps} \n\t\\caption{Distribution of electrons in the relativistic shock wave with Lorentz factor 1.5 with different inclination angle.}\n\t\\label{electrons}\n\\end{figure}\n\nOne can see in Figures \\ref{protons} and \\ref{electrons} the particle spectrum for different angles $\\theta$. The spectra consist of three parts - the narrow peak of cold but fast moving initial flow, the wide peak of hot downstream and the non-thermal accelerated component. Figures show that the spectrum of accelerated particles strongly depends on angle $\\theta$. If $\\theta$ is less than critical value, defined by the equation $c\\cdot \\cos(\\theta_{crit})=v_{shock}$, where all values are measured in the upstream rest frame, particles can escape from the front and cross it several times to gain more energy (see, e.g., \\cite{Pelletier2017}). It is difficult to evaluate the critical angle a priori, because the compression relation of the shock wave which will be created in the simulation is unknown. However the estimation for case of a strong wave (the compression relation equals $4$) provides $\\theta_{crit}=45^{\\circ}$ in the downstream frame, which is consistent with the results of our simulations.\n\nAlso, one can see that for the angles less then the critical one, the particle spectra are higher and longer for larger $\\theta$. The spectrum of non-thermal component is about 10 times higher for protons than for electrons at the same energy. It is consistent with other Particle-in-cell simulations of the shock waves {\\cite{Sironi2011}}.\n\nThe results show some interesting effects for angles close to the critical value (black and yellow lines)- electrons are still accelerating while protons are not. It can be explained by electrons acceleration in the short-wavelength turbulence of the shock wave precursor. Due to the small gyroradius of electrons in initial flow, short-wavelength turbulence scatter them more efficiently than protons. However, further research is necessary in order to study this phenomena in detail.\n\n\n\n", "meta": {"hexsha": "470968c10ee7363797d0e899ca68bc8964fe1a9f", "size": 5049, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "papers/Physica2017/shock.tex", "max_stars_repo_name": "eskyhome/PICpp", "max_stars_repo_head_hexsha": "3365e0e36ba46a87e7a406670ed2dbd9f60ef219", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-05-16T01:41:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-17T05:13:23.000Z", "max_issues_repo_path": "papers/Physica2017/shock.tex", "max_issues_repo_name": "eskyhome/PICpp", "max_issues_repo_head_hexsha": "3365e0e36ba46a87e7a406670ed2dbd9f60ef219", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "papers/Physica2017/shock.tex", "max_forks_repo_name": "eskyhome/PICpp", "max_forks_repo_head_hexsha": "3365e0e36ba46a87e7a406670ed2dbd9f60ef219", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-05-16T01:45:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-26T06:43:58.000Z", "avg_line_length": 114.75, "max_line_length": 1013, "alphanum_fraction": 0.7884729649, "num_tokens": 1169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.33816910158461405}}
{"text": "\\documentclass[a4paper]{article}\n\n\\usepackage{amsmath, amssymb}\n\\usepackage{bm}\n\\usepackage{booktabs}\n\\usepackage{dcolumn}\n\\usepackage{graphicx}\n\\usepackage{siunitx}\n\\usepackage{pgfplots}\n\\usepackage{pgfplotstable}\n\n\\def\\mean#1{\\left< #1 \\right>}\n\n\\title{Investigating the Fracturing of Raw Spaghetti}\n\\date{1 September 2015}\n\\author{Tarik Onalan}\n\n\\begin{document}\n    \\maketitle\n    \\section{Introduction}\n        \\subsection{Purpose}\n            To understand how the separation of the applied forces on the spaghetti affect\n            the length of the secondary fracture.\n        \\subsection{Hypothesis/Prediction}\n            I predict that as the distance between the two forces decreases, the length of\n            the broken spaghetti pieces will decrease, as there will be less space for a\n            cascading fracture to take place.\n        \\subsection{Variables}\n            \\textbf{Independent Variable}\n            \\begin{itemize}\n                \\item Width between forces [\\si\\cm]\n            \\end{itemize}\n            \\textbf{Dependent Variables}\n            \\begin{itemize}\n                \\item Length of broken spaghetti pieces [\\si\\cm]\n            \\end{itemize}\n            \\textbf{Controlled Variables}\n            \\begin{itemize}\n                \\item Length of starting spaghetti [\\SI{25.0}{\\cm}]\n                \\item Width of starting spaghetti [\\SI{0.2}{\\cm}]\n                \\item Mass of starting spaghetti [\\SI{5.4}{\\g}]\n            \\end{itemize}\n    \\section{Materials}\n        \\begin{itemize}\n            \\item Spaghetti $\\cdot 20$\n            \\item Rotatable clamps $\\cdot 2$\n            \\item Ruler $\\cdot 1$\n            \\item Scale $\\cdot 1$\n        \\end{itemize}\n    \\section{Procedure}\n        \\begin{enumerate}\n            \\item (CONTROL) Measure length of spaghetti\n            \\item (CONTROL) Measure width of spaghetti\n            \\item (CONTROL) Measure mass of spaghetti\n            \\item Pick a spaghetti, check it is within margin of error (\\SI{0.05}{\\cm})\n            \\item Measure distance between clamps (25, 20, 15, and \\SI{10}{\\cm})\n            \\item Clamp spaghetti\n            \\item Turn clamps at the same speed until spaghetti breaks\n            \\item Measure length of broken spaghetti pieces, if any (else record \\SI{0.0}{\\cm})\n            \\item Repeat steps 4-8 as necessary for data collection\n            \\item Repeat step 9 with remaining distances\n        \\end{enumerate}\n        \\resizebox{\\linewidth}{!}{\n            \\includegraphics{./figure.png}\n        }\n    \\section{Data}\n        \\resizebox{\\linewidth}{!}{\n            \\pgfplotstabletypeset[\n                multicolumn names,\n                display columns/0/.style={\n                    column name=Separation,\n                    column type={S},string type},\n                display columns/1/.style={\n                    column name=Trial 1,\n                    column type={S},string type},\n                display columns/2/.style={\n                    column name=Trial 2,\n                    column type={S},string type},\n                display columns/3/.style={\n                    column name=Trial 3,\n                    column type={S}, string type},\n                display columns/4/.style={\n                    column name=Trial 4,\n                    column type={S}, string type},\n                display columns/5/.style={\n                    column name=Trial 5,\n                    column type={S}, string type},\n                display columns/6/.style={\n                    column name=Average,\n                    column type={S}, string type},\n                columns/t1/.append style={\n                    postproc cell content/.append style={\n                        /pgfplots/table/@cell content/.add={}{$\\pm0.05$}\n                    }\n                },\n                columns/t2/.append style={\n                    postproc cell content/.append style={\n                        /pgfplots/table/@cell content/.add={}{$\\pm0.05$}\n                    }\n                },\n                columns/t3/.append style={\n                    postproc cell content/.append style={\n                        /pgfplots/table/@cell content/.add={}{$\\pm0.05$}\n                    }\n                },\n                columns/t4/.append style={\n                    postproc cell content/.append style={\n                        /pgfplots/table/@cell content/.add={}{$\\pm0.05$}\n                    }\n                },\n                columns/t5/.append style={\n                    postproc cell content/.append style={\n                        /pgfplots/table/@cell content/.add={}{$\\pm0.05$}\n                    }\n                },\n                columns/avg/.append style={\n                    postproc cell content/.append style={\n                        /pgfplots/table/@cell content/.add={}{$\\pm0.05$}\n                    }\n                },\n                every head row/.style={\n                    before row={\\toprule},\n                    after row={\n                        \\si\\cm & \\si\\cm & \\si\\cm & \\si\\cm & \\si\\cm & \\si\\cm & \\si\\cm\\\\\n                        \\midrule}\n                },\n                every last row/.style={after row=\\bottomrule}\n            ]{data.dat}\n        }\n\n        \\begin{tikzpicture}\n            \\begin{axis}[\n                title={Length of Spaghetti Piece Relative to Breaking Force Separation},\n                scale=1.75,\n                xlabel={Separation [\\si\\cm]},\n                ylabel={Length [\\si\\cm]},\n                xmin=9.0, xmax=26.0,\n                ymin=0.0, ymax=3.0,\n                x dir=reverse,\n                legend pos=north east,\n                ymajorgrids=true,\n                grid style=dashed\n            ]\n                \\addplot [\n                    color=blue,\n                    only marks\n                ] plot [\n                    error bars/.cd,\n                        x dir=both,\n                        y dir=both,\n                        x explicit,\n                        y explicit,\n                        x fixed=0.05,\n                        y fixed=0.05,\n                ] table [\n                    x=sep,\n                    y=avg,\n                ]{data.dat};\n\n                \\addplot [thick, red] table [y={create col/linear regression={y=avg}}]{data.dat};\n\n                \\draw (axis cs:24.95,2.45) -- (axis cs:10.05,-0.05);\n                \\draw (axis cs:25.05,2.35) -- (axis cs:9.95,0.05);\n\n                \\addlegendentry{Average}\n                \\addlegendentry{$\\pgfmathprintnumber{\\pgfplotstableregressiona} \\cdot x \\pgfmathprintnumber[print sign]{\\pgfplotstableregressionb}$}\n            \\end{axis}\n        \\end{tikzpicture}\n    \\section{Explanations}\n        \\subsection{Uncertainty}\n            There are uncertainty bars for both $x$ and $y$ axes, though they are difficult\n            to see on the $x$ axis due to scaling issues. Uncertainty was assumed to be\n            \\SI{0.05}{\\cm}, as the ruler used could only measure within the nearest\n            \\SI{0.1}{\\cm}, meaning that the \\SI{0.1}{\\cm} region that was $50\\%$ offset\n            from the ruler would be least certain.\n        \\subsection{Intercepts}\n            There is only one intercept on the graph, and that is when, at a separation of\n            \\SI{10.0}{\\cm}, the spaghetti does not fracture into any extra pieces during any\n            of the five trials.\n        \\subsection{Slope}\n            The slope is positive ($0.15$), meaning that as the width between the two clamps\n            increases, the length of the secondary broken spaghetti piece will also increase.\n    \\section{Calculations}\n        \\subsection{Average}\n            \\begin{equation}\n                \\mean{x_i^*}\n            \\end{equation}\n            \\begin{equation}\n                \\frac{\\displaystyle\\sum_i{x_i}}{i}\n            \\end{equation}\n            \\begin{equation}\n                \\frac{x_1+x_2+...+x_{i-1}+x_i}{i}\n            \\end{equation}\n        \\subsection{Error and Minimization for Line of Best Fit}\n            \\centerline{Error was calculated using sum squared error, which is defined as follows:}\n            \\begin{equation}\n                E=\\displaystyle\\sum_{i=1}^n{(y_i-f(x_i))^2}\n            \\end{equation}\n            \\begin{center}\n                While a program carried out the minimization of the function, the basic\n                premise of minimization is to ``follow the gradient,'' so to speak. The\n                program follows the gradient\n            \\end{center}\n            \\begin{equation}\n                E'=\\frac{\\partial}{\\partial x}(\\displaystyle\\sum_{i=1}^n{(y_i-f(x_i))^2})\n            \\end{equation}\n            \\begin{center}\n                similar to Euler's method for solving differential equations. Minimizing\n                the function is simply following the ``negative'' slope to the local minima\n                of the function.\n            \\end{center}\n    \\section{Conclusion}\n        My hypothesis, that the length of the secondary break will shorten as the separation of\n        the applied forces on the spaghetti was reduced, was supported by the data. When the separation\n        was \\SI{25.0}{\\cm}, the secondary break averaged a length of \\SI{2.4}{\\cm}. At \\SI{20.0}{\\cm},\n        the average dropped to \\SI{0.4}{\\cm}. \\SI{15.0}{\\cm} had an average of \\SI{0.2}{\\cm}, and,\n        the smallest separation, \\SI{10.0}{\\cm}, produced an average of \\SI{0.0}{\\cm}, meaning that\n        no secondary pieces were produced from the breaking of the spaghetti through the five trials.\n        This makes sense, as when the distance between the two clamps was decreased, there was less\n        ``spaghetti'' available for a cascading fracture to take place. A cascading fracture, in this\n        case, is the secondary fracturing of the spaghetti due to regions (namely the centre region)\n        of the spaghetti straightening before other regions (like the bases). In regards to the data,\n        however, I believe there is too much random error at play to make an outright statement of the\n        validity of my hypothesis. Spaghetti has too much inherent randomness to make it a reliable\n        object of measurement. A spaghetti could have microscopic weaknesses that predispose it to\n        breaking from certain locations: perhaps another spaghetti was slightly more dense; it would\n        have been impossible to tell with my measuring devices. Additionally, as I was the one turning\n        the clamps, I was introducing error into the measurements; humans are not precise. However,\n        because the data shows such an overwhelming trend in support of my hypothesis, I believe I can\n        claim that my hypothesis is valid.\n\n        The design of the investigation was not incredible by any stretch of the mind, but given that\n        it was quite simple, the implementation, I believe, was up-to-par with the standards I had in\n        mind. That said, I was not impressed by the error accrued throughout the investigation. As I\n        said before, the spaghetti was a central source of randomness throughout the investigation.\n        A particular with my investigation, the clamps, also introduced randomness, but this was the\n        product of a compromise instead of ignorance. As I was investigating the secondary breakage\n        of spaghetti (around the centre), I wanted to make sure that I was avoiding contact with the\n        centre region of the spaghetti at the time of breakage. As a result, I had to resort to rotating\n        clamps as a compromise, as even though I still control their movement, I felt that they would\n        provide a more consistent torque than my hands would. The error introduced by both sources, in\n        the end, were mostly random; the results could essentially have gone either way.\n\n        One improvement that comes to mind is replacing the spaghetti with thin plastic sticks; the\n        material would be more uniform (mass, dimensions, elasticity), and would thus introduce less\n        random error into test results. However, this would undoubtedly be more expensive, so whether\n        or not it would be feasible is unknown.\n\\end{document}\n", "meta": {"hexsha": "97c26584b10233bd223c5f7dd7efbeabd65c2a38", "size": 12181, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "2015-2016/Physics/Spaghetti_Lab/Spaghetti_Lab.tex", "max_stars_repo_name": "QuantumPhi/school", "max_stars_repo_head_hexsha": "a1bec6b1ed4ea843cb291babf7b7b9925e370749", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2015-2016/Physics/Spaghetti_Lab/Spaghetti_Lab.tex", "max_issues_repo_name": "QuantumPhi/school", "max_issues_repo_head_hexsha": "a1bec6b1ed4ea843cb291babf7b7b9925e370749", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2015-04-10T07:28:17.000Z", "max_issues_repo_issues_event_max_datetime": "2015-04-10T07:30:10.000Z", "max_forks_repo_path": "2015-2016/Physics/Spaghetti_Lab/Spaghetti_Lab.tex", "max_forks_repo_name": "QuantumPhi/school", "max_forks_repo_head_hexsha": "a1bec6b1ed4ea843cb291babf7b7b9925e370749", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.9196787149, "max_line_length": 148, "alphanum_fraction": 0.5655529103, "num_tokens": 2733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.3379132916256894}}
{"text": "\\notocchapter{Additional Plots}\n\\section{Viscosities of all CESM Experiments}\n\\label{sec:viscosity-all}\n\\vfill\n\\begin{whole}\n\t\\centering\\importpgf{figures/appendix/visc-all-x3/}{visc-all-x3.pgf}\n\\end{whole}\n\\figcaption{Perpendicular viscosity parameter $B$ for all \\grid{x3} runs.\\label{fig:viscosity-all-x3}}\n\\vfill\n\\clearpage\n\\null\n\\vfill\n{\n\t\\centering\\importpgf{figures/appendix/visc-all-x1/}{visc-all-x1.pgf}\\par\n}\n\\figcaption[Perpendicular viscosity parameter \\(B\\) for all \\grid{x1} runs.]{Perpendicular viscosity parameter \\(B\\) for all \\grid{x1} runs. Note the changed scale from \\figref{fig:viscosity-all-x3}.\\label{fig:viscosity-all-x1}}\n\\vfill\n\n\\notocchapter{An Equatorial Shallow-Water Model (cont.)}\n\\label{appendix:shallow-water}\nThe following sections describe some technical aspects of the shallow water model used in \\secref{sec:equatorial-shallow-water}. \\secref{sec:appendix-sw-implementation} gives a summary of the numerical implementation of the model, while \\secref{sec:appendix-sw-verification} focuses on the reproduction of some results found in literature (\\cite{killworth} \\cite{greatbatch}), in order to verify the consistency of the model, and to allow for the detection of obvious errors in the implementation. Although no quantitative analysis is made, my shallow water model succeeds in reproducing the structure of each solution.\n\n\\section{Numerical Implementation}\n\\label{sec:appendix-sw-implementation}\nWhen implementing numerical models, oceanographers often apply a low-level approach, by explicitly discretizing the model equations using finite differences (see \\eg \\cite{kaempf}). These implementations are usually very efficient, but on the flip side quite static --- adding additional terms is cumbersome, since the numerical properties of the chosen scheme have to be preserved, and many methods work on regular meshes only.\n\nBecause it was important to me that my model supported an \\enquote{agile} development style allowing for quick prototyping, I have decided not to implement it from scratch using finite differences, but rather make use of the FiPy software package \\citep{fipy}, a finite volume solver framework that is accessed via the Python programming language. FiPy pre-defines finite-volume implementations for the most common terms that appear in \\acp{PDE}. On their homepage\\sidenote{\\url{http://www.ctcms.nist.gov/fipy/}}, the FiPy developers summarize the capabilities of FiPy:\n\n\\q{\\slshape The solution of coupled sets of PDEs is ubiquitous to the numerical simulation of science problems. Numerous PDE solvers exist, using a variety of languages and numerical approaches. Many are proprietary, expensive and difficult to customize. As a result, scientists spend considerable resources repeatedly developing limited tools for specific problems. Our approach, combining the FV method and Python, provides a tool that is extensible, powerful and freely available. A significant advantage to Python is the existing suite of tools for array calculations, sparse matrices and data rendering.\n\nThe FiPy framework includes terms for transient diffusion, convection and standard sources, enabling the solution of arbitrary combinations of coupled elliptic, hyperbolic and parabolic PDEs.}\n\nUsing FiPy, the actual formulation of the model equations becomes much easier (\\listingref{lst:fipy-equations}) and, for the most part, does not depend on the actual numerical implementation of the various terms. This way, I could explore a wide range of problems with different formulations of the model equations and model grids. The FiPy solutions also tended to be quite stable, since most of the terms are solved implicitly\\sidenote[-1]{Unfortunately, FiPy does not allow to formulate the shallow-water equations in a fully implicit manner (since the face velocities need to appear as explicit sources).}. However, this comes of course at a computational cost --- by choosing FiPy, I accepted higher run times in exchange for a lower implementation time, which seemed adequate for a project that is as time constrained as a Master's thesis.\n\n\\begin{listing}[p]\n\t\\caption[Equation setup for the shallow-water model in FiPy.]{Equation setup for the shallow-water model in FiPy. The cell-centered variables of the model are called \\texttt{height}, \\texttt{xVelocity}, and \\texttt{yVelocity}. Some terms use the rank 1 \\texttt{FaceVariable} \\texttt{fVelocity}, which is the linearly interpolated velocity at cell faces. \\texttt{A} and \\texttt{B} are \\texttt{CellVariable}s holding the parallel and perpendicular viscosities, respectively. \\texttt{WaterSourceBoundary} represents the forcing of the model (Gaussian in the north-western corner of the domain).}\n\t\\label{lst:fipy-equations}\n\t\t\\begin{listingsbox}{pythoncode}\n\t\t\tdiffCoeffX = FaceVariable(mesh=mesh, rank=1)\n\t\t\tdiffCoeffX[0] = A.faceValue\n\t\t\tdiffCoeffX[1] = B.faceValue\n\t\t\tdiffCoeffY = FaceVariable(mesh=mesh, rank=1)\n\t\t\tdiffCoeffY[0] = B.faceValue\n\t\t\tdiffCoeffY[1] = A.faceValue\n\n\t\t\tfDiv = faceVelocity.divergence\n\t\t\twaterSourceInterior = \\\n\t\t\t  (ImplicitSourceTerm(coeff=1.,var=height)-1) / \\\n\t\t\t  dampening_scale\n\n\t\t\txVelocityEq = TransientTerm(var=xVelocity) \\\n\t\t\t+ ConvectionTerm(coeff=fVelocity,var=xVelocity) \\\n\t\t\t- ImplicitSourceTerm(coeff=fDiv, var=xVelocity) \\\n\t\t\t- ImplicitSourceTerm(var=yVelocity,coeff=.5*mesh.y) \\\n\t\t\t== \\\n\t\t\t- height.grad.dot((1.,0.)) \\\n\t\t\t+ DiffusionTerm(diffCoeffX,var=xVelocity)\n\n\t\t\tyVelocityEq = TransientTerm(var=yVelocity) \\\n\t\t\t+ ConvectionTerm(coeff=fVelocity,var=yVelocity) \\\n\t\t\t- ImplicitSourceTerm(coeff=fDiv, var=yVelocity) \\\n\t\t\t+ ImplicitSourceTerm(var=xVelocity,coeff=.5*mesh.y) \\\n\t\t\t== \\\n\t\t\t- height.grad.dot((0.,1.)) \\\n\t\t\t+ DiffusionTerm(diffCoeffY,var=yVelocity)\n\n\t\t\theightEq = TransientTerm(var=height) \\\n\t\t\t+ ConvectionTerm(coeff=fVelocity, var=height) \\\n\t\t\t== \\\n\t\t\twaterSourceBoundary - waterSourceInterior\n\n\t\t\t# couple equations\n\t\t\tswEquations = xVelocityEq & yVelocityEq & heightEq\n\t\t\\end{listingsbox}\n\\end{listing}\n\n\\section{Verification}\n\\label{sec:appendix-sw-verification}\n\n\\subsection{\\cite{killworth}}\n\nAs%\n\\sidetable[Parameters used in the first verification run.]{Parameters used in the first verification run. Definitions as in \\cite{killworth}.}[tab:killworth-parameters]{%\n\t\\footnotesize%\n\\begin{align}\n\tL_x &= \\SI{4000}{\\kilo\\metre}& \\\\\n\tL_y &= \\SI{2000}{\\kilo\\metre}& \\\\\n\tg &= \\SI{0.01}{\\metre\\per\\second\\squared}& \\\\\n\t\\beta &= \\SI{2e-11}{\\per\\second\\per\\metre}& \\\\\n\tH &= \\SI{400}{\\metre}& \\\\\n\tA_h &= \\SI{e4}{\\metre\\squared\\per\\second}& \\\\\n\tY &= \\SI{-75}{\\kilo\\metre}&\n\\end{align}\n\\vspace*{-2\\baselineskip}\n}[2]%\n%\na first step, I have used my shallow-water model to qualitatively reproduce the figures shown in the second part of \\cite{killworth}. For this purpose, I have deactivated all forcing (\\(\\lambda = Q = 0\\)), and integrated the model forward for \\SI{100}{\\day} starting with a dam-break scenario, using parameters as in \\tabref{tab:killworth-parameters}\\sidenote[-4]{An animation of the adjustment process may be found at \\url{https://vimeo.com/145881146}.}, which are the same as used by \\citeauthor{killworth}. During the integration, the expected features such as Kelvin waves traveling along the boundaries of the domain are visible.\n\nThe final state after \\SI{100}{\\day} bears a striking resemblance with the corresponding figure from \\cite{killworth} (\\figref{fig:killworth-comp}). The height field, which coincides with stream lines in high latitudes, shows the same two large circulation cells in the western half of the basin with a comparable magnitude. The velocity field reveals that water predominantly crosses the equator in a western boundary current, from where it either enters the circulation far north, or re-circulates into the southern hemisphere in the interior.\n\nConsidering how similar the resulting figures look, given that the two models are implemented using entirely different numerical schemes (finite volume method vs.\\ finite differences on a Arakawa C-grid\\sidenote[-2]{The Arakawa grids were first introduced by \\citet{arakawa}, and are still widely used in geophysical fluid dynamics due to their computational efficiency and conservation properties.}), and presumably use different resolutions (used resolution not reported in \\cite{killworth}), I assume my shallow water model to be working correctly for this application.\n\n\\begin{figure}\n\t\t\\subbottom[My model]{%\n\t\t\t\\raisebox{.15\\totalheight}{\\importpgf{figures/appendix/killworth-comp}{killworth-comp.pgf}}%\n\t\t}%\n\t\t\\hfill%\n\t\t\\subbottom[From \\cite{killworth}]{%\n\t\t\t\\includegraphics[width=.45\\textwidth]{appendix/killworth-sol}%\n\t\t}\n\t\t\\caption[Comparison between a geostrophic adjustment solution from \\cite{killworth}, and one created with my own shallow-water model.]{Comparison between a geostrophic adjustment solution from \\cite{killworth}, and one created with my own shallow-water model (identical parameters, as in \\tabref{tab:killworth-parameters}).}\n\t\t\\label{fig:killworth-comp}\n\\end{figure}\n\n\\subsection{\\cite{greatbatch}}\n\\cite{greatbatch} contains an interesting study of the \\cite{kawase} model, giving a range of numerical solutions for different damping timescales. Since the implementation and used parameters are well described, this publication is a valuable resource to verify my model with a forced reference. However, since the Kawase model equations differ slightly from the ones I have used in my model\\sidenote[-3]{\\citeauthor{kawase} (and thus \\citeauthor{greatbatch}) uses full spherical coordinates, and the \\(h\\)-equation has been linearized. See also \\secref{sec:sw-equations}.}, a comparison has to remain qualitative.\n\nSince we are only interested in the low damping regime\\sidenote{Otherwise, deeply penetrating cross-equatorial flow becomes impossible.}, I have used a damping time scale of \\SI{1}{\\year} for my experiments. Comparing the steady state solution of a high viscosity run with the corresponding figure given in \\cite{greatbatch} (\\figref{fig:greatbatch-comp}) reveals another striking similarity. In the steady state, the interior height field is symmetric around the equator, with a narrow western boundary current and a wide interior circulation. During spin-up, the same features as described by \\citeauthor{greatbatch} can be observed, such as the formation of a swift eastward jet along the equator, that splits up into two branches as a Kelvin wave is emitted by the eastern boundary that arrests the flow at the equator (not shown).\n\n\\begin{figure}\n\t\t\\subbottom[My model]{%\n\t\t\t\\raisebox{1.5ex}{\\importpgf{figures/appendix/greatbatch-comp}{greatbatch-comp.pgf}}%\n\t\t}\n\t\t\\subbottom[From \\cite{greatbatch}]{%\n\t\t\t\\includegraphics[width=.75\\textwidth]{appendix/greatbatch-sol}%\n\t\t}\n\t\\caption{Comparison between a steady-state solution from \\cite{greatbatch}, and one created with my own shallow-water model.}\n\t\\label{fig:greatbatch-comp}\n\\end{figure}\n", "meta": {"hexsha": "94a63c9d62dd153296999a73c734e3d987ed28d2", "size": 10868, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "msc-thesis/src/backmatter/appendix.tex", "max_stars_repo_name": "dionhaefner/dionsthesis", "max_stars_repo_head_hexsha": "cc06f14d54f21692ae87a1a4858979841cf531c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2017-01-31T00:26:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-25T09:32:03.000Z", "max_issues_repo_path": "msc-thesis/src/backmatter/appendix.tex", "max_issues_repo_name": "dionhaefner/dionsthesis", "max_issues_repo_head_hexsha": "cc06f14d54f21692ae87a1a4858979841cf531c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "msc-thesis/src/backmatter/appendix.tex", "max_forks_repo_name": "dionhaefner/dionsthesis", "max_forks_repo_head_hexsha": "cc06f14d54f21692ae87a1a4858979841cf531c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-09-29T18:31:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-29T16:00:45.000Z", "avg_line_length": 83.6, "max_line_length": 845, "alphanum_fraction": 0.77944424, "num_tokens": 2696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.3379103161776006}}
{"text": "\\section{Vaccination history stratification}\n% Referring to the immunity stratification as the vaccination stratification here, for the Bhutan application\nHistory of vaccination is captured by stratifying all model compartments by vaccination status.\nTwo vaccination strata are included to represent those who have received at least two doses of a COVID-19 vaccine,\nand those who have not.\nThe following are not considered in this approach to simulating vaccination:\n\\begin{itemize}\n    \\item Any effect of receiving a single dose of vaccine\n    \\item Waning of vaccine-induced immunity\n    \\item Any additional effect from receiving additional vaccine doses following the second dose\n\\end{itemize}\nThe effect of vaccination on transmission is to partially reduce the rate of infection for all persons at-risk of infection in the vaccinated stratum.\nThis includes both fully susceptible (never previously infected) persons,\nas well as recovered persons who are at risk of reinfection.\nEmerging variants of concern (VoCs) may escape this immunity, as described further below.\n% To illustrate this further, the next steps would be to display the population distribution by stratum,\n% and/or to explain the implementation of the dynamic proportions code\n\n\\section{Immunity-strain interaction}\nThe strains/VoCs implemented in the model may escape both vaccine-induced and natural immunity, as follows.\n\n\\subsection{Application to first infection}\nThe first infection episode with SARS-CoV-2 is represented through the transition from the susceptible\nto the first latent compartment.\nThe susceptible compartment is not stratified by strain,\nbecause these persons have no infection history.\nTherefore, for infection of persons never previously infected,\nonly the vaccination-induced immunity status is relevant.\nThe rate of infection for a particular vaccination status and infecting strain is adjusted by the factor:\n\\[1 - p_{i} \\times s_{j}\\]\nWhere \\(p_{i}\\) represents the protection afforded by vaccination stratum \\(_{i}\\),\nand \\(s_{j}\\) represents the degree of immune escape against vaccine-induced immunity for strain \\(_{j}\\).\nNote that this assumes that the extent of immune escape for a given strain is the same\nfor all vaccination strata. \n\n\\subsection{Application to re-infection}\nPersons who have recovered from previous infection episodes remain in a compartment that is stratified\naccording to the last infecting strain.\nThe recovered compartment is replicated into early and late stages,\nwhich can afford different levels of protection against re-infection.\nThe extent of protection must be explicitly specified for each strain-stage combination.\nThe rate of reinfection is adjusted by the factor:\n\\[(1 - p_{i} \\times s_{j})\\times (1 - n_{i,k,l})\\]\nWhere the additional term \\(n_{k,l,m}\\) represents the cross protection\nafforded by past infection with strain \\(_{k}\\)\nagainst infecting strain \\(_{l}\\)\nin vaccination stratum \\(_{i}\\).\n\n\\subsection{Adjusting age-specific severity parameters for immunity}\nWe use inputs for the age-specific case fatality rate and the age-specific hospitalisation rate from Nyberg et al., \nwhich provides estimates of these quantities in a population that already had substantial vaccine-induced immunity.\nWe therefore adjust these quantities for pre-existing immunity, to account for protection against death and hospitalisation.\nWe apply the following method to ensure that after adjusting the parameters for a specific age bracket for immunity,\nthe average parameter value would be equal to that reported by Nyberg et al. if weights were applied according to the\ndistribution of immunity in the population that was described in this study.\nTo do this, we estimate the proportion of the population in each of the three modelled immunity categories\nin the United Kingdom around the mid-point of the study,\nand the protection afforded by each of the immunity classes (see Table \\ref{tab:immunity_weighting}).\n\n\\begin{table}\n    \\begin{threeparttable}\n    \\begin{tabularx}{\\textwidth}{| X | X | X |}\n        \\hline\n        \\textbf{Immunity category} & \\textbf{Proportion of population} \\tnote{a} & \\textbf{Estimated protection} \\tnote{b} \\\\\n        \\hline\n        No immunity, unvaccinated & 0.312 & 0 \\\\\n        \\hline\n        Low immunity, vaccinated with two doses & 0.302 & 0.5 \\\\\n        \\hline\n        High immunity, vaccinated with three doses & 0.386 & 0.85 \\\\\n        \\hline\n\t\\end{tabularx}\n\t\\caption{Values used to re-weight the severity estimates provided in Nyberg et al. to separate immunity classes.}\n\t\\label{tab:immunity_weighting}\n    \\begin{tablenotes}\n        \\item[a] Estimated population distribution as at 16th December 2021 (study mid-point),\n        taken from Our World In Data.\n        \\item[b] Estimated protection against hospitalisation or death following Omicron infection.\n    \\end{tablenotes}\n    \\end{threeparttable}\n\\end{table}\n\n", "meta": {"hexsha": "7a4f7e8f64155225d1e6840301d91445492b4cc6", "size": 4905, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/tex/tex_descriptions/models/sm_sir/stratifications/immunity.tex", "max_stars_repo_name": "emmamcbryde/AuTuMN-1", "max_stars_repo_head_hexsha": "b1e7de15ac6ef6bed95a80efab17f0780ec9ff6f", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/tex/tex_descriptions/models/sm_sir/stratifications/immunity.tex", "max_issues_repo_name": "emmamcbryde/AuTuMN-1", "max_issues_repo_head_hexsha": "b1e7de15ac6ef6bed95a80efab17f0780ec9ff6f", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/tex/tex_descriptions/models/sm_sir/stratifications/immunity.tex", "max_forks_repo_name": "emmamcbryde/AuTuMN-1", "max_forks_repo_head_hexsha": "b1e7de15ac6ef6bed95a80efab17f0780ec9ff6f", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.0963855422, "max_line_length": 150, "alphanum_fraction": 0.779204893, "num_tokens": 1074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.33791031617760053}}
{"text": "\\chapter{Related Works}\\label{ch2}\nPreviously there have been many researches conducted on knowledge graphs. They share some common as well \nas different approaches.\nLet us discuss them one by one.\n \\section{Knowledge Graph Identification}\nIn the paper `Knowledge Graph Identification' ~\\cite{ref0kgi}, the authors collected two different data sets.\nIn both of them, they extracted uncertain entities and their relations to create an `extraction graph'. \nThe resulting extraction graph was full of noise, missing information. So they removed noise, \nadded missing informations. After that, they needed to find candidate facts. \nReasoning jointly about candidate facts, extracting their confidence, identifying coreferences, \n imposing ontological constraints, removing duplicate entities, resolving ontological conflicts\n were some of the other tasks. Let us take an example.\n\n ``We can use \\textbf{Binary Search Tree}, for fast lookup, addition and deletion of an item''.\nUsually, the word \\textbf{tree} means something related to plants. But in this case, \\textbf{tree}\nrefers to a data structure because the words \\textbf{binary}, \\textbf{search} are imposing ontological \nconstraints. Therefore we can distinguish between the two meanings and disambiguate them. Next, they needed to \ncreate edges between the nodes.\n To relate a concept with similar concept,\nthe researchers have used Probabilistic Soft Logic (PSL) ~\\cite{ref0psl}  ontological constraints,\nidentify coreferences etc. \n\\subsection{Probabilistic Soft Logic(PSL)}\nWe know, that boolean variables have only two values: $True$ and $False$ or $1$ and $0$. So boolean\nlogics can tell only between 2 choices. In real world problems, this is not always usable. \nThis is where PSL comes innto play. PSL assigns a value in range $[0,1]$. For example, the word\n \\textbf{tree} is not always related to plants. So, we cannot assign $0$ or $1$ to it.\n  Instead, we can assign \\textbf{tree} with a value, say $0.8$ with the meaning \\textbf{plan}\n  and $0.2$ with the meaning  \n\nPSL has some advantages. We can represent models using first order logic syntaxes.\nWe can have continuously valued random variables that is convenient with uncertainty or probability.\nUsing weights, we can control the importance of model rules.\n\n\\section{Link Detection}\nOne common problem in building a Knowledge Graph is to find appropriate links between various \nconcepts. Mihalcea annd Csomai et al ~\\cite{ref3LinkWikipedia} have worked on link detection. They used \nmachine learning on a wikipedia dump to link a concept(article) with its corresponding mention. \nThere they have also calculated \nlink probability of various phrases or mentions. Define link probability of a phrase as the \nnumber of wikipedia articles that use the phrase as anchor divided by  number of articles that mention the phrase at all.\n% \\begin{equation}\n%   $$ link probability of a phrase = \\frac{number of wikipedia articles that use the phrase as anchor}{ number of articles that mention the phrase at all } $$\n% \\end{equation}\n% link probability of a phrase = \\frac{number of wikipedia articles that use itthe phrases anchor}{ number of }\nNext they disambiguated links by taking help of the surrounding words \n( the words themselves and their parts of speech). Here a problem occurs on which meaning to select.\nThe best method is to take the most common meaning first. Then calculate the relatedness\nwith the context. Define $ relatedness(a,b) = \\frac{log(max(|A|, |B|)) - log(|AB|)}{log|W|-log(min(|A|, |B|))} $,\nwhere $a$,$b$ are the Article of interest, $A$ , $B$ are sets of all articles linking to $a$,$b$ respectively and $W$ \nis the set of all articles.\n\nAfter that, by comparing \nthe  common meaning with the relatedness, the correct link was found. \nFor example, the word `tree' has a common meaning `plant' and so 97\\% of the time, it will link to a page on plants.\nBut if we find `binary tree' in a document, the relatedness of `tree' to `binary' suggests that this\nphrase is related to data structure. That is how almost everyone disambiguates links. Followed by this, they \ndid Topic indexing which aims to identify the most significant topics, summarize the document and organize it \ninto various categories, and to answer queries fast. In topic indexing, the key problem is to find the correct significant \nterms and disambiguate them to appropriate topic.   \n\n%After that, in order to organize the documents, they have used topic indexing.\n%In order to make link detection efficient, Mihalcea annd Csomai et al used \n%(a) commonness (prior probability of each sense) and (b) how the sense relate with the nearby context.\n\n\nThe Next work deals with a semi-supervised graph regularization method on \ntwitter data wikification ~\\cite{ref4tw-wiki}. There the authores described the problems as unlinkability \n( absense of a valid concept from knowledge base), ambiguity and prominence. Some more major problem for working\nwith twitter data are informal writing style, shortness and noisiness. To deal with these problems, the authors \ndeveloped a graph-based semi-supervised learning algorithm for wikification. Their model at the same time, detects \nmentions and disambiguates them at both local and global levels. They have also developed meta path-based unified framework\nto detect relevant mentions. Their method works in this way: given a set of tweets $<t_1,t_2,... ,t_n>$ ,\nfirst find candidate concept mentions $<m,c1,c2,...,ck>$. From there, we find the most probable concept $c$\nrelated to  mention $m$ and so we get $<m,c>$ . After that , they constructed a relational graph $G= <V,E>$ .\n\nHere set of nodes $V = <v_1,...,v_n>$, and set of edges $E = <e_1,...,v_e>$. Here $v_i = <m_i, c_i>$. \n\\section{A Deep Neural Networking Approach}\nFinally, we have an important work of Larry Heck and Hongzhao Huang ~\\cite{ref1DeepLearning}. \nFirst they developed a robust way to represent concepts.\n Many NLP tools use string concatenation to represent ideas.\nBut most of the time it fails to represent appropriate concepts. For example `Madrid' is a place, `Real'\n means \nsomething authentic or true, but `Real Madrid' refers to a football club. \nThis is a counter example where string concatenation fails.\nA possible alternative is to use \\textit{Word Hashing} with $n$-gram ( tri-gram in this case) \nword representation. This way turns words into concept-vectors. This representation is \nrobust because it can be used even for unseen words.\nSo for example, \\textit{dog} is a word. First put \\# before and after the word, so it becomes \\textit{\\#dog\\#}.\nThen we get these trigrams: \\#do , dog , og\\#.\n  Thus $ \\vec(m) = \\vec(\\#dog\\#) = \\widehat(\\#do) + \\widehat(dog) + \\widehat(og\\#)$.\n  Since tweets donot have adequate data, one needs external source of knowledge to  make sense of \n  the tweets. In this case, they took a wikipedia dump, converted the documents into concept vectors\n   $\\vec(c)$ and simply took a dot product of the $ \\vec(m) $ and $ \\vec(c) $. If the tweet and the concept \n   are similar, the two vectors will have smaller angle, ie, $ \\cos(\\theta) = \\vec(m).\\vec(c)/mc $ . \nThis is defined as the semantic relatedness of two concepts, $R(m,c) $.\n After that they did neural embedding of knowledge\n graph. \n To do so, they tracked a concept and its corresponding subgraph, encode the knowledge as featured \n vector.\n then they trained Deep Neural Network to get semantic relationships among various concepts.\nAfter that, they took tweets and used their deep neural network on those tweets.\n\\endinput\n", "meta": {"hexsha": "781e34a32cc7d58321bc7d432460e4837931947b", "size": 7555, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapter2-relatedworks.tex", "max_stars_repo_name": "t33rtha/Building-A-Knowledge-Graph-Using-Twitter-Data", "max_stars_repo_head_hexsha": "52ae9fbd2cf5ca20dce6ad44441cc6ed402bc5b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-06T11:04:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T11:04:57.000Z", "max_issues_repo_path": "chapter2-relatedworks.tex", "max_issues_repo_name": "t33rtha/Building-A-Knowledge-Graph-Using-Twitter-Data", "max_issues_repo_head_hexsha": "52ae9fbd2cf5ca20dce6ad44441cc6ed402bc5b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter2-relatedworks.tex", "max_forks_repo_name": "t33rtha/Building-A-Knowledge-Graph-Using-Twitter-Data", "max_forks_repo_head_hexsha": "52ae9fbd2cf5ca20dce6ad44441cc6ed402bc5b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 73.3495145631, "max_line_length": 159, "alphanum_fraction": 0.7670416942, "num_tokens": 1822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593171945416, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3379103085735447}}
{"text": "\\documentclass[12pt]{article}\n\\usepackage{geometry} \n\\geometry{margin=1in}\n\\geometry{a4paper} \n\n\n\\usepackage{textcomp}\n\\usepackage{booktabs}\n\\usepackage{array}\n\\usepackage{paralist}\n\\usepackage{verbatim} \n\\usepackage{subfigure}\n\\usepackage{graphicx,caption}\n\\usepackage{placeins}\n\\usepackage{lipsum}\n\\usepackage{xcolor}\n\\usepackage{dcolumn}\n\\usepackage{sectsty}\n\\allsectionsfont{\\sffamily\\mdseries\\upshape}\n\\usepackage{gensymb,amsmath,mathtools,amssymb}\n\\usepackage{flafter}\n%\\usepackage{parskip}\n\\usepackage[utf8]{inputenc}\n\\usepackage[english]{babel}\n\\usepackage{tocbibind}\n\\usepackage[toc,page]{appendix}\n\\captionsetup{width=\\linewidth}\n\\usepackage{bm}\n\\usepackage{url}\n\n\\usepackage{pdflscape}\n\n\\newcommand{\\half}{\\frac{1}{2}}\n\n\n\\graphicspath{{./figs/}}\n\n\\title{Initial Sizing of 2020 ICLR hybrid rocket}\n\\author{Devansh Agrawal}\n%\\date{} \n\n\n\\begin{document}\n\n\\maketitle\n\n\n\\section{Introduction}\n\nThis document provides an overview of the sizing analysis and results for the 10k SRAD hybrid entry by Imperial College London Rocketry. \n\nThis is a working document, and as more information is fed into the system, the parameters may be updated.\n\n\\section{Flight performance requirement}\n\nThe first challenge was to estimate the performance requirements of the hybrid rocket to able to attain the target altitude with some margin. A separate document details the analysis, but a summary is provided here. \n\nWe assume the rocket follows a bang-off control scheme - the rocket thrusts at its main engine's max thrust, $F_{max}$~Newtons for $t_{burn}$~seconds and then coasts the remaining part of the journey. In this scenario, the final altitude of the rocket, $h_f = \\hat h_f c^2/g$, is entirely dependent on four non-dimensional parameters\\footnote{Assumes exponential atmosphere, constant drag coefficient, perfectly vertical flight}:\n\n\n\\begin{enumerate}\n\\item The thrust to initial weight ratio, $\\hat F = (F_{max})/(m_0 g)$\n\n\\item A drag parameter defined as\\footnote{Note: This parameter is like the drag to weight ratio (except it uses $c$ as the velocity and $m_0$ as the mass)}, $ x \\equiv (\\half \\rho c^2 c_d A)/(m_0 g)$\n\n\\item Propellant mass fraction, $MR \\equiv m_p/m_0$\n\n\\item Atmosphere parameter, $\\hat \\beta = \\beta c^2/g$\n\n\\end{enumerate}\n\nPlugging in suitable parameters, we find the required propellant mass fraction as a function of the thrust to weight ratio, as in figure~\\ref{fig:PMF}. \n\n%\\FloatBarrier\n\\begin{figure}[htbp]\n   \\centering\n   \\includegraphics[width=0.8\\linewidth]{perf_req.eps}\n   \\caption{Required thrust to weight ratio as a function of the propellant mass fraction}\n   \\label{fig:PMF}\n\\end{figure}\n%FloatBarrier\n\n\nFrom this, we can see that we need a propellant mass fraction of approximate 17\\%. The fact that the lines are near vertical above $T/W>2$ suggests that a slow, low thrust burn is roughly equivalent to a fast, high thrust burn. Therefore, since we have the ability to control our burn during the flight, a long, slow burn allows us to turn off the thrust closer to apogee, and with greater certainty of success. \n\n\\textbf{For design purposes, and to give ourselves some flexibility, we can therefore design our rocket to have a $T/W>2$ and a propellant mass fraction of at least 20\\%. }\n\nDetailed analysis with accurate drag coefficients, the mach dependence, and optimal control should be performed next to ensure these performance targets are sufficient and robust to future design changes. \n\n\\section{Vehicle Architecture}\n\nThe chosen system breakdown of the rocket is:\n \n\\begin{enumerate}\n\n\\item Payload\n\\begin{itemize}\n\\item 4~kg payload\n\\item 4.5~kg allocated, to allow for mounting\n\\end{itemize}\n\n\\item Avionics\n\\begin{itemize}\n\\item Includes all flight computers and sensing equipment, switchboards and mounting hardware\n\\item Includes interface wiring to other components with electronics\n\\item Does not include mass of electronics for other subsystems\n\\item Allocated 2~kg, based on previous IREC reports.\n\\end{itemize}\n\n\\item Recovery System\n\\begin{itemize}\n\\item Includes main and drogue parachute, parachute lines and deployment mechanism mass\n\\item includes mass of black powder and associated electronics. \n\\item Allocated 3~kg, based on previous IREC reports.\n\\end{itemize}\n\n\\item Main Engine\n\\begin{itemize}\n\\item Includes oxidiser tank, fuel tank\n\\item ox mass, fuel mass, \n\\item valves assembly with electronics (allocated 1~kg), and nozzle assembly (allocated 1~kg)\n\\item Detailed engine sizing was not performed, and needs to be throughly verified. \n\\end{itemize}\n\n\\item Boosters\n\\begin{itemize}\n\\item Since the $T/W$ of the main engine is around 2, it is not enough to clear the launch rail with the required speed. As such, solid boosters are to be used launch the rocket, sized to provide $T/W = 10$ for the duration needed to clear the launch rails.\n\\item Includes motor dry mass, but not mounting structural mass\n\\end{itemize}\n\n\\item Structures\n\\begin{itemize}\n\\item Includes nose cone (allocated 0.5 kg)\n\\item fins (1.2~kg)\n\\item body tube with internal bulkheads and couplers (4~kg)\n\\item booster mounting structure (0.3~kg)\n\\item overall structural mass allowed is 6~kg.\n\\end{itemize}\n\n\\end{enumerate}\n\n\n\\section{Sizing approach}\n\nGPkit\\footnote{\\url{https://gpkit.readthedocs.io/en/latest/}} was used to perform the sizing study. GPkit allows the user to define variables describing the vehicle, the constraints relating the variables (either due to physics, performance requirements or due to design requirements), and an objective function to optimise. It will then perform a global optimisation and return the optimised parameters of the design. GPkit also allows for easy compartmentalisation, by allowing the user to define these variables within classes, and thus separating the different parts of the design. \n\nI have created a basic framework that should be general enough to allow more detail to be added into the model, as we develop it. \n\nAt the top level, a \\texttt{rocket} class is defined. The six components above are created, each defined in a separate python file. These classes inherit from \\texttt{gpkit.Model} which allows gpkit to interpret the variables and the constraints, and exposes a \\texttt{solve} method to perform the optimisation.\n\nFor ease of visualisation and interpretation, a jupyter notebook instantiates the \\texttt{rocket} and calls the signomial solver, \\texttt{localsolve}. Due to the structure of the rocket unfortunately, the geometric globally optimal solver cannot be called, but a local signomial solver must be used. That said, in most scenarios, this solver is sufficiently robust to return a good, and viable solution. \n\nThe jupyter notebook also has result printing code blocks to allow for easy debugging of models. \n\nNote, when there are changes to the python files where the relationships are described, jupyter must re-import the classes. The best way to ensure this is accurately done is by clicking the \\texttt{Restart \\& Run-All} button. \n\nThe most important relationships used in this sizing are listed at the end of the document, but the most up-to-date relationships are only available in the python files. \n\n\n\\section{Sizing results}\n\nThe solve  took 5 GP solves, and 1.54 seconds. \n\n\\textbf{Total rocket mass: 27.89 kg}\n\nThe results are more easily interpreted in the form of a diagram, on the last page.\n\n\\begin{landscape}\n\n\\begin{verbatim}\nSORTED BY LINEAGE, SENSITIVITY (solved on 05-11 19:18) NOTE: ENGINE IS POORLY SIZED.\n+----------------+---------------------+----------+--------+--------+---------------------------------------+\n|            key |             lineage |    value |   unit |   sens |                           Description |\n+----------------+---------------------+----------+--------+--------+---------------------------------------+\n|            PMF |              Rocket |    0.220 |      - |  0.814 |     Propellant Mass Fraction required |\n|     v_{launch} |              Rocket |   30.000 |    m/s |  0.125 |              Velocity off launch rail |\n|     L_{launch} |              Rocket |    5.200 |      m | -0.029 |                 Length of launch rail |\n|              g |              Rocket |    9.810 |  m/s^2 |  0.011 |           Acceleration due to gravity |\n|     a_{launch} |              Rocket |   86.538 |  m/s^2 |      * |          Acceleration off launch rail |\n|              m |              Rocket |   27.891 |     kg |      * |                        Mass of Rocket |\n| TW_{main, min} |              Rocket |    2.500 |      - |  0.000 | Main engine thrust to take off weight |\n|          min_a |              Rocket |   86.538 |  m/s^2 |      * |           minimum launch acceleration |\n|              m |     Rocket/Avionics |    1.000 |     kg |  0.069 |                      Mass of Avionics |\n|            DMF |     Rocket/Boosters |    0.700 |      - |  0.157 |         Dry mass fraction of boosters |\n|              c |     Rocket/Boosters | 2000.000 |    m/s | -0.067 |                boosters exhaust speed |\n|              m |     Rocket/Boosters |    0.975 |     kg |      * |                      Mass of Boosters |\n|       m_{prop} |     Rocket/Boosters |    0.292 |     kg |      * |           Propellant mass of boosters |\n|        m_{dry} |     Rocket/Boosters |    0.682 |     kg |      * |                  Dry mass of boosters |\n|       t_{burn} |     Rocket/Boosters |    0.347 |      s |      * |                     Booster burn time |\n|              F |     Rocket/Boosters | 1687.261 |      N |      * |            Boosters cumulative thrust |\n|              m |      Rocket/Payload |    4.000 |     kg |  0.275 |                       Mass of Payload |\n|              m |     Rocket/Recovery |    3.500 |     kg |  0.241 |                      Mass of Recovery |\n| \\rho_{ox, tank}| Rocket/SimpleEngine | 8000.000 | kg/m^3 |  0.391 |             Density of ox tank, steel |\n|         Tank P | Rocket/SimpleEngine |   60.000 |    bar |  0.391 |                  Max Ox Tank pressure |\n|             SF | Rocket/SimpleEngine |    3.000 |      - |  0.391 |          Wall thickness safety factor |\n|   \\sigma_{max} | Rocket/SimpleEngine |  585.000 |    MPa | -0.391 |             Max stress of tank, steel |\n|       rho_{ox} | Rocket/SimpleEngine |  650.000 | kg/m^3 | -0.282 |          density of liquid ox *ROUGH* |\n|      rho_{wax} | Rocket/SimpleEngine |  900.000 | kg/m^3 | -0.109 |                       Density of fuel |\n|     m_{valves} | Rocket/SimpleEngine |    1.000 |     kg |  0.069 |           Mass of valves and plumbing |\n|     m_{nozzle} | Rocket/SimpleEngine |    1.000 |     kg |  0.069 |               Mass of nozzle assembly |\n|             OF | Rocket/SimpleEngine |    7.500 |      - | -0.063 |                      Ox to fuel ratio |\n|              F | Rocket/SimpleEngine | 1000.000 |      N | -0.040 |                         Engine thrust |\n|              m | Rocket/SimpleEngine |   13.816 |     kg |      * |                        Mass of Engine |\n| m_{grain tank} | Rocket/SimpleEngine |    1.580 |     kg |      * |            Mass of combustion chamber |\n|    m_{ox tank} | Rocket/SimpleEngine |    4.101 |     kg |      * |                       Mass of ox tank |\n|       m_{prop} | Rocket/SimpleEngine |    6.136 |     kg |      * |                    Mass of Propellant |\n|        m_{dry} | Rocket/SimpleEngine |    7.680 |     kg |      * |                    Dry mass of engine |\n|         m_{ox} | Rocket/SimpleEngine |    5.414 |     kg |      * |                               ox mass |\n|       m_{fuel} | Rocket/SimpleEngine |    0.722 |     kg |      * |                             fuel mass |\n|           d_ox | Rocket/SimpleEngine |    6.000 |     in |  0.000 |                   Diameter of ox tank |\n|       t_{wall} | Rocket/SimpleEngine |    2.345 |     mm |      * |             Wall Thickness of ox tank |\n|         L_{ox} | Rocket/SimpleEngine |    0.457 |      m |      * |                     Length of ox tank |\n|       v_{fuel} | Rocket/SimpleEngine |  802.096 |   cm^3 |      * |                        Volume of fuel |\n|      L_{grain} | Rocket/SimpleEngine |    0.176 |      m |      * |                   Length of the grain |\n|         V_{ox} | Rocket/SimpleEngine | 8329.458 |   cm^3 |      * |                     Volume of ox tank |\n|      A_{grain} | Rocket/SimpleEngine |   45.581 |   cm^2 |      * |           cross section area of grain |\n|              m |   Rocket/Structures |    4.600 |     kg |  0.317 |                    Mass of Structures |\n+----------------+---------------------+----------+--------+--------+---------------------------------------+\n\\end{verbatim}\n\nNote, the sensitivity is the logarithmic sensitivity, ie, $\\text{sensitivity} = \\frac{d \\log(\\text{cost})}{d\\log(\\text{var})}$. A positive number indicates that increasing the variable will increase the cost. Note, the star indicates a zero sensitivity, since this is a variable that gpkit has solved for. As such, it represents the minima of the function and thus has zero sensitivity, similar to how a function has zero gradient wrt to a variable when it is optimized. \n\n\\end{landscape}\n\n\n\\section{Next steps}\n\\begin{itemize}\n\\item Verify structural mass allocations\n\\item Verify stability requirements - ie, ensure fins are large enough\n\\item Perform detailed drag accounting\n\\item Perform detailed controls analysis\n\\item more accurate tank sizing needed, especially considering manufacturability, source-ability, cost.\n\\item tank ullage not accounted for\n\\item very simplified thrust curve needs to be improved\n\\end{itemize}\n\nDesign modification if the engine performance is poorer than expected: bigger boosters. Therefore, the booster mounts need to be flexible enough to allow different booster designs. Could look into dropping boosters after their work is done, but this is complicated. \n\n%\\bibliographystyle{unsrt}\n%\\bibliography{biblio}\n\n\\section{Sizing relationships used}\n\n\\emph{NOTE: the values in this section are probably wrong, the method should be roughly accurate. Consult the github for the values used.}\n\nMost constraints are fairly straightforward. Here are the key ones\n\n\\begin{itemize}\n\\item m = sum of mass of components\n\\item propellant mass fraction $>$ 20\\%\n\\item Launch requirements:\n\\begin{itemize}\n\\item v off launch rail $>$ 30m/s\n\\item launch accel = (booster thrust + main engine thrust - mg)/m \n\\item launch accel $>$ min accel = (launch v)$^2$/(2 launch rail L)\n\\item booster burn time such that burn out occurs at 5 m/s\n\\end{itemize}\n\\item Components:\n\\begin{itemize}\n\\item Payload: m = 4.5 kg\n\\item Avionics: m = 2 kg\n\\item Recovery: m = 3 kg\n\\item Engine: \n\\begin{itemize}\n\\item OF = 6\n\\item m fuel, m ox based on m prop and OF\n\\item d = 150 mm\n\\item P tank $<$ 60 bar\n\\item wall thickness based on hoop stress and safety factor of 5, assumes Al-7075 due to high yield strength (double of Al 6061), sealing and welding to be determined more thoroughly\n\\item ox is fully liquid, at critical density of 490 kg/m3 $\\rightarrow$ determine length of ox tank\n\\item mass of ox tank based on cylinder material thickness, end caps not accounted for\n\\item grain tank is similarly sized, assumes the grain is only occupied in half the cross sectional area (needs to be refined), and same wall thickness as ox tank. No liner material considered. Carbon overwrap of tank tube would save lots of mass if possible. \n\\item \\emph{regression rates, motor dynamics, etc not accounted for}\n\\item m valves = 1 kg\n\\item m nozzle = 1 kg\n\\item assumed F= 1000 N\n\\item c = 1800 m/s (needs to be verified)\n\\end{itemize}\n\\item Boosters:\n\\begin{itemize}\n\\item propellant mass such that total impulse can be delivered\n\\item dry mass fraction is 70\\%. Needs to be refined by picking a motor, assumed c = 2000m/s\n\\end{itemize}\n\\item Structures:\n\\begin{itemize}\n\\item m = sum of components\n\\item m fins = 1.2 kg\n\\item m nose cone = 0.5 kg\n\\item m tube = 4 kg\n\\item m  booster struc = 0.3 kg\n\\end{itemize}\n\\end{itemize}\n\n\\end{itemize}\n\n\n\\FloatBarrier\n\\begin{figure}[htbp]\n   \\centering\n   \\includegraphics[width=\\linewidth]{sizing_result_Nov_5.eps}\n   \\caption{Summary of Sizing results}\n   \\label{fig:}\n\\end{figure}\n%FloatBarrier\n\n\n\n\\end{document}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "6a72bcce4243f2e7b754501d1b5e4fc56b8c2954", "size": 16238, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Sizing/writeup/writeup.tex", "max_stars_repo_name": "icl-rocketry/optimalSizing", "max_stars_repo_head_hexsha": "c23f5a84bc9f46cf86977ec7da97dbf7126dcb1b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-06T04:45:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-18T07:41:06.000Z", "max_issues_repo_path": "Sizing_FronzenNov5/writeup/writeup.tex", "max_issues_repo_name": "icl-rocketry/optimalSizing", "max_issues_repo_head_hexsha": "c23f5a84bc9f46cf86977ec7da97dbf7126dcb1b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sizing_FronzenNov5/writeup/writeup.tex", "max_forks_repo_name": "icl-rocketry/optimalSizing", "max_forks_repo_head_hexsha": "c23f5a84bc9f46cf86977ec7da97dbf7126dcb1b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-06T04:45:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-06T04:45:46.000Z", "avg_line_length": 48.9096385542, "max_line_length": 586, "alphanum_fraction": 0.6519275773, "num_tokens": 4218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011686727232, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.33789321307329956}}
{"text": "\\section{Conclusion}\n\nIn conclusion, we find that Parareal is indeed capable of providing significant\nspeedup to our general numerical methods for ordinary differential equations.\nhowever, it's difficult to determine what's the correct choice of $\\fine$ and\n$\\coarse$, since the stability function is not easy to analyze in general, and\nbecause there's an unfomfortable optimization problem between wanting $\\coarse$\nto be as accurate as possible, while making sure that the ratio $T_f/T_g$ is as\nlarge as possible. In addition, for systems with strong requirements on $\\Delta\nt$, such as for the heat equation, we might have no choice but to make $\\Delta\nt$ small, and thus making $T_g$ large with respect to $T_f$. This implies that\nfor these system, there might be better approaches to parallelism.\n\nSome points to personally reflect on this project:\n\\begin{itemize}\n  \\item I should not have used OpenMP to implement parareal. In the end, I was\n    limited in the number of processors I could test on due to it, and the\n    pipelined efficient implementation was just mimicing MPI-like behavior\n    anyway. If I had to do this again, I would use a combination of MPI and\n    OpenMP, MPI would split the domain over different compute nodes, and OpenMP\n    would internally handle the parallel computation of the fine integrations\n    assigned to that node.\n\\item I ran out of time to test implicit integrators, and how their stability\n  regions functioned. I found it difficult to implement them, since the way I\n  had written my code isolated the actual $f$ of the ODE $u' = f(t,u)$, and\n  thus if I wanted implicit solvers, I had to solve a nonlinear optimization\n  problem, which was too much trouble.\n\\item I wanted to look at generalizations and improvements of parareal, such as\n  PFASST, which takes a spectral deffered corrections approach to the iteration,\n  and another which adapts it to a multigrid scheme, but I ran out of time.\n\\end{itemize}\n", "meta": {"hexsha": "2e1556d239a25f1181375f4c575009b9047897c1", "size": 1959, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Report/TeXsrc/src/conclusion.tex", "max_stars_repo_name": "abhijit-c/Parareal", "max_stars_repo_head_hexsha": "e64c8ae44577da7e92720aa12b12f28acb3fc473", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-08-01T19:31:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-08T13:54:15.000Z", "max_issues_repo_path": "Report/TeXsrc/src/conclusion.tex", "max_issues_repo_name": "abhijit-c/Parareal", "max_issues_repo_head_hexsha": "e64c8ae44577da7e92720aa12b12f28acb3fc473", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Report/TeXsrc/src/conclusion.tex", "max_forks_repo_name": "abhijit-c/Parareal", "max_forks_repo_head_hexsha": "e64c8ae44577da7e92720aa12b12f28acb3fc473", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-09-25T00:02:33.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-25T00:02:33.000Z", "avg_line_length": 61.21875, "max_line_length": 80, "alphanum_fraction": 0.7774374681, "num_tokens": 458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.33789321307329945}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\subsection{The physical effects of Comptonization}\n\n\\marginpar{Thursday\\\\ 2020-8-27, \\\\ compiled \\\\ \\today}\n\nAs we have said it is hard to find numerical solutions to the Kompaneets equation, however there is an interesting quantity whose evolution we can study analytically: the photon energy density. \nThe energy density can be calculated as \n%\n\\begin{align}\nu = \\int \\dd[3]{p} h \\nu \\frac{N}{ \\dd[3]{p}\\dd[3]{x}}\n= \\int \\dd[3]{p} h \\nu   \\frac{2 n}{h^3} \n= \\frac{8 \\pi (k_B T)^{4}}{h^3c^3} \\int_0^{\\infty } \\dd{x} x^3 n\n\\,,\n\\end{align}\n%\nwhere, as usual, \\(x = h \\nu / k_B T\\), and the last equality comes about by substituting this and \\(\\dd[3]{p} = p^2 \\dd{p} \\dd{\\Omega }\\) and assuming isotropy. \n\nIn order to see how it changes in the first stage of the Comptonization, when the photon energy is low compared to the electron temperature, let us differentiate this energy density with respect to time (rescaled, as in the Kompaneets equation, by the mean time between two scatterings): \n%\n\\begin{align}\n\\dv{u}{t_s} \n= \\frac{8 \\pi (k_B T)^{4}}{h^3c^3} \\int_0^{\\infty } \\dd{x} x^3 \\pdv{n}{t_s}\n= \\frac{8 \\pi (k_B T)^{4}}{h^3c^3} \\int_0^{\\infty } \\dd{x} x^3 \\frac{\\Theta}{x^2} \\pdv{}{x} \\qty[x^{4 } (n' + n + n^2)]\n\\marginnote{Used the Kompaneets equation.}\n\\,.\n\\end{align}\n\nNow, let us suppose that \\(n\\) is very small, so that we can neglect \\(n\\) and \\(n^2\\) inside the derivative, keeping \\(n'\\): this yields \n% \\todo[inline]{Not super clear why \\(n \\ll n'\\) if \\(n\\) is small should hold\\dots }\n%\n\\begin{align}\n\\dv{u}{t_s} \\approx \\frac{8 \\pi (k_B T)^{4}}{h^3 c^3} \\Theta \\int_0^{\\infty } \\dd{x} x \\pdv{[x^{4} n']}{x}\n\\,.\n\\end{align}\n\nWe integrate by parts twice and assume that \\(x^{k} n' \\to 0 \\) for \\(k> 3\\): this give us \n%\n\\begin{align}\n\\dv{u}{t_s} \\approx \\frac{8 \\pi (k_B T)^{4}}{h^3 c^3} 4 \\Theta \\int_0^{\\infty } \\dd{x} x^3 n = 4 \\Theta u\n\\,.\n\\end{align}\n\nThe solution to this is an exponential: \n%\n\\begin{align}\nu(t_s) = u(0 ) \\exp( 4 \\Theta t_s) = u(0 ) \\exp( t / t_c )\n\\,,\n\\end{align}\n%\nwhere \\(t_c = 1/ (4 \\Theta n \\sigma _T c)\\) is called the Compton time. \nThis means that the radiative energy density increases \\textbf{exponentially fast}, over a characteristic time of the order \\(t_c\\). \n\n\\todo[inline]{So, to see if I understand correctly: the contributions \\(n + n^2\\) are relevant as we move closer to equilibrium, while the \\(n'\\) term dominates the first stage of the evolution; and the exponential describes the first stage of an evolution which is shaped like some kind of sigmoid?}\n\n\\subsection{Relativistic Kompaneets equation}\n\nWe made the hypotheses that \\(\\Theta \\ll 1\\) and \\(\\epsilon \\ll 1\\) at the start: the electrons and photons were nonrelativistic.\nIf we keep all the other hypotheses (isotropy, homogeneity, small fractional energy change and so on) can we generalize the Kompaneets equation to relativistic particles?\n\nWe will need to use a relativistic Maxwellian (Jüttner distribution) instead of a Maxwellian, and the Klein-Nishina cross section instead of the Thomson one. This will allow us to deal with generic \\(\\Theta \\) and \\(\\epsilon \\): the result is \n%\n\\begin{align}\n\\pdv{n}{t} = \\frac{1}{\\epsilon^2} \\pdv{}{\\epsilon } \\qty[ \\alpha (\\epsilon , \\Theta ) \\qty(\\Theta \\pdv{n}{\\epsilon } + n + n^2)]\n\\,,\n\\end{align}\n%\nwhere \\(\\alpha \\) is a certain known function, \n%\n\\begin{align}\n\\alpha (\\epsilon , \\Theta ) = \\frac{\\epsilon^4}{2 K_2 (1 / \\Theta )} \\int_0^{\\infty } \\dd{z} z^2 \\alpha_0 (\\epsilon z) \\exp( - \\frac{z + 1/z}{2 \\Theta })\n\\,,\n\\end{align}\n%\nwhere \\(\\alpha_0\\) is a known analytical function, whose expression is omitted here. \n\nThe form of the relativistic Kompaneets equation is very similar to the nonrelativistic one. \n\nThe shape of \\(\\alpha \\) is quite similar to \\(\\epsilon^4\\), its nonrelativistic counterpart, for low photon energies; while for high photon energies \\(\\alpha \\) is lower than \\(\\epsilon^4\\). \n\nThe take-away, here, is that if we were to need the relativistic form of the equation we can find it in the literature and apply it to our problem.\n\n\\subsection{The emerging spectrum}\n\nIn astrophysical (non-cosmological) settings we will not find infinite homogeneous media; instead, we need to treat clouds of finite size. \nHowever, we cannot simply use the Kompaneets equation for them.\n\nWhat is the spectrum we expect to observe at infinity? \nLet us suppose we have a source inside a spherical cloud of radius \\(R\\); this source will emit a pulse of radiation at a time \\(t\\), so that the density at a time \\(t_0 \\) is \n%\n\\begin{align}\nn(\\nu , t_0 ) = n_0 (\\nu ) \\delta (t_0  - t )\n\\,.\n\\end{align}\n\nPhotons will propagate and scatter in the cloud, until finally they are emitted and some of them can be observed. What will be the spectral distribution of these? \n\nRoughly speaking, we can express the observed number density as \n%\n\\begin{align}\nn _{\\text{obs}}(\\epsilon ) = \\sum _{i} p_i n(\\epsilon , t_i)\n\\,,\n\\end{align}\n%\nwhere \\(t_i\\) are different times after \\(t_0 \\), \\(n(\\epsilon, t_i)\\) are solutions of the Kompaneets equation at these times, and \\(p_i\\) are the probabilities that a photon emitted at \\(t\\) will exit the cloud at \\(t_i\\).\nProperly speaking this should be an integral, but we are just giving the rough idea. We will turn it into an integral later.\n\nThe escape probability will satisfy \n%\n\\begin{align}\np(t) \\dd{t} = \\frac{ \\dd{n}}{n}\n\\,,\n\\end{align}\n%\nso that it describes the fraction of photons (\\(\\dd{n} / n\\)) which escape the medium in a time \\(\\dd{t}\\). \nThe observed intensity will then be \n%\n\\begin{align}\nn _{\\text{obs}}(\\epsilon ) = \\int_0^{\\infty } p(\\tau) n(\\epsilon , \\tau ) \\dd{\\tau }\n\\,.\n\\end{align}\n\nThe typical timescale for a photon to leave the cloud will be given by the mean number of scatterings times the typical time per scattering: if the medium is assumed to be optically thick we get \n%\n\\begin{align}\nt _{\\text{esc}} \\sim N_s t_s \\sim \\max \\frac{\\qty(\\tau,\\tau^2) }{n \\sigma _T c} \\sim \\frac{\\tau^2 R}{nR \\sigma _T c} \\sim \\frac{\\tau R}{c}\n\\,,\n\\end{align}\n%\nsince \\(n R \\sigma _T = \\tau \\). \nThis result makes sense: it is the light travel time \\(R / c\\) times the optical depth. \n\nThe form of \\(p(t)\\) depends on the shape of the cloud; for example in our spherical cloud we have \n%\n\\begin{align}\np(t) = \\frac{1}{\\tau } \\sum _{n=1}^{\\infty } \\lambda_n \\sin \\lambda_n \\exp( - \\frac{\\lambda _n^2}{3} \\frac{t}{ t _{\\text{esc}}}) \n\\,,\n\\end{align}\n%\nwhere the coefficients \\(\\lambda _n\\) are the solutions of \\(\\tan \\lambda _n  = \\lambda _n / (1 - 3 \\tau / 2)\\). \n\nIt is important to apply this procedure instead of blindly plugging the distribution inside the Kompaneets equation: we know that in that case the photons will eventually thermalize, which is not of physical interest in most situations. \n\n\\subsubsection{Unsaturated Comptonization and power-law tails}\n\nLet us consider a phenomenologically-motivated modified Kompaneets equation, which accounts for the injection and escape of photons in a finite medium: \n%\n\\begin{align}\n\\dot{H} - \\dot{S} = \\frac{\\Theta}{x^2} \\pdv{[x^{4} (n' + n + n^2)]}{x}\n\\,,\n\\end{align}\n%\nwhere \\(\\dot{S} = Q(x)\\) quantifies the photons gained per unit time, while \\(\\dot{H} = n / \\max(\\tau , \\tau^2)\\) quantifies the photons lost per unit time.\n\n\\todo[inline]{Are the signs of the \\(\\dot{S}\\) and \\(\\dot{H}\\) not the other way around?}\n\n\\todo[inline]{How does this work dimensionally? Are \\(\\dot{H}\\) and \\(\\dot{S}\\) not supposed to be inverse times?}\n\nSuppose that the input is \\emph{soft}, that is, low-energy. \nThis means that we will have \\(Q(x)\\) different from zero only for \\(x\\) smaller than a certain threshold, \\(x< x_s \\ll 1\\). \nWe then look at the high-energy tail in emissions, \\(x \\gg 1\\).\n\nWe will neglect the \\(n^2\\) term. The equation  will then read \n%\n\\begin{align}\n0 = \\frac{\\Theta}{x^2} \\pdv{[x^{4}(n' + n)]}{x} + \\underbrace{Q(x) - \\frac{n}{\\max (\\tau , \\tau^2)}}_{\\text{vanish in the high \\(x\\) regime}}\n\\,,\n\\end{align}\n%\nso we are left with \\(n' + n = \\const\\), meaning that \\(n \\sim \\exp(- x)\\). \nThis means that at very high energies the decay of the emission is exponential.\n\n\\todo[inline]{Why does the term proportional to \\(n\\) vanish?}\n\nNow, instead, we look for mid-energy solutions, in the range between the threshold for the emission \\(x_s\\) and 1. We will suppose that \\(x_s \\ll x \\ll 1\\). \nWe will then neglect the \\(n\\) and \\(n^2\\) terms, meaning that we can ignore \\(Q(x)\\) but not the escape term, so we have \n%\n\\begin{align}\n0 = \\frac{\\Theta}{x^2} \\pdv{[x^{4} (n')]}{x} - \\frac{n}{\\max (\\tau , \\tau^2)}\n\\,.\n\\end{align}\n\nIf we take a powerlaw ansatz, \\(n \\propto x^{m}\\), we find that the equation for \\(m\\) becomes \n%\n\\begin{align}\nm(m+3) - \\frac{4}{4 \\Theta \\max (\\tau, \\tau^2)}= 0 \n\\,,\n\\end{align}\n%\nwhere we recognize the Compton parameter \\(4 \\Theta \\max (\\tau , \\tau^2) = y\\), which quantifies how much the scatterings affect the spectrum. \nThe second-order equation for \\(m\\) then becomes \n%\n\\begin{align}\nm = \\frac{-3 \\pm \\sqrt{9 + 16 / y^2}}{2}\n\\,.\n\\end{align}\n\nIf we take the positive solution it will be \\(m_+>0\\), so the spectrum will increase at high energies, which is unphysical. \nSo, we consider the negative solution: expanding the square root under the assumption that \\(y < 1\\)\\footnote{As \\(a\\) and \\(b\\) get further from one another in magnitude, the approximation \\(\\sqrt{a + b} = \\sqrt{a} + \\sqrt{b}\\) gets closer to being true. For small \\(y\\) we have quite a good result, while for \\(y\\) closer to 1 the exponent is slowly-varying anyway.} we get \n%\n\\begin{align}\nm_- \\approx -3 - \\frac{2}{y}\n\\,.\n\\end{align}\n\nThis is then a powerlaw spectrum: for any soft photon input, then, we have found a qualitative result. It is a powerlaw for medium photon energies and an exponential for high photon energies. \nThis then gives a typical signature for the observational spectrum we observe in Compton scattering. \n\nNote that, like in the Planck function, the spectrum of the observed intensity scales like \\(I_\\nu \\sim n \\nu^3\\), so we expect to see \\(I_\\nu \\sim \\nu^{3+m} \\sim \\nu^{-2/y}\\) for medium energies, and \\(I_\\nu \\sim \\nu^3 e^{-x}\\). \n\n\\subsubsection{Dynamical Comptonization}\n\nWe have so far discussed the effects of repeated scattering of photons onto electrons which are moving due to thermal motion. This is however not the only reason electrons may move! \n\nAn interesting situation is one in which the temperature \\(T\\) of the electrons is low, but the bulk velocity of the plasma \\(\\vec{v}\\) is high, so that interaction with photons is still capable of causing inverse Compton scattering. \n\nSuppose we have a flow of electrons moving with a uniform \\(\\vec{v}\\), constant for all of them. Then, the Electron Rest Frame is the same for all the electrons. \n\nSo, in order to deal with the first scattering we must boost to the ERF, but then we are done: we can stay in that frame for all subsequent scatterings. \nThe energy the photon will emerge with will be \\(\\epsilon_2 \\approx \\gamma^2 \\epsilon_1 \\) regardless of the number of scatterings.\n\nIf, on the other hand, the velocity is not uniform we need to insert a relative \\(\\gamma \\) factor for each new electron.\nThis effect will build up for each scattering. \nSo, dynamical Comptonization requires a nonvanishing velocity gradient to work. \n\n\\todo[inline]{He writes \\(\\nabla \\cdot \\vec{v} \\neq 0\\), which is not the same\\dots why would the \\emph{divergence} not vanishing specifically be the condition? what about the curl, or the other components of \\(\\partial_{i} v_j\\) anyway?}\n\nThis is similar to \\emph{second-order Fermi acceleration.}\n\\todo[inline]{what is that?}\n\n\\end{document}", "meta": {"hexsha": "775e172846e5da4faca0b9ea6a20298ec61f40e8", "size": 11640, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ap_second_semester/radiative_processes/apr22.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "ap_second_semester/radiative_processes/apr22.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ap_second_semester/radiative_processes/apr22.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 50.1724137931, "max_line_length": 376, "alphanum_fraction": 0.6945017182, "num_tokens": 3570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.33789320471723494}}
{"text": "\\section{Time scale}\\label{sec:time_scale}\n\nIn Sect. \\ref{subsec:time_definition} we describe the physical time scale and\nthe trade time scale. In Sect. \\ref{subsec:trade_time} and Sect.\n\\ref{subsec:physical_time} we define the trade and the physical time scales,\nrespectively.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Time definition}\\label{subsec:time_definition}\n\nDue to the nature of the data, there are several options to define time for\nanalyzing data. In general, the time series are labeled in calendar time\n(hours, minutes, seconds, milliseconds).Moreover, tick-by-tick data available\non financial markets all over the world are time stamped up to the nanosecond\n\\cite{xetra}, but the order of magnitude of the guaranteed precision is much\nlarger, usually one second or a few hundreds of milliseconds\n\\cite{market_digest,empirical_facts}. In several papers are used different time\ndefinitions (calendar time, physical time, event time, trade time, tick time)\n\\cite{empirical_facts,sampling_returns,market_making}. The spot foreign\nexchange market data used in the analysis only has the quotes. In consequence,\nwe have to infer the trades during the market time. As we have tick-by-tick\nresolution, we can use either trade time scale or physical time scale.\n\nThe trade time scale increases by one unit each time a transaction happens,\nwhich in our case is every time the quotes change. The advantage of this count\nis that limit orders far away in the order book do not increase the time by one\nunit. The main outcome of trade time scale is its ``smoothing\" of data and the\naggregational normality \\cite{empirical_facts}.\n\nThe physical time scale is increased by one unit each time a second passes.\nThis means that computing the responses in this scale involves sampling\n\\cite{Wang_2016_cross,sampling_returns}, which has to be done carefully when\ndealing for example with several stocks with different liquidity. This sampling\nis made in the trade signs and in the midpoint prices.\n\nWe use these two definitions of time scale to compute the price response\nfunction. Between these two scales, there is not a judgment which is better or\nworse.Their use directly depends on the application. Thus, our aim is to\npresent how the price response function behaves under these two different time\nscales.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Trade time scale}\\label{subsec:trade_time}\n\nAs a first approximation, we use the trade sign classification in trade time\nscale proposed in Ref. \\cite{Wang_2016_cross} and used in Refs.\n\\cite{my_paper_response_financial,Wang_2016_avg,Wang_2017,Wang_2018_copulas}\nthat reads\n\\begin{equation}\\label{eq:trade_signs_trade}\n    \\varepsilon^{\\left(\\textrm{t}\\right)}\\left(t,n\\right)=\\left\\{\n    \\begin{array}{cc}\n    \\text{sgn}\\left(m\\left(t,n\\right)-m\\left(t,n-1\\right)\\right),\n    & \\text{if }\\\\ m\\left(t,n\\right) \\ne m\\left(t,n-1\\right)\\\\\n    \\varepsilon^{\\left(\\textrm{t}\\right)}\\left(t,n-1\\right),\n    & \\text{otherwise}\n    \\end{array}\\right..\n\\end{equation}\nHere, $t$ distinguish each second where one or more trades can happen.\n$\\varepsilon^{\\left(\\textrm{t}\\right)}\\left( t,n \\right) = +1$ implies a\ntrade triggered by a market order to buy, and a value\n$\\varepsilon^{\\left(\\textrm{t}\\right)}\\left( t,n \\right) = -1$ indicates a\ntrade triggered by a market order to sell.\n\nIn the second case of Eq. (\\ref{eq:trade_signs_trade}), if two consecutive\ntrades with the same trading direction do not exhaust all the available volume\nat the best quote, the trades would have the same price, and they will thus\nhave the same trade sign.\n\nWith this classification we obtain trade signs for every single trade in the\ndata set. According to Ref. \\cite{Wang_2016_cross}, the average accuracy of the\nclassification is $85\\%$ for the trade time scale.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Physical time scale}\\label{subsec:physical_time}\n\nWe use the trade sign definition in physical time scale proposed in Ref.\n\\cite{Wang_2016_cross} and used in Refs.\n\\cite{Wang_2016_avg,Wang_2017}, that depends on the classification in\nEq. (\\ref{eq:trade_signs_trade}) and reads\n\\begin{equation}\\label{eq:trade_signs_physical}\n    \\varepsilon^{\\left(\\textrm{p}\\right)}\\left(t\\right)=\\left\\{\n    \\begin{array}{cc}\n    \\text{sgn}\\left(\\sum_{n=1}^{N\\left(t\\right)}\n    \\varepsilon^{\\left(\\textrm{t}\\right)} \\left(t,n\\right)\\right),\n    & \\text{If }N \\left(t\\right)>0\\\\\n    0, & \\text{If }N\\left(t\\right)=0\n    \\end{array}\\right. ,\n\\end{equation}\nwhere $N \\left(t \\right)$ is the number of trades in an interval of one second\nfollowing t. Here, $\\varepsilon^{\\left(\\textrm{p}\\right)}\\left( t \\right) = +1$\nimplies that the imbalance of trades in the second $t$ are triggered by a\nmarket order to buy, and a value\n$\\varepsilon^{\\left(\\textrm{p}\\right)}\\left( t \\right) = -1$ indicates an\nimbalance of sell market orders. In this definition, there are two ways to\nobtain $\\varepsilon^{\\left(\\textrm{p}\\right)}\\left( t \\right) = 0$.  First,\nthere are no trades in a particular second and thus no trade sign. Second, the\nsum of the trade signs in a given second amounts to zero, indicating an exact\nbalance of buy and sell market orders.\n\nMarket orders show opposite trade directions as compared to limit orders\nexecuted simultaneously. An executed sell limit order corresponds to a\nbuyer-initiated market order. An executed buy limit order corresponds to a\nseller-initiated market order. In this case we do not compare every single\ntrade sign in a second, but the net trade sign obtained for every second with\nthe definition, see Eq. (\\ref{eq:trade_signs_physical}). According to Ref.\n\\cite{Wang_2016_cross}, this definition has an average accuracy up to $82\\%$ in\nthe physical time scale.\n", "meta": {"hexsha": "5423fe0880529cea67eab57411f128326699f5b7", "size": 5862, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/forex_response_spread_paper/sections/06_time_scale.tex", "max_stars_repo_name": "juanhenao21/forex", "max_stars_repo_head_hexsha": "251ccccfc9a49f546db5e325ea6b594ff035d97f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-01T07:22:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-01T07:22:34.000Z", "max_issues_repo_path": "paper/forex_response_spread_paper/sections/06_time_scale.tex", "max_issues_repo_name": "juanhenao21/forex", "max_issues_repo_head_hexsha": "251ccccfc9a49f546db5e325ea6b594ff035d97f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2020-03-17T09:30:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-27T08:43:29.000Z", "max_forks_repo_path": "paper/forex_response_spread_paper/sections/06_time_scale.tex", "max_forks_repo_name": "juanhenao21/forex", "max_forks_repo_head_hexsha": "251ccccfc9a49f546db5e325ea6b594ff035d97f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 54.2777777778, "max_line_length": 79, "alphanum_fraction": 0.7347321733, "num_tokens": 1532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3378932047172349}}
{"text": "\\input assets/cs-pre\n\\bibliography{assets/references.bib}\n\n\\begin{document}\n\\MYTITLE{CMPSC 383: Multi-Agent and Robotic Systems}{Final Project Progress Report}\n\\MYHEADERS{}\n\n\\section{Introduction}\n    \\textit{Flocking}, in the context of multi-agent systems, involves the collective behavior of a group of interacting, mobile agents. Flocking patterns are exhibited by such a group when the individual agents attempt to move together with their neighbors. This behavior in multi-agent systems mimics the similar flocking behaviors of groups of animals such as birds or fish. Applications of this type of behavior are diverse: multi-robot teams can use flocking to coordinate their movement towards a goal while maintaining a consistent formation or level of proximity~\\cite{saska2014swarms,min2011design}, finding optimized solutions to mathematical problems~\\cite{cui2009boid}, and simulating the behavior and appearance of flocks or swarms of animals.% TODO: more examples\n    \\par Boids particular simulation model for multi-agent flocking behaviour~\\cite{hartman2006autonomous}. It was first described by Craig Reynolds in 1987~\\cite{reynolds1987flocks}. Boids uses a set of three rules for the manipulation: separation, cohesion, and alignment~\\cite{reynolds1987flocks,hartman2006autonomous}. More detail on this model can be found in~\\Cref{boids}. This model has been used in a number of computer graphics applications, including motion pictures and video games, as well as in robotics applications~\\cite{saska2014swarms,min2011design}.\n    \\par Our project is an implementation of this Boids simulation. To do so, we used the Haskell programming language, a purely functional language with lazy evaluation. This document describes some particulars of Haskell and how they relate to the task of agent programming, the details of the mechanism of our implementation, and the results we acquired from our implementation.\n\n\\section{Method}\n\\subsection{Language Choice}\n\nWe chose Haskell as the implementation language for our Boids simulation.\nHaskell is a purely functional language with lazy evaluation~\\cite{hudak1994haskell,jones2003haskell}. It has been observed that Haskell supports the rapid prototyping of software systems, allowing working systems to be implemented quickly and with minimal complexity~\\cite{hudak1994haskell}. The functional programming paradigm in general has been noted to support modularity and allow problems to be decomposed easily~\\cite{hughes1989functional}. These observations, along with our previous experience in the language, influenced our choice of Haskell as a platform for our project.\n\nAs our class experience with implementing multi-agent simulations has been solely through the object-oriented programming (OOP) paradigm, our language choice presented a challenge, but also a valuable learning experience. Our\nimplementation of the Boid agents involves the definition of an abstract data\ntype, which contains the position, velocity, and neighborhood radius of an\nindividual boid. In Haskell, this is defined as follows:\n\\begin{listing}[h!]\n\\begin{minted}{haskell}\ndata Boid = Boid { position :: Point\n                 , velocity :: Vector\n                 , radius   :: Float\n                 }\n\\end{minted}\n\\end{listing}\n\\FloatBarrier\nNote that Haskell, as a purely functional programming language, does not allow mutation of existing values. Therefore, once a\n\\mintinline{haskell}|Boid| is created, it cannot be mutated, and updating the \\mintinline{haskell}|Boid|'s state\nrequires the creation of an entirely new \\mintinline{haskell}|Boid| instance.\n\nAlso, in contrast to a corresponding OOP implementation, which might define some \\mintinline{haskell}|Boid|behaviour (i.e. methods) to accompany this basic data structure, this \\mintinline{haskell}|Boid| data type is kept distinct from the functions which act upon it.. Instead, we define a type called \\mintinline{haskell}|Update|:\n\n\\begin{minted}{haskell}\ntype Update = Boid -> Boid\n\\end{minted}\n\nThus, a function of type \\mintinline{haskell}|Update| is a function that takes a \\mintinline{haskell}|Boid| and returns\na new \\mintinline{haskell}|Boid|. We use \\mintinline{haskell}|Update| to define \\mintinline{haskell}|Behaviour|:\n\n\\begin{minted}{haskell}\ntype Perception = [Boid]\ntype Behaviour = Perception -> Update\n\\end{minted}\n\nThis defines a \\mintinline{haskell}|Behaviour| as a function that maps an agent's perception of its environment (in this case, a \\mintinline{haskell}|Boid|'s visible neighborhood) to\na function for updating its environment. These examples demonstrate how implementing a multi-agent\nsimulation in a purely-functional language requires a different conception of\nwhat it means programmatically for an Agent to behave. \n\n\\subsection{Boids}\\label{boids}\n\nBoids models the behaviour of a flock in as being effected by three primary steering forces: \\textit{cohesion}, the tendency of an individual to stay close to the centre of the flock; \\textit{separation}, the tendency of an individual to avoid collision with other individuals, and \\textit{alignment}, the tendency of an individual to match velocities with its neighbors~\\cite{hartman2006autonomous,reynolds1987flocks}. Each of these steering forces is modeled as a vector, which are then summed to compute the position of a given boid at each time interval.\n\nThe separation steering vector $\\vec{s}_i$ for a given boid $b_i$ may be calculated as the negative sum of the position vector of $b_i$ and each visible boid $b_j$, using the following formula:\n\n\\[ \\vec{s}_i = - \\sum\\limits_{\\forall b_j \\in V_i} (p_i - p_j) \\]\n\nwhere $V_i$ is the set of boids visible by $b_i$ (i.e. the neighborhood)~\\cite{hartman2006autonomous}. In our implementation, this formula corresponds to the following Haskell source code:\n\n\\begin{minted}{haskell}\nseparation :: Boid -> Perception -> Vector\n        -- :: Boid -> [Boid] -> V3 Float\nseparation self neighbors =\n    let p = position self\n    in sumV . map (^-^ p) $ positions neighbors\n\\end{minted}\n\nThe cohesion steering vector $\\vec{k}_i$ for a given boid $b_i$ may be calculated by finding the centre of density $c_i$ of the visible boids $V_i$ using the formula\n\n\\[ c_i = \\sum\\limits_{\\forall b_j \\in V_i} \\frac{p_j}{m} \\]\n\nwhere $m$ is the cardinality of $V_i$. The steering vector may then be calculated by subtracting $b_i$'s position from $c_i$~\\cite{hartman2006autonomous}:\n\n\\[ \\vec{k}_i = c_i - p_i \\]\n\nIn our implementation, these formulae corresponds to the following Haskell source code:\n\n\\begin{minted}{haskell}\ncentre :: Perception -> Vector\n    -- :: [Boid] -> V3 Float\ncentre boids =\n    let m = fromIntegral $ length boids :: Float\n    in sumV $ map (^/ m) $ positions boids\n\ncohesion :: Boid -> Perception -> Vector\n      -- :: Boid -> [Boid] -> V3 Float\ncohesion self neighbors =\n    let p = position self\n    in centre neighbors - p\n\\end{minted}\n\nFinally, the alignment steering vector $\\vec{m}_i$ for a boid $b_i$ may be calculated by averaging the velocities of the set of visible boids $V_i$ using the following formula\n\n\\[ \\vec{m}_i = \\sum\\limits_{\\forall b_j \\in V_i} \\frac{\\vec{v}_j}{m} \\]\n\nwhere $\\vec{v}_j$ is the velocity of $b_j$. If the cardinality of $V_i$ is zero, then $\\vec{v}_i = 0$~\\cite{hartman2006autonomous}. In our implementation, this formula corresponds to the following Haskell source code:\n\n\\begin{minted}{haskell}\nalignment :: Boid -> Perception -> Vector\n       -- :: Boid -> [Boid] -> V3 Float\nalignment _ []        = V3 0 0 0\nalignment _ neighbors =\n    let m = fromIntegral $ length neighbors :: Float\n    in (sumV $ map velocity neighbors) ^/ m\n\\end{minted}\n\nOnce all three steering vectors have been calculated, they are combined to find the velocity $\\vec{v_i\\prime}$ of a boid\n\n\\[ \\vec{v_i\\prime} = \\vec{v_i} + S.\\vec{s_i} + K.\\vec{k_i} + M.\\vec{m_i} \\]\n\nwhere $S$, $K$, and $M$ are coefficients which control the weight of each steering force and are typically global parameters to the simulation.\n\nThe position of that boid at time $t + \\Delta t$ maythen  be updated using $\\vec{v_i\\prime}$\n\n\\[ p\\prime_i = p_i + \\Delta t\\vec{v_i}\\]\n\nIn our implementation, these formulae corresponds to the following Haskell source code:\n\n\\begin{minted}{haskell}\nsteer :: Weights -> Behaviour\n   -- :: Weights -> [Boid] -> Boid -> Boid\nsteer (s, c, m) neighbors self =\n    let s_i  = s *^ separation self neighbors\n        c_i  = c *^ cohesion self neighbors\n        m_i  = m *^ alignment self neighbors\n        v'   = velocity self ^+^ s_i ^+^ c_i ^+^ m_i\n        p    = position self\n        p'   = p ^+^ v'\n    in self { position = p', velocity = v'}\n\\end{minted}\n\n\\subsection{Program Usage}\n\nOur implementation supports a number of command-line arguments to set simulation parameters and control the resulting visualization. The following options for controlling the simulation parameters are supported:\n\n\\begin{description}\n    \\item[Height] of the space can be set using the options \\texttt{-x HEIGHT} or \\texttt{--height=HEIGHT}. \n    \\item[Width] of the space can be set using the options \\texttt{-y WIDTH} or \\texttt{--width=WIDTH}.\n    \\item[Number of Boids] can be  set using the options \\texttt{-n BOIDS} or \\texttt{--num=BOIDS}.\n    \\item[Boid visibility radius] can be set using the options \\texttt{-v RADIUS} or \\texttt{--visibility=RADIUS}. The default is 50.\n    \\item[Simulation speed] can be set using the options \\texttt{-p SPEED} or \\texttt{--speed=SPEED}. This value sets a coefficient by which the movement vector of each boid is divided every simulation tick. The default is 1000 at 30 frames per second.\n\\end{description}\n\nAdditionally, our implementation allows the user to select one of a set of preset behavior types. These control the values of the weight constants for the three boid steering forces, as discussed in \\Cref{boids}.\n\n\\begin{description}\n    \\item[Equal-Weight Behavior] selected with the command-line flag \\texttt{-e} or \\texttt{--equal}, sets all weight coefficients to 1.\n    \\item[Cohesive Behavior] selected with the flag \\texttt{-c} or \\texttt{--cohesive}, sets weights as follows: $S = 1, K = 0.5, M = 0.5$.\n    \\item[Swarming Behavior] selected with the flag \\texttt{-s} or \\texttt{--swarm}, sets the alignment coefficient ($M$) equal to zero, creating true swarming behavior.\n\\end{description}\n\nOur program may also be run in `debug mode,' using the \\texttt{-d} or \\texttt{--debug} option. In debug mode, the program will run the visibility radius and velocity vector of each boid, so that the user can gain a greater understanding of how the simulation functions. Finally, the \\texttt{-h} or \\texttt{--help} flag will print out a summary of the available command-line options.\n\n\\section{Results}\n    \n    The results of this simulation are visible in the following figures:\n    \\begin{itemize}\n        \\item Figure~\\ref{fig:no-debug} demonstrates our simulation without our ``debug-mode''. Of course, as a static image without any representation of boid vectors, it is difficult to tell how the swarm is behaving.\n        \\item Figure~\\ref{fig:eqweight} demonstrates our ``debug mode'' with equal weights for cohesion, separation, and alignment. A large degree of agent clustering is visible.\n        \\item However, with smaller radii as in Figure~\\ref{fig:eqweight-small}, we see a significantly decreased level of clustering of the agents.\n        \\item On the other hand, increasing the radii as in Figure~\\ref{fig:eqweight-large}, gives an even greater degree of clustering than before.\n        \\item With our ``cohesive'' mode, as in Figure~\\ref{fig:eqweight-large}, we see that the boids form a much more even distribution throughout the space. This is due the fact that the separation impulse is still present, but does not dominate the vectors of the boids, preventing them from separating a great distance apart.\n    \\end{itemize}\n    \n    \\begin{figure}\n        \\centering\n        \\includegraphics[width=0.5\\textwidth]{assets/img/nodebug}\n        \\caption{Simulation run in swarm mode, with debugging off.}\n        \\label{fig:no-debug}\n    \\end{figure}\n    \n    \\begin{figure}\n        \\centering\n        \\includegraphics[width=0.5\\textwidth]{assets/img/eqweight}\n        \\caption{Simulation run in equal-weight mode, with debugging and radii of size 20.}\n        \\label{fig:eqweight}\n    \\end{figure}\n    \n    \\begin{figure}\n        \\centering\n        \\includegraphics[width=0.5\\textwidth]{assets/img/eqweight-small}\n        \\caption{Simulation run in equal-weight mode, with debugging and radii of size 10.}\n        \\label{fig:eqweight-small}\n    \\end{figure}\n    \n    \\begin{figure}\n        \\centering\n        \\includegraphics[width=0.5\\textwidth]{assets/img/eqweight-large}\n        \\caption{Simulation run in equal-weight mode, with debugging and radii of size 30.}\n        \\label{fig:eqweight-large}\n    \\end{figure}\n    \n    \\begin{figure}\n        \\centering\n        \\includegraphics[width=0.5\\textwidth]{assets/img/cohesion}\n        \\caption{Simulation run in cohesion mode.}\n        \\label{fig:cohesion}\n    \\end{figure}\n    % describe behavior for each mode\n    \\FloatBarrier\n\\section{Conclusion}\n    \\subsection{Challenges}\n    One of our major challenges was the existence of a bug in the ``alignment'' behavior of our code. This bug caused all boids in the scene to speed up erratically, eventually causing overflow in the vector components of the boids' velocities, and causing the program to crash. This was fixed after we realized that the neighborhood selection code for each boid included the boid itself, and thus added on the boid's own velocity to itself in the alignment function.\n    \\par Another challenge we faced early on was our early ambitions of creating a 3D simulation using the Haskell OpenGL bindings. These bindings caused us a number of problems, and abandoning them in favor of the 2D \\texttt{gloss} library allowed us to focus on the details of our implementation with greater detail. Neither of us is particularly experienced with computer graphics, and we found that the higher level of abstraction provided by \\texttt{gloss} made our task much easier. Furthermore, using OpenGL directly requires writing code that could be considered fairly unidiomatic in Haskell.\n    \n    \\subsection{Takeaways}\n    Both group members enjoyed the experience of implementing a multi-agent system using a purely functional programming language. As Hawk had significantly less experience programming in Haskell than Will, he found this assignment to be a particularly good learning experience in that language, but both members of the team enjoyed the opportunity to try something different than the previous course assignments. Furthermore, we found experimenting with Haskell's libraries for vector mathematics, as necessitated by the boids algorithm, to be interesting and fun.\n    \\par We also enjoyed being able to implement swarming and flocking behavior in a multi-agent system. Our previous experiences with swarming in class had only involved using preexisting programs, so we were interested in how such programs were written. Although Boids is not a particularly complex algorithm, the simulations it produces provide a fairly convincing approximation of real-life bird behavior. Both team members are very interested in `artificial life' simulations in general --- for his first final project in a computer science course at Allegheny, Will wrote an implementation of Conway's Game of Life in Processing. As this project is his last final project for a computer science course here at Allegheny, artificial life provides `book ends,' in a sense, on his Allegheny career.\n\n\\printbibliography\n\n\\end{document}", "meta": {"hexsha": "d8bae0d65448641f6006f940d6d733075d22027e", "size": 15666, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/final_report.tex", "max_stars_repo_name": "yarbroughw/cs383-finalproject", "max_stars_repo_head_hexsha": "fe387499209e9e7ec4b68dda308c16b6cd78ef91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-03-11T19:45:17.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-11T19:45:17.000Z", "max_issues_repo_path": "doc/final_report.tex", "max_issues_repo_name": "yarbroughw/cs383-finalproject", "max_issues_repo_head_hexsha": "fe387499209e9e7ec4b68dda308c16b6cd78ef91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2015-03-12T15:57:02.000Z", "max_issues_repo_issues_event_max_datetime": "2015-04-17T04:22:11.000Z", "max_forks_repo_path": "doc/final_report.tex", "max_forks_repo_name": "yarbroughw/cs383-finalproject", "max_forks_repo_head_hexsha": "fe387499209e9e7ec4b68dda308c16b6cd78ef91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 72.1935483871, "max_line_length": 801, "alphanum_fraction": 0.7526490489, "num_tokens": 3814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3378932047172349}}
{"text": "\\documentclass[runningheads]{llncs}\n\n\\usepackage{graphicx}\n\\usepackage{placeins}\n\\usepackage{hyperref,xcolor}\n\\renewcommand\\UrlFont{\\color{blue}\\rmfamily}\n\\usepackage{listings}\n\\definecolor{very-light-gray}{gray}{0.95}\n\n\\begin{document}\n\n\\title{Solving Combinatorial Puzzles with Parallel Evolutionary Algorithms \\thanks{This work was supported by a private funding of Velbazhd Software LLC.}}\n\\titlerunning{Solving Puzzles with PEA}\n\n\\author{Todor Balabanov\\orcidID{0000-0003-3139-069X} \\and\nStoyan Ivanov \\and\nRumen Ketipov}\n\\authorrunning{T. Balabanov et al.}\n\n\\institute{Institute of Information and Communication Technologies \\\\\nBulgarian Academy of Sciences \\\\\nacad. Georgi Bonchev Str., Block 2, 1113 Sofia, Bulgaria \\\\\n\\email{todorb@iinf.bas.bg} \\\\\n\\url{http://iict.bas.bg/}}\n\n\\maketitle\n\n\\begin{abstract}\nRubik's cube is the most popular combinatorial puzzle. It is well known that solutions of the combinatorial problems are generally hard to find. If 90 degree clockwise rotations of the cube's sides are taken as operations it will give a minimal cube's grammar. By building formal grammar sentences with the usage of the six operations ([L]eft, [R]ight, [T]op, [D]own, [F]ront, [B]ack) all cube's permutations can be achieved. In an evolutionary algorithms (like genetic algorithms for example) set of formal grammar sentences can be represented as population individuals. Single cut point crossover can be efficiently applied when population individuals are strings. Changing randomly selected operation with another randomly selected operation can be used as efficient mutation operator. The most important part of such global optimization is the fitness function. For better individuals fitness value evaluation a combination between Euclidean and Hausdorff distances is proposed in this research. The experiments in this research are done as parallel program written in C++ and Open MPI.\n\n\\keywords{Distributed evolutionary algorithms \\and Combinatorial puzzles \\and Integer optimization.}\n\\end{abstract}\n\n\\section{Introduction}\n\nA parallel implementation of a genetic algorithm-based solver of the Rubik's cube was implemented by Balabanov in \\cite{balabanov01} and it was presented in \\cite{balabanov02}. Rubik's cube was invented and introduced by Erno Rubik in the 70s of the 20th century. After its creation the cube became the most popular combinatorial puzzle all over the world. In its original version it has 3x3x3 cubical segments. There are stickers in six different colors on each subcube square of the exposed sides. Each of the six planes (3x3x1) can be rotated in 90, 180, 270 or 360 degrees, relative to the other part of the puzzle. In the original initial state all sides of the cube are in single color. Scumbling of the puzzle is done by many random rotations of the (3x3x1) sides. The optimization task aims to restore the cube in its original state. Such combinatorial optimization problem is quite difficult because there are billions of combinations. The real number of combinations is $4.3252*10^{19}$ \\cite{korf01} and all of them can be reached from any starting combination. The puzzle is successfully resolved when a sequence of moves is applied such that all subcubes are matched to each other by their color on each side of the cube. According to an estimation in \\cite{korf01} resolutions sequences variate from 50 to 100 moves when the cube is well scrambled. \n\nWhen there is an optimization problem with a sequence of commands it is a perfect candidate for evolutionary algorithms as optimizers. This research addresses the application of parallel genetic algorithms for Rubik's cube optimal or suboptimal solutions findings. The source code of the experiments is written in C++ with OpenMPI for parallel calculations and it can be found in a public source code repository \\cite{balabanov01}. Modification of the evaluation function presented in \\cite{balabanov02} is upgraded by addition of Hausdorff distance component.\n\nThe rest of this paper is organized as follows: Section 2 briefly describes theoretical details. Hence, section 3 presents the proposed modifications into a practical software example and section 4 is devoted to some experiments and results. Finally, Section 5 concludes and presents some ideas for further research.\n\n\\section{Parallel Genetic Algorithms}\n\nGenetic algorithms are global optimization strategy inspired from the evolution process in the Biology theories. Place of the genetic algorithms and the genetic programming in the family of the metaheuristics is well presented in Fig.\\ref{fig02}.\n\n\\begin{figure}\n\\includegraphics[width=1.0\\textwidth,height=0.65\\textwidth]{fig02.png}\n\\centering\n\\caption{Euler diagram of the different classifications of metaheuristics.} \\label{fig02}\n\\end{figure}\n%\\FloatBarrier\n\nSolutions of a particular problem are represented as vectors of values into the solution space. All selected solution vectors are the population of the algorithm. The most common way of initial population establishment is by generation of random vectors. Each new generation appears in the population after recombination of selected individuals. In genetic algorithms recombination is done by two consequent operators - crossover and mutation. Which individuals to participate in the recombination process is decided by application of selection operator. It is very common during selection process elitism rule to be applied. Elitism means that some percent of the best found solutions survive to the real end of the optimization process. Because genetic algorithms based optimization is an iterative optimization a stopping criteria is needed. The most used stopping criteria is initially given number of genetic algorithm generations. \n\nGenetic algorithms are the base of the genetic programming which is used in this research. Each element of the solution vector actually is an operation applied over the state of the Rubik's cube. Ordered set of such instructions is actually an algorithmic program. Because there is no direct intermediate relation between the individuals in a particular population genetic algorithms are highly appropriate for implementation in parallel computing or distributed computing. Population of the genetic algorithm can be easily divided in many sub-population and it can be distributed on many processors/cores or even heterogeneous computers in a cluster. Separation of the global population is the preferred approach, but in cases where only the fitness value calculation is time consuming, population is kept in the central processor/computer and only fitness value calculation is sent to the other contributing processors/computers. \n\nWhen sub-populations distribution calculation scheme is selected some strategy for individual migration should be applied \\cite{balabanov02}. Migration between different islands is needed in order best found solutions to be available in some or in all sub-populations. When the implementation of the calculation is organized as donated distributed computing project in the inclusion of a new remote contributing computer fresh subset of the global population can be supplied. With such strategy solutions space is much better investigated. \n\n\\section{Modified Rubik's Cube Solver}\n\nThe core of the optimization code is Rubik's cube representation into the computer memory. For the needs in this research the cube is presented as six (one for each side) two-dimensional (3x3) arrays. Values in these arrays are integer numbers which correspond to cube's colors. There are better ways for digital representation \\cite{korf01}, but it is much more practical in this way from algorithmic aspect. \n\nData structures are the first side of the modeling proccess. On the second side are the algorithmic operations done over the data structures. The cube has six sides that is why the minimum number of operations over the cube is six. Six capital letters are used for 90 degrees clockwise rotations, as proposed in \\cite{randall01,balabanov02}: \\\\ \n\\\\\nT (Top) –90 degrees clockwise rotation of the top side; \\\\ \nL (Left) –90 degrees clockwise rotation of the left side; \\\\ \nB (Back) –90 degrees clockwise rotation of the back side; \\\\ \nR (Right) –90 degrees clockwise rotation of the right side; \\\\ \nF (Front) –90 degrees clockwise rotation of the front side; \\\\ \nD (Down) –90 degrees clockwise rotation of the down side. \\\\ \n\nThis set of six operations is the minimal fully functional grammar for the Rubik's cube. Extended grammars are also possible, for example if counter-clockwise operators are included (+T, +L, +B, +R, +F, +D, –T, –L, –B, –R, –F, –D). Next level of extension is addition as number of turns (+1T, +2T, +3T, +1L, +2L, +3L, +1B, +2B, +3B, +1R, +2R, +3R, +1F, +2F, +3F, +1D,+2D, +3D, –1T, –2T, –3T, –1L, –2L, –3L, –1B, –2B, –3B, –1R, –2R, –3R, –1F, –2F, –3F, –1D, –2D, –3D) \\cite{balabanov02}.\n\nWith the presented ideas for a formal Rubik's cube grammar the neutral choice is genetic algorithm individuals to be represented as formal grammar sentences with variable length. Each of the letters can appear at any position many times repeated in the chromosome. As it was appointed in \\cite{korf01} the average expected length of the chromosomes can be between 50 and 100.\n\n\\begin{figure}\n\\includegraphics[width=0.75\\textwidth]{fig01.png}\n\\centering\n\\caption{Fitness value evaluation by combination between Euclidean and Hausdorff distance.} \\label{fig01}\n\\end{figure}\n\\FloatBarrier\n\nSingle cut point is selected as crossover population, but other options \\cite{poli01} are also applicable. As mutation operator random change of a single instruction is selected. Selection is done by randomly selected parents, but elitism rule is applied. For the evaluation of the newly created individuals instructions encoded in the individual are applied over the scrambled cube. After that the state of the cube is compared with the target state (cube in the solved state). The listing in Fig.\\ref{fig01} shows the proposed in this paper modification of fitness evaluation function. For each pairs of cube's sides Euclidean distance is calculated. After that according to Hausdorff distance rules the maximum of the minimums is found. Evaluated fitness value is positive because the Euclidean distance is calculated with positive integers (cube's colors are mapped to integers) and the Hausdorff distance is a calculation of a maximum of the minimums. The puzzle is as better solved as the fitness value is smaller. \n\n\\section{Experiments and Results}\n\nAll experiments were done on a single processor desktop machine - Intel Core i5, 2.3 GHz, 2 Cores, 8GB RAM and Mac OS X 10.13.6, Apple LLVM version 9.1.0. For the parallel implementation Open MPI is used.\n\n\\begin{figure}\n\\includegraphics[width=0.75\\textwidth]{fig03.png}\n\\centering\n\\caption{Algorihtm convergence with star topology.} \\label{fig03}\n\\end{figure}\n\\FloatBarrier\n\nExperiments are done in two groups with 30 independent runs for each. The source code originally is divided for test with star topology and incident nodes participation as migration strategies. That is why there are two groups of experiments. Each experiment compares pure Euclidean distance implementation and the proposed Hausdorff distance modification. Parameters of the genetic algorithm are listed in Tab. \\ref{tab01}.\n\n\\begin{table}\n\\caption{Genetic algorithm parameters.}\n\\label{tab01}\n\\begin{tabular}{p{6.9cm}p{4.4cm}}\n\\hline\\noalign{\\smallskip}\n\\textbf{Parameter} & \\textbf{Value} \\\\\n\\hline\\noalign{\\smallskip}\ngeneration gap & 0.93 \\\\\ncrossover rate & 0.98 \\\\\nmutation rate & 0.01 \\\\\nmaximum generations & 10000 \\\\\nnumber of individuals & 37 \\\\\nnumber of variables & floating \\\\\ninserted rate & 100 \\% \\\\\n\\noalign{\\smallskip}\\hline\\noalign{\\smallskip}\n\\end{tabular}\n\\end{table}\n\\FloatBarrier\n\n\\begin{figure}\n\\includegraphics[width=0.75\\textwidth]{fig04.png}\n\\centering\n\\caption{Algorihtm convergence with incident nodes participation.} \\label{fig04}\n\\end{figure}\n\\FloatBarrier\n\nFig.\\ref{fig03} shows that when star topology is used the advantage of Hausdorff modification is not so great, but as it is shown in Fig.\\ref{fig04} when an incident nodes participation is used the proposed modification leads to convergence seep-up. Calculation of a Euclidean distance between two cubes uses six calculations of the sides for the cube (Listing \\ref{lst01}). In the case of Hausdorff distance there are six times more calls of a single Euclidean distance calculation (Listing \\ref{lst02}).\n\n\\begin{lstlisting}[caption={Euclidean distance.},label={lst01},backgroundcolor=\\color{very-light-gray},frame={single}]\ndouble euclidean(const int side1[3][3], \n                 const int side2[3][3]) const {\n  double distance = 0.0;\n\n  for(int i=0; i<3; i++) {\n    for(int j=0; j<3; j++) {\n      distance += (side1[i][j]-side2[i][j]) * \n                  (side1[i][j]-side2[i][j]);\n    }\n  }\n\n  return sqrt(distance);\n}\n\\end{lstlisting}\n\\FloatBarrier\n\n\\begin{lstlisting}[caption={Hausdorff distance.},label={lst02},backgroundcolor=\\color{very-light-gray},frame={single}]\ndouble hausdorff(const RubiksCube &cube) const {\n  double min[] = {INT_MAX, INT_MAX, INT_MAX, \n                  INT_MAX, INT_MAX, INT_MAX};\n\n  for(int s1=0; s1<6; s1++) {\n    for(int s2=0; s2<6; s2++) {\n      double distance = \n      euclidean(*sides[s1], *(cube.sides)[s2]);\n\n      if(min[s1] > distance) {\n        min[s1] = distance;\n      }\n    }\n  }\n\n  double result = min[0];\n  for(int s1=0; s1<6; s1++) {\n    if(result < min[s1]) {\n      result = min[s1];\n    }\n  }\n\n  return(result);\n}\n\\end{lstlisting}\n\\FloatBarrier\n\n\\section{Conclusions}\n\nThe experiments show that the addition of Hausdorff distance component improves the performance of the genetic algorithm. A calculation of the Hausdorff distance is a little bit slower than the calculation of the Euclidean distance, but better solution fitness estimation generally leads to genetic algorithm convergence improvement. Further investigations in the field of the soft computing can be done for the proposed fitness value evaluation as it was done in \\cite{angelova01}.\n\nAs further research it will be interesting an evaluation of the fitness value to be additionally filtered with Kalman filter \\cite{alexandrov01}, for example. Another interesting direction would be an involvement of the artificial neural networks such as \\cite{tashev01,atanasova01} for preliminary solutions evaluation.\n\n\\begin{thebibliography}{8}\n\\bibitem{balabanov01}\nMPI Parallel Implementation of Genetic Algorithm Based Rubik’s Cube Solver, \\url{http://github.com/TodorBalabanov/RubiksCubeGeneticAlgorithmsSolver}. Last accessed 10 Feb 2019\n\\bibitem{balabanov02}\nBalabanov, T., Zankinski, I., Barova, M.: Strategy for Individuals Distribution by Incident Nodes Participation in Star Topology of Distributed Evolutionary Algorithms. Cybernetics and Information Technologies \\textbf{16}(1), 80--88 (2016)\n\\bibitem{korf01}\nKorf, R.: Finding Optimal Solutions to Rubik’s Cube Using Pattern Databases. In: AAAI-98 Proceedings, pp. 700--705. AAAI Press, Menlo Park, CA, USA (1998)\n\\bibitem{randall01}\nRandall, K.: Cilk - Efficient Multithreaded Computing. Doctor of Philosophy Thesis in Computer Science and Engineering, Massachusetts Institute of Technology, USA (1998) \n\\bibitem{poli01}\nPoli, R., Kozak J.: Genetic Programming. In: Burke, EK., Kendall, G. (eds.) Search Methodologies, pp. 143--185. Springer US (2014)\n\\bibitem{angelova01}\nAngelova, V.: Investigations in the Area of Soft Computing Targeted State of the Art Report. Cybernetics and Information Technologies \\textbf{9}(1), 18--24 (2009)\n\\bibitem{alexandrov01}\nAlexandrov, A.: AD HOC Kalman filter based fusion algorithm for real-time Wireless Sensor Data Integration. In: FQAS-2015 Proceedings, pp. 151--160. Springer, Heidelberg (2015)\n\\bibitem{tashev01}\nTashev, T., Hristov, H.: Modeling of synthesis of information processes with generalized nets. Cybernetics and Information Technologies, \\textbf{3}(2), 92--104 (2003) \n\\bibitem{atanasova01}\nAtanasova T., Barova M.: Exploratory analysis of Time Series for hypothesize feature values. In: UniTech17 Proceedings,  \\textbf{16}(2), 399--403 (2017)\n\\end{thebibliography}\n\\end{document}\n", "meta": {"hexsha": "6a5c830203d3621a3873783925d36777f86d8048", "size": 16198, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Solving-Combinatorial-Puzzles-with-Parallel-Evolutionary-Algorithms/paper.tex", "max_stars_repo_name": "TodorBalabanov/Large-Scale-Scientific-Computations-2019", "max_stars_repo_head_hexsha": "c265ba248244c59ab90af608c6b4fcc5cfae77d0", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-01-01T14:41:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-01T14:41:16.000Z", "max_issues_repo_path": "Solving-Combinatorial-Puzzles-with-Parallel-Evolutionary-Algorithms/paper.tex", "max_issues_repo_name": "TodorBalabanov/Large-Scale-Scientific-Computations-2019", "max_issues_repo_head_hexsha": "c265ba248244c59ab90af608c6b4fcc5cfae77d0", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solving-Combinatorial-Puzzles-with-Parallel-Evolutionary-Algorithms/paper.tex", "max_forks_repo_name": "TodorBalabanov/Large-Scale-Scientific-Computations-2019", "max_forks_repo_head_hexsha": "c265ba248244c59ab90af608c6b4fcc5cfae77d0", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 81.8080808081, "max_line_length": 1363, "alphanum_fraction": 0.7841708853, "num_tokens": 3896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.3378931963611703}}
{"text": "\n% This LaTeX was auto-generated from an M-file by MATLAB.\n% To make changes, update the M-file and republish this document.\n\n\n\n    \n    \n      \\subsection{propagated.m}\n\n\\begin{par}\n\\textbf{Summary:} Propagate the state distribution one time step forward            with derivatives\n\\end{par} \\vspace{1em}\n\n\\begin{verbatim}function [Mnext, Snext, dMdm, dSdm, dMds, dSds, dMdp, dSdp] = ...\n  propagated(m, s, plant, dynmodel, policy)\\end{verbatim}\n    \\begin{par}\n\\textbf{Input arguments:}\n\\end{par} \\vspace{1em}\n\\begin{verbatim}m                 mean of the state distribution at time t           [D x 1]\ns                 covariance of the state distribution at time t     [D x D]\nplant             plant structure\ndynmodel          dynamics model structure\npolicy            policy structure\\end{verbatim}\n\\begin{par}\n\\textbf{Output arguments:}\n\\end{par} \\vspace{1em}\n\\begin{verbatim}Mnext             predicted mean at time t+1                         [E x 1]\nSnext             predicted covariance at time t+1                   [E x E]\ndMdm              output mean wrt input mean                         [E x D]\ndMds              output mean wrt input covariance matrix         [E  x D*D]\ndSdm              output covariance matrix wrt input mean        [E*E x  D ]\ndSds              output cov wrt input cov                       [E*E x D*D]\ndMdp              output mean wrt policy parameters                  [E x P]\ndSdp              output covariance matrix wrt policy parameters  [E*E x  P]\\end{verbatim}\n\\begin{verbatim}where P is the number of policy parameters.\\end{verbatim}\n\\begin{par}\nCopyright (C) 2008-2013 by Marc Deisenroth, Andrew McHutchon, Joe Hall, Henrik Ohlsson, and Carl Edward Rasmussen.\n\\end{par} \\vspace{1em}\n\\begin{par}\nLast modified: 2013-01-23\n\\end{par} \\vspace{1em}\n\n\n\\subsection*{High-Level Steps} \n\n\\begin{enumerate}\n\\setlength{\\itemsep}{-1ex}\n   \\item Augment state distribution with trigonometric functions\n   \\item Compute distribution of the control signal\n   \\item Compute dynamics-GP prediction\n   \\item Compute distribution of the next state\n\\end{enumerate}\n\n\\begin{lstlisting}\nfunction [Mnext, Snext, dMdm, dSdm, dMds, dSds, dMdp, dSdp] = ...\n  propagated(m, s, plant, dynmodel, policy)\n\\end{lstlisting}\n\n\n\\subsection*{Code} \n\n\n\\begin{lstlisting}\nif nargout <= 2                                  % just predict, no derivatives\n  [Mnext, Snext] = propagate(m, s, plant, dynmodel, policy);\n  return\nend\n\nangi = plant.angi; poli = plant.poli; dyni = plant.dyni; difi = plant.difi;\n\nD0 = length(m);                                        % size of the input mean\nD1 = D0 + 2*length(angi);          % length after mapping all angles to sin/cos\nD2 = D1 + length(policy.maxU);          % length after computing control signal\nD3 = D2 + D0;                                         % length after predicting\nM = zeros(D3,1); M(1:D0) = m; S = zeros(D3); S(1:D0,1:D0) = s;   % init M and S\n\nMdm = [eye(D0); zeros(D3-D0,D0)]; Sdm = zeros(D3*D3,D0);\nMds = zeros(D3,D0*D0); Sds = kron(Mdm,Mdm);\nX = reshape(1:D3*D3,[D3 D3]); XT = X'; Sds = (Sds + Sds(XT(:),:))/2;\nX = reshape(1:D0*D0,[D0 D0]); XT = X'; Sds = (Sds + Sds(:,XT(:)))/2;\n\n% 1) Augment state distribution with trigonometric functions ------------------\ni = 1:D0; j = 1:D0; k = D0+1:D1;\n[M(k) S(k,k) C mdm sdm Cdm mds sds Cds] = gTrig(M(i), S(i,i), angi);\n\n[S Mdm Mds Sdm Sds] = ...\n  fillIn(S,C,mdm,sdm,Cdm,mds,sds,Cds,Mdm,Sdm,Mds,Sds,[ ],[ ],[ ],i,j,k,D3);\n\nmm=zeros(D1,1); mm(i)=M(i); ss(i,i)=S(i,i)+diag(exp(2*dynmodel.hyp(end,:))/2);\n[mm(k), ss(k,k) C] = gTrig(mm(i), ss(i,i), angi);     % noisy state measurement\nq = ss(j,i)*C; ss(j,k) = q; ss(k,j) = q';\n\n% 2) Compute distribution of the control signal -------------------------------\ni = poli; j = 1:D1; k = D1+1:D2;\n[M(k) S(k,k) C mdm sdm Cdm mds sds Cds Mdp Sdp Cdp] = ...\n  policy.fcn(policy, mm(i), ss(i,i));\n\n[S Mdm Mds Sdm Sds Mdp Sdp] = ...\n  fillIn(S,C,mdm,sdm,Cdm,mds,sds,Cds,Mdm,Sdm,Mds,Sds,Mdp,Sdp,Cdp,i,j,k,D3);\n\n% 3) Compute distribution of the change in state ------------------------------\nii = [dyni D1+1:D2]; j = 1:D2;\nif isfield(dynmodel,'sub'), Nf = length(dynmodel.sub); else Nf = 1; end\nfor n=1:Nf                               % potentially multiple dynamics models\n  [dyn i k] = sliceModel(dynmodel,n,ii,D1,D2,D3); j = setdiff(j,k);\n\n  [M(k) S(k,k) C mdm sdm Cdm mds sds Cds] = dyn.fcn(dyn, M(i), S(i,i));\n\n  [S Mdm Mds Sdm Sds Mdp Sdp] = ...\n    fillIn(S,C,mdm,sdm,Cdm,mds,sds,Cds,Mdm,Sdm,Mds,Sds,Mdp,Sdp,[ ],i,j,k,D3);\n\n  j = [j k];                                   % update 'previous' state vector\nend\n\n% 4) Compute distribution of the next state -----------------------------------\nP = [zeros(D0,D2) eye(D0)]; P(difi,difi) = eye(length(difi));  P = sparse( P);\nMnext = P*M; Snext = P*S*P'; Snext = (Snext+Snext')/2;\n\nPP = kron(P,P);\ndMdm =  P*Mdm; dMds =  P*Mds; dMdp =  P*Mdp;\ndSdm = PP*Sdm; dSds = PP*Sds; dSdp = PP*Sdp;\n\nX = reshape(1:D0*D0,[D0 D0]); XT = X';                          % symmetrize dS\ndSdm = (dSdm + dSdm(XT(:),:))/2; dMds = (dMds + dMds(:,XT(:)))/2;\ndSds = (dSds + dSds(XT(:),:))/2; dSds = (dSds + dSds(:,XT(:)))/2;\ndSdp = (dSdp + dSdp(XT(:),:))/2;\n\n\n% A1) Separate multiple dynamics models ---------------------------------------\n\\end{lstlisting}\n\n\\begin{lstlisting}\nfunction [dyn i k] = sliceModel(dynmodel,n,ii,D1,D2,D3) % separate sub-dynamics\nif isfield(dynmodel,'sub')\n  dyn = dynmodel.sub{n}; do = dyn.dyno; D = length(ii)+D1-D2;\n  if isfield(dyn,'dyni'), di=dyn.dyni; else di=[]; end\n  if isfield(dyn,'dynu'), du=dyn.dynu; else du=[]; end\n  if isfield(dyn,'dynj'), dj=dyn.dynj; else dj=[]; end\n  i = [ii(di) D1+du D2+dj]; k = D2+do;\n  dyn.inputs = [dynmodel.inputs(:,[di D+du]) dynmodel.target(:,dj)];   % inputs\n  dyn.target = dynmodel.target(:,do);                                 % targets\nelse\n  dyn = dynmodel; k = D2+1:D3; i = ii;\nend\n\n% A2) Apply chain rule and fill out cross covariance terms --------------------\nfunction [S Mdm Mds Sdm Sds Mdp Sdp] = ...\n  fillIn(S,C,mdm,sdm,Cdm,mds,sds,Cds,Mdm,Sdm,Mds,Sds,Mdp,Sdp,dCdp,i,j,k,D)\n\nif isempty(k), return; end\n\nX = reshape(1:D*D,[D D]); XT = X';                         % vectorized indices\nI=0*X; I(i,i)=1; ii=X(I==1)'; I=0*X; I(k,k)=1; kk=X(I==1)';\nI=0*X; I(j,i)=1; ji=X(I==1)'; I=0*X; I(j,k)=1; jk=X(I==1)'; kj=XT(I==1)';\n\nMdm(k,:)  = mdm*Mdm(i,:) + mds*Sdm(ii,:);                           % chainrule\nMds(k,:)  = mdm*Mds(i,:) + mds*Sds(ii,:);\nSdm(kk,:) = sdm*Mdm(i,:) + sds*Sdm(ii,:);\nSds(kk,:) = sdm*Mds(i,:) + sds*Sds(ii,:);\ndCdm      = Cdm*Mdm(i,:) + Cds*Sdm(ii,:);\ndCds      = Cdm*Mds(i,:) + Cds*Sds(ii,:);\nif isempty(dCdp) && nargout > 5\n  Mdp(k,:)  = mdm*Mdp(i,:) + mds*Sdp(ii,:);\n  Sdp(kk,:) = sdm*Mdp(i,:) + sds*Sdp(ii,:);\n  dCdp      = Cdm*Mdp(i,:) + Cds*Sdp(ii,:);\nelseif nargout > 5\n  aa = length(k); bb = aa^2; cc = numel(C);\n  mdp = zeros(D,size(Mdp,2)); sdp = zeros(D*D,size(Mdp,2));\n  mdp(k,:)  = reshape(Mdp,aa,[]); Mdp = mdp;\n  sdp(kk,:) = reshape(Sdp,bb,[]); Sdp = sdp;\n  Cdp       = reshape(dCdp,cc,[]); dCdp = Cdp;\nend\n\nq = S(j,i)*C; S(j,k) = q; S(k,j) = q';                           % off-diagonal\nSS = kron(eye(length(k)),S(j,i)); CC = kron(C',eye(length(j)));\nSdm(jk,:) = SS*dCdm + CC*Sdm(ji,:); Sdm(kj,:) = Sdm(jk,:);\nSds(jk,:) = SS*dCds + CC*Sds(ji,:); Sds(kj,:) = Sds(jk,:);\nif nargout > 5\n  Sdp(jk,:) = SS*dCdp + CC*Sdp(ji,:); Sdp(kj,:) = Sdp(jk,:);\nend\n\\end{lstlisting}\n", "meta": {"hexsha": "4a5e3f71c8330e0b6100701d70531a2931a060c7", "size": 7368, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/tex/propagated.tex", "max_stars_repo_name": "SJTUGuofei/pilco-matlab", "max_stars_repo_head_hexsha": "a0b48b7831911837d060617903c76c22e4180d0b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 53, "max_stars_repo_stars_event_min_datetime": "2016-12-17T15:15:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T16:59:27.000Z", "max_issues_repo_path": "doc/tex/propagated.tex", "max_issues_repo_name": "sahandrez/quad_pilco", "max_issues_repo_head_hexsha": "2c99152e3a910d147cd0a52822da306063e6a834", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-24T11:02:23.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-24T11:09:45.000Z", "max_forks_repo_path": "doc/tex/propagated.tex", "max_forks_repo_name": "sahandrez/quad_pilco", "max_forks_repo_head_hexsha": "2c99152e3a910d147cd0a52822da306063e6a834", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 36, "max_forks_repo_forks_event_min_datetime": "2017-04-19T06:55:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-19T10:19:12.000Z", "avg_line_length": 40.262295082, "max_line_length": 114, "alphanum_fraction": 0.5582247557, "num_tokens": 2620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3378823005095238}}
{"text": "\\section{Learning to Optimally Segment Point Clouds}\\label{header-n863}\n\n\\emph{IEEE ROBOTICS AND AUTOMATION LETTERS, VOL. 5, NO. 2, APRIL 2020}\n{[}28{]}\n\n\\subsection{Introduction}\\label{header-n865}\n\nThis letter focuses on the application of autonomous vehicles.\nPerception for autonomous robots presents a series of challenges. First,\nthe right representation of the 3D data obtained by a LiDAR sensor still\nremains an open question. Secondly, contemporary approaches to object\ndetection and scene understanding tend to be closed-world, where the\ntask is predicting 1-of-N possible labels. Finally, practical autonomous\nrobotics makes heavy use of perceptual priors in the forms of geometric\nmaps and assumptions on LiDAR geometry. In this work, the authors focus\non the problem of class-agnostic instance segmentation of LiDAR point\nclouds in an open-world setting.\n\n\\begin{figure}[h!]\n\\centering\n\\includegraphics[width=0.7\\linewidth]{images/pointcloudseg.png}\n\\caption{The class-agnostic instance-level segmentation over all foreground points performed by the proposed method }\n\\end{figure}\n\nThey carefully mix graph-theoretic algorithms with data-driven learning.\nWhile data-driven learning is widely used due to its performance, it is\ndifficult to guarantee good results when processing out-of-sample data\nfrom an open world. The proposed method searches over an exponentially\nlarge space of possible segmentations and returns the one most similar\nto the data-driven point-based model of ``objectness\". First, the search\nis restricted into a subset of segmentations that are consistent with a\nhierarchical grouping of a point cloud sweep. Such hierarchical groups\ncan be readily produced with agglomerative clustering or hierarchical\ngraph-based algorithms. Since that a segmentation algorithm can produce\nan exponentially-large set of segmentations, the authors introduce\nefficient algorithms that search over a space of tree-consistent\nsegmentations and return the one that maximizes a global segmentation\nscore.\n\n\\subsection{Proposed approach}\\label{header-n869}\n\nFor 3D object point segmentation, the input is a 3D point cloud, which\ncontains an \\emph{unknown} number of objects. The goal is to produce a\npoint segmentation, in which every segment contains points from one and\nonly one object.\n\n\\subsubsection{Definitions}\\label{header-n871}\n\nA \\emph{global segmentation} $P_X$ is a partition of a set of points\n$X$ into subsets of points $C_i$ (called local segment), i.e\n$P_X = \\{C_i\\}_{i = 1}^{M}$, where $M$ denotes the number of\nsegments and $C_i \\subset X$. Importantly, every point exists in one\nand only one segment.\n\nThe concept of \\emph{tree-consistent segmentation} is defined as\nfollows. The set of all possible global segmentations on $X$ is\ndefined as $S_X$. Without constraints, the size of $S_X$ is\nexponential but in practice the authors reduce the number of candidates\nby enforcing geometric constraints. All points are grouped\nhierarchically into a tree structure $T_X$. Now, the tree-consistent\nsegmentation is $S_{X,T}$ and contains all possible segmentation\ndefined by the tree $T$. The following figure illustrates the\nrelationship between $S_X$ and $S_{X,T}$.\n\n\\begin{figure}[h!]\n\\centering\n\\includegraphics[width=0.7\\linewidth]{images/treesegment.png}\n\\caption{Tree-consistent segmentation}\n\\end{figure}\n\nAny tree-consistent segmentation from corresponds to a vertex cut set of\nthe tree $T$, i.e. a set of tree nodes, which satisfy the following\nconstraints:\n\n\\begin{itemize}\n\\item\n  for each node in the vertex cut, its ancestor and itself cannot both\n  be in the cut and\n\\item\n  each leaf node must have itself or its ancestor in the cut. \n\\end{itemize}\n\nThe \\emph{segment score} is defined as a function $f(C, \\theta)$,\nwhere $C$ is the segment and $\\theta$ are the function parameters.\n$f$ predicts a given segment's ``objectness\" and can be implemented by\na PointNet++, where $\\theta$ are the network's weights.\n\nThe \\emph{segmentation score} is calculated as the aggregation of the\nscore of all segments in a global segmentation $P_X$. Formally, given\na global segmentation $P_X = \\{Ci\\}^{M}_{i=1}$, its score is\n$F(P_X; \\theta) : PX→ [0, 1]$ by aggregating over local objectness of\nall its segments.\n\n\\subsubsection{Worst-case segmentation}\\label{header-n884}\n\nThe \\emph{worst-case segmentation} score of a global segmentation is the\nworst objectness among its local segments:\n\n$ F_{\\min }(P_X; \\theta) = \\min _i{f(C_i; \\theta)}, i\\in {1 \\ldots M}.$\n\nNow, the optimal worst-case segmentation is\n\n$ P_{X,\\min }^* = \\mathop{\\operatorname{argmax}}\\limits_{P_X\\in S_{X,T}} {F_{\\min } (P_X; \\theta)} $.\n\nIt turns out the problem of finding optimal worst-case segmentation has\noptimal substructure, allowing us to find the global optimum efficiently\nwith dynamic programming (see the following figure).\n\n\\begin{figure}[h!]\n\\centering\n\\includegraphics[width=0.8\\linewidth]{images/worstcaseseg.png}\n\\caption{Optimal worst case segmentation}\n\\end{figure}\n\nThe algorithm starts from the root node $X$ and chooses between a\ncoarse segmentation and a fine one. The fine segmentation will be the\nunion of all $X$`s children's optimal worst-case segmentation, which\ncan be computed recursively. The algorithm would first traverse down to\nthe leaf nodes, representing the finest segmentation. Then it will make\nits way up, during which it finalizes optimal segmentation for each\nintermediate node by making local coarse vs. fine decisions. Eventually,\nit returns to the root node and produces an optimal worst-case global\nsegmentation. This algorithm might not visit all nodes. Instead, it\nskips a sub-trees whenever one sub-tree exhibits a lower score. The\nalgorithm's complexity is linear in $N$ despite the fact that the\nsearch space is exponential in $N$.\n\n\\subsubsection{Average-case segmentation}\\label{header-n892}\n\nAverage-case segmentation score of a global segmentation is the average\nobjectness among its local segments:\n\\newline\n$ F_{\\operatorname{avg}{}}(P_X; \\theta) = \\frac{1}{M} \\sum _{i=1}^M f(C_i; \\theta).$\n\\newline\n$P_{X,\\operatorname{avg}{}}^*$ can be defined as \\emph{optimal\naverage-case segmentation} if\n\\newline\n$ P_{X,\\operatorname{avg}{}}^* = \\mathop{\\operatorname{argmax}}\\limits_{P_X\\in S_{X,T}} {F_{\\operatorname{avg}{}} (P_X; \\theta)}. $\n\\newline\nIt is important to specify that the problem of finding the optimal\naverage-case segmentation does not have optimal substructure, unlike\nworst-case segmentation.\n\n\\subsubsection{Learning the Objectness Function}\\label{header-n898}\n\nUntil now, the segmentation algorithms have been discussed under the\nassumption that the objectness function $f(C; \\theta)$ is defined (it\npredicts an objectness score for a given point cloud). First of all, the\nground-truth function must be defined. Suppose to have the ground truth\nsegmentation $P^{gt} = \\{C_1^{gt},...,C_L^{gt}\\}$. To define the\ntarget objectness of a segment, we have to consider that 3D sensors\n(e.g. LiDAR) tend to produce denser points near the sensor. In\nconsequence, the objectness will be heavily influenced by the\npartitioning of points closer to the sensor. A segment objectness\nfunction of a segment is the largest point between itself and any ground\ntruth segment:\n\\newline\n$ Objectness(C, P^{gt}) = \\max _{l=1,\\ldots,L} \\frac{\\sum _{x \\in C \\cap C^{gt}_l} x^T x }{\\sum _{x \\in C \\cup C^{gt}_l} x^T x }, $\n\\newline\nwhere $x^T x$ represents the squared distance of a point $x$ to\nsensor origin. The authors train a PointNet++ model for learning the\nobjectness function. Each segment is re-sampled to 1024 points.\n\n\\subsubsection{Building tree hierarchies}\\label{header-n902}\n\nThis section explains how to build a tree structure given a set of\npoints $X$. One natural approach is agglomerative clustering, merging\npoints in classes according to their spatial features. This approach\ntends to create tree hierarchies with very fine granularity, e.g. one\nnode may differ from another with only one point of difference. In this\nwork, the authors propose a method which builds a coarser tree whose\nleaf nodes are segments (rather than individual points) and adjacent\nnodes should differ from each other much more. To build such a tree,\nEuclidean Clustering algorithm is used recursively in a top-down fashion\nwith a list of decreasing $\\epsilon$. In the beginning, the algorithm\nis run with the largest $\\epsilon$ value, defining the most coarse\nconnected components. Then, the procedure is repeated a smaller\n$\\epsilon$ within each connected component. This produces a\nmultiple-tree top-down hierarchy.\n\n\\subsection{Experiments}\\label{header-n904}\n\nFor evaluation, the authors repurpose the KITTI object detection\nbenchmark for point cloud segmentation, following the setup in {[}30{]}.\nThe ground truth segmentation is composed of a series of point segments\nmarked with a bounding box. All the background points (those outside the\nbounding box) are removed. To evaluate the performance are considered\ntwo metrics: the \\emph{under-segmentation error} $U$ and the\n\\emph{over-segmentation error} $O$, defined as follows:\n\\newline\n$ U = \\frac{1}{L} \\sum _{l=1}^L \\mathbf {1} \\left(\\frac{|C_{i^*} \\cap C_l^{gt}|}{|C_{i^*}|} < \\tau _U\\right) \\\\ O = \\frac{1}{L} \\sum _{l=1}^L \\mathbf {1} \\left(\\frac{|C_{i^*} \\cap C_l^{gt}|}{|C_l^{gt}|} < \\tau _O\\right)$\n\\newline\nwith\n\\newline\n$ i^* = \\operatorname{argmax}_{i=1}^M{|C_i \\cap C^{gt}_l|}$\n\\newline\nand $\\tau _U, \\tau _O$ as constant thresholds, set to\n$\\frac{2}{3}, 1$.\n\\newline\nThe Euclidean clustering algorithm is applied with an\n$\\epsilon \\in \\{2 m, 1 m, 0.5 m, 0.25 m\\}$. The authors include it as\na baseline to find better solutions. As baselines, other\nstate-of-the-art 3D detectors are included: AVOD, PointPillars,\nPointRCNN, and SECOND. Since these detectors output class-specific\nbounding box detection, the authors simply ignore the class label to\nproduce class-agnostic segmentations. In addition, the authors include\nfor evaluation modified versions of the proposed baselines, in order to\nimprove their performance. A much better approach, called\n\\emph{\\{Detector\\}++} (e.g. AVOD++ etc.), check if the leftover segments\ncan be included in an existing detection segment. Another approach,\nSECOND++, consists of re-train and re-evaluate the best baseline, i.e.\nSECOND, with background removal. These baselines are marked with ``+ BG\nRemoval\". In addition, the authors discover that, by extending the\nSECOND's detection range from 50 m to 80 m, the SECOND's performance is\nsignificantly improved. The affected baselines are marked with ``+ Ext.\nRange\". Finally, they re-train and re-evaluate SECOND on all 8 classes.\nThe new baselines are labeled as ``SECOND++(8)\", while the off-the-shelf\nSECOND baselines are labeled as ``SECOND++(4)\". The following figure\nresumes the results obtained.\n\n\\begin{figure}[h!]\n\\centering\n\\includegraphics[width=1\\linewidth]{images/segmentationerrors.png}\n\\caption{Segmentation errors on the proposed method (*Ours*) and the baselines}\n\\end{figure}\n\nThe table shows that the average-case segmentation, \\emph{Ours(avg)},\nconsistently outperforms the optimal worst-case segmentation\n\\emph{Ours(min)}. \\emph{Ours(min)} produces a much lower\nover-segmentation error but a much higher under-segmentation error,\nsuggesting it makes more mistakes of grouping different objects into one\nsegment and fewer mistakes of splitting points from one single object\ninto multiple segments. The authors label Euclidean Clustering as\n``EC(),\" where $\\epsilon$ represents the distance threshold (meter) and\nconstructs a pool of segments that contains every node (segment) in the\nhierarchy and call this ``EC(all)*\". This serves as an unreachable\nupper-bound. The gap between our proposed method and the upper bound is\nrelatively small (3--4\\%), suggesting plenty of room left for\nimprovement in creating better hierarchies. The confront between a\n\\emph{Detector} algorithm and its variation \\emph{Detector++}, shows\nthat the improved version obtains better performance (see the AVOD's\ncase). SECOND++ performs the best among all Detector++ baselines.\nSECOND++ performs better on common classes such as cars while the\nproposed method perform better on rare ones such as misc. Another\nevaluation metric is measure how objectness generalizes over different\nclasses. The authors apply the learned objectness onto truth segments\nfrom the validation set. The graph below shows the results.\n\n\\begin{figure}[h!]\n\\centering\n\\includegraphics[width=0.8\\linewidth]{images/objectnessgen.png}\n\\caption{Learned objectness generalization}\n\\end{figure}\n\nAs the number of training data decreases dramatically, the average score\ntends to drops slightly and the variance tends to rise slightly. In\nconclusion, the authors prove that their algorithm is guaranteed to\nachieve optimality to a specific definition. On KITTI, the proposed\napproach significantly outperforms past bottom-up approaches and\ntop-down object-based algorithms for segmenting point clouds.", "meta": {"hexsha": "5754a845fb5448428df9fc0056fa78ea4a47c9da", "size": 12966, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "article_8.tex", "max_stars_repo_name": "micheleantonazzi/intelligent-systems", "max_stars_repo_head_hexsha": "521eed39147a4ec22a55dcf7df1b3210bbe8f30b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "article_8.tex", "max_issues_repo_name": "micheleantonazzi/intelligent-systems", "max_issues_repo_head_hexsha": "521eed39147a4ec22a55dcf7df1b3210bbe8f30b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "article_8.tex", "max_forks_repo_name": "micheleantonazzi/intelligent-systems", "max_forks_repo_head_hexsha": "521eed39147a4ec22a55dcf7df1b3210bbe8f30b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.8692307692, "max_line_length": 220, "alphanum_fraction": 0.7788832331, "num_tokens": 3270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3378823005095238}}
{"text": "\\documentclass[a4paper,11pt]{article}\n\\usepackage{graphicx}\n\\usepackage{enumerate}\n\\usepackage[usenames, dvipsnames]{color}\n\n\\begin{document}\n\n\\begin{flushright}\n\n\\vspace{1.1cm}\n\n{\\bf\\Huge Problem Set 10}\n\n\\rule{0.25\\linewidth}{0.5pt}\n\n\\vspace{0.5cm}\n%Put Authors\nJustin Ely\n\\linebreak\n\\newline\n%Put Author's affiliations\n\\footnotesize{605.411 Foundations of Computer Architecture \\\\}\n\\vspace{0.5cm}\n% Date here below\n15 November, 2016\n\\end{flushright}\n\n\\noindent\\rule{\\linewidth}{1.0pt}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section*{1a)}\n\\begin{itemize}\n  \\item A: $time = 5s + \\frac{3145728 \\, bytes \\times s^{-1}}{5120s} = 619.4s$\n  \\item B: $time = 4s + \\frac{3145728 \\, bytes \\times s^{-1}}{3072s} = 1028s$\n\\end{itemize}\n\n\n\\section*{1b)}\n\\begin{eqnarray}\n5 + \\frac{N}{5120} &=& 4 + \\frac{N}{3072} \\\\\n\\frac{N}{5120} &=& -1 + \\frac{N}{3072} \\\\\nN &=& -5120 + \\frac{5N}{3} \\\\\n \\frac{-2N}{3}  &=& -5120 \\\\\n N  &=& 7680 \\, bytes\n\\end{eqnarray} \n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section*{2a)} \nWith a device generating 150 requests per second, and each request requiring 12,000 cycles to handle, the total number of \ncycles per second spent handling interrupts and processing requests will be: \\\\\n\n$150 \\, \\frac{requests}{second} \\times 12,000 \\, cycles = 1,800,000 \\frac{cycles}{second}$. \n\n\\section*{2b)} \nFor just a polling scenario, the CPU will use 500 cycles once every .5ms.  \\\\\n\n$ \\frac{1 \\, poll}{5e^{-4} \\, seconds} \\times 500 \\, cycles= 1,000,000 \\frac{cycles}{second}$\n\n\\section*{2c)} \n\n$ \\frac{1 \\, poll}{N \\, seconds} \\times (500 + 12000)\\, cycles = 1800000 $, thus N = .0069s or 6.9ms.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section*{3a)}\nMemory-mapping implements I/O by allowing peripheral device access through the same address bus as normal memory.  This has the benefit of not needing special I/O commands; rather the same load instruction can be used to access system memory or an external device, at the cost of decreasing the amount of addresses reserved for memory.  Consequently, CPUs are allowed to remain simpler, cheaper, smaller, and faster without the overhead of the extra logic. \n\n\\section*{3b)}\nDMA is an improvement over CPU programmed I/O because it requires fewer active CPU cycles to complete memory access.  CPU Programmed I/O requires the CPU to be active during the entire read or write sequence.  With DMA, a device is allowed to directly access memory and bypass the need for the CPU to act as middleman.  In this scheme the CPU is only need at the beginning and end of an access, the rest of the time it is free to perform other functions.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\end{document}\n", "meta": {"hexsha": "e41c7b63606b0c8bb3267131897d5a831d3451ea", "size": 2735, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "JHU/605.411_foundations_architecture/hw10/ely_hw10.tex", "max_stars_repo_name": "justincely/classwork", "max_stars_repo_head_hexsha": "2d2b1882f9141bc5776977a5c7c6a4788ea7bc4f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-16T03:17:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-16T03:17:26.000Z", "max_issues_repo_path": "JHU/605.411_foundations_architecture/hw10/ely_hw10.tex", "max_issues_repo_name": "justincely/classwork", "max_issues_repo_head_hexsha": "2d2b1882f9141bc5776977a5c7c6a4788ea7bc4f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "JHU/605.411_foundations_architecture/hw10/ely_hw10.tex", "max_forks_repo_name": "justincely/classwork", "max_forks_repo_head_hexsha": "2d2b1882f9141bc5776977a5c7c6a4788ea7bc4f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2017-06-13T13:11:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-04T17:04:32.000Z", "avg_line_length": 35.5194805195, "max_line_length": 457, "alphanum_fraction": 0.649725777, "num_tokens": 803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.33783298698328146}}
{"text": " \n\\documentclass[11pt,a4paper]{article}\n% \\renewcommand{\\baselinestretch}{2}\n\n\\input{psfig}\n\\textwidth 17truecm\n\\textheight 24.2truecm\n\\hoffset -1.5truecm\n\\voffset -1.5truecm\n \n\\title{A New Entropy Measure Based on the Wavelet Transform and Noise Modeling}\n\\author{ J.-L. Starck \\\\\nCEA/DSM/DAPNIA, CE-SACLAY, F-91191 Gif sur Yvette Cedex \\\\ [12pt]\nF. Murtagh \\\\\nFaculty of Informatics, University of Ulster, Magee College, \\\\\nLondonderry BT48 7JL, Northern Ireland \\\\ [12pt]\nR. Gastaud \\\\\nCEA/DSM/DAPNIA, CE-SACLAY, F-91191 Gif sur Yvette Cedex}\n\n\n\\begin{document}\n\\maketitle\n\n\\abstract{\nWe present in this paper a new way to measure the information\nin a signal, based on noise modeling. We show that the use of such \nan entropy-related measure leads to good results for signal restoration.}\n  \n\\section{Introduction}\nThe term ``entropy'' term is due to Clausius (1865), and the concept of \nentropy was introduced by Boltzmann into statistical mechanics,\nin order to measure the number of microscopic ways that a given macroscopic\nstate can be realized. Shannon \\cite{shannon48} \nfounded the mathematical theory of\ncommunication when he suggested that the information gained in a \nmeasurement depends on the number of possible outcomes out of \nwhich one is realized. Shannon also suggested that \nthe entropy can be used for maximization of the bits transferred under\na quality constraint. Jaynes \\cite{jaynes57} proposed to use \nthe entropy measure\nfor radio interometric image deconvolution,  in\norder to select in a set of possible solutions that which contains the\nminimum of information, or following his entropy definition, that \nwhich has a maximum entropy. In principle, the solution verifying such \na condition should be the most reliable. A lot of work has been carried out\nin the last 30 years on the use of entropy for the general problem\nof data filtering and deconvolution \n\\cite{ables74,bontekoe94,burg67,frieden75,gull91,narrayan86,pantin96,skilling84_1,\nweir92}. \n\nTraditionally information and entropy are determined from events and the\nprobability of their occurrence.  Signal and noise are basic building-blocks \nof signal and data analysis in the physical sciences.  Instead of the \nprobability of an event, in this work\n we are led to consider the probabilities of our\ndata being either signal or noise. \n\nObserved data $Y$ in the physical sciences \nare generally corrupted by noise, which is often additive and which \nfollows in many cases a Gaussian distribution, a Poisson distribution, or\na combination of both.\n Using Bayes' theorem to evaluate the probability of the \nrealization of the original signal $X$,\nknowing the data $Y$, we have\n\n\\begin{eqnarray}\n \\mathrm{Prob}(X|Y) = \\frac{\\mathrm{Prob}(Y|X).\\mathrm{Prob}(X)}{\\mathrm{Prob}(Y)}\n\\label{eqn_bayes}\n\\end{eqnarray}\n$\\mathrm{Prob}(Y|X)$ is the conditional probability of getting the data \n$Y$ given an original signal $X$, i.e.\\ it represents the distribution \nof the noise. It is given, in the case of uncorrelated Gaussian \nnoise with variance $\\sigma^2$, by:\n\\begin{eqnarray}\n \\mathrm{Prob}(Y|X) = \\mathrm{exp}(-\\sum_{pixels} \\frac{ (Y-X)^2}{2{\\sigma}^2} )\n\\label{eqn_proba}\n\\end{eqnarray}\nThe denominator in  equation \\ref{eqn_bayes} is independent of $X$ and\n is considered as a constant (stationary noise). \n$\\mathrm{Prob(X)}$ is the a priori distribution \nof the solution $X$. In the absence of any information on the solution \n$X$ except its positivity, a possible course of action \nis to derive the probability\nof $X$ from its entropy, which is defined from information theory.\n\nThe main idea of information theory \\cite{shannon48} is to establish\na relation between the received information and the probability of\nthe observed event \\cite{bijaoui84}. If we note ${\\cal I}(E)$ the information\nrelated to the event $E$, and $p$ the probability of this\nevent happening, then we consider that\n\\begin{eqnarray}\n%\\cal{I}(E) =    f(p)       \n{\\cal I}(E) = f(p)\n\\end{eqnarray}\n\nThen we assume the two following principles:\n\\begin{itemize}\n\\item The information is a decreasing function of the probability. This \nimplies that the more information we have, the  less will be the probability \nassociated with one event.\n\\item Additivity of the information. If we have two independent events \n$E_1$ and $E_2$, the information ${\\cal I}(E)$ associated with the happening\nof both is equal\nto the addition of the information of each of them.\n\\begin{eqnarray}\n{\\cal I}(E) = {\\cal I}(E_1) + {\\cal I}(E_2)\n\\end{eqnarray}\n\\end{itemize}\n\nSince $E_1$ (of probability $p_1$) and $E_2$ (of probability $p_2$) are \nindependent, then the probability of both happening is equal to the\nproduct of $p_1$ and $p_2$.  Hence\n\\begin{eqnarray}\nf(p_1 p_2) = f(p_1) + f(p_2) \n\\end{eqnarray}\n\nThen we can say that the information measure is\n\\begin{eqnarray}\n{\\cal I}(E) = k \\ln(p)\n\\end{eqnarray}\nwhere k is a constant. Information must be positive, and $k$\nis generally fixed at $-1$.\n\nAnother interesting measure is the mean information which is denoted\n\\begin{eqnarray}\nH = - \\sum_i p_i \\ln(p_i)\n\\end{eqnarray}\nThis quantity is called the entropy of the system and was established by \nShannon in 1948 \\cite{shannon48}.\n\nThis measure has several properties:\n\\begin{itemize}\n\\item It is maximal when all events have the same probability \n$p_i = 1/ N_e$ ($N_e$ being the number of events), and is equal to \n$\\ln(N_e)$. It is in this \nconfiguration that the system is the most undefined.\n\\item It is minimal when one event is sure. In this case, the system is \nperfectly known, and no information can be added.\n\\item The entropy is a positive, continuous, and symmetric function.\n%\\item The mean information, obtained in two steps, can be added.\n\\end{itemize}\n\nThen if we know the entropy $H$ of the solution (the next section \ndescribes different ways to calculate it), \nwe derive its probability by\n\\begin{eqnarray}\n\\mathrm{Prob}(X) = \\mathrm{exp}(- \\alpha H(X))\n\\label{info_prop}\n\\end{eqnarray}\n\nGiven the data, the most probable image is obtained by maximizing\n$\\mathrm{Prob}(X|Y)$. Taking the logarithm of equation \\ref{eqn_bayes}, we \nthus need to maximize\n\\begin{eqnarray}\n \\ln (\\mathrm{Prob}(X|Y))  = - \\alpha  H(X) + \\ln(\\mathrm{Prob}(Y|X)) - \n\\ln(\\mathrm{Prob}(Y))\n\\end{eqnarray}\nThe last term is a constant and can be omitted.\nThen, in the case of Gaussian noise, the solution is found by minimizing \n\\begin{eqnarray}\nJ(X) = \\sum_{pixels} \\frac{{(Y-X)}^{2}}{2 {\\sigma}^{2}} + {\\alpha} H(X)\n= \\frac{{\\chi}^2}{2} + {\\alpha} H(X)\n\\label{eqn_j1}\n\\end{eqnarray}\nwhich is a linear combination of two terms: the entropy of the signal,\nand a quantity corresponding to ${\\chi}^2$ in statistics measuring the\ndiscrepancy between the data and the predictions of the model.\n$\\alpha$ is a parameter that can be viewed alternatively as \na Lagrangian parameter or a value fixing the relative weight between \nthe goodness-of-fit and the entropy H. \n\nFor the deconvolution problem, the object-data relation is given by the\nconvolution\n\\begin{eqnarray}\nY = P * X\n\\end{eqnarray}\nwhere $P$ is the point spread function, and the solution is found (in the case\nof Gaussian noise) by minimizing\n\\begin{eqnarray}\nJ(X) = \\sum_{pixels} \\frac{{(Y-P*X)}^{2}}{2 {\\sigma}^{2}} + {\\alpha} H(X)\n\\end{eqnarray}\n\nThe way the entropy is defined is fundamental, because from its definition\nwill depend the solution. The next section discusses the different approaches \nwhich have been proposed in the past.\n\n\\section{The concept of entropy}\n\\label{sect_entr}\n\nWe wish to estimate an unknown probability density $p(x)$ of the data.\nA direct approach would be to build up the histogram of values $X(i)$, using\na suitable interval $\\Delta x$, counting up how many times $m_k$ each interval\n$(x_k, x_k + \\Delta x)$ occurs among the N occurrences. Then the probability\nthat a data value belongs to an interval $k$ is $p_k = \\frac{m_k}{N}$, and\neach data value has a probability $p_k$. The entropy is defined by\n\\begin{eqnarray}\nH_s(X) = - \\sum_{k=1}^{m} p_k \\ln(p_k) \n\\end{eqnarray}\nwhere $m$ is the number of intervals.\nThe entropy is minimum and equal to zero when the signal is flat, and\nincreases when we have some fluctuations. Using this entropy in \nequation~\\ref{eqn_j1} for restoration leads to a minimum entropy restoration\n method.\n\nThe trouble with this approach is that, because the number of occurrences is\nfinite, the estimate $p_k$ will be in error by an amount proportional\nto $m_k^{-\\frac{1}{2}}$~\\cite{frieden}. The error becomes significant when\n$m_k$ is small. Furthermore this kind of entropy definition is not\neasy to use for signal restoration, because the gradient of \nequation~\\ref{eqn_j1} is not easy to compute. For these reasons, other\nentropy functions are generally used. The main ones are:\n\\begin{itemize}\n\\item Burg \\cite{burg67}:\n\\begin{eqnarray}\nH_b(X) = -\\sum_{pixels} \\ln(X) \n\\end{eqnarray}\n\\item Frieden \\cite{frieden75}:\n\\begin{eqnarray}\nH_f(X) = -\\sum_{pixels}X \\ln(X)\n\\end{eqnarray}\n\\item Gull and Skilling \\cite{gull91}:\n\\begin{eqnarray}\nH_g(X) = \\sum_{pixels} X - M - X \\ln(X|M)\n\\end{eqnarray}\n\\end{itemize}\nEach of these entropies can be used, and they correspond to different\nprobability distributions that one can associate with \nan image \\cite{narrayan86}.\n(See \\cite{frieden75,skilling84_1,skilling89} for descriptions).\nThe last definition of the entropy has the advantage of having a zero\n maximum when $X$ equals the model $M$, usually taken as a flat image. \nAll of these entropy measures are negative, and maximum when the image is flat.\nThey are negative because an offset term is omitted which has no importance\nfor the minimization of the functional. The fact that we consider that\na signal has maximum information value when it is flat is evidently\na curious way to measure information. The probability of $X$ \nmust be defined by $\\mathrm{Prob}(X) = \\mathrm{exp}(\\alpha H(X))$. The sign has \nbeen inverted\n(see equation~\\ref{info_prop}), which is natural if we want the best\nsolution to be  the smoothest. These three entropies lead to the \nmaximum entropy restoration method, for which the \nsolution is found by minimizing \n(for Gaussian noise)\n\\begin{eqnarray}\nJ(X) = \\sum_{pixels} \\frac{{(Y-X)}^{2}}{2 {\\sigma}^{2}} - {\\alpha} H(X)\n\\label{eqn_j3}\n\\end{eqnarray}\n\nIn 1986, Narayan and Nityanda \\cite{narrayan86} \ncompared several entropy functions,\n and finally \nconcluded by saying that all were comparable if they have good\nproperties, i.e.\\ they enforce positivity, and they have a negative \nsecond derivative which discourages ripple. They showed also that \nresults varied strongly with the background level, and\nthat these entropy functions produced poor results\nfor negative structures, i.e.\\ structures under the background level\n(absorption area in an image, absorption band in a spectrum, etc.), and \ncompact structures in the signal.\nThe Gull and Skilling entropy gives rise to  \nthe difficulty of estimating a model.\nFurthermore it has been shown \\cite{bontekoe94} \nthat the solution was dependent on this choice.\n\nMany studies \\cite{weir92,bontekoe94,pantin96} \nhave been carried out in order to improve the functional to be minimized.\nBut the question which should be raised is: what is a good entropy for \nsignal restoration?\n\nTrying to answer this corresponds to asking what is the information\nin the signal. The entropy should verify the following criteria:\n\\begin{enumerate}\n\\item The information in a flat signal is zero.\n\\item The amount of information in a signal is independent of the background.\n\\item The amount of information is dependent on the noise. A given \nsignal $Y$ ($Y = X + Noise$) doesn't furnish the  same information if \nthe noise is high or small.\n\\item The entropy must work in the same way for a pixel which\nhas a value $B + \\epsilon$ ($B$ being the background), and\nfor a pixel which has a value $B - \\epsilon$.\n\\item The amount of information is dependent on the correlation in the signal.\nIf a signal $S$  presents large features above the noise, it contains\na lot of information. By generating a new set of  data from $S$, by \nrandomly taking the pixel values in $S$, the large features will\nevidently disappear, and this new signal will contain less information.\nBut the pixel values will be the same as in $S$.\n\\end{enumerate}\n\n\\begin{figure}[htb]\n\\centerline{\n\\hbox{\n\\psfig{figure=lenna256.ps,bbllx=1.8cm,bblly=12.9cm,bburx=14.5cm,bbury=25.5cm,width=8cm,height=8cm,clip=}\n\\psfig{figure=scrambled_lenna.ps,bbllx=1.8cm,bblly=12.9cm,bburx=14.5cm,bbury=25.5cm,width=8cm,height=8cm,clip=}\n}}\n\\caption{Lena image (left) and the same data distributed differently (right). \nThese\ntwo images have the same entropy, using any of the standard entropy methods.}\n\\label{fig_lenna}\n\\end{figure}\n\nFigure~\\ref{fig_lenna} shows the Lena image (left), and an image obtained \nby distributing randomly the Lena image pixel values. For someone, who is\nnot involved in image processing, the second image contains less information\nthan the first one. For someone working on image transmission, it is clear\nthat the second image will require more bits for a lossless transmission,\nand from this point of view, he will consider that the second one contains\nmore information. The standard entropy methods produce exactly \nthe same value for both images and, for such methods, both images contain\nthe same amount of information. For data restoration, all fluctuations\ndue to noise are not of interest, and do not contain relevant \ninformation.  From this physical point of view, that is the reason why \nthe standard \ndefinition of entropy seems badly adapted to information measurement \nin signal restoration.\n\n\\section{Entropy from noise modeling}\n \nIn the case of signal restoration, the noise is the main problem. This \nmeans that we should not consider the probability of appearance of \na pixel value in an image, but rather its probability of being due to the\nsignal (or to the noise). \nIf we consider a variable $x$ which follows a probability distribution \n$p(x)$, we\ncan define the information in $x$ by $- \\ln(p(x))$, and a signal $S$ can\nbe considered as a set of individual variables $x_k$ (pixels), each of which \nfollows the same probability distribution. \nThen the information contained in the data \ncan be measured by $- \\sum_{pixel} \\ln(p(x))$. If $x$ follows a Gaussian \ndistribution with zero mean, we have\n\\begin{eqnarray}\nH(X) = \\sum_{pixel} \\frac{x^2}{2 \\sigma^2}\n\\end{eqnarray}\nThe energy gives a good measurement of information. But many of the required\ncriteria are not fulfilled by using such an entropy (correlation between \npixels, background-independent, etc.). It seems difficult to derive\na good probability distribution from the pixel values which fulfill the \nentropy requirements.\n\nThis is not so for transformed data, especially when using  \nthe wavelet transform. \nThis has  already been done, in fact,\nfor finding threshold levels in filtering \nmethods by means of wavelet coefficient thresholding \\cite{starck95}. Thus we \nmust introduce the concept of multiresolution into our entropy.\nWe will now consider that the information contained in some dataset\nis the sum of the information at different resolution levels $j$.\nChoosing the ``\\`a trous'' wavelet transform (see \\cite{starck95} \nfor a description of this wavelet transform algorithm), a signal $S$ can \nbe represented by:\n\\begin{eqnarray}\nS(k) = \\sum_{j=1}^{l} w_j(k) + c_l(k)\n\\end{eqnarray}\nwhere $k$ is the pixel index, $w_j$ are the wavelet coefficients of $S$, $j$ the \nresolution\nlevel, and $c_l$ the smoothed version of $S$. Due to the properties of\nthe wavelet transform, the set $w_j(x)$ for all $x$ has a zero mean. From \nnoise modeling, we can derive the probability distribution in the \nwavelet space of a wavelet coefficient, assuming it is due to the noise. \nThe entropy becomes\n\\begin{eqnarray}\nH(X) = - \\sum_{j=1}^{l}  \\sum_{k=1}^{N} \\ln ( p(w_j(k)))\n\\end{eqnarray}\nFor Gaussian noise, we get\n\\begin{eqnarray}\nH(X) =  \\sum_{j=1}^{l}  \\sum_{k=1}^{N} \\frac{w_j(k)^2}{2 \\sigma_j^2}\n\\end{eqnarray}\nwhere $\\sigma_j$ is the noise at scale $j$. We see that \nthe information is proportional\nto the energy of the wavelet coefficients.\nThe higher a wavelet coefficient, then the lower will be the  probability, and the \nhigher will\nbe the information furnished by this wavelet coefficient. We can see\neasily that this entropy fulfills all the requirements of \nsection~\\ref{sect_entr}.\nIf we consider two signals $S_1$, $S_2$, derived from a third one $S_0$ by \nadding noise:\n\\begin{eqnarray}\nS_1 & = & S_0 + N_1(\\sigma_1) \\\\ \\nonumber\nS_2 & = & S_0 + N_2(\\sigma_2)\n\\end{eqnarray}\nthen we have:\n\\begin{eqnarray}\n\\mbox{if } \\sigma_1 < \\sigma_2 \\mbox{ then } H(S_1) > H(S_2)\n\\end{eqnarray}\nand a flat image has zero entropy. \n\nOur entropy definition is completely dependent on the noise modeling.\nIf we consider a signal $S$, and we assume that the noise is Gaussian, with \na  standard deviation equal to $\\sigma$, we won't measure the same\ninformation compared to  the case when we consider that the noise has \nanother standard deviation\nvalue, or if the noise follows another distribution.\n\n\\begin{figure}[htb]\n\\centerline{\n\\hbox{\n\\psfig{figure=fig_multi_memscale.ps,bbllx=2.5cm,bblly=13cm,bburx=19.5cm,bbury=25.5cm,width=14cm,height=7cm,clip=}\n}}\n\\caption{Multiscale entropy of the Lena image (continuous curve), \nand multiscale\nentropy of the scrambled image (dashed curve).}\n\\label{fig_multi_memscale}\n\\end{figure}\nFigure~\\ref{fig_multi_memscale} shows the information measure at each\nscale for both the Lena image and its scrambled version. The global \ninformation is the addition of the information at each scale. We see\nthat for the scrambled image (dashed curve), the \ninformation-versus-scale \ncurve is flat, while for the unscrambled Lena image,\nit increases with the scale.  \n\n\\section{Signal information and noise information}\n\\subsection{Definition}\nIn the previous section, we have seen how it was possible to measure\nthe information related to a wavelet coefficient. Since the data\nis composed of an original signal and noise, our information measure\nis corrupted by noise. Trying to decompose our information measure\ninto two components, one ($H_S$) corresponding to the non-corrupted part, and\nanother  ($H_N$) to the corrupted part, we have\n\\begin{eqnarray}\nH(X) = H_S(X) + H_N(X)\n\\end{eqnarray}\nWe will define in the following $H_S$ as the signal information, and $H_N$\nas the noise information. It must be clear that noise does not \ncontain any information, and what we call noise information is a quantity\nwhich is measured as information by the multiscale entropy, and which is \nprobably not informative to us.\n\nAs described in the previous section, the information $h$ relative to \na wavelet coefficient $w_j$ is $- \\ln(p(w_j))$. If the wavelet coefficient\nis small, its value can be due to the noise, \nand  $h$ should be assigned to $H_N$.\nIf the wavelet coefficient is high, compared to the noise standard\ndeviation, $h$ cannot be due to the noise, and $h$ should be assigned to $H_S$.\n$h$ can be distributed as $H_N$ or $H_S$ based on  the probability $p_n(w_j)$\nthat the wavelet coefficient is due to noise, or the probability \n$p_s(w_j)$ that it is due to \nsignal.  We have $p_s(w_j) = 1 - p_n(w_j)$. We consider \nthat  $h_n(w_j) = - p_n(w_j) \\ln(p(w_j))$ is\nthe noise information, and \n$h_s(w_j) = - p_s(w_j) \\ln(p(w_j))$ is the signal information. \nHence  signal information and  noise information are defined by\n\\begin{eqnarray}\nH_s(X) & = & \\sum_{j=1}^{l}  \\sum_{k=1}^{N} h_s(w_j(k)) = - \\sum_{j=1}^{l}  \n\\sum_{k=1}^{N} p_s(w_j(k)) \\ln ( p(w_j(k))) \\\\ \\nonumber\nH_n(X) & = & \\sum_{j=1}^{l}  \\sum_{k=1}^{N} h_n(w_j(k)) = - \\sum_{j=1}^{l}  \n\\sum_{k=1}^{N} p_n(w_j(k)) \\ln ( p(w_j(k)))\n\\end{eqnarray}\nFor the Gaussian noise case, we estimate $p_n(w_j)$ that a wavelet \ncoefficient is due to the noise by\n\\begin{eqnarray}\np_n(w_j) = \\mathrm{Prob}(W > \\mid w_j \\mid)  & =  & \\frac{2}{\\sqrt{2 \\pi} \n\\sigma_j} \\int_{\\mid w_j \\mid}^{+\\infty} \\exp(-W^2/2\\sigma^2_j) dW\\\\ \\nonumber\n & = & \\mbox{erfc}(\\frac{\\mid w_j \\mid }{\\sqrt{2}\\sigma_j})\n\\end{eqnarray}\nand\n\\begin{eqnarray}\nH_s(X) &= & \\sum_{j=1}^{l}  \\sum_{k=1}^{N}  \\frac{w_j^2}{2\\sigma_j^2} \n\\mbox{erf}(\\frac{\\mid w_j \\mid }{\\sqrt{2}\\sigma_j}) \\\\ \\nonumber\nH_n(X) &= & \\sum_{j=1}^{l}  \\sum_{k=1}^{N}  \\frac{w_j^2}{2\\sigma_j^2} \n\\mbox{erfc}(\\frac{\\mid w_j \\mid }{\\sqrt{2}\\sigma_j}) \n\\label{eq_entrop_result_1} \n\\end{eqnarray}\n\nNote that $H_s(X) + H_n(X)$ is always equal to $H(X)$. \nFor Gaussian noise, the functional to minimize becomes\n\\begin{eqnarray}\nJ(X) = \\sum_{pixels} \\frac{{(Y-X)}^{2}}{2 {\\sigma}^{2}} + {\\alpha} (H_s(X)+H_n(X))\n\\end{eqnarray}\nIf we want to preserve features with high signal-to-noise ratio from the\nregularization, we just omit $H_s(X)$ and we get\n\\begin{eqnarray}\nJ(X) = \\sum_{pixels} \\frac{{(Y-X)}^{2}}{2 {\\sigma}^{2}} + {\\alpha} H_n(X)\n\\end{eqnarray}\nWe seek a solution which minimizes the amount of information which could\nbe due to the noise.\n\nBy this measure, information relative to high wavelet coefficients is  \ncompletely assigned to the signal. This allows us also to exclude\nwavelet coefficients with high signal-to-noise ratio (SNR)\nfrom the regularization.\nIt leads to perfect fit of the solution with the data at scales and\n positions with high SNR. If we want to consider the information due\nto noise, even for significant wavelet coefficients, the noise information\nrelative to a wavelet coefficient is \n\\begin{eqnarray}\nh_n(w_j) =  \\int_{0}^{\\mid w_j \\mid } p_n(u|w_j) (\\frac{\\partial H(x)}{\\partial \nx})_{x=u} du\n\\end{eqnarray}\nwhich gives for Gaussian noise\n\\begin{eqnarray}\nh_n(w_j) =  \\frac{1}{\\sigma_j^2} \\int_{0}^{\\mid w_j \\mid} u \\mbox{ \nerfc}(\\frac{\\mid w_j \\mid -u}{\\sqrt{2} \\sigma_j}) du\n\\label{eqn_hn2}\n\\end{eqnarray}\nand the noise and signal information in a signal are\n\\begin{eqnarray}\nH_s(X) & = & \\sum_{j=1}^{l}  \\sum_{k=1}^{N}  \\frac{1}{\\sigma_j^2} \\int_{0}^{\\mid \nw_j \\mid} u \\mbox{ erf}(\\frac{\\mid w_j \\mid -u}{\\sqrt{2} \\sigma_j}) du \\\\ \n\\nonumber \nH_n(X) & = & \\sum_{j=1}^{l}  \\sum_{k=1}^{N}   \\frac{1}{\\sigma_j^2} \\int_{0}^{\\mid \nw_j \\mid} u \\mbox{ erfc}(\\frac{\\mid w_j \\mid -u}{\\sqrt{2} \\sigma_j}) du  \n\\label{eq_entrop_result_2}\n\\end{eqnarray}\n\nEquations 27 and 32 lead to two\ndifferent ways to regularize a signal. The first requires that we use\nall the information which is furnished in high wavelet coefficients, and \nleads to an exact preservation of the flux in a structure. If the signal\npresents high discontinuities, artifacts can appear in the solution \ndue to the fact that the wavelet coefficients located at the discontinuities\nare not noisy, but have been modified like noise. The second equation \ndoesn't have this drawback, but a part of the flux of a structure\n(compatible with noise amplitude) can be lost in the restoration process. \nIt is however not as effective as in the standard maximum entropy methods.\n\n\\subsection{A new approach for signal restoration}\nThe new  definition of the information contained\nin noisy data can easily lead to a new approach for restoration of images.\n\nThe problem of filtering or restoring data $D$ can be expressed by the \nfollowing: \nWe search for a solution $\\tilde D$ such that the difference between\n$D$ and $\\tilde D$ minimizes the information due to the signal, and \nsuch that  $\\tilde D$ minimizes the information due to the noise. \n\\begin{eqnarray}\nJ(\\tilde D) = H_s(D-\\tilde D) + H_n(\\tilde D)\n\\label{eqn_func1}\n\\end{eqnarray}\nFurthermore, the smoothness of the solution can be controlled by adding\na parameter:\n\\begin{eqnarray}\nJ(\\tilde D) = H_s(D-\\tilde D) + \\alpha H_n(\\tilde D)\n\\label{eqn_func2}\n\\end{eqnarray}\nHere, $\\alpha$ is considered as a constant value, but we can easely \nimagine to have a regularization parameter per scale, or even per wavelet\ncoefficient, depending on the Signal to Noise Ratio of the data. This\ndirection will be investigated in the future.\n   \nThree points must be noted:\n\\begin{itemize}\n\\item The positivity of the solution is not enforced.\n\\item There is no constraint on the flux.\n\\item The last scale of the wavelet transform is not taken into \naccount in this entropy.\n\\end{itemize}\nThe first two points can be easily resolved by introducing strict a priori\n constraints on the solution \\cite{thiebault95}:\n\\begin{eqnarray}\nJ(Z) = H_s(D-{\\cal C}(Z)) + \\alpha H_s({\\cal C}(Z))\n\\end{eqnarray}\nAnd the real solution is evidently $\\tilde D = {\\cal C}(Z)$. \nPositivity and total flux conservation impose\n\\begin{eqnarray}\n{\\cal C}(Z)(x) = \\frac{\\sum_x I(x)}{\\sum_x Z(x)^2} Z(x)^2\n\\end{eqnarray}\nAny other constraint can evidently be introduced into the function ${\\cal C}$.\n\nThere is no constraint to be introduced to cater for the third point above, \nbut this should not be a problem\nif the number of scales we use for the entropy is high enough. Indeed, in\nthis case, the last scale becomes flat, and flux normalization should \ncorrectly fix this level.\n\n\\subsection{Example}\n\\begin{figure}[htb]\n\\centerline{\n\\vbox{\n\\psfig{figure=fig_lit6_mem1.ps,bbllx=2.5cm,bblly=13cm,bburx=19.5cm,bbury=25.5cm,width=16cm,height=9cm}\n}}\n\\caption{Spectrum and filtered spectrum superimposed.}\n\\label{fig_lit6_mem1}\n\\end{figure}\n\n\\begin{figure}[htb]\n\\centerline{\n\\vbox{ \n\\psfig{figure=fig_lit6_mem2.ps,bbllx=2.5cm,bblly=13cm,bburx=19.5cm,bbury=25.5cm,width=16cm,height=10cm}\n}}\n\\caption{Difference (upper part) \nbetween the real spectrum and its smoothed version.\nPart (pixels 400 to 500) of the spectrum (continuous curve), \nwith the filtered spectrum\noverplotted (dashed).}\n\\label{fig_lit6_mem2}\n\\end{figure}\nFigure~\\ref{fig_lit6_mem1} presents a spectrum and the result (overplotted)\nafter filtering using the multiscale entropy. The difference between the\nspectrum and its smoothed version is plotted in \nFigure~\\ref{fig_lit6_mem2} (upper part). \nAs we can see, the residual contains only noise.\nIn order to better see the quality of the smoothing, we have plotted\nonly a part of the spectrum (see lower part of Figure~\\ref{fig_lit6_mem2}),\nand the filtered spectrum superimposed. The absorption lines are not \nmodified using our filtering technique. \n\n\\begin{figure}[h]\n\\centerline{\n\\hbox{\n\\psfig{figure=fig_lenna_g10.ps,bbllx=1.8cm,bblly=12.8cm,bburx=14.5cm,bbury=25.5cm,width=8cm,height=8cm,clip=}\n\\psfig{figure=fig_filmem_g2_lenna.ps,bbllx=1.8cm,bblly=12.8cm,bburx=14.5cm,bbury=25.5cm,width=8cm,height=8cm,clip=}\n}}\n\\caption{Left, Lena + Gaussian noise, right, filtered image .}\n\\label{fig_filter_gauss_noise}\n\\end{figure}\nFigure~\\ref{fig_filter_gauss_noise} (left) shows the Lena image \n(see Figure~\\ref{fig_lenna}) to which Gaussian \nnoise of standard deviation 10 has been added.  Figure~\\ref{fig_filter_gauss_noise} (right) shows \nthe result using equation 32 with a regularization parameter value of 2.  \n\n\\section{Conclusion}\n\nWe have seen that information must be measured from the transformed\ndata, and not from the data itself. This approach has been used in fact\nfor several years in the domain of image compression. Indeed, modern\nimage compression methods consist firstly of  applying a transformation \n(cosine transform for JPEG, wavelet transform, etc.) to the image, and\nthen coding the coefficients obtained. A good transform for\nimage compression is obviously an orthogonal transform because there\nis no redundancy, and the number of pixels is the same as in the original\nimage. The exact number of bits necessary to code the coefficients is\ngiven by the Shannon entropy. For signal restoration, the problem is\nnot to reduce the number of bits in the representation of the data, and we\nprefer to use a non-orthogonal wavelet transform, which avoids\nartifacts in reconstruction due to undersampling. \n\nWe could\nhave used the Shannon entropy to measure the information at a given scale,\nand derive the bins of the histogram from the standard deviation of the noise,\nbut for several reasons we thought it better to directly introduce \nnoise probability into our information measure. \nFirstly, we have seen that this leads, for Gaussian noise, to\na very physical relation between the information and the wavelet coefficients:\ninformation is proportional to the energy of the wavelet coefficients\nnormalized by the standard deviation of the noise. \nSecondly, it works even in the case\nof images with few photons/events (the histograms in this case present a bias).\nWe have seen that the equations are easy to manipulate. \nFinally, experiments have \nconfirmed that this approach gives good results.\nWe have seen also that our new information\nmeasure leads naturally to a new method for signal restoration. \nWe are now experimenting with this method, and working on generalizations to\nother classes of noise.\n\n\\newpage\n\\include{annexA}\n\\include{annexB}\n\n\\begin{thebibliography}{99}\n\\bibitem{ables74} J.G. Ables, {\\it Astronomy and Astrophysics Supplement Series},\n15, 383--393, 1974.\n \n\\bibitem{bijaoui84} A. Bijaoui, {\\it Introduction au \nTraitement Num\\'erique des Images}, Masson, Paris, 1984.\n\n \\bibitem{bijaoui94} A. Bijaoui, J.L. Starck and \n F. Murtagh, ``Restauration des \n images\n multi-\\'echelles par l'algorithme \\`a trous'', {\\it Traitement du Signal},\n 11, 229--243, 1994.\n\n\\bibitem{bontekoe94} Tj.R. Bontekoe, E. Koper and D.J.M. Kester,   \n``Pyramid maximum entropy images of IRAS survey data'', {\\it Astronomy and\n Astrophysics}, 294, 1037--1053, 1994.\n\n\\bibitem{burg67} J.P. Burg, {\\it \nAnnual Meeting International Society Exploratory Geophysics}, 1967. \nReprinted in {\\it Modern Spectral Analysis}, 1978, D.G. Childers, ed., \nIEEE Press, New York, 34--41, 1978.\n\n \\bibitem{chui92} C.H. Chui, {\\it Wavelet Analysis and Its \n Applications}, Academic Press, New York, 1992.\n\n \\bibitem{daubechies88} I. Daubechies, \n ``Orthogonal bases of compactly supported \n wavelets'', {\\it Communications on Pure and Applied Mathematics}, \n 41, 909--996, 1988.\n\n\\bibitem {frieden75} B.R. Frieden, ``Image enhancement and restoration'', \n {\\it Topics in Applied Physics}, 6,  Springer-Verlag Berlin, 177--249, 1975.\n\n\\bibitem{frieden} B.R Frieden, {\\it Probability, Statistical Optics, and\nData Testing: a problem solving approach}, 2nd edition, Springer-Verlag Berlin, \n1991.\n\n\\bibitem{jaynes57} E.T. Jaynes, {\\it Phys. Rev.}, 106, 620--630, 1957.\n\n \\bibitem{holschneider89} M. Holschneider, R. Kronland-Martinet, J. Morlet\n and Ph. Tchamitchian, ``A real-time algorithm for signal analysis with the\n help of the wavelet transform'', in \n {\\it Wavelets: Time-Frequency Methods and Phase Space}, \n Springer-Verlag,  Berlin, 286--297, 1989.\n\n\\bibitem{gull91} S.F. Gull, and J. Skilling, MEMSYS5 User's Manual, 1991.\n\n\\bibitem{narrayan86} R. Narayan, and R. Nityananda, ``Maximum \nEntropy Image Restoration in Astronomy'', Ann. Rev. Astron. Astrophys., \n24, pp 127--170, 1986.\n\n\\bibitem{pantin96} E. Pantin and J.L. Starck, ``Deconvolution of \nastronomical images using the multiresolution maximum entropy method'', \n {\\it Astronomy and Astrophysics Supplement Series}, 118, 575--585, 1996. \n\n \\bibitem {ruskai92} M.M. Ruskai, G. Beylkin, R. Coifman, I. Daubechies,\n S. Mallat, Y. Meyer and  L. Raphael, {\\it Wavelets and Their Applications},\n Jones and Barlett, 1992.\n\n\\bibitem{shannon48} C.E. Shannon,  \n``A Mathematical Theory for Communication'', {\\it Bell System Tech J.} 27 \n379--423, 1948.\n\n\\bibitem{shensa92} M.J. Shensa, ``Discrete wavelet transforms:  \n wedding  the \\`a trous and Mallat algorithms\", {\\it IEEE Transactions on \n Signal\n Processing}, 40, 2464--2482, 1992.\n\n\\bibitem{skilling84_1} J. Skilling and S.F. Gull, {\\it Proceedings of \nthe American Mathematical Society}, SIAM, 14, 167, 1984.\n\n\\bibitem{skilling89} J. Skilling, ``Classic maximum entropy'', \nin: Skilling. J, ed., {\\it Maximum \nEntropy and\nBayesian Methods}, Kluwer, Dordrecht, 45--52, 1989. \n\n\\bibitem{starck95}  J.L. Starck, F. Murtagh and  A. Bijaoui, \n``Multiresolution support\n applied to image filtering and deconvolution'', {\\it Graphical\nModels and Image Processing}, 57, 420--431, 1995.\n\n\\bibitem{starck97} J.L. Starck, F. Murtagh  and A. Bijaoui,  \n{\\it Image Processing and Data Analysis: The\nMultiscale Approach},  Cambridge University Press, forthcoming, 1997.\n\n\\bibitem{weir92} N. Weir, ``A multi-channel method of maximum entropy image\nrestoration'', in: D.M. Worral, C. Biemesderfer and J. Barnes, \neds., {\\it Astronomical Data Analysis Software and System 1}, Astronomical \nSociety of the Pacific, San Francisco, 186--190, 1992.\n\n\\bibitem{thiebault95} E. Thiebault and J.-M. Conan, ``Strict a priori\nconstraints for maximum-likelihood blind deconvolution'', {\\it JOSA}, \n12, 485--492, 1995.\n\n\\end{thebibliography}\n\n\n\\end{document}\n\\subsection{Spectrum filtering}\n\n\\subsection{Image filtering}\n\\begin{figure}[h]\n\\centerline{\n\\hbox{\n\\psfig{figure=fig_simu4_bw.ps,bbllx=1.8cm,bblly=12.8cm,bburx=14.5cm,bbury=25.5cm,width=16cm,height=16cm,clip=}\n}}\n\\caption{(a) Simulated image, (b) simulated image and \nGaussian noise, (c) filtered image, and (d)\nresidual image.}\n\\label{fig_filter_gauss_noise}\n\\end{figure}\n\nA simulated image containing stars and galaxies is shown in Fig.\\ \n\\ref{fig_filter_gauss_noise} (top left). The simulated noisy\nimage, the filtered image and the residual image are respectively shown in\nFig.\\ \\ref{fig_filter_gauss_noise} top right, bottom left, and\nbottom right. We can see that there is no structure in the residual \nimage. The filtering was carried out using the multiresolution support.\n\n\n", "meta": {"hexsha": "62d9261a0e08e69c69458b1bf7c1dd0e6af2663a", "size": 33360, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/doc/doc_mra/doc_mr2/entropy_eq.tex", "max_stars_repo_name": "sfarrens/cosmostat", "max_stars_repo_head_hexsha": "a475315cda06dca346095a1e83cb6ad23979acae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/doc/doc_mra/doc_mr2/entropy_eq.tex", "max_issues_repo_name": "sfarrens/cosmostat", "max_issues_repo_head_hexsha": "a475315cda06dca346095a1e83cb6ad23979acae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/doc/doc_mra/doc_mr2/entropy_eq.tex", "max_forks_repo_name": "sfarrens/cosmostat", "max_forks_repo_head_hexsha": "a475315cda06dca346095a1e83cb6ad23979acae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.2684824903, "max_line_length": 115, "alphanum_fraction": 0.751588729, "num_tokens": 9614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.33783297870498263}}
{"text": "In this section we individually present the interpretation and rationale for our solutions.\n\n\\subsection{Question 1}\nQuestion 1 is intended to: \\textit{``Find the top 10 most frequent routes during the last 30 minutes''}.\n\nThis particular query is the same that was asked in the first delivery of this course and the execution was inspired in that same implementation with spark streaming.\n\nAt first we started by translating the coordinates to a 300x300 grid as requested in the question. After that we filter all the invalid coordinates of the new grid since all valid values should be between 0 and 300.\n\nIn order to get the top 10 most frequent areas we run a query which selects the most common coordinate combinations, of pickup and drop off, and their \\textit{count()}, grouped by all the coordinates of a ride, orders them in descending order, of the \\textit{count()}, and limit the top to 10 results.\n\n\n\n\\subsection{Question 2}\n\nQuestion 2 is intended to: \\textit{``Identify areas that are currently most profitable for taxi drivers\"}.\\par\nFor this, we start by dividing the map into a 600x600 grid. To identify the most profitable areas, we divided the profit made in that area by the number of empty taxis.\nFor each area we calculate the average profit in that area, where we consider the sum of fares plus the sum tips (using the aggregation function \\textit{sum}) dividing by the number of trips (using the aggregation function \\textit{count}), in each area in the last 15 minutes.\\par\nTo calculate the number of empty taxis, we selected, for each taxi, its highest dropoff$_-$datetime, in the last 30 minutes, and for each area we count the taxis, using the aggregation function \\textit{count}.\\par\nFor the presentation of results, we sorted by average profit, descending, selecting only the first five results. \n\n\\subsection{Question 3}\nQuestion 3 is intended to: \\textit{``send an alert whenever the average idle time of taxis is greater than 10 minutes''}.\n\nIn our implementation we start by only selecting the medallion, to identify the taxi, and the pickup and drop off times for each event. In this selection we perform a parsing of the string value of the times to a timestamp using ``$time:timestampInMilliseconds(time_-string, format)$'', for example.\n\nNext we use the ``arrow'' (-$>$) logical pattern in order to select the sequence of drop off and pickup times from taxis with the same medallion and use it to calculate the idle time between rides of the same taxi.\n\nAfter that we perform a query over a time batch of 10 seconds so that we can see the results quickly and we select the computed average idle time, calculated with the function \\textit{$avg()$} and we add a \\textit{$having \\ avg_-idle_-time > (10.0*60.0*1000.0)$} so that we only alert when the average idle time exceeds 10 minutes.\n\nAt last at the sink we provide an alert message which says that a 10 minute threshold was exceeded.\n\n\\subsection{Question 4}\n\nQuestion 4 is intended to: \\textit{``Detect congested areas\"}.\\par\nFor this query, as in query 2 we split the map into a 600x600 grid. To identify the most congested areas, we used a logical pattern, selecting the areas that had a sequence of four trips, all increasing in duration, accessing the values in \\textit{trip$_-$time$_-$in$_-$secs}.\\par\nMore details about this query in the Detailed Query Presentation section. \n\n\\subsection{Question 5}\n\nQuestion 5 is intended to: \\textit{``Select the most pleasant taxi drivers\"}.\\par\nFor this query, the solution was quite simple. To select the most pleasant taxi driver, we grouped by taxi driver, adding (using the aggregation function \\textit{sum}) the tips received by the taxi driver on all trips that occurred in the time window. Then, sorting by the tip value in a descending way, just select the taxi driver that is at the top, using \"\\textit{limit 1}\". \n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "07f86e85839f5c16d589034ab0c51b066c572133", "size": 3874, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/queries.tex", "max_stars_repo_name": "ricardojnf/PStr-Project2", "max_stars_repo_head_hexsha": "d936874c309fe0bf92c4d2dcb393bdbe67462dea", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "report/queries.tex", "max_issues_repo_name": "ricardojnf/PStr-Project2", "max_issues_repo_head_hexsha": "d936874c309fe0bf92c4d2dcb393bdbe67462dea", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/queries.tex", "max_forks_repo_name": "ricardojnf/PStr-Project2", "max_forks_repo_head_hexsha": "d936874c309fe0bf92c4d2dcb393bdbe67462dea", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 69.1785714286, "max_line_length": 378, "alphanum_fraction": 0.7764584409, "num_tokens": 893, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.33781787896245397}}
{"text": "\\documentclass[11pt]{article}\n\n\\usepackage{amsmath}\n\\usepackage{listings}\n\\usepackage{hyperref}\n\n\\setlength\\parindent{0pt}\n\n\\begin{document}\n    \\title{HPCSE II - Exercise 4}\n    \\author{Anian Ruoss}\n    \\maketitle\n\n    \\section*{Task 1}\n    \\label{sec:Task1}\n\n    As in Task 2 of Part 2 of Homework 3, we use the head2DSolver to model\n    the temperature distribution on the steel sheets.\n    For every torch we want to determine the optimal beam width, beam\n    intensity and x- and y-coordinates meaning that we have 16 parameters in\n    total for the 4 robotic torches.\n    For all parameters we know the upper and the lower bounds given by:\n    \\begin{itemize}\n        \\item $x \\in [0.0, 0.5]$ for torches 1 and 2\n        \\item $x \\in [0.5, 1.0]$ for torches 3 and 4\n        \\item $y \\in [0.0, 1.0]$ for all torches\n        \\item $\\text{beam intensity} \\in [0.4, 0.6]$ for all torches\n        \\item $\\text{beam width} \\in [0.04, 0.06]$ for all torches\n    \\end{itemize}\n    Since we do not have any additional information about the parameter\n    distributions, we model all parameters as being uniformly distributed\n    within their respective bounds.\n    We employ Korali's CMA-ES solver to maximize the posterior\n    distribution of the parameters (even though we don't really have\n    informative prior distributions, but the posterior was given in the\n    template) to find the most likely parameter values and we display the\n    results in Listing~\\ref{lst:Task1}.\n\n    \\begin{lstlisting}[basicstyle=\\tiny, frame=single, caption={Korali\n    output when maximizing the posterior distribution of the parameters for\n    the model with four robotic torches.}, label={lst:Task1}]\n    [Korali] Starting CMAES. Parameters: 17, Seed: 0xFFFFFFFFFFFFFFFF\n    ...\n    [Korali] Finished - Reason: Object variable changes < 1.00e-06\n    [Korali] Parameter 'Sigma' Value: 0.937023\n    [Korali] Parameter 'torch_1_x' Value: 0.242895\n    [Korali] Parameter 'torch_1_y' Value: 0.240862\n    [Korali] Parameter 'torch_1_intensity' Value: 0.505957\n    [Korali] Parameter 'torch_1_width' Value: 0.046153\n    [Korali] Parameter 'torch_2_x' Value: 0.251464\n    [Korali] Parameter 'torch_2_y' Value: 0.741347\n    [Korali] Parameter 'torch_2_intensity' Value: 0.479662\n    [Korali] Parameter 'torch_2_width' Value: 0.051501\n    [Korali] Parameter 'torch_3_x' Value: 0.757994\n    [Korali] Parameter 'torch_3_y' Value: 0.254470\n    [Korali] Parameter 'torch_3_intensity' Value: 0.474448\n    [Korali] Parameter 'torch_3_width' Value: 0.054619\n    [Korali] Parameter 'torch_4_x' Value: 0.760434\n    [Korali] Parameter 'torch_4_y' Value: 0.770577\n    [Korali] Parameter 'torch_4_intensity' Value: 0.475872\n    [Korali] Parameter 'torch_4_width' Value: 0.059926\n    [Korali] Total Elapsed Time: 234.156253s\n    \\end{lstlisting}\n\n    Korali performs the optimization in roughly 4 minutes.\n    We know from the lecture that CMA-ES is embarrassingly parallel since we\n    can compute and evaluate every sample independently, which can be\n    achieved by parallelizing the two for-loops at lines 11 and 14.\n    Typically the evaluation is a lot more costly than random\n    number generation, which is why we should already observe a considerable\n    speedup from only parallelizing the loop at line 14.\n\n    \\section*{Task 2}\n    \\label{sec:Task2}\n\n    We run the single tasking engine and display its output in\n    Listing~\\ref{lst:Task2Single}.\n\n    \\begin{lstlisting}[basicstyle=\\tiny, frame=single, caption={Output from\n    executing the single tasking engine.}, label={lst:Task2Single}]\n    Processing 240 Samples each with 2 Parameter(s)...\n    Verification Passed\n    Total Running Time: 29.717s\n    \\end{lstlisting}\n\n    \\subsection*{a)}\n    \\label{subsec:Task2a}\n\n    Since all samples are well-known at the beginning, they can be distributed\n    evenly among all ranks and gathered back to one rank once the evaluations\n    are completed.\n    We implement this divide-and-conquer strategy with UPC++ and MPI and\n    display the results obtained from running the implementations with 24\n    ranks on an Euler compute node in listings~\\ref{lst:Task2aUPCXX}\n    and~\\ref{lst:Task2aMPI} respectively.\n\n    \\begin{lstlisting}[basicstyle=\\tiny, frame=single, caption={Output from\n    executing the UPC++ tasking engine with the divide-and-conquer strategy.},\n    label={lst:Task2aUPCXX}]\n    Verification Passed\n    Total time:           1.37665\n    Average time:         1.17792\n    Load imbalance ratio: 0.144362\n    \\end{lstlisting}\n\n    \\begin{lstlisting}[basicstyle=\\tiny, frame=single, caption={Output from\n    executing the MPI tasking engine with the divide-and-conquer strategy.},\n    label={lst:Task2aMPI}]\n    Verification Passed\n    Total time:           1.31242\n    Average time:         1.17451\n    Load imbalance ratio: 0.10508\n    \\end{lstlisting}\n\n    We observe a speedup of $\\approx 21.5$ for UPC++ and $\\approx 22.5$ for\n    MPI and thus we report efficiencies of $\\approx 90\\%$ for UPC++ and\n    $\\approx 94.5\\%$ for MPI.\\@\n    Both implementations suffer from a relatively high load imbalance ratio\n    ($\\approx 0.145$ for UPC++ and $\\approx 0.105$ for MPI) which results\n    from the fluctuation in evaluation times and the static distribution\n    schedule.\n    The MPI approach is practically identical to that employed for the UPC++\n    code but the collective operations in MPI allow for a much cleaner\n    implementation (especially using \\textit{MPI\\_Scatter} since it eliminates\n    the need to care about the global sample index of sample that is processed\n    locally on a given rank).\n    In general, MPI feels more natural since it requires very explicit\n    communication.\n\n    \\subsection*{b)}\n    \\label{subsec:Task2b}\n\n    To solve the load imbalance problem observed in Task 2a) we implement\n    the producer-consumer strategy which takes advantage of the fact that the\n    evaluation times differ and distributes workloads\n    according to rank availability and not according to a fixed scheme.\n    We display the results obtained from running the UPC++ and MPI\n    implementations with 24 ranks on an Euler compute node in\n    listings~\\ref{lst:Task2bUPCXX} and~\\ref{lst:Task2bMPI} respectively.\n\n    \\begin{lstlisting}[basicstyle=\\tiny, frame=single, caption={Output from\n    executing the UPC++ tasking engine with the producer-consumer strategy.},\n    label={lst:Task2bUPCXX}]\n    Processing 240 Samples each with 2 Parameter(s)...\n    Verification Passed\n    Total time:           1.32383\n    Average time:         1.25486\n    Load imbalance ratio: 0.0520984\n    \\end{lstlisting}\n\n    \\begin{lstlisting}[basicstyle=\\tiny, frame=single, caption={Output from\n    executing the MPI tasking engine with the producer-consumer strategy.},\n    label={lst:Task2bMPI}]\n    Verification Passed\n    Total time:           1.32354\n    Average time:         1.24246\n    Load imbalance ratio: 0.0612577\n    \\end{lstlisting}\n\n    We observe for both UPC++ and MPI that the load imbalance ratio drops\n    significantly compared to the divide-and-conquer strategy, although more\n    drastically for UPC++.\n    For UPC++ we observe that the total time decreases slightly compared to\n    the divide-and-conquer strategy (speedup: $\\approx 22.5$, efficiency:\n    $\\approx 93.5\\%$), whereas for the MPI implementation the total running\n    time increases marginally (speedup: $\\approx 22.5$, efficiency:\n    $\\approx 93.5\\%$).\n    We take this as evidence that the UPC++ implementation has successfully\n    solved the load imbalance problem.\n    Even though the load imbalance has also dropped for MPI, the\n    producer-consumer strategy requires a lot more communication which explains\n    the slightly higher running time.\n    The MPI approach differs slightly from the UPC++ approach:\n    \\begin{itemize}\n        \\item UPC++ employs a queue of consumers which contain a future among\n        other data.\n        The producer iterates over the queue and checks whether a RPC has\n        completed before distributing another sample to the idling rank.\n        \\item The MPI implementation does not require a queue as the\n        producer just sends samples and listens for results until all\n        samples have been evaluated.\n        Unlike the UPC++ implementation, we need to explicitly tell every\n        rank that the evaluation has completed once all samples have been\n        processed.\n    \\end{itemize}\n    In general one can say that UPC++ is more suited for the implementation\n    of the producer-consumer problem.\n    Nevertheless, the MPI approach feels cleaner as its communication is more\n    explicit\\footnote{From \\emph{The Zen of Python, by Tim Peters}:\n    ``Explicit is better than implicit.``.}.\n\n    \\section*{Task 3}\n    \\label{sec:Task3}\n\n    We run the single tasking engine and display its output in\n    Listing~\\ref{lst:Task3Single}.\n\n    \\begin{lstlisting}[basicstyle=\\tiny, frame=single, caption={Output from\n    executing the single tasking engine.}, label={lst:Task3Single}]\n    Processing 240 Samples (24 initially available), each with 2 Parameter(s)...\n    Verification Passed\n    Total Running Time: 29.458s\n    \\end{lstlisting}\n\n    Since not all samples are available at the beginning of the generation\n    it does not make sense to have more ranks than initially available\n    samples and we enforce this constraint with an assert.\n    Apart from that our approaches are similar to those from Task 2b) and we\n    display the results obtained from running the UPC++ and MPI\n    implementations with 24 ranks on an Euler compute node in\n    listings~\\ref{lst:Task3UPCXX} and~\\ref{lst:Task3MPI} respectively.\n\n    \\begin{lstlisting}[basicstyle=\\tiny, frame=single, caption={Output from\n    executing the UPC++ tasking engine .},\n    label={lst:Task3UPCXX}]\n    Processing 240 Samples (24 initially available), each with 2 Parameter(s)...\n    Verification Passed\n    Total Running Time: 1.355s\n    \\end{lstlisting}\n\n    \\begin{lstlisting}[basicstyle=\\tiny, frame=single, caption={Output from\n    executing the MPI tasking engine .},\n    label={lst:Task3MPI}]\n    Verification Passed\n    Total Running Time: 1.311s\n    \\end{lstlisting}\n\n    We observe speedups of $\\approx 21.5$ for UPC++ and $\\approx 22.5$ for\n    MPI and correspondingly efficiencies of $\\approx 90.5\\%$ for UPC++ and\n    $\\approx 93.5\\%$ for MPI.\\@\n    For the UPC++ implementation we faced the challenge that\n    \\mbox{\\textit{getSample()}} and \\mbox{\\textit{updateEvaluation()}}\n    have to be called from the root rank and that\n    \\mbox{\\textit{updateEvaluation()}} has to be called after the evaluation\n    has completed on a consumer rank.\n    This problem can be elegantly solved with the \\textit{then()} method\n    from UPC++.\n    Our MPI implementation is basically equivalent to that of Task 2b) and\n    thus we refer to Task 2b) for a discussion of the differences between\n    the UPC++ and MPI approaches.\n    Using the $then()$ function is definitely more elegant than sending data\n    back and forth as is required for MPI.\\@\n\n    \\section*{Task 4}\n    \\label{sec:Task4}\n\n    To exploit full parallelism we increase the population size to 23 since\n    we have 23 consumer ranks and 1 producer rank.\n    We run Korali with the single conduit and display its output in\n    Listing~\\ref{lst:Task4Single}.\n\n    \\begin{lstlisting}[basicstyle=\\tiny, frame=single, caption={Korali\n    output for the single conduit when running the code from Task 1 with\n    population size 23.}, label={lst:Task4Single}]\n    [Korali] Starting CMAES. Parameters: 17, Seed: 0xFFFFFFFFFFFFFFFF\n    ...\n    [Korali] Finished - Reason: Object variable changes < 1.00e-06\n    [Korali] Parameter 'Sigma' Value: 0.937782\n    [Korali] Parameter 'torch_1_x' Value: 0.251375\n    [Korali] Parameter 'torch_1_y' Value: 0.741905\n    [Korali] Parameter 'torch_1_intensity' Value: 0.414076\n    [Korali] Parameter 'torch_1_width' Value: 0.060000\n    [Korali] Parameter 'torch_2_x' Value: 0.242771\n    [Korali] Parameter 'torch_2_y' Value: 0.240310\n    [Korali] Parameter 'torch_2_intensity' Value: 0.435900\n    [Korali] Parameter 'torch_2_width' Value: 0.053473\n    [Korali] Parameter 'torch_3_x' Value: 0.760406\n    [Korali] Parameter 'torch_3_y' Value: 0.770098\n    [Korali] Parameter 'torch_3_intensity' Value: 0.590264\n    [Korali] Parameter 'torch_3_width' Value: 0.048075\n    [Korali] Parameter 'torch_4_x' Value: 0.756812\n    [Korali] Parameter 'torch_4_y' Value: 0.254229\n    [Korali] Parameter 'torch_4_intensity' Value: 0.501190\n    [Korali] Parameter 'torch_4_width' Value: 0.051603\n    [Korali] Total Elapsed Time: 441.061222s\n    \\end{lstlisting}\n\n    Our UPC++ and MPI approaches are very similar to those of tasks 2b) and\n    3 and we display the results obtained from running the UPC++ and MPI\n    implementations with 24 ranks on an Euler compute node in\n    listings~\\ref{lst:Task4UPCXX} and~\\ref{lst:Task4MPI}.\n\n    \\begin{lstlisting}[basicstyle=\\tiny, frame=single, caption={Korali\n    output for the UPC++ conduit when running the code from Task 1 with\n    population size 23.}, label={lst:Task4UPCXX}]\n    [Korali] Starting CMAES. Parameters: 17, Seed: 0xFFFFFFFFFFFFFFFF\n    ...\n    [Korali] Finished - Reason: Object variable changes < 1.00e-06\n    [Korali] Parameter 'Sigma' Value: 0.937782\n    [Korali] Parameter 'torch_1_x' Value: 0.251375\n    [Korali] Parameter 'torch_1_y' Value: 0.741905\n    [Korali] Parameter 'torch_1_intensity' Value: 0.414076\n    [Korali] Parameter 'torch_1_width' Value: 0.060000\n    [Korali] Parameter 'torch_2_x' Value: 0.242771\n    [Korali] Parameter 'torch_2_y' Value: 0.240310\n    [Korali] Parameter 'torch_2_intensity' Value: 0.435900\n    [Korali] Parameter 'torch_2_width' Value: 0.053473\n    [Korali] Parameter 'torch_3_x' Value: 0.760406\n    [Korali] Parameter 'torch_3_y' Value: 0.770098\n    [Korali] Parameter 'torch_3_intensity' Value: 0.590264\n    [Korali] Parameter 'torch_3_width' Value: 0.048075\n    [Korali] Parameter 'torch_4_x' Value: 0.756812\n    [Korali] Parameter 'torch_4_y' Value: 0.254229\n    [Korali] Parameter 'torch_4_intensity' Value: 0.501190\n    [Korali] Parameter 'torch_4_width' Value: 0.051603\n    [Korali] Total Elapsed Time: 21.553523s\n    \\end{lstlisting}\n\n    \\begin{lstlisting}[basicstyle=\\tiny, frame=single, caption={Korali\n    output for the MPI conduit when running the code from Task 1 with\n    population size 23.}, label={lst:Task4MPI}]\n    [Korali] Starting CMAES. Parameters: 17, Seed: 0xFFFFFFFFFFFFFFFF\n    ...\n    [Korali] Finished - Reason: Object variable changes < 1.00e-06\n    [Korali] Parameter 'Sigma' Value: 0.937782\n    [Korali] Parameter 'torch_1_x' Value: 0.251375\n    [Korali] Parameter 'torch_1_y' Value: 0.741905\n    [Korali] Parameter 'torch_1_intensity' Value: 0.414076\n    [Korali] Parameter 'torch_1_width' Value: 0.060000\n    [Korali] Parameter 'torch_2_x' Value: 0.242771\n    [Korali] Parameter 'torch_2_y' Value: 0.240310\n    [Korali] Parameter 'torch_2_intensity' Value: 0.435900\n    [Korali] Parameter 'torch_2_width' Value: 0.053473\n    [Korali] Parameter 'torch_3_x' Value: 0.760406\n    [Korali] Parameter 'torch_3_y' Value: 0.770098\n    [Korali] Parameter 'torch_3_intensity' Value: 0.590264\n    [Korali] Parameter 'torch_3_width' Value: 0.048075\n    [Korali] Parameter 'torch_4_x' Value: 0.756812\n    [Korali] Parameter 'torch_4_y' Value: 0.254229\n    [Korali] Parameter 'torch_4_intensity' Value: 0.501190\n    [Korali] Parameter 'torch_4_width' Value: 0.051603\n    [Korali] Total Elapsed Time: 22.081863s\n    \\end{lstlisting}\n\n    We observe that the results are identical for all three conduits and\n    that UPC++ achieves a speedup of $\\approx 20.5$ with efficiency\n    $\\approx 85.5\\%$ whereas MPI achieves a speedup of $\\approx 20$ with\n    efficiency $\\approx 83\\%$.\n    Both implementations thus exceed the requirement of being at least 10x\n    faster while producing results similar to those of the single conduit,\n    implying that the CEO of the company will give us a raise.\n    As mentioned above, both approaches are similar to those of tasks 2b)\n    and 3 and can thus be easily adapted to the current task.\n    However, for UPC++ we faced the new challenge that the number of\n    parameters is not given as a constant.\n    Consequently, we cannot use the \\textit{Consumer} struct from Task 3 as\n    its sample array would have to be allocated dynamically, which in turn\n    means that \\textit{Consumer} is not trivially copyable anymore.\n    With UPC++ we can solve this problem by simply using the local pointer of\n    the global sampleArrayPointer to access the sample data from every\n    consumer rank.\n    The MPI implementation for this task is basically identical to that of\n    tasks 2b) and 3.\n    For this reason, we refer to Task 2b) for a discussion on the difference\n    between the implementations.\n    As for Task 3, it was relatively easy to adapt the implementations to\n    the current task for both frameworks.\n    The most difficult part of the MPI conduit implementation is the\n    integration with Korali which is described below:\n\n    \\begin{itemize}\n        \\item load the required modules and set the environment variables\n        \\begin{lstlisting}[basicstyle=\\footnotesize]\n    module load new\n    module load gcc/6.3.0\n    module load intel/2018.1\n    module load impi/2018.1.163\n\n    export UPCXX_GASNET_CONDUIT=smp\n    export UPCXX_THREADMODE=seq\n    export UPCXX_CODEMODE=O3\n    export KORALI_CONDUIT=single\n        \\end{lstlisting}\n        \\item replace single.cpp with mpi.cpp\n        \\item replace the Makefile in the conduits directory\n        with this\n        \\href{https://github.com/anianruoss/HPCSE-II/blob/master/exercise04/task1/conduits/Makefile_MPI}{Makefile}\n        \\item replace the Makefile in the task1 directory with this\n        \\href{https://github.com/anianruoss/HPCSE-II/blob/master/exercise04/task1/Makefile_MPI}{Makefile}\n    \\end{itemize}\n\n\\end{document}", "meta": {"hexsha": "c95d4dbfd66da65fb6886254296af99e91b9e745", "size": 17934, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "exercise04/report.tex", "max_stars_repo_name": "anianruoss/HPCSE-II", "max_stars_repo_head_hexsha": "725eb9e0f020b665d83cfb4c55e38d68854cf75b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exercise04/report.tex", "max_issues_repo_name": "anianruoss/HPCSE-II", "max_issues_repo_head_hexsha": "725eb9e0f020b665d83cfb4c55e38d68854cf75b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercise04/report.tex", "max_forks_repo_name": "anianruoss/HPCSE-II", "max_forks_repo_head_hexsha": "725eb9e0f020b665d83cfb4c55e38d68854cf75b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.9476439791, "max_line_length": 114, "alphanum_fraction": 0.718746515, "num_tokens": 5126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.3378178789624539}}
{"text": "\\documentclass[a4paper]{article}\n\\usepackage{amsmath}\n\\usepackage{amsthm}\n\\usepackage{amssymb}\n\\usepackage{amsfonts}\n\\usepackage{graphicx}\n\\usepackage[left=2cm,right=2cm,bottom=2.5cm,top=2.5cm]{geometry}\n\\usepackage{fancyhdr}\n\\usepackage{subcaption}\n\\usepackage{hyperref}\n\\usepackage{enumitem}\n\\usepackage{float}\n\\usepackage{breqn}\n\\usepackage{soul}\n\\setlength{\\headheight}{14.5pt}\n\n%Swap bullets for long dash in itemize\n\t\\renewcommand\\labelitemi{---}\n\t\\renewcommand\\qedsymbol{\\(\\blacksquare\\)}\n\n% Typesets derivatives nicely using roman d. Adapts size automatically. Stolen from https://tex.stackexchange.com/questions/135944/commath-and-ifinner/135985#135985\n% \\od{y}{x} is ordinary derivative, \\pd{f}{x} is partial derivative. See commath documentation for others\n\t\\usepackage{amsmath}\n\t\\newcommand{\\dif}{\\mathop{}\\!\\mathrm{d}}\n\t\\newcommand{\\Dif}{\\mathop{}\\!\\mathrm{D}}\n\n\t\\makeatletter\n\t\\newcommand{\\spx}[1]{%\n\t\t\\if\\relax\\detokenize{#1}\\relax\n\t\t\\expandafter\\@gobble\n\t\t\\else\n\t\t\\expandafter\\@firstofone\n\t\t\\fi\n\t\t{^{#1}}%\n\t}\n\t\\makeatother\n\n\t\\newcommand\\pd[3][]{\\frac{\\partial\\spx{#1}#2}{\\partial#3\\spx{#1}}}\n\t\\newcommand\\tpd[3][]{\\tfrac{\\partial\\spx{#1}#2}{\\partial#3\\spx{#1}}}\n\t\\newcommand\\dpd[3][]{\\dfrac{\\partial\\spx{#1}#2}{\\partial#3\\spx{#1}}}\n\n\t\\newcommand{\\md}[6]{\\frac{\\partial\\spx{#2}#1}{\\partial#3\\spx{#4}\\partial#5\\spx{#6}}}\n\t\\newcommand{\\tmd}[6]{\\tfrac{\\partial\\spx{#2}#1}{\\partial#3\\spx{#4}\\partial#5\\spx{#6}}}\n\t\\newcommand{\\dmd}[6]{\\dfrac{\\partial\\spx{#2}#1}{\\partial#3\\spx{#4}\\partial#5\\spx{#6}}}\n\n\t\\newcommand{\\od}[3][]{\\frac{\\dif\\spx{#1}#2}{\\dif#3\\spx{#1}}}\n\t\\newcommand{\\tod}[3][]{\\tfrac{\\dif\\spx{#1}#2}{\\dif#3\\spx{#1}}}\n\t\\newcommand{\\dod}[3][]{\\dfrac{\\dif\\spx{#1}#2}{\\dif#3\\spx{#1}}}\n\n\t\\newcommand{\\genericdel}[4]{%\n\t\t\\ifcase#3\\relax\n\t\t\\ifx#1.\\else#1\\fi#4\\ifx#2.\\else#2\\fi\\or\n\t\t\\bigl#1#4\\bigr#2\\or\n\t\t\\Bigl#1#4\\Bigr#2\\or\n\t\t\\biggl#1#4\\biggr#2\\or\n\t\t\\Biggl#1#4\\Biggr#2\\else\n\t\t\\left#1#4\\right#2\\fi\n\t}\n\t\\newcommand{\\del}[2][-1]{\\genericdel(){#1}{#2}}\n\t\\newcommand{\\set}[2][-1]{\\genericdel\\{\\}{#1}{#2}}\n\t\\let\\cbr\\set\n\t\\newcommand{\\sbr}[2][-1]{\\genericdel[]{#1}{#2}}\n\t\\let\\intoo\\del\n\t\\let\\intcc\\sbr\n\t\\newcommand{\\intoc}[2][-1]{\\genericdel(]{#1}{#2}}\n\t\\newcommand{\\intco}[2][-1]{\\genericdel[){#1}{#2}}\n\t\\newcommand{\\eval}[2][-1]{\\genericdel.|{#1}{#2}}\n\t\\newcommand{\\envert}[2][-1]{\\genericdel||{#1}{#2}}\n\t\\let\\abs\\envert\n\t\\newcommand{\\sVert}[1][0]{%\n\t\t\\ifcase#1\\relax\n\t\t\\rvert\\or\\bigr|\\or\\Bigr|\\or\\biggr|\\or\\Biggr\n\t\t\\fi\n\t}\n\t\\newcommand{\\enVert}[2][-1]{\\genericdel\\|\\|{#1}{#2}}\n\t\\let\\norm\\enVert\n\t\\newcommand{\\fullfunction}[5]{%\n\t\t\\begin{array}{@{}r@{}r@{}c@{}l@{}}\n\t\t\t#1 \\colon & #2 & {}\\longrightarrow{} & #3 \\\\\n\t\t\t& #4 & {}\\longmapsto{}     & #5\n\t\t\\end{array}\n\t}\n\n\n\\title{Presentation Sketch Script}\n\\author{B. Han, T.M. Hodgson, M. Holden \\& M. Puza}\n\n% Define new commands for typesetting here\n\\newcommand{\\R}{\\mathbb{R}}\n\\renewcommand{\\L}{\\mathcal{L}}\n\\renewcommand{\\P}{\\mathbb{P}}\n%\\renewcommand{\\epsilon}{\\varepsilon}\n\\newcommand{\\e}{\\mathrm{e}}\n\\newcommand{\\grad}{\\nabla}\n\\newcommand{\\E}{\\mathbb{E}}\n\n\\begin{document}\n\\maketitle\n\\section{Introduction}\n``Recent Advances in Langevin Monte Carlo'' \\\\\nThe aim of MCMC is to be able to accurately sample from an unknown probability distribution. When do we not know a distribution?\n \\begin{itemize}\n     \\item Bayesian Statistics, only have some data and an incomplete idea of what the distribution looks like\n     \\item Molecular Dynamics\n \\end{itemize}\n All MCMC methods aim to sample as accurately and efficiently as possible. We will focus on distributions of the form \n \\[\\pi(x) = \\mathcal{Z}^{-1} \\e^{-U(x)}\\]\n This distribution goes by many names as it crops up in many areas:\n \\begin{itemize}\n     \\item \\st{Statisticians know it as a `log-linear model'} \\textbf{REALLY? -- MH}\n     \\item Mathematicians often call it a `Gibbs measure'\n     \\item Physicists know it as the `Boltzmann distribution' or `canonical ensemble'\n \\end{itemize}\n \\st{In fact, the Hammersley-Clifford theorem states that any measure that satisfies a Markov property can be expressed as a Gibbs measure}. So although we only look at distributions of this form, it is not actually as much of a restriction as it initially appears. Borrowing the terminology from MD, we call \\(U\\) the potential function (\\(\\mathcal{Z}\\) is a normalising constant). We know potential, not normaliser. Let's look pursue this molecular dynamics link to gain some intuition. How does this distribution arise?\n \n In MD, \\(U\\) describes the potential energy of a particle, for this reason we call \\(U\\) a potential well. (Picture of potential well). If we let a particle move in this well, this is what we see (animation?). The particle moves in the well, up and down each side. \n \n The equation of motion for a particle moving like this (Brownian dynamics) is the SDE\n \\[\\dif X_t = -\\grad U(X_t) \\dif t +\\sqrt{2}\\dif W_t\\]\n the (overdamped) Langevin equation. A natural question to ask is where is this particle on average? It spends most of the time in the bottom of the well (can see that just by watching), sometimes makes it quite high up the sides. Shock horror, it is exactly given by \\(\\pi\\)! This is what we call the invariant measure of the SDE (kind of).\n\n\n\\section{Algorithms}\n So back to statistics: the problem of statistical sampling has just been reduced to watching particles in wells! Bonzer! ... Except not quite. Just like in the ordinary differential equation case, one can't solve exactly in many cases, so we must discretise. Like in ODEs we use the Euler method! \n \n Applying this to the Langevin equation gives an iterative scheme to approximate the continuous diffusion (this is the MC from which MCMC gets its name). \n \\[X_{n+1} = X_n - h\\grad U(X_n)  + \\sqrt{2h}Z_{n+1}\\]\n Let's see what this looks like (trace plot of approximation? Or vis in well with a higher stepsize) This is only exact when the step size tends to zero, which we obviously can't do. This means that the invariant measure (the average positions of the particles) may not be the same as the continuous case. Or we may not even be able to find one! (Chain is transient/not ergodic) \n \n Example:\n \n Most extreme case: \\(h=1, U(x)=x^2/2\\). Obvious invariant measure is \\(N(0,1)\\), but chain (immediately) converges to \\(N(0,2)\\). \n \n So we have to be careful with stepsize. Also if the potential is superlinear (sides of the well are too steep), the iterative scheme diverges, even though the underlying diffusion is ergodic.\n \n \n Can we fix this? Yeeees, with Metropolis rejection (explain? Idea is to just reject some of the samples with some probability - show vis with rejects). Doing so means that whenever the underlying diffusion is exp ergodic?, the chain also will be (in the limit -- not actually useful - show vis.). Still runs in to problems when the potential is superlinear.\n \n So this is the direction that most research has taken since its initial proposal in 1996. We have been looking at a different method that avoids Metropolis rejection -- TAMING!\n \n \\section{Taming the Beast}\n We have seen in the visualisation that \\texttt{ULA} and \\texttt{MALA} don't quite work. The issue is the gradient of the potential well. Taming swaps the gradient for a function that is `close' to the gradient, but preserves the invariant measure of the diffusion.\n\\[\\dif X_t = -\\grad U(X_t) \\dif t +\\sqrt{2}\\dif W_t \\Longrightarrow \\dif X_t = -T(X_t)\\dif t +\\sqrt{2}\\dif W_t \\]\nDifferent choices of \\(T\\) are available, we consider \n\\[T=\\frac{\\grad U }{1+h\\grad U}\\]\nWhat does this do? It reduces the effect the gradient has on the iteration. Visualise.\n\nStiffness effects motivates coordinatewise? Show how taming deals with stiff problems in 2d. (Impacts ability in ill-conditioned problems).\n\nOne final modification we wish to mention is to use a different method of discretisation: Higher order (Stochastic Runge-Kutta) \\texttt{tHOLA}, Leimkuhler-Matthews (Non-Markovian) \\texttt{LM}. We don't have time to go into these methods here but ask at the end if you're interested in how they work.\n\\section{Horse Racing}\nSo we have given a heuristic (qualitative) motivation of how these algorithms are different. Can we quantify each methods effectiveness on different potentials/distributions? \n\nThe existing results on \\texttt{tULA} only looked at first and second moments Brosse et al.. This is sufficient only for Gaussian distributions, which aren't even superlinear. We wish to get some stronger results in terms of metrics. \n\nShitty boxplots \\(\\longrightarrow\\) Histograms? Wasserstein? KL? Computer time? Pick two or three plots that best illustrate errors, or use vis.\n\nWe also have some theoretical non-asymptotic error bounds in these metrics. \n\n\\section{Conclusion}\nWhat algorithm is best? Probably problem dependent, depends what you want out of the alorithm. Taming will give you an answer, which may be inaccurate -- but at least it is an answer. \n\\subsection*{Next Steps}\nThere are many many methods we haven't considered: HMC, mMALA, SGLD. Discuss SGLD? So hot right now NeurIPS. \n\\subsubsection*{Future Work}\nWe'd like to test these methods on real data, or even just simulated data, when we don't know the gradient analytically. This is much more relevant for the end user than a theoretical bound on convergence. Especially wish to test on `big data' as many (all?) MCMC methods suffer the curse of dimensionality. Lower dimensions may not show off the benefits of taming, may only become relevant in high dimensions. Also for algorithms with very complex iteration steps, they may lend themselves to parallelisation  better than simpler algorithms.\n\nFinally, we've made all the code used for testing available on github, as well as the visualisation. \n\n\\begin{center}Any questions? PLease say no\\end{center}\n\\end{document}", "meta": {"hexsha": "6712c9c015c4b8a6b0ff945e93addf7ecedcb73a", "size": 9758, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "WriteUp/Presentation/sketchscript.tex", "max_stars_repo_name": "Tom271/LangevinMC", "max_stars_repo_head_hexsha": "ed36a17ce9b7d1e39097aeaf5b92f0fa286d5489", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2019-02-07T12:51:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T13:35:13.000Z", "max_issues_repo_path": "WriteUp/Presentation/sketchscript.tex", "max_issues_repo_name": "swyoon/LangevinMC", "max_issues_repo_head_hexsha": "ed36a17ce9b7d1e39097aeaf5b92f0fa286d5489", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WriteUp/Presentation/sketchscript.tex", "max_forks_repo_name": "swyoon/LangevinMC", "max_forks_repo_head_hexsha": "ed36a17ce9b7d1e39097aeaf5b92f0fa286d5489", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-19T17:44:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-19T17:44:19.000Z", "avg_line_length": 57.4, "max_line_length": 542, "alphanum_fraction": 0.7295552367, "num_tokens": 2967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.33781787172647215}}
{"text": "\\documentclass{article}\n\\usepackage[elliptic]{qed}\n\n\\begin{document}\n\n\\section*{Numerical fallback}\n\nThe Legendre relation is a relation among the elliptic integrals of the first\n($\\ellipk$) and second ($\\ellipe$) kinds, given by\n%\n\\begin{qed}\n    \\ellipe(k^2) \\ellipk(1-k^2) + \\ellipe(1 - k^2) \\ellipk(k^2)\n    - \\ellipk(k^2) \\ellipk(1 - k^2) = \\frac{\\pi}{2}\n\\end{qed}\n%\nUnfortunately, \\textsf{sympy} doesn't know how to automatically simplify it,\nso \\QED cannot analytically determine its validity. Nevertheless,\nwhen we typeset it, we still got a passing badge. That's because \\QED falls\nback to numerical evaluation automatically.\n\n\\end{document}\n", "meta": {"hexsha": "ff3b541ad360e823bc4ef6f52cd7001e9499c3dd", "size": 651, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "examples/numerical_fallback.tex", "max_stars_repo_name": "rodluger/qed", "max_stars_repo_head_hexsha": "36c9cd37c5f29398e36b6a35790c678cd099535c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-15T18:49:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-15T18:49:48.000Z", "max_issues_repo_path": "examples/numerical_fallback.tex", "max_issues_repo_name": "rodluger/qed", "max_issues_repo_head_hexsha": "36c9cd37c5f29398e36b6a35790c678cd099535c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2021-03-15T17:27:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-22T18:10:56.000Z", "max_forks_repo_path": "examples/numerical_fallback.tex", "max_forks_repo_name": "rodluger/qed", "max_forks_repo_head_hexsha": "36c9cd37c5f29398e36b6a35790c678cd099535c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5909090909, "max_line_length": 77, "alphanum_fraction": 0.7250384025, "num_tokens": 209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6406358548398982, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.33781787172647215}}
{"text": "\\documentclass[executivepaper]{extarticle}\n\\usepackage[margin=3.0cm]{geometry}\n\\usepackage{fancyhdr}\n\\usepackage{extsizes}\n\\usepackage{enumerate}\n\\usepackage{enumitem}\n\\usepackage{mathtools}\n\n\\begin{document}\n\n\\vspace*{-40mm}\n\n\\begin{center}\n\n\\textbf{Modern Class Notes}\n\n\\end{center}\n\n\\section*{1/12/16}\n\n\\vspace{-5.5mm}\n\n\\noindent \\rule{2cm}{0.5pt}\n\nA group is an object that tries to describe the symmetry of something \\\\\n\nGoing to study:\n\n\\begin{enumerate}\n\n\\item Permutation groups\n\n\\item Matrix groups\n\n\\item Cosets and Legrange's Theorem\n\n\\item And other constructs\n\n\\end{enumerate}\n\nReview of some discrete math stuff: \\\\\n\n\\begin{enumerate}\n\n\\item A function $f: x \\rightarrow y$ (where X and Y are sets) is an assignment of an element of Y for each element of X\n\n\\item Fact: let $f: x \\rightarrow y$ be a function. Then:\n\n\\begin{enumerate}\n\n\\item $f$ is invertible $\\iff f$ is one to one\n\n\\end{enumerate}\n\n\\end{enumerate}\n\nEx)Let x={1, 2, 3,...,n}\\\\\n\n$\\pi(1)=2$\n\n$\\pi(2)=3$\n\n$\\pi(n-1)=n$\n\n$\\pi(n)=1$\\\\\n\nA permutation is a one-to-one and onto function from a finite set to itself \\\\\n\nAt least 3 ways of recording a permutation: \\\\\n\n\\begin{enumerate}\n\n\\item Two line notation\n\n\\item One line notation (works for permutations of order up to 9)\n\n\\item Cycle notation: start with a number and write down where it goes and then repeat this process for the rest of the numbers\n\n\\item \n\n\\end{enumerate}\n\n\n\\end{document}", "meta": {"hexsha": "848cf09688501aba994e89b1edbcd4fd38f4fb14", "size": 1420, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Modern_Algebra(Group_Theory)/ModernAlgebraClassNotes.tex", "max_stars_repo_name": "busebd12/Mathematics", "max_stars_repo_head_hexsha": "53530f5864af952afb4083c79632bb4280fd5c3a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Modern_Algebra(Group_Theory)/ModernAlgebraClassNotes.tex", "max_issues_repo_name": "busebd12/Mathematics", "max_issues_repo_head_hexsha": "53530f5864af952afb4083c79632bb4280fd5c3a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Modern_Algebra(Group_Theory)/ModernAlgebraClassNotes.tex", "max_forks_repo_name": "busebd12/Mathematics", "max_forks_repo_head_hexsha": "53530f5864af952afb4083c79632bb4280fd5c3a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.9047619048, "max_line_length": 127, "alphanum_fraction": 0.7183098592, "num_tokens": 422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.3378178717264721}}
{"text": "% Created: Enze Chen, June 2017\r\n% Last edited: Enze Chen, February 2018\r\n%\r\n% Chapter 4 of the MSE 142 coursereader. This chapter discusses quantum tunneling using the finite potential step/barrier. It derives the math behind boundary conditions and tunneling probability. Interference from multiple boundaries is also discussed. There is an emphasis on applications to really drive the point home that this phenomenon is cool and more ubiquitous than we might initially think!\r\n\r\n% Uncomment the following three lines and last line to individually compile this chapter\r\n%\\documentclass[12pt, english]{book}\r\n%\\usepackage{142crstyle}\r\n%\\begin{document}\r\n\r\n\\chapter{Quantum Tunneling} \\label{ch:tunnel}\r\n%{ \\doublespacing \r\nImagine you're tossing a tennis ball against the wall. Classical mechanics says that the ball will bounce back at you, or, should you throw it very hard, it might get stuck in the wall. But what if the ball somehow \\emph{goes through} the wall and emerges on the other side, leaving both unscathed? This is the basis for \\textbf{quantum tunneling}, a phenomenon where a particle passes through a potential barrier that it classically could not surmount. As bizarre as this may seem, quantum mechanics says there is a non-zero probability for tunneling to occur, and this phenomenon is actually leveraged for a variety of physical applications. Tunneling at the quantum scale occurs in physical systems ranging from photons\\footnote{See D. D. Coon \\href{http://aapt.scitation.org/doi/10.1119/1.1972893}{\\emph{American Journal of Physics}} \\textbf{34}, 240 (1966).} to water\\footnote{See \\href{https://physics.aps.org/articles/v9/43}{this focus article} from \\emph{Physics} \\textbf{9}, 43 about the work of A. I. Kolesnikov et al, \\href{https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.116.167802}{\\emph{Physical Review Letters}} \\textbf{116}, 167802 (2016).} and we will spend this chapter exploring the nature of this truly quantum mechanical behavior.\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n\\section{Finite potential step}\r\nTo facilitate our analysis of this behavior, we need to first devise a simple model for a quantum mechanical system, which we have shown here in Figure~\\ref{fig:tunnel-step}. On the left half of the figure in region I, where $x < 0$, we have a free particle ($V=0$) traveling to the right with energy $E$. At $x=0$, the particle encounters a \\textbf{potential step} with some \\emph{finite} potential $V=V_0$ that extends for all $x>0$ into region II.\r\n\r\n\\begin{figure}[!h]\r\n\t\\centering\r\n\t\\includegraphics[width=0.42\\linewidth]{tunnel-step}\r\n\t\\caption{A simple model to demonstrate quantum tunneling. A free particle with energy $E$ is traveling to the right and at $x=0$ is incident on a finite potential step with magnitude $V_0$.}\r\n\t\\label{fig:tunnel-step}\r\n\\end{figure}\r\n\r\nNote that we have not said anything yet about the relationship between $E$ and $V_0$ (the vertical position of the particle in Figure~\\ref{fig:tunnel-step} was arbitrarily drawn). Since the finite potential step is time-independent, we will try to understand how quantum mechanical particles interact with such a potential by solving the time-independent \\Sch\\ equation. In region I, we only have the free particle, so we can write down the \\Sch\\ equation as \r\n\\begin{equation}\r\n\t-\\frac{\\hbar^2}{2m} \\dv[2]{\\Psi}{x} = E\\Psi \\label{eq:reg-1-se}\r\n\\end{equation}\r\nIn region II, we have\r\n\\begin{equation}\r\n\t-\\frac{\\hbar^2}{2m} \\dv[2]{\\Psi}{x} = (E-V_0)\\Psi \\label{eq:reg-2-se}\r\n\\end{equation}\r\nwhere the energy of the particle is now with reference to the step's potential. We've seen these kinds of equations before and know that the general solution are sines and cosines, as was the case with the particle in a box. Here we write the general solutions in a slightly different, but equivalent way:\r\n\\begin{tcolorbox}[title = Traveling wave solutions] \\vspace{-2ex}\r\n\t\\begin{align}\r\n\t\t\\Psi_{\\text{I}} &= Ae^{ik_1x} + Be^{-ik_1x} \\label{eq:reg-1-wf} \\\\\r\n\t\t\\Psi_{\\text{II}} &= Ce^{ik_2x} + De^{-ik_2x} \\label{eq:reg-2-wf} \r\n\t\\end{align}\r\n\\end{tcolorbox}\r\nwhere $A$, $B$, $C$, and $D$ are unknown coefficients. Whoa! We know by Euler's formula that complex exponentials can be reformulated as sinusoidal functions, so these solutions at least seem plausible on the surface. To be sure we did our math right, let's plug Equation~\\ref{eq:reg-1-wf} into Equation~\\ref{eq:reg-1-se} to verify that it is a valid solution.\r\n\\begin{align*}\r\n\t-\\frac{\\hbar^2}{2m} \\dv[2]{\\Psi_{\\text{I}}}{x} &= E\\Psi_{\\text{I}} \\\\\r\n\t-\\frac{\\hbar^2}{2m} \\dv[2]{x}(Ae^{ik_1x} + Be^{-ik_1x}) &= E(Ae^{ik_1x} + Be^{-ik_1x}) \\\\\r\n\t-\\frac{\\hbar^2}{2m} \\dv{x}(Aik_1e^{ik_1x} - Bik_1e^{-ik_1x}) &= E(Ae^{ik_1x} + Be^{-ik_1x}) \\\\\r\n\t\\frac{\\hbar^2}{2m} \\left(Ak_1^2e^{ik_1x} + Bk_1^2e^{-ik_1x}\\right) &= E(Ae^{ik_1x} + Be^{-ik_1x}) \\\\\r\n\tk_1^2\\left(Ae^{ik_1x} + Be^{-ik_1x}\\right) &= \\frac{2mE}{\\hbar^2}(Ae^{ik_1x} + Be^{-ik_1x})\r\n\\end{align*}\r\n\r\nSo we see that\r\n\\begin{equation}\r\n\tk_1 = \\sqrt{\\frac{2mE}{\\hbar^2}} \\label{eq:reg-1-k}\r\n\\end{equation}\r\nwhich is the same expression we found previously and shows that Equation~\\ref{eq:reg-1-wf} is a valid solution. In a similar vein, we see that the magnitude of the wave vector in region II is given by \r\n\\begin{equation}\r\n\tk_2 = \\sqrt{\\frac{2m(E-V_0)}{\\hbar^2}} \\label{eq:reg-2-k}\r\n\\end{equation}\r\n\r\nNote that if $E > V_0$, then $k_2$ is real and we have sinusoidal behavior in region II. This makes sense because a particle with higher energy than the potential step should be able to surmount it and continue exhibiting wave-like behavior. However, if $E < V_0$, then $k_2$ becomes imaginary, and the wave-like solutions given in Equation~\\ref{eq:reg-2-wf} turn into exponentially growing and decaying functions. Thus it seems like even though the particle does not have sufficient energy to surmount the potential step, there is still something happening in region II \\emph{inside} the step. We will come back to this point shortly. \\par \r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n\\section{Forward and backward waves}\r\nNow, the general solutions given by Equation~\\ref{eq:reg-1-wf} and~\\ref{eq:reg-2-wf} are perfectly acceptable mathematically, but we argued in class that there is also a useful physical interpretation of these solutions. Recall that the de Broglie relation relates the wave vector $k$ to the momentum. Now we see that these wave function solutions not only resemble the plane wave solutions that we started with, but they also have a superposition of positive and negative wave vectors which determine the direction of propagation of the wave. We therefore argue that we can associate $A$ with the amplitude of the \\textbf{incident wave} on the step (since the exponent has a positive $k_1$) and $B$ with the amplitude of the \\textbf{reflected wave} (arising from a reflection at the interface). Similarly, we will associate $C$ with the amplitude of the \\textbf{transmitted wave} through the step and $D$ with the amplitude of the wave incident on the step from the right. \\par \r\n\r\nIn the example shown in Figure~\\ref{fig:tunnel-step}, because we are only considering a wave incident on the step from the left, the coefficient $D$ must be zero. For the case when $E > V_0$, we still have a complex exponential function, so the wave function hasn't changed much. But for the case when $E < V_0$, the wave function in region II is only an exponentially damped function, which as we discussed in class is analogous to an evanescent wave in wave optics.\\footnote{Indeed, evanescent wave coupling causes \\href{https://en.wikipedia.org/wiki/Total_internal_reflection\\#Frustrated_total_internal_reflection}{``frustrated'' total internal reflection}, which is a very similar behavior to quantum tunneling.} To see why this is the case, we can define a constant\r\n\\begin{equation}\r\n\tk' = \\sqrt{\\frac{2m(V_0-E)}{\\hbar^2}} \\label{eq:reg-2-kp}\r\n\\end{equation}\r\nsuch that\r\n\\begin{equation*}\r\n\tk_2 = \\sqrt{\\frac{2m(E-V_0)}{\\hbar^2}} = i\\sqrt{\\frac{2m(V_0-E)}{\\hbar^2}} = ik'\r\n\\end{equation*}\r\n\r\nThis allows us to rewrite Equation~\\ref{eq:reg-2-wf} as \r\n\\begin{equation}\r\n\t\\Psi_{\\text{II}} = Ce^{ik_2x} = Ce^{-k'x} \\label{eq:reg-2-wfp}\r\n\\end{equation}\r\n\r\nand the exponential decay function emerges. Our goal now is to extract the reflection coefficient $R$ and transmission coefficient $T$. We define these two quantities as follows:\r\n\\begin{equation*}\r\n\t\\boxed{R = \\abs{\\frac{B}{A}}^2 \\quad \\text{and} \\quad T = \\frac{k_2}{k_1}\\abs{\\frac{C}{A}}^2}\r\n\\end{equation*}\r\n% TODO: check with Aaron about this\r\nSimilar to the statistical interpretation of the wave function, we have taken the modulus squared to represent the probability of an event occurring. \\par \r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n\\section{Continuity condition}\r\nIn order to relate the coefficients from the wave function in region I with those from the wave function in region II, we have to be precise and specify the behavior at the boundary of the two regions (i.e. at $x=0$). Let us consider what the conditions are for continuity of the wave function and its first derivative in a region where the potential is discontinuous (as it is at $x=0$). Starting from the time-independent \\Sch\\ equation, we integrate over an infinitesimal region $(-\\epsilon, \\epsilon)$ about $x=0$:\r\n\\begin{align*}\r\n\t-\\frac{\\hbar^2}{2m} \\dv[2]{\\Psi}{x} + V(x)\\Psi &= E\\Psi \\\\\r\n\t\\dv[2]{\\Psi}{x} &= \\frac{2m}{\\hbar^2}(V(x) - E)\\Psi \\\\\r\n\t\\int_{-\\epsilon}^{\\epsilon} \\dv[2]{\\Psi(x)}{x} \\dd{x} &= \\frac{2m}{\\hbar^2} \\int_{-\\epsilon}^{\\epsilon} (V(x)-E)\\Psi(x) \\dd{x} \r\n\\end{align*}\r\n\r\nNow as $\\epsilon$ approaches zero, the right hand side approaches zero if $V(x)$ and $\\Psi(x)$ are not infinite (and there are good reasons why $\\Psi$, from which one calculates the probability density function, cannot go to infinity).\\footnote{Though $\\Psi(x)$ cannot be infinite at the boundary, $V(x)$ still can. We'll save this for the next chapter when we discuss the Kronig-Penney model.} We therefore conclude, after performing the straightforward integral on the left hand side, that\r\n\\begin{tcolorbox}[title = Continuity of the wave function] \\vspace{-2ex}\r\n\t\\begin{equation}\r\n\t\t\\dv{\\Psi}{x} \\bigg|_{\\epsilon} - \\dv{\\Psi}{x} \\bigg|_{-\\epsilon} = 0 \\label{eq:cont-dx}\r\n\t\\end{equation}\r\n\\end{tcolorbox}\r\n\r\nThis means that across the discontinuity in the potential, the first derivative of the wave function (and by extension the wave function itself) must be continuous.\\footnote{Continuity of the wave function is an important point, so if you need another explanation to internalize the ideas, \\href{https://www.quora.com/Why-does-the-wave-function-have-to-be-continuous}{Quora} actually gives a pretty good answer.} \r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n\\section{Tunneling probability}\r\nEquation~\\ref{eq:cont-dx} allows us to obtain the desired transmission and reflection coefficients as follows. At the boundary, we require that \r\n\\begin{align*}\r\n\t\\Psi_{\\text{I}}(0) &= \\Psi_{\\text{II}}(0) \\\\\r\n\t\\Psi_{\\text{I}}'(0) &= \\Psi_{\\text{II}}'(0)\r\n\\end{align*}\r\nwhich directly translates into\r\n\\begin{align}\r\nA + B &= C \\label{eq:abc1} \\\\\r\nAk_1 - Bk_1 &= Ck_2 \\label{eq:abc2}\r\n\\end{align}\r\n\r\nWe can solve the above system of equations in many ways, such as multiplying Equation~\\ref{eq:abc1} by $k_1$ and adding the result to Equation~\\ref{eq:abc2}. Doing so gives\r\n\\begin{equation}\r\n\t\\frac{C}{A} = \\frac{2k_1}{k_1+k_2} \\label{eq:c-a}\r\n\\end{equation}\r\nand a similar method gives \r\n\\begin{equation}\r\n\t\\frac{B}{A} = \\frac{k_1 - k_2}{k_1 + k_2} \\label{eq:b-a}\r\n\\end{equation}\r\n\r\nFinally, this gives \r\n\\begin{tcolorbox}[title = $T$ and $R$ for finite potential step] \\vspace{-2ex}\r\n\t\\begin{align}\r\n\t\tT = \\frac{k_2}{k_1}\\abs{\\frac{C}{A}}^2 &= \\frac{4k_1k_2}{(k_1+k_2)^2} \\label{eq:t-step} \\\\ \r\n\t\tR = \\abs{\\frac{B}{A}}^2 &= \\frac{(k_1-k_2)^2}{(k_1+k_2)^2} \\label{eq:r-step}\r\n\t\\end{align}\r\n\\end{tcolorbox}\r\nIf you have taken a course in optics or acoustics these equations should look familiar---they are similar to the results for the transmission and reflection coefficients for an acoustic wave or light wave incident on a boundary. Now we're beginning to see how quantum mechanics predicts transmission with a non-zero probability. Note here that the way we have defined $T$ and $R$ also gives us the identity $T + R = 1$. \\par \r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n\\section{Finite potential barrier} \\label{sec:tunnel-barrier}\r\nHaving successfully managed the previous example, we're now ready to tackle the slightly more complicated case (and the one that we've been waiting for!) of quantum tunneling through a finite potential barrier of width $L$ and height $V_0$ (Figure~\\ref{fig:tunnel-barrier}). We will carry out the following calculations in particular for the case $E < V_0$, which is the most interesting and surprising case.\r\n\r\n\\begin{figure}[!h]\r\n\t\\centering\r\n\t\\includegraphics[width=0.6\\linewidth]{tunnel-barrier}\r\n\t\\caption{In this example, a free particle with energy $E$ is traveling to the right and at $x=0$ is incident on a finite potential barrier with width $L$ and height $V_0$. The potential is otherwise zero in front of and behind the barrier.}\r\n\t\\label{fig:tunnel-barrier}\r\n\\end{figure}\r\n\r\nWith three regions, we can now write down the solutions to the time-independent \\Sch\\ equation as\r\n\\begin{align}\r\n\t\\Psi_{\\text{I}} &= Ae^{ikx} + Be^{-ikx} \\label{eq:barr-1} \\\\\r\n\t\\Psi_{\\text{II}} &= Ce^{k'x} + De^{-k'x} \\label{eq:barr-2} \\\\\r\n\t\\Psi_{\\text{III}} &= Fe^{ikx} \\label{eq:barr-3}\r\n\\end{align}\r\n\r\nHere, we have defined $k = \\sqrt{\\frac{2m}{\\hbar^2}(E)}$ and $k'=\\sqrt{\\frac{2m}{\\hbar^2}(V_0-E)}$ such that $k'$ is a real number. As before, we note that Equation~\\ref{eq:barr-2} models exponential growth and decay inside the barrier. We also argue that a particle incident only from the left means that the only term in region III is the transmitted wave with amplitude $F$ (Equation~\\ref{eq:barr-3}). Now our goal is to extract the transmission coefficient $T = \\abs{\\frac{F}{A}}^2$.\\footnote{Whereas previously we had an extra $k_2/k_1$ term, in this case the momentum of the wave in region I and region III are the same! It might seem weird, but tunneling doesn't cause the wave to actually lose energy.} In this case, the transmitted wave with amplitude $F$ encodes within it all the possible ways in which the wave can transmit through the barrier, including multiple reflections inside the barrier. All of these complicated possibilities are accounted for simply by enforcing the continuity equations at $x=0$ and $x=L$. This gives us the following set of equations:\r\n\\begin{align*}\r\n\tA + B &= C + D \\\\\r\n\tA - B &= (C - D)\\frac{k'}{ik} \\\\\r\n\tCe^{k'L} + De^{k'L} &= Fe^{ikL} \\\\\r\n\tCe^{k'L} - De^{k'L} &= Fe^{ikL}\\frac{ik}{k'}\r\n\\end{align*}\r\n\r\nWe will not go through the gory details here of solving this system of equations as it involves messy algebra and nothing more of substance, but feel free to consult Appendix~\\ref{sec:tunnel-deriv} for all the steps. After combining these equations and eliminating variables appropriately, we obtain the following equation relating $F$ to $A$:\r\n\\begin{equation}\r\n\t4Aikk'e^{-ikL} = F \\left[(k'+ik)^2e^{-k'L} - (k'-ik)^2e^{k'L}\\right] \\label{eq:tunnel-fa}\r\n\\end{equation}\r\n\r\nIn the limit where $k'L \\gg 1$ (i.e. the barrier width is much larger than the effective wavelength of the particle inside the barrier), one can simplify Equation~\\ref{eq:tunnel-fa} to obtain\r\n\\begin{equation}\r\n\tT = \\abs{\\frac{F}{A}}^2 = \\frac{16k^2k^{\\prime 2}e^{-2k'L}}{(k^{\\prime 2}+k^2)^2} \\label{eq:tunnel-prob}\r\n\\end{equation}\r\n\r\nSince this expression for $T$ is dominated by the exponential term, it asymptotically approaches the very simple equation\r\n\\begin{tcolorbox}[title = Tunneling probability approximation when $E < V_0$] \\vspace{-2ex}\r\n\t\\begin{equation}\r\n\t\tT \\approx e^{-2k'L} \\label{eq:tunnel-approx}\r\n\t\\end{equation}\r\n\\end{tcolorbox}\r\n\r\nThe above equation is a very useful approximate solution for the tunneling probability that is often applied in practice. For completeness, we will also give the exact solution for the tunneling probability below.\r\n\\begin{tcolorbox}[title = Tunneling probability exact solution when $E < V_0$] \\vspace{-2ex}\r\n\t\\begin{equation}\r\n\t\tT = \\abs{\\frac{F}{A}}^2 = \\frac{1}{1 + \\left(\\frac{k^2+k^{\\prime 2}}{2kk'}\\right)^2 \\sinh^2(k'L)} \\label{eq:tunnel-prob-full}\r\n\t\\end{equation}\r\n\\end{tcolorbox}\r\n\r\nThe exact solution has a maximum value of 1 when $k'L=0$ and rapidly decreases to 0 as $k'L$ increases. However, $T$ is still non-zero, which means there is a chance for the particle to tunnel through the barrier and emerge on the other side! This is shown schematically in Figure~\\ref{fig:tunnel-wave}.\\footnote{What we've plotted is the actual wave function amplitude. How would the probability density differ?} As discussed in class, for $L \\approx \\SI{1}{\\nano\\meter}$ and for typical electron-volt-scale potential barriers, the transmission probability is close to 1, indicating how important these kinds of effects become at the nanoscale. \\par\r\n\r\n\\begin{figure}[!h]\r\n\t\\centering\r\n\t\\includegraphics[width=0.48\\linewidth]{tunnel-wave}\r\n\t\\caption{An illustration of the amplitude of the wave function in the three regions. It exponentially decays through the barrier but emerges from the right side with a lower amplitude and the same frequency (energy) as the wave function in the left region. A non-zero value of the wave function on the right indicates that the particle may exist past the barrier.}\r\n\t\\label{fig:tunnel-wave}\r\n\\end{figure}\r\n\r\nFurthermore, note how the wave function in region III differs from the wave function in region I. The amplitude is much smaller, which makes sense as there is a much lower probability that we will find the particle on the right side of the barrier. However, should tunneling occur, we can apply the conservation of energy to see that the particle has the same energy as before, and hence the frequency of the wave function is the same. It's easy to get probability and energy mixed up, but make sure you can draw the distinction.\\footnote{An analogy to classical mechanics: A ball with a certain amount of kinetic energy that rolls up and over a hill will have the same amount of kinetic energy when it arrives back to ground level (assuming no friction).} \\par \r\n\r\nThough we did not derive it here, it is interesting to look at the transmission probability for the case when $E > V_0$, which is given by Equation~\\ref{eq:tunnel-prob-res} and plotted in Figure~\\ref{fig:tunnel-prob} as a function of energy.\r\n\\begin{equation}\r\n\t\\boxed{T = \\frac{1}{1 + \\left(\\frac{k^2-k_2^2}{2kk_2}\\right)^2 \\sin^2(k_2L)}} \\label{eq:tunnel-prob-res}\r\n\\end{equation}\r\n\r\n\\begin{figure}[!h]\r\n\t\\centering\r\n\t\\includegraphics[width=0.35\\linewidth]{tunnel-prob}\r\n\t\\caption{Tunneling probability as a function of energy for the finite potential barrier when $E > V_0$. At characteristic energies, the tunneling probability reaches 1 due to resonance of the wave function in the region of the barrier.}\r\n\t\\label{fig:tunnel-prob}\r\n\\end{figure}\r\n\r\nIn this case, the wave function displays sinusoidal behavior in region II instead of exponential behavior, and we have made the appropriate substitution as $k_2=ik'$. It may come as no surprise that if the energy of the particle was high enough, then the transmission probability approaches 1 (i.e. it's as if the barrier wasn't even there). However, as seen in Figure~\\ref{fig:tunnel-prob}, total transmission is also achievable at lower values of $E$, which correspond to tunneling \\textbf{resonance} when the wavelength of the particle coincides with the width of the barrier. This leads to a constructive interference effect analogous to what we observed in the double-slit experiment.\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n\\section[Application: Devices]{Application: Optical and electronic devices}\r\nOnce the theory behind quantum tunneling was formally developed, scientists suddenly realized just how ubiquitous the phenomenon was. It turns out quantum tunneling is necessary to explain the radioactive decay of nuclei, the fusion reactions inside stars, and even the mechanisms behind photosynthesis! Furthermore, scientists have leveraged quantum tunneling to create many new nanoscale devices, two of which will be discussed here.\r\n\r\n\\subsection{Quantum cascade laser}\r\nThe first device we will survey here, the \\textbf{quantum cascade laser} (QCL), actually combines quantum tunneling with the quantum wells that we analyzed in the previous chapter. First demonstrated in 1994 using a mixture of GaInAs/AlInAs, QCLs are semi-conductor lasers comprised of a stack of quantum well heterostructures (Figure~\\ref{fig:qcl}).\r\n\r\n\\begin{figure}[!h]\r\n\t\\centering\r\n\t\\includegraphics[width=0.55\\linewidth]{qcl}\r\n\t\\caption{Schematic of the quantum cascade laser, where periodic layers of varying thicknesses confine electrons into different energy levels. A population inversion causes electron transitions that lead to photon emission and subsequent tunneling of the electron to the next period in the structure. Reproduced from J. Faist et al. \\href{http://science.sciencemag.org/content/264/5158/553}{\\emph{Science}} \\textbf{264}, 5158 (1994).}\r\n\t\\label{fig:qcl}\r\n\\end{figure}\r\n\r\nInstead of having a bulk structure, QCLs use a periodic series of layers of different materials and thicknesses to achieve a superlattice. This superlattice is capable of confining electrons into different discrete sub-bands across all of the quantum wells. When a \\textbf{population inversion} is achieved, where more electrons are in an excited state than in the ground state, electrons will drop in energy and emit photons, which is how all lasers operate in general. What makes the QCL unique, in addition to its highly tunable layers (e.g. grown with molecular beam epitaxy), is that once an electron has transitioned to a lower energy level in one period of the structure, it can then tunnel to the next period in the heterostructure and undergo more transitions, thereby releasing more photons in a \\emph{cascading} effect. The ability for electrons to tunnel through barriers and emit multiple photons leads to higher power output for QCLs than normal lasers, which could lead to advances in spectroscopy, sensing, and signaling.\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n\\subsection{Scanning tunneling microscope}\r\nOur second nanoscale device, the \\textbf{scanning tunneling microscope} (STM), is a more popular tool that you might have previously heard about. It was developed in 1981 by Gerd Binnig and Heinrich Rohrer at IBM, and a schematic detailing the principles of operation is shown in Figure~\\ref{fig:stm}.\r\n\r\n\\begin{figure}[!h]\r\n\t\\centering\r\n\t\\includegraphics[width=0.5\\linewidth]{stm}\r\n\t\\caption{Schematic for how the scanning tunneling microscope operates. As the tip moves across the surface, the control unit (CU) applies an appropriate voltage $V_p$ to a piezoelectric arm $P_z$ and modulates its height such that the same tunneling current $J_T$ is maintained. As a result, the tip moves up and down to trace a material's topography, which is imaged at angstrom-scale resolution. Reproduced from G. Binnig et al. \\href{https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.49.57}{\\emph{Phys. Rev. Lett.}} \\textbf{49}, 57 (1982).}\r\n\t\\label{fig:stm}\r\n\\end{figure}\r\n\r\nIn order to detect small changes on a material's surface, the STM leverages \\textbf{piezoelectricity} to control the three arms that guide a sharp tip that sits less than \\SI{1}{\\nano\\meter} away from the surface.\\footnote{For those unfamiliar with piezoelectricity, it is briefly explained by \\href{http://hyperphysics.phy-astr.gsu.edu/hbase/Solids/piezo.html}{Rod Nave} at Georgia State University.} As $P_x$ and $P_y$ raster scan the tip across the surface, a control unit applies a small voltage ($\\sim\\SI{10}{\\milli\\volt}$) to cause electrons to tunnel between the tip and the surface. It measures the tunneling current $J_T$ that's produced and adjusts the height of the third arm $P_z$ to maintain the same current. The piezoelectric arms are so sensitive to changes in $J_T$ that the STM is capable of imaging the surface topography with a resolution of \\SI{1}{\\angstrom} (\\SI{e-10}{\\meter}) or less! Not only are scientists able to image \\emph{individual atoms} with this technique, but they have been able to manipulate the atoms as well, forming unique nanostructures like the quantum corral in Figure~\\ref{fig:corral} and even a stop-motion animated short film by the folks at IBM Research.\\footnote{A video of ``A Boy and His Atom'' and more information can be found on the \\href{http://www.research.ibm.com/articles/madewithatoms.shtml\\#fbid=9xTkVKSpT3k}{IBM Research website}.}\r\n\r\n\\begin{figure}[!h]\r\n\t\\centering\r\n\t\\includegraphics[width=0.4\\linewidth]{corral}\r\n\t\\caption{A quantum corral constructed by arranging 48 Fe atoms in a ring on Cu(111) surface using a STM. Reproduced from M. F. Crommie et al. \\href{http://science.sciencemag.org/content/262/5131/218}{\\emph{Science}} \\textbf{262}, 5131 (1993).}\r\n\t\\label{fig:corral}\r\n\\end{figure}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n%\\subsection{Resonant tunneling diode}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n\\section{Summary}\r\nTo recap, in this chapter we analyzed the peculiar phenomenon of quantum tunneling, whereby a particle incident on a finite potential barrier has a non-zero probability of penetrating the barrier and emerging on the other side. This holds true even if the particle carried less energy than the barrier's potential, which is prohibited by the laws of classical mechanics. In that case, we argued that the wave function of the particle exhibits exponential behavior inside the barrier and it must maintain continuity with the wave function on the outside. This allowed us to derive the transmission probability as a function of the particle's wave vector and the barrier width, and we typically use Equation~\\ref{eq:tunnel-approx} to approximate this probability. Tunneling is a vital mechanism for many natural processes and scientists have leveraged its power to create novel nanoscale devices like the quantum cascade laser and scanning tunneling microscope. In the next chapter, we will solve the \\Sch\\ equation for yet another model, one that consists of periodic potential barriers that are infinitely tall and infinitely narrow.\r\n\r\n\r\n%} % for doublespacing\r\n%\\end{document}", "meta": {"hexsha": "636aa06549c962eef9f1757067e197514d6ae3d7", "size": 26821, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/chapter_4.tex", "max_stars_repo_name": "Enze-Chen/mse_142_cr", "max_stars_repo_head_hexsha": "a98585b32f26f6c189b96345d9cc1e9727156268", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-13T17:08:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-13T17:08:24.000Z", "max_issues_repo_path": "tex/chapter_4.tex", "max_issues_repo_name": "Enze-Chen/mse_142_cr", "max_issues_repo_head_hexsha": "a98585b32f26f6c189b96345d9cc1e9727156268", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/chapter_4.tex", "max_forks_repo_name": "Enze-Chen/mse_142_cr", "max_forks_repo_head_hexsha": "a98585b32f26f6c189b96345d9cc1e9727156268", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 101.5946969697, "max_line_length": 1393, "alphanum_fraction": 0.7291301592, "num_tokens": 7176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.33781786810848113}}
{"text": "\\documentclass[12pt]{article}\n\\usepackage{verbatim}\n\\usepackage{amssymb,amsmath}\n\\usepackage{amsthm}\n\\usepackage{graphicx}\n\\usepackage{epsfig}\n\\begin{comment}\n\\setlength{\\textwidth}{6.50in}\n\\setlength{\\oddsidemargin}{0in}\n\\setlength{\\evensidemargin}{0in}\n\\setlength{\\textheight}{8.5in}\n\\setlength{\\topmargin}{-.25in}\n\\end{comment}\n%\\newtheorem{theorem}{Theorem}\n\\newtheorem{corollary}{Corollary}[section]\n\\newtheorem{lemma}[corollary]{Lemma}\n\\newtheorem{proposition}[corollary]{Proposition}\n\\newtheorem{theorem}[corollary]{Theorem}\n%\\newtheorem{conjecture}[corollary]{Conjecture}\n\\newcommand{\\Prob} {{\\bf P}}\n\\newcommand{\\Z}{{\\mathbb Z}} \n\\newcommand{\\E}{{\\bf E}}\n\\newcommand{\\Es}{{\\rm Es}}\n\\newcommand{\\Cp}{{\\rm cap}}\n\\newcommand{\\R}{{\\mathbb{R}}}\n\\newcommand{\\C}{{\\mathbb C}}\n\\newcommand{\\rad}{{\\rm rad}}\n\\newcommand{\\hdim}{{\\rm dim}_h}\n\\newcommand{\\bound}{\\partial_O}\n\\newcommand{\\dist}{{\\rm dist}}\n\\newcommand{\\x}{{\\bf x}}\n\\newcommand{\\y}{{\\bf y}}\n\\newcommand{\\sphere}{{\\cal S}}\n\\newcommand{\\Var}{{\\rm Var}}\n\\newcommand{\\Q}{{\\bf Q}}\n\\newcommand{\\add}{+}\n\\newcommand{\\bdim}{{\\rm dim}_b}\n\\newcommand{\\lf}{\\lfloor}\n\\newcommand{\\rf}{\\rfloor}\n\n\\newcommand{\\be}{\\begin{equation}}\n\\newcommand{\\ee}{\\end{equation}}\n\\newcommand{\\bea}{\\begin{eqnarray}}\n\\newcommand{\\eea}{\\end{eqnarray}}\n\\newcommand{\\beann}{\\begin{eqnarray*}}\n\\newcommand{\\eeann}{\\end{eqnarray*}}\n\n\\def\\reff#1{(\\ref{#1})}\n\n\\def \\dHalf  {{\\cal H}}\n\\def \\dhulls {{\\cal A}}\n\\def \\dhcap {{\\rm dhcap}}\n\\def \\Im {{\\rm Im}}\n\\def \\Re {{\\rm Re}}\n\\def \\p {\\partial}\n\\def \\edges {{\\cal E}}\n\\def \\Half {{\\mathbb H}}\n\\def \\reals {{\\mathbb R}}\n\\def \\interior {\\rm int}\n\\def \\LEW{LEW}\n\\def \\sledim{\\hat d}\n\\def \\Disk {{\\mathbb D}}\n\\def \\Square {{\\cal S}}\n\\def \\diam {{\\rm diam}}\n\\def \\state {{\\cal X}}\n\\def \\eset {\\emptyset}\n\n\\def \\saws {{\\cal R}}\n\\def \\paths {{\\cal K}}\n\\def \\loop {{\\cal L}}\n\\def \\um  {{\\bar m}}\n\\def \\soup {{\\cal C}}\n\\def \\tree {{\\cal T}}\n\\def \\sgn {{\\rm sgn}}\n\\def \\looper {{\\cal J}}\n\\def \\strip{{\\cal S}}\n\n\\def \\scaleexp{{\\rho}}\n\n\\def \\energy {{\\cal E}}\n\\def \\hcap {{\\rm hcap}}\n\\def \\rect{{\\cal R}}\n\\def \\distsub {{\\Upsilon}}\n\\def \\distsubtwo {{\\Theta}}\n\n\\def \\dyad {{\\cal D}}\n\n\\def \\F {{\\mathcal F}}\n\n\\def \\walk {{\\mathcal W}}\n\\def \\hwalk {{\\mathcal H}}\n\\def \\bridge{{\\mathcal B}}\n\\def \\ibridge{{\\mathcal I}}\n\n\\def \\acat {{\\oplus}}\n\\def \\bcat {{\\otimes}}\n\n\n\\def \\Define {\\noindent {\\bf Definition.} }\n\\def  \\Pf  {\\noindent {\\bf Proof.} }\n\\def \\freemass {{\\cal C}}\n\\newenvironment{remark}[1][Remark]{\\begin{trivlist}\n\\item[\\hskip \\labelsep {\\bfseries #1}]}{\\end{trivlist}}\n\\newenvironment{definition}[1][Definition]{\\begin{trivlist}\n\\item[\\hskip \\labelsep {\\bfseries #1}]}{\\end{trivlist}}\n\\newenvironment{example}[1][Example]{\\begin{trivlist}\n\\item[\\hskip \\labelsep {\\bfseries #1}]}{\\end{trivlist}}\n\\newenvironment{conjecture}[1][Conjecture]{\\begin{trivlist}\n\\item[\\hskip \\labelsep {\\bfseries #1}]}{\\end{trivlist}}\n\n\\begin{document}\n\n\n\\section{SLE partition functions}\n\nFor a domain $D$ and points $z,w$ on its boundary, we let \n$H_D(z,w)$ denote the total mass of the SAW's in $D$ from $z$ to $w$. \nThis is a rather vague definition. Our goal is to argue that it \nshould be conformally covariant in the following sense. If $\\Phi$ is \na conformal map on $D$, then \n\\bea\nH_D (z,w)  = \n[\\Phi_A^\\prime(z) \\Phi_A^\\prime(w)]^{5/8} \nH_{\\Phi(D)}(\\Phi(z),\\Phi(w)) \n\\label{eqzz}\n\\eea\nThis formula should not be taken too literally. In particular, there \nare lattice effects to be taken into account. \n\nLet \n\\beann\nZ(0,n) = \\sum_{\\omega:0 \\rightarrow n, \\omega \\subset \\Half} \\beta^{|\\omega|} \n\\eeann\nThe sum is over all self-avoiding walks that start at $(0,0)$, end \nat $(n,0)$  and stay in the upper half plane except for their endpoints.\nWe assume that there is an exponent $\\scaleexp$ such that \nthe limit \n\\beann\nc=\\lim_{n \\rightarrow \\infty} Z(0,n) n^\\rho\n\\eeann\nexists. Now let $x >0$. Let $[nx]$ denote the integer closest to $x$. \nWe have\n\\beann\n\\lim_{n \\rightarrow \\infty} Z(0,[nx]) n^\\scaleexp = \n\\lim_{n \\rightarrow \\infty}  Z(0,[nx]) [nx]^\\scaleexp \n{n^\\scaleexp \\over [nx]^\\scaleexp}\n= {c \\over x^\\scaleexp}\n\\eeann\nThis shows that \n\\bea\nH_\\Half(0,x) = \\frac{1}{x^\\scaleexp} \\, H_\\Half(0,1)\n\\label{scaling}\n\\eea\n\nLet $A \\subset \\Half$ be such that $\\Half \\setminus A$ is a simply connected\ndomain which is bounded away from $0$. The scaling limit of the \nself-avoiding walk is conjectured to be $SLE_{8/3}$, a \nchordal restriction measure.\nThe probability that a SAW $\\gamma$ in $\\Half$ from $0$ to $\\infty$ does not \nenter $A$ is given by \n\\beann\nP(\\gamma \\cap A = \\emptyset) = [\\phi_A^\\prime(0)]^{5/8}\n\\eeann\nwhere $\\phi_A$ is a conformal map from $\\Half \\setminus A$ to $\\Half$\nwhich sends $\\infty$ to itself and has derivative $1$ at $\\infty$. \n(This means $\\phi(z) \\asymp z$ as $z \\rightarrow \\infty$.)\nIf we assume that the scaling limit of the probability mesasure\nfor the SAW between two points is conformally invariant,\nthen we can find the probability that a SAW in $\\Half$ from $0$ to a \nreal $x$ hits $A$. Denote this probability by \n$P_{\\Half,0,x}(\\gamma \\cap A =\\emptyset)$.\nLet $\\psi_x$ be a Moibius transformation of \n$\\Half$ to itself which fixes $0$ and sends $x$ to $\\infty$. \nThen \n\\beann\nP_{\\Half,0,x}(\\gamma \\cap A =\\emptyset)=  [\\phi_{\\psi_x(A)}^\\prime(0)]^{5/8}\n\\eeann\nWe can express this probability as a ratio of partition functions\n\\beann\nP_{\\Half,0,x}(\\gamma \\cap A =\\emptyset) = {H_{\\Half \\setminus A} (0,x) \n\\over H_\\Half(0,x) }\n\\eeann\nSo we have the following transformation result for partition functions\n\\beann\nH_{\\Half \\setminus A} (0,x)  = [\\phi_{\\psi_x(A)}^\\prime(0)]^{5/8} H_\\Half(0,x) \n\\eeann\n\nRecall that $\\phi_{\\psi_x(A)}$ is a conformal map that takes \n$\\Half \\setminus \\psi_x(A)$ to $\\Half$ and fixes $0$ and $\\infty$. \nLetting\n\\beann\n\\phi_{x,A}= \\psi_x^{-1} \\circ \\phi_{\\psi_x(A)} \\circ \\psi_x,\n\\eeann\n$\\phi_{x,A}$ maps $\\Half \\setminus A$ to $\\Half$ and fixes $0$ \nand $x$. \nSince $\\psi_x(0)=0$, $\\phi_{\\psi_x(A)}(0)=0$, and \n$(\\psi_x^{-1})^\\prime(0)=1/\\psi_x^\\prime(0)$, \nwe have that \n\\beann\n\\phi_{x,A}^\\prime(0) = \\phi_{\\psi(A)}^\\prime(0) \n\\eeann\nSo we have\n\\bea\nH_{\\Half \\setminus A} (0,x)  = [\\phi_{x,A}^\\prime(0)]^{5/8} H_\\Half(0,x) \n\\label{trans}\n\\eea\nOf course there is more that one conformal map of $\\Half \\setminus A$\nto $\\Half$ that fixes $0$ and $x$. The particular map we defined has \n$\\phi_{x,A}^\\prime(x)=1$. \nA general conformal map $\\Phi_{x,A}$ of $\\Half \\setminus A$\nto $\\Half$ that fixes $0$ and $x$ can be written as \n$\\Phi_{x,A} = \\chi \\circ \\phi_{x,A}$ \nwhere $\\chi$ is a Moibius transformation of $\\Half$ to itself that \nfixes $0$ and $x$. \nSuch transformations are given by \n\\beann \n\\chi(z) = {z \\over c(z-x)+1}\n\\eeann\nwhere $c \\in \\reals$. \nA short computation shows $\\chi^\\prime(0) \\chi^\\prime(x)=1$. \nSince \n\\beann\n\\Phi_{x,A}^\\prime(0) &=& \\chi^\\prime(0) \\phi_{x,A}^\\prime(0) \\\\\n\\Phi_{x,A}^\\prime(x) &=& \\chi^\\prime(x) \\phi_{x,A}^\\prime(x) = \\chi^\\prime(x) \n\\eeann\nwe find\n\\beann\n\\phi_{x,A}^\\prime(0) = \\Phi_{x,A}^\\prime(0)  \\Phi_{x,A}^\\prime(x)  \n\\eeann\nSo \\reff{trans} can be written as \n\\bea\nH_{\\Half \\setminus A} (0,x)  = \n[\\Phi_{x,A}^\\prime(0) \\Phi_{x,A}^\\prime(x)]^{5/8} H_\\Half(0,x) \n\\label{eqaa}\n\\eea\nwhere $\\Phi_{x,A}$ is any conformal map of $\\Half \\setminus A$ to $\\Half$ \nwhich fixes $0$ and $x$.\n\n\nNow let $\\Phi_A$ be a conformal map that maps $\\Half \\setminus A$\nonto $\\Half$ and fixes $0$ but not $x$. Let $\\lambda=\\Phi_A(x)/x$. \nThen $\\Phi_{x,A} = \\lambda^{-1} \\Phi_A$ fixes $x$, and so \\reff{eqaa}\nimplies\n\\beann\nH_{\\Half \\setminus A} (0,x)  = \n[\\Phi_A^\\prime(0) \\Phi_A^\\prime(x)]^{5/8} \\lambda^{-5/4} H_\\Half(0,x) \n\\label{eqbb}\n\\eeann\nUsing \\reff{scaling} we can rewrite this as \n\\bea\nH_{\\Half \\setminus A} (0,x)  = \n[\\Phi_A^\\prime(0) \\Phi_A^\\prime(x)]^{5/8} \\lambda^{\\rho-5/4} \nH_\\Half(0,\\Phi_A(x)) \n\\eea\n\nUntil now we have been assuming the conformal map $\\Phi_A$ fixes $0$. \nBy adding a real constant to the map we can relax this constraint. \nSince $H_\\Half(x,y) = H_\\Half(y-x)$, we conclude that for any \nconformal map of $\\Half \\setminus A$ to $\\Half$, \n\\bea\nH_{\\Half \\setminus A} (0,x)  = \n[\\Phi_A^\\prime(0) \\Phi_A^\\prime(x)]^{5/8} \\lambda^{\\rho-5/4} \nH_\\Half(\\Phi_A(0),\\Phi_A(x)) \n\\eea\nIf $\\rho=5/4$ this estabilishes \\reff{eqzz} for a limited \nclass of domains. \n\n\n\\end{document}\n\\end", "meta": {"hexsha": "44a83a3fbc98b5f01d66deb3b5f856b6a3d25773", "size": 8252, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/sle_partition_func.tex", "max_stars_repo_name": "johnkerl/bridge-walk-count", "max_stars_repo_head_hexsha": "d17765e9376c11a858f7f7a9627ab70648b12c9c", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-06T17:12:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-06T17:12:21.000Z", "max_issues_repo_path": "doc/sle_partition_func.tex", "max_issues_repo_name": "johnkerl/bridge-walk-count", "max_issues_repo_head_hexsha": "d17765e9376c11a858f7f7a9627ab70648b12c9c", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/sle_partition_func.tex", "max_forks_repo_name": "johnkerl/bridge-walk-count", "max_forks_repo_head_hexsha": "d17765e9376c11a858f7f7a9627ab70648b12c9c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.562962963, "max_line_length": 79, "alphanum_fraction": 0.6528114397, "num_tokens": 3121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.33781786449049017}}
{"text": "\\documentclass{article}\n\n\\usepackage{amsmath,amssymb,amsthm,graphicx}\n\\usepackage{fullpage}\n\\usepackage{caption,subcaption}\n\\newtheorem{prob}{Problem}\n\\newtheorem{theorem}{Theorem}[section]\n\\newtheorem{lemma}{Lemma}[section]\n\n\\newenvironment{problem}\n{\n\\renewcommand{\\labelenumi}{(\\alph{enumi})}\n\\renewcommand{\\labelenumii}{\\roman{enumii}.}\n\\begin{prob}\n}\n{\n\\end{prob}\n }\n \\newcommand{\\N}{\\mathbb{N}}\n \\newcommand{\\Z}{\\mathbb{Z}}\n \\newcommand{\\Q}{\\mathbb{Q}}\n \\newcommand{\\R}{\\mathbb{R}}\n \\newcommand{\\C}{\\mathbb{C}}\n \\newcommand{\\bM}{\\begin{bmatrix}}\n \\newcommand{\\eM}{\\end{bmatrix}}\n \\newcommand{\\Ni}{\\N\\cup\\{\\infty\\}}\n  \\newcommand{\\rmD}[1]{\\mathrm{d}#1}\n\\newcommand{\\floor}[1]{\\lfloor #1 \\rfloor}\n\\title{Optimal Path Planning for Robotic Arms in Household Assistance}\n\\author{Vikram Sunder and Zachary Greenberg}\n\n\\begin{document}\n\n\\maketitle\n\n\\section{Abstract}\nWe investigated and implemented motion planning algorithms for a robotic arm. The algorithm computes a shortest path in a given metric space.  To find the optimal path, we considered various metrics on a graph in Configuration Space. For example we considered the Euclidean distance in work space, energy needed to transition between states, and the energy required to hold an object in the gripper. Currently we have a small mobile robot with a five degrees of freedom arm. The overall objective is for the robot to help with small household tasks. We simulated the motion of the arm in Matlab to evaluate the various paths. \n\n\\section{Introduction}\nOne of the main problems with bringing robots into the home is the cost of hight precision parts. Currently the cost of quality robotic arms is far beyond the price range of the average household. While they might be more accessible in the future, we want to experiment with a lower cost robotic arm currently available. The trade off here is decreased power and precession. Our robot has a small 5 degree of freedom arm, that we hope to use to pick up plates/cups or open doors. However, to maximize the set of objects we can manipulate and the duration of time that we can carry out interactions we need minimize the length of individual interactions and the energy required to carry them out.  The longer our arm takes to manipulate an object the more power it will consume from its highly limited power source.  Likewise the more torque required from the servos will translate to increased current draw and minimize the weight of the objects we can manipulate.  As such we must optimize our trajectories to meet these goals.  \n\n\\section{The Robot}\nOur robot uses Willow Garage's Turtlebot as a base. On top of this we have attached a PhantomX Reactor robotic arm. This arm has 5 degrees of freedom. It can rotate about the base to select a particular plane of motion.  There are then three degrees of freedom in this particular plane.  The last degree of freedom is a wrist joint. \\ref{fig:DHparam} for the Denavit-Hartenberg parameters for the robot. \\\\\n\\begin{figure}[hb]\n\\centering\n\\begin{tabular}{|r|c|c|c|c|}\n\\hline\n&$\\alpha$ & a & d & $\\theta$\\\\\n\\hline\n\\hline\n1& $\\frac{\\pi}{2}$ & 0 & 26.5 & $\\theta_0$\\\\\n\\hline\n2& 0 & 150 & 0 & $\\frac{\\pi}{2}+\\theta_1$\\\\\n\\hline\n3& 0 & 150 & 0 & $\\theta_2$\\\\\n\\hline\n4& $\\frac{\\pi}{2}$& 0 & 0 & $\\frac{\\pi}{2}+\\theta_3$\\\\\n\\hline\n5& 0& 0& 116.525 & $\\theta_4$\\\\\n\\hline\n\\end{tabular}\n\\caption{Denavit Hartenberg Paramaters}\n\\label{fig:DHparam}\n\\end{figure} \\\\\nFor path planning there are a few convenient things about the forward kinematics for this robot. The first is that the final angle, $\\theta_4$ doesn't affect the final position of the robot. Therefore when searching configuration space, any algorithm doesn't need to search changes in $\\theta_4$. Similarly $\\theta_0$ only affects what plane the robot needs to be in. In a configuration space only constrained by angle limits, it is a simple computation to figure out what plane the goal point is in. Then $\\theta_0$ can be calculated to point the arm in that plane. Thus we only have to search the space defined by $\\theta_1,\\theta_2,\\theta_3$. This cuts the search space from a five dimensional space to a three dimensional space. It also solves one workspace variable, which leaves only $x,z,\\alpha$ where $\\alpha$ is the pitch of the end effector. \n\\section{Path Planning}\nInstead of computing the inverse kinematics for the arm, we decided to search the configuration space using a shortest path algorithm and use the forward kinematics to stop. From above we saw that only 3 angles had to be searched over. From there we discretized the space by placing nodes at even intervals along all three dimensions. Let a tick be the length of the intervals in radians. Then we connected any two nodes that differed by one tick in some coordinate. This created a graph to search over. Currently we are using a tick size of $\\frac{\\pi}{100}$ radians, but eventually a tick will correspond to the precision of the servos. This tick size gave us enough precision to find smooth paths, without making the graph too big.\\\\\nWe considered several search algorithms for the graph and eventually settled on $A^*$. We looked into $D*$, but since we chose not to consider any moving obstacles, we did not have to recompute the paths as we searched. This meant that the added complexity of $D*$ wasn't helpful. $D*$ also isn't any faster then $A*$ to find the initial path. The other search algorithm we considered was RRT. RRT is fast, but does guarantee an optimal path. The advantage of RRT is its ability to search high-dimensional non-convex spaces.  Given the number of degrees of freedom available to us this is not advantageous or necessary. Once we optimized our $A^*$ code for speed, it was fast enough to search the entire space. This combined with the simplicity of $A^*$ made it the best choice.\\\\\nThe next thing that we needed to do was find a consistent and admissible heuristic. The simplest metric we could use was the Euclidean distance in the work space between the nodes. The standard heuristic for this space is the euclidean distance to the target. When we changed the metric, we wanted an easy way to determine a heuristic. So for every new metric we added the cost to the euclidean distance. Let $c(v,w)$ be the added cost function. Let $d(v,w)$ be the euclidean distance between the nodes. So the weight of an edge $(u,v)$ is $c(v,w)+d(v,w)$. Then let $h(v)$ be the distance from $v$ to the target, $g$. So for an edge $(u,v)$ we have:\n\\begin{align*}\nh(v) =& d(v,g)\\\\\n\\leq& d(v,w) + d(w,g) & \\text{[triangle inequality]}\\\\\n\\leq& d(v,w) + c(v,w) + d(w,g) & [c(v,w)>0]\\\\\n\\leq& w(\\{u,v\\}) +h(g)\n\\end{align*}\nSo as long as our additional cost is always positive, the standard distance heuristic is always consistent. \n\n\\section{Metrics }\n\\subsection{Euclidean Work Space}\nThe first metric we tried was looking at the euclidean distance in the work space. So if $FK$ was the function that maps angles to work space, the cost between nodes $u$ and $v$ is $d_{e}(FK(u),FK(v))$. In path planning in addition to specifying a position we might want to specify an orientation of the arm. For this arm the orientation we care about is the sum of $\\theta_1,\\theta_2,\\theta_3$, which we will call $\\alpha$.\nSo we will add to the distance between nodes $|\\Delta\\alpha|$ and add $|\\alpha- \\alpha_{target}|$ to the heuristic. Everything is still consistent so $A^*$ still works. This gives two different metrics, the basic distance, which considers orientation, and the no-alpha metric, which does not. See Figure {fig:basicPaths} to see the difference in the paths found for each metric.\\\\\n\\begin{figure}[htb]\n\\centering\n\\begin{subfigure}[b]{0.5\\textwidth}\n\\centering\n\\includegraphics[scale=.5]{PathPics/Basic_Path.jpg}\n\\caption{Orientation Path}\n\\end{subfigure}%\n~ \n\\begin{subfigure}[b]{0.5\\textwidth}\n\\centering\n\\includegraphics[scale=.5]{PathPics/NoAlpha_Path.jpg}\n\\caption{No Orientation Path}\n\\end{subfigure}\n\n\\caption{Euclidean Distance Paths}\n\\label{fig:basicPaths}\n\\end{figure}\\\\ \n\n\\subsection{State Maintenance Method 1}\n\n\tFrom here, so long as we add positive weights to the existing costs of edges in our graph our heuristic will remain consistent and admissible.  Power is a major constraint for our robot. The amount of force the arm can output is highly limited, as is the amount of power available to the robot to carry out its various actions and functions.  As such we want to make all our motions as energy efficient as possible.  To do this we used the fact that the torque output of every actuator correlates to its energy consumption.  Therefore we will attempt to minimize the sum of the total torque of each state on a given path.  Let J be the Jacobian of the forward kinematic map of our robotic arm.  The Jacobian transpose will provide us with a linear map from forces applied by the arm to the output torques of the individual joints.  Thus we can calculate the torques required to generate a force at the end effector to counteract the force of gravity on object we are manipulating.   The cost of the edge between two configuration states $u$ and $v$ is as follows:\n\t\n\\[\td(u,v) =  \\left\\|(FK(u)-FK(v))\\right\\|^2 + \\left\\|J^T_v\\bM 0 \\\\ 0 \\\\ mg \\eM\\right\\|^2\\]\nFigure \\ref{fig:EnergyPaths1} shows the different paths obtained by considering this energy. \n\\begin{figure}[htb]\n\\centering\n\\begin{subfigure}[b]{0.5\\textwidth}\n\\centering\n\\includegraphics[scale=.3]{PathPics/Wrench_Path.jpg}\n\\caption{Orientation Path}\n\\end{subfigure}%\n~ \n\\begin{subfigure}[b]{0.5\\textwidth}\n\\centering\n\\includegraphics[scale=.3]{PathPics/Wrench_NoAlpha_Path.jpg}\n\\caption{No Orientation Path}\n\\end{subfigure}\n\n\\caption{Paths When Considering Energy To Hold Up an Object}\n\\label{fig:EnergyPaths1}\n\\end{figure}\\\\\n\\subsection{State Maintenance Method 2}\n\n\tOne of the issues with this is that it does not take into account the transition from one state to the next.  To do this we use the ratio of the torque at the new state to the torque at the old state.  This causes a transition to a state that requires more torque to have a higher cost and a transition to a lower state have lower cost.  Our cost function here where u is the initial state and v is the next state is as follows:\n\t\n\t \\[\td(u,v) =  \\left\\|(FK(u)-FK(v))\\right\\|^2 + \\frac{\\left\\|J^T_v\\bM 0 \\\\ 0 \\\\ mg \\eM\\right\\|^2}{\\left\\|J^T_u\\bM 0 \\\\ 0 \\\\ mg \\eM\\right\\|^2}\\]\n\t \nFigure \\ref{fig:EnergyPaths2} compares taking the ratio of these torques to the original formulation, of looking at the torque needed to hold the next state. You can see that the ratio of torques resulted in a shorter, smoother path to the goal.\\\\\n\\begin{figure}[htb]\n\\centering\n\\begin{subfigure}[b]{0.5\\textwidth}\n\\centering\n\\includegraphics[scale=.3]{PathPics/Wrench_Path.jpg}\n\\caption{Path When Only Considering The Next State}\n\\end{subfigure}%\n~ \n\\begin{subfigure}[b]{0.5\\textwidth}\n\\centering\n\\includegraphics[scale=.3]{PathPics/Wrench_Ratio_Path.jpg}\n\\caption{Path for Ratio of Torques}\n\\end{subfigure}\n\n\\caption{Paths When Considering Energy To Hold Up an Object}\n\\label{fig:EnergyPaths2}\n\\end{figure}\\\\\n\n\\subsection{Kinetic Energy}\nThe final set of metrics we considered take into account the kinetic energy needed to move from state to state. To simplify this problem we assume the arm is massless except for a mass in the end effector. \\\\\nOnce again the Jacobian $J$, comes in handy as a map from from angular velocity to linear velocity. Let $\\dot{\\theta}$ be the difference in angles between the states $(u,v)$ divided by a time-step $h$. Then the linear kinetic energy of the object the arm is carrying is:\n \\[E_{linear} = \\frac{1}{2}m \\|J_u\\dot{\\theta}\\|^2\\]. \\\\\nFor angular kinetic energy we approximated the actual value. We assumed that each angle contributes equally to angular kinetic energy and rotates about the same point. This is a significant simplification, but it saves on computation time and complexity. In order to calculate the actual rotation energy, we would need to compute the locations of each joint, not just the end effector in the search, which is at least three times slower. With this approximation our angular kinetic energy is: \n\\[E_{angular} = \\frac{1}{2}m \\left\\|\\frac{\\Delta\\theta_1+\\Delta\\theta_2+\\Delta\\theta_3)}{h}\\right\\|^2\\]\nThe final metric we considered was the total kinetic energy between points, which is the sum of the previous two metrics.\\\\\nFigure \\ref{fig:KineticPaths} shows the paths for these three metrics. In this path you can see that the total kinetic energy path is identical to the linear kinetic energy path. This is most likely due to the level of approximation in our angular kinetic energy calculations.\\\\\n\\begin{figure}[htb]\n\\centering\n\\begin{subfigure}[b]{0.33\\textwidth}\n\\centering\n\\includegraphics[scale=.33]{PathPics/Energy_Linear_Path.jpg}\n\\caption{Linear Kinetic Engery Path}\n\\end{subfigure}%\n~ \n\\begin{subfigure}[b]{0.33\\textwidth}\n\\centering\n\\includegraphics[scale=.33]{PathPics/Energy_Angular_Path.jpg}\n\\caption{Angular Kinetic Energy Path}\n\\end{subfigure}%\n~ \n\\begin{subfigure}[b]{0.33\\textwidth}\n\\centering\n\\includegraphics[scale=.33]{PathPics/Energy_Kinetic_Path.jpg}\n\\caption{Total Kinetic Energy Path}\n\\end{subfigure}\n\n\\caption{Paths When Considering Kinetic Energy}\n\\label{fig:EnergyPaths2}\n\\end{figure}\\\\\n\\section{Conclusion}\nOverall the smoothest path we found was paths that accounted for the total/linear kinetic energy. In this case we specified position and orientation and still found a smooth path to the goal. Using just Euclidean distance if we don't care about orientation the algorithm finds a smooth path. But when trying to find a path with orientation as well it moves into position and then struggles to change orientation without moving too far away from the target. By considering the energies the algorithm can find paths that change orientation on the way even if takes more distance. \\\\\nIn practice specifying orientation of the arm will be important. In order to pick up objects, the arm must grip them in a specific way and then place them the right way up. If the path planning can't specify an angle it won't be able to do this. Therefore either including kinetic energy or the cost of holding a position is important for getting smooth paths. Which of these two methods to use depends on the weight of the object you are holding and how long it will stay at each state.\n\\section{Future Work}\nIn the future there are several other metrics to consider. One thing to do is to remove the approximations on angular kinetic energy to get a better optimization. Another metric to consider would be the combination of the Kinetic Energy with the cost to hold up an object. These two costs would need to be scaled appropriately to determine which was more important. In general we can continue to work on developing a more accurate physics model of the arm to accurately determine the cost of individual motions. \\\\\nAnother way to improve the smoothness of the paths found is to make the tick size smaller. This increases the size of the grid, but lets the robot check more paths. Unfortunately the complexity of the problem is cubic in the grid size, so even small increases in size quickly become too expensive to compute. This is especially true, if the cost of each edge is doing a lot of complicated forward kinematics for each joint and energy calculations.\\\\\nOutside of our simulation, the robot will need to navigate in a house to perform tasks. So it will need to plan a path to move before, it plans a path for the arm. Choosing where to move is another optimization problem in and of itself. There is a shell in the workspace of the arm, where it is more maneuverable and can reach more orientations. Ideally a complete path planning algorithm would move the robot so that the target is in that zone. Alternatively we can relax the constraints on arm position and use the addition of the mobile base to enhance possible manipulations\\\\\nFinally this algorithm needs to move beyond simulation and on to an actual robot. In practice it might be apparent that certain paths are less prone to drifting and accumulating error. This would provided a decisive case for one metric over the other. \n\\end{document}", "meta": {"hexsha": "675c12a1bee0746cc4afcbe41087e2ab3982f5da", "size": 16168, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Documentation/Arm Planning/finalReport.tex", "max_stars_repo_name": "Boberito25/ButlerBot", "max_stars_repo_head_hexsha": "959f961bbc8c43be0ccb533dd2e2af5c55b0cc2a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Documentation/Arm Planning/finalReport.tex", "max_issues_repo_name": "Boberito25/ButlerBot", "max_issues_repo_head_hexsha": "959f961bbc8c43be0ccb533dd2e2af5c55b0cc2a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-06-08T19:55:40.000Z", "max_issues_repo_issues_event_max_datetime": "2015-06-08T19:55:40.000Z", "max_forks_repo_path": "Documentation/Arm Planning/finalReport.tex", "max_forks_repo_name": "Boberito25/ButlerBot", "max_forks_repo_head_hexsha": "959f961bbc8c43be0ccb533dd2e2af5c55b0cc2a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 86.4598930481, "max_line_length": 1064, "alphanum_fraction": 0.7692973775, "num_tokens": 4067, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.33781786449049017}}
{"text": "\\paragraph{}\nThe several algorithms that are being used warrant having some high-level pseudocode written in order to better explain their operation in the programming, those that where omitted are either highly implementation specific or basic equations.\n\n\\setcounter{algorithm}{1}\n\n\\begin{algorithm}[H]\n\\caption{Calculation of All Forces}\n\\begin{algorithmic}[1]\n\\FOR{$Body_A \\leftarrow 1$ \\TO Bodies} \n  \\FOR{$Body_B \\leftarrow (Body_A-1)$ \\TO Bodies}\n    \\IF{$Body_B \\neq Body_A$}\n      \\STATE $Matrix_F[Body_A][Body_B] \\leftarrow calculateForce(Body_A, Body_B, x)$\n      \\STATE $Matrix_F[Body_B][Body_A] \\leftarrow calculateForce(Body_A, Body_B, y)$\n    \\ENDIF\n  \\ENDFOR\n\\ENDFOR\n\\end{algorithmic}\n\\end{algorithm}\n\n\\begin{algorithm}[H]\n\\caption{Summation of All Forces}\n\\begin{algorithmic}[1]\n\\FOR{$Body_A \\leftarrow 1$ \\TO Bodies} \n  \\FOR{$Body_B \\leftarrow 1$ \\TO Bodies}\n    \\IF{$Body_B \\neq Body_A$}\n      \\IF{$Body_B < BodyA$}\n        \\STATE $Body[xAccess]_F~-\\leftarrow Matrix_F[Body_B][Body_A]$\n        \\STATE $Body[yAccess]_F~+\\leftarrow Matrix_F[Body_A][Body_B]$   \n      \\ELSE\n        \\STATE $Body[xAccess]_F~+\\leftarrow Matrix_F[Body_A][Body_B]$\n        \\STATE $Body[yAccess]_F~-\\leftarrow Matrix_F[Body_B][Body_A]$      \n      \\ENDIF\n    \\ENDIF\n  \\ENDFOR\n\\ENDFOR\n\\end{algorithmic}\n\\end{algorithm}\n\n\\begin{algorithm}[H]\n\\caption{Integration of New Position}\n\\begin{algorithmic}[1]\n\\IF{$ScenarioChange$}\n  \\STATE $CalculateForceMatrix()$\n  \\STATE $SumAllForcesToBodies()$\n  \\STATE\n  \\FOR{$bC \\leftarrow 1$ \\TO $Bodies$}\n    \\STATE \\COMMENT{Acceleration}\n    \\STATE $Body[bC]_{ax} \\leftarrow Body[bC]_{Fx}/Body[bC]_{m})$\n    \\STATE $Body[bC]_{ay} \\leftarrow Body[bC]_{Fy}/Body[bC]_{m})$\n  \\ENDFOR\n  \\STATE\n  \\STATE $ScenarioChange \\leftarrow false$\n\\ENDIF\n\\STATE\n\\FOR{$bC \\leftarrow 1$ \\TO $Bodies$}\n  \\STATE \\COMMENT{Half-Velocity}\n  \\STATE $Body[bC]_{vx} ~+\\leftarrow 0.5(Body[bC]_{ax}\\times\\Delta{t})$\n  \\STATE $Body[bC]_{vy} ~+\\leftarrow 0.5(Body[bC]_{ay}\\times\\Delta{t})$\n  \\STATE \\COMMENT{Position}\n  \\STATE $Body[bC]_{rx} ~+\\leftarrow Body[bC]_{vx}\\times\\Delta{t}$\n  \\STATE $Body[bC]_{ry} ~+\\leftarrow Body[bC]_{vy}\\times\\Delta{t}$\n\\ENDFOR\n\\STATE\n\\STATE $CheckCollisions()$\n\\STATE\n\\STATE $CalculateForceMatrix()$\n\\STATE $SumAllForcesToBodies()$\n\\STATE\n\\FOR{$bC \\leftarrow 1$ \\TO $Bodies$}\n  \\STATE \\COMMENT{Acceleration}    \n  \\STATE $Body[bC]_{ax} \\leftarrow Body[bC]_{Fx}/Body[bC]_{m})$\n  \\STATE $Body[bC]_{ay} \\leftarrow Body[bC]_{Fy}/Body[bC]_{m})$\n  \\STATE \\COMMENT{Half-Velocity}\n  \\STATE $Body[bC]_{vx} ~+\\leftarrow 0.5(Body[bC]_{ax}\\times\\Delta{t})$\n  \\STATE $Body[bC]_{vy} ~+\\leftarrow 0.5(Body[bC]_{ay}\\times\\Delta{t})$\n\\ENDFOR\n\\end{algorithmic}\n\\end{algorithm}\n\n\\begin{algorithm}[H]\n\\caption{Collision Detection and Simulation}\n\\begin{algorithmic}[1]\n\\FOR{$bC_A \\leftarrow 1$ \\TO $Bodies$} \n  \\FOR{$bC_B \\leftarrow (bC_A-1)$ \\TO $Bodies$}\n    \\IF{$bC_B \\neq bC_A$}\n      \\STATE $Distance \\leftarrow calculateDistance(bC_A, bC_B)$\n      \\IF{$Distance < (Body[bC_A]_r+Body[bC_B]_r)$)}\n        \\STATE $p_{x} \\leftarrow ((Body[bC_A]_m \\cdot Body[bC_A]_{vx}) + (Body[bC_B]_m \\cdot Body[bC_B]_{vx}))$\n        \\STATE $p_{y} \\leftarrow ((Body[bC_A]_m \\cdot Body[bC_A]_{vy}) + (Body[bC_B]_m \\cdot Body[bC_B]_{vy}))$\n        \\STATE\n        \\STATE $Body[bC_A]_m \\leftarrow (Body[bC_A]_m+Body[bC_B]_m)$\n        \\STATE $Body[bC_A]_{vx} \\leftarrow (p_{x}/Body[bC_A]_m)$\n        \\STATE $Body[bC_A]_{vy} \\leftarrow (p_{y}/Body[bC_A]_m)$\n        \\STATE\n        \\STATE $DeleteBody(bC_B)$\n      \\ENDIF\n    \\ENDIF\n  \\ENDFOR\n\\ENDFOR\n\\end{algorithmic}\n\\end{algorithm}", "meta": {"hexsha": "95b72fa26a26eddc368c0708ed8e2ca0aff841fc", "size": 3575, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/tex/sections/design/pseudocode.tex", "max_stars_repo_name": "btheobald/compa2", "max_stars_repo_head_hexsha": "aa9d5b966fb4c6a4e836e481d9df1bd297de3140", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-02-11T20:01:26.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-30T16:16:02.000Z", "max_issues_repo_path": "doc/tex/sections/design/pseudocode.tex", "max_issues_repo_name": "btheobald/compa2", "max_issues_repo_head_hexsha": "aa9d5b966fb4c6a4e836e481d9df1bd297de3140", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/tex/sections/design/pseudocode.tex", "max_forks_repo_name": "btheobald/compa2", "max_forks_repo_head_hexsha": "aa9d5b966fb4c6a4e836e481d9df1bd297de3140", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.396039604, "max_line_length": 242, "alphanum_fraction": 0.6676923077, "num_tokens": 1321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3377326251886422}}
{"text": "\\chapter{Type theoretic descent}\\label{chap:descent}\n\nIn this chapter we study homotopy pushouts, which were established as higher inductive types in homotopy type theory in section 6.8 of \\cite{hottbook}. From this chapter on, we will assume that universes are closed under homotopy pushouts. This is the last assumption that we will be making in the present work. In particular, we will not assume the existence of higher inductive types with some self-reference in the constructors (e.g.~the propositional truncation).\n\nOur first main result is the descent theorem for homotopy pushouts (\\cref{thm:descent,cor:descent_fib}), in which we establish that a cartesian transformation of spans\n\\begin{equation*}\n\\begin{tikzcd}\nA' \\arrow[d]  & S' \\arrow[l] \\arrow[r] \\arrow[d] \\arrow[dl,phantom,\"\\llcorner\" very near start] \\arrow[dr,phantom,\"\\lrcorner\" very near start] & B' \\arrow[d] \\\\\nA & S \\arrow[l] \\arrow[r] & B\n\\end{tikzcd}\n\\end{equation*}\nextends uniquely to a cartesian transformation of the pushout squares, i.e. a commuting cube\n\\begin{equation*}\n\\begin{tikzcd}\n& S' \\arrow[dl] \\arrow[dr] \\arrow[d] \\\\\nA' \\arrow[d] & S \\arrow[dl] \\arrow[dr] & B' \\arrow[dl,crossing over] \\arrow[d] \\\\\nA \\arrow[dr] & A'\\sqcup^{S'}B' \\arrow[d] \\arrow[from=ul,crossing over] & B \\arrow[dl] \\\\\n& A\\sqcup^S B\n\\end{tikzcd}\n\\end{equation*}\nof which the vertical sides are pullback squares.\n\nThe second main theorem of this chapter, \\cref{thm:cartesian_cube}, is an adaption to homotopy type theory of a theorem due to \\cite{AnelBiedermanFinsterJoyal}. It is closely related to the descent theorem but can be stated without a universe: for any commuting cube\n\\begin{equation*}\n\\begin{tikzcd}\n& S' \\arrow[dl] \\arrow[dr] \\arrow[d] \\\\\nA' \\arrow[d] & S \\arrow[dl] \\arrow[dr] & B' \\arrow[dl,crossing over] \\arrow[d] \\\\\nA \\arrow[dr] & X' \\arrow[d] \\arrow[from=ul,crossing over] & B \\arrow[dl] \\\\\n& X\n\\end{tikzcd}\n\\end{equation*}\nof which the two vertical back squares are pullback squares, the two vertical front squares are pullback squares if and only if the square\n\\begin{equation*}\n\\begin{tikzcd}\nA' \\sqcup^{S'} B' \\arrow[r] \\arrow[d] & X' \\arrow[d] \\\\\nA\\sqcup^{S} B \\arrow[r] & X.\n\\end{tikzcd}\n\\end{equation*}\nis a pullback square. Even though this statement does not involve a universe, we use the univalence axiom in our proof that this square being pullback implies that the front two vertical squares of the cube are pullback squares. Function extensionality suffices for the converse direction.\n\n\\section{Homotopy pushouts}\n\n\\subsection{Pushouts as higher inductive types}\n\n\\begin{defn}\nA \\define{span} $\\mathcal{S}$ from $A$ to $B$ is a triple $(S,f,g)$ consisting of a type $S$ and maps $f:S\\to A$ and $g:S\\to B$. We write $\\mathsf{span}(A,B)$ for the type of small spans from $A$ to $B$. \n\\end{defn}\n\n\\begin{defn}\nConsider a span $\\mathcal{S}\\jdeq (S,f,g)$ from $A$ to $B$, and let $X$ be a type. A cocone with vertex $X$ on $\\mathcal{S}$ is a triple $(i,j,H)$ consisting of maps $i:A\\to X$, $j:B\\to X$, and a homotopy $H:i\\circ f\\htpy j\\circ g$ witnessing that the square\n\\begin{equation*}\n\\begin{tikzcd}\nS \\arrow[d,swap,\"f\"] \\arrow[r,\"g\"] & B \\arrow[d,\"j\"] \\\\\nA \\arrow[r,swap,\"i\"] & X\n\\end{tikzcd}\n\\end{equation*}\ncommutes. We write $\\mathsf{cocone}_{\\mathcal{S}}(X)$ for the type of cocones with vertex $X$ on $\\mathcal{S}$. \n\\end{defn}\n\n\\begin{defn}\nConsider a commuting square\n\\begin{equation*}\n\\begin{tikzcd}\nS \\arrow[d,swap,\"f\"] \\arrow[r,\"g\"] & B \\arrow[d,\"j\"] \\\\\nA \\arrow[r,swap,\"i\"] & X,\n\\end{tikzcd}\n\\end{equation*}\nwith $H:i\\circ f\\htpy j\\circ g$, and let $Y$ be a type. We define the operation\n\\begin{equation*}\n\\mathsf{cocone\\usc{}map}((i,j,H),Y) \\defeq (X\\to Y) \\to \\mathsf{cocone}_{\\mathcal{S}}(Y).\n\\end{equation*}\nby $h\\mapsto (h\\circ i,h\\circ j,h\\cdot H)$. \n\\end{defn}\n\n\\begin{defn}\nA commuting square\n\\begin{equation*}\n\\begin{tikzcd}\nS \\arrow[r,\"g\"] \\arrow[d,swap,\"f\"] & B \\arrow[d,\"j\"] \\\\\nA \\arrow[r,swap,\"i\"] & X\n\\end{tikzcd}\n\\end{equation*}\nwith $H:i\\circ f \\htpy j\\circ g$ is said to be a \\define{(homotopy) pushout square}\\index{pushout square} if the cocone $(i,j,H)$ with vertex $X$ on the span $\\mathcal{S}\\jdeq (S,f,g)$\nsatisfies the \\define{universal property of pushouts}\\index{universal property!of pushouts|textbf}, which asserts that the map\n\\begin{equation*}\n\\mathsf{cocone\\usc{}map}(i,j,H):(X\\to Y)\\to \\mathsf{cocone}(Y)\n\\end{equation*}\nis an equivalence for any type $Y$. Sometimes pushout squares are also called \\define{cocartesian squares}\\index{cocartesian square|textbf}.\n\\end{defn}\n\n\\begin{defn}\nConsider a pushout square\n\\begin{equation*}\n\\begin{tikzcd}\nS \\arrow[r,\"g\"] \\arrow[d,swap,\"f\"] & B \\arrow[d,\"j\"] \\\\\nA \\arrow[r,swap,\"i\"] & X\n\\end{tikzcd}\n\\end{equation*}\nwith $H:i\\circ f \\htpy j\\circ g$, and consider a cocone $(i',j',H')$ with vertex $Y$ on the same span $\\mathcal{S}\\jdeq(S,f,g)$. Then the unique map $h:X\\to Y$ such that \n\\begin{equation*}\n\\mathsf{cocone\\usc{}map}((i,j,H),Y,h)= (i',j',H')\n\\end{equation*}\nis called the \\define{cogap map} of $(i',j',H')$. We also write $\\mathsf{cogap}(i',j',H')$ for the cogap map, and we write\n\\begin{align*}\n\\mathsf{left\\usc{}comp}(i',j',H') & : i' \\htpy \\mathsf{cogap}(i',j',H')\\circ \\inl  \\\\\n\\mathsf{right\\usc{}comp}(i',j',H') & : j' \\htpy \\mathsf{cogap}(i',j',H')\\circ \\inr  \\\\\n\\mathsf{coh\\usc{}comp}(i',j',H') & : \\ct{(\\mathsf{left\\usc{}comp}(i',j',H')\\cdot g)}{H'} \\htpy \\ct{(\\mathsf{cogap}(i',j',H')\\cdot \\glue)}{(\\mathsf{right\\usc{}comp}(i',j',H')\\cdot f)}.\n\\end{align*}\nfor the homotopies determining the uniqueness of $\\mathsf{cogap}(i',j',H')$.\n\\end{defn}\n\n\\begin{prp}\\label{thm:pushout_up}\nConsider a commuting square\\index{universal property!of pushouts|textit}\n\\begin{equation*}\n\\begin{tikzcd}\nS \\arrow[r,\"g\"] \\arrow[d,swap,\"f\"] & B \\arrow[d,\"j\"] \\\\\nA \\arrow[r,swap,\"i\"] & X,\n\\end{tikzcd}\n\\end{equation*}\nwith $H:i\\circ f\\htpy j\\circ g$. The following are equivalent:\n\\begin{enumerate}\n\\item The square is a pushout square.\n\\item The square\n\\begin{equation*}\n\\begin{tikzcd}\nY^X \\arrow[r,\"\\blank\\circ j\"] \\arrow[d,swap,\"\\blank\\circ i\"] & Y^B \\arrow[d,\"\\blank\\circ g\"] \\\\\nY^A \\arrow[r,swap,\"\\blank\\circ f\"] & Y^S,\n\\end{tikzcd}\n\\end{equation*}\nwhich commutes by the homotopy\n\\begin{equation*}\n\\lam{h} \\mathsf{eq\\usc{}htpy}(h\\cdot H),\n\\end{equation*}\nis a pullback square, for every type $Y$.\n\\item For every type family $P$ over $X$, the square\n\\begin{equation*}\n\\begin{tikzcd}[column sep=9em]\n\\prd{x:X}P(x) \\arrow[r,\"\\blank\\circ j\"] \\arrow[d,swap,\"\\blank\\circ i\"] & \\prd{b:B}P(j(b)) \\arrow[d,\"\\blank\\circ g\"] \\\\\n\\prd{a:A}P(i(a)) \\arrow[r,swap,\"{\\lam{h}{x} \\tr_{P}(H(x),h(f(x)))}\"] & \\prd{x:S}P(j(g(x))),\n\\end{tikzcd}\n\\end{equation*}\nwhich commutes by the homotopy\n\\begin{equation*}\n\\lam{h}\\mathsf{eq\\usc{}htpy}(\\lam{x}\\apd{h}{H(x)})\n\\end{equation*}\nis a pullback square. This property is also called the \\define{dependent universal property of pushouts}.\n\\item The gap map of the square\n\\begin{equation*}\n\\begin{tikzcd}\n\\prd{x:X}P(x) \\arrow[r] \\arrow[d] & \\prd{b:B}P(j(b)) \\arrow[d] \\\\\n\\prd{a:A}P(i(a)) \\arrow[r] & \\prd{x:S}P(j(g(x)))\n\\end{tikzcd}\n\\end{equation*}\nhas a section, for any type family $P$ over $X$. This property is also called the \\define{induction principle of pushouts}.\n\\end{enumerate}\n\\end{prp}\n\n\\begin{defn}\nFrom now on we will assume that any span has a pushout, and moreover that universes are closed under pushouts. We will write $A\\sqcup^{\\mathcal{S}} B$ for the pushout of the span $\\mathcal{S}\\jdeq(S,f,g)$ from $A$ to $B$. The type $A\\sqcup^{\\mathcal{S}} B$ comes equipped with a colimiting cocone $(\\inl,\\inr,\\glue)$, as displayed in the pushout square\n\\begin{equation*}\n\\begin{tikzcd}\nS \\arrow[d,swap,\"f\"] \\arrow[r,\"g\"] & B \\arrow[d,\"\\inr\"] \\\\\nA \\arrow[r,swap,\"\\inl\"] & A \\sqcup^{\\mathcal{S}} B.\n\\end{tikzcd}\n\\end{equation*}\n\\end{defn}\n\n\\begin{rmk}\nWe note that if $\\mathcal{S}\\jdeq (S,f,g)$ is a span of \\emph{pointed} types and pointed maps between them, then the pushout $A\\sqcup^{\\mathcal{S}} B$ of $\\mathcal{S}$ is again a pointed type. The cocone $(\\inl,\\inr,\\glue)$ consists of two pointed maps and a pointed homotopy filling the square of pointed maps. Moreover, the pushout $A\\sqcup^{\\mathcal{S}} B$ satisfies a pointed version of the universal property: for any pointed type $Y$ the square\n\\begin{equation*}\n\\begin{tikzcd}\n(A\\sqcup^{\\mathcal{S}} B \\to_\\ast Y) \\arrow[r] \\arrow[d] & (B\\to_\\ast Y) \\arrow[d] \\\\\n(A\\to_\\ast Y) \\arrow[r] & (S\\to_\\ast Y)\n\\end{tikzcd}\n\\end{equation*}\nis a pullback square. \n\\end{rmk}\n\n\\subsection{Examples of pushouts}\n\n\\begin{defn}\nLet $X$ be a type. We define the \\define{suspension}\\index{suspension|textbf} $\\susp X$\\index{SX@{$\\susp X$}|textbf} of $X$ to be the pushout of the span\n\\begin{equation*}\n\\begin{tikzcd}\nX \\arrow[r] \\arrow[d] & \\unit \\arrow[d,\"\\inr\"] \\\\\n\\unit \\arrow[r,swap,\"\\inl\"] & \\susp X \n\\end{tikzcd}\n\\end{equation*}\nWe will write $\\north\\defeq\\inl(\\ttt)$ and $\\south\\defeq\\inr(\\ttt)$. \n\\end{defn}\n\n\\begin{rmk}By the universal property it follows that the map\n\\begin{equation*}\n(\\susp X \\to Y) \\to \\sm{y,y':Y}X\\to (y=y')\n\\end{equation*}\ngiven by $h\\mapsto (h(\\north),h(\\south),h\\cdot\\glue)$ is an equivalence. \n\nMoreover, if $X$ is a pointed type, then the suspension is considered to be a pointed type with base point $\\north$. By the universal property of $\\susp X$ it follows that the square\n\\begin{equation*}\n\\begin{tikzcd}\n(\\susp X\\to_\\ast Y) \\arrow[r] \\arrow[d] & (\\unit \\to_\\ast Y) \\arrow[d] \\\\\n(\\unit\\to_\\ast Y) \\arrow[r] & (X\\to_\\ast Y)\n\\end{tikzcd}\n\\end{equation*}\nis a pullback square. Since $\\unit\\to_\\ast Y$ is contractible, it follows that \n\\begin{equation*}\n(\\susp X\\to_\\ast Y) \\eqvsym \\loopspace{X\\to_\\ast Y} \\eqvsym X \\to_\\ast \\loopspace Y\n\\end{equation*}\n\\end{rmk}\n\n\\begin{defn}\nGiven a map $f:A\\to B$, we define the \\define{cofiber}\\index{cofiber|textbf} $\\mathsf{cof}_f$\\index{cofib_f@{$\\mathsf{cof}_f$}|textbf} of $f$ as the pushout\n\\begin{equation*}\n\\begin{tikzcd}\nA \\arrow[r,\"f\"] \\arrow[d] & B \\arrow[d,\"\\inr\"] \\\\\n\\unit \\arrow[r,swap,\"\\inl\"] & \\mathsf{cof}_f. \n\\end{tikzcd}\n\\end{equation*}\nThe cofiber of a map is sometimes also called the \\define{mapping cone}\\index{mapping cone|textbf}.\n\\end{defn}\n\n\\begin{defn}\nWe define the \\define{join}\\index{join} $\\join{X}{Y}$\\index{join X Y@{$\\join{X}{Y}$}|textbf} of $X$ and $Y$ to be the pushout \n\\begin{equation*}\n\\begin{tikzcd}\nX\\times Y \\arrow[r,\"\\proj 2\"] \\arrow[d,swap,\"\\proj 1\"] & Y \\arrow[d,\"\\inr\"] \\\\\nX \\arrow[r,swap,\"\\inl\"] & X \\ast Y. \n\\end{tikzcd}\n\\end{equation*}\n\\end{defn}\n\n\\begin{defn}\nWe define the \\define{$n$-sphere}\\index{n-sphere@{$n$-sphere}|textbf} $\\sphere{n}$\\index{Sn@{$\\sphere{n}$}|textbf} for any $n\\geq -1$ by induction on $n$, by taking\n\\begin{align*}\n\\sphere{-1} & \\defeq \\emptyt \\\\\n\\sphere{0} & \\defeq \\bool \\\\\n\\sphere{n+1} & \\defeq \\join{\\bool}{\\sphere{n}}.\n\\end{align*}\n\\end{defn}\n\n\n\\begin{defn}\nSuppose $A$ and $B$ are pointed types, with base points $a_0$ and $b_0$, respectively. The \\define{(binary) wedge}\\index{wedge@(binary) wedge|textbf} $A\\vee B$ of $A$ and $B$ is defined as the pushout\n\\begin{equation*}\n\\begin{tikzcd}\n\\bool \\arrow[r] \\arrow[d] & A+B \\arrow[d] \\\\\n\\unit \\arrow[r] & A\\vee B.\n\\end{tikzcd}\n\\end{equation*}\n\\end{defn}\n\n\\begin{defn}\nGiven a type $I$, and a family of pointed types $A$ over $i$, with base points $a_0(i)$. We define the \\define{(indexed) wedge}\\index{wedge@{(indexed) wedge}|textbf} $\\bigvee_{(i:I)}A_i$ as the pushout\n\\begin{equation*}\n\\begin{tikzcd}[column sep=huge]\nI \\arrow[d] \\arrow[r,\"{\\lam{i}(i,a_0(i))}\"] & \\sm{i:I}A_i \\arrow[d] \\\\\n\\unit \\arrow[r] & \\bigvee_{(i:I)} A_i.\n\\end{tikzcd}\n\\end{equation*}\n\\end{defn}\n\n\\begin{defn}\nSuppose $A$ and $B$ are pointed types. We define the \\define{wedge inclusion} $\\mathsf{wedge\\usc{}in}:A\\vee B\\to A\\times B$ to be the unique map obtained via the universal property of pushouts as indicated in the diagram\n\\begin{equation*}\n\\begin{tikzcd}\n\\unit \\arrow[d] \\arrow[r] &[1em] B \\arrow[d] \\arrow[ddr,bend left=15,\"{\\lam{b}(a_0,b)}\"] \\\\\nA \\arrow[r] \\arrow[drr,bend right=15,swap,\"{\\lam{a}(a,b_0)}\"] & A\\vee B \\arrow[dr,swap,\"\\mathsf{wedge\\usc{}in}\" near start] \\\\\n& & A \\times B.\n\\end{tikzcd}\n\\end{equation*}\nWe define the \\define{smash product} $A\\wedge B$ of $A$ and $B$ as the cofiber of the wedge inclusion, i.e.~as a pushout\n\\begin{equation*}\n\\begin{tikzcd}[column sep=large]\nA\\vee B \\arrow[r,\"\\mathsf{wedge\\usc{}in}\"] \\arrow[d] & A\\times B \\arrow[d] \\\\\n\\unit \\arrow[r] & A\\wedge B.\n\\end{tikzcd}\n\\end{equation*}\n\\end{defn}\n\n\\subsection{Properties of iterated pushouts}\nThe following corollary is also called the \\define{pasting property} of pullbacks.\\index{pasting property!of pullbacks|textit}\\marginnote{edit}\n\n\\begin{cor}\\label{thm:pb_pasting}\nConsider a commuting diagram of the form\n\\begin{equation*}\n\\begin{tikzcd}\nA \\arrow[r,\"k\"] \\arrow[d,swap,\"f\"] & B \\arrow[r,\"l\"] \\arrow[d,\"g\"] & C \\arrow[d,\"h\"] \\\\\nX \\arrow[r,swap,\"i\"] & Y \\arrow[r,swap,\"j\"] & Z\n\\end{tikzcd}\n\\end{equation*}\nwith homotopies $H:i\\circ f\\htpy g\\circ k$ and $K:j\\circ g\\htpy h\\circ l$, and the homotopy\n\\begin{equation*}\n\\ct{(j\\cdot H)}{(K\\cdot k)}:j\\circ i\\circ f\\htpy h\\circ l\\circ k\n\\end{equation*}\nwitnessing that the outer rectangle commutes. Furthermore, suppose that the square on the right is a pullback square. Then the following are equivalent:\n\\begin{samepage}%\n\\begin{enumerate}\n\\item The square on the left is a pullback square.\n\\item The outer rectangle is a pullback square.\n\\end{enumerate}%\n\\end{samepage}%\n\\end{cor}\n\n\\begin{proof}\nThe commutativity of the two squares induces fiberwise transformations\n\\begin{align*}\n& \\prd{x:X}\\fib{f}{x}\\to \\fib{g}{i(x)} \\\\\n& \\prd{y:Y}\\fib{g}{y}\\to \\fib{h}{j(y)}.\n\\end{align*}\nBy the assumption that the square on the right is a pullback square, it follows from \\cref{cor:pb_fibequiv} that the fiberwise transformation\n\\begin{equation*}\n\\prd{y:Y}\\fib{g}{y}\\to\\fib{h}{j(y)}\n\\end{equation*}\nis a fiberwise equivalence. Therefore it follows from 3-for-2 property of equivalences that the fiberwise transformation\n\\begin{equation*}\n\\prd{x:X}\\fib{f}{x}\\to\\fib{g}{i(x)}\n\\end{equation*}\nis a fiberwise equivalence if and only if the fiberwise transformation\n\\begin{equation*}\n\\prd{x:X}\\fib{f}{x}\\to\\fib{h}{j(i(x))}\n\\end{equation*}\nis a fiberwise equivalence. Now the claim follows from one more application of \\cref{cor:pb_fibequiv}.\n\\end{proof}\n\n\\begin{cor}\nConsider a commuting cube\n\\begin{equation*}\n\\begin{tikzcd}\n& S' \\arrow[dl] \\arrow[dr] \\arrow[d] \\\\\nA' \\arrow[d] & S \\arrow[dl] \\arrow[dr] & B' \\arrow[dl,crossing over] \\arrow[d] \\\\\nA \\arrow[dr] & X' \\arrow[d] \\arrow[from=ul,crossing over] & B \\arrow[dl] \\\\\n& X,\n\\end{tikzcd}\n\\end{equation*}\nof which the two front squares are pullback squares. Then the back left square is a pullback square if and only if the back right square is a pullback square.\n\\end{cor}\n\n\\begin{prp}\\label{thm:pushout_pasting}\nConsider the following configuration of commuting squares:\\index{pushout!pasting property|textit}\\index{pasting property!for pushouts|textit}\n\\begin{equation*}\n\\begin{tikzcd}\nA \\arrow[r,\"i\"] \\arrow[d,swap,\"f\"] & B \\arrow[r,\"k\"] \\arrow[d,swap,\"g\"] & C \\arrow[d,\"h\"] \\\\\nX \\arrow[r,swap,\"j\"] & Y \\arrow[r,swap,\"l\"] & Z\n\\end{tikzcd}\n\\end{equation*}\nwith homotopies $H:j\\circ f\\htpy g\\circ i$ and $K:l\\circ g\\htpy h\\circ k$, and suppose that the square on the left is a pushout square. \nThen the square on the right is a pushout square if and only if the outer rectangle is a pushout square.\n\\end{prp}\n\n\\begin{proof}\nLet $T$ be a type. Taking the exponent $T^{(\\blank)}$ of the entire diagram of the statement of the theorem, we obtain the following commuting diagram\n\\begin{equation*}\n\\begin{tikzcd}\nT^Z \\arrow[r,\"\\blank\\circ l\"] \\arrow[d,swap,\"\\blank\\circ h\"] & T^Y \\arrow[d,swap,\"\\blank\\circ g\"] \\arrow[r,\"\\blank\\circ j\"] & T^X \\arrow[d,\"\\blank\\circ f\"] \\\\\nT^C \\arrow[r,swap,\"\\blank\\circ k\"] & T^B \\arrow[r,swap,\"\\blank\\circ i\"] & T^A.\n\\end{tikzcd}\n\\end{equation*}\nBy the assumption that $Y$ is the pushout of $B\\leftarrow A \\rightarrow X$, it follows that the square on the right is a pullback square. It follows by \\autoref{thm:pb_pasting} that the rectangle on the left is a pullback if and only if the outer rectangle is a pullback. Thus the statement follows by the second characterization in \\autoref{thm:pushout_up}.\n\\end{proof}\n\n\\begin{lem}\nConsider a map $f:A\\to B$. Then the cofiber of the map $\\inr:B\\to \\mathsf{cof}_f$ is equivalent to the suspension $\\susp{A}$ of $A$. \n\\end{lem}\n\n\\begin{prp}\nConsider a commuting square\n\\begin{equation*}\n\\begin{tikzcd}\nA \\arrow[r,\"i\"] \\arrow[d,swap,\"f\"] & B \\arrow[d,\"g\"] \\\\\nX \\arrow[r,swap,\"j\"] & Y\n\\end{tikzcd}\n\\end{equation*}\nand write $\\mathsf{cogap}: X\\sqcup^A B\\to Y$ for the cogap map. \nThen the square\n\\begin{equation*}\n\\begin{tikzcd}\n\\mathsf{cof}_f \\arrow[d] \\arrow[r] & \\mathsf{cof}_g \\arrow[d] \\\\\n\\unit \\arrow[r] & \\mathsf{cof}_{\\mathsf{cogap}}\n\\end{tikzcd}\n\\end{equation*}\nis a pushout square.\n\\end{prp}\n\n\\section{Descent for pushouts}\\label{sec:descent}\n\n\\subsection{Type families over pushouts}\n\n\\begin{defn}\nConsider a commuting square\n\\begin{equation*}\n\\begin{tikzcd}\nS \\arrow[r,\"g\"] \\arrow[d,swap,\"f\"] & B \\arrow[d,\"j\"] \\\\\nA \\arrow[r,swap,\"i\"] & X.\n\\end{tikzcd}\n\\end{equation*}\nwith $H:i\\circ f\\htpy j\\circ g$, where all types involved are in $\\UU$. The type $\\mathsf{Desc}(\\mathcal{S})$\\index{Desc@{$\\mathsf{Desc}(\\mathcal{S})$}|textbf} of \\define{descent data}\\index{descent data|textbf} for $X$, is defined to be the type of triples $(P_A,P_B,P_S)$ consisting of\n\\begin{align*}\nP_A & : A \\to \\UU \\\\\nP_B & : B \\to \\UU \\\\\nP_S & : \\prd{x:S} \\eqv{P_A(f(x))}{P_B(g(x))}.\n\\end{align*}\nFurthermore, we define the map\\index{desc_fam@{$\\mathsf{desc\\usc{}fam}_{\\mathcal{S}}$}|textbf}\n\\begin{equation*}\n\\mathsf{desc\\usc{}fam}_{\\mathcal{S}}(i,j,H) : (X\\to \\UU)\\to \\mathsf{Desc}(\\mathcal{S})\n\\end{equation*}\nby $P\\mapsto (P\\circ i,P\\circ j,\\lam{x}\\mathsf{tr}_P(H(x)))$.\n\\end{defn}\n\n\\begin{prp}\\label{thm:desc_fam}\nConsider a commuting square\n\\begin{equation*}\n\\begin{tikzcd}\nS \\arrow[r,\"g\"] \\arrow[d,swap,\"f\"] & B \\arrow[d,\"j\"] \\\\\nA \\arrow[r,swap,\"i\"] & X.\n\\end{tikzcd}\n\\end{equation*}\nwith $H:i\\circ f\\htpy j\\circ g$. If the square is a pushout square, then the function\\index{desc_fam@{$\\mathsf{desc\\usc{}fam}_{\\mathcal{S}}$}!is an equivalence|textit}\n\\begin{equation*}\n\\mathsf{desc\\usc{}fam}_{\\mathcal{S}}(i,j,H) : (X\\to \\UU)\\to \\mathsf{Desc}(\\mathcal{S})\n\\end{equation*}\nis an equivalence.\n\\end{prp}\n\n\\begin{proof}\nBy the 3-for-2 property of equivalences it suffices to construct an equivalence $\\varphi:\\mathsf{cocone}_{\\mathcal{S}}(\\UU)\\to\\mathsf{Desc}(\\mathcal{S})$ such that the triangle\n\\begin{equation*}\n\\begin{tikzcd}\n& \\UU^X \\arrow[dl,swap,\"{\\mathsf{cocone\\usc{}map}_{\\mathcal{S}}(i,j,H)}\"] \\arrow[dr,\"{\\mathsf{desc\\usc{}fam}_{\\mathcal{S}}(i,j,H)}\"] & \\phantom{\\mathsf{cocone}_{\\mathcal{S}}(\\UU)} \\\\\n\\mathsf{cocone}_{\\mathcal{S}}(\\UU) \\arrow[rr,densely dotted,\"\\eqvsym\",\"\\varphi\"'] & & \\mathsf{Desc}(\\mathcal{S})\n\\end{tikzcd}\n\\end{equation*}\ncommutes.\n\nSince we have equivalences\n\\begin{equation*}\n\\mathsf{equiv\\usc{}eq}:\\eqv{\\Big(P_A(f(x))=P_B(g(x))\\Big)}{\\Big(\\eqv{P_A(f(x))}{P_B(g(x))}\\Big)}\n\\end{equation*}\nfor all $x:S$, we obtain an equivalence on the dependent products\n\\begin{equation*}\n\\eqv{\\Big(\\prd{x:S}P_A(f(x))=P_B(g(x))\\Big)}{\\Big(\\prd{x:S}\\eqv{P_A(f(x))}{P_B(g(x))}\\Big)}.\n\\end{equation*}\nby post-composing with the equivalences $\\mathsf{equiv\\usc{}eq}$. \nWe define $\\varphi$ to be the induced map on total spaces. Explicitly, we have\n\\begin{equation*}\n\\varphi\\defeq \\lam{(P_A,P_B,K)}(P_A,P_B,\\lam{x}\\mathsf{equiv\\usc{}eq}(K(x))).\n\\end{equation*}\nThen $\\varphi$ is an equivalence by \\cref{thm:fib_equiv}, and the triangle commutes because there is a homotopy\n\\begin{equation*}\n\\mathsf{equiv\\usc{}eq}(\\ap{P}{H(x)}) \\htpy \\mathsf{tr}_P(H(x)). \\qedhere\n\\end{equation*}\n\\end{proof}\n\n\\begin{cor}\\label{cor:desc_fam}\nConsider descent data $(P_A,P_B,P_S)$ for a pushout square as in \\cref{thm:desc_fam}.\nThen the type of quadruples $(P,e_A,e_B,e_S)$ consisting of a family $P:X\\to\\UU$ equipped with fiberwise equivalences\n\\begin{samepage}\n\\begin{align*}\ne_A & : \\prd{a:A}\\eqv{P_A(a)}{P(i(a))} \\\\\ne_B & : \\prd{b:B}\\eqv{P_B(a)}{P(j(b))}\n\\end{align*}\n\\end{samepage}%\nand a homotopy $e_S$ witnessing that the square\n\\begin{equation*}\n\\begin{tikzcd}[column sep=huge]\nP_A(f(x)) \\arrow[r,\"e_A(f(x))\"] \\arrow[d,swap,\"P_S(x)\"] & P(i(f(x))) \\arrow[d,\"\\mathsf{tr}_P(H(x))\"] \\\\\nP_B(g(x)) \\arrow[r,swap,\"e_B(g(x))\"] & P(j(g(x)))\n\\end{tikzcd}\n\\end{equation*}\ncommutes, is contractible.\n\\end{cor}\n\n\\begin{proof}\nThe fiber of $\\mathsf{desc\\usc{}fam}_{\\mathcal{S}}(i,j,H)$ map at $(P_A,P_B,P_S)$ is equivalent to the type of quadruples $(P,e_A,e_B,e_S)$ as described in the theorem, which are contractible by \\cref{thm:contr_equiv}.\n\\end{proof}\n\nFor the remainder of this subsection we consider a pushout square\n\\begin{equation*}\n\\begin{tikzcd}\nS \\arrow[r,\"g\"] \\arrow[d,swap,\"f\"] & B \\arrow[d,\"j\"] \\\\\nA \\arrow[r,swap,\"i\"] & X.\n\\end{tikzcd}\n\\end{equation*}\nwith $H:i\\circ f\\htpy j\\circ g$, descent data\n\\begin{align*}\nP_A & : A \\to \\UU \\\\\nP_B & : B \\to \\UU \\\\\nP_S & : \\prd{x:S} \\eqv{P_A(f(x))}{P_B(g(x))},\n\\end{align*}\nand a family $P:X\\to\\UU$ equipped with \n\\begin{align*}\ne_A & : \\prd{a:A}\\eqv{P_A(a)}{P(i(a))} \\\\\ne_B & : \\prd{b:B}\\eqv{P_B(a)}{P(j(b))}\n\\end{align*}\nand a homotopy $e_S$ witnessing that the square\n\\begin{equation*}\n\\begin{tikzcd}[column sep=huge]\nP_A(f(x)) \\arrow[r,\"e_A(f(x))\"] \\arrow[d,swap,\"P_S(x)\"] & P(i(f(x))) \\arrow[d,\"\\mathsf{tr}_P(H(x))\"] \\\\\nP_B(g(x)) \\arrow[r,swap,\"e_B(g(x))\"] & P(j(g(x)))\n\\end{tikzcd}\n\\end{equation*}\ncommutes.\n\n\\begin{defn}\nWe define the commuting square\n\\begin{equation*}\n\\begin{tikzcd}[column sep=6em]\n\\sm{x:S}P_A(f(x)) \\arrow[d,swap,\"{f'\\,\\defeq\\,\\total[f]{\\lam{x}\\idfunc[P_A(f(x))]}}\"] \\arrow[r,\"{g'\\,\\defeq\\, \\total[g]{e_S}}\"] & \\sm{b:B}P_B(b) \\arrow[d,\"{j'\\,\\defeq\\, \\total[j]{e_B}}\"] \\\\\n\\sm{a:A}P_A(a) \\arrow[r,swap,\"{i'\\, \\defeq\\, \\total[i]{e_A}}\"] & \\sm{x:X}P(x)\n\\end{tikzcd}\n\\end{equation*}\nwith the homotopy $H':i'\\circ f'\\htpy j'\\circ g'$ defined as\n\\begin{equation*}\n\\lam{(x,y)}\\mathsf{eq\\usc{}pair}(H(x),e_S(x,y)^{-1}).\n\\end{equation*}\nFurthermore, we will write $\\mathcal{S'}$ for the span\n\\begin{equation*}\n\\begin{tikzcd}\n\\sm{a:A}P_A(a) & \\sm{x:S}P_A(f(x)) \\arrow[l,swap,\"{f'}\"] \\arrow[r,\"{g'}\"] & \\sm{b:B}P_B(b).\n\\end{tikzcd}\n\\end{equation*}\n\\end{defn}\n\nWe now state the flattening lemma for pushouts, which should be compared to the flattening lemma for coequalizers, stated in Lemma 6.12.2 of \\cite{hottbook}. We note that, using the dependent universal property of pushouts, our proof is substantially shorter.\n\n\\begin{lem}[The flattening lemma]\\label{lem:flattening}\nThe commuting square\\index{flattening lemma!for pushouts|textit}\n\\begin{equation*}\n\\begin{tikzcd}\n\\sm{x:S}P_A(f(x)) \\arrow[d,swap,\"{f'}\"] \\arrow[r,\"{g'}\"] & \\sm{b:B}P_B(b) \\arrow[d,\"{j'}\"] \\\\\n\\sm{a:A}P_A(a) \\arrow[r,swap,\"{i'}\"] & \\sm{x:X}P(x)\n\\end{tikzcd}\n\\end{equation*}\nis a pushout square.\n\\end{lem}\n\n\\begin{proof}\nNote that we have a commuting cube\n\\begin{equation*}\n\\begin{tikzcd}[row sep=large]\n& Y^{\\sm{x:X}P(x)} \\arrow[dl] \\arrow[d,\"\\mathsf{ev\\usc{}pair}\"] \\arrow[dr] \\\\\nY^{\\sm{a:A}P_A(a)} \\arrow[d,swap,\"\\mathsf{ev\\usc{}pair}\"] & \\prd{x:X}Y^{P(x)} \\arrow[dl] \\arrow[dr] & Y^{\\sm{b:B}P_B(b)} \\arrow[dl,crossing over] \\arrow[d,\"\\mathsf{ev\\usc{}pair}\"] \\\\\n\\prd{a:A}Y^{P_A(a)} \\arrow[dr] & Y^{\\sm{x:S}P_A(f(x))} \\arrow[from=ul,crossing over] \\arrow[d,swap,\"\\mathsf{ev\\usc{}pair}\"] & \\prd{b:B}Y^{P_B(b)} \\arrow[dl] \\\\\n\\phantom{\\prd{b:B}Y^{P_B(b)}} & \\prd{x:S}Y^{P_A(f(x))} & \\phantom{\\prd{a:A}Y^{P_A(a)}}\n\\end{tikzcd}\n\\end{equation*}\nfor any type $Y$. In this cube, the bottom square is a pullback square by property (iii) of \\cref{thm:pushout_up}. The vertical maps (of the form $\\mathsf{ev\\usc{}pair}$) are equivalences, so it follows that the top square is a pullback square. We conclude that $\\sm{x:X}P(x)$ is a pushout.\n\\end{proof}\n\n\\subsection{The descent property for pushouts}\n\n\\begin{defn}\nConsider a span $\\mathcal{S}$ from $A$ to $B$, and a span $\\mathcal{S}'$ from $A'$ to $B'$. A \\define{cartesian transformation} of spans\\index{cartesian transformation!of spans|textbf} from $\\mathcal{S}'$ to $\\mathcal{S}$ is a tuple\n\\begin{equation*}\n(h_A,h_S,h_B,F,G,p_f,p_g)\n\\end{equation*}\nconsisting of maps $h_A:A'\\to A$, $h_S:S'\\to S$, and $h_B:B'\\to B$, as indicated in the diagram\n\\begin{equation*}\n\\begin{tikzcd}\nA' \\arrow[d,swap,\"h_A\"]  & S' \\arrow[l,swap,\"{f'}\"] \\arrow[r,\"{g'}\"] \\arrow[d,swap,\"h_S\"] & B' \\arrow[d,\"h_B\"] \\\\\nA & S \\arrow[l,\"f\"] \\arrow[r,swap,\"g\"] & B,\n\\end{tikzcd}\n\\end{equation*}\nwith homotopies $F:f\\circ h_S\\htpy h_A\\circ f'$ and $G:g\\circ h_S\\htpy h_B\\circ g'$, satisfying the conditions\n\\begin{align*}\np_f & : \\mathsf{is\\usc{}pullback}(h_S,f',F) \\\\\np_g & : \\mathsf{is\\usc{}pullback}(h_S,g',G)\n\\end{align*}\nthat both squares are pullback squares. We write $\\mathsf{cart}(\\mathcal{S}',\\mathcal{S})$\\index{cart(S,S')@{$\\mathsf{cart}(\\mathcal{S},\\mathcal{S}')$}|textbf} for the type of cartesian transformations from $\\mathcal{S}'$ to $\\mathcal{S}$, and we write\n\\begin{equation*}\n\\mathsf{Cart}(\\mathcal{S}) \\defeq \\sm{A',B':\\UU}{\\mathcal{S}':\\mathsf{span}(A',B')}\\mathsf{cart}(\\mathcal{S}',\\mathcal{S}).\n\\end{equation*}\n\\end{defn}\n\nGiven descent data $(P_A,P_B,P_S)$ on a span $\\mathcal{S}$ from $A$ to $B$, we obtain a cartesian transformation\n\\begin{equation*}\n\\begin{tikzcd}[column sep=large]\n\\sm{a:A}P_A(a) \\arrow[d,swap,\"\\proj 1\"] & \\sm{x:S}P_A(f(x)) \\arrow[d,swap,\"\\proj 1\"] \\arrow[l,swap,\"{\\total[f]{\\idfunc}}\"] \\arrow[r,\"{\\total[g]{P_S}}\"] & \\sm{b:B}P_B(b) \\arrow[d,\"\\proj 1\"] \\\\\nA & S \\arrow[l,\"f\"] \\arrow[r,swap,\"g\"] & B\n\\end{tikzcd}\n\\end{equation*}\nwith the canonical homotopies witnessing that the squares commute. Note that both the left and right commuting squares are pullback squares by \\cref{thm:pb_fibequiv}. Thus we obtain an operation\n\\begin{equation*}\n\\mathsf{cart\\usc{}desc}_{\\mathcal{S}}:\\mathsf{Desc}(\\mathcal{S})\\to \\mathsf{Cart}(\\mathcal{S}).\n\\end{equation*}\n\n\\begin{lem}\\label{lem:cart_desc}\nFor any span $\\mathcal{S}$, the operation\\index{cart_desc@{$\\mathsf{cart\\usc{}desc}_{\\mathcal{S}}$}|textit}\n\\begin{equation*}\n\\mathsf{cart\\usc{}desc}_{\\mathcal{S}}:\\mathsf{Desc}(\\mathcal{S})\\to \\mathsf{Cart}(\\mathcal{S})\n\\end{equation*}\nis an equivalence.\n\\end{lem}\n\n\\begin{proof}\nNote that by \\cref{thm:pb_fibequiv_complete} it follows that the types of triples $(f',F,p_f)$ and $(g',G,p_g)$ are equivalent to the types of fiberwise equivalences\n\\begin{align*}\n& \\prd{x:S}\\eqv{\\fib{h_S}{x}}{\\fib{h_A}{f(x)}} \\\\\n& \\prd{x:S}\\eqv{\\fib{h_S}{x}}{\\fib{h_B}{g(x)}}\n\\end{align*} \nrespectively. Furthermore, by \\cref{thm:fam_proj} the types of pairs $(S',h_S)$, $(A',h_A)$, and $(B',h_B)$ are equivalent to the types $S\\to \\UU$, $A\\to \\UU$, and $B\\to \\UU$, respectively. Therefore it follows that the type $\\mathsf{Cart}(\\mathcal{S})$ is equivalent to the type of tuples $(Q,P_A,\\varphi,P_B,P_S)$ consisting of\n\\begin{align*}\nQ & : S\\to \\UU \\\\\nP_A & : A \\to \\UU \\\\\nP_B & : B \\to \\UU \\\\\n\\varphi & : \\prd{x:S}\\eqv{Q(x)}{P_A(f(x))} \\\\\nP_S & : \\prd{x:S}\\eqv{Q(x)}{P_B(g(x))}.\n\\end{align*}\nHowever, the type of $\\varphi$ is equivalent to the type $P_A\\circ f=Q$. Thus we see that the type of pairs $(Q,\\varphi)$ is contractible, so our claim follows.\n\\end{proof}\n\n\\begin{defn}\nConsider a commuting square\n\\begin{equation*}\n\\begin{tikzcd}\nS \\arrow[r,\"g\"] \\arrow[d,swap,\"f\"] & B \\arrow[d,\"j\"] \\\\\nA \\arrow[r,swap,\"i\"] & X\n\\end{tikzcd}\n\\end{equation*}\nwith $H:i\\circ f\\htpy j\\circ g$. \nWe define an operation\\index{cart map!{$\\mathsf{cart\\usc{}map}_{\\mathcal{S}}$}|textbf}\n\\begin{equation*}\n\\mathsf{cart\\usc{}map}_{\\mathcal{S}}:{\\Big(\\sm{X':\\UU}X'\\to X\\Big)}\\to \\mathsf{Cart}(\\mathcal{S}).\n\\end{equation*}\n\\end{defn}\n\n\\begin{proof}[Construction]\nLet $X':\\UU$ and $h_X:X'\\to X$. Then we define $A'$, $B'$, and $S'$ as the pullbacks\n\\begin{align*}\nA' & \\defeq A\\times_X X' \\\\\nB' & \\defeq B\\times_X X' \\\\\nS' & \\defeq S\\times_A A',\n\\end{align*}\nresulting in a diagram of the form\n\\begin{equation*}\n\\begin{tikzcd}\n& S' \\arrow[dl] \\arrow[dr,densely dotted] \\arrow[d] \\\\\nA' \\arrow[d] & S \\arrow[dl] \\arrow[dr] & B' \\arrow[dl,crossing over] \\arrow[d] \\\\\nA \\arrow[dr] & X' \\arrow[d] \\arrow[from=ul,crossing over] & B \\arrow[dl] \\\\\n& X\n\\end{tikzcd}\n\\end{equation*}\nBy the universal property of $B'$ it follows that there is a unique map $g':S'\\to B'$ making the cube commute. \nMoreover, since the two front squares and the back left squares are pullback squares by construction, it follows by \\cref{thm:pb_pasting} that also the back right square is a pullback square. Thus we obtain a cartesian transformation of spans.\n\\end{proof}\n\nThe following theorem is analogous to \\cref{thm:desc_fam}.\n\n\\begin{thm}[The descent theorem for pushouts]\\label{thm:descent}\\index{descent theorem!for pushouts|textit}\nConsider a commuting square\n\\begin{equation*}\n\\begin{tikzcd}\nS \\arrow[r,\"g\"] \\arrow[d,swap,\"f\"] & B \\arrow[d,\"j\"] \\\\\nA \\arrow[r,swap,\"i\"] & X\n\\end{tikzcd}\n\\end{equation*}\nwith $H:i\\circ f\\htpy j\\circ g$. \nIf this square is a pushout square, then the operation $\\mathsf{cart\\usc{}map}_{\\mathcal{S}}$\\index{cart map!{$\\mathsf{cart\\usc{}map}_{\\mathcal{S}}$}!is an equivalence|textit} is an equivalence\n\\begin{equation*}\n\\eqv{\\Big(\\sm{X':\\UU}X'\\to X\\Big)}{\\mathsf{Cart}(\\mathcal{S})}\n\\end{equation*}\n\\end{thm}\n\n\\begin{proof}\nIt suffices to show that the square\n\\begin{equation*}\n\\begin{tikzcd}[column sep=huge]\n\\UU^X \\arrow[r,\"{\\mathsf{desc\\usc{}fam}_{\\mathcal{S}}(i,j,H)}\"] \\arrow[d,swap,\"\\mathsf{map\\usc{}fam}_X\"] & \\mathsf{Desc}(\\mathcal{S}) \\arrow[d,\"\\mathsf{cart\\usc{}desc}_{\\mathcal{S}}\"] \\\\\n\\sm{X':\\UU}X^{X'} \\arrow[r,swap,\"\\mathsf{cart\\usc{}map}_{\\mathcal{S}}\"] & \\mathsf{Cart}(\\mathcal{S})\n\\end{tikzcd}\n\\end{equation*}\ncommutes. To see that this suffices, note that the operation $\\mathsf{map\\usc{}fam}_X$ is an equivalence by \\cref{thm:fam_proj}, the operation $\\mathsf{desc\\usc{}fam}_{\\mathcal{S}}(i,j,H)$ is an equivalence by \\cref{thm:desc_fam}, and the operation $\\mathsf{cart\\usc{}desc}_{\\mathcal{S}}$ is an equivalence by \\cref{lem:cart_desc}.\n\nTo see that the square commutes, note that the composite\n\\begin{equation*}\n\\mathsf{cart\\usc{}map}_{\\mathcal{S}}\\circ \\mathsf{map\\usc{}fam}_X\n\\end{equation*}\ntakes a family $P:X\\to \\UU$ to the cartesian transformation of spans\n\\begin{equation*}\n\\begin{tikzcd}\nA\\times_X\\tilde{P} \\arrow[d,swap,\"\\pi_1\"] & S\\times_A\\Big(A\\times_X\\tilde{P}\\Big) \\arrow[l] \\arrow[r] \\arrow[d,swap,\"\\pi_1\"] & B\\times_X\\tilde{P} \\arrow[d,\"\\pi_1\"] \\\\\nA & S \\arrow[l] \\arrow[r] & B,\n\\end{tikzcd}\n\\end{equation*}\nwhere $\\tilde{P}\\defeq\\sm{x:X}P(x)$.\n\nThe composite \n\\begin{equation*}\n\\mathsf{cart\\usc{}desc}_{\\mathcal{S}}\\circ \\mathsf{desc\\usc{}fam}_X\n\\end{equation*}\ntakes a family $P:X\\to \\UU$ to the cartesian transformation of spans\n\\begin{equation*}\n\\begin{tikzcd}\n\\sm{a:A}P(i(a)) \\arrow[d] & \\sm{s:S}P(i(f(s))) \\arrow[l] \\arrow[r] \\arrow[d] & \\sm{b:B}P(j(b)) \\arrow[d] \\\\\nA & S \\arrow[l] \\arrow[r] & B\n\\end{tikzcd}\n\\end{equation*}\nThese cartesian natural transformations are equal by \\cref{thm:pb_fibequiv}.\n\\end{proof}\n\nSince $\\mathsf{cart\\usc{}map}_{\\mathcal{S}}$ is an equivalence it follows that its fibers are contractible. \n\n\\begin{cor}\\label{cor:descent_fib}\nConsider a diagram of the form \n\\begin{equation*}\n\\begin{tikzcd}\n& S' \\arrow[d,swap,\"h_S\"] \\arrow[dl,swap,\"{f'}\"] \\arrow[dr,\"{g'}\"] \\\\\nA' \\arrow[d,swap,\"h_A\"] & S \\arrow[dl,swap,\"f\"] \\arrow[dr,\"g\"] & B' \\arrow[d,\"{h_B}\"] \\\\\nA \\arrow[dr,swap,\"i\"] & & B \\arrow[dl,\"j\"] \\\\\n& X\n\\end{tikzcd}\n\\end{equation*}\nwith homotopies\n\\begin{align*}\nF & : f\\circ h_S \\htpy h_A\\circ f' \\\\\nG & : g\\circ h_S \\htpy h_B\\circ g' \\\\\nH & : i\\circ f \\htpy j\\circ g,\n\\end{align*}\nand suppose that the bottom square is a pushout square, and the top squares are pullback squares.\nThen the type of tuples $((X',h_X),(i',I,p),(j',J,q),(H',C))$ consisting of\n\\begin{enumerate}\n\\item A type $X':\\UU$ together with a morphism\n\\begin{equation*}\nh_X : X'\\to X,\n\\end{equation*}\n\\item A map $i':A'\\to X'$, a homotopy $I:i\\circ h_A\\htpy h_X\\circ i'$, and a term $p$ witnessing that the square\n\\begin{equation*}\n\\begin{tikzcd}\nA' \\arrow[d,swap,\"h_A\"] \\arrow[r,\"{i'}\"] & X' \\arrow[d,\"h_X\"] \\\\\nA \\arrow[r,swap,\"i\"] & X\n\\end{tikzcd}\n\\end{equation*}\nis a pullback square.\n\\item A map $j':B'\\to X'$, a homotopy $J:j\\circ h_B\\htpy h_X\\circ j'$, and a term $q$ witnessing that the square\n\\begin{equation*}\n\\begin{tikzcd}\nB' \\arrow[d,swap,\"h_B\"] \\arrow[r,\"{j'}\"] & X' \\arrow[d,\"h_X\"] \\\\\nB \\arrow[r,swap,\"j\"] & X\n\\end{tikzcd}\n\\end{equation*}\nis a pullback square,\n\\item A homotopy $H':i'\\circ f'\\htpy j'\\circ g'$, and a homotopy\n\\begin{equation*}\nC : \\ct{(i\\cdot F)}{(\\ct{(I\\cdot f')}{(h_X\\cdot H')})} \\htpy \\ct{(H\\cdot h_S)}{(\\ct{(j\\cdot G)}{(J\\cdot g')})}\n\\end{equation*}\nwitnessing that the cube\n\\begin{equation*}\n\\begin{tikzcd}\n& S' \\arrow[dl] \\arrow[dr] \\arrow[d] \\\\\nA' \\arrow[d] & S \\arrow[dl] \\arrow[dr] & B' \\arrow[dl,crossing over] \\arrow[d] \\\\\nA \\arrow[dr] & X' \\arrow[d] \\arrow[from=ul,crossing over] & B \\arrow[dl] \\\\\n& X,\n\\end{tikzcd}\n\\end{equation*}\ncommutes,\n\\end{enumerate}\nis contractible.\n\\end{cor}\n\nThe following theorem should be compared to the flattening lemma, \\cref{lem:flattening}.\\index{flattening lemma!for pushouts}\n\n\\begin{thm}\\label{cor:descent}\nConsider a commuting cube\n\\begin{equation*}\n\\begin{tikzcd}\n& S' \\arrow[dl,swap,\"{f'}\"] \\arrow[dr,\"{g'}\"] \\arrow[d,\"h_S\"] \\\\\nA' \\arrow[d,swap,\"h_A\"] & S \\arrow[dl,swap,\"f\" near start] \\arrow[dr,\"g\" near start] & B' \\arrow[dl,crossing over,\"{j'}\" near end] \\arrow[d,\"h_B\"] \\\\\nA \\arrow[dr,swap,\"i\"] & X' \\arrow[d,\"h_X\" near start] \\arrow[from=ul,crossing over,\"{i'}\"' near end] & B \\arrow[dl,\"j\"] \\\\\n& X\n\\end{tikzcd}\n\\end{equation*}\nin which the bottom square is a pushout, and the two vertical squares in the back are pullbacks. Then the following are equivalent:\n\\begin{enumerate}\n\\item The two vertical squares in the front are pullback squares.\n\\item The top square is a pushout square.\n\\end{enumerate}\n\\end{thm}\n\n\\begin{proof}\nBy \\cref{cor:pb_fibequiv} we have fiberwise equivalences\n\\begin{align*}\nF & : \\prd{x:S}\\eqv{\\fib{h_S}{x}}{\\fib{h_A}{f(x)}} \\\\\nG & : \\prd{x:S}\\eqv{\\fib{h_S}{x}}{\\fib{h_B}{g(x)}} \\\\\nI & : \\prd{a:A}\\eqv{\\fib{h_A}{a}}{\\fib{h_X}{i(a)}} \\\\\nJ & : \\prd{b:B}\\eqv{\\fib{h_B}{b}}{\\fib{h_X}{j(b)}}. \n\\end{align*}\nMoreover, since the cube commutes we obtain a fiberwise homotopy\n\\begin{equation*}\nK : \\prd{x:S} I(f(x))\\circ F(x) \\htpy J(g(x))\\circ G(x).\n\\end{equation*}\nWe define the descent data $(P_A,P_B,P_S)$ consisting of $P_A:A\\to\\UU$, $P_B:B\\to\\UU$, and $P_S:\\prd{x:S}\\eqv{P_A(f(x))}{P_B(g(x))}$ by\n\\begin{align*}\nP_A(a) & \\defeq \\fib{h_A}{a} \\\\\nP_B(b) & \\defeq \\fib{h_B}{b} \\\\\nP_S(x) & \\defeq G(x)\\circ F(x)^{-1}.\n\\end{align*}\nWe have\n\\begin{align*}\nP & \\defeq \\fibf{h_X} \\\\\ne_A & \\defeq I \\\\\ne_B & \\defeq J \\\\\ne_S & \\defeq K.\n\\end{align*}\nNow consider the diagram\n\\begin{equation*}\n\\begin{tikzcd}\n\\sm{s:S}\\fib{h_S}{s} \\arrow[r] \\arrow[d] & \\sm{s:S}\\fib{h_A}{f(s)} \\arrow[r] \\arrow[d] & \\sm{b:B}\\fib{h_B}{b} \\arrow[d] \\\\\n\\sm{a:A}\\fib{h_A}{a} \\arrow[r] & \\sm{a:A}\\fib{h_A}{a} \\arrow[r] & \\sm{x:X}\\fib{h_X}{x}\n\\end{tikzcd}\n\\end{equation*}\nSince the top and bottom map in the left square are equivalences, we obtain that the left square is a pushout square. Moreover, the right square is a pushout by \\cref{lem:flattening}. Therefore it follows by \\cref{thm:pushout_pasting} that the outer rectangle is a pushout square.\n\nNow consider the commuting cube\n\\begin{equation*}\n\\begin{tikzcd}\n& \\sm{s:S}\\fib{h_S}{s} \\arrow[dl] \\arrow[dr] \\arrow[d] \\\\\n\\sm{a:A}\\fib{h_A}{a} \\arrow[d] & S' \\arrow[dl] \\arrow[dr] & \\sm{b:B}\\fib{h_B}{b} \\arrow[dl,crossing over] \\arrow[d] \\\\\nA' \\arrow[dr,swap] & \\sm{x:X}\\fib{h_X}{x} \\arrow[d] \\arrow[from=ul,crossing over] & B' \\arrow[dl] \\\\\n& X'.\n\\end{tikzcd}\n\\end{equation*}\nWe have seen that the top square is a pushout. The vertical maps are all equivalences, so the vertical squares are all pushout squares. Thus it follows from one more application of \\cref{thm:pushout_pasting} that the bottom square is a pushout.\n\\end{proof}\n\n\\begin{thm}\\label{thm:cartesian_cube}\nConsider a commuting cube of types \n\\begin{equation*}\\label{eq:cube}\n\\begin{tikzcd}\n& S' \\arrow[dl] \\arrow[dr] \\arrow[d] \\\\\nA' \\arrow[d] & S \\arrow[dl] \\arrow[dr] & B' \\arrow[dl,crossing over] \\arrow[d] \\\\\nA \\arrow[dr] & X' \\arrow[d] \\arrow[from=ul,crossing over] & B \\arrow[dl] \\\\\n& X,\n\\end{tikzcd}\n\\end{equation*}\nand suppose the two vertical squares in the back are pullback squares. Then the following are equivalent:\n\\begin{enumerate}\n\\item The two vertical squares in the front are pullback squares.\n\\item The commuting square\n\\begin{equation*}\n\\begin{tikzcd}\nA' \\sqcup^{S'} B' \\arrow[r] \\arrow[d] & X' \\arrow[d] \\\\\nA\\sqcup^{S} B \\arrow[r] & X\n\\end{tikzcd}\n\\end{equation*}\nis a pullback square.\n\\end{enumerate}\n\\end{thm}\n\n\\begin{proof}\nTo see that (i) implies (ii), it suffices to show that the pullback \n\\begin{equation*}\n(A\\sqcup^{S} B)\\times_{X}X'\n\\end{equation*}\nhas the universal property of the pushout. This follows by the descent theorem, since the vertical squares in the cube\n\\begin{equation*}\n\\begin{tikzcd}\n& S' \\arrow[dl] \\arrow[dr] \\arrow[d] \\\\\nA' \\arrow[d] & S \\arrow[dl] \\arrow[dr] & B' \\arrow[dl,crossing over] \\arrow[d] \\\\\nA \\arrow[dr] & (A\\sqcup^{S} B)\\times_{X}X' \\arrow[d] \\arrow[from=ul,crossing over] & B \\arrow[dl] \\\\\n& A\\sqcup^{S} B\n\\end{tikzcd}\n\\end{equation*}\nare pullback squares by \\cref{thm:pb_pasting}.\n\nTo prove that (ii) implies (i), we note that in the cube\n\\begin{equation*}\n\\begin{tikzcd}\n& S' \\arrow[dl] \\arrow[dr] \\arrow[d] \\\\\nA' \\arrow[d] & S \\arrow[dl] \\arrow[dr] & B' \\arrow[dl,crossing over] \\arrow[d] \\\\\nA \\arrow[dr] & A'\\sqcup^{S'}B' \\arrow[d] \\arrow[from=ul,crossing over] & B \\arrow[dl] \\\\\n& A\\sqcup^S B,\n\\end{tikzcd}\n\\end{equation*}\nthe two back squares are pullback squares, and the top and bottom squares are pushout squares. Therefore it follows from \\cref{cor:descent} that the two front squares are pullback squares. Now we obtain (i) from the pasting lemma for pushouts.\n\\end{proof}\n\n\\section{Applications of the descent theorem for pushouts}\n\\sectionmark{Applications of the descent theorem}\n\n\\subsection{Fiber sequences}\n\n\\begin{defn}\nA \\define{pointed type} is a pair $(X,x)$ consisting of a type $X$ equipped with a \\define{base point} $x:X$. We will write $\\UU_\\ast$ for the type $\\sm{X:\\UU}X$ of all pointed types.\n\\end{defn}\n\nIn the following lemma we characterize the identity type of $\\UU_\\ast$. \n\n\\begin{lem}\\label{lem:equiv_of_ptdtype}\nFor any $(A,a),(B,b):\\UU_\\ast$ we have an equivalence\n\\begin{equation*}\n\\eqv{\\Big(\\pairr{A,a}=\\pairr{B,b}\\Big)}{\\Big(\\sm{e:\\eqv{A}{B}}e(a)=b\\Big)}.\n\\end{equation*}\n\\end{lem}\n\n\\begin{proof}[Construction]\nBy \\cref{thm:eq_sigma} the type on the left hand side is\nequivalent to the type $\\sm{p:A=B}\\tr_{\\universalfam}({p},{a})=b$.\nBy the univalence axiom, the map \n\\begin{equation*}\n\\equiveq_{A,B}:(A=B)\\to (\\eqv{A}{B})\n\\end{equation*}\nis an equivalence for each $B:\\UU$. \nTherefore, we have an equivalence of type\n\\begin{equation*}\n\\eqv{\\Big(\\sm{p:A=B}\\tr_{\\universalfam}({p},{a})=b\\Big)}{\\Big(\\sm{e:\\eqv{A}{B}}\\tr_{\\universalfam}({\\eqequiv(e)},{a})=b\\Big)}\n\\end{equation*} \nMoreover, by equivalence induction (the analogue of path induction for \nequivalences), we can compute the transport:\n\\begin{equation*}\n\\tr_{\\universalfam}({\\eqequiv(e)},{a})=e(a).\n\\end{equation*}\nIt follows that $\\eqv{(\\tr_{\\universalfam}({\\eqequiv(e)},{a})=b)}\n{(e(a)=b)}$.\n\\end{proof}\n\n\\begin{defn}\n\\begin{enumerate}\n\\item Let $(X,\\ast_X)$ be a pointed type. A \\define{pointed family} over $(X,\\ast_X)$ consists of a type family $P:X\\to \\UU$ equipped with a base point $\\ast_P:P(\\ast_X)$. \n\\item Let $(P,\\ast_P)$ be a pointed family over $(X,\\ast_X)$. A \\define{pointed section} of $(P,\\ast_P)$ consists of a dependent function $f:\\prd{x:X}P(x)$ and an identification $p:f(\\ast_X)=\\ast_P$. We define the \\define{pointed $\\Pi$-type} to be the type of pointed sections:\n\\begin{equation*}\n\\Pi^\\ast_{(x:X)}P(x) \\defeq \\sm{f:\\prd{x:X}P(x)}f(\\ast_X)=\\ast_P\n\\end{equation*}\nIn the case of two pointed types $X$ and $Y$, we may also view $Y$ as a pointed family over $X$. In this case we write $X\\to_\\ast Y$ for the type of pointed functions.\n\\item Given any two pointed sections $f$ and $g$ of a pointed family $P$ over $X$, we define the type of pointed homotopies\n\\begin{equation*}\nf\\htpy_\\ast g \\defeq \\Pi^\\ast_{(x:X)} f(x)=g(x),\n\\end{equation*}\nwhere the family $x\\mapsto f(x)=g(x)$ is equipped with the base point $\\ct{p}{q^{-1}}$. \n\\end{enumerate}\n\\end{defn}\n\n\\begin{defn}\n\\begin{enumerate}\n\\item For any pointed type $X$, we define the \\define{pointed identity function} $\\idp_X\\defeq (\\idfunc[X],\\refl{\\ast})$. \n\\item For any two pointed maps $f:X\\to_\\ast Y$ and $g:Y\\to_\\ast Z$, we define the \\define{pointed composite}\n\\begin{equation*}\ng\\mathbin{\\circ_\\ast} f \\defeq (g\\circ f,\\ct{\\ap{g}{p_f}}{p_g}).\n\\end{equation*}\n\\end{enumerate}\n\\end{defn}\n\n\\begin{defn}\nLet $X$ be a pointed type with base point $x$. We define the \\define{loop space} $\\loopspace{X,x}$ of $X$ at $x$ to be the pointed type $x=x$ with base point $\\refl{x}$. \n\\end{defn}\n\n\\begin{defn}\nThe loop space operation $\\loopspacesym$ is \\emph{functorial} in the sense that\n\\begin{enumerate}\n\\item For every pointed map $f:X\\to_\\ast Y$ there is a pointed map\n\\begin{equation*}\n\\loopspace{f}:\\loopspace{X}\\to_\\ast \\loopspace{Y},\n\\end{equation*}\ndefined by $\\loopspace{f}(\\omega)\\defeq \\ct{p_f}{\\ap{f}{\\omega}}{p_f^{-1}}$, which is base point preserving by $\\rightinv(p_f)$. \n\\item For every pointed type $X$ there is a pointed homotopy\n\\begin{equation*}\n\\loopspace{\\idp_X}\\htpy_\\ast \\idp_{\\loopspace{X}}.\n\\end{equation*}\n\\item For any two pointed maps $f:X\\to_\\ast Y$ and $g:Y\\to_\\ast X$, there is a pointed homotopy witnessing that the triangle\n\\begin{equation*}\n\\begin{tikzcd}\n& \\loopspace{Y} \\arrow[dr,\"\\loopspace{g}\"] \\\\\n\\loopspace{X} \\arrow[rr,swap,\"\\loopspace{g\\circ_\\ast f}\"] \\arrow[ur,\"\\loopspace{f}\"] & & \\loopspace{Z}\n\\end{tikzcd}\n\\end{equation*}\nof pointed types commutes.\n\\end{enumerate}\n\\end{defn}\n\n\\begin{lem}\\label{lem:equiv_of_ptdequiv}\nFor any $\\pairr{e,p},\\pairr{f,q}:\\sm{e:\\eqv{A}{B}}e(a)=b$, we have an equivalence of type\n\\begin{equation*}\n\\eqv{\\Big(\\pairr{e,p}=\\pairr{f,q}\\Big)}{\\Big(\\sm{h:e\\htpy f} p=\\ct{h(a)}{q}\\Big)}.\n\\end{equation*}\n\\end{lem}\n\n\\begin{proof}[Construction]\nThe type $\\pairr{e,p}=\\pairr{f,q}$ is equivalent\nto the type $\\sm{h:e=f}\\tr({h},{p})=q$.\nNote that by the principle of function extensionality,\nthe map $\\htpyeq:(e=f)\\to(e\\htpy f)$\nis an equivalence. Furthermore, it follows by homotopy induction that for any \n$h:e\\htpy f$ we have an equivalence of type\n\\begin{equation*}\n\\eqv{(\\tr({\\eqhtpy(h)},{p})=q)}\n    {(p= \\ct{h(a)}{q})}.\\qedhere\n\\end{equation*}\n\\end{proof}\n\n\\begin{defn}\nA \\define{fiber sequence} $F\\hookrightarrow E \\twoheadrightarrow B$ consists of:\n\\begin{enumerate}\n\\item Pointed types $F$, $E$, and $B$, with base points $x_0$, $y_0$, and $b_0$ respectively, \n\\item Base point preserving maps $i:F\\to_\\ast E$ and $p:E\\to_\\ast B$, with $\\alpha:i(x_0)=y_0$ and $\\beta:p(y_0)=b_0$,\n\\item A pointed homotopy $H:\\const_{b_0}\\htpy_\\ast p\\circ_\\ast i$ witnessing that the square\n\\begin{equation*}\n\\begin{tikzcd}\nF \\arrow[r,\"i\"] \\arrow[d] & E \\arrow[d,\"p\"] \\\\\n\\unit \\arrow[r,swap,\"\\const_{b_0}\"] & B,\n\\end{tikzcd}\n\\end{equation*}\ncommutes and is a pullback square.\n\\end{enumerate}\nWe will write $\\FibSeq$ for the type of all fiber sequences in $\\UU$.\n\\end{defn}\n\n\\begin{prp}\nThe type of all fiber sequences is equivalent to the type\n\\begin{equation*}\n\\sm{(B,b):\\UU_\\ast}{P:B\\to\\UU}P(b).\n\\end{equation*}\n\\end{prp}\n\n\\subsection{Fiber sequences obtained by the descent property}\n\n\\begin{defn}\nLet $f:A\\to B$ be a map. The \\define{codiagonal}\\index{codiagonal}\\index{nabla@{$\\nabla_f$}} $\\nabla_f$ of $f$ is the map obtained from the universal property of the pushout, as indicated in the diagram\n\\begin{equation*}\n\\begin{tikzcd}\nA \\arrow[d,swap,\"f\"] \\arrow[r,\"f\"] \\arrow[dr, phantom, \"\\ulcorner\", very near end] & B \\arrow[d,\"\\inr\"] \\arrow[ddr,bend left=15,\"{\\idfunc[B]}\"] \\\\\nB \\arrow[r,\"\\inl\"] \\arrow[drr,bend right=15,swap,\"{\\idfunc[B]}\"] & B\\sqcup^{A} B \\arrow[dr,densely dotted,near start,swap,\"\\nabla_f\"] \\\\\n& & B\n\\end{tikzcd}\n\\end{equation*}\n\\end{defn}\n\n\\begin{prp}\nFor any map $f:A\\to B$ and any $y:B$, there is an equivalence $\\eqv{\\fib{\\nabla_f}{y}}{\\susp(\\fib{f}{y})}$. \n\\end{prp}\n\n\\begin{proof}\nFor any $b:B$ we have the commuting cube \n\\begin{equation*}\n\\begin{tikzcd}\n& \\fib{f}{b} \\arrow[dl] \\arrow[d] \\arrow[dr] \\\\\n\\unit \\arrow[d] & A \\arrow[dl] \\arrow[dr] & \\unit \\arrow[dl,crossing over] \\arrow[d] \\\\\nB \\arrow[dr] & \\unit \\arrow[from=ul,crossing over] \\arrow[d,swap,\"b\"] & B \\arrow[dl] \\\\\n& B\n\\end{tikzcd}\n\\end{equation*}\nof which the vertical sides are pullback squares. Hence we obtain the pullback square\n\\begin{equation*}\n\\begin{tikzcd}\n\\susp{\\fib{f}{b}} \\arrow[r] \\arrow[d] & \\unit \\arrow[d,\"b\"] \\\\\nB\\sqcup^{A} B \\arrow[r] & B\n\\end{tikzcd}\n\\end{equation*}\nfrom \\cref{thm:cartesian_cube}, from which the claim follows.\n\\end{proof}\n\n\\begin{defn}\nConsider two maps $f:A\\to B$ and $g:C\\to D$.\nThe \\define{pushout-product}\\index{pushout-product}\n\\begin{equation*}\nf\\square g : (A\\times D)\\sqcup^{A\\times C} (B\\times C)\\to B\\times D\n\\end{equation*}\nof $f$ and $g$ is defined by the universal property of the pushout as the unique map rendering the diagram\n\\begin{equation*}\n\\begin{tikzcd}\nA\\times C \\arrow[r,\"{f\\times \\idfunc[C]}\"] \\arrow[d,swap,\"{\\idfunc[A]\\times g}\"] & B\\times C \\arrow[d,\"\\inr\"] \\arrow[ddr,bend left=15,\"{\\idfunc[B]\\times g}\"] \\\\\nA\\times D \\arrow[r,\"\\inl\"] \\arrow[drr,bend right=15,swap,\"{f\\times\\idfunc[D]}\"] & (A\\times D)\\sqcup^{A\\times C} (B\\times C) \\arrow[dr,densely dotted,swap,near start,\"f\\square g\"] \\\\\n& & B\\times D\n\\end{tikzcd}\n\\end{equation*}\ncommutative.\n\\end{defn}\n\n\\begin{prp}\nFor any two maps $f:A\\to B$ and $g:C\\to D$, and any $(b,d):B\\times D$, there is an equivalence\n\\begin{equation*}\n\\eqv{\\fib{f\\square g}{b,d}}{\\join{\\fib{f}{b}}{\\fib{g}{d}}}.\n\\end{equation*}\n\\end{prp}\n\n\\begin{proof}\nLet $b:B$ and $d:D$. Then we have the commuting cube \n\\begin{equation*}\n\\begin{tikzcd}\n& \\fib{f}{b}\\times \\fib{g}{d} \\arrow[dl] \\arrow[d] \\arrow[dr] \\\\\n\\fib{f}{b} \\arrow[d] & A\\times C \\arrow[dl] \\arrow[dr] & \\fib{g}{d} \\arrow[dl,crossing over] \\arrow[d] \\\\\nA\\times D \\arrow[dr] & \\unit \\arrow[from=ul,crossing over] \\arrow[d] & B\\times C \\arrow[dl] \\\\\n& B\\times D\n\\end{tikzcd}\n\\end{equation*}\nof which the vertical sides are pullback squares. Hence the claim follows from \\cref{thm:cartesian_cube}.\n\\end{proof}\n\n\\begin{defn}\\label{defn:fib_join}\nLet $f:A\\to X$ and $g:B\\to X$ be maps into $X$. We define the \\define{fiberwise join} $\\join[X]{A}{B}$ and the \\define{join}\\footnote{\\emph{Warning}: By $\\join{f}{g}$ we do \\emph{not} mean the functorial action of the\njoin, applied to $(f,g)$.} $\\join{f}{g}:\\join[X]{A}{B}\\to X$ of\n$f$ and $g$, as indicated in the following diagram:\n\\begin{equation*}\n\\begin{tikzcd}\nA\\times_X B \\arrow[r,\"\\pi_2\"] \\arrow[d,swap,\"\\pi_1\"] \\arrow[dr, phantom, \"{\\ulcorner}\", at end] & B \\arrow[d,\"\\inr\"] \\arrow[ddr,bend left=15,\"g\"] \\\\\nA \\arrow[r,swap,\"\\inl\"] \\arrow[drr,bend right=15,swap,\"f\"] & \\join[X]{A}{B} \\arrow[dr,densely dotted,swap,near start,\"\\join{f}{g}\" xshift=1ex] \\\\\n& & X.\n\\end{tikzcd}\n\\end{equation*}\n\\end{defn}\n\n\\begin{thm}\\label{defn:join-fiber}\nLet $f:A\\to X$ and $g:B\\to X$ be maps into $X$, and let $x:X$. Then there is\nan equivalence\n\\begin{equation*}\n\\eqv{\\fib{\\join{f}{g}}{x}}{\\join{\\fib{f}{x}}{\\fib{g}{x}}}.\n\\end{equation*}\n\\end{thm}\n\n\\begin{proof}\nWe have the following commuting cube\n\\begin{equation*}\n\\begin{tikzcd}\n& \\fib{f}{x}\\times\\fib{g}{x} \\arrow[dl] \\arrow[d] \\arrow[dr] \\\\\n\\fib{f}{x} \\arrow[d] & A\\times_X B \\arrow[dl] \\arrow[dr] & \\fib{g}{x} \\arrow[dl,crossing over] \\arrow[d] \\\\\nA \\arrow[dr] & \\unit \\arrow[d] \\arrow[from=ul,crossing over] & B \\arrow[dl] \\\\\n& X\n\\end{tikzcd}\n\\end{equation*}\nin which the vertical squares are pullback squares. Therefore it follows by \\cref{thm:cartesian_cube} that the square\n\\begin{equation*}\n\\begin{tikzcd}\n\\join{\\fib{f}{x}}{\\fib{g}{x}} \\arrow[r] \\arrow[d] & \\unit \\arrow[d] \\\\\n\\join[X]{A}{B} \\arrow[r] & X\n\\end{tikzcd}\n\\end{equation*}\nis a pullback square.\n\\end{proof}\n\n\\begin{rmk}\nThe join operation on maps with a common codomain is associative up to homotopy (this was formalized by Brunerie, see Proposition 1.8.6 of \\cite{BruneriePhD}), and it is a commutative operation on the generalized elements of a type $X$. Furthermore, the unique map of type $\\emptyt\\to X$ is a unit for the join operation.\n\\end{rmk}\n\n\\begin{defn}\nLet $A$ and $B$ be pointed types with base points $a_0:A$ and $b_0:B$. The \\define{wedge inclusion}\\index{wedge inclusion} is defined as follows by the universal property of the wedge:\n\\begin{equation*}\n\\begin{tikzcd}[column sep=huge]\n\\unit \\arrow[r] \\arrow[d] & B \\arrow[d,\"\\inr\"] \\arrow[ddr,bend left=15,\"{\\lam{b}(a_0,b)}\"] \\\\\nA \\arrow[r,\"\\inl\"] \\arrow[drr,bend right=15,swap,\"{\\lam{a}(a,b_0)}\"] & A\\vee B \\arrow[dr,densely dotted,swap,\"{\\mathsf{wedge\\usc{}in}_{A,B}}\"{near start,xshift=1ex}] \\\\\n& & A\\times B\n\\end{tikzcd}\n\\end{equation*}\n\\end{defn}\n\n\\begin{prp}\nThere is a fiber sequence \n\\begin{equation*}\n\\join{\\loopspace{A}}{\\loopspace{B}}\\hookrightarrow A\\vee B\\twoheadrightarrow A\\times B.\n\\end{equation*}\n\\end{prp}\n\n\\begin{proof}\nWe have the commuting cube \n\\begin{equation*}\n\\begin{tikzcd}\n& \\loopspace{B}\\times\\loopspace{A} \\arrow[dl] \\arrow[d] \\arrow[dr] \\\\\n\\loopspace{B} \\arrow[d,swap,\"\\mathsf{const}_a\"] & \\unit \\arrow[dl] \\arrow[dr] & \\loopspace{A} \\arrow[dl,crossing over] \\arrow[d,\"\\mathsf{const}_b\"] \\\\\nA \\arrow[dr] & \\unit \\arrow[from=ul,crossing over] \\arrow[d] & B \\arrow[dl] \\\\\n& A\\times B\n\\end{tikzcd}\n\\end{equation*}\nof which the vertical sides are pullback squares. Hence the claim follows from \\cref{thm:cartesian_cube}.\n\\end{proof}\n\n\\begin{defn}\nConsider a pointed type $X$. We define the map $\\mathsf{fold}:X\\vee X\\to X$ by the universal property of the wedge as indicated in the diagram\n\\begin{equation*}\n\\begin{tikzcd}\n\\unit \\arrow[d,swap,\"x_0\"] \\arrow[r,\"x_0\"] \\arrow[dr, phantom, \"\\ulcorner\", very near end] & X \\arrow[d,\"\\inr\"] \\arrow[ddr,bend left=15,\"{\\idfunc[X]}\"] \\\\\nX \\arrow[r,\"\\inl\"] \\arrow[drr,bend right=15,swap,\"{\\idfunc[X]}\"] & X\\vee X \\arrow[dr,densely dotted,near start,swap,\"\\mathsf{fold}\"] \\\\\n& & X.\n\\end{tikzcd}\n\\end{equation*}\n\\end{defn}\n\n\\begin{prp}\nThere is a fiber sequence\n\\begin{equation*}\n\\susp\\loopspace{X} \\hookrightarrow X\\vee X \\twoheadrightarrow X.\n\\end{equation*}\n\\end{prp}\n\n\\begin{proof}\nWe have the commuting cube \n\\begin{equation*}\n\\begin{tikzcd}\n& \\loopspace{X} \\arrow[dl] \\arrow[d] \\arrow[dr] \\\\\n\\unit \\arrow[d] & \\unit \\arrow[dl] \\arrow[dr] & \\unit \\arrow[dl,crossing over] \\arrow[d] \\\\\nX \\arrow[dr] & \\unit \\arrow[from=ul,crossing over] \\arrow[d] & X \\arrow[dl] \\\\\n& X\n\\end{tikzcd}\n\\end{equation*}\nof which the vertical sides are pullback squares. Hence the claim follows from \\cref{thm:cartesian_cube}.\n\\end{proof}\n\n\\begin{rmk}\nAs a corollary, there are fiber sequences\n\\begin{align*}\n\\sphere{1} \\hookrightarrow \\rprojective{\\infty}\\vee \\rprojective{\\infty} & \\twoheadrightarrow \\rprojective{\\infty} \\\\\n\\sphere{2} \\hookrightarrow \\cprojective{\\infty}\\vee \\cprojective{\\infty} & \\twoheadrightarrow \\cprojective{\\infty}.\n\\end{align*}\nHere we take $\\rprojective{\\infty}\\defeq K(\\Z/2,1)$ and $\\cprojective{\\infty}\\defeq K(\\Z,2)$, where the Eilenberg-Mac Lane space $K(G,n)$ is defined in \\cite{FinsterLicata}.\n\\end{rmk}\n\n\\begin{cor}\nThere is a fiber sequence\n\\begin{equation*}\n(\\susp\\loopspace{X})^{\\vee n} \\hookrightarrow X^{\\vee (n+1)} \\twoheadrightarrow X.\n\\end{equation*}\n\\end{cor}\n\n\\begin{defn}\\label{defn:coh_hspace}\nA \\define{coherent H-space} consists of a type $X$ equipped with a unit $1:X$, a multiplication operation $\\mu:X \\to (X \\to X)$ such that the function $\\mu(x,\\blank)$ and $\\mu(\\blank,y)$ are equivalences for each $x:X$ and $y:X$, respectively, and \\emph{coherent} unit laws\n\\begin{align*}\n\\mathsf{right\\usc{}unit} & : \\prd{x: X} \\mu(x,1)= x \\\\\n\\mathsf{left\\usc{}unit} & : \\prd{y:X} \\mu(1,y) = y \\\\\n\\mathsf{coh\\usc{}unit} & : \\mathsf{left\\usc{}unit}(1)=\\mathsf{right\\usc{}unit}(1).\n\\end{align*}\n\\end{defn}\n\nThe following theorem is also known as the Hopf-construction.\n\n\\begin{thm}\\label{thm:hopf_construction}\nFor any coherent H-space $X$ there is a fiber sequence\n\\begin{equation*}\nX \\hookrightarrow \\join{X}{X} \\twoheadrightarrow \\susp X.\n\\end{equation*}\nThe map $\\eta_X:\\join{X}{X}\\to \\susp X$ is called the \\define{Hopf fibration} for $X$.\n\\end{thm}\n\n\\begin{proof}\nWe have the commuting cube\n\\begin{equation*}\n\\begin{tikzcd}\n& X \\times X \\arrow[dl,swap,\"\\pi_1\"] \\arrow[d,swap,\"\\mu\"] \\arrow[dr,\"\\pi_2\"] \\\\\nX \\arrow[d] & X \\arrow[dl] \\arrow[dr] & X \\arrow[dl,crossing over] \\arrow[d] \\\\\n\\unit \\arrow[dr] & \\join{X}{X} \\arrow[from=ul,crossing over] \\arrow[d,densely dotted] & \\unit \\arrow[dl] \\\\\n& \\susp X,\n\\end{tikzcd}\n\\end{equation*}\nwhere the front map is obtained by the universal property of the pushout.\n\nIn this cube, the two vertical squares in the back are pullback squares by \\cref{thm:pb_fibequiv}, since $\\mu(\\blank,y)$ and $\\mu(x,\\blank)$ are equivalences for every $x:X$ and $y:X$, respectively. Since the bottom and top squares are pushout squares it follows by \\cref{thm:cartesian_cube} that the front two squares are pullback squares.\n\\end{proof}\n\n\\begin{rmk}\nThe classical Hopf fibration\n\\begin{equation*}\n\\begin{tikzcd}\n\\sphere{1} \\arrow[r,hookrightarrow] & \\sphere{3} \\arrow[r,->>] & \\sphere{2}\n\\end{tikzcd}\n\\end{equation*}\nis now obtained from the fact that $\\join{\\sphere{1}}{\\sphere{1}}\\eqvsym \\sphere{3}$, which was established in \\cite{BruneriePhD}. Indeed, the circle is a coherent H-space.\n\\end{rmk}\n", "meta": {"hexsha": "b0425e48bcf90965e2e3ee231f9eeb4ea154a049", "size": 53491, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "descent.tex", "max_stars_repo_name": "EgbertRijke/dissertation", "max_stars_repo_head_hexsha": "f2c087ba8983205d3dd336bbc194be5b7218c2c5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-07-06T10:37:12.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-06T10:37:12.000Z", "max_issues_repo_path": "descent.tex", "max_issues_repo_name": "EgbertRijke/dissertation", "max_issues_repo_head_hexsha": "f2c087ba8983205d3dd336bbc194be5b7218c2c5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "descent.tex", "max_forks_repo_name": "EgbertRijke/dissertation", "max_forks_repo_head_hexsha": "f2c087ba8983205d3dd336bbc194be5b7218c2c5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.7244408946, "max_line_length": 467, "alphanum_fraction": 0.6745994653, "num_tokens": 20221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.33773262472938753}}
{"text": "% The LaTeX below is mostly computer-generated (for reasons of speed); don't expect it to be very readable. Sorry.\n\r\n\\documentclass[paper=a4, fontsize=12pt]{scrartcl}%\r\n\\usepackage[T1]{fontenc}\r\n\\usepackage[english]{babel}\r\n\\usepackage{amsmath,amsfonts,amsthm,amssymb}\r\n\\usepackage{mathrsfs}\r\n\\usepackage{sectsty}\r\n\\usepackage{hyperref}\r\n\\usepackage{graphicx}\r\n\\usepackage{framed}\r\n\\usepackage{ifthen}\r\n\\usepackage{lastpage}\r\n\\usepackage{mathdots}\r\n\\usepackage[headsepline,footsepline,manualmark]{scrlayer-scrpage}\r\n\\usepackage[height=10in,a4paper,hmargin={1in,0.8in}]{geometry}\r\n\\usepackage[usenames,dvipsnames]{xcolor}\r\n\\usepackage{tikz}\r\n\\usepackage{verbatim}\r\n\\usepackage{amsmath}\r\n\\usepackage{amsfonts}\r\n\\usepackage{amssymb}%\r\n\\setcounter{MaxMatrixCols}{30}\r\n%TCIDATA{OutputFilter=latex2.dll}\r\n%TCIDATA{Version=5.50.0.2960}\r\n%TCIDATA{LastRevised=Thursday, May 09, 2019 19:19:28}\r\n%TCIDATA{<META NAME=\"GraphicsSave\" CONTENT=\"32\">}\r\n%TCIDATA{<META NAME=\"SaveForMode\" CONTENT=\"1\">}\r\n%TCIDATA{BibliographyScheme=Manual}\r\n%BeginMSIPreambleData\r\n\\providecommand{\\U}[1]{\\protect\\rule{.1in}{.1in}}\r\n%EndMSIPreambleData\r\n\\allsectionsfont{\\centering \\normalfont\\scshape}\r\n\\setlength\\parindent{20pt}\r\n\\newcommand{\\CC}{\\mathbb{C}}\r\n\\newcommand{\\RR}{\\mathbb{R}}\r\n\\newcommand{\\QQ}{\\mathbb{Q}}\r\n\\newcommand{\\NN}{\\mathbb{N}}\r\n\\newcommand{\\DD}{{\\mathbb{D}}}\r\n\\newcommand{\\PP}{\\mathbb{P}}\r\n\\newcommand{\\KK}{\\mathbb{K}}\r\n\\newcommand{\\LL}{\\mathbb{L}}\r\n\\newcommand{\\MM}{\\mathbb{M}}\r\n\\newcommand{\\FF}{\\mathbb{F}}\r\n\\newcommand{\\Z}[1]{\\mathbb{Z}/#1\\mathbb{Z}}\r\n\\newcommand{\\ZZ}{\\mathbb{Z}}\r\n\\newcommand{\\id}{\\operatorname{id}}\r\n\\newcommand{\\op}{\\operatorname{op}}\r\n\\newcommand{\\tildot}{\\left. \\widetilde{\\cdot} \\right.}\r\n\\newcommand{\\lcm}{\\operatorname{lcm}}\r\n\\newcommand{\\set}[1]{\\left\\{ #1 \\right\\}}\r\n\\newcommand{\\abs}[1]{\\left| #1 \\right|}\r\n\\newcommand{\\tup}[1]{\\left( #1 \\right)}\r\n\\newcommand{\\ive}[1]{\\left[ #1 \\right]}\r\n\\newcommand{\\floor}[1]{\\left\\lfloor #1 \\right\\rfloor}\r\n\\newcommand{\\underbrack}[2]{\\underbrace{#1}_{\\substack{#2}}}\r\n\\newcommand{\\powset}[2][]{\\ifthenelse{\\equal{#2}{}}{\\mathcal{P}\\left(#1\\right)}{\\mathcal{P}_{#1}\\left(#2\\right)}}\r\n\\newcommand{\\mapeq}[1]{\\underset{#1}{\\equiv}}\r\n\\newcommand{\\eps}{\\varepsilon}\r\n\\newcommand{\\N}{\\operatorname{N}}\r\n\\newcommand{\\horrule}[1]{\\rule{\\linewidth}{#1}}\r\n\\newcommand{\\nnn}{\\nonumber\\\\}\r\n\\let\\sumnonlimits\\sum\n\\let\\prodnonlimits\\prod\n\\let\\cupnonlimits\\bigcup\n\\let\\capnonlimits\\bigcap\n\\renewcommand{\\sum}{\\sumnonlimits\\limits}\n\\renewcommand{\\prod}{\\prodnonlimits\\limits}\n\\renewcommand{\\bigcup}{\\cupnonlimits\\limits}\n\\renewcommand{\\bigcap}{\\capnonlimits\\limits}\n\\newtheoremstyle{plainsl}\r\n{8pt plus 2pt minus 4pt}\r\n{8pt plus 2pt minus 4pt}\r\n{\\slshape}\r\n{0pt}\r\n{\\bfseries}\r\n{.}\r\n{5pt plus 1pt minus 1pt}\r\n{}\r\n\\theoremstyle{plainsl}\n\\newtheorem{theorem}{Theorem}[section]\r\n\\newtheorem{proposition}[theorem]{Proposition}\r\n\\newtheorem{lemma}[theorem]{Lemma}\r\n\\newtheorem{corollary}[theorem]{Corollary}\r\n\\newtheorem{conjecture}[theorem]{Conjecture}\r\n\\theoremstyle{definition}\n\\newtheorem{definition}[theorem]{Definition}\r\n\\newtheorem{example}[theorem]{Example}\r\n\\newtheorem{exercise}[theorem]{Exercise}\r\n\\newtheorem{examples}[theorem]{Examples}\r\n\\newtheorem{algorithm}[theorem]{Algorithm}\r\n\\newtheorem{question}[theorem]{Question}\r\n\\theoremstyle{remark}\n\\newtheorem{remark}[theorem]{Remark}\r\n\\newenvironment{statement}{\\begin{quote}}{\\end{quote}}\r\n\\newenvironment{fineprint}{\\begin{small}}{\\end{small}}\r\n\\newcommand{\\myname}{Darij Grinberg}\r\n\\newcommand{\\myid}{00000000}\r\n\\newcommand{\\mymail}{dgrinber@umn.edu}\r\n\\newcommand{\\psetnumber}{6}\r\n\\ihead{Solutions to homework set \\#\\psetnumber}\r\n\\ohead{page \\thepage\\ of \\pageref{LastPage}}\r\n\\ifoot{\\myname, \\myid}\r\n\\ofoot{\\mymail}\r\n\\begin{document}\r\n\r\n\\title{ \\normalfont {\\normalsize \\textsc{University of Minnesota, School of\r\nMathematics} }\\\\[25pt] \\rule{\\linewidth}{0.5pt} \\\\[0.4cm] {\\huge Math 4281: Introduction to Modern Algebra, }\\\\Spring 2019: Homework 6\\\\\\rule{\\linewidth}{2pt} \\\\[0.5cm] }\r\n\\author{Darij Grinberg}\r\n\\maketitle\r\n\r\n%----------------------------------------------------------------------------------------\r\n%\tEXERCISE 1\r\n%----------------------------------------------------------------------------------------\r\n\\rule{\\linewidth}{0.3pt} \\\\[0.4cm]\n\r\n\\section{Exercise 1: The opposite ring}\r\n\r\nLet $\\mathbb{K}$ be a ring. We define a new binary operation $\\left.\r\n\\widetilde{\\cdot} \\right.  $ on $\\mathbb{K}$ by setting\r\n\\[\r\na \\left.  \\widetilde{\\cdot} \\right.  b = ba \\qquad\\text{for all } a, b\r\n\\in\\mathbb{K} .\r\n\\]\r\n(Thus, $\\left.  \\widetilde{\\cdot} \\right.  $ is the multiplication of\r\n$\\mathbb{K}$, but with the arguments switched.)\r\n\r\n\\begin{enumerate}\r\n\\item[\\textbf{(a)}] Prove that the set $\\mathbb{K}$, equipped with the\r\naddition $+$, the multiplication $\\left.  \\widetilde{\\cdot} \\right.  $, the\r\nzero $0_{\\mathbb{K}}$ and the unity $1_{\\mathbb{K}}$, is a ring.\r\n\\end{enumerate}\r\n\r\n\\noindent This new ring is called the \\textit{opposite ring} of $\\mathbb{K}$,\r\nand is denoted by $\\mathbb{K}^{\\operatorname{op}}$.\r\n\r\nNote that the \\textbf{sets} $\\mathbb{K}$ and $\\mathbb{K}^{\\operatorname{op}}$\r\nare identical (so a map from $\\mathbb{K}$ to $\\mathbb{K}$ is the same as a map\r\nfrom $\\mathbb{K}$ to $\\mathbb{K}^{\\operatorname{op}}$); but the \\textbf{rings}\r\n$\\mathbb{K}$ and $\\mathbb{K}^{\\operatorname{op}}$ are generally not the same\r\n(so a ring homomorphism from $\\mathbb{K}$ to $\\mathbb{K}$ is not the same as a\r\nring homomorphism from $\\mathbb{K}$ to $\\mathbb{K}^{\\operatorname{op}}$).\r\n\r\n\\begin{enumerate}\r\n\\item[\\textbf{(b)}] Prove that the identity map $\\operatorname{id} :\r\n\\mathbb{K} \\to\\mathbb{K}$ is a ring isomorphism from $\\mathbb{K}$ to\r\n$\\mathbb{K}^{\\operatorname{op}}$ if and only if $\\mathbb{K}$ is commutative.\r\n\r\n\\item[\\textbf{(c)}] Now, assume that $\\mathbb{K}$ is the matrix ring\r\n$\\mathbb{L}^{n \\times n}$ for some commutative ring $\\mathbb{L}$ and some $n\r\n\\in\\mathbb{N}$. Prove that the map\r\n\\[\r\n\\mathbb{K} \\to\\mathbb{K}^{\\operatorname{op}}, \\qquad A \\mapsto A^{T}\r\n\\]\r\n(where $A^{T}$, as usual, denotes the transpose of a matrix $A$) is a ring isomorphism.\r\n\\end{enumerate}\r\n\r\n[\\textbf{Hint:} In \\textbf{(a)}, you only have to check the ring axioms that\r\nhave to do with multiplication. Similarly, in \\textbf{(b)}, you are free to\r\ncheck the one axiom relating to multiplication only. In \\textbf{(c)}, you can\r\nuse \\cite[Exercise 6.5]{detnotes} without proof.]\r\n\r\n\\subsection{Remark}\r\n\r\nThis exercise gives some examples of rings $\\mathbb{K}$ that are isomorphic to\r\ntheir opposite rings $\\mathbb{K}^{\\operatorname{op}}$. See\r\n\\url{https://mathoverflow.net/questions/64370/} for examples of rings that are not.\r\n\r\n\\subsection{Solution}\r\n\r\nWe shall follow the PEMDAS convention for the order of operations, treating\r\nthe new multiplication $\\left.  \\widetilde{\\cdot}\\right.  $ operation as a\r\nmultiplicative operation. Thus, the expression \\textquotedblleft$a\\left.\r\n\\widetilde{\\cdot}\\right.  b+c\\left.  \\widetilde{\\cdot}\\right.  d$%\r\n\\textquotedblright\\ will mean \\textquotedblleft$\\left(  a\\left.\r\n\\widetilde{\\cdot}\\right.  b\\right)  +\\left(  c\\left.  \\widetilde{\\cdot\r\n}\\right.  d\\right)  $\\textquotedblright\\ rather than \\textquotedblleft%\r\n$a\\left.  \\widetilde{\\cdot}\\right.  \\left(  b+c\\right)  \\left.\r\n\\widetilde{\\cdot}\\right.  d$\\textquotedblright.\r\n\r\nWe are in the slightly confusing situation of having two different\r\n\\textquotedblleft multiplications\\textquotedblright\\ on one and the same set\r\n$\\mathbb{K}$: the original multiplication $\\cdot$ of the ring $\\mathbb{K}$,\r\nand the new multiplication $\\left.  \\widetilde{\\cdot}\\right.  $ of the ring\r\n$\\mathbb{K}^{\\operatorname*{op}}$ (although we still have not shown that\r\n$\\mathbb{K}^{\\operatorname*{op}}$ is actually a ring). Let us agree that if\r\n$a,b\\in\\mathbb{K}$, then the notation \\textquotedblleft$ab$\\textquotedblright%\r\n\\ shall always mean \\textquotedblleft$a\\cdot b$\\textquotedblright\\ (that is,\r\nthe image of the pair $\\left(  a,b\\right)  $ under the original multiplication\r\n$\\cdot$, not under the new multiplication $\\left.  \\widetilde{\\cdot}\\right.  $).\r\n\r\nThe original ring $\\mathbb{K}$ satisfies all eight ring axioms (since it is a ring).\r\n\r\n\\bigskip\r\n\r\n\\textbf{(a)} Clearly, the addition $+$ and the multiplication $\\left.\r\n\\widetilde{\\cdot}\\right.  $ are binary operations on $\\mathbb{K}$, and the\r\nelements $0_{\\mathbb{K}}$ and $1_{\\mathbb{K}}$ indeed belong to $\\mathbb{K}$.\r\nIt remains to prove that these two operations and these two elements make\r\n$\\mathbb{K}$ into a ring. In order to do so, we need to verify the ring\r\naxioms. These axioms are the following:\r\n\r\n\\begin{itemize}\r\n\\item \\textbf{Commutativity of addition:} We have $a+b=b+a$ for all\r\n$a,b\\in\\mathbb{K}$.\r\n\r\n\\item \\textbf{Associativity of addition:} We have $a+\\left(  b+c\\right)\r\n=\\left(  a+b\\right)  +c$ for all $a,b,c\\in\\mathbb{K}$.\r\n\r\n\\item \\textbf{Neutrality of zero:} We have $a+0_{\\mathbb{K}}=0_{\\mathbb{K}%\r\n}+a=a$ for all $a\\in\\mathbb{K}$.\r\n\r\n\\item \\textbf{Existence of additive inverses:} For any $a\\in\\mathbb{K}$, there\r\nexists an element $a^{\\prime}\\in\\mathbb{K}$ such that $a+a^{\\prime}=a^{\\prime\r\n}+a=0_{\\mathbb{K}}$.\r\n\r\n\\item \\textbf{Associativity of multiplication:} We have $a\\left.\r\n\\widetilde{\\cdot}\\right.  \\left(  b\\left.  \\widetilde{\\cdot}\\right.  c\\right)\r\n=\\left(  a\\left.  \\widetilde{\\cdot}\\right.  b\\right)  \\left.  \\widetilde{\\cdot\r\n}\\right.  c$ for all $a,b,c\\in\\mathbb{K}$. (Of course, we \\textbf{cannot} use\r\n\\textquotedblleft$ab$\\textquotedblright\\ as an abbreviation for\r\n\\textquotedblleft$a\\left.  \\widetilde{\\cdot}\\right.  b$\\textquotedblright,\r\nsince \\textquotedblleft$ab$\\textquotedblright\\ already stands for the\r\ndifferent product $a\\cdot b$.)\r\n\r\n\\item \\textbf{Neutrality of one:} We have $a\\left.  \\widetilde{\\cdot}\\right.\r\n1_{\\mathbb{K}}=1_{\\mathbb{K}}\\left.  \\widetilde{\\cdot}\\right.  a=a$ for all\r\n$a\\in\\mathbb{K}$.\r\n\r\n\\item \\textbf{Annihilation:} We have $a\\left.  \\widetilde{\\cdot}\\right.\r\n0_{\\mathbb{K}}=0_{\\mathbb{K}}\\left.  \\widetilde{\\cdot}\\right.  a=0_{\\mathbb{K}%\r\n}$ for all $a\\in\\mathbb{K}$.\r\n\r\n\\item \\textbf{Distributivity:} We have%\r\n\\[\r\na\\left.  \\widetilde{\\cdot}\\right.  \\left(  b+c\\right)  =a\\left.\r\n\\widetilde{\\cdot}\\right.  b+a\\left.  \\widetilde{\\cdot}\\right.\r\nc\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\text{and}\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\left(  a+b\\right)  \\left.\r\n\\widetilde{\\cdot}\\right.  c=a\\left.  \\widetilde{\\cdot}\\right.  c+b\\left.\r\n\\widetilde{\\cdot}\\right.  c\r\n\\]\r\nfor all $a,b,c\\in\\mathbb{K}$.\r\n\\end{itemize}\r\n\r\nThe first four of these eight axioms do not involve the new multiplication\r\n$\\left.  \\widetilde{\\cdot}\\right.  $. Thus, they say exactly the same thing as\r\nthe corresponding axioms for the original ring $\\mathbb{K}$ (with the original\r\noperations $+$ and $\\cdot$). Hence, they are satisfied (since the\r\ncorresponding axioms for the original ring $\\mathbb{K}$ are satisfied). It\r\nthus remains to prove that the remaining four axioms are satisfied. Let us\r\ncheck this:\r\n\r\n[\\textit{Proof of the \\textquotedblleft Associativity of\r\nmultiplication\\textquotedblright\\ axiom:} Let $a,b,c\\in\\mathbb{K}$. We must\r\nprove that $a\\left.  \\widetilde{\\cdot}\\right.  \\left(  b\\left.\r\n\\widetilde{\\cdot}\\right.  c\\right)  =\\left(  a\\left.  \\widetilde{\\cdot\r\n}\\right.  b\\right)  \\left.  \\widetilde{\\cdot}\\right.  c$.\r\n\r\nThe definition of the operation $\\left.  \\widetilde{\\cdot}\\right.  $ yields\r\n$b\\left.  \\widetilde{\\cdot}\\right.  c=cb$ and $a\\left.  \\widetilde{\\cdot\r\n}\\right.  b=ba$ and%\r\n\\begin{equation}\r\na\\left.  \\widetilde{\\cdot}\\right.  \\left(  b\\left.  \\widetilde{\\cdot}\\right.\r\nc\\right)  =\\underbrace{\\left(  b\\left.  \\widetilde{\\cdot}\\right.  c\\right)\r\n}_{=cb}a=\\left(  cb\\right)  a \\label{sol.ring.op.a.ass.1}%\r\n\\end{equation}\r\nand%\r\n\\begin{equation}\r\n\\left(  a\\left.  \\widetilde{\\cdot}\\right.  b\\right)  \\left.  \\widetilde{\\cdot\r\n}\\right.  c=c\\underbrace{\\left(  a\\left.  \\widetilde{\\cdot}\\right.  b\\right)\r\n}_{=ba}=c\\left(  ba\\right)  . \\label{sol.ring.op.a.ass.2}%\r\n\\end{equation}\r\nBut the original ring $\\mathbb{K}$ satisfies the \\textquotedblleft\r\nAssociativity of multiplication\\textquotedblright\\ axiom (since it is a ring);\r\nthus, $\\left(  cb\\right)  a=c\\left(  ba\\right)  $. In other words, the right\r\nhand sides of the two equalities \\eqref{sol.ring.op.a.ass.1} and\r\n\\eqref{sol.ring.op.a.ass.2} are equal. Thus, their left hand sides are also\r\nequal. In other words, $a\\left.  \\widetilde{\\cdot}\\right.  \\left(  b\\left.\r\n\\widetilde{\\cdot}\\right.  c\\right)  =\\left(  a\\left.  \\widetilde{\\cdot\r\n}\\right.  b\\right)  \\left.  \\widetilde{\\cdot}\\right.  c$. Thus, the\r\n\\textquotedblleft Associativity of multiplication\\textquotedblright\\ axiom is proven.]\r\n\r\n[\\textit{Proof of the \\textquotedblleft Neutrality of one\\textquotedblright%\r\n\\ axiom:} Let $a\\in\\mathbb{K}$. We must prove that $a\\left.  \\widetilde{\\cdot\r\n}\\right.  1_{\\mathbb{K}}=1_{\\mathbb{K}}\\left.  \\widetilde{\\cdot}\\right.  a=a$.\r\n\r\nBut the original ring $\\mathbb{K}$ satisfies the \\textquotedblleft Neutrality\r\nof one\\textquotedblright\\ axiom (since it is a ring); thus, $a1_{\\mathbb{K}%\r\n}=1_{\\mathbb{K}}a=a$.\r\n\r\nThe definition of the operation $\\left.  \\widetilde{\\cdot}\\right.  $ yields\r\n$a\\left.  \\widetilde{\\cdot}\\right.  1_{\\mathbb{K}}=1_{\\mathbb{K}}a=a$ and\r\n$1_{\\mathbb{K}}\\left.  \\widetilde{\\cdot}\\right.  a=a1_{\\mathbb{K}}=a$.\r\nCombining these two equalities, we find $a\\left.  \\widetilde{\\cdot}\\right.\r\n1_{\\mathbb{K}}=1_{\\mathbb{K}}\\left.  \\widetilde{\\cdot}\\right.  a=a$. Thus, the\r\n\\textquotedblleft Neutrality of one\\textquotedblright\\ axiom is proven.]\r\n\r\n[\\textit{Proof of the \\textquotedblleft Annihilation\\textquotedblright%\r\n\\ axiom:} Let $a\\in\\mathbb{K}$. We must prove that $a\\left.  \\widetilde{\\cdot\r\n}\\right.  0_{\\mathbb{K}}=0_{\\mathbb{K}}\\left.  \\widetilde{\\cdot}\\right.\r\na=0_{\\mathbb{K}}$.\r\n\r\nBut the original ring $\\mathbb{K}$ satisfies the \\textquotedblleft\r\nAnnihilation\\textquotedblright\\ axiom (since it is a ring); thus,\r\n$a0_{\\mathbb{K}}=0_{\\mathbb{K}}a=0_{\\mathbb{K}}$.\r\n\r\nThe definition of the operation $\\left.  \\widetilde{\\cdot}\\right.  $ yields\r\n$a\\left.  \\widetilde{\\cdot}\\right.  0_{\\mathbb{K}}=0_{\\mathbb{K}%\r\n}a=0_{\\mathbb{K}}$ and $0_{\\mathbb{K}}\\left.  \\widetilde{\\cdot}\\right.\r\na=a0_{\\mathbb{K}}=0_{\\mathbb{K}}$. Combining these two equalities, we find\r\n$a\\left.  \\widetilde{\\cdot}\\right.  0_{\\mathbb{K}}=0_{\\mathbb{K}}\\left.\r\n\\widetilde{\\cdot}\\right.  a=0_{\\mathbb{K}}$. Thus, the \\textquotedblleft\r\nAnnihilation\\textquotedblright\\ axiom is proven.]\r\n\r\n[\\textit{Proof of the \\textquotedblleft Distributivity\\textquotedblright%\r\n\\ axiom:} Let $a,b,c\\in\\mathbb{K}$. We must prove that%\r\n\\[\r\na\\left.  \\widetilde{\\cdot}\\right.  \\left(  b+c\\right)  =a\\left.\r\n\\widetilde{\\cdot}\\right.  b+a\\left.  \\widetilde{\\cdot}\\right.\r\nc\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\text{and}\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\left(  a+b\\right)  \\left.\r\n\\widetilde{\\cdot}\\right.  c=a\\left.  \\widetilde{\\cdot}\\right.  c+b\\left.\r\n\\widetilde{\\cdot}\\right.  c.\r\n\\]\r\n\r\n\r\nBut the original ring $\\mathbb{K}$ satisfies the \\textquotedblleft\r\nDistributivity\\textquotedblright\\ axiom (since it is a ring); thus,%\r\n\\[\r\nc\\left(  a+b\\right)  =ca+cb\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\text{and}%\r\n\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\left(  b+c\\right)  a=ba+ca.\r\n\\]\r\n\r\n\r\nThe definition of the operation $\\left.  \\widetilde{\\cdot}\\right.  $ yields\r\n$a\\left.  \\widetilde{\\cdot}\\right.  \\left(  b+c\\right)  =\\left(  b+c\\right)\r\na$ and $a\\left.  \\widetilde{\\cdot}\\right.  b=ba$ and $a\\left.\r\n\\widetilde{\\cdot}\\right.  c=ca$. Thus,%\r\n\\[\r\na\\left.  \\widetilde{\\cdot}\\right.  \\left(  b+c\\right)  =\\left(  b+c\\right)\r\na=ba+ca.\r\n\\]\r\nComparing this with $\\underbrace{a\\left.  \\widetilde{\\cdot}\\right.  b}%\r\n_{=ba}+\\underbrace{a\\left.  \\widetilde{\\cdot}\\right.  c}_{=ca}=ba+ca$, we\r\nobtain $a\\left.  \\widetilde{\\cdot}\\right.  \\left(  b+c\\right)  =a\\left.\r\n\\widetilde{\\cdot}\\right.  b+a\\left.  \\widetilde{\\cdot}\\right.  c$.\r\n\r\nThe definition of the operation $\\left.  \\widetilde{\\cdot}\\right.  $ yields\r\n$\\left(  a+b\\right)  \\left.  \\widetilde{\\cdot}\\right.  c=c\\left(  a+b\\right)\r\n$ and $a\\left.  \\widetilde{\\cdot}\\right.  c=ca$ and $b\\left.  \\widetilde{\\cdot\r\n}\\right.  c=cb$. Thus,%\r\n\\[\r\n\\left(  a+b\\right)  \\left.  \\widetilde{\\cdot}\\right.  c=c\\left(  a+b\\right)\r\n=ca+cb.\r\n\\]\r\nComparing this with $\\underbrace{a\\left.  \\widetilde{\\cdot}\\right.  c}%\r\n_{=ca}+\\underbrace{b\\left.  \\widetilde{\\cdot}\\right.  c}_{=cb}=ca+cb$, we\r\nobtain $\\left(  a+b\\right)  \\left.  \\widetilde{\\cdot}\\right.  c=a\\left.\r\n\\widetilde{\\cdot}\\right.  c+b\\left.  \\widetilde{\\cdot}\\right.  c$.\r\n\r\nThus, we have proven the equalities%\r\n\\[\r\na\\left.  \\widetilde{\\cdot}\\right.  \\left(  b+c\\right)  =a\\left.\r\n\\widetilde{\\cdot}\\right.  b+a\\left.  \\widetilde{\\cdot}\\right.\r\nc\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\text{and}\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\left(  a+b\\right)  \\left.\r\n\\widetilde{\\cdot}\\right.  c=a\\left.  \\widetilde{\\cdot}\\right.  c+b\\left.\r\n\\widetilde{\\cdot}\\right.  c.\r\n\\]\r\nHence, the \\textquotedblleft Associativity of multiplication\\textquotedblright%\r\n\\ axiom is proven.]\r\n\r\nWe have now shown that the set $\\mathbb{K}$, equipped with the addition $+$,\r\nthe multiplication $\\left.  \\widetilde{\\cdot}\\right.  $, the zero\r\n$0_{\\mathbb{K}}$ and the unity $1_{\\mathbb{K}}$, satisfies all the eight ring\r\naxioms. Hence, it is a ring. This solves part \\textbf{(a)} of the problem.\r\n\r\n\\bigskip\r\n\r\n\\textbf{(b)} $\\Longrightarrow:$ Assume that $\\operatorname{id}:\\mathbb{K}%\r\n\\rightarrow\\mathbb{K}$ is a ring isomorphism from $\\mathbb{K}$ to\r\n$\\mathbb{K}^{\\operatorname{op}}$. We must prove that $\\mathbb{K}$ is commutative.\r\n\r\nWe have assumed that $\\operatorname*{id}$ is a ring isomorphism from\r\n$\\mathbb{K}$ to $\\mathbb{K}^{\\operatorname{op}}$. Thus, in particular,\r\n$\\operatorname*{id}$ is a ring homomorphism from $\\mathbb{K}$ to\r\n$\\mathbb{K}^{\\operatorname{op}}$ (since any ring isomorphism must be a ring homomorphism).\r\n\r\nRecall that if $\\mathbb{U}$ and $\\mathbb{V}$ are two rings, and if $f$ is a\r\nring homomorphism from $\\mathbb{U}$ to $\\mathbb{V}$, then%\r\n\\begin{equation}\r\nf\\left(  a\\cdot b\\right)  =f\\left(  a\\right)  \\cdot f\\left(  b\\right)\r\n\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\text{for all }a,b\\in\\mathbb{U}.\r\n\\label{sol.ring.op.b.fwd.1}%\r\n\\end{equation}\r\n(Indeed, this is one of the four axioms in our definition of a ring\r\nhomomorphism.) But keep in mind that the two \\textquotedblleft$\\cdot\r\n$\\textquotedblright\\ signs in the equality \\eqref{sol.ring.op.b.fwd.1} have\r\ndifferent meanings: The \\textquotedblleft$\\cdot$\\textquotedblright\\ sign on\r\nthe left hand side stands for the multiplication of the ring $\\mathbb{U}$,\r\nwhereas the \\textquotedblleft$\\cdot$\\textquotedblright\\ sign on the right hand\r\nside stands for the multiplication of the ring $\\mathbb{V}$. Thus,\r\n\\eqref{sol.ring.op.b.fwd.1} (applied to $\\mathbb{U}=\\mathbb{K}$,\r\n$\\mathbb{V}=\\mathbb{K}^{\\operatorname*{op}}$ and $f=\\operatorname*{id}$)\r\nyields%\r\n\\begin{equation}\r\n\\operatorname*{id}\\left(  a\\cdot b\\right)  =\\operatorname*{id}\\left(\r\na\\right)  \\left.  \\widetilde{\\cdot}\\right.  \\operatorname*{id}\\left(\r\nb\\right)  \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\text{for all }a,b\\in\\mathbb{K}\r\n\\label{sol.ring.op.b.fwd.2}%\r\n\\end{equation}\r\n(since $\\operatorname*{id}$ is a ring homomorphism from $\\mathbb{K}$ to\r\n$\\mathbb{K}^{\\operatorname{op}}$, and since the multiplication of the ring\r\n$\\mathbb{K}$ is denoted by \\textquotedblleft$\\cdot$\\textquotedblright\\ whereas\r\nthe multiplication of the ring $\\mathbb{K}^{\\operatorname*{op}}$ is denoted by\r\n\\textquotedblleft$\\left.  \\widetilde{\\cdot}\\right.  $\\textquotedblright).\r\n\r\nNow, if $a,b\\in\\mathbb{K}$, then%\r\n\\begin{align*}\r\nab  &  =a\\cdot b=\\operatorname*{id}\\left(  a\\cdot b\\right)\r\n=\\underbrace{\\operatorname*{id}\\left(  a\\right)  }_{=a}\\left.\r\n\\widetilde{\\cdot}\\right.  \\underbrace{\\operatorname*{id}\\left(  b\\right)\r\n}_{=b}\\qquad\\left(  \\text{by \\eqref{sol.ring.op.b.fwd.2}}\\right) \\\\\r\n&  =a\\left.  \\widetilde{\\cdot}\\right.  b=ba\\qquad\\left(  \\text{by the\r\ndefinition of the operation }\\left.  \\widetilde{\\cdot}\\right.  \\right)  .\r\n\\end{align*}\r\nIn other words, the ring $\\mathbb{K}$ satisfies the \\textquotedblleft\r\nCommutativity of multiplication\\textquotedblright\\ axiom. In other words, the\r\nring $\\mathbb{K}$ is commutative. This proves the \\textquotedblleft%\r\n$\\Longrightarrow$\\textquotedblright\\ direction of part \\textbf{(b)}.\r\n\r\n$\\Longleftarrow:$ Assume that $\\mathbb{K}$ is commutative. We must prove that\r\n$\\operatorname{id}:\\mathbb{K}\\rightarrow\\mathbb{K}$ is a ring isomorphism from\r\n$\\mathbb{K}$ to $\\mathbb{K}^{\\operatorname{op}}$.\r\n\r\nIf $a,b\\in\\mathbb{K}$, then%\r\n\\begin{align*}\r\na\\left.  \\widetilde{\\cdot}\\right.  b  &  =ba\\qquad\\left(  \\text{by the\r\ndefinition of the operation }\\left.  \\widetilde{\\cdot}\\right.  \\right) \\\\\r\n&  =ab\\qquad\\left(  \\text{since the ring }\\mathbb{K}\\text{ is commutative}%\r\n\\right) \\\\\r\n&  =a\\cdot b.\r\n\\end{align*}\r\nThus, the binary operation $\\left.  \\widetilde{\\cdot}\\right.  $ is identical\r\nwith the binary operation $\\cdot$.\r\n\r\nBut the only difference between the rings $\\mathbb{K}$ and $\\mathbb{K}%\r\n^{\\operatorname*{op}}$ is that $\\mathbb{K}^{\\operatorname*{op}}$ has the\r\nmultiplication $\\left.  \\widetilde{\\cdot}\\right.  $ while $\\mathbb{K}$ has the\r\nmultiplication $\\cdot$. (All the remaining structure of $\\mathbb{K}$ and\r\n$\\mathbb{K}^{\\operatorname*{op}}$ is the same.) But since we have shown that\r\n$\\left.  \\widetilde{\\cdot}\\right.  $ is identical with $\\cdot$, we see that\r\nthis difference is not actually a difference either; the multiplications of\r\n$\\mathbb{K}$ and $\\mathbb{K}^{\\operatorname*{op}}$ are also the same. Hence,\r\nthe ring $\\mathbb{K}^{\\operatorname*{op}}$ is completely identical to the ring\r\n$\\mathbb{K}$ (not just as sets, but as rings with all their structure).\r\n\r\nBut recall that $\\operatorname*{id}:\\mathbb{K}\\rightarrow\\mathbb{K}$ is a ring\r\nisomorphism from $\\mathbb{K}$ to $\\mathbb{K}$. Since the ring $\\mathbb{K}%\r\n^{\\operatorname*{op}}$ is completely identical to the ring $\\mathbb{K}$, we\r\ncan replace the last \\textquotedblleft$\\mathbb{K}$\\textquotedblright\\ in this\r\nsentence by \\textquotedblleft$\\mathbb{K}^{\\operatorname*{op}}$%\r\n\\textquotedblright\\ without changing its meaning. Thus, we obtain that\r\n$\\operatorname*{id}:\\mathbb{K}\\rightarrow\\mathbb{K}$ is a ring isomorphism\r\nfrom $\\mathbb{K}$ to $\\mathbb{K}^{\\operatorname*{op}}$. This proves the\r\n\\textquotedblleft$\\Longleftarrow$\\textquotedblright\\ direction of part\r\n\\textbf{(b)}.\r\n\r\n\\bigskip\r\n\r\n\\textbf{(c)} Let us quote the following fact from \\cite[Exercise\r\n6.5]{detnotes} (except that we are replacing $\\mathbb{K}$ by $\\mathbb{L}$):\r\n\r\n\\begin{proposition}\r\n\\label{prop.sol.ring.op.c.transp.helper}Let $\\mathbb{L}$ be a commutative\r\nring. In this proposition, all matrices are over $\\mathbb{L}$.\r\n\r\n\\textbf{(a)} If $u$, $v$ and $w$ are three nonnegative integers, if $P$ is a\r\n$u\\times v$-matrix, and if $Q$ is a $v\\times w$-matrix, then%\r\n\\[\r\n\\left(  PQ\\right)  ^{T}=Q^{T}P^{T}.\r\n\\]\r\n\r\n\r\n\\textbf{(b)} Every $u\\in\\mathbb{N}$ satisfies%\r\n\\[\r\n\\left(  I_{u}\\right)  ^{T}=I_{u}.\r\n\\]\r\n\r\n\r\n\\textbf{(c)} If $u$ and $v$ are two nonnegative integers, if $P$ is a $u\\times\r\nv$-matrix, and if $\\lambda\\in\\mathbb{L}$, then%\r\n\\[\r\n\\left(  \\lambda P\\right)  ^{T}=\\lambda P^{T}.\r\n\\]\r\n\r\n\r\n\\textbf{(d)} If $u$ and $v$ are two nonnegative integers, and if $P$ and $Q$\r\nare two $u\\times v$-matrices, then%\r\n\\[\r\n\\left(  P+Q\\right)  ^{T}=P^{T}+Q^{T}.\r\n\\]\r\n\r\n\r\n\\textbf{(e)} If $u$ and $v$ are two nonnegative integers, and if $P$ is a\r\n$u\\times v$-matrix, then%\r\n\\[\r\n\\left(  P^{T}\\right)  ^{T}=P.\r\n\\]\r\n\r\n\\end{proposition}\r\n\r\nNow, let $\\mathbf{T}$ be the map%\r\n\\[\r\n\\mathbb{K}\\rightarrow\\mathbb{K}^{\\operatorname{op}},\\qquad A\\mapsto A^{T}.\r\n\\]\r\nWe must prove that $\\mathbf{T}$ is a ring isomorphism.\r\n\r\nIn class\\footnote{specifically, Proposition 5.10.5 in\r\n\\href{http://www.cip.ifi.lmu.de/~grinberg/t/19s/notes.pdf}{the class notes};\r\nbut the numbering may change}, we have proven that any invertible ring\r\nhomomorphism is a ring isomorphism. Hence, it suffices to prove that\r\n$\\mathbf{T}$ is an invertible ring homomorphism.\r\n\r\nLet us first prove that $\\mathbf{T}$ is a ring homomorphism. In order to do\r\nso, we need to verify the following four claims:\r\n\r\n\\begin{statement}\r\n\\textit{Claim 1:} We have $\\mathbf{T}\\left(  a+b\\right)  =\\mathbf{T}\\left(\r\na\\right)  +\\mathbf{T}\\left(  b\\right)  $ for all $a,b\\in\\mathbb{K}$.\r\n\\end{statement}\r\n\r\n\\begin{statement}\r\n\\textit{Claim 2:} We have $\\mathbf{T}\\left(  0_{\\mathbb{K}}\\right)\r\n=0_{\\mathbb{K}^{\\operatorname*{op}}}$.\r\n\\end{statement}\r\n\r\n\\begin{statement}\r\n\\textit{Claim 3:} We have $\\mathbf{T}\\left(  ab\\right)  =\\mathbf{T}\\left(\r\na\\right)  \\left.  \\widetilde{\\cdot}\\right.  \\mathbf{T}\\left(  b\\right)  $ for\r\nall $a,b\\in\\mathbb{K}$.\r\n\\end{statement}\r\n\r\n\\begin{statement}\r\n\\textit{Claim 4:} We have $\\mathbf{T}\\left(  1_{\\mathbb{K}}\\right)\r\n=1_{\\mathbb{K}^{\\operatorname*{op}}}$.\r\n\\end{statement}\r\n\r\n(Note the \\textquotedblleft$\\left.  \\widetilde{\\cdot}\\right.  $%\r\n\\textquotedblright\\ sign on the right hand side of Claim 3; this is because\r\n$\\mathbf{T}\\left(  a\\right)  $ and $\\mathbf{T}\\left(  b\\right)  $ are being\r\nconsidered as elements of $\\mathbb{K}^{\\operatorname*{op}}$, and the\r\nmultiplication of the ring $\\mathbb{K}^{\\operatorname*{op}}$ is $\\left.\r\n\\widetilde{\\cdot}\\right.  $.)\r\n\r\nLet us now prove these claims:\r\n\r\n[\\textit{Proof of Claim 3:} Let $a,b\\in\\mathbb{K}$. Then, $a\\in\\mathbb{K}%\r\n=\\mathbb{L}^{n\\times n}$ and $b\\in\\mathbb{K}=\\mathbb{L}^{n\\times n}$. Hence,\r\n$a$ and $b$ are two $n\\times n$-matrices over $\\mathbb{L}$. The definition of\r\n$\\mathbf{T}$ yields $\\mathbf{T}\\left(  ab\\right)  =\\left(  ab\\right)  ^{T}$\r\nand $\\mathbf{T}\\left(  a\\right)  =a^{T}$ and $\\mathbf{T}\\left(  b\\right)\r\n=b^{T}$. The definition of the operation $\\left.  \\widetilde{\\cdot}\\right.  $\r\nyields $\\mathbf{T}\\left(  a\\right)  \\left.  \\widetilde{\\cdot}\\right.\r\n\\mathbf{T}\\left(  b\\right)  =\\underbrace{\\mathbf{T}\\left(  b\\right)  }%\r\n_{=b^{T}}\\underbrace{\\mathbf{T}\\left(  a\\right)  }_{=a^{T}}=b^{T}a^{T}$. But\r\n$\\mathbf{T}\\left(  ab\\right)  =\\left(  ab\\right)  ^{T}=b^{T}a^{T}$ (by\r\nProposition \\ref{prop.sol.ring.op.c.transp.helper} \\textbf{(a)}, applied to\r\n$u=n$, $v=n$, $w=n$, $P=a$ and $Q=b$). Comparing these two equalities, we\r\nobtain $\\mathbf{T}\\left(  ab\\right)  =\\mathbf{T}\\left(  a\\right)  \\left.\r\n\\widetilde{\\cdot}\\right.  \\mathbf{T}\\left(  b\\right)  $. This proves Claim 3.]\r\n\r\n[\\textit{Proof of Claim 1:} Let $a,b\\in\\mathbb{K}$. Then, $a\\in\\mathbb{K}%\r\n=\\mathbb{L}^{n\\times n}$ and $b\\in\\mathbb{K}=\\mathbb{L}^{n\\times n}$. Hence,\r\n$a$ and $b$ are two $n\\times n$-matrices over $\\mathbb{L}$. The definition of\r\n$\\mathbf{T}$ yields $\\mathbf{T}\\left(  a+b\\right)  =\\left(  a+b\\right)  ^{T}$\r\nand $\\mathbf{T}\\left(  a\\right)  =a^{T}$ and $\\mathbf{T}\\left(  b\\right)\r\n=b^{T}$. But $\\underbrace{\\mathbf{T}\\left(  a\\right)  }_{=a^{T}}%\r\n+\\underbrace{\\mathbf{T}\\left(  b\\right)  }_{=b^{T}}=a^{T}b^{T}$. But\r\n$\\mathbf{T}\\left(  a+b\\right)  =\\left(  a+b\\right)  ^{T}=a^{T}+b^{T}$ (by\r\nProposition \\ref{prop.sol.ring.op.c.transp.helper} \\textbf{(d)}, applied to\r\n$u=n$, $v=n$, $P=a$ and $Q=b$). Comparing these two equalities, we obtain\r\n$\\mathbf{T}\\left(  a+b\\right)  =\\mathbf{T}\\left(  a\\right)  +\\mathbf{T}\\left(\r\nb\\right)  $. This proves Claim 1.]\r\n\r\n[\\textit{Proof of Claim 2:} We have $0_{\\mathbb{K}}=0_{n\\times n}$ (by the\r\ndefinition of the ring $\\mathbb{K}=\\mathbb{L}^{n\\times n}$). Applying the map\r\n$\\mathbf{T}$ to both sides of this equality, we obtain $\\mathbf{T}\\left(\r\n0_{\\mathbb{K}}\\right)  =\\mathbf{T}\\left(  0_{n\\times n}\\right)  =\\left(\r\n0_{n\\times n}\\right)  ^{T}$ (by the definition of $\\mathbf{T}$). But the\r\ndefinition of the transpose of a matrix easily yields $\\left(  0_{n\\times\r\nn}\\right)  ^{T}=0_{n\\times n}$. Hence, $\\mathbf{T}\\left(  0_{\\mathbb{K}%\r\n}\\right)  =\\left(  0_{n\\times n}\\right)  ^{T}=0_{n\\times n}$. But the\r\ndefinition of the ring $\\mathbb{K}^{\\operatorname*{op}}$ yields $0_{\\mathbb{K}%\r\n^{\\operatorname*{op}}}=0_{\\mathbb{K}}=0_{n\\times n}$. Comparing the latter two\r\nequalities, we obtain $\\mathbf{T}\\left(  0_{\\mathbb{K}}\\right)  =0_{\\mathbb{K}%\r\n^{\\operatorname*{op}}}$. This proves Claim 2.]\r\n\r\n[\\textit{Proof of Claim 4:} We have $1_{\\mathbb{K}}=I_{n}$ (by the definition\r\nof the ring $\\mathbb{K}=\\mathbb{L}^{n\\times n}$). Applying the map\r\n$\\mathbf{T}$ to both sides of this equality, we obtain $\\mathbf{T}\\left(\r\n1_{\\mathbb{K}}\\right)  =\\mathbf{T}\\left(  I_{n}\\right)  =\\left(  I_{n}\\right)\r\n^{T}$ (by the definition of $\\mathbf{T}$). But Proposition\r\n\\ref{prop.sol.ring.op.c.transp.helper} \\textbf{(b)} (applied to $u=n$) yields\r\n$\\left(  I_{n}\\right)  ^{T}=I_{n}$. Hence, $\\mathbf{T}\\left(  1_{\\mathbb{K}%\r\n}\\right)  =\\left(  I_{n}\\right)  ^{T}=I_{n}$. But the definition of the ring\r\n$\\mathbb{K}^{\\operatorname*{op}}$ yields $1_{\\mathbb{K}^{\\operatorname*{op}}%\r\n}=1_{\\mathbb{K}}=I_{n}$. Comparing the latter two equalities, we obtain\r\n$\\mathbf{T}\\left(  1_{\\mathbb{K}}\\right)  =1_{\\mathbb{K}^{\\operatorname*{op}}%\r\n}$. This proves Claim 4.]\r\n\r\nWe have now proven all four Claims 1, 2, 3 and 4. Hence, $\\mathbf{T}$ is a\r\nring homomorphism from $\\mathbb{K}$ to $\\mathbb{K}^{\\operatorname*{op}}$ (by\r\nthe definition of a ring homomorphism).\r\n\r\nLet us next prove that the map $\\mathbf{T}$ is invertible. In proving this, we\r\ndo not need to concern ourselves with the ring structures (i.e., the\r\nadditions, multiplications, zeroes and unities) of $\\mathbb{K}$ and\r\n$\\mathbb{K}^{\\operatorname*{op}}$, but can simply consider $\\mathbb{K}$ and\r\n$\\mathbb{K}^{\\operatorname*{op}}$ as sets (because the invertibility of a map\r\nhas nothing to do with any ring structures).\r\n\r\nRecall that $\\mathbb{K}^{\\operatorname*{op}}=\\mathbb{K}$ \\textbf{as sets}.\r\nThus, the map $\\mathbf{T}$ is a map from $\\mathbb{K}$ to $\\mathbb{K}$ (since\r\n$\\mathbf{T}$ is a map from $\\mathbb{K}$ to $\\mathbb{K}^{\\operatorname*{op}}$).\r\nHence, the map $\\mathbf{T}\\circ\\mathbf{T}:\\mathbb{K}\\rightarrow\\mathbb{K}$ is\r\nwell-defined. Moreover, each $P\\in\\mathbb{K}$ satisfies%\r\n\\begin{align*}\r\n\\left(  \\mathbf{T}\\circ\\mathbf{T}\\right)  \\left(  P\\right)   &  =\\mathbf{T}%\r\n\\left(  \\underbrace{\\mathbf{T}\\left(  P\\right)  }_{\\substack{=P^{T}\\\\\\text{(by\r\nthe definition of }\\mathbf{T}\\text{)}}}\\right)  =\\mathbf{T}\\left(\r\nP^{T}\\right)  =\\left(  P^{T}\\right)  ^{T}\\qquad\\left(  \\text{by the definition\r\nof }\\mathbf{T}\\right) \\\\\r\n&  =P\\qquad\\left(  \\text{by Proposition \\ref{prop.sol.ring.op.c.transp.helper}\r\n\\textbf{(e)} (applied to }u=n\\text{ and }v=n\\text{)}\\right) \\\\\r\n&  =\\operatorname*{id}\\left(  P\\right)  .\r\n\\end{align*}\r\nIn other words, $\\mathbf{T}\\circ\\mathbf{T}=\\operatorname*{id}$. Hence, the\r\nmaps $\\mathbf{T}:\\mathbb{K}\\rightarrow\\mathbb{K}$ and $\\mathbf{T}%\r\n:\\mathbb{K}\\rightarrow\\mathbb{K}$ are mutually inverse. Thus, the map\r\n$\\mathbf{T}:\\mathbb{K}\\rightarrow\\mathbb{K}$ is invertible. In other words,\r\nthe map $\\mathbf{T}:\\mathbb{K}\\rightarrow\\mathbb{K}^{\\operatorname*{op}}$ is\r\ninvertible (since $\\mathbb{K}=\\mathbb{K}^{\\operatorname*{op}}$ as sets).\r\n\r\nSo we have proven that the map $\\mathbf{T}:\\mathbb{K}\\rightarrow\r\n\\mathbb{K}^{\\operatorname*{op}}$ is an invertible ring homomorphism from\r\n$\\mathbb{K}$ to $\\mathbb{K}^{\\operatorname*{op}}$. Thus, this map $\\mathbf{T}$\r\nis a ring isomorphism from $\\mathbb{K}$ to $\\mathbb{K}^{\\operatorname*{op}}$\r\n(since any invertible ring homomorphism is a ring isomorphism). This solves\r\npart \\textbf{(c)} of the exercise.\r\n\r\n%----------------------------------------------------------------------------------------\r\n%\tEXERCISE 2\r\n%----------------------------------------------------------------------------------------\r\n\\rule{\\linewidth}{0.3pt} \\\\[0.4cm]\r\n\r\n\\section{Exercise 2: More ring isomorphisms}\r\n\r\n\\subsection{Problem}\r\n\r\n\\begin{enumerate}\r\n\\item[\\textbf{(a)}] Let $\\mathbb{L}$ be a ring. Let $w \\in\\mathbb{L}$ be an\r\ninvertible element. Prove that the map\r\n\\[\r\n\\mathbb{L} \\to\\mathbb{L} , \\qquad a \\mapsto waw^{-1}\r\n\\]\r\nis a ring isomorphism.\r\n\r\n\\item[\\textbf{(b)}] Let $\\mathbb{K}$ be a ring. Let $W$ be the $n \\times\r\nn$-matrix\r\n\\[\r\n\\left(  \\left[  i + j = n + 1 \\right]  \\right)  _{1\\leq i\\leq n,\\ 1\\leq j\\leq\r\nn} =\r\n\\begin{pmatrix}\r\n0 & \\cdots & 0 & 0 & 1\\\\\r\n0 & \\cdots & 0 & 1 & 0\\\\\r\n0 & \\cdots & 1 & 0 & 0\\\\\r\n\\vdots & \\iddots & \\vdots & \\vdots & \\vdots\\\\\r\n1 & \\cdots & 0 & 0 & 0\r\n\\end{pmatrix}\r\n\\in\\mathbb{K}^{n \\times n}\r\n\\]\r\n(where we are using \\href{https://en.wikipedia.org/wiki/Iverson_bracket}{the\r\nIverson bracket notation} again).\r\n\r\nProve that $W = W^{-1}$.\r\n\r\n\\item[\\textbf{(c)}] Let $A = \\left(  a_{i,j} \\right)  _{1\\leq i\\leq n,\\ 1\\leq\r\nj\\leq n} \\in\\mathbb{K}^{n \\times n}$ be any $n \\times n$-matrix. Prove that\r\n\\[\r\nWAW^{-1} = \\left(  a_{n+1-i,n+1-j} \\right)  _{1\\leq i\\leq n,\\ 1\\leq j\\leq n}.\r\n\\]\r\n(In other words, $WAW^{-1}$ is the $n \\times n$-matrix obtained from $A$ by\r\nreversing the order of the rows and also reversing the order of the columns.)\r\n\\end{enumerate}\r\n\r\n\\subsection{Remark}\r\n\r\nThe map\r\n\\[\r\n\\mathbb{L} \\to\\mathbb{L} , \\qquad a \\mapsto waw^{-1}\r\n\\]\r\nin part \\textbf{(a)} of this exercise is called \\textit{conjugation by $w$}.\r\nIt is best known in the case of a matrix ring, where it corresponds to a\r\nchange of basis for an endomorphism of a vector space. When $\\mathbb{K}$ is a\r\nfield, the \\textbf{only} ring isomorphisms $\\mathbb{K}^{n \\times n}\r\n\\to\\mathbb{K}^{n \\times n}$ are conjugations by invertible matrices; this is\r\nthe Noether--Skolem theorem (in one of its less general variants).\r\n\r\n\\subsection{Solution}\r\n\r\n\\textbf{(a)} Let $f$ be the map%\r\n\\[\r\n\\mathbb{L}\\rightarrow\\mathbb{L},\\qquad a\\mapsto waw^{-1}.\r\n\\]\r\nWe must prove that $f$ is a ring isomorphism.\r\n\r\nIn class, we have proven that any invertible ring homomorphism is a ring\r\nisomorphism. Hence, it suffices to prove that $f$ is an invertible ring homomorphism.\r\n\r\nLet us first prove that $f$ is a ring homomorphism. In order to do so, we need\r\nto verify the following four claims:\r\n\r\n\\begin{statement}\r\n\\textit{Claim 1:} We have $f\\left(  a+b\\right)  =f\\left(  a\\right)  +f\\left(\r\nb\\right)  $ for all $a,b\\in\\mathbb{L}$.\r\n\\end{statement}\r\n\r\n\\begin{statement}\r\n\\textit{Claim 2:} We have $f\\left(  0\\right)  =0$.\r\n\\end{statement}\r\n\r\n\\begin{statement}\r\n\\textit{Claim 3:} We have $f\\left(  ab\\right)  =f\\left(  a\\right)  f\\left(\r\nb\\right)  $ for all $a,b\\in\\mathbb{L}$.\r\n\\end{statement}\r\n\r\n\\begin{statement}\r\n\\textit{Claim 4:} We have $f\\left(  1\\right)  =1$.\r\n\\end{statement}\r\n\r\nLet us now prove these claims:\r\n\r\n[\\textit{Proof of Claim 1:} Let $a,b\\in\\mathbb{L}$. The definition of $f$\r\nyields $f\\left(  a\\right)  =waw^{-1}$ and $f\\left(  b\\right)  =wbw^{-1}$ and\r\n$f\\left(  a+b\\right)  =w\\left(  a+b\\right)  w^{-1}$. Hence,%\r\n\\begin{align*}\r\nf\\left(  a+b\\right)   &  =w\\underbrace{\\left(  a+b\\right)  w^{-1}%\r\n}_{\\substack{=aw^{-1}+bw^{-1}\\\\\\text{(by distributivity)}}}=w\\left(\r\naw^{-1}+bw^{-1}\\right)  =\\underbrace{waw^{-1}}_{=f\\left(  a\\right)\r\n}+\\underbrace{wbw^{-1}}_{=f\\left(  b\\right)  }\\qquad\\left(  \\text{by\r\ndistributivity}\\right) \\\\\r\n&  =f\\left(  a\\right)  +f\\left(  b\\right)  .\r\n\\end{align*}\r\nThis proves Claim 1.]\r\n\r\n[\\textit{Proof of Claim 2:} The definition of $f$ yields $f\\left(  0\\right)\r\n=w\\underbrace{0w^{-1}}_{=0}=w0=0$. This proves Claim 2.]\r\n\r\n[\\textit{Proof of Claim 3:} Let $a,b\\in\\mathbb{L}$. The definition of $f$\r\nyields $f\\left(  a\\right)  =waw^{-1}$ and $f\\left(  b\\right)  =wbw^{-1}$ and\r\n$f\\left(  ab\\right)  =w\\left(  ab\\right)  w^{-1}$. Hence,%\r\n\\[\r\n\\underbrace{f\\left(  a\\right)  }_{=waw^{-1}}\\ \\ \\underbrace{f\\left(  b\\right)\r\n}_{=wbw^{-1}}=wa\\underbrace{w^{-1}w}_{=1}bw^{-1}=wabw^{-1}=w\\left(  ab\\right)\r\nw^{-1}=f\\left(  ab\\right)  .\r\n\\]\r\nIn other words, $f\\left(  ab\\right)  =f\\left(  a\\right)  f\\left(  b\\right)  $.\r\nThis proves Claim 3.]\r\n\r\n[\\textit{Proof of Claim 4:} The definition of $f$ yields $f\\left(  1\\right)\r\n=w\\underbrace{1w^{-1}}_{=w^{-1}}=ww^{-1}=1$. This proves Claim 4.]\r\n\r\nWe have now proven all four Claims 1, 2, 3 and 4. Hence, $f$ is a ring\r\nhomomorphism from $\\mathbb{L}$ to $\\mathbb{L}$ (by the definition of a ring homomorphism).\r\n\r\nLet us next prove that the map $f$ is invertible.\r\n\r\nIndeed, let $g$ be the map%\r\n\\[\r\n\\mathbb{L}\\rightarrow\\mathbb{L},\\qquad a\\mapsto w^{-1}aw.\r\n\\]\r\n\r\n\r\nThen, each $a\\in\\mathbb{L}$ satisfies%\r\n\\begin{align*}\r\n\\left(  g\\circ f\\right)  \\left(  a\\right)   &  =g\\left(  f\\left(  a\\right)\r\n\\right)  =w^{-1}\\underbrace{f\\left(  a\\right)  }_{\\substack{=waw^{-1}%\r\n\\\\\\text{(by the definition of }f\\text{)}}}w\\qquad\\left(  \\text{by the\r\ndefinition of }g\\right) \\\\\r\n&  =\\underbrace{w^{-1}w}_{=1}a\\underbrace{w^{-1}w}_{=1}=a=\\operatorname*{id}%\r\n\\left(  a\\right)  .\r\n\\end{align*}\r\nIn other words, $g\\circ f=\\operatorname*{id}$.\r\n\r\nAlso, each $a\\in\\mathbb{L}$ satisfies%\r\n\\begin{align*}\r\n\\left(  f\\circ g\\right)  \\left(  a\\right)   &  =f\\left(  g\\left(  a\\right)\r\n\\right)  =w\\underbrace{g\\left(  a\\right)  }_{\\substack{=w^{-1}aw\\\\\\text{(by\r\nthe definition of }g\\text{)}}}w^{-1}\\qquad\\left(  \\text{by the definition of\r\n}f\\right) \\\\\r\n&  =\\underbrace{ww^{-1}}_{=1}a\\underbrace{ww^{-1}}_{=1}=a=\\operatorname*{id}%\r\n\\left(  a\\right)  .\r\n\\end{align*}\r\nIn other words, $f\\circ g=\\operatorname*{id}$.\r\n\r\nNow, the two maps $f$ and $g$ are mutually inverse (since $f\\circ\r\ng=\\operatorname*{id}$ and $g\\circ f=\\operatorname*{id}$). Thus, the map $f$ is invertible.\r\n\r\nSo we have proven that the map $f$ is an invertible ring homomorphism. Thus,\r\nthis map $f$ is a ring isomorphism (since any invertible ring homomorphism is\r\na ring isomorphism). This solves part \\textbf{(a)} of the exercise.\r\n\r\n\\bigskip\r\n\r\n\\textbf{(b)} We first show two auxiliary claims about how multiplication by\r\n$W$ changes a matrix:\r\n\r\n\\begin{statement}\r\n\\textit{Claim 5:} Let $A=\\left(  a_{i,j}\\right)  _{1\\leq i\\leq n,\\ 1\\leq j\\leq\r\nn}\\in\\mathbb{K}^{n\\times n}$ be any $n\\times n$-matrix. Then,%\r\n\\[\r\nWA=\\left(  a_{n+1-i,j}\\right)  _{1\\leq i\\leq n,\\ 1\\leq j\\leq n}.\r\n\\]\r\n\r\n\\end{statement}\r\n\r\n\\begin{statement}\r\n\\textit{Claim 6:} Let $A=\\left(  a_{i,j}\\right)  _{1\\leq i\\leq n,\\ 1\\leq j\\leq\r\nn}\\in\\mathbb{K}^{n\\times n}$ be any $n\\times n$-matrix. Then,%\r\n\\[\r\nAW=\\left(  a_{i,n+1-j}\\right)  _{1\\leq i\\leq n,\\ 1\\leq j\\leq n}.\r\n\\]\r\n\r\n\\end{statement}\r\n\r\n[\\textit{Proof of Claim 5:} We have $W=\\left(  \\left[  i+j=n+1\\right]\r\n\\right)  _{1\\leq i\\leq n,\\ 1\\leq j\\leq n}$ and $A=\\left(  a_{i,j}\\right)\r\n_{1\\leq i\\leq n,\\ 1\\leq j\\leq n}$. Hence, the definition of the multiplication\r\nof matrices yields%\r\n\\begin{equation}\r\nWA=\\left(  \\sum_{k=1}^{n}\\left[  i+k=n+1\\right]  a_{k,j}\\right)  _{1\\leq i\\leq\r\nn,\\ 1\\leq j\\leq n}. \\label{sol.ring.matrix.W-conj.b.c5.pf.1}%\r\n\\end{equation}\r\n\r\n\r\nNow, let $\\left(  i,j\\right)  \\in\\left\\{  1,2,\\ldots,n\\right\\}  ^{2}$. Thus,\r\n$i,j\\in\\left\\{  1,2,\\ldots,n\\right\\}  $. From $i\\in\\left\\{  1,2,\\ldots\r\n,n\\right\\}  $, we obtain $n+1-i\\in\\left\\{  1,2,\\ldots,n\\right\\}  $. Now,%\r\n\\begin{align}\r\n&  \\sum_{k=1}^{n}\\left[  i+k=n+1\\right]  a_{k,j}\\nonumber\\\\\r\n&  =\\sum_{k\\in\\left\\{  1,2,\\ldots,n\\right\\}  }\\left[  i+k=n+1\\right]\r\na_{k,j}\\nonumber\\\\\r\n&  =\\underbrace{\\left[  i+\\left(  n+1-i\\right)  =n+1\\right]  }%\r\n_{\\substack{=1\\\\\\text{(since }i+\\left(  n+1-i\\right)  =n+1\\text{)}%\r\n}}a_{n+1-i,j}+\\sum_{\\substack{k\\in\\left\\{  1,2,\\ldots,n\\right\\}  ;\\\\k\\neq\r\nn+1-i}}\\underbrace{\\left[  i+k=n+1\\right]  }_{\\substack{=0\\\\\\text{(since\r\n}i+k\\neq n+1\\\\\\text{(because }k\\neq n+1-i\\text{))}}}a_{k,j}\\nonumber\\\\\r\n&  \\qquad\\qquad\\left(\r\n\\begin{array}\r\n[c]{c}%\r\n\\text{here, we have split off the addend for }k=n+1-i\\text{ from the sum}\\\\\r\n\\text{(since }n+1-i\\in\\left\\{  1,2,\\ldots,n\\right\\}  \\text{)}%\r\n\\end{array}\r\n\\right) \\nonumber\\\\\r\n&  =a_{n+1-i,j}+\\underbrace{\\sum_{\\substack{k\\in\\left\\{  1,2,\\ldots,n\\right\\}\r\n;\\\\k\\neq n+1-i}}0a_{k,j}}_{=0}=a_{n+1-i,j}.\r\n\\label{sol.ring.matrix.W-conj.b.c5.pf.2}%\r\n\\end{align}\r\n\r\n\r\nNow, forget that we fixed $\\left(  i,j\\right)  $. We thus have proven\r\n\\eqref{sol.ring.matrix.W-conj.b.c5.pf.2} for each $\\left(  i,j\\right)\r\n\\in\\left\\{  1,2,\\ldots,n\\right\\}  ^{2}$. Thus, we have%\r\n\\[\r\n\\left(  \\sum_{k=1}^{n}\\left[  i+k=n+1\\right]  a_{k,j}\\right)  _{1\\leq i\\leq\r\nn,\\ 1\\leq j\\leq n}=\\left(  a_{n+1-i,j}\\right)  _{1\\leq i\\leq n,\\ 1\\leq j\\leq\r\nn}.\r\n\\]\r\nHence, \\eqref{sol.ring.matrix.W-conj.b.c5.pf.2} becomes%\r\n\\[\r\nWA=\\left(  \\sum_{k=1}^{n}\\left[  i+k=n+1\\right]  a_{k,j}\\right)  _{1\\leq i\\leq\r\nn,\\ 1\\leq j\\leq n}=\\left(  a_{n+1-i,j}\\right)  _{1\\leq i\\leq n,\\ 1\\leq j\\leq\r\nn}.\r\n\\]\r\nThis proves Claim 5.]\r\n\r\n[\\textit{Proof of Claim 6:} We have $A=\\left(  a_{i,j}\\right)  _{1\\leq i\\leq\r\nn,\\ 1\\leq j\\leq n}$ and $W=\\left(  \\left[  i+j=n+1\\right]  \\right)  _{1\\leq\r\ni\\leq n,\\ 1\\leq j\\leq n}$. Hence, the definition of the multiplication of\r\nmatrices yields%\r\n\\begin{equation}\r\nAW=\\left(  \\sum_{k=1}^{n}a_{i,k}\\left[  k+j=n+1\\right]  \\right)  _{1\\leq i\\leq\r\nn,\\ 1\\leq j\\leq n}. \\label{sol.ring.matrix.W-conj.b.c6.pf.1}%\r\n\\end{equation}\r\n\r\n\r\nNow, let $\\left(  i,j\\right)  \\in\\left\\{  1,2,\\ldots,n\\right\\}  ^{2}$. Thus,\r\n$i,j\\in\\left\\{  1,2,\\ldots,n\\right\\}  $. From $j\\in\\left\\{  1,2,\\ldots\r\n,n\\right\\}  $, we obtain $n+1-j\\in\\left\\{  1,2,\\ldots,n\\right\\}  $. Now,%\r\n\\begin{align}\r\n&  \\sum_{k=1}^{n}a_{i,k}\\left[  k+j=n+1\\right] \\nonumber\\\\\r\n&  =\\sum_{k\\in\\left\\{  1,2,\\ldots,n\\right\\}  }a_{i,k}\\left[  k+j=n+1\\right]\r\n\\nonumber\\\\\r\n&  =a_{i,n+1-j}\\underbrace{\\left[  \\left(  n+1-j\\right)  +j=n+1\\right]\r\n}_{\\substack{=1\\\\\\text{(since }\\left(  n+1-j\\right)  +j=n+1\\text{)}}%\r\n}+\\sum_{\\substack{k\\in\\left\\{  1,2,\\ldots,n\\right\\}  ;\\\\k\\neq n+1-j}%\r\n}a_{i,k}\\underbrace{\\left[  k+j=n+1\\right]  }_{\\substack{=0\\\\\\text{(since\r\n}k+j\\neq n+1\\\\\\text{(because }k\\neq n+1-j\\text{))}}}\\nonumber\\\\\r\n&  \\qquad\\qquad\\left(\r\n\\begin{array}\r\n[c]{c}%\r\n\\text{here, we have split off the addend for }k=n+1-j\\text{ from the sum}\\\\\r\n\\text{(since }n+1-j\\in\\left\\{  1,2,\\ldots,n\\right\\}  \\text{)}%\r\n\\end{array}\r\n\\right) \\nonumber\\\\\r\n&  =a_{i,n+1-j}+\\underbrace{\\sum_{\\substack{k\\in\\left\\{  1,2,\\ldots,n\\right\\}\r\n;\\\\k\\neq n+1-j}}a_{i,k}0}_{=0}=a_{i,n+1-j}.\r\n\\label{sol.ring.matrix.W-conj.b.c6.pf.2}%\r\n\\end{align}\r\n\r\n\r\nNow, forget that we fixed $\\left(  i,j\\right)  $. We thus have proven\r\n\\eqref{sol.ring.matrix.W-conj.b.c6.pf.2} for each $\\left(  i,j\\right)\r\n\\in\\left\\{  1,2,\\ldots,n\\right\\}  ^{2}$. Thus, we have%\r\n\\[\r\n\\left(  \\sum_{k=1}^{n}a_{i,k}\\left[  k+j=n+1\\right]  \\right)  _{1\\leq i\\leq\r\nn,\\ 1\\leq j\\leq n}=\\left(  a_{i,n+1-j}\\right)  _{1\\leq i\\leq n,\\ 1\\leq j\\leq\r\nn}.\r\n\\]\r\nHence, \\eqref{sol.ring.matrix.W-conj.b.c6.pf.2} becomes%\r\n\\[\r\nAW=\\left(  \\sum_{k=1}^{n}a_{i,k}\\left[  k+j=n+1\\right]  \\right)  _{1\\leq i\\leq\r\nn,\\ 1\\leq j\\leq n}=\\left(  a_{i,n+1-j}\\right)  _{1\\leq i\\leq n,\\ 1\\leq j\\leq\r\nn}.\r\n\\]\r\nThis proves Claim 6.]\r\n\r\nLet us now come back to part \\textbf{(b)} of this exercise. Recall the\r\ndefinition of the identity matrix $I_{n}\\in\\mathbb{K}^{n\\times n}$. Namely,\r\n$I_{n}$ is defined by\r\n\\[\r\nI_{n}=\\left(  \\delta_{i,j}\\right)  _{1\\leq i\\leq n,\\ 1\\leq j\\leq n}%\r\n,\\qquad\\text{where }\\delta_{i,j}=%\r\n\\begin{cases}\r\n1, & \\text{if }i=j;\\\\\r\n0, & \\text{if }i\\neq j\r\n\\end{cases}\r\n.\r\n\\]\r\n(Note that $\\delta_{i,j}$ can also be written as $\\left[  i=j\\right]  $ using\r\nthe Iverson bracket notation.)\r\n\r\nNow, $W=\\left(  \\left[  i+j=n+1\\right]  \\right)  _{1\\leq i\\leq n,\\ 1\\leq j\\leq\r\nn}$. Hence, Claim 6 (applied to $A=W$ and $a_{i,j}=\\left[  i+j=n+1\\right]  $)\r\nyields%\r\n\\begin{equation}\r\nWW=\\left(  \\left[  \\left(  n+1-i\\right)  +j=n+1\\right]  \\right)  _{1\\leq i\\leq\r\nn,\\ 1\\leq j\\leq n}. \\label{sol.ring.matrix.W-conj.b.WW=}%\r\n\\end{equation}\r\nNow, let $\\left(  i,j\\right)  \\in\\left\\{  1,2,\\ldots,n\\right\\}  ^{2}$. Thus,\r\n$i,j\\in\\left\\{  1,2,\\ldots,n\\right\\}  $. Now, the statement \\textquotedblleft%\r\n$\\left(  n+1-i\\right)  +j=n+1$\\textquotedblright\\ is equivalent to\r\n\\textquotedblleft$i=j$\\textquotedblright\\ (since $\\left(  \\left(\r\nn+1-i\\right)  +j\\right)  -\\left(  n+1\\right)  =j-i$). Thus,%\r\n\\begin{align}\r\n\\left[  \\left(  n+1-i\\right)  +j=n+1\\right]   &  =\\left[  i=j\\right]  =%\r\n\\begin{cases}\r\n1, & \\text{if }i=j\\text{ is true;}\\\\\r\n0, & \\text{if }i=j\\text{ is false}%\r\n\\end{cases}\r\n\\nonumber\\\\\r\n&  \\qquad\\left(  \\text{by the definition of the Iverson bracket notation}%\r\n\\right) \\nonumber\\\\\r\n&  =%\r\n\\begin{cases}\r\n1, & \\text{if }i=j;\\\\\r\n0, & \\text{if }i\\neq j\r\n\\end{cases}\r\n=\\delta_{i,j}. \\label{sol.ring.matrix.W-conj.b.1}%\r\n\\end{align}\r\n\r\n\r\nForget that we fixed $\\left(  i,j\\right)  $. We thus have proven\r\n\\eqref{sol.ring.matrix.W-conj.b.1} for each $\\left(  i,j\\right)  \\in\\left\\{\r\n1,2,\\ldots,n\\right\\}  ^{2}$. Thus, we have%\r\n\\[\r\n\\left(  \\left[  \\left(  n+1-i\\right)  +j=n+1\\right]  \\right)  _{1\\leq i\\leq\r\nn,\\ 1\\leq j\\leq n}=\\left(  \\delta_{i,j}\\right)  _{1\\leq i\\leq n,\\ 1\\leq j\\leq\r\nn}.\r\n\\]\r\nHence, \\eqref{sol.ring.matrix.W-conj.b.WW=} becomes%\r\n\\[\r\nWW=\\left(  \\left[  \\left(  n+1-i\\right)  +j=n+1\\right]  \\right)  _{1\\leq i\\leq\r\nn,\\ 1\\leq j\\leq n}=\\left(  \\delta_{i,j}\\right)  _{1\\leq i\\leq n,\\ 1\\leq j\\leq\r\nn}=I_{n}.\r\n\\]\r\n\r\n\r\nNow, the matrix $W$ is an inverse of $W$ (since $WW=I_{n}$ and $WW=I_{n}$).\r\nThus, the matrix $W$ is invertible, and its inverse is $W^{-1}=W$. This solves\r\npart \\textbf{(b)} of the exercise.\r\n\r\n\\bigskip\r\n\r\n\\textbf{(c)} We have $A=\\left(  a_{i,j}\\right)  _{1\\leq i\\leq n,\\ 1\\leq j\\leq\r\nn}$. Thus, Claim 5 yields%\r\n\\[\r\nWA=\\left(  a_{n+1-i,j}\\right)  _{1\\leq i\\leq n,\\ 1\\leq j\\leq n}.\r\n\\]\r\nHence, Claim 6 (applied to $WA$ and $a_{n+1-i,j}$ instead of $A$ and $a_{i,j}%\r\n$) yields%\r\n\\[\r\nWAW=\\left(  a_{n+1-i,n+1-j}\\right)  _{1\\leq i\\leq n,\\ 1\\leq j\\leq n}.\r\n\\]\r\nBut part \\textbf{(b)} of this exercise yields $W=W^{-1}$. Hence,\r\n$WA\\underbrace{W}_{=W^{-1}}=WAW^{-1}$, so that\r\n\\[\r\nWAW^{-1}=WAW=\\left(  a_{n+1-i,n+1-j}\\right)  _{1\\leq i\\leq n,\\ 1\\leq j\\leq\r\nn}.\r\n\\]\r\nThis solves part \\textbf{(c)} of the exercise.\r\n\r\n%----------------------------------------------------------------------------------------\r\n%\tEXERCISE 3\r\n%----------------------------------------------------------------------------------------\r\n\\rule{\\linewidth}{0.3pt} \\\\[0.4cm]\r\n\r\n\\section{Exercise 3: Entangled inverses}\r\n\r\nLet $\\mathbb{K}$ be a ring.\r\n\r\nA \\textit{left inverse} of an element $x \\in\\mathbb{K}$ is defined to be a $y\r\n\\in\\mathbb{K}$ such that $yx = 1$.\r\n\r\nA \\textit{right inverse} of an element $x \\in\\mathbb{K}$ is defined to be a $y\r\n\\in\\mathbb{K}$ such that $xy = 1$.\r\n\r\nLet $a$ and $b$ be two elements of $\\mathbb{K}$. Prove the following:\r\n\r\n\\begin{enumerate}\r\n\\item[\\textbf{(a)}] If $c$ is a left inverse of $1 - ab$, then $1 + bca$ is a\r\nleft inverse of $1 - ba$.\r\n\r\n\\item[\\textbf{(b)}] If $c$ is a right inverse of $1 - ab$, then $1 + bca$ is a\r\nright inverse of $1 - ba$.\r\n\r\n\\item[\\textbf{(c)}] If $c$ is an inverse of $1 - ab$, then $1 + bca$ is an\r\ninverse of $1 - ba$.\r\n\\end{enumerate}\r\n\r\nHere and in the following, the word ``\\textit{inverse}'' (unless qualified\r\nwith an adjective) means ``multiplicative inverse''.\r\n\r\n\\subsection{Solution}\r\n\r\n\\textbf{(a)} Assume that $c$ is a left inverse of $1-ab$. Thus, $c\\left(\r\n1-ab\\right)  =1$ (by the definition of a left inverse).\r\n\r\nNow, the laws of distributivity\\footnote{When we say \\textquotedblleft the\r\nlaws of distributivity\\textquotedblright\\ here, we mean not just the axiom of\r\ndistributivity (which says that $u\\left(  v+w\\right)  =uv+uw$ and $\\left(\r\nu+v\\right)  w=uw+vw$ for all $u,v,w\\in\\mathbb{K}$), but also its analogue for\r\nsubtraction (which says that $u\\left(  v-w\\right)  =uv-uw$ and $\\left(\r\nu-v\\right)  w=uw-vw$ for all $u,v,w\\in\\mathbb{K}$). The latter analogue is not\r\none of the ring axioms, but follows easily from them.} yield%\r\n\\[\r\na\\left(  1-ba\\right)  =a-aba=\\left(  1-ab\\right)  a,\r\n\\]\r\nthus%\r\n\\[\r\nc\\underbrace{a\\left(  1-ba\\right)  }_{=\\left(  1-ab\\right)  a}%\r\n=\\underbrace{c\\left(  1-ab\\right)  }_{=1}a=1a=a.\r\n\\]\r\nHence, using the distributivity axiom, we obtain%\r\n\\[\r\n\\left(  1+bca\\right)  \\left(  1-ba\\right)  =\\left(  1-ba\\right)\r\n+b\\underbrace{ca\\left(  1-ba\\right)  }_{=a}=\\left(  1-ba\\right)  +ba=1.\r\n\\]\r\nIn other words, $1+bca$ is a left inverse of $1-ba$ (by the definition of a\r\nleft inverse). This solves part \\textbf{(a)} of the exercise.\r\n\r\n\\bigskip\r\n\r\n\\textbf{(b)} Assume that $c$ is a right inverse of $1-ab$. Thus, $\\left(\r\n1-ab\\right)  c=1$ (by the definition of a right inverse).\r\n\r\nNow, the laws of distributivity yield%\r\n\\[\r\n\\left(  1-ba\\right)  b=b-bab=b\\left(  1-ab\\right)  ,\r\n\\]\r\nthus%\r\n\\[\r\n\\underbrace{\\left(  1-ba\\right)  b}_{=b\\left(  1-ab\\right)  }%\r\nc=b\\underbrace{\\left(  1-ab\\right)  c}_{=1}=b1=b.\r\n\\]\r\nHence, using the distributivity axiom, we obtain%\r\n\\[\r\n\\left(  1-ba\\right)  \\left(  1+bca\\right)  =\\left(  1-ba\\right)\r\n+\\underbrace{\\left(  1-ba\\right)  bc}_{=b}a=\\left(  1-ba\\right)  +ba=1.\r\n\\]\r\nIn other words, $1+bca$ is a right inverse of $1-ba$ (by the definition of a\r\nright inverse). This solves part \\textbf{(b)} of the exercise.\r\n\r\n\\bigskip\r\n\r\n\\textbf{(c)} Assume that $c$ is an inverse of $1-ab$. In other words, $c$ is a\r\nmultiplicative inverse of $1-ab$. Thus, $\\left(  1-ab\\right)  c=c\\left(\r\n1-ab\\right)  =1$ (by the definition of a multiplicative inverse).\r\n\r\nFrom $c\\left(  1-ab\\right)  =1$, we conclude that $c$ is a left inverse of\r\n$1-ab$. Hence, part \\textbf{(a)} of this exercise shows that $1+bca$ is a left\r\ninverse of $1-ba$. In other words, $\\left(  1+bca\\right)  \\left(  1-ba\\right)\r\n=1$.\r\n\r\nFrom $\\left(  1-ab\\right)  c=1$, we conclude that $c$ is a right inverse of\r\n$1-ab$. Hence, part \\textbf{(b)} of this exercise shows that $1+bca$ is a\r\nright inverse of $1-ba$. In other words, $\\left(  1-ba\\right)  \\left(\r\n1+bca\\right)  =1$.\r\n\r\nCombining $\\left(  1+bca\\right)  \\left(  1-ba\\right)  =1$ with $\\left(\r\n1-ba\\right)  \\left(  1+bca\\right)  =1$, we obtain\r\n\\[\r\n\\left(  1-ba\\right)  \\left(  1+bca\\right)  =\\left(  1+bca\\right)  \\left(\r\n1-ba\\right)  =1.\r\n\\]\r\nIn other words, $1+bca$ is a multiplicative inverse of $1-ba$ (by the\r\ndefinition of a multiplicative inverse). In other words, $1+bca$ is an inverse\r\nof $1-ba$. This solves part \\textbf{(c)} of the exercise.\r\n\r\n%----------------------------------------------------------------------------------------\r\n%\tEXERCISE 4\r\n%----------------------------------------------------------------------------------------\r\n\\rule{\\linewidth}{0.3pt} \\\\[0.4cm]\r\n\r\n\\section{Exercise 4: Composition of ring homomorphisms}\r\n\r\n\\subsection{Problem}\r\n\r\nLet $\\mathbb{K}$, $\\mathbb{L}$ and $\\mathbb{M}$ be three rings. Prove the following:\r\n\r\n\\begin{enumerate}\r\n\\item[\\textbf{(a)}] If $f : \\mathbb{K} \\to\\mathbb{L}$ and $g : \\mathbb{L}\r\n\\to\\mathbb{M}$ are two ring homomorphisms, then $g \\circ f : \\mathbb{K}\r\n\\to\\mathbb{M}$ is a ring homomorphism.\r\n\r\n\\item[\\textbf{(b)}] If $f : \\mathbb{K} \\to\\mathbb{L}$ and $g : \\mathbb{L}\r\n\\to\\mathbb{M}$ are two ring isomorphisms, then $g \\circ f : \\mathbb{K}\r\n\\to\\mathbb{M}$ is a ring isomorphism.\r\n\\end{enumerate}\r\n\r\n\\subsection{Solution}\r\n\r\n\\textbf{(a)} Let $f:\\mathbb{K}\\rightarrow\\mathbb{L}$ and $g:\\mathbb{L}%\r\n\\rightarrow\\mathbb{M}$ be two ring homomorphisms. We must prove that $g\\circ\r\nf:\\mathbb{K}\\rightarrow\\mathbb{M}$ is a ring homomorphism.\r\n\r\nWe have assumed that $f:\\mathbb{K}\\rightarrow\\mathbb{L}$ is a ring\r\nhomomorphism. In other words, $f$ satisfies the four axioms in our definition\r\nof a ring homomorphism. In other words, the following four claims hold:\r\n\r\n\\begin{statement}\r\n\\textit{Claim 1:} We have $f\\left(  a+b\\right)  =f\\left(  a\\right)  +f\\left(\r\nb\\right)  $ for all $a,b\\in\\mathbb{K}$.\r\n\\end{statement}\r\n\r\n\\begin{statement}\r\n\\textit{Claim 2:} We have $f\\left(  0\\right)  =0$.\r\n\\end{statement}\r\n\r\n\\begin{statement}\r\n\\textit{Claim 3:} We have $f\\left(  ab\\right)  =f\\left(  a\\right)  f\\left(\r\nb\\right)  $ for all $a,b\\in\\mathbb{K}$.\r\n\\end{statement}\r\n\r\n\\begin{statement}\r\n\\textit{Claim 4:} We have $f\\left(  1\\right)  =1$.\r\n\\end{statement}\r\n\r\nSimilarly, from the assumption that $g:\\mathbb{L}\\rightarrow\\mathbb{M}$ is a\r\nring homomorphism, we conclude that the following four claims hold:\r\n\r\n\\begin{statement}\r\n\\textit{Claim 5:} We have $g\\left(  a+b\\right)  =g\\left(  a\\right)  +g\\left(\r\nb\\right)  $ for all $a,b\\in\\mathbb{L}$.\r\n\\end{statement}\r\n\r\n\\begin{statement}\r\n\\textit{Claim 6:} We have $g\\left(  0\\right)  =0$.\r\n\\end{statement}\r\n\r\n\\begin{statement}\r\n\\textit{Claim 7:} We have $g\\left(  ab\\right)  =g\\left(  a\\right)  g\\left(\r\nb\\right)  $ for all $a,b\\in\\mathbb{L}$.\r\n\\end{statement}\r\n\r\n\\begin{statement}\r\n\\textit{Claim 8:} We have $g\\left(  1\\right)  =1$.\r\n\\end{statement}\r\n\r\nNow, we must prove that $g\\circ f:\\mathbb{K}\\rightarrow\\mathbb{M}$ is a ring\r\nhomomorphism. In other words, we must prove that $g\\circ f$ satisfies the four\r\naxioms in our definition of a ring homomorphism. In other words, we must prove\r\nthat the following four claims hold:\r\n\r\n\\begin{statement}\r\n\\textit{Claim 9:} We have $\\left(  g\\circ f\\right)  \\left(  a+b\\right)\r\n=\\left(  g\\circ f\\right)  \\left(  a\\right)  +\\left(  g\\circ f\\right)  \\left(\r\nb\\right)  $ for all $a,b\\in\\mathbb{K}$.\r\n\\end{statement}\r\n\r\n\\begin{statement}\r\n\\textit{Claim 10:} We have $\\left(  g\\circ f\\right)  \\left(  0\\right)  =0$.\r\n\\end{statement}\r\n\r\n\\begin{statement}\r\n\\textit{Claim 11:} We have $\\left(  g\\circ f\\right)  \\left(  ab\\right)\r\n=\\left(  g\\circ f\\right)  \\left(  a\\right)  \\left(  g\\circ f\\right)  \\left(\r\nb\\right)  $ for all $a,b\\in\\mathbb{K}$.\r\n\\end{statement}\r\n\r\n\\begin{statement}\r\n\\textit{Claim 12:} We have $\\left(  g\\circ f\\right)  \\left(  1\\right)  =1$.\r\n\\end{statement}\r\n\r\nBut this is straightforward:\r\n\r\n[\\textit{Proof of Claim 9:} For all $a,b\\in\\mathbb{K}$, we have%\r\n\\begin{align*}\r\n\\left(  g\\circ f\\right)  \\left(  a+b\\right)   &  =g\\left(\r\n\\underbrace{f\\left(  a+b\\right)  }_{\\substack{=f\\left(  a\\right)  +f\\left(\r\nb\\right)  \\\\\\text{(by Claim 1)}}}\\right)  =g\\left(  f\\left(  a\\right)\r\n+f\\left(  b\\right)  \\right)  =\\underbrace{g\\left(  f\\left(  a\\right)  \\right)\r\n}_{=\\left(  g\\circ f\\right)  \\left(  a\\right)  }+\\underbrace{g\\left(  f\\left(\r\nb\\right)  \\right)  }_{=\\left(  g\\circ f\\right)  \\left(  b\\right)  }\\\\\r\n&  \\qquad\\left(  \\text{by Claim 5, applied to }f\\left(  a\\right)  \\text{ and\r\n}f\\left(  b\\right)  \\text{ instead of }a\\text{ and }b\\right) \\\\\r\n&  =\\left(  g\\circ f\\right)  \\left(  a\\right)  +\\left(  g\\circ f\\right)\r\n\\left(  b\\right)  .\r\n\\end{align*}\r\nThus, Claim 9 is proven.]\r\n\r\n[\\textit{Proof of Claim 10:} We have $\\left(  g\\circ f\\right)  \\left(\r\n0\\right)  =g\\left(  \\underbrace{f\\left(  0\\right)  }_{\\substack{=0\\\\\\text{(by\r\nClaim 2)}}}\\right)  =g\\left(  0\\right)  =0$ (by Claim 6). Thus, Claim 10 is proven.]\r\n\r\n[\\textit{Proof of Claim 11:} The proof of Claim 11 is analogous to the proof\r\nof Claim 9, except that we need to use Claims 3 and 7 instead of Claims 1 and 5.]\r\n\r\n[\\textit{Proof of Claim 12:} The proof of Claim 12 is analogous to the proof\r\nof Claim 10, except that we need to use Claims 4 and 8 instead of Claims 2 and 6.]\r\n\r\nThus, all four Claims 9, 10, 11 and 12 are proven. As we explained, this shows\r\nthat $g\\circ f$ is a ring homomorphism. Hence, part \\textbf{(a)} of the\r\nexercise is solved.\r\n\r\n\\bigskip\r\n\r\n\\textbf{(b)} Let $f:\\mathbb{K}\\rightarrow\\mathbb{L}$ and $g:\\mathbb{L}%\r\n\\rightarrow\\mathbb{M}$ be two ring isomorphisms. We must show that $g\\circ\r\nf:\\mathbb{K}\\rightarrow\\mathbb{M}$ is a ring isomorphism.\r\n\r\nThe map $f$ is a ring isomorphism. In other words, $f$ is invertible and both\r\n$f$ and $f^{-1}$ are ring homomorphisms (by the definition of a ring isomorphism).\r\n\r\nThe map $g$ is a ring isomorphism. In other words, $g$ is invertible and both\r\n$g$ and $g^{-1}$ are ring homomorphisms (by the definition of a ring isomorphism).\r\n\r\nNow we know that $f:\\mathbb{K}\\rightarrow\\mathbb{L}$ and $g:\\mathbb{L}%\r\n\\rightarrow\\mathbb{M}$ are two ring homomorphisms. Hence, part \\textbf{(a)} of\r\nthis exercise shows that $g\\circ f:\\mathbb{K}\\rightarrow\\mathbb{M}$ is a ring homomorphism.\r\n\r\nAlso, we know that $g^{-1}:\\mathbb{M}\\rightarrow\\mathbb{L}$ and $f^{-1}%\r\n:\\mathbb{L}\\rightarrow\\mathbb{K}$ are two ring homomorphisms. Hence, part\r\n\\textbf{(a)} of this exercise (applied to $\\mathbb{M}$, $\\mathbb{K}$, $g^{-1}$\r\nand $f^{-1}$ instead of $\\mathbb{K}$, $\\mathbb{M}$, $f$ and $g$) shows that\r\n$f^{-1}\\circ g^{-1}:\\mathbb{M}\\rightarrow\\mathbb{K}$ is a ring homomorphism.\r\n\r\nBut the maps $f$ and $g$ are invertible. Hence, it is well-known that their\r\ncomposition $g\\circ f$ is invertible as well, and its inverse is $\\left(\r\ng\\circ f\\right)  ^{-1}=f^{-1}\\circ g^{-1}$. Hence, $\\left(  g\\circ f\\right)\r\n^{-1}$ is a ring homomorphism (since $f^{-1}\\circ g^{-1}$ is a ring homomorphism).\r\n\r\nNow, we know that the map $g\\circ f$ is invertible and both $g\\circ f$ and\r\n$\\left(  g\\circ f\\right)  ^{-1}$ are ring homomorphisms. In other words,\r\n$g\\circ f$ is a ring isomorphism (by the definition of a ring isomorphism).\r\nThis solves part \\textbf{(b)} of the exercise.\r\n\r\n%----------------------------------------------------------------------------------------\r\n%\tEXERCISE 5\r\n%----------------------------------------------------------------------------------------\r\n\\rule{\\linewidth}{0.3pt} \\\\[0.4cm]\r\n\r\n\\section{Exercise 5: Squares in finite fields I}\r\n\r\n\\subsection{Problem}\r\n\r\nLet $\\mathbb{F}$ be a field.\r\n\r\n\\begin{enumerate}\r\n\\item[\\textbf{(a)}] Prove that if $a, b \\in\\mathbb{F}$ satisfy $ab = 0$, then\r\n$a = 0$ or $b = 0$.\r\n\r\n\\item[\\textbf{(b)}] Prove that if $a, b \\in\\mathbb{F}$ satisfy $a^{2} = b^{2}%\r\n$, then $a = b$ or $a = -b$.\r\n\\end{enumerate}\r\n\r\nRecall that an element $\\eta\\in\\mathbb{F}$ is called a \\textit{square} if\r\nthere exists some $\\alpha\\in\\mathbb{F}$ such that $\\eta= \\alpha^{2}$.\r\n\r\nFrom now on, assume that $2 \\cdot1_{\\mathbb{F}} \\neq0_{\\mathbb{F}}$ (that is,\r\n$1_{\\mathbb{F}} + 1_{\\mathbb{F}} \\neq0_{\\mathbb{F}}$). Note that this is\r\nsatisfied whenever $\\mathbb{F} = \\mathbb{Z} / p$ for a prime $p > 2$ (but also\r\nfor various other finite fields), but fails when $\\mathbb{F} = \\mathbb{Z} / 2$.\r\n\r\n\\begin{enumerate}\r\n\\item[\\textbf{(c)}] Prove that $a \\neq-a$ for every nonzero $a \\in\\mathbb{F}$.\r\n\\end{enumerate}\r\n\r\nFrom now on, assume that $\\mathbb{F}$ is finite.\r\n\r\n\\begin{enumerate}\r\n\\item[\\textbf{(d)}] Prove that the number of squares in $\\mathbb{F}$ is\r\n$\\dfrac{1}{2} \\left(  \\left|  \\mathbb{F} \\right|  + 1 \\right)  $.\r\n\r\n\\item[\\textbf{(e)}] Conclude that $\\left|  \\mathbb{F} \\right|  $ is odd.\r\n\\end{enumerate}\r\n\r\n[\\textbf{Hint:} For part \\textbf{(d)}, argue that each nonzero square in\r\n$\\mathbb{F}$ can be written as $\\alpha^{2}$ for exactly two $\\alpha\r\n\\in\\mathbb{F}$.]\r\n\r\n\\subsection{Solution}\r\n\r\nWe have assumed that $\\mathbb{F}$ is a field. Hence, $\\mathbb{F}$ is a\r\ncommutative skew field (by the definition of a field). Every nonzero element\r\nof $\\mathbb{F}$ is invertible (since $\\mathbb{F}$ is a skew field).\r\n\r\n\\bigskip\r\n\r\n\\textbf{(a)} Let $a,b\\in\\mathbb{F}$ be such that $ab=0$. We must prove that\r\n$a=0$ or $b=0$.\r\n\r\nAssume the contrary. Thus, neither $a=0$ nor $b=0$ holds. In other words, we\r\nhave $a\\neq0$ and $b\\neq0$. Thus, the elements $a$ and $b$ of $\\mathbb{F}$ are\r\nnonzero, and therefore invertible (since every nonzero element of $\\mathbb{F}$\r\nis invertible). Hence, their inverses $a^{-1}$ and $b^{-1}$ are well-defined.\r\nComparing the equalities $\\underbrace{a^{-1}a}_{=1}b=b$ and $a^{-1}%\r\n\\underbrace{ab}_{=0}=a^{-1}0=0$, we obtain $b=0$. This contradicts $b\\neq0$.\r\nThis contradiction shows that our assumption was false. This completes the\r\nsolution to part \\textbf{(a)} of the exercise.\r\n\r\n\\bigskip\r\n\r\n\\textbf{(b)} Let $a,b\\in\\mathbb{F}$ satisfy $a^{2}=b^{2}$. We must prove that\r\n$a=b$ or $a=-b$.\r\n\r\nSince $\\mathbb{F}$ is commutative, we have $ab=ba$. Now, multiplying out\r\n$\\left(  a-b\\right)  \\left(  a+b\\right)  $ (by applying the distributivity\r\nlaws several times), we obtain%\r\n\\[\r\n\\left(  a-b\\right)  \\left(  a+b\\right)  =\\underbrace{aa}_{=a^{2}=b^{2}%\r\n}+\\underbrace{ab}_{=ba}-ba-\\underbrace{bb}_{=b^{2}}=b^{2}+ba-ba-b^{2}=0.\r\n\\]\r\nThus, part \\textbf{(a)} of this exercise (applied to $a-b$ and $a+b$ instead\r\nof $a$ and $b$) shows that $a-b=0$ or $a+b=0$. In other words, $a=b$ or\r\n$a=-b$. Thus, part \\textbf{(b)} of the exercise is solved.\r\n\r\n\\bigskip\r\n\r\n\\textbf{(c)} Let $a\\in\\mathbb{F}$ be nonzero. We must prove that $a\\neq-a$.\r\n\r\nAssume the contrary. Thus, $a=-a$, so that $a+a=0$. Now,%\r\n\\[\r\n\\underbrace{\\left(  2\\cdot1_{\\mathbb{F}}\\right)  }_{=1_{\\mathbb{F}%\r\n}+1_{\\mathbb{F}}}a=\\left(  1_{\\mathbb{F}}+1_{\\mathbb{F}}\\right)\r\na=\\underbrace{1_{\\mathbb{F}}a}_{=a}+\\underbrace{1_{\\mathbb{F}}a}_{=a}=a+a=0.\r\n\\]\r\n\r\n\r\nThe element $2\\cdot1_{\\mathbb{F}}$ of $\\mathbb{F}$ is nonzero (since\r\n$2\\cdot1_{\\mathbb{F}}\\neq0_{\\mathbb{F}}$), and thus invertible (since every\r\nnonzero element of $\\mathbb{F}$ is invertible). Hence, it has a well-defined\r\ninverse $\\left(  2\\cdot1_{\\mathbb{F}}\\right)  ^{-1}$.\r\n\r\nNow,%\r\n\\[\r\n\\left(  2\\cdot1_{\\mathbb{F}}\\right)  ^{-1}\\cdot\\underbrace{\\left(\r\n2\\cdot1_{\\mathbb{F}}\\right)  a}_{=0}=\\left(  2\\cdot1_{\\mathbb{F}}\\right)\r\n^{-1}\\cdot0=0.\r\n\\]\r\nComparing this with $\\underbrace{\\left(  2\\cdot1_{\\mathbb{F}}\\right)\r\n^{-1}\\cdot\\left(  2\\cdot1_{\\mathbb{F}}\\right)  }_{=1}a=1a=a$, we obtain $a=0$.\r\nThis contradicts the fact that $a$ is nonzero. This contradiction shows that\r\nour assumption was false. Hence, $a\\neq-a$. Thus, part \\textbf{(c)} of the\r\nexercise is solved.\r\n\r\n\\bigskip\r\n\r\n\\textbf{(d)} We have the following:\r\n\r\n\\begin{statement}\r\n\\textit{Claim 1:} Let $c\\in\\mathbb{F}$. Then:\r\n\r\n\\textbf{(i)} If $c$ is a nonzero square, then%\r\n\\[\r\n\\left\\vert \\left\\{  d\\in\\mathbb{F}\\ \\mid\\ c=d^{2}\\right\\}  \\right\\vert =2.\r\n\\]\r\n\r\n\r\n\\textbf{(ii)} If $c$ is not a square, then%\r\n\\[\r\n\\left\\vert \\left\\{  d\\in\\mathbb{F}\\ \\mid\\ c=d^{2}\\right\\}  \\right\\vert =0.\r\n\\]\r\n\r\n\r\n\\textbf{(iii)} If $c=0$, then%\r\n\\[\r\n\\left\\vert \\left\\{  d\\in\\mathbb{F}\\ \\mid\\ c=d^{2}\\right\\}  \\right\\vert =1.\r\n\\]\r\n\r\n\\end{statement}\r\n\r\n[\\textit{Proof of Claim 1:} \\textbf{(i)} Assume that $c$ is a nonzero square.\r\nThus, there exists a $g\\in\\mathbb{F}$ such that $c=g^{2}$ (since $c$ is a\r\nsquare). Consider this $g$. Moreover,\r\n\\[\r\n\\left(  -g\\right)  ^{2}=\\left(  -g\\right)  \\left(  -g\\right)\r\n=-\\underbrace{\\left(  \\left(  -g\\right)  g\\right)  }_{=-gg}=-\\left(\r\n-gg\\right)  =gg=g^{2}=c\r\n\\]\r\n(since $c=g^{2}$). Hence, $c=\\left(  -g\\right)  ^{2}$.\r\n\r\nIf we had $g=0$, then we would have $c=\\underbrace{g}_{=0}\\ ^{2}=0^{2}=0$,\r\nwhich would contradict our assumption that $c$ is nonzero. Hence, we cannot\r\nhave $g=0$. Thus, $g$ is nonzero. Therefore, $g\\neq-g$ (by part \\textbf{(c)}\r\nof this exercise, applied to $a=g$). Hence, the elements $g$ and $-g$ of\r\n$\\mathbb{F}$ are distinct. Thus, $\\left\\vert \\left\\{  g,-g\\right\\}\r\n\\right\\vert =2$.\r\n\r\nBut $g\\in\\left\\{  d\\in\\mathbb{F}\\ \\mid\\ c=d^{2}\\right\\}  $ (since\r\n$g\\in\\mathbb{F}$ and $c=g^{2}$) and $-g\\in\\left\\{  d\\in\\mathbb{F}%\r\n\\ \\mid\\ c=d^{2}\\right\\}  $ (since $-g\\in\\mathbb{F}$ and $c=\\left(  -g\\right)\r\n^{2}$). Combining these two facts, we obtain\r\n\\begin{equation}\r\n\\left\\{  g,-g\\right\\}  \\subseteq\\left\\{  d\\in\\mathbb{F}\\ \\mid\\ c=d^{2}%\r\n\\right\\}  . \\label{sol.ffields.squares1.c1.pf.1}%\r\n\\end{equation}\r\n\r\n\r\nOn the other hand, let us prove that $\\left\\{  d\\in\\mathbb{F}\\ \\mid\r\n\\ c=d^{2}\\right\\}  \\subseteq\\left\\{  g,-g\\right\\}  $. Indeed, let\r\n$a\\in\\left\\{  d\\in\\mathbb{F}\\ \\mid\\ c=d^{2}\\right\\}  $. Thus, $a$ is a\r\n$d\\in\\mathbb{F}$ such that $c=d^{2}$. In other words, $a$ is an element of\r\n$\\mathbb{F}$ and satisfies $c=a^{2}$. Hence, $a^{2}=c=g^{2}$. Thus, part\r\n\\textbf{(b)} of this exercise (applied to $b=g$) yields that $a=g$ or $a=-g$.\r\nIn other words, $a\\in\\left\\{  g,-g\\right\\}  $. Now, forget that we fixed $a$.\r\nWe thus have shown that $a\\in\\left\\{  g,-g\\right\\}  $ for each $a\\in\\left\\{\r\nd\\in\\mathbb{F}\\ \\mid\\ c=d^{2}\\right\\}  $. In other words, $\\left\\{\r\nd\\in\\mathbb{F}\\ \\mid\\ c=d^{2}\\right\\}  \\subseteq\\left\\{  g,-g\\right\\}  $.\r\nCombining this with \\eqref{sol.ffields.squares1.c1.pf.1}, we obtain%\r\n\\[\r\n\\left\\{  d\\in\\mathbb{F}\\ \\mid\\ c=d^{2}\\right\\}  =\\left\\{  g,-g\\right\\}  .\r\n\\]\r\nHence,%\r\n\\[\r\n\\left\\vert \\left\\{  d\\in\\mathbb{F}\\ \\mid\\ c=d^{2}\\right\\}  \\right\\vert\r\n=\\left\\vert \\left\\{  g,-g\\right\\}  \\right\\vert =2.\r\n\\]\r\nThis proves Claim 1 \\textbf{(i)}.\r\n\r\n\\textbf{(ii)} Assume that $c$ is not a square. Then, there exists no\r\n$\\alpha\\in\\mathbb{F}$ such that $c=\\alpha^{2}$ (by the definition of a\r\nsquare). In other words, there exists no $d\\in\\mathbb{F}$ such that $c=d^{2}$\r\n(here, we have renamed the index $\\alpha$ as $d$). In other words, $\\left\\{\r\nd\\in\\mathbb{F}\\ \\mid\\ c=d^{2}\\right\\}  =\\varnothing$. Hence, $\\left\\vert\r\n\\left\\{  d\\in\\mathbb{F}\\ \\mid\\ c=d^{2}\\right\\}  \\right\\vert =\\left\\vert\r\n\\varnothing\\right\\vert =0$. This proves Claim 1 \\textbf{(ii)}.\r\n\r\n\\textbf{(iii)} Assume that $c=0$. Then, $0\\in\\left\\{  d\\in\\mathbb{F}%\r\n\\ \\mid\\ c=d^{2}\\right\\}  $ (since $0\\in\\mathbb{F}$ and $c=0=0^{2}$) and thus\r\n$\\left\\{  0\\right\\}  \\subseteq\\left\\{  d\\in\\mathbb{F}\\ \\mid\\ c=d^{2}\\right\\}\r\n$.\r\n\r\nOn the other hand, let us show that $\\left\\{  d\\in\\mathbb{F}\\ \\mid\r\n\\ c=d^{2}\\right\\}  \\subseteq\\left\\{  0\\right\\}  $.\r\n\r\nIndeed, let $a\\in\\left\\{  d\\in\\mathbb{F}\\ \\mid\\ c=d^{2}\\right\\}  $. Then, $a$\r\nis a $d\\in\\mathbb{F}$ such that $c=d^{2}$. In other words, $a$ is an element\r\nof $\\mathbb{F}$ and satisfies $c=a^{2}$. Hence, $aa=a^{2}=c=0$. Thus, part\r\n\\textbf{(a)} of this exercise (applied to $b=a$) yields that $a=0$ or $a=0$.\r\nIn other words, $a=0$. In other words, $a\\in\\left\\{  0\\right\\}  $. Now, forget\r\nthat we fixed $a$. We thus have shown that $a\\in\\left\\{  0\\right\\}  $ for each\r\n$a\\in\\left\\{  d\\in\\mathbb{F}\\ \\mid\\ c=d^{2}\\right\\}  $. In other words,\r\n$\\left\\{  d\\in\\mathbb{F}\\ \\mid\\ c=d^{2}\\right\\}  \\subseteq\\left\\{  0\\right\\}\r\n$. Combining this with $\\left\\{  0\\right\\}  \\subseteq\\left\\{  d\\in\r\n\\mathbb{F}\\ \\mid\\ c=d^{2}\\right\\}  $, we obtain $\\left\\{  d\\in\\mathbb{F}%\r\n\\ \\mid\\ c=d^{2}\\right\\}  =\\left\\{  0\\right\\}  $. Hence, $\\left\\vert \\left\\{\r\nd\\in\\mathbb{F}\\ \\mid\\ c=d^{2}\\right\\}  \\right\\vert =\\left\\vert \\left\\{\r\n0\\right\\}  \\right\\vert =1$. This proves Claim 1 \\textbf{(iii)}.]\r\n\r\nNow, let us count all pairs $\\left(  c,d\\right)  \\in\\mathbb{F}\\times\r\n\\mathbb{F}$ satisfying $c=d^{2}$. We shall count these pairs in two ways:\r\n\r\n\\begin{itemize}\r\n\\item The first way is to split this count according to the value of $c$ (that\r\nis, first count all such pairs $\\left(  c,d\\right)  $ with a given $c$, and\r\nthen sum the result up over all $c\\in\\mathbb{F}$). Thus, we find%\r\n\\begin{align*}\r\n&  \\left(  \\text{the number of all }\\left(  c,d\\right)  \\in\\mathbb{F}%\r\n\\times\\mathbb{F}\\text{ such that }c=d^{2}\\right) \\\\\r\n&  =\\sum_{c\\in\\mathbb{F}}\\underbrace{\\left(  \\text{the number of all }%\r\nd\\in\\mathbb{F}\\text{ such that }c=d^{2}\\right)  }_{=\\left\\vert \\left\\{\r\nd\\in\\mathbb{F}\\ \\mid\\ c=d^{2}\\right\\}  \\right\\vert }\\\\\r\n&  =\\sum_{c\\in\\mathbb{F}}\\left\\vert \\left\\{  d\\in\\mathbb{F}\\ \\mid\r\n\\ c=d^{2}\\right\\}  \\right\\vert \\\\\r\n&  =\\sum_{\\substack{c\\in\\mathbb{F};\\\\c=0}}\\underbrace{\\left\\vert \\left\\{\r\nd\\in\\mathbb{F}\\ \\mid\\ c=d^{2}\\right\\}  \\right\\vert }_{\\substack{=1\\\\\\text{(by\r\nClaim 1 \\textbf{(iii)})}}}+\\sum_{\\substack{c\\in\\mathbb{F};\\\\c\\text{ is a\r\nnonzero}\\\\\\text{square}}}\\underbrace{\\left\\vert \\left\\{  d\\in\\mathbb{F}%\r\n\\ \\mid\\ c=d^{2}\\right\\}  \\right\\vert }_{\\substack{=2\\\\\\text{(by Claim 1\r\n\\textbf{(i)})}}}\\\\\r\n&  \\qquad+\\sum_{\\substack{c\\in\\mathbb{F};\\\\c\\text{ is not a}\\\\\\text{square}%\r\n}}\\underbrace{\\left\\vert \\left\\{  d\\in\\mathbb{F}\\ \\mid\\ c=d^{2}\\right\\}\r\n\\right\\vert }_{\\substack{=0\\\\\\text{(by Claim 1 \\textbf{(ii)})}}}\\\\\r\n&  \\qquad\\left(\r\n\\begin{array}\r\n[c]{c}%\r\n\\text{because each }c\\in\\mathbb{F}\\text{ satisfies exactly one of the three\r\nstatements}\\\\\r\n\\text{\\textquotedblleft}c=0\\text{\\textquotedblright, \\textquotedblleft}c\\text{\r\nis a nonzero square\\textquotedblright\\ and \\textquotedblleft}c\\text{ is not a\r\nsquare\\textquotedblright}%\r\n\\end{array}\r\n\\right) \\\\\r\n&  =\\underbrace{\\sum_{\\substack{c\\in\\mathbb{F};\\\\c=0}}1}%\r\n_{\\substack{=1\\\\\\text{(since this sum has}\\\\\\text{exactly one addend)}%\r\n}}+\\underbrace{\\sum_{\\substack{c\\in\\mathbb{F};\\\\c\\text{ is a nonzero}%\r\n\\\\\\text{square}}}2}_{=2\\cdot\\left(  \\text{the number of nonzero squares in\r\n}\\mathbb{F}\\right)  }+\\underbrace{\\sum_{\\substack{c\\in\\mathbb{F};\\\\c\\text{ is\r\nnot a}\\\\\\text{square}}}0}_{=0}\\\\\r\n&  =1+2\\cdot\\left(  \\text{the number of nonzero squares in }\\mathbb{F}\\right)\r\n+0\\\\\r\n&  =1+2\\cdot\\left(  \\text{the number of nonzero squares in }\\mathbb{F}\\right)\r\n.\r\n\\end{align*}\r\n\r\n\r\n\\item The second way is to split this count according to the value of $d$\r\n(that is, first count all such pairs $\\left(  c,d\\right)  $ with a given $d$,\r\nand then sum the result up over all $d\\in\\mathbb{F}$). Thus, we find%\r\n\\begin{align*}\r\n&  \\left(  \\text{the number of all }\\left(  c,d\\right)  \\in\\mathbb{F}%\r\n\\times\\mathbb{F}\\text{ such that }c=d^{2}\\right) \\\\\r\n&  =\\sum_{d\\in\\mathbb{F}}\\underbrace{\\left(  \\text{the number of all }%\r\nc\\in\\mathbb{F}\\text{ such that }c=d^{2}\\right)  }_{\\substack{=1\\\\\\text{(since\r\nthere is exactly one }c\\in\\mathbb{F}\\text{ such that }c=d^{2}\\text{ (namely,\r\n}c=d^{2}\\text{))}}}\\\\\r\n&  =\\sum_{d\\in\\mathbb{F}}1=\\left\\vert \\mathbb{F}\\right\\vert \\cdot1=\\left\\vert\r\n\\mathbb{F}\\right\\vert .\r\n\\end{align*}\r\n\r\n\\end{itemize}\r\n\r\nComparing these two equalities, we obtain%\r\n\\[\r\n\\left\\vert \\mathbb{F}\\right\\vert =1+2\\cdot\\left(  \\text{the number of nonzero\r\nsquares in }\\mathbb{F}\\right)  .\r\n\\]\r\nSolving this for $\\left(  \\text{the number of nonzero squares in }%\r\n\\mathbb{F}\\right)  $, we find%\r\n\\[\r\n\\left(  \\text{the number of nonzero squares in }\\mathbb{F}\\right)\r\n=\\dfrac{\\left\\vert \\mathbb{F}\\right\\vert -1}{2}.\r\n\\]\r\n\r\n\r\nNow, there are two kinds of squares in $\\mathbb{F}$: namely, the nonzero\r\nsquares (of which there are exactly $\\dfrac{\\left\\vert \\mathbb{F}\\right\\vert\r\n-1}{2}$ many, as we just proved) and the zero squares (of which there is only\r\n$1$, namely $0^{2}=0$). Thus, the total number of squares in $\\mathbb{F}$ is\r\n$\\dfrac{\\left\\vert \\mathbb{F}\\right\\vert -1}{2}+1=\\dfrac{\\left\\vert\r\n\\mathbb{F}\\right\\vert +1}{2}=\\dfrac{1}{2}\\left(  \\left\\vert \\mathbb{F}%\r\n\\right\\vert +1\\right)  $. This solves part \\textbf{(d)} of the exercise.\r\n\r\n\\bigskip\r\n\r\n\\textbf{(e)} Part \\textbf{(d)} of this exercise shows that the number of\r\nsquares in $\\mathbb{F}$ is $\\dfrac{1}{2}\\left(  \\left\\vert \\mathbb{F}%\r\n\\right\\vert +1\\right)  $. Thus,%\r\n\\[\r\n\\dfrac{1}{2}\\left(  \\left\\vert \\mathbb{F}\\right\\vert +1\\right)  =\\left(\r\n\\text{the number of squares in }\\mathbb{F}\\right)  \\in\\mathbb{N}%\r\n\\]\r\n(since a number that counts something is always $\\in\\mathbb{N}$). Therefore,\r\n$\\dfrac{1}{2}\\left(  \\left\\vert \\mathbb{F}\\right\\vert +1\\right)  \\in\r\n\\mathbb{N}\\subseteq\\mathbb{Z}$, so that the integer $\\left\\vert \\mathbb{F}%\r\n\\right\\vert +1$ is even. This shows that $\\left\\vert \\mathbb{F}\\right\\vert $\r\nis odd. This solves part \\textbf{(e)} of the exercise.\r\n\r\n%----------------------------------------------------------------------------------------\r\n%\tEXERCISE 6\r\n%----------------------------------------------------------------------------------------\r\n\\rule{\\linewidth}{0.3pt} \\\\[0.4cm]\r\n\r\n\\section{Exercise 6: The characteristic of a field}\r\n\r\n\\subsection{Problem}\r\n\r\nLet $\\mathbb{F}$ be a field. Recall that we have defined $na$ to mean\r\n$\\underbrace{a + a + \\cdots+ a}_{n \\text{ times}}$ whenever $n \\in\\mathbb{N}$\r\nand $a \\in\\mathbb{F}$.\r\n\r\nAssume that there exists a positive integer $n$ such that $n \\cdot\r\n1_{\\mathbb{F}} = 0$. Let $p$ be the \\textbf{smallest} such $n$.\r\n\r\nProve that $p$ is prime.\r\n\r\n[\\textbf{Hint:} $\\left(  a \\cdot1_{\\mathbb{F}} \\right)  \\cdot\\left(  b\r\n\\cdot1_{\\mathbb{F}} \\right)  = ab \\cdot1_{\\mathbb{F}}$ for all $a, b\r\n\\in\\mathbb{N}$.]\r\n\r\n\\subsection{Remark}\r\n\r\nThe $p$ we just defined is called the \\textit{characteristic} of the field\r\n$\\mathbb{F}$ when it exists. (Otherwise, the characteristic of the field\r\n$\\mathbb{F}$ is defined to be $0$.)\r\n\r\nThus, for each prime $p$, the finite field $\\mathbb{Z} / p$, as well as the\r\nfinite field of size $p^{2}$ that we constructed in class, have characteristic\r\n$p$.\r\n\r\n\\subsection{Solution sketch}\r\n\r\nWe have assumed that $\\mathbb{F}$ is a field. Hence, $\\mathbb{F}$ is a\r\ncommutative skew field (by the definition of a field). We have $0_{\\mathbb{F}%\r\n}\\neq1_{\\mathbb{F}}$ (since $\\mathbb{F}$ is a skew field).\r\n\r\nWe have defined $p$ to be the \\textbf{smallest} positive integer $n$ such that\r\n$n\\cdot1_{\\mathbb{F}}=0$. Thus, $p$ is a positive integer which itself\r\nsatisfies $p\\cdot1_{\\mathbb{F}}=0$. Furthermore, if $n$ is a positive integer\r\nsuch that $n\\cdot1_{\\mathbb{F}}=0$, then%\r\n\\begin{equation}\r\nn\\geq p \\label{sol.field.char.prime.1}%\r\n\\end{equation}\r\n(since $p$ is the \\textbf{smallest} positive integer $n$ such that\r\n$n\\cdot1_{\\mathbb{F}}=0$).\r\n\r\nIf we had $p=1$, then we would have $p\\cdot1_{\\mathbb{F}}=1\\cdot1_{\\mathbb{F}%\r\n}=1_{\\mathbb{F}}\\neq0_{\\mathbb{F}}$ (since $0_{\\mathbb{F}}\\neq1_{\\mathbb{F}}%\r\n$), which would contradict $p\\cdot1_{\\mathbb{F}}=0=0_{\\mathbb{F}}$. Thus, we\r\ncannot have $p=1$. Therefore, we have $p>1$ (since $p$ is a positive integer).\r\n\r\nWe shall now show that the only positive divisors of $p$ are $1$ and $p$.\r\nIndeed, assume the contrary. Thus, $p$ has a positive divisor other than $1$\r\nand $p$. Consider such a divisor, and denote it by $d$. Thus, $d$ is a\r\npositive divisor of $p$ that is distinct from $1$ and $p$. In other words, $d$\r\nis a positive divisor of $p$ and satisfies $d\\neq1$ and $d\\neq p$. We have\r\n$d\\leq p$ (since $d$ is a positive divisor of the positive integer $p$).\r\nCombining this with $d\\neq p$, we obtain $d<p$. Also, $d\\in\\mathbb{Z}$ (since\r\n$d$ is an integer) and $\\dfrac{p}{d}\\in\\mathbb{Z}$ (since $d$ is a divisor of\r\n$p$).\r\n\r\nNow, for all $a,b\\in\\mathbb{Z}$, we have%\r\n\\[\r\n\\left(  a\\cdot1_{\\mathbb{F}}\\right)  \\cdot\\left(  b\\cdot1_{\\mathbb{F}}\\right)\r\n=a\\cdot\\underbrace{\\left(  1_{\\mathbb{F}}\\cdot\\left(  b\\cdot1_{\\mathbb{F}%\r\n}\\right)  \\right)  }_{=b\\cdot1_{\\mathbb{F}}}=a\\cdot\\left(  b\\cdot\r\n1_{\\mathbb{F}}\\right)  =ab\\cdot1_{\\mathbb{F}}.\r\n\\]\r\nApplying this to $a=d$ and $b=\\dfrac{p}{d}$, we obtain%\r\n\\[\r\n\\left(  d\\cdot1_{\\mathbb{F}}\\right)  \\cdot\\left(  \\dfrac{p}{d}\\cdot\r\n1_{\\mathbb{F}}\\right)  =\\underbrace{d\\cdot\\dfrac{p}{d}}_{=p}\\cdot\r\n1_{\\mathbb{F}}=p\\cdot1_{\\mathbb{F}}=0.\r\n\\]\r\nThus, Exercise 5 \\textbf{(a)} (applied to $a=d\\cdot1_{\\mathbb{F}}$ and\r\n$b=\\dfrac{p}{d}\\cdot1_{\\mathbb{F}}$) shows that $d\\cdot1_{\\mathbb{F}}=0$ or\r\n$\\dfrac{p}{d}\\cdot1_{\\mathbb{F}}=0$.\r\n\r\nIf we had $d\\cdot1_{\\mathbb{F}}=0$, then we would have $d\\geq p$ (by\r\n\\eqref{sol.field.char.prime.1}, applied to $n=d$), which would contradict\r\n$d<p$. Hence, we cannot have $d\\cdot1_{\\mathbb{F}}=0$. Thus, we have\r\n$\\dfrac{p}{d}\\cdot1_{\\mathbb{F}}=0$ (since $d\\cdot1_{\\mathbb{F}}=0$ or\r\n$\\dfrac{p}{d}\\cdot1_{\\mathbb{F}}=0$). But $\\dfrac{p}{d}$ is an integer (since\r\n$\\dfrac{p}{d}\\in\\mathbb{Z}$) and is positive (since $p$ and $d$ are positive);\r\nthus, $\\dfrac{p}{d}$ is a positive integer. Hence,\r\n\\eqref{sol.field.char.prime.1} (applied to $n=\\dfrac{p}{d}$) yields $\\dfrac\r\n{p}{d}\\geq p$ (since $\\dfrac{p}{d}\\cdot1_{\\mathbb{F}}=0$). Since $d$ is\r\npositive, we can multiply this inequality by $d$, and thus obtain $p\\geq pd$.\r\nSince $p$ is positive, we can divide this inequality by $p$, and thus obtain\r\n$1\\geq d$. Hence, $d=1$ (since $d$ is a positive integer). This contradicts\r\n$d\\neq1$.\r\n\r\nThis contradiction shows that our assumption was false. Hence, the only\r\npositive divisors of $p$ are $1$ and $p$. Thus, $p$ is a prime (since $p$ is\r\nan integer satisfying $p>1$). Qed.\r\n\r\n\\subsection{Remark}\r\n\r\nWe have never used the commutativity of multiplication (in $\\mathbb{F}$) in\r\nthe above proof. Thus, we can replace \\textquotedblleft\r\nfield\\textquotedblright\\ by \\textquotedblleft skew field\\textquotedblright\\ in\r\nthis exercise.\r\n\r\n\\begin{thebibliography}{99999999}                                                                                         %\r\n\r\n\r\n%Feel free to add your sources -- or copy some from the source code\r\n%of the class notes ( http://www.cip.ifi.lmu.de/~grinberg/t/19s/notes.tex ).\r\n\r\n\r\n%This is the bibliography: The list of papers/books/articles/blogs/...\r\n%cited. The syntax is: \"\\bibitem[name]{tag}Reference\",\r\n%where \"name\" is the name that will appear in the compiled\r\n%bibliography, and \"tag\" is the tag by which you will refer to\r\n%the source in the TeX file. For example, the following source\r\n%has name \"GrKnPa94\" (so you will see it referenced as\r\n%\"[GrKnPa94]\" in the compiled PDF) and tag \"GKP\" (so you\r\n%can cite it by writing \"\\cite{GKP}\").\r\n\r\n\r\n%I've commented the below references out, since I'm not citing\r\n%them above.\r\n\r\n\r\n%\\bibitem[GrKnPa94]{GKP}Ronald L. Graham, Donald E. Knuth, Oren Patashnik,\r\n%\\textit{Concrete Mathematics, Second Edition}, Addison-Wesley 1994.\\\\\r\n%See \\url{https://www-cs-faculty.stanford.edu/~knuth/gkp.html} for errata.\r\n\r\n\r\n\\bibitem[Grinbe19]{detnotes}Darij Grinberg, \\textit{Notes on the combinatorial\r\nfundamentals of algebra}, 10 January 2019. \\newline%\r\n\\url{http://www.cip.ifi.lmu.de/~grinberg/primes2015/sols.pdf} \\newline The\r\nnumbering of theorems and formulas in this link might shift when the project\r\ngets updated; for a ``frozen'' version whose numbering is guaranteed to match\r\nthat in the citations above, see\r\n\\url{https://github.com/darijgr/detnotes/releases/tag/2019-01-10} .\r\n\\end{thebibliography}\r\n\r\n\r\n\\end{document}", "meta": {"hexsha": "034a59245d73eae4352b8dec13b52efc4c50dd63", "size": 76516, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "hw6s.tex", "max_stars_repo_name": "darijgr/algebra19s", "max_stars_repo_head_hexsha": "16476909502a4566bd33b4f11ade52829ef9b16f", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-03-21T05:38:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-17T00:48:51.000Z", "max_issues_repo_path": "hw6s.tex", "max_issues_repo_name": "darijgr/algebra19s", "max_issues_repo_head_hexsha": "16476909502a4566bd33b4f11ade52829ef9b16f", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw6s.tex", "max_forks_repo_name": "darijgr/algebra19s", "max_forks_repo_head_hexsha": "16476909502a4566bd33b4f11ade52829ef9b16f", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.9747126437, "max_line_length": 171, "alphanum_fraction": 0.6340503947, "num_tokens": 29248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.3376767719421184}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% how to typeset algorithms\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\chapter{Algorithms}\n\n% USE THE TEMPLATE BELOW FOR YOUR ALGORITHMS\n%============================================\n%\n% \\begin{algorithm}\n% \n% \\SetKwInOut{Input}{Input}\n% \\SetKwInOut{Output}{Output}\n% \n% \\Indm\n% \\Input{Description of the input to the algorithm.}\n% \\Output{Description of the output from the algorithm.}\n% \\Indp\n% \n% \\BlankLine\n% \n%   % main algorithm code here\n% \n% \\caption{Algorithm example}\n% \\label{alg}\n%\n% \\end{algorithm}\n\n\n\n\\begin{algorithm}\n\n\\SetKwInOut{Input}{Input}\n\\SetKwInOut{Output}{Output}\n\n\\SetKwData{Left}{left}\n\\SetKwData{This}{this}\n\\SetKwData{Up}{up}\n\\SetKwFunction{Union}{Union}\n\\SetKwFunction{FindCompress}{FindCompress}\n\n\\Indm\n\\Input{Description of the input to the algorithm.}\n\\Output{Description of the output from the algorithm.}\n\\Indp\n\n\\BlankLine\n\n\\emph{special treatment of the first line}\\;\n\\For{$i\\leftarrow 2$ \\KwTo $l$}{\n  \\emph{special treatment of the first element of line $i$}\\;\n  \\For{$j\\leftarrow 2$ \\KwTo $w$}{\\label{forins}\n    \\Left$\\leftarrow$ \\FindCompress{$Im[i,j-1]$}\\;\n    \\Up$\\leftarrow$ \\FindCompress{$Im[i-1,]$}\\;\n    \\This$\\leftarrow$ \\FindCompress{$Im[i,j]$}\\;\n    \\If{\\Left compatible with \\This}{\\label{lt}\n      \\lIf{\\Left $<$ \\This}{\\Union{\\Left,\\This}}\\;\n      \\lElse{\\Union{\\This,\\Left}\\;}\n    }\n    \\If{\\Up compatible with \\This}{\\label{ut}\n      \\lIf{\\Up $<$ \\This}{\\Union{\\Up,\\This}}\\;\n      \\lElse{\\Union{\\This,\\Up}}\n    }\n  }\n  \\lForEach{element $e$ of the line $i$}{\\FindCompress{p}}\n}\n\n\\caption[Do not end short caption with full-stop]{Algorithm example}\n\\label{alg}\n\n\\end{algorithm}\n\n\n\n\n\\begin{algorithm}[t]\n%\\SetAlgoNoLine\n \\Input{A tree $T$ represented by an array {\\sf Parent}$[1,\\ldots,n]$.}\n\\Output{A minimum secure dominating set of $T$, represented by a boolean array $X$.}\n\\For{$i\\leftarrow 1$ to $n$}{\n{\\sf A3Label}$[i] \\leftarrow$ {\\sc False}\\;\n$X[i] \\leftarrow$ {\\sc F\\SetKwInOut{Input}{Input}\n\t\\SetKwInOut{Output}{Output}\n\t\n\t\\SetKwData{Left}{left}\n\t\\SetKwData{This}{this}\n\t\\SetKwData{Up}{up}\n\t\\SetKwFunction{Union}{Union}\n\t\\SetKwFunction{FindCompress}{FindCompress}\n\t\n\t\\Indm\n\t\\Input{Description of the input to the algorithm.}\n\t\\Output{Description of the output from the algorithm.}\n\t\\Indp\n\t\n\t\\BlankLine\n\t\n\t\\emph{special treatment of the first line}\\;\n\t\\For{$i\\leftarrow 2$ \\KwTo $l$}{\n\t\t\\emph{special treatment of the first element of line $i$}\\;\n\t\t\\For{$j\\leftarrow 2$ \\KwTo $w$}{\\label{forins}\n\t\t\t\\Left$\\leftarrow$ \\FindCompress{$Im[i,j-1]$}\\;\n\t\t\t\\Up$\\leftarrow$ \\FindCompress{$Im[i-1,]$}\\;\n\t\t\t\\This$\\leftarrow$ \\FindCompress{$Im[i,j]$}\\;\n\t\t\t\\If{\\Left compatible with \\This}{\\label{lt}\n\t\t\t\t\\lIf{\\Left $<$ \\This}{\\Union{\\Left,\\This}}\\;\n\t\t\t\t\\lElse{\\Union{\\This,\\Left}\\;}\n\t\t\t}\n\t\t\t\\If{\\Up compatible with \\This}{\\label{ut}\n\t\t\t\t\\lIf{\\Up $<$ \\This}{\\Union{\\Up,\\This}}\\;\n\t\t\t\t\\lElse{\\Union{\\This,\\Up}}\n\t\t\t}\n\t\t}\n\t\t\\lForEach{element $e$ of the line $i$}{\\FindCompress{p}}\n\t}\n\t\n\t\\caption[Do not end short caption with full-stop]{Algorithm example}\n\t\\label{alg}\n\talse}\\;\n{\\sf Labels}$[i] \\leftarrow [0,0,0,0,0,0,0]$\\;\n{\\bf if} vertex $i$ is a anchor of $T$ {\\bf then} {\\sf Branch}$[i] \\leftarrow$ {\\sc True}\\;\n{\\sf Previous1Label}$[i] \\leftarrow 0$\\;\n}\n\\For{$i\\leftarrow n$ down to $2$}{\n$\\ell \\leftarrow$ {\\sf\\bf EffectiveLabel}({\\sf Labels}[$i$])\\;\n{\\bf if} $\\ell$ is odd {\\bf then} $X[i] \\leftarrow ${\\sc True}\\;\n{\\sf Labels$[$Parent$[i],\\ell(i)+1 \\ (\\rm{mod}\\ 7)]$} $++$\\;\n\\If{$\\ell=2$ {\\bf and} {\\sf Branch$[$Parent$[i]]$}}{\n{\\sf A3Label[Parent}$[i]] \\leftarrow$ {\\sc True}\\;\n{\\sf prev} $\\leftarrow$ {\\sf Previous1Label$[$Parent$[i]]$}\\;\n{\\bf if} {\\sf prev} $>0$ {\\bf then} $X[${\\sf prev}$] \\leftarrow$ {\\sc True}\\;\n}\n\\If{$\\ell=0$ {\\bf and} {\\sf Branch$[$Parent$[i]]$}}{\n\\If{{\\sf A3Label$[$Parent$[i]]$}}{\n$X[i] \\leftarrow$ {\\sc True}\\;\n}\n\\Else{\n{\\sf prev} $\\leftarrow$ {\\sf Previous1Label$[$Parent$[i]]$}\\;\n{\\bf if} {\\sf prev} $>0$ {\\bf then} $X[${\\sf prev}$] \\leftarrow$ {\\sc True}\\;\n{\\sf Previous1Label$[$Parent$[i]] \\leftarrow i$}\\;\n}\n}\n}\n$\\ell \\leftarrow$ {\\sf\\bf EffectiveLabel}({\\sf Labels}[$1$])\\;\n{\\bf if} $\\ell$ is odd {\\bf then} $X[1] \\leftarrow ${\\sc True}\\;\n{\\bf if}  {\\sf Labels}$[1,j]=0$ for $j=1,3,4,5,6$ {\\bf then} $X[1] \\leftarrow$ {\\sc True}\\;\n{\\bf if} {\\sf Labels}$[1,j]=0$ for $j=1,3,5,6$ {\\bf and} {\\sf Labels}$[1,0] \\geq |${\\sf Labels}$[1]-1|$  {\\bf then} $X[1] \\leftarrow$ {\\sc True}\\;\n\\If{$\\ell=3$}{\n{\\sf prev} $\\leftarrow$ {\\sf Previous1Label$[1]$}\\;\n{\\bf if} {\\sf prev} $ > 0$ {\\bf then} $X[$\\sf{prev}$]$ $\\leftarrow$ {\\sc True}\\;\n}\n\\Return[$X$]\\;\n\\caption[{{Do not end short caption with full-stop}}]{{\\sf\\bf DefendTree}}\n\\label{Alg:Tree}\n\\end{algorithm}\n\n", "meta": {"hexsha": "1cfc27018c5459bb49e04840afc63e96a50a3623", "size": 4700, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "example/algorithms.tex", "max_stars_repo_name": "UlrichLouw/Masters_Latex", "max_stars_repo_head_hexsha": "92d341948a6c9dea47d987c9b9e7f55421960694", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/algorithms.tex", "max_issues_repo_name": "UlrichLouw/Masters_Latex", "max_issues_repo_head_hexsha": "92d341948a6c9dea47d987c9b9e7f55421960694", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/algorithms.tex", "max_forks_repo_name": "UlrichLouw/Masters_Latex", "max_forks_repo_head_hexsha": "92d341948a6c9dea47d987c9b9e7f55421960694", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.746835443, "max_line_length": 146, "alphanum_fraction": 0.5993617021, "num_tokens": 1751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.337676764996149}}
{"text": "\\section{Theoretical stellar grid}\\label{sec:grid}\n\n\\subsection{Grid computation}\n\nWe compute a stellar model grid as the training dataset. We aim to cover stars with approximate solar mass on the main-sequence and the subgiant phases. The mass range is set up as 0.8 -- 1.2$\\rm M_{\\odot}$. The computation of evolutionary tracks starts at the Hayashi line and terminates at the base of red-giant branch (RGB) where $\\log g$ = 3.6 dex. Note that we only use models after the zero-age-main-sequence (ZAMS). We define ZAMS as the point where core-hydrogen burning contributes over 99.9\\% of the total luminosity. \n%\nThe stellar gird considers four independent fundamental inputs which are stellar mass ($M$), initial helium fraction ($Y_{\\rm init}$), initial metallicity ([Fe/H]$_{\\rm init}$), and the mixing-length parameter ($\\alpha_{\\rm MLT}$). \n%\nWe calculated three model grids. First, a primary grid covers the whole input range. Uniform grid step is applied for $M$, $Y_{\\rm init}$, $\\alpha_{\\rm MLT}$, and we use tow different grid steps for [Fe/H]$_{\\rm init}$ below and above 0.2 dex.  Second, an additional grid is computed for $M$ > 1.05$\\rm M_{\\odot}$. Grid points of this grid are in between of the primary grid to increase the resolution for tracks with the 'hook'. \nThird, we compute off-grid models with random fundamental input values as an independent dataset for validating and testing GP models. \n%4,880 tracks with input parameters that are randomly sampled in the grid ranges for validating GPR models. The evolution time step was mainly controlled by the set-up tolerances on changes in surface effective temperature and luminosity. We also saved structural models for computing theoretical oscillation models.\n%\nDetails of the computation are listed in Table \\ref{tab:grid}. \n\n\\begin{table}\n\t\\centering\n\t\\caption{Computation of Stellar model grid.}\n\t\\label{tab:grid}\n\t\\begin{tabular}{llll} % four columns, alignment for each\n\t\t\\hline\n\t\t\\multicolumn{3}{c}{Primary Grid}\\\\\n\t\t\\hline\n\t\tInput Parameter & Range & Increment \\\\\n        \\hline\n\t$M$ ($\\rm M_{\\odot}$) & 0.80 -- 1.20 &  0.01\\\\\n        $\\rm{[Fe/H]}$ (dex) & -0.5 -- 0.2/0.2 -- 0.5 & 0.1/0.05\\\\\n        \t$Y_{\\rm init}$ & 0.24 -- 0.32 & 0.02\\\\\n        $\\alpha_{\\rm{MLT}}$  & 1.7 -- 2.5&  0.2\\\\\n        \\hline\n       \\multicolumn{3}{c}{Additional Grid}\\\\\n\t\\hline\n\tInput Parameter & Range & Increment \\\\\n        \\hline\n\t$M$ ($\\rm M_{\\odot}$)  & 1.055 -- 1.195 &  0.01\\\\\n        $\\rm{[Fe/H]}$ (dex) & 0.25 -- 0.45 & 0.1\\\\\n        \t$Y_{\\rm init}$ & 0.25 -- 0.31 & 0.02\\\\\n        $\\alpha_{\\rm{MLT}}$  & 1.8-- 2.4&  0.2\\\\\n        \\hline\n        \\multicolumn{3}{c}{Off-grid Models}\\\\\n        \\hline\n        \\multicolumn{3}{c}{Input Parameters} &N\\\\\n        \\hline\n         \\multicolumn{3}{l}{Random $M$, [Fe/H]$_{\\rm init}$ = 0.0, $Y_{\\rm init}$ = 0.28, $\\alpha_{\\rm MLT}$ = 2.1 } & 44\\\\\n        \\multicolumn{3}{l}{Random $M$ and [Fe/H]$_{\\rm init}$, $Y_{\\rm init}$ = 0.28, $\\alpha_{\\rm MLT}$ = 2.1 }&174\\\\\n        \\multicolumn{3}{l}{Random $M$, [Fe/H]$_{\\rm init}$, $Y_{\\rm init}$, and $\\alpha_{\\rm MLT}$}&4880\\\\\n\t\\hline\n\t\\end{tabular}\n\\end{table}\n\n%\\subsection{Stellar models and input physics}\\label{subsec:stellar_model}\n\nWe use the stellar code Modules for Experiments in Stellar Astrophysics\n(\\textsc{MESA}, version 12115) to construct stellar grids. \n\\textsc{MESA} is an open-source stellar evolution package which is undergoing active development. \nDescriptions of input physics and numerical methods\ncan be found in \\citet{2011ApJS..192....3P,2013ApJS..208....4P, 2015ApJS..220...15P}.\nWe adopted the solar chemical mixture [$(Z/X)_{\\odot}$ = 0.0181]\nprovided by \\citet{2009ARA&A..47..481A}. \nThe initial helium fraction ($Y_{\\rm init}$) and initial metallicity ($\\rm{[Fe/H]_{init}}$) are independent inputs. \nThe initial chemical composition is calculated with \n\\begin{equation}\n\\log (Z_{\\rm{init}}/X_{\\rm{init}}) = \\log (Z/X)_{\\odot} + \\rm{[Fe/H]_{init}}.  \\\\\n\\end{equation}\nWe use the \\textsc{MESA} $\\rho-T$ tables based on the 2005\nupdate of OPAL EOS tables \\citep{2002ApJ...576.1064R} and OPAL opacity\nsupplemented by low-temperature opacity \\citep{2005ApJ...623..585F}. \nThe grey Eddington $T-\\tau$ relation is used to determine boundary conditions for modelling the atmosphere.\nThe mixing-length theory is implemented and the convection is adjusted by the mixing-length parameter ($\\alpha_{\\rm MLT}$).\nWe also apply the \\textsc{MESA} predictive mixing scheme \\citep{2018ApJS..234...34P,2019ApJS..243...10P}, which improves model structures at the convective boundary.  \nAtomic diffusion of helium and heavy elements was also taken into account. MESA calculates particle diffusion and gravitational settling by solving Burger's equations using the method and diffusion coefficients of \\citet{Thoul94}. \n%We considered 8 classes of species (H1, He3, He4, C12, N14, O16, Ne20, and Mg24) We considered 8 classes of species (H1, He3, He4, C12, N14, O16, Ne20, and Mg24)\nWe consider eight elements (${}^1{\\rm H}, {}^3{\\rm He}, {}^4{\\rm He}, {}^{12}{\\rm C}, {}^{14}{\\rm N}, {}^{16}{\\rm O}, {}^{20}{\\rm Ne}$, and ${}^{24}{\\rm Mg}$)\nfor diffusion calculations, and have the charge calculated by the MESA ionization module, which estimates the typical ionic charge as a function of $T$, $\\rho$, and free electrons per nucleon from \\citet{Paquette1986}.\nThe \\textsc{MESA} inlist used for the computation is available on \\url{https://github.com/litanda/mesa_inlist}.  \n\n%\\subsection{Oscillation models and seismic $\\Delta \\nu$}\\label{subsec:seismo_model}\n\n%Theoretical stellar oscillations were calculated with the \\textsc{GYRE} code (version 5.1), which was developed by \\citet{2013MNRAS.435.3406T}. And we computed radial modes (for $\\ell$ = 0) by solving the adiabatic stellar pulsation equations with the structural models generated by \\textsc{MESA}. We computed a seismic large separation($\\Delta \\nu$) for each model with theoretical radial modes to avoid the systematic offset of the scaling relation. We derived $\\Delta \\nu$ with the approach given by \\citet{2011ApJ...743..161W}, which is a weighted least-squares fit to the radial frequencies as a function of $n$.  \n\n\\subsection{Equivalent Evolutionary Phase}\n\nFor training GP models, we need to convert stellar age, whose dynamical range varies track by track, into a uniform range. The fractional age is an option. However, we find that global parameters (e.g. effective temperature) sharply change with the fractional age around the 'hook' and the turn-off point (left panel in Figure~\\ref{fig:eep}). It requires a complex and spiky kernel function to fit the curvatures in this area and hence difficult for GP to learn. \\citet{2016ApJS..222....8D} has introduced a quantity Equivalent Evolutionary Phase ({\\it EEP}), which numbers evolutionary stages and transform stellar tracks onto a uniform basis. We follow this idea but define {\\it EEP} in a different way.\n%\nOn each evolutionary track, we compute the displacement between model $n$ and model $n-1$ on the $T_{\\rm eff} - \\log g$ diagram as\n\\begin{equation}\\label{eq:disp}\n\\delta d_{n} = ((T_{\\rm eff, n} - T_{\\rm eff, n-1}) ^{2} + (\\log g _{n} - \\log g_{n-1})^{2}))^{f},\n\\end{equation}\nand the total displacement of model $n$ from the ZAMS (model 0) can be calculated with\n\\begin{equation}\nd_{n} = \\sum_{i = 0}^{i = n} \\delta d_{i} .\n\\end{equation}\nWe then normalise $d_{n}$ to the 0 --1 range and define it as {\\it EEP}. On the same evolutionary track, {\\it EEP} equals to 0 at the ZAMS and 1 on the RGB where $\\log$ = 3.6 $dex$. The factor $f$ in Eq. \\ref{eq:disp} is adjustable for modulating {\\it EEP} to avoid obvious gap in the data space, and we find that $f$ = 0.18 gives the best data distribution.\n%\nIn Figure~\\ref{fig:eep}, we demonstrate how the effective temperature changes with fractional age and {\\it EEP}. It can be seen that the usage of {\\it EEP} significantly smoothes the sharp features at the 'hook' and the turn-off point.\n\n\\begin{figure*}\n        \\includegraphics[width=1.\\columnwidth]{2d_fage_data.pdf}\n\t\\includegraphics[width=1.\\columnwidth]{2d_EEP_data.pdf}\n     \\caption{Surface plots of model effective temperature on the mass-fractional age (left) and mass-EEP (right) diagrams. Models in this figure are from the primary grid with fixed initial metallicity ($\\rm [Fe/H]_{init}$ = 0.0), helium fraction ($Y_{\\rm init}$ = 0.28) and mixing-length parameter ($\\alpha_{\\rm MLT}$ = 2.1). It can be seen that the effective temperature changes much smoother on the mass-EEP diagram at the hook and turn-off points.}\n    \\label{fig:eep}\n\\end{figure*}\n\n\\subsection{Data Selection}\\label{sec:selection}\n\nWe need three types of data for training, validating, and testing GP models. \n%\nEvolutionary tracks in the primary and additional grids are the training data. Off-grid tracks are divided 50-to-50 as validating and testing data . \n%Note that validating and testing datasets are not on the same evolutionary tracks so they are independent to each other. \n%Validating dataset is for validating the GP model in the training process and is mainly used for early stopping, which is a form of regularisation for avoiding overfitting. We choose off-grid models but not on-grid models as validating data because the grid is equally spaced. Without additional information between grid points, an optimiser could either use a smooth function or a periodic function to fit the data and find no obvious differences in the likelihood. We describe how we use validating data in Section \\ref{sec:training}. Lastly, testing dataset is independent on the training process and used for evaluating the final GP models. \nThere is a limitation of the data size in the GP framework, because the computational and memory complexity exponentially increase with the number of data points. In practice, the typical data size is on an order of $10^{4}$. Given that the grid contents $\\sim 10,000,000$ stellar models, only a small subset can be used. The sampling method is hence critical.\n%\n A flat sampling is not appropriate, because the evolving step is not uniform at different evolutionary stages due to the \\textsc{MESA} step-control strategy. For instance, stellar models are dense at the main-sequence and lower RGB but quite sparse at the subgiant stage. We test a few methods and find that using the displacement ($\\delta d_{n}$) defined in Eq.~\\ref{eq:disp} as the weight of sampling give a relatively uniform data distribution. \n%meets the above two requirements. \n%Firstly, we want the data to uniformly cover the parameter space for the best efficiency. Secondly, we need to highly weight models at phases where sharp changes present, e.g., models around the hook and turn-off points.   \n\n\n\n", "meta": {"hexsha": "bba7ce0863141000429cc272994a15d6757e6147", "size": 10696, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/grids.tex", "max_stars_repo_name": "litanda/GPGrid_paper", "max_stars_repo_head_hexsha": "b03fafdb523cb147e85ebaaba42fbe7c14d4fced", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paper/grids.tex", "max_issues_repo_name": "litanda/GPGrid_paper", "max_issues_repo_head_hexsha": "b03fafdb523cb147e85ebaaba42fbe7c14d4fced", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-07-24T12:26:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-14T21:35:20.000Z", "max_forks_repo_path": "paper/grids.tex", "max_forks_repo_name": "litanda/GPGrid_paper", "max_forks_repo_head_hexsha": "b03fafdb523cb147e85ebaaba42fbe7c14d4fced", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 90.6440677966, "max_line_length": 705, "alphanum_fraction": 0.7262528048, "num_tokens": 3037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421274, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.33767676499614896}}
{"text": "\\documentclass{memoir}\n\\usepackage{notestemplate}\n\n% \\begin{figure}[ht]\n%     \\centering\n%     \\incfig{riemmans-theorem}\n%     \\caption{Riemmans theorem}\n%     \\label{fig:riemmans-theorem}\n% \\end{figure}\n\n\\begin{document}\n\\section{Subring, Ideals, Quotient rings, Ring homomorphisms}\t\n\\begin{defn}[Subring]\n\tA subring is a subset \\(S\\) of a ring \\(R\\) which is a ring under the restriction of the operations in \\(R\\). We denote this by \\(S\\leq R\\).\n\\end{defn}\n\n\\begin{rmrk}\n\\(S\\leq R\\) nonempty is a subring if and only if \\(a,b \\in S \\implies a+b, ab, -a \\in S\\). This is equivalent to \\(a,b \\in S \\implies a-b, ab \\in S\\).\n\\end{rmrk}\n\n\\begin{defn}[Ideal]\n\tAn ideal is a subring \\(I \\leq R\\) which is closed under multiplication with elements of \\(R\\). Notationally, we say that \\(I \\triangleleft R\\).\n\\end{defn}\n\n\\begin{rmrk}\n\\(I\\) nonempty is an ideal if and only if \\(a,b \\in I \\implies a-b \\in I\\), which is equivalent to \\(a \\in I, r \\in R \\implies ar, ra \\in I\\).\n\\end{rmrk}\n\n\\begin{hw}\nShow that a field has only trivial ideals.\n\\end{hw}\n\n\\begin{defn}[Principal Ideal]\n\tIf \\(R\\) is commutative and has an identity, then the principal ideal generated by \\(c\\) is the ideal \\((c) = \\left\\{rc \\mid r \\in R \\right\\} \\). \n\\end{defn}\nThis is the smallest ideal containing \\(c\\).\n\\end{document}\n", "meta": {"hexsha": "6f1adb6227ab4b78151f46856fffd57ac91de3ee", "size": 1296, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Abstract Algebra - Introductory/Algebra I/Notes/source/2020-02-12-Subrings.tex", "max_stars_repo_name": "gjgress/Libera-Mentis", "max_stars_repo_head_hexsha": "d9f1bfd9e6ea62a9d56292f7890f99c450b54c9b", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-16T23:18:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-16T23:18:15.000Z", "max_issues_repo_path": "Abstract Algebra - Introductory/Algebra I/Notes/source/2020-02-12-Subrings.tex", "max_issues_repo_name": "gjgress/Libera-Mentis", "max_issues_repo_head_hexsha": "d9f1bfd9e6ea62a9d56292f7890f99c450b54c9b", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2021-05-20T22:09:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:23:22.000Z", "max_forks_repo_path": "Abstract Algebra - Introductory/Algebra I/Notes/source/2020-02-12-Subrings.tex", "max_forks_repo_name": "gjgress/LibreMath", "max_forks_repo_head_hexsha": "d9f1bfd9e6ea62a9d56292f7890f99c450b54c9b", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1052631579, "max_line_length": 150, "alphanum_fraction": 0.6697530864, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.3376767649961489}}
{"text": "\\documentclass{article} % For LaTeX2e\n\\usepackage[legalpaper, margin=0.5in]{geometry}\n\\usepackage{amsmath}\n\\usepackage{amsfonts,dsfont}\n\\usepackage{amssymb}\n\\usepackage[ruled,vlined]{algorithm2e}\n\n\\usepackage{graphicx}\n\\usepackage{caption}\n\\usepackage{subcaption}\n\\usepackage{xcolor}\n\n\\begin{document}\n\n\\section{Simple GAN vs. Unsupervised Conditional GAN}\n\\begin{figure}[h]\n\t\\centering\n\t\\captionsetup{labelformat=empty}\n\t\\begin{subfigure}[b]{0.3\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{2_gan_ls9_1000_1000.pdf}\n\t\t\\caption{Simple GAN (2 modes)}\n\t\t\\label{fig:gan_2}\n\t\\end{subfigure}\n\t\\begin{subfigure}[b]{0.3\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{3_gan_ls9_1000_1000.pdf}\n\t\t\\caption{Simple GAN (3 modes)}\n\t\t\\label{fig:gan_3}\n\t\\end{subfigure}\n\t\\begin{subfigure}[b]{0.3\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{4_gan_ls9_1000_1000.pdf}\n\t\t\\caption{Simple GAN (4 modes)}\n\t\t\\label{fig:gan_4}\n\t\\end{subfigure} \\\\\n\t\\begin{subfigure}[b]{0.3\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{2_cond_gan_k2_ls9_1000_1000.pdf}\n\t\t\\caption{Conditional GAN (2 modes)}\n\t\t\\label{fig:cgan_2}\n\t\\end{subfigure}\n\t\\begin{subfigure}[b]{0.3\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{3_cond_gan_k3_ls9_1000_1000.pdf}\n\t\t\\caption{Conditional GAN (3 modes)}\n\t\t\\label{fig:cgan_3}\n\t\\end{subfigure}\n\t\\begin{subfigure}[b]{0.3\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{4_cond_gan_k4_ls9_1000_1000.pdf}\n\t\t\\caption{Conditional GAN (4 modes)}\n\t\t\\label{fig:cgan_4}\n\t\\end{subfigure} \\\\[-1ex]\n\t\\caption{Comparison between simple GAN and {\\bf unsupervised} Conditional GAN (cGAN) for $1D$ data with multiple modes. The samples at $y=0$ are the real samples on which the GAN was trained. The samples at $y=0.5$ are synthetic samples generated by the GANs after training for $1000$ epochs. The {\\em black} lines show the histogram of the original data. The \\textit{\\textcolor{red}{red}} lines show the histogram of the synthetic samples generated by the GAN. For the unsupervised cGAN, we first perform {\\em unsupervised} clustering with Gaussian Mixture Models. The number of components were selected with {\\em BIC}. The cluster labels are then assigned as the class labels. For the 1D data shown here, cluster information seems to help.}\n\t\\label{fig:1d_gan}\n\\end{figure}\n\n\\section{AnoGAN}\n\\begin{figure}[h]\n\t\\centering\n\t\\captionsetup{labelformat=empty}\n\t\\begin{subfigure}[b]{0.45\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{toy2_ano_gan_ls9_2000.pdf}\n\t\t\\caption{Toy data samples}\n\t\t\\label{fig:toy}\n\t\\end{subfigure}\n\t\\begin{subfigure}[b]{0.45\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{toy2_ano_gan_ls9_2000_test_ano_50.pdf}\n\t\t\\caption{{\\em AnoGAN} with simple GAN}\n\t\t\\label{fig:gan_ano}\n\t\\end{subfigure} \\\\\n\t\\begin{subfigure}[b]{0.45\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{toy2_cond_ano_gan_k3_ls9_2000.pdf}\n\t\t\\caption{Clusters for cGAN}\n\t\t\\label{fig:cgan_k}\n\t\\end{subfigure}\n\t\\begin{subfigure}[b]{0.45\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{toy2_cond_ano_gan_k3_ls9_2000_test_ano_50.pdf}\n\t\t\\caption{{\\em AnoGAN} with cGAN}\n\t\t\\label{fig:cgan_ano}\n\t\\end{subfigure} \\\\[-1ex]\n\t\\caption{Illustration of {\\bf AnoGAN}. {\\bf (a)} shows the $2D$ {\\em Toy} data. All GANs were trained for $2000$ epochs. {\\bf (b)} shows the AnoGAN results with a simple GAN. {\\bf (c)} shows the unsupervised clustering of the {\\em Toy} dataset. The number of components in the Gaussian Mixture Model was found to be $3$ using the $BIC$ model selection criteria. {\\bf (d)} shows the AnoGAN results with a cGAN where the labels were assigned according to the clusters shown in {\\bf (c)}. In {\\bf (b)} and {\\bf (d)} the points marked in {\\em black} are test data points which were not available during training. Each test point has a corresponding colored point (marked with a \\textit{\\textcolor{red}{red `$\\times$'}}) that represents its synthetic image reconstructed by AnoGAN. In simplistic terms, the distance between a test point and its reconstructed image can be considered a measure of anomalousness. {\\bf (b)} and {\\bf (d)} show that the points in the dense regions (e.g., $2, 3, 4, 7$) generally have low reconstruction loss. However, points in low-density regions (e.g., $1, 5, 6, 8$) give mixed results: while the reconstruction loss for $1$ is low, it is high for $5, 6, 8$. {\\bf (b)} and {\\bf (d)} also show the trace of reconstruction for each data point. AnoGAN computes the reconstructed image iteratively. For example, with test point $5$, the initial random latent representation $z_0$ corresponds to a point in the middle. After optimizing the AnoGAN loss, a new latent representation $z_1$ is found which corresponds to a point slightly closer to $5$. Then, using $z_1$ and optimizing, the next latent representation $z_2$ is found. Over the several iterations, the reconstructed image for $5$ moved along the \\textcolor{brown}{brown} line until it finally reached the point marked with \\textcolor{red}{$\\times$}. The traces are useful for debug: we can see that all reconstructed points move closer to the target test points irrespective of where they start. It is hard to see whether a cGAN performs better than a simple GAN in this case. Moreover, the AnoGAN loss should be averaged over multiple runs for each test point because there is stochasticity in the initial latent representation.}\n\t\\label{fig:ano_gan}\n\\end{figure}\n\n\n\\end{document}\n", "meta": {"hexsha": "70e7b39cc2f996b1e674a93c29d29dcd7a2141d6", "size": 5360, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "documentation/gan/gan.tex", "max_stars_repo_name": "snad-space/ad_examples", "max_stars_repo_head_hexsha": "7c62a81f52e79874d6215b262f5a849d56eeae4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 773, "max_stars_repo_stars_event_min_datetime": "2017-12-10T04:08:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T01:50:38.000Z", "max_issues_repo_path": "documentation/gan/gan.tex", "max_issues_repo_name": "snad-space/ad_examples", "max_issues_repo_head_hexsha": "7c62a81f52e79874d6215b262f5a849d56eeae4f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2018-12-25T00:46:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T00:02:29.000Z", "max_forks_repo_path": "documentation/gan/gan.tex", "max_forks_repo_name": "snad-space/ad_examples", "max_forks_repo_head_hexsha": "7c62a81f52e79874d6215b262f5a849d56eeae4f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 197, "max_forks_repo_forks_event_min_datetime": "2018-05-08T04:16:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T21:37:03.000Z", "avg_line_length": 64.578313253, "max_line_length": 2213, "alphanum_fraction": 0.7578358209, "num_tokens": 1684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.33767675805017944}}
{"text": "\n\\documentclass[english]{beamer}\n\\input{preamble.tex}\n\\begin{document}\n\n\n\\title{Estimation of DP Models}\n\n\\subtitle{ScPo CompEcon}\n\n\n\\frame{\\titlepage} \n\n\\frame{\\frametitle{Table of contents}\\tableofcontents} \n\n\\section{Rust Bus Replacement}\n\n\\begin{frame}\n\\tableofcontents[currentsection] \n\\end{frame}\n\n\n\n\n\n\\begin{frame}{Estimation of Dynamic Programming Models}\n\\begin{midi}\n\\item Now that we know how to solve them, how do we estimate DP models?\n\\item Examples\n\\begin{itemize}\n\\item \\cite{rustbus}\n\\item \\cite{BLP}\n\\end{itemize}\n\\item There are many different methods. We will introduce just a few. Look at the survey \\cite{Aguirre} for more details.\n\\end{midi}\n\\end{frame}\n\n\\begin{frame}{\\cite{rustbus}}\n\\begin{itemize}\n\\item Each Bus comes in once a month for repair\n\\begin{itemize}\n\\item Harold Zurcher decides after observing mileage $x_t$ since last engine replacment \\bred{and} some other unobserved variable $\\varepsilon$ whether to replace or not:\n\\begin{equation*}\nu(x+t,d_t,\\red{\\theta^c},\\red{RC}) = \\begin{cases}-c(x_t,\\red{\\theta^c}) & \\text{if }d_t=0 \\\\ \n                                                  -(\\red{RC} + c(0,\\red{\\theta^c}) & \\text{if }d_t=1\n  \\end{cases}\n\\end{equation*}\n\n\\item He solves the DP\n\\begin{equation*}\nV_\\red{\\theta}(x_t) = \\sup_{d_t} \\mathbb{E}\\left\\{ \\sum_{j=t}^\\infty \\beta^{j-t} u(x_j,d_j,\\red{\\theta}) + \\varepsilon_t(d_t) |x_t \\right\\}\n\\end{equation*}\n\\end{itemize}\n\\item Parameters to be estimated: $\\red{\\theta} = \\red{(\\theta^c,RC,\\theta^p)}$\n\\item This formulation results after making a set of simplifying assumptions.\n\\end{itemize}\n\\end{frame}\n\n\n\\begin{frame}{\\cite{rustbus}}\n\\begin{midi}\n\\item To simplify, the odometer progress is assumed to be a random process.\n\\item that is, $x_t$ evolves stochastically.\n\\item The assumption is that $x_{t+1}\\in\\{s,s+1,s+2,s+3\\}$ where $s$ is the state of $x_t$, i.e. the bin it lies in. \n\\end{midi}\n\n\\end{frame}\n\t\n\\begin{frame}{Model and Data}\n\\begin{midi}\n\\item Data: a time series $\\{x_t,d_t \\}_{t=1}^T$\n\\item Likelihood function is\n\\begin{equation*}\n\\mathcal{L}(\\red{\\theta}) = \\Pi_{t=2}^T P(d_t|x_t,\\red{\\theta^c},\\red{RC})p(x_t|x_{t-1},d_{t-1},\\red{\\theta^p})\n\\end{equation*}\nwhere the conditional choice probabilities are given by\n\\begin{equation*}\nP(d_t|x_t,\\red{\\theta^c},\\red{RC}) = \\frac{\\exp[u(x,d,\\red{\\theta^c},\\red{RC}) + \\beta\\blue{EV}_\\red{\\theta}(x,d)]}{\\sum_{d'\\in\\{0,1\\}}\\exp[u(x,d',\\red{\\theta^c},\\red{RC}) + \\beta\\blue{EV}_\\red{\\theta}(x',d')]}\n\\end{equation*}\nand, importantly, $\\blue{EV}$ is the solution to\n\n\\begin{align*}\n\\blue{EV}_\\red{\\theta}(x,d) =& T_\\red{\\theta}(\\blue{EV}_\\red{\\theta})(x,d) \\\\\n                       \\equiv&\\int_{x'=0}^\\infty \\log \\left( \\sum_{d'\\in{0,1}}\\exp[u(x,d',\\red{\\theta^c},\\red{RC}) + \\beta\\blue{EV}_\\red{\\theta}(x',d')] \\right)\n\\end{align*}\n\\end{midi}\n\\end{frame}\n\n\n\\begin{frame}{Nested Fixed Point Algorithm (NXFP)}\n\\begin{widee}\n\\item \\bred{Outer Loop}: Solve the Likelihood function\n\\begin{equation*}\n\\max_{\\red{\\theta}>0} \\mathcal{L}(\\red{\\theta}) = \\Pi_{t=2}^T P(d_t|x_t,\\red{\\theta^c},\\red{RC})p(x_t|x_{t-1},d_{t-1},\\red{\\theta^p})\n\\end{equation*}\n\\item \\bblue{Inner Loop}: Compute Expected value function $\\blue{EV}_\\red{\\theta}$ for a given guess $\\red{\\theta}$\n\\begin{equation*}\n\\blue{EV}_\\red{\\theta} = T_\\red{\\theta}(\\blue{EV}_\\red{\\theta})(x,d)\n\\end{equation*}\n\\end{widee}\n\\end{frame}\n\n\\begin{frame}{Potential Issues with NXFP}\n\\begin{midi}\n\\item We need a stopping rule for the likelihood function.\n\\item We need one for the inner loop as well.\n\\item Errors will propagate from the inner loop to the outer loop.\n\\item Given that the search direction on $\\mathcal{L}(\\red{\\theta})$ depends on it's gradient, errors will matter a lot.\n\\item the tolerance on the inner loop needs to be \\bred{tight}, like $1.0e^{-13}$\n\\end{midi}\n\\end{frame}\n\n\n\n\n\\begin{frame}{MPEC}{Mathematical Programming with Equality constraints}\n\n\\begin{midi}\n\\item We can turn the problem around. \n\\item Instead of asking \\emph{Whats the \\blue{EV} compatible with my guess $\\red{\\theta}$?}, we could directly attack the likelihood: \n\\item Maximize $\\mathcal{L}(\\red{\\theta})$ \\bred{subject to} the constraint, that behavior is \\bblue{optimal} according to the model.\n\\item in other words, augment the likelihood:\n\\end{midi}\n\n\\begin{align*}\n\\mathcal{L}(\\red{\\theta},\\blue{EV};X) &= \\Pi_{t=2}^T P(d_t|x_t,\\red{\\theta^c},\\red{RC})p(x_t|x_{t-1},d_{t-1},\\red{\\theta^p}) \\\\\nP(d_t|x_t,\\red{\\theta^c},\\red{RC}) &= \\frac{\\exp[u(x,d,\\red{\\theta^c},\\red{RC}) + \\beta\\blue{EV}(x,d)]}{\\sum_{d'\\in\\{0,1\\}}\\exp[u(x,d',\\red{\\theta^c},\\red{RC}) + \\beta\\blue{EV}(x',d')]}\n\\end{align*}\n\n\\end{frame}\n\n\\begin{frame}{Different Optimization problems}\n\\bred{NXFP} solves the unconstrained optimization problem:\n\\begin{equation*}\n\\max_{\\red{\\theta}} \\mathcal{L}(\\red{\\theta},\\blue{EV}_\\red{\\theta})\n\\end{equation*}\n\\bblue{MPEC} solves the constrained optimization problem:\n\\begin{align*}\n\\max_{\\red{\\theta},\\blue{EV}} & \\mathcal{L}(\\red{\\theta},\\blue{EV};X) \\\\\n\\text{subject to} & \\blue{EV} = T(\\blue{EV},\\red{\\theta})\n\\end{align*}\n\\end{frame}\n\n\\begin{frame}{\\cite{juddsu}}\n\n\\begin{midi}\n\\item \\cite{juddsu} perform MPEC on the bus model.\n\\item the key difference to note is that $\\blue{EV}$ now becomes a choice variable.\n\\item In fact, the optimizer will be fed a vector\n\\begin{equation*}\nx = [RC,\\theta^c,\\mathbf{EV}]\n\\end{equation*}\nwhere $\\mathbf{EV}$ is an approximation to $\\blue{EV}$. In \\cite{juddsu}, this is just going to be \n\\begin{equation*}\n\\mathbf{EV} \\equiv [EV(x_1),EV(x_2),\\dots,EV(x_n)]\n\\end{equation*}\ni.e. the approximation needs to hold pointwise.\n\\end{midi}\n\\end{frame}\n\n\\begin{frame}{\\cite{juddsu}}\n\\includegraphics[width=11cm]{su-2.png}\n\n\\end{frame}\n\n\\begin{frame}{Performance}\n\\begin{midi}\n\\item In \\emph{general}, NXFP is a computationally expensive operation.\n\\begin{itemize}\n\\item you have to solve a DP for many many many times in order to find your $\\red{\\theta}$.\n\\end{itemize}\n\\item However, there is much to qualify about this statement. The \\bred{details} matter here.\n\\item For example, \\cite{juddsu} are very critical about NXFP in the Bus Model. They compare it to the performance of \\bblue{MPEC}.\n\\item But \\citet{iskhakov2016comment} redo the exercise with Rust's original method to solve $\\blue{EV}$ and show that NXFP is still a very strong contender in this example.\n\\end{midi}\n\\end{frame}\n\n\n\\section{Berry, Levinsohn and Pakes (BLP) as MPEC}\n\n\\begin{frame}\n\\tableofcontents[currentsection] \n\\end{frame}\n\t\n\\begin{frame}{BLP after \\cite{dube2012improving}}\n\\begin{midi}\n\\item \\cite{BLP} is a model for automobile sales.\n\\item It has become a very widely applied model and estimation technique, short: \\bred{BLP}.\n\\item The original paper performs demand estimation with a large number of differentiated products:\n\\begin{itemize}\n\\item characteristics approach\n\\item useful when only aggregate data are available\n\\item allows for flexible substitition patterns\n\\item controls for price endogeneity\n\\end{itemize}\n\\item The computational algorithm derives moment conditions from a non-linear model\n\\item The method is also known as \\bblue{Random Coefficients Logit Demand} \n\\end{midi}\n\\end{frame}\n\n\\begin{frame}{Random Coefficients Logit Demand}\n\\begin{midi}\n\\item The Utility of $i$ from purchasing product $j$ in market $t$ is\n\\begin{equation}\nu_{ijt} = \\red{\\beta_i^0} + x_{jt}\\red{\\beta_i^x} - \\red{\\beta_i^p} p_{jt} + \\blue{\\xi_{jt}} + \\varepsilon_{ijt} \\label{eq:demand}\n\\end{equation}\n\\item with product characteristics $x_{jt},p_{jt},\\blue{\\xi_{jt}}$\n\\begin{itemize}\n\\item $x_{jt},p_{jt}$: ovserved with $cov(p_{jt},\\blue{\\xi_{jt}})\\neq 0$\n\\item $\\blue{\\xi_{jt}}$: unovserved to econometrician.\n\\end{itemize}\n\\item $\\red{\\beta_i} \\equiv [\\red{\\beta_i^0},\\red{\\beta_i^x},\\red{\\beta_i^p}]$: random coefficients or individual specific tastes to be estimated.\n\\begin{itemize}\n\\item We posit a distribution: $\\red{\\beta_i} \\sim F_\\beta(\\beta,\\red{\\theta})$\n\\item \\redbox{Goal of BLP}: estimate $\\red{\\theta}$ in the above parametric distribution.\n\\item errors are assumed type 1 EV\n\\item Consumer picks product $j$ if $u_{ijt}\\geq u_{ij't}$\n\\end{itemize}\n\\end{midi}\n\\end{frame}\n\n\\begin{frame}{The Model: Market Shares}\n\\begin{midi}\n\\item The model predicts \\cyanbox{market shares}:\n\\begin{equation}\ns_j(x_t,p_t,\\blue{x_{it}};\\red{\\theta}) = \\int_{\\{\\beta_i,\\varepsilon_i | u_{ijt}\\geq u_{ij't},\\forall j'\\neq j\\}} dF_\\beta(\\beta,\\red{\\theta}) dF_\\varepsilon(\\varepsilon)\n\\end{equation}\n\\item with type 1 EV shocks $\\varepsilon$, there is an analytical solution to one of those integrals:\n\\begin{equation}\ns_j(x_t,p_t,\\blue{x_{it}};\\red{\\theta})  = \\int_\\beta \\frac{\\exp(\\beta^0 + x_{jt}\\beta^x - \\beta^p p_{jt} + \\blue{\\xi_{jt}})}{1+\\sum_{k=1}^J \\exp(\\beta^0 + x_{kt}\\beta^x - \\beta^p p_{kt} + \\blue{\\xi_{kt}})} dF_\\beta(\\beta,\\red{\\theta})\n\\end{equation}\n\\end{midi}\n\\end{frame}\n\n\\begin{frame}{The Model: Market Shares}\nThey use numerical integration:\n\\begin{equation}\n\\hat{s}_j(x_t,p_t,\\blue{x_{it}};\\red{\\theta})  = \\frac{1}{ns} \\sum_{r=1}^{ns} \\frac{\\exp(\\beta^{0r} + x_{jt}\\beta^{xr} - \\beta^{pr} p_{jt} + \\blue{\\xi_{jt}})}{1+\\sum_{k=1}^J \\exp(\\beta^{0r} + x_{kt}\\beta^{xr} - \\beta^{pr} p_{kt} + \\blue{\\xi_{kt}})} dF_\\beta(\\beta,\\red{\\theta})\n\\end{equation}\nto arrive at the market share (moment) conditions:\n\\begin{equation}\n\\hat{s}_j(x_t,p_t,\\blue{\\xi_{it}};\\red{\\theta}) = S_{jt},\\forall j \\in J,t\\in T  \\label{eq:shares}\n\\end{equation}\nwhere $S_{jt}$ is data.\n\\end{frame}\n\n\\begin{frame}{GMM Estimator}\n\\begin{midi}\n\\item If firms can observe demand shocks $\\blue{\\xi_t}$, they will set prices accordingly.\n\\item There will be correlation between $p_t$ and $\\blue{\\xi_t}$ $\\Rightarrow$ Endogeneity Bias!\n\\item BLP solve endogeneity of prices with a vector $z_{jt}$ of IVs, which are \\bred{excluded} from the demand equation \\eqref{eq:demand}\n\\item they propose a moment condition $E[\\blue{\\xi_{jt}}|z_{jt},x_{jt}] = 0 $\n\\item $z_{jt}$: e.g. product-specific cost shifters, or $K$ non-price characteristics in $x_{j,t}$ (assumed mean independent of $\\blue{\\xi_t}$)\n\\item We often form $E[\\xi_{jt} \\cdot h(z_{jt},x_{jt})] = 0 $ for some known function $h$.\n\\end{midi}\n\\end{frame}\n\n\\begin{frame}{Getting moment equations}\n\\begin{midi}\n\\item To get the sample analog of $E[\\blue{\\xi_{jt}}|z_{jt},x_{jt}] = 0$, we need to find $\\blue{\\xi_{jt}}$ corresponding to $\\red{\\theta}$\n\\item System \\eqref{eq:shares} defines a mapping $\\blue{\\xi_{jt}}$ and $S_t$\n\\item Berry proved that $s$ has an inverse, hence any observed $S_t$ can be explained by a \\bblue{unique} $\\blue{\\xi_{jt}}(\\red{\\theta}) = s^{-1}(S_t,\\red{\\theta})$\n\\item Sample analog of $E[\\blue{\\xi_{jt}}|z_{jt},x_{jt}] = 0$ is thus\n\\begin{equation*}\ng(\\red{\\theta}) = \\frac{1}{TJ}\\sum_{t,j} \\blue{\\xi_{jt}}(\\red{\\theta})' z_{jt}\n\\end{equation*}\n\\end{midi}\n\\end{frame}\n\n\\begin{frame}{GMM Estimator}\n\\begin{widei}\n\\item Data are $\\{(x_{jt},p_{jt},S_{jt},z_{jt})_{j\\in J,t\\in T}\\}$\n\\item We want to minimize the GMM objective\n\\begin{equation*}\nQ(\\red{\\theta}) = g(\\red{\\theta})' W g(\\red{\\theta})\n\\end{equation*}\n\\item There is no analytic form for $\\blue{\\xi_{jt}}(\\red{\\theta})$, see previous slide\n\\end{widei}\n\\end{frame}\n\n\\begin{frame}{\\cite{BLP} Estimation Algorithm - NFXP}\n\\begin{midi}\n\\item \\bred{Outer} Loop: $\\min_{\\red{\\theta}} g(\\red{\\theta})' W g(\\red{\\theta})$\n\\begin{enumerate}\n\\item Guess vector $\\red{\\theta}$ to get $g(\\red{\\theta}) = \\frac{1}{TJ}\\sum_t \\sum_j\\blue{\\xi_{jt}}(\\red{\\theta})' z_{jt}$\n\\item Stop whenever $|| \\nabla_\\theta(g(\\red{\\theta})' W g(\\red{\\theta})) || \\leq \\red{\\epsilon_\\text{out}}$\n\\end{enumerate}\n\\pause\n\\item \\bblue{Inner} loop: compute $\\blue{\\xi_{jt}}(\\red{\\theta})$ given $\\red{\\theta}$\n\\begin{enumerate}\n\\item Solve system $s_j(x_t,p_t,\\blue{x_{it}};\\red{\\theta}) = S_{\\cdot t}$ by \\bblue{Berry} constraction:\n\\begin{equation*}\n\\xi_t^{h+1} = \\xi_t^{h} + \\log S_t - \\log s_j(x_t,p_t,\\blue{\\xi_{t}^h};\\red{\\theta})\n\\end{equation*}\n\\item Stop whenever $|| \\xi_{\\cdot t}^{h+1} - \\xi_{\\cdot t}^{h}  || \\leq \\red{\\epsilon_\\text{in}}$\n\\item Call resulting demand shock $\\blue{\\xi_{jt}}(\\red{\\theta},\\red{\\epsilon_\\text{in}})$\n\\end{enumerate}\n\\item Clearly, need to choose \\bred{both stopping rules} for inner and outer loop.\n\\end{midi}\n\\end{frame}\n\n\\begin{frame}{\\cite{knittel2014estimation}}\n\n\\begin{midi}\n\\item They perform an extensive investigation into BLP on two widely used datasets: cars and cereals.\n\\item They use 10 free solvers and 50 starting points for each.\n\\item Find: convergence occurs at several local extrema, saddles, and in regions where the FOC is not satisfied.\n\\item Resulting parameter estimates of economic variables (market shares, price elasticiteis) exhibit \\bred{huge} variation depending on solver/starting point.\n\\item All in all, they found 400 local solutions.\n\\end{midi}\n\\end{frame}\n\n\\begin{frame}{\\cite{dube2012improving}'s concerns}\n\\begin{mide}\n\\item Too much computation\n\\begin{itemize}\n\\item need to know $\\xi(\\theta)$ only at true $\\theta$.\n\\item NFXP solves for $\\xi(\\theta)$ at each stage.\n\\end{itemize}\n\\item Stopping criteria\n\\begin{itemize}\n\\item inner loop can be slow to converge\n\\item it's tempting to loosen $\\red{\\epsilon_\\text{in}}$ (often see $\\red{\\epsilon_\\text{in}}=1e^{-6}$ or higher!)\n\\item outer loop may not converge with loose inner criterion\n\\end{itemize}\n\\item Inner loop error propagates to outer loop.\n\\end{mide}\n\\end{frame}\n\n\\begin{frame}{Errors from loose stopping}\n\\begin{align*}\t\n\\theta^* = & \\arg \\max_{\\theta} Q(\\xi(\\theta,0)) \\\\\n\\hat{\\theta} = & \\arg \\max_{\\theta} Q(\\xi(\\theta,\\red{\\epsilon_\\text{in}})) \n\\end{align*}\t\n\\begin{midi}\n\\item \\cite{dube2012improving} derive bounds on the order of estimatin error as a function of $\\red{\\epsilon_\\text{in}}$\n\\item Consider \\cite{knittel2014estimation} for numerical experiments.\n\\end{midi}\n\\end{frame}\n\n\\begin{frame}{BLP as an MPEC}\n\\begin{midi}\n\\item \\cite{dube2012improving} cast this as an MPEC:\n\\begin{align*}\n\\min_{\\red{\\theta},\\blue{\\xi}} & \\blue{\\xi}^T ZWZ^T\\blue{\\xi} \\\\\n\\text{subject to } & s(\\blue{\\xi},\\red{\\theta}) = S\n\\end{align*}\n\\item Advantages:\n\\begin{enumerate}\n\\item No need to set up 2 tolerances\n\\item no inner errors propagated\n\\item easy to code in AMPL\n\\item fewer iterations, given that AMPL provides analytic gradients/hessian\n\\end{enumerate}\n\\end{midi}\n\\end{frame}\n\n\\begin{frame}{Exploring Sparsity in BLP}\n\\begin{midi}\n\\item The way this is formulated now, the Hessian of objective is dense. :-(\n\\item They add an additional variable $\\blue{r}$ and associated constraint $Z^T \\blue{\\xi}=\\blue{r}$\n\\begin{align*}\n\\min_{\\red{\\theta},\\blue{\\xi},\\blue{r}} & \\blue{r}^T W \\blue{r} \\\\\n\\text{subject to } & s(\\blue{\\xi},\\red{\\theta}) = S \\\\\n\\text{ and       } & Z^T \\blue{\\xi}=\\blue{r}\n\\end{align*}\n\\item advantages: \n\\begin{enumerate}\n\\item Hessian of objective function is now sparse\n\\item Very big saving in memory requirements.\n\\end{enumerate}\n\\end{midi}\n\\end{frame}\n\n\\begin{frame}{Convergence and Loose vs Tight}\n\\includegraphics[width=10cm]{dube-2.png}\n\n\\end{frame}\n\n\\begin{frame}{Speed}\n\\includegraphics[width=10cm]{dube-3.png}\n\n\\end{frame}\n\n\\begin{frame}[allowframebreaks]{References}\n\n        % \\frametitle{References}\n\t\t\\bibliographystyle{unsrtnat}\n\t\t\\bibliography{../../references/references.bib}\n\\end{frame}\n\n\n\\end{document}\n", "meta": {"hexsha": "965cf508e5adf1811a6b6d7b37c9666a0b61c89c", "size": 15228, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "TeX/dp-estimation.tex", "max_stars_repo_name": "snowdj/CoursePack", "max_stars_repo_head_hexsha": "f3ad25012167f580b9ea97aa7e84890986648837", "max_stars_repo_licenses": ["MIT-0"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2017-06-21T16:55:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-04T13:44:26.000Z", "max_issues_repo_path": "TeX/dp-estimation.tex", "max_issues_repo_name": "snowdj/CoursePack", "max_issues_repo_head_hexsha": "f3ad25012167f580b9ea97aa7e84890986648837", "max_issues_repo_licenses": ["MIT-0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-01-23T14:13:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-01T11:10:31.000Z", "max_forks_repo_path": "TeX/dp-estimation.tex", "max_forks_repo_name": "snowdj/CoursePack", "max_forks_repo_head_hexsha": "f3ad25012167f580b9ea97aa7e84890986648837", "max_forks_repo_licenses": ["MIT-0"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2017-02-24T12:23:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-03T07:25:38.000Z", "avg_line_length": 38.6497461929, "max_line_length": 277, "alphanum_fraction": 0.6923430523, "num_tokens": 5181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199008363969, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.33767675177399614}}
{"text": "\\documentclass[a4paper]{article}\n\n\\usepackage[english]{babel}\n\\usepackage[utf8]{inputenc}\n\\usepackage{times}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{graphicx}\n\\usepackage{subcaption}\n\\usepackage{float}\n\\usepackage[colorinlistoftodos]{todonotes}\n\\usepackage{hyperref}\n\\usepackage{listings}\n\n\\setlength{\\parskip}{\\baselineskip}%\n\\setlength{\\parindent}{0pt}%\n\\frenchspacing\n\n\\lstset{\n    frame=single,\n    basicstyle=\\footnotesize\\ttfamily\n}\n\n\\title{Experimental data transmission method using sound}\n\n\\author{FÁBIÁN Tamás László}\n\n\\date{\\today}\n\n\\begin{document}\n\\maketitle\n\n\\section{Introduction}\n\nA method for transmitting and receiving 20 bytes long data packets \nusing sound is described. The method uses continuous-phase multiple frequency-shift keying (CPFSK), and a robust synchronization method. A Reed-Solomon code is used for forward error correction.\n\nA software was written in the Python language for experimental and \ndemonstration purposes. Scripts are provided to send and receive short \ntext messages using the computer's audio devices, or to read/write the \naudio to/from data files. The files can be played back, or converted \ninto more traditional audio formats using sox\\cite{sox1}.\n\nA framework was established to gauge the performance of the software. A \nscript can generate random messages and save them into audio files with \nvarious levels of white noise. An other script then can be used to \nattempt decoding these files. Various statistics are shown after the \nscript finished decoding the files.\n\nExperiments show that this method can transmit data 99.9\\% accurately \nat a carrier to noise ratio (CNR) of -11dB (or at about 10dB \n$E_b/N_0$) measured over 22.05 KHz bandwidth, and with 83.4\\% accuracy \nat -12dB CNR (about 9dB $E_b/N_0$).\n\nIn real-world experiments using a small set of consumer-grade computer \naudio devices reliable data transfer could be achieved over 1 meter \nin a quiet room at quite low volume levels. Noisy environments mandate \nhigher volume setting and/or shorter distances. Interference due to \nmultipath propagation probably is the main performance bottleneck.\n\n\\section{Theory of Operation}\n\nI provide a summary on the operation of the software. See the in-line\ncode documentation for implementation details.\n\n\\subsection{Modulation}\n\nThe data has to be transmitted and received with equipments designed to\nproduce and record audio. Since little was known about the working\nenvironment, an Additive Gaussian White Noise (AGWN) channel was used\nas the channel model. In real life however, it is likely that noise\nbursts will occur frequently.\n\nAudio sampling rate was determined to be 44.1KHz. This sampling rate \nalong with 48KHz is the most frequently supported one, and 48KHz audio \ncan easily be downsampled on devices only supporting that.\n\nThe channel properties were chosen so that the transmitting device \ncould be a low-quality piezoelectric speaker. A carrier frequency of \nabout 4KHz, and a maximum bandwidth of also 4KHz was determined. The \nbandwidth were kept lower than the carrier frequency, to prevent \nharmonics interfering with the reception, so the transmitter can drive \nthe speaker with a square wave.\n\nUsing 44100 samples per second sampling rate, a 200 sample DFT will have\na bucket size of 220.5 Hz. To keep the modulation process simple, one\ntransmitted symbol will contain 4 bits, or half a byte of information.\nTo encode 4 bits, a symbol must communicate 16 separate states.\n\nThe modulation uses 17 frequencies in the form of $4410 + n*220.5$ Hz\nwhere $n \\in [0..16] \\cap \\mathbb{Z}$. About half of the time the\ncarrier ($n=0$) is transmitted, and no actual data is sent. This is for\nsynchronization. When this tone is off, one of the other 16 frequencies\n($n \\in [1..16] \\cup \\mathbb{Z}$) is transmitted, this is when data is\nactually being transmitted. So instead of 16 symbols, a 17 symbol\nalphabet is being used, out of which the carrier or zero symbol is used\nfor frame synchronization.\n\nThe carrier is turned on-off in a way so it can easily be found using \ncorrelation. The exact sequence of on-off states affect how easily it \nmay be spotted by correlating a potentially noisy and arbitrary \ntime-shifted signal with a known, clean synchronization sequence.\n\nGood sync sequences were found using gradient descent with random \nrestarts: essentially by checking random sequences, and looking for \nneighbors with increasingly better properties, until the process \nstuck in a local optimum, after which it is restarted from an other\nrandom vector.\n\nA total of 200 symbols are transmitted, out of those 108 are used to \ntransmit data, and 92 used for synchronization only. Transmitting one \nframe takes about 0.907 seconds. \\textbf{The effective bit rate is \n176.4bps.}\n\n\\subsection{Demodulation}\n\nDemodulation begins by recording a chunk of audio longer than a single\nframe. After normalizing the received data and correlating it with the\nsynchronization sequence, a decision is made whether there is a signal\npresent. The correlation will return the position where the sync signal\nmatches the audio the most.\n\nUsing the position information 108 DFTs at positions where the first\ntone is off. The received power in each bin is observed, and a hard\ndecision is made about what symbol the particular 200-sample audio data\nmight encode. Only the DFTs encoding the 108 data nibbles are kept.\n\n\\subsection{Forward Error Correction}\n\nA Reed-Solomon code RS(54,20) were chosen for forward error correction,\nmainly because implementations were readily available, and of course\nbecause of their good performance.\n\nThe error correcting code takes 20 byte payload, and produces a 54 byte\ncodeword. The code is capable of correcting 17 errors or 34 erasures.\nCurrently the software does not signal erasure towards the decoder,\nbut there are methods\\cite{ft1} for doing so.\n\n\\section{The Software}\n\nThis section describes how the software should be operated to run\ndemonstrations and experiments.\n\n\\subsection{Prerequisites}\n\nThe demonstration software requires a functional Python 3.6 \ninstallation, and a machine with enough resources. The following \nconfiguration \\textit{before} Python installation is recommended:\n\n\\begin{itemize}\n\\item Intel Core i5 processor, or better\n\\item 4GB RAM\n\\item 6GB of free disk space\n\\item Speakers\n\\item Microphone\n\\item Ubuntu Linux 17.04 or newer is recommended, a recent Windows or\nmacOS should also work\n\\end{itemize}\n\nIt is recommended to install a Python distribution called Anaconda\n\\cite{ana1}. Anaconda a contains stable and fast Python build along\nwith several important libraries.\n\n\\subsection{Installation}\n\nAnaconda 5.0.1 with Python 3.6 can be downloaded from:\n\n\\url{https://www.anaconda.com/download}.\n\nThere are installers for Linux, Windows and macOS operating system. Any \nof those systems should be able to run the demo software, but it had \nonly been tested throughly on Ubuntu Linux \"zesty\" 17.04.\n\nThe scripts \\texttt{send.py} and \\texttt{receive.py} use \n\\textit{pyaudio}, a Python binding for an audio library called \n\\textit{portaudio}. The portaudio library (.so, .dll, or .dynlib) and \nheader files need to be installed. The installation process differs \nacross operating systems, and can be as simple as issuing a command \n(Linux and maxOS), or having to install Visual Studio and compile the \nlibrary by hand (Windows)\\footnote{This is why the .dll-s and headers \nbundled with the pyaudio Python library for Windows}.\n\n\\subsubsection{Installation on Ubuntu Linux \"zesty\" 17.04}\n\nThe \\texttt{portaudio19-dev} package need to be installed with the \npackage manager \\texttt{apt}:\n\n\\begin{lstlisting}\n$ sudo apt install portaudio19-dev\n$ cd <path-to-demo-software>\n$ pip install -r requirements.txt\n\\end{lstlisting}\n\n\\subsubsection{Installation on Apple macOS}\n\nPortaudio need to be installed using \\texttt{brew}:\n\n\\begin{lstlisting}\n$ brew install portaudio\n$ cd <path-to-demo-software>\n$ pip install -r requirements.txt\n\\end{lstlisting}\n\n\\subsubsection{Installation on Microsoft Windows}\n\nOn Windows, the portaudio binaries are included in the pyaudio wheel, \nso separate installation should not be necessary (make sure \n\\texttt{pip} and \\texttt{python} are on the \\texttt{PATH}):\n\n\\begin{lstlisting}\nC:\\> cd <path-to-demo-software>\nC:\\> pip install -r requirements.txt\n\\end{lstlisting}\n\n\\subsection{Usage}\n\nThe scripts \\texttt{test-gen.py} and \\texttt{text-score.py} can \ngenerate a large set of audio files, and run a decoding benchmark on \nthem respectively. Any computer capable of running Python properly may \nbe used to run the benchmark. Since the process involves generating\n14000 files consuming about 1.2GB space, this should be done on a fast\nmachine.\n\nThe scripts \\texttt{send.py} and \\texttt{receive.py} use audio devices \nto play and record audio. They use the default system device, but they \ncan set up to use any device with the \\texttt{-d <number>} or \n\\texttt{--device <number>} parameter. Use \\texttt{devices.py} to view a \nlist of audio devices.\n\nAll command examples assume Linux operating system, but they should \nwork with no or only minor modifications on macOS and Windows too. \nCommands should be executed in the directory where the scripts are \nlocated.\n\n\\subsubsection{Listing audio devices}\n\nThe \\texttt{devices.py} script shows a list of audio devices available. \nOn some systems error messages may occur on the first few lines. These \ncan be ignored.\n\nSince \\texttt{send.py} and \\texttt{receive.py} are using the default \naudio device, this list will probably rarely be needed.\n\n\\newpage\n\n\\begin{lstlisting}\n$ ./devices.py \nALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear\nALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM\ncards.pcm.center_lfe\nALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side\nALSA lib pcm_route.c:867:(find_matching_chmap) Found no matching\nchannel map\n0 HDA Intel PCH: ALC898 Analog (hw:0,0)\n1 HDA Intel PCH: ALC898 Digital (hw:0,1)\n2 HDA Intel PCH: ALC898 Alt Analog (hw:0,2)\n3 USB Audio CODEC: - (hw:1,0)\n4 HDA NVidia: HDMI 0 (hw:2,3)\n5 HDA NVidia: HDMI 1 (hw:2,7)\n6 HDA NVidia: HDMI 2 (hw:2,8)\n7 HDA NVidia: HDMI 3 (hw:2,9)\n8 sysdefault\n9 front\n10 surround21\n11 surround40\n12 surround41\n13 surround50\n14 surround51\n15 surround71\n16 iec958\n17 spdif\n18 pulse\n19 dmix\n20 default\n$\n\\end{lstlisting}\n\n\\subsubsection{Sending or saving messages}\n\nThe \\texttt{send.py} script can send a message by playing the modulated\naudio carrier on an audio device, or saving and audio file.\n\nIn it's simplest form it's just called with a short text to send:\n\n\\begin{lstlisting}\n$ ./send.py test\nCNR (dB):    inf\nEb/N0 (dB):  inf\nPeak:        0.252437119188\n$\n\\end{lstlisting}\n\nThe command always displays the estimated carrier to noise power ratio \nand $E_b/N_0$ in decibels. Since there is no noise added by default, \nboth figures are displayed as being infinite.\n\nAdding noise, distortion and saving the audio into a file:\n\n\\begin{lstlisting}\n$ ./send.py -f test.s16 -c -11 -d 10000 test\nCNR (dB):    -11.0397105534\nEb/N0 (dB):  9.92938957672\nPeak:        0.742417642773\n$\n\\end{lstlisting}\n\nThe files store a single audio channel at a sampling rate of 44100 KHz.\nEach sample is a signed 16 bit little endian integer. The files contain\nno header or any kind of metadata.\n\nOne can specify a string of hexadecimal digits to send with the \n\\texttt{-x} or \\texttt{--hex} flag:\n\n\\begin{lstlisting}\n$ ./send.py -f test.s16 -c -11 -d 10000 -x \\\n  9d7133b7f07274a5be88a06f7b5ae2914822c008\n\nCNR (dB):    -11.0397105534\nEb/N0 (dB):  9.92938957672\nPeak:        0.742417642773\n$\n\\end{lstlisting}\n\nFor a brief description of usage and parameters, issue \n\\texttt{./send.py -h}.\n\n\\subsubsection{Receiving or loading messages}\n\nThe script \\texttt{receive.py} can be used to load audio files, or \ndecode audio read from an audio device in real-time. The test.s16 file \ncreated above can (very likely) be decoded with the following \ncommand:\n\n\\begin{lstlisting}\n$ ./receive.py -f test.s16 -x\nGot sync signal, decoding... \nDECODED: >>> 9d7133b7f07274a5be88a06f7b5ae2914822c008 <<<\nEnd of data stream reached, terminating\n$\n\\end{lstlisting}\n\nWithout the \\texttt{-f} parameter the script listens on the default \naudio device. The \\texttt{-x} flag is useful for printing arbitrary \nbinary data. Without this flag the script tries to convert the received \ndata to ASCII strings, and print that instead of hex digits. Call the \nscript with the \\texttt{-h} parameter to get a list of usable flags \nand parameters and their descriptions.\n\n\\subsubsection{Recording audio}\n\nA short script is provided for Linux using the SoX command \n\\texttt{rec}, and providing it with the necessary parameters, so only \nthe file name has to be given:\n\n\\begin{lstlisting}\n$ ./rec.sh test.s16\n\nInput File     : 'default' (alsa)\nChannels       : 1\nSample Rate    : 44100\nPrecision      : 16-bit\nSample Encoding: 16-bit Signed Integer PCM\n\nIn:0.00% 00:00:05.20 [00:00:00.00] Out:221k  [ -====|====- ]     Clip:0\nAborted.\n$\n\\end{lstlisting}\n\nThe recording can be stopped by hitting CTRL+C. It is worth keeping an \neye on the \"Clip\" indicator at the end of the last line. If this \ncounter starts growing then the audio level is too high.\n\n\\subsubsection{Playing saved audio}\n\nPlaying audio is also handled by SoX via a Linux shell script:\n\n\\begin{lstlisting}\n$ ./play.sh test.s16 \n\ntest.s16:\n\n File Size: 459k      Bit Rate: 706k\n  Encoding: Signed PCM    \n  Channels: 1 @ 16-bit   \nSamplerate: 44100Hz      \nReplaygain: off         \n  Duration: 00:00:05.20  \n\nIn:100%  00:00:05.20 [00:00:00.00] Out:229k  [      |      ]     Clip:0    \nDone.\n$\n\\end{lstlisting}\n\n\\subsubsection{Generating test files}\n\nThe test set generator script will generate one thousand random test \nfiles for each CNR level. The tested levels are between and including\n-14dB and -1 dB.\n\nThe \\texttt{test-gen.py} script accepts no arguments, and calling it \nwill start generating test files right away:\n\n\\begin{lstlisting}\n$ ./test-gen.py \n  0%|                              | 5/14000 [00:01<1:06:18,  3.52it/s]\n$\n\\end{lstlisting}\n\nDuring test set generation a progress bar with the speed and ETA is \ndisplayed. Before generating a test set, make sure the \\texttt{data} \ndirectory only contains a \\texttt{.gitignore} file, and no *.s16 audio \nfiles. These are not removed automatically, and new files will have\ndifferent names every time.\n\nEvery file is exactly 1 second, or 44100 samples -- 88200 bytes -- \nlong. The signal is right in the middle of every file at offset 2050.\n\n\\subsubsection{Scoring performance on a test file set}\n\nThe \\texttt{test-score.py} script will read any .s16 files from the \ndata directory and will attempt to demodulate and decode them. It will \nrecord any success or failure in finding the synchronization signal or \ndecoding the actual message.\n\nBefore exiting, the script will print out a rather dense representation \nof the results. It looks like this:\n\n\\begin{lstlisting}\nFILES:         {-5: 1000, -3: 1000, -4: 1000, -14: 1000, ...\nGOOD DECODES:  {-5: 1000, -3: 1000, -4: 1000, -12: 834, ...\nNO DECODES:    {-14: 1000, -13: 897, -12: 166, -11: 1}\nBAD DECODES:   {}\nGOOD SYNCS:    {-5: 1000, -3: 1000, -4: 1000, -14: 980, ...\nBAD SYNCS:     {-13: 10, -14: 20, -12: 1, -11: 1}\nBAD SYNC SET:  {2040, 2060}\n\\end{lstlisting}\n\nEach line shows a metric. The number before the colons are specific CNR \nvalues, the number after the colons are the number of occurrences.\n\nFor example the ,,FILES'' line shows the number of files. It can be \nseen that for the CNR level of -5(dB) there were ,,1000'' files in the \ndata directory.\n\nIt can also be seen that for levels -5, -3 and -4 ever file was decoded \nOK, and only 834 ,,GOOD DECODES'' were possible at CNR level -12.\n\n,,NO DECODES'' counts files that could not be decoded at all, ,,BAD \nDECODES'' count files that could be decoded, but the results were \ndifferent from the originally encoded data. ,,GOOD SYNCS'' show the \nnumber of files where the synchronization signal could be recovered \nwith utmost precision. ,,BAD SYNCS'' counts ill-identified sync \nvectors. ,,BAD SYNC SET'' shows all the offsets where a sync vector was \nfound, except the correct 2050 offset.\n\n\\subsubsection{Generating synchronization vectors}\n\nThe synchronization vector has to have a special property: it must have \nlow aperiodic autocorrelation. Such vectors are rare, and long vectors \nare hard to find. The script \\texttt{syncvec-search.py} tries to find \nsuch vectors using gradient descent with random restarts. This script \nwas used design/development time, and can be used again if (when) \nchanging the modulation becomes necessary.\n\n\\subsubsection{Observing saved audio waveforms and spectra}\n\nA script named \\texttt{scope.py} is provided for graphically displaying \nwaveforms stored in s16 files. The script accepts a file name as a \nsingle mandatory positional parameter, and various flags that control \nwhat should be displayed. By default a simple waveform is displayed.\n\nThe following flags are available:\n\n\\begin{description}\n\\item[\\texttt{-h}] Show help and exit.\n\\item[\\texttt{-s}] Show spectrum.\n\\item[\\texttt{-c}] Show correlation vector.\n\\item[\\texttt{-w}] Show waterfall.\n\\item[\\texttt{-o}] Offset: skip this many samples.\n\\item[\\texttt{-y}] Synchronize: try to find a packet, cut it out, and.\n  display only that\n\\end{description}\n\nSome examples follow showing clean and noisy signals.\n\n\\begin{lstlisting}\n$ ./scope.py clean.s16\n...\n$ ./scope.py noisy.s16\n...\n\\end{lstlisting}\n\n\\begin{figure}[H]\n    \\centering\n    \\begin{subfigure}[b]{0.45\\textwidth}\n        \\includegraphics[width=\\textwidth]{scope_clean.png}\n        \\caption{Clean waveform}\n    \\end{subfigure}\n    \\begin{subfigure}[b]{0.45\\textwidth}\n        \\includegraphics[width=\\textwidth]{scope_noisy.png}\n        \\caption{Noisy waveform}\n    \\end{subfigure}\n\\end{figure}\n\n\\begin{lstlisting}\n$ ./scope.py -s clean.s16\n...\n$ ./scope.py -s noisy.s16\n...\n\\end{lstlisting}\n\n\\begin{figure}[H]\n    \\centering\n    \\begin{subfigure}[b]{0.45\\textwidth}\n        \\includegraphics[width=1\\textwidth]{dft_clean.png}\n        \\caption{Clean DFT}\n    \\end{subfigure}\n    \\begin{subfigure}[b]{0.45\\textwidth}\n        \\includegraphics[width=1\\textwidth]{dft_noisy.png}\n        \\caption{Noisy DFT}\n    \\end{subfigure}\n\\end{figure}\n\n\\begin{lstlisting}\n$ ./scope.py -c clean.s16\n...\n$ ./scope.py -c noisy.s16\n...\n\\end{lstlisting}\n\n\\begin{figure}[H]\n    \\centering\n    \\begin{subfigure}[b]{0.45\\textwidth}\n        \\includegraphics[width=1\\textwidth]{correlation_clean.png}\n        \\caption{Correlation vector, clean signal}\n    \\end{subfigure}\n    \\begin{subfigure}[b]{0.45\\textwidth}\n        \\includegraphics[width=1\\textwidth]{correlation_noisy.png}\n        \\caption{Correlation vector, noisy signal}\n    \\end{subfigure}\n\\end{figure}\n\n\\begin{lstlisting}\n$ ./scope.py -y -w clean.s16\n...\n$ ./scope.py -y -w noisy.s16\n...\n\\end{lstlisting}\n\n\\begin{figure}[H]\n    \\centering\n    \\begin{subfigure}[b]{0.45\\textwidth}\n        \\includegraphics[width=1\\textwidth]{waterfall_sync_clean.png}\n        \\caption{Clean signal, synchronized}\n    \\end{subfigure}\n    \\begin{subfigure}[b]{0.45\\textwidth}\n        \\includegraphics[width=1\\textwidth]{waterfall_sync_noisy.png}\n        \\caption{Noisy signal, synchronized}\n    \\end{subfigure}\n\\end{figure}\n\n\\section{Experimental results}\n\nA large number of simulations, and some real-world experiments were\nconducted. These are described below.\n\n\\subsection{Real-World Experiments}\n\nReal-world experiments in the given time frame could only yield a\nmodest number of data points. The following description focuses more on\nusability and other practical aspects, and does not try to communicate\nprecise figures.\n\n\\subsubsection{Single PC setup}\n\nA single desktop personal computer with a high quality speaker and \nmicrophone were used to test performance at the early stages of \ndevelopment.\n\n\\textbf{With this setup I could easily achieve reliable data transfer \nat distances slightly over 1 meter even when music played, or people \nwere talking if the microphone and speaker were facing each other.}\n\nPerformance was heavily dependent on the microphone setup and volume \nsetting. Too high volume causes clipping and destroys the signal, to \nlow volume hides the signal in the noise of the recording equipment. If \nthe microphone were facing in a direction other than the speaker, \n\\emph{multipath propagation} was found to interfere with reception.\n\n\\subsubsection{Single notebook setup}\n\nA single laptop computer was used to try and replicate the results. The \nnotebook had a built-in microphone with lots of noise, since it was \nequipped with forced air cooling, and the fan was on most of the time.\n\nThe built-in microphone and the speaker were about 12cm close together. \nThe received signals weren't as high quality as with the PC setup. This \nwas due not to the distance, but to the fact that the speakers and the \nmicrophone were deliberately placed and insulated so that the audio \nfeedback is as little as possible.\n\nThe microphone in this setup faces away from the speakers, and picks \nother sounds up easily, including the sound of the speakers bouncing\noff objects, and arriving from the front. Because of this, the signal\ngets back to the receiver multiple times with some delay.\nThis can easily confuse the demodulator.\n\n\\subsubsection{Notebook-PC setup}\n\nTo rule out any problem with the laptop's microphone and audio \ncircuitry, several experiments were conducted with the PC set being the \ntransmitter, and it being the receiver.\n\nA performance similar to the PC-only setup were measured: signals could \neasily be picked up from about 1 meter even when the laptop's fan were \non, or when some music or noise could be heard in the room. The\nexperiments were repeated with reversed roles, and performance remained\nsimilar.\n\n\\subsubsection{Conclusions}\n\nExperiments showed that the software worked beyond expectations, but also\nrevealed performance bottlenecks. The sensitivity to multipath in\nparticular needs to be addressed. Ambient noise will of course interfere\nwith the reception, but the volume of the transmitted signal could always\nbe set high enough to ensure success, and not be particularly annoying\n(although this is highly subjective, and should carefully be considered\nwhile developing the product). Multipath in contrast mostly dependent on\nthe paths, and not the volume, so increasing volume it has little\nbenefit in combating multipath.\n\n\\subsection{Benchmarks}\n\nUsing the \\texttt{test-gen.py} script, 14000 audio files were \ngenerated, from and including -14dB CNR to and including -1dB CNR. The \nfiles contained randomly generated binary data. All the files were \nexactly 1 second long, and every file had the encoded data right in the \nmiddle, at offset 2050. The decoding benchmark does not ,,know'' about \nthis convention, and has to guess the position correctly in every file.\n\n\\textbf{It was found the decoding is possible 99.9\\% of the time at \n-11dB CNR under 22.05 KHz band-limited white noise.} Performance were \nquickly falling under that: about 83.4\\% good decodes were logged at \n-12dB, and none at -13db.\n\n\\textbf{It is also worth mentioning that no false decodes were ever\nobserved. The messages either decoded correctly, or didn't at all.}\n\nThe synchronization method was found out to have been a very good \nchoice, might even have been an overkill. \\textbf{In the vast majority\nof the cases, the positions of the data frames were precisely \nidentified, even in cases where decoding was impossible.} Even when the\nalgorithm made errors finding frames, it only missed 10 samples in \neither direction, so instead of one, only 3 positions were ever \nidentified. This is a useful property, and worth noting it in case the\nsynchronization precision would need to be improved for some reason.\n\n\\section{Implementation Challenges, Possible Improvements}\n\nThe work I've done on this project so far is rather experimental. The \nfinished product has to work in different environments, with various\nnoise sources, and a large variety of devices with different\nproperties.\n\nI hereby attempt to address a few problems that might come up during \nthe deployment of this -- or similar -- solution.\n\n\\subsection{Parameters, Tuning}\n\nThe performance of the components of the system is not well balanced.\nThe synchronization works very well, but also takes about the half of\nthe bandwidth away. It's possible to make a trade-off between the\neffectiveness of the synchronization algorithm and the bandwidth it\nuses. Bandwidth then can be used to increase symbol time and combat\nnoise and multipath, and/or to decrease code rate, and have more\nimmunity to momentarily signal dropout and similar burst errors.\n\nThere is a trade-off between the code rate and the symbol time even when\nwe consider the sync vector to be constant. A longer symbol time and\nhigher code rate might provide better white noise and multipath\nimmunity. The possible set of parameters can be explored automatically\nwith machine learning algorithms, similarly to how good synchronization\nvectors were found in the first place.\n\n\\subsection{Processing power}\n\nIn the current form, the software consumes quite a lot of CPU. The\nimplementation of the decoding algorithm must be chosen carefully, and\nwell-optimized native code will probably be needed for acceptable\nperformance.\n\n\\subsection{Channel model}\n\nThe simulations use a simple Additive Gaussian White Noise channel.\nReal-world noise will very likely to be different. Any further\ndevelopment would benefit from a noise model that is more faithful to\nthe environments in which the solution will be deployed.\n\n\\subsection{Choice of FEC, Implementation, Performance}\n\nThe Franke-Taylor algorithm\\cite{ft1} can be adapted for RS(54,20).\nThis could provide as much as 2dB improvement over the hard-decision\nalgebraic decoding that were used in the software.\n\nOther modern codes, like LDPC codes could be used instead of\nReed-Solomon codes. Because the lack of ready-to-use implementations,\nusing such codes was not attempted.\n\n\\subsection{Multipath}\n\nCurrently this is one of the major factors that limit the performance \nof this solution. It can confuse the receiver even when noise and\ndistance are not problems. It is also not obvious what is happening,\nand multipath can cause seemingly random, frustrating packet loss.\n\nOn the following waterfall charts a clean and a multipath-affected\nsignal can be seen:\n\n\\begin{figure}[H]\n    \\centering\n    \\begin{subfigure}{0.45\\textwidth}\n        \\includegraphics[width=\\textwidth]{waterfall_sync_clean.png}\n        \\caption{Clean signal}\n    \\end{subfigure}\n    \\begin{subfigure}{0.45\\textwidth}\n        \\includegraphics[width=1\\textwidth]{waterfall_sync_multipath.png}\n        \\caption{Multipath-affected signal}\n    \\end{subfigure}\n\\end{figure}\n\nNotice how the power creeps from one symbol to the next few one, and\nblur the image, making correct demodulation impossible. This signal\ncannot be decoded, despite having no significant noise in it.\n\nThe next images show correlation vectors of the same signals. The\ncorrelation vector contains information about the position of the\nreceived frame. The clean signal has a sharp, single spike with small\nside lobes, whereas the multipath-affected signal has multiple large\nbumps near the main spike that also looks flattened. This is a sign of\nmultiple synchronization vectors in the same audio. During the\nexperiment only one transmitter was used, so these must be different\ncopies of the very same signal bouncing around the room, and getting\nback into the microphone.\n\n\\begin{figure}[H]\n    \\centering\n    \\begin{subfigure}{0.45\\textwidth}\n        \\includegraphics[width=1\\textwidth]{correlation_clean.png}\n        \\caption{Correlation vector of a reasonably clean signal}\n    \\end{subfigure}\n    \\begin{subfigure}{0.45\\textwidth}\n        \\includegraphics[width=1\\textwidth]{correlation_multipath.png}\n        \\caption{Correlation vector of a signal affected by multipath}\n    \\end{subfigure}\n\\end{figure}\n\nThis problem were almost only encountered when the transmitting speaker\nand the receiving microphone weren't facing each other. Microphones and\nspeakers tend to be directional \\emph{by design}. If they are facing\neach other, they amplify the signal, and signals coming from other\ndirections are attenuated. If they are facing away each other, stray\nsignals are amplified, and the original one gets attenuated.\n\nThis phenomenon can be mitigated by increasing the symbol time, and\neven by introducing guard intervals. This decreases symbol rate, and\nmakes synchronization harder. Using frequency hopping spread spectrum\n(FHSS) is an other effective way to combat this issue.\n\n\\textbf{To tackle this problem efficiently, more information on the\ntransmitting equipment and the working environments is needed, because\nthe carrier frequency, bandwidth, noise, and multipath models need to be\ngotten right for the design of the system to be optimal.}\n\n\\begin{thebibliography}{9}\n\\bibitem{sox1}\n  SoX, \\url{http://sox.sourceforge.net/}\n\\bibitem{ana1}\n  Anaconda, \\url{https://www.anaconda.com/download}\n\\bibitem{ft1}\n  Steven J. Franke, K9AN and Joseph H. Taylor, K1JT\n  \\emph{Open Source Soft-Decision Decoder for the JT65 (63,12) Reed-Solomon\n  Code}, QEX, 2016\n\\end{thebibliography}\n\n\n\\end{document}\n", "meta": {"hexsha": "8115985f3f44009e0fd9151f9d380a309b10ee42", "size": 29352, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/report.tex", "max_stars_repo_name": "netom/airpacket", "max_stars_repo_head_hexsha": "d3f55dfe69bf30b2d5bf1b19a8ad47be75934f7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/report.tex", "max_issues_repo_name": "netom/airpacket", "max_issues_repo_head_hexsha": "d3f55dfe69bf30b2d5bf1b19a8ad47be75934f7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/report.tex", "max_forks_repo_name": "netom/airpacket", "max_forks_repo_head_hexsha": "d3f55dfe69bf30b2d5bf1b19a8ad47be75934f7c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2960609911, "max_line_length": 194, "alphanum_fraction": 0.7688402835, "num_tokens": 7417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.337616183459178}}
{"text": "%\\documentclass[aps,epsf,rotate,preprint]{revtex}\n%\\documentstyle[aps,epsf,rotate,preprint,graphics]{revtex}\n\\documentstyle[aps,epsf,rotate,multicol]{revtex}\n%\\documentstyle[aps]{revtex}\n\n\\newcommand{\\sigmabf}{\\text{\\boldmath$\\sigma$}}\n\\newcommand{\\Sigmasf}{{\\mathsf\\Sigma}}\n\\newcommand{\\nablabf}{\\text{\\boldmath$\\nabla$}}\n\\newcommand{\\lambdabf}{\\text{\\boldmath$\\lambda$}}\n\\newcommand{\\dbf}{\\text{\\boldmath$d$}}\n\\newcommand{\\iu}{\\underline{i}}\n\\newcommand{\\ju}{\\underline{j}}\n\\newcommand{\\be}{\\begin{equation}}\n\\newcommand{\\ee}{\\end{equation}}\n\\newcommand{\\ddx}{d^d\\! x\\,}\n\n\\begin{document}\n\n\\draft\n\n\\title{Self-Consistent Effective-Medium Approximations with Path Integrals}\n\n\\author{Yves-Patrick Pellegrini$^1$ and Marc Barth\\'el\\'emy$^{1,2}$}\n\n\\address{ $^1$ Service de Physique de la Mati\\`ere Condens\\'ee, \\\\\n\t\tCommissariat \\`a l'Energie Atomique,\\\\\n\t\tBP12, 91680 Bruy\\`eres-le-Ch\\^atel, France.\\\\\n\t  $^2$ Center for Polymer Studies and Dept. of Physics,\n\t\tBoston University, Boston, MA 02215.}\n\n\\date{Last modified: December 9, 1999. Printed: \\today\\\\\nTo be published in Physical Review E.}\n\n\\maketitle\n\n\\begin{abstract}\nWe study effective-medium approximations for linear composite media\nby means of a path integral formalism with replicas. \nWe show how to recover the Bruggeman\nand Hori-Yonezawa effective-medium formulas. \nUsing a replica-coupling ansatz, \nthese formulas are extended into new ones\nwhich have the same percolation thresholds as that of the Bethe \nlattice and Potts model of percolation, \nand critical exponents $s=0$\nand $t=2$ in any space dimension $d\\geq 2$. \nLike the Bruggeman and Hori-Yonezawa formulas, the new formulas \nare exact to second order in the weak-contrast and dilute limits. \nThe dimensional range of validity of the four effective-medium \nformulas is discussed, and it is argued that the new ones are \nof better relevance than the classical ones in dimensions $d=3,4$ \nfor systems obeying the Nodes-Links-Blobs picture, such as \nrandom-resistor networks.\n\\end{abstract}\n\n\\vskip 1cm\n\\pacs{PACS numbers: 05.10.-a, 05.40.-a, 05.50.+q, 72.70.+m }\n\n%\\begin{multicols}{2}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Introduction}\nAmong various effective-medium formulas used to model the effective\nbehavior of random conducting linear composites, the symmetrical\nBruggeman formula \\cite{BRUG35,LAND52} is undoubtly the most\npopular. Applied to an insulator/conductor binary mixture, it predicts\na percolation-like transition \\cite{KIRK71,CLER90,STAU92,SAHI98} for a\nvolumic fraction of conductor $p_c=1/d$, where $d$ is the space\ndimension. The critical exponents are $s=t=1$, and its critical properties\nare thoroughly discussed in Ref.\\ \\cite{CLER90}. This formula can be\ninterpreted in two ways. On one hand, Milton has shown \\cite{MILT85} that it\nyields the exact effective conductivity of an {\\it ad hoc} ideal medium\nbuilt with a particular hierarchical structure. On the other hand, the\nBruggeman formula can be seen as a first (one-body) self-consistent\napproximation to general disordered symmetric cell-materials\n\\cite{MILL69}, to which systematic corrections could be worked\nout. However, the Bruggeman approximation is very different from a\nmean-field theory of random conducting media. Indeed, an exact\nmean-field calculation on the Bethe lattice \\cite{STIN73,STRA74} predicts a\npercolation threshold $p_c\\sim 1/(2d)$ and exponents $s=0$ and\n$t=3$. These exponents are exact for $d\\geq 6$, as well as the\nasymptotic behavior of the threshold when $d\\to\\infty$ (at least, for\nthe hypercubic lattice \\cite{STAU92} to which a continuum theory\nnaturally compares \\cite{NOTE1}). These values are also obtained in a\nmore systematic mean-field theory for random resistor networks\n\\cite{STEP77}.\nThe remarkable discrepancy between the mean-field results and\nBruggeman's formula indicates the ambiguous status of the Bruggeman\ntheory. As a matter of fact, in spite of various (mostly perturbative)\ninvestigations \\cite{HORI75,BERG81,LUCK91} in order to precise its\ntheoretical status, the reasons for the peculiar critical behavior of\nBruggeman's formula are not completely cleared up. \nMore surprisingly, another\nself-consistent effective-medium approximation \\cite{HORI75,HORI77} due\nto Hori and Yonezawa (HY), obtained for the same type of media by means\nof a completely different approximation scheme (and later derived by\nfunctional methods \\cite{BART93}), exhibits the same exponents $s=t=1$\nand a similar threshold behavior $p_c=1-\\exp(-1/d)\\sim 1/d$.\n\nApart from phenomelogical variants, and up to our knowledge,\nthe Bruggeman and HY effective-medium formulas are\nthe only ones obtained from the equations of\nelectrostatics in continuous media which are able to describe, at least\nqualitatively, the overall features of a percolation transition in any\ndimension. One intriguing question concerns the possibility of deriving\nalternative effective-medium formulas from a continuum formulation, which\ndo not lead to the seemingly unavoidable values $s=t=1$ and $p_c\\sim\n1/d$. As we show in this paper, such a possibility exists. Our starting\npoint is the path integral approach recently put forward by\nBarth\\'el\\'emy and Orland\\cite{BART98}, where the effective-medium\nproblem is recast in a functional form. The problem reduces to\ncompute a free-energy: roughly, the logarithm, averaged over the\ndisorder, of a functional integral of Boltzmann-like weights, over\nallowed field configurations (which include boundary conditions). The\naverage of the logarithm is carried out with the replica method (already\nused in Ref.\\ \\cite{STEP77}). In Ref.\\ \\cite{BART98}, the authors showed\nthat the path integral formulation \nallows one to easily recover the second-order\nweak-disorder expansion of the effective permittivity of nonlinear\ncomposites \\cite{BLUM91}.\n\nHowever, this formulation\nhas not yet been used to derive self-consistent estimates.\nIn this paper, we show how this can be done. \nAfter a presentation of the functional approach to the homogeneization \nproblem, and of the replica method (Sec.\\ \\ref{pifotp}), \nwe discuss self-consistent effective-medium \napproximations (Sec.\\ \\ref{posa}). As usual\nin such approximations, a background reference medium is introduced under the\nform of an ansatz for the energy of the system, \nwhose parameters are to be\ndetermined self-consistently (Sec.\\ \\ref{o}). \nThe new feature here is that the ansatz\ncontains a replica-coupling term, whose significance is\nexplained (Sec.\\ \\ref{rcacota}). \nThe self-consistency conditions to determine its parameters \nare next discussed,\nand two types of effective-medium formulas are identified (Sec.\\ \\ref{sc}):\none in which the replica couplings are cancelled\n(hereafter referred to as ``type 1''), \nand the other one with non-zero replica couplings (``type 2'').\nTwo different approximations are then worked out for each type \n(Sec.\\ \\ref{tm}). It is found that \ntype 1 generates the Bruggeman and HY formulas, \nwhereas type 2 brings in two new effective-medium formulas which \nare ``replica coupling counterparts'' of the previous ones. \nThey possess exponents $s=0$, $t=2$, and \na threshold $p_c\\sim 1/(2d)$ (Sec.\\ \\ref{nef}).\nThese new formulas are discussed in Sec.\\ \\ref{d}, \nwhere numerical results are presented\nbefore we conclude in Sec.\\ \\ref{c}.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Path integral formulation of the problem}\n\\label{pifotp}\nThe effective properties of a random \nconducting medium can be defined with the help of the\ntotal dissipated power in the medium\\cite{WILL86,SANC87,PONT92b}. \nIn terms of the electric field\n$E(x)$, the dissipated power $w$ in the system of volume $V$ reads\n\\begin{equation}\nW[E]=\\int_V dx\\,w_x\\bigl(E(x)\\bigr), \n\\end{equation}\nwhere $w_x$ is the local power density.\n\n{\\em Hereafter, we take the volume $V$ of the sample equal to one}. In\nheterogeneous materials, $w_x$ depends on constitutive\nparameters randomly varying from point to point. For linear conducting\nmedia with $j(x)=\\sigma(x)E(x)$, where $\\sigma$ is the local random\nconductivity and $j$ is the electric current, we have\n\\begin{equation}\n\\label{linmed}\nw_x\\bigl(E(x)\\bigr)=\\sigma(x)E^2(x)/2.\n\\end{equation}\nIn the analogous effective\npermittivity problem the dissipated power is replaced by the stored\nenergy $\\varepsilon(x)E^2(x)/2$ ($\\varepsilon$ is the\npermittivity). For this reason, we shall abusively refer to $w_x$ as\nthe ``energy density'' hereafter. In the nonlinear problem, $w_x(E)$\nis a non-quadratic function of $E$.\n\nAn alternative to solving Maxwell's equations is to minimize the total\nenergy $W$ subjected to the two constraints \\cite{WILL86,SANC87}: (i) $E=- \\nabla\\phi$ and \n(ii) $\\overline{E}=E_0$; here, the bar stands for a spatial average, \nand $E_0$ is a constant applied electric field. The \nminimum, $W^*\\bigl(E_0\\bigr)$, is expected to be self-averaging, as\noccurs for the free-energy in disordered systems. We can therefore write\n\\begin{equation}\n\\label{mini}\nW^*(E_0)=\\left\\langle\\mathop{\\text{min}}_{\\overline{E}\n=E_0 \\atop{E=-\\nabla\\phi}} W[E]\\right\\rangle\n\\end{equation}\nwhere the brackets $\\langle\\cdot\\rangle$ denote the disorder average. \n$W^*(E_0)$ is the energy in a homogeneous medium \ncharacterized by an effective\nconstitutive law \\cite{WILL86}\n\\begin{equation}\n\\label{constef}\n\\left\\langle j\\right\\rangle={\\partial W^*(E_0)\\over \\partial\nE_0}=\\sigma_{\\text{eff}} E_0.\n\\end{equation}\nThe second equality defines the effective conductivity of the medium.\n\nThe problem thus reduces to computing the average of\nthe constrained minimum of a functional of the electric field. The\nelectric field derives from a potential and has a fixed mean value. We\ncan rewrite the constrained minimum in (\\ref{mini}) using a path\nintegral\n\\begin{equation}\n\\mathop{\\text{min}}_{\\overline{E}=E_0\\atop{E=-\\nabla\\phi}}\nW[E]=-\\lim_{\\beta\\rightarrow\\infty}\n\\frac{1}{\\beta}\\mathop{\\text{ln}}\n\\int{\\cal D}E\\,{\\cal D}\\phi\\,\n\\delta(E+\\nabla\\phi)\n\\delta(\\overline{E}-E_0)\ne^{-\\beta W[E]}.\n\\end{equation}\nThe minimum can be interpreted as the ground state energy\nassociated to the partition function\n\\be\n\\label{ZZ}\nZ=\\int \\tilde{\\cal D}E\\,\ne^{-\\beta W[E]},\n\\end{equation}\nwhere we have used the shorthand notation\n\\begin{equation}\n\\tilde{\\cal D}E={\\cal D}E\\,\\delta(\\overline{E}-E_0)\\int {\\cal D}\\phi\\,\n\\delta(E+\\nabla\\phi) \n\\end{equation}\nfor the constrained functional measure. \nWe need to compute the average of the logarithm of (\\ref{ZZ}).  In order\nto proceed, we introduce replicas \\cite{EDWA75,MEZA87} and use the identity\n$\\left\\langle\\ln Z\\right\\rangle=\n\\lim_{n\\rightarrow 0}(\\left\\langle Z^n\\right\\rangle-1)/n$, hence\n\\begin{equation}\n\\label{wstar0}\nW^*=-\\lim_{\\beta\\rightarrow\\infty}\n\\lim_{n\\rightarrow 0}\n\\frac{1}{n\\beta}\n(\\left\\langle Z^n\\right\\rangle-1).\n\\end{equation}\nThe limits do not commute. The equivalent form\n\\begin{equation}\n\\label{wstar}\nW^*=-\\lim_{\\beta\\rightarrow\\infty}\\lim_{n\\rightarrow\n0}\\frac{1}{n\\beta}\\ln\\left\\langle Z^n\\right\\rangle\n\\end{equation}\ncan be used as well. The replica method \nrelies on the fact that one can easily compute\nthe replicated partition function \n$\\langle Z^n\\rangle$ for $n$ integer, and subsequently take the limit\n$n\\rightarrow 0$. The main quantity of interest therefore is\n\\be\n\\left\\langle Z^n\\right\\rangle=\n\\int\\prod_{\\alpha=1}^{n}\n\\tilde{\\cal D}E^{\\alpha}\\,\\left\\langle\ne^{-\\beta \\sum_{\\alpha=1}^{n} W[E^{\\alpha}]}\n\\right\\rangle.\n\\end{equation}\nDenoting the replicated measure by \n$\\tilde{\\cal D}\\bigl(E^\\alpha\\bigr)=\\prod_{\\alpha=1}^{n}\n\\tilde{\\cal D}E^{\\alpha}$, the average $\\langle Z^n\\rangle$ can be written \nin terms of an ``effective Hamiltonian''\n\\be\n\\label{zneff}\n\\langle Z^n\\rangle=\n\\int\\tilde{\\cal D}\\bigl(E^\\alpha\\bigr)\\, e^{-\\beta{\\cal H}_e},\n\\ee\nwith\n\\begin{equation}\n\\label{heff}\n{\\cal H}_e=-{1\\over\\beta}\\ln\\left\\langle e^{-\\beta\\sum_{\\alpha=1}^{n}\nW[E^{\\alpha}]}\n\\right\\rangle.\n\\end{equation}\n\nFor simplicity, we restrict ourselves to cell materials where the local\nproperties are statistically uncorrelated from site to site. Volume\nintegrals may then to be identified with sums over sites (each\npertaining to one cell) according to the correspondence $\\int\ndx\\leftrightarrow v\\sum_x$, where $v$ is an infinitesimal cell volume\n(which defines the microscopic correlation length of the\nproblem). Then, ${\\cal H}_e$ simplifies to\n\\begin{equation}\n\\label{calf}\n{\\cal H}_e=-{1\\over\\beta}\\int\\frac{dx}{v} \\ln\\left\\langle \ne^{-\\beta v\\sum_\\alpha w_x\\bigl(E^\\alpha(x)\\bigr)}\\right\\rangle.\n\\end{equation}\n\nNote that our discussion in Sec.\\ III will be specialized to binary\ndisorder for which the constitutive parameters can take only two\nvalues (but the proofs are general). That is, we assume that the\nlocal energy density is distributed according to the probability\ndistribution\n\\be\nP\\bigl(w=w_x(E)\\bigr)=p\\delta \\bigl(w-w_1(E)\\bigr)+\nq\\delta \\bigl(w-w_2(E)\\bigr). \n\\ee \n(where $q=1-p$). With this choice, \n\\be\n\\label{znmoyen}\n{\\cal H}_e=-{1\\over\\beta}\\int\\frac{dx}{v} \\ln\n\\left[p e^{-\\beta v\\sum_{\\alpha=1}^n w_1\\left(E^{\\alpha}(x)\\right)}\n+qe^{-\\beta v \\sum_{\\alpha=1}^n w_2\\left(E^{\\alpha}(x)\\right)}\\right].\n\\end{equation}\nThe above formalism applies to any form of the energy density, and in\nparticular to nonlinear media \\cite{BERG92,PONT92a,YU94,PONT97}. \nA method for extracting from the path integral the second-order \nweak-contrast perturbation expansion of the effective potential \n$W^*(E_0)$, for nonlinear media, has been introduced in Ref.\\ \\cite{BART98}. \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Principle of self-consistent approximations}\n\\label{posa}\nIn this paper, we consider the linear problem only. This section is devoted to self-consistent approximations to $W^*$. We first present\nthe principle for building such approximations through the \nintroduction of a trial Hamiltonian. Then, we \ndiscuss the choice of a trial Hamiltonian with replica couplings. \nFinally, we explain how to exploit these replica couplings \nin order to obtain two kinds of self-consistent formulas.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Overview}\n\\label{o}\n The common ingredient to the approximations discussed\nbelow is the introduction of a linear comparison medium\ndescribed by a trial Hamiltonian ${\\cal H}_0$ which is quadratic in the\nelectric field and non-random, e.g.\\ the one-parameter ansatz\n\\begin{equation}\n\\label{trybrug}\n{\\cal H}_0=\\frac{\\sigma_0}{2}\\int dx\\,\\sum_{\\alpha}{E^{\\alpha}}^2(x),\n\\end{equation}\nwhere $\\sigma_0>0$ is to be determined by an \nappropriate self-consistency condition. \nThis Hamiltonian is that of a (replicated) homogeneous medium, \nbut without couplings between replicas. Its meaning and that of \nother possible choices with replica couplings are discussed below.\n\nThe partition function $\\langle Z^n\\rangle$ can be rewritten as\n\\begin{equation}\n\\left\\langle Z^n\\right\\rangle =\n\\frac{\n\\int{\\tilde{\\cal D}}\\bigl(E^{\\alpha}\\bigr)\\, e^{-\\beta({\\cal\nH}_e-{\\cal H}_0)}e^{-\\beta{\\cal H}_0}\n}{\n\\int{\\tilde{\\cal D}}\\bigl(E^{\\alpha}\\bigr)\\,e^{-\\beta{\\cal H}_0}\n}\n\\int{\\tilde{\\cal D}}\\bigl(E^{\\alpha}\\bigr)\\,e^{-\\beta{\\cal H}_0}\n,\n\\end{equation}\nor, with another notation\n\\begin{equation}\n\\label{znmoyen2}\n\\left\\langle Z^n\\right\\rangle =\n\\left\\langle\ne^{-\\beta({\\cal H}_e-{\\cal H}_0)}\n\\right\\rangle_0 Z_0,\n\\end{equation}\nwhere $Z_0$ is the partition function associated to ${\\cal H}_0$, and\n$\\left\\langle\\cdot\\right\\rangle_0$ stands for the functional average with\nweights $e^{-\\beta{\\cal H}_0}/Z_0$. Equ.\\ (\\ref{wstar}) thus reads\n\\begin{equation}\n\\label{wsplit}\nW^*=W_0+\\Delta W,\n\\end{equation}\nwhere\n\\begin{eqnarray}\n\\label{wo}\nW_0(E_0)&=&-\\lim_{n\\to 0\\atop\n\\beta\\to\\infty}\\frac{1}{n\\beta}\\ln Z_0,\\\\\n\\label{dwo}\n\\Delta W(E_0)&=&-\\lim_{n\\to 0\\atop \\beta\\to\\infty}\\frac{1}{n\\beta}\n\\ln \\left\\langle e^{-\\beta({\\cal H}_e-{\\cal H}_0)}\n\\right\\rangle_0.\n\\end{eqnarray}\nThe quantity $\\Delta W(E_0)$ is difficult to compute (an exact evaluation\nwould lead to the exact result for the effective conductivity),\nand we have to resort to approximations.\n\nA natural self-consistency condition for ${\\cal H}_0$ \nis \n\\begin{equation}\n\\label{sccond}\n\\Delta W(E_0)=0,\n\\end{equation}\nwhich completely determines ${\\cal H}_0$ in the case where it \ndepends on one single parameter, as in (\\ref{trybrug}). For more general \nchoices of ${\\cal H}_0$ with several free parameters, (\\ref{sccond}) \nonly provides a relation between these parameters, and additional \nconsiderations are in order to determine them all. First of all, \nwe have to precise the form of the ansatz to be used in our calculations.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Replica couplings and choice of the ansatz}\n\\label{rcacota}\nWe deduce here the form of the trial Hamiltonian ${\\cal H}_0$ from an\nanalysis of the effective Hamiltonian ${\\cal H}_e$. Eq.\\ (\\ref{heff})\nshows that the effective Hamiltonian is non-random but that the\naverage over disorder introduced a coupling between different\nreplicas. The meaning of these couplings is more transparent if we\ncarry out an expansion of (\\ref{heff}) around the average field\n$\\overline{E}=E_0$ as in the weak-contrast expansion \\cite{BART98}.\nWith $\\partial_i=\\partial/\\partial E_i$ and $\\Delta\nE^\\alpha=E^\\alpha-E_0$ we have\n\\begin{eqnarray}\n{\\cal H}_e&=&n\\langle w_x(E_0)\\rangle\\nonumber\\\\\n&+&\\frac{1}{2}\n\\left[ \\sum_{\\alpha}\\int dx\\,a_{ij}\\Delta E^\\alpha_i(x)\n\\Delta E^\\alpha_j(x)-\\beta\\sum_{\\alpha,\\gamma}\n\\int dx dy\\, c^{(2)}_{ij}(x-y)\\Delta E^\\alpha_i(x)\n\\Delta E^\\gamma_j(y)\\right] +\\cdots,\n\\end{eqnarray}\nwhere\n\\begin{eqnarray}\n\\label{aa}\na_{ij}&=&\\langle \\partial^2_{ij} w_x(E_0)\\rangle,\\\\\n\\label{bb}\nc^{(2)}_{ij}(x-y)&=&\\langle\\partial_{i} w_x(E_0)\\partial_{j} w_y(E_0)\n\\rangle-\\langle \\partial_{i} w_x(E_0)\\rangle\\langle\\partial_{j} \nw_y(E_0)\\rangle.\n\\end{eqnarray}\nThe first non-zero replica-coupling term is proportional to $\\beta\nc^{(2)}$. We thus see that the coupling between replicas acts only\nwithin clusters defined by $n$-point connected correlation functions\n$c^{(n)}$, and accounts for the fluctuations of the electric field in\nthese clusters. The replica coupling would vanish if there were no\ndisorder at all. In the limit where the size of the region defined by\n$c^{(2)}$ shrinks to zero -- which means that the system is observed\nat a macroscopic level, we can approximate\n\\begin{equation}\nc^{(2)}_{ij}(x-y)\\simeq v c^{(2)}_{ij}(0)\\delta(x-y),\n\\end{equation}\nand we recover the expansion\n\\begin{equation}\n\\label{expan}\n{\\cal H}_e=n\\langle w_x(E_0)\\rangle+\\frac{1}{2}\\int dx\\,\\left[\n\\sum_{\\alpha}a_{ij}\\Delta E^\\alpha_i(x)\\Delta E^\\alpha_j(x)-v\\beta\n\\sum_{\\alpha,\\gamma}c^{(2)}_{ij}(0)\\Delta E^\\alpha_i(x)\\Delta\nE^\\gamma_j(x)\\right] +\\cdots.\n\\end{equation}\nwhich could directly be obtained from (\\ref{calf}). The presence of\n$v$ in front of the replica coupling term is the macroscopic remnant\nof a microscopic average having been taken within a two-particle\ncluster, of center $x$ and volume $v$. This discussion therefore\nenlightens a relation between replica coupling and the electric field\nfluctuations within clusters.\n\nExpansion (\\ref{expan}) suggests a two-parameter \nreplica-symmetric ansatz of the form\n\\begin{equation}\n\\label{ansatz}\n{\\cal H}_0=\\frac{1}{2} \\sum_{\\alpha\\gamma}\\int dx\\, M^{\\alpha\\gamma} \nE^\\alpha_i  E^\\gamma_i,\n\\end{equation}\nwhere\n\\begin{equation}\n\\label{matmok}\nM^{\\alpha\\gamma}=\\sigma_0\\delta_{\\alpha\\gamma}-v\\beta Q E_0^2.\n\\end{equation}\nThe free parameters are $\\sigma_0$ and $Q$. Note that $Q$ has the\ndimension of a squared conductivity, because it is related to a\nquantity relative to two points. For simplicity, the ansatz $M$ is\ndiagonal in the euclidean vector space. However, we tried calculations\nwith a tensorial structure reproducing that of $a_{ij}$ and\n$c^{(2)}_{ij}$ in Eqs.\\ (\\ref{aa}), (\\ref{bb}); but, apart from a\ndifferent normalization for $Q$, no differences showed up in the final\neffective-medium theories (as far as linear media are concerned).\n\nAn interesting feature of the ansatz (\\ref{matmok}) is that, though \nbeing non-random, it embodies underlying disorder through its replica \ncouplings. In order to understand this point, we compute \n$W_0(E_0)$ given by (\\ref{wo})\n\\begin{equation}\n\\label{wopath}\nW_0(E_0)=-\\lim_{n\\to 0\\atop \\beta\\to\\infty}\\frac{1}{n\\beta}\\ln \\int\n\\tilde{\\cal D} E\\,e^{-\\frac{\\beta}{2}\\int\ndx\\,\\left(\\sigma_0\\sum_\\alpha{E^\\alpha}^2-v\\beta Q E_0^2\n\\sum_{\\alpha,\\gamma}{E^\\alpha}\\cdot{E^\\gamma}\\right)}.\n\\end{equation}\nAfter writing $E=E_0-\\nabla \\phi$, and going to the Fourier transform \nof $\\phi$ \\cite{NOTE2}, we arrive at\n\\begin{eqnarray}\nW_0(E_0)&=&-\\lim_{n\\to 0\\atop \\beta\\to\\infty}\\frac{1}{n\\beta}\\ln\n\\left[(\\mathop{\\text{Det}}M)^{-1/2v}\ne^{-\\frac{\\beta}{2}\\sum_{\\alpha\\gamma}\nM_{\\alpha\\gamma}E_0^2}\\right]\\nonumber\\\\\n\\label{wocomp}\n&=&\\frac{1}{2}\\sigma_0(1-Q/\\sigma_0^2) E_0^2.\n\\end{eqnarray}\n\nCarrying out the derivative of (\\ref{wopath}) \nwith respect to $\\sigma_0$, we obtain\n\\begin{equation}\n\\lim_{n\\to 0\\atop \\beta\\to\\infty}\\frac{1}{n}\\left\\langle\\sum_\\alpha\n\\langle{E^\\alpha}^2\\rangle\\right\\rangle_0=E_0^2+ \\frac{Q}{\\sigma_0^2}\nE_0^2,\n\\end{equation}\nwhere volume averages $\\overline{E^2}$ have been replaced by statistical \nones, the microscopic size $v^{1/d}$ being much smaller than \nthat of the system, $V^{1/d}=1$.\nAll the replicas are equivalent, and the functional average $\\langle\\cdot\\rangle_0$ selects in the limit $\\beta\\to\\infty$ the real \nfield in the medium. Hence, setting $\\Delta E=E-E_0$, the previous \nequation leads to\n\\begin{equation}\n\\label{qq}\n\\frac{\\langle\\Delta E^2\\rangle}{E_0^2}=\\frac{Q}{\\sigma_0^2}.\n\\end{equation}\nwhich implies that $Q\\geq 0$. When $Q\\not=0$, the electric field\nfluctuates in the medium, whereas it is uniform when $Q=0$. The ansatz\n${\\cal H}_0$ therefore represents a medium which is homogeneized\n(because it is non-random), but which nonetheless\naccounts for field fluctuations. \nWe thus expect new effective medium approximations\nwhen the replica coupling $Q$ is non zero.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Self-consistency}\n\\label{sc}\nUp to this point the discussion focused on the ansatz itself, without \nreferring to ${\\cal H}_e$. In particular, $\\sigma_0$ was treated as a \nmere number. We now discuss what happens when self-consistency is \nimposed, within some approximation scheme. The medium is made of $N$ \nphases labelled by $\\nu$, of respective conductivities $\\sigma_\\nu$ \nand volume concentrations $p_\\nu$. The self-consistency relation \n$\\Delta W(E_0)=0$, which imposes constraints on the ansatz, \ndetermines $Q$ as a function $Q=Q(\\sigma_0,\\{\\sigma_\\nu\\})$. \nThen $W^*=W_0$ and, with (\\ref{constef}),\n\\begin{equation}\n\\label{sigeff}\n\\sigma_{\\text{eff}}=\\sigma_0\\left[1-\\frac{Q(\\sigma_0,\\{\\sigma_\\nu\\})}\n{\\sigma_0^2}\\right].\n\\end{equation}\n\nSuppose now that $\\sigma_0=\\sigma_0(\\{\\sigma_\\nu\\})$ is determined \nby an additional condition (to be precised below). Using the exact \nformula \\cite{BERG78}  (cf.\\ Appendix \\ref{qfotf})\n\\begin{equation}\n\\label{berg}\n\\frac{\\langle\\Delta E^2\\rangle}{E_0^2}=\\sum_\\nu \\frac{\\partial\n\\sigma_{\\text{eff}}}{\\partial \\sigma_\\nu} -1,\n\\end{equation}\nthe fluctuations of the electric field deduced from (\\ref{sigeff}) \ncan be written\n\\begin{equation}\n\\label{qberg}\n\\frac{\\langle\\Delta\nE^2\\rangle}{E_0^2}=\\sigma_{\\text{eff}}'(\\sigma_0)\\left(\\sum_\\nu\n\\frac{\\partial \\sigma_0}{\\partial\n\\sigma_\\nu}-1\\right)+\\frac{Q}{\\sigma_0^2}-\\frac{1}{\\sigma_0}\n\\left[\\frac{\\partial Q}{\\partial\n\\sigma_0}+\\sum_\\nu\\left(\\frac{\\partial Q}{\\partial\n\\sigma_\\nu}\\right)_{\\sigma_0}\\right]\n\\end{equation}\nwhere the last derivative is performed at constant $\\sigma_0$.  This\nexpression distinguishes between different contributions to the field\nfluctuations: (i) the first term represents fluctuations coming from\nthe ``macroscopic'' background effective medium $\\sigma_0$; (ii) the\nsecond one is that already found in (\\ref{qq}), and would be the only\none if $Q$ were independent from $\\sigma_0$, and if \n$\\sigma_0$ were equal to $\\langle\\sigma\\rangle$,\n the trivial value corresponding\nto a non-fluctuating reference medium for a multiphase composite, cf.\\\nAppendix \\ref{qfotf}; (iii) and finally a third\nterm comes from the dependence of $Q$ on $\\sigma_0$ and\n$\\sigma_\\nu$. Both last terms are, according to the interpretation of\nreplica coupling developped in the previous section, of\n``microscopic'' origin.\n\nWe now turn to the determination of $\\sigma_0(\\{\\sigma_\\nu\\})$. A \nfirst obvious self-consistency condition for $\\sigma_0$ is $Q\\equiv 0$, \nso that $\\sigma_{\\text{eff}}=\\sigma_0$. The effective-medium formulas obtained \nthis way are referred to as ``type 1'' hereafter. As is shown \nbelow, to this type pertain the Bruggeman and HY formulas.\n\n``Type 2'' effective-medium formulas are obtained by taking $\\sigma_0$\nas the solution of $\\sigma_{\\text{eff}}'(\\sigma_0)=0$, and by using\nthis value in $\\sigma_{\\text{eff}}$. According to (\\ref{qberg}), this\nprocedure makes the effective-medium insensitive to the fluctuations\ngenerated in the reference medium $\\sigma_0$, so that relevant fluctuations\nonly come from $Q$.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Two approximations}\n\\label{tm}\nIn this section, the ideas introduced above are used within two\ndifferent approximations to $\\Delta W(E_0)$, based on the ansatz\n(\\ref{ansatz}), (\\ref{matmok}). For each approximation to $\\Delta W$,\n``type 1'' and ``type 2'' formulas are obtained.  Herafter,\n$q=Q/\\sigma_0^2$, so that\n\\begin{equation}\n\\label{sigefq}\n\\sigma_{\\text{eff}}=\\sigma_0(1-q).\n\\end{equation}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{One-impurity approximation}\n\\label{oia}\n\nWe first consider a ``one-impurity'' (or ``local'') calculation. The\nBruggeman formula emerges as the ``type 1'' effective-medium formula\nin this approximation, which is not suprising since it can be seen as\na one-site (self-consistent) theory \\cite{HORI75,LUCK91}.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Approximation scheme}\nThe approximation for $\\Delta W(E_0)$ [Eq.\\ (\\ref{dwo})], detailed in \nAppendix \\ref{appb}, is a one-impurity approximation where interactions \nbetween different points are ignored. Let us denote by $w_0$ the \ntrial Hamiltonian density, which depends on all the replicas, \ndefined from (\\ref{ansatz}), (\\ref{matmok}) by\n\\begin{equation}\n\\label{hdens}\n{\\cal H}_0\\equiv\\int dx\\, w_0[E(x)].\n\\end{equation}\nHere and in Appendix \\ref{appb}, the notation $[\\cdot]$ indicates \na dependence with respect to all the replicas.\nSetting \n\\begin{equation}\n\\label{dwx}\n\\Delta w_x[E(x)]=\\sum_\\alpha w_x\\bigl(E^\\alpha(x)\\bigr)-w_0[E(x)],\n\\end{equation}\nthe one-impurity approximation results in\n\\begin{equation}\n\\label{oneimp}\n\\left\\langle e^{-\\beta({\\cal H}_e-{\\cal H}_0)}\\right\\rangle_0\\simeq \n1+\\frac{1}{v}\\left\\langle \\left\\langle e^{-\\beta v \\Delta w_x[E(x)]}\\right\\rangle_0-1\\right\\rangle.\n\\end{equation}\nBecause of statistical translation invariance, the final result is \nindependant of the point $x$. The right-hand side can be computed \nexactly for any potential $w_x$ in the limit $\\beta\\to\\infty$ using \na saddle-point method. Setting $\\Delta\\sigma=\\sigma-\\sigma_0$ \nand\n\\begin{equation}\n\\mu=\\left(1+\\frac{\\Delta\\sigma}{d\\sigma_0}\\right)^{-1},\n\\end{equation}\nwe arrive at\n\\begin{equation}\n\\label{dwoi}\n\\Delta W(E_0)=\\frac{1}{2}\\langle\\Delta\\sigma \\mu\\rangle E_0^2\n+\\frac{q}{2}\\langle \\sigma\\mu\\rangle E_0^2.\n\\end{equation}\nThe condition $\\Delta W(E_0)=0$ yields\n\\begin{equation}\n\\label{qbrug}\nq=-\\frac{\\langle\\Delta\\sigma \\mu\\rangle}{\\langle \\sigma\\mu\\rangle}.\n\\end{equation}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Type 1 formula: Bruggeman's}\nLetting $q\\equiv 0$ amounts to imposing $\\langle\\Delta\\sigma \n\\mu\\rangle=0$, which is nothing but the Bruggeman equation\n\\begin{equation}\n\\left\\langle\\frac{\\sigma-\\sigma_0}{\\sigma+(d-1)\\sigma_0}\\right\\rangle=0.\n\\end{equation}\nThe Bruggeman equation can also be written $\\langle\\mu\\rangle=1$, or $\\sigma_0=\\langle\\sigma\\mu\\rangle$ if $d\\not= 1$, or $\\sigma_0=\\langle\\sigma\\mu\\rangle/\\langle\\mu\\rangle$. \nThe last expression is suitable for computing $\\sigma_0$ iteratively \n(starting, e.g., from $\\sigma_0=\\langle\\sigma\\rangle$) in any \ndimension. The Bruggeman conductivity $\\sigma_{\\text{eff}}\n=\\sigma_0$ possesses a percolation threshold $p_c=1/d$, and critical \nexponents $s=t=1$ \\cite{CLER90}.\n\nThe fluctuations computed from (\\ref{berg}) read\n\\begin{equation}\n\\frac{\\langle\\Delta E^2\\rangle}{E_0^2}=\n\\frac{\\sigma_0\\langle\\mu^2\\rangle}\n{\\langle\\sigma\\mu^2\\rangle}.\n\\end{equation}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Type 2 formula}\nWe now let $q\\neq 0$ and given by (\\ref{qbrug}) and\n$\\sigma_{\\text{eff}}(\\sigma_0)=\\sigma_0\\bigl(1-q(\\sigma_0)\\bigr)$. The\nequation $\\sigma_{\\text{eff}}'(\\sigma_0)=0$ reads\n\\begin{equation}\n\\label{eqsigo}\n\\sigma_0=\\frac{\\langle\\sigma\\mu\\rangle}{\\langle\\mu\\rangle}\n\\left(1+\\frac{\\langle\\mu\\rangle\\langle\\sigma^2\\mu^2\\rangle\n-\\langle\\sigma\\mu^2\\rangle\\langle\\sigma\\mu\\rangle}\n{2d\\langle\\sigma\\mu\\rangle^2}\\right).\n\\end{equation}\nLike Bruggeman's, this equation is easily solved by iterations starting\nfrom $\\sigma_0=\\langle\\sigma\\rangle$. The iterations then always\nconverge to the physical solution, which we denote by\n$\\sigma_0^*$. The effective conductivity thus is\n$\\sigma_{\\text{eff}}=\\sigma_0^*\\bigl(1-q(\\sigma_0^*)\\bigr)$.  To study\nits critical behavior, we consider a binary mixture, where\n$\\sigma=\\sigma_1$ with probability $(1-p)$, and $\\sigma=\\sigma_2$ with\nprobability $p$. In the conductor/superconductor limit where\n$\\sigma_2\\to\\infty$ we find, setting $p_c=1/(2d-1)$,\n\\begin{equation}\n\\label{sols0}\n\\sigma_0^*=\\frac{\\sigma_1}{p(d-1)}\\left(\\sqrt{\\frac{1-p}{1-p/p_c}}\n-1\\right)\\qquad (p<p_c)\n\\end{equation}\nand\n\\begin{equation}\n\\label{solseff}\n\\sigma_{\\text{eff}}=2\\sigma_1\\frac{\\left[1-dp\n-\\sqrt{(1-p)(1-p/p_c)}\\right]}{p^2(d-1)^2}\\qquad  (p<p_c).\n\\end{equation}\nThe critical concentration $p_c$ can be interpreted as a percolation\nthreshold, and is the same as that obtained in the mean-field model on\na Bethe lattice\\cite{STEP77} with connectivity $z=2d$. Since\n$\\sigma_{\\text{eff}}=2(2d-1)\\sigma_1/(d-1)\\sim(p_c-p)^0$ for\n$p\\lesssim p_c$, the superconductivity exponent is $s=0$. Note however\nthat $\\sigma_0$ displays a square-root cusp at $p=p_c$.  The critical\nbehavior for $p>p_c$ is obtained by exmining the insulator/conductor\nmixture where $\\sigma_2$ is finite and $\\sigma_1=0$.  Then\n\\begin{eqnarray}\n\\sigma_0^*&=&\\sigma_2\\frac{p/p_c-1}{2(d-1)},\\\\\n\\sigma_{\\text{eff}}&=&\\sigma_2\\frac{(p/p_c-1)^2}{4(d-1)^2 p} \n\\qquad  (p>p_c).\n\\end{eqnarray}\nSince $\\sigma_{\\text{eff}}\\sim(p-p_c)^2$ for $p\\gtrsim p_c$, \nthe conductivity exponent is $t=2$.\n\nFor the special case of $d=1$, $\\mu=\\sigma_0/\\sigma$ so that \n(\\ref{eqsigo}) reduces to $\\sigma_0=\\langle1/\\sigma\\rangle^{-1}$, \nand $q=0$. Therefore, $\\sigma_{\\text{eff}}=\\langle1/\\sigma\\rangle^{-1}$, \nwhich is the exact result. Like Bruggeman's, the new formula \nis also exact to second order in the \ncontrast, in any dimension\n\\begin{equation}\n\\label{wcl}\n\\sigma_{\\text{eff}}=\\langle\\sigma\\rangle\\left[1-\\frac{\\langle\n\\sigma^2\\rangle-\\langle\\sigma\\rangle^2}{d\\langle\\sigma\\rangle^2}\n+\\cdots\\right];\n\\end{equation}\nand in the dilute limit where (e.g.) $p_2\\ll 1$\n\\begin{equation}\n\\label{dl}\n\\sigma_{\\text{eff}}=\\sigma_1\\left[1+d\\frac{\\sigma_2-\\sigma_1}\n{\\sigma_2+(d-1)\\sigma_1}+\\cdots\\right].\n\\end{equation}\nIn the discussion (Section \\ref{d}), it is argued that because \nof its exponents $s\\not= t$, and because it is less trivial than \nthe Bruggeman formula (especially in the insulator/conductor case \nwhere it does not reduce to a straight line), this formula may \nconstitute an easy-to-handle alternative to the latter in dimensions \n$d\\geq 3$. Graphical comparisons between different effective-medium \nformulas are discussed in Sec.\\ \\ref{d}.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Cumulant series approximation}\n\\label{asa}\n\nIn this section, we show how to recover by means of a cumulant\napproximation to $\\Delta W$ the effective-medium formula of HY,\ntogether with its ``type 2'' counterpart.\n\n\\subsubsection{Approximation scheme}\nWe consider the first-order cumulant approximation\n\\begin{equation}\n\\label{cumul}\n\\left\\langle\ne^{-\\beta({\\cal H}_e-{\\cal H}_0)}\n\\right\\rangle_0\\simeq\ne^{-\\beta\\left\\langle{\\cal H}_e-{\\cal H}_0\\right\\rangle_0}.\n\\end{equation}\n\nWe have then\n\\begin{equation}\n\\label{dwsa}\n\\Delta W(E_0)\\simeq\\lim_{n\\to 0\\atop \\beta\\to\\infty}\\frac{1}{n}\n\\left\\langle\n{\\cal H}_e-{\\cal H}_0\\right\\rangle_0.\n\\end{equation}\nAs is shown in Appendix C, the calculations here involve an expansion\nin a series of the cumulants of the distribution of $\\sigma$, whose\nsignificance has been discussed at length in the original paper by\nHY\\cite{HORI77}. After some algebra, we obtain (cf.\\ Appendix C)\n\\begin{equation}\n\\label{fmfodeu}\n\\Delta W(E_0)\n=-{\\sigma_0\\over 2}\\Bigl\\{\\left[1+d h_0\n\\bigl(1/(d\\sigma_0)\\bigr)\\right]+d q h_0 \n\\bigl(1/(d\\sigma_0)\\bigr)\\Bigr\\}E_0^2,\n\\end{equation}\nwhere\n\\begin{equation}\nh_0(z)=\\int_0^{\\infty}du\\, e^{-u}\\ln\\langle e^{-u\\sigma z}\\rangle.\n\\end{equation}\nThe family of functions $h_k$ is defined in Appendix C. \nThe self-consistency $\\Delta W(E_0)=0$ now yields\n\\begin{equation}\n\\label{q}\nq=-\\left[1+\\frac{1}{d h_0\n\\bigl(1/(d\\sigma_0)\\bigr)}\\right].\n\\end{equation}\n  \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Type 1 formula: the Hori-Yonezawa formula}\n\\label{thfr}\n\nWe first consider the case with no couplings between replicas,\ni.e. $q=0$. The HY formula for $\\sigma_0$ reads\n\\begin{equation}\n\\label{hy}\nh_0 \\bigl(1/(d\\sigma_0)\\bigr)=-{1\\over d},\n\\end{equation}\nand the effective conductivity is $\\sigma_{\\text{eff}}=\\sigma_0$. \nIt can be shown that $\\sigma_{\\text{eff}}$ displays a percolation \nthreshold\n$p_c=1-\\exp(-1/d)$, and exponents $s=t=1$\\cite{HORI77}. \nApplying (\\ref{berg})  and using (\\ref{deriv}), the fluctuations read\n\\begin{equation}\n\\frac{\\langle\\Delta E^2\\rangle}{E_0^2}=\n-{2 +d h_1\\bigl(1/(d\\sigma_0)\\bigr)\\over 1+d h_1\\bigl(1/(d\\sigma_0)\\bigr)}.\n\\end{equation}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Type 2 formula}\n\\label{nef}\n\nWe now consider $q\\neq 0$ and determined as a function of $\\sigma_0$\nby (\\ref{q}). Then\n\\begin{equation}\n\\label{phiosol}\n\\sigma_{\\text{eff}}(\\sigma_0)=\\sigma_0\n\\left[2+{1\\over dh_0\n\\bigl(1/(d\\sigma_0)\\bigr)}\n\\right].\n\\end{equation}\nThe equation for $\\sigma_0$ is $\\sigma_{\\text{eff}}'(\\sigma_0)=0$; \nthat is, with (\\ref{deriv})\n\\begin{equation}\n\\label{deriveq}\n2+{1\\over d}{h_1\\bigl(1/(d\\sigma_0)\\bigr)\\over\nh_0^2\\bigl(1/(d\\sigma_0)\\bigr)}=0.\n\\end{equation}\nIn order to study the critical behavior of $\\sigma_{\\text{eff}}$, \nwe consider again a binary mixture where $\\sigma=\\sigma_1$ with\nprobability $(1-p)$, and $\\sigma=\\sigma_2$ with probability\n$p$. In the conductor/superconductor case where\n$\\sigma_2\\to\\infty$, we have\n$h_0\\bigl(1/(d\\sigma_0))\\bigr)=\\ln(1-p)-\\sigma_1/(d\\sigma_0)$ and \na similar equation for $h_1$, so that (\\ref{deriveq}) reduces to \na second-degree polynomial equation. Its physical solution reads\n\\begin{equation}\n\\label{solinf}\n\\sigma_0^*={2\\sigma_1\\over\\sqrt{1+2d\\ln(1-p)}\n\\left[1+\\sqrt{1+2d\\ln(1-p)}\\right]}.\n\\end{equation}\nIt is defined for $p$ less than a critical value\n\\begin{equation}\np_c=1-e^{-1/(2d)}.\n\\end{equation}\nThis percolation threshold is the same as the one obtained in the Potts \nmodel at the mean-field level, and in the \nmean-field theory\nof Ref.\\ \\cite{STEP77}. Reporting (\\ref{solinf}) into (\\ref{phiosol}), \nwe arrive at\n\\begin{equation}\n\\sigma_{\\text{eff}}={4\\sigma_1\\over\n\\left[1+\\sqrt{1+2d\\ln(1-p)}\\right]^2}\\qquad(p<p_c).\\\\\n\\end{equation}\nSince $\\sigma_{\\text{eff}}\\propto (p_c-p)^0$\nfor $p\\lesssim p_c$, the superconductivity exponent is $s=0$.\n\nIn the opposite insulator/conductor case, where $\\sigma_1=0$ \nand $\\sigma_2$ is finite, the solution for $p>p_c$ can only be found perturbatively around the percolation threshold. Expanding the \nlogarithm in $h_0$ and $h_1$ as\n\\begin{equation}\n\\ln\\left[(1-p)+p\ne^{-u\\sigma_2/(d\\sigma_0)}\\right]=\\ln(1-p)+\\sum_{l\\geq\n1}{(-1)^{l-1}\\over l}\\left({p\\over 1-p}\\right)^l\ne^{-lu\\sigma_2/(d\\sigma_0)},\n\\end{equation}\nand defining\n\\begin{equation}\nA(x)=\\sum_{l\\geq 1} {(-1)^{l-1}\\over l^2} x^l=\\int_0^x {dt\\over t}\n\\ln(1+t),\n\\end{equation}\nwe find that \n\\begin{equation}\n\\sigma_0^*={\\sigma_2\\over 4 d^2 A\\bigl(p_c/(1-p_c)\\bigr)}(p-p_c)+O\n\\left((p-p_c)^2\\right),\n\\end{equation}\nand that\n\\begin{equation}\n\\sigma_{\\text{eff}}={\\sigma_2\\over\n4d^2 A\\bigl(p_c/(1-p_c)\\bigr)}(p-p_c)^2+O\\left((p-p_c)^3\\right)\n\\qquad (p\\gtrsim p_c),\n\\end{equation} \nwhere the conductivity exponent is $t=2$. Hence, as in the previous\n``one-impurity'' approximation, the replica-coupling ansatz yields\ncritical exponents $s=0$, $t=2$, and an asymptotic dependence of the\nthreshold $p_c\\sim 1/(2d)$ when $2d\\gg 1$. One can easily check that\nthis new ``type 2'' effective-medium formula is exact to second order\nin the weak-contrast limit and in the dilute limit.\n\nAfter a few manipulations, we now obtain with (\\ref{berg}) and (\\ref{q}) \n\\begin{equation}\n{\\left\\langle \\Delta E^2\\right\\rangle\\over \\left\\langle E\\right\\rangle^2}\n=2q\\left(1+\\frac{q}{2}\\right).\n\\end{equation}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Discussion}\n\\label{d}\n\nWe plot in Fig. \\ref{fig1} (resp.\\ \\ref{fig2}) the ``type 2'' scaled\nconductivities $\\sigma_{\\text{eff}}/\\sigma_1$ versus $p$, the volume\nfraction of material 2, for a dielectric ratio $\\sigma_2/\\sigma_1=10$\n(resp.\\ $\\sigma_2/\\sigma_1=1000$). We also show the Hashin-Shtrikman\n(HS) bounds \\cite{HASH62}, the Hori-Yonezawa formula which comes from\na cumulant series (CS) approximation, and the one-impurity (OI)\nBruggeman formula.  The dimension is $d=2$. Figs.\\ \\ref{fig3} and\n\\ref{fig4} display similar plots for $d=3$.\n\nFor moderate contrast (Figs.\\ 1 and 3), we observe that all four\nself-consistent formulas lie close to each other. This is a\nconsequence of the fact that they are exact to second order in the\ncontrast. Also, for any contrast, the slopes at $p=0$ and $p=1$ are\nall identical, which is a consequence of the fact that they are exact\nto second order in the dilute limit $p\\to 0$ (the expression near\n$p=1$ is obtained by replacing $p$ by $p-1$ and by interchanging\n$\\sigma_1$ and $\\sigma_2$). We also observe that the HS bounds are\nsatisfied in each case considered. However, the formulas obtained via\nthe cumulant series summation, i.e.\\ both the HY formula and its\n``type 2'' counterpart, do not reduce to the exact result\n$\\sigma_{\\text{eff}}=\\langle 1/\\sigma\\rangle^{-1}$ in dimension 1 (not\nshown). This exact result is also the common value of the HS bounds\nfor $d=1$. Hence, formulas derived from the cumulant series\napproximation do not obey the HS bounds in dimension $d=1$. On the\nother hand, both the Bruggeman formula and its ``type 2'' counterpart\ndo reduce to the exact result when $d=1$, and can be seen to always\nobey the HS bounds whatever $d$ is. The one-impurity approximation\nscheme therefore appears to be of better physical relevance for all\ndimensions, than the cumulant series approximation.\n\nWe now discuss the critical behavior. First of all, the percolation\nthresholds found in the``type 2'' formulas are\n$p_c=1-\\exp\\bigl(-1/(2d)\\bigr)$ (cumulant series) and $p_c=1/(2d-1)$\n(one-impurity). These thresholds are the percolation thresholds of the\nPotts model, and that of the Bethe lattice model, respectively. Both\nthresholds decrease as $1/(2d)$ when $d\\to\\infty$, which is the exact\nasymptotics. The Bethe and Potts models are mean-field models, where\nemphasis is put on fluctuations in the couplings between a given site\nand its neighbours. On the contrary, in effective-medium theories,\ninteractions between impurities are taked into account through the\nself-consistent background medium. Such interactions are more\nimportant for low dimensions. Effective-medium theories therefore\noverestimate interactions in high dimensions, whereas mean-field\nmodels are expected to underestimate them in low dimensions. Above the\nupper critical dimension where mean-field models are accurate,\ninteractions between impurities become irrelevant. According to this\ndiscussion, our ``type 2'' formulas appear as hybrids between\nmean-field and usual effective-medium theories, and are expected to be\nmostly relevant in dimensions intermediate between $d=1$ and the upper\ncritical dimension $d=6$.  Indeed, the condition\n$\\sigma'_{\\text{eff}}(\\sigma_0)=0$ minimizes the influence of the\nbackground medium and, according to the interpretation developped in\nSec.\\ \\ref{rcacota}, replica coupling has to do with couplings\nbetween neighboring points. The reason for which the introduction of a\nreplica-coupling ansatz yields the exact thresholds of mean-field\ntheories will have to be clarified in the future.  In Fig.\\\n\\ref{fig5}, we plot the quadratic fluctuations $\\left\\langle\\Delta\nE^2\\right\\rangle/\\left\\langle E\\right\\rangle^2$ as a function of\n$p$. The fluctuations in the ``type 2'' estimates are greatly reduced\ncompared to those of the Bruggeman and HY formula. This is consistent\nwith the fact that the influence of the background is reduced.\n\n``Type 1'' formulas give exponents $s=t=1$, while for ``type 2''\nformulas they are $s=0$, $t=2$. Mean-field theories yield $s=0$, $t=3$\nwhich are the exact values for $d\\geq 6$.  It is interesting to\ncompare these values to exact bounds deduced from the\nNodes-Links-Blobs (NLB) model, in all dimensions. The NLB model is\ncurrently accepted as a good one for the backbone structure of real\nrandom resistor networks\\cite{STAU92}. The bounds read\n\\begin{mathletters}\n\\label{expbounds}\n\\begin{eqnarray}\n&&t\\ge 1+(d-2)\\nu,\\\\\n&&s\\ge 1+(2-d)\\nu,\n\\end{eqnarray}\n\\end{mathletters}\nwhere $\\nu>0$ is the correlation length exponent: $\\xi\\propto\n|p-p_c|^{-\\nu}$. They hold for $2\\leq d\\leq 6$, whereas for $d>6$ the\nright-hand sides in (\\ref{expbounds}) are fixed to their $d=6$\nvalues. These bounds follow, e.g., from comparing the lower and upper\nexact bounds obtained in Ref.\\ \\cite{WRIG86} for the noise exponent\n$\\kappa$ in weakly nonlinear networks, within the NLB scheme. They\nare satisfied by simulation results \\cite{WRIG86}. \nUsing the usual\neffective-medium values $s=t=1$ in (\\ref{expbounds}) implies the\nabsurd value $\\nu=0$, save for $d=2$ where a finite value of $\\nu$ is\nallowed. Though information about the correlation length $\\xi$ (and\ntherefore about $\\nu$) is not included in the Bruggeman nor in the HY\nformulas, the above bounds show that, as long as they are meant to\nmodel percolating systems obeying the NLB picture, these formulas are\ntruly adequate only in dimension $d=2$ -- and $d=1$ where the Bruggeman\nformula is exact. As to ``type 2'' formulas, we insert the\nvalues $s=0$, $t=2$ into (\\ref{expbounds}) and deduce that\n$\\nu=1/(d-2)$, a reasonable expression for $d\\geq 3$ only. If we\nfurthermore insist on having $\\nu\\geq 1/2$ as in real systems, these\nheuristic arguments restrict the range of validity of the new formulas\nto $d=3,4$. Note, moreover, that only in dimension $d=2$ are the\nexponents equal: $s=t$, because of self-duality \\cite{STRA77}.  A\nformula with unequal exponents therefore is expected to be essentially\nrelevant to dimensions $\\geq 3$.\n\nWe also quote theoretical bounds for $t$ due to Golden, valid for\nhierarchical NLB models: $1\\leq t\\leq 2$ for $d=2,3$ and $2\\leq t\\leq\n3$ for $d\\geq 4$ \\cite{GOLD90}. The above analysis is consistent with\nthese bounds, and can be summarized as a set of prescriptions for\nusing the ``best'' available effective medium theories, as far as a\nnon-conflicting critical behaviour is concerned: for $d=1$,\nBruggeman's formula, or its ``type 2'' counterpart are exact; for\n$d=2$, the Bruggeman or HY formulas are adequate; for $d=3,4$, ``type\n2'' formulas are applicable; finally, for $d\\geq 5$ mean-field\ntheories would be the most relevant.  Estimates or exact values for\nthe exponents are \\cite{STAU92}: $(\\nu,s,t)=(4/3,1.3,1.3)_{d=2}$,\n$(0.88,0.73,2.00)_{d=3}$, $(0.68,0.4,2.4)_{d=4}$,\n$(0.57,0.1,2.7)_{d=5}$, $(1/2,0,3)_{d\\geq 6}$. These values support\nour prescriptions.\n\nAn interesting observation is that actually both ``type 1'' \nand ``type 2'' formulas can be given by a variational formulation as\n\\begin{eqnarray}\n\\label{min}\n\\sigma_{\\text{eff}}^{\\text{type 1}}&=& \\min_{\\sigma_0\\geq 0\\atop 0\\leq\nq(\\sigma_0)\\leq 1}\\sigma_{\\text{eff}}(\\sigma_0),\\\\\n\\label{max}\n\\sigma_{\\text{eff}}^{\\text{type 2}}&=&\n\\max_{\\sigma_0\\geq 0\\atop 0\\leq q(\\sigma_0)\\leq 1}\n\\sigma_{\\text{eff}}(\\sigma_0),\n\\end{eqnarray}\nprovided that an unphysical solution $\\sigma_{\\text{eff}}=0$ is\ndiscarded in the minimization (\\ref{min}). Indeed, at least in the\nframework of the two different models introduced in Sec.\\ \\ref{tm},\nthe curves for $q(\\sigma_0)$ and $\\sigma_{\\text{eff}}(\\sigma_0)$ are\nfound to have the form shown in Fig.\\ 6. The infimum (\\ref{min})\noccurs at $q=0$, whereas the solution $\\sigma_0^*$ to the equation\n$\\sigma_{\\text{eff}}'(\\sigma_0)=0$ corresponds to a maximum of\n$\\sigma_{\\text{eff}}$. Both types of theories can therefore be\ninterpreted as extremal theories in the framework of self-consistent\nmodels built on the replica-coupling ansatz.  The physical meaning of\nthis interpretation is still not clear. However, ``type 2''\nformulas should not been disregarded as unphysical because of their\nshowing up as maximal ones: the minimization principle states that the\ndissipated power is minimized with respect to the electric field; but\nthere is no reason why an extremization with respect to arbitrary\nvariational parameters should not lead to a maximum of the dissipated\npower.  Eqs.\\ (\\ref{min}), (\\ref{max}) explain why for a given\napproximation, one always has $\\sigma_{\\text{eff}}^{\\text{type 1}}\n\\leq\\sigma_{\\text{eff}}^{\\text{type 2}}$ in Figs.\\ 1-4.\n \nWe now consider some points that were not explicitly treated in the\npaper. First, we presented the formalism in terms of the electric\nfield $E$, from which we obtained a conductivity\n$\\sigma_{\\text{eff}}$. The electric current $j$ (or the induction\n$D$), could be used instead \\cite{BART98}. In such a formulation, the\nrandom constitutive parameter is the resistivity $\\rho(x)=1/\\sigma(x)$\nand the constraints are $\\nabla\\cdot j=0$ and $\\overline{j}=j_0$. One\nthen computes an effective resistivity $\\rho_{\\text{eff}}$. Both\nformulations are equivalent, but a given approximation scheme in\ngeneral leads to different results for $\\sigma_{\\text{eff}}$ and\n$\\tilde\\sigma_{\\text{eff}}=1/\\rho_{\\text{eff}}$.  Preliminary\ninvestigations of ``type 2'' formulas have been led in this\ncase. These will be presented elsewhere.  Finally, we discuss the\nnatural question about the possibility of replica-symmetry breaking\n\\cite{PARI84}. Replica symmetry breaking introduces more free\nparameters in the ansatz, and the final extremization has to be\ncarried out with respect to several variables. There is no frustration\nin this problem, and we therefore expect the replica symmetric\nsolution to be the only one. In order to test this, we tried a one-step\nsymmetry-breaking solution and did indeed not find any new solution.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Conclusion}\n\\label{c}\n\nWe presented a functional approach to the calculation of\neffective-medium properties of random media. We showed how to recover\nthe Bruggeman and Hori-Yonezawa formulas by using specific\napproximation schemes to the basic functional integral.  We also\ndiscussed the introduction of a replica-coupling parameter in a\ngaussian Ansatz, from which new effective-medium formulas were\nobtained. These formulas appear to be more adequate in $d=3$ compared\nto the standard ones by Bruggeman and HY. Because it yields a\nsensible result in all dimensions, and fulfills all the constraints\nrequired to deserve the label of a ``good'' effective-medium theory,\nthe ``type 2'' counterpart of the Bruggeman formula offers an\ninteresting alternative to the latter. Indeed, it has a percolation\nthreshold equal to $p_c=1/5$ in three dimensions. This is closer to\nvalues observed in real materials, compared to the $p_c=1/3$ of the\nBruggeman formula which often constitutes an overestimation.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\acknowledgements\n\nWe gratefully acknowledge H.~Orland for stimulating discussions. One\nof us (MB) wants to thank H.E.~Stanley for his hospitality at the CPS\nand the DGA for financial support.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\appendix\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Quadratic fluctuations of the field}\n\\label{qfotf}\nFor completeness, we give here the demonstration of Eq.\\ (\\ref{berg})\n\\cite{BERG78}. Volume averages are identified to statistical ones.\nBecause $W^*=(1/2)\\langle \\sigma E^2\\rangle =(1/2)\\sum_\\nu p_\\nu\n\\sigma_\\nu \\langle E^2\\rangle_\\nu$, where $\\langle \\cdot \\rangle_\\nu$\ndenotes an average on the phase $\\nu$ on which the conductivity\n$\\sigma_\\nu$ is constant, the effective conductivity reads\n\\begin{equation}\n\\sigma_{\\text{eff}}=\\sum_\\nu p_\\nu \\sigma_\\nu \\frac{\\langle E^2\\rangle_\\nu}{E_0^2}.\n\\end{equation}\nOn the other hand, $\\sigma_{\\text{eff}}$ has to be an homogeneous \nfunction of degree one of the $\\sigma_\\nu$, whence\n\\begin{equation}\n\\sigma_{\\text{eff}}=\\sum_\\nu \\sigma_\\nu \\frac{\\partial \\sigma_{\\text{eff}}}{\\partial \\sigma_\\nu}.\n\\end{equation}\nComparing both equations yields the values of the \n$\\langle E^2\\rangle_\\nu$ and consequently that of $\\langle E^2\\rangle\n=\\sum_\\nu p_\\nu \\langle E^2\\rangle_\\nu$. Equ.\\ (\\ref{berg}) follows. \nWe note that if $\\sigma_{\\text{eff}}=\\langle\\sigma\\rangle$ (an exact \nupper bound for the effective conductivity), then \n$\\langle \\Delta E^2\\rangle=0$. Therefore, $\\sigma_{\\text{eff}}=\\langle\\sigma\\rangle$ defines a trivial model \nof a medium which is a composite, but from which field fluctations \nare nonetheless absent. \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Calculations in the ``one-impurity'' approximation}\n\\label{appb}\nThe approximation which leads to (\\ref{oneimp}) is built as follows. We first expand the exponential\n\\begin{equation}\n\\label{ser}\n\\left\\langle e^{-\\beta({\\cal H}_e-{\\cal H}_0)}\\right\\rangle_0=\\sum_{k\\geq 0}\n{(-\\beta)^k\\over k!} \\left\\langle({\\cal H}_e-{\\cal H}_0)^k\\right\\rangle_0.\n\\end{equation}\nSince ${\\cal H}_0$ is non-random, using the hamiltonian \ndensity $w_0$ defined in (\\ref{hdens}) and $\\Delta w_x[E(x)]$ defined by (\\ref{dwx}) we can rewrite  the difference ${\\cal H}_e-{\\cal H}_0$ as\n\\begin{equation}\n{\\cal H}_e-{\\cal H}_0=\\int dx\\, \\Delta H(x),\n\\end{equation}\nwhere \n\\begin{equation}\n\\label{dh}\n\\Delta H(x)=-\\frac{1}{\\beta v}\\ln\\left\\langle e^{-\\beta v \\Delta w_x[E(x)]}\\right\\rangle.\n\\end{equation}\nThe one-impurity approximation consists in writing ($k\\geq 1$)\n\\begin{mathletters}\n\\begin{eqnarray}\n\\label{intint}\n({\\cal H}_e-{\\cal H}_0)^k\n&=&\n\\int dx_1\\ldots dx_k\\,\\Delta H(x_1)\n\\ldots\n\\Delta H(x_k)\\\\ \n&\\simeq& v^{k-1}\\int dy\\, \n\\Delta H(y)^k.\n\\end{eqnarray}\n\\end{mathletters}\nThe last expression only retains contributions from identical points \nin Eq.\\ (\\ref{intint}). Summing back the series in (\\ref{ser}), and using (\\ref{dh}) yields\n\\begin{eqnarray}\n\\label{ebracko}\n&&\\left\\langle e^{-\\beta({\\cal H}_e-{\\cal H}_0)}\\right\\rangle_0\n\\simeq \n1+\\int {dy\\over v}\n\\left\\langle {\\cal I}(y)-1\\right\\rangle,\\\\\n\\label{caliy}\n&&{\\cal I}(y)=\\frac{\\int \\tilde{\\cal D}(E^{\\alpha})\\,\ne^{-\\beta\\int dx\\, \\left\\{w_0[E(x)]\n+v\\,\\Delta w_{\\bf x}[E(x)]\n\\delta(x-y)\\right\\}}}\n{\\int \\tilde{\\cal D}(E^{\\alpha})\\,e^{-\\beta {\\cal H}_0}},\n\\end{eqnarray}\nwhere a one-impurity-type integral is involved. Since the fundamental\nsize of the theory ($\\sim v^{1/d}$) is much smaller than the volume\n$V=1$ of the system, and since the latter is statistically\ntranslation-invariant, the outer integral over $y$ is redundant with\nthe disorder average, and can be dropped. We therefore arrive at\n(\\ref{oneimp}).\n\nWhen $\\beta\\to\\infty$, the functional ${\\cal I}(y)$ can be computed\nexactly. Let us briefly indicate how to do it. We first introduce the\nnotation $\\vec{h}$ for vectors of dimension $nd$, and components\n$h^\\alpha_i$, with $\\alpha=1,\\ldots,n$, $i=1,\\ldots,d$.  Hence,\n$\\Delta w_y[E(y)]\\equiv \\Delta w_y\\bigl(\\vec{E}(y)\\bigr)$. The next\nstep is to use the formal identity\n\\begin{equation}\ne^{-\\beta v\\Delta w_y(\\vec{E})}=\\int {d\\vec{h}\\,d\\vec{h}'\\over\n(2\\pi)^{nd}}e^{-i\\vec{h}\\cdot \\vec{h}'} e^{-\\beta v\\Delta\nw_y\\bigl(-i\\frac{\\partial}{\\partial \\vec{h}'}\\bigr)} e^{i\n\\vec{h}'\\cdot \\vec{E}}\n\\end{equation}\nto write the numerator of (\\ref{caliy}), which we denote hereafter by\n${\\cal J}(y)$, as\n\\begin{equation}\n{\\cal J}(y)=\\int {d\\vec{h}\\, d\\vec{h}'\\over\n(2\\pi)^{nd}}e^{-i\\vec{h}\\cdot \\vec{h}'} e^{-\\beta v \\Delta\nw_y\\bigl(-i\\frac{\\partial}{\\partial\\vec{h}'}\\bigr)}\\int\\tilde{\\cal\nD}E\\,e^{-(\\beta/2)\\int dx\\, \\vec{E}(x)\\cdot \\tilde{M} \\cdot\n\\vec{E}(x)+i\\vec{h}'\\cdot \\vec{E}(y)},\n\\end{equation}\nwhere $\\tilde{M}$ is the matrix defined from the replica-coupling\nmatrix $M$ in $w_0$ by $\\tilde{M}^{\\alpha\\gamma}_{ij}\\equiv\nM^{\\alpha\\gamma}\\delta_{ij}$. After an integration over the fields $E$\nand $\\phi$ implied in the measure $\\tilde{\\cal D}E$ (which can be\neasily done using the Fourier components of $\\phi$, and with $y=0$\nsince (\\ref{oneimp}) is independent of $y$), $\\cal J$ reads, up to\ninessential factors \\cite{NOTE2}:\n\\begin{equation}\n{\\cal J}(y)=e^{-(\\beta/2)\\sum_{\\alpha\\gamma}M^{\\alpha\\gamma}E_0^2}\n\\int {d\\vec{h}\\, d\\vec{h}'\\over (2\\pi)^{nd}}e^{-i\\vec{h}\\cdot \\vec{h}'}\ne^{-v\\beta\\Delta w_y\\bigl(-i\\frac{\\partial}{\\partial \\vec{h}'}\\bigr)}\ne^{i \\vec{h}'\\cdot \\vec{E}_0-\\vec{h}'\\cdot \\tilde{M}^{-1}\n\\cdot \\vec{h}'/(2\\beta v d)}.\n\\end{equation}\nFormally expanding $\\exp(-v\\beta\\Delta w_y)$ in powers of \n$-i\\partial/\\partial \\vec{h}'$, and carrying out successive \nintegrations by parts over $\\vec{h}'$ yields\n\\begin{equation}\n{\\cal J}(y)=\\left[\\mathop{\\text{Det}}(M)\\left(\\frac{v\\beta\nd}{2\\pi}\\right)^n\\right]^{d/2}\ne^{-(\\beta/2)\\sum_{\\alpha\\gamma}M^{\\alpha\\gamma}E_0^2}\\int d\\vec{h}\\,\ne^{-(v \\beta d/2)(\\vec{E}_0-\\vec{h})\\cdot\n\\tilde{M}\\cdot(\\vec{E}_0-\\vec{h})-v\\beta\\Delta w_y(\\vec{h})},\n\\end{equation}\nwhere the determinant is evaluated in replica space. Finally, \n${\\cal I}(y)={\\cal J}(y)/{\\cal J}(y;\\Delta w_y=0)$:\n\\begin{equation}\n\\label{iy}\n{\\cal I}(y)=\\left[\\mathop{\\text{Det}}(M)\\left(\\frac{v\\beta\nd}{2\\pi}\\right)^n\\right]^{d/2}\\int \\prod_\\alpha dh^\\alpha \\,\ne^{-v\\beta\\left\\{{d\\over 2}\n\\sum_{\\alpha\\gamma}M^{\\alpha\\gamma}(E_0-h^\\alpha)_i\n(E_0-h^\\gamma)_i+\\Delta w_y[h]\\right\\}}.\n\\end{equation}\nFor any $\\Delta w_y$, this integral over the replicated vector field\n$h$ can be computed exactly using a saddle-point method \\cite{NEGE87}\nin the limit $\\beta\\to\\infty$, as announced. This allows for a\npossible extension of the theory to nonlinear media in the\n``one-impurity'' approximation. Here, for the linear problem at hand,\nEq.\\ (\\ref{iy}) is a simple gaussian integral. Setting\n$\\Delta\\sigma=\\sigma-\\sigma_0$ and\n\\begin{equation}\n\\mu=\\left(1+\\frac{\\Delta\\sigma}{d\\sigma_0}\\right)^{-1},\n\\end{equation}\nwe obtain\n\\begin{equation}\n\\ln{\\cal I}(y)=\\left[-\\frac{\\beta v}{2}\\Delta\\sigma\\,\\mu E_0^2\n+\\frac{d}{2}(\\ln \\mu-\\beta v q \\sigma\\mu E_0^2/d)\\right]n+O(n^2),\n\\end{equation}\nfrom which follows (\\ref{dwoi}).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Calculation in the ``cumulant series'' approximation}\n\\label{co}\nWe have to compute $\\left\\langle {\\cal H}_e\\right\\rangle_0$ and \n$\\left\\langle {\\cal H}_0\\right\\rangle_0$ in Equ.\\ (\\ref{dwsa}).\nThe calculation of $\\left\\langle {\\cal H}_0\\right\\rangle_0$ is easy\nwith the methods already employed, and yields\n\\begin{equation}\n\\lim_{n\\to 0}\\left\\langle \n{\\cal H}_0\\right\\rangle_0/n =\\frac{1}{2}\\sigma_0 E_0^2.\n\\end{equation}\nAs to $\\left\\langle {\\cal H}_e\\right\\rangle_0$, \nwe first expand ${\\cal H}_e$ (Eq.\\ (\\ref{calf})) in the cumulants\n$C_k$ of the disorder averages of $\\sigma(x)$, according to their\ndefinition by the generating funtion ($X$ is a generic expansion\nvariable)\n\\begin{equation}\n\\ln\\left<e^{X\\sigma}\\right>=\\sum_{k\\ge 1} {X^k\\over k!}C_k(\\sigma).\n\\end{equation}\nWe therefore have:\n\\begin{equation}\n\\label{fexpand}\n{\\cal H}_e=-{1\\over \\beta}\\sum_{\\bf x}\\sum_{k\\ge 1}{1\\over k!}\n\\left[-{\\beta v\\over 2}\\sum_\\alpha {E^\\alpha}({\\bf x})^2\\right]^k\nC_k(\\sigma).\n\\end{equation}\nWe deduce that\n\\begin{equation}\n\\label{fob}\n{1\\over n}\\left\\langle{\\cal H}_e\\right\\rangle_0=-{1\\over V\\beta}\n\\sum_{\\bf x}\\sum_{k\\ge\n1}{(-\\beta v)^k\\over k!}  C_k(\\sigma)\\,{\\cal C}_k(E^2/2),\n\\end{equation}\nwhere\n\\begin{equation}\n\\label{calck}\n{\\cal C}_k(E^2/2)={1\\over n} \n\\left\\langle \\left[\\sum_\\alpha {E^\\alpha(x)}^2/2\\right]^k\n\\right\\rangle_0\n\\end{equation}\n(because of statistical homogeneity, these coefficients do not depend\non the position variable $x$). It is convenient to introduce the\nfollowing generating function ${\\cal Z}(X)$ in order to compute the ${\\cal C}_k$:\n\\begin{eqnarray}\n{\\cal Z}(X)&=&\\sum_{k\\geq 1} {(-X)^k\\over k!}{\\cal C}_k(E^2/2)\n\\nonumber\\\\\n&=&{1\\over n} \\left\\{\\left\\langle\\exp\\left[-{1\\over 2}X \n\\sum_\\alpha{E^\\alpha}^2(x)\\right]\n\\right\\rangle_0-1\\right\\}\n\\nonumber\\\\ \n&=&{1\\over n}\\ln\\left\\langle\\exp\n\\left[-{1\\over 2}X \\sum_\\alpha{E^\\alpha}^2(x)\\right]\n\\right\\rangle_0+O(n).\n\\end{eqnarray}\nSetting $A^{\\alpha\\gamma}=\\delta_{\\alpha\\gamma}+(X/v\\beta d) [M^{-1}]^{\\alpha\\gamma}$, we obtain \\cite{NOTE2}\n\\begin{equation}\n\\label{zx}\n{\\cal Z}(X)=-{1\\over 2n} \\left\\{d\\mathop{\\text{Tr}}\n\\mathop{\\text{Ln}} A+X E_0^2\n\\sum_{\\alpha\\gamma} [A^{-1}]^{\\alpha\\gamma}\\right\\}+O(n)\n\\end{equation}\n(the trace and the logarithm act in the replica space).\n\nExpanding (\\ref{zx}) in powers of $X$ then allows for the identification\n\\begin{equation}\n{\\cal C}_k(E^2/2)={k!\\over 2}\\left({1\\over v\\beta d}\\right)^k \\frac{d}{n}\\left[{1\\over k}\\mathop{\\text{Tr}} (M^{-k})+{v\\beta d} E_0^2 \\sum_{\\alpha\\gamma} [M^{1-k}]^{\\alpha\\gamma}\\right]+O(n).\n\\end{equation}\nUse of this expression in (\\ref{fob}) cancels the convergence factor\n$k!$: we reintroduce it by inserting the identity\n\\begin{equation}\n{1\\over m!}\\int_0^\\infty du\\, e^{-u} u^m =1,\n\\end{equation}\napplied to $m=k-1$ and $m=k$ in the resulting cumulant series. This\npermits its Borel summation, which brings in the functions $h_m(x)$\ndefined by (\\ref{hm}). This results in \n\\begin{equation}\n\\label{fmfo}\n{1\\over n}\n\\langle{\\cal H}_e\\rangle_0\n=-{1\\over n}\n\\left[ \n{d\\over 2}E_0^2\n\\sum_{\\alpha\\gamma}\\left[ M\nh_0(M^{-1}/d)\\right]^{\\alpha\\gamma}\n+{1\\over 2 v \\beta}\\mathop{\\text{Tr}}\\, h_{-1}(M^{-1}/d)\n\\right]+O(n),\n\\end{equation}\nwhere we defined the family of functions\n\\begin{equation}\n\\label{hm}\nh_m(z)=\\int_0^\\infty du\\,u^m e^{-u} \\ln\\left\\langle e^{-u\\sigma\nz}\\right\\rangle\\qquad(m>-2).\n\\end{equation}\nNote for further use that\n\\begin{equation}\n\\label{deriv}\nh_m'(z)={1\\over z}\\left[h_{m+1}(z)-(k+1)h_{m}(z)\\right].\n\\end{equation}\n\nFor $M$ given by (\\ref{matmok}), the differents terms in (\\ref{fmfo}) are\n\\begin{eqnarray}\n&&\\lim_{n\\to 0}{1\\over n} \\sum_{\\alpha\\gamma} \\left[M\nh_0(M^{-1}/d)\\right]^{\\alpha\\gamma}=\\sigma_0 h_0\n\\bigl(1/(d\\sigma_0)\\bigr),\n\\nonumber\\\\ \n&&\\lim_{n\\to 0}{1\\over n}\\mathop{\\text{Tr}}\nh_{-1}(M^{-1}/d)=dh_{-1}\\bigl(1/(d\\sigma_0)\\bigr)+v\\beta\\, d\\sigma_0 q\\, h_0 \\bigl(1/(d\\sigma_0)\\bigr)E_0^2.\n\\end{eqnarray}\nwhich leads to Eq.\\ (\\ref{fmfodeu}).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{references}\n\\bibitem{BRUG35} D.~A.~G.~Bruggeman, Ann.\\ Physik (Leipzig) \n{\\bf 24}, 636 (1935).\n\n\\bibitem{LAND52} R.~Landauer, J.~Appl.~Phys. {\\bf 23}, 779 (1952); \nalso, in {\\it Electical Transport and Optical Properties of \nInhomogeneous Media}, edited by J.~C.~Garland and D.~B.~Tanner. \nAIP Conf.~Proc.~No.\\ 40 (AIP, New York, 1978). \n\n\\bibitem{KIRK71} S.\\ Kirkpatrick, Phys.\\ Rev.\\ Lett. {\\bf 27}, \n1722 (1971); Rev.\\ Mod.\\ Phys. {\\bf 45}, 574 (1973).\n\n\\bibitem{CLER90} J.~P.~Clerc, G.~Giraud, J.~M.~Laugier, and\nJ.~M.~Luck, Adv.\\ Phys. {\\bf 39}, 191 (1990).\n\n\\bibitem{STAU92} D.\\ Stauffer and A.\\ Aharony, \n{\\em Introduction to Percolation Theory} (Taylor \\& Francis, London, 1992). \n\n\\bibitem{SAHI98} M.\\ Sahimi, Phys.\\ Rep. {\\bf 306}, 213 (1998), \nand references therein.\n\n\\bibitem{MILT85} G.\\ W.\\ Milton, Commun.\\ Math.\\ Phys. {\\bf 99}, 463\n(1985).\n\n\\bibitem{MILL69} M.~N.~Miller, J. Math. Phys. {\\bf 12}, 1057 (1971).\n\n\\bibitem{STIN73} R.~B.~Stinchcombe, J.\\ Phys.\\ C {\\bf 6}, L1 (1973).\n\n\\bibitem{STRA74} J.~P.~Straley, J.\\ Phys.\\ C {\\bf 9}, 783 (1976). \n\n\\bibitem{NOTE1} This is because the key ingredient of the continuum \ntheory, namely the Green function $\\sum_k k_i k_j/k^2$ (computed at $x=0$ \nin the calculations of this paper, cf.\\ \\cite{NOTE2}), \nhas the same low-momentum structure as its counterpart on an \nhypercubic lattice (see, e.g.\\ Ref.\\ \\cite{LUCK91}).\n\n\\bibitem{STEP77} M.~J.~Stephen, Phys.\\ Rev.\\ B {\\bf 17}, 4444 (1977).\n\n\\bibitem{HORI75} M.~Hori and F.~Yonezawa, J.\\ Math.\\ Phys.  {\\bf 16},\n352 (1975).\n\n\\bibitem{BERG81} D.~J.~Bergman and Y.~Kantor, J.\\ Phys.\\ C {\\bf 14},\n3365 (1981).\n\n\\bibitem{LUCK91} J.~M.~Luck, Phys.\\ Rev.\\ B {\\bf 43}, 3933 (1991).\n\n\\bibitem{HORI77} M.~Hori, J. Math. Phys. {\\bf 18}, 487 (1977).\n\n\\bibitem{BART93} M.~Barth\\'el\\'emy and H.~Orland, J.\\ Phys.\\ I\n(France) {\\bf 3} 2171 (1993).\n\n\\bibitem{BART98} M.~Barth\\'el\\'emy and H.~Orland, Eur.\\ Phys.\\ J.\\ B\n{\\bf 6} 537 (1998), cond-mat/9806302.\n\n\\bibitem{BLUM91} R.~Blumenfeld and D.~J.~Bergman, Phys.\\ Rev.\\ B {\\bf\n44}, 7378 (1991); D.~J.~Bergman and R.~Blumenfeld, Phys.\\ Rev.\\ B {\\bf\n54}, 7378 (1996).\n\n\\bibitem{WILL86} J.~R.~Willis, in {\\it Homogeneization and Effective Moduli \nof Materials and Media}, edited by J.~L.~Ericksen {\\it et al.} \n(Springer-Verlag, New York, 1896), p.\\ 247; D.~R.~S.~Talbot and J.~R.~Willis, \nIMA J.\\ Appl.\\ Math. {\\bf 39}, 215 (1987).\n\n\\bibitem{SANC87} E.\\ Sanchez-Palencia and A.\\ Zaoui eds.\\, \n{\\em Homogeneization Techniques for Composite Media. Proceedings, Udine, \nItaly 1985}, Lecture notes in Physics {\\bf 272} (Springer-Verlag, Berlin, \n1987), and references therein.\n\n\\bibitem{PONT92b} P.~Ponte Casta\\~neda, SIAM J.\\ Appl.\\ Math. {\\bf\n52}, 1321 (1992).\n\n\\bibitem{EDWA75} S.~F.~Edwards and P.~W.~Anderson, J.\\ Phys.\\ F {\\bf\n5} 965 (1975).\n\n\\bibitem{MEZA87} M.~M\\'ezard, G.~Parisi, and M.~Virasoro, {\\it\nSpin Glass Theory and Beyond} (World Scientific, Singapore, 1987).\n\n\\bibitem{BERG92} D.~J.~Bergman and D.~Stroud, Solid State Phys.  {\\bf\n46}, 147 (1992).\n\n\\bibitem{PONT92a} P.~Ponte Casta\\~neda, G.~DeBotton, and G.~Li, Phys.\\\nRev.\\ B {\\bf 46}, 4387 (1992).\n\n\\bibitem{YU94} K.~W.~Yu, Y.~C.~Chu, and E.~M.~Y.~Chan, Phys.\\ Rev.\\ B\n{\\bf 50}, 4387 (1994).\n\n\\bibitem{PONT97} P.~Ponte Casta\\~neda and M.\\ Kailasam, Proc.\\ R.\\\nSoc.\\ London A {\\bf 453}, 793 (1997).\n\n\\bibitem{NOTE2} Integration is performed over the independant scalars \n$\\phi_k$ and $\\phi_{-k}$ with $1/(2v)$ such couples of Fourier modes \ninvolved. Use is made in the calculations of the \nequality $1/v=\\sum_k 1\\simeq\\int dk /(2\\pi)^d$, with an \nupper cut-off on the $k$ implied. In particular, one appeals \nto the formula $\\sum_k k_i k_j/k^2=\\delta_{ij}/(dv)$.\n\n\\bibitem{BERG78} D.~J.~Bergman, Phys.\\ Rep. {\\bf 43}, 377 (1978).\n\n\\bibitem{HASH62} Z.~Hashin and S.~Shtrikman, J.\\ Appl.\\ Phys. \n{\\bf 33}, 3125 (1962).\n\n\\bibitem{WRIG86} D.\\ C.\\ Wright, D.\\ J.\\ Bergman, and Y.\\ Kantor, \nPhys.\\ Rev.\\ B {\\bf 33}, 396 (1986), and references therein.\n\n\\bibitem{STRA77} J.\\ P.\\ Straley, Phys.\\ rev.\\ B {\\bf 15}, 5733\n(1977).\n\n\\bibitem{GOLD90} K.\\ Golden, Phys.\\ Rev.\\ Lett. {\\bf 65}, 2923 (1990).\n\n\\bibitem{PARI84} G.~Parisi, in {\\it Les Houches, Session XXXIX , 1982 -- \nD\\'eveloppements R\\'ecents en Th\\'eorie des Champs et M\\'ecanique \nStatistique / Recent Advances in Field Theory and Statistical Mechanics}, \nedited by  J.-B.\\ Zuber and R.~Stora (North Holland, Amsterdam, 1984), \npp.\\ 473--523.\n\n\\bibitem{NEGE87} J.~W.~Negele and H.~Orland, \n{\\it Quantum Many-Particle Systems} (Addison-Wesley, New York, 1987).\n\\end{references}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%  FIGURES\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n\\twocolumn\n%\n\\begin{figure}\n\\narrowtext\n\\vspace*{0.0cm}\n\\centerline{\n\\epsfysize=0.9\\columnwidth{\\rotate[r]{\\epsfbox{fig1_c.eps}}}}\n\\vspace*{0.3cm}\n\\caption{Rescaled effective conductivities in dimension $d=2$ \nfor a binary medium, versus the volume concentation $p$ of \ncomponent 2. The conductivity ratio is $\\sigma_2/\\sigma_1=10$. \nHighest and lowest solid curves: Hashin-Shtrikman bounds; Br.: \nthe Bruggeman formula (``type 1'', one-impurity \napproximation -- OI); HY: the Hori-Yonezawa formula (``type 1'',\ncumulant series approximation -- CS); both ``type 2'' curves \nare the new formulas, within OI and CS approximations. \n}\n\\label{fig1} \n\\end{figure} \n\n\\begin{figure}\n\\narrowtext\n\\vspace*{0.0cm}\n\\centerline{\n\\epsfysize=0.9\\columnwidth{\\rotate[r]{\\epsfbox{fig2_c.eps}}}}\n\\vspace*{0.3cm}\n\\caption{Rescaled effective conductivities in dimension $d=2$ \nfor a binary medium, versus the volume concentation $p$ of \ncomponent 2. The conductivity ratio is $\\sigma_2/\\sigma_1=1000$.\nSame plots as in Fig.\\ \\ref{fig1}.\n}\n\\label{fig2}\n\\end{figure}\n\n\\begin{figure}\n\\narrowtext\n\\vspace*{0.0cm}\n\\centerline{\n\\epsfysize=0.9\\columnwidth{\\rotate[r]{\\epsfbox{fig3_c.eps}}}}\n\\vspace*{0.3cm}\n\\caption{Rescaled effective conductivities in dimension $d=3$ \nfor a binary medium, versus the volume concentation $p$ of \ncomponent 2. The conductivity ratio is $\\sigma_2/\\sigma_1=10$.\nSame plots as in Fig.\\ \\ref{fig1}.\\\\\n\\\\\n\\\\\n\\\\\n}\n\\label{fig3}\n\\end{figure}\n\n\\begin{figure}\n\\narrowtext\n\\vspace*{0.0cm}\n\\centerline{\n\\epsfysize=0.9\\columnwidth{\\rotate[r]{\\epsfbox{fig4_c.eps}}}}\n\\vspace*{0.3cm}\n\\caption{Rescaled effective conductivities in dimension $d=3$ \nfor a binary medium, versus the volume concentation $p$ of \ncomponent 2.The conductivity ratio is $\\sigma_2/\\sigma_1=1000$.\nSame plots as in Fig.\\ \\ref{fig1}.\n}\n\\label{fig4}\n\\end{figure}\n\n\\begin{figure}\n\\narrowtext\n\\vspace*{0.0cm}\n\\centerline{\n\\epsfysize=0.9\\columnwidth{\\rotate[r]{\\epsfbox{fig5_c.eps}}}}\n\\vspace*{0.3cm}\n\\caption{Relative quadratic fluctuations of the field in dimension\n$d=3$ for a binary medium, versus the volume concentation $p$ of\ncomponent 2. The conductivities are $\\sigma_1=1$, $\\sigma_2=1000$.\n}\n\\label{fig5}\n\\end{figure}\n\n\\begin{figure}\n\\narrowtext\n\\vspace*{0.0cm}\n\\centerline{\n\\epsfysize=0.9\\columnwidth{\\rotate[r]{\\epsfbox{fig6_b.eps}}}}\n\\vspace*{0.3cm}\n\\caption{Rescaled effective conductivity \n$\\sigma_{\\text{eff}}(\\sigma_0)/\\sigma_1$, and reduced\nreplica coupling parameter $q(\\sigma_0)$ vs.\\ $\\sigma_0$ in\ndimension $d=3$ for a binary medium. In this exemple computed \nfrom Eqs.\\ (\\ref{sigefq}), (\\ref{qbrug}), the conductivity ratio is \n$\\sigma_2/\\sigma_1=100$, and the volume fraction $p$ of \ncomponent 2 is $p=0.18$. The ``type 1'' effective conductivity is\nobtained when $q=0$, whereas the ``type 2'' effective conductivity\ncorresponds to the maximum of the curve $\\sigma_{\\text{eff}}(\\sigma_0)$.\n}\n\\label{fig6}\n\\end{figure}\n\n\\end{document}\n", "meta": {"hexsha": "af793ea281679dc4d84b61d6c0b6d09796972bab", "size": 67081, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "benchmark-generator/tex-paragraph-parser/src/test/resources/input3.tex", "max_stars_repo_name": "ckorzen/pdf-text-extraction-benchmark", "max_stars_repo_head_hexsha": "47b456f7c5c445b5087200d2ce4051647a9cbbf6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 34, "max_stars_repo_stars_event_min_datetime": "2018-05-16T17:50:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-12T19:40:40.000Z", "max_issues_repo_path": "benchmark-generator/tex-paragraph-parser/src/test/resources/input3.tex", "max_issues_repo_name": "e-sim/pdf-text-extraction-benchmark", "max_issues_repo_head_hexsha": "42eede9867e5795a6fc040b0a7ce92da3ddd3120", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-06-20T10:31:15.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-08T20:10:16.000Z", "max_forks_repo_path": "benchmark-generator/tex-paragraph-parser/src/test/resources/input3.tex", "max_forks_repo_name": "e-sim/pdf-text-extraction-benchmark", "max_forks_repo_head_hexsha": "42eede9867e5795a6fc040b0a7ce92da3ddd3120", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2018-07-07T15:37:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T07:06:27.000Z", "avg_line_length": 42.2690611216, "max_line_length": 191, "alphanum_fraction": 0.7092023077, "num_tokens": 21837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3375922157911054}}
{"text": "\\documentclass[conference]{IEEEtran} \n%\\usepackage{babel}\n\\IEEEoverridecommandlockouts\n% The preceding line is only needed to identify funding in the first footnote. If that is unneeded, please comment it out.\n\\usepackage{cite}\n\\usepackage{amsmath,amssymb,amsfonts}\n\\usepackage{algorithmic}\n\\usepackage{graphicx}\n\\usepackage{textcomp}\n\\usepackage{xcolor}\n\\def\\BibTeX{{\\rm B\\kern-.05em{\\sc i\\kern-.025em b}\\kern-.08em\n    T\\kern-.1667em\\lower.7ex\\hbox{E}\\kern-.125emX}}\n\\usepackage{hyperref}\n\\usepackage[space]{grffile}\n\\usepackage[margin=2.5cm]{geometry}\n\\usepackage{pdfpages}\n%\\usepackage{graphicx}\n\\usepackage[capitalize,noabbrev]{cleveref}\n\n%\\documentclass[a4paper]{paper} \n%\\usepackage{babel}\n%\\usepackage{hyperref}\n%\\usepackage{amsfonts}\n%\\usepackage{amsmath}\n%\\usepackage{graphicx}\n%\\usepackage[space]{grffile}\n%\\usepackage[margin=2.5cm]{geometry}\n%\\usepackage{pdfpages}\n%\\usepackage{graphicx}\n%\\usepackage[capitalize,noabbrev]{cleveref}\n\n\\graphicspath{{img/}}\n\\title{Lightning Network imbalance measure and proactive channel rebalancing algorithm}\n%\\title{Imbalance measure and proactive channel rebalancing algorithm for the Lightning Network}\n\\begin{document} \n\n\\author{\\IEEEauthorblockN{1\\textsuperscript{st} Rene Pickhardt}\n\\IEEEauthorblockA{\\textit{Department of Computer Science} \\\\\n\\textit{Norwegian University of Science and Technology}\\\\\nGj{\\o}vik, Norway \\\\\nrene.m.pickhardt@ntnu.no}\n\\and\n\\IEEEauthorblockN{2\\textsuperscript{nd} Mariusz Nowostawski}\n\\IEEEauthorblockA{\\textit{Department of Computer Science} \\\\\n\\textit{Norwegian University of Science and Technology}\\\\\nGj{\\o}vik, Norway \\\\\nmariusz.nowostawski@ntnu.no}\n}\n\n\\maketitle\n\\begin{abstract}\nMaking a payment in a privacy-aware payment channel network can be achieved by trying out several payment paths until one succeeds.\nWith a large network, such as the Lightning Network, a completion of a single payment can take up to several minutes.\nWe introduce a network imbalance measure and formulate the optimization problem of improving the balance of the network as a sequence of rebalancing operations of the funds within the channels along circular paths within the network.\nAs the funds and balances of channels are not globally known, we introduce a greedy heuristic\nthat improves every node's local balance despite the uncertainty.\nIn an empirical simulation on a snapshot of the Lightning Network we demonstrate that the imbalance distribution of the network has a Kolmogorov-Smirnoff distance of $0.74$ in comparison to the imbalance distribution after the heuristic is applied.\nWe further show that the success rate of a single unit payment increases from $11.2\\%$ on the imbalanced network to $98.3\\%$ in the balanced network.\nSimilarly, the median possible payment size across all pairs of participants increases from $0$ to $0.5$ mBTC for initial routing attempts on the cheapest possible path.\nExecuting $4$ different strategies for selecting rebalancing cycles lead to similar results \nindicating that a collaborative approach within the friend of a friend network might be preferable from a practical point of view.\\footnote{A full version of this text - including a discussion about fee free rebalancing - is available at: \\url{https://arxiv.org/abs/1912.09555}}\n\n\\end{abstract}\n\\begin{IEEEkeywords}\nimbalance, rebalancing, optimization, Bitcoin, Lightning Network, payment channel networks, path finding, routing, liquidity, flow control, congestion control, game theory, uncertainty, simulations, collaborative problem solving, privacy \n\\end{IEEEkeywords}\n\n%==========================================================================\n\\section{Introduction}\nThe Lightning Network has been introduced in order to mitigate the scaling issues of blockchain technologies such as Bitcoin\\cite{poon2016bitcoin} by creating a network of payment channels.\nIn order to protect users privacy while routing a payment through several payment channels privacy a payment network can use a source-based onion routing scheme, like the Sphinx Mix format~\\cite{danezis2009sphinx}.\nWhile the Lightning Network, for example, shares the capacity of public channels with its participants through its gossip protocol, the local split of the capacity of the channels into the balance of its participants is not shared with the rest of the network for two reasons:\n(1) this would compromise the privacy as one could collect all changes of the channel balances and reconstruct the flow of payments;\n(2) propagating this information would essentially mean that every node in the network is made aware of every payment which would have the same poor scaling properties as blockchain technology and other broadcast networks.\nThe decision to use source-based routing together with the unknown channel balances of the network results in a challenge for finding a path of payment channels so that all channels along the path have enough liquidity to be able to forward an attempted payment.\nCurrently, this challenge is met by probing paths until one succeeds.\nIt has been demonstrated that probing for paths can take more than 3 minutes for more than $5\\%$ of the attempted payments~\\cite{decker2019lnconf}. This leads to a poor payment latency and poor user experience.\nImagine a grocery store in which for every $20^{th}$ customer the cash register would have to wait three minutes until the payment was received.\n\nThis study examins the consequences of nodes proactively and collaboratively distributing their funds evenly across their channels.\nWe introduce the notation of an imbalanced network.\nThe imbalance is measured as the average of the imbalance scores of its nodes.\nThe node's imbalance of payment channels is defined as the Gini coefficient of a node's channel balance coefficients which are the relative amount of funds a node owns in a channel in comparison to the capacity of that channel.\nNodes can reduce their imbalance either by initiating a rebalancing their own channels themselves, or, by collaboratively rebalancing the channels with the help of their channel partners by conducting circular payments.\n\nWe formulate an optimization problem of finding a sequence of rebalancing operations that minimize the network's imbalance.\nAs the information necessary to solve the optimization problem is not publicly known in privacy-aware payment channel networks, we provide a greedy heuristic for its participants to find a minimum for the problem. \nIn an empirical study, we show that the greedy heuristic will lead to a success rate of $98.3\\%$ for a small payment between two arbitrary selected nodes.\nAlso the median possible payment size between all pairs of nodes increases from $0$ in the imbalanced network to $0.5$ mBTC in the best balanced networks that we found.\n\nLooking at different strategies of finding rebalancing cycles we suggest, for the sake of speed, that nodes share with their neighbors on which local channels they would like to have inbound or outbound capacity.\nThis information could easily be probed anyway and will not to worsen the privacy of the nodes involved in rebalancing.\n\n%==========================================================================\n\\section{Related Work}\n\\label{sec:relatedWork}\n\nWhile the Lightning Network white paper~\\cite{poon2016bitcoin} does not discuss path finding and states routing as an easy problem it is generally recognized that pathfinding on the Lightning Network is a difficult problem~\\cite{piatkivskyi2018split, prihodko2016flare, bagaria2019boomerang, pickhardt2019pathfinding, grunspan2018ant, sivaraman2018routing}.\nThere is already research conducted in the field of rebalancing channels~\\cite{khalil2017revive},which was about the cryptographic protocols used to make sure that participants can enforce the rebalancing that was agreed upon.\nThere are rebalancing operations for existing lightning implementations: c-lightning\\footnote{\\url{https://github.com/lightningd/plugins/tree/master/rebalance}} and for lnd\\footnote{\\url{https://github.com/bitromortac/lndmanage}}.\nIn particular, the idea of just in time rebalancing while fulfilling routing requests~\\cite{pickhardt2019jit} has been implemented as JIT-routing for c-lightning\\footnote{\\url{https://github.com/lightningd/plugins/pull/66}}. \n\n% ===========================================================================\n\\section{Formalization and Assumptions}\n\\label{sec:formalization}\n\nLet $N=(V,E,c)$ be a payment channel network with a finite set of nodes.\nThe payment channels are the edges in the network such that $E\\subset V\\times V$.\nAdditionally, we have a publicly known capacity function $c: E\\longrightarrow \\mathbb{N}$ that assigns a capacity to every edge of the network.\nFor every edge $e=(u,v)$ we denote $e_u:=(e,u)$ as the first participant of the channel and $e_v=(e,v)$ as the second participant.\nNaturally, the capacity of every channel $e=(u,v)$ is privately split into the local balances with the balance function $b: E\\times V\\longrightarrow\\mathbb{N}$ such that $b(e_u)+b(e_v)\\stackrel{!}{=}c(e)$.\n\nWe define the channel balance coefficient for $u$ on the channel $e=(u,v)$ as  $\\zeta_{(u,v)} = \\frac{b(e_u)}{c(e)}$.\nThis is just the relative amount of funds that the participant $u$ has in the channel $e$.\nIn general, for an imbalanced chanel we have $\\zeta_{(u,v)} \\neq \\zeta_{(v,u)}$.\n\nThe neighbor function $n : V \\longrightarrow 2^{E}$ assigns every node a set of all the channels it is part of.\nWe call $U:=n(u)$ the neighborhood of node $u$.\n\nThe total funds of a participant $u$ are denoted as $\\tau_u:=\\displaystyle{\\sum_{e\\in U}b(e_u)}$.\nThe value of $\\tau_u$ is constant while no payments are made and no channels are being opened and closed.\nThe balance function $b$ can vary.\nThe total capacity of a participant $u$ is denoted as $\\kappa_u:=\\displaystyle{\\sum_{e\\in U}c(e)}$.\nUsing the last two definitions let us define the node balance coefficient for a participant $u$ as $\\nu_u = \\frac{\\tau_u}{\\kappa_u}$.\n\nWe call a node $u$ {\\bf balanced} if its channel balance coefficients $\\zeta_{(u,v_1)},\\dots,\\zeta_{(u,v_d)}$ have the same value.\\footnote{This value does not have to take a value of $0.5$, but it certainly is a reasonable goal.}\nConsequently, we consider a node {\\bf unbalanced}, if its local channel balance coefficients are unequal.\nStatistically, inequality of a distribution can be measured with the Gini coefficient.\nThus, for a node $u$ with channel balance coefficients $\\zeta_{(u,v_1)},\\dots,\\zeta_{(u,v_d)}$ we define $G_u = \\frac{\\displaystyle{\\sum_{i\\in U} \\sum_{j \\in U}} | \\zeta_i - \\zeta_j |}{2 \\displaystyle{\\sum_{i \\in U} \\sum_{j \\in U} \\zeta_j}}$.\nIf $G_u = 0$ this means that the channel balance coefficients are equal.\nThis value will be exactly the same as the node's balance coefficient $\\nu_u$.\nIn contrast, if $G_u = 1$ the channel balance coefficients are distributed in the most unequal way.\n\nFinally, $G$ denotes the imbalance of the network $G = \\displaystyle{\\frac{1}{|V|}\\sum_{v\\in V}G_v}$. It is the mean of the imbalance values of all nodes in the network.\nA perfectly balanced network would be achieved if $G$ takes the value of $0$ whereas the balance is poor if the value of $G$ is close to 1.\nOur goal is to find a balance function $b$ which minimizes $G$ given a privacy aware payment channel network with initial distribution of funds $\\tau_{u_1},\\dots,\\tau_{u_n}$.\nThe constraint to this optimization problem is that the total funds $\\tau_u$ are fixed for every node $u \\in V$ and any choice of the balance function $b$.\nAs we lack knowledge about the global network state, we cannot apply standard optimization techniques such as gradient descent, conjugate gradient methods or simulated annealing.\nWe suggest to use a greedy heuristic in which every participant executes some operations to improve its own balance which others support if it also improves their balance.\n\n\\subsection{Description of the rebalancing algorithm}\n\\label{sec:Greedy Rebalancing Heuristic}\n\nParticipants use the local knowledge and make local adjustments trying to solve the optimization problem of finding $b$ such that $G$ is minimized.\n\\begin{enumerate}\n\\item A node $u$ computes its node balance coefficient $\\nu_u$.\n\\item $u$ then computes its channel balance coefficients $\\zeta_{(u,v_1)},\\dots,\\zeta_{(u,v_d)}$.\n\\item All channels $e=(u,v_i)$ for which the channel balance coefficient is higher \nthan its node balance coefficient, are selected as $C = \\{(u,v_i) | \\zeta_{(u,v_i)} - \\nu_u\\ > 0\\}$.\\footnote{\n  Note, that we do not need to take absolute values as $u$ will only be able to initiate a rebalancing operation by sending money which means decreasing its channel balance coefficient of $\\zeta_{(u,v_i)}$ towards $\\nu_u$.}.\n\\item From the candidate set $C$ a random channel $e=(u,v)$ is selected.\n\\item Now the node searches for a circular payment to itself along $e=(u,v)$ by choosing a path $p = [v,x_1,\\dots,x_n,u]$. The amount of that payment should decrease the value of $\\zeta_{(u,v)}$ to that of $\\nu_u$ and can be computed as $a = c(e)\\cdot (\\zeta_{(u,v)}-\\nu_u)$. The end of the circle should be a channel $(x_n,u)$ for which the channel balance coefficient $\\zeta_{(u,x_n)}$ is smaller than the node balance coefficient $\\nu_u$.\\footnote{In one of the experiments we weaken this strong criteria and show empirically that it makes sense to drop it for the benefit of easier path finding at the cost of small oscillations of the algorithm.}\n\\item The node conducts the payment if all the nodes on the path $p$ agree to participate. It could happen that some nodes will only participate with a value smaller than $a$. As this is already progress $u$ will accept the suggested amount instead of being stubborn. \n\\item Repeat all steps as long as the local balance coefficients are not even enough and as long as paths are found.\n\\end{enumerate}\n\n\\section{Experimental Setup}\n\\label{sec:setup}\n\nWe evaluated $4$ different strategies for finding rebalancing cycles. \\texttt{cycles4} tests all cycles of length $4$ or smaller. In the same way \\texttt{cycle5} tests all cycles of length $5$ or smaller. \\texttt{foaf} tests most cycles of the friend of a friend network.\\footnote{This approximation is achieved by using \\texttt{cycle4} as a cycle base as all cycles of length 4 and smaller certainly are part of the friend of a friend network.}\n\\texttt{mpp} is short for multi-path payments and uses the same heuristic as \\texttt{foaf} but will only take a $20^{th}$ of the maximum possible amount for rebalancing operation since it is supposed to split the rebalancing over various cycles.\nOur approximation for \\texttt{foaf} and \\texttt{mpp} explains why the final results for these two strategies are not entirely monotonic but oscillating a bit.\n\nWe conducted our experiment on a snapshot of the public Lightning Network from October 2019.\nAs channels are currently almost always opened by one side\\footnote{Dual funded channels are not part of the protocol and no implementation is merged to any of the standard nodes} we randomly guessed who opened the channel by a coin flip and allocated the entire channel capacity to that node.\nAs a result the histogram of all node balance coefficients had a mode of $0.5$ which is plausible with this random process\\footnote{We refer again to the long Version of this paper for more details.}.\n\nAfter we randomly chose the founder of each channel we compute the largest strongly connected component to remove nodes which had the funds allocated in a way that would not allow any rebalancing.\nThe strongly connected component consists of $2707$ nodes and $24161$ edges.\nThe diameter of the strongly connected component had a value of 10.\nAlmost $40\\%$ of shortest paths are longer than the cycles that our strategies have tested. \nThis demonstrates that the single rebalancing operations which we conducted were not covering the entire network but only taking place within local parts of the network.\nThis is particularly true for the rebalancing in the friend of a friend network.\n\nIn order to conduct the experiments we simulated the proposed algorithm and strategies in the following way.\nFor each channel we computed up to $5000$ rebalancing cycles following the defined strategy.\nThe number $5000$ was chosen to be as large as possible so that we were able to conduct the simulation on the $16$ GB of main memory of our machine.\n\n% ==========================================================\n\\section{Results}\n\\label{sec:results}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=6cm]{code/vs/fig/imba_vs_steps.png}\n \\caption{Comparing how the imbalance score of the network behaves with the amount of successfull rebalancing operations. As the rebalancing amounts are much smaller with multi path payments the x-axis has a logarithmic scale.}\n \\label{fig:imbalancehovertime}\n\\end{figure}\n\n\\cref{fig:imbalancehovertime} confirms that the imbalance of the network is decreasing over time when running our simulation.\nThis means that the network is becoming more balanced.\nWe see that most improvement is happening quite fast with $10$k to $100$k rebalancing operations being necessary.\nThis is not more than $37$ rebalancing operations per node.\nTaking into account that the average node degree is $9$ this means that on average each node needs to successfully execute about $4$ rebalancing operations per channel.  \nThis seams plausible in the sense that every channel gets rebalanced at least once.\\footnote{Note, that due to the collaborative behaviour of nodes a node might also get its channels rebalanced in the rebalancing attempts of other nodes.}\nThe multi-path rebalancing needs more operations which makes sense as we only rebalanced for a $20^{th}$ of the possible amount in the multi-path case since we wanted to have multiple other cycles to rebalance that particular channel.\nWhile \\texttt{cycle4} improves the balance more quickly, it does not reach the minimum imbalance as well as the other strategies.\nIn particular, the algorithm converges to a local minimum rather quickly.\nOur experimental runs resulted in states that are not identical when we shuffled the order of cycles that we probed, however, the differences were negligible. \nWe guess that the local minimum might be close to global minimum of the optimization problem.\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=6cm]{code/vs/fig/imba_vs_success_rates.png}\n \\caption{Every time the imbalance score reached a new low to a two digit decimal we computed the probability for a random payment of the smallest possible amount to succeed on the cheapest path.}\n \\label{fig:imba_vs_success}\n\\end{figure}\n\nIn~\\cref{fig:imba_vs_success} we see that a lower imbalance score $G$ yields a higher success rate of payments as one would expect.\nThe success rate is measured by attempting a payment of $1$ Satoshi between all pairs of nodes and counting the relative amount of payment attempts for which the cheapest path from the source to the destination was successful.\nWe computed the success rate of every time the balance score hits a new score rounded to two decimals.\nIt is the first experiment that indicates that the defined imbalance score was well chosen. \nAgain the multi-path payment strategy sticks out as it achieves a rather high success rate while the network is still rather imbalanced.\nA success rate of $80\\%$ is reached for an imbalance score of $0.43$.\nComparing this to~\\cref{fig:imbalancehovertime} we see that about $250$k rebalance operations are necessary to achieve this success rate.\nEven the worst performing algorithm achieves this success rate with far less than $100$k rebalancing operations and a much better overall imbalance score. \n\nThis effect, while expected as multi-path rebalancing uses smaller amounts, is more pronounced in the next experiment.\nAs $1$ Satoshi payments are not too useful in a real world setting we checked if the overall amounts that can be routed increase in a better balanced network.\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=6cm]{code/vs/fig/imba_vs_median_payment_size.png}\n \\caption{The imbalance of the network is plotted against the median value of payments that can be fulfilled between all pairs of nodes on the first attempt along the cheapest path. Note that failed payments are part of the statistics and counted as payments which can send $0$ Satoshi.}\n \\label{fig:imba_vs_payment_size}\n\\end{figure}\n\n\nIn~\\cref{fig:imba_vs_payment_size} we compare the imbalance of the network with the median possible payment amount which is computed as follows:\nFor all pairs of shortest paths on the base fee graph we look at the amount that could be forwarded along that path.\nFinally we take the median of those values.\nThis means that at least $50\\%$ of payment pairs are able to forward this amount.\nAgain we see that the lower the imbalance score becomes the higher the median possible payment size gets.\nThis suggests that statistically a more balanced network is able to successfully route higher payment amounts on the first try.\nAll four strategies are achieving a median possible payment amount of roughly $50000$ Satoshi.\nThis means that in a balanced network $50\\%$ of payment pairs are able to successfully conduct a payment of $0.5$ mBTC along the cheapest path. \nThe result also indicates that the strategy for probing rebalancing cycles seems to have little to no impact to the final abilities of the network to perform payments.\n\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=6cm]{code/vs/fig/maximum_payable_amount_all_pair_chepest_paths_balanced_network.png}\n \\caption{The maximal payable amounts on all pairs of cheapest paths on the initial imbalanced network and on the network after applying the friend of a friend rebalancing strategy.}\n \\label{fig:cdf_paymentsize}\n\\end{figure}\n\nWe look a little bit closer at the data point of the most balanced network with the friend of a friend strategy and compare it to the imbalanced network.\nInstead of only looking at the median we study the cumulative distribution function of the histogram in~\\cref{fig:cdf_paymentsize}.\nWe can see that in the imbalanced network almost $88.8\\%$ of the paths are not able to forward a single Satoshi (meaning a $11.2\\%$ success rate).\nThis number drops below $1.7\\%$ (meaning a $98.3\\%$ success rate) for the balanced network.\n\nFor the friend of a friend network we examine the distribution of Gini coefficients with the initial distribution of Gini coefficients.\nWe provide the cumulative distribution function of both distributions with in~\\cref{fig:cdf_gini}.\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=6cm]{code/vs/fig/comparison distribution of Ginicoefficients.png}\n \\caption{Comparing the distribution of the node's Gini coefficients before and after rebalancing with the friend of a friend strategy.}\n \\label{fig:cdf_gini}\n \\end{figure}\n\nThe Kolmogorov-Smirnoff distance reaches a value of $0.74$.\nThis verifies the statistical significance of the rebalancing heuristic in comparison to staying with the imbalanced network.\nThe median value of the Gini coefficients in the best balanced network we could acquire is about $0.15$.\nIn comparison, on the imbalanced network the median Gini coefficient is $0.5$.\n\nOur results show that nodes do not need to strive for $\\nu_u = 0.5$ and perfect local balance of their channels in order to produce high success rate of random payments.\n\n% =========================================================================================\n\\section{Future Work}\n\\label{sec:future}\n\nAs the simulation had consumed a lot of computational resources, we have not check if the greedy heuristic is stable under concurrent payments and rebalancing operations taking place.\nIn a similar gist simulations on larger networks would be interesting but require more significant computational resources and time to be conducted.\n\nThe current experiments have assumed a stable network topology. \nHowever, every channel opening or closure, as well as every single payment, will change the imbalance of the network.\nIt is therefore necessary to study how it adapts if the topology changes in real time due to opening or closing channels as well as a reallocation of funds due to payments that are taking place.\nIn particular, it would be interesting to see how this heuristic works in combination with JIT-Routing as this would unbalance nodes to provide liquidity which our heuristic would then redistribute over the friend of a friend network.\nThis would occur along all nodes on a path in intersecting friend of a friend networks.\nIt would be interesting to see how this algorithm behaves together with Atomic Multipath Payments which are in the style of~\\cite{bagaria2019boomerang} redundant but along our results carry at most $50000$ Satoshi. \n\n\n% =======================================================================\n\\section{Discussion}\n\\label{sec:conclusion}\n\nComputing the rebalancing cycles is the most expensive operation in our simulation.\nIf the greedy heuristic is implemented in a real payment channel network, it would only be \ndone locally by each node, which in itself is not expensive.\nThis holds true if those cycles will only be searched within the friend of a friend network which is typically small.\nAs the results of the different strategies for finding cycles did not vary and for the previous reason we propose to stick to rebalancing in the friend of a friend network and introducing a communications protocol between nodes to collaboratively find such rebalancing cycles by sharing some information.\n\n\n% ==========================================================================================\n\\section{Acknowledgements}\n\\label{sec:ack}\n\nWe are grateful to Vivek Bagaria and Joachim Neu for an interesting discussion about their and our work that initiated this research. We thank Stefan Richter for helpful comments on early drafts of this work. A special thank goes to Thomas Gottron, Christian Decker and Dmytro Piatkivskyi. \nFinally we thank the donors to \\url{https://tallyco.in/s/lnbook} and Patreons supporting open knowledge. \n\n\n\\bibliography{lightningNetworkHealth}\n\\bibliographystyle{plain}\n\n\\end {document}\n", "meta": {"hexsha": "69537890973b1b70ff1fa0f3389a095c6d0af4a0", "size": 26176, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "lightningNetworkHealth.tex", "max_stars_repo_name": "renepickhardt/Improve-path-finding-in-the-Lightning-Network-with-the-Health-Improvement-Algorithm", "max_stars_repo_head_hexsha": "0a2613b5e94185b68869962cdf13a19053adfdd8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-12-23T17:00:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T07:58:58.000Z", "max_issues_repo_path": "lightningNetworkHealth.tex", "max_issues_repo_name": "renepickhardt/Imbalance-measure-and-proactive-channel-rebalancing-algorithm-for-the-Lightning-Network", "max_issues_repo_head_hexsha": "0a2613b5e94185b68869962cdf13a19053adfdd8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-11-28T09:14:01.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-28T16:08:08.000Z", "max_forks_repo_path": "lightningNetworkHealth.tex", "max_forks_repo_name": "renepickhardt/Improve-path-finding-in-the-Lightning-Network-with-the-Health-Improvement-Algorithm", "max_forks_repo_head_hexsha": "0a2613b5e94185b68869962cdf13a19053adfdd8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 85.2638436482, "max_line_length": 651, "alphanum_fraction": 0.7793016504, "num_tokens": 5911, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.3375922157911054}}
{"text": "\\documentclass[11pt]{beamer}\n\\usepackage{amsmath,amssymb}\n\\usepackage{graphicx}\n\\usepackage{url}\n\\usepackage{textcomp}\n\\usetheme{iqss}\n\n\\title[Beamer Demo]{Beamer Class Demonstration\\thanks{for beamer}}\n\n\\author{Me Myself and I }\n\\date{\\today}\n\\institute{IQSS}\n%\\titlegraphic{\\includegraphics[height=3em]{iqlogo.png}}\n\n\\begin{document}\n\n\\frame[plain]{\\titlepage}\n\n\\iqsssectiontitle{Outline}\n\n\\section[Features]{Beamer Features}\n\n\\subsection{Some of Gary's Examples}\n\\begin{frame}\\frametitle{What's this course about?}\n  \n  \\begin{itemize}\n  \\item \\alert{Specific statistical methods for many research problems}\n    \\begin{itemize}\n    \\item How to learn (or create) new methods\n    \\item Inference: \\underline{Using facts you know to learn about\n        facts you don't know}\n    \\end{itemize}\n  \\item \\alert{How to write a publishable scholarly paper}\n  \\item \\alert{All the practical tools of research} --- theory,\n    applications, simulation, programming, word processing, plumbing,\n    whatever is useful\n  \\item $\\leadsto$ \\alert{Outline and class materials:}\n    \\begin{itemize}\n    \\item[]    \\begin{center}\n        \n      \\mbox{{\\huge\\parbox[b][.5in][t]{1in}{\\alert{j.mp/G2001}}}\n        $\\qquad\\qquad$\\includegraphics[width=.95in]{figs/phbAr.png}}\n    \\end{center}\n  \\item The syllabus gives topics, not a weekly plan.\n  \\item We will go as fast as possible subject to everyone following\n    along\n  \\item We cover different amounts of material each week\n  \\end{itemize}\n  \\end{itemize}\n\\end{frame}\n\n\\begin{frame}\\frametitle{How much math will you scare us with?}\n  \\begin{itemize}\n  \\item All math requires two parts: \\alertb{proof} and\n    \\alertb{concepts \\& intuition}\n  \\item Different classes emphasize:\n    \\begin{itemize}\n    \\item \\alert{Baby Stats}: dumbed down proofs, vague intuition\n    \\item \\alert{Math Stats}: rigorous mathematical proofs\n    \\item \\alert{\\underline{Practical Stats}}: deep concepts and\n      intuition, proofs when needed\n      \\begin{itemize}\n      \\item Goal: how to do empirical research, in depth\n      \\item Use rigorous statistical theory --- when needed\n      \\item Insure we understand the intuition --- always\n      \\item Always traverse from theoretical foundations to practical\n        applications\n      \\item Includes ``how to'' computation\n      \\item $\\leadsto$ Fewer proofs, more concepts, better practical\n        knowledge\n      \\end{itemize}\n    \\end{itemize}\n  \\item Do you have the background for this class? \\uncover<+->{\\alert{A\n      Test: What's this?\n    \\begin{align*}\n      b=(X'X)^{-1}X'y\n    \\end{align*} }}\n  \\end{itemize}\n\\end{frame}\n\n\\begin{frame}\\frametitle{Systematic Components: Examples}\n  \\begin{center}\n    \\includegraphics<+->[width=8cm]{figs/functionalForms}\n  \\end{center}\n  \\begin{itemize}\n  \\item \\alertb{$E(Y_i) \\equiv \\mu_i = X_i\\beta = \\beta_0 +\n      \\beta_1X_{1i} +\\dots+\\beta_kX_{ki}$}\n  \\item \\alertc{$\\Pr(Y_i=1) \\equiv \\pi_i =\n      \\frac{1}{1+e^{-x_i\\beta}}$}\n  \\item \\alertd{$V(Y_i)\\equiv \\sigma_i^2 = e^{x_i\\beta}$}\n  \\item Interpretation:\n    \\begin{itemize}\n    \\item Each is a \\alert{class of functional forms}\n    \\item Set $\\beta$ and it picks out one \\alert{member of the class}\n    \\item \\alert{$\\beta$} in each is an ``effect parameter'' vector,\n      with different meaning\n    \\end{itemize}    \n  \\end{itemize}\n\\end{frame}\n\n\\begin{frame}\\frametitle{Negative Binomial Derivation} \\uncover<+->{Recall:}\n  \\begin{equation*}\n    \\uncover<+->{\\Pr(A|B)=\\frac{\\Pr(AB)}{\\Pr(B)} \\implies \\alertb{\\Pr(AB)}=\\alerte{\\Pr(A|B)}\\alertd{\\Pr(B)}}\n  \\end{equation*}\n  \\alertb<1-1>{one}\n  \\alertc<2-2>{two}\n  \\alertd<3-3>{three}\n  \\begin{align*}\n    \\uncover<+->{\\text{NegBin}(y|\\phi,\\sigma^2) &= \\int_0^\\infty\n      \\alerte{\\text{Poisson}(y|\\lambda)}\n      \\times\\alertd{\\text{gamma}(\\lambda|\\phi,\\sigma^2)}d\\lambda\\\\}\n    \\uncover<+->{&= \\int_0^\\infty\n      \\alertb{\\P(y,\\lambda|\\phi,\\sigma^2) }d\\lambda\\\\}\n    \\uncover<+->{&=\n      \\frac{\\Gamma\\left(\\frac{\\phi}{\\sigma^2-1}+y_i\\right)}\n      {y_i!\\Gamma\\left(\\frac{\\phi}{\\sigma^2-1}\\right)}\n      \\left(\\frac{\\sigma^2-1}{\\sigma^2}\\right)^{y_i}\n      \\left(\\sigma^2\\right)^{\\frac{-\\phi}{\\sigma^2-1}}}\n  \\end{align*}\n\\end{frame}\n\n\\section[ ]{Other features} % optional [ ] omits section head.\n\n\n\\subsection{Structural Features}\n\\begin{frame}\n  \\frametitle{Structural Features}\n  \\begin{block}{Levels of Structure}\n    \\begin{itemize}\n      \\item usual \\LaTeX\\ \\textbackslash{}section, \\textbackslash{}subsection \n      commands\n      \n      \\item `frame' environments provide slides\n      \n      \\item `block' environments divide slides into logical sections\n      \n      \\item `columns' environments divide slides vertically (example later)\n      \n      \\item overlays (\\`a la prosper) change content of slides dynamically\n    \\end{itemize}\n  \\end{block}\n  \n  \\begin{example}[Overlay Alerts]\n    On the first overlay, \\alert<1>{this text} is highlighted (or \\emph{alerted}).\\\\ On the second, \\alert<2>{this text} is.\n  \\end{example}\n\\end{frame}\n\n\\begin{frame}[fragile]\n  \\frametitle{Code blocks}\n\n\\begin{lstlisting}[language=R]\n# Say hello in R\nhello <- function(name) paste(\"hello\", name)\n\\end{lstlisting}\n\n\\begin{uncoverenv}<2->\n\\begin{lstlisting}[language=Python]\n# Say hello in Python\ndef hello(name):\nreturn(\"Hello\" + \" \" + name)\n\\end{lstlisting}\n\\end{uncoverenv}\n\n\\begin{uncoverenv}<3->\n\\begin{lstlisting}[language=Haskell]\n-- Say hello in Haskell\nhello name = \"Hello\" ++ \" \" ++ name\n\\end{lstlisting}\n\\end{uncoverenv}\n\n\n\\begin{uncoverenv}<4->\n\\begin{lstlisting}[language=C]\n/* Say hello in C */\n#include <stdio.h>\nint main()\n{\n  char name[256];\n  fgets(name, sizeof(name), stdin);\n  printf(\"Hello %s\", name);\n  return(0);\n}\n\\end{lstlisting}\n\\end{uncoverenv}\n\n\\end{frame}\n\n\\begin{frame}\n  \\frametitle{Alerts}\n  \\begin{itemize}\n     \\item First level \\alert{alert}\n     \\item Second level \\alertb{alert}\n     \\item Third level \\alertc{alert}\n     \\item Fourth level \\alertd{alert}\n     \\item Fifth level \\alerte{alert}\n  \\end{itemize}\n\n\\end{frame}\n\n\\section{More Features}\n\n\\begin{frame}\n  \\frametitle{Other Features}\n\n  \\begin{block}{Levels of Structure}\n    \\begin{itemize}\n    \\item Clean, extensively customizable visual style\n    \\item Hyperlinks (\\href{http://github.com/izahn/iqss-beamer-theme}{click here}) \n      \\item No weird scaling prosper\n      \\begin{itemize}\n        \\item slides are 96~mm~$\\times$~128~mm\n        \n        \\item text is 10-12pt on slide\n        \n        \\item slide itself magnified with Adobe Reader/xpdf/gv to fill screen\n      \\end{itemize}\n      \n      \\item pgf graphics framework easy to use\n      \n      \\item include external JPEG/PNG/PDF figures\n      \n      \\item output directly to pdf: no PostScript hurdles\n      \n      \\item detailed User's Manual (with good presentation advice, too)\n    \\end{itemize}\n  \\end{block}\n\\end{frame}\n\n\\subsection{Blocks}\n\n\\begin{frame}\n\\frametitle{Theorems and Proofs}\n\\framesubtitle{The proof uses \\textit{reductio ad absurdum}.}\n\\begin{theorem}\nThere is no largest prime number.\n\\end{theorem}\n\\begin{proof}\n\\begin{enumerate}\n\\item<1-| alert@1> Suppose $p$ were the largest prime number.\n\\item<2-> Let $q$ be the product of the first $p$ numbers.\n\\item<3-> Then $q+1$ is not divisible by any of them.\n\\item<1-> But $q + 1$ is greater than $1$, thus divisible by some prime\nnumber not in the first $p$ numbers.\\qedhere\n\\end{enumerate}\n\\end{proof}\n\\end{frame}\n\n\n\\begin{frame}\n  \\frametitle{Blocks}\n\n  \\begin{block}{Normal block}\nA \\alert{set} consists of elements.\n\\end{block}\n\n\\begin{alertblock}{Alert block}\n$2=2$.\n\\end{alertblock}\n\n\\begin{exampleblock}{Example block}\nThe set $\\{1,2,3,5\\}$ has four elements.\n\\end{exampleblock}\n\n\\end{frame}\n\n\\appendix\n\n\\section{\\appendixname}\n\n\\subsection{More stuff}\n\n\\frame{Details}\n\\frame{Text omitted in main talk.}\n\\subsection{Even more additional material}\n\\frame{More details}\n\\frame{Even more details}\n\n\\end{document}\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-engine: xetex\n%%% TeX-master: t\n%%% End:\n", "meta": {"hexsha": "735671c0610de88b98b8d25d50cdd2c22d9cdc30", "size": 7971, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "200+ beamer 模板合集/iqss-beamer-theme-master(哈佛量化社会科学研究所)/demo/beamer-demo.tex", "max_stars_repo_name": "lemoxiao/Awesome-Beamer-Collection", "max_stars_repo_head_hexsha": "3ab28a23fb60cb0a97fcec883847e2d8728b98c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2019-07-30T04:09:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-24T09:27:26.000Z", "max_issues_repo_path": "200+ beamer 模板合集/iqss-beamer-theme-master(哈佛量化社会科学研究所)/demo/beamer-demo.tex", "max_issues_repo_name": "lemoxiao/Awesome-Beamer-Collection", "max_issues_repo_head_hexsha": "3ab28a23fb60cb0a97fcec883847e2d8728b98c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "200+ beamer 模板合集/iqss-beamer-theme-master(哈佛量化社会科学研究所)/demo/beamer-demo.tex", "max_forks_repo_name": "lemoxiao/Awesome-Beamer-Collection", "max_forks_repo_head_hexsha": "3ab28a23fb60cb0a97fcec883847e2d8728b98c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2019-11-02T03:10:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-12T04:13:23.000Z", "avg_line_length": 27.9684210526, "max_line_length": 124, "alphanum_fraction": 0.6730648601, "num_tokens": 2448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241911813151, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3374704331133765}}
{"text": "\\documentclass[12]{scrartcl}\n\\usepackage{amssymb,amsmath,gensymb,dsfont,calc,multicol,fullpage}\n\\makeatletter\n\\newcommand\\Aboxed[1]{\n   \\@Aboxed#1\\ENDDNE}\n\\def\\@Aboxed#1&#2\\ENDDNE{%\n   &\n   \\settowidth\\@tempdima{$\\displaystyle#1{}$}\n   \\setlength\\@tempdima{\\@tempdima+\\fboxsep+\\fboxrule}\n   \\kern-\\@tempdima\n   \\boxed{#1#2}\n}\n\\makeatother\n\n\\begin{document}\n\n\\title{Homework 33, Section 6.4: 2, 5, 7}\n\\author{Alex Gordon}\n\\date{\\today}\n\\maketitle\n\\section*{Homework}\n\\subsection*{2.}\nSo basically, this isn't that hard. All I'm doing is picking some random numbers for the average number of women on the Committee. \\\\\n$1 \\cdot \\frac{C(10,1)C(15,2)}{C(25,3)} + 2 \\cdot \\frac{C(10,2)C(15,1)}{C(25,3)} + 3 \\cdot \\frac{C(10,3)}{C(25,3)} = 1.2$\n\n\\subsection*{5.}\n$1 \\cdot \\frac{C(4,1)C(48,4)}{C(52,5)} + 2 \\cdot \\frac{C(4,2)C(48,3)}{C(52,5)} + 3 \\cdot \\frac{C(48,2)C(4,3)}{C(52,5)} + 4 \\cdot \\frac{C(48,2)}{C(52,5)} = .39$\n\\subsection*{7.}\n$\\frac{10}{3} + \\frac{5}{4} + \\frac{1}{5} = 4.78$, multiplied by 5 courses so \\$23.90 per semester. \n\\end{document}", "meta": {"hexsha": "18d6dc3463045c2b7eb4ea1653adbe5940efa461", "size": 1049, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "DiscreteMath/Homework33.tex", "max_stars_repo_name": "alexggordon/latex", "max_stars_repo_head_hexsha": "7dd945f33490e6585e26cff39d9cf6ad8f582a0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DiscreteMath/Homework33.tex", "max_issues_repo_name": "alexggordon/latex", "max_issues_repo_head_hexsha": "7dd945f33490e6585e26cff39d9cf6ad8f582a0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DiscreteMath/Homework33.tex", "max_forks_repo_name": "alexggordon/latex", "max_forks_repo_head_hexsha": "7dd945f33490e6585e26cff39d9cf6ad8f582a0e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9666666667, "max_line_length": 159, "alphanum_fraction": 0.6434699714, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.3374704255929373}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\subsection{No-stress source}\n\n\\marginpar{Monday\\\\ 2021-4-26, \\\\ compiled \\\\ \\today}\n\nWe considered a source in the form \\(T_{\\mu \\nu } = \\rho t_\\mu t_\\nu \\), where \\(t^{\\mu } = (1, \\vec{0})\\). \n\nNow we will consider a source in the form \n%\n\\begin{align}\nT_{\\mu \\nu } = - 2 \\rho t_\\mu t_\\nu + 2 J_{(\\mu } t_{\\nu )}\n\\,,\n\\end{align}\n%\nwhere \\(J^{\\mu } = \\rho u^{\\mu } = \\rho (\\gamma , \\gamma v^{i} / c)\\). \n\n\\todo[inline]{Probably the first 2 is not there.}\n\nThe static source from before can be recovered from this expression in the low-velocity limit \\(v^{i} / c \\to 0\\). \nIn that case, \\(T_{ij} = 0\\): we can see that \\(T_{ij}\\) is of order \\(v^2 / c^2\\), so to first order they vanish. \n\nIn this situation, we get the system \n%\n\\begin{align}\n\\begin{cases}\n    \\square \\overline{h}_{0 \\mu } &= - 16 \\pi T_{0 \\mu } \\\\\n    \\square \\overline{h}_{ij} &= 0\n\\,.\n\\end{cases}\n\\end{align}\n\nIn order to simplify, let us assume that \\(\\partial_{t} \\overline{h}_{ij} = 0\\): then, the solution to the second of these becomes \\(\\nabla^2 \\overline{h}_{ij} = 0\\), with flat boundary conditions at large distance. \nBy linearity, this leads to \\(\\overline{h}_{ij} = 0\\).\n\n\\begin{claim}\nIf we define \\(A_{\\mu } = - (1/4) \\overline{h}_{0 \\mu } = - (1/4) \\overline{h}_{\\mu \\nu } t^{\\nu }\\), then the metric becomes \n%\n\\begin{align}\ng_{00} &= - 1 + 2 A_0  \\\\\ng_{0i} &= 4 A_i  \\\\\ng_{ij} &= (1 + 2 A_0) \\delta_{ij}\n\\,.\n\\end{align}\n\\end{claim}\n\nIn terms of this \\(A_{\\mu }\\), the Dalambertian equation from before reads \n%\n\\begin{align}\n\\square A_{\\mu } = - \\frac{16}{4} \\pi J_\\mu = - 4 \\pi J_\\mu \n\\,,\n\\end{align}\n%\nwhich are formally identical to the Maxwell equations! \nTherefore, we can employ known techniques from electromagnetism. \n\nFor example, if \\(\\partial_{t} A_{\\mu } = 0\\) then \n%\n\\begin{align}\n\\begin{cases}\n    A_0 &= - \\phi  \\\\\n    A_{i} &= \\int \\dd[3]{x^{i}} \\frac{J_i}{\\abs{x - x^{i}}}\n\\,,\n\\end{cases}\n\\end{align}\n%\nwhich is the reason why the phenomena which can be described through this formalism are known as gravito-electric and gravito-magnetic effects. \n\n\\begin{claim}\nFor example, geodesics in a weak-field stationary (no stress) spacetime are described by a Lagrangian \n%\n\\begin{align}\n\\mathscr{L} &= - mc \\qty(- g_{\\mu \\nu } \\dot{x}^{\\mu } \\dot{x}^{\\nu })^{1/2}  \\\\\n&= - mc^2 \\qty(- g_{00} - 2 g_{0i} \\frac{v^{i}}{c} - g_{ij} \\frac{v^{i} v^{j}}{c^2})^{1/2}  \\\\\n&\\approx -mc^2 + \\frac{m}{2} v^2 + m \\phi + 4 mc A_{i}v^{i}\n\\,.\n\\end{align}\n\\end{claim}\n\nWe have a mass term, a kinetic term, a gravitational term, and a contribution to the Lorentz force. \n\nThe corresponding equations of motion read \n%\n\\begin{align}\n\\ddot{\\vec{x}} = \\vec{E} + 4 \\vec{v} \\times \\vec{B}\n\\,,\n\\end{align}\n%\nwhere \\(\\vec{E}\\) and \\(\\vec{B}\\) are the gravitoelectric and gravitomagnetic fields derived from our \\(A_{\\mu }\\). \nThe differences from EM are: the absence of charge, and the factor of 4 before the magnetic term.\n\nAn example of a gravito-electromagnetic effect is the Lense-Thirring effect: a magnetic moment \\(\\vec{s}\\) in a magnetic field precesses, according to \n%\n\\begin{align}\n\\dv{\\vec{s}}{t} &= \\vec{s} \\times \\vec{\\Omega}\n\\qquad \\text{where} \\qquad\n\\vec{\\Omega} = - \\frac{q}{m} \\vec{B}_{EM}\n\\,,\n\\end{align}\n%\nso in order to generalize to the precession of a gyroscope in an EM field we need to map \\(q \\to m\\) and \\(\\vec{B}_{EM} \\to 4 \\vec{B}\\). \n\nThis way, we see for example that \\(\\Omega _g = - 4 B\\). \nA mission called Gravity Probe B measured this effect: they found precession with \\(\\Omega _g \\sim \\SI{.22}{arcsec / yr} (R_{\\oplus} / r)^3\\). \nThis is a \\SI{20}{\\percent} accurate test of GR in the weak field. \n\n\\todo[inline]{What does that mean?}\n\nAnother example is \\textbf{frame dragging}, which applies in full GR: if we put the gyroscope around a BH a similar effect emerges. \nAround a Kerr BH we have \n%\n\\begin{align}\ng_{0i}^{\\text{Kerr}} \\sim \\Omega_{BH} \n\\,,\n\\end{align}\n%\nand if the particle is close to the BH a particle is ``locked'' to the BH rotation. \n\n\\section{Gravitational Waves in linear GR}\n\nGW are solutions of weak-field GR in a vacuum.\nThere, the wave equation reads \\(0 = \\square _\\eta \\overline{h}_{\\mu \\nu }\\). What are the properties of the solutions of these equations? \nThe simplest thing we can do is look for plane wave solutions. We take a wave vector \\(k^{\\mu } = (\\omega , k^{i})\\) and an amplitude \\(A_{\\mu \\nu }\\); then \n%\n\\begin{align}\n\\overline{h}_{\\mu \\nu } = A_{\\mu \\nu } e^{i k_\\mu x^{\\mu }} = A_{\\mu \\nu } e^{i (- \\omega t + \\vec{k} \\cdot \\vec{x}) }\n\\,,\n\\end{align}\n%\nso \\(\\partial_{\\mu } \\overline{h}_{\\alpha \\beta } =  (i k_\\mu ) \\overline{h}_{\\alpha \\beta }\\). \n\nSubstituting the plane wave ansatz yields \n%\n\\begin{align}\n0 = \\square \\overline{h}_{\\alpha \\beta } = - \\eta^{\\mu \\nu } k_\\mu k_\\nu \\overline{h}_{\\alpha \\beta }\n\\,,\n\\end{align}\n%\ntherefore \\(k_{\\mu }k^{\\mu } = 0\\). The wavevector is null. \n\nThis implies that the GW propagates at the speed of light: \\(\\omega s^2 = \\abs{\\vec{k}}^2\\). \n\nHow do we completely specify a gauge?\nAny infinitesimal transformation such that \\(\\square \\xi^{\\mu } = 0\\) preserves the Hilbert gauge, so we can make a residual gauge transformation. \n\nThe harmonic gauge implies that \n%\n\\begin{align}\n0 = - \\partial^{\\alpha } \\overline{h}_{\\mu \\alpha } = i k^{\\alpha } \\overline{h}_{\\mu \\alpha }\n\\,,\n\\end{align}\n%\nwhich yields \\(k^{\\alpha } A_{\\alpha \\mu } = 0\\). This means that GWs are \\textbf{transverse} to the propagation direction. \n\nWe know that \\(\\overline{h}_{\\mu \\nu }\\) maps to \\(\\overline{h}_{\\mu \\nu } + 2 \\partial_{(\\mu } \\xi_{\\nu )} + \\eta_{\\mu \\nu } \\partial_{\\alpha } \\xi^{\\alpha }\\). \n\nLet us use \\(\\xi^{\\mu } = B^{\\mu } e^{i k_{\\alpha } x^{ \\alpha }}\\) as an ansatz for our residual gauge transformation, since it automatically harmonic: we get \n%\n\\begin{align}\nA_{\\mu \\nu } \\to A_{\\mu \\nu } - 2 i k_{(\\mu } B_{\\nu )} + i \\eta_{\\mu \\nu } k_{\\alpha } B^{\\alpha }\n\\,,\n\\end{align}\n%\nand since we can pick \\(B^{\\mu }\\) arbitrarily we can impose \\(\\overline{h} = A^{\\mu }_{\\mu } = 0\\), the \\textbf{traceless condition}, as well as \\(\\overline{h}_{\\mu 0} = 0\\), the \\textbf{transverse condition}.\nThe second is suggested by the previously found result \\(k_\\alpha A^{\\alpha \\beta } = 0\\). \n\nIn terms of \\(B\\), this is a linear algebraic system, and it is invertible.\n\nIn summary, we start from 10 variables, we use 4 equations to impose the Hilbert gauge, and 4 more to impose the TT gauge. \nThe two degrees of freedom which are left are the true degrees of freedom of a GW. \n\nMore explicitly, if we have \\(k^{\\mu } = (\\omega, 0, 0, k_z)\\) this means \n\\begin{enumerate}\n    \\item \\(k^2 =0 \\) implies \\(- \\omega = k_z\\);\n    \\item the phase reads \\(k_\\alpha x^{\\alpha } = \\omega (t - z)\\);\n    \\item the Hilbert gauge \\(k^{\\mu } A_{\\mu \\nu } = 0\\) tells us that \\(A_{0 \\nu } = A_{3 \\nu }\\); \n    \\item the transverse condition tells us that \\(A_{0 \\mu } = 0\\) (so also \\(A_{3 \\mu } = 0\\));\n    \\item the traceless condition tells us that \\(A^{\\mu }_{\\mu } = 0\\).\n\\end{enumerate}\n\nThis leads to the usual formulation \n%\n\\begin{align}\nA_{\\mu \\nu }^{TT} = \\left[\\begin{array}{cccc}\n0 & 0 & 0 & 0 \\\\ \n0 & A_+ & A_\\times & 0 \\\\ \n0 & A_\\times  & - A_+ & 0 \\\\ \n0 & 0 & 0 & 0\n\\end{array}\\right]\n\\,.\n\\end{align}\n\nTherefore, \n%\n\\begin{align}\nh^{TT}_{\\mu \\nu } = A_{\\mu \\nu }^{TT} \\exp(i \\omega (t - z))\n\\,.\n\\end{align}\n\nIn TT gauge we have \\(\\overline{h}_{\\mu \\nu } = h_{\\mu \\nu }\\) since the trace is zero.\nImportantly, the TT gauge can only be defined in vacuo! This is because in that case \\(\\square \\overline{h}_{\\mu \\nu } \\neq 0\\), so while we can still exploit gauge freedom we cannot set components to zero inside the source. \n\nThe metric in TT gauge reads \n%\n\\begin{align}\ng &= - \\dd{t^2} + \\dd{z^2} + (1 + h_+) \\dd{x^2} (1 - h_\\times ) \\dd{y^2} + 2 h_\\times \\dd{x} \\dd{y}\ng &= - \\dd{t^2} + (\\delta_{ij} + h^{TT}_{ij} ) \\dd{x^{i}} \\dd{x^{j}}\n\\,.\n\\end{align}\n\nHow do we identify the GW degrees of freedom in general? \nWe can impose the TT gauge outside the source (far away from the \\(T_{\\mu \\nu }\\)). \n\nIn general, \n%\n\\begin{align}\nh^{TT}_{\\mu \\nu } = \\Lambda_{\\mu \\nu }{}^{\\alpha \\beta } \\overline{h}_{\\alpha \\beta }\n\\,,\n\\end{align}\n%\nwhere \\(\\Lambda \\) is a projection operator, defined as \n%\n\\begin{align}\n\\Lambda_{\\mu \\nu }{}^{\\alpha \\beta } &= P_{\\mu }^{\\alpha } P_\\nu^{\\beta } - \\frac{1}{2} P_{\\mu \\nu } P^{\\alpha \\beta }  \\\\\nP_{\\mu \\nu } &= \\delta_{\\mu \\nu } - n_\\mu n_\\nu \n\\,,\n\\end{align}\n%\nwhere \\(n^\\mu \\) is the propagation direction. \n\nThe projection tensor \\(P_{\\mu \\nu }\\) is symmetric, it is transverse (\\(P_{\\mu \\nu } n^{\\nu } = 0\\)), it is idempotent (\\(P_{\\mu \\alpha } P_{\\alpha \\nu } = P_{\\mu \\nu }\\)), and its trace is equal to \\(2\\). \n\nThe tensor \\(\\Lambda_{\\mu \\nu \\alpha \\beta } \\) is also idempotent, transverse in all indices, traceless in \\(\\mu \\nu \\) and \\(\\alpha \\beta \\) separately, and symmetric in the swap of \\(\\mu \\nu \\) and \\(\\alpha \\beta \\). \n\nIn summary, we have found GW solutions, they propagate with \\(c\\), they are transverse, they have two degrees of freedom. \n\nSymmetric, Transverse, Trace-Free tensors play an important role in GW theory. They can be used to obtain the \\textbf{Multipolar expansion}. \n\n``Living review of relativity'' (see webpage) describes all the tests of GR. \n\n\\end{document}\n", "meta": {"hexsha": "0066aec15086290d59fbc64360617edbc9ff9814", "size": 9281, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "phd_courses/gravitational_waves/apr26.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "phd_courses/gravitational_waves/apr26.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phd_courses/gravitational_waves/apr26.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 38.1934156379, "max_line_length": 225, "alphanum_fraction": 0.6308587437, "num_tokens": 3269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3374704255929373}}
{"text": "\\section{Transition Systems Properties}\n\\label{sec:ts-properties}\n\n\n\\subsection{Transition-system traces}\n\\label{sec:ts-traces}\n\nThis section introduces the notion of traces induced by the transition systems\ndescribed in \\cite{small_step_semantics}.\n\n\\begin{definition}[Traces]\n  Given a state transition system $L=(S,T,\\Sigma, R, \\Gamma)$, the set of\n  traces of $L$, denoted as $\\fun{traces}_L$ is defined as:\n  $$\n  \\{ (e, s, \\txs, s') \\mid e \\in \\Gamma,~ s \\in S,~ \\txs \\in \\seqof{\\Sigma},~ s' \\in S\\}\n  $$\n\n\\end{definition}\n\n\n\\begin{definition}[Valid traces]\n  Given a state transition system $L=(S,T,\\Sigma, R, \\Gamma)$, we define the\n  notion of valid traces inductively:\n\n  \\begin{itemize}\n  \\item For all $e \\in \\Gamma$, $s \\in S$, $(e, s, \\epsilon, s)$ is a valid\n    trace of $L$.\n\n  \\item If $(e, s, \\txs, s')$ is a valid trace, and\n    $e \\vdash s' \\trans{}{\\var{t}} s''$ is a valid transition according to the\n    rules of $L$, then $(e, s, \\txs; t, s'')$ is also a valid trace.\n  \\end{itemize}\n\n\\end{definition}\n\nWe denote the set of valid traces of $L$ as $\\transtar{L}{}$, and we write\n$e \\vdash s \\transtar{L}{\\txs} s'$ as a shorthand for\n$(e, s, \\txs, s') \\in \\transtar{L}{}$. Furthermore, when the transition system\nname is clear from the context we will omit it from the transition arrow label.\n\n\\subsection{Additional notation}\n\\label{sec:additional-notation}\n\nWe describe next additional notation needed in the properties of the transition\nsystems specified in this document.\n\n\\subsubsection{Sequence indexing}\n\\label{sec:seq-indexing}\n\nGiven a sequence $\\mathcal{A} \\in \\seqof{\\type{A}}$, and a natural number $i$\nsuch that $0 \\leq i < \\size{\\mathcal{A}}$, $\\mathcal{A}_i$ refers to the\n$i^{\\text{th}}$ element of $\\mathcal{A}$.\n\n\nGiven a sequence $\\mathcal{A}$, a quantification symbol $\\bigoplus$, e.g.\n$\\forall$ or $\\exists$, a range predicate $R$, and a quantification term $T$\n(both of which depend on an element of $\\mathcal{A}$) we write:\n%\n$$\n\\bigoplus \\mathcal{A}_i \\cdot R~\\mathcal{A}_i \\cdot T~\\mathcal{A}_i\n$$\n%\nas a shorthand notation for:\n%\n$$\n\\bigoplus i \\cdot 0 \\leq i < \\size{\\mathcal{A}} \\wedge R~\\mathcal{A}_i \\cdot T~\\mathcal{A}_i\n$$\n\nFor instance:\n%\n$$\n\\forall \\txs_i \\cdot \\txins{\\txs_i} \\neq \\emptyset\n$$\nis a shorthand notation for:\n$$\n\\forall i \\cdot 0 \\leq i < \\size{\\txs} \\Rightarrow \\txins{\\txs_i} \\neq \\emptyset\n$$\nRemember that the range of a universal quantification can be expressed by an\nimplication, and the range of an existential qualification by a conjunction.\n\n\\subsubsection{Quantifying over set operations}\n\\label{sec:quantifying-over-set-operators}\n\nGiven a sequence $\\mathcal{A} \\in \\seqof{A}$, a set $B$, a set operation\n$\\bigoplus$, e.g. $\\cup$ or $\\unionoverrideRight$, and a function\n$\\fun{f} \\in \\type{A} \\to \\type{B}$, the term:\n%\n$$\n\\underset{\\fun{f}}{\\bigoplus} \\mathcal{A}\n$$\nis a shorthand notation for:\n%\n$$\n\\underset{0 \\leq i < \\size{\\mathcal{A}}}{\\bigoplus} \\mathcal{A}_i\n$$\n\nFor instance:\n$$\n\\bigcup_{\\txins{}} \\txs\n$$\ndenotes the sequence of unions:\n$$\n\\bigcup_{0 \\leq i < \\size{\\txs}} \\txins{\\txs_i}\n$$\n\nIn a set operation quantification over a sequence $\\mathcal{A}$, the operation\nis applied to the elements the order in which they appear in $\\mathcal{A}$.\nThis is crucial in the case of non-commutative operations, such as union\noverride ($\\unionoverrideRight$).\n\n\\subsection{UTxO Properties}\n\\label{sec:utxo-properties}\n\nProperty~\\ref{prop:no-double-spending} expresses the fact that transaction\ninputs cannot be used more than once. This property requires that the starting\nUTxO does not contain any future outputs, which is a reasonable constraint.\n\n\\begin{property}[No double spending]\\label{prop:no-double-spending}\n  For all\n\n  $$\n  \\left(\n    \\begin{array}{l}\n      \\var{utxo_0}\\\\\n      \\var{reserves_0}\n    \\end{array}\n  \\right)\n  \\transtar{\\hyperref[fig:rules:utxo]{utxo}}{\\txs}\n  \\left(\n    \\begin{array}{l}\n      \\var{utxo}\\\\\n      \\var{reserves}\n    \\end{array}\n  \\right)\n  $$\n\n  such that\n\n  $$\n    \\forall \\txs_i \\cdot \\dom~(\\txouts{\\txs_i}) \\cap \\dom~(\\var{utxo_0}) = \\emptyset\n  $$\n\n  we have:\n\n  $$\n  \\forall \\txs_i,~\\txs_j \\cdot i < j \\Rightarrow \\txins{\\txs_i} \\cap \\txins{\\txs_j} = \\emptyset\n  $$\n\\end{property}\n\nProperty~\\ref{prop:utxo-out-min-in} expresses the fact that all inputs and\noutputs are accounted for, in such a way that we can reconstruct the final\n(UTxO) state by adding all the outputs to the initial state, and removing the\nspent outputs.\n\n\\begin{property}[UTxO is outputs minus inputs]\\label{prop:utxo-out-min-in}\n  For all\n\n  $$\n  \\left(\n    \\begin{array}{l}\n      \\var{utxo_0}\\\\\n      \\var{reserves_0}\n    \\end{array}\n  \\right)\n  \\transtar{\\hyperref[fig:rules:utxo]{utxo}}{\\txs}\n  \\left(\n    \\begin{array}{l}\n      \\var{utxo}\\\\\n      \\var{reserves}\n    \\end{array}\n  \\right)\n  $$\n\n  such that\n\n  $$\n    \\forall \\txs_i \\cdot \\dom~(\\txouts{\\txs_i}) \\cap \\dom~(\\var{utxo_0}) = \\emptyset\n  $$\n\n  we have:\n\n  $$\n  \\bigcup_{\\txins{}} \\txs \\subtractdom (\\var{utxo_0} \\cup \\bigcup_{\\txouts{}} \\txs) = \\var{utxo}\n  $$\n\n\\end{property}\n\nProperty~\\ref{prop:utxo-money-supply-cnst} models the fact that the amount of\nmoney in the system (counted as Entropics) remains constant.\n\n\\begin{property}[Money supply is constant in the system]\\label{prop:utxo-money-supply-cnst}\n  For all\n\n  $$\n  \\left(\n    \\begin{array}{l}\n      \\var{utxo_0}\\\\\n      \\var{reserves_0}\n    \\end{array}\n  \\right)\n  \\transtar{\\hyperref[fig:rules:utxo]{utxo}}{\\txs}\n  \\left(\n    \\begin{array}{l}\n      \\var{utxo}\\\\\n      \\var{reserves}\n    \\end{array}\n  \\right)\n  $$\n\n  we have:\n\n  $$ \\var{reserves} + \\balance{utxo} =  \\var{reserves_0} + \\balance{utxo_0} $$\n\\end{property}\n\n\\subsection{Delegation Properties}\n\\label{sec:delegation-props}\n\nProperty~\\ref{prop:no-dcert-replay} states that delegation certificates cannot be replayed. Remember\nthat $\\Delta_i$ is the $i^{\\text{th}}$ element of $\\Delta$, which is a sequence of sequences of\ndelegation certificates, so $\\Delta_i \\in \\seqof{\\DCert}$ and $\\Delta_{i_j} \\in \\DCert$ (assuming\n$j$ is a valid index of $\\Delta_i$).\n\n\\begin{property}[No replay of delegation certificates]\\label{prop:no-dcert-replay}\n  For all\n  %\n  $$\n  \\left(\n    \\begin{array}{l}\n      \\var{delegSt}\n    \\end{array}\n  \\right)\n  \\transtar{\\hyperref[fig:rules:delegation-interface]{deleg}}{\\Delta}\n  \\left(\n    \\begin{array}{l}\n      \\var{delegSt'}\n    \\end{array}\n  \\right)\n  $$\n  %\n  we have:\n  %\n  $$\n  \\forall i, j, k, l \\cdot j < l \\Rightarrow \\Delta_{i_j} \\neq \\Delta_{k_l}\n  $$\n\\end{property}\n", "meta": {"hexsha": "5b55f598ef1424ab0ed76c12c2e6a46dbebafd3e", "size": 6507, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "cole/ledger/formal-spec/properties.tex", "max_stars_repo_name": "Quantum-One-DLT/bcc-ledger-specs", "max_stars_repo_head_hexsha": "e1109f35aee321bbf899a5e2cc4de3eec583f9b7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cole/ledger/formal-spec/properties.tex", "max_issues_repo_name": "Quantum-One-DLT/bcc-ledger-specs", "max_issues_repo_head_hexsha": "e1109f35aee321bbf899a5e2cc4de3eec583f9b7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cole/ledger/formal-spec/properties.tex", "max_forks_repo_name": "Quantum-One-DLT/bcc-ledger-specs", "max_forks_repo_head_hexsha": "e1109f35aee321bbf899a5e2cc4de3eec583f9b7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-11-13T21:20:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T16:37:19.000Z", "avg_line_length": 26.4512195122, "max_line_length": 100, "alphanum_fraction": 0.6671277086, "num_tokens": 2199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.33747041807249795}}
{"text": "%% LyX 2.3.2 created this file.  For more info, see http://www.lyx.org/.\n%% Do not edit unless you really know what you are doing.\n\\documentclass[english,aspectratio=169, handout]{beamer}\n\\usepackage{mathptmx}\n\\usepackage{eulervm}\n\\usepackage[T1]{fontenc}\n\\usepackage[latin9]{inputenc}\n\\usepackage{babel}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{graphicx}\n\\ifx\\hypersetup\\undefined\n  \\AtBeginDocument{%\n    \\hypersetup{unicode=true,pdfusetitle,\n bookmarks=true,bookmarksnumbered=false,bookmarksopen=false,\n breaklinks=false,pdfborder={0 0 0},pdfborderstyle={},backref=false,colorlinks=true,\n allcolors=NYUPurple,urlcolor=LightPurple}\n  }\n\\else\n  \\hypersetup{unicode=true,pdfusetitle,\n bookmarks=true,bookmarksnumbered=false,bookmarksopen=false,\n breaklinks=false,pdfborder={0 0 0},pdfborderstyle={},backref=false,colorlinks=true,\n allcolors=NYUPurple,urlcolor=LightPurple}\n\\fi\n\n\\makeatletter\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LyX specific LaTeX commands.\n%% A simple dot to overcome graphicx limitations\n\\newcommand{\\lyxdot}{.}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Textclass specific LaTeX commands.\n% this default might be overridden by plain title style\n\\newcommand\\makebeamertitle{\\frame{\\maketitle}}%\n% (ERT) argument for the TOC\n\\AtBeginDocument{%\n  \\let\\origtableofcontents=\\tableofcontents\n  \\def\\tableofcontents{\\@ifnextchar[{\\origtableofcontents}{\\gobbletableofcontents}}\n  \\def\\gobbletableofcontents#1{\\origtableofcontents}\n}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% User specified LaTeX commands.\n\\usetheme{CambridgeUS} \n\\beamertemplatenavigationsymbolsempty\n\n\n% Set Color ==============================\n\\definecolor{NYUPurple}{RGB}{87,6,140}\n\\definecolor{LightPurple}{RGB}{165,11,255}\n\n\n\\setbeamercolor{title}{fg=NYUPurple}\n%\\setbeamercolor{frametitle}{fg=NYUPurple}\n\\setbeamercolor{frametitle}{fg=NYUPurple}\n\n\\setbeamercolor{background canvas}{fg=NYUPurple, bg=white}\n\\setbeamercolor{background}{fg=black, bg=NYUPurple}\n\n\\setbeamercolor{palette primary}{fg=black, bg=gray!30!white}\n\\setbeamercolor{palette secondary}{fg=black, bg=gray!20!white}\n\\setbeamercolor{palette tertiary}{fg=gray!20!white, bg=NYUPurple}\n\n\\setbeamertemplate{headline}{}\n\n\\setbeamercolor{parttitle}{fg=NYUPurple}\n\\setbeamercolor{sectiontitle}{fg=NYUPurple}\n\\setbeamercolor{sectionname}{fg=NYUPurple}\n\\setbeamercolor{section page}{fg=NYUPurple}\n\n\\AtBeginSection[]{\n  \\begin{frame}\n  \\vfill\n  \\centering\n\\setbeamercolor{section title}{fg=NYUPurple}\n \\begin{beamercolorbox}[sep=8pt,center,shadow=true,rounded=true]{title}\n    \\usebeamerfont{title}\\usebeamercolor[fg]{title}\\insertsectionhead\\par%\n  \\end{beamercolorbox}\n  \\vfill\n  \\end{frame}\n}\n\n\\makeatother\n\n\\begin{document}\n\\global\\long\\def\\reals{\\mathbf{R}}%\n \n\\global\\long\\def\\integers{\\mathbf{Z}}%\n \n\\global\\long\\def\\naturals{\\mathbf{N}}%\n \n\\global\\long\\def\\rationals{\\mathbf{Q}}%\n \n\\global\\long\\def\\ca{\\mathcal{A}}%\n \n\\global\\long\\def\\cb{\\mathcal{B}}%\n \n\\global\\long\\def\\cc{\\mathcal{C}}%\n \n\\global\\long\\def\\cd{\\mathcal{D}}%\n \n\\global\\long\\def\\ce{\\mathcal{E}}%\n \n\\global\\long\\def\\cf{\\mathcal{F}}%\n \n\\global\\long\\def\\cg{\\mathcal{G}}%\n \n\\global\\long\\def\\ch{\\mathcal{H}}%\n \n\\global\\long\\def\\ci{\\mathcal{I}}%\n \n\\global\\long\\def\\cj{\\mathcal{J}}%\n \n\\global\\long\\def\\ck{\\mathcal{K}}%\n \n\\global\\long\\def\\cl{\\mathcal{L}}%\n \n\\global\\long\\def\\cm{\\mathcal{M}}%\n \n\\global\\long\\def\\cn{\\mathcal{N}}%\n \n\\global\\long\\def\\co{\\mathcal{O}}%\n \n\\global\\long\\def\\cp{\\mathcal{P}}%\n \n\\global\\long\\def\\cq{\\mathcal{Q}}%\n \n\\global\\long\\def\\calr{\\mathcal{R}}%\n \n\\global\\long\\def\\cs{\\mathcal{S}}%\n \n\\global\\long\\def\\ct{\\mathcal{T}}%\n \n\\global\\long\\def\\cu{\\mathcal{U}}%\n \n\\global\\long\\def\\cv{\\mathcal{V}}%\n \n\\global\\long\\def\\cw{\\mathcal{W}}%\n \n\\global\\long\\def\\cx{\\mathcal{X}}%\n \n\\global\\long\\def\\cy{\\mathcal{Y}}%\n \n\\global\\long\\def\\cz{\\mathcal{Z}}%\n \n\\global\\long\\def\\ind#1{1(#1)}%\n %\\newcommand{\\pr}{P}\n\\global\\long\\def\\pr{\\mathbb{P}}%\n \n\\global\\long\\def\\predsp{\\cy}%\n %{\\hat{\\cy}}\n\\global\\long\\def\\outsp{\\cy}%\n\n\\global\\long\\def\\prxy{P_{\\cx\\times\\cy}}%\n \n\\global\\long\\def\\prx{P_{\\cx}}%\n \n\\global\\long\\def\\prygivenx{P_{\\cy\\mid\\cx}}%\n %\\newcommand{\\ex}{E}\n\\global\\long\\def\\ex{\\mathbb{E}}%\n \n\\global\\long\\def\\var{\\textrm{Var}}%\n \n\\global\\long\\def\\cov{\\textrm{Cov}}%\n \n\\global\\long\\def\\sgn{\\textrm{sgn}}%\n \n\\global\\long\\def\\sign{\\textrm{sign}}%\n \n\\global\\long\\def\\kl{\\textrm{KL}}%\n \n\\global\\long\\def\\law{\\mathcal{L}}%\n \n\\global\\long\\def\\eps{\\varepsilon}%\n \n\\global\\long\\def\\as{\\textrm{ a.s.}}%\n \n\\global\\long\\def\\io{\\textrm{ i.o.}}%\n \n\\global\\long\\def\\ev{\\textrm{ ev.}}%\n \n\\global\\long\\def\\convd{\\stackrel{d}{\\to}}%\n \n\\global\\long\\def\\eqd{\\stackrel{d}{=}}%\n \n\\global\\long\\def\\del{\\nabla}%\n \n\\global\\long\\def\\loss{\\ell}%\n \n\\global\\long\\def\\risk{R}%\n \n\\global\\long\\def\\emprisk{\\hat{R}}%\n \n\\global\\long\\def\\lossfnl{L}%\n \n\\global\\long\\def\\emplossfnl{\\hat{L}}%\n \n\\global\\long\\def\\empminimizer#1{\\hat{#1}^{*}}%\n \n\\global\\long\\def\\minimizer#1{#1^{*}}%\n\\global\\long\\def\\optimizer#1{#1^{*}}%\n \n\\global\\long\\def\\etal{\\textrm{et. al.}}%\n \n\\global\\long\\def\\tr{\\operatorname{tr}}%\n\n\\global\\long\\def\\trace{\\operatorname{trace}}%\n \n\\global\\long\\def\\diag{\\text{diag}}%\n \n\\global\\long\\def\\rank{\\text{rank}}%\n \n\\global\\long\\def\\linspan{\\text{span}}%\n \n\\global\\long\\def\\spn{\\text{span}}%\n \n\\global\\long\\def\\proj{\\text{Proj}}%\n \n\\global\\long\\def\\argmax{\\operatornamewithlimits{arg\\, max}}%\n \n\\global\\long\\def\\argmin{\\operatornamewithlimits{arg\\, min}}%\n\n\\global\\long\\def\\bfx{\\mathbf{x}}%\n \n\\global\\long\\def\\bfy{\\mathbf{y}}%\n \n\\global\\long\\def\\bfl{\\mathbf{\\lambda}}%\n \n\\global\\long\\def\\bfm{\\mathbf{\\mu}}%\n \n\\global\\long\\def\\calL{\\mathcal{L}}%\n\n\\global\\long\\def\\vw{\\boldsymbol{w}}%\n \n\\global\\long\\def\\vx{\\boldsymbol{x}}%\n \n\\global\\long\\def\\vxi{\\boldsymbol{\\xi}}%\n \n\\global\\long\\def\\valpha{\\boldsymbol{\\alpha}}%\n \n\\global\\long\\def\\vbeta{\\boldsymbol{\\beta}}%\n \n\\global\\long\\def\\vsigma{\\boldsymbol{\\sigma}}%\n\\global\\long\\def\\vtheta{\\boldsymbol{\\theta}}%\n \n\\global\\long\\def\\vd{\\boldsymbol{d}}%\n \n\\global\\long\\def\\vs{\\boldsymbol{s}}%\n \n\\global\\long\\def\\vt{\\boldsymbol{t}}%\n \n\\global\\long\\def\\vh{\\boldsymbol{h}}%\n \n\\global\\long\\def\\ve{\\boldsymbol{e}}%\n \n\\global\\long\\def\\vf{\\boldsymbol{f}}%\n \n\\global\\long\\def\\vg{\\boldsymbol{g}}%\n \n\\global\\long\\def\\vz{\\boldsymbol{z}}%\n \n\\global\\long\\def\\vk{\\boldsymbol{k}}%\n \n\\global\\long\\def\\va{\\boldsymbol{a}}%\n \n\\global\\long\\def\\vb{\\boldsymbol{b}}%\n \n\\global\\long\\def\\vv{\\boldsymbol{v}}%\n \n\\global\\long\\def\\vy{\\boldsymbol{y}}%\n\n\\global\\long\\def\\dom{\\textrm{\\textbf{dom} }}%\n\\global\\long\\def\\rank{\\text{\\textbf{rank }}}%\n\\global\\long\\def\\conv{\\textrm{\\textbf{conv} }}%\n\\global\\long\\def\\relint{\\text{\\textbf{relint }}}%\n\\global\\long\\def\\aff{\\text{\\textbf{aff }}}%\n\n\\global\\long\\def\\hil{\\ch}%\n \n\\global\\long\\def\\rkhs{\\hil}%\n \n\\global\\long\\def\\ber{\\text{Ber}}%\n\n\\title[DS-GA 1003 / CSCI-GA 2567]{Subgradient Descent}\n\\author{Xintian Han \\& David S. Rosenberg }\n\\date{Feb 13, 2019}\n\\institute{NYU CDS}\n\n\\makebeamertitle\n\\mode<article>{Just in article version}\n\n\\begin{frame}{Contents}\n\\tableofcontents{}\n\\end{frame}\n\n\n\\section{Motivation and Review: Lasso}\n\\begin{frame}{The Lasso Problem}\n\\begin{itemize}\n\\item Lasso problem can be parametrized as\n\\[\n\\min_{w\\in\\reals^{d}}J(w) = \\frac{1}{n}\\sum_{i=1}^{n}\\left\\{ w^{T}x_{i}-y_{i}\\right\\} ^{2}+\\lambda\\|w\\|_{1}\n\\]\n\\pause{}\n\\item We could solve Lasso by Shooting Method and Projected SGD.\n\\pause{}\n\\item How about using SGD?\n\\pause{}\n\\item $\\|w\\|_{1}=\\mid w_{1}\\mid+\\mid w_{2}\\mid$ is not differentiable!\n\\end{itemize}\n\\end{frame}\n%\n\\begin{frame}{Gradient Descent on Lasso Objective?}\n\\begin{itemize}\n\\item The partial gradient of the Lasso objective is\n\\[\n\\del_{w}J(w)=\\frac{1}{n}\\sum_{j=1}^n 2\\{w^Tx_j-y_j\\}x_j+\\lambda \\cdot\\text{sign}(w) \n\\]\nwhen $w_i\\neq 0$ for all $i$, and \\textbf{otherwise\nis undefined}.\n\\end{itemize}\n\n\\pause{}\n\nPotential arguments for why we shouldn't care about the points of\nnondifferentiability:\n\\begin{itemize}\n\\item If we start with a random $w$, will we ever hit exactly $w_i=0$?\n\n\\pause{}\n\\item If we did, could we perturb the step size by $\\eps$ to miss such\na point?\n\n\\pause{}\n\\item Does it even make sense to check $w_i=0$ with floating\npoint numbers?\n\\end{itemize}\n\\end{frame}\n%\n\\begin{frame}{Gradient Descent on Lasso Objective?}\n\\begin{itemize}\n\\item If we blindly apply gradient descent from a random starting point\n\\begin{itemize}\n\\item seems unlikely that we'll hit a point where the gradient is undefined.\n\\item So it's clear how we could apply gradient descent or SGD to a function that's not differentiable everywhere\n\\end{itemize}\n\\end{itemize}\n\n\\pause{}\n\\begin{itemize}\n\\item Still, doesn't mean that gradient descent will work if objective not\ndifferentiable!\n\\end{itemize}\n\n\\pause{}\n\\begin{itemize}\n\\item Theory of subgradients and subgradient descent will clear up any uncertainty.\n\\end{itemize}\n\\end{frame}\n%\n\n\\section{Convexity and Sublevel Sets}\n\n\\mode<article>{Just in article version}\n\n \n\\begin{frame}{Convex Sets}\n\n\\begin{definition}\nA set $C$ is \\textbf{convex} if the line segment between any two\npoints in $C$ lies in $C$. \n\\end{definition}\n\n\\begin{center}\n\\includegraphics[height=0.55\\textheight]{fig7\\lyxdot 4a}\\includegraphics[height=0.55\\textheight]{fig7\\lyxdot 4b}\\let\\thefootnote\\relax\\footnotetext{\\tiny{KPM Fig. 7.4}}\n\\par\\end{center}\n\n\\end{frame}\n\n\\begin{frame}{Convex and Concave Functions}\n\\begin{definition}\nA function $f:\\reals^{d}\\to\\reals$ is \\textbf{convex} if the line\nsegment connecting any two points on the graph of $f$ lies above\nthe graph. $f$ is \\textbf{concave }if $-f$ is convex.\n\\end{definition}\n\n\\begin{center}\n\\includegraphics[height=0.5\\textheight]{fig7\\lyxdot 5a}\\includegraphics[height=0.5\\textheight]{fig7\\lyxdot 5b}\\let\\thefootnote\\relax\\footnotetext{\\tiny{KPM Fig. 7.5}}\n\\par\\end{center}\n\n\\end{frame}\n%\n\\begin{frame}{Examples of Convex Functions on $\\reals$}\n\\begin{examples}\n\n\\begin{itemize}\n\\item $x\\mapsto ax+b$ is both convex and concave on $\\reals$ for all $a,b\\in\\reals$.\n\n\\pause{}\n\\item $x\\mapsto\\left|x\\right|^{p}$ for $p\\ge1$ is convex on $\\reals$\n\n\\pause{}\n\\item $x\\mapsto e^{ax}$ is convex on $\\reals$ for all $a\\in\\reals$ \n\n\\pause{}\n\\item Every norm on $\\reals^{n}$ is convex (e.g. $\\|x\\|_{1}$ and $\\|x\\|_{2}$)\n\n\\pause{}\n\\item Max: $\\left(x_{1},\\ldots,x_{n}\\right)\\mapsto\\max\\left\\{ x_{1}\\ldots,x_{n}\\right\\} $\nis convex on $\\reals^{n}$\n\\end{itemize}\n\\end{examples}\n\n\\end{frame}\n%\n\\begin{frame}{Simple Composition Rules }\n\\begin{examples}\n\n\\begin{itemize}\n\\item If $g$ is convex, and $Ax+b$ is an affine mapping, then $g(Ax+b)$\nis convex.\n\\item If $g$ is convex then $\\exp g(x)$ is convex.\n\\item If $g$ is convex and nonnegative and $p\\ge1$ then $g(x)^{p}$ is\nconvex. \n\\item If $g$ is concave and positive then $\\log g(x)$ is concave\n\\item If $g$ is concave and positive then $1/g(x)$ is convex.\n\\end{itemize}\n\\end{examples}\n\n\\end{frame}\n%\n\\begin{frame}{Main Reference for Convex Optimization}\n\\begin{itemize}\n\\item Boyd and Vandenberghe (2004)\n\\begin{itemize}\n\\item Very clearly written, but has a ton of detail for a first pass.\n\\item See the \\href{https://davidrosenberg.github.io/mlcourse/Notes/convex-optimization.pdf}{Extreme Abridgement of Boyd and Vandenberghe}.\n\\end{itemize}\n\\end{itemize}\n\\includegraphics[height=0.6\\textheight]{bv_cvxbook_cover}\n\\end{frame}\n%\n\\begin{frame}{Level Sets and Sublevel Sets}\n\nLet $f:\\reals^{d}\\to\\reals$ be a function. Then we have the following\ndefinitions:\n\\begin{definition}\nA \\textbf{level set} or \\textbf{contour line} for the value $c$ is\nthe set of points $x\\in\\reals^{d}$ for which $f(x)=c$.\n\\end{definition}\n\n\n\\pause{}\n\\begin{definition}\nA \\textbf{sublevel} set for the value $c$ is the set of points $x\\in\\reals^{d}$\nfor which $f(x)\\le c$.\n\\end{definition}\n\n\n\\pause{}\n\\begin{theorem}\nIf $f:\\reals^{d}\\to\\reals$ is \\textbf{convex}, then the \\textbf{sublevel\nsets are convex}. \n\\end{theorem}\n\n\n\\pause{}\n\n(Proof straight from definitions.)\n\\end{frame}\n%\n\\begin{frame}{Convex Function}\n\\begin{center}\n\\includegraphics[height=0.65\\textheight]{3d-plot-convex-fn} \n\\par\\end{center}\n\n\\begin{center}\n\\let\\thefootnote\\relax\\footnotetext{\\tiny{Plot courtesy of Brett Bernstein.}}\n\\par\\end{center}\n\n\\end{frame}\n%\n\\begin{frame}{Contour Plot Convex Function: Sublevel Set}\n\\begin{center}\n\\includegraphics[height=0.65\\textheight]{contour-plot-convex-fn}\n\\par\\end{center}\n\nIs the sublevel set $\\left\\{ x\\mid f(x)\\le1\\right\\} $ convex?\n\\begin{center}\n\\let\\thefootnote\\relax\\footnotetext{\\tiny{Plot courtesy of Brett Bernstein.}}\n\\par\\end{center}\n\n\\end{frame}\n%\n\\begin{frame}{Nonconvex Function}\n\\begin{center}\n\\includegraphics[height=0.7\\textheight]{3d-plot-nonconvex-fn}\\let\\thefootnote\\relax\\footnotetext{\\tiny{Plot courtesy of Brett Bernstein.}}\n\\par\\end{center}\n\n\\end{frame}\n%\n\\begin{frame}{Contour Plot Nonconvex Function: Sublevel Set}\n\\begin{center}\n\\includegraphics[height=0.65\\textheight]{contour-plot-nonconvex-fn}\n\\par\\end{center}\n\nIs the sublevel set $\\left\\{ x\\mid f(x)\\le1\\right\\} $ convex?\n\\begin{center}\n\\let\\thefootnote\\relax\\footnotetext{\\tiny{Plot courtesy of Brett Bernstein.}}\n\\par\\end{center}\n\n\\end{frame}\n%\n\\begin{frame}{Fact: Intersection of Convex Sets is Convex}\n\\begin{center}\n\\includegraphics[height=0.65\\textheight]{convex-set-intersection} \n\\par\\end{center}\n\n\\begin{center}\n\\let\\thefootnote\\relax\\footnotetext{\\tiny{Plot courtesy of Brett Bernstein.}}\n\\par\\end{center}\n\n\\end{frame}\n%\n\\begin{frame}{Level and Superlevel Sets}\n\\begin{center}\n\\includegraphics[height=0.65\\textheight]{superlevel-sets}\n\\par\\end{center}\n\nLevel sets and superlevel sets of convex functions are \\textbf{not}\ngenerally convex.\n\\begin{center}\n\\let\\thefootnote\\relax\\footnotetext{\\tiny{Plot courtesy of Brett Bernstein.}}\n\\par\\end{center}\n\n\\end{frame}\n%\n\\begin{frame}{Convex Optimization Problem: Standard Form}\n\\begin{block}{Convex Optimization Problem: Standard Form}\n\\begin{eqnarray*}\n\\textrm{minimize} &  & f_{0}(x)\\\\\n\\textrm{subject to} &  & f_{i}(x)\\le0,\\;\\;i=1,\\ldots,m\n\\end{eqnarray*}\nwhere $f_{0},\\ldots,f_{m}$ are convex functions. \n\\end{block}\n\n\\pause{}\n\\begin{itemize}\n\\item What can we say about each constraint set $\\left\\{ x\\mid f_{i}(x)\\le0\\right\\} ?\\pause$\n(convex)\n\\item What can we say about the feasible set $\\left\\{ x\\mid f_{i}(x)\\le0,\\,i=1,\\ldots,m\\right\\} ?\\pause$\n(convex)\n\\end{itemize}\n\\end{frame}\n%\n\\begin{frame}{Convex Optimization Problem: Implicit Form}\n\\begin{block}{Convex Optimization Problem: Implicit Form}\n\\begin{eqnarray*}\n\\textrm{minimize} &  & f(x)\\\\\n\\textrm{subject to} &  & x\\in C\n\\end{eqnarray*}\nwhere $f$ is a convex function and $C$ is a convex set.\n\n\\pause{}\n\nAn alternative ``generic'' convex optimization problem.\n\\end{block}\n\\end{frame}\n%\n\n\\section{Convex and Differentiable Functions}\n\\begin{frame}{First-Order Approximation}\n\\begin{itemize}\n\\item Suppose $f:\\reals^{d}\\to\\reals$ is \\textbf{differentiable.}\n\\item Predict $f(y)$ given $f(x)$ and $\\del f(x)$?\n\n\\pause{}\n\\item Linear (i.e. ``\\textbf{first order}'') approximation:\n\\[\nf(y)\\approx f(x)+\\del f(x)^{T}(y-x)\n\\]\n\\end{itemize}\n\\begin{center}\n\\let\\thefootnote\\relax\\footnotetext{\\tiny{Boyd \\& Vandenberghe Fig. 3.2}}\n\\par\\end{center}\n\n\\begin{center}\n\\includegraphics[width=0.7\\columnwidth]{BVFig3\\lyxdot 2-convexTangent}\n\\par\\end{center}\n\n\\end{frame}\n%\n\\begin{frame}{First-Order Condition for Convex, Differentiable Function}\n\n\\begin{itemize}\n\\item Suppose $f:\\reals^{d}\\to\\reals$ is \\textbf{convex} and \\textbf{differentiable.}\n\\item Then for any $x,y\\in\\reals^{d}$\n\\[\nf(y)\\ge f(x)+\\del f(x)^{T}(y-x)\n\\]\n\n\n\\pause{}\n\\item The linear approximation to $f$ at $x$ is a \\textbf{global underestimator\n}of $f$:\n\\end{itemize}\n\\let\\thefootnote\\relax\\footnotetext{\\tiny{Figure from Boyd \\& Vandenberghe Fig. 3.2; Proof in Section 3.1.3 }}\n\\begin{center}\n\\includegraphics[width=0.7\\columnwidth]{BVFig3\\lyxdot 2-convexTangent}\n\\par\\end{center}\n\n\\end{frame}\n%\n\\begin{frame}{First-Order Condition for Convex, Differentiable Function}\n\\begin{itemize}\n\\item Suppose $f:\\reals^{d}\\to\\reals$ is \\textbf{convex} and \\textbf{differentiable}\n\\item Then for any $x,y\\in\\reals^{d}$\n\\[\nf(y)\\ge f(x)+\\del f(x)^{T}(y-x)\n\\]\n\n\n\\pause{}\n\n\\end{itemize}\n\\begin{corollary}\nIf $\\del f(x)=0$ then $x$ is a global minimizer of $f$.\n\\end{corollary}\n\n\n\\pause{}\n\nFor convex functions, \\textbf{local information gives global information.}\n\\end{frame}\n\n\\section{Subgradients }\n\\begin{frame}{Subgradients}\n\\begin{definition}\nA vector $g\\in\\reals^{d}$ is a \\textbf{subgradient} of $f:\\reals^{d}\\to\\reals$\nat $x$ if for all $z$, \n\\[\nf(z)\\ge f(x)+g^{T}(z-x).\n\\]\n\n\\pause{}\n\\end{definition}\n\n\\begin{center}\n\\includegraphics[height=0.4\\textheight]{Subderivative_illustration}\n\\par\\end{center}\n\nBlue is a graph of $f(x)$. \\\\\nEach red line $x\\mapsto f(x_{0})+g^{T}\\left(x-x_{0}\\right)$ is a\nglobal lower bound on $f(x)$.\n\\end{frame}\n%\n\\begin{frame}{Subdifferential}\n\\begin{definitions}\n\\begin{itemize}\n\\item $f$ is \\textbf{subdifferentiable} at $x$ if $\\exists$ at least\none subgradient at $x$. \n\\item The set of all subgradients at $x$ is called the \\textbf{subdifferential:}\n$\\partial f(x)$ \n\n\\pause{}\n\n\\end{itemize}\n\\end{definitions}\n\n\\begin{block}{Basic Facts}\n\\end{block}\n\\begin{itemize}\n\\item $f$ is convex and differentiable $\\implies$ $\\partial f(x)=\\left\\{ \\del f(x)\\right\\} $.\n\n\\pause{}\n\\item Any point $x$, there can be $0$, $1$, or infinitely many subgradients.\n\n\\pause{}\n\\item $\\partial f(x)=\\emptyset$ $\\implies$ $f$ is not convex.\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Globla Optimality Condition}\n\\begin{definition}\nA vector $g\\in\\reals^{d}$ is a \\textbf{subgradient} of $f:\\reals^{d}\\to\\reals$\nat $x$ if for all $z$, \n\\[\nf(z)\\ge f(x)+g^{T}(z-x).\n\\]\n\n\\pause{}\n\n\\end{definition}\n\n\\begin{corollary}\nIf $0\\in\\partial f(x)$, then $x$ is a \\textbf{global minimizer}\nof $f$.\n\\end{corollary}\n\n\\end{frame}\n\n\\begin{frame}{Subdifferential of Absolute Value}\n\\begin{itemize}\n\\item Consider $f(x)=\\left|x\\right|$\n\n\\pause{}\n\n\\end{itemize}\n\\let\\thefootnote\\relax\\footnotetext{\\tiny{Boyd EE364b: Subgradients Slides}}\n\n\\begin{center}\n\\includegraphics[width=0.8\\columnwidth]{subgradient-absolute-value}\n\\par\\end{center}\n\\begin{itemize}\n\\item Plot on right shows $\\left\\{ (x,g)\\mid x\\in\\reals,\\;g\\in\\partial f(x)\\right\\} $ \n\\end{itemize}\n\\end{frame}\n%\n\\begin{frame}{$f(x_{1},x_{2})=\\left|x_{1}\\right|+2\\left|x_{2}\\right|$}\n\\begin{center}\n\\includegraphics[height=0.75\\textheight]{3d-plot-abs-x1-plus-2absx2}\\let\\thefootnote\\relax\\footnotetext{\\tiny{Plot courtesy of Brett Bernstein.}}\n\\par\\end{center}\n\n\\end{frame}\n%\n\\begin{frame}{Subgradients of $f(x_{1},x_{2})=\\left|x_{1}\\right|+2\\left|x_{2}\\right|$}\n\\begin{itemize}\n\\item Let's find the subdifferential of $f(x_{1},x_{2})=\\left|x_{1}\\right|+2\\left|x_{2}\\right|$\nat $\\left(3,0\\right)$.\n\\end{itemize}\n\n\\pause{}\n\\begin{itemize}\n\\item First coordinate of subgradient must be $1$, from $\\left|x_{1}\\right|$\npart (at $x_{1}=3$).\n\\end{itemize}\n\n\\pause{}\n\\begin{itemize}\n\\item Second coordinate of subgradient can be anything in $\\left[-2,2\\right]$.\n\\end{itemize}\n\n\\pause{}\n\\begin{itemize}\n\\item So graph of $h(x_{1},x_{2})=f(3,0)+g^{T}\\left(x_{1}-3,x_{2}-0\\right)$\nis a global underestimate of $f(x_{1},x_{2})$, for any $g=\\left(g_{1},g_{2}\\right),$\nwhere $g_{1}=1$ and $g_{2}\\in[-2,2]$. \n\\end{itemize}\n\\end{frame}\n%\n\\begin{frame}{Underestimating Hyperplane to $f(x_{1},x_{2})=\\left|x_{1}\\right|+2\\left|x_{2}\\right|$}\n\\begin{center}\n\\includegraphics[height=0.75\\textheight]{underestimating-3d-plot-abs-x1-plus-2absx2}\\let\\thefootnote\\relax\\footnotetext{\\tiny{Plot courtesy of Brett Bernstein.}} \n\\par\\end{center}\n\n\\end{frame}\n\n\\begin{frame}{Important Properties of Subdifferential}\n\\begin{itemize}\n\\item If $f_1,\\dots,f_m:\\reals^d \\rightarrow \\reals$ are convex functions and $f = f_1+\\cdots + f_m$, then $\\partial f(x) = \\partial f_1(x) + \\cdots +\\partial f_m(x)$.\n\\item For $\\alpha \\geq 0$, $\\partial (\\alpha f) (x) = \\alpha \\partial f(x)$. \t\n\\end{itemize}\n\t\n\\end{frame}\n\n\\begin{frame}{Subgradients of $f(x) = \\|x\\|_1$}\n\\begin{itemize}\n\\item Let's find the subdifferential of $f(x) = \\|x\\|_1 = \\sum_{i=1}^d |x_i|$ at any given point $x^0 = (x^0_1,x^0_2, \\dots, x^0_d)$.\n\\item By an important property of subdifferential: If $f = f_1+\\cdots+f_m$, then $\\partial f(x) = \\partial f_1(x) + \\cdots \\partial f_m(x)$. \n\\item We could calculate the subgradient of $f^i(x) = |x_i|$ and sum them up.\n\\item The subgradient $g^i = (g^i_1,\\dots, g^i_d)$ of $f^i(x) = |x_i|$ at $x^0 = (x^0_1,x^0_2, \\dots, x^0_d)$ is:\n\\[\ng_j^i = 0, \\quad {j\\neq i}; \\quad g_j^i = s(x^0_j), \\quad j = i,\n\\]\nwhere $s(x) = \\text{sign}(x)$ if $x\\neq 0$ and $s(x) \\in [-1,1]$ if $x = 0$\n\\item We sum all the $g^i$ up to get the subgradient $g = (g_1,\\dots, g_d)$ of $f(x)$ at $x^0$:\n\\[\ng_i = s(x^0_i) \\quad \\text{for all } i\n\\]\n\\end{itemize}\n\n\\end{frame}\n\n%\n\n\\section{Subgradient Descent}\n\\begin{frame}{Subgradient Descent}\n\\begin{itemize}\n\\item Suppose $f$ is convex, and we start optimizing at $x_{0}$.\n\\item Repeat\n\\begin{itemize}\n\\item Step in a negative subgradient direction: \n\\[\nx=x_{0}-tg,\n\\]\nwhere $t>0$ is the step size and $g\\in\\partial f(x_{0})$.\n\\end{itemize}\n\\end{itemize}\n\n\\pause{}\n\\begin{itemize}\n\\item $-g$ not a descent direction -- can this work?\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Convergence Theorem for Fixed Step Size}\n\nAssume $f:\\reals^{n}\\to\\reals$ is convex and\n\\begin{itemize}\n\\item $f$ is Lipschitz continuous with constant $G>0$:\n\\[\n\\left|f(x)-f(y)\\right|\\le G\\|x-y\\|\\mbox{ for all }x,y\n\\]\n\\end{itemize}\n\\begin{theorem}\nFor fixed step size $t$, subgradient method satisfies:\n\\[\n\\lim_{k\\to\\infty}f(x_{\\text{best}}^{(k)})\\le f(x^{*})+G^{2}t/2\n\\]\n\\end{theorem}\n\n\\begin{center}\n\\let\\thefootnote\\relax\\footnotetext{\\tiny{Based on \\url{https://www.cs.cmu.edu/~ggordon/10725-F12/slides/06-sg-method.pdf}}}\n\\par\\end{center}\n\n\\end{frame}\n\n\\begin{frame}{Convergence Theorems for Decreasing Step Sizes}\n\nAssume $f:\\reals^{n}\\to\\reals$ is convex and\n\\begin{itemize}\n\\item $f$ is Lipschitz continuous with constant $G>0$:\n\\[\n\\left|f(x)-f(y)\\right|\\le G\\|x-y\\|\\mbox{ for all }x,y\n\\]\n\\end{itemize}\n\\begin{theorem}\nFor step size respecting Robbins-Monro conditions,\n\\[\n\\lim_{k\\to\\infty}f(x_{\\text{best}}^{(k)})=f(x^{*})\n\\]\n\\end{theorem}\n\n\\begin{center}\n\\let\\thefootnote\\relax\\footnotetext{\\tiny{Based on \\url{https://www.cs.cmu.edu/~ggordon/10725-F12/slides/06-sg-method.pdf}}}\n\\par\\end{center}\n\\end{frame}\n\n\\begin{frame}{Subgradient Descent for Lasso Problem}\n\\begin{itemize}\n\\item Lasso problem can be parametrized as\n\\[\n\\min_{w\\in\\reals^{d}}J(w) = \\frac{1}{n}\\sum_{i=1}^{n}\\left\\{ w^{T}x_{i}-y_{i}\\right\\} ^{2}+\\lambda\\|w\\|_{1}\n\\]\n\\pause{}\n\\item Subgradients of $J(w)$ are\n\\[\n\\frac{1}{n}\\sum_{i=1}^n 2\\{w^Tx_i-y_i\\}x_i+\\lambda s,\n\\]\nwhere $s_i = \\text{sign}(w_i)$ if $w_i\\neq 0$ and $s_i \\in [-1,1]$ if $w_i=0$.\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Subgradient Descent for Lasso Problem: Potential Issues}\n\\begin{itemize}\n\\item Subgradient descent will work for all convex and Lipschitz continuous objective functions.\n\\pause{}\n\\item BUT, convergence can be very \\textbf{slow} for non-differentiable functions\n\\pause{}\n\\item One can often find better approaches by closer examination of the objective function. For example, shooting method or projected SGD.\n\\pause{}\n\\item Taking small steps in the direction of the (sub)gradient usually may \\textbf{not} lead to zero coordinates.\n\\pause{}\n\\item BUT, in practice, we can threshold small values.\n\\end{itemize}\n\t\n\\end{frame}\n\\begin{frame}{Appendix: Subgradient Gets Us Closer To Minimizer}\n\\begin{theorem}\nSuppose $f$ is convex.\n\\begin{itemize}\n\\item Let $x=x_{0}-tg$, for $g\\in\\partial f(x_{0})$.\n\\item Let $z$ be any point for which $f(z)<f(x_{0})$.\n\\item Then for small enough $t>0$,\n\\[\n\\|x-z\\|_{2}<\\|x_{0}-z\\|_{2}.\n\\]\n\\end{itemize}\n\n\\pause{}\n\\end{theorem}\n\n\\begin{itemize}\n\\item Apply this with $z=x^{*}\\in\\argmin_{x}f(x)$. \n\\end{itemize}\n$\\implies$\\textbf{Appendix: Negative subgradient step gets us closer to minimizer}.\n\\end{frame}\n\n\\begin{frame}{Subgradient Gets Us Closer To Minimizer (Proof)}\n\\begin{itemize}\n\\item Let $x=x_{0}-tg$, for $g\\in\\partial f(x_{0})$ and $t>0$.\n\\item Let $z$ be any point for which $f(z)<f(x_{0})$.\n\\item Then\n\\begin{eqnarray*}\n\\|x-z\\|_{2}^{2} & = & \\|x_{0}-tg-z\\|_{2}^{2}\\\\\n\\pause & = & \\|x_{0}-z\\|_{2}^{2}-2tg^{T}\\left(x_{0}-z\\right)+t^{2}\\|g\\|_{2}^{2}\\\\\n\\pause & \\le & \\|x_{0}-z\\|_{2}^{2}-2t\\left[f(x_{0})-f(z)\\right]+t^{2}\\|g\\|_{2}^{2}\n\\end{eqnarray*}\n\n\n\\pause{}\n\\item Consider $-2t\\left[f(x_{0})-f(z)\\right]+t^{2}\\|g\\|_{2}^{2}$. \n\\begin{itemize}\n\\item It's a convex quadratic (facing upwards).\n\\item Has zeros at $t=0$ and $t=2\\left(f(x_{0})-f(z)\\right)/\\|g\\|_{2}^{2}>0$.\n\\item Therefore, it's negative for any \n\\[\nt\\in\\left(0,\\frac{2\\left(f(x_{0})-f(z)\\right)}{\\|g\\|_{2}^{2}}\\right).\n\\]\n\\end{itemize}\n\n\\let\\thefootnote\\relax\\footnotetext{\\tiny{Based on Boyd EE364b: Subgradients Slides}}\n\\end{itemize}\n\\end{frame}\n\n\\end{document}\n", "meta": {"hexsha": "b6f0730bcdbe3b22ab71ef82a30f9df466d45832", "size": 24614, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Archive/2019/Lectures/source/03c.subgradient-descent-lasso/03c.subgradient-descent-lasso.tex", "max_stars_repo_name": "LBJ-Wade/mlcourse", "max_stars_repo_head_hexsha": "f5af0db001bf5e2fb153d381c10b35d34a491ebf", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 484, "max_stars_repo_stars_event_min_datetime": "2016-01-29T18:44:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T21:31:34.000Z", "max_issues_repo_path": "Archive/2019/Lectures/source/03c.subgradient-descent-lasso/03c.subgradient-descent-lasso.tex", "max_issues_repo_name": "LBJ-Wade/mlcourse", "max_issues_repo_head_hexsha": "f5af0db001bf5e2fb153d381c10b35d34a491ebf", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 76, "max_issues_repo_issues_event_min_datetime": "2016-12-25T19:14:21.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-20T19:52:59.000Z", "max_forks_repo_path": "Archive/2019/Lectures/source/03c.subgradient-descent-lasso/03c.subgradient-descent-lasso.tex", "max_forks_repo_name": "LBJ-Wade/mlcourse", "max_forks_repo_head_hexsha": "f5af0db001bf5e2fb153d381c10b35d34a491ebf", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 248, "max_forks_repo_forks_event_min_datetime": "2016-01-31T04:11:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T00:45:41.000Z", "avg_line_length": 26.5523193096, "max_line_length": 168, "alphanum_fraction": 0.6951328512, "num_tokens": 9065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.3374704163196747}}
{"text": "\\documentclass[a4paper,12pt]{article}\n\n\n\\usepackage[latin2]{inputenc}\n\\usepackage{t1enc}\n\\usepackage{graphicx}\n\\usepackage{amsmath}\n\\usepackage{amsthm}\n\\usepackage{amssymb}\n\\usepackage{natbib}\n\\usepackage{longtable}\n\\usepackage[table]{xcolor}\n\\usepackage[affil-it]{authblk}\n\n  \\newcommand{\\biexample}[2]{\n* \\hspace{1cm}   $v_A$: \\texttt{#1} \\\\\n* \\hspace{1cm}   $v_B$: \\texttt{#2} \\\\\n}\n\n\\newcommand{\\triexample}[3]{ \\\\\n* \\hspace{1cm}   $v_A$: \\texttt{#1} \\\\\n* \\hspace{1cm}   $v_B$: \\texttt{#2} \\\\\n* \\hspace{1cm}   $v_C$: \\texttt{#3}\n}\n\n\\newtheorem{thm}{Theorem}[section]\n\\newtheorem{lemma}{Lemma}[section]\n\\newtheorem{cor}{Corollary}[section]\n\\newtheorem{fact}{Fact}[section]\n\\newtheorem{claim}{Claim}[section]\n\\newtheorem{example}{Example}[section]\n\\newtheorem{defn}{Definition}[section]\n\n\n\n\\begin{document}\n\n\\title{Aggregate-monotonicity and Population-monotonicity in Cake-cutting}\n\n\\author{Erel Segal-Halevi}\n\\affil{Bar-Ilan University}\n\n\\author{Bal{\\'{a}}zs Sziklai}\n\\affil{Centre for Economic and Regional Studies, Hungarian Academy of Sciences, \\iffalse Buda\\\"{o}rsi 45. H-1112 Budapest,  \\fi E-mail: koczy@krtk.mta.hu, sziklai.balazs@krtk.mta.hu}\n\n\n\n\n\n\n\\date{\\today}\n\n\\bibliographystyle{apalike}\n\n\\maketitle\n\n\n\n\\section{Introduction}\n\nA village is built near the sea shore and its lands are divided fairly among the founders. In time, the village grows in area and the lands are re-divided. Can we guarantee that all villagers gain from the growth, or at least not lose?\nSome time later, a few villagers leave the village and their lands become free for re-division. Can we guarantee that all remaining villagers gain from this re-division, or at least not lose?\n\nSimilar questions may arise in inheritance cases and divorce settlements. Although the monotonicity issues of division rules have been extensively studied with respect to cooperative game theory \\citep{Calleja2012}, the apportionment problem \\citep{Balinski1982} or classical economic models \\citep{Thomson_2011}, the cake-cutting literature so far focused on other properties of fairness, like proportionality and envy-freeness.\n\nAggregate monotonicity\\footnote{Also known as resource monotonicity.} requires that whenever the cake is enlarged the welfare of the participants should weakly increase. Population monotonicity is concerned with changes in the number of participants. No one should profit from the arrival of a new agent, when more people share the same resource, and everyone should be weakly better of if someone leaves\\footnote{\\cite{Thomson_2011} uses a more subtle phrasing. He requires that, whenever a change happens in the environment and no one is responsible for it, the welfare of all agents should be affected in the same direction.}. Note, that population monotonicity fundamentally differs from the so called consistency axiom, where the leaving agents take their fair shares with them (cf. \\cite{Young1987} or \\cite{Thomson_2012}).\n\nExperimental studies show that people value certain fairness criteria more than others. \\cite{Herreiner2009} demonstrated that people are willing to sacrifice Pareto-efficiency in order to reach an envy free allocation. To our knowledge no study was ever conducted to unfold the relationship between monotonicity and efficiency or envy-freeness. However some indirect evidence points toward that monotonicity of the solution is in some cases as important as proportionality. \n\nIn the apportionment problem there is a parliament with a fixed number of seats and administrative regions with different number of voters. The question is -- assuming that electoral districts are of equal size within each of the administrative regions -- how to distribute the seats among the administrative regions to minimize the differences between the voters influences. The problem is analogous to cake-cutting where the cake corresponds to the parliamentary seats that have to be distributed. During the 1880 US census C.W. Seaton, a Chief Clerk of the Census Office, noted that an enlargement of the House of Representatives from 299 to 300 would result in loss of seat for State Alabama. This anomaly together with the later discovered population and new state paradoxes pressed the legislators to adopt newer and newer apportionment rules. The currently used seat distribution method is free from such anomalies, however it does not satisfy the so called Hare-quota, a basic guarantee of proportionality \\citep{Balinski1975}.\n\nIn this paper we analyze aggregate and population monotonicity with respect to cake-cutting. We show that none of the traditional cake cutting protocols satisfy aggregate monotonicity. In particular all the methods which are based on the cut and choose scheme violate it. We show an aggregate monotonic two player method and prove the existence of a proportional and Pareto-optimal protocol which satisfies both aggregate and population monotonicity. In addition we prove several impossibility results. Most importantly we show that aggregate monotonicity is not compatible with proportionality and Pareto-efficiency if we only allow contiguous pieces.  \n\n%The size of the parliament changes due to various reasons, as it did in the US House of Representatives in 1880. \n\n%These two questions motivate the two axioms of \\emph{aggregate monotonicity (AM)} and \\emph{population monotonicity (PM)}. These axioms have been studied in the context of resource allocation; we study these axioms in the context of the classic cake-cutting problem \\cite{Steinhaus1948Problem}.\n\n\n\n\\iffalse\n\\section{Model}\nThere is a cake $C$, which is assumed to be a 1-dimensional interval in $\\mathbb{R}$. There are $n$ agents with different value measures over subsets of the cake. The value measure of agent $i$ is $V_i$. The value measures are assumed to be \\emph{absolutely continuous with respect to length}, or just \\emph{continuous} for short. This means that there are no valuable \"atoms\" - all singular points have zero value to all agents. The value measures of all agents are normalized such that $\\forall i: V_i(C)=1$.\nAll these assumptions are common in the cake-cutting literature.\n\nThe cake should be partitioned to $n$ measurable pairwise-disjoint subsets, which we call \"pieces\". The piece allocated to agent $i$ is marked $C_i$.\n\nA \\emph{division rule} is a function that takes as input $n$ continuous value measures and returns a single partition, or a set of partitions.\n\nA partition is called \\emph{whole} (WH) if the entire cake is divided, i.e: $\\cup_{i=1}^{n}{C_i}=C$. In this paper we consider only whole partitions.\n\nA partition is called \\emph{connected} (CON) if each piece is connected (i.e, an interval).\n\nA partition is called \\emph{proportional} (PROP) if each agent values its piece as at least $1/n$: $\\forall i V_i(C_i)\\geq 1/n$. This was the first fairness criterion studied in the context of cake-cutting \\cite{Steinhaus1948Problem}.\n\nA partition is called \\emph{Pareto-optimal} (PO) if there is no partition which is weakly better for all agents and strictly better for at least one agent.\n\nOften, we consider only connected partitions. In these cases, we call a partition \\emph{Pareto-optimal for Connected Allocations} (POCA) if there is no \\emph{connected} partition which is weakly better for all agents and strictly better for at least one agent.\n\nA division rule is called WH/CON/PROP/PO/POCA if it returns only WH/CON/PROP/PO/POCA partitions, respectively.\n\nFor division rules that return a single partition, the following definitions hold:\n\\begin{itemize}\n\\item{A rule is AM if, whenever the cake grows [to one side], the value of the piece allocated to each agent is weakly larger.}\n\\item{A rule is PM if, whenever one or more agents leave, the value of the piece allocated to each remaining agent is weakly larger.}\n\\end{itemize}\n\nFor division rules that return a set of partitions, the following definitions hold:\n\\begin{itemize}\n\\item{A rule is AM if, for every x in the set returned for the smaller (original) cake, there exists y in the set returned for the larger (new) cake,\nsuch that y is at least as good as x for every agent.}\n\\item{A rule is PM if, for every x in the set returned for the larger number of agents, there exists y in the set returned for the smaller (new) number of agents, such that y is at least as good as x for every remaining player.}\n\\end{itemize}\n\nThe following table summarizes the abbreviations we use for the axioms we study in this paper.\n\n\\begin{table}\n    \\begin{tabular}{|l|l|}\n        CON  & All players receive connected pieces \\\\\n        PROP & Proportional - every player receives at least $1/n$ of total  \\\\\n        PO   & Pareto-Optimal (no weakly better allocation) \\\\\n        POCA & Pareto-Optimal assuming connected pieces (no weakly better allocation with connected pieces)  \\\\\n        WH   & Whole cake is divided (note that PO $\\to$ POCA $\\to$ WH) \\\\\n        AM   & Aggregate-monotonic  (one-sided) \\\\\n        PM   & Population-monotonic \\\\\n    \\end{tabular}\n\\end{table}\n\nWe say that two or more axioms are \\emph{compatible} if there exists a division rule which satisfies all of them. Our goal in the rest of the paper is to check what axioms are compatible with the monotonicity axioms AM and PM.\n\n\n\\section{Related Work}\nThe AM and PM axioms were studied in the context of fair division of homogeneous resources \\cite{Moulin_1988} \\cite{Moulin_1990} \\cite{Thomson_1994} \\cite{Thomson_2011}.\n\nOther axioms were studied in the context of fair cake-cutting. \\cite{Chambers_2005} studied the axiom of \\emph{division independence}, which means that, if a land is divided to sub-plots and each sub-plot is divided according to a rule, then the outcome is identical to dividing the original land using that rule. He proves that the only rule which satisfies PO and division-independence is the \\emph{utilitarian-optimal} rule - the rule which maximizes the sum of the agents' utilities. Unfortunately, this rule is incompatible with CON - the piece given to each agent might be a collection of infinitely many tiny fractions of land. We believe that in practical land division setting, connectivity is crucial.\n\n\n\\section{Aggregate Monotonicity with Connected Pieces}\nIn this section, we assume that CON is a non-negotiable requirement. This makes sense, for example, when the \"cake\" which has to be divided is a land. People usually want a single, connected piece of land, rather than a large collection of small patches.\n\nIt is well known that CON+PO are incompatible. Consider the following cake:\n\n\\biexample{0101}{1010}\n\nThe only PO allocation is to give slices 1 and 3 to B and the other slices to A, but this allocation is not CON. Therefore, when CON is a requirement, we use either POCA or WH.\n\n\\begin{thm}\nThe global PROP solution (the solution that returns all proportional allocations) is not AM (not even OSAM).\n\\end{thm}\n\\begin{proof}\nConsider the following cake:\n\n\\biexample{0011}{1111}\n\nThe global solution returns some allocations in which the value of A is 2.\n\nHowever, when the cake is increased to the right like this:\n\n\\biexample{001100}{111111}\n\nthe only proportional allocation gives A a value of 1.\n\\end{proof}\n\n\nThe following result is positive:\n\n\\begin{thm}\nFor two agents, CON+PROP+WH+AM (one-sided) are compatible.\n\\end{thm}\n\\begin{proof}\nThe proof is constructive: we show an AM cake-cutting procedure, which works for the two person case and needs only one cut. Its like a Dubins-Spanier moving knife method only its reversed (instead of left to right, the knife moves from right to left).\n\\begin{itemize}\n\\item{Ask both players to make a mark which cuts the cake in half according their own valuation.}\n\\item{Cut the cake at the righmost mark and give the slice on the right to the player who made the mark.}\n\\item{The remaining part is given to the other player.}\n\\end{itemize}\n\n\nWe now prove that this algorithm is AM when the cake grows to the right. Suppose that the order of marks on the smaller cake was A:B. So Bob got the part from mark B to the right of the cake, which is exactly half for him, and Alice got the part from B to the left of the cake, which is more than half for her. When the cake becomes larger, Bob necessarily receives at least half of a bigger total. For Alice, there are two possible cases:\n\\begin{itemize}\n\\item{If the order of marks on the larger cake is still A:B, then, since the mark of B moved rightwards, Alice receives a piece containing his previous piece.}\n\\item{If the order of the marks on the larger cake is B:A, then Alice now receives the part from A to the right of the cake, but this part is equal for him to the part from A to the left of the cake, which contains the part from B to the left of the cake, which contains Alice's previous piece.}\n\\end{itemize}\n\\end{proof}\n\nThe above procedure divides the whole cake (WH), but the allocation it finds is not necessarily POCA. Indeed, we have:\n\n\\begin{thm}\nCON+PROP+POCA+AM (one-sided) are incompatible even for two agents.\n\\end{thm}\n\\begin{proof}\nConsider the following cake:\n\n\\biexample{401}{022}\n\nAny protocol that is CON+PROP+POCA must cut after the first slice. No other allocation is possible. Hence, A gets 4 and B gets 4.\n\nNow the cake grows in the following way:\n\n\\biexample{4014}{0220}\n\nNow by proportionality we must give A at least 4.5. No matter how it is done, B gets less than 4. Hence the protocol is not AM.\n\\end{proof}\n\n\\textcolor{red}{\nWe have to check whether CON+PROP+WH+AM are compatible for 3 or more agents.\nIf not, whether CON+PROP+AM are compatible for 3 or more agents.\n}\n\n\n\\begin{figure}[h!]\n\\begin{center}\n\\includegraphics[width=0.7\\columnwidth]{TwoPlayerAM.pdf}\n\\caption{Replace this text with your caption%\n}\n\\end{center}\n\\end{figure}\n\n\\section{Population Monotonicity with Connected Pieces}\n\n\\begin{thm}\nCON+PROP+POCA+PM are incompatible.\n\\end{thm}\n\n\\begin{proof}\nConsider the following preferences:\n\\triexample{0202020200}{0000000030}{2000002003}\nIf C receives the left piece, then by PROP the piece must touch the two \"2\" slices.\nBut then, only a value of 2 is left for A, which contradicts PROP.\nB also obviously cannot receive the left piece.\nHence, A must receive the left piece.\n\nIf C receives the next piece to the right, it must touch the \"2\" and the \"3\", which leaves B with no value. Hence, B must receives the next piece, whose value is 3 (and C receives the right piece, whose value is 3).\n\nBy POCA, this means that A must receive all the cake up to the \"3\" slice of B, which means that A's value is 8.\n\nNow, suppose player B leaves. Now $n=2$, so player C must get a value of at least 7/2, so he must get at least the \"3\" and \"2\". But this means that A receives a value of at most 6.\n\\end{proof}\n\nNote that this proof relies on POCA. Without POCA, we could not prove that the initial value of A must be 8.\n\n\\textcolor{red}{\nWe have to check whether CON+PROP+WH+PM are compatible.\nIf not, check whether    CON+PROP+PM are compatible.\n}\n\n\n\n\n\\section{Disconnected pieces}\nIn this section we assume that the piece given to each agent need not be connected; it is only required to be measurable. We are going to describe a division rule that satisfies PROP+AM+PM+PO. For ease of presentation, we first describe two simpler rules: a rule that satisfies PROP+AM+PM but is not PO, and a rule that satisfies PO+AM+PM but is not PROP. Then\n\n\\subsection{A PROP+AM+PM division rule}\nGiven integers $n\\geq 1$ and $k\\geq 1$, an \\textit{exact division} of a cake, marked $Exact(n,k)$, is a partition of the cake to $k$ pieces, such that each of $n$ agents believes that each piece is worth \\emph{exactly} $1/k$. Note that an $Exact(n,n)$ division is PROP.\n\nFor every $n$ and $k$, there exists an $Exact(n,k)$ division of a cake with at most $n(k-1)$ cuts, and this is the smallest number of cuts that can be guaranteed \\cite{Alon_1987}. In particular, there exists an $Exact(n,n)$ division of a cake with at most $n(n-1)$ cuts, and for every $n\\geq 2$, such a division is not necessarily CON (since there are more than $n-1$ cuts).\n\nAn exact division is necessarily PM, since when an agent leaves, the value of each of the remaining agents rises from $1/n$ to $1/(n-1)$. It is also necessarily AM, since when the cake increases (to either side), all agents receive exactly $1/n$ of a larger whole. Hence we get:\n\n\\begin{thm}\nPROP+AM+PM  are compatible.\n\\end{thm}\n\nNote that for $n=2$, there is a moving-knife procedure that actually finds an exact division \\cite{Austin_1982}. Hence, for $n=2$ the above theorem is constructive.\n\n\n\n\\subsection{An AM+PM+PO division rule}\nOur PO solution relies maximizing the sum of the agents' values (also termed: \\emph{utilitarian social welfare}). The relation between social welfare optimization and Pareto optimality is well-studied, e.g \\cite{Varian_1976}.\n\nWe need some definitions. The following definitions are about a partition of a cake $C$ to $n$ pairwise-disjoint measurable pieces: $C = C_1\\cup\\cdots\\cup C_n$:\n\n\\begin{defn}\n(a) The \\emph{utilitarian social welfare} of a partition is the sum of agents' values: $U = \\sum_{i=1}^n{V_i(C_i)}$.\n(b) A partition is called \\emph{utilitarian-optimal} if its utilitarian social welfare is maximal among all partitions.\n\\end{defn}\n\nA utilitarian-optimal partition is obviously PO, since every Pareto-improvement strictly increases the utilitarian-social-welfare.\n\nMoreover, the rule that selects a utilitarian-optimal partition is division-independent \\cite{Chambers_2005}. This means that a utilitarian-optimal partition of a cake can be calculated by combining utilitarian-optimal partitions of two sub-cakes. This implies that the utilitarian-optimal rule is also AM+PM:\n\n\\begin{lemma}\n\\label{lemma:utilitarian-optimal-is-am-pm}\nThe rule that selects a utilitarian-optimal partition is AM and PM.\n\\end{lemma}\n\\begin{proof}\nFor AM, suppose that a cake $C$ is enlarged by a piece $E$ such that the new cake is $C\\cup E$. By division independence, a utilitarian-optimal division of $C\\cup E$ can be composed of a utilitarian-optimal division of $C$ and a utilitarian-optimal division of $E$. This means that in the utilitarian-optimal division of $C\\cup E$, all agents are weakly better-off.\n\nFor PM, suppose that agent $n$ leaves and abandons his share $C_n$. Mark $E=C_n$ and $C=C\\setminus C_n$. Apply the argument in the previous paragraph to prove that all agents are weakly better-off.\n\\end{proof}\n\n\\begin{cor}\nAM+PM+PO are compatible.\n\\end{cor}\n\n\n\n\\subsection{A PROP+AM+PM+PO division rule}\nIn general, an exact division is proportional but not Pareto-optimal, and a utilitarian-optimal division is Pareto-optimal but not proportional. Hence, to satisfy both PROP and PO we must work harder. We need some definitions.\n\n\\begin{defn}\nLet $k$ be an integer such that $0\\leq k\\leq n$. Let $W=(W_1,\\cdots,W_k)$ a vector of $k$ weights.\n\n(a) A partition is called \\emph{$W$-exact} if the values of the first $k$ agents are exactly determined by the vector $W$, i.e: $\\forall i\\in 1,\\cdots,k: V_i(C_i)=W_i$.\n\n(b) A partition is called \\emph{$W$-optimal} if its utilitarian social welfare is maximal among all \\emph{$W$-exact} partitions.\n\\end{defn}\n\nSo when $k=0$, $W$ is an empty vector and the set of $W$-optimal partitions coincides with the set of utilitarian-optimal partitions. On the other extreme, when $k=n$ the set of $W$-optimal partitions coincides with the set of $W$-exact partitions.\n\nA necessary condition for the existence of $W$-exact partitions is that the sum of weights in $W$ is at most 1. This condition is also sufficient: whenever the agents' value measures are continuous and $\\sum_{i=1}^{k}{W_i}\\leq 1$, there exist $W$-exact partitions. This is an immediate corollary of Corollary 1.1 of \\cite{Dubins_1961}.\n\nWhenever the agents' value measures are continuous, there exists a utilitarian-optimal partition. This is proved in Theorem 2 of \\cite{Dubins_1961}. The following generalization of this theorem can be proved analogously:\n\n\\begin{lemma}\nLet $k$ be an integer such that $0\\leq k\\leq n$. Let $W=(W_1,\\cdots,W_k)$ a vector of $k$ weights. If there exist $W$-exact partitions, then there exists a $W$-optimal partition.\n\\end{lemma}\n\n\\begin{cor}\nLet $W_{n-1}$ be the following vector of length $n-1$: $(\\frac{1}{n},\\cdots,\\frac{1}{n})$. Then there exists a $W_{n-1}$-optimal partition.\n\\end{cor}\n\nA $W_{n-1}$-optimal partition is a partition in which the first $n-1$ agents receive exactly their fair share of $1/n$, while the $n$-th agent receives the largest value that can be given to him under this constraint.\n\nA $W_{n-1}$-optimal partition is Pareto-optimal in certain conditions which we now define. The following definition and fact are adapted from basic measure-theory:\n\n\\begin{defn}\n(a) A measure on an interval is called \\emph{strictly positive} if it assigns a positive value to any non-empty open sub-interval.\n\n(b) The \\emph{support} of a measure $V$, written $supp(V)$, is the set of all points $x$ for which every open neighborhood of $x$ has positive measure.\n\\end{defn}\n\n\\begin{fact}\nEvery measure $V$ is strictly positive on $supp(V)$.\n\\end{fact}\n\nIn the context of cake-cutting, the support of $V_i$ is the subset of the cake from which agent $i$ derives a positive value.\n\n\\begin{lemma}\n\\label{lemma:W-optimal-is-PO}\nIf the value measure of agent $n$ is strictly positive, then any $W_{n-1}$-optimal partition is Pareto-optimal.\n\\end{lemma}\n\\begin{proof}\nLet $P$ be a $W_{n-1}$-optimal partition. Suppose by contradiction that there exists another partition $Q$ which Pareto-dominates $P$. There are two cases:\n\n(a) The values of all the first $n-1$ agents in $Q$ are the same as in $P$, while the value of agent $n$ is strictly larger in $Q$. But this contradicts our assumption that $P$ is $W_{n-1}$-optimal.\n\n(b) There is one or more agents $i$, where $i<n$, whose value in $Q$ is strictly larger than in $P$. In this case, we can cut a small piece of agent $i$'s share in $Q$, such that the value of agent $i$ reduces to exactly $1/n$. Then we can give the removed piece to agent $n$. Because agent $n$'s value measure is strictly positive, this transfer strictly increases the value of agent $n$. We can do the same to all other agents $i$ where $i<n$. The result is a $W_{n-1}$-exact partition in which agent $n$'s value is strictly more than in the partition $P$. But this again contradicts our assumption that $P$ is $W_{n-1}$-optimal.\n\\end{proof}\n\n\\begin{lemma}\nIf the value measure of agent $n$ is strictly positive, then the rule that selects a $W_{n-1}$-optimal partition is AM and PM.\n\\end{lemma}\n\\begin{proof}\nBecause agents $1,\\cdots,n-1$ receive a value of exactly $1/n$, it is clear that they are weakly better-off when the cake is enlarged or when an agent leaves. It remains to prove that this is also true for agent $n$.\n\nLet $P_C$ be a $W_{n-1}$-optimal partition of the original cake $C$.\n\nFor AM, suppose that a cake $C$ is enlarged by a piece $E$ such that the new cake is $C\\cup E$. Suppose the enlargement $E$ is divided in an $W_{n-1}$-exact way; call this partition $P_E$. Then, the partition composed of $P_C$ and $P_E$ is also a $W_{n-1}$-exact division of $C\\cup E$. In this partition, agent $n$ receives the same piece as in $P_C$, so he is weakly better off. By definition, in any $W_{n-1}$-optimal partition the value of agent $n$ is weakly better-off.\n\nFor PM, suppose that an agent $i\\in 1,\\cdots,n-1$ leaves and abandons his piece $C_i$. Mark $E=C_i$ and $C=C\\setminus C_i$. Apply the argument in the previous paragraph to prove that agent $n$ is weakly better-off.\n\\end{proof}\n\nWe are now ready to describe our AM+PM+PROP+PO division rule.\n\nFor every subset $K$ of the agents (a subset of $\\{1,\\cdots,n\\}$), define:\n\n$$ C_K := \\cap_{i\\in K}{supp(V_i)} \\setminus \\cup_{i\\notin K}{supp(V_i)} $$\n\n$C_K$ is the subset of $C$ which is valuable only for the agents in $K$.\nThus the cake $C$ is partitioned to $2^n$ pairwise-interior-disjoint sub-cakes, one sub-cake for each subset of the agents.\n\nWe define the \\emph{exact-optimal division rule} as follows:\n\nFor every subset $K$ of agents, let $k=|K|$:\n\\begin{itemize}\n\\item{If $k=0$ ($K=\\emptyset$), then discard the sub-cake $C_K$.}\n\\item{If $k=1$, then give $C_K$ to the single agent in $k$.}\n\\item{Otherwise, divide $C_K$ according to a $W_{k-1}$-optimal partition. I.e, give every agent in $K$ a value of $1/k$ of its valuation of $C_K$, except the agent with the largest index in $K$, which receives the largest possible value subject to this constraint.}\n\\end{itemize}\n\n\\begin{thm}\nThe exact-optimal division rule presented above is PROP+PO+AM+PM\n\\end{thm}\n\\begin{proof}\nPROP is obvious, since every agent receives a proportional share from every sub-cake whose value for it is positive.\n\nPO is also obvious, since by Lemma \\ref{lemma:W-optimal-is-PO}, every division of $C_K$ is Pareto-optimal relative to that cake and the agents in $K$. Because all agents not in $K$ value $C_K$ as 0, this means that the entire division is PO.\n\nFor AM, suppose that a cake $C$ is enlarged by an enlargement $E$. Then for every subsets $K$ of the agents, the sub-cake $C_K$ is enlarged by the corresponding subset $E_K$ (which may be empty). By an argument analogous to the proof of Lemma \\ref{lemma:utilitarian-optimal-is-am-pm}, in the new division of $C_K\\cup E_K$, all agents of $K$ are weakly better-off. This implies that in the new division of $C$, all agents are weakly better-off.\n\nFor PM, suppose that agent $i$ leaves and abandons its share $C_i$. This has an effect only on the divisions of the sub-cakes $C_K$ where $i\\in K$. In each of these sub-cakes, all agents are weakly better-off by an argument analogous to the proof of Lemma \\ref{lemma:utilitarian-optimal-is-am-pm}.\n\\end{proof}\n\n\\begin{cor}\nPROP+AM+PM+PO are compatible.\n\\end{cor}\n\n\\textcolor{red}{NOTE: I have a feeling that the \\emph{optimal proportional} rule - the rule that selects the proportional allocation with the largest utilitarian welfare - is AM+PM. Of course it is also PROP+PO. If my feeling is correct than we can remove most of this section. But currently the proof eludes me.}\n\n\n\n\n\n\n\n\n\\section{Future Work}\nIn this paper we studied monotonicity properties in combination with the basic fairness axiom of proportionality. An interesting future research topic is to study the same axioms in combination with the stronger fairness axion of envy-freeness.\n\n\n\n\\fi\n\n\\bibliography{CCM}\n\n\\end{document}\n\n", "meta": {"hexsha": "6e4b368c39e39c78b5557fd62813aee51f923687", "size": 26380, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Cake_Cutting_Monotonicity.tex", "max_stars_repo_name": "bsziklai/CakeCutting", "max_stars_repo_head_hexsha": "3857130ec85a04d85883eb1588df8f51c8c94c05", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Cake_Cutting_Monotonicity.tex", "max_issues_repo_name": "bsziklai/CakeCutting", "max_issues_repo_head_hexsha": "3857130ec85a04d85883eb1588df8f51c8c94c05", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cake_Cutting_Monotonicity.tex", "max_forks_repo_name": "bsziklai/CakeCutting", "max_forks_repo_head_hexsha": "3857130ec85a04d85883eb1588df8f51c8c94c05", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 63.1100478469, "max_line_length": 1035, "alphanum_fraction": 0.7601592115, "num_tokens": 6972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.3374118004864944}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\marginpar{Tuesday\\\\ 2021-6-15, \\\\ compiled \\\\ \\today}\n\nWe continue discussing the initial data problem. \n\n\\subsection{Conformal Thin Sandwich}\n\nWe can give a different decomposition of \\(\\widetilde{A}_{ij}\\): \n%\n\\begin{align}\n\\mathscr{L}_m \\widetilde{\\gamma}_{ij} &= \\partial_{t} \\widetilde{\\gamma}_{ij} - \\mathscr{L}_\\beta \\widetilde{\\gamma}_{ij} = \\partial_{t} \\widetilde{\\gamma}_{ij} + \\qty( \\widetilde{L} \\beta )^{ij} + \\frac{2}{3} \\widetilde{D}_{k} \\beta^{k} \\widetilde{\\gamma}_{ij}  \\\\\n&= 2 \\alpha \\hat{A}_{ij} + \\frac{2}{3} \\widetilde{D}_{k} \\beta^{k} \\hat{\\gamma}_{ij}\n\\,.\n\\end{align}\n\nThe idea is to combine these two equations in order to express \\(\\hat{A}_{ij}\\) as follows: \n%\n\\begin{align}\n\\hat{A}_{ij} = (2\\alpha )^{-1} \\qty[ \\widetilde{\\dot{\\gamma}}_{ij} + \\qty(\\widetilde{L} \\beta )_{ij}]\n\\,,\n\\end{align}\n%\nand similarly for \\(\\overline{A}_{ij}\\) if we wanted to use the conformal rescaling.\n\nThis equation replaces the \\(L + TT\\) decomposition of \\(\\hat{A}_{ij}\\) in CTS. \nWe can plug this into the momentum constraint \\(C_i = 0\\), and we find \n%\n\\begin{align}\n\\widetilde{D}_{j} \\qty[ \\widetilde{a}^{-1} \\qty(\\widetilde{L} \\beta )^{ij}] + \\widetilde{D}_{j} \\qty[\\widetilde{\\alpha}^{-1} \\widetilde{\\dot{\\gamma}}^{ij}] \n- \\frac{4}{3} \\psi^{6} \\widetilde{D}^{i} K \n- 16 \\pi \\widetilde{P}^{i} = 0\n\\,.\n\\end{align}\n\nThis must be paired with the Lichnerowicz equation: \n%\n\\begin{align}\n\\widetilde{D}^{i} \\widetilde{D}_{i} \\psi + \\dots = 0\n\\,.\n\\end{align}\n\nThe free data will be \\(\\widetilde{\\gamma}_{ij}\\), \\(K\\), \\(\\widetilde{\\dot{\\gamma}}_{ij}\\), \\(E\\) and \\(P^{i}\\). \nThe constrained data can be \\(\\psi \\) and \\(\\beta^{i}\\). \n\nThe difference from before is that we have substituted this TT part with the time derivative of the conformal metric; in some sense specifying \\(\\widetilde{\\dot{\\gamma}}\\) can help in specifying free data, for example stationary data.\n\nThe term \\(\\widetilde{\\alpha} = \\psi^{-6} \\alpha \\) is a conformally rescaled lapse.\nThe maximal slicing condition \\(K=0\\) means that the CTS equations decouple.\nThe momentum constraint for \\(P^{i}\\) turns out to be \\emph{linear} in this case. \n\nYork and Pfeiffer in 2003 proposed a formalism called XCTS, extended CTS, where the idea is to specify an equation for the conformal lapse \\(\\widetilde{\\alpha}\\) in order not to have to specify it.\n\nLet us consider \n%\n\\begin{align}\n\\mathscr{L}_m K &= \\dot{K} - \\beta^{i} \\widetilde{D}_{i} K   \\\\\n&= - \\psi^{-4} \\qty(\\widetilde{D}_{i} \\widetilde{D}^{i} K + 2 \\widetilde{D}_{i} \\log \\psi \\widetilde{D}^{i} \\alpha ) \n+ \\alpha \\qty[ \\dots]\n\\,:\n\\end{align}\n%\nthe piece multiplied by \\(\\psi^{-4}\\) can be written as \n%\n\\begin{align}\n\\widetilde{D}_{i} \\widetilde{D}^{i} K + 2 \\widetilde{D}_{i} \\log \\psi \\widetilde{D}^{i} \\alpha =\n\\psi^{-1} \\qty[\\widetilde{D}_{i} \\widetilde{D}^{i} (\\alpha \\psi ) + \\alpha \\widetilde{D}^{i} \\widetilde{D}_{i} \\psi ]\n\\,,\n\\end{align}\n%\nbut using the Hamiltonian constraint \\(C_0 = 0\\) we can write this as \n%\n\\begin{align}\n\\widetilde{D}_{i} \\widetilde{D}^{i} \\qty(\\hat{a} \\psi^{7})\n- \\qty(\\hat{a} \\psi^{7}) \\qty[ \\frac{\\hat{K}}{8} \n+ \\frac{5}{12} K^2 \\psi^{4} + \\frac{7}{8} \\hat{A}_{ij} \\hat{A}^{ij} \n\\psi^{-8} + 2 \\pi \\qty( E + 25 \\psi^{8}) \\psi^{-4}]\n+ \\qty(\\dot{K} - \\beta^{i} \\widetilde{D}_{i} K ) \\psi^{5} = 0\n\\,.\n\\end{align}\n\nThe XCTS scheme uses this equation, the Lichnerowicz equation and the one previously dubbed equation 1. \n\nUnder \\(K = 0\\) these do not decouple; however there is a nice feature: free data includes \\(\\widetilde{\\gamma}_{ij} \\), \\(\\widetilde{\\dot{\\gamma}}\\), \\(K\\) and \\(\\dot{K}\\). Being able to specify these is very convenient. \n\nThere exist examples for which XCTS yields non-unique solutions. \nLet us give a simple example: the solution of these for conformally, asymptotically flat \\& zero-derivative vacuum initial data. \n\nThe equation reads \n%\n\\begin{align}\n\\triangle \\psi + \\frac{1}{8} \\hat{A}_{ij} \\hat{A}^{ij} \\psi^{-7} &= 0  \\\\\nD_j \\qty[\\widetilde{\\alpha }^{-1} (L \\beta )^{ij} ] &= 0 iln\n\\triangle \\qty(\\widetilde{a} \\psi^{7}) - \\frac{7}{8} \\hat{A}_{ij} \\hat{A}^{ij} \\widetilde{\\alpha} \\psi^{-7} &= 0\n\\,.\n\\end{align}\n\nAsymptotically flat means \\(\\psi = 1\\), \\(\\beta^{i} = 0\\), \\(\\alpha = 1\\) as \\(r \\to \\infty \\). \nThen, \\(\\beta^{i} = 0\\) is a solution we can take, together with \\(\\widetilde{\\dot{\\gamma}} = 0\\), which means \\(\\hat{A}^{ij} = 0\\). \n\nThe equations then read \n%\n\\begin{align}\n\\triangle \\psi &= 0  \\\\\n\\triangle (\\hat{\\alpha} \\psi^{7}) &= 0\n\\,. \n\\end{align}\n\nThe inner boundary condition as before is a punctured space: \\(\\Sigma_0 = \\mathbb{R}^3 \\setminus 0\\). \nThis yields \\(\\psi = 1 + M / 2r\\). \n\nThe solution of the second equation is in the same form: \\(\\phi = \\widetilde{\\alpha} \\psi^{7} = 1 + a / r\\) for some constant \\(a\\). \nNow, \\(\\alpha = \\psi^{6} \\widetilde{\\alpha} = \\phi \\psi^{-1}\\); therefore the lapse reads \n%\n\\begin{align}\n\\alpha = \\qty(1 + \\frac{a}{r}) \\qty(1 + \\frac{M}{2r})^{-1} \n= \\frac{r + a}{r + M/2}\n\\,.\n\\end{align}\n\nWhat is the constant \\(a\\), though? Remember that we are solving this equation on the punctured \\(\\mathbb{R}^3\\): \\(a\\) is fixed by the choice of the value of the lapse \\(\\alpha \\) at a certain radius, say \\(r \\to 0\\). \nThe simplest choice is \\(\\alpha_0 = +1\\): this yields \\(a = M/2\\), which also means that the lapse is identically equal to 1. \n\nTherefore, we have re-found Schwarzschild in isotropic coordinates and geodesic gauge, \n%\n\\begin{align}\ng = - \\dd{t^2} + \\psi^{4} \\qty(\\dd{r^2} + r^2 \\dd{\\Omega^2})\n\\,.\n\\end{align}\n\nWhat if we set \\(\\alpha_0 = -1\\)? We know that \\(\\alpha > 0\\), but let us explore this crazy condition anyways. \nThis yields \n%\n\\begin{align}\na = - \\frac{M}{2}\n\\,,\n\\end{align}\n%\nwhich implies \n%\n\\begin{align}\n\\alpha = \\qty(1 - \\frac{M}{r}) \\qty(1 + \\frac{M}{2r})\n\\,.\n\\end{align}\n\nThis is the lapse in isotropic coordinates. \n\nWe have a moment of time symmetry, but the time development of \\(\\Sigma_0 \\) are different! \nIf we take \\(\\alpha_0 = +1\\), \\(\\Sigma_0 \\) evolves in a nontrivial way! \nIf, instead, \\(\\alpha_0 = -1\\) then \\(\\Sigma_0 \\) does not evolve, and \\(\\partial_{t}\\) is a Killing vector. \n\nWhat do we do with this negative lapse? In some points the \\(\\vec{n}\\) vector will remain future-pointing, but we will be in a weird coordinate system such that the time starts to run backwards at small radii. \nWe have to learn to live with it.\n\nWhere is XCTS useful? \nImagine a binary system: here there is no \\(\\partial_{t}\\) timelike Killing vector, and despite the rotation there is no rotational Killing vector \\(\\partial_{\\varphi }\\). \n\nSuppose we are considering a circular orbit with frequency \\(\\Omega \\): \nwe can define \n%\n\\begin{align}\nn^a = \\qty(\\partial_{t})^{a} + \\Omega \\qty(\\partial_{\\varphi })^{a}\n\\,,\n\\end{align}\n%\nwhich is conserved! This is because the orbit looks like a helix in \\(t, r, \\varphi \\) space: the direction of \\(n\\) is always along this helix. \n\nThis is an idealized, approximate situation, in which there is no radiation.\n\nIn a comoving frame with \\(\\dot{\\gamma}_{ij} = 0 = \\dot{K}\\) we can use a CTT + Bowman-Yosk puncture method.\n\nThe other part of the discussion for today is about gauge conditions. \n\n\\subsection{Gauge condition}\n\nWe need to make a choice of the foliation and a choice of the spatial coordinates. \nWe want our choice to \n\\begin{enumerate}\n    \\item avoid singularities;\n    \\item enhance symmetries;\n    \\item minimize grid distortions.\n\\end{enumerate}\n\nSomething useful is to have our slicing be as close as possible to some Kerr coordinates. \nIf some Killing vector is present we want to stay close to it.\n\nLet us start with \\textbf{slicing} (\\(\\alpha \\)). \nWe have already discussed \\emph{geodesic slicing} in which \\(\\alpha = 1\\) and \\(\\beta^{i} = 0\\): the coordinates follow freely-falling observers. \n\nHere, \\(n^a = (\\partial_{t})^{a}\\), and \\(\\alpha^{a} = D_a \\log \\alpha \\). This also means that \\(t = \\tau \\). \n\nThis is certainly not singularity-avoiding: free-falling observers fall into the singularity. Also, it does not seek symmetries, and it distorts the grid a lot. \n\nIn this gauge, the ADM equation reads \n%\n\\begin{align}\n\\partial_{t} K &= K_{ij} K^{ij} + 4 \\pi (E - S)  \\\\\n\\partial_{t} \\log \\sqrt{ \\gamma } &= - K\n\\,.\n\\end{align}\n\nThe behaviour of this gauge can be seen from these equations if we think about gravitational collapse: \nwe can draw a \\(r\\) versus \\(t\\) diagram and see that matter eventually falls into the horizon. \n\n\\(E-S\\) gets large, \\(\\partial_{t} K\\) gets large, and \\(\\partial_{t} \\log \\sqrt{\\gamma }\\) gets small. The curvature increases, and the coordinate volume element decreases. These are all characteristics of the \\emph{bad gauges}. \n\nAnother gauge we have seen is \\textbf{maximal slicing}: \\(0 = K\\), and we already discussed its geometric meaning.\n\nIf we look at \\(0 = K = - \\nabla_a n^a\\), the picture we can draw suggests the motion of an incompressible fluid: the coordinate volume element cannot be squeezed. \n\nThe Maximal Slicing equation can be also written as \n%\n\\begin{align}\nD_i D^{i} \\alpha = - \\alpha \\qty[ 4 \\pi (E-S) + K_{ij} K^{ij} ] = 0\n\\,,\n\\end{align}\n%\nto be compared with the previous geodesic slicing ones.\nHere the acceleration of an Eulerian observer will be different from 0, and the lapse \\(\\alpha \\) will evolve in a certain way which counteracts the effect of this volume element compression, as well as counteracting the ``singularity seeking'' property of geodesic slicing. \n \n\\end{document}\n", "meta": {"hexsha": "8d9f26934576d809fe94a823b8f7723b07d8dfc3", "size": 9455, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "phd_courses/numerical_relativity/jun15.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "phd_courses/numerical_relativity/jun15.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phd_courses/numerical_relativity/jun15.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 42.399103139, "max_line_length": 275, "alphanum_fraction": 0.6655737705, "num_tokens": 3163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6001883592602049, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.33741179168129026}}
{"text": "\\documentclass[12pt]{article}\n\n\\usepackage[tracking]{microtype}\n\n\\usepackage[sc]{mathpazo}\n% \\usepackage[euler-digits,small]{eulervm}\n\\usepackage[small]{eulervm}\n\n\\usepackage{amsmath,amsfonts,amssymb}\n\\usepackage{stmaryrd} % for semantic brackets [[ ]]\n\n\\usepackage{algorithm}\n\\usepackage[noend]{algpseudocode}\n\\usepackage{calc}\n\n\\usepackage{varwidth}\n\n% Modify this to change the format of function names in algoritms\n\\renewcommand{\\textproc}{\\textsl}\n\n% Define let command in algorithm\n\\newcommand{\\Let}{\\textbf{let} }\n\\newcommand{\\In}{\\textbf{in}}\n\\newcommand{\\Raise}{\\textbf{raise} }\n\n\\algblock{LetBlock}{EndLet}\n% customising the new block\n\\algnewcommand\\algorithmicletblock{\\textbf{let}}\n\\algnewcommand\\algorithmicendlet{\\textbf{in}}\n\\algrenewtext{LetBlock}[1]{\\algorithmicletblock\\ #1\\ =}\n\\algrenewtext{EndLet}{\\algorithmicendlet}\n\n% Widest label is \"Invariant:\"\n\\newcommand{\\algorithmicwidestlabel}{\\widthof{\\textbf{Invariant:}}}\n\n% Make ensures and requires of equal width\n\\algrenewcommand\\algorithmicensure{%\n  \\makebox[\\algorithmicwidestlabel][l]{\\textbf{Ensure:}}}\n\\algrenewcommand\\algorithmicrequire{%\n  \\makebox[\\algorithmicwidestlabel][l]{\\textbf{Require:}}}\n\n% Invariants in pseudocode\n\\algnewcommand\\algorithmicinvar{%\n  \\makebox[\\algorithmicwidestlabel][l]{\\textbf{Invariant:}}}\n\\algnewcommand\\Invar{\\item[\\algorithmicinvar]}%\n\n% Assertions in pseudocode\n\\algnewcommand\\algorithmicassert{%\n  \\makebox[\\algorithmicwidestlabel][l]{\\textbf{Assert:}}}\n\\algnewcommand\\Assert{\\item[\\algorithmicassert]}%\n\n\\renewcommand{\\vec}[1]{\\mathbf{#1}}            % bold vector\n\n\\newcommand{\\lo}{\\mathcal{L}}                  % a logic\n\\newcommand{\\lent}{\\,\\models_\\lo\\,}            % entailment in a logic \n\\newcommand{\\ext}[1]{\\llbracket #1 \\rrbracket} % model of a formula\n\n\\newcommand{\\sspace}{\\ensuremath{\\mathcal{S}}}\n\n\\newcommand{\\init}{\\ensuremath{I}}\n\\newcommand{\\trans}{\\ensuremath{T}}\n\\newcommand{\\transt}{\\ensuremath{\\mathcal{T}}}\n\n\\newcommand{\\reachablek}[1]{\\ensuremath{\\mathcal{R}_{#1}}}\n\\newcommand{\\reachable}{\\ensuremath{\\mathcal{R}_\\infty}}\n\n\n\n\\newcommand{\\pvalid}{\\ensuremath{\\mathcal{P}_\\mathrm{valid}}}\n\\newcommand{\\pinvalid}{\\ensuremath{\\mathcal{P}_\\mathrm{invalid}}}\n\n\\begin{document}\n\n\\title{Multi-Property $k$-induction in Kind 2}\n\n\\author{Christoph Sticksel}\n\\maketitle\n\n\\section{Preliminaries}\n\\label{sec:prelim}\n\n\nLet~${(I[\\vec x], T[\\vec x, \\vec x'])}$ be the encoding of a transition system with the initial state constraint~$I$ and the transition relation~$T$. Let~${\\mathcal{P} = \\{ P_1[\\vec x], \\dotsc, P_n[\\vec x] \\}}$ be a set of~$n$ properties to be checked for invariance. The variables~$I[\\vec x]$,~$T[\\vec x, \\vec x']$ and~$\\mathcal{P}[\\vec x]$ are static and always in scope.\n\n\\[ \\mathcal{P}[\\vec x] = \\bigwedge_{P\\in\\mathcal{P}} P[\\vec x] \\]\n\n\\[ \\mathcal{P}[\\vec x_s,\\dotsc,\\vec x_t] = \\bigwedge_{i=s}^t P[\\vec x_i] \\]\n\n\\[ \\mathcal{T}[\\vec x_s,\\dotsc,\\vec x_t] = \\bigwedge_{i=s}^{t-1}  T[\\vec x_i,\\vec x_{i+1}]  \\]\n\n\\[ \\reachablek{0} = \\{ \\vec x_k \\in \\sspace \\mid \\init[\\vec x_k] \\} \\]\n\n\\[ \\reachablek{k} = \\{ \\vec x_k \\in \\sspace \\mid \\exists \\vec x_0,\\dotsc,\\vec x_{k-1} \\in \\sspace \\colon \\init[\\vec x_0] \\land \\transt[\\vec x_0,\\dotsc,\\vec x_k] \\} \\]\n\n\\[ \\reachable = \\bigcup_{k \\geq 0} \\reachablek{k} \\]\n\n\n% \\[ \\mathcal{T}(\\mathcal{P})[\\vec x_s,\\dotsc,\\vec x_t] = \\left( \\bigwedge_{i=s}^{t-1} \\mathcal{P}[\\vec x_i] \\land T[\\vec x_i,\\vec x_{i+1}] \\right) \\land \\mathcal{P}[\\vec x_t] \\]\n\n% The relation~$\\mathcal{T}$ is to be extended with path compression etc.\n\n% \\section{Implementation}\n% \\label{sec:impl}\n\n% The transition system~${(I[\\vec x], T[\\vec x, \\vec x'])}$ is static and always in scope.\n\n% A global state consisting of the following variables that are shared by all procedures is maintained, it is realized by message passing. Every function maintains its own consistent snapshot of the global state that only changes after an explicit call to a function~\\textproc{update} --- this corresponds to receiving incoming queued messages in a message passing model. Changes to the global state are denoted by the~$:=$ operator, which corresponds to sending a message. Implicitly, the~$:=$ operator ensures to modify only an up to date view and correctly serializes concurrent writes to the global state.\n\n% \\begin{description}\n% \\item[$\\mathcal{P}_\\mathrm{invalid}$] A subset of~$\\mathcal{P}$ such that for each~$P\\in\\mathcal{P}_\\mathrm{invalid}$ there is a counterexample trace~$\\vec x_0,\\dotsc,\\vec x_k$ where \n%   \\[ I[\\vec x_0] \\land \\mathcal{T}[\\vec x_0,\\dotsc,\\vec x_{k}] \\land \\lnot P[\\vec x_{k}]. \\]\n% \\item[$\\mathcal{P}_\\mathrm{valid}$] A subset of~$\\mathcal{P}$ such that each~$P\\in\\mathcal{P}_\\mathrm{valid}$ is invariant:\n%   \\[ I[\\vec x] \\lent P[\\vec x], \\]\n%   \\[ P[\\vec x] \\land T[\\vec x,\\vec x'] \\lent P[\\vec x']. \\]\n% \\item[$k_\\textproc{bmc}$] For all~${k \\leq k_\\textproc{bmc}}$ there is no counterexample of length~$k$ to any property${P \\in \\mathcal{P} \\setminus \\mathcal{P}_\\mathrm{invalid}}$: \\[ I[\\vec x_0] \\land \\mathcal{T}[\\vec x_0,\\dotsc,\\vec x_{k}] \\lent P[\\vec x_{k}]. \\]\n% \\end{description}\n\n\n\\begin{figure}[tp]\n  \\centering\n  \\begin{algorithmic}\n    \\Require $\\forall P \\in \\pvalid \\ \\forall \\vec x \\in \\reachable \\colon P[\\vec x]$\n    \\Require $\\forall P \\in \\pinvalid \\ \\exists \\vec x_0,\\dotsc,\\vec x_k \\in \\sspace \\colon \\init[\\vec x_0] \\land \\transt[\\vec x_0,\\dotsc,\\vec x_k] \\land \\lnot P[\\vec x_k]$\n    \\Function{send$_\\mathcal{P}$}{$\\pvalid$, $\\pinvalid$}\n    \\State \\Return \n    \\EndFunction\n\n    \\bigskip\n\n    \\Ensure $\\forall P \\in \\pvalid \\ \\forall \\vec x \\in \\reachable \\colon P[\\vec x]$\n    \\Ensure $\\forall P \\in \\pinvalid \\ \\exists \\vec x_0,\\dotsc,\\vec x_k \\in \\sspace \\colon \\init[\\vec x_0] \\land \\transt[\\vec x_0,\\dotsc,\\vec x_k] \\land \\lnot P[\\vec x_k]$\n    \\Function{receive$_\\mathcal{P}$}{\\null}\n    \\State \\Return $\\langle \\pvalid, \\; \\pinvalid \\rangle$\n    \\EndFunction\n\n    \\bigskip\n    \\Require $\\forall P \\in \\mathcal{P} \\setminus \\pinvalid \\; \\forall \\vec x_0,\\dotsc,\\vec x_k \\in \\sspace \\colon \\init[\\vec x_0] \\land \\transt[\\vec x_0,\\dotsc,\\vec x_k] \\models P[\\vec x_k]$\n    \\Require $\\forall P \\in \\pinvalid \\; \\exists i \\leq k \\; \\exists \\vec x_0,\\dotsc,\\vec x_i \\in \\sspace \\colon \\init[\\vec x_0] \\land \\transt[\\vec x_0,\\dotsc,\\vec x_i] \\models P[\\vec x_i]$\n\n    \\Function{send$_{k_\\textproc{bmc}}$}{$k$, $\\pinvalid$}\n    \\State \\Return\n    \\EndFunction\n    \n    \\bigskip\n\n    \\Ensure $\\forall P \\in \\mathcal{P} \\setminus \\pinvalid \\; \\forall \\vec x_0,\\dotsc,\\vec x_k \\in \\sspace \\colon \\init[\\vec x_0] \\land \\transt[\\vec x_0,\\dotsc,\\vec x_k] \\models P[\\vec x_k]$\n    \\Ensure $\\forall P \\in \\pinvalid \\; \\exists i \\leq k \\; \\exists \\vec x_0,\\dotsc,\\vec x_i \\in \\sspace \\colon \\init[\\vec x_0] \\land \\transt[\\vec x_0,\\dotsc,\\vec x_i] \\models P[\\vec x_i]$\n    \\Function{receive$_{k_\\textproc{bmc}}$}{\\null}\n    \\State \\Return $\\langle k, \\; \\pinvalid \\rangle$\n    \\EndFunction\n\n  \\end{algorithmic}\n  \\caption{Interface and Guarantees of Message Passing Architecture}\n  \\label{fig:message-passing}\n\\end{figure}\n\n% \\section{Bounded Model Checking (BMC)}\n% \\label{sec:bmc}\n\n\\begin{figure}[tp]\n  \\label{fig:bmc}\n  \\centering\n  \\begin{algorithmic}[1]\n    \\Function{bmc}{$k$, $\\mathcal{P}_\\mathrm{in}$, $\\pinvalid$} \n\n    % Update global state\n    \\State \\Let $\\langle \\mathcal{P}_\\mathrm{valid},\\; \\mathcal{P}_\\mathrm{invalid}\\rangle$ = \\Call{receive$_\\mathcal{P}$}{\\null} \\In\n    \n    % Reduce to unknown properties \n    \\State \\Let $\\mathcal{P} = \\mathcal{P}_\\mathrm{in} \\setminus \\mathcal{P}_\\mathrm{valid} \\setminus \\mathcal{P}_\\mathrm{invalid}$ \\In \n\n    % Premise of entailment check\n    \\State \\Let $\\Phi = I[\\vec x_0] \\land \\mathcal{T}[\\vec x_0,\\dotsc,\\vec x_{k}] \\land \\mathcal{P}_\\mathrm{valid}[\\vec x_0,\\dotsc,\\vec x_k]$ \\In \n\n    % Conclusion of entailment check\n    \\State \\Let $\\Psi =  \\mathcal{P}[\\vec x_{k}]$ \\In\n\n    % Entailment check \n    \\If {$\\Phi \\lent \\Psi$} \n\n      % Found no invalid properties\n      \\State \\Call{send$_{k_\\textproc{bmc}}$}{$k$, $\\pinvalid$}\n      \\label{alg:bmc-send-k}\n\n      % Recurse to find longer counterexamples\n      \\State \\Call{bmc}{$k+1$, $\\mathcal{P}$, $\\pinvalid$}\n\n    \\Else \n\n      % Counterexample to entailment\n      \\State \\Let $\\mathcal{M} \\in \\ext{\\Phi \\land \\lnot \\Psi}$ \\In\n    \n      % Properties that can still be valid\n      \\State \\Let $\\mathcal{P}' = \\{P \\in \\mathcal{P} \\mid \\mathcal{M} \\lent P[\\vec x_{k}] \\}$ \\In\n\n      % Properties that are invalid\n      \\State \\Let $\\pinvalid' = \\mathcal{P} \\setminus \\mathcal{P}'$ \\In\n\n      % Send invalid properties \n      \\State \\Call{send$_\\mathcal{P}$}{$\\emptyset$, $\\pinvalid'$}\n      \\label{alg:bmc-send-pinvalid}\n\n      % Unknown properties left?\n      \\If {$\\mathcal{P}' \\not = \\emptyset$} \n\n        % Recurse to find counterexamples for potentially valid\n        % properties\n        \\State \\Call{bmc}{$k$, $\\mathcal{P}'$, $\\pinvalid \\cup \\pinvalid'$} \n\n      \\Else\n      \n        % Terminate \n        \\State \\Return\n\n      \\EndIf\n    \\EndIf\n    \\EndFunction\n  \\end{algorithmic}\n  \\caption{BMC Algorithm}\n\\end{figure}\n\n% Soundness: show that preconditions of~\\textproc{send$_x$} in Lines~\\ref{alg:bmc-send-k} and~\\ref{alg:bmc-send-pinvalid} are satisfied. \n\n% Termination: \n\n\n%  to add all properties~$P\\in\\mathcal{P}$ that are not invariant to~$\\mathcal{P}_\\mathrm{invalid}$ and preserves the invariants about the global state. It is not guaranteed to terminate unless all invariant properties are eventually added to~$\\mathcal{P}_\\mathrm{valid}$.\n\n\n\n%  $I[\\vec x_0] \\land \\mathcal{T}[\\vec x_0,\\dotsc,\\vec x_{k}] \\land \\mathcal{P}_\\mathrm{valid}[\\vec x_0,\\dotsc,\\vec x_k] \\lent \\mathcal{P}[\\vec x_{k}]$\n\n\n\n\n\n\n% Called as~\\textproc{bmc}($0$, $\\mathcal{P}$), it guarantees to add all properties~$P\\in\\mathcal{P}$ that are not invariant to~$\\mathcal{P}_\\mathrm{invalid}$ and preserves the invariants about the global state. It is not guaranteed to terminate unless all invariant properties are eventually added to~$\\mathcal{P}_\\mathrm{valid}$.\n\n% Since a property in~$\\mathcal{P}_\\mathrm{valid}$ is invariant, the entailment check in Line~\\ref{alg:bmc-check} is equivalent to checking the stronger~${I[\\vec x_0] \\land \\mathcal{T}[\\vec x_0,\\dotsc,\\vec x_{k}] \\lent \\mathcal{P}[\\vec x_{k}]}$ thus will find all counterexamples of length~$k$.\n\n% \\section{$k$-induction}\n% \\label{sec:k-induction}\n\n\\begin{figure}[tp]\n  \\label{fig:k-induction-update}\n  \\centering\n    \n  \\begin{algorithmic}[1]\n    \\Function{update$_{\\mathcal{P},\\mathcal{D}}$}{$\\mathcal{P}_\\mathrm{in}$, $\\mathcal{D}$, $\\pvalid$}\n    \n    % New valid and invalid properties \n    \\State \\Let $\\langle \\pvalid',\\; \\pinvalid' \\rangle$ = \\Call{receive$_\\mathcal{P}$}{\\null} \\In\n    \n    % New k in BMC\n    \\State \\Let $\\langle k^\\textproc{bmc}, \\pinvalid^\\textproc{bmc} \\rangle$ = \\Call{receive$_\\textproc{bmc}$}{\\null} \\In\n    \n    \\State \\Let $\\pvalid'' = \\pvalid \\cup \\pvalid'$ \\In\n    \\State \\Let $\\pinvalid'' = \\pinvalid' \\cup \\pinvalid^\\textproc{bmc}$ \\In\n\n    % New valid and invalid properties do not need to be proved\n    \\State \\Let $\\mathcal{P}_\\mathrm{out}$ = $\\mathcal{P}_\\mathrm{in} \\setminus \\pvalid'' \\setminus \\pinvalid''$ \\In\n\n    % Any tentatively valid property disproved?\n    \\If {$\\exists (l, D) \\in \\mathcal{D} \\colon D \\in \\pinvalid''$}\n    \n      % Prove all dependent properties again\n      \\State \\Return $\\langle \\mathcal{P}_\\mathrm{out} \\cup \\{ D \\mid (l,D) \\in \\mathcal{D} \\}  \\setminus \\pinvalid'',\\; \\emptyset,\\; k_\\textproc{bmc}, \\pvalid'' \\rangle$\n      \n    % All tentatively valid properties proved?\n    \\ElsIf {$\\forall (l, D) \\in \\mathcal{D} \\colon D \\in \\pvalid \\lor k_\\textproc{bmc} \\geq l$}\n\n      % Commit all properties as valid \n      \\State \\Call{send$_\\mathcal{P}$}{$\\{ D \\mid (l, D) \\in \\mathcal{D} \\}$, $\\emptyset$}\n\n      % Continue with properties to prove and no tentatively valid\n      % properties\n      \\State \\Return $\\langle \\mathcal{P}_\\mathrm{out},\\; \\emptyset,\\; k_\\textproc{bmc},\\; \\pvalid'' \\rangle$\n      \n    \\Else\n      \n      % Continue with properties to prove and tentatively valid properties\n      \\State \\Return $\\langle \\mathcal{P}_\\mathrm{out},\\; \\mathcal{D},\\; k_\\textproc{bmc},\\; \\pvalid'' \\rangle$\n\n    \\EndIf\n\n    \\EndFunction\n\n  \\end{algorithmic}\n  \\caption{Updating Dependencies in $k$-Induction}\n\\end{figure}\n\n\\begin{figure}[tp]\n  \\label{fig:k-induction}\n  \\centering\n    \n  \\begin{algorithmic}[1]\n    \\Function{ind}{$k$, $\\mathcal{P}_\\mathrm{in}$, $\\mathcal{Q}$, $\\mathcal{D}_\\mathrm{in}$, $\\pvalid$} \n\n    % Update properties to prove and tentative properties\n    \\State \\Let $\\langle \\mathcal{P}_\\mathrm{prove},\\; \\mathcal{D},\\; k_\\textproc{bmc},\\; \\pvalid' \\rangle$ = \\Call{update$_{\\mathcal{P},\\mathcal{D}}$}{$\\mathcal{P}_\\mathrm{in}$, $\\mathcal{D}_\\mathrm{in}$, $\\pvalid$} \\In\n\n    % Terminate when no more properties to prove\n    \\If {$\\mathcal{P}_\\mathrm{prove} = \\emptyset$} \\State \\Return \\EndIf\n\n    % Assume tentative properties\n    \\State \\Let $\\mathcal{P}_\\mathrm{assume}$ = $\\{ D \\mid (l, D) \\in \\mathcal{D} \\}$ \\In\n\n    % Premises that can be disproved later\n    \\State \\Let {$\\Phi_1 = \\mathcal{P}_\\mathrm{prove}[\\vec x_0,\\dotsc,\\vec x_k] \\land \\mathcal{P}_\\mathrm{assume}[\\vec x_0,\\dotsc,\\vec x_{k+1}]$} \\In\n\n    % Premises that cannot be disproved \n    \\State \\Let {$\\Phi_2 = \\pvalid'[\\vec x_0,\\dotsc,\\vec x_{k+1}] \\land \\mathcal{T}[\\vec x_0,\\dotsc,\\vec x_{k+1}] $} \\In\n\n    % Conclusion\n    \\State \\Let {$\\Psi = \\mathcal{P}_\\mathrm{prove}[\\vec x_{k+1}]$} \\In\n\n    % k-induction check \n    \\If {$\\Phi_1 \\land \\Phi_2 \\lent \\Psi$} \n\n      % Can there be counterexamples of length up to k? \n      \\If {$\\left(k_\\textproc{bmc} \\geq k\\right)$}\n\n        % Premises can safely be assumed, properties are certainly valid\n        \\State \\Call{send$_\\mathcal{P}$}{$\\mathcal{P}_\\mathrm{prove} \\cup \\mathcal{P}_\\mathrm{assume}$, $\\emptyset$}\n\n        % Properties to prove for next k? \n        \\If {$\\mathcal{Q} \\not = \\emptyset$} \n\n          % Increment k and prove remaining properties \n          \\State \\Call{ind}{$k+1$, $\\mathcal{Q}$, $\\emptyset$, $\\emptyset$, $\\pvalid'$}\n\n        \\Else\n        \n          % All properties proved\n          \\State \\Return \n\n        \\EndIf\n\n      % Premises can be disproved\n      \\Else\n        \n          % Each property must be in D only for one l\n          \\State \\Let $\\mathcal{D}'$ = $\\{ (k, P) \\mid P \\in \\mathcal{P}_\\mathrm{prove} \\}$ \\In\n        \n        % Still more properties to prove? \n        \\If {$\\mathcal{Q} \\not = \\emptyset$} \n        \n          % Continue trying to prove failed properties k+1-inductive, \n          % properties P are proved dependent on P and P_assume\n          \\State \\Call{ind}{$k+1$, $\\mathcal{Q}$, $\\emptyset$, $\\mathcal{D} \\cup \\mathcal{D}'$, $\\pvalid'$}\n\n        \\Else\n\n          % Wait for BMC to catch up \n          \\Repeat\n          \n            % New valid and invalid properties \n            \\LetBlock {$\\langle \\mathcal{P}_\\mathrm{prove},\\; \\mathcal{D},\\; k_\\textproc{bmc}, \\pvalid' \\rangle$} \n            \\State \\Call{update$_{\\mathcal{P},\\mathcal{D}}$}{$\\emptyset$, $\\mathcal{D} \\cup \\mathcal{D}'$, $\\pvalid'$}\n            \\EndLet\n            \n            \\If {$\\mathcal{P}_\\mathrm{prove} \\not = \\emptyset$} \n            \\State \\Call{ind}{$k$, $\\mathcal{P}_\\mathrm{prove}$, $\\emptyset$, $\\emptyset$, $\\pvalid'$}\n            \\EndIf\n\n          \\Until {$k_\\textproc{bmc} \\geq k \\lor \\mathcal{D} = \\emptyset$}\n\n          \\State \\Return\n\n        \\EndIf\n\n      \\EndIf\n\n      \\Else\n\n      % Get an inductive counterexample\n      \\State \\Let $\\mathcal{M} \\in \\ext{\\Phi_1 \\land \\Phi_2 \\land \\lnot \\Psi}$ \\In\n\n      % Properties that may be k-inductive for this k\n      \\State \\Let $\\mathcal{P}' = \\{P \\in \\mathcal{P}_\\mathrm{prove} \\mid \\mathcal{M} \\lent P[\\vec x_{k+1}] \\}$ \\In      \n\n      % Properties that are not k-inductive for this k\n      \\State \\Let $\\mathcal{Q}' = \\mathcal{Q} \\cup \\mathcal{P}_\\mathrm{prove} \\setminus \\mathcal{P}'$\n\n      % Try proving properties at the same k\n      \\State \\Call{ind}{$k$, $\\mathcal{P}'$, $\\mathcal{Q}'$, $\\mathcal{D}$, $\\pvalid'$}\n\n    \\EndIf\n    \\EndFunction\n  \\end{algorithmic}\n  \\caption{$k$-Induction Algorithm}\n\\end{figure}\n\n% The (tail-)recursive $k$\\nobreakdash-induction procedure~\\textproc{ind}($k$, $\\mathcal{P}$, $\\mathcal{Q}$, $\\mathcal{D}$) is initially called with the parameters~${k = 0}$,~${\\mathcal{Q} = \\emptyset}$, and~${\\mathcal{D} = \\emptyset}$. The set~$\\mathcal{P}$ contains all properties that are not~$l$\\nobreakdash-inductive for any $l < k$ and are true for at least~$k_\\textproc{bmc}$ steps from the initial state. Properties that are in addition not $k$\\nobreakdash-inductive are in~$\\mathcal{Q}$. The set~$\\mathcal{D}$ contains pairs~$(l,D)$ with~${l \\geq 0}$ and~$D$ being a set of properties that are~$l$\\nobreakdash-inductive if all properties in~$D$ hold for at least~$l$ steps from the initial state.\n\n% The function~\\textproc{ind} starts by partitioning~$\\mathcal{D}$ into three disjoint sets based on the global state:~the set~$\\mathcal{D}_\\mathrm{invalid}$ of pairs~$(l,D)$ where at least one property in~$D$ has a counterexample;~the set~$\\mathcal{D}_\\mathrm{valid}$ of pairs~$(l,D)$ where no property in~$D$ has an~$l$ step counterexample; and the remaining pairs~$(l,D)$ where none of the properties in~$D$ has a counterexample of length~$k_\\textproc{bmc} < l$. \n\n% All properties of~$D$ in any pair~$(l,D)$ of~$\\mathcal{D}_\\mathrm{valid}$ have no counterexample of length~$l$, and are~$l$\\nobreakdash-inductive, therefore  certainly valid and are added to the global state. \n\n% All properties of~$D$ of some pair~$(l,D)$ of~$\\mathcal{D}_\\mathrm{invalid}$ are either in~$\\mathcal{P}_\\mathrm{invalid}$ or~$l$\\nobreakdash-inductive, but under the now violated assumption that some property in~$\\mathcal{P}_\\mathrm{invalid}$ is valid. Those properties not in~$\\mathcal{P}_\\mathrm{invalid}$ are still candidates for invariance and are added back to the set of properties~$\\mathcal{P}$ to be proved.\n\n% All properties of~$D$ in some pair~$(l,D)$ of~$\\mathcal{D}$ are optimistically assumed to be invariant, and make up the set~$\\mathcal{P}_\\mathrm{assume}$. These properties are used to strengthen the~$k$\\nobreakdash-inductive check, but every property proved~$k$\\nobreakdash-inductive is only so relative to~$\\mathcal{P}_\\mathrm{assume}$ and its proof is invalid as soon as a counterexample to one property~$\\mathcal{P}_\\mathrm{assume}$ is found.\n\n% The~$k$\\nobreakdash-inductive check uses the premise~$\\Phi_1$, which is a conjunction of properties in~$\\mathcal{P}$ and~$\\mathcal{P}_\\mathrm{assume}$ that have not been proven invariant. Thus the check is conditional on the non-existence of a counterexample of length~$k$ for each of the properties in~$\\mathcal{P}$ and~$\\mathcal{P}_\\mathrm{assume}$.\n\n% The second half of the premises in the~$k$\\nobreakdash-inductive check contains properties that have been proven valid and the transition relation. Both are unconditionally true.\n\n% If the~$k$\\nobreakdash-inductive check succeeds, the properties~$\\mathcal{P}$ are invariant if there is no~$k$ step counterexample to any property in~$\\mathcal{P}$ or~$\\mathcal{P}_\\mathrm{assume}$. For this we check if in the global state~${k_\\textproc{bmc}\\geq k}$. Then, the global state is modified to include~$\\mathcal{P}$ and~$\\mathcal{P}_\\mathrm{assume}$ in~$\\mathcal{P}_\\mathrm{valid}$. The properties in~$\\mathcal{P}_\\mathrm{assume}$ were proved under the condition of the non-existence of a counterexample of some length~${l < k \\leq k_\\textproc{bmc}}$ and hence are now invariant, too. If the set of properties~$\\mathcal{Q}$ is not empty, the procedure continues to check those for~${k+1}$\\nobreakdash-in\\-duct\\-ive\\-ness, otherwise it exits.\n\n% If the~$k$\\nobreakdash-inductive check succeeds, but it is unknown if there are counterexamples of length~$k$, the properties in~$\\mathcal{P}$ are invariant if no counterexamples of length~$k$ exist for any of the properties in~$\\mathcal{P}$ and~$\\mathcal{P}_\\mathrm{assume}$. This condition is added to the set~$\\mathcal{D}$ and the procedure continues to check if the properties in~$\\mathcal{Q}$ are~${k+1}$\\nobreakdash-inductive, if~$\\mathcal{Q}$ is not empty. If~$\\mathcal{Q}$ is empty, the procedure monitors the global state for additions to~$\\mathcal{P}_\\mathrm{invalid}$ that are in~$D$ of some pair~${(l,D)\\in\\mathcal{D}}$. This triggers a reentry to the procedure with~${\\mathcal{P}=\\mathcal{Q}=\\emptyset}$, where the properties that were proved conditional on properties in~$\\mathcal{P}_\\mathrm{invalid}$ are checked for~$k$\\nobreakdash-inductiveness again. If the global state changes to~$k_\\textproc{bmc} \\geq k$, then the condition on~$k$\\nobreakdash-inductiveness of all properties of~$\\mathcal{P}$ and~$\\mathcal{P}_\\mathrm{assume}$ is satisfied. These properties are added to~$\\mathcal{P}_\\mathrm{valid}$ in the global state and the procedure terminates.\n\n% If the~$k$\\nobreakdash-inductive check fails, some properties of~$\\mathcal{P}$ are not~$k$\\nobreakdash-inductive. By examining the inductive counterexample, those properties that are false in the final state~$\\vec x_{k+1}$ are added to~$\\mathcal{Q}$ to be checked for~${k+1}$\\nobreakdash-inductiveness. The~$k$\\nobreakdash-inductive check is then tried again for those properties that are true in the final state~$\\vec x_{k+1}$.\n\n  \n\\end{document}\n\n\n%%% Local Variables: \n%%% TeX-command-default: \"LaTeX\"\n%%% TeX-parse-self: t\n%%% TeX-auto-save: t\n%%% TeX-PDF-mode: t\n%%% TeX-master: t\n%%% ispell-dictionary: \"american\"\n%%% flyspell-default-dictionary: \"american\"\n%%% End: ", "meta": {"hexsha": "4dfd81a69efb4035c582a4b5a1481cd699dcaca2", "size": 21516, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/multi-k-induction.tex", "max_stars_repo_name": "amarmaduke/kind2", "max_stars_repo_head_hexsha": "9d729088587e2d95b7732c77a6d8ee02c9fc2178", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 62, "max_stars_repo_stars_event_min_datetime": "2015-02-04T17:49:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T21:52:06.000Z", "max_issues_repo_path": "report/multi-k-induction.tex", "max_issues_repo_name": "amarmaduke/kind2", "max_issues_repo_head_hexsha": "9d729088587e2d95b7732c77a6d8ee02c9fc2178", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 110, "max_issues_repo_issues_event_min_datetime": "2015-01-20T14:26:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T02:25:49.000Z", "max_forks_repo_path": "report/multi-k-induction.tex", "max_forks_repo_name": "amarmaduke/kind2", "max_forks_repo_head_hexsha": "9d729088587e2d95b7732c77a6d8ee02c9fc2178", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25, "max_forks_repo_forks_event_min_datetime": "2017-02-20T21:13:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-20T19:46:09.000Z", "avg_line_length": 50.3887587822, "max_line_length": 1172, "alphanum_fraction": 0.6640639524, "num_tokens": 7175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.33741178364055446}}
{"text": "\\chapter{Gravity Inversion}\\label{Chp:cook:gravity inversion}\n\n\\section{Introduction}\n\nIn this part of the documentation we give an introduction on how to use the\n\\downunder module and the inversion driver functions to perform inversion\nof gravity and magnetic data.\nThe driver functions enable geologists and geophysicists to apply the\n\\downunder module quickly and easily without requiring detailed\nknowledge of either the theory behind inversion or programming skills.\nHowever, users who are interested in specializing or extending the inversion\ncapacity are referred to Part~\\ref{part2} of this manual.\nIt is beyond the intention of this manual to give a detailed introduction to\ngeophysical inversion, in particular to the appropriate preprocessing of data\nsets.\n\nThe \\downunder module described here is designed to calculate estimations for\nthe 3-D distribution of density and/or susceptibility from 2-D gravity and\nmagnetic data measured in ground or airborne surveys.\nThis process is generally called inversion of geophysical data.\nFollowing the standard assumption it is assumed that data are measured as\nperturbation of an expected gravity and/or magnetic field of the Earth.\nIn this context measured gravity and magnetic data describe\nanomalies in the gravity and magnetic field.\nAs a consequence, the inversion process provides corrections to an average\ndensity (typically $2670 kg/m^3$) and susceptibility (typically $0$).\nIn the following we always assume that the given data are anomalies and\njust use the terms gravity and density to describe  them.\n\nIn this chapter we give a detailed introduction for using the driver\nfunctions for inversion of gravity data.\nIn the following chapters~\\ref{Chp:cook:magnetic inversion} and~\\ref{Chp:cook:joint inversion}\nwe discuss the inversion of magnetic data, and the joint inversion of\ngravity and magnetic data using \\downunder.\nNote, that the principles introduced in this chapter apply to magnetic and\njoint inversion so the presentation for these problem classes is kept short\nand users interested in magnetic data only should still work through this\nchapter on gravity data. \n\nTo run the examples discussed you need to have \\escript (version 3.3.1 or\nnewer) installed on your computer.\nTo visualize the results you need to have access to a\ndata plotting software which is able to process \\VTK input files, e.g.\n\\mayavi or \\VisIt.\nAs \\mayavi can be easily obtained and installed for most platforms the\ntutorial includes commands to visualize output files using \\mayavi .\nHowever, it is pointed out that \\VisIt is the preferred visualization tool for\n\\escript as it can deal with very large data sets more efficiently.\n    \n\\begin{figure}\n\\centering\n\\includegraphics[width=0.7\\textwidth]{QLDWestGravityDataPlot.png}\n\\caption{Gravity Anomaly Data in $mgal$ from Western Queensland, Australia\n    (file \\examplefile{data/QLDWestGravity.nc}). Data obtained from Geoscience Australia.}\n%\\AZADEH{Tracey R, Bacchin M, \\& Wynne P. 2008. In preparation. AAGD07: A new absolute gravity datum for Australian gravity and new standards for the Australian National Gravity Database. Exploration Geophysics.}\n\\label{FIG:P1:GRAV:0}\n\\end{figure}\n\n\\begin{figure}\n\\centering%\n\\includegraphics[width=0.9\\textwidth]{QLDGravContourMu10.png}\n\\caption{3-D contour plot of the density distribution obtained by inversion of\n    file \\file{data/QLDWestGravity.nc} (with $\\mu=10$).\n    Colours represent values of density where high values are represented by\n    blue and low values are represented by red.}\n\\label{FIG:P1:GRAV:1}\n\\end{figure}\n\n\\section{How does it work?}\nInversion execution is controlled by a script that can be edited using any text editor.\nThe script contains a series of statements to be read and executed line by line by an\ninterpreter.  In the case of \\downunder this interpreter is \\Python.\nIn order to process each statement in the script certain rules (called syntax) need to be obeyed.\nThere are many online tutorials for \\Python available\\footnote{e.g.\n\\url{http://www.tutorialspoint.com/python} and \\url{http://doc.pyschools.com}}.\nFor a deeper understanding we also refer the reader to the \\escript cook book \\cite{ESCRIPTCOOKBOOK} and user's\nguide \\cite{ESCRIPT}.\nFor this part of the manual no \\Python knowledge is required but it is\nrecommended that users acquire some basic \\Python knowledge as they\nprogress in their work with \\downunder.\n\nThe following script~\\ref{code: gravity1}\\footnote{The script is similar to\n\\examplefile{grav_netcdf.py} within the \\escript example file directory.} is a\nsimple example to run an inversion for gravity data:\n\n\\begin{pyc}\\label{code: gravity1}\n\\\n\\begin{python}\n# Header:\nfrom esys.downunder import *\nfrom esys.weipa import *\nfrom esys.escript import unitsSI as U\n\n# Step 1: set up domain\ndom=DomainBuilder()\ndom.setVerticalExtents(depth=40.*U.km, air_layer=6.*U.km, num_cells=28)\ndom.setFractionalPadding(pad_x=0.2, pad_y=0.2)\ndom.fixDensityBelow(depth=40.*U.km)\n\n# Step 2: read gravity data\nsource0=NetCdfData(NetCdfData.GRAVITY, 'GravitySmall.nc')\ndom.addSource(source0)\n\n# Step 3: set up inversion\ninv=GravityInversion()\ninv.setSolverTolerance(1e-4)\ninv.setSolverMaxIterations(50)\ninv.setup(dom)\n\n# Step 4: run inversion \ninv.getCostFunction().setTradeOffFactorsModels(10.) \nrho = inv.run()\n\n# Step 5: write reconstructed density to file\nsaveVTK(\"result.vtu\", density=rho)\n\\end{python}\n\\end{pyc}\nThe result, in this case the density distribution, is written to an external\nfile for further processing. You can copy and paste the text of the script\ninto a file of any name, let's say for further reference we use the file\nname \\file{grav.py}.\nIt is recommended to use the extension \\file{.py} to identify the file as a\n\\Python script.\nWe will discuss the statements of the script later in this chapter. \n\nThe inversion needs to be fed with some gravity data. You can find\nexample data from western Queensland, Australia in two resolutions in the\n\\escript example directory. In this case data are loaded from the file\n\\examplefile{GravitySmall.nc} which is in \\netcdf file format.\nAfter you have copied this file into the directory in which you have saved the\nscript \\file{grav.py} you can run the program using the command line \n\\begin{verbatim}\nrun-escript grav.py\n\\end{verbatim}\nWe are running \\file{grav.py} through the \\escript start-up command since\n\\escript is used as a back end for the inversion algorithm\\footnote{Please see\nthe \\escript user's guide~\\cite{ESCRIPT} on how to run your script in parallel\nusing threading and/or MPI.}.  It is assumed that you have an installation of \\escript available on\nyour computer, see \\url{https://launchpad.net/escript-finley}.\n\nAfter the execution has successfully completed you will find the result file\n\\file{result.vtu} in the directory where you started the execution\nof the script.\nThe file has the \\VTK format and can be imported easily into many\nvisualization tools.\nOne option is the \\mayavi package which is available on most platforms.\nYou can invoke the visualization using the commands\n\\begin{verbatim}\nmayavi2 -d result.vtu -m SurfaceMap\n\\end{verbatim}\nfrom the command line.\nFigure~\\ref{FIG:P1:GRAV:1} shows the result of this inversion as a contour\nplot\\footnote{These plots were generated by \\VisIt using the higher resolution\ndata.}, while the gravity anomaly data is shown in Figure~\\ref{FIG:P1:GRAV:0}.\nWe will discuss data later in Section~\\ref{SEC:P1:GRAV:DATA}.\n\nLet us take a closer look at the script\\footnote{In \\Python lines starting\nwith `\\#` are comments and are not processed further.}. Besides the header\nsection one can separate the script into five steps:\n\\begin{enumerate}\n    \\item set up domain on which the inversion problem is solved\n    \\item load the data \n    \\item set-up the inversion problem\n    \\item run the inversion\n    \\item further processing of the result. Here we write the reconstructed\n          density distribution to a file.\n\\end{enumerate}\nIn the following we will discuss the steps of the scripts in more detail.\nBefore we do this it is pointed out that the header section, following\n\\Python conventions, makes all required packages available to access within\nthe script.\nAt this point we will not discuss this in more details but emphasize that the\nheader section is a vital part of the script.\nIt is is required in each \\downunder inversion script and should not be\naltered except if additional modules are needed.\n\n\\begin{figure}\n\\centering\n\\includegraphics[width=\\textwidth]{dom2D.pdf}\n\\caption{2-D domain set-up for gravity inversion}\n\\label{FIG:P1:GRAV:2}\n\\end{figure}\n\n\\section{Creating the Inversion Domain}\nThe first step in Script~\\ref{code: gravity1} is the definition of the domain over\nwhich the inversion is performed.\nWe think of the domain as a block with orthogonal, plain faces.\nFigure~\\ref{FIG:P1:GRAV:2} shows the set-up for a two-dimensional domain\n(see also Figure~\\ref{fig:domainBuilder} for 3-D).\nThe lateral coordinates along the surface of the Earth are denoted by $x$ and\n$y$ (only $x$-direction is used in 2-D).\nThe $z$ direction defines the vertical direction where the part above the\nsurface ($z=0$) has positive coordinates and the subsurface negative coordinates.\nThe height of the section above the surface, which is assumed to be filled\nwith air, needs to be set by the user.\nThe inversion assumes that the density in the section is known to be\nzero\\footnote{Always keeping in mind that these are not absolute values but\nanomalies.}.\nThe density below the surface is unknown and is calculated through inversion. The user needs to specify the depth below the surface in which the\ndensity is to be calculated.\nThe lateral extension of the domain is defined by the data sets fed into the\ninversion.\nIt is chosen large enough to cover all data sets (in case more than one is\nused). In order to reduce the impact of the boundary a padding zone around the\ndata sets can be introduced.\n\n\\begin{figure}\n\\centering\n\\includegraphics[width=\\textwidth]{dom2DFEM.pdf}\n\\caption{Cell distribution and boundary conditions for a 2-D domain}\n\\label{FIG:P1:GRAV:3}\n\\end{figure}\n\nThe reconstruction of the gravity field from an estimated density distribution\nis the key component of the inversion process.\nTo do this \\downunder uses the finite element method (FEM).\nWe need to introduce a grid over the domain, see Figure~\\ref{FIG:P1:GRAV:3}.\nThe number of vertical cells is set by the user while the number of horizontal\ncells is derived from the grid spacing of the gravity data set(s).\nIt is assumed that gravity field data given are constant across a cell.\nTo be able to reconstruct the gravity field some assumptions on the values of\nthe gravity field on the domain boundary have to be made.\n\\downunder assumes that on all faces the lateral gravity field component\nequals zero. No assumptions on the horizontal components are\nmade\\footnote{It is assumed that the gravity potential equals zero on the top\nand bottom surface, see Section~\\ref{sec:forward gravity} for details}%\n\\footnote{Most inversion codes use Green's functions over an unbounded domain\nto reconstruct the gravity field. This approach makes the assumption that the\ngravity field (or potential) converges to zero when moving away from the\nregion of interest. The boundary conditions used here are stronger in the\nsense that the lateral gravity component is enforced to be zero in a defined\ndistance of the region of interest but weaker in the sense that no constraint\non the horizontal component is applied.}.\n   \nIn script~\\ref{code: gravity1} the statement\n\\begin{verbatim}\ndom=DomainBuilder()\n\\end{verbatim}\ncreates something like a factory to build a domain.\nWe then define the features of the domain we would like to create:\n\\begin{verbatim}\ndom.setVerticalExtents(depth=40.*U.km, air_layer=6.*U.km, num_cells=28)\ndom.setFractionalPadding(pad_x=0.2, pad_y=0.2)\n\\end{verbatim}\nHere we specify the depth of the domain to $40 km$, the thickness of the air\nlayer above the surface to $6 km$ and the number of vertical cells to $28$.\nWe also introduce a lateral padding of $20 \\%$ of the expansion of the gravity\ndata on each side of the data and in both lateral directions.\n\nIn some cases it can be appropriate to assume that the density below a certain\ndepth is zero\\footnote{As we are in fact calculating density corrections this\nmeans that the density is assumed to be the average density.}.\nThe statement \n\\begin{verbatim}\ndom.fixDensityBelow(depth=40.*U.km)\n\\end{verbatim}\nintroduces this constraint.\nAs in the case discussed here if the depth for zero density is not less than\nthe depth of the domain no constraint at depth is applied to the density.\n\n\\downunder uses the metre-kilogram-second based International System of Units\n(SI)\\footnote{see \\url{http://en.wikipedia.org/wiki/International_System_of_Units}}\\index{SI}.\nSo all values must be converted to appropriate units.\nThis does not apply to geographic coordinates which in \\module{downunder} are given in\nfractional degrees (as a floating point number) to represent longitude and\nlatitude. In the script we have used the expression\n\\begin{verbatim}\ndepth=40.*U.km\n\\end{verbatim}\nto define the depth of the domain to $40 km$.\nThe expression \\verb|U.km| denotes the unit $km$ (kilometer) and ensures\nappropriate conversion of the value $40$ into the base unit $m$ (meter).\nIt is recommended that units are added to values (where present) in order to ensure\nthat the values used in  \\downunder are given with the appropriate\nunits.\nThe physical units module of \\escript, which we have imported here under the\nname \\verb|U| in the script header, defines a large number of physical units\nand constants, please see~\\cite{ESCRIPT} and~\\cite{ESCRIPTONLINE}. \n\n\\section{Loading Gravitational Data}\\label{SEC:P1:GRAV:DATA}\nIn practice gravity acceleration is measured in various ways, including\nairborne surveys~\\cite{Telford1990a} or surface surveys.\nThe\\\\ \\downunder library assumes that all data supplied as input are already appropriately\npre-processed. In particular, corrections for\n\\begin{itemize}\n \\item free-air, to remove effects from altitude above ground;\n \\item latitude, to remove effects from ellipsoidicity of the Earth;\n \\item terrain, to remove effects from topography\n\\end{itemize}\nmust have been applied to the data.  In general, data prepared in such a form are called Bouguer anomalies~\\cite{Telford1990a}.\n\nTo load gravity data into \\downunder the data are given on a plane parallel\nto the surface of the Earth at a constant altitude, see\ndiagram~\\ref{FIG:P1:GRAV:2}.\nThe data need to be defined over a rectangular grid covering a subregion of\nthe Earth surface.\nThe grid uses a geographic coordinate system with latitudes and longitudes\nassumed to be given in the Clarke 1866 geodetic system.\nFigure~\\ref{FIG:P1:GRAV:0} shows an example of such a data set from \nwestern Queensland, Australia.\nThe data set covers a rectangular region between $140^o$ and $141^o$ east\nand between $20^o$ and $21^o$ south.\nNotice that latitude varies between $-90^o$ to $90^o$ where negative signs\nrefer to places in the southern hemisphere and longitude varies between\n$-180^o$ to $180^o$ where negative signs refer to places west of Greenwich.\nThe colour at a location represents the value of the vertical Bouguer gravity\nanomaly at this point at the surface of the Earth.\nValues in this data set range from $-160 \\; mgal$ to about $500 \\; mgal$\\footnote{The unit\n$mgal$ means milli $gal$ (galileo) with $1 \\; gal = 0.01 \\frac{m}{sec^2}$.}\nover a $121 \\times 121$ grid.\n\nIn general, a patch of gravity data needs to be defined over a plane\n\\verb|NX| $\\times$ \\verb|NY| where \\verb|NX| and \\verb|NY| define the number\nof grid lines in the longitude (\\verb|X|) and the latitude (\\verb|Y|)\ndirection, respectively.\nThe grid is spanned from an origin with spacing \\verb|DELTA_X| and\n\\verb|DELTA_Y| in the longitude and the latitude direction, respectively.\nGravity data for all grid points need to be given as an \\verb|NX|\n$\\times$ \\verb|NY| array.\nIf available, measurement errors can be associated with gravity data.\nThe values are given as an \\verb|NX| $\\times$ \\verb|NY| array matching the\nshape of the gravity array.\nNote that data need not be available on every single point of the grid, see\nSection~\\ref{SEC:P1:GRAV:REMARK:DATAHOLES} for more information on this.\n\nCurrently, two data file formats are supported, namely \\emph{ER Mapper Raster}\n\\cite{ERMAPPER} files and \\netcdf~\\cite{NETCDF} files.\nThe examples from this chapter use \\netcdf files and we refer the reader to\nSection~\\ref{SEC:P1:GRAV:REMARK:ERMAPPER} and\nSection~\\ref{sec:ref:DataSource:ERM} for more information on using ER Mapper\nRaster files.\nIf you have data in any other format you have the option of writing a suitable\nreader (for advanced users, see Chapter~\\ref{Chp:ref:data sources}) or,\nassuming you are able to read the data in \\Python, refer to the example\nscript \\examplefile{create_netcdf.py} which shows how to create a file\nin the \\netcdf file format~\\cite{NETCDF} compatible with \\downunder from\na data array.\n\nIn script~\\ref{code: gravity1} we use the statement \n\\begin{verbatim}\nsource0=NetCdfData(NetCdfData.GRAVITY, 'GravitySmall.nc')\n\\end{verbatim}\nto load the gravity data stored in \\examplefile{GravitySmall.nc} in the\n\\netcdf format. \nWithin the script the data set is now available under the name \\verb|source0|.\nWe need to link the data set to the \\verb|DomainBuilder| using \n\\begin{verbatim}\ndom.addSource(source0)\n\\end{verbatim}\nTo build the domain for inversion, \\verb|DomainBuilder| uses the information about origin,\nextent, spacing and other options used to build an appropriate domain.\nA flat Earth is assumed and geographic coordinates used to\nrepresent data in the input file are mapped to a (local) Cartesian coordinate\nsystem. This is achieved by projecting the geographic coordinates into the\n\\emph{Universal Transverse Mercator} (UTM) coordinate system\\footnote{See e.g.\n\\url{http://en.wikipedia.org/wiki/Universal_Transverse_Mercator_coordinate_system}}.\n\nThere are a few optional arguments that can be added when constructing a data source.\nWhile Section~\\ref{sec:ref:DataSource} has a detailed description of all\narguments it is worth noting a few.\nFirstly, it is important to know that data slices are assumed to be at altitude\n$0$m by default. This can be easily changed though:\n\\begin{verbatim}\nsource0=NetCdfData(NetCdfData.GRAVITY, 'GravitySmall.nc', \n    altitude=2.5*U.km)\n\\end{verbatim}\nAnother important setting is the scale or unit of the measurements.\nThe default is dependent on the data type and for gravity anomalies a scale\nof $\\frac{\\mu m}{sec^2}$ (or $0.1 \\; mgal$) is assumed. For instance to \nchange the default scale to $mgal$ (which is $10^{-5} \\frac{m}{sec^2}$),\nyou could use:\n\\begin{verbatim}\nsource0=NetCdfData(NetCdfData.GRAVITY, 'GravitySmall.nc', \n    scale_factor=U.mgal)\n\\end{verbatim}\nFinally, it is possible to specify measurement errors (i.e. uncertainties)\nalongside the data.\nSince these can never be zero, a value of $2$ units is used if nothing else\nhas been specified.\nThe error value is assumed to be given in the same units as the data so the\ndefault value translates to an error of $0.2 \\; mgal$.\nThere are two possibilities to specify the error, namely by providing a\nconstant value which is applied to all data points:\n\\begin{verbatim}\nsource0=NetCdfData(NetCdfData.GRAVITY, 'GravitySmall.nc', error=1.7)\n\\end{verbatim}\nor, if the information is available in the same \\netcdf file under the name\n\\verb|errors|, provide \\downunder with the appropriate variable name:\n\\begin{verbatim}\nsource0=NetCdfData(NetCdfData.GRAVITY, 'GravitySmall.nc', error=\"errors\")\n\\end{verbatim}\n\n\nIt is important to keep an eye on the complexity of the inversion.\nA good measure is the total number of cells being used.\nAssume we have given a data set on a $20 \\times 20$ grid and we add lateral\npadding of, say, $20 \\%$ to each side of the data, the lateral number of cells\nbecomes $(20\\cdot 1.4)\\times (20\\cdot 1.4)=1.4^2\\cdot 20^2\\approx 2\\cdot 10^2=800$.\nIf we use $20$ cells in the vertical direction we end up with a total number\nof $800 \\times 20 = 16,000$ cells.\nThis size can be easily handled by a modern desktop PC.\nIf we increase the grid size of the data to $40 \\times 40$ points and use $40$\ncells in the vertical extent we get a total of $(2\\cdot 40^2)\\cdot 40=128,000$\ncells, a problem size which is considerably larger but can still be handled by\na desktop computer.\nTaking this one step further, if the amount of data is increased to\n$200\\times 200$ points and we use $200$ cells in the vertical extent the\ndomain will contain $16,000,000$ ($16$ million) cells.\nThis scenario requires a computer with enough memory and (a) fast processor(s)\nto run the inversion.\nThis estimate of complexity growth applies to the case where the increase\nof data grid size is driven by an increase of resolution where it is\nrecommended to increase the vertical resolution in synch with the lateral\nresolution. Note that if more than one data set is used the target resolution\nwill be the resolution of the finest data set (see also\nSection~\\ref{SEC:P1:GRAV:REMARK:MULTIDATA}).\nIn other cases, the expansion of the region of interest drives an increase of\ndata grid size and the increase of total number of cells is less dramatic as\nthe vertical number of cells can remain constant while keeping a balanced\nresolution in vertical and lateral direction.\n\n\\section{Setting up the Inversion and Running it}\nWe are now at step three of script~\\ref{code: gravity1} where the \ninversion is set up.\nFirst we create an empty inversion under the name \\verb|inv|:\n\\begin{verbatim}\ninv=GravityInversion()\n\\end{verbatim}\nAs indicated by the name we can use \\verb|inv| to perform an inversion of\ngravity data\\footnote{\\verb|GravityInversion| is a driver with a simplified\ninterface which is provided for convenience. See Part~\\ref{part2} for more\ndetails on how to write inversion scripts with more general functionality, e.g.\nconstraints.}. The inversion is an iterative process which sequentially\ncalculates updates to the density distribution in an attempt to improve the\nmatch of the gravity field produced by the density distribution with the data.\nTermination of the iteration is controlled by the tolerance which is set by\nthe user:\n\\begin{verbatim}\ninv.setSolverTolerance(1e-4)\n\\end{verbatim}\nHere we set the tolerance to $10^{-4}$, i.e. the iteration is terminated if\nthe maximum density correction is less than or equal to $10^{-4}$ relative to\nthe maximum value of estimated density anomaly.\nIn case the iteration does not converge a maximum number of iteration steps is\nset:\n\\begin{verbatim}\ninv.setSolverMaxIterations(50)\n\\end{verbatim}\nIf the maximum number of iteration steps (here $50$) is reached the iteration\nprocess is aborted and an error message is printed.\nIn this case you can try to rerun the inversion with a larger value for the\nmaximum number of iteration steps.\nIf even for a very large number of iteration steps no convergence is achieved,\nit is very likely that the inversion has not been set up properly.\n\nThe statement \n\\begin{verbatim}\ninv.setup(dom)\n\\end{verbatim}\nlinks the inversion with the domain and the data.\nAt this step -- as we are solving a gravity inversion problem -- only\ngravitational data attached to the domain builder \\verb|dom| are considered.\nInternally a cost function $J$ is created which is minimized during the\ninversion iteration.\nIt is a combination of a measure of the data misfit of the gravity field from\nthe given density distribution and a measure of the smoothness of the density\ndistribution.\nThe latter is often called the regularization term.\nBy default the gradient of density is used as the regularization term, see\nalso Section~\\ref{SEC:P1:GRAV:REMARK:REG}.\nObviously, the result of the inversion is sensitive to the weighting between\nthe misfit and the regularization.\nThis trade-off factor $\\mu$ for the misfit function is set by the following\nstatement:\n\\begin{verbatim}\ninv.getCostFunction().setTradeOffFactorsModels(0.1) \n\\end{verbatim}\nHere we set $\\mu=0.1$. The statement \\verb|inv.setup| must appear in the\nscript before setting the trade-off factor.\nA small value for the trade-off factor $\\mu$ will give more emphasis to the\nregularization component and create a smoother density distribution.\nA large value of the trade-off factor $\\mu$ will emphasize the misfit more\nand typically creates a better fit to the data and a rougher density\ndistribution.\nIt is important to keep in mind that the regularization reduces noise in the\ndate and in fact gives the problem a unique solution.\nConsequently, the trade-off factor $\\mu$ may not be chosen too large in order\ncontrol the noise on the solution and ensure convergence in the iteration\nprocess.\n\nWe can now run the inversion:\n\\begin{verbatim}\nrho = inv.run()\n\\end{verbatim}\nThe answer as calculated during the inversion is returned and can be accessed\nunder the name \\verb|rho|.\nAs pointed out earlier the iteration process may fail in which case the\nexecution of the script is aborted with an error message.\n\n\\section{Taking a Look}\nIn the final step of script~\\ref{code: gravity1} the calculated density\ndistribution is written to an external file.\nA popular file format used by several visualization packages such as\n\\VisIt~\\cite{VISIT} and \\mayavi~\\cite{mayavi} is the \\VTK file format.\nThe result of the inversion which has been named \\verb|rho| can be written to\nthe file \\file{result.vtu} by adding the statement\n\\begin{verbatim}\nsaveVTK(\"result.vtu\", density=rho)\n\\end{verbatim}\nat the end of script.\nThe inversion solution is tagged with the name \\verb|density| in the result\nfile, however any other name for the tag could be used.\nAs the format is text-based (as opposed to binary) \\VTK files tend to be very\nlarge and take compute time to create, in particular when it comes to large\nnumbers of cells ($>10^6$).\nFor large problems it is more efficient to use the \\SILO file format~\\cite{SILO} \npreferred by the visualization program \\VisIt~\\cite{VISIT}.  \\SILO files are smaller \nand can be generated more quickly than \\VTK files.  \\VisIt is particularly suited for visualizing \nlarge data sets and can read \\SILO files faster than \\VTK files. \nInversion results can be directly exported into \\SILO files using the statement\n\\begin{verbatim}\nsaveSilo(\"result.silo\", density=rho)\n\\end{verbatim}\nreplacing the \\verb|saveVTK(...)| statement.\nSimilar to \\VTK files the result \\verb|rho| is tagged with the name\n\\verb|density| so it can be identified in the visualization program.\n\nAnother useful output option is the \\Voxet format which is understood by the\n\\GOCAD\\cite{GOCAD} geologic modelling software.\nIn order to write inversion results to \\Voxet files use the statement\n\\begin{verbatim}\nsaveVoxet(\"result.vo\", density=rho)\n\\end{verbatim}\nUnlike the other output formats \\Voxet data consists of a header file with the\nfile extension \\verb|.vo| and separate \\emph{property} files without file\nextension. The call to \\verb|saveVoxet(...)| above would produce the files\n\\file{result.vo} and \\file{result_density}.\n\n\\begin{figure}\n    \\begin{center}\n        \\subfigure[$\\mu=0.1$]{%\n            \\label{FIG:P1:GRAV:10 MU01}\n            \\scalebox{0.95}{\\includegraphics[width=0.45\\textwidth]{QLDGravContourMu01.png}}\n        }%\n        \\subfigure[$\\mu=1.$]{%\n            \\label{FIG:P1:GRAV:10 MU1}\n            \\scalebox{0.95}{\\includegraphics[width=0.45\\textwidth]{QLDGravContourMu1.png}}\n        }\\\\ %  ------- End of the first row ----------------------%\n        \\subfigure[$\\mu=10.$]{%\n            \\label{FIG:P1:GRAV:10 MU10}\n            \\scalebox{0.95}{\\includegraphics[width=0.45\\textwidth]{QLDGravContourMu10.png}}\n        }%\n        \\subfigure[$\\mu=100.$]{%\n            \\label{FIG:P1:GRAV:10 MU100}\n            \\scalebox{0.95}{\\includegraphics[width=0.45\\textwidth]{QLDGravContourMu100.png}}\n        }\\\\ %  ------- End of the second row ----------------------%\n        \\subfigure[$\\mu=1000.$]{%\n            \\label{FIG:P1:GRAV:10 MU1000}\n            \\scalebox{0.95}{\\includegraphics[width=0.45\\textwidth]{QLDGravContourMu1000.png}}\n        }%\n    \\end{center}\n    \\caption{3-D contour plots of gravity inversion results with data from\n    Figure~\\ref{FIG:P1:GRAV:0} for various values of the model trade-off\n    factor $\\mu$. Visualization has been performed in \\VisIt.}\n    \\label{FIG:P1:GRAV:10}\n\\end{figure}\n\n\\begin{figure}\n    \\begin{center}\n        \\subfigure[$\\mu=0.1$]{%\n            \\label{FIG:P1:GRAV:11 MU01}\n            \\scalebox{0.95}{\\includegraphics[width=0.45\\textwidth]{QLDGravDepthMu01.png}}\n        }%\n        \\subfigure[$\\mu=1.$]{%\n            \\label{FIG:P1:GRAV:11 MU1}\n            \\scalebox{0.95}{\\includegraphics[width=0.45\\textwidth]{QLDGravDepthMu1.png}}\n        }\\\\ %  ------- End of the first row ----------------------%\n        \\subfigure[$\\mu=10.$]{%\n            \\label{FIG:P1:GRAV:11 MU10}\n            \\scalebox{0.95}{\\includegraphics[width=0.45\\textwidth]{QLDGravDepthMu10.png}}\n        }%\n        \\subfigure[$\\mu=100.$]{%\n            \\label{FIG:P1:GRAV:11 MU100}\n            \\scalebox{0.95}{\\includegraphics[width=0.45\\textwidth]{QLDGravDepthMu100.png}}\n        }\\\\ %  ------- End of the second row ----------------------%\n        \\subfigure[$\\mu=1000.$]{%\n            \\label{FIG:P1:GRAV:11 MU1000}\n            \\scalebox{0.95}{\\includegraphics[width=0.45\\textwidth]{QLDGravDepthMu1000.png}}\n        }%\n    \\end{center}\n    \\caption{3-D slice plots of gravity inversion results with data from\n    Figure~\\ref{FIG:P1:GRAV:0} for various values of the model trade-off\n    factor $\\mu$. Visualization has been performed \\VisIt.%\n    }\n%    \\AZADEH{check images.}\n    \\label{FIG:P1:GRAV:11}\n\\end{figure}\n\nFigures~\\ref{FIG:P1:GRAV:10} and~\\ref{FIG:P1:GRAV:11} show two different\nstyles of visualization generated in \\VisIt using the result of the inversion\nof the gravity anomalies shown in Figure~\\ref{FIG:P1:GRAV:0}.\nThe inversions have been performed with different values for the model\ntrade-off factor $\\mu$.\nThe visualization shows clearly the smoothing effect of lower values for the\ntrade-off factors.\nFor larger values of the trade-off factor the density distribution becomes\nrougher showing larger details.\nComputational costs are significantly higher for larger trade-off factors.\nMoreover, noise in the data has a higher impact on the result.\nTypically several runs are required to adjust the value for the trade-off\nfactor to the datasets used.\n\nFor some analysis tools it is useful to process the results in form of\nComma-separated Values (\\CSV)\\footnote{see \n\\url{http://en.wikipedia.org/wiki/Comma-separated_values}}.\nSuch a file can be created using the statement\n\\begin{verbatim}\nsaveDataCSV(\"result.csv\", x=rho.getFunctionSpace().getX(), density=rho)\n\\end{verbatim}\nin the script.\nThis will create a \\file{result.csv} with columns separated by a comma.\nEach row contains the value of the density distribution and the three\ncoordinates of the corresponding location in the domain.\nThere is a header specifying the meaning of the corresponding column.\nNotice that rows are not written in a particular order and therefore, if\nnecessary, the user has to apply appropriate sorting of the rows.\nColumns are written in alphabetic order of their corresponding tag names.\nFor the interested reader: the statement \\verb|rho.getFunctionSpace()| returns\nthe type used to store the density data \\verb|rho|.\nThe \\verb|getX()| method returns the coordinates of the sampling points used\nfor the particular type of representation, see~\\cite{ESCRIPT} for details. \n\n\\section{Remarks}\n\n\\subsection{ER Mapper Raster Files}\\label{SEC:P1:GRAV:REMARK:ERMAPPER}\nThe \\downunder module can read data stored in ER Mapper Raster files. A data\nset in this format consists of two files, a header file whose name usually ends\nin \\verb|.ers| and the actual data file which has the same filename as the\nheader file but without any file extension.\nThese files are usually produced by a commercial software package and the\ncontents can be quite diverse.\nTherefore, it is not guaranteed that every data set is supported by \\downunder\nbut the most common types of raster data should work\\footnote{If your data\ndoes not load please contact us through \\url{https://launchpad.net/escript-finley}.}.\n\nThe interface for loading ER Mapper files is very similar to the \\netcdf\ninterface described in Section~\\ref{SEC:P1:GRAV:DATA}.\nTo load gravity data stored in the file pair\\footnote{These files are available\nin the example directory.} \\examplefile{GravitySmall.ers} (the\nheader) and \\examplefile{GravitySmall} (the data) without changing any of the\ndefaults use:\n\\begin{verbatim}\nsource0=ErMapperData(ErMapperData.GRAVITY, 'GravitySmall.ers')\n\\end{verbatim}\nIf your data set does not follow the default naming convention you can specify\nthe name of the data file explicitly:\n\\begin{verbatim}\nsource0=ErMapperData(ErMapperData.GRAVITY, 'GravitySmall.ers',\n                     datafile='GravityData')\n\\end{verbatim}\nPlease note that there is no way for the reader to determine if the two files\nreally form a pair so make sure to pass the correct filenames when constructing\nthe reader object.\nThe same optional arguments explained in sections \\ref{SEC:P1:GRAV:DATA} and\n\\ref{SEC:P1:GRAV:REMARK:DATAHOLES} are available for ER Mapper data sets.\nHowever, due to the limitation of the file format only a constant error value\nis supported.\n\n\\subsection{Data With Holes}\\label{SEC:P1:GRAV:REMARK:DATAHOLES}\nAs described previously in this chapter, input data is always given in the form\nof a rectangular grid with constant cell size in each dimension.\nHowever, there are cases when this is not necessarily the case.\nConsider an onshore data set which includes parts of the offshore region as in\nFigure~\\ref{FIG:P1:GRAV:onshoreoffshore}.\nThe valid data in this example has a value range of about $-600$ to $600$ and\nthe inversion is to be run based on these values only, disregarding the\noffshore region.\nIn order to achieve that, the offshore region is \\emph{masked} by using a\nconstant value which is not found within the onshore area.\nFigure~\\ref{FIG:P1:GRAV:onshoreoffshore} clearly shows this masked area in\ndark blue since a mask value of $-1000$ was used.\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.45\\textwidth]{onshore-offshore.png}\n    \\caption{Plot of a rectangular gridded onshore data set that includes\n    offshore regions which have a value (here $-1000$) not found within the\n    real data (Bouguer anomalies in Tasmania, courtesy Geoscience Australia)}\n    \\label{FIG:P1:GRAV:onshoreoffshore}\n\\end{figure}\n\nThe \\netcdf conventions supported in \\downunder include a standard way of\nspecifying such a mask value.\nThe example script \\examplefile{create_netcdf.py} demonstrates how this is\naccomplished in an easy way with any data.\nIf, for any reason, the mask value in the input file is invalid it can be\noverridden via the \\verb|null_value| argument when constructing the\n\\verb|NetCdfData| object:\n\\begin{verbatim}\nsource0=NetCdfData(NetCdfData.GRAVITY, 'data0.nc', null_value=-1000)\n\\end{verbatim}\nIn this example, all data points that have a value of $-1000$ are ignored and\nnot used in the inversion.\nPlease note that the special value \\emph{NaN} (not-a-number) is sometimes used\nfor the purposes of masking in data sets.\nAreas marked with this value are always disregarded in \\downunder.\n\n\\subsection{Multiple Data Sets}\\label{SEC:P1:GRAV:REMARK:MULTIDATA}\nIt is possible to run a single inversion using more than one input data set,\npossibly in different file formats.\nTo do so, simply create the data sources and add them to the domain builder:\n\\begin{verbatim}\nsource0=NetCdfData(NetCdfData.GRAVITY, 'data0.nc')\nsource1=ErMapperData(ErMapperData.GRAVITY, 'data1.ers')\ndom.addSource(source0)\ndom.addSource(source1)\n\\end{verbatim}\nHowever, there are some restrictions when combining data sets:\n\\begin{itemize}\n    \\item Due to the coordinate transformation all data sets must be located in\n        the same UTM zone. If a single dataset crosses UTM zones only the zone\n        of the central longitude is used when projecting.\n        For example, if one data set lies mostly in zone 51 but contains areas\n        of zone 52, it is transformed using zone 51. In this case more data\n        from zone 51 can be added, but not from any other zone.\n    \\item All data sets should have the same spatial resolution but this is not\n        enforced. Combining data with different resolution is currently\n        considered experimental but works best when the resolutions are\n        multiples of each other. For example if the first data set has a\n        resolution (or cell size) of $100$ metres and the second has a cell\n        size of $50$ metres then the target domain will have a cell size of\n        $50$ metres (the finer resolution) and each point of the coarse data\n        will occupy two cells (in the respective dimension).\n\\end{itemize}\n\n\\subsection{Regularization Term}\\label{SEC:P1:GRAV:REMARK:REG}\nThe \\verb|GravityInversion| class supports the following form for the\nregularization:\n\\begin{equation}\n\\int w^{(0)} \\cdot \\rho^2 + w^{(1)}_0  \\rho_{,0}^2 +  w^{(1)}_1  \\rho_{,1}^2 +  w^{(1)}_2  \\rho_{,2}^2\\; dx   \n\\end{equation}\nwhere the integral is calculated across the entire domain.  %In vector notation, this is\n%\\begin{equation}\n%\\int w^{(0)} \\cdot \\rho^2 + {w}\\nabla  \\rho\\cdot \\nabla \\rho \\; dx   \n%\\end{equation}\n$\\rho$ represents the density distribution where $\\rho_{,0}$ $\\rho_{,1}$ and\n$\\rho_{,2}$ are the spatial derivatives of $\\rho$ with respect to the two\nlateral and vertical directions, respectively.\n$w^{(0)}$, $w^{(1)}_0$, $w^{(1)}_1$ and $w^{(1)}_2$ are weighting\nfactors\\footnote{A more general form, e.g. spatially variable values for the\nweighting factors, is supported, see Part~\\ref{part2}}.\nBy default these are $w^{(0)}=0$, $w^{(1)}_0=w^{(1)}_1=w^{(1)}_2=1$.\nOther weighting factors can be set in the inversion set-up.\nFor instance to set $w^{(0)}=10$, $w^{(1)}_0=w^{(1)}_1=0$ and $w^{(1)}_2=100$\nuse the statement:\n\\begin{verbatim}\ninv.setup(dom, w0=10, w1=[0,0,100])\n\\end{verbatim}\nIt is pointed out that the weighting factors are rescaled in order to improve\nnumerical stability. Therefore the relative size of the weighting factors is\nrelevant and using\n\\begin{verbatim}\ninv.setup(dom, w0=0.1, w1=[0,0,1])\n\\end{verbatim}\nwould lead to the same regularization as the statement above.\n", "meta": {"hexsha": "367ad259275d6f831a9d03fbf194bd6b8638a358", "size": 38491, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/inversion/CookGravity.tex", "max_stars_repo_name": "markendr/esys-escript.github.io", "max_stars_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/inversion/CookGravity.tex", "max_issues_repo_name": "markendr/esys-escript.github.io", "max_issues_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/inversion/CookGravity.tex", "max_forks_repo_name": "markendr/esys-escript.github.io", "max_forks_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.2493472585, "max_line_length": 212, "alphanum_fraction": 0.7670364501, "num_tokens": 9836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.33741178287608614}}
{"text": "% \\documentclass[final,3p,times,twocolumn]{elsarticle}\n\\documentclass[final,3p,times]{elsarticle}\n\\usepackage[american]{babel}\n\\usepackage[font=normal]{caption}\n\\usepackage[font=normal]{subcaption}\n\\usepackage[tensorialbold]{userCommands}\n\\usepackage{mathtools,cuted}\n\\usepackage{empheq}\n\\usepackage{tikz} % geometrical figures\n\\usetikzlibrary{calc,trees,positioning,arrows,chains,shapes.geometric,decorations.pathreplacing,decorations.pathmorphing,shapes,\n    matrix,shapes.symbols,shapes.multipart,patterns,shapes,snakes,pgfplots.groupplots,spy,backgrounds}\n\\usetikzlibrary{external}\n\\tikzexternalize[prefix=external/]\n\\usetikzlibrary{spy,backgrounds}\n\\usetikzlibrary{decorations.markings}\n\\usetikzlibrary{arrows.meta}\n\\tikzset{\n  arrows along my path/.style={\n    postaction={\n      decorate,\n      decoration={\n        markings,\n        mark=between positions 0.03 and 1 step 24pt with {\\arrow{Stealth[length=8pt]}},\n   }}}}\n\n\\usepackage{pgfplots} % pdf picture declaration\n\n\\usepackage{array}\n\\newcolumntype{M}[1]{>{\\centering\\arraybackslash}m{#1}}\n\\newcolumntype{N}{@{}m{0pt}@{}}\n\n\n%% The amssymb package provides various useful mathematical symbols\n\\usepackage{amssymb}\n\\usepackage{lineno}\n\\usepackage{float}\n% \\linenumbers\n\n\\usepackage{float}\n\n\n\\usepackage{mathtools}\n\\mathtoolsset{showonlyrefs}\n\n%\\journal{Journal of the Mechanics and Physics of Solids}\n\\journal{}\n\n\\pgfplotsset{%compat=1.3,\n  %compat=1.8,\n  compat=newest,\n  grid=both,\n  tick label style={font=\\normalsize},\n  label style={font=\\normalsize},\n  legend style={font=\\normalsize},\n  legend cell align={left},\n  yticklabel style={/pgf/number format/fixed},\n  %scaled y ticks=false,\n  % define user colormap\n  colormap={tol}{[1cm] rgb255(0cm)=(120,28,129) rgb255(1cm)=(63,96,174) rgb255(2cm)=(83,158,182) rgb255(3cm)=(109,179,136) rgb255(4cm)=(202,184,67) rgb255(5cm)=(231,133,50) rgb255(6cm)=(217,33,32)}\n}\n\n\\definecolor{Purple}{RGB}{120,28,129}\n\\definecolor{Orange}{RGB}{231,133,50}\n\\definecolor{Blue}{RGB}{63,96,174}\n\\definecolor{Red}{RGB}{217,33,32}\n\\definecolor{Duck}{RGB}{83,158,182}\n\\definecolor{Green}{RGB}{109,179,136}\n\\definecolor{Yellow}{RGB}{202,184,67}\n\n\\newcommand{\\review}[1]{\\color{Red}#1\\color{black}}\n\n\\newtheorem{remark}{Remark}\n\\newtheorem{property}{Property}\n\n\n\\begin{document}\n\n\\begin{frontmatter}\n\n\n  %% Title, authors and addresses\n\n  %% use the tnoteref command within \\title for footnotes;\n  %% use the tnotetext command for theassociated footnote;\n  %% use the fnref command within \\author or \\address for footnotes;\n  %% use the fntext command for theassociated footnote;\n  %% use the corref command within \\author for corresponding author footnotes;\n  %% use the cortext command for theassociated footnote;\n  %% use the ead command for the email address,\n  %% and the form \\ead[url] for the home page:\n  %% \\title{Title\\tnoteref{label1}}\n  %% \\tnotetext[label1]{}\n  %% \\author{Name\\corref{cor1}\\fnref{label2}}\n  %% \\ead{email address}\n  %% \\ead[url]{home page}\n  %% \\fntext[label2]{}\n  %% \\cortext[cor1]{}\n  %% \\address{Address\\fnref{label3}}\n  %% \\fntext[label3]{}\n  \n  %\\title{A unified framework for simple wave solutions in two-dimensional elastic-plastic solids}\n  \\title{On loading paths followed inside plastic simple waves in two-dimensional elastic-plastic solids}\n  \n  %% use optional labels to link authors explicitly to addresses:\n  %% \\author[label1,label2]{}\n  %% \\address[label1]{}\n  %% \\address[label2]{}\n  \n  \\author{Adrien Renaud$^{1,2}$, Thomas Heuz{\\'e}$^2$, Laurent Stainier$^2$}\n  \\address{$^1$ Laboratory MSSMat (UMR 8579 CNRS)\\\\\n    CentraleSup{\\'e}lec, Universit{\\'e} Paris-Saclay\\\\\n    8-10 rue Joliot-Curie, 91190 Gif-sur-Yvette\\\\\n    e-mail: adrien.renaud@centralesupelec.fr }\n\n  \\address{$^2$ Research Institute in Civil and Mechanical Engineering (GeM, UMR 6183 CNRS)\\\\\n    Ecole Centrale de Nantes \\\\\n    1 rue de la No\\\"e, Nantes\\\\\n    e-mail: \\{thomas.heuze,laurent.stainier\\}@ec-nantes.fr}\n  \n  \\begin{abstract}\n    Although the solution of hyperbolic partial differential equations in elastic-plastic media is of major importance in solid mechanics, the mathematical complexity of such problems increases with the space dimensionality.\n    As a result, the development of analytical solutions is in general not possible.\n    % Whereas the wave structure arising in one-dimensional problems is known and well understood, several gaps still need to be filled for problems with more space dimensions.\n    Whereas the wave structure resulting from given external loads is known and well understood for one-dimensional problems, several gaps still need to be filled for problems with more space dimensions.\n    Indeed, the literature related to the propagation of simple waves in elastic-plastic solids is rather sparse since only particular two-dimensional and three-dimensional problems have been considered.\n    Following the general three-dimensional framework of \\textsc{Mandel} (1962), the object of the paper is to construct the loading paths followed inside the simple waves under plane strain and plane stress conditions.\n    It is believed that the mathematical and numerical studies of the waves presented here could help %(i) relate the boundary conditions of the Picard problem to the wave pattern; (ii)\n    define the characteristic structure involved in a Riemann problem. % so that the latter can be solved.\n    % The object of the paper is first to derive a unified framework for the study of the propagation of waves in elastic-plastic media that gathers configurations already investigated as well as other ones not treated so far. \n    % A generic three-dimensional formulation of hyperbolic problems in these solids, which can be easily specialized to plane strain and plane stress problems, is then proposed in the linearized geometrical framework.\n    % This work focuses on simple waves arising in the solution in two space dimensions.\n    % Mathematical as well as numerical studies of these waves under plane strain and plane stress conditions are next carried out in order to emphasize typical loading paths followed and hence, characteristic physical responses.\n  \\end{abstract}\n  \n  \\begin{keyword}\n    Hyperbolic problems; Elastic-plastic solids; Simple waves; Loading paths; Characteristic analysis.\n  \\end{keyword}\n\n\n\\end{frontmatter}\n\n\n\\section{Introduction}\n\\label{sec:introduction}\n\\input{introduction}\n\n\n\\section{Hyperbolic system in elastic-plastic media}\n\\label{sec:charac_plast}\n\\input{characteristic_analysis}\n\n\\section{The eigen-value problem in two space dimensions}\n\\label{sec:2dproblem}\n\\input{2dFormulation}\n\n\\section{Integral curves for two-dimensional problems}\n\\label{sec:integral_curves}\n\\input{integral_curves}\n\n% \\section{Loading paths through simple waves}\n\n\\section{Some properties of the loading paths for several cases}\n\\label{sec:stress_paths}\n\\input{analytical_results}\n\n% should we talk about lin & ballman after the numerical results about the thin-walled tube?\n\\section{Numerical integration of stress paths}\n\\label{sec:numerical_results}\n\\input{numerical_results}\n\n\n\\section{Conclusion}\n\\label{sec:conclusion}\n\\input{conclusion}\n\n\n\\section*{References}\n\\bibliographystyle{elsarticle-num}\n\\bibliography{Biblio}\n\n\n\\end{document}\n\\endinput\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: t\n%%% End:\n", "meta": {"hexsha": "f1e6acccbba0714d5819f543652ec6292f09add4", "size": 7292, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "papJmPs/manuscript.tex", "max_stars_repo_name": "adRenaud/research", "max_stars_repo_head_hexsha": "2f0062a1800d7a17577bbfc2393b084253d567f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-18T14:52:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-18T14:52:03.000Z", "max_issues_repo_path": "papJmPs/manuscript.tex", "max_issues_repo_name": "adRenaud/research", "max_issues_repo_head_hexsha": "2f0062a1800d7a17577bbfc2393b084253d567f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-01-07T13:11:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-07T13:11:11.000Z", "max_forks_repo_path": "papJmPs/manuscript.tex", "max_forks_repo_name": "adRenaud/research", "max_forks_repo_head_hexsha": "2f0062a1800d7a17577bbfc2393b084253d567f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7872340426, "max_line_length": 229, "alphanum_fraction": 0.7580910587, "num_tokens": 1951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863698, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.33720053003063616}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n\\chapter{Background}\n\\label{chap:Background}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n\nThis chapter sets the stage for type systems in later chapters. \\Cref{sec:HM}\nreviews the Hindley-Milner type system \\citep{Damas:Milner,hindley,milner}, a\nclassical type system for the lambda calculus with parametric polymorphism.\n\\Cref{sec:OL} presents the Odersky-L{\\\"a}ufer type system\n\\citep{odersky:putting}, which extends upon the Hindley-Milner type system by\nputting higher-rank type annotations to work. Finally in \\Cref{sec:DK} we\nintroduce the Dunfield-Krishnaswami type system, a bidirecitonal higher-rank\ntype system. Here we pay particular attention to the Dunfield-Krishnaswami\nsystem as it serves as a basis for extensions in later chapters; for example,\n\\Cref{chap:Gradual} is a direct extension of Dunfield-Krishnaswami. There is\nplenty of other related work to higher-rank type system (e.g.,\n\\cite{practical:inference}), and we include a more substantive discussion of\nthose works in \\Cref{chap:related}.\n\n\n\\input{Gen/Background/HM}\n\\input{Gen/Background/OL}\n\\input{Gen/Background/DK}\n\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: \"../Thesis\"\n%%% org-ref-default-bibliography: \"../Thesis.bib\"\n%%% End:", "meta": {"hexsha": "8cb0bde2c242b7484222752dc68d719e44f02f01", "size": 1324, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Sources/Background.tex", "max_stars_repo_name": "xnning/Dissertation", "max_stars_repo_head_hexsha": "bcdca568b3e89ba9cc0e4e9858a34e7c008a4ebb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-09-07T00:43:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T23:07:52.000Z", "max_issues_repo_path": "Sources/Background.tex", "max_issues_repo_name": "xnning/Dissertation", "max_issues_repo_head_hexsha": "bcdca568b3e89ba9cc0e4e9858a34e7c008a4ebb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sources/Background.tex", "max_forks_repo_name": "xnning/Dissertation", "max_forks_repo_head_hexsha": "bcdca568b3e89ba9cc0e4e9858a34e7c008a4ebb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-15T08:46:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T08:46:35.000Z", "avg_line_length": 44.1333333333, "max_line_length": 77, "alphanum_fraction": 0.6903323263, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3372005300306361}}
{"text": "\\chapter{Bayes minimum risk}\\label{ch:6}\n\n\\begin{remark}{Outline}\nIn this chapter, we propose the cost-sensitive Bayes minimum risk classifier. The method \nconsists in quantifying tradeoffs between various decisions using probabilities and the costs that \naccompany such decisions. First, in Section~\\ref{sec:6:bmr}, we present the Bayes minimum risk \nalgorithm. Then, in Section~\\ref{sec:6:prob}, we discuss the impact of calibrating the probabilities \nin the model. Finally, in Section~\\ref{sec:6:experiments},  using the five real-world cost-sensitive \ndatabases, we compare the results of the proposed algorithm, against state-of-the-art methods.\n\\end{remark}\n\n\n\\section{Bayes minimum risk model}\n\\label{sec:6:bmr}\n\n% % As decribed in Section \\ref{sec:3:cs}, state-of-the-art example dependent techniques, only \n% introduce the cost by modifying the training set. In \\citep{CorreaBahnsen2013,CorreaBahnsen2014}, \n% we proposed a cost-sensitive model called Bayes minimum risk classifier ($BMR$).  \n\nAs defined in \\citep{Ghosh2006}, the BMR classifier is a decision model based on quantifying \ntradeoffs between various decisions using probabilities and the costs that accompany such decisions. \nThis is done in a way that for each example the expected losses are minimized. In  what follows, we \nconsider the probability estimates $\\hat p_i$ as known, regardless of the algorithm used to \ncalculate them.  The risk that accompanies each decision is calculated using the cost matrix \nas described in \\tablename{ \\ref{tab:3:cost_matrix}}. In the specific framework of binary \nclassification, the risk of predicting the example $i$ as negative is \n\\begin{equation}\n  R(c_i=0|\\mathbf{x}_i)=C_{TN_i}(1-\\hat p_i)+C_{FN_i} \\cdot \\hat p_i, \n\\end{equation}\nand\n\\begin{equation}\n  R(c_i=1|\\mathbf{x}_i)=C_{TP_i} \\cdot \\hat p_i + C_{FP_i}(1- \\hat p_i), \n\\end{equation}\nis the risk when predicting the example as positive, where $\\hat p_i$ is the estimated positive \nprobability for example $i$. Subsequently, if \n\\begin{equation}\n  R(c_i=0|\\mathbf{x}_i) \\le R(c_i=1|\\mathbf{x}_i), \n\\end{equation}\nthen  the example $i$ is classified as negative. This means that the risk associated with the \ndecision $c_i$ is lower than the risk associated with classifying it as positive. \n\n\n\\section{Calibration of probabilities}\n\\label{sec:6:prob}\n\nWhen using the output of a binary classifier as a basis for decision making, there is a \nneed for a probability that not only separates well between positive and negative examples, but \nthat also assesses the real probability of the event \\citep{cohen2004}.\n\nIn this section, two methods for calibrating probabilities are explained. First, the method proposed \nin \\citep{Elkan2001} to adjust the probabilities based on the   difference in bad rates  between the \ntraining and testing datasets.  Then, the method proposed in \\cite{Hernandez-Orallo2012}, in which \ncalibrated probabilities are extracted after modifying the ROC curve using the ROC convex hull \nmethodology, is described.\n \n\\subsection{Calibration due to a change in base rates}\n\nOne of the reasons why a probability may not be calibrated is because the algorithm is trained \nusing a dataset with a different base (or positive) rate than the one on the evaluation dataset.  \nThis is something common in machine learning since using under-sampling or over-sampling is a \ntypical method to solve problems such as class imbalance and cost sensitivity \\citep{Hulse2007}.\n  \nIn order to solve this and find probabilities that are calibrated, in \\citep{Elkan2001} a formula  \nthat corrects the probabilities based on the difference of the base rates is proposed.  The \nobjective is using $\\hat p$ which was estimated using a population with base rate $\\pi_1$,\nto find $\\hat p'$ for the real population which has a base rate $\\pi_1'$. A solution for $\\hat p'$ \nis given as follows:\n\\begin{equation}\n  \\hat p'=\\pi_1' \\frac{\\hat p - \\hat p \\pi_1}{\\pi_1- \\pi_1 \\hat p +\\pi_1' \\hat p - \\pi_1 \\pi_1'}.\n\\end{equation}\n\n% Nevertheless, a strong assumption is made by taking: $P'(x|j=1)=P(x|j=1)$} and \n% \\mbox{$P'(x|j=0)=P(x|j=0)$}, meaning that there\n%   is no change in the example probability within the positive and negative\n%   subpopulations density functions.\n  \n\\subsection{Calibration using the ROC convex hull}\n\nIn order to illustrate the ROC convex hull approach proposed in \\citep{Hernandez-Orallo2012},\nlet us consider the set of probabilities given in \\figurename{~\\ref{tab:6:example_prob}}.\nTheir corresponding  ROC curve  is shown in \\figurename{~\\ref{fig:6:ROC_1}}.  It can be seen that \nthis set of probabilities is not calibrated, since when $fpr=0.1$ there is a positive example  \nfollowed by 2 negative examples. This inconsistency is represented in the ROC curve as a non convex \nsegment  over the curve.\n  \n\\begin{figure}[!t]\n\\hskip 1cm\n\\hbox{\n  \\vtop{\n    \\hbox{\n      \\subfloat[Set of probabilities and their respective class label]{\n   \\footnotesize\n\t\\begin{tabular}{cc}\n\t\\hline\n\tProbability & Label\\\\\n\t\\hline\n\t0.0&\t0\\\\\n\t0.1&\t1\\\\\n\t0.2&\t0\\\\\n\t0.3&\t0\\\\\n\t0.4&\t1\\\\\n\t0.5&\t0\\\\\n\t0.6&\t1\\\\\n\t0.7&\t1\\\\\n\t0.8&\t0\\\\\n\t0.9&\t1\\\\\n\t1.0&\t1\\\\\n\t\\hline\n\t\\end{tabular}\\label{tab:6:example_prob}\n      }\n    }\n  }\\hskip 1.5cm\n  \\vtop{\\vskip -2.5cm\n    \\subfloat[ROC curve of the set of probabilities]{\n      \\includegraphics[scale=0.5]{ch6_fig2}\\label{fig:6:ROC_1}\n    }%\n  }%\n}\n\\vskip 1.5cm\n\n\\hbox{ \n  \\vtop{ \\vskip -0.5cm\n    \\hbox{\n      \\subfloat[Convex hull of the ROC curve]{\n\t\\includegraphics[scale=0.5]{ch6_fig1}\\label{fig:6:ROC_2}\n      }\n    }\n  }\\hskip 1.75cm\n  \\vtop{ \\vskip -1cm\n    \\subfloat[Calibrated probabilities]{\n   \\footnotesize\n\t\\begin{tabular}{cc}\n\t\\hline\n\tProb & Cal Prob\\\\\n\t\\hline\n\t0.0&\t0\\\\\n\t0.1&\t0.333\\\\\n\t0.2&\t0.333\\\\\n\t0.3&\t0.333\\\\\n\t0.4&\t0.5\\\\\n\t0.5&\t0.5\\\\\n\t0.6&\t0.666\\\\\n\t0.7&\t0.666\\\\\n\t0.8&\t0.666\\\\\n\t0.9&\t1\\\\\n\t1.0&\t1\\\\\n\t\\hline\n\t\\end{tabular}\\label{fig:6:cal_prob} \n    }\n  }\n}\n\\caption{Estimation of calibrated probabilities using the ROC convex hull.}\\label{fig:6:rocch}\n\\end{figure}\n\nIn order to obtain a set of calibrated probabilities, first the ROC curve must be modified in \norder to be convex. The way to do that, is to find the convex \\mbox{hull \n\\citep{Hernandez-Orallo2012}} to find the minimal convex set containing the different \npoints of the ROC curve. In \\figurename{~\\ref{fig:6:ROC_2}}, the convex hull algorithm is applied \nto the previously evaluated ROC curve shown in \\figurename{~\\ref{fig:6:ROC_1}}. It is shown that \nthe new curve is convex, and includes all the points of the previous ROC curve.\n\nNow that there is a new convex ROC curve or ROCCH, the calibrated probabilities can be extracted \nas shown in  \\figurename{~\\ref{fig:6:cal_prob}}. The procedure to extract the new probabilities is \nto first group the probabilities according to the points in the ROCCH curve, and then make the \ncalibrated  probabilities be the slope of the ROCCH for each group.\n  \n   \n\\section{Experiments}\n\\label{sec:6:experiments}\n\nFor the experiments we use five datasets from four different real world example-dependent \ncost-sensitive problems: Credit card fraud detection (see Section~\\ref{sec:4:fraud}), credit \nscoring (see Section~\\ref{sec:4:creditscoring}), churn modeling (see Section~\\ref{sec:5:churn}) and \ndirect marketing (see Section~\\ref{sec:5:directmarketing}). The different datasets are summarized \nin \\tablename{~\\ref{tab:4:databases}} and \\tablename{~\\ref{tab:5:databases}}.\n\nFor the experiments, we first used three classification algorithms, decision tree ($DT$), logistic \n  regression ($LR$) and random forest ($RF$). Using the implementation of \\textit{Scikit-learn} \n  \\citep{Pedregosa2011}, each algorithm is trained using the different training sets: training \n  ($t$), under-sampling ($u$), cost-proportionate rejection-sampling  ($r$) \\citep{Zadrozny2003}   \n  and   cost-proportionate over-sampling ($o$) \\citep{Elkan2001}. Afterwards,  we evaluate the \n  results of  the algorithms using $BMR$ methods. In particular, we   check the impact on the \n  results of the different calibration methods. The implementation of the cost-sensitive algorithms \n  is done using the \\textit{CostCla} library, see Appendix~\\ref{ch:A}.\n  \n  \\begin{table}\n    \\centering\n    \\footnotesize\n    %\\hspace{-3.5cm}\n    \\rotatebox{90}{\n    \\begin{tabular}{l l r@{\\hskip 0in}c@{\\hskip 0in}l r@{\\hskip 0in}c@{\\hskip 0in}l r@{\\hskip \n    0in}c@{\\hskip 0in}l  r@{\\hskip 0in}c@{\\hskip 0in}l r@{\\hskip 0in}c@{\\hskip 0in}l} %sum 7.7\n    \\hline\n    \\bf{Family} & \\bf{Algorithm} & \\multicolumn{3}{c}{\\bf{Fraud}} & \n    \\multicolumn{3}{c}{\\bf{Churn}} & \\multicolumn{3}{c}{\\bf{Credit 1}}\n    &  \\multicolumn{3}{c}{\\bf{Credit 2}} & \\multicolumn{3}{c}{\\bf{Marketing}} \\\\ \n    \\hline\nCI&DT-t & 0.3176 &$\\pm$& 0.0357 & -0.0018 &$\\pm$& 0.0194 & 0.1931 &$\\pm$& 0.0087& -0.0616 &$\\pm$& 0.0229 & -0.2342 &$\\pm$& 0.0609\\\\ \n&LR-t & 0.0092 &$\\pm$& 0.0002 & -0.0001 &$\\pm$& 0.0002 & 0.0177 &$\\pm$& 0.0126& 0.0039 &$\\pm$& 0.0012 & -0.2931 &$\\pm$& 0.0602\\\\\n&RF-t & 0.3342 &$\\pm$& 0.0156 & -0.0026 &$\\pm$& 0.0079 & 0.1471 &$\\pm$& 0.0071 & 0.0303 &$\\pm$& 0.0040 & -0.2569 &$\\pm$& 0.0637\\\\  \n&DT-u & 0.5239 &$\\pm$& 0.0118 & -0.0389 &$\\pm$& 0.0583 & 0.3287 &$\\pm$& 0.0125 & -0.1893 &$\\pm$& 0.0314 & -0.0278 &$\\pm$& 0.0475\\\\ \n&LR-u & 0.1243 &$\\pm$& 0.0387 & 0.0039 &$\\pm$& 0.0492 & 0.4118 &$\\pm$& 0.0313 & 0.1850 &$\\pm$& 0.0231 & 0.2200 &$\\pm$& 0.0376\\\\ \n&RF-u & 0.5684 &$\\pm$& 0.0097 & 0.0433 &$\\pm$& 0.0533 & 0.4981 &$\\pm$& 0.0079 & 0.1237 &$\\pm$& 0.0228 & 0.1227 &$\\pm$& 0.0443\\\\\n\\hline \nCPS&DT-r & 0.3439 &$\\pm$& 0.0453 & 0.0054 &$\\pm$& 0.0568 & 0.3310 &$\\pm$& 0.0126 & 0.0724 &$\\pm$& 0.0212 & 0.1960 &$\\pm$& 0.0527\\\\ \n&LR-r & 0.3077 &$\\pm$& 0.0301 & 0.0484 &$\\pm$& 0.0375 & 0.3965 &$\\pm$& 0.0263& 0.2650 &$\\pm$& 0.0115 & 0.4210 &$\\pm$& 0.0267\\\\ \n&RF-r & 0.3812 &$\\pm$& 0.0264 & 0.1056 &$\\pm$& 0.0412 & \\bf{0.4989} &\\bf{$\\pm$}& \\bf{0.0080}& 0.3055 &$\\pm$& 0.0106 & 0.3840 &$\\pm$& 0.0360\\\\ \n&DT-o & 0.3172 &$\\pm$& 0.0274 & 0.0251 &$\\pm$& 0.0195 & 0.1738 &$\\pm$& 0.0092 & 0.0918 &$\\pm$& 0.0225 & -0.2598 &$\\pm$& 0.0559\\\\ \n&LR-o & 0.2793 &$\\pm$& 0.0185 & 0.0316 &$\\pm$& 0.0228 & 0.3301 &$\\pm$& 0.0109 & 0.2554 &$\\pm$& 0.0090 & 0.3129 &$\\pm$& 0.0277\\\\ \n&RF-o & 0.3612 &$\\pm$& 0.0295 & 0.0205 &$\\pm$& 0.0156 & 0.2128 &$\\pm$& 0.0081& 0.2242 &$\\pm$& 0.0070 & -0.1782 &$\\pm$& 0.0618\\\\ \n\\hline \nBMR&DT-t-BMR & 0.6045 &$\\pm$& 0.0386 & 0.0226 &$\\pm$& 0.0200 & 0.1931 &$\\pm$& 0.0087 & -0.0616 &$\\pm$& 0.0230 & -0.2185 &$\\pm$& 0.0611\\\\ \n&LR-t-BMR & 0.4552 &$\\pm$& 0.0203 & 0.0872 &$\\pm$& 0.0308 & 0.1973 &$\\pm$& 0.0404 & 0.3119 &$\\pm$& 0.0089 & 0.4915 &$\\pm$& 0.0090\\\\ \n&RF-t-BMR & 0.6175 &$\\pm$& 0.0149 & 0.0435 &$\\pm$& 0.0356 & 0.4878 &$\\pm$& 0.0082 & 0.3027 &$\\pm$& 0.0096 & 0.3722 &$\\pm$& 0.0263\\\\ \n\\hline \nCAL&DT-t-BMR-cal & 0.5936 &$\\pm$& 0.0386 & 0.0298 &$\\pm$& 0.0145 & 0.1054 &$\\pm$& 0.0358& 0.2740 &$\\pm$& 0.0067 & 0.4598 &$\\pm$& 0.0089\\\\ \nBMR&LR-t-BMR-cal & 0.0897 &$\\pm$& 0.0203 & \\bf{0.1082} &\\bf{$\\pm$}& \\bf{0.0316} & 0.2189 &$\\pm$& \n0.0541 & \\bf{0.3148} &\\bf{$\\pm$}& \\bf{0.0094} & \\bf{0.4973} &\\bf{$\\pm$}& \\bf{0.0084}\\\\ \n&RF-t-BMR-cal & \\bf{0.6414} &\\bf{$\\pm$}& \\bf{0.0154} & 0.0856 &$\\pm$& 0.0354 & 0.4924 &$\\pm$& \n0.0087 & 0.3133 &$\\pm$& 0.0094 & 0.4807 &$\\pm$& 0.0093\\\\  \n\\hline\n  \\multicolumn{17}{c}{(Models with the highest savings are marked in bold)}\n  \\end{tabular}\n  }\n    \\caption{Results of the algorithms measured by savings}\n    \\label{tab:6:results_savings}\n  \\end{table}\n  \nThe results are shown in \\tablename{ \\ref{tab:6:results_savings}}. First, when observing  the \nresults of the cost-insensitive methods ($CI$), that is, $DT$, $LR$ and $RF$ algorithms trained \non the $t$ and $u$ sets, the $RF$ algorithm produces the best result by savings in three out of \nthe five sets, followed by the $LR-u$. It is also clear that the results on the $t$ dataset are \nnot as good as the ones on the $u$ dataset, this is highly related to the unbalanced distribution \nof the positives and negatives in all the databases.  \n  \nIn the case of cost-proportionate sampling methods ($CPS$), specifically the \ncost-proportionate rejection sampling ($r$) and cost-proportionate over \nsampling ($o$), it is observed that in four cases the savings increase quite \nsignificantly. It is on the fraud detection database where these methods do not outperform the \nalgorithms trained on the under-sampled set. This may be related to the fact that in this \ndatabase the initial percentage of positives is 1.5\\% which is similar to the percentage in the \n$r$ and   $o$ sets. However, it is 50.42\\% in the $u$ set, which may help explain why this method \nperforms much better as measured by savings.\n\n\\begin{figure}[!t]\n  \\centering\n  \\includegraphics{ch6_fig3}\n  \\caption{\\textbf{Comparison of the average savings of the algorithms versus the \n    highest savings by family of classifiers.} When the probabilities are calibrated there is a \n    significant increase in savings.}\n  \\label{fig:6:comparison_family}\n  \\vspace{1cm}\n\\end{figure}\n\n  \\begin{table}[!t]\n    \\centering\n    \\footnotesize\n    \\rotatebox{90}{\n    \\begin{tabular}{l l r@{\\hskip 0in}c@{\\hskip 0in}l r@{\\hskip 0in}c@{\\hskip 0in}l r@{\\hskip \n    0in}c@{\\hskip 0in}l  r@{\\hskip 0in}c@{\\hskip 0in}l r@{\\hskip 0in}c@{\\hskip 0in}l} %sum 7.7\n    \\hline\n    \\bf{Family} & \\bf{Algorithm} & \\multicolumn{3}{c}{\\bf{Fraud}} & \n    \\multicolumn{3}{c}{\\bf{Churn}} & \\multicolumn{3}{c}{\\bf{Credit 1}}\n    &  \\multicolumn{3}{c}{\\bf{Credit 2}} & \\multicolumn{3}{c}{\\bf{Marketing}} \\\\ \n    \\hline\nCI&DT-t & 0.0134 &$\\pm$& 0.0005 & 0.0932 &$\\pm$& 0.0054 & 0.1054 &$\\pm$& 0.0016& 0.3103 &$\\pm$& 0.0041 & 0.1924 &$\\pm$& 0.0035\\\\ \n&LR-t & 0.0440 &$\\pm$& 0.0008 & 0.0449 &$\\pm$& 0.0025 & 0.0598 &$\\pm$& 0.0016& 0.1511 &$\\pm$& 0.0016 & 0.0960 &$\\pm$& 0.0018\\\\ \n&RF-t & 0.0064 &$\\pm$& 0.0002 & 0.0532 &$\\pm$& 0.0027 & 0.0519 &$\\pm$& 0.0007 & 0.1525 &$\\pm$& 0.0016 & 0.1090 &$\\pm$& 0.0018\\\\ \n&DT-u & 0.1424 &$\\pm$& 0.0071 & 0.4152 &$\\pm$& 0.0205 & 0.3141 &$\\pm$& 0.0052& 0.4526 &$\\pm$& 0.0057 & 0.4125 &$\\pm$& 0.0062\\\\ \n&LR-u & 0.1872 &$\\pm$& 0.0195 & 0.2439 &$\\pm$& 0.0139 & 0.1718 &$\\pm$& 0.0088 & 0.2317 &$\\pm$& 0.0017 & 0.2016 &$\\pm$& 0.0027\\\\ \n&RF-u & 0.0724 &$\\pm$& 0.0007 & 0.2442 &$\\pm$& 0.0134 & 0.1565 &$\\pm$& 0.0019& 0.2325 &$\\pm$& 0.0024 & 0.2256 &$\\pm$& 0.0036\\\\ \n\\hline \nCPS&DT-r & 0.2041 &$\\pm$& 0.0111 & 0.3595 &$\\pm$& 0.0185 & 0.2884 &$\\pm$& 0.0054 & 0.5516 &$\\pm$& 0.0070 & 0.3581 &$\\pm$& 0.0111\\\\ \n&LR-r & 0.1726 &$\\pm$& 0.0098 & 0.1906 &$\\pm$& 0.0112 & 0.1448 &$\\pm$& 0.0063& 0.2657 &$\\pm$& 0.0051 & 0.2029 &$\\pm$& 0.0055\\\\ \n&RF-r & 0.1764 &$\\pm$& 0.0127 & 0.1964 &$\\pm$& 0.0101 & 0.1374 &$\\pm$& 0.0028& 0.3613 &$\\pm$& 0.0055 & 0.2123 &$\\pm$& 0.0054\\\\ \n&DT-o & 0.1264 &$\\pm$& 0.0102 & 0.0963 &$\\pm$& 0.0048 & 0.1020 &$\\pm$& 0.0014& 0.4550 &$\\pm$& 0.0039 & 0.1904 &$\\pm$& 0.0028\\\\ \n&LR-o & 0.2158 &$\\pm$& 0.0098 & 0.1136 &$\\pm$& 0.0025 & 0.1134 &$\\pm$& 0.0014& 0.2258 &$\\pm$& 0.0023 & 0.1517 &$\\pm$& 0.0013\\\\ \n&RF-o & 0.1694 &$\\pm$& 0.0146 & 0.0701 &$\\pm$& 0.0031 & 0.0550 &$\\pm$& 0.0008& 0.3283 &$\\pm$& 0.0030 & 0.1190 &$\\pm$& 0.0016\\\\ \n\\hline \nBMR&DT-t-BMR & 0.0134 &$\\pm$& 0.0005 & 0.0932 &$\\pm$& 0.0054 & 0.1054 &$\\pm$& 0.0016 & 0.3103 &$\\pm$& 0.0041 & 0.1924 &$\\pm$& 0.0035\\\\ \n&LR-t-BMR & 0.0440 &$\\pm$& 0.0008 & 0.0449 &$\\pm$& 0.0025 & 0.0598 &$\\pm$& 0.0016& 0.1511 &$\\pm$& 0.0016 & 0.0960 &$\\pm$& 0.0018\\\\ \n&RF-t-BMR & 0.0064 &$\\pm$& 0.0002 & 0.0532 &$\\pm$& 0.0027 & 0.0519 &$\\pm$& 0.0007 & 0.1525 &$\\pm$& 0.0016 & 0.1090 &$\\pm$& 0.0018\\\\ \n\\hline \nCAL&DT-t-BMR-cal & 0.0098 &$\\pm$& 0.0004 & 0.0448 &$\\pm$& 0.0029 & 0.0604 &$\\pm$& 0.0009& 0.1586 &$\\pm$& 0.0019 & 0.1075 &$\\pm$& 0.0017\\\\ \nBMR&LR-t-BMR-cal & 0.0148 &$\\pm$& 0.0007 & \\bf{0.0444} &\\bf{$\\pm$}& \\bf{0.0025} & 0.0590 &$\\pm$& \n0.0018& \\bf{0.1505} &\\bf{$\\pm$}& \\bf{0.0016} & \\bf{0.0952} &\\bf{$\\pm$}& \\bf{0.0017}\\\\ \n&RF-t-BMR-cal & \\bf{0.0058} &\\bf{$\\pm$}& \\bf{0.0003} & 0.0446 &$\\pm$& 0.0026 & \\bf{0.0514} \n&\\bf{$\\pm$}& \\bf{0.0008}& 0.1510 &$\\pm$& 0.0016 & 0.0999 &$\\pm$& 0.0019\\\\ \n\\hline\n  \\multicolumn{17}{c}{(Models with the lowest Brier score are marked as bold)}\n  \\end{tabular}\n }\n    \\caption{Results of the algorithms measured by Brier score}\n    \\label{tab:6:results_brier}\n\\end{table}\n\nAfterwards, in the case of the $BMR$ algorithms, the results show that this method outperforms \nthe previous ones in four cases and has almost the same result in the other set. In the fraud \ndetection  set, the results are better, since the savings of the three classification \nalgorithms increase when using this methodology. Moreover, we found that by calibrating the \nprobabilities, the results of the Bayes minimum risk increase. In \n\\figurename{~\\ref{fig:6:comparison_family}}, we compare the different families of algorithms, by \ncalculating in each dataset the performance of the methods compared with the best method. First, it \nis shown the huge difference of using only cost-insensitive methods, compared with any of the \ncost-sensitive families. Furthermore, the Bayes minimum risk methods outperforms the \ncost-proportionate sampling methods.\n  \nMoreover, we evaluate the Brier score of the different algorithms. The objective of this, is \nbecause as mention in  \\citep{cohen2004}, when using the output of a binary classifier as a basis \nfor decision making, there is a need for a probability that not only separates well between \npositive \nand negative examples, but that also assesses the real probability of the event. The results are \nshown in \\tablename{~\\ref{tab:6:results_brier}}. First of all, as expected, the logistic regression \nmodels are very well calibrated regardless of the dataset used for train them. This is because, the \nlogistic regression algorithm is intended to estimate the most reliable probabilities as we will \ndiscuss in \\chaptername{~\\ref{ch:7}}.\n\nWhen comparing the results of the Bayes minimum risk with and without calibration, it is clear that \nthe calibration of the probabilities lead to a lower Brier score as shown in \n\\figurename{~\\ref{fig:6:comparison_family_brier}}. Interestingly, the results of Brier score \nand the savings are highly correlated, confirming the intuition behind the need to calibrate the \nprobabilities before using the Bayes minimum risk method.\n\n\\begin{figure}[ht!]\n  \\centering\n  \\includegraphics{ch6_fig4}\n  \\caption{\\textbf{Comparison of the average Brier score of the algorithms versus the \n    lowest Brier score by family of classifiers.} Overall, the models that are calibrated are \nindeed the ones with the best Brier score.}\n  \\label{fig:6:comparison_family_brier}\n\\end{figure}\n\n\\makeatletter\n\\setlength{\\@fptop}{0pt}\n\\makeatother\n  \n  \n  ", "meta": {"hexsha": "cbeb32dc77c5f7ad97ad3dc2e942f918983464ad", "size": 18530, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/chapters/chapter06.tex", "max_stars_repo_name": "albahnsen/phd-thesis", "max_stars_repo_head_hexsha": "8aedb00cba939b6f8a2f891f453a37206db1f635", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2015-10-07T13:31:49.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-09T12:02:27.000Z", "max_issues_repo_path": "tex/chapters/chapter06.tex", "max_issues_repo_name": "albahnsen/phd-thesis", "max_issues_repo_head_hexsha": "8aedb00cba939b6f8a2f891f453a37206db1f635", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/chapters/chapter06.tex", "max_forks_repo_name": "albahnsen/phd-thesis", "max_forks_repo_head_hexsha": "8aedb00cba939b6f8a2f891f453a37206db1f635", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-01-25T17:16:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-11T13:47:21.000Z", "avg_line_length": 54.8224852071, "max_line_length": 142, "alphanum_fraction": 0.6730706962, "num_tokens": 7221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.3372005300306361}}
{"text": "% This file was converted to LaTeX by Writer2LaTeX ver. 1.4\n% see http://writer2latex.sourceforge.net for more info\n\\documentclass[a4paper]{article}\n%\\usepackage[latin1]{inputenc}\n\\usepackage[T1]{fontenc}\n\\usepackage[english]{babel}\n\\usepackage{amsmath}\n\\usepackage{amssymb,amsfonts,textcomp}\n\\usepackage{color}\n\\usepackage{xcolor,colortbl}\n\\usepackage{sectsty}\n\\usepackage{tocloft}\n\\usepackage{fancyhdr}\n\\usepackage{afterpage}\n\\fancyhf{}\n\\usepackage{lastpage}\n\\usepackage{datetime}\n\\usepackage{colortbl}\n\\usepackage{array}\n%\\usepackage[top=0.7882in,bottom=0.4917in,left=1.25in,right=1.25in,nohead,includefoot,foot=0.5083in,footskip=0.97720003in]{geometry}\n\\usepackage[headheight=110pt]{geometry}\n%\\usepackage{supertabular}\n\\usepackage{hhline}\n\\usepackage{caption}\n\\usepackage{hyperref}\n\n\\usepackage{graphicx}\n\\usepackage{verbatim}\n\\pagestyle{fancy}\n%\\usepackage{titlesec}\n\\afterpage{\\cfoot{\\thepage}}\n\n%new packages & rules\n\\linespread{1.1} % Definition of the linespread\n%\\usepackage[square,sort,comma,numbers]{natbib}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\mathchardef\\mhyphen=\"2D % Define a \"math hyphen\" \n\\usepackage{amsthm}\n\\usepackage{amsmath}\n\\usepackage{amsfonts}\n\\usepackage{amssymb}\n\\usepackage{amsthm}\n\n\n\\usepackage[utf8]{inputenc}\n\\usepackage[english]{babel}\n\\usepackage{amsthm}\n\\theoremstyle{definition}\n\\newtheorem{definition}{Definition}\n\\newtheorem{example}{Example}\n\n\n%\\usepackage{eufrak}\n\\newcommand{\\R}{\\mathbb{R}}\n\\newcommand{\\N}{\\mathbb{N}}\n\\usepackage[ruled,vlined,noend]{algorithm2e}\n\\usepackage{natbib}\n\\usepackage{pgf}\n\\usepackage{tikz}\n\\usetikzlibrary{arrows,automata}\n% to start new page for each new section\n%\\titlespacing*{\\section}\n%{0pt}{6.5ex plus 1ex }{6.3ex plus .2ex}\n%\\titlespacing*{\\subsection}\n%{0pt}{6.5ex plus 1ex }{6.3ex plus .2ex}\n\n%\\allsectionsfont{\\centering}\n\\setlength{\\headsep}{0.2in}\n\n%\\newdateformat{bkdate}{\\twodigit{\\THEDAY}-\\twodigit{\\THEMONTH}-\\twodigit{\\THEYEAR}}\n%\\dmyydate\n\n\n\\definecolor{datacroninner}{rgb}{0.0,0.0,0.5647059}\n\\newcommand{\\datacroncolor}{\\color{datacroninner}}\n\\chapterfont{\\datacroncolor}  % sets colour of chapters\n\\sectionfont{\\datacroncolor}  % sets colour of sections\n\\subsectionfont{\\datacroncolor}  % sets colour of sections\n\\subsubsectionfont{\\datacroncolor}\n\\hypersetup{colorlinks=true, linkcolor=datacroninner, citecolor=datacroninner, filecolor=datacroninner, urlcolor=blue}\n\n\\newcommand{\\documenttitle}{\\ Master Thesis Proposal}\n%\\newcommand{\\horizongeneral}{\\ H2020-ICT-2015 \\dmyydate \\today}\n%\\lhead{\\includegraphics[width=122pt]{figures/datACRONDXYTemplate201512162-img001.png}}\n\\chead{\\documenttitle}\n%\\rhead{\\horizongeneral}\n\\lfoot{}\n\\fancyfoot[C]{Page \\thepage \\hspace{1pt}}\n%\\cfoot{Page \\thepage \\hspace{1pt} of \\pageref{LastPage}}\n\n\\cfoot{Page \\thepage}\n\\rfoot{}\n\n\n%\\makeatletter\n\\newcommand\\arraybslash{\\let\\\\\\@arraycr}\n%\\makeatother\n% Footnote rule\n\\setlength{\\skip\\footins}{0.0469in}\n\\renewcommand\\footnoterule{\\vspace*{-0.0071in}\\setlength\\leftskip{0pt}\\setlength\\rightskip{0pt plus 1fil}\\noindent\\textcolor{black}{\\rule{0.0\\columnwidth}{0.0071in}}\\vspace*{0.0398in}}\n\\setlength\\tabcolsep{1mm}\n\\renewcommand\\arraystretch{1.3}\n\\newcounter{Table}\n\\renewcommand\\theTable{\\arabic{Table}}\n\n\\title{\\documenttitle}\n\\author{Ehab Qadah \\\\\\\\Supervisor:\n\tPD Dr. Michael Mock}\n\\date{\\dmyydate \\today}\n\\begin{document}\n\\pagestyle{fancy}\n\\newcommand{\\sectionbreak}{\n\\clearpage{\\pagestyle{fancy}}}\n\n\\pagenumbering{gobble}\n\n%\\cfttoctitlefont{\\datacroncolor}\n%\n\n%\\title{\\Huge Grant Agreement No: 687591}\n%{\\centering\n%\\par}\n%\\clearpage{\\pagestyle{fancy}}\n%%\\setcounter{page}{1}\n%\\maketitle{\\Huge}\n%%\\centering\n%\\title{\\Large \\textbf{ Predicting patterns of moving objects based\n%\ton contextual information with distributed online learning \\\\ \n%Distributed Online Learning for Forecasting Patterns of Moving Objects Events Streams \\\\\n%Distributed Online Learning for Forecasting Patterns in Event Streams of Moving Objects}}\n%{\\centering\n%\\Large\n%\\par}\n%\\maketitle\n\n%{\\centering\n%\\includegraphics[width=2.5835in,height=0.6634in]{figures/datACRONDXYTemplate201512162-img001.png}\n% \\par}\n\n\n\n\n\n\n%\\begin{flushleft}\n%\\centering\n%\\begin{tabular}{lm{5.83516in}l}\n%\\hline\n%%\\centering\n%\\title{\\documenttitle}\n%\\maketitle\n%\\\\\\hline\n%\\end{tabular}\n%\\end{flushleft}\n\n\n\n\n\n%\\begin{flushleft}\n%\\begin{tabular}{|m{0.25\\textwidth}|m{0.75\\textwidth}|}\n%%\\multicolumn{2}{|m{5.8350596in}|}{Deliverable Form}\\\\\\hline\n%\\rowcolor{datacroninner}\n%{\\bfseries\\color{white}Deliverable Form}& \\\\\\hline\n%Project Reference No. &\n%H2020-ICT-2015 687591\\\\\\hline\n%Deliverable No.  & 8.1\\\\\\hline\n%Relevant Work Package: & WP 8\\\\\\hline\n%Nature: &R\\\\\\hline\n%Dissemination Level: &PU\\\\\\hline\n%Document version: &1.0\\\\\\hline\n%Due Date: &29/02/2016\\\\\\hline\n%Date of latest revision: &16/12/2015\\\\\\hline\n%Completion Date: &~\\\\\\hline\n%Lead partner: &UPRC\\\\\\hline\n%Authors: &\n%George Vouros\\\\\\hline\n%Reviewers: &~\\\\\\hline\n%Document description: &\n%This deliverable documents the main project procedures. These procedures have been presented and agreed at the kickoff\n%\n%meeting chaired by the coordinator.\\\\\\hline\n%Document location: &\n%Desktop/Projects/datACRON/Project/Dels\\\\\\hline\n%\\end{tabular}\n%\\end{flushleft}\n\n%\\clearpage\n\n%\\section*{HISTORY OF CHANGES}\n%\\thispagestyle{empty}\n%\\addcontentsline{toc}{section}{HISTORY OF CHANGES}\n%\\begin{flushleft}\n%\\begin{tabular}{|m{1.10in}|m{1.10in}|m{1.10in}|m{1.10in}|m{1.10in}|}\n%\\hline\n%\\rowcolor{datacroninner}\n%{\\bfseries\\color{white} Version} &{\\bfseries\\color{white} Date} & {\\bfseries\\color{white} Changes} & {\\bfseries\\color{white} Author} & {\\bfseries\\color{white} Remarks}\\\\\\hline\n%~ &~ &~ &~ &~\\\\\\hline\n%\\end{tabular}\n%\\end{flushleft}\n\n%\\clearpage\n\n%\\section*{EXECUTIVE SUMMARY}\n%\\addcontentsline{toc}{section}{EXECUTIVE SUMMARY}\n%%\\clearpage\n\n\n%\\section*{TABLE OF CONTENTS}\n%\\addcontentsline{toc}{section}{TABLE OF CONTENTS}\n%\n%\n%\n%\\setcounter{tocdepth}{3}\n%\\renewcommand\\contentsname{}\n%\\renewcommand{\\cfttoctitlefont}{\\datacroncolor}\n%\\tableofcontents\n%\\section*{TERMS \\& ABBREVIATIONS}\n%\\addcontentsline{toc}{section}{TERMS \\& ABBREVIATIONS}\n%\n%\\section*{LIST OF FIGURES}\n%\\addcontentsline{toc}{section}{LIST OF FIGURES}\n%%\\cftloftitlefont{\\datacroncolor}\n%\\listoffigures\n%\\section*{LIST OF TABLES}\n%\\addcontentsline{toc}{section}{LIST OF TABLES}\n%\n%\\listoftables\n\n\\input{title}\n\\clearpage\n\n\\section*{Abstract}\n\nPredicting full matches of complex patterns from various real-time event streams is an important utility for the decision maker in many application domains such as maritime surveillance, financial services, and sensor networks. Such a utility allows him/her to proactively react to the new situations and enhances the operational decision making. An event stream is an unbounded collection of timely ordered data observations in the form of an attribute tuple that is composed of a value from finite event types along with other categorical and numerical features. For example, in the context of maritime surveillance, patterns prediction over real-time tracking streams of moving vessels is useful to alert maritime operation mangers about suspicious activities (e.g., fast sailing vessels near ports) before they happen, in this scenario, the event stream of a moving vessel consists of spatial-temporal and kinematic information along with the vessel's identification and its trajectory related event types. However, processing real-time streaming data is challenging since data streams are large in nature and continuously keep on coming at a high rate. \n% we describe the design and implementation of a system called% \n\\par To this end, in this thesis, we present an online, distributed and scalable patterns prediction system over massive input event streams. The proposed approach is based on a novel approach that combines the  distributed online prediction protocol \\citep{kamp2014communication} with the event forecasting with Pattern Markov Chain system\\citep{alevizos2017event}, in order to provide an online and large-scale patterns prediction system over distributed real-time event streams. \n\n \\par We leverage an existing online probabilistic forecasting model, which consists of the event forecasting with Pattern Markov Chain~\\citep{alevizos2017event}. This system gives the ability to predicate when a pattern within a stream of events will be fully matched. In addition, we integrate the distributed online synchronization protocol \\citep{kamp2014communication} to provide distributed online learning capabilities between the prediction models in a communication-efficient manner. This protocol enables us to dynamically synchronize the distributed local prediction models of the multiple input event streams.\n \n  In some practical applications the input event streams may belong to different distributions, we propose to divide the input event streams into similar groups, in order to combine the corresponding predictions models to construct a representative global model in each group. The aggregation operation refers to the synchronization operation (e.g., joint average of the local models) in the distributed online learning protocol, which is performed by a central coordinator that constructs and distributes a global prediction model for the input event streams based on the  local models. In addition, we are using one of the modern Big Data frameworks for stream processing i.e., Apache Flink \\footnote{\\url{https://flink.apache.org/}} to implement the proposed system.\n\\par We aim to provide an architecture and implementation of a system for large-scale patterns prediction over multiple input event streams. Our approach exploits the collaborative learning from multiple input streams by combing their associated predication models in a dynamic way. \n \n\\par We will analysis and develop the proposed approach, and evaluate the effectiveness through empirical experiments over synthetic event streams and real-word data streams of moving objects, in particular, events streams related to trajectories of moving vessels, which are provided in the context of the datAcron project\\footnote{\\url{http://www.datacron-project.eu/}}.\n\n%Furthermore, we will try to provide probabilistic guarantees for the new proposed %method by performing theoretical analysis procedures. \n\n\n{\\large\\textbf{\\\\ \\\\ Acknowledgment\\\\\\\\}}\nThis work is supported by the EU H2020 datAcron project (grant agreement No 6875).\n\n{\\large\\textbf{\\\\ Keywords\\\\\\\\}}\nBig Event Data Streams, Stream processing,Large-scale Patterns Prediction, Maritime Surveillance, Apache Flink, Distributed Pattern Markov Chain\\\\\n\n\n\\pagenumbering{arabic}\n\\setcounter{page}{1}\n\\thispagestyle{fancy}\n\\input{introduction}\n\\input{related_work}\n\\input{implementation}\n\\input{experimental_evaluation}\n\\input{work_plan}\n\n%\\input{extra_rources}\n\n\n%{\\centering  \n%\\includegraphics[width=4.972in,height=3.5693in]{figures/datACRONDXYTemplate201512162-img002.png}\n% \\par}\n%\n%\\captionof{figure}{datACRON Overall Architecture }\n%\n%\n%\n%\\begin{flushleft}\n%\\begin{tabular}{m{0.48in}|m{3.29in}|m{1.89in}c|}\n%\\hline\n%\\rowcolor{datacroninner}\n%{\\bfseries\\color{white}lala}&{\\bfseries\\color{white} Bla} &{\\bfseries\\color{white} bla}\\\\\\hline\n%1 &~ &~\\\\\\hline\n%2 &~ &~\\\\\\hline\n%\\end{tabular}\n%\\end{flushleft}\n\n\n\\clearpage\n%\\nocite{*}\n%\\bibliographystyle{plain-annote}\n%\\bibliographystyle{plainnat}\n \\bibliographystyle{agsm} \n\\bibliography{myrefs}\n\\end{document}\n\n\n\n", "meta": {"hexsha": "372cb13505b6a4d791da32b56dd4673c0b889609", "size": 11336, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "presentation2/expose.tex", "max_stars_repo_name": "wsgan001/thesis-8", "max_stars_repo_head_hexsha": "6131d734f4cc48746575221370669da14de5024b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-09-25T22:44:18.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-25T22:44:18.000Z", "max_issues_repo_path": "presentation2/expose.tex", "max_issues_repo_name": "wsgan001/thesis-8", "max_issues_repo_head_hexsha": "6131d734f4cc48746575221370669da14de5024b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "presentation2/expose.tex", "max_forks_repo_name": "wsgan001/thesis-8", "max_forks_repo_head_hexsha": "6131d734f4cc48746575221370669da14de5024b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-09-25T22:44:17.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-25T22:44:17.000Z", "avg_line_length": 38.0402684564, "max_line_length": 1158, "alphanum_fraction": 0.7786697248, "num_tokens": 3196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.3372005228800169}}
{"text": "\\section*{New Clock Stability Application}\n\n\\gpstkapp{Clock Tools}, a recent addition to the GPSTk, allows for\nbasic clock stability analyses.  \\gpstkapp{Clock Tools} implement\nclock time-domain frequency stability metrics as well as data editing,\nnoise identification, and plotting routines.  The \\gpstkapp{Clock\n  Tools} are interoperable with other GPSTk programs, allowing clock\nanalyses to be easily run alongside other GPS analyses.\n\nGiven RINEX GPS observation and navigation files, clock estimates may\nbe generated using the GPSTk \\gpstkapp{Observed Range Deviation (ORD) Tools}.\nKalman filter and time interval analyzer data-sets provide another\nsource of clock data.  For instance, the TSC 5110A Time Interval\nAnalyzer (TIA) compares two input clocks and outputs the phase\ndifference between them at a 10- to 100-Hz sampling rate.  These clock\nestimates are used for time-domain frequency stability analysis.\n\nFrequency stability measures the ability of a clock to maintain its nominal frequency over a given period of time.  From input clock data, both short-term and long-term stability can be assessed.  The Allan variance represents the variance of a clock from its nominal value over a range of averaging times.  The Allan variance is an IEEE standard for stability analysis~\\cite{ieee1139}.  An Allan variance plot is often helpful in stability analysis.\n\nThe \\gpstkapp{Clock Tools} suite currently computes the Allan, overlapping Allan, modified Allan, total Allan, overlapping Hadamard, and dynamic Allan deviation stability metrics.  These \\gpstkapp{Clock Tools} may be run from the command line with their output piped to other GPSTk programs.  Data formatting and outlier removal routines for GPS and time interval analyzer data-sets facilitate compatibility with the \\gpstkapp{Clock Tools} stability programs.\n\n\\subsection*{Design}\n\nThe \\gpstkapp{Clock Tools} applications are encapsulated, so that the output of\none tool acts as the input to the next.  By using redirection and\npiping the user is able to connect the \\gpstkapp{Clock Tools} together in a way\nthat allows for flexibility in analysis and ease of use.\n\nRoutines within the \\gpstkapp{Clock Tools} suite fall into four functional categories: input parsing, data grooming, data analysis, and plotting.  Input parsing takes data generated outside of \\gpstkapp{Clock Tools} and puts it in a format understood within the suite.  Data grooming cleans the data of outliers before analysis.  Data analysis performs the frequency stability calculations.  Plotting creates a graphical representation of the frequency stability.\n\n\\subsection*{Implementation}\n\nAs mentioned, \\gpstkapp{Clock Tools} has four functional categories: input\nparsing, data grooming, data analysis, and plotting.\nTable~\\ref{table:clockapps} presents a description and example use of\neach tool.  Note that \\gpstkapp{ordClock} makes an estimate of the receiver’s\nclock offset by averaging the ORDs of all the GPS satellites at each\nepoch.  An epoch is an instant in time in which GPS data is recorded.\n%\n\\begin{table*}\n\\centering\n\\caption{Description and example invocations of \\gpstkapp{Clock Tools}.}\n\\label{table:clockapps}\n\\begin{tabular}{lll} \\hline \\hline\n\\emph{Tool} & \\emph{Description} & \\emph{Example} \\\\ \\hline\n\\gpstkapp{ORDPhaseParser} & Parses data generated by the \\gpstkapp{ORD Tools} & \\gpstkcommand{ordGen –o input.o –e input.n | } \\\\ \n & &\\gpstkcommand{ordClock|ORDPhaseParser>parsed.dat} \\\\ \\hline\n\\gpstkapp{TIAPhaseParser} & Parses data generated by the & \\gpstkcommand{TIAPhaseParser < raw.dat > parsed.dat} \\\\ \n   &  TSC 5110A Timing Interval Analyzer. & \\\\ \\hline \n\\gpstkapp{rmoutlier} & Removes outlier data within a set of  data. & \\gpstkcommand{rmoutlier < parsed.dat} \\\\ \\hline \n\\gpstkapp{nallandev} & Computes the Allan deviation. & \\gpstkcommand{nallandev < parsed.dat} \\\\ \\hline \n\\gpstkapp{oallandev} & Computes the overlapping Allan deviation. & \\gpstkcommand{oallandev < parsed.dat} \\\\ \\hline \n\\gpstkapp{mallandev} & Computes the modified Allan deviation. & \\gpstkcommand{mallandev < parsed.dat} \\\\ \\hline \n\\gpstkapp{totvar} & Computes the total Allan deviation. & \\gpstkcommand{totvar < parsed.dat} \\\\ \\hline \n\\gpstkapp{ohadamarddev} & Computes the overlapping Hadamard & \\gpstkcommand{ohadamarddev < parsed.dat} \\\\\n& deviation. & \\\\ \\hline\n\\gpstkapp{dallandev} & Computes the dynamic Allan deviation. & \\gpstkcommand{dallandev < parsed.dat} \\\\ \\hline \n\\gpstkapp{allanplot} & Plots the output of \\gpstkapp{nallandev}, \\gpstkapp{oallandev}, & \\gpstkcommand{nallandev < parsed.dat | allanplot} \\\\ \n& \\gpstkapp{ohadamarddev}, \\gpstkapp{totvar}, and \\gpstkapp{mallandev}. & \\\\ \\hline \n\\gpstkapp{ddevplot.m} & Plots the output of dallandev. & \\gpstkcommand{octave ddevplot.m} \\\\ \\hline \\hline\n\\end{tabular}\n\\end{table*}\n%\nThe input parsers are the classes \\gpstkapp{ORDPhaseParser} and\n\\gpstkapp{TIAPhaseParser}.  The data grooming tool is\n\\gpstkapp{rmoutlier}.  The data analysis tools are\n\\gpstkapp{nallandev}, \\gpstkapp{oallandev}, \\gpstkapp{mallandev},\n\\gpstkapp{totvar}, \\gpstkapp{ohadamarddev}, and \\gpstkapp{dallandev}.\nThe plotting scripts are \\gpstkapp{allanplot} and\n\\gpstkapp{ddevplot.m}.  Data flows from the parsers to data grooming\nto data analysis and finally to plotting.\n\n\\subsection*{Example Usage and Plots}\n\nTwo example command lines are given below.  The first command\ngenerates clock estimates using the GPSTk ORD tools (\\gpstkapp{ordGen} and\n\\gpstkapp{ordClock}), parses the data (\\gpstkapp{ORDPhaseParser}), then removes outliers\n(\\gpstkapp{rmoutlier}), computes the overlapping Allan deviation (\\gpstkapp{oallandev}), and\nfinally writes the data to a file (\\gpstkcommand{output.oadev}).  The second example\ntakes data in from a file produced by the Timing Interval Analyzer\n(\\gpstkcommand{raw.dat}), parses the data (\\gpstkapp{TIAPhaseParser)}, computes the overlapping\nHadamard variance (\\gpstkcommand{ohadamard}), and plots the output (\\gpstkcommand{allanplot}).\n%\n\\begin{scriptsize}\n\\begin{lstlisting}\nordGen –o input.o –e input.n | ordClock \n| ORDPhaseParser | rmoutlier | \noallandev > output.oadev\n\nraw.dat | TIAPhaseParser | \nohadamard | allanplot\n\\end{lstlisting}\n\\end{scriptsize}\n%\nAnother example is shown below.  This example is an analysis performed on a reference station that is part of the NGA GPS Monitor Station Network (MSN).\n\nThis analysis compares the results of running an overlapping Allan\ndeviation calculation on data generated by \\gpstkapp{ordClock} from\nunsmoothed raw RINEX files versus data output by the NGA Kalman\nfilter. The \\gpstkapp{ordClock} and Kalman filter data sets cover\ndifferent time periods, but both data sets are good representatives of\nnominal MSN data. The overlapping Allan deviation of the \\gpstkapp{ordClock}\ngenerated data is represented by the blue line.  The overlapping Allan\ndeviation of the Kalman filter generated data is represented by the\ngreen line.  The lighter slanted red line shows the 5071A CFS\ntime-domain stability specification.  The darker red line along the\nbottom represents the cesium’s flicker floor.  Note that drift removal\nmay be necessary depending on the input dataset and the deviation\ncomputation performed.\n%\n\\begin{figure*}\n  \\centering\n  \\includegraphics[width=5in,bb=65 387 547 727]{clockapps.eps}\n  \\caption{Frequency Stability of \\gpstkapp{ordClock} and Kalman Filter Data}\n  \\label{fig:clockapps}\n\\end{figure*}\n%\nFigure~\\ref{fig:clockapps} shows that the frequency stability of the\nclock estimates generated by the Kalman filter lies within the CFS\nspecifications, but that the frequency stability of the output\ngenerated by \\gpstkapp{ordClock} from the raw data does not.  Using\nraw GPS data and \\gpstkapp{ordClock} a stability trend is apparent,\nbut further filtering and smoothing of the data is necessary to get\nmore accurate clock stability estimates.\n", "meta": {"hexsha": "52eddde795239bfbc276193e7263aaa8611cb5d3", "size": 7842, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "3rdparty/GPSTk/ref/papers/ion-gnss-2009/appsclock.tex", "max_stars_repo_name": "mfkiwl/ICE", "max_stars_repo_head_hexsha": "e660d031bb1bcea664db1de4946fd8781be5b627", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50, "max_stars_repo_stars_event_min_datetime": "2019-10-12T01:22:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T23:28:26.000Z", "max_issues_repo_path": "3rdparty/GPSTk/ref/papers/ion-gnss-2009/appsclock.tex", "max_issues_repo_name": "wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation", "max_issues_repo_head_hexsha": "2f1ff054b7c5059da80bb3b2f80c05861a02cc36", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3rdparty/GPSTk/ref/papers/ion-gnss-2009/appsclock.tex", "max_forks_repo_name": "wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation", "max_forks_repo_head_hexsha": "2f1ff054b7c5059da80bb3b2f80c05861a02cc36", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2019-11-05T01:50:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T06:23:44.000Z", "avg_line_length": 62.736, "max_line_length": 463, "alphanum_fraction": 0.7871716399, "num_tokens": 2063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583270090337582, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.3371914543844873}}
{"text": "\\chapter{Introduction}\n\nThe constraints, that we are talking about here, are not like the constraints in classical mechanics. They appear when we try to get from the Lagrange to the Hamilton formalism. \n\\begin{itemize}\n\\item $L(q_i,\\dot{q}_i)$, \\ where $i = 1, ..., n$ degrees of freedom \\\\\nThe mechanical properties of a system are completly described by the Lagrangian. \n\\end{itemize}\nWe will study constraints from a mathematical point of view, not a physical:\n\\begin{itemize}\n\\item Classical mechanics: physical constraints lead to changes in the mathematical description.\n\\item Now: most general description of Hamiltonian theory. The constraints will follow from the Lagrangian.\n\\end{itemize}\n\nWhy do we need the Hamilton formalism? \\\\\nThe most important fact is that a Hamiltonian system (described by coordinates $q_i$ and momenta $p_i$) can be quantized in a canonical way:\n\\begin{align}\nL(q_i,\\dot{q}_i) \\ \\longrightarrow \\ H(q_i,p_i) \\ \\longrightarrow \\ H(\\hat{q}_i,\\hat{p}_i) .\n\\end{align}\nNowadays, there are of course other methods of quantization, like the Feynman path integral, but we won't focus on quantization here. For us, it is important to know what happens when we try to get from the Lagrangian to the Hamiltonian. \\\\\n\nHow does it work?\n\\begin{enumerate}\n\\item Calculate the generalized momenta\n\\begin{align}\\label{eq:momentum}\nq_i \\ \\longrightarrow \\ p_i \\equiv \\frac{\\partial L(q_i,\\dot{q}_i)}{\\partial \\dot{q}_i}.\n\\end{align}\nThis step is always possible, it results in $p_i(q_i,\\dot{q}_i)$.\n\\item Build the Hamiltonian\n\\begin{align}\\label{eq:hamilton}\nH(q_i,p_i) = \\sum_{i = 1}^n p_i \\dot{q}_i - L(q_i,\\dot{q}_i).\n\\end{align}\nThe expression on the right side still contains the velocities $\\dot{q}_i$, so we have to express them through the generalized coordinates and momenta, by inverting \\eqref{eq:momentum}\n\\begin{align}\np_i(q_i,\\dot{q}_i) \\longrightarrow \\dot{q}_i = \\dot{q}_i(q_i,p_i),\n\\end{align}\nand insert in the equation \\eqref{eq:hamilton}. Sometimes (if the Lagrangian is degenerate), this step is not possible. We will investigate, what to do in this cases.\n\\end{enumerate} \n\nWe will start with discrete and finite dimensional systems and then move on to continuous systems by introducing field theoretical aspects.", "meta": {"hexsha": "31014499a2e8a3fdc305c86565609c856a813eeb", "size": 2257, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "02_introduction.tex", "max_stars_repo_name": "Spektralzerleger/Hamilton-Systems", "max_stars_repo_head_hexsha": "53ba6a624bda7a6e03acdecbd48d43f79e221823", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-11T22:55:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-11T22:55:50.000Z", "max_issues_repo_path": "02_introduction.tex", "max_issues_repo_name": "Spektralzerleger/Hamilton-Systems", "max_issues_repo_head_hexsha": "53ba6a624bda7a6e03acdecbd48d43f79e221823", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "02_introduction.tex", "max_forks_repo_name": "Spektralzerleger/Hamilton-Systems", "max_forks_repo_head_hexsha": "53ba6a624bda7a6e03acdecbd48d43f79e221823", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 57.8717948718, "max_line_length": 240, "alphanum_fraction": 0.7589720868, "num_tokens": 621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.3371914455076655}}
{"text": "\\documentclass[preprint]{sigplanconf}\n\n\\usepackage{graphicx}\n\\usepackage{comment}\n\\usepackage{amsmath}\n\\usepackage{xspace}\n\\usepackage{amssymb}\n\\usepackage{stmaryrd}\n\\usepackage{proof}\n\\usepackage{multicol}\n\\usepackage[nodayofweek]{datetime}\n\\usepackage{etex}\n\\usepackage[all, cmtip]{xy}\n\\usepackage{xcolor}\n\\usepackage{listings}\n\\usepackage{multicol}\n\\newcommand\\hmmax{0} % default \\newcommand\\bmmax{0} % default 4\n\\usepackage{bm}\n\\usepackage{cmll}\n\n\\newcommand{\\fname}[1]{\\ulcorner #1 \\urcorner}\n\\newcommand{\\fconame}[1]{\\llcorner #1 \\lrcorner}\n\n\\newcommand{\\xcomment}[2]{\\textbf{#1:~\\textsl{#2}}}\n\\newcommand{\\amr}[1]{\\xcomment{Amr}{#1}}\n\\newcommand{\\roshan}[1]{\\xcomment{Roshan}{#1}}\n\n\\newcommand{\\asterix}[0]{*}\n\n\\newcommand{\\ie}{\\textit{i.e.}\\xspace}\n\\newcommand{\\eg}{\\textit{e.g.}\\xspace}\n\n\\newcommand{\\lcal}{\\ensuremath{\\lambda}-calculus\\xspace}\n\\newcommand{\\G}{\\ensuremath{\\mathcal{G}}\\xspace}\n\n\\newcommand{\\code}[1]{\\lstinline[basicstyle=\\small]{#1}\\xspace}\n\\newcommand{\\name}[1]{\\code{#1}}\n\n\\def\\newblock{}\n\n\\newenvironment{floatrule}\n    {\\hrule width \\hsize height .33pt \\vspace{.5pc}}\n    {\\par\\addvspace{.5pc}}\n\n\\newtheorem{theorem}{Theorem}[section]\n\\newtheorem{lemma}[theorem]{Lemma}\n\\newtheorem{definition}[theorem]{Definition}\n\\newtheorem{proposition}[theorem]{Proposition}\n\\newenvironment{proof}[1][Proof.]{\\begin{trivlist}\\item[\\hskip \\labelsep {\\bfseries #1}]}{\\end{trivlist}}\n\n\\newcommand{\\arrow}[1]{\\mathtt{#1}}\n\n\\newcommand{\\dgm}[2][0.95]{\n\\begin{center}\n\\scalebox{#1}{\n\\includegraphics{diagrams/#2.pdf}\n}\n\\end{center}\n}\n\n%subcode-inline{bnf-inline} name langRev\n%! swap+ = \\mathit{swap}^+\n%! swap* = \\mathit{swap}^*\n%! dagger =  ^{\\dagger}\n%! assocl+ = \\mathit{assocl}^+\n%! assocr+ = \\mathit{assocr}^+\n%! assocl* = \\mathit{assocl}^*\n%! assocr* = \\mathit{assocr}^*\n%! identr* = \\mathit{uniti}\n%! identl* = \\mathit{unite}\n%! dist = \\mathit{distrib}\n%! factor = \\mathit{factor}\n%! eta = \\eta\n%! eps = \\epsilon\n%! eta+ = \\eta^+\n%! eps+ = \\epsilon^+\n%! eta* = \\eta^{\\times}\n%! eps* = \\epsilon^{\\times}\n%! trace+ = trace^+\n%! trace* = trace^{\\times}\n%! ^^^ = ^{-1}\n%! (o) = \\circ\n%! (;) = \\fatsemi\n%! (*) = \\times\n%! (+) = +\n%! LeftP = L^+\n%! RightP = R^+\n%! LeftT = L^{\\times}\n%! RightT = R^{\\times}\n%! alpha = \\alpha\n%! bool = \\textit{bool}\n%! color = \\textit{color}\n%! Gr = G\n\n%subcode-inline{bnf-inline} regex \\{\\{(((\\}[^\\}])|[^\\}])*)\\}\\} name main include langRev\n%! Gx = \\Gamma^{\\times}\n%! G = \\Gamma\n%! [] = \\Box\n%! |-->* = \\mapsto^{\\asterix}\n%! |-->> = \\mapsto_{\\ggg}\n%! |--> = \\mapsto\n%! <--| = \\mapsfrom\n%! |- = \\vdash\n%! <><> = \\approx\n%! ==> = \\Longrightarrow\n%! <== = \\Longleftarrow\n%! <=> = \\Longleftrightarrow\n%! <-> = \\leftrightarrow\n%! ~> = \\leadsto\n%! -o+ = \\multimap^{+}\n%! -o* = \\multimap^{\\times}\n%! -o = \\multimap\n%! ::= = &::=&\n%! /= = \\neq\n%! @@ = \\mu\n%! [^ = \\lceil\n%! ^] = \\rceil\n%! forall = \\forall\n%! exists = \\exists\n%! empty = \\epsilon\n%! Pi = \\Pi\n%! Pi0 = \\Pi^{o}\n%! PiEE* = \\Pi^{\\eta\\epsilon}_{*}\n%! PiEE+ = \\Pi^{\\eta\\epsilon}_{+}\n%! PiEE = \\Pi^{\\eta\\epsilon}\n%! CatSet = \\textbf{Set}\n%! theseus = Theseus\n%! sqrt(x) = \\sqrt{#x}\n%! surd(p,x) = \\sqrt[#p]{#x}\n%! inv(x) = \\frac{1}{#x}\n%! frac(x,y) = \\frac{#x}{#y}\n%! * = \\times\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{document}\n\n\\conferenceinfo{POPL'13}{}\n\\CopyrightYear{}\n\\copyrightdata{}\n\\titlebanner{}\n\\preprintfooter{}\n\n\\title{Fractional Types} \n\n\\authorinfo{*}{*}{*}\n\\maketitle\n\n\\begin{abstract}\n\n\\end{abstract}\n\n\\category{D.3.1}{Formal Definitions and Theory}{}\n\\category{F.3.2}{Semantics of Programming Languages}{}\n\\category{F.3.3}{Studies of Program Constructs}{Type structure}\n\n\\terms\nLanguages, Theory\n\n\\keywords continuations, information flow, linear logic, logic programming,\nquantum computing, reversible logic, symmetric monoidal categories, compact\nclosed categories.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{The Game}\n\nWe start with a type {{A}} and build terms of the types {{A}}, {{Id_A}},\n{{Id_{Id_a} }}, etc.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Level of Atoms}\n\nWe start with the kind {{type}} and terms of kind {{type}}:\n\n%subcode{bnf} include main\n% kinds, k ::= type\n% value types, b ::= 0 | 1 | b + b | b * b \n\n%subcode{proof} include main\n%@  ~\n%@@ 0 : type\n%\n%@  ~\n%@@ 1 : type\n%\n%@  b1 : type\n%@  b2 : type\n%@@ b1 + b2 : type\n%\n%@  b1 : type\n%@  b2 : type\n%@@ b1 * b2 : type\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{ {{Pi}} Combinators}\n\nNow we introduce isomorphisms between terms of kind {{type}}. This is where\nthe {{Pi}} combinators appear.\n\n%subcode{bnf} include main\n% kinds, k ::= type\n% value types, b ::= 0 | 1 | b + b | b * b \n% \n% identity types, t0 ::= Id_k(b1,b2)\n% iso ::= zeroe | zeroi \n%     &|& swap+ | assocl+ | assocr+ \n%     &|& identl* | identr* \n%     &|& swap* | assocl* | assocr* \n%     &|& dist | factor \n% comb., c ::= iso | id | sym c | c (;) c | c (+) c | c (*) c \n\n%subcode{proof} include main\n%@  b : k\n%@@ zeroe : Id_k(0+b,b)\n%\n%@  b : k\n%@@ zeroi : Id_k(b,0+b)\n%---\n%@  b1 : k\n%@  b2 : k\n%@@ swap+ : Id_k(b1+b2,b2+b1)\n%---\n%@  b1 : k\n%@  b2 : k\n%@  b3 : k\n%@@ assocl+ : Id_k(b1+(b2+b3),(b1+b2)+b3)\n%---\n%@  b1 : k\n%@  b2 : k\n%@  b3 : k\n%@@ assocr+ : Id_k((b1+b2)+b3,b1+(b2+b3))\n%---\n%@  b : k\n%@@ unite : Id_k(1 * b, b)\n%\n%@  b : k\n%@@ uniti : Id_k(b, 1 * b)\n%---\n%@  b1 : k\n%@  b2 : k\n%@@ swap* : Id_k(b1 * b2,b2 * b1)\n%---\n%@  b1 : k\n%@  b2 : k\n%@  b3 : k\n%@@ assocl* : Id_k(b1*(b2*b3),(b1*b2)*b3)\n%---\n%@  b1 : k\n%@  b2 : k\n%@  b3 : k\n%@@ assocr* : Id_k((b1*b2)*b3,b1*(b2*b3))\n%---\n%@  b1 : k\n%@  b2 : k\n%@  b3 : k\n%@@ distrib : Id_k((b1+b2)*b3,(b1*b3)+(b2*b3))\n%---\n%@  b1 : k\n%@  b2 : k\n%@  b3 : k\n%@@ factor : Id_k((b1*b3)+(b2*b3),(b1+b2)*b3)\n%---\n%@ b : k\n%@@ id : Id_k(b,b)\n%\n%@ c : Id_k(b1,b2)\n%@@ sym c : Id_k(b2,b1)\n%---\n%@ c1 : Id_k(b1,b2)\n%@ c2 : Id_k(b2,b3)\n%@@ c1(;)c2 : Id_k(b1,b3)\n%---\n%@ c1 : Id_k(b1,b3)\n%@ c2 : Id_k(b2,b4)\n%@@ c1(+)c2 : Id_k(b1+b2,b3+b4)\n%---\n%@ c1 : Id_k(b1,b3)\n%@ c2 : Id_k(b2,b4)\n%@@ c1(*)c2 : Id_k(b1*b2,b3*b4)\n\nWe will give the semantics in an usual style to simplify the presentation of\nnext section. First we define values and clauses:\n\n%subcode{bnf} include main\n% values, v ::= () | left v | right v | (v,v)\n% clauses, m ::= (1/v,v) \n\n%subcode{proof} include main\n%@  ~\n%@@ () : 1\n%\n%@  v : b1\n%@@ left v : b1 + b2\n%\n%@  v : b2\n%@@ right v : b1 + b2\n%---\n%@  v1 : b1\n%@  v2 : b2\n%@@ (v1,v2) : b1 * b2\n\nThe intuition behind clauses is the following: if applying \n{{c : Id_k(b1,b2)}} to {{v1 : b1}} yields {{v2 : b2}}, we say that \nthe clause {{ (1/v1, v2) }} has type {{c}}. \n\n%subcode{proof} include main\n%@ zeroe : Id_k(0+b,b)\n%@ v : b\n%@@ (1/right v, v) : zeroe\n% \n%@ zeroi : Id_k(b,0+b)\n%@ v : b\n%@@ (1/v, right v) : zeroi\n%---\n%@ swap+ : Id_k(b1+b2,b2+b1)\n%@ v : b1\n%@@ (1/left v, right v) : swap+\n%---\n%@ swap+ : Id_k(b1+b2,b2+b1)\n%@ v : b2\n%@@ (1/right v, left v) : swap+\n%---\n%@ assocl+ : Id_k(b1+(b2+b3),(b1+b2)+b3)\n%@ v : b1\n%@@ (1/ left v, left (left v)) : assocl+\n%---\n%@ assocl+ : Id_k(b1+(b2+b3),(b1+b2)+b3)\n%@ v : b2\n%@@ (1/ right (left v), left (right v)) : assocl+\n%---\n%@ assocl+ : Id_k(b1+(b2+b3),(b1+b2)+b3)\n%@ v : b3\n%@@ (1/ right (right v), right v) : assocl+\n%---\n%@ assocr+ : Id_k((b1+b2)+b3,b1+(b2+b3))\n%@ v : b1\n%@@ (1/ left (left v), left v) : assocr+\n%---\n%@ assocr+ : Id_k((b1+b2)+b3,b1+(b2+b3))\n%@ v : b2\n%@@ (1/ left (right v), right (left v)) : assocr+\n%---\n%@ assocr+ : Id_k((b1+b2)+b3,b1+(b2+b3))\n%@ v : b3\n%@@ (1/ right v, right (right v)) : assocr+\n%---\n%@ unite : Id_k(1 * b, b)\n%@ v : b\n%@@ (1/((),v), v) : unite\n% \n%@ uniti : Id_k(b, 1 * b)\n%@ v : b\n%@@ (1/v, ((),v)) : uniti\n%---\n%@ swap* : Id_k(b1 * b2,b2 * b1)\n%@ v1 : b1\n%@ v2 : b2\n%@@ (1/(v1,v2), (v2,v1)) : swap*\n%---\n%@ assocl* : Id_k(b1*(b2*b3),(b1*b2)*b3)\n%@ v1 : b1\n%@ v2 : b2\n%@ v3 : b3\n%@@ (1/(v1,(v2,v3)), ((v1,v2),v3)) : assocl*\n%---\n%@ assocr* : Id_k((b1*b2)*b3,b1*(b2*b3))\n%@ v1 : b1\n%@ v2 : b2\n%@ v3 : b3\n%@@ (1/((v1,v2),v3), (v1,(v2,v3))) : assocr*\n%---\n%@ distrib : Id_k((b1+b2)*b3,(b1*b3)+(b2*b3))\n%@ v1 : b1\n%@ v3 : b3\n%@@ (1/(left v1,v3), left (v1,v3)) : distrib\n%---\n%@ distrib : Id_k((b1+b2)*b3,(b1*b3)+(b2*b3))\n%@ v2 : b2\n%@ v3 : b3\n%@@ (1/(right v2,v3), right (v2,v3)) : distrib\n%---\n%@ factor : Id_k((b1*b3)+(b2*b3),(b1+b2)*b3)\n%@ v1 : b1\n%@ v3 : b3\n%@@ (1/(left (v1,v3)), (left v1,v3)) : factor\n%---\n%@ factor : Id_k((b1*b3)+(b2*b3),(b1+b2)*b3)\n%@ v2 : b2\n%@ v3 : b3\n%@@ (1/(right (v2,v3)), (right v2,v3)) : factor\n%---\n%@ id : Id_k(b,b)\n%@ v : b\n%@@ (1/v,v) : id\n%\n%@ c : Id_k(b2,b1)\n%@ (1/v2, v1) : c\n%@@ (1/v1, v2) : sym c\n%---\n%@ c1 : Id_k(b1,b2)\n%@ c2 : Id_k(b2,b3)\n%@ (1/v1, v2) : c1\n%@ (1/v2, v3) : c2\n%@@ (1/v1, v3) : c1 (;) c2\n%---\n%@ c1 : Id_k(b1,b3)\n%@ (1/v1, v3) :: c1\n%@@ (1/left v1, left v3) : c1 (+) c2\n%\n%@ c2 : Id_k(b2,b4)\n%@ (1/v2, v4) :: c2\n%@@ (1/right v2, right v4) : c1 (+) c2\n%---\n%@ c1 : Id_k(b1,b3)\n%@ c2 : Id_k(b2,b4)\n%@ (1/v1, v3) :: c1\n%@ (1/v2, v4) :: c2\n%@@ (1/(v1,v2), (v3,v4)) : c1 (*) c2\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{ {{Pi}} semantics I}\n\nNow we introduce isomoprhisms between terms of type {{Id_k(b1,b2)}}. This is\nwhere we start reasoning about equivalence of the {{Pi}}-combinators\nthemselves. For {{c1 : Id_k(b1,b2)}} and {{c2 : Id_k(b1,b2)}}, terms of type\n{{Id_{Id_k(b1,b2)}(c1,c2)}} would witness that {{c1}} and {{c2}} are\nisomorphic (up to equivalence at the next level). \n\nFor example, given the combinator {{uniti}} at type {{bool = 1+1}}:\n\n%subcode{proof} include main\n%@ uniti : Id_k(1+1, 1 * (1+1))\n%@ v : 1+1\n%@@ (1/v, ((),v)) : uniti\n\nwhen viewed as a type, the elements of {{uniti}} are:\n{{ (1/left (), ((), left ())) }}\nand \n{{ (1/right (), ((), right ())) }}\n\nUsing our isomorphisms we can apply {{ id (*) unite }} to the above to\nproduce\n{{ (1/left (), left ()) }}\nand \n{{ (1/right (), right ()) }}.\n\nIn other words, there is an isomorphism {{alpha = id (*) unite}} beween\n{{uniti}} and {{id}} at type {{bool}}. We now need to generalize this idea to\nthe full language. We possibly (probably) need to add the meadow rules so\nthat we can convert a clause to a regular value, use the isomorphisms on it,\nand then translate it back to a clause.\n\n%subcode{bnf} include main\n% kinds, k ::= type\n% value types, b ::= 0 | 1 | b + b | b * b \n%\n% identity types, t0 ::= Id_k(b1,b2) \n% iso ::= zeroe | zeroi \n%     &|& swap+ | assocl+ | assocr+ \n%     &|& identl* | identr* \n%     &|& swap* | assocl* | assocr* \n%     &|& dist | factor \n% comb., c ::= iso | id | sym c | c (;) c | c (+) c | c (*) c \n%\n% identity types, t1 ::= Id_{t0}(c1,c2)\n% alpha ::= ...\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\end{document}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n", "meta": {"hexsha": "cf5b9afffe274e97f7d7dcebeaa285daccb9acf6", "size": 10854, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "popl13/outline.tex", "max_stars_repo_name": "JacquesCarette/pi-dual", "max_stars_repo_head_hexsha": "003835484facfde0b770bc2b3d781b42b76184c1", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2015-08-18T21:40:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T01:07:57.000Z", "max_issues_repo_path": "popl13/outline.tex", "max_issues_repo_name": "JacquesCarette/pi-dual", "max_issues_repo_head_hexsha": "003835484facfde0b770bc2b3d781b42b76184c1", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-06-07T16:27:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-29T20:41:23.000Z", "max_forks_repo_path": "popl13/outline.tex", "max_forks_repo_name": "JacquesCarette/pi-dual", "max_forks_repo_head_hexsha": "003835484facfde0b770bc2b3d781b42b76184c1", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-05-29T01:56:33.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-10T09:47:13.000Z", "avg_line_length": 22.9957627119, "max_line_length": 105, "alphanum_fraction": 0.5190713101, "num_tokens": 4347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.3371914455076655}}
{"text": "\\XtoCBlock{Sqrt}\r\n\\label{block:Sqrt}\r\n\\begin{figure}[H]\\includegraphics{Sqrt}\\end{figure} \r\n\r\n\\begin{XtoCtabular}{Inports}\r\nIn & Input u\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n\r\n\\begin{XtoCtabular}{Outports}\r\nOut & Result of sqrt(|u|)\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n\\subsubsection*{Description:}\r\nSquare root computation of absolute input value.\r\n\n% include optional documentation file\r\n\\InputIfFileExists{\\XcHomePath/Library/Math/Doc/Sqrt_Info.tex}{\\vspace{1ex}}{}\r\n\r\n\\subsubsection*{Implementations:}\r\n\\begin{tabular}{l l}\r\n\\textbf{FiP8} & 8 Bit Fixed Point Implementation\\tabularnewline\r\n\\textbf{FiP16} & 16 Bit Fixed Point Implementation\\tabularnewline\r\n\\textbf{FiP32} & 32 Bit Fixed Point Implementation\\tabularnewline\r\n\\textbf{Float32} & 32 Bit Floating Point Implementation\\tabularnewline\r\n\\textbf{Float64} & 64 Bit Floating Point Implementation\\tabularnewline\r\n\\end{tabular}\r\n\r\n\\XtoCImplementation{FiP8}\r\n\\index{Block ID!4816}\r\n\\nopagebreak[0]\r\n% Implementation details\r\n\\begin{tabular}{l l}\r\n\\textbf{Name} & FiP8 \\tabularnewline\r\n\\textbf{ID} & 4816 \\tabularnewline\r\n\\textbf{Revision} & 0.1 \\tabularnewline\r\n\\textbf{C filename} & Sqrt\\_FiP8.c \\tabularnewline\r\n\\textbf{H filename} & Sqrt\\_FiP8.h \\tabularnewline\r\n\\end{tabular}\r\n\\vspace{1ex}\r\n\r\n8 Bit Fixed Point Implementation\r\n\r\n% Implementation data structure\r\n\\XtoCDataStruct{Data Structure:}\r\n\\begin{lstlisting}\r\ntypedef struct {\r\n     uint16        ID;\r\n     int8          *In;\r\n     int8          Out;\r\n} SQRT_FIP8;\r\n\\end{lstlisting}\r\n\r\n\\ifdefined \\AddTestReports\r\n\\InputIfFileExists{\\XcHomePath/Library/Math/Doc/Test_Sqrt_FiP8.tex}{}{}\r\n\\fi\r\n\\XtoCImplementation{FiP16}\r\n\\index{Block ID!4817}\r\n\\nopagebreak[0]\r\n% Implementation details\r\n\\begin{tabular}{l l}\r\n\\textbf{Name} & FiP16 \\tabularnewline\r\n\\textbf{ID} & 4817 \\tabularnewline\r\n\\textbf{Revision} & 0.1 \\tabularnewline\r\n\\textbf{C filename} & Sqrt\\_FiP16.c \\tabularnewline\r\n\\textbf{H filename} & Sqrt\\_FiP16.h \\tabularnewline\r\n\\end{tabular}\r\n\\vspace{1ex}\r\n\r\n16 Bit Fixed Point Implementation\r\n\r\n% Implementation data structure\r\n\\XtoCDataStruct{Data Structure:}\r\n\\begin{lstlisting}\r\ntypedef struct {\r\n     uint16        ID;\r\n     int16         *In;\r\n     int16         Out;\r\n} SQRT_FIP16;\r\n\\end{lstlisting}\r\n\r\n\\ifdefined \\AddTestReports\r\n\\InputIfFileExists{\\XcHomePath/Library/Math/Doc/Test_Sqrt_FiP16.tex}{}{}\r\n\\fi\r\n\\XtoCImplementation{FiP32}\r\n\\index{Block ID!4818}\r\n\\nopagebreak[0]\r\n% Implementation details\r\n\\begin{tabular}{l l}\r\n\\textbf{Name} & FiP32 \\tabularnewline\r\n\\textbf{ID} & 4818 \\tabularnewline\r\n\\textbf{Revision} & 0.1 \\tabularnewline\r\n\\textbf{C filename} & Sqrt\\_FiP32.c \\tabularnewline\r\n\\textbf{H filename} & Sqrt\\_FiP32.h \\tabularnewline\r\n\\end{tabular}\r\n\\vspace{1ex}\r\n\r\n32 Bit Fixed Point Implementation\r\n\r\n% Implementation data structure\r\n\\XtoCDataStruct{Data Structure:}\r\n\\begin{lstlisting}\r\ntypedef struct {\r\n     uint16        ID;\r\n     int32         *In;\r\n     int32         Out;\r\n} SQRT_FIP32;\r\n\\end{lstlisting}\r\n\r\n\\ifdefined \\AddTestReports\r\n\\InputIfFileExists{\\XcHomePath/Library/Math/Doc/Test_Sqrt_FiP32.tex}{}{}\r\n\\fi\r\n\\XtoCImplementation{Float32}\r\n\\index{Block ID!4819}\r\n\\nopagebreak[0]\r\n% Implementation details\r\n\\begin{tabular}{l l}\r\n\\textbf{Name} & Float32 \\tabularnewline\r\n\\textbf{ID} & 4819 \\tabularnewline\r\n\\textbf{Revision} & 0.1 \\tabularnewline\r\n\\textbf{C filename} & Sqrt\\_Float32.c \\tabularnewline\r\n\\textbf{H filename} & Sqrt\\_Float32.h \\tabularnewline\r\n\\end{tabular}\r\n\\vspace{1ex}\r\n\r\n32 Bit Floating Point Implementation\r\n\r\n% Implementation data structure\r\n\\XtoCDataStruct{Data Structure:}\r\n\\begin{lstlisting}\r\ntypedef struct {\r\n     uint16        ID;\r\n     float32       *In;\r\n     float32       Out;\r\n} SQRT_FLOAT32;\r\n\\end{lstlisting}\r\n\r\n\\ifdefined \\AddTestReports\r\n\\InputIfFileExists{\\XcHomePath/Library/Math/Doc/Test_Sqrt_Float32.tex}{}{}\r\n\\fi\r\n\\XtoCImplementation{Float64}\r\n\\index{Block ID!4820}\r\n\\nopagebreak[0]\r\n% Implementation details\r\n\\begin{tabular}{l l}\r\n\\textbf{Name} & Float64 \\tabularnewline\r\n\\textbf{ID} & 4820 \\tabularnewline\r\n\\textbf{Revision} & 0.1 \\tabularnewline\r\n\\textbf{C filename} & Sqrt\\_Float64.c \\tabularnewline\r\n\\textbf{H filename} & Sqrt\\_Float64.h \\tabularnewline\r\n\\end{tabular}\r\n\\vspace{1ex}\r\n\r\n64 Bit Floating Point Implementation\r\n\r\n% Implementation data structure\r\n\\XtoCDataStruct{Data Structure:}\r\n\\begin{lstlisting}\r\ntypedef struct {\r\n     uint16        ID;\r\n     float64       *In;\r\n     float64       Out;\r\n} SQRT_FLOAT64;\r\n\\end{lstlisting}\r\n\r\n\\ifdefined \\AddTestReports\r\n\\InputIfFileExists{\\XcHomePath/Library/Math/Doc/Test_Sqrt_Float64.tex}{}{}\r\n\\fi\r\n", "meta": {"hexsha": "2c3034446ad6ea055a0f09801fbdc50cf4bf4811", "size": 4564, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Library/Math/Doc/Sqrt.tex", "max_stars_repo_name": "AlexisTM/X2C", "max_stars_repo_head_hexsha": "31f39b598afe271a7fd46ef1ee9e06c410b1120c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Library/Math/Doc/Sqrt.tex", "max_issues_repo_name": "AlexisTM/X2C", "max_issues_repo_head_hexsha": "31f39b598afe271a7fd46ef1ee9e06c410b1120c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Library/Math/Doc/Sqrt.tex", "max_forks_repo_name": "AlexisTM/X2C", "max_forks_repo_head_hexsha": "31f39b598afe271a7fd46ef1ee9e06c410b1120c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6900584795, "max_line_length": 79, "alphanum_fraction": 0.7180105171, "num_tokens": 1439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.33719144550766533}}
{"text": "\\maketitle\n\n\\setlength{\\epigraphwidth}{0.6\\textwidth}\n\\epigraph{\\it Mathematics is a process of staring hard enough with enough perseverance at the fog of muddle and confusion to eventually break through to improved clarity. I’m happy when I can admit, at least to myself, that my thinking is muddled, and I try to overcome the embarrassment that I might reveal ignorance or confusion. }{William Thurston}\n\n\n\\section*{How to use these notes.}\n\\label{sec:intro}\n\\addcontentsline{toc}{section}{\\nameref{sec:intro}}\n\nLinear algebra is the study of linearity. The main players of this story are the vectors, but instead of studying vectors individually, we study collections of vectors, called {\\bf vector spaces}, and maps between vector spaces, called {\\bf linear transformations}.\n\nBecause linearity is such a simple condition (Section \\ref{section:VectorSpaces}), linear algebra is one of the most widely applied branches of mathematics.\\\\\\\\\n\nThese notes provide a very, very brief introduction to linear algebra.\nYou'll learn enough to be able to continue the study of the subject on your own.\n\nEach day you will be given a set of problems to solve in class.\nYou should attempt as many problems as you can, and it is ok to not finish all the problems before the next class.\nHowever, you should make an honest attempt to read and understand the various definitions and theorems.\\footnote{These notes are likely to contain \\sout{a few} several \\sout{typos} mistakes. Please do tell if you find any, thanks in advance.}\n", "meta": {"hexsha": "a3d295bdbdbdea66696ccb0daf0b7fb68dba9850", "size": 1518, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "00.tex", "max_stars_repo_name": "apurvnakade/mc2019-linear-algebra", "max_stars_repo_head_hexsha": "6626512c3109bbe8696ab5787293037ed90d5058", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "00.tex", "max_issues_repo_name": "apurvnakade/mc2019-linear-algebra", "max_issues_repo_head_hexsha": "6626512c3109bbe8696ab5787293037ed90d5058", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "00.tex", "max_forks_repo_name": "apurvnakade/mc2019-linear-algebra", "max_forks_repo_head_hexsha": "6626512c3109bbe8696ab5787293037ed90d5058", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 72.2857142857, "max_line_length": 351, "alphanum_fraction": 0.7885375494, "num_tokens": 342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.3371914366308435}}
{"text": "\\documentclass{sigplanconf}\r\n\\usepackage{url}\r\n\\usepackage{proof}\r\n\\usepackage{amssymb}\r\n\\usepackage{stmaryrd}\r\n\\usepackage{listings}\r\n\\usepackage{graphicx}\r\n\\usepackage{comment}\r\n\r\n\\newcommand{\\dgm}[2][1.5]{\r\n\\begin{center}\r\n\\scalebox{#1}{\r\n\\includegraphics{diagrams/#2.pdf}\r\n}\r\n\\end{center}\r\n}\r\n\\newcommand{\\todo}[1]{\\textbf{TODO:} #1}\r\n\\newcommand{\\jacques}[1]{\\textsc{Jacques says:} #1}\r\n\\newcommand{\\amr}[1]{\\textsc{Amr says:} #1}\r\n\r\n\\newtheorem{theorem}{Theorem}[section]\r\n\\newtheorem{lemma}[theorem]{Lemma}\r\n\\newtheorem{definition}[theorem]{Definition}\r\n\\newtheorem{proposition}[theorem]{Proposition}\r\n\r\n%subcode-inline{bnf-inline} name Pi\r\n%! swap+ = \\mathit{swap}^+\r\n%! swap* = \\mathit{swap}^*\r\n%! dagger =  ^{\\dagger}\r\n%! assocl+ = \\mathit{assocl}^+\r\n%! assocr+ = \\mathit{assocr}^+\r\n%! assocl* = \\mathit{assocl}^*\r\n%! assocr* = \\mathit{assocr}^*\r\n%! identr* = \\mathit{uniti}\r\n%! identl* = \\mathit{unite}\r\n%! dist = \\mathit{distrib}\r\n%! factor = \\mathit{factor}\r\n%! (o) = \\fatsemi\r\n%! (;) = \\fatsemi\r\n%! (*) = \\times\r\n%! (+) = +\r\n%! foldB = fold_B\r\n%! unfoldB = unfold_B\r\n%! foldN = fold_N\r\n%! unfoldN = unfold_N\r\n%! trace+ = \\mathit{trace}^{+}\r\n%! trace* = \\mathit{trace}^{\\times}\r\n%! :-* = \\multimap\r\n%! :-+ = \\multimap^{+}\r\n%! emptyset = \\emptyset\r\n\r\n%subcode-inline{bnf-inline} regex \\{\\{(((\\}[^\\}])|[^\\}])*)\\}\\} name main include Pi\r\n%! [^ = \\ulcorner\r\n%! ^] = \\urcorner\r\n%! [v = \\llcorner\r\n%! v] = \\lrcorner\r\n%! [[ = \\llbracket\r\n%! ]] = \\rrbracket\r\n%! ^^^ = ^{\\dagger}\r\n%! eta* = \\eta\r\n%! eps* = \\epsilon\r\n%! Union = \\bigcup\r\n%! in = \\in\r\n%! |-->* = \\mapsto^{*}\r\n%! |-->> = \\mapsto_{\\ggg}\r\n%! |-->let = \\mapsto_{let}\r\n%! |--> = \\mapsto\r\n%! <--| = \\mapsfrom\r\n%! |- = \\vdash\r\n%! <=> = \\Longleftrightarrow\r\n%! <-> = \\leftrightarrow\r\n%! -> = \\rightarrow\r\n%! ~> = \\leadsto\r\n%! ::= = ::=\r\n%! amp = \\&\r\n%! /= = \\neq\r\n%! vi = v_i\r\n%! di = d_i\r\n%! si = s_i\r\n%! sj = s_j\r\n%! F = \\texttt{F}\r\n%! T = \\texttt{T}\r\n%! forall = \\forall\r\n%! exists = \\exists\r\n%! empty = \\emptyset\r\n%! Sigma = \\Sigma\r\n%! eta = \\eta\r\n%! where = \\textbf{where}\r\n%! epsilon = \\varepsilon\r\n%! least = \\phi\r\n%! loop+ = loop_{+}\r\n%! loop* = loop_{\\times}\r\n%! CatC = {\\mathcal C}\r\n%! CatA = {\\mathcal A}\r\n%! gamma = \\gamma\r\n%! {[ = \\{\r\n%! ]} = \\}\r\n%! elem = \\in\r\n%! dagger = ^\\dagger\r\n%! alpha = \\alpha\r\n%! beta = \\beta\r\n%! rho = \\rho\r\n%! @@ = \\mu\r\n%! @ = \\,@\\,\r\n%! Pow = \\mathcal{P}\r\n%! Pi = \\Pi\r\n%! PiT = \\Pi^{o}\r\n%! PiEE = \\Pi^{\\eta\\epsilon}_{+}\r\n%! PiT = \\Pi^{o}\r\n%! PiTF = \\Pi^{/}\r\n%! bullet = \\bullet\r\n%! * = \\times\r\n\r\n\\begin{document}\r\n\\conferenceinfo{POPL '14}{date, City.} \r\n\\copyrightyear{2014}\r\n\\copyrightdata{[to be supplied]} \r\n\r\n\\title{\\ldots}\r\n\\authorinfo{\\ldots}\r\n           {\\ldots}\r\n           {\\ldots}\r\n\r\n\\maketitle\r\n\r\n\\begin{abstract}\r\n\\ldots\r\n\\end{abstract}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\section{Background: {{Pi}} }\r\n\\label{sec:pi}\r\n\r\nWe review our language {{Pi}} providing the necessary background and\r\ncontext for our higher-order extension.\\footnote{The presentation in this\r\n  section focuses on the simplest version of {{Pi}}. Other versions\r\n  include the empty type, recursive types, and trace operators but these\r\n  extensions are orthogonal to the higher-order extension emphasized in this\r\n  paper.} The terms of {{Pi}} are not classical values and functions;\r\nrather, the terms are isomorphism witnesses.  In other words, the terms of\r\n{{Pi}} are proofs that certain ``shapes of values'' are isomorphic.\r\nAnd, in classical Curry-Howard fashion, our operational semantics shows how\r\nthese proofs can be directly interpreted as actions on ordinary values which\r\neffect this shape transformation. Of course, ``shapes of values'' are very\r\nfamiliar already: they are usually called \\emph{types}.  But frequently one\r\ndesigns a type system as a method of classifying terms, with the eventual\r\npurpose to show that certain properties of well-typed terms hold, such as\r\nsafety.  Our approach is different: we start from a type system, and then\r\npresent a term language which naturally inhabits these types, along with an\r\nappropriate operational semantics.\r\n\r\n\\paragraph*{Data.}\r\nWe view {{Pi}} as having two levels:  it has traditional values, given by:\r\n%subcode{bnf} include main\r\n% values, v ::= () | left v | right v | (v, v)\r\n\r\n\\noindent and these are classified by ordinary types:\r\n%subcode{bnf} include main\r\n% value types, b ::= 1 | b + b | b * b \r\n\r\n\\noindent \r\nTypes include the unit type {{1}}, sum types {{b1+b2}}, and product types\r\n{{b1*b2}}.  Values include {{()}} which is the only value of type {{1}},\r\n{{left v}} and {{right v}} which inject~{{v}} into a sum type, and\r\n{{(v1,v2)}} which builds a value of product type.  These values should be\r\nregarded as largely ancillary: we do not treat them as first-class citizens,\r\nand they only occur when observing the effect of an isomorphism.\r\n\r\n\\paragraph*{Isomorphisms.} The important terms of {{Pi}} are witnesses to\r\n(value) type isomorphisms.  They are also typed, by the shape of the (value)\r\ntype isomorphism they witness {{b <-> b}}.  Specifically, they are witnesses\r\nto the following isomorphisms:\r\n%subcode{bnf} include main\r\n%! columnStyle = r@{\\hspace{-0.5pt}}r c l@{\\hspace{-0.5pt}}l\r\n%swap+ :&  b1 + b2 & <-> & b2 + b1 &: swap+\r\n%assocl+ :&  b1 + (b2 + b3) & <-> & (b1 + b2) + b3 &: assocr+\r\n%identl* :&  1 * b & <-> & b &: identr*\r\n%swap* :&  b1 * b2 & <-> & b2 * b1 &: swap*\r\n%assocl* :&  b1 * (b2 * b3) & <-> & (b1 * b2) * b3 &: assocr*\r\n%dist :&~ (b1 + b2) * b3 & <-> & (b1 * b3) + (b2 * b3)~ &: factor\r\n\r\n\\noindent Each line of the above table introduces a pair of dual\r\nconstants\\footnote{where {{swap*}} and {{swap+}} are self-dual.} that witness\r\nthe type isomorphism in the middle.  These are the base (non-reducible) terms\r\nof the second, principal level of {{Pi}}. Note how the above has two\r\nreadings: first as a set of typing relations for a set of constants. Second,\r\nif these axioms are seen as universally quantified, orientable statements,\r\nthey also induce transformations of the (traditional) values. The\r\n(categorical) intuition here is that these axioms have computational content\r\nbecause they witness isomorphisms rather than merely stating an extensional\r\nequality.\r\n\r\nThe isomorphisms are extended to form a congruence relation by adding the\r\nfollowing constructors that witness equivalence and compatible closure:\r\n\r\n%subcode{proof} include main\r\n%@  ~\r\n%@@ id : b <-> b \r\n%\r\n%@ c : b1 <-> b2\r\n%@@ sym c : b2 <-> b1\r\n%\r\n%@ c1 : b1 <-> b2\r\n%@ c2 : b2 <-> b3\r\n%@@ c1(;)c2 : b1 <-> b3\r\n%---\r\n%@ c1 : b1 <-> b3\r\n%@ c2 : b2 <-> b4\r\n%@@ c1 (+) c2 : b1 + b2 <-> b3 + b4\r\n%\r\n%@ c1 : b1 <-> b3\r\n%@ c2 : b2 <-> b4\r\n%@@ c1 (*) c2 : b1 * b2 <-> b3 * b4\r\n\\noindent The syntax is overloaded: we use the same symbol at the value-type level\r\nand at the isomorphism-type level for denoting sums and products.  Hopefully\r\nthis will not cause undue confusion.\r\n\r\nIt is important to note that ``values'' and ``isomorphisms'' are completely\r\nseparate syntactic categories which do not intermix. The semantics of the\r\nlanguage come when these are made to interact at the ``top level'' via\r\n\\emph{application}: \r\n%subcode{bnf} include main\r\n% top level term, l ::= c v\r\n\r\n\\noindent\r\nTo summarize, the syntax of {{Pi}} is given as follows. \r\n\r\n\\begin{definition}{(Syntax of {{Pi}})}\r\n\\label{def:Pi}\r\n%subcode{bnf} include main\r\n% value types, b ::= 1 | b+b | b*b \r\n% values, v ::= () | left v | right v | (v,v) \r\n%\r\n% iso.~types, t ::= b <-> b\r\n% base iso ::= swap+ | assocl+ | assocr+ \r\n%     &|& unite | uniti | swap* | assocl* | assocr* \r\n%     &|& dist | factor \r\n% iso comb., c ::= iso | id | sym c | c (;) c | c (+) c | c (*) c \r\n% top level term, l ::= c v\r\n\\end{definition}\r\n\r\nThe language presented above, at the type level, models a commutative ringoid\r\nwhere the multiplicative structure forms a commutative monoid, but the\r\nadditive structure is just a commutative semigroup.  Note that the version of\r\n{{Pi}} that includes the empty type with its usual laws exactly captures, at\r\nthe type level, the notion of a \\emph{semiring} (occasionally called a\r\n\\emph{rig}) where we replace equality by isomorphism.  Semantically, {{Pi}}\r\nmodels a \\emph{bimonoidal category} whose simplest example is the category of\r\nfinite sets and bijections. In that interpretation, each value type denotes a\r\nfinite set of a size calculated by viewing the types as natural numbers and\r\neach combinator {{c : b1 <-> b2}} denotes a bijection between the sets\r\ndenoted by~{{b1}} and~{{b2}}. \r\n\r\nOperationally, the semantics of {{Pi}} is given using two mutually recursive\r\ninterpreters: one going forward and one going backwards. The use of {{sym}}\r\nswitches control from one evaluator to the other. We will present the\r\noperational semantics in the next section along with the extension with\r\nfractional types and values. For now, we state without proof that the\r\nevaluation of well-typed combinators always terminates and that {{Pi}} is\r\nlogically reversible, i.e., that for all combinators {{c : b1 <-> b2}} and\r\nvalues {{v1 : b1}} and {{v2 : b2}} we have the forward evaluation of {{c v1}}\r\nproduces {{v2}} iff the backwards evaluation of {{c v2}} produces {{v1}}.\r\n\r\nAs is usual with type theories, the coherence conditions (pentagonal and\r\ntriangle identity) are not explicit, but would correspond to certain identity\r\ntypes being trivial.\r\n\r\n\\section{ {{Pi}} with trace}\r\n\r\nIn order to take a step toward being able to write the Int construction in\r\n{{Pi}} to give it fractional types, we want to add a trace combinator to it,\r\nwith the following type:\r\n\r\n%subcode{proof} include main\r\n%@  c : b1 * b <-> b2 * b\r\n%@@ trace c : b1 <-> b2\r\n\r\nThis kind of combinator allows us to cancel out a common factor. When the type\r\n{{0}} is removed from the language, it is always possible to do this, but adding\r\ncomputational content becomes tricky. For example, consider permutations on the\r\nfinite set of size {{6}}. If we wish to trace one of these to get a permutation\r\non the set of size {{3}}, we are able to, but which set of size {{3}}? There\r\nare several different ways to do this, but there is no obvious canonical answer.\r\n\r\nMore concretely, suppose we have a combinator {{c : 3 * 2 <-> 3 * 2}}. The\r\ncombinator {{trace c : 3 <-> 3}} can be constructed in two obvious ways: let\r\n{{(trace c) v}} run {{c}} on {{(v, true)}} or on {{(v, false)}}. It is possible\r\nto choose {{c}} so that depending on which default value of type {{2}} is used,\r\na different combinator results.\r\n\r\nTo fix this, we parameterize {{trace}} with a value {{v : b}}, as follows:\r\n\r\n%subcode{proof} include main\r\n%@  c : b1 * b <-> b2 * b\r\n%@  v : b\r\n%@@ trace_v c : b1 <-> b2\r\n\r\nIt remains to show that this is ``well-behaved''; that is, we want it to obey\r\nsome (ideally all) of the trace properties, or at the very least some subset of\r\nthem that is sufficient to prove some necessary properties for {{Pi}} extended\r\nwith fractional types, as presented in the next few sections.\r\n\r\n\\subsection{Alternatives}\r\n\r\nIf this formulation of trace does not work, we have a few alternatives:\r\n\r\n\\begin{itemize}\r\n\r\n\\item Don't bother choosing a default element at all. We did this previously\r\nwith the relational semantics, without much success, but perhaps there's a\r\nbetter way of looking at it.\r\n\r\n\\item Choose a canonical representative of the type {{b}} that's being traced\r\nout. This seems like it's a strictly worse option than parameterizing it, but\r\nit's still on the table, at least for now.\r\n\r\n\\item Focus on the combinator. Jacques pointed out that our old version of trace\r\n``worked'' whenever the part of {{c}} acting on {{b}} was equivalent to the\r\nidentity. This seems promising, but I'm not quite sure how to think about it\r\nyet, so I'm ignoring it for now. It's definitely something we want to look at,\r\nthough, especialy if the current approach doesn't work.\r\n\r\n\\end{itemize}\r\n\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\section{Syntax of Fractionals}\r\n\r\nThe types of {{Pi}} correspond to the natural numbers. Our goal is to have a\r\ntype system that corresponds to the (positive) rational numbers. \r\n\r\n\\begin{definition}{(Syntax of {{PiTF}})}\r\n\\label{def:PiTF}\r\n%subcode{bnf} include main\r\n% value types, r ::= b1 / b2\r\n% values, f ::= (v1 |--> v2, c)\r\n%\r\n% iso.~types, t ::= r <=> r\r\n% base iso ::= swap+ | assocl+ | assocr+ \r\n%     &|& unite | uniti | swap* | assocl* | assocr* \r\n%     &|& dist | factor \r\n%     &|& eta | epsilon\r\n% iso comb., c ::= iso | id | sym c | c (;) c | c (+) c | c (*) c \r\n% top level term, l ::= c v\r\n\\end{definition}\r\n\r\nIf we restrict our attention to types {{b / 1}} and values {{ () |--> v amp id}},\r\nwe recover {{Pi}}. \r\n\r\nIn algebra, the rational number {{a/b}} denotes \r\n$\\{ (a','b) ~|~ a * b' = a' * b \\}$. We essentially use the same denotation but\r\nadd computational content, i.e., the type {{a/b}} denotes\r\n$\\{ (a',b',c) ~|~ c : a * b' \\leftrightarrow a' * b \\}$ where $c$ is a {{Pi}}\r\ncombinator witnessing the equivalence of {{a * b'}} and {{a' * b}}. \r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\section{Higher-Order Reversible Functions}\r\n\r\nTo get from {{Pi}}~\\cite{James:2012:IE:2103656.2103667} types and combinators\r\nto a higher order setting, we hope to add \\emph{fractional types} to the\r\nlanguage. Recall that to construct the (positive) rational numbers {{Q}}, we\r\ncan take pairs of positive integers {{(m, n)}} and quotient by the\r\nequivalence relation that says {{(m1, n1)}} is equal to {{(m2, n2)}} if \r\n{{m1 * n2 = m2 * n1}}. We can write this as an inference rule as follows:\r\n\r\n%subcode{proof} include main\r\n%@ m1 * n2 = m2 * n1\r\n%@@ (m1, n1) = (m2, n2)\r\n\r\n\\noindent\r\nAdding in computational content, pi-style, suggests that we want something like:\r\n\r\n%subcode{proof} include main\r\n%@ c : A1 * B2 <-> B1 * A2\r\n%@@ {[c]} : (B1 |--> A1) <=> (B2 |--> A2)\r\n\r\n\\noindent\r\nHowever, this does not quite work. To see why, recall that we want to treat the\r\npair {{(m, n)}} (written here as {{A |--> B}}) as an internalization of the\r\nreversible function space. Thus, the type {{(B1 |--> A1) <=> (B2 |--> A2)}}\r\nshould be a transformation of a {{Pi}} combinator of type {{B1 <-> A1}} into a\r\n{{Pi}} combinator of type {{B2 <-> A2}}. In order to do this, we need a trace\r\ncombinator (TODO: draw a diagram that demonstrates this) with the type\r\n\r\n%subcode{proof} include main\r\n%@ c : A * C <-> B * C\r\n%@@ trace c : A <-> B\r\n\r\n\\noindent\r\nThis is an issue, since prior attempts at defining an adequate trace operator\r\nfailed: we got a language that could express all relations, but was no longer\r\nreversible in a meaningful sense.\r\n\r\n%%%%%%%%%%%%%%%%%%%\r\n\\subsection{Defining trace}\r\n\r\nThe trace operator had two problems: it allowed arbitrary function definition,\r\nand it would not work in a language that contained the empty type {{0}}. The\r\nformer problem arose due to the logic programming-style interpretation we\r\nassigned to trace: it would create *all* possible values of type {{C}}, then run\r\nthe given combinator on them and throw away the branches that did not return the\r\nsame {{C}} value.\r\n\r\nWe can solve this problem by parameterizing the trace operator with a value {{v\r\n: C}}. This results in the following new typing rule for trace:\r\n\r\n%subcode{proof} include main\r\n%@ c : A * C <-> B * C\r\n%@ v : C\r\n%@@ trace_v c : A <-> B\r\n\r\n\\noindent\r\nThis ends up solving both problems: we give the trace a default value, and\r\nprevent it from running on the empty type (since {{C}} now must be inhabited).\r\nHowever, we still must assign dynamic semantics to trace. The na\\\"ive solution\r\nof running {{c}} on the pair of the input value and {{v}} does not work, as this\r\nis trivially irreversible---consider, for example, {{trace_v swap*}}, which\r\ntakes any value of the same type as {{v}} and returns {{v}}. Thus, the semantics\r\nfor {{trace}} must be slightly more complicated.\r\n\r\nRecall that in {{Pi}}, combinators can be viewed as permutations on finite sets.\r\nA combinator of type {{A * C <-> B * C}} can be seen as two separate\r\npermutations: one on {{A}} (or equivalently, B, since they must have the same\r\nsize and thus the same denotation as a finite set) and one on {{C}}. If we\r\napply the fragment of the combinator that acts on {{C}} enough times, we will\r\neventually get out the same value that we started with\\footnote{I want to prove\r\nthat this is actually true; having the extra {{A}} there seems like it might\r\ncomplicate things.}. Thus, the semantics that we want is for {{(trace_v c) v'}}\r\nto run {{c}} on the pair of {{v'}} and the last {{C}} value (starting with\r\n{{v}}) until the {{C}} value matches {{v}}, at which point it returns the {{B}}\r\nvalue returned by the combinator. In pseudocode:\r\n\r\n\\begin{verbatim}\r\nTODO: figure out how to do the code \r\nenvironment in subcode\r\n\r\ntrace v c vin =\r\n  v0 = v\r\n  <vout, v'> = c <vin, v>\r\n\r\n  while (v' != v)\r\n    <vout, v'> := c <vin, v'>\r\n\r\n  return vout\r\n\\end{verbatim}\r\n\r\nA more concise formulation as an inference rule is as follows:\r\n\r\n%subcode{proof} include main\r\n%@ exists v0 : C. c <v_{in}, v> = <v_{out}, v>\r\n%@@ (trace_v c) v_{in} = v_{out}\r\n\r\nThis is easily reversible: {{(trace_v c)dagger = trace_v (c dagger)}}\r\n\\footnote{Also need to prove this.}.\r\n\r\n%%%%%%%%%%%%%%%%%%%\r\n\\subsection{Higher-Order Combinators}\r\n\r\nNow that we have the trace combinator defined, we can proceed with defining\r\nhigher-order combinators. Note that this parameterizes our definition of\r\n$\\{c\\}$ by {{v}}, the value of type {{A}} (or equivalently, type {{B}}) used\r\nin the trace:\r\n\r\n%subcode{proof} include main\r\n%@ c : A1 * B2 <-> B1 * A2\r\n%@@ {[c]}_v : (B1 |--> A1) <=> (B2 |--> A2)\r\n\r\n\\noindent\r\nWe want this to be a transformation on combinators, taking a combinator of type\r\n{{B1 <-> A1}} to a combinator of type {{B2 <-> A2}}. This can be achieved by\r\nletting the combinator {{{[c]}_v c'}} be {{trace_v (c ; c' * id)}}, where\r\n{{c : B1 <-> A1}} and {{v : A1}}.\r\n\r\nFrom here, we want to define bifunctors {{/}}, {{*}}, and {{+}}, to make sure\r\nthat our definition of functions is truly higher-order.\r\n\r\n\\begin{itemize}\r\n\r\n\\item {{(B |--> A) / (D |--> C) = (A * D) |--> (B * C)}}, with\r\n\r\n{{{[c1]}_{v1} : ((B |--> A) <=> (D |--> C)) / {[c2]}_{v_2} : ((B' |--> A') <=> (D' |--> C')) = {[shuffle ; c1 * c2dagger ; shuffle]}_{<v1, c2 v2>}}}\r\n%%: B1 * A2 |--> A1 * B2 <=> D1 * C2 |--> C1 * D2}},\r\nwhere\r\n{{shuffle : (A * B) * (C * D) <-> (A * C) * (B * D)}}.\r\n\r\n\\item {{(B |--> A) * (D |--> C) = (B * D) |--> (A * C)}}, with\r\n\r\n\\end{itemize}\r\n\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n\\bibliographystyle{abbrvnat}\r\n\\bibliography{cites}\r\n\\end{document}\r\n", "meta": {"hexsha": "9e1f9f2dc9ab3405f60856aa4a39835765a4fe6d", "size": 18686, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "summer13/frac2.tex", "max_stars_repo_name": "JacquesCarette/pi-dual", "max_stars_repo_head_hexsha": "003835484facfde0b770bc2b3d781b42b76184c1", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2015-08-18T21:40:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T01:07:57.000Z", "max_issues_repo_path": "summer13/frac2.tex", "max_issues_repo_name": "JacquesCarette/pi-dual", "max_issues_repo_head_hexsha": "003835484facfde0b770bc2b3d781b42b76184c1", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-06-07T16:27:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-29T20:41:23.000Z", "max_forks_repo_path": "summer13/frac2.tex", "max_forks_repo_name": "JacquesCarette/pi-dual", "max_forks_repo_head_hexsha": "003835484facfde0b770bc2b3d781b42b76184c1", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-05-29T01:56:33.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-10T09:47:13.000Z", "avg_line_length": 37.6733870968, "max_line_length": 149, "alphanum_fraction": 0.6372150273, "num_tokens": 5478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3369914028110428}}
{"text": "\n\\section{Reduced formulation to local variables.}\n\n\\subsection{Formulation}\n\nLet us start with \n\\begin{equation}\n  \\label{eq:AC-L7}\n  \\begin{array}{l}\n  \\varPhi_1(U,P) =  - U_{k+1}  + \\widehat W P_{k+1}  + U_{\\mathrm{free}}\\\\ \\\\\n  \\varPhi_2(U,P) =  P_{\\n} - \\proj_{\\nbR^{a}_+} (P_{\\n} - \\rho_{\\n}\\circ (U_{\\n} +e \\circ  U_{\\n,k}) ) \\\\ \\\\\n  \\varPhi_3(U,P) =  P_{\\t} - \\proj_{\\widehat {\\bf D}(P_{\\n},U_{\\n})} (P_{{\\t}} - \\rho_{\\t}\\circ \\,U_{\\t} )\n\\end{array}\n\\end{equation}\nwhere the modified friction disk for a contact $\\alpha$ is\n\\begin{equation}\\label{eq:AC-L3}\n  \\widehat {\\bf D}^\\alpha(P^\\alpha_{\\n,k+1},U_{\\n,k+1}^{\\alpha}) = {\\bf D}(\\mu(\\proj_{\\nbR_+} (P^\\alpha_{\\n,k+1} - \\rho^\\alpha_{\\n}\\,(U_{\\n,k+1}^{\\alpha}+e^\\alpha U_{\\n,k}^{\\alpha}) )).\n\\end{equation}\n\\subsection{Structure of the Jacobians}\n\nLet us denote the one element of the  generalized Jacobian by  $ H(U,P) \\in \\partial \\Phi(U,P)$ which has the structure\n\\begin{equation}\n  \\label{eq:AC-L6}\n   H(U,P) = \n   \\left[\\begin{array}{cccc}\n       - I & 0 &  \\widehat W_{\\n\\n} & \\widehat W_{\\n\\t} \\\\ \\\\\n       0  & -I  &  \\widehat W_{\\t\\n} & \\widehat W_{\\t\\t} \\\\ \\\\\n       \\partial_{U_{\\n}} \\Phi_2(U,P) & 0 &   \\partial_{P_{\\n}} \\Phi_2(U,P) & 0 \\\\ \\\\\n       \\partial_{U_{\\n}} \\Phi_3(U,P) &  \\partial_{U_{\\t}} \\Phi_3(U,P) &  \\partial_{P_{\\n}} \\Phi_3(U,P)  & \\partial_{P_{\\t}} \\Phi_3(U,P)\n   \\end{array}\\right]\n\\end{equation}\n\n\n\\subsection{Computation of the gradients}\n\n\nLet us consider the single contact case.\n\\paragraph{Computation of the gradients of $\\Phi_2$}\n\\begin{equation}\n  \\label{eq:AC-T1}\n  \\begin{array}{l}\n  \\varPhi_2(U,P) =  P_{\\n} - \\proj_{\\nbR^{a}_+} (P_{\\n} - \\rho_{\\n} (U_{\\n} +e  U_{\\n,k}) ) \\\\ \\\\\n\\end{array}\n\\end{equation}\n\\begin{itemize}\n\\item \\textbf{If} $P_{\\n} - \\rho_{\\n} (U_{\\n} +e  U_{\\n,k}) \\geq 0 $, we get \n  \\begin{equation}\n    \\label{eq:AC-T2}\n    \\begin{array}{l}\n      \\varPhi_2(U,P) =  + \\rho_{\\n} (U_{\\n} +e  U_{\\n,k})\n    \\end{array}\n  \\end{equation}\n  and \n  \\begin{equation}\n    \\label{eq:AC-T3}\n    \\begin{array}{l}\n     \\partial_{U_{\\n}} \\varPhi_2(U,P) =  + \\rho_{\\n} \\\\ \\\\\n     \\partial_{P_{\\n}} \\varPhi_2(U,P) =  0 \\\\ \\\\ \n    \\end{array}\n  \\end{equation}\n\\item \\textbf{If} $P_{\\n} - \\rho_{\\n} (U_{\\n} +e  U_{\\n,k})  < 0 $, we get \n  \\begin{equation}\n    \\label{eq:AC-T4}\n    \\begin{array}{l}\n      \\varPhi_2(U,P) =  P_{\\n}\n    \\end{array}\n  \\end{equation}\n  and \n  \\begin{equation}\n    \\label{eq:AC-T5}\n    \\begin{array}{l}\n     \\partial_{U_{\\n}} \\varPhi_2(U,P) =  0 \\\\ \\\\\n     \\partial_{P_{\\n}} \\varPhi_2(U,P) =  1 \\\\ \\\\ \n    \\end{array}\n  \\end{equation}\n\\end{itemize}\n\\paragraph{Computation of the gradients of $\\Phi_3$}\n\\begin{equation}\n  \\label{eq:AC-TT1}\n  \\begin{array}{l}\n  \\varPhi_3(U,P) =  P_{\\t} - \\proj_{\\widehat {\\bf D}(P_{\\n},U_{\\n})} (P_{\\t} - \\rho_{\\t} U_{\\t} ) \\\\ \\\\\n\\end{array}\n\\end{equation}\n\\begin{itemize}\n\\item \\textbf{If} $\\|P_{\\t} - \\rho_{\\t} U_{\\t}\\| \\leq \\mu \\max (0 ,P_{\\n} - \\rho_{\\n} (U_{\\n} +e  U_{\\n,k}) ) $  , we get \n\\begin{equation}\n  \\label{eq:AC-TT2}\n  \\begin{array}{l}\n  \\varPhi_3(U,P) =  + \\rho_{\\t} U_{\\t} \n\\end{array}\n\\end{equation}\nand\n \\begin{equation}\n    \\label{eq:AC-TT3}\n    \\begin{array}{l}\n     \\partial_{U_{\\n}} \\varPhi_3(U,P) =  0 \\\\ \\\\\n     \\partial_{P_{\\n}} \\varPhi_3(U,P) =  0 \\\\ \\\\ \n     \\partial_{U_{\\t}} \\varPhi_3(U,P) =  + \\rho_{\\t} \\\\ \\\\\n     \\partial_{P_{\\t}} \\varPhi_3(U,P) =  0 \\\\ \\\\ \n    \\end{array}\n  \\end{equation}\n\\item \\textbf{If} $\\|P_{\\t} - \\rho_{\\t} U_{\\t}\\| > \\mu \\max (0 ,P_{\\n} - \\rho_{\\n} (U_{\\n} +e  U_{\\n,k}) ) $  , we get \n\\begin{equation}\n  \\label{eq:AC-TT4}\n  \\begin{array}{l}\n  \\varPhi_3(U,P) =  P_{\\t} - \\mu \\max(0,P_{\\n} - \\rho_{\\n} (U_{\\n} +e  U_{\\n,k}) )  \\Frac{P_{\\t} - \\rho_{\\t} U_{\\t} }{ \\| P_{\\t} - \\rho_{\\t} U_{\\t}\\| }\n\\end{array}\n\\end{equation}\n\n\\begin{itemize}\n\\item  \\textbf{If} $P_{\\n} - \\rho_{\\n} (U_{\\n} +e  U_{\\n,k}) \\leq 0$, we get \n  \\begin{equation}\n  \\label{eq:AC-TT5}\n  \\begin{array}{l}\n  \\varPhi_3(U,P) =   P_{\\t}\n\\end{array}\n\\end{equation}\nand \n \\begin{equation}\n   \\label{eq:AC-TT6}\n   \\begin{array}{l}\n     \\partial_{U_{\\n}} \\varPhi_3(U,P) =  0 \\\\ \\\\\n     \\partial_{P_{\\n}} \\varPhi_3(U,P) =  0 \\\\ \\\\ \n     \\partial_{U_{\\t}} \\varPhi_3(U,P) =  0 \\\\ \\\\\n     \\partial_{P_{\\t}} \\varPhi_3(U,P) =  I_2 \\\\ \\\\ \n   \\end{array}\n \\end{equation}\n\\item  \\textbf{If} $P_{\\n} - \\rho_{\\n} (U_{\\n} +e  U_{\\n,k}) > 0$, we get \n\\begin{equation}\n  \\label{eq:AC-TT7}\n  \\begin{array}{l}\n  \\varPhi_3(U,P) =  P_{\\t} - \\mu (P_{\\n} - \\rho_{\\n} (U_{\\n} +e  U_{\\n,k}) )  \\Frac{P_{\\t} - \\rho_{\\t} U_{\\t} }{ \\| P_{\\t} - \\rho_{\\t} U_{\\t}\\| }\n\\end{array}\n\\end{equation}\nand \n \\begin{equation}\n   \\label{eq:AC-TT8}\n   \\begin{array}{l}\n     \\partial_{U_{\\n}} \\varPhi_3(U,P) =  \\mu \\rho_{\\n}  \\Frac{P_{\\t} - \\rho_{\\t} U_{\\t} }{ \\| P_{\\t} - \\rho_{\\t} U_{\\t}\\| }\\text{{\\bf WARNING} case was not taken into account}\\\\ \\\\\n     \\partial_{P_{\\n}} \\varPhi_3(U,P) =  -\\mu  \\Frac{P_{\\t} - \\rho_{\\t} U_{\\t} }{ \\| P_{\\t} - \\rho_{\\t} U_{\\t}\\| } \\\\ \\\\ \n     \\partial_{U_{\\t}} \\varPhi_3(U,P) =  \\mu\\rho_{\\t}(P_{\\n} - \\rho_{\\n} (U_{\\n} +e  U_{\\n,k}) ) \\Gamma(P_{\\t} - \\rho_{\\t} U_{\\t})  \\\\ \\\\\n     \\partial_{P_{\\t}} \\varPhi_3(U,P) =  I_2-\\mu(P_{\\n} - \\rho_{\\n} (U_{\\n} +e  U_{\\n,k}) ) \\Gamma(P_{\\t} - \\rho_{\\t} U_{\\t})  \\\\ \\\\ \n   \\end{array}\n \\end{equation}\n\\end{itemize}\n\n\n\n\\end{itemize}\n\n\\subsection{Rearranging the cases}\n\n{\\bf TO BE COMPLETED}\n\\section{Formulation with global variables.}\n\n\\subsection{Formulation}\nLet us start with \n\\begin{equation}\n  \\label{eq:GAC-L1}\n  \\begin{array}{l}\n  \\Psi_{1}^{a}(v,U,P) =  - \\widehat M v_{k+1}  +  H P_{k+1}  + q \\\\ \\\\\n  \\Psi_{1}^{b}(v,U,P) =  - U_{k+1}  + H^\\top v _{k+1}  + b \\\\ \\\\\n  \\Psi_2(v,U,P) =  P_{\\n} - \\proj_{\\nbR^{a}_+} (P_{\\n} - \\rho_{\\n}\\circ (U_{\\n} +e \\circ  U_{\\n,k}) ) \\\\ \\\\\n  \\Psi_3(v,U,P) =  P_{\\t} - \\proj_{\\widehat {\\bf D}(P_{\\n},U_{\\n})} (P_{{\\t}} - \\rho_{\\t}\\circ \\,U_{\\t} )\n\\end{array}\n\\end{equation}\nwhere the modified friction disk for a contact $\\alpha$ is\n\\begin{equation}\\label{eq:GAC-L2}\n  \\widehat {\\bf D}^\\alpha(P^\\alpha_{\\n,k+1},U_{\\n,k+1}^{\\alpha}) = {\\bf D}(\\mu(\\proj_{\\nbR_+} (P^\\alpha_{\\n,k+1} - \\rho^\\alpha_{\\n}\\,(U_{\\n,k+1}^{\\alpha}+e^\\alpha U_{\\n,k}^{\\alpha}) )).\n\\end{equation}\n\n\\subsection{Structure of the Jacobians}\n\n Let us denote the one element of the  generalized Jacobian by  $ H(v,U,P) \\in \\partial \\Psi(s,U,P)$ which has the structure\n\\begin{equation}\n  \\label{eq:GAC-L3}\n   H(v,U,P) = \n   \\left[\\begin{array}{ccccc}\n       - \\widehat M & 0 & 0 & H_{\\n} & H_{\\t} \\\\ \\\\\n        H_{\\n}^\\top &  - I & 0 & 0 &0 \\\\ \\\\\n        H_{\\t}^\\top &  0  & -I & 0 &0 \\\\ \\\\\n        0 & \\partial_{U_{\\n}} \\Psi_2(v,U,P) & 0 &   \\partial_{P_{\\n}} \\Psi_2(v,U,P) & 0 \\\\ \\\\\n        0 & \\partial_{U_{\\n}} \\Psi_3(v,U,P) &  \\partial_{U_{\\t}} \\Psi_3(v,U,P) &  \\partial_{P_{\\n}} \\Psi_3(v,U,P)  & \\partial_{P_{\\t}} \\Psi_3(v,U,P)\n   \\end{array}\\right]\n\\end{equation}\n\nWe clearly have\n\\begin{equation}\n  \\label{eq:equivalentJacobian}\n  \\begin{array}{lcl}\n     \\partial_{U} \\Psi_2(v,U,P) &=& \\partial_{U} \\Phi_2(U,P) \\\\ \n     \\partial_{P} \\Psi_2(v,U,P) &=& \\partial_{P} \\Phi_2(U,P) \\\\     \n     \\partial_{U} \\Psi_3(v,U,P) &=& \\partial_{U} \\Phi_3(U,P) \\\\ \n     \\partial_{P} \\Psi_3(v,U,P) &=& \\partial_{P} \\Phi_3(U,P) \\\\\n  \\end{array}\n\\end{equation}\nand we get\n\\begin{equation}\n  \\label{eq:GAC-L4}\n   H(v,U,P) = \n   \\left[\\begin{array}{ccccc}\n       - \\widehat M & 0 & 0 & H_{\\n} & H_{\\t} \\\\ \\\\\n        H_{\\n}^\\top &  - I & 0 & 0 &0 \\\\ \\\\\n        H_{\\t}^\\top &  0  & -I & 0 &0 \\\\ \\\\\n        0 & \\partial_{U_{\\n}} \\Phi_2(U,P) & 0 &   \\partial_{P_{\\n}} \\Phi_2(U,P) & 0 \\\\ \\\\\n        0 & \\partial_{U_{\\n}} \\Phi_3(U,P) &  \\partial_{U_{\\t}} \\Phi_3(U,P) &  \\partial_{P_{\\n}} \\Phi_3(U,P)  & \\partial_{P_{\\t}} \\Phi_3(U,P)\n   \\end{array}\\right]\n\\end{equation}\n\n\n\\subsection{Simplification ?}\nSince the second line $\\Psi_1^b$ is linear, we should be able to derive a reduced Jacobian using the chain rule. Let us define $\\widetilde \\Psi$\n\\begin{equation}\n  \\label{eq:chainrule}\n  \\widetilde \\Psi(v,P)  = \\Psi(v,H^\\top v +b,P)\n\\end{equation}\n\n\\begin{equation}\n  \\label{eq:GAC-L5}\n  \\begin{array}{l}\n  \\widetilde \\Psi_{1}(v,P) =  - \\widehat M v_{k+1}  +  H P_{k+1}  + q \\\\ \\\\\n  \\widetilde \\Psi_2(v,P) =  P_{\\n} - \\proj_{\\nbR^{a}_+} (P_{\\n} - \\rho_{\\n}\\circ (H^\\top_{\\n}v+b_{\\n} +e \\circ  U_{\\n,k}) ) \\\\ \\\\\n  \\widetilde \\Psi_3(v,P) =  P_{\\t} - \\proj_{\\widehat {\\bf D}(P_{\\n},U_{\\n})} (P_{{\\t}} - \\rho_{\\t}\\circ \\,(H^\\top_\\t v + b_\\t) )\n\\end{array}\n\\end{equation}\n\n\\paragraph{Chain rule}\n\\begin{equation}\n  \\label{eq:chainrule1}\n  \\begin{array}{lcl}\n  \\partial_v \\widetilde \\Psi_{2,3}(v,P) &=&  \\partial_v \\Psi_{2,3}(v,H^\\top v +b,P)  \\\\ \\\\\n  &=& H_{\\n}^\\top \\partial_{U_\\n} \\Phi_{2,3}(H^\\top v + b,P) + H_{\\t}^\\top \\partial_{U_\\t} \\Phi_{2,3}(H^\\top v + b,P)  \n\\end{array}\n\\end{equation}\n\n\\begin{equation}\n  \\label{eq:GAC-L6}\n   H(v,P) = \n   \\left[\\begin{array}{ccc}\n       - \\widehat M &   H_{\\n} & H_{\\t} \\\\ \\\\\n       H_{\\n}^\\top \\partial_{U_\\n} \\Phi_{2}(H^\\top v + b,P) &   \\partial_{P_{\\n}} \\Phi_2(H^\\top v + b,P) & 0 \\\\ \\\\\n       \\begin{array}{c}\n         H_{\\n}^\\top \\partial_{U_\\n} \\Phi_{3}(H^\\top v + b,P) \\\\\n         \\quad \\quad + H_{\\t}^\\top \\partial_{U_\\t} \\Phi_{3}(H^\\top v + b,P)\\\\\n     \\end{array}\n     &  \\partial_{P_{\\n}} \\Phi_3(H^\\top v + b,P)  & \\partial_{P_{\\t}} \\Phi_3(H^\\top v + b,P)\n   \\end{array}\\right]\n\\end{equation}\n\n\\paragraph{discussion}\n\\begin{itemize}\n\\item Formulae has to be checked carefully\n\\item I do not known if there an interest in the simplification. With sparse matrices, it is perhaps easier to deal with~(\\ref{eq:GAC-L4})\n\\end{itemize}\n\n\n%%% Local Variables: \n%%% mode: latex\n%%% TeX-master: t\n%%% End: \n", "meta": {"hexsha": "a28cc628fedb563137ba457a60e0cd6cfa955988", "size": 9556, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/sphinx/devel_guide/notes/AlartCurnier.tex", "max_stars_repo_name": "ljktest/siconos", "max_stars_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "docs/sphinx/devel_guide/notes/AlartCurnier.tex", "max_issues_repo_name": "ljktest/siconos", "max_issues_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "docs/sphinx/devel_guide/notes/AlartCurnier.tex", "max_forks_repo_name": "ljktest/siconos", "max_forks_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 36.6130268199, "max_line_length": 185, "alphanum_fraction": 0.5376726664, "num_tokens": 4384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.33698205696730343}}
{"text": "\\documentclass[12pt]{article}\n\\usepackage{graphicx}\n\\usepackage{amssymb}\n\\usepackage{multirow}\n%\\usepackage{subfig}\n\n%\\input epsf.sty\n%\\topmargin   0.25in\n\\topmargin -.5cm \\textheight 21cm\n\n\\oddsidemargin -.125cm\n\n\\textwidth 16cm\n\n\n\\newcommand{\\ra}{\\rangle}\n\\newcommand{\\la}{\\langle}\n\\newcommand{\\T}{\\widetilde \\Phi_{CFT}}\n\\newcommand{\\Cn}{{\\cal C}_n}\n\\newcommand{\\vp}{\\varphi}\n\n\\newcommand{\\B}{b'}\n\\newcommand{\\C}{c'}\n\\newcommand{\\bB}{\\bar b'}\n\\newcommand{\\bC}{\\bar c'}\n\\newcommand{\\Bu}{B_{\\vec u}}\n\\newcommand{\\VV}{{\\cal V}}\n\\newcommand{\\II}{{\\cal I}}\n\\newcommand{\\HH}{{\\cal H}}\n\\newcommand{\\MM}{{\\cal M}}\n\\newcommand{\\BB}{{\\cal B}}\n\\newcommand{\\CC}{{\\cal C}}\n\\newcommand{\\OO}{{\\cal O}}\n\\newcommand{\\QQ}{{\\cal Q}}\n\\newcommand{\\PP}{{\\cal P}}\n\\newcommand{\\EE}{{\\cal E}}\n\\newcommand{\\LL}{{\\cal L}}\n\\newcommand{\\SSS} {{\\cal S}}\n%\\newcommand{\\lll}{\\langle\\langle}\n%\\newcommand{\\rrr}{\\rangle\\rangle}\n\\newcommand{\\half}{{1\\over 2}}\n\\newcommand{\\wt}{\\widetilde}\n\\newcommand{\\wh}{\\widehat}\n\\newcommand{\\wc}{\\check}\n\\newcommand{\\wb}{\\bar}\n\\newcommand{\\RR}{{\\cal R}}\n\\newcommand{\\NN}{{\\cal N}}\n\\newcommand{\\TT}{{\\cal T}}\n\\newcommand{\\bet}{\\beta'}\n\\newcommand{\\gam}{\\gamma'}\n\\newcommand{\\WW}{{\\cal W}}\n\\newcommand{\\nl}{\\hspace{-.65cm}}\n\\newcommand{\\bd}{\\begin{displaymath}}\n\\newcommand{\\ed}{\\end{displaymath}}\n\\newcommand{\\ba}{\\begin{eqnarray}}\n\\newcommand{\\ea}{\\end{eqnarray}}\n\\newcommand{\\be}{\\begin{equation}}\n\\newcommand{\\ee}{\\end{equation}}\n\\newcommand{\\ben}{\\begin{eqnarray}}\n\\newcommand{\\een}{\\end{eqnarray}}\n\\newcommand{\\refb}[1]{(\\ref{#1})}\n\\newcommand{\\p}{\\partial}\n\\newcommand{\\sectiono}[1]{\\section{#1}}\n\\setcounter{equation}{0}\n\\renewcommand{\\theequation}{\\thesection.\\arabic{equation}}\n\n\n\n\n\\def\\sqr#1#2{{\\vcenter{\\vbox{\\hrule height.#2pt\n         \\hbox{\\vrule width.#2pt height#1pt \\kern#1pt\n            \\vrule width.#2pt}\n         \\hrule height.#2pt}}}}\n\\def\\square{\\mathop{\\mathchoice\\sqr66\\sqr66\\sqr{3.75}4\\sqr34\\,}\\nolimits}\n\n\n\\begin{document} \n\\section{Methodology}\nBy comparing the statistic of the observed lensed galaxies to the theoretical\npredictions one can constrain the intrinsic luminosity function. Here we make\nuse of the observed sub-mm galaxies  located between $z = 1$ and $z = 4$ with\nthe  redshift distribution of sources from Simpson et al. 2014 \\cite{Simpson:2014lr}, $\ndN/dz \\propto \\exp\\left[-(\\ln(z+1)-\\ln(1+z_\\mu))^2/2\\sigma_z^2\\right]/\\left[(z+1)\\sigma_z\\sqrt{2\\pi}\\right]$, where $z_\\mu = 2.6$, $\\sigma_z = 0.2$ to constrain the intrinsic luminosity function. To this end, we test several theoretical models which include broken power law and Schechter luminosity functions with various parameters and test them against the data. Similar analysis appeared, e.g.  in  Lima et al. 2010a \\cite{Lima:2010a}, Lima et al. 2010b \\cite{Lima:2010b}, Wardlow et al. (2013) \\cite{Wardlow:2013}, etc. \n\n\n In the following we first describe our way to model the foreground population, we then discuss the calculation of the lensing statistics, and, finally, we list our choices for the intrinsic luminosity functions. \n\n\n\\subsection{Magnification by an individual lens}\n\nWe begin by summarizing the properties of the lenses. We use two ways to model our halos: (1) as a single isothermal sphere (SIS), and (2) a NFW profile (Navarro et al. 1997).  The NFW profile describes the outskirts of halos better whereas the SIS profile is good in describing the inside of a halo since it yields the  observed flat rotational curves. Here we make use of the both profiles to create the total probability distribution function.\n\nIn general, the magnification can be calculated as follows \n\\begin{equation}\n\\mu(\\theta) = \\frac{1}{(1-\\kappa(\\theta))^2-|\\gamma(\\theta)|^2},\n\\end{equation}\nwhere  $\\theta$ is the angular  coordinate in the lens plane, $\\kappa$ is the convergence and $\\gamma $ the shear, which depend on the properties of the lens and its distance from the source.  \n\nWe start with the NFW halos. In this case the convergence and shear are given by \n\\begin{equation}\n\\kappa_{NFW}(\\theta) = \\frac{M_{vir}fc_{200}^2}{2\\pi r_{200}^2}\\frac{F\\left(c_{200}\\theta/\\theta_{200}\\right)}{\\Sigma_{cr}}~~~~\\textrm{and}~~~~\\gamma(\\theta) = \\frac{M_{vir}f c_{200}^2}{2\\pi r_{200}^2}\\frac{G\\left(c_{200}\\theta/\\theta_{200}\\right)}{\\Sigma_{cr}},\n\\label{Eq:kappa}\\end{equation}\nwith  the critical projected density is given by  \n\\begin{equation}\n\\Sigma_{cr} = \\frac{1}{4\\pi G(1+z)}\\frac{D_A^s)}{D_A^l)D_A^{ls})},\n\\end{equation}\nwhere $D_A^s$, $D_A^l$ and $D_A^{ls}$  are the angular diameter distance between the observer and the source,  the observer and the lens and the lens and the source respectively. In eq.  \\ref{Eq:kappa}  F and G are two functions given by Takada and Jian 2003 \\cite{Takada:2003}, for which we assumed a truncated NFW profile (truncated at $r_{vir}$).  $M_{vir}$ is the virial mass, $r_{200}$ is the comoving virial radius, $\\theta_{200}$ is the angular size on the lens plane which corresponds to  $r_{200}$, $c_{200}$ is the concentration parameter of the dark matter halos calculated as in Diemer and Kravtsov (2014) \\cite{Diemer:2014} and  $f = \\left[\\log(1+c_{200})-c_{200}/(1+c_{200})\\right]^{-1}$.\n\nThe magnification of SIS can be written as  \n\\begin{equation}\n\\mu_{SIS}(\\theta)= \\left(1-\\frac{\\theta_E}{|\\theta|}\\right)^{-1},~~~~\\textrm{with}~~~~\\theta_E = 4\\pi\\frac{\\sigma_V^2}{c^2}\\frac{D_{A}(r_{ls})}{D_A(r_s)}.\n\\end{equation}\nHere $\\sigma_V^2$ is the velocity  dispersion which we take from a simulation by Evrard et al. (2008) \\cite{Evrard:2008}. In this simulation the dependence of $\\sigma_V^2$ on the halo mass and redshift is provided which allows us to apply our model to high and low redshift galaxies. \n\nNext for each given source we need to sum up the contributions to the total magnification from different lenses. Here we generate abundances of halos at each redshift using the Sheth-Tormen (1999) \\cite{Sheth:1999} formalism which gives the number of halos per unit volume in each mass bin. \n \n\n\n\\subsection{Lensing Statistics}\n\nThe magnification of a source galaxy by a foreground galaxy depends on the profile of the foreground galaxy, redshifts of the lens and of the source and the impact parameter.  To model the probability distribution of lensing the  procedure is as follows. We first model the differential probability distribution $P(\\mu)$ for a particular pair of source which emits light at $z_s$ and lens of mass $M_l$ which deflects the the light ray at $z_l$ where we account for a wide range of impact parameters. We next sum over the distribution of redshift sources and the masses and the redshifts of the  lenses to get the total probability distribution function.\n\n\nNext, we calculate the total probability for lensig with the magnification larger than some $\\mu$, $P(>\\mu)$ and the probability density for magnification $\\mu$, $P(\\mu) = -dP(>\\mu)/d\\mu$. In this we generally follow the approach taken in Lima et al. (2010a) \\cite{Lima:2010a}. \n\nIt should be noted that neither SIS nor NFW profiles fully describe the observations with SIS being a better match at small distances from the halo center and NFW better describing the outskirts. To be closer to reality,  we smoothly glue the probability densities $P_{SIS}(\\mu)$ and $P_{NFW}(\\mu)$ so that the former dominates at large magnifications (small impact parameters) and the latter dominates at small  magnifications (large impact parameters). We make sure that the resulting probability density, $P_{tot}(\\mu)$, is normalized to unity. \n\nWe further use this probability density to estimate the effect of lensing on the observed luminosity function. To this end we calculate the mean magnification at given observed flux and compare it to data  \\begin{equation}\n <\\mu>(S_{obs}) = \\int_0^\\infty \\mu P(\\mu|S_{obs})  d\\mu,\n \\end{equation}\nwhere the probability for lesning with magnification $\\mu$ given the observed flux \\cite{Lima:2010b} is\n\\begin{equation}\nP(\\mu|S_{obs}) = \\frac{1}{N}\\frac{P(\\mu)}{\\mu}\\frac{dn}{dS}\\left(\\frac{S_{obs}}{\\mu}\\right), ~~~\\textrm{where}~~~N = \\frac{dn_{obs}(S_{obs})}{dS_{obs}} = \\int  \\frac{P(\\mu)}{\\mu}\\frac{dn}{dS}\\left(\\frac{S_{obs}}{\\mu}\\right)d\\mu.\n\\end{equation} \nHere $ dn_{obs}(S_{obs})/dS_{obs}$ is the observed luminosity function and $dn/dS$ is the intrinsic one which we discuss in the next section.\n\nIn addition we calculate the expected fraction of the sources of observed flux $S_{obs}$ lensed with magnification greater than $\\mu$\n\\begin{equation}\nFr = \\frac{\\int_\\mu^\\infty P(\\mu|S_{obs})}{\\int_0^\\infty P(\\mu|S_{obs})}.\n\\end{equation}\n\n\n \n\n\n\n\n\\subsection{Intrinsic luminosity function}\n\nThe effects of lensing are expected to be manifested at the bright-luminosity end of the luminosity function. Therefore it is natural to assume that the faint-luminosity end has undergone a negligible amount of lensing.  \nWe use the faint-luminosity number counts recently reported by Karim et al. (2013) to normalize our intrinsic luminosity functions. \n\nWe use two functional forms to fit the number counts: \n\\begin{enumerate}\n\\item The Shechter function with \n\\begin{equation}\n\\frac{dn}{dS} = \\frac{n_\\star}{S_\\star}\\left(\\frac{S}{S_\\star}\\right)^{-\\alpha}\\exp\\left(-S/S_\\star\\right)\n\\end{equation}\nwith the parameters $n_s = 424$ $mJ^{-1}deg^{-2}$, $S_\\star = 8$ [mJy], $\\alpha = 1.1$ (from Karim et al. 2013) and $n_s = 424$ $mJ^{-1}deg^{-2}$, $S_\\star = 7$ [mJy], $\\alpha = 1.9$ (steep).   \n\\item The broken power law \n\\begin{equation}\n\\frac{dn}{dS} = N_s\\left(\\frac{S}{S_\\star}\\right)^{-\\beta_1},~~~~\\textrm{for}~~~~S<S_\\star,\n\\end{equation} \n\\begin{displaymath}\n\\frac{dn}{dS} = N_s\\left(\\frac{S}{S_\\star}\\right)^{-\\beta_2},~~~~\\textrm{for}~~~~S>S_\\star,\n\\end{displaymath}\nwith the parameters $N_s = 25$ $mJ^{-2}deg^{-2}$, $S_\\star = 8$ [mJy], $\\beta_1 = 2$ and $\\beta_2 = 18$. \n\\end{enumerate}\n\n\n\\begin{thebibliography}{9}\n\n\n{\\footnotesize\n\n\\bibitem{Simpson:2014}\nJ. M. Simpson, et al.,\nApJ, 788 (2014) 125.\n\n\n\\bibitem{Lima:2010a}\nM. Lima, B. Jain, M. Devlin, \nMNRAS, 406 (2010) 2352.\n\n\\bibitem{Lima:2010b}\nM. Lima, B. Jain, M. Devlin,  J. Aguirre, \nApJL, 717 (2010) 31.\n\n\\bibitem{Wardlow:2013}\nJ.L.~Wardlow, et al.,\nApJ 762 (2013). \n\n\\bibitem{Takada:2003}\nM.~Takada, B. Jain,\nMNRAS 344 (2003) 857. \n\n\\bibitem{Diemer:2014}\nB.~Diemer, A. V. Kravtsov,\narXiv:1407.4730. \n\n\\bibitem{Evrard:2008}\nA.~E. Evrard et al.,\nApJ 672 (2008) 122.\n\n\\bibitem{Sheth:1999}\nR. K. Sheth, G. Tormen, \n MNRAS  308 (1999) 119.\n}\n\\end{thebibliography} \n\\end{document}\n\n", "meta": {"hexsha": "789d6c70103a4b49c31d88144c9cd0cd40f48ed8", "size": 10422, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "LaTeX/SMGs_summary2.tex", "max_stars_repo_name": "sbussmann/Bussmann2015", "max_stars_repo_head_hexsha": "38515be0b8973a66e4e509a3a25369b4af0a5a85", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LaTeX/SMGs_summary2.tex", "max_issues_repo_name": "sbussmann/Bussmann2015", "max_issues_repo_head_hexsha": "38515be0b8973a66e4e509a3a25369b4af0a5a85", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-02-01T20:19:57.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-01T20:19:57.000Z", "max_forks_repo_path": "LaTeX/SMGs_summary2.tex", "max_forks_repo_name": "sbussmann/Bussmann2015", "max_forks_repo_head_hexsha": "38515be0b8973a66e4e509a3a25369b4af0a5a85", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.1603773585, "max_line_length": 702, "alphanum_fraction": 0.7154097102, "num_tokens": 3417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.33693128819574125}}
{"text": "\\chapter{A Second Approach : Constraint Based Learning}\n\nAs seen in the previous chapter, the initial approach suffered from significant difficulty scaling. Even simple two argument functions took upwards of 400 seconds to complete. This was mainly due to the sheer size of the ground learning task, and the complexity from combinations of rule and where predicates.\n\n\\section{Top Down Vs. Bottom Up}\nThe main issue with the interpreted approach is that it is bottom-up. To learn the output of a rule, it must first iterate down the expression tree (shown in Figure \\ref{fig:expr_tree_2}), calculate the value of each simple sub-expression, then iterate back up the tree combining values until a value is known for the entire rule body. My second approach overcomes this issue by implementing a top down approach. \\\\ \\\\\n\n\\begin{figure}[h!]\n\\centering\n\\includegraphics[width=0.55\\textwidth]{C1/expression_tree.png}\n\\caption{Expression tree for a simple expression}\n\\label{fig:expr_tree_2}\n\\end{figure}\n\\mbox{}\\\\\nThe idea behind this new approach is simple. By maintaining an ``equality constraint'', the tool keeps track of what each expression is supposed to be equal to (as defined by the input examples). Then, as the program iterates down the expression tree, it fails if it ever finds some easily provable equality failure, i.e 1 = 2. \\\\ \\\\\nFor example, if it knows that \\lstinline{call(f, 2) = 5} and that the body of function f is \\lstinline{(2 * X) + 1}, then it can deduce that \n\\begin{align*}\n(2*2) + 1 &= 5 \\\\\n(2*2) &= 4 \\\\\n2 &= 2\n\\end{align*}\nSo there are no contradictions. \\\\ \\\\\nHowever, if instead there is an example stating that \\lstinline{call(f, 2) == 6}, with the same function, then instead we get %{\n\\begin{align*}\n(2*2) + 1 &= 6 \\\\\n(2*2) &= 5 \\\\\n\\end{align*}\nWhich fails because 5 is not a multiple of 2.\n\n\\subsection{Dealing with termination}\nOne issue with this new approach is that it does not automatically handle programs which do not terminate. Whilst these programs do not stop clingo from finding a solution, they are incorrect as the generated constraints never become simple enough to have a contradiction be proved. \\\\ \\\\\nTo deal with this, the tool has to check input examples for termination. While this is typically an undecidable problem, for my small target language it is decidable and computable. To represent this in ASP, there needed to be a way to represent the next step of execution of an expression. For example, we can say that \\lstinline!next_step(add(1, mul(2, 3)), mul(2, 3))!, meaning that it next evaluates \\lstinline!mul(2, 3)!. \\\\ \\\\\nI then define termination as :\n\\begin{itemize}\n\\item If an expression is simple, containing only constants, then it terminates.\n\\item If the next step of an expression terminates, then that expression also terminates.\n\\end{itemize}\n\\mbox{}\\\\\nThis approach is fairly efficient as it as another top down approach, and generates a similar number of rules in the ground program as the constraint checking rules.\n\\mbox{}\\\\\n\\section{ASP Representation}\nI represent this approach using the following ASP predicates.\n\n\\begin{center}\n\\begin{tabular}{| c | m{0.7\\linewidth} |}\n\\hline\n\\textbf{ASP Term} & \\textbf{Semantics} \\\\\n\\hline\n\\lstinline!eq(Expr, Val)! \n&\n\\mbox{}\\newline\nAn equality constraint. Expr, when evaluated, should equal Val. \\newline\n\\\\\n\\hline\n\\lstinline!is_call(call(F, Expr))!\n&\n\\mbox{}\\newline\nRepresents if a function is called. Used to generate more ground skeleton rules. \\newline\n\\\\\n\\hline\n\\lstinline!terminates(Expr)! \n&\n\\mbox{}\\newline\nRepresents if an expression terminates. \\newline\n\\\\\n\\hline\n\\lstinline!next_step(A, B)!\n&\n\\mbox{}\\newline\nThe next step of the execution of expression A is expression B.\\newline\n\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\mbox{}\\\\\nNow, these predicates are used in the following rules. \\\\\n\n\\lstinputlisting[language=Prolog, firstline=32, lastline=32, firstnumber=32, label=lst:eq_gen, caption=Equality generation]{../ASP/eq/eq_rules.lp} \n\\mbox{} \\\\\n\\ref{lst:eq_gen} generates initial equality constraints given by the examples.  \\\\\n\n\\lstinputlisting[language=Prolog, firstline=33, lastline=33, firstnumber=33, label=lst:eq_const, caption=Equality contradiction]{../ASP/eq/eq_rules.lp} \n\\mbox{} \\\\\n\\ref{lst:eq_const} constrains equality on constants. The tool should fail if two different constants are equal. \\\\\n\n\\lstinputlisting[language=Prolog, firstline=34, lastline=37, firstnumber=34, label=lst:eq_const_mul, caption=Multiplication contradictions]{../ASP/eq/eq_rules.lp} \n\\mbox{} \\\\\n\\ref{lst:eq_const_mul} handles edge cases when dealing with multiplication. If multiplying any expression by 0, then it should be equal to 0, and if multiplying two things together, then the answer should be a multiple of them both. \\\\\n\n\\lstinputlisting[language=Prolog, firstline=38, lastline=38, firstnumber=38, label=lst:term_constraint, caption=Termination contradiction]{../ASP/eq/eq_rules.lp} \n\\mbox{} \\\\\n\\ref{lst:term_constraint} handles termination. The tool fails if an input example does not terminate.\\\\\n\n\\lstinputlisting[language=Prolog, firstline=40, lastline=40, firstnumber=40, label=lst:is_call, caption=Is\\_call generation]{../ASP/eq/eq_rules.lp} \n\\mbox{} \\\\\n\\ref{lst:is_call} generates \\lstinline{is_call} predicates, which are used to generate more ground instances of skeleton rules. \\\\ %{\n\n\\lstinputlisting[language=Prolog, firstline=42, lastline=45, firstnumber=42, label=lst:eq_call, caption=Constraint propagation through function calls]{../ASP/eq/eq_rules.lp} \n\\mbox{} \\\\\n\\ref{lst:eq_call} handles propagation of equality constraints through function calls. If a called function is equal to some value, then the body of the function (with correct arguments) is also equal to that value. \\\\\n\n\\lstinputlisting[language=Prolog, firstline=47, lastline=60, firstnumber=47, label=lst:eq_math, caption=Constraint propagation through arithmetic operations]{../ASP/eq/eq_rules.lp} \n\\mbox{} \\\\\n\\ref{lst:eq_math} specifies generation of equality predicates with arithmetic, through use of the opposite operations. Addition terms in the head of the rule are necessary to handle edge cases such as division by zero. \\\\\n\n\\lstinputlisting[language=Prolog, firstline=62, lastline=63, firstnumber=62, label=lst:eq_pair, caption=Constraint propagation through tuples]{../ASP/eq/eq_rules.lp}\n\\mbox{}\\\\\n\\ref{lst:eq_pair} describes the propagation of equality constraints through tuple pairs. If a tuple of expressions is equal to a tuple of values, then the respective halves of the tuple are equal to each other. \\\\\n\n\\lstinputlisting[language=Prolog, firstline=65, lastline=66, firstnumber=65, label=lst:term, caption=Termination]{../ASP/eq/eq_rules.lp} \n\\mbox{} \\\\\n\\ref{lst:term} defines termination. If an expression is a constant, then it terminates, or if the next step of an expression terminates then that expression also terminates. \\\\\n\n\\lstinputlisting[language=Prolog, firstline=68, lastline=68, firstnumber=68, label=lst:next_init, caption=Next step initialisation]{../ASP/eq/eq_rules.lp} \n\\mbox{} \\\\\n\\ref{lst:next_init} generates the initial \\lstinline!next_step! predicates. If there exists an example input, then it is the next step of some arbitrary term \\lstinline!e!. \\\\\n\n\\lstinputlisting[language=Prolog, firstline=82, lastline=82, firstnumber=82, label=lst:next_is, caption=Next step grounding improvement]{../ASP/eq/eq_rules.lp} \n\\mbox{} \\\\\n\\ref{lst:next_is} exists to reduce the grounding. If any expression is a next step, we generate an \\lstinline{is_next_step} predicate, used in the remaining \\lstinline{next_step} rules.\\\\\n\n\\lstinputlisting[language=Prolog, firstline=70, lastline=73, firstnumber=70, label=lst:next_func, caption=Next step propagation through function calls]{../ASP/eq/eq_rules.lp} \n\\mbox{} \\\\\n\\ref{lst:next_func} handles the next step of function calls. The next step of a function call is the body of that function. \\\\\n\n\\lstinputlisting[language=Prolog, firstline=65, lastline=81, firstnumber=65, label=lst:next_match, caption=Next step propagation through arithmetic operations]{../ASP/eq/eq_rules.lp} \n\\mbox{} \\\\\n\\ref{lst:next_match} generates \\lstinline{next_step} predicates for arithmetic and tuples. The next step of an arithmetic expression is the argument that is not constant. %{\n\n\\section{Learning}\nThe actual learning task operates in a similar way to my initial approach. The task is again encoded as an ASP program, where the solution is a subset of the Answer Set of this program. \\\\ \\\\\nBy enumerating all possible rule bodies in the skeleton rules, a choice rule can be used to generate answer sets with each combination of skeleton rule, keeping the answer sets which do not fail the equality constraints. However, because \\lstinline!where! rules are no longer being used, the skeleton rules now contain full bodies. This means that unfortunately the number of skeleton rules becomes large, numbering in the thousands for even simple tasks. To avoid this scaling poorly once again, I decided to implement a number of simple optimisations.%{\n\n\\subsection{Using inbuilt arithmetic}\nAs part of the first approach, arithmetic was represented with my own predicates \\lstinline{add(A, B)}, \\lstinline{sub(A, B)} and \\lstinline{mul(A, B)} because the tool needed to evaluate expressions that the grounder would not be able to compute (i.e the value of function calls or where variables). \\\\ \\\\ %{\nHowever, in my new approach I have made partial use of the clingo inbuilt arithmetic. If inside function arguments, or the rule body has no function calls at all, then the tool knows that all sub expressions will be arithmetic and it can make use of the simple \\lstinline{+, -} and \\lstinline{*}. \\\\ \\\\\nThe main advantage of this approach is that it vastly reduces the ground output. As the inbuilt operations are computed by the grounder, if two different expressions compute the same output number, then they are not repeated in the ground output. For example, \\lstinline{X + X} and \\lstinline{2 * X} are semantically equivalent, so when ground with \\lstinline!X = 3! both produce the term \\lstinline!6!, corresponding to one output rule.\n\n\\section{A Worked Example : Greatest common divisor}\nOnce again I will use Euclid's algorithm for the Greatest Common Divisor \\cite{Euclid} to illustrate this new approach. Because the tool still does not have modulo as part of its target language, the simplified definition is used: \\\\\n\n\\lstinputlisting[language=Haskell, firstline=2, lastline=5]{../ASP/eq/gcd.lp} \n\\mbox{} \\\\\nAs input, I will be using the following examples : \\\\\n\n\\lstinputlisting[language=Prolog, firstline=34, lastline=40]{../ASP/eq/gcd.lp} \n\\mbox{} \\\\\nWhich cover both cases $(X < Y)$ and $(X > Y)$ while also not being too simplistic. \\\\ \\\\\nAfter running the learning task, the resulting Answer Set contains the terms: \\\\\n\n\\begin{lstlisting}\nchoose(1,2).\nchoose(2,150, 0).\nchoose(3,159, 1, 1).\n\\end{lstlisting}\n\\mbox{} \\\\\nThese terms correspond to the following skeleton rules : \\\\\n\n\\begin{lstlisting}\nrule(R, gcd, (N0, N1), N0) :- is_call(call(gcd, (N0, N1))), choose(R, 2). \n\nrule(R, gcd, (N0, N1), call(gcd, ((N0 - N1), (N1 - 0)))) :- \n\t\tis_call(call(gcd, (N0, N1))), \n\t\tchoose(R, 150, 0).\n\nrule(R, gcd, (N0, N1), call(gcd, ((N1 * 1), (N0 * 1)))) :- \n\t\tis_call(call(gcd, (N0, N1))), \n\t\tchoose(R, 190).\n\\end{lstlisting}\n\\mbox{} \\\\\nWhich then corresponds to the Haskell program (simplified for readability):\n\n\\begin{lstlisting}\ngcd x y\n\t| x == y = x\n\t| x > y\t = gcd (x - y) y\n\t| x < y\t = gcd y x\n\\end{lstlisting}\n\\mbox{} \\\\\nWhat is interesting is that whilst it has not learned the exact target program, the learned program is still correct. This is due to the optimisations preferring rules with shorter bodies.\\\\ \\\\\nTo see why this result is returned, it is useful to look at the corresponding \\lstinline{eq} predicates for each example. \\\\ \\\\%{\nThe example \\lstinline{example(call(gcd,(8,12)),4)} produces the terms :\\\\ %{\n\\begin{multicols}{2}\n\\begin{lstlisting}\neq(call(gcd,(8,12)),4). \neq(call(gcd,(12,8)),4).\neq(call(gcd,(4,8)),4).\neq(call(gcd,(8,4)),4).\neq(call(gcd,(4,4)),4).\neq(4, 4).\nnext_step(e,call(gcd,(8,12))).\nnext_step(call(gcd,(8,12)),call(gcd,(12,8))).\nnext_step(call(gcd,(12,8)),call(gcd,(4,8))).\nnext_step(call(gcd,(4,8)),call(gcd,(8,4))).\nnext_step(call(gcd,(8,4)),call(gcd,(4,4))).\nnext_step(call(gcd,(4,4)),4).\n\\end{lstlisting}\n\\end{multicols}\n\\mbox{}\\\\\nBecause these terms are all created without constraints failing, the respective rule bodies are returned as a solution.\n\n\\section{Performance}\nWhile this new approach does perform better than the old one, it still suffers from a lot of the same issues limiting performance. \\\\ \\\\\nBecause of the large number of combinations of skeleton rules, they can still grow very large very quickly, lowering the performance of my tool. In addition, expanding the language bias to different types also has an adverse effect on this.\n\n\\subsection{Reducing the language bias}\nAs a way to deal with the explosive expansion of skeleton rules, I implemented a way to help contain this by artificially limiting the language bias. \\\\ \\\\\nBy removing operations from the bias that will not be used in the output functions, the tool can remove a large number of skeleton rules that will have no effect on the output of the learning task. In a similar way, learning can be limited to only tail recursive programs, meaning that the skeleton rules only use inbuilt arithmetic operations, further increasing performance. \\\\ \\\\\nOf course, this method for improving performance is limited by the knowledge of the user. If they have no idea what the output function will look like, this is completely unhelpful, but in many cases they may have even a small idea of what operations will be used. Alternatively, users can iteratively add operations to the background knowledge, starting with a minimal set and gradually increasing it until a valid solution is found.\n\n\\pagebreak\n\\section{Full ASP Listing}\n\\lstinputlisting[firstline=32, firstnumber=32]{../ASP/eq/eq_rules.lp}\n\n\\pagebreak\n%\\renewcommand\\bibname{{References}}\n%\\bibliography{References}\n%\\bibliographystyle{plain}", "meta": {"hexsha": "3b9afccf8ebbe5929bdd1c8006e48a7333f1e5a3", "size": 14117, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/C4/chapter4.tex", "max_stars_repo_name": "roddejams/program-synthesis", "max_stars_repo_head_hexsha": "acca214241e9e7d7ff5c344039778dbd967a8008", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "report/C4/chapter4.tex", "max_issues_repo_name": "roddejams/program-synthesis", "max_issues_repo_head_hexsha": "acca214241e9e7d7ff5c344039778dbd967a8008", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/C4/chapter4.tex", "max_forks_repo_name": "roddejams/program-synthesis", "max_forks_repo_head_hexsha": "acca214241e9e7d7ff5c344039778dbd967a8008", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 64.7568807339, "max_line_length": 555, "alphanum_fraction": 0.7580930793, "num_tokens": 3698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.3369312803165705}}
{"text": "\\begin{figure}\n\\begin{center}\n\\includegraphics[width=0.9\\textwidth]{figs/inferred_props.pdf}\n\\caption{\n    Comparison between the true galaxy properties, $\\theta_{\\rm true}$, and\n    those inferred from SED modeling of mock observations, $\\hat{\\theta}$. \n    From the left to right columns, we compare $\\log M_*$, $\\log \\avgsfr$, \n    $\\log Z_{\\rm MW}$, $\\tage$ and $\\tauism$. \n    The inferred galaxy properties are derived from SED modeling of mock\n    spectra (top), photometry (middle), and spectrophotometry (bottom). \n    \\edits{\n        For each simulated galaxy, we plot 10 samples drawn from the\n        marginalized posterior of $\\theta$.\n        We also include violin plots, whose widths represent the marginalized\n        posteriors, for a handful of randomly selected galaxies.\n    }\n    \\emph{The posteriors demonstrate that, overall, we can derive accurate and \n    precise constraints on certain galaxy properties from joint SED modeling of\n    DESI photometry and spectra.}\n    } \\label{fig:prop_inf}\n\\end{center}\n\\end{figure}\n\n\\section{Results} \\label{sec:results}\n%\\subsection{Inferred Galaxy Properties}\nThe goal of this work is to demonstrate the precision and accuracy of inferred\ngalaxy properties for PROVABGS. \nWe apply our SED modeling to the mock observables of 2,123 \\lgal~galaxies.\nFrom the posterior distributions of the SPS parameters, we derive the following\nphysical galaxy properties: stellar mass ($M_*$), SFR averaged over 1 Gyr\n($\\avgsfr$), mass-weighted stellar metallicity ($Z_{\\rm MW}$), mass-weighted\nstellar age ($\\tage$), and diffuse-dust optical depth ($\\tau_{\\rm ISM}$).\n$M_*$ and $\\tau_{\\rm ISM}$ are SPS model parameters, while $\\avgsfr$, \n$Z_{\\rm MW}$, and $\\tage$ are derived as \n\\begin{equation} \\label{eq:prop_eqs}\n    \\avgsfr = \\frac{\\int\\limits_{t_{\\rm age} - {\\rm 1 Gyr}}^{t_{\\rm age}}{\\rm\n    SFH}(t)\\,{\\rm d}t}{{\\rm 1 Gyr}}, \\quad\n    Z_{\\rm MW} = \\frac{\\int\\limits_0^{t_{\\rm age}}{\\rm SFH}(t)\\,{\\rm\n    ZH}(t)\\,{\\rm d}t}{M_*}, \\quad{\\rm and}\\quad\n    \\tage = \\frac{\\int\\limits_0^{t_{\\rm age}}{\\rm SFH}(t)\\,t\\,{\\rm d}t}{M_*}.\n\\end{equation} \n\nIn Figure~\\ref{fig:prop_inf}, we compare the galaxy properties inferred from\nSED modeling the mock observations, $\\hat{\\theta}$, to the true (input) galaxy\nproperties, $\\theta_{\\rm true}$, of the simulated galaxies.\nFrom left to right, we compare $\\log M_*$, $\\log \\avgsfr$, $\\log Z_{\\rm MW}$,\n$\\tage$, and $\\tauism$ in each column.  \nThe inferred properties in the top, middle, and bottom rows are derived from\nSED modeling of spectra, photometry, and spectrophotometry, respectively.\n\\edits{\n    In each panel, we represent $\\hat{\\theta}$ by plotting 10 samples from the\n    marginalized posterior for each simulated galaxy. \n    We also include violin plots of  $\\hat{\\theta}$, where the width of the\n    marker represents the marginalized posterior distribution of $\\theta$, for\n    a handful of randomly selected galaxies.\n    We note that in our SED modeling of spectra only, we do not include \n    $f_{\\rm fiber}$ so the true stellar mass in this case corresponds to \n    $f_{\\rm fiber} \\times M_*$, which has a different range than for the \n    photometry and spectrophotometry cases.\n}\nThe comparison demonstrates that \\emph{overall we robustly infer galaxy\nproperties using the {\\sc PROVABGS} SED modeling}. \n\nIn more detail, we find that we infer unbiased and precise constraints on\n$M_*$ throughout the entire $M_*$ range. \n%For spectra+photometry SED modeling, the posteriors have $\\sigma_{M_*}\\sim0.06$ dex.\nWe also infer robust $\\avgsfr$ above $\\log \\avgsfr > -1$ dex; below this limit,\nhowever, the inferred $\\avgsfr$ are significantly less precise and\noverestimate the true $\\avgsfr$. \nThis bias at low $\\avgsfr$ is caused by model priors, which we discuss in\nfurther detail later in Section~\\ref{sec:discuss} and\nAppendix~\\ref{sec:model_priors}. \nBoth $Z_{\\rm MW}$ and $\\tage$ are not precisely constrained. \n\\edits{\n    The violin plots suggest that the inferred $Z_{\\rm MW}$ overestimate the\n    true $Z_{\\rm true}$.\n}\nFor $\\tage$, the posteriors are less precise for galaxies with older stellar\npopulations and they reveal the log-spaced $\\tlb$ binning used in our\nSPS model for $\\tage > 6$ Gyr.\nLastly, $\\tauism$ is overall accurately inferred for galaxies with low\n$\\tauism$ but appears to be underestimated for high $\\tauism$.\n\nThe overall constraints on galaxy properties for the mock observations is\nencouraging due to the significant differences in the forward model used to\ngenerate the observations and the SPS model used in the SED modeling. \nFirst, the SFHs and ZHs in the mock observations are taken directly from\n\\lgal~simulation outputs while the SFH and ZH parameterization in the SPS model\nis based on NMF bases fit to Illustris galaxies.\nSecond, in the forward model, we construct the SED of the bulge and disk\ncomponents of the simulated galaxies separately: the components have separate\nSFHs and ZHs. \nThe SPS model treats all galaxies as having one component. \nLastly, we use different dust prescriptions: \\cite{mathis1983} dust\nattenuation curve in the forward model and \\cite{kriek2013} dust attenuation\ncurve in the SPS model. \nDespite these significant differences, our constraints on certain galaxy\nproperties are unbiased and precise. \n\nFigure~\\ref{fig:prop_inf}, also highlights the advantages of jointly modeling\nspectra and photometry. \nComparing the constraints from spectrophotometry (bottom) versus photometry\nalone (middle), we find that including spectra significantly tightens the\nconstraints for all properties. \nIn addition, including spectra also appears to reduce biases of the\nconstraints. \nFor instance, with only photometry, we derive significantly more biased\n$\\avgsfr$ constraints.\nThis is due to the limited constraining power of photometry, which allows the\nposteriors to be dominated by model priors. \nAdding spectra, significantly increases the contribution of the likelihood and\nameliorates this effect. \n%Therefore, joint SED modeling of spectra and photometry \n\nBeyond qualitative comparisons of the posterior, we want to quantify the\nprecision and accuracy of the inferred galaxy properties. \nLet $\\Delta_{\\theta,i}$ be the discrepancy between the inferred and true\nparameters for each galaxy: \n$\\Delta_{\\theta,i} = \\hat{\\theta}_i - \\theta^{\\rm true}_i$.\nThen, if we assume that $\\Delta_{\\theta,i}$ are sampled from a Gaussian\ndistribution,\n\\begin{equation} \\label{eq:eta_gauss}\n    \\Delta_{\\theta,i} \\sim \\mathcal{N}(\\mu_{\\Delta_{\\theta}}, \\sigma_{\\Delta_{\\theta}}),\n\\end{equation}\nthe mean ($\\mu_{\\Delta_{\\theta}}$) and standard deviation\n($\\sigma_{\\Delta_{\\theta}}$) of the distribution are population hyperparameters\nthat represent the accuracy and precision of the inferred posteriors for the\ngalaxy population. \nWe can infer $\\mu_{\\Delta_{\\theta}}$ and $\\sigma_{\\Delta_{\\theta}}$ using a\nhierarchical Bayesian framework~\\citep[\\emph{e.g.}][]{hogg2010,\nforeman-mackey2014, baronchelli2020}.\n\nLet $\\{{\\bfi X}_i\\}$ represent the photometry or spectrum of a galaxy\npopulation and $\\eta_\\Delta = \\{\\mu_{\\Delta_{\\theta}},\n\\sigma_{\\Delta_{\\theta}}\\}$ represent the population hyperparameters.\nOur goal is to constrain $\\eta_\\Delta$ from $\\{{\\bfi X}_i\\}$ --- \\emph{i.e.}\nto infer $p(\\eta_\\Delta \\given \\{{\\bfi X}_i\\})$.\nWe expand \n\\begin{align}\\label{eq:popinf}\np(\\eta_\\Delta \\given \\{{\\bfi X_i}\\}) \n    =&~\\frac{p(\\eta_\\Delta)~p( \\{{\\bfi X_i}\\} \\given \\eta_\\Delta)}{p(\\{{\\bfi X_i}\\})}\\\\\n    =&~\\frac{p(\\eta_\\Delta)}{p(\\{{\\bfi X_i}\\})}\\int p(\\{{\\bfi X_i}\\} \\given \\{\\theta_i\\})~p(\\{\\theta_i\\} \\given \\eta_\\Delta)~{\\rm d}\\{\\theta_i\\}.\n\\intertext{\n    $\\theta_i$ is the SPS parameters for galaxy $i$ and $p(\\{{\\bfi X_i}\\}\n    \\given \\{\\theta_i\\})$ is likelihood of the set of observations $\\{{\\bfi\n    X_i}\\}$ given the set of $\\{\\theta_i\\}$. \n    Since the likelihoods for each of the $N$ galaxies, $p(\\bfi X_i \\given\n    \\theta_i)$, are not correlated, we can factorize and write the expression\n    above as \n}\n    =&~\\frac{p(\\eta_\\Delta)}{p(\\{{\\bfi X_i}\\})}\\prod\\limits_{i=1}^N\\int p({\\bfi X_i} \\given \\theta_i)~p(\\theta_i \\given \\eta_\\Delta)~{\\rm d}\\theta_i\\\\\n    =&~\\frac{p(\\eta_\\Delta)}{p(\\{{\\bfi X_i}\\})}\\prod\\limits_{i=1}^N\\int\n    \\frac{p(\\theta_i \\given {\\bfi X_i})~p({\\bfi X_i})}{p(\\theta_i)}~p(\\theta_i\n    \\given \\eta_\\Delta)~{\\rm d}\\theta_i\\\\\n    =&~p(\\eta_\\Delta)\\prod\\limits_{i=1}^N\\int \\frac{p(\\theta_i \\given {\\bfi\n    X_i})~p(\\theta_i \\given \\eta_\\Delta)}{p(\\theta_i)}~{\\rm d}\\theta_i. \n\\intertext{\n    $p(\\theta_i \\given {\\bfi X_i})$ is the posterior for an individual galaxy,\n    so the integral can be estimated using the Monte Carlo samples from the\n    posterior: \n}\n    \\approx&~p(\\eta_\\Delta)\\prod\\limits_{i=1}^N\\frac{1}{S_i}\\sum\\limits_{j=1}^{S_i}\n    \\frac{p(\\theta_{i,j} \\given \\eta_\\Delta)}{p(\\theta_{i,j})}.\n    \\label{eq:popinf2}\n\\end{align} \n$S_i$ is the number of posterior samples and $\\theta_{i,j}$ is the $j^{\\rm th}$\nsample of galaxy $i$.\n$p(\\theta_{i,j} \\given \\eta_\\Delta) = p(\\Delta_{\\theta,i,j} \\given\n\\eta_\\Delta)$ is a Gaussian distribution and, hence, easy to evaluate. \n$p(\\theta_{i,j}) = 1$ since we use uninformative and Dirichlet priors\n(Table~\\ref{tab:params}). \nFinally, we derive the maximum a posteriori (MAP) value of $\\eta_\\Delta$ by\nmaximizing the $p(\\eta_\\Delta \\given \\{{\\bfi X_i}\\})$ posterior distribution.\nThis type of population inference is a major advantage of inferring full\nposteriors distributions of the galaxy properties.\nWe discuss the derivation and interpretation of the hyperparameters in more\ndetail in Appendix~\\ref{sec:hyper}.\n\n\\begin{figure}\n\\begin{center}\n    \\includegraphics[width=0.85\\textwidth]{figs/etas_v2.pdf}\n    \\caption{\n        The accuracy and precision of galaxy property posteriors from our\n        joint SED modeling of spectrophotometry, quantified using population\n        hyperparameters $\\eta_\\Delta = \\{\\mu_{\\Delta_{\\theta}},\n        \\sigma_{\\Delta_{\\theta}}\\}$, as a function of true galaxy property\n        (green). \n        We plot $\\theta_{\\rm true} + \\mu_{\\Delta_{\\theta}}$ in solid line and\n        represent $\\sigma_{\\Delta_{\\theta}}$ with the shaded region.\n        We include $\\eta_\\Delta$ for SED modeling of photometry alone (orange)\n        for comparison. \n        Including DESI spectra significantly improves both the accuracy and\n        precision of the inferred galaxy properties. \n        $\\log\\avgsfr$, $\\log Z_{\\rm MW}$, and $\\tage$ constraints are\n        significantly impacted by  priors imposed by the SPS model\n        (Appendix~\\ref{sec:model_priors}).\n        Discrepancies in the dust prescriptions between our SPS model and the\n        mock observations drive the bias in $\\tauism$.\n        Nevertheless, \\emph{we accurately and precisely infer: $\\log M_*$ for\n        all $M_*$, $\\log\\avgsfr$ above $\\log\\avgsfr > -1\\,{\\rm dex}$, and \n        $\\tage$ below $8\\,{\\rm Gyr}$.}\n        } \\label{fig:etas}\n\\end{center}\n\\end{figure}\n\nIn Figure~\\ref{fig:etas}, we present the accuracy ($\\mu_{\\Delta_{\\theta}}$) and\nprecision ($\\sigma_{\\Delta_{\\theta}}$) of our joint SED modeling of spectra and\nphotometry (green) as a function of true galaxy property. \n$\\mu_{\\Delta_{\\theta}}$ (solid) and $\\sigma_{\\Delta_{\\theta}}$ (shaded region)\nare the MAP values of $p(\\eta_\\Delta \\given \\{{\\bfi X_i}\\})$ posterior. \nIn each panel, we derive $p(\\eta_\\Delta \\given \\{{\\bfi X_i}\\})$ for \n$\\log M_*$, $\\avgsfr$, $\\log Z_{\\rm MW}$, $\\tage$, and $\\tauism$ in bins of\nwidths 0.2 dex, 0.5 dex, 0.05 dex, 0.5 Gyr, and 0.1, respectively. \nWe only include bins with more than ten galaxies. \nFor comparison, we include $\\eta_\\Delta$ for SED modeling of photometry alone\n(orange).\nWe also include $\\eta_\\Delta$ for $\\log\\zmw$ of galaxies with $r_{\\rm fiber} >\n20$ (black dot-dashed) and $\\eta_\\Delta$ for $\\tauism$ of galaxies\nwithout bulges (black dotted), which we discuss later. \n\n\\begin{figure}\n\\begin{center}\n    \\includegraphics[width=0.95\\textwidth]{figs/etas_photo.pdf}\n    \\caption{\n        Accuracy and precision of the galaxy properties inferred from joint SED\n        modeling of spectrophotometry as a function of $r_{\\rm fiber}$, $r$,\n        $g-r$, and $r-z$.\n        $r_{\\rm fiber}$ and $r$ magnitudes are proxies for spectral and\n        photometric SNR. \n        From the top to bottom rows, we present $\\eta_\\Delta$ for $\\log M_*$,\n        $\\log\\avgsfr$, $\\log Z_{\\rm MW}$, $t_{\\rm age, MW}$ and \n        $\\tau_{\\rm ISM}$.\n        We find a significant dependence on spectral SNR in the inferred \n        $\\log \\zmw$. \n        When the spectral SNR is low ($r_{\\rm fiber} > 20$), the prior on \n        $\\log \\zmw$ imposed by the SPS model dominate the posterior and\n        cause $Z_{\\rm MW}$ to be overestimated. \n        We find a significant color dependence on $\\log\\avgsfr$, $\\log Z_{\\rm\n        MW}$, and $\\tage$. \n        For $\\log\\zmw$ and $\\tage$, the dependence is driven by underlying\n        correlations with spectral SNR and true $\\tage$. \n        Meanwhile, $\\log\\avgsfr$ is overestimated for the reddest galaxies with\n        $r - z > 0.6$, which correspond to quiescent galaxies with $\\log\\avgsfr\n        < -1$ dex. \n        Otherwise we find no significant dependence on SNR or optical color. \n    }    \n    \\label{fig:eta_photo}\n\\end{center}\n\\end{figure}\n\nIn Figure~\\ref{fig:eta_photo}, we examine how the accuracy and precision of\nour galaxy parameter constraints are impacted by signal-to-noise ratio (SNR) or\nphotometric color. \nWe present $\\eta_\\Delta$ of our joint SED modeling of spectra and photometry as\na function of $r_{\\rm fiber}$, $r$, $g-r$, and $r-z$. \n$r_{\\rm fiber}$ and $r$ magnitudes serve as proxies of the SNR for the spectra\nand photometry, respectively. \nIn each row, we plot $\\eta_\\Delta$ for a different galaxy property: $\\log M_*$,\n$\\avgsfr$, $\\log Z_{\\rm MW}$, $\\tage$ and $\\tauism$ (from top to bottom).\n\n\\begin{figure}\n\\begin{center}\n    \\includegraphics[width=\\textwidth]{figs/etas_msfr.pdf} \n    \\caption{\n        Accuracy and precision of the galaxy properties inferred from joint SED\n        modeling of spectrophotometry as a function of the galaxies' true $M_*$\n        and $\\avgsfr$. \n        We present $\\mu_{\\Delta_{\\theta}}$ and $\\sigma_{\\Delta_{\\theta}}$ in\n        ($M_*$, $\\avgsfr$) bins for $\\log M_*$, $\\log\\avgsfr$, $\\log Z_{\\rm\n        MW}$, $t_{\\rm age, MW}$ and $\\tau_{\\rm ISM}$ in the top and bottom\n        panels respectively. \n        $\\log M_*$ is accurately and precisely constrained for all types of galaxies. \n        $\\log\\avgsfr$ is accurately and precisely constrained for all galaxies\n        except for quiescent galaxies with $\\log\\avgsfr < -1$ dex. \n        $\\log\\zmw$ is overestimated for star-forming galaxies, due to their\n        overall lower spectral SNR. \n        $\\tage$ is accurately and precisely constrained for star-forming\n        galaxies that have overall younger stellar populations. \n        $\\tauism$ is accurately and precisely constrained for all galaxies\n        except massive star-forming galaxies, which have high true $\\tauism$. \n    }\\label{fig:etas_msfr}\n\\end{center}\n\\end{figure}\n\nLastly, in Figure~\\ref{fig:etas_msfr}, we investigate whether there is any\nunderlying dependence in the inferred galaxy properties on the  \n$M_*$-${\\rm SFR}$ plane. \nIn the top and bottom panels, we present $\\mu_{\\Delta_{\\theta}}$ and \n$\\sigma_{\\Delta_{\\theta}}$ in $(\\log M_*, \\log\\avgsfr)$ bins for \n$\\log M_*$, $\\log\\avgsfr$, $\\log Z_{\\rm MW}$, $\\tage$ and $\\tauism$ (left to\nright).\nWe use $\\log M_*$ bins of width 0.225 dex and $\\log\\avgsfr$ bins of width \n0.25 dex for $\\log \\avgsfr > 0$ dex and 0.5 dex for $\\log \\avgsfr < 0$ dex. \nWe only present bins with more than 10 galaxies. \nOn the $M_*-{\\rm SFR}$ plane, we can examine whether the accuracy and precision\nof the inferred properties have significant dependencies for galaxy type. \n\nBased on Figures~\\ref{fig:etas}, \\ref{fig:eta_photo}, and~\\ref{fig:etas_msfr},\nwe draw the following conclusions on the accuracy and precision of the inferred\nposteriors for each galaxy property:\\\\\n\n% log M*\n\\noindent \\underline{\\emph{Inferred $\\log M_*$}}: \nOverall, we infer accurate and precise $\\log M_*$ from the {\\sc PROVABGS} SED\nmodeling. \nThere is no significant dependence in $\\mu_{\\Delta_{\\theta}}$ and\n$\\sigma_{\\Delta_{\\theta}}$ with true $\\log M_*$ throughout the $M_*$ range. \nWe accurately infer the true $M_*$ throughout ${\\sim}10^{9}$- $10^{12} M_\\odot$\nwith uniform precision of $\\sigma_{\\Delta_{\\log M_*}}{\\sim}0.1$ dex. \nWe also find no significant dependence on SNR for $M_*$ --- neither $r_{\\rm\nfiber}$ nor $r$ magnitudes significantly affect $\\mu_{\\Delta_{\\log M_*}}$ and\n$\\sigma_{\\Delta_{\\log M_*}}$.\nThere is a noticeable correlation with $g-r$ and $r-z$ color, which also\nappears in the $M_*-{\\rm SFR}$ plane. \nHowever, this correlation is small compared to the precision of our inferred\nposterior on $\\log M_*$. \nWhen we compare the $\\eta_\\Delta$ from spectrophotometry to $\\eta_\\Delta$ from\nphotometry we find that including DESI spectra increases both the accuracy and\nprecision of the constraints, especially at high $M_* > 10^{11}M_\\odot$. \\\\\n\n% log SFR \n\\noindent \\underline{\\emph{Inferred $\\log\\avgsfr$}}: \nWe infer accurate $\\log\\avgsfr$ for galaxies with $\\log\\avgsfr > -1$ dex with\n${\\sim} 0.1$ dex precision. \nIn fact, we find a $\\log \\avgsfr \\sim -1$ dex lower bound for the inferred\n$\\log \\avgsfr$.\nBelow this limit, we significantly overestimate $\\log \\avgsfr$, consistent with\nthe bias in Figure~\\ref{fig:prop_inf}, and the constraints are also\nsignificantly broader with $\\sigma_{\\Delta_{\\log M_*}}{\\sim}0.25 - 0.3$ dex.\nComparing $\\mu_{\\Delta_{\\theta}}$ and $\\sigma_{\\Delta_{\\theta}}$ from\nspectrophotometry versus from only photometry, we confirm that including\nspectra significantly improves the accuracy and tightens the $\\log\\avgsfr$\nconstraints.\nFor $\\avgsfr$ below $\\log\\avgsfr < -1$ dex, including spectra reduces the bias\n${\\sim}1$ dex --- an order of magnitude. \n\nWe find no significant correlation between the accuracy and precision of\n$\\avgsfr$ with spectral or photometric SNR.\nHowever, there is a more significant color dependence where we overestimate\n$\\log\\avgsfr$ by $\\mu_{\\Delta_{\\log\\avgsfr}}{>}0.5$ dex for the reddest galaxies\n($g-r > 1.5$ and $r-z> 0.6$).\nThe constraints for these galaxies are also significantly less precise:\n$\\sigma_{\\Delta_{\\log\\avgsfr}} \\sim 0.5$ dex. \nThe bias is also apparent in Figure~\\ref{fig:etas_msfr}: there is significant\nbias in the inferred for quiescent galaxies where we overestimate $\\avgsfr$. \n$\\avgsfr$ is also slightly underestimated for the most massive ($M_* >\n10^{11}M_\\odot$) star-forming galaxies. \nThese biases are consequences of our SPS model priors.\n$\\avgsfr$ is a derived quantity; hence, the uninformative priors we impose on\nSPS parameters induce non-uniform priors on them.\nOur SPS model imposes a prior on $\\log \\overline{\\rm SSFR}_{\\rm 1 Gyr}$\nthat is skewed towards the peaks at $\\sim$-10.4 dex\n(Appendix~\\ref{sec:model_priors}, Figure~\\ref{fig:model_prior}). \nConsequently, the posterior overestimates $\\avgsfr$ at low $\\avgsfr$ (red,\nquiescent galaxies) and underestimates $\\avgsfr$ at the highest $\\avgsfr$. \\\\\n\n% log Z_MW  \n\\noindent \\underline{\\emph{Inferred $\\log\\zmw$}}:  \nUnlike in Figure~\\ref{fig:prop_inf}, $\\eta_\\Delta$ in Figure~\\ref{fig:etas}\nclearly reveals the accuracy and precision of the posteriors on $\\log\\zmw$. \nWe find that $\\mu_{\\Delta_{\\theta}}$ depends significantly on the true $\\zmw$: \ninferred $\\log\\zmw$ is overestimated by ${\\sim}0.2$ dex below $\\log\\zmw <\n-2$ dex and slightly underestimated at the highest $\\log\\zmw > -1.6$ dex.\n$\\sigma_{\\Delta_\\theta} \\sim 0.15$ dex is uniform throughout the $\\zmw$ range.\nSimilar to $\\avgsfr$, the bias in inferred $\\zmw$ is a consequence of our SPS\nmodel priors. \nThe prior skews $\\log\\zmw$ constraints towards the peak of the prior at\n$\\log\\zmw\\sim-1.5$. \nFigure~\\ref{fig:etas} also includes $\\eta_\\Delta$ for posteriors derived from\nphotometry alone (orange), which demonstrates that including DESI spectra\nsubstantially improves the accuracy of the $\\log\\zmw$ constraints.\nSpectra reduces the overall bias on $\\zmw$ by $\\sim$0.3 dex. \nThe improvement comes from the likelihood contribution from DESI spectra\nreducing the relative contribution of the prior on the posterior. \n\nThis is also why we find that the posteriors overestimate $\\log\\zmw$ at \n$r_{\\rm fiber} > 20$ in Figure~\\ref{fig:eta_photo}.\nThese correspond to mock observations with low spectral SNR where the\ncontribution of the likelihood from the spectra is reduced and the prior on\n$\\log\\zmw$ has a larger effect.\nThe color dependence of $\\mu_{\\Delta_\\theta}$ for $\\zmw$ in\nFigure~\\ref{fig:eta_photo} is also a consequence of this spectral SNR\ndependence; so is the $M_*-{\\rm SFR}$ dependence in Figure~\\ref{fig:etas_msfr}.\nIf we exclude galaxies with low spectral SNR, both the color and $M_*-{\\rm\nSFR}$  dependences are substantially reduced: for $r_{\\rm fiber} < 20$\ngalaxies, we infer $\\log\\zmw$ with $\\mu_{\\Delta_\\theta}<0.15$ dex and\n$\\sigma_{\\Delta_\\theta}\\sim0.1$ (Figure~\\ref{fig:etas}; black dot-dashed). \nThe posteriors on $\\zmw$ further underscore the constraining power of DESI\nspectra. \\\\\n\n% t_age, MW \n\\noindent \\underline{\\emph{Inferred $\\tage$}}:  \nFigure~\\ref{fig:etas} confirms that we derive unbiased and precise constraints\non $\\tage$ out to $\\tage < 8$ Gyr. \nBelow this limit, we infer $\\tage$ with $\\sigma_{\\Delta_\\theta}{\\sim}0.5$ Gyr.\nFor galaxies with older stellar populations above this limit, the log-spaced\n$\\tlb$ binning in our SPS model (Section~\\ref{sec:sps}) expectedly\nunderestimates $\\tage$ constraints and produces larger uncertainties \n($\\sigma_{\\Delta_{\\tage}} \\gtrsim 1$ Gyr). \nMeanwhile, we find no significant SNR or color dependence in\nFigure~\\ref{fig:eta_photo}. \nAt $r - z > 0.6$, $\\tage$ is underestimated, but this is driven by the\ncorrelation between $r-z$ and true $\\tage$: the simulated galaxies with $r - z\n> 0.6$ in our sample have overall older stellar populations. \nIn Figure~\\ref{fig:etas_msfr}, we do not find a clear $M_*-{\\rm SFR}$\ndependence; however, $|\\mu_{\\Delta_{\\tage}}|$ is larger and constraints are\nsignificantly less precise for galaxies with older stellar populations below\nthe star-forming sequence.  \\\\\n\n\\noindent \\underline{\\emph{Inferred $\\tauism$}}:  \nLastly, we find that both the accuracy and precision of our $\\tauism$ depend\nsignificant only on the true $\\tauism$ value. \nThe inferred constraints increasingly underestimate $\\tauism$ with lower\nprecision for greater $\\tauism$.\nThe bias is due to discrepancies between the dust prescriptions of SPS model\nand the mock observations. \nFirst, we use a dust prescription with a different attenuation curve in the SPS\nmodel than in the forward model. \nThis places a strict limit on how accurately we can derive $\\tauism$.\nWe intentially introduce this discrepancy since we do not know the ``true''\nattenuation curve of observed galaxies in practice. \nAnother reason for the biased $\\tauism$ constraints is that we only attenuate\nthe stellar emission in the disk component of the simulated galaxies and not\nthe bulge component (Section~\\ref{sec:sed}).\nThe true $\\tauism$ is the optical depth for the disk component while our\n$\\tauism$ constraints correspond to the optical depth of dust attenuation\nfor the entire galaxies, a quantity that will be lower than the true $\\tauism$\ndepending on how much the bulge contributes to the SED. \nGiven these discrepancies, in this work we are primarily testing whether the\n{\\sc PROVABGS} SPS modeling can successfully marginalize over the effect of\ndust and derive robust constraints on the other galaxy properties.\n\nNevertheless, we find no significant SNR or color dependence on the accuracy\nand precision of $\\tauism$ constraints (Figure~\\ref{fig:eta_photo}). \nFurthermore, we find unbiased and precise $\\tauism$ constraints for all galaxies\nexcept star-forming galaxies above $M_* > 10^{11}M_\\odot$ where we underestimate \n$\\tauism$. \nMassive star-forming galaxies in this regime mainly have $\\tauism > 1$.\nIn Figure~\\ref{fig:etas}, we present a more apples-to-apples comparison of the\n$\\tauism$ constraints, where we present $\\eta_\\Delta$ for only galaxies without\nbulge contributions (black dotted). \nFor these galaxies, the bias in our $\\tauism$ constraints is reduced and\n$\\mu_{\\Delta_\\theta}<0.5$ throughout the $\\tauism$ range. \nOur constraints are still biased, however, due to the discrepant attenuation\ncurves. \nWe emphasize that the primary goal of dust prescription in our SPS model is to\nmarginalize out the effect of dust. \nBased on the accuracy and precision of the constraints on other galaxy\nproperties, the {\\sc PROVABGS} SPS model achieves this objective.  \n", "meta": {"hexsha": "d343b3b51b2ff808f76b5a8c1949ff6eeb7e0e52", "size": 24718, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/paper/results.tex", "max_stars_repo_name": "changhoonhahn/gqp_mc", "max_stars_repo_head_hexsha": "abdfadac2e7d7e12c1642743e2b3c6a6a6fe370b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-12-18T20:51:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T05:59:24.000Z", "max_issues_repo_path": "doc/paper/results.tex", "max_issues_repo_name": "changhoonhahn/gqp_mc", "max_issues_repo_head_hexsha": "abdfadac2e7d7e12c1642743e2b3c6a6a6fe370b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44, "max_issues_repo_issues_event_min_datetime": "2020-02-20T06:02:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-13T20:00:50.000Z", "max_forks_repo_path": "doc/paper/results.tex", "max_forks_repo_name": "changhoonhahn/gqp_mc", "max_forks_repo_head_hexsha": "abdfadac2e7d7e12c1642743e2b3c6a6a6fe370b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-10-04T22:25:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:05:03.000Z", "avg_line_length": 54.9288888889, "max_line_length": 150, "alphanum_fraction": 0.7176956064, "num_tokens": 7117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.5544704649604272, "lm_q1q2_score": 0.33693128031657044}}
{"text": "\\section{Theoretical Foundations}\n\\label{sec:Theoretical_Foundations}\nIn this experiment the Planck constant $h$ was determined. This is a physical constant that relates the frequency of a photon to the energy it carries. This section summarizes the theory and formulas necessary to understand the following experiments on ultrasound in section \\ref{sec:Evaluation}.\n\n%-------------------------------------------------------------------------------------------\n\\subsection{Electromagnetic Radiation}\n\\label{subsec:Electromagnetic_Radiation}\nThe various effects that occur during the propagation and interaction of electromagnetic radiation with material objects can be classified into wave and particle phenomena:\n\n\\textbf{Wave Phenomena:} Interference and diffraction are described by the wave theory of electromagnetic radiation. From this point of view, the radiation occurs in the form of electromagnetic waves, which can be represented by a continuous wave function \\cite{light_quantum}.\n\n\\begin{equation}\nc = \\lambda\\cdot f\n\\label{eq:wave_length_frequency}\n\\end{equation}\nwhere:\n\\begin{multicols}{2}\n\t\\begin{center}\n\t\t\\begin{conditions}\n\t\t\tc & speed of light in $\\,^{\\text{m}}\\!/_{\\text{s}}$ \\\\\n\t\t\t\\lambda & wave length in m\n\t\t\\end{conditions}\n\t\t\\begin{conditions}\n\t\t\tf & frequency in Hz\n\t\t\\end{conditions}\n\t\\end{center}\n\\end{multicols}\n\n\\textbf{Particle Phenomena:} Emission and absorption are described by the quantum theory of electromagnetic radiation. From this point of view, the radiation occurs in the form of photon current $\\gamma$ (also called light quantum), which interacts with single atoms, electrons etc. in individual quantum processes. This is subject to chance, which is why only probability statements can be made \\cite{light_quantum}.\n\n\\begin{equation}\nE_\\gamma = h\\cdot f = h\\cdot\\frac{c}{\\lambda}\n\\label{eq:energy_particle}\n\\end{equation}\nwhere:\n\\begin{multicols}{2}\n\t\\begin{center}\n\t\t\\begin{conditions}\n\t\t\tE_\\gamma & photon energy in J \\\\\n\t\t\th & Planck constant in J$\\cdot$s \\\\\n\t\t\tf & frequency in Hz\n\t\t\\end{conditions}\n\t\t\\begin{conditions}\n\t\t\tc & speed of light in $\\,^{\\text{m}}\\!/_{\\text{s}}$ \\\\\n\t\t\t\\lambda & wave length in m\n\t\t\\end{conditions}\n\t\\end{center}\n\\end{multicols}\n\nEnergy and impulse exchange between radiation and matter can only take place in such quanta. Equation \\ref{eq:energy_particle} shows that the magnitude is essentially determined by the Planck constant $h$ (also known as Planck's quantum of action) \\cite{light_quantum}.\n\nSince the 20\\textsuperscript{th} May 2019 the value of the Planck constant $h$ is exactly\n\\begin{equation}\nh = 6.626\\ 070\\ 15 \\cdot 10^{-34}\\ \\si{J}\\cdot\\si{s}.\n\\label{eq:plank_constant}\n\\end{equation}\nThe value of the Planck constant $h$ has been fixed due to the redefinition of the kilogram \\cite{planck_constant}.\n\nThe two illustrative models are in principle incompatible. On the one hand the wave, the most smudgy thing there is. On the other hand the particle, the most concentrated thing there is. The solution to this dilemma is known as wave-particle duality, which is a concept in quantum mechanics. It expresses the inability to fully describe the behavior of quantum-scale objects with the classical concepts \\flqq wave\\frqq\\ or \\flqq particle\\frqq\\ \\cite{light_quantum, wave_particle_duality}.\n\n\\newpage\n%-------------------------------------------------------------------------------------------\n\\subsection{Photoelectric Effect}\n\\label{subsec:Photoelectric_Effect}\nThe photoelectric effect is the absorption of light quanta by atoms, molecules or solids, in which the photon disappears and transfers part of its energy to an electron. In the case of atoms and molecules, free electrons with kinetic energy $E_k = E_\\gamma - E_B$ are formed in the first moment, which can then attach themselves to other particles. $E_B$ is the binding energy of an electron. However, the atoms involved in the process are much heavier, so the energy of these electrons can be neglected. In the case of interaction with solids, a distinction is made between the outer photoelectric effect and the inner photoelectric effect \\cite{light_quantum}.\n\n%-------------------------------------------------------------------------------------------\n\\subsubsection{Outer Photoelectric Effect}\n\\label{subsubsec:Outer_Photoelectric_Effect}\nThe light quanta knock photoelectrons out of the surface of metals, metal oxides and semiconductors. To release an electron, its binding energy has to be expended. This binding energy is called the electron work function $W_a$. The photo energy $E_\\gamma$ must be at least equal to the electron work function $W_a$ for this effect to occur. The process takes in a thin surface layer place, which corresponds to the penetration depth of the photons. Therefore, the photoelectrons suffer different energy losses and leave the surface with variable kinetic energy \\cite{light_quantum}.\n\n\\begin{equation}\n\\widehat{E}_k = E_\\gamma - W_a = h\\cdot f - W_a\n\\label{eq:outer_photoelectric_effect}\n\\end{equation}\nwhere:\n\\begin{multicols}{2}\n\t\\begin{center}\n\t\t\\begin{conditions}\n\t\t\t\\widehat{E}_k & max. kinetic energy in eV \\\\\n\t\t\tE_\\gamma & photon energy in eV \\\\\n\t\t\tW_a & electron work function in eV\n\t\t\\end{conditions}\n\t\t\\begin{conditions}\n\t\t\th & Planck constant in J$\\cdot$s \\\\\n\t\t\tf & frequency in Hz\n\t\t\\end{conditions}\n\t\\end{center}\n\\end{multicols}\n\nEquation \\ref{eq:outer_photoelectric_effect} shows the calculation of the maximum value of this kinetic energy. The electron work function is a surface property and only material-specific at extremely high purity. Absorbed contaminants such as gases, oxide films and other impurities can change the value significantly.Layers used to convert radiation into a photoelectron stream are called photocathodes. If such a layer is combined with a multiplier (resulting in a photomultiplier) a very sensitive radiation detector is obtained \\cite{light_quantum}.\n\n%-------------------------------------------------------------------------------------------\n\\subsubsection{Inner Photoelectric Effect}\n\\label{subsubsec:Inner_Photoelectric_Effect}\nThe light quanta that penetrate a semiconductor prodce additional charge carriers. It can be distinguished between photoconductors and photodiodes \\cite{light_quantum}.\n\n\\textbf{Photoconductors:} When irradiated, the charge carrier density and thus the conductivity increase. This is why they are sometimes also called photo resistors \\cite{light_quantum}.\n\n\\textbf{Photodiodes:} In the region of the p-n junction, the absorbed photons generate electron-hole pairs. Without an external source, the p-side is positively charged and the n-side is negatively charged, resulting in a photovoltage. This photovoltag can be as high as the diffusion voltage $U_d$. A corresponding current flows under load. Solar cells use this element operation. If an external voltage is applied in the reverse direction, a photocurrent flows in this direction. This current is proportional to the incident radiant power. This diode operation is used for photodetectors. The described processes only take place when the photon energy exceeds a material-specific threshold value, which is the release of an electron bound to the crystal lattice \\cite{light_quantum}.\n\n\\newpage\n%-------------------------------------------------------------------------------------------\n\\subsection{Counter-Field Method (Millikan)}\n\\label{subsec:Countervailing_Field_Method}\nThe counter-field method can be used to determine the kinetic energy of the photoelectrons. Figure \\ref{fig:millikan} displays this graphically. The photocathode $K$ to be investigated and the anode $A$, which serves as a collector for the photoelectrons, are located in an evacuated glass bulb. The electrons triggered by monochromatic light of wavelength $\\lambda$ have a maximum kinetic energy as shown in equation \\ref{eq:outer_photoelectric_effect} \\cite{light_quantum}.\n\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[scale=2]{millikan}\n\t\\caption{This figure shows how the counter-field method is used to determine the kinetic energy of the photoelectrons. The voltage $U$ is increased until the current $I_{ph}$ reaches zero. As soon as the current $I_{ph} = 0$, the voltage $U$ must be equal to the voltage $U_{KA}$ \\cite{light_quantum}.}\n\t\\label{fig:millikan}\n\\end{figure}\n\nIf the voltage between anode and cathode is positive, the electrons are still accelerated and the full photocurrent flows, determined by the incident radiation power. If an increasing countervoltage $U$ is applied, fewer and fewer electrons reach the anode until the photocurrent finally disappears at the critical countervoltage $U_o$. Due to the material-dependent contact potential $U_c$ that is present even without an external voltage between cathode and anode, the following equation \\ref{eq:millikan} applies for zero photocurrent \\cite{light_quantum}.\n\n\\begin{equation}\n\\widehat{E}_k = e\\cdot (U_o - U_c)\n\\label{eq:millikan}\n\\end{equation}\nwhere:\n\\begin{multicols}{2}\n\t\\begin{center}\n\t\t\\begin{conditions}\n\t\t\t\\widehat{E}_k & max. kinetic energy in eV \\\\\n\t\t\te & elementary charge ($\\approx 1.602\\cdot 10^{-19}\\ \\si{C}$)\n\t\t\\end{conditions}\n\t\t\\begin{conditions}\n\t\t\tU_o & critical counter-voltage in V \\\\\n\t\t\tU_c & contact potential in V\n\t\t\\end{conditions}\n\t\\end{center}\n\\end{multicols}\n\n\\newpage\n%-------------------------------------------------------------------------------------------\n\\subsection{Light-Emitting Diode (LED)}\n\\label{subsec:light-emitting_diode}\nThe luminous emission of LEDs is caused by the fact that electrons pass from the conduction energy band to the valence energy band. This means that the electrons change from a higher to a lower energy state. In a regular diode this energy is dissipated as heat. In the case of a light-emitting diode, on the other hand, it is mostly released as light. Figure \\ref{fig:led} shows this graphically. This process is the reversal process to the inner photoelectric effect \\cite{light_quantum}.\n\nThe relationship between the photon energy and the characteristic curve of an LED is given by equation \\ref{eq:led}. The diffusion voltage $U_d$ depends on the material, its doping and the geometric structure of the diode. Due to the fact, that light emitting diodes are highly doped, the Fermi energies are close to the band edges and $e\\cdot U_d$ is approximately equal to the band gap $E_g$ (usually a little bit smaller). $U_d$ roughly corresponds to the threshold voltage $U_K$ of the characteristic curve. Therefore, equation \\ref{eq:led_threshold} can be used as an approximation for the measurable threshold voltage and the wavelength of the emission of an LED \\cite{light_quantum}.\n\n\\begin{equation}\ne\\cdot U_K \\approx E_\\gamma\n\\label{eq:led}\n\\end{equation}\nthus:\n\\begin{equation}\nU_K \\approx \\frac{h}{e}\\cdot\\frac{c}{\\lambda}\n\\label{eq:led_threshold}\n\\end{equation}\nwhere:\n\\begin{multicols}{2}\n\t\\begin{center}\n\t\t\\begin{conditions}\n\t\t\tU_K & LED threshold voltage in V \\\\\n\t\t\tE_\\gamma & photon energy in eV \\\\\n\t\t\te & elementary charge ($\\approx 1.602\\cdot 10^{-19} \\si{C}$)\n\t\t\\end{conditions}\n\t\t\\begin{conditions}\n\t\t\th & Planck constant in J$\\cdot$s \\\\\n\t\t\tc & speed of light in $\\,^{\\text{m}}\\!/_{\\text{s}}$ \\\\\n\t\t\t\\lambda & wave length in m\n\t\t\\end{conditions}\n\t\\end{center}\n\\end{multicols}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[scale=1.2]{led}\n\t\\caption{Graphical representation of the inner workings of an LED. The p-n junction emits light when electrons cross it. The free electrons move from the conduction band to the valence energy band (lower energy level). To recombine the electrons and the holes, some portion of the energy is dissipated in the form of heat and light (release of photons) \\cite{led}.}\n\t\\label{fig:led}\n\\end{figure}\n", "meta": {"hexsha": "488040fa36e211f6fe914f2a2b8226622877560e", "size": 11722, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "glaL4_A_8_Light_Quantum/sections/theoretical_foundations.tex", "max_stars_repo_name": "MuellerDominik/Physics-Laboratory-Notebooks", "max_stars_repo_head_hexsha": "02836870e6d97a29b1857c956fbd58eb5933eede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "glaL4_A_8_Light_Quantum/sections/theoretical_foundations.tex", "max_issues_repo_name": "MuellerDominik/Physics-Laboratory-Notebooks", "max_issues_repo_head_hexsha": "02836870e6d97a29b1857c956fbd58eb5933eede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "glaL4_A_8_Light_Quantum/sections/theoretical_foundations.tex", "max_forks_repo_name": "MuellerDominik/Physics-Laboratory-Notebooks", "max_forks_repo_head_hexsha": "02836870e6d97a29b1857c956fbd58eb5933eede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 67.367816092, "max_line_length": 785, "alphanum_fraction": 0.7409145197, "num_tokens": 2854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3369231678652273}}
{"text": "\\chapter{Demo cases}\n\\section{2D cavity flow at $\\text{Kn}=0.075$}\n\\label{sec_cavity}\nThis demonstrational case is provided in the \\verb|demos| subdirectory of the dugksFoam source code package.\nThis case is a popular benchmark problem for validating numerical method for micro or rarefied gas flows.\nIt has been studied in Ref.~\\cite{zhulh15} using this solver,\nwhere you can find the detailed description of this problem.\nWe only mention some setting that need special attention for a new user.\nThe mesh file and setting have already been prepared in the case directory.\nSo you can run the dugksFoam directly.\n\nThe flow configuration is illustrated in Fig.~\\ref{ldc}.\nThe walls are diffusive boundaries.\nFor such a simple geometry, you can use the \\verb|blockMesh| shipped with the OpenFOAM to generate the structured mesh.\nRefer to the cavity flow tenurial case in the \\emph{OpenFOAM User's Guide} for the detailed usage of \\verb|blockMesh|.\nThe initial temperautre filed is uniform 273K, and the wall temperature is also 273K.\nIn this case, the Knudsen number Kn is 0.075 based on the initial density filed and the cavity width $L$.\nSo the mean free path is 0.075m.\nThe initial density field input in the \\verb|0/rho| file should be calculated from the mean free path provided the argon gas properties.\nRefer to ~\\cite{zhulh15} for the related formulations.\nWe also provide a simple Python script named \\verb|para.py| in the case's directory to compute the related parameters.\nYou can run it by \\verb|python para.py|.\n\n\nThe discrete velocities used are $28\\times28$ half-range Gauss-Hermite quadrature points.\nThe files \\verb|constant/Xis| and \\verb|constant/weights| can be generated by\n\\begin{verbatim}\n    setDV.py GH 337.196399395 28\n\\end{verbatim}\nwhere 28 is the number of discrete velocity in each direction, and 337.196399395 stands for the most probable speed of argon gas molecular at $T=273$K.\nRefer to Sec.~\\ref{sec_dv} for more details about settings of discrete velocities.\n\nFig.~\\ref{ldc_UT} show some of the results of this case.\nYou can also compare the results with those in \\cite{zhulh15} in detail.\n\n\\begin{figure}\n  \\centering\n  % Requires \\usepackage{graphicx}\n  \\includegraphics[width=0.4\\textwidth]{img/ldc.pdf}\n  \\caption{Lid-driven cavity flow}\\label{ldc}\n\\end{figure}\n\n\\begin{figure}[htbp]\n\\centering\n\\subfloat[]{\\includegraphics[width=0.48\\textwidth]{img/temperature.png}} ~\n\\subfloat[]{\\includegraphics[width=0.48\\textwidth]{img/U.png}}\n\\caption{\nResults of the cavity flow case. (a) Temperature contours and heat flux. (b) Velocity magnitude and streamlines.\n}\\label{ldc_UT}\n\\end{figure}\n\n% Local Variables:\n% TeX-master: \"dugksFoam\"\n% mode: latex\n% mode: flyspell\n% End:\n", "meta": {"hexsha": "fa2ff4eb15abd5593c95b5dfca8c1e95e1559b52", "size": 2706, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/demo.tex", "max_stars_repo_name": "zhulianhua/dugksFoam", "max_stars_repo_head_hexsha": "d28df85e5651c2585dce5aff8ad65ee5a61ad20a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 62, "max_stars_repo_stars_event_min_datetime": "2015-10-22T03:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T09:21:51.000Z", "max_issues_repo_path": "doc/demo.tex", "max_issues_repo_name": "zhulianhua/dugksFoam", "max_issues_repo_head_hexsha": "d28df85e5651c2585dce5aff8ad65ee5a61ad20a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2018-02-01T10:17:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-15T10:31:49.000Z", "max_forks_repo_path": "doc/demo.tex", "max_forks_repo_name": "zhulianhua/dugksFoam", "max_forks_repo_head_hexsha": "d28df85e5651c2585dce5aff8ad65ee5a61ad20a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 37, "max_forks_repo_forks_event_min_datetime": "2015-10-22T03:17:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-29T05:23:12.000Z", "avg_line_length": 47.4736842105, "max_line_length": 151, "alphanum_fraction": 0.7764227642, "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819874558604, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.33663142544877067}}
{"text": "\\documentclass[a4paper,12pt]{article}\n\\usepackage{lmodern}\n\\usepackage{pstricks}\n\\usepackage{pst-plot}\n\\usepackage{pst-coil}\n% https://www.ctan.org/pkg/pst-solides3d\n\\usepackage{pst-solides3d}\n\n\\pagestyle{empty}\n\\title{Hello World!}\n\\author{Author's Name}\n\n\\begin{document}\n\\maketitle\n\\thispagestyle{empty}\n\n\\section{PStricks Picture}\n\n\\begin{pspicture}(-5,-4)(5,4)\n\\psgrid[subgriddiv=1,griddots=10]\n\\psset{unit=1mm,linewidth=.25mm,hatchwidth=.2,hatchsep=1}\n\n\\rput(10,10){\n\n\\psline{->}(-20,0)(40,0)\n\\psline{->}(0,-30)(0,40)\n\\uput[ul](40,0){$x$}\n\\uput[dr](0,40){$y$}\n\\uput[ur](0,0){$O$}\n\n\\psset{linewidth=.5mm}\n\\pscircle(10,0){20}\n\\psarc[linestyle=dashed,dash=3 2](15,0){15}{0}{180}\n\\psarc[fillstyle=solid,fillcolor=lightgray](-5,0){5}{0}{180}\n\n\\pscircle{1}\n\\psframe[fillstyle=vlines,linecolor=white,linewidth=0](-3,-3)(3,-5)\n\\psline(-.5,-.5)(-3,-3)(3,-3)(.5,-.5)\n\n\\rput(5,20){ \\psframe*[framearc=.5,linecolor=gray](0,0)(10,8) }\n\\rput{90}(30,0){\n    \\pscircle{1}\t\\psline(-.5,-.5)(-2,-2)(2,-2)(.5,-.5)\n    \\psframe[fillstyle=vlines,linecolor=white,linewidth=0](-3,-3)(3,-5)\n    \\pscircle(0,-2.5){.5} \\psline(-3,-3)(3,-3)\n}\n\n% with pst-plot (functions given with reverse polish notation):\n\\parametricplot[linestyle=dotted,plotpoints=200,arrows=->]{0}{540}{%\n% -15*exp(-.002*t)*cos(t) + 15,  15*exp(-.002*t)*(-.002*cos(t)-sin(t)) \n    2.71828 .002 t mul neg exp -15 mul t cos mul 15 add\t%\n    2.71828 -.002 t mul exp 15 mul t cos -.002 mul t sin sub mul\n}\n% with pst-coil:\n\\pscoil[coilwidth=2,coilarm=2](10,-20)(10,-30)\n\\rput(10,-30){\n    \\psframe[fillstyle=hlines,linecolor=white,linewidth=0](-3,0)(3,-2)\n    \\psline(-3,0)(3,0)\n}\n} %rput(10,10)\n\n\\rput(-10,-30){\n\n\\psset{viewpoint=1000 2000 1000,Decran=2500,lightsrc=0 100 100,linewidth=.1}\n\\axesIIID[linewidth=.2,linecolor=green,arrowsize=5pt,arrowinset=0,\n\taxisemph={\\color{green}},labelsep=8pt](0,0,0)(40,40,35)\n\n\\psLineIIID[linecolor=red](20,0,0)(20,25,0)(20,25,30)(20,25,0)(0,25,0)\n\n\\psset{r=1,ngrid=4 10,linecolor=gray,action=none}\n\\psset{solidmemory}\n\\psSolid[object=cylindre,h=30,name=bAD,fillcolor=gray!50](20,0,0)\n\\psSolid[object=cylindre,h=25,name=bDE,fillcolor=gray!50,RotX=-90](20,0,30)\n\\psSolid[object=cylindre,h=20,name=bEB,fillcolor=gray!50,RotY=-90](20,25,30)\n\\psSolid[object=cylindre,h=30,name=bBC,fillcolor=gray!50](0,25,0)\n\\psSolid[object=fusion,action=draw**,base=bAD bDE bEB bBC]\n\\composeSolid\n\n\\psset{action=draw,linecolor=red}\n\n\\psLineIIID[linecolor=blue,linewidth=.7]{->}(20,0,0)(30,10,-10)\n\\psLineIIID(30,0,0)(30,10,0)(30,10,-10)(30,10,0)(20,10,0)\n\\uput[ul](-22,-20){$F_1$}\n\\psLineIIID[linecolor=blue,linewidth=.7]{<-}(20,0,30)(20,0,40)\n\\uput[ur](-18,30){$M_2$}\n\\psLineIIID[linecolor=blue,linewidth=.7]{->}(20,25,30)(30,25,30)\n\\uput[dr](-15,13){$F_3$}\n\\psLineIIID[linecolor=blue,linewidth=.7]{->}(0,25,30)(0,10,30)\n\\uput[u](10,20){$F_2$}\n\\psLineIIID[linecolor=blue,linewidth=.7]{->}(0,25,0)(5,20,10)\n\\psLineIIID(5,25,0)(5,20,0)(5,20,10)(5,20,0)(0,20,0)\n\\uput[u](5,0){$M_1$}\n\n} %rput(-10,-10)\n\\end{pspicture}\n\n\\section{So long...}\n... and thank you for the fish!\n\n\\end{document}\n", "meta": {"hexsha": "7ceded413d59f0e0becf34c80ab998db1d6e449b", "size": 3050, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "hello_world.tex", "max_stars_repo_name": "szazs89/jupyter_ex", "max_stars_repo_head_hexsha": "366079f54a8ac8f3d6e65d45ec79d4b2318bed40", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hello_world.tex", "max_issues_repo_name": "szazs89/jupyter_ex", "max_issues_repo_head_hexsha": "366079f54a8ac8f3d6e65d45ec79d4b2318bed40", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hello_world.tex", "max_forks_repo_name": "szazs89/jupyter_ex", "max_forks_repo_head_hexsha": "366079f54a8ac8f3d6e65d45ec79d4b2318bed40", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5, "max_line_length": 76, "alphanum_fraction": 0.668852459, "num_tokens": 1358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.3366314176512292}}
{"text": "\\graphicspath{{Ch3_2019_neurips/figs/}}\n\n\\chapter{{Understanding Attention and Generalization in Graph Neural Networks}\\label{ch:neurips2019}}\n\n\\input{Ch3_2019_neurips/prolog}\n\n\\section{Attention meets pooling in graph neural networks}\\label{sec:attn_intro}\n\nThe practical importance of attention in deep learning is well-established and there are many arguments in its favor~\\citep{vaswani2017attention}, including interpretability~\\citep{park2016attentive, deac2018attentive}.\nIn graph neural networks (\\gnns), attention can be defined over edges~\\citep{velickovic2017graph, zhang2018gaan} or over nodes~\\citep{lee2018graph}. In this work, we focus on the latter, because, despite being equally important in certain tasks, it is not as thoroughly studied~\\citep{lee2018attention}. To begin our description, we first establish a connection between attention and pooling methods.\nIn convolutional neural networks (CNNs), pooling methods are generally based on uniformly dividing the regular grid (such as one-dimensional temporal grid in audio) into local regions and taking a single value from that region (average, weighted average, max, stochastic, etc.), while attention in CNNs is typically a separate mechanism that weights $C$-dimensional input $\\X \\in \\mathbb{R}^{N \\times C}$:\n%\n\\begin{equation}\n\\label{eq:attn}\n\\Z = \\mathbf{\\alpha} \\odot \\X,\n\\end{equation}\n%\n\\noindent where $\\Z_i = \\mathbf{\\alpha}_i \\X_i$ - output for unit (node in a graph) $i$, $\\sum_i^N \\mathbf{\\alpha}_i = 1$, $\\odot$ - element-wise multiplication, $N$ - the number of units in the input (i.e. number of nodes in a graph).\n\nIn \\gnns, pooling methods generally follow the same pattern as in CNNs, but the pooling regions (sets of nodes) are often found based on clustering~\\citep{defferrard2016convolutional, shaham2018spectralnet, ying2018hierarchical}, since there is no grid that can be uniformly divided into regions in the same way across all examples (graphs) in the dataset.\nRecently, top-k pooling~\\citep{graphunet2018} was proposed, diverging from other methods: instead of clustering ``similar'' nodes, it propagates only part of the input and this part is not uniformly sampled from the input. Top-k pooling can thus select some local part of the input graph, completely ignoring the rest. For this reason at first glance it does not appear to be logical.\n\nHowever, we can notice that pooled feature maps in~\\cite[Eq.~2]{graphunet2018} are computed in the same way as attention outputs $\\Z$ in \\eqref{eq:attn} above, if we rewrite their Eq.~2 in the following way:\n%\n\\begin{equation}\n\\label{eq:top-k}\n%\t\\Z_i = \\mathbf{\\alpha}_i X_i, \\forall i \\in P, \\Z_i = \\emptyset, \\forall i \\notin P\n%\\[\n\\Z_i =\n\\begin{cases}\n\\mathbf{\\alpha}_i \\X_i,& \\forall i \\in P\\\\\n\\emptyset, & \\text{otherwise} ,\n\\end{cases}\n%\\]\n\\end{equation}\n%\nwhere $P$ is a set of indices of pooled nodes, $|P| \\leq N$, and $\\emptyset$ denotes the unit is absent in the output.\n\nThe only difference between \\eqref{eq:top-k} and \\eqref{eq:attn} is that $\\Z \\in \\mathbb{R}^{|P| \\times C}$, i.e. the number of units in the output is smaller or, formally, there exists a ratio $r=|P| / N \\leq 1$ of preserved nodes.\nWe leverage this finding to integrate attention and pooling into a unified computational block of a GNN.\nIn contrast, in CNNs, it is challenging to achieve this, because the input is defined on a regular grid, so we need to maintain resolution for all examples in the dataset after each pooling layer.\nIn \\gnns, we can remove any number of nodes, so that the next layer will receive a smaller graph. When applied to the input layer, this form of attention-based pooling also brings us interpretability of predictions, since the network makes a decision only based on pooled nodes.\n\n\\begin{figure}[t]\n\t\\begin{center}\n\t\t\\small\n\t\t\\begin{tabular}{ccc}\n\t\t\t{\\includegraphics[width=0.3\\textwidth, align=c, trim={0cm 6.5cm 20.7cm 6cm}, clip]{tasks}} &\n\t\t\t{\\includegraphics[width=0.27\\textwidth, align=c, trim={10cm 6cm 10.8cm 6.1cm}, clip]{tasks}} &\n\t\t\t{\\includegraphics[width=0.3\\textwidth, align=c, trim={20cm 6cm 0.3cm 6cm}, clip]{tasks}} \\\\\n\t\t\t(a) \\textsc{Colors} & (b) \\textsc{Triangles} & (c) \\mnistfull \\\\\n\t\t\\end{tabular}\n\t\\end{center}\n\t\\vspace{-10pt}\n\t\\caption{\\small Three tasks with a controlled environment we consider in this work. The values inside the nodes are ground truth attention coefficients, $\\mathbf{\\alpha}_i^{GT}$, which we find heuristically (see \\secref{\\ref{sec:datasets}}).}\n\t\\label{fig:tasks}\n\\end{figure}\n%\nDespite the appealing nature of attention, it is often unstable to train and the conditions under which it fails or succeeds are unclear.\nMotivated by insights of~\\citep{xu2018powerful} recently proposed Graph Isomorphism Networks (GIN), we design two simple graph reasoning tasks\nthat allow us to study attention in a controlled environment where we know ground truth attention.\nThe first task is counting colors in a graph (\\textsc{Colors}), where a color is a unique discrete feature. The second task is counting the number of triangles in a graph (\\textsc{Triangles}). We confirm our observations on a standard benchmark, \\mnistfull~\\citep{lecun1998gradient} (\\fig{\\ref{fig:tasks}}), and identify factors influencing the effectiveness of attention.\n\nOur synthetic experiments also allow us to study the ability of attention \\gnns to generalize to larger, more complex or noisy graphs. Aiming to provide a recipe to train more effective, stable and robust attention \\gnns, we propose a \\wsup~scheme to train attention, that does not require ground truth attention scores, and as such is agnostic to a dataset and the choice of a model.\nWe validate the effectiveness of this scheme on our synthetic datasets, as well as on \\mnistfull~and on real graph classification benchmarks in which ground truth attention is unavailable and hard to define, namely \\collab~\\citep{leskovec2007graph, shrivastava2014new}, \\proteins~\\citep{borgwardt2005protein}, and \\dd~\\citep{dobson2003distinguishing}.\n\n\\section{Model}\n\nWe study two variants of \\gnns: Graph Convolutional Networks (GCN)~\\citep{kipf2016semi} and Graph Isomorphism Networks (GIN)~\\citep{xu2018powerful}. One of the main ideas of GIN is to replace the \\textsc{Mean} aggregator over nodes, such as the one in GCN, with a \\textsc{Sum} aggregator, and add more fully-connected layers after aggregating neigboring node features. The resulting model can distinguish a wider range of graph structures than previous models~\\cite[Figure 3]{xu2018powerful}.\n\n\\subsection{Thresholding by attention coefficients}\nTo pool the nodes in a graph using the method from\\citep{graphunet2018} a predefined ratio $r=|P| / N$ must be chosen for the entire dataset \\eqref{eq:top-k}. For instance, for $r=0.8$ only 80\\% of nodes are left after each pooling layer. Intuitively, it is clear that this ratio should be different for small and large graphs.\nTherefore, we propose to choose threshold $\\tilde{\\mathbf{\\alpha}}$, such that only nodes with attention values $\\mathbf{\\alpha}_i > \\tilde{\\mathbf{\\alpha}}$ are propagated:\n%\n\\begin{equation}\n\\label{eq:top-k_ours}\n%\\Z_i = \\mathbf{\\alpha}_i \\X_i, \\forall\\ i: \\mathbf{\\alpha}_i > \\tilde{\\mathbf{\\alpha}}.\n\\Z_i =\n\\begin{cases}\n\\mathbf{\\alpha}_i \\X_i,& \\forall i: \\mathbf{\\alpha}_i > \\tilde{\\mathbf{\\alpha}} \\\\\n\\emptyset, & \\text{otherwise}.\n\\end{cases}\n\\end{equation}\n%\nNote, that dropping nodes from a graph is different from keeping nodes with very small, or even zero, feature values, because a bias is added to node features after the following graph convolution layer affecting features of neighbors. An important potential issue of dropping nodes is the change of graph structure and emergence of isolated nodes. However, in our experiments we typically observe that the model predicts similar $\\mathbf{\\alpha}$ for nearby nodes, so that an entire local neighborhood is pooled or dropped, as opposed to clustering-based methods which collapse each neighborhood to a single node. We provide a quantitative and qualitative comparison in \\secref{\\ref{sec:exper}}.\n\n\\subsection{Attention subnetwork}\nTo train an attention model that predicts the coefficients for nodes, we consider two approaches: (1)~Linear Projection~\\citep{graphunet2018}, where a single layer projection $\\mathbf{p} \\in \\mathbb{R}^C$ is trained: $\\mathbf{\\alpha}_{pre} = \\X \\mathbf{p}$; and (2)~DiffPool~\\citep{ying2018hierarchical}, where a separate \\gnn is trained:\n%\n\\begin{equation}\n\\label{eq:attn_gcn}\n\\mathbf{\\alpha}_{pre} = \\text{GNN}(\\A, \\X),\n\\end{equation}\n%\nwhere $\\A$ is the adjacency matrix of a graph.\nIn all cases, we use a softmax activation~\\citep{vaswani2017attention,park2016attentive} instead of tanh in~\\citep{graphunet2018}, because it provides more interpretable results  and ecourages sparse outputs: $\\mathbf{\\alpha} = \\text{softmax}(\\mathbf{\\alpha}_{pre})$.\nTo train attention in a supervised or \\wsup~way, we use the Kullback-Leibler divergence loss (see \\secref{\\ref{sec:arch_train}}).\n\nNote that the GNN used in \\eqref{eq:attn_gcn} is called an attention subnetwork because its outputs $\\mathbf{\\alpha} = \\text{softmax}(\\mathbf{\\alpha}_{pre})$ are used to weight the input node features $\\X$ according to \\eqref{eq:top-k_ours}: $\\Z = \\mathbf{\\alpha} \\odot \\X$. This way $\\mathbf{\\alpha}$ defines how much the following layers pay attention (or attend) to each of the nodes as we discuss in \\secref{\\ref{sec:attn_intro}}.\n\n\\subsection{ChebyGIN}\n\nIn some of our experiments, the performance of both GCNs and GINs is quite poor and, consequently, it is also hard for the attention subnetwork to learn. By combining GIN~\\citep{xu2018powerful} with ChebyNet~\\citep{defferrard2016convolutional}, we propose a stronger model, ChebyGIN.\nChebyNet is a multiscale extension of GCN~\\citep{kipf2016semi}, so that for the first scale, $k=0$, node features are node features themselves, for $k=1$ features are averaged over one-hop neighbors, for $k=2$ - over two-hop neighbors and so forth (see \\eqref{eq:cheb_graph_conv} in \\S~\\ref{sec:bg_gnn}).\nTo implement the \\textsc{Sum} aggregator in ChebyGIN, we multiply node features $\\X$ by a diagonal node degree matrix $\\D_{ii}=\\sum_j \\A_{ij}$ starting from $k=1$. We also add more fully-connected layers (denoted as $\\text{MLP}^{(l)}$) after feature aggregation as in GIN. Thus, following \\eqref{eq:cheb_graph_conv}, the $l$-th layer of our ChebyGIN is defined as:\n%\n\\begin{equation}\n\\label{eq:chebygin}\n\\X^{(l+1)} = \\text{MLP}^{(l)} \\Big(\\sum^{K-1}_{k=0} \\D_{ii}^{(k)} T_k(\\tilde{\\Lapl}) \\X^{(l)} \\W^{(l)}_k \\Big),\n\\end{equation}\n%\n\\noindent where $\\D_{ii}^{(k)} = \\mathbf{I}_N$ for $k=0$ and $\\D_{ii}^{(k)} = \\sum_j \\A_{ij}$ for $k > 0$. $T_k(\\tilde{\\Lapl})$ are the Chebyshev polynomials applied to a rescaled graph Laplacian $\\tilde{\\Lapl}$; $\\W^{(l)}_k$ are trainable weights. See a detailed description of these terms in \\S~\\ref{sec:bg_gnn} and the implementation details of ChebyGIN in our code \\url{https://github.com/bknyaz/graph_attention_pool/blob/master/chebygin.py}.\n\n\\section{Experiments}\n\\label{sec:exper}\nWe introduce the color counting task (\\textsc{Colors}) and the triangle counting task (\\textsc{Triangles}) in which we generate synthetic training and test graphs. We also experiment with MNIST images~\\citep{lecun1998gradient} and three molecule and social datasets. In \\colors, \\tri~and \\mnistfull~tasks (\\fig{\\ref{fig:tasks}}), we assume to know ground truth attention, i.e. for each node~$i$ we heuristically define its importance in solving the task correctly, $\\mathbf{\\alpha}_i^{GT} \\in [0,1]$, which is necessary to train (in the supervised case) and evaluate our attention models.\n\n\n\\subsection{Datasets}\n\\label{sec:datasets}\n\\densepar{\\textsc{Colors}.} We introduce the color counting task. We generate random graphs where features for each node are assigned to one of the three one-hot values (colors): [1,0,0] (red), [0,1,0] (green), [0,0,1] (blue). The task is to count the number of green nodes, $N_{green}$. This is a trivial task, but it lets us study the influence of initialization of the attention model $\\mathbf{p} \\in \\mathbb{R}^3$ on the training dynamics.\nIn this task, graph structure is unimportant and edges of graphs act like a medium to exchange node features. Ground truth attention is $\\mathbf{\\alpha}_i^{GT}=1 / N_{green}$, when $i$ corresponds to green nodes and $\\mathbf{\\alpha}_i^{GT}=0$ otherwise.\nWe also extend this dataset to higher $n$-dimensional cases $\\mathbf{p} \\in \\mathbb{R}^n$ to study how model performance changes with $n$.\nIn these cases, node features are still one-hot vectors and we classify the number of nodes where the second feature is one.\n\n\\densepar{\\textsc{Triangles}.} Counting the number of triangles in a graph is a well-known task which can be solved analytically by computing $\\text{trace}(\\A^3) / 6$, where $\\A$ is an adjacency matrix. This task turned out to be hard for \\gnns, so we add node degree features as one-hot vectors to all graphs, so that the model can exploit both graph structure and features. Compared to the \\textsc{Colors} task, here it is more challenging to study the effect of initializing $\\mathbf{p}$, but we can still calculate ground truth attention as $\\mathbf{\\alpha}_i^{GT}=T_i / \\sum_i T_i$, where $T_i$ is the number of triangles that include node $i$, so that $\\mathbf{\\alpha}_i^{GT} = 0$ for nodes that are not part of triangles.\n\n\\densepar{\\textsc{Mnist-75sp}.} \\textsc{Mnist}~\\citep{lecun1998gradient} contains 70k grayscale images of size 28$\\times$28 pixels. While each of 784 pixels can be represented as a node, we follow~\\citep{monti2017geometric, fey2018splinecnn} and consider an alternative approach to highlight the ability of \\gnns to work on irregular grids. In particular, each image can be represented as a small set of superpixels without losing essential class-specific information (see \\fig{\\ref{fig:test_subsets}}). We compute SLIC~\\citep{achanta2012slic} superpixels for each image and build a graph, in which each node corresponds to a superpixel with node features being pixel intensity values and coordinates of their centers of masses. We extract $N\\leq75$ superpixels, hence the dataset is denoted as \\mnist.\nEdges are formed based on spatial distance between superpixel centers as in~\\cite[Eq.~8]{defferrard2016convolutional}. Each image depicts a handwritten digit from 0 to 9 and the task is to classify the image. Ground truth attention is considered to be $\\mathbf{\\alpha}_i^{GT}=1 / N_{nonzero}$ for superpixels with nonzero intensity, and $N_{nonzero}$ is the total number of such superpixels. The idea is that only nonzero superpixels determine the digit class.\\looseness-1\n\n\\densepar{Molecule and social datasets.}\n\\label{sec:graph_data}\nWe extend our study to more practical cases, where ground truth attention is not available, and experiment with protein datasets: \\proteins~\\citep{borgwardt2005protein} and \\dd~\\citep{dobson2003distinguishing}, and a scientific collaboration dataset, \\collab~\\citep{leskovec2007graph, shrivastava2014new}.\nThese are standard graph classification benchmarks.\nA standard way to evaluate models on these datasets is to perform 10-fold cross-validation and report average accuracy~\\citep{yanardag2015deep, ying2018hierarchical}.\nIn this work, we are concerned about a model's ability to generalize to larger and more complex or noisy graphs, therefore, we generate splits based on the number of nodes. For instance, for \\proteins~we train on graphs with $ N \\leq 25$ nodes and test on graphs with $ 6 \\leq N \\leq 620$ nodes (see Table~\\ref{table:results_graphs} for details about splits of other datasets and results).\\looseness-1\n\n%A detailed description of tasks and model hyperparameters is provided in the \\apdx.\n\n%\\vspace{-10pt}\n\\subsection{Generalization to larger and noisy graphs}\n%\\vspace{-10pt}\nOne of the core strengths of attention is that it makes it easier to generalize to unseen, potentially more complex and/or noisy, inputs by reducing them to better resemble certain inputs in the training set. To examine this phenomenon, for \\textsc{Colors} and \\textsc{Triangles} tasks we add test graphs that can be several times larger (\\textsc{Test-Large}) than the training ones. For \\textsc{Colors} we further extend it by adding unseen colors to the test set (\\textsc{Test-LargeC}) in the format $[c_1, c_2, c_3, c_4]$, where $c_i=0$ for $i \\neq 2$ if $c_2=1$ and $c_i \\in [0,1]$ for $i \\neq 2$ if $c_2=0$, i.e.~there is no new colors that have nonzero values in a green channel. This can be interpreted as adding mixtures of red, blue and transparency channels, with nine possible colors in total as opposed to three in the training set (\\fig{\\ref{fig:test_subsets}}).\n\n\n\\newcommand{\\figwidth}{0.14\\textwidth}\n\\newcommand{\\rangeupper}[1]{\\tiny{($N\\leq#1$)}}\n\\newcommand{\\rangetwo}[2]{\\tiny{($#1<N\\leq#2$)}}\n\\begin{figure}[h!]\n    \\newcommand{\\figtasks}[2]{\\includegraphics[width=\\figwidth, align=c, trim=#1, clip]{#2}}\n    \\centering\n\t\\begin{center}\n\t\t\\scriptsize\n\t\t\\setlength{\\tabcolsep}{7pt}\n\t\t\\begin{tabularx}{\\textwidth}{ccccc}\n\t\t\t{\\rotatebox[origin=c]{90}{\\textsc{\\textbf{Colors}} }} &\n\t\t\t\\figtasks{{2cm 0.5cm 1.3cm 1.3cm}}{colors_train.pdf} &\n\t\t\t\\figtasks{{2cm 0.5cm 1.3cm 1.3cm}}{colors_test1.pdf} &\n\t\t\t\\figtasks{{2cm 0.5cm 1.3cm 1.3cm}}{colors_test2.pdf} &\n\t\t\t\\figtasks{{2cm 0.5cm 1.3cm 1.3cm}}{colors_test_mix.pdf} \\\\\n\t\t\t& \\textsc{Train} \\rangeupper{25} & \\textsc{Test-Orig} \\rangeupper{25} & \\textsc{Test-Large} \\rangetwo{25}{200} & \\textsc{Test-LargeC} \\rangetwo{25}{200} \\\\\n\t\t\t\\hline \\\\\n\t\t\\end{tabularx}\n\t\t\\setlength{\\tabcolsep}{21pt}\n\t\t\\begin{tabularx}{\\textwidth}{cccc}\n\t\t\t\\hspace{-25pt}\n\t\t\t\\multirow{2}{*}{\\rotatebox[origin=c]{90}{\\parbox{0.8cm}{\\textsc{\\textbf{Triangles}}}}} &\n\t\t\t\\figtasks{{1.5cm 0.7cm 0cm 0cm}}{triangles_train1.pdf} &\n\t\t\t\\figtasks{{1.5cm 0.7cm 0cm 0cm}}{triangles_test1.pdf} &\n\t\t\t\\figtasks{{1.5cm 0.7cm 0cm 0cm}}{triangles_test2.pdf} \\\\\n\t\t\t& \\textsc{Train} \\rangeupper{25} & \\textsc{Test-Orig} \\rangeupper{25} & \\textsc{Test-Large} \\rangetwo{25}{100}\\\\\n\t\t\t\\hline \\\\\n\t\t\\end{tabularx}\n\t\t\\setlength{\\tabcolsep}{12pt}\n\t\t\\begin{tabularx}{\\textwidth}{ccccc}\n\t\t\t\\hspace{-7pt} \\multirow{2}{*}{\\rotatebox[origin=c]{90}{\\parbox{0.9cm}{\\mbox{\\textbf{\\mnist}}}}} &\n\t\t\t\\figtasks{{0cm 0cm 0cm 0cm}}{7_train_75sp.pdf} &\n\t\t\t\\figtasks{{0cm 0cm 0cm 0cm}}{7_test_75sp.pdf} &\n\t\t\t\\figtasks{{0cm 0cm 0cm 0cm}}{7_noise0_4_test_75sp.pdf} &\n\t\t\t\\figtasks{{0cm 0cm 0cm 0cm}}{7_colornoise0_6_test_75sp.pdf} \\\\\n\t\t\t& \\textsc{Train}\\tiny{($N=64$)} & \\textsc{Test-Orig}\\tiny{($N=63$)} & \\textsc{Test-Noisy}\\tiny{($N=63$)} & \\textsc{Test-NoisyC}\\tiny{($N=63$)} \\\\\n\t\t\\end{tabularx}\n\t\\end{center}\n\t\\vspace{-10pt}\n\t\\caption{\\small Examples from training and test sets. For \\colors, the correct label is $N_{green}=4$ in all cases; for \\tri~$N_{tri}=3$ and color intensities denote ground truth attention values $\\mathbf{\\alpha}^{GT}$. The range of the number of nodes, $N$, is shown in each case. For \\mnist, we visualize graphs for digit 7 by assigning an average intensity value to all pixels within a superpixel. Even though superpixels have certain shapes and borders between each other (visible only on noisy graphs), we feed only superpixel intensities and coordinates of their centers of masses to our \\gnns.}\n\t\\label{fig:test_subsets}\n\t\\vspace{-8pt}\n\\end{figure}\n\nNeural networks (NNs) have been observed to be brittle if they are fed with test samples corrupted in a subtle way, i.e.~by adding a noise~\\citep{dodge2017study} or changing a sample in an adversarial way~\\citep{szegedy2013intriguing}, such that a human can still recognize them fairly well. To study this problem, test sets of standard image benchmarks have been enlarged by adding corrupted images~\\citep{hendrycks2019benchmarking}.\n\nGraph neural networks, as a particular case of NNs, inherit this weakness. The attention mechanism, if designed and trained properly, can improve a net's robustness by attending to only important and ignoring misleading parts (nodes) of data. In this work, we explore the ability of \\gnns with and without attention to generalize to noisy graphs and unseen node features. This should help us to understand the limits of \\gnns, and potentially NNs in general, with attention and conditions when it succeedes and when it does not. To this end, we generate two additional test sets for \\mnist. In the first set, \\textsc{Test-Noisy}, we add Gaussian noise, drawn from $\\mathcal{N}(0, 0.4)$, to superpixel intensity features, i.e.~the shape and coordinates of superpixels are the same as in the original clean test set. In the second set, \\textsc{Test-Noisy-C}, we colorize images by adding two more channels and add independent Gaussian noise, drawn from $ \\mathcal{N}(0, 0.6)$, to each channel (\\fig{\\ref{fig:test_subsets}}).\n\n\\subsection{Network architectures and training}\n\\label{sec:arch_train}\nWe build 2 layer \\gnns for \\textsc{Colors} and 3 layer \\gnns for other tasks with 64 filters in each layer, except for \\mnist~where we have more filters. Our baselines are \\gnns with global sum or max pooling (gpool), DiffPool~\\citep{ying2018hierarchical} and top-k pooling~\\citep{graphunet2018}. We add two layers of our pooling for \\tri, each of which is a \\gnn with 3 layers and 32 filters \\eqref{eq:attn_gcn}; whereas a single pooling layer in the form of vector $\\mathbf{p}$ is used in other cases.\nWe train all models with Adam~\\citep{kingma2014adam}, learning rate 1e-3, batch size 32, weight decay 1e-4.\n\nFor \\textsc{Colors} and \\textsc{Triangles} we minimize the regression loss (MSE) and cross entropy (CE) for other tasks, denoted as $\\mathcal{L}_{MSE/CE}$. For experiments with supervised and \\wsup~(described below in \\secref{\\ref{sec:wsup}}) attention, we additionally minimize the Kullback-Leibler (KL) divergence loss between ground truth attention $\\mathbf{\\alpha}^{GT}$ and predicted coefficients $\\mathbf{\\alpha}$. The KL term is weighted by scale $\\beta$, so that the total loss for some training graph with $N$ nodes becomes:\n%\n\\begin{equation}\n\\label{eq:kl_div_loss}\n\\mathcal{L} = \\mathcal{L}_{MSE/CE} + \\frac{\\beta}{N}\\sum_i \\mathbf{\\alpha}_i^{GT} \\text{log}(\\frac{\\mathbf{\\alpha}_i^{GT}}{\\mathbf{\\alpha}_i}).\n\\end{equation}\n%\n%where $\\beta$ controls the scale and importance of the KL term.\n%\nWe repeat experiments at least 10 times and report an average accuracy and standard deviation in Tables~\\ref{table:results} and~\\ref{table:results_graphs}.\nFor \\colors~we run experiments 100 times, since we observe larger variance.\nIn Table~\\ref{table:results} we report results on all test subsets independently.\nIn all other experiments on \\synthetic, we report an average accuracy on the combined test set.\nFor \\real, we run experiments 10 times using splits described in \\secref{\\ref{sec:graph_data}}.\n\nThe only hyperparameters that we tune in our experiments are threshold $\\tilde{\\mathbf{\\alpha}}$ in our method \\eqref{eq:top-k_ours}, ratio $r$ in top-k \\eqref{eq:top-k} and $\\beta$ in \\eqref{eq:kl_div_loss}. For synthetic datasets, we tune them on a validation set generated in the same way as \\textsc{Test-Orig}. For \\mnist, we use part of the training set. For \\real, we tune them using 10-fold cross-validation on the training set.\n\n\n\\densepar{Attention correctness.} We evaluate attention correctness using area under the ROC curve (AUC) as an alternative to other methods, such as~\\citep{liu2017attention}, which can be overoptimistic in some extreme cases, such as when all attention is concentrated in a single node or attention is uniformly spread over all nodes. AUC allows us to evaluate the ranking of $\\mathbf{\\alpha}$ instead of their absolute values. Compared to ranking metrics, such as rank correlation, AUC enables us to directly choose a pooling threshold $\\tilde{\\mathbf{\\alpha}}$ from the ROC curve by finding a desired balance between false-positives (pooling unimportant nodes) and false-negatives (dropping important nodes).\n\nTo evaluate attention correctness of models with global pooling, we follow the idea from convolutional neural networks~\\citep{zeiler2014visualizing}. After training a model, we remove node $i \\in [1, N]$ and compute an absolute difference from prediction $y$ for the original graph:\n%\n\\begin{equation}\n\\label{eq:heat_maps}\n\\mathbf{\\alpha}_i^{WS} = \\frac{|y_i - y|}{\\sum_{j=1}^N |y_j - y|},\n\\end{equation}\n%\nwhere $y_i$ is a model's prediction for the graph without node $i$.\nWhile this method shows surprisingly high AUC in some tasks, it is not built-in in training and thus does not help to train a better model and only implicitly interprets a model's prediction (Figures~\\ref{fig:attn_mnist} and~\\ref{fig:attn_graphs}). However, these results inspired us to design a \\wsup~method described below.\n\n\\subsection{Weakly-supervised attention supervision}\n\\label{sec:wsup}\nAlthough for \\colors, \\tri~and \\mnist~we can define ground truth attention, so that it does not require manual labeling, in practice it is usually not the case and such annotations are hard to define and expensive, or even unclear how to produce. Based on results in Table~\\ref{table:results}, supervision of attention is necessary to reveal its power. Therefore, we propose a weakly-supervised approach, agnostic to the choice of a dataset and model, that does not require ground truth attention labels, but can improve a model's ability to generalize.\nOur approach is based on generating attention coefficients $\\mathbf{\\alpha}_i^{WS}$ \\eqref{eq:heat_maps} and using them as labels to train our attention model with the loss defined in Eq~\\ref{eq:kl_div_loss}.\nWe apply this approach to \\colors, \\tri~and \\mnist~and observe peformance and robustness close to supervised models. We also apply it to \\collab, \\proteins~and \\dd, and in all cases we are able to improve results compared to unsupervised attention.\n\n\\textbf{Training weakly-supervised models.}\nAssume we want to train model \\textbf{A} with ``weak-sup'' attention on a dataset without ground truth attention. We first need to train model \\textbf{B} that has the same architecture as \\textbf{A}, but does not have any attention/pooling between graph convolution layers. So, model \\textbf{B} has only global pooling. After training \\textbf{B} with the $\\mathcal{L}_{MSE/CE}$ loss, we need to evaluate training graphs on \\textbf{B} in the same way as during computation of $\\mathbf{\\alpha}^{WS}$ in \\eqref{eq:heat_maps}. In particular, for each training graph $\\cal G$ with $N$ nodes, we first make a prediction $y$ for the entire $\\cal G$. Then, for each $i \\in [1,N]$, we remove node $i$ from $\\cal G$, and feed this reduced graph with $N-1$ nodes to model \\textbf{B} recording the model's prediction $y_i$. We then use \\eqref{eq:heat_maps} to compute $\\mathbf{\\alpha}^{WS}$ based on $y$ and $y_i$. Now, we can train \\textbf{A} and use $\\mathbf{\\alpha}^{WS}$ instead of ground truth $\\mathbf{\\alpha}^{GT}$ in \\eqref{eq:kl_div_loss} to optimize both \\textit{MSE/CE} and \\textit{KL} losses.\\looseness-1\n\n%\\definecolor{extreme}{gray}{0.85}\n%\\definecolor{bad}{gray}{0.95}\n\n\n\\begin{table}[b!]\n\t%\\newcommand\\crule[3][black]{\\textcolor{#1}{\\rule{#2}{#3}}}\n\t%\\vspace{-8pt}\n\t\\caption{\\small \\textbf{Results on three tasks for different test subsets.} $\\pm$ denotes standard deviation, not shown in case of small values (large values are explained in \\secref{\\ref{sec:results}}). \\textsc{Attn} denotes attention accuracy in terms of AUC and is computed for the combined test set. The best result in each column (ignoring upper bound results) is bolded.\n\t\\crule[bad]{12pt}{8pt} denotes poor results with relatively low accuracy and/or high variance;\n\t\\crule[extreme]{12pt}{8pt} denotes failed cases with accuracy close to random and/or extremely high variance. $^\\dagger$~For \\colors~and \\mnist, ChebyNets are used instead of ChebyGINs.\\looseness-1}\n    \\vspace{-10pt}\n\t\\scriptsize\n\t\\label{table:results}\n\t\\begin{center}\n\t\t\\setlength{\\tabcolsep}{2pt}\n\t\t\\begin{tabular}{clllll|lll|llll}\n\t\t\t\\toprule\n\t\t\t&  &\\multicolumn{4}{c|}{\\bf \\colors} & \\multicolumn{3}{c|}{\\bf \\tri}  & \\multicolumn{4}{c}{\\bf \\mnist}\\Tstrut\\\\\n\t\t\t& & \\textsc{Orig} & \\textsc{Large} & \\textsc{LargeC} & \\textsc{Attn} & \\textsc{Orig} & \\textsc{Large} & \\textsc{Attn} & \\textsc{Orig} & \\textsc{Noisy} & \\textsc{NoisyC} & \\textsc{Attn} \\\\\n\t\t\t\\midrule\\\\\n\t\t\t\\multirow{3}{*}{\\rotatebox[origin=c]{90}{\\parbox{0.6cm}{\\tiny \\centering Global pool}}}\n\t\t\t& GCN & 97 & \\cellcolor{bad}72\\std{15} & \\cellcolor{extreme}20\\std{3} & 99.6 & 46\\std{1} & \\cellcolor{extreme}23\\std{1}  & 79 & \\cellcolor{bad}78.3\\std{2} & \\cellcolor{extreme}38\\std{4} & \\cellcolor{extreme}36\\std{4} & 72\\std{2}\\\\\n\t\t\t& GIN & \\cellcolor{bad}96\\std{10} & \\cellcolor{bad}71\\std{22} & \\cellcolor{extreme}26\\std{11} & 99.2 & 50\\std{1} & \\cellcolor{extreme}22\\std{1} & 77 & 87.6\\std{3} & \\cellcolor{extreme}55\\std{11} & \\cellcolor{extreme}51\\std{12} & 71\\std{5} \\\\\n\t\t\t& ChebyGIN$^\\dagger$ & \\textbf{100} & \\cellcolor{bad}93\\std{12} & \\cellcolor{extreme}15\\std{7} & 99.8 & 66\\std{1} & \\cellcolor{bad}30\\std{1} & 79 & \\textbf{97.4} & \\cellcolor{bad}80\\std{12} & \\cellcolor{bad}79\\std{11} & 72\\std{3} \\\\\n\t\t\t\\hline \\\\\n\t\t\t\\multirow{4}{*}{\\rotatebox[origin=c]{90}{\\parbox{1cm}{\\tiny \\centering Unsuperv.}}} &\n\t\t\tGIN, top-k & 99.6 & \\cellcolor{extreme}17\\std{4} & \\cellcolor{extreme}9\\std{3}  & 75\\std{6} & 47\\std{2} & \\cellcolor{extreme}18\\std{1} & 63\\std{5} & 86\\std{6} & \\cellcolor{extreme}59\\std{26} & \\cellcolor{extreme}55\\std{23} & \\cellcolor{extreme}65\\std{34} \\\\\n\t\t\t& GIN, ours & \\cellcolor{bad}94\\std{18} & \\cellcolor{extreme}13\\std{7} & \\cellcolor{extreme}11\\std{6} & \\cellcolor{bad}72\\std{15} & 47\\std{3} & \\cellcolor{extreme}20\\std{2} & 68\\std{3} & 82.6\\std{8} & \\cellcolor{extreme}51\\std{28} & \\cellcolor{extreme}47\\std{24} & \\cellcolor{extreme}58\\std{31} \\\\\n\t\t\t& ChebyGIN$^\\dagger$, top-k & \\textbf{100} & \\cellcolor{extreme}11\\std{7} & \\cellcolor{extreme}6\\std{6} & \\cellcolor{bad}79\\std{20} & 64\\std{5} & \\cellcolor{extreme}25\\std{2} & 76\\std{6} & 92.9\\std{4} & \\cellcolor{extreme}68\\std{26} & \\cellcolor{extreme}67\\std{25} & \\cellcolor{extreme}52\\std{37} \\\\\n\t\t\t& ChebyGIN$^\\dagger$, ours & \\cellcolor{extreme}80\\std{30} & \\cellcolor{extreme}16\\std{10} & \\cellcolor{extreme}11\\std{6} & \\cellcolor{bad}67\\std{31} & 67\\std{3} & \\cellcolor{extreme}26\\std{2} & 77\\std{4} & 94.6\\std{3} & \\cellcolor{bad}80\\std{23} & \\cellcolor{bad}77\\std{22} & \\cellcolor{bad}78\\std{31} \\\\\n\t\t\t\\hline \\\\\n\t\t\t\\multirow{4}{*}{\\rotatebox[origin=c]{90}{\\parbox{1cm}{\\tiny Supervised}}}\n\t\t\t& GIN, topk & \\cellcolor{bad}87\\std{1} & \\cellcolor{extreme}39\\std{18} & \\cellcolor{extreme}28\\std{8} & \\textbf{99.9} & 49\\std{1} & \\cellcolor{extreme}20\\std{1} & 88 & 90.5\\std{1} & 85.5\\std{2} & \\cellcolor{bad}79\\std{5} & 99.3 \\\\\n\t\t\t& GIN, ours  & \\textbf{100} & \\textbf{96\\std{9}} & \\cellcolor{bad}\\textbf{89\\std{18}} & 99.8 & 49\\std{1} & \\cellcolor{extreme}22\\std{1} & 76\\std{1} & 90.9\\std{0.4} & 85.0\\std{1} & \\cellcolor{bad}80\\std{3} & 99.3 \\\\\n\t\t\t& ChebyGIN$^\\dagger$, topk & \\textbf{100} & \\cellcolor{bad}86\\std{15} & \\cellcolor{extreme}31\\std{15} & 99.8 & 83\\std{1} & \\cellcolor{bad}39\\std{1} & \\textbf{97} & 95.1\\std{{0.3}} & 90.6\\std{0.8} & \\cellcolor{bad}83\\std{16} & \\textbf{100}  \\\\\n\t\t\t& ChebyGIN$^\\dagger$, ours & \\textbf{100} & 94\\std{8} & \\cellcolor{bad}75\\std{17} & 99.8 & \\textbf{88\\std{1}} & \\textbf{48\\std{1}} & 96 & 95.4\\std{0.2} & \\textbf{92.3\\std{0.4}} & \\cellcolor{bad}\\textbf{86\\std{16}} & \\textbf{100} \\Bstrut \\\\\n\t\t\t\\hline \\Tstrut \\\\\n\t\t\t\\multirow{1}{*}{\\rotatebox[origin=c]{90}{\\parbox{0.15cm}{\\tiny \\centering Weak sup.}}} &\n\t\t\tChebyGIN$^\\dagger$, ours & \\textbf{100} &  90\\std{6} & \\cellcolor{bad}73\\std{14} & \\textbf{99.9} & 68\\std{1} & \\cellcolor{bad}30\\std{1} & 88 & 95.8\\std{0.4} & 88.8\\std{4} & \\textbf{86\\std{9}} & 96.5\\std{1} \\Tstrut \\Bstrut\\\\\n\t\t\t\\hline\n\t\t\t\\hline \\\\\n\t\t\t\\multirow{2}{*}{\\rotatebox[origin=c]{90}{\\parbox{0.5cm}{\\tiny \\centering Upper bound}}}\n\t\t\t& GIN & 100 & 100 & 100 & 100 & 94\\std{1} & 85\\std{2} & 100 & 93.6\\std{0.4} & 90.8\\std{1} & 90.8\\std{1} & 100 \\\\\n\t\t\t& ChebyGIN$^\\dagger$ & 100 & 100 & 100 & 100 & 99.8 & 99.4\\std{1} & 100 & 96.9\\std{0.1} & 94.8\\std{0.3} & 95.1\\std{0.3} & 100 \\\\\n\t\t\t\\bottomrule\n\t\t\t\\vspace{-15pt}\n\t\t\\end{tabular}\n\t\\end{center}\n\\end{table}\n\n\n\\begin{figure}%[]\n\t\\begin{center}\n\t\t\\small\n\t\t\\setlength{\\tabcolsep}{1.5pt}\n\t\t\\begin{tabular}{cccc}\n\t\t\t\\begin{tikzpicture}\n\t\t\t\\node[anchor=south west,inner sep=0] (image) at (0,0) {\\includegraphics[width=0.24\\textwidth, trim={0.3cm 0.4cm 0.3cm 0.3cm}, clip]{fig3/colors_gin_sup_ada_top_Acc_vs_AUC_dim3}};\n\t\t\t\\begin{scope}[x={(image.south east)},y={(image.north west)}]\n\t\t\t\\draw[green,thick,dashed,dash pattern=on 3pt off 2pt] (0.88,0.25) rectangle (0.97,0.98);\n\t\t\t\\end{scope}\n\t\t\t\\end{tikzpicture}\n\t\t\t&\n\t\t\t\\includegraphics[width=0.24\\textwidth, trim={0.3cm 0.4cm 0.3cm 0.3cm}, clip]{fig3/colors_gin_sup_ada_top_Acc_vs_AUC_zoomed_dim3} &\n\n\t\t\t\\begin{tikzpicture}\n\t\t\t\\node[anchor=south west,inner sep=0] (image) at (0,0) {\\includegraphics[width=0.24\\textwidth, trim={0.3cm 0.4cm 0.3cm 0.3cm}, clip]{fig3/colors_cheb_sup_ada_top_Acc_vs_AUC_dim3}};\n\t\t\t\\begin{scope}[x={(image.south east)},y={(image.north west)}]\n\t\t\t\\draw[green,thick,dashed,dash pattern=on 3pt off 2pt] (0.88,0.25) rectangle (0.97,0.98);\n\t\t\t\\end{scope}\n\t\t\t\\end{tikzpicture}\n\t\t\t&\n\t\t\t{\\includegraphics[width=0.24\\textwidth, trim={0.3cm 0.4cm 0.3cm 0.3cm}, clip]{fig3/colors_cheb_sup_ada_top_Acc_vs_AUC_zoomed_dim3}} \\\\\n\t\t\t(a) & (a)-zoomed & (b) & (b)-zoomed \\\\\n\n\t\t\t{\\includegraphics[width=0.24\\textwidth, align=c, trim={0.3cm 0.4cm 0.3cm 0.3cm}, clip]{fig3/GIN_AUC_vs_Cos_dim3_16}} &\n\t\t\t\\includegraphics[width=0.24\\textwidth, align=c, trim={0.3cm 0.4cm 0.3cm 0.3cm}, clip]{fig3/Cheb_ACC_vs_Dim} &\n\n\t\t\t{\\includegraphics[width=0.24\\textwidth, align=c, trim={0.3cm 0.4cm 0.3cm 0cm}, clip]{fig3/colors_gin_sup_ada_top_Acc_vs_AUC_dim16}} &\n\t\t\t\\includegraphics[width=0.24\\textwidth, align=c, trim={0.3cm 0.4cm 0.3cm 0cm}, clip]{fig3/triangles_cheb_ACC_vs_Acc} \\\\\n\t\t\t(c) & (d) & (e)  & (f)\n\t\t\\end{tabular}\n\t\\end{center}\n\t\\vspace{-18pt}\n\t\\caption{\\small Disentangling factors influencing attention and classification accuracy for \\textsc{Colors} \\textit{(a-e)} and \\textsc{Triangles} \\textit{(f)}. Accuracies are computed over all test subsets. Notice the exponential growth of classification accuracy depending on attention correctness \\textit{(a,b)}, see zoomed plots \\textit{(a)}-zoomed, \\textit{(b)}-zoomed for cases when attention AUC$>$95\\%. \\textit{(d)} Probability of a good initialization is estimated as the proportion of cases when cosine similarity $>$ 0.5; error bars indicate standard deviation. \\textit{(c-e)} show results using a higher dimensional attention model, $\\mathbf{p} \\in \\mathbb{R}^n$.}\n\t%\\vspace{-10pt}\n\t\\label{fig:accuracy_cos_sim}\n\\end{figure}\n\n\\section{Analysis of results}\n\\label{sec:results}\nIn this work, we aim to better understand attention and generalization in graph neural networks, and,  based on our empirical findings, below we provide our analysis for the following questions.\n\n\\densepar{How powerful is attention over nodes in \\gnns?}\nOur results on the \\synthetic~datasets suggest that the main strength of attention over nodes in \\gnns is the ability to generalize to more complex or noisy graphs at test time. This ability essentially transforms a model that fails to generalize into a fairly robust one. Indeed, a classification accuracy gap for \\textsc{Colors-LargeC} between the best model without supervised attention (GIN with global pooling) and a similar model with supervised attention (GIN, sup) is more than 60\\%. For \\textsc{Triangles-Large} this gap is 18\\%  and for \\textsc{MNIST-75sp-Noisy} it is more than 12\\%. This gap is even larger if compared to upper bound cases indicating that our supervised models can be further tuned and improved. Models with supervised or \\wsup~attention also have a more narrow spread of results (\\fig{\\ref{fig:accuracy_cos_sim}}).\n\n\n\n\\begin{figure}[thb]\n\t\\newcommand{\\width}{0.28\\textwidth}\n\t\\begin{center}\n\t\t\\begin{small}\n\t\t\t\\setlength{\\tabcolsep}{3pt}\n\t\t\t\\begin{tabular}{cccc}\n\t\t\t\t\\multicolumn{4}{c}{\n\t\t\t\t\t\\includegraphics[width=0.95\\textwidth, trim={1.5cm 1cm 3cm 10.5cm}, clip]{colors_init/legend.pdf}} \\\\\n\t\t\t\t& \\scriptsize bad initialization (cos.~sim.=-0.75) &\\scriptsize\n\t\t\t\tgood initialization (cos.~sim.=0.75) &\n\t\t\t\t\\scriptsize optimal initialization (cos.~sim.=1.00) \\\\\n\t\t\t\t\\rotatebox[origin=c]{90}{\\small \\textsc{Unsupervised}} &\n\t\t\t\t{\\includegraphics[width=\\width, align=c, trim={0cm 0cm 0.5cm 0cm}, clip]{colors_init/bad_unsup}} & %\\hspace{0.5cm}\n\t\t\t\t{\\includegraphics[width=\\width, align=c, trim={0cm 0cm 0.5cm 0cm}, clip]{colors_init/good1_unsup}} &\n\t\t\t\t{\\includegraphics[width=\\width, align=c, trim={0cm 0cm 0.5cm 0cm}, clip]{colors_init/optimal4_unsup}} \\\\\n\t\t\t\t& (a) & (b) & (c) \\\\\n\t\t\t\t\\rotatebox[origin=c]{90}{\\small \\textsc{Supervised}} &\n\t\t\t\t{\\includegraphics[width=\\width, align=c, trim={0cm 0cm 0.5cm 0cm}, clip]{colors_init/bad_sup}} & %\\hspace{0.5cm}\n\t\t\t\t{\\includegraphics[width=\\width, align=c, trim={0cm 0cm 0.5cm 0cm}, clip]{colors_init/good1_sup}} &\n\t\t\t\t{\\includegraphics[width=\\width, align=c, trim={0cm 0cm 0.5cm 0cm}, clip]{colors_init/optimal4_sup}} \\\\\n\t\t\t\t& (d) & (e) & (f) \\\\\n\t\t\t\\end{tabular}\n\t\t\\end{small}\n\t\t\\vspace{-18pt}\n\t\\end{center}\n\t\\caption{\\small Influence of initialization on training dynamics for \\textsc{Colors} using GIN trained in unsupervised (a-c) and supervised (d-e) ways. The nodes that should be pooled according to our ground truth prior, must have larger attention values $\\alpha$. However, in the unsupervised cases, only the model with an optimal initialization (c) reaches a high accuracy, while other models (a,b) are stuck in a suboptimal state and wrong nodes are pooled, which degrades performance. In the supervised cases (d-f), models converge to a perfect accuracy and initialization only affects the speed of convergence. In these experiments, we train models longer to see if they can recover from a bad initialization.}\n\t\\label{fig:training_curves_unsup}\n\\end{figure}\n\n\n\\densepar{What are the factors influencing performance of \\gnns with attention?}\nWe identify three key factors influencing performance of \\gnns with attention: initialization of the attention model (i.e.~vector $\\mathbf{p}$ or \\gnn in \\eqref{eq:attn_gcn}), strength of the main \\gnn model (i.e.~the model that actually performs classification), and finally other hyperparameters of the attention and \\gnn models.\n\nWe highlight initialization as the critical factor. We ran 100 experiments on \\colors~with random initializations (\\fig{\\ref{fig:accuracy_cos_sim}}, \\textit{(a-e)}) of the vector $\\mathbf{p}$ and measured how performance of both attention and classification is affected depending on how close (in terms of cosine similarity) the initialized $\\mathbf{p}$ was to the optimal one, $\\mathbf{p} = [0,1,0]$.\nWe disentangle the dependency between the classification accuracy and cos.~sim. into two functions to make the relationship clearer (\\fig{\\ref{fig:accuracy_cos_sim}}, \\textit{(a, c)}).\nInterestingly, we found that classification accuracy depends \\textit{exponentially} on attention correctness and becomes close to 100\\% only when attention is also close to being perfect. In the case of slightly worse attention, even starting from 99\\%, classification accuracy drops significantly.\nThis is an important finding that can also be valid for other more realistic applications. In the \\textsc{Triangles} task we only partially confirm this finding, because our attention models could not achieve AUC high enough to boost classification. However, by observing the upper bound results obtained by training with ground truth attention, we assume that this boost potentially should happen once attention becomes accurate enough.\\looseness=-1\n\n\\begin{figure}[tbh]\n\t\\begin{center}\n\t\t\\small\n\t\t\\setlength{\\tabcolsep}{0pt}\n\t\t\\begin{minipage}{.55\\textwidth}\n\t\t\\begin{tabular}{cccc}\n\t\t\t& \\textsc{Test-Orig} & \\textsc{Test-Noisy} & \\textsc{Test-NoisyC} \\\\\n\t\t\t\\rotatebox[origin=c]{90}{\\tiny \\textsc{Input}} &\n\t\t\t{\\includegraphics[width=0.3\\textwidth, align=c, trim={4cm 1cm 3cm 1cm}, clip]{cheb_weak_sup/fig_0.pdf}} &\n\t\t\t{\\includegraphics[width=0.3\\textwidth, align=c, trim={4cm 1cm 3cm 1cm}, clip]{cheb_weak_sup/fig_1.pdf}} &\n\t\t\t{\\includegraphics[width=0.3\\textwidth, align=c, trim={4cm 1cm 3cm 1cm}, clip]{cheb_weak_sup/fig_2.pdf}} \\\\\n\n\t\t\t\\rotatebox[origin=c]{90}{\\tiny \\textsc{DiffPool}} &\n\t\t\t{\\includegraphics[width=0.3\\textwidth, align=c, trim={4cm 1cm 3cm 1cm}, clip]{cheb_diff_pool_clusters/fig_diffpool_3.pdf}} &\n\t\t\t{\\includegraphics[width=0.3\\textwidth, align=c, trim={4cm 1cm 3cm 1cm}, clip]{cheb_diff_pool_clusters/fig_diffpool_4.pdf}} &\n\t\t\t{\\includegraphics[width=0.3\\textwidth, align=c, trim={4cm 1cm 3cm 1cm}, clip]{cheb_diff_pool_clusters/fig_diffpool_5.pdf}} \\\\\n\n\t\t\t\\rotatebox[origin=c]{90}{$\\mathbf{\\alpha}^{WS}$} &\n\t\t\t{\\includegraphics[width=0.3\\textwidth, align=c, trim={4cm 1cm 3cm 1cm}, clip]{cheb_global_max_heat/fig_heat_3.pdf}} &\n\t\t\t{\\includegraphics[width=0.3\\textwidth, align=c, trim={4cm 1cm 3cm 1cm}, clip]{cheb_global_max_heat/fig_heat_3.pdf}} &\n\t\t\t{\\includegraphics[width=0.3\\textwidth, align=c, trim={4cm 1cm 3cm 1cm}, clip]{cheb_global_max_heat/fig_heat_5.pdf}} \\\\\n\n\t\t\t\\rotatebox[origin=c]{90}{$\\mathbf{\\alpha}$} &\n\t\t\t{\\includegraphics[width=0.3\\textwidth, align=c, trim={4cm 1cm 3cm 1cm}, clip]{cheb_weak_sup/fig_3.pdf}} &\n\t\t\t{\\includegraphics[width=0.3\\textwidth, align=c, trim={4cm 1cm 3cm 1cm}, clip]{cheb_weak_sup/fig_4.pdf}} &\n\t\t\t{\\includegraphics[width=0.3\\textwidth, align=c, trim={4cm 1cm 3cm 1cm}, clip]{cheb_weak_sup/fig_5.pdf}} \\\\\n\t\t\\end{tabular}\n\t\t\\end{minipage}\n%\t\t\\hspace{-2pt}\n\t\t\\begin{minipage}{0.35\\textwidth}\n\t\t\\begin{tabular}{cc}\n\t\t\t\\multicolumn{2}{c}{\\textsc{Triangles Test-Large}} \\rule[-7pt]{0pt}{0pt} \\\\\n\t\t\t{{\\includegraphics[width=0.45\\textwidth, align=c, trim={1cm 1cm 2cm 1.5cm}, clip]{cheb_weak_sup_triangles/triangles_test2_large.png}}} &\n\t\t\t{\\includegraphics[width=0.5\\textwidth, align=c, trim={2cm 1cm 0cm 1.5cm}, clip]{cheb_weak_sup_triangles/triangles_test2_gt_pool_large.pdf}} \\\\\n\t\t\t\\tiny $N=93$ & \\tiny $N=16$ \\rule[-10pt]{0pt}{0pt} \\\\\n\t\t\t{\\includegraphics[width=0.45\\textwidth, align=c, trim={1cm 1cm 2cm 1.5cm}, clip]{cheb_weak_sup_triangles/triangles_test2_pred_large.png}} &\n\t\t\t{\\includegraphics[width=0.5\\textwidth, align=c, trim={2cm 1cm 0cm 1.5cm}, clip]{cheb_weak_sup_triangles/triangles_test2_pred_layer1_large.pdf}} \\\\\n\t\t\t\\tiny $N=93$ & \\tiny $N=27$ \\\\\n\t\t\\end{tabular}\n\t\t\\end{minipage}\n\t\\end{center}\n\t\\vspace{-10pt}\n\t\\caption{\\small Qualitative analysis. For \\mnist~(on the left) we show examples of input test images (top row), results of DiffPool~\\citep{ying2018hierarchical} (second row), attention weights $\\mathbf{\\alpha}^{WS}$ generated using a model with global pooling based on \\eqref{eq:heat_maps} (third row), and $\\mathbf{\\alpha}$ predicted by our \\wsup~model (bottom row). Both our attention-based pooling and DiffPool can be strong and interpretable depending on the task, but in our tasks DiffPool was inferior.\n\tFor \\tri~(on the right) we show an example of a test graph with $N=93$ nodes with six triangles and the results of pooling based on ground truth attention weights $\\mathbf{\\alpha}^{GT}$ (top row); in the bottom row we show attention weights predicted by our \\wsup~model and results of our threshold-based pooling \\eqref{eq:top-k_ours}. Note that during training, our model has not encountered noisy images (\\mnist) nor graphs larger than with $N=25$ nodes (\\tri). }\n\t\\label{fig:attn_mnist}\n\t\\vspace{-1pt}\n\\end{figure}\n\n\\densepar{Why is the variance of some results so high?}\nIn Table~\\ref{table:results} we report high variance of results, which is mainly due to initialization of the attention model as explained above. This variance is also caused by initialization of other trainable parameters of a GNN, but we show that once the attention model is perfect, other parameters can recover from a bad initialization leading to better results. The opposite, however, is not true: we never observed recovery of a model with poorly initialized attention (\\fig{\\ref{fig:training_curves_unsup}}).\\looseness=-1\n\n\\densepar{How top-k compares to our threshold-based pooling method?}\nOur method to attend and pool nodes \\eqref{eq:top-k_ours} is based on top-k pooling~\\citep{graphunet2018} and we show that the proposed threshold-based pooling is superior in a principle way. When we use supervised attention our results are better by more than 40\\% on \\textsc{Colors-LargeC}, by 9\\%  on \\textsc{Triangles-Large} and by 3\\% on \\textsc{MNIST-75sp}. In \\fig{\\ref{fig:accuracy_cos_sim}} (\\textit{(a,b)}-zoomed) we show that GIN and ChebyGIN models with supervised top-k pooling never reach an average accuracy of more than 80\\% as opposed to our method which reaches 100\\% in many cases.\n\n\\densepar{How results change with increase of attention model input dimensionality or capacity?}\nWe performed experiments using ChebyGIN-h - a model with higher dimensionality of an input to the attention model. In such cases, it becomes very unlikely to initialize it in a way close to optimal (\\fig{\\ref{fig:accuracy_cos_sim}}, \\textit{(c-e)}), and attention accuracy is concentrated in the 60-80\\% region. Effect of the attention model of such low accuracy is neglible or even harmful, especially on the large and noisy graphs. We also experimented with a deeper attention model (ChebyGIN-h), i.e. a 2 layer fully-connected layer with 32 hidden units for \\colors~and \\mnist, and a deeper \\gnn \\eqref{eq:attn_gcn} for \\tri. This has a positive effect overall, except for \\tri, where our attention models were already deep \\gnns.\\looseness-1\n\n\\begin{figure}[htpb]\n\t\\vspace{-1pt}\n\t\\setlength{\\tabcolsep}{0pt}\n\t\\begin{tabular}{ccccc}\n\t\t{\\includegraphics[width=0.2\\textwidth, align=c, trim={0cm 0cm 0cm 0cm}, clip]{init/unsup_colors3.pdf}} &\n\t\t{\\includegraphics[width=0.2\\textwidth, align=c, trim={0cm 0cm 0cm 0cm}, clip]{init/sup_colors3.pdf}} &\n\t\t{\\includegraphics[width=0.2\\textwidth, align=c, trim={0cm 0cm 0cm 0cm}, clip]{init/wsup_colors3.pdf}} &\n\t\t{\\includegraphics[width=0.2\\textwidth, align=c, trim={0cm 0cm 0cm 0cm}, clip]{init/acc_scale_cos_colors3.pdf}} &\n\t\t{\\includegraphics[width=0.2\\textwidth, align=c, trim={0cm 0cm 0cm 0cm}, clip]{init/acc_scale_cos_colors3_gcn.pdf}}\n\t\\end{tabular}\n\t\\caption{\\small Influence of distribution parameters used to initialize the attention model $\\mathbf{p}$ in the \\colors~task with $n=3$ dimensional features. We show points corresponding to the commonly used initialization strategies of \\ul{Xavier}~\\citep{he2015delving} and \\ul{Kaiming}~\\citep{he2015delving}. \\textit{(a-c)} Shaded areas show range, bars show $\\pm1$ std.}\n\t\\label{fig:init}\n\t\\vspace{-10pt}\n\\end{figure}\n\n\\densepar{Can we improve initialization of attention?}\nIn all our experiments, we initialize $\\mathbf{p}$ from the Normal distribution, ${\\cal N}(0, 1)$. To verify if the performance can be improved by choosing another distribution, we evaluate GIN and GCN models on a wide range of random distributions, Normal ${\\cal N}(0, \\sigma)$ and Uniform $U(-\\sigma, \\sigma)$, by varying scale $\\sigma$ (\\fig{\\ref{fig:init}}).\nWe found out that for unsupervised training (\\fig{\\ref{fig:init}}, \\textit{(a)}), larger initial values and the Normal distribution should be used to make it possible to converge to an optimal solution, which is still unlikely and greatly depends on cosine similarity with GT attention (\\fig{\\ref{fig:init}}, \\textit{(d,e)}). For supervised and ``weak-sup'' attention, smaller initial weights and either the Normal or Uniform distribution should be used (\\fig{\\ref{fig:init}}, \\textit{(b,c)}).\n\n\n\\begin{table}[tbhp]%{R}{7.2cm}%[t]\n\t%\\vspace{-12pt}\n\t\\caption{\\small \\textbf{Results on the social (\\collab) and molecule (\\proteins~and \\dd) datasets.} We use 3 layer GCNs~\\citep{kipf2016semi} or ChebyNets~\\citep{defferrard2016convolutional}. Dataset subscripts denote the maximum number of nodes in the training set according to our splits (\\secref{\\ref{sec:graph_data}}).\\looseness-1}\n\t\\vspace{-10pt}\n\t\\scriptsize\n\t\\label{table:results_graphs}\n\t\\begin{center}\n\t\t%\\setlength{\\tabcolsep}{2.4pt}\n\t\t\\begin{tabular}{lcccc}\n\t\t\t\\toprule\n\t\t\t& \\textbf{\\collab}$_{35}$ & \\textbf{\\proteins}$_{25}$ & \\textbf{\\dd}$_{200}$ & \\textbf{\\dd}$_{300}$\\Tstrut\\Bstrut\\\\\n\t\t\t\\midrule \\\\\n\t\t\t\\# train / test graphs & 500 / 4500  & 500 / 613 & 462 / 716 & 500 / 678 \\\\\n\t\t\t\\# nodes ($N$) train & 32-35 & 4-25 & 30-200 & 30-300 \\\\\n\t\t\t\\# nodes ($N$) test & 32-492 & 6-620 & 201-5748 & 30-5748 \\\\\n\t\t\t\\hline \\\\\n\t\t\tGlobal max & 65.9\\std{3.4} & 74.4\\std{1.0} & 29.7\\std{4.9} & 72.7\\std{3.6} \\\\\n\t\t\tUnsup, ours & 65.7\\std{3.5} & 75.6\\std{1.4} & 51.9\\std{5.3} & 77.2\\std{2.9} \\\\\n\t\t\t\\hline \\\\\n\t\t\tWeak-sup & \\textbf{67.0\\std{1.7}} & \\textbf{76.2\\std{0.7}} &  \\textbf{54.3\\std{5.0}} & \\textbf{78.4\\std{1.1}} \\\\\n\t\t\t\\bottomrule\n\t\t\\end{tabular}\n\t\\end{center}\n\t%\\vspace{-8pt}\n\\end{table}\n\n\n\n\n\\begin{figure}[tbhp]\n\t\\newcommand{\\imgwidth}{0.17\\textwidth}\n\t\\begin{center}\n\t\t\\small\n\t\t\\setlength{\\tabcolsep}{3pt}\n\t\t\\begin{tabular}{cccccc}\n\t\t\t& \\small \\textsc{Global pool} & \\small \\textsc{Unsup} & \\small \\textsc{Unsup pooled} & \\small \\textsc{Weak-sup} &  \\small \\textsc{Weak-sup pooled} \\\\\n\t\t\t\\rotatebox[origin=c]{90}{\\small \\collab$_{35}$} &\n\t\t\t{\\includegraphics[width=\\imgwidth, align=c, trim={0 0 0 0}, clip]{collab/56_96_32nodes_0_0_global.pdf}} &\n\t\t\t{\\includegraphics[width=\\imgwidth, align=c, trim={0 0 0 0}, clip]{collab/56_96_32nodes_0_1_unsup.pdf}} &\n\t\t\t{\\includegraphics[width=\\imgwidth, align=c, trim={0 0 0 0}, clip]{collab/56_96_21nodes_0_1_unsup_pooled.pdf}} &\n\t\t\t{\\includegraphics[width=\\imgwidth, align=c, trim={0 0 0 0}, clip]{collab/56_96_32nodes_0_0.pdf}} &\n\t\t\t{\\includegraphics[width=\\imgwidth, align=c, trim={0 0 0 0}, clip]{collab/56_96_14nodes_0_0_pooled.pdf}} \\\\ \\\\\n\t\t\t\\rotatebox[origin=c]{90}{\\small \\proteins$_{25}$} &\n\t\t\t{\\includegraphics[width=\\imgwidth, align=c, trim={0 0 0 0}, clip]{proteins/46_437_134nodes_0_0_global.pdf}} &\n\t\t\t{\\includegraphics[width=\\imgwidth, align=c, trim={0 0 0 0}, clip]{proteins/46_437_134nodes_0_0_unsup.pdf}} &\n\t\t\t{\\includegraphics[width=\\imgwidth, align=c, trim={0 0 0 0}, clip]{proteins/46_437_79nodes_0_0_unsup_pooled.pdf}} &\n\t\t\t{\\includegraphics[width=\\imgwidth, align=c, trim={0 0 0 0}, clip]{proteins/46_437_134nodes_0_0.pdf}} &\n\t\t\t{\\includegraphics[width=\\imgwidth, align=c, trim={0 0 0 0}, clip]{proteins/46_437_72nodes_0_0_pooled.pdf}} \\\\ \\\\\n\t\t\t\\rotatebox[origin=c]{90}{\\small \\dd$_{200}$} &\n\t\t\t{\\includegraphics[width=\\imgwidth, align=c, trim={0 0 0 0}, clip]{dd/65_640_212nodes_1_1_global.pdf}} &\n\t\t\t{\\includegraphics[width=\\imgwidth, align=c, trim={0 0 0 0}, clip]{dd/65_640_212nodes_1_1_unsup.pdf}} &\n\t\t\t{\\includegraphics[width=\\imgwidth, align=c, trim={0 0 0 0}, clip]{dd/65_640_70nodes_1_1_unsup_pooled.pdf}} &\n\t\t\t{\\includegraphics[width=\\imgwidth, align=c, trim={0 0 0 0}, clip]{dd/65_640_212nodes_1_1.pdf}} &\n\t\t\t{\\includegraphics[width=\\imgwidth, align=c, trim={0 0 0 0}, clip]{dd/65_640_73nodes_1_1_pooled.pdf}} \\\\\n\t\t\\end{tabular}\n\t\\end{center}\n\t\\vspace{-10pt}\n\t\\caption{\\small Qualitative results. In \\collab, a graph represents an ego-network of a researcher, therefore \\textit{center nodes} are important. In \\proteins~and \\dd, a graph is a protein and nodes are amino acids, so it is important to attend to a \\textit{connected chain} of amino acids to distinguish an enzyme from a non-enzyme protein. Our \\wsup~method attends to and pools more relevant nodes compared to global and unsupervised models, leading to better classification results. }\n\t\\label{fig:attn_graphs}\n\\end{figure}\n\n\\densepar{What is the recipe for more powerful attention \\gnns?}\nWe showed that \\gnns with supervised training of attention are significantly more accurate and robust, although in case of a bad initialization it can take a long time to reach the performance of a better initialization.\nHowever, supervised attention is often infeasible. We suggested an alternative approach based on \\wsup~training and validated it on our synthetic (Table~\\ref{table:results}) and real (Table~\\ref{table:results_graphs}) datasets. In case of \\synthetic~we can compare to both unsupervised and supervised models and conclude that our approach shows performance, robustness and relatively low variation  (i.e. sensitivity to initialization) similar to supervised models and much better than unsupervised models. In case of \\real~we can only compare to unsupervised and global pooling models and confirm that our method can be effectively employed for a wide diversity of graph classification tasks and attends to more relevant nodes (Figures~\\ref{fig:attn_mnist} and~\\ref{fig:attn_graphs}). Tuning the distribution and scale $\\sigma$ for the initialization of attention can further improve results. For instance, on \\proteins~for the \\wsup~case, we obtain 76.4\\% as opposed to 76.2\\%.\\looseness-1\n\n\\section{Conclusion}\n%\\vspace{-10pt}\nWe have shown that learned attention can be extremely powerful in graph neural networks, but only if it is close to optimal. This is difficult to achieve due to the sensitivity of initialization, especially in the unsupervised setting where we do not have access to ground truth attention. Thus, we have identified initialization of attention models for high dimensional inputs as an important open issue.\nWe also show that attention can make \\gnns more robust to larger and noisy graphs, and that the weakly-supervised approach proposed in our work brings advantages similar to the ones of supervised models, yet at the same time can be effectively applied to datasets without annotated attention.\n\n\\vfill\n\\clearpage\n\n", "meta": {"hexsha": "9834f360f644248d2d5eef5afe2fbc9da6be1a35", "size": 53474, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Ch3_2019_neurips/main.tex", "max_stars_repo_name": "uoguelph-mlrg/phdthesis_boris", "max_stars_repo_head_hexsha": "bf8f9e040e664356af31a2d2e4f9122bb33d0196", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Ch3_2019_neurips/main.tex", "max_issues_repo_name": "uoguelph-mlrg/phdthesis_boris", "max_issues_repo_head_hexsha": "bf8f9e040e664356af31a2d2e4f9122bb33d0196", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Ch3_2019_neurips/main.tex", "max_forks_repo_name": "uoguelph-mlrg/phdthesis_boris", "max_forks_repo_head_hexsha": "bf8f9e040e664356af31a2d2e4f9122bb33d0196", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 102.0496183206, "max_line_length": 1104, "alphanum_fraction": 0.7395743726, "num_tokens": 16913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.33663141765122917}}
{"text": "\\chapter{Conclusions}\n\\label{chpr:conclusion}\nThe aim of this thesis is to give an introduction to the Schnorr signature algorithm, starting from the mathematics and the cryptography behind the scheme, and present some of its amazing applications to Bitcoin, detailing the benefits and the improvements that would arise from its deployment. We started with a brief but thorough description of the mathematical structures (Chapter \\ref{chpr:math}) and cryptographic primitives (Chapter \\ref{chpr:ecc}) that underpin digital signature schemes based on elliptic curve cryptography. In Chapter \\ref{chpr:dss} we presented both ECDSA and Schnorr algorithm, respectively the one actually implemented in Bitcoin and the one that is under development. We compared the two schemes, investigating ECDSA lacks and Schnorr benefits, that ranged from security to efficiency. In particular we focused on the linearity property, that turned out to be the key for the higher level construction presented in Chapter \\ref{chpr:application}.\n\\\\\nWe have seen how to traduce utilities already implemented in Bitcoin in terms of Schnorr signatures: multi-signature schemes are implemented through MuSig (Section \\ref{musig}), whose main advantage is to recover key aggregation; threshold signatures can be deployed through the protocols presented in Section \\ref{threshold}, that makes them indistinguishable from a single signature; the last application we studied has been adaptor signature and its benefits to cross-chain atomic swaps and to the Lightning Network.\n\n\\bigskip\n\\noindent\nThe immediate benefits that Schnorr would bring to Bitcoin are improved efficiency (smaller signatures, batch validation, cross-input aggregation) and privacy (multi-signatures and threshold signatures would be indistinguishable from a single signature), leading also to an enhancement in fungibility. All this applications would be possible in a straightforward way after the introduction of Schnorr, that could be brought to Bitcoin through a soft-fork\\footnote{Improvements in the protocol have to be made without consensus split.}: the fact that Schnorr is superior to ECDSA in every aspect hopefully will ease the process.\n\n\\bigskip\n\\noindent\nThe last thing we would like to point out is that, by no means, the applications presented in the present work are the unique benefits that Schnorr could bring to Bitcoin. More complex ideas take the names of Taproot \\cite{Taproot} and Graftroot \\cite{Graftroot}, and are built on top of the concepts of MAST and Pay-to-Contract: through these constructions it would be possible, in the cooperative case, to hide completely the redeem script, presenting a single signature (no matter how complex the script is). For how soft forks need to be implemented after SegWit (i.e. with an upgrade of the version number), there is incentive to develop as many innovations as possible altogether (the presence of too many version numbers with little differences would constitute a lack of privacy): for this reason, it is probable that Schnorr will come to life accompanied by Taproot. \n\\\\\nHopefully, we have convinced the reader that Schnorr (and Bitcoin!) is worth being studied, providing also the tools to properly understand further features and innovations other than the ones presented. Moreover, we hope that you are now motivated not only to delve deeper in the technical side of Bitcoin, but also to approach it from other sides, to fully appreciate its disruptiveness and make yourself an idea of what Bitcoin is and which possibilities it hides.", "meta": {"hexsha": "2ed93639ea7fe4adbc08c205f96eb7289895c4f4", "size": 3561, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapters/Conclusion.tex", "max_stars_repo_name": "gionasoldati/thesis", "max_stars_repo_head_hexsha": "e8b3b3828f4ccb0a35e26381b361425e09a51b11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapters/Conclusion.tex", "max_issues_repo_name": "gionasoldati/thesis", "max_issues_repo_head_hexsha": "e8b3b3828f4ccb0a35e26381b361425e09a51b11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapters/Conclusion.tex", "max_forks_repo_name": "gionasoldati/thesis", "max_forks_repo_head_hexsha": "e8b3b3828f4ccb0a35e26381b361425e09a51b11", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-06T23:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-06T23:47:52.000Z", "avg_line_length": 237.4, "max_line_length": 976, "alphanum_fraction": 0.8174670037, "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073507867328, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.3366314086342576}}
{"text": "\\section{Simulation of local NPI implementation during Victoria's second wave}\n\n\\subsection{School closures}\nThe effect of Victorian school closures is captured through the timeline presented in Table \\ref{tab:school_timeline}.\n\n\n\\begin{table}[ht]\n\\renewcommand{\\baselinestretch}{1}\n\t\\begin{tabular}[ht]{| p{4.2cm} | p{6.2cm} | p{3.2cm} |}\n\t\\hline\n\t\tDate of change & Policy change & Modification applied to school contacts contribution to mixing matrix, \\(s(t)\\) \\\\\n\t\t\\hline\n\t\tFrom model start & Remote learning & 0.1 \\\\\n\t\t\\hline\n\t\t26\\textsuperscript{th} May & 400,000 school students return to school & 0.393 \\\\\n\t\t\\hline\n\t\t9\\textsuperscript{th} June & Remaining 618,000 school students return to school & 1 \\\\\n\t\t\\hline\n\t\t9\\textsuperscript{th} July & Remote learning for stage 3 restrictions & 0.1 \\\\\n\t\t\\hline\n    \\end{tabular}\n    \\title{Timeline used to implement Victorian school closure policies.}\n    \\caption{\\textbf{Timeline used to implement Victorian school closure policies.} The function is applied to both metropolitan and regional services.}\t\n    \\label{tab:school_timeline}\n\\end{table}\n\n\\subsection{Macrodistancing in workplaces and other locations}\nThe functions applied here are determined by the Google mobility data according to Table \\ref{tab:mobility_map}, as described above, but are applied separately for each service. Because Google mobility data pertains to local government areas (LGAs), whereas health service clusters may receive patients from across the state, it was necessary to map mobility data to services. Health service clusters' overall mobility values in each location were calculated using a weighted average of LGA mobility values according to the historical pattern of the origin of patients presenting to services within each service.\n\nAs a hypothetical example, if 50\\% of patients historically presenting to Barwon South West health services come from the City of Geelong, the mobility data for the City of Geelong will contribute 50\\% of the Google mobility estimate of Barwon South West.\n\nHistorical patterns of patient presentations by health service cluster were provided by the Victorian Department of Health and Human Services (DHHS).\n\n\\subsection{Microdistancing approach}\nIn this application to Victoria, the microdistancing function \\(m(t)\\) is comprised of two components: physical distancing and face coverings. Both physical distancing and face coverings micro-distancing are applied to the three non-household locations, such that the microdistancing function for non-household locations is given by: \\[m(t)=d(t)^2\\times f(t)^2\\]\nThe two interventions are assumed to be independent and so are multiplicative. As for the macrodistancing functions, the two functions of time are squared to represent their effects on both the infector and the infectee in any potentially infectious interaction.\n\n\\subsection{Physical distancing}\nThe physical distancing function \\(d(t)\\) is a transposed and translated hyperbolic tan function. The parameters of this function were estimated by using maximum a posteriori inference, with priors that penalised large shape parameters (to avoid extremely rapid transitions). The proportions of respondents answering ``always\" to YouGov surveys of Victorian residents asking ``Thinking about the last 7 days, about how many people from your household have you come into physical contact with (within 2 meters / 6 feet)?\" were used as input data. Resulting parameters were: shape, 0.262764; lower asymptote, 0.2803973; upper asymptote; 0.4421819; and inflection point, 15\\textsuperscript{th} July. The resulting function is presented in Figure \\ref{fig:physical}.\n\n\\begin{figure}[ht]\n    \\resizebox{1\\textwidth}{!}{\\includegraphics[scale=1]{../covid_19/projects/victoria/methods_figures/physical_distancing_fig.png}}\n    \\caption{\\textbf{Physical distancing micro-distancing function with data used for fitting} (for all services).}\n    \\title{Physical distancing micro-distancing function with data used for fitting}\n    \\label{fig:physical}\n\\end{figure}\n\n\\subsection{Face coverings}\nTwo separate face coverings microdistancing functions are employed, one for metropolitan and one for regional health service clusters. These functions were fitted using the same methods as for physical distancing, using YouGov data on Victorian residents' survey responses to the question ``Thinking about the last 7 days, have you worn a face mask outside your home (e.g. when on public transport, going to a supermarket, going to a main road)?\". Estimated parameters were: shape, 0.5261693; lower asymptote, 0.130469; upper asymptote, 0.9143849; and inflection point, 23\\textsuperscript{rd} July (consistent with the policy change in metropolitan Melbourne). This was applied directly to metropolitan services and translated ten days later for regional services, where face coverings were mandated from the 2\\textsuperscript{nd} August. The resulting function is presented in Figure \\ref{fig:face}.\n\n\\begin{figure}[ht]\n \t\\resizebox{1\\textwidth}{!}{\\includegraphics[scale=1]{../covid_19/projects/victoria/methods_figures/face_covering_fig.png}}\n    \\caption{\\textbf{Face coverings micro-distancing function for metropolitan Melbourne services with data used for fitting.}}\n\t\\label{fig:face}\n\t\\title{Face coverings micro-distancing function for metropolitan Melbourne services with data used for fitting.}\n\\end{figure}\n", "meta": {"hexsha": "96f30a605f56ee0aab431fb15ae4b1af8513a241", "size": 5387, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/papers/covid_19/projects/victoria/mixing_and_npis.tex", "max_stars_repo_name": "monash-emu/AuTuMN", "max_stars_repo_head_hexsha": "fa3b81ef54cf561e0e7364a48f4ff96585dc3310", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2020-03-11T06:15:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T03:38:35.000Z", "max_issues_repo_path": "docs/papers/covid_19/projects/victoria/mixing_and_npis.tex", "max_issues_repo_name": "monash-emu/AuTuMN", "max_issues_repo_head_hexsha": "fa3b81ef54cf561e0e7364a48f4ff96585dc3310", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 96, "max_issues_repo_issues_event_min_datetime": "2020-01-29T05:10:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T01:48:46.000Z", "max_forks_repo_path": "docs/papers/covid_19/projects/victoria/mixing_and_npis.tex", "max_forks_repo_name": "monash-emu/AuTuMN", "max_forks_repo_head_hexsha": "fa3b81ef54cf561e0e7364a48f4ff96585dc3310", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2020-04-24T00:38:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-19T16:19:03.000Z", "avg_line_length": 94.5087719298, "max_line_length": 900, "alphanum_fraction": 0.7943196584, "num_tokens": 1252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.3365764931934892}}
{"text": "\n\\subsection{Online Tensor Decomposition}\nSince dynamic tensor decomposition pursues shorter time factor updates, fast decomposition process results low accuracy factorization when real-time data incomes.\n\n\\begin{center}\n\t\\includegraphics[width=0.8\\textwidth]{FIG/0-online-tensor-decomposition.pdf}\n\\end{center}\n\n\\subsubsection{\\em Transformed Online CP}\nWe've developed \\tocp by extending the basic intuition of \\ocp. To optimize the speed accuracy problem, \\tocp resembles \\cpals by iteratively updating the factor matrix of temporal mode. In spite of time consumption, however it achieves remarkable accuracy improvement.\n\n\\subsubsection{\\em DTD}\ntemporally growing dtd mentioned in Multi-aspect tensor completion\n\n\\newpage\n\\subsection{Drastic Data Handling}\nWhen we decompose a tensor, we can find error norm comparing real and estimated entries. As the tensor temporally grows, we can calculate local and global error norm by measuring incoming slices and the whole tensor respectively.\n\nDrastic data can be detected by measuring local error norm and distribution of previous norms. Using Welford's algorithm, we can track mean and deviation and find out anomalies in current local error norm by z-score calculation. Differentiating the upper and lower limit of z-score, we can trigger one of accuracy optimizing processes. Trigger function now decides whether to split or to concatenate behind after one temporal factor update. It allows to store the tensor efficiently by grouping tensors with similar themes and splitting them otherwise.\n\n\\begin{center}\n\t\\includegraphics[width=0.8\\textwidth]{FIG/0-drastic-data-handling.pdf}\n\\end{center}\n\n\\subsubsection{\\em Split Process}\nAnomaly detection in image error norm tells us sudden change in data. What if the incoming data may have a new theme unseen before? It implies that new decomposition starting point with tensor split is needed. In this process, we'd like to apply upper limit ${ul}$ to trigger splitting the tensor into serial tensors of different themes.\n\n\\subsubsection{\\em Refinement Process}\nRefinement process is to concatenate incoming tensor slices whose theme is similar to the previous tensor. Exceedance of lower limit ${ll}$ trigger forgetting preious decomposition result and decompose the tensor once again.\n\n\\begin{center}\n\t\\includegraphics[width=0.49\\textwidth]{FIG/1-online-tensor-decomposition.pdf}\n\t\\includegraphics[width=0.49\\textwidth]{FIG/1-drastic-data-handling.pdf}\n\\end{center}\n", "meta": {"hexsha": "8b6c3692ce158ca52e3ef9c2a10debdf2e39d5d3", "size": 2466, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Tech Report/030method.tex", "max_stars_repo_name": "lucetre/dao-cp", "max_stars_repo_head_hexsha": "26453f6c1b4bcfd1161aeb28770a85c3a8b5c3d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tech Report/030method.tex", "max_issues_repo_name": "lucetre/dao-cp", "max_issues_repo_head_hexsha": "26453f6c1b4bcfd1161aeb28770a85c3a8b5c3d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tech Report/030method.tex", "max_forks_repo_name": "lucetre/dao-cp", "max_forks_repo_head_hexsha": "26453f6c1b4bcfd1161aeb28770a85c3a8b5c3d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 70.4571428571, "max_line_length": 552, "alphanum_fraction": 0.8142741281, "num_tokens": 524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.33657648696048703}}
{"text": "\\chapter{Further research}\n\\label{chap:furtherResearch}\n\nIt is possible to list an enormous number of ideas for further research in a field\nlike crypto-currencies, blockchain or cryptography. But some of those more related to the work\ndone in this paper are listed in the following. Some of them are improvements of\nthe work already done, but not yet ready for production, and some of them are\nentirely exploratory.\n\n% -----------------------------------------------------------------------------\n\\section{Side-channel attack resistant implementation and improvements}\n\nThe proposed implementation in the library \\texttt{secp256k1} relies upon\n\\texttt{libgmp} for all mathematical calculus but this library is\nnot robust against side-channel attacks. The library has not\nbeen developed for that particular purpose. Therefore, another implementation\nis needed to handle, in constant time and constant memory if\npossible, the mathematical calculus part. This is a significant improvement that\ncan be done, or must be done, before hoping to use the module in some real case\nscenario.\n\n\\subsection{Second hash function}\n\nThe current implementation uses the hash function \\texttt{SHA256} implemented\nin the library \\texttt{secp256k1} for $\\Pi$ and $\\Pi'$. This is not compliant\nwith the scheme requirements. Another hash function must be implemented\nand used for $\\Pi'$.\n\n\\subsection{Paillier cryptosystem}\n\nTwo major improvements or modifications can be made specifically on the\nPaillier cryptosystem implementation. As shown in Paillier's paper, the\nChinese Remainder Theorem can be used to optimize the decryption. In the\nstandard approach, with a private key $(n, g, \\lambda, \\mu)$ and a ciphertext $c\n\\in \\mathbb{Z}_{n^2}^*$ it is possible to compute the plaintext $m =\nL(c^{\\lambda} \\mod n^2) \\cdot \\mu \\mod n$ where $L(x) = \\frac{x-1}{n}$. With the\nCRT two functions $L_p$ and $L_q$ are defined as\n\n\\begin{ceqn}\n\\begin{align*}\n  L_p(x) = \\frac{x-1}{p} \\quad \\text{and} \\quad L_q(x) = \\frac{x-1}{q}\n\\end{align*}\n\\end{ceqn}\n\nDecryption can, therefore, be performed with modulo $p$ and modulo $q$ and\nrecombining modular residues afterward\n\n\\begin{ceqn}\n\\begin{align*}\n  m_p = L_p(c^{p-1} \\mod p^2) \\ h_p \\mod p \\\\\n  m_q = L_q(c^{q-1} \\mod p^2) \\ h_q \\mod q \\\\\n  m = \\text{CRT}(m_p, m_q) \\mod pq\n\\end{align*}\n\\end{ceqn}\n\nwith precomputations\n\n\\begin{ceqn}\n\\begin{align*}\n  h_p &= L_p(g^{p-1} \\mod p^2)^{-1} \\mod p \\quad \\text{and} \\\\\n  h_q &= L_q(g^{q-1} \\mod p^2)^{-1} \\mod q\n\\end{align*}\n\\end{ceqn}\n\nPaillier cryptosystem can also be adapted to \\gls{ec} cryptography as shown in the\npaper \\say{Trapdooring Discrete Logarithms on Elliptic Curves over Rings} by\nPascal Paillier \\cite{10.1007/3-540-44448-3_44}. It is worth noting however that\nthe curve construction is different from the curve used to sign and so the code\nbase cannot necessarily be reused.\n\n\\subsection{Zero-knowledge proofs}\n\nNon-interactive zero-knowledge proofs are a significant research field. The\narticle \\say{From Extractable Collision Resistance to Succinct Non-interactive\nArguments of Knowledge, and Back Again} by Bitansky, Nir and Canetti, Ran and\nChiesa, Alessandro and Tromer, and Eran \\cite{Bitansky:2012:ECR:2090236.2090263}\nintroduced the acronym zk-SNARK for zero-knowledge Succinct Non-interactive\nARgument of Knowledge that is the backbone of the Zcash protocol\n\\cite{cryptoeprint:2014:349}. In the recent paper \\say{Bulletproofs: Efficient\nRange Proofs for Confidential Transactions} \\cite{cryptoeprint:2017:1066} a new\nnon-interactive zero-knowledge proof protocol with concise proofs and without a\ntrusted setup is proposed. Further research could be done to adapt the\nzero-knowledge proof construction and migrate to a more generic approach. These\nzero-knowledge proofs date from the early 2000s and advancement has been made\nsince then.\n\n% -----------------------------------------------------------------------------\n\\section{Hardware wallets}\n\nHardware wallet devices have become increasingly popular. They promise to keep\nthe keys safe and, at least, expose the keys less\nthanks to a dedicated and controlled environment. Keys can be stored\nsafely and, in an organization, for example, multiple hardware wallets can be\nused to create a multi-signature to control the funds.\n\nThe development of this threshold library, even if it is just a 2-out-of-2\nmulti-signature script equivalent, can be used to create threshold hardware\nwallet devices. Two hardware wallet devices can be set up together to create a\nmulti-user setup, or a hardware wallet device can be coupled with a phone to\nsecure a web-wallet.\n\n% -----------------------------------------------------------------------------\n\\section{Key management}\n\nUsually, when a new Bitcoin wallet is created a list of words, called a \\textit{mnemonic} phrase,\nis shown to the user as a backup of his key. The \\textit{mnemonics} are between\ntwelve and twenty four words, and each word represents 11 bits of the initial seed\n\\cite{Mnemonic}. For a threshold key, it is not possible to represent all the\ndata in the same way given the size of the key (near 4.5 Kb). Another way to\ndisplay and transmit this information is needed to improve usability. Further\nresearch could be done to find a better way to represent and display a threshold\nkey.\n\nThe master tag is not included in the \\texttt{DER} schema. Is the key itself\nresponsible for storing this information or is this information part of the\nsetup and can be stored elsewhere? This question can also be explored.\n\n% -----------------------------------------------------------------------------\n\\section{General threshold scheme}\n\nThe way multi-signature scripts work in Bitcoin requires exposing all\npublic keys related to the signatures. That increases the transaction size,\nwhich implies significant fees. Due to the script size limit of near to 500 bytes,\nthe maximum number of signatories is around fifteen. The signatures are\nnaturally present with the public keys in the script, which implies that it is\npossible to know which keys signed the transaction. That implies less anonymity\non the blockchain. With a general threshold scheme, these limitations would be\nremoved.\n\nAs previously mentioned, research has been done to generalize and find an\noptimal $(t, n)$-threshold in \\gls{ecdsa} \\cite{10.1007/BFb0052253,\n10.1007/978-3-642-27954-6_20}. These papers base their work on the scheme chosen\nin this thesis, so a deeper analysis could be performed to assess the\nchanges needed and adapt the current implementation to construct a generic threshold scheme.\n\n% -----------------------------------------------------------------------------\n\\section{Schnorr signatures}\n\nIn the paper \\say{Efficient Identification and Signatures for Smart Cards}\npublished in CRYPTO 1989, C.P. Schnorr proposes the \\say{Schnorr signature\nalgorithm} \\cite{10.1007/0-387-34805-0_22}. The Schnorr signature is considered\nthe simplest digital signature scheme to be provably secure in a random oracle\nmodel \\cite{Bellare:1993:ROP:168588.168596, 10.1007/978-3-642-29011-4_33}.\nBitcoin developers and researchers have had a strong interest in this specific\nscheme for some years now. Schnorr signatures could greatly reduce the size of\nthe signature from 65 bytes (\\gls{ecdsa} in \\texttt{DER} format) to around 40 bytes.\n\nWith the arrival of SegWit, script versioning was also introduced, making it\nis easier to introduce a new \\texttt{OP\\_CODE} and so introduce a new signature\nvalidation scheme. However, this will not invalidate the present work and\nresearch because of the specific requirements needed to optimize payment channels.\n\nNevertheless, Schorr signatures are tipped to be the next scheme used in Bitcoin\nand maybe in other crypto-currencies. Further research could be done to find a\nprotocol that fulfills the requirements defined for payment channel\noptimization.\n", "meta": {"hexsha": "023a5eb8134702e98cf3d646967e021298b72a27", "size": 7858, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "02-main/ch6_further_research.tex", "max_stars_repo_name": "GuggerJoel/msc-thesis-report", "max_stars_repo_head_hexsha": "3ea9ece819549d494234c095fa667b6bab5854f1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-05-24T15:28:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-15T15:40:14.000Z", "max_issues_repo_path": "02-main/ch6_further_research.tex", "max_issues_repo_name": "GuggerJoel/msc-thesis-report", "max_issues_repo_head_hexsha": "3ea9ece819549d494234c095fa667b6bab5854f1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "02-main/ch6_further_research.tex", "max_forks_repo_name": "GuggerJoel/msc-thesis-report", "max_forks_repo_head_hexsha": "3ea9ece819549d494234c095fa667b6bab5854f1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.050955414, "max_line_length": 97, "alphanum_fraction": 0.7463731229, "num_tokens": 1909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982315512489, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3365449936137329}}
{"text": "\\subsubsection{\\stid{3.12} Enabling Time Integrators for Exascale Through SUNDIALS} \\label{subsubsect:SUNDIALS}\n\n\\paragraph{Overview} \n\nThis project is enhancing the SUNDIALS library of numerical software packages for integrating differential systems in time using state-of-the-art adaptive time step technologies for use on exascale systems.  Through software infrastructure developments, this project is enabling the efficient and robust SUNDIALS time integrator packages to easily interoperate with external linear and nonlinear solver packages developed for exascale computing.  In addition, this project is providing a many-vector capability so that SUNDIALS time integrators can more easily operate on data divided over heterogeneous architectures.  Lastly, this project is supporting the deployment and use of SUNDIALS packages within ECP applications, mainly through incorporation into the discretization-based Co-Design Centers, AMReX and CEED.\n\nEfficient time integrators are essential for ECP because they are at the core of every time-dependent simulation application.  However, many applications do not use state-of-the-art methods, and if they do, they often do not yet use them fully on their systems.  For example, at the start of the ECP the astrophysics code, Nyx, used an adaptive integration package for solving individual reactions.  However, by applying a time integration package to a larger reaction system, the code is able to vectorize more of the calculations and get an accurate solution much faster.  By allowing for solvers tuned to exascale systems and vectors that are heterogeneous, SUNDIALS will be more applicable for use in multiphysics systems running on exascale platforms.\n\n\n\n\\paragraph{Key  Challenges}\n\nCurrent implementations of efficient time integrators face challenges on many fronts.  First, integrators typically have treated the full physical problem with a single step size or have relied on low order operator splitting methods to couple physical processes at different time scales. While research is moving forward within the time integration community on methods for multirate systems, the software infrastructure needs to be in place to accommodate these schemes once they are developed.   Second, typical integrators operate on problem data in the form of vectors.  These operations suffer from low arithmetic intensity, and their efficiency is often memory bandwidth limited.  Lastly, implicit integrators, which are required in many exascale systems, require efficient linear and nonlinear solvers to be highly effective.  In addition, by applying integrator-dependent controls on these solvers, their efficiency can be significantly increased.  Applying these controls, however, often requires that information about the integrator and its progress be passed to the solver, and software must be designed to effectively pass that information while ensuring adequate encapsulation to provide ease of maintenance and software extension.\n\n\\paragraph{Solution Strategy}\n\nThis project includes a number of implementation activities that will prepare the SUNDIALS suite of time integrators for exascale systems. A major activity is a redesign of all linear solver interfaces and encapsulation of the nonlinear solvers within the time integrators in SUNDIALS.  The new linear solver interfaces make it much easier to interface external solver packages while maintaining the efficiency of SUNDIALS integrators. Encapsulating the nonlinear solvers reduces redundant code and allows the time integrators to better leverage common code resulting in a lower code maintenance burden within SUNDIALS.  In addition, the integrators are able to take advantage of outside nonlinear solvers.  \n\nThis project also introduced a set of optional fused vector kernels into SUNDIALS.  These kernels execute multiple vector operations at once thereby reducing the number of kernel launches in GPU environments and also reducing the number of communications required for reduction operations.  These new kernels were added to all supplied SUNDIALS vectors and are invoked through optional interfaces.\n\nLastly, this project is developing a many-vector capability for SUNDIALS.  Due to the tight data encapsulation within SUNDIALS, users are able to supply any vector they would like underneath the integrators.  This project will supply the infrastructure needed to make it easy to place a vector of vectors underneath the integrators.  This vector of vectors is essential for later implementation of time integrators that will advance various parts of the system with different time step sizes.  This many-vector capability will also ease the use of different programming environments as differing vectors can be instantiated on different parts of a hybrid machine. \n\n\\paragraph{Recent Progress}\n\nIn May of 2018, SUNDIALS 4.0.0-dev was released, including new fused vector kernels in the vector API and in all supplied vectors.  Results show speedup from using these routines, especially for parallel reductions.  In September of 2018, SUNDIALS 4.0.0-dev.2 was released, including a full redesign of the nonlinear solver interfaces to the time integrators and encapsulation of the nonlinear solevrs.  Figure \\ref{fig:sunorg1} shows the new organization of SUNDIALS where separate nonlinear solver interfaces are provided for Newton and fixed point nonlinear solver methods.  These interfaces are shared across all SUNDIALS integrators.  \nIndividual integrators have the freedom to supply specific information from the integrator that controls the solver.  In addition, the SUNDIALS team has been collaborating closely with the AMReX Co-Design Center team to \ndesign effective interfaces to SUNDIALS time integrators from AMReX for applications using ODE integrators,\nsuch as for chemistry reaction systems as in Nyx, Castro, and PELE.\n\n\\begin{figure}[htb]\n\t\\centering\n\t\\includegraphics[width=6in]{projects/2.3.3-MathLibs/2.3.3.12-SUNDIALS-hypre/sunorg1.pdf}\n\t\\caption{\\label{fig:sunorg1}New structure of SUNDIALS showing options for the new SUNNONLINEARSOLVER classes.}\n\\end{figure}\n\n\\paragraph{Next Steps}\n\nDuring the remainder of FY19, this project team will:\n\\begin{enumerate}\n\\item Complete a release of SUNDIALS with a new many-vector that will enable easier use of SUNDIALS on heterogeneous architectures and for multiphysics systems.\n\\item Complete a scalable demonstration example program that will enable performance assessments on large-scale problems and provide a testbed for new time integrators.\n\\item Continue to support AMReX and CEED Co-Design Centers in their use of SUNDIALS for ECP applications.\n\\end{enumerate}\n", "meta": {"hexsha": "afefb2d7c5ecac0c36569d9087af1f6b4c594ef4", "size": 6662, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "projects/2.3.3-MathLibs/2.3.3.12-SUNDIALS-hypre/2.3.3.12-SUNDIALS.tex", "max_stars_repo_name": "mikiec84/ECP-ST-CAR-PUBLIC", "max_stars_repo_head_hexsha": "b9d6e478ed34830e0ae83693564ced7e044e2b12", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "projects/2.3.3-MathLibs/2.3.3.12-SUNDIALS-hypre/2.3.3.12-SUNDIALS.tex", "max_issues_repo_name": "mikiec84/ECP-ST-CAR-PUBLIC", "max_issues_repo_head_hexsha": "b9d6e478ed34830e0ae83693564ced7e044e2b12", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "projects/2.3.3-MathLibs/2.3.3.12-SUNDIALS-hypre/2.3.3.12-SUNDIALS.tex", "max_forks_repo_name": "mikiec84/ECP-ST-CAR-PUBLIC", "max_forks_repo_head_hexsha": "b9d6e478ed34830e0ae83693564ced7e044e2b12", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 151.4090909091, "max_line_length": 1246, "alphanum_fraction": 0.8269288502, "num_tokens": 1364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3365449865486904}}
{"text": "\\chapter[The Visualization Pipeline]{The\\\\ Visualization\\\\ Pipeline}\n\\label{chap:visualization_pipeline}\n\n% Position the image to the right of the heading.\n\\vspace{-11\\baselineskip} % move up\n\\hfill\n \\begin{minipage}{0.5\\textwidth}\n \\centering\n \\includegraphics{VTKTextbook-38}\n  \\captionof*{figure}{\\textit{The VisTrails multi-view visualization system.\n          VisTrials enables interactive creation of visualization pipelines, maintaining the history of their evolution, optimizing their execution and allowing multiple pipelines to be compared in a spreadsheet-style layout.\n          Image courtesy of SCI Institute University of Utah.}}\n \\end{minipage}\n\\vspace{2\\baselineskip}\n\n\\firstletter{I}n the previous chapter we created graphical images using simple mathematical models for lighting, viewing, and geometry. The lighting model included ambient, diffuse, and specular effects. Viewing included the effects of perspective and projection. Geometry was defined as a static collection of graphics primitives such as points and polygons. In order to describe the process of visualization we need to extend our understanding of geometry to include more complex forms. We will see that the visualization process transforms data into graphics primitives. This chapter examines the process of data transformation and develops a model of data flow for visualization systems.\n\n\\section {Overview}\nVisualization transforms data into images that efficiently and accurately convey information about the data. Thus, visualization addresses the issues of \\emph{transformation} and \\emph{representation}.\n\nTransformation is the process of converting data from its original form into graphics primitives, and eventually into computer images. This is our working definition of the visualization process. An example of such a transformation is the process of extracting stock prices and creating an $x-y$ plot depicting stock price as a function of time.\n\nRepresentation includes both the internal data structures used to depict the data and the graphics primitives used to display the data. For example, an array of stock prices and an array of times are the computational representation of the data, while the $x-y$ plot is the graphical representation. Visualization transforms a computational form into a graphical form.\n\nFrom an object-oriented viewpoint, transformations are processes in the functional model, while representations are the objects in the object model. Therefore, we characterize the visualization model with both functional models and object models.\n\n\\subsection{A Data Visualization Example}\n\\label{subsec:data_visualization_example}\n\nA simple mathematical function for a quadric will clarify these concepts. The function\n\n\\begin{equation}\\label{eq:4.1}\nF(x,y,z) = a_0x^2 + a_1y^2 + a_2z^2 + a_3xy + a_4yz + a_5xz + a_6x + a_7y + a_8z + a9\n\\end{equation}\n\\myequations{A quadric function.}\n\nis the mathematical representation of a quadric. Figure \\ref{fig:Figure4-1a} shows a visualization of Equation \\ref{eq:4.1} in the region $-1 \\leqslant x, y, z \\leqslant 1$. The visualization process is as follows. We sample the data on a regular grid at a resolution of $50 \\times 50 \\times 50$. Three\ndifferent visualization techniques are then used. On the left, we generate 3D surfaces corresponding to the function $F(x,y,z) = c$ where $c$ is an arbitrary constant (i.e., the isosurface value). In the center, we show three different planes that cut through the data and are colored by function value. On the right we show the same three planes that have been contoured with constant valued lines. Around each we place a wireframe outline.\n\n\\begin{figure}[htb]\n  \\begin{subfigure}[h]{0.80\\linewidth}\n    \\includegraphics[width=\\linewidth]{Figure4-1a}\n    \\caption{Quadric visualization. (\\href{https://lorensen.github.io/VTKExamples/site/Cxx/Visualization/QuadricVisualization/}{QuadricVisualization.cxx} or \\href{https://lorensen.github.io/VTKExamples/site/Python/Visualization/QuadricVisualization/}{QuadricVisualization.py})}\n    \\label{fig:Figure4-1a}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[h]{0.80\\linewidth}\n    \\includegraphics[width=\\linewidth]{Figure4-1b}\n    \\caption{Functional model.}\\label{fig:Figure4-1b}\n  \\end{subfigure}%\n  \\hfill\n  \\begin{subfigure}[h]{0.80\\linewidth}\n    \\includegraphics[width=\\linewidth]{Figure4-1c}\n    \\caption{Visualization network.}\\label{fig:Figure4-1c}\n  \\end{subfigure}\n  \\caption{Visualizing a quadric function $F(x,y,z) = c$.}\\label{fig:Figure4-1}\n\\end{figure}\n\n\\subsection{The Functional Model}\n\\label{subsec:the_functional_model}\n\nThe functional model in Figure \\ref{fig:Figure4-1b} illustrates the steps to create the visualization. The oval blocks indicate operations (processes) we performed on the data, and the rectangular blocks represent data stores (objects) that represent and provide access to data. Arrows indicate the direction of data movement. Arrows that point into a block are inputs; data flowing out of a block indicate outputs. The blocks also may have local parameters that serve as additional input. Processes that create data with no input are called data \\emph{source} objects, or simply sources. Processes that consume data with no output are called \\emph{sinks} (the are also called \\emph{mappers} because these processes map data to a final image or output). Processes with both an input and an output are called \\emph{filters}.\n\nThe functional model shows how data flows through the system. It also describes the depen-dency of the various parts upon one another. For any given process to execute correctly, all the inputs must be up to date. This suggests that functional models require a synchronization mechanism to insure that the correct output will be generated.\n\n\\subsection{The Visualization Model}\n\\label{subsec:the_visualization_model}\n\nIn the examples that follow we will frequently use a simplified representation of the functional model to describe visualization processes (Figure \\ref{fig:Figure4-1c}). We will not explicitly distinguish between sources, sinks, data stores, and process objects. Sources and sinks are implied based on the number of inputs or outputs. Sources will be process objects with no input. Sinks will be process objects with no output. Filters will be process objects with at least one input and one output. Intermediate data stores will not be represented. Instead we will assume that they exist as necessary to support the data flow. Thus, as Figure \\ref{fig:Figure4-1c} shows, the \\emph{Lines} data store that the \\emph{Outline} object generates (Figure \\ref{fig:Figure4-1b}) are combined into the single object \\emph{Outline}. We use oval shapes to represent objects in the visualization model.\n\n\\subsubsection{The Object Model}\n\nThe functional model describes the flow of data in our visualization,\nthe object model describes which modules operate on it. But what \\emph{are} the objects in the system? At first glance, we have two choices (Figure \\ref{fig:Figure4-2}).\n\n\\begin{figure}[!htb]\n  \\centering\n  \\includegraphics[width=0.8\\textwidth]{Figure4-2}\\\\\n  \\caption{Object model design choices. One basic choice is to combine processes and data stores into a single object. This is the usual object-oriented choice. Another choice creates separate data objects and process objects.}\\label{fig:Figure4-2}\n\\end{figure}\n\nThe first choice combines data stores (object attributes) with processes (object methods) into a single object. In the second choice we use separate objects for data stores and processes. There is actually a third alternative: a hybrid combination of these two choices.\n\nThe conventional object-oriented approach (our first choice above) combines data stores and processes into a single object. This view follows the standard definition that objects contain a data representation combined with procedures to operate on the data. One advantage of this approach is that the processes, which are the data visualization algorithms, have complete access to the data structures, resulting in good computational performance. But this choice suffers from several drawbacks.\n\n\\begin{itemize}\n\n\\item From a user's perspective, processes are often viewed as independent of data representation. In other words, processes are naturally viewed as objects in the system. For example, we often say we want to \"contour\" data, meaning creating lines or surfaces corresponding to a constant data value. To the user it is convenient to have a single contour object to operate on different data representations.\n\n\\item We must duplicate algorithm implementation. As in the previous contouring example, if we bind data stores and processes into a single object, the contour operation must be recreated for each data type. This results in duplicating code even though the implementations of an algorithm may be functionally and structurally similar. Modifying such algorithms also means modifying a large amount of code, since they are implemented across many objects.\n\n\\item Binding data stores and algorithms together results in complex, data dependent code. Some algorithms may be much more complex than the data they operate on, with large numbers of instance variables and elaborate data structures. By combining many such algorithms with a data store, the complexity of the object greatly increases, and the simple meaning of the object becomes lost.\n\n\\end{itemize}\n\nThe second choice separates the data stores and processes. That is, one set of objects represents and provides access to the data, while another set of objects implements all operations on the data. Our experience shows that this is natural to users, although it may be considered unconventional to the object-oriented purist. We also have found that the resulting code is simple, modular, and easy for developers to understand, maintain, and extend.\n\nOne disadvantage to the second choice is that the interface between data representation and process is more formal. Thus the interface must be carefully designed to insure good performance and flexibility. Another disadvantage is that strong separation of data and process results in duplicate code. That is, we may implement operations that duplicate algorithms and that cannot be considered strictly data access methods. One example of such a situation is computing data derivatives. This operation is more than simple data access, so strictly speaking it doesn't belong in the data object methods. So to compute derivatives we would have to duplicate the code each time we needed derivatives computed. (Or create a procedural library of functions or macros!)\n\nAs a result of these concerns we use the hybrid approach in the \\emph{Visualization Toolkit}. Our approach is closest to the second choice described above, but we have selected a small set of critical operations that we implement within the data objects. These operations have been identified based on our experience implementing visualization algorithms. This effectively combines the first two choices to receive the maximum benefit and fewest disadvantages of each.\n\n\n\\section{The Visualization Pipeline}\n\\label{sec:visualization_pipeline}\n\nIn the context of data visualization, the functional model of Figure \\ref{fig:Figure4-1c} is referred to as the \\emph{visualization pipeline} or \\emph{visualization network}. The pipeline consists of objects to represent data (data objects), objects to operate on data (process objects), and an indicated direction of data flow (arrow connections between objects). In the text that follows, we will frequently use visualization networks to describe the implementation of a particular visualization technique.\n\n\\subsection{Data Objects}\n\\label{subsec:data_objects}\n\n\\emph{Data objects} represent information. Data objects also provide methods to create, access, and delete this information. Direct modification of the data represented by the data objects is not allowed except through formal object methods. This capability is reserved for process objects. Additional methods are also available to obtain characteristic features of the data. This includes determining the minimum and maximum data values, or determining the size or the number of data values in the object.\n\nData objects differ depending upon their internal representation. The internal representation has significant impact on the access methods to the data, as well as on the storage efficiency or computational performance of process objects that interact with the data object. Hence, different data objects may be used to represent the same data depending on demands for efficiency and process generality.\n\n\\subsection{Process Objects}\n\\label{subsec:process_objects}\n\n\\emph{Process objects} operate on input data to generate output data. A process object either derives new data from its inputs, or transforms the input data into a new form. For example, a process object might derive pressure gradient data from a pressure field or transform the pressure field into constant value pressure contours. The input to a process object includes both one or more data objects as well as local parameters to control its operation. Local parameters include both instance variables or associations and references to other objects. For example, the center and radius are local parameters to control the generation of sphere primitives.\n\nProcess objects are further characterized as \\emph{source objects}, \\emph{filter objects}, or \\emph{mapper objects}. This categorization is based on whether the objects initiate, maintain, or terminate visualization data flow.\n\nSource objects interface to external data sources or generate data from local parameters. Source objects that generate data from local parameters are called \\emph{procedural objects}. The previous example of Figure \\ref{fig:Figure4-1} uses a procedural object to generate function values for the quadric function of Equation \\ref{eq:4.1}. Source objects that interface to external data are called \\emph{reader} objects since the external file must be read and converted to an internal form. Source objects may also interface to external data communication ports and devices. Possible examples include simulation or modelling programs, or data acquisition systems to measure temperature, pressure, or other similar physical attributes.\n\nFilter objects require one or more input data objects and generate one or more output data objects. Local parameters control the operation of the process object. Computing weekly stock market averages, representing a data value as a scaled icon, or performing union set operations on two input data sources are typical example processes of filter objects.\n\nMapper objects correspond to the sinks in the functional model. Mapper objects require one or more input data objects and terminate the visualization pipeline data flow. Usually mapper objects are used to convert data into graphical primitives, but they may write out data to a file or interface with another software system or devices. Mapper objects that write data to a computer file are termed \\emph{writer} objects.\n\n\\section{Pipeline Topology}\n\\label{sec:pipeline_topology}\n\nIn this section we describe how to connect data and process objects to form visualization networks.\n\n\\subsection{Pipeline Connections}\n\\label{subsec:pipeline_connections}\n\nThe elements of the pipeline (sources, filters, and mappers) can be connected in a variety of ways to create visualization networks. However, there are two important issues that arise when we try to assemble these networks: \\emph{type} and \\emph{multiplicity}.\n\nType means the form or type of data that process objects take as input or generate as output. For example, a sphere source object may generate as output a polygonal or faceted representation, an implicit representation (e.g., parameters of a conic equation), or a set of occupancy values in a discretized representation of 3D space. Mapper objects might take as input polygonal, triangle strip, line, or point geometric representations. The input to a process object must be specified correctly for successful operation.\n\n\\begin{figure}[htb]\n    \\centering\n\t\\begin{subfigure}[h]{0.48\\linewidth}\n        \\centering\n\t\t\\includegraphics[width=0.56\\linewidth]{Figure4-3a}\n\t\t\\captionsetup{justification=centering}\n\t\t\\caption{Single type system \\\\ \\emph{Input Type = Output Type}} \n\t\t\\label{fig:Figure4-3a}\n\t\\end{subfigure}\n\t\\hfill\n\t\\begin{subfigure}[h]{0.48\\linewidth}\n\t\t\\includegraphics[width=0.96\\linewidth]{Figure4-3b}\n\t\t\\captionsetup{justification=centering}\n\t\t\\caption{Enforced type checking}\n\t\t\\label{fig:Figure4-3b}\n\t\\end{subfigure}\n\t\\caption{Maintaining compatible data type. (a) Single-type systems require no type checking. (b) In multiple-type systems only compatible types can be connected together.}\\label{fig:Figure4-3}\n\\end{figure}\n\nThere are two general approaches to maintain proper input type. One approach is to design with type-less or single-type systems. That is, create a single type of data object and create filters that operate only on this one type (Figure \\ref{fig:Figure4-3a}). For example, we could design a general \\emph{DataSet} that represents any form of data that we're interested in, and the process objects would only input \\emph{DataSets} and generate \\emph{DataSets}. This approach is simple and elegant, but inflexible. Often, particularly useful algorithms (i.e., process objects) will operate only on specific types of data and generalizing them results in large inefficiencies in representation or data access. A typical example is a data object that represents structured data such as pixmaps or 3D volumes. Because the data is structured it can easily be accessed as planes or lines. However, a general representation will not include this capability since typically data is not structured.\n\nAnother approach to maintain proper input type is to design typed systems. In typed systems only objects of compatible type are allowed to be connected together. That is, more than one type is designed, but type checking is performed on the input to insure proper connection. Depending on the particular computer language, type checking can be performed at compile, link, or run time. Although type checking does insure correct input type, this approach often suffers from an explosion of types. If not careful, the designers of a visualization system may create too many types, resulting in a fragmented, hard to use and understand system. In addition, the system may require a large number of \\emph{type-converter} filters. (Type-converter filters serve only to transform data from one form to another.) Carried to extremes, excessive type conversion results in computationally and memory wasteful systems.\n\nThe issue of multiplicity deals with the number of input data objects allowed, and the number of output data objects created during the operation of a process object (Figure \\ref{fig:Figure4-4}). We know that all filter and mapper objects require at minimum one input data object, but in general these filters can operate sequentially across a list of input. Some filters may naturally require a specific number of inputs. A filter implementing boolean operations is one example. Boolean operations such as union or intersection are implemented on data values two at a time. However, even here more than two inputs may be defined as a recursive application of the operation to each input.\n\n\\begin{figure}[!htb]\n  \\centering\n  \\includegraphics[width=0.8\\textwidth]{Figure4-4}\\\\\n  \\caption{Multiplicity of input and output. (a) Definition of source, filter, and mapper objects. (b) Various types of input and output.}\\label{fig:Figure4-4}\n\\end{figure}\n\nWe need to distinguish what is meant by multiplicity of output. Most sources and filters generate a single output. Multiple fan-out occurs when an object generates an output that is used for input by more than one object. This would occur, for example, when a source object is used to read a data file, and the resulting data is used to generate a wireframe outline of the data, plus contours of the data (e.g., Figure \\ref{fig:Figure4-1a}). Multiple output occurs when an object generates two or more output data objects. An example of multiple output is generating x, y, and z components of a gradient function as distinct data objects. Combinations of multiple fan-out and multiple output are possible.\n\n\\subsection{Loops}\n\\label{subsec:loops}\n\nIn the examples described so far, the visualization networks have been free of cycles. In graph theory these are termed directed, acyclic graphs. However, in some cases it is desirable to introduce feedback loops into our visualization networks. Feedback loops in a visualization network allow us to direct the output of a process object upstream to affect its input.\n\nFigure \\ref{fig:Figure4-5} shows an example of a feedback loop in a visualization network. We seed a velocity field with an initial set of random points. A probe filter is used to determine the velocity (and possibly other data) at each point. Each point is then repositioned in the direction of its associated vector value, possibly using a scale factor to control the magnitude of motion. The process continues until the points exit the data set or until a maximum iteration count is exceeded.\n\n\\begin{figure}[!htb]\n  \\centering\n  \\includegraphics[width=0.8\\textwidth]{Figure4-5}\\\\\n  \\caption{Looping in a visualization network. This example implements linear integration. The sample points are created to initialize the looping process. The output of the integration filter is used in place of the sample points once the process begins.}\\label{fig:Figure4-5}\n\\end{figure}\n\nWe will discuss the control and execution of visualization networks in the next section. However, suffice it to say that loops can pose special problem in visualization networks depending on the design of the execution model. The design must insure that the loop does not enter an infinite loop or nonterminating recursive state. Typically, the number of executions of the loop is limited in order to view intermediate results. However, it is possible to execute the loop repeatedly to process data as required.\n\n\\section{Executing the Pipeline}\n\\label{sec:executing_pipeline}\n\nSo far we have seen the basic elements of the visualization network and ways to connect these elements together. In this section we discuss how to control the execution of the network.\n\nTo be useful, a visualization network must process data to generate a desired result. The complete process of causing each process object to operate is called the execution of the network.\n\nMost often the visualization network is executed more than once. For example, we may change the parameters of, or the input to, a process object. This is typically due to user interaction: The user may be exploring or methodically varying input to observe results. After one or more changes to the process object or its input, we must execute the network to generate up-to-date results.\n\nFor highest performance, the process objects in the visualization network must execute only if a change occurs to their input. In some networks, as shown in Figure \\ref{fig:Figure4-6}, we may have parallel branches that need not execute if objects are modified local to a particular branch. In this figure, we see that object D and the downstream objects E and F must execute because D's input parameter is changed, and objects E and F depend on D for their input. The other objects need not execute because there is no change to their input.\n\nWe can control the execution of the network using either a demand-driven or event-driven approach. In the demand-driven approach, we execute the network only when output is requested, and only that portion of the network affecting the result. In the event-driven approach, every change to a process object or its input causes the network to reexecute. The advantage of the eventdriven approach is that the output is always up to date (except during short periods of computation). The advantage of the demand-driven approach is that large numbers of changes can be processed without intermediate computation (i.e., data is processed only after the request for data is received). The demand-driven approach minimizes computation and results in more interactive visualization networks.\n\n\\begin{figure}[!htb]\n  \\centering\n  \\includegraphics[width=0.8\\textwidth]{Figure4-6}\\\\\n  \\caption{Network execution. Parallel branches need not execute.}\\label{fig:Figure4-6}\n\\end{figure}\n\nThe execution of the network requires synchronization between process objects. We want to execute a process object only when all of its input objects are up to date. There are generally two ways to synchronize network execution: explicit or implicit control (Figure \\ref{fig:Figure4-7}).\n\n\\subsection{Explicit Execution}\n\\label{subsec:explicit_execution}\n\nExplicit control means directly tracking the changes to the network, and then directly controlling the execution of the process objects based on an explicit dependency analysis. The major characteristic of this approach is that a centralized \\emph{executive} is used to coordinate network execution. This executive must track changes to the parameters and inputs of each object, including subsequent changes to the network topology (Figure \\ref{fig:Figure4-7a}).\n\nThe advantage of this approach is that synchronization analysis and update methods are local to the single executive object. In addition, we can create dependency graphs and perform analysis of data flow each time output is requested. This capability is particularly important if we wish to decompose the network for parallel computing or to distribute execution across a network of computers.\n\nThe disadvantage of the explicit approach is that each process object becomes dependent upon the executive, since the executive must be notified of any change. Also, the executive cannot easily control execution if the network execution is conditional, since whether to execute or not depends on the local results of one or more process objects. Finally, a centralized executive can create non-scalable bottlenecks in parallel computing environments.\n\nThe explicit approach may be either demand-driven or event-driven. In the event-driven approach, the executive is notified whenever a change to an object occurs (typically in response to a user-interface event), and the network is immediately executed. In the demand-driven approach, the executive accumulates changes to object inputs and executes the network based on explicit user demand.\n\n\\begin{figure}[htb]\n    \\centering\n\t\\begin{subfigure}[h]{0.48\\linewidth}\n        \\centering\n\t\t\\includegraphics[width=0.96\\linewidth]{Figure4-7a}\n\t\t\\captionsetup{justification=centering}\n        \\captionsetup{singlelinecheck=off}\n\t\t\\caption{Explicit \\\\ \n        \\begin{enumerate}\n        \\item A parameter modified\n        \\item Executive performs dependency analysis\n        \\item Executive executes necessary modules in order A--B--C--D--E\n        \\end{enumerate}} \n\t\t\\label{fig:Figure4-7a}\n\t\\end{subfigure}\n\t\\hfill\n\t\\begin{subfigure}[h]{0.48\\linewidth}\n\t\t\\includegraphics[width=0.96\\linewidth]{Figure4-7b}\n\t\t\\captionsetup{justification=centering}\n        \\captionsetup{singlelinecheck=off}\n\t\t\\caption{Implicit \\\\ \n        \\begin{enumerate}\n        \\item A parameter modified\n        \\item E output requested\n        \\item Chain E--D--B--A back propagates \\texttt{Update()} method\n        \\item Chain A--B--D--E executes via \\texttt{RequestData()} method\n        \\end{enumerate}} \n\t\t\\label{fig:Figure4-7b}\n\t\\end{subfigure}\n\t\\caption{Explicit and implicit network execution.}\\label{fig:Figure4-7}\n\\end{figure}\n\n\nThe explicit approach with a central executive is typical of many commercial visualization systems such as AVS, Irix Explorer, and IBM Data Explorer. Typically these systems use a visual-programming interface to construct the visualization network. Often these systems are implemented on parallel computers, and the ability to distribute computation is essential.\n\n\\subsection{Implicit Execution}\n\\label{subsec:implicit_execution}\n\nImplicit control means that a process object executes only if its local input or parameters change (Figure 4-7 \\ref{fig:Figure4-7b}). Implicit control is implemented using a two-pass process. First, when output is requested from a particular object, that object requests input from its input objects. This process is recursively repeated until source objects are encountered. The source objects then execute if they have changed or their external inputs have changed. Then the recursion unwinds as each process object examines its inputs and determines whether to execute. This procedure repeats until the initial requesting object executes and terminates the process. These two steps are called the \\emph{update} and \\emph{execution} passes.\n\nImplicit network execution is naturally implemented using *demand-driven* control. Here network execution occurs only when output data is requested. Implicit network execution may also be event-driven if we simply request output each time an appropriate event is encountered (such as change to object parameter).\n\n\\begin{figure}[!htb]\n  \\centering\n  \\includegraphics[width=0.8\\textwidth]{Figure4-8}\\\\\n  \\caption{Examples of conditional execution. Depending upon range, data is mapped through different color lookup tables.}\\label{fig:Figure4-8}\n\\end{figure}\n\nThe primary advantage of the implicit control scheme is its simplicity. Each object only need keep track of its internal modification time. When output is requested, the object compares its modification time with that of its inputs, and executes if out of date. Furthermore, process objects need only know about their direct input, so no global knowledge of other objects (such as a network executive) is required.\n\nThe disadvantage of implicit control is that it is harder to distribute network execution across computers or to implement sophisticated execution strategies. One simple approach is to create a queue that executes process objects in order of network execution (possibly in a distributed fashion). Of course, once a central object is introduced back into the system, the lines between implicit and explicit control are blurred.\n\n\\subsection{Conditional Execution}\n\\label{subsec:conditional_execution}\n\nAnother important capability of visualization networks is conditional execution. For example, we may wish to map data through different color lookup tables depending upon the variation of range in the data. Small variations can be amplified by assigning more colors within the data range, while we may compress our color display by assigning a small number of colors to the data range (Figure \\ref{fig:Figure4-8}). \n\nThe conditional execution of visualization models (such as that shown Figure \\ref{fig:Figure4-1c}) can be realized in principle. However, in practice we must supplement the visualization network with a conditional language to express the rules for network execution. Hence, conditional execution of visualization networks is a function of implementation language. Many visualization systems are programmed using the visual programming style. This approach is basically a visual editor to construct data flow diagrams directly. It is difficult to express conditional execution of networks using this approach. Alternatively, in a procedural programming language, conditional execution of networks is straightforward. We defer discussions of the topic until ``Putting It All Together'' on page \\pageref{sec:chap04.putting_it_all_together}.\n\n\\section{Memory and Computation Trade-off}\n\\label{sec:memory_computation_trade-off}\n\nVisualization is a demanding application, both in terms of computer memory and computational requirements. Data streams on the order of one megabyte to one gigabyte are not uncommon. Many visualization algorithms are computationally expensive, in part due to input size, but also due to the inherent algorithm complexity. In order to create applications that have reasonable performance, most visualization systems have various mechanisms to trade off memory and computation costs.\n\n\\begin{figure}[!htb]\n  \\centering\n  \\includegraphics[width=0.8\\textwidth]{Figure4-9}\\\\\n  \\caption{Comparison of static versus dynamic memory models for typical network. Execution begins when output is requested from objects \\emph{C} and \\emph{D}. In more complex dynamic models, we can prevent \\emph{B} from executing twice by performing a more thorough dependency analysis image.}\\label{fig:Figure4-9}\n\\end{figure}\n\n\\subsection{Static and Dynamic Memory Models}\n\\label{subsec:static_dynamic_memory_models}\n\nMemory and computation trade-offs are important performance issues when executing visualization networks. In the networks presented thus far, the output of a process object is assumed to be available to downstream process objects at all times. Thus, network computation is minimized. However, the computer memory requirement to preserve filter output can be huge. Networks of only a few objects can tie up extensive computer memory resources.\n\nAn alternative approach is to save intermediate results only as long as they are needed by other objects. Once these objects finish processing, the intermediate result can be discarded. This approach results in extra computation each time output is requested. The memory resources required are greatly reduced at the expense of increased computation. Like all trade-offs, the proper solution depends upon the particular application and the nature of the computer system executing the visualization network.\n\nWe term these two approaches as \\emph{static} and \\emph{dynamic} memory models. In the static model intermediate data is saved to reduce overall computation. In the dynamic model intermediate data is discarded when it is no longer needed. The static model serves best when small, variable portions of the network reexecute, and when the data sizes are manageable by the computer system. The dynamic model serves best when the data flows are large, or the same part of the network executes each time. Often, it is desirable to combine both the static and dynamic models into the same network. If an entire leg of the network must execute each time, it makes no sense to store intermediate results, since they are never reused. On the other hand, we may wish to save an intermediate result at a branch point in the network, since the data will more likely be reused. A comparison of the static and dynamic memory model for a specific network is shown in Figure \\ref{fig:Figure4-9}.\n\n\\begin{figure}[!htb]\n  \\centering\n  \\includegraphics[width=0.8\\textwidth]{Figure4-10}\\\\\n  \\caption{Reference counting to conserve memory resource. Each filter \\emph{A}, \\emph{B}, and \\emph{C} shares a common point representation. Other data is local to each object.}\\label{fig:Figure4-10}\n\\end{figure}\n\nAs this figure shows, the static model executes each process object only once, storing intermediate results. In the dynamic model, each process object releases memory after downstream objects complete execution. Depending upon the implementation of the dynamic model, process object \\emph{B} may execute once or twice. If a thorough dependency analysis is performed, process \\emph{B} will release memory only after both objects \\emph{C} and \\emph{B} execute. In a simpler implementation, object \\emph{B} will release memory after \\emph{C} and subsequently, \\emph{D} executes.\n\n\\subsection{Reference Counting and Garbage Collection}\n\\label{subsec:reference_counting_garbage_collection}\n\nAnother valuable tool to minimize memory cost is to share storage using reference counting. To use reference counting, we allow more than one process object to refer to the same data object and keep track of the number of references. For example, assume that we have three objects *A*, *B*, and *C* that form a portion of a visualization network as shown in Figure \\ref{fig:Figure4-10}. Also assume that these objects modify only part of their input data, leaving the data object that specifies *x-y-z* coordinate position unchanged. Then to conserve memory resources we can allow the output of each process object to refer to the single data object representing these points. Data that is changed remains local to each filter and is not shared. It is only when the reference count goes to zero that the object is deleted.\n\nGarbage collection is an alternative memory management strategy that is not well suited to visualization applications. The garbage collection process is automatic; it attempts to reclaim memory used by objects that will never again be accessed by the running application. While convenient due to its automated nature, in general garbage collection introduces overhead that may inadvertently introduce pauses into software execution at inopportune times (during an interactive process). Of more concern, however, is that released, unused memory may not be reclaimed by the system until some time after the last reference to the memory is dropped, and in visualization pipelines this memory may be too large to leave around for any length of time. That is, in some applications if memory usage in a filter is not released immediately, downstream filters may not have enough memory resource available to them to successfully execute.\n\n\\section{Advanced Visualization Pipeline Models}\n\\label{sec:advanced_visualization_pipeline_models}\n\nThe preceding sections have provided a general framework for the implementation of a useful visualization pipeline model. However, there are several advanced capabilities that complex applications often require. These capabilities are driven by deficiencies in the simpler design described previously. The principle drivers for developing advanced models include: processing unknown dataset types, managing complex execution strategies including processing pieces of data, and extending the visualization pipeline to propagate new information. These concerns are discussed in the following three sections.\n\n\\subsection{Processing Unknown Dataset Types}\n\\label{subsec:processing_unknown_dataset_types}\n\nThere exist data files and data sources where the type of dataset represented by the file or source is unknown until run-time. For example, consider a general purpose VTK reader that can read any type of VTK data file. Such a class is convenient because the user need not concern himself with the type of dataset, instead the user may want to set up a single pipeline that processes whatever type is found. As indicated by Figure \\ref{fig:Figure4-3}, such an approach works well if the system is of a single dataset type, however in practice, and due to performance/efficiency concerns, there typically exist many different types of data in a visualization system. The other alternative shown in Figure \\ref{fig:Figure4-3} is enforced type checking. However, in situations like the reader example described above, it is not possible to enforce type checking at compile-time because the type is determined by the data. As a result, type checking must be performed at run-time.\n\nRun-time type checking of a multiple dataset type visualization system requires that the data passed between filters is a generic dataset container (i.e., it appears like a single type but contains the actual data and methods to determine what type of data it is). Run-time type checking has the advantage of flexibility, but the trade-off is that a pipeline may not execute properly until the program executes. For example, a generic pipeline may be designed that can process structured data (see ``Types of Datasets''on page \\pageref{sec:types_of_datasets}), but the data file may contain unstructured data. In this case, the pipeline will be unable to execute at run-time, producing empty output. Thus pipelines designed to process any type of data must be carefully assembled to create robust applications.\n\n\\subsection{Extending the Data Object Representation}\n\\label{subsec:extending_data_object_representation}\n\nAs described earlier in this chapter, a pipeline consists of data objects that are operated on by process objects. Further, because the process objects are separate from the data objects on which they operate, there is necessarily an expected interface through which these objects exchange information. Defining this interface has the side effect of cementing the data representation, implying that it is difficult to extend it without modifying the corresponding interface, and hence all the classes that depend on the interface (of which there are many). Fortunately what tends to change is not the basic data representations (these are generally well established), rather the metadata associated with the dataset itself changes. (In the context of visualization, metadata are data that describe datasets.) While it is feasible to represent new datasets by creating new classes (since the addition of new dataset types occurs infrequently); the diversity of metadata precludes creating new classes because the resulting explosion of data types, and the potential change to programming interfaces, would adversely affect the stability of the visualization system. Hence a general mechanism to support metadata is required. Packaging metadata into a generic container that contains both the dataset andcmetadata is a obvious design, and is compatible with the design described in the previous section.\n\nExamples of metadata include time step information, data ranges or other data characteristics, acquisition protocols, patient names, and annotation. In an extensible visualization pipeline, a specific data reader (or other data source) may read such information and associate it with the output data that it produces. While many filters may ignore the metadata, they can be configured to pass the information along the pipeline. Alternatively, a pipeline sink (or mapper) may request that specific metadata be passed through the pipeline so it can be processed appropriately. For example, a mapper may request annotations, and if available, place them on the final image.\n\n\\subsection{Managing Complex Execution Strategies}\n\\label{subsec:managing_complex_execution_strategies}\n\nIn real-world applications the pipeline design described thus far may not adequately support complex execution strategies, or may fail to execute successfully when data sizes become large. In the next sections we address these issues by considering alternative design possibilities.\n\n\\textbf{Large Data}. Previous discussions relative to the visualization pipeline have assumed that the size of a particular dataset does not exceed the total memory resource of a computer system. However, with modern dataset sizes pushing into the terabyte and even petabyte range, a typical desktop computer system is incapable of processing such datasets. Thus alternative strategies must be adopted when processing large data. One such approach is based on breaking data into pieces, and then *streaming* the pieces through the visualization pipeline \\cite{Martin01}. Figure \\ref{fig:Figure4-11} illustrates how a dataset can be divided into pieces.\n\n\\begin{figure}[!htb]\n  \\centering\n  \\includegraphics[width=0.8\\textwidth]{Figure4-11}\\\\\n  \\caption{Dividing a sphere into a piece (red) with ghost level cells and points (blue and green).}\\label{fig:Figure4-11}\n\\end{figure}\n\nStreaming data through a visualization pipeline offers two major benefits. The first is that visualization data that would not normally fit into memory can be processed. The second is that visualizations can be run with a smaller memory footprint resulting in higher cache hits, and little or no swapping to disk. To realize these benefits the visualization software must support breaking the dataset into pieces and correctly processing those pieces. This requires that the dataset and the algorithms that operate on it are \\emph{separable}, \\emph{mappable}, and \\emph{result invariant} as described in the following \\cite{Law99}.\n\n\\begin{enumerate}\n\\item \\textbf{Separable}. The data must be separable. That is, the data can be broken into pieces. Ideally, each piece should be coherent in geometry, topology, and/or data structure. The separation of the data should be simple and efficient. In addition, the algorithms in this architecture must be able to correctly process pieces of data.\n\n\\item \\textbf{Mappable}. In order to control the streaming of the data through a pipeline, we must be able to determine what portion of the input data is required to generate a given portion of the output. This allows us to control the size of the data through the pipeline, and configure the algorithms.\n\n\\item \\textbf{Result Invariant}. The results should be independent of the number of pieces, and independent of the execution mode (i.e., single- or multi-threaded). This means proper handling of boundaries and developing algorithms that are multi-thread safe across pieces that may overlap on their boundaries.\n\\end{enumerate}\n\nSeparating data into pieces is relatively straightforward if the data is structured, i.e., topologically regular (see ``Types of Datasets'' on page \\pageref{sec:types_of_datasets}). Such datasets can be topological described by a rectangular extent in a regularly $x-y-z$ subdivided cubical domain (see Figures \\ref{fig:Figure5-7}(a)-(c)). However, if the data is unstructured (e.g. a mesh of triangles or polygons), then specifying pieces is difficult. Generally an unstructured extent is defined by grouping adjacent data (e.g., cells) into pieces, and then addressing each piece using a $N$ of $M$ notation, where $N$ is the $n$-th piece out of a total of $M$ pieces. The exact organizational structure of a piece is left unspecified and depends on the particular application and algorithm used to group the data.\n\nTo satisfy the third requirement of results invariancy, processing pieces also requires the abiity to generate boundary data, or \\emph{ghost levels}. Boundary information is necessary when information from the neighbors of a piece is needed to perform a computation. For example, gradient calculations or boundary analysis (e.g., do I have a cell face neighbor?) require one level of boundary information. In rare cases, two or more levels are required. Figure \\ref{fig:Figure4-11} illustrates boundary cells and points corresponding to the central red piece of the sphere.\n\nFinally, it should be noted that the ability to divide data into pieces for streaming is exactly the same capability required for data parallel processing. In such methods, data is subdivided and sent to different processors to be operated on in parallel. Boundary information may also be required to perform certain computations. Parallel processing has the added complexity that the data must be communicated to processors (in the case of distributed computing) or mutual exclusion (i.e., mutexing) must be employed to avoid simultaneous write operations. Thus streaming and parallel processing are complementary technologies used in large data computing.\n\n\\subsubsection{Complex Execution Strategies}\n\\label{subsubsec:complex_execution_strategies}\n\nIn many cases the simple execution model of Figure \\ref{fig:Figure4-7b} is not suitable for complex data processing tasks. For example, as discussed in the previous section, streaming data is a complex execution strategy required when a dataset becomes too large to fit into memory, or when parallel computing is used. In some cases event-driven (see ``Executing the Pipeline''on page \\pageref{sec:executing_pipeline}) or ``push'' pipelines (i.e., those that receive data and push the data through the pipeline for processing) may be preferred. Finally, there exist hierarchical data structures such as multi-block or adaptive mesh refinement (AMR) \\cite{Berger84} grids. Processing such datasets in a pipeline requires hierarchical traversal as filters process each block in the grid (an advanced research topic in the visualization field and not covered in this edition of the book).\n\nAddressing these requirements implies that the execution model must be extended. Thus we revisit the object-oriented design in the next section.\n\n\\subsubsection{Object-Oriented Design Revisited}\n\\label{subsubsec:object_oriented_design_revisited}\n\nFigure \\ref{fig:Figure4-2} illustrates two choices relative to the design of the visualization object model. The first choice, which was discarded, was to combine data and operations on the data into a single object, a typical object-oriented design pattern. The second choice, which was advocated, was to create a design consisting of two classes --- data objects and process objects --- which were then combined into visualization pipelines. While this second strategy works well for simple pipelines, when complex execution strategies are introduced, this design begins to break down. This is because the execution strategy is necessarily, and implicitly, distributed across the data objects and process objects; there is no explicit mechanism to implement a particular strategy. Thus the design is problematic because new strategies cannot be introduced without modifying the interface to both the data and process objects. Good design demands that the execution strategy is separated from the data objects and process objects. The benefits of such a design include reducing the complexity of the data and process objects, encapsulating execution strategies, performing run-time type checking (see ``Processing Unknown Dataset Types'' on page \\pageref{subsec:processing_unknown_dataset_types}) and even managing metadata (see ``Extending the Data Object Representation''on page  \\pageref{subsec:extending_data_object_representation}).\n\nAs the execution model becomes more complex, execution strategies are separated from the data and process objects as separate classes.\n\n\\begin{wrapfigure}{r}{0.4\\textwidth}\n  \\centering\n  \\includegraphics[width=0.96\\textwidth]{Figure4-12}\\\\\n  \\caption{As the execution model becomes more complex, execution strategies are separated from the data and process objects as separate classes.}\\label{fig:Figure4-12}\n\\end{wrapfigure}\n\nThe advanced design re-introduces the notion of an executive (see ``Executing the Pipeline'' on page \\pageref{sec:executing_pipeline}). However, the design differs from that of Figure \\ref{fig:Figure4-7}. As that figure illustrated, a single, centralized executive introduces dependencies into the pipeline that will not scale as pipeline complexity increases, or in parallel processing applications. In the advanced design, we assume \\emph{multiple} executives, typically one per filter. In  some cases the executive may control multiple filters. This is particularly useful if the filters are interdependent or complex execution strategies are required. Different classes of executive can implement different execution strategies, for example a demand-driven, streaming pipeline is one such strategy. Other important classes include executives that coordinate the execution of filters on composite datasets.\n\nFigure \\ref{fig:Figure4-12} is a high-level view of the executive and its relationship to data and process objects. In ``Pipeline Design and Implementation'' on page \\pageref{subsec:pipeline_design_implementation} the design is explored in more detail.\n\n\\section{Programming Models}\n\\label{sec:programming_models}\n\nVisualization systems are by their very nature designed for human interaction. As a result they must be easy to use. On the other hand, visualization systems must readily adapt to new data, and must be flexible enough to allow rapid data exploration. To meet these demands, a variety of programming models have been developed.\n\n\\subsection{Visualization Models}\n\\label{subsec:visualization_models}\n\nAt the highest level are applications. Visualization applications have finely tailored user-interfaces that are specific to an application area, e.g., fluid flow visualization. Applications are the easiest to use, but are the least flexible. It is very difficult or impossible for the user to extend applications into a new domain because of inherent logistical issues. Commercial turn-key visualization software is generally considered to be application software.\n\nAt the opposite end of the spectrum are programming libraries. A conventional programming library is a collection of procedures that operate on a library-specific data structure. Often these libraries are written in conventional programming languages such as C or FORTRAN. These offer great flexibility and can be easily combined with other programming tools and techniques. Programming libraries can be extended or modified by the addition of user-written code. Unfortunately, the effective use of programming libraries requires skilled programmers. Furthermore, non graphics/visualization experts cannot easily use programming libraries because there is no notion of how to fit (or order) the procedures together correctly. These libraries also require extensive synchronization schemes to control execution as input parameters are varied.\n\nMany visualization systems lie between these two extremes. These typically use a \\emph{visual programming} approach to construct visualization networks. The basic idea is to provide graphical tools and libraries of modules or process objects. Modules may be connected subject to input/output type constraints, using simple graphical layout tools. In addition, user interface tools allow association of interface widgets with object input parameters. System execution is generally transparent to the user by way of an internal execution executive.\n\n\\subsection{Alternative Visual Programming Models}\n\\label{subsec:alternative_visual_programming_models}\n\nThere are two other graphics and visualization programming models that bear mentioning. These are \\emph{scene graphs} and the \\emph{spreadsheet} model. \n\nScene graphs are typically found in 3D graphics systems such as OpenInventor \\cite{Wernecke94}. Scene graphs are acyclic tree-structures that represent objects, or nodes, in an order defined by the tree layout. The nodes may be geometry (called shape nodes), graphics properties, transformations, manipulators, lights, cameras, and so forth, that define a complete scene. The parent/child relationship controls how properties and transformations are applied to the nodes as they are rendered, or how the objects relate to other objects in the scene (e.g., which objects the lights shine on). Scene graphs are not used to control the execution of a visualization pipeline, rather they are used to control the rendering process. Scene graphs and visualization pipelines may be used together in the same application. In such a case the visualization pipeline is the generator of the shape nodes, and the scene graph controls the rendering of the scene including the shapes.\n\nScene graphs have found wide use in the graphics community because of their ability to compactly and graphically represent a scene. In addition, scene graphs have been popularized by their recent use in Web tools such as VRML and Java3D. See Chapter 11: \\nameref{chap:visualization_web} for more information.\n\nAnother recently introduced technique for visual programming is the spreadsheet technique of Levoy \\cite{Levoy94}. In the spreadsheet model, we arrange operations on a regular grid similar to the common electronic accounting spreadsheets. The grid consists of rows and columns of cells, where each cell is expressed as a computational combination of other cells. The combination is expressed for each cell by using a simple programming language to add, subtract, or perform other more complex operations. The result of the computation (i.e., a visual output) is displayed in the cell. A recent extension to the spreadsheet approach is exemplified by VisTrails \\cite{Bavoil05}, a system that enables interactive multiple-view visualizations by simplifying the creation and maintenance of visualization pipelines, and by optimizing the execution of the pipelines. VisTrials has the further benefit that it tracks changes to the visualization pipeline so that it is straightforward to create extensive design studies.\n\nAlthough visual programming systems are widely successful, they suffer two drawbacks. First, they are not as tailored as an application and require extensive programming, albeit visual, to be so. Second, visual programming is too limited for detailed control, so constructing complex low-level algorithms and user-interfaces is not feasible. What is required is a visualization system that provides the ``modularity'' and automatic execution control of a visual system, and the low-level programming capability of a programming library. Object-oriented systems have the potential to provide these capabilities. Carefully crafted object libraries provide the ease of use of visual systems with the control of programming libraries. That is a major goal of the described in this text.\n\n\\section{Data Interface Issues}\n\\label{sec:data_interface_issues}\n\nAt this point in the text you may be wondering how to apply a visualization pipeline towards your own data. The answer depends on the type of data you have, preferences in programming style, and required complexity. Although we have not yet described particular types of data (we will in the next chapter), there are two general approaches you may wish to consider when interfacing your data to a visualization system: a programming interface and an application interface.\n\n\\section{Programming Interface}\n\\label{sec:programming_interface}\n\nThe most powerful and flexible approach is to directly program your application to read, write, and process data. There is almost no limit to what you can achieve using this approach. Unfortunately, in a complex system like VTK this requires a level of expertise that may be beyond your time budget to obtain. (If you are interested in this approach using VTK, you'll have to become familiar with the objects in the system. You will also want to refer to the Doxygen-generated manual pages --- on-line at \\href{https://www.vtk.org}{https://www.vtk.org} or CD-ROM. The companion text \\emph{The VTK User's Guide} is also helpful.)\n\nTypical applications requiring a programming interface are interfacing to data files that are not currently supported by the system or generating synthetic data (e.g., from a mathematical relationship) where no data file is available. Also, sometimes it is useful to directly code your data in the form of a program, and then execute the program to visualize the results. (This is exactly what many of the VTK examples do.)\n\nIn general, programming a complex system such as VTK is a difficult undertaking because of the initial learning curve. There are, however, simpler ways to interface to data. While skilled developers may be required to create sophisticated applications, the points of an object-oriented toolkit like VTK is that it provides many of the pieces required to interface to common data forms. Thus focusing on those objects that import and export data is a good start towards interfacing with data. In VTK, these objects are known as readers, writers, importers and exporters.\n\n\\subsubsection{File Interface (Readers / Writers)}\n\\label{subsubsec:file_interface_readers_writers}\n\nIn this chapter we saw that readers are source objects, and writers are mappers. What this means from a practical point of view is that readers will ingest data from a file, create a data object, and then pass the object down the pipeline for processing. Similarly, writers ingest a data object and then write the data object to a file. Thus, readers and writers will interface to your data well if VTK supports your format, \\emph{and} you only need to read or write a \\emph{single} data object. If your data file format is not supported by the system, you will need to interface to your data via a general programming interface described above. Or, if you wish to interface to a collection of objects, you will probably want to see whether an exporter or importer object (described in the next section) exists to support your application.\n\nExamples of readers include vtkSTLReader (read stereo-lithography files) and vtkBYUReader (read MOVIE.BYU format data files). Similarly the objects vtkSTLWriter and vtkBYUWriter can be used to write data files. To see which readers and writers are supported by VTK, see \\emph{The VTK User's Guide} or refer to the Web pages at \\href{https://www.vtk.org}{https://www.vtk.org} for the current Doxygen manual pages.\n\n\\subsubsection{File Interface (Importers / Exporters)}\n\\label{subsubsec:file_interface_importers_exporters}\n\n\\emph{Importers} and \\emph{exporters} are objects in the system that read or write data files consisting of more than one object. Typically importers and exporters are used to save or restore an entire scene (i.e., lights, cameras, actors, data, transformations, etc.). When an importer is executed, it reads one or more files and may create several objects. For example, in VTK the vtk3DSImporter imports a \\emph{3D Studio} file and creates a rendering window, renderer, lights, cameras, and actors. Similarly, the vtkVRMLExporter creates a VRML file given a VTK render window. The VRML file contains cameras, lights, actors, geometry, transformations, and the like, indirectly referred to by the rendering window provided.\n\nIn the \\emph{Visualization Toolkit}, there are several importers and exporters. To see which importers and exporters are supported by VTK, see \\emph{The VTK User's Guide}. You may also want to check the Web pages at \\href{https://www.vtk.org}{https://www.vtk.org} for the current Doxygen manual pages. If the exporter you are looking for does not exist, you will have to develop your own using the programming interface.\n\n\\begin{figure}[htb]\n  \\begin{subfigure}[h]{0.48\\linewidth}\n    \\includegraphics[width=0.96\\linewidth]{Figure4-13a}\n    \\caption*{}\n    \\label{fig:Figure4-13a}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[h]{0.48\\linewidth}\n    \\includegraphics[width=0.96\\linewidth]{Figure4-13b}\n    \\caption*{See:  \\href{https://lorensen.github.io/VTKExamples/site/Cxx/IO/3DSImporter/}{3DSImporter.cxx} and \\href{https://lorensen.github.io/VTKExamples/site/Python/IO/3DSImporter/}{3DSImporter.py}})\n    \\label{fig:Figure4-13b}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[h]{0.96\\linewidth}{Figure4-13c}\n  \\begin{lstlisting}[language=TCL,  caption={}, numbers=none, frame=none]\n    # import from 3d Studio\n    vtk3DSImporter importer\n      importer ComputeNormalsOn\n      importer SetFileName \"$VTK_DATA_ROOT/Data/iflamigm.3ds\"\n      importer Read\n    # export to rib format\n    vtkRIBExporter exporter\n      exporter SetFilePrefix importExport\n      exporter SetRenderWindow [importer GetRenderWindow]\n      exporter BackgroundOn\n      exporter Write\n    \\end{lstlisting} \n    \\caption*{}\n    \\label{fig:Figure4-13c}\n  \\end{subfigure}\n  \\caption{Importing and exporting files in VTK. An importer creates a vtkRenderWindow that describes the scene. Exporters use an instance of vtkRenderWindow to obtain a description of the scene.}\\label{fig:Figure4-13}\n\\end{figure}\n\nFigure \\ref{fig:Figure4-13} shows an image created from a *3D Studio* model and saved as a *Renderman* RIB file.\n\n\\subsection{Application Interface}\n\\label{subsec:application_interface}\n\nThe majority of users interface to their data by using an existing application. Rather than programming pipelines or writing their own readers and writers, users acquire an application that suits their particular visualization needs. Then to interface to their data, users simply identify the reader, writer, importer, and/or exporter that can successfully process it. In some cases, users may have to modify the program used to generate the data so that it exports it in a standard data format. The advantage of using existing applications is that the user interface and pipeline are pre-programmed, insuring that the user can focus on their data, rather than expending the significant resources required to write visualization programs. The disadvantage of using existing applications is that necessary features are often missing, and applications typically lack the flexibility that a general purpose tool can provide.\n\n\\begin{figure}[htb]\n  \\begin{subfigure}[h]{0.48\\linewidth}\n    \\includegraphics[width=0.96\\linewidth]{Figure4-14a}\n    \\caption{Paraview parallel visualization application}\n    \\label{fig:Figure4-14a}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[h]{0.48\\linewidth}\n    \\includegraphics[width=0.96\\linewidth]{Figure4-14b}\n    \\caption*{VolView volume rendering application}\n    \\label{fig:Figure4-14b}\n  \\end{subfigure}\n  \\caption{The choice of an appropriate visualization application depends on the type of dataset(s) it must support, required interaction techniques, rendering capabilities, and support for large data, including parallel processing. While both applications above are built using the VTK visualization toolkit, they provide very different user experiences. ParaView (\\href{https://www.paraview.org/}{https://www.paraview.org/}) is a general purpose visualization system that can process large data in a distributed, parallel environment (as well as on single processor systems), with the ability to display on a Cave or tiled display. VolView (\\href{https://www.kitware.com/volview/}{https://www.kitware.com/volview/}) focuses on volumetric and image data and uses multi-threading and sophisticated level-of-detail methods to achieve interactive performance.}\\label{fig:Figure4-14}\n\\end{figure}\n\nSelecting the right application is not always simple. The application must support the correct dataset types, and support suitable rendering devices, for example generating images on large displays \\cite{Humphreys99} or in a Cave \\cite{CruzNeira93} environment. In some cases user interaction is required, and demands on parallel processing or data handling capacities further complicates the selection. For example, while a general purpose tool like ParaView (Figure \\ref{fig:Figure4-14a}) can be used to visualize most types of data, including providing support for large data and parallel computing, a specialized tool such as VolView (Figure \\ref{fig:Figure4-14}(b) )may be better suited for a particular type task such as viewing medical data shown in the figure. It is imperative that users have a familiarity with the visualization process if they are to successfully choose the right application for their data.\n\n\\section{Putting It All Together}\n\\label{sec:chap04.putting_it_all_together}\n\nIn the previous sections we have treated a variety of topics relating to the visualization model. In this section we describe the particular implementation details that we have adopted in the \\emph{Visualization Toolkit}.\n\n\\subsection{Procedural Language Implementation}\n\\label{subsec:procedural_language_implementation}\n\nThe \\emph{Visualization Toolkit} is implemented in the procedural language C++. Automated wrapping technology creates language bindings to the Python, Tcl and Java interpretive programming languages \\cite{King03}. The class library contains data objects, filters (i.e., process objects) and executives to facilitate the construction of visualization applications. A variety of supporting abstract super-classes are available to derive new objects including data objects and filters. The visualization pipeline is designed to connect directly to the graphics subsystem described in the previous chapter. This connection is via VTK's mappers, which are the sinks of the pipeline and interface to the VTK's actors.\n\nA visual programming interface could be (and has been) implemented using the class library provided. However, for real-world applications the procedural language implementation provides several advantages. This includes straightforward implementation of conditional network execution and looping, ease of interface to other systems, and the ability to create custom applications with sophisticated graphical user interfaces. The VTK community has created several visual programming and visualization applications from the toolkit. Many of these are available as open-source software (e.g., ParaView at paraview.org) or as commercial applications (e.g., VolView at \\href{https://www.kitware.com/volview/}{https://www.kitware.com/volview/}).\n\n\\subsection{Pipeline Design and Implementation}\n\\label{subsec:pipeline_design_implementation}\n\nThe \\emph{Visualization Toolkit} implements a general execution mechanism. Filters are divided into two basic parts: algorithm and executive objects. An algorithm object, whose class is derived from vtkAlgorithm, is responsible for processing information and data. An executive object, whose class is derived from vtkExecutive, is responsible for telling an algorithm when to execute and what information and data to process. The executive component of a filter may be created independently of the algorithm component allowing custom pipeline execution mechanisms without modifying core VTK classes.\n\nInformation and data produced by a filter are stored in one or more output \\emph{ports}. An output port corresponds to one logical output of the filter. For example, a filter producing a color image and a corresponding binary mask image would define two output ports, each holding one of the images. Pipeline--related information is stored in an instance of vtkInformation on each output port. The data for an output port is stored in an instance of a class derived from vtkDataObject.\n\nInformation and data consumed by a filter are retrieved through one or more input ports. An input port corresponds to one logical input of 1ethe filter. For example, a glyph filter would define one input port for the glyph itself and another input port defining the glyph positions. Input ports store input connections that reference the output ports of other filters; these output ports eventually provide information and data to the filter. Each input connection provides one data object and its corresponding information obtained from the output port to which the connection is made. Since connections are stored through logical ports and not in the data flowing through those ports, the data type need not be known when the connection is made. This is particularly useful when creating pipelines whose source is a reader that does not know its output data type until the file is read (see \\nameref{subsec:pipeline_connections} and \\nameref{subsec:processing_unknown_dataset_types}).\n\n\\begin{figure}[!htb]\n  \\centering\n  \\includegraphics[width=0.8\\textwidth]{Figure4-15}\\\\\n  \\caption{Description of implicit execution process implemented in VTK. The Update() method is initiated via the Render() method from the actor. Data flows back to the mapper via the RequestData() method. Arrows connecting filter and data objects indicate direction of the Update() process.}\\label{fig:Figure4-15}\n\\end{figure}\n\nTo understand the execution of the VTK pipeline, it is useful to view the process from several different vantage points. Note that each of the following figures is not completely accurate, rather they are presented as depictions whose purpose is to describe the important features of the process.\n\nFigure \\ref{fig:Figure4-15} shows a simplified description of VTK's execution process. Generally the execution of the pipeline is triggered by a mapper's Render() method invocation, typically in response to a Render() method invocation on an associated vtkActor (which in turn receives it from the render window). Next, the Update() method is called on the input to the mapper (resulting in a cascade of method invocations requesting information and data). Eventually, data must be computed and returned to the object initiating the request, in this case the mapper. The RequestData() method actually executes the filter(s) in the pipeline and produces output data. Note the direction of flow --- here we define the direction of data flow as the \\emph{downstream} direction, and the direction of the Update() invocation the \\emph{upstream} direction.\n\n\\begin{figure}[!htb]\n  \\centering\n  \\includegraphics[width=0.8\\textwidth]{Figure4-16}\\\\\n  \\caption{The logical relationship of the algorithm, executive and ports constituting a filter. The executive is responsible for managing the execution of the algorithm, and coordinating with information requests traveling through the pipeline. Ports correspond to logical, distinct inputs and outputs.}\\label{fig:Figure4-16}\n\\end{figure}\n\nThe next figure, Figure \\ref{fig:Figure4-16}, shows the relationship between the executive and the algorithm, which are paired to form a filter. This view of the filter is independent of the pipeline and contains all the information about the interface of the algorithm, namely the number and availability of inputs and outputs. Finally Figure \\ref{fig:Figure4-17} shows the connections between filters. Notice that the output data object is not directly wired to the input connection. Rather the downstream filters's input connection is associated with the upstream filter's output port. This separation of data object from the input port means that data type checking can be deferred until run-time, when the consuming filter requests data from the producer of the data. Thus the producer can generate different types of data (e.g., it is a reader that produces different data types), and as long as the consumer supports these different data types, the pipeline will Qexecute without error.\n\n\\subsection{Connecting Pipeline Objects}\n\\label{subsec:connecting_pipeline_objects}\n\nThis leads us to the method of making connections between filters and data objects to form a visualization pipeline. As is evident from the previous figures, the \\emph{Visualization Toolkit} pipeline architecture has been designed to support multiple inputs and outputs. In practice, you will find that most filters and sources actually generate a single output and filters accept a single input. This is because most algorithms tend to be single input/output in nature. There are exceptions and we will describe some of these shortly. However, first we would like to provide a brief history lesson relative to the evolution of VTK's pipeline architecture. This lesson is instructive because it sheds light on the evolution of the pipeline design in response to new requirements.\n\nPrior to VTK 5.0. In earlier versions of VTK (i.e., prior to version 5.0), the visualization pipeline architecture was accurately depicted by Figure \\ref{fig:Figure4-15}. In this figure, which shows how filters and data objects were connected to form a visualization network, the input data was represented by the Input instance variable and was set using the SetInput() method. The output data was represented by the Output instance variable and was accessed using the GetOutput() method. To connect filters together, the C++ statement\n\n\\begin{lstlisting}[language=C++, caption={}]\nfilter2->SetInput(filter1->GetOutput()); //Prior to VTK5.0\n\\end{lstlisting}\n\nwas typically used with filter1 and filter2 filter objects of compatible type. In this design, compiletime type checking was performed (i.e., the C++ compiler would enforce proper type.) Obviously, this meant that correcting filters together producing output of unknown type was problematic. Several other issues with this design remained as well, many of which have been alluded to earlier, but are summarized here to motivate the use of the newer pipeline architecture. \n\n\\begin{figure}[!htb]\n  \\centering\n  \\includegraphics[width=0.8\\textwidth]{Figure4-17}\\\\\n  \\caption{The logical relationship of ports and connections An input port may have more than one connection associated with it. Multiple connections are possible in certain filters such as the append filter, where a single logical input port represents all the data to be ``appended'' together, and each input is represented by a different connection.}\\label{fig:Figure4-17}\n\\end{figure}\n\n\\begin{itemize}\n\\item The older design did not support deferred dataset type checking. It was difficult to support arbitrary reader types or filters that could produce different types of output.\n\n\\item The strategy for updating and managing the execution of the pipeline were implicitly embedded in the process objects and data objects. As the strategy became more complex, or needed to change, this required modifying data and/or process objects.\n\n\\item In the older design it was difficult to abort pipeline execution during an update pass. Further, it was not possible to centralize the error checking; each filter had to do some checking thereby duplicating code.\n\n\\item Introducing metadata into the pipeline required changing the API to the data and process objects. It was desirable to support the ability of a reader to add metadata to a data stream and have a filter in the pipeline retrieve it, without having to modify the API.\n\\end{itemize}\n\nFor this, and other reasons related to parallel processing, the original VTK pipeline design was reworked. While the transition was difficult, such changes are often necessary if a software system is to change and grow with advances in technology.\n\n\\textbf{VTK 5.0 and Beyond}. While VTK 5.0 still supports the use of SetInput()/GetOutput(), its use in Figure \\ref{fig:Figure4-16} and Figure \\ref{fig:Figure4-17} is discouraged. Rather, the newer pipeline architecture should be used. Referring to Figure \\ref{fig:Figure4-17}, we use connections and ports to configure VTK's visualization pipeline:\n\n\\begin{lstlisting}[language=C++, caption={}, numbers=none, frame=none]\nfilter2->SetInput(filter1->GetOutputPort()); // VTK5.0\n\\end{lstlisting}\n\nYou probably have already guessed how this approach can be extended to multiple inputs and multiple outputs. Let's look at some concrete examples. vtkGlyph3D is an example of a filter that accepts multiple inputs and generates a single output. The inputs to vtkGlyph3D are represented by the Input and Source instance variables. The purpose of vtkGlyph3D is to copy the geometry defined by the data in Source to each point defined by Input. The geometry is modified according to the Source data values (e.g., scalars and vectors). (For more information about glyphs see \\nameref{subsec:glyphs} in Chapter 6: \\nameref{chap:fundamental_algorithms}.) To use the vtkGlyph3D object in C++ code you would do the following:\n\n\\begin{lstlisting}[language=C++, caption={}, numbers=none, frame=none]\nglyph = vtkGlyph3D::New();\nglyph->SetInputConnection(foo->GetOutputPort());\nglyph->SetSourceConnection(bar->GetOutputPort());\n...\n\\end{lstlisting}\n\nwhere foo and bar are filters returning the appropriate type of output. The class vtkExtractVectorComponents is an example of a filter with a single input and multiple outputs. This filter extracts the three components of a 3D vector into separate scalar components. Its three outputs are available on output ports 0, 1, and 2. An example use of the filter follows:\n\n\\begin{lstlisting}[language=C++, caption={}, numbers=none, frame=none]\nvz = vtkExtractVectorComponents::New();\nfoo = vtkDataSetMapper::New();\nfoo->SetInputConnection(vz->GetOutputPort(2));\n...\n\\end{lstlisting}\n\nSeveral other special objects having multiple inputs or outputs are also available. Some of the more notable classes are vtkMergeFilter, vtkAppendFilter, and vtkAppendPolyData. These filters com bine multiple pipeline streams and generate a single output. Note, however, that while vtkMergeFilter has multiple input ports (i.e., different logical inputs), vtkAppendFilter has only one logical input, but presumes multiple connections are made to that one input. This is because in the case of vtkMergeFilter, each input has a distinct and separate purpose, while in vtkAppendFilter all the inputs have the same meaning (i.e., just one more input in a list to append together). Here are some code fragments:\n\n\\begin{lstlisting}[language=C++, caption={}, numbers=none, frame=none]\nmerge = vtkMergeFilter::New();\nmerge->SetGeometryConnection(foo->GetOutputPort());\nmerge->SetScalarsConnection(bar->GetOutputPort());\n\\end{lstlisting}\n\nand\n\n\\begin{lstlisting}[language=C++, caption={}, numbers=none, frame=none]\nappend = vtkAppendFilter::New();\nappend->AddInputConnection(foo->GetOutputPort());\nappend->AddInputConnection(bar->GetOutputPort());\n\\end{lstlisting}\n\nNotice the use of the method AddInputConnection(). This method adds to the list of connections, whereas SetInputConnection() clears the list and specifies the single connection to the port.\n\nAnother important filtering class is vtkProbeFilter. This filter takes two inputs. The first input is the data we wish to probe. The second input supplies a set of points that are used as probe points. Some process objects take a list of input data. Another interesting filter is the vtkBooleanStructuredPoints class which performs set operations on volume datasets. The first data item in the list is used to initialize the set operation. Each subsequent item in the list is combined with the result of previous operations using a boolean operation specified by the user.\n\nFor more details regarding the object design of filters and data objects, please see Chapter 5: \\nameref{chap:basic_data_representation} and Chapter 6: \\nameref{chap:fundamental_algorithms}.\n\n\\subsection{Pipeline Execution and Information Objects}\n\\label{subsec:pipeline_execution_and_information_objects}\n\nUntil now, we have used the terms metadata and information objects rather informally. As described previously, in the context of VTK, these terms refer to data that describes datasets. In this section, we show how these objects, which are subclasses of vtkInformation, are used to facilitate the execution of the VTK pipeline.\n\n\\begin{itemize}\n\\item \\textbf{Information Objects}. Information objects are the basic containers used throughout the VTK pipeline to hold a wide variety of metadata. They are heterogeneous key-to-value maps in which the type of the key determines the type of the value. The following is an enumeration of the places information objects are used.\n\n\\item \\emph{Pipeline information} objects hold information for pipeline execution. They are stored in instances of vtkExecutive or subclasses and are accessible via the method vtkExecutive::GetOutputInformation(). There is one pipeline information object per output port. It contains an entry pointing to the output vtkDataObject on the corresponding port (if it has been created). The vtkDataObject contains a pointer back to its corresponding pipeline information object, accessible via vtkDataObject::GetPipelineInformation(). The pipeline information object also holds information about what will populate the data object when the filter executes and generates the output. The actual information contained is determined by the output data type and the execution model in use. Pipeline information objects for input connections are accessible via the method vtkExecutive::GetInputInformation(), and they are the pipeline information objects on the output ports to which the input ports are connected.\n\n\\item \\emph{Port information} objects hold information about the data types produced on output ports and consumed by input ports. They are stored by instances of vtkAlgorithm. There is one input port information object per input port and one output port information object per output port. They are accessible via the methods vtkAlgorithm::GetInputPortInformation() and vtkAlgorithm::GetOutputPortInformation(). Port information objects are usually created and populated by subclasses of vtkAlgorithm in order to specify the interface of the filter.\n\n\\item \\emph{Request information} objects hold information about a specific request being sent to an executive or algorithm. There is one entry indicating what request is being sent and possibly other entries giving additional details about the specific request. These information objects are not accessible via any public method but are passed to ProcessRequest() methods that implement the requests.\n\n\\item \\emph{Data information} objects hold information about what is currently stored in a vtkDataObject. There is one data information object in each data object, accessible via vtkDataObject::GetInformation(). The actual information contained is determined by the data object type.\n\n\\item \\emph{Algorithm information} objects hold information about an instance of vtkAlgorithm. There is one algorithm information object per algorithm object, accessible via vtkAlgorithm::GetInformation(). The actual information contained is determined by the algorithm object type.\n\\end{itemize}\n\nThe importance of the information objects in VTK is that they are flexible (e.g., new key-value pairs can be easily added) and extensible. That is, readers, filters and mappers can add new information to the containers without requiring the API of the pipeline--related classes to change.\n\n\\begin{figure}[!htb]\n  \\centering\n  \\includegraphics[width=0.8\\textwidth]{Figure4-18}\\\\\n  \\caption{Path of a request sent through a pipeline. For example, assume the consumer (at the far right) needs only a single piece of this data (e.g., piece 1 of 4); also assume that the producer (on the far left) is a reader that can partition its data into pieces. The consumer passes this request upstream, and it continues upstream (via executives) until it reaches a producer that can fulfill the request. When the reader algorithm is asked for a piece of the data, it provides it, and passes the new data back (with the information that it is piece 1 of 4) down the pipeline. It stops when it reaches the consumer who made the request.}\\label{fig:Figure4-18}\n\\end{figure}\n\n\\subsubsection{Pipeline Execution Models}\n\\label{subsubsec:pipeline_execution_models}\n\nIn VTK, the fundamental pipeline update mechanism is based on the request. A request is the basic pipeline operation (or ``pipeline pass'') that generally asks for particular piece of information to be propagated through the pipeline. An execution model is a set of requests defined by a specific executive. Refer to Figure \\ref{fig:Figure4-18} in the following description of the execution process.\n\nRequests are generated by the executive object of a filter that has been explicitly asked to update by its algorithm due to some user call. For example, when the Write() method of a writer is called, the algorithm object asks its executive to update the pipeline, and execute the writer, by calling this->GetExecutive()->Update(). Several requests may be sent through the pipeline in order to bring it up to date.\n\nA request is implemented as an information object. There is one key of type vtkInformationRequestKey specifying the request itself. This key is typically defined by the executive's class. Additional information about the request may also be stored in the request information object.\n       \nRequests are propagated through the pipeline by the executives of each filter. The vtkExecutive::ProcessRequest() method is invoked on an executive given the request information object. This method is implemented by each executive and is responsible for fulfilling the request as it sees fit. Many requests may be fulfilled for a filter only after it has been fulfilled for the filters providing its inputs. For these requests the executive will pass the request on to the executives of these upstream filters and then handle the request itself.\n\nAn executive often asks its algorithm object for help in fulfilling a request. It sends the request to the algorithm object by invoking the vtkAlgorithm::ProcessRequest() method. This method is implemented by all algorithms and is responsible for handling the request. Input and output pipeline information objects are provided as arguments to the method. The algorithm must handle the request using only its own filter parameter settings and the pipeline information objects given. An algorithm is not allowed to ask its executive for any additional information. This insures that the algorithms are independent of the executives. Figure \\ref{fig:Figure4-18} shows a typical path taken by a request as it is sent through a pipeline. Typically the request originates in a consumer at the end of the pipeline. It is sent back through the pipeline by the executives. Each executive asks its algorithm to help handle the request.\n\n\\subsection{Flexible Computation / Memory Trade-off}\n\\label{subsec:flexible_computation_memory_trade-off}\n\nBy default, networks constructed using the \\emph{Visualization Toolkit} store intermediate computational results (i.e., favor computation). However, a single class variable can be set to discard intermediate data when they are no longer needed (i.e., favor memory). In addition, a local parameter can be set within each process object to control this trade-off at object level.\n\nThis global variable is set as follows. Given the data object O, (or the output of a filter obtained using O=filter->GetOutput()), invoke O->SetGlobalReleaseDataFlagOn() to enable data release. To enable data release for a particular object use O->SetReleaseDataFlagOn(). Appropriate methods exist to disable memory release as well.\n\n\\subsection{High-Level Object Design}\n\\label{subsec:high-level_object_design}\n\nAt this point in the text it is premature to describe design details of the various objects making up the visualization pipeline. However, there are two important classes that affect many of the objects in the text. These are the classes vtkObject and vtkObjectBase.\n\nvtkObjectBase is the base object for almost all inheritance hierarchies found in VTK. vtkObjectBase implements data object reference counting (see ``Reference Counting and Garbage Collection'' on page \\pageref{subsec:reference_counting_garbage_collection}). Subclasses of vtkObjectBase may be shared by other objects, without duplicating memory. It also defines an API for objects to print information about themselves.\n\nvtkObject is a subclass of vtkObjectBase. It provides methods and instance variables to control run-time debugging and maintains internal object modification time. In particular, the method Modified() is used to update the modification time, and the method GetMTime() is used to retrieve it. vtkObject also provides a framework for the event callbacks that we saw in the previous chapter (see ``Events and Observers''on page \\pageref{sub:events_observers}).\n\nNote that we do not always include vtkObject and vtkObjectBase in object diagrams to conserve space. Refer to the source code for a definitive statement.\n\n\\subsection{Examples}\n\\label{subsec:Ch04Examples}\n\nWe will now demonstrate some of the features of the visualization pipeline with four examples. Some of the objects used here will be unfamiliar to you. Please overlook missing details until we cover the information later in the book. The goal here is to provide a flavor and familiarity with the software architecture and its use.\n\n\\subsubsection{Simple Sphere}\n\\label{subsubsec:simple_sphere}\n\nThe first example demonstrates a simple visualization pipeline. A polygonal representation of a sphere is created with the source object (vtkSphereSource). The sphere is passed through a filter (vtkElevationFilter) that computes the height of each point of the sphere above a plane. The plane is perpendicular to the z-axis, and passes through the point (0,0,-1). The data is finally mapped (vtkDataSetMapper) through a lookup table. The mapping process converts height value into colors, and interfaces the sphere geometry to the rendering library. The mapper is assigned to an actor, and then the actor is displayed. The visualization network, a portion of code, and output image are shown in Figure \\ref{fig:Figure4-19}.\n\nThe execution of the pipeline occurs implicitly when we render the actor. Each actor asks its mapper to update itself. The mapper in turn asks its input to update itself. This process continues until a source object is encountered. Then the source will execute if modified since the last render.\n\n\\begin{figure}[htb]\n  \\begin{subfigure}[h]{0.48\\linewidth}\n    \\includegraphics[width=0.96\\linewidth]{Figure4-19a}\n    \\caption*{}\n    \\label{fig:Figure4-19a}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[h]{0.48\\linewidth}\n    \\includegraphics[width=0.96\\linewidth]{Figure4-19b}\n    \\caption*{See: href{https://lorensen.github.io/VTKExamples/site/Cxx/Rendering/ColoredSphere/}{ColoredSphere.cxx} and \\href{https://lorensen.github.io/VTKExamples/site/Python/Rendering/ColoredSphere/}{ColoredSphere.py}.})\n    \\label{fig:Figure4-19b}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[h]{0.96\\linewidth}{Figure4-19c}\n  \\begin{lstlisting}[language=C++,  caption={}, numbers=none, frame=none]\n    vtkSphereSource *sphere = vtkSphereSource::New();\n      sphere->SetPhiResolution(12); sphere->SetThetaResolution(12);\n    \n    vtkElevationFilter *colorIt = vtkElevationFilter::New();\n      colorIt->SetInputConnection(sphere->GetOutputPort());\n      colorIt->SetLowPoint(0,0,-1);\n      colorIt->SetHighPoint(0,0,1);\n    \n    vtkDataSetMapper *mapper = vtkDataSetMapper::New();\n      mapper->SetInputConnection(colorIt->GetOutputPort());\n      \n    vtkActor *actor = vtkActor::New();\n      actor->SetMapper(mapper);\n    \\end{lstlisting} \n    \\caption*{}\n  \\end{subfigure}\n  \\caption{A simple sphere example.}\\label{fig:Figure4-19}\n\\end{figure}\n\nThen the system walks through the network and executes each object if its input or instance variables are out of date. When completed, the actor's mapper is up to date and an image is generated.\n\nNow let's reexamine the same process of pipeline execution by following method invocation. The process begins when the actor receives a Render() message from a renderer. The actor in turn sends a Render() message to its mapper. The mapper begins network execution by asking its input to update itself via the Update() operation. This causes a cascade of Update() methods as each filter in turn asks its input to update itself. If branching in the pipeline is present, the update method will branch as well. Finally, the cascade terminates when a source object is encountered. If the source object is out of date, it will send itself an RequestData() command. Each filter will send itself an RequestData() as necessary to bring itself up to date. Finally, the mapper will perform operations to transform its input into rendering primitives.\n\nIn the \\emph{Visualization Toolkit}, the Update() method is public while the RequestData() method is protected. Thus, you can manually cause network execution to occur by invoking the Update() operation. This can be useful when you want to set instance variables in the network based on the results of upstream execution, but do not want the whole network to update. The RequestData() method is protected because it requires a certain object state to exist. The Update() method insures that this state exists.\n\nOne final note. The indentation of the code serves to indicate where objects are instantiated and modified. The first line (i.e., the New() operator) is where the object is created. The indented lines that follow indicate that various operations are being performed on the object. We encourage you to use a similar indenting scheme in your own work.\n\n\\subsubsection{Warped Sphere}\n\\label{subsubsec:warped_sphere}\n\nThis example extends the pipeline of the previous example and shows the effects of type checking on the connectivity of process objects. We add a transform filter (vtkTransformFilter) to nonuniformly scale the sphere in the x-y-z directions.\n\nThe transform filter only operates on objects with explicit point coordinate representation (i.e., a subclass of vtkPointSet). However, the elevation filter generates the more general form vtkDataSet as output. Hence we cannot connect the transform filter to the elevation filter. But we can connect the transform filter to the sphere source, and then the elevation filter to the transform filter. The result is shown in Figure \\ref{fig:Figure4-20}. (Note: an alternative method is to use vtkCastToConcrete to perform run-time casting.)\n\nThe C++ compiler enforces the proper connections of sources, filters, and mappers. To decide which objects are compatible, we check the type specification of the SetInput() method. If the input object returns an output object or a subclass of that type, the two objects are compatible and may be connected.\n\n\\begin{figure}[htb]\n  \\begin{subfigure}[h]{0.48\\linewidth}\n    \\includegraphics[width=0.96\\linewidth]{Figure4-20a}\n    \\caption*{}\n    \\label{fig:Figure4-20a}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[h]{0.48\\linewidth}\n    \\includegraphics[width=0.96\\linewidth]{Figure4-20b}\n    \\caption*{(\\href{https://lorensen.github.io/VTKExamples/site/Cxx/Rendering/TransformSphere/}{TransformSphere.cxx} or \\href{https://lorensen.github.io/VTKExamples/site/Python/Rendering/TransformSphere/}{TransformSphere.py}).}\n    \\label{fig:Figure4-20b}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[h]{0.96\\linewidth}\n    \\caption*{}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[h]{0.96\\linewidth}\n    \\begin{lstlisting}[language=C++, caption={Warped Sphere.}]\n    vtkSphereSource *sphere = vtkSphereSource::New();\n      sphere->SetThetaResolution(12);\n      sphere->SetPhiResolution(12);\n\n    vtkTransform *aTransform = vtkTransform::New();\n      aTransform->Scale(1,1.5,2);\n\n    vtkTransformFilter *transFilter = vtkTransformFilter::New();\n      transFilter->SetInputConnection(sphere->GetOutputPort());\n      transFilter->SetTransform(aTransform);\n\n    vtkElevationFilter *colorIt = vtkElevationFilter::New();\n      colorIt->SetInputConnection(transFilter->GetOutputPort());\n      colorIt->SetLowPoint(0,0,-1);\n      colorIt->SetHighPoint(0,0,1);\n\n    vtkLookupTable *lut = vtkLookupTable::New();\n      lut->SetHueRange(0.667,0.0); lut->SetSaturationRange(1,1);\n      lut->SetValueRange(1,1);\n\n    vtkDataSetMapper *mapper = vtkDataSetMapper::New();\n      mapper->SetLookupTable(lut);\n      mapper->SetInputConnection(colorIt->GetOutputPort());\n\n    vtkActor *actor = vtkActor::New();\n      actor->SetMapper(mapper);\n    \\end{lstlisting}\n    \\caption*{}\n    \\label{fig:Figure4-20c}\n  \\end{subfigure}\n  \\caption{The addition of a transform filter to the previous example.}\\label{fig:Figure4-20}\n\\end{figure}\n\n\\subsubsection{Generating Oriented Glyphs}\n\\label{subsubsec:generating_oriented_glyphs}\n\nThis example demonstrates the use of an object with multiple inputs. vtkGlyph3D places 3D icons or glyphs (i.e., any polygonal geometry) at every input point. The icon geometry is specified with the instance variable Source, and the input points are obtained from the Input instance variable. Each glyph may be oriented and scaled in a variety of ways, depending upon the input and instance variables. In our example we place cones oriented in the direction of the point normals (Figure \\ref{fig:Figure4-21}).\n\nThe visualization network branches at vtkGlyph3D. If either branch is modified, then this filter will reexecute. Network updates must branch in both directions, and both branches must be up to date when vtkGlyph3D executes. These requirements are enforced by the Update() method, and pose no problem to the implicit execution method.\n\n\\begin{figure}[htb]\n  \\begin{subfigure}[h]{0.64\\linewidth}\n    \\includegraphics[width=0.96\\linewidth]{Figure4-21a}\n    \\caption*{}\n    \\label{fig:Figure4-21a}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[h]{0.32\\linewidth}\n    \\includegraphics[width=0.96\\linewidth]{Figure4-21b}\n    \\caption*{See: \\href{https://lorensen.github.io/VTKExamples/site/Cxx/Rendering/Mace/}{Mace.cxx} and \\href{https://lorensen.github.io/VTKExamples/site/Python/Rendering/Mace/}{Mace.py}.}\n    \\label{fig:Figure4-21b}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[h]{0.96\\linewidth}{Figure4-22c}\n    \\begin{lstlisting}[language=C++, caption={Warped Sphere.}]\n    vtkSphereSource *sphere = vtkSphereSource::New();\n      sphere->SetThetaResolution(8); sphere->SetPhiResolution(8);\n    \n    vtkPolyDataMapper *sphereMapper = vtkPolyDataMapper::New();\n      sphereMapper->SetInputConnection(sphere->GetOutputPort());\n    \n    vtkActor *sphereActor = vtkActor::New();\n      sphereActor->SetMapper(sphereMapper);\n    \n    vtkConeSource *cone = vtkConeSource::New();\n      cone->SetResolution(6);\n    \n    vtkGlyph3D *glyph = vtkGlyph3D::New();\n      glyph->SetInputConnection(sphere->GetOutputPort());\n      glyph->SetSourceConnection(cone->GetOutputPort());\n      glyph->SetVectorModeToUseNormal();\n      glyph->SetScaleModeToScaleByVector();\n      glyph->SetScaleFactor(0.25);\n    \n    vtkPolyDataMapper *spikeMapper = vtkPolyDataMapper::New();\n      spikeMapper->SetInputConnection(glyph->GetOutputPort());\n    \n    vtkActor *spikeActor = vtkActor::New();\n      spikeActor->SetMapper(spikeMapper);\n    \\end{lstlisting}\n    \\caption*{}\n  \\end{subfigure}\n  \\caption{An example of multiple inputs and outputs.}\\label{fig:Figure4-21}\n\\end{figure}\n\n\\textbf{Disappearing Sphere}. In our last example we construct a visualization network with a feedback loop, and show how we can use procedural programming to change the topology of the network. The network consists of four objects: vtkSphereSource to create an initial polygonal geometry, vtkShrinkFilter to shrink the polygons and create a gap or space between neighbors, vtkElevationFilter to color the geometry according to height above the x-y plane, and vtkDataSetMapper to map the data through a lookup table and interface to the rendering library. The network topology, a portion of the C++ code, and output are shown in Figure \\ref{fig:Figure4-22}.\n\nAfter vtkSphereSource generates an initial geometry (in response to a render request), the input of vtkShrinkFilter is changed to the output of the vtkElevationFilter. Because of the feedback loop, vtkShrinkFilter will always reexecute. Thus, the behavior of the network is to reexecute each time a render is performed. Because the shrink filter is reapplied to the same data, the polygons become smaller and smaller and eventually disappear.\n\n\\begin{figure}[htb]\n  \\begin{subfigure}[h]{0.48\\linewidth}\n    \\includegraphics[width=0.96\\linewidth]{Figure4-22a}\n    \\caption*{}\n    \\label{fig:Figure4-22a}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[h]{0.48\\linewidth}\n    \\includegraphics[width=0.96\\linewidth]{Figure4-22b}\n    \\caption*{See: \\href{https://lorensen.github.io/VTKExamples/site/Cxx/Visualization/LoopShrink/}{LoopShrink.cxx} and \\href{https://lorensen.github.io/VTKExamples/site/Python/Visualization/LoopShrink/}{LoopShrink.py}.}\n    \\label{fig:Figure4-22b}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[h]{0.96\\linewidth}{Figure4-22c}\n    \\begin{lstlisting}[language=C++, caption={Warped Sphere.}]\n    vtkSphereSource *sphere = vtkSphereSource::New();\n      sphere->SetThetaResolution(12); sphere->SetPhiResolution(12);\n    \n    vtkShrinkFilter *shrink = vtkShrinkFilter::New();\n      shrink->SetInputConnection(sphere->GetOutputPort());\n      shrink->SetShrinkFactor(0.9);\n    \n    vtkElevationFilter *colorIt = vtkElevationFilter::New();\n      colorIt->SetInputConnection(shrink->GetOutputPort());\n      colorIt->SetLowPoint(0,0,-.5);\n      colorIt->SetHighPoint(0,0,.5);\n    \n    vtkDataSetMapper *mapper = vtkDataSetMapper::New();\n      mapper->SetInputConnection(colorIt->GetOutputPort());\n    \n    vtkActor *actor = vtkActor::New();\n      actor->SetMapper(mapper);\n    \n      renWin->Render(); // execute first time\n      // create loop\n      shrink->SetInputConnection(colorIt->GetOutputPort());\n      renWin->Render(); // begin looping\n    \\end{lstlisting}\n    \\caption*{}\n  \\end{subfigure}\n  \\caption{A network with a loop (LoopShrk.cxx). VTK 5.0 does not allow you to execute a looping visualization network; this was possible in previous versions of VTK.}\\label{fig:Figure4-22}\n\\end{figure}\n\n\\section{Chapter Summary}\n\\label{Ch04ChapterSummary}\n\nThe visualization process is naturally modelled using a combination of functional and object models. The functional model can be simplified and used to describe visualization networks. The object model specifies the components of the visualization network. Visualization networks consist of process objects and data objects. Data objects represent information; process objects transform the data from one form to another. There are three types of process objects --- sources have no input and at least one output; filters have at least one input and output; sinks, or mappers, terminate the visualization network. The execution of the network can be controlled implicitly or explicitly. Implicit control means that each object must insure its input is up to date, thereby distributing the control mechanism. Explicit control means that there is a centralized executive to coordinate the execution of each object. Many techniques are available to program visualization networks. Direct visual programming is most common in commercial systems. At a higher level, applications provide tailored but more rigid interfaces to visualize information. At the lowest level, subroutine or object libraries provide the greatest flexibility. The \\emph{Visualization Toolkit} contains an object library implemented in C++ for constructing visualization networks.\n\n\\section{Bibliographic Notes}\n\\label{Ch04BibNotes}\n\nThe practical way to learn about the visualization process is to study commercially available systems. These systems can be categorized as either direct visual programming environments or as applications. Common visual programming systems include AVS \\cite{AVS89}, Iris Explorer \\cite{IrisExplorer}, IBM Data Explorer \\cite{DataExplorer}, apE \\cite{apE90}, and Khoros \\cite{Rasure91}. Application systems generally provide less flexibility than visual programming systems, but are better tailored to a particular problem domain. PLOT3D \\cite{PLOT3D} is an early example of a tool for CFD visualization. This has since been superseded by FAST \\cite{FAST90}. FieldView is another popular CFD visualizer \\cite{FieldView91}. VISUAL3 \\cite{VISUAL3} is a general tool for unstructured or structured grid visualization. PV-WAVE \\cite{Charal90} can be considered a hybrid system, since it has both simple visual programming techniques to interface to data files as well as a more structured user-interface than the visual programming environments. Wavefront's DataVisualizer \\cite{DataVisualizer} is a general-purpose visualization tool. It is unique in that it is part of a powerful rendering and animation package. A nice system for visualizing 3D gridded data (such as that produced by numerical weather models) is VIS5D. Find out more at the \\href{http://www.ssec.wisc.edu/\\~billh/vis5d.html}{VIS5D Web site}).\n\nAlthough many visualization systems claim to be object-oriented, this is often more in appearance than implementation. Little has been written on object-oriented design issues for visualization. \\cite{VISAGE92} presents an architecture similar to that described in this chapter. Favre \\cite{Favre94} describes a more conventional object-oriented approach. His dataset classes are based on topological dimension and both data and methods are combined into classes.\n\n\\printbibliography\n\n\\section{Exercises}\n\\begin{enumerate}\n\n\\item Consider the following 2D visualization techniques: $x-y$ plotting, bar charts, and pie charts.\n\nFor each technique:\n\n\\begin{enumerate}\n\n    \\item Construct functional models.\n\n    \\item Construct object models.\n\n\\end{enumerate}\n\n    \\item \\label{ex:ch04_4.2} A \\emph{height field} is a regular array of 2D points where $h = f(x,y)$, $h$ is an altitude above the point $(x,y)$. Height fields are often used to represent terrain data. Design an object-oriented system to visualize height fields.\n\n\\begin{enumerate}\n\n    \\item How would you represent the height field?\n\n    \\item What methods would you use to access this data?\n\n    \\item Develop one process object (i.e., visualization technique) to visualize a height field. Describe the methods used by the object to access and manipulate the height field.\n\n\\end{enumerate}\n\n\\item Describe how you would implement an explicit control mechanism for network execution.\n\n\\begin{enumerate}\n\n    \\item How do process objects register their input data with the executive?\n\n    \\item How is the executive notified of object modification?\n\n    \\item By what method is the executive notified that network execution is necessary?\n\n    \\item Describe an approach for network dependency analysis. How does the executive invoke execution of the process objects?\n\n\\end{enumerate}\n\n\\item Visual programming environments enable the user to construct visualization applications by graphically connecting process objects.\n\n\\begin{enumerate}\n\n    \\item Design a graphical notation to represent process objects, their input and output, and data flow direction.\n\n    \\item How would you modify instance variables of process objects (using a graphical technique)?\n\n    \\item By what mechanism would network execution be initiated?\n\n    \\item How would you control conditional execution and looping in your network?\n\n    \\item How would you take advantage of parallel computing?\n\n    \\item How would you distribute network execution across two or more computers sharing a network connection?\n\n\\end{enumerate}\n\n\\item Place oriented cylinders (instead of cones) on the mace in Figure \\ref{fig:Figure4-20}. (\\emph{Hint}: use vtkCylinderSource.)\n\n\\item The implicit update method for the visualization network used by VTK is simple to implement and understand. However, it is prone to a common programming error. What is this error?\n\n\\item Experiment with the transformation object in Figure \\ref{fig:Figure4-20}.\n\n\\begin{enumerate}\n\n    \\item Translate the actor with vtkTransform's Translate() method.\n\n    \\item Rotate the actor with the RotateX(), RotateY(), and RotateZ() methods.\n\n    \\item Scale the actor with the Scale() method.\n\n    \\item Try combinations of these methods. Does the actor transform in ways that you expect?\n\n\\end{enumerate}\n\n\\item Visualize the following functions. (\\emph{Hint}: use vtkSampleFunction and refer to Figure \\ref{fig:Figure4-1}.)\n\n\\begin{enumerate}\n\n    \\item $F(x,y,z)=x^2$\n\n    \\item $F(x,y,z) = x_2 + 2 y + 3 z +1$\n\n    \\item $F(x,y,z) = x+2 + y^2 - \\cos (z) + 1$\n\n\\end{enumerate}\n\n\\end{enumerate}\n\n", "meta": {"hexsha": "86d4f053179724919607cec70ab03af5e6086cfe", "size": 110402, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/VTKBookLaTex/Chapter04.tex", "max_stars_repo_name": "FlorianFritz/VTKExamples", "max_stars_repo_head_hexsha": "02ab2bd354275eddc15633374eb9a00eb13f0888", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/VTKBookLaTex/Chapter04.tex", "max_issues_repo_name": "FlorianFritz/VTKExamples", "max_issues_repo_head_hexsha": "02ab2bd354275eddc15633374eb9a00eb13f0888", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/VTKBookLaTex/Chapter04.tex", "max_forks_repo_name": "FlorianFritz/VTKExamples", "max_forks_repo_head_hexsha": "02ab2bd354275eddc15633374eb9a00eb13f0888", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 111.404641776, "max_line_length": 1438, "alphanum_fraction": 0.8000942012, "num_tokens": 23304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.3365449865486904}}
{"text": "\\documentclass{beamer}\n\\usepackage[francais]{babel}\n\\usepackage[T1]{fontenc}\n\\usepackage[utf8]{inputenc}\n\\usepackage{amsrefs}\n\\usepackage{graphicx}\n\n\\mode<presenation>\n{ \\usetheme{boxes} }\n\n%\\AtBeginSection[]{\n%  \\begin{frame}<beamer>\n%  \\frametitle{R\\'esum\\'e}\n%  \\tableofcontents[currentsection]\n%  \\end{frame}\n%}\n\n\\title{Knot thickness computation in parallel}\n\\author{Mathias Carlen}\n\\date{11 june 2009}\n\n\\begin{document}\n\n\\frame{\\titlepage}\n\\frame{\\frametitle{Content}\\tableofcontents}\n\n%skeleton\n%\\section{Test}\n%\\frame{\n%  \\frametitle{1. titre}\n%  \\begin{itemize}\n%  \\item<2-> Bla 1\n%  \\item<3-> Bla bla 2\n%  \\end{itemize}\n%}\n\n\\section{Curves and thickness}\n\n\\begin{frame}\n\\frametitle{Curves and thickness}\n\n\\begin{itemize}\n \\item<1-> closed curve $\\gamma(s)$, with $s$ arclength param.\n \\item<2-> knot class\n \\item<3-> maximal thick tube $\\longrightarrow$ thickness $\\Delta$.\n\\end{itemize}\n\\vspace{1cm}\n\\pause\n\\pause\n\\pause\n\\includegraphics[height=2cm]{global.pdf}\\hspace{.2cm}\n\\pause\n\\includegraphics[height=2cm]{local.pdf}\n\\pause\n\\[\n\\Delta = min ( min_s r(s) , min_{dc} \\frac{\\gamma(s)-\\gamma(t)}{2} )\n\\]\n\\end{frame}\n\n\\section{Motivation}\n\\begin{frame}\n\\frametitle{Motivation}\n\\begin{itemize}\n\\item<1-> Why parallelize?\n\\item<2-> Minimize $L[\\gamma]/\\Delta[\\gamma]$\n\\item<3-> Monte carlo\n\\item<4-> Animation\n\\end{itemize}\n\\end{frame}\n\n\\section{Thickness Algorithm}\n\n\\begin{frame}\n\\frametitle{Thickness Algorithm}\n\\begin{itemize}\n\\item[(1)]<1-> Discretize $\\gamma$ with biarcs\n\\item[(2)]<2-> Compute smallest local radius $r_i$\n\\item[(3)]<3-> Prepare a set of candidate arc pairs $(a_i,b_i)$\n\\item[(4)]<4-> Compute minimal distance between arcs\n\\item[(5)]<5-> Double criticality test\n\\item[(6)]<6-> Distance test\n\\item[(7)]<7-> Bisect remaining arc pairs ($1$ pair -> $4$ pairs)\n\\item[(8)]<8-> If not below some tolerance goto 4\n\\item[(9)]<9-> Return thickness\n\\end{itemize}\n\\end{frame}\n\n\\section{Parallelization}\n%\\subsection{Master/Slave work}\n%\\subsection{MPI}\n%\\subsection{Implementation details}\n%\\subsubsection{Custom datatypes}\n%\\subsubsection{Batching}\n\n\\begin{frame}\n\\frametitle{Parallelization (1)}\n\\includegraphics[height=.8\\textheight]{parallel_algo_flowchart.pdf}\n\\end{frame}\n\n\\begin{frame}\n\\frametitle{Parallelization (2)}\n\\begin{itemize}\n\\item<1-> MPI\n\\item<2-> custom datatype \\texttt{struct Candidate}\n\\item<3-> batching candidates\n\\end{itemize}\n\\end{frame}\n\n\\section{Experiments and benchmarks}\n%\\subsection{Hardware/Software used}\n%\\subsection{CPUs}\n%\\subsection{Knot data points}\n%\\subsection{Batching}\n%\\subsection{Knot shapes}\n%\\subsection{Master/slaves timing}\n\n\\begin{frame}\n\\frametitle{Experiments and benchmarks (1)}\nComputed on cluster \\texttt{lcvmlc2} using \\texttt{mpich-mx}. \\\\\n\\vspace{.5cm}\n\\pause\nTime vs. number of CPUs \\\\\n\\includegraphics[width=.75\\textwidth]{time_vs_cpus.pdf}\n\\end{frame}\n\n\\begin{frame}\n\\frametitle{Experiments and benchmarks (2)}\nTime vs. discretization \\\\\n\\includegraphics[width=.75\\textwidth]{time_vs_nodes.pdf}\n\\end{frame}\n\n\\begin{frame}\n\\frametitle{Experiments and benchmarks (3)}\nTime vs. batching \\\\\n\\includegraphics[width=.75\\textwidth]{time_vs_batch.pdf}\n\\end{frame}\n\n\\begin{frame}\n\\frametitle{Experiments and benchmarks (4)}\nTime vs. knot type \\\\\n\\includegraphics[width=.75\\textwidth]{time_vs_knots.pdf}\n\\end{frame}\n\n\\begin{frame}\n\\frametitle{Experiments and benchmarks (5)}\nMaster/Slave timing \\\\[1cm]\n\\begin{tabular}{lclll}\nknot & data points & master (sec) & slaves (sec) & total (sec) \\\\\nj3.1 & 512 & 0.165336 & 2.092650 & 2.258000 \\\\\nk3.1 & 160 & 0.016368 & 0.016206 & 0.032578 \\\\\nk4.1 & 208 & 0.024819 & 0.018046 & 0.042868 \\\\\nk5.1 & 232 & 0.031302 & 0.000165 & 0.031471 \\\\\nk6.1 & 280 & 0.042829 & 0.000162 & 0.042995 \\\\\n\\end{tabular}\n\\end{frame}\n\n\\section{Possible improvements}\n%\\subsection{Master idle or not}\n%\\subsection{Master computes, interrupt system?}\n%\\subsection{Best value broadcast}\n%\\subsection{Optimize master initialization step}\n\n\\begin{frame}\n\\frametitle{Possible improvements}\n\\begin{itemize}\n\\item<1-> Master idle/working\n\\item<2-> Master computing (interrupt system)\n\\item<3-> Broadcast best current value\n\\item<4-> Optimize master init step\n\\end{itemize}\n\\end{frame}\n\n\\end{document}\n", "meta": {"hexsha": "b9bfa03ddf2672e425ef49229d3f9288196ca1ee", "size": 4183, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "experimental/mpi/presentation/slides/presentation.tex", "max_stars_repo_name": "mcarlen/libbiarc", "max_stars_repo_head_hexsha": "d016a1be643ddcded53411b4f242ac6004b65173", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "experimental/mpi/presentation/slides/presentation.tex", "max_issues_repo_name": "mcarlen/libbiarc", "max_issues_repo_head_hexsha": "d016a1be643ddcded53411b4f242ac6004b65173", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-08-23T09:36:29.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-26T09:56:38.000Z", "max_forks_repo_path": "experimental/mpi/presentation/slides/presentation.tex", "max_forks_repo_name": "mcarlen/libbiarc", "max_forks_repo_head_hexsha": "d016a1be643ddcded53411b4f242ac6004b65173", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-08-11T21:12:02.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-11T21:12:02.000Z", "avg_line_length": 24.0402298851, "max_line_length": 68, "alphanum_fraction": 0.7236433182, "num_tokens": 1377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.33654497948364787}}
{"text": "\\section{Gaussian Distributions}\n\nThe behaviour of all quantitative traits of the dataset is assumed to adhere to a\nGaussian Distribution.\nThis assumption is taken due to how the values of the data set are presented.\nAs shown in Figures\n% \\ref{fig: sepal length normal distribution},\n% \\ref{fig: sepal width normal distribution},\n\\ref{fig: petal length normal distribution} and\n\\ref{fig: petal width normal distribution}\nthe distribution for each flower variety follows the\ngeneral behaviour of the Gaussian Distribution.\n\nHaving confirmed that all quantitative features of the dataset\nadhere to Gaussian Distributions, it is possible to proceed with the\ndevelopment of the classifiers.\n\n% \\begin{figure}[htb!]\n%  \\includegraphics[width=\\textwidth]{normSepalLength}\n%  \\caption{Sepal Length}\n%  \\label{fig: sepal length normal distribution}\n% \\end{figure}\n%\n% \\begin{figure}[htb!]\n%  \\includegraphics[width=\\textwidth]{normSepalWidth}\n%  \\caption{Sepal Width}\n%  \\label{fig: sepal width normal distribution}\n% \\end{figure}\n\n\\begin{figure}[htb!]\n \\includegraphics[width=\\textwidth]{normPetalLength}\n \\caption{Petal Length}\n \\label{fig: petal length normal distribution}\n\\end{figure}\n\n\\begin{figure}[htb!]\n \\includegraphics[width=\\textwidth]{normPetalWidth}\n \\caption{Petal Width}\n \\label{fig: petal width normal distribution}\n\\end{figure}\n\n\n\n\\pagebreak\n\\newpage\n", "meta": {"hexsha": "e8badd87dbcc08d905ca706c9dac3832ad08426e", "size": 1361, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/gaussianBehaviour.tex", "max_stars_repo_name": "der-coder/CINVESTAV-Mathematics-II-2020", "max_stars_repo_head_hexsha": "ccd3364818c673f7a6bf13d495004034d2c6ecc0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tex/gaussianBehaviour.tex", "max_issues_repo_name": "der-coder/CINVESTAV-Mathematics-II-2020", "max_issues_repo_head_hexsha": "ccd3364818c673f7a6bf13d495004034d2c6ecc0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/gaussianBehaviour.tex", "max_forks_repo_name": "der-coder/CINVESTAV-Mathematics-II-2020", "max_forks_repo_head_hexsha": "ccd3364818c673f7a6bf13d495004034d2c6ecc0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5869565217, "max_line_length": 81, "alphanum_fraction": 0.7759000735, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.33654497948364775}}
{"text": "\\documentclass{article}\n\n\\usepackage{amsmath,amssymb,amsthm}\n\\usepackage{url}\n\\usepackage{comment}\n\\usepackage{proof}\n\\usepackage{stmaryrd}\n\\usepackage{parskip}\n\\usepackage{fullpage}\n\n\\newcommand{\\choice}[0]{\\zeta}\n\\newcommand{\\elcap}[0]{\\cap}\n\\newcommand{\\abs}[4]{{#1}\\, #2\\! : \\! #3.\\, #4}\n\\newcommand{\\absu}[3]{{#1}\\, #2.\\, #3}\n\\mathchardef\\mhyph=\"2D % Define a \"math hyphen\"\n\\newcommand{\\interp}[1]{\\llbracket #1 \\rrbracket} \n\\newcommand{\\tpcheck}[0]{\\Leftarrow}\n\\newcommand{\\tpsynth}[0]{\\Rightarrow}\n\\newcommand{\\cbe}[0]{c\\beta\\eta}\n\\newcommand{\\utp}[0]{\\mathcal{U}}\n\\newcommand{\\startcase}[1]{\\vspace{#1} \\noindent\\textbf{\\underline{Case:}}}\n\n\\newtheorem{theorem}{Theorem}\n\\newtheorem{definition}[theorem]{Definition}\n\\newtheorem{lemma}[theorem]{Lemma}\n\\newtheorem{observation}[theorem]{Observation}\n\n\\begin{document}\n\n\\title{Syntax and Semantics of Cedille}\n\n\\author{Aaron Stump \\\\\n  Computer Science \\\\\n  The University of Iowa \\\\\n\\texttt{aaron-stump@uiowa.edu}}\n\n\\date{}\n\n\\maketitle\n\n\\section{Introduction}\n\nThe type theory of Cedille is called the Calculus of Dependent Lambda\nEliminations (CDLE).  This document presents the version of CDLE as of\nJune 1, 2018.  We have made many changes from the first paper on CDLE~\\cite{stump17},\nmostly in the form of dropping constructs we discovered (to our\nsurprise) could be derived~\\cite{stump18}. I have also omitted\n\\emph{lifting} -- a technique for large eliminations with lambda\nencodings -- in this document's version of CDLE.  Some uses of lifting\ncan be simulated other ways within the system, though the limits of\nthis are still under investigation.  We also include a construct\n$\\delta$, for deriving a contradiction from a proof that\nlambda-encoded true equals lambda-encoded false.  This also\ncompensates somewhat for the lack of lifting.\n\nAt a high level, CDLE is an extrinsic (i.e., Curry-style) type theory\nextending the Calculus of Constructions with three additional\nconstructs, which allow deriving induction principles within the\ntheory, for inductive datatypes.  The goal is to support usual\nidioms of dependently typed programming and proving as in Agda or\nsimilar tools, but using pure lambda encodings for all data, and\nrequiring a much smaller core theory.\n\nThe current Cedille implementation of CDLE extends the system\ndescribed below with a number of features intended to make programming\nin the system more convenient and with less redundancy.  These\nfeatures all compile away to a slightly simplified version of the\ntheory presented in this document, called Cedille Core, described\nhere: \\url{https://github.com/astump/cedille-core-spec}.\n\n\\section{Classification Rules}\n\nThe classification rules are given in\nFigures~\\ref{fig:superknd},~\\ref{fig:knd}, and~\\ref{fig:tp}.  For\nbrevity, we take these figures as implicitly specifying the syntax of\nkinds $\\kappa$, types $T$, and annotated terms $t$; these may use term\nvariables $x$ and type variables $X$, which we assume come from\ndistinct sets.  So terms and types are syntactically distinguished.\nThe typing rules (Figure~\\ref{fig:tp}) are\nbidirectional~\\cite{pierce+00}, while the kinding and superkinding\nrules (Figure~\\ref{fig:knd} and~\\ref{fig:superknd}) are only\nsynthesizing.  We write $\\Leftrightarrow$ to range over\n$\\{\\tpcheck,\\tpsynth\\}$. We follow the syntax of our implementation\nCedille, which distinguishes application of a term or type $e$ to a\ntype ($e \\cdot T$), from application to a term ($e\\ t$), and\napplication to an erased term argument ($e\\ \\mhyph t$).  The rules are\nintended, with a few points of nondeterminism, to be read bottom-up\n(in a standard way; cf.~\\cite{peytonjones07}) as an algorithm for\ncomputing a classifier from a context and an expression ($\\tpsynth$)\nor checking an expression against a classifier in context\n($\\tpcheck$).\n\nThe classification rules refer to an erasure function, defined in\nFigure~\\ref{fig:eraser}.  The type theory is \\emph{extrinsic} (aka,\nCurry-style), and hence we only consider erasures $|t|$ of terms when\ntesting for $\\beta\\eta$-equivalence.  This is done by the conversion\nrelation $T\\cong T'$, whose central rules are given in\nFigure~\\ref{fig:conv}.  That figure omits the various congruence rules\nneeded to equate bigger expressions by equating subexpressions.  The\nmain ideas of conversion shown in the figure are to use\n$\\beta$-equivalence at the type level, and $\\beta\\eta$-equivalence of\nerased terms at the term level.\n\n\n\\begin{figure}\n  \\[\n  \\begin{array}{llll}\n    \\infer{\\Gamma \\vdash \\star}{\\ } &\n    \\infer{\\Gamma\\vdash\\abs{\\Pi}{x}{T}{\\kappa}}{\\Gamma \\vdash T \\tpsynth \\star & \\Gamma,x:T\\vdash\\kappa} &\n    \\infer{\\Gamma\\vdash\\abs{\\Pi}{X}{\\kappa'}{\\kappa}}{\\Gamma \\vdash \\kappa' & \\Gamma,X:\\kappa'\\vdash\\kappa}\n  \\end{array}\n  \\]\n  \\caption{Rules for checking that a kind is well-formed ($\\Gamma \\vdash \\kappa$)}\n  \\label{fig:superknd}\n\\end{figure}\n\n\\begin{figure}\n  \\[\n  \\begin{array}{ll}\n    \\infer{\\Gamma \\vdash X \\tpsynth \\kappa}{(X : \\kappa) \\in \\Gamma} &\n    \\infer{\\Gamma\\vdash \\abs{\\forall}{X}{\\kappa}{T} \\tpsynth \\star}{\\Gamma \\vdash \\kappa & \\Gamma,X:\\kappa\\vdash T \\tpsynth \\star} \\\\ \\\\\n    \\infer{\\Gamma\\vdash\\abs{\\forall}{x}{T}{T'} \\tpsynth \\star}{\\Gamma \\vdash T \\tpsynth \\star & \\Gamma,x:T\\vdash T' \\tpsynth \\star} &\n    \\infer{\\Gamma\\vdash\\abs{\\Pi}{x}{T}{T'} \\tpsynth \\star}{\\Gamma \\vdash T \\tpsynth \\star & \\Gamma,x:T\\vdash T' \\tpsynth \\star} \\\\ \\\\\n    \\infer{\\Gamma\\vdash\\abs{\\lambda}{x}{T}{T'} \\tpsynth \\abs{\\Pi}{x}{T}{\\kappa}}{\\Gamma \\vdash T \\tpsynth \\star & \\Gamma,x:T\\vdash T'\\tpsynth\\kappa} &\n    \\infer{\\Gamma\\vdash\\abs{\\lambda}{X}{\\kappa}{T'} \\tpsynth \\abs{\\Pi}{X}{\\kappa}{\\kappa'}}{\\Gamma \\vdash \\kappa & \\Gamma,X:\\kappa\\vdash T'\\tpsynth\\kappa'} \\\\ \\\\\n    \\infer{\\Gamma\\vdash T\\ t \\tpsynth [t/x]\\kappa}{\\Gamma\\vdash T \\tpsynth \\abs{\\Pi}{x}{T'}{\\kappa} & \\Gamma\\vdash t \\tpcheck T'} &\n    \\infer{\\Gamma\\vdash T\\cdot T' \\tpsynth [T'/X]\\kappa}{\\Gamma\\vdash T \\tpsynth \\abs{\\Pi}{X}{\\kappa'}{\\kappa} & \\Gamma\\vdash T' \\tpsynth \\kappa' & \\kappa \\cong \\kappa'} \\\\ \\\\\n    \\infer{\\Gamma\\vdash\\abs{\\iota}{x}{T}{T'} \\tpsynth \\star}{\\Gamma \\vdash T \\tpsynth \\star & \\Gamma,x:T\\vdash T' \\tpsynth \\star} &\n    \\infer{\\Gamma\\vdash \\{ t \\simeq t' \\} : \\star}{\\textit{FV}(t\\ t')\\subseteq\\textit{dom}(\\Gamma)}\n  \\end{array}\n  \\]\n  \\caption{Rules for synthesizing a kind for a type ($\\Gamma \\vdash T \\tpsynth \\kappa$)}\n  \\label{fig:knd}\n\\end{figure}\n\n\n\\begin{figure}\n  \\[\n  \\begin{array}{ll}\n    \\infer{\\Gamma\\vdash x\\tpsynth T}{(x : t)\\in\\Gamma} &\n    \\infer{\\Gamma\\vdash t\\tpcheck T'}{\\Gamma\\vdash t \\tpcheck T & T' \\leadsto^*_\\beta T} \\\\ \\\\    \n    \\infer{\\Gamma\\vdash t\\tpsynth T'}{\\Gamma\\vdash t \\tpsynth T & T \\leadsto^*_\\beta T'} &\n    \\infer{\\Gamma\\vdash t\\tpcheck T}{\\Gamma\\vdash t\\tpsynth T' & T' \\cong T} \\\\ \\\\    \n    \\infer{\\Gamma\\vdash \\absu{\\lambda}{x}{t} \\tpcheck \\abs{\\Pi}{x}{T}{T'}}{\\Gamma,x:T\\vdash t\\tpcheck T'} &\n    \\infer{\\Gamma\\vdash t\\ t' \\tpsynth [t'/x]T}{\\Gamma\\vdash t \\tpsynth \\abs{\\Pi}{x}{T'}{T} & \\Gamma\\vdash t' \\tpcheck T'} \\\\ \\\\\n\n    \\infer{\\Gamma\\vdash \\absu{\\Lambda}{X}{t} \\tpcheck \\abs{\\forall}{X}{\\kappa}{T}}{\\Gamma,X:\\kappa\\vdash t \\tpcheck T} &\n    \\infer{\\Gamma\\vdash t \\cdot T' \\tpsynth [T'/X]T}\n          {\\Gamma\\vdash t \\tpsynth \\abs{\\forall}{X}{\\kappa}{T} & \\Gamma\\vdash T' \\tpcheck\\kappa} \\\\ \\\\\n\n    \\infer{\\Gamma\\vdash \\absu{\\Lambda}{x}{t} \\tpcheck \\abs{\\forall}{x}{T'}{T}}{\\Gamma,x:T'\\vdash t \\tpcheck T & x\\not\\in\\textit{FV}(|t|)} &\n    \\infer{\\Gamma\\vdash t\\ \\mhyph t' \\tpsynth [t'/x]T}{\\Gamma\\vdash t \\tpsynth \\abs{\\forall}{x}{T'}{T} & \\Gamma\\vdash t' \\tpcheck T'} \\\\ \\\\\n\n    \\infer{\\Gamma\\vdash [ t , t' ] \\tpcheck \\abs{\\iota}{x}{T}{T'}}\n          {\\Gamma\\vdash t \\tpcheck T & \\Gamma\\vdash t' \\tpcheck [t/x]T' & |t| =_{\\beta\\eta} |t'|} &\n    \\infer{\\Gamma\\vdash t.1 \\tpsynth T}{\\Gamma\\vdash t \\tpsynth \\abs{\\iota}{x}{T}{T'}} \\\\ \\\\\n    \\infer{\\Gamma\\vdash t.2 \\tpsynth [t.1/x]T'}{\\Gamma\\vdash t \\tpsynth \\abs{\\iota}{x}{T}{T'}} &\n\n    \\infer{\\Gamma\\vdash \\beta\\{t'\\} \\tpcheck \\{ t \\simeq t \\}}{\\Gamma\\vdash \\textit{FV}(t)\\subseteq \\textit{dom}(\\Gamma)}  \\\\ \\\\    \n    \\infer{\\Gamma\\vdash \\delta\\ t \\tpcheck T}{\\Gamma\\vdash t\\tpcheck \\{ \\absu{\\lambda}{x}{\\absu{\\lambda}{y}{x}} \\simeq \\absu{\\lambda}{x}{\\absu{\\lambda}{y}{y}}\\}}  &\n    \\infer{\\Gamma\\vdash \\rho\\ t'\\ \\mhyph\\ t \\Leftrightarrow [t_2/x]T}\n          {\\Gamma\\vdash t' \\tpsynth t_1 \\simeq t_2 & \\Gamma \\vdash t \\Leftrightarrow [t_1/x]T} \\\\ \\\\\n    \\infer{\\Gamma\\vdash \\chi\\ T\\ \\mhyph\\ t \\tpcheck T'}\n          {\\Gamma\\vdash T\\tpcheck \\star & \\Gamma\\vdash t \\tpcheck T & T \\cong T'} &\n    \\infer{\\Gamma\\vdash \\chi\\ T\\ \\mhyph\\ t \\tpsynth T}\n          {\\Gamma\\vdash T\\tpcheck \\star & \\Gamma\\vdash t \\tpsynth T' & T \\cong T'} \\\\ \\\\\n    \\infer{\\Gamma\\vdash \\phi\\ t\\ \\mhyph\\ t'\\{t''\\} \\Leftrightarrow T}\n          {\\Gamma\\vdash t\\tpsynth \\{t'\\simeq t''\\} & \\Gamma\\vdash t' \\Leftrightarrow T}  & \\\n  \\end{array}\n  \\]\n\\caption{Rules for checking a term against a well-kinded type ($\\Gamma \\vdash t \\tpcheck T$)\n           and synthesizing a type for a term ($\\Gamma \\vdash t \\tpsynth T$)}\n\\label{fig:tp}\n\\end{figure}\n\n\n\\begin{figure}\n  \\[\n  \\begin{array}{lllllll}\n    |x| & = & x &\\ &\n    |\\abs{\\lambda}{x}{t'}{t}| & = & \\absu{\\lambda}{x}{|t|} \\\\\n    |t\\ t'| & = & |t|\\ |t'| &\\ &\n    |t\\cdot T| & = & |t| \\\\\n    |\\absu{\\Lambda}{x}{t'}{t}| & = & |t| &\\ &\n    |t\\ \\mhyph t'| & = & |t| \\\\\n    |[t , t']| & = & |t| &\\ &\n    |t.1| & = & |t| \\\\\n    |t.2| & = & |t| &\\ &\n    |\\beta\\{t\\}| & = & |t|\\\\\n    |\\delta\\ t| & = & |t|&\\ &\n    |\\rho\\ t\\ \\mhyph\\ t'| & = & |t'| \\\\\n    |\\phi\\ t\\ \\mhyph\\ t'\\ \\{t''\\}| & = & |t''| &\\ &\n    |\\chi\\ T\\ \\mhyph\\ t'| & = & |t'|\n  \\end{array}\n  \\]\n  \\caption{Erasure for annotated terms}\n  \\label{fig:eraser}\n\\end{figure}  \n\n\\begin{figure}\n  \\[\n  \\begin{array}{ll}\n    \\infer{T \\cong T'}{T \\leadsto^*_\\beta T_1 & T' \\leadsto^*_\\beta T_2 & T_1\\cong^t T_2}  & \n    \\infer{T \\cong T'}{T \\cong^t T'} \\\\ \\\\\n    \\infer{T\\ t \\cong^t T\\ t'}{T \\cong^t T' & |t| =_{\\beta\\eta} |t'|} &\n    \\infer{\\{ t_1 \\simeq t_2 \\} \\cong^t \\{ t_1'\\ \\simeq t_2' \\}}{|t_1| =_{\\beta\\eta} |t_1'| & |t_2| =_{\\beta\\eta} |t_2'|}\n  \\end{array}\n  \\]\n  \\caption{Non-congruence rules for conversion}\n  \\label{fig:conv}\n\\end{figure}  \n\n\\subsection{Overview of the constructs}\n\\label{sec:overview}\n\nCDLE has as a subsystem the extrinsic Calculus of\nConstructions (CC).  We have dependent types\n$\\abs{\\Pi}{x}{T}{T'}$ and kinds $\\abs{\\Pi}{x}{T}{\\kappa}$, as well as\nterm- and type-level quantification over (possibly higher-kinded)\ntypes $\\abs{\\forall}{X}{\\kappa}{T}$ and\n$\\abs{\\Pi}{X}{\\kappa}{\\kappa'}$.  We use $\\forall$ when the\ncorresponding argument will be erased, and $\\Pi$ when it will be\nretained.  Since we do not erase term or type arguments from\ntype-level applications, we thus write $\\abs{\\Pi}{X}{\\kappa}{\\kappa'}$\ninstead of $\\abs{\\forall}{X}{\\kappa}{\\kappa'}$.  We write $\\lambda$ to\ncorrespond to $\\Pi$ and $\\Lambda$ to correspond to $\\forall$.  As noted\nabove, application to a type is denoted with center dot ($\\cdot$).\n\nTo Curry-style CC, CDLE adds: implicit products, introduced orginially\nby Miquel~\\cite{miquel01}; a primitive equality type $\\{ t \\simeq\nt'\\}$; and dependent intersection types $\\abs{\\iota}{x}{T}{T'}$,\nintroduced by Kopylov~\\cite{kopylov03}.  Implicit products are used\nfor erased arguments to functions, found also in systems like Agda\n(cf.~\\cite{mishraLinger08}).  Dependent intersections are a rather\nexotic construct allowing us to assign type $\\abs{\\iota}{x}{T'}{T}$ to\nerased term $t$ when we can assign $T'$ to $t$, and also assign\n$[t/x]T$ to $t$.  For an annotated introduction form, we write\n$[t,t'$], where $t$ checks against type $T'$, $t'$ checks against\n$[t/x]T$, and $t$ and $t'$ have identical (i.e., $\\alpha$-equivalent)\nerasures.  Dependent intersections thus enable a controlled form of\nself-reference in the type.  Previous work showed how to use this to\nderive induction for Church-encoded natural numbers~\\cite{stump18}.\nWe will see below further uses of this construct.\n\nThe typing rules include conversion checks in a few places; e.g., as\nstandardly, when switching from checking to synthesizing mode.  Two\nrules near the top of Figure~\\ref{fig:tp} state that one may (nondeterministically)\n$\\beta$-reduce the type one is synthesizing or checking, before proceeding.\nThis allows reduction to head-normal form,\nto match the form of type required by other rules.\nFinally, we include the construct $\\chi\\ T\\ \\mhyph\\ t$ to change the\nsynthesized or checked type $T'$ to $T$, if $T \\cong T'$.  This may\nbe necessary to get the type into a specific form for purposes of rewriting\nwith the $\\rho$ construct.\n\nFinally, we have modified\nthe rules for equality types $\\{ t \\simeq t' \\}$ so that we require\nnothing of $t$ and $t'$ except that the set $\\textit{dom}(\\Gamma)$ of variables\ndeclared by $\\Gamma$ includes their free variables $\\textit{FV}(t\\ t')$.  Further modifications\nover the version of CDLE in~\\cite{stump18} are:\n\\begin{itemize}\n\\item To prove $\\{ t \\simeq t\\}$, one now writes $\\beta\\{t'\\}$,\n  with the critical idea that $|\\beta\\{t\\}|$ erases to $|t|$.  We call this the \\textbf{Kleene trick},\n  because it goes back to Kleene's numeric realizability, which accepts any number $n$ as a realizer\n  of a true equation.  Here, we accept any closed term $t$ as a realizer\n  of $\\{ t \\simeq t\\}$.  This means that in Cedille, any such term -- even otherwise untypable\n  terms, non-normalizing terms, etc. -- have type $\\{ t \\simeq t\\}$ for any term $t$.\n\\item The $\\rho$ construct allows one to rewrite occurrences of $t_1$ to $t_2$ in the synthesized or\n  checked type, where $t_1$ and $t_2$ are provably equal.  In the Cedille implementation, we rewrite\n  all matching occurrences.  This may be compared to \\verb|rewrite| in Agda, except that it may be\n  applied anywhere, not just as part of pattern matching~\\cite{agda}.\n\\item We adopt a strong form of Nuprl's \\textbf{direct computation rules}~\\cite{constable+86}:\n  If we have a term $t'$ of type $T$ and a proof $t$ that $\\{ t' \\simeq t''\\}$, then we may conclude that\n  $t''$ has type $T$ by writing the annotated term $\\phi\\ t\\ \\mhyph\\ t'\\{t''\\}$, which\n  erases to $t''$.\n\\item Where the previous version of CDLE uses $\\beta$-equivalence for (erased) terms, we here adopt $\\beta\\eta$-equivalence.  This\n  allows us to observe in many cases that retyping functions are actually $\\beta\\eta$-equivalent to $\\absu{\\lambda}{x}{x}$.\n  While $\\beta\\eta$-equivalence takes more work to incorporate into intrinsic \n  type theory~\\cite{geuvers92},\n  it raises no difficulties for our extrinsic one.\n\\item In this version, we add an explicit axiom $\\delta$ saying that Church-encoded boolean \\emph{true} is different from\n  \\emph{false}.  In the first version of CDLE, such an axiom was derivable from \\emph{lifting}, a construct allowing\n  simply typable terms to be lifted to the type level~\\cite{stump17}.  We omit lifting in this new version of CDLE, because while\n  sound, lifting as defined in that previous work is complicated and appears to be incomplete.  Developing a new\n  form of lifting remains to future work.\n\\end{itemize}\n\nThe equality type remains \\textbf{intensional}: we equate terms iff they are $\\beta\\eta$-equal.  \n\n\\subsection{Semantics and metatheory}\n\nFigure~\\ref{fig:semtp} gives a realizability semantics for types and\nkinds, following the semantics given in the previous papers on\nCDLE~\\cite{stump18,stump17}.  Details of this semantics are presented\nfurther in Section~\\ref{sec:snd} below.  Using the semantics and the\ndefinition in Figure~\\ref{fig:semctxt} of $\\interp{\\Gamma}$, we can\nprove the following theorem:\n\\begin{theorem}[Soundness]\n\\label{thm:snd}\nSuppose $(\\sigma,\\rho)\\in\\interp{\\Gamma}$.  Then we have:\n\\begin{enumerate}\n\\item If $\\Gamma\\vdash \\kappa$, then $\\interp{\\kappa}_{\\sigma,\\rho}$ is defined.\n\\item If $\\Gamma\\vdash T \\tpsynth \\kappa$, then $\\interp{T}_{\\sigma,\\rho}\\in\\interp{\\kappa}_{\\sigma,\\rho}$.\n\\item If $\\Gamma\\vdash t \\tpsynth T$ then $[\\sigma |t|]_{\\cbe}\\in\\interp{T}_{\\sigma,\\rho}\\in \\mathcal{R}$.\n\\item If $\\Gamma\\vdash t \\tpcheck T$ and $\\interp{T}_{\\sigma,\\rho}\\in \\mathcal{R}$, then\n    $[\\sigma |t|]_{\\cbe}\\in\\interp{T}_{\\sigma,\\rho}\\in \\mathcal{R}$.\n\\item If $T \\cong T'$ or $T \\cong^t T'$ and $\\interp{T}_{\\sigma,\\rho}$ and $\\interp{T'}_{\\sigma,\\rho}$ are both defined, then they are equal.\n\\end{enumerate}\n\\end{theorem}\n\nAn easy corollary, by the semantics of $\\forall$-types, is then:\n\n\\begin{theorem}[Logical consistency]\n\\label{thm:consis}\n  There is no term $t$ such that $\\vdash t : \\abs{\\forall}{X}{\\star}{X}$.\n\\end{theorem}\n\nIt may worry some readers that we have:\n\\begin{observation}\n  There are typable terms $t$ which fail to normalize.\n\\end{observation}\n\nDefining \\verb|Top| to be $\\{\\absu{\\lambda}{x}{x} \\simeq\n\\absu{\\lambda}{x}{x}\\}$, we may assign \\verb|Top| to any closed term \\verb|t|,\nincluding non-normalizing ones.  In our annotated syntax, we write \\verb|β{t}|.\nEven without this, the presence of\n$\\delta$ in combination with $\\phi$ allows us to type non-normalizing\nterms assuming an erased argument $x$ of type $\\{ \\textit{tt} \\simeq\n\\textit{ff} \\}$ for Church-encoded booleans \\textit{tt} and\n\\textit{ff}.  For example, $\\delta\\ x$ has type\n\\verb|{λ x . x ≃ λ x . x x}|, and with $\\phi$ we can use this to type\n$\\Omega$ by changing the typed term \\verb|id · True id|, where\n\\verb|True| is \\verb|∀ X : ★ . X ➔ X|. But failure of normalization\ndoes not impinge on Theorem~\\ref{thm:consis}.   Extensional Martin-L\\\"of type theory (MLTT) is\nalso non-normalizing, for a very similar reason, but fact\ndoes not contradict its logical soundness~\\cite{dybjer16}.  In CDLE, the guarantees one gets about the\nbehavior of terms are expressed almost entirely in their types.  If\nthe types are weak, then not much is guaranteed; but stronger types\ncan guarantee properties like normalization.\n\nGiven the lack of normalization, several checks in the typing rules --\nfor things like $t =_{\\beta\\eta} t'$ -- are formally undecidable.  In\npractice, we simply impose a bound on the number of steps of reduction,\nand thus restore formal decidability (we are checking ``typable within\na given budget'').  In practice, the same is done for Coq and Agda,\nwhere type checking is decidable but, in general, infeasible (since one\nmay write astronomically slow terminating functions).\n\nFinally, in line with ideas recently advocated by Dreyer, we\ndo not concern ourselves with syntactic\ntype preservation~\\cite{dreyer18}, noting instead that by construction,\nsemantic types $\\interp{T}_{\\sigma,\\rho}$ are preserved by $\\beta\\eta$-reduction:\n\n  \\begin{theorem}[Semantic type preservation]\n    If $t \\leadsto_{\\beta\\eta} t'$ and $t\\in\\interp{T}_{\\sigma,\\rho}$, then $t'\\in\\interp{T}_{\\sigma,\\rho}$.\n    \\end{theorem}\n\n  Confluence of $\\beta\\eta$-reduction for (erased)\n  terms is nothing other than confluence of untyped lambda calculus.\n  This is because, as easily verified by inspecting\n  Figure~\\ref{fig:eraser}, the erasure function maps annotated terms\n  $t$ to terms $|t|$ of pure untyped lambda calculus.\n\\begin{comment}\n  \\begin{lemma}\n    If $t$ is an annotated term of CDLE, then $|t|$ is a term of pure untyped lambda calculus.\n    \\end{lemma}\n\\end{comment}    \n\n\\begin{figure}\n\\[\n\\begin{array}{lll}\n\\interp{X}_{\\sigma,\\rho} & = & \\rho(X) \\\\ \n\\interp{\\Pi x : T_1. T_2}_{\\sigma,\\rho} & = & \n    [\\{ \\lambda x.t\\ |\\ \\forall E\\in\\interp{T_1}_{\\sigma,\\rho}.\\\\\n\\ &\\ &\\ \\ \\ \\  [[\\choice(E)/x]t]_{\\cbe}\\in\\interp{T_2}_{\\sigma[x\\mapsto \\choice(E)],\\rho} \\ \\wedge\\ t = |t|\\}]_{\\cbe}\n \\\\\n\\interp{\\forall X:\\kappa.T}_{\\sigma,\\rho} & = & \n  \\elcap \\{ \\interp{T}_{\\sigma,\\rho[X\\mapsto S]} |\\ S\\in\\interp{\\kappa}_{\\sigma,\\rho} \\}  \\\\ \n\\interp{\\forall x:T.T'}_{\\sigma,\\rho} & = & \n  \\elcap_\\star \\{ \\interp{T'}_{\\sigma[x\\mapsto \\choice(E)],\\rho}\\ |\\ E\\in\\interp{T}_{\\sigma,\\rho} \\} \\\\ \n\\interp{\\iota x:T.T'}_{\\sigma,\\rho} & = & \\{ E\\in\\interp{T}_{\\sigma,\\rho} |\\ E \\in \\interp{T'}_{\\sigma[x\\mapsto \\choice(E)],\\rho} \\} \\\\ \n\\interp{\\lambda X:\\kappa.T}_{\\sigma,\\rho} & = & (S\\in\\interp{\\kappa}_{\\sigma,\\rho} \\mapsto \\interp{T}_{\\sigma,\\rho[X\\mapsto S]}) \n\\\\ \n\\interp{\\lambda x:T.T'}_{\\sigma,\\rho} & = & \n    (E\\in\\interp{T}_{\\sigma,\\rho} \\mapsto \\interp{T'}_{\\sigma[x\\mapsto \\choice(E)],\\rho}) \n\\\\ \n\\interp{T\\ T'}_{\\sigma,\\rho} & = & \\interp{T}_{\\sigma,\\rho}(\\interp{T'}_{\\sigma,\\rho})\n\\\\ \n\\interp{T\\ t}_{\\sigma,\\rho} & = & \\interp{T}_{\\sigma,\\rho}([\\sigma |t|]_{\\cbe})\n\\\\\n\\interp{t \\simeq t'}_{\\sigma,\\rho} & = & [\\{ t''\\ |\\ \\sigma |t| =_{\\beta\\eta} \\sigma |t'|\\ \\wedge\\ t'' = |t''| \\}]_{\\cbe} \\\\\n\\ &\\ &\\ \\ \\ \\textnormal{ if }\\textit{FV}(t\\ t')\\subseteq\\textit{dom}(\\sigma) \n\\\\\n\\interp{\\star}_{\\sigma,\\rho} & = & \\mathcal{R} \\\\ \n\\interp{\\Pi x:T.\\kappa}_{\\sigma,\\rho} & = & \n(E\\in\\interp{T}_{\\sigma,\\rho} \\to \\interp{\\kappa}_{\\sigma[x\\mapsto \\choice(E)],\\rho}),\\\\\n\\ &\\ &\\ \\ \\ \\textnormal{ if }\\interp{T}_{\\sigma,\\rho}\\in\\mathcal{R} \\\\\n\\interp{\\Pi x:\\kappa.\\kappa'}_{\\sigma,\\rho} & = & (S\\in\\interp{\\kappa}_{\\sigma,\\rho} \\to \\interp{\\kappa}_{\\sigma,\\rho[X\\mapsto S]}) \\\\\n\\elcap_\\star X & = & \\left\\{\\begin{array}{l}\n                                         \\, \\negthinspace\\elcap X, \\textnormal{ if } X\\neq\\emptyset\\\\\n                                         \\, \\negthinspace[\\mathcal{L}]_{\\cbe},\\textnormal{ otherwise}\n                                       \\end{array}\\right. \\\\\n\\end{array}\n\\]\n\\caption{Semantics for types and kinds}\n\\label{fig:semtp}\n\\end{figure}\n\n\\begin{figure}\n\\[\n\\begin{array}{lll}\n(\\sigma\\uplus[x\\mapsto t],\\rho)\\in\\interp{\\Gamma,x:T} & \\Leftrightarrow & (\\sigma,\\rho)\\in\\interp{\\Gamma} \\ \\wedge\\ \n [t]_{\\cbe}\\in\\interp{T}_{\\sigma,\\rho}\\in\\mathcal{R}\\ \\wedge\\ t = |t| \\\\\n(\\sigma,\\rho\\uplus[X\\mapsto S])\\in\\interp{\\Gamma,X:\\kappa} & \\Leftrightarrow & (\\sigma,\\rho)\\in\\interp{\\Gamma} \\ \\wedge\\ \nS\\in\\interp{\\kappa}_{\\sigma,\\rho} \\\\\n(\\emptyset,\\emptyset)\\in\\interp{\\cdot}\n\\end{array}\n\\]\n\\caption{Semantics of typing contexts $\\Gamma$}\n\\label{fig:semctxt}\n\\end{figure}\n\n\\subsection{Some details about the semantics and the proof of Theorem~\\ref{thm:snd}}\n\\label{sec:snd}\n\nFollowing the development in~\\cite{stump17}, we work with\nset-theoretic partial functions for the semantics of higher-kinded\ntypes.  Types are interpreted as $\\beta\\eta$-closed sets of closed\nterms. Let $\\mathcal{L}$ be the set of closed terms of pure lambda calculus\n(differently from~\\cite{stump17}, we include all terms at this point,\neven non-normalizing ones).  We\nwrite $=_{\\cbe}$ for standard $\\beta\\eta$-equivalence of pure lambda calculus, restricted to\nclosed terms; and $[t]_{\\cbe}$ for $\\{ t'\\ |\\ t =_{\\cbe} t'\\}$.  This\nis extended to sets $S$ of terms by writing $[S]_{\\cbe}$ for\n$\\{[t]_{\\cbe}\\ |\\ t\\in S\\}$.  In a few places we write\n$\\textit{nf}(t)$ for the (unique) $\\beta\\eta$-normal form of term $t$,\nif it has one.  If (in our meta-language) we affirm a statement\ninvolving application of a partial function, then it is to be\nunderstood that that application is defined.\n\n\\begin{definition}[Reducibility candidates]\n  $\\mathcal{R} := \\{ [S]_{\\cbe}\\ |\\ S\\subseteq \\mathcal{L} \\}$.\n\\end{definition}\n\nThroughout the development we find it convenient to use a\n\\textbf{choice function} $\\choice$.  Given any nonempty set $E$ of\nterms, $\\choice$ returns some element of $E$.  Note that if $a \\in A\n\\in \\mathcal{R}$, then $a$ is a nonempty set of terms of pure lambda\ncalculus; it can also happen that $A \\in\\mathcal{R}$ is empty.  The\nproof of Theorem~\\ref{thm:snd} (see appendix) is then a straightforward adaptation of~\\cite{stump17}. \n\n\\textbf{Acknowledgments.}  This work was partially supported by the US\nNSF support under award 1524519, and US DoD support under award\nFA9550-16-1-0082 (MURI program).\n\n\n\n\\begin{thebibliography}{10}\n\n\\bibitem{constable+86}\nRobert~L. Constable, Stuart~F. Allen, Mark Bromley, Rance Cleaveland, J.~F.\n  Cremer, R.~W. Harper, Douglas~J. Howe, Todd~B. Knoblock, N.~P. Mendler,\n  Prakash Panangaden, James~T. Sasaki, and Scott~F. Smith.\n\\newblock {\\em Implementing mathematics with the Nuprl proof development\n  system}.\n\\newblock Prentice Hall, 1986.\n\n\\bibitem{dreyer18}\nDerek Dreyer.\n\\newblock {The Type Soundness Theorem That You Really Want to Prove (and Now\n  You Can)}.\n\\newblock Milner Award Lecture, delivered at Principles of Programming\n  Languages (POPL), 2018.\n\n\\bibitem{dybjer16}\nPeter Dybjer and Erik Palmgren.\n\\newblock {Intuitionistic Type Theory}.\n\\newblock In Edward~N. Zalta, editor, {\\em The Stanford Encyclopedia of\n  Philosophy}. Metaphysics Research Lab, Stanford University, winter 2016\n  edition, 2016.\n\n\\bibitem{geuvers92}\nHerman Geuvers.\n\\newblock {The Church-Rosser Property for beta-eta-reduction in Typed\n  lambda-Calculi}.\n\\newblock In {\\em Proceedings of the Seventh Annual Symposium on Logic in\n  Computer Science {(LICS} '92), Santa Cruz, California, USA, June 22-25,\n  1992}, pages 453--460. {IEEE} Computer Society, 1992.\n\n\\bibitem{kopylov03}\nAlexei Kopylov.\n\\newblock Dependent intersection: {A} new way of defining records in type\n  theory.\n\\newblock In {\\em 18th {IEEE} Symposium on Logic in Computer Science {(LICS)}},\n  pages 86--95, 2003.\n\n\\bibitem{agda}\n\\mbox{The Agda development team}.\n\\newblock {\\em Agda}, 2018.\n\\newblock Version 2.5.4.\n\n\\bibitem{miquel01}\nAlexandre Miquel.\n\\newblock {The Implicit Calculus of Constructions Extending Pure Type Systems\n  with an Intersection Type Binder and Subtyping}.\n\\newblock In Samson Abramsky, editor, {\\em {Typed Lambda Calculi and\n  Applications}}, volume 2044 of {\\em Lecture Notes in Computer Science}, pages\n  344--359. Springer, 2001.\n\n\\bibitem{mishraLinger08}\nNathan Mishra{-}Linger and Tim Sheard.\n\\newblock {Erasure and Polymorphism in Pure Type Systems}.\n\\newblock In Roberto~M. Amadio, editor, {\\em Foundations of Software Science\n  and Computational Structures, 11th International Conference, {FOSSACS} 2008,\n  Held as Part of the Joint European Conferences on Theory and Practice of\n  Software, {ETAPS} 2008, Budapest, Hungary, March 29 - April 6, 2008.\n  Proceedings}, volume 4962 of {\\em Lecture Notes in Computer Science}, pages\n  350--364. Springer, 2008.\n\n\\bibitem{peytonjones07}\nSimon Peyton~Jones, Dimitrios Vytiniotis, Stephanie Weirich, and Mark Shields.\n\\newblock {Practical Type Inference for Arbitrary-rank Types}.\n\\newblock {\\em J. Funct. Program.}, 17(1):1--82, January 2007.\n\n\\bibitem{pierce+00}\nBenjamin~C. Pierce and David~N. Turner.\n\\newblock Local type inference.\n\\newblock {\\em {ACM} Trans. Program. Lang. Syst.}, 22(1):1--44, 2000.\n\n\\bibitem{stump17}\nAaron Stump.\n\\newblock {The Calculus of Dependent Lambda Eliminations}.\n\\newblock {\\em J. Funct. Program.}, 27:e14, 2017.\n\n\\bibitem{stump18}\nAaron Stump.\n\\newblock {From Realizability to Induction via Dependent Intersection}, 2018.\n\\newblock in press.\n\n\\end{thebibliography}\n\n\n%% Appendix\n\\appendix\n\n\\section{Proof of Theorem~\\ref{thm:snd}}\n\nFirst a few lemmas (easy proofs omitted):\n\n\\begin{lemma}\n  $\\interp{\\kappa}_{\\sigma,\\rho}$ is nonempty if defined.\n\\end{lemma}\n\n\\begin{lemma}\n\\label{lem:choice}\nIf $E$ is nonempty, then $[\\choice(E)]_{\\cbe} = E$\n\\end{lemma}\n\n\\begin{lemma}\n  The set $\\mathcal{R}$ ordered by subset forms a complete lattice,\n  with greatest element $[\\mathcal{L}]_{\\cbe}$ and greatest lower bound\n  of a nonempty set of elements given by\n  intersection.  Also, $\\emptyset$ is the least element.\n\\end{lemma}\n\n\\begin{lemma}[Term substitution and interpretation]\n\\label{lem:termsubstinterp}\nIf $t' =_{\\cbe} \\sigma |t|$, then: \n\\begin{itemize}\n\\item $\\interp{T}_{\\sigma[x\\mapsto t'],\\rho} = \\interp{[t/x]T}_{\\sigma,\\rho}$\n\\item $\\interp{\\kappa}_{\\sigma[x\\mapsto t'],\\rho} = \\interp{[t/x]\\kappa}_{\\sigma,\\rho}$\n\\end{itemize}\n\\end{lemma}\n\n\\begin{lemma}[Type substitution and interpretation] \n\\label{lem:tpsubstinterp}\n\\begin{itemize}\n\\item $\\interp{T}_{\\sigma,\\rho[X\\mapsto\\interp{T'}_{\\sigma,\\rho}]} = \\interp{[T'/X]T}_{\\sigma,\\rho}$\n\\item $\\interp{\\kappa}_{\\sigma,\\rho[X\\mapsto\\interp{T'}_{\\sigma,\\rho}]} = \\interp{[T'/X]\\kappa}_{\\sigma,\\rho}$\n\\end{itemize}\n\\end{lemma}\n\n\\begin{lemma}\n  \\label{lem:interppres}\n  If $T \\leadsto^*_{\\beta} T'$ and $\\interp{T}_{\\sigma,\\rho}$ is defined, then $\\interp{T'}_{\\sigma,\\rho}$ is also defined and equals $\\interp{T}_{\\sigma,\\rho}$.\n\\end{lemma}\n\\begin{proof}\n  This follows by induction on the reduction derivation, making use of the previous substitution lemmas.\n  \\end{proof}\n\n\\begin{proof}[Soundness (Theorem~\\ref{thm:snd})]\n  The following proof is adapted from~\\cite{stump17}.  It proceeds by\n  mutual induction on the assumed typing, kinding, or superkinding\n  derivation, for each part of the lemma.  We prove the parts\n  successively.  \n\n\\subsection{Proof of part (1)}\n\n\\startcase{.2cm}\n\\[\n\\infer{\\Gamma \\vdash \\star }{\\ }\n\\]\n$\\interp{\\star}_{\\sigma,\\rho}$ is just $\\mathcal{R}$, which is\ndefined.  \n\n\\startcase{.2cm}\n\\[\n    \\infer{\\Gamma\\vdash\\abs{\\Pi}{x}{T}{\\kappa}}{\\Gamma \\vdash T \\tpsynth \\star & \\Gamma,x:T\\vdash\\kappa} \n\\]\nBy the IH, $\\interp{T}_{\\sigma,\\rho}\\in\\mathcal{R}$, and so\n$\\interp{\\Pi x : T.\\, \\kappa}_{\\sigma,\\rho}$ is\n$(E\\in\\interp{T}_{\\sigma,\\rho} \\to \\interp{\\kappa}_{\\sigma[x\\mapsto  \\choice(E)],\\rho})$.\nThe latter quantity is defined if for all\n$E\\in\\interp{T}_{\\sigma,\\rho}$, $\\interp{\\kappa}_{\\sigma[x\\mapsto \\choice(E)],\\rho})$ is, too.  Since\n$\\interp{T}_{\\sigma,\\rho}\\in\\mathcal{R}$, every element $E$ of\n$\\interp{T}_{\\sigma,\\rho}$ is nonempty, as noted above, \nso $\\choice(E)$ is defined.  We may apply the IH to the second\npremise, since\n$(\\sigma[x\\mapsto\\choice(E)],\\rho)\\in\\interp{\\Gamma,x:T}$, because $E\\in\\interp{T}_{\\sigma,\\rho}$ (by assumption)\nand $[\\choice(E)]_{\\cbe} = E$.  This gives definedness of the semantics\nof the $\\Pi$-kind.\n\n\\startcase{.2cm}\n\\[\n   \\infer{\\Gamma\\vdash\\abs{\\Pi}{X}{\\kappa'}{\\kappa}}{\\Gamma \\vdash \\kappa' & \\Gamma,X:\\kappa'\\vdash\\kappa}\n\\]\nWe must show $(S\\in\\interp{\\kappa}_{\\sigma,\\rho} \\to \\interp{\\kappa}_{\\sigma,\\rho[X\\mapsto S]})$ is defined.\nThis is true if $\\interp{\\kappa}_{\\sigma,\\rho}$ is defined, which is the case by\nthe IH applied to the first premise; and if for all\n$S\\in\\interp{\\kappa}_{\\sigma,\\rho}$,\n$\\interp{\\kappa}_{\\sigma,\\rho[X\\mapsto S]}$ is defined.  The latter is\ntrue by the IH applied to the second premise.  \n\n\\subsection{Proof of part (2)}\n\n\\startcase{.2cm}\n\\[\n\\infer{\\Gamma \\vdash X \\tpsynth \\kappa}{(X : \\kappa) \\in \\Gamma} \n\\]\nFrom the definition of $\\interp{\\Gamma}$, we obtain\n$\\rho(x)\\in\\interp{\\kappa}_{\\sigma,\\rho}$.\n\n\\startcase{.2cm}\n\\[\n   \\infer{\\Gamma\\vdash\\abs{\\Pi}{x}{T}{T'} \\tpsynth \\star}{\\Gamma \\vdash T \\tpsynth \\star & \\Gamma,x:T\\vdash T' \\tpsynth \\star} \n\\]\nWe must show $\\interp{\\Pi x:T.T'}_{\\sigma,\\rho}\\in\\mathcal{R}$. The\nsemantics defines $\\interp{\\Pi x:T.T'}_{\\sigma,\\rho}$ to be\n$[A]_{\\cbe}$ for a certain $A$, where if $A$ is defined, then\n$A\\subseteq\\mathcal{L}$.  So it suffices to shown definedness. By the IH\nfor the first premise, $\\interp{T}_{\\sigma,\\rho}\\in\\mathcal{R}$.  This\nmeans that if $E\\in\\interp{T}_{\\sigma,\\rho}$, $\\choice(E)$ is defined.\nWe can then apply the IH to the second premise, since\n$\\sigma[x\\mapsto\\choice(E)]\\in\\interp{\\Gamma,x:T}$, to obtain\ndefinedness of $\\interp{T'}_{\\sigma[x\\mapsto\\choice(E),\\rho}$.\n\n\n\\startcase{.2cm}\n\\[\n   \\infer{\\Gamma\\vdash\\abs{\\forall}{x}{T}{T'} \\tpsynth \\star}{\\Gamma \\vdash T \\tpsynth \\star & \\Gamma,x:T\\vdash T' \\tpsynth \\star} \n\\]\nBy the IH for the second premise, $\\interp{T_2}_{\\sigma[x\\mapsto  \\choice(E)],\\rho}\\in\\mathcal{R}$, for every\n$E\\in\\interp{T_1}_{\\sigma,\\rho}$ where\n$\\interp{T_1}_{\\sigma,\\rho}\\in\\mathcal{R}$.  By the IH for the first\npremise, we indeed have $\\interp{T_1}_{\\sigma,\\rho}\\in\\mathcal{R}$.\nSo if $\\interp{T_1}_{\\sigma,\\rho}$ is non-empty, then the intersection of all the sets\n$\\interp{T_2}_{\\sigma[x\\mapsto \\choice(E)],\\rho}$ where $E\\in\\interp{T_1}_{\\sigma,\\rho}$ is a\nreducibility candidate, since each of those sets is.  By the semantics\nof $\\forall$-types quantifying over terms, this is sufficient.  If $\\interp{T_1}_{\\sigma,\\rho}$ is\nempty, then the interpretation of the $\\forall$-type is $[\\mathcal{L}]_{\\cbe}$ by the definition\nof $\\elcap_\\star$, and this is in $\\mathcal{R}$.\n\n\\startcase{.2cm}\n\\[\n    \\infer{\\Gamma\\vdash \\abs{\\forall}{X}{\\kappa}{T} \\tpsynth \\star}{\\Gamma \\vdash \\kappa & \\Gamma,X:\\kappa\\vdash T \\tpsynth \\star} \n\\]\nSimilarly to the previous case: by the IH for the second premise,\n$\\interp{T_2}_{\\sigma,\\rho[X\\mapsto S}\\in\\mathcal{R}$, for every\n$S\\in\\interp{\\kappa}_{\\sigma,\\rho}$.  By the IH part for the first\npremise, $\\interp{\\kappa}_{\\sigma,\\rho}$ is defined.  So the\nintersection of all the sets $\\interp{T_2}_{\\sigma,\\rho[X\\mapsto S]}$\nwhere $S\\in\\interp{\\kappa}_{\\sigma,\\rho}$ is a reducibility candidate,\nsince each of those sets is.  The intersection is nonempty, since $\\interp{\\kappa}_{\\sigma,\\rho}$ is (as stated in a lemma above).\nBy the semantics of $\\forall$-types\nquantifying over types, this is sufficient. \n\n\\startcase{.2cm}\n\\[\n    \\infer{\\Gamma\\vdash\\abs{\\iota}{x}{T}{T'} \\tpsynth \\star}{\\Gamma \\vdash T \\tpsynth \\star & \\Gamma,x:T\\vdash T' \\tpsynth \\star} \n\\]\nThe set $\\interp{\\iota x:T.T'}_{\\sigma,\\rho}$ is explicitly defined to\nbe a subset of $\\interp{T}_{\\sigma,\\rho}$, which is in $\\mathcal{R}$,\nby the IH applied to the first premise.  Since for any\n$A\\subseteq\\mathcal{L}$, $[A]_{\\cbe}$ is in $\\mathcal{R}$, to show that\n$\\interp{\\iota x:T.T'}_{\\sigma,\\rho}$ is also in $\\mathcal{R}$ it suffices\nto show definedness of $\\interp{T'}_{\\sigma[x\\mapsto \\choice(E)],\\rho}\\}$\n(which is used in the predicate picking out the\nparticular subset of $\\interp{T}_{\\sigma,\\rho}$), for\n$E\\in\\interp{T}_{\\sigma,\\rho}$.  For such $E$, $\\choice(E)$ is defined\n(since $\\interp{T}_{\\sigma,\\rho}\\in\\mathcal{R}$ and hence $E\\in\\interp{T}_{\\sigma,\\rho}$ is nonempty)\nand in $E$,\nso $\\sigma[x\\mapsto\\choice(E)]\\in\\interp{\\Gamma,x:T}$.  So\nby the IH for the second premise,\n$\\interp{T'}_{\\sigma[x\\mapsto\\choice(E),\\rho]}$ is defined.\n\n\\startcase{.2cm}\n\\[\n \\infer{\\Gamma\\vdash\\abs{\\lambda}{x}{T}{T'} \\tpsynth \\abs{\\Pi}{x}{T}{\\kappa}}{\\Gamma \\vdash T \\tpsynth \\star & \\Gamma,x:T\\vdash T'\\tpsynth\\kappa}\n\\]\nBy the semantics, $\\interp{\\lambda x:T.T'}_{\\sigma,\\rho}$ is\n$(E\\in\\interp{T}_{\\sigma,\\rho} \\mapsto \\interp{T'}_{\\sigma[x\\mapsto\n  \\choice(E)],\\rho})$.  We must show that this (meta-level) function\nis in $\\interp{\\Pi x:T.\\kappa}_{\\sigma,\\rho}$.  By the semantics of\nkinds, the latter quantity, if defined, is\n$(E\\in\\interp{T}_{\\sigma,\\rho} \\to_{\\cbe}\n\\interp{\\kappa}_{\\sigma[x\\mapsto \\choice(E)],\\rho})$.\nBy the IH for the first premise, $\\interp{T}_{\\sigma,\\rho}\\in\\mathcal{R}$.\nSo we must just show that for any $E\\in\\interp{T}_{\\sigma,\\rho}$,\n$\\interp{T'}_{\\sigma[x\\mapsto\n  \\choice(E)],\\rho}\\in\\interp{\\kappa}_{\\sigma[x\\mapsto\n  \\choice(E)],\\rho}$.  But this follows by the IH for the second\npremise.\n\n\\startcase{.2cm}\n\\[\n\\infer{\\Gamma\\vdash\\abs{\\lambda}{X}{\\kappa}{T'} \\tpsynth \\abs{\\Pi}{X}{\\kappa}{\\kappa'}}\n      {\\Gamma \\vdash \\kappa & \\Gamma,X:\\kappa\\vdash T'\\tpsynth\\kappa'} \n\\]\nThis case is an easier version of the previous one.  It suffices to\nassume an arbitrary $S\\in\\interp{\\kappa}_{\\sigma,\\rho}$ and show\n$\\interp{T'}_{\\sigma,\\rho[X\\mapsto S]}\\in\\interp{\\kappa'}_{\\sigma,\\rho[X\\mapsto S]}$.  But this follows\nby the IH applied to the second premise.  And we have definedness of\n$\\interp{\\kappa}_{\\sigma,\\rho}$ by the IH for the first premise.\n\n\\startcase{.2cm}\n\\[\n   \\infer{\\Gamma\\vdash T\\ t \\tpsynth [t/x]\\kappa}{\\Gamma\\vdash T \\tpsynth \\abs{\\Pi}{x}{T'}{\\kappa} & \\Gamma\\vdash t \\tpcheck T'} \n\\]\nBy the IH for the first premise,\n$\\interp{T}_{\\sigma,\\rho}\\in\\interp{\\Pi x:T'.\\kappa}_{\\sigma,\\rho}$.\nBy the semantics of $\\Pi$-kinds, this means that\n$\\interp{T}_{\\sigma,\\rho}$ is a function which given any\n$E\\in\\interp{T'}_{\\sigma,\\rho}$, will produce a result in\n$\\interp{\\kappa}_{\\sigma[x\\mapsto \\choice(E)],\\rho}$.  By the\nsemantics of type applications, $\\interp{T\\ t}_{\\sigma,\\rho}$ is equal\nto $\\interp{T}_{\\sigma,\\rho}([\\sigma |t|]_{\\cbe})$.  This is defined,\nsince $[\\sigma |t|]_{\\cbe}\\in\\interp{T'}_{\\sigma,\\rho}$, by the IH for\nthe second premise; note that $\\interp{T'}_{\\sigma,\\rho}$ is defined\nsince otherwise $\\interp{\\Pi x:T'.\\kappa}_{\\sigma,\\rho}$ would not be defined.\nThe result of applying the function is thus indeed\nin $\\interp{[t/x]\\kappa}_{\\sigma,\\rho}$, since by\nLemma~\\ref{lem:termsubstinterp}, this equals\n$\\interp{\\kappa}_{\\sigma[x\\mapsto \\choice([\\sigma |t|]_{\\cbe})],\\rho}$\n(the codomain of the function being applied).\n\n\\startcase{.2cm}\n\\[\n\\infer{\\Gamma\\vdash T\\cdot T' \\tpsynth [T'/X]\\kappa}\n      {\\Gamma\\vdash T \\tpsynth \\abs{\\Pi}{X}{\\kappa'}{\\kappa} & \\Gamma\\vdash T' \\tpsynth \\kappa' & \\kappa \\cong \\kappa'} \n\\]\nBy the IH applied to the first premise,\n$\\interp{T}_{\\sigma,\\rho}\\in\\interp{\\abs{\\Pi}{X}{\\kappa'}{\\kappa}}_{\\sigma,\\rho}$.\nBy the semantics of $\\Pi$-kinds, this means that for any\n$S\\in\\interp{\\kappa'}_{\\sigma,\\rho}$, $\\interp{T}_{\\sigma,\\rho}\\ S$ is in\n$\\interp{\\kappa}_{\\sigma,\\rho[X\\mapsto S]}$.  By the IH for the second premise, we have \n$\\interp{T'}\\interp{\\kappa'}_{\\sigma,\\rho}$, and by the IH for the third premise,\nwe have $\\interp{\\kappa}_{\\sigma,\\rho} = \\interp{\\kappa'}_{\\sigma,\\rho}$.  So\nwe get $\\interp{T}_{\\sigma,\\rho}(\\interp{T'}_{\\sigma,\\rho})\\in \\interp{\\kappa}_{\\sigma,\\rho[X\\mapsto \\interp{T'}_{\\sigma,\\rho}]}$,\nwhich suffices by Lemma~\\ref{lem:tpsubstinterp}.\n\n\\startcase{.2cm}\n\\[\n    \\infer{\\Gamma\\vdash \\{ t \\simeq t' \\} : \\star}{\\textit{FV}(t\\ t')\\subseteq\\textit{dom}(\\Gamma)}\n\\]\nEither $\\sigma |t| =_{\\cbe} \\sigma |t'|$ or not.  Either way, the interpretation is defined and in $\\mathcal{R}$, since\n$\\textit{FV}(t\\ t')\\subseteq\\textit{dom}(\\sigma)$ (as an easy consequence of $(\\sigma,\\rho)\\in\\interp{\\Gamma}$).\n\n\\subsection{Proof of parts (3) and (4)}\n\n\\startcase{.2cm}\n\\[\n    \\infer{\\Gamma\\vdash x\\tpsynth T}{(x : t)\\in\\Gamma} \n\\]\nThis follows from the definition of $\\interp{\\Gamma}$.\n\n\\startcase{.2cm}\n\\[\n \\infer{\\Gamma\\vdash t\\tpcheck T'}{\\Gamma\\vdash t \\tpcheck T & T' \\leadsto^*_\\beta T} \n\\]\nWe are assuming $\\interp{T'}_{\\sigma,\\rho}$ is defined, since this is a checking judgment. The desired result then\nfollows from Lemma~\\ref{lem:interppres}.\n\n\\startcase{.2cm}\n\\[\n    \\infer{\\Gamma\\vdash t\\tpsynth T'}{\\Gamma\\vdash t \\tpsynth T & T \\leadsto^*_\\beta T'} \n\\]\nThis also follows from Lemma~\\ref{lem:interppres} and the induction hypothesis for the first premise,\nwhich implies $\\interp{T}_{\\sigma,\\rho}\\in\\mathcal{R}$ (and hence defined).\n\n\\startcase{.2cm}\n\\[\n\\infer{\\Gamma\\vdash t\\tpcheck T}{\\Gamma\\vdash t\\tpsynth T' & T' \\cong T} \n\\]\nBy the IH applied to the first premise, we have \n$[\\sigma t]_{\\cbe}\\in\\interp{T'}_{\\sigma,\\rho}\\in\\mathcal{R}$. By assumption, $\\interp{T}_{\\sigma,\\rho}\\in\\mathcal{R}$,\nand so by the IH applied to the second premise, we have $[\\sigma t]_{\\cbe}\\in\\interp{T'}_{\\sigma,\\rho} = \\interp{T}_{\\sigma,\\rho}$.\n\n\n\\startcase{.2cm}\n\\[\n    \\infer{\\Gamma\\vdash \\absu{\\lambda}{x}{t} \\tpcheck \\abs{\\Pi}{x}{T}{T'}}{\\Gamma,x:T\\vdash t\\tpcheck T'} \n\\]\nTo show $[\\sigma \\lambda x.t]_{\\cbe}\\in\\interp{\\Pi  x:T.T'}_{\\sigma,\\rho}$ (noting that the latter is defined\nand in $\\mathcal{R}$ by assumption), it suffices to assume an arbitrary\n$E\\in\\interp{T}_{\\sigma,\\rho}$, and show\n$[[\\choice(E)/x]\\sigma t]_{\\cbe}\\in\\interp{T'}_{\\sigma[x\\mapsto\\choice(E)],\\rho}$.  By the IH,\nwe have\n$[\\sigma[x\\mapsto\\choice(E)]t]_{\\cbe}\\in\\interp{T'}_{\\sigma[x\\mapsto\\choice(E)],\\rho}$.\nBut $[\\sigma[x\\mapsto\\choice(E)]t]_{\\cbe} = [[\\choice(E)/x]\\sigma t]_{\\cbe}$,\nso this is sufficient.\n\n\\startcase{.2cm}\n\\[\n    \\infer{\\Gamma\\vdash t\\ t' \\tpsynth [t'/x]T}{\\Gamma\\vdash t \\tpsynth \\abs{\\Pi}{x}{T'}{T} & \\Gamma\\vdash t' \\tpcheck T'} \n\\]\nBy the IH applied to the first premise, $[\\sigma\nt]_{\\cbe}\\in\\interp{\\Pi x:T'.T}_{\\sigma,\\rho}\\in\\mathcal{R}$.  This\nmeans that there exists a $\\lambda$-abstraction $\\lambda x.\\hat{t}$\nsuch that $\\lambda x.\\hat{t} =_{\\cbe} \\sigma t$, by the semantics of $\\Pi$-types.\nFurthermore, for any $E\\in\\interp{T'}_{\\sigma,\\rho}$,\n$[[\\choice(E)/x]\\hat{t}]_{\\cbe}\\in\\interp{T}_{\\sigma[x\\mapsto\\choice(E)],\\rho}$.\nBy the IH applied to the second premise, $[\\sigma t']_{\\cbe}\\in\\interp{T'}_{\\sigma,\\rho}$,\nso we can instantiate the quantifier in the previous formula to obtain\n\\[\n [[\\choice([\\sigma t']_{\\cbe})/x]\\hat{t}]_{\\cbe}\\in\\interp{T}_{\\sigma[x\\mapsto\\choice([\\sigma t']_{\\cbe})],\\rho}\n\\]\nBy Lemma~\\ref{lem:termsubstinterp}, this is equivalent to\n\\[\n [[\\choice([\\sigma t']_{\\cbe})/x]\\hat{t}]_{\\cbe}\\in\\interp{[t'/x]T_2}_{\\sigma,\\rho}\n\\]\nSince $\\sigma (t\\ t') =_{\\cbe} (\\lambda x.\\hat{t})\\ \\sigma t' =_{\\cbe} [[\\choice([\\sigma t']_{\\cbe})/x]\\hat{t}$,\nthis is sufficient.\n\n\\startcase{.2cm}\n\\[\n    \\infer{\\Gamma\\vdash \\absu{\\Lambda}{X}{t} \\tpcheck \\abs{\\forall}{X}{\\kappa}{T}}{\\Gamma,X:\\kappa\\vdash t \\tpcheck T} \n\\]\nBy the IH, $[\\sigma |t|]_{\\cbe}\\in\\interp{T}_{\\sigma,\\rho[X\\mapsto S]}$, for all $S\\in\\interp{\\kappa}_{\\sigma,\\rho}$.\nThis is sufficient to prove $[\\sigma |\\absu{\\Lambda}{X}{t}|]_{\\cbe}\\in\\interp{\\forall X:\\kappa.T}_{\\sigma,\\rho}$, by the semantics\nof $\\forall$-types and definition of erasure.\n\n\\startcase{.2cm}\n\\[\n    \\infer{\\Gamma\\vdash t \\cdot T' \\tpsynth [T'/X]T}\n          {\\Gamma\\vdash t \\tpsynth \\abs{\\forall}{X}{\\kappa}{T} & \\Gamma\\vdash T' \\tpcheck\\kappa} \n\\]\nBy the semantics of $\\forall$-types and the IH applied to the first\npremise, we have $[\\sigma |t|]_{\\cbe}\\in\\interp{T}_{\\sigma,\\rho[X\\mapsto\n  S]}$, for all $S\\in\\interp{\\kappa}_{\\sigma,\\rho}$.  Since\n$\\interp{T'}_{\\sigma,\\rho}\\in\\interp{\\kappa}_{\\sigma,\\rho}$ by the IH\napplied to the second premise, we can derive $[\\sigma t]_{\\cbe}\\in\\interp{T}_{\\sigma,\\rho[X\\mapsto \\interp{T'}_{\\sigma,\\rho}]}$.\nBy Lemma~\\ref{lem:tpsubstinterp},\nthis is equivalent to the required $[\\sigma |t|]_{\\cbe}\\in\\interp{[T'/X]T}_{\\sigma,\\rho}$,\nusing also the definition of erasure.\n\n\\startcase{.2cm}\n\\[\n    \\infer{\\Gamma\\vdash \\absu{\\Lambda}{x}{t} \\tpcheck \\abs{\\forall}{x}{T'}{T}}{\\Gamma,x:T'\\vdash t \\tpcheck T & x\\not\\in\\textit{FV}(|t|)} \n\\]\n\nBy the IH applied to the first premise, we have\n$[\\sigma[x\\mapsto\\choice(E)]\nt]_{\\cbe}\\in\\interp{T'}_{\\sigma[x\\mapsto\\choice(E)],\\rho}$, for any\n$E\\in\\interp{T}_{\\sigma,\\rho}$.  This is because\n$\\interp{T}_{\\sigma,\\rho}\\in\\mathcal{R}$, since $\\interp{\\abs{\\forall}{x}{T'}{T}}_{\\sigma,\\rho}$ is in $\\mathcal{R}$ and\nhence defined, by assumption.  Since $x\\not\\in\\textit{FV}(t)$, we know\n$[[\\sigma[x\\mapsto\\choice(E)]t]_{\\cbe} = [\\sigma t]_{\\cbe}$.  By the\nsemantics of $\\forall$-types and definition of erasure, this suffices to show the desired\nconclusion.\n\n\\startcase{.2cm}\n\\[\n    \\infer{\\Gamma\\vdash t\\ \\mhyph t' \\tpsynth [t'/x]T}{\\Gamma\\vdash t \\tpsynth \\abs{\\forall}{x}{T'}{T} & \\Gamma\\vdash t' \\tpcheck T'}\n\\]\nThe result follows easily by the IH applied to the premises, the\nsemantics of $\\forall$-types, definition of erasure, and Lemma~\\ref{lem:termsubstinterp}.\n\n\n\\startcase{.2cm}\n\\[\n    \\infer{\\Gamma\\vdash [ t , t' ] \\tpcheck \\abs{\\iota}{x}{T}{T'}}\n          {\\Gamma\\vdash t \\tpcheck T & \\Gamma\\vdash t' \\tpcheck [t/x]T' & |t| =_{\\beta\\eta} |t'|} \n\\]\nBy the IH, we have $[\\sigma |t|]_{\\cbe}\\in\\interp{T}_{\\sigma,\\rho}$ and\n$[\\sigma |t|]_{\\cbe}\\in\\interp{[t/x]T'}_{\\sigma,\\rho}$.  By\nLemma~\\ref{lem:termsubstinterp}, the latter is equivalent to\n$[\\sigma t]_{\\cbe}\\in\\interp{T'}_{\\sigma[x\\mapsto\\choice([\\sigma t]_{\\cbe}),\\rho}$.  These two facts about $[\\sigma t]_{\\cbe}$ are\nsufficient, by the semantics of $\\iota$-types, for the desired\nconclusion, using also the fact (from the third premise) that $\\sigma|t| =_{\\cbe} \\sigma|t'|$.\n\n\\startcase{.2cm}\n\\[\n   \\infer{\\Gamma\\vdash t.1 \\tpsynth T}{\\Gamma\\vdash t \\tpsynth \\abs{\\iota}{x}{T}{T'}} \n\\]\nThe desired conclusion follows easily from the IH and the semantics of $\\iota$-types.\n\n\\startcase{.2cm}\n\\[\n    \\infer{\\Gamma\\vdash t.2 \\tpsynth [t.1/x]T'}{\\Gamma\\vdash t \\tpsynth \\abs{\\iota}{x}{T}{T'}} \n\\]\nSimilar to the previous case, using Lemma~\\ref{lem:termsubstinterp}.\n\n\\startcase{.2cm}\n\\[\n    \\infer{\\Gamma\\vdash \\beta\\{t'\\} \\tpcheck \\{ t \\simeq t \\}}{\\Gamma\\vdash \\textit{FV}(t)\\subseteq \\textit{dom}(\\Gamma)}  \n\\]\n$[\\sigma|t'|]_{\\cbe}\\in\\interp{\\{ t \\simeq t \\}}_{\\sigma,\\rho}$ follows directly from the semantics of equality types.\n\n\\startcase{.2cm}\n\\[\n    \\infer{\\Gamma\\vdash \\delta\\ t \\tpcheck T}{\\Gamma\\vdash t\\tpsynth \\{ \\absu{\\lambda}{x}{\\absu{\\lambda}{y}{x}} \\simeq \\absu{\\lambda}{x}{\\absu{\\lambda}{y}{y}}\\}}  \n\\]\nBy the semantics of equality types, $[\\sigma|t'|]_{\\cbe}$ cannot be in the interpretation of the equation in the premise,\nsince the two terms in question are closed and not $\\beta\\eta$-equal.  By the IH applied to the first premise, however,\n$[\\sigma|t'|]_{\\cbe}$ is in the interpretation of that equation.  This is a contradiction.\n\n\\startcase{.2cm}\n\\[\n    \\infer{\\Gamma\\vdash \\rho\\ t'\\ \\mhyph\\ t \\Leftrightarrow [t_2/x]T}\n          {\\Gamma\\vdash t' \\tpsynth t_1 \\simeq t_2 & \\Gamma \\vdash t \\Leftrightarrow [t_1/x]T} \n\\]\nBy the IH applied to the first premise, $\\sigma|t_1| =_{\\beta\\eta} \\sigma|t_2|$.  The result then follows by the IH applied to the second premise,\nand Lemma~\\ref{lem:termsubstinterp}.\n\n\\startcase{.2cm}\n\\[\n    \\infer{\\Gamma\\vdash \\chi\\ T\\ \\mhyph\\ t \\tpcheck T'}\n          {\\Gamma\\vdash T\\tpcheck \\star & \\Gamma\\vdash t \\tpcheck T & T \\cong T'} \n\\]\nUsing the IH for the first premise and the assumption that $\\interp{T'}_{\\sigma,\\rho}$ is in $\\mathcal{R}$ and hence defined,\nwe can apply the IH to the third premise to get $\\interp{T}_{\\sigma,\\rho} = \\interp{T'}_{\\sigma,\\rho}$.  Using this and the IH for second premise,\nwe get the desired conclusion, using also the definition of erasure.\n\n\\startcase{.2cm}\n\\[\n    \\infer{\\Gamma\\vdash \\chi\\ T\\ \\mhyph\\ t \\tpsynth T}\n          {\\Gamma\\vdash T\\tpcheck \\star & \\Gamma\\vdash t \\tpsynth T' & T \\cong T'} \n\\]\nBy the IH applied to the second premise, we have $[\\sigma|t|]_{\\cbe}\\in\\interp{T'}_{\\sigma,\\rho}\\in\\mathcal{R}$.\nUsing definedness of $\\interp{T'}_{\\sigma,\\rho}$ and the IH applied to the first premise, we can apply the\nIH to the third premise to get $\\interp{T}_{\\sigma,\\rho} = \\interp{T'}_{\\sigma,\\rho}$, from which the desired\nconclusion follows by definition of erasure.\n\n\\startcase{.2cm}\n\\[\n    \\infer{\\Gamma\\vdash \\phi\\ t\\ \\mhyph\\ t'\\{t''\\} \\Leftrightarrow T}\n          {\\Gamma\\vdash t\\tpsynth \\{t'\\simeq t''\\} & \\Gamma\\vdash t' \\Leftrightarrow T}  \n\\]\nBy the IH for the first premise, $\\sigma|t'| =_{\\cbe} \\sigma|t''|$.  By the IH for the second\npremise, $[\\sigma|t'|]_{\\cbe}\\in\\interp{T}_{\\sigma,\\rho}$.  This suffices for the desired conclusion,\nusing also the definition of erasure ($|\\phi\\ t\\ \\mhyph\\ t'\\{t''\\}| = |t''|$).\n\n\\subsection*{Proof of part (5) }\n\n\n\n\\startcase{.2cm}\n\\[\n    \\infer{T \\cong T'}{T \\leadsto^*_\\beta T_1 & T' \\leadsto^*_\\beta T_2 & T_1\\cong^t T_2}  \n\\]\nBy Lemma~\\ref{lem:interppres}, we have\n\\[\n\\begin{array}{lll}\n  \\interp{T}_{\\sigma,\\rho} & = & \\interp{T_1}_{\\sigma,\\rho}\\\\\n  \\interp{T'}_{\\sigma,\\rho} & = & \\interp{T_2}_{\\sigma,\\rho}\n\\end{array}\n\\]\nBy the IH for the third premise, we have $\\interp{T_1}_{\\sigma,\\rho} = \\interp{T_2}_{\\sigma,\\rho}$,\nwhich suffices.\n\n\\startcase{.2cm}\n\\[\n    \\infer{T \\cong T'}{T \\cong^t T'} \n\\]\nBy the IH.\n\n\\startcase{.2cm}\n\\[\n    \\infer{T\\ t \\cong^t T'\\ t'}{T \\cong^t T' & |t| =_{\\beta\\eta} |t'|}\n\\]\nBy the semantics, $\\interp{T\\ t}_{\\sigma,\\rho} =\n\\interp{T}_{\\sigma,\\rho}([\\sigma|t|]_{\\cbe})$.  By the second premise\nand the IH for the first premise, this equals\n$\\interp{T'}_{\\sigma,\\rho}([\\sigma|t'|]_{\\cbe})$, as required.\n\n\\startcase{.2cm}\n\\[\n    \\infer{\\{ t_1 \\simeq t_2 \\} \\cong^t \\{ t_1'\\ \\simeq t_2' \\}}{|t_1| =_{\\beta\\eta} |t_1'| & |t_2| =_{\\beta\\eta} |t_2'|}\n\\]\nThis follows easily from the premises and the semantics of equality types.\n\n\\end{proof}\n\\end{document}\n", "meta": {"hexsha": "c8647b77b98585482994acb6812b6221f8fe06cf", "size": 47443, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/semantics/arxiv-version.tex", "max_stars_repo_name": "xoltar/cedille", "max_stars_repo_head_hexsha": "acf691e37210607d028f4b19f98ec26c4353bfb5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/semantics/arxiv-version.tex", "max_issues_repo_name": "xoltar/cedille", "max_issues_repo_head_hexsha": "acf691e37210607d028f4b19f98ec26c4353bfb5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/semantics/arxiv-version.tex", "max_forks_repo_name": "xoltar/cedille", "max_forks_repo_head_hexsha": "acf691e37210607d028f4b19f98ec26c4353bfb5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.2539840637, "max_line_length": 175, "alphanum_fraction": 0.6711000569, "num_tokens": 16574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3364734692568112}}
{"text": "\\documentclass{article}\n\\usepackage[english]{babel}\n\\usepackage{amsmath,amssymb,graphicx,enumerate,latexsym}\n\n%%%%%%%%%% Start TeXmacs macros\n\\newcommand{\\dueto}[1]{\\textup{\\textbf{(#1) }}}\n\\newcommand{\\longupdownarrow}{{\\mbox{\\rotatebox[origin=c]{-90}{$\\longleftrightarrow$}}}}\n\\newcommand{\\nobracket}{}\n\\newcommand{\\tmaffiliation}[1]{\\\\ #1}\n\\newcommand{\\tmemail}[1]{\\\\ \\textit{Email:} \\texttt{#1}}\n\\newcommand{\\tmop}[1]{\\ensuremath{\\operatorname{#1}}}\n\\newenvironment{enumeratenumeric}{\\begin{enumerate}[1.] }{\\end{enumerate}}\n\\newenvironment{proof}{\\noindent\\textbf{Proof\\ }}{\\hspace*{\\fill}$\\Box$\\medskip}\n%%%%%%%%%% End TeXmacs macros\n\n\\begin{document}\n\n\n\n\\title{Topology}\n\n\\author{\n  Liangchun Xu\n  \\tmaffiliation{Department of Mechanical Engineering, Tufts University\\\\\n  574 Boston Avenue, Medford, 02155, US}\n  \\tmemail{liangchun.xu@tufts.edu}\n}\n\n\\date{March 4, 2019}\n\n\\maketitle\n\n{\\tableofcontents}\n\n\\section{Cardinality and the Axiom of Choice}\n\n{\\definition*{{\\dueto{number sets}}Throughout these notes we will use the\nfollowing notation:\n\\begin{enumeratenumeric}\n  \\item $\\mathbb{N}= \\tmop{the} \\tmop{set} \\tmop{of} \\tmop{natural}\n  \\tmop{numbers}$ (i.e., the positive integers).\n  \n  \\item $\\mathbb{Z}= \\tmop{the} \\tmop{set} \\tmop{of} \\tmop{all}\n  \\tmop{integers}$.\n  \n  \\item $\\mathbb{Q}= \\tmop{the} \\tmop{set} \\tmop{of} \\tmop{rational}\n  \\tmop{numbers}$.\n  \n  \\item $\\mathbb{R}= \\tmop{the} \\tmop{set} \\tmop{of} \\tmop{real}\n  \\tmop{numbers}$.\n\\end{enumeratenumeric}}}\n\n{\\definition*{{\\dueto{cardinality}}Two sets, $A \\tmop{and} B$, have the same\ncardinality iff there is a 1-1, onto function $f : X \\rightarrow \\{ 1, 2,\n\\ldots, n \\}$ where $n$ is an element of $\\mathbb{N}$. A set that's not finite\nis infinite.}}\n\nAbout the natural numbers $\\mathbb{N}$: every non-empty set of natural numbers\nhas a least element.\n\n{\\theorem*{The even positive integers have the same cardinality as the natural\nnumbers.}}\n\n\\begin{proof}\n  The even positive integers are\n  \\begin{eqnarray*}\n    \\mathbb{E}^+ & = & \\{ \\nobracket 2 n | n \\in \\mathbb{N} \\}\n  \\end{eqnarray*}\n  Construct function $f : \\mathbb{N} \\rightarrow \\mathbb{E}^+$\n  \\[ f (n) = 2 n \\]\n  $f (n)$ is in $\\mathbb{E}^+$ by definition. Claim $f$ is 1-1 and onto:\n  \n  1-1: Suppose $f (n) = f (n')$, then $2 n = 2 n'$ and $n = n'$;\n  \n  onto: Suppose $b \\in \\mathbb{E}^+$, then $b = 2 n$ for some $n \\in\n  \\mathbb{N}$, $f (n) = 2 n = b$.\n  \n  As we have exhibited a $1 - 1$ onto function $f : \\mathbb{N} \\rightarrow\n  \\mathbb{E}^+$, $| \\mathbb{N} | = | \\mathbb{E}^+ |$.\n\\end{proof}\n\n{\\theorem*{$| \\mathbb{N} | = | \\mathbb{Z} |$.}}\n\n\\begin{proof}\n  The correpondence is\n  \\[ \\begin{array}{ccccccccccc}\n       0 & - 1 & 1 & - 2 & 2 & - 3 & 3 & - 4 & 4 & - 5 & \\ldots\\\\\n       \\longupdownarrow &  &  &  & \\longupdownarrow &  &  &  &  &\n       \\longupdownarrow & \\\\\n       1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & \\ldots\n     \\end{array} \\]\n  \n  \n  Construct function $f : \\mathbb{N} \\rightarrow \\mathbb{Z}$\n  \\[ f (n) = \\left\\{\\begin{array}{l}\n       \\frac{n - 1}{2}, \\tmop{if} n \\in \\mathbb{E}^+\\\\\n       - \\frac{n}{2}, \\tmop{if} n \\in \\mathbb{O}^+\n     \\end{array}\\right. \\]\n  $f (n)$ is in $\\mathbb{Z}$ by definition. Claim $f$ is 1-1 and onto:\n  \n  1-1: Suppose $f (n) = f (n')$, then\n  \\[ \\left\\{\\begin{array}{l}\n       \\frac{n - 1}{2} = \\frac{n' - 1}{2}, \\tmop{if} n \\in \\mathbb{E}^+\\\\\n       - \\frac{n}{2} = - \\frac{n'}{2}, \\tmop{if} n \\in \\mathbb{O}^+\n     \\end{array}\\right. \\Rightarrow n = n' \\]\n  Since $\\frac{n - 1}{2} \\geqslant 0 \\tmop{and} - \\frac{n}{2} < 0$, we have\n  $\\frac{n - 1}{2} \\neq - \\frac{n'}{2}$; only the above two cases are\n  possible.\n  \n  onto: Suppose $b \\in \\mathbb{Z}$, then\n  \\[ \\left\\{\\begin{array}{l}\n       b = \\frac{n - 1}{2}, \\tmop{if} b \\geqslant 0\\\\\n       b = - \\frac{n}{2}, \\tmop{if} b < 0\n     \\end{array}\\right. \\]\n  for some $n \\in \\mathbb{N}$, $f (n) = b$.\n  \n  As we have exhibited a $1 - 1$ onto function $f : \\mathbb{N} \\rightarrow\n  \\mathbb{Z}$, $| \\mathbb{N} | = | \\mathbb{Z} |$.\n\\end{proof}\n\n{\\theorem*{{\\dueto{pigeon-hole principle}}Suppose that $n$ is a natural number\nand you have $n$ pidgeon-holes. If you have $m$ podgeons where $m > n$, and\nyou put each pidgeon in one of your $n$ pidgeon-holes, there will be some hole\nwhich contains more than 1 pidgeon.}}\n\n\\begin{proof}\n  Let $q_i$ be the number of pidgeons in each hole, then\n  \\[ \\sum_{i = 1}^n q_i = m \\]\n  Suppose no hole contains more than 1 pidgeon, which is\n  \\[ 0 \\leqslant q_i \\leqslant 1, \\applicationspace{1 \\tmop{em}} i = 1, 2,\n     \\ldots n \\]\n  Then we have\n  \\[ \\sum_{i = 1}^n q_i \\leqslant \\sum_{i = 1}^n 1 = n \\]\n  Since $m > n$, then\n  \\[ \\sum_{i = 1}^n q_i < m \\]\n  which leads to contradiction. Therefore the assumption is not correct. There\n  must be some hole which contains more than 1 pidgeon.\n\\end{proof}\n\n{\\theorem*{{\\dueto{induction}}For each natural number $n$, let $S (n)$ be a\nstatement that is either true or false. Then suppose that\n\\begin{enumeratenumeric}\n  \\item $S (1)$ is true.\n  \n  \\item If $S (k)$ is true, then $S (k + 1)$ is true.\n\\end{enumeratenumeric}\nThen $S (n)$ is true for all natural numbers $n$.}}\n\n\\begin{proof}\n  Suppose there is an non-empty set\n  \\[ X = \\{ n \\in \\mathbb{N}, S (n) \\tmop{is} \\tmop{false} \\} \\]\n  There exists a smallest element $x \\in X$ since $X \\subseteq \\mathbb{N}$.\n  \n  According to assumption 1 and the definiton of $X$, $x \\neq 1 \\tmop{and} x\n  > 1$.\n  \n  According to assumption 2, if $S (x)$ is false, then $S (x - 1)$ is also\n  false. Since $x - 1 < x$ and $x - 1 \\in \\mathbb{N}$, $x - 1$ becomes the\n  smallest element in $X$, which is contradictory to the fact that $x$ is the\n  smallest element in $X$. Therefore the assumption is wrong. $X$ is empty and\n  $S (n)$ is true for all natural numbers $n$.\n\\end{proof}\n\n{\\theorem*{Every subset of $\\mathbb{N}$ is either finite or has the same\ncardinality as $\\mathbb{N}$.}}\n\n\\begin{proof}\n  Let $X \\subseteq \\mathbb{N}$, construct function $f : \\mathbb{N} \\rightarrow\n  X$\n  \\begin{eqnarray*}\n    f (1) & = & \\min (X)\\\\\n    f (2) & = & \\min (X\\backslash \\{ f (1) \\})\\\\\n    & \\vdots & \\\\\n    f (n) & = & \\min (X\\backslash \\{ f (1), f (2), \\ldots, f (n - 1) \\})\n  \\end{eqnarray*}\n  if $X\\backslash \\{ f (1), f (2), \\ldots, f (n - 1) \\}$ is empty, then we\n  have a 1-1 bijection $f : \\{ 1, 2, \\ldots, n \\} \\rightarrow X$, which means\n  $X$ is finite. If $X$ is infinite, then claim $f : \\mathbb{N} \\rightarrow X$\n  is $1 - 1$ and onto:\n  \n  1-1: Suppose $f (n) = f (n')$, then $n = n'$.\n  \n  onto: Suppose $b \\in X$, then $b = \\min (X\\backslash \\{ f (1), f (2),\n  \\ldots, f (n - 1) \\})$ for some $n \\in \\mathbb{N}$, $f (n) = b$.\n  \n  As we have exhibited a $1 - 1$ onto function $f : \\mathbb{N} \\rightarrow X$,\n  $| \\mathbb{N} | = | X |$.\n  \n  Therefore every subset of $\\mathbb{N}$ is either finite or has the same\n  cardinality as $\\mathbb{N}$.\n\\end{proof}\n\n{\\definition*{{\\dueto{countable set}}A set that has the same cardinality as a\nsubset of $\\mathbb{N}$ is countable.}}\n\n{\\theorem*{Every infinite set has a countably infinite subset.}}\n\n{\\theorem*{A set is infinite iff there is a 1-1 function from the set into a\nproper subset of itself.}}\n\n{\\theorem*{$\\mathbb{Q}$ is countable.}}\n\n\\begin{proof}\n  Construct function $f : \\mathbb{N} \\rightarrow \\mathbb{Q}$\n  \n  \n  \\[ \\begin{array}{lllllllllllll}\n       & 0 &  & - 1 &  & 1 &  & - 2 &  & 2 &  & - 3 & \\ldots\\\\\n       1 & \\frac{0}{1} & \\rightarrow & - \\frac{1}{1} & \\rightarrow &\n       \\frac{1}{1} &  & - \\frac{2}{1} & \\rightarrow & \\frac{2}{1} &  & -\n       \\frac{3}{1} & \\ldots\\\\\n       &  &  &  & \\swarrow &  & \\nearrow &  & \\swarrow &  & \\nearrow &  & \\\\\n       2 &  &  & - \\frac{1}{2} &  & \\frac{1}{2} &  & - \\frac{2}{2} &  &\n       \\frac{2}{2} &  &  & \\\\\n       &  &  & \\downarrow & \\nearrow &  & \\swarrow &  & \\nearrow &  &  &  &\n       \\\\\n       3 &  &  & - \\frac{1}{3} &  & \\frac{1}{3} &  & - \\frac{2}{3} &  &  &  & \n       & \\\\\n       &  &  &  & \\swarrow &  & \\nearrow &  &  &  &  &  & \\\\\n       4 &  &  & - \\frac{1}{4} &  & \\frac{1}{4} &  &  &  &  &  &  & \\\\\n       &  &  & \\downarrow & \\nearrow &  &  &  &  &  &  &  & \\\\\n       5 &  &  & - \\frac{1}{5} &  &  &  &  &  &  &  &  & \\\\\n       \\vdots &  &  &  &  &  &  &  &  &  &  &  & \n     \\end{array} \\]\n  \n  \n  $f (n)$ is in $\\mathbb{Z}$ by definition. Claim $f$ is 1-1 and onto:\n  \n  1-1: Suppose $f (n) = f (n')$, then\n  \n  \n  \n  onto: Suppose $b \\in \\mathbb{Z}$, then\n  \n  \\\n  \n  for some $n \\in \\mathbb{N}$, $f (n) = b$.\n  \n  As we have exhibited a $1 - 1$ onto function $f : \\mathbb{N} \\rightarrow\n  \\mathbb{Q}$, $| \\mathbb{N} | = | \\mathbb{Q} |$.\n\\end{proof}\n\n\\end{document}\n", "meta": {"hexsha": "187fa7b8905904b3e576afc70293b7d2746bb8f9", "size": 8594, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/topology.tex", "max_stars_repo_name": "maiar/maiar.github.io", "max_stars_repo_head_hexsha": "709f6bff588a1fba71dd31274e9028a44c95b953", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tex/topology.tex", "max_issues_repo_name": "maiar/maiar.github.io", "max_issues_repo_head_hexsha": "709f6bff588a1fba71dd31274e9028a44c95b953", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/topology.tex", "max_forks_repo_name": "maiar/maiar.github.io", "max_forks_repo_head_hexsha": "709f6bff588a1fba71dd31274e9028a44c95b953", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2213114754, "max_line_length": 88, "alphanum_fraction": 0.5663253433, "num_tokens": 3460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.33647346925681115}}
{"text": "% !TeX spellcheck = en_US\r\n\\documentclass{yLectureNote}\r\n\r\n\\title{Analyse I}\r\n\\subtitle{subtitle}\r\n\\author{Harvey Sheppard}\r\n\\date{Fall Semester 2016}\r\n\\yLanguage{English}\r\n\r\n\\professor{M. Professor}\r\n\r\n\r\n\\usepackage{lipsum}\r\n\r\n\\begin{document}\r\n\t\\titleOne\r\n\t\r\n\t\\yTableOfContent\r\n\t\r\n\t\r\n\t\r\n\t\\chapter{Mathematical Argumentation and Proofs}\r\n\t\\printMarginPartialToc\r\n\t\r\n\t\r\n\t\\section{Mathematical Argumentation}\r\n\t\\classDate{13}{9}{2016}\r\n\t\\nextSerie\r\n\t\r\n\t\\lipsum[1]\r\n\t\r\n\t\\marginTips*{Don't remember to practice your math! It is the only way to get through!}\r\n\t\r\n\t\r\n\t\\subsection{Using Conditions}\r\n\t\\lipsum[2]\r\n\t\\marginCritical*{I should reread this part, as I didn't understood it well... Maybe it's because it's in Latin?}\r\n\t\r\n\t\\lipsum[3]\\marginElement{\\marginTitle{Title} \\lipsum*[7]}\r\n\t\r\n\t\\checkInfo{Yeaaaah!}{\\lipsum[4]\\lipsum[2]}\r\n\t\r\n\t\r\n\t\\section{Mathematical Proofs}\r\n\t\\begin{theorem}[Pythagoras]\r\n\t\tAssuming we have a rectangle triangle with the hypotenuse named c. Then:\r\n\t\t\\[\r\n\t\t\ta^2 + b^2 = c^2\r\n\t\t\\]\r\n\t\\end{theorem}\r\n\t\r\n\t\r\n\t\\marginInfo*{This formula is really important:\r\n\t\t\\begin{equation}\r\n\t\ta^2 + b^2 = c^2\r\n\t\t\\end{equation}\r\n\t}\r\n\t\r\n\t\\yOrnament\t\r\n\\end{document}", "meta": {"hexsha": "1527892eda79d5bcb1aade236700879818aca129", "size": 1172, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "examples/yLectureNote/yLectureNoteShowcase.tex", "max_stars_repo_name": "MarcinKlejna/yLaTeX", "max_stars_repo_head_hexsha": "bdca18907abc49ea51b9d33de20f4c9c9769eff7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 227, "max_stars_repo_stars_event_min_datetime": "2016-09-05T20:29:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:27:53.000Z", "max_issues_repo_path": "examples/yLectureNote/yLectureNoteShowcase.tex", "max_issues_repo_name": "MarcinKlejna/yLaTeX", "max_issues_repo_head_hexsha": "bdca18907abc49ea51b9d33de20f4c9c9769eff7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 24, "max_issues_repo_issues_event_min_datetime": "2017-02-08T03:02:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T10:28:15.000Z", "max_forks_repo_path": "examples/yLectureNote/yLectureNoteShowcase.tex", "max_forks_repo_name": "MarcinKlejna/yLaTeX", "max_forks_repo_head_hexsha": "bdca18907abc49ea51b9d33de20f4c9c9769eff7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 65, "max_forks_repo_forks_event_min_datetime": "2016-11-17T01:01:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T17:27:24.000Z", "avg_line_length": 19.5333333333, "max_line_length": 114, "alphanum_fraction": 0.6740614334, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.33647346558076263}}
{"text": "\\appendix\n\n\\section{Appendix: The \\texttt{VPINN\\_HelmholtzImpedanceRF} Network}\n\\label{app:deeprf}\n\\autoref{lst:deeprf} includes the code implementation of the proposed network on top of the parent class. In this architecture, we use a local version of ReLU as the activation function of the first hidden layer, and a sinusoidal (hyperbolic tangent) activation function for other hidden layers. The idea is to impose different behaviors for different regions of the domain. \\autoref{fig:deeprftrain} shows that without any other consideration, training such a network fails. The solution of the failed training is shown in \\autoref{fig:deeprfsol}. Some other similar architectures have been tried out, which also failed. Among those were putting the ReLU activation function only on the last layer, and non-local ReLU activation functions on the first two layers.\n\n\\begin{figure}[h!]\n    \\centering\n    \\includegraphics[width = 0.48\\textwidth]{img/DeepRF-D004N012K038-training.png}\n    \\caption{Training loss and solution error of the \\texttt{VPINN\\_HelmholtzImpedanceRF} network with 4 hidden layers for wave number $k=8.0$.}\n    \\label{fig:deeprftrain}\n\\end{figure}\n\n\\begin{figure}[h!]\n    \\centering\n    \\includegraphics[width = 0.7\\textwidth]{img/DeepRF-D004N012K038-sol.png}\n    \\caption{The solution of the \\texttt{VPINN\\_HelmholtzImpedanceRF} network with 4 hidden layers for wave number $k=8.0$.}\n    \\label{fig:deeprfsol}\n\\end{figure}\n\n\\lstinputlisting[\n    language=Python,\n    style=pythonstyle,\n    label={lst:deeprf},\n    caption={Code snippet of the \\texttt{VPINN\\_HelmholtzImpedanceRF} class which inherits from the main \\texttt{VPINN\\_HelmholtzImpedance} class.}\n    ]\n{lst/VPINN-HelmholtzImpedanceRF.py}\n\n\\section{Appendix: Evolution of the Solution}\n\\label{app:evolutions}\n\\autoref{fig:evolutionrandinitsol} illustrates the evolution of the solution of a network architecture that converges to the solution in 30000 epochs. We can see that from the initial random initialization, the network is able to capture the main features of the solution in 2000 epochs, and converges to the final solution in the following 28000 epochs. An interesting observation is that there is a bias from left to right which could also be captured in the initial result of the network (epoch 0). We can see that the solution converges faster in the ranges closer to the left boundary.\n\nThe same bias to the left boundary could also be observed in \\autoref{fig:evolutionlsinitsol} which illustrates the evolution of solution of the same network with least-squares initialization in the initial 2000 epochs. In \\autoref{fig:vpinnslsinitk8}, we can see that the solution error of this network does not improve much with least-square initialization after around epoch 2000. Another observation is that the most of the error comes from the imaginary part of the solution, which is not the case with random initialization.\n\n\\begin{figure}[h!]\n    \\centering\n    \\begin{subfigure}[b]{0.85\\textwidth}\n        \\includegraphics[width=\\textwidth]{img/evolution_randinit/sol-00000.png}\n    \\end{subfigure}\n    \\vfill\n    \\begin{subfigure}[b]{0.85\\textwidth}\n        \\includegraphics[width=\\textwidth]{img/evolution_randinit/sol-02000.png}\n    \\end{subfigure}\n    \\vfill\n    \\begin{subfigure}[b]{0.85\\textwidth}\n        \\includegraphics[width=\\textwidth]{img/evolution_randinit/sol-04000.png}\n    \\end{subfigure}\n    \\vfill\n    \\begin{subfigure}[b]{0.85\\textwidth}\n        \\includegraphics[width=\\textwidth]{img/evolution_randinit/sol-08000.png}\n    \\end{subfigure}\n    \\vfill\n    \\begin{subfigure}[b]{0.85\\textwidth}\n        \\includegraphics[width=\\textwidth]{img/evolution_randinit/sol-08000.png}\n    \\end{subfigure}\n    \\vfill\n    \\begin{subfigure}[b]{0.85\\textwidth}\n        \\includegraphics[width=\\textwidth]{img/evolution_randinit/sol-16000.png}\n    \\end{subfigure}\n    \\vfill\n    \\begin{subfigure}[b]{0.85\\textwidth}\n        \\includegraphics[width=\\textwidth]{img/evolution_randinit/sol-30000.png}\n    \\end{subfigure}\n    \\caption{The evolution of the solution during the training of a shallow network with 20 nodes and 20 test functions for $k=8.0$.}\n    \\label{fig:evolutionrandinitsol}\n\\end{figure}\n\n\\begin{figure}[h!]\n    \\centering\n    \\begin{subfigure}[b]{0.85\\textwidth}\n        \\includegraphics[width=\\textwidth]{img/evolution_lsinit/sol-00000.png}\n    \\end{subfigure}\n    \\vfill\n    \\begin{subfigure}[b]{0.85\\textwidth}\n        \\includegraphics[width=\\textwidth]{img/evolution_lsinit/sol-00350.png}\n    \\end{subfigure}\n    \\vfill\n    \\begin{subfigure}[b]{0.85\\textwidth}\n        \\includegraphics[width=\\textwidth]{img/evolution_lsinit/sol-00700.png}\n    \\end{subfigure}\n    \\vfill\n    \\begin{subfigure}[b]{0.85\\textwidth}\n        \\includegraphics[width=\\textwidth]{img/evolution_lsinit/sol-01400.png}\n    \\end{subfigure}\n    \\vfill\n    \\begin{subfigure}[b]{0.85\\textwidth}\n        \\includegraphics[width=\\textwidth]{img/evolution_lsinit/sol-02000.png}\n    \\end{subfigure}\n    \\caption{The evolution of the solution during the training of a shallow network with 20 nodes and 20 test functions with least-squares initialization (constant weights) for $k=8.0$.}\n    \\label{fig:evolutionlsinitsol}\n\\end{figure}", "meta": {"hexsha": "62846fe5d65079ba8f3986b5112bd97653c32f65", "size": 5206, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/appendices.tex", "max_stars_repo_name": "sepeehr/VPINN_Helmholtz", "max_stars_repo_head_hexsha": "97757df978ced16b8df4169ee3de056edc8b9065", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tex/appendices.tex", "max_issues_repo_name": "sepeehr/VPINN_Helmholtz", "max_issues_repo_head_hexsha": "97757df978ced16b8df4169ee3de056edc8b9065", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/appendices.tex", "max_forks_repo_name": "sepeehr/VPINN_Helmholtz", "max_forks_repo_head_hexsha": "97757df978ced16b8df4169ee3de056edc8b9065", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-25T08:56:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T08:56:26.000Z", "avg_line_length": 57.2087912088, "max_line_length": 764, "alphanum_fraction": 0.7512485594, "num_tokens": 1503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.33629199743303334}}
{"text": "%=================================================================\n\\section{GPU Testbed and Selected CUDA kernels} \\label{sec:methodChar}\nSeveral different benchmarks have been proposed in the literature to measure and assess existing GPGPU heterogeneous architectures, such as Rodinia~\\citep{Rodinia:Che:2009}, Parboil~\\citep{Stratton:2012:Parboil} and SHOC~\\citep{Danalis:2010:SHOC}. Rodinia benchmark was devised for heterogeneous parallel computing research, it has had a high level of acceptance in the community and its applications represent different high-level domains or behaviours,  called the Berkeley dwarfs~\\cite{asanovic2009dwarfs}. In this work, we have selected  a set of GPU Applications from the Rodinia Benchmark suite and  other classical algorithms of linear algebra. First to all, we present in the next subsection the different GPUs that we used for our experiments. After in Subsection~\\ref{ssec:useCases}, we characterize each one of the kernel that we used for our experiments.\n\n%For each application we iterated over the values of one or two parameters, with some applications invoking the same kernel multiple times on each execution. During our evaluation, all applications were executed using the CUDA profiling tool \\textit{nvprof}. Each experiment is presented as the average of ten executions, with a confidence interval of 95\\%. In this section we describe the GPU applications, GPU testbed used to do this work.\n\n%---------------------------------------------------------------------------\n\n\\subsection{GPU Testbed}\\label{ssec:GPUTestbed}\nFor our experiments in the Chapter~\\ref{chap:BSPmodel} and Chapter~\\ref{Chap:ML} we used 9 different GPUs, described in Table~\\ref{tab:GPUs}, with 5 belonging to Kepler architecture (Compute Capability 3.X), 3 to Maxwell (C.C. 5.X) and 1 to Pascal (C.C. 6.x). More information about these GPUs are presented in Table~\\ref{tab:CC} and we have described the main changes of hardware and software between architectures in Section~\\ref{ssec:GPUroadmap}. \n\n%Experiments with the Tesla Pascal P-100 were performed accessing the Free OpenPOWER Cloud by Unicamp, running in an IBM OpenPOWER Server configured with 16 physical cores, up to 128 simultaneous treads or vcpus, and 2 x NVIDIA GPU Tesla-P100, connected via NVLINK 1.0. \n\n% \\todoRaph{You described where the Pascal experiments were performed. And the other boards? \\textbf{Corrected - That was question of acknowledge}}\n\n\\begin{table}[htpb]\n    \\centering\n    \\scalebox{0.75}{\n    \\begin{tabular}{lccccccc}\n        \\toprule\n        \\textbf{Model}&\\textbf{C.C.}&\\textbf{Memory}&\\textbf{Bus}&\\textbf{Bandwidth}&\\textbf{L2}&\\textbf{Cores/SM}&\\textbf{Clock} \\\\ \\bottomrule\n        GTX-680&3.0&2 GB&256-bit&192.2 GB/s&0.5 M&1536/8&1058 Mhz \\\\ \\midrule \n        Tesla-K40&3.5&12 GB&384-bit&276.5 GB/s&1.5 MB&2880/15&745 Mhz \\\\ \\midrule\n        Tesla-K20&3.5&4 GB&320-bit&200 GB/s&1 MB&2496/13&706 MHz\\\\ \\midrule\n        %Titan Black&3.5&6 GB&384-bit&336 GB/s&1.5 MB&2880/15 &980 Mhz \\\\ \\midrule\n        Titan&3.5&6 GB&384-bit&288.4 GB/s&1.5 MB&2688/14&876 Mhz\\\\ \\midrule\n        Quadro K5200&3.5&8 GB&256-bit&192.2 Gb/s&1 MB&2304/12&771 Mhz \\\\ \\midrule\n        Titan X&5.2&12 GB&384-bit&336.5 GB/s&3 MB&3072/24&1076 Mhz \\\\ \\midrule\n        GTX-970&5.2&4 GB&256-bit&224.3 GB/s&1.75 MB&1664/13&1279 Mhz\\\\ \\midrule\n        GTX-980&5.2&4 GB&256-bit&224.3 GB/s&2 MB&2048/16&1216 Mhz \\\\ \\midrule\n        Pascal-P100&6.0 GB&16 GB&4096-bit&732 GB/s&4 MB&3584/56&1328 Mhz\\\\ \\midrule\n    \\end{tabular}}\n    \\caption{Hardware specifications of the GPUs in the testbed}\n    \\label{tab:GPUs}\n\\end{table}\n\n\\subsection{Selected CUDA kernels}\\label{ssec:useCases}\nThe  source code for all the use cases, experiments and results are available\\footnote{Hosted at GitHub: \\texttt{\\scriptsize https://github.com/marcosamaris/gpuperfpredict} [Accessed on March 2018]} under Creative Commons Public License for the sake of reproducibility. \n\nOur benchmark contains 4 different strategies for \\emph{matrix multiplication}~\\citep{CUDAGuide}, 2 algorithms for \\emph{matrix addition}, 1 dot product algorithm, 1 vector addition algorithm and 1 \\emph{maximum sub-array problem} algorithm~\\citep{Cleber:Thesis}, and 11 CUDA kernel functions belonging to 6 applications from Rodinia benchmarking suite (see Table~\\ref{tab:Rodinia}). The remainder of this section discusses some details of these algorithms, and introduces a code of letters for each application, used in Chapter~\\ref{chap:BSPmodel} and Chapter~\\ref{Chap:ML}.\n\n\\subsubsection{Matrix Multiplication}\nMatrix multiplication is the core of many scientific areas. This operation is highly used in areas like deep learning, visual computing and digital images processing, among others. The analysis and modeling of these algorithms brings a better understanding and help to researcher and developer of Job Management Systems to deal with this mathematical operations.\n\nIn this research, we used four different versions of matrix multiplication, these versions differ in memory access optimizations: global memory with non-coalesced accesses (MMGU); global memory with coalesced accesses (MMGC); shared memory with non-coalesced accesses (MMSU); and shared memory with coalesced accesses (MMSC). This algorithm has a high utilization of the Streaming Processors and it obtains a high throughput of communication in the different levels of memory, L2 cache and L1 cache for small matrices. We have adopted \\texttt{block\\_size}$^2$ threads per block and defined the number of blocks to be square of \\texttt{(N + block\\_size-1)/block\\_size}, dynamically devised from the size of the problem ($N$) and the block size. Aiming to take advance of coalesced accesses the value of \\texttt{block\\_size} is equal to 16 in our experiments. In Section~\\ref{sec:characterization} is presented an communication analysis of this application with different sizes of threads per block.\n\nThe asymptotic computational complexity of a square matrix multiplication of size $N$ is $O(N^3)$ in a sequential algorithm, in a CUDA algorithm this complexity is $O(N)$ using $N\\times{}N$ threads. In this algorithm each thread requests $N$ elements from both matrices and perform a dot product with these arrays. This CUDA kernel performs $N$ reads from global memory for each matrix and $N$ arithmetic operations. A single write instruction is performed. shared memory is not used in two versions, MMGU and MMGC. In Figure~\\ref{fig:matMulGMUN} is shown the source code of the kernel MMGU, we only changed the data access pattern, to permit coalesced accesses to data in global memory. In Figure \\ref{fig:matMulGMUN} line 7 is changed to \\texttt{Pvalue += A\\_d[i * N + k] * B\\_d[k * N + j];} and line 10 is changed to \\texttt{C\\_d[i * Width + j] = Pvalue;}.\n\n\\lstset{emph={[2]__global__}, emphstyle={[2]\\color{red}\\bf },language=C++, keywordstyle=\\color{blue}, numbers=left, showspaces=false,\n    showstringspaces=false, tabsize=1, breaklines=false,stringstyle=\\color{red}, commentstyle=\\color{red}, morecomment=[l][\\color{magenta}]{\\#}}\n\n\\begin{figure}[htpb]\n\\centering\n{\\scriptsize\n\\begin{lstlisting}\n__global__ void matMul(float* C_d, float* A_d, float* B_d, int N) {\n  float Pvalue = 0.0;\n  int j = blockIdx.x * blockDim.x + threadIdx.x;\n  int i = blockIdx.y * blockDim.y + threadIdx.y;\n\n  for (int k = 0; k < N; ++k) \n    Pvalue += A_d[j * N + k] * B_d[k * N + i];\n  \n  C_d[j * N + i] = Pvalue;\n}\n\n\\end{lstlisting}}\n\\caption{Kernel in CUDA of matrix multiplication only with global memory and uncoalesced accesses (MMGU).}\n\\label{fig:matMulGMUN}\n\\end{figure}\n\nThe version MMSU and MMSC use shared memory to load data from global memory and to process them with a lower latency of communication. As shared memory is limited in GPU architectures, the implementations of matrix multiplication with shared memory must be tiled. The concept of tiling in shared memory is graphically described with Figure~\\ref{fig:TilingMMSU}, with the matrix multiplication. Tiling is a common strategy to partition data into subset called tiles such that each tile fits into the shared memory. This technique splits our problem domain into phases. The tiled process is executed to guarantee that each thread can access data in shared memory to perform its part of the matrix multiplication. \n\nIn process shown in Figure~\\ref{fig:TilingMMSU}, a tile process charges a subset from matrix A and Matrix B in the shared memory of the GPU. A barrier synchronization is used to guarantee that all data was loaded in the shared memory, after the calculations are performed, the barrier synchronization guarantees that the shared memory can be safely overwritten. In this application \\texttt{tile\\_size=block\\_size}, consequently the sizes in bytes of both subsets of the matrices will be \\texttt{(tile\\_size)$^2 \\times$FP\\_Bytes}, where \\texttt{FP\\_Bytes} is the size of the single precision used for the application. \n\n\\begin{figure}[htpb]\n\t\\centering\n    \\includegraphics[scale=.3]{images/square-tiling.png}\n    \\caption{Tiling technique of the Matrix multiplication using shared memory}\n    \\label{fig:TilingMMSU}\n\\end{figure}\n\n\\subsubsection{Matrix Addition}\nFor the Matrix addition algorithm, we used two different memory access optimizations: global memory with non-coalesced accesses (MAU); and global memory with coalesced accesses (MAC);  The run-time complexity for a sequential matrix addition algorithm using two matrices of size $N\\times{}N$ is $O(N^2)$. In a CUDA implementation, the run-time complexity of the matrix addition is $O(1)$ using $N^2$ threads. In this algorithm each thread request $1$ element from each one of the matrix elements and perform a single addition. The implementation of this kernel is similar than matrix multiplication. In Figure \\ref{fig:matMulGMUN} the loop of the line 6-7 is deleted and the statement with the addition is added \\texttt{C[tid] = A[tid] + B[tid];}, where \\texttt{tid} = \\texttt{int tid = i*N + j;}. To take advances of coalesced accesses, \\texttt{tid} is changed to \\texttt{int tid = j*N + i;}. \n\nMatrix addition has the same threads hierarchy than matrix multiplication. The blocks are bi-dimensional with \\texttt{block\\_size}$^2$ threads per block. The size of the grid is square of \\texttt{N/block\\_size}, dynamically devised from the size of the problem \\texttt{N} and \\texttt{block\\_size}.\n\n\\subsubsection{Vector Addition Algorithm (vAdd)}\nFor two vectors $A$ and $B$, the Vector Addition $C = A + B$ is obtained by adding the corresponding components. In a CUDA implementation, the run-time complexity of the vector addition algorithm is $O(1)$ using N threads, so each threads perform an addition of a position of the vectors $A$ and $B$ and stores the result in the vector $C$. This algorithm is a simplified version of the matrix addition. This application has an uni-dimensional block, the block size used for the experiments is $256$ and the size of the grid is also uni-dimensional and dynamically devised from the size of the problem  \\texttt{N} and \\texttt{block\\_size}. The source code of this kernel is similar than matrix addition, only change the dimension indexes of each threads, i.e. \\texttt{int tid = blockDim.x * blockIdx.x + threadIdx.x;}, using only the dimension $x$ of \\texttt{blockDim}.\n\n\\subsubsection{Dot Product Algorithm (dotP)}\nFor two vectors $A$ and $B$, the dot product $C = A \\cdot B$ is obtained by adding the multiplication of corresponding components of the input, the result of this operation is a scalar. Unlike vector addition, dot product is a reduction from vectors to a scalar. In a GPU algorithm, each thread performs a multiplication of a position of the vectors $A$ and $B$ and stores the result shared variable. Then a reduction using the shared memory is performed and finally a vector with size equal to \\texttt{N/block\\_size} is transferred to the CPU memory for later processing. The block size used for the experiments is $256$ and the size of the grid is also uni-dimensional and dynamically devised from the size of the problem  \\texttt{N} and \\texttt{block\\_size}.\n\n\\subsubsection{Maximum Sub-Array Problem (MSA)}\nLet $X$ be a sequence of $N$ integer numbers $(x_1, ... , x_N)$. The Maximum Sub-Array Problem (MSA) consists of finding the contiguous sub-array within $X$ which has the largest sum of elements. The solution for this problem is frequently used in computational biology for gene identification, analysis of sequence of protein and DNAs, identification of hydrophobic regions, among others. The implementation used in this paper creates a kernel with 4096 threads, divided in 32 blocks with 128 threads~\\citep{Cleber:Thesis}. The $N$ elements are divided in intervals of $N/t$, and each block receives a portion of the array. The blocks use the shared memory for storing segments, which are read from the global memory using coalesced accesses. Each interval is reduced to a set of 5 integer variables, which are stored in vector of size $5 \\times t$ in global memory. This vector is then transferred to the CPU memory for later processing. \n\nA summary of each one of these applications is shown in Table~\\ref{tab:useCases}, in this table is shown the thread hierarchy and the request shared memory per block in each kernel. In column \\texttt{dimGrid} and \\texttt{dimBlock} is shown how each solution is associated to the dimension of the problem. Column Shared Mem shows the size of shared memory that each kernel needs per block.\n\n\\begin{table}[htpb]\n    \\centering \n    \\scalebox{.9}{\n        \\begin{tabular}{cccccc} \n            \\midrule\\midrule\n            \\textbf{Application} & \\textbf{Param} & \\textbf{Kernel}& \\textbf{\\texttt{dimGrid}}&  \\textbf{\\texttt{dimBlock}}&\\textbf{Shared Mem}\\\\\\midrule\\midrule   \n            \\multirow{4}{*}{Matrix Mul} & \\multirow{4}{*}{1} &MMGU &\\multirow{4}{*}{(GS, GS, 1)}&\\multirow{4}{*}{ (BS, BS, 1)}&\\multirow{4}{*}{($BS^2\\times{}2\\times{}4B$)}\\\\      \n            &  &MMGC & & &\\\\\n            &  &MMSU & & &\\\\   \n            &  &MMSC & & &\\\\\\midrule     \n            \\multirow{2}{*}{Matrix Add} & \\multirow{2}{*}{1} &MAU &\\multirow{2}{*}{(GS, GS, 1)}&\\multirow{2}{*}{ (BS, BS, 1)}&\\multirow{2}{*}{0}\\\\ \n            &  &MAC & & & \\\\\\midrule \n            Vector Add&1  &VAdd &(GS, 1, 1) &(BS, 1, 1)& 0 \\\\\\midrule\n            Dot Product&1  &dotP &(GS, 1, 1) &(BS, 1, 1) &($BS\\times{}4B$)\\\\\\midrule\n            Max. Sub Array&1  &MSA & (48, 1, 1) &(128, 1, 1)&($4096\\times{}4B$)\\\\\\midrule\n        \\end{tabular}}\n    \\caption{Key linear algebra applications used in the experiments}\n    \\label{tab:useCases} \n\\end{table}\n\n\\subsubsection{Rodinia Benchmark Suite}\nWe selected 11 CUDA kernel functions belonging to 6 applications from Rodinia for the benchmarks (Table~\\ref{tab:Rodinia}). Some applications invoke the same kernel multiple times on each execution, resulting in the number of collected samples shown in the last column. For each kernel we iterated over the values of one or two parameters, with the number of iterations indicated inside the brackets. For instance, the Hot Spot application has 2 parameters, with the first iterated among 5 values and the second 4 values, for a total of 20 executions in each machine. %In those applications only some part of them can be compute concurrently, above we will explain the performance behavior of each one of the selected Rodinia benchmarks kernels.\n\n\\begin{table*}[htpb]\n    \\centering \n    \\scalebox{.8}{\n        \\begin{tabular}{cccccc} \n            \\midrule\\midrule\n            \\textbf{Application} & \\textbf{Berkeley Dwarf} & \\textbf{Domain}& \\textbf{Param.}& \\textbf{Kernels} & \\textbf{Samples}\\\\\\midrule\\midrule   \n            \\multirow{2}{*}{Back Propagation (BCK)} & \\multirow{2}{*}{Unstructured Grid} & \\multirow{2}{*}{Pattern Recognition} &\\multirow{2}{*}{1 - [57]}&layerforward&\\multirow{2}{*}{57}\\\\\n            &  &  & &adjust-weights  \\\\\\midrule      \n            \\multirow{2}{*}{Gaussian Elimination (GAU)} & \\multirow{2}{*}{Dense Linear Algebra} & \\multirow{2}{*}{Linear Algebra} &\\multirow{2}{*}{1 - [32]}& Fan1&\\multirow{2}{*}{34800}  \\\\             \n            &  &  & & Fan2  \\\\\\midrule\n            Heart Wall (HWL) & Structured Grid & Medical Imaging &1 - [84]& heartWall&5270 \\\\\\midrule\n            Hot Spot (HOT) & Structured Grid & Physics Simulation &2 - [5,4]& calculate-temp&396288 \\\\\\midrule            \n            % Hot Spot 3D (H3D) & Structured Grid & Physics Simulation &2 - [3,10]& hotspotOpt1&150150 \\\\\\midrule                     \n            %LavaMD (LMD) & N-Body & Molecular Dynamics &1 - [50]& LavaMD&50\\\\\\midrule\n            \\multirow{3}{*}{LU Decomposition (LUD)} & \\multirow{3}{*}{Dense Linear Algebra} & \\multirow{3}{*}{Linear Algebra} &\\multirow{3}{*}{1 - [32]}&diagonal&8448 \\\\\n            & & &  & perimeter&8416 \\\\\n        &  &  & & internal&8416 \\\\\\midrule            \n            \\multirow{2}{*}{Needleman-Wunsch (NDL)} & \\multirow{2}{*}{Dynamic Programming} & \\multirow{2}{*}{Bioinformatics} &\\multirow{2}{*}{2 - [16,10]}& needle-1&21760 \\\\\n             &  &  & & needle-2&21600 \\\\\\midrule\n            \n        \\end{tabular}}\n    \\caption{Rodinia applications used in the experiments}\n    \\label{tab:Rodinia} \n\\end{table*}\n\n\\begin{itemize}\n    \\item {\\bf Back Propagation (BCK):}\nBCK trains a layered neural network. The application is comprised of two kernels: Forward Phase (BCK-K1), in which the activation are propagated from the input to the output layer, and Backward Phase (BCK-K2), in which the error between the observed and requested values in the output layer is propagated backwards to adjust the weights and bias values. The time complexity of a back-propagation neural network algorithm on a single processor is of $O(W^3)$; where $W$ is the count of weights in the network. In this CUDA implementation both kernels have a complexity $O(log(BS))$ where $BS=16$. Each block has \\texttt{BLOCK\\_SIZE}$^2$ number of threads. The number of blocks in the grid is \\texttt{(N/block\\_size} nad it is dynamically calculated from the layer size ($N$) and the block size.\n\nIn kernel (BCK-K1), only one thread (with id 0) in the each block load an element of the input layer on the shared memory, after each thread load an element of the weight matrix on the shared memory. Then, the weight matrix is updated with the values of the input layer. Finally a loop reduction is done with a loop of size log2(block\\_size). Inside this loop, log2(block\\_size) power instructions are done and log2(block\\_size) additions over data in the shared memory. Each interval is reduced to a set of \\texttt{grid\\_size}$\\times$\\texttt{block\\_size} integer variables. This vector is then transferred to the main memory of the host for later processing. In kernel (BCK-K2), shared memory is not used. According to the source code of (BCK-K2), each thread performs O(1) reads and write in the global memory and does different computations over this data.\n\n\\item{\\bf Gaussian Elimination (GAU):}\nGAU solves a linear system $Ax = b$, the application analyzes an $n\\times{}n$ matrix and an associated $1 x n$ vector to solve a \nset of equations with $n$ variables and $n$ unknowns. Gaussian Elimination algorithms has a complexity $O(n^3)$. This application compute the results row by row. The algorithm synchronizes between iterations, but the values calculated in each iteration is computed in parallel, see Figure~\\ref{fig:GauCode}.\n\n, where $n$ is the size of the matrix elements in both dimensions, i.e. the matrix is $n\\times{}n$. \n\n\nThe application has two different kernels Fan1 and Fan2, which we call (GAU-K1) and (GAU-K2) respectively. (GAU-1) calculate multiplier matrix and (GAU-2) modify the matrix A into LUD. In the experiments, we varied the size of the matrix. \n\nIn this implementation, First kernel GAU-K1, has a uni-dimensionmal block, each block \\texttt{block\\_size = 512} threads and the number of block is dynamic and computed with the next expression \\texttt{(N/block\\_size)}. Second kernel has a bi-dimensional block, its dimension is \\texttt{block\\_size}$^2$ and \\texttt{block\\_size = 4} in this implementation. The size of the grid also is dynamic depending to size of the problem $N$and the $BS$ (Block size), and it is computed as \\texttt{(N/block\\_size)}. Both kernel are iterative, it means that the same kernels are invoked multiple times on a single execution of the whole application. Any of these kernel use the shared memory of the streaming processors. \n\n\\lstset{emph={[2]__global__}, emphstyle={[2]\\color{red}\\bf },language=C++, keywordstyle=\\color{blue}, numbers=left, showspaces=false,\n    showstringspaces=false, tabsize=1, breaklines=false,stringstyle=\\color{red}, commentstyle=\\color{red}, morecomment=[l][\\color{magenta}]{\\#}}\n\n\\begin{figure}[htpb]\n\\centering\n{\\scriptsize\n\\begin{lstlisting}\nfor (t=0; t<(Size-1); t++) {\n\t\tFan1<<<dimGrid1,dimBlock1>>>(m_cuda,a_cuda,Size,t);\n\t\tcudaThreadSynchronize();\n\t\tFan2<<<dimGrid2,dimBlock2>>>(m_cuda,a_cuda,b_cuda,Size,t);\n\t\tcudaThreadSynchronize();\n\t}\n\\end{lstlisting}}\n\\caption{Kernel in CUDA of matrix multiplication only with global memory and uncoalesced accesses (MMGU).}\n\\label{fig:GauCode}\n\\end{figure}\n\n\\item {\\bf Heart Wall (HWL):}\nHWL tracks the movement of a mouse heart over a sequence of 104 609x590 ultrasound images to record response to the stimulus. In the experiments, we varied the number of frames to process. This kernel has two different stages, in the first stage the kernel performs operations on the first frame to detect initial, partial shapes of inner and outer heart walls in the second stage the kernel presents multiple nested loops that process batches of 10 frames and 51 points in each image. This kernel is very complicated to analyze, i.e. this kernel has 1300 codes lines more or less, it uses 8 variables in the shared memory and 44 variables to store all its computations in each streaming multiprocessor, obtaining a low latency in this process. it runs multiple times depending the number of frame to compute. As the number of threads in a block as the number of blocks in a thread ar uni-dimensionals. For all the experiments, this kernels has a \\texttt{block\\_size}$= 256$ and a \\texttt{grid\\_size}$ = 51$. For a total of 13056 threads in each one of the executions. This application modeled a set of  ordinary differential equations (ODEs) that are determined by more than 200 parameters. HWL requires the inclusion of some non-parallel computation into the kernel, leading to a slight warp under-utilization.\n\n% \\todoRaph{Describe something about the computations performed in the HWL kernel/application.}\n\n\\item {\\bf HotSpot (HOT):}\nHOT is a tool to estimate processor temperature based on an architectural floor plan and simulated power measurements. This application includes the 2D transient thermal simulation kernel which iteratively solves a series of differential equations to determine block temperatures. This kernel has a bi-dimensional grid and block. The dimension of the block is square of \\texttt{block\\_size} and \\texttt{block\\_size}$ = 16$. The size of the grid is the square of \\texttt{N/block\\_size} and it is dynamic depending the size of the problem and the size of the thread block. In the experiments, we varied two parameters: size of the problem and number of iterations. This application has a single kernel. It uses the shared memory.\n\n\n\n\\item {\\bf LU Decomposition (LUD):}\nthis is a factorization algoritm, where ''LU'' means \\emph{lower upper}, LUD is an algorithm to calculate the solutions of a set of linear equations. The LUD kernel decomposes a matrix as the product of a lower triangular matrix and an upper triangular matrix. This benchmark present tree different kernels (LUD-K1, LUD-K2 and LUD-K3). Similarly to the Gaussian Elimination, the matrix size of this experiment was also iterated. First kernel LUD-K1 (named diagonal) has a static size of threads, the size of threads of this kernels always 16. The second kernel LUD-K2 (named perimeter) has a uni-dimensional block the size of thread per block always is \\texttt{block\\_size}$*2$, the number of block in the grid also is uni-dimensional and it is computed dynamically with the next expression \\texttt{(matrix\\_dim-i)/block\\_size-1}. The third kernel LUD-K3 (named internal) has a block bi-dimensional, this size is the square of \\texttt{block\\_size} and \\texttt{block\\_size}$ = 16$, the grid also is bi-dimensional and it is computed with the same expression than the second kernel, \\texttt{(matrix\\_dim-i)/block\\_size-1}.\n\n\n\\item {\\bf Needleman-Wunsch (NDL):}\nis a nonlinear global optimization method for DNA sequence alignments. The potential pairs of sequences are organized in a 2D matrix. In the first step, the algorithm fills the matrix from top left to bottom right, step-by-step. In the second step, the maximum path is traced backward to deduce the optimal alignment. Needleman-Wunsch has two CUDA kernels, NDL-K1 and NDL-K2. We iterated over the matrix dimension and penalty positive integer parameters. In both kernels each block use $2180$ KB of shared memory. This implementation use a static number of threads per block of 16 and the grid is dynamically computed with this expression $(N-1)/16$. Where $N$ is the size of the input matrix. \n\n\n% \\lstset{language=C++, keywordstyle=\\color{blue}, numbers=left, showspaces=false,\n%     showstringspaces=false, tabsize=1, breaklines=false,stringstyle=\\color{red}, commentstyle=\\color{red}, morecomment=[l][\\color{magenta}]{\\#}}\n\n% \\begin{figure}[htpb]\n% \t\\centering\n%     \\lstset{emph={[2]dim3}, \n%             emphstyle={[2]\\color{red}\\bf},\n%             emph={[3]dimGrid, dimBlock},\n%             emphstyle={[3]\\color{blue}\\bf},\n%             emphstyle={\\bf}, basicstyle={\\ttfamily \\scriptsize},\n%             commentstyle={\\em},\n%             keywordstyle={\\color{blue}\\bf},\n%             numbers=left,\n%             captionpos=b,\n%             xleftmargin=1cm}\n% \t\\begin{lstlisting}[frame=trBL,language=C,linewidth=.92\\linewidth]\n% for( int i = 1 ; i <= block_width ; i++){\n% \t\tneedle_cuda_shared_1<<<dimGrid, dimBlock>>>(referrence_cuda, matrix_cuda\n% \t\t                                      ,max_cols, penalty, i, block_width); \n% \t}\n% \tfor( int i = block_width - 1  ; i >= 1 ; i--){\n% \t\tdimGrid.x = i;\n% \t\tdimGrid.y = 1;\n% \t\tneedle_cuda_shared_2<<<dimGrid, dimBlock>>>(referrence_cuda, matrix_cuda\n% \t\t                                      ,max_cols, penalty, i, block_width); \n% \t}\n\t\n% \t\\end{lstlisting}\n% \\caption{Launched kernel with its respective dimension variables dimBlock and dimGrid}\n% \\label{fig:dimGridBlock}\n% \\end{figure}\n\n\\end{itemize}\n", "meta": {"hexsha": "30cb43927a0f79237f4729943897341f61de704e", "size": 26603, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/thesis/sections/use-cases.tex", "max_stars_repo_name": "marcosamaris/svm-gpuperf", "max_stars_repo_head_hexsha": "35b81711089273c775f143ecaeadae03ebf5910a", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-06-03T18:32:48.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-03T18:32:48.000Z", "max_issues_repo_path": "docs/thesis/sections/use-cases.tex", "max_issues_repo_name": "marcosamaris/svm-gpuperf", "max_issues_repo_head_hexsha": "35b81711089273c775f143ecaeadae03ebf5910a", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/thesis/sections/use-cases.tex", "max_forks_repo_name": "marcosamaris/svm-gpuperf", "max_forks_repo_head_hexsha": "35b81711089273c775f143ecaeadae03ebf5910a", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 114.1759656652, "max_line_length": 1312, "alphanum_fraction": 0.7327744991, "num_tokens": 7015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.33629199743303334}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\chapter{Beyond QED}\n\n\\section{Decay of a heavy vector boson}\n\n\\marginpar{Friday\\\\ 2020-6-19, \\\\ compiled \\\\ \\today}\n\nWe consider a \\textbf{massive real vector field}. The generalization to a complex one is simple. \nThe Lagrangian, describing the massive vector \\(V^{\\mu }\\) and the fermion \\(\\psi \\), is: \n%\n\\begin{align}\n\\mathscr{L} &= - \\frac{1}{4} V^{\\mu \\nu } V_{\\mu \\nu } \n+ \\frac{1}{2} M^2 V^{\\mu } V_{\\mu } \n+ \\overline{\\psi} \\qty(i \\slashed{\\partial} - m) \\psi \n+ \\mathscr{L} _{\\text{int}} \\\\ \n\\mathscr{L} _{\\text{int}} &= \n\\frac{g}{c_{w}} \\overline{\\psi} \\qty(\n    c_L \\gamma^{\\mu } p_L +\n    c_R \\gamma^{\\mu } p_R \n) \\psi V_{\\mu }\n\\,,\n\\end{align}\n%\nwhere as usual the field strength is defined as \\(V^{\\mu \\nu } = 2 \\partial^{[\\mu } V^{\\nu ]}\\), while \\(\\theta_{w}\\) is the Weinberg angle, whose cosine is denoted \\(c_w = \\cos \\theta_{w} \\approx \\num{.88}\\). \n\nIt is experimentally measured that \\(\\sin^2\\theta \\approx \\num{.22}\\). \nOn the other hand, the coupling \\(g\\) is \\(g = e / \\sin \\theta \\approx \\num{.64} \\) in natural units. \n\nThe couplings \\(c_{L, R}\\) depend on the specific particle considered. \n\nThe terms \\(P_L\\) and \\(P_R\\) are the projection operators defined in \\eqref{eq:chirality-projection-operators}: they project onto the left- or right-handed subspaces. \n\n\\subsection{Massive vector diagrams}\n\nIf we have a free field term for the massive vector in which it is incoming we get a factor \\(\\epsilon^{\\mu }_{\\lambda } (p)\\), if the massive vector is outgoing we have its conjugate, \\(\\epsilon^{\\mu *}_{\\lambda } (p)\\). \n\nThe propagator (in momentum space) is given by \n%\n\\begin{align}\n\\widetilde{D}^{\\mu \\nu }_F (q) &=- \n\\frac{i}{q^2 - M^2} \n\\qty(\n    \\eta^{\\mu \\nu } \n    - \\frac{p^{\\mu }p^{\\nu }}{M^2}\n)\n\\,,\n\\end{align}\n%\nwhile for a vertex in which the massive vector interacts with a fermion with \\(\\mathscr{L} _{\\text{int}}\\) we get a term: \n%\n\\begin{align}\n-i \\frac{g}{c_w} \\qty(c_L \\gamma^{\\mu }_{L} + c_R \\gamma^{\\mu }_{R})\n\\,,\n\\end{align}\n%\nwhere the matrices \\(\\gamma^{\\mu }_{L, R}\\) are defined as \\(\\gamma^{\\mu} P_{L, R}\\). \n\nA useful relation is this pseudo-completeness one:\n%\n\\begin{align}\n\\sum _{\\lambda = 1}^{3} \\epsilon^{\\mu }_{\\lambda }(p) \\epsilon^{\\nu }_{\\lambda } (p) &= - \\eta^{\\mu \\nu } + \\frac{p^{\\mu } p^{\\nu }}{M^2}\n\\,.\n\\end{align}\n\nNotice the fact that we have three independent polarizations now, as opposed to the massless vector which has two; the polarizations of the massive vector span the whole spacelike section of spacetime orthogonal to \\(p^{\\mu }\\), whereas the polarizations of the massless vector only span the two-dimensional region which is spacelike \\emph{and} orthogonal to the 3D wavevector \\(\\vec{k}\\). \nThis is also relevant when averaging over polarizations: we will need to divide by \\(3\\). \n\nNow, since we have the Feynman rules we can quickly calculate the Feynman amplitude for the decay \\(V \\to \\overline{f} f\\), which now is permitted: \n%\n\\begin{align}\n\\mathcal{M}_{V \\to \\overline{f}f}\n= -i \\frac{g}{c_w} \\overline{u}_{r} (k)  \n\\qty(c_L \\gamma^{\\mu }_{L} + c_R \\gamma^{\\mu }_{R})\nu_{r'} (k') \\epsilon_{\\mu }^{\\lambda} (p)\n\\,,\n\\end{align}\n%\nand from it we can sum and average to get the unpolarized square amplitude: \n%\n\\begin{align}\n\\abs{\\mathcal{\\overline{M}}}^2 &=\n\\frac{g^2}{c_w^2} \\frac{1}{3} \n\\sum _{\\lambda } \\epsilon_{\\mu }^{\\lambda }(p) \\epsilon_{\\nu }^{\\lambda *}(p) \n\\sum _{r r'} (\\overline{u}_r (\\dots)^{\\mu } v_{r'}  )\n( \\overline{v}_{r'} (\\dots)^{\\nu } u_r )  \\\\\n&= \\frac{1}{3} \\frac{g^2}{c_w^2} \n\\qty(- \\eta_{\\mu\\nu } \\frac{p_{\\mu }p_{\\nu}}{M^2})\n\\Tr[(\\slashed{k} - m)\\qty(c_L \\gamma^{\\mu }_{L} + c_R \\gamma^{\\mu }_{R})\n (\\slashed{k}' + m)\\qty(c_L \\gamma^{\\nu }_{L} + c_R \\gamma^{\\nu }_{R})]\n\\,.\n\\end{align}\n\n\\begin{claim}\nThe trace can be explicitly calculated to give \n%\n\\begin{align}\n\\begin{split}\n&\\Tr[(\\slashed{k} - m)\\qty(c_L \\gamma^{\\mu }_{L} + c_R \\gamma^{\\mu }_{R})\n(\\slashed{k}' + m)\\qty(c_L \\gamma^{\\nu }_{L} + c_R \\gamma^{\\nu }_{R})] = \\\\\n&\\phantom{=}\\ = 2 (c_L^2 + c_R^2) \\qty(k^{\\prime \\nu } k^{\\mu } - \\eta^{\\mu \\nu } \\qty(k \\cdot k') + k^{\\prime \\mu } k^{\\nu })\n- 4 m^2 c_L c_R \\eta^{\\mu \\nu }\n\\end{split}\n\\,.\n\\end{align}\n\\end{claim}\n\n\\begin{proof}\n\\todo[inline]{To do.}\n\\end{proof}\n\nUsing this result, we find \n%\n\\begin{align}\n\\abs{\\mathcal{\\overline{M}}}^2 &= \n\\frac{1}{3} \\frac{g^2}{c_w^2} \\qty(2 (c_L^2 + c_R^2)\n\\qty(k \\cdot k' + 2 \\frac{(p \\cdot k) (p \\cdot k')}{M^2}) \n+ 12 m^2 c_L c_R\n)\n\\,.\n\\end{align}\n\nNow, we can specify the kinematics to the rest frame of the massive vector. Then, we can see that the ``Mandelstam variables'' are given by \\(s = p^2 = M^2\\), \\(t = u = (p-k)^2 = (k')^2 = m^2\\), and that \n%\n\\begin{align}\nk \\cdot k' = \\frac{M^2}{2} - m^2\n&&\np \\cdot k = p \\cdot k' = \\frac{M^2}{2}\n\\,.\n\\end{align}\n\nSo the amplitude reads: \n%\n\\begin{align}\n\\abs{\\mathcal{\\overline{M}}}^2 &= \n\\frac{1}{3} \\frac{g^2}{c_w^2} \\qty(2 (c_L^2 + c_R^2)\n\\qty( \\frac{M^2}{2} - m^2 + 2 \\frac{M^2}{4}) + 12 m^2 c_L c_R )  \\\\\n&= \\frac{g^2}{c_w^2} \\frac{M^2}{3} \n\\qty(2 (c_L^2 + c_R^2) \\qty(1 - \\frac{m^2}{M^2}) + 12 c_L c_R \\frac{m^2}{M^2})\n\\,.\n\\end{align}\n\nIf the vector is very massive compared to the fermion (\\(m \\ll M\\)) then this simplifies heavily: \n%\n\\begin{align}\n\\abs{\\mathcal{\\overline{M}}}^2\n\\overset{m \\ll M}{\\approx}\n\\frac{g^2}{c_w^2} \\frac{M^2}{3} 2 (c_L^2 + c_R^2)\n\\,,\n\\end{align}\n%\nhowever we will not make this assumption.\n\nWe can apply the general formula for the \\textbf{differential decay rate} (in the lab frame): \n%\n\\begin{align}\n\\eval{\\dv{\\overline{\\Gamma} }{\\Omega }}_{\\text{lab}}\n= \\frac{1}{64 \\pi^2} \\frac{1}{M} \n\\sqrt{1- \\frac{4m^2}{M^2}} \\abs{\\mathcal{\\overline{M}}}^2_{\\text{lab}}\n\\,,\n\\end{align}\n%\nbut this does not depend on the angles (as it should: this is the decay of a particle in its frame, it better be isotropic!) we can integrate over the angles, which gives a factor \\(4 \\pi \\), so we get \n%\n\\begin{align}\n\\eval{\\overline{\\Gamma}}_{\\text{lab}}=\n\\frac{g^2}{c_w^2}\n\\frac{M}{48 \\pi } \\sqrt{1 - \\frac{4m^2}{M^2}}\n\\qty(2 (c_L^2 + c_R^2) \\qty(1 - \\frac{m^2}{M^2}) + 12 c_L c_R \\frac{m^2}{M^2})\n\\,,\n\\end{align}\n%\nwhich, in the limit \\(m \\ll M\\), becomes  \n%\n\\begin{align}\n\\eval{\\overline{\\Gamma}}_{\\text{lab}}\n\\overset{m \\ll M}{\\approx}\n\\frac{g^2}{c_w^2}\n\\frac{M}{24 \\pi }\n(c_L^2 + c_R^2)\n\\,.\n\\end{align}\n\nFor example, in the decay \\(Z \\to \\nu \\overline{\\nu}\\) we have \\(c_L = 1/2\\), \\(c_R = 0\\) so the result is \n%\n\\begin{align}\n\\overline{\\Gamma}_{\\text{lab}}\n= \\frac{g^2}{c_w^2} \\frac{M}{96 \\pi }\n\\,.\n\\end{align}\n\nThis is known as the \\emph{invisible decay width} of the \\(Z\\) boson, since it is extremely difficult to detect the neutrino pair generated by the decay, so at a collider one would see a fraction of the \\(Z\\) bosons effectively disappear without a trace.\n\n\\section{Spontaneous Symmetry Breaking} \\label{sec:ssb}\n\n\\subsection{SSB for a discrete symmetry}\n\nConsider the following Lagrangian for a real scalar field \\(\\varphi \\): \n%\n\\begin{align}\n\\mathscr{L} &= \\underbrace{\\frac{1}{2} \\qty( \\partial_{\\mu } \\varphi ) \\qty(\\partial^{\\mu } \\varphi )}_{\\text{kinetic term}}\n\\underbrace{- \\frac{1}{2} m^2 \\varphi^2 - \\frac{\\lambda}{4!} \\varphi^{4} }_{V(\\varphi )}\n\\,.\n\\end{align}\n\nThe potential \\(V(\\varphi )\\) can also be written as \n%\n\\begin{align}\nV(\\varphi ) = \\frac{\\lambda}{4!} \\qty(\\varphi^2 + \\mu^2)^2 + C\n\\,,\n\\end{align}\n%\nwhere \\(\\mu^2 = 6 m^2 / \\lambda \\) and \\(C\\) is an inessential constant (which does not affect the EOM). \n\nThe Lagrangian has a discrete symmetry: \\(\\varphi \\to -\\varphi \\). \n\nThe Hamiltonian for the theory is \n%\n\\begin{align}\n\\mathscr{H} = \\frac{1}{2} \\qty(\\partial_0 \\varphi )^2 + \\frac{1}{2} \\qty(\\nabla \\varphi )^2 + V(\\varphi )\n\\,,\n\\end{align}\n%\nand it is positive definite as long as \\(\\lambda > 0\\), while \\(\\lambda = 0\\) returns us to the free theory. The parameter \\(\\mu \\), instead, is unconstrained.\n\nWe are interested in the study of the \\textbf{ground state} \\(\\varphi_0 \\) of the theory: the field configuration which has the minimum energy. \nWhat are the requirements we must ask in order for it to actually be the ground state? \n\n\\begin{enumerate}\n    \\item It must be stationary: \\(\\partial_{\\mu } \\varphi_0 = 0\\). This corresponds to the kinetic part of the Lagrangian vanishing, so that the kinetic energy of the configuration is zero. \n    \\item The value of the constant \\(\\varphi_0 \\) is determined by minimizing the potential \\(V (\\varphi_0 )\\). \n\\end{enumerate}\n\n\nLet us consider two separate cases. \n\n\\subsubsection{Positive mass: \\(\\mu^2> 0\\)} \n\nIn this case the state \\(\\varphi_0  = 0\\) is a stable minimum: we have \\(V' (\\varphi  = 0) = 0\\) and \\(V'' (\\varphi = 0) > 0\\). \n\nThis is the same vacuum we have in the free theory. \n\n\\subsubsection{Negative mass: \\(\\mu^2 <0\\)}\n\nNow we have \\(V'(\\varphi =0) = 0\\) and \\(V'' (\\varphi=0) < 0\\): the configuration \\(\\varphi_0 = 0\\) is an \\emph{unstable} maximum. \n\nNow, however, we have two new minima at \\(\\varphi = \\pm \\abs{\\mu }^2\\): these are stable.\n\nNow, a perturbation of the ground state will look like \n%\n\\begin{align}\n\\varphi (x) = \\sigma (x) + \\abs{\\mu }\n\\,,\n\\end{align}\n%\nwhere we have arbitrarily chosen the right vacuum: in order to perturb around the vacuum we lose the parity symmetry. \n\nThen, we can express the Lagrangian with respect to this fluctuation: \n%\n\\begin{align}\n\\mathscr{L} = \\frac{1}{2} \\qty(\\partial_{\\mu }\\sigma ) \\qty(\\partial^{\\mu }\\sigma ) - \\frac{1}{2} \\qty(\\frac{\\lambda }{3} \\abs{\\mu }^2)\\sigma^2 - \\frac{\\lambda}{3!} \\abs{\\mu } \\sigma^3 + \\frac{\\lambda}{4!} \\sigma^{4}\n\\,,\n\\end{align}\n%\nwhich appears to have no parity symmetry anymore! \nIn fact the symmetry is still there, but it will have to be expressed in a complicated way in terms of the powers of \\(\\sigma \\). \n\n\\subsection{SSB for a continuous symmetry}\n\nNow we consider the situation in which a continuous global symmetry is spontaneously broken. Consider the following Lagrangian: \n%\n\\begin{align}\n\\mathscr{L} = \\qty(\\partial_{\\mu }\\varphi )^{*} \\qty(\\partial_{\\mu } \\varphi ) \\underbrace{- \\lambda \\qty(\\varphi^{*} \\varphi + \\frac{\\mu^2}{2})^2}_{V(\\varphi )}\n\\,,\n\\end{align}\n%\nwhich is, up to constants, the most general renormalizable theory for a complex scalar.\nNotice that this Lagrangian has a global \\(U(1)\\) symmetry, \\(\\varphi \\to e^{i \\alpha } \\varphi \\). \n\nJust like before, we assume \\(\\lambda > 0\\), which is needed in order for the Hamiltonian to be positive definite (or, equivalently, to have a global minimum for the energy) and discuss separately the cases \\(\\mu^2 \\lessgtr 0\\). \n\n\\subsubsection{\\(\\mu^2 > 0\\): positive mass}\n\nIn this case we have \\(\\partial_{\\varphi } \\eval{V}_{\\varphi =0} = 0\\), so the field configuration \\(\\varphi_0 = 0 \\) is stable. \n\nThe Hessian is positive definite in this case, so this is a minimum. In fact, the potential is globally convex, so it is the global minimum.\n\nIn this case, perturbing around the vacuum as \\(\\varphi (x) = \\varphi_0 + \\sigma (x)\\) does not change the Lagrangian, since \\(\\varphi_0 = 0\\). The symmetry is preserved. \n\n\\subsubsection{\\(\\mu^2 < 0\\): negative mass}\n\nIn this case, solving \\(V' (\\varphi ) = 0\\) yields two classes of solutions: one is \\(\\varphi_0 = 0\\), the other instead is \\(\\varphi^{*}_{0} \\varphi_0 = v^2 / 2\\), where we define \\(v^2 = - \\mu^2 > 0 \\). Notice that this is not a single point, but a whole circle: the condition on \\(\\varphi^{*}_{0} \\varphi_0 \\) has a \\(U(1)\\) symmetry!\n\nThe point \\(\\varphi_0 = 0\\) is a local maximum (the Hessian is negative definite), while the other stationary point can be parametrized as \n%\n\\begin{align}\n\\varphi_0 = e^{i \\alpha } \\frac{v}{\\sqrt{2}}\n\\,,\n\\end{align}\n%\nwhere \\(\\alpha \\) is a real parameter. \n\nNow, it is convenient to express the perturbation around this vacuum as \n%\n\\begin{align}\n\\varphi (x) = \\qty(\\frac{\\sigma (x) + v}{\\sqrt{2}}) e^{i \\pi (x) / v}\n\\,,\n\\end{align}\n%\nwhere \\(\\sigma (x)\\) and \\(\\pi (x)\\) are both real fields.\nThis means that we are choosing a specific vacuum in the continuum of the circle (that at \\(\\alpha = 0\\)) and moving from it; changing \\(\\sigma \\) moves us in the direction of increasing potential, while changing \\(\\pi \\) moves us around the circle. \n\nSubstituting this in, we get \n%\n\\begin{align}\n\\mathscr{L} = \\frac{1}{2} \\qty(\\partial \\sigma )^2 - \\frac{1}{2} \\qty(2 \\lambda v^2) \\sigma^2 - \\lambda v \\sigma^3 - \\frac{\\lambda}{4} \\sigma^{4}\n+ \\frac{1}{2} \\qty(\\partial \\pi )^2 + \\qty(v \\sigma + \\frac{\\sigma^2}{2}) \\qty(\\partial \\pi )^2\n\\,.\n\\end{align}\n\nIn terms of \\(\\sigma \\) and \\(\\pi \\) there is no \\(U(1)\\) symmetry anymore. \n\nIn the unbroken \\(\\mu^2 > 0\\) theory we have one complex scalar of mass \\(m\\), which is equivalent to two real scalars of mass \\(m\\): if we set \\(\\varphi = (\\varphi_1 + i \\varphi_2 ) / \\sqrt{2}\\) we have \n%\n\\begin{align}\n\\mathscr{L} = \\sum _{i=1}^{2}\\qty( \\frac{1}{2} (\\partial \\varphi_{i} )^2 - \\frac{1}{2} m \\varphi_{i}^2 ) - \\frac{\\lambda }{4} \\qty(\\varphi_1^2 + \\varphi_2^2)^2 \n\\,.\n\\end{align}\n\nOn the other hand, in the spontaneously broken symmetry we get two real scalars: the mass of \\(\\sigma \\) is \\(m_\\sigma^2 =  2 \\lambda v^2\\); the mass of \\(\\pi \\) is \\(m_\\pi^2 = 0\\)!\n\nThe field \\(\\pi \\) is called the \\textbf{(Nambu) - Goldstone boson} of the \\(U(1)\\) theory which is spontaneously broken to \\(\\phi \\). \n\n\\todo[inline]{What is \\(\\phi \\)?} \n\nThe physics of the SB theory look different, however there are some important facts which are maintained: \n\\begin{enumerate}\n    \\item the coupling terms are those of the original theory, \\(\\lambda \\) and \\(v^2 = - \\mu^2\\);\n    \\item the Goldstone boson can only have \\textbf{derivative couplings}.\n\\end{enumerate}\n\nWhat we have done can be stated with more generality: if we have a theory with a global symmetry group \\(G\\) which is spontaneously broken by a choice of vacuum to a group \\(H\\), then there will be \\(\\dim G - \\dim H\\) massless real Goldstone bosons. \nThis is the \\textbf{Goldstone theorem}.\n\nIn our case we had \\(G = U(1)\\) and \\(H = \\mathbb{1}\\), since the vacuum of our theory was a single point. \n\nThe Higgs mechanism is the spontaneous breaking of a local symmetry. \n\n\\end{document}\n", "meta": {"hexsha": "115292edfc182ed1ecf9ecc0d6d9348614e5832d", "size": 14077, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ap_second_semester/theoretical_physics/sheet17.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "ap_second_semester/theoretical_physics/sheet17.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ap_second_semester/theoretical_physics/sheet17.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 40.1054131054, "max_line_length": 390, "alphanum_fraction": 0.6456631385, "num_tokens": 5009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.33613229636782854}}
{"text": "\\documentclass{article}\n\\usepackage[utf8]{inputenc}\n\n\\title{RFC stats}\n\\author{Chloe Yugawa}\n\\date{November 2017}\n\n\\begin{document}\n\n\\maketitle\n\n\\section{Introduction}\nSignals that collide are problematic with the current proposed solution to this problem. In this section, we will explore the probability that signals will collide in a few different cases. Assumptions for this section are as follows:\n\\begin{itemize}\n\\item The number of crabs transmitting in the entire study is 500\n\\item The target listening radius is $50$ meters with an area of $7853.98m^2$\n\\item The estimated density of tagged crabs is 0.00012 tagged crabs/m2 (that's 1 tagged crab per 8500 square meters)\n\\item The conservative estimate of tagged crabs is 0.001 crabs/m2 (1 tagged crab per 1000 square meters).  The average distance between crabs will be about 32 meters if they're all evenly spaced.\n\\item For the sake of simplicity, a signal is defined as the total time between the beginning of a signal and the end of the signal, including the encoded silence. The time for this is estimated to be 11ms to 212ms, or 0.0011s to .212s.\n\\item The signal space is defined as the time between the end of one signal and the start of the next. This will be between 10 and 15 seconds.\n\\item The total signal time will then be between 10.0011 and 15.212 seconds (signal + signal space). On average, that's 5 signals per minute.\n\\item A conservative estimate for the percentage of crabs tagged is $.5\\% $\n\\item The probability of finding more than one crab within a meter (tagged or untagged) during the season when research will occur is $3-5\\%$\n\n\\end{itemize}\n\n\n\nThe number of crabs within the detection radius is shown in table 1. The low estimate is assuming 1 crab per $8500m^2$, while the high estimate is 1 crab per $1000m^2$.\n\nLooking at periods of 0.5 seconds as a conservative estimate and dividing 60 seconds into 5 12 second sections, assume that each signal is contained within one of those 0.5 second periods. Within a 12 second section, each crab will on average signal once. Dividing that section into 24 0.5 second parts, by the pidgin hole principle, at least two crabs must signal within the same 0.5 second period when the number of signaling crabs is greater than 24. See table 3 for probability of collisions. Table 2 shows the same reasoning for a period of 0.2 seconds and 60 intervals.\n\n\\section{Conclusion}\nIf average signal is 4 per minute, 9 crabs gives a 30\\% chance of collision for 0.2 second periods. When determining factors such as detection radius and length of signal space, it is advised to look at 3 different tagged crab densities: the conservative 1 crab per 1000$m^2$; the more likely 1 crab per 8500$m^2$; and the midpoint of the two estimates of 1 crab per 4750$m^2$. For each estimate, calculate the number of crabs within the detection radius. Calculate probabilities based on signal time and space. If the number of crabs in the detection radius for the middle estimate has a probability of collision over 30\\%, variables should be adjusted. \n\\newpage\n\\section{Tables}\n\n\\begin{table}[ht]\n\\centering\n\\caption{Number of tagged crabs based on detection radius}\n%\\label{my-label}\n\\begin{tabular}{|c|c|c|c|}\n\\hline\n\\textbf{Radius (meters)} & \\textbf{Area (meters squared)} & \\textbf{\\# of crabs - low} & \\textbf{\\# of crabs - high} \\\\ \\hline\n50                       & 7854                           & 1                          & 8                           \\\\ \\hline\n100                      & 31,416                         & 4                          & 31                          \\\\ \\hline\n150                      & 70,686                         & 8                          & 71                          \\\\ \\hline\n200                      & 125,664                        & 15                         & 126                         \\\\ \\hline\n250                      & 196,350                        & 23                         & 196                         \\\\ \\hline\n\\end{tabular}\n\\end{table}\n\n\n\\begin{table}[ht]\n\\centering\n\\caption{Crab Collision Probability with 0.2 second periods}\n%\\label{my-label}\n\\begin{tabular}{|c|c|}\n\\hline\nNumber of crabs & Probability of collision \\\\ \\hline\n1               & 0                        \\\\ \\hline\n2               & .017                     \\\\ \\hline\n3               & .05                      \\\\ \\hline\n4               & .096                      \\\\ \\hline\n5               & .15                      \\\\ \\hline\n6               & .22                      \\\\ \\hline\n7               & .30                      \\\\ \\hline\n8               & .38                      \\\\ \\hline\n9               & .45                      \\\\ \\hline\n10              & .53                      \\\\ \\hline\n11              & .60                      \\\\ \\hline\n12              & .67                        \\\\ \\hline\n\\end{tabular}\n\\end{table}\n\\begin{table}[ht]\n\\centering\n\\caption{Crab Collision Probability with 0.5 second periods}\n%\\label{my-label}\n\\begin{tabular}{|c|c|}\n\\hline\nNumber of crabs & Probability of collision \\\\ \\hline\n1               & 0                        \\\\ \\hline\n2               & .042                     \\\\ \\hline\n3               & .12                      \\\\ \\hline\n4               & .23                      \\\\ \\hline\n5               & .35                      \\\\ \\hline\n6               & .47                      \\\\ \\hline\n7               & .59                      \\\\ \\hline\n8               & .70                      \\\\ \\hline\n9               & .78                      \\\\ \\hline\n10              & .85                      \\\\ \\hline\n11              & .90                      \\\\ \\hline\n12              & .94                        \\\\ \\hline\n\\end{tabular}\n\\end{table}\n\n\\end{document}\n", "meta": {"hexsha": "e046556bdbae0e6a30dc459e6450a94a26b4ae41", "size": 5742, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/rfc1/RFC_stats_2_0.tex", "max_stars_repo_name": "cabeese/crab-tracker", "max_stars_repo_head_hexsha": "a0b3f9604f04435c8dbdcb1be109f35c34d34e59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-31T01:32:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-31T01:32:17.000Z", "max_issues_repo_path": "doc/rfc1/RFC_stats_2_0.tex", "max_issues_repo_name": "cabeese/crab-tracker", "max_issues_repo_head_hexsha": "a0b3f9604f04435c8dbdcb1be109f35c34d34e59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 47, "max_issues_repo_issues_event_min_datetime": "2017-11-04T02:04:42.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-16T01:00:48.000Z", "max_forks_repo_path": "doc/rfc1/RFC_stats_2_0.tex", "max_forks_repo_name": "cabeese/crab-tracker", "max_forks_repo_head_hexsha": "a0b3f9604f04435c8dbdcb1be109f35c34d34e59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-06-10T21:58:49.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-18T17:21:03.000Z", "avg_line_length": 58.5918367347, "max_line_length": 655, "alphanum_fraction": 0.5625217694, "num_tokens": 1402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.3361322929811333}}
{"text": "\\section{Syntax and Semantics}\\label{sec:abstractrefinements:check}\n\n\nNext, we present a core calculus \\corelan that formalizes the notion\nof abstract refinements. We start with the syntax (\\S~\\ref{sec:syntax}),\npresent the typing rules (\\S~\\ref{sec:abstractrefinements:typing}), show soundness \nvia a reduction to contract calculi \\cite{Knowles10,Greenberg11}\n(\\S~\\ref{sec:soundness}), and inference via Liquid types (\\S~\\ref{sec:abstractrefinements:infer}).\n\n\\subsection{Syntax}\\label{sec:syntax}\n\nFigure~\\ref{fig:abstractrefinements:syntax} summarizes the syntax of our core \ncalculus \\corelan which is a polymorphic $\\lambda$-calculus \nextended with abstract refinements. \n%\nWe write \n$b$, \n$\\tref{b}{\\reft}$ and \n$\\tpp{b}{\\areft}$ \nto abbreviate \n$\\tpref{b}{\\true}{\\true}$, \n$\\tpref{b}{\\true}{\\reft}$, and\n$\\tpref{b}{\\areft}{\\true}$ respectively. \nWe say a type or schema is \\emph{non-refined} if all the \nrefinements in it are $\\true$. We write $\\overline{z}$ \nto abbreviate a sequence $z_1 \\ldots z_n$.\n\n\n\\mypara{Expressions}\n\\corelan\\ expressions include the standard variables $x$, \nprimitive constants $c$, $\\lambda$-abstraction $\\efunt{x}{\\tau}{e}$,\napplication $\\eapp{e}{e}$, type abstraction $\\etabs{\\alpha}{e}$,\nand type application $\\etapp{e}{\\tau}$. The parameter $\\tau$ in \nthe type application is a \\emph{refinement type}, as described shortly.\nThe two new additions to \\corelan are the refinement abstraction\n$\\epabs{\\rvar}{\\tau}{e}$, which introduces a refinement variable \n$\\rvar$ (together with its type $\\tau$), which can appear in refinements\ninside $e$, and the corresponding refinement application $\\epapp{e}{e}$.\n%\n%where the argument, is of the form $\\efun{\\bar{x}{e}}$ which is\n%an abbreviation for $\\efun{x_1 \\ldots x_n}{e}$.\n%which is of the form $\\ptype{\\bar{\\tau}}$ which is an \n%abbreviation for $\\ptype{tau_1 \\rightarrow \\ldots \\tau_n}$,\n%where each $\\tau_i$ is a simple (non-function) type.\n\n\\mypara{Refinements}\nA \\emph{concrete refinement} \\reft is a boolean valued expression \\reft \ndrawn from a strict subset of the language of expressions which\nincludes only terms that \n(a)~neither diverge nor crash and \n(b)~can be embedded into an SMT decidable refinement logic including \nthe theory of linear arithmetic and uninterpreted functions.\n%\nAn \\emph{abstract refinement} \\areft is a conjunction of refinement\nvariable applications of the form $\\rvapp{\\pi}{e}$.\n\n\\mypara{Types and Schemas}\nThe basic types of \\corelan include the base types $\\tbint$ and $\\tbbool$\nand type variables $\\alpha$. An \\emph{abstract refinement type} $\\tau$ is \neither a basic type refined with an abstract and concrete refinements,\n$\\tpref{b}{\\areft}{\\reft}$, or \na dependent function type where the parameter $x$ can appear in the \nrefinements of the output type. \nWe include refinements for functions, as refined type variables can be \nreplaced by function types. However, typechecking ensures these refinements\nare trivially true.\n%\n%type application\n%Type application consists of a type constructor, its type arguments\n%and its refinement arguments \n%that are used to describe properties between its elements.\n%\nFinally, types can be quantified over refinement variables and type \nvariables to yield abstract refinement schemas.\n\n\n\\begin{figure}[t!]\n\\centering\n\\captionsetup{justification=centering}\n$$\n\\begin{array}{rrcl}\n\\emphbf{Expressions} \\quad \n  & e \n  & ::= \n  &      x \n  \\spmid c \n  \\spmid \\efunt{x}{\\tau}{e} \n  \\spmid \\eapp{e}{e} \\\\\n  &&\\spmid &\\etabs{\\alpha}{e} \n  \\spmid \\etapp{e}{\\tau} \n  \\spmid \\epabs{\\rvar}{\\tau}{e}\n  \\spmid \\epapp{e}{e} \n  \\\\[0.05in] \n\n\\emphbf{Abstract Refinements} \\quad \n  & \\areft \n  & ::= \n  &      \\true \n  \\spmid \\areft \\land \\rvapp{\\rvar}{e}\n  \\\\[0.05in] \n\n\\emphbf{Basic Types} \\quad \n  & b \n  & ::= \n  &      \\tbint\n  \\spmid \\tbbool\n  \\spmid \\alpha\n  \\\\[0.05in]\n\n\\emphbf{Abstract Refinement Types} \\quad \n  & \\tau \n  & ::= \n  &      \\tpref{b}{\\areft}{\\reft} \n  \\spmid \\trfun{x}{\\tau}{\\tau}{\\reft}\n  \\\\[0.05in]\n\n\\emphbf{Abstract Refinement Schemas} \\quad \n  & \\sigma\n  & ::= \n  &      \\tau \n  \\spmid \\ttabs{\\alpha}{\\sigma}\n  \\spmid \\tpabs{\\rvar}{\\tau}{\\sigma}\n  \\\\[0.05in]\n\\end{array}\n$$\n\\caption[Syntax of \\corelan.]{\\textbf{Syntax of Expressions, Refinements, Types and Schemas of \\corelan.}}\n\\label{fig:abstractrefinements:syntax}\n\\end{figure}\n\n\\subsection{Static Semantics}\\label{sec:abstractrefinements:typing}\n\n\\input{text/abstractrefinements/rules}\n\nNext, we describe the static semantics of \\corelan by describing the typing\njudgments and derivation rules. Most of the rules are \nstandard~\\cite{Ou2004,LiquidPLDI08,Knowles10,GordonTOPLAS2011}; we \ndiscuss only those pertaining to abstract refinements.\n%\n\n\\mypara{Judgments}\nA type environment $\\Gamma$ is a sequence of type bindings $x:\\sigma$.\nWe use environments to define three kinds of typing judgments.\n\n\\mypara{Wellformedness judgments (\\isWellFormed{\\Gamma}{\\sigma})}\nstate that a type schema $\\sigma$ is well-formed under environment\n$\\Gamma$, that is, the refinements in $\\sigma$ are boolean \nexpressions in the environment $\\Gamma$.\n%\nThe wellformedness rules check that the concrete and abstract\nrefinements are indeed $\\tbbool$-valued expressions in the \nappropriate environment.\nThe key rule is \\wtBase, which checks, as usual, that the (concrete) \nrefinement $\\reft$ is boolean and additionally, that the abstract\nrefinement $\\areft$ applied to the value $\\vref$ is also boolean.\nThis latter fact is established by \\wtRVApp which checks that \neach refinement variable application $\\rvapp{\\rvar}{e}\\ \\vref$ \nis also of type \\tbbool in the given environment.\n\n\\mypara{Subtyping judgments}\n(\\isSubType{\\Gamma}{\\sigma_1}{\\sigma_2}) \nstate that the type schema $\\sigma_1$ is a subtype of the type schema\n$\\sigma_2$ under environment $\\Gamma$, that is, when the free variables\nof $\\sigma_1$ and $\\sigma_2$\nare bound to values described by $\\Gamma$, the set of values described\nby $\\sigma_1$ is contained in the set of values described by $\\sigma_2$. \n%\nThe rules are standard except for \\tsubVar, which encodes the base types' \nabstract refinements $\\areft_1$ and $\\areft_2$ with conjunctions of \n\\emph{uninterpreted predicates} \n$\\inter{\\areft_1\\ \\vref}$ and $\\inter{\\areft_2\\ \\vref}$ in the \nrefinement logic as follows:\n\\begin{align*}\n\\inter{\\true\\ \\vref} & \\defeq \\true\\\\\n\\inter{(\\areft \\land \\rvapp{\\rvar}{e})\\ \\vref} & \\defeq \\inter{\\areft\\\n\\vref} \\land \\rvar(\\inter{e_1},\\ldots,\\inter{e_n},\\vref)\n\\end{align*}\nwhere $\\rvar(\\overline{e})$ is a term in the refinement logic corresponding\nto the application of the uninterpreted predicate symbol $\\rvar$ to the \narguments $\\overline{e}$.\n% $\\text{Valid}(p)$ (\\tsubBase) holds if an SMT determines the formula $p$ \n% is \\emph{valid}~\\cite{Nelson81}.\n\n\n\n\\mypara{Typing judgments}\n(\\hastype{\\Gamma}{e}{\\sigma}) state that\nthe expression $e$ has the type schema $\\sigma$ under environment $\\Gamma$,\nthat is, when the free variables in $e$ are bound to values described by \n$\\Gamma$, the expression $e$ will evaluate to a value described by $\\sigma$.\n%\nThe type checking rules are standard except for \\tpgen and \\tpinst, which\npertain to abstraction and instantiation of abstract refinements.\n%\nThe rule \\tpgen is the same as \\tfunction: we simply check the body\n$e$ in the environment extended with a binding for the refinement \nvariable $\\rvar$.\n%\nThe rule \\tpinst checks that the concrete refinement is of the appropriate\n(unrefined) type $\\tau$, and then replaces all (abstract) applications of\n$\\rvar$ inside $\\sigma$ with the appropriate (concrete) refinement $\\reft'$ \nwith the parameters $\\overline{x}$ replaced with arguments at that application.\nFormally, this is represented as $\\rpinst{\\sigma}{\\rvar}{\\efunbar{x:\\tau}{\\reft'}}$\nwhich is $\\sigma$ with each base type transformed as\n\\begin{align*}\n\\rpinst{\\tpref{b}{\\areft}{\\reft}}{\\rvar}{z}\n  & \\defeq \\tpref{b}{\\areft''}{\\reft \\land \\reft''} \\\\\n\\mbox{where} \\quad (\\areft'', \\reft'') \n  & \\defeq \\rpapply{\\areft}{\\rvar}{z}{\\true}{\\true} \n\\intertext{$\\mathsf{Apply}$ replaces each application of $\\rvar$ in \n$\\areft$ with the corresponding conjunct in $\\reft''$, as}\n\\rpapply{\\true}{\\cdot}{\\cdot}{\\areft'}{\\reft'} \n  & \\defeq (\\areft', \\reft') \\\\\n\\rpapply{\\areft \\wedge \\rvapp{\\rvar'}{e}}{\\rvar}{z}{\\areft'}{\\reft'} \n  & \\defeq \\rpapply{\\areft}{\\rvar}{z}{\\areft' \\land \\rvapp{\\rvar'}{e}}{\\reft'} \\\\\n\\rpapply{\\areft \\wedge \\rvapp{\\rvar}{e}}{\\rvar}{\\efunbar{x:\\tau}{\\reft''}}{\\areft'}{\\reft'} \n  & \\defeq\n  \\rpapply{\\areft}{\\rvar}{\\efunbar{x:\\tau}{\\reft''}}{\\areft'}{\\reft' \\wedge \\SUBST{\\reft''}{\\overline{x}}{\\overline{e},\\vref}}\n\\end{align*}\nIn other words, the instantiation can be viewed as two symbolic \nreduction steps: first replacing the refinement variable with the\nconcrete refinement, and then ``beta-reducing\" concrete refinement \nwith the refinement variable's arguments. For example, \n$$\\rpinst{\\tpref{\\tbint}{\\rvar\\ y}{\\vref > 10}}\n       {\\rvar}\n       {\\efunt{x_1}{\\tau_1}{\\efunt{x_2}{\\tau_2}{x_1 < x_2}}}\n\\defeq \\tref{\\tbint}{\\vref > 10 \\land y < \\vref}$$\n%%rp(x:tx->t , \\rvar, z) = x:tx' -> t'\n%%  where tx'      = rp(tx, \\rvar, z)\n%%        t'       = rp(t , \\rvar, z)\n%%\n%%rp(\\a.t, \\rvar, z) = \\a.t'\n%%  where t'       = rp(t, \\rvar, z)\n%%\n%%rp(\\p.t, \\rvar, z) = \\p.t'\n%%  where t'       = rp(t, \\rvar, z)\n\n%%The other rule that handles abstract refinements is \\tcase.\n%%This rule initially checks that the expression to be analyzed \n%%has a type application type $T = \\tcon{\\chi}{e_\\chi}{\\listOf{T}}{\\listOf{e}}$.\n%%Then for all cases, the case expression is typechecked in the initial environment, \n%%extended with case binders \\listOf{x_i} and the initial expression binder $x$.\n%%The types of these binders are gained after unfolding data constructor's type \\tc{K_i}. \n%%The unfolding is done by replacing its type variables with actual type arguments\n%%of $T$, ie. \\listOf{T} \n%%its abstract refinements with actual inferred refinements \\listOf{e},\n%%and its binders with actual binders \\listOf{x_i}.\n\n\\subsection{Soundness}\\label{sec:abstractrefinements:soundness}\n\nAs hinted by the discussion about refinement variable instantiation,\nwe can intuitively think of abstract refinement variables as \n\\emph{ghost} program variables whose values are boolean-valued \nfunctions. Hence, abstract refinements are a special case of \nhigher-order contracts, that can be statically verified using \nuninterpreted functions. (Since we focus on static checking, \nwe don't care about the issue of blame.)\nWe formalize this notion by translating \\corelan programs into\nthe contract calculus \\conlan of \\cite{Greenberg11} and use this \ntranslation to define the dynamic semantics and establish soundness.\n\n\\mypara{Translation} \nWe translate \\corelan schemes $\\sigma$ to \\conlan schemes $\\tx{\\sigma}$\nas by translating abstract refinements into contracts,\nand refinement abstraction into function types:\n\n\\[\\arraycolsep=0.5pt\n\\begin{array}{rclcrcl}\n\\tx{\\true\\ \\vref} & \\defeq \n  & \\true  \n  & \\quad \\quad &\n\n\\tx{\\tpabs{\\rvar}{\\tau}{\\sigma}} & \\defeq \n  & \\tfun{\\rvar}{\\tx{\\tau}}{\\tx{\\sigma}} \\\\\n\n\\tx{(\\areft \\land \\rvapp{\\rvar}{e})\\ \\vref} & \\defeq \n  & \\tx{\\areft\\ \\vref} \\land \\eapp{\\eapp{\\rvar}{\\overline{e}}}{\\vref} \n  & \\quad \\quad &\n\n\\tx{\\ttabs{\\alpha}{\\sigma}} & \\defeq \n  & \\ttabs{\\alpha}{\\tx{\\sigma}} \\\\\n\n\\tx{\\tpref{b}{\\areft}{\\reft}} & \\defeq \n  & \\tref{b}{\\reft \\land \\tx{\\areft\\ \\vref}} \n  & \\quad \\quad &\n\n\\tx{\\tfun{x}{\\tau_1}{\\tau_2}} & \\defeq \n  & \\tfun{x}{\\tx{\\tau_1}}{\\tx{\\tau_2}} \n%\\tx{\\trfun{x}{\\tau_1}{\\tau_2}{\\reft}} \\defeq \n%  & \\trfun{x}{\\tx{\\tau_1}}{\\tx{\\tau_2}}{\\tx{\\reft}} \\\\\n\\end{array}\\]\nSimilarly, we translate \\corelan terms $e$ to \\conlan \nterms $\\tx{e}$ by converting refinement abstraction and application \nto $\\lambda$-abstraction and application\n\\[\\arraycolsep=0.5pt\n\\begin{array}{rclcrcl}\n\\tx{x} & \\defeq & x & \\quad \\quad \\quad & \\tx{c} & \\defeq & c \\\\\n\\tx{\\efunt{x}{\\tau}{e}} & \\defeq & \\efunt{x}{\\tx{\\tau}}{\\tx{e}} & \\quad & \\tx{\\eapp{e_1}{e_2}} & \\defeq & \\eapp{\\tx{e_1}}{\\tx{e_2}} \\\\\n\\tx{\\etabs{\\alpha}{e}} & \\defeq & \\etabs{\\alpha}{\\tx{e}} & \\quad & \\tx{\\etapp{e}{\\tau}} & \\defeq & \\eapp{\\tx{e}}{\\tx{\\tau}} \\\\\n\\tx{\\epabs{\\rvar}{\\tau}{e}} &\\defeq & \\efunt{\\rvar}{\\tx{\\tau}}{\\tx{e}} & \\quad & \\tx{\\epapp{e_1}{e_2}} &\\defeq & \\eapp{\\tx{e_1}}{\\tx{e_2}}\n\\end{array}\\]\n\n%%\\begin{align*}\n%%\\tx{\\true\\ \\vref} \\defeq \n%%  & \\true\\\\\n%%\\tx{(\\areft \\land \\rvapp{\\rvar}{e})\\ \\vref} \\defeq \n%%  & \\tx{\\areft\\ \\vref} \\land \\eapp{\\eapp{\\rvar}{\\overline{e}}}{\\vref}\\\\\n%%\\tx{\\tpref{b}{\\areft}{\\reft}} \\defeq \n%%  & \\tref{b}{\\reft \\land \\tx{\\areft\\ \\vref}} \\\\\n%%\\tx{\\tfun{x}{\\tau_1}{\\tau_2}} \\defeq \n%%  & \\tfun{x}{\\tx{\\tau_1}}{\\tx{\\tau_2}} \\\\\n%%%\\tx{\\trfun{x}{\\tau_1}{\\tau_2}{\\reft}} \\defeq \n%%%  & \\trfun{x}{\\tx{\\tau_1}}{\\tx{\\tau_2}}{\\tx{\\reft}} \\\\\n%%\\tx{\\ttabs{\\alpha}{\\sigma}} \\defeq \n%%  & \\ttabs{\\alpha}{\\tx{\\sigma}} \\\\\n%%\\tx{\\tpabs{\\rvar}{\\tau}{\\sigma}} \\defeq \n%%  & \\tfun{\\rvar}{\\tx{\\tau}}{\\tx{\\sigma}}\n%%\\end{align*}\n%%\\tx{x} \\defeq & x \\\\\n%%\\tx{c} \\defeq & c \\\\\n%%\\tx{\\efunt{x}{\\tau}{e}} \\defeq & \\efunt{x}{\\tx{\\tau}}{\\tx{e}} \\\\\n%%\\tx{\\eapp{e_1}{e_2}} \\defeq & \\eapp{\\tx{e_1}}{\\tx{e_2}} \\\\\n%%\\tx{\\etabs{\\alpha}{e}} \\defeq & \\etabs{\\alpha}{\\tx{e}} \\\\\n%%\\tx{\\etapp{e}{\\tau}} \\defeq & \\eapp{\\tx{e}}{\\tx{\\tau}} \\\\\n%%\\tx{\\epabs{\\rvar}{\\tau}{e}} \\defeq & \\efunt{\\rvar}{\\tx{\\tau}}{\\tx{e}} \\\\\n%%\\tx{\\epapp{e_1}{e_2}} \\defeq & \\eapp{\\tx{e_1}}{\\tx{e_2}}\n\n\n\n\n\n\\mypara{Translation Properties}\nWe can show by induction on the derivations that the \ntype derivation rules of \\corelan \\emph{conservatively approximate}\nthose of \\conlan. Formally, \n\n\\begin{itemize}\n\\item If $\\isWellFormed{\\Gamma}{\\tau}$ then $\\isWellFormedH{\\Gamma}{\\tau}$,\n\\item If $\\isSubType{\\Gamma}{\\tau_1}{\\tau_2}$ then $\\isSubTypeH{\\Gamma}{\\tau_1}{\\tau_2}$,\n\\item If $\\hastype{\\Gamma}{e}{\\tau}$ then\n$\\hastypeH{\\tx{\\Gamma}}{\\tx{e}}{\\tx{\\tau}}$.\n\\end{itemize}\n\n\\mypara{Soundness} Thus rather than re-prove preservation and progress\nfor \\corelan, we simply use the fact that the type derivations are\nconservative to derive the following preservation and progress \ncorollaries from \\cite{Greenberg11}:\n%\n\\begin{itemize}\n\\item{\\textbf{Preservation: }} \n  If $\\hastype{\\emptyset}{e}{\\tau}$ \n  and $\\tx{e} \\longrightarrow e'$ \n  then $\\hastypeH{\\emptyset}{e'}{\\tx{\\tau}}$\n\n\\item{\\textbf{Progress: }}\n  If $\\hastype{\\emptyset}{e}{\\tau}$, then either\n  $\\tx{e} \\longrightarrow e'$ or \n  $\\tx{e}$ is a value.\n\\end{itemize}\n%\nNote that, in a contract calculus like \\conlan, subsumption is encoded\nas a \\emph{upcast}. However, if subtyping relation can be statically \nguaranteed (as is done by our conservative SMT based subtyping) \nthen the upcast is equivalent to the identity function and can \nbe eliminated. Hence, \\conlan terms $\\tx{e}$ translated from well-typed \n\\corelan terms $e$ have no casts.\n\n\\subsection{Refinement Inference}\\label{sec:abstractrefinements:infer}\n\nOur design of abstract refinements makes it particularly easy to \nperform type inference via Liquid typing, which is crucial for\nmaking the system usable by eliminating the tedium of instantiating \nrefinement parameters all over the code. (With value-dependent \nrefinements, one cannot simply use, say, unification to determine\nthe appropriate instantations, as is done for classical type systems).\nWe briefly recall how Liquid types work, and sketch how they are \nextended to infer refinement instantiations.\n\n\\mypara{Liquid Types} \nThe Liquid Types method infers refinements in three steps. \n%\nFirst, we create refinement \\emph{templates} for the unknown, \nto-be-inferred refinement types. The \\emph{shape} of the template \nis determined by the underlying (non-refined) type it corresponds to, \nwhich can be determined from the language's underlying (non-refined) \ntype system. \nThe template is just the shape refined with fresh refinement variables\n$\\kappa$ denoting the unknown refinements at each type position. \nFor example, from a type ${\\tfun{x}{\\tbint}{\\tbint}}$ we create \nthe template ${\\tfun{x}{\\tref{\\tbint}{\\kappa_x}}{\\tref{\\tbint}{\\kappa}}}$.\n%\nSecond, we perform type checking using the templates (in place of the\nunknown types). Each wellformedness check becomes a wellformedness\nconstraint over the templates, and hence over the individual $\\kvar$,\nconstraining which variables can appear in $\\kvar$.\nEach subsumption check becomes a subtyping constraint\nbetween the templates, which can be further simplified, via syntactic\nsubtyping rules, to a logical implication query between the variables\n$\\kappa$.\n%\nThird, we solve the resulting system of logical implication constraints\n(which can be cyclic) via abstract interpretation --- in particular,\nmonomial predicate abstraction over a set of logical qualifiers\n\\cite{Houdini,LiquidPLDI08}. The solution is a map from $\\kvar$ to\nconjunctions of qualifiers, which, when plugged back into the templates,\nyields the inferred refinement types.\n\n\\mypara{Inferring Refinement Instantiations}\nThe key to making abstract refinements practical is a means of \nsynthesizing the appropriate arguments $\\reft'$ for each refinement \napplication $\\epapp{e}{\\reft'}$. \nNote that for such applications, we can, from $e$, determine the \nnon-refined type of $\\reft'$, which is of the form \n${\\tau_1 \\rightarrow \\ldots \\rightarrow \\tau_n \\rightarrow \\tbbool}$.\nThus, $\\reft'$ has the template \n${\\efunt{x_1}{\\tau_1}{\\ldots \\efunt{x_n}{\\tau_n}{\\kvar}}}$\nwhere $\\kvar$ is a fresh, unknown refinement variable that \nmust be solved to a boolean valued expression over $x_1,\\ldots,x_n$.\nThus, we generate a \\emph{wellformedness} constraint \n${\\isWellFormed{x_1:\\tau_1, \\ldots, x_n:\\tau_n}{\\kvar}}$\nand carry out typechecking with template, which, as before, yields\nimplication constraints over $\\kvar$, which can, as before, be \nsolved via predicate abstraction.\nFinally, in each refinement template, we replace each $\\kvar$ with its\nsolution $e_\\kvar$ to get the inferred refinement instantiations.\n\n%%To infer appropabstract refinements we used the liquid type variables\n%%$\\kappa$ with explicit arguments to avoid inferring function \n%%expressions:\n%%To infer an expression to replace a predicate of type \n%%$\\listOf{x_i:\\tau_i; \\tau}$ in an environment $\\Gamma$, \n%%we create a fresh liquid variable $\\kappa$ on $\\tau$ which is\n%%wellformed in the environment $\\Gamma$ extended with the bindings\n%%\\listOf{x_i:\\tau_i}.\n%%When $\\kvar$ is solved via predicate abstraction to an expression \n%%$e_\\kvar$, we simply replace $\\kvar$ with \n%%the set as the inferred expression \n%%$e =\\efun{x_1}{\\dots\\efun{x_n}{\\efun{v}{e_\\kappa}}}$.\n%add a refinement variable in place of expressions. \n%\\mypara{Constants}\\jhala{constant-refinements and soundness guarantees?}\n%%TODO: \n%%[SKIP] add paragraph on constants to opsem\n%%[SKIP] redefine \\reft to r? (to emphasize not arbitrary expression?)\n\n", "meta": {"hexsha": "5ebac178f7bd802f73abf4ac7101279f2271c780", "size": 18730, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "text/abstractrefinements/typechecking.tex", "max_stars_repo_name": "nikivazou/thesis", "max_stars_repo_head_hexsha": "a12f2e857a358e3cc08b657bb6b029ac2d500c3b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2016-12-02T00:46:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-20T07:04:01.000Z", "max_issues_repo_path": "text/abstractrefinements/typechecking.tex", "max_issues_repo_name": "nikivazou/thesis", "max_issues_repo_head_hexsha": "a12f2e857a358e3cc08b657bb6b029ac2d500c3b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "text/abstractrefinements/typechecking.tex", "max_forks_repo_name": "nikivazou/thesis", "max_forks_repo_head_hexsha": "a12f2e857a358e3cc08b657bb6b029ac2d500c3b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-12-02T00:46:51.000Z", "max_forks_repo_forks_event_max_datetime": "2016-12-02T00:46:51.000Z", "avg_line_length": 42.1846846847, "max_line_length": 138, "alphanum_fraction": 0.7047517352, "num_tokens": 5913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.33613228959443797}}
{"text": "\\section{Method}\n\\label{sec:method}\n\\label{sec:algorithm}\n\n\\paragraph{Assumption}\n\nThe key assumption about textures is locality under contextual control \\cite{Wei:2009:STTS}.\nIn particular, each texture sample (e.g. pixel of an image texture or vertex of a mesh texture) relates to only those that are in its spatial vicinity (locality) \\cite{Efros:1999:TSN}, but its property is conditioned upon global control such as environment variables (context) \\cite{Lu:2007:CT}.\nTaking these two together, a texture consists of repetitive patterns that are local but potentially globally varying.\n\n\\paragraph{Idea}\n\nOur method is adapted from \nk-coherence \\cite{Tong:2002:SBT} and randomized patch-match \\cite{Barnes:2009:PRC} for quality\\nothing{efficacy}, efficiency, flexibility, and simplicity.\nThe basic idea stems from the coherence observation: regardless of the exact synthesis algorithms used, as long as the output has sufficient quality, it is usually composed of coherent patches from the input exemplar.\nIn other words, if we record the source position $\\position(\\inputex, \\sample)$ within the input exemplar $\\inputex$ from which each output pixel $\\sample \\in \\outputex$ comes from, the positions usually form coherent patches as visualized in \\cite{Wei:2002:TSF}.\nThis implies that to determine the color value $\\range(\\sample)$ of $\\sample$, we can look at each one of its already synthesized neighbor $\\sample' \\in \\outputex$ with input position $\\position(\\inputex, \\sample')$, and use their relative input and output position offsets to compute a good potential candidate:\n\\begin{align}\n\\position(\\inputex, \\sample' \\rightarrow \\sample) = \\position(\\outputex, \\sample) - \\position(\\outputex, \\sample') + \\position(\\inputex, \\sample')\n\\label{eqn:coherence_offset}\n\\end{align}\n, where $\\position(\\inputex, \\sample' \\rightarrow \\sample)$ indicates a potentially good source position of $\\sample$ at the input $\\inputex$ as voted from an already computed output pixel $\\sample'$.\nWe can collect a set of such $\\sample'$ in the (coherence) neighborhood $\\corneighborhood$ of $\\sample$, and see which one has the best matched (texture) neighborhood $\\texneighborhood$:\n\\begin{align}\n\\range(\\outputex, \\sample) \\leftarrow \\range\\left(\\argmin_{\\sample'} \\left\\{\\left|\\texneighborhood(\\outputex, \\sample) - \\texneighborhood(\\outputex, \\sample')\\right|^2 \\forall \\sample' \\in \\corneighborhood(\\outputex, \\sample) \\right\\} \\right)\n\\label{eqn:coherence_synthesis}\n\\end{align}\nThe coherence and texture neighborhoods $\\corneighborhood$ and $\\texneighborhood$ are usually small regions with specific shapes and sizes, e.g. circles or squares.\n\n\\paragraph{Variations}\n\nBoth k-coherence \\cite{Tong:2002:SBT} and patch-match \\cite{Barnes:2009:PRC} are generalizations of the main idea expressed in \\Cref{eqn:coherence_synthesis}.\nIn particular, \\cite{Tong:2002:SBT} pre-computes a set of $\\knumber$ candidates with similar texture neighborhoods to each input pixel $\\sample \\in \\inputex$, so that each $\\sample$ can provide $\\knumber$ instead of just $1$ votes in \\Cref{eqn:coherence_offset}.\nEmpirical evidence indicates that this can indeed improve quality (with sufficiently small $\\knumber$ in the range of 4 to 8), but this pre-computation can be too expensive for large input exemplars.\nPatch-match \\cite{Barnes:2009:PRC} also bypasses this pre-computation, but instead of adding $\\knumber$ random candidates to \\Cref{eqn:coherence_synthesis}, which works surprisingly well.\n\nOptimization \\cite{Kwatra:2005:TOE,Han:2006:TDO} can be imposed as an orthogonal component, but greedy assignment usually suffices.\n\n\\paragraph{Constraint}\n\nConstraints can be easily added by simply presetting the colors of certain output pixels in \\Cref{eqn:coherence_synthesis}, and let the synthesis process assign neighboring output to have consistent texture patterns.\nGood output quality can never be fully guaranteed as it depends on several factors, including whether the constraints leave enough degrees of freedom for optimization.\n\n\\paragraph{Multi-resolution}\n\nThe basic ideas above can be directly extended for multi-resolution synthesis \\cite{Wei:2000:FTS} via the following basic steps:\n\\begin{enumerate}\n\\item\nCompute a Gaussian pyramid from the input with number of levels specified by the user.\n\n\\item\nSynthesize the output from lower to higher levels, with each level generated from the corresponding input level.\nEach level computation is very similar to the single-resolution algorithm above, except that we can use multi-resolution neighborhoods (for both similarity measure and coherence).\n\n\\item\nWrite out the highest output level.\n\\end{enumerate}\n\nHard constraints are currently handled directly as invariant values inside the output pyramid during multi-resolution synthesis.\nThis is not theoretically optimal, as hard constraints should be on the highest level only.\nBut it seems to work well in practice.\nFor better theoretical approach, we will need to pursue a joint optimization schemes such as \\cite{Kwatra:2005:TOE,Han:2006:TDO} or a multi-grid solver.\n", "meta": {"hexsha": "6bad325c9548a96e9a7b928c816531734c13c758", "size": 5065, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/method.tex", "max_stars_repo_name": "1iyiwei/texture", "max_stars_repo_head_hexsha": "eaa78c00666060ca0a51c69920031b367c265e7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2017-04-13T18:32:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-21T07:53:59.000Z", "max_issues_repo_path": "doc/method.tex", "max_issues_repo_name": "1iyiwei/texture", "max_issues_repo_head_hexsha": "eaa78c00666060ca0a51c69920031b367c265e7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-09-24T07:21:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-29T23:39:41.000Z", "max_forks_repo_path": "doc/method.tex", "max_forks_repo_name": "1iyiwei/texture", "max_forks_repo_head_hexsha": "eaa78c00666060ca0a51c69920031b367c265e7d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-04-12T17:46:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-31T00:50:12.000Z", "avg_line_length": 80.3968253968, "max_line_length": 312, "alphanum_fraction": 0.7903257651, "num_tokens": 1203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.33613228959443797}}
{"text": "%!TEX root=../main.tex\n\\chapter{Dynamic Gradient Damage Models} \\label{chap:graddama}\n\\minitoc\n\nIn this chapter the author first proposes a variational framework of the gradient damage models in the dynamic setting. Its ingredients and physical principles are presented in \\cref{sec:formulation}. The author then reviews and analyzes in \\cref{sec:TC} several approaches in an attempt to account for the tension-compression asymmetry of damage behavior of materials. In \\cref{sec:linkDF} the dynamic gradient damage evolution is theoretically compared with the Griffith's theory of fracture. It is found that the crack evolution is governed by an asymptotic Griffith's law as long as the internal length is small compared to the dimension of the body.\n\n\\section{Variational Framework Based on Physical Principles} \\label{sec:formulation}\nIn this section the author extends the original quasi-static gradient damage models as formulated in \\cite{PhamMarigo:2010-1} to the dynamic setting. A variationally consistent framework for dynamic gradient damage models thanks to the definition of a generalized space-time action integral is obtained. A comparison with other phase-field approaches is then carried out. An extension to large-displacement situations is also discussed. The thematic subjects covered are summarized in \\cref{tab:summvaria}.\n\\begin{table}[htbp]\n\\centering\n\\caption{Thematic subjects covered in this section} \\label{tab:summvaria}\n\\begin{tabular}{ccccc} \\toprule\n& Going dynamical & $\\alpha\\leftrightarrow\\phi$ & $\\nabla\\alpha\\to\\Gamma$ & Experimental validation \\\\ \\midrule\nTheoretics & \\rightthumbsup & \\rightthumbsup & & \\\\\nNumerics & & & & \\\\ \\bottomrule\n\\end{tabular}\n\\end{table}\n\n\\subsection{Variational ingredients} \\label{sec:ingredients}\nFor the sake of simplicity, let us consider first a homogeneous and isotropic body $\\Omega$ under the small strain hypothesis. Anisotropy is not the object of the present study and we assume that the local elastic material behavior can be characterized by two constants: the Young's modulus $E$ and the Poisson's ratio $\\nu$ for instance. A discussion on an extension to large displacement situations is provided at the end of this section, since they should not influence the variational formulation proposed here.\n\nThe construction of the dynamic model is based on that of the quasi-static gradient damage model \\cite{PhamMarigo:2010-1,PhamAmorMarigoMaurini:2011}. Its physical background and motivation has been discussed in \\cref{sec:graddamage} and are not reproduced here. An element in the phase space of the dynamic gradient damage model regarded as a dynamical system corresponds to a state tuple $(\\vec{u}_t,\\dot{\\vec{u}}_t,\\alpha_t)$ consisting of the displacement field $\\vec{u}_t$, the velocity field $\\dot{\\vec{u}}_t$ and the damage field $\\alpha_t$. They are scalar or vector fields defined on the body $\\Omega$, \\emph{i.e.} a snapshot of the dynamic evolution at a certain time $t$. The modeling parameters are embedded into several energetic quantities that are defined as follows. The elastic energy as well as the damage dissipation energy retain their quasi-static definitions, since they are unaffected by dynamics.\n\\begin{itemize}\n\\item \\textbf{Elastic energy} characterizes the elastic behavior of the material. It is given by\n\\begin{equation} \\label{eq:elasticG}\n\\mathcal{E}(\\vec{u}_t,\\alpha_t)=\\int_\\Omega\\psi\\bigl(\\eps(\\vec{u}_t),\\alpha_t\\bigr)\\dx=\\int_\\Omega\\frac{1}{2}\\tens{A}(\\alpha_t)\\eps(\\vec{u}_t)\\cdot\\eps(\\vec{u}_t)\\dx\\,,\n\\end{equation}\nwhere $\\eps(\\vec{u}_t)=\\frac{1}{2}(\\nabla\\vec{u}_t+\\nabla^\\mT\\vec{u}_t)$ denotes the linearized strain and $\\tens{A}(\\alpha)$ is the isotropic Hooke's elasticity tensor at a given damage state. We assume that the Poisson's ratio is unaffected by the damage variable, which leads to\n\\[\n\\tens{A}(\\alpha)=\\mathsf{a}(\\alpha)\\tens{A}_0\\,,\n\\]\nwhere $\\alpha\\mapsto\\mathsf{a}(\\alpha)$ is an adimensional function of damage characterizing stiffness degradation in the bulk from an initial undamaged state $\\tens{A}_0=\\tens{A}(0)$. The \\emph{damage-dependent} stress tensor conjugate to the strain variable is thus given by\n\\begin{equation} \\label{eq:stress}\n\\sig_t=\\tens{A}(\\alpha_t)\\eps(\\vec{u}_t).\n\\end{equation}\nIt can be observed that here the damage acts symmetrically on the undamaged elastic energy density $\\psi_0\\bigl(\\eps(\\vec{u}_t)\\bigr)=\\psi\\bigl(\\eps(\\vec{u}_t),0\\bigr)$ such that\n\\begin{equation} \\label{eq:psi0}\n\\psi\\bigl(\\eps(\\vec{u}_t),\\alpha_t\\bigr)=\\psi\\bigl(-\\eps(\\vec{u}_t),\\alpha_t\\bigr)=\\mathsf{a}(\\alpha_t)\\psi_0\\bigl(\\eps(\\vec{u}_t)\\bigr).\n\\end{equation}\nAn extension to tension-compression asymmetry will be discussed in \\cref{sec:TC}.\n\n\\item \\textbf{Kinetic energy} is defined as usual by\n\\begin{equation} \\label{eq:kineticG}\n\\mathcal{K}(\\dot{\\vec{u}}_t)=\\int_\\Omega\\kappa(\\dot{\\vec{u}}_t)\\dx=\\int_\\Omega\\frac{1}{2}\\rho\\dot{\\vec{u}}_t\\cdot\\dot{\\vec{u}}_t\\dx.\n\\end{equation}\nThe material density $\\rho$ is independent of the damage, which implies total mass conservation. Furthermore, it assumes that the local damage behavior is not affected by inertia.\n\n\\item \\textbf{Damage dissipation energy} quantifies the amount of energy consumed in a damage process. For theoretic analyses of gradient damage models, for example in \\cite{PhamAmorMarigoMaurini:2011,SicsicMarigo:2013}, one often uses the following definition\n\\begin{equation} \\label{eq:surface}\n\\mathcal{S}(\\alpha_t)=\\int_\\Omega\\varsigma(\\alpha_t,\\nabla\\alpha_t)\\dx=\\int_\\Omega\\bigl(w(\\alpha_t)+\\frac{1}{2}w_1\\ell^2\\nabla\\alpha_t\\cdot\\nabla\\alpha_t\\bigr)\\dx\\,,\n\\end{equation}\nwhere $\\alpha\\mapsto w(\\alpha)$ describes local damage dissipation during a homogeneous damage evolution and its maximal value $w(1)=w_1$ is the energy completely dissipated during such process when damage attains 1. For numerical implementation purposes, see \\cite{BourdinMarigoMauriniSicsic:2014,MesgarnejadBourdinKhonsari:2014}, a non-essential rescaling of the internal length $\\ell=\\sqrt{2}\\eta$ is usually performed and \\eqref{eq:surface} is rewritten as follows\n\\begin{align} \\label{eq:surfaceGc}\n\\mathcal{S}(\\alpha_t)=\\int_\\Omega\\varsigma(\\alpha_t,\\nabla\\alpha_t)\\dx=\\int_\\Omega\\frac{\\gc}{c_w}\\left(\\frac{\\mathsf{w}(\\alpha_t)}{\\eta}+\\eta\\nabla\\alpha_t\\cdot\\nabla\\alpha_t\\right)\\dx. \\tag{\\ref*{eq:surface}${}^\\prime$}\n\\end{align}\nTo ensure equivalence between these two definitions, we have necessarily $w(\\alpha)=w_1\\mathsf{w}(\\alpha)$ and $\\gc=c_ww_1\\eta$, where $\\alpha\\mapsto\\mathsf{w}(\\alpha)$ denotes the adimensional damage dissipation function. Note that\n\\begin{quotation}\nIn the sequel, both $\\ell$ and $\\eta$ denote the material internal length.\n\\end{quotation}\n\\end{itemize}\n\n\\paragraph{Damage constitutive functions} We assume that the stiffness degradation function $\\alpha\\mapsto\\mathsf{a}(\\alpha)$ along with the damage dissipation function $\\alpha\\mapsto\\mathsf{w}(\\alpha)$ verify certain constitutive properties which characterize the behavior of a \\emph{strongly brittle material} for the underlying local damage model, cf. \\cite{PhamMarigoMaurini:2011,PhamMarigo:2013,SicsicMarigo:2013}. In particular, we have\n\\begin{itemize}\n\\item Energy completely dissipated during a homogeneous damage evolution is finite: $0<w_1<\\infty$. This condition justifies the use of a damage variable the value of which is between 0 and 1.\n\n\\item Strain-softening, which ensures that the elastic domain in the stress space is a decreasing function of damage in the sense of set inclusion. Using the variational nature of the elastic-damage evolution \\cite{Marigo:2002}, it implies that the function $\\alpha\\mapsto \\mathsf{s}'(\\alpha)/\\mathsf{w}'(\\alpha)$ must be increasing, where $\\mathsf{s}=\\mathsf{a}^{-1}$. This property should be verified for all $\\alpha\\in[0,1]$, or at least in a neighborhood of $\\alpha=1$. During a homogeneous uniaxial traction experiment, it leads to the definition of the critical stress $\\sigma_\\mathrm{c}$ beyond which damage grows and the maximal stress that the material can sustain:\n\\begin{equation} \\label{eq:sigc0}\n\\sigma_\\mathrm{c}=\\sqrt{\\frac{2Ew'(0)}{\\tens{s}'(0)}}\\,,\\quad \\sigma_\\mathrm{m}=\\max_{\\beta\\in[0,1)}\\sqrt{\\frac{2Ew'(\\beta)}{\\tens{s}'(\\beta)}}.\n\\end{equation}\n\\end{itemize}\n\nDepending on the specific damage constitutive laws $\\alpha\\mapsto\\tens{a}(\\alpha)$ and $\\alpha\\mapsto \\mathsf{w}(\\alpha)$ used, the material and structural behaviors could be quantitatively or even qualitatively different. An abundant literature is devoted to a theoretic or numerical analysis of these damage constitutive laws. The interested readers are referred to \\cite{PhamAmorMarigoMaurini:2011,PhamMarigoMaurini:2011,LorentzCuvilliezKazymyrenko:2012,PhamMarigo:2013} and references therein for a discussion on this point. In the numerical simulation part of this work, two particular damage constitutive laws will be considered. They both involve only polynomial functions of the damage up to degree 2, thus the elastic energy $\\mathcal{E}$ as well as the damage dissipation energy $\\mathcal{S}$ are \\emph{quadratic} with respect to damage, a rather interesting property from a computational cost point of view since the Hessian matrix is constant.\n\\begin{itemize}\n\\item The Pham, Amor, Marigo and Maurini model initially introduced in \\cite{PhamAmorMarigoMaurini:2011} and named after their initials:\n\\begin{align} \\label{eq:at1}\n\\mathsf{a}(\\alpha)=(1-\\alpha)^2\\,,\\quad \\mathsf{w}(\\alpha)=\\alpha. \\tag{PAMM}\n\\end{align}\nDamage does not evolve as long as a non-zero critical stress is not reached, a rather appreciated property when modeling brittle fracture. Then a strain-softening behavior is observed as damage grows for $\\alpha\\in(0,1)$, which implies that the critical stress coincides with the maximal stress. According to \\eqref{eq:sigc0}, we have\n\\[\n\\sigma_\\mathrm{c}=\\sigma_\\mathrm{m}=\\sqrt{w_1E}.\n\\]\n\n\\item The original Ambrosio and Tortorelli regularization model introduced in \\cite{BourdinFrancfortMarigo:2000}:\n\\begin{align} \\label{eq:at2}\n\\mathsf{a}(\\alpha)=(1-\\alpha)^2\\,,\\quad \\mathsf{w}(\\alpha)=\\alpha^2. \\tag{AT}\n\\end{align}\nIn this model a purely elastic domain is absent $\\sigma_\\mathrm{c}=0$ and the strain-softening property is satisfied only for $\\alpha\\in(\\frac{1}{4},1)$. At $\\alpha=\\frac{1}{4}$ the stress reaches its maximal value and is given by\n\\[\n\\sigma_\\mathrm{m}=\\frac{3\\sqrt{6}}{16}\\sqrt{w_1E}.\n\\]\n\\end{itemize}\n\nTheir constitutive behaviors are illustrated in the \\cref{fig:at1at2} during a homogeneous uniaxial traction experiment. Their respective maximal stress $\\sigma_\\mathrm{m}$ as well as the corresponding strain $\\varepsilon_\\mathrm{m}$ are used for normalization.\n\\begin{figure}[htbp]\n\\centering\n\\includegraphics[width=0.9\\textwidth]{1d.pdf}\n\\caption{Constitutive behaviors for the \\eqref{eq:at1} model (a) and the \\eqref{eq:at2} model (b) during a homogeneous uniaxial traction experiment} \\label{fig:at1at2}\n\\end{figure}\n\n\\paragraph{Links between damage and fracture} As outlined in \\cref{sec:fm98,sec:graddamage}, the link between damage and fracture can be established in terms of the $\\Gamma$-convergence theory. The damage dissipation energy \\eqref{eq:surface} can be regarded as an equivalent Griffith crack surface functional in the phase-field model. An effective fracture toughness $\\gc$, \\emph{i.e.} the energy required to create a unit Griffith-like crack surface, can be identified as the energy dissipated during the optimal damage profile creation in a uniaxial traction experiment, see \\cite{PhamAmorMarigoMaurini:2011} for a detailed discussion on this point. The optimal damage profile $\\alpha_*$ can be considered as the theoretic cross-section perpendicular to a gradient-damage crack. If $x$ refers to the transverse coordinate axis centered at the crack where $\\alpha_*(x)=1$, the optimal damage profile for the \\eqref{eq:at1} model is given by\n\\begin{equation} \\label{eq:at1alpha}\n\\alpha_*(x)=\\begin{cases}\n\\left(1-\\dfrac{\\abs{x}}{2\\eta}\\right)^2 & \\text{if $\\abs{x}<2\\eta$\\,,} \\\\\n0 & \\text{else}.\n\\end{cases}\n\\end{equation}\nWhile for the damage constitutive model \\eqref{eq:at2}, one derives\n\\begin{equation} \\label{eq:at2alpha}\n\\alpha_*(x)=\\exp\\left(-\\frac{\\abs{x}}{\\eta}\\right).\n\\end{equation}\nThese two damage profiles are illustrated in \\cref{fig:at12}. It can be observed that \\eqref{eq:at2alpha} does not possess a finite support from a theoretic point of view.\n\\begin{figure}[htbp]\n\\centering\n\\includegraphics[width=0.5\\textwidth]{at12.pdf}\n\\caption{Optimal damage profiles for the \\eqref{eq:at1} and \\eqref{eq:at2} damage constitutive models} \\label{fig:at12}\n\\end{figure}\nWith such optimal damage profiles, the corresponding dissipated energy can be consequently computed by injecting $\\alpha_*$ into \\eqref{eq:surface} or \\eqref{eq:surfaceGc}. For the damage dissipation energy written in the form of \\eqref{eq:surface}, we have\n\\begin{equation} \\label{eq:gcingd}\n\\gc=2\\sqrt{2}\\ell\\int_0^1\\sqrt{w_1w(\\beta)}\\D{\\beta}.\n\\end{equation}\nThis equation prescribes a relation between the fracture toughness $\\gc$, the maximal damage dissipation $w_1$ and the internal length $\\ell$.\n\nWhen the damage dissipation energy is written in the form of \\eqref{eq:surfaceGc}, one anticipates the fact that the gradient damage model can be regarded as a genuine model of fracture. The link between damage and fracture is hidden in the definition of the normalization coefficient $c_w$. According to \\eqref{eq:gcingd}, it leads to\n\\begin{equation} \\label{eq:gcingdcw}\nc_w=4\\int_0^1\\sqrt{\\mathsf{w}(\\beta)}\\D{\\beta}.\n\\end{equation}\nA direct calculation gives $c_w=\\frac{8}{3}$ for the \\eqref{eq:at1} model and $c_w=2$ for the \\eqref{eq:at2} one.\n\n\\paragraph{Modeling parameters} The modeling parameters of the dynamic gradient damage model can thus be summarized in \\cref{tab:modelgrad}. The elastodynamic parameters corresponds to the material density as well as two elastic constants. The fracture behavior can be characterized by a maximal stress defined by \\eqref{eq:sigc0} and a fracture toughness $\\gc$, thanks to the identification \\eqref{eq:gcingd} or to the definition of the normalization coefficient in \\eqref{eq:gcingdcw}. The internal length $\\ell$ can be regarded as a parameter that achieves a link between damage and fracture. It can be considered as a dependent or independent modeling parameter depending on the choice of damage constitutive functions.\n\\begin{table}[htbp]\n\\centering\n\\caption{Modeling parameters of the dynamic gradient damage model regarded as a genuine model of fracture} \\label{tab:modelgrad}\n\\begin{tabular}{ccccc} \\toprule\n& Elastodynamics & Fracture & Damage $\\leftrightarrow$ fracture & Constitutive functions \\\\ \\midrule\nParameters & $\\rho$, $E$ and $\\nu$ & $\\gc$ and $\\sigma_\\mathrm{m}$ & $\\ell$ & $\\mathsf{a}(\\alpha)$ and $\\mathsf{w}(\\alpha)$ \\\\ \\bottomrule\n\\end{tabular}\n\\end{table}\n\nThe damage constitutive functions $\\mathsf{a}(\\alpha)$ and $\\mathsf{w}(\\alpha)$ contribute to the quantitative behaviors of gradient damage models used to approximate brittle fracture. Remark that no additional parameters are introduced in the \\eqref{eq:at1} and the \\eqref{eq:at2} models. In particular, the internal length $\\ell$ is determined as long as the two fracture parameters $\\gc$ and $\\sigma_\\mathrm{m}$ as known. More modeling parameters can be introduced via the use of more sophisticated constitutive functions such as that defined in \\cite{LorentzCuvilliezKazymyrenko:2012,AlessiMarigoVidoli:2015}. For instance, in \\cite{AlessiMarigoVidoli:2015} the following damage constitutive laws are proposed\n\\begin{align*}\n\\mathsf{a}(\\alpha)=\\frac{1-\\mathsf{w}(\\alpha)}{1+(k-1)\\mathsf{w}(\\alpha)}\\,,\\quad \\mathsf{w}(\\alpha)=1-(1-\\alpha)^2.\n\\end{align*}\nIts homogeneous damage behavior is characterized by a linear softening curve parametrized by the $k$-parameter as illustrated in \\cref{fig:atk}.\n\\begin{figure}[htbp]\n\\centering\n\\includegraphics[width=0.9\\textwidth]{1d_ATk.pdf}\n\\caption{Constitutive behaviors for the constitutive functions proposed in \\cite{AlessiMarigoVidoli:2015} during a homogeneous uniaxial traction experiment: (a) stress-strain behavior and (b) damage evolution} \\label{fig:atk}\n\\end{figure}\nAccording to \\eqref{eq:sigc0} and \\eqref{eq:gcingd}, the following relationships between the material parameters hold\n\\[\nG_\\mathrm{c}=\\pi w_1\\eta\\,,\\quad \\sigma_\\mathrm{c}^2=\\frac{2G_\\mathrm{c}E}{\\pi k\\eta}.\n\\]\nIn particular, the introduction of the $k$-parameters permits one to interpret $\\ell$ as a genuine independent parameter. In that case, the $k$-parameter is fixed as long as other material parameters are\n\\[\nk=\\frac{2\\gc E}{\\pi\\eta\\sigma_\\mathrm{c}^2}.\n\\]\nFuture work could be devoted to a thorough theoretic and numerical analysis of these kind of models in the dynamic setting.\n\n\\subsection{Dynamic evolution laws}\nIn this work we propose to formulate the variational dynamic evolution problem using an extension of Hamilton's principle, cf. \\cite{Hamilton:1834}. In the quasi-static case the meta-stability condition \\eqref{eq:qsstability} is a physically feasible principle due to the minimization structure of static equilibrium. In dynamics however, we merely have a \\emph{stationary} action integral, since the temporal minimality is not always guaranteed, see \\cite{Gray:2007aa}. From a mathematical modeling point of view, Hamilton's principle applies to temporal \\emph{boundary value problems} defined in an interval $[0,T]$, since the state at both time ends is fixed during arbitrary variations of the action. More sophisticated variational principles can be designed to take into account only the initial displacement $\\vec{u}_0$ and the initial velocity $\\dot{\\vec{u}}_0$ conditions, see for example \\cite{Gurtin:1964aa}. We admit that the use of Hamilton's principle may not be an optimal one from a formulation point of view. Nevertheless it is not the object of the present work. Here Hamilton's principle is mainly used to derive the equations to solve the physical \\emph{initial value problem}.\n\nThe loading conditions and the admissible function spaces are now specified. Body forces $\\vec{f}_t$ and surface tractions $\\vec{F}_t$ applied to the body through a subset $\\partial\\Omega_F$ of the boundary are characterized by an external work potential $\\mathcal{W}_t$ given by\n\\begin{equation} \\label{eq:power}\n\\mathcal{W}_t(\\vec{u}_t)=\\int_\\Omega\\vec{f}_t\\cdot\\vec{u}_t\\dx+\\int_{\\partial\\Omega_F}\\vec{F}_t\\cdot\\vec{u}_t\\D{\\vec{s}}.\n\\end{equation}\nOn a subset $\\partial\\Omega_U$ of the boundary the body is subject to a prescribed displacement $t\\mapsto \\vec{U}_t$ which is built into the definition of the admissible displacement space $\\mathcal{C}_t$. We suppose that the admissible displacement space is an affine space of form $\\mathcal{C}_t=\\mathcal{C}_0+\\vec{U}_t$ where the associated vector space $\\mathcal{C}_0$ is given by\n\\begin{equation} \\label{eq:C0}\n\\mathcal{C}_0=\\set{\\vec{u}_t:\\Omega\\to\\mathbb{R}^\\mathrm{dim}|\\vec{u}_t=\\vec{0}\\text{ on }\\partial\\Omega_U}.\n\\end{equation}\n\n\\begin{remark}[Dirichlet boundary condition]\nThe field $\\vec{U}_t\\in\\mathcal{C}_t$ should be understood as a \\emph{lifting} of the Dirichlet boundary condition classically defined only on $\\partial\\Omega_U$.\n\\end{remark}\n\nDamage is here modeled as an irreversible defect evolution. Its admissible space will be built from a current damage state $0\\leq\\alpha_t\\leq 1$ and it is defined by\n\\begin{equation} \\label{eq:Dalphat}\n\\mathrm{D}(\\alpha_t)=\\set{\\beta_t:\\Omega\\to[0,1]|0\\leq\\alpha_t\\leq\\beta_t\\leq 1}.\n\\end{equation}\nIt can be seen that a virtual damage field $\\beta_t$ is admissible, if and only if it is accessible from the current damage state $\\alpha_t$ verifying the irreversibility condition, \\emph{i.e.} the damage only grows. In order to use Hamilton's principe, we consider an arbitrary interval of time $I=[0,T]$ and fix the values of $(\\vec{u},\\alpha)$ at both time ends denoted by $\\vec{u}_{\\partial I}=(\\vec{u}_0,\\vec{u}_T)$ and $\\alpha_{\\partial I}=(\\alpha_0,\\alpha_T)$. Hence, the admissible displacement and damage evolution spaces read\n\\begin{align}\n\\mathcal{C}(\\vec{u}) &= \\set{\\vec{v}:I\\times\\Omega\\to\\mathbb{R}^\\mathrm{dim}|\\vec{v}_t\\in\\mathcal{C}_t\\text{ for all $t\\in I$ and }\\vec{v}_{\\partial I}=\\vec{u}_{\\partial I}}\\,, \\label{eq:Du} \\\\\n\\mathcal{D}(\\alpha) &= \\set{\\beta:I\\times\\Omega\\to[0,1]|\\beta_t\\in\\mathrm{D}(\\alpha_t)\\text{ for all $t\\in I$ and }\\beta_{\\partial I}=\\alpha_{\\partial I}}. \\label{eq:Dalpha}\n\\end{align}\n\n\\begin{remark}[Spatial and temporal regularity of $\\vec{u}$ and $\\alpha$]\nInformally, we assume that the displacement $\\vec{u}$ and the damage $\\alpha$ are sufficiently regular in time and in space such that all the energetic quantities defined in \\cref{sec:ingredients} make sense. Before the onset of fracture when the damage attains 1 somewhere in the body $\\operatorname{ess\\ sup}\\alpha_t< 1$, the elastic energy density \\eqref{eq:psi0} is strictly positive almost everywhere, hence a natural functional framework for the displacement would be $H^1(\\Omega,\\mathbb{R}^\\mathrm{dim})$. Since the temporal derivative of the damage is not involved in the variational formulation, for every $t\\in I$ the damage $\\alpha_t$ belongs at least to $H^1(\\Omega)\\cap L^\\infty(\\Omega)$. Due to the kinetic energy \\eqref{eq:kineticG}, the current velocity $\\dot{\\vec{u}}_t$, regarded as the temporal derivative of the displacement in the distributional sense, should be an element of $L^2(\\Omega,\\mathbb{R}^\\mathrm{dim})$. A precise statement of the function spaces in the most general case remains beyond the scope of this work.\n\\end{remark}\n\nWith all the variational ingredients set, we are now in a position to introduce the following space-time action integral associated with an admissible pair of displacement and damage evolutions $(\\vec{u},\\alpha)\\in\\mathcal{C}(\\vec{u})\\times\\mathcal{D}(\\alpha)$, which involves an augmented Lagrangian\n\\begin{equation} \\label{eq:actionG}\n\\mathcal{A}(\\vec{u},\\alpha)=\\int_I\\mathcal{L}_t(\\vec{u}_t,\\dot{\\vec{u}}_t,\\alpha_t)\\,\\mathrm{d}t=\\int_I\\bigl(\\mathcal{E}(\\vec{u}_t,\\alpha_t)+\\mathcal{S}(\\alpha_t)-\\mathcal{K}(\\dot{\\vec{u}}_t)-\\mathcal{W}_t(\\vec{u}_t)\\bigr)\\D{t}.\n\\end{equation}\nThe coupled two-field time-continuous dynamic gradient damage problem can then be formulated by the following\n\\begin{definition}[Dynamic Gradient Damage Evolution Law] \\label{def:dynagraddama} \\noindent\n\\begin{enumerate}\n\\item \\textbf{Irreversibility}: the damage $t\\mapsto\\alpha_t$ is a non-decreasing function of time.\n\\item \\textbf{First-order stability}: the first-order action variation is non-negative with respect to arbitrary admissible displacement and damage evolutions\n\\begin{equation} \\label{eq:vi}\n\\mathcal{A}'(\\vec{u},\\alpha)(\\vec{v}-\\vec{u},\\beta-\\alpha)\\geq 0\\text{ for all $\\vec{v}\\in\\mathcal{C}(\\vec{u})$ and all $\\beta\\in\\mathcal{D}(\\alpha)$}.\n\\end{equation}\n\\item \\textbf{Energy balance}: the only energy dissipation is due to damage\n\\begin{multline} \\label{eq:dyngdeb}\n\\mathcal{H}_t=\\mathcal{H}_0+\\int_0^t\\left(\\int_\\Omega\\bigl(\\sig_s\\cdot\\eps(\\dot{\\vec{U}}_s)-\\rho\\dot{\\vec{u}}_s\\cdot\\ddot{\\vec{U}}_s\\bigr)\\dx-\\mathcal{W}_s(\\dot{\\vec{U}}_s)-\\dot{\\mathcal{W}}_s(\\vec{u}_s)\\right)\\D{s} \\\\\n+\\int_\\Omega\\rho(\\dot{\\vec{u}}_t\\cdot\\dot{\\vec{U}}_t-\\dot{\\vec{u}}_0\\cdot\\dot{\\vec{U}}_0)\\dx\n\\end{multline}\nwhere the total energy is defined by\n\\[\n\\mathcal{H}_t=\\mathcal{E}(\\vec{u}_t,\\alpha_t)+\\mathcal{S}(\\alpha_t)+\\mathcal{K}(\\dot{\\vec{u}}_t)-\\mathcal{W}_t(\\vec{u}_t).\n\\]\n\\end{enumerate}\n\\end{definition}\n\nIn the first-order stability condition \\eqref{eq:vi}, we evaluate the directional (Gâteaux) derivative of the action integral at $(\\vec{u},\\alpha)$, a possible solution to the dynamic evolution problem, in the direction $(\\vec{v}-\\vec{u},\\beta-\\alpha)$ which corresponds to a perturbation. Formally, using the Lagrangian $\\mathcal{L}_t$, we have\n\\[\n\\mathcal{A}'(\\vec{u},\\alpha)(\\vec{w},\\beta-\\alpha)=\\int_I\\left(\\frac{\\partial \\mathcal{L}_t}{\\partial\\vec{u}_t}(\\vec{s}_t)(\\vec{w}_t)+\\frac{\\partial \\mathcal{L}_t}{\\partial\\dot{\\vec{u}}_t}(\\vec{s}_t)(\\dot{\\vec{w}}_t)+\\frac{\\partial \\mathcal{L}_t}{\\partial\\alpha_t}(\\vec{s}_t)(\\beta_t-\\alpha_t)\\right)\\D{t}\\,,\n\\]\nwhere $\\vec{w}=\\vec{v}-\\vec{u}$ denotes a displacement evolution variation and $\\vec{s}_t=(\\vec{u}_t,\\dot{\\vec{u}}_t,\\alpha_t)$ corresponds to a state of the dynamical system. Remark that \\eqref{eq:vi} is written as a variational inequality to take into account the unilateral effects introduced by the irreversibility condition in the definition of the damage admissible space \\eqref{eq:Dalphat}. It can be regarded as an extension of Hamilton's principle applied to systems with irreversible dissipation.\n\nThe energy balance condition \\eqref{eq:dyngdeb} characterizes the energy flow into the system: the external work is balanced by the mechanical energy variation of the system consisting of the elastic energy \\eqref{eq:elasticG} and the kinetic energy \\eqref{eq:kineticG}, and the energy dissipated in the process of crack production \\eqref{eq:surface}. The energy balance condition \\eqref{eq:dyngdeb} complements the first-order stability condition \\eqref{eq:vi} which ensures that energy could only be dissipated through damage (or gradient-damage like fracture). Observe that \\eqref{eq:dyngdeb} also applies to non-smooth evolutions in the presence of possible velocity shocks, since no higher spatial or temporal derivatives of the displacement and the damage are involved other than that needed for the definition of the Lagrangian density. With the help of integration by parts, the regularity is transferred to the boundary conditions $t\\mapsto \\vec{U}_t$ and the external work potential $t\\mapsto \\mathcal{W}_t$. If in particular the acceleration field $\\ddot{\\vec{u}}_t$ is sufficiently regular, the energy balance condition admits an equivalent formulation which reads after an integration by parts in the time domain\n\\begin{align} \\label{eq:dyngdeb2}\n\\mathcal{H}_t=\\mathcal{H}_0+\\int_0^t\\left(\\int_\\Omega\\bigl(\\sig_s\\cdot\\eps(\\dot{\\vec{U}}_s)+\\rho\\ddot{\\vec{u}}_s\\cdot\\dot{\\vec{U}}_s\\bigr)\\dx-\\mathcal{W}_s(\\dot{\\vec{U}}_s)-\\dot{\\mathcal{W}}_s(\\vec{u}_s)\\right)\\D{s}. \\tag{\\ref*{eq:dyngdeb}${}^\\prime$}\n\\end{align}\n\n\\subsection{Equivalent local interpretations} \\label{sec:equivalentlocal}\nBy developing the Gâteaux derivative of the action integral, further physical insights into the first-order stability condition \\eqref{eq:vi} can be obtained if sufficient spatial and temporal regularities of the involved fields are assumed. Writing the variation $\\vec{v}-\\vec{u}$ by $\\vec{w}$ and testing \\eqref{eq:vi} with $\\beta=\\alpha$, we obtain after an integration by parts in the time domain\n\\begin{equation} \\label{eq:actionu}\n\\mathcal{A}'(\\vec{u},\\alpha)(\\vec{w},0)=\\int_I\\left(\\int_\\Omega\\bigl(\\sig_t\\cdot\\eps(\\vec{w}_t)+\\rho\\ddot{\\vec{u}}_t\\cdot\\vec{w}_t\\bigr)\\dx-\\mathcal{W}_t(\\vec{w}_t)\\right)\\D{t}=0\\text{ for all $\\vec{w}_t\\in\\mathcal{C}_0$}\n\\end{equation}\nwhere the equality $\\mathcal{A}'(\\vec{u},\\alpha)(\\vec{w},0)=0$ follows given that the associated linear space $\\mathcal{C}_0$ of $\\mathcal{C}_t$ is a vector space. The arbitrariness of the temporal variation of $\\vec{w}$ leads thus to the weak elastic-damage dynamic wave equation\n\\begin{equation} \\label{eq:weakform}\n\\int_\\Omega\\bigl(\\sig_t\\cdot\\eps(\\vec{w}_t)+\\rho\\ddot{\\vec{u}}_t\\cdot\\vec{w}_t\\bigr)\\dx-\\mathcal{W}_t(\\vec{w}_t)=0\\text{ for all $\\vec{w}_t\\in\\mathcal{C}_0$}.\n\\end{equation}\nIf further spatial regularity is assumed, one deduces the strong form\n\\begin{equation} \\label{eq:wavedyn}\n\\rho\\ddot{\\vec{u}}_t-\\div\\sig_t=\\vec{f}_t\\quad\\text{in }\\Omega\\quad\\text{and}\\quad\\sig_t\\vec{n}=\\vec{F}_t\\quad\\text{on }\\partial\\Omega_F\n\\end{equation}\nCompared to the classical elastodynamic equation, here the stress tensor $\\sig_t$ is damage dependent through the elasticity tensor, see \\eqref{eq:stress}.\n\nWe now turn to the governing equation for damage evolution induced from the first-order stability condition \\eqref{eq:vi}. We observe that the admissible damage space $\\mathrm{D}(\\alpha_t)$ defined in \\eqref{eq:Dalphat} is convex. Due to the arbitrariness of the temporal variation of $\\beta$, testing \\eqref{eq:vi} now with $\\vec{v}=\\vec{u}$ gives the Euler's inequality condition stating the partial minimality of the total energy with respect to the damage variable under the irreversible constraint for every $t\\in I$\n\\begin{equation} \\label{eq:crackmin}\n\\mathcal{E}(\\vec{u}_t,\\alpha_t)+\\mathcal{S}(\\alpha_t)\\leq\\mathcal{E}(\\vec{u}_t,\\beta_t)+\\mathcal{S}(\\beta_t)\\text{ for all $\\beta_t\\in\\mathrm{D}(\\alpha_t)$}.\n\\end{equation}\nAlthough the same energy minimization principle \\eqref{eq:crackmin} holds also for quasi-static gradient damage models \\cite{PhamAmorMarigoMaurini:2011}, here the displacement field $\\vec{u}_t$ is governed by the elastic-damage wave equation \\eqref{eq:wavedyn}. Developing the Euler's inequality condition and performing an integration by parts of the damage gradient term yield a strong formulation of \\eqref{eq:crackmin} which serves as the local damage criterion at a particular material point\n\\begin{equation} \\label{eq:localdamagefirstorder}\nY_t+\\div\\vec{q}_t\\leq 0\\quad\\text{in }\\domaint\\quad\\text{and}\\quad\\vec{q}_t\\cdot\\vec{n}\\geq 0\\quad\\text{on }\\partial\\Omega\\setminus\\Gamma_t.\n\\end{equation}\nFor notational simplicity, the following dual variables are defined\n\\begin{equation} \\label{eq:Ytqt}\nY_t=-\\frac{1}{2}\\tens{A}'(\\alpha_t)\\eps(\\vec{u}_t)\\cdot\\eps(\\vec{u}_t)-w'(\\alpha_t)\\quad\\text{and}\\quad\\vec{q}_t=w_1\\ell^2\\nabla\\alpha_t\n\\end{equation}\nThey can be interpreted as the energy release rate density with respect to damage and the damage flux vector, see \\cite{SicsicMarigo:2013}. In \\eqref{eq:localdamagefirstorder}, the subset $\\Gamma_t=\\set{\\vec{x}\\in\\Omega|\\alpha_t(\\vec{x})=1}$ denotes the totally damaged region. We note that the local damage criterion holds only in the uncracked part of the body, since $\\beta_t=\\alpha_t=1$ on $\\Gamma_t$ because of the definition of the admissible damage space \\eqref{eq:Dalphat}. Due to the presence of the damage gradient, the criterion is described by an elliptic type equation in space involving the Laplacian of the damage. Assuming that the considered fields are also sufficiently smooth in time, the global energy balance \\eqref{eq:dyngdeb} leads to the following consistency condition\n\\begin{equation} \\label{eq:damageconsis}\n(Y_t+\\div\\vec{q}_t)\\dot{\\alpha}_t=0\\quad\\text{in }\\domaint\\quad\\text{and}\\quad(\\vec{q}_t\\cdot\\vec{n})\\dot{\\alpha}_t=0\\quad\\text{on }\\partial\\Omega\\setminus\\Gamma_t.\n\\end{equation}\nHence damage growth is possible until a certain non-local threshold is reached. Similarly here the local consistency condition holds only in the uncracked part of the body, since $\\dot{\\alpha}_t=0$ on $\\Gamma_t$ by definition. These local interpretations \\eqref{eq:localdamagefirstorder} and \\eqref{eq:damageconsis} are also formally the same with that derived in the quasi-static model \\cite{PhamMarigo:2010-1,SicsicMarigo:2013}.\n\n\\paragraph{Damage initiation in an initially sound region}\nIf the body is initially undamaged inside a particular region (where the damage as well as the damage gradient are zero), then according to the consistency condition \\eqref{eq:damageconsis}, damage could initiate as long as the following condition is satisfied\n\\begin{equation} \\label{eq:damageinitiationsound}\nY_t|_{\\alpha_t=0}=0\\implies -\\frac{1}{2}\\mathsf{a}'(0)\\tens{A}_0\\eps(\\vec{u}_t)\\cdot\\eps(\\vec{u}_t)-w'(0)=0.\n\\end{equation}\nThis criterion can be equivalently written in the stress-space, which reads\n\\begin{align} \\label{eq:damageinitiationsound2}\n-\\frac{1}{2}\\mathsf{a}'(0)\\tens{S}_0\\sig_t\\cdot\\sig_t-w'(0)=0\\,, \\tag{\\ref*{eq:damageinitiationsound}${}^\\prime$}\n\\end{align}\nwhere $\\tens{S}_0=\\tens{A}_0^{-1}$ denotes the compliance tensor.\n\n\\paragraph{Construction of the optimal damage profile}\nAs is noted in \\cref{sec:ingredients}, the optimal damage profile $\\alpha_*$ (for example that given in \\eqref{eq:at1alpha} for the \\eqref{eq:at1} law) corresponds to the damage field at fracture during a uniaxial traction experiment of a bar centered at $x=0$. Concretely, it consists of applying the consistency condition \\eqref{eq:damageconsis} at the instant of fracture when the uniaxial stress vanishes $\\sigma=0$. The optimal damage profile is thus the solution to the following differential equation\n\\begin{equation} \\label{eq:defoptimaldamage}\nw'\\bigl(\\alpha_*(x)\\bigr)-w_1\\ell^2\\alpha_*''(x)=0\\text{ for $x\\in[-D,D]$}\\,\n\\end{equation}\nwhere $D$ measures the half-damage band or the support of the damage field where $\\alpha_t> 0$. Hence we have $D=2\\eta$ for the \\eqref{eq:at1} model and $D=\\infty$ for the \\eqref{eq:at2} model. One can easily solve this autonomous second order differential equation by using the boundary conditions $\\alpha_*=0$ and $\\alpha_*'=0$ at $x=\\pm D$. Readers are referred to \\cite{PhamAmorMarigoMaurini:2011} for a detailed derivation.\n\n\\paragraph{Singular surfaces and jump conditions}\nHere we discuss the presence of a possible singular surface $S_t\\subset\\Omega$ inside the reference configuration $\\Omega$ across which first derivatives of the fields involved in the variational ingredients could be discontinuous: the strain $\\eps(\\vec{u}_t)$, the velocity $\\dot{\\vec{u}}_t$ or the damage gradient $\\nabla\\alpha_t$. The body is partitioned into two parts $\\Omega^+$ and $\\Omega^-$, and we note $\\vec{n}$ as the normal vector of $S_t$ pointing into $\\Omega^+$. As usual we define the jump of a quantity $q$ to be\n\\[\n\\jump{q}(\\vec{x})=\\lim_{\\Omega{^+}\\ni\\vec{y}\\to\\vec{x}}q(\\vec{y})-\\lim_{\\Omega{^-}\\ni\\vec{y}\\to\\vec{x}}q(\\vec{y}).\n\\]\nDue to the presence of the damage gradient, the damage field remain continuous across such surfaces $\\jump{\\alpha_t}=0$. The same case takes place for the displacement vector $\\jump{\\vec{u}_t}=\\vec{0}$ before the onset of fracture $\\operatorname{ess\\ sup}\\alpha_t< 1$.\n\nThe variational approach outlined in \\cref{def:dynagraddama} permits also a systematic derivation of the jump conditions across such surfaces. We assume here that the space-time evolution $t\\mapsto S_t$ is known advance and its normal velocity in the reference configuration $\\Omega$ is denoted by $V_t$. A perturbation to the singular surface is considered in \\cite{BatraBedfordDrumheller:1986} however the formalism is similar to what will be described in \\cref{sec:linkDF}. The presence of such surfaces can thus be included into the admissible spaces \\eqref{eq:C0} and \\eqref{eq:Dalphat}. The first-order stability condition \\eqref{eq:vi} leads directly to the classical vectorial jump condition for the stress tensor\n\\[\n\\jump{\\rho\\dot{\\vec{u}}_t}V_t+\\jump{\\sig_t}\\vec{n}=\\vec{0}.\n\\]\nCompared to the classical stress jump condition, note that here the stress tensor $\\sig_t$ is modulated by the damage, see \\eqref{eq:stress}. Concerning the damage criterion, we have\n\\[\n\\jump{\\nabla\\alpha_t}\\cdot\\vec{n}\\leq 0.\n\\]\nAs can be seen from \\cref{fig:at12}, a discontinuity in the damage gradient often corresponds to the fracture point where $\\alpha_t=1$.\n\nSimilarly, the global energy balance condition \\eqref{eq:dyngdeb} results in the following energy density jump condition\n\\[\n\\jump{\\psi\\bigl(\\eps(\\vec{u}_t),\\alpha_t\\bigr)+\\kappa(\\dot{\\vec{u}}_t)+\\varsigma(\\alpha_t,\\nabla\\alpha_t)}V_t+\\jump{\\sig_t\\dot{\\vec{u}}_t}\\cdot\\vec{n}=0.\n\\]\nIn addition to the remark concerning the stress tensor, the dissipated energy density \\eqref{eq:surface} is also included. When the damage evolves $\\dot{\\alpha}_t>0$, the normal component of the damage gradient is continuous across these surfaces. We have\n\\[\n\\jump{\\nabla\\alpha_t}\\cdot\\dot{\\alpha}_t\\vec{n}=0.\n\\]\n\n\\subsection{Comparison with phase-field approaches} \\label{sec:phasefields}\nTwo essentially different phase-field models co-exist in the literature: one that originated from the mechanics community initiated by the work of \\cite{MieheHofackerWelschinger:2010,MieheWelschingerHofacker:2010}, and the other independently proposed by the physicists via the work of \\cite{KarmaKesslerLevine:2001,HakimKarma:2009}. They will be separately compared with the gradient damage approach outlined in \\cref{def:dynagraddama}.\n\n\\paragraph{Phase-field model originated from the mechanics community}\nThe phase-field model in the sense of \\cite{MieheHofackerWelschinger:2010,MieheWelschingerHofacker:2010} is initially stated for rate-independent evolutions but has been quickly extended to the dynamic setting in \\cite{HofackerMiehe:2012,HofackerMiehe:2013}. Since then, phase-field models have been used to study various real-world dynamic fracture problems, see for example the work of \\cite{BordenVerhooselScottHughesLandis:2012,SchlueterWillenbuecherKuhnMueller:2014}. The governing equations are similar to that derived from the variational principles for the gradient damage model. In particular, the evolution law of the phase-field  lies in on the definition of a \\emph{regularized crack functional} which measures the Griffith's surface energy of the phase-field crack. It turns out that this functional can be regarded as a damage dissipation energy \\eqref{eq:surface} in the gradient-damage terminology with a particular damage constitutive law: the \\eqref{eq:at2} model. Using \\eqref{eq:gcingdcw}, the damage dissipation energy associated with the \\eqref{eq:at2} model reads\n\\[\n\\mathcal{S}(\\alpha_t)=\\int_\\Omega\\frac{\\gc}{2}\\left(\\frac{\\alpha_t^2}{\\eta}+\\eta\\nabla\\alpha_t\\cdot\\nabla\\alpha_t\\right)\\dx\\,,\n\\]\nwhich agrees exactly with that used in \\cite{MieheHofackerWelschinger:2010,MieheWelschingerHofacker:2010,HofackerMiehe:2012,HofackerMiehe:2013,KlinsmannRosatoKamlahMcMeeking:2015}. In \\cite{BordenVerhooselScottHughesLandis:2012,SchlueterWillenbuecherKuhnMueller:2014,MayVignolletBorst:2015}, a non-essential rescaling of the internal length $\\eta=2\\widetilde{\\eta}$ is performed. As stated in \\cref{sec:ingredients}, this constitutive law originates from the Ambrosio and Tortorelli regularization model introduced in \\cite{BourdinFrancfortMarigo:2000} and enjoys hence the desired $\\Gamma$-convergence property. In this respect, these phase-field models correspond to a special case of gradient damage models.\n\nAnother difference between the gradient damage model and these phase-field approaches lies in the irreversibility condition (cf. a discussion on this point in \\cite{AmorMarigoMaurini:2009}). In our approach the damage is assumed to be an irreversible evolution, \\emph{i.e.} $\\dot{\\alpha}_t\\geq 0$. This condition is enforced during the energy minimization principle \\eqref{eq:crackmin} as an optimization constraint prescribed in the damage admissible space \\eqref{eq:Dalphat}. By doing so, \\eqref{eq:crackmin} corresponds to a bound-constrained optimization problem which requires specially designed numerical algorithms. On the contrary, in these phase-field approaches the irreversibility condition is only weakly prescribed:\n\\begin{itemize}\n\\item In \\cite{MieheHofackerWelschinger:2010,MieheWelschingerHofacker:2010,BordenVerhooselScottHughesLandis:2012,KlinsmannRosatoKamlahMcMeeking:2015,MayVignolletBorst:2015} for instance, the irreversible constraint is dropped during energy minimization. The current phase-field corresponds to the solution of the following unconstrained optimization problem\n\\begin{equation} \\label{eq:linearsystem}\n\\mathcal{E}(\\vec{u}_t,\\alpha_t)+\\mathcal{S}(\\alpha_t)\\leq\\mathcal{E}(\\vec{u}_t,\\beta_t)+\\mathcal{S}(\\beta_t)\\text{ for all $\\beta_t$}.\n\\end{equation}\nThe irreversible behaviors of the phase-field is modeled via the introduction of a history field defined by\n\\begin{equation} \\label{eq:historyfield}\n\\mathcal{H}_t=\\max_{s\\leq t}\\psi_0\\bigl(\\eps(\\vec{u}_s)\\bigr)\n\\end{equation}\nwhich records for every material point the maximal undamaged elastic energy density in the history. The growth criterion for the phase field adapted from \\eqref{eq:damageconsis} is then given by\n\\begin{equation} \\label{eq:unconstrained}\n-\\mathsf{a}'(\\alpha_t)\\mathcal{H}_t-w'(\\alpha_t)+\\div\\vec{q}_t=0\\,,\n\\end{equation}\nwhere the history field $\\mathcal{H}_t$ is regarded as the driving force of damage. According to the analyses in \\cite{Amor:2008}, this method can only be applied to the \\eqref{eq:at2} model, since in that case the unconstrained solution $\\alpha_t$ to \\eqref{eq:crackmin} or solved by \\eqref{eq:unconstrained} is necessarily bounded by the interval $[0,1]$. When other sophisticated models are used such as the \\eqref{eq:at1} model, one has to introduce the bound constraints during the minimization procedure.\n\n\\item In \\cite{LancioniRoyer-Carfagni:2009}, one solves the same linear system \\eqref{eq:linearsystem} and then performs an \\emph{a posteriori} projection in the admissible space. It can be considered as a numerical approximation of the real irreversibility condition embedded in the bound-constrained minimization problem. Nevertheless this method is also only limited to the \\eqref{eq:at2} model.\n\n\\item In \\cite{BourdinFrancfortMarigo:2000,SchlueterWillenbuecherKuhnMueller:2014}, the same linear system \\eqref{eq:linearsystem} is solved and one prescribes irreversibility only for totally damaged material points, \\emph{i.e.} where $\\alpha_t(\\vec{x})=1$. According to \\cite{AmorMarigoMaurini:2009}, it can be regarded as a purely numerical approximation of the constrained minimization problem \\eqref{eq:crackmin}. On the other hand, this is also physics-motivated according to \\cite{SchlueterWillenbuecherKuhnMueller:2014}. Nevertheless, the physical motivation behind this weakly reinforced irreversibility originates from an undesired property of the \\eqref{eq:at2} model: that of strain-hardening in the phase-field interval $[0,\\frac{1}{4}]$, see \\cref{fig:at1at2}. This property has already been illustrated theoretically in \\cite{PhamAmorMarigoMaurini:2011} and numerically in \\cite{BordenVerhooselScottHughesLandis:2012} for instance. In this interval \\emph{damage} does not take place since the stress increases with the phase-field, and hence the material behavior should be reversible. However a more natural requirement, that the \\eqref{eq:at1} model satisfies, is the strain-softening behavior for every phase field in the internal $\\alpha\\in(0,1)$. In this case the phase-field retrieves its physical meaning of \\emph{damage}, and one necessarily should introduce the irreversible condition and solve a constrained minimization problem \\eqref{eq:crackmin}.\n\\end{itemize}\n\n\\paragraph{Phase-field model originated from the physics community}\nThe phase-field model studied in \\cite{KarmaKesslerLevine:2001,HakimKarma:2009} constitutes another continuum and regularized approach for quasi-static and dynamic fracture problems. Compared to the gradient damage approach, in these models the phase field evolution is \\emph{viscous} in nature. The governing equations for the phase fields $\\phi$ can be obtained in a semi-variational way from a potential energy $\\mathcal{P}(\\vec{u}_t,\\phi_t)$ defined as the sum of the elastic energy similar to \\eqref{eq:elasticG} and the dissipation energy similar to \\eqref{eq:surface}. Using the notations given in \\cite{HakimKarma:2009}, one has\n\\begin{equation} \\label{eq:PF_phi}\n\\chi^{-1}\\dot{\\phi}_t=-\\frac{\\partial\\mathcal{P}}{\\partial\\phi_t}(\\vec{u}_t,\\phi_t)\\,,\n\\end{equation}\nwhich corresponds to the standard Ginzburg-Landau equation with $\\chi>0$ a kinetic or mobility \\cite{KuhnMuller:2010} coefficient. This parameter controls an \\emph{additional} energy dissipation in the form of heat during the crack propagation, as can be seen by following (corrected) equation based on (13) in \\cite{HakimKarma:2009}\n\\begin{equation} \\label{eq:PF_dissipation}\n\\dot{\\mathcal{H}}_t=-\\chi\\left(\\frac{\\partial\\mathcal{P}}{\\partial\\phi_t}(\\vec{u}_t,\\phi_t)\\right)^2\\leq 0.\n\\end{equation}\nRecall that damage is the only dissipation mechanism in the gradient damage model since an energy balance condition \\eqref{eq:dyngdeb} is added in the formulation.\n\nA parallel consequence of the appearance of a kinetic coefficient $0<\\chi<\\infty$ in \\eqref{eq:PF_phi}, as discussed in \\cite{Bourdin:2011}, is that an evolutionary parabolic equation \\eqref{eq:PF_phi} governing the phase field is coupled with the elliptic static equilibrium problem or the hyperbolic dynamic wave equation. Physically it means that the crack can evolve solely with a rate determined by $\\chi$, even if the structure is in static equilibrium at $t=T$ with all external loading frozen for all $t>T$. With a physical time being introduced into the model (the dimension of the kinetic coefficient is $[\\mathrm{T}]^{-1}$), the coupled system isn't well suited for quasi-static computations, as numerically the static problem should be combined with a specific time-stepping scheme (the explicit Euler scheme in \\cite{HakimKarma:2009}) to integrate the evolution problem for the phase field.\n\n\\subsection{Extension to large displacement situations} \\label{sec:extensions}\nWe discuss a large-displacement extension of the original gradient damage model in an explicit dynamics case. The small displacement condition (small rotation and small strain) is a plausible hypothesis for brittle materials when finite rotations are also not expected in the body. Otherwise geometrical nonlinearities should be taken into account in the definition of the elastic energy \\eqref{eq:elasticG} or more specifically the undamaged elastic energy density \\eqref{eq:psi0}, through the introduction of a nonlinear strain measure.\n\nIn the literature, a Lagrangian strain measure based on the right Cauchy-Green tensor $\\vec{F}_t^\\mT\\vec{F}_t$ is used for the geometrically nonlinear or finite-strain extension of phase-field models, both in the quasi-static case, see \\cite{PieroLancioniMarch:2007,ClaytonKnap:2014,MieheSchaenzel:2014,MieheSchaenzelUlmer:2015} and in the implicit dynamic case, cf. \\cite{HeschWeinberg:2014,MieheHofackerSchaenzelAldakheel:2015}. It is a natural choice since the current configuration $\\Omega_t$ is not known in advance for implicit calculations and the momentum equilibrium is written either in the initial reference configuration $\\Omega=\\Omega_0$ (total Lagrangian formulation) or in the last known reference configuration (updated Lagrangian formulation). In explicit dynamics however, dynamic momentum balance can be directly prescribed in the current known configuration $\\Omega_t=\\vphi_t(\\Omega)$ updated from the last iteration following the explicit temporal discretization scheme. For this reason here we will use the Eulerian Hencky logarithmic strain tensor \\cite{XiaoBruhnsMeyers:1997} defined by\n\\begin{equation} \\label{eq:logstrain}\n\\vec{h}_t=\\vec{h}(\\vec{u}_t)=\\log\\vec{V}_t=\\sum_i(\\log\\lambda_i)\\vec{n}_i\\otimes\\vec{n}_i\n\\end{equation}\nwhere $\\vec{V}_t$ is the left stretch tensor from the polar decomposition of the deformation gradient $\\vec{F}_t=\\mathbb{I}+\\nabla\\vec{u}_t=\\vec{V}_t\\vec{R}_t$ and $(\\lambda_i,\\vec{n}_i)$ denotes a pair of the principal stretch and the corresponding spatial principal directions. Based on this strain measure, a simple Hookean type hyperelastic model \\cite{XiaoChen:2002} is adopted to account for geometric nonlinearities\n\\begin{equation}\n\\psi_0(\\vec{h}_t)=\\frac{1}{2}\\lambda(\\tr\\vec{h}_t)^2+\\mu\\vec{h}_t\\cdot\\vec{h}_t. \\label{eq:soundpsi}\n\\end{equation}\nWe emphasize that the stress measure conjugate to the Hencky logarithmic strain is the Kirchhoff stress, which implies the following definition of the Cauchy stress\n\\begin{equation} \\label{eq:kirchhoffs}\n\\sig_t=\\frac{1}{J_t}\\frac{\\partial\\psi_0}{\\partial\\vec{h}_t}(\\vec{h}_t)=\\frac{1}{J_t}\\bigl(\\lambda(\\tr\\vec{h}_t)\\mathbb{I}+2\\mu\\vec{h}_t\\bigr)\\,,\n\\end{equation}\nwhere $J_t=\\det\\vec{F}_t$ is the Jacobian determinant.\n\nIt should be noted that the variational framework as summarized by \\cref{def:dynagraddama} remains the same. The same energy minimization principle \\eqref{eq:crackmin} can be derived, since the damage problem is naturally defined in the initial reference configuration. On the other hand, by developing the directional derivative of the action integral with respect to $\\vec{u}$ similar to \\eqref{eq:actionu} and supposing that the displacement field is sufficiently regular in time and in space, the elastic-damage dynamic wave equation can be derived in the \\emph{deformed} configuration $\\Omega_t=\\vphi_t(\\Omega)$, which reads\n\\begin{equation} \\label{eq:waveeq}\n\\rho_t\\ddot{\\vec{u}}_t-\\div\\sig_t=\\overline{\\vec{f}}_t\\quad\\text{in $\\Omega_t$}\\quad\\text{and}\\quad\\sig_t\\vec{n}=\\overline{\\vec{F}}_t\\quad\\text{on $\\vphi_t(\\partial\\Omega_F)$}\\,,\n\\end{equation}\nwhere $\\rho_t=\\rho/J_t$ is the density in the current configuration and the external power potential is also transformed to the deformed configuration according to \\cite{Ciarlet:1993aa}:\n\\[\n\\overline{\\mathcal{W}}_t(\\vec{w}_t)=\\int_{\\Omega_t}\\overline{\\vec{f}}_t\\cdot\\vec{w}_t\\dx+\\int_{\\vphi_t(\\partial\\Omega_F)}\\overline{\\vec{F}}_t\\cdot\\vec{w}_t\\ds.\n\\]\nTo obtain \\eqref{eq:waveeq}, the work conjugacy condition satisfied by the Hencky's hyperelastic model is used, see \\cite{XiaoChen:2002}. Specifically, we have\n\\begin{equation} \\label{eq:workconjugacy}\n\\dot{w}_t=\\vtau_t\\cdot\\vec{D}_t=\\vtau_t\\cdot\\dot{\\vec{h}}_t\\implies\\vtau_t\\cdot\\symgrad\\vec{v}_t=\\vtau_t\\cdot\\vec{h}'(\\vec{u}_t)\\vec{v}_t\n\\end{equation}\nwhere $\\dot{w}_t$ is the rate of work per unit volume in the reference configuration and $\\vec{D}_t$ is the stretching, \\emph{i.e.} the symmetrized part of the velocity gradient $\\nabla\\vec{v}_t=\\dot{\\vec{F}}_t\\vec{F}_t^{-1}$.\n\n\\section{Tension-Compression Asymmetry} \\label{sec:TC}\nIn this section we will discuss several approaches in an attempt to account for the tension-compression asymmetry of damage behavior of materials. The objective is to provide a better understanding of the existing models following a theoretical approach and to point out some improvements that can be done in the future. Both approaches from the gradient damage community and the phase-field community will be analyzed. The thematic subjects covered here are thus summarized in \\cref{tab:summTC}.\n\\begin{table}[htbp]\n\\centering\n\\caption{Thematic subjects covered in this section} \\label{tab:summTC}\n\\begin{tabular}{ccccc} \\toprule\n& Going dynamical & $\\alpha\\leftrightarrow\\phi$ & $\\nabla\\alpha\\to\\Gamma$ & Experimental validation \\\\ \\midrule\nTheoretics & & \\rightthumbsup & & \\\\\nNumerics & & & & \\\\ \\bottomrule\n\\end{tabular}\n\\end{table}\n\n\\subsection{Review of existing models} \\label{sec:reviewTC}\nIn general two possibilities can be considered: modification of damage-dependence of the elastic energy density \\eqref{eq:psi0}, and/or modification of the variational principles (of irreversibility, stability and energy balance) outlined in \\cref{def:dynagraddama}. The second approach has been discussed in \\cite{LorentzKazymyrenko:2014,MieheSchaenzelUlmer:2015} where the damage driving force in the sense of $\\mathcal{H}_t$ in \\eqref{eq:unconstrained} deduced from the energy minimization principle \\eqref{eq:crackmin} is replaced by, for example, some stress-based criteria. However it is known from \\cite{SicsicMarigo:2013} that the variational formulation plays an essential role in establishing the link between damage and fracture and in the definition of a generalized energy release rate with respect to the crack extension. That's why only the first possibility will be discussed in this section. For notational simplicity, we place ourselves at a particular material point $\\vec{x}$ characterized by a strain tensor $\\eps=\\eps(\\vec{u}_t)(\\vec{x})$ and a current damage state $\\alpha=\\alpha_t(\\vec{x})$.\n\nSeveral existing approaches consist of \\emph{additively} partitioning the sound elastic energy density $\\psi_0$ in \\eqref{eq:psi0} into two parts: a \\emph{positive} part $\\psi_0^+(\\eps)$ which is assumed to contribute to damage, and the \\emph{negative} part $\\psi_0^-(\\eps)$ which resists damage. The elastic energy density in \\eqref{eq:psi0} being acted symmetrically in tension and compression by damage is then replaced by the expression\n\\begin{equation} \\label{eq:elasticTC}\n\\psi(\\eps,\\alpha)=\\mathsf{a}(\\alpha)\\psi_0^+(\\eps)+\\psi_0^-(\\eps)\n\\end{equation}\nwhere the damage degradation function $\\mathsf{a}(\\alpha)$ only acts on the \\emph{positive} part $\\psi_0^+(\\eps)$. By doing so, damage evolution is then driven by the \\emph{positive} elastic energy according to \\eqref{eq:crackmin}.\n\nFurthermore, if the partition of the sound elastic energy $\\psi_0(\\eps)$ is based on that of the strain tensor $\\eps=\\eps^++\\eps^-$, \\emph{i.e.} the constitutive behaviors\n\\begin{equation} \\label{eq:elasdecom}\n\\begin{aligned}\n\\eps^\\pm &\\mapsto \\psi_0^\\pm(\\eps^\\pm)=\\frac{1}{2}\\tens{A}_0\\eps^\\pm\\cdot\\eps^\\pm, \\\\\n\\eps^\\pm &\\mapsto \\sig_0^\\pm(\\eps^\\pm)=\\tens{A}_0\\eps^\\pm\n\\end{aligned}\n\\end{equation}\nare characterized by the same elasticity tensor $\\tens{A}_0$ both for the \\emph{positive} and \\emph{negative} strains, then there exists in fact a local variational principle from which several existing tension-compression asymmetry models can be derived. This formulation is adapted from \\cite{FreddiRoyer-Carfagni:2010} where the framework of \\emph{structured deformations} is used to decompose the strain tensor into an elastic part and an inelastic one related to microstructures which in our notation is given by $\\alpha\\eps^+$. However here we confine ourselves to macroscopic modeling and interpret the \\emph{positive} strain $\\eps^+$ as the part that merely contributes to local material degradation. The mechanical modeling of such \\emph{positive} strains will be encapsulated into a \\emph{convex} subset $\\mathcal{C}$ of all symmetric 2nd-order tensors. The effective computation of $\\eps^+\\in\\mathcal{C}$ is determined by the following local variational requirement for every material point\n\\begin{equation} \\label{eq:variationalepspos}\n\\norm{\\eps^+-\\eps}_{\\tens{A}_0}=\\min_{\\vec{e}\\in\\mathcal{C}}\\norm{\\vec{e}-\\eps}_{\\tens{A}_0}=\\min_{\\vec{e}\\in\\mathcal{C}}\\tens{A}_0(\\eps-\\vec{e})\\cdot(\\eps-\\vec{e}).\n\\end{equation}\nOwing to the convexity of $\\mathcal{C}$, the \\emph{positive} strain $\\eps^+$ is unique and is defined as the orthogonal projection of the total strain $\\eps$ onto the space $\\mathcal{C}$ with respect to the energy norm defined by the elasticity tensor $\\tens{A}_0$. From convex analysis it is known that $\\eps^+$ that satisfies \\eqref{eq:variationalepspos} can be equivalently characterized by\n\\begin{equation} \\label{eq:vipos}\n-\\tens{A}_0(\\eps-\\eps^+)\\cdot(\\vec{e}-\\eps^+)\\geq0\\text{ for all $\\vec{e}\\in\\mathcal{C}$}.\n\\end{equation}\nwhich implies from the definition \\eqref{eq:elasdecom} that the negative sound stress $\\sig_0^-=\\tens{A}_0\\eps^-$ is in the polar cone $\\mathcal{C}^*=\\set{\\vec{e}^*|\\vec{e}^*\\cdot\\vec{e}\\leq 0\\text{ for all $\\vec{e}\\in \\mathcal{C}$}}$. If the space $\\mathcal{C}$ is also a cone, \\emph{i.e.} closed with respect to arbitrary positive rescaling $\\alpha\\vec{e}$ for $\\alpha>0$, then testing \\eqref{eq:vipos} with $\\vec{e}=2\\eps^+$ and $\\vec{e}=\\frac{1}{2}\\eps^+$ furnishes along with the symmetry of $\\tens{A}_0$ the following orthogonality conditions\n\\begin{equation} \\label{eq:orthogonality}\n\\begin{aligned}\n\\sig_0^-\\cdot\\eps^+ &= \\tens{A}_0(\\eps-\\eps^+)\\cdot\\eps^+=0, \\\\\n\\sig_0^+\\cdot\\eps^- &= \\tens{A}_0(\\eps-\\eps^-)\\cdot\\eps^-=0.\n\\end{aligned}\n\\end{equation}\nThis implies that $\\psi_0^+$ and $\\psi_0^-$ defined in \\eqref{eq:elasdecom} constitute indeed a partition of the sound elastic energy density\n\\[\n2\\psi_0(\\eps)=\\tens{A}_0\\eps\\cdot\\eps=\\sig_0^+\\cdot\\eps^++\\sig_0^-\\cdot\\eps^-\n\\]\nwhere the crossed terms disappear thanks to \\eqref{eq:orthogonality}. This provides another interpretation of \\eqref{eq:variationalepspos} from a mechanical point of view: the \\emph{positive} part of the strain minimizes the \\emph{negative} part of the elastic energy $\\sig_0^-\\cdot\\eps^-$ that resists to damage.\n\n\\begin{remark}\nThe orthogonality conditions \\eqref{eq:orthogonality} are nothing but Moreau's decomposition theorem \\cite{Moreau:1962}.\n\\end{remark}\n\n\\begin{remark}\nThis variational principle \\eqref{eq:variationalepspos} is similar in essence to that initially proposed in \\cite{Ortiz:1985} for the modeling of microcracks. Here the damage mechanism is based on the partition of a given strain tensor (or the elasticity tensor), however in \\cite{Ortiz:1985} the external stress tensor is regarded as an input and a decomposition of the compliance tensor is performed.\n\\end{remark}\n\nWe now turn to the stress tensor derived from \\eqref{eq:elasticTC} and \\eqref{eq:elasdecom}. In general we should have by definition\n\\begin{equation} \\label{eq:sige}\n\\sig(\\eps,\\alpha)\\vec{e}=\\mathsf{a}(\\alpha)\\sig_0^+\\cdot\\frac{\\partial\\eps^+}{\\partial\\eps}(\\eps)\\vec{e}+\\sig_0^-\\cdot\\frac{\\partial\\eps^-}{\\partial\\eps}(\\eps)\\vec{e}\n\\end{equation}\nwhere derivatives of the decomposed strains $\\eps^\\pm$ with respect to the total strain appear. Fortunately, as $\\partial_{\\eps}\\eps^+\\in\\mathcal{C}$ and $\\partial_{\\eps}\\sig_0^-\\in\\mathcal{C}^*$, we have due to \\eqref{eq:vipos}\n\\begin{equation} \\label{eq:crossed}\n\\sig_0^-\\cdot\\frac{\\partial\\eps^+}{\\partial\\eps}(\\eps)\\vec{e}\\leq 0\\text{ and }\\sig_0^+\\cdot\\frac{\\partial\\eps^-}{\\partial\\eps}(\\eps)\\vec{e}\\leq 0.\n\\end{equation}\nBy differentiating the orthogonality condition \\eqref{eq:orthogonality} with respect to the total strain $\\eps$, we find that the sum of the above two non-positive inner products equals to zero, which implies individually that these two expressions in \\eqref{eq:crossed} vanish. Recalling $\\eps=\\eps^++\\eps^-$, the stress tensor is readily identified from \\eqref{eq:sige}\n\\begin{equation} \\label{eq:stressposneg}\n\\sig_t=\\sig(\\eps,\\alpha)=\\mathsf{a}(\\alpha)\\sig_0^++\\sig_0^-.\n\\end{equation}\nThis is the stress expression $\\sig_t$ which will be used in the elastic-damage dynamic wave equation \\eqref{eq:weakform} or \\eqref{eq:wavedyn} when tension-compression asymmetry is considered. It can be noted that this expression is reduced to its negative part $\\sig(\\eps,1)=\\sig_0^-\\in\\mathcal{C}^*$ for a totally damaged element.\n\n\\begin{remark}\nThe tension-compression split described above, especially the additive strain decomposition \\eqref{eq:elasdecom}, applies only to the small displacement case. However it can be extended to the large displacement framework outlined in \\cref{sec:extensions}.\n\nAssume that the additive strain decomposition is performed with respect to a same basis, \\emph{i.e.} the positive/negative strain $\\eps^\\pm$ is coaxial to the total strain $\\eps$, then the definition of the Hencky logarithmic strain $\\eps=\\vec{h}_t$ implies (see \\eqref{eq:logstrain})\n\\begin{align*}\n\\eps &= \\eps^++\\eps^- \\\\\n&= \\sum_i(\\log\\lambda_i)\\vec{n}_i\\otimes\\vec{n}_i=\\sum_i(\\log\\lambda_i^++\\log\\lambda_i^-)\\vec{n}_i\\otimes\\vec{n}_i=\\sum_i\\bigl(\\log(\\lambda_i^+\\lambda_i^-)\\bigr)\\vec{n}_i\\otimes\\vec{n}_i.\n\\end{align*}\nThus, an additive decomposition of the logarithmic strain becomes automatically a multiplicative decomposition of the principal stretches\n\\[\n\\lambda_i=\\lambda_i^+\\lambda_i^-.\n\\]\nThis strategy is adopted for example in \\cite{HeschWeinberg:2014}. Note that the coaxiality between $\\eps^\\pm$ and $\\eps$ is generally verified in the current variational principle \\eqref{eq:variationalepspos}, if elastic isotropy is assumed.\n\nSince the stress measure conjugate to the Hencky logarithmic strain is the Kirchhoff stress, see \\eqref{eq:kirchhoffs}. The stress expression \\eqref{eq:stressposneg} becomes\n\\[\n\\sig_t=\\sig(\\eps,\\alpha)=\\frac{1}{J}(\\mathsf{a}(\\alpha)\\tens{A}_0\\eps^++\\tens{A}_0\\eps^-)\\,,\n\\]\nwhere $J$ refers to the Jacobian determinant of the total strain, for the particular material point under question.\n\\end{remark}\n\nUsing this variational formulation \\eqref{eq:variationalepspos}, the modeling of material tension-compression asymmetry is thus reduced to the setting of such convex cone $\\mathcal{C}$ destined to represent the strains that contribute to damage. Several existing phase-field like models of fracture can be derived within this framework \\cite{FreddiRoyer-Carfagni:2010}.\n\\begin{itemize}\n\\item The original symmetric model of \\cite{BourdinFrancfortMarigo:2000} can be trivially obtained by choosing $\\mathcal{C}$ to all symmetric 2nd-order tensors. From \\eqref{eq:vipos} it can be deduced that $\\eps^+=\\eps$, \\emph{i.e.} the total strain contributes to damage irrespective of whether it corresponds to traction or compression.\n\n\\item The deviatoric model of \\cite{LancioniRoyer-Carfagni:2009} is retrieved when $\\mathcal{C}$ represents all symmetric 2nd-order tensors that have a zero trace (and the condition that $\\tens{A}_0$ is isotropic). Only the deviatoric part of the strain participates to damage, \\emph{i.e.} $\\eps^+=\\dev\\eps$. The negative stress $\\sig_0^-$ belongs to the polar cone of $\\mathcal{C}$ which is characterized by a zero deviatoric part. Thus for a totally damaged material point the stress is hydrostatic and has the form $p\\mathbb{I}$ for $p\\in\\mathbb{R}$.\n\n\\item The model of \\cite{AmorMarigoMaurini:2009} is a combination of the previous two models. If the total strain corresponds to an expansion $\\tr\\eps\\geq 0$, the damage mechanism is completely active and $\\mathcal{C}$ corresponds to all symmetric 2nd-order tensors. However if a compressive strain is present $\\tr\\eps< 0$, only the deviatoric part of the strain participates to damage ($\\eps^+=\\dev\\eps$) and $\\mathcal{C}$ corresponds to all symmetric 2nd-order tensors that have a zero trace. In this case a totally damaged material point experiences a compressive hydrostatic pressure $p\\mathbb{I}$ for $p\\leq 0$.\n\n\\item The masonry-like model of \\cite{FreddiRoyer-Carfagni:2010} is obtained when $\\mathcal{C}$ is chosen to include all positive semidefinite symmetric tensors. Since $\\mathcal{C}$ is a convex cone, the stress tensor can be simplified to \\eqref{eq:stressposneg} and hence the stress that can be attained by a totally damaged material point is necessarily negative semidefinite, corresponding in fact to materials that do not support tension \\cite{PieroLancioniMarch:2007}. However the model as suggested by \\cite{FreddiRoyer-Carfagni:2010} with $\\mathcal{C}$ containing all symmetric tensors of which all eigenvalues are greater than -1 may present some difficulties, as the orthogonality condition \\eqref{eq:orthogonality} and the simplified stress expression \\eqref{eq:stressposneg} no longer apply, $\\mathcal{C}$ not being closed with respect to arbitrary positive rescaling.\n\\end{itemize}\n\nFor the masonry-like model \\cite{FreddiRoyer-Carfagni:2010}, an explicit formula of the positive strain $\\eps^+$ as a function of the total strain $\\eps$ is obtained for both two-dimensional or three-dimensional problems in the isotropic case. The solution is derived from the minimization structure \\eqref{eq:variationalepspos} or equivalently the variational inequality \\eqref{eq:vipos}. The coaxiality between $\\eps^+$ and $\\eps$ is also exploited due to isotropy, see \\cite{Del:1989,AlfanoRosatiValoroso:2000}. In the three dimensional case $\\eps^+$ can be calculated according to \\cref{algo:epspos3d}. In the plane strain or plane stress case, \\cref{algo:epspos2d} can be used, where the strain space is partitioned into four subdomains, see \\cref{fig:epspos2dill}. It can be observed that due to the use of the $\\tens{A}_0$-norm during minimization \\eqref{eq:variationalepspos}, the function $\\eps\\mapsto\\eps^+$ depends on the Poisson's ratio.\n\\begin{algorithm}[htbp]\n\\caption{Explicit formula for $\\eps^+$ as a function of $\\eps$ for the masonry-like model \\cite{FreddiRoyer-Carfagni:2010} in the three-dimensional case according to \\cite{Sacco:1990}} \\label{algo:epspos3d}\n\\begin{algorithmic}[1]\n\\State Perform a spectral decomposition of the total strain $\\eps=(\\varepsilon_1,\\varepsilon_2,\\varepsilon_3)$ with $\\varepsilon_1\\geq\\varepsilon_2\\geq\\varepsilon_3$\n\\If{$\\varepsilon_3\\geq 0$}\n  \\State $\\eps^+\\gets\\eps$\n\\ElsIf{$\\varepsilon_2+\\nu\\varepsilon_3\\geq 0$}\n  \\State $\\eps^+\\gets(\\varepsilon_1+\\nu\\varepsilon_3,\\varepsilon_2+\\nu\\varepsilon_3,0)$ in the same principal basis as $\\eps$\n\\ElsIf{$(1-\\nu)\\varepsilon_1+\\nu(\\varepsilon_2+\\varepsilon_3)\\geq 0$}\n  \\State $\\eps^+\\gets(\\varepsilon_1+\\frac{\\nu}{1-\\nu}(\\varepsilon_2+\\varepsilon_3),0,0)$ in the same principal basis as $\\eps$\n\\Else\n  \\State $\\eps^+\\gets\\vec{0}$\n\\EndIf\n\\State Transform $\\eps^+$ back to the canonical basis if necessary\n\\end{algorithmic}\n\\end{algorithm}\n\\begin{algorithm}[htbp]\n\\caption{Explicit formula for $\\eps^+$ as a function of $\\eps$ for the masonry-like model \\cite{FreddiRoyer-Carfagni:2010} in the two-dimensional case according to \\cite{AlfanoRosatiValoroso:2000}} \\label{algo:epspos2d}\n\\begin{algorithmic}[1]\n\\State Perform a spectral decomposition of the total strain $\\eps=(\\varepsilon_1,\\varepsilon_2)$ with $\\varepsilon_1\\geq\\varepsilon_2$\n\\If{Plane strain case}\n  \\State $\\alpha=\\nu/(1-2\\nu)$\n\\Else\n  \\State $\\alpha=\\nu/(1-\\nu)$\n\\EndIf\n\\If{$\\varepsilon_2\\geq 0$}\n  \\State $\\eps^+\\gets\\eps$\n\\ElsIf{$(1+\\alpha)\\varepsilon_1+\\alpha\\varepsilon_2\\geq 0$}\n  \\State $\\eps^+\\gets(\\varepsilon_1+\\frac{\\alpha}{1+\\alpha}\\varepsilon_2,0)$ in the same principal basis as $\\eps$\n\\Else\n  \\State $\\eps^+\\gets\\vec{0}$\n\\EndIf\n\\State Transform $\\eps^+$ back to the canonical basis if necessary\n\\end{algorithmic}\n\\end{algorithm}\n\\begin{figure}[htbp]\n\\includegraphics[width=0.5\\textwidth]{epspos2d.pdf}\n\\caption{Calculation of $\\eps^+$ for the masonry-like model \\cite{FreddiRoyer-Carfagni:2010} in the plane strain case} \\label{fig:epspos2dill}\n\\end{figure}\n\nThe tension-compression asymmetry model of \\cite{MieheHofackerWelschinger:2010}, that is widely used among the phase field community in for instance \\cite{HofackerMiehe:2012,BordenVerhooselScottHughesLandis:2012,KlinsmannRosatoKamlahMcMeeking:2015,MayVignolletBorst:2015}, adopts the elastic energy density split \\eqref{eq:elasticTC} but does not fit into the variational formalism \\eqref{eq:variationalepspos}. Denoting $\\eps^+$ (resp. $\\eps^-$) as the positive (resp. negative) part of the total strain obtained by projecting $\\eps$ onto the space of all symmetric positive (resp. negative) semidefinite tensors \\emph{with respect to the natural Frobenius norm}, their model reads\n\\begin{equation} \\label{eq:miehe}\n\\begin{aligned}\n\\psi_0^\\pm(\\eps) &= \\frac{1}{2}\\lambda\\inp{\\tr\\eps}_\\pm^2+\\mu\\eps_\\pm\\cdot\\eps_\\pm, \\\\\n\\sig_0^\\pm(\\eps) &= \\lambda\\inp{\\tr\\eps}_\\pm\\mathbb{I}+2\\mu\\eps_\\pm\n\\end{aligned}\n\\end{equation}\nwhere contrary to the formulation \\eqref{eq:elasdecom} there is no more individual constitutive relation separately for the positive or the negative strain. The function $\\eps\\mapsto\\eps^+$ no longer depends on the Poisson's ratio. The orthogonality condition \\eqref{eq:orthogonality} is not satisfied, however a partition of the sound elastic energy $\\psi_0=\\psi_0^++\\psi_0^-$ is achieved. It is due to the fact that the positive bracket operator applies to the trace of the strain tensor. Despite its variational inconsistency, the stress for a totally damaged element is also negative semidefinite as for the model of \\cite{FreddiRoyer-Carfagni:2010}. The qualitative differences between these two models will be illustrated in the following section.\n\n\\subsection{Uniaxial traction and compression experiment} \\label{sec:uniaxial}\nHere we will investigate the theoretical behavior of the above outlined models under a very simple loading condition to illustrate their individual particularities. It can be understood that the underlying \\emph{local} damage model obtained by suppressing the gradient damage $\\nabla\\alpha_t$ in the dissipation energy density \\eqref{eq:surface} represents the material behavior when no strain or damage localization appears. Hence some general properties of these tension-compression asymmetry models can be extracted under an academic homogeneous 3-dimensional uniaxial traction or compression experiment. Inertia is not essential for this analysis and will be neglected. We suppose that the stress tensor is of form $\\sig_t=\\sigma_{33}\\vec{e}_3\\otimes\\vec{e}_3$ corresponding to an imposed axial strain $\\varepsilon_{33}=t$ viewed as a loading parameter. Since $\\tens{A}_0$ is isotropic, the goal is to find the evolutions of the transversal strain $t\\mapsto\\varepsilon_{11}=\\varepsilon_{22}$, the axial stress $t\\mapsto\\sigma_{33}$ and the homogeneous damage $t\\mapsto \\alpha_t$. This amounts to solve the following system when the damage evolves $\\dot{\\alpha}_t>0$\n\\begin{subequations} \\label{eq:1dsystem}\n\\begin{align}\n& \\sigma_{11}(t)=\\bigl(\\mathsf{a}(\\alpha_t)\\sig_0^++\\sig_0^-\\bigr)\\vec{e}_1\\cdot\\vec{e}_1=0, \\label{eq:eps11as33} \\\\\n& \\frac{\\partial\\psi}{\\partial\\alpha_t}(\\eps_t,\\alpha_t)+w'(\\alpha_t)=0 \\label{eq:damagecrit}\n\\end{align}\n\\end{subequations}\nwhere $\\eps_t=\\varepsilon_{11}(\\vec{e}_1\\otimes\\vec{e}_1+\\vec{e}_2\\otimes\\vec{e}_2)+t\\vec{e}_3\\otimes\\vec{e}_3$. The second equation \\eqref{eq:damagecrit} corresponds to the consistency condition \\eqref{eq:damageconsis}.\n\nWe remark that in order to solve \\eqref{eq:1dsystem} a particular set of damage constitutive laws also has to be chosen. Strictly speaking the functions $\\alpha\\mapsto \\mathsf{a}(\\alpha)$ and $\\alpha\\mapsto w(\\alpha)$ should influence the exact behavior of the tension-compression asymmetry models. Nevertheless we discover that the solutions obtained with two particular damage constitutive laws \\eqref{eq:at1} and \\eqref{eq:at2} share many qualitative properties.\n\nThe model of \\cite{AmorMarigoMaurini:2009} has been already studied in this uniaxial traction and compression setting with the damage model \\eqref{eq:at2}. The material undergoes a softening behavior both under tension or compression when a certain \\emph{finite} threshold $\\sigma_0^\\pm$ is reached. The ratio between these two maximal stresses is given by\n\\[\n-\\frac{\\sigma_0^-}{\\sigma_0^+}=\\sqrt{\\frac{3}{2(1+\\nu)}}\\leq\\sqrt{\\frac{3}{2}}\\approx 1.22\n\\]\nwhich is not sufficient for applications to brittle materials where this factor can attain 10. This ratio is the same when the damage constitutive law \\eqref{eq:at1} is used.\n\nWe then turn to the tension-compression separation proposed in \\cite{MieheHofackerWelschinger:2010}. Similar as it is to the model of \\cite{FreddiRoyer-Carfagni:2010} since both ones perform spectral decomposition of the total strain (with respect to two different inner products, though), their behavior under compression will be unexpectedly different. For the constitutive model of \\eqref{eq:at1}, the material remains intact until a tensile $\\sigma_0^+$ or a compressive $\\sigma_0^-$ stress threshold is reached\n\\begin{align*}\n\\sigma_0^+ &= \\sqrt{\\frac{(1+\\nu)}{(1-\\nu)(1+2\\nu)}w_1E}, \\\\\n\\sigma_0^- &= -\\sqrt{\\frac{1+\\nu}{2\\nu^2}w_1E}\\to\\infty\\text{ as $\\nu\\to 0$}.\n\\end{align*}\nIt can be seen that the critical stress $\\sigma_0^+$ increases with the Poisson ratio but stays bounded in tension. The compressive threshold $\\sigma_0^-$ goes to infinity when $\\nu$ is near zero, hence no damage will occur in this case. We use the tensile threshold $\\sigma_0^+$ as well as its corresponding strain $\\varepsilon_0^+$ both evaluated at $\\nu=0.2$ to normalize the results shown in \\cref{fig:miehe}.\n\\begin{figure}[htbp]\n\\centering\n\\includegraphics[width=\\textwidth]{TC5.pdf}\n\\caption{Uniaxial traction $\\varepsilon_{33}\\geq 0$ and compression $\\varepsilon_{33}\\leq 0$ experiment for the tension-compression asymmetry proposed in \\cite{MieheHofackerWelschinger:2010}. The damage constitutive law \\eqref{eq:at1} is used} \\label{fig:miehe}\n\\end{figure}\n\nRemark that under a uniaxial tensile loading, the material undergoes a classical softening behavior when the threshold stress is reached. For quasi-incompressible materials $\\nu\\approx\\frac{1}{2}$ a snap-back is present and hence the evolution of the stress $\\sigma_{33}$ and the strain $\\varepsilon_{11}$ may experience a temporal discontinuity. However this behavior is only limited to the law \\eqref{eq:at1} whereas for \\eqref{eq:at2} no snap-back is observed. Unexpectedly, under compression the material may experience a two-phase softening-hardening (with an initial snap-back for $0\\leq \\nu\\leq 3/8$ limited to the \\eqref{eq:at1} case), while the damage increases. As $\\alpha_t$ approaches 1, \\emph{i.e.} as the material point becomes totally damaged, the uniaxial stress is not bounded and is given by $\\sigma_{33}=2\\mu\\varepsilon_{33}$. Moreover, an apparent incompressible behavior is observed $\\tr\\eps_t=0$. These properties can be readily derived using the definitions \\eqref{eq:miehe}. Due to a non-vanishing stress inside a completely damaged element, one may expect large diffusive ``damage'' for highly compressive zones. This may complicate the physical interpretation of the model of \\cite{MieheHofackerWelschinger:2010} in this situation.\n\nIn contrast, for any damage constitutive laws the model proposed in \\cite{FreddiRoyer-Carfagni:2010} does not permit any damage under uniaxial compression. The positive strain contributing to damage after projection \\eqref{eq:variationalepspos} is given by $\\eps^+=(\\varepsilon_{11}+\\nu\\varepsilon_{33})(\\vec{e}_1\\otimes\\vec{e}_1+\\vec{e}_2\\otimes\\vec{e}_2)$, which vanishes due to the uniaxial stress state $\\sig_t=\\sigma_{33}\\vec{e}_3\\otimes\\vec{e}_3$ implying $\\varepsilon_{11}=-\\nu\\varepsilon_{33}$. Under traction and when using the damage law \\eqref{eq:at1}, a stress threshold under which no damage appears is given by\n\\[\n\\sigma_0^+=\\sqrt{\\frac{(1-\\nu)}{(1-2\\nu)(1+\\nu)}w_1E}\\to\\infty\\text{ as $\\nu\\to\\frac{1}{2}$}\n\\]\nso cracks cannot appear for incompressible materials. We again use the tensile stress threshold $\\sigma_0^+$ as well as its corresponding strain $\\varepsilon_0^+$ both evaluated at $\\nu=0.2$ to normalize the results shown in \\cref{fig:freddi}. A classical softening behavior is observed after damage initiation. Analyses show that snapbacks are present for $\\nu>(\\sqrt{33}-1)/16\\approx 0.3$. However it is only limited to the \\eqref{eq:at1} case.\n\\begin{figure}[htbp]\n\\centering\n\\includegraphics[width=0.98\\textwidth]{TC6.pdf}\n\\caption{Uniaxial traction $\\varepsilon_{33}\\geq 0$ experiment for the tension-compression asymmetry proposed in \\cite{FreddiRoyer-Carfagni:2010}. The damage constitutive law \\eqref{eq:at1} is used} \\label{fig:freddi}\n\\end{figure}\n\n\\subsection{How to choose among different models} \\label{sec:howtochoose}\nFollowing the previous review and analyses of several existing models on tension-compression asymmetry, a natural question arises as to how to choose the \\emph{best} or the \\emph{right} one for a particular problem. If the variational formulation \\eqref{eq:variationalepspos} is used, the problem can be reduced to choose a \\emph{good} convex cone $\\mathcal{C}$ of the 2nd-order symmetric tensors. As the elastic energy density split \\eqref{eq:elasticTC} influences both the displacement and the damage problems through the first order stability condition \\eqref{eq:vi}, these two aspects will be separately discussed.\n\\begin{itemize}\n\\item For the $\\vec{u}$-problem, the tension-compression asymmetry model is widely recognized to \\emph{approximate} the material non-interpenetration condition \\cite{LancioniRoyer-Carfagni:2009,AmorMarigoMaurini:2009,AmbatiGerasimovLorenzis:2015}. However we would like to recall that this approximation is merely heuristic. Taking into account the actual non-interpenetration condition at finite strains in the sense of \\cite{CiarletNecas:1987}, \\emph{i.e.} local orientation preservation and global injectivity, is a difficult task both from a theoretical or numerical point of view, and hence is often merely checked \\emph{a posteriori}. Nevertheless we could expect that the tension-compression decomposition \\emph{itself} should depend on the local damage state and the damage gradient $\\nabla\\alpha_t$ approximating the local crack normal in the reference frame. A better elastic energy density split of \\eqref{eq:elasticTC} could be\n\\begin{equation}\n\\psi(\\eps,\\alpha,\\nabla\\alpha)=\\mathsf{a}(\\alpha)\\psi_0^+(\\eps,\\alpha,\\nabla\\alpha)+\\psi_0^-(\\eps,\\alpha,\\nabla\\alpha).\n\\end{equation}\nWhen the crack is created, the elastic energy split \\emph{itself} should become orientation dependent so that only non-positive normal stress can be applied on crack lips if friction is not considered. This point will be illustrated in several numerical experiments.\n\n\\item For the $\\alpha$-problem, the decomposition \\eqref{eq:elasticTC} directly controls the type of strain or stress state which initiates and produces further damage: deviatoric part in \\cite{LancioniRoyer-Carfagni:2009} or in \\cite{PhamAmorMarigoMaurini:2011} under compression and positive principal values in  \\cite{MieheHofackerWelschinger:2010,FreddiRoyer-Carfagni:2010}. We share the remark given in \\cite{AmbatiGerasimovLorenzis:2015} that only experiments conducted with real materials can determine or identify a \\emph{good} model. We thus regard the elastic energy split \\eqref{eq:elasticTC} or the convex cone $\\mathcal{C}$ as another independent material property or parameter characterizing the microstructure. For rocks or stones the deviatoric model may predict realistic crack path, however for more brittle materials such as concrete or glass, models based on a spectral decomposition may be more suitable.\n\\end{itemize}\n\n\\section{Griffith's Law in Gradient Damage Models} \\label{sec:linkDF}\nThe author proposes in this section to investigate the link between the dynamic gradient damage model and the classical Griffith's theory of dynamic fracture \\eqref{eq:gtgc} during the crack propagation phase. The major difficulty lies in the proper definition of an energy release rate (playing the role of $G$) and an equivalent material fracture resistance (playing the role of $\\gc$) in gradient damage models. These concepts involve, generally speaking, the derivative of a certain energy with respect to the crack length, hence the damage zone evolution should be assumed to follow a specific path parametrized by the arc length. Based on an Eulerian approach, authors of \\cite{SicsicMarigo:2013} then identify a generalized damage-dependent Rice's $J$-integral containing these two concepts, which is automatically induced by the variational formulation of quasi-static gradient damage models.\n\nTo accomplish our objective in dynamics, the author proposes a rigorous and systematic methodology of performing the derivative of an energy functional with respect to the crack arc length. It is based on a Lagrangian description in the initial cracked configuration with the help of calculus of variations and shape optimization techniques. The equation of motion of the crack tip predicted by the dynamic gradient damage model is shown to be governed by a generalized Griffith criterion. With the help of a separation of scales, the former derived generalized Griffith criterion admits also an asymptotic interpretation. The thematic subjects covered here are thus summarized in \\cref{tab:summgriffith}.\n\\begin{table}[htbp]\n\\centering\n\\caption{Thematic subjects covered in this section} \\label{tab:summgriffith}\n\\begin{tabular}{ccccc} \\toprule\n& Going dynamical & $\\alpha\\leftrightarrow\\phi$ & $\\nabla\\alpha\\to\\Gamma$ & Experimental validation \\\\ \\midrule\nTheoretics & \\rightthumbsup & & \\rightthumbsup & \\\\\nNumerics & & & & \\\\ \\bottomrule\n\\end{tabular}\n\\end{table}\n\n\\subsection{Lagrangian description in the initial cracked configuration}\nThis section will be devoted to a rigorous energetic approach to deriving dynamic energy release rates. The basic assumptions will be a two-dimensional body $\\Omega$ containing a smoothly propagating crack $\\Gamma_t$ with a pre-defined path $l\\mapsto\\vec{\\gamma}(l)\\in\\mathbb{R}^2$ parametrized by its arc length $t\\mapsto l_t\\geq 0$, see \\cref{fig:philt}. The symbol $\\vec{P}_t=\\vec{\\gamma}(l_t)$ will be used to represent the crack tip at time $t$. The current cracked configuration will be denoted by $\\domaint$ on which the kinematic quantities are defined. For the sake of simplicity, the crack $\\Gamma_t$ is assumed to remain far from the boundary $\\partial\\Omega$. The spatial crack path $l\\mapsto\\vec{\\gamma}(l)$ can be curved but in this contribution we will only consider a straight crack with a constant tangent $\\vec{\\gamma}'(l_t)=\\vtau_t=\\vtau_0$. Generalization to a curved crack path will be briefly discussed at the end of \\cref{chap:griffithrevis}.\n\\begin{remark}\nFor sharp-interface models (Griffith's theory for example), the crack $\\Gamma_t$ refers to an evolving strong discontinuity in the body. For gradient damage models, the crack $\\Gamma_t$ stands for a totally damage zone where $\\alpha_t=1$, see the local damage criterion \\eqref{eq:localdamagefirstorder} and the consistency condition \\eqref{eq:damageconsis}. This interpretation will be formalized in \\cref{hypo:damageband}. The essential requirement here is that the energetic quantities of the body can be written in the current cracked configuration $\\domaint$.\n\\end{remark}\n\\begin{figure}[htbp]\n\\centering\n\\includegraphics[width=0.9\\textwidth]{phi_gtheta.pdf}\n\\caption{Definition of a diffeomorphism $\\philt_{l_t}:\\domaini\\to\\domaint$ transforming the current cracked material configuration $\\domaint$ to the initial one $\\domaini$. It should not be confused with the actual deformation $\\vec{\\varphi}_t$ of the body which takes a particular material point $\\vec{x}\\in\\domaint$ to its spatial location $\\vec{\\varphi}_t(\\vec{x})$ in the deformed configuration $\\vec{\\varphi}_t(\\domaint)$} \\label{fig:philt}\n\\end{figure}\n\nThe displacement $\\vec{u}_t$ is defined in the current crack configuration $\\domaint$, consequently its total variation depends on that of the crack. A Lagrangian description of the fracture problem is thus preferred if one needs to rigorously define an energy release rate with respect to the crack length, see \\cite{Destuynder:1981}. The current cracked \\emph{material} configuration $\\domaint$ is transformed to the initial one $\\domaini$ thanks to a well-defined bijection $\\philt_{l_t}$ whose inverse as well as itself is differentiable, see \\cref{fig:philt}. Proving existence of such diffeomorphisms may be technical \\cite{KhludnevSokolowskiSzulc:2010} and consequently will be directly admitted. This bijection $\\philt_{l_t}$ should not be confused with the actual deformation $\\vec{\\varphi}_t$ of the body which takes a particular material point $\\vec{x}\\in\\domaint$ to its spatial location $\\vec{\\varphi}_t(\\vec{x})$ in the deformed configuration $\\vec{\\varphi}_t(\\domaint)$. Recall that the displacement field $\\vec{u}_t$ is defined by $\\vec{\\varphi}_t(\\vec{x})=\\vec{x}+\\vec{u}_t(\\vec{x})$ for all $\\vec{x}$ in $\\domaint$.\n\nWe can explicit this domain transformation by using a virtual perturbation $\\vtheta^*$ defined on the initial configuration \\cite{Destuynder:1981,KhludnevSokolowskiSzulc:2010}. An example of such virtual perturbations is given in \\cref{fig:exampletheta}.\n\\begin{figure}[htbp]\n\\centering\n\\includegraphics[width=0.55\\textwidth]{thetaGriffith.pdf}\n\\caption{A particular virtual perturbation $\\vtheta^*=\\theta\\vtau_0$ verifying \\cref{def:velocityfield}. It is obtained by solving the Laplace's equation $\\Delta\\theta=0$ inside the crown $r\\leq\\norm{\\vec{x}^*-\\vec{P}_0}\\leq R$ with adequate boundary conditions} \\label{fig:exampletheta}\n\\end{figure}\nThis virtual perturbation should verify the following\n\\begin{definition}[Virtual Perturbation] \\label{def:velocityfield} \\noindent\n\\begin{enumerate}\n\\item It is sufficiently smooth in space to satisfy the definition of a diffeomorphism.\n\\item It represents a virtual crack advance along the current crack propagation direction, that is in our case $\\vtheta^*(\\vec{P}_0)=\\vtau_0$.\n\\item It does not alter the crack lip \\emph{shape}, that is $\\vtheta^*\\cdot\\vec{n}=0$ on the crack lip $\\Gamma_0$ with $\\vec{n}$ the unit normal vector.\n\\item The domain boundary remains invariant, \\emph{i.e.} $\\vtheta^*=\\vec{0}$ on $\\partial\\Omega$.\n\\end{enumerate}\n\\end{definition}\n\nWith an arbitrary virtual perturbation verifying \\cref{def:velocityfield}, we can thus construct the bijection between the initial and current cracked material configurations. In the particular case of a straight crack path, it reads\n\\begin{equation} \\label{eq:philt}\n\\philt_{l_t}:\\vec{x}^*\\mapsto\\vec{x}=\\vec{x}^*+(l_t-l_0)\\vtheta^*(\\vec{x}^*).\n\\end{equation}\nwhere $\\vec{x}=\\philt_{l_t}(\\vec{x}^*)$ denotes the material point $\\vec{x}$ in the current cracked configuration $\\domaint$ associated with the material point $\\vec{x^*}$ in the initial cracked configuration $\\domaini$. For notational simplicity, we will suppress its subscript by writing $\\philt=\\philt_{l_t}$. The (real) displacement field $\\vec{u}_t$ will thus be pulled-back to the initial configuration via the introduced bijection by\n\\begin{equation} \\label{eq:transportofu}\n\\vec{u}_t\\circ\\philt=\\vec{u}_t^*\n\\end{equation}\nfrom which along with \\eqref{eq:philt} we deduce the following useful identities using the classical chain rule\n\\begin{align}\n\\nabla\\vec{u}_t^*(\\vec{x}^*) &= \\nabla\\vec{u}_t(\\vec{x})\\nabla\\philt(\\vec{x}^*)\\,, \\label{eq:grad} \\\\\n\\dot{\\vec{u}}_t^*(\\vec{x}^*) &= \\dot{\\vec{u}}_t(\\vec{x})+\\nabla\\vec{u}_t(\\vec{x})\\dot{l}_t\\vtheta^*(\\vec{x}^*)=\\dot{\\vec{u}}_t(\\vec{x})+\\nabla\\vec{u}_t^*(\\vec{x}^*)\\nabla\\philt(\\vec{x}^*)^{-1}\\dot{l}_t\\vtheta^*(\\vec{x}^*). \\label{eq:v}\n\\end{align}\nAs can be observed, all quantities \\emph{referring} to the initial material configuration $\\domaini$ are indicated by a superscript $(\\cdot)^*$. In particular, the Lebesgue integration measure in $\\domaini$ will be denoted by $\\mathrm{d}\\vec{x^*}$. When spatial or temporal differentiation is present, the pullback operation similar to \\eqref{eq:transportofu} is performed first. Hence in \\eqref{eq:grad}, $\\nabla\\vec{u}_t^*$ denotes the gradient of $\\vec{u}_t^*$ in $\\domaini$, and in \\eqref{eq:v}, $\\dot{\\vec{u}}_t^*$ is understood as the time derivative of the transported displacement.\n\nNote that we can also map the original virtual perturbation $\\vtheta^*$ defined on the initial configuration to the current one, via a pushforward operation\n\\[\n\\vtheta_t=\\vtheta^*\\circ\\philt^{-1}.\n\\]\nAll the properties discussed in \\cref{def:velocityfield} for the initial virtual perturbation should adequately apply for the push-forwarded one by using the current crack tip $\\vec{P}_t=\\philt(\\vec{P}_0)$ and lip $\\Gamma_t$.\n\nBy virtue of \\eqref{eq:grad} and \\eqref{eq:v}, we can thus formulate the energetic quantities of the body $\\Omega$ using the transported displacement in the initial cracked configuration. In \\cref{chap:griffithrevis}, this approach is applied to revisit the Griffith's theory of dynamic fracture reviewed in \\cref{sec:griffithfreund}. The desired evolution laws for the cracked body (elastodynamic equation) and the crack itself (Griffith's law) automatically follow by considering variations of a space-time action integral written in the initial configuration. In particular, a rigorous variational interpretation of the dynamic $J$-integral \\eqref{eq:Jdyn} is obtained: it can be identified by performing the shape derivative of a space-time action integral involving the Griffith's surface energy \\eqref{eq:StGriffith}.\n\n\\subsection{Generalized Griffith criterion for a propagating damage band}\nThis section is devoted to the application of the shape derivative methods to the dynamic gradient damage model outlined in \\cref{def:dynagraddamanew}. An evolution law similar to Griffith's law \\eqref{eq:gtgc} will be obtained which governs the \\emph{crack tip} equation of motion in the gradient damage model. As in \\cite{SicsicMarigo:2013}, we are interested in the smooth dynamic propagation phase of a damage band concentrated along a certain path. An example of such a damage evolution phase is illustrated in \\cref{fig:kalthoffF} where numerical simulations results of an edge-cracked plate under dynamic shearing impact are indicated.\n\\begin{figure}[htbp]\n\\centering\n\\includegraphics[width=0.35\\textwidth]{kalthoff_damage.pdf}\n\\caption{Numerical simulation of an edge-cracked plate under dynamic shearing impact that will be considered in \\cref{sec:kalthoff}. The damage is concentrated inside a band and varies from 0 (blue zones) to 1 (red zones). It serves as a phase-field indicator of the crack propagating currently in the direction of $\\vtau_t$ with its tip located at $\\vec{P}_t$} \\label{fig:kalthoffF}\n\\end{figure}\nWe observe initiation of the edge crack and subsequent propagation of the damage band representing the crack. The objective here is to understand the current crack tip $\\vec{P}_t$ evolution during such \\emph{simple} propagation phase. Complex topology changes such as crack kinking, branching or coalescence indicated by the phase-field $\\alpha_t$ remain beyond the scope of the present section. Formally, we admit the following\n\\begin{hypothesis}[Damage Band Structuration] \\label{hypo:damageband} \\noindent\n\\begin{enumerate}\n\\item The time-dependent totally damaged zone can be described by a pre-defined curve $l\\mapsto\\vec{\\gamma}(l)$ parametrized by its arc-length $l_t$\n\\begin{equation} \\label{eq:graddamalt}\n\\Gamma_t=\\set{\\vec{x}\\in\\Omega|\\alpha_t(\\vec{x})=1}=\\set{\\vec{\\gamma}(l_s)\\in\\mathbb{R}^2|0\\leq s\\leq t}\n\\end{equation}\nwith the current propagation direction given by $\\vtau_t=\\vec{\\gamma}'(l_t)$. For simplicity, similarly to \\cref{chap:griffithrevis}, we only consider a straight crack path with a constant propagation tangent $\\vtau_t=\\vtau_0$, however generalization to smoothly curved crack path is possible (cf. the end of \\cref{chap:griffithrevis}). We focus on the propagation phase when the crack length is much larger than the internal length $\\ell\\ll l_0\\leq l_t$.\n\\begin{figure}[htbp]\n\\centering\n\\includegraphics[width=0.45\\textwidth]{damage_structuration.pdf}\n\\caption{Damage band structuration along a pre-defined path $l\\mapsto\\vec{\\gamma}(l)$ indicating a crack propagating in the direction of $\\vtau_t$ with its tip located at $\\vec{P}_t$} \\label{fig:damage_structuration}\n\\end{figure}\n\n\\item During propagation the damage profile along this curve $l\\mapsto\\vec{\\gamma}(l)$ develops a cross-section of the same order of $\\ell$. The current damage evolution rate $\\dot{\\alpha}_t$ is partitioned into two components: one that contributes to crack advance in the propagation direction, and the other that describes possible profile evolution in the coordinate system that moves with the crack tip $\\vec{P}_t$. Formally, we make use of the diffeomorphism $\\philt$ introduced in \\eqref{eq:philt} that transforms the current cracked configuration to the initial one, in the context of gradient damage models where cracks refer to the totally damaged curve \\eqref{eq:graddamalt}. The evolution of the damage field $\\alpha_t$ is thus given by\n\\begin{equation} \\label{eq:transportofdamage}\n\\alpha_t\\circ\\philt=\\alpha_t^*\n\\end{equation}\nwhere the damage profile field $\\alpha_t^*$ corresponds to an initial crack which remains \\emph{stationary}\n\\[\n\\set{\\vec{x}\\in\\Omega|\\alpha_t^*(\\vec{x})=1}=\\Gamma_0.\n\\]\nThe establishment of such initial damage field which corresponds to $\\Gamma_0$ is beyond the scope of this document. Using the classical chain rule, the time derivative of the damage reads\n\\begin{equation} \\label{eq:alphadot}\n\\dot{\\alpha}_t(\\vec{x})=\\dot{\\alpha}_t^*(\\vec{x}^*)-\\dot{l}_t\\nabla\\alpha_t(\\vec{x})\\cdot\\vtheta_t(\\vec{x})\\,,\n\\end{equation}\nwhich reflects faithfully our partition of the damage rate. Remark that if the crack is arrested $\\dot{l}_t=0$, the total damage rate corresponds to that of the profile evolution.\n\\begin{figure}[htbp]\n\\centering\n\\includegraphics[width=0.85\\textwidth]{pacman_gtheta-bw.pdf}\n\\caption{Propagation of an existing damage band via the diffeomorphism $\\philt$} \\label{fig:pacmangtheta}\n\\end{figure}\n\\end{enumerate}\n\\end{hypothesis}\n\n\\begin{remark}\n\\cref{hypo:damageband} highlights the scope of the current contribution: propagation (or arrest) of an \\emph{initially existing phase-field} crack (damage band), without complex topology changes such as kinking or branching. For illustration purposes, several situations are presented in \\cref{fig:examples}.\n\\begin{enumerate}[(a)]\n\\item The current section focuses on the further propagation of an \\emph{existing damage band} as illustrated in \\cref{fig:examples}(a).\n\n\\item Discrete cracks as a geometric discontinuity in the domain are not to be confused with phase-field like cracks (damage band). The current section does not consider the further ``propagation'' of the tip $\\vec{P}_t$ appearing in \\cref{fig:examples}(b), since the damage field is identically zero $\\alpha_t=0$. The determination of an initial damage field in such cracked domain refers to the phase-field crack nucleation problem, and is subject to the irreversibility condition, the damage criterion \\eqref{eq:localdamagefirstorder} and the consistency condition \\eqref{eq:damageconsis}.\n\n\\item Complex topology changes in the damage band illustrated in \\cref{fig:fiss3} and \\cref{fig:examples}(c) are not considered in this contribution.\n\\end{enumerate}\n\n\\begin{figure}[htbp]\n\\centering\n\\includegraphics[width=0.45\\textwidth]{Li-Fig8.pdf}\n\\caption{Illustrations of the scope of the present contribution: (a) a \\emph{simple} phase-field crack with its tip $\\vec{P}_t$, (b) a \\emph{discrete} crack in the domain with an identically zero damage field $\\alpha_t=0$ and (c) a phase-field crack at \\emph{branching}, leading to the existence of two crack tips (similar to \\cref{fig:fiss3}). The damage field varies from 0 (blue zones) to 1 (red zones). The current section focuses on (a), and studies further propagation of the \\emph{existing phase-field} crack (damage band)} \\label{fig:examples}\n\\end{figure}\n\nFurthermore, the crack path, straight or curved, is assumed to be \\emph{pre-defined}. Crack path prediction is indeed the \\emph{raison d'être} of phase-field models of fracture. A thorough investigation of this point is a very important task to which future work will be devoted. Nevertheless, the current contribution focuses on the behavior of gradient damage models when the crack path is not of concern, which permits a direct comparison with the classical Griffith's theory of dynamic fracture without additional hypotheses, \\emph{i.e.} Griffith's law \\eqref{eq:gtgc}. We concentrate on ``when'' cracks propagate (temporal evolution) and not on ``how'' cracks propagate (spatial evolution).\n\\end{remark}\n\nFrom \\eqref{eq:transportofdamage}, the current damage field $\\alpha_t$ can be considered as a function depending on the current crack length $l_t$ and the current damage profile $\\alpha_t^*$. Using the diffeomorphism we can thus rewrite the space-time action integral \\eqref{eq:actionG} in the initial cracked configuration $\\domaini$, by transforming the displacement via \\eqref{eq:transportofu}. Since we assume that the crack $\\Gamma_t$ (or the totally damaged zone) is of measure zero with respect to $\\mathrm{d}\\vec{x}$ (and hence also to $\\mathrm{d}\\vec{x}^*$), contribution on this subset $\\Gamma_t$ can be neglected. By virtue of \\eqref{eq:grad} and \\eqref{eq:v}, we have\n\\begin{itemize}\n\\item The damage-dependent elastic energy \\eqref{eq:elasticG} is then given by\n\\begin{equation} \\label{eq:elasticGi}\n\\mathcal{E}(\\vec{u}_t,\\alpha_t)=\\mathcal{E}^*(\\vec{u}_t^*,\\alpha_t^*,l_t)=\\int_\\domaini\\psi\\bigl({\\textstyle\\frac{1}{2}}\\nabla\\vec{u}_t^*\\nabla\\philt^{-1}+{\\textstyle\\frac{1}{2}}\\nabla\\philt^{-\\mathsf{T}}(\\nabla\\vec{u}_t^*)^\\mT,\\alpha_t^*\\bigr)\\det\\nabla\\philt\\dxx.\n\\end{equation}\n\n\\item The kinetic energy \\eqref{eq:kineticG} admits the following Lagrangian description\n\\begin{equation} \\label{eq:kinetici}\n\\mathcal{K}(\\dot{\\vec{u}}_t)=\\mathcal{K}^*(\\vec{u}_t^*,\\dot{\\vec{u}}_t^*,l_t,\\dot{l}_t)=\\int_\\domaini\\kappa(\\dot{\\vec{u}}_t^*-\\dot{l}_t\\nabla\\vec{u}_t^*\\nabla\\philt^{-1}\\vtheta^*)\\det\\nabla\\philt\\dxx\n\\end{equation}\nwhere we note that the transported kinetic energy functional $\\mathcal{K}^*$ depends on the transported displacement $\\vec{u}_t^*$, the crack length $l_t$ and the crack velocity $\\dot{l}_t$\n\n\\item The non-local damage dissipation energy \\eqref{eq:surface} now reads\n\\begin{equation} \\label{eq:surfacei}\n\\mathcal{S}(\\alpha_t)=\\mathcal{S}^*(\\alpha_t^*,l_t)=\\int_\\domaini\\varsigma(\\alpha_t^*,\\nabla\\philt^{-\\mT}\\nabla\\alpha_t^*)\\det\\nabla\\philt\\dxx\\,,\n\\end{equation}\nwhere the identity $\\nabla\\alpha_t(\\vec{x})=\\nabla\\philt^{-\\mT}(\\vec{x}^*)\\nabla\\alpha_t^*(\\vec{x}^*)$ is used following \\eqref{eq:transportofdamage}.\n\n\\item The external work potential \\eqref{eq:power} written in the initial configuration reads\n\\begin{equation} \\label{eq:externalworki}\n\\mathcal{W}_t(\\vec{u}_t)=\\mathcal{W}^*_t(\\vec{u}_t^*,l_t)=\\int_\\domaini (\\vec{f}_t\\circ\\philt)\\cdot\\vec{u}_t^*\\det\\nabla\\philt\\dxx+\\int_{\\partial\\Omega_F} \\vec{F}_t\\cdot\\vec{u}_t^*\\D{\\vec{s}}.\n\\end{equation}\nRemark that the boundary $\\partial\\Omega$ is invariant under the transformation $\\philt$.\n\n\\item The generalized space-time action integral \\eqref{eq:actionG} is hence given by\n\\begin{equation} \\label{eq:actionGG}\n\\begin{aligned}\n\\mathcal{A}(\\vec{u},\\alpha) &= \\mathrm{A}(\\vec{u}^*,\\alpha^*,l)=\\int_I\\mathcal{L}_t(\\vec{u}^*_t,\\dot{\\vec{u}}^*_t,\\alpha^*_t,l_t,\\dot{l}_t)\\,\\mathrm{d}t \\\\\n&= \\int_I\\bigr(\\mathcal{E}^*(\\vec{u}^*_t,\\alpha_t^*,l_t)+\\mathcal{S}^*(\\alpha_t^*,l_t)-\\mathcal{K}^*(\\vec{u}_t,\\dot{\\vec{u}}_t,l_t,\\dot{l}_t)-\\mathcal{W}_t^*(\\vec{u}^*_t,l_t)\\bigr)\\D{t}.\n\\end{aligned}\n\\end{equation}\n\\end{itemize}\n\nThe definition of the admissible evolution spaces for the triplet $(\\vec{u}^*,\\alpha^*,l)$ are discussed as follows. The admissible function space for the displacement \\eqref{eq:Du} is slightly modified to reflect the fact that now the displacement is defined in the uncracked bulk:\n\\begin{align} \\label{eq:Cu}\n\\mathcal{C}(\\vec{u}^*)=\\set{\\vec{v}^*:I\\times(\\Omega\\setminus\\Gamma_0)\\to\\mathbb{R}^\\mathrm{dim}|\\vec{v}^*_t\\in\\mathcal{C}_t\\text{ for all $t\\in I$ and }\\vec{v}^*_{\\partial I}=\\vec{u}^*_{\\partial I}}\\,, \\tag{\\ref*{eq:Du}${}^\\prime$}\n\\end{align}\nwhere $\\mathcal{C}_t=\\mathcal{C}_0+\\vec{U}_t$ and the associated vector space $\\mathcal{C}_0$ is given by\n\\[\n\\mathcal{C}_0=\\set{\\vec{u}^*_t:\\Omega\\setminus\\Gamma_0\\to\\mathbb{R}^\\mathrm{dim}|\\vec{u}^*_t=\\vec{0}\\text{ on }\\partial\\Omega_U}.\n\\]\n\nFor the admissible crack evolution, we require that the evolution of the crack tip $t\\mapsto l_t$ should be a non-decreasing function of time and virtual advance of the crack tip at every instant should also be non-negative to ensure irreversibility. Concretely, given an arbitrary but non-decreasing crack evolution $t\\mapsto l_t$, the admissible crack evolution space is given by\n\\begin{equation} \\label{eq:Dl}\n\\mathcal{Z}(l)=\\set{s:I\\to\\mathbb{R}^+|s_t\\geq l_t\\text{ for all $t\\in I$ and }s_{\\partial I}=l_{\\partial I}}\\,,\n\\end{equation}\nwhere it can be observed that the crack length value is also fixed at both time ends $l_{\\partial I}=(l_0,l_T)$.\n\nThe damage profile $\\alpha^*$ is merely a component contributing to the total damage evolution, hence the temporal irreversibility still applies to the true damage evolution $t\\mapsto\\alpha_t$, which reads $\\dot{\\alpha}_t\\geq 0$. Given an arbitrary such evolution verifying \\cref{hypo:damageband}, we want to consider admissible variation of the current damage state $\\alpha_t$ corresponding to a crack length $l_t$, based on an admissible crack length variation $\\delta l_t=s_t-l_t\\geq 0$ and a crack profile variation $\\beta_t^*-\\alpha_t^*$. At time $t\\in(0,T)$ the induced admissible non-negative variation of the true damage reads\n\\begin{equation} \\label{eq:unilateral}\n\\beta_t-\\alpha_t=\\beta_t^*\\circ\\philt_{s_t}^{-1}-\\alpha_t^*\\circ\\philt_{l_t}^{-1}\\geq 0.\n\\end{equation}\nAs can be seen, the damage profile variation $\\beta_t^*-\\alpha_t^*$ and the crack length variation $\\delta l_t$ are now involved in a unilateral fashion to ensure irreversibility of the true damage:\n\\begin{itemize}\n\\item If the crack length variation is zero $\\delta l_t=0$, then the damage profile variation $\\beta_t^*-\\alpha_t^*$ corresponds exactly to the true damage variation $\\beta_t-\\alpha_t$. Thus it suffices that $\\beta_t^*-\\alpha_t^*\\geq 0$ to ensure irreversibility.\n\\item However if a finite extension of the crack length is considered $\\delta l_t>0$, then the damage profile variation depends non-trivially on the $\\delta l_t$ via \\eqref{eq:unilateral} to obtain $\\beta_t-\\alpha_t\\geq 0$.\n\\end{itemize}\nIn practice, it means that if crack length variation is not considered, then the variation of the action integral with respect to the displacement and to the damage (profile) can be separately computed. Otherwise when $\\delta l_t>0$, then damage variation must also be taken into account. Given an admissible crack length evolution $s\\in\\mathcal{Z}(l)$, the admissible evolution space for the damage profile will be denoted by $\\mathcal{D}_s(\\alpha^*)$, where the dependence on $s$ is explicitly indicated by the subscript and $\\alpha^*$ describes the profile of a damage evolution verifying \\cref{hypo:damageband}. As usual, at both ends of the time interval $I$, no variations of true damage profile are considered.\n\nAssociated with an admissible triplet of displacement, damage profile and crack length evolutions $(\\vec{u}^*,\\alpha^*,l)\\in\\mathcal{C}(\\vec{u}^*)\\times\\mathcal{D}_l(\\alpha^*)\\times\\mathcal{Z}(l)$, we can now reformulate the dynamic gradient damage model under \\cref{hypo:damageband} by the following\n\\begin{definition}[Dynamic Gradient Damage Evolution Law for a Propagating Crack] \\noindent \\label{def:dynagraddamanew}\n\\begin{enumerate}\n\\item \\textbf{Irreversibility}: the damage $t\\mapsto\\alpha_t$ and the crack length $t\\mapsto l_t$ are non-decreasing functions of time.\n\\item \\textbf{First-order stability}: the first-order action variation is non-negative with respect to arbitrary admissible displacement, damage profile and crack evolutions\n\\begin{multline} \\label{eq:vi2}\n\\mathrm{A}'(\\vec{u}^*,\\alpha^*,l)(\\vec{v}^*-\\vec{u}^*,\\beta^*-\\alpha^*,s-l)\\geq 0 \\\\\n\\text{ for all $\\vec{v}^*\\in\\mathcal{C}(\\vec{u}^*)$, all $\\beta^*\\in\\mathcal{D}_s(\\alpha^*)$ and all $s\\in\\mathcal{Z}(l)$}.\n\\end{multline}\n\\item \\textbf{Energy balance}: the only energy dissipation is due to crack propagation such that we have the following energy balance\n\\begin{equation} \\label{eq:dyngdeb3}\n\\mathcal{H}_t=\\mathcal{H}_0+\\int_0^t\\left(\\int_{\\Omega\\setminus\\Gamma_s}\\bigl(\\sig_s\\cdot\\eps(\\dot{\\vec{U}}_s)+\\rho\\ddot{\\vec{u}}_s\\cdot\\dot{\\vec{U}}_s\\bigr)\\dx-\\mathcal{W}_s(\\dot{\\vec{U}}_s)-\\dot{\\mathcal{W}}_s(\\vec{u}_s)\\right)\\D{s}\n\\end{equation}\nwhere the total energy is defined by\n\\begin{equation}\n\\mathcal{H}_t=\\mathcal{E}^*(\\vec{u}_t^*,\\alpha_t^*,l_t)+\\mathcal{S}^*(\\alpha_t^*,l_t)+\\mathcal{K}(\\vec{u}_t^*,\\dot{\\vec{u}}_t^*,l_t,\\dot{l}_t)-\\mathcal{W}_t^*(\\vec{u}_t^*,l_t).\n\\end{equation}\n\\end{enumerate}\n\\end{definition}\n\nWe then exploit the first-order stability condition \\eqref{eq:vi2} by carefully developing the Gâteaux derivative of the action integral \\eqref{eq:actionGG}. With the help of detailed calculations provided in \\cref{chap:detailedcal} and using the same arguments developed before, the first-order action variation testing with $\\beta^*-\\alpha^*=0$ and $s-l=0$ leads to the elastic-damage dynamic wave equation on the uncracked domain similar to \\eqref{eq:wavedyn}\n\\begin{equation} \\label{eq:waveequation}\n\\rho\\ddot{\\vec{u}}_t-\\div\\sig_t=\\vec{f}_t\\quad\\text{in }\\domaint\\,,\\quad\\sig_t\\vec{n}=\\vec{F}_t\\quad\\text{on }\\partial\\Omega_F\\quad\\text{and}\\quad\\sig_t\\vec{n}=\\vec{0}\\quad\\text{on }\\Gamma_t\n\\end{equation}\nwhere we recall that here the stress tensor $\\sig_t$ is damage-dependent and is given by \\eqref{eq:stress}. The stress-free condition is automatically retrieved. Similarly at fixed displacement and crack length variations, evaluating the directional derivative of the action integral with respect to damage variation $\\beta^*-\\alpha^*$ leads to\n\\begin{multline*}\n\\mathrm{A}'(\\vec{u}^*,\\alpha^*,l)(\\vec{0},\\beta^*-\\alpha^*,0)= \\\\\n\\int_I\\left(\\int_\\domaint-(Y_t+\\div\\vec{q}_t)\\cdot(\\beta_t-\\alpha_t)\\dx+\\int_{\\partial\\Omega\\setminus\\Gamma_t}(\\vec{q}_t\\cdot\\vec{n})(\\beta_t-\\alpha_t)\\ds\\right)\\D{t}\\geq 0\n\\end{multline*}\nwhere the integration domain is first transformed to the current cracked one and an integration by parts is then performed. Since the induced true damage variation is non-negative due to \\eqref{eq:unilateral}, we obtain thus the same local damage criterion \\eqref{eq:localdamagefirstorder} as before. Finally, we consider the first-order action variation with respect to crack length evolution variation. Through \\eqref{eq:unilateral}, damage profile variation is thus coupled with that of the crack length. We thus merely have\n\\begin{equation} \\label{eq:staball}\n\\int_\\domaint-(Y_t+\\div\\vec{q}_t)\\cdot(\\beta_t-\\alpha_t)\\dx+\\int_{\\partial\\Omega\\setminus\\Gamma_t}(\\vec{q}_t\\cdot\\vec{n})(\\beta_t-\\alpha_t)\\ds-\\widehat{G}_t\\cdot\\delta l_t\\geq 0\n\\end{equation}\nwith a generalized dynamic energy release rate defined by\n\\begin{equation} \\label{eq:GtG}\n\\widehat{G}_t=G_t^\\alpha-\\gamma_t.\n\\end{equation}\nThis quantity contains the conventional dynamic energy release rate\n\\begin{equation} \\label{eq:GtC}\nG_t^\\alpha=\\int_\\domaint\\Bigl(\\bigl(\\kappa(\\dot{\\vec{u}}_t)-\\psi\\bigl(\\eps(\\vec{u}_t),\\alpha_t\\bigr)\\bigr)\\div\\vtheta_t+\\sig_t\\cdot(\\nabla\\vec{u}_t\\nabla\\vtheta_t)+\\div(\\vec{f}_t\\otimes\\vtheta_t)\\cdot\\vec{u}_t+\\rho\\ddot{\\vec{u}}_t\\cdot\\nabla\\vec{u}_t\\vtheta_t+\\rho\\dot{\\vec{u}}_t\\cdot\\nabla\\dot{\\vec{u}}_t\\vtheta_t\\Bigr)\\dx\n\\end{equation}\nand the damage dissipation rate as the partial derivative of the damage dissipation energy $\\mathcal{S}^*(l_t)$ with respect to the crack length\n\\begin{equation} \\label{eq:Gammat}\n\\gamma_t=\\frac{\\partial}{\\partial l_t}\\mathcal{S}^*(\\alpha^*_t,l_t)=\\int_\\domaint\\bigl(\\varsigma(\\alpha_t,\\nabla\\alpha_t)\\div\\vtheta_t-\\vec{q}_t\\cdot\\nabla\\vtheta_t\\nabla\\alpha_t\\bigr)\\dx.\n\\end{equation}\nIn \\eqref{eq:staball}, although the crack length variation is non-negative $\\delta l_t\\geq 0$, the sign of the generalized dynamic energy release rate is undetermined in general, since the first two terms are both positive due to \\eqref{eq:localdamagefirstorder} and \\eqref{eq:unilateral}.\n\nIt remains to use the energy balance \\eqref{eq:dyngdeb3} to derive the consistency conditions. With the help of the detailed calculations given in \\cref{chap:detailedcal}, we obtain\n\\begin{equation} \\label{eq:crackconsistency}\n\\int_\\domaint-(Y_t+\\div\\vec{q}_t)(\\dot{\\alpha}_t+\\dot{l}_t\\nabla\\alpha\\cdot\\vtheta)\\dx+\\int_{\\partial\\Omega\\setminus\\Gamma_t}(\\vec{q}_t\\cdot\\vec{n})\\dot{\\alpha}_t\\ds-\\widehat{G}_t\\dot{l}_t=0\n\\end{equation}\nwhere the first term represents energy dissipation due to damage profile evolution following \\eqref{eq:alphadot} and the second term corresponds to damage dissipation on the uncracked boundary where $\\vtheta_t=\\vec{0}$. The third term denotes dissipation due to pure propagation of the phase-field crack.  It can be observed that in case of a currently stationary crack $\\dot{l}_t=0$, we retrieve directly the classical consistency conditions for damage \\eqref{eq:damageconsis}. However when the crack propagates $\\dot{l}_t>0$, nothing can be deduced from \\eqref{eq:crackconsistency} since the damage profile evolution $\\alpha^*$ is not necessarily irreversible and the sign of $\\widehat{G}_t$ is not yet known.\n\nFrom \\cref{prop:J}, the dynamic energy release rate \\eqref{eq:Gt} in the Griffith's theory of fracture can be written as a path integral. This property can be extended to the dynamic gradient damage model due to the analogies with their respective variational ingredients.\n\\begin{proposition} \\label{prop:EshelbyG}\nThe generalized dynamic energy release rate \\eqref{eq:GtG} defines a generalized $\\widehat{J}$-integral\n\\begin{equation} \\label{eq:GtGandJdynG}\n\\widehat{J}_t=\\lim_{r\\to 0}\\int_{C_r}\\widehat{\\vec{J}}_t\\vec{n}\\cdot\\vtau_t\\ds=\\widehat{G}_t+\\int_\\domaint (Y_t+\\div\\vec{q}_t)\\nabla\\alpha_t\\cdot\\vtheta_t\\dx\n\\end{equation}\nwhere the generalized dynamic $\\widehat{\\vec{J}}_t$ tensor is defined by\n\\begin{equation} \\label{eq:JdynG}\n\\widehat{\\vec{J}}_t=\\Bigl(\\psi\\bigl(\\eps(\\vec{u}_t),\\alpha_t\\bigr)+\\kappa(\\dot{\\vec{u}}_t)+\\varsigma(\\alpha_t,\\nabla\\alpha_t)\\Bigr)\\mathbb{I}-\\nabla\\vec{u}_t^\\mT\\sig_t-\\vec{q}_t\\otimes\\nabla\\alpha_t.\n\\end{equation}\nAs in \\cref{prop:J}, here $\\vec{n}$ denotes the normal pointing out of the ball $B_r(\\vec{P}_t)$ with $C_r=\\partial B_r(\\vec{P}_t)$ its boundary.\n\\end{proposition}\n\n\\begin{proof}\nThe equation \\eqref{eq:GtGandJdynG} can be obtained mainly by following the proof of \\cref{prop:J}. The last term containing the damage gradient results from the identity below which accounts for the damage dependence of the elastic energy and the damage dissipation energy\n\\begin{multline} \\label{eq:includedamage}\n\\div\\Bigl(\\bigl(\\psi\\bigl(\\eps(\\vec{u}_t),\\alpha_t\\bigr)+\\varsigma(\\alpha_t,\\nabla\\alpha_t)\\bigr)\\vtheta_t\\Bigr)=\\sig_t\\cdot\\eps(\\nabla\\vec{u}_t)\\vtheta_t-Y_t\\nabla\\alpha_t\\cdot\\vtheta_t+\\vec{q}_t\\cdot\\nabla^2\\alpha_t\\vtheta_t+\\bigl(\\psi\\bigl(\\eps(\\vec{u}_t),\\alpha_t\\bigr) \\\\\n+\\varsigma(\\alpha_t,\\nabla\\alpha_t)\\bigr)\\div\\vtheta_t\\,\n\\end{multline}\ntogether with an additional integration by parts\n\\[\n\\int_{\\Omega_r}\\vec{q}_t\\cdot\\nabla\\vtheta_t\\nabla\\alpha_t\\dx=-\\int_{C_r}(\\vec{q}_t\\otimes\\nabla\\alpha_t)\\vec{n}\\cdot\\vtheta_t\\ds-\\int_{\\Omega_r}(\\div\\vec{q}_t\\nabla\\alpha_t\\cdot\\vtheta_t+\\vec{q}_t\\cdot\\nabla^2\\alpha_t\\vtheta_t)\\dx.\n\\]\nTo pass from the Lagrangian density in \\eqref{eq:GtG} to the Hamiltonian density in \\eqref{eq:JdynG}, it suffices to observe that the most singular part of the time derivatives corresponds to the transport term. Similar calculations at the end of the proof of \\cref{prop:J} then lead to the desired result.\n\\end{proof}\n\nThe tensor $\\widehat{\\vec{J}}_t$ can be seen as the dynamic extension of the quasi-static generalized Eshelby tensor (or energy-momentum tensor) introduced respectively in the quasi-static gradient damage model \\cite{SicsicMarigo:2013} and the dissipative phase field model originating from the physics community, see for instance \\cite{Ballarini:2016aa,HakimKarma:2009}. Inserting \\eqref{eq:GtGandJdynG} into \\eqref{eq:crackconsistency}, an equivalent expression of the consistency condition can be obtained\n\\begin{equation} \\label{eq:wideJ}\n\\int_\\domaint(Y_t+\\div\\vec{q}_t)\\dot{\\alpha}_t\\dx+\\int_{\\partial\\Omega\\setminus\\Gamma_t}-(\\vec{q}_t\\cdot\\vec{n})\\dot{\\alpha}_t\\ds+\\widehat{J}_t\\dot{l}_t=0.\n\\end{equation}\nIn \\cite{SicsicMarigo:2013}, a careful singularity analysis is conducted to determine the sign of the $\\widehat{J}$-integral with a particular strongly brittle material. Such calculations could be extended to the dynamic setting but are beyond the scope of this work. Based on numerical verifications, we assume the following\n\\begin{hypothesis} \\label{eq:Jleq0}\nThe generalized dynamic $\\widehat{J}$-integral is non-positive\n\\begin{equation} \\label{eq:stab}\n\\widehat{J}_t\\leq 0\n\\end{equation}\nfor all damage constitutive laws $\\alpha\\mapsto\\mathsf{a}(\\alpha)$ and $\\alpha\\mapsto\\mathsf{w}(\\alpha)$ which characterize the behavior of a strongly brittle material.\n\\end{hypothesis}\nDue to the local damage criterion \\eqref{eq:localdamagefirstorder} and the irreversibility conditions, each term in \\eqref{eq:wideJ} is non-positive while their sum yields zero, which implies that each term vanishes separately\n\\begin{equation} \\label{eq:ebG}\n(Y_t+\\div\\vec{q}_t)\\dot{\\alpha}_t=0\\quad\\text{in }\\domaint\\,,\\quad(\\vec{q}_t\\cdot\\vec{n})\\dot{\\alpha}_t=0\\quad\\text{on }\\partial\\Omega\\setminus\\Gamma_t\\quad\\text{and}\\quad\\widehat{J}_t\\dot{l}_t=0\\,,\n\\end{equation}\nwhich represent local energy balances. We note that the first two equalities correspond to the consistency condition \\eqref{eq:damageconsis} derived without \\cref{hypo:damageband}.\n\nIt can be seen from \\eqref{eq:stab} and the last equation in \\eqref{eq:ebG} that the generalized dynamic $\\widehat{J}$-integral plays the role of $G_t-\\gc$ in the classical Griffith's law \\eqref{eq:gtgc}. It involves a path integral on a contour $C_r$ that shrinks to the crack tip $r\\to 0$, which may lead to difficulties in a finite element calculation. From a numerical point of view, the generalized dynamic energy release rate $\\widehat{G}_t$ defined in \\eqref{eq:GtG} should be preferred since it is written as a cell integral on a finite domain. It turns out that under a particular circumstance, these two objects are equivalent and they both define the following generalized Griffith criterion.\n\\begin{proposition}[Generalized Griffith Criterion] \\label{prop:Ggriffithlaw}\nThe crack tip equation of motion predicted by the dynamic gradient damage model is governed by the following generalized Griffith criterion\n\\begin{equation} \\label{eq:GgriffithlawJ}\n\\dot{l}_t\\geq 0\\,,\\quad \\widehat{J}_t\\leq 0\\quad\\text{and}\\quad\\widehat{J}_t\\dot{l}_t=0.\n\\end{equation}\n\nIf we assume that in \\eqref{eq:alphadot} the time derivative of the damage profile is negligible compared to the transport term and furthermore the damage gradient in the direction of crack propagation is non-positive at every time $t$ and almost everywhere\n\\begin{equation} \\label{eq:transportbigalphadevneg}\n\\dot{\\alpha}_t\\approx-\\dot{l}_t\\nabla\\alpha_t\\cdot\\vtheta_t\\,,\\quad \\nabla\\alpha_t\\cdot\\vtheta_t\\leq 0\\,,\n\\end{equation}\nthen the generalized dynamic energy release rate \\eqref{eq:GtG} can be equivalently used in the above generalized Griffith criterion, which leads to\n\\begin{equation} \\label{eq:GgriffithlawG}\n\\dot{l}_t\\geq 0\\,,\\quad \\widehat{G}_t\\leq 0\\quad\\text{and}\\quad\\widehat{G}_t\\dot{l}_t=0.\n\\end{equation}\n\\end{proposition}\n\n\\begin{proof}\nUsing the definition of $\\widehat{J}_t$ in \\eqref{eq:GtGandJdynG} and the second condition in \\eqref{eq:transportbigalphadevneg}, we obtain the equivalent stability condition\n\\[\n\\widehat{G}_t=\\widehat{J}_t-\\int_\\domaint (Y_t+\\div\\vec{q}_t)\\nabla\\alpha_t\\cdot\\vtheta_t\\dx\\leq 0\n\\]\nsince $Y_t+\\div\\vec{q}_t\\leq 0$ due to the local damage criterion \\eqref{eq:localdamagefirstorder}. If the first condition in \\eqref{eq:transportbigalphadevneg} holds, then the local consistency condition for damage in \\eqref{eq:crackconsistency} reads\n\\[\n(Y_t+\\div\\vec{q}_t)\\dot{l}_t\\nabla\\alpha_t\\cdot\\vtheta_t=0.\n\\]\nMultiplying \\eqref{eq:GtGandJdynG} by $\\dot{l}_t$ gives the desired condition $\\widehat{G}_t\\dot{l}_t=0$.\n\\end{proof}\n\n\\begin{remark}\nThese two conditions \\eqref{eq:transportbigalphadevneg} needed to establish \\eqref{eq:GgriffithlawG} can be justified in the crack tip problem when the internal length is small compared to the dimension of the body.\n\\end{remark}\n\n\\begin{remark}\n\\cref{prop:Ggriffithlaw} and in particular \\eqref{eq:GgriffithlawJ} and \\eqref{eq:GgriffithlawG} constitute one of the main results of the present contribution. Above all, arbitrary damage evolution in the dynamic gradient damage model is governed by the irreversibility condition, the damage criterion \\eqref{eq:localdamagefirstorder} and the consistency condition \\eqref{eq:damageconsis}. However it is shown that the propagation (or arrest) of an existing damage band (phase-field crack) is governed by the above Griffith like \\emph{scalar} equations involving several energy release rate concepts.\n\\end{remark}\n\n\\subsection{Separation of scales} \\label{sec:asymptotic}\nThe generalized dynamic $\\widehat{J}$-integral as well as the generalized dynamic energy release rate $\\widehat{G}_t$ that enter into the generalized Griffith's law (\\cref{prop:Ggriffithlaw}) don't possess directly an intuitive interpretation in fracture mechanics terminology. To establish the link between damage and fracture, we will essentially follow the separation of scales made in the quasi-static case \\cite{SicsicMarigo:2013} (and similar in essence to that reviewed in \\cite{HakimKarma:2009}) which decomposes the complete gradient damage evolution problem into three subproblems. From now on, all quantities that depend on the internal length will be indicated by a superscript $\\ell$. We also adopt the assumption made on the internal length dependence of the external loading, namely\n\\begin{equation} \\label{eq:loadingell}\n\\vec{f}_t^\\ell=\\sqrt{\\ell}\\vec{f}_t,\\qquad\\vec{F}_t^\\ell=\\sqrt{\\ell}\\vec{F}_t\\qquad\\text{and}\\qquad\\vec{U}_t^\\ell=\\sqrt{\\ell}\\vec{U}_t.\n\\end{equation}\n\\begin{figure}[htbp]\n\\centering\n\\includegraphics[width=0.65\\textwidth]{scales.pdf}\n\\caption{Separation of scales conducted in \\cite{SicsicMarigo:2013} which decomposes the gradient damage evolution problem into three sub-problems: the outer linear elastic fracture mechanics problem where the damage band is replaced by a true crack in the domain, the damage band problem in which the fracture toughness can be identified with the energy dissipated during the damage band creation and the crack tip problem where the matching conditions with the previous two subproblems will be used}\n\\end{figure}\n\n\\subsubsection{Outer linear elastic dynamic fracture problem}\nIn this elastodynamic problem we assume that the body contains a sharp-interface crack corresponding to the totally damaged region $\\Gamma_t$. Due to the linear nature of the macroscopic dynamic fracture problem on the cracked domain $\\domaint$, dependence of the real mechanical fields on the internal length can be given by\n\\begin{equation} \\label{eq:dependenceell}\n\\vec{u}_t^\\ell=\\sqrt{\\ell}\\vec{u}_t+\\ldots,\\qquad\\dot{\\vec{u}}^\\ell_t=\\sqrt{\\ell}\\dot{\\vec{u}}_t+\\ldots,\\qquad\\ddot{\\vec{u}}^\\ell_t=\\sqrt{\\ell}\\ddot{\\vec{u}}_t+\\ldots\\qquad\\text{and}\\qquad\\sig_t^\\ell=\\sqrt{\\ell}\\sig_t+\\ldots.\n\\end{equation}\n\nThe behaviors of the fields are described in \\cref{sec:griffithfreund}. In particular, the rescaled stress $\\sig_t$ and the rescaled velocity $\\dot{\\vec{u}}_t$ admit the following asymptotic form\n\\begin{equation} \\label{eq:singularforms}\n\\begin{aligned}\n\\sig_t(r,\\theta) &\\approx \\frac{\\overline{K}_\\RNN{1}(t)}{\\sqrt{2\\pi r}}\\vec{\\Sigma}_\\RNN{1}(\\theta,\\dot{l}_t)+\\frac{\\overline{K}_\\RNN{2}(t)}{\\sqrt{2\\pi r}}\\vec{\\Sigma}_\\RNN{2}(\\theta,\\dot{l}_t)\\,, \\\\\n\\dot{\\vec{u}}_t(r,\\theta) &\\approx \\frac{\\dot{l}_t\\overline{K}_\\RNN{1}(t)}{\\sqrt{2\\pi r}\\mu}\\vec{V}_\\RNN{1}(\\theta,\\dot{l}_t)+\\frac{\\dot{l}_t\\overline{K}_\\RNN{2}(t)}{\\sqrt{2\\pi r}\\mu}\\vec{V}_\\RNN{2}(\\theta,\\dot{l}_t)\\,,\n\\end{aligned}\n\\end{equation}\nwhere $\\overline{K}$'s is the rescaled stress intensity factors. The true stress intensity factors $K^\\ell$'s are given by $K_i^\\ell=\\sqrt{\\ell}\\,\\overline{K}_i$ since they are of order $\\mathcal{O}(\\sqrt{\\ell})$ due to \\eqref{eq:dependenceell}.\n\nAn equivalent dynamic energy release rate $G_t^\\ell$ associated with this outer problem is of order $\\mathcal{O}(\\ell)$. The rescaled dynamic energy release rate under the plane strain condition is given by\n\\begin{equation} \\label{eq:GasafunctionofKs}\n\\overline{G}_t=\\frac{1-\\nu^2}{E}\\left(A_\\RNN{1}(\\dot{l}_t)\\overline{K}_\\RNN{1}(t)^2+A_\\RNN{2}(\\dot{l}_t)\\overline{K}_\\RNN{2}(t)^2\\right)\\,,\n\\end{equation}\nwhere the rescaling condition reads\n\\begin{equation} \\label{eq:Gtell}\nG_t^\\ell=\\ell\\overline{G}_t\n\\end{equation}\n\n\\subsubsection{Damage band problem}\nThe damage band problem will be essentially the same as in the quasi-static case \\cite{SicsicMarigo:2013}, due to the formally identical energy minimization principle \\eqref{eq:crackmin} and its local interpretations \\eqref{eq:localdamagefirstorder} and \\eqref{eq:damageconsis}. The first-order term of the damage field $\\alpha_t^\\ell$ inside or near the crack band but far from the crack tip admits the following form\n\\begin{equation} \\label{eq:damageprofile}\n\\alpha_t^\\ell(\\vec{x})\\approx\\alpha_*(s,\\zeta)=\\alpha_*\\bigl(s,\\operatorname{dist}(\\vec{x},\\Gamma_t)/\\ell\\bigr)\n\\end{equation}\nwhere $\\alpha_*$ is the normalized (with respect to $\\ell$) damage profile along the crack normal at a certain arclength $s$ of the crack $\\Gamma_t$ and $\\operatorname{dist}(\\vec{x},\\Gamma_t)$ is the Euclidean distance from the point $\\vec{x}$ near the crack band to the crack $\\Gamma_t$. The damage gradient in the tangential direction is thus negligible compared to that in the normal direction\n\\begin{equation} \\label{eq:tangentialzero}\n\\nabla\\alpha_t^\\ell\\cdot\\vtau_t\\approx 0.\n\\end{equation}\nUsing the definition of the dual quantities \\eqref{eq:Ytqt}, the consistency condition \\eqref{eq:damageconsis} during the crack band creation reads\n\\begin{equation} \\label{eq:damagecondition}\n\\frac{1}{2}\\tens{A}'(\\alpha_*)\\eps(\\vec{u}_t^\\ell)\\cdot\\eps(\\vec{u}_t^\\ell)+w'(\\alpha_*)-w_1\\frac{\\partial^2\\alpha_*}{\\partial\\zeta^2}=0.\n\\end{equation}\nNote that in this damage band problem the term $\\frac{1}{2}\\tens{A}'(\\alpha_*)\\eps(\\vec{u}_t^\\ell)\\cdot\\eps(\\vec{u}_t^\\ell)$ is still of order $\\mathcal{O}(\\ell)$ due to \\eqref{eq:dependenceell} while the other two terms in \\eqref{eq:damagecondition} are of order $\\mathcal{O}(1)$, which leads to the following first-order damage profile condition\n\\begin{equation} \\label{eq:firstorderdamagecondition}\nw'\\bigl(\\alpha_*\\bigr)-w_1\\frac{\\partial^2\\alpha_*}{\\partial\\zeta^2}=0.\n\\end{equation}\n\nThis problem is thus similar to the construction of the optimal damage profile for a uniaxial traction experiment, see the end of \\cref{sec:equivalentlocal}. The energy per unit length dissipated during the damage band creation can be calculated by the integral of the damage dissipation density \\eqref{eq:surface} over the real cross section, which gives\n\\begin{equation} \\label{eq:gcindamage}\n\\gc^\\ell=\\ell\\overline{G}_\\mc\\quad\\text{where}\\quad\\overline{G}_\\mc=2\\sqrt{2}\\int_0^1\\sqrt{w_1w(\\beta)}\\D{\\beta}.\n\\end{equation}\nThis energy as in the quasi-static case \\cite{SicsicMarigo:2013} will play the role of the fracture toughness in the asymptotic Griffith's law during the crack propagation phase.\n\n\\subsubsection{Crack tip problem}\nWe perform the same translation and rescaling of the system of coordinates $\\vec{y}=(\\vec{x}-\\vec{P}_t)/\\ell$ in the vicinity of the crack tip and assume the following near-tip forms of the displacement, stress and damage fields established in Sect. 3.3 of \\cite{SicsicMarigo:2013}\n\\[\n\\vec{u}_t^\\ell(\\vec{x})=\\sqrt{\\ell}\\vec{u}_t(\\vec{P}_t)+\\ell\\overline{\\vec{u}}_t(\\vec{y})+\\ldots\\,,\\quad\\sig_t(\\vec{x})=\\overline{\\sig}_t(\\vec{y})+\\ldots\\quad\\text{and}\\quad\\alpha_t(\\vec{x})=\\overline{\\alpha}_t(\\vec{y})+\\ldots\n\\]\nwith $\\vec{u}_t(\\vec{P}_t)$ the displacement of the crack tip given by the outer problem \\eqref{eq:dependenceell} and $\\overline{\\sig}_t=\\tens{A}(\\overline{\\alpha}_t)\\eps(\\overline{\\vec{u}}_t)$. In dynamics, the asymptotic expansion of the velocity $\\dot{\\vec{u}}_t^\\ell$ and the acceleration $\\ddot{\\vec{u}}_t^\\ell$ can be obtained by differentiating $\\vec{u}_t^\\ell$ with respect to time, which gives to their first order with respect to the internal length\n\\begin{equation} \\label{eq:asymsteadycondition}\n\\begin{aligned}\n\\dot{\\vec{u}}_t &\\approx -\\dot{l}_t\\nabla\\overline{\\vec{u}}_t\\vtau_t=\\mathcal{O}(1)\\,, \\\\\n\\ddot{\\vec{u}}_t &\\approx -\\dot{l}_t\\nabla\\dot{\\vec{u}}_t\\vtau_t=\\mathcal{O}(1).\n\\end{aligned}\n\\end{equation}\nThese equations illustrate in fact the steady-state condition \\eqref{eq:steadystatecondition} for the crack tip problem. We note that here the stress, the velocity and the acceleration are of order $\\mathcal{O}(1)$ while they are of order $\\mathcal{O}(\\sqrt{\\ell})$ in the outer problem. Using the expressions given in \\eqref{eq:singularforms}, the behavior of $\\overline{\\sig}_t$ and $\\dot{\\vec{u}}_t$ far from the crack tip can thus be obtained by virtue of the following matching conditions\n\\begin{equation} \\label{eq:asymgradu}\n\\begin{aligned}\n\\lim_{r\\to\\infty}\\left(\\overline{\\sig}_t(r,\\theta)-\\frac{\\overline{K}_\\RNN{1}(t)}{\\sqrt{2\\pi r}}\\vec{\\Sigma}_\\RNN{1}(\\theta,\\dot{l}_t)-\\frac{\\overline{K}_\\RNN{2}(t)}{\\sqrt{2\\pi r}}\\vec{\\Sigma}_\\RNN{2}(\\theta,\\dot{l}_t)\\right)=\\vec{0}, \\\\\n\\lim_{r\\to\\infty}\\left(\\dot{\\vec{u}}_t(r,\\theta)-\\frac{\\dot{l}_t\\overline{K}_\\RNN{1}(t)}{\\sqrt{2\\pi r}\\mu}\\vec{V}_\\RNN{1}(\\theta,\\dot{l}_t)-\\frac{\\dot{l}_t\\overline{K}_\\RNN{2}(t)}{\\sqrt{2\\pi r}\\mu}\\vec{V}_\\RNN{2}(\\theta,\\dot{l}_t)\\right)=\\vec{0}.\n\\end{aligned}\n\\end{equation}\nSince the body force density $\\vec{f}_t^\\ell$ is of higher order, the first-order dynamic equilibrium for this crack tip problem reads\n\\begin{equation} \\label{eq:waveequationattip}\n\\rho\\ddot{\\vec{u}}_t-\\div\\overline{\\sig}_t=\\vec{0}\\quad\\text{in}\\quad\\mathbb{R}^2\\setminus\\overline{\\Gamma}\\qquad\\text{and}\\qquad\\overline{\\sig}_t\\vec{n}=\\vec{0}\\quad\\text{on}\\quad\\overline{\\Gamma}\n\\end{equation}\nwhere $\\overline{\\Gamma}=(-\\infty,0)\\times\\set{0}$ corresponds to a rescaled crack along the direction $\\vec{e}_1$, where $\\overline{\\alpha}_t=1$.\n\nWe now turn to damage evolution in the crack tip problem. In the rescaled coordinate system the virtual perturbation admits the form $\\vtheta_t(\\vec{y})=\\theta_t(\\vec{y})\\vec{e}_1$ where $0\\leq\\theta_t(\\vec{y})\\leq1$. From the chain rule, the rate of damage \\eqref{eq:alphadot} is of order $\\mathcal{O}(1/\\ell)$ and reads\n\\begin{equation} \\label{eq:alphadotcracktip}\n\\dot{\\alpha}_t^\\ell(\\vec{x})=-\\frac{\\dot{l}_t}{\\ell}\\nabla\\overline{\\alpha}_t(\\vec{y})\\cdot\\vtheta_t(\\vec{y})+\\ldots=-\\frac{\\dot{l}_t}{\\ell}\\theta_t\\frac{\\partial\\overline{\\alpha}_t}{\\partial y_1}(\\vec{y})+\\ldots.\n\\end{equation}\nwhere the damage profile rate disappears since it is of higher order. This corresponds to the first condition assumed in \\eqref{eq:transportbigalphadevneg}. Due to the irreversibility condition of damage, when the crack propagates $\\dot{l}_t>0$ the term $\\nabla\\overline{\\alpha}_t(\\vec{y})\\cdot\\vtheta_t(\\vec{y})$ is necessarily non-positive. We assume that the condition remains true at every time. It is sufficient that the damage remains constant near the crack tip when when the crack is arrested.\n\\begin{hypothesis}\nWe assume that $\\nabla\\alpha_t\\cdot\\vtheta_t\\leq 0$ for every time.\n\\end{hypothesis}\nThis corresponds to the second condition of \\eqref{eq:transportbigalphadevneg}. All the terms in the local damage criterion \\eqref{eq:localdamagefirstorder} are of order $\\mathcal{O}(1)$, hence at the first order we have\n\\begin{equation} \\label{eq:damageconditiontip}\n\\frac{1}{2}\\tens{A}'(\\overline{\\alpha}_t)\\eps(\\overline{\\vec{u}}_t)\\cdot\\eps(\\overline{\\vec{u}}_t)+w'(\\overline{\\alpha}_t)-w_1\\Delta\\overline{\\alpha}_t\\leq 0.\n\\end{equation}\nThe damage field $\\overline{\\alpha}_t$ should also be matched to its asymptotic expansions for the outer and the damage band problems, which implies\n\\begin{equation} \\label{eq:asymalpha}\n\\lim_{y_1\\to+\\infty\\text{ or }\\abs{y_2}\\to\\infty}\\overline{\\alpha}_t(\\vec{y})=0\\qquad\\text{and}\\qquad\\lim_{y_1\\to-\\infty}\\overline{\\alpha}_t(\\vec{y})=\\alpha_*(y_2).\n\\end{equation}\n\nSince all conditions in \\eqref{eq:transportbigalphadevneg} are satisfied in the crack tip problem, the generalized Griffith criterion admits the form \\eqref{eq:GgriffithlawG} involving the above two objects. We will take advantage of the asymptotic behavior of the fields \\eqref{eq:asymgradu} and \\eqref{eq:asymalpha} to analyze that of the conventional dynamic energy release rate \\eqref{eq:GtC} and the damage dissipation rate \\eqref{eq:Gammat}. Note that they are both of order $\\mathcal{O}(\\ell)$ as in the case for $G_t^\\ell$ in \\eqref{eq:Gtell} as well as for $\\gc^\\ell$ in \\eqref{eq:gcindamage}, and thus are rescaled accordingly\n\\begin{equation} \\label{eq:Gtalphaell}\n(G^\\alpha_t)^\\ell=\\ell\\overline{G}^\\alpha_t\\qquad\\text{and}\\qquad\\gamma_t^\\ell=\\ell\\overline{\\gamma}_t.\n\\end{equation}\n\n\\begin{proposition} \\label{prop:Gammattogc}\nUsing virtual perturbations defined in \\cref{fig:theta}, the damage dissipation rate \\eqref{eq:Gammat} converges to the fracture toughness \\eqref{eq:gcindamage} defined in the damage band problem in the limit $r\\to\\infty$.\n\\end{proposition}\n\\begin{figure}[htbp]\n\\centering\n\\includegraphics[width=0.5\\textwidth]{theta.pdf}\n\\caption{A particular virtual perturbation $\\vtheta_t$ in the scaled coordinate system $\\vec{y}=(\\vec{x}-\\vec{P}_t)/\\ell$ adapted from \\cref{fig:exampletheta}} \\label{fig:theta}\n\\end{figure}\n\n\\begin{proof}\nWithin the scaled coordinate system we will construct a particular family of virtual perturbations of form $\\vtheta_t(\\vec{y})=\\theta_t(\\vec{y})\\vec{e}_1$ as illustrated in \\cref{fig:theta}. As can be seen, the definition is adapted from \\cref{fig:exampletheta}. The asymptotic behavior of the rescaled damage dissipation rate $\\overline{\\gamma}_t$ is analyzed when the inner radius $r$ goes to infinity with a fixed ratio of $R/r$. As $\\nabla\\theta_t=\\vec{0}$ inside $B_r(\\vec{P}_t)$, the scaled damage dissipation rate $\\overline{\\gamma}_t$ reads\n\\[\n\\overline{\\gamma}_t=\\int_{\\circledcirc_r}\\left(\\overline{\\varsigma}(\\overline{\\alpha}_t,\\nabla\\overline{\\alpha}_t)\\div\\vtheta_t-\\overline{\\vec{q}}_t\\cdot\\nabla\\vtheta_t\\nabla\\overline{\\alpha}_t\\right)\\D{\\vec{y}}\n\\]\nwhere the integral is defined on the uncracked crown by $\\circledcirc_r=\\bigl(B_R(\\vec{P}_t)\\setminus B_r(\\vec{P}_t)\\bigr)\\setminus\\Gamma_t$ and $\\overline{\\varsigma}$ is the rescaled damage dissipation energy given by\n\\[\n\\overline{\\varsigma}(\\overline{\\alpha}_t,\\nabla\\overline{\\alpha}_t)=w(\\overline{\\alpha}_t)+\\frac{1}{2}w_1\\nabla\\overline{\\alpha}_t\\cdot\\nabla\\overline{\\alpha}_t\\implies\\overline{\\vec{q}}_t=w_1\\nabla\\overline{\\alpha}_t.\n\\]\nIntegrating by parts the virtual perturbation gradient term and using \\eqref{eq:includedamage}, we obtain\n\\[\n\\overline{\\gamma}_t=\\int_{\\circledcirc_r}\\left(\\div\\bigl(\\overline{\\varsigma}(\\overline{\\alpha}_t,\\nabla\\overline{\\alpha}_t)\\vtheta_t\\bigr)-\\frac{\\partial\\overline{\\varsigma}}{\\partial\\alpha}(\\overline{\\alpha}_t,\\nabla\\overline{\\alpha}_t)\\nabla\\overline{\\alpha}_t\\cdot\\vtheta_t+\\div\\overline{\\vec{q}}_t(\\nabla\\overline{\\alpha}_t\\cdot\\vtheta_t)\\right)\\D{\\vec{y}}-\\int_{C_r}(\\overline{\\vec{q}}_t\\cdot\\vec{n})(\\nabla\\overline{\\alpha}_t\\cdot\\vtheta_t)\\D{\\vec{a}}\n\\]\nwhere the boundary integral is due to the fact that $\\vtheta_t=\\vec{e}_1\\neq\\vec{0}$ only on the inner circle $C_r=\\partial B_r(\\vec{P}_t)$ and $\\vtheta_t\\cdot\\vec{n}=0$ on $\\Gamma_t$. Note that here the vector $\\vec{n}$ is defined as the normal pointing into the circle $C_r$ and $\\md\\vec{a}$ denotes the arc length measure associated with $\\md\\vec{y}$. From the damage band problem we have $\\nabla\\overline{\\alpha}_t\\cdot\\vec{e}_1=0$ away from the crack tip $\\vec{P}_t$, see \\eqref{eq:tangentialzero}. Hence using the matching condition with the damage band problem \\eqref{eq:asymalpha} we have in the limit $r\\to\\infty$\n\\[\n\\lim_{r\\to\\infty}\\overline{\\gamma}_t=\\int_{\\circledcirc_\\infty}\\div\\bigl(\\overline{\\varsigma}(\\overline{\\alpha}_t,\\nabla\\overline{\\alpha}_t)\\vtheta_t\\bigr)\\D{\\vec{y}}=\\int_{C_\\infty}\\overline{\\varsigma}(\\overline{\\alpha}_t,\\nabla\\overline{\\alpha}_t)\\vec{e}_1\\cdot\\vec{n}\\D{\\vec{a}}=\\int_{-\\overline{D}}^{\\overline{D}}\\overline{\\varsigma}\\bigl(\\alpha_*(y),\\nabla\\alpha_*(y)\\bigr)\\D{y}=\\overline{G}_\\mc\n\\]\nwhere the last equality comes from the definition of $\\overline{G}_\\mc$ in \\eqref{eq:gcindamage}.\n\\end{proof}\n\n\\begin{proposition} \\label{prop:GalphatoG}\nUsing virtual perturbations defined in \\cref{fig:theta}, the conventional dynamic energy release rate \\eqref{eq:GtC} converges to the equivalent dynamic energy release rate of the outer problem \\eqref{eq:Gtell} in the limit $r\\to\\infty$,\n\\end{proposition}\n\n\\begin{proof}\nThe conventional dynamic energy release rate will still be calculated with the above introduced virtual perturbation of \\cref{fig:theta}. The term involving the body force density in \\eqref{eq:GtC} will be neglected since it is of higher order. By denoting the uncracked inner ball by $\\tilde{B}_r=B_r(\\vec{P}_t)\\setminus\\Gamma_t$, we will partition $\\overline{G}^\\alpha_t$ defined on $B_R(\\vec{P}_t)\\setminus\\Gamma_t$ into two parts\n\\begin{multline} \\label{eq:Galphaintwoparts}\n\\overline{G}^\\alpha_t=\\int_{\\circledcirc_r}\\Bigl(\\bigl(\\kappa(\\dot{\\vec{u}}_t)-\\psi\\bigl(\\eps(\\overline{\\vec{u}}_t),\\overline{\\alpha}_t\\bigr)\\bigr)\\div\\vtheta_t+\\sig\\bigl(\\eps(\\overline{\\vec{u}}_t),\\overline{\\alpha}_t\\bigr)\\cdot(\\nabla\\overline{\\vec{u}}_t\\nabla\\vtheta_t)+\\rho\\ddot{\\vec{u}}_t\\cdot\\nabla\\overline{\\vec{u}}_t\\vtheta_t+\\rho\\dot{\\vec{u}}_t\\cdot\\nabla\\dot{\\vec{u}}_t\\vtheta_t\\Bigr)\\D{\\vec{y}} \\\\\n+\\int_{\\tilde{B}_r}\\left(\\rho\\ddot{\\vec{u}}_t\\cdot\\nabla\\overline{\\vec{u}}_t\\vtau_t+\\rho\\dot{\\vec{u}}_t\\cdot\\nabla\\dot{\\vec{u}}_t\\vtau_t\\right)\\D{\\vec{y}}\n\\end{multline}\nwhere we note that the virtual perturbation $\\vtheta_t$ is constant and is equal to the crack propagation direction $\\vec{e}_1$ inside $B_r(\\vec{P}_t)$ by definition. Using the identities and integrations by parts similar to \\eqref{eq:div}, \\eqref{eq:signunt} and \\eqref{eq:includedamage}, the first line defined in the crown $\\circledcirc_r$ can be written as\n\\begin{multline*}\n\\left(\\overline{G}^\\alpha_t\\right)_1=\\int_{\\circledcirc_r}\\Bigl(\\div\\Bigl(\\bigl(\\kappa(\\dot{\\vec{u}}_t)-\\psi\\bigl(\\eps(\\overline{\\vec{u}}_t),\\overline{\\alpha}_t\\bigr)\\bigr)\\vtheta_t\\Bigr)+\\frac{\\partial\\psi}{\\partial\\alpha}\\bigl(\\eps(\\overline{\\vec{u}}_t),\\overline{\\alpha}_t\\bigr)\\nabla\\overline{\\alpha}_t\\cdot\\vtheta_t \\\\\n+\\rho\\ddot{\\vec{u}}_t\\cdot\\nabla\\overline{\\vec{u}}_t\\vtheta_t-\\div\\overline{\\sig}_t\\cdot\\nabla\\overline{\\vec{u}}_t\\vtheta_t\\Bigr)\\D{\\vec{y}}-\\int_{C_r}(\\nabla\\overline{\\vec{u}}_t^\\mT\\overline{\\sig}_t)\\vec{n}\\cdot\\vec{e}_1\\D{\\vec{a}}\n\\end{multline*}\nwhere the integral on the circle $C_r=\\partial B_r(\\vec{P}_t)$ comes from the integration by parts of the term $\\sig\\bigl(\\eps(\\overline{\\vec{u}}_t),\\overline{\\alpha}_t\\bigr)\\cdot(\\nabla\\overline{\\vec{u}}_t\\nabla\\vtheta_t)$, the boundary conditions of $\\vtheta_t$ due to definition, and the fact that $\\vec{n}$ is defined as the normal pointing out of the ball $\\partial B_r(\\vec{P}_t)$. Thanks to dynamic equilibrium \\eqref{eq:waveequationattip}, we have\n\\begin{align*}\n\\left(\\overline{G}^\\alpha_t\\right)_1 &= \\int_{\\circledcirc_r}\\left(\\div\\Bigl(\\bigl(\\kappa(\\dot{\\vec{u}}_t)-\\psi\\bigl(\\eps(\\overline{\\vec{u}}_t),\\overline{\\alpha}_t\\bigr)\\bigr)\\vtheta_t\\Bigr)+\\frac{\\partial\\psi}{\\partial\\alpha}\\bigl(\\eps(\\overline{\\vec{u}}_t),\\overline{\\alpha}_t\\bigr)\\nabla\\overline{\\alpha}_t\\cdot\\vtheta_t\\right)\\D{\\vec{y}}-\\int_{C_r}(\\nabla\\overline{\\vec{u}}_t^\\mT\\overline{\\sig}_t)\\vec{n}\\cdot\\vec{e}_1\\D{\\vec{a}} \\\\\n&= \\int_{C_r}\\left(\\bigl(\\psi\\bigl(\\eps(\\overline{\\vec{u}}_t),\\overline{\\alpha}_t\\bigr)-\\kappa(\\dot{\\vec{u}}_t)\\bigr)(\\vec{e}_1\\cdot\\vec{n})-(\\nabla\\overline{\\vec{u}}_t^\\mT\\overline{\\sig}_t)\\vec{n}\\cdot\\vec{e}_1\\right)\\D{\\vec{a}}+\\int_{\\circledcirc_r}\\frac{\\partial\\psi}{\\partial\\alpha}\\bigl(\\eps(\\overline{\\vec{u}}_t),\\overline{\\alpha}_t\\bigr)\\nabla\\overline{\\alpha}_t\\cdot\\vtheta_t\\D{\\vec{y}}\n\\end{align*}\nwhere the second equality follows by the integration by parts of the divergence term with the same remarks about the normal and the boundary conditions of $\\vtheta_t$.\n\nUsing the steady state condition \\eqref{eq:asymsteadycondition} for this crack tip problem and the integration by parts similar to \\eqref{eq:magicformula}, the second part of \\eqref{eq:Galphaintwoparts} reads\n\\[\n\\left(\\overline{G}^\\alpha_t\\right)_2=\\int_{C_r}\\rho(\\dot{\\vec{u}}_t\\cdot\\dot{\\vec{u}}_t)(\\vec{e}_1\\cdot\\vec{n})\\D{\\vec{a}}-\\int_{\\tilde{B}_r}\\rho\\dot{\\vec{u}}_t\\cdot\\dot{\\vec{u}}_t\\div\\vtheta_t\\D{\\vec{y}}=\\int_{C_r}2\\kappa(\\dot{\\vec{u}}_t)\\vec{e}_1\\cdot\\vec{n}\\D{\\vec{a}}\n\\]\nbecause $\\div\\vtheta_t=0$ inside the inner ball $B_r(\\vec{P}_t)$. Regrouping $\\left(\\overline{G}^\\alpha_t\\right)_1$ and $\\left(\\overline{G}^\\alpha_t\\right)_2$, we obtain thus\n\\[\n\\overline{G}^\\alpha_t=\\int_{C_r}\\left(\\bigl(\\psi\\bigl(\\eps(\\overline{\\vec{u}}_t),\\overline{\\alpha}_t\\bigr)+\\kappa(\\dot{\\vec{u}}_t)\\bigr)(\\vec{e}_1\\cdot\\vec{n})-(\\nabla\\overline{\\vec{u}}_t^\\mT\\overline{\\sig}_t)\\vec{n}\\cdot\\vec{e}_1\\right)\\D{\\vec{a}}+\\int_{\\circledcirc_r}\\frac{\\partial\\psi}{\\partial\\alpha}\\bigl(\\eps(\\overline{\\vec{u}}_t),\\overline{\\alpha}_t\\bigr)\\nabla\\overline{\\alpha}_t\\cdot\\vtheta_t\\D{\\vec{y}}.\n\\]\nWhen the inner radius $r$ tends to infinity, we observe that the angular sector corresponding to $\\overline{\\alpha}_t>0$ goes to zero. Using the matching conditions of the mechanical fields \\eqref{eq:asymgradu} and of the damage field \\eqref{eq:asymalpha} which implies that $\\nabla\\overline{\\alpha}_t\\cdot\\vec{e}_1\\to 0$, see \\eqref{eq:tangentialzero}, we obtain in this limit\n\\[\n\\lim_{r\\to\\infty}\\overline{G}^\\alpha_t=\\int_{C_\\infty}\\left(\\bigl(\\psi\\bigl(\\eps(\\overline{\\vec{u}}_t),0\\bigr)+\\kappa(\\dot{\\vec{u}}_t)\\bigr)(\\vec{e}_1\\cdot\\vec{n})-(\\nabla\\overline{\\vec{u}}_t^\\mT\\overline{\\sig}_t)\\vec{n}\\cdot\\vec{e}_1\\right)\\D{\\vec{a}}=\\int_{C_\\infty}(\\overline{\\vec{J}}_t\\vec{n}\\cdot\\vec{e}_1)\\D{\\vec{a}}=\\overline{G}_t\n\\]\nwhere $\\overline{\\vec{J}}_t$ is the rescaled dynamic $\\vec{J}$ tensor \\eqref{eq:Jdyn} corresponding to the outer problem and the last equality comes from \\cref{prop:J} and \\eqref{eq:Gtell}.\n\\end{proof}\n\n\\begin{proposition}[Asymptotic Griffith's Law] \\label{prop:whenellpetit}\nThe crack tip evolution in the dynamic gradient damage model is governed by the following asymptotic Griffith's law as long as the material internal length is sufficiently small compared to the dimension of the body\n\\[\n\\dot{l}_t\\geq 0\\,,\\quad G_t^\\ell\\leq\\gc^\\ell\\quad\\text{and}\\quad(G_t^\\ell-\\gc^\\ell)\\dot{l}_t=0.\n\\]\n\\end{proposition}\n\n\\begin{proof}\nIrreversibility follows directly by the generalized Griffith criterion \\eqref{eq:GgriffithlawG}. Using its definition \\eqref{eq:GtG} and the rescaling condition \\eqref{eq:Gtalphaell}, the generalized dynamic energy release rate reads\n\\[\n\\widehat{G}^\\ell_t=\\ell(\\overline{G}_t^\\alpha-\\overline{\\gamma}_t)\n\\]\nThanks to the two asymptotic results from \\cref{prop:Gammattogc,prop:GalphatoG} and the rescaling conditions \\eqref{eq:Gtell} and \\eqref{eq:gcindamage}, the desired crack stability and energy balance conditions can be obtained by passing the limit $r\\to\\infty$ using virtual perturbations defined in \\cref{fig:theta}.\n\\end{proof}\n\n\\begin{remark}\n\\cref{prop:whenellpetit} constitutes another main result of the present contribution. It can be regarded as an asymptotic interpretation of \\cref{prop:Ggriffithlaw}. When the internal length is small, it is shown that the propagation of a phase-field like crack is driven by the dynamic energy release rate of the outer mechanical response. Numerical verification of this asymptotic Griffith's law is performed in \\cref{sec:antiplane} for a mode-III crack propagation situation.\n\\end{remark}\n\n\\begin{remark}\nBased on a generalized energy-momentum tensor in the quasi-static phase-field model of fracture, authors of \\cite{Ballarini:2016aa,HakimKarma:2009} also established a link between the phase-field crack evolution and classical Griffith's theory, by providing an equivalent energy release rate. The separation of scales considered in \\cref{sec:asymptotic} summarizes and justifies the asymptotic behaviors of the displacement and damage fields assumed in their analyses.\n\\end{remark}\n\n\\section*{Summary of this Chapter}\nIn this chapter a general variational framework of the dynamic gradient damage model is outlined in \\cref{def:dynagraddama}. The evolution laws for the displacement and the damage are governed by three physical principles of irreversibility, first-order stability \\eqref{eq:vi} and energy balance \\eqref{eq:dyngdeb}, similarly to the quasi-static gradient damage model. The first-order stability \\eqref{eq:vi} is based on an extension of Hamilton's principle which involves a generalized space-time action integral \\eqref{eq:actionG}. Due to the link between damage and fracture, the gradient damage model can be regarded as a genuine model of fracture. Several damage constitutive laws can be used as long as they verify certain physics-based properties. The phase-field models in the sense of \\cite{MieheHofackerWelschinger:2010,MieheWelschingerHofacker:2010} can be obtained by using the \\eqref{eq:at2} model. To take into account possible large rotation effects, a large displacement extension of the model is discussed in an explicit dynamics context. It is based on the Eulerian Hencky logarithmic strain, see \\eqref{eq:logstrain}.\n\nBrittle materials present significantly different fracture or damage behaviors under tension and compression, hence the use of these models is essential especially in dynamics due to wave refection at the boundary. Several tension-compression asymmetry models that fit into the variational framework of \\cref{def:dynagraddama} are then reviewed. A variational interpretation is given to several existing approaches, see \\eqref{eq:variationalepspos}. It is based on the definition of a convex subset $\\mathcal{C}$ which mathematically achieves a distinction between \\emph{tension} and \\emph{compression}. A uniaxial traction/compression experiment is performed to highlight the properties of several models. In particular, the model of \\cite{MieheHofackerWelschinger:2010} widely used in the phase-field community leads to a non-vanishing stress for a completely damaged material point under compression. It should be used with caution in the presence of highly compressive loads.\n\nA better understanding of dynamic gradient damage models is then obtained via a comparison with the dynamic Griffith's law \\eqref{eq:gtgc}. In the formulation of dynamic gradient damage models, inertia effects are taken into account solely via an inclusion of the kinetic energy \\eqref{eq:kineticG} into the space-time action integral \\eqref{eq:actionG}. Static equilibrium is thus replaced by an elastic-damage wave equation \\eqref{eq:wavedyn}, however the same energy minimization principle \\eqref{eq:crackmin} still governs the damage evolution similarly in the quasi-static model. Nevertheless it turns out that the crack tip equation of motion becomes automatically rate-dependent and follows a dynamic evolution law summarized in \\cref{prop:Ggriffithlaw}, thanks to the definition of the generalized dynamic $\\widehat{J}$-integral and the generalized dynamic energy release rate $\\widehat{G}_t$. Assuming that the internal length $\\ell$ is small compared to the dimension of the body, we retrieve the classical Griffith's law of cracks outlined in \\cref{prop:whenellpetit} involving the dynamic energy release rate of the outer problem and the material toughness defined as the amount of energy dissipated across the damage process zone. This theoretic analysis justifies the interpretation of these models as a genuine fracture model.", "meta": {"hexsha": "40d8b27234169a01a162bd34a7716f6a6ced492b", "size": 141956, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ressources/example/litianyi-thesis-manuscript-a7b94b463ca5/chapters/formulation.tex", "max_stars_repo_name": "antoinetavant/PhD_thesis_manuscript", "max_stars_repo_head_hexsha": "1fdaf99356f75abc488edf1f30b5dd65f22bcdca", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-10-16T01:38:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-31T08:26:20.000Z", "max_issues_repo_path": "chapters/formulation.tex", "max_issues_repo_name": "tianyikillua/thesis-manuscript", "max_issues_repo_head_hexsha": "3d41f049377aed4e987756811b5b6a232e5af514", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/formulation.tex", "max_forks_repo_name": "tianyikillua/thesis-manuscript", "max_forks_repo_head_hexsha": "3d41f049377aed4e987756811b5b6a232e5af514", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 128.4669683258, "max_line_length": 1474, "alphanum_fraction": 0.7677942461, "num_tokens": 42146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6992544210587586, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.3359768398494669}}
{"text": "\\chapter{Specification}\\label{chap:specification}\n\nBelow ``$\\log$'' means ``$\\log_2$'', ``$\\Vert$'' is string concatenation, all hash values are 32-byte. The type of tree used is a complete binary hash tree (i.e., a complete Merkle tree).\n\n\\section{Primitives}\n\n\\gravity requires three hash functions, which all return 32-byte hash\nvalues:\n\n\\begin{itemize}\n\n\\item \\hashx takes input values of any length. We use \\textbf{SHA-256} as \\hashx.\n\n\\item \\hashy takes input values of 32 bytes. We use \\textbf{Haraka-256} with 6 rounds as \\hashy.\n\n\\item \\hashz takes input values of 64 bytes. We use \\textbf{Haraka-512} with 6 rounds as \\hashz.\n\n\\end{itemize}\nThe Haraka versions are the v2~\\cite{haraka}.\n\n\\gravity also uses \\textbf{AES-256-CTR} as a deterministic generator of pseudorandom bytes.\n\n\n\n\\section{Parameters}\n\n\\gravity signature schemes are defined by three parameters:\n\n\\begin{itemize}\n\n\\item The \\textbf{set size} $T$, which must be a power of two.\n\n\\item The \\textbf{subset size} $K$, which must be lower than $T$.\n\n\\item The \\textbf{number of subtrees} $C$, which must be a power of two and strictly lower than $T$.\n\n\\end{itemize}\n\nThese parameters determine:\n\n\\begin{itemize}\n\n\\item The \\textbf{public key size}, equal to $32C$ bytes.\n\n\\item The \\textbf{signature size}, equal to $32\\times (K + K(\\log T- \\log C)+1)$ bytes.\n\n\\end{itemize}\n\n$T$ and $K$ together determine the security and signature length, while $C$ determines the public key and signature lengths but not security. \n\nThe choice of $T$ and $K$ depends on the target security security level and on the maximum number of messages to be signed.\nThe security level for a given $(T,K)$ is discussed in \\S\\ref{sec:attacks}.\n\nThe choice of $C$ is mostly a trade-off between the public key size (higher with a higher $C$) and the  signature size (smaller with a higher $C$).\nThe optimal value of $C$ for a given $(T,K)$ is discussed in \\S\\ref{sec:tradeoff}.\n\n\n\\section{Key Generation}\n\nA secret key \\sk is a random 64-byte value, viewed as two 32-byte values $\\sk_1\\Vert\\sk_2=\\sk$.\n\nA public key \\pk is derived from a secret key's $\\sk_1$ as follows:\n\n\\begin{enumerate}\n\n\\item Expand \\sk into $T$ 32-byte \\emph{subkeys} $\\ek_0, \\ek_1, \\dots, \\ek_{T-1}$, by taking the first $32T$ bytes generated with AES-256-CTR keyed with $\\sk_1$ and with a 16-byte counter initialized to \\hex{0000\\dots0000}.\n\n\\item Hash each subkey to obtain $T$ values $L_i=\\hashy(\\ek_i)$, $i=0,\\dots,T-1$, which will be the leaves of the tree.\n\n\\item Compute $\\pk = \\pk_0, \\cdots, \\pk_{C}$ as the $C$ nodes on level $\\log C$ of the binary hash tree with leaves $L_0, \\dots, L_{T-1}$, computing $\\hashz(L_0\\Vert L_1)$, $\\hashz(L_2\\Vert L_3)$, and so on.\n\n\\end{enumerate}\n\nStep 1 requires $32T$ bytes from \\drbg, step 2 requires $T$ calls to $\\hashy$, and step 3 requires $T - C$ calls to $\\hashz$.\n\nThe value $\\log C$ can be seen as the ``cut-off'' level of the tree.\n\nThe $\\sk_2$ component of the secret key is not used in key generation, but only when signing a message.\n\n\n\\section{Subset Generation}\\label{sec:subsetgen}\n\nThe core component of \\gravity is its \\emph{subset generation function}, which picks $K$ distinct values in $0, 1, \\dots, T-1$ given a 32-byte \\emph{signature seed} $S$ and $H = \\hashx(M)$, the 32-byte hash of the message.\n\nSubset generation works like this:\n\n\\begin{itemize}\n\n\\item Compute the \\emph{subset seed} $D=\\hashz(S\\Vert H)$.\n\n\\item Generate pseudorandom bits from \\drbg keyed with $D$ and with a 16-byte counter initialized to \\hex{0000\\dots0000}.\n\n\\item Parse the pseudorandom stream as a sequence of 4-byte big-endian unsigned integers $N_0, N_1, N_2, \\dots$, where each integer is reduced modulo $T$ (since $T$ is a power of two, the distribution remains uniform)\n\n\\item Determine the $K$ distinct values $V_0,\\dots,V_{K-1}$  as follows: $V_0=N_0$; $V_1$ is the first $N_i, i>0$ such that $N_i\\neq V_0$; third value is the first subsequent $N_i$ distinct from both $V_0$ and $V_1$, and so on.\n\n\\end{itemize}\n\n\\section{Signing a Message}\n\nGiven a secret key $\\sk=\\sk_1\\Vert \\sk_2$ and a message $M$, \\gravity computes a signature $\\sig$ as follows:\n\n\\begin{enumerate}\n\n\\item Generate a subset of indices $V_0, V_1,\\dots,V_{K-1}$ as per \\S\\ref{sec:subsetgen}, using $S=\\hashz(\\sk_2 \\Vert \\hashx(M))$ as signature seed. Initialize the signature with the 32-byte $S$.\n\n\\item Expand $\\sk_1$ into $T$ 32-byte \\emph{subkeys} $\\ek_0, \\ek_1, \\dots, \\ek_{T-1}$ in the same manner as for public key generation.\n\n\\item Append $K$ subkeys to the signature in order to have $\\sig= S \\Vert \\ek_{V_0}\\Vert \\ek_{V_1}\\Vert \\cdots \\Vert \\ek_{V_{K-1}}$.\n\n\\item Compute the binary hash tree up to level $1 + \\log C$ like for public key generation, but recording the \\emph{authentication paths} for each of the $K$ leaves from the subset, as follows:\n\\begin{enumerate}\n\\item Hash each subkey to obtain leaves hashes $L_i=\\hashy(\\ek_i)$, $i=0,\\dots,T-1$.\n\\item Append to $S$ the leaf value to be hashed together with $L_{V_0}$, then the leaf value to be hashed together with $L_{V_1}$, and so on until $L_{V_{K-1}}$.\n\\item Compute the parent node of each consecutive pair of leaves by doing $\\hashz(L_0\\Vert L_1)$, $\\hashz(L_2\\Vert L_3)$, and so on. Append to $S$ the sibling hash value for each of the $K$ parents of a subkey, from $V_0$ to $V_{K-1}$; $K$ hashes are thus appended to $S$.\n\\item Iterate step (c) for upper levels of the tree, appending sibling nodes to $S$ to form $K$ authentication paths, until level $1 + \\log C$ (that is, one level deeper than the level of the subtrees' roots in the public key).\n\\end{enumerate}\n\\end{enumerate}\nThe signature $\\sig$ eventually contains, in this order: the signature seed, the $K$ hashes from step 3, and the $K(\\log T - \\log C)$ hashes from step 4.\n\nStep 1 requires one call to $\\hashx$, two calls to $\\hashz$, and at least $4K$ bytes from \\drbg; step 2 requires $32T$ bytes from \\drbg; step 4.a requires $T$ calls to $\\hashy$, then iterating step 4.b-d requires $T-C$ calls to $\\hashz$.\n\n\n\\begin{figure}\n\\includegraphics[width=16cm]{sig}\n\\caption{Content of a signature.}\n\\end{figure}\n\n\\section{Verifying a Signature}\n\nGiven a public key \\pk and a message $M$, \\gravity verifies a signature $\\sig$ as follows:\n\n\\begin{enumerate}\n\n\\item Generate a subset of indices $V_0, V_1,\\dots,V_{K-1}$ as per \\S\\ref{sec:subsetgen}, using the first 32 bytes of \\sig as a signature seed.\n\n\\item For each of the $K$ indices:\n\\begin{enumerate}\n\n\\item Retrieve the subkey from the signature, where the subkey of index $V_i$ is the $i$th 32-byte string in the signature.\n\n\\item Using the authentication path in the signature (every other $K$ hash after the signature seed), compute parent nodes up to level $\\log C$.\n\n\\item Check if the subtree root found at level $\\log C$ is the same as in the public key.\n\n\\end{enumerate}\n\\item Verification of $\\sig$ is successful only and only if all $K$ verifications succeeded.\n\\end{enumerate}\n\nStep 1 requires one call to $\\hashx$ and one call to $\\hashz$, and at least $4K$ bytes from \\drbg; step 2 requires $K$ calls to $\\hashy$ and $K (\\log T- \\log C)$ calls to $\\hashz$.\n\n\n\\begin{figure}\n\\includegraphics[width=16cm]{tree}\n\\caption{Binary hash tree of a signature, with a set of $T=8$ hashes (thus a tree depth of $\\log T=3$), a subset of $K=2$ hashes, $C=2$ subtrees (thus their two respective roots in the public key), and subset of indexes $V_0=2, V_1=5$. The nodes in black are part of the signature, the nodes in pale grey are computed during the verification, and the nodes in dark grey are part of the public key.\n}\n\\end{figure}\n\n\\section{Proposed Instances}\n\nSee Table~\\ref{tab:instances}.\n\n\\begin{table}\n\\centering \n\\begin{tabular}{c|ccc|c|ccc}\n\\toprule\n\\multirow{2}{*}{ID} & \\multicolumn{3}{c|}{Parameters} & Messages & \\multicolumn{3}{c}{Byte length} \\\\\n& $T$ & $K$ & $C$ & limit & Sig & Pub & Priv \\\\\n\\midrule\nS & $2^{17}$ & 54 & $2^{6}$ & 100 & $\\num{20768}$ & 2048 & 64 \\\\\nM & $2^{18}$ & 62 & $2^{7}$ & 300 & $\\num{23840}$ & 4096 & 64 \\\\\nL & $2^{19}$ & 64 & $2^{7}$ & 600 & $\\num{26656}$ & 4096 & 64 \\\\\n\\bottomrule\n\\end{tabular}\n\\caption{Proposed \\gravity instances, expected to provide 128-bit pre- and post-quantum security.}\n\\label{tab:instances}\n\\end{table}\n", "meta": {"hexsha": "8077efbc8f708040f2dbee09cb1c3811dbdf2b3e", "size": 8214, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Supporting_Documentation/latex_source/chapters/specification.tex", "max_stars_repo_name": "gravity-postquantum/prune-horst", "max_stars_repo_head_hexsha": "23560366f55ddc3029bc72f18ba207e0f8334c22", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2017-09-25T16:27:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T15:35:30.000Z", "max_issues_repo_path": "Supporting_Documentation/latex_source/chapters/specification.tex", "max_issues_repo_name": "gravity-postquantum/prune-horst", "max_issues_repo_head_hexsha": "23560366f55ddc3029bc72f18ba207e0f8334c22", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Supporting_Documentation/latex_source/chapters/specification.tex", "max_forks_repo_name": "gravity-postquantum/prune-horst", "max_forks_repo_head_hexsha": "23560366f55ddc3029bc72f18ba207e0f8334c22", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2017-09-26T08:46:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T09:28:19.000Z", "avg_line_length": 46.1460674157, "max_line_length": 397, "alphanum_fraction": 0.7083028975, "num_tokens": 2581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6992544210587586, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.33597683984946686}}
{"text": "\\documentclass[preprint]{sigplanconf}\n\n\\usepackage{graphicx}\n\\usepackage{longtable}\n\\usepackage{comment}\n\\usepackage{amsmath}\n\\usepackage{mdwlist}\n\\usepackage{txfonts}\n\\usepackage{xspace}\n\\usepackage{amstext}\n\\usepackage{amssymb}\n\\usepackage{stmaryrd}\n\\usepackage{proof}\n\\usepackage{multicol}\n\\usepackage[nodayofweek]{datetime}\n\\usepackage{etex}\n\\usepackage[all, cmtip]{xy}\n\\usepackage{xcolor}\n\\usepackage{listings}\n\\usepackage{multicol}\n\\usepackage{bm}\n\n\n\\newtheorem{theorem}{Theorem}[section]\n\\newtheorem{lemma}[theorem]{Lemma}\n\\newtheorem{proposition}[theorem]{Proposition}\n\\newtheorem{corollary}[theorem]{Corollary}\n\n\\newcommand{\\xcomment}[2]{\\textbf{#1:~\\textsl{#2}}}\n\\newcommand{\\amr}[1]{\\xcomment{Amr}{#1}}\n\\newcommand{\\roshan}[1]{\\xcomment{Roshan}{#1}}\n\n\\newcommand{\\ie}{\\textit{i.e.}\\xspace}\n\\newcommand{\\eg}{\\textit{e.g.}\\xspace}\n\n\\newcommand{\\lcal}{\\ensuremath{\\lambda}-calculus}\n\\newcommand{\\G}{\\ensuremath{\\mathcal{G}}\\xspace}\n\n\\newcommand{\\code}[1]{\\lstinline[basicstyle=\\small]{#1}\\xspace}\n\\newcommand{\\name}[1]{\\code{#1}}\n\n\\def\\newblock{}\n\n\\newenvironment{floatrule}\n    {\\hrule width \\hsize height .33pt \\vspace{.5pc}}\n    {\\par\\addvspace{.5pc}}\n\n%subcode-inline{bnf-inline} name langRev\n%! swap+ = \\mathit{swap}^+\n%! swap* = \\mathit{swap}^*\n%! dagger =  ^{\\dagger}\n%! assocl+ = \\mathit{assocl}^+\n%! assocr+ = \\mathit{assocr}^+\n%! assocl* = \\mathit{assocl}^*\n%! assocr* = \\mathit{assocr}^*\n%! identr* = \\mathit{uniti}\n%! identl* = \\mathit{unite}\n%! dist = \\mathit{distrib}\n%! factor = \\mathit{factor}\n%! (o) = \\fatsemi\n%! (;) = \\fatsemi\n%! (*) = \\times\n%! (+) = +\n\n%subcode-inline{bnf-inline} regex \\{\\{(((\\}[^\\}])|[^\\}])*)\\}\\} name main include langRev\n%! Gx = \\Gamma^{\\times}\n%! G = \\Gamma\n%! [] = \\Box\n%! |-->* = \\mapsto^{*}\n%! |-->> = \\mapsto_{\\ggg}\n%! |--> = \\mapsto\n%! |- = \\vdash\n%! ==> = \\Longrightarrow\n%! <== = \\Longleftarrow\n%! <=> = \\Longleftrightarrow\n%! <-> = \\leftrightarrow\n%! ~> = \\leadsto\n%! -o = \\multimap\n%! ::= = &::=&\n%! /= = \\neq\n%! forall = \\forall\n%! exists = \\exists\n%! empty = \\epsilon\n%! langRev = \\Pi\n%! langRevT = \\Pi^{o}\n%! langRevEE = \\Pi^{\\eta\\epsilon}\n%! theseus = Theseus\n%! * = \\times\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\begin{document}\n\n\\conferenceinfo{ICFP'12}{}\n\\CopyrightYear{}\n\\copyrightdata{}\n\\titlebanner{}\n\\preprintfooter{}\n\n\\title{Functional Pearl --- Programming with \\\\ \n  Negative, Fractional, Square Root, and Imaginary Types} \n\\authorinfo{Roshan P. James}\n           {Indiana University}\n           {rpjames@indiana.edu}\n\\authorinfo{Amr Sabry}\n           {Indiana University}\n           {sabry@indiana.edu}\n\\maketitle\n\n\\begin{abstract}\n  Every functional programmer knows about sum and product types, $a+b$ and\n  $a*b$ respectively. Negative, fractional, square root, and imaginary types,\n  $a-b$, $a/b$, $\\sqrt{a}$, and $a+ib$ respectively, are much less known and\n  their computational interpretation is unfamiliar and often complicated. We\n  show that in a programming model in which information is preserved (such as\n  the model introduced in our recent paper on \\emph{Information Effects}),\n  these types have particularly intuitive and natural computational\n  interpretations. Intuitively, values of negative types are values that flow\n  ``backwards'' to satisfy demands, values of fractional types are values\n  that represent first-class ``structural'' constraints, and values of square\n  root and imaginary types are values that can be related by arbitrary\n  algebraic constraints. The combination of these negative, fractional,\n  square root, and imaginary types enable greater flexibility in programming\n  by breaking complicated invariants into local ones that can be\n  independently satisfied by a subcomputation. Furthermore, they allow a\n  programmer to express a wide range of programming idioms, including\n  higher-order functions, delimited continuations, speculative computation,\n  logic programming, and more.\n\\end{abstract}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\category{D.3.1}{Formal Definitions and Theory}{}\n\\category{F.3.2}{Semantics of Programming Languages}{}\n\\category{F.3.3}{Studies of Program Constructs}{Type structure}\n\n\\terms\nLanguages, Theory\n\n\\keywords continuations, information flow, linear logic, logic programming,\nquantum computing, reversible logic, symmetric monoidal categories, compact\nclosed categories.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Introduction}\n\nThe world of computation we are describing has:\n\\begin{itemize}\n\\item suppliers, \n\\item consumers, and\n\\item bi-directional transformations\n\\end{itemize}\nThis is the same world described by the papers on the duality of computation\nbut that work only scratched the surface! We have the following features:\n\\begin{itemize}\n\\item we can start from the supplier and push the values towards the\n  consumer (call-by-value in the duality of computation papers)\n\\item we can start from the consumer and pull the values from the suppliers\n  (call-by-name in the duality of computation papers)\n\\item we can combine the pushing and pulling and values using eta/epsilon for\n  sum types; these allow us to at any point in the middle of the computation\n  create out of nothing a value to send to the consumers and a demand to send\n  to the suppliers.\n\\item we can break a big data structure into fragments described by\n  fractional types; the suppliers and consumers can produce and consume the\n  pieces completely independently of each other. Eventually the pieces will\n  fit together at the consumer to produce the desired output.\n\\item we can break a bi-directional transformation into pieces using square\n  roots\n\\item we can take into account that values have phase (complex numbers),\n  i.e., it is not that they flow towards the consumer or just towards the\n  suppliers; they can be flowing in direction that ``30 degrees'' towards the\n  consumer for example.\n\\end{itemize}\nSo it is all about breaking dependencies in some sense to allow for maximum\nautonomy (parallelism) of subcomputations. It is probably the case that to\nmake full use of square root types and imaginary types, we have to move to a\nvector space. If that's the case, we should probably leave this stuff out and\nfocus on negative and fractional types and only have a short discussion of\nthe polynomials restricted to seven trees in one and similar issues.\n\nThe conventional idea is to divide the world into a ``real'' one and a\n``virtual'' one. In the ``real'' world, we can define datatypes like\n\\verb|t=t^2+1| but we don't have additive inverses so it makes no sense to\ntalk of negative types and we can't rearrange the terms in the datatype\ndefinition. However the observation is that we can map these datatypes to a\nvirtual world that has more structure (a ring that provides additive inverses\nor a field that also provides multiplicative inverses) and then perform\ncomputations in the ring/field. If we perform computations in the ring, then\nsome of these will use additive inverses in ways that cannot be mapped back\nto the ``real'' world. Much of current research attempts to characterize\nwhich computations done in the ring are valid isomorphisms between datatypes\nin the ``real'' world. This is nice but is not what I am after. In fact I am\nnot interested in the ring or the semiring at all. I am interested in the\nfield and I want this field to be \\textbf{the real world.} This is partly\nmotivated by the fact that Quantum Mechanics seems to demand an underlying\nfield and more generally that the field provides the maximum generality in\nslicing and dicing computations. So assuming I live in a field and that the\nnegative, fractional, square root, and imaginary types are all ``real,'' how\ndo I compute in this field? Clearly there will be constraints on\n``measurement'' in the sense that a full program cannot produce any of the\ncrazy types but that's done outside the formalism in some sense just as in\nQuantum Computing. The main question I am after is how to compute in this\nfield with first-class negative, fractional, etc. types. As I mentioned in my\nprevious email, we can produce programs that have types \\verb|t^3 <-> -1| and\nthey ``run'' (but only to give infinite loops). \n\nSo when a programmer writes the datatype declaration \\verb|t = t^2+1|, if we\nallow negative etc. then this is effectively writing \n\\verb|t = cubicroot{-1}|. If we are in the field then computations that \nmanipulate these trees can be sliced and diced even at interfaces that\nexpose the cubic root and the imaginary types. \n\nFuture work: develop a type system for a ``normal language'' that has\nnegative, fractional, etc. types as first-class types. More long term,\ninstead of adding one polynomial at a time, we can go to an algebraically\nclosed field. The complex numbers is an obvious choice but I would rather go\nto something computable like the field of algebraic numbers. Is the adele\nring or the p-adics relevant here?\n\nWe show a deep symmetry between functions and delimited continuations,\nvalues and continuations that arises in {{langRev}} in a manner that\nis reminiscent of Filinksi's Symmetric \\lcal\n~\\cite{Filinski:1989:DCI:648332.755574}. The symmetry arises by\nextending {{langRev}} with a notion of additive duality over the\nmonoid {{(+, 0)}} by including {{eta}} and {{eps}} operators of\nCompact Closed Categories. The resulting dual types, which we denote\n{{-b}}, have a time traveling ``backward information flow''\ninterpretation and allow for the encoding of higher-order function and\niteration via the construction of {{trace}} operators, thereby making\nthe extended language {{langRevEE}} a Turing-complete reversible\nprogramming language with higher-order functions and first-class\ndelimited continuations.\n\nWe introduced this thesis that computation should be based on isomorphisms\nthat preserve information~\\cite{infeffects}. Since Filinski, we've had the\nidea that values and continuations are like mirror images. In a conventional\nlanguage, the negative (continuation) side is implicit and we introduce\ninformation effects on the positive. Trying to recover the duality from this\ndistorted positive side has always been messy. Now it looks clean because we\nhave kept the positive side pure.\n\nThe way to think about something of type $A$ is that it is a value we have\nproduced. The way to think about something of type $-A$ is that is a value we\nhave already consumed. \n\nOther interpretations of the types of think about. The first one is\narithmetic obviously. Another one is languages consisting of sets of\nstring. The type 0 is the empty set, the type 1 is the set containing the\nempty word, the $+$ constructor corresponds to union, and the $*$ constructor\ncorresponds to concatenation. The constructor $-$ would not correspond to set\ndifference however. It would correspond to marking the elements in the set as\n``consumed'' so that if we take the union and a ``consumed'' element appears\nin the other set, the two cancel. This makes it clear that concatenating a\nproduced $a$ and a consumed $b$ is not the same as concatenating a consumed\n$a$ and a produced $b$. They really need to be kept separate. Incidentally,\ndivision would be defined as follows:\n\\[\nL_1 / L_2 = \\{ x ~|~ xy \\in L_1 \\mbox{~for~some~} y \\in L_2 \\}\n\\]\n\nConnections to type logical grammars and Lambek calculus\n\nSome background on {{langRev}} because it is mentioned in the next section.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Negative Types: Intuition} \n\nConsider the following two ways of purchasing an item that costs \\$20.00:\n\\begin{enumerate}\n\\item You give the seller a \\$20.00 bill.\n\\item You use a credit card to pay the seller.\n\\end{enumerate}\nIn both cases, the seller receives the money immediately but there is a\nsubtle difference. In the first transaction, the money received by the seller\ncorresponds to a value that has been produced earlier in the computation. In\nthe second transaction, the money may or may not exist yet: computationally,\na \\emph{debt} is generated to compensate for the money received by the seller\nand this debt travels ``backwards'' towards the bank where it is (hopefully)\nreconciled.\n\nThe example suggests that the ability to consider values flowing backwards\nenriches our computational model. This observation goes back to Filinski's\nMasters thesis where continuations are identified with these negative values.\nWe discuss the connections to Filinski's work and others in more detail in\nSec.~\\ref{sec:related}. For now, we note that in a conventional programming\nlanguage in which values can be copied and deleted at will, extreme care is\nneeded to keep track of negative values. Indeed, in the example above, if it\nwere possible to simply delete the variable corresponding to the debt, we\nwould have produced money out of nothing. \n\nFor this reason, our treatment of negative values in the context of\n{{langRev}} is particularly simple. We will have a type $0$ and an\nisomorphism {{0 <-> a + (-a)}} that when used in the left-to-right direction\nallows us to create a value and a corresponding debt out of nothing. Both the\nvalue and its negative counterpart can flow anywhere in the system. Because\ninformation is preserved, a closed program (which does not have any\n``dangling'' negative values) will eventually have to match the negative\nvalue with some corresponding value, effectively using the isomorphism in the\nright-to-left direction. In more detail, we can model the credit card\ntransaction above using the following program (shown diagrammatically):\n\nFIGURE\n\nCLEAN UP the following based on the figure. In contrast, in our setting, one\ncan start from the empty type $0$, introduce a positive value and its\nnegative counterpart, and let each of these flow in arbitrary ways. The\nentire framework guarantees that neither the value nor its negative\ncounterpart will be deleted or duplicated and hence that, in any closed\nprogram, the ``debt'' corresponding to the negative value is paid off exactly\nonce. Computationally we model the first transaction using essentially the\nidentity function which receives a \\$20.00 bill as input from the buyer and\npropagates it on its output to the seller. The second transaction is more\ncomplicated. We model it as shown in the circuit below: There are two ways to\nunderstand this circuit that are both quite instructive. Let's first examine\nthe type structure of each of the combinators that comprise the circuit. The\nfirst combinator on the right outputs \\$20.00 to the seller. This \\$20.00 is\nproduced from nothing so to speak by generating an equivalent debt that\ntravels backwards. COMPLETE BASED ON THE FIGURE. The other way is to follow\nthe execution. It goes forward in time so to speak, comes back, and then goes\nforwards again.\n\nIt is critical that the framework in which the negative types are introduced\nis a framework in which all information is preserved, with no duplication or\nerasure. This guarantees that the generated debts are paid once and exactly\nonce.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Fractional Types: Intuition} \n\nThe type $a/b$ is prominent in the Lambek-Grishin calculus which is\nextensively used in computational linguistics. In the common interpretation,\na value of type $a/b$ is a value of some type $c$ such that when put in a\ncontext of type $b$, the result is a value of type $a$. For example, assuming\ncontexts are represented as functions, a value of type $\\texttt{bool} /\n(\\texttt{int} \\rightarrow \\texttt{bool})$ is simply a value of type\n$\\texttt{int}$. Indeed in this case, putting a value of type $\\texttt{int}$\nin the context $(\\texttt{int} \\rightarrow \\texttt{bool})$ produces a value of\ntype $\\texttt{bool}$. \n\nIn our case, the situation is simpler. If the goal is to produce a value of\ntype {{a * b}} and a subcomputation can only produce the {{a}}-part, it would\nhave type {{(a * b) / b}}. In most settings, this type would be equivalent to\n{{a}}. However in our setting, the constraint that this value must eventually\nfit in a larger value that supplies the {{b}} is explicitly recorded and must\nbe resolved. In more detail, we have an isomorphism {{ 1 <-> a * (1/a) }}\nwhich when used in the left-to-right direction allows the creation of a value\nand a corresponding constraint on the context.  Both the value and the\nconstraint can flow in arbitrary ways during the computation but eventually\nin a closed program with no ``dangling'' constraints, the isomorphism should\nbe used in the right-to-left direction to resolve the constraints.  To\nunderstand the computational interpretation, consider the following example.\n\nThe goal is to produce a value of type $(\\texttt{bool} \\times\n\\texttt{int})$. One part of the program, $e_1$, knows how to produce the\nvalue of type $\\texttt{int}$ (say {{3}}) and another part, $e_2$, knows how\nto produce the value of type $\\texttt{bool}$ (say {{true}}). Computationally,\nwe model this as follows. The first subcomputation $e_1$ produces {{((),3)}}\nand uses the isomorphism to convert {{()}} to {{(alpha,1/alpha)}} where\n{{alpha}} is a yet-unknown boolean value. Reshuffling the components, $e_1$\nproduces {{((alpha,3), 1/alpha)}}. Similarly, $e_2$ can independently produce\n{{((true,beta),1/beta)}} where {{beta}} is a yet-unknown integer value.\nWhen the two values meet, we can group the components as follows:\n\\[\n{{(alpha,beta)}}  {{(3,1/beta)}}  {{(true,1/alpha)}}\n\\]\nUsing the isomorphism in the right-to-left direction on the last two pairs,\nforces {{alpha}} to be resolved to {{true}} and forces {{beta}} to be\nresolved to {{3}}. Both of these pairs then become {{()}} and be absorbed. We\nare left with the pair {{(true,3)}} as desired. \n\nTo summarize, one can think of a value of type $a/b$ as a value that imposes\na constraint on its context of use: it is a value that requires its context\nto be of type $b$ and only if that condition is satisfied, can the value be\nconsidered as a value of type $a$. In the simplest case, the type $1/b$ just\nconstraints the context to be of type $b$. By allowing the fractional types\nto be first-class, we can separate the generation of constraints from their\nuse. Both the value and the constraint can flow in arbitrary ways during the\ncomputation but eventually in a closed program with no ``dangling''\nconstraints, the isomorphism should be used in the right-to-left direction to\nresolve the constraints.\n\nNEED to work out the example in detail (or perhaps another example that's\nbetter. \n\nAgain it is critical that the framework in which the fractional types are\nintroduced is a framework in which all information is preserved, with no\nduplication or erasure. This guarantees that the generated constraints are\nsatisfied once and exactly once. \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Algebraic Types: Intuition} \n\nSquare root and imaginary types have also appeared in the literature: we\nrelegate the connections to Sec.~\\ref{related} and proceed with a simple\nexplanation. We have so far extended the set of types to be the rational\nnumbers. Now we will push this and extend the set of types to algebraic\nnumbers. In other words, we will allow datatypes defined by arbitrary\npolynomials and allow the roots of such polynomials to be types. \n\nConsider first an example in which we want to compute with the sides of a\nrectangle whose area is 91 and whose length is longer than its width by 6\nunits. One can solve the quadratic equation to determine that the sides are 7\nand 13 and proceed. This however prematuraly forces us to globally solve the\nconstraint. Instead we can let the two sides of the rectangle be $x$ and\n$x+6$ and use the following equation to capture the desired constraint:\n\\[\nx^2 + 6x - 91 = 0\n\\]\nThe equation introduces an isomorphism between the type $x^2 + 6x - 91$ and\nthe type $0$. We can now proceed to compute with the unknown $x$, being\nassured that in a closed program, our computation will eventually be\nconsistent with the solution of the algebraic equation. \n\nPreviously the most famous example of a similar nature is the puzzling\nisomorphism that one can establish between seven binary trees and one.\nA binary tree is defined by the datatype\n\\[\nx = 1 + x * x \n\\]\nwhich can be rearranged to the polynomial equation $x^2 - x + 1 = 0$. By\nalgebraic manipulation we can reason as follows:\n\\[\\begin{array}{rclclclcl}\nx^3 &=& x^2 x &=& (x-1) x &=& x^2 - x &=& -1 \\\\\nx^6 &=& 1 \\\\\nx^7 &=& x^6 x &=& x\n\\end{array}\\]\nFiore poses the question of why such algebraic manipulation would make sense\ntype theoretically but states that even though some of the intermediate steps\nmake no sense, the final equivalence is valid and can be used to actually\nconstruct an isomorphism between $x^7$ the type of seven binary trees \nand $x$ the type of binary trees.\n\nDiscussion of possible polynomials:\n\\begin{itemize}\n\\item $b=1+1$. Boring.\n\\item $b=b+1$. That introduces the natural numbers. No solution for this\n  polynomial over the algebraic numbers. We must extend the numbers with\n  $\\omega$ to get a solution. We reject this in this paper and prefer to\n  stick to algebraic numbers. The advantage is that all the isomorphisms are\n  valid numerically. With the above type we could subtract $b$ from both\n  sides to show that $0=1$ which is nonsense. We can however have infinite\n  types as long as they have algebraic solutions.\n\\item $b^2=2$ or $b = \\pm \\sqrt{2}$. We have introduced the square root of a\n  boolean! If we had superpositions, we could then write a function that\n  performs the square root of negation in the sense that applying it twice\n  would be equivalent to boolean negation.\n\\end{itemize}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Summary}\n\nTo summarize negative, fractional, square root, and imaginary types all make\nsense. What they help you accomplish as a programmer is to disassociate\nglobal invariants into local ones that can be satisfied independently by\nsubcomputations with no synchronization or communication. A computation\nproducing something of type $a/b$ does not need to concern itself with who is\ngoing to supply the missing $b$: it just does its part. Conversely faced with\na complicated task, a computation might decide to break it into pieces and\ndemand these pieces using negative types. \n\nIt is no surprise that these types are closely related to quantum mechanics\nand that they give us the feel that this is how nature computes. This is\nspeculation however.\n\nIn any case, in a framework where information can be copied and deleted, none\nof this makes much sense. It is critical that these constraints and demands\ncan neither be duplicated nor erased.  This gives us the maximum\n``parallelism'' possible.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Additive Duality in {{langRev}} }\n\n%%%%%%%%%%%%%%%\n\\subsection{Syntax}\n\n%subcode{bnf} include main\n% Values, v = () | (v, v) | L v | R v\n% Combinators, c &=& iso | c (;) c | c(+)c | c (*) c \n%\n% Sequential Contexts, P, F = [] | P:c\n% Parallel Contexts, D = [] \n%                     &|& D:(P| [](+)c| F)\n%                     &|& D:(P| c(+)[]| F)\n%                     &|& D:(P| [] (*) c v| F)\n%                     &|& D:(P| [] (*) v c| F)\n%                     &|& D:(P| c v (*)  []| F)\n%                     &|& D:(P| v c (*) []| F)\n%\n%\n% Machine States  = D[P| c v| F] | D[P| v c| F]\n% Start State  = [][[]| v c| []]\n% Stop State  = [][P| c v| []]\n\nCombinator reconstruction, {{P[c]}}:\n%subcode{opsem} include main\n% [](c) '= c\n% P:c'(c) '= P(c'(;)c)\n\n%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Operational Semantics}\n\nThe small step semantics present for {{langRev}} below work\nsymmetrically for forward and backward evaluation.\n\n\\begin{itemize}\n\\item \nBasic reduction of an isomorphism. Note that the evaluation leaves the\nadjoint of the combinator behind. This will become important when we\nreverse the direction of computation.\n%% %subcode{opsem} include main\n%% % <P; F; iso v; D>      &|-->& <P; F; v'~ iso{dagger}; D>\n\n%subcode{opsem} include main\n% D[P|v iso| F]      &|-->& D[P| iso{dagger} v| F]\n\n\\item\nSequencing involves pushing and popping from the Future and Past\ncontinuations:\n%subcode{opsem} include main\n% D[P|v (c1(;)c2)| F]  &|-->& D[P| v c1| F:c2]\n% D[P| c1 v| F:c2] &|-->& D[P:c1| v c2| F]\n\n\n\\item\nParallel composition, captures the current Future and Past and extends\nthe parallel context.\n%subcode{opsem} include main\n% D[P|(L v) c1 (+) c2| F] &|-->& D:(P|[](+)c2|F)[ []| v c1| [] ]\n% D[P| (R v) c1 (+) c2| F] &|-->& D:(P|c1(+)[]|F)[ []| v c2| [] ]\n% D:(P|[](+)c2|F)[P'|c1 v| [] ]  &|-->& D[P|(P'(c1)(+)c2{dagger}) (L v)| F] \n% D:(P|c1(+)[]|F)[P'| c2 v| [] ] &|-->& D[P|(c1{dagger}(+)P'(c2)) (R v)| F]\n\n\n\\item\nSimilarly for products:\n%subcode{opsem} include main\n% D[P| (v1, v2) c1 (*) c2| F] &|-->& D:(P| [] (*) v2 c2|F)[ []| v1 c1| [] ]\n% D:(P|[] (*) v2 c2|F)[P'| c1 v1| [] ] &|-->& D:(P|P'(c1) v1 (*) []|F)[ []| v2 c2| [] ]\n% D:(P|c1 v1(*) []|F)[P'|c2 v2| [] ]  &|-->& D[P|c1(*)P'(c2) (v1, v2)| F]\n\n\nand symmetrical rules for evaluation along the second branch. \n%subcode{opsem} include main\n% D:(P|v1 c1 (*) []|F)[P'| c2 v2| [] ] &|-->& D:(P,[] (*) P'(c2) v2,F)[ []| v1 c1| [] ]\n% D:(P|[] (*) c2 v2|F)[P'|c1 v1| [] ] &|-->& D[P |P'(c1) (*) c2 (v1, v2)| F]\n\nThe later two rules will be relevant only for reverse execution. \n\n\\end{itemize}\n\n\n%%%%%%%%%%%%%%%%%\n\\subsection{Rules for {{eta}} and {{eps}} }\n\nThe operation {{eps}} reverses the direction of a particle by\nreversing the world. \n\nNote that we deviate from the categorical definition of {{eta}} and\n{{eps}} slightly in that they swap the order of {{-b}} and {{b}} in\nchoice of {{eta}}. This however does not affect us, because we deal\nwith a symmetric category.\n\n\\begin{itemize}\n\\item Grammar\n%subcode{bnf} include main\n% Values, v = () | (v, v) | L v | R v | -v\n% Isomorphisms, iso &=& ... | eta | eps\n% Combinators, c &=& iso | c (;) c | c(+)c | c (*) c \n\n\\item\nType judgement.\n%subcode{opsem} include main\n% eta &: 0 <-> (-b) + b :& eps\n\n%subcode{proof} include main\n%@ |- v : b\n%@@ |- -v : -b\n\n\\item\nOperational Semantics.\n%subcode{opsem} include main\n% D[P| (R v) eps| F]      &|-->&  D{dagger}[F | eps (L (-v))| P]\n% D[P| (L (-v)) eps| F]      &|-->&  D{dagger}[F | eps (R v)| P]\n\nNote: there is NO reduction rule for {{eta}}. \n\n\\item\nThe adjoint of a parallel context is defined to be:\n%subcode{opsem} include main\n% []{dagger} '= []\n% (D:(P, [](+)c, F)){dagger} '= D{dagger}:(F, [](+)c{dagger}, P)\n% (D:(P, c(+)[], F)){dagger} '= D{dagger}:(F, c{dagger}(+)[], P)\n% (D:(P, [](*)c v, F)){dagger} '= D{dagger}:(F, [](*)v c, P)\n% (D:(P, [](*)v c, F)){dagger} '= D{dagger}:(F, [](*)c v, P)\n% (D:(P, c v(*)[], F)){dagger} '= D{dagger}:(F, v c(*)[], P)\n% (D:(P, v c(*)[], F)){dagger} '= D{dagger}:(F, c v(*)[], P)\n\n\\end{itemize}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Diagrams}\n\n{{eta}}\n\n\\begin{center}\n  \\includegraphics{diagrams/eta.pdf}\n\\end{center}\n\nNote that the connective is a {{+}}, hence only one of the branches\nmay be inhabited at any time. Thus the action of {{eta}} is to\ntransfer a backward flowing value on one wire to a forward flowing\nvalue on the other wire.\n\n{{eps}}\n\n\\begin{center}\n  \\includegraphics{diagrams/eps.pdf}\n\\end{center}\n\nCoherence condition\n\n\\begin{center}\n  \\includegraphics{diagrams/coherence.pdf}\n\\end{center}\n\nFunction\n\n\\begin{center}\n  \\includegraphics{diagrams/function.pdf}\n\\end{center}\n\nLet us use the shorthand {{b1 -o b2 = -b1 + b2}}\n\nFunction application\n\n\\begin{center}\n  \\includegraphics{diagrams/apply1.pdf}\n\\end{center}\n\n\\begin{center}\n  \\includegraphics{diagrams/apply2.pdf}\n\\end{center}\n\n\nFunction composition\n\n\\begin{center}\n  \\includegraphics{diagrams/compose1.pdf}\n\\end{center}\n\n\\begin{center}\n  \\includegraphics{diagrams/compose.pdf}\n\\end{center}\n\nThis is also equivalent to sequencing both the computation blocks. \n\n\\begin{center}\n  \\includegraphics{diagrams/compose2.pdf}\n\\end{center}\n\n\nDelimited continuation\n\n\\begin{center}\n  \\includegraphics{diagrams/delimc.pdf}\n\\end{center}\n\nTrace \n\n%subcode{proof} include main\n%@ c : b2 + b1 <-> b2 + b3\n%@@ trace c : b1 <-> b3\n\n\\begin{center}\n  \\includegraphics{diagrams/trace.pdf}\n\\end{center}\n\nDouble Negation\n\n{{b <-> -(-b)}}\n\n\\begin{center}\n  \\includegraphics{diagrams/double_neg.pdf}\n\\end{center}\n\nNegation distributes over {{+}}.\n\n{{-(b1 + b2) <-> (b1) + (-b2)}}\n\n\\begin{center}\n  \\includegraphics{diagrams/dist_neg_plus.pdf}\n\\end{center}\n\n{{eps_{fst} }}\n\n{{(-b1)*b2 + b1*b2 <-> 0}}\n\n\\begin{center}\n  \\includegraphics{diagrams/eps_fst.pdf}\n\\end{center}\n\nLifting negation out of {{*}}.\n\n{{(-b1) * b2 <-> -(b1 * b2) <-> b1 * (-b2)}}\n\n\\begin{center}\n  \\includegraphics{diagrams/mult_neg.pdf}\n\\end{center}\n\nThe following isomoprhism can be constructed similarly \n\n{{b1 * b2 <-> (-b1)*(-b2)}}\n\n\nLifting a operation of postive types to negated types:\n\nGiven {{c : b1 <-> b2}}\n\n\\begin{center}\n  \\includegraphics{diagrams/neg_lift.pdf}\n\\end{center}\n\n\\paragraph*{Observability.} \nExecution of program is defined by {{c : b1 <-> b2}} when evaluated on\ninput {{v1 : b1}} gives us a value {{v2 : b2}} on\ntermination. Execution is well defined only if {{b1}} and {{b2}} are\nentirely positive types. Consider the program that\n\n\\begin{center}\n  \\includegraphics{diagrams/shuffle.pdf}\n\\end{center}\n\nWe define observables to be only positive types. The ouputs of\nprograms that ouput mixed positive and negative types are not\nobservable.  Also, programs that input mixed positive and negatives\ntypes are not executable.\n\n\\subsection{To think about}\n\n\\begin{itemize}\n\n\\item If we built an effect over {{langRevEE}}, say {{create}} and\n  {{erase}}, are effects structured by an arrow or a monad now?\n\n\\item Which operations can be lifted to work on negative types?\n\n\\item Can the operational semantics for {{langRevEE}} be an\n  interpreter that is implemented in {{langRevT}} (similar to how the\n  the tree traversal interpreter was implemented). This would imply\n  the existence of a more powerful construction than Int, wherein the\n  products would also be preserved. This is possibly worth a paper in\n  itself.\n\n\\item These functions aren't really values. There is no value one can\n  produce that denotes a function. These functions are the ability to\n  transform a value - the possibility of transforming a value.  In the\n  product encoding of environments, there is no value one can assign\n  to a variable such that it denotes a function.\n\n\nActually this is possible. Consider two functions {{f : b1 <-> b2}}\nand {{g : b1 <-> b2}}. A value of type {{bool}} is sufficient to\ndiscriminate them. Hence the {{boo}} is the first class representation\nof the functions and can be thought of as the address of the function. \n\n\\begin{center}\n  \\includegraphics{diagrams/dispatch.pdf}\n\\end{center}\n\n\n\\item It is not fair to say that negative types flow backwards. The\n  following circuits are valid in {{langRevEE}}. It is however proper\n  to say that for any type {{b}} that flows in a direction, the type\n  {{-b}} flows in the reverse direction. \n\n\\begin{center}\n  \\includegraphics{diagrams/neg_circuit1.pdf}\n\\end{center}\n\n\\begin{center}\n  \\includegraphics{diagrams/neg_circuit2.pdf}\n\\end{center}\n\n\\end{itemize}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Multiplicative Duality in {{langRev}} }\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Related Work} \n\\label{sec:related}\n\nFilinski proposes that continuations are a \\emph{declarative} concept. He,\nfurthermore, introduces a symmetric extension of the $\\lambda$-calculus in\nwhich values and continuations are treated as opposites. This is essentially\nwhat we are proposing with one fundamental difference: our underlying\nlanguage is not the $\\lambda$-calculus but a language of pure isomorphisms in\nwhich information is preserved. This shift of perspective enables us to\ndistill and generalize the duality of values and continuations: in\nparticular, in the conventional $\\lambda$-calculus setting values and\ncontinuations can be erased and duplicated which makes it difficult to\nmaintain the correspondence between a value and its negative counterpart. \n\n\\paragraph*{Continuations.} The idea of using negative types to model\ninformation flowing backwards, demand for values, continuations, etc. goes\nback to at Filinski's thesis. We recall these connections below but we first\nnote that all these systems are complicated because in all these systems\ninformation can be ignored, destroyed, or duplicated. Clearly the possibility\nof erasure of information would mean that our credit card transaction is\nincorrect. In our work, information is maintained and hence we have a\nguarantee that, in a closed program, the debt must be accounted and paid for.\n\n\\paragraph*{Filinski~\\cite{Filinski:1989:DCI:648332.755574}.}\nIn his Masters thesis, Filinski proposes that continuations are a\n\\emph{declarative} concept. He, furthermore, introduces a symmetric extension\nof the $\\lambda$-calculus in which values and continuations are treated as\nopposites. This is essentially what we are proposing with one fundamental\ndifference: our underlying language is not the $\\lambda$-calculus but a\nlanguage of pure isomorphisms in which information is preserved. This shift\nof perspective enables us to distill and generalize the duality of values and\ncontinuations: in particular, in the conventional $\\lambda$-calculus setting\nvalues and continuations can be erased and duplicated which makes it\ndifficult to maintain the correspondence between a value and its negative\ncounterpart. In contrast, in our setting, one can start from the empty type\n$0$, introduce a positive value and its negative counterpart, and let each of\nthese flow in arbitrary ways. The entire framework guarantees that neither\nthe value nor its negative counterpart will be deleted or duplicated and\nhence that, in any closed program, the ``debt'' corresponding to the negative\nvalue is paid off exactly once. The forward and backward executions in our\nframework correspond to call-by-value and call-by-name. This duality was\nobserved by Filinski and others following him but it is particularly clean in\nour framework.\n\n\\paragraph*{Subtraction} Wadler the reloaded paper, does not consider the\nsubtraction type because its ``computational interpretation is not\nfamiliar.'' Curien and Herbelin study duality in classical logic, show that\nit exchanges call-by-value and call-by-name. They extend classical natural\ndeduction with subtraction but give it no computational meaning. Crolard (in\nthe formulae-as-types interpretation of subtractive logic) address the\ncomputational interpretation of substraction. He explains the type $A-B$ as\nthe of \\emph{coroutines} with a local environment of type $A$ and a\ncontinuation of type $B$. The description is complicated by what is\nessentially the desire to enforce linearity constraints so that coroutines\ncannot access the local environment of other coroutines. Must cite Selinger\ncontrol categories in this context of duality but I am not sure what to say:\nit assumes cartesian closed categories for one thing and not symmetric\nmonoidal ones. Ariola, Herbelin, and Sabry also use subtractive types to\nexplain delimited continuations. \n\n\\paragraph*{Linear Logic} In accounts that are linear, the value and\ncontinuation that comprise the substractive type need to be constrained to\n``stay together.'' This can be achieved by various restrictions. In this work\nwe have no such constraints, the negative value can flow anywhere. The entire\nsystem guarantees that any closed program would have to account for it. We\ndon't have to introduce special constraints to achieve that. Zeilberger in\nthe paper on polarity and the logic of delimited continuations uses polarized\nlogic: he shows that if positive and negative values are completely symmetric\nexcept that answer types are positive, then the framework accommodates\ndelimited continuations. But he interprets negative values are control\noperators, or as values defined by the shape of their continuations. We\nsimply interpret values of negative type as values flowing in the ``other''\ndirection.\n\n\\paragraph*{Int Construction.}\nFor a traced monoidal category {{C}} the Int construction produces a\nCompact Closed Category called Int {{C}} \\cite{joyal1996traced}.\nFurther we know that the target of the Int construction is isomorphic\nto the target of \\G construction of Abramsky \\cite{Abramsky96:0} from\nHaghverdi. However, note that the {{langRevEE}} is not the same as the\nimage of the Int construction on {{langRevT}}, since the the later\nlacks a multiplicative tensor that distrbutes over the additive tensor\nin Int {{langRevT}}.\n\n\\paragraph*{Recursion.} In our previous work we introduce recursive types and\ntrace operators. This is dangerous here because infinite loops allow us to\nprolong paying the debt for as long as we want.\n\n\\paragraph*{GoI machines} \nWe can now encode the GoI machine of Mackie \\cite{Mackie2011,DBLP:conf/popl/Mackie95}.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Conclusion}\n\n\\acks This project was partially funded by Indiana University's Office\nof the Vice President for Research and the Office of the Vice Provost\nfor Research through its Faculty Research Support Program.  We also\nacknowledge support from Indiana University's Institute for Advanced\nStudy.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{small}\n\\bibliographystyle{abbrvnat}\n\\bibliography{cites}\n\\end{small}\n\n\\end{document}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n", "meta": {"hexsha": "27eea1dcfa120eb0729b5de6ef2f8d6c124c5651", "size": 37776, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "rationals/dual.tex", "max_stars_repo_name": "JacquesCarette/pi-dual", "max_stars_repo_head_hexsha": "003835484facfde0b770bc2b3d781b42b76184c1", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2015-08-18T21:40:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T01:07:57.000Z", "max_issues_repo_path": "rationals/dual.tex", "max_issues_repo_name": "JacquesCarette/pi-dual", "max_issues_repo_head_hexsha": "003835484facfde0b770bc2b3d781b42b76184c1", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-06-07T16:27:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-29T20:41:23.000Z", "max_forks_repo_path": "rationals/dual.tex", "max_forks_repo_name": "JacquesCarette/pi-dual", "max_forks_repo_head_hexsha": "003835484facfde0b770bc2b3d781b42b76184c1", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-05-29T01:56:33.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-10T09:47:13.000Z", "avg_line_length": 42.0200222469, "max_line_length": 88, "alphanum_fraction": 0.7178896654, "num_tokens": 9738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.33591318545786586}}
{"text": "\\subsection{Analysis of spectral series containing more components}\n\nGenerally, the standard approach used in optical spectroscopic studies of NA\nfor analysis of a system with more components is based on a variation of some\nparameter which influences the ratio between components and observation of the\nimpact of the change on the spectra.\nFor example, the concentration of ions or pH of the buffer can be modified in\ntitration experiments, and their influence on the preferred conformation or\ncomplex formation can be observed\n\\parencite{Klener2015}.\nAlternatively, increased temperature causes a structural transition of a folded\ninto an unfolded state\n\\parencite{Klener2021}.\n\nAbsorbance at one wavelength (260\\,nm as a rule for UV absorption of NA) is\nusually used as the monitored parameter.\nTemperature-dependent measurements then model the temperature profile of the\nabsorbance by sigmoidal curve (typically derived from the Van't Hoff equation)\nwith linear asymptotes to take into account the temperature effects outside\nthe region of the temperature transition\n\\parencite{%\n\tOwczarzy1997,%\n\tOwczarzy2005,%\n\tMergny2009%\n}.\n\nChanges in RS are richer and influence the intensity and positions of numerous\nRaman bands.\nA similar approach can be applied to individual spectral parameters of Raman\nbands\n\\parencite{%\n\tDuguid1996,%\n\tMukerji1996,%\n\tMercier1999,%\n\tBaumruk2001,%\n\tMovileanu2002a,%\n\tKnee2008%\n},\nbut the results are influenced by uncertainties in the subtraction of the\nbackground signal, the effects of overlapping bands, and other experimental\nerrors.\nIt means that each individual spectral parameter gives different results making\nit difficult to obtain a general picture of the underlying process.\n\nAnother alternative is a plot of differential spectra for spectral changes\nduring subsequent parameter steps\n\\parencite{%\n\tDuguid1996,%\n\tBaumruk2001,%\n\tChan1997,%\n\tMovileanu1999,%\n\tMovileanu2002%\n}.\nThey provide an excellent overview of thermally induced changes in individual\nRaman bands but they do not determine the underlying chemical process's\nparameters nor separatef different simultaneous processes.\n\nThe advantages of both of the above methods can be provided by a multivariate\nanalysis of a series of Raman spectra.\nOne suitable multivariate analysis method is\n\\emph{Principal component analysis} (PCA,\n\\cite{%\n\tWold1987,%\n\tMalinowski2002%\n}),\nwhich reduces the measured spectra to several spectral profiles (loadings) and\nscores indicating each profile's portion in the measured spectra.\nThe scores can then be fitted by a function based on an underlying chemical\nmodel, and for example, thermodynamic parameters for structural transitions\ncan be estimated in temperature-dependent measurement\n\\parencite{Nemecek2013}.\n\nPCA converts sets of experimental spectra $Y_i(\\nu)$\ninto novel sets of mutually independent spectral profiles (loadings)\n$U_j(\\nu)$ and scores $P_{ij}$ representing their portions in the original\nspectra\n\\begin{equation*}\n\tY_i(\\nu) = \\sum_{j=1}^M P_{ij}U_j(\\nu),\n\\end{equation*}\nwhere $\\nu$ is the wavenumber, $i \\in \\{1,\\dots,N\\}$ enumerates spectra from\nthe original spectral series of size $N$ and $M$ is the estimated number of\nsignificant components.\n\nUnderlying chemical model for relationships between concentrations of the\nchemical components $c_k(t_i)$ can be fitted to the loading $P_{ij}$\n\\begin{equation*}\n\tP_{ij}^\\text{model} = \\sum_{k=1}^{M_\\text{c}} c_k(t_i) Q_{ki}(t_i)\n\\end{equation*}\nwhere $t_i$ is the parameter value for spectrum number $i$ (for example\ntemperature, concentration of ions or pH),\n$c_k(t_i)$ is concentration of chemical component $k$, which is dependent on\nthe parameter $t_i$,\n$k$ enumerates on the number of chemical components $M_\\text{c}$ and\n$Q_{ki}(t_i)$ is polynomial in parameter $t_i$\n\\begin{equation*}\n\tQ_{ki}(t_i) = \\sum_{l_k=0}^{L_k} a_{k,l_k} t_i^{l_k},\n\\end{equation*}\nwhere $l$ enumerates on the degree of polynomial $L_k$ for the chemical\ncomponent $k$.\nThe underlying chemical model $c_k(t_i)$ explains the spectral changes\ncompletely only when the polynomial $Q_{ki}(t_i)$ is of degree\n$L_k = 0$, i.e. $Q_{ki}(t_i) = a_k$.\nHigher degrees of the polynomial enhances the chemical model so that it can\nbetter fit also other processes which are not sufficiently reflected in the\nchemical model; for example,\n\\textcite{Klener2021}\napplied polynomials of the first degree to accommodate for temperature effects\non folded/unfolded components even outside of the region of temperature\ntransition between the folded and unfolded state.\n\nThe relationships between $c_k(t_i)$ concentrations of chemical components from\nthe chemical model are usually not linear in the internal parameters $b_{k,m}$\nof the model because the chemical model is usually dependent on equilibrium\nconstants $K$ in a nonlinear manner.\nMoreover, Van't Hoff equation is usually used in the case of\ntemperature-dependent measurement, which introduces exponential dependency of\nthe equilibrium constants on entropy and enthalpy.\n\nThe least-squares regression with the internal model parameters $a_{k,l_k}$ and\n$b_{k,m}$ minimizes the sum of squares\n\\begin{equation}\n\tS(a_{k,l_k},b_{k,m}) = \\sum_{i=1}^N{\\sum_{j=1}^M{\n\t\t\\left[P_{ij} - P_{ij}^\\text{model}(a_{k,l_k},b_{k,m})\\right]^2\n\t}},\n\t\\label{\\eqnlabel{two_comp:sos}}\n\\end{equation}\nwhich is, as discussed above, linear in polynomial parameters $a_{k,l_k}$ and\nnonlinear in parameters $b_{k,m}$.\nNonlinear minimization is usually much more expensive because it utilizes\niterative methods of searching for the minimum.\nThey are also susceptible to finding only local minima.\nOn the other hand, linear least squares regression is “just” solution of a set\nof normal equations\n\\parencite[p.~671]{NumericalRecipes}.\nIt means that the nonlinear iterative minimization algorithm can be applied\nto $b_{k,m}$ values, the $a_{k,l_k}$ values are estimated by linear least\nsquares for the given $c_k(t_i)$ which are determined by the values of\n$b_{k,m}$.\n", "meta": {"hexsha": "4d907b4cf1afd4f1431e4886ae954177fbfa1b35", "size": 5961, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/results_and_discussion/two_components.tex", "max_stars_repo_name": "lumik/phd_thesis", "max_stars_repo_head_hexsha": "3b29f24732d49b64c627aeb8f6585f042cd59c4e", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/results_and_discussion/two_components.tex", "max_issues_repo_name": "lumik/phd_thesis", "max_issues_repo_head_hexsha": "3b29f24732d49b64c627aeb8f6585f042cd59c4e", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2019-08-13T12:27:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-07T03:00:58.000Z", "max_forks_repo_path": "src/results_and_discussion/two_components.tex", "max_forks_repo_name": "lumik/phd_thesis", "max_forks_repo_head_hexsha": "3b29f24732d49b64c627aeb8f6585f042cd59c4e", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.8848920863, "max_line_length": 79, "alphanum_fraction": 0.7887938265, "num_tokens": 1498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.33591318545786586}}
{"text": "%!TEX root = ceres.tex\n\\chapter{Introduction}\n\\label{sec:introduction}\nCeres Solver\\footnote{For brevity, in the rest of this document we will just use the term Ceres.} is a non-linear least squares solver developed at Google. It is designed to solve small and large sparse problems accurately and efficiently~\\footnote{For a gentle but brief introduction to non-liner least squares problems, please start by reading the~\\hyperref[chapter:tutorial]{Tutorial}}. Amongst its various features is a simple but expressive API with support for automatic differentiation, robust norms, local parameterizations, automatic gradient checking, multithreading and automatic problem structure detection.\n\nThe key computational cost when solving a non-linear least squares problem is the solution of a linear least squares problem in each iteration. To this end Ceres supports a number of different linear solvers suited for different needs. This includes dense QR factorization (using \\eigen) for small scale problems, sparse Cholesky factorization (using \\cholmod) for general sparse problems and specialized Schur complement based solvers for problems that arise in multi-view geometry~\\cite{hartley-zisserman-book-2004}.\n\nCeres has been used for solving a variety of problems in computer vision and machine learning at Google with sizes that range from a tens of variables and objective functions with a few hundred terms to problems with millions of variables and objective functions with tens of millions of terms. \n\n\\section{What's in a name?}\nWhile there is some debate as to who invented of the method of Least Squares~\\cite{stigler1981gauss}. There is no debate that it was Carl Friedrich Gauss's prediction of the orbit of the newly discovered asteroid Ceres based on just 41 days of observations that brought it to the attention of the world~\\cite{tennenbaum-director}. We named our solver after Ceres to celebrate this seminal event in the history of astronomy, statistics and optimization.\n\n\\section{Contributing to Ceres Solver}\nWe welcome contributions to Ceres, whether they are new features, bug fixes or tests. If you have ideas on how you would like to contribute to Ceres, please join the Ceres mailing list (\\texttt{ceres-solver@googlegroups.com}) or if you are looking for ideas, please let us know about your interest and skills and we will be happy to make a suggestion or three.\n\nWe follow Google's C++ Style Guide~\\footnote{\\url{http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml}}.\n\n\\section{Citing Ceres Solver}\nIf you use Ceres for an academic publication, please cite this manual. e.g.,\n\\begin{verbatim}\n@manual{ceres-manual,\n\tAuthor = {Sameer Agarwal and Keir Mierle},\n\tTitle = {Ceres Solver: Tutorial \\& Reference},\n\tOrganization = {Google Inc.}\n}\n\\end{verbatim}\n\t\n\n\\section{Acknowledgements}\nA number of people have helped with the development and open sourcing of Ceres. \n\nFredrik Schaffalitzky when he was at Google started the development of Ceres, and even though much has changed since then, many of the ideas from his original design are still present in the current code.\n\nAmongst Ceres' users at Google two deserve special mention: William Rucklidge and James Roseborough. William was the first user of Ceres. He bravely took on the task of porting production code to an as-yet unproven optimization library, reporting bugs and helping fix them along the way. James is perhaps the most sophisticated user of Ceres at Google. He has reported and fixed bugs and helped evolve the API for the better.\n\nNathan Wiegand contributed the MacOS port.\n\\clearpage\n\n\\section{License}\nCeres Solver is licensed under the New BSD license, whose terms are as follows.\n\n\\begin{quotation}\n\n\\noindent\nCopyright (c) 2010, 2011, 2012, Google Inc. All rights reserved.\n\n\\noindent\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\\begin{enumerate}\n\\item Redistributions of source code must retain the above copyright notice,\n      this list of conditions and the following disclaimer.\n\\item Redistributions in binary form must reproduce the above copyright notice,\n      this list of conditions and the following disclaimer in the documentation\n      and/or other materials provided with the distribution.\n\\item Neither the name of Google Inc.,  nor the names of its contributors may\n      be used to endorse or promote products derived from this software without\n      specific prior written permission.\n\\end{enumerate}\n\n\\noindent\nThis software is provided by the copyright holders and contributors \"AS IS\" and\nany express or implied warranties, including, but not limited to, the implied\nwarranties of merchantability and fitness for a particular purpose are\ndisclaimed. In no event shall Google Inc. be liable for any direct, indirect,\nincidental, special, exemplary, or consequential damages (including, but not\nlimited to, procurement of substitute goods or services; loss of use, data, or\nprofits; or business interruption) however caused and on any theory of\nliability, whether in contract, strict liability, or tort (including negligence\nor otherwise) arising in any way out of the use of this software, even if\nadvised of the possibility of such damage.\n\\end{quotation}\n", "meta": {"hexsha": "acc1bb31d40cd12dabf1bef59ac23c24bc3cff4b", "size": 5290, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/introduction.tex", "max_stars_repo_name": "cvfish/ceres-solver", "max_stars_repo_head_hexsha": "087462a90dd1c23ac443501f3314d0fcedaea5f7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2015-11-25T13:51:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T06:26:58.000Z", "max_issues_repo_path": "docs/introduction.tex", "max_issues_repo_name": "kashif/ceres-solver", "max_issues_repo_head_hexsha": "087462a90dd1c23ac443501f3314d0fcedaea5f7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/introduction.tex", "max_forks_repo_name": "kashif/ceres-solver", "max_forks_repo_head_hexsha": "087462a90dd1c23ac443501f3314d0fcedaea5f7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2016-03-31T15:34:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T19:29:27.000Z", "avg_line_length": 72.4657534247, "max_line_length": 619, "alphanum_fraction": 0.8015122873, "num_tokens": 1152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.6187804407739559, "lm_q1q2_score": 0.3359131816414796}}
{"text": "\\def\\module{M4P33 Algebraic Geometry}\n\\def\\lecturer{Prof Kevin Buzzard}\n\\def\\term{Spring 2020}\n\\def\\cover{\n$$\n\\begin{tikzpicture}\n\\draw [thick] (-1, 11) to (-1, 10);\n\\draw [in=-90, out=-90, thick] (-1, 10) to (-3, 7);\n\\draw [in=150, out=90, thick] (-3, 7) to (-2, 7.5);\n\\draw [in=120, out=-30, thick] (-1, 7) to (0, 6);\n\\draw [in=90, out=-60, thick] (0.5, 4.5) to (0.5, 4);\n\\draw [thick] (0.5, 4) to (0.5, 3);\n\\draw [thick] (1, 12) to (1, 11);\n\\draw [in=90, out=-90, thick] (1, 11) to (3, 7);\n\\draw [in=90, out=-90, thick] (3, 7) to (-0.5, 3);\n\\draw [thick] (-0.5, 3) to (-0.5, 2);\n\\draw [dotted, thick] (0, 11.8) to (0, 6);\n\\draw [dotted, thick] (0, 4.2) to (0, 2.2);\n\\draw [dashed] (-1, 10.5) to (1, 11.5);\n\\draw [dashed] (-1, 10) to (1, 11);\n\\draw [dashed] (-1, 9.5) to (1, 10.5);\n\\draw [dashed] (-1.2, 9) to (1.2, 10);\n\\draw [dashed] (-1.4, 8.4) to (1.4, 9.6);\n\\draw [dashed] (-1.8, 7.8) to (1.9, 9.1);\n\\draw [dashed] (-2.2, 7.2) to (2.4, 8.5);\n\\draw [dashed] (-2.8, 6.6) to (2.8, 7.8);\n\\draw [dashed] (-3, 7) to (-2.3, 7);\n\\draw [dashed] (-1, 7) to (3, 7);\n\\draw [dashed] (-2.8, 7.4) to (-2.15, 7.25);\n\\draw [dashed] (-1, 7) to (2.8, 6.2);\n\\draw [dashed] (-1, 7) to (2.2, 5.6);\n\\draw [dashed] (-0.2, 6.3) to (1.3, 5);\n\\draw [dashed] (0, 6) to (0.4, 4.5);\n\\draw [dashed] (0, 6) to (-0.4, 3.5);\n\\draw [dashed] (-0.5, 3) to (0.5, 4);\n\\draw [dashed] (-0.5, 2.5) to (0.5, 3.5);\n\\draw [in=0, out=-120, very thick] (1.9, 9.1) to (0, 7.8);\n\\draw [in=90, out=-180, very thick] (0, 7.8) to (-0.5, 7);\n\\draw [in=-180, out=-90, very thick] (-0.5, 7) to (0, 6.6);\n\\draw [in=120, out=0, very thick] (0, 6.6) to (1.3, 5);\n\\fill (1.9, 9.1) circle (0.05);\n\\fill (0, 7.8) circle (0.05);\n\\fill (0, 6.6) circle (0.05);\n\\fill (1.3, 5) circle (0.05);\n\\draw [thick] (0, 0) ellipse (3 and 1);\n\\draw [dashed] (3, 0) to (-3, 0);\n\\draw [dashed] (2.7, 0.4) to (-2.7, -0.4);\n\\draw [dashed] (2, 0.7) to (-2, -0.7);\n\\draw [dashed] (1, 0.9) to (-1, -0.9);\n\\draw [dashed] (0, 1) to (0, -1);\n\\draw [dashed] (-1, 0.9) to (1, -0.9);\n\\draw [dashed] (-2, 0.7) to (2, -0.7);\n\\draw [dashed] (-2.7, 0.4) to (2.7, -0.4);\n\\draw [in=30, out=-120, very thick] (1, 0.9) to (0, 0);\n\\draw [in=-90, out=-150, very thick] (0, 0) to (-1, 0);\n\\draw [in=150, out=90, very thick] (-1, 0) to (0, 0);\n\\draw [in=120, out=-30, very thick] (0, 0) to (1, -0.9);\n\\fill (1, 0.9) circle (0.05);\n\\fill (0, 0) circle (0.1);\n\\fill (1, -0.9) circle (0.05);\n\\draw (-2, 6) node{$ \\overline{\\pi^{-1}\\br{\\CCC \\setminus \\cbr{\\br{0, 0}}}} $};\n\\draw [->, dashed, thick] (2, 4) to node[right]{$ \\pi $} (2, 2);\n\\draw (0, -2) node{$ \\CCC = \\cbr{\\br{x, y} \\in \\AA^2 \\st y^2 = x^2\\br{x + 1}} \\subseteq \\AA^2 $};\n\\end{tikzpicture}\n$$\n}\n\\def\\syllabus{Affine algebraic sets. Projective algebraic sets. Regular functions and maps. Rational functions and maps. Equivalence of algebra and geometry. The weak and strong Nullstellensatz. Rigidity and images of maps. Completeness and Chevalley's theorem. Dimension and transcendence degree. Dimension of hypersurfaces. Topological definition of dimension. Counting dimensions of parameter spaces.}\n\\def\\thm{subsection}\n\n\\input{../style/header}\n\n% Macros\n\\newcommand{\\rational}[5][]{\n  \\ifx &#1&\n    \\begin{array}{rcl}\n      #2 & \\dashrightarrow & #3 \\\\\n      #4 & \\longmapsto     & #5\n    \\end{array}\n  \\else\n    \\begin{array}{ccrcl}\n      #1 & : & #2 & \\dashrightarrow & #3 \\\\\n         &   & #4 & \\longmapsto     & #5\n    \\end{array}\n  \\fi\n}\n\\newcommand{\\birational}[7][]{\n  \\ifx &#1&\n    \\begin{array}{rcl}\n      #2 & \\dashrightarrow & #3 \\\\\n      #4 & \\longmapsto     & #5 \\\\\n      #6 & \\longmapsfrom   & #7\n    \\end{array}\n  \\else\n    \\begin{array}{ccrcl}\n      #1 & : & #2 & \\dashrightarrow & #3 \\\\\n         &   & #4 & \\longmapsto     & #5 \\\\\n         &   & #6 & \\longmapsfrom   & #7\n    \\end{array}\n  \\fi\n}\n\n\\begin{document}\n\n\\input{../style/cover}\n\n\\section{Introduction}\n\n\\subsection{B\\'ezout's theorem}\n\n\\lecture{1}{Monday}{13/01/20}\n\nHere is an example of a theorem in algebraic geometry and an outline of a geometric method for proving it which illustrates some of the main themes in algebraic geometry.\n\n\\begin{theorem}[B\\'ezout]\nLet $ C $ be a plane algebraic curve $ \\cbr{\\br{x, y} \\st f\\br{x, y} = 0} $ where $ f $ is a polynomial of degree $ m $. Let $ D $ be a plane algebraic curve $ \\cbr{\\br{x, y} \\st g\\br{x, y} = 0} $ where $ g $ is a polynomial of degree $ n $. Suppose that $ C $ and $ D $ have no component in common, since if they had a component in common, then their intersection would obviously be infinite. Then $ C \\cap D $ consists of $ mn $ points, provided that\n\\begin{itemize}\n\\item we work over the complex numbers $ \\CC $,\n\\item we work in the projective plane, which consists of the ordinary plane together with some points at infinity, and\n\\item we count intersections with the correct multiplicities, so if the curves are tangent at a point, it counts as more than one intersection.\n\\end{itemize}\n\\end{theorem}\n\nConsider the cases where $ C $ is a line of degree one and $ D $ has either degree one or two. The projective plane will be formally defined later in the course. We will not define intersection multiplicities in this course, but the idea is that multiple intersections resemble multiple roots of a polynomial in one variable.\n\n\\begin{proof}\nWe prove a special case, where $ C $ is the union of $ m $ lines, then use this to prove the general case of the theorem.\n\\begin{itemize}\n\\item First for the special case, suppose we have $ m $ lines in the plane, with equations\n$$ a_1x + b_1y + c_1 = 0, \\qquad \\dots, \\qquad a_mx + b_my + c_m = 0. $$\nWe can multiply these equations together to get\n$$ \\br{a_1x + b_1y + c_1} \\dots \\br{a_mx + b_my + c_m} = 0. $$\nThis is an equation of degree $ m $ and its solution set is the union of the lines. Each line intersects $ D $ in $ n $ points, counted with multiplicities, because we can rearrange the equation of the line into the form $ x = \\dots $ or $ y = \\dots $ then substitute into the equation for $ D $. This usually gives a polynomial of degree $ n $ in one variable, and this has $ n $ roots if we count them correctly. There are also special cases to worry about where the line intersects $ D $ at infinity. Combining all the $ m $ lines, we deduce that their union intersects $ D $ in $ mn $ points.\n\\item Now we deduce the general case from the special case. We let the curve $ C $ vary in a family of curves of degree $ m $. What exactly we mean by varying in a family will be defined later in the course. As an example, consider the family of curves\n$$ \\FFF : \\cbr{\\br{x, y} \\st x^2 - y^2 = t}, $$\nwhere $ t $ is a parameter, so for different values of $ t $ we get different curves. When the curve $ C $ varies in a family like this, the number of intersection points in $ C \\cap D $ does not change, counting with multiplicity. This is the core of the proof. It requires a lot of work to justify which we will not do here. For any degree $ m $ curve $ C $, it is possible to find a family of curves which contains both $ C $ itself and a union of $ m $ lines $ X $. For example, if $ C $ is the hyperbola defined by the equation $ x^2 - y^2 = 1 $, then it is found in the family $ \\FFF $, with $ t = 1 $. If we let $ t = 0 $ in this family, then the equation factors as $ \\br{x - y}\\br{x + y} $ and this defines the union of two lines in the plane. We have already proved that $ X \\cap D $ has $ mn $ points, and we stated that $ X \\cap D $ has the same number of points as $ C \\cap D $ because $ C $ and $ X $ are in the same family. We conclude that $ C \\cap D $ has $ mn $ points.\n\\end{itemize}\n\\end{proof}\n\n\\pagebreak\n\nThe idea that something stays the same everywhere, or almost everywhere, in a family of varying algebraic sets is a key theme in algebraic geometry. Note that this proof uses not just curves but also higher-dimensional algebraic sets, since instead of thinking about a family of curves such as $ \\FFF $, with coordinates $ \\br{x, y} $ and a parameter $ t $, we can regard $ x, y, t $ all as coordinates in three-dimensional space and consider the surface\n$$ \\cbr{\\br{x, y, t} \\st x^2 - y^2 = t}. $$\nThen we use facts about this surface as part of the proof. We will not prove B\\'ezout's theorem in this course. In particular, we will not define intersection multiplicities. But we will set up many of the tools needed to fill in the gaps in this outline proof.\n\n\\subsection{Practical information about the course}\n\nThe following are books.\n\\begin{itemize}\n\\item M Reid, Undergraduate algebraic geometry, 1988\n\\item R Hartshorne, Algebraic geometry, 1977\n\\end{itemize}\nDuring the course we will sometimes assume results from commutative algebra. Books which contain these results, and much much more, include the following.\n\\begin{itemize}\n\\item H Matsumura, Commutative ring theory, 1986\n\\item M F Atiyah and I G Macdonald, Introduction to commutative algebra, 1969\n\\item D Eisenbud, Commutative algebra: with a view toward algebraic geometry, 2011\n\\end{itemize}\nThe following is the course outline.\n\\begin{itemize}\n\\item Affine varieties.\n\\begin{itemize}\n\\item Definition and examples.\n\\item Maps between varieties.\n\\item Translating between geometry and commutative algebra and the Nullstellensatz.\n\\end{itemize}\n\\item Projective varieties.\n\\begin{itemize}\n\\item Definition and examples.\n\\item Maps between varieties.\n\\item Rigidity and images of maps.\n\\end{itemize}\n\\item Dimension.\n\\begin{itemize}\n\\item Several different definitions, all equivalent, but useful for different purposes.\n\\item Calculating dimensions of examples.\n\\end{itemize}\n\\end{itemize}\nWhat is not in the course?\n\\begin{itemize}\n\\item Schemes.\n\\item Sheaves and cohomology.\n\\item Curves, divisors, and the Riemann–Roch theorem.\n\\end{itemize}\n\n\\begin{note*}\nThe official notes are integrated in these unofficial notes.\n\\end{note*}\n\n\\pagebreak\n\n\\section{Affine varieties}\n\n\\subsection{Affine algebraic sets}\n\nLet $ k $ be an algebraically closed field. We are going to be thinking about solutions to polynomials, so everything is much simpler over algebraically closed fields. We already saw this in B\\'ezout's theorem. Number theorists might be interested in other fields, but you generally have to start by understanding the algebraically closed case first. In this course we will stop with the algebraically closed case too. Apart from being algebraically closed, it usually does not matter much which field we use to do algebraic geometry, except sometimes it matters whether the characteristic is zero or positive. In this course I will take care to mention results which depend on the characteristic, and sometimes we might consider only the characteristic zero case. You will not lose much if you just assume that $ k = \\CC $ throughout the course, except when it will be explicitly something else. Indeed it is often useful to think about $ k = \\CC $ because then you can use your usual geometric intuition. When I draw pictures on the whiteboard, I am usually only drawing the real solutions because it is hard to draw shapes in $ \\CC^2 $. This is cheating but it is often very useful. The real solutions are not the full picture but in many cases we can still see the important features there.\n\n\\subsubsection{Affine space}\n\n\\begin{definition*}\nAlgebraic geometers write $ \\AA^n $ to mean $ k^n $, and call it \\textbf{affine $ n $-space}.\n\\end{definition*}\n\nYou may think of this as just a funny choice of notation, but there are at least two reasons for it.\n\\begin{itemize}\n\\item When we write $ k^n $, it makes us think of a vector space, equipped with operations of addition and scalar multiplication. But $ \\AA^n $ means just a set of points, described by coordinates $ \\br{x_1, \\dots, x_n} $ with $ x_i \\in k $, without the vector space structure.\n\\item Because it usually does not matter much what our base field $ k $ is, as long as it is algebraically closed, it is convenient to have notation which does not prominently mention $ k $.\n\\end{itemize}\nOn occasions when it is important to specify which field $ k $ we are using, we write $ \\AA_k^n $ for affine $ n $-space.\n\n\\subsubsection{Definition and examples}\n\n\\lecture{2}{Thursday}{16/01/20}\n\n\\begin{definition*}\nAn \\textbf{affine algebraic set} is a subset $ V \\subseteq \\AA^n $ which consists of the common zeroes of some finite set of polynomials $ f_1, \\dots, f_m $ with coefficients in $ k $. More formally, an affine algebraic set is a set of the form\n$$ V = \\cbr{\\br{x_1, \\dots, x_n} \\in \\AA^n \\st f_1\\br{x_1, \\dots, x_n} = \\dots = f_m\\br{x_1, \\dots, x_n} = 0}, \\qquad f_1, \\dots, f_m \\in k\\sbr{X_1, \\dots, X_n}. $$\n\\end{definition*}\n\n\\begin{example*}\nExamples.\n\\begin{itemize}\n\\item The empty set, defined by the polynomial $ f_1 = 3 $, for example.\n\\item The whole space $ \\AA^n $, defined by the polynomial $ f_1 = 0 $, or by the empty set of polynomials.\n\\item Any finite subset $ \\cbr{a_1, \\dots, a_n} $ in $ \\AA^1 $, defined by the polynomial $ f_1 = \\br{X - a_1} \\dots \\br{X - a_n} $.\n\\item Any single-point set $ \\cbr{\\br{a_1, \\dots, a_n}} $ in $ \\AA^n $, defined by the polynomials $ f_i = X_i - a_i $. Note that this is different from the example of a finite set in $ \\AA^1 $, because that example had a single polynomial in one variable of degree $ n $, while here we have $ n $ distinct polynomials in $ n $ variables of degree one.\n\\item Any algebraic curve in $ \\AA^n $, that is, a set of the form\n$$ \\cbr{\\br{x_1, \\dots, x_n} \\in \\AA^n \\st f\\br{x_1, \\dots, x_n} = 0}, \\qquad f \\in k\\sbr{X_1, \\dots, X_n}. $$\n\\item Embeddings of $ \\AA^m $ in $ \\AA^n $ where $ m < n $,\n$$ \\cbr{\\br{x_1, \\dots, x_m, 0, \\dots, 0} \\in \\AA^n} = \\cbr{\\br{x_1, \\dots, x_n} \\in \\AA^n \\st x_{m + 1} = \\dots = x_n = 0}. $$\nMore generally, the image of a linear map $ \\AA^m \\to \\AA^n $,\n$$ \\cbr{\\br{x_1, \\dots, x_n} \\in \\AA^n \\st \\text{some linear conditions}}. $$\n\\end{itemize}\n\\end{example*}\n\n\\pagebreak\n\n\\begin{example*}\nNon-examples.\n\\begin{itemize}\n\\item Any infinite subset of $ \\AA^1 $, other than $ \\AA^1 $ itself, such as a line segment, a line with a double point, or an infinite discrete set. This is because a one-variable polynomial with infinitely many roots must be the zero polynomial. This also tells us that $ \\cbr{x \\in \\AA^1 \\st x \\ne 0} $ is not an affine algebraic set. However there is an affine algebraic set which is isomorphic to $ \\AA^1 \\setminus \\cbr{0} $, namely $ \\cbr{\\br{x, y} \\in \\AA^2 \\st xy - 1 = 0} $. By looking at just the $ x $ coordinate, this set bijects to $ \\AA^1 \\setminus \\cbr{0} $.\n\\item A sine wave. If $ \\cbr{\\br{x, y} \\st y = \\sin x} $ were an affine algebraic set, then $ \\cbr{\\br{x, y} \\st y = \\sin x, \\ y = 0} $ would also be an affine algebraic set because it is defined by imposing an extra polynomial condition, but the latter is an infinite discrete set.\n\\item The example of the image of a linear map $ \\AA^m \\to \\AA^n $ does not generalise to images of maps where each coordinate is given by a polynomial. For example, consider the map\n$$ \\function[\\phi]{\\AA^2}{\\AA^2}{\\br{x, y}}{\\br{x, xy}}. $$\nThe image of $ \\phi $ is $ S = \\AA^2 \\setminus \\cbr{\\br{0, y}} \\cup \\cbr{\\br{0, 0}} $. To prove that $ S $ is not an affine algebraic set, consider a polynomial $ g\\br{X, Y} \\in k\\sbr{X, Y} $ which vanishes on $ S $. For each fixed $ y \\in k $, the one-variable polynomial $ g\\br{X, y} $ vanishes at all $ x \\ne 0 $. This implies that $ g\\br{X, y} $ is the zero polynomial. Thus $ g\\br{x, y} = 0 $ for all $ \\br{x, y} \\in k^2 $, that is, $ g $ is the zero polynomial.\n\\end{itemize}\n\\end{example*}\n\n\\begin{remark}\nThe words affine variety mean more or less the same thing as affine algebraic set but there is an ontological difference. Affine algebraic set means a subset which lives inside $ \\AA^n $ and knows how it lives inside $ \\AA^n $, while affine variety means an object in its own right which is considered outside of $ \\AA^n $. I will try to use these words consistently, but the difference is quite subtle and books may not always use it consistently. For the first few weeks, we will talk about affine algebraic sets only. Note that some books, such as Reid and Hartshorne, have another difference between affine varieties and affine algebraic sets. They require varieties to be irreducible, which we will define next time. Other books, such as Shafarevich, do not require varieties to be irreducible. In this course we will not require varieties to be irreducible.\n\\end{remark}\n\n\\subsubsection{New algebraic sets from old}\n\nNow we prove that the union of two affine algebraic sets is an affine algebraic set. Consider two points $ \\br{a_1, \\dots, a_n} $ and $ \\br{b_1, \\dots, b_n} $ in $ \\AA^n $. The two-point set $ \\cbr{\\br{a_1, \\dots, a_n}, \\br{b_1, \\dots, b_n}} $ can be defined by taking the product for each possible pair of equations, one from each list, so $ \\br{X_i - a_i}\\br{X_j - b_j} = 0 $ for all $ i, j \\in \\cbr{1, \\dots, n} $.\n\n\\begin{note*}\nIt is necessary to consider all the pairs between the lists, not just the ones with $ i = j $, because otherwise we would be allowing points like $ \\br{a_1, \\dots, a_{n - 1}, b_n} $.\n\\end{note*}\n\n\\begin{lemma}\nIf $ V, W \\subseteq \\AA^n $ are affine algebraic sets, then their union $ V \\cup W \\subseteq \\AA^n $ is also an affine algebraic set.\n\\end{lemma}\n\n\\begin{proof}\nWe have to take the product for each possible pair of defining polynomials, since if\n$$ V = \\cbr{\\underline{x} \\in \\AA^n \\st f_1\\br{\\underline{x}} = \\dots = f_r\\br{\\underline{x}} = 0}, \\qquad W = \\cbr{\\underline{x} \\in \\AA^n \\st g_1\\br{\\underline{x}} = \\dots = g_s\\br{\\underline{x}} = 0}, $$\nthen\n$$ V \\cup W = \\cbr{\\underline{x} \\in \\AA^n \\st \\forall 1 \\le i \\le r, \\ \\forall 1 \\le j \\le s, \\ f_i\\br{\\underline{x}}g_j\\br{\\underline{x}} = 0}. $$\nLet us check that these equations really do define $ V \\cup W $. First, suppose that $ \\underline{x} \\in V \\cup W $. Then either $ \\underline{x} \\in V $, so $ f_i\\br{\\underline{x}} = 0 $ for every $ i $, so we can multiply by $ g_j\\br{\\underline{x}} $ to get $ f_i\\br{\\underline{x}}g_j\\br{\\underline{x}} = 0 $ for every $ i $ and $ j $, or $ \\underline{x} \\in W $, in which case the same argument works with $ g_j $ in place of $ f_i $. The reverse direction is a little trickier. Suppose that we have $ \\underline{x} \\in \\AA^n $ satisfying $ f_i\\br{\\underline{x}}g_j\\br{\\underline{x}} = 0 $ for all $ i $ and $ j $. Looking just at $ f_1 $, we get\n$$ f_1\\br{\\underline{x}}g_1\\br{\\underline{x}} = 0 \\implies f_1\\br{\\underline{x}} = 0 \\ \\text{or} \\ g_1\\br{\\underline{x}} = 0, \\qquad \\dots, \\qquad f_1\\br{\\underline{x}}g_s\\br{\\underline{x}} = 0 \\implies f_1\\br{\\underline{x}} = 0 \\ \\text{or} \\ g_s\\br{\\underline{x}} = 0. $$\nPutting these all together, we get $ f_1\\br{\\underline{x}} = 0 $ or $ g_j\\br{\\underline{x}} = 0 $ for every $ j $. We can do the same thing for $ f_2 $ to get $ f_2\\br{\\underline{x}} = 0 $ or $ g_j\\br{\\underline{x}} = 0 $ for every $ j $, and so on for each $ f_i $. Putting all these together, we get $ f_i\\br{\\underline{x}} = 0 $ for every $ i $ or $ g_j\\br{\\underline{x}} = 0 $ for every $ j $. This says precisely that $ \\underline{x} \\in V \\cup W $.\n\\end{proof}\n\n\\pagebreak\n\nIt is even easier to check that the intersection of finitely many affine algebraic sets is an affine algebraic set.\n\n\\begin{lemma}\nIf $ V, W \\subseteq \\AA^n $ are affine algebraic sets, then their intersection $ V \\cap W \\subseteq \\AA^n $ is also an affine algebraic set.\n\\end{lemma}\n\n\\begin{proof}\nJust combine the lists of defining equations. That is, say\n$$ V = \\cbr{\\underline{x} \\in \\AA^m \\st f_1\\br{\\underline{x}} = \\dots = f_r\\br{\\underline{x}} = 0}, \\qquad W = \\cbr{\\underline{y} \\in \\AA^n \\st g_1\\br{\\underline{y}} = \\dots = g_s\\br{\\underline{y}} = 0}. $$\nThen $ V \\cap W $ is simply the set where all the polynomials in both lists vanish, that is\n$$ V \\cap W = \\cbr{\\underline{x} \\in \\AA^n \\st f_1\\br{\\underline{x}} = \\dots = f_r\\br{\\underline{x}} = g_1\\br{\\underline{x}} = \\dots = g_s\\br{\\underline{x}} = 0}. $$\n\\end{proof}\n\nJust a remark on one other way of constructing new affine algebraic sets from existing ones.\n\n\\begin{lemma}\nIf $ V \\subseteq \\AA^m $ and $ W \\subseteq \\AA^n $ are affine algebraic sets, then their Cartesian product $ V \\times W \\subseteq \\AA^{m + n} $ is an affine algebraic set.\n\\end{lemma}\n\n\\begin{proof}\nWrite\n$$ V = \\cbr{\\underline{x} \\in \\AA^m \\st f_1\\br{\\underline{x}} = \\dots = f_r\\br{\\underline{x}} = 0}, \\qquad W = \\cbr{\\underline{y} \\in \\AA^n \\st g_1\\br{\\underline{y}} = \\dots = g_s\\br{\\underline{y}} = 0}. $$\nThen\n$$ V \\times W = \\cbr{\\br{\\underline{x}, \\underline{y}} \\in \\AA^{m + n} \\st f_1\\br{\\underline{x}} = \\dots = f_r\\br{\\underline{x}} = g_1\\br{\\underline{y}} = \\dots = g_s\\br{\\underline{y}} = 0}. $$\n\\end{proof}\n\nThis looks a bit like the equations defining $ V \\cap W $, but here the $ f_i $ involve different variables from the $ g_j $, while for $ V \\cap W $ both used the same variables.\n\n\\subsubsection{Ideals and algebraic sets}\n\n\\lecture{3}{Friday}{17/01/20}\n\nThe union of infinitely many affine algebraic sets is not always an affine algebraic set. I do not mean that it is never an affine algebraic set, just that there exist counter-examples. Indeed, any subset of $ \\AA^n $ can be written as a union of single-point sets. The intersection of infinitely many affine algebraic sets always an affine algebraic set. If we try to prove this by combining the lists of defining equations, we run into a problem, since in our definition of affine algebraic sets we only allowed a finite list of polynomial equations. We introduce ideals to remove this restriction.\n\n\\begin{definition*}\nRecall from commutative algebra that, if $ R $ is a ring, an \\textbf{ideal} is a subset $ I \\subseteq R $ with the properties that\n\\begin{itemize}\n\\item if $ f, g \\in I $, then $ f + g \\in I $, and\n\\item if $ f \\in I $ and $ q \\in R $, then $ qf \\in I $.\n\\end{itemize}\nGiven any subset $ S \\subseteq R $, we define the \\textbf{ideal generated by $ S $} to be the smallest ideal which contains $ S $, and denote it by $ \\abr{S} $. In particular, if $ S $ is the finite set $ \\cbr{f_1, \\dots, f_m} $ then it generates the ideal\n$$ \\abr{f_1, \\dots, f_m} = \\cbr{q_1f_1 + \\dots + q_mf_m \\st q_1, \\dots, q_m \\in R}. $$\n\\end{definition*}\n\nLet us introduce some notation.\n\n\\begin{definition*}\nFor any set $ S \\subseteq k\\sbr{X_1, \\dots, X_n} $, let\n$$ \\VV\\br{S} = \\cbr{\\underline{x} \\in \\AA^n \\st \\forall f \\in S, \\ f\\br{\\underline{x}} = 0}. $$\n\\end{definition*}\n\n\\begin{lemma}\n\\label{lem:vs}\nIf $ S \\subseteq k\\sbr{X_1, \\dots, X_n} $ generates the ideal $ I $, then $ \\VV\\br{S} = \\VV\\br{I} $.\n\\end{lemma}\n\n\\begin{proof}\nWe have $ S \\subseteq I $ and so it is easy to see that $ \\VV\\br{I} \\subseteq \\VV\\br{S} $. Suppose that $ \\underline{x} \\in \\VV\\br{S} $, and $ f \\in \\VV\\br{I} $. Then there are $ f_1, \\dots, f_m \\in S $ and $ q_1, \\dots, q_m \\in k\\sbr{X_1, \\dots, X_n} $ such that $ f = q_1f_1 + \\dots + q_mf_m $. Since $ f_1\\br{\\underline{x}} = \\dots = f_m\\br{\\underline{x}} = 0 $, it follows that $ f\\br{\\underline{x}} = 0 $. Since this holds for every $ f \\in I $, $ \\underline{x} \\in \\VV\\br{I} $.\n\\end{proof}\n\n\\pagebreak\n\n\\begin{theorem}[Hilbert basis theorem]\nFrom commutative algebra, if $ k $ is any field, then the polynomial ring $ k\\sbr{X_1, \\dots, X_n} $ is noetherian. That means that the following two equivalent conditions hold.\n\\begin{itemize}\n\\item Let $ I $ be an ideal in $ k\\sbr{X_1, \\dots, X_n} $. Then there exists a finite set $ \\cbr{f_1, \\dots, f_m} \\subseteq k\\sbr{X_1, \\dots, X_n} $ which generates $ I $.\n\\item Let $ I_1 \\subseteq I_2 \\subseteq \\dots $ be an ascending chain of ideals in $ k\\sbr{X_1, \\dots, X_n} $. Then there is some $ N $ such that $ I_n = I_N $ for every $ n > N $.\n\\end{itemize}\n\\end{theorem}\n\nUsing the Hilbert basis theorem, we can deduce that the restriction to finite lists of polynomials in the definition of affine algebraic sets is unnecessary.\n\n\\begin{corollary}\n\\label{cor:vs}\n$ \\VV\\br{S} $ is an affine algebraic set for any set of polynomials $ S \\subseteq k\\sbr{X_1, \\dots, X_n} $.\n\\end{corollary}\n\n\\begin{proof}\nLet $ I $ be the ideal in $ k\\sbr{X_1, \\dots, X_n} $ generated by $ S $. By the Hilbert basis theorem, $ k\\sbr{X_1, \\dots, X_n} $ is noetherian and so we can choose a finite set $ \\cbr{f_1, \\dots, f_m} $ which generates $ I $. Then Lemma \\ref{lem:vs} tells us that $ \\VV\\br{S} = \\VV\\br{I} = \\VV\\br{f_1, \\dots, f_m} $.\n\\end{proof}\n\n\\begin{corollary}\nThe intersection of finitely many affine algebraic sets is an affine algebraic set.\n\\end{corollary}\n\n\\begin{proof}\nCombine the lists of defining polynomials for all the algebraic sets, and apply Corollary \\ref{cor:vs}.\n\\end{proof}\n\nWe can also go in the other direction, from affine algebraic sets to ideals. Say $ V_n = \\VV\\br{I_n} $. Does $ V_1 \\supseteq V_2 $ imply that $ I_1 \\subseteq I_2 $? No. The problem is that there is more than one ideal defining the same algebraic set.\n\n\\begin{example*}\nLet $ I_1 = \\abr{X} $ and $ I_2 = \\abr{X^2} $ in $ k\\sbr{X} $. We have $ \\VV\\br{I_1} = \\cbr{0} = \\VV\\br{I_2} $.\n\\end{example*}\n\nHowever, there is a natural choice we can make for one ideal canonically associated with an affine algebraic set, the set of all polynomials which vanish on that set.\n\n\\begin{definition*}\nFormally, if $ A $ is any subset of $ \\AA^n $, usually $ A $ will be an affine algebraic set, we define\n$$ \\II\\br{A} = \\cbr{f \\in k\\sbr{X_1, \\dots, X_n} \\st \\forall \\underline{x} \\in A, \\ f\\br{\\underline{x}} = 0}. $$\n\\end{definition*}\n\n\\begin{note*}\n$ \\II\\br{A} $ is an ideal in $ k\\sbr{X_1, \\dots, X_n} $.\n\\end{note*}\n\nWe have now defined two functions\n$$ \\VV : \\cbr{\\text{ideals in} \\ k\\sbr{X_1, \\dots, X_n}} \\to \\cbr{\\text{affine algebraic sets in} \\ \\AA^n}, $$\n$$ \\II : \\cbr{\\text{affine algebraic sets in} \\ \\AA^n} \\to \\cbr{\\text{ideals in} \\ k\\sbr{X_1, \\dots, X_n}}. $$\nThese functions are not inverses of each other, since the example of $ \\abr{X} $ and $ \\abr{X^2} $ shows that $ \\II\\br{\\VV\\br{\\abr{X^2}}} = \\abr{X} \\ne \\abr{X^2} $. But composing $ \\VV $ and $ \\II $ in the other order gives the identity.\n\n\\begin{lemma}\n\\label{lem:viv}\nIf $ V $ is an affine algebraic set, then $ \\VV\\br{\\II\\br{V}} = V $.\n\\end{lemma}\n\n\\begin{proof}\nIt is clear that $ V \\subseteq \\VV\\br{\\II\\br{V}} $, and this works when $ V $ is any subset of $ \\AA^n $, not necessarily algebraic. For the reverse inclusion, we have to use the hypothesis that $ V $ is an affine algebraic set. By the definition of affine algebraic sets, $ V = \\VV\\br{J} $ for some ideal $ J \\subseteq k\\sbr{X_1, \\dots, X_n} $. Suppose that $ \\underline{y} \\notin V $. We shall show that $ \\underline{y} \\notin \\VV\\br{\\II\\br{V}} $. Because $ \\underline{y} \\notin V = \\VV\\br{J} $, there exists $ f \\in J $ such that $ f\\br{\\underline{y}} \\ne 0 $. By definition, $ J \\subseteq \\II\\br{V} $ and so $ f \\in \\II\\br{V} $. Hence $ f\\br{\\underline{y}} \\ne 0 $ tells us that $ \\underline{y} \\notin \\VV\\br{\\II\\br{V}} $.\n\\end{proof}\n\nWhat is the geometric interpretation of the Hilbert basis theorem?\n\n\\begin{note*}\nIt is clear that $ \\VV $ and $ \\II $ reverse the direction of inclusions, since if $ I_1 \\subseteq I_2 $, then $ \\VV\\br{I_2} \\subseteq \\VV\\br{I_1} $.\n\\end{note*}\n\nHence the ascending chain condition for ideals translates into the descending chain condition for affine algebraic sets. The following statement is the translation into affine algebraic sets of the Hilbert basis theorem.\n\n\\begin{lemma}\n\\label{lem:descendingchain}\nLet $ V_1 \\supseteq V_2 \\supseteq \\dots $ be a descending chain of affine algebraic sets in $ \\AA^n $. Then there exists $ N $ such that $ V_n = V_N $ for all $ n > N $.\n\\end{lemma}\n\n\\begin{proof}\nThe fact that $ V_1 \\supseteq V_2 \\supseteq \\dots $ implies that $ \\II\\br{V_1} \\subseteq \\II\\br{V_2} \\subseteq \\dots $. Because $ k\\sbr{X_1, \\dots, X_n} $ is noetherian, there exists $ N $ such that $ \\II\\br{V_n} = \\II\\br{V_N} $ for all $ n > N $. By Lemma \\ref{lem:viv}, $ V_n = \\VV\\br{\\II\\br{V_n}} $ for every $ n $ and so this proves Lemma \\ref{lem:descendingchain}.\n\\end{proof}\n\n\\pagebreak\n\n\\subsubsection{Statement of the Nullstellensatz}\n\nWhen does $ \\II\\br{\\VV\\br{I}} = I $? It turns out that the only reason that this can fail is where elements of the ideal $ I $ have $ n $-th roots which are not in $ I $, just as with the example of $ I = \\abr{X^2} $ where $ X^2 \\in I $ has a square root $ X $ which is not in $ I $. To state this precisely, we need to recall the definition of the radical of an ideal from commutative algebra.\n\n\\begin{definition*}\nLet $ I $ be an ideal in a ring $ R $. The \\textbf{radical} of $ I $ is\n$$ \\rad I = \\sqrt{I} = \\cbr{f \\in R \\st \\exists n > 0, \\ f^n \\in I}. $$\nWe say that $ I $ is a \\textbf{radical ideal} if $ \\rad I = I $.\n\\end{definition*}\n\n\\begin{note*}\nIf $ I $ is any ideal, then $ \\rad I $ is always a radical ideal.\n\\end{note*}\n\n\\begin{theorem}[Hilbert's Nullstellensatz]\n\\label{thm:strongnullstellensatz}\nLet $ I $ be any ideal in the polynomial ring $ k\\sbr{X_1, \\dots, X_n} $ over an algebraically closed field $ k $. Then we have\n$$ \\II\\br{\\VV\\br{I}} = \\rad I. $$\n\\end{theorem}\n\nThis is a substantial theorem, fundamental to algebraic geometry. We will prove it in a few lectures' time, not because we need to develop more theory, just because I would like to introduce some more concepts first which will allow us to do more with examples.\n\n\\begin{note*}\nTo calculate $ \\rad I $, we need to add in $ n $-th roots of all elements of $ I $, not just the generators.\n\\end{note*}\n\n\\begin{example*}\nIf $ I = \\abr{X, Y^2 - X} \\subseteq k\\sbr{X, Y} $, then we can rewrite this as $ I = \\abr{X, Y^2} $ and so $ \\rad I = \\abr{X, Y} \\ne I $, even though neither of the original generators of $ I $ had any non-trivial $ n $-th roots.\n\\end{example*}\n\n\\subsubsection{Basic facts about the Zariski topology}\n\nWe have seen that affine algebraic sets in $ \\AA^n $ satisfy the following conditions.\n\\begin{itemize}\n\\item $ \\AA^n $ and $ \\emptyset $ are affine algebraic sets, since the empty set is the vanishing set of a non-zero constant polynomial.\n\\item A finite union of affine algebraic sets is an affine algebraic set.\n\\item An arbitrary intersection of affine algebraic sets is an affine algebraic set.\n\\end{itemize}\nThe are precisely the conditions satisfied by the closed sets in a topological space. Therefore, we can define a topological space in which the underlying set is $ \\AA^n $ and closed sets are the affine algebraic sets. This is called the \\textbf{Zariski topology}. This is a very different topology from the ones you are used to in analysis. In particular, it is a very long way from being Hausdorff. For any affine algebraic set $ V \\subseteq \\AA^n $, we define the \\textbf{Zariski topology} on $ V $ to be the subspace topology on $ V $ induced by the Zariski topology on $ \\AA^n $. Thus, a subset of $ V $ is Zariski closed in $ V $ if and only if it is Zariski closed in $ \\AA^n $. Thus for closed sets it does not matter whether we say Zariski closed in $ V $ or Zariski closed in $ \\AA^n $.\n\n\\lecture{4}{Monday}{20/01/20}\n\n\\begin{example*}\nThe Zariski topology on $ \\AA^1 $ is the same as the cofinite topology. Prove that the Zariski topology on $ \\AA^1 $ is not Hausdorff. \\footnote{Exercise}\n\\end{example*}\n\nThus we see that the Zariski topology has much fewer closed sets, or much fewer open sets, than for example the Euclidean topology.\n\n\\begin{lemma}\nSuppose that $ k = \\CC $, so there is a Euclidean topology on $ \\AA_\\CC^n $. If $ V $ is a Zariski closed subset of $ \\AA_\\CC^n $, then $ V $ is closed in the Euclidean topology, so the Euclidean topology is finer than the Zariski topology.\n\\end{lemma}\n\n\\begin{proof}\nLet $ f \\in \\CC\\sbr{X_1, \\dots, X_n} $ be a polynomial. It is a continuous function $ \\AA_\\CC^n \\to \\CC $ for the Euclidean topology. Since $ \\cbr{0} $ is a closed subset of $ \\CC $, $ \\VV\\br{f} = f^{-1}\\br{0} $ is a closed subset of $ \\AA_\\CC^n $ in the Euclidean topology. We conclude by noting that intersections of closed sets are closed.\n\\end{proof}\n\n\\pagebreak\n\nOn the other hand, for open sets Zariski open in $ V $ does not mean the same thing as Zariski open in $ \\AA^n $. A Zariski open subset of $ V $ need not be Zariski open in $ \\AA^n $.\n\n\\begin{example*}\nLet $ V $ be the $ x $-axis in $ \\AA^2 $. Then $ V \\setminus \\cbr{0} $ is open in $ V $, but not open in $ \\AA^2 $.\n\\end{example*}\n\nThe open subsets of the Zariski topology are all very big. This is made precise, for $ \\AA^1 $, by the following lemma.\n\n\\begin{lemma}\nProve that every pair $ U_1 $ and $ U_2 $ of non-empty open sets in $ \\AA^1 $ has a non-empty intersection $ U_1 \\cap U_2 $.\n\\end{lemma}\n\nHence the Zariski topology on $ \\AA^1 $ is not Hausdorff. A subset of $ \\AA^1 $ is dense in the Zariski topology if and only if it is infinite. At the moment, the Zariski topology is likely to seem very strange. It might also seem like, what is the point of such a strange topology? We will not use it in a very deep way, it is just a convenient language to be able to talk about open and closed sets. It does get used more seriously in the theory of schemes.\n\n\\subsubsection{Connected and irreducible sets}\n\nRecall the definition of a connected topological space.\n\n\\begin{definition*}\nA topological space $ S $ is \\textbf{connected} if it is not possible to write it as the union of two disjoint non-empty open sets. This is equivalent to, it is not possible to write $ S $ as the union of two disjoint non-empty closed sets.\n\\end{definition*}\n\nIt is possible to talk about connectedness in the Zariski topology.\n\n\\begin{example*}\nA finite set of points of size greater than one is not connected in the Zariski topology, since every subset is closed.\n\\end{example*}\n\nConsider the following affine algebraic sets in $ \\AA^2 $. Do they have one or two pieces? Do they have one or two pieces? I have deliberately not specified what I mean by pieces. There are multiple sensible interpretations, so there is not always a unique correct answer.\n\\begin{itemize}\n\\item The union of two disjoint lines $ \\VV\\br{X\\br{X - 1}} $.\n\\item The union of two intersecting lines $ \\VV\\br{XY} $.\n\\item The hyperbola $ \\VV\\br{XY - 1} $.\n\\end{itemize}\n\n\\begin{example*}\nThe union of two disjoint lines $ \\VV\\br{X\\br{X - 1}} $ is not connected, since it unambiguously has two pieces, the two lines $ \\VV\\br{X} $ and $ \\VV\\br{X - 1} $, and each line is a non-empty closed subset.\n\\end{example*}\n\nBut there is a more refined notion for the Zariski topology.\n\n\\begin{example*}\nThe set $ \\VV\\br{XY} $ has more than one answer. The two axes form two pieces. It is a union of two lines, intersecting at the origin, joining them into one piece. Describe the Zariski closed subsets. \\footnote{Exercise}\n\\end{example*}\n\nThe following notion gives us a way of formally understanding the example described.\n\n\\begin{definition*}\nA topological space $ S $ is \\textbf{reducible} if it is empty, or there exist closed sets $ S_1, S_2 \\subseteq S $ such that $ S = S_1 \\cup S_2 $, and neither $ S_1 $ nor $ S_2 $ is equal to $ S $. A topological space $ S $ is \\textbf{irreducible} if it is non-empty and it is not possible to write it as the union $ S_1 \\cup S_2 $ of two closed sets, unless at least one of $ S_1 $ and $ S_2 $ is equal to $ S $ itself. Compared to the second definition of connected, we no longer require $ S_1 $ and $ S_2 $ to be disjoint.\n\\end{definition*}\n\nThis is not a very useful notion for the topological spaces we consider in analysis.\n\n\\begin{example*}\nConsidering the real line with the Euclidean topology, we can write it as a union of proper closed subsets,\n$$ \\RR = \\cbr{x \\in \\RR \\st x \\le 0} \\cup \\cbr{x \\in \\RR \\st x \\ge 0}. $$\nThese subsets are not disjoint because they intersect at zero. Of course, there are many other ways to write $ \\RR $ as a union of proper closed subsets in the usual topology. The same is true for any other Hausdorff space.\n\\end{example*}\n\n\\pagebreak\n\n\\begin{example*}\nThe drawing of $ \\VV\\br{XY - 1} $ in $ \\RR^2 $ is misleading, since it looks like it has two pieces, but, as mentioned before, we are missing a lot by only looking at real solutions. For algebraic geometry, we need to look at complex solutions, and then over $ \\CC $ it unambiguously has one piece. One way to visualise this is to note that, if we project down to the $ x $ coordinate, $ \\VV\\br{XY - 1} $ looks like the set $ \\AA^1 \\setminus \\cbr{0} $. This is not a formal statement. We have not yet defined a notion of isomorphism of affine algebraic sets, and even if we had, $ \\AA^1 \\setminus \\cbr{0} $ is not an affine algebraic set. In a few weeks we will develop technology to make this into a rigorous statement. But for now we use it as a heuristic. Then $ \\RR \\setminus \\cbr{0} $ unambiguously has two pieces, but $ \\CC \\setminus \\cbr{0} $ is connected in the usual analytic topology on $ \\CC $ and unambiguously has one piece. So the hyperbola, over an algebraically closed field, should have only one piece.\n\\end{example*}\n\nWe prove below in the lecture that $ \\VV\\br{XY - 1} $ is irreducible, and also connected.\n\n\\begin{lemma}\nThe hyperbola $ H = \\VV\\br{XY - 1} $ is irreducible.\n\\end{lemma}\n\n\\begin{proof}\nWe need to describe the Zariski closed subsets of $ H $. So let $ V \\subseteq H $ be a proper Zariski closed subset. Since $ V \\ne H $ there must be some polynomial $ f \\in k\\sbr{X, Y} $ which vanishes on $ V $ but does not vanish on all of $ H $. Because $ V \\subseteq H $ and $ y = 1 / x $ on $ H $, we have $ f\\br{x, y} = f\\br{x, 1 / x} $ when $ \\br{x, y} \\in V $. Now $ f\\br{X, 1 / X} $ is almost a polynomial in the single variable $ X $, except that it may contain negative powers of $ X $, so\n$$ f\\br{X, \\dfrac{1}{X}} = \\sum_{n \\in \\ZZ} a_nX^n. $$\nWe can multiply up by $ X^m $ where $ -m $ is the lowest exponent of $ X $ which appears in this expression. Then $ X^mf\\br{X, 1 / X} $ is a polynomial in $ X $, which vanishes on $ V $. Furthermore $ f\\br{X, 1 / X} $ is not identically zero because $ f $ does not vanish identically on $ H $. Hence $ X^mf\\br{X, 1 / X} $ is a non-zero single-variable polynomial, therefore it has only finitely many roots. The roots of $ X^mf\\br{X, 1 / X} = 0 $ are the possible $ x $ coordinates for points in $ V $. For each value of $ x $, there is at most one possible $ y $ such that $ \\br{x, y} \\in V $ because $ y = 1 / x $ on $ V $. Therefore $ V $ is finite. Thus we have shown that all proper Zariski closed subsets of $ H $ are finite. In particular, if $ V_1 $ and $ V_2 $ are two proper Zariski closed subsets of $ H $, they are both finite and so their union is finite. Hence $ V_1 \\cup V_2 \\ne H $ so $ H $ is irreducible.\n\\end{proof}\n\nThus the Zariski topology on $ H $ is the cofinite topology. Here is a bonus fact about connected sets in the Zariski topology which I did not mention in the lecture. The proof is surprisingly hard.\n\n\\begin{theorem}\nOver $ \\CC $, an affine algebraic set is connected in the Zariski topology if and only if it is connected in the Euclidean topology.\n\\end{theorem}\n\n\\subsubsection{Prime ideals and irreducible sets}\n\nIf $ V $ is an affine algebraic set, what condition on the ideal $ \\II\\br{V} $ is equivalent to $ V $ being irreducible?\n\n\\lecture{5}{Thursday}{23/01/20}\n\n\\begin{definition*}\nFrom commutative algebra, an ideal $ I $ in a ring $ R $ is a \\textbf{prime ideal} if $ I \\ne R $ and for every $ f, g \\in R $, if $ fg \\in I $, then $ f \\in I $ or $ g \\in I $, or both.\n\\end{definition*}\n\n\\begin{lemma}\n\\label{lem:irreducibleprime}\nAn affine algebraic set $ V \\subseteq \\AA^n $ is irreducible if and only if $ \\II\\br{V} $ is a prime ideal in $ k\\sbr{X_1, \\dots, X_n} $.\n\\end{lemma}\n\n\\begin{proof}\nFirst suppose that $ V $ is irreducible. Suppose we have $ f, g \\in k\\sbr{X_1, \\dots, X_n} $ such that $ fg \\in \\II\\br{V} $. Let\n$$ V_1 = \\cbr{\\underline{x} \\in V \\st f\\br{\\underline{x}} = 0}, \\qquad V_2 = \\cbr{\\underline{x} \\in V \\st g\\br{\\underline{x}} = 0}. $$\nFor every $ \\underline{x} \\in V $, $ f\\br{\\underline{x}}g\\br{\\underline{x}} = 0 $ and hence either $ f\\br{\\underline{x}} = 0 $ or $ g\\br{\\underline{x}} = 0 $. Thus for every $ \\underline{x} \\in V $, either $ \\underline{x} \\in V_1 $ or $ \\underline{x} \\in V_2 $. In other words, $ V = V_1 \\cup V_2 $. Furthermore $ V_1 $ and $ V_2 $ are closed subsets of $ V $. Hence as $ V $ is irreducible, either $ V_1 = V $ or $ V_2 = V $. If $ V_1 = V $ then $ f \\in \\II\\br{V} $ and if $ V_2 = V $ then $ g \\in \\II\\br{V} $. Now suppose that $ V $ is reducible. Then we can write it as a union $ V_1 \\cup V_2 $ of proper closed subsets. Since $ V_1 $ is a proper closed subset of $ V $, there exists some $ f \\in k\\sbr{X_1, \\dots, X_n} $ vanishing on $ V_1 $ but not on all of $ V $. Similarly there exists $ g $ vanishing on $ V_2 $ but not on all of $ V $. Thus neither $ f $ nor $ g $ is in $ \\II\\br{V} $, but the product $ fg $ vanishes on $ V_1 \\cup V_2 $ and hence we have $ fg \\in \\II\\br{V} $. Thus $ \\II\\br{V} $ is not prime. Then $ V $ is empty if and only if $ \\II\\br{V} = k\\sbr{X_1, \\dots, X_n} $, which is explicitly defined to not be a prime ideal. So it was ok to ignore this case above.\n\\end{proof}\n\n\\pagebreak\n\n\\begin{definition*}\nA \\textbf{hypersurface} is an affine algebraic set in $ \\AA^n $ defined by one polynomial equation, that is,\n$$ \\cbr{\\underline{x} \\in \\AA^n \\st f\\br{\\underline{x}} = 0}, \\qquad f \\in k\\sbr{X_1, \\dots, X_n}. $$\n\\end{definition*}\n\nIt follows from Lemma \\ref{lem:irreducibleprime} together with Hilbert's Nullstellensatz that a hypersurface defined by a polynomial $ f $ is irreducible if and only if $ f $ is a power of an irreducible polynomial. See problem sheet $ 1 $.\n\n\\begin{example*}\nWe can use this to prove that the circle $ \\cbr{\\br{x, y} \\st x^2 + y^2 = 1} $ is irreducible, by proving that the polynomial $ X^2 + Y^2 - 1 $ is irreducible. This is because, if $ f = X^2 + Y^2 - 1 = f_1f_2 $ then we can scale $ f_1 $ and $ f_2 $ by constants to get\n$$ f_1 = X + g_1\\br{Y}, \\qquad f_2 = X + g_2\\br{Y}, $$\nsince $ f $ has degree two in $ X $ and its $ X^2 $ term has coefficient one. Since $ f $ has no $ X $ term, we must have $ g_1 + g_2 = 0 $. But then\n$$ f_1f_2 = \\br{X + g_1\\br{Y}}\\br{X - g_1\\br{Y}} = X^2 - g_1\\br{Y}^2, $$\nso $ g_1\\br{Y}^2 = -Y^2 + 1 $, and $ -Y^2 + 1 $ is not a square. On the other hand, the hypersurface $ \\cbr{\\br{x, y} \\st x^2 + y^2 = 0} $ is reducible, because $ X^2 + Y^2 $ factors as $ \\br{X - iY}\\br{X + iY} $.\n\\end{example*}\n\nIt can often be convenient to rewrite the definition of irreducible spaces in terms of open sets instead of closed sets.\n\n\\begin{lemma}\n\\label{lem:irreducibleopen}\nThe following conditions on a topological space $ S $ are equivalent to irreducibility.\n\\begin{itemize}\n\\item $ S $ is non-empty, and every pair of non-empty open subsets $ U_1, U_2 \\subseteq S $ have non-empty intersection $ U_1 \\cap U_2 $.\n\\item $ S $ is non-empty, and every non-empty open subset of $ S $ is dense in $ S $.\n\\end{itemize}\n\\end{lemma}\n\n\\begin{proof}\nJust manipulation of the topological definition.\n\\end{proof}\n\n\\begin{corollary}\n\\label{cor:irreducibleopen}\nLet $ S $ be a irreducible topological space and $ U \\subseteq S $ a non-empty open subset. Then $ U $ is irreducible, in the subspace topology.\n\\end{corollary}\n\nLemma \\ref{lem:irreducibleopen} says that irreducible is a very long way from Hausdorff. The Hausdorff condition says that a space has lots of pairs of disjoint non-empty open subsets, while an irreducible space has none.\n\n\\begin{example*}\nWe saw that $ \\RR $, with the Euclidean topology, is reducible in many ways.\n\\end{example*}\n\nCorollary \\ref{cor:irreducibleopen} implies that $ \\AA^1 \\setminus \\cbr{0} $ is irreducible, in the subspace topology induced by the Zariski topology on $ \\AA^1 $, because it is open in $ \\AA^1 $. Compare this to the fact that the hyperbola $ H $ is irreducible. This lends support to the heuristic argument that the hyperbola $ H $ is irreducible, but it is not a proof. Checking that the subspace topology on $ \\AA^1 \\setminus \\cbr{0} $ is the same as the Zariski topology on $ H $ would require exactly the same work as the proof that $ H $ is irreducible to prove that the Zariski topology on $ H \\subseteq \\AA^2 $.\n\n\\subsubsection{Irreducible components}\n\nJust like the definition of connected components, we can define the following.\n\n\\begin{definition*}\nLet $ S $ be a topological space. An \\textbf{irreducible component} of $ S $ is a maximal irreducible subset of $ S $.\n\\end{definition*}\n\nUnlike connected components, irreducible components need not be disjoint.\n\n\\begin{example*}\nThe irreducible components of $ \\cbr{\\br{x, y} \\st xy = 0} $ are the lines $ x = 0 $ and $ y = 0 $, which intersect in $ \\cbr{\\br{0, 0}} $.\n\\end{example*}\n\nMore generally, the irreducible components of a hypersurface $ \\VV\\br{f} $ correspond to the irreducible factors of $ f $, since if $ f = f_1^{a_1} \\dots f_m^{a_m} $, where the $ f_i $ are distinct irreducible polynomials, then the irreducible components of $ \\VV\\br{f} $ are $ \\VV\\br{f_1}, \\dots, \\VV\\br{f_m} $. Irreducible components have the following key properties.\n\n\\pagebreak\n\n\\begin{proposition}\n\\label{prop:irreduciblecomponent}\nLet $ V $ be an affine algebraic set. Then\n\\begin{enumerate}\n\\item the union of the irreducible components of $ V $ is all of $ V $, and\n\\item $ V $ has only finitely many irreducible components.\n\\end{enumerate}\n\\end{proposition}\n\nProposition \\ref{prop:irreduciblecomponent}.$ 1 $ matches a property of connected components. Proposition \\ref{prop:irreduciblecomponent}.$ 2 $ does not apply to the connected components of an arbitrary topological space.\n\n\\begin{example*}\n$ \\ZZ $ or $ \\QQ $ with the subspace topology from $ \\RR $.\n\\end{example*}\n\n\\begin{note*}\nProposition \\ref{prop:irreduciblecomponent}.$ 2 $ does imply that an affine algebraic set has only finitely many connected components for the Zariski topology, because each connected component must be a union of irreducible components.\n\\end{note*}\n\nProposition \\ref{prop:irreduciblecomponent}.$ 2 $ is a finiteness statement, so it is not surprising that it follows from the noetherian property, the descending chain condition on closed subsets. The key idea in the proof is as follows. If an affine algebraic set is reducible, then we can write it as a union of proper closed subsets. If these subsets are reducible, then we can write them in turn as unions of proper closed subsets. The following lemma says that this process eventually stops, since after finitely many steps, we reach irreducible sets.\n\n\\begin{lemma}\n\\label{lem:irreducibleclosed}\nEvery affine algebraic set can be written as a union of finitely many irreducible closed subsets.\n\\end{lemma}\n\n\\begin{proof}\nSuppose that $ V $ is an affine algebraic set which cannot be written as a union of finitely many irreducible closed subsets. Then $ V $ must be reducible, otherwise we could write it as a union of one irreducible closed subset. So $ V = V_1 \\cup W_1 $, with $ V_1 $ and $ W_1 $ proper closed subsets of $ V $. Then $ V_1 $ and $ W_1 $ cannot both be unions of finitely many irreducible closed subsets, because taking the union of those decompositions would give us $ V $ as a union of finitely many irreducible closed subsets. Thus at least one of $ V_1 $ and $ W_1 $ does not satisfy Lemma \\ref{lem:irreducibleclosed}. Without loss of generality, we may suppose that $ V_1 $ does not satisfy Lemma \\ref{lem:irreducibleclosed}. Then $ V_1 $ must be reducible, so we can write $ V_1 = V_2 \\cup W_2 $. We can repeat the argument, since at least one of $ V_2 $ and $ W_2 $ does not satisfy Lemma \\ref{lem:irreducibleclosed}, without loss of generality $ V_2 $, etc. Thus we build up a chain of closed subsets $ V \\supset V_1 \\supset V_2 \\supset \\dots $ where all these sets do not satisfy Lemma \\ref{lem:irreducibleclosed}, and all the inclusions are strict. This contradicts Lemma \\ref{lem:descendingchain}, the descending chain condition for affine algebraic sets.\n\\end{proof}\n\nIn order to prove Proposition \\ref{prop:irreduciblecomponent}, we want to show that the finitely many irreducible closed subsets in Lemma \\ref{lem:irreducibleclosed} are the irreducible components. There is just one wrinkle. Consider $ V = \\VV\\br{XY} $. The irreducible components are $ \\VV\\br{X} $ and $ \\VV\\br{Y} $. But we could write $ V $ as a union of finitely many irreducible closed subsets by saying, $ V = \\VV\\br{X} \\cup \\VV\\br{Y} \\cup \\cbr{\\br{0, 2}} $. Thus we can always add in extra sets to a decomposition as in Lemma \\ref{lem:irreducibleclosed}, where the extra sets are contained in one of the other sets in the decomposition. Of course we can always just throw away these empty sets from the list without changing the union. Let $ V = V_1 \\cup \\dots \\cup V_r $, as in Lemma \\ref{lem:irreducibleclosed}. By throwing away any $ V_i $ which is contained in another $ V_j $, we can assume that $ V_i \\not\\subseteq V_j $ whenever $ i \\ne j $, and still the union of the $ V_j $'s will be $ V $. Subject to this non-redundancy condition, there is only one way to write $ V $ as a finite union of irreducible closed subsets and we can prove the following.\n\n\\begin{proposition}\n\\label{prop:irreducibleclosed}\nLet $ V $ be an affine algebraic set. Write $ V = V_1 \\cup \\dots \\cup V_r $, where the $ V_i $ are irreducible closed subsets and $ V_i \\not\\subseteq V_j $ for $ i \\ne j $. Then $ V_1, \\dots, V_r $ are precisely the irreducible components of $ V $.\n\\end{proposition}\n\n\\begin{proof}\nFirst we show that each $ V_i $ is an irreducible component. By hypothesis, $ V_i $ is irreducible. So if $ V_i $ is not an irreducible component, it is not a maximal irreducible set and must be contained in a larger irreducible set $ W \\subseteq V $. But then\n$$ W = \\br{V_1 \\cap W} \\cup \\dots \\cup \\br{V_r \\cap W}, $$\nwhere $ V_1 \\cap W, \\dots, V_r \\cap W $ are closed subsets of $ W $. Because $ W $ is irreducible, we must have $ W = V_j \\cap W $ for some $ j $. Thus $ V_i \\subseteq W \\subseteq V_j $. By the condition $ V_i \\not\\subseteq V_j $ for any $ j \\ne i $, we must have $ i = j $ and $ W = V_i $. Thus $ V_i $ is an irreducible component of $ V $. Conversely, let $ C $ be an irreducible component of $ V $. Then\n$$ C = \\br{V_1 \\cap C} \\cup \\dots \\cup \\br{V_r \\cap C}. $$\nBy the same argument as before, the irreducibility of $ C $ implies that $ C \\subseteq V_i $ for some $ i $. Then the maximality of $ C $ implies that $ C = V_i $.\n\\end{proof}\n\nThe combination of Lemma \\ref{lem:irreducibleclosed} and Proposition \\ref{prop:irreducibleclosed} proves both of Proposition \\ref{prop:irreduciblecomponent}.\n\n\\pagebreak\n\n\\subsubsection{Primary decomposition of ideals}\n\nThe irreducible component decomposition of an affine algebraic set can give a geometric understanding of the primary decomposition of ideals in the noetherian ring $ k\\sbr{X_1, \\dots, X_n} $. However, the irreducible decomposition gives only partial information about the primary decomposition of an ideal, because ideals contain more information than affine algebraic sets. Recall that the algebraic set depends only on the radical of the ideal.\n\n\\begin{example*}\nLet $ I = \\abr{X^2, XY} \\subseteq k\\sbr{X, Y} $. Then $ \\VV\\br{I} $ is simply the line $ X = 0 $, which of course is irreducible. However a primary decomposition of $ I $ is\n$$ I = \\abr{X} \\cap \\abr{X^2, XY, Y^2}. $$\nHere $ \\abr{X} $ is the ideal of the line $ X = 0 $, the unique irreducible component of $ V = \\VV\\br{I} $. The ideal $ \\abr{X^2, XY, Y^2} $ defines the point $ \\cbr{\\br{0, 0}} $, which is contained in $ V $ so is not an irreducible component.\n\\end{example*}\n\nThus the minimal associated primes of the primary decomposition of $ I $ corespond to the irreducible components of $ \\VV\\br{I} $, while non-minimal associated primes correspond to additional smaller sets strictly contained in the irreducible components, called \\textbf{embedded components}. In scheme theory, we can think of $ \\VV\\br{I} $ as containing multiple copies of these embedded components.\n\n\\begin{example*}\nThe ideal $ I = \\abr{X^2, XY} $ corresponds, in the world of schemes, to the line $ X = 0 $ with two copies of the origin.\n\\end{example*}\n\n\\subsection{Regular and rational maps}\n\n\\subsubsection{Regular functions}\n\n\\lecture{6}{Friday}{24/01/20}\n\nSo far we have only considered algebraic sets as sets, sitting individually. Now we look at functions between them. Just as one uses continuous functions for topological spaces, holomorphic functions for complex manifolds, homomorphisms for groups, etc, so algebraic geometry has its own type of functions, regular functions. Of course, these are given by polynomials.\n\n\\begin{definition*}\nLet $ V \\subseteq \\AA^n $ be an affine algebraic set. A \\textbf{regular function} on $ V $ is a function $ f : V \\to k $ such that there exists a polynomial $ F \\in k\\sbr{X_1, \\dots, X_n} $ with $ f\\br{\\underline{x}} = F\\br{\\underline{x}} $ for all $ \\underline{x} \\in V $.\n\\end{definition*}\n\n\\begin{note*}\nThe polynomial $ F $ is not uniquely determined by the function $ f $, since $ F, G \\in k\\sbr{X_1, \\dots, X_n} $ determine the same regular function on $ V $ if and only if $ F - G $ vanishes on $ V $, that is if and only if $ F - G \\in \\II\\br{V} $.\n\\end{note*}\n\n\\begin{definition*}\nThe regular functions on $ V $ form a $ k $-algebra, since they can be added and multiplied by each other, and multiplied by scalars in $ k $. This is called the \\textbf{coordinate ring} of $ V $ and denoted $ k\\sbr{V} $.\n\\end{definition*}\n\nThere is a ring homomorphism $ k\\sbr{X_1, \\dots, X_n} \\to k\\sbr{V} $ which sends a polynomial $ F $ to the function $ \\eval{F}_V $ which it defines on $ V $. This homomorphism is surjective and its kernel is $ \\II\\br{V} $, so\n$$ k\\sbr{V} \\cong k\\sbr{X_1, \\dots, X_n} / \\II\\br{V}. $$\n\n\\begin{example*}\nWhat are the coordinate rings of the following affine algebraic sets?\n\\begin{itemize}\n\\item The coordinate ring of $ \\AA^n $ is $ k\\sbr{X_1, \\dots, X_n} $.\n\\item The coordinate ring of a point is $ k $. A regular function on a point is just a single value.\n\\item The coordinate ring of two points $ \\cbr{x \\in \\AA^1 \\st x\\br{x - 1} = 0} $ is $ k \\times k $. A regular function on two points is determined by two scalars, namely its value on each of the two points. For any pair of values $ \\br{a, b} \\in k \\times k $, one can easily write down a polynomial $ f \\in k\\sbr{X} $ such that $ f\\br{1} = a $ and $ f\\br{0} = b $. Alternatively, one can check algebraically that the map\n$$ \\function{k \\times k}{k\\sbr{X} / \\abr{X\\br{X - 1}}}{\\br{a, b}}{\\br{a - 1}X + b \\mod \\abr{X\\br{X - 1}}} $$\nis a $ k $-algebra isomorphism. This example generalises, since if $ V $ is a disconnected affine algebraic set, we can write $ V $ as a union $ V_1 \\cup V_2 $ of disjoint Zariski closed subsets, and then $ k\\sbr{V} = k\\sbr{V_1} \\times k\\sbr{V_2} $. On the other hand, if $ V $ is reducible but connected, so that the sets $ V_1 $ and $ V_2 $ are not disjoint, then $ k\\sbr{V} $ is a proper subset of $ k\\sbr{V_1} \\times k\\sbr{V_2} $.\n\n\\pagebreak\n\n\\item The coordinate ring of two intersecting lines $ \\cbr{\\br{x, y} \\in \\AA^2 \\st xy = 0} $ is\n$$ \\cbr{\\br{f, g} \\in k\\sbr{X} \\times k\\sbr{Y} \\st f\\br{0} = g\\br{0}}. $$\nTo prove this, one can also interpret this as\n$$ k\\sbr{X, Y} / \\abr{XY} \\cong \\cbr{a_0 + \\sum_{r = 1}^m b_rX^r + \\sum_{s = 1}^n c_sY^s \\st a_0, b_1, \\dots, b_m, c_1, \\dots, c_n \\in k, \\ m, n \\in \\NN}. $$\nWe can compare these two descriptions by observing that\n$$ k\\sbr{X} = \\cbr{a_0 + \\sum_{r = 1}^m b_rX^r}, \\qquad k\\sbr{Y} = \\cbr{a_0 + \\sum_{s = 1}^n c_sY^s}, $$\nand the condition that $ f\\br{0} = g\\br{0} $ is equivalent to insisting that these two polynomials have the same constant coefficient $ a_0 $. This does not generalise to arbitrary reducible algebraic sets. We may have $ V = V_1 \\cup V_2 $ where $ V_1 $ and $ V_2 $ are closed subsets, but\n$$ k\\sbr{V} \\ne \\cbr{\\br{f, g} \\in k\\sbr{V_1} \\times k\\sbr{V_2} \\st \\eval{f}_{V_1 \\cap V_2} = \\eval{g}_{V_1 \\cap V_2}}. $$\nThere will be an example of this on problem sheet $ 2 $.\n\\item The coordinate ring of a hyperbola $ \\cbr{\\br{x, y} \\in \\AA^2 \\st xy - 1 = 0} $ is the quotient ring $ k\\sbr{X, Y} / \\abr{XY - 1} $. To describe this more explicitly, note that any term of a two-variable polynomial is\n$$ a_{r, s}X^rY^s \\equiv\n\\begin{cases}\na_{r, s}X^{r - s} & r \\ge s \\\\\na_{r, s}Y^{s - r} & s > r\n\\end{cases}\n\\mod \\abr{XY - 1}.\n$$\nThus every coset in $ k\\sbr{X, Y} / \\abr{XY - 1} $ has a representative of the form\n$$ \\sum_{i = 0}^m a_iX^i + \\sum_{j = 1}^n a_jY^j. $$\nThe polynomials of this form determine different functions on $ V $, so we have written down exactly one representative of each coset. Furthermore, since $ XY = 1 $ in $ k\\sbr{V} $, we may relabel $ Y $ as $ X^{-1} $. Then the multiplication rule will be what the notation leads us to expect. So we can write\n$$ k\\sbr{V} = k\\sbr{X, X^{-1}} = \\cbr{\\sum_{j = -n}^m a_jX^m \\st a_{-n}, \\dots, a_m \\in k, \\ m, n \\in \\NN}. $$\n\\end{itemize}\n\\end{example*}\n\n\\begin{lemma}\nAn affine algebraic set $ V $ is irreducible if and only if $ k\\sbr{V} $ is an integral domain.\n\\end{lemma}\n\n\\begin{proof}\n$ V $ is irreducible if and only if $ \\II\\br{V} $ is a prime ideal in $ k\\sbr{X_1, \\dots, X_n} $.\n\\end{proof}\n\n\\subsubsection{Regular maps}\n\nA regular function goes from an algebraic set $ V $ to the field $ k $. We can also define regular maps, which go from one algebraic set $ V $ to another algebraic set $ W $.\n\n\\begin{definition*}\nLet $ V \\subseteq \\AA^m $ and $ W \\subseteq \\AA^n $ be affine algebraic sets. A \\textbf{regular map} $ \\phi : V \\to W $ is a function $ V \\to W $ such that there exist polynomials $ F_1, \\dots, F_n \\in k\\sbr{X_1, \\dots, X_n} $ such that $ \\phi\\br{\\underline{x}} = \\br{F_1\\br{\\underline{x}}, \\dots, F_n\\br{\\underline{x}}} $ for all $ \\underline{x} \\in V $. Regular maps are often called \\textbf{morphisms}.\n\\end{definition*}\n\n\\begin{note*}\nIn order to check that a given list of polynomials $ F_1, \\dots, F_n $ defines a regular map $ V \\to W $, it is necessary to check that $ \\br{F_1\\br{\\underline{x}}, \\dots, F_n\\br{\\underline{x}}} \\in W $ for every $ \\underline{x} \\in V $. Equivalently, we need to check that the regular functions $ \\eval{F_1}_V, \\dots, \\eval{F_n}_V \\in k\\sbr{V} $ satisfy the equations $ g\\br{\\eval{F_1}_V, \\dots, \\eval{F_n}_V} = 0 $ in the coordinate ring $ k\\sbr{V} $, for each polynomial $ g \\in \\II\\br{W} $.\n\\end{note*}\n\n\\pagebreak\n\n\\begin{example*}\n\\hfill\n\\begin{itemize}\n\\item Let $ V \\subseteq \\AA^m $ be an affine algebraic set. For any $ n < m $, the projection defined by\n$$ \\function[\\pi]{V}{\\AA^n}{\\br{x_1, \\dots, x_m}}{\\br{x_1, \\dots, x_n}} $$\nis a regular map.\n\\item A regular function on $ V $ is the same thing as a regular map $ V \\to \\AA^1 $.\n\\item Let $ C = \\cbr{\\br{x, y} \\st y^2 = x^3} $. Then\n$$ \\function{\\AA^1}{C}{t}{\\br{t^2, t^3}} $$\nis a regular map.\n\\item Consider $ \\SL_n $, the set of $ n \\times n $ matrices with determinant one. This is an affine algebraic set in $ \\AA^{n^2} $ because the determinant is a polynomial in the entries of a matrix. The map\n$$ \\function{\\SL_n}{\\SL_n}{a}{a^{-1}} $$\nis a regular map, since Cramer's rule tells us how to write each entry of $ a^{-1} $ as a polynomial in the entries of $ a $ divided by $ \\det a $, and because we are only considering $ a \\in \\SL_n $ we can drop the division.\n\\end{itemize}\n\\end{example*}\n\nA regular map $ \\phi : V \\to W $ is a continuous function with respect to the Zariski topology. This is because, if $ A \\subseteq W $ is a Zariski closed subset defined by polynomials $ f_1, \\dots, f_r $, then $ \\phi^{-1}\\br{A} $ is the zero set\n$$ \\phi^{-1}\\br{A} = \\cbr{x \\in V \\st \\br{f_1 \\circ \\phi}\\br{x} = 0, \\ \\dots, \\ \\br{f_r \\circ \\phi}\\br{x} = 0}, $$\nand therefore $ \\phi^{-1}\\br{A} $ is a Zariski closed subset of $ V $. In complex analysis, holomorphic is a much stricter condition than continuous in the Euclidean topology, and similarly regular is much stricter than continuous in the Zariski topology. The following fact is very useful.\n\n\\begin{lemma}\n\\label{lem:affinedense}\nLet $ \\phi, \\psi : V \\to W $ be regular maps. If there exists a Zariski dense subset $ A \\subseteq V $ such that $ \\eval{\\phi}_A = \\eval{\\psi}_A $, then $ \\phi = \\psi $ on all of $ V $.\n\\end{lemma}\n\n\\begin{note*}\nIf $ X $ and $ Y $ are Hausdorff topological spaces, then any continuous maps $ X \\to Y $ which agree on a dense set must agree everywhere. However Lemma \\ref{lem:affinedense} does not follow immediately from the fact that regular maps are continuous, because the Zariski topology is not Hausdorff, and is definitely false if we try to generalise it to all continuous maps with respect to the Zariski topology. Thus in order to prove Lemma \\ref{lem:affinedense}, we have to use something special about regular maps as opposed to general continuous maps.\n\\end{note*}\n\n\\begin{proof}\nWrite $ \\phi = \\br{F_1, \\dots, F_m} $ and $ \\psi = \\br{G_1, \\dots, G_m} $, where $ F_1, \\dots, F_m, G_1, \\dots, G_m $ are polynomials. Then $ F_i - G_i $ is also a polynomial for each $ i $, and so\n$$ V' = \\cbr{\\underline{x} \\in V \\st \\phi\\br{\\underline{x}} = \\psi\\br{\\underline{x}}} = \\cbr{\\underline{x} \\in V \\st \\forall i, \\ \\br{F_i - G_i}\\br{\\underline{x}} = 0} $$\nis a Zariski closed subset of $ V $. But we know that $ V' $ contains $ A $, which is Zariski dense in $ V $. Hence $ V' = V $.\n\\end{proof}\n\n\\subsubsection{Isomorphisms}\n\n\\lecture{7}{Monday}{27/01/20}\n\n\\begin{definition*}\nA regular map $ \\phi : V \\to W $ is an \\textbf{isomorphism} if there exists a regular map $ \\psi : W \\to V $ such that $ \\psi \\circ \\phi = \\id_V $ and $ \\phi \\circ \\psi = \\id_W $.\n\\end{definition*}\n\n\\begin{example*}\nIf $ V $ is the parabola $ \\cbr{\\br{x, y} \\st y - x^2 = 0} $, then the regular map given by\n$$ \\function[\\phi]{V}{\\AA^1}{\\br{x, y}}{x} $$\nis an isomorphism because it has an inverse given by\n$$ \\function[\\psi]{\\AA^1}{V}{x}{\\br{x, x^2}}. $$\n\\end{example*}\n\n\\pagebreak\n\n\\begin{example*}\nOn the other hand, if $ H $ is the hyperbola $ \\cbr{\\br{x, y} \\st xy = 1} $, then the projection\n$$ \\function{H}{\\AA^1}{\\br{x, y}}{x} $$\nis not an isomorphism because it is not surjective so it cannot possibly have an inverse. This is not enough to prove that $ H $ is not isomorphic to $ \\AA^1 $, because maybe there is some other regular map $ H \\to \\AA^1 $ which is an isomorphism. We will soon prove that $ H $ is not isomorphic to $ \\AA^1 $.\n\\end{example*}\n\n\\begin{example*}\nConsider the affine algebraic set $ W = \\cbr{\\br{x, y} \\st y^2 - x^3 = 0} $. The regular map given by\n$$ \\function[\\phi]{\\AA^1}{W}{t}{\\br{t^2, t^3}} $$\nis a bijection but it is not an isomorphism. Note that we should expect $ W $ not to be isomorphic to $ \\AA^1 $ because it has a singularity at the origin. To prove that $ \\phi : \\AA^1 \\to W $ is not an isomorphism, consider a regular map $ \\psi : W \\to \\AA^1 $. It must be given by a polynomial $ g\\br{X, Y} \\in k\\sbr{X, Y} $ and so $ \\br{\\psi \\circ \\phi}\\br{t} = \\psi\\br{t^2, t^3} $ is a polynomial in $ t $ which can have a constant term and terms of degree two or greater, but no term of degree one. Hence we cannot find $ \\psi $ such that $ \\br{\\psi \\circ \\phi}\\br{t} = t $.\n\\end{example*}\n\n\\subsubsection{Regular maps and \\texorpdfstring{$ k $}{k}-algebra homomorphisms}\n\nSuppose we have a regular map $ \\phi : V \\to W $ between affine algebraic sets. For each regular function $ g $ on $ W $, we get a regular function $ \\phi^*g $ on $ V $ defined by\n$$ \\function[\\phi^*]{k\\sbr{W}}{k\\sbr{V}}{g}{g \\circ \\phi}. $$\nWe call $ \\phi^*g \\in k\\sbr{V} $ the \\textbf{pull-back} of $ g \\in k\\sbr{W} $. Thus $ \\phi $ induces a $ k $-algebra homomorphism $ \\phi^* : k\\sbr{W} \\to k\\sbr{V} $.\n\n\\begin{note*}\n$ \\phi^* $ goes in the opposite direction to $ \\phi $.\n\\end{note*}\n\nIf we have two regular maps $ \\phi : V \\to W $ and $ \\psi : W \\to Z $, then we can compose them to get $ \\psi \\circ \\phi : V \\to Z $. One can easily check that the associated pull-back maps on coordinate rings satisfy\n$$ \\br{\\psi \\circ \\phi}^* = \\phi^* \\circ \\psi^* : k\\sbr{Z} \\to k\\sbr{V}. $$\nFor those who know category theory, we say that $ V \\mapsto k\\sbr{V} $ is a contravariant functor\n$$ \\cbr{\\text{affine algebraic sets}} \\to \\cbr{\\text{$ k $-algebras}}. $$\nIn particular, this tells us that if $ \\phi : V \\to W $ is an isomorphism with inverse $ \\psi : W \\to V $, then $ \\psi^* \\circ \\phi^* = \\id $ and $ \\phi^* \\circ \\psi^* = \\id $. Thus if $ V $ and $ W $ are isomorphic affine algebraic sets, then their coordinate rings $ k\\sbr{V} $ and $ k\\sbr{W} $ are isomorphic as $ k $-algebras.\n\n\\begin{example*}\nNow we can prove that the hyperbola $ H $ is not isomorphic to $ \\AA^1 $, because $ k\\sbr{H} = k\\sbr{X, X^{-1}} $ is not isomorphic to $ k\\sbr{\\AA^1} = k\\sbr{X} $. To verify that these $ k $-algebras are not isomorphic, observe that in $ k\\sbr{X} $ the only invertible elements are the scalars, while $ k\\sbr{X, X^{-1}} $ contains non-scalar invertible elements, such as $ X $.\n\\end{example*}\n\n\\begin{example*}\nWe can similarly prove that $ \\AA^1 $ is not isomorphic to the singular cubic $ W = \\cbr{\\br{x, y} \\st y^2 = x^3} $. We saw earlier that $ k\\sbr{W} $ is the ring of polynomials in one variable with no term of degree one, that is\n$$ k\\sbr{W} = \\cbr{a_0 + \\sum_{r = 2}^m a_rX^r \\st a_0, a_2, \\dots, a_m \\in k}. $$\nTo prove that $ k\\sbr{W} $ is not isomorphic to $ k\\sbr{\\AA^1} = k\\sbr{X} $, observe that $ k\\sbr{X} $ is a unique factorisation domain but $ k\\sbr{W} $ is not because $ \\abr{X^2}^3 = \\abr{X^3}^2 $, and $ X^2 $ and $ X^3 $ are both irreducible in $ k\\sbr{W} $.\n\\end{example*}\n\n\\pagebreak\n\n\\subsubsection{Rational functions}\n\nInformally, rational functions are functions on varieties defined by polynomial fractions, for example the function $ x \\mapsto 1 / x $ on $ \\AA^1 $. Observe that this is not really a function $ \\AA^1 \\to \\AA^1 $ because it is not defined at $ x = 0 $, but it is a genuine function on the Zariski open subset $ \\AA^1 \\setminus \\cbr{0} $. These are analogues of meromorphic functions in complex analysis. Just as with regular functions and regular maps, we first define rational functions, which take values in $ k $, then rational maps, which go into any algebraic set. We make this definition only for irreducible affine algebraic sets because, as we saw in the example of $ 1 / x $, a rational function defines a genuine function on a Zariski open subset of $ V $, and irreducibility guarantees that all open subsets of $ V $ are dense in $ V $, so that a function defined on an open subset really is defined almost everywhere on $ V $.\n\n\\begin{definition*}\nLet $ V $ be an irreducible affine algebraic set. The \\textbf{function field} of $ V $ is the field of fractions of the coordinate ring $ k\\sbr{V} $. We denote this by $ k\\br{V} $.\n\\end{definition*}\n\n\\begin{note*}\n$ k\\sbr{V} $ is an integral domain because $ V $ is irreducible, and therefore $ k\\sbr{V} $ has a field of fractions.\n\\end{note*}\n\n\\begin{example*}\nThe function field of $ \\AA^1 $ is $ k\\br{X} $, the fraction field of the polynomial ring $ k\\sbr{X} $.\n\\end{example*}\n\n\\begin{definition*}\nA \\textbf{rational function} on $ V $ is an element of the function field $ k\\br{V} $. Thus a rational function can be written in the form $ f / g $, where $ f $ and $ g $ are regular functions. There may be many different choices for $ f $ and $ g $ which define the same rational function $ f / g $.\n\\end{definition*}\n\n\\begin{definition*}\nWe say that a rational function $ \\phi \\in k\\br{V} $ is \\textbf{regular} at a point $ x \\in V $ if there exist regular functions $ f, g \\in k\\sbr{V} $ such that $ \\phi = f / g $ and $ g\\br{x} \\ne 0 $.\n\\end{definition*}\n\nThus regular points are precisely the points at which we can assign a value to $ \\phi\\br{x} $, since if $ g\\br{x} \\ne 0 $, then we can define $ \\phi\\br{x} = f\\br{x} / g\\br{x} $.\n\n\\begin{note*}\nWe are allowed to choose different fractions $ f / g $ representing $ \\phi $ at different points $ x \\in V $, in order to show that those points are regular. The value $ \\phi\\br{x} $ is independent of which fraction representing $ \\phi $ we choose, as long as it has $ g\\br{x} \\ne 0 $.\n\\end{note*}\n\n\\begin{example*}\nConsider the algebraic set defined by the equation $ XY = ZT $ in $ \\AA^4 $. Let $ \\phi = X / Z \\in k\\br{V} $. The defining equation implies that we also have $ \\phi = T / Y $. Looking at the fraction $ X / Z $ shows us that $ \\phi $ is regular wherever $ Z \\ne 0 $, and looking at the fraction $ T / Y $ shows us that $ \\phi $ is regular wherever $ Y \\ne 0 $. On the other hand, $ \\phi $ is not regular on the closed subset $ Y = Z = 0 $. One can verify that there is no other fraction representing $ \\phi $ which is non-zero on this closed subset.\n\\end{example*}\n\n\\lecture{8}{Thursday}{30/01/20}\n\nLet $ V $ be an irreducible affine algebraic set. Let $ \\phi \\in k\\br{V} $ be a rational function.\n\n\\begin{definition*}\nThe set of points where $ \\phi $ is regular is called the \\textbf{domain of definition} of $ \\phi $, and denoted $ \\dom \\phi $.\n\\end{definition*}\n\nThis is the set of points where it makes sense to assign a value to $ \\phi\\br{x} $. For $ x \\in \\dom \\phi $, the value $ \\phi\\br{x} $ is independent of which fraction $ f / g $ we choose to represent $ \\phi $, as long as $ g\\br{x} \\ne 0 $.\n\n\\begin{lemma}\n\\label{lem:domaindefinition}\nThe domain of definition of a rational function $ \\phi \\in k\\br{V} $ is a non-empty Zariski open subset of $ V $.\n\\end{lemma}\n\n\\begin{proof}\nConsider the set of all possible fractions $ f / g $ with $ f, g \\in k\\sbr{V} $ representing $ \\phi \\in k\\br{V} $. The set of points at which $ \\phi $ is not regular is the intersection of the Zariski closed sets $ \\cbr{x \\in V \\st g\\br{x} = 0} $ across all these fractions. Hence the set of points at which $ \\phi $ is not regular is a Zariski closed subset of $ V $. The domain of definition is the complement of this set, and therefore is Zariski open. To show that the domain of definition is non-empty, pick a single fraction $ f / g $ representing $ \\phi \\in k\\br{V} $. The regular function $ g $ is not equal to zero as an element of $ k\\sbr{V} $, by the definition of the field of fractions, so $ \\cbr{x \\in V \\st g\\br{x} = 0} $ is a proper closed subset of $ V $. The domain of definition contains the complement of this set, namely $ \\cbr{x \\in V \\st g\\br{x} \\ne 0} $, and hence is non-empty.\n\\end{proof}\n\n\\begin{note*}\nEvery regular function $ f \\in k\\sbr{V} $ is also a rational function $ f / 1 \\in k\\br{V} $, and its domain of definition is all of $ V $.\n\\end{note*}\n\n\\pagebreak\n\nThe converse also holds.\n\n\\begin{lemma}\n\\label{lem:rationalregular}\nLet $ \\phi \\in k\\br{V} $ be a rational function whose domain of definition is equal to $ V $. Then $ \\phi $ is a regular function on $ V $.\n\\end{lemma}\n\n\\begin{proof}\nSince $ \\dom \\phi = V $, for each point $ x \\in V $, we can choose regular functions $ f_x, g_x \\in k\\sbr{V} $ such that $ \\phi = f_x / g_x $ and $ g_x\\br{x} \\ne 0 $. Let $ I \\subseteq k\\sbr{V} $ denote the ideal generated by the functions $ g_x $. Because $ k\\sbr{V} $ is noetherian, we can pick finitely many of these functions $ g_{x_1}, \\dots, g_{x_m} $ which still generate $ I $. For each $ x \\in V $, there is some $ g_x \\in I $ which is non-zero at $ x $. Hence the Zariski closed subset of $ V $ defined by $ \\cbr{x \\in V \\st \\forall h \\in I, \\ h\\br{x} = 0} $ is empty. Then the Nullstellensatz implies that $ I $ is all of $ k\\sbr{V} $. In particular, $ 1 \\in I $. Since $ I = \\abr{g_{x_1}, \\dots, g_{x_m}} $, there exist $ u_1, \\dots, u_m \\in k\\sbr{V} $ such that $ 1 = u_1g_{x_1} + \\dots + u_mg_{x_m} $ in $ k\\sbr{V} $. We can now calculate\n$$ \\phi = \\br{u_1g_{x_1} + \\dots + u_mg_{x_m}}\\phi = u_1g_{x_1}\\dfrac{f_{x_1}}{g_{x_1}} + \\dots + u_mg_{x_m}\\dfrac{f_{x_m}}{g_{x_m}} = u_1f_{x_1} + \\dots + u_mf_{x_m}. $$\nSince $ u_i, f_{x_i} \\in k\\sbr{V} $, so is $ \\phi $. Note that it might appear that we have only proved the above equation $ \\phi = u_1f_{x_1} + \\dots + u_mf_{x_m} $ on a Zariski open subset of $ V $, namely the intersections of the domains of definition of $ f_{x_1} / g_{x_1}, \\dots, f_{x_m} / g_{x_m} $. Because $ V $ is irreducible, this open subset must be dense, but the subset where an equation of polynomials holds is closed, so it is equal to all of $ V $.\n\\end{proof}\n\n\\subsubsection{Rational maps}\n\nLet $ V \\subseteq \\AA^m $ and $ W \\subseteq \\AA^n $ be irreducible affine algebraic sets.\n\n\\begin{definition*}\nA \\textbf{rational map} $ \\phi : V \\dashrightarrow W $ is an $ n $-tuple of rational functions $ \\phi_1, \\dots, \\phi_n \\in k\\br{V} $ such that, for every point $ x \\in V $ where $ \\phi_1, \\dots, \\phi_n $ are all regular, the point $ \\br{\\phi_1\\br{x}, \\dots, \\phi_n\\br{x}} $ is in $ W $.\n\\end{definition*}\n\nWe use the broken arrow symbol instead of the usual arrow because a rational map is not a function on $ V $ in the usual set-theoretic sense. It only defines a genuine function $ U \\to W $, where $ U $ is the domain of definition of $ \\phi $. This is defined as follows.\n\n\\begin{definition*}\nThe \\textbf{domain of definition} of a rational map $ \\phi : V \\dashrightarrow W $ is the intersection of the domains of definition of the component rational functions $ \\br{\\phi_1, \\dots, \\phi_n} $.\n\\end{definition*}\n\nThe two lemmas we proved for rational functions also hold for rational maps, since the domain of definition of a rational map $ \\phi : V \\dashrightarrow W $ is a non-empty Zariski open subset of $ V $, and if a rational map is regular everywhere then it is a regular map. In order to prove that the domain of definition of a rational map is non-empty, we have to use the fact that $ V $ is irreducible, and therefore every open subset of $ V $ is dense.\n\n\\begin{example*}\nAn important example of a rational map is the projection from a point onto a hyperplane. Let $ H $ be a hyperplane in $ \\AA^n $, that is a set defined by a single linear equation. Let $ p $ be a point in $ \\AA^n \\setminus H $. For simplicity, we shall assume that $ p $ is the origin and that\n$$ H = \\cbr{\\br{x_1, \\dots, x_n} \\in \\AA^n \\st x_n = 1}, $$\nsince we could always reduce to this case by a suitable change of coordinates. Let us write $ H_p $ for the hyperplane through $ p $ parallel to $ H $, that is\n$$ H_p = \\cbr{\\br{x_1, \\dots, x_n} \\in \\AA^n \\st x_n = 0}. $$\nFor each point $ x \\in \\AA^n \\setminus H_p $, let $ L_x $ denote the line which passes through $ p $ and $ x $. Since $ x \\notin H_p $, $ L_x $ intersects $ H $ in exactly one point. Call this point $ \\phi\\br{x} $. We can write this algebraically as\n$$ \\rational[\\phi]{\\AA^n}{H}{\\br{x_1, \\dots, x_n}}{\\br{\\dfrac{x_1}{x_n}, \\dots, \\dfrac{x_{n - 1}}{x_n}, 1}}, $$\nand so $ \\phi $ is a rational map. This map is called the \\textbf{projection from $ p $ onto $ H $}. We have $ \\dom \\phi = \\AA^n \\setminus H_p $. Note that we have not proved this, because we have not proved that there is no other list of fractions which define the same rational map but have non-zero denominators at points in $ H_p $. One can prove this. For any affine algebraic set $ V \\subseteq \\AA^n $ such that $ V \\not\\subseteq H_p $, we can restrict $ \\phi $ to get a rational map $ V \\dashrightarrow H $. Note that $ p $ might be in $ V $, or it might not.\n\\end{example*}\n\n\\pagebreak\n\n\\begin{example*}\nLet $ V $ be the circle $ \\cbr{\\br{x, y} \\st x^2 + y^2 = 1} $. Consider the projection from the point $ p = \\br{1, 0} $ on to the line $ x = 0 $. This is a rational map with the formula\n$$ \\rational[\\pi]{V}{\\AA^1}{\\br{x, y}}{\\dfrac{y}{1 - x}}. $$\nWe can see geometrically that this projection induces a bijection between the circle, excluding $ p $, and the line, at least for real points. If we compute the formula for the inverse map, we get\n$$ \\rational[\\psi]{\\AA^1}{V}{t}{\\br{\\dfrac{t^2 - 1}{t^2 + 1}, \\dfrac{2t}{t^2 + 1}}}, $$\na well-known parameterisation of the circle. Thus we see that the inverse is a rational map. Note that $ \\psi $ is not regular at $ t = \\pm i $. We do not see this on the picture, which only shows the real points.\n\\end{example*}\n\nWe would like to define formally what it means to say that the rational maps $ \\pi $ and $ \\psi $ are inverse to each other, taking into account that they are not true functions between the sets $ V $ and $ \\AA^1 $ because they are not regular everywhere. These maps are inverses in that composing them, either way round, gives the identity, if we ignore the points where the maps are not regular.\n\n\\subsubsection{Birational equivalences}\n\n\\lecture{9}{Friday}{31/01/20}\n\nIn order to do this, we first define what it means to compose rational maps. But it does not always make sense to compose rational maps. In order to rigorously define composition of rational maps, we need to notice that sometimes the set of points where a composite map is undefined is everywhere and exclude that situation.\n\n\\begin{example*}\nConsider the rational map defined by\n$$ \\rational[\\xi]{\\AA^2}{\\AA^1}{\\br{x, y}}{\\dfrac{1}{1 - x^2 - y^2}}. $$\nThis map is not regular anywhere on the circle $ V $, and hence it does not make sense to try to define the composite map $ \\xi \\circ \\psi : \\AA^1 \\dashrightarrow \\AA^1 $, since it is not defined anywhere.\n\\end{example*}\n\nThis problem can occur because the image of $ \\psi $ is not dense in $ \\AA^2 $. So to rule it out this problem, we make the following definition of dominant rational maps.\n\n\\begin{definition*}\nThe \\textbf{image} of a rational map $ \\phi : V \\dashrightarrow W $ is the set of points\n$$ \\cbr{\\phi\\br{x} \\in W \\st x \\in \\dom \\phi}. $$\nA rational map is \\textbf{dominant} if its image is Zariski dense in $ W $.\n\\end{definition*}\n\n\\begin{example*}\n$ \\psi $ from the end of the previous lecture is dominant if we consider it as a rational map $ \\AA^1 \\dashrightarrow V $ but it is not dominant if we consider it as a rational map $ \\AA^1 \\dashrightarrow \\AA^2 $. This is like surjectivity, since whether a function is surjective or not depends on what codomain you declare it to have.\n\\end{example*}\n\nLet $ V, W, T $ be irreducible affine algebraic sets. If $ \\phi : V \\dashrightarrow W $ is a dominant rational map and $ \\psi : W \\dashrightarrow T $ is a rational map, where $ \\psi $ is not required to be dominant, then it makes sense to compose them because we know that $ \\dom \\psi $ is a Zariski open subset of $ W $, while $ \\im \\phi $ is a Zariski dense subset of $ W $ and so $ \\dom \\psi \\cap \\im \\phi \\ne \\emptyset $. Thus there are at least some points where $ \\psi \\circ \\phi $ is defined. One can check, by writing out $ \\psi $ in terms of fractions of polynomials, then substituting in fractions of polynomials representing $ \\phi $, that $ \\psi \\circ \\phi $ is a rational map $ V \\dashrightarrow T $.\n\n\\begin{definition*}\nRational maps $ \\phi : V \\dashrightarrow W $ and $ \\psi : W \\to V $ are \\textbf{rational inverses} if both are dominant and $ \\phi \\circ \\psi = \\id_W $ and $ \\psi \\circ \\phi = \\id_V $, everywhere these composite rational maps are well-defined. A rational map $ \\phi : V \\dashrightarrow W $ is a \\textbf{birational equivalence} if it is dominant and has a rational inverse. We say that irreducible algebraic sets $ V $ and $ W $ are \\textbf{birational}, or \\textbf{birationally equivalent}, if there exists a birational equivalence $ V \\dashrightarrow W $.\n\\end{definition*}\n\n\\begin{example*}\nOur example from the previous lecture showed that the circle is birational to $ \\AA^1 $.\n\\end{example*}\n\n\\pagebreak\n\n\\begin{example*}\nAnother example is the cuspidal cubic $ W = \\cbr{\\br{x, y} \\st y^2 = x^3} $. This is also birational to $ \\AA^1 $, as shown by the rational maps\n$$ \\birational{W}{\\AA^1}{\\br{x, y}}{\\dfrac{y}{x}}{\\br{t^2, t^3}}{t}. $$\n\\end{example*}\n\nBirationally equivalent affine algebraic sets look the same almost everywhere.\n\n\\begin{example*}\nThe cuspidal cubic is the same as the affine line everywhere except at the origin.\n\\end{example*}\n\n\\begin{example*}\n$ \\AA^1 $ is not birationally equivalent to $ \\AA^2 $ or to an elliptic curve $ \\cbr{\\br{x, y} \\st y^2 = f\\br{x}} $ where $ f $ is a cubic polynomial with no repeated roots. We will prove this later in the course once we have more tools.\n\\end{example*}\n\n\\subsubsection{Dominant rational maps and \\texorpdfstring{$ k $}{k}-field homomorphisms}\n\nIf $ \\phi : V \\dashrightarrow W $ is a dominant rational map, then we can use it to pull back rational functions from $ W $ to $ V $, just like we earlier used regular maps to pull back regular functions. We get a $ k $-homomorphism of fields defined by\n$$ \\function[\\phi^*]{k\\br{W}}{k\\br{V}}{g}{g \\circ \\phi}. $$\nA \\textbf{$ k $-homomorphism} means that $ \\phi^* $ restricts to the identity on the copies of $ k $ which are contained in $ k\\br{W} $ and $ k\\br{V} $, namely the constant functions. If $ \\phi $ is a birational equivalence, then $ \\phi^* $ is a $ k $-isomorphism of fields.\n\n\\subsection{Equivalence of algebra and geometry}\n\n\\subsubsection{From algebra homomorphisms to regular maps}\n\nWe have seen that each regular map $ f : V \\to W $ induces a $ k $-algebra homomorphism $ f^* : k\\sbr{W} \\to k\\sbr{V} $, and that each dominant rational map $ \\phi : V \\dashrightarrow W $ induces a $ k $-field homomorphism $ \\phi^* : k\\br{W} \\to k\\br{V} $. We can also carry out these constructions in the reverse direction. Starting with a $ k $-algebra homomorphism and getting a regular map, or similarly for rational maps. Observe that if $ f : V \\to W $ is a regular map and $ W \\subseteq \\AA^n $, we can recover $ f $ from $ f^* : k\\sbr{W} \\to k\\sbr{V} $ by taking the coordinate functions $ X_1, \\dots, X_n \\in k\\sbr{W} $ on $ W $ and pulling them back to get $ f_1 = f^*X_1, \\dots, f_n = f^*X_n \\in k\\sbr{V} $. These are precisely the regular functions on $ V $ such that $ f = \\br{f_1, \\dots, f_n} $. We generalise this procedure for any $ k $-algebra homomorphism $ \\alpha : k\\sbr{W} \\to k\\sbr{V} $. Starting from an arbitrary $ k $-algebra homomorphism $ \\alpha : k\\sbr{W} \\to k\\sbr{V} $, we define a regular map $ s : V \\to W $ by\n$$ s = \\br{\\alpha\\br{X_1}, \\dots, \\alpha\\br{X_n}}. $$\nHere $ \\alpha\\br{X_1}, \\dots, \\alpha\\br{X_n} \\in k\\sbr{V} $. Then $ \\alpha = s^* : k\\sbr{W} \\to k\\sbr{V} $. Thus every $ k $-algebra homomorphism $ k\\sbr{W} \\to k\\sbr{V} $ is the pull-back by some regular map $ V \\to W $. We conclude the following.\n\n\\begin{proposition}\n$ \\phi \\mapsto \\phi^* $ is a bijection\n$$ \\cbr{\\text{regular maps} \\ V \\to W} \\to \\cbr{\\text{$ k $-algebra homomorphisms} \\ k\\sbr{W} \\to k\\sbr{V}}. $$\n\\end{proposition}\n\n\\begin{corollary}\nAffine algebraic sets $ V $ and $ W $ are isomorphic if and only if their coordinate rings $ k\\sbr{V} $ and $ k\\sbr{W} $ are isomorphic as $ k $-algebras.\n\\end{corollary}\n\nThe moral is that if we only care about affine algebraic sets up to isomorphism, then coordinate rings contain exactly the same information as algebraic sets themselves. In the language of category theory, the functor $ V \\to k\\sbr{V} $ is fully faithful. One can do the same thing for rational maps.\n\n\\begin{proposition}\n$ \\phi \\mapsto \\phi^* $ is a bijection\n$$ \\cbr{\\text{dominant rational maps} \\ V \\dashrightarrow W} \\to \\cbr{\\text{$ k $-field homomorphisms} \\ k\\br{W} \\to k\\br{V}}. $$\n\\end{proposition}\n\n\\begin{corollary}\n\\label{cor:algebrageometry}\nIrreducible affine algebraic sets $ V $ and $ W $ are birationally equivalent if and only if their function fields $ k\\br{V} $ and $ k\\br{W} $ are $ k $-isomorphic.\n\\end{corollary}\n\n\\pagebreak\n\n\\subsubsection{Dictionary between algebraic subsets and ideals}\n\nCan we do something similar with Zariski closed subsets of $ V $, and work them out from the algebra of $ k\\sbr{V} $? Suppose that $ V \\subseteq \\AA^n $. In $ \\AA^n $, the Nullstellensatz tells us that the functions $ \\II $ and $ \\VV $ are bijections\n$$ \\correspondence{\\text{Zariski closed subsets of} \\ \\AA^n}{\\text{radical ideals in} \\ k\\sbr{X_1, \\dots, X_n}}. $$\nSince $ \\II $ and $ \\VV $ reverse the direction of inclusions, we deduce that they restrict to bijections\n$$ \\correspondence{\\text{Zariski closed subsets of} \\ V}{\\text{radical ideals in} \\ k\\sbr{X_1, \\dots, X_n} \\ \\text{containing} \\ \\II\\br{V}}. $$\nWe know that $ k\\sbr{V} \\cong k\\sbr{X_1, \\dots, X_n} / \\II\\br{V} $. It is a basic algebraic fact that\n$$ \\correspondence{\\text{ideals in} \\ k\\sbr{X_1, \\dots, X_n} \\ \\text{containing} \\ \\II\\br{V}}{\\text{ideals in} \\ k\\sbr{X_1, \\dots, X_n} / \\II\\br{V}}. $$\nUnder this correspondence, radical ideals on one side correspond to radical ideals on the other side and similarly for prime ideals. We conclude that the natural maps are bijections\n$$ \\correspondence{\\text{Zariski closed subsets of} \\ V}{\\text{radical ideals in} \\ k\\sbr{V}}, $$\nand\n$$ \\correspondence{\\text{irreducible Zariski closed subsets of} \\ V}{\\text{prime ideals in} \\ k\\sbr{V}}. $$\nCan we describe the points of an affine algebraic set $ V $ in terms of the algebra of $ k\\sbr{V} $? The points of $ V $ are the smallest non-empty Zariski closed subsets. Since the bijection between Zariski closed subsets and ideals reverses direction of inclusion, they correspond to maximal ideals, so\n$$ \\correspondence{\\text{points of} \\ V}{\\text{maximal ideals in} \\ k\\sbr{V}}. $$\n\n\\lecture{10}{Monday}{03/02/20}\n\nLecture 10 is a problems class.\n\n\\subsubsection{Reduced finitely generated \\texorpdfstring{$ k $}{k}-algebras}\n\n\\lecture{11}{Thursday}{06/02/20}\n\nWe have seen that $ V \\mapsto k\\sbr{V} $ leads to bijections on maps between affine algebraic sets. To fully understand the relationship between affine algebraic sets and $ k $-algebras, there is one more question to answer. Which $ k $-algebras can occur as $ k\\sbr{V} $ where $ V $ is an affine algebraic set? We write down some algebraic properties which obviously hold for $ A = k\\sbr{V} $, the coordinate ring of an affine algebraic set $ V $.\n\\begin{itemize}\n\\item $ A $ is finitely generated, because if $ V \\subseteq \\AA^n $ then $ A $ is generated by the coordinate functions $ X_1, \\dots, X_n $.\n\\item $ A $ is reduced, meaning that if $ f \\in A $ and $ f^k = 0 $ for some $ k > 0 $, then $ f = 0 $. This is because $ A $ is a ring of functions in the usual set-theoretic sense, since if $ f^k = 0 $ then $ f\\br{x}^k = 0 $ for all $ x \\in V $, so $ f\\br{x} = 0 $ for all $ x \\in V $.\n\\end{itemize}\nUsing the Nullstellensatz, we can prove that these properties are enough to characterise the $ k $-algebras which are coordinate rings of affine algebraic sets.\n\n\\begin{proposition}\n\\label{prop:kva}\nLet $ A $ be a finitely generated reduced $ k $-algebra. Then there exists an affine algebraic set $ V $ such that $ k\\sbr{V} \\cong A $.\n\\end{proposition}\n\n\\begin{proof}\nPick a finite set $ f_1, \\dots, f_n \\in A $ which generates $ A $ as a $ k $-algebra. We can define a homomorphism\n$$ \\function[\\alpha]{k\\sbr{X_1, \\dots, X_n}}{A}{\\br{X_1, \\dots, X_n}}{\\br{f_1, \\dots, f_n}}. $$\nLet $ I = \\ker \\alpha $ and let $ V = \\VV\\br{I} \\subseteq \\AA^n $. The homomorphism $ \\alpha $ is surjective because $ f_1, \\dots, f_n $ generate $ A $, and so $ A \\cong k\\sbr{X_1, \\dots, X_n} / I $. Thus $ k\\sbr{X_1, \\dots, X_n} / I $ is a reduced $ k $-algebra. It follows that $ I $ is a radical ideal. Hence the Nullstellensatz tells us that $ I = \\II\\br{V} $. Thus\n$$ k\\sbr{V} \\cong k\\sbr{X_1, \\dots, X_n} / \\II\\br{V} \\cong k\\sbr{X_1, \\dots, X_n} / I \\cong A. $$\n\\end{proof}\n\n\\pagebreak\n\n\\subsubsection{The notion of an affine variety}\n\nOften in mathematics, it is convenient to consider objects only up to isomorphism.\n\n\\begin{example*}\nOne might talk about the group with seven elements, ignoring the fact that there are many different groups with seven elements because they are all isomorphic to each other, and therefore they all behave in the same ways.\n\\end{example*}\n\nSimilarly, in algebraic geometry we often want to consider affine algebraic sets up to isomorphism. But affine algebraic sets are always defined in a concrete way, since they are a subset of some specific affine space $ \\AA^n $. It is as if we had defined all finite groups to be subgroups of a symmetric group $ \\SSS_n $. And we have seen that affine algebraic sets can be isomorphic even when they appear to be quite different as subsets of affine space.\n\n\\begin{example*}\nThe line $ \\AA^1 $ is isomorphic to the parabola $ \\VV\\br{Y - X^2} \\subseteq \\AA^2 $.\n\\end{example*}\n\nThus it is useful to use different terminology. We talk about affine algebraic sets when we mean subsets of $ \\AA^n $, and we talk about \\textbf{affine varieties} when we mean an affine algebraic set up to isomorphism, forgetting its embedding into $ \\AA^n $. Proposition \\ref{prop:kva} is more naturally stated in terms of affine varieties rather than affine algebraic sets, since in the proof we had to choose a generating set for $ A $, for which there is no distinguished choice. Different choices of generating set would lead to isomorphic affine algebraic sets, but embedded differently into affine space. So it is better to say that each finitely generated reduced $ k $-algebra $ A $ is the coordinate ring of some affine variety $ V $, with no distinguished choice of embedding into $ \\AA^n $. I mentioned this philosophy about affine varieties before, and I will mention it again after we have defined quasi-projective varieties. For those who know some fancy categorical language, we can sum up all the results on the equivalence between affine geometric objects and their coordinate rings by saying that $ V \\mapsto k\\sbr{V} $ is an equivalence of categories\n$$ \\cbr{\\text{affine varieties over} \\ k} \\to \\cbr{\\text{reduced finitely generated $ k $-algebras}}^{\\op}, $$\nwhere the superscript $ \\op $ indicates that the directions of morphisms are reversed. Let $ A $ be a reduced finitely generated $ k $-algebra and $ V $ an affine variety such that $ A \\cong k\\sbr{V} $. How can we work out the geometry of $ V $ from the algebra of $ A $? If we choose an embedding of $ V $ into $ \\AA^n $, then we get an isomorphism $ k\\sbr{X_1, \\dots, X_n} / \\II\\br{V} \\to A $. We conclude that\n$$ \\correspondence{\\text{Zariski closed subsets of} \\ V}{\\text{radical ideals in} \\ A}, $$\n$$ \\correspondence{\\text{irreducible Zariski closed subsets of} \\ V}{\\text{prime ideals in} \\ A}, $$\n$$ \\correspondence{\\text{points of} \\ V}{\\text{maximal ideals in} \\ A}. $$\n\n\\subsubsection{The weak and strong Nullstellensatz}\n\nNow we aim to prove Hilbert's Nullstellensatz. There are many different proofs, all of which require some difficult algebra. We will roughly follow the method in Shafarevich appendix A, which incorporates the hard algebra into one statement which we can quote, and then do the rest as geometrically as possible. Recall the statement of Hilbert’s Nullstellensatz, Theorem \\ref{thm:strongnullstellensatz}, also called the strong Nullstellensatz. In order to prove this, we will first prove a weaker version, which is called the weak Nullstellensatz, then use that to deduce the strong Nullstellensatz.\n\n\\begin{theorem}[Weak Nullstellensatz]\nLet $ I $ be an ideal in the polynomial ring $ k\\sbr{X_1, \\dots, X_n} $ over an algebraically closed field $ k $. If $ \\VV\\br{I} = \\emptyset $, then $ I = k\\sbr{X_1, \\dots, X_n} $.\n\\end{theorem}\n\nThis is a statement about the existence of solutions to polynomial equations, so it is necessary to require $ k $ to be algebraically closed.\n\n\\begin{example*}\nTo show that it fails when $ k $ is not algebraically closed, consider the ideal $ \\abr{X^2 + Y^2 + 1} $ in $ \\RR\\sbr{X, Y} $. This ideal is not the full polynomial ring, but there are no real solutions to the equation $ x^2 + y^2 + 1 = 0 $.\n\\end{example*}\n\n\\begin{note*}\nThe strong Nullstellensatz easily implies the weak Nullstellensatz. If $ \\VV\\br{I} = \\emptyset $ then the strong Nullstellensatz tells us that $ \\rad I = \\II\\br{\\emptyset} = k\\sbr{X_1, \\dots, X_n} $. In particular, $ 1 \\in \\rad I $ but then $ 1 \\in I $ so $ I = k\\sbr{X_1, \\dots, X_n} $.\n\\end{note*}\n\n\\pagebreak\n\n\\begin{proof}[Proof of Theorem \\ref{thm:strongnullstellensatz}]\nWe use a method called the Rabinowitsch trick, introducing an extra variable. Let $ I $ be an ideal in $ k\\sbr{X_1, \\dots, X_n} $ and let $ V = \\VV\\br{I} \\subseteq \\AA^n $. It is easy to see that $ \\rad I \\subseteq \\II\\br{V} $. Thus we have to prove that $ \\II\\br{V} \\subseteq \\rad I $. Let $ f \\in \\II\\br{V} $. Define a new polynomial $ g $ with an extra variable $ Y $ by\n$$ g\\br{X_1, \\dots, X_n, Y} = f\\br{X_1, \\dots, X_n} \\cdot Y - 1. $$\nLet $ J $ be the ideal in $ k\\sbr{X_1, \\dots, X_n, Y} $ generated by $ I $ and $ g $, and consider the affine algebraic set $ W = \\VV\\br{J} \\subseteq \\AA^{n + 1} $. Every point $ \\br{x_1, \\dots, x_n, y} \\in W $ satisfies $ f\\br{x_1, \\dots, x_n} \\ne 0 $, in order for there to exist some $ y $ such that $ f\\br{x_1, \\dots, x_n}y - 1 = 0 $. This is generalising the fact that the hyperbola projects down to $ \\AA^1 \\setminus \\cbr{0} $. Since $ I \\subseteq J $, points $ \\br{x_1, \\dots, x_n, y} $ of $ W $ also satisfy $ \\br{x_1, \\dots, x_n} \\in V $. Therefore, if $ \\pi : \\AA^{n + 1} \\to \\AA^n $ is the projection map, forgetting the extra $ Y $ coordinate, then\n$$ \\pi\\br{W} \\subseteq \\cbr{\\br{x_1, \\dots, x_n} \\in V \\st f\\br{x_1, \\dots, x_n} \\ne 0}. $$\nSince $ f \\in \\II\\br{V} $, the set on the right is empty. Thus $ \\pi\\br{W} = \\emptyset $. This implies that $ W $ itself is empty. Therefore, by the weak Nullstellensatz, $ J = k\\sbr{X_1, \\dots, X_n, Y} $. In particular, $ 1 \\in J $ and thus $ 1 = a + bg $ for some $ a \\in I \\cdot k\\sbr{X_1, \\dots, X_n, Y} $ and $ b \\in k\\sbr{X_1, \\dots, X_n, Y} $. Expanding out $ a $ and $ b $ as sums over powers of $ Y $,\n$$ a = \\sum_{j \\ge 0} a_jY^j, \\qquad b = \\sum_{j \\ge 0} b_jY^j, \\qquad a_j \\in I, \\qquad b_j \\in k\\sbr{X_1, \\dots, X_n}. $$\nThe equation $ 1 = a + bg $ can be expanded and rearranged to give\n$$ 1 = a_0 - b_0 + \\sum_{j \\ge 1} \\br{a_j + b_{j - 1}f - b_j}Y^j. $$\nLooking at the terms of degree zero in $ Y $ gives $ b_0 = a_0 - 1 \\in I - 1 $, then terms of degree one in $ Y $ gives $ b_1 = a_1 + b_0f \\in I - f $, using $ a_1 \\in I $ and $ b_0 \\in I - 1 $. Continuing by induction on $ j $, these imply that\n$$ b_j = a_j + b_{j - 1}f \\in I - f^j, \\qquad j \\ge 0, $$\nwhere $ I - f^j $ means the coset $ \\cbr{t - f^j \\st t \\in I} $. But $ b $ is a polynomial, so $ b_j = 0 $ once $ j $ gets large enough. Thus for some $ j $, we get $ 0 \\in I - f^j $, that is $ f^j \\in I $. This proves that $ f \\in \\rad I $.\n\\end{proof}\n\n\\lecture{12}{Friday}{07/02/20}\n\nWe can restate the weak Nullstellensatz in elementary terms as, if $ f_1, \\dots, f_m \\in k\\sbr{X_1, \\dots, X_n} $ are a finite set of polynomials, and the ideal $ I $ which they generate is not the whole polynomial ring, then there exists a common solution $ \\br{x_1, \\dots, x_n} \\in k^n $ to the equations\n$$ f_1\\br{x_1, \\dots, x_n} = 0, \\qquad \\dots, \\qquad f_m\\br{x_1, \\dots, x_n} = 0. $$\nWe prove this in two steps.\n\\begin{enumerate}[label=Step \\arabic*., leftmargin=0.5in]\n\\item There exists a larger field $ K $ containing $ k $ such that these equations have a common solution in $ K^n $.\n\\item If the equations have a common solution in $ K^n $, then they also have a common solution in $ k^n $.\n\\end{enumerate}\n\n\\subsubsection{Finding a solution in a bigger field}\n\nThe proof of step $ 1 $ is fairly short, and relies on Zorn's lemma.\n\n\\begin{lemma}\nLet $ f_1, \\dots, f_m $ be polynomials in $ k\\sbr{X_1, \\dots, X_n} $, such that the ideal $ I = \\abr{f_1, \\dots, f_m} $ is not equal to $ k\\sbr{X_1, \\dots, X_n} $. Then there exists a field $ K $ which is a finitely generated extension of $ k $ such that the equations $ f_1 = \\dots = f_m = 0 $ have a common solution $ \\br{x_1, \\dots, x_n} \\in K^n $.\n\\end{lemma}\n\nBecause $ I \\ne k\\sbr{X_1, \\dots, X_n} $, we can use Zorn's lemma to show that $ I $ is contained in some maximal ideal $ M \\subseteq k\\sbr{X_1, \\dots, X_n} $. This is a natural way to start, since we are trying to show that $ \\VV\\br{I} $ has a point, and last time we saw that points in $ \\VV\\br{I} $ correspond to maximal ideals in $ k\\sbr{X_1, \\dots, X_n} $ containing $ I $. We cannot just quote the correspondence from the previous lecture because we used the Nullstellensatz in proving that correspondence, but this justifies why obtaining a maximal ideal is a good first step.\n\n\\begin{proof}\nLet $ K = k\\sbr{X_1, \\dots, X_n} / M $. Let $ x_1, \\dots, x_n $ denote the images of $ X_1, \\dots, X_n $ in $ K $. Then $ K $ is a field because $ M $ is a maximal ideal, and it is finitely generated as an extension of $ k $ because it is generated by $ x_1, \\dots, x_n $. Since $ f_j\\br{X_1, \\dots, X_n} \\in I \\subseteq M $, we get that $ f_j\\br{x_1, \\dots, x_n} = 0 $ in $ K $ for each $ j $. Thus $ \\br{x_1, \\dots, x_n} $ is the required common solution to $ f_1, \\dots, f_m $ in $ K^n $.\n\\end{proof}\n\n\\pagebreak\n\n\\subsubsection{Shrinking the field required}\n\nBefore proving step $ 2 $, we begin by quoting an algebraic result.\n\n\\begin{lemma}\n\\label{lem:algebraicallyindependent}\nLet $ k $ be an algebraically closed field and let $ K $ be a finitely generated extension field of $ k $. Then there exist $ t_1, \\dots, t_d, u \\in K $ such that\n\\begin{itemize}\n\\item $ K = k\\br{t_1, \\dots, t_d, u} $,\n\\item $ t_1, \\dots, t_d $ are algebraically independent over $ k $, that is there is no non-zero polynomial in $ d $ variables with coefficients in $ k $ whose value at $ \\br{t_1, \\dots, t_d} $ is zero, and\n\\item $ u $ is algebraic over $ k\\br{t_1, \\dots, t_d} $, that is there exists a non-zero polynomial in one variable with coefficients in the field $ k\\br{t_1, \\dots, t_d} $ which is zero at $ u $.\n\\end{itemize}\n\\end{lemma}\n\n\\begin{proof}\nThis follows from the primitive element theorem in field theory. For a full proof, see Proposition A.7 in the appendix of Shafarevich basic algebraic geometry.\n\\end{proof}\n\nLemma \\ref{lem:algebraicallyindependent} has a nice geometric interpretation. Every finitely generated extension of $ k $ is isomorphic to the field of fractions of a hypersurface. We need to use the Nullstellensatz to prove this geometric interpretation, so that is postponed until after we have finished the proof of the Nullstellensatz.\n\n\\begin{theorem}\n\\label{thm:shrinkingfield}\nLet $ k $ be an algebraically closed field and let $ K $ be a finitely generated extension field of $ k $. Let $ f_1, \\dots, f_m \\in k\\sbr{X_1, \\dots, X_n} $. Suppose there exists a common solution $ \\br{x_1, \\dots, x_n} \\in K^n $ to the equations $ f_1 = \\dots = f_m = 0 $. Then there exists a common solution $ \\br{y_1, \\dots, y_n} \\in k^n $ to the equations $ f_1 = \\dots = f_m = 0 $.\n\\end{theorem}\n\n\\begin{proof}\nWrite $ K = k\\br{t_1, \\dots, t_d, u} $ as in Lemma \\ref{lem:algebraicallyindependent}. Let $ K' = k\\br{t_1, \\dots, t_d} $. Because $ t_1, \\dots, t_d $ are algebraically independent, we can identify $ K' $ with $ k\\br{T_1, \\dots, T_d} $, the field of fractions of the polynomial ring $ k\\sbr{T_1, \\dots, T_d} $. This will allow us to substitute a vector $ \\underline{z} \\in k^d $ into an element $ \\alpha \\in K' $ and get out an element $ \\alpha\\br{\\underline{z}} \\in k $, as long as the denominator of $ \\alpha $ does not vanish at $ \\underline{z} $. We use two facts about the finite algebraic extension $ K / K' $.\n\\begin{enumerate}[label=Fact \\arabic*., leftmargin=0.5in]\n\\item There exists a minimal polynomial $ p\\br{U} \\in K'\\sbr{U} $ for $ u $. That is, $ p\\br{u} = 0 $, $ p $ has leading coefficient one, and $ p $ divides every other polynomial $ q\\br{U} \\in K'\\sbr{U} $ such that $ q\\br{u} = 0 $.\n\\item Every element of $ K $ can be written in the form $ a\\br{u} $ for some polynomial $ a\\br{U} \\in K'\\sbr{U} $.\n\\end{enumerate}\nThe idea of the proof is to consider the almost hypersurface\n$$ H = \\cbr{\\br{z_1, \\dots, z_d, s} \\in k^{d + 1} \\st p\\br{z_1, \\dots, z_d, s} = 0}. $$\nThe almost is because $ p $ is not a polynomial in $ k\\sbr{T_1, \\dots, T_d, U} $ but rather may have denominators, so we have to ignore the places where these denominators vanish. Then we construct a rational map $ \\phi : H \\dashrightarrow \\VV\\br{f_1, \\dots, f_m} $. The domain of definition of $ \\phi $ is an open subset of an almost hypersurface, and we can easily check that this is non-empty. Then a point in the image of $ \\phi $ gives us a point in $ \\VV\\br{f_1, \\dots, f_m} $, as desired. In particular, we apply fact $ 2 $ to $ x_1, \\dots, x_n \\in K $, our common solution to $ f_1 = \\dots = f_m = 0 $, so we can write $ x_i = a_i\\br{u} $ where $ a_i\\br{U} \\in K'\\sbr{U} $. In the informal outline, these $ a_i \\in k\\br{T_1, \\dots, T_d}\\sbr{U} $ define a rational map $ \\phi : H \\dashrightarrow \\AA^n $. Next we check that the image of this rational map is contained in $ \\VV\\br{f_1, \\dots, f_m} $. We know that $ \\br{x_1, \\dots, x_n} $ is a common solution to the polynomials $ f_1, \\dots, f_m $. Hence\n$$ f_j\\br{a_1\\br{u}, \\dots, a_n\\br{u}} = 0 \\in K, \\qquad j = 1, \\dots, m. $$\nIn other words, the single-variable polynomial $ f_j\\br{a_1\\br{U}, \\dots, a_n\\br{U}} \\in K'\\sbr{U} $ has $ u $ as a root. Therefore, fact $ 1 $ tells us that this polynomial is divisible by $ p\\br{U} $. Thus there exist polynomials $ q_1, \\dots, q_m \\in K'\\sbr{U} $ such that\n\\begin{equation}\n\\label{eq:1}\nf_j\\br{a_1\\br{U}, \\dots, a_n\\br{U}} = q_j\\br{U}p\\br{U} \\in K'\\sbr{U}, \\qquad j = 1, \\dots, m.\n\\end{equation}\nNow, if $ \\br{z_1, \\dots, z_d, s} \\in k^{d + 1} $ satisfies $ p\\br{z_1, \\dots, z_d, s} = 0 $, then $ \\br{\\ref{eq:1}} $ implies that\n$$ f_j\\br{a_1\\br{z_1, \\dots, z_d, s}, \\dots, a_n\\br{z_1, \\dots, z_d, s}} = 0, \\qquad j = 1, \\dots, m, $$\n\n\\pagebreak\n\nso long as all the denominators involved are non-zero. Thus we just have to find $ \\br{z_1, \\dots, z_d, s} $ where all these denominators will be non-zero. So consider the polynomials $ p\\br{U}, a_i\\br{U}, q_j\\br{U} \\in K'\\sbr{U} $.\nTheir coefficients are elements of the field $ K' $ which we are identifying with the field of fractions $ k\\br{T_1, \\dots, T_d} $. Let $ \\sigma \\in k\\sbr{T_1, \\dots, T_d} $ denote the product of the denominators of all these fractions. Because the denominator of a fraction is never zero, $ \\sigma $ is not the zero polynomial in $ k\\sbr{T_1, \\dots, T_d} $. Therefore, there exists $ \\br{s_1, \\dots, s_d} \\in k^d $ such that $ \\sigma\\br{s_1, \\dots, s_d} \\ne 0 $. Then the denominators of the coefficients of $ p, a_i, q_j $ do not vanish at $ s_1, \\dots, s_d $, so we can substitute $ \\br{s_1, \\dots, s_d} $ into each of these coefficients, as elements of $ K' $, and get out values in $ k $. Thus we get new polynomials $ \\widetilde{p}\\br{U}, \\widetilde{a_i}\\br{U}, \\widetilde{q_j}\\br{U} \\in k\\sbr{U} $. The leading coefficient of $ \\widetilde{p}\\br{U} $ is one, which is unchanged by this process. So $ \\widetilde{p}\\br{U} $ has the same degree as $ p\\br{U} $. In particular $ \\widetilde{p}\\br{U} $ is not a constant polynomial. Hence as $ k $ is algebraically closed, there exists $ s \\in k $ such that $ \\widetilde{p}\\br{s} = 0 $. Let $ y_i = \\widetilde{a_i}\\br{s} \\in k $. Then $ \\br{\\ref{eq:1}} $ tells us that\n$$ f_j\\br{y_1, \\dots, y_n} = \\widetilde{q_j}\\br{s}\\widetilde{p}\\br{s}, \\qquad j = 1, \\dots, m. $$\nBut we chose $ s $ such that $ \\widetilde{p}\\br{s} = 0 $, and so we conclude that $ \\br{y_1, \\dots, y_n} \\in k^n $ is a common solution to $ f_1 = \\dots = f_m = 0 $.\n\\end{proof}\n\nCombining Lemma \\ref{lem:algebraicallyindependent} and Theorem \\ref{thm:shrinkingfield} proves the weak Nullstellensatz.\n\n\\subsubsection{Hypersurfaces and birational equivalence}\n\nNow we prove the geometrical interpretation of Lemma \\ref{lem:algebraicallyindependent}.\n\n\\begin{proposition}\n\\label{prop:irreduciblehypersurface}\nLet $ K $ be a finitely generated extension of $ k $. Then there exists an irreducible hypersurface $ H \\subseteq \\AA^{d + 1} $ for some $ d $ such that $ K $ is isomorphic to the field of functions $ k\\br{H} $.\n\\end{proposition}\n\n\\begin{corollary}\n\\label{cor:irreduciblehypersurface}\nLet $ V \\subseteq \\AA^n $ be an irreducible affine algebraic set. Then there exists an irreducible hypersurface $ H \\subseteq \\AA^{d + 1} $ for some $ d $ such that $ V $ is birationally equivalent to $ H $.\n\\end{corollary}\n\nCorollary \\ref{cor:irreduciblehypersurface} tells us that, even if $ V $ is a complicated algebraic set defined by many equations, provided we only care about properties of $ V $ which are preserved by birational equivalence, we can replace $ V $ by a simpler set defined by just one equation, that is a hypersurface.\n\n\\begin{note*}\nIt is not true that every irreducible affine algebraic set is isomorphic to a hypersurface.\n\\end{note*}\n\n\\begin{proof}[Proof of Proposition \\ref{prop:irreduciblehypersurface}]\nWrite $ K = k\\br{t_1, \\dots, t_d, u} $ as in Lemma \\ref{lem:algebraicallyindependent}, and let $ K' = k\\br{t_1, \\dots, t_d} $. Because $ u $ is algebraic over $ K' $, let $ p\\br{U} \\in K'\\sbr{U} $ be the minimal polynomial of $ u $ over $ K' $. Each coefficient of $ p\\br{U} $ is a fraction whose numerator and denominator are polynomials in $ t_1, \\dots, t_d $. We can multiply up by a suitable element of $ k\\sbr{t_1, \\dots, t_d} $ to clear the denominators, and also replace $ t_1, \\dots, t_d $ by indeterminates $ T_1, \\dots, T_d $ to get a polynomial $ g \\in k\\sbr{T_1, \\dots, T_d, U} $ such that $ g\\br{t_1, \\dots, t_d, u} = 0 $ in the field $ K $. Assuming we multiplied up by a lowest common denominator for the coefficients of $ p $, $ g $ is irreducible. Let $ H $ be the hypersurface in $ \\AA^{d + 1} $ defined by the polynomial $ g $. Because $ g $ is irreducible, it generates a radical ideal in $ k\\sbr{X_1, \\dots, X_n} $ and so the strong Nullstellensatz implies that $ \\II\\br{H} = \\abr{g} $. Thus the coordinate ring is given by\n$$ k\\sbr{H} = k\\sbr{T_1, \\dots, T_d, U} / \\abr{g}. $$\nThere is a $ k $-algebra homomorphism\n$$ \\function[\\alpha]{k\\sbr{T_1, \\dots, T_d, U}}{K}{\\br{T_1, \\dots, T_d, U}}{\\br{t_1, \\dots, t_d, u}}. $$\nA little algebra, using Gauss' lemma, shows that the kernel of $ \\alpha $ is generated by $ g $, so $ \\alpha $ induces an injection $ k\\sbr{H} \\hookrightarrow K $. Furthermore, the image of $ \\alpha $ generates $ K $ as a field, so $ \\alpha $ induces an isomorphism from the fraction field of $ k\\sbr{H} $ to $ K $. The fraction field of $ k\\sbr{H} $ is the function field $ k\\br{H} $. Thus we have shown that $ k\\br{H} \\cong k\\br{V} $. By Corollary \\ref{cor:algebrageometry}, this implies that $ V $ is birationally equivalent to $ H $.\n\\end{proof}\n\n\\begin{proof}[Proof of Corollary \\ref{cor:irreduciblehypersurface}]\nApply Proposition \\ref{prop:irreduciblehypersurface} to the function field $ K = k\\br{V} $.\n\\end{proof}\n\n\\lecture{13}{Monday}{10/02/20}\n\nLecture 13 is a class test.\n\n\\pagebreak\n\n\\section{Projective varieties}\n\n\\subsection{Projective algebraic sets}\n\n\\subsubsection{Projective space}\n\n\\lecture{14}{Thursday}{13/02/20}\n\nProjective space consists of affine space together with points at infinity, one for each direction. The purpose for adding extra points is that it avoids special cases where a point disappears to infinity.\n\n\\begin{example*}\nA pair of parallel lines do not intersect in affine space but they do intersect at a point at infinity in projective space.\n\\end{example*}\n\n\\begin{definition*}\n\\textbf{Projective $ n $-space}, $ \\PP^n $, is the set of lines through the origin in $ \\AA^{n + 1} $.\n\\end{definition*}\n\nA convenient way to label points in $ \\PP^n $ is via homogeneous coordinates. These are just coordinates in $ k^{n + 1} \\setminus \\cbr{\\br{0, \\dots, 0}} $, since any sequence of coordinates $ \\underline{x} \\in k^{n + 1} \\setminus \\cbr{\\br{0, \\dots, 0}} $ represents the unique line through the origin and $ \\underline{x} $ in $ \\AA^{n + 1} $. Two sequences of homogeneous coordinates $ \\br{x_0, \\dots, x_n} $ and $ \\br{y_0, \\dots, y_n} $ represent the same point in $ \\PP^n $ if and only if there exists $ \\lambda \\in k \\setminus \\cbr{0} $ such that $ \\br{x_0, \\dots, x_n} = \\br{\\lambda y_0, \\dots, \\lambda y_n} $. Thus projective $ n $-space is the quotient of $ k^{n + 1} \\setminus \\cbr{\\br{0, \\dots, 0}} $ by the equivalence relation\n$$ \\br{x_0, \\dots, x_n} \\sim \\br{\\lambda x_0, \\dots, \\lambda x_n}, \\qquad \\lambda \\in k \\setminus \\cbr{0}. $$\nWe call a representative for an equivalence class the \\textbf{homogeneous coordinates} of that point in $ \\PP^n $, and there are many choices for each point, by scaling by $ \\lambda $. To avoid confusion between homogeneous coordinates for $ \\PP^n $ and ordinary coordinates for $ \\AA^n $, we usually write homogeneous coordinates as $ \\sbr{x_0 : \\dots : x_n} $. Observe that we can embed\n$$ \\function{\\AA^n}{\\PP^n}{\\br{x_1, \\dots, x_n}}{\\sbr{1 : x_1 : \\dots : x_n}}. $$\nAny other homogeneous coordinates where the first coordinate is non-zero can be re-scaled to have first coordinate one. So we are left with the points with first coordinate equal to zero. These are the \\textbf{points at infinity}. A point $ \\sbr{0 : x_1 : \\dots : x_n} $ can be seen as a point in $ \\PP^{n - 1} $, by just dropping the initial zero. Thus\n$$ \\PP^n = \\AA^n \\cup \\PP^{n - 1}. $$\nSimilarly, we can embed $ \\AA^1 $ by the map $ x \\mapsto \\sbr{1 : x} $, and then the point at infinity is $ \\sbr{0 : 1} $, so\n$$ \\PP^1 = \\AA^1 \\cup \\cbr{\\sbr{0 : 1}}. $$\nOver the complex numbers, $ \\PP_\\CC^1 $ is also called the \\textbf{Riemann sphere}. Thinking about projective space as affine space plus points at infinity can be useful if we want to make use of our geometric intuition about affine space or the algebraic tools we have developed for working with affine algebraic sets. On the other hand, thinking about projective space in terms of homogeneous coordinates emphasises that all points of projective space look the same, since we can only distinguish points at infinity from points in affine space after choosing a convention for how we embed $ \\AA^n $ into $ \\PP^n $.\n\n\\begin{example*}\nWe could have used $ \\sbr{x_1 : \\dots : x_n : 1} $ instead.\n\\end{example*}\n\nThroughout this lecture we will use the convention above.\n\n\\subsubsection{Definition and examples}\n\nA projective algebraic set is a subset of projective space defined by the vanishing of a finite list of polynomials. What does it mean for a polynomial to vanish at a point in projective space? Because a single point in $ \\PP^n $ can be represented by many different homogeneous coordinates, it does not make sense to evaluate a polynomial in $ k\\sbr{X_0, \\dots, X_n} $ at a point of $ \\PP^n $. We have to restrict attention to homogeneous polynomials.\n\n\\begin{definition*}\nA polynomial $ f \\in k\\sbr{X_0, \\dots, X_n} $ is \\textbf{homogeneous} if every term of $ f $ has the same degree.\n\\end{definition*}\n\n\\begin{example*}\n$ X_0^3 + X_0^2X_1 + 3X_2^3 - X_0X_1X_2 $ is homogeneous of degree three while $ X_0X_1 - X_2 $ is not homogeneous because it has a term of degree two and a term of degree one.\n\\end{example*}\n\nIf $ \\sbr{x_0 : \\dots : x_n} $ and $ \\sbr{y_0 : \\dots : y_n} $ represent the same point $ p \\in \\PP^n $, then\n$$ \\br{x_0, \\dots, x_n} = \\lambda\\br{y_0, \\dots, y_n}, \\qquad \\lambda \\in k \\setminus \\cbr{0}. $$\n\n\\pagebreak\n\nHence if $ f \\in k\\sbr{X_0, \\dots, X_n} $ is a homogeneous polynomial of degree $ d $, then\n$$ f\\br{x_0, \\dots, x_n} = \\lambda^df\\br{y_0, \\dots, y_n}. $$\nThus the actual value of $ f $ at $ p $ is not well-defined, but it is well-defined to ask whether or not $ f $ is zero at $ p $.\n\n\\begin{definition*}\nA \\textbf{projective algebraic set} is a set of the form\n$$ \\cbr{\\sbr{x_0 : \\dots : x_n} \\in \\PP^n \\st f_1\\br{x_0, \\dots, x_n} = \\dots = f_m\\br{x_0, \\dots, x_n} = 0}, $$\nfor some finite list of homogeneous polynomials $ f_1, \\dots, f_m \\in k\\sbr{X_0, \\dots, X_n} $.\n\\end{definition*}\n\nBy definition, a projective algebraic set is the vanishing of finitely many homogeneous polynomials. We can use the Hilbert basis theorem to show that the vanishing set of an infinite collection of homogeneous polynomials is a projective algebraic set. This is similar to the analogous result for affine algebraic sets, but a little trickier due to the word homogeneous.\n\n\\begin{example*}\nAn example of a projective algebraic set is\n$$ V' = \\cbr{\\sbr{w : x : y} \\in \\PP^2 \\st wx - y^2 = 0}. $$\nWhat is $ V = V' \\cap \\AA^2 $, using the embedding $ \\AA^2 \\to \\PP^2 $ which we considered before? To find this, we just substitute $ w = 1 $ into the equation for $ V' $, so\n$$ V = \\cbr{\\br{x, y} \\in \\AA^2 \\st x - y^2 = 0}, $$\nthat is an affine parabola. The polynomial $ X - Y^2 $ is not homogeneous. Therefore consider instead the homogeneous polynomial $ WX - Y^2 $. When $ W = 1 $, this restricts to $ X - Y^2 $. That takes care of the points of $ V' $ where $ w \\ne 0 $, since we can scale the homogeneous coordinates of such a point to get $ w = 1 $. But $ V' $ contains extra points where $ w = 0 $. We can also work out the intersection of $ V' $ with the $ \\PP^1 $ at infinity. Substituting $ w = 0 $ into the equation $ wx - y^2 = 0 $ for $ V' $ gives also $ y = 0 $. There is only one point of $ \\PP^2 $ with $ w = y = 0 $, the point $ \\sbr{0 : 1 : 0} $, since any other value for $ x $ could be scaled to one. So we get\n$$ V' = V \\cup \\cbr{\\sbr{0 : 1 : 0}}. $$\nThus geometrically, $ V' $ consists of the parabola $ V $ together with a point at infinity in the direction $ \\br{1, 0} $, that is along the $ x $-axis. Informally, the two arms of the parabola close up at infinity.\n\\end{example*}\n\nWe would like to reverse this process, and go from an affine algebraic set to a projective algebraic set.\n\n\\begin{example*}\nConsider the affine hyperbola\n$$ H = \\cbr{\\br{x, y} \\in \\AA^2 \\st xy - 1 = 0}. $$\nWe need to turn the polynomial $ XY - 1 $ into a homogeneous polynomial, using a new variable $ W $ in $ k\\sbr{W, X, Y} $, which restricts to $ XY - 1 $ when $ W = 1 $. To do this, note that the highest degree term in $ XY - 1 $ has degree two. We multiply each term by an appropriate power of $ W $ to get all terms of degree two, so we have to replace the constant one by $ W^2 $. Thus we get $ XY - W^2 = 0 $. Thus we consider\n$$ H' = \\cbr{\\sbr{w : x : y} \\in \\PP^2 \\st xy - w^2 = 0}. $$\nAgain, when $ w \\ne 0 $, we can scale to get $ w = 1 $, so we can substitute that in and see that we just get back $ H' $. When $ w = 0 $, the equation becomes $ xy = 0 $, so we now get two points at infinity. Either $ x = 0 $, giving the point $ \\sbr{0 : 0 : 1} \\in \\PP^2 $, or $ y = 0 $, giving the point $ \\sbr{0 : 1 : 0} \\in \\PP^2 $. Thus\n$$ H' = H \\cup \\cbr{\\sbr{0 : 0 : 1}, \\sbr{0 : 1 : 0}}. $$\nGeometrically, $ H' $ consists of $ H $ together with points at infinity along the $ x $-axis and $ y $-axis. These axes are the asymptotes of $ H $.\n\\end{example*}\n\nCompare the two above examples, where $ V' $ had equation $ wx - y^2 $, and $ H' $ had equation $ xy - w^2 $. These equations differ only by relabelling the coordinates. Thus $ V' $ and $ H' $ are isomorphic. We have not yet defined isomorphism of projective algebraic sets, but just relabelling the coordinates should certainly be an isomorphism. From the point of view of projective geometry, the only difference between the hyperbola and the parabola is that the parabola has one point at infinity while the hyperbola has two points at infinity. It turns out that $ V' $ and $ H' $ are also isomorphic to the projective line $ \\PP^1 $. We will need to define isomorphism of projective algebraic sets before we can prove this.\n\n\\pagebreak\n\n\\subsubsection{Homogenisation}\n\nThe process we went through above to obtain $ V' $ from $ V $ and $ H' $ from $ H $ can be generalised.\n\n\\begin{definition*}\nFor any polynomial $ f \\in k\\sbr{X_1, \\dots, X_n} $, we define the \\textbf{homogenisation} of $ f $ to be the polynomial in $ \\overline{f} \\in k\\sbr{X_0, \\dots, X_n} $ obtained by the following procedure. Let $ d $ be the maximum degree of terms of $ f $. Then multiply each term of $ f $ by $ X_0^{d - e} $, where $ e $ is the degree of this term in $ f $.\n\\end{definition*}\n\n\\begin{example*}\nIf\n$$ f\\br{X_1, X_2, X_3} = X_1^3 + 4X_1X_2X_3 - X_1^2 - X_2^2 + 5X_3 + 8, $$\nthen the homogenisation is\n$$ \\overline{f}\\br{X_0, X_1, X_2, X_3} = X_1^3 + 4X_1X_2X_3 - X_1^2X_0 - X_2^2X_0 + 5X_3X_0^2 + 8X_0^3. $$\n\\end{example*}\n\nLet $ V \\subseteq \\AA^n $ be an affine algebraic set. Let $ W \\subseteq \\PP^n $ be the set defined by the homogenisations of all polynomials in $ \\II\\br{V} $. Then $ W $ is the smallest projective algebraic set containing $ V $. This is not entirely obvious, because we have defined it using infinitely many homogeneous polynomials. When we substitute $ x_0 = 1 $ into the polynomials defining $ W $, we just get back $ \\II\\br{V} $, so\n$$ W \\cap \\cbr{\\sbr{1 : x_1 : \\dots : x_n}} = V. $$\nThis proves that every affine algebraic set $ V $ is of the form $ W \\cap \\AA^n $ for some projective algebraic set $ W $. We call $ W $ the \\textbf{projective closure} of $ V $. When defining the projective closure, it is not enough to just take the homogenisations of some finite list of polynomials which define $ V $. You must take all of $ \\II\\br{V} $. The standard example of this below shows that if we just use homogenisations of a generating set, instead of all of $ \\II\\br{V} $, we still get a projective algebraic set $ V' $ such that $ V' \\cap \\AA^n = V $, but it might not be the smallest such set.\n\n\\begin{example*}\nHere is a more complex example, the twisted cubic curve. Let\n$$ C = \\cbr{\\br{t, t^2, t^3} \\in \\AA^3} = \\VV\\br{Y - X^2, Z - XY} \\subseteq \\AA^3. $$\nParametrically, we can write this as\n$$ C = \\cbr{\\sbr{1 : t : t^3 : t^3} \\in \\PP^3}. $$\nHomogenising the parametric description, we might expect the projective closure to be\n$$ C' = \\cbr{\\sbr{s^3 : s^2t : st^2 : t^3} \\in \\PP^3} = C \\cup \\cbr{\\sbr{0 : 0 : 0 : 1}}. $$\nOne can check that $ C' $ is a projective algebraic set. But if we homogenise the two defining polynomials $ Y - X^2 $ and $ Z - XY $, we get the projective algebraic set\n$$ C'' = \\cbr{\\sbr{w : x : y : z} \\in \\PP^3 \\st wy - x^2 = wz - xy = 0}. $$\nIt is still true that we can reverse this by just setting $ w = 1 $, so $ C'' \\cap \\AA^3 = C $. But what happens at infinity? Substituting in $ w = 0 $, one can check that\n$$ C'' = C \\cup \\cbr{\\sbr{0 : x : y : z} \\in \\PP^3 \\st -x^2 = -xy = 0} = C \\cup \\cbr{\\sbr{0 : 0 : y : z} \\in \\PP^3}. $$\nThus the intersection of $ C'' $ with the plane at infinity is a copy of $ \\PP^1 $. Thus $ C'' \\ne C' $, since it contains an extra line at infinity. This is not what we should expect, if $ C'' $ were the projective closure of $ C $, since the dimension of the intersection with the plane at infinity should be smaller than the dimension of the initial affine algebraic set, speaking informally. If we homogenised all polynomials in $ \\II\\br{C} $ and not just the two generators, then you can calculate that the projective closure of $ C $ is in fact\n$$ C' = \\cbr{\\sbr{w : x : y : z} \\in \\PP^3 \\st wy - x^2 = wz - xy = xz - y^2 = 0} = C \\cup \\cbr{\\sbr{0 : 0 : 0 : 1}}. $$\nThe three polynomials $ Y - X^2, Z - XY, XZ - Y^2 $ are a generating set for $ \\II\\br{C} $ and their homogenisations define $ C' $. The extra polynomial involves only $ x, y, z $ and is in the ideal generated by $ Y - X^2 $ and $ Z - XY $. I am not giving a procedure to find the projective closure of a given affine algebraic set. I just assert that this happens to work in this case. There is an algorithm but you would not want to have to use it by hand.\n\\end{example*}\n\n\\pagebreak\n\n\\subsubsection{Zariski topology on projective space}\n\nWe can define the Zariski topology on $ \\PP^n $ by saying that the closed subsets are the projective algebraic sets. Observe that $ \\AA^n $ is embedded as a Zariski open subset in $ \\PP^n $, because the complement $ \\PP^n \\setminus \\AA^n $ is described by the homogeneous polynomial equation $ X_0 = 0 $. The existence of projective closures shows that the Zariski topology on $ \\AA^n $ is the same as the subspace topology coming from the Zariski topology on $ \\AA^n \\subseteq \\PP^n $. The terminology projective closure is justified by noting that the smallest projective algebraic set containing $ V \\subseteq \\AA^n $ which we just described is the same as the closure of $ V $ in the Zariski topology on $ \\PP^n $.\n\n\\subsubsection{Homogeneous ideals}\n\nI did not actually prove that the projective closure $ \\overline{V} $ of $ V \\subseteq \\AA^n $ is a projective algebraic set, because we constructed $ V $ as the zero set of infinitely many homogeneous polynomials, but said that a projective algebraic set must be defined using finitely many homogeneous polynomials. We can prove that these are equivalent using the Hilbert basis theorem, but it is a little more subtle than in the affine case.\n\n\\begin{definition*}\nA \\textbf{homogeneous ideal} in $ k\\sbr{X_0, \\dots, X_n} $ is an ideal which can be generated by homogeneous polynomials.\n\\end{definition*}\n\n\\begin{note*}\nA homogeneous ideal does not contain only homogeneous polynomials, since one can take a homogeneous polynomial $ f $ in the ideal and multiply it by $ X_0 + 1 $ to get a non-homogeneous ideal in $ I $.\n\\end{note*}\n\nIf $ f $ is any polynomial in $ k\\sbr{X_0, \\dots, X_n} $, we can write $ f $, uniquely, as\n$$ f = \\sum_{i = 0}^d f_i, $$\nwhere $ f_i $ is homogeneous of degree $ i $. The $ f_i $ are called the \\textbf{homogeneous components} of $ f $.\n\n\\begin{lemma}\n\\label{lem:homogeneousideal}\nAn ideal $ I \\subseteq k\\sbr{X_0, \\dots, X_n} $ is a homogeneous ideal if and only if, for each $ f \\in I $, every homogeneous component of $ f $ is in $ I $.\n\\end{lemma}\n\n\\begin{proof}\nJust some algebraic manipulation.\n\\end{proof}\n\n\\begin{proposition}\n\\label{prop:homogeneousideal}\nLet $ I \\subseteq k\\sbr{X_0, \\dots, X_n} $ be a homogeneous ideal. Then there exists a finite set $ f_1, \\dots, f_m $ of homogeneous polynomials which generate $ I $.\n\\end{proposition}\n\n\\begin{proof}\nBy the Hilbert basis theorem, there exists a finite set $ g_1, \\dots, g_r $ of polynomials, not necessarily homogeneous, which generate $ I $. In total, the $ g_i $ have finitely many homogeneous components. By Lemma \\ref{lem:homogeneousideal}, all homogeneous components are in $ I $. Clearly they generate $ I $.\n\\end{proof}\n\nThus any set of homogeneous polynomials, even an infinite set, defines a projective algebraic set. We can use Proposition \\ref{prop:homogeneousideal} to prove that every projective algebraic set is a finite union of irreducible components, by the same proof as for affine algebraic sets.\n\n\\subsubsection{The projective Nullstellensatz}\n\n\\lecture{15}{Friday}{14/02/20}\n\nWhich homogeneous ideals can occur as the ideal of functions vanishing on a projective algebraic set? Clearly they have to be radical ideals. Is there a projective version of the Nullstellensatz? Yes, but it turns out that there is an exceptional case to deal with. Consider the homogeneous ideal\n$$ I_1 = \\abr{X_0, \\dots, X_n} \\subseteq k\\sbr{X_0, \\dots, X_n}. $$\nThe only solution in $ k^{n + 1} $ to the equations $ x_0 = 0, \\dots, x_n = 0 $ is $ \\br{0, \\dots, 0} $. But this is not the homogeneous coordinates of any point in $ \\PP^n $. So the projective algebraic set defined by $ I_1 $ is the empty set. Thus the ideals $ I_1 $ and $ k\\sbr{X_0, \\dots, X_n} $ both define the empty set by $ I_1 $ is the empty set. Thus the ideals $ I_1 $ and $ k\\sbr{X_0, \\dots, X_n} $ both define the empty set in $ \\PP^n $, even though they are both radical homogeneous ideals. So we have to modify the statement of the Nullstellensatz slightly from the affine case. Thus turns out to be the only special case.\n\n\\pagebreak\n\n\\begin{proposition}[Projective weak Nullstellensatz]\nLet $ I \\subseteq k\\sbr{X_0, \\dots, X_n} $ be a homogeneous ideal such that $ \\rad I $ is not equal to either $ k\\sbr{X_0, \\dots, X_n} $ or $ I_1 = \\abr{X_0, \\dots, X_n} $. Then the projective algebraic set defined by $ I $ is non-empty.\n\\end{proposition}\n\n\\begin{proof}\nLet $ V \\subseteq \\PP^n $ denote the projective algebraic set defined by $ I $. We can also consider the affine algebraic set $ \\VV\\br{I} \\subseteq \\AA^{n + 1} $ defined by $ I $, which we label $ C $. Since $ \\rad I \\ne k\\sbr{X_0, \\dots, X_n} $ and $ \\rad I \\ne I_1 $, the affine strong Nullstellensatz tells us that $ C $ is not equal to their associated affine algebraic sets, namely $ \\emptyset $ or $ \\cbr{\\br{0, \\dots, 0}} $. Therefore $ C $ contains some point $ \\br{x_0, \\dots, x_n} \\in \\AA^{n + 1} $ other than the origin. But then the point of $ \\PP^n $ with homogeneous coordinates $ \\sbr{x_0 : \\dots : x_n} $ is in $ V $.\n\\end{proof}\n\nWe saw the projective weak Nullstellensatz, and we saw that the radical homogeneous ideal $ \\abr{X_0, \\dots, X_n} $ defines the empty projective algebraic set, the same as $ \\abr{1} $. However, this turns out to be the only exception to the bijection between radical homogeneous ideals and projective algebraic sets.\n\n\\begin{theorem}\nThe map sending a homogeneous ideal to the corresponding projective algebraic set is a bijection between the sets\n$$ \\correspondence{\\text{radical homogeneous ideals in} \\ k\\sbr{X_0, \\dots, X_n} \\\\ \\text{other than} \\ \\abr{X_0, \\dots, X_n}}{\\text{projective algebraic sets in} \\ \\PP^n}. $$\n\\end{theorem}\n\nThe set $ C $ which appears in the above proof is called the \\textbf{affine cone} of $ V $. It is the union of the lines through the origin in $ \\AA^{n + 1} $ which correspond to points of $ V \\subseteq \\PP^n $.\n\n\\begin{proof}\nApply the affine Nullstellensatz to the affine cones of projective algebraic sets in $ \\AA^{n + 1} $ defined by the same ideal.\n\\end{proof}\n\n\\subsubsection{A remark on compactness}\n\nOver the complex numbers, every projective algebraic set is compact in the analytic topology. This is because they are closed subsets of $ \\PP_\\CC^n $, which is compact. In the Zariski topology, the notion of compactness is not very interesting, since every algebraic set is compact in the Zariski topology, even affine algebraic sets. Affine algebraic sets definitely do not behave in ways matching our intuition about compactness, since this intuition and most of the usual theory of compact sets is only valid when the spaces are Hausdorff. There is a converse to this, which tells us that there is a very close relationship between analytic and algebraic geometry in $ \\PP_\\CC^n $.\n\n\\begin{theorem}[Chow's theorem]\n\\label{thm:chowtheorem}\nLet $ V $ be an analytic subset of $ \\PP_\\CC^n $ which is closed in the analytic topology. Then $ V $ is a projective algebraic set.\n\\end{theorem}\n\nI will not define analytic subsets here, but roughly it means a set defined by zeroes of holomorphic functions. Theorem \\ref{thm:chowtheorem} is much harder to prove than to state, and requires too much complex analytic geometry beyond this course to prove here. One can prove analytically that every holomorphic function on a connected compact complex manifold is constant.\n\n\\begin{example*}\nThis holds on the Riemann sphere, which is equal to $ \\PP_\\CC^1 $.\n\\end{example*}\n\nPolynomials are holomorphic, so every regular function on a connected projective algebraic set over $ \\CC $ is constant. Once we define regular functions on projective algebraic sets, it will turn out that the same is true over any field.\n\n\\pagebreak\n\n\\subsection{Regular and rational maps}\n\nIn the affine case, we defined regular functions first and then used them to define regular maps. However, as remarked above the only regular functions on an irreducible projective algebraic set are constants so they are not useful for defining regular maps. Therefore we will jump directly to defining regular maps between projective algebraic sets.\n\n\\subsubsection{Regular maps between projective algebraic sets}\n\nLet $ V \\subseteq \\PP^m $ and $ W \\subseteq \\PP^n $ be projective algebraic sets. We expect a regular map $ \\phi : V \\to W $ to be a function which can be expressed as polynomials in the homogeneous coordinates, so\n$$ \\phi\\br{\\sbr{x_0 : \\dots : x_m}} = \\sbr{f_0\\br{x_0, \\dots, x_m} : \\dots : f_n\\br{x_0, \\dots, x_m}}. $$\nBecause we are working with homogeneous coordinates, in order for this to be a well-defined function, all the $ f_i $ must be homogeneous polynomials of the same degree. Then, if we re-scale the input coordinates $ \\sbr{x_0 : \\dots : x_m} $ by $ \\lambda $, we get\n\\begin{align*}\n\\sbr{f_0\\br{\\lambda x_0, \\dots, \\lambda x_m} : \\dots : f_n\\br{\\lambda x_0, \\dots, \\lambda x_m}}\n& = \\sbr{\\lambda^df_0\\br{x_0, \\dots, x_m} : \\dots : \\lambda^df_n\\br{x_0, \\dots, x_m}} \\\\\n& = \\sbr{f_0\\br{x_0, \\dots, x_m} : \\dots : f_n\\br{x_0, \\dots, x_m}}.\n\\end{align*}\nThus all the output coordinates are multiplied by the same value $ \\lambda^d $, so they define the same point in $ \\PP^n $. There is another condition which must be imposed to get a well-defined function $ V \\to \\PP^m $. We must never have\n$$ f_0\\br{x_0, \\dots, x_m} = \\dots = f_m\\br{x_0, \\dots, x_m} = 0, $$\nbecause $ \\sbr{0 : \\dots : 0} $ is not the homogeneous coordinates of a point in $ \\PP^n $. However it turns out that often, there is not a single sequence of polynomials which will define a regular map at every point of $ V $. Whatever polynomials we try, there might be some points where they all vanish. This is a very strong condition and there are too few lists of polynomials which satisfy it. However, we can get round it to some extent by imitating rational maps between affine algebraic sets, and allowing different sequences of polynomials to represent our regular map at different points of $ V $, so that, at each point, there is some list of polynomials which is always non-zero. It is the homogeneous nature of the coordinates that allows us to do this in such a way that the different sequences of polynomials represent the same regular map at places wherever they overlap. To help explain this, we consider an example.\n\n\\begin{example*}\nLet $ V $ be the projective closure of the parabola, that is\n$$ V = \\cbr{\\sbr{w : x : y} \\in \\PP^2 \\st wy = x^2}. $$\nLet\n$$ V' = V \\cap \\cbr{\\sbr{w : x : y} \\st w \\ne 0} = \\cbr{\\br{x, y} \\in \\AA^2 \\st y = x^2}. $$\nThere is a regular map given by\n$$ \\function[\\phi']{V'}{\\AA^1}{\\br{x, y}}{x}. $$\nDoes this extend to a regular map $ \\phi : V \\to \\PP^1 $? We guess it should send the point at infinity $ \\sbr{0 : 0 : 1} \\in V $ to the point at infinity $ \\sbr{0 : 1} \\in \\PP^1 $. To attempt to construct such a map, write $ \\phi' $ in homogeneous coordinates using the embedding $ \\AA^2 \\hookrightarrow \\PP^2 $, so\n$$ \\function[\\phi']{V'}{\\AA^1}{\\sbr{1 : x : y}}{\\sbr{1 : x}}. $$\nNow we homogenise, that is multiply by powers of the extra coordinate $ w $ to make all the polynomials homogeneous of degree one, so\n$$ \\function[\\phi]{V}{\\PP^1}{\\sbr{w : x : y}}{\\sbr{w : x}}. $$\n\n\\pagebreak\n\nThis maps $ \\sbr{0 : 0 : 1} $ to $ \\sbr{0 : 0} $ which is not allowed. But we can fix this by expressing the same map differently. Using the homogeneous nature of the coordinates, and the equation $ x^2 = wy $ defining $ V $, we have\n$$ \\sbr{w : x} = \\sbr{wx : x^2} = \\sbr{wx : wy} = \\sbr{x : y}, $$\nwhenever the values we multiplied or divided by, $ w $ and $ x $, are non-zero. The expression $ \\sbr{x : y} $ is well-defined at $ \\sbr{0 : 0 : 1} $, with value $ \\sbr{0 : 1} $. On the other hand, $ \\sbr{x : y} $ gives $ \\sbr{0 : 0} $ at the point $ \\sbr{1 : 0 : 0} \\in V $, so we cannot use $ \\sbr{x : y} $ alone to define a map $ V \\to \\PP^1 $. The two expressions together give a well-defined regular map\n$$ \\function[\\phi]{V}{\\PP^1}{\\sbr{w : x : y}}{\n\\begin{cases}\n\\sbr{w : x} & w \\ne 0 \\\\\n\\sbr{x : y} & y \\ne 0\n\\end{cases}\n}. $$\nTo check that this does indeed define a map $ V \\to \\PP^1 $, we have the check the following.\n\\begin{itemize}\n\\item We have defined the map at every point of $ \\PP^1 $. This is true because every point of $ V $ must have to satisfy at least one of $ w \\ne 0 $ or $ y \\ne 0 $, since if $ w = y = 0 $, then the equation $ wy = x^2 $ implies that $ x = 0 $ but $ \\sbr{0 : 0 : 0} $ is not a point of $ \\PP^2 $. Thus at least one of these two expressions is defined everywhere on $ V $.\n\\item On the overlap between the two open sets, both expressions define the same map. This is true because, if $ w $ and $ y $ are both non-zero and $ \\sbr{w : x : y} \\in V $, then $ x $ is also non-zero. We can then see that $ \\sbr{x : y} = \\sbr{w : x} $.\n\\end{itemize}\nIn this example, there is no single sequence of homogeneous polynomials which defines $ \\phi $ everywhere on $ \\PP^1 $. Note that each of these expressions is well-defined on a Zariski open subset of $ V $, since they are made up of homogeneous polynomials of the same degree, and they never give a point with homogeneous coordinates $ \\sbr{0 : 0} $ within the specified open sets. This is important because it is how we ensure that the value of $ \\phi $ at each point is polynomially related to its value at nearby points. Open sets are the natural way to talk about nearby points in a topological space. This still applies in the Zariski topology, even though open sets are very big.\n\\end{example*}\n\n\\begin{note*}\nQuestions $ 5 $ and $ 6 $ on problem sheet $ 2 $ give examples of regular maps defined everywhere except at a single point of an affine algebraic set, where there is an obvious value the map should take at the missing point, but the map is not regular at that point because there is no way to extend it to that point using polynomials. This is why we are not allowed just to write down polynomials on arbitrary non-open subsets of $ V $ and claim they define a regular map.\n\\end{note*}\n\nTherefore, a regular map is defined to be a map which can be represented by some homogeneous polynomials at every point of $ V $. It is not enough just to say that for each point $ x \\in V $, there exist some polynomials which give the correct value at $ x $, because then we could get every set-theoretic map by choosing different polynomials at different points. To relate the values of the map at different points, we require that there is some list of polynomials which defines the map on an open neighbourhood of $ x $. The formal definition of a regular map between projective algebraic sets $ V \\subseteq \\PP^m $ and $ W \\subseteq \\PP^n $ is the following.\n\n\\begin{definition*}\nA \\textbf{regular map} $ \\phi : V \\to W $ is a function $ V \\to W $ such that for every point $ x \\in V $, there exist a Zariski open set $ U \\subseteq V $ containing $ x $ and a sequence of polynomials $ f_0, \\dots, f_n \\in k\\sbr{X_0, \\dots, X_m} $ such that,\n\\begin{itemize}\n\\item $ f_0, \\dots, f_n $ are homogeneous of the same degree,\n\\item for every $ y \\in U $, $ f_0, \\dots, f_n $ are not all zero at $ y $, and\n\\item for every $ y = \\sbr{y_0 : \\dots : y_m} \\in U $, $ \\phi\\br{y} = \\sbr{f_0\\br{y_0, \\dots, y_m} : \\dots : f_n\\br{y_0, \\dots, y_m}} $.\n\\end{itemize}\n\\end{definition*}\n\nIn practice, every regular map can be written down by specifying lists of polynomials on just finitely many open sets, like $ \\phi $. This follows ultimately from the Hilbert basis theorem. To check that a purported definition like $ \\phi $ really does define a regular map $ V \\to W $, you have to check\n\n\\pagebreak\n\n\\begin{itemize}\n\\item each set on which an expression is defined is Zariski open,\n\\item an expression never gives $ \\sbr{0 : \\dots : 0} $ on its associated set,\n\\item two expressions agree wherever they are both defined, and\n\\item the image of the map is contained in $ W $.\n\\end{itemize}\n\n\\begin{example*}\nAs another example, taking $ V $ and $ V' $ as in the previous example, let us try to extend the inverse of $ \\phi $ from affine to projective algebraic sets. On affine algebraic sets, the inverse of $ \\phi' $ is given by\n$$ \\function[\\psi']{\\AA^1}{V'}{t}{\\br{t, t^2}}. $$\nIn projective coordinates, this is\n$$ \\function[\\psi']{\\AA^1}{V'}{\\sbr{1 : t}}{\\sbr{1 : t : t^2}}. $$\nHomogenising, by inserting powers of $ s $ to make all the polynomials on right hand side degree two, we get\n$$ \\function[\\psi]{\\PP^1}{V}{\\sbr{s : t}}{\\sbr{s^2 : st : t^2}}. $$\nNow recalling that $ s $ and $ t $ cannot both be zero at the same point, $ s^2, st, t^2 $ are never simultaneously zero for $ \\sbr{s : t} \\in \\PP^1 $, so in this case the single expression $ \\sbr{s^2 : st : t^2} $ is enough to define a regular map $ \\psi : \\PP^1 \\to V $ everywhere on $ \\PP^1 $. Note that the image of $ \\phi $ is indeed contained in $ V $.\n\\end{example*}\n\n\\begin{note*}\nThis homogenisation procedure often allows us to extend a regular map between affine algebraic sets into a regular map between their projective closures, but it does not always work. Sometimes there are regular maps between affine algebraic sets which it is impossible to extend to regular maps between their projective closures, since there are points for which it is impossible to avoid sending them to $ \\sbr{0 : \\dots : 0} $, or we might find that the homogeneous polynomials\ninvolved become simultaneously zero at some point at infinity.\n\\end{note*}\n\n\\lecture{16}{Monday}{17/02/20}\n\n\\begin{definition*}\nA regular map $ \\phi : V \\to W $ between projective algebraic sets is an \\textbf{isomorphism} if there exists a regular map $ \\psi : W \\to V $ such that $ \\phi \\circ \\psi = \\id_W $ and $ \\psi \\circ \\phi = \\id_V $.\n\\end{definition*}\n\nObserve that the two maps $ \\phi : V \\to \\PP^1 $ and $ \\psi : \\PP^1 \\to V $ which we just defined are inverses, so we conclude that the projective parabola $ V $ is isomorphic to $ \\PP^1 $. We already remarked that the projective parabola is isomorphic to the projective hyperbola\n$$ H = \\cbr{\\sbr{w : x : y} \\in \\PP^2 \\st xy = w^2}, $$\nby relabelling coordinates, so we deduce that the projective hyperbola is also isomorphic to $ \\PP^1 $. In fact, we can show that all irreducible \\textbf{conics} in $ \\PP^2 $, subsets of $ \\PP^2 $ defined by a homogeneous polynomial of degree two, are isomorphic to $ \\PP^1 $, by using a projection as in problem $ 5 $ on problem sheet $ 2 $, and checking that in the projective setting, in this case, the projection gives regular maps and not just rational ones.\n\n\\subsubsection{Regular maps equal on a dense subset}\n\nWe already proved and made use of the following lemma previously for regular maps between affine algebraic sets. It is even more useful for regular maps between projective algebraic sets as it tells us that we only need to test equality between regular maps on a dense subset, since we will need it in the definition of rational maps.\n\n\\begin{lemma}\n\\label{lem:projectivedense}\nLet $ \\phi, \\psi : V \\to W $ be regular maps. If there exists a Zariski dense subset $ A \\subseteq V $ such that $ \\eval{\\phi}_A = \\eval{\\psi}_A $, then $ \\phi = \\psi $.\n\\end{lemma}\n\n\\begin{example*}\nLemma \\ref{lem:projectivedense} is especially useful if $ V $ is irreducible, because then Zariski open subsets of $ V $ are dense. So Lemma \\ref{lem:projectivedense} tells us that, given a list of polynomials on a Zariski open subset of $ V $, there is at most one regular map which is given by that list of polynomials on that set, then it is sufficient to look at the open set where a single expression for the regular map is defined.\n\\end{example*}\n\n\\pagebreak\n\nWe will use the following topological fact.\n\n\\begin{fact*}\nLet $ S $ be any topological space, not necessarily Hausdorff. Let $ \\cbr{U_\\alpha} $ be a collection of open subsets of $ S $, whose union is all of $ S $. Let $ Z $ be any subset of $ S $ such that $ Z \\cap U_\\alpha $ is closed in the subspace topology on $ U_\\alpha $ for every $ \\alpha $. Then $ Z $ is closed as a subset of $ S $.\n\\end{fact*}\n\n\\begin{proof}\nLet\n$$ Z = \\cbr{x \\in V \\st \\phi\\br{x} = \\psi\\br{x}}. $$\nBy hypothesis, $ Z $ contains a dense subset of $ V $. Hence in order to show that $ Z = V $, it suffices to show that $ Z $ is closed in $ V $. From the definition of regular maps, we know that we can cover $ V $ by Zariski open sets $ U_\\alpha $ such that on each $ U_\\alpha $, both $ \\phi $ and $ \\psi $ are defined by sequences of homogeneous polynomials, so\n$$ \\eval{\\phi}_{U_\\alpha} = \\sbr{f_{\\alpha, 0} : \\dots : f_{\\alpha, m}}, \\qquad \\eval{\\psi}_{U_\\alpha} = \\sbr{g_{\\alpha, 0} : \\dots : g_{\\alpha, m}}. $$\nBy the general topological fact, it suffices to show that $ Z \\cap U_\\alpha $ is relatively closed in the subspace topology on $ U_\\alpha $ for every $ \\alpha $. Now\n$$ Z \\cap U_\\alpha = \\cbr{x \\in U_\\alpha \\st \\sbr{f_{\\alpha, 0}\\br{x} : \\dots : f_{\\alpha, m}\\br{x}} = \\sbr{g_{\\alpha, 0}\\br{x} : \\dots : g_{\\alpha, m}\\br{x}}}. $$\nThis is the same as the set of $ x \\in U_\\alpha $ where the vectors $ \\br{f_{\\alpha, 0}\\br{x}, \\dots, f_{\\alpha, m}\\br{x}} $ and $ \\br{g_{\\alpha, 0}\\br{x}, \\dots, g_{\\alpha, m}\\br{x}} $ are proportional, for any choice of homogeneous coordinates for $ x $, or in other words where the matrix\n$$ \\twobyone{f_{\\alpha, 0}\\br{x} \\qquad \\dots \\qquad f_{\\alpha, m}\\br{x}}{g_{\\alpha, 0}\\br{x} \\qquad \\dots \\qquad g_{\\alpha, m}\\br{x}} $$\nhas rank one. A little linear algebra shows that this condition is equivalent to all the $ 2 \\times 2 $ minors of this matrix vanishing, that is\n$$ f_{\\alpha, i}\\br{x}g_{\\alpha, j}\\br{x} - f_{\\alpha, j}\\br{x}g_{\\alpha, i}\\br{x} = 0, \\qquad i, j \\in \\cbr{0, \\dots, m}. $$\nThis last condition is given by homogeneous polynomials, and therefore defines a closed subset in the subspace topology on $ U_\\alpha $.\n\\end{proof}\n\n\\subsubsection{Quasi-projective algebraic sets}\n\nSo far, we have defined affine algebraic sets and projective algebraic sets, as separate types of objects. It is very convenient to have a single notion that unifies both affine and projective algebraic sets, for example to save us from having to prove a lemma for affine algebraic sets, then the same lemma for projective algebraic sets.\n\n\\begin{definition*}\nA \\textbf{quasi-projective algebraic set} is the intersection between an open subset and a closed subset of $ \\PP^n $, in the Zariski topology.\n\\end{definition*}\n\nA projective algebraic set is quasi-projective, by just taking the open subset to be $ \\PP^n $ itself. An affine algebraic set $ V $ is also quasi-projective, since it is the intersection between $ \\AA^n $, which is open in $ \\PP^n $, and the projective closure $ \\overline{V} $. There are other quasi-projective algebraic sets, for example $ \\AA^1 \\setminus \\cbr{0} $ which is an open subset of $ \\PP^1 $. We define a regular map between quasi-projective algebraic sets by the same definition as a regular map between projective algebraic sets, so it is a map which has a well-defined expression by homogeneous polynomials on a neighbourhood of every point. If $ V $ and $ W $ are affine algebraic sets, we now have two ways to define regular maps $ V \\to W $.\n\\begin{itemize}\n\\item The original definition of regular maps between affine algebraic sets.\n\\item View $ V $ and $ W $ as quasi-projective algebraic sets, and use the new definition of regular maps between quasi-projective algebraic sets.\n\\end{itemize}\nFortunately, these two definitions turn out to be equivalent. One has to do a bit of work to check this. The problem is that a regular map of affine algebraic sets must be defined by the same list of polynomials at every point, but a regular map of quasi-projective algebraic sets may be defined by different polynomials at every point. Proving that actually one list of polynomials is enough if the set happens to be affine is similar to the proof of Lemma \\ref{lem:rationalregular}. This gives us for free a notion of regular maps from a projective algebraic set to an affine algebraic set or vice versa. Just view them both as quasi-projective algebraic sets.\n\n\\pagebreak\n\n\\begin{example*}\nWe can now define a regular function on a projective algebraic set $ V $ to be a regular map $ V \\to \\AA^1 $, thus it is a function from the algebraic set $ V $ taking values in the base field $ k $. As remarked last lecture, we will later prove that the only regular functions on a projective algebraic set are the constants.\n\\end{example*}\n\n\\begin{example*}\nWe can now make rigorous the claim that $ \\AA^1 \\setminus \\cbr{0} $ looks the same as the affine hyperbola\n$$ H = \\cbr{\\br{x, y} \\in \\AA^2 \\st xy = 1}. $$\nThe set $ \\AA^1 \\setminus \\cbr{0} = \\PP^1 \\setminus \\cbr{\\sbr{1 : 0}, \\sbr{0 : 1}} $ is a Zariski open subset of $ \\PP^1 $, because its complement is finite. Hence $ \\AA^1 \\setminus \\cbr{0} $ is a quasi-projective algebraic set. The map\n$$ \\function[\\phi]{\\AA^1 \\setminus \\cbr{0}}{H}{t}{\\dfrac{1}{t}} $$\ncan be written in homogeneous coordinates as\n$$ \\function[\\phi]{\\AA^1 \\setminus \\cbr{0}}{H}{\\sbr{1 : t}}{\\sbr{1 : t : \\dfrac{1}{t}} = \\sbr{t : t^2 : 1}}, $$\nso homogenising, we get\n$$ \\function[\\phi]{\\AA^1 \\setminus \\cbr{0}}{H}{\\sbr{s : t}}{\\sbr{st : t^2 : s^2}}. $$\nSo long as $ \\sbr{s : t} \\in \\AA^1 \\setminus \\cbr{0} $, this does give a point in\n$$ H = \\cbr{\\sbr{w : x : y} \\in \\PP^2 \\st xy = w^2} \\cap \\AA^2, $$\nso $ \\phi $ is a regular map $ \\AA^1 \\setminus \\cbr{0} \\to H $. The projection $ \\br{x, y} \\mapsto x $ is a regular inverse to $ \\phi $. Hence $ \\AA^1 \\setminus \\cbr{0} $ and $ H $ are isomorphic as quasi-projective algebraic sets.\n\\end{example*}\n\n\\subsubsection{Varieties}\n\nAs mentioned previously, we use the word \\textbf{variety} to mean an algebraic set considered up to isomorphism, not caring about how it is embedded into affine or projective space.\n\n\\begin{example*}\n$ \\AA^1 \\setminus \\cbr{0} $ is isomorphic, as a quasi-projective algebraic set, to the affine algebraic set $ H $, so we may say that $ \\AA^1 \\setminus \\cbr{0} $ is an affine variety, even though $ \\AA^1 \\setminus \\cbr{0} $ is definitely not an affine algebraic set.\n\\end{example*}\n\nThere exist quasi-projective algebraic sets which are not isomorphic to anything either projective or affine.\n\n\\begin{example*}\n$ \\AA^2 \\setminus \\cbr{\\br{0, 0}} $. See problem sheet $ 3 $.\n\\end{example*}\n\n\\subsubsection{Rational maps between quasi-projective algebraic sets}\n\nLet $ V \\subseteq \\PP^m $ and $ W \\subseteq \\PP^n $ be irreducible quasi-projective algebraic sets. The formal definition of a rational map $ V \\dashrightarrow W $ looks quite complicated, but the underlying idea is the same as for regular maps. Just like for affine algebraic sets, a rational map is something which is almost a regular map, except that it is allowed to have some points where it is not defined. Rational maps of affine algebraic sets were non-regular at points where the denominator was zero. For quasi-projective algebraic sets, they are non-regular at points where the coordinates of the image become $ \\sbr{0 : \\dots : 0} $.\n\n\\begin{note*}\nUnlike for affine sets, there is no need to use fractions of polynomials in the definition of rational maps between quasi-projective algebraic sets. Because our coordinates are homogeneous, we can always multiply up by a common denominator and get an expression involving only polynomials.\n\\end{note*}\n\nOnce again, somehow we have to make a definition which takes account of the fact that rational maps can be expressed in terms of different lists of polynomials at different points, and it might be necessary to use more than one expression to see the full domain of definition of the rational map. But unlike with regular maps of projective algebraic sets, we cannot tie the different expressions together into a single object by saying a rational map is a function $ V \\to W $, because a rational map is not a function $ V \\to W $. Instead we define rational maps as equivalence classes for a certain equivalence relation.\n\n\\pagebreak\n\n\\begin{note*}\nBefore defining rational maps as equivalence classes, let us ask, why is that a sensible thing to do? Thinking back to the definition of rational functions on an affine variety $ V $, this happens under the hood in defining rational functions on affine varieties too. They are defined as the elements of the field of fractions of $ k\\sbr{V} $. The field of fractions of an integral domain $ R $ is defined as a set of equivalence classes, namely, you take the set $ \\cbr{\\br{a, b} \\in R^2 \\st b \\ne 0} $, and the equivalence relation $ \\br{a, b} \\sim \\br{c, d} $ if $ ad = bc $. The field of fractions of $ R $ is defined to be the set of equivalence classes for this relation. But normally we do not think of fractions as equivalence classes. We just write down one representative, with the special notation $ a / b $, and then manipulate it by the normal rules for manipulating fractions. In the ring $ R = \\ZZ $, then often it may make sense to reduce fractions to lowest terms representatives, and if we impose the condition $ b > 0 $, then every fraction has a unique lowest terms representative. But if $ R $ is not a UFD, then we do not have special lowest terms representatives for fractions. This matches the fact that we might need different expressions to define a rational map at different points.\n\\end{note*}\n\nSo our definition begins by saying which sequences of polynomials determine rational maps, and then specifies when two sequences of polynomials determine the same rational map.\n\n\\begin{definition*}\nA \\textbf{rational map} $ \\phi : V \\dashrightarrow \\PP^n $ is defined by a sequence of homogeneous polynomials $ f_0, \\dots, f_n \\in k\\sbr{X_0, \\dots, X_m} $ of the same degree such that $ f_0, \\dots, f_n $ are not identically zero on $ V $. We write this as $ \\phi = \\sbr{f_0 : \\dots : f_n} $. Two sequences of polynomials $ \\sbr{f_0 : \\dots : f_n} $ and $ \\sbr{g_0 : \\dots : g_n} $ represent the same rational map if the homogeneous coordinates $ \\sbr{f_0\\br{x} : \\dots : f_n\\br{x}} $ and $ \\sbr{g_0\\br{x} : \\dots : g_n\\br{x}} $ represent the same point in $ \\PP^n $ wherever both expressions make sense. Using the fact that $ V $ is irreducible, we can check that this is an equivalence relation on sequences of homogeneous polynomials.\n\\end{definition*}\n\nThis is exactly the same as the definition of a regular map $ V \\to \\PP^n $, except that we are allowing there to be points where no expression for the map is defined. Now we define rational maps $ V \\dashrightarrow W $, where $ W \\subseteq \\PP^n $ is any quasi-projective algebraic set. The definition is mostly what you would expect. A rational map is determined by a sequence of homogeneous polynomials $ \\sbr{f_0 : \\dots : f_n} $. There are points where these polynomials are allowed to be all zero, but they cannot be all zero everywhere on $ V $ so that the rational map is defined somewhere. When we say that the rational map goes into $ W $ instead of into $ \\PP^n $, we require there to be a Zariski dense set $ A \\subseteq V $ on which $ \\sbr{f_0\\br{x} : \\dots : f_n\\br{x}} $ lies in $ W $, but we do not require $ \\sbr{f_0\\br{x} : \\dots : f_n\\br{x}} \\in W $ at every point of $ V $. This is the difference between regular and rational maps.\n\n\\begin{definition*}\nLet $ V \\subseteq \\PP^m $ and $ W \\subseteq \\PP^n $ be irreducible quasi-projective algebraic sets. Let $ S $ denote the set of sequences $ \\br{f_0, \\dots, f_n} \\in k\\sbr{X_0, \\dots, X_m}^{n + 1} $ such that,\n\\begin{itemize}\n\\item $ f_0, \\dots, f_n $ are homogeneous of the same degree,\n\\item $ f_0, \\dots, f_n $ are not all identically zero on $ V $, noting that this looks a little like the $ b \\ne 0 $ condition in defining the field of fractions, and\n\\item there exists a non-empty Zariski dense open set $ A \\subseteq V $ such that, for all $ x \\in A $, the homogeneous coordinates $ \\sbr{f_0\\br{x} : \\dots : f_n\\br{x}} $ make sense and define a point in $ W $.\n\\end{itemize}\nDefine an equivalence relation $ \\sim $ on $ S $ by,\n$$ \\br{f_0, \\dots, f_n} \\sim \\br{g_0, \\dots, g_n} \\qquad \\iff \\qquad \\sbr{f_0\\br{x} : \\dots : f_n\\br{x}} = \\sbr{g_0\\br{x} : \\dots : g_n\\br{x}} \\in \\PP^n, $$\nfor all $ x \\in V $ where both expressions make sense. We could write this more algebraically as,\n$$ \\br{f_0, \\dots, f_n} \\sim \\br{g_0, \\dots, g_n} \\qquad \\iff \\qquad f_ig_j = f_jg_i, \\qquad i, j \\in \\cbr{0, \\dots, n}. $$\nHaving defined $ S $ and $ \\sim $, we then define a \\textbf{rational map} $ \\phi : V \\dashrightarrow W $ to be an equivalence class in $ S $ for $ \\sim $.\n\\end{definition*}\n\nThese two definitions of $ S $ and $ \\sim $ are more formal ways of writing the two parts of the definition of a rational map. Observe that this resembles the equivalence relation used in defining the field of fractions. One needs to check that $ \\sim $ really is an equivalence relation. This is a detail which was hidden in my informal statement of the definition. This uses the fact that $ V $ is irreducible and Lemma \\ref{lem:projectivedense} that if two polynomials are equal on a Zariski dense set, then they are equal everywhere. Just as with fractions, we usually just write down a single representative for a rational map. There is a special notation for representatives of rational maps in $ S $, namely $ \\sbr{f_0 : \\dots : f_n} $. We have seen examples on problem sheets of UFD-like situations where one can choose a lowest terms representative for the rational map, but this is not always possible.\n\n\\lecture{17}{Thursday}{20/02/20}\n\nLecture 17 is a problems class.\n\n\\pagebreak\n\n\\subsubsection{Domain of definition of rational maps}\n\n\\lecture{18}{Friday}{21/02/20}\n\n\\begin{definition*}\nA rational map $ \\phi : V \\to W $ is \\textbf{regular} at a point $ x \\in V $ if there exists at least one list of polynomials $ \\br{f_0, \\dots, f_n} \\in S $ representing $ \\phi $ such that $ \\sbr{f_0\\br{x} : \\dots : f_n\\br{x}} \\ne \\sbr{0 : \\dots : 0} $ and $ \\sbr{f_0\\br{x} : \\dots : f_n\\br{x}} \\in W $. If $ \\phi $ is regular at $ x \\in V $, then the equivalence relation $ \\sim $ ensures that the value $ \\phi\\br{x} \\in W $ makes sense and is well-defined, with homogeneous coordinates given by $ \\sbr{f_0\\br{x} : \\dots : f_n\\br{x}} $. This point is independent of the choice of polynomials representing $ \\phi $, as well as independent of the choice of homogeneous coordinates for $ x $. Just as for affine algebraic sets, we define the \\textbf{domain of definition} of a rational map to be the set of points where it is regular, the union of the sets where each representative of the equivalence class makes sense as a map.\n\\end{definition*}\n\n\\begin{note*}\nJust as in the affine case, when checking whether $ \\phi $ is regular at a point $ x $, it is not enough to check whether the representation $ \\sbr{f_0 : \\dots : f_n} $ which we first used to define the map is regular at $ x $. We have to check whether there exists any representation $ \\sbr{g_0 : \\dots : g_n} $ for $ \\phi $ which is defined at $ x $.\n\\end{note*}\n\n\\begin{note*}\nFurthermore, the domain of definition of a rational map can change if we change the target set $ W $.\n\\end{note*}\n\n\\begin{example*}\nConsider the map defined by\n$$ \\function{\\PP^1}{\\PP^2}{\\sbr{s : t}}{\\sbr{s^2 : st : t^2}}. $$\nThis is regular at every point. We could interpret the same formula as defining a rational map $ \\PP^1 \\dashrightarrow W $ where $ W \\subseteq \\PP^2 $ is the open set $ W = \\cbr{\\sbr{w : x : y} \\st w \\ne 0} $. As a rational map $ \\PP^1 \\dashrightarrow W $, this is not regular at the point $ \\sbr{0 : 1} $ because this point maps to $ \\sbr{0 : 0 : 1} \\notin W $.\n\\end{example*}\n\n\\begin{lemma}\nLet $ \\phi : V \\dashrightarrow W $ be a rational map. The domain of definition of $ \\phi $ is a non-empty Zariski open subset of $ V $.\n\\end{lemma}\n\n\\begin{proof}\nSimilar to the affine case, in Lemma \\ref{lem:domaindefinition}.\n\\end{proof}\n\nIt follows immediately from the definition of regular maps between quasi-projective algebraic sets that if a rational map is regular at every point, then it is a regular map. In the affine case, in Lemma \\ref{lem:rationalregular}, we had to work to prove that if a rational map is regular at every point, then there is a single polynomial expression which defines the map everywhere. In the quasi-projective case, we do not need to do this because our definition of regular map allows different expressions at different points.\n\n\\begin{example*}\nLet $ C $ denote the affine algebraic set\n$$ C = \\cbr{\\br{x, y} \\in \\AA^2 \\st y = x^3}. $$\nThis has projective closure\n$$ \\overline{C} = \\cbr{\\sbr{w : x : y} \\in \\PP^2 \\st w^2y = x^3} = C \\cup \\cbr{\\sbr{0 : 0 : 1}}. $$\nConsider the regular map of affine algebraic sets given by\n$$ \\function[\\phi]{C}{\\AA^1}{\\br{x, y}}{x}. $$\nIf we try to extend this to a map of projective algebraic sets $ \\overline{\\phi} : \\overline{C} \\to \\PP^1 $, we would say that for points $ \\sbr{1 : x : y} \\in C \\subseteq \\overline{C} $,\n$$ \\function[\\phi]{C}{\\AA^1}{\\br{\\sbr{1 : x : y}}}{\\sbr{1 : x}}, $$\nand this homogenises to\n$$ \\rational[\\overline{\\phi}]{\\overline{C}}{\\PP^1}{\\br{\\sbr{w : x : y}}}{\\sbr{w : x}}. $$\nThus $ \\overline{\\phi} $ is a rational map $ \\overline{C} \\dashrightarrow \\PP^1 $. The above expression for $ \\overline{\\phi} $ is not defined at the point $ \\sbr{0 : 0 : 1} \\in \\overline{C} $. We can prove that there is no other expression for $ \\overline{\\phi} $ which is defined at that point, and so $ \\overline{\\phi} $ is not regular at $ \\sbr{0 : 0 : 1} $. See problem sheet $ 3 $, question $ 3 $.\n\\end{example*}\n\nThus a regular map of affine algebraic sets extends to a rational map between their projective closures, but the extended map is not necessarily regular at the points at infinity.\n\n\\pagebreak\n\n\\subsubsection{Birational maps}\n\nJust as in the affine case, if we have irreducible quasi-projective sets $ V, W, T $ and rational maps $ \\phi : V \\dashrightarrow W $ and $ \\psi : W \\dashrightarrow T $, if the image of $ \\phi $ is dense in $ W $, then the composite $ \\psi \\circ \\phi $ is a rational map $ V \\dashrightarrow T $. The following definitions are the same as the affine case.\n\n\\begin{definition*}\nA rational map $ \\phi : V \\dashrightarrow W $ is \\textbf{dominant} if its image is dense in $ W $. A rational map $ \\phi : V \\dashrightarrow W $ is a \\textbf{birational equivalence} if it is dominant and there exists a dominant rational map $ \\psi : W \\dashrightarrow V $ such that $ \\psi \\circ \\phi = \\id_V $ and $ \\phi \\circ \\psi = \\id_W $, where these composite rational maps are defined. Irreducible algebraic sets $ V $ and $ W $ are \\textbf{birational} if there exists a birational equivalence $ V \\dashrightarrow W $.\n\\end{definition*}\n\n\\begin{note*}\n$ \\AA^n $ is birational to $ \\PP^n $. Consider the regular map\n$$ \\function[\\phi]{\\AA^n}{\\PP^n}{\\br{x_1, \\dots, x_n}}{\\sbr{1 : x_1 : \\dots : x_n}}, $$\nand the rational map\n$$ \\rational[\\psi]{\\PP^n}{\\AA^n}{\\sbr{x_0 : \\dots : x_n}}{\\br{\\dfrac{x_1}{x_0}, \\dots, \\dfrac{x_n}{x_0}}}. $$\nEach of these is dominant and composing them in either direction gives the identity, so these are birational equivalences. Observe that $ \\phi $ is an isomorphism from $ \\AA^n $ to an open subset of $ \\PP^n $.\n\\end{note*}\n\nWe can generalise this to show that if $ V $ is any irreducible quasi-projective variety and $ U $ is a Zariski open subset of $ V $, thus $ U $ is also an irreducible quasi-projective variety, then $ U $ is birational to $ V $. Indeed, this is a corollary of the following stronger result, which makes precise the intuition that varieties are birational if and only if they are the same almost everywhere.\n\n\\begin{note*}\nWe need the concept of quasi-projective varieties to state this lemma, even if $ V $ and $ W $ are both affine or both projective, because it is necessary to interpret the statement that $ A $ and $ B $ are isomorphic.\n\\end{note*}\n\n\\begin{lemma}\nIrreducible quasi-projective varieties $ V $ and $ W $ are birational if and only if there exist non-empty Zariski open subsets $ A \\subseteq V $ and $ B \\subseteq W $ such that $ A $ is isomorphic to $ B $, as quasi-projective varieties.\n\\end{lemma}\n\n\\begin{proof}\nLet $ \\phi : V \\dashrightarrow W $ and $ \\psi : W \\dashrightarrow V $ be an inverse pair of rational maps. Let $ A_1 = \\dom \\phi $ and $ B_1 = \\dom \\psi $. Then $ B_1 $ is a non-empty open subset of $ W $. Since $ \\phi $ induces a continuous map $ A_1 \\to W $, $ A = \\eval{\\phi}_{A_1}^{-1}\\br{B_1} $ is an open subset of $ V $. Furthermore, since $ \\phi $ is dominant, its image intersects the open set $ B_1 \\subseteq W $. Therefore $ A $ is non-empty. Similarly $ B = \\eval{\\psi}_{B_1}^{-1}\\br{A_1} $ is a non-empty open subset of $ W $. One can now check that $ \\eval{\\phi}_A $ and $ \\eval{\\psi}_B $ form an inverse pair of isomorphisms between $ A $ and $ B $.\n\\end{proof}\n\nIf $ V $ is a quasi-projective algebraic set, we define a \\textbf{rational function} on $ V $ to be a rational map $ \\phi : V \\dashrightarrow \\AA^1 $. By definition, this is the same as a rational map $ \\phi' : V \\dashrightarrow \\PP^1 $ except that we declare $ \\phi $ to be non-regular at points where $ \\phi'\\br{x} = \\infty = \\sbr{0 : 1} \\in \\PP^1 $. We can therefore say\n$$ \\phi\\br{x} = \\sbr{f\\br{x} : g\\br{x}} = \\sbr{1 : \\dfrac{g\\br{x}}{f\\br{x}}} = \\dfrac{g\\br{x}}{f\\br{x}} \\in \\AA^1, $$\nwhenever $ f\\br{x} \\ne 0 $, for suitable polynomials $ f $ and $ g $. Of course, as always with rational maps, we might need to use different polynomials to evaluate it at different points. The rational functions on $ V $ form a field $ k\\br{V} $. Just as in the affine case, $ V $ is birational to $ W $ if and only if $ k\\br{V} $ is $ k $-isomorphic to $ k\\br{W} $. This allows us to calculate\n$$ k\\br{\\PP^n} = k\\br{\\AA^n} = k\\br{X_1, \\dots, X_n}. $$\n\n\\pagebreak\n\n\\subsection{Rigidity and images of maps}\n\n\\subsubsection{Linear spaces in projective space}\n\nWe want to define a fundamental example of a rational map, the projection from a point to a hyperplane. First, we need to make a few other definitions.\n\n\\begin{definition*}\nA \\textbf{hyperplane} in $ \\PP^n $ is the projective algebraic set defined by a single homogeneous linear equation,\n$$ H = \\cbr{\\sbr{x_0 : \\dots : x_n} \\in \\PP^n \\st h_0x_0 + \\dots + h_nx_n = 0}, $$\nfor some $ h_0, \\dots, h_n \\in k $, not all zero. More generally, a \\textbf{linear subspace} of $ \\PP^n $ is a subset defined by any set of homogeneous linear equations.\n\\end{definition*}\n\n\\begin{example*}\nExamples of linear subspaces are $ \\PP^n $ itself with the empty set of equations, $ \\emptyset $ with too many equations, and singletons. We cannot define the singleton $ \\cbr{\\sbr{p_0 : \\dots : p_n}} $ by the equations $ x_0 = p_0, \\dots, x_n = p_n $ because these are not homogeneous. Instead, we can write homogeneous equations asserting that the ratios between pairs of coordinates are correct, so\n$$ \\cbr{\\sbr{p_0 : \\dots : p_n}} = \\cbr{\\sbr{x_0 : \\dots : x_n} \\in \\PP^n \\st \\forall i, j, \\ p_ix_j = p_jx_i}. $$\n\\end{example*}\n\nIf $ \\Lambda $ is a linear subspace of $ \\PP^n $, then the affine cone $ \\C\\br{\\Lambda} $, the set of points in $ \\AA^{n + 1} $ satisfying the same equations as $ \\Lambda $, is a vector subspace of $ k^{n + 1} $. As a vector space, we know what is meant by $ \\dim \\C\\br{\\Lambda} $. We define\n$$ \\dim \\Lambda = \\dim \\C\\br{\\Lambda} - 1. $$\nWe have not yet defined the dimension of an arbitrary algebraic set. This definition is only for linear subspaces of projective space. The $ -1 $ is because $ \\C\\br{\\Lambda} $ contains a line for each point in $ \\Lambda $.\n\n\\begin{example*}\n$ \\PP^n $ has dimension $ n $, a hyperplane has dimension $ n - 1 $, and a point has dimension zero.\n\\end{example*}\n\nIf $ \\Lambda $ is a linear subspace of $ \\PP^n $ of dimension $ d $, then $ \\C\\br{\\Lambda} \\cong k^{d + 1} $, as a vector space, and\n$$ \\Lambda = \\br{\\C\\br{\\Lambda} \\setminus \\cbr{0}} / \\text{scalars} \\cong \\PP^d. $$\n\n\\begin{definition*}\nA \\textbf{line} in $ \\PP^n $ is a linear subspace of dimension one.\n\\end{definition*}\n\n\\lecture{19}{Monday}{24/02/20}\n\n\\begin{lemma}\nFor any two distinct points $ p, q \\in \\PP^n $, there exists a unique line $ \\L_{pq} $ through $ p $ and $ q $.\n\\end{lemma}\n\nOne could prove this by saying, $ \\PP^n $ can be written as a union $ \\AA^n \\cup \\PP^{n - 1} $, and going through the cases $ p, q \\in \\AA^n $, $ p, q \\in \\PP^{n - 1} $, and $ p \\in \\AA^n $ and $ q \\in \\PP^{n - 1} $. In order to make this into a full proof, we would need to check that a line in $ \\PP^n $, intersected with $ \\AA^n $, is the same as the ordinary definition of a line in $ \\AA^n $, which is true. Instead we shall give a proof using linear algebra. A benefit of this proof is that it gives a description of the homogeneous coordinates of points in the line $ \\L_{pq} $.\n\n\\begin{proof}\nLet $ p = \\sbr{p_0 : \\dots : p_n} $ and $ q = \\sbr{q_0 : \\dots : q_n} $. The affine cones $ \\C\\br{p} $ and $ \\C\\br{q} $ are the one-dimensional vector spaces of generated by $ \\br{p_0, \\dots, p_n} $ and $ \\br{q_0, \\dots, q_n} $ respectively. Since $ p \\ne q $, these vector spaces are linearly independent so there is a unique two-dimensional vector subspace $ W \\subseteq k^{n + 1} $ which contains $ \\C\\br{p} $ and $ \\C\\br{q} $. The image of $ W \\setminus \\cbr{0} $ in $ \\PP^n $ is the unique line through $ p $ and $ q $. Explicitly, $ W $ consists of all linear combinations of the vectors $ \\br{p_0, \\dots, p_n} $ and $ \\br{q_0, \\dots, q_n} $. It follows that\n$$ \\L_{pq} = \\cbr{\\sbr{p_0s + q_0t : \\dots : p_ns + q_nt} \\in \\PP^n \\st \\sbr{s : t} \\in \\PP^1}. $$\n\\end{proof}\n\n\\subsubsection{Projections of projective algebraic sets}\n\nA fundamental example of a rational map is the projection from a point to a hyperplane. Let $ p = \\sbr{p_0 : \\dots : p_n} \\in \\PP^n $ and let $ H \\subseteq \\PP^n $ be a hyperplane such that $ p \\notin H $. To simplify the calculations, we shall assume that\n$$ H = \\cbr{\\sbr{x_0 : \\dots : x_n} \\in \\PP^n \\st x_n = 0}. $$\n\n\\pagebreak\n\nAny line in $ \\PP^n $ which is not contained in $ H $ meets $ H $ in exactly one point. This is geometrically clear. One can prove it algebraically via linear algebra using the affine cones, or by the following calculation. Let $ x \\in \\PP^n \\setminus \\cbr{p} $. Then\n$$ \\L_{px} = \\cbr{\\sbr{p_0s + x_0t : \\dots : p_ns + x_nt} \\in \\PP^n \\st \\sbr{s : t} \\in \\PP^1}. $$\nHence, to find $ \\L_{px} \\cap H $, we need to choose $ \\sbr{s : t} $ such that $ p_ns + x_nt = 0 $. We can choose $ \\sbr{s : t} = \\sbr{x_n : -p_n} $, noting that $ p_n \\ne 0 $ because $ p \\notin H $, so we do not get $ \\sbr{0 : 0} $. Substituting in to $ \\L_{px} $, the unique point of $ \\L_{px} \\cap H $ is\n$$ \\sbr{p_0x_n - x_0p_n : \\dots : p_{n - 1}x_n - x_{n - 1}p_n : 0}. $$\nThe final $ 0 = p_nx_n - x_np_n $ is what we expect for a point in $ H $.\n\n\\begin{note*}\nIf $ p \\ne x $, then this is not $ \\sbr{0 : \\dots : 0} $ so it is well-defined.\n\\end{note*}\n\nThus, for $ x \\in \\PP^n \\setminus \\cbr{p} $, it makes sense to define $ \\pi\\br{x} $ to be the unique point of $ \\L_{px} \\cap H $. The above calculation shows that $ \\pi $ is a rational map $ \\PP^n \\dashrightarrow H $, regular on $ \\PP^n \\setminus \\cbr{p} $. We show below that $ \\pi $ is not regular at $ p $. This rational map is called the \\textbf{projection from $ p $ to $ H $}. One could replace this particular fixed $ H $ by any hyperplane not containing $ p $, and carry out the same recipe.\n\n\\begin{lemma}\nLet $ n \\ge 2 $. The projection of $ \\PP^n $ from $ p $ to $ H $ is not regular at $ p $.\n\\end{lemma}\n\nIntuitively, there are many lines passing through $ p $ and $ p $, so the projection would have to map $ p $ to everywhere at once. We can make this rigorous.\n\n\\begin{proof}\nPick a point $ s \\in H $ and consider the line $ \\L_{ps} $. For any $ x \\in \\L_{ps} \\setminus \\cbr{p} $, the geometric description of $ \\pi $ shows that $ \\pi\\br{x} = s $. If we assume that $ \\pi $ is regular at $ p $, then it restricts to a regular map $ \\L_{ps} \\to H $. We have just shown that this map is constant on $ \\L_{ps} \\setminus \\cbr{p} $ and therefore it is constant on $ \\L_{ps} $. Hence $ \\pi\\br{p} = s $. We could pick another point $ t \\in H $ and repeat exactly the same argument using $ \\L_{pt} $, so that $ \\pi\\br{p} = t $. This is a contradiction.\n\\end{proof}\n\nThe condition $ n \\ge 2 $ is needed to ensure that $ H \\cong \\PP^{n - 1} $ has two distinct points $ s $ and $ t $. If $ n = 1 $, then $ H $ is just a point and $ \\pi $ is a constant map, so it is regular everywhere.\n\n\\subsubsection{Products of projective algebraic sets}\n\nMany sets that we want to work with, for example, the graph of a regular map $ V \\to W $, are naturally defined as subsets of products $ V \\times W $ of algebraic sets. Therefore we would like to be able to say that the product of algebraic sets are also algebraic sets. We saw that this is easy for affine algebraic sets, since $ V \\times W $ is an affine algebraic subset of $ \\AA^{m + n} $. The key point here is the isomorphism $ \\AA^m \\times \\AA^n \\cong \\AA^{m + n} $. For projective algebraic sets, it is harder to define products because $ \\PP^m \\times \\PP^n \\not\\cong \\PP^{m + n} $.\n\n\\begin{example*}\nTo see informally why $ \\PP^1 \\times \\PP^1 \\not\\cong \\PP^2 $, recall that $ \\PP^1 = \\AA^1 \\cup \\cbr{\\text{point}} $ so\n$$ \\PP^1 \\times \\PP^1 = \\br{\\AA^1 \\times \\AA^1} \\cup \\br{\\AA^1 \\times \\cbr{\\text{point}}} \\cup \\br{\\cbr{\\text{point}} \\times \\AA^1} \\cup \\br{\\text{point} \\times \\cbr{\\text{point}}} = \\AA^2 \\cup \\AA^1 \\cup \\AA^1 \\cup \\cbr{\\text{point}}. $$\nMeanwhile $ \\PP^2 = \\AA^2 \\cup \\PP^1 = \\AA^2 \\cup \\AA^1 \\cup \\cbr{\\text{point}} $. Thus $ \\PP^1 \\times \\PP^1 $ contains an extra copy of $ \\AA^1 $ compared to $ \\PP^2 $. This is only an informal argument. A rigorous proof will be on problem sheet $ 4 $.\n\\end{example*}\n\nWe could try giving an ad hoc definition for $ \\PP^m \\times \\PP^n $ by hand. It is fairly clear what algebraic subsets of $ \\PP^m \\times \\PP^n $, sets defined by polynomials in the two sets of homogeneous coordinates $ \\sbr{x_0 : \\dots : x_m} $ and $ \\sbr{y_0 : \\dots : y_n} $, should mean. In order for the zero set of such a polynomial to be well-defined, it must be \\textbf{bihomogeneous}, that is homogeneous in the $ x $ variables and homogeneous in the $ y $ variables, but the $ x $ and $ y $ degrees can potentially be different. Similarly, we could give a definition of regular maps between subvarieties of $ \\PP^m \\times \\PP^n $ involving bihomogeneous polynomials. But it would be annoying to have just defined quasi-projective varieties, unifying affine and projective varieties, and then immediately have to introduce ad hoc definitions for another different kind of variety. So we aim to construct the product in a way which makes it a quasi-projective set, and then we can just reuse the definitions from before. Furthermore, projective varieties have special properties of their own. In particular, we will prove that the image of a projective variety under a regular map is always closed. By showing that the product of projective varieties is itself a projective variety, we will be able to apply these properties to products too.\n\n\\pagebreak\n\n\\subsubsection{The Segre embedding}\n\nTo construct the product $ \\PP^m \\times \\PP^n $ as a projective algebraic set, we will embed it inside some larger $ \\PP^N $. The homogeneous coordinates of a point in $ \\PP^m \\times \\PP^n $ will be given by an $ \\br{m + 1} \\times \\br{n + 1} $ matrix, so we need\n$$ N = \\br{m + 1}\\br{n + 1} - 1 = mn + m + n. $$\nThus the number of homogeneous coordinates needed to specify a point in $ \\PP^N $ is $ \\br{m + 1}\\br{n + 1} $. We will arrange the homogeneous coordinates of points in $ \\PP^N $ as if they were entries of a matrix. Thus we label them as\n$$ \\sbr{\\br{z_{ij} \\st 0 \\le i \\le m, \\ 0 \\le j \\le n}}, $$\nrather than the usual $ \\sbr{z_0 : \\dots : z_N} $. Define a map given by\n$$ \\function[\\sigma_{m, n}]{\\PP^m \\times \\PP^n}{\\PP^N}{\\br{\\sbr{x_0 : \\dots : x_m}, \\sbr{y_0 : \\dots : y_n}}}{\\sbr{\\br{z_{ij} = x_iy_j \\st 0 \\le i \\le m, \\ 0 \\le j \\le n}}}. $$\nAnother way to describe this is to say that the homogeneous coordinates of $ \\sigma_{m, n}\\br{\\sbr{x_0 : \\dots : x_m}, \\sbr{y_0 : \\dots : y_n}} $ are given by the product matrix\n$$ \\br{z_{ij}} = \\threebyone{x_0}{\\vdots}{x_m}\\onebythree{y_0}{\\dots}{y_n}. $$\nObserve that this matrix has rank one. Let\n$$ \\Sigma_{m, n} = \\cbr{\\sbr{z_{00} : \\dots : z_{mn}} \\in \\PP^N \\st \\rk \\br{z_{ij}} = 1}. $$\nSome linear algebra shows that we can describe $ \\Sigma_{m, n} $ as the subset of $ \\PP^N $ where all $ 2 \\times 2 $ submatrices of the matrix $ \\br{z_{ij}} $ have zero determinant. Thus $ \\Sigma_{m, n} $ is a projective algebraic set, defined by the equations\n$$ z_{ij}z_{kl} = z_{kj}z_{il}, \\qquad 0 \\le i, k \\le m, \\qquad 0 \\le j, l \\le n. $$\n\n\\begin{lemma}\n$ \\sigma_{m, n} $ is a bijection from $ \\PP^m \\times \\PP^n $ to $ \\Sigma_{m, n} $.\n\\end{lemma}\n\nThis proof is not part of the course.\n\n\\begin{proof}\nWe can define an inverse to $ \\sigma_{m, n} $ as follows. Let $ a \\in \\Sigma_{m, n} $, and let $ A $ be a matrix giving homogeneous coordinates for $ a $. Then $ A $ is not the zero matrix, because it is a set of homogeneous coordinates, so we can pick $ j $ such that the $ j $-th column of $ A $ contains a non-zero entry. Define $ \\pi_1\\br{a} \\in \\PP^m $ to be the point with homogeneous coordinates given by the $ j $-th column of $ A $, that is $ \\pi_1\\br{a} = \\sbr{A_{1j} : \\dots : A_{mj}} $. This is independent of the choice of $ j $ because the matrix has rank one, since every non-zero column is a multiple of every other non-zero column. Similarly we can pick $ i $ such that the $ i $-th row of $ A $ contains a non-zero entry, and define $ \\pi_2\\br{a} \\in \\PP^n $ to be the point with homogeneous coordinates given by the $ i $-th row of $ A $. Again this is independent of the choice of $ i $. Now $ \\br{\\pi_1, \\pi_2} : \\Sigma_{m, n} \\to \\PP^m \\times \\PP^n $ is an inverse to $ \\sigma_{m, n} $.\n\\end{proof}\n\nThis construction shows that the projections $ \\pi_1 : \\Sigma_{m, n} \\to \\PP^m $ and $ \\pi_2 : \\Sigma_{m, n} \\to \\PP^n $ are regular maps, since each column of the matrix is non-zero on a Zariski open subset of $ \\Sigma_{m, n} $. The map $ \\sigma_{m, n} : \\PP^m \\times \\PP^n \\to \\PP^N $ is called the \\textbf{Segre embedding} and its image $ \\Sigma_{m, n} \\subseteq \\PP^N $ is called the \\textbf{Segre variety}.\n\n\\lecture{20}{Thursday}{27/02/20}\n\n\\begin{example*}\nWhen $ m = n = 1 $, $ N = 3 $. The Segre variety $ \\Sigma_{m, n} \\subseteq \\PP^3 $ is defined by the single equation\n$$ \\det \\twobytwo{z_{00}}{z_{01}}{z_{10}}{z_{11}} = z_{00}z_{11} - z_{10}z_{01} = 0. $$\nThe Segre embedding is given by\n$$ \\sigma_{m, n}\\br{\\sbr{x_1 : x_2}, \\sbr{y_1 : y_2}} = \\sbr{x_1y_1 : x_1y_2 : x_2y_1 : x_2y_2}. $$\nWe see that $ \\Sigma_{m, n} $ is an irreducible quadric hypersurface in $ \\PP^3 $. Therefore by problem sheet $ 3 $, question $ 4 $, it is birational to $ \\PP^2 $ and $ \\AA^2 $. This is not surprising, because of course $ \\PP^1 \\times \\PP^1 $ should have an open subset isomorphic to $ \\AA^1 \\times \\AA^1 \\cong \\AA^2 $, which in turn is an open subset of $ \\PP^2 $. We gave an informal argument earlier that $ \\PP^1 \\times \\PP^1 $ should not be isomorphic to $ \\PP^2 $. A rigorous proof of this will be on the next problem sheet.\n\\end{example*}\n\n\\pagebreak\n\nBecause $ \\Sigma_{m, n} $ is a projective algebraic set, it has a subspace topology induced by the Zariski topology on $ \\PP^N $ and so we get a Zariski topology on $ \\PP^m \\times \\PP^n $. One can check that this topology is the same as what we expect, namely the following.\n\n\\begin{lemma}\nLet $ V \\subseteq \\PP^m \\times \\PP^n $. Then $ \\sigma_{m, n}\\br{V} \\subseteq \\Sigma_{m, n} $ is closed if and only if\n$$ V = \\cbr{\\br{\\sbr{x_0 : \\dots : x_m}, \\sbr{y_0 : \\dots : y_n}} \\st \\forall 1 \\le i \\le s, \\ f_i\\br{x_0, \\dots, x_m, y_0, \\dots, y_n} = 0}, $$\nwhere $ f_1, \\dots, f_s \\in k\\sbr{X_0, \\dots, X_m, Y_0, \\dots, Y_n} $ are bihomogeneous polynomials.\n\\end{lemma}\n\nWe say that a polynomial $ f \\in k\\sbr{X_0, \\dots, X_m, Y_0, \\dots, Y_n} $ is \\textbf{bihomogeneous of degree $ \\br{d, e} $} if every term of $ f $ has degree $ d $ with respect to the $ X $ variables and degree $ e $ with respect to the $ Y $ variables.\n\n\\begin{proof}\nSuppose that $ \\sigma_{m, n}\\br{V} $ is Zariski closed in $ \\PP^N $. Then it is defined by some homogeneous polynomials $ g_r\\br{z_{00}, \\dots, z_{mn}} $. Making the substitutions $ z_{ij} = x_iy_j $, as in the definition of $ \\sigma_{m, n} $, we get a finite set of polynomials which define $ V $. If $ g_r $ is homogeneous in $ z_{ij} $ of degree $ d_r $, then $ g_r \\circ \\sigma_{m, n} $ is bihomogeneous of degree $ \\br{d_r, d_r} $. It is easy to see that if $ V $ is defined by polynomials $ f_r $, where $ f_r $ is bihomogeneous of degree $ \\br{d_r, d_r} $, then we can reverse this process to get homogeneous polynomials in $ z_{ij} $ which define $ \\sigma_{m, n}\\br{V} $. But what if the defining polynomials for $ V $ include some $ f $ which is bihomogeneous of degree $ \\br{d, e} $, where $ d \\ne e $? Without loss of generality, suppose that $ d > e $. Then $ f = 0 $ is equivalent to the system of equations\n$$ x_0^{d - e}f = 0, \\qquad \\dots, \\qquad x_m^{d - e}f = 0, $$\nand these equations are bihomogeneous of degree $ \\br{d, d} $.\n\\end{proof}\n\n\\subsubsection{Graphs of regular functions}\n\nIf $ V \\subseteq \\PP^m $ and $ W \\subseteq \\PP^n $ are projective algebraic sets, then their product $ V \\times W \\subseteq \\PP^m \\times \\PP^n $ is a Zariski closed subset of $ \\PP^m \\times \\PP^n $, since the homogeneous polynomials defining $ V $ become bihomogeneous polynomials of degree $ \\br{d, 0} $ while those defining $ W $ become bihomogeneous polynomials of degree $ \\br{0, e} $, and therefore $ V \\times W $ is itself a projective variety. Similarly, if $ V \\subseteq \\PP^m $ and $ W \\subseteq \\PP^n $ are quasi-projective algebraic sets, then the product $ V \\times W $ is also quasi-projective, since it is the intersection of an open subset and a closed subset in $ \\PP^m \\times \\PP^n $, and therefore in $ \\PP^N $ via the Segre embedding.\n\n\\begin{example*}\nOne useful example of a subvariety of a product is the graph of a regular function. Let $ V \\subseteq \\PP^n $ and $ W \\subseteq \\PP^m $ be quasi-projective algebraic sets, and let $ \\phi : V \\to W $ be a regular map. The \\textbf{graph} of $ \\phi $ is\n$$ \\Gamma = \\cbr{\\br{x, y} \\in V \\times W \\st y = \\phi\\br{x}}. $$\nTo check that this is closed in $ V \\times W $, observe that $ \\Gamma $ is the preimage of the diagonal $ \\Delta \\subseteq \\PP^m \\times \\PP^m $ under the regular map\n$$ \\br{\\iota \\circ \\phi, \\iota} : V \\times W \\to \\PP^m \\times \\PP^m, $$\nwhere $ \\iota $ denotes the inclusion map $ W \\to \\PP^m $. Since $ \\br{\\iota \\circ \\phi, \\iota} $ is a regular map, it is continuous. Therefore it suffices to check that the diagonal is a Zariski closed subset of $ \\PP^m \\times \\PP^m $. This is true because we can describe the diagonal by bihomogeneous equations as\n$$ \\Delta = \\cbr{\\br{\\sbr{x_0 : \\dots : x_m}, \\sbr{y_0 : \\dots : y_m}} \\st \\forall i, j, \\ x_iy_j = x_jy_i}. $$\n\\end{example*}\n\n\\subsubsection{Images of projective varieties}\n\nThe following is a key property of projective algebraic varieties, which is analogous to compactness for Hausdorff topological spaces.\n\n\\begin{theorem}\n\\label{thm:imageclosed}\nLet $ V $ be a projective variety. Let $ \\phi : V \\to W $ be a regular map into any quasi-projective variety. Then the image of $ \\phi $ is Zariski closed.\n\\end{theorem}\n\nClearly Theorem \\ref{thm:imageclosed} is false if $ V $ is not projective.\n\n\\begin{example*}\nConsider the projection of the hyperbola $ \\cbr{\\br{x, y} \\st xy = 1} $ onto one of the axes.\n\\end{example*}\n\n\\pagebreak\n\nTheorem \\ref{thm:imageclosed} shows that projective varieties are similar to compact spaces in topology, since if $ S $ is a compact topological space and $ T $ is a Hausdorff topological space, then the image of any continuous map $ S \\to T $ is closed. By applying Theorem \\ref{thm:imageclosed} to $ \\iota \\circ \\phi $, where $ \\iota $ is an embedding $ W \\to \\PP^m $, we see that the image of a projective variety under a regular map is again a projective variety. Before proving Theorem \\ref{thm:imageclosed}, we shall state some important corollaries.\n\n\\begin{corollary}\n\\label{cor:regularconstant}\nEvery regular function on an irreducible projective variety is constant.\n\\end{corollary}\n\n\\begin{proof}\nLet $ V $ be an irreducible projective variety and $ \\phi : V \\to \\AA^1 $ a regular function. Let $ \\iota : \\AA^1 \\to \\PP^1 $ be the natural inclusion. Then $ \\iota \\circ \\phi : V \\to \\PP^1 $ is a regular map, so by Theorem \\ref{thm:imageclosed}, its image is a closed subset of $ \\PP^1 $. But the image of $ \\iota \\circ \\phi $ is contained in $ \\AA^1 $, so it cannot be all of $ \\PP^1 $. Therefore the image of $ \\phi $ is finite. Since $ V $ is irreducible, its image is also irreducible and therefore consists of a single point.\n\\end{proof}\n\nThus projective algebraic sets are essentially opposite to affine ones, since an affine algebraic set is determined by its ring of regular functions while a projective algebraic set has no regular functions except constants.\n\n\\begin{corollary}\n\\label{cor:regularpoint}\nThe image of a regular map from an irreducible projective variety to an affine variety is a point.\n\\end{corollary}\n\n\\begin{proof}\nSuppose we have a regular map $ \\phi : V \\to W $, where $ V $ is projective and irreducible and $ W $ is affine. We can suppose that $ W \\subseteq \\AA^m $, and let $ X_1, \\dots, X_m $ denote the coordinate functions on $ W $. Then $ X_1 \\circ \\phi, \\dots, X_m \\circ \\phi $ are all constant by Corollary \\ref{cor:regularconstant}, and so $ \\phi $ is constant.\n\\end{proof}\n\n\\begin{lemma}\n\\label{lem:hyperplaneintersection}\nLet $ V \\subseteq \\PP^n $ be an infinite projective algebraic set and let $ H \\subseteq \\PP^n $ be a hyperplane. Then the intersection $ V \\cap H $ is non-empty.\n\\end{lemma}\n\nWe use the following fact. This fact is proved for $ \\PP^2 $ on problem sheet $ 3 $ using the Veronese embedding, and the proof generalises to arbitrary $ \\PP^n $.\n\n\\begin{fact*}\nIf $ H \\subseteq \\PP^n $ is a hypersurface, then the complement $ \\PP^n \\setminus H $ is isomorphic to an affine algebraic set.\n\\end{fact*}\n\n\\begin{proof}\nSuppose for contradiction that Lemma \\ref{lem:hyperplaneintersection} were false, then $ V \\cap H = \\emptyset $. Then $ V \\subseteq \\PP^n \\setminus H $, which is isomorphic to an affine algebraic set $ \\AA^n $ for some $ n $. Hence we get an injective regular map $ \\iota : V \\to \\AA^n $. Pick an infinite irreducible component $ V_1 \\subseteq V $. Then $ V_1 $ is a projective algebraic set so, by Corollary \\ref{cor:regularpoint}, $ \\iota $ is constant on $ V_1 $, and since $ \\iota $ is injective, $ V_1 $ maps to a point. But $ V $ has only finitely many irreducible components, so this contradicts the hypothesis that $ V $ is infinite.\n\\end{proof}\n\n\\subsubsection{Completeness of varieties}\n\nTo prove Theorem \\ref{thm:imageclosed}, we will use the graph $ \\Gamma \\subseteq V \\times W $ of $ \\phi $. The image of $ \\phi $ is the same as the projection of $ \\Gamma $ onto $ W $. Hence Theorem \\ref{thm:imageclosed} can be deduced from the following theorem, which will be a more convenient statement to prove.\n\n\\begin{theorem}\n\\label{thm:projectionclosed}\nLet $ V $ be a projective variety. For any quasi-projective variety $ W $, the second projection map $ \\pi_2 : V \\times W \\to W $ maps closed sets to closed sets.\n\\end{theorem}\n\nAgain, we can see that Theorem \\ref{thm:projectionclosed} does not apply when $ V $ is not projective by taking $ V = W = \\AA^1 $ and taking the hyperbola as a closed subset of $ V \\times W $. At first sight, Theorem \\ref{thm:projectionclosed} looks stronger than Theorem \\ref{thm:imageclosed} because it applies to all closed subsets of $ V \\times W $, not just the graphs $ \\Gamma $ of regular maps $ \\phi : V \\to W $, using that $ \\im \\phi = \\pi_2\\br{\\Gamma} $. In fact it is easy to deduce Theorem \\ref{thm:projectionclosed} from Theorem \\ref{thm:imageclosed}, by applying it to $ \\pi_2 \\circ \\iota : Z \\to W $ where $ \\iota $ is the inclusion map $ Z \\to V \\times W $ for any closed subset $ Z \\subseteq V \\times W $.\n\n\\begin{definition*}\nA variety $ V $ is \\textbf{complete} if it satisfies the conclusion of Theorem \\ref{thm:projectionclosed}. In other words, for every quasi-projective variety $ W $, the second projection $ \\pi_2 : V \\times W \\to W $ maps closed sets to closed sets.\n\\end{definition*}\n\nFor quasi-projective varieties, complete is equivalent to projective, but if we go beyond the world of quasi-projective varieties, and we have not defined non-quasi-projective varieties at all in this course, then it is possible to find algebraic varieties which are complete but not projective. Completeness is the natural analogue in algebraic geometry for compactness in topology. This is justified by the following result from topology.\n\n\\begin{lemma}\n\\label{lem:projectionclosed}\nLet $ S $ be a topological space. Then $ S $ is compact if and only if, for every topological space $ T $, the second projection map $ S \\times T \\to T $ maps closed sets to closed sets.\n\\end{lemma}\n\n\\pagebreak\n\n\\begin{note*}\nIn Lemma \\ref{lem:projectionclosed}, we use closed sets for the product topology on $ S \\times T $, while in Theorem \\ref{thm:projectionclosed} we use closed sets for the Zariski topology on $ V \\times W $, coming from the Segre embedding. These are not the same thing, since we have seen, in the case $ \\AA^1 \\times \\AA^1 $, that the Zariski topology on a product has more closed sets than the product topology.\n\\end{note*}\n\nWe remark that, over the complex numbers, an algebraic variety is complete if and only if it is compact for the analytic topology. This is hard to prove.\n\n\\subsubsection{Images of quasi-projective varieties}\n\nCompleteness tells us that images of regular maps of projective algebraic sets are closed. We know that this is false for affine algebraic sets, by considering our favourite example of the hyperbola and its projection to $ \\AA^1 $. So what can we say about the images of regular maps of affine, or more generally quasi-projective algebraic sets? We might speculate that they would always be quasi-projective, that is the intersection of an open and a closed set. But this is not true either. Consider the regular map given by\n$$ \\function[\\phi]{\\AA^2}{\\AA^2}{\\br{x, y}}{\\br{x, xy}}. $$\nThe image of $ \\phi $ is $ \\cbr{\\br{x, y} \\st x \\ne 0} \\cup \\cbr{\\br{0, 0}} $. This is the union of an open set with a closed set, not their intersection. It turns out that this is more or less as bad as things can get.\n\n\\begin{definition*}\nLet $ S $ be any topological space. A \\textbf{locally closed} subset of $ S $ is the intersection between an open and a closed set. A \\textbf{constructible} subset of $ S $ is a finite union of locally closed sets.\n\\end{definition*}\n\n\\begin{example*}\nQuasi-projective algebraic sets are locally closed subsets of $ \\PP^n $.\n\\end{example*}\n\nEquivalently, a constructible set is any set which can be obtained by starting with a finite list of open and closed sets, and combining them in any way using unions and intersections. The image of the map $ \\br{x, y} \\mapsto \\br{x, xy} $ considered above is the typical example to keep in mind for a constructible set which is not locally closed. Chevalley's theorem tells us that the image of a regular map between quasi-projective varieties is constructible. Indeed it tells us slightly more. The image of a constructible set is constructible.\n\n\\begin{theorem}[Chevalley's theorem]\n\\label{thm:chevalleytheorem}\nLet $ \\phi : V \\to W $ be a regular map of quasi-projective algebraic sets. The image of any constructible set in $ V $ is a constructible set in $ W $.\n\\end{theorem}\n\nWe will prove completeness of projective varieties and Chevalley's theorem in the next lecture. Their proofs are linked but neither theorem is an easy consequence of the other.\n\n\\subsubsection{Chevalley's theorem and mathematical logic}\n\nThis is not a formal part of the course, so I will not define things carefully. For anyone with an interest in mathematical logic, we remark on a logical interpretation of Chevalley's theorem. In logic, we consider formulas made out of some algebraic operations. In the context of algebraic geometry, these will be polynomial equations over an algebraically closed field, and combine these using logical operations, $ \\land, \\lor, \\lnot, \\exists, \\forall $.\n\n\\begin{example*}\nA logical formula might look like $ \\br{\\lnot\\br{xy = z}} \\land \\exists\\br{u, v}\\br{\\br{x = u^2} \\land \\br{y = uv} \\land \\br{z = v^2}} $.\n\\end{example*}\n\nIf we allow just $ \\land, \\lor, \\lnot $ then formulas like this define unions and intersections of Zariski open and closed sets in $ \\AA^n $, that is constructible sets. If we also allow quantifiers, then we can also get images of regular maps.\n\n\\begin{example*}\nThe part of the formula above starting with $ \\exists\\br{u, v} $ defines the image of the regular map $ \\br{u, v} \\mapsto \\br{u^2, uv, v^2} $.\n\\end{example*}\n\nBut Chevalley's theorem tells us that images of regular maps are actually also constructible sets, so we deduce the following.\n\n\\begin{fact*}\nEvery formula, made out of polynomials over an algebraically closed field, is equivalent to a formula without quantifiers.\n\\end{fact*}\n\nThis is called \\textbf{elimination of quantifiers for algebraically closed fields}.\n\n\\pagebreak\n\n\\subsubsection{Affine open covers}\n\n\\lecture{21}{Friday}{28/02/20}\n\nBy definition, every quasi-projective algebraic set is contained in a projective algebraic set. We can use this to reduce some proofs for quasi-projective algebraic sets to the projective case, proving from the outside in. On the other hand, it is often useful to know that we can find affine varieties as open sets inside each quasi-projective algebraic set. This can be used to reduce some proofs to the affine case, proving from the inside out.\n\n\\begin{lemma}\n\\label{lem:quasiprojectiveaffine}\nLet $ V $ be a quasi-projective variety. For every point $ x \\in V $, there exists an open set $ U \\subseteq V $ which contains $ x $ and is isomorphic to an affine variety.\n\\end{lemma}\n\n\\begin{proof}\nWrite $ V = V_0 \\cap U_0 $ where $ V_0 \\subseteq \\PP^n $ is closed and $ U_0 \\subseteq \\PP^n $ is open. Given a point $ x \\in V $, we may assume that $ x $ is in $ \\AA^n \\subseteq \\PP^n $, embedded by setting $ X_0 = 1 $. We can achieve this by changing the coordinate system if necessary. Since $ \\PP^n \\setminus U_0 $ is a projective algebraic set which does not contain $ x $, there is some homogeneous polynomial $ f $ which vanishes on $ \\PP^n \\setminus U_0 $ but not at $ x $. Then $ x $ is contained in the set $ U_0 = V_0 \\cap D\\br{f} = V \\cap D\\br{f} $, where\n$$ D\\br{f} = \\cbr{\\br{y_1, \\dots, y_n} \\in \\AA^n \\st f\\br{1, y_1, \\dots, y_n} \\ne 0}. $$\nWe have $ V_0 \\cap D\\br{f} = V \\cap D\\br{f} $ because $ D\\br{f} \\subseteq U_0 $. Then $ U $ is an open subset of $ V $ because $ D\\br{f} $ is an open subset of $ \\PP^n $, and $ U $ is a closed subset of $ D\\br{f} $, so in order to show that $ U $ is an affine variety, it suffices to show that $ D\\br{f} $ is an affine variety. We can prove this using the hyperbola trick. Consider the set\n$$ E\\br{f} = \\cbr{\\br{y_1, \\dots, y_n, z} \\in \\AA^{n + 1} \\st zf\\br{1, y_1, \\dots, y_n} = 1}. $$\nThen $ E\\br{f} $ is an affine algebraic set in $ \\AA^{n + 1} $, and projection onto the first $ n $ coordinates gives an isomorphism between $ E\\br{f} $ and $ D\\br{f} $.\n\\end{proof}\n\n\\subsubsection{Proof of completeness}\n\nWe will now prove the completeness of projective varieties, in the form of Theorem \\ref{thm:projectionclosed}. Let $ Z $ be a closed subset of $ V \\times W $. By Lemma \\ref{lem:quasiprojectiveaffine}, we may cover $ W $ by open sets $ U_\\alpha $ such that each $ U_\\alpha $ is an affine variety. According to the topological fact from the proof of Lemma \\ref{lem:projectivedense}, in order to show that $ \\pi_2\\br{Z} $ is closed in $ W $, it suffices to show that $ \\pi_2\\br{Z} \\cap U_\\alpha $ is closed in $ U_\\alpha $ for every $ \\alpha $. In other words, since $ \\pi_2\\br{Z} \\cap U_\\alpha = \\pi_2\\br{Z \\cap \\br{V \\times U_\\alpha}} $, replacing $ W $ by $ U_\\alpha $, we conclude that it suffices to prove Theorem \\ref{thm:projectionclosed} for the case where $ W $ is affine. Then we can replace $ V \\subseteq \\PP^m $ by $ \\PP^m $ and $ W \\subseteq \\AA^n $ by $ \\AA^n $, because $ V $ is closed in $ \\PP^m $ and $ W $ is closed in $ \\AA^n $, so $ Z \\subseteq V \\times W $ is closed in $ \\PP^m \\times \\AA^n $. The benefit of doing this is that it simplifies the algebra when we change everything into coordinates. Thus it suffices to prove the following special case of Theorem \\ref{thm:projectionclosed}.\n\n\\begin{theorem}\n\\label{thm:projectionclosed2}\nThe second projection map $ \\pi_2 : \\PP^m \\times \\AA^n \\to \\AA^n $ maps closed sets to closed sets.\n\\end{theorem}\n\n\\begin{proof}\nWe can concretely describe a Zariski closed subset $ Z \\subseteq \\PP^m \\times \\AA^n $ as the zero set of some polynomials $ f_0, \\dots, f_r \\in k\\sbr{X_0, \\dots, X_m, Y_1, \\dots, Y_n} $ which are homogeneous with respect to $ X_0, \\dots, X_m $. The coordinates $ Y_1, \\dots, Y_n $ are affine coordinates, so there is no homogeneity condition with respect to them. For each point $ \\underline{y} \\in \\AA^n $, we can substitute the values $ \\underline{y} $ into these polynomials and get a projective algebraic set\n$$ Z_{\\underline{y}} = \\cbr{\\sbr{x_0 : \\dots : x_m} \\in \\PP^m \\st \\forall i, \\ f_i\\br{x_0, \\dots, x_m, \\underline{y}} = 0}. $$\nObserve that $ \\underline{y} \\in \\pi_2\\br{Z} $ if and only if $ Z_{\\underline{y}} $ is non-empty. Let $ I_{\\underline{y}} $ denote the ideal in $ k\\sbr{X_0, \\dots, X_m} $ generated by the polynomials\n$$ f_0\\br{X_0, \\dots, X_m, \\underline{y}}, \\qquad \\dots, \\qquad f_r\\br{X_0, \\dots, X_m, \\underline{y}}. $$\nBy the projective Nullstellensatz, $ Z_{\\underline{y}} $ is non-empty if and only if $ \\rad I_{\\underline{y}} $ is not equal to either the full ring $ k\\sbr{X_0, \\dots, X_m} $ or to the ideal $ \\abr{X_0, \\dots, X_m} $. It is easy to see that this is equivalent to, $ I_{\\underline{y}} $ does not contain $ S_d $ for any $ d \\in \\NN $, where $ S_d $ denotes the set of all homogeneous polynomials of degree $ d $ in $ k\\sbr{X_0, \\dots, X_m} $. For each $ d \\in \\NN $, write\n$$ W_d = \\cbr{\\underline{y} \\in \\AA^n \\st I_{\\underline{y}} \\not\\supseteq S_d}. $$\n\n\\pagebreak\n\nWe have shown that $ \\pi_2\\br{Z} = \\bigcap_{d \\in \\NN} W_d $. Let the polynomials $ f_0, \\dots, f_r $ have degrees $ d_0, \\dots, d_r $ with respect to the $ X $ variables. We shall show that $ W_d $ is closed for $ d \\ge \\max\\br{d_0, \\dots, d_r} $. Since the $ W_d $ are a descending chain of sets, this is sufficient to show that $ \\pi_2\\br{Z} $ is closed. Now we just need some linear algebra to finish the proof. If $ g \\in S_d $, then $ g \\in I_{\\underline{y}} $ if and only if we can write\n$$ g\\br{X_0, \\dots, X_m} = \\sum_{i = 1}^r f_i\\br{X_0, \\dots, X_m, \\underline{y}}h_i\\br{X_0, \\dots, X_m}, $$\nfor some homogeneous polynomials $ h_1, \\dots, h_r $, where $ \\deg h_i = d - d_i $. Hence $ S_d \\cap I_{\\underline{y}} $ is the image of the linear map given by\n$$ \\function[\\alpha_{d, \\underline{y}}]{\\bigoplus_{i = 1}^r S_{d - d_i}}{S_d}{\\br{h_1, \\dots, h_r}}{\\sum_{i = 1}^r f_i\\br{X_0, \\dots, X_m, \\underline{y}}h_i\\br{X_0, \\dots, X_m}}. $$\nTherefore\n\\begin{align*}\nW_d\n& = \\cbr{\\underline{y} \\in \\AA^n \\st \\alpha_{d, \\underline{y}} \\ \\text{is not surjective}} \\\\\n& = \\cbr{\\underline{y} \\in \\AA^n \\st \\rk \\alpha_{d, \\underline{y}} < \\dim S_d} \\\\\n& = \\cbr{\\underline{y} \\in \\AA^n \\st \\text{all} \\ \\br{\\dim S_d \\times \\dim S_d} \\ \\text{submatrices of} \\ \\alpha_{d, \\underline{y}} \\ \\text{have determinant zero}},\n\\end{align*}\nwhere we fix bases for $ S_d $ and $ \\bigoplus_i S_{d - d_i} $ and use these to write $ \\alpha_{d, \\underline{y}} $ as a matrix with respect to these bases. The determinants of these submatrices are polynomials in $ y_1, \\dots, y_n $, proving that $ W_d $ is Zariski closed in $ \\AA^n $.\n\\end{proof}\n\n\\subsubsection{The resultant}\n\nTheorem \\ref{thm:projectionclosed2} has the following application to roots of polynomials. We want to describe the set of pairs of polynomials $ f, g \\in k\\sbr{S, T} $, homogeneous of degrees $ d $ and $ e $ respectively, for which the set of common zeroes\n$$ \\cbr{\\sbr{s : t} \\in \\PP^1 \\st f\\br{s, t} = 0, \\ g\\br{s, t} = 0} $$\nis non-empty. We can identify the space of homogeneous polynomials of degree $ d $ in two variables with $ \\AA^{d + 1} $, by associating $ \\underline{a} = \\br{a_0, \\dots, a_d} \\in \\AA^{d + 1} $ with the polynomial\n$$ f_{\\underline{a}}\\br{S, T} = \\sum_{i = 0}^d a_iS^iT^{d - i}. $$\nWe can define a Zariski closed subset of $ \\PP^1 \\times \\AA^{\\br{d + 1} + \\br{e + 1}} $ by\n$$ Z_{d, e} = \\cbr{\\br{\\sbr{s : t}, \\underline{a}, \\underline{b}} \\in \\PP^1 \\times \\AA^{\\br{d + 1} + \\br{e + 1}} \\st \\sum_{i = 0}^d a_is^it^{d - i} = 0, \\ \\sum_{i = 0}^e b_is^it^{e - i} = 0}. $$\nFor any point $ \\br{\\underline{a}, \\underline{b}} \\in \\AA^{\\br{d + 1} + \\br{e + 1}} $ the fibre $ \\pi_2^{-1}\\br{\\underline{a}, \\underline{b}} \\cap Z_{d, e} $ is simply the set of common zeroes of $ f_{\\underline{a}} $ and $ f_{\\underline{b}} $ in $ \\PP^1 $. Hence\n$$ \\pi_2\\br{Z_{d, e}} = \\cbr{\\br{\\underline{a}, \\underline{b}} \\in \\AA^{\\br{d + 1} + \\br{e + 1}} \\st f_{\\underline{a}} \\ \\text{and} \\ f_{\\underline{b}} \\ \\text{have a common zero in} \\ \\PP^1}. $$\nBy Theorem \\ref{thm:projectionclosed2}, $ \\pi_2\\br{Z_{d, e}} $ is a Zariski closed subset of $ \\AA^{\\br{d + 1} + \\br{e + 1}} $. In other words, there is some list of polynomials $ p_1, \\dots, p_r $ such that the condition, homogeneous polynomials $ f $ and $ g $ in two variables of given degrees have a common zero in $ \\PP^1 $, is equivalent to $ p_1, \\dots, p_r $ all vanishing at the coefficients of $ f $ and $ g $. It turns out that this condition is equivalent not just to the vanishing of a list of polynomials in the coefficients, but to a single polynomial called the \\textbf{resultant} $ \\Res_{d, e} $.\n\n\\pagebreak\n\n\\begin{theorem}\n\\label{thm:fieldresultant}\nFix $ d, e \\in \\ZZ_{> 0} $. There exists a polynomial\n$$ \\Res_{d, e} \\in k\\sbr{A_0, \\dots, A_d, B_0, \\dots, B_e}, $$\nsuch that the polynomials\n$$ \\sum_{i = 0}^d a_iS^iT^{d - i}, \\qquad \\sum_{i = 0}^e b_iS^iT^{e - i} $$\nhave a common root in $ \\PP^1 $ if and only if\n$$ \\Res_{d, e}\\br{a_0, \\dots, a_d, b_0, \\dots, b_e} = 0. $$\n\\end{theorem}\n\nThis can be proved by going through the linear algebra from the end of the proof of Theorem \\ref{thm:projectionclosed2}. Indeed it is possible to work out the polynomial $ \\Res_{d, e} $ explicitly in this way. We shall just quote this as a result of algebra. The algebra actually gives us something more. This works not just for polynomials over an algebraically closed field, but for polynomials over any integral domain, provided we replace have a common zero by have a common factor of positive degree.\n\n\\begin{theorem}\n\\label{thm:domainresultant}\nFix $ d, e \\in \\ZZ_{> 0} $. There exists a universal polynomial\n$$ \\Res_{d, e} \\in \\ZZ\\sbr{A_0, \\dots, A_d, B_0, \\dots, B_e}, $$\nsuch that, for any integral domain $ R $ and any values $ a_0, \\dots, a_d, b_0, \\dots, b_e \\in R $, the homogeneous polynomials\n$$ f = \\sum_{i = 0}^d a_iS^iT^{d - i} \\in R\\sbr{S, T}, \\qquad g = \\sum_{i = 0}^e b_iS^iT^{e - i} \\in R\\sbr{S, T} $$\nhave a common factor of positive degree in $ R\\sbr{S, T} $ if and only if\n$$ \\Res_{d, e}\\br{a_0, \\dots, a_d, b_0, \\dots, b_e} = 0. $$\n\\end{theorem}\n\nFrom the perspective of elementary algebra, when stating Theorem \\ref{thm:fieldresultant}, it is simpler to look at inhomogeneous polynomials in one variable and roots in $ \\AA^1 $ instead of homogeneous polynomials in two variables and roots in $ \\PP^1 $. Of course, we can convert back and forth by homogenising and dehomogenising the polynomials, replacing $ f\\br{S, T} $ by $ f\\br{1, T} $ and vice versa, but we have to be a little bit careful. We have to worry about the possibility that $ f\\br{S, T} $ and $ g\\br{S, T} $ might have a common root at $ \\infty = \\sbr{0 : 1} \\in \\PP^1 $ but not anywhere in $ \\AA^1 = \\PP^1 \\setminus \\cbr{\\infty} $. It turns out that $ f\\br{S, T} $ has a root at $ \\infty $ if and only if the dehomogenised polynomial $ f\\br{1, T} $ has degree strictly less than $ \\deg f\\br{S, T} $. Thus, Theorem \\ref{thm:fieldresultant} implies that $ \\Res_{d, e} $ vanishes on the coefficients of two single variable polynomials\n$$ f\\br{T} = \\sum_{i = 0}^d a_iT^i, \\qquad g\\br{T} = \\sum_{i = 0}^e b_iT^i $$\nif and only if $ f $ and $ g $ have a common root in $ k $, as long as $ f $ and $ g $ have degrees exactly $ d $ and $ e $ respectively. If $ \\deg f < d $, but we still write out $ f $ as in the above with $ a_d = 0 $, then looking at $ \\Res_{d, e} $ might give the wrong answer for whether $ f $ and $ g $ have a common root, and similarly if $ \\deg g < e $.\n\n\\subsubsection{Proof of Chevalley's theorem}\n\n\\lecture{22}{Monday}{02/03/20}\n\nWe shall now prove Chevalley's theorem. We will reduce the proof to projections by using graphs, in a similar way to what we did for completeness. We can also reduce to the case where $ V $ and $ W $ are affine spaces, and perform a few more simplifications. The real work of the proof lies in the first two lemmas. After proving these lemmas, we will show the sequence of simpler steps to get from there to Theorem \\ref{thm:chevalleytheorem}.\n\n\\pagebreak\n\n\\begin{lemma}\n\\label{lem:projectioneither}\nLet $ \\pi : \\PP^1 \\times \\AA^m \\to \\AA^m $ denote the second projection map. Let $ V $ be an irreducible closed subset of $ \\PP^1 \\times \\AA^m $ and let $ T $ be a proper closed subset of $ V $. Then either\n\\begin{enumerate}\n\\item $ \\pi\\br{T} $ is strictly contained in $ \\pi\\br{V} $, or\n\\item $ V = \\PP^1 \\times \\pi\\br{V} $.\n\\end{enumerate}\n\\end{lemma}\n\n\\begin{proof}\nLet $ W = \\pi\\br{V} $. By the completeness of $ \\PP^1 $, $ W $ is closed in $ \\AA^m $, by Theorem \\ref{thm:projectionclosed}. Since $ V $ is irreducible, $ W $ is also irreducible. Hence the ring of regular functions $ k\\sbr{W} $ is an integral domain. We write $ k\\sbr{W}\\sbr{X, Y} $ for the ring of polynomials in two variables $ X $ and $ Y $ with coefficients in $ k\\sbr{W} $. Let $ I \\subseteq k\\sbr{W}\\sbr{X, Y} $ denote the homogeneous ideal of polynomials which vanish on $ V \\subseteq \\PP^1 \\times W $. Assume that $ V \\ne \\PP^1 \\times W $, otherwise conclusion $ 2 $ holds so we have nothing to prove. Thus $ I \\ne \\cbr{0} $. Let $ f $ be a homogeneous polynomial in $ I $ which has minimum degree with respect to $ X $ and $ Y $. Since $ V $ is irreducible, $ f $ has no factorisation into factors of positive degree, since if $ f = f_1f_2 $, then $ V \\cup \\cbr{f_1 = 0} $ and $ V \\cup \\cbr{f_2 = 0} $ would be two closed subsets which cover $ V $. Since $ T $ is closed and properly contained in $ V $, there exists $ g \\in k\\sbr{W}\\sbr{X, Y} $ which vanishes on $ T $ but not on $ V $. Since $ g $ does not vanish on $ V $, $ f $ does not divide $ g $. Since $ f $ has no factors of positive degree, we conclude that $ f $ and $ g $ have no common factors of positive degree. Hence we can use the resultant over the integral domain $ k\\sbr{W} $, by Theorem \\ref{thm:domainresultant}, to say that\n$$ \\Res_{d, e}\\br{f, g} \\ne 0, \\qquad d = \\deg f, \\qquad e = \\deg g $$\nin $ k\\sbr{W} $. Now $ \\Res_{d, e}\\br{f, g} $ is an element of $ k\\sbr{W} $, that is it is a regular function on $ W $. Since it is not identically zero, we can choose $ w \\in W $ such that $ \\Res_{d, e}\\br{f, g}\\br{w} \\ne 0 $. This is the same as saying that\n$$ \\Res_{d, e}\\br{f_w, g_w} \\ne 0, $$\nwhere $ f_w, g_w \\in k\\sbr{X, Y} $ are the polynomials obtained from $ f $ and $ g $ by evaluating their coefficients at $ w $. By the defining property of the resultant over the algebraically closed field $ k $, we conclude that $ f_w $ and $ g_w $ have no common root in $ \\PP^1 $. But $ \\pi^{-1}\\br{w} \\cap T $ is contained in the set of common roots of $ f_w $ and $ g_w $. Thus $ \\pi^{-1}\\br{w} \\cap T = \\emptyset $, that is $ w \\notin \\pi\\br{T} $.\n\\end{proof}\n\nLemma \\ref{lem:projectioneither} needed $ \\PP^1 \\times \\AA^m $ in order to use completeness, here we need $ \\AA^{1 + m} \\to \\AA^m $ so that we can set up an induction\n$$ \\AA^{2 + m} \\to \\AA^{1 + m} \\to \\AA^m, $$\netc.\n\n\\begin{lemma}\n\\label{lem:projectionopen}\nLet $ \\pi : \\AA^{1 + m} \\to \\AA^m $ denote projection onto the last $ m $ coordinates. Let $ Z \\subseteq \\AA^{1 + m} $ be an irreducible locally closed subset. Let $ W $ be the Zariski closure of $ \\pi\\br{Z} $ in $ \\AA^m $. Then $ \\pi\\br{Z} $ contains a non-empty open subset of $ W $.\n\\end{lemma}\n\n\\begin{proof}\nWe embed $ \\AA^{1 + m} = \\AA^1 \\times \\AA^m $ into $ \\PP^1 \\times \\AA^m $, in order to be able to use Lemma \\ref{lem:projectioneither}. Let $ V $ be the closure of $ Z $ in $ \\PP^1 \\times \\AA^m $. By completeness, in Theorem \\ref{thm:projectionclosed}, $ \\pi\\br{V} $ is closed in $ \\AA^m $, so $ \\pi\\br{V} = W $. Let $ T = V \\setminus Z $. Since $ Z $ is locally closed, $ T $ is a closed subset of $ \\PP^1 \\times \\AA^m $. We can now apply Lemma \\ref{lem:projectioneither}. We get two cases.\n\\begin{enumerate}[label=Case \\arabic*., leftmargin=0.5in]\n\\item $ \\pi\\br{T} $ is strictly contained in $ \\pi\\br{V} $. Completeness tells us that $ \\pi\\br{T} $ is closed in $ \\AA^m $. Hence $ W \\setminus \\pi\\br{T} $ is an open subset of $ W $. Since $ Z = V \\setminus T $, it is clear that $ W \\setminus \\pi\\br{T} $ is contained in $ \\pi\\br{Z} $. And $ W \\setminus \\pi\\br{T} $ is non-empty because $ \\pi\\br{T} \\ne W $.\n\\item $ V = \\PP^1 \\times W $. In this case, an element $ w \\in W $ is in the image of $ Z $ if and only if $ \\PP^1 \\times \\cbr{w} $ is not contained in $ T $. That is,\n$$ \\pi\\br{Z} = \\cbr{w \\in W \\st \\PP^1 \\times \\cbr{w} \\not\\subseteq T}. $$\nIt is easy to see that the complement\n$$ W \\setminus \\pi\\br{Z} = \\cbr{w \\in W \\st \\PP^1 \\times \\cbr{w} \\subseteq T} $$\nis a closed subset of $ W $, so $ \\pi\\br{Z} $ is open in $ W $. And $ \\pi\\br{Z} $ is certainly non-empty.\n\\end{enumerate}\n\\end{proof}\n\n\\pagebreak\n\n\\begin{corollary}\n\\label{cor:projectionopen}\nLet $ \\pi : \\AA^{n + m} \\to \\AA^m $ denote projection onto the last $ m $ coordinates. Let $ Z \\subseteq \\AA^{n + m} $ be a constructible subset. Let $ W $ be the Zariski closure of $ \\pi\\br{Z} $ in $ \\AA^m $. Then $ \\pi\\br{Z} $ contains a dense open subset of $ W $.\n\\end{corollary}\n\n\\begin{proof}\nIt suffices to assume that $ Z $ is an irreducible locally closed set. If it was not, we could simply break it up first into finitely many locally closed sets, by the definition of constructible sets, and then break up each of these into finitely many irreducible components. The proof is by induction on $ n $. The base case is Lemma \\ref{lem:projectionopen}. We factor $ \\pi : \\AA^{n + m} \\to \\AA^m $ as\n$$ \\AA^{n + m} \\xrightarrow{p} \\AA^{1 + m} \\xrightarrow{q} \\AA^m. $$\nLet $ W' $ be the Zariski closure of $ p\\br{Z} $. By induction, $ p\\br{Z} $ contains a dense open subset $ U \\subseteq W' $. Since $ U $ is dense in $ W' $, $ q\\br{U} $ is dense in $ q\\br{W'} = \\pi\\br{Z} $ which in turn is dense in $ W $. Therefore $ W $ is equal to the closure of $ q\\br{U} $ in $ \\AA^m $. Then $ U $ is an open subset of the closed subset $ W' $ in $ \\AA^{1 + m} $, so $ U $ is locally closed in $ \\AA^{1 + m} $. Hence we can apply Lemma \\ref{lem:projectionopen} to conclude that $ q\\br{U} $ contains a non-empty open subset of $ W $. Because $ Z $, and hence $ W $, is irreducible, this non-empty open subset is dense in $ W $.\n\\end{proof}\n\n\\begin{lemma}\n\\label{lem:projectionconstructible}\nLet $ \\pi : \\AA^{n + m} \\to \\AA^m $ denote projection onto the last $ m $ coordinates. If $ Z \\subseteq \\AA^{n + m} $ is a constructible subset, then $ \\pi\\br{Z} $ is constructible.\n\\end{lemma}\n\n\\begin{proof}\nLet $ W_1 $ be the Zariski closure of $ \\pi\\br{Z} $. By Corollary \\ref{cor:projectionopen}, $ \\pi\\br{Z} $ contains a dense open subset $ U_1 \\subseteq W_1 $. Then $ Z_1 = \\pi^{-1}\\br{W_1 \\setminus U_1} $ is a proper closed subset of $ Z $. In particular $ Z_1 $ is itself constructible. Now repeat this argument. Let $ W_2 $ be the Zariski closure of $ \\pi\\br{Z_1} $. By Corollary \\ref{cor:projectionopen}, $ \\pi\\br{Z_1} $ contains a dense open subset $ U_2 \\subseteq W_2 $. Then $ Z_2 = \\pi^{-1}\\br{W_2 \\setminus U_2} $ is a proper closed subset of $ Z_1 $. We repeat this, getting $ W_3, U_3, Z_3 $, etc. Now $ \\pi\\br{Z_1} $ is contained in the closed set $ W_1 \\setminus U_1 $, so $ W_2 \\subseteq W_1 \\setminus U_1 $. Since $ U_1 \\ne \\emptyset $, $ W_2 \\ne W_1 $. Similarly, $ W_3 \\ne W_2 $ etc. Hence we get a strictly descending chain of closed subsets of $ \\AA^m $,\n$$ W_1 \\supsetneq W_2 \\supsetneq \\dots. $$\nBy the noetherian property of the Zariski topology, in Lemma \\ref{lem:descendingchain}, this chain must terminate. So we eventually get to $ W_r = \\emptyset $. But then $ \\pi\\br{Z_{r - 1}} \\subseteq W_r $, so $ Z_{r - 1} $ is empty. We cannot go back any further than that, since it is entirely possible that $ U_{r - 1} = W_{r - 1} $. Then\n$$ \\pi\\br{Z} = U_1 \\cup \\pi\\br{Z_1} = \\dots = U_1 \\cup \\dots \\cup U_{r - 1}. $$\nEach $ U_i $ is an open subset of a closed subset of $ \\AA^n $, so we conclude that $ \\pi\\br{Z} $ is constructible. Since $ q\\br{U} \\subseteq \\pi\\br{Z} $, this completes the proof.\n\\end{proof}\n\nThis argument, building a descending chain of closed subsets and concluding that it terminates, is called \\textbf{noetherian induction}. Now we can finish the proof of Theorem \\ref{thm:chevalleytheorem}. By considering the graph of a regular map $ \\phi : V \\to W $, just as for completeness, we can reduce it to the following.\n\n\\begin{theorem}\n\\label{thm:projectionconstructible}\nLet $ V $ and $ W $ be quasi-projective algebraic sets. The second projection $ \\pi_2 : V \\times W \\to W $ maps constructible sets to constructible sets.\n\\end{theorem}\n\n\\begin{proof}\nLet $ Z $ be a contructible subset of $ V \\times W $. Suppose that $ V \\subseteq \\PP^n $ and $ W \\subseteq \\PP^m $. Then $ Z $ is also constructible as a subset of $ \\PP^n \\times \\PP^m $, so we can replace $ V $ and $ W $ by $ \\PP^n $ and $ \\PP^m $. Let\n$$ U_i = \\cbr{\\sbr{x_0 : \\dots : x_m} \\in \\PP^m \\st x_i \\ne 0}. $$\nThe $ U_i $ form an open cover for $ \\PP^m $, and each of them is isomorphic to $ \\AA^m $. If each set $ Z \\cap \\br{V \\times U_i} $ has a constructible image, then $ \\pi\\br{Z} $ is a finite union of constructible sets, so is itself constructible. So it suffices to prove Theorem \\ref{thm:projectionconstructible} for $ W = \\AA^m $. A similar argument allows us to replace $ V = \\PP^n $ by $ V = \\AA^n $. Thus the proof of Theorem \\ref{thm:projectionconstructible} is reduced to Lemma \\ref{lem:projectionconstructible}.\n\\end{proof}\n\nThe real hard work in this argument was in the proof of Lemma \\ref{lem:projectioneither} and Lemma \\ref{lem:projectionopen}, while the rest consisted of a series of relatively simple steps allowing us to gradually simplify the varieties and regular maps which we had to work with. A sequence of reductions like this, before you do the hard work on a simpler case of the original problem, is a very common technique in algebraic geometry, common enough to be given its own name, \\textbf{d\\'evissage}.\n\n\\pagebreak\n\n\\section{Dimension}\n\n\\subsection{Definitions and examples}\n\n\\subsubsection{Dimension and transcendence degree}\n\n\\lecture{23}{Thursday}{05/03/20}\n\nWe want to define the dimension of algebraic varieties. There are several different definitions, all equivalent but each being useful in different situations. None of these definitions is particularly obvious, so we begin by listing some properties that the dimension of an irreducible quasi-projective variety $ V $ ought to have. We only consider irreducible varieties here, because a reducible variety might have components of different dimensions so it is harder to be confident about what properties it should have.\n\\begin{enumerate}\n\\item $ \\dim V \\in \\NN $.\n\\item $ \\dim V = 0 $ if and only if $ V $ is a point. Remember that we are assuming that $ V $ is irreducible.\n\\item $ \\dim \\AA^n = \\dim \\PP^n = n $.\n\\item A hypersurface in $ \\AA^n $ or $ \\PP^n $ has dimension $ n - 1 $.\n\\item If $ U $ is an open subset of $ V $, then $ \\dim U = \\dim V $. Note that this holds for manifolds in differential geometry.\n\\item If $ V $ and $ W $ are birational, then $ \\dim V = \\dim W $. This follows from $ 5 $.\n\\end{enumerate}\nActually, we can generalise property $ 6 $ to something stronger than this. We do not need a birational map $ V \\dashrightarrow W $, just generically finite dominant rational maps, which are defined as follows.\n\n\\begin{definition*}\nLet $ V $ and $ W $ be irreducible quasi-projective varieties. A dominant rational map $ \\phi : V \\dashrightarrow W $ is \\textbf{generically finite} if there is a non-empty open set $ U \\subseteq W $ such that $ \\phi^{-1}\\br{x} $ is finite for every $ x \\in U $.\n\\end{definition*}\n\n\\begin{note*}\nThere is more than one possible reasonable definition of generically finite for non-dominant rational maps. I shall avoid the issue by only using the words generically finite when the map is dominant.\n\\end{note*}\n\nNow we expect the following.\n\\begin{itemize}\n\\item[$ 7 $.] If there exists a generically finite dominant rational map $ \\phi : V \\dashrightarrow W $, then $ \\dim V = \\dim W $.\n\\end{itemize}\nIt turns out that these properties are enough to tell us the dimension of every irreducible quasi-projective variety, thanks to the following lemma.\n\n\\begin{lemma}\nLet $ V $ be an irreducible quasi-projective variety. Then there exists a generically finite dominant rational map $ V \\dashrightarrow \\PP^d $ for some $ d $.\n\\end{lemma}\n\n\\begin{proof}\nBy Lemma \\ref{lem:quasiprojectiveaffine}, $ V $ has a non-empty affine open subset $ U \\subseteq V $. By Corollary \\ref{cor:irreduciblehypersurface}, which we used in the proof of the Nullstellensatz, $ U $ is birational to a hypersurface $ H $ in some affine space $ \\AA^n $. Taking the projective closure $ \\overline{H} $ of $ H $ in $ \\PP^n $, we conclude that $ V $ is birational to $ \\overline{H} $. Now projection from any point $ p \\in \\PP^n \\setminus \\overline{H} $ gives a generically finite dominant rational map $ \\overline{H} \\dashrightarrow \\PP^{n - 1} $.\n\\end{proof}\n\nUsing properties $ 3 $ and $ 7 $, we can calculate $ \\dim V $ by finding a generically finite dominant rational map $ V \\dashrightarrow \\PP^d $ and then saying that $ \\dim V = d $. There is one problem with this definition. Maybe we can find generically finite dominant rational maps from $ V $ to two different projective spaces, giving two values for $ \\dim V $. How do we know that they will all live in affine space of the same dimension? Fortunately this cannot happen, which is proved using the notion of transcendence degree from algebra.\n\n\\begin{theorem}\n\\label{thm:algebraicallyindependent}\nLet $ k $ and $ K $ be fields, with $ k \\subseteq K $. All maximal $ k $-algebraically independent sets in $ K $ have the same cardinality.\n\\end{theorem}\n\n\\begin{definition*}\nLet $ k $ and $ K $ be fields, with $ k \\subseteq K $. The \\textbf{transcendence degree} of the extension $ K $ over $ k $ is the cardinality of a maximal $ k $-algebraically independent set in $ K $.\n\\end{definition*}\n\n\\begin{note*}\nWe already made use of the idea of transcendence degree in the proof of Corollary \\ref{cor:irreduciblehypersurface}, even if we did not prove it. In the proof of Corollary \\ref{cor:irreduciblehypersurface}, we took a maximal $ k $-algebraically independent set $ z_1, \\dots, z_d $ in $ k\\br{V} $, then proved that $ V $ is birational to a hypersurface in $ \\AA^{d + 1} $. Theorem \\ref{thm:algebraicallyindependent} shows that the value of $ d $ here is the same for all maximal $ k $-algebraically independent sets in $ k\\br{V} $.\n\\end{note*}\n\n\\pagebreak\n\n\\begin{definition*}\nThe \\textbf{dimension} of an irreducible quasi-projective variety $ V $ is the transcendence degree, over $ k $, of the field of rational functions $ k\\br{V} $.\n\\end{definition*}\n\nIt is easy to see that this definition satisfies all the above desired properties. This definition satisfies property $ 3 $ above, since $ k\\br{\\PP^n} = k\\br{\\AA^n} = k\\br{X_1, \\dots, X_n} $ has transcendence degree $ n $ because $ \\cbr{X_1, \\dots, X_n} $ is a maximal algebraically independent set, so $ \\dim \\AA^n = n $. It clearly also satisfies property $ 6 $. In particular, if $ V $ and $ W $ are birational, then they have the same dimension because $ k\\br{V} \\cong k\\br{W} $. We need to prove that it satisfies property $ 7 $. It will then be easy to deduce the rest of the properties listed above.\n\n\\begin{lemma}\nLet $ V $ and $ W $ be irreducible quasi-projective varieties. If $ \\phi : V \\dashrightarrow W $ is a generically finite dominant rational map, then\n$$ \\trdeg\\br{k\\br{V} / k} = \\trdeg\\br{k\\br{W} / k}. $$\n\\end{lemma}\n\n\\begin{proof}\nWe can replace $ V $ by the open subset $ \\dom \\phi $, so that $ \\phi $ becomes a regular map. Using Lemma \\ref{lem:quasiprojectiveaffine}, we can replace $ V $ and $ W $ by affine open subsets, and then replace $ V $ by the graph of $ \\phi $ in $ V \\times W $. Hence it suffices to assume that $ \\phi = \\eval{\\pi_2}_V $, where $ \\pi_2 $ is the projection $ \\AA^{m + n} \\to \\AA^n $, $ V $ is a closed subset of $ \\AA^{m + n} $, and $ W $ is the Zariski closure of $ \\pi_2\\br{V} $. By induction, by breaking up $ \\phi $ into projections $ \\AA^{m + n} \\to \\dots \\to \\AA^n $, we may reduce to the case $ m = 1 $. Since $ \\phi $ is a dominant rational map, it induces an injection of fields $ \\phi^* : k\\br{W} \\to k\\br{V} $. We have to prove that the resulting field extension $ k\\br{V} / \\phi^*k\\br{W} $ is algebraic, and hence that the transcendence degrees are the same. Look at the coordinate function $ X_1 $ on $ V $. This is the coordinate which is discarded by $ \\pi $. Because $ \\phi $ is a projection, $ X_2, \\dots, X_{1 + n} $ on $ V $ are all in $ \\phi^*k\\br{W} $ and so the field $ k\\br{V} $ is generated by $ \\phi^*k\\br{W} $ and $ X_1 $. Since $ \\phi $ is generically finite, $ V $ is strictly contained in $ W \\times \\AA^1 $. Hence there is a non-zero polynomial $ f \\in k\\sbr{W}\\sbr{X_{1 + n}} $ which vanishes on $ V $. This gives a $ k\\br{W} $-algebraic relation satisfied by $ \\eval{X_1}_V $ in $ k\\br{V} $. Now $ k\\br{V} $ is generated by $ k\\br{W} $ and $ \\eval{X_1}_V $, so $ k\\br{V} $ is algebraic over $ k\\br{W} $ as required.\n\\end{proof}\n\nThis allows us to restate the definition by saying, $ \\dim V = d $ if and only if there exists a generically finite dominant rational map $ V \\dashrightarrow \\PP^d $.\n\n\\lecture{24}{Friday}{06/03/20}\n\nLecture 24 is a problems class.\n\n\\subsubsection{Facts about dimension}\n\n\\lecture{25}{Monday}{09/03/20}\n\nWe begin with some simple facts.\n\n\\begin{fact*}\nLet $ V $ and $ W $ be irreducible quasi-projective algebraic varieties.\n\\begin{itemize}\n\\item If $ \\phi : V \\dashrightarrow W $ is a dominant rational map, then $ \\dim W \\le \\dim V $. This follows from the fact that $ \\phi^* $ is an injection $ k\\br{W} \\to k\\br{V} $.\n\\item $ \\dim V \\times W = \\dim V + \\dim W $. This holds because if $ \\phi : V \\dashrightarrow \\AA^d $ and $ \\psi : W \\dashrightarrow \\AA^e $ are generically finite dominant rational maps, then $ \\br{\\phi, \\psi} : V \\times W \\dashrightarrow \\AA^{d + e} $ is a generically finite dominant rational map.\n\\end{itemize}\n\\end{fact*}\n\n\\subsubsection{Dimension of closed subsets}\n\n\\begin{lemma}\n\\label{lem:subsetdimension}\nLet $ V $ be an irreducible quasi-projective variety and let $ W $ be an irreducible closed subset of $ V $. Then $ \\dim W \\le \\dim V $.\n\\end{lemma}\n\n\\begin{proof}\nIt suffices to prove Lemma \\ref{lem:subsetdimension} for irreducible $ V $ and $ W $. Using Lemma \\ref{lem:quasiprojectiveaffine}, we may assume that $ V $ and $ W $ are affine algebraic sets in some affine space $ \\AA^n $. Let $ d = \\dim V $. Then any $ d + 1 $ of the coordinate functions are algebraically dependent in $ k\\br{V} $. In other words, there exists a polynomial $ f \\in k\\sbr{T_1, \\dots, T_{d + 1}} $ such that $ f\\br{\\eval{X_{i_1}}_V, \\dots, \\eval{X_{i_{d + 1}}}_V} = 0 $ in $ k\\br{V} $. Since $ W \\subseteq V $, this relation still holds after restricting to $ W $, so $ f\\br{\\eval{X_{i_1}}_W, \\dots, \\eval{X_{i_{d + 1}}}_W} = 0 $ in $ k\\sbr{W} $. But the field of functions $ k\\br{W} $ is generated, as a $ k $-field, by $ \\eval{X_1}_W, \\dots, \\eval{X_n}_W $, so this establishes that $ \\trdeg\\br{k\\br{W} / k} \\le d $.\n\\end{proof}\n\nWe will later show that equality can only happen in Lemma \\ref{lem:subsetdimension} if $ W = V $. We could prove this algebraically now, but instead we will end the algebraic proofs using transcendence degree here and prove everything else geometrically. This means that we will need several steps before improving Lemma \\ref{lem:subsetdimension} to a strict inequality.\n\n\\pagebreak\n\n\\subsubsection{Dimension of a reducible variety}\n\nSo far we have defined the dimension of an irreducible quasi-projective variety. The \\textbf{dimension} of a reducible variety is defined to be the maximum of the dimensions of the irreducible components. To explain why this is a sensible definition, and why not minimum for example, note that if $ V = V_1 \\cup \\dots \\cup V_r $ are the irreducible components of $ V $, then $ V_i \\subseteq V $ so we should have $ \\dim V_i \\le \\dim V $ for each $ i $. Meanwhile, we could find $ W_i $ for each $ i $ such that $ V_i \\subseteq W_i $ and $ \\dim W_i = \\max\\br{\\dim V_1, \\dots, \\dim V_r} $. Then every irreducible component of $ W_1 \\cup \\dots \\cup W_r $ has the same dimension, so it makes sense to declare that $ \\dim\\br{W_1 \\cup \\dots \\cup W_r} $ is equal to $ \\dim W_i $ for all $ i $. But then $ V \\subseteq W_1 \\cup \\dots \\cup W_r $ so $ \\dim V \\le \\dim W_i = \\max\\br{\\dim V_1, \\dots, \\dim V_r} $.\n\n\\subsubsection{Intersection with a hyperplane}\n\nWe begin by studying intersections between a projective algebraic set and hypersurfaces. For today, just hyperplanes. This is much simpler for projective varieties than for quasi-projective varieties, because then we know that there can be no intersections hiding at infinity. The expectation is that, if $ V $ is an algebraic set and $ H $ is a hypersurface, then $ \\dim V \\cap H $ should usually be $ \\dim V - 1 $, because it is just adding one more equation to the equations defining $ V $. Before proving this, we need a couple of lemmas. Firstly, there is no room between a hypersurface and $ \\PP^n $ to squeeze in another irreducible algebraic set.\n\n\\begin{lemma}\n\\label{lem:hypersurfaceirreducible}\nLet $ H \\subseteq \\PP^n $ be a hyperplane, or more generally a hypersurface. Let $ V \\subseteq \\PP^n $ be an irreducible projective algebraic set. If $ V \\ne \\PP^n $ and $ V \\ne H $, then $ H \\not\\subseteq V $.\n\\end{lemma}\n\n\\begin{proof}\nLook at ideals of polynomials which vanish on $ H $ and $ V $.\n\\end{proof}\n\nSecondly, we need to know how projection interacts with dimension.\n\n\\begin{lemma}\n\\label{lem:projectiondimension}\nLet $ V \\subseteq \\PP^n $ be an irreducible projective algebraic set. Let $ p \\in \\PP^n $ and let $ Z \\subseteq \\PP^n $ be a hyperplane such that $ p \\notin Z $. Let $ \\pi : \\PP^n \\dashrightarrow Z $ be the projection from $ p $ onto $ Z $. If $ p \\notin V $, then $ \\pi\\br{V} $ is a Zariski closed subset of $ Z $ and $ \\eval{\\pi}_V : V \\to \\pi\\br{V} $ is generically finite, so $ \\dim \\pi\\br{V} = \\dim V $.\n\\end{lemma}\n\n\\begin{proof}\nThe projection $ \\pi $ is regular on $ \\PP^n \\setminus \\cbr{p} $, and in particular it is regular on $ V $. Since $ V $ is complete, $ \\pi\\br{V} $ is a closed subset of $ Z $. Now $ \\eval{\\pi}_V : V \\to \\pi\\br{V} $ is certainly dominant. Indeed it is surjective. In order to show that $ \\dim \\pi\\br{V} = \\dim V $, it suffices to show that $ \\eval{\\pi}_V $ is generically finite. Consider a point $ y \\in \\pi\\br{V} $. The preimage of $ y $ under $ \\eval{\\pi}_V $ is the intersection $ V \\cap \\L_{py} $, where $ \\L_{py} $ is the line through $ p $ and $ y $. Now $ V \\cap \\L_{py} $ is a closed subset of $ \\L_{py} $. Furthermore $ V \\cap \\L_{py} \\ne \\L_{py} $ because $ p \\notin V $. Because $ \\L_{py} \\cong \\PP^1 $, we conclude that $ V \\cap \\L_{py} $ must be finite. In other words $ \\eval{\\pi}_V^{-1}\\br{y} $ is finite for all $ y \\in \\pi\\br{V} $, and so $ \\eval{\\pi}_V $ is generically finite.\n\\end{proof}\n\nNow we are ready to prove the result on the dimension of intersection with a hyperplane. Note the exceptional cases. If $ H $ contains a component of $ V $ of maximum dimension, then $ \\dim V \\cap H = \\dim V $, while if $ \\dim V = 0 $ then $ V \\cap H $ might be empty. If $ \\dim V > 0 $, then $ V \\cap H \\ne \\emptyset $ by Lemma \\ref{lem:hyperplaneintersection}.\n\n\\begin{proposition}\n\\label{prop:hyperplanedimension}\nLet $ V \\subseteq \\PP^n $ be a projective algebraic set. Let $ H \\subseteq \\PP^n $ be a hyperplane which does not contain any irreducible component of $ V $. If $ \\dim V > 0 $, then $ V \\cap H $ is non-empty and $ \\dim V \\cap H = \\dim V - 1 $.\n\\end{proposition}\n\n\\begin{proof}\nFirst replace $ V $ by an irreducible component $ V_1 $ such that $ \\dim V_1 = \\dim V $. Thus we may assume that $ V $ is irreducible. The proof is by induction on $ n $, the dimension of the ambient space. The base case of the induction is when $ V = \\PP^n $. Remember we are inducting on $ n $, not $ \\dim V $. This is trivial, since $ V \\cap H = H \\cong \\PP^{n - 1} $ certainly has dimension $ n - 1 $. Otherwise, $ V \\ne \\PP^n $. We will project into $ \\PP^{n - 1} $. In order to use Lemma \\ref{lem:projectiondimension}, we need to project from a point $ p \\notin V $. In order for the projection to interact nicely with $ H $, we need $ p \\in H $. Fortunately, we can use Lemma \\ref{lem:hypersurfaceirreducible} to show that a suitable $ p $ exists. We are assuming $ V \\ne \\PP^n $ while the hypothesis of Proposition \\ref{prop:hyperplanedimension} tells us that $ V \\not\\subseteq H $, so $ V \\ne H $. Therefore by Lemma \\ref{lem:hypersurfaceirreducible}, $ H \\not\\subseteq V $, the opposite way round to our hypothesis, so we can select a point $ p \\in H $ such that $ p \\notin V $. Choose a hyperplane $ Z \\subseteq \\PP^n $ such that $ p \\notin Z $. It does not matter which we choose. Let $ \\pi : \\PP^n \\to Z $ be the projection from $ p $ onto $ Z $. Because $ p \\in H $, all lines through $ p $ and a point of $ H $ lie entirely in $ H $. Therefore $ x \\in H \\setminus \\cbr{p} $ if and only if $ \\pi\\br{x} \\in H \\cap Z $, and consequently $ \\pi\\br{V \\cap H} = \\pi\\br{V} \\cap \\br{H \\cap Z} $. This implies that $ \\pi\\br{V} \\not\\subseteq H \\cap Z $, because $ V \\not\\subseteq H $. By completeness, $ \\pi\\br{V} $ is a closed subset of $ Z \\cong \\PP^{n - 1} $, while $ H \\cap Z $ is a hyperplane in $ Z $. Furthermore, $ \\pi\\br{V} $ is irreducible and we have shown that $ \\pi\\br{V} \\not\\subseteq H \\cap Z $. Therefore, by induction, we have $ \\dim \\pi\\br{V} \\cap \\br{H \\cap Z} = \\dim \\pi\\br{V} - 1 $. We conclude by using Lemma \\ref{lem:projectiondimension}, which tells us that $ \\dim \\pi\\br{V} = \\dim V $ and $ \\dim \\pi\\br{V \\cap H} = \\dim \\pi\\br{V} \\cap \\br{H \\cap Z} $.\n\\end{proof}\n\n\\pagebreak\n\n\\subsubsection{The Veronese embedding}\n\n\\lecture{26}{Thursday}{12/03/20}\n\nIn order to generalise Proposition \\ref{prop:hyperplanedimension} from intersections between $ V $ and hyperplanes to intersections with hypersurfaces, we use the Veronese embedding to reduce this to the case of an intersection with a hyperplane. This is defined as follows. Let $ d, n \\in \\ZZ_{\\ge 0} $ and let $ N = \\binom{n + d}{d} - 1 $. There are $ N + 1 $ monomials of degree $ d $ in variables $ X_0, \\dots, X_n $, expressions of the form\n$$ X_0^{a_0} \\dots X_n^{a_n}, \\qquad a_0, \\dots, a_n \\in \\ZZ_{\\ge 0} \\qquad a_0 + \\dots + a_n = d. $$\nWe define a regular map $ \\nu_{n, d} : \\PP^n \\to \\PP^N $ by writing down all these monomials of degree $ d $, in some order.\n\n\\begin{example*}\nFor $ n = d = 2 $ we get $ N = 5 $ and\n$$ \\nu_{2, 2}\\br{\\sbr{X_0 : X_1 : X_2}} = \\sbr{X_0^2 : X_1^2 : X_2^2 : X_0X_1 : X_1X_2 : X_0X_2}. $$\n\\end{example*}\n\nThis is called the \\textbf{degree $ d $ Veronese embedding} of $ \\PP^n $. By completeness, the image of $ \\nu_{n, d} $ is a projective algebraic set $ V_{n, d} \\subseteq \\PP^N $. One can write down explicit polynomials defining this algebraic set, since they are determinants of $ 2 \\times 2 $ matrices. Importantly, $ \\nu_{n, d} $ is an isomorphism $ \\PP^n \\to V_{n, d} $, and proving this is elementary but the notation gets pretty complicated. The benefit of doing all this is that, if $ H \\subseteq \\PP^n $ is a hypersurface defined by some homogeneous polynomial $ f = \\sum_I a_I\\underline{X}^I $ of degree $ d $, then because the monomials of degree $ d $ become individual homogeneous coordinates via the Veronese embedding, the equation for $ \\nu_{n, d}\\br{H} $ is a linear equation $ \\sum_I a_IZ_I = 0 $. Thus $ \\nu_{n, d}\\br{H} = V_{n, d} \\cap Z $ for some hyperplane $ Z \\subseteq \\PP^N $. Therefore, instead of studying the intersection between $ V \\subseteq \\PP^n $ and a hypersurface $ H \\subseteq \\PP^n $, we can instead study the intersection between $ \\nu_{n, d}\\br{V} \\subseteq V_{n, d} \\subseteq \\PP^N $ and a hyperplane $ Z \\subseteq \\PP^N $. Because $ \\nu_{n, d} $ is an isomorphism, we can use Proposition \\ref{prop:hyperplanedimension} to deduce the same result for intersections with hypersurfaces.\n\n\\begin{theorem}\n\\label{thm:projectivedimension}\nLet $ V \\subseteq \\PP^n $ be a projective algebraic set. Let $ H \\subseteq \\PP^n $ be a hypersurface which does not contain any irreducible component of $ V $. If $ \\dim V > 0 $, then $ V \\cap H $ is non-empty and $ \\dim V \\cap H = \\dim V - 1 $.\n\\end{theorem}\n\nOn the other hand, it is much harder to tell what the dimension will be for the intersection between $ V $ and two or more hyperplanes, since the problem is that $ H_2 $ must satisfy the condition that it does not contain any irreducible component of $ V \\cap H_1 $, and it may be hard to tell whether this happens or not.\n\n\\subsubsection{Dimension of proper closed subsets}\n\nI mentioned last time that we can strengthen Lemma \\ref{lem:subsetdimension} to a strict inequality, as long as $ W \\ne V $. In this lemma, it is essential that $ V $ is irreducible, whereas in Lemma \\ref{lem:subsetdimension}, that condition is not necessary.\n\n\\begin{lemma}\n\\label{lem:properdimension}\nLet $ V $ be an irreducible quasi-projective variety and let $ W $ be a closed subset of $ V $. If $ W \\ne V $, then $ \\dim V < \\dim W $.\n\\end{lemma}\n\n\\begin{proof}\nSuppose that $ V $ is a quasi-projective algebraic set in $ \\PP^n $. Let $ \\overline{V} $ and $ \\overline{W} $ denote the closures of $ V $ and $ W $ respectively in $ \\PP^n $. Because $ W $ is closed in $ V $ and not equal to $ V $, $ \\overline{V} \\ne \\overline{W} $. So we can pick a homogeneous polynomial $ f \\in k\\sbr{X_0, \\dots, X_n} $ which vanishes on $ \\overline{W} $ but not on $ \\overline{V} $. Let $ H $ be the hypersurface defined by $ f $. Then $ \\overline{W} \\subseteq \\overline{V} \\cap H $ so Theorem \\ref{thm:projectivedimension} implies that $ \\dim \\overline{W} \\le \\dim \\overline{V} \\cap H = \\dim \\overline{V} - 1 $. Since $ V $ is open in $ \\overline{V} $, $ \\dim V = \\dim \\overline{V} $ and similarly $ \\dim W = \\dim \\overline{W} $ which completes the proof.\n\\end{proof}\n\n\\subsubsection{Dimension and equations}\n\nWhat is the dimension of a subset of $ \\PP^n $ defined by $ r $ homogeneous polynomial equations? We can try to work this out by applying Theorem \\ref{thm:projectivedimension} repeatedly. The zero set of a single homogeneous polynomial $ f_1 $ is a hypersurface $ H_1 $, which we know has dimension $ n - 1 $. The zero set of two homogeneous polynomials $ f_1 $ and $ f_2 $ is an intersection $ H_1 \\cap H_2 $ of two hypersurfaces. If $ f_1 $ and $ f_2 $ have no common factor, then $ H_2 $ does not contain any irreducible component of $ H_1 $ and so Theorem \\ref{thm:projectivedimension} tells us that $ \\dim H_1 \\cap H_2 = n - 2 $. But once we look at three homogeneous polynomials $ f_1, f_2, f_3 $, we try to apply Theorem \\ref{thm:projectivedimension} to $ V = H_1 \\cap H_2 $ so we have to ask whether $ H_3 $ contains any irreducible component of $ H_1 \\cap H_2 $. There is no easy condition to tell whether this is true. Consider the examples from problem sheets $ 1 $ and $ 2 $. There were algebraic sets defined by two polynomials with no common factors. Working out the irreducible components of the intersection was hard work. The best we can say is $ \\dim H_1 \\cap H_2 \\cap H_3 = n - 2 $ or $ \\dim H_1 \\cap H_2 \\cap H_3 = n - 3 $. As we repeat the process, controlling the irreducible components only gets harder. All we can say is that for each extra equation, the dimension goes down by either zero or one. By induction, all we get is the following inequality.\n\n\\pagebreak\n\n\\begin{proposition}\n\\label{prop:equationsdimension}\nLet $ f_1, \\dots, f_r \\in k\\sbr{X_0, \\dots, X_n} $ be homogeneous polynomials and let $ V \\subseteq \\PP^n $ be the zero set of these polynomials. If $ r \\le n $, then $ V \\ne \\emptyset $ and $ \\dim V \\ge n - r $.\n\\end{proposition}\n\n\\begin{proof}\nLet $ H_i $ be the hypersurface defined by the equation $ f_i = 0 $. By Theorem \\ref{thm:projectivedimension}, if $ H_i $ does not contain any irreducible component of $ H_1 \\cap \\dots \\cap H_{i - 1} $, then $ \\dim H_1 \\cap \\dots \\cap H_i = \\dim H_1 \\cap \\dots \\cap H_{i - 1} - 1 $. On the other hand, if $ H_i $ does contain an irreducible component of $ H_1 \\cap \\dots \\cap H_{i - 1} $, then the dimension might not go down at all. In any case, $ \\dim H_1 \\cap \\dots \\cap H_i \\ge \\dim H_1 \\cap \\dots \\cap H_{i - 1} - 1 $. Iterating this proves Proposition \\ref{prop:equationsdimension}.\n\\end{proof}\n\n\\subsubsection{Complete intersections}\n\nWe saw that if you take $ r $ homogeneous polynomials, their zero set in $ \\PP^n $ has dimension at least $ n - r $. We cannot insist that the dimension be equal to $ n - r $, because the zero set of one of the polynomials might contain the zero set of the others. In reverse, we can ask the following. If $ V \\subseteq \\PP^n $ is a projective algebraic set of dimension $ n - r $, do there exist $ r $ homogeneous polynomials which define $ V $? The answer is not always. There are two relevant definitions. The first one is more in the style of this course, but the second one turns out to be more natural because it gives more algebraic information.\n\n\\begin{definition*}\nLet $ V \\subseteq \\PP^n $ be an algebraic set of dimension $ n - r $. Then $ V $ is a \\textbf{set-theoretic complete intersection} if there exist $ r $ homogeneous polynomials such that $ V $ is the zero set of these polynomials, and $ V $ is a \\textbf{complete intersection} if there exist $ r $ homogeneous polynomials which generate the ideal of $ V $.\n\\end{definition*}\n\nBeing a complete intersection is a stronger property than being a set-theoretic complete intersection.\n\n\\begin{example*}\n\\hfill\n\\begin{itemize}\n\\item A set of three non-collinear points in $ \\PP^2 $ is a set-theoretic complete intersection but not a complete intersection, since there exist two polynomials defining this set, but you need three polynomials to generate its ideal.\n\\item An irreducible example is the twisted cubic which we saw earlier. It is the one-dimensional algebraic set $ C \\subseteq \\PP^3 $ defined by the three equations\n$$ WY - X^2 = 0, \\qquad WZ - XY = 0, \\qquad XZ - Y^2 = 0. $$\nAny two of these equations define a one-dimensional algebraic set which has $ C $ as an irreducible component, but also has another irreducible component. It is possible to find two polynomials which define the set $ C $, for example\n$$ WY - X^2 = 0, \\qquad WZ^2 - 2XYZ + Y^3 = 0. $$\nBut two polynomials cannot generate the ideal of $ C $. The earlier three polynomials do generate the ideal of $ C $.\n\\item Take the two planes in $ \\PP^4 $,\n$$ P_1 = \\cbr{x \\in \\PP^4 \\st x_1 = x_2 = 0}, \\qquad P_2 = \\cbr{x \\in \\PP^4 \\st x_3 = x_4 = 0}. $$\nThese intersect in only one point, namely $ \\sbr{1 : 0 : 0 : 0 : 0} $. The union $ P_1 \\cup P_2 $ has dimension two but it needs four equations to define it.\n\\item One can also find examples of irreducible two-dimensional algebraic sets of $ \\PP^4 $ which are not set-theoretic complete intersections, with a singularity which looks like the intersection point of the two planes in $ P_1 \\cup P_2 $.\n\\end{itemize}\n\\end{example*}\n\nWe had to go to $ \\PP^4 $ to give explicit examples of non-set-theoretic complete intersections. It is an open question whether every irreducible algebraic set in $ \\PP^3 $ is a set-theoretic complete intersection.\n\n\\subsubsection{Generalising to quasi-projective varieties}\n\nTheorem \\ref{thm:projectivedimension} applies to irreducible quasi-projective algebraic sets $ V \\subseteq \\PP^n $ as well as projective algebraic sets, except that for a quasi-projective algebraic set it can happen that $ V \\cap H = \\emptyset $, since Lemma \\ref{lem:hyperplaneintersection} applies only to projective algebraic sets. The precise statement is as follows.\n\n\\pagebreak\n\n\\begin{theorem}\n\\label{thm:quasiprojectivedimension}\nLet $ V \\subseteq \\PP^n $ be an irreducible quasi-projective algebraic set. Let $ H \\subseteq \\PP^n $ be a hypersurface which does not contain $ V $. If $ V \\cap H \\ne \\emptyset $, then $ \\dim V \\cap H = \\dim V - 1 $.\n\\end{theorem}\n\nThis is much harder to prove than Theorem \\ref{thm:projectivedimension}, so we will omit the proof. One might attempt to prove Theorem \\ref{thm:quasiprojectivedimension} by writing $ V $ as $ \\overline{V} \\cap U $, where $ \\overline{V} $ is the closure of $ V $ in $ \\PP^n $ and $ U $ is an open set and then applying Theorem \\ref{thm:projectivedimension} to $ \\overline{V} $. A priori, the problem with this is that the maximum-dimension components of $ \\overline{V} \\cap H $ might be contained in the closed set which is the complement of $ U $, and then $ V \\cap H $ would have dimension less than $ \\dim \\overline{V} \\cap H = \\dim V - 1 $. Actually this cannot happen, since with harder work we can show that every irreducible component of $ \\overline{V} \\cap H $ has dimension equal to $ \\dim V - 1 $. You can do this either geometrically or using an algebraic result called Krull's Hauptidealsatz. Of course the non-emptiness part of Proposition \\ref{prop:equationsdimension} does not generalise to affine sets, but the dimension inequality does provided we assume that the set is non-empty.\n\n\\subsubsection{Topological definition of dimension}\n\n\\lecture{27}{Friday}{13/03/20}\n\nOur previous definition of dimension was algebraic. We can also describe the dimension of a projective variety in terms of its topology.\n\n\\begin{theorem}\n\\label{thm:topologicaldimension}\nLet $ V $ be a projective variety. The dimension of $ V $ is the maximum $ d \\in \\ZZ $ such that there exists a chain of irreducible closed subsets\n$$ V \\supseteq V_d \\supsetneq \\dots \\supsetneq V_0 \\supsetneq \\emptyset. $$\n\\end{theorem}\n\nSome care is required in the statement of Theorem \\ref{thm:topologicaldimension} to get the numbering right. The point is that $ \\dim V_i = i $, so $ V_0 $ is still non-empty.\n\n\\begin{note*}\n$ V = V_d $ if and only if $ V $ is irreducible. All the other inclusions must be strict.\n\\end{note*}\n\nIn Theorem \\ref{thm:topologicaldimension}, it is essential to require all the $ V_i $ to be irreducible. Otherwise we could make the chain arbitrarily long by inserting reducible sets with more and more components, all of dimension $ i $, in between $ V_i $ and $ V_{i + 1} $.\n\n\\begin{proof}\nFirst we prove that such a sequence with $ d = \\dim V $ exists. Choose $ V_d $ to be an irreducible component of $ V $ whose dimension is equal to $ \\dim V $. Choose $ H $ as in Proposition \\ref{prop:hyperplanedimension} applied to $ V_d $. Let $ V_{d - 1} $ be an irreducible component in $ V_d \\cap H $ such that $ \\dim V_{d - 1} = \\dim V_d \\cap H = \\dim V - 1 $. We can repeat this procedure, getting $ V_i \\subsetneq V_{i + 1} $ with $ \\dim V_i = i $ until we get to $ V_0 $ with $ \\dim V_0 = 0 $. In the other direction, to show that there is no such sequence with $ d > \\dim V $, this follows immediately from the fact that $ \\dim V_i < \\dim V_{i + 1} $, by Lemma \\ref{lem:properdimension}.\n\\end{proof}\n\n\\subsubsection{Generalising to quasi-projective varieties}\n\nJust like Theorem \\ref{thm:projectivedimension}, Theorem \\ref{thm:topologicaldimension} generalises to quasi-projective varieties as well as projective varieties. We will omit the proof, but it is not much harder. The idea is to apply the same argument to the projective closure $ \\overline{V_d} $. Almost all hyperplanes give $ \\dim \\overline{V_d} \\cap H = \\dim V - 1 $, but only a few hyperplanes cause trouble by having a component of $ \\overline{V_d} \\cap H $ which does not intersect $ V_d $. So it is possible to find some hyperplane which gives $ \\dim V_d \\cap H = \\dim V - 1 $ and then repeat. However, Theorem \\ref{thm:topologicaldimension} is not really strong enough to be useful.\n\n\\begin{example*}\nIn $ \\PP^n $, we can write down a chain of closed subsets\n$$ \\PP^n \\supsetneq \\dots \\supsetneq \\PP^1 \\supsetneq \\cbr{\\text{point}} \\supsetneq \\emptyset. $$\nThis chain is maximal, so we cannot insert another irreducible closed subset anywhere in the middle of it. But just exhibiting this chain, together with Theorem \\ref{thm:topologicaldimension}, is not enough to prove that $ \\dim \\PP^n = n $. Maybe there is a completely different chain which is longer.\n\\end{example*}\n\nIt turns out that that cannot happen. One can prove that every maximal chain of irreducible closed subsets in an irreducible quasi-projective variety $ V $ has length equal to $ \\dim V $. This is another hard theorem, requiring the same work as proving Theorem \\ref{thm:quasiprojectivedimension}, about the intersection of a quasi-projective algebraic set with a hypersurface.\n\n\\pagebreak\n\n\\subsection{Counting dimensions of parameter spaces}\n\n\\subsubsection{Fibre dimension theorem}\n\nWe have now seen several definitions of dimension, via transcendence degree, via rational maps to hypersurfaces or to affine space, and via chains of closed subsets. None of these is easy to compute for specific examples, except in simple cases, since knowing that the chain of closed subsets definition works for any maximal chain means that it is sometimes usable. When we want to calculate the dimension of a particular variety, we often use the following powerful theorem.\n\n\\begin{theorem}\n\\label{thm:fibredimension}\nLet $ V $ and $ W $ be irreducible quasi-projective varieties and let $ \\phi : V \\to W $ be a surjective regular map. Then\n\\begin{enumerate}\n\\item for every $ w \\in W $, $ \\dim \\phi^{-1}\\br{w} \\ge \\dim V - \\dim W $, and\n\\item there exists a non-empty open subset $ U \\subseteq W $ such that $ \\dim \\phi^{-1}\\br{w} = \\dim V - \\dim W $ for all $ w \\in U $.\n\\end{enumerate}\n\\end{theorem}\n\nThe sets $ \\phi^{-1}\\br{w} $ for $ w \\in W $ are called the \\textbf{fibres} of $ \\phi $. Consequently,\n$$ \\dim V - \\dim W = \\min_{w \\in W} \\dim \\phi^{-1}\\br{w}. $$\n\n\\begin{example*}\nConsider the projection from $ \\AA^{n + m} $ to $ \\AA^n $. All the fibres are copies of $ \\AA^m $, which has dimension equal to $ \\dim \\AA^{n + m} - \\dim \\AA^n $.\n\\end{example*}\n\nPart $ 2 $ of Theorem \\ref{thm:fibredimension} tells us that most fibres have the expected dimension, as in this example, but there might be a proper closed subset of exceptions. Part $ 1 $ of Theorem \\ref{thm:fibredimension} tells us that for the exceptional fibres, the dimension is always bigger than expected. It is complicated to write down examples of surjective maps where there is a non-empty exceptional set using equations. So I shall cheat and give an example which is not surjective, only dominant, so Theorem \\ref{thm:fibredimension} does not actually apply to this example, but it still illustrates the idea that fibre dimension gets bigger over a closed subset.\n\n\\begin{example*}\nConsider\n$$ \\function[\\phi]{\\AA^2}{\\AA^2}{\\br{x, y}}{\\br{x, xy}}. $$\nConsider the vertical line\n$$ L_x = \\cbr{\\br{x, y} \\st y \\in k}. $$\nWhen $ x \\ne 0 $, $ \\phi $ restricts to an isomorphism $ L_x \\to L_x $. But when $ x = 0 $, $ \\phi $ maps all of $ L_0 $ down to $ \\br{0, 0} $. Hence the image of $ \\phi $ is $ \\br{\\AA^2 \\setminus \\cbr{\\br{0, y}}} \\cup \\cbr{\\br{0, 0}} $. We see that, above the open set $ \\cbr{\\br{x, y} \\st x \\ne 0} $, the fibres of $ \\phi $ are single points, that is with dimension $ 2 - 2 = 0 $. On the other hand, above the point $ \\br{0, 0} $, the fibre $ \\phi^{-1}\\br{\\br{0, 0}} $ is a line, so has dimension $ 1 \\ge 2 - 2 $.\n\\end{example*}\n\nWe will not prove Theorem \\ref{thm:fibredimension}. The proof uses similar methods to Theorem \\ref{thm:quasiprojectivedimension}, plus an induction. We generally use Theorem \\ref{thm:fibredimension} in situations where we know the dimension of either $ V $ or $ W $ and want to work out the other. If we can work out $ \\dim \\phi^{-1}\\br{w} $ for just a single $ w \\in W $, then we get an inequality. If we can work out $ \\dim \\phi^{-1}\\br{w} $ for $ w $ in some open set then we can work out the desired dimension exactly. An importantly special case is if there exists $ w $ such that $ \\dim \\phi^{-1}\\br{w} = 0 $, then $ \\dim V = \\dim W $.\n\n\\lecture{28}{Monday}{16/03/20}\n\nLecture 28 is a class test.\n\n\\subsubsection{Universal family of hypersurfaces}\n\n\\lecture{29}{Thursday}{19/03/20}\n\nThe fibre dimension theorem is particularly useful when applied to families of algebraic varieties and parameter spaces. These are a powerful feature of algebraic geometry, since often we can consider some collection of algebraic varieties, and construct another algebraic variety which has one point for each variety in the collection. We may also be able to fit all the varieties of the collection together into a single big algebraic variety. This is different form other forms of geometry, where a family of objects rarely forms an object of the same type.\n\n\\pagebreak\n\n\\begin{definition*}\nLet $ B $ be a quasi-projective variety. A \\textbf{family of projective algebraic sets} over $ B $ is a Zariski closed subset $ \\VVV \\subseteq B \\times \\PP^n $. For each $ b \\in B $, we write\n$$ \\VVV_b = \\cbr{x \\in \\PP^n \\st \\br{b, x} \\in \\VVV}, $$\nand call this a \\textbf{fibre} of $ \\VVV $. The set $ B $ is called the \\textbf{base} or \\textbf{parameter space} of the family.\n\\end{definition*}\n\nThis definition might seem rather abstract. To give some idea of what is going on, we will look at a simple example, since we will see some more complex examples later.\n\n\\begin{example*}\nA hypersurface of degree $ d $ in $ \\PP^n $ means the zero set of a non-zero homogeneous polynomial in $ k\\sbr{X_0, \\dots, X_n} $ of degree $ d $. Let $ \\V_{n, d} $ denote the space of homogeneous polynomials in $ k\\sbr{X_0, \\dots, X_n} $ of degree $ d $, and these polynomials form a vector space of dimension $ \\dim \\V_{n, d} = \\binom{n + d}{d} $. If one homogeneous polynomial is a scalar multiple of another, then they define the same hypersurface. Let $ \\P_{n, d} $ denote the projective space associated with $ \\V_{n, d} $, that is\n$$ \\P_{n, d} = \\br{\\V_{n, d} \\setminus \\cbr{0}} / \\text{scalars} \\cong \\PP^N, \\qquad N = \\binom{n + d}{d} - 1. $$\nFor a polynomial $ f \\in \\V_{n, d} $, let us write $ \\sbr{f} $ for the corresponding point in $ \\P_{n, d} $. Using the basis for $ \\V_{n, d} $ which consists of the monomials\n$$ X_0^{i_0} \\dots X_n^{i_n}, \\qquad i_0 + \\dots + i_n = d, $$\nwe see that the homogeneous coordinates of $ \\sbr{f} \\in \\P_{n, d} $ are given by the coefficients of $ f $. Each non-zero polynomial $ f \\in \\V_{n, d} $ defines a hypersurface $ \\HHH_f \\subseteq \\PP^n $. If $ f $ is a scalar multiple of $ g $, then they define the same hypersurface, $ \\HHH_f = \\HHH_g $. This is not quite an if and only if, because things can go wrong with polynomials that do not generate a radical ideal. Try to come up with an example. Thus, instead of labelling hypersurfaces by polynomials $ f \\in \\V_{n, d} $ we can label them instead by points in $ \\P_{n, d} $. Hence we get a hypersurface $ \\HHH_{\\sbr{f}} $ associated with each point $ \\sbr{f} \\in \\P_{n, d} $. The homogeneous coordinates of $ f $ form the coefficients of the polynomial defining $ \\HHH_{\\sbr{f}} $. This has two benefits.\n\\begin{itemize}\n\\item The association of hypersurfaces with points in $ \\P_{n, d} $ is almost injective. It is injective for polynomials $ f $ which generate radical ideals, and these form a dense open subset of $ \\P_{n, d} $.\n\\item By using the projective base $ \\P_{n, d} $ instead of the affine base $ \\V_{n, d} $, we can take advantage of properties like completeness.\n\\end{itemize}\nWe can fit these hypersurfaces together into a family over the base $ \\P_{n, d} $. In other words, there is a single closed set $ \\HHH \\subseteq \\P_{n, d} \\times \\PP^n $ such that the fibre\n$$ \\HHH_{\\sbr{f}} = \\cbr{x \\in \\PP^n \\st \\br{\\sbr{f}, x} \\in \\HHH} $$\nis the hypersurface defined by the polynomial $ f $. To see that $ \\HHH $ is closed, we observe that it is defined by a polynomial equation which is bihomogeneous of degree $ \\br{1, d} $,\n$$ \\HHH = \\cbr{\\br{\\sbr{f}, x} \\in \\P_{n, d} \\times \\PP^n \\st \\sum_{0 \\le i_0, \\dots, i_n \\le d, \\ i_0 + \\dots + i_n = d} f_{i_0 \\dots i_n}X_0^{i_0} \\dots X_n^{i_n} = 0}, $$\nwhere $ f_{i_0 \\dots i_n} $ denote the coefficients of the polynomial $ f \\in \\V_{n, d} $. We call $ \\HHH $ the \\textbf{universal family of hypersurfaces of degree $ d $ in $ \\PP^n $}. We think of $ \\P_{n, d} \\cong \\PP^N $ as the \\textbf{parameter space for hypersurfaces of degree $ d $ in $ \\PP^n $}.\n\\end{example*}\n\n\\begin{remark*}\nThe word universal here is related to the fact that every hypersurface of degree $ d $ appears as a fibre in this family, and most of them only appear once. If we work with schemes instead of varieties, then each hypersurface will really appear exactly once. However a rigorous definition of what it means for a family to be universal is more subtle than this, and too complicated to define in this course, since it involves the notion of a flat family of schemes.\n\\end{remark*}\n\n\\pagebreak\n\n\\subsubsection{Subsets of parameter spaces}\n\nOne of the benefits of parameter spaces and families of varieties is that they give us a way of talking about all varieties with some particular property at once. If we take a family $ \\VVV \\subseteq B \\times \\PP^n $ and consider the subset of fibres which satisfy an interesting geometric condition, then very often the corresponding set of points in the parameter space\n$$ \\cbr{b \\in B \\st \\VVV_b \\ \\text{satisfies a given condition}} $$\nis an open or closed subset of $ B $.\n\n\\begin{example*}\nAs a simple example, if we fix a point $ x \\in \\PP^n $, then the set\n$$ \\cbr{b \\in B \\st x \\in \\VVV_b} $$\nis a closed subset. This is the image of the closed set $ \\br{B \\times \\cbr{x}} \\cap \\VVV \\subseteq B \\times \\PP^n $ under the projection $ \\pi_1 : B \\times \\PP^n \\to B $, so it is closed because $ \\PP^n $ is complete, by Theorem \\ref{thm:projectionclosed}.\n\\end{example*}\n\n\\begin{example*}\nThe set\n$$ \\cbr{\\sbr{f} \\in \\P_{n, d} \\st f \\ \\text{is irreducible}} $$\nis an open set, and so is the set\n$$ \\cbr{\\sbr{f} \\in \\P_{n, d} \\st f \\ \\text{generates a radical ideal}}. $$\nThis will be on problem sheet $ 5 $.\n\\end{example*}\n\n\\subsubsection{Dimension counting}\n\n\\lecture{30}{Friday}{20/03/20}\n\nAn important use of families of varieties, and the fact that the family is itself a variety, is that we can calculate the dimension of the parameter space, or of interesting subsets of it, using the fibre dimension theorem. By doing this, we can show that certain sets are empty or non-empty or finite or infinite or equal or not equal to the entire parameter space.\n\n\\begin{example*}\nConsider the intersection of $ n + 1 $ hypersurfaces in $ \\PP^n $. From our earlier discussions of dimension, we expect that usually such an intersection should be empty, because $ n + 1 > n $, but of course sometimes it will be non-empty. By counting dimensions of parameter spaces, we can be more specific about how often sometimes non-empty occurs, since we will prove that the subset of the parameter space where this intersection is non-empty is a closed subset, and then we will compare its dimension with the dimension of the entire parameter space. What is the appropriate parameter space? In order to get parameter spaces for hypersurfaces, we have to fix the degree of the defining polynomial, since the dimension of $ \\P_{n, d} $ increases as $ d $ grows, so if there was a single parameter space for all hypersurfaces in degree $ d $ it would have to be infinite-dimensional, which does not fit within our notion of varieties. For simplicity, we will assume that all of the $ n + 1 $ hypersurfaces we are intersecting have the same degree $ d $. We are looking at sequences of $ n + 1 $ hypersurfaces, so the parameter space we need is $ \\P_{n, d}^{n + 1} $. We could more generally pick a sequence of $ d_0, \\dots, d_n \\in \\ZZ_{> 0} $ and look at intersections of the form $ \\HHH_0 \\cap \\dots \\cap \\HHH_n $ where $ \\HHH_0 $ has degree $ d_0 $, $ \\HHH_1 $ has degree $ d_1 $, etc. Because we have fixed the degree of each $ \\HHH_i $, we can still form a parameter space for such sequences, since it would be the product $ \\P_{n, d_0} \\times \\dots \\times \\P_{n, d_n} $. The example below would still work, but would sometimes get a little more complicated. The subset of the parameter space which we want to study is\n$$ S = \\cbr{\\br{a_0, \\dots, a_n} \\in \\P_{n, d}^{n + 1} \\st \\bigcap_{i = 0}^n \\HHH_{a_i} \\ne \\emptyset}. $$\nThe algebraic varieties we are interested in, intersections of $ n + 1 $ hypersurfaces, should form a family over $ \\P_{n, d}^{n + 1} $. More precisely, we want a family of algebraic varieties over $ \\P_{n, d}^{n + 1} $ such that the fibre above $ \\br{a_0, \\dots, a_n} $ is $ \\bigcap_{i = 0}^n \\HHH_{a_i} $. We can define this family by\n$$ \\Sigma = \\cbr{\\br{a_0, \\dots, a_n, x} \\in \\P_{n, d}^{n + 1} \\times \\PP^n \\st \\forall i, \\ x \\in \\HHH_{a_i}}. $$\nThen $ \\Sigma $ is a closed subset of $ \\P_{n, d}^{n + 1} \\times \\PP^n $ because for each $ i $, the condition $ x \\in \\HHH_{a_i} $ is given by a polynomial condition in the homogeneous coordinates of $ a_i \\in \\P_{n, d} $, which is equal to the coefficients of a polynomial $ f_i $ such that $ a_i = \\sbr{f_i} $, and of $ x \\in \\PP^n $. Thus it is a family of algebraic varieties in the sense we defined in the previous lecture.\n\n\\pagebreak\n\nLet $ \\pi_1 $ denote the projection $ \\Sigma \\subseteq \\P_{n, d}^{n + 1} \\times \\PP^n \\to \\P_{n, d}^{n + 1} $. By definition, $ \\pi_1^{-1}\\br{a_0, \\dots, a_n} \\cap \\Sigma \\ne \\emptyset $ if and only if $ \\br{a_0, \\dots, a_n} \\in S $. In other words, $ S = \\pi_1\\br{\\Sigma} $. Therefore, because $ \\PP^n $ is complete, $ S $ is a closed subset of $ \\P_{n, d}^{n + 1} $. Why are we focussing on the set where $ \\bigcap_{i = 0}^n \\HHH_{a_i} $ is non-empty rather than the set where it is empty? Because closed sets are usually more interesting than open sets, for example it makes sense to ask what is the dimension of a closed subset, while the dimension of an open set is always the same as the dimension of the space it is contained in. What is $ \\dim S $? We can work this out by two applications of the fibre dimension theorem. First we apply it to the projection $ \\Sigma \\to \\PP^n $ to find $ \\dim \\Sigma $, then we apply it to the projection $ \\Sigma \\to S $ to find $ \\dim S $. The reason we can do this is that we know the dimension of $ \\PP^n $ and we can work out the dimensions of the fibres of both projections from $ \\Sigma $. In order to apply the fibre dimension theorem to $ \\Sigma $, we need to know that $ \\Sigma $ is irreducible. This is true, and could be proved using tools from this course, but is a little more complicated than we want to do now, so we shall take it for granted. To compute $ \\dim \\Sigma $, we will apply the fibre dimension theorem to the projection $ p : \\Sigma \\to \\PP^n $. This map is surjective, since for any $ x \\in \\PP^n $, we can pick $ a \\in \\P_{n, d} $ such that $ x \\in \\HHH_a $ and then $ \\br{a, \\dots, a, x} \\in p^{-1}\\br{x} \\subseteq \\Sigma $. The fibres are\n$$ p^{-1}\\br{x} = \\cbr{\\br{a_0, \\dots, a_n} \\in \\P_{n, d}^{n + 1} \\st \\forall i, \\ x \\in \\HHH_{a_i}} = \\cbr{a \\in \\P_{n, d} \\st x \\in \\HHH_a}^{n + 1}. $$\nThus\n$$ \\dim p^{-1}\\br{x} = \\br{n + 1}\\dim \\cbr{a \\in \\P_{n, d} \\st x \\in \\HHH_a}. $$\nIn order to calculate $ \\dim \\cbr{a \\in \\P_{n, d} \\st x \\in \\HHH_a} $, make a linear change of coordinates so that $ x = \\sbr{0 : \\dots : 0 : 1} $. This change of coordinates will not change the dimension of $ \\cbr{a \\in \\P_{n, d} \\st x \\in \\HHH_a} $, so it suffices to work out the dimension for the special case of $ \\sbr{0 : \\dots : 0 : 1} $. Now $ \\sbr{0 : \\dots : 0 : 1} \\in \\HHH_a $ if and only if the homogeneous polynomial $ f $ vanishes at $ \\sbr{0 : \\dots : 0 : 1} $, where $ a = \\sbr{f} $. The value of $ f $ at $ \\sbr{0 : \\dots : 0 : 1} $ is just the $ X_n^d $ coefficient of $ f $. Thus $ \\sbr{0 : \\dots : 0 : 1} \\in \\HHH_{\\sbr{f}} $ if and only if the $ X_n^d $ coefficient of $ f $ is zero. In other words, $ \\cbr{a \\in \\P_{n, d} \\st x \\in \\HHH_a} $ is a subspace of $ \\P_{n, d} $ defined by one linear equation, so\n$$ \\dim \\cbr{a \\in \\P_{n, d} \\st x \\in \\HHH_a} = \\dim \\P_{n, d} - 1 = N - 1, \\qquad N = \\binom{n + d}{d} - 1. $$\nAlternatively, we could have seen this without reducing to the case $ x = \\sbr{0 : \\dots : 0 : 1} $ by observing that the condition $ x \\in \\HHH_{\\sbr{f}} $ is a single linear condition on the coefficients of $ f $, as you see just by expanding out $ f\\br{x_0, \\dots, x_n} = 0 $. Therefore,\n$$ \\dim p^{-1}\\br{x} = \\br{n + 1}\\br{N - 1}, \\qquad x \\in \\PP^n. $$\nWe can apply the fibre dimension theorem, in Theorem \\ref{thm:fibredimension}, to get\n$$ \\dim \\Sigma = \\dim \\PP^n + \\dim p^{-1}\\br{x} = n + \\br{n + 1}\\br{N - 1} = N\\br{n + 1} - 1. $$\nBy part $ 2 $ of the fibre dimension theorem, this holds for all $ x $ in some non-empty open subset of $ \\PP^n $. It does not matter which $ x $ we choose because we showed that all the fibres have the same dimension. Now to compute $ \\dim S $, we will apply the fibre dimension theorem to the projection $ q : \\Sigma \\to S $. This map is surjective by construction. This time, the fibres do not all have the same dimension, but the minimum dimension of the fibres is zero. To see that there are fibres of dimension zero, observe that for suitable choices of $ n + 1 $ homogeneous polynomials of degree $ d $, the intersection of the corresponding hypersurfaces is finite and non-empty, for example $ f_i = X_i^d $ for $ 0 \\le i \\le n - 1 $ and $ f_n X_0^d $, repeating $ f_0 $, have the unique common solution $ \\sbr{0 : \\dots : 0 : 1} $. Therefore the fibre dimension theorem implies that\n$$ \\dim S = \\dim \\Sigma - 0 = N\\br{n + 1} - 1. $$\nWe recall how this follows from the fibre dimension theorem. By part $ 1 $, the fact that there is just a single fibre of dimension zero implies that $ 0 \\ge \\dim \\Sigma - \\dim S $. By part $ 2 $ of the fibre dimension theorem, there exists an open subset $ U \\subseteq S $ on which $ \\dim q^{-1}\\br{s} = \\dim \\Sigma - \\dim S $. But since $ q^{-1}\\br{s} $ can never be negative, this forces $ 0 \\le \\dim q^{-1}\\br{s} = \\dim \\Sigma - \\dim S $. Combining these gives $ \\dim S = \\dim \\Sigma $ as we claimed. In particular, we have $ \\dim S = \\dim \\P_{n, d}^{n + 1} - 1 $. This means that it is only slightly unusual for $ n + 1 $ hypersurfaces to have non-empty intersection, since this subset of the parameter space has dimension only one less than the entire parameter space. As an application of this calculation, we see that $ S $ is a hypersurface in $ \\P_{n, d}^{n + 1} $, and therefore it is defined by a single polynomial $ F \\in k\\sbr{X_{iI} \\st 0 \\le i \\le n, \\ 0 \\le I \\le N} $. In other words, there exists some polynomial $ F $ such that, when we evaluate it at the coefficients of $ n + 1 $ homogeneous polynomials $ f_0, \\dots, f_n $ of degree $ d $, we get zero if and only if the intersection $ \\bigcap_{i = 0}^n \\HHH_{\\sbr{f_i}} $ is non-empty.\n\\end{example*}\n\n\\end{document}", "meta": {"hexsha": "fa74eb7bd1aa18aaafe98ae3bf8f3bf149a0f945", "size": 259328, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "M4P33 Algebraic Geometry/M4P33.tex", "max_stars_repo_name": "KIRIKODESU/GANT", "max_stars_repo_head_hexsha": "05222442d24ee5aac54ca7044ec0089b10780953", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-13T18:41:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-13T18:41:17.000Z", "max_issues_repo_path": "M4P33 Algebraic Geometry/M4P33.tex", "max_issues_repo_name": "liuyujian1995/GANT", "max_issues_repo_head_hexsha": "f33d124eac180e5f3e23d1d7a262ac21ac1013f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "M4P33 Algebraic Geometry/M4P33.tex", "max_forks_repo_name": "liuyujian1995/GANT", "max_forks_repo_head_hexsha": "f33d124eac180e5f3e23d1d7a262ac21ac1013f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 96.0829937014, "max_line_length": 2080, "alphanum_fraction": 0.6892005491, "num_tokens": 81971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.3359131778250933}}
{"text": "\\documentclass{svproc}\n%\\documentclass{article}\n\\def\\UrlFont{\\rmfamily}\n\\usepackage{graphicx}\n%\\usepackage{subcaption}\n\\usepackage{bm}\n%\\usepackage{geometry}\n\\usepackage{float}\n\\usepackage{caption}\n\\usepackage{pdfpages}\n\\usepackage{setspace}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{multicol}\n\\usepackage{color}\n\\doublespacing\n\\usepackage[margin=1.1in]{geometry}% to typeset URLs, URIs, and DOIs\n\\usepackage{url}\n\\usepackage{threeparttable}\n\\usepackage[bottom]{footmisc}\n\\usepackage{adjustbox}\n\\usepackage{multirow}\n\\usepackage{makecell}\n\\usepackage{caption}\n\\usepackage{subfig}\n\\def\\UrlFont{\\rmfamily}\n\\raggedbottom\n\\newenvironment{centermath}\n {\\begin{center}$\\displaystyle}\n {$\\end{center}}\n\\newcommand\\scalemath[2]{\\scalebox{#1}{\\mbox{\\ensuremath{\\displaystyle #2}}}}\n\n\n\n\\begin{document}\n\\mainmatter              % start of a contribution\n%\n\n\n\\title{Solar Analysis}\n%\n\\titlerunning{Solar Analysis}  % abbreviated title(for running head)\n%                                     also used for the TOC unless\n%                                     \\toctitle is used\n%\n\\author{Jacob Merrell}\n\n\\institute{}\n%\n%%%% list of authors for the TOC(use if author list has to be modified)\n\n\\maketitle  \n\n\\begin{abstract}\n   Solar energy is environmentally friendly, but can it also be cost efficient? This study focuses on power bill data collected from one solar panel owner. The study confirms that solar power helps save money, and hypothesizes that on average the savings from using the solar panel after 8 years will cover the costs of the installation. We explore ways to account for the correlation in the data, and to also incorporate temperature into the model.   \n\\end{abstract}\n\n\\section{Introduction}\n\nIdeally energy would be efficient, cheap, and environmentally friendly. Finding the right balance is a difficult question for scientists to answer. Sunlight is available to all, given the weather is right. Harnessing the power of solar energy is an environmentally friendly alternative to other more pollutant producing energy sources. The purpose of this analysis to be able to: (1) predict how much power bills are going to be in the future (2) how much can someone save, on average, using solar energy, and (3) how long it will take to earn back the money used to install solar equipment. Regression techniques to handle correlated data will be used to answer the goals of the analysis.\n\n\\section{Exploratory Data Analysis}\n\n\\begin{center}\n\\includegraphics [height=7.5cm]{solar_data.pdf}\n\\end{center}\n\nThe graph above shows the power bill for the subject given dates in time. There is a sizable difference between the power bill after switching to solar energy. Exploring the data shows that normal regression methods are inadequate for this data. There appears to be a seasonal trend in the power bill. This makes sense because in very cold and very hot months, more energy is used to maintain the climate inside the home. The dataset includes 51 months of power bills from the same subject. \n\n\\section{Model Selection}\n\nThe model used for this analysis is \n\n\\begin{equation}\n Y \\sim N(X\\beta, \\sigma^2R)\n\\end{equation}\n\nIn the model $Y$ denotes the vector of power bill amounts, and the $X$ matrix contains the observed values of the explanatory variables at the date of each power bill. The $\\beta$ vector contains the model coefficients, $\\sigma^2$ is the variance of the residuals, and $R$ is the variance covariance matrix. The variance covariance matrix in this model is structured as AR(1). This model assumes that correlation of each observation with the previous observation is constant and equal to $\\rho$. This makes sense to use an AR(1) model since the data are measured in discrete and consistent time intervals.\n\nThe effects being measured in the model are solar v non-solar power bills, the interaction between solar status and season (summer or winter), and the interaction between season and temperature. Temperature was not originally given in the dataset, but was gathered from the US Climate Data website. The reason for gathering this data was to see the effect extreme temperatures had on the power bill.\n\nThe model assumptions are normality of the standardized residuals, homoscedacisity, and that the data are multivariate normally distributed. Normality of the residuals can be observed by plotting the residuals to verify if they seem normally distributed. Homoscedacisity is verified through a graph of the fitted values v. the residuals. A constant variability or jitter of the residual values about 0 should be similar across all fitted values. The model follows multivariate normal distribution. \n\nThe model will help us achieve our goals by estimating coefficients and allowing us to make predictions of the power bill amount at each month. The model will also help us capture the seasonality trends inherent in the data.\n\n\n\n\n\\section{Model Justification}\nSince the data are correlated, using the residuals from the model without any adjustment can lead to incorrect conclusions about the assumptions. To correct for this issue, we used a decorrelated regression model. After undergoing the decorrelation transformation, the residuals and fitted values can be used to verify whether or not the assumptions hold. The assumptions for the model are explored in the graphs below\n\n\\begin{center}\n\\includegraphics [height=7.5cm]{assump.pdf}\n\\end{center}\n\nThe histogram of the standardized residuals shows a normal distribution. The fitted v. residual plot shows that the variance of the residuals about the 0 line is about the same. All assumptions hold for this study.\n\n\\section{Performance Evaluation}\n\nThe model had an adjusted R-squared of 0.9376. This mean 93.76\\% of variation in power bill is explained by the model. To test the predictive power of the model, we used test and training data to cross validate. The test and training datasets were chosen to preserve the time series; in this case choosing random points would interfere with the correlated structure inherent in the data. The training data was used to predict the test data. The RMSE, bias, and 95\\% prediction interval coverage we calculated. This process was repeated several times to get more reliable results. On average, the RMSE was \\$27.21; this means the predictions were off by \\$27.21 on average. The 95\\% confidence interval for the RMSE was (\\$6.74, \\$54.48). The bias showed that we were underestimating the power bill by \\$0.67 on average, and almost 95\\% of all observed power bill values were contained within the prediction intervals. Even though the coverage was very good, the average prediction window was \\$104.57. This means most of the predictions for a power bill during a given month would have been in a ballpark of plus or minus \\$50 away from the point estimate. \n\n\\section{Results}\n\nThe graph below shows the fitted values from the model compared to the actual power bill values.\n\n\\begin{center}\n\\includegraphics [height=7.5cm]{solar_fit.pdf}\n\\end{center}\n\nWhile the model uses an AR(1) covariance structure, the model estimate for $\\rho$ is very small (.0377). This means the effects and interactions included in the model account for most of the correlation inherent in the data. To achieve the goals of the study we used the model to predict the amount of money spent on power bills over the next 10 years. Then we compared the amount of money spent per month when using solar power v. the amount of money spent on power when not using solar energy. The average monthly savings when using solar energy is \\$86.69. The 95\\% confidence interval for the monthly savings is (\\$80.41,\\$92.97). In this the study, the subject using solar power in their home paid \\$8,000 (after government subsidies) to install the solar panels. Assuming the average monthly savings, it would take 7.69 years of cumulative saving to cover the installation costs. The 95\\% confidence interval for the amount of time it would take to recover the initial investment is (7.17,8.29).\n\n\n\\section{Conclusion}\nUsing solar power helps save \\$86.69 on average each month. However, the RMSE is fairly given the size of the monthly power bill. Predictions for individual months will vary much more than average yearly totals or average seasonal totals. Assuming an initial \\$8,000 investment, it will take 7.69 years on average for the investment in solar panels to pay off. All power bill data in this study was gathered about 1 home owner. One improvement to be made for future studies is to include more solar panel owners across a broad range of geographical locations. Another element not incorporated into the study was the impact of inflation or changing utility costs on the power bill amount. The data overall could have used more explanatory variables to explain the variation in power bill. If one plans on living in their home for an extended period of time, solar energy is a cost effective and nature friendly way of using electricity.\n\n\\newpage\n\\begin{thebibliography}{6}\n\n\\bibitem{R}\nR: A Language and Environment for Statistical Computing.R Core Team.\nR Foundation for Statistical Computing.Vienna, Austria.\n(2017).url = {https://www.R-project.org/}\n\n\n\\end{thebibliography}\n\n\n\n\n\\end{document}\n\n\n\n", "meta": {"hexsha": "3cfab04fcf43d3022055d248c4f6fcc8b17746b8", "size": 9226, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "solar_AR1/solar_project.tex", "max_stars_repo_name": "jmmerrell/jmmerrell.github.io", "max_stars_repo_head_hexsha": "5c71914201531289e4614337ba308268579dfc8b", "max_stars_repo_licenses": ["BSD-3-Clause", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "solar_AR1/solar_project.tex", "max_issues_repo_name": "jmmerrell/jmmerrell.github.io", "max_issues_repo_head_hexsha": "5c71914201531289e4614337ba308268579dfc8b", "max_issues_repo_licenses": ["BSD-3-Clause", "MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-07-18T20:48:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-18T20:48:10.000Z", "max_forks_repo_path": "solar_AR1/solar_project.tex", "max_forks_repo_name": "jmmerrell/jmmerrell.github.io", "max_forks_repo_head_hexsha": "5c71914201531289e4614337ba308268579dfc8b", "max_forks_repo_licenses": ["BSD-3-Clause", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 68.8507462687, "max_line_length": 1157, "alphanum_fraction": 0.7853891177, "num_tokens": 2045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.3358515474041741}}
{"text": "% Created 2021-04-21 Wed 21:01\n% Intended LaTeX compiler: xelatex\n\\documentclass[12pt]{article}\n\\usepackage{graphicx}\n\\usepackage{grffile}\n\\usepackage{longtable}\n\\usepackage{wrapfig}\n\\usepackage{rotating}\n\\usepackage[normalem]{ulem}\n\\usepackage{amsmath}\n\\usepackage{textcomp}\n\\usepackage{amssymb}\n\\usepackage{capt-of}\n\\usepackage{hyperref}\n\\usepackage{minted}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{setspace}\n\\usepackage{subcaption}\n\\usepackage{mathtools}\n\\usepackage{xfrac}\n\\usepackage[margin=1in]{geometry}\n\\usepackage{marginnote}\n\\usepackage[utf8]{inputenc}\n\\usepackage{color}\n\\usepackage{epsf}\n\\usepackage{tikz}\n\\usepackage{graphicx}\n\\usepackage{pslatex}\n\\usepackage{hyperref}\n\n\\usepackage{beton}\n\\usepackage{euler}\n\\usepackage[OT1]{fontenc}\n\n\\usepackage{textgreek}\n\\renewcommand*{\\textgreekfontmap}{%\n{phv/*/*}{LGR/neohellenic/*/*}%\n{*/b/n}{LGR/artemisia/b/n}%\n{*/bx/n}{LGR/artemisia/bx/n}%\n{*/*/n}{LGR/artemisia/m/n}%\n{*/b/it}{LGR/artemisia/b/it}%\n{*/bx/it}{LGR/artemisia/bx/it}%\n{*/*/it}{LGR/artemisia/m/it}%\n{*/b/sl}{LGR/artemisia/b/sl}%\n{*/bx/sl}{LGR/artemisia/bx/sl}%\n{*/*/sl}{LGR/artemisia/m/sl}%\n{*/*/sc}{LGR/artemisia/m/sc}%\n{*/*/sco}{LGR/artemisia/m/sco}%\n}\n\\makeatletter\n\\newcommand*{\\rom}[1]{\\expandafter\\@slowromancap\\romannumeral #1@}\n\\makeatother\n\\DeclarePairedDelimiterX{\\infdivx}[2]{(}{)}{%\n#1\\;\\delimsize\\|\\;#2%\n}\n\\newcommand{\\infdiv}{D\\infdivx}\n\\DeclarePairedDelimiter{\\norm}{\\left\\lVert}{\\right\\rVert}\n\\DeclarePairedDelimiter{\\ceil}{\\left\\lceil}{\\right\\rceil}\n\\DeclarePairedDelimiter{\\floor}{\\left\\lfloor}{\\right\\rfloor}\n\\def\\Z{\\mathbb Z}\n\\def\\R{\\mathbb R}\n\\def\\C{\\mathbb C}\n\\def\\N{\\mathbb N}\n\\def\\Q{\\mathbb Q}\n\\def\\noi{\\noindent}\n\\onehalfspace\n\\usemintedstyle{bw}\n\\author{Sandy Urazayev\\thanks{thecsw@Mania.local}}\n\\date{\\today}\n\\title{}\n\\hypersetup{\n pdfauthor={Sandy Urazayev},\n pdftitle={},\n pdfkeywords={},\n pdfsubject={},\n pdfcreator={Emacs 28.0.50 (Org mode 9.4.5)}, \n pdflang={English}}\n\\begin{document}\n\n\\section*{Differential Equations Cookbook 🔥}\n\\label{sec:org68348f2}\n\nMay 12th, 2020\n\n\\href{./index.pdf}{(PDF Version)}\n\n\\subsection*{Abstract}\n\\label{sec:org9f36d0e}\n\nWhen I got first introduced to differential equations, I had a love-hate\nrelationship with it. Mainly due to some back-of-the-book problems we were given\nand never-ending projects we were assigned to. After some time, differential\nequations is a way to truly understand physics and the foundations of gravity,\nfields, and everything. This articles is merely an intro on manually solving\ncommon forms of differential equations. Hope you enjoy\n\n\\subsubsection*{Quick notes}\n\\label{sec:orgb1870c9}\n\n\\begin{itemize}\n\\item \\(f_x \\iff \\partial_x f\\)\n\\item \\(A,B,C\\) are usually constants\n\\item \\(c_k\\) is usually solution's constant that is defined with initial conditions\n\\item Most of the functions are \\(\\mathbb{R}^k \\to \\mathbb{R}\\), \\(k \\in \\mathbb{N}^+\\)\n\\item If you found a typo or want to comment, feel free to email me. Email on\ntop of the page.\n\\end{itemize}\n\n\n\\subsubsection*{First-order, linear}\n\\label{sec:org122c719}\n\nThose equations have the form: \\(y' + p(t) y = q(t)\\)\n\nFind \\(\\mu(t) = e^{\\int p(t) dt}\\)\n\nThen \\(\\frac{d}{dt}(\\mu(t)y) = q(t) \\mu(t)\\)\n\\(\\implies y = \\frac{\\int q(t) \\mu(t) dt}{\\mu(t)}\\)\n\n\\subsubsection*{First-order, separable}\n\\label{sec:orgd322a73}\n\nThose equations have the form: \\(\\frac{dy}{dx} = f(x)g(y)\\)\n\nFind the solution by solving \\(\\int \\frac{dy}{g(y)} = \\int f(x) dx\\)\n\nSolve for exact (explicit) values of \\(y\\)\n\n\\subsubsection*{Exact equations}\n\\label{sec:orgab1ad9e}\n\nThey have the form \\(M(x,y) + N(x,y) \\frac{dy}{dx} = 0\\)\n\n\\begin{itemize}\n\\item \\((\\xi)\\) If \\(M_y = N_x\\)\n\n\\(\\implies\\) Find such \\(F(x,y)=C\\), where \\(F_x = M\\), \\(F_y = N\\)\n\n\\item otherwise, make it exact, such that\n\n\\(\\frac{M_y-N_x}{N}\\) only depends on \\(x\\) \\textbf{or} \\(\\frac{N_x-M_y}{M}\\) only\ndepends on \\(y\\) \n\nFind \\(\\mu(x) = e^{\\int \\frac{M_y-N_x}{N} dx}\\) \\textbf{or}\n\\(\\mu(y) = e^{\\int \\frac{N_x-M_y}{M} dy}\\), multiply both by \\(M\\) \\textbf{and} \\(N\\),\nso the condition \\(M_y = N_y\\) is satisfied. Go to \\((\\xi)\\) and proceed with\nfinding \\(F(x,y)\\)\n\\end{itemize}\n\n\\subsubsection*{Second-order, linear, constant-coefficient equations}\n\\label{sec:org57d7f32}\n\nThey have the form \\(y'' + p y' + q y = f(t)\\)\n\n\\begin{itemize}\n\\item First, solve for the homogeneous case, where \\(y'' + p y' + q y = 0\\)\n\nMake a characteristic polynomial, let \\(y = e^{rt}\\): \n\n\\(r^2+pr+q=0\\)\n\nFind roots, solution (general) will be \\(y = c_1 e^{r_1 t} + c_2 e^{r_2 t}\\)\n\n\\textbf{**} if repeated root \\(\\implies y = c_1 e^{rt} + c_2 t e^{rt}\\)\n\n\\textbf{**} if \\(r = \\alpha \\pm i \\beta\\) \\(\\implies y=c_1 \\cos(\\beta t)e^{\\alpha t} + c_2 \\sin(\\beta t) e^{\\alpha t}\\)\n\n\\item Solving for particular solution \\(y_p(t)\\)\n\n\\textbf{**} Undetermined coefficients (superpositioned) for \\(f(t)\\)\n\nWhatever is in \\(f(t)\\), start adding up the corresponding coefficients into\n\\(y_p(t)\\)\n\n\\textbf{\\textbf{*}} \\(e^{nt} \\to Ae^{nt}\\)\n\n\\textbf{\\textbf{*}} \\(t^m \\to A_m t^m + \\ldots + A_1 t + A_0\\)\n\n\\textbf{\\textbf{*}} \\(\\cos(\\beta t)\\) or \\(\\sin(\\beta t) \\to Acos(\\beta t) + B\\sin(\\beta t)\\)\n\nNOTE: should not be linearly dependent with the general solution. If it\nis, multiply by \\(t\\) until it is linearly independent.\n\n\\textbf{**} Variation of parameters\n\nSeek \\(y_p(t) = v_1(t)y_1(t)+v_2(t)y_2(t)\\), where\n\n\\(\\begin{cases}v_1'y_1+v_2'y_2=0\\\\v_1'y_1'+v_2'y_2'=f(t)\\end{cases}\\)\n\\end{itemize}\n\n\nSo the final solution is \\(y(t)=c_1 y_1(t) + c_2 y_2(t) + y_p(t)\\)\n\n\\subsubsection*{Second-order, linear, variable-coefficient equations}\n\\label{sec:orge10bbe0}\n\nEquations have the form \n\n\\begin{itemize}\n\\item \\((1)\\): \\(a(t)y'' + b(t)y'+c(t)y = f(t)\\)\n\\item \\((2)\\): \\(y'' + p(t)y'+q(t)y = g(t)\\)\n\\end{itemize}\n\nIn general case, guess the first homogeneous solution (try \\(y_1=e^t\\)) and\nuse reduction of order to find the second homogeneous solution, so that\n\n\\(y_2(t) = v(t)y_1(t)\\)\n\n\\(\\implies y_2'' + p(t)y_2' + q(t)y_2 = 0\\)\n\n\\(\\implies (v(t)y_1(t))''+p(t)(v(t)y_1(t))'+q(t)(v(t)y_1(t))=0\\)\n\nNOTE: Also applicable with form \\((1)\\)\n\nYou will probably have another differential equation emerge from above. It\nshould have lower order than our current equation, so just refer to one of\nthe techniques above to find \\(v(t)\\) and then you can find\n\\(y_2(t)=v(t)y_1(t)\\)\n\nUse \\textbf{variation of parameters} to find a particular solution. It's that\nsystem with \\(v\\)\n\nNOTE: What you if you have a \\textbf{Cauchy-Euler equation}?\n\nThey have the form \\(at^2y''+bty'+cy=0\\)\n\nthen \\(y=t^r \\implies ar^2+(b-a)r+c=0\\)\n\n\\begin{itemize}\n\\item if \\(r\\) is repeated, \\(y_1=t^r\\), \\(y_2=ln|t|t^r\\)\n\\item if \\(r=\\alpha\\pm i\\beta\\), \\(y_1=t^{\\alpha}\\cos(\\beta ln|t|)\\) and\n\\(y_2=t^{\\alpha}\\sin(\\beta ln|t|)\\)\n\\end{itemize}\n\nGenerally, solution has the form \\(y=c_1t^{r_1}+c_2t^{r_2}\\)\n\n\\subsubsection*{Higher-order, linear equations}\n\\label{sec:org9fadd1a}\n\n\\(a_n(t)y^{(n)}+a_{n-1}(t)y^{(n-1)}+\\ldots+a_1(t)y'+a_0(t)y=g(t)\\)\n\nAll second-order methods above extend to \\(n^{th}\\) order.\n\n\\subsubsection*{Laplace transform}\n\\label{sec:org42331b3}\n\nLaplace is a holy grail of solving differential equations with initial\nvalues defined. Laplace is the same kind of Bible to engineers like Taylor\nSeries is. \n\n\\(\\mathcal{L}\\{f\\}(s) = \\int_0^{\\infty} e^{-st} f(t) dt\\)\n\nassuming \\(f\\) is piecewise continuous and of exponential order.\n\nTable of common transformations:\n\n\\begin{center}\n\\begin{tabular}{ll}\n\\(f(t)\\) & \\(\\mathcal{L}\\{f\\}(s)\\)\\\\\n\\hline\n\\(1\\) & \\(\\frac{1}{s}\\)\\\\\n\\(e^{at}\\) & \\(\\frac{1}{s-a}\\)\\\\\n\\(\\sin(bt)\\) & \\(\\frac{b}{s^2+b^2}\\)\\\\\n\\(\\cos(bt)\\) & \\(\\frac{s}{s^2+b^2}\\)\\\\\n\\(u(t-a)\\) & \\(\\frac{e^{-as}}{s}\\)\\\\\n\\(\\delta(t-a)\\) & \\(e^{-as}\\)\\\\\n\\end{tabular}\n\\end{center}\n\nWhere \\(u(t)\\) is the \\href{https://en.wikipedia.org/wiki/Heaviside\\_step\\_function}{Heaviside step function} and \\(\\delta(t)\\) is the \\href{https://en.wikipedia.org/wiki/Dirac\\_delta\\_function}{Dirac\ndelta function}.\n\nSome Laplace transform properties:\n\n\\begin{itemize}\n\\item \\(\\mathcal{L}\\{e^{at}f(t)\\}(s) = \\mathcal{L}\\{f(t)\\}(s-a)\\)\n\\item \\(\\mathcal{L}\\{t^nf(t)\\}(s) = s^n\\mathcal{L}\\{f\\}(s)-s^{n-1}f(0)-\\ldots-sf^{(n-2)}(0)-f^{(n-1)}(0)\\)\n\\item \\(\\mathcal{L}\\{t^nf(t)\\}(s) = (-1)^n \\frac{d^n}{ds^n} \\mathcal{L}\\{f(t)\\}(s)\\)\n\\end{itemize}\n\nIf \\(f\\) is a T-periodic function, \n\n\\(\\mathcal{L}\\{f(t)\\}(s) = \\frac{\\int_0^T e^{-sT} f(t) dt}{1-e^{-sT}}\\)\n\nwhere \\(\\int_0^T e^{-sT} f(t) dt = \\mathcal{L}\\{f_T(t)\\}(s)\\), the sum of\nintegrals of different parts of the piecewise function.\n\nConvolutions:\n\n\\begin{itemize}\n\\item \\((f*g)(t) = \\int_0^t f(t-v)g(v)dv\\)\n\\item \\(\\mathcal{L}\\{(f*g)(t)\\} = \\mathcal{L}\\{f(t)\\}(s)\\cdot \\mathcal{L}\\{g(t)\\}(s)\\)\n\\item \\((f*g)(t) = \\mathcal{L}^{-1}\\{F\\cdot G\\}(t)\\), where\n\\(F=\\mathcal{L}\\{f\\}(s)\\) and \\(G=\\mathcal{L}\\{g\\}(s)\\)\n\\end{itemize}\n\nHeaviside/unit step function:\n\n\\begin{itemize}\n\\item \\(\\mathcal{L}\\{u(t-a)f(t)\\}(s) = e^{-as}\\mathcal{L}\\{f(t+a)\\}(s)\\)\n\\item \\(\\mathcal{L}^{-1}\\{e^{-as}F(s)\\}(t)=u(t-a)\\mathcal{L}^{-1}\\{F(s)\\}(t-a)\\)\n\\end{itemize}\n\nIf IVP is not at 0, define some new function like \\(w(t)=y(t+\\alpha)\\), and\nsolve for \\(w\\). Finally, you can offset to find \\(y\\)\n\nStep (block) function:\n\n\\begin{itemize}\n\\item \\(\\Pi_{a,b}(t) = u(t-a)-u(t-b)\\)\n\\item \\(\\mathcal{L}\\{\\Pi_{a,b}(t)\\}(s)=\\frac{e^{-sa}-e^{-sb}}{s}\\)\n\\end{itemize}\n\n\\subsubsection*{Constant-coefficient, homogeneous systems of ODE}\n\\label{sec:org1715575}\n\n\\(\\vec{x}' = A \\vec{x}\\), where \\(A\\in\\mathbb{R}^{n\\times n}\\), \\(x\\in\\mathbb{R}^n\\)\n\nIf \\(A\\) has n linearly independent eigenvectors \\(\\vec{u_i}\\) associated to n\neigenvalues \\(\\lambda_i\\), then a general solution of the system is given by\n\\(\\vec{x}(t) = c_1 e^{\\lambda_1 t}\\vec{u_1}+c_2e^{\\lambda_2t}\\vec{u_2} + \\ldots + c_ne^{\\lambda_nt}\\vec{u_n}\\)\n\n\\begin{itemize}\n\\item If \\(\\lambda=\\alpha \\pm i \\beta\\), so \\(\\vec{u}=\\vec{a}+i\\vec{b}\\), we have\n\\end{itemize}\n\\(\\vec{x}=c_1e^{\\alpha t}(\\cos(\\beta t)\\vec{a}-\\sin(\\beta t)\\vec{b}) + c_2e^{\\alpha t}(\\cos(\\beta t)\\vec{b}+\\sin(\\beta t)\\vec{a})\\)\n\n\\begin{itemize}\n\\item Matrix exponential\n\\end{itemize}\n\n\\(e^{At} = \\sum_{k=0}^{\\infty} \\frac{A^k t^k}{k!}\\), where \\(A^0=I\\), an\nidentity matrix.\n\n\\begin{itemize}\n\\item Find solutions for any eigenvalues\n\\end{itemize}\n\n\\begin{itemize}\n\\item Compute the characteristic polynomial \\(p(\\lambda)\\) of \\(A\\)\n\\label{sec:org9452c21}\n\n\\(p(\\lambda)=det(A-\\lambda I)\\)\n\n\\item Factor \\(p(\\lambda)\\) into linear factors to yield\n\\label{sec:org8696d39}\n\n\\(p(\\lambda) = c(\\lambda-\\lambda_1)^{m_1} \\cdot \\ldots \\cdot (\\lambda-\\lambda_k)^{m_k}\\), where \\(c=\\pm 1\\)\n\n\\item For each \\(\\lambda_j\\), find \\(m_j\\) linearly independent generalized eigenvectors \\(\\{\\vec{u_j}^{m_1},\\cdots,\\vec{u_j}^{m_j}\\}\\) satisfying\n\\label{sec:org8178bbd}\n\n\\((A-\\lambda_i I)^{m_j} \\vec{u} = \\vec{0}\\)\n\n\\item For each \\(\\vec{u_j}^i\\) computed in the previous step, compute \\(e^{At}\\vec{u_j}^i\\) by\n\\label{sec:orgef0c1a3}\n\n\\(e^{At}\\vec{u_j}^i\\)\n\n\\(=e^{\\lambda_jt}e^{(A-\\lambda_jI)t}\\vec{u_j}^i\\)\n\n\\(=e^{\\lambda_jt}(\\vec{u_j}^i+t(A-\\lambda_jI)\\vec{u_j}^i+\\cdots+\\frac{t^{m_j-1}}{(m_j-1)!}(A-\\lambda_jI)^{m_j-1}\\vec{u_j}^i)\\)\n\\end{itemize}\n\n\\subsubsection*{Linear systems of ODE}\n\\label{sec:orgf164fc6}\n\n\\(\\vec{x}' = A(t)\\vec{x} + \\vec{f}(t)\\), where \\(A\\in\\mathbb{R}^{n\\times n}\\),\n\\(x\\in\\mathbb{R}^n\\), \\(f\\in\\mathbb{R}^n\\)\n\nIf \\(X(t)\\) is a matrix whose columns are made up of n linearly independent\nhomogeneous solutions (\\(X(t)\\) is the fundamental matrix), then a general\nsolution may be written as \\(\\vec{x}(t_0)=\\vec{x_0}\\)\n\n\\(\\vec{x}(t) = X(t)X^{-1}(t_0)\\vec{x_0}+X(t)\\int_{t_0}^{t}X^{-1}(s)f(s)ds\\)\n\nIf \\(A(t)\\) is constant-coefficient, then we recover Duhamel's formula:\n\n\\(\\vec{x}(t) = e^{A(t-t_0)}x_0 + \\int_{t_0}^{t}e^{A(t-s)}f(s)ds\\)\n\n\\subsubsection*{Applications}\n\\label{sec:org4ccdfb4}\n\nThere are many applications of differential equations in classical\nmechanics, fields, etc. Below you will find just a snippet of some very\ncommon Physics 1/2 scenarios\n\n\n\\begin{itemize}\n\\item Falling object\n\\label{sec:orga0f31b1}\n\n\\(m\\frac{dv}{dt}=mg-bv\\), where \\(b\\) is the air resistance\n\n\\item Fluid mix, define \\(R_{in}\\) and \\(R_{out}\\)\n\\label{sec:org4bd501f}\n\n\\(\\frac{dx}{dt}=R_{in}-R_{out}\\)\n\n\\item Mass-Spring System\n\\label{sec:orgd309b6d}\n\n\\begin{itemize}\n\\item Vertical spring (direction of gravity)\n\\label{sec:org6762ecf}\n\n\\(my''=-by'-k(L+y)+mg+F_{ext}(t)\\), assume \\(KL=mg\\), where \\(b\\) is dumping, and \\(k\\) is stiffness\n\n\\item Horizontal spring\n\\label{sec:org3c38231}\n\n\\(my''=-by'-ky+F_{ext}(t)\\), where \\(b\\) is dumping, and \\(k\\) is stiffness\n\\end{itemize}\n\\end{itemize}\n\n\\subsubsection*{Conclusion}\n\\label{sec:orgfb53db8}\n\nThis is as much as I can recover from my initial experience with differential\nequations. This article is not as much to teach you how to solve them but\nprovide a quick lookup cheatsheet if needed or glance at different forms that we\ncan actually solve! There are infinitely many differential equations that we\ncannot find an exact solution for!\n\\end{document}", "meta": {"hexsha": "6d45d09b7f94501610c18b6e0c6ea10106e84daa", "size": 12911, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "blogs/diffeq/index.tex", "max_stars_repo_name": "thecsw/thecsw.github.io", "max_stars_repo_head_hexsha": "fdb600ec97cb59b2f89408f8a730ea01bcd21742", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-03-01T09:22:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-11T01:17:07.000Z", "max_issues_repo_path": "blogs/diffeq/index.tex", "max_issues_repo_name": "thecsw/thecsw.github.io", "max_issues_repo_head_hexsha": "fdb600ec97cb59b2f89408f8a730ea01bcd21742", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-06T16:15:09.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-06T16:35:31.000Z", "max_forks_repo_path": "blogs/diffeq/index.tex", "max_forks_repo_name": "thecsw/thecsw.github.io", "max_forks_repo_head_hexsha": "fdb600ec97cb59b2f89408f8a730ea01bcd21742", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-03-01T09:02:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-06T14:17:27.000Z", "avg_line_length": 30.3788235294, "max_line_length": 200, "alphanum_fraction": 0.6544806754, "num_tokens": 4940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.3358515369352436}}
{"text": "% Tell Texshop where the project root is\r\n%!TEX root = requirements.tex\r\n%\r\n\\subsection{Sorption}  \\label{sec:Sorption}\r\n\r\n\\subsubsection{Overview} \r\n\r\nSorption involves the attachment of dissolved and/or colloidal species to mineral or other solid surfaces.  Sorption has the effect of slowing the effective transport rate of a species through porous media through its retardation effect.  The retardation effect for a species, $R_f$, is given by~\\citep{bouwer-1991}\r\n\\begin{equation}\r\n  R_f = \\frac{V_{gw}}{V_{sp}},\r\n\\end{equation}\r\nwhere \r\n$V_{gw}$ is the velocity of the groundwater and $V_{sp}$ is the velocity of the species.  \r\nA variety of models have been used to describe sorption and can be broadly divided \r\ninto those that describe it as a bulk process versus those that are mineral or solid phase specific.  \r\nThe latter approach involves the calculation of  bulk sorption from the sum of sorption on individual solid phases, \r\nan assumption referred to as \\textit{Component Additivity}.  \r\nWithin the class of bulk sorption models, a distinction can be made between those \r\nwhich assume a finite number of sorption sites (these are referred to as showing \r\nLangmuir type behavior and include the Langmuir isotherm itself and most surface complexation \r\nand ion exchange models) and those that assume either an infinite sorption capacity \r\nor at least a capacity that is not tightly constrained \r\n(these include the linear distribution coefficient and the nonlinear Freundlich isotherm).  \r\nAlternatively, one could also distinguish between single component, \r\nnon-competitive models (e.g., Langmuir and Freundlich) and multicomponent competitive models (surface complexation and ion exchange).\r\n\r\nAnother possible distinction is between equilibrium and kinetic sorption models.  \r\nIn many cases, the formulations for the equilibrium and kinetic cases differ \r\nonly insofar as the kinetic case involves involves a thermodynamic driving force \r\n(as in the equilibrium case), but modified by a finite rate constant.  \r\nIn some cases, however, sorption is described as irreversible, which implies that there is no back reaction (desorption).\r\n\r\n%%\\paragraph{Assumptions, Approximations, Applicability.}\r\n\r\n\r\n\\subsubsection{Process Model Equations}\r\n\r\n\\paragraph{Linear Distribution Coefficients ($K_d$).}\r\nA simple approach to describe metal or ionic radionuclide sorption by a sediment,\r\n\\begin{equation}\r\n  A_{aq}\\leftrightharpoons A_{ads},\r\n\\end{equation}\r\nis to use a constant distribution coefficient, defined by:\r\n\\begin{equation} \\label{eq:Kd} \r\n  K_d = \\frac{[A_{ads}]}{[A_{aq}]},\r\n\\end{equation} \r\nwhere $K_d$ is the distribution coefficient (L/kg), $[A_{ads}]$ is the sorbed concentration (mol/kg) to the bulk solid phase, \r\nand $[A_{aq}]$ is the total dissolved concentration in groundwater (mol/L) \\citep{davis-1990}.  \r\nOne of the key advantages of representing sorption with a distribution coefficient is that it can be easily incorporated \r\ninto reactive transport models used for migration predictions. \r\n\r\nEquation \\eqref{eq:Kd} shows that if one assumes that the amount of sorption is proportional to the dissolved concentration, \r\nthen there is a linear relationship where the $K_d$ value is the slope. \r\nIn this simple case, referred to as a linear isotherm, retardation of a concentration  front in simple porous media is given by\r\n%\r\n\\begin{equation}  \\label{eq:KdRetardation}\r\n  \\frac{\\bar{v}}{\\bar{v}_{c} } \r\n  =\r\n  1+\\frac{\\rho _{b} }{n} K_{d}  ,\r\n\\end{equation}\r\nwhere $\\rho_b$ is the bulk density, \r\n$n$ the porosity, \r\n$\\bar{v}$ the average linear velocity of the groundwater and \r\n$\\bar{v}_{c} $ the velocity of the point on the concentration profile \r\nwhere the concentration is half that of the input concentration \\citep{freeze-1979}. \r\nNote that the ratio $\\bar{v}$/$\\bar{v}_{c} $ here is the retardation factor and represents \r\nthe retardation of the movement of front relative to the flowing groundwater. \r\nWhile this is a simplified example, it serves to illustrate the key point that the $K_d$ value \r\ndirectly influences predictions of adsorbing metal or radionuclide mobility. \r\n\r\n%Could have the following\r\n\\subparagraph{Assumptions and Applicability} \r\nSorption is proportional to the dissolved concentration. \r\nThe aqueous and adsorbed phases are in equilibrium.\r\n\r\n\\subparagraph{Data Needs}\r\nTypically $K_d$ values are determined for a particular subsurface material \r\nfrom the slope of a fitted line to the concentration of the sorbed species, $A_{ads}$, \r\nplotted versus the dissolved concentration of the same species, $A_{aq}$.  \r\nThese data may be derived from laboratory analyses, where one typically varies the dissolved concentrations systematically, \r\nor they may be derived from in situ field data.  \r\nSince $K_d$ values may be variable, and in particular a function of temperature, \r\npH or the redox state of the system (see below), it is often necessary to compile them in a lookup table for use by a particular computer code.\r\n\r\n\\paragraph{Langmuir Isotherm.}\r\nThe Langmuir isotherm assumes that the sorption sites, S, on the surface of a solid (absorbent) become occupied \r\nby an absorbate from the solution, A.  Implying a 1:1 stoichiometry\r\n%\r\n\\begin{equation}  \\label{eq:langmuir} \r\n  S + A \\leftrightharpoons SA,\r\n\\end{equation}\r\nwhere $SA$ is the adsorbed species on the surface. At equilibrium, a\r\nstandard mass action equation can be written:\r\n%\r\n\\begin{equation}  \\label{eq:langmuir_massaction}\r\n  K_{ads,L} = \\frac{ [ SA ] }{ [S] \\{A\\} },\r\n\\end{equation}\r\nwhere the square brackets here refer to the concentration of the\r\nspecies or site, and the curly brackets refer to the aqueous\r\nactivity.  Using the maximum concentration of surface sites, $S_T$\r\n%\r\n\\begin{equation}  \\label{eq:totalsurfacesites}\r\n  [S_T] = [S] + [SA],\r\n\\end{equation}\r\none can write the Langmuir isotherm in its familiar hyperbolic form\r\n%\r\n\\begin{equation}  \\label{eq:hyperbolicLangmuir}\r\n  [SA] = [S_T] \\frac{ K_{ads} \\{A\\} }{1 + K_{ads} \\{A\\} }.\r\n\\end{equation}\r\n\r\n%Could have the following\r\n\\subparagraph{Assumptions} \r\nFor the following, it is assumed that the surface and aqueous species are in equilibrium.\r\n\r\n\\subparagraph{Data Needs} \r\nThe equilbrium constant, $K_{ads}$, is typically obtained from experimental data. \r\nIt depends on the specified absorbent and absorbate, and may be a function of temperature. \r\nIt may be calculated from:\r\n\\begin{equation}\r\n  K_{ads} = \\exp\\left(\\frac{-\\Delta G^{\\circ}_{ads}}{RT}\\right),\r\n\\end{equation}\r\nwhere $\\Delta G$ is the change in free energy for the reaction,\r\ntypically obtained from a database, $R$ is the gas constant and $T$ is the temperature.\r\n\r\n\\paragraph{Freundlich.} \r\nThe Freundlich isotherm is another equilibrium model for sorption of absorabte A onto sorption sites, S\r\n\\begin{equation}  \\label{eq:langmuir_reaction} \r\n  S + A \\leftrightharpoons SA.\r\n\\end{equation}\r\nRepresented by the mass action equation:\r\n\\begin{equation}\r\n  K_{ads,F} = \\frac{ [ SA ] }{ \\{A\\}^{\\beta_F} },\r\n\\end{equation}\r\nwhere the square brackets again refer to the concentration of the\r\nspecies or site, the curly brackets refer to the aqueous activity.\r\n$K_{ads,F}$ and ${\\beta_F}$ are the Freundlich parameters\r\n\\citep[e.g.][]{langmuir-1997, stumm-1992}.\r\n\r\n%Could have the following\r\n\\subparagraph{Assumptions} \r\nFor the following, it is assumed that the surface and aqueous species are in equilibrium.\r\n\r\n\\subparagraph{Data Needs} \r\nThe Freundlich parameters, $K_{ads,F}$ and $n$, are generally obtained by fits to experimental data \r\nfor a specific surface and aqueous species. \r\nThey will generally be obtained from a database, and \r\nmay be represented by a functional form or lookup table.\r\n\r\n%Steefel\r\n\\paragraph{Multi-site, Multi-component Ion Exchange.}\r\nAn ion exchange reaction can be described via a mass action expression\r\nwith an associated equilibrium constant \\citep{vanselow-1932,sposito-1981,appelo-1993}.  \r\nThe exchange reaction can be written in generic form as\r\n\\begin{equation}\r\n  vACl_{u} (aq)+uBX_{\\nu } (s)\\leftrightharpoons uBCl_{\\nu } (aq)+vAX_{u} (s),\r\n\\end{equation} \r\nwhere X refers to the exchange site occupied by the cations $A^{u+}$ and $B^{v+}$.  \r\nThe equilibrium constant, $K_{eq}$, for this reaction can be written as \\citep{vanselow-1932}\r\n\\begin{equation}\r\n  K_{eq} =\\frac{\\{BCl_{\\nu } \\}^{u} \\{AX_{u}\\}^{\\nu } }{\\{ACl_{u} \\}^{\\nu } \\{BX_{\\nu } \\}^{u} },\r\n\\end{equation} \r\nwhere the curly braces refer to the thermodynamic activities.\r\nSeveral activity conventions are in wide use.  One possibility is the\r\nGaines-Thomas activity convention, which assumes a reaction\r\nstoichiometry of the following form \\citep{appelo-1993}, written\r\nhere assuming the $Cs^+$ is the relevant cation of interest\r\n\\begin{equation}\r\n  Cs^{+} + (1/z) MX(i)_{z} \\leftrightharpoons CsX(i) + (1/z) M^{z+},\r\n\\end{equation} \r\nwhere $M$ is the competing cation ($Na^+$, $K^+$, $Ca^{++}$), $z$ is\r\nits charge, and $X(i)$ refers to the $i^{th}$ type of exchange site.  \r\nIn the Gaines-Thomas convention, each exchange site, $X(i)$ has a charge of -1. \r\nThe activities of adsorbed species correspond to the charge equivalent fractions, $\\beta (i)_{M} $,\r\n\\begin{equation}\r\n  \\beta (i)_{M} =\\frac{z_{M} q(i)_{M} }{\\sum _{M}z_{M} q(i)_{M}  } = \\{X(i)_{M} \\},\r\n\\end{equation} \r\nwhere $z_M$ is the charge of cation $M$, $q(i)_M$ is the concentration\r\nof adsorbed cation $M$ in exchange site \\textit{i} (moles/g),\r\nand the curly brackets denote activities.  \r\nThe Gapon activity convention is obtained by writing the reactions in every case with a\r\nsingle exchanger \\citep{appelo-1993}.  \r\nAlternatively, the Vanselow convention \\citep{vanselow-1932} describes the exchanger activity\r\nwith mole fractions\r\n\\begin{equation}\r\n  \\beta (i)_{M} =\\frac{q(i)_{M} }{\\sum _{M}q(i)_{M}  } = \\{ X(i)_{M} \\}.\r\n\\end{equation} \r\nThe exchange reactions can then be used to write a mass action equation for binary Cs-M exchange:\r\n\\begin{eqnarray}\r\n  K_{M/Cs} & = & \\frac{\\beta (i)_{M} ^{1/z} \\{Cs^{+} \\}}{\\beta (i)_{Cs} \\{M^{z+} \\}^{1/z} } \\\\\r\n  & = & \r\n\\frac{\\{X(i)_{M} \\}^{1/z} \\{Cs^{+} \\}}{\\{X(i)_{Cs} \\}\\{M^{z+} \\}^{1/z} } .\r\n\\end{eqnarray}\r\n\r\nIn a single-site ion exchange model, the CEC is equal to the sum of the charge equivalent concentrations of the adsorbed cations:\r\n\\begin{equation}\r\n  CEC = \\sum _{M}z_{M} q_{M},\r\n\\end{equation} \r\nwhile in a multi-site model, the CEC is the charge summed over all of the cation exchange sites \\citep{cernik-1996, voegelin-2000}\r\n\\begin{equation}\r\n  CEC = \\sum _{i}\\sum _{M}z_{M} q(i)_{M}   .\r\n\\end{equation} \r\n\r\n%Could have the following\r\n\\subparagraph{Assumptions} \r\nFor the following, it is assumed that the surface and aqueous species are in equilibrium.\r\n%\\todo{Need short description here}\r\n\r\n%%\\subparagraph{Data Needs}\r\n%%\\todo{Need short description here}\r\n\r\n\\paragraph{Surface Complexation.} \r\n\\label{sec:surfaceComplexation} An alternative approach that allows a modeler to describe sorption while\r\nsimultaneously considering variable chemical conditions in the subsurface is a surface complexation model \\citep{davis-2004}.  \r\nIn this approach, the sorbing sediment surfaces are considered to possess\r\nsurface functional groups that can form complexes analogous to the\r\nformation of aqueous complexes in solution.  \r\nThese surface reactions include proton exchange, cation binding and anion binding via ligand\r\nexchange at surface hydroxil sites (represented here as $XOH$ to avoid\r\nconfusion with other chemical species). \r\nFor example, the sorption of a metal could be represented as\r\n%\r\n\\begin{equation} \\label{eq:metalSorption} \r\n  XOH + M^{z_+} \\leftrightharpoons XOM^{z_+ - 1} + H^{+}  .\r\n\\end{equation} \r\n\r\nAt equilibrium, the sorption reactions can be described by the mass law equation\r\n%\r\n\\begin{equation} \\label{eq:sorptionMassAction}\r\n  K_{app} =\\frac{\\left[XOM^{z_{+}-1 } \\right]\\{H^{+} \\} }{\\left[XOH\\right] \\{M^{z+} \\} }  ,\r\n\\end{equation} \r\nwhere $K_{app}$ is referred to as the apparent equilibrium constant,\r\nbecause it includes surface charge effects and hence is dependent on\r\nthe extent of surface ionization \\citep{dzombak-1990}, $\\{i\\}$\r\nis the thermodynamic activity of aqueous species $i$, and the terms in\r\nsquare brackets represent the concentration of surface complexes (mol/kg).\r\n\r\nSurface complexation differs from the simpler isotherm and\r\nion-exchange models in several important ways. Surface complexation is\r\nbased on the electrical double layer (EDL) theory. EDL theory assumes\r\nthat the surface charge of a sorbent in contact with solution\r\ngenerates an electrostatic potential that declines rapidly away from\r\nthe sorbent surface, creating an electrostatic field. An additional\r\nenergetic term accounting for the work needed for the aqueous species\r\nto travel across the surface electric field is required:\r\n%\r\n\\begin{eqnarray} \\label{eq:EDLdeltaG}\r\n\\Delta G_{ads} & = & \\Delta G_{intr} + \\Delta G_{coul} \\nonumber \\\\\r\n               & = & \\Delta G_{intr} + (\\Delta G_{\\psi =0} - \\Delta G_{\\psi =\\psi_{0} } ) \\nonumber \\\\\r\n               & = & \\Delta G_{intr} - z F \\psi_{0}  .\r\n\\end{eqnarray} \r\n\\noindent where $\\Delta G_{ads} $ is the free energy change of the overall adsorption reaction, $\\Delta G_{intr} $ and $\\Delta G_{coul} $ are the free energy change due to chemical bonding and to the electrostatic work (Coulombic attraction), respectively, $z$ is the charge of the surface species, $F$ the Faraday's constant (96485 C/mol), and $\\psi _{0} $ is the mean surface potential ($V$). Since\r\n%\r\n\\begin{equation} \\label{eq:deltaGKeq}\r\n  \\Delta G = -RTlnK,\r\n\\end{equation}\r\n%\r\n\\noindent Equation~\\eqref{eq:EDLdeltaG} can be rewritten as\r\n\\begin{equation} \\label{eq:KappEDL} \r\nK_{app}  = K_{int} \\exp\\left({\\frac{z F \\psi _{0} }{RT} } \\right),\r\n\\end{equation} \r\nwhere $R$ is the gas constant (8.314 J/mol/K), $T$ is the absolute\r\ntemperature (K), and $K_{int}$ is the intrinsic equilibrium constant\r\nwhich does not depend on the surface charge.\r\n\r\n%Could have the following\r\n%\\subparagraph{Assumptions}\r\n%\\subparagraph{Issues Associated with the Application of Surface Complexation}\r\n\r\n\\subparagraph{Bulk and Mineral Specific Surface Complexation. }\r\n\r\nThere are two major approaches for applying the surface complexation\r\nconcept to soils and sediments: the Component Additivity (CA) and\r\nGeneralized Composite (GC) approaches \\citep{davis-2004, davis-1998}. In\r\nthe CA approach, it is assumed that a mineral assemblage is composed\r\nof a mixture of one or more reference phases, whose surface chemical\r\nreactions are known from independent studies of each phase \\citep[e.g.][]{\r\nlandry-2009, davis-2004, arnold-2001}. Based\r\non a measurement of the relative amounts or surface areas of each\r\nmineral present in the soil or sediment, sorption by the mixture of\r\nphases can be predicted by an equilibrium calculation, without any\r\nfitting of experimental data for the mixture. CA model predictions are\r\nsometimes made by assuming that one mineral component dominates\r\nsorption \\citep{zhang-2009, davis-2004, payne-2004, barnett-2002},\r\n% Barnett et al., 2002\r\nallowing a straightforward equilibrium calculation, if the exposed\r\nsurface area of that mineral component in the soil or sediment can be\r\nquantified.\r\n\r\nIn the GC approach, the surface of the mineral assemblage is\r\nconsidered too complex to be quantified in terms of the contributions\r\nof individual phases to sorption and/or that the contribution of\r\nindividual components is not additive. The complexity is caused, in\r\npart, by the difficulties in quantifying the electrical field and\r\nproportions of surface functional groups at the mineral-water\r\ninterface in the mixture of mineral phases and associated surface\r\ncoatings. In the GC approach, it is assumed that sorption can be\r\ndescribed by mass laws written with ``generic'' surface functional\r\ngroups, with the stoichiometry and formation constants for each mass\r\nlaw determined by fitting experimental data for the mineral assemblage\r\nas a whole \\citep{hyun-2009, bond-2008, davis-2004}. \r\n%Bond et al., 2008;\r\nThe GC modeling approach has generally been applied using a\r\nnon-electrostatic model (NEM), which considers surface equilibria\r\nstrictly as chemical reactions without explicit correction for\r\nelectrostatic attraction or repulsion \\citep{yabusaki-2008,\r\n  davis-2004, kent-2000}. In an NEM, the apparent binding constants\r\nand stoichiometry of the mass action equations are derived by fitting\r\nthe \\textit{macroscopic} dependence of adsorption as a function of pH\r\n\\citep{davis-1998}. Because of the exclusion of electrical double\r\nlayer terms, the mass action equations are not expected to provide\r\naccurate representations of the stoichiometry of the reactions\r\n\\textit{at the molecular scale}, however, the surface reactions can\r\nstill be coupled with aqueous complexation reactions to provide\r\nsimulations of macroscopic sorption as a function of aqueous chemical\r\nconditions.\r\n\r\nAlthough there are differences between the GC and CA approaches, \r\nthey are very similar with respect to their scientific basis. \r\nThe following concepts form the basic tenets of both GC and CA modelling approaches \\citep{davis-1998}:\r\n\r\n\\begin{enumerate}\r\n\\item Mineral surfaces are composed of chemical functional groups that can react with dissolved solutes to form surface complexes (coordinated\r\n%~\\todo{coordinated? - Williamson} \r\ncomplexes or ion pairs) in a manner analogous to aqueous complexation reactions in homogeneous solutions.\r\n\r\n\\item The equilibria of surface complexation and ionization reactions can be described via mass law equations, either with or without correction factors applied for electrostatic attraction to or repulsion from the surface.\r\n\r\n\\item The apparent binding constants determined for the mass law equations of surface complexation and ionization reactions are semi-empirical parameters related to thermodynamic constants via rational activity coefficients for surface species.\r\n\\end{enumerate}\r\n\r\nBoth CA and GC models may: \r\n\\begin{enumerate}\r\n\\item be coupled to the same critically reviewed aqueous thermodynamic data\r\n\\item use spectroscopic data to constrain and/or determine surface complex chemical composition and stoichiometry, and \r\n\\item use the same mass laws and surface species. \r\n\\end{enumerate}\r\nThe differences among the model approaches lie primarily in the manner in which the models are calibrated and assumptions about various model parameters (in particular, whether the contributions of the various mineral phases to sorption and electrostatic fields can be considered as additive). CA models have almost always been applied using mass laws with electrostatic correction factors, while GC models have not usually used these factors.\r\n\r\n\\subparagraph{Experimental and Modeling Issues Associated with SCMs for Soils and Sediments.}\r\n\r\nCommon to all applications of surface complexation approaches in soils\r\nand sediments is an initial characterization with respect to surface\r\narea, bulk mineralogy, and clay and organic carbon content.  In\r\naddition, if the sediment is already contaminated with a metal or\r\nradionuclide, a measurement of the labile fraction of the contaminant\r\nneeds to be determined \\citep{kohler-2004, curtis-2004, bond-2008}.\r\n\r\nIn the GC approach, laboratory experiments are conducted with the field site sediments across the range of chemical conditions that are relevant to the scenarios of the physical and temporal modeling domains. Then, mass law relationships are derived that describe the change in metal or radionuclide sorption with variations in the aqueous chemical conditions \\citep{davis-2004}.  Total surface functional groups are typically estimated from surface area measurements.  The number of surface site types and surface binding reactions is a practical modeling decision made based on the goodness-of-fit and the desired number of modeling parameters \\citep{hyun-2009}.\r\n\r\nIn the CA modeling approach, after the sediment mineralogy is known, an estimate of the distribution of mineral surface areas is made.  This can be done by simply assuming that the bulk weight abundances of various mineral phases are related to the distribution of functional groups at the sediment surface.  For example, if quartz represents 60\\% by weight of the sediment, then an initial estimate could be that 60\\% of the surface area is represented by the quartz surfaces. Then a model of metal or radionuclide adsorption on quartz (as a function of chemical conditions relevant to the field site) is chosen from available literature data.  Similar models for other minerals in the sediment are also catalogued.  In some cases, model parameters may need to be re-derived from the original experimental data to develop a dataset that is self-consistent. In particular, this may be necessary if different electrical double layer models were used in the reference mineral models.  Other approaches for estimating the distribution of mineral surface areas may be used, including chemical extractions and other methods \\citep{davis-2004, davis-1998}.  Once the component mineral models have been chosen, a predictive calculation of metal or radionuclide sorption for a specific set of chemical conditions can be made.\r\n\r\nPossible limitations inherent to the surface complexation approach include poor representation of: a) surface functional groups, b) surface area, c) electrical double layer properties, d) surface species, e) surface binding constants, and f) competing surface reactions and their electrostatic effects. These limitations exist for both GC and CA modeling approaches, but the GC approach attempts to resolve some of the issues by using empirical data to overcome unknown factors and unmeasured parameters. For example, consider the representation of surface functional groups: Assume that only silanol, aluminol, ferrinol, and clay mineral edge sites are of importance in a particular sediment sample. At present it is very difficult or expensive to determine the distribution of mineral surface areas in a mixed mineral assemblage. Extractions, X-ray diffraction, and surface spectroscopies have been used by various investigators, but each of these methods provides estimates that are difficult to confirm independently. This uncertainty is circumvented in the GC approach by assuming that the distribution of site types is an unknowable quantity, and only generic sites are used. However, this requires that experimental data for the metal or radionuclide sorption on a site-specific sediment sample are collected, whereas in principle at least, additional characterization experiments are not needed for the CA modeling approach.\r\n\r\n\\subparagraph{Quantifying Surface Sites}\r\n\r\nSurface area is an important experimental quantity to be characterized in all surface complexation approaches. Typically a mixed mineral assemblage is characterized by BET analysis of nitrogen gas adsorption. Adjustments may need to be made for samples that contain high abundances of clay minerals, depending on whether there is evidence of sorption on the basal planes of clay mineral particles. Many investigators have concluded that surface functional groups of the basal planes are unreactive for metal and radionuclide sorption, and therefore the surface area of the basal planes does not need to be included in most applications. Fortunately, the BET method does not typically measure the surface area of the basal planes. In GC applications, the surface area is typically used in a straightforward manner to quantify the total abundance of surface sites using a conversion factor. In CA applications, however, the surface area should be distributed among different functional group types.\r\n\r\nMultiple site-types are commonly used in formulating SCMs and approximate the nonlinear isotherms commonly observed for cation adsorption on well-characterized oxide mineral phases \\citep{dzombak-1990, davis-1990}.  Postulating multiple site-types is also important for simulating peak tailing observed in experimental studies of U(VI) transport in columns \\citep{kohler-1996}.  Reactive transport simulations that use multisite adsorption models can also simulate significant peak tailing in field-scale simulations \\citep{curtis-2006, kent-2000, kent-2007, kent-2008}. \r\n\r\n%\\subparagraph{Data Needs}\r\n\r\n\\subparagraph{Sub-models}\r\n\r\n\\begin{enumerate}\r\n\\item \\textbf{Non-electrostatic Models:}\r\nEDL models differ in whether coulombic attraction or repulsion terms are considered in the mass laws of surface reactions. A non-electrostatic EDL means that the term\r\n\\begin{equation}  \\label{eq:ElectrostaticExponential}\r\n  \\exp\\left(\\frac{zF\\psi_0 }{RT}\\right) \r\n\\end{equation}\r\nin Equation~\\eqref{eq:KappEDL} need not be considered. \r\nWhile electrical double layer (EDL) models may represent these terms well for simple systems with single mineral phases, \r\nthe approaches for treating these terms in mixed mineral assemblages have not been studied. \r\nIn Component Additivity (CA) \\citep{davis-2004, davis-1998} applications to sediments, \r\ntypically authors assume that the EDL properties of pure, clean mineral phases \r\ninvestigated remain the same in mixed mineral assemblages \\citep{davis-2004}. \r\nThis ignores the likely effects of surface contaminants (adsorbed major solutes such as silicate, organic compounds, etc.) \r\nand the overlapping EDL regions of particles that are known to change coulombic terms. \r\nIn Generalized Composite (GC) approaches \\citep{davis-2004, davis-1998}, \r\nthe coulombic attraction or repulsion terms are not included, \r\nbut are instead built into the semi-empirical model calibration of reaction stoichiometries and binding constants to experimental data. \r\nThat is, whatever EDL forces exist, they are lumped into the model fitting of reactions and binding constants. \r\nIn each case, there is inherent uncertainty in the modeling approach. \r\nThe errors within the GC model may not be that significant because of model calibration to experimental data, \r\nbut the error is only minimized by confining model calculations to chemical conditions interpolated between those \r\ninvestigated in laboratory experiments. \r\nExtrapolation of any non-electrostatic model to uninvestigated chemical conditions is unwise \r\nbecause the EDL forces for those conditions will not necessarily be captured accurately by the model calibration. \r\nIn addition the formation of unknown surface species may not be realized if calculations are extrapolated to chemical conditions \r\nnot investigated at all.\r\n\r\n\\item \\textbf{Electrostatic models:}\r\nWhen the coulombic attraction or repulsion terms is considered as shown in Equation~\\eqref{eq:KappEDL}, \r\nthe electrostatic models differs also among themselves in how they conceptualize the structure of the double-layer \r\nand describe changes in surface potential and surface charge from the surface of the sorbent phase to the bulk solution. \r\nIn the constant capacity and diffuse-layer models, all adsorbed species are considered specifically adsorbed at the zero plane \r\nwhile the triple layer model can assign adsorbed species to either a zero plane or more distant plane. \r\nThe constant capacity and diffuse-layer model are elaborated in the following sections.  \r\n\r\n\\begin{enumerate}\r\n\\item \\textbf{Constant Capacitance} The constant capacitance model is\r\n  a special case of the diffuse-layer model. Both models are based on\r\n  the assumption that all the species are adsorbed in the same layer\r\n  and a diffuse layer of counterions constitutes the transition to\r\n  homogenous solution.  Additionally, it is assumed that the surface\r\n  potentials are small, or the double layer has been compressed (very\r\n  high ionic strength).  However, differently from the diffuse-layer\r\n  model, the relationship between the surface charge and the potential\r\n  is assumed to be linear:\r\n%\r\n\\begin{equation} \\label{eq:constantCapacitance} \r\n  \\sigma  = \\mathbb{C}\\psi  ,\r\n\\end{equation} \r\nwhere $\\sigma$ is the surface charge, $C\\;m^{-2}$, $\\psi$ is the\r\npotential at the surface, $V$, and $\\mathbb{C}$ is a constant\r\ncapacitance value, $C\\;V^{-1}\\;m^{-2}$, to be obtained from fitting\r\nexperimental data.  Equation~\\eqref{eq:constantCapacitance} is solved\r\nfor the potential and substituted into Equation~\\eqref{eq:KappEDL}.\r\n\r\n\\item \\textbf{Diffuse Double Layer Model}\r\nThe diffuse layer model has been described in great detail by \\citet{dzombak-1990} and was applied to adsorption of metals on iron oxide surfaces. In the diffuse layer model, the solid-water interface is composed of two layers: a layer of surface-bound complexes and a diffuse layer of counter ions in solution. The surface charge is calculated from the total surface species adsorbed on the layer:\r\n\\begin{equation} \\label{eq:doubleLayerSurfaceChargeDensity} \r\n  \\sigma _{p} = \\frac{F}{A} \\sum _{k=1}^{N_{s} } z_{k} y_{k}  .\r\n\\end{equation} \r\nHere $A$ is the surface area sorbent per liter solution ($m^2/L$), $F$ is the\r\nFaraday constant ($96,480 C/mol$), $z_k$ is the charge of the ion, and $y_k$ is the concentration (mol/L) of surface bound ions in the Stern Layer.  According to the Gouy-Chapman theory, the surface charge density $\\sigma_{p}$ ($C/m^2$) is related to the potential at the surface (volts) by:\r\n\\begin{equation} \\label{eq:doubleLayerGouyChapman} \r\n  \\sigma _{p}  =  (8RT\\epsilon_R \\ \\epsilon _{0}\\; C_e \\times 10^{3} )^{1/2} \\sinh \\left(\\frac{zF \\psi _0 }{ 2RT}\\right)  ,\r\n\\end{equation} \r\nwhere $R$ is the molar gas constant (8.314 $J mol^{-1} K^{-1}$), $C_e$\r\nis the molar electrolyte concentration ($M$), $z$ is the electrolyte\r\ncharge, $T$ is the absolute temperature ($K$), $\\epsilon_R$ is the\r\nrelative dielectric constant of water ($\\epsilon = 78.5$ at\r\n$25^{\\circ}C$), and $\\epsilon_{0}$ is the permittivity of free space\r\n($8.854\\times 10^{-12}$ $C\\;V^{-1} m^{-1}$).  Equation\r\n\\eqref{eq:doubleLayerGouyChapman} is only valid for a symmetrical\r\nelectrolyte, the anion and cation must have the same charge.  Note\r\nthat $C$ the unit (coulombs or celcius) is not a concentration.\r\nCapacitance is not solved for explicitly, but is implicitly accounted\r\nfor in Equation~\\eqref{eq:doubleLayerGouyChapman}.  It is common to use\r\nthe linearized version of Equation \\eqref{eq:doubleLayerGouyChapman} for\r\nlow values of the potential:\r\n%\r\n\\begin{equation} \\label{eq:doubleLayerLinearizedGouyChapman} \r\n  \\sigma _{p} =\\epsilon \\ \\epsilon _{0} \\kappa \\psi _{0},\r\n\\end{equation} \r\nwhere $1/\\kappa$ (m) is the double-layer thickness defined as\r\n%\r\n\\begin{equation} \\label{eq:doubleLayerThickness} \r\n  \\frac{1}{\\kappa }  = \\left( \\frac{\\epsilon \\ \\epsilon_{0} RT}{2 F^{2} \\cdot 1000 \\;I} \\right)^{1/2}  ,\r\n\\end{equation} \r\nwhere $I$ is the ionic strength $mol\\;L^{-1}$. The first term of Equation~\\eqref{eq:doubleLayerGouyChapman}, $(8RT\\epsilon \\ \\epsilon _{0} C_e \\times 10^{3} )^{1/2}$, can be rewritten at $25^{\\circ}C$:\r\n%\r\n\\begin{equation} \\label{eq:doubleLayerGouyChapman25} \r\n  \\mathop{\\sigma }\\nolimits_{p} = 0.1174\\;C_e^{1/2} \\sinh \\left( \\frac{zF \\psi_d}{2RT} \\right) .\r\n\\end{equation} \r\nTherefore, in the diffuse-layer model, the value of the capacitance $\\mathbb{C}$ relating the surface charge and the potential can be calculated based on theoretical considerations instead of being an experimental fitting parameter.\r\n\r\n\\item \\textbf{Triple Layer Model} \r\nThe triple layer model is similar to the double layer model, but\r\ndivides the sorbed species into two layers,\r\nFigure~\\ref{fig:triple-layer-model}. Strongly sorbed species are\r\nlocated close to the surface, the zero plane, while weakly sorbed\r\nspecies reside in the beta plane, seperated from the surface by the\r\nstrongly sorbed species and hydration layers \\citep[e.g.][]{langmuir-1997}. Further out from the surface is a diffuse layer and the bulk solution similar to the double\r\nlayer.\r\n\r\nThe charge balance equation for the triple layer model is\r\n\\begin{equation}\r\n  \\sigma_0 + \\sigma_{\\beta} + \\sigma_d = 0,\r\n\\end{equation}\r\n\\noindent where $\\sigma_0$, $\\sigma_{\\beta}$ and $\\sigma_d$ are the\r\nnet surface charges in the zero, beta and diffuse planes respectively, ($C/m^2$).\r\nThe net surface charge in the zero plane is given by:\r\n\\begin{equation}    \\label{eq:ChargeDensityZeroPlane}\r\n  \\sigma_0 =  \\frac{F}{A} \\sum _{k=1}^{N_{s} } z_{k} y^{0}_{k}  ,\r\n\\end{equation}\r\nwhere the variables are as defined in Equation \\eqref{eq:doubleLayerSurfaceChargeDensity} with the exception of $y^{0}_{k}$, which is the concentration (mol/L) bound in the zero plane. Similarly, the net surface charge of the beta plane is\r\n\\begin{equation}    \\label{eq:ChargeDensityBetaPlane}\r\n  \\sigma_{\\beta} =  \\frac{F}{A} \\sum _{k=1}^{N_{s} } z_{k} y^{\\beta}_{k}  ,\r\n\\end{equation}\r\nwhere $y^{\\beta}_{k}$ refers to the ions bound in the beta plane.\r\nNote that the composition of the diffuse layer is not often calculated explicitly in either Triple Layer Model or the Diffuse Double Layer Model, although a method to do so has been presented by \\citet{leroy2007modeling}.\r\n\r\nThe triple layer model assumes constant capacitances between the zero\r\nplane and beta plane, $\\mathbb{C}_1$, and the beta plane and d-plane, $\\mathbb{C}_2$.\r\nThese are related to the surface charges and potentials by:\r\n%\\todo{Two captions here and it is not referenced. -Williamson}\r\n\\begin{eqnarray}\r\n  \\sigma_0 &=& \\mathbb{C}_1 \\left( \\psi_0 - \\psi_{\\beta} \\right), \\\\\r\n  \\sigma_{\\beta} &=& \\mathbb{C}_1 \\left( \\psi_{\\beta} - \\psi_0 \\right) + \\mathbb{C}_2 \\left( \\psi_{\\beta} - \\psi_d \\right),\\\\\r\n  \\sigma_{d} &=& \\hspace{28mm}\\mathbb{C}_2 \\left( \\psi_d - \\psi_{\\beta} \\right).\r\n\\end{eqnarray}\r\n\r\n\\begin{figure}\r\n  \\begin{center}\r\n    \\includegraphics[width=0.75\\linewidth]\r\n                    {figs/sorption/goncalves-2007-TLM-Fig-a.pdf}\r\n    \\\\[24pt]\r\n    \\includegraphics[width=0.75\\linewidth]\r\n                    {figs/sorption/goncalves-2007-TLM-Fig-b.pdf}\r\n  \\end{center} \r\n  \\caption{Schematic of the TLM model from \\citet{goncalves-2007}.}    \r\n  \\label{fig:triple-layer-model}\r\n\\end{figure}\r\n\r\n\\end{enumerate}\r\n%  End electrostatic models\r\n\r\n\\end{enumerate}\r\n%  End sub-models\r\n\r\n\\subsubsection{Common Data Needs for Sorption Models}\r\n%\\todo{Need to gather more requirements for this}\r\n\r\nAll sorption models will require access to a database of parameter values that are potentially independent of the specific contaminated site under consideration.  For example, the cation exchange capacity (CEC) of a mineral like smectite or kaolinite can be described with a range of values.  However, it is likely that site-specific experimental data will have to\r\nbe collected and either collected in a site-specific database, or serve as the basis of a site-specific lookup table.\r\n\r\n%\\todo{Davis: A database for Freundlich parameters is required? Is\r\n% there such a database? In general, I think the model requirements\r\n% for Kd, Langmuir, Freundlich, surface complexation and ion exchange\r\n%  should state that it is likeley that experimental data have to be\r\n%  collected with site-specific samples.}\r\n\r\n", "meta": {"hexsha": "b0fa5394f2bd2b9ec080601b6ca80f0014474202", "size": 34951, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/theory_guide/sorption.tex", "max_stars_repo_name": "fmyuan/amanzi", "max_stars_repo_head_hexsha": "edb7b815ae6c22956c8519acb9d87b92a9915ed4", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": 37, "max_stars_repo_stars_event_min_datetime": "2017-04-26T16:27:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T07:38:57.000Z", "max_issues_repo_path": "doc/theory_guide/sorption.tex", "max_issues_repo_name": "fmyuan/amanzi", "max_issues_repo_head_hexsha": "edb7b815ae6c22956c8519acb9d87b92a9915ed4", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": 494, "max_issues_repo_issues_event_min_datetime": "2016-09-14T02:31:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T18:57:05.000Z", "max_forks_repo_path": "doc/theory_guide/sorption.tex", "max_forks_repo_name": "fmyuan/amanzi", "max_forks_repo_head_hexsha": "edb7b815ae6c22956c8519acb9d87b92a9915ed4", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": 43, "max_forks_repo_forks_event_min_datetime": "2016-09-26T17:58:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T02:29:59.000Z", "avg_line_length": 66.7003816794, "max_line_length": 1433, "alphanum_fraction": 0.7611227147, "num_tokens": 8937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6513548511303336, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3358515334456}}
{"text": "\\documentclass{article}\n\n\\usepackage[final]{styles}\n\\usepackage[utf8]{inputenc} % allow utf-8 input\n\\usepackage[T1]{fontenc}    % use 8-bit T1 fonts\n\\usepackage{hyperref}       % hyperlinks\n\\usepackage{url}            % simple URL typesetting\n\\usepackage{booktabs}       % professional-quality tables\n\\usepackage{amsfonts}       % blackboard math symbols\n\\usepackage{nicefrac}       % compact symbols for 1/2, etc.\n\\usepackage{microtype}      % microtypography\n\\usepackage{amsmath}\n\\usepackage{amsthm}\n\\usepackage{amssymb}\n\\usepackage{tikz}\n\\usepackage{csquotes}\n\\usepackage{float}\n\\title{Unifying Inference in Ergodic World Models}\n% \\title{Unifying Inference in Ergodic Latent Space}\n% \\title{Free-energy Dynamics in Ergodic Domains}\n% \\title{Fast \\& Slow Inference in Ergodic Domains}\n% The \\author macro works with any number of authors. There are two commands\n% used to separate the names and addresses of multiple authors: \\And and \\AND.\n%\n% Using \\And between authors leaves it to LaTeX to determine where to break the\n% lines. Using \\AND forces a line break at that point. So, if LaTeX puts 3 of 4\n% authors names on the first line, and the last on the second line, try using\n% \\AND instead of \\And before the third author name.\n\n\\author{%\n  Luke J. Pereira \\\\\n%   \\texttt{lukejoepereira@gmail.com} \\\\\n  % examples of more authors\n  % \\And\n  % Coauthor \\\\\n  % Affiliation \\\\ consciousness\n  % Address \\\\\n  % \\texttt{email} \\\\\n  % \\AND\n  % Coauthor \\\\\n  % Affiliation \\\\\n  % Address \\\\\n  % \\texttt{email} \\\\\n  % \\And\n  % Coauthor \\\\\n  % Affiliation \\\\\n  % Address \\\\\n  % \\texttt{email} \\\\\n  % \\And\n  % Coauthor \\\\\n  % Affiliation \\\\\n  % Address \\\\\n  % \\texttt{email} \\\\\n}\n\n\\begin{document}\n\\maketitle\n% \\vspace{-0.5cm}\n\n\\begin{abstract}\n\nFast and slow inference are presented as trajectories existing on a high-dimensional spectrum with their extrema bounding surfaces of a latent phase space. On one end, an Autoencoder is trained on sensory observations and impresses latent encodings onto a Discriminator-like energy manifold. On the other end, the latent space is delimited by repeating the training process on sparse and low-dimensional symbolic abstractions, producing an upper bounding manifold. An agent's trajectory corresponds to a flow of a symbolic dynamical system that minimizes the KL divergence between the upper and lower boundaries, which minimizes the free-energy of the system and can be learned from a series of initial value random walks.\n\n% (Equivilently complex PDEs trajectories have dimensions reduced using ordinary differential representation of neural networks.)\nBirkhoff's theorem states that in an ergodic domain, the average of a function $f$ over an infinite number of flows converges to the continuous integral of the function over the phase space. Defining $f$ to be a function that minimizes the joint divergence of the boundaries of a world model will produce a measure preserving ergodic flow. Moreover, we can show that the time average can be derived from inference using standard Bayesian expected loss while the space average can be derived from energy-based inference methods. This reveals that the two methods of inference become pointwise unified in ergodic domains, like language generation. This in turn explains the effectiveness of modern deep learning methods that, despite being restricted to surface level System 1 thinking, are able to imitate System 2 thinking. It is possible for a model to learn how to construct and maintain a minimal ergodic latent space even when sampling from sparse non-ergodic observations. This pointwise equivalence enables an agent to fluidly switch between systems of thinking and improve inference performance.\n\n\n\n% known as a time average, known as its space average\n% The  implications of an analogous process potentially occurring in biological neural configurations are examined.\n%\\textbf{}\n% Free energy minimization unifies fast and slow thinking in ergodic latent spaces. \n%  where the time average of infinitely many trajectories approach an equivalence to an integral of a space average\n%  correspond to inference that has been perfected by SOTA machine learning models vs. dialogue response needed to pass a sufficient Turing test,\n\n% If we think of the measure as being an associative memory dimension, we find that the time average of\n\n% Internal modesls correspond to intermideary state between humans and the world\n\\end{abstract}\n\n\\section{Systems of Thinking}\n\nIn \\textit{Thinking, Fast and Slow} (Kahneman, 2011), cognitive processes are categorized into two modes. In System 1, thought processes are fast, intuitive, unconscious, and habitual. In System 2, thought processes become slower, logical, conscious, algorithmic, and may involve planning or reasoning. It can be claimed that the system of fast thought closely corresponds to many state-of-the-art deep learning approaches (Bengio, 2019). These methods aim to discover underlying distributions of data in the form of a normalized probability density by training on many examples while minimizing a cost function. In doing so, a model is able to quickly perform inference when being tested on unseen examples. \n% Training probabilistic models with neural networks is intractable in many cases and requires using expensive and problematic approximate inference algorithms like Markov chain Monte Carlo (MCMC) or mean-field variational inference (VI).\nSystem 2 thinking instead embodies the future aspirations of models that require very few examples and can learn in a self-supervised manner. Though the model may perform inference slowly, this method of thinking appears to be a necessary aspect in developing an artificial general intelligence (AGI) that matches and exceeds our own abilities. It's possible to draw a comparison between System 2 thinking and energy-based models (EBM) which aim to capture dependencies between variables by associating a scalar energy to each configuration of the variables (LeCunn, 2006). Learning is often faster than with a standard loss functions and consists in finding an energy function where observed configurations of the variables are given lower energies than unobserved ones. Inference is often slower and involves searching the energy function using optimization methods like stochastic gradient descent to find compatible variables that minimize the energy function. \n\n% where learning consists of finding an energy\n% function so that observed configurations of the variables are given lower energies than unobserved ones.  an energy function $F$ by using contrastive or regularized latent variable methods. Inference  involves searching the energy function using a optimization methods like gradient descent to find compatible $y$’s that minimize $F$. This can be expressed as $\\hat y = \\text{argmin}_{y}{F(x, y)}$\\footnote{\\url{https://lukepereira.github.io/notebooks/documents/2020-neural-nets/main.pdf}}. \n\n\n\\section{Birkhoff's Ergodic Theorem}\nA dynamical system, usually written as the tuple $(T, X)$, is described by a transformation that maps a phase space onto itself, $T: X \\to X$. The set of points attained from repeated applications of the transformation from some starting point is known as its forward orbit or trajectory. ergodicity can be viewed as an indecomposability condition and is concerned with how a typical orbit of a dynamical system is distributed throughout the phase space with these qualitative distributional properties being expressed in terms of measure theory. Measure preserving means that $P(T^{-1}(A)) = P(A)$ for all measurable sets $A \\in \\mathcal A$. ergodic means that $T(A) = A$\nimplies $P(A) = 0$ or $P(A) = 1$ for all $A \\in \\mathcal A$.\n\n\\textit{Birkhoff's Ergodic Theorem} states that if a mapping is ergodic, as the number of finite averages taken along any of its orbits increases to infinity (the time average), this value will converge to the continuous integral (the space average). That is, a finite average sampling of points of any orbit will be as accurate as a continuous average integral over the entire state space.  Formally, let $(X, \\mathcal{B}, \\mu)$ be a probability space and let $T : X \\mapsto X$ be a measure-preserving transformation (on a $\\sigma$-finite measure space $\\mu(X)< \\infty$). If $f$ is any integrable function and $T$ is ergodic, then the time average is constant in measure $\\mu$ almost everywhere and is equivalent to the space average,\n\\begin{align*}\n    \\underbrace{\n        \\lim_{n\\to \\infty} \\frac{1}{n}\\sum_{i=0}^{n-1}f(T^{i}(x))\n    }_\\textrm{Time Average, $\\hat f$} \n    &=  \\underbrace{\n        \\vphantom{ \\sum_{i=0}^{n-1} }\n        \\frac{1}{\\mu(x)} \\int_{X} f d \\mu\n    }_\\textrm{Space Average, $\\bar f$}\\\\\n    \\intertext{Corollary (Point-wise Ergodic Theorem):}\n        \\lim_{n\\to \\infty} \\frac{1}{n}\\sum_{i=0}^{n-1}f(T^{i}(x))\n    &=  \n        \\vphantom{ \\sum_{i=0}^{n-1} }\n        E(f)\n\\end{align*}\nWorking backwards from the expected value, we can derive the standard Bayesian training method of averaging over a large number of training examples.  We consider $x \\in X$ to be a sampled observation, $f$ is our cost minimization function, and $T$ represents a transformation attained from a trained model that encodes and predicts a future state. As the number of training orbits increases to infinity, the encoding and prediction mechanisms converge to the continuous integration over the space and the expected output of the function in the point-wise interpretation.\n\nEnergies can be thought of as being \\textit{unnormalized negative log probabilities}. That is, we may use the Gibbs-Boltzmann distribution to convert an energy function to its equivalent probabilistic representation after normalization, i.e. $P(y \\mid x)$. Recall, \\textit{marginalisation} is a method that sums over the possible values of one variable to determine the marginal contribution of another. $P(y \\mid x)$ is just an application of the Gibbs-Boltzmann formula with latent variables $z$ being marginalized implicitly through integration, i.e. $P(y \\mid x) = \\int_z P(y,z | x)$. Then,\n\\begin{align*}\n    P(y \\mid x) &= \\frac{ \\int_z \\exp(-\\beta E(x,y,z)) }{ \\int_y \\int_z \\exp(-\\beta E(x, y, z))} \\\\\n    % &= \\frac{\n    %     \\exp \\bigg [  -\\beta (-\\frac{1}{\\beta} \\log  \\int_z \\exp(-\\beta E(x,y,z)) ) \\bigg ]\n    % }{\n    %     \\int_y \\exp \\bigg [  -\\beta (-\\frac{1}{\\beta} \\log  \\int_z \\exp(-\\beta E(x,y,z)) ) \\bigg ]\n    % }\n\\end{align*}\nThe derivation introduces a $\\beta$ term which is the inverse of temperature $T$, so as $\\beta \\rightarrow \\infty$ the temperature goes to zero. $\\beta$ is a positive constant that needs to be calibrated to fit the model. A larger $\\beta$ value produces a more fluctuate model while a smaller $\\beta$ gives a smoother model. When $\\beta \\rightarrow \\infty$, we see that $\\check{y} = \\text{argmin}_{y} E(x,y)$. So we can redefine our energy function as an equivalent function using $F_\\beta$,\n\\begin{align*}\n    F_{\\infty} (x,y) &= \\text{argmin}_z E(x,y,z)\\\\\n    F_{\\beta} (x,y) &= -\\frac{1}{\\beta} \\log \\int_z \\exp(-\\beta E(x,y,z)).\n\\end{align*}\n\nIn physics, $F_\\beta$ is known as the free energy and $E$ is the energy. If we have a latent variable model and want to eliminate the latent variable $z$ in a probabilistically correct way, we just need to redefine the energy function in terms of $F_\\beta$,\n\\[\n    P(y \\mid x) = \\frac{ \\exp(-\\beta F_\\beta(x,y,z)) }{ \\int_y \\exp(-\\beta F_\\beta(x, y, z))}. \\\\\n\\]\n\n% The Bayes classifier is\n% \\[\n% C^\\text{Bayes}(x) = \\underset{r \\in \\{1,2,\\dots, K\\}}{\\operatorname{argmax}} \\operatorname{P}(Y=r \\mid X=x).\n% \\]\n% \\textit{The ergodic hypothesis} says that, over long periods of time, the time spent by a system in some region of the phase space of microstates with the same energy is proportional to the volume of this region, i.e., that all accessible microstates are equiprobable over a long period of time.\n\n\n\n\\section{Ergodic World Models}\n% If we let $E(f|{\\mathcal {C}})$ be the conditional expectation given the $\\sigma$-algebra ${\\mathcal {C}}$ of invariant sets of $T$, then the probabilistic formulation is given by the Birkhoff–Khinchin theorem, \n% \\[\n% \\displaystyle \\lim_{n\\to \\infty} \\frac{1}{n}\\sum_{i=0}^{n-1}f(T^{i}(x)) = E(f\\mid {\\mathcal {C}})(x)\n% \\]\n\n% procedure minimizes the standard Kullback-Leibler (KL) divergence $\\text{KL}(q_\\theta(z) || p(z | x))$, where $q_\\theta(z)$ is an explicit amortized distribution.\n\n% Zhang et al. (2018) described a method to combine MCMC with VI that tries to directly minimize KL(q(t)θ(z) || p(z | x)), which is intractable\nWe see that in ergodic domains, an averaging of an increasingly large number of examples will become increasingly close to the average behaviour of the underlying causative process depicted by the space average integral. We can claim an equivalence between the time averages of a summation with the first system of thinking and the space average of an integral with the second system of thinking. It can then be claimed that the dichotomy of the systems of thought become increasingly unified in ergodic domains.\n\nIn environments that contain non-ergodic domains, a learning agent can establish an internal ergodic world model by actively selecting which observations are sampled and manipulating how these observations are encoded and stored. To maintain ergodic averages, only a local stablility is necessary, making this model biologically plausible. An ergodic world model allows the agent to attain a pointwise fluidity between System 1 and System 2 inference capabilities which ultimately improves its decision-making speed and quality in unpredictable environments. When applied to the energy-based dynamical system described in a previous paper, the latent space explored during the dream phase of training can be manipulated in order to generate ergodic measure preserving flows despite the external world explored during its waking test phase not necessarily being ergodic. Recall, the flows are attained by minimizing the free-energy of the system, represented as a Kullback–Leibler divergence or relative entropy of bounding energy manifolds. \n\nIt follows that the latent trajectories can be interpreted with symbolic dynamics. A symbolic orbit is a sequence of symbols corresponding to the successive partition elements visited by the point in its orbit is typically be represented as a Bernoulli Scheme. Instead, we use an Autoencoder to learn an encoding that will partition the space while maintaining ergodicity. This means the learned trajectories on the discrete space will on average be consistent with those in dense continuous space, which reduces the memory and computation of what would otherwise involve solving high dimensional differential equations on a continuous domain. The learned symbolic encodings of the Autoencoder are closely correlated with the form of the latent world model itself.\n\n\n\\subsection{Ornstein Isomorphism Theorem}\nThe Ornstein isomorphism theorem is a deep result for ergodic theory. It states that if two different Bernoulli schemes have the same Kolmogorov entropy, then they are isomorphic. It reveals that many systems previously believed to be unrelated are in fact isomorphic; these include all finite stationary stochastic processes, including Markov chains and subshifts of finite type, Anosov flows and Sinai's billiards, ergodic automorphisms of the n-torus (uniform hyperbolic dynamics), and the continued fraction transform.\n\n\n% \\section{Language-based Thought as an Ergodic Domain}\n% We see that in Ergodic domains, an averaging of an increasingly large number of examples will become close to the average behaviour of the underlying causative process captured in the space average integral. We can see an equivalence between the time averages of a summation and the first system of inference and the space average of an integral and the second system of thinking. It can then be claimed that the dichotomy of the systems of thought become unified in Ergodic domains.\n\n% We find evidence for this in the increasing effectiveness of contemporary machine learning models that are trained on a massive number of examples. Language models like GPT-3 are a good example of showing that in certain domains, a large model with billions of parameters will produce output that closely resembles the thinking and reasoning a human does during System 2 cognitive processes, despite the model only ever being trained in a probabilistic System 1 like manner. In other words, we see that GPT-3 produces time-averages that approach the space-average of human thought as the number of example orbits that it is trained on increases. \n\n% Though it may be difficult or even impossible to formally prove, we can use this as evidence to show that language-based thinking is an Ergodic domain. When we think and speak we are fluidly switching between systems of thinking. Moreover, this fluidity between unconscious stochastic inference and conscious deterministic inference will exist in any Ergodic domain. Although modern machine learning techniques appear to be effective at imitating human reasoning in these domains, they require a massive amount of compute and training examples and will be constrained to certain domains of problems. They will also suffer from being unconscious and may lack the ability to perform well in tasks that require creative improvisation that diverges from expected behaviour. This can be thought of as an artist that can successfully write a speech or play but is unable to answer questions well or be interviewed, as is necessary in a Turing test.\n\n% \\section{Implications on Consciousness and Psychology}\n\n% Impactful and traumatic experiences are often difficult to reconcile because our world model becomes deeply shaped around these moments as our mind reinforces its world model over time. The latent space world model is capable of reshaping itself but must always maintain coherence. Here, coherency can be thought of as some threshold on the divergence between experienced reality and feasible observations.\n\n\n% With little control over how our automatic consciousness shapes latent space in to be Ergodic, our world model can grow highly incoherent and stochastic which may result in mental illness. A top-down effort is necessary to push down on the traumatic memory using constrastive methods to reshape the latent space into a coherent and more desirable world model.\n\n% As trajectories move higher in the space, they lose coherence and become highly stochastic. Coherence can be thought of as a divergence value that is normalized with a variable threshold and represents a mask made of potential walls of a certain threshold. the latent space is restricted by some rule-set so that the many orbits through it maintain coherence despite entropy from loss of information.\n\n% The lower bounds of our world model represent our experiences and our memory, while the upper bound represents the limits of coherence in our imaginations.\n% \n% Experiment in mice shows how memories could be altered while at rest\n\n\\section*{References}\n\n\\small\n\n[1] Kahneman, Daniel. Thinking, Fast and Slow. New York: Farrar, Straus and Giroux, 2011. \n\n[2] Bengio, Yoshua, From System 1 Deep Learning to System 2 Deep Learning, NeurIPS 2019.\n\n[3] LeCun, Yann, A Tutorial on Energy-Based Learning, 2006.\n% http://yann.lecun.com/exdb/publis/pdf/lecun-06.pdf\n\n\n% https://arxiv.org/pdf/1811.07192.pdf\n% https://openreview.net/pdf?id=HJx4KjRqYQ\n\n\\end{document}\n", "meta": {"hexsha": "f4d8a4991b3c0809d916015f08359046fc3c2780", "size": 19484, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "documents/2020-ergodic-world-models/main.tex", "max_stars_repo_name": "lukepereira/latex-ci", "max_stars_repo_head_hexsha": "4390a2da344ec00a3f651f464c79b7e097cbabe6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-09-04T20:32:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T21:30:32.000Z", "max_issues_repo_path": "documents/2020-ergodic-world-models/main.tex", "max_issues_repo_name": "lukepereira/latex-ci", "max_issues_repo_head_hexsha": "4390a2da344ec00a3f651f464c79b7e097cbabe6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-07-13T01:21:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-13T02:09:19.000Z", "max_forks_repo_path": "documents/2020-ergodic-world-models/main.tex", "max_forks_repo_name": "lukepereira/latex-ci", "max_forks_repo_head_hexsha": "4390a2da344ec00a3f651f464c79b7e097cbabe6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 99.4081632653, "max_line_length": 1102, "alphanum_fraction": 0.7742763293, "num_tokens": 4514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.3356998489930982}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\section{Machine learning approach}\r\n\\label{sec31}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nMachine learning (ML) is a sub-field of AI which belongs to computer science field. \r\nML is defined as \\say{the ability of a computer to learn without being explicitly programmed}~\\cite{munoz2014machine}.\r\nThe conventional way of software engineering is through creating rules by human and combine them with data to create a solution to a problem.\r\nAlternatively, when it comes to ML, it utilises data and answers to learn the rules behind the problem~\\cite{franoischollet2017learning}.\r\nIn Fig.~\\ref{fig:Machine_learning} the conventional software programming and ML are presented in (a) and (b) respectively.\r\nIn ML, machines have to run into a learning process to learn inference rules which are responsible for controlling the relations within a phenomenon. Hence, it is called a ML.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\begin{figure} [!ht]\r\n\t\\begin{center}\r\n\t\t\\centering\r\n\t\t\\includegraphics[scale=1]{Figures/Chapter_1/machine_learning_vs_conventional_programming.png}\r\n\t\\end{center}\r\n\t\\caption{(a) Conventional Programming\t(b) Machine learning} \r\n\t\\label{fig:Machine_learning}\r\n\\end{figure}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\paragraph{}\r\nML techniques in SHM were heavily utilised by researchers for damage detection~\\cite{raghavan2008effects, Su2009, Mitra2016}.\r\nMoreover, ML techniques attempt to map the patterns of the input data acquired by sensors to output targets for a damage estimation at different levels. \r\nAccordingly, ML techniques demands high domain knowledge of the examiner to perform hand-crafted damage-sensitive feature extraction on the raw data acquired by sensors before being fed into a suitable ML model.\r\nGenerally, the process of damage-sensitive features extraction (hand-crafted) in the field of SHM emerged due to the enormous development in the physics-based SHM techniques such as modal strain energy (MSE)~\\cite{Kim}, modal curvature (MC)~\\cite{Wahab}, modal assurance criterion (MAC), and Coordinate (MAC)~\\cite{Allemang2003}, modal flexibility (MF)~\\cite{Jaishi}, damage locating vector (DLV)~\\cite{Bernal2002}, wavelet transform~\\cite{Staszewski,Kima} and probabilistic reconstruction algorithm (PRA)~\\cite{Hay2006} among others.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nThere are different methods which can be implemented when performing ML. \r\nGenerally, those methods are grouped into four approaches: Supervised learning, Unsupervised learning, Reinforcement learning, and Transfer learning approach.\r\nFig.~\\ref{fig:Machine_learning_approaches} shows the different types of ML approaches.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\begin{figure} [!ht]\r\n\t\\begin{center}\r\n\t\t\\centering\r\n\t\t\\includegraphics[scale=1]{Figures/Chapter_1/ML_approaches.png}\r\n\t\\end{center}\r\n\t\\caption{Machine Learning Approaches} \r\n\t\\label{fig:Machine_learning_approaches}\r\n\\end{figure}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\paragraph{}\r\nSupervised learning is the task of learning a machine the inference rules from the training data, and how to map inputs with outputs.\r\nThe training data is a collection of variables together with its labels e.g. a set of civil images of structures that are labelled as cracked or undamaged.\r\nDuring the learning process, the machine gets a collection of inputs simultaneously with the corresponding label (ground truth).\r\nAccordingly, by comparing its predicted output with the correct output to find errors, it modifies the model and the learning occurs~\\cite{Ongsulee2018}. \r\nSupervised learning uses patterns to predict the values of the output label  for new unlabeled data by applying methods like regression and classification~\\cite{Ongsulee2018}. \r\n%Fig~\\ref{fig:Machine_learning_approaches} presents most utilised algorithms for ML different approaches like: \r\n%K Nearest Neighbors algorithm (KNN) where K represents the number of the nearest neighbours used for classification of the observations in a test sample, based on their characteristics e.g. the mean distance. \r\n%Moreover,Decision Trees where the data keeps splitting according to a specific parameter. \r\n%Furthermore, Naive Bayes algorithm which is based on probabilistic approach, through implementing Bayes' theorem.\r\n%In addition, Support vector Machine SVM and Logistic regression. \r\n%For Regression purposes, algorithms like linear and polynomial regression are implemented.\r\n\r\nUnsupervised Learning is applied to such data with no historical labels~\\cite{Ongsulee2018}. \r\nIn this case, the model does not know the ground truth labels of the input values. Therefore, the algorithm needs to figure out some common characteristics among the input values.\r\nConsequently, unsupervised learning is more difficult than supervised learning, due to removing the supervision which implies the problem becomes less defined.\r\n%The most well-known techniques used in Unsupervised learning is clustering~\\cite{Russell2010}. \r\n%In which it creates subgroups within the input data based on their characteristics, Fig~\\ref{fig:Machine_learning_approaches} presents most Clustering algorithms like:k-means algorithm, which intends to split n observations into k clusters, where each observation relates to the cluster that has the nearest mean distance.   \r\n\r\nReinforcement learning is based on the trial and error principle, which means the algorithm learns through actions that explore the environment in a way that results with the greatest rewards~\\cite{Russell2010}.\r\nIn this approach of learning the process consists of three parts: the agent which is responsible for making decisions, the environment that relates to any interaction with the agent, and the actions that are made by the agent. Fig.~\\ref{fig:ReinforcementLearning} illustrates the procedure of the reinforcement learning approach.\r\n%Fig~\\ref{fig:Machine_learning_approaches} presents some examples of reinforcement learning.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\begin{figure} [!ht]\r\n\t\\begin{center}\r\n\t\t\\centering\r\n\t\t\\includegraphics[scale=1]{Figures/Chapter_1/Reinforcement_learning.png}\r\n\t\\end{center}\r\n\t\\caption{Reinforcement Learning} \r\n\t\\label{fig:ReinforcementLearning}\r\n\\end{figure}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nTransfer learning is different compared to the traditional ML approaches that are designed to particular tasks, which means their learning and knowledge can not be transferred from one model to another.\r\nTherefore, when starting a new ML task we have to start from scratch.\r\nOn the contrary, in transfer learning, the model knowledge (e.g features and weights) can be transferred from a previously learned task to a new learning task.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\subsection[Data prepossessing and FE]{Data prepossessing and feature extraction techniques}\t\t\r\n\r\nIn SHM applications, the damage identification process is based on comparing the collected data from the structure without damage (base-line) with its current status to determine if there are any occurrence of changes such as damage.\r\nAccordingly, signal processing techniques must be applied to the collected data to identify components of interest in a registered signal from a structure.\r\nIn general, the process of extracting features of the defects occurred in structures can be achieved in different domains: time domain, frequency domain, time-frequency domain, electromechanical impedance domain, and modal analysis domain~\\cite{Khan2019}.\r\n\r\nIn this section, various methods for signal processing, data prepossessing and feature extraction are presented.\r\n\r\n\\subsubsection{Fourier Transform} \r\nFourier Transform (TF) is considered as a conventional method for signal analysis, it is used to decompose the registered signal in the time domain for its frequency components. \r\nFT works by first transforming a function inn the time domain into a function in the frequency domain. \r\nThen, the signal can be analysed for its frequency components because the FT coefficients of the transformed function demonstrate the contribution of the sines and cosines functions at each frequency.\r\nFT presents global information about the frequency content, therefore, it is suited for signals with stationary frequency content meaning their frequency content does not change with time~\\cite{Raghavan2006}.\r\nAlternatively, there are other time-frequency representations (TER) that are able to identify the local frequency content and are better suited for non-stationary-frequency signals~\\cite{Raghavan2006}.\r\nShort-time Fourier transform (STFT) is considered as the simplest example of a TER, in which STFT divides the signal into a number of short overlapping segments in the time-domain, each segment is multiplied in time using a fixed modulation window and the FT is used on resulting signal~\\cite{Raghavan2006}\r\n\r\n\\subsubsection{Wavelet Transform} \r\nWavelet Transform (WT) is a mathematical function for data preprocessing that enhancing the process of feature extraction in a wide range of applications such as civil engineering, power engineering, traffic engineering, mechanical systems and aerospace engineering. . \t\t\r\nFurthermore, WT is considered as one of the most widely used tools for signal preprocessing in SHM in recent years~\\cite{Taha2006}.\t\t\r\nThe principal idea of WT is splitting data signal into different scale components, accordingly, analysing each component with a resolution matched to its scale~\\cite{Graps1995},hence wavelets are referring to little or small waves. \r\nThe WT is based on dilated scales and shifted windows that can perform a time-frequency resolution of a data signal. \r\nWT is represented in the following Eqn~\\ref{wavelet}, that yields a 2D coefficients matrix  $WT\\{x\\}(a,b)$. \r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\begin{equation}\r\n\tWT\\{x\\}(a,b) = \\int_{R}^{}\\Psi_{a,b}(t)x(t)dt\r\n\t\\label{wavelet}\r\n\\end{equation}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n$\\Psi_{a,b}$ is defined as the mother wavelet which scaled and dilated wavelets  where a and b are the scale and dilation parameters.\r\nScaling in WT indicates stretching or compressing it in the time domain. \r\nTherefore, compressed wavelets are represented by smaller scales while stretched wavelets can be produced by larger scales~\\cite{Graps1995}.\r\n%\\subsubsection{Principle component analysis} Principle component analysis (PCA) is a technique of multi-variable and mega-variate analysis used for reducing complex data dimensionality in ML. \r\n%Furthermore, PCA can be identified as an unsupervised, simple and non-parametric method for information extraction and data compression~\\cite{Jolliffe2002}.\r\n%\r\n%Consequently, PCA is considered as a patterns recognition technique, and when it is applied on collected data, new important hidden data with some simplified patterns  are identified.\r\n%Accordingly, PCA is responsible for determining the dynamics in the system according to their importance, as a result, there are more important dynamics and redundant dynamics and which are just noise~\\cite{Farrar2007}.\r\n%To develop a PCA model it is essential to organise the data in an (\\(m \\times n\\)) matrix \\(X = [x_{i1}x_{i2}...x_{ij}]\\) where $i = 1,2,3...m ; j = 1,2,3,...n$ which carries information from \\(n\\) sensors (variables) and \\(m\\) experimental trials (observations).\r\n%Considering different magnitudes and scales regarding the physical variables and sensors in the structure, each point in the collected data is computed using the mean of all the sensor measurements at the same time and the standard deviation of all sensor measurements.\r\n%Following normalization the variables the covariance matrix $C_x$ is calculated as show in  Eqn~\\ref{covar matrix}~\\cite{Tibaduiza}.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\\begin{equation}\r\n%\tC_x =  \\frac{1}{m-1}X^TX\r\n%\t\\label{covar matrix}\r\n%\\end{equation}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%where $C_x$ is a square symmetric $(m \\times m)$ matrix that determines the linear relationship degree in the data set within all possible pairs of variables which are the sensors in this case, and $T$ is the transposition.\r\n%Considering the covariance matrix $C_x$ and the eigenvalues $(\\lambda) $ of $C_x$, therefore, the eigenvector $(E)$ can be determined according to Eqn~\\ref{eigenvector}.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\\begin{equation}\r\n%\tC_xE=\\lambda E\r\n%\t\\label{eigenvector}\r\n%\\end{equation}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%Columns of the eigenvectors matrix $E$ are arranged based on the eigenvalues by descending order and they are termed the Principal Components (PCs) of the data set.\r\n%Accordingly, the most important features in the data with the highest weight of information are represented by the eigenvectors with the highest eigenvalue.\r\n%Therefore, by picking only a reduced number of $r$ of PCs, that is corresponding to the first eigenvalues, the reduced transformation matrix could be considered as a model for the structure with compressed data. \r\n%\r\n%The transformed data matrix T (score matrix) can be represented geometrically as the projection of the original data over the direction of the PCs of the eigenvector matrix E as presented in Eqn~\\ref{score matrix}.\r\n%The Principal Component Coefficient (PCC) quantify the influence of each variable $(x_{1,i},x_{2,i},x_{3,i},...,x_{i,j})$ have on each principle component $(z_{i,1},z_{i,2},z_{i,3},...,z_{i,j})$.\r\n%For the PCC matrix $W$, the rows represent the variables, columns represent the component the PCC for each variable mentioned before, the component principal can be calculated as shown in Eqn~\\ref{PCC},\r\n%where $e_{i,j}$ denotes an element of eigenvector matrix E and Var($x_{i,j}$) denotes the variance of $x_{i,j}$~\\cite{DeOliveira2014}.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\\begin{equation}\r\n%\tT = XE\r\n%\t\\label{score matrix}\r\n%\\end{equation}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\\begin{equation}\r\n%\tW = \\frac{e_{i,j}}{\\sqrt{ Var(x_{i,j})}}\r\n%\t\\label{PCC}\r\n%\\end{equation}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\\begin{table}\r\n%\t\\renewcommand{\\arraystretch}{1.1}\r\n%\t\\centering\r\n%\t\\caption{Advantages/Disadvantages of PCA}\r\n%\t\\scriptsize\t\r\n%\t\\begin{tabular}{ll} \r\n%\t\t\\toprule\r\n%\t\t\\textbf{Advantages} & \\textbf{Disadvantages} \\\\ \r\n%\t\t\\midrule\r\n%\t\tRemoves Correlated Features & Independent variables become less \tinterpretable  \\\\ \r\n%\t\t%\\hline\r\n%\t\tImproves Algorithm Performance & Data must be standardized before PCA \\\\ \r\n%\t\t%\t\\hline\r\n%\t\tReduces Overfitting & Information Loss \\\\\r\n%\t\t%\t\\hline\r\n%\t\tImproves Visualisation &  \\\\\r\n%\t\t\\bottomrule\r\n%\t\\end{tabular}\r\n%\t\\label{tab:pca pros and cons}\r\n%\\end{table}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%Consequently, determining the optimal number of PCs is performed by looking at the cumulative variance ratio as a function of the number of components. The choice of selecting the number of PCs completely relies on the trade-off between information loss and dimensionality reduction. \r\n%PCA technique has several advantages and disadvantages, as presented in Table~\\ref{tab:pca pros and cons}.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\subsubsection{Principal component analysis}\r\nPCA is a popular method used for damage identification in SHM.\r\nFurther, PCA shows a solid and efficient performance in feature extraction, and structural damage detection~\\cite{liu2014research, wang2014principal, nguyen2010fault}. \r\nBesides, PCA proves to be an effective tool to improve the training efficiency and enhance the classification accuracy for other ML algorithms, such as unsupervised learning methods~\\cite{liu2019rapid, datteo2017statistical, torres2014data}. \r\n\r\nPCA is dimensionality reduction technique utilised to reduce the dimensionality of large data (input space) into a lower dimension (feature space) through transforming a large set of variables into a smaller one with minimal loss information~\\cite{Jolliffe2002}.\r\nMoreover, PCA can be utilised for damage detection by eliminating noise and obtaining sensitive features of damage as eigenvectors.\r\nThe PCA technique is illustrated below.\r\nIn the beginning, a matrix \\(U(t)\\) is constructed as shown in Eqn. \\ref{U(t)}, which contains all registered data with time histories.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\begin{equation}\r\n\tU(t)=\r\n\t\\begin{bmatrix}\r\n\t\tu_1{(t1)}       & u_2{(t1)} & \\dots & u_M{(t1)} \\\\\r\n\t\tu_1{(t2)}       & u_2{(t2)} & \\dots & u_M{(t2)} \\\\\r\n\t\t\\vdots \t\t\t& \\vdots \t& \\ddots & \\vdots \\\\\r\n\t\tu_1{(t_N)}      & u_2{(t_N)} & \\dots & u_M{(t_N)}\r\n\t\\end{bmatrix}\\ ,\r\n\t\\label{U(t)}\r\n\\end{equation}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nwhere \\(t\\) corresponds to the time, \\(u_i\\ (i = 1, 2, ..., M)\\) represents to the response from the \\(i-th\\) sensor installed in the monitored structure, \\(M\\) represents the total number of sensors, \\(t_j\\ (j = 1, 2, ..., N)\\) represents the \\(j-th\\) time step of the data registering and \\(N\\) is the total time observations during monitoring.\r\nAdditionally, each column represents data registration of one sensor.\r\nThe next step is to normalise the time series of each sensor data registrations by subtracting the mean value shown in Eqn.~\\ref{mean value}:\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\begin{equation}\r\n\t\\bar{u_i} = \\frac{1}{N}\\sum_{j=1}^{N}u_i(t_j)\\ ,\r\n\t\\label{mean value}\r\n\\end{equation}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nEquation~\\ref{normalised matrix} represents the normalised matrix.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\begin{equation}\r\n\tU'(t)=\r\n\t\\begin{bmatrix}\r\n\t\tu_1{(t1)}-\\bar{u_1}       & u_2{(t1)}-\\bar{u_2} & \\dots  & u_M{(t1)}-\\bar{u_M} \\\\\r\n\t\tu_1{(t2)}-\\bar{u_1}       & u_2{(t2)}-\\bar{u_2} & \\dots  & u_M{(t2)}-\\bar{u_M} \\\\\r\n\t\t\\vdots \t\t\t\t\t  & \\vdots \t  \t\t\t& \\ddots & \\vdots \\\\\r\n\t\tu_1{(t_N)}-\\bar{u_1}      & u_2{(t_N)}-\\bar{u_2}& \\dots  & u_M{(t_N)}-\\bar{u_M}\r\n\t\\end{bmatrix}\r\n\t\\label{normalised matrix}\r\n\\end{equation}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nAfter computing the normalised matrix, the covariance matrix is computed as shown in Eqn.~\\ref{covariance}:\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\begin{equation}\r\n\tC = \\frac{1}{M}U'^TU' \\ ,\r\n\t\\label{covariance}\r\n\\end{equation}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nNext, the eigenvalue and the corresponding eigenvector of the covariance matrix are computed through solving the following equation~\\ref{eigvalue}:\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\begin{equation}\r\n\t(C-\\lambda_iI)\\psi_i =0 \\ ,\r\n\t\\label{eigvalue}\r\n\\end{equation}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nwhere \\(I\\) represents the \\(M\\times M\\) identity matrix, \\(\\psi_i = [\\psi_{i,1},\\psi_{i,2}, \\hdots, \\psi_{i,j}]^T\\) in which \\(\\psi_{i,j}(j=1, 2, \\hdots, M)\\) is the element related to the \\(j-th\\) sensor.\r\nUsually, eigenvalues are sorted into decreasing order, particularly \\(\\lambda_1>\\lambda_2>\\hdots>\\lambda_M\\). \r\nThen, the first eigenvector \\(\\psi_1\\) corresponding to \\(\\lambda_1\\) holds the greatest variance and consequently holds the most important information for the original matrix U. \r\nThe first few principal components hold most of the variance, whereas the remaining less important components involve the measurement of noise.\r\nAccordingly, the first few eigenvectors are utilised as sensitive features for damage detection and localisation.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\subsubsection{Auto-associative Neural Networks}\r\nAuto-associative Neural Network (AANN) which is also called autoencoder is considered as one of the ANN architectures. \r\nGenerally, AANN is composed of five layers as shown in the Fig.~\\ref{fig:AANN}, which includes the input layer, mapping layer, bottleneck layer (has less neurons than the input and the output layers), demapping layer and the output layer. \r\nAANN is considered as an unsupervised learning technique, the idea behind AANN is to map the input using nonlinear functions then reconstruct it using nonlinear functions so the network can learn from the inputs themselves.\r\nThe main purpose of the bottleneck is to push the model to learn important features of the mapped data patterns.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\begin{figure}[!ht]\r\n\t\\begin{center}\r\n\t\t\\centering\r\n\t\t\\includegraphics[scale=1]{Figures/Chapter_1/Auto-associative NN.png}\r\n\t\\end{center}\r\n\t\\caption{Auto-associative Neural Network architecture} \r\n\t\\label{fig:AANN}\r\n\\end{figure}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\paragraph{}\r\nOriginally, AANN technique was based on nonlinear principal component analysis (NLPCA) which is a powerful statistical technique used in the process of the feature extracting and data dimensionality reduction~\\cite{Dervilis2014}. \r\nThe difference between the PCA and NLPCA is that NLPCA is utilising nonlinear functions for mapping the input data as shown in Eqn~\\ref{NLPCA}.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\begin{equation}\r\n\tT= G(X)\r\n\t\\label{NLPCA}\r\n\\end{equation} \r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nAs mentioned in the previously $T$ is the score matrix, $X$ is the input data with of size $(m \\times n)$ where m represents the number of variables and n represents the number of observations, and G is a nonlinear vector function that holds several individual nonlinear functions. \r\nAccordingly, the demapping process is performed by the inverse of the Eqn~\\ref{NLPCA} using a nonlinear function $H$ as shown in Eqn~\\ref{inverseNLPCA}.\r\nThe loss of information occurred due to the mapping and demapping process can be calculated in the reconstruction error matrix as shown in Eqn~\\ref{errorMatrix}~\\cite{Dervilis2014}.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\begin{equation}\r\n\t\\hat{X} = H(T)\r\n\t\\label{inverseNLPCA}\r\n\\end{equation}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\begin{equation}\r\n\tE= X-\\hat{X}\r\n\t\\label{errorMatrix}\r\n\\end{equation}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\subsubsection{Mahalanobis squared distance}\r\nMSD is an effective multivariate distance measuring technique in which it measures the distance between a point and a distribution.\r\nTherefore, MSD is utilised with multivariate statistics outlier detection~\\cite{Worden2000}.\r\nAssuming \\(X\\) to be a training set with data acquired when the undamaged structure is under environmental and/or operational variations (EOVs) with multivariate mean vector \\(\\mu\\) and covariance matrix \\(\\Sigma\\)~\\cite{Farrar2013}.\r\nAccordingly, the damage index \\((DI_i)\\) between feature vectors from training set \\(X\\) and any new feature vector from the test matrix \\(Z\\) is calculated using Eqn.~\\ref{msd}.\r\n\\begin{equation}\r\n\tDI_i = (z_i-\\mu)\\Sigma^{-1}(z_i-\\mu)^T\r\n\t\\label{msd}\r\n\\end{equation}\r\nwhere \\(z_i\\) is a tested feature vector.\r\nThe performance of this technique mainly relies on acquiring all likely EOVs in the training set~\r\n\\cite{Farrar2013}.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\subsubsection{Gaussian mixture models}\r\nGMM is a clustering method commonly used with unsupervised learning, in which it aims to find main clusters of points in a dataset that share some common characteristics or features.\r\nAdditionally, GMM has also been referred to as Expectation-Maximization (EM) clustering that is based on the optimization strategy.\r\n%%%%%%%%%%\r\nThe damage detection is performed based on multiple MSD-based algorithms, in which the covariance matrices and mean vectors are functions of the main components.\r\n%%%%%%%%%%\r\nA GMM is defined as a superposition of K Gaussian distributions as shown in Eqn. \\ref{gmm}.\r\n\r\n\\begin{equation}\r\n\tp(x) = \\sum_{k=1}^K P(k) \\mathcal{N}(x|\\mu_k,\\Sigma_k) \r\n\t\\label{gmm}\r\n\\end{equation}\r\nwhere \\(x\\) represents the training samples in the dataset, and \\(P(k)\\) corresponds to the mixture proportion (contribution weight) of the \\(k-\\)th distribution, in which the mixture proportion must satisfy \\(0\\leq P(x)\\leq 1\\).\r\nThe sum of all mixture proportion satisfies the following Eqn.~\\ref{mixture}\r\n\\begin{equation}\r\n\t\\sum_{k=1}^{K}P(x) =1 \r\n\t\\label{mixture}\r\n\\end{equation}  \r\n\\(\\mathcal{N}(x|\\mu_k,\\Sigma_k)\\) refers to the conditional probability of the instance \\(x\\) for the \\(k-\\)th Gaussian distribution \\(\\mathcal{N}(\\mu_k,\\Sigma_k)\\) presented in Eqn.~\\ref{conditional}, where \\(\\mu_k\\) and \\(\\Sigma_k\\) are the mean and the covariance of that Gaussian distribution respectively.\r\n\\begin{equation}\r\n\t\\mathcal{N}(x|\\mu_k,\\Sigma_k) = \\frac{\\exp(-\\frac{1}{2}(x-\\mu_k)^T\\Sigma_k^{-1}(x-\\mu_k))}{(2\\pi)^{\\frac{d}{2}\\sqrt{\\det(\\Sigma_k)}}}\r\n\t\\label{conditional}\t\t\r\n\\end{equation}\r\nThe complete GMM is parameterized by the mean vectors, covariance matrices and the mixture weights from all component densities \\(\\{\\mu_k,\\Sigma_k, P(x)\\}_{k=1,\\hdots,K}\\).\r\n\r\nThe parameters can be carried out from the training data using the classical maximum likelihood estimator (CMLE) based on the EM algorithm~\\cite{Dempster1977}.\r\nDamage can be detected through estimating \\(k\\) \\(DIs\\) for each data sample \\(x\\) as shown in Eqn. \\ref{DIs}\r\n\\begin{equation}\r\n\tDI_q(x) = (x-\\mu_k)\\Sigma_k^{-1}(x-\\mu_k)^T\r\n\t\\label{DIs}\r\n\\end{equation}\r\nwhere \\(\\mu_k\\) and \\(\\Sigma_k\\) refers to all observations from the \\(k\\) data component.\r\nFor each observation the DI is given by the smallest DI estimated on each component as in Eqn. \\ref{DI}\r\n\\begin{equation}\r\n\tDI(x) = \\min[DI_k(x)]\r\n\t\\label{DI}\r\n\\end{equation}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\subsection{Classification techniques}\r\nIn this section, various classification techniques utilised in classifying the extracted features are presented.\r\n\\subsubsection{Support vector machine}\r\nSupport vector machine (SVM) is a supervised ML model that is utilised as a classification and regression tool.  \r\nThe idea behind SVM is to find an optimal hyperplane (e.g separate line) in N-dimensional space (N is the number of features) that separates the classes, furthermore, the aim of the hyperplane is to maximize the margin between the points on either side hence so called \"decision line/boundary\".\r\nFurthermore, when we try to separate two classes of data points, we could have many possible hyperplanes, however, our goal is to find the hyperplane that has the maximum margin (maximum distance between data points of both classes). \r\nFigure~\\ref{fig:SVM} shows SVM hyperplanes in 2D feature space and 3D feature space.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\begin{figure}[!ht]\r\n\t\\centering\r\n\t\\begin{subfigure}[b]{0.40\\textwidth}\t\t\r\n\t\t\\includegraphics[width=1\\textwidth]{Figures/Chapter_2/2d_svm.png}\r\n\t\t\\caption{Hyperplane 2D feature space.}\r\n\t\t\\label{fig:2dsvm}\r\n\t\\end{subfigure}\r\n\t\\begin{subfigure}[b]{0.49\\textwidth}\r\n\t\t\\includegraphics[width=1\\textwidth]{Figures/Chapter_2/3d_svm.png}\r\n\t\t\\caption{Hyperplane 3D feature space.} \r\n\t\t\\label{fig:3dsvm}\r\n\t\\end{subfigure}\t\r\n\t\\caption{SVM for 2D and 3D feature space.}\r\n\t\\label{fig:SVM}\r\n\\end{figure}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\subsubsection{K-Nearest Neighbor}\r\nK-Nearest Neighbor (KNN) is a supervised ML technique utilized to perform classification tasks.\r\nKNN does not have a specialized training phase.\r\nIt saves all the training data and uses the entire training set for classifying a new data point, which adds time complexity at the testing time.\r\nMoreover, KNN is a non-parametric learning algorithm, which means it does not have any assumptions regarding the input data, which is useful considering the real-world data does not obey the typical theoretical assumptions such as linear separability, uniform distribution among others.\r\n\r\nIn the KNN technique, at the first, the distance between the new data point and the whole other data points is calculated.\r\nFurthermore, any distance method can be applied e.g. Euclidean, Manhattan, etc.\r\nAccordingly, it picks the K-nearest points, where K is an integer number (number of neighbors) that can be chosen in such a way the model will be able to predict new unseen data accurately. \r\nThen, it assigns the new data point to the class to which the majority of the K data points belong.\r\nIn Fig.~\\ref{fig:datapoints} shows initial data points (training set) before classification, and Fig.~\\ref{fig:KNN_K_5} shows the result of applying KNN techniques on the data points (3 classes) assuming \\(K=6\\).\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\begin{figure}[!ht]\r\n\t\\centering\r\n\t\\begin{subfigure}{0.49\\textwidth}\t\t\r\n\t\t\\centering\r\n\t\t\\includegraphics[width=1\\textwidth]{Figures/Chapter_2/KNN_data_points.png}\r\n\t\t\\caption{Data points} \r\n\t\t\\label{fig:datapoints}\r\n\t\\end{subfigure}\r\n\t\\hfill\r\n\t\\begin{subfigure}{0.49\\textwidth}\r\n\t\t\\centering\r\n\t\t\\includegraphics[width=1\\textwidth]{Figures/Chapter_2/KNN_K_6.png}\r\n\t\t\\caption{3-Classes with \\(K=6\\)} \r\n\t\t\\label{fig:KNN_K_5}\r\n\t\\end{subfigure}\t\r\n\t\\caption{KNN algorithm: data classification with \\(K=6\\).}\r\n\t\\label{fig:KNN}\r\n\\end{figure}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\subsubsection{Decision tree}\r\nDecision trees are supervised ML that is used in applications for classification and regression. \r\nAdditionally, decision trees are considered the bases for many other ML techniques such as random forests, bagging and boosted decision trees.\r\nThe idea of a decision tree is to represent the whole data as a tree where each internal node represents a test on an attribute (a decision rule) and each branch represents an outcome of the test, and finally each leaf node (terminal node) holds the label of the class.\r\n\r\nDecision tree can be divided into two categories:\r\n\\begin{enumerate}\r\n\t\\item Categorical variable decision trees: which includes categorical target variables that are divided into categories. A category means that the decision falls into one of the categories and there is no in-between such as (Yes/No category).\r\n\t\\item Continuous variable decision trees: which has a continuous target variable that can be predicted based on available information (e.g. crack length).\r\n\\end{enumerate}\r\nFigure~\\ref{fig:Decision_tree} presents a typical decision tree.\r\nAny decision tree has a root node where data input is carried through.\r\nFurthermore, the root node is split into sets of decision rules that result either in a leaf node which is a non-splitting node, or into another decision rule, creating what so-called a branch or sub-tree.\r\nIn case there are decision rules that can be eliminated from the tree, a process called \"pruning\" is applied to minimize the complexity of the algorithm.\r\n\\begin{figure}[!ht]\r\n\t\\begin{center}\r\n\t\t\\includegraphics[scale=1]{Figures/Chapter_3/decision_tree.png}\r\n\t\\end{center}\r\n\t\\caption{Decision tree.}\r\n\t\\label{fig:Decision_tree}\r\n\\end{figure} ", "meta": {"hexsha": "609f5e1ceb0c2d2e98cb66e3b6c0ddc3539b1416", "size": 32276, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "reports/project_reports/Ijjeh_thesis_template/Chapters/Chapter3/sect31.tex", "max_stars_repo_name": "IFFM-PAS-MISD/aidd", "max_stars_repo_head_hexsha": "9fb0ad6d5e6d94531c34778a66127e5913a3830c", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-03T05:36:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T05:36:07.000Z", "max_issues_repo_path": "reports/project_reports/Ijjeh_thesis_template/Chapters/Chapter3/sect31.tex", "max_issues_repo_name": "IFFM-PAS-MISD/aidd", "max_issues_repo_head_hexsha": "9fb0ad6d5e6d94531c34778a66127e5913a3830c", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "reports/project_reports/Ijjeh_thesis_template/Chapters/Chapter3/sect31.tex", "max_forks_repo_name": "IFFM-PAS-MISD/aidd", "max_forks_repo_head_hexsha": "9fb0ad6d5e6d94531c34778a66127e5913a3830c", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 80.4887780549, "max_line_length": 535, "alphanum_fraction": 0.6811562771, "num_tokens": 7290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.33569984061527874}}
{"text": "\\documentclass[12pt]{cdblatex}\n\\usepackage{bssn-eqtns}\n\n\\begin{document}\n\n\\section*{PhysRevD.62.044034 equation (9)}\n\n\\begin{cadabra}\n   from shared import *\n   import cdblib\n\n   jsonfile = 'bssn-eqtns-09.json'\n   cdblib.create (jsonfile)\n\n   # --------------------------------------------------------------------------\n\n   DgBarDt := \\partial_{t}{gBar_{ij}}.           # cdb(eq09.00,DgBarDt)\n   DgBarDt := -2 N ABar_{i j}.                   # cdb(eq09.01,DgBarDt)\n\n   canonicalise (DgBarDt)                        # cdb(eq09.02,DgBarDt)  # no change\n                                                 # cdb(eq09.99,DgBarDt)  # no change\n\n   cdblib.put ('DgBarDt',DgBarDt,jsonfile)\n\\end{cadabra}\n\n\\begin{dgroup*}\n   \\begin{dmath*} \\cdb{eq09.00} = \\Cdb*{eq09.02}\\end{dmath*}\n\\end{dgroup*}\n\n\\end{document}\n", "meta": {"hexsha": "7ba32df0f93cb41a58b55c67bebf97548b4f2b9f", "size": 802, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "bssn/cadabra/bssn-eqtns-09.tex", "max_stars_repo_name": "leo-brewin/adm-bssn-numerical", "max_stars_repo_head_hexsha": "9e32c201272e9a41e7535475fe381e450b99b058", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-25T11:36:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T11:36:06.000Z", "max_issues_repo_path": "bssn/cadabra/bssn-eqtns-09.tex", "max_issues_repo_name": "leo-brewin/adm-bssn-numerical", "max_issues_repo_head_hexsha": "9e32c201272e9a41e7535475fe381e450b99b058", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bssn/cadabra/bssn-eqtns-09.tex", "max_forks_repo_name": "leo-brewin/adm-bssn-numerical", "max_forks_repo_head_hexsha": "9e32c201272e9a41e7535475fe381e450b99b058", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8709677419, "max_line_length": 84, "alphanum_fraction": 0.5211970075, "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.33569984061527874}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\section*{7 October 2019}\n\n% The exam for this part of the course: it might be around the end of october.\n\n% The subscripts on last lecture \\emph{were} inverted after all.\n\nWe introduce the \\emph{mirror principle}: when the core contracts or expands, the envelope does the opposite.\n\nThe shell must remain at around the same temperature to maintain equilibrium: contracting the core would increase the temperature, therefore the envelope exapands.\nThis heuristic argument is actually derived from simulations.\n\nThe relevant time scale for oscillations is the free-fall, dynamical time scale.\n\nWe come back to the energy equation\n\n\\begin{equation}\n  \\pdv{L}{m} = \\varepsilon - \\varepsilon_\\nu - \\varepsilon_g\n\\end{equation}\n\nwe incorporate the nuclear energy generation rate and the energy lost as neutrino production into an effective energy generation rate per unit mass \\(\\varepsilon - \\varepsilon_\\nu = \\varepsilon_{\\text{eff}} \\) and express the energy absorbed by the stellar layer as \n%\n\\begin{align} \\label{eq:heat-transfer-effective}\n \\varepsilon_g = \\dv{Q}{t} = \\varepsilon_{\\text{eff}} - \\pdv{L}{m}\n\\,.\n\\end{align}\n%\n\nThis makes the meaning of this transfer equation clearer.\nUsing the first and second laws of thermodynamics, and recalling some thermodynamical values: the specific heat at constant volume \\(c_V = \\qty(\\pdv{Q}{T})_V \\), the equation of state exponents \\(\\chi_T \\) and \\(\\chi_\\rho\n\\) which satisfy: \\(P = T^{ \\chi_{T}}\\) and \\(P = \\rho^{\\chi_{\\rho }}\\) and the adiabatic exponents \\(\\Gamma_{1,2,3}\\), which are defined by \n%\n\\begin{subequations}\n\\begin{align}\n\\Gamma_1 = \\gamma_{\\text{ad}} &= \\qty(\\pdv{\\log P}{\\log \\rho })_{s}  \\\\\n\\frac{\\Gamma_2 }{\\Gamma_2 -1} = \\frac{1}{\\nabla _{\\text{ad}}} &= \\qty(\\pdv{\\log P}{\\log T})_{s}  \\\\\n\\Gamma_3 -1 &= \\qty(\\pdv{\\log T}{\\log \\rho })_{s}  \\\\\n\\,\n\\end{align}\n\\end{subequations}\n%\nand satisfy \n%\n\\begin{align}\n\\frac{\\Gamma_1 }{\\Gamma_3 -1} = \\frac{\\Gamma_2 }{\\Gamma_2 -1}\n\\,.\n\\end{align}\n\nThese are all \\emph{exponents} in some power law.\nWe use log values since our variables change by orders of magnitude.\n\nWe start with  the definition of the entropy differential: \\(\\dd{Q}\\) is not an exact differential but \\(\\dd{Q} / T = \\dd{S}\\) is. So, we express it using the first law of thermodynamics: \\(\\dd{Q} = \\dd{E} + P \\dd{V}\\). \nWe assume the internal energy \\(E\\) to be a function of the volume \\(V\\) and of the temperature \\(T\\), so we will have: \n%\n\\begin{align}\n\\dd{E} = \\pdv{E}{V} \\dd{V} + \\pdv{E}{T} \\dd{T}\n\\,,\n\\end{align}\n%\nwhich we can substitute into the expression for the entropy differential: \n%\n\\begin{subequations}\n\\begin{align}\n\\dd{S} &= \\frac{1}{T} \\qty(\\pdv{E}{V} \\dd{V} + \\pdv{E}{T} \\dd{T} + P \\dd{V})  \\\\\n&= \\qty(\\frac{1}{T} \\pdv{E}{V} + \\frac{P}{T}) \\dd{V} \n+ \\frac{1}{T} \\pdv{E}{T} \\dd{T}  \\\\\n&= \\pdv{S}{V} \\dd{V} + \\pdv{S}{T} \\dd{T}\n\\,,\n\\end{align}\n\\end{subequations}\n%\nso we have identified the partial derivatives of the entropy. By Schwarz's lemma, we then have the equality: \n%\n\\begin{subequations}\n\\begin{align}\n\\pdv[2]{S}{T}{V} &= \\pdv[2]{S}{V}{T}  \\\\\n\\pdv{}{T} \\qty(\\frac{1}{T} \\pdv{E}{V} + \\frac{P}{T})&=\n\\pdv{}{V} \\qty(\\frac{1}{T} \\pdv{E}{T})  \\\\\n\\frac{1}{T} \\qty(\\cancelto{}{\\pdv[2]{E}{T}{V}} + \\pdv{P}{T} ) \n- \\frac{1}{T^2} \\qty(\\pdv{E}{V} + P) &=\n\\cancelto{}{\\frac{1}{T} \\pdv[2]{E}{V}{T}}  \\\\\n \\pdv{E}{V} &= T \\pdv{P}{T} - P \n\\,,\n\\end{align}\n\\end{subequations}\n%\nbut we can turn the derivatives with respect to \\(V\\) with ones with respect to \\(\\rho \\propto V^{-1}\\), by \n%\n\\begin{align}\n\\pdv{}{V} = \\pdv{\\rho }{V} \\pdv{}{\\rho } = - \\rho^2 \\pdv{}{\\rho }\n\\,,\n\\end{align}\n%\nso after dividing through by \\(\\rho \\) we find: \n%\n\\begin{subequations}\n\\begin{align}\n\\rho \\pdv{E}{\\rho } &= -\\frac{T}{\\rho } \\pdv{P}{T} + \\frac{P}{\\rho }  \\\\\n&= - \\frac{P}{\\rho } \\pdv{\\log P }{\\log T} + \\frac{P}{\\rho }  \\\\\n\\rho \\pdv{E}{\\rho }&= - \\frac{P}{\\rho } \\qty(\\pdv{\\log P }{\\log T} -1 )  \\\\\n\\pdv{E}{\\log \\rho }&= -\\frac{P}{\\rho } \\qty(\\chi_{T} - 1)\n\\,.\n\\end{align}\n\\end{subequations}\n%\n\nWe used the fact that \n%\n\\begin{align}\n\\pdv{}{\\log x} = \\pdv{x}{\\log x} \\pdv{}{x}= x \\pdv{}{x} \n\\,.\n\\end{align}\n\nNow, we can write the first law of thermodynamics for the specific energy density \\(E(\\rho, T)\\): \n%\n\\begin{subequations}\n\\begin{align}\n\\dd{Q} &= \\dd{E} - \\frac{P}{\\rho^2} \\dd{\\rho }  \\label{eq:heat-differential}\\\\\n&= \\pdv{E}{\\log \\rho } \\dd{\\log \\rho } \n+ \\pdv{E }{\\log T} \\dd{\\log T} - \\frac{P}{\\rho}  \\dd{\\log \\rho }  \\\\\n&= \\qty(- \\frac{P}{\\rho } \\qty(\\chi_{T} -1) - \\frac{P}{\\rho }) \\dd{\\log \\rho } + \\pdv{E}{\\log T} \\dd{\\log T}  \\\\\n&= - \\frac{P \\chi_T }{\\rho } \\dd{\\log \\rho } + \\pdv{E}{\\log T} \\dd{\\log T} \n\\,,\n\\end{align}\n\\end{subequations}\n%\nwhich in the adiabatic (\\(\\dd{Q} = 0\\)) case reduces to \n%\n\\begin{subequations}\n\\begin{align}\n\\Gamma_3 - 1 \\overset{\\text{def}}{=} \\pdv{\\log T }{\\log \\rho } &= - \\frac{P \\chi_{T}  }{\\rho } \\pdv{\\log T}{E} = - \\frac{P \\chi_T }{\\rho T c_V}  \\\\\n&=- \\frac{1}{\\rho } \\times \\underbrace{\\frac{P \\chi_T}{T}}_{\\pdv{P}{T}} \\times \\underbrace{\\frac{1}{c_V}}_{\\pdv{T}{E}}  \\\\\n&= - \\frac{1}{\\rho } \\pdv{P}{E}\n\\,,\n\\end{align}\n\\end{subequations}\n%\nwhere we used the fact that \\(c_V = \\pdv*{E}{T}\\). This can also be written as \n%\n\\begin{align}\n\\pdv{E}{P} = \\frac{1}{\\rho (\\Gamma_3 -1)}\n\\,.\n\\end{align}\n\nIf we drop the hypothesis of adiabaticity, we can study the variation with respect to time of \\(Q\\), both when writing \\(E = E(\\rho , T)\\) and when writing \\(E = E(\\rho , P)\\). \nIn the first case we can use equation \\eqref{eq:heat-differential}, ``dividing through by \\(\\dd{t}\\)'' (more formally, applying the differential covector equation to the vector \\(\\partial_{t}\\)), after some manipulation we can bring out a factor \\(T \\pdv*{E}{T}\\) to get: \n%\n\\begin{align} \\label{eq:heat-variation-temperature-dependence}\n\\dv{Q}{t} = T \\pdv{E}{T} \\qty(\\dv{\\log T}{t} + \\frac{\\rho \\pdv{E}{\\rho } - \\frac{P}{\\rho }}{T \\pdv{E}{T}} \\dv{\\log \\rho }{t})\n\\,,\n\\end{align}\n%\nand similarly if we express \\(E = E(\\rho, P)\\) we find \n%\n\\begin{align}\\label{eq:heat-variation-pressure-dependence}\n\\dv{Q}{t} = P \\pdv{E}{P} \\qty(\\dv{\\log P}{t} + \\frac{\\rho \\pdv{E}{\\rho } - \\frac{P}{\\rho }}{P \\pdv{E}{P}} \\dv{\\log \\rho }{t})\n\\,.\n\\end{align}\n\nWe can simplify these two expressions by recalling some results from before, plus two more expression we now derive for the coefficients \\(\\Gamma_1\\) and \\(\\Gamma_3 -1\\): we assume adiabaticity, and get\n%\n\\begin{subequations}\n\\begin{align}\n0=\\dd{S} &= \\frac{1}{T} \\qty(\\pdv{E}{\\rho } \\dd{\\rho } + \\pdv{E}{P } \\dd{P} - \\frac{P}{\\rho^2} \\dd{\\rho })  \\\\\n0&= \\qty(\\rho \\pdv{E}{\\rho } - \\frac{P}{\\rho } ) \\dd{\\log \\rho }   + P \\pdv{E}{P} \\dd{\\log P}  \\\\\n\\Gamma_1 = \\left. \\dv{\\log P}{\\log \\rho } \\right\\vert_{\\text{ad}} &= \\frac{\\frac{P}{\\rho } - \\rho \\pdv{E}{\\rho }}{P \\pdv{E}{P}}\n\\,\n\\end{align}\n\\end{subequations}\n%\nand \n%\n\\begin{subequations}\n\\begin{align}\n0 = \\dd{S} &= \\frac{1}{T} \\qty(\\pdv{E}{\\rho } \\dd{\\rho } + \\pdv{E}{T} \\dd{T} - \\frac{P}{\\rho^2} \\dd{\\rho })  \\\\\n0&= \\qty(\\rho \\pdv{E}{ \\rho } - \\frac{P}{\\rho }) \\dd{\\log \\rho } + T \\pdv{E}{T} \\dd{\\log T}  \\\\\n\\Gamma_3 -1 = \\left. \\dv{\\log T}{\\log \\rho } \\right\\vert_{\\text{ad}} &= \\frac{\\frac{P}{\\rho } - \\rho \\pdv{E}{\\rho }}{T \\pdv{E}{T}}\n\\,,\n\\end{align}\n\\end{subequations}\n%\n\n\nThe identifications are: \n%\n\\begin{align}\n\\dv{Q}{t} = T \\underbrace{\\pdv{E}{T}}_{c_V} \\qty(\\dv{\\log T}{t} + \\underbrace{\\frac{\\rho \\pdv{E}{\\rho } - \\frac{P}{\\rho }}{T \\pdv{E}{T}}}_{- (\\Gamma_3 - 1) } \\dv{\\log \\rho }{t})\n\\,,\n\\end{align}\n%\nand\n%\n%\n\\begin{align}\n\\dv{Q}{t} = P \\underbrace{\\pdv{E}{P}}_{1/ \\rho (\\Gamma_3 -1)} \\qty(\\dv{\\log P}{t} + \\underbrace{\\frac{\\rho \\pdv{E}{\\rho } - \\frac{P}{\\rho }}{P \\pdv{E}{P}}}_{- \\Gamma_1 } \\dv{\\log \\rho }{t})\n\\,.\n\\end{align}\n\nFinally, we substitute in the equation of energy conservation: \n%\n\\begin{align}\n\\dv{Q}{t} = \\varepsilon_{\\text{eff}} - \\pdv{L}{m}\n\\,,\n\\end{align}\n%\nto find the equations for the evolution of the energy and pressure:\n%\n\\boxalign{\n\\begin{subequations}\n\\begin{align}\n  \\pdv{\\log P }{t} &= \\Gamma_1 \\pdv{\\log \\rho}{t} + \\frac{\\rho}{P} (\\Gamma_3 - 1) \\qty(\\varepsilon_{\\text{eff}} - \\pdv{L}{m})  \\label{eq:log-pressure-energy-conservation}\\\\\n  \\pdv{\\log T }{t} &= (\\Gamma_3 - 1) \\pdv{\\log \\rho}{t} + \\frac{1}{c_V T} \\qty(\\varepsilon_{\\text{eff}} - \\pdv{L}{m}) \\label{eq:log-temperature-energy-conservation}\n\\end{align}\n\\end{subequations}}\n\n\\subsection{Linear perturbation theory}\n\nSay we have a solution for these equations, we look at linear perturbations of them.\nThis makes sense: the main solution is basically static on the pulsation time-scales.\n\nThe perturbed model is \\(f = f(m)\\),  the unperturbed one is \\(f_0(m)\\).\nThe Lagrangian perturbation is \\(\\delta f (m, t) = f(m, t) - f_0(m, t)\\).\n\nLet us consider specific cases for \\(f\\): the radial displacement is \\(\\delta r (m, t)\\). The position of the layer at time \\(t\\) is \\(r = r_0 + \\delta r\\).\n\nWe can write:\n%\n\\begin{equation}\n  r = r_0 \\qty(1 + \\frac{\\delta r}{r_0} ) = r_0 (1+ \\zeta)\n  \\,,\n\\end{equation}\n%\nwhere we define \\(\\zeta = \\delta r / r_0 \\).\n\nIn general the fractional perturbation \\(\\delta f / f_0\\) is assumed to be \\(\\ll 1 \\). So, \\(\\delta f / f_0 \\sim \\delta_f / f\\). Formally, we only consider terms which are of first order in either perturbed function.\nWe will insert expressions which are functions of perturbations of all our variables, and thus get linear differential equations.\n\n\\subsubsection{Properties of Lagrangian perturbations}\n\nIn general for a Lagrangian perturbation we have the following useful properties: \n\\begin{enumerate}\n  \\item we can use the properties of derivatives: \\(\\delta (f^n) = n f_0^{n-1} \\delta f\\);\n  \\item we can use the properties of logarithmic derivatives:\n  %\n  \\begin{align} \\label{eq:lagrangian-perturbation-logarithmic}\n  \\frac{ \\delta \\qty( \\prod f_i)}{\\prod f_i} = \\sum \\frac{ \\delta f_i}{f_i}\n  \\,;\n  \\end{align}\n  %\n  \\item \\(\\delta \\) commutes with partial derivation. \n\\end{enumerate}\n\n\\subsubsection{Continuity equation}\n\nLet us try the continuity equation, substituting in \\(r = r_0 (1+\\zeta)\\) and \\(\\rho = \\rho_0 (1 + \\delta \\rho / \\rho_0)\\).\n\n\\begin{subequations}\n\\begin{align}\n  \\pdv{r}{m} &= \\frac{1}{4 \\pi r^2 \\rho }  \\\\\n  \\pdv{}{m} \\qty(r_0 (1+\\zeta)) &=\n  \\frac{1}{4 \\pi r_0^2} \\qty(1+\\zeta)^{-2} \\qty(1 + \\frac{\\delta \\rho}{\\rho_0})^{-1}\n\\end{align}\n\\end{subequations}\n\nand we use \\((1+x)^n \\approx 1 + nx\\) plus the zeroth order equation: \\(\\pdv*{r_0 }{m} = 1 / 4 \\pi r_0^2 \\rho_0\\). \nWith these, we find:\n%\n\\begin{equation}\n  4 \\pi \\rho_0^2 \\qty(\\pdv{r_0}{m} (1+\\zeta) + r_0 \\pdv{\\zeta}{m})\n  = (1-2 \\zeta) -\\frac{\\delta \\rho}{\\rho_0}\n\\end{equation}\n\nWe can collapse the equation into:\n\\boxalign{\n\\begin{align} \\label{eq:linearized-continuity}\n  \\frac{\\delta \\rho}{\\rho_0} =\n  - 3 \\zeta - 4 \\pi r_0^3 \\rho_0 \\pdv{\\zeta}{m}\n\\end{align}}\n\nor, the density perturbation is proportional with a negative constant to the radial perturbation, plus a term proportional to \\(\\pdv*{\\zeta}{m}\\).\nIf there is a positive gradient of radial perturbation, the corresponding layer expands.\n\n\\subsubsection{Momentum conservation}\n\nLet us also perturb the momentum conservation equation; the unperturbed solution will be at hydrostatic equilibrium, so \\(\\pdv*[2]{r_0}{t} = \\pdv{r_0 }{t} =0 \\), which means \n%\n\\begin{align} \\label{eq:hydrostatic-equilibrium}\n\\pdv{P_0 }{m} = - \\frac{Gm}{4 \\pi r_0^{4}}\n\\,.\n\\end{align}\n\nSubstituting in we find that, to linear order: \n%\n\\begin{subequations}\n\\begin{align}\n\\pdv[2]{r}{t} &= - 4 \\pi r^2 \\pdv{P}{m} - \\frac{Gm}{r^2} \\\\\n\\pdv[2]{}{t} \\qty(r_0 \\qty(1 + \\zeta )) \n&= \n- 4 \\pi \\qty(r_0 (1+z))^2 \\pdv{}{m} \\qty(P_0 \\qty(1 + \\frac{ \\delta P }{P_0 })) - \\frac{Gm}{r_0^2 (1 + \\zeta^2)} \n\\\\\nr_0 \\pdv[2]{\\zeta }{t} \n&=\n- 4 \\pi r_0^2 \\qty(1 + 2 \\zeta )\n\\qty(\\pdv{P_0 }{m} \\qty(1 + \\frac{ \\delta P}{P_0 }) + P_0 \\pdv{}{m} \\qty(\\frac{ \\delta P}{P_0 }))\n- \\frac{GM}{r_0^2} \\qty(1 - 2z) \n\\\\\n\\frac{r_0}{4 \\pi r_0^2} \\pdv[2]{\\zeta }{t} &= - \\qty(1 + 2 \\zeta )\n\\qty(\\pdv{P_0 }{m} \\qty(1 + \\frac{ \\delta P}{P_0 }) + P_0 \\pdv{}{m} \\qty(\\frac{ \\delta P}{P_0 }))\n+ \\qty(1 - 2z) \\pdv{P_0 }{m} \\marginnote{Used equation \\eqref{eq:hydrostatic-equilibrium}.} \\\\ \n\\begin{split}\n\\frac{1}{4 \\pi r_0} \\pdv[2]{\\zeta }{t} &= \n- \\qty(\\pdv{P_0 }{m} \\qty(1 + \\frac{ \\delta P}{P_0 }) + P_0 \\pdv{}{m} \\qty(\\frac{ \\delta P}{P_0 })) + \\pdv{P_0 }{m} + \\\\\n&\\phantom{=}\\ - 2\\zeta \\qty(\\pdv{P_0 }{m} \\qty(1 + \\frac{ \\delta P}{P_0 }) + P_0 \\pdv{}{m} \\qty(\\frac{ \\delta P}{P_0 }))\n- 2 \\zeta \\pdv{P_0 }{m} \n\\end{split} \\marginnote{Split the terms into different orders of \\(\\zeta \\)} \\\\\n\\begin{split}\n\\frac{1}{4 \\pi r_0} \\pdv[2]{\\zeta }{t} &= \n- \\pdv{}{m} \\qty(\\delta P ) + \\\\\n&\\phantom{=}\\ \n- 4 \\zeta \\pdv{P_0 }{m}\n- 2\\zeta \\pdv[]{}{m} \\qty(\\delta P )\n\\end{split} \\\\\nr_0 \\dv[2]{\\zeta }{t} &= -4 \\pi r_0^2 \\qty( \\pdv{}{m} (\\delta P) + 4 \\zeta \\pdv{P_0 }{m}) \\marginnote{Neglected a second order term} \n\\,.\n\\end{align}\n\\end{subequations}\n\nThe final equation then looks like \n%\n\\boxalign{\n\\begin{align} \\label{eq:linearized-momentum-conservation}\nr_0 \\pdv[2]{\\zeta}{t} = - 4 \\pi r_0^2 \\qty(\n  \\underbrace{P_0 \\pdv{}{m} \\qty( \\frac{ \\delta P}{P_0 }) + \n  \\frac{ \\delta P}{P_0 } \\pdv{P_0 }{m}}_{ \\pdv{ \\delta P}{m} } + 4 \\zeta \\pdv{P_0 }{m}\n)\n\\,,\n\\end{align}}\n%\nand we can now give a physical interpretation of the various terms.  \n\nWe have a term \\(-16 \\pi r_0^2 \\zeta \\pdv*{P_0}{m} = 4 \\zeta Gm /r_0^2\\).\nThis, by itself, is a force moving the system away from equilibrium: the equation with only that term on the RHS is precisely like a harmonic repulsor, \\(\\ddot{\\zeta} = \\omega^2 z\\) with \n%\n\\begin{align}\n\\omega^2 = \\frac{4Gm}{r_0^3}\n\\,.\n\\end{align}\n\nThis term is of geometric origin: as the layer moves outwards it expands, and the expansion is favoured by the decrease in the gravitational potential and the corresponding increase in pressure due to the increase of the area of the layer. \n\nThe equation with only the other term looks like \n%\n\\begin{align}\n\\ddot{\\zeta} = - 4 \\pi r_0 \\pdv{ \\delta P }{m}\n= - 4 \\pi r_0  \\qty( P_0 \\pdv{}{m} \\qty(\\frac{ \\delta P }{P_0 }) + \\frac{ \\delta P}{P_0 } \\pdv{P_0 }{m})\n\\,.\n\\end{align}\n\n\\todo[inline]{According to the slides, the action of this term is to be split in two: for the second, a restoring force towards equilibrium, since if the pressure decreases as the layer expands then the force is inward, and a more vague interpretation for the first bit, stating that ``a non uniform variation of \\(\\delta P\\) from a layer to the next generates a change in the pressure gradient'': but it \\emph{is} a change in the pressure field\\dots}\n\n\\subsubsection{Energy conservation}\n\nLet us also consider the expression for the time derivative of \\(\\log P\\) coming from the energy conservation equation: equation \\eqref{eq:log-pressure-energy-conservation}; the perturbed equation for the time derivative of \\(\\log T\\) (equation \\eqref{eq:log-temperature-energy-conservation}) is analogously derived.  \nBesides \\(\\rho \\) and \\(P\\), we also perturb the adiabatic exponents and the \\(\\dv*{Q}{t} = \\epsilon_{\\text{eff}} - \\pdv*{L}{m}\\) term.\n\nAfter difficult manipulations we get back an equation which relates the changes in density and pressure to the change in energy: we manipulate until we get something which is similar to the original equation: \n%\n\\boxalign{\n\\begin{subequations}\n\\begin{align}\n\\pdv{}{t} \\qty(\\frac{ \\delta P }{P_0 }) &= \n\\Gamma_{1,0} \\pdv{}{t} \\qty(\\frac{ \\delta \\rho }{\\rho_0 })\n+ \\frac{\\rho_0 }{P_0 } \\qty(\\Gamma_{3, 0} -1) \\delta \\qty(\\epsilon_{\\text{eff}} - \\pdv{L}{m}) \\label{eq:perturbed-linearized-energy-log-pressure}\\\\ \n\\pdv{}{t} \\qty(\\frac{ \\delta T }{T_0 }) &= \n(\\Gamma_{3,0} - 1) \\pdv{}{t} \\qty(\\frac{ \\delta \\rho }{\\rho_0 })\n+ \\frac{1}{c_V T_{0}} \\delta \\qty(\\epsilon_{\\text{eff}} - \\pdv{L}{m}) \\label{eq:perturbed-linearized-energy-log-temperature}\n\\,,\n\\end{align}\n\\end{subequations}}\n\n%\nwhere we note that the first index of the adiabatic exponents denotes \\emph{which exponent it is}, while the second indicates that it is the unperturbed value.\n\n\\todo[inline]{The last \\(T\\) in the temperature equation is not unperturbed nor perturbed in the slides.}\n\n\\subsubsection{Luminosity equation}\n\nIn the radiative case with the diffusion approximation we can perturb the luminosity equation, \\eqref{eq:luminosity-equation}. It is much more convenient not to calculate \\(\\delta L\\) but \\(\\delta L  / L_0 \\) instead: this allows us to use the logarithmic derivative properties of the perturbation; also, since \n%\n\\begin{align}\nT^{3} \\pdv{T}{m} = T^{4} \\pdv{\\log T}{m}\n\\,\n\\end{align}\n%\nwe use the latter expression, which is more convenient. \nSo we have \\(L = \\prod f_i\\), with \n%\n\\begin{align}\nf_{i} = \\qty{- \\frac{64 \\pi^2 ac}{3}, r^{4}, \\kappa_{R}^{-1}, T^{4}, \\pdv{\\log T}{m}}\n\\,.\n\\end{align}\n\nNow we can apply the rule given in equation \\eqref{eq:lagrangian-perturbation-logarithmic}: we find\n%\n\\begin{equation}\n  \\frac{\\delta L}{L_0} = 4 \\zeta + 4 \\frac{\\delta T}{T_0} - \\frac{\\delta \\kappa_R}{\\kappa_{R,0}} + \\qty(\\pdv{\\log T}{m})^{-1}_{0} \\pdv{}{m} \\qty( \\frac{\\delta T}{T_0 })\n  \\,,\n\\end{equation}\n%\nwhere we used the simplification \n%\n\\begin{subequations}\n\\begin{align}\n\\delta \\qty(\\pdv{\\log T}{m}) &= \\delta \\qty(\\frac{1}{T} \\pdv{T}{m})  \\\\\n&= \\delta \\qty(\\frac{1}{T}) \\pdv{T_0 }{m} + \\frac{1}{T_0 }  \\delta \\qty(\\pdv{T}{m})  \\\\\n&= - \\frac{ \\delta T}{ T_{0}} \\pdv{T_0 }{m} + \\frac{1}{T_0 } \\pdv{ \\delta T }{m }  \\\\\n&= \\pdv{}{m} \\qty(\\frac{ \\delta T}{T_0 }) \\marginnote{Inverse application of the product rule}\n\\,.\n\\end{align}\n\\end{subequations}\n\nThe last step is to assume a certain dependence of the Rosseland mean opacity on the temperature and density: specifically, it is a ``Kramers-like'' expression, given by \n%\n\\begin{align}\n\\kappa_{R} \\propto \\rho^{n} T^{-s}\n\\,,\n\\end{align}\n%\nwhich can be substituted into our expression: the proportionality factor does not matter, and we get additional temperature and density terms: \n%\n\\boxalign{\n\\begin{align}\n\\frac{ \\delta L}{L_0 } \n= 4 \\zeta + (4+s) \\frac{\\delta T}{T_0} - n \\frac{ \\delta \\rho }{\\rho_0 } + \\qty(\\pdv{\\log T}{m})^{-1}_{0} \\pdv{}{m} \\qty( \\frac{\\delta T}{T_0 })\n\\,,\n\\end{align}}\n%\n\n\nIn the end, we have a set of four linear PDE equations (written as a 5-equation system).\n\nThese describe implicitly how the properties of the star change over time.\n\nPulsation usually affects mostly the outer layers of a star.\n\n% Moving on to\n\n\\section{Adiabatic oscillations}\n\n\\subsection{Derivation of the LAWE}\n\nExploiting the adiabatic approximation we will get the  Linear Adiabatic Wave Equation (LAWE): a single equation which summarizes the 4 and can be solved explicitly.\n\nRecall the heat transfer equation \\eqref{eq:heat-transfer-effective}: \nif we suppose that each layer does not lose nor gain heat, \\(\\dv*{Q}{t} =0\\), this implies that \\(\\delta (\\varepsilon_{\\text{eff}} - \\pdv*{L}{m} )=0\\).\n\nIs this approximation justified? The term multiplying \\(\\delta (\\varepsilon_{\\text{eff}} - \\pdv*{L}{m} )\\) in the perturbed energy equation \\eqref{eq:perturbed-linearized-energy-log-pressure} is \\(\\rho (\\Gamma_3-1)/P  = \\chi_T / (c_V T)\\).\nUsually \\(\\chi_T \\sim 1\\), while the density perturbation term is multiplied by \\(\\Gamma_1 \\sim 1\\).\n\nThis term,  \\( \\chi_T / (c_V T) \\delta (\\varepsilon_{\\text{eff}} - \\pdv*{L}{m} )\\), is of the order \\(1/\\tau_{\\text{th}}\\), the thermal time scale of this layer, while the term before, \\(\\Gamma_1 \\pdv*{}{t} (\\delta \\rho / \\rho)\\), is of the order \\(1/\\tau_{\\text{dyn}}\\), the dynamical time scale.\n\n\\todo[inline]{Is this just because the first term contains a time derivative while the second one does not?}\n\nTherefore, we neglect the second part.\nThis only works for the star as a whole, not for single layers.\nThere are stellar layers which are \\emph{strongly} non-adiabatic (driving layers). We will need some non-adiabatic theory to explain how pulsations \\emph{start}.\n\nSo, the energy conservation equations become \n%\n\\begin{align} \\label{eq:linearized-adiabatic-energy-conservation}\n\\frac{ \\delta P}{P} = \\Gamma_1 \\frac{ \\delta \\rho }{\\rho }\n\\qquad \\text{and} \\qquad\n\\frac{ \\delta T }{T} = \\qty(\\Gamma_3 -1) \\frac{ \\delta \\rho }{\\rho }\n\\,,\n\\end{align}\n%\nwhich we can substitute into the momentum conservation equation \\eqref{eq:linearized-momentum-conservation} to find \n%\n\\begin{align}\nr_0 \\pdv[2]{\\zeta }{t} = \n- 4 \\pi r_0^2 \\qty(\nP_0 \\pdv{}{m} \\qty(\\Gamma_1  \\frac{ \\delta \\rho}{\\rho })\n+ \\Gamma_1 \\frac{ \\delta \\rho }{\\rho } \\pdv{P_0}{m}\n+ 4 \\zeta \\pdv{P_0 }{m}\n)\n\\,,\n\\end{align}\n%\nand now we can use the continuity equation \\eqref{eq:linearized-continuity} which gives us an expression for \\(\\delta \\rho  / \\rho \\): inserting it we get \n%\n\\begin{subequations}\n\\begin{align}\n\\begin{split}\nr_0 \\pdv[2]{\\zeta }{t} &= \n- 4 \\pi r_0^2 \\bigg[\nP_0 \\pdv{}{m} \\qty(\\Gamma_1  \\qty(-3\\zeta - 4 \\pi r_0^3 \\rho_0 \\pdv{\\zeta }{m})) + \\\\\n&\\phantom{=}\\ + \\Gamma_1 \\qty(- 3\\zeta - 4 \\pi r_0^3 \\rho_0 \\pdv{\\zeta }{m}) \\pdv{P_0}{m}\n+ 4 \\zeta \\pdv{P_0 }{m}\n\\bigg]\n\\end{split}  \\\\\n\\label{eq:step0-LAWE-derivation-substituted}\n\\begin{split}\nr_0 \\pdv[2]{\\zeta }{t} &= 4 \\pi r_0^2 \\bigg(\n\\underbrace{(3 \\Gamma_1 - 4)\\zeta \\pdv{P}{m}}_{\\Circled{1}} \n+ \n\\underbrace{4 \\pi r_0^3 \\Gamma_1 \\rho \\pdv{\\zeta }{m} \\pdv{P}{m} }_{\\Circled{2}}\n+ \\\\\n&\\phantom{=}\\ \n+ \\underbrace{3 P \\pdv{}{m} \\qty(\\Gamma_1 \\zeta )}_{\\Circled{3}} \n+ \\underbrace{4 \\pi P \\pdv{}{m} \\qty(\\Gamma_1 r^3 \\rho \\pdv{\\zeta }{m})}_{\\Circled{4}}\n\\bigg)\n\\,,\n\\end{split}\n\\end{align}\n\\end{subequations}\n%\nand now we can can manipulate the terms inside the parentheses; we start to drop the zero indices, any quantity not being \\(\\delta \\)'d is meant to be unperturbed.\nThe first and third terms are respectively given by  \n%\n\\begin{align}\n\\Circled{1} = \n\\pdv{P}{m} \\zeta \\qty(3 \\Gamma_1 - 4) =\n\\hlc{pink}{\\zeta \\pdv{}{m} \\qty((3 \\Gamma_1 - 4) P)}- \\hlc{teal}{3 \\zeta P \\pdv{\\Gamma_1}{m}} \\marginnote{Backwards derivative of a product}\n\\,\n\\end{align}\n%\nand \n%\n\\begin{align} \\label{eq:step1-LAWE-derivation}\n\\Circled{3} = \n3 P \\pdv{}{m} \\qty(\\Gamma_1 \\zeta ) = 3P \\Gamma_1 \\pdv{\\zeta }{m} + \\hlc{teal}{ 3 P \\zeta \\pdv{\\Gamma_1 }{m}}\n\\,,\n\\end{align}\n%\nso we can see that the highlighted terms cancel.\nAlso, the other term in equation \\eqref{eq:step1-LAWE-derivation} can be rewritten using the continuity equation \\eqref{eq:continuity}: \n%\n\\begin{align}\n3P \\Gamma_1 \\pdv{\\zeta }{m} \n= \\hlc{lightgray}{12 \\pi r^2 \\rho  \\Gamma_1 P \\pdv{\\zeta }{m} \\pdv{r}{m}}\n\\,,\n\\end{align}\n%\nso we can see that if we expand the fourth term in \\eqref{eq:step0-LAWE-derivation-substituted} we find a thing that is equal to it: \n%\n\\begin{align}\n\\Circled{4} = \n4 \\pi P \\pdv{}{m} \\qty(r^3 \\times  \\Gamma_1  \\rho \\pdv{\\zeta }{m})\n= \\hlc{lightgray}{4 \\pi P \\times 3 r^2 \\pdv{r}{m} \\Gamma_1 \\rho \\pdv{\\zeta }{m}}\n+  \\hlc{lime}{4 \\pi P r^3 \\pdv{}{m} \\qty(\\Gamma_1 \\rho \\pdv{\\zeta }{m})}\n\\,,\n\\end{align}\n%\nso we will have twice that contribution in the final result.\n\nFor now then, we have shown that \n%\n\\begin{align}\n\\Circled{1} + \\Circled{3} + \\Circled{4} = \n\\hlc{pink}{\\zeta \\pdv{}{m} \\qty((3 \\Gamma_1 - 4) P)} +\n2 \\times \\hlc{lightgray}{12 \\pi P r^2 \\pdv{r}{m} \\Gamma_1 \\rho \\pdv{\\zeta }{m}}\n+ \\hlc{lime}{4 \\pi P r^3 \\pdv{}{m} \\qty(\\Gamma_1 \\rho \\pdv{\\zeta }{m})}\n\\,.\n\\end{align}\n\nNow then, the full equation reads \n%\n\\begin{subequations}\n\\begin{align}\n\\begin{split}\nr_0 \\pdv[2]{\\zeta }{t} &= \n4 \\pi r^2 \\zeta \\pdv{}{m} \\qty((3\\Gamma_1 -4) P) \n+ \\hlc{red}{16 \\pi^2 r_0^5 \\Gamma_1 \\rho \\pdv{\\zeta }{m} \\pdv{P}{m}} + \\\\\n&\\phantom{=}\\ \n\\hlc{red}{+ 96 \\pi^2 P r^4 \\pdv{r}{m} \\Gamma_1 \\rho \\pdv{\\zeta }{m}\n+ 16 \\pi^2 P r^5 \\pdv{}{m} \\qty(\\Gamma_1 \\rho \\pdv{\\zeta }{m})}\n\\,,\n\\end{split}\n\\end{align}\n\\end{subequations}\n%\nand we can notice a certain similarity between the highlighted terms: consider the expression \n%\n\\begin{align}\n\\pdv{}{m} \\qty(16 \\pi^2 \\Gamma_1 P \\rho r^{6} \\pdv{\\zeta }{m})\n\\,,\n\\end{align}\nto which we can apply the general expression, which holds for nonzero differentiable functions of a certain variable \\(x\\) (and if it is interpreted as a limit, even if the functions go to 0): \n%\n\\begin{align}\n\\pdv{}{x} \\qty(\\prod_i f_i) \n= \\qty(\\prod_i f_i) \\sum_i \\frac{1}{f_i} \\pdv{f_i}{x}\n\\,,\n\\end{align}\n%\nso \n%\n\\begin{subequations}\n\\begin{align}\n\\frac{\\displaystyle\\pdv{}{m} \\qty(16 \\pi^2 \\Gamma_1 P \\rho r^{6} \\pdv{\\zeta }{m})}{\\displaystyle 16 \\pi^2 \\Gamma_1 P \\rho r^{6} \\pdv{\\zeta }{m}} &= \n\\frac{1}{P} \\pdv{P}{m} \n+ \\frac{1}{\\Gamma_1 \\rho \\pdv*{\\zeta }{m}} \\pdv{}{m} \\qty(\\Gamma_1 \\rho \\pdv{\\zeta }{m})\n+ \\frac{1}{r^{6}} \\pdv{r^{6}}{m}  \\\\\n&= \\frac{1}{P} \\pdv{P}{m} \n+ \\frac{1}{\\Gamma_1 \\rho \\pdv*{\\zeta }{m}} \\pdv{}{m} \\qty(\\Gamma_1 \\rho \\pdv{\\zeta }{m})\n+ \\frac{6}{r} \\pdv{r}{m} \n\\,,\n\\end{align}\n\\end{subequations}\n%\nso \n%\n\\begin{subequations}\n\\begin{align}\n\\begin{split}\n\\frac{1}{r} \\pdv{}{m} \\qty(16 \\pi^2 \\Gamma_1 P \\rho r^{6} \\pdv{\\zeta }{m}) &= \n\\hlc{red}{16 \\pi^2 r^{5} \\Gamma_1 \\rho \\pdv{\\zeta }{m} \\pdv{P}{m} +} \\\\\n&\\phantom{=}\\ \n\\hlc{red}{+ 16 \\pi^2 r^{5} P \\pdv{}{m} \\qty(\\Gamma_1 \\rho \\pdv{\\zeta }{m}) + 96 \\pi^2r^{4} \\Gamma_1 \\rho \\pdv{\\zeta }{m} P \\pdv{r}{m}}\n\\,.\n\\end{split}\n\\end{align}\n\\end{subequations}\n\nNow, we can finally write the simplest form of the LAWE:\n%\n\\boxalign{\n\\begin{align} \\label{eq:LAWE}\nr \\pdv[2]{\\zeta}{t} =\n4 \\pi r^2 \\zeta \\pdv{}{m} \\qty((3 \\Gamma_1 - 4)P)+\n\\frac{1}{r} \\pdv{}{m} \\qty(16 \\pi^2 \\Gamma_1 P \\rho r^6 \\pdv{\\zeta}{m} )  \n\\,,\n\\end{align}}\n%\n\nNext time, we will decompose: \\(\\zeta(m, t) = \\eta(m) e^{i \\sigma t}\\) with a constant \\(\\sigma\\): putting this into the LAWE we simplify the exponentials and get the space dependent form of the LAWE.\n\nThe LAWE is a Storm-Liouville equation.\n\n\\end{document}\n", "meta": {"hexsha": "35b99662e2a472b306170327d15db44ffee4ccaa", "size": 25464, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ap_first_semester/advanced_astrophysics/07oct.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "ap_first_semester/advanced_astrophysics/07oct.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ap_first_semester/advanced_astrophysics/07oct.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 39.6018662519, "max_line_length": 451, "alphanum_fraction": 0.6374882187, "num_tokens": 9957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.33569984061527874}}
{"text": "\\documentclass[12pt]{article}\n\\topmargin=0cm \\oddsidemargin=0cm \n\\textheight=22cm\n\\textwidth=17cm\n\\parskip=0.1cm\n\\parindent=0.5cm\n\\pdfminorversion=4\n\\renewcommand{\\baselinestretch}{1.2}\n\n\\usepackage{mathrsfs}\n\n\\usepackage{latexsym}\n\\usepackage{amsmath}\n\\usepackage{amsfonts}\n\\usepackage{amssymb}\n\\usepackage{amsthm}\n\\usepackage{epsfig}\n\\usepackage{subfigure}\n\\usepackage{arydshln}\n\n\n\\usepackage[nolists]{endfloat}\n\n\\usepackage{natbib}\n\\usepackage{times}\n\\usepackage[usenames]{color}\n%\\usepackage{rotating}\n\\bibpunct{(}{)}{;}{a}{,}{,}\n\n\n% Nuevos comandos que estoy usando:\n\\newcommand{\\bx}{\\boldsymbol{x}}\n\\newcommand{\\by}{\\boldsymbol{y}}\n\\newcommand{\\bu}{\\boldsymbol{u}}\n\\newcommand{\\bU}{\\boldsymbol{U}}\n\\newcommand{\\bI}{\\boldsymbol{I}}\n\\newcommand{\\bbeta}{\\boldsymbol{\\beta}}\n\\newcommand{\\bmu}{\\boldsymbol{\\mu}}\n\\newcommand{\\brho}{\\boldsymbol{\\rho}}\n\\newcommand{\\bm}{\\boldsymbol{m}}\n\\newcommand{\\bS}{\\boldsymbol{S}}\n\\newcommand{\\bPsi}{\\boldsymbol{\\Psi}}\n\n\\newcommand{\\Xcur}{\\mathscr{X}}\n\n\n\n\n\\newtheorem{definition}{Definition}\n\\newtheorem{theorem}{Theorem}\n\\newtheorem{lemma}{Lemma}\n\\newtheorem{proposition}{Proposition}\n\\newtheorem{corollary}{Corollary}\n\\newtheorem{remark}{Remark}\n\\pdfminorversion=4\n\n\\newcommand{\\afb}{\\color{red}}\n\n\\begin{document}\n\n\\section{The models}\nIn what follows, the three models that we are now considering are presented. The term $F(\\cdot\\mid \\theta)$ and $H(\\cdot \\mid \\mu)$ will denote general distribution functions with parameters (can be vectors) $\\theta$ and $\\mu$, respectively, otherwise the distribution will be explicit. \\\\\n\nModel 1:\n\\begin{align*}\n&y_i\\mid \\theta_i \\sim N(\\theta_i, \\sigma^2),\\\\\n&\\theta_i= \\theta^{\\star}_{\\xi_i^{\\star}},\\\\\n&\\xi_i^{\\star}\\mid \\boldsymbol{w} \\sim Categorical(\\boldsymbol{w}),\\\\\n&w_k=z_k\\prod_{l<k}(1-z_l), \\hspace{0.5cm} k=2, \\ldots, K, w_1=z_1\\\\\n&z_k \\sim Beta(1, \\alpha), \\hspace{0.5cm} k=1, \\ldots, K-1, z_K=1, \\\\\n&\\theta^{\\star}_k  \\sim N(\\mu, \\tau^2), \\hspace{0.5cm}k=1, \\ldots, K.\n\\end{align*} \n\nModel 2:\n\\begin{align*}\n&y_i\\mid \\theta_i \\sim F(\\cdot \\mid \\theta_i),\\\\\n&\\theta_i= \\tilde{\\theta}_{\\tilde{\\xi}_i},\\\\\n&(\\tilde{\\xi}_1, \\ldots, \\tilde{\\xi}_n) \\sim CRP(\\alpha),\\\\\n&\\alpha \\sim H_1,\\\\\n&\\tilde{\\theta}_k  \\sim H(\\cdot\\mid \\mu), \\hspace{0.5cm}k=1, \\ldots, \t\\tilde{K}.\n\\end{align*} \n\nModel 3:\n\\begin{align*}\n&y_i\\mid \\theta_i \\sim N(\\theta_i, \\sigma^2),\\\\\n&\\theta_i\\mid G\\sim G,\\\\\n&G  \\sim DP(\\alpha, N(\\mu, \\tau^2)).\n\\end{align*} \n\n\n\n\n\\section{About Model 2}\nI'll give more details on the definition of the model in the BUGS code and describe the sampler. I will change the notation just to be consistent with the notation in code.\n\\subsection{The model and its BUGS Code}\n\\begin{minipage}{.5\\textwidth}\nThe model:\n\\begin{align*}\n&\\tilde{\\theta}_i  \\sim H(\\cdot\\mid \\mu), \\hspace{0.5cm}i=1, \\ldots, \tn,\\\\\n&({\\xi}_1, \\ldots, {\\xi}_n) \\sim CRP(\\alpha),\\\\\n& \\alpha \\sim H_1,\\\\ \n&\\theta_i= \\tilde{\\theta}_{{\\xi}_i},\\\\\n&y_i\\mid \\theta_i \\sim F(\\cdot \\mid \\theta_i).\n\\end{align*} \n\\end{minipage}\n\\begin{minipage}{.5\\textwidth}\nBUGS code:\n\\begin{verbatim}\nCode=nimbleCode({\n    for(i in 1:n){ \n    thetatilde[i] ~ H \n    }\n    xi[1:n] ~ dCRP(conc)\n    conc ~ H_1\n    \n    for(i in 1:n){\n      theta[i] <- thetatilde[xi[i]]\n      y[i] ~ F\n    }\n  })\n\\end{verbatim} \n\\end{minipage}\n\\vspace{0.5cm}\n\nI have tried different combinations of $F$ and $H$: normal with known variance and normal, normal with unknown variance and normal, Poisson and gamma, Weibull and gamma.\n\nSaying that $({\\xi}_1, \\ldots, {\\xi}_n) \\sim CRP(\\alpha)$ means that $\\xi_1=1$, and\n\\begin{align*}\n\\xi_i\\mid \\xi_1, \\ldots, \\xi_{i-1} \\sim \\frac{1}{i-1+\\alpha} \\sum_{j=1}^{i-1}\\delta_{\\xi_j} + \\frac{\\alpha}{i-1+\\alpha}\\delta_{\\xi^{new}}, \n\\end{align*}\nwhere $\\xi^{new}=\\max\\{ \\xi_1, \\ldots, \\xi_{i-1}\\}+1$.\n\n\\subsection{Samplers}\n\\begin{enumerate}\n\\item Sampling $\\tilde{\\theta}_k$: using NIMBLE's sampler.\n\\item Sampling $\\xi_i$:\n\\begin{enumerate}\n\\item when $H$ is not conjugate for $F$, a non conjugate sampler sampler based on algorithm 8 of \\cite{neal;2000} is used.  More specifically, the $\\xi_i$ are updated one at the time  from the following conditional distribution\n%each $\\tilde{\\theta}_k$ is updated from its  posterior based on  directly or an  random walk Metropolis-Hastings algorithm, which by the specification of the model, updates the  $\\tilde{\\theta}_k$ that are related to observations from the corresponding posterior distribution, or from the prior distribution if it is not related to observations. \n\\begin{align*}\n\\xi_i\\mid \\boldsymbol{y}, \\xi_{-i},... \\sim \\frac{1}{n-1+\\alpha}\\sum_{j \\neq i}f(y_i\\mid \\tilde{\\theta}_{\\xi_j})\\delta_{\\xi_j} +\\frac{\\alpha}{n-1+\\alpha}f(y_i\\mid \\tilde{\\theta}_{\\xi^{new}})\\delta_{\\xi^{new}},\n\\end{align*}\nthis is, $\\xi_i$ is an already existing label, $\\xi_j$,  or a new one, $\\xi^{new}$, with probabilities proportional to $f(y_i\\mid \\tilde{\\theta}_{\\xi_j})$ and $\\alpha f(y_i\\mid \\tilde{\\theta}_{\\xi^{new}})$, respectively,   $\\xi^{new}$ is the smallest label related with no observations. \n\\item when $H$ is conjugate for $F$, a conjugate sampler based on algorithm 2  of \\cite{neal;2000} is used. Here, the  $\\xi_i$  are updated one at the time from the following conditional distribution\n\\begin{align*}\n\\xi_i\\mid \\boldsymbol{y}, \\xi_{-i},... \\sim \\frac{1}{n-1+\\alpha}\\sum_{j \\neq i}f(y_i\\mid \\tilde{\\theta}_{\\xi_j})\\delta_{\\xi_j} +\\frac{\\alpha}{n-1+\\alpha}f(y_i)\\delta_{\\xi^{new}},\n\\end{align*}\nwhere $f(y_i)$ is the prior predictive density function at $y_i$.  If a new component for $\\xi_i$ is sampled, then the corresponding $\\tilde{\\theta}_{\\xi_i}$ has to be updated. In this case $\\tilde{\\theta}_{\\xi_i}$ is updated from its posterior distribution  based on observation $y_i$, which is conjugate.\\\\\n\nHere are the conjugate cases that are implemented in NIMBLE:\n\\begin{itemize}\n\\item $F=N(\\theta, \\sigma^2)$, with known variance $\\sigma^2$, and $H=N(\\mu, \\tau^2)$: \n$$\\theta \\mid y_i \\sim N\\left(\\frac{y_i/\\sigma^2 + \\mu/\\tau^2}{1/\\sigma^2+1/\\tau^2}, \\frac{1}{1/\\sigma^2 +1/\\tau^2} \\right), \\hspace{0.2cm}f(y_i)=N(y_i \\mid \\mu, \\sigma^2+\\tau^2).$$\n\\item $F=Poisson(\\theta)$,  and $H=Gamma(a, b)$: \n$$\\theta \\mid y_i \\sim Gamma(a+y_i, b+1), \\hspace{0.2cm}f(y_i)=\\frac{b^a}{(b+1)^{a+y_i}}\\frac{\\Gamma(a+y_i)}{\\Gamma(a)}\\frac{1}{y_i!}.$$\n\\item $F=Bernoulli(\\theta)$,  and $H=Beta(a, b)$: \n$$\\theta \\mid y_i \\sim Beta(a+y_i, b+1-y_i), \\hspace{0.2cm}f(y_i)=\\frac{\\Gamma(a+y_i)\\Gamma(b+1-y_i)}{(a+b)\\Gamma(a)\\Gamma(b)}.$$\n\\item $F=exp(\\theta)$,  and $H=Gamma(a, b)$: \n$$\\theta \\mid y_i \\sim Gamma(a+1, b+y_i), \\hspace{0.2cm}f(y_i)=\\frac{ab^a}{(b+y_i)^{a+1}}.$$\n\\item $F=Gamma(\\lambda, \\theta)$, with known $\\lambda$, and $H=Gamma(a, b)$: \n$$\\theta \\mid y_i \\sim Gamma(a+\\lambda, b+y_i), \\hspace{0.2cm}f(y_i)=\\frac{y_i^{\\lambda-1}b^a \\Gamma(\\lambda+a)}{\\Gamma(\\lambda)\\Gamma(a)(b+y_i)^{a+\\lambda}}.$$\n\\item $F=Multinomial(n, \\boldsymbol{\\theta})$,  with known $n$, and $H=Dirichlet(\\boldsymbol{\\alpha})$, where $\\boldsymbol{\\theta}=(\\theta_1, \\ldots, \\theta_d)$,  $\\boldsymbol{\\alpha}=\\alpha_1, \\ldots, \\alpha_d$: for $\\by_i=(y_{i,1}, \\ldots, y_{i,d})$,\n$$\\boldsymbol{\\theta} \\mid \\by_i \\sim Dirichelt(\\boldsymbol{\\alpha}+\\by_i), \\hspace{0.2cm}f(\\by_i)=\\frac{n! \\Gamma(\\sum_{l=1}^d\\alpha_l)}{\\Gamma(\\sum_{l=1}^d\\alpha_l+y_{i,l})}\\prod_{l=1}^d\\left\\{ \\frac{\\Gamma(\\alpha_l+y_{i,l})}{y_{i,l}! \\Gamma(\\alpha_l)}\\right\\}.$$\n\\end{itemize}\n\n\n\n\n\\item when $H$ is conjugate for $F$, we can define a new sampler were we can integrate out $\\tilde{\\theta}$ eliminating them from the algorithm. In this case, the sampler is  based on algorithm 3 of \\cite{neal;2000}. Let $1, 2, \\ldots, K$, be the relabeled  $K$ unique values in $(\\xi_1, \\ldots, \\xi_n)$, let and $m_{-i,k}$ be the number of times label $k$ appears in $\\xi_{-i}=(\\xi_1, \\ldots, \\xi_{i-1}, \\xi_{i+1}, \\ldots, \\xi_n)$.  The $\\xi_i$ are updated one at the time  from the following conditional distribution\n\\begin{align*}\n\\xi_i\\mid \\boldsymbol{y}, \\xi_{-i},... \\sim \\sum_{k =1 }^K\\frac{m_{-i,k}}{n-1+\\alpha}f(y_i\\mid \\by_{-i,k})\\delta_{k} +\\frac{\\alpha}{n-1+\\alpha}f(y_i)\\delta_{k+1},\n\\end{align*}\nwhere $\\by_{-i, k}$ denotes all observations $y_l$ such that $l\\neq i$ and $\\xi_l=k$,  $f(y_i\\mid \\by_{-i, k})$ is the posterior predictive density function  at $y_i$ based on data $\\by_{-i, k}$ and the prior $H$, i.e., $f(y_i\\mid \\by_{-i, k})=\\int f(y_i\\mid \\theta)\\prod_{\\{j : j\\neq i, \\xi_j=k\\}}f(y_j\\mid \\theta)H(d\\theta) $,  and $f(y_i)$ is the prior predictive density function at $y_i$, i.e., $f(y_i)=\\int f(y_i\\mid \\theta)H(d\\theta)$. \n\nFor instance, considering\n\\begin{itemize}\n\\item $F=N(\\theta, \\sigma^2)$, with known variance $\\sigma^2$, and $H=N(\\mu, \\tau^2)$, it follows that \\\\$f(y_i\\mid \\by_{-i, k})=N\\left(y_i \\mid \\mu_{-i,1}, \\sigma^2+ \\tau^2_{-i,1} \\right)$, where $\\tau^2_{-i,1}=1/\\left(m_{-i,k}/\\sigma^2 + 1/\\tau^2 \\right)$,  $\\mu_{-i,1}=\\tau^2_{-i,1}\\left(\\sum_{\\{j: j\\neq i, \\xi_j=k\\}}y_j/\\sigma^2 +\\mu/\\tau^2 \\right)$,  and $f(y_i)=N(y_i \\mid \\mu, \\sigma^2+\\tau^2)$\n\\item $F=Poisson(\\theta)$  and $\\theta \\sim Gamma(a,b)$, it follows that \\\\\n$f(y_i\\mid \\by_{-i, k})=\\frac{b_{1}^{a_{1 }}}{(b_1+1)^{a_1+y_i}}\\frac{\\Gamma(a_1+y_i)}{\\Gamma(a_{1})}\\frac{1}{y_i!}$, where $a_1=a+\\sum_{\\{j: j\\neq i, \\xi_j=k\\}}y_j$, $b_1=b+m_{-i,k}$, and $f(y_i)=\\frac{b^a}{(b+1)^{a+y_i}}\\frac{\\Gamma(a+y_i)}{\\Gamma(a)}\\frac{1}{y_i!}$.\n\\end{itemize}\n\\end{enumerate} \n \n \n\\underline{Some inefficiencies}:  1) the \\textit{calculate} function is used at each step, 2) maybe we could update only few more $\\tilde{\\theta}$ than the unique ones, rather than the whole vector, in the random walk Metropolis step. ( 3) The $\\xi$ are updated one at the time, we could update only the ones related with observations (need of varying dimensions)).\n\n\n\n\\item Sampling $\\alpha$: if $H_1\\equiv Gamma(a,b)$, then the following sampler can be used:\n\\begin{itemize}\n\\item sample $z\\sim Beta(1+\\alpha, n)$ and compute $w=\\frac{a+K-1}{a+K-1+n(b-ln(z))},$ where $K$ is the number of unique values in $(\\xi_1 ,\\ldots, \\xi_n)$.\n\\item sample $\\alpha\\sim Gama(a+K, b-ln(z))$ with probability $w$, and sample $\\alpha\\sim Gamma(a+K-1, b-ln(z))$ with probability $1-w$.\n\\end{itemize}\n\\end{enumerate}\n\n\\subsection{Output}\nGiven samples  $(\\tilde{\\theta}, (\\xi_1, \\ldots, \\xi_n)$  or $\\theta$,  we compute an approximation of measure $G$ based on a truncation level, say $L$, given by the user. \\\\\nMeasure $G$ is given by \n$$G(\\cdot)=\\sum_{j=1}^Lw_j\\delta_{\\theta^{\\star}_j}(\\cdot), \\hspace{0.5cm} w_1=v_1, \\hspace{0.2cm}w_j=v_j\\prod_{l<j}(1-v_l), l=2, \\ldots, L-1, \\hspace{0.2cm}w_L=\\prod_{l<L}(1-v_l),$$\nwhere $v_l\\sim Beta(1, \\alpha+n)$, and $$\\theta^{\\star}_j\\sim \\frac{\\alpha}{\\alpha+n}G_0 + \\sum_{j=1}^K\\frac{m_j}{\\alpha+n}\\delta_{\\overline{\\theta}_j},$$\nwhere $K$ is the number of unique values in $(\\xi_1 ,\\ldots, \\xi_n)$, $m_j$ denotes the number of relabeled $(\\xi_1 ,\\ldots, \\xi_n)$ equal to $j$, and $\\overline{\\theta}_j$ denote the  unique values in $(\\tilde{\\theta}_{\\xi_1}, \\ldots, \\tilde{\\theta}_{\\xi_n})$.\\\\\n\n\\underline{Comments}: $K$, $m_j$, and $\\overline{\\theta}$ can be obtained from $\\theta$.\\\\\nThere are results relating $\\alpha$, and acceptable error, $\\epsilon$, and  the truncation level, $L$, of $G$. More specifically,  $\\left(\\frac{\\alpha}{\\alpha+1}\\right)^{L-1}=\\epsilon$, so we can give a warning when the truncation level is too small for the value (or samples) of $\\alpha$ and $\\epsilon$.\n\n\n\\section{Model 1}\nWe don't have a BUGS version for this model as is stated before. We have  BUGS code for another representation of this model that involves the random measure $G$ written as the truncation of its stick breaking representation  written as a matrix,  and integrating out the random indexes. \n\\subsection{The model and its BUGS Code}\n\\begin{minipage}{.5\\textwidth}\nThe model:\n\\begin{align*}\n&w_k=z_k\\prod_{l<k}(1-z_l), \\hspace{0.5cm} k=2, \\ldots, T, w_1=z_1\\\\\n&z_k \\sim Beta(1, \\alpha), \\hspace{0.5cm} k=1, \\ldots, T-1, z_T=1, \\\\\n&\\theta^{\\star}_k  \\sim N(\\mu, \\tau^2), \\hspace{0.5cm}k=1, \\ldots, T,\\\\\n&\\theta_i= \\theta^{\\star}_{\\xi_i^{\\star}},\\\\\n&\\xi_i^{\\star}\\mid \\boldsymbol{w} \\sim Categorical(\\boldsymbol{w}),\\\\\n&y_i\\mid \\theta_i \\sim N(\\theta_i, \\sigma^2).\\\\\n\\end{align*} \n\\end{minipage}\n\\begin{minipage}{.5\\textwidth}\nBUGS code:\n\\begin{verbatim}\nCode=nimbleCode(\n  {\n    G[1:T,1:2] ~ dtruncSBDPnormal(\n        conc=conc0, mean=mean0, sd=tau0)\n    theta[1:T] ~ dNPDiscreteV(G[1:T,1:2])\n    for(i in 1:n){\n      y[i] ~ dnorm(theta[i], sd=s0)\n    }\n    conc0 <-1;\n    mean0 <- 5; tau0 <- sqrt(10);\n     s0 <- sqrt(10)\n})\n\\end{verbatim}\n\\end{minipage}\n\\vspace{0.5cm}\n\nFor this  model only the conjugate normal-normal model has been considered. \n\nIn the BUGS code, saying \\texttt{G[1:T,1:2] \\~{} truncSBDPnormal(conc=conc0, mean=mean0, sd=tau0)} means that \n \\begin{align*}\n G(\\cdot)=\\sum_{k=1}^T w_k \\delta_{\\theta_k}(\\cdot), \\hspace{0.5cm}w_k=z_k\\prod_{l<k}(1-z_l), \\hspace{0.2cm}z_k \\sim Beta(1, \\alpha), \\hspace{0.2cm} \\theta_k  \\sim N(\\mu, \\tau^2),\n \\end{align*}\n  and saying $theta[1:T] ~ dNPDiscreteV(G[1:T,1:2])$ means that \n \\begin{align*}\n \\theta_k\\sim \\sum_{j=1}^T w_j \\delta_{m_j},\n \\end{align*}\n where $w_j$ are weights that add up to one, and $m_j$ are possible values for $\\theta_k$.\n\nNote that lines 1 to 3 in the model correspond to \\texttt{G[1:T,1:2] \\~{} dtruncSBDPnormal(conc=conc0, mean=mean0, sd=tau0) } in the BUGS code, and lines 4 and 5 are related  to \\texttt{theta[1:T] \\~{} dNPDiscreteV(G[1:T,1:2])} in the BUGS code.\n\n\\subsection{Sampler}\nThe sampler that we have is the blocked Gibbs sampler and samples the random measure $G$ as a matrix whose first and second columns are the vector of $\\theta^{\\star}$ and $w$, respectively. The steps of the sampler are the following:\n\\begin{itemize}\n\\item[a)] updating $(\\theta^{\\star}_1, \\ldots, \\theta^{\\star}_T)$: $\\theta^{\\star}_k$ is updated from the prior if it is no related with any observation. Otherwise, $\\theta^{\\star}_k$ is updated from the posterior (which is conjugate in this case) considering the observations that have label $k$. \n\\item[b)] updating the labels $\\xi^{\\star}$: \n\\begin{align*}\n\\xi^{\\star}_i\\mid \\boldsymbol{y}, ...\\sim \\sum_{k=1}^T w_kN(y_i\\mid \\theta^{\\star}_k, \\sigma^2)\\delta_k.\n\\end{align*}\n\\item[c)] updating the weights $(w_1, \\ldots, w_T)$: first the stick variables are updated as \\begin{align*}\nz_k\\mid \\boldsymbol{y}, ... \\sim Beta \\left(1 + M_k, \\alpha+\\sum_{l=k+1}^TM_l\\right),\n\\end{align*}\nwhere $M_k$ denotes the number of observations that  have label $k$. Then $w_k=v_k\\prod_{l<k}(1-z_l)$.\n\\end{itemize}\n\nSeveral changes: 1) $\\theta^{\\star}$ could be updated using NIMBLE samplers, 2) I need to check the conjugacy between $z_k$, $w_k$ and $\\xi^{\\star}$ (Dirichlet-categorical), 3) if there is conjugacy, then use the NIMBLE sampler too, and 4) create a sampler only for the $\\xi^{\\star}$. \n\n\\bibliographystyle{biometrika}\n\\bibliography{ref}\n\\end{document}\n\n\n\n \n\n\n\n\n\n\n\n", "meta": {"hexsha": "c8f0602280894ad1bceb0a6f6198f0934c2b62c6", "size": 14852, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "notes/bnp_ModelsAndSamplers.tex", "max_stars_repo_name": "vishalbelsare/nimble", "max_stars_repo_head_hexsha": "1685f42fe992ff403a9144c9ad990b4f924eae53", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 120, "max_stars_repo_stars_event_min_datetime": "2015-02-17T18:56:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T16:58:09.000Z", "max_issues_repo_path": "notes/bnp_ModelsAndSamplers.tex", "max_issues_repo_name": "vishalbelsare/nimble", "max_issues_repo_head_hexsha": "1685f42fe992ff403a9144c9ad990b4f924eae53", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1011, "max_issues_repo_issues_event_min_datetime": "2015-01-06T06:06:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T13:28:14.000Z", "max_forks_repo_path": "notes/bnp_ModelsAndSamplers.tex", "max_forks_repo_name": "vishalbelsare/nimble", "max_forks_repo_head_hexsha": "1685f42fe992ff403a9144c9ad990b4f924eae53", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 29, "max_forks_repo_forks_event_min_datetime": "2015-05-18T19:52:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T21:13:05.000Z", "avg_line_length": 52.480565371, "max_line_length": 518, "alphanum_fraction": 0.666576892, "num_tokens": 5622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030761371502, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.3356998322374592}}
{"text": "\\XtoCBlock{SinGen}\r\n\\label{block:SinGen}\r\n\\begin{figure}[H]\\includegraphics{SinGen}\\end{figure} \r\n\r\n\\begin{XtoCtabular}{Inports}\r\nA & Amplitude\\tabularnewline\r\n\\hline\r\nf & Frequency\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n\r\n\\begin{XtoCtabular}{Outports}\r\nu & Sine wave output\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n\\begin{XtoCtabular}{Mask Parameters}\r\nfmax & Maximum Frequency in Hz\\tabularnewline\r\n\\hline\r\nOffset & Offset\\tabularnewline\r\n\\hline\r\nPhase & Phase [-Pi..Pi]\\tabularnewline\r\n\\hline\r\nts\\_fact & Multiplication factor of base sampling time (in integer format)\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n\\subsubsection*{Description:}\r\nGeneration of a sine wave with amplitude (A) and frequency (f).\r\n\n% include optional documentation file\r\n\\InputIfFileExists{\\XcHomePath/Library/General/Doc/SinGen_Info.tex}{\\vspace{1ex}}{}\r\n\r\n\\subsubsection*{Implementations:}\r\n\\begin{tabular}{l l}\r\n\\textbf{FiP8} & 8 Bit Fixed Point Implementation\\tabularnewline\r\n\\textbf{FiP16} & 16 Bit Fixed Point Implementation\\tabularnewline\r\n\\textbf{FiP32} & 32 Bit Fixed Point Implementation\\tabularnewline\r\n\\textbf{Float32} & 32 Bit Floating Point Implementation\\tabularnewline\r\n\\textbf{Float64} & 64 Bit Floating Point Implementation\\tabularnewline\r\n\\end{tabular}\r\n\r\n\\XtoCImplementation{FiP8}\r\n\\index{Block ID!416}\r\n\\nopagebreak[0]\r\n% Implementation details\r\n\\begin{tabular}{l l}\r\n\\textbf{Name} & FiP8 \\tabularnewline\r\n\\textbf{ID} & 416 \\tabularnewline\r\n\\textbf{Revision} & 1.0 \\tabularnewline\r\n\\textbf{C filename} & SinGen\\_FiP8.c \\tabularnewline\r\n\\textbf{H filename} & SinGen\\_FiP8.h \\tabularnewline\r\n\\end{tabular}\r\n\\vspace{1ex}\r\n\r\n8 Bit Fixed Point Implementation\r\n\r\n\\begin{XtoCtabular}{Controller Parameters}\r\ndelta\\_phi & Angle increment\\tabularnewline\r\n\\hline\r\nphase & Angle offset\\tabularnewline\r\n\\hline\r\noffset & Amplitude offset\\tabularnewline\r\n\\hline\r\nphi & Current angle\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n% Implementation data structure\r\n\\XtoCDataStruct{Data Structure:}\r\n\\begin{lstlisting}\r\ntypedef struct {\r\n     uint16        ID;\r\n     int8          *A;\r\n     int8          *f;\r\n     int8          u;\r\n     int8          delta_phi;\r\n     int8          phase;\r\n     int8          offset;\r\n     int8          phi;\r\n} SINGEN_FIP8;\r\n\\end{lstlisting}\r\n\r\n\\ifdefined \\AddTestReports\r\n\\InputIfFileExists{\\XcHomePath/Library/General/Doc/Test_SinGen_FiP8.tex}{}{}\r\n\\fi\r\n\\XtoCImplementation{FiP16}\r\n\\index{Block ID!417}\r\n\\nopagebreak[0]\r\n% Implementation details\r\n\\begin{tabular}{l l}\r\n\\textbf{Name} & FiP16 \\tabularnewline\r\n\\textbf{ID} & 417 \\tabularnewline\r\n\\textbf{Revision} & 1.0 \\tabularnewline\r\n\\textbf{C filename} & SinGen\\_FiP16.c \\tabularnewline\r\n\\textbf{H filename} & SinGen\\_FiP16.h \\tabularnewline\r\n\\end{tabular}\r\n\\vspace{1ex}\r\n\r\n16 Bit Fixed Point Implementation\r\n\r\n\\begin{XtoCtabular}{Controller Parameters}\r\ndelta\\_phi & Angle increment\\tabularnewline\r\n\\hline\r\nphase & Angle offset\\tabularnewline\r\n\\hline\r\noffset & Amplitude offset\\tabularnewline\r\n\\hline\r\nphi & Current angle\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n% Implementation data structure\r\n\\XtoCDataStruct{Data Structure:}\r\n\\begin{lstlisting}\r\ntypedef struct {\r\n     uint16        ID;\r\n     int16         *A;\r\n     int16         *f;\r\n     int16         u;\r\n     int16         delta_phi;\r\n     int16         phase;\r\n     int16         offset;\r\n     int16         phi;\r\n} SINGEN_FIP16;\r\n\\end{lstlisting}\r\n\r\n\\ifdefined \\AddTestReports\r\n\\InputIfFileExists{\\XcHomePath/Library/General/Doc/Test_SinGen_FiP16.tex}{}{}\r\n\\fi\r\n\\XtoCImplementation{FiP32}\r\n\\index{Block ID!418}\r\n\\nopagebreak[0]\r\n% Implementation details\r\n\\begin{tabular}{l l}\r\n\\textbf{Name} & FiP32 \\tabularnewline\r\n\\textbf{ID} & 418 \\tabularnewline\r\n\\textbf{Revision} & 1.0 \\tabularnewline\r\n\\textbf{C filename} & SinGen\\_FiP32.c \\tabularnewline\r\n\\textbf{H filename} & SinGen\\_FiP32.h \\tabularnewline\r\n\\end{tabular}\r\n\\vspace{1ex}\r\n\r\n32 Bit Fixed Point Implementation\r\n\r\n\\begin{XtoCtabular}{Controller Parameters}\r\ndelta\\_phi & Angle increment\\tabularnewline\r\n\\hline\r\nphase & Angle offset\\tabularnewline\r\n\\hline\r\noffset & Amplitude offset\\tabularnewline\r\n\\hline\r\nphi & Current angle\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n% Implementation data structure\r\n\\XtoCDataStruct{Data Structure:}\r\n\\begin{lstlisting}\r\ntypedef struct {\r\n     uint16        ID;\r\n     int32         *A;\r\n     int32         *f;\r\n     int32         u;\r\n     int32         delta_phi;\r\n     int32         phase;\r\n     int32         offset;\r\n     int32         phi;\r\n} SINGEN_FIP32;\r\n\\end{lstlisting}\r\n\r\n\\ifdefined \\AddTestReports\r\n\\InputIfFileExists{\\XcHomePath/Library/General/Doc/Test_SinGen_FiP32.tex}{}{}\r\n\\fi\r\n\\XtoCImplementation{Float32}\r\n\\index{Block ID!419}\r\n\\nopagebreak[0]\r\n% Implementation details\r\n\\begin{tabular}{l l}\r\n\\textbf{Name} & Float32 \\tabularnewline\r\n\\textbf{ID} & 419 \\tabularnewline\r\n\\textbf{Revision} & 0.1 \\tabularnewline\r\n\\textbf{C filename} & SinGen\\_Float32.c \\tabularnewline\r\n\\textbf{H filename} & SinGen\\_Float32.h \\tabularnewline\r\n\\end{tabular}\r\n\\vspace{1ex}\r\n\r\n32 Bit Floating Point Implementation\r\n\r\n\\begin{XtoCtabular}{Controller Parameters}\r\ndelta\\_phi & Angle increment\\tabularnewline\r\n\\hline\r\nphase & Angle offset\\tabularnewline\r\n\\hline\r\noffset & Amplitude offset\\tabularnewline\r\n\\hline\r\nphi & Current angle\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n% Implementation data structure\r\n\\XtoCDataStruct{Data Structure:}\r\n\\begin{lstlisting}\r\ntypedef struct {\r\n     uint16        ID;\r\n     float32       *A;\r\n     float32       *f;\r\n     float32       u;\r\n     float32       delta_phi;\r\n     float32       phase;\r\n     float32       offset;\r\n     float32       phi;\r\n} SINGEN_FLOAT32;\r\n\\end{lstlisting}\r\n\r\n\\ifdefined \\AddTestReports\r\n\\InputIfFileExists{\\XcHomePath/Library/General/Doc/Test_SinGen_Float32.tex}{}{}\r\n\\fi\r\n\\XtoCImplementation{Float64}\r\n\\index{Block ID!420}\r\n\\nopagebreak[0]\r\n% Implementation details\r\n\\begin{tabular}{l l}\r\n\\textbf{Name} & Float64 \\tabularnewline\r\n\\textbf{ID} & 420 \\tabularnewline\r\n\\textbf{Revision} & 0.1 \\tabularnewline\r\n\\textbf{C filename} & SinGen\\_Float64.c \\tabularnewline\r\n\\textbf{H filename} & SinGen\\_Float64.h \\tabularnewline\r\n\\end{tabular}\r\n\\vspace{1ex}\r\n\r\n64 Bit Floating Point Implementation\r\n\r\n\\begin{XtoCtabular}{Controller Parameters}\r\ndelta\\_phi & Angle increment\\tabularnewline\r\n\\hline\r\nphase & Angle offset\\tabularnewline\r\n\\hline\r\noffset & Amplitude offset\\tabularnewline\r\n\\hline\r\nphi & Current angle\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n% Implementation data structure\r\n\\XtoCDataStruct{Data Structure:}\r\n\\begin{lstlisting}\r\ntypedef struct {\r\n     uint16        ID;\r\n     float64       *A;\r\n     float64       *f;\r\n     float64       u;\r\n     float64       delta_phi;\r\n     float64       phase;\r\n     float64       offset;\r\n     float64       phi;\r\n} SINGEN_FLOAT64;\r\n\\end{lstlisting}\r\n\r\n\\ifdefined \\AddTestReports\r\n\\InputIfFileExists{\\XcHomePath/Library/General/Doc/Test_SinGen_Float64.tex}{}{}\r\n\\fi\r\n", "meta": {"hexsha": "a606afb00f1155e092912d9a0e53cdf7712b9763", "size": 6915, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Library/General/Doc/SinGen.tex", "max_stars_repo_name": "AlexisTM/X2C", "max_stars_repo_head_hexsha": "31f39b598afe271a7fd46ef1ee9e06c410b1120c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Library/General/Doc/SinGen.tex", "max_issues_repo_name": "AlexisTM/X2C", "max_issues_repo_head_hexsha": "31f39b598afe271a7fd46ef1ee9e06c410b1120c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Library/General/Doc/SinGen.tex", "max_forks_repo_name": "AlexisTM/X2C", "max_forks_repo_head_hexsha": "31f39b598afe271a7fd46ef1ee9e06c410b1120c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1931818182, "max_line_length": 90, "alphanum_fraction": 0.701373825, "num_tokens": 2093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3356998321612695}}
{"text": "\\chapter{Anomaly Detection}\n\\label{cha:anomaly_detection}\n\\epigraph{\n  The field of anomaly detection is very broad and many different fields have\n  developed a great variation of different methods for finding outliers.  This\n  work is focusing on detecting anomalies in sequences by predicting the\n  expected evolution of a time series and comparing this prediction to real\n  observations (or simply: the truth).  Before describing this process in more\n  detail, this chapter defines the different kinds of anomalies that exist in\n  sequences and briefly summarizes two other, common detection methods\n  for sequence outlier detection.\n}\n\n\\section{Anomalies}\n\\label{sec:anomalies}\nAn anomaly (or outlier) refers to a pattern in a dataset that does not match\nan expected behaviour.\nIn time series, there are two basic types of anomalies:\n\\begin{enumerate}\n\n  \\item \\emph{Simple anomalies}, describe instances that can be considered as\n    an outlier only with respect to their value. This is the most basic kind of\n    anomaly which can easily be caught by ordinary, statistical, range-based\n    detection algorithms. The anomaly in Fig.~\\ref{fig:intro_point_anomaly}\n    consists of a single instance and is hence called a \\emph{point} anomaly.\n    \\begin{figure}\n      \\centering\n      \\includegraphics[width=\\linewidth]{intro_point_anomaly.pdf}\n      \\caption{The simple point anomaly can easily be detected by appropriate\n      thresholds (green lines).}\n      \\label{fig:intro_point_anomaly}\n    \\end{figure}\n\n  \\item \\emph{Contextual anomalies} are patterns that are only anomalous within\n    a certain context, but not otherwise. In time series, the context is\n    provided by two attributes: The \\emph{contextual attribute} is typically\n    time itself, while the \\emph{behavioural attributes} describe the actual\n    values of the examined dataset. Fig.~\\ref{fig:intro_context_anomaly} shows\n    a contextual anomaly consisting of several abnormal points, which is\n    referred to as a \\emph{discord} or \\emph{subsequence} anomaly.\n    \\begin{figure}\n      \\centering\n      \\includegraphics[width=\\linewidth]{intro_context_anomaly.pdf}\n      \\caption{Contextual anomalies are not detectable with simple statistical\n      methods without causing a large number of false positives.}\n      \\label{fig:intro_context_anomaly}\n    \\end{figure}\n\\end{enumerate}\n\n\n\\newpage\n\\section{Techniques}\n\\label{sec:techniques}\n\nThe difficulty of anomaly detection stems from the fact that the patterns that\nare searched for are typically not known.  Different fields have come up with a\nlarge number of different approaches for the detection of the different kinds\nof anomalies. Two such approaches  are sketched below: \\emph{proximity-based}\ntechniques, and {\\em information theoretical} approaches [\\cite{AggarwalCharuC2017}].\n\n\\subsection{Proximity-based Anomaly Detection}\n\\label{sub:proximity_based_anomaly_detection}\n\nBy applying certain transformations to segments of a time series, a segment can be\nmapped into a multidimensional vector space. The proximity can then be\ncalculated for example with the Euclidean distance, which opens up the whole\nrange of proximity-based outlier detection methods, such as cluster, distance,\nand density based techniques.\n\nThe trivial example of such a transformation is to just consider segments of\nlength $n$ as a vector of length $n$.  Other approaches include \\emph{Discrete\nFourier Transforms} (DFT) or \\emph{Discrete Wavelet Transforms} (DWT), the\nsimplest of which is the \\emph{Haar Wavelet}. A Haar Wavelet decomposition is\nsketched in Fig.~\\ref{fig:haar_wavelets}, a more detailed description of how\nwavelet transformations work is given in [\\cite{AggarwalCharuC2017}]. The\nadvantage of transforming a sequence into a vector of wavelet coefficients is\nthat the coefficients directly represent short-term and long-term dependencies.\nThis enables a reduction of the dimensionality of the space that has to be\nanalyzed depending on the nature of the problem. For example, frequencies above\na certain threshold can be ignored.  The application of proximity-based methods\nnaturally becomes much more effective on the transformed sequences. Depending\non the nature of the dataset different transformations are more effective.  For\nsequences with dominant periodic parts the DFT works better, while series with\ndiscontinuities are well represented by the Haar-DWT.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=0.9\\linewidth]{haar_wavelets.png}\n  \\caption{Haar wavelet decomposition of series of length $N=4$.\n  [\\cite{AggarwalCharuC2017}]}\n  \\label{fig:haar_wavelets}\n\\end{figure}\n\n\n\\subsection{Information Theoretical Approaches}\n\\label{sub:information_theoretical_approaches}\n\nInformation theoretical models rely on the creation of so-called\n\\emph{summaries} of a dataset. The length of the summary is shorter the simpler\nthe sequence is.  A completely periodic sequence can be described very\nconcisely.  Sequences that contain anomalies require a longer description,\nhence the summary becomes longer. An anomaly is defined as a point or\nsubsequence that leads to a large increase of the length of the summary.  In\npractice, measures such as entropy can take the part of the summary length. The\nentropy of a sequence $X$ is defined by:\n\n\\begin{equation}\n  H(X) = - \\sum_{x \\in X} P(x) \\log P(x),\n\\end{equation}\n\nwhere $P(x)$ is the probability of a value $x$.\n\n\n\n\\subsection{Prediction}\n\\label{sub:prediction}\n\nThe approach that is used in this thesis relies on modelling the normal\nbehaviour of the given dataset and creating predictions. The predictions can\nthen be compared to the actual values of the series, essentially reducing the\nproblem to a \\emph{simple anomaly}, which can be detected by a simple threshold\non the error.\\\\\nConsidering a time series of length $T$, the single input \\emph{frames} of a\nseries will further be denoted by $\\vt{u}$ with $t \\in [0,T]$.  An input frame\ncontains all the features at time $t$ and is represented by a vector with $m$\ncomponents, which could be the pixel values of a flattened image.  The same\nholds for the target frames $\\vt{d}$, which hold the desired output at every\ntime step. The output of the forecasting algorithm is called the prediction,\ndenoted by $\\vt{y}$, and ought to be as close as possible to the target\n$\\vt{d}$.  Prediction and target frames can have a different size from the\ninput frames:\n\n\\begin{align}\n  \\vt{u} &= (u^t_1, u^t_2, ..., u^t_m)^T, \\nonumber\\\\\n  \\vt{d} &= (d^t_1, d^t_2, ..., d^t_k)^T. \\\\\n  \\vt{y} &= (y^t_1, y^t_2, ..., y^t_k)^T. \\nonumber\n\\end{align}\n\nBy defining an input sequence $\\textbf{u}$ as a sequence of vectors\n\n\\begin{equation}\n  \\textbf{u} := (\\vec{u}_0, \\vec{u}_1, \\vec{u}_2, ..., \\vec{u}_M)\n\\end{equation}\n\nthe prediction problem can be formulated by finding a function $F$, that\nreturns a good estimate $\\textbf{y}$ of the next $N$ true vectors $\\textbf{d}\n:= (\\vec{u}_{M+1}, ..., \\vec{u}_{M+N})$.\n\n\\begin{equation}\n  \\textbf{y} = (\\vec{y}_{M+1}, ..., \\vec{y}_{M+N}) \n             = F(\\vec{u}_0, \\vec{u}_1, ..., \\vec{u}_M)\n             = F(\\textbf{u})\n\\end{equation}\n\nThe approximation of the function $F$ is a regression problem which has\nbeen studied intensively throughout history [\\cite{narx_prediction}].\nRecently, Neural Networks (NN) have been applied to anomaly detection, as they\ncan model certain non-linear sequences without a priori knowledge about the\ndata, just by applying a learning algorithm. An in depth explanation of how NNs\ncan be applied to find $F$ for spatio-temporal datasets is given in\nChapter~\\ref{cha:neural_networks}.  Before 1980, time series were typically\npredicted by using autoregressive, moving-average models (ARMA), which where\nintroduced by [\\cite{boxjenkins}].  Another method published by\n[\\cite{winters1960forecasting}] on forecasting sales improved Holt`s double\nexponential smoothing.  This method later became known as the Holt-Winters\nmethod.  Both approaches are described in in the next paragraphs.  It should be\nnoted though that they are both linear regression models, which makes them\nincapable of predicting non-linear time series. For the sake of simplicity they\nare described only for the case of scalar time series.\\\\\n\nDuring the regression (or training) phase of the forecasting algorithm the\ntarget for the prediction is typically the true observation of the next time\nstep $\\vt{d} = \\vec{u}_{t+1}$.  The parameters of the algorithm are tuned until\nthe predictions $\\vt{y}$ are good enough.  As soon as the `one step ahead'\nprediction problem is solved, predictions further into the future can be made\nby feeding $\\vt{y}$ back to the algorithm as the next input $\\vec{u}_{t+1}$. In\nthis case the algorithm is in the forecasting phase and is not optimized\nany more. This prevents information about the next frame to leak into the\nprediction process.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=\\linewidth]{train_predict_mode.pdf}\n  \\caption{Input $\\vt{u}$, target $\\vt{d}$, and prediction $\\vt{y}$ during the\n  regression phase (left of the black line) and during the prediction phase.\n  In the prediction phase the algorithm has no access to the true target\n  any more, which is why they are depicted by a dashed line.}\n  \\label{fig:train_predict_mode}\n\\end{figure}\n\n\\subsubsection{Auto-regressive Integrated Moving Average}\n\\label{sub:arma}\n\nAuto-regressive integrated moving average (ARIMA) models are widely used in\nforecasting and are typically applied to non-stationary time series.  A\nnon-seasonal ARIMA model is defined by three parameters $p$, $q$, and $d$.  The\nfirst parameter $p$ is the order of the auto-regressive (AR) model, $q$ is the\norder of the moving-average (MA) model, and $d$ is the number of non-seasonal\ndifferences that are needed to obtain a stationary time series.  This means\nthat $Y_t$ is the result of applying the sequence difference operator $\\Delta\ny_t = y_{t+1}-y_{t}$ for $d$ times to $y_t$:\n\\begin{equation}\n  Y_t = \\Delta^d y_t = \\sum_{k=0}^d (-1)^{d-k} \\binom{d}{k} y_{t+k}\n\\end{equation}\n\nWith the difference $Y_t$ we can write the general forcasting equation of the\nARIMA model:\n\\begin{equation}\n  y_t = \\mu + \\sum_{i=1}^p \\varphi_i Y_{t-i} + \\sum_{i=1}^q \\theta_i \\epsilon_{t-i}\n\\end{equation}\n\nwhere $\\mu$ is the mean of the series, $\\varphi_i$ are the $p$ parameters of\nthe AR model, $\\theta_i$ the parameters of the MA model, and $\\epsilon_i$ white\nnoise error terms.  The parameters of the MA and AR models have to be fit to\nthe data and the order of the difference must chosen a priori.\n\n\n\\subsubsection{Holt-Winters Method}\n\\label{sub:holt_winters_method}\n\nThe Holt-Winters method belongs to the class of exponential smoothing\nalgorithms.  In contrast to MA models that apply the same weights over a window\nof a time series, exponential smoothing uses exponentially decaying weights\nback in time.\n\nThe most basic form is called simple exponential smoothing (SES), where the\nlevel of previous points provides an estimate for the next time step.  The\nmethod maintains an estimated point $\\vt{y}$, which is calculated based on\nprevious points and estimates.  They are assigned weights, which decrease\nexponentially going back in time.\n\\begin{align}\n  y_t = \\alpha d_t + (1-\\alpha)y_{t-1}\n\\end{align}\nThe smoothing parameter $\\alpha$ determines exponentially\ndecreasing weights that are applied to previous data points.  The smoothing\nparameter is chosen such that the mean squared error of prediction and data\npoint is minimized.\n\nThe Holt-Winters method extends the SES approach from only forecasting the level\nto smoothing equations for trend $b_t$ and seasonal $s_t$.\nIt is described by the following four equations:\n\\begin{align}\n  l_t &= \\alpha(d_t - s_{t-L}) + (1-\\alpha)(y_{t-1} + b_{t-1}) &\\text{level} \\\\\n  b_t &= \\beta(l_t - l_{t-1}) + (1-\\beta)b_{t-1} &\\text{trend} \\\\\n  s_t &= \\gamma(y_t - l_t) + (1 - \\gamma)s_{t-L} &\\text{seasonal} \\\\\n  y_{t+m} &= l_t + m b_t + s_{t-L+1+(m-1) \\bmod L} &\\text{forecast}\n\\end{align}\n\nwhere $L$ is the length of the seasonal component, $\\alpha$, $\\beta$, $\\gamma$\nare constants that need to be fit to the data and $m$ denotes how far into\nthe future the prediction goes.\n\n\n\\subsection{Anomaly Score}%\n\\label{sub:anomaly_score}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=\\linewidth]{anomaly_score.pdf}\n  \\caption{With a good prediction $y$, the problem can be reduced to a simple\n    anomaly detection over the error sequence $E$ (upper plot). The error\n    sequence still takes on arbitrary values and can be converted into a\n    probability of normality with an anomaly score (lower plot).\n    The normality is calculated with sliding windows of length 100 for $\\mu_E$\n    and a length of 5 for $\\mu_e$.\n  }\n  \\label{fig:anomaly_score}\n\\end{figure}\n\nWith the predicted sequence $\\textbf{y}$ it becomes quite simple to detect an\noutlier, because the problem can be reduced to a \\emph{simple anomaly} by\ncalculating the absolute error sequence $E$.\n\n\\begin{equation}\n  \\label{eq:err_seq}\n  E_i = || \\vt{y} - \\vt{d} ||_2\n\\end{equation}\n\nThe error can now be thresholded to detect an anomaly, but the value of this\nthreshold depends on the specific dataset that is being analyzed.  To obtain a\nprobability for how anomalous a point or subsequence is, an \\emph{anomaly\nscore} $\\Sigma$ is defined as suggested by [\\cite{numenta_realtime}]:\n\n\\begin{equation}\n  \\label{eq:normality_score}\n  \\Sigma = 1 - \\text{erf}\\bigg(\\frac{\\mu_e - \\mu_E}{\\sqrt{2}\\sigma_E}\\bigg),\n\\end{equation}\n\nwhere $\\mu_E$ and $\\sigma_E$ denote the mean and standard deviation of a window\nof length $N$ of the error sequence $E$. The mean $\\mu_e$ is calculated from a\nsmaller subsequence of $E$ of length $n \\ll N$. If $\\mu_e$ is close to $\\mu_E$\nthen $\\Sigma$ will be close to one, and can thus be considered \\emph{normal}\nwith a high probability. If $\\mu_e$ and $\\mu_E$ are far apart, the probability\nof normality is low and the point becomes more likely to be an\noutlier. This results in a score for the whole sequence, which can be used as\nan intuitive threshold according to the problem at hand.\nFig.~\\ref{fig:anomaly_score} shows how the anomaly detection problem of a\ncontextual outlier is first reduced to a simple anomaly by calculating $E$ and\nthen detected with a threshold on $\\Sigma$. \n\nIf the quantities $\\vt{y}$ and $\\vt{d}$ are vectors or matrices it might be\ndesirable to know which components in the vector (matrix) caused the anomaly.\nFor such a spatially resolved anomaly score the norm from Eq.~\\ref{eq:err_seq}\ncan be removed and $\\Sigma$ is calculated component-wise for every\ncoefficient in $|\\vt{y} - \\vt{d}|$.\n", "meta": {"hexsha": "4e1c9725ba41585e68b7a2f1a951e5fc086b5177", "size": 14615, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "mainmatter/anomaly.tex", "max_stars_repo_name": "nmheim/thesis", "max_stars_repo_head_hexsha": "feafb9f5c7bcf6b6473d3fca844a33dc25dcff0f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-09-22T12:17:23.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-22T12:17:23.000Z", "max_issues_repo_path": "mainmatter/anomaly.tex", "max_issues_repo_name": "nmheim/thesis", "max_issues_repo_head_hexsha": "feafb9f5c7bcf6b6473d3fca844a33dc25dcff0f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mainmatter/anomaly.tex", "max_forks_repo_name": "nmheim/thesis", "max_forks_repo_head_hexsha": "feafb9f5c7bcf6b6473d3fca844a33dc25dcff0f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.7614379085, "max_line_length": 85, "alphanum_fraction": 0.7560041054, "num_tokens": 3820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3356599068713037}}
{"text": "\n\n\\begin{frame}[fragile]{Lineage specific evolution}\n   \\begin{columns}[T,onlytextwidth]\n    \\column{0.5\\textwidth}\n    \\begin{figure}\n\t\t\\includegraphics[width=0.77\\textwidth]{images/monkey-model.png}\n        \\caption{Modeling full phylogeny as one component}\n\t\\end{figure}\n    \\column{0.5\\textwidth}\n    \\uncover<2>{\\begin{figure}\n\t\t\\includegraphics[width=\\textwidth]{images/csmet-model.png}\n        \\caption{Modeling full phylogeny as one component}\n\t\\end{figure}}\n    \\end{columns}\n\\end{frame}\n\n\\begin{frame}[fragile]{Ornstein-Uhlenbeck Models: Whole TFBS evolving as a unit}\n\\begin{itemize}\n\\item HB models neglects lineage or specie specific selection\n\\item OU models this gap by accounting for lineage/specie specific selection by requiring regime specific optima to be obtained\n\\item OU models can account for whole element substituion by defining a quantitative trait as a score attached to the TFBS $X(t)$\n\\item $X(t)$ evolves by two components one deterministic, other stochastic (BM)\n\\end{itemize}\n\\begin{align*}\ndX(t) &= \\alpha(\\theta-X(t)) + \\sigma dB(t)\\\\\n\\alpha & = \\text{Strength of selection}\\\\\n\\theta - X(t) & = \\text{Distance from optimum value}\\\\\n\\sigma &= \\text{strength of random drift}\\\\\ndB(t) &= \\text{random white noise}\n\\end{align*}\n\\end{frame}\n\n\n\n\n\\section{Brownian Motion and Evolution}\n\n\n\\begin{frame}[fragile]{Ornstein-Uhlenbeck Models: Whole TFBS evolving as a unit}\n   \\begin{columns}[T,onlytextwidth]\n    \\column{0.3\\textwidth}\n\t\\begin{figure}\n    \\begin{tikzpicture}[scale=0.6]\n    \\tikzstyle{operator} = [draw,fill=white,minimum size=1em] \n        \\draw[->] (0,-2) -- (6,-2);\n        \\draw[line width=1mm] (0,0) -- (1,0);   \n        \\draw[line width=1mm] (1,0) -- (2,1);\n        \\draw[line width=1mm] (2,1) -- (5,1);\n        \\draw[line width=1mm] (1,0) -- (2,-1);\n        \\draw[line width=1mm] (2,-1) -- (5,-1);   \n        \\draw[dashed] (1,0) -- (1,-2);\n        \\node at (1,-2.4) {$s$};\n        \\node at (3,-2.4) {Time};\n        \\node at (5,-2.4) {$T$};\n        \\node at (5.3,1) {$s_1$};\n        \\node at (5.3,-1) {$s_2$};\n    \\end{tikzpicture}\n\\caption{$s_1$, $s_2$ -- BM}    \n\\end{figure}\n\n\t\\column{0.7\\textwidth}    \n    \\begin{align*}\nE[\\mathbf{X}(t)] &= \\begin{pmatrix}\n\\theta_0\\\\\n\\theta_1\n\\end{pmatrix}\\\\\n \\texorpdfstring{{\\Sigma}} &= \\sigma^2\\begin{pmatrix}\nT & s\\\\\ns & T\n\\end{pmatrix}\\\\\n\\end{align*}    \n  \\end{columns}\n  \\begin{columns}[T,onlytextwidth]\n    \\column{0.3\\textwidth}     \n    \\begin{figure}\n    \\begin{tikzpicture}[scale=0.6]\n    \\tikzstyle{operator} = [draw,fill=white,minimum size=1em] \n        \\draw[->] (0,-2) -- (6,-2);\n        \\draw[line width=1mm] (0,0) -- (1,0);   \n        \\draw[line width=1mm] (1,0) -- (2,1);\n        \\draw[line width=1mm] (2,1) -- (5,1);\n        \\draw (1,0) -- (2,-1);\n        \\draw (2,-1) -- (5,-1);   \n        \\draw[dashed] (1,0) -- (1,-2);\n        \\node at (1,-2.4) {$s$};\n        \\node at (3,-2.4) {Time};\n        \\node at (5,-2.4) {$T$};\n        \\node at (5.3,1) {$s_1$};\n        \\node at (5.3,-1) {$s_2$};\n    \\end{tikzpicture}\n    \\caption{$s_2$ -- new optimum regime, $s_1$ -- ancestral}    \n\\end{figure}\n    \\column{0.7\\textwidth}\n    \\begin{align*}\n      E[X_1(T)] &= \\theta_0e^{-\\alpha T}+ \\theta_1(1-e^{-\\alpha T})\\\\\n      E[X_2(T)] &= \\theta_0e^{-\\alpha T} + \\theta_1e^{-\\alpha(T-s)}(1-e^{-\\alpha s})\\\\ \n      &+ \\theta_2(1-e^{-\\alpha(T-s)})\\\n\t\\end{align*}\n  \\end{columns}\n\\end{frame}\n", "meta": {"hexsha": "7b4ee190d01d0ed3199e40b7f330d7bd867e5664", "size": 3384, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "2016-july-lab/dump.tex", "max_stars_repo_name": "saketkc/talks", "max_stars_repo_head_hexsha": "1a7ac73adff41d43328584785206fc5f28836d9f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2016-july-lab/dump.tex", "max_issues_repo_name": "saketkc/talks", "max_issues_repo_head_hexsha": "1a7ac73adff41d43328584785206fc5f28836d9f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2016-july-lab/dump.tex", "max_forks_repo_name": "saketkc/talks", "max_forks_repo_head_hexsha": "1a7ac73adff41d43328584785206fc5f28836d9f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1764705882, "max_line_length": 129, "alphanum_fraction": 0.5859929078, "num_tokens": 1246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.33565989834193494}}
{"text": "%% Anti-Copyright 2015 - the scrivener\n\n\\chapter{Homology and cohomology (abelianization of homotopy types)}\n\\label{ch:V}\n\n\\presectionfill\\ondate{1.7.}\\pspage{291}\\par\n\n% 87\n\\hangsection[Comments on Thomason's paper on closed model structure\n\\dots]{Comments on Thomason's paper on closed model structure on\n  \\texorpdfstring{\\Cat}{(Cat)}.}\\label{sec:87}%\nI couldn't resist last night and had to look through Thomason's\npreprint on the closed model structure of\n\\Cat.\\scrcomment{\\textcite{Thomason1980}} The paper is really pleasant\nreading -- and it gives exactly what had been lacking me in my\nreflections lately on the homotopy theory of \\Cat{} -- namely, a class\nof neat monomorphisms $Y\\to X$ which all have the property that cobase\nchange by these preserves weak equivalence, the so-called \\emph{Dwyer\n  maps}.\\scrcomment{These Dwyer maps are not closed under retracts, so\n  \\textcite{Cisinski1999} introduced the\n  \\href{http://ncatlab.org/nlab/show/Dwyer+map}{\\emph{pseudo-Dwyer\n      maps}} which are, and \\emph{they} are now called Dwyer maps.} I\nhad hoped for a while that ``open immersions'' and their duals, the\n``closed immersions'' (namely sieve and cosieve maps, in Thomason's\nwording), have this property, and when it turned out they hadn't, I\nhad been at a loss of what stronger property to put instead, wide\nenough however to allow for the standard factorization statements for\na map to go through. The definition of a Dwyer map is an extremely\npretty one -- it is an open immersion $Y\\to X$ such that the induced\nmap from $Y$ into its closure $\\overline Y$ should have a right\nadjoint. Now this implies that $Y\\to\\overline Y$ is aspheric, and I\nsuspect that this extra condition on an open immersion $Y\\to X$ should\nbe sufficient to imply that it has the ``cofibration property'' above\nwith respect to weak equivalence. It would mean in a sense that the\ngiven open immersion is very close to being a closed immersion too,\nwithout however being a direct summand necessarily. The dual notion is\nthat of a closed immersion such that the corresponding interior\n$\\mathring Y$ of $Y$ in $X$ gives a map $\\mathring Y \\to Y$ which has\na left adjoint, or only which is ``coaspheric''. By Quillen's duality\nprinciple, if one notion works well for pushouts, so does the\nother. -- With this notion in hands, it shouldn't be difficult now to\nget a closed model structure on \\Cat{} a lot simpler than\nThomason's. Visibly, he was hampered by the standing reflex: homotopy\n= semi-simplicial algebra, which caused him to pass by the detour of\nthe category \\Simplexhat{} of semi-simplicial complexes, rather than\njust working in \\Cat{} itself. I'll have to come back upon this in\npart \\ref{ch:V} of the notes, where I intend to investigate the\nhomotopy properties of \\Cat{} and elementary modelizers \\Ahat,\nincluding the existence of closed model structures.\n\nSome comments of Thomason's at the end of his preprint, about\napplication to algebraic K-theory, seem to indicate that the notion of\n``integration'' and ``cointegration'' of homotopy types I have been\ninterested in, has been studied (under the name holim and hocolim) in\nthe context of closed model categories by Anderson (his paper appeared\nin 1978).\\scrcomment{\\textcite{Anderson1978}} As I am going to develop\nsome ideas along these lines in part \\ref{ch:VI} on derivators, I\nshould have a look at what Anderson does, notably\\pspage{292} what his\nassumptions on the indexing categories are. Thomason seems to believe\nthat the closed model structure of \\Cat{} is essential for being able\nto take homotopy limits -- whereas it is clear a priori to me that the\nnotion depends only on the notion of weak equivalence. Indeed, he\nseems to consider the possibility of taking homotopy limits in \\Cat{}\nas the main application of his theorem, and in order to apply\nAnderson's results, believes it is necessary to be able to give\nconcrete characterizations for ``fibrations'' and ``cofibrations'' of\nhis closed model structure. Now, it turns out that the case he is\ninterested in (for proving ``Lichtenbaum's\nconjecture'')\\scrcomment{aka the\n  \\href{https://en.wikipedia.org/wiki/Quillen-Lichtenbaum_conjecture}{Quillen–Lichtenbaum\n    conjecture}} is a typical\ncase of \\emph{direct} homotopy limits, namely ``integration'' -- which\ncan be described directly in \\Cat{} in such an amazingly simple way\n(as sketched in section \\ref{sec:69}, p.\\\n\\ref{p:198}--\\ref{p:199}). Thus, I feel for this application, the\nclosed model structure is wholly irrelevant. As for cointegration, I\ndo not expect that there is a comparably simple construction of this\noperation within the modelizer \\Cat, but presumably there is when\ntaking \\oo-Gr-stacks as models (as suggested by the ``geometric''\napproach to cohomology invariants, via stacks, where the operation of\n``direct image'', namely cohomology precisely, is the obvious one,\nwhereas inverse images are more delicate to define, by an adjunction\nproperty with respect to direct images\\ldots). When working in \\Cat,\ncointegration of homotopy types should be no more nor less involved\nthan in any closed model category say, and involve intensive recourse\nto ``fibrations'' (in the sense of the closed model structure, or more\nintrinsically, in the sense that base change by these should preserve\nweak equivalence). Now the latter have become quite familiar to me\nduring my long scratchwork on cohomology properties of maps in \\Cat,\nand I'll have to try to put it down nicely in part \\ref{ch:V} of the\nnotes.\n\n% 88\n\\hangsection[Review of pending questions and topics (questions 1) to\n\\dots]{Review of pending questions and topics\n  \\texorpdfstring{\\textup(questions \\textup{1)} to \\textup{5)},\n    including characterizing canonical modelizers\\textup)}{(questions\n    1) to 5), including characterizing canonical\n    modelizers)}.}\\label{sec:88}%\nThe present ``part \\ref{ch:IV}'' on asphericity structures (and their\nrelations to contractibility structures) turns out a lot longer than I\nanticipated, and the end is not yet quite in sight! Therefore, before\npursuing, I would like to make a review of the questions along these\nlines which seem to require elucidation, and then decide which I'm\ngoing to deal with, before going over to part \\ref{ch:V}.\n\n\\namedlabel{q:88.1}{1)}\\enspace Whereas the relevant notions of\n``morphisms'' and ``bimorphisms'' for contractibility structures seem\nto me well understood, there remains\\pspage{293} a certain feeling of\nuneasiness with respect to asphericity structures, which haven't got\nyet a reasonable notion of morphism. Thus, I have left unanswered the\nquestions raised in section \\ref{sec:84} around the inclusion\ncondition\n\\[ f_!(M\\suba) \\subset M'\\suba,\\]\nso it is not impossible that, while relying on the mere feeling that\nthe inclusion is just not reasonable and that the answer to the\nspecific questions are presumably negative, I am about to miss some\nunexpected important fact! It seems I developed kind of a block\nagainst checking -- maybe the answers are well-known and Tim Porter\nwill tell me\\ldots Maybe I better leave the question for a later\nmoment, as it will ripen by itself if I leave it alone\\ldots\n\n\\namedlabel{q:88.2}{2)}\\enspace I should at last introduce\ncontractors, and morphisms of such. When I set out on part \\ref{ch:IV}\nof the notes, I expected that the notion of a contractor would be one\nmain notion, alongside with the notion of a canonical modelizer -- it\nturns out that so far I didn't have much use yet for one or the\nother. Contractors can be viewed as categories generating\ncontractibility structures, just as aspherators are there for\ngenerating asphericity structures. However, whereas any small category\nis an aspherator, the same is definitely not so for contractors, as we\ndemand that every object in $C$ should be contractible, for the\nhomotopy structure in \\Chat{} generated by $C$ itself. If we except\nthe case of a contractor equivalent to the final category (a so-called\n\\emph{trivial} contractor), a contractor is a strict test category --\nthus the notion appears somewhat as a hinge notion between the test\nnotions, and the ``pure'' homotopy notions and more specifically,\ncontractibility structures. Writing up some scratchnotes I got should\nbe a pure routine matter.\n\n\\namedlabel{q:88.3}{3)}\\enspace A lot more interesting seems to me to\ntry and resolve a persistent feeling of uneasiness which has been\nfloating, throughout the long-winded reflections on homotopy and\nasphericity structures in parts \\ref{ch:III} and \\ref{ch:IV} of the\nnotes. This is tied up with this fact, that my treatment of the main\nnotions, namely contractibility and asphericity, has been consistently\n\\emph{non-autodual}. More specifically, when a category $M$ is\nendowed with either a contractibility or an asphericity structure, it\ndoes \\emph{not} follow that the opposite category $M\\op$ is too in a\nnatural way. When defining homotopy relations and homotopism\nstructures (section \\ref{sec:51}, \\ref{subsec:51.A} and\n\\ref{subsec:51.B}), these were autodual notions, but the notion of a\nhomotopy interval structure, which we used in order to pass from a\ncontractibility\\pspage{294} structure to the corresponding notions of\nhomotopy equivalence between maps and of homotopisms, is highly\nnon-autodual too. It breaks down altogether when $M$ is a ``pointed''\ncategory, namely contains an object which is both initial and final --\nin this case, for any homotopy interval structure on $M$, any two maps\nin $M$ are homotopic, and any map is a homotopism, hence any object is\ncontractible!\n\nOur initial motivation, namely understanding ``modelizers'' for\nordinary homotopy types, made it very natural to get involved in\nnon-autodual situations, as the homotopy category \\Hot{} itself, and\nthe usual model categories for it, displays strongly non-autodual\nfeatures. (Thus, whereas the usual test categories all have a final\nobject, it is easy to see that a test category cannot possibly have an\ninitial object.) However, the homotopy and asphericity notions we then\ncame to develop make sense and are familiar indeed not only in the\n``modelizing story'', but in any situation whatever which turns up,\ngiving rise to anything like a ``homology'' or a ``homotopy''\ntheory. To give one specific example, starting with an abelian\ncategory \\scrA, the corresponding homology theory is concerned with the\ncategory of \\scrA-valued complexes, say $\\mathrm\nK^\\bullet(\\scrA)$. The most basic notions here are the three homotopy\nnotions and two asphericity notions, namely: homotopy equivalence\nbetween maps, homotopism, contractible objects, and quasi-isomorphisms\n(= ``weak equivalences''), and acyclic (= ``aspheric'') objects. The\ntwo first homotopy notions determine each other in the usual way, and\ndefine the third, namely an object is contractible (or null-homotopic)\nif{f} the map $0\\to X$, or equivalently $X\\to 0$, is a homotopism. On\nthe other hand, if we use the mapping-cylinder construction for a map,\nthe set of contractible objects determines the set of homotopisms, as\nthe maps whose mapping cylinder is contractible. Likewise, weak\nequivalences determine aspheric objects, and conversely if the mapping\ncylinder construction is given. The question that now comes to mind\nimmediately is whether the two sets of notions, the three pure\nhomotopy notions (determining each other), and the two ``asphericity\nnotions'' (determining each other too), mutually determine each\nother, as in the non-commutative set-up we have worked in so far. We\ncan also remark that the functor\n\\[ \\mathrm H^0 : \\mathrm K^\\bullet(\\scrA)\\to\\scrA\\]\nvisibly plays the part of the functor \\piz{} in the non-commutative\nset-up, it gives rise moreover to the $\\mathrm H^i$ functors (any\ninteger $i$) by composing with the iterated shift functor (where the\nshift of $X$ is just the mapping\\pspage{295} cylinder of $0\\to X$),\nthus the set of aspheric objects formally from the functor $\\mathrm\nH^0$ (as the objects $X$ such that $\\mathrm H^i(X)=0$ for all $i$),\nmuch as in the non-commutative set-up the functor \\piz{} for a\ncontractibility structure determines the latter, and hence also the\ncorresponding asphericity structure.\n\nThus, the question arises of formulating the basic structures, namely\ncontractibility and asphericity structures, in an autodual way,\napplying both to the autodual situation just described, and to the\nnon-autodual one we have been working out in the notes -- and if\npossible even, in all situations met with so far where a homology or\nhomotopy theory of some kind of other has turned up. Of course, it is\nby no means sure a priori that we can do so, by keeping first nicely\napart the two sets of notions (contractibility and asphericity),\nnamely defining them separately, and then showing that a\ncontractibility structures determines an asphericity structures, and\nis determined by the latter. Maybe we'll have to define from the\noutset a richer kind of structure, where both ``pure'' homotopy\nnotions and asphericity notions are involved. Also, the familiar\ngeneralization of mapping cylinders, namely homotopy fibers and\ncofibers, and the corresponding long exact sequences, will evidently\nplay an important role in the structure to be described. Now, this\nagain ties in with the corresponding structure of a derivator, as\ncontemplated in section \\ref{sec:69}, namely ``integration'' and\n``cointegration'' of diagrams in a given category.\n\nDefinitely, this reflection is going to lead well beyond the scope of\nthe present part \\ref{ch:IV}\\scrcomment{I guess it is because this\n  question is already growing in prominence that AG later decided to include\n  the present section in part \\ref{ch:V}!} -- it relates rather to\npart \\ref{it:71.C} of the working program envisioned by the end of May\n(section \\ref{sec:71}, p.\\ \\ref{p:207}--\\ref{p:210}), and rather\nbelong to part \\ref{ch:VI} of these notes, which presumably will\ncenter around the notion of a derivator. There is however a more\ntechnical question, and of more limited scope, which deserves some\nthought and goes somewhat in the same direction, namely: how to define\n(for a given contractibility or asphericity structure on $M$) an\n\\emph{induced} structure on a category $M_{/a}$, where $a$ is in $M$?\nThere is a little perplexity in my mind, even when $M$ is of the type\n\\Chat{} say, with $C$ a contractor and $a$ in $C$, taking the\ncanonical structure on \\Chat{} -- because with the most evident choice\nof an ``induced'' asphericity structure on $(\\Chat)_{/a} \\simeq\n(C_{/a})\\uphat$, namely the usual notion of aspheric objects, this\nstructure\\pspage{296} will practically never be totally aspheric\n(unless we take $a$ to be a final object of $C$), hence will not be\nassociated to a contractibility structure -- whereas we expect that\nthe contractibility structure of \\Chat{} should induce one on\n$\\Chat_{/a}$. Presumably, the ``correct'' notions of induced\nstructure, in the case of asphericity structure and the corresponding\nnotion of weak equivalence, should be considerably stronger than the\none I just envisioned, and correspond to the intuition of\n``\\emph{fiberwise} homotopy types'' over the object $a$ (visualized as\na space-like object). A careful description of such induced structures\nseems to me to be needed, and the natural place to be the present part\n\\ref{ch:IV} of the notes.\n\n\\namedlabel{q:88.4}{4)}\\enspace A little reflection on semi-simplicial\nhomotopy notions (and their analogons when $\\Simplex$ is replaced by a\ngeneral test category $\\Delta$) seems needed, in order to situate the\nfollowing fact: ss homotopy notions, namely for ss objects in any\ncategory $A$, behave well with respect to \\emph{any} functor\n\\begin{equation}\n  \\label{eq:88.1}\n  A\\to B,\\tag{1}\n\\end{equation}\nwithout having to assume that this functor commutes with finite\nproducts, whereas in the context of homotopy structures, when have a\nfunctor between categories endowed say with homotopy interval\nstructures (for instance, with contractibility structures), such a\nfunctor\n\\begin{equation}\n  \\label{eq:88.2}\n  M\\to N\\tag{2}\n\\end{equation}\nbehaves well with respect to homotopy notions only, it would seem, if\nwe assume beforehand it commutes with finite products (plus, of\ncourse, that it transforms a given generating family of homotopy\nintervals of $M$ into homotopy intervals of $N$). In\ncase\n\\[ M = \\bHom(\\Delta\\op,A), \\quad N=\\bHom(\\Delta\\op,B),\\]\nand \\eqref{eq:88.2} comes from a functor \\eqref{eq:88.1} which does\nnot commutes to finite products, neither does \\eqref{eq:88.2} -- and\nstill \\eqref{eq:88.2} is well-behaved with respect to ss homotopy\nnotions! It should be noted of course that the semi-simplicial\nhomotopy notions in $M$ can be defined, even without assuming that in\n$A$ finite products exist, namely in situations when $M$ does not\nadmit finite products -- and hence, strictly speaking, the set-up of\nsection \\ref{sec:51} does not apply. All this causes a slightly\nawkward feeling, which I would like to clarify and see what's going\non. I suspect it should be simple enough to do it here and now.\n\nFirst, assume that $A$ is stable under finite products, and under\ndirect sums (with small indexing set say -- for what we want to do\nwith $\\Simplex$, finite direct sums even would be enough). We'll use\nsums only with summands\\pspage{297} equal to a chosen final object $e$\nof $A$, in order to get a functor\n\\[ I\\mapsto I_A : \\Sets\\to A,\\]\nwhere $I_A$ is the ``constant'' object of $A$ with value $I$, namely a\nsum of $I$ copies of $e$ (sometimes also written $I\\times e$). Using\nthis functor, we get a functor\n\\[\\Delta\\!\\uphat = \\bHom(\\Delta\\op,\\Sets) \\to M =\n\\bHom(\\Delta\\op,A),\\]\nwhich I denote by\n\\[K\\mapsto K_A,\\]\nassociating to any ss~set the corresponding ``constant'' (relative to\n$A$) ss~object of $A$.\\scrcomment{I think it's a bit unclear here\n  whether the test category $\\Delta$ is actually assumed to be\n  $\\Simplex$ after all\\ldots} On the other hand, because $A$ admits\nfinite products, so does $M$, which enables us to make use of the\nhomotopy notions developed in sections \\ref{sec:51} etc. Thus, if\n\\[\\bI=(I,\\delta_0,\\delta_1)\\]\nis any interval in $\\Delta\\!\\uphat$, considering the corresponding\n``$A$-constant'' interval $\\bI_A$ in $M$, we get homotopy notions in\n$M$, which we may refer to as \\emph{\\bI-homotopy} (dropping the\nsubscript $A$). They can all be deduced from the elementary\n\\bI-homotopy between maps in $M$, which is expressed in the known way,\nin terms of a map in $M$\n\\[ h : \\bI_A \\times X\\to Y,\\]\nwhere $X$ and $Y$ are the source and target in $M$ of the two\nconsidered maps, between which we want to find an elementary\n\\bI-homotopy $h$. This map $h$ decomposes componentwise into\n\\begin{equation}\n  \\label{eq:88.star}\n  h_n : (I_n)_A \\times X_n\\to Y_n,\\tag{*}\n\\end{equation}\nand each $h_n$ can be interpreted, in view of the definition of $I_n$,\nas a map\n\\begin{equation}\n  \\label{eq:88.starprime}\n  h_n': I_n \\to \\Hom_A(X_n,Y_n),\\tag{*'}\n\\end{equation}\nprovided we assume that taking products in $A$ is distributive with\nrespect to the sums we are taking, whence\n\\[ (I_n)_A \\times X_n \\simeq (I_n)_{X_n} = \\text{direct sum of $I_n$\n  copies of $X_n$.}\\]\nNow to give $h$, or equivalently a sequence of maps $h_n$ in\n\\eqref{eq:88.star} ``functorial in $n$ for variable $n$'', amounts to\ngiving a sequence of maps \\eqref{eq:88.starprime}, satisfying a\ncorresponding compatibility relation for variable $n$. The point of\ncourse is that (for any $I$ in $\\Delta\\!\\uphat$ and $X,Y$ in $M$)\n\\emph{the set of data \\eqref{eq:88.starprime} plus the compatibility\n  condition make sense, formally, independently of any exactness\n  assumptions on $A$}. Thus, it can be taken\\pspage{298} as the formal\ningredient of a definition of ``elementary \\bI-homotopy'' between two\nmaps in $M$, without any assumptions whatever on the category $A$ we\nstart with. The standard case is the one when $I=\\Simplex_1$, the\n``unit interval'', but never mind. The definition works just as well,\nwhen $\\Simplex$ is replaced by any (let's say small) category $\\Delta$\nwhatever. On the other hand, it is immediate that for a functor $M\\to\nN$ as above, induced by a functor $A\\to B$, for two maps in $M$, any\nelementary homotopy between them gives rise to an elementary homotopy\nof their images in $N$ -- which is just the well-known fact (in case\n$\\Delta=\\Simplex$, $I=\\Simplex_1$) that $M\\to N$ is compatible with\nsimplicial homotopy notions.\n\nIn order to fit this into the general framework of section\n\\ref{sec:51}, let's remark that if $A$ is a full subcategory of a\ncategory $A'$, then for a pair of maps in $M$, the elementary\n\\bI-homotopies between these are the same as when considering the\ngiven maps as maps in $M'=\\bHom(\\Delta\\op,A')$, in which $M$ is embedded\nas a full subcategory. Now, any (small, say) category $A$ can be\nembedded canonically into $A'=\\Ahat$ as a full subcategory, and any\nfunctor\n\\[f:A\\to B\\]\nembeds in the corresponding functor\n\\[f_!:\\Ahat\\to\\Bhat,\\]\nhence the functor\n\\[\\varphi:M\\to N\\]\nembeds in the corresponding functor\n\\[\\varphi':M'\\to N', \\quad M'=\\bHom(\\Delta\\op,\\Ahat),\nN'=\\bHom(\\Delta\\op,\\Bhat).\\]\nAs \\Ahat, \\Bhat{} satisfy the required exactness properties, it\nfollows that the \\bI-homotopy notions in $M',N'$ can be interpreted in\nterms of the notions of section \\ref{sec:51}, with respect to $\\bI_A$\nand $\\bI_B$, defined now as (componentwise) constant objects of\n\\Ahat{} and \\Bhat{} respectively. Still, $f_!$ commutes to finite\nproducts only if $f$ does, so we are still left with explaining why\n$M'\\to N'$ is well-behaved with respect to \\bI-homotopy\nnotions. Equivalently, we need only see this in the case of\n\\eqref{eq:88.2} $M\\to N$, when $A$ and $B$ are supposed to have the\nrequired exactness properties to allow for the interpretation given\nabove of the \\bI-homotopy notions in terms of the formalism of section\n\\ref{sec:51}, and when moreover $f$ (as $f_!$ above)\\pspage{299}\ncommutes with sums. This now is readily expressed by the relations\n\\begin{align*}\n  &\\varphi'(\\bI_A) \\simeq \\bI_B , \\\\\n  &\\varphi'(\\bI_A\\times X) \\tosim \\varphi'(\\bI_A)\\times \\varphi'(X),\n\\end{align*}\ni.e., while $\\varphi'$ does \\emph{not} commute to finite products in\ngeneral, however it \\emph{does} commute to the products which enter in\nthe description of elementary homotopies (as these products can be\nexpressed in terms of direct sums in $A,B$, and $f$ commutes to\nthese).\n\nThese reflections suggest that the notions of homotopy interval\nstructures and contractibility structures may be generalized, in a way\nthat the underlying category need no longer be stable under finite\nproducts nor even admit a final object; and likewise, the notion of a\nmorphism of such structures may be generalized, without assuming that\nthe underlying functor should commute with finite products. The\nthought that this kind of generalization may be needed had already\noccurred before in these notes, in connection with the corresponding\nsituation about twenty five years ago, when the notion of a site was\ndeveloped. But at present, the extension doesn't seem urgent yet, and\nI better stop here this long digression!\n\nThe remaining questions possibly to deal with in part \\ref{ch:IV} are\nall concerned with modelizers. I'll try to be brief!\n\n\\namedlabel{q:88.5}{5)}\\enspace Consider an ``algebraic structure\ntype'', and the category $M$ of its set-theoretic realizations. I am\nlooking for a comprehensive set of sufficient conditions on $M$ to\nensure that $M$ is a ``canonical modelizer''. It seems natural to\nassume beforehand that in $M$ (where at any rate small direct and\ninverse limits must exist) internal $\\bHom$'s exist, and more\ngenerally, for $X,Y$ two objects over an object $S$ of $M$, that\n$\\bHom_S(X,Y)$ -- this implies that base change $S'\\to S$ in $M$\ncommutes with small direct limits and a fortiori, that direct sums are\nuniversal -- we may as well suppose them disjoint too. One feel quite\nwilling too to throw in the total $0$-connectedness assumption (cf.\\\nsection \\ref{sec:58}), and that every non-empty object has a section\nover the final object. This preliminary set of conditions on an\nalgebraic structure species is of course highly unusual, however it is\nsatisfied for must ``elementary'' algebraic structures (by which I\nmean $M\\equeq \\Ahat$ for some small category $A$), as well as for\n$n$-stacks or \\oo-Gr-stacks, for any $n$ between $0$ and \\oo. The hope\nnow is, in terms of these assumptions, to give a necessary and\nsufficient condition in order that a)\\enspace the ``canonical''\nhomotopy structure on $M$ be a contractibility structure, and moreover\nb)\\enspace the latter structure be ``modelizing'', by which we mean\nthat the\\pspage{300} associated \\scrWoo-asphericity structure (\\scrWoo{}\n= usual weak equivalences) be modelizing, which will imply that for\n\\emph{any} basic localizer \\scrW, the corresponding \\scrW-asphericity\nstructure is modelizing.\n\nEven if I don't look into this question now, it'll turn up soon enough\nin a similar shape, when it comes to prove modelizing properties for\ncategories of stacks of various kinds. The best we could hope for\nwould be a statement in terms of the category structure of $M$ alone,\nwith no assumption that $M$ be defined in terms of an algebraic\nstructure type. If I try to formulate anything by way of wishful\ntesting conjecture, what comes to mind is: is it enough that there\nshould exist a separating contractible interval? So the first I would\ntry to get an idea, is to see how to make a counterexample to\nthis\\ldots\n\n\\bigbreak\n\\presectionfill\\ondate{3.7.}\\par\n\n% 89\n\\hangsection[Digression (continued) on left exactness properties of\n$f_!$ \\dots]{Digression\n  \\texorpdfstring{\\textup(continued\\textup)}{(continued)} on left\n  exactness properties of \\texorpdfstring{$f_!$}{f!}\n  functors.}\\label{sec:89}%\nIn connection with the left exactness properties of a $f_!$ functor,\nconsidered three days ago (section \\ref{sec:85}), I have been befallen\nby some doubts whether any subcategory of \\Cat{} containing the\nsubcategory of standard simplices is strictly generating. I wrote\nthere (p.\\ \\ref{p:284}) that as this is true for $\\Simplex$ itself, it\n``follows a fortiori'' for any subcategory $A$ of \\Cat{} containing\n$\\Simplex$. Assuming $A$ to be full and denoting by $i$ the inclusion\nfunctor, this is known to be equivalent (cf.\\ remark \\ref{rem:85.2}\nsame page) to $i^*:\\Cat\\to\\Ahat$ being fully faithful, and in this\nform, it doesn't look so obvious that when this is true for one full\nsubcategory, $A_0$ say, it should be true for any larger one $A$. This\nthought had been lingering for a second while writing the ``a\nfortiori'' and I then brushed it aside, because of the formulation of\nbeing generating in terms of strict epimorphisms. Only the next day\ndid it occur to me that it is by no means clear that if a family of\nmaps $X_i\\to X$ in a category $M$ is strictly epimorphic, any larger\nfamily with same target $X$ should be ``a fortiori'' strictly\nepimorphic too -- the ``a fortiori'' is known to apply only in the\ncase of the similar notions of epimorphic, or universally strictly\nepimorphic, families of maps. After a little perplexity, I found the\nsituation was saved, in the case I was interested in, through the fact\nthat it was known from Giraud's article on\ndescent\\scrcomment{\\textcite{Giraud1964}} (Bull.\\ Soc.\\ Math.\\ France,\nMémoire 2, 1964, prop.\\ 2.5, p.\\ 28) that $\\Simplex$ and even the\nsmaller subcategory of simplices of dimension $\\le 2$, is\neven\\pspage{301} generating by ``\\emph{universally} strict\nepimorphisms'', a notion which is stable under enlargement of the\nfamily of maps, as recalled above. Thus, the statement made on p.\\\n\\ref{p:284} does hold true. And I just checked today that, while this\nstability property by enlargement is surely not always true for a\nfamily of maps which is strictly epimorphic, however, it \\emph{is}\ntrue that if a full subcategory $A_0$ of a category $M$ is generating\nby strict epimorphisms (or, as we'll say, is ``strictly generating''),\nthen so is any larger full subcategory $A$. This is seen by an easy\ndirect argument, in terms of the initial definition, as meaning that\nfor any object $X$ in $M$, the family of maps $a_i\\to X$ with target\n$X$ and source in the given subcategory ($A$ say) should be strictly\nepimorphic. (For\\scrcomment{\\textcite{SGA4vol1}} the definition of\ncommon variants of the notion of epimorphism, see the ``Glossaire'' at\nthe end of chapter 1, SGA~4, vol.~1.)\n\nIt occurred also to me that (as suspected in remark \\ref{rem:85.3},\nloc.\\ cit.) the functor\n\\[i_!: \\Simplexhat\\to\\Cat\\]\ncoming from the inclusion functor $i:\\Simplex\\to\\Cat$ is \\emph{not}\nleft exact (for another reason though than first contemplated), namely\nbecause \\Cat{} is known \\emph{not to be a topos} (for instance, an\nepimorphism need not be \\emph{strict} (or, what amounts here to the\nsame, \\emph{effective}) -- as stated in the cited result of\nGiraud). Indeed, we have the following\n\\begin{proposition}[which should belong to section \\ref{sec:85}!]\n  Let $M$ be a \\scrU-category stable under small direct limits, $A$ a\n  small full subcategory, $i:A\\to M$ the inclusion functor, hence a\n  functor\n  \\[i_!:\\Ahat\\to M.\\]\n  If $A$ is strictly generating \\textup(i.e., $i^*:M\\to\\Ahat$ fully\n  faithful\\textup), then $i_!$ is left exact if{f} $M$ is a topos.\n\\end{proposition}\n\nIndeed, the inclusion functor into \\Ahat{} of $M'$, the essential\nimage of $i^*$ in \\Ahat, admits a left adjoint ($i_!$ essentially). By\nthe criterion of Giraud, left exactness of this adjoint, or\nequivalently of $i_!$, means that $M'$ is the category of sheaves on\n$A$ for a suitable site structure on $A$, qed.\n\\begin{corollary}\n  If $M$ is \\emph{not} a topos, then $i_!$ does \\emph{not} commute to\n  fibered products in \\Ahat{} of diagrams of the type\n  \\begin{equation}\n    \\label{eq:89.star}\n    \\begin{tabular}{@{}c@{}}\n      \\begin{tikzcd}[baseline=(O.base),column sep=tiny,row sep=small]\n        b\\ar[dr] & & c\\ar[dl] \\\\ & |[alias=O]| F &\n      \\end{tikzcd},\n    \\end{tabular}\\tag{*}\n  \\end{equation}\n  with $b,c$ in $A$ and $F$ in \\Ahat,\\pspage{302} while it does\n  commute to finite products, and to fibered products of any two\n  objects of \\Ahat{} over an object of $A$\\kern1pt.\n\\end{corollary}\n\nThe ``while'' comes from prop.\\ \\ref{prop:85.1} and prop.\\\n\\ref{prop:85.2} of section \\ref{sec:85}, which imply too that, if $M$ is\nstrictly generating and whether or not $M$ is a topos, left exactness\nof $i_!$ is equivalent with commutation to fibered products of the\ndiagrams \\eqref{eq:89.star}. Hence the corollary.\n\nThis corollary answers also the perplexity raised in remark\n\\ref{rem:85.1} (p.\\ \\ref{p:283}), as to a hypothetical sharper version\nof part \\ref{it:85.prop1.b}, concerning fibered products. As\nanticipated there, it turns out that this sharper version is not\nvalid, -- not without additional assumptions at any rate.\n\n% 90\n\\hangsection[Review of questions (continued): 6) Existence of test\n\\dots]{Review of questions\n  \\texorpdfstring{\\textup(continued\\textup)}{(continued)}:\n  \\texorpdfstring{\\textup{6)}}{6)} Existence of test functors and\n  related questions. Digression on strictly generating\n  subcategories.}\\label{sec:90}%\nAfter this digression on exactness properties of $f_!$ functors, let's\ncome back to the review of those questions not yet dealt with, which\nseem more or less to belong to the present part \\ref{ch:IV} of the\nnotes. We had stopped two days ago with the question \\ref{q:88.5} of\nfinding some simple characterization of canonical modelizers,\ncomparable maybe in simplicity to the characterization we found for\ntest categories (in part \\ref{ch:II}). This question may well turn out\nto be related to the following one.\n\n\\namedlabel{q:90.6}{6)}\\enspace This is the question of finding handy\nexistence theorems for test functors, whereas so far our attention to\ntest functors had been turned towards a thorough understanding of the\nvery notion of a test functor and its variants. I have the feeling\nthat, after the reflections of sections \\ref{sec:78} and \\ref{sec:86}\nnotably, the notion in itself is about understood now, so that time is\ngetting ripe for asking for existence theorems. As all modelizers we\nhave been meeting so far were associated to asphericity structures, it\nseems reasonable to restrict to these, namely to the case of a given\nmodelizing asphericity structure\n\\[(M,M\\suba),\\]\nand, if need be, even restrict to the case when this structure is\nassociated to a contractibility structure $M\\subc$. We suppose given\nmoreover a test category $A$, which we may (if needed) assume to be\nstrict even, or even a contractor (i.e., the objects of $A$ in \\Ahat{}\nare moreover contractible, for the homotopy interval structure in\n\\Ahat{} defined by all intervals coming from $A$). The question then\nis whether there exists a test functor\n\\[A\\to M.\\]\nThis (under the assumptions made) just reduces to the existence\nof\\pspage{303} a functor which be $M\\suba$-\\scrW-aspheric. Here,\n\\scrW{} is a given basic localizer, with respect to which we got an\nasphericity structure. The most important case for us surely is the\none when $\\scrW=\\scrWoo$, namely usual weak equivalence. It is\nimmediate indeed that an $M\\suba$-\\scrW-aspheric functor is equally\naspheric for the corresponding $\\scrW'$-asphericity structure of $M$,\nfor any basic localizer $\\scrW'\\supset\\scrW$. Thus, if we get an\naspheric functor for \\scrWoo, the finest basic localizer of all, we\nget ipso facto an aspheric functor for any basic localizer\n\\scrW. (Note also that if an asphericity structure is modelizing for a\ngiven \\scrW, the corresponding $\\scrW'$-structure is modelizing too,\nfor any $\\scrW'\\supset\\scrW$; and the analogous fact holds for the\nnotion of a test category -- namely a \\scrW-test category is also a\n$\\scrW'$-test category, and similarly for total asphericity of \\Ahat{}\nand hence for the condition of being a \\emph{strict} test category.)\n\nIn case $M$ is even endowed with a contractibility structure, we will\nbe interested, more specifically still, in aspheric functors factoring\nnot only through $M\\suba$, but even through $M\\subc$:\n\\[ i:A\\to M\\subc,\\]\nwhile replacing the asphericity requirement on this functor, by the\nstronger one that for any $x$ in $M\\subc$, the object $i^*(x)$ in\n\\Ahat{} be \\emph{contractible} (for the homotopy structure in \\Ahat{}\ndefined by homotopy intervals coming from objects in $A$, say). In\nother words, we are interested in the question of existence of\n\\emph{bimorphisms} of contractibility structures (in the sense of\nsection \\ref{sec:86}) from $(M,M\\subc)$ to $(\\Ahat,\\Ahatc)$. It may be\nnoted that in both cases (working with asphericity structures or with\nthe contractibility structures instead), in this existence question,\nwe may altogether forget $M$ itself, and consider it as an existence\nquestion for functors from $A$ into either $M\\suba$, or $M\\subc$, with\nthe property that for any object $x$ in the target category $M\\suba$\nor $M\\subc$, the object $i^*(x)$ in \\Ahat{} be either aspheric, or\ncontractible. In the second case, we may even restrict $x$ to be in\nany given subcategory $C$ of $M\\subc$ generating the contractibility\nstructure -- and in the cases met with so far, we can find such a $C$\nreduced to just one object $I$. In the case of asphericity structures,\nthe same holds when taking for $C$ a subcategory generating the\nasphericity structure, provided however $C$ contains the image of $A$\nby $i$ (which gives little hope to have $C$ restricted to just one\nelement!)\n\nThe interest of finding criteria for existence of \\scrW-aspheric\nor\\pspage{304} or more stringently still of ``c-\\emph{aspheric\n  functor}'' (as we may call them) is rather evident, as it gives a\nway, via $i^*$, for any homotopy type described in terms of a\n``model'' $x$ in $M$, to find a corresponding model $i^*(x)$ in\n\\Ahat. The situation would be more satisfactory still if we could find\nthe test functor $i$ such that the corresponding functor\n\\begin{equation}\n  \\label{eq:90.1}\n  i_!:\\Ahat\\to M\\tag{1}\n\\end{equation}\nbe modelizing too (assuming $M$ to be stable under small direct\nlimits, so that $i_!$ is defined as the left adjoint of\n\\begin{equation}\n  \\label{eq:90.2}\n  i^*:M\\to\\Ahat\\quad\\text{.)}\\tag{2}\n\\end{equation}\nIn this case, for a homotopy type described by a model $K$ in \\Ahat,\n$i_!(K)$ gives a description of the same by a model in $M$.\n\nMaybe we should remember though that even if we do not know about any\ntest functor from $A$ to $M$, still we always can find in three steps\na modelizing functor\n\\[M\\to\\Ahat,\\]\nnamely a composition\n\\begin{equation}\n  \\label{eq:90.star}\n  M \\xrightarrow{j^*} \\Bhat \\xrightarrow{i_B}\n  \\Cat\\xrightarrow{j_A=i_A^*} \\Ahat,\\tag{*}\n\\end{equation}\nwhere $j:B\\to M$ is an $M\\suba$-aspheric functor from an auxiliary\nsmall category, which we may assume to be a test category, by a mild\nextra assumption on $M$ (cf.\\ cor.\\ \\ref{cor:79.3} p.\\\n\\ref{p:253}). The modelizing functor we thus get has the disadvantage\nof not being left exact, whereas the looked-for functor $i^*$ commutes\nto small inverse limits. Still, the composition \\eqref{eq:90.star} is\npretty near to being left exact, it commutes to fibered products\n(because $i_B$ does) which is the next best -- we can view it as a\nleft-exact functor from $M$ to $\\Ahat_{/E}$, where $E$ is the image in\n\\Ahat{} of the final object of $M$ (assuming $e_M$ exists).\n\nThere is another advantage still of having a test functor $i:A\\to M$,\nrather than merely using \\eqref{eq:90.star}, namely it allows us to\n``enrich'' the category structure of $M$, in such a way as to get\n``external $\\Hom$'s'' of objects of $M$, with ``values in \\Ahat'', by\ndefining, for $x,y$ in $M$, the object $\\bHom(A)(x,y)$ of \\Ahat{} as\n\\begin{equation}\n  \\label{eq:90.3}\n  \\bHom(A)(x,y) = \\bigl\\{ a\\mapsto\\Hom_M(i(a)\\times x,y)\\bigr\\}.\n  \\tag{3}\n\\end{equation}\nSuch enriched structure, when $A=\\Simplex$, plays an important part in\nthe second part of Quillen's treatment of homotopical algebra, under\nthe name of (semi-)simplicial categories, especially with the notion\nof (semi-)simplicial model categories, which looks quite handy\nindeed.\\pspage{305} We should of course define composition of the\n$\\bHom(A)$'s, as required too in Quillen's set-up. This is done by\nrelating the $\\bHom(A)$'s to the well-known internal $\\bHom$'s in\n$M\\uphat$ -- which will show at the same time that for formula\n\\eqref{eq:90.3} to make sense, we do not really have to assume $M$ be\nstable under binary products, as we can interpret the products\n$i(a)\\times x$ as being taken in $M\\uphat$, as well as the $\\Hom$, so\nas to get\n\\[\\Hom_{M\\uphat}(i(a)\\times x,y) \\simeq \\Hom_{M\\uphat}(i(a),\n\\bHom_{M\\uphat}(x,y)),\\]\nhence\n\\begin{equation}\n  \\label{eq:90.4}\n  \\bHom(A)(x,y)\\simeq i^*(\\bHom_{M\\uphat}(x,y)),\\tag{4}\n\\end{equation}\nwhere $i^*$ in the right hand side is interpreted as a functor\n\\[ i^*:M\\uphat\\to\\Ahat,\\]\nrather than $M\\to\\Ahat$. (I leave to the reader the task of enlarging\nthe basic universe, as need may be\\ldots) As $i^*$ commutes to\nproducts, the evident composition of the internal $\\bHom$'s in\n$M\\uphat$ gives rise to the looked-for composition of the\n$\\bHom(A)$'s, with the required associativity properties. Of course,\nin case $M$ is stable under binary products and $\\bHom$'s, which\napparently is going to be the case in all modelizing situations, there\nis no need in the interpretation \\eqref{eq:90.4} to introduce the\nprohibitively large $M\\uphat$, and we can work in $M$ throughout.\n\nThere is an important relation though on the external $\\bHom(A)$'s\nwhich we would like to be true for a satisfactory formalism, namely\n\\begin{equation}\n  \\label{eq:90.5}\n  \\Gamma_\\Ahat(\\bHom(A)(x,y)) \\fromsim \\Hom_M(x,y),\\tag{5}\n\\end{equation}\nwhere $\\Gamma_\\Ahat$ just means $\\Hom_\\Ahat(e_\\Ahat,\\dots)$. This is\nequivalent to the requirement\n\\begin{equation}\n  \\label{eq:90.6}\n  i_!(e_\\Ahat)\\simeq e_M\\tag{6}\n\\end{equation}\n(assuming a final object $e_M$ in $M$ to exist), or equivalently\n\\begin{equation}\n  \\label{eq:90.7}\n  i(e_A)\\simeq e_M\\tag{7}\n\\end{equation}\nif we assume moreover $e_A$ to exist. Thus, it will be natural to ask\nfor test functors satisfying the extra condition \\eqref{eq:90.5} or\n\\eqref{eq:90.6} -- and when trying to construct test functors in\nvarious situations (even without being aware of constructing test\nfunctors, as Mr~Jourdain\\scrcomment{the reference is of course to\n  Molière's \\emph{comédie-ballet},\n  \\href{https://en.wikipedia.org/wiki/Le_Bourgeois_gentilhomme}{Le\n    Bourgeois gentilhomme}} was ``doing prose without knowing\nit''\\ldots), the very first thing everybody has been doing\ninstinctively was to write down formula \\eqref{eq:90.7},\\pspage{306} I\nwould bet!\n\nThe motivation for wanting to find test functors being reasonably\nclear by now, what kind of existence theorems may we hope for? When\n$A$ is such a beautiful test category as $\\Simplex$, $\\Square$ or\n$\\Globe$, I would expect that for practically any $M$ endowed with a\nmodelizing contractibility structure say, under mild restrictions\n(such as the exactness assumptions which are natural in the modelizing\nstory), there should exist a test functor indeed. What I feel less\ndefinite about is whether it is reasonable to expect we can find $i$\neven such that $i_!$ be modelizing too, in which case we would expect\nof course that the pair of equivalences of categories\n\\begin{equation}\n  \\label{eq:90.8}\n  \\begin{tikzcd}[cramped,sep=small]\n    \\HotOf_A \\ar[r,shift left] & \\HotOf_M \\ar[l,shift left]\n  \\end{tikzcd}\\tag{8}\n\\end{equation}\ndefined in terms of $i_!$ and $i^*$ should be quasi-inverse to each\nother, and the adjunction maps deduced from those between the functors\n$i_!$ and $i^*$ themselves. This in turn is equivalent with the\nadjunction morphism\n\\begin{equation}\n  \\label{eq:90.9}\n  F\\to i^*i_!(F)\\tag{9}\n\\end{equation}\nbeing a weak equivalence, for any object $F$ in \\Ahat. A test functor\nsatisfying this exacting extra property merits a name of its own, we\nmay call it a \\emph{perfect test functor} (or a \\emph{perfect aspheric\n  functor}, when not making any modelizing assumptions on $A$ or\n$M$). Thus, the existence problem of finding test functors can be\nsharpened to the one of finding perfect ones. Remember though that the\nmost familiar test functor of all (besides the geometric realization\nfunctor $\\Simplex\\to\\Spaces$, namely the inclusion\n\\begin{equation}\n  \\label{eq:90.10}\n  i:\\Simplex\\to\\Cat\\tag{10}\n\\end{equation}\ngiving rise to the nerve functor (introduced for the first time, I\nbelieve, in a Bourbaki talk of mine, on passage to quotient by a\npreequivalence relation in the category of schemes\\ldots), is\n\\emph{not} perfect. The most natural perfect test functor from\n$\\Simplex$ into \\Cat, more generally from any weak test category $A$\ninto \\Cat, is of course $i_A$ -- the functor indeed which has been\ndominating the whole modelizing picture in our reflections from the\nstart. In the case of $A=\\Simplex$, Thomason discovered another\nperfect test functor, conceptually less simple surely, namely\n$i_!\\Sd^2$, where $\\Sd$ is the ``barycentric subdivision functor''.\nI suspect there must be an impressive bunch of perfect test functors\nfrom $\\Simplex$ with values in more or less any given modelizer, not\nonly the basic one -- and the question here is to get a clear picture\nof\\pspage{307} how to get them, and the same of course for test\nfunctors which need not be perfect, including \\eqref{eq:90.10}.\n\nNext question then would be to see whether the existence theorems we\nmay get for $\\Simplex$, or its siblings $\\Square$ and $\\Globe$ and the\nlike, still hold true for a more or less arbitrary test category, or\ncontractor. If so, this would be a very strong confirmation of the\nfeeling which has been prompting the reflections in part \\ref{ch:II},\nnamely that for the purpose of having ``all-purpose''-models for\nhomotopy types (insofar as this is feasible), any strict test\ncategory, or any contractor at any rate, is just as good as simplices\nor cubes, which people have kept working with for the last twenty-five\nyears. If not, it will be quite interesting indeed to come a grasp of\nwhat the relevant extra features of $\\Simplex$ and the like are, and\nhow restrictive they are.\n\nI doubt I will dive into these questions, still less come to a clear\npicture, in the present part of the notes. Still, before leaving the\ntopic now, I would like to write down some hints I came upon while\ndoing my scratchwork on homotopy properties of \\Ahat{}\ncategories. When looking for functors\n\\[A\\to M\\]\nhaving some specified properties (such as being a test functor, or a\nperfect one, etc.), we may view this question as meaning that we are\nlooking for an object with specified properties in the category\n\\[M^A =\\bHom(A,M).\\]\nPresumably, this category is endowed with an asphericity or\ncontractibility structure if $M$ is (as we assume), presumably even a\nmodelizing one. This reminds me that as far as the notion of weak\nequivalence goes, there may be even several non-equivalent ways of\nfinding such structure on $M^A$, one being modelizing, whereas\nanother, more useful one in some respects, is not. Thus, if $M$ is of\nthe type \\Bhat, we may rewrite $M^A$ as\n\\[ M^A \\equeq (A\\op\\times B)\\uphat \\equeq P\\uphat;\\]\nhence we get the weak equivalence notion coming from $P\\uphat$,\ndisregarding its product structure, which is modelizing indeed if $B$\nis a test category and $A$ aspheric, hence $A\\op\\times B$ a test\ncategory. The structure which should be of more relevance though for\nour purpose should be a considerably finer one (namely with a smaller\nset of weak equivalences), which we may\\pspage{308} visualize best\nmaybe by writing\n\\[M^A=(\\bHom(A\\op,M\\op))\\op,\\]\ni.e., interpreting the dual of $M^A$ as the category of $A$-objects of\n$M\\op$, for instance (if $A=\\Simplex$) as the dual of the category of\nss~objects of $M\\op$. Now, Quillen has given handy conditions, in\nterms of projectives of $M\\op=N$, namely in terms of injectives of\n$M$, for the category $\\bHom(\\Simplexop,N)$ of ss~objects of $N$ to\nbe a closed model category -- hence the dual category $M^A$ will turn\nout as a closed model category too, under suitable conditions\ninvolving existence of injective objects in $M$. These conditions are\nsatisfied for instance when $M$ is a topos, and notably when $M$ is of\nthe type \\Bhat{} -- quite an interesting particular case indeed!\nAssuming that $M$ is stable under both types of limits, so is $M^A$,\nhence there is an initial and final object, and according to Quillen's\nfactorization axiom, the map from the former to the latter can be\nfactored through an object\n\\[\\text{$F$ in $M^A$,}\\quad\\text{i.e.,}\\quad F:A\\to M,\\]\nwhich is \\emph{cofibering}, and such that $F\\to e$ is a \\emph{trivial\n  fibration}. The idea is that these conditions mean more or less, at\nany rate imply, that $F$ is a test functor.\n\nI hit upon this ``way out'' while trying to construct test functors\nfrom $\\Simplex$ to any elementary modelizer \\Bhat, in order to try and\ncheck that \\Bhat{} is a (semi)simplicial model category in the sense\nof Quillen. The intuitive idea of constructing inductively the\ncomponents $F_n$ of $F$ was simple enough, still I got stuck in some\nmessiness and did not try to push through this way, all the less as\nthis naive approach had no chance of generalizing to the case of a\nmore or less general test category $A$. Of course, for the time being\nQuillen's theorems, about certain categories $\\bHom(A\\op,N)$ being\nclosed model categories, is equally restricted to the case when\n$A=\\Simplex$, which looks as usual like a rather arbitrary\nassumption. Thus, to ``test'' whether the feeling about \\emph{any}\ntest category more or less being ``just as good'' as $\\Simplex$, a\nsecond point would be to see whether Quillen's theorems extend, which\npresumably is going to be very close to the first point I raised.\n\nI take this occasion to raise a third point -- where there is no\nreason to restrict to an $M$ which is modelizing (neither was there\nsuch reason before, when phrasing everything in terms of aspheric or\nc-aspheric functors, rather than test functors\\ldots). Namely,\nassuming as\\pspage{309} above that for any test category or contractor\n$A$, $M^A$ or $M^{A\\op}$ can be endowed with an asphericity structure\nor a closed model structure, or at any rate with a set of weak\nequivalences, hence a localization or corresponding ``homotopy\ncategory''. What one would expect now is that up to (canonical)\nequivalence, the latter does not depend upon the choice of $A$, and\nhence is the same for arbitrary $A$ as when using $\\Simplex$, i.e.,\nsimplices. This should be true at any rate for $M^{A\\op}$ and when $M$\nis a topos -- which means that \\emph{Illusie's derived category\n  $\\mathrm D_\\bullet(X)$ of the category of semisimplicial sheaves on\n  a topos $X$, could be constructed by using, instead of ss~objects,\n  $A$-objects of the category of sheaves on $X$, where $A$ is any test\n  category.} This should be one of the main points to settle in part\n\\ref{ch:VII} of the notes.\n\nThere is a slight discrepancy though between the first point, about\nexistence of test functors with values in $M$, depending on a given\nasphericity or contractibility structure of $M$, and the second and\nthe third, which seem to depend only on the category structure of\n$M$. This is further evidence that the set of questions raised here is\nstill far from being clear in my mind yet. Stating them now, however\nconfusingly, is a first step towards clarification!\n\n\\bigbreak\n\\presectionfill\\ondate{4.7.}\\par\n\nJust still two comments about the existence questions for test\nfunctors, before going over to the next questions in our present\nreview. One is that for given $A$, to prove that for rather general\nmodelizing $M$ there exists a test functor from $A$ to $M$, we are\nreduced to the case when $M$ is of the type \\Bhat, where $B$ is a test\ncategory -- namely, it is enough to take a $B$ such that there exists\na test functor $B\\to M$. If we can even find a perfect test functor\nfrom some $B$ to $M$, then likewise the existence question for perfect\ntest functors from $A$ to $M$ is reduced to the case when\n$M=\\Bhat$. These comments may be useful for applying to the situation\nQuillen's model theory, as envisioned on the previous page -- as his\ncriteria for $\\bHom(\\Simplexop,N)$ to be a closed model category\napply when $N$ is the dual of a topos, for instance the dual of\n\\Bhat. The second comment is about Thomason's result concerning the\nstandard inclusion\n\\[i:\\Simplex\\hookrightarrow \\Cat,\\]\nwhich can be expressed by saying that, although $i$ itself is not a\n\\emph{perfect} test functor, however, for any integer $n\\ge2$, the\ncomposition\\pspage{310}\n\\[i_n=i_!\\Sd^n \\alpha: \\Simplex\\to\\Simplexhat\\to\\Simplexhat\\to\\Cat\\]\nis a perfect test functor, where $\\alpha:\\Simplex\\to\\Simplexhat$ is\nthe canonical inclusion. It is tempting to surmise that this result is\nnot special to $i$ alone, but that it holds for a large class, if not\nall, test functors from $\\Simplex$ to asphericity or contractibility\nmodelizers. Here, $\\Sd^n$ denotes the $n$'th iterate of the\nbarycentric subdivision functor $\\Sd$ (following now the notation in\nThomason's paper, which presumably is standard, while I have been\nusing ``Bar'' in part \\ref{ch:II} of the notes). Presumably, functors\nanalogous to $\\Sd$ can be defined in any elementary modelizer \\Ahat,\nas suggested by the natural constructions arising in connection with\nthe factorization property for a closed model structure on\n\\Ahat. Thus, possibly there is a general method in view for deducing\nperfect test functors from ordinary ones. However, it definitely seems\nto me that the natural place for these existence questions is in part\n\\ref{ch:V} of the notes, as they seem intimately related to an\nunderstanding of the homotopy structures of elementary modelizers, and\nmore specifically to the closed model structures to which such\nmodelizers give rise in various ways.\n\n\\starsbreak\n\nBefore proceeding, I would like to state still another afterthought to\nthe reflections of section \\ref{sec:89}, about strictly generating\nsubcategories of a category $M$. I recall that a family of arrows in\n$M$ with same target $X$\n\\[u_i:X_i\\to X\\]\nis called \\emph{strictly epimorphic}, if for every object $Y$ of $M$,\nthe corresponding map\n\\begin{equation}\n  \\label{eq:90.starbis}\n  \\Hom(X,Y) \\to \\prod_i\\Hom(X_i,Y)\\tag{*}\n\\end{equation}\nis injective (which is expressed by saying that the family $(u_i)$ is\n\\emph{epimorphic}), and if \\emph{moreover} the following obviously\nnecessary condition for an element $(f_i)$ of the product set of\n\\eqref{eq:90.starbis} to be in the image of the map \\eqref{eq:90.starbis},\nis also sufficient:\n\\begin{description}\n\\item[\\namedlabel{cond:90.Comp}{(Comp)}]\n  For any two indices $i,j$ (possibly equal) and any commutative\n  square\n  \\[\\begin{tikzcd}[sep=tiny]\n    & T\\ar[dl,\"v_i\"']\\ar[dr,\"v_j\"] & \\\\\n    X_i\\ar[dr,\"u_i\"'] & & X_j\\ar[dl,\"u_j\"] \\\\\n    & X &\n  \\end{tikzcd}\\]\n  in $M$, the relation $f_iv_i=f_jv_j$ holds.\n\\end{description}\nIt is immediate that the condition for $(u_i)$ to be strictly\nepimorphic\\pspage{311} depends only on the \\emph{sieve} $X_0$ of $X$\nin $M$ (namely, the subobject of $X$, viewed as an object of\n$M\\uphat$) generated by the $u_i$'s -- we'll say also that this\n\\emph{sieve is strictly epimorphic}. One should beware that this does\nnot mean of course that $X_0\\to X$ is epimorphic in $M\\uphat$ (which\nwould imply $X_0=X$, i.e., that one of the $u_i$'s admits a section,\ni.e., a right inverse); nor is it true that if a sieve is strictly\nepimorphic, a large one should be so too -- which means that when\nadding more arrows to a strictly epimorphic family, the family need\nnot stay str.\\ ep.\n\nWe'll say that the family $(u_i)$ is \\emph{universally strictly\n  epimorphic} if it is strictly epimorphic, i.e., the corresponding\nsieve $X_0$ is, and if the latter remains so by arbitrary base change\n$X'\\to X$ in $M$, i.e., if the corresponding sieve $X'_0$ of $X'$ is\nstrictly epimorphic too. If the fibered products\n\\[X'_i = X_i\\times_X X'\\]\nexist in $M$, this condition also means that the corresponding family\nof maps\n\\[ u'_i:X'_i\\to X'\\]\nis strictly epimorphic. The condition that $(u_i)$ be univ.\\ str.\\\nepimorphic again depends only on the generated sieve, it is moreover\n\\emph{stable under base change}, and equally \\emph{stable under adding\n  new arrows}, i.e., replacing a sieve in $X$ by a larger one.\n\nIt should be noted that if the fibered products $X_i\\times_X X_j$\nexist in $M$, then the compatibility condition \\ref{cond:90.Comp}\nabove is equivalent to the one obtained by restricting to\n\\[T = X_i\\times_X X_j,\\]\nwith $v_i$ and $v_j$ the two projections.\n\nAssume the indices $i$ are objects of a category $I$, and the $X_i$\nare the values of a functor\n\\[I\\to M,\\]\nand that the family of arrows $(u_i)$ turns $X$ into the direct limit\nin $M$ of the $X_i$:\n\\[X=\\varinjlim_i X_i,\\]\nthen it follows immediately that the family $(u_j)$ is strictly\nepimorphic.\n\nAfter these terminological preliminaries, we're ready to give\nthe\\pspage{312} following useful statement, which is lacking in\nSGA~4\\scrcomment{\\textcite{SGA4vol1}} \nChap.~I (compare loc.\\ cit.\\ prop.\\ 7.2, page 47, giving part of the\nstory):\n\\begin{proposition}\n  Let $M$ be a \\scrU-category, $A$ a small full subcategory, $i:A\\to\n  M$ the inclusion functor, hence a functor\n  \\[i^*:M\\to \\Ahat.\\]\n  For any object $X$ of $M$, we consider the family $F_X$ of all\n  arrows in $M$ with target $X$, source in $A$\\kern1pt. The following\n  conditions are equivalent:\n  \\begin{enumerate}[label=(\\roman*),font=\\normalfont]\n  \\item\\label{it:90.i}\n    For any $X$ in $M$, the family $F_X$ is strictly epimorphic.\n  \\item\\label{it:90.ii}\n    For any $X$ in $M$, the family $F_X$ is universally strictly\n    epimorphic.\n  \\item\\label{it:90.iii}\n    For any $X$ in $M$, $F_X$ turns $X$ into a direct limit of the\n    composition functor $A_{/X}\\to A\\to M$, i.e.,\n    \\[X \\fromsim \\varinjlim_{A_{/X}} a.\\]\n  \\item\\label{it:90.iv}\n    The functor $i^*$ is fully faithful.\n  \\end{enumerate}\n\\end{proposition}\n\nProof left to the reader (who may consult loc.\\ cit.\\ for\n\\ref{it:90.i} $\\Rightarrow$ \\ref{it:90.iii} $\\Leftrightarrow$\n\\ref{it:90.iv}, so that only \\ref{it:90.i} $\\Rightarrow$\n\\ref{it:90.ii} is left to prove).\n\\begin{definition}\n  When the equivalent conditions above are satisfied, we'll say that\n  $A$ is a \\emph{strictly generating} subcategory of $M$.\n\\end{definition}\n\nNB\\enspace The notion makes sense too without assuming $A$ to be\nsmall, nor $M$ to be a \\scrU-category, by passing to a larger universe\n(it is immediate for \\ref{it:90.i} or \\ref{it:90.iii} that the\ncondition does not depend on the choice of the universe.)\n\\begin{corollary}\n  If $A$ is strictly generating in $M$, then so is any larger full\n  subcategory $B$.\n\\end{corollary}\n\nThis is clear by criterion \\ref{it:90.ii} (whereas it isn't by any one\nof the other two criteria!).\n\n% 91\n\\hangsection[Review of questions (continued): 7) Homotopy types of\n\\dots]{Review of questions \\texorpdfstring{\\textup(continued\\textup):\n    \\textup{7)}}{(continued): 7)} Homotopy types of finite type,\n  \\texorpdfstring{\\textup{8)}}{8)} test categories with boundary\n  operations, \\texorpdfstring{\\textup{9)}}{9)}\n  miscellaneous.}\\label{sec:91}%\nI see three more questions to review -- presumably they will be a lot\nshorter than the last!\n\n\\namedlabel{q:91.7}{7)}\\enspace\\textbf{Description of homotopy types\n  ``of finite type'',} in terms of an elementary modelizer \\Ahat. In\nterms of the modelizer \\Spaces, a natural finiteness condition on a\nhomotopy type is that it may be described (up\\pspage{313} to\nisomorphism) as the homotopy type of a \\emph{space admitting a finite\n  triangulation}. In terms of ss~sets, i.e., of the modelizer\n\\Simplexhat, the natural finiteness condition, suggested by the\nalgebraic formalism, is that the homotopy type be isomorphic to one\ndefined by an object \\emph{``of finite presentation'' in} \\Simplexhat,\nnamely one which is a direct limit of a \\emph{finite} diagram in\n\\Simplexhat, made up with simplices, i.e., coming from a diagram in\n$\\Simplex$. It is clear that the first finiteness condition implies\nthe second, by using a total order on the set of vertices of the\ntriangulation. The converse shouldn't be hard either, using an\ninduction argument on the number of simplices occurring in the\ndiagram, and using the fact that any quotient object in \\Simplexhat{}\nof a simplex is again a simplex, hence also a subobject of a simplex\nis a union of subsimplices; from this should follow by induction that\nthe geometric realization of a ss~set of finite presentation is\nendowed with a natural compact \\emph{piecewise linear structure}, and\nhence can be finitely triangulated. Presumably, one can even find a\ncanonical triangulation, using twofold barycentric subdivision $\\Sd^2$\n(again!) on any simplex. All this is surely standard knowledge, and I\ndon't feel like diving into technicalities on this matter, unless I am\nforced to.\n\nIf we start with an arbitrary test category $A$, the notion of an\nobject of finite presentation in \\Ahat{} still makes sense. Indeed, in\nany category $M$, stable under filtering small direct limits, we may\ndefine objects of finite presentation as those for which the\ncorresponding \\emph{covariant} functor\n\\[Y\\mapsto \\Hom(X,Y)\\]\ncommutes to filtering direct limits. If $M$ is stable under some type\nof finite direct limits, say under any finite direct limits, then so\nis the full subcategory $M\\subfp$ of objects of finite presentation of\n$M$. In the case when $M=\\Ahat$, $A$ any small category, it is obvious\nthat objects of $A$, and hence finite direct limits of such, are of\nfinite presentation, and it is not difficult to show that the converse\nequally holds. As a matter of fact $\\Ahatfp$ \\emph{can be viewed as\n  the solution of the $2$-universal problem of ``adding finite direct\n  limits to $A$''}.\n\nComing back to the case when $A$ is a test category, and hence \\Ahat{}\nis modelizing, one may ask for conditions upon $A$ which ensure that\nthe homotopy types of finite presentation are exactly those isomorphic\nto the homotopy types defined by objects of \\Ahatfp. One expects that\nsome stringent\\pspage{314} extra condition is needed on $A$ to ensure\nthis. To see this, let's take a finite group $G$, and an aspherical\ntopological space $E_G$ upon which $G$ operates freely, with quotient\n$B_G$, a classifying space of $G$. If $G\\ne1$, the homotopy type of\n$B_G$ isn't of finite type, because $B_G$ has non-vanishing cohomology\ngroups in arbitrarily high dimensions, as well known. We could\ntranspose the following construction in either \\Cat{} or \\Simplexhat{}\nsay, but we may as well work in the modelizer $M=\\Spaces$, and take\nany small full subcategory $A$ of $M$, containing the unit interval\nbut not the empty space, and stable under finite products -- which\nimplies that $A$ is a strict test category. We'll take $A$ large\nenough to contain $E_G$, and small enough to be made up with aspheric\nspaces, hence the inclusion functor\n\\[i: A\\to\\Spaces\\]\nis a test functor. Now consider the quotient object \\emph{in} \\Ahat\n\\[F = E_G / G,\\]\ni.e., the presheaf on $A$\n\\[ F : T\\mapsto \\Hom(T,E_G)/G \\simeq \\Hom(T,B_G),\\]\nwhere the last isomorphism comes from the fact that the object $T$ of\n$A$ is aspheric and hence $1$-connected. Thus, we get\n\\[F\\simeq i^*(B_G),\\]\nhence the homotopy type defined by $F$ is the homotopy type of $B_G$,\nwhich is not of finite type, despite the fact that $F$ is of finite\npresentation.\n\nIn order to ensure that the homotopy type defined by any object in\n\\Ahatfp{} be of finite type, it may be useful perhaps to make on $A$\nthe assumption that any quotient in \\Ahat{} of an object in $A$ is\nisomorphic to an object in $A$, and that the set of all subobjects in\n\\Ahat{} of an object $a$ in $A$ (i.e., the set of all sieves on $a$)\nis finite -- possibly too that for any two objects $a$ and $b$ of $A$,\n$\\Hom(a,b)$ is finite. As for the opposite inclusion, namely that any\nhomotopy type of finite type can be described by an object of \\Ahatfp,\nthis would follow from the existence of a \\emph{perfect} test functor\nfrom $\\Simplex$ into \\Ahat, factoring through\\pspage{315}\n\\Ahatfp. Thus, the present question about finiteness conditions, seems\nto be related (possibly) to the previous one about existence of\nvarious types of test functors.\n\nThe condition for a strict test category $A$ we are looking at is\nsurely satisfied, besides $\\Simplex$, by the cubical and hemispherical\ntest categories $\\Square$ and $\\Globe$, and surely also by any finite\nproducts of these. I add this comment, of course, in order to ``push\nthrough'' the point that not any more with respect to finiteness\nconditions on homotopy types, than (presumably at least, for the time\nbeing)in any other essential respect concerning the ability for\nexpressing basic situations and facts in homotopy or cohomology\ntheory, the category of simplices stands singled out by itself from\nall other test categories. Nor does it seem that the ``trinity''\n\\[ \\Simplex, \\Square, \\Globe\\]\nhas this property, with the only exception so far, possibly, of the\nDold-Puppe theorem (as no other test category except these is known to\nme for which a Dold-Puppe theorem in its strict form holds true\n(compare reflections section \\ref{sec:71})).\n\n\\namedlabel{q:91.8}{8)}\\enspace\nI could make the same point in favor of more general test categories\nthan the trinity above, when it comes to the existence of an algorithm\nfor computing homology and cohomology groups, using suitable\n\\emph{boundary operators}. What is meant by these is clear of course\nfor the three types of complexes, but then it extends in an obvious\nway to multicomplexes too -- which means that for the test categories\ndeduced from the trinity by taking finite products, we still get an\nalgorithm for cohomology via boundary operators. Of course, for any\ntest category $A$, using a test functor (if we can find one) from one\nof the three above (say) into \\Ahat{} will allow us to reduce\n``computation'' of homology and cohomology invariants in terms of a\nmodel in \\Ahat, to the case of the corresponding type of complexes --\nhence again an algorithm (similar to the familiar one of computing the\ncohomology of an object of \\Cat{} semisimplicially, via the\nnerve). But this is cheating of course! The question I want to raise\nhere is about existence of ``boundary operations'' \\emph{in} $A$,\nsimilar to the familiar ones used for the three basic types of\ncomplexes, and allowing to compute the homology and cohomology groups\nof an object of \\Ahat{} in the usual way, involving suitable\n\\emph{signs} $+$ or $-$ associated to the various boundary\noperations.\\pspage{316} It shouldn't be hard, I feel, to pin down\nexactly what is needed for getting such a formalism. The intuitive\nidea behind it (suggested by the example of standard complexes and\nmulticomplexes) is that \\emph{such a formalism should be associated to\n  cellular decompositions of $n$-cells for variable $n$}, such that\nthe interior of each $n$-cell should be an open cell of the\nsubdivision. There may of course be several $n$-cells for the same\n$n$, which are not combinatorially isomorphic. When trying to express\nthis idea in a precise way, we are led to assume, as an extra\nstructure on the would-be test category $A$, a functor\n\\begin{equation}\n  \\label{eq:91.1}\n  i:A\\to\\Ord\\tag{1}\n\\end{equation}\nof $A$ into the category of ordered sets, such that for any $a$ in\n$A$, $i(a)$ be a \\emph{finite} ordered set, whose geometric\nrealization (cf.\\ section \\ref{sec:22}) is an $n$-cell for suitable\n$n\\eqdef\\dim(a)$. We assume moreover that $i(a)$ has a largest element\n$e(a)$, and that the geometric realization of $i(a)\\setminus\\{e(a)\\}$\nis the bounding $(n-1)$-sphere of the $n$-cell $\\abs{i(a)}$:\n\\begin{equation}\n  \\label{eq:91.2}\n  \\abs{i(a)^*} \\simeq \\mathrm S^{n-1}, \\quad\\text{where}\\quad\n  i(a)^* \\eqdef i(a)\\setminus\\{e(a)\\},\\tag{2}\n\\end{equation}\nwhich will imply the precedent condition, namely\n\\begin{equation}\n  \\label{eq:91.3}\n  \\abs{i(a)}\\simeq \\mathrm B^n,\\tag{3}\n\\end{equation}\nas $\\mathrm B^n$ can be identified to the cone over $\\mathrm\nS^{n-1}$. As another condition, we need that\n\\medbreak\n\\noindent(\\namedlabel{eq:91.4}{4})\\hfill%\n\\parbox[t]{0.9\\textwidth}{For any $a$ in $A$ and $x\\in i(a)$, there\n  exists $b$ in $A$ and an isomorphism\n  \\[i(b)\\tosim i(a)_{/x} \\eqdef\\set[\\big]{y\\in i(a)}{y\\le x}\n  \\hookrightarrow i(a),\\]\n  induced by a map\n  \\[b\\to a\\]\n  in $A$.}\\par\n\\medbreak\n\\noindent It is enough to make this assumption for $x$ of codimension\n$1$ in $i(a)$, which will imply that it is true for any $x$. It seems\nreasonable on the other hand to make the assumption that for a given\n$x$, the object $b$ in \\eqref{eq:91.4}, viewed as an object of\n$A_{/a}$, is determined up to a unique isomorphism, we may call it\n$a_x$, and $\\partial_x$ the canonical map of $b$ into $a$\n\\begin{equation}\n  \\label{eq:91.5}\n  \\partial_x:a_x\\to a \\qquad\n  \\begin{tabular}[t]{@{}c@{}}\n    ($x\\in i(a)$, of codim.\\ $1$ in $i(a)$, \\\\\n    i.e., $\\dim(x)=\\dim(a)-1$).\n  \\end{tabular}\n  \\tag{5}\n\\end{equation}\nAs an extra structure, we need for any $a$ in $A$\n\\begin{equation}\n  \\label{eq:91.6}\n  \\omega_a,\\quad\\text{an \\emph{orientation} of the $n$-cell\n    $i(a)$}\\quad(n=\\dim(a)).\\tag{6}\n\\end{equation}\nThis allows us, for any $x$ as in \\eqref{eq:91.5}, to define a\nsignature\n\\begin{equation}\n  \\label{eq:91.7}\n  \\varepsilon(x)\\quad\\text{or}\\quad \\varepsilon_a(x)\\in\\{+1,-1\\},\\tag{7}\n\\end{equation}\nwhich\\pspage{317} will be $+1$ or $-1$, depending on whether in the\ninclusion\n\\[\\abs{\\partial_x}:\\abs{i(a_x)}\\to\\abs{i(a)},\\]\nthe orientation $\\omega(a_x)$ is induced ``à la Stokes'' by the\norientation $\\omega(a)$ of the ambient $n$-cell, or not. Having the\nboundary operations \\eqref{eq:91.5} with their signatures\n\\eqref{eq:91.7}, and the decomposition\n\\begin{equation}\n  \\label{eq:91.8}\n  A = \\coprod_{n\\ge0} A_n,\\quad\\text{where $A_n=\\set[\\big]{a\\in\\Ob A}{\\dim\n      a=n}$,}\\tag{8}\n\\end{equation}\nwe get in the usual way, for any contravariant functor $K_\\bullet$\nfrom $A$ with values in an additive category, a corresponding chain\ncomplex in this category, with components\n\\begin{equation}\n  \\label{eq:91.9}\n  K_n = \\coprod_{a\\in A_n} K_\\bullet(a),\\tag{9}\n\\end{equation}\nand boundary operators defined in the usual way via \\eqref{eq:91.5}\nand \\eqref{eq:91.7}. Applying this to the case of the category \\Ab{}\nof abelian groups, or to its dual, and to the abelianization of an\nobject $X$ of \\Ahat, we obtain a tentative way for computing the\nhomology and cohomology groups of the homotopy type of $A_{/X}$, and\nsimilarly for any system of twisted coefficients on $X$. The question\nwhich arises here is to write down a set of natural extra conditions\non the data, which will ensure that we do get a canonical isomorphism\nbetween the ``homology'' and ``cohomology'' groups thus constructed,\nand the usual homology and cohomology invariants of the object\n$A_{/X}$ of \\Cat. Moreover, we would like too to have conditions to\nensure that $A$ is a test category, or even a strict one.\n\nOne difficulty here, if one really wants a test category and not just\na weak one (which may not be without any problem either), is that\npresumably for this, we'll need suitable \\emph{degeneracy operations},\nwhich may well turn out a very exacting condition indeed! The\nskeptical reader may wonder, as I am just doing myself, whether there\nwill be any example within the set-up I propose, which does not reduce\nto a finite product of test categories in our trinity.\\pspage{318}\n\nI just spent a while trying to find some convincing example, by using\na suitable full subcategory $A_0$ of \\Ord, made up with finite sets\nsatisfying the assumption \\eqref{eq:91.2} above for $i(a)$, under some\nadditional assumption on $A_0$ such as stability under finite products\nand under passage from $a$ to an object $a_{/x}$, and that $A_0$\ncontain the ordered set\n\\[I =\n\\begin{tikzcd}[baseline=(O.base),cramped,row sep=-3pt,column sep=small]\n  \\bullet\\ar[dr] & \\\\ & |[alias=O]| \\bullet \\\\ \\bullet\\ar[ur] &\n\\end{tikzcd},\\]\nwhose geometric realization is the segment $\\mathrm B^1$ with its\nusual cellular decomposition. In terms of $A_0$ and introducing\n``orientations'' of object of $A_0$, the idea was to define another\ncategory $A$ (of pairs $(a,\\omega)$, with $a$ in $A_0$ and $\\omega$ an\norientation of $\\abs a$), \\emph{stable under finite products} so that\n\\Ahat{} is totally aspheric, together with a functor\n$i:A\\to\\Ord\\hookrightarrow\\Cat$ such that $i^*(I)$ should be\nrepresentable, and hence furnish the homotopy interval needed to\nensure that $A$ is a test category. The first idea that comes to mind,\nnamely define a map from $(a,\\omega)$ to $(a',\\omega')$ as merely a\nmap from $a$ to $a'$ in $A_0$, is nonsense unfortunately, as in the\ndata \\eqref{eq:91.6}, the orientations will not be stable under\nisomorphisms, a condition which I forgot to state before, and which is\nvisibly needed in order to be able to define the differential between\nthe $K_n$'s. If we try to define $A$ taking into account this\ncompatibility condition, we loose existence of products, anyhow\n$i^*(I)$ isn't representable anymore, so why should it be aspheric\nover the final object, so why should the functor $i$ be a test functor?\n\nThe difficulty I find in carrying through any explicit example for a\n``test category with boundary operations'', except those which stem\nfrom our trinity, is rather intriguing I feel. The question is whether\nmaybe in this direction, one might get at an intrinsic description of\nthe trinity, in terms of the rather natural structure species of a\n``test category with boundary operations''. This is the second\ninstance where the thought arises that the three standard test\ncategories $\\Simplex$, $\\Square$ and $\\Globe$ may be distinguished in\nsome respects -- the first instance was in relation to the Dold-Puppe\ntheorem.\n\n\\namedlabel{q:91.9}{9)}\\enspace\\textbf{Miscellaneous residual\n  questions from part \\ref{ch:II}.} One of these was about the category\n$\\Simplexf$ of simplices without degeneracies being a weak test\ncategory (cf.\\ section \\ref{sec:43}) -- while it is definitely\n\\emph{not} a test category. It seems worth while to write down a proof\nfor this, maybe too for the analogous statements for\n$\\Square^{\\mathrm f}$ and $\\Globe^{\\mathrm f}$. This reminds\nme\\pspage{319} too that I never got around to introducing formally the\nhemispherical test category, which presumably will be very useful when\nit comes to studying stacks -- this too could be done in part\n\\ref{ch:IV}, as well as proving of course that $\\Globe$ is a strict\ntest category indeed, or better still, a contractor. It may be fun too\nconstructing test functors from any one of the three basic test\ncategories in the trinity, to the category of complexes defined by the\ntwo others -- six cases altogether to consider! But as I am not in the\nprocess of writing the\\scrcomment{pity!} ``Elements d'Algèbre\nHomotopique'', maybe I will skip this!\n\nIn the same section \\ref{sec:43}, I raised the question as to whether\nthe ordered set of all non-empty finite subsets of a given infinite\nset, viewed as a category in the usual way for an ordered set, was a\nweak test category (on page \\ref{p:78} it was seen not to be a test\ncategory, and it is immediate then that it is not totally aspheric\neither). One interesting application, as noticed there, would be to\nthe effect that \\Ord, the subcategory of \\Cat{} defined by ordered\nsets, is a modelizer (for the induced notion of weak\nequivalences). Now the question arises moreover whether this\nmodelizing structure comes from an asphericity structure, or even from\na contractibility structure -- and the same question arises in the\nmore general situation described in the proposition of page\n\\ref{p:74}.\n\nA last question along these lines I would like to clear up, is the\nrelation of total \\scrW-asphericity for an asphericity structure, for\nvariable \\scrW, when $\\scrW\\subset\\scrW'$. Assuming the localizers\nsatisfy the condition \\ref{loc:4}, is it true that total\n\\scrW-asphericity is equivalent to total $\\scrW'$-asphericity -- or\nequivalently, is it equivalent to total $0$-connectedness?\n\n\\bigbreak\n\n\\presectionfill\\ondate{5.7.}\\pspage{320}\\par\n\n% 92\n\\hangsection[Short range working program, and an afterthought on\n\\dots]{Short range working program, and an afterthought on\n  abelianization of homotopy types: a handful of questions around the\n  Whitehead and Dold-Puppe theorems.}\\label{sec:92}%\nThe review on ``pending questions and topics'' related to part\n\\ref{ch:IV} of the notes has taken pretty much longer than\nexpected. It was quite useful though, to get a clearer view of what\nthose questions are about, and to get a feeling for what to include\nand develop, and where. As I do not intend to spend my life on the\ntask, not even one year, it is becoming clear that I am not going to\nget the whole picture of all the questions touched -- and some\npresumably I am going to leave just aside, as they do not seem\nindispensable for a comprehensive overall picture of what I'm\nafter. This seems to me to be the case for the questions \\ref{q:91.7}\nand \\ref{q:91.8}, concerned with finiteness conditions for homotopy\ntypes in terms of models, and with test categories with boundary\noperations. At the opposite side, it seems that the questions\n\\ref{q:88.2}, part of \\ref{q:88.3}, and \\ref{q:91.9}, about the notion\nof contractor, induced asphericity and contractibility structures on a\ncategory $M_{/a}$, and ``miscellaneous'' left-overs from part\n\\ref{ch:II}, should be dealt with in part \\ref{ch:IV} -- whose end now\nis in sight after all!  On the other hand, questions \\ref{q:88.1},\nanother part of \\ref{q:88.3}, \\ref{q:88.5} and \\ref{q:90.6}, about\nmorphisms of asphericity structures and related problems, about an\nautodual treatment of asphericity and contractibility notions, about a\nhandy criterion for canonical modelizers, and about existence theorems\nfor various kinds of test functors or aspheric functors, while I feel\nthat I should come at least to a considerably clear understanding of\nthese matters than now, the adequate place for developing such\nreflection is definitely \\emph{not} in the present part \\ref{ch:IV},\nbut belong to one or the other of the three parts still ahead in our\noverall reflection on the modelizing story.\n\nDuring our review, we came a number of times upon situations when the\nquestion arose as to whether one point I like to make, namely that a\nmore or less arbitrary (strict) test category ``is just as good'' as\nthe sacrosanct test category $\\Simplex$, or its twin brothers\n$\\Square$ and $\\Globe$, is a valid one or not. I would like to list\nhere these situations, with a view of coming back to it later:\n\\begin{enumerate}[label=\\alph*)]\n\\item\\label{it:92.a}\n  Existence theorems for test functors (cf.\\ section \\ref{sec:90}).\n\\item\\label{it:92.b}\n  \\Ahat{} and various other categories constructed in terms of $A$,\n  such as $\\bHom(A\\op,M)$, are closed model categories (under suitable\n  assumptions\\ldots).\n\\item\\label{it:92.c}\n  Independence of the derived category of $\\bHom(A\\op,M)$ on the\n  choice of test category, notably when $M$ is a topos or the dual of\n  a\\pspage{321} topos (with suitable assumptions on $A,M$\\ldots).\n\\item\\label{it:92.d}\n  Possibility of expressing finite type of a homotopy type in terms of\n  \\Ahatfp, for suitable test categories $A$.\n\\item\\label{it:92.e}\n  Possibility of defining boundary operations within a test category\n  -- and/or getting Dold-Puppe type relations.\n\\end{enumerate}\n\n\\starsbreak\n\nBefore resuming more technical work with the matters left over for\npart \\ref{ch:IV}, I would like still to write down some afterthoughts,\nconcerning the question of boundary operations in a test category\n(question \\ref{q:91.8} in our review). It occurred to me that perhaps\nit isn't such a good idea, to try at all costs to subordinate this\nquestion to a question of cellular decompositions of spheres, however\nnatural this idea may be in view of the examples of the standard types\nof complexes and multicomplexes. In this connection, I remember that\namong my first thoughts when starting unwittingly on the modelizing\nstory, was that a ``test category'' $A$ (namely one such that \\Ahat{}\nshould be ``modelizing'') should more or less correspond to such\ndecompositions. Soon after it came as a big surprise that so little\nwas needed in fact for $A$ to merit the name of a test category -- and\nthat the relevant conditions had nothing to do with cellular\ndecompositions of this or that. The same may well turn out, when\nlooking for a generalization of the standard simplicial, cubical or\nhemispherical chain complexes, giving rise to the homology and\ncohomology invariants of a given ``complex''. The kind of set-up I\nproposed in yesterday's notes, for a formalism of boundary operations\nin a test category $A$, now looks to me in some respects\nsomewhat\\scrcomment{``étriqué'' can again be translated as\n  ``narrow-minded''} ``étriqué'', and I'll try another start in a\ndifferent spirit.\n\nIn order not to get involved in irrelevant technicalities, I assume\nthat the basic localizer \\scrW{} is $\\scrWoo=$ usual weak\nequivalence. It seems that one basic fact for writing down\na relationship between homotopy types and ``homology types'', is the\nexistence of a canonical ``abelianization functor''\n\\begin{equation}\n  \\label{eq:92.1}\n  \\Hot\\to\\D_\\bullet(\\Ab) \\quad (\\eqdef \\HotabOf),\\tag{1}\n\\end{equation}\nwhere \\Ab{} is the abelian category of abelian groups, and\n$\\D_\\bullet$ designates the ``derived category'' of the category\n$\\Ch_\\bullet(\\Ab)$ of chain complexes of abelian groups, namely its\nlocalization with respect to ``weak equivalences'', i.e.,\nquasi-isomorphisms:\\pspage{322}\n\\begin{equation}\n  \\label{eq:92.2}\n  \\D_\\bullet\\Ab = W^{-1}\\Ch_\\bullet\\Ab,\\tag{2}\n\\end{equation}\nwhere $W$ means ``quasi-isomorphisms'', i.e., maps inducing\nisomorphisms for all homology groups. The most common way for defining\nthe canonical functor \\eqref{eq:92.1}, where as usual here \\Hot{} is\ndefined as $\\scrW^{-1}\\Cat$, is via the test category $\\Simplex$, as\nthe composition in the bottom row of\n\\begin{equation}\n  \\label{eq:92.3}\n  \\begin{tabular}{@{}c@{}}\n    \\begin{tikzcd}[baseline=(O.base)]\n      \\Cat \\ar[r,\"i^*\"]\\ar[d] &\n      \\Simplexhat \\ar[r,\"\\Wh_{\\Simplex}\"]\\ar[d] &\n      \\Simplexhatab \\ar[r,\"\\equ\\supDP\"]\\ar[d] &\n      \\Ch_\\bullet\\Ab \\ar[d] \\\\\n      \\Hot \\ar[r,\"\\equ\"] &\n      \\HotOf_{\\Simplex} \\ar[r] &\n      \\HotabOf_{\\Simplex} \\ar[r,\"\\equ\"] &\n      |[alias=O]| \\D_\\bullet\\Ab\n    \\end{tikzcd},\n  \\end{tabular}\\tag{3}\n\\end{equation}\nwhich is deduced from the top row by passing to the localized\ncategories. The subscript $\\mathrm{ab}$ in \\Simplexhatab{} denotes the\ncategory of abelian group objects in \\Simplexhat, the functor\n\\begin{equation}\n  \\label{eq:92.4}\n  \\Wh_{\\Simplex} : \\Simplexhat\\to\\Simplexhatab\\tag{4}\n\\end{equation}\nis the ``\\emph{abelianization functor}'' obtained by composing a\npresheaf $\\Simplexop\\to\\Sets$ with the abelianization functor\n\\[\\Sets\\to\\Ab, \\quad X\\mapsto\\bZ^{(X)}.\\]\nWe call this functor $\\Wh_\\Simplex$ also the ``Whitehead functor'', as\nits main property is expressed in \\emph{Whitehead's theorem}, namely\nthat it is compatible with weak equivalences (where weak equivalences\nin \\Simplexhatab{} are defined in terms of the underlying\nsemisimplicial sets, forgetting the addition laws). The localized\ncategory of \\Simplexhatab{} with respect to the latter notion of weak\nequivalence is denoted by $\\HotabOf_\\Simplex$, the functor\n\\begin{equation}\n  \\label{eq:92.4prime}\n  \\HotOf_\\Simplex \\to \\HotabOf_\\Simplex\\tag{4'}\n\\end{equation}\ninduced by $\\Wh_\\Simplex$ may be equally (and still more validly) be\ndesignated by $\\Wh_\\Simplex$. The two subscripts $\\Simplex$ (in $\\Wh$\nand in $\\HotabOf$) refer to the fact that the notions make still a\nsense when $\\Simplex$ is replaced by an arbitrary small category $A$,\ncf.\\ below.\n\nThe functor $\\DP$ in the top row is the well-known \\emph{Dold-Puppe\n  functor}, which is an equivalence of categories. As for $i^*$, it is\ndefined in terms of an arbitrary test functor\n\\[i:\\Simplex\\to\\Cat,\\]\nwhich may be either the standard inclusion (which is the more commonly\nused one) or the canonical functor $a\\mapsto\\Simplex_{/a}$, called\n$i_\\Simplex$. The functors $i^*$ corresponding to different choices of\n$i$ are of course in general non-isomorphic, however (as follows from\nsection \\ref{sec:77})\\pspage{323} the corresponding functor\n\\[\\overline{i^*}:\\Hot\\to\\HotOf_\\Simplex\\]\nis independent of such choice, up to canonical isomorphism.\n\nInstead of $\\Simplex$, we could have worked with $\\Square$ or $\\Globe$\ninstead, as these give rise to a Dold-Puppe functor (which is still an\nequivalence), and (almost certainly, see below) to a corresponding\nvariant of the ``Whitehead theorem''. We thus get two other ways for\ndefining a canonical ``abelianization functor'' \\eqref{eq:92.1} for\nhomotopy types, and it should be an easy and pleasant exercise to show\nthese three functors are canonically isomorphic, using the fact that a\nproduct of test categories is again a test category.\n\n\\begin{remark}\n  Of course, when concerned mainly with defining a functor\n  \\eqref{eq:92.1} we don't really need Whitehead and Dold-Puppe\n  theorems -- indeed, instead of taking the functor\n  \\[\\DP\\circ\\Wh_\\Simplex:\\Simplexhat\\to\\Ch_\\bullet\\Ab,\\]\n  we could have taken directly (using the standard boundary operations\n  between the components of a semisimplicial abelian group) the\n  standard chain complex structure of $\\bZ^{(K_\\bullet)}$ (for\n  $K_\\bullet$ in \\Simplexhat), without taking the trouble and\n  normalizing it à la Dold-Puppe -- and it is a lot more trivial than\n  either Whitehead's or Dold-Puppe's theorem, that the latter functor\n  transforms weak equivalences into quasi-isomorphisms; moreover, it\n  gives rise to the same functor\n  \\begin{equation}\n    \\label{eq:92.5}\n    \\HotOf_\\Simplex\\to\\D_\\bullet\\Ab\\quad(=\\HotabOf)\\tag{5}\n  \\end{equation}\n  as $\\DP\\circ\\Wh_\\Simplex$.\n\\end{remark}\n\nLet now $A$ be \\emph{any} small category, we are interested in the\nfunctor\n\\begin{equation}\n  \\label{eq:92.6}\n  \\HotOf_A \\to \\D_\\bullet\\Ab\\quad (=\\HotabOf)\\tag{6}\n\\end{equation}\nobtained as the composition\n\\begin{equation}\n  \\label{eq:92.7}\n  \\HotOf_A\\to\\Hot \\to\\D_\\bullet\\Ab,\\tag{7}\n\\end{equation}\nwhere the second functor is the abelianization functor\n\\eqref{eq:92.1}, and the first is the canonical functor, deduced by\nlocalization from\n\\begin{equation}\n  \\label{eq:92.8}\n  i_A:\\Ahat\\to\\Cat,\\quad a\\mapsto A_{/a}.\\tag{8}\n\\end{equation}\nWe see immediately that for $A=\\Simplex$, the functor \\eqref{eq:92.6}\nreduces to \\eqref{eq:92.5} up to canonical isomorphism -- and the same\nof course when\\pspage{324} $A$ is either $\\Square$ or $\\Globe$. In\nthese three cases, the functor \\eqref{eq:92.6} can be factorized in a\nnatural way through the category\n\\[\\HotabOf_A = W^{-1}\\Ahatab,\\]\nwhere now $W$ stands for the set of ``weak equivalences'' in \\Ahatab,\ndefined in the same way as above in the case $A=\\Simplex$. The\nquestion then arises, for any given $A$, as to whether such a\nfactorization can be still obtained, and how exactly.\n\nThis formulation is inspired by the description of abelianization of\nhomotopy types via the (slightly sophisticated diagram)\n\\eqref{eq:92.3}. When following the more naive approach of the remark\nabove, this leads us to the closely related question of defining\n\\eqref{eq:92.6} via a composition\n\\begin{equation}\n  \\label{eq:92.9}\n  \\Ahat\\xrightarrow{\\Wh_A} \\Ahatab \\xrightarrow L \\Ch_\\bullet\\Ab,\\tag{9}\n\\end{equation}\n(for a suitable functor $L$, cf.\\ below), by passing to localizations.\n\nBoth approaches seem to me of interest. The first one, to make sense\nat all as stated, relies on the existence of a canonical functor\n\\begin{equation}\n  \\label{eq:92.9prime}\n  \\HotOf_A\\to\\HotabOf_A,\\tag{9'}\n\\end{equation}\ninduced by the abelianization functor\n\\[\\Wh_A:\\Ahat\\to\\Ahatab,\\quad X\\mapsto\\bZ^{(X)},\\]\ni.e., on the \\emph{validity of Whitehead's theorem, with $\\Simplex$\n  replaced by $A$}. This looks like an interesting question, whose\nanswer should be in the affirmative. At any rate, if we can find an\naspheric functor\n\\begin{equation}\n  \\label{eq:92.10}\n  j:\\Simplex\\to\\Ahat\\tag{10}\n\\end{equation}\n(with respect to the standard asphericity structure of $A$), then the\nanswer is affirmative, as we are immediately reduced to the known case\n$A$ is replaced by $\\Simplex$. Thus, the answer is possibly tied up\nwith the question of existence of test functors, which we'll deal with\npresumably in part \\ref{ch:V}. It should be noted though that if such\na functor \\eqref{eq:92.10} exists, then necessarily $A$ is aspheric,\nand even totally aspheric -- a substantial restriction indeed.\n\nMore generally, let\n\\begin{equation}\n  \\label{eq:92.10prime}\n  j:B\\to\\Ahat\\tag{10'}\n\\end{equation}\nany aspheric functor with respect to the standard asphericity\nstructure of \\Ahat, where $B$ is any small category. The corresponding\nfunctor\\pspage{325}\n\\begin{equation}\n  \\label{eq:92.11}\n  j^*:\\Ahat\\to\\Bhat\\tag{11}\n\\end{equation}\nthen satisfies\n\\[(j^*)^{-1}(\\scrWB)=\\scrWA,\\]\nand the corresponding functor for the localizations gives rise to a\ncommutative diagram\n\\[\\begin{tikzcd}[baseline=(O.base),column sep=tiny]\n  \\HotOf_A \\ar[rr,\"\\overline{j^*}\"]\\ar[dr,\"\\overline{i_A}\"'] & &\n  \\HotOf_B \\ar[dl,\"\\overline{i_B}\"] \\\\\n  & |[alias=O]| \\Hot &\n\\end{tikzcd},\\]\nand hence the corresponding diagram\n\\begin{equation}\n  \\label{eq:92.12}\n  \\begin{tikzcd}[column sep=tiny]\n    \\HotOf_A \\ar[rr,\"\\overline{j^*}\"]\\ar[dr] & &\n    \\HotOf_B \\ar[dl] \\\\\n    & \\D_\\bullet\\Ab=\\HotabOf &\n  \\end{tikzcd}\n  \\tag{12}\n\\end{equation}\nis commutative, where the vertical arrows are the canonical functors\n\\eqref{eq:92.6}. Coming back to the base $B=\\Simplex$ say, this shows\nthat \\eqref{eq:92.6} can be viewed as the composition\n\\[ \\HotOf_A \\xrightarrow{\\overline{j^*}} \\HotOf_\\Simplex\n\\xrightarrow{\\overline{\\Wh_\\Simplex}} \\HotabOf_\\Simplex\n\\xrightarrow[\\equ]{\\overline{\\DP}} \\HotabOf,\\]\nand hence it can be inserted in the commutative diagram\n\\begin{equation}\n  \\label{eq:92.13}\n  \\begin{tabular}{@{}c@{}}\n    \\begin{tikzcd}[baseline=(O.base)]\n      \\HotOf_A\\ar[r]\\ar[d] & \\HotOf_\\Simplex\\ar[d] & \\\\\n      \\HotabOf_A\\ar[r] & \\HotabOf_\\Simplex \\ar[r,\"\\equ\"] &\n      |[alias=O]| \\HotabOf\n    \\end{tikzcd},\n  \\end{tabular}\\tag{13}\n\\end{equation}\nwhere the functor\n\\[\\HotabOf_A \\to \\HotabOf_\\Simplex\\]\nis induced by $j^*\\subab$. Thus, we get the wished for factorization\nof \\eqref{eq:92.6} via $\\HotabOf_A$, \\emph{provided we can find an\n  aspheric functor} \\eqref{eq:92.10}. It should not be hard moreover\nto see that the factorizing functor obtained from \\eqref{eq:92.13},\nnamely\n\\begin{equation}\n  \\label{eq:92.14}\n  \\HotabOf_A\\to\\HotabOf,\\tag{14}\n\\end{equation}\ndoes not depend up to canonical isomorphism on the choice of $j$, at\nleast in the case when $A$ is a contractor, using the end remarks of\nsection \\ref{sec:82} (p.\\ \\ref{p:272}) concerning products of aspheric\nfunctors.\n\nThe question remains whether we can define \\eqref{eq:92.14} for (more\nor less) any small category $A$, without having to rely upon the\nexistence of\\pspage{326} an aspheric functor \\eqref{eq:92.10}, in such\na way that it factors the canonical functor \\eqref{eq:92.6} (granting\nWhitehead's theorem holds for $A$), and moreover that for an aspheric\nfunctor \\eqref{eq:92.10prime} $j:B\\to\\Ahat$, giving rise to\n\\[\\overline{j^*\\subab}:\\HotabOf_A\\to\\HotabOf_B,\\]\nthen corresponding diagram\n\\begin{equation}\n  \\label{eq:92.15}\n  \\begin{tikzcd}[column sep=tiny]\n    \\HotabOf_A\\ar[rr]\\ar[dr] & & \\HotabOf_B\\ar[dl] \\\\ & \\HotabOf &\n  \\end{tikzcd}\\tag{15}\n\\end{equation}\nshould commute, where the vertical arrows are the functors\n\\eqref{eq:92.14}.\n\nFor defining \\eqref{eq:92.14} in this general case, recalling that\n\\[\\HotabOf \\fromequ \\HotabOf_\\Simplex,\\]\nwe can't help it and have to use diagram \\eqref{eq:92.3} and the\nfunctor\n\\[i_A:\\Ahat\\to\\Cat,\\]\nor rather (\\Cat{} serving only as an intermediary) the functor\n\\[u \\eqdef i^*i_A : \\Ahat\\to\\Simplexhat,\\]\nso that \\eqref{eq:92.6} can be viewed as deduced by localization of\n\\Ahat{} from the composition\n\\begin{equation}\n  \\label{eq:92.star}\n  \\Ahat\\xrightarrow\n  u\\Simplexhat\\xrightarrow{\\Wh_\\Simplex}\\Simplexhatab\\to\\HotabOf_\\Simplex\n  \\quad (\\toequ\\HotabOf).\\tag{*}\n\\end{equation}\nOne difficulty here is that $u$ does not commute to finite products,\nand hence doesn't induce a functor\n\\[\\Ahatab\\to\\Simplexhatab,\\]\nit would seem. Now this difficulty, I just noticed, can be overcome,\nusing the fact that $i_A$ and hence also $u$ \\emph{commutes to fibered\n  products}, or, what amounts to the same, induces an \\emph{exact}\nfunctor\n\\[u_0 : \\Ahat\\to\\Simplexhat_{/F}\\toequ(\\Simplex_{/F})\\uphat,\\]\nwhere\n\\[F=u(e_\\Ahat)=i^*(A)\\]\nis a suitable object in \\Simplexhat. A fortiori, $u_0$ commutes to\nfinite products, hence transforms abelian group objects into same,\ni.e., induces\n\\[u_{0\\mathrm{ab}} : \\Ahatab\\to(\\Simplex_{/F})\\uphat\\subab,\\]\non\\pspage{327} the other hand, we do have too a natural functor\n\\begin{equation}\n  \\label{eq:92.16}\n  \\alpha^{\\mathrm{ab}}_!:(\\Simplex_{/F})\\uphat\\subab\\to\\Simplexhatab,\\tag{16}\n\\end{equation}\ndefined as the left adjoint of the evident functor\n\\[\\alpha^*\\subab:\\Simplexhatab\\to(\\Simplex_{/F})\\uphat\\subab\\]\ninduced by the left exact functor $\\alpha^*$, where $\\alpha$ is the\n``localization morphism of topoi''\n\\[\\alpha:\\Simplex_{/F}\\to \\Simplex_F\\]\ndefined by the object $F$ of \\Simplexhat. We thus get a diagram\n\\begin{equation}\n  \\label{eq:92.17}\n  \\begin{tabular}{@{}c@{}}\n    \\begin{tikzcd}[baseline=(O.base)]\n      \\Ahat\\ar[r,\"\\Wh_A\"] \\ar[d,\"u_0\"'] \\ar[dd,bend right=50,\"u\"'] &\n      \\Ahatab\\ar[d,\"u_{0\\mathrm{ab}}\"]  & & \\\\\n      (\\Simplex_{/F})\\uphat \\ar[r,\"\\Wh_{\\Simplex_{/F}}\"]\n      \\ar[d,\"\\alpha_!\"'] &\n      (\\Simplex_{/F})\\uphat\\subab \\ar[d,\"\\alpha_!^{\\mathrm{ab}}\"] & & \\\\\n      \\Simplexhat\\ar[r,\"\\Wh_\\Simplex\"] & \\Simplexhatab \\ar[r] &\n      \\HotabOf_\\Simplex \\ar[r] & |[alias=O]| \\HotabOf\n    \\end{tikzcd},\n  \\end{tabular}\n  \\tag{17}\n\\end{equation}\ncontaining \\eqref{eq:92.star} above as the composition of maps in the\nleft-hand vertical column and in the bottom row. The lower square in\nthis diagram commutes (up to natural isomorphism) -- which is a\ngeneral fact surely for morphisms of topoi $f:X\\to Y$ such that $f_!$\nexists, which allows to define too a functor $f_!^{\\mathrm{ab}}$ as\n\\eqref{eq:92.16} above. The upper square though doesn't look at all\ncommutative, too bad! The only hope left now is that the natural\ncompatibility arrow for this square (there is bound to be one, isn't\nthere!), when composed with the lower square (so as to give a\ncompatibility map for the composite rectangle) \\emph{should give rise\n  to a weak equivalence in} \\Simplexhatab, for any choice of an object\n$X$ in \\Ahat.\n\nIt would seem to me that a reasonable functor \\eqref{eq:92.14} will\nexist, without an existence assumption of a test functor\n\\eqref{eq:92.10}, exactly in those cases when the composite rectangle\nin \\eqref{eq:92.17} is ``commutative up to weak equivalence''. I have\nno idea whether or not this is true for any small category $A$, not\neven (I confess) when there \\emph{is} an aspheric functor\n\\eqref{eq:92.10} -- as a matter of fact, I don't feel like going any\nfurther now in this direction, and trying to check anything\nwhatsoever.\n\nI was a little rash in the definite statement I made about the\n``exact'' assumption to make for a ``reasonable'' functor\n\\eqref{eq:92.14} to exist; another seems needed still, namely that the\nfunctor\\pspage{328}\n\\begin{equation}\n  \\label{eq:92.18}\n  \\Ahatab\\to\\Simplexhatab\\tag{18}\n\\end{equation}\nwe obtain by composing the two arrows in the right hand vertical\ncolumn, transforms weak equivalences into same, which is needed in\norder to deduce \\eqref{eq:92.14} by passing to the localized\ncategories. When the two assumptions are satisfied, then the functor\n\\eqref{eq:92.14} obtained from \\eqref{eq:92.18} does factorize\n\\eqref{eq:92.6} as required, and it should be clear too that it\nsatisfies the compatibility \\eqref{eq:92.15}.\n\nThus, it seems there are good prospects for getting canonical functors\n\\[\\HotOf_A \\to \\HotabOf_A \\to \\HotabOf,\\]\nwhose composition is \\eqref{eq:92.6}, i.e., inserting into the\ncommutative diagram\n\\begin{equation}\n  \\label{eq:92.19}\n  \\begin{tabular}{@{}c@{}}\n    \\begin{tikzcd}[baseline=(O.base)]\n      \\HotOf_A\\ar[r]\\ar[d] & \\HotabOf_A\\ar[d] \\\\\n      \\HotOf \\ar[r] & |[alias=O]| \\HotabOf\n    \\end{tikzcd}.\n  \\end{tabular}\n  \\tag{19}\n\\end{equation}\nThe next question then which arises is \\emph{whether the second\n  vertical arrow} (namely \\eqref{eq:92.14}) \\emph{is an equivalence,\n  whenever the first one is}, i.e., when $A$ is a pseudo-test\ncategory, or whether this is true if we make some familiar extra\nassumption on $A$, such as being an actual test category say.\n\nI feel I am getting gradually back into thin air conjecturing, I\nwouldn't go on too long this way! This whole $\\HotabOf_A$ business was\njust a digression, which then took me longer than expected, it doesn't\nseem to have much to do with what I have been out for in this section,\nnamely afterthoughts about \\emph{boundary operations in a test\n  category}, which are designed to gave a ``computational''\ndescription of the canonical functor \\eqref{eq:92.6}, the latter being\ndefined without any restriction nor difficulty for \\emph{any} small\ncategory $A$. More accurately still, we want to describe the\ncomposition of \\eqref{eq:92.6} with the canonical functor\n$\\Ahat\\to\\HotOf_A$, namely $\\Ahat\\to\\HotabOf$, via a suitable functor\n$\\Ahat\\to\\Ch_\\bullet\\Ab$, with the expectation that the latter should\nfactor through \\Ahatab{} via the abelianization functor $\\Wh_A$. In\nother words, we are looking for commutative diagrams\n\\begin{equation}\n  \\label{eq:92.20}\n  \\begin{tabular}{@{}c@{}}\n    \\begin{tikzcd}[baseline=(O.base),sep=tiny]\n      & \\Ahat\\ar[dl]\\ar[rr]\\ar[dd,\"K\"] & & \\HotOf\\ar[dd] \\\\\n      \\Ahatab\\ar[dr,\"L\"'] & & & \\\\\n      & \\Ch_\\bullet\\Ab\\ar[rr] & & |[alias=O]| \\HotabOf\n    \\end{tikzcd},\n  \\end{tabular}\n  \\tag{20}\n\\end{equation}\nwhere\\pspage{329} all functors in the diagram, except for $K$ and $L$,\nare the canonical ones familiar to us. The question then is how to\ndefine a suitable $L$, such that the corresponding square (where\n$K=L\\circ\\Wh_A$) should commute up to (canonical?) isomorphism.\n\nThere \\emph{is} such an $L$, whenever we have an aspheric functor\n\\eqref{eq:92.10} (where $\\Simplex$ may be replaced by one of its\ntwins), using corresponding semisimplicial chain complexes -- but, as\nalready remarked yesterday, taking things this way is ``cheating''!\nConceivably too, there are quite general theorems asserting that a\nfunctor from a category \\Ahat{} say to a derived additive category\nsuch as $\\HotabOf$ can be lifted to the category of models (here\nabelian chain complexes) it comes from, and possibly even in a way\nfactoring through \\Ahatab? I don't intend to dive into these questions\neither, but rather, make a comment on a general method for\nconstructing certain functors\n\\begin{equation}\n  \\label{eq:92.21}\n  L:\\Ahatab\\to\\Ch_\\bullet\\Ab,\\tag{21}\n\\end{equation}\n(maybe not in a way to give rise to a commutative diagram\n\\eqref{eq:92.20}), as suggested by the standard chain complexes\nassociated to the three types of complexes, using simplices, cubes or\nhemispheres, or multicomplexes (using products of the standard test\ncategories). Writing\n\\[\\Ahatab\\simeq \\bHom(A\\op,\\Ab),\\]\nwe remark that the standard constructions of chain complexes\nassociated to semisimplicial (say) complexes of abelian groups, makes\nsense not only for such abelian complexes, but more generally for\n\\emph{complexes with values in \\emph{any} additive category}, $M$\nsay. This induces us to look more generally, for any such $M$, for a\nfunctor\n\\begin{equation}\n  \\label{eq:92.22}\n  L_M:\\bHom(A\\op,M)\\to\\Ch_\\bullet(M),\\tag{22}\n\\end{equation}\nin a way \\emph{compatible with additive functors}\n\\[M\\to M'\\]\n(in the obvious sense of the word).\n\nNow, for any category $B$ (here $A\\op$) one can define an\n``\\emph{enveloping additive category}'' $\\Add(B)$, together with a\ncanonical functor\n\\begin{equation}\n  \\label{eq:92.23}\n  B\\to \\Add(B),\\tag{23}\n\\end{equation}\nwhich is ``$2$-universal'' for all possible functors of $B$ into any\nadditive category $M$. More specifically, for any such $M$, the\ncorresponding\\pspage{330} functor ``composition with\n\\eqref{eq:92.23}'' is an \\emph{equivalence}\n\\begin{equation}\n  \\label{eq:92.24}\n  \\mathbf{Homadd}(\\Add(B),M) \\toequ \\bHom(B,M).\\tag{24}\n\\end{equation}\nThis condition defines \\eqref{eq:92.22} ``up to canonical equivalence''\n-- but we'll give an explicit description in a minute. Before doing\nso, let's just remark that the universal property of \\eqref{eq:92.23}\nimplies that to give a system of functors $L_M$ as above, ``amounts to\nthe same'' as giving a chain complex $L_\\bullet$ in $\\Add(B)$. More\naccurately, the category of all systems $L_M$ (where maps are defined\nin an evident way) is \\emph{equivalent} to the category\n$\\Ch_\\bullet(\\Add(B))$, where $B=A\\op$. The functors $L$\n\\eqref{eq:92.21} we are specifically interested in, are those which\nare associated to some chain complex in $\\Add(A\\op)$,\n\\begin{equation}\n  \\label{eq:92.25}\n  L_\\bullet\\in\\Ob(\\Ch_\\bullet(\\Add(A\\op))),\\tag{25}\n\\end{equation}\nby the formula\n\\begin{equation}\n  \\label{eq:92.26}\n  L(X) = \\widetilde X(L_\\bullet)\\quad\\text{for any $X$ in\n    $\\Ahatab\\simeq\\bHom(A\\op,\\mathrm{Ab})$}\\tag{26}\n\\end{equation}\nwhere\n\\[\\widetilde X: \\Add(A\\op)\\to\\Ab\\]\nis the \\emph{additive} functor corresponding to $X$.\n\nWe are thus led to the question: if $A$ is any small category, does\nthere exist a chain complex $L_\\bullet$ in $\\Add(A\\op)$, the additive\nenvelope of $A\\op$, giving rise to a functor \\eqref{eq:92.21} via\n\\eqref{eq:92.26} and hence to a diagram \\eqref{eq:92.20}, such that\nthe square in \\eqref{eq:92.20} commutes up to isomorphism? And when\nthis is so, what kind of unicity statement, if any, can be made for\n$L_\\bullet$ (such as being unique up to chain homotopy say), and what\nabout the structure of the category of all pairs\n$(L_\\bullet,\\lambda)$, where $\\lambda$ is a compatibility isomorphism\nmaking the square in \\eqref{eq:92.20} commute?\n\nWe are far here from the rather narrow set-up in yesterday's notes,\nand as far as existence goes, if no extra conditions are put upon\n$L_\\bullet$, it seems likely that for a rather large class of small\ncategories $A$ (if not all) it should hold true. At any rate, the\nfunctor $L$ obtained from a functor \\eqref{eq:92.10}, i.e., ``by\ncheating'', is visibly associated to an $L_\\bullet$. Sorry, we have to\nassume that the functor $j$ factors even through $A$ itself, i.e., is\njust an aspherical functor between the small categories $\\Simplex$ and\n$A$, a much more stringent condition on $A$ to be sure -- and which\nimplies that there is an induced\\pspage{331} functor\n\\begin{equation}\n  \\label{eq:92.27}\n  \\Add(j\\op):\\Add(\\Simplexop)\\to\\Add(A\\op),\\tag{27}\n\\end{equation}\nhence we get an $L_\\bullet$ as the image of the canonical chain\ncomplex $L_\\bullet^\\Simplex$ we got in $\\Add(\\Simplexop)$.\n\n\\bigbreak\n\\presectionfill\\ondate{6.7.}\\par\n\n% 93\n\\hangsection[The afterthought continued: abelianizators, and\n\\dots]{The afterthought continued: abelianizators, and ``standard''\n  abelianizators for categories with boundary\n  operators.}\\label{sec:93}%\nIt is time to give the promised construction of $\\Add(B)$, the\nadditive envelope of $B$, for any given category $B$. The obvious idea\nis to enlarge the sets $\\Hom(a,b)$, for $a$ and $b$ in $B$, by taking\nlinear combinations with coefficients in \\bZ, i.e., writing\n\\begin{equation}\n  \\label{eq:93.1}\n  \\Hom_{\\Add(B)}(a,b) = \\bZ^{(\\Hom(a,b))},\\tag{1}\n\\end{equation}\nand composing these $\\Hom_{\\Add}$ in the obvious way. This is not\nquite enough though, as we still have to add new objects, namely\ndirect sums of objects in $B$. The most convenient way for doing so\nseems by defining an object of $\\Add(B)$ to be defined by a finite set\n$I$ (in the given universe), namely the indexing set for taking the\ndirect sum, and a map\n\\[ I\\to\\Ob B,\\]\nin other words, the new objects are just \\emph{families} of objects of\n$B$\n\\[(b_i)_{i\\in I},\\]\nindexed by finite sets. We'll however denote by\n\\begin{equation}\n  \\label{eq:93.2}\n  \\bigoplus_{i\\in I}b_i\\tag{2}\n\\end{equation}\nthe corresponding object of $\\Add(B)$, as this will turn out to be the\ndirect sum indeed of the images of the $b_i$'s in $\\Add(B)$ -- but of\ncourse we'll ignore the possible existence of direct sums in $B$\nitself, when they exist, and not confuse \\eqref{eq:93.2} with a direct\nsum taken in $B$. Writing $\\Homadd$ instead of $\\Hom_{\\Add(B)}$ for\nthe sake of abbreviation, the maps between objects \\eqref{eq:93.2} are\ndefined by matrices in the obvious way\n\\begin{multline}\n  \\label{eq:93.3}\n  \\Homadd((a_i)_{i\\in I},(b_j)_{j\\in J}) = \\\\\n  \\set[\\big]{(u_{ij})_{(i,j)\\in I\\times\n      J}}{u_{ij}\\in\\Homadd(a_i,b_j)=\\bZ^{\\Hom(a_i,b_j)}},\\tag{3}\n\\end{multline}\nwhile composition of maps is defined by the composition of\nmatrices. We thus get a new category $\\Add(B)$ and a functor\n\\begin{equation}\n  \\label{eq:93.4}\n  B\\to\\Add(B),\\tag{4}\n\\end{equation}\nit\\pspage{332} is immediately checked that $\\Add(B)$ is an additive\ncategory and that the functor \\eqref{eq:93.4} has the $2$-universal\nproperty for functors from $B$ into any additive category, stated in\nyesterday's notes (p.\\ \\ref{p:330}).\n\n\\begin{remark}\n  The same construction essentially applies when considering the\n  universal problem of mapping $B$ into any $k$-\\emph{additive}\n  category $M$ (where $k$ is any commutative ring with unit), i.e.,\n  an additive category $M$ endowed with a ring homomorphism\n  \\[k\\to\\End(\\id_M),\\]\n  replacing $\\bZ$ by $k$ in formulas \\eqref{eq:93.1} and\n  \\eqref{eq:93.3}. The ``abelianization'' questions touched at in\n  yesterday's notes still make sense in terms of ``$k$-linearization''\n  -- a notion much in the spirit of our introduction of a general\n  basic localizer \\scrW, as the very notion of $k$-linearization will\n  give rise to a corresponding basic localizer $\\scrW_k$\\ldots\n\\end{remark}\n\nLet's come back to the case when $B=A\\op$, $A$ being a small category,\nand to our question about chain complexes\n\\[L_\\bullet \\quad\\text{in}\\quad \\Ch_\\bullet(\\Add(A\\op))\\]\ngiving rise to a commutative diagram \\eqref{eq:92.20} (p.\\\n\\ref{p:328}), up to isomorphism. A pair\n\\[(L_\\bullet,\\lambda),\\]\nwhere $L_\\bullet$ is a chain complex as above, and $\\lambda$ a\ncompatibility isomorphism for the square in \\eqref{eq:92.20}, could be\nsuggestively called an \\emph{abelianizator} for the small category\n$A$. The question of existence, and uniqueness up to homotopy say, of\nan abelianizator for $A$ seems especially relevant when $A$ is a test\ncategory say, and hence \\Ahat{} modelizes homotopy types. In any case,\nin terms of an abelianizator we get an additive functor\n\\begin{equation}\n  \\label{eq:93.5}\n  L:\\Ahatab\\to\\Ch_\\bullet\\Ab,\\tag{5}\n\\end{equation}\nand the question arises whether this is compatible with weak\nequivalences and quasi-isomorphisms; maybe even if this is not\nautomatic, we should insist it holds when defining the notion of an\nabelianizator. When this is OK, then by passing to localizations we\ndeduce from \\eqref{eq:93.5} a functor\n\\begin{equation}\n  \\label{eq:93.6}\n  \\HotabOf_A\\to\\HotabOf,\\tag{6}\n\\end{equation}\ni.e., a functor \\eqref{eq:92.14} as looked for in yesterday's notes,\ngiving rise to the commutative diagram \\eqref{eq:92.19} (p.\\\n\\ref{p:328}) -- whereas commutativity of diagrams of the type\n\\eqref{eq:92.15} (p.\\ \\ref{p:326}) looks less obvious.\n\nWhen\\pspage{333} $A$ is a finite product of copies taken from among\nthe three standard test categories $\\Simplex$, $\\Square$, $\\Globe$,\nthe standard chain complex structure on multicomplexes does furnish us\nwith a \\emph{``canonical'' abelianizator} for $A$, which we may denote\nby $L_\\bullet^A$ (as we did yesterday for $A=\\Simplex$). This\n``standard'' abelianizator has some very remarkable extra features\nwhich I would like to pin down, which had caused our rather narrow\nfocus in the notes of two days ago (section \\ref{sec:91}).\n\n\\namedlabel{cond:93.a}{a)}\\enspace\nThere is a ``dimension map''\n\\begin{equation}\n  \\label{eq:93.7}\n  \\dim:\\Ob A\\to \\bN.\\tag{7}\n\\end{equation}\nIt can be described (in the particular case above at any rate) in\nterms of the intrinsic category structure of $A$, by associating to\nevery $a$ in $A$ the ordered set\n\\begin{equation}\n  \\label{eq:93.8}\n  i(a)=\\text{set of subobjects of $a$ in $A$.}\\tag{8}\n\\end{equation}\n(NB\\enspace not to be confused with subobjects of $a$ in \\Ahat, namely\nsieves in $a$). This is an ordered set with a largest object (namely\n$a$ itself), and which turns out to be finite (in the particular cases\nconsidered), hence of finite combinatorial dimension (equal to the\ndimension of the geometrical realization $\\abs{i(a)}$), and we have\n\\begin{equation}\n  \\label{eq:93.9}\n  \\dim(a)=\\dim i(a).\\tag{9}\n\\end{equation}\n\n\\namedlabel{cond:93.b}{b)}\\enspace\nThe $n$'th component $L_n$ of $L_\\bullet^A=L_\\bullet$ is given by\n\\begin{equation}\n  \\label{eq:93.10}\n  L_n = \\bigoplus_{\\dim(a)=n} a\\tag{10}\n\\end{equation}\n(where the direct sum of course is taken in $\\Add(A\\op)$ as in\n\\eqref{eq:93.2} above), which makes sense when we assume (as is the\ncase in our example) that the map \\eqref{eq:93.7} is ``finite'', i.e.,\nhas finite fibers. For instance, in all our ``standard'' cases, there\nis just \\emph{one} object of $A$ which is of dimension $0$, and this\nis also the final object.\n\n\\namedlabel{cond:93.c}{c)}\\enspace\nThe differential operator\n\\begin{equation}\n  \\label{eq:93.11}\n  d_n:L_n\\to L_{n-1}\\tag{11}\n\\end{equation}\ncan be obtained in the following way. We have only to describe $d_n$\non each summand $a$ of $L_n$, i.e., by \\eqref{eq:93.10} on each $a$ in\n\\begin{equation}\n  \\label{eq:93.12}\n  A_n=\\set[\\big]{a\\in\\Ob A}{\\dim a=n}.\\tag{12}\n\\end{equation}\nIn view of \\eqref{eq:93.3}, this restriction $d_n\\mid a$ can be\ndescribed as a linear combination of elements in the disjoint sum of\nthe sets\n\\[\\Hom(b,a),\\quad\\text{with}\\quad b\\in A_{n-1}\\quad (\\text{$a\\in A_n$\n  fixed}).\\]\nThis\\pspage{334} being clear, the non-zero coefficients which occur in\nthis linear combination are all $\\pm1$, and moreover the maps which\ntarget $a$\n\\[b\\to a\\quad(b\\in A_{n-1})\\]\nwhich occur with non-zero coefficient are exactly \\emph{all\n  monomorphisms} from objects $b$ in $A_{n-1}$ into $a$. Thus, the\ndifferential operators are known, when we know, for all monomorphisms\nin $A$\n\\begin{equation}\n  \\label{eq:93.13}\n  \\partial:b\\to a,\\quad\\text{with}\\quad \\dim a=\\dim b+1\\tag{13}\n\\end{equation}\n(the so-called \\emph{``boundary maps''}), the corresponding\ncoefficients\n\\begin{equation}\n  \\label{eq:93.14}\n  \\varepsilon_{\\partial}\\in\\{\\pm1\\}.\\tag{14}\n\\end{equation}\nInstinct tells us, at this point, that we may get into trouble, when\ntrying to define (in a more or less general case) boundary operations\nin such a way, because of the ambiguity in the definition of\nsubobjects, namely, because of possible \\emph{existence of\n  isomorphisms which may not be identities}. But precisely, in the\nstandard cases we are copying from, \\emph{any isomorphism is an\n  identity}!\n\n\\namedlabel{cond:93.d}{d)}\\enspace\nFor describing the ``signatures'' \\eqref{eq:93.14}, in one of the\n``standard'' cases, we still need to remark that for any $a$ in $A$,\nwe have\n\\begin{equation}\n  \\label{eq:93.15}\n  \\text{$i(a)$ is an $n$-cell, with $n=\\dim(a)$,}\\tag{15}\n\\end{equation}\nand the choice of the signatures will be determined by a choice of\norientations\n\\begin{equation}\n  \\label{eq:93.16}\n  \\text{$\\omega_a$ an \\emph{orientation} of the $n$-cell\n    $\\abs{i(a)}$,}\\tag{16}\n\\end{equation}\n(a notion which could be given a purely combinatorial definition, by\ninduction on the dimension of a given ordered set whose geometrical\nrealization is a variety\\ldots). We then get a the \\emph{``Stokes\n  rule''}\n\\begin{flalign}\\label{eq:93.17}\n  &&&\\parbox[t]{0.9\\textwidth}{For a boundary map $\\partial:b\\to a$,\n  $\\varepsilon_{\\partial}=+1$ if{f} $\\omega_b$ is ``induced'' à la\n  Stokes by $\\omega_a$, via the induced orientation on the boundary of\n  $i(a)$ (which is the union of the images of all $i(b)$'s, for all\n  boundary operations with target $a$).}\n  \\tag{17}\n\\end{flalign}\n\nWhether or not we are in a ``standard'' case, if $A$ is any category\nsuch that for any object $a$ of $A$, the ordered set $i(a)$ of its\nsubobjects in $A$ is finite, and its geometrical realization is an\n$n$-cell (call $n$ the ``dimension'' of $a$), and if moreover for a\ngiven $n$, the set $A_n$ of objects with dimension $n$ is finite, and\nalso (to be on the safe side!) assuming that all isomorphisms are\nidentities, then for \\emph{any} choice of orientations\n\\eqref{eq:93.16}, giving rise to a system of\\pspage{335} signatures\n\\eqref{eq:93.13} by the ``Stokes rule'' \\eqref{eq:93.17}, the\ncorresponding operators \\eqref{eq:93.11} do turn the family $(L_n)$\ninto a chain complex, namely we have the relations\n\\begin{equation}\n  \\label{eq:93.18}\n  d_{n-1}d_n=0.\\tag{18}\n\\end{equation}\nThis follows immediately from the well-known anti-commutativity\nproperty of (twofold) induction of orientation on boundaries.\n\nThings are a little more delicate if we don't assume that isomorphisms\nare identities, even if (by compensation) we should insist that two\ndistinct objects are never isomorphic. To define $d_n$, we then must\n\\emph{choose}, for any subobject $b$ of dimension $n-1$ of an object\n$a$ of dimension $n$, just \\emph{one} representative monomorphism\n\\eqref{eq:93.13} of $b$. The coherence condition then needed in order\nto get \\eqref{eq:93.18} is that any square diagram\n\\begin{equation}\n  \\label{eq:93.19}\n  \\begin{tikzcd}[sep=tiny]\n    & c\\ar[dl]\\ar[dr] & \\\\\n    b\\ar[dr] && b'\\ar[dl] \\\\\n    & a &\n  \\end{tikzcd}\n  \\tag{19}\n\\end{equation}\nmade up with such restricted boundary maps, should commute -- a\nsomewhat delicate condition, presumably hard to ensure, for the\nchoices involved for defining the ``strict'' boundary maps in $A$.\n\nIn one case as in the other, we are very close of course to the set-up\nenvisioned in section \\ref{sec:91} -- it wouldn't be hard even to fit\nthe case considered here into this set-up, if we make the slight extra\nassumption that any map in $A$ factors into an\nepimorphism-with-section, followed by a monomorphism (which is true\nindeed in the ``standard'' cases), which will ensure that for varying\n$a$, $i(a)$ is indeed a functor with values in \\Ord, as stated in\nloc.\\ cit. But from the point of view of construction of\nabelianizators, it would seem that the existence of the functor\n\\begin{equation}\n  \\label{eq:93.20}\n  i:A\\to\\Ord\\tag{20}\n\\end{equation}\nis irrelevant.\n\nOur main question now, of course, is about \\emph{the chain complex\n  $L_\\bullet$ being an abelianizator or not}. The question is\ninteresting even in the standard cases, by choosing the orientations\n\\eqref{eq:93.16} in a way different from the standard one. Are the\ncorresponding chain complexes in $\\Add(A\\op)$ necessarily\nchain-homotopic?\n\nIt just occurs to me that indeed, between the chain\ncomplexes\\pspage{336}\n\\begin{equation}\n  \\label{eq:93.22}\n  L_\\bullet^\\omega = ((L_n)_{n\\in\\bN},(d_n^\\omega)_{n\\in\\bN})\\tag{22}\n\\end{equation}\nassociated to all possible systems of orientations\n\\begin{equation}\n  \\label{eq:93.23}\n  \\omega=(\\omega_a)_{a\\in\\Ob(A)}\\tag{23}\n\\end{equation}\nof the various cells $i(a)$, there is a canonical \\emph{transitive\n  system} of isomorphisms, by defining the isomorphism\n\\begin{equation}\n  \\label{eq:93.24}\n  u_{\\omega,\\omega'}:L_\\bullet \\tosim L_\\bullet'\\tag{24}\n\\end{equation}\nfor two different choices $\\omega,\\omega'$ of systems of orientations,\nby\n\\begin{equation}\n  \\label{eq:93.25}\n  u_{\\omega,\\omega'} \\mid a=\\varepsilon_a^{\\omega,\\omega'}\\,\n  \\id_a,\\quad \\varepsilon_a^{\\omega,\\omega'}\\in\\{\\pm1\\},\\tag{25}\n\\end{equation}\nwhere the sign $\\varepsilon_a^{\\omega,\\omega'}$ is equal to $+1$ or\n$-!$, \\emph{according to whether $\\omega_a$ and $\\omega_a'$ are equal\n  or not}. It is immediate that \\eqref{eq:93.24} then is an\nisomorphism componentwise, respecting degrees, and commuting to the\nrespective differential operators. Transitivity of the isomorphisms\n\\eqref{eq:93.24} for a triple $(\\omega,\\omega',\\omega'')$ is equally\nimmediate. This implies that by this transitive system of\nisomorphisms, \\emph{we may identify all the chain complexes}\n$L_\\bullet^\\omega$ in $\\Add(A\\op)$ to a single chain complex,\ncanonically isomorphic to each $L_\\bullet^\\omega$, and which we may\njust designate by $L_\\bullet$. This chain complex now is defined\nintrinsically in terms of the category structure of $A$ (up to\ncanonical isomorphism), in the ``safe'' case at any rate when every\nisomorphism in $A$ is an identity, so that in the construction of\n$L_\\bullet^\\omega$ there enters no other choice besides\n$\\omega$. Otherwise as seen above (precedent page), we must still\nsuitably choose the so-called ``strict'' boundary operators\n\\eqref{eq:93.13}, among all monomorphisms $b\\hookrightarrow a$ in $A$\nsuch that $\\dim a=\\dim b+1$.\n\nIn the first case say (isomorphisms being identities), all conditions\nconsidered for $A$ are stable under finite products, that's why in\nterms of the three standard cases of $\\Simplex$, $\\Square$ and\n$\\Globe$, we could construct others by taking finite products. The\nthree standard test categories may be viewed as particularly\n``economic'' of skillful ways of ``cutting out'' a suitable bunch of\ncellular decompositions, and of eliminating automorphisms (by total\nordering of vertices and the like\\ldots), so as to ensure: a)\\enspace\nthat isomorphisms in $A$ are identities, b)\\enspace the canonical\nchain complex $L_\\bullet$ in $\\Add(A\\op)$ is an abelianizator, and\nc)\\enspace $A$ moreover is a strict test category, and even a\ncontractor. On the other hand, as all these conditions (plus the\ncondition \\eqref{eq:93.15} of course about the $i(a)$'s representing\n$n$-cells)\\pspage{337} are stable under taking products (of finite\nnon-empty families of categories $A_i$), hence in terms of the three\nstandard cases, the possibility of satisfying them too by the\n``multistandard'' test categories. I wonder if there are any other\nways (up to equivalence). If we take categories such as\n$\\widetilde\\Simplex$ (non-ordered simplices), we still get\ncontractors, but objects have non-trivial automorphisms, and if we\ntake categories such as \\Simplexf{} (ordered simplices without\ndegeneracy operations, only boundary maps), it is true that\nisomorphisms are identities, but the category is no longer a test\ncategory but only a weak one.\n\nIf we do not insist on the rigidity assumption (isomorphisms are\nidentities), but on suitable choice of so-called ``\\emph{strict}\nboundary operations'' within $A$, then it would seem after all that we\ndo have a lot more elbow freedom than it seemed by the end of our\nreflections on that matter two days ago (cf.\\ p.\\ \\ref{p:318}), where\nthe picture of the relevant data and corresponding construction of\nchain complexes was still a little confused. Let now $A$ be the\ncategory called $A_0$ in loc.\\ cit.  We don't have to modify it in\norder to introduce orientations of cells $i(a)$ as extra structure and\ntake account of this in defining a new notion of maps. Therefore, it\nis clear that $A$ \\emph{just as it is, is a strict test category}\n(presumably \\emph{not} a contractor though). There is problem of\ncourse of isomorphisms which are not identities, and particularly of\nnon-trivial automorphisms -- for instance the object $I$ (playing the\npart of the unit segment) has a non-trivial automorphism, the\nelimination of which does not look so trivial! However, there\n\\emph{is} a rather evident way of cutting out \\emph{strict} boundary\nmaps, in a way as to satisfy the transitivity condition of p.\\\n\\ref{p:335} -- namely by taking boundary maps \\eqref{eq:93.13}\n$\\partial:b\\to a$ which are \\emph{inclusions} in the strict sense,\nnamely the inclusion map of a \\emph{subset} of $a$, endowed with the\ninduced order relation.\n\nThus, there are many other cases still than just multi-standard test\ncategories for getting a canonical chain complex $L_\\bullet$ in\n$\\Add(A\\op)$, and for which now the question makes sense as to whether\n$L_\\bullet$ is an abelianizator. In the construction above, we were\ncareful to assume that the full subcategory $A$ of \\Ord, besides\ncontaining $I$, was stable under finite products, so as to make sure\nit comes out as a test category. The silly thing is that this\ncondition is not satisfied by any one among the standard test\ncategories -- thus, it seems reasonable to try and\\pspage{338} replace\nit by a suitable substitute, such as the existence, of any two objects\n$a$ and $b$ in $A$, of a cellular subdivision of\n$\\abs{i(a)}\\times\\abs{i(b)}$, made up with cells of the type\n$\\abs{i(c)}$, and inducing on the latter the given cellular structure\nof $\\abs{i(c)}$. The problem is now (besides getting or not an\nabelianizator $L_\\bullet$) \\emph{whether $A$ is at any rate a weak\n  test category} (in view of the example \\Simplexf, we can't expect\nnow of course to get an actual test category). Maybe I'll come back to\nthis later, when writing down a proof for \\Simplexf{} being a weak\ntest category, i.e., a more general result along these lines should\ncome out alongside.\n\n\\begin{remarks}\n  I feel the canonical chain complex $L_\\bullet$ in $\\Add(A\\op)$\n  constructed in this section, under suitable assumptions on the small\n  category $A$, merits a name of its own. We may call it the\n  \\emph{standard abelianizator} of $A$ -- but this is reasonable only\n  if it turns out that in all cases when it can be constructed, it is\n  an abelianizator indeed. Another convenient name may be the\n  \\emph{Dold-Puppe chain complex}, as in the three standard cases, the\n  standard Dold-Puppe construction of the ``normalization'' of an\n  abelian complex (ss say) can be viewed as being performed in the\n  ``universal'' case, namely for $A\\op\\to\\Add(A\\op)$, and the\n  corresponding ``full'' chain complex, namely $L_\\bullet$ -- with\n  this grain of salt though that we still have to enlarge $\\Add(A\\op)$\n  slightly, so as to make stable under taking direct summands\n  corresponding to projectors. But then it occurs to me that the name\n  of Dold-Puppe chain complex is much more suitable for the\n  \\emph{result of normalization} applied to $L_\\bullet$, which (if I\n  got it right) is the ``new'' complex discovered by Dold-Puppe,\n  together with the inverse construction, whereas $L_\\bullet$ had\n  already been known for ages (even if not under its universal\n  disguise\\ldots).\n\\end{remarks}\n\n% 94\n\\hangsection[Afterthought (continued): retrospective on the ``De Rham\n\\dots]{Afterthought\n  \\texorpdfstring{\\textup(continued\\textup)}{(continued)}:\n  retrospective on the ``De Rham complex with divided powers'' and on\n  some wishful thinking about linearization of homotopy types and\n  arbitrary ground-ring extension in homotopy types.}\\label{sec:94}%\nIn the last section, as in the two preceding days, our emphasis with\nabelianization of homotopy types has been to look at it in terms of\nmore or less arbitrary test categories and the corresponding\nelementary modelizers, and even in terms of arbitrary small\ncategories. This has causes as spinning a kind of dream for a while,\nwith the Whitehead and Dold-Puppe theorems and generalized boundary\nmaps as our main thread. Now this reminds me of a rather different\nline of thoughts tied up with abelianization, quite independently of\nplaying around with variable modelizers -- a question which has been\nintriguing me for a very long time now, ever since I got acquainted a\nlittle with the very notion of homotopy types, and the corresponding\nhomology and\\pspage{339} cohomology invariants. This is the question\nof \\emph{how far a homotopy type can be expressed in terms of homology\n  or cohomology invariants} (or both together), plus \\emph{some\n  relevant extra structure}, the most important surely being\ncup-products in cohomology (or, dually, ``interior'' operation of\ncohomology on homology).\\scrcomment{I wonder whether AG knew of the\n  Steenrod algebra\\ldots yes, see below} Once the notion of derived\ncategories of various kinds had become familiar, in the early sixties,\nthe question would appear as expressing, or recovering, a homotopy\ntype, namely an object in the (highly non-abelian) ``derived\ncategory'' \\Hot, in terms of its abelianization in\n$\\HotabOf=\\D_\\bullet\\Ab$, \\emph{endowed with suitable extra\n  structure}. It was about clear that this extra structure had to\ninclude, as its main non-commutative item, the fundamental group\n$\\pi$, so as to allow for description of homology and cohomology\ninvariants with twisted coefficients. The most natural candidate for\nexpressing this would be the chain complex associated to the universal\ncovering, viewed as an object in the derived category\n\\begin{equation}\n  \\label{eq:94.26}\n  \\D_\\bullet(\\bZ(\\pi))\\tag{26}\n\\end{equation}\nof chain complexes of modules over the group ring $\\bZ(\\pi)$. Another\nimportant structural item, giving rise to all cup-products with\nnon-twisted coefficients, is the diagonal map for the abelianization\n\\[L_\\bullet\\quad\\text{in}\\quad \\HotabOf=\\D_\\bullet\\Ab,\\]\nnamely a map\n\\begin{equation}\n  \\label{eq:94.27}\n  L_\\bullet \\to L_\\bullet \\Lotimes L_\\bullet,\\tag{27}\n\\end{equation}\nwhere $\\Lotimes$\\scrcomment{aka the $\\Tor$ functor} is the ``total''\nleft derived functor of tensor product. This map is subjected to\nsuitable conditions, concerning mainly commutativity and\nassociativity. In case of a non-$1$-connected space, i.e., $\\pi\\ne1$,\nit shouldn't be hard combining the two structural items so as to get a\nstructure embodying at any rate cup-products with arbitrary twisted\ncoefficients. One key question in my mind, which I never really looked\ninto, was whether these two structures were enough in order to\nreconstruct entirely (up to canonical isomorphism) the (pointed,\n$0$-connected) homotopy type giving rise to it, and hence also any\nother homotopy invariants, such as ``operations'' on cohomology and\nthe like, K-invariants, etc.\n\nIf I got it right, it has been known now for quite a while that even\nfor a $1$-connected homotopy type, so that the relevant structure\nreduces to \\eqref{eq:94.27}, that this is \\emph{not} quite enough for\nrecovering the homotopy type, maybe not even the rational homotopy\ntype. I believe I first got this from Sullivan, namely\nthat\\pspage{340} what was needed for recovering a $1$-connected\nrational homotopy type was not merely \\eqref{eq:94.27} (where now\n$L_\\bullet$ is an object of $\\D_\\bullet(\\bQ)$ rather than of\n$\\D_\\bullet(\\bZ)=\\D_\\bullet\\Ab$), which reduces more or less (under\nsuitable finiteness assumption) to knowing the rational cohomology\nring, but an anti-commutative and associative \\emph{differential graded\nalgebra} over $\\bQ$ (giving rise to \\eqref{eq:94.27} by\nduality). Thus, $1$-connected rational homotopy types are expressible\nas objects of the derived category defined in terms of such algebras,\nand the obvious notion of quasi-isomorphism for these. To any space or\nss~set, Sullivan associates a corresponding \\emph{``De Rham complex''}\nwith rational coefficients, in order to get a functor from rational\nhomotopy types to the derived category obtained from those algebras --\nand (if I remember it right) this is an equivalence of categories,\nprovided one restricts to $1$-connected homotopy types, and\ncorrespondingly to $1$-connected algebras. Probably somebody must have\nexplained to me by then (it was in 1976 more or less) why not every\neligible differential algebra could be recovered (up to isomorphism in\nthe derived category) by the corresponding cohomology algebra, namely\nwhy it was not necessarily isomorphic to the latter, endowed with zero\ndifferential operator; I am afraid I forgot it since! Also, it was\nwell-known by the informed people (as I was told too) that there where\nobstructions against expressing the multiplicative structure in\ncohomology with (say) integer coefficients, in terms of an\nanti-commutative differential graded $\\bZ$-algebra; so there was no\nhope, I was informed, for defining something like a ``De Rham complex\nwith integer coefficients'' for an arbitrary topological space.\n\nAll this was very interesting indeed -- still, I found it hard to\nbelieve that, while succeeding in constructing De Rham complexes with\nrational coefficients for arbitrary spaces, by looking at the\nalgebraic De Rham complex on the enveloping affine space for the\nvarious singular simplices of a space, that the same could not be\nachieved with integral coefficients. Of course, the basic Poincaré\nlemma for algebraic differential forms was no longer true, however\nthis reminded me strongly of a similar difficulty met with in\nalgebraic geometry, and which is overcome by working with suitable\n``divided power structures'' -- as Poincaré's lemma becomes valid when\nreplacing usual polynomials (as coefficients for differential forms)\nby ``polynomials with divided powers''. Then I got quite excited and\ninvolved in a formalism of De Rham complexes with divided powers\nfor\\pspage{341} arbitrary semisimplicial sets, which took me a few\nweeks to work out and alongside getting back into homotopy and\ncohomology formalism again. I had the feeling that this structure, or\nthe technically more adequate dual ``coalgebra'' structure, might well\nturn out to be the more refined version of \\eqref{eq:94.27} needed for\nrecovering homotopy types -- or at any rate $1$-connected ones. I gave\na talk about the matter at IHES while things were still hot in my mind\n-- but it doesn't seem it went really through. It doesn't seem this\nstructure (which was worked out independently by someone else too, I\nunderstand) has become a familiar notion to\ntopologists.\\scrcomment{I'm guessing the reference is to \\textcite{Cartan1976} and\n  \\textcite{Miller1978}\\ldots anyhow, there has been many developments since\n  concerning Witt vectors, crystalline cohomology, etc.\\ldots} Maybe\none reason is that most topologists and homotopy theorists never\nreally got acquainted with the formalism of derived categories -- and\nit seems that moreover, by the mid-seventies, it had even become\naltogether unfashionable and ``mal vu'' to make any mention of them,\nlet alone work with them, also among some of the people who during\nsome time had been helping develop it. Now one of the main points I\nwas making in that talk was a somewhat delicate property of derived\ncategories of abelian categories, with respect to binomial\ncoefficients -- too bad!\n\nI have not heard since about any work done in this direction I am\nreflecting about now (somewhat retrospectively) -- namely recovering\nhomotopy types from their abelianization, \\emph{plus} extra\nstructure. For all I know, \\emph{the} relevant structure may well be\nthe differential algebra with divided powers structure embodied by the\nDe Rham complex (with a bigraduation however instead of just a\ngraduation), or its coalgebra version -- viewed as defining an object\nof a suitable derived category. (Of course, when there is a\nfundamental group $\\pi$ around, one will have to look at a slightly\nmore complex structure still, involving operations of $\\pi$, by\nlooking at the De Rham complex of the universal covering.) If it is\njust the matter of describing homotopy types in terms of other models\nthan semisimplicial complexes, it must be admitted that the new models\nare of incomparably more intricate description than the complexes!\nThere \\emph{is} however one feature of it which greatly struck me by\nthat time, and still seems to me quite intriguing, namely \\emph{that\n  this structure, although definitely not ``abelian'' anymore} (due to\nmultiplication as well as to divided power structure), \\emph{makes a\n  sense over any commutative ground ring} (or even scheme, etc.). When\nthis ring is $\\bQ$, the ``models'' we get modelize rational homotopy\ntypes, which was the starting point of my reflections\\pspage{342}\nabout seven years ago. Replacing $\\bQ$ by a more general ring, this\nsuggests that \\emph{there might exist a notion of ``homotopy types''\n  over any ground ring $k$} -- and a corresponding notion of ground\nring extension for homotopy types. For abelianizations of homotopy\ntypes, this is particularly ``obvious'', as being just the functorial\ndependence of the derived category $\\D_\\bullet(k)$ with respect to the\nground ring $k$, corresponding to ring extension in a chain\ncomplex. For a week or two I played around with this idea, which on\nthe semisimplicial level tied in with expressing homotopy types of\nsome simple spaces (such as standard $K(\\pi,n)$ spaces and fibrations\nbetween these) in terms of some simple \\emph{semisimplicial schemes}\n(affine and of finite type over $\\Spec(\\bZ)$), by taking $\\bZ$-valued\npoints of these; ring extension $\\bZ\\to k$ was interpreted in the\nscheme-theoretic sense.\n\nI didn't go on very long, as soon after I was taken by personal\nmatters and never took up the matter later -- and maybe it was an\naltogether unrealistic or silly attempt. If I remember it right, the\nidea lurking was something of this kind, that \\emph{there was a\n  functor from \\Hot{} to} (if not an equivalence of \\Hot{} with\\ldots)\n\\emph{a suitable derived category of some category of semisimplicial\n  schemes over} $\\Spec(\\bZ)$, and that the base change intuition, as\nsuggested by the abelianized theory or by the subtler ``divided power\nDe Rham theory'', would reflect in naive base change $\\bZ\\to k$ for\nschemes.\n\nI was then looking mainly at $1$-connected structures, but there was\nan idea too that nilpotent fundamental groups might fit into the\npicture, with the hope that such a group (under suitable restrictions,\nfinite presentation and torsion freeness say) could be expressed in a\ncanonical way in terms of an affine nilpotent group scheme of finite\ntype over $\\Spec(\\bZ)$, by taking the integral points of the\nlatter. It seems (if I remember right) that this is not quite true\nthough -- that one couldn't hope for much better than getting a\nnilpotent algebraic group scheme \\emph{over $\\bQ$} -- and that one\nwould recover the discrete group one started with only ``up to\ncommensurability''. Possibly, there may be \\emph{an equivalence\n  between localization of the category of nilpotent groups as above\n  \\textup(with respect to monomorphisms with image of finite\n  index\\textup) and affine nilpotent connected algebraic group schemes\n  over $\\bQ$}, or equivalently, group schemes whose underlying scheme\nis isomorphic to standard affine space.\n\n\\bigbreak\n\n\\presectionfill\\ondate{7.7.}\\pspage{343}\\par\n\n% 95\n\\hangsection{Contractors}\\label{sec:95}%\nAfter this cascade of ``afterthoughts'' on abelianization of homotopy\ntypes, it is time now to resume some more technical work, and get\nthrough with this unending part \\ref{ch:IV}, in accordance with the\nshort range working program I had come to four days ago (section\n\\ref{sec:92}, p.\\ \\ref{p:320}). I'll take up the three topics stated\nthere -- namely contractors, induced structures, and ``miscellaneous''\n-- in that order, as reviewed previously. Thus, we'll start with\ncontractors. I have in mind now mainly the definition of contractors,\nand a few basic facts following easily from what is already known to\nus.\n\nThe first thought that comes to my mind is to define a contractor as a\ncategory $A$ such that the set $\\Ob(A)$ of all objects of $A$ is a\ncontractibility structure on $A$, i.e., that there exists a\ncontractibility structure on $A$ for which every object in $A$ is\ncontractible. The trouble with this definition is that it makes the\nimplicit assumption that $A$ is stable under finite products -- as the\nnotion of a contractibility structure was defined only in a category\nsatisfying this extra assumption (cf.\\ section \\ref{sec:51},\n\\ref{subsec:51.D}). Now, this assumption is \\emph{not} satisfied by\nthe three standard test categories, including $\\Simplex$, which surely\nwe do want to consider as contractors! The next thought then,\nsuggested by this reflection, is to embed $A$ into \\Ahat{} to supply\nthe products which may be lacking in $A$, and demand there exist a\ncontractibility structure on \\Ahat, such that the objects in $A$ be\ncontractible and moreover generate; or, what amounts to the same, that\nfor the homotopy interval structure on \\Ahat{} defined by intervals\ncoming from $A$ as a generating family, the objects of $A$ are\ncontractible (which implies that this structure ``is'' indeed a\ncontractibility structure). This condition (in the more general case,\nwhen $A$ appears as a full subcategory of any larger category $M$) has\nbeen restated in wholly explicit terms as the \\emph{``basic\n  assumption''} \\ref{cond:51.Bas.4} on a set of objects, in order that\nit generate a contractibility structure (section \\ref{sec:51}, p.\\\n\\ref{p:118}). It is immediate that in the case when $A$ itself is\nstable under finite products in the ambient category, that this\ncondition is intrinsic to $A$ and just amounts to the first definition\nwe had in mind.\n\nStill,\\pspage{344} we will call a category $A$ satisfying the\ncondition \\ref{cond:51.Bas.4} with respect to the embedding\n\\begin{equation}\n  \\label{eq:95.1}\n  A\\hookrightarrow\\Ahat\n  \\tag{1}\n\\end{equation}\na \\emph{precontractor}, as we'll expect something more still from a\ncontractor, which will be automatically satisfied in the particular\ncase when $A$ is stable under finite products. Roughly speaking, we\nwant to have a satisfactory relation between contractibility and\nasphericity in \\Ahat{} -- we'll make this more precise below. For the\ntime being, let's dwell just a little more on the notion of a\nprecontractor.\n\nA second thought about contractors, coming alongside with the first,\nis that for any full embedding of $A$ into a larger category\n\\begin{equation}\n  \\label{eq:95.2}\n  f:A\\to M, \\quad\\text{$M$ stable under finite products,}\\tag{2}\n\\end{equation}\n$f(A)$ should generate in $M$ a contractibility structure. In the\nparticular case when $A$ is stable under finite products (and hence\nthe notion of a precontractor, already defined, coincides with the\nnotion of a contractor), this is indeed so provided $A$ is a\n(pre)contractor, and moreover $f$ commutes to finite products. When\n$A$ is just assumed to be a precontractor (without an assumption about\nstability of $A$ under products), we'll assume in compensation that\n$M$ is stable under small direct limits, which allows to take the\ncanonical extension $f_!$ of $f$ to \\Ahat{} in a way commuting to\ndirect limits\n\\begin{equation}\n  \\label{eq:95.3}\n  f_!:\\Ahat\\to M,\\tag{3}\n\\end{equation}\nand we can now state: \\emph{if $f_!$ commutes to finite products}\n(cf.\\ prop.\\ \\ref{prop:85.1}, \\ref{it:85.prop1.a}, p.\\ \\ref{p:281}),\n\\emph{then $f(A)$ generates a contractibility structure in $M$.} This\nstatement is true even without assuming that the functor $f$ is fully\nfaithful (and follows immediately from the criterion\n\\ref{cond:51.Bas.4} of p.\\ \\ref{p:118}); however, in the particular\ncase when $f$ is fully faithful, we have a handy criterion (prop.\\\n\\ref{prop:85.2}, p.\\ \\ref{p:283}) for $f_!$ to commute to finite\nproducts, namely that $f(A)$ be a strictly generating subcategory of\n$M$, or equivalently, that the functor\n\\begin{equation}\n  \\label{eq:95.4}\n  f^*:M\\to\\Ahat\\tag{4}\n\\end{equation}\n(right adjoint to $f_!$) be fully faithful. In this case, we may\nidentify $M$ (up to equivalence) to a full subcategory of \\Ahat{}\ncontaining $A$, and the fact that $f(A)$ generates a contractibility\nstructure in $M$ follows immediately directly (without having to rely\non existence of direct limits in $M$, nor even existence of $f_!$). To\nsum up:\n\\begin{propositionnum}\\label{prop:95.1}\n  Let\\pspage{345} $A$ be a small category, $M$ a category stable under\n  finite products, $f:A\\to M$ a functor, we assume $A$ is a\n  \\emph{precontractor}. Then $f(A)$ generates a contractibility\n  structure in $M$ in each of the following three cases:\n  \\begin{enumerate}[label=\\alph*),font=\\normalfont]\n  \\item\\label{it:95.prop1.a}\n    $A$ stable under finite products, and $f$ commutes to these.\n  \\item\\label{it:95.prop1.b}\n    There exists a functor $f_!:\\Ahat\\to M$ extending $f$, and\n    commuting to final object and binary products in \\Ahat{} of\n    objects in $A$\\kern1pt.\n  \\item\\label{it:95.prop1.c}\n    The functor $f$ is fully faithful and strictly generating.\n  \\end{enumerate}\n\\end{propositionnum}\n\nOf course, the validity of the conclusion in either case\n\\ref{it:95.prop1.b} or \\ref{it:95.prop1.c}, for fixed $A$ and variable\n$M$ and $f$, \\emph{characterizes} the property for $A$ of being a\nprecontractor, and the same for \\ref{it:95.prop1.a} if we assume\nbeforehand that $A$ is stable under finite products. Thus, we may view\nthe proposition \\ref{prop:95.1} as the most comprehensive statement of\nthe meaning of this property.\n\\begin{propositionnum}\\label{prop:95.2}\n  Let $A$ be a precontractor. Let \\Ahatc{} be the set of contractible\n  objects in \\Ahat{} for the contractibility structure generated by\n  the subcategory $A$\\kern1pt, \\Ahatas{} \\textup(resp.\\ \\Ahatlocas\\textup) the\n  set of aspheric \\textup(resp.\\ locally aspheric -- cf.\\ p.\\\n  \\ref{p:250}\\textup) objects of \\Ahat, $h$ the homotopy structure on\n  \\Ahat{} associated to the contractibility structure \\Ahatc, i.e.,\n  generated by the intervals in \\Ahat{} coming from $A$\\kern1pt. As usual,\n  \\scrWA{} denotes the set of weak equivalences in \\Ahat{} -- it is\n  understood here that the basic localizer $\\scrW\\subset\\Fl\\Cat$ is\n  $\\scrWoo$ = usual weak equivalence. The following conditions on $A$\n  are equivalent:\n  \\begin{description}\n  \\item[\\namedlabel{it:95.prop2.i}{(i)}]\n    \\Ahat{} is totally aspheric \\textup(i.e., $\\Ob A\\subset\\Ahatlocas$\\textup).\n  \\item[\\namedlabel{it:95.prop2.ii}{(ii)}]\n    The asphericity structure \\Ahatas{} on \\Ahat{} is generated by the\n    contractibility structure \\Ahatc.\n  \\item[\\namedlabel{it:95.prop2.iiprime}{(ii')}]\n    $\\Ahatc\\subset\\Ahatas$.\n  \\item[\\namedlabel{it:95.prop2.iidblprime}{(ii'')}]\n    $\\Ahatc\\subset\\Ahatlocas$.\n  \\item[\\namedlabel{it:95.prop2.iii}{(iii)}]\n    Any $h$-homotopism is in \\scrWA{} \\textup(i.e., \\scrWA{} is\n    ``strictly compatible'' with the homotopy structure $h$,\n    \\textup(cf.\\ section \\ref{sec:54}\\textup), i.e., $h\\le\n    h'=h_{\\scrWA}$\\textup).\n  \\item[\\namedlabel{it:95.prop2.iv}{(iv)}]\n    The homotopy structure $h$ is equal to the homotopy structure\n    $h'=h_W$ associated to $W=\\scrWA$ \\textup(cf.\\ section\n    \\ref{sec:54}\\textup). \n  \\end{description}\n\\end{propositionnum}\n\\begin{proof}[Proof of proposition]\n  Immediate from what is known to us, via\n  \\[\\text{\\ref{it:95.prop2.i}} \\Rightarrow\n  \\text{\\ref{it:95.prop2.ii}} \\Rightarrow\n  \\text{\\ref{it:95.prop2.iiprime}} \\Leftrightarrow\n  \\text{\\ref{it:95.prop2.iidblprime}} \\Rightarrow\n  \\text{\\ref{it:95.prop2.i}}\n  \\quad\\text{and}\\quad\n  \\text{\\ref{it:95.prop2.ii}} \\Rightarrow\n  \\text{\\ref{it:95.prop2.iv}} \\Rightarrow\n  \\text{\\ref{it:95.prop2.iii}} \\Rightarrow\n  \\text{\\ref{it:95.prop2.i}.}\\]\n\\end{proof}\n\\begin{definitionnum}\\label{def:95.1}\n  A\\pspage{346} small category $A$ is called a \\emph{contractor} if it\n  is a precontractor, and if moreover it is totally aspheric or,\n  equivalently, satisfies one of the equivalent condition\n  \\ref{it:95.prop2.i} to \\ref{it:95.prop2.iv} of prop.\\\n  \\ref{prop:95.2}.\n\\end{definitionnum}\n\nEquivalently, this also means that\n\\begin{equation}\n  \\label{eq:95.5}\n  \\Ob A \\subset \\Ahatc\\sand \\Ahatlocas,\\tag{5}\n\\end{equation}\ni.e., every object in $A$ is contractible and locally aspheric, where\nthe set \\Ahatc{} of ``contractible'' objects of \\Ahat{} is defined in\nterms of the homotopy interval structure $h$ generated by all\nintervals in \\Ahat{} coming from objects in $A$. (Thus structure is\nnot necessarily a contractibility structure, but it is when $A$ is a\nprecontractor, namely $\\Ob A\\subset\\Ahatc$.)\n\nThe most trivial example of a contractor is the final category\n$\\Simplex_0$, and more generally, any category equivalent to it\n(NB\\enspace a category equivalent to a precontractor resp.\\ to a\ncontractor is again a precontractor resp.\\ a contractor). Such a\ncontractor will be called \\emph{trivial}. For a trivial contractor\n$A$, we get an equivalence\n\\[\\Ahat\\equeq\\Sets.\\]\n\nIf\n\\[ (M,M\\subc)\\]\nis a contractibility structure, and $A\\subset M$ any small full\nsubcategory of $M$ generating the contractibility structure, then $A$\nis a precontractor, hence a contractor if{f} $A$ is totally aspheric,\nwhich will be the case if $A$ is stable in $M$ under binary products,\na fortiori if it is stable under finite products, i.e., contains\nmoreover a final object of $M$. Thus, \\emph{the contractibility\n  structure of $M$ can always be generated by a full subcategory $A$\n  of $M$ which is a contractor}.\n\nApart from these two examples, the most interesting examples of\ncontractors are of course the three standard test categories\n$\\Simplex$, $\\Square$ and $\\Globe$, and also their finite\nproducts. Note that the notion of a precontractor or of a contractor\nis clearly stable under finite products.\n\\begin{propositionnum}\\label{prop:95.3}\n  Let $A$ be a precontractor, assume $A$ non-trivial, i.e.,\n  non-equivalent to the final category. Then $A$ contains a separating\n  interval, and hence it is a \\textup(strict\\textup) test category if\n  $A$ is tot.\\ asph., i.e., is a contractor.\n\\end{propositionnum}\n\\begin{proof}\n  As any object of $A$ has a section (over $e_\\Ahat$), it follows\n  immediately that any non-empty object of \\Ahat{} has a section too,\n  hence \\emph{any non-empty subobject of $e_\\Ahat$ is equal to\n    $e_\\Ahat$}. This implies that for any\\pspage{347} interval\n  \\[\\bI=(I,\\delta_0,\\delta_1)\\]\n  in \\Ahat, either \\bI{} is separating, i.e.,\n  $\\Ker(\\delta_0,\\delta_1)$ is the empty object of \\Ahat, or\n  $\\delta_0=\\delta_1$. If no interval coming from $A$ was separating,\n  this then would just mean that any two sections (over $e_\\Ahat$) of\n  an object $I$ of $A$ are equal. By the definition of the homotopy\n  structure in \\Ahat{} generated by these intervals, this would imply\n  that any homotopism in \\Ahat{} is an isomorphism, and hence that any\n  contractible object for this structure is isomorphic to the final\n  object $e_\\Ahat$. As by assumption on $A$ all objects of $A$ are\n  contractible, this would mean that $A$ is trivial, which is against\n  our assumptions, qed.\n\\end{proof}\n\\begin{corollarynum}\\label{cor:95.1}\n  Let $(M,M\\subc)$ be a contractibility structure.\n  \\begin{enumerate}[label=\\alph*),font=\\normalfont]\n  \\item\\label{it:95.cor1.a}\n    The following conditions are equivalent \\textup(and will be\n    expressed by saying that this given contractibility structure is\n    \\emph{trivial}\\textup):\n    \\begin{enumerate}[label=(\\roman*),font=\\normalfont]\n    \\item\\label{it:95.cor1.a.i}\n      Two maps in $M$ which are homotopic are equal.\n    \\item\\label{it:95.cor1.a.ii}\n      Any homotopism in $M$ is an isomorphism.\n    \\item\\label{it:95.cor1.a.iii}\n      Any homotopy interval in $M$ is ``trivial'', i.e., any two\n      homotopic sections of an object of $M$ are equal.\n    \\item\\label{it:95.cor1.a.iv}\n      Any contractible object of $M$ is a final object, i.e., $M\\subc$\n      is just the set of all final objects of $M$.\n    \\item\\label{it:95.cor1.a.v}\n      Any two sections of a contractible object are equal.\n    \\end{enumerate}\n  \\item\\label{it:95.cor1.b}\n    Assume\\pspage{348} the contractibility structure $M\\subc$\n    non-trivial, i.e., there exists an interval\n    \\[\\bI=(I,\\delta_0,\\delta_1)\\quad\\text{with}\\quad I\\in M\\subc,\n    \\delta_0\\ne\\delta_1.\\]\n    Then for any small category $A$ and any functor\n    \\[i:A\\to M\\]\n    factoring through $M\\subc$, the interval $i^*(\\bI)$ in \\Ahat{} is\n    separating. Hence if \\textup(for a given basic localizer\n    \\scrW\\textup) $i$ is totally \\scrW-aspheric \\textup(cf.\\ theorem\n    \\ref{thm:79.1} cor.\\ \\ref{cor:79.1} p.\\ \\ref{p:252}\\textup), hence\n    $i^*(I)$ is totally aspheric in \\Ahat, then $A$ is a \\scrW-test\n    category. In particular, if $A$ is totally \\scrW-aspheric and $i$\n    is $M\\suba$-\\scrW-aspheric, then $A$ is a strict \\scrW-test category.\n  \\end{enumerate}\n\\end{corollarynum}\n\\begin{proof}\n  Part \\ref{it:95.cor1.a} is a tautology in terms of section\n  \\ref{sec:51}. For part \\ref{it:95.cor1.b}, to prove that $i^*(\\bI)$\n  is separating, we only have to check that for any $a$ in $A$, the\n  two compositions\n  \\[\\begin{tikzcd}[cramped,sep=huge]\n    a \\to i^*(e_M) \\simeq e_\\Ahat\n    \\ar[r,shift left=1pt,\"\\ensuremath{i^*(\\delta_0),i^*(\\delta_1)}\"]\\ar[r,shift right=2pt] &\n    i^*(I)\n  \\end{tikzcd}\\]\n  are distinct, or what amounts to the same by the definition of\n  $i^*$, that the compositions\n  \\[\\begin{tikzcd}[cramped,sep=small]\n    i_!(a) \\eqdef x \\to e_M\n    \\ar[r,shift left=2pt]\\ar[r,shift right=2pt] &\n    I\n  \\end{tikzcd}\\]\n  are distinct. As $x$ is in $M\\subc$, it has a section over $e_M$, so\n  it is enough to check that the compositions with $e_M\\to x$ are\n  distinct, which just means that $\\delta_0\\ne\\delta_1$, qed.\n\\end{proof}\n\\begin{remarks}\n  \\namedlabel{rem:95.1}{1)}\\enspace Part \\ref{it:95.cor1.b} of the\n  corollary replaces cor.\\ \\ref{cor:79.3} on page \\ref{p:253}, which\n  is a little monster of incongruity (as I just discovered) -- namely,\n  two of the assumption on \\bI{} made there (namely that \\bI{} be a\n  multiplicative interval, and $I\\in\\Ob C$) are useless if we assume\n  just $I$ contractible, moreover the awkward separation assumption\n  made there just reduces by the trivial argument above to the\n  assumption $\\delta_0\\ne\\delta_1$!\n\n  \\namedlabel{rem:95.2}{2)}\\enspace It should be noted that the\n  homotopy structure on \\Ahat{} envisioned in th.\\ \\ref{thm:79.1} of\n  section \\ref{sec:79} (p.\\ \\ref{p:252}) is \\emph{not} defined as in\n  the present section, in terms of intervals in \\Ahat{} coming from\n  $A$ (call this structure $h$), but as\n  \\[ h' = h_\\scrWA\\]\n  defined in terms of intervals in $\\Ahatlocas$; this depends a priori\n  on the choice of \\scrW, as it has to because th.\\ \\ref{thm:79.1}\n  gives a criterion for the functor $i$ to be $M\\suba$-\\scrW-aspheric\n  which does depend on \\scrW. (It surely won't be the same if we take\n  $\\scrW=\\scrWoo=$ usual weak equivalence, or $\\scrW=\\Fl(\\Cat)$ hence\n  $\\scrWA=\\Fl(A)$ and\\pspage{349} the condition that $i$ be\n  $M\\suba$-\\scrW-aspheric is always satisfied!) However, let's assume\n  $A$ to be totally \\scrW-aspheric and every object of $A$ has a\n  section (over the final object $e_\\Ahat$ of \\Ahat) or, what amounts\n  to the same, every ``non-empty'' object of \\Ahat{} has a section --\n  we'll say in this case $A$ is \\emph{``strictly totally\n    \\scrW-aspheric''} (compare section \\ref{sec:60}, p.\\ \\ref{p:149},\n  in the particular case $\\scrW=\\scrWoo$, and with \\Ahat{} replaced by\n  an arbitrary topos). Let's assume moreover that \\scrW{} satisfied\n  \\ref{loc:4}. In this case, the homotopy structure $h'=h_\\scrWA$ does\n  not depend on the choice of \\scrW, namely it is the so-called\n  ``canonical homotopy structure''\n  \\[h'' = h_\\Ahat\\]\n  of the (strictly totally $0$-connected) category \\Ahat{} (cf.\\\n  section \\ref{sec:57}), which in the special case of a category\n  \\Ahat{} can also be defined as the homotopy structure $h_\\scrWz$\n  associated to ${\\scrWz}_A$, where \\scrWz{} is the coarsest basic\n  localizer satisfying \\ref{loc:4}, i.e.,\n  \\[\\scrWz=\\set[\\big]{f\\in\\Fl\\Cat}{\\text{$\\piz(f)$ bijective}}.\\]\n  The proof of this fact $h'=h''$, i.e.,\n  \\[h_\\scrWA = h_\\Ahat \\quad ({}=h_{\\scrWz})\\]\n  is essentially the same as for the similar prop.\\ (section\n  \\ref{sec:60}, p.\\ \\ref{p:149}). The condition \\ref{loc:4} on \\scrW,\n  i.e., $\\scrW\\subset\\scrWz$ clearly implies\n  \\[h_\\scrWA\\subset h_{{\\scrWz}_A},\\]\n  and to get the opposite inequality, for which we'll use the\n  assumption on $A$, we only have to prove that for any $0$-connected\n  object $K$ of \\Ahat, any two sections are ($h'=h_\\scrWA$)-homotopic,\n  a fortiori (as $h\\le h'$ by the assumption of total\n  \\scrW-asphericity of $A$) it is enough to prove they are\n  $h$-homotopic. Now this follows from lemma \\ref{lem:82.2}, p.\\\n  \\ref{p:268}, applied to $\\scrC=\\Ahat$, $C=A$.\n\\end{remarks}\n\nThe\\pspage{350} preceding reflections thus prove the following\nafterthought to theorem \\ref{thm:79.1} of section \\ref{sec:79}:\n\\begin{propositionnum}\\label{prop:95.4}\n  Let $(M,M\\subc)$ be a contractibility structure, $A$ a small\n  category, $i:A\\to M$ a functor factoring through $M\\subc$. Let\n  moreover \\scrW{} be a basic localizer satisfying\n  \\textup{\\ref{loc:4}}. We assume $A$ \\emph{strictly totally\n    \\scrW-aspheric}, i.e., totally \\scrW-aspheric and moreover any\n  object of $A$ has a section \\textup(over $e_\\Ahat$\\textup).\n  \\begin{enumerate}[label=\\alph*),font=\\normalfont]\n  \\item\\label{it:95.prop4.a}\n    The homotopy structure $h_\\scrWA$ on \\Ahat{} is equal to the\n    canonical homotopy structure $h_\\Ahat$ defined by $0$-connected\n    intervals, and equal also to the homotopy structure $h$ defined by\n    intervals coming from $A$:\n    \\begin{equation}\n      \\label{eq:95.6}\n      h=h_\\scrWA=h_\\Ahat.\\tag{6}\n    \\end{equation}\n  \\end{enumerate}\n  In what follows, we assume \\Ahat{} endowed with this homotopy\n  structure, and denote by \\Ahatc{} the set of all contractible object\n  in \\Ahat. We equally endow \\Ahat{} with its canonical\n  \\scrW-asphericity structure, and $M$ with the \\scrW-asphericity\n  structure associated to its contractibility structure $M\\subc$. With\n  these conventions:\n  \\begin{enumerate}[label=\\alph*),font=\\normalfont,start=2]\n  \\item\\label{it:95.prop4.b}\n    The following conditions on $i$ are equivalent, where\n    \\[i^*:M\\to\\Ahat\\]\n    is the functor defined as usual in terms of $i$:\n    \\begin{enumerate}[label=(\\roman*),font=\\normalfont]\n    \\item\\label{it:95.prop4.b.i}\n      $i^*$ is compatible with the homotopy structures \\textup(cf.\\\n      criteria on pages \\ref{p:251}--\\ref{p:252}\\textup), which can be\n      expressed also by\n      \\[i^*(M\\subc)\\subset\\Ahatc\\]\n      \\textup(a condition independent from \\scrW, in view of\n      \\textup{\\ref{it:95.prop4.a})}.\n    \\item\\label{it:95.prop4.b.ii}\n      $i$ is \\scrW-aspheric, i.e.,\n      \\[M_\\scrW \\subset (i^*)^{-1}(A\\uphat_\\scrW)\\]\n      \\textup(where $M_\\scrW$ and $A\\uphat_\\scrW$ are the sets of\n      \\scrW-aspheric objects in $M$ and in \\Ahat\\textup).\n    \\item\\label{it:95.prop4.b.iii}\n      \\textup(For a given full subcategory $C$ of $M$ generating the\n      contractibility structure $M\\subc$\\textup):\n      \\[i^*(C)\\subset A\\uphat_\\scrWz = \\text{set of $0$-connected\n        objects of \\Ahat.}\\]\n    \\end{enumerate}\n  \\item\\label{it:95.prop4.c}\n    Assume these conditions hold, and moreover that the\n    contractibility structure of $M$ is non-trivial. Then $A$ is a\n    strict \\scrW-test category.\n  \\end{enumerate}\n\\end{propositionnum}\n\\begin{proof}\n  Part\\pspage{351} \\ref{it:95.prop4.a} has been proved in remark\n  \\ref{rem:95.2} above, and in view of th.\\ \\ref{thm:79.1}, p.\\\n  \\ref{p:252}, the equivalence of \\ref{it:95.prop4.b.i} and\n  \\ref{it:95.prop4.b.ii} is clear, hence also the equivalence with\n  \\ref{it:95.prop4.b.iii} by applying loc.\\ cit.\\ to \\scrWz{} instead\n  of \\scrW. Part \\ref{it:95.prop4.c} now follows from prop.\\\n  \\ref{prop:95.3} cor.\\ \\ref{cor:95.1} \\ref{it:95.cor1.b}.\n\\end{proof}\n\\begin{corollary}\n  Under the conditions of \\textup{\\ref{it:95.prop4.c}} above, if\n  $M\\subc$ is \\scrW-modelizing, then $i$ is a \\scrW-test functor, and\n  induces an \\emph{equivalence}\n  \\[\\HotOf_{M,\\scrW} \\eqdef \\scrW_M^{-1} M \\tosimeq \\HotOf_{A,\\scrW}\n  \\eqdef \\scrWA^{-1}\\Ahat.\\]\n\\end{corollary}\n\n\\bigbreak\n\n\\presectionfill\\ondate{8.7.}\\par\n\n% 96\n\\hangsection{Vertical and horizontal topoi\\dots\n  \\texorpdfstring{\\textup(afterthought on\n    terminology\\textup)}{(afterthought on\n    terminology)}.}\\label{sec:96}%\nYesterday's notes have proceeded very falteringly, to my surprise,\nwhile everything seemed ready for smooth sailing. A number of times,\nafter going on for a page or two ``following my nose'' (as they say in\nGerman),\\scrcomment{I'm pretty sure that ``to follow one's nose'' is an\n  English idiom in the sense of following one's instinct, while the\n  meaning of going straight ahead is shared with the German ``der Nase nach\n  gehen''} or for half a page, it turned out it just wasn't right that\nway and I would feel quite stupid and put the silly pages away as\nscratchpaper and have another start. There wouldn't have been any\npoint dragging the poor reader (if there is still one left\\ldots)\nalong on my stumbling path, where it was a matter merely of getting\nsome technical adjustments right. Maybe it is just that attention was\ndistracted, perhaps precisely through this (partly mistaken, and\nanyhow not too inspiring) feeling that everything was kind of cooked\nalready, and what was left to do was just swallow! What came out in\nthe process was that finally things were not so clear yet in my mind\nas I thought they were. It is a frequent experience that whenever one\nwants to go ahead too quickly, one finds oneself dispersing stupidly a\nhell of a lot of energy\\ldots\n\nThere occurred to me some inadequacies with terminology. One is about\nthe property of certain categories (contractor or precontractors for\ninstance) that every object of $A$ has a section (over $e_\\Ahat$),\nwhich can be viewed also as a property of the topos $\\Ahat=\\scrA$,\nnamely that any ``non-empty'' object of the topos has a section. This\nis immediately seen (for any given topos \\scrA) to imply the property\nthat the final object $e_\\scrA$ has only the two trivial subobjects,\nthe ``empty'' and the ``full'' one -- or equivalently, that any\nsubtopos of the topos is either the empty of the full one, -- a\nproperty, too of obvious geometric significance. In case of a topos of\nthe type \\Ahat, one immediately sees the two properties are equivalent\n-- but this is not\\pspage{352} true for an arbitrary topos: for\ninstance the classifying topos $B_G$ of a discrete group $G$ has the\nsecond property, but visibly not the first unless $G$ is the unit\ngroup. (I recall that the category of sheaves on $B_G$ is the category\n\\Gsets{} of sets on which $G$ operates.) I feel both properties for a\ntopos merit a name. The first (every sheaf has a section) can be\nviewed as the strongest conceivable (I would think) global asphericity\nproperty for a topos, as far as $\\mathrm H^1$ goes at any rate, as the\n$\\mathrm H^1$ of $X$ with coefficients in \\emph{any} group object will\nbe zero. (But I confess I didn't try and look if any precontractor,\nsay, is aspheric\\ldots) The second property (every subtopos is\ntrivial) comes with a rather different flavor, it suggests the image\nof just one ``point'' -- and as a matter of fact, the étale topos of a\nscheme, say has this property if{f} it is reduced to a point. Such a\ntopos may called ``punctual'' (not to be confused though with some\nother meanings suggested by this word, such as being equivalent to the\ntopos defined by a one-point topological space, namely \\scrA{} being\nequivalent to \\Sets) or ``atomic'' (which has rather unpleasant\nconnotations though nowadays!), or maybe ``vertical'' (this image is\nsuggested by the $B_G$ above) -- the ``base'', i.e., the final object\nof \\scrA{} being very ``small'' (in terms of harboring subobjects), so\nthe inner structure is expressed like a kind of tower, related (in the\ncase of $B_G$) to the ``Galois tower'' of subgroups of $G$\\ldots The\ncorresponding notion of a ``horizontal'' topos is visibly the one when\n\\scrA{} admits the subobjects of the final object as a generating\nfamily. In terms of these definitions, a topos is horizontal and\nvertical if{f} it is either the ``empty'' or the ``final'' (or\n``one-point'') topos. This brings to mind that in the notion of\nverticality, we should exclude the ``empty'' topos (which formally\nsatisfies the condition -- every sheaf has a section). This brings to\nmy attention too that I certainly do not want to consider an empty\ncategory $A$ (defining the ``empty'' topos \\Ahat) as a precontractor,\nalthough formally (in terms of yesterday's definition) it is. Thus, I\nsuggest I'll introduce the following\n\\begin{definition}\n  A topos is called \\emph{vertical} if it is not an ``empty'' topos\n  (i.e., the category of sheaves on it is not equivalent to the final\n  category $\\Simplex_0$), and if moreover any open subtopos is either\n  the ``empty'' or the ``full'' one (hence the same for any subtopos,\n  whether open or not). A small category $A$ is called vertical, if\n  the associated topos (with category of sheaves \\Ahat)\n  is,\\pspage{353} or equivalently, if $A$ is non-empty and any object\n  of $A$ has a section (over $e_\\Ahat$). A topos is called\n  \\emph{horizontal} if the family of all subobjects of the final\n  object in the category of sheaves \\scrA{} is generating.\n\\end{definition}\n\nFor instance, the topos associated to a topological space is\nhorizontal -- in particular, an ``empty'' topos is horizontal. A topos\nis both horizontal and vertical if{f} it is a ($2$-)final topos, i.e.,\nequivalent to the topos defined by a one-point topological space\n(i.e., the category of sheaves is equivalent to \\Sets).\n\nThe property of verticality, I feel, is of interest in its own right,\nas exemplified notably by lemma \\ref{lem:82.2} p.\\ \\ref{p:268} (which\nwe used yesterday), and the related proposition of section\n\\ref{sec:60} (p.\\ \\ref{p:149}). It does not seem at all subordinated\nto notions such as total asphericity or total $0$-connectedness, and\ngoes in an entirely different direction -- thus, the terminology\n``\\emph{strictly} totally aspheric'' (or totally $0$-connected), which\nI still used yesterday (hesitatingly, I should say), is definitely\ninadequate. I would rather say ``totally aspheric (or totally\n$0$-connected) \\emph{and} vertical''.\n\nAnother point is about the terminology of \\emph{totally aspheric} and\n\\emph{locally aspheric} objects in a category \\Ahat{} (with respect to\na given basic localizer \\scrW), introduced in section \\ref{sec:79}\n(p.\\ \\ref{p:250}), and still used yesterday. This terminology does not\nseem inadequate by itself, I introduced it because it struck me as\nsuggestive (and the notions it refers to do deserve a name, in order\nto be at ease). The trouble here is that it conflicts with another\npossible meaning, in accordance with the principle insisted upon\nforcefully in the reflections of section \\ref{sec:66} -- namely that\nfor objects or arrows in \\Cat, or within a category \\Ahat, the\nterminology used for naming properties for these should be in\naccordance with the terminology used for the corresponding topoi or\nmaps of topoi. Now, we do have already the notions of a locally\naspheric and totally aspheric topos, which therefore should imply\nautomatically the meaning of these notions for an object of \\Cat{}\n(which was done satisfactorily months ago), or for an object of a\ncategory \\Ahat. But in the latter case, there is definitely conflict\nwith the terminology introduced on p.\\ \\ref{p:252}. This conflict has\nnot manifested itself yet in any concrete situation, while the\nunorthodox terminology has been used quite satisfactorily a number of\ntimes. Therefore, I would like to keep it, as long as I am not forced\notherwise.\n\n\\starsbreak\n\nWe\\pspage{354} were faced yesterday with three different homotopy\nstructures $h,h',h''$ on a category \\Ahat, for a given small category\n$A$, which make sense for any $A$, and which in case $A$ is a\ncontractor all coincide. The exact relationship between these\nstructures in more general cases has remained somewhat confused, and\nin order to dispel the resulting feeling of uneasiness, I took finally\nthe trouble today to write it out with some case. One of these\nstructures, $h'$, depends on the choice of a basic localizer \\scrW,\nwhereas the two others don't\\ldots\n\n\\bigbreak\n\\presectionfill\\ondate{12.7.}\\par\n\n% 97\n\\hangsection[``Projective'' topoi. Morphisms and bimorphisms of\n\\dots]{``Projective'' topoi. Morphisms and bimorphisms of\n  contractors.}\\label{sec:97}%\nI was interrupted in my notes by visiting friends arriving in close\nsuccession -- then since yesterday I have been busy mainly with letter\nwriting. Now, I am ready to take up the thread where I left it --\nnamely some afterthoughts to the reflections of section \\ref{sec:95}\non contractors.\n\nFirst an afterthought to the afterthoughts! I had introduced the name\n``\\emph{vertical} topos'' for a topos admitting only the two trivial\nopen subtopoi (page \\ref{p:352}), whereas the stronger property that\nevery ``non-empty'' sheaf has a section remained unnamed (which is no\nreal drawback as long as we are restricting to topoi of the type\n\\Ahat, where indeed the two notions coincide). Now, the latter\nproperty can be viewed as the property that every sheaf $F$ \\emph{such\n  that $F\\to e$ be epimorphic}, should admit a section. It is this\nlast property which does merit to ``be viewed as the strongest\nconceivable asphericity property for a topos'' as I commented on it\nlast Friday (p.\\ \\ref{p:352}). After I had written this down as a kind\nof selfevidence, a doubt turned up though and I qualified the comment\nby added ``as far as $\\mathrm H^1$ goes at any rate, as the $\\mathrm\nH^1$ with coefficients in \\emph{any} group object will be zero''. I\ndidn't pause then to see if the doubt was founded -- quite evidently\nit isn't, except for $\\mathrm H^0$, as it is clear by the usual shift\nargument, using embedding of an abelian sheaf into an injective one,\nthat if for given $k$ (here $k=1$) $\\mathrm H^k(X,F)=0$ for any\nabelian sheaf $F$, then the same holds for $\\mathrm H^n$ with any\n$n\\ge k$ -- i.e., the global cohomological dimension of $X$ is\n$<k$. This implies that any small vertical category (a fortiori any\n\\emph{precontractor}) is aspheric, provided it is $0$-connected,\nindeed its cohomology variants with values in \\emph{any} sheaf of\ncoefficients (not necessarily commutative as far as $\\mathrm H^1$\ngoes) are trivial.\n\nThe\\pspage{355} property for a topos $X$, with category of sheaves\n\\scrA, that any object $F$ in \\scrA{} covering the final object\n$e_\\scrA$ should have a section, can be expressed by saying that the\nlatter is a \\emph{projective} object in the category \\scrA. Following\nthe principle to use the same names for properties of a topos, and\ncorresponding properties of the final sheaf on it, we may call a topos\nwith the above property a \\emph{projective topos}. Thus, the\n``non-empty'' topoi such that every ``non-empty'' sheaf has a section,\nare exactly the topoi which are both vertical and projective.\n\n\\starsbreak\n\nHere is the promised ``exact relationship'' between the three standard\nhomotopy structures $h,h',h''$ on \\Ahat, where $A$ is any small\ncategory (cf.\\ end of section \\ref{sec:96}, p.\\ \\ref{p:354}):\n\\begin{equation}\n  \\label{eq:97.star}\n  \\begin{tabular}{@{}c@{}}\n    \\begin{tikzcd}[baseline=(O.base),row sep=small,column sep=large]\n      h \\ar[d,equal]\\ar[r,phantom,\"\\le\"{description}]\n      \\ar[r,invisible,\"(\\text{$A$ tot. \\scrW-asph.})\"{inner sep=1.2ex}]\n      &\n      h' \\ar[d,equal]\\ar[r,phantom,\"\\le\"{description}]\n      \\ar[r,invisible,\"(\\scrW\\subset\\scrWz)\"{inner sep=1.2ex}]\n      &\n      h'' \\ar[d,equal]\\ar[r,phantom,\"\\le\"{description}]\n      \\ar[r,invisible,\"(\\text{$A$ vertical})\"{inner sep=1.2ex}]\n      & h \\\\\n      |[alias=O]| h_{\\Ahat\\!,\\;A} & h_\\scrWA & h_{{\\scrWz}_A}=h_\\Ahat &\n    \\end{tikzcd},\n  \\end{tabular}\\tag{*}\n\\end{equation}\nwhere \\scrW{} is a given basic localizer. Above each one of the three\nconditional inequalities between homotopy structures $h,h',h''$ I\nwrote the natural assumption on $A$ or \\scrW{} validating it, and in\nthe diagram I have recalled the definition of the three homotopy\nstructures. Apropos the description $h=h_{\\Ahat\\!,\\;A}$, the notation\nused here is $h_{M,A}$ when $M$ is a category stable under finite\nproducts and $A$ a full subcategory, for designating the homotopy\nstructure on $M$ generated by intervals in $M$ coming from\n$A$. Apropos $h''=h_\\Ahat$, I recall the notation $h_M$ for\ndesignating the canonical homotopy structure on a category $M$\nsatisfying suitable conditions (section \\ref{sec:57}). Also, I recall\n\\[\\scrWz =\\set[\\big]{f\\in\\Fl\\Cat}{\\text{$\\piz(f)$ bijective}}.\\]\nThe diagram implies that if $\\scrW\\subset\\scrWz$, i.e., \\scrW{}\nsatisfies \\ref{loc:4}, and if moreover $A$ is vertical and totally\n\\scrW-aspheric, then all three homotopy structures coincide. Also,\ntaking $\\scrW=\\scrWz$, we see that $h=h''$ if $A$ is vertical and\ntotally $0$-connected, which is lemma \\ref{lem:82.2} of p.\\\n\\ref{p:268} for $\\Ahat$, $A$.\n\nFrom \\eqref{eq:97.star} it follows of course that if $A$ is a\ncontractor, then (for any \\scrW{} satisfying \\ref{loc:4}) the three\nhomotopy structures $h, h', h''$ on $\\Ahat$ coincide. In case the\ncontractor $A$ is not trivial, hence $A$ is\\pspage{356} a strict test\ncategory and \\Ahat{} is \\scrW-modelizing, it follows that \\Ahat{} is\neven a \\emph{canonical modelizer} (with respect to \\scrW), i.e.,\ndefined in terms of the \\scrW-asphericity structure associated to the\n``canonical'' homotopy structure $h''=h_\\Ahat$ on \\Ahat{} (cf.\\ prop.\\\n\\ref{prop:95.2} \\ref{it:95.prop2.ii} p.\\ \\ref{p:345}). These, for the\ntime being, together with the modelizers \\Cat{} and \\Spaces, are the\nmain examples we got of canonical modelizers. Presumably, stacks\nshould give another sizable bunch of canonical modelizers, not of the\ntype \\Ahat.\n\n\\starsbreak\n\nWe still have to say a word about morphisms between contractors $A,\nB$. The first thing that comes to my mind is that this should be a\nfunctor\n\\begin{equation}\n  \\label{eq:97.0}\n  f:A\\to B\\tag{0}\n\\end{equation}\nsuch that the corresponding functor\n\\begin{equation}\n  \\label{eq:97.1}\n  f^*:\\Bhat\\to\\Ahat\\tag{1}\n\\end{equation}\nshould be compatible with the homotopy structures, which can be\nexpressed, as we know, in manifold ways, the most natural one here\nbeing the following two\n\\begin{equation}\n  \\label{eq:97.2}\n  f^*(B) \\subset \\Ahatc\\tag{2}\n\\end{equation}\nor\n\\begin{equation}\n  \\label{eq:97.3}\n  f^*(\\Bhatc) \\subset \\Ahatc,\\tag{3}\n\\end{equation}\nwhich are both implied by the apparently weaker one\n\\begin{equation}\n  \\label{eq:97.4}\n  f^*(B) \\subset A\\uphat_{\\scrWz} \\eqdef \\text{set of $0$-connected\n    objects of \\Ahat,}\\tag{4}\n\\end{equation}\nand equivalently still, as $\\Ahatc\\subset A\\uphat_\\scrW\\subset\nA\\uphat_\\scrWz$ (where \\scrW{} is a basic localizer satisfying\n\\ref{loc:4}), to the condition\n\\begin{equation}\n  \\label{eq:97.5}\n  f^*(B)\\subset A\\uphat_\\scrW \\quad ( \\eqdef \\text{set of\n    \\scrW-aspheric objects of \\Ahat}).\\tag{5}\n\\end{equation}\nThus, the condition for $f$ to be a ``morphism of contractors'' just\nboils down to the long familiar \\emph{\\scrW-asphericity} of $f$, and\nimplies the following relation, apparently stronger than\n\\eqref{eq:97.5}:\n\\begin{equation}\n  \\label{eq:97.5prime}\n  B\\uphat_\\scrW=(f^*)^{-1}(A\\uphat_\\scrW).\\tag{5'}\n\\end{equation}\nThis comes almost as a surprise (after a four day interruption in\ncontact with the stuff!) -- but it occurs to me now that we got\nalready a more general statement with prop.\\ \\ref{prop:95.4} of\nsection \\ref{sec:95} (p.\\ \\ref{p:350}), which includes the\nsituation\\pspage{357} when instead of $f:A\\to B$, we got a functor\n\\begin{equation}\n  \\label{eq:97.6}\n  f:A\\to \\Bhat, \\quad\\text{factoring through \\Bhatc}\\tag{6}\n\\end{equation}\n(which need not factor through $B$), or equivalently a functor\n\\begin{equation}\n  \\label{eq:97.7}\n  f_!:\\Ahat\\to\\Bhat\\tag{7}\n\\end{equation}\ncommuting with small direct limits, or equivalently still, a functor\n$f^*$ in opposite direction, commuting with small inverse limits, but\nin the last two cases with the extra condition that $f_!(A)\\subset\n\\Bhatc$. We may want to extend the notion of morphism of contractors\nto include this situation, hence expressed by the two following\nconditions on a functor $f$ \\eqref{eq:97.6} or $f_!$ \\eqref{eq:97.7},\nor on the pair $(f_!,f^*)$ of adjoint functors\n\\begin{equation}\n  \\label{eq:97.8}\n  \\begin{cases}\n    f_!(A)\\subset\\Bhatc &\\\\\n    f^*(B)\\subset\\Ahatc &\\quad.\n  \\end{cases}\\tag{8}\n\\end{equation}\nHowever, in order for this notion to be stable under composition, we\nshould strengthen the first of the relations \\eqref{eq:97.8} into\n\\begin{equation}\n  \\label{eq:97.9}\n  f_!(\\Ahatc)\\subset\\Bhatc,\\tag{9}\n\\end{equation}\nwhich follows automatically whenever $f_!$ commutes to finite products\n(cf.\\ section \\ref{sec:85}), but may not follow from \\eqref{eq:97.8}\nin general, even in the case when $f$ factors through $B$, i.e., in\nthe case we start with a functor \\eqref{eq:97.0} $f:A\\to B$. Thus, we\nget \\emph{two} plausible notions of a morphism of contractors, neither\nof which implies the other, and I feel unable to predict which one\nwill prove the more useful. As far as terminology goes, it seems\nreasonable to reserve the name ``morphism of contractors'' to the\nfirst notion, as the second is adequately characterized as a\n\\emph{bimorphism} between the contractibility structures\n$(\\Ahat,\\Ahatc)$ and $(\\Bhat,\\Bhatc)$ defined by the contractors $A$\nand $B$ (cf.\\ section \\ref{sec:86}).\n\n\\bigbreak\n\\presectionfill\\ondate{16.7.}\\par\n\n% 98\n\\hangsection[Sketch of proof of \\protect\\smashSimplexf{} being a weak test\ncategory -- and \\dots]{Sketch of proof of\n  \\texorpdfstring{\\protect\\Simplexf{}}{Delta-f} being a weak test\n  category -- and perplexities about its being\n  aspheric!}\\label{sec:98}%\nNext point on my provisional program is induced structures\n(asphericity of contractibility structures) on a category $M_{/a}$,\nwhen one is given on $M$ -- but finally I decided to skip this, as\nthere was no urgent need for clarifying this and I am not writing a\ntreatise, thanks Gods! I felt more interested writing down the proof\nthat the category \\Simplexf{} of standard ordered simplices without\ndegeneracies is a weak test category, as announced months ago, in\nsection \\ref{sec:43}. It then\\pspage{358} seemed to come out rather\nsimply, but I didn't keep notes of the proof I thought I found, which\ncaused me spending now a day or two feeling a little stupid, as the\nstuff was resisting while I felt it shouldn't! It did come out in the\nend I guess -- and still I feel a little stupid, with the impression\nof having bypassed definitely some very simple argument which had\npresented itself as a matter of evidence by the end of March. On the\nother hand, I was led to reflect on some other noteworthy features of\nthe situation, so I don't feel I altogether have been loosing my time.\n\nThere are four main variants of categories of standard simplices,\ninserting into a diagram\n\\begin{equation}\n  \\label{eq:98.1}\n  \\begin{tabular}{@{}c@{}}\n    \\begin{tikzcd}[baseline=(O.base)]\n      \\Simplex\\ar[r,\"\\beta\"] & \\Simplextilde \\\\\n      \\Simplexf\\ar[u,\"\\alpha\"]\\ar[r,\"\\beta^{\\mathrm f}\"] &\n      |[alias=O]| \\Simplextildef\\ar[u,\"\\widetilde\\alpha\"] \n    \\end{tikzcd},\n  \\end{tabular}\\tag{1}\n\\end{equation}\nwhere \\Simplextilde{} denotes the category of non-ordered standard\nsimplices $\\Simplex_n$, and where the exponent $f$ in \\Simplexf{} and\n\\Simplextildef{} denotes restriction to maps which are injective,\nnamely compositions of boundary maps (plus symmetric in the\nnon-ordered case). I recall that $\\Simplex$ and \\Simplextilde{} are\ncontractors, wheres \\Simplexf{} and \\Simplextildef{} are not even test\ncategories. We'll see however that \\Simplexf{} is a \\emph{weak} test\ncategory, and presumably the same kind of argument should apply to\nprove that \\Simplextildef{} is a weak test category too. On the other\nhand, from the point of view of the modelizing story, the main common\nproperty of the four functors in \\eqref{eq:98.1} should be\nasphericity. However, I checked this for $\\alpha$ and $\\beta$ only, as\nthis was all I needed for getting the desired result on \\Simplexf. As\na matter of fact, $\\beta$ is even better than being aspheric, it is a\n\\emph{morphism of contractors}; more precisely still, for any object\n$E$ in \\Simplextilde, namely essentially a finite non-empty set,\nchoosing one point $a$ in $E$, one easily constructs an elementary\nhomotopy for $\\beta^*(E)$ from the identity map to the constant map\ndefined by $\\beta^*(a)$. I do not know on the other hand whether\n$\\beta$ defines a bimorphism between the canonical contractibility\nstructures on \\Simplexhat{} and \\Simplextildehat, namely whether\n$\\beta_!$ transforms contractible elements into contractible ones\n(which would be clear if we knew that $\\beta_!$ commutes to finite\nproducts).\n\nWe'll come back upon proof of asphericity of $\\alpha$, and show at\nonce how this implies that \\Simplexf{} is a weak test category, or\nequivalently, that the canonical functor\\pspage{359}\n\\[i_\\Simplexf : \\Simplexf\\to\\Cat\\]\nis aspheric, for the canonical asphericity structure on \\Cat. (I\nshould have noted that the asphericity statements are meant here in\nthe strongest possible sense, namely with respect to $\\scrW=\\scrWoo=$\nusual weak equivalence.) Now, for any $\\Simplex_n$ in \\Simplexf, the\ncategory\n\\[ i_\\Simplexf(\\Simplex_n) \\eqdef \\Simplexf_{/\\Simplex_n}\\]\nis canonically isomorphic to the category associated to the ordered\nset of all non-empty subsets of $\\Simplex_n$, hence we get a canonical\nisomorphism\n\\begin{equation}\n  \\label{eq:98.2}\n  i_\\Simplexf \\simeq \\widetilde i(\\beta\\alpha),\\tag{2}\n\\end{equation}\nwhere\n\\begin{equation}\n  \\label{eq:98.3}\n  \\widetilde i:\\Simplextilde\\to\\Cat\\tag{3}\n\\end{equation}\nis the standard test functor, associating to any non-ordered simplex\n$E$ the category associated to the ordered set of all non-empty\nsubsets of $E$. We know already (section \\ref{sec:34}) that\n$\\widetilde i$ is aspheric, i.e., $\\widetilde i^*$ transforms aspheric\nobjects of \\Cat{} into aspheric ones, hence the same holds for its\ncomposition with the aspheric functor $\\beta\\alpha$, hence also for\n$i_\\Simplexf$, qed.\n\nThus, we are left with proving that $\\alpha$ is aspheric, i.e., that\nthe categories\n\\begin{equation}\n  \\label{eq:98.star}\n  \\Simplexf_{/\\alpha^*(\\Simplex_n)}\\tag{*}\n\\end{equation}\nare aspheric. Now, let's denote by \\Simplexprimef{} the category\ndeduced from \\Simplexf{} by adding an initial object $\\varnothing$\n(which we may view as being the empty simplex), which defines an\n``open subcategory'' $U$, namely as sieve in \\Simplexprimef, in such a\nway that \\Simplexf{} appears as the ``closed subcategory'', i.e.,\ncosieve in \\Simplexprimef{} complementary to $U$. One immediately\nchecks that the category \\eqref{eq:98.star} is canonically isomorphic\nto\n\\begin{equation}\n  \\label{eq:98.starstar}\n  (\\Simplexprimef)^{n+1} \\setminus U^{n+1},\\tag{**}\n\\end{equation}\nwhere $U^{n+1}$ is the open subcategory defined by the initial object\nof the ambient category $(\\Simplexprimef)^{n+1}$. Now, asphericity of\n\\eqref{eq:98.starstar} and hence of \\eqref{eq:98.star} follows from\nthe following two lemmas:\n\\begin{lemmanum}\\label{lem:98.1}\n  The category \\Simplexf{} is aspheric.\n\\end{lemmanum}\n\\begin{lemmanum}\\label{lem:98.2}\n  Let $(X_i,U_i)_{i\\in I}$ be a finite non-empty family of pairs\n  $(X_i,U_i)$, where $X_i$ is a small category, $U_i$ an open\n  subcategory. We assume that for any $i$ in $I$, $X_i$ and the closed\n  complement $Y_i$ of $U_i$ in $X_i$ are aspheric. Let $X$ be the\n  product of the $X_i$'s, $U$ the products of the $U_i$'s,\\pspage{360}\n  then \\textup($X$ and\\textup) $X\\setminus U=Y$ are aspheric too.\n\\end{lemmanum}\n\\noindent\\emph{Proof of lemma \\ref{lem:98.2}:} by an immediate\ninduction, we are reduced to the case when $I$ has just two elements,\n$I=\\{1,2\\}$, but then $X\\setminus U$ can be viewed as the union of the\ntwo closed subcategories $X_1\\times Y_2$ and $X_2\\times Y_1$, whose\nintersection is $Y_1\\times Y_2$. As all three categories are aspheric\n(being products of aspheric categories), it follows by the well-known\nMayer-Vietoris argument that so is $X\\times U$, qed.\n\nThus, we are left with proving that \\Simplexf{} is aspheric. Somewhat\nsurprisingly, that's where I spent a number of hours not getting\nanywhere and feeling foolish! There is a very simple heuristic\nargument though involving the standard calculation of the cohomology\ninvariants of any semisimplicial ``complex'', in terms of the standard\nboundary operations: if we admit that the same calculations are valid\nwhen working with semisimplicial ``face complexes'', i.e., objects of\n\\Simplexfhat, then it is enough to apply this to the final object of\n\\Simplexfhat{} (including for computation of the non-commutative\n$\\mathrm H^1$ with constant coefficients) to get asphericity of\n\\Simplexf. As a matter of fact, this argument would give directly\nasphericity of $\\alpha$, bypassing altogether the categories\n\\eqref{eq:98.starstar} and lemmas \\ref{lem:98.1} and \\ref{lem:98.2}.\nApparently, I got a block against the down-to-earth computational\napproach to cohomology via semisimplicial calculations, and have been\ntrying to bypass it at all price -- and not succeeding! Then,\ncuriously enough, when finding no other way out than look at those\nboundary operations and try to understand what they meant (something I\nremember vaguely have been doing once ages ago!), this brought me back\nagain to the abelianization story of sections \\ref{sec:92} and\n\\ref{sec:93}, and to a more comprehensive way for looking at\n``abelianizators'', and get an existence and unicity statement for\nthese. (At any rate, for a suitably strengthened version of these.)\nThis seems to me of independent interest, and worth being written down\nwith some care.\n\n% 99\n\\hangsection{Afterthoughts on abelianization IV: Integrators.}\\label{sec:99}%\nWhen writing down (in sections \\ref{sec:92} and \\ref{sec:93}) some\nrambling reflections about ``abelianization'' and ``abelianizators'',\nthere has been a persistent feeling of uneasiness, which I kept\npushing aside, as I didn't want to spend too much thought on this\n``digression''. This uneasiness had surely something to do with the\nway abelianization (of an object $X$ say of an elementary modelizer\n\\Ahat) was handled, so that it was designed in a more or less\nexclusive way for embodying information about the ``homology\nstructure'' of the homotopy type modelized by $X$, or\\pspage{361}\nequivalently, to describe its cohomology invariants with arbitrary\n\\emph{constant} coefficients. Now, among the strongest reflexes I\nacquired in the past while working with cohomology, was systematically\nto look at coefficients which are arbitrary sheaves (abelian say), and\nto view constant or locally constant coefficients as being just\nparticular cases. This reflex has been remaining idle, not to say\nrepressed, during nearly all of the reflections of the last four\nmonths, due to the fact that in the whole modelizing story woven\naround weak equivalence, there was a rather exclusive emphasis on\nconstant and locally constant coefficients, disregarding any other\ncoefficients throughout. Probably, while reflecting on abelianization,\na more or less underground reminiscence must have been around of the\nsemisimplicial boundary operators having a meaning for computing\ncohomology of ``something'', with coefficients in arbitrary sheaves --\nand also that to get it straight, one had to be careful not to get\nmixed up in the variances. But I just didn't want to dive into all\nthis again if I could help it -- and now it is getting clear, after a\nday or two of feeling silly, that it can't be helped, and I'll have to\nwrite things down at last, however ``well-known'' they may be.\n\nLet $A$ be a small category. In section \\ref{sec:93} we defined an\n``abelianizator'' for $A$ to be a chain complex $L_\\bullet$ in the\nadditive envelope $\\Add(A\\op)$ of the category $A\\op$ opposite to $A$,\nsatisfying a suitable condition of commutativity (in the diagram\n\\eqref{eq:92.20} of p.\\ \\ref{p:328}), and endowed with a mild extra\nstructure $\\lambda$, expressing this commutativity. The function of an\nabelianizator in loc.\\ cit.\\ was essentially to allow for a\nsimultaneous ``computational'' description of the homology structure\nof the homotopy types stemming from a variable object $X$ in \\Ahat, or\nequivalently, to describe cohomology of such $X$ (as an object of a\nsuitable derived category say, to get it at strongest) with\ncoefficients in any (\\emph{constant}) ring or abelian\ngroup. Introducing by an independent symbol the opposite category\n\\begin{equation}\n  \\label{eq:99.1}\n  B=A\\op,\\tag{1}\n\\end{equation}\nI want now to establish a relationship between this property or\nfunction of a chain complex $L_\\bullet$ in $\\Add(B)$, involving\nobjects in \\Ahat{} and their abelianizations in \\Ahatab, with an\napparently different one, in terms of a variable object of \\Bhatab{}\n(\\emph{not} \\Ahatab{} this time!), namely expressing \\emph{cohomology\n  of $B$} (i.e., of the topos \\Bhat{} defined by $B$) with\ncoefficients in an \\emph{arbitrary} abelian presheaf $F$ on $B$, i.e.,\nan arbitrary object\\pspage{362} of \\Bhatab. I will first describe this\nproperty of (possible) function of a chain complex in $\\Add(B)$,\nforgetting for the time being the category $A=B\\op$ and the homotopy\ntypes defined by objects $X$ in \\Ahat. Once this property is well\nunderstood, it will be time to show it implies the previous one\nrelative to $A$ and objects of \\Ahat, and presumably is even\nequivalent with it.\n\nFirst, we'll have to interpret the category $\\Add(B)$, which was\nconstructed somewhat ``abstractly'' in section \\ref{sec:93} (as the\nsolution of a universal problem stated in section \\ref{sec:92}), as a\nfull subcategory of the category \\Bhatab{} of abelian presheaves on\n$B$. It will be useful to keep in mind the following diagram of\ncanonical functors\n\\begin{equation}\n  \\label{eq:99.2}\n  \\begin{tabular}{@{}c@{}}\n    \\begin{tikzcd}[baseline=(O.base)]\n      B\\ar[r,\"\\alpha_B\"] \\ar[d]\\ar[dr,\"\\beta_B\"] & \\Bhat\n      \\ar[d,\"\\Wh_B\"] \\\\\n      \\Add(B) \\ar[r,\"\\gamma_B\"'] & |[alias=O]| \\Bhatab\n    \\end{tikzcd},\n  \\end{tabular}\\tag{2}\n\\end{equation}\nwhere $\\alpha_B$ is the canonical inclusion, $\\Wh_B$ is the\nabelianization functor, $\\beta_B$ the composition of the two, and\n$\\gamma_B$ the \\emph{additive} functor factoring $\\beta_B$, in virtue\nof the universal property of $\\Add(B)$. This functor is defined up to\ncanonical isomorphism, and the lower triangle of \\eqref{eq:99.2} is\ncommutative, up to a given commutativity isomorphism. Also, we'll use\nthe composition of the following sequence of canonical equivalences of\ncategories:\n\\begin{multline*}\n  \\Bhatab = \\bHom(B\\op,\\Ab) \\tosim \\bHom(B,\\Ab\\op)\\op \\\\\n  \\tosim \\bHomadd(\\Add(B),\\Ab\\op)\\op\n  \\tosim \\bHomadd(\\Add(B)\\op,\\Ab),\n\\end{multline*}\ni.e., a canonical equivalence of category\n\\begin{equation}\n  \\label{eq:99.3}\n  \\Bhatab\\tosim\\bHomadd(\\Add(B)\\op,\\Ab),\\quad\n  F\\mapsto\\widetilde F,\\tag{3}\n\\end{equation}\nwhich is a particular case of\n\\begin{equation}\n  \\label{eq:99.3prime}\n  \\bHom(B\\op,M)\\tosim \\bHom(\\Add(B)\\op,M),\\tag{3'}\n\\end{equation}\nwhere $M$ is any additive category. If $F$ is an abelian presheaf on\n$B$, i.e., an object in the left-hand side of \\eqref{eq:99.3}, we'll\ndenote by\n\\begin{equation}\n  \\label{eq:99.4}\n  \\widetilde F: \\Add(B)\\op \\to \\Ab\\tag{4}\n\\end{equation}\nthe corresponding additive functor. Now, this functor can be\ninterpreted very nicely in terms of the functor $\\gamma_B$ in\n\\eqref{eq:99.2}, by the canonical isomorphism of abelian groups\n\\begin{equation}\n  \\label{eq:99.5}\n  \\widetilde F(L)\\tosim \\Hom_\\Bhat(\\gamma_B(L),F),\\tag{5}\n\\end{equation}\nfunctorial\\pspage{363} with respect to the pair $(F,L)$ in\n$\\Bhatab\\times\\Add(B)\\op$. This formula in turn implies easily that\nthe functor $\\gamma_B$ is \\emph{fully faithful}. Thus, we can\ninterpret $\\Add(B)$ as the full subcategory of \\Bhatab{} whose objects\nare all finite direct sums (in \\Bhatab) of objects of the type\n$\\Wh_B(b)$, with $b$ in $B$. In terms of this interpretation,\n$\\gamma_B$ is just an inclusion functor, and on the other hand, for\n$F$ in the ambient category \\Bhatab, $\\widetilde F$ is just the\nrestriction to the subcategory $\\Add(B)$ of the contravariant functor\non \\Bhatab{} represented by $F$.\n\nThis situation is the exact ``additive'' analogon of the situation of\n$B$ embedded in \\Bhat{} as a full subcategory, the functor on $B$\ndefined by an object $F$ of \\Bhat{} being the restriction to $B$ of\nthe contravariant functor on \\Bhat{} represented by $F$, i.e., an\nobject of $F(b)$ or $\\widetilde F(b)$ can (often advantageously) be\ninterpreted as a map in \\Bhat, $b\\mapsto F$. Moreover, the fact that\n\\[\\alpha_B^*: F\\mapsto \\widetilde F: \\Bhat \\tosim \\bHom(b\\op,\\Sets)\\]\nis an equivalence (in fact, an isomorphism even), is paralleled by the\nequivalence \\eqref{eq:99.3}, which can likewise be interpreted as\n$\\gamma_B^*$, or more accurately as the canonical factorization of the\npurely set-theoretic $\\gamma_B^*:\\Bhatab\\to\\bHom(\\Add(B)\\op,\\Sets)$\nthrough $\\bHomadd(\\Add(B)\\op,\\Ab)$\\ldots\n\nThe objects $L$ of the full subcategory $\\Add(B)$ of \\Bhatab{} have a\nvery strong common property, namely they are \\emph{projectives}, and\nthey are of \\emph{finite presentation} (``small'' in Quillen's\nterminology), namely for variable $F$ in \\Bhatab, the functor\n\\[F\\mapsto \\Hom_\\Bhatab(L,F)\\]\ncommutes with filtering direct limits. Both properties are immediate,\nand they nearly characterize the objects in $\\Add(B)$ -- more\naccurately, it is immediately checked that the projectives of finite\npresentation in \\Bhatab{} are exactly those which are isomorphic to\n\\emph{direct factors} of objects in $\\Add(B)$. It shouldn't be hard to\ncheck that the full subcategory of \\Bhatab{} made up with the\nprojectives of finite presentation can be identified up to equivalence\nto the ``Karoubi envelope'' of the category $\\Add(B)$ (obtained by\nformally adding images of projectors), or equivalently, can be\ndescribed as the solution of the $2$-universal problem defined by\nsending $B$ into categories which are, not only additive, but moreover\nstable under taking images of projectors (i.e., endomorphisms $u$ of\nobjects, such that $u^2=u$).\n\nWe'll\\pspage{364} henceforth identify $\\Add(B)$ to a full subcategory\nof \\Bhatab{} (by replacing the solution of the universal problem,\nconstructed in section \\ref{sec:95}, by the essential image in\n\\Bhatab{} say), and rewrite \\eqref{eq:99.5} simply as\n\\begin{equation}\n  \\label{eq:99.5prime}\n  \\widetilde F(L)\\simeq \\Hom(L,F),\\tag{5'}\n\\end{equation}\nthe $\\Hom$ being taken in \\Bhatab, category of abelian presheaves on\n$B$. Accordingly, if $L_\\bullet$ is a chain complex in $\\Add(B)$,\nhence in \\Bhatab, the corresponding \\emph{cochain} complex $\\widetilde\nF(L_\\bullet)$ in \\Ab{} can be interpreted as\n\\begin{equation}\n  \\label{eq:99.6}\n  \\widetilde F(L_\\bullet) \\simeq \\Hom^\\bullet(L_\\bullet,F),\\tag{6}\n\\end{equation}\nwhere the symbol $\\Hom^\\bullet$ means taking $\\Hom$'s componentwise.\n\nWhat we're after here is to find a \\emph{fixed} chain complex\n$L_\\bullet$ in $\\Add(B)$, such that for \\emph{any} abelian presheaf\n$F$ on $B$, the cochain complex \\eqref{eq:99.6} in \\Ab{} should be\nisomorphic (in the derived category $\\D^\\bullet\\Ab$ of cochain\ncomplexes in \\Ab{} with respect to quasi-isomorphisms) to the\n``integration'' of $F$ over the topos \\Bhat, i.e., to $\\mathrm\nR\\Gamma_B(F)$:\n\\begin{equation}\n  \\label{eq:99.star}\n  \\Hom^\\bullet(L_\\bullet,F)\\simeq \\mathrm R\\Gamma_B(F)\\text{\n    ?}\\quad(\\text{isom.\\ in $\\D^\\bullet\\Ab$}),\\tag{*}\n\\end{equation}\nnamely to the total right derived functor $\\mathrm R\\Gamma_B$ (taken\nfor the argument $F$) of the ``sections'' functor\n\\begin{equation}\n  \\label{eq:99.7}\n  \\Gamma_B(F) \\eqdef \\varprojlim_{B\\op} F.\\tag{7}\n\\end{equation}\nNow, using the fact that the components of the chain complex\n$L_\\bullet$ are projective, hence $\\Ext^i(L_n,F)=0$ for $i>0$ (any\n$n$, any $F$), we get at any rate a canonical isomorphism in\n$\\D^\\bullet\\Ab$, or in $\\D\\Ab$:\n\\begin{equation}\n  \\label{eq:99.8}\n  \\Hom^\\bullet(L_\\bullet,F)\\simeq \\mathrm R\\Hom(L_\\bullet,F),\\tag{8}\n\\end{equation}\ni.e., an interpretation of \\eqref{eq:99.6} as a ``hyperext''. Now,\nlet's remember that $\\mathrm R\\Gamma_B(F)$ (as on any topos) can be\ninterpreted equally as\n\\begin{equation}\n  \\label{eq:99.9}\n  \\mathrm R\\Gamma_B(F)\\simeq\\mathrm R\\Hom(\\bZ_B,F),\\tag{9}\n\\end{equation}\nwhere $\\bZ_B$ denotes the constant presheaf on $B$ with value\n$\\bZ$. Thus, the wished-for isomorphism \\eqref{eq:99.star} will follow\nmost readily from a corresponding isomorphism in $\\D_\\bullet(\\Bhatab)$\nbetween $L_\\bullet$ and $\\bZ_B$. But using again the fact that the\ncomponents of $L_\\bullet$ are projective, we see that to give a map in\nthe derived category of $L_\\bullet$ into $\\bZ_B$ amounts to the same\nas to give an \\emph{augmentation}\n\\begin{equation}\n  \\label{eq:99.10}\n  L_\\bullet\\to\\bZ_B,\\tag{10}\n\\end{equation}\nand the map is an isomorphism in $\\D_\\bullet(\\Bhatab)$\nif{f}\\pspage{365} the augmentation \\eqref{eq:99.10} turns $L_\\bullet$\ninto a (projective) \\emph{resolution} of $\\bZ_B$.\n\nWe now begin to feel in known territory again! Let's call\n``\\emph{integrator}'' on $B$ any projective resolution of $\\bZ_B$, and\nlet's call the integrator ``\\emph{special}'' (by lack of a more\nsuggestive name) if its components $L_n$ are in $\\Add(B)$, or what\namounts to the same, if it can be viewed as a chain complex in\n$\\Add(B)$, endowed with the extra structure \\eqref{eq:99.10}. Of\ncourse, $\\bZ_B$ is no longer in $\\Add(B)$ in general, and therefore\nthe data \\eqref{eq:99.10} has to be interpreted as a map $L_0\\to\\bZ_B$\nexternal to $\\Add(B)$, or equivalently (via \\eqref{eq:99.5prime}) as\nan object\n\\begin{equation}\n  \\label{eq:99.11}\n  \\lambda\\quad\\text{in}\\quad \\widetilde{\\bZ}_B(L_0) = \\bZ^{(I_0)},\\tag{11}\n\\end{equation}\nwhere $I_0$ is the set of indices used in order to express $L_0$ as\nthe direct sum in \\Bhatab{} of elements of $B$. We know, by the\ngeneral principles of homological algebra, that any two integrators\nmust be chain homotopic, hence, if they are special, as $\\Add(B)$ is a\nfull additive subcategory of \\Bhatab, they must be chain homotopic in\n$\\Add(B)$.\n\nAs for existence of integrators, it follows equally from general\nprinciples, as we know that \\Bhatab{} has ``enough projectives''\n(which is a very special feature indeed of \\Bhatab, coming from the\nfact that the topos \\Bhat{} has enough projectives, namely the objects\nof $B$\\ldots). It isn't clear though that there exists a special\nintegrator, because when trying inductively to construct the\nresolution $L_\\bullet$ of $\\bZ_B$ with components in $\\Add(B)$, it\nisn't clear that the kernel of $L_n\\to L_{n-1}$ is ``of finite type'',\nnamely is isomorphic to a quotient of an object of $\\Add(B)$ (or,\nequivalently, is a quotient of a projective of finite\npresentation). If we take for instance $B$ to be the one-object\ngroupoid defined by a group $G$, an integrator on $B$ is just a\nresolution of the constant $G$-module $\\bZ$ by projective\n$\\bZ[G]$-modules, and the integrator is special of{f} the components\nare even free modules of finite type -- I doubt such a resolution\nexists unless $G$ itself is finite. This example seems to indicate\nthat the existence of a special integrator for $B$ is a very strong\ncondition on $B$, of the nature of a (homological) finiteness\ncondition. Maybe this condition, more than most others, singles out\nthe three standard test categories and their finite products, from\narbitrary test categories (even strict ones and contractors\\ldots).\n\nEven in case a strict integrator doesn't exist for $B$, there is\na rather evident way out to get ``the next best'' in terms of\ncomputations, namely replacing the very much finitely restricted\ncategory $\\Add(B)$ by a larger category\\pspage{366}\n\\begin{equation}\n  \\label{eq:99.12}\n  \\Addinf(B)\\hookrightarrow \\Bhatab\\tag{12}\n\\end{equation}\ndeduced from $B$ by adding, not merely finite direct sums (and linear\ncombinations of maps), but equally infinite ones. The construction can\nbe given ``formally'' as in section \\ref{sec:93}, and it can be\nchecked that this category satisfies the obvious $2$-universal\nproperty with respect to functors\n\\[f:B\\to M\\]\nfrom $B$ to infinitely additive categories $M$ (namely additive\ncategories stable under direct sums), and functors $M\\to M'$ which are\nnot merely additive, but commute to small direct sums. Moreover, it is\nchecked that the category $\\Addinf(B)$ thus constructed embeds by a\nfully faithful functor into \\Bhatab{} as indicated in\n\\eqref{eq:99.12}, and hence can be identified up to equivalence to a\nfull subcategory of \\Bhatab. The formulas \\eqref{eq:99.5} and\n\\eqref{eq:99.5prime} are still valid, when $L$ is in $\\Addinf(B)$ only\ninstead of $\\Add(B)$. The objects of $\\Addinf(B)$ in \\Bhatab{} are\nstill projective (as direct sums of projectives), but of course no\nlonger of finite presentation. In compensation, any element in\n\\Bhatab{} is now a quotient of an object in $\\Addinf(B)$. As a\nconsequence, the projectives in \\Bhatab{} can be characterized as the\ndirect factor of objects of $\\Addinf(B)$, and presumably the full\nsubcategory of \\Bhatab{} made up with all projectives can again be\ndescribed (up to equivalence) as the Karoubi envelope of $\\Addinf(B)$,\nor equivalently, as the solution of the $2$-universal problem of\nsending $B$ into infinitely additive karoubian categories (karoubian =\nevery projective has an image, i.e., corresponds to a direct sum\ndecomposition). We may call an integrator $L_\\bullet$ for $B$ with\ncomponents in $\\Addinf(B)$ ``\\emph{quasi-special}''. We did just what\nwas needed in order to be sure now that there always exist\nquasi-special integrators; moreover, these integrators are unique up\nto chain homotopy in $\\Addinf(B)$. The interpretation \\eqref{eq:99.11}\nof the augmentation structure \\eqref{eq:99.10} on $L_\\bullet$ is still\nvalid in the quasi-special case, with the only difference that now the\nindexing set $I_0$ need not be finite anymore.\n\n\\bigbreak\n\n\\presectionfill\\ondate{17.6.}\\pspage{367}\\par\n\n% 100\n\\hangsection{Abelianization V: Homology versus cohomology.}\\label{sec:100}%\nYesterday I introduced the notion of an \\emph{integrator} for any\nsmall category $B$, to be just a projective resolution of $\\bZ_B$ in\nthe category \\Bhatab{} of all abelian presheaves on $B$, where $\\bZ_B$\ndenotes the constant presheaf with value $\\bZ$. Such an object in\n$\\Ch_\\bullet(\\Bhatab)$ exists, due to the existence of sufficiently\nmany projectives in \\Bhatab, and it is unique up to homotopism of\naugmented chain complexes, which encourages us to denote it by a\ncanonizing symbol, namely\n\\begin{equation}\n  \\label{eq:100.1}\n  L_\\bullet^B\\to \\bZ_B.\\tag{1}\n\\end{equation}\nAs will become clear in the sequel, $L_\\bullet^B$ can be viewed as\nembodying \\emph{homology properties} of $B$, i.e., of the topos\nassociated to $B$ (whose category of sheaves of sets is \\Bhat). The\nway we hit upon it though was in order to obtain a ``computational''\nway for computing \\emph{cohomology} of $B$ (i.e., of the associated\ntopos) with coefficients in any abelian presheaf $F$ in \\Bhatab, by a\ncanonical isomorphism\n\\begin{equation}\n  \\label{eq:100.2}\n  \\mathrm R \\Gamma_B(F) \\tosim \\Hom^\\bullet(L_\\bullet^B,F)\\tag{2}\n\\end{equation}\nin the derived category $\\D^\\bullet\\Ab$, where $\\Hom^\\bullet$ denotes\nthe cochain complex obtained by applying $\\Hom$ componentwise. Passing\nto the cohomology groups of both members, this gives rise to\n\\begin{equation}\n  \\label{eq:100.3}\n  \\mathrm H^i(B,F) \\simeq \\mathrm H^i \\Hom^\\bullet(L_\\bullet^B,F).\\tag{3}\n\\end{equation}\nThe designation ``computational'' takes a rather concrete meaning,\nwhen we choose $L_\\bullet^B$ to have its components in the infinitely\nadditive envelope $\\Addinf(B)$ of $B$, which (as we saw yesterday) can\nbe viewed as a full subcategory of \\Bhatab, made up with projectives,\nand such that any object in \\Bhat{} is quotient of an object coming\nfrom $\\Addinf(B)$; this ensures that there exist indeed integrators\nwhich are ``\\emph{quasi-special}'', i.e., are made up with objects of\n$\\Addinf(B)$, and hence can be interpreted as chain complexes of this\nadditive category. Thus, any component $L_n$ can now be written, in an\nessentially canonical way, as\n\\begin{equation}\n  \\label{eq:100.4}\n  L_n = \\bigoplus_{i\\in I_n} \\bZ^{(b_i)} ,\\tag{4}\n\\end{equation}\nwhere\n\\begin{equation}\n  \\label{eq:100.5}\n  (b_i)_{i\\in I_n} \\tag{5}\n\\end{equation}\nis a family of objects of $B$ indexed by $I_n$ (NB\\enspace for\nsimplicity of notations, we assume the $I_n$'s mutually disjoint,\notherwise we should write the\\pspage{368} general object in the family\n\\eqref{eq:100.5} $b_i^n$ rather than $b_i$). Thus, the $n$'th\ncomponent of the cochain complex of the second member of\n\\eqref{eq:100.2} can be explicitly written as\n\\begin{equation}\n  \\label{eq:100.6}\n  \\Hom^n(L_\\bullet^B,F) = \\Hom(L_n^B,F) \\simeq \\bigoplus_{i\\in I_n} F(b_i),\\tag{6}\n\\end{equation}\nand the coboundary operators between these components can be made\nexplicit in a similar way, by means of (possibly infinite) matrices,\nwhose entries are $\\bZ$-linear combinations of maps from some $b_i^n$\nto some $b_j^{n-1}$ ($i\\in I_n$, $j\\in I_{n-1}$). We feel a little\nhappier still when the direct sums \\eqref{eq:100.4} yielding the\ncomponents $L_n$ are finite, i.e., the sets $I_n$ are finite, which\nalso means that $L_\\bullet^B$ can be interpreted as a chain complex in\nthe additive envelope $\\Add(B)$ of $B$, as contemplated in the first\nplace -- in which case the integrator will be called\n``\\emph{special}''.\n\nThe formula \\eqref{eq:100.2} immediately generalizes when $F$ is\nreplaced by a complex of presheaves $F^\\bullet$, with degrees bounded\nfrom below (NB\\enspace as the notation indicates, the differential\noperator is of degree $+1$), to\n\\begin{equation}\n  \\label{eq:100.7}\n  \\mathrm R\\Gamma_B(F^\\bullet) \\tosim \\Hom^{\\bullet\\bullet}(L_\\bullet^B,F^\\bullet),\\tag{7}\n\\end{equation}\nwhere now the left-hand side designates hypercohomology of $B$ (i.e.,\nof the corresponding topos), viewed as an objects of the right derived\ncategory $\\D^+\\Ab$ of the category of abelian groups, and where\n$\\Hom^{\\bullet\\bullet}$ designates the double complex obtained by\ntaking $\\Hom$'s componentwise, or more accurately, the object in\n$\\D^+\\Ab$ defined by the associated simple complex.\n\nAn interesting special case of \\eqref{eq:100.7} is obtained when\nstarting with a complex of abelian groups $K^\\bullet$ bounded from\nbelow, i.e., defining an object of the right derived category\n$\\D^+\\Ab$, and taking\n\\begin{equation}\n  \\label{eq:100.8}\n  F^\\bullet=K_B^\\bullet=p_B^*(K^\\bullet),\\tag{8}\n\\end{equation}\nthe corresponding \\emph{constant complex of presheaves} on $B$, which\nmay be viewed equally as the inverse image of $K^\\bullet$ by the\nprojection\n\\begin{equation}\n  \\label{eq:100.9}\n  p_B:B\\to\\Simplex_0\\quad(\\text{the final category}),\\tag{9}\n\\end{equation}\nwhich geometrically interprets as the canonical morphism of the topos\nassociated to $B$ to the final (or ``one-point'') topos. The second\nmember of \\eqref{eq:100.7} can be rewritten componentwise, using the\nadjunction formula for the pair $(p_!\\supab,p^*)$ (where the\nqualifying $B$ is omitted now in the notation $p$):\n\\[\\Hom(L_n,p^*(K^m))\\simeq\\Hom(p_!\\supab(L_n),K^M),\\]\nso that \\eqref{eq:100.7} can be rewritten as\\pspage{369}\n\\begin{equation}\n  \\label{eq:100.10}\n  \\mathrm R \\Gamma_B(K_B^\\bullet) \\simeq\n  \\Hom^{\\bullet\\bullet}(p_{B!}\\supab(L_\\bullet^B),K^\\bullet),\\tag{10}\n\\end{equation}\nwhere this time the $\\Hom$'s in the right-hand side of\n\\eqref{eq:100.10} are taken in \\Ab, not in \\Bhatab.\n\nThis formula very strongly suggests to view the chain complex of\nabelian groups\n\\begin{equation}\n  \\label{eq:100.11}\n  p_{B!}\\supab(L_\\bullet^B),\\tag{11}\n\\end{equation}\nwhich is in fact a complex of projective (hence free) abelian groups\ndefined up to chain homotopy, as embodying the global homology\nstructure of $B$ (or of the corresponding topos), more accurately\nstill, as embodying the homology structure of the corresponding\nhomotopy type. It is easily seen that the corresponding object of\n$\\D_\\bullet\\Ab$ depends covariantly on $B$ when $B$ varies in the\ncategory \\Cat, so that we get a functor\n\\[\\Cat\\to \\D_\\bullet\\Ab \\eqdef \\Hotab,\\]\nwhich in view of \\eqref{eq:100.10} (an isomorphism functorial not only\nwith respect to $K^\\bullet$, but equally with respect to $B$) factors\nthrough the localization \\Hot{} of \\Cat, thus yielding a canonical\nfunctor\n\\begin{equation}\n  \\label{eq:100.12}\n  \\Hot\\to\\Hotab,\\tag{12}\n\\end{equation}\nwhich deserves to be called the \\emph{abelianization functor}, from\nhomotopy types to ``abelian homotopy types''. This cannot be of course\nanything else (up to canonical isomorphism) but the functor\n\\eqref{eq:92.1} of section \\ref{sec:92} (p.\\ \\ref{p:321}), but\nobtained here in a wholly ``intrinsic'' way, without having to pass\nthrough the particular properties of a particular test category such\nas $\\Simplex$ or one of its twins. One possible way to check this\nidentity would be by proving that an isomorphism \\eqref{eq:100.10} is\nvalid when replacing (for a given $B$ in \\Cat{} and $K^\\bullet$ in\n$\\D^+\\Ab$) the chain complex \\eqref{eq:100.11} by the corresponding\none deduced from the map \\eqref{eq:92.1} defined p.\\ \\ref{p:321} (via\nthe diagram \\eqref{eq:92.3} on p.\\ \\ref{p:322}), and checking moreover\nthat an object $\\ell_\\bullet$ of $\\D^-\\Ab$ is known up to canonical\nisomorphism, when we know the corresponding functor\n\\begin{equation}\n  \\label{eq:100.13}\n  K^\\bullet\\mapsto \\Hom_{\\D\\Ab}(\\ell_\\bullet,K^\\bullet)\\tag{13}\n\\end{equation}\non $\\D^+\\Ab$. Presumably, this latter statement holds when replacing\n\\Ab{} by any abelian category, but I confess I didn't sit down to\ncheck it, nor do I remember having seen it stated somewhere -- as I\ndon't remember either having seen anywhere a comprehensive treatment\nabout the relationship between homology and cohomology. So maybe my\npresent reflections do fill a gap, or at any rate give some\nindications as to how to fill it\\ldots\n\nI played around some yesterday and today with the formalism of\nintegrators, notably with respect to maps\n\\[ f:B'\\to B\\]\nbetween small categories, and the corresponding \\emph{integration\n  functor}\n\\[ f_!\\supab: {B'}\\subab\\uphat \\to \\Bhatab,\\]\nand its left derived functor $\\mathrm Lf_!\\supab$. Thus, the chain\ncomplex in \\Bhatab\n\\begin{equation}\n  \\label{eq:100.14}\n  L_\\bullet^{B'/B}\\quad\\text{or}\\quad\n  L_\\bullet^f \\eqdef f_!\\supab(L_\\bullet^{B'}),\\tag{14}\n\\end{equation}\nwhich has projective components (and even is a chain complex in\n$\\Addinf(B)$ resp.\\ in $\\Add(B)$, if $L_\\bullet^{B'}$ is quasi-special\nresp.\\ is special), and is defined up to chain homotopism, embodies\nthe relative homology properties of $B'$ over $B$, i.e., of $f$, in\nmuch the same way as \\eqref{eq:100.11} embodies the global homology\nproperties of $B$ (i.e., of $B$ over one point). When the functor $f$\nis ``coaspheric'', i.e., the functor\n\\[f\\op:{B'}\\op \\to B\\op\\]\nbetween the opposite categories is aspheric, then $L_\\bullet^{B'/B}$\nis again an integrator on $B$, and the converse should hold too\nprovided we take the meaning of ``coaspheric'' and ``aspheric'' with\nrespect to a suitable basic localizer $\\scrW=\\scrW_\\oo^{\\bZ}$ --\npresumably, we'll come back upon this in part \\ref{ch:V} or part\n\\ref{ch:VI} of the notes. For the time being, it seems more\ninteresting to give now the precise relationship between the notion of\nan \\emph{integrator} for $B$, and the notion of an\n\\emph{abelianizator} for the dual category $A=B\\op$, introduced in\nsection \\ref{sec:93}.\n\n\\medbreak\n\n\\noindent\\textbf{Remarks.} \\namedlabel{rem:100.1}{1})\\enspace It is a familiar fact that when\nworking in \\v Cech-flavored contexts, such as general topoi, or étale\ntopoi for schemes and the like, one has throughout and from the start\na good hold upon \\emph{cohomology} notions, whereas it is a lot more\nsubtle to squeeze out adequate homology notions, which (to my\nknowledge) can be carried through only indirectly via cohomology, and\nusing suitable finiteness and duality statements within the cohomology\nformalism. Historically however, homology was introduced before\ncohomology via cellular decompositions of spaces, with a more direct\nappeal to geometric intuition. This preference for homology rather\nthan cohomology seems to be still prevalent among most homotopy\ntheorists, who have a tendency to view a topological space (however\nwild it may be) as being no more no less than its singular complex. A\ncomprehensive statement establishing, in a suitable wide enough\ncontext, essential equivalence between the two viewpoints, seems to be\nstill lacking, as far as I\\pspage{371} know -- although a fair number\nof partly overlapping results in this direction are known, among the\noldest being the relevant ``universal coefficients formulæ'' relating\nhomology and cohomology (reducing all to a formula of the type\n\\eqref{eq:100.2} or \\eqref{eq:100.10} above), or Cartan's old seminar\non Leray's sheaf theory, introducing singular homology with\ncoefficients in a sheaf and proving that on a topological variety,\nthis was (up to dimension shift and twist by the twisted integers)\nessentially the same as singular cohomology (with coefficients in\nsheaves too). It is not sure that an all-inclusive statement of\nequivalence between homology and cohomology (in those situations when\nsuch equivalence is felt hold indeed) does at all exist -- at any\nrate, according to what kind of coefficients one wants to consider,\nand what kind of extra structures one is interested in when dealing\nwith homology and cohomology invariants, it seems that each of the two\npoints of view has an originality and advantages of its own and cannot\nbe entirely superseded by the other. From the contexts I have been\nmainly working in, there definitely was no choice, namely cohomology\n(including non-commutative one) was the basic data, while sheaves and\ntheir generalizations (such complexes of sheaves, or stacks) were the\ncoefficients. I don't remember of any moment where I would have paused\nand asked myself \\emph{why} in most contexts where I was working in\n(whose common denominator was topoi), there wasn't any direct hold on\nanything like homology invariants. The reason for this inertness of\nmine, probably, is that the cohomology formalisms I hit upon were\nself-contained enough, so as to leave no regret for the absence of a\nhomology formalism, or at any rate of a more or less direct\ndescription of it independently of cohomology. Another reason, surely,\nis that I didn't have too much contact with topologists and\nhomotopists and their everyday tools, such as Steenrod operations,\nhomology of the symmetric group, and the like. This question of ``why\nthis reluctance of homology to show forth'' has finally surfaced only\nduring these very last days, when the answer for it (or one possible\nanswer at any rate) is becoming evident: namely, that \\emph{for a\n  general topos}, embodied by a category of sheaves (of sets) \\scrA,\n\\emph{there are not enough projectives in \\scrA, and not even enough\n  projectives in $\\scrAab$}, the category of abelian sheaves. It\nis becoming apparent (what surely everybody has known ages) that in\ntechnical terms, \\emph{doing ``homology'' is working with projectives,\n  while doing ``cohomology'' is working with injectives}. As there are\nenough injectives in $\\scrAab$ but not enough projectives,\ncohomology is around and homology not, period!\n\nThere is however a rather interesting class of topoi admitting\nsufficiently\\pspage{372} many projective sheaves of sets, and hence\nsufficiently many projective abelian sheaves -- namely the topoi\n\\Bhat{} defined in terms of small categories $B$. They include the\ntopoi which can be described in terms of semisimplicial complexes and\nthe like, and can be viewed equally as the topoi which are ``closest\nto algebra'' or ``purely algebraic'' in a suitable sense -- for\ninstance, definable directly in terms of arbitrary presheaves, without\nany reference to the notion of site and of localization. (The\nintuition of localization remaining however and indispensable guide\neven in the so-called ``algebraic'' set-up.) Moreover, the morphisms\nwhich arise most naturally among such topoi, namely those associated\nto maps\n\\[f:B'\\to B\\]\nin \\Cat, besides the traditional adjoint pair $(f^*,f_*)$ of functors\nbetween sheaves of sets, gives rise equally to a functor\n\\begin{equation}\n  \\label{eq:100.15}\n  f_!:{B'}\\uphat\\to\\Bhat\\tag{15}\n\\end{equation}\nleft adjoint to $f^*$ (i.e., $f^*$ commutes to small inverse limits,\nnot only to small direct limits and to finite inverse limits),\ninserting in a triple of mutually adjoint functors (from left to\nright)\n\\begin{equation}\n  \\label{eq:100.16}\n  (f_!,f^*,f_*).\\tag{16}\n\\end{equation}\nThe functors $f^*$ and $f_*$ induce corresponding adjoint functors on\nabelian sheaves (due to the fact that they commute to finite\nproducts), $f^*\\subab$ and $f_*\\supab$, whereas $f_!$ does not in\ngeneral transform group objects into group objects; however, as\n$f^*\\subab$ commutes to small inverse limits, it does admit again a\nleft adjoint $f_!\\supab$, so as to give again a triple\n\\begin{equation}\n  \\label{eq:100.17}\n  (f_!\\supab,f^*\\subab,f_*\\supab)\\tag{17}\n\\end{equation}\nof mutually adjoint functors. Now, whereas the derived functors\n\\[\\text{$f^*$ or $\\mathrm L f^*\\subab$,} \\quad\n\\text{$\\mathrm R f_*$ or $\\mathrm R f_*\\supab$}\\]\nof $f^*\\subab$ and $f_*\\supab$ have been extensively used in the\nevery-day cohomology formalism of topoi, the existence in certain\ncases (such as the one we are interested in here) of a functor\n$f_!\\supab$ and of its left derived functor\n\\begin{equation}\n  \\label{eq:100.18}\n  \\text{$\\mathrm L f_!$ or $\\mathrm Lf_!\\supab: \\D^-({B'}\\uphat\\subab)\n    \\to \\D^-(\\Bhatab),$}\\tag{18}\n\\end{equation}\nseems to me to have been widely overlooked so far, except in extremely\nparticular cases such as inclusion of an open subtopos; at any rate, I\nhave been overlooking it till lately, when it came to my attention\nthrough\\pspage{373} the writing of these notes. (Namely, first in\nconnection with my reflections on derivators (cf.\\ section\n\\ref{sec:69}), and now in connection with the reflections on\nabelianization.) In view of my reflections on derivators, I would like\nto view the functor \\eqref{eq:100.18} as an operation of\n``integration'', whereas the traditional functor\n\\begin{equation}\n  \\label{eq:100.19}\n  \\mathrm Rf_* : \\D^+({B'}\\uphat\\subab) \\to \\D^+(\\Bhatab)\\tag{19}\n\\end{equation}\nis viewed as ``cointegration'' (which I prefer to my former way of\ncalling it an ``integration''). The first should be viewed as\nexpressing \\emph{homology} properties of the map $f$ in \\Cat{} (or\nbetween the corresponding topoi), just as the latter expresses\n\\emph{cohomology} properties of $f$. This does check with the\ncorresponding qualifications ``integration'' -- ``cointegration'' --\nas well as with the intuition, when $B$ is reduced to a point,\nidentifying the first to a kind of direct sum (= integration), whereas\nthe latter is viewed as a kind of direct product (=\n\\emph{co}integration). The idea behind the terminology will go through\nmaybe when looking at the particular case when $B'$ is a sum of copies\nof $B$, namely a product of $B$ by a discrete category $I$, and\n\\[f : B'=B\\times I\\to B\\]\nthe projection.\n\nThe point I want to make here, mainly to myself, is that in the\npresent context \\emph{when \\eqref{eq:100.18}, namely integration,\n  exists, this operation presumably is by no means less meaningful and\n  important than the familiar $\\mathrm Rf_*$ or cointegration} -- or\n\\emph{equivalently stated, that the homology properties of $f$ are\n  just as meaningful and deserving close attention, as the cohomology\n  properties}, which so far have been the only ones I have been\nlooking at. Presumably, when following this recommendation, a few\nunexpected facts and relationships should come out, such as various\n``duality'' relationships between homology properties of $f$, and\ncohomology properties of the map $f\\op$ between the opposite\ncategories. (This is suggested by some of the scratchwork I made on\nderivators and cohomology properties of maps in \\Cat.) The only\ntrouble is that such change or broadening of emphasis as I am now\nsuggesting will require a certain amount of extra attention, which I\nam not too sure to be willing to invest in the subject, namely\nalgebraic topology. Thus presumably, my main emphasis will remain with\ncohomology, rather than homology. I am no longer convinced though that\nthis point of view is technically more adequate than the dual one.\n\n\\namedlabel{rem:100.2}{2})\\enspace All the reflections of yesterday's\nnotes as well as today's can be extended, when replacing throughout\nabelian presheaves by presheaves of\\pspage{374} $k$-modules, and\nadditive envelopes by $k$-linear ones, where $k$ is any given\ncommutative ring. Of course, the category \\Ab{} and its various\nderived categories will have to be replaced accordingly by the\ncategory \\kMod{} of $k$-modules etc. The same holds for the\nrelationship I am going to write down between integrators for $B$ and\nabelianizators for $A=B\\op$. For simplicity of notations, I am going\nto keep the exposition in the \\Ab-framework I have started with, and\nleave the necessary adjustments to the reader.\n\n\\bigbreak\n\\presectionfill\\ondate{18.7.}\\par\n\n% 101\n\\hangsection[Abelianization VI: The abelian integration operation\n\\dots]{Abelianization VI: The abelian integration operation\n  \\texorpdfstring{$\\mathrm Lf_!\\supab$}{Lf!ab} defined by a map\n  \\texorpdfstring{$f$ in \\Cat{} \\textup(}{f in (Cat) (}versus abelian\n  cointegration\n  \\texorpdfstring{$\\mathrm Rf_*$\\textup)}{Rf*)}.}\\label{sec:101}%\nFinally with yesterday's non-technical reflections on homology versus\ncohomology, it was getting prohibitively late, and there could be no\nquestion to deal with the relationship between integrators (for $B$)\nand abelianizators (for $B\\op=A$). Also, I feel I should give some\n``computational'' details about the functor $f_!\\supab$ associated to\na map in \\Cat\n\\[f:B'\\to B,\\]\nnamely\n\\[f_!\\supab:{B'}\\uphat\\subab \\to \\Bhatab,\\]\nwhich is a lot less familiar to me than its right adjoint and\nbiadjoint $f^*$ and $f_*$. One way to get a ``computational hold''\nupon it is by noting that $f_!\\supab$ commuting to small direct limits\nand a fortiori being right exact, and moreover any object $F'$ in\n${B'}\\uphat\\subab$ being a cokernel of a map between ``\\emph{special\n  projectives}'' in ${B'}\\uphat\\subab$, i.e., between objects in\n$\\Addinf(B')$, namely inserting into an exact sequence\n\\[L_1' \\xrightarrow d L_0' \\to F' \\to 0 \\quad\\text{with $L_0',L_1'$ in\n  $\\Addinf(B')$,}\\]\nthe functor $f_!\\supab$ (via its values on any $F'$ say) is\nessentially known, when we know its restriction to the subcategory\n$\\Addinf(B')$, as we'll get a corresponding exact sequence in \\Bhatab\n\\[f_!\\supab(L_1') \\to f_!\\supab(L_0') \\to f_!\\supab(F') \\to 0,\\]\ndescribing $f_!\\supab(F')$ as a cokernel of a map $f_!\\supab(d)$\ncorresponding to a map in $\\Addinf(B')$. The relevant fact now is that\nwe have a commutative diagram of functors (up to can.\\ isomorphism as\nusual)\n\\begin{equation}\n  \\label{eq:101.1}\n  \\begin{tabular}{@{}c@{}}\n    \\begin{tikzcd}[baseline=(O.base)]\n      \\Addinf(B')\\ar[r]\\ar[d,\"\\Addinf(f)\"'] &\n      {B'}\\uphat\\subab\\ar[d,\"f_!\\supab\"] \\\\\n      \\Addinf(B)\\ar[r] & |[alias=O]| \\Bhatab\n    \\end{tikzcd},\n  \\end{tabular}\\tag{1}\n\\end{equation}\nwhere\\pspage{375} the horizontal arrows are the canonical inclusion\nfunctors, and $\\Addinf(f)$ is the ``tautological'' extension of $f:B'\n\\to B$ to the infinitely additive envelopes, defined computationally\nas\n\\begin{equation}\n  \\label{eq:101.2}\n  \\Addinf(f)(L') \\simeq \\bigoplus_{i\\in I}\\bZ^{f(b_i')}\\tag{2}\n\\end{equation}\nfor an object of $\\Addinf(B')$ written canonically as\n\\begin{equation}\n  \\label{eq:101.3}\n  L'=\\bigoplus_{i\\in I}\\bZ^{(b_i')}.\\tag{3}\n\\end{equation}\nHere, for an object $b$ in a small category $B$, we denote by the more\nsuggestive symbol $\\bZ^{(F)}$ the abelianization $\\Wh_B(F)$ of an\nobject $F$ of \\Bhat, and accordingly of $F$ is an object $b$ in\n$B$. The fact that \\eqref{eq:101.2} is equally an expression for\n$f_!\\supab$ follows immediately from commutation of $f_!\\supab$ to\nsmall direct sums, and from the canonical isomorphism\n\\begin{equation}\n  \\label{eq:101.4}\n  f_!\\supab(\\bZ^{F'}) \\simeq \\bZ^{(f_!(F'))},\\tag{4}\n\\end{equation}\ni.e., commutation up to canonical isomorphism of the diagram\n\\begin{equation}\n  \\label{eq:101.5}\n  \\begin{tabular}{@{}c@{}}\n    \\begin{tikzcd}[baseline=(O.base)]\n      {B'}\\uphat \\ar[r,\"\\Wh_{B'}\"] \\ar[d,\"f_!\"'] &\n      {B'}\\uphat\\subab \\ar[d,\"f_!\\supab\"] \\\\\n      \\Bhat\\ar[r,\"Wh_B\"] & |[alias=O]| \\Bhatab\n    \\end{tikzcd},\n  \\end{tabular}\\tag{5}\n\\end{equation}\nthe verification of which is immediate. (For a generalization to\nsheaves endowed with arbitrary ``algebraic structures'' and taking\nfree objects, see\\scrcomment{\\textcite{SGA4vol1}} SGA~4 I~5.8.3,\np.~30.)\n\nOf course, \\eqref{eq:101.1} and \\eqref{eq:101.2} imply that\n$f_!\\supab$ maps $\\Add(B')$ into $\\Add(B)$, and induces the\ntautological extension $\\Add(f)$ of $f$ to the additive\nenvelopes. Thus, \\eqref{eq:101.1} and \\eqref{eq:101.5} can be inserted\ninto a beautiful commutative diagram (up to canonical isomorphism)\n\\begin{equation}\n  \\label{eq:101.6}\n  \\begin{tabular}{@{}c@{}}\n    \\begin{tikzcd}[baseline=(O.base),column sep=small]\n      B' \\ar[rr,hook] \\ar[d,\"f\"'] \\ar[ddrrr,hook,%\n      dash pattern=on 33 pt off 30pt on 60pt] & &\n      \\Add(B')\\ar[rr,hook] \\ar[d,\"\\Add(f)\"] & &\n      \\Addinf(B')\\ar[rr,hook] \\ar[d,\"\\Addinf(f)\"'] & &\n      {B'}\\uphat\\subab \\ar[d,\"f_!\\supab\"] \\\\\n      B \\ar[rr,hook] \\ar[ddrrr,hook] & &\n      \\Add(B) \\ar[rr,hook] & &\n      \\Addinf(B)\\ar[rr,hook] & &\n      \\Bhatab \\\\\n      & & & {B'}\\uphat \\ar[d,\"f_!\"] \\ar[uurrr,\"\\Wh_{B'}\" pos=0.15,%\n      dash pattern=on 40pt off 30pt on 60pt] & & & \\\\\n      & & & |[alias=O]| \\Bhat \\ar[uurrr,\"\\Wh_B\" pos=0.4] & & &\n    \\end{tikzcd}.\n  \\end{tabular}\\tag{6}\n\\end{equation}\n\nThe formula \\eqref{eq:101.1} (or equivalently, \\eqref{eq:101.2}) can\nbe viewed as giving a computational description of the left derived\nfunctor\n\\begin{equation}\n  \\label{eq:101.7}\n  \\mathrm Lf_!\\supab:\\D^-({B'}\\uphat\\subab)\\to \\D^-(\\Bhatab).\\tag{7}\n\\end{equation}\nIndeed,\\pspage{376} by general principles of homological algebra, for\nany small category $B$, from the fact that $\\Addinf(B)$ is made up\nwith projective objects of \\Bhatab{} and that any object in \\Bhatab{}\nis isomorphic to a quotient of an object in this subcategory, it\nfollows that\n\\begin{equation}\n  \\label{eq:101.8}\n  \\D^-(\\Bhatab)\\equeq W_B^{-1}\\Comp^-(\\Addinf(B)),\\tag{8}\n\\end{equation}\ni.e., the left derived category $\\D^-(\\Bhatab)$ is equivalent with the\ncategory obtained by localizing, with respect to the set $W_B$ of\nhomotopy equivalences, the category $\\Comp^-(\\ldots)$ of differential\ncomplexes in the additive category $\\Addinf(B)$, with degrees bounded\nfrom above (the differential operator being of degree $+1$, according\nto my preference for cohomology notation, sorry!). An object of\n$\\D^-(\\Bhatab)$ may thus be viewed as being essentially the same as a\ndifferential complex in $\\Addinf(B)$ with degrees bounded from above,\nand given ``up to homotopism''.  The similar description holds for\n$\\D^-({B'}\\uphat\\subab)$, and in terms of these descriptions, the\n``integration functor'' (in the abelian context) \\eqref{eq:101.7} can\nbe described by\n\\begin{equation}\n  \\label{eq:101.9}\n  \\mathrm Lf_!\\supab(L_\\bullet') = \\Addinf(L_\\bullet'),\\tag{9}\n\\end{equation}\ni.e., by applying componentwise the tautological extension\n$\\Addinf(f)$ of $f$ to the differential complexes in\n$\\Addinf(B')$. This very concrete description applies notably to the\ncomplex\n\\begin{equation}\n  \\label{eq:101.10}\n  L_\\bullet^{B'/B}\\quad\\text{or}\\quad L_\\bullet^f\\eqdef f_!\\supab(L_\\bullet^{B'})\\tag{10}\n\\end{equation}\nintroduced yesterday, whenever a (quasi-special) integrator\n$L_\\bullet^{B'}$ for $B'$ has been chosen. Applying this to the case\nof the map\n\\[p_B:B\\to\\Simplex_0,\\]\nwe get (for a given integrator $L_\\bullet^B$ for $B$) an explicit\ndescription of the abelianization of the homotopy type of $B$ in terms\nof the chain complex $p_{B!}\\supab(L_\\bullet^B)$ in \\Ab, with the\n$n$'th component given by\n\\begin{equation}\n  \\label{eq:101.11}\n  \\bigl(L_\\bullet^{B/\\mathrm{pt}}\\bigr)_n = \\bZ^{(I_n)},\\tag{11}\n\\end{equation}\nwhere $I_n$ is the set of indices used for describing $L_n^B$ as the\ndirect sum of objects of the type $\\bZ^{(b_i)}$.\n\nReturning to the case of a general map $f:B'\\to B$, maybe I should\nstill write down the formula generalizing \\eqref{eq:100.2} or\n\\eqref{eq:100.10} of yesterday's notes (pages \\ref{p:367} and\n\\ref{p:369}), relating $L_\\bullet^{B'/B}$ to the cohomology properties\nof the map $f$, i.e., to cointegration relative to $f$. The\nformula\\pspage{377} expresses cointegration $\\mathrm Rf_*$ with\ncoefficients coming from downstairs, namely $f^*(K^\\bullet)$, where\n$K^\\bullet$ is any differential complex in \\Bhatab{} with degrees\nbounded from below (thus defining an object in $\\D^+(\\Bhatab)$). The\nrelevant formula is\\scrcomment{see section~\\ref{sec:139}, bottom of\n  p.~\\ref{p:588}, for corrections to this formula and\n  \\eqref{eq:101.12prime}, \\eqref{eq:101.13} below\\dots}\n\\begin{equation}\n  \\label{eq:101.12}\n  \\mathrm Rf_*(f^*(K^\\bullet)) \\simeq \\bHom^{\\bullet\\bullet}(L_\\bullet^{B'/B},K^\\bullet),\\tag{12}\n\\end{equation}\nan isomorphism in $\\D^+(\\Bhatab)$, where $\\bHom^{\\bullet\\bullet}$\ndesignates the double complex in \\Bhatab{} obtained by applying\n$\\bHom$ componentwise, more accurately the associated simple complex,\nand where $\\bHom$ is the internal $\\bHom$ in the category \\Bhatab,\nnamely the (pre)sheaf of additive homomorphisms of a given abelian\n(pre)sheaf ($L_n$ say) into another ($K^m$ say). The proof of\n\\eqref{eq:101.12} is essentially trivial, it is just the computational\ninterpretation, in terms of using projective resolutions, of the\nadjunction formula ``localized on $B$\n\\begin{equation}\n  \\label{eq:101.12prime}\n  \\mathrm Rf_*(\\mathrm Lf^*(K^\\bullet)) \\simeq \\mathrm R\\bHom(\\mathrm\n  Lf_!\\supab(\\bZ_{B'}), K^\\bullet),\\tag{12'}\n\\end{equation}\nwhich is a particular case of the more general ``adjunction formula''\n\\begin{equation}\n  \\label{eq:101.13}\n  \\mathrm Rf_*(\\mathrm R\\bHom(F_\\bullet', \\mathrm Lf^*(K^\\bullet))\n  \\simeq \\mathrm R\\bHom(\\mathrm Lf_!\\supab(F'_\\bullet),K^\\bullet),\\tag{13}\n\\end{equation}\nvalid for\n\\[ \\text{$F_\\bullet'$ in $\\D^-({B'}\\uphat\\subab)$,}\\quad\n\\text{$K^\\bullet$ in $\\D^+(\\Bhatab)$,}\\]\n\\eqref{eq:101.12prime} following from \\eqref{eq:101.13} by taking\n$F_\\bullet'=\\bZ_{B'}$.\n\n\\begin{remarks}\n  We may view \\eqref{eq:101.13}, and its particular case\n  \\eqref{eq:101.12} or \\eqref{eq:101.12prime}, as the main formula\n  relating the \\emph{homology} and \\emph{cohomology} invariants for a\n  map $f$ in \\Cat, or equivalently, the (abelian) \\emph{integration}\n  and \\emph{cointegration} operations defined by $f$. It now occurs to\n  me that this formula, and the variance formalism in which it\n  inserts, is valid more generally whenever we have a map $f$ between\n  two ringed topoi, such that $f_!$ exists for sheaves of sets, hence\n  there exists too a corresponding functor $f_!^{\\mathrm{mod}}$ for\n  sheaves of modules. The fact that we have been restricting to the\n  case of the constant sheaves of rings defined by $\\bZ$ isn't\n  relevant, and (in the case of topoi defined by objects in \\Cat,\n  hence with sufficiently many projective sheaves of sets) the\n  formalism of the subcategories $\\Add(B)$ and $\\Addinf(B)$ in\n  \\Bhatab{} can be generalized equally to arbitrary sheaves of rings\n  on $B$. At present, I don't see though any striking particular case\n  where this generalization would seem useful.\\pspage{378}\n\\end{remarks}\n\n% 102\n\\hangsection[Abelianization VII: Integrators (for $A\\op$) are\n\\dots]{Abelianization VII: Integrators\n  \\texorpdfstring{\\textup(\\kernifitalic{2pt}}{(}for\n  \\texorpdfstring{$A\\op$\\textup)}{Aop)} are abelianizators\n  \\texorpdfstring{\\textup(\\kernifitalic{2pt}}{(}for\n  \\texorpdfstring{$A$\\textup)}{A)}.}\\label{sec:102}%\nWe now focus attention upon the pair of mutually dual small categories\n\\begin{equation}\n  \\label{eq:102.1}\n  (A,B), \\quad\\text{with $B=A\\op$, i.e., $A=B\\op$,}\\tag{1}\n\\end{equation}\nand recall the equivalence of section \\ref{sec:93} following from the\nuniversal property of $\\Add(B)$\n\\begin{equation}\n  \\label{eq:102.2}\n  \\Ahatab = \\bHom(A\\op,\\Ab) \\equeq \\bHomadd(\\Add(A\\op),\\Ab),\\tag{2}\n\\end{equation}\nwhich we parallel with the formula \\eqref{eq:99.3} of section\n\\ref{sec:99} (p.\\ \\ref{p:362}), which reads when replacing in it $B$\nby $A$\n\\[\\Ahatab\\simeq\\bHomadd(\\Add(A)\\op,\\Ab)\\text{;}\\]\nthis immediately suggests a canonical equivalence of categories\n\\begin{equation}\n  \\label{eq:102.3}\n  \\Add(A\\op)\\equeq \\Add(A)\\op,\\tag{3}\n\\end{equation}\nfollowing immediately indeed from the $2$-universal properties of\nthese categories. We complement \\eqref{eq:102.2} by the similar\nformula\n\\begin{equation}\n  \\label{eq:102.4}\n  F\\mapsto \\widetilde F: \\quad\n  \\Ahatab\\toequ\\bHomaddinf(\\Addinf(B),\\Ab), \\quad B=A\\op,\\tag{4}\n\\end{equation}\nwhere $\\bHomaddinf$ denotes the category of infinitely additive\nfunctors between two infinitely additive categories. In view of the\nemphasis lately on chain complexes in $\\Addinf(B)$ rather than in\n$\\Add(B)$, in order to reconstruct say the derived category\n$\\D_\\bullet(\\Bhatab)$ of chain complexes in \\Bhatab, and get existence\nof ``integrators'' with components in $\\Addinf(B)$ (whereas there may\nbe none with components in $\\Add(B)$), it is formula \\eqref{eq:102.4}\nrather than \\eqref{eq:102.2} which is going to be relevant for our\nhomology formalism. Using \\eqref{eq:102.4}, we get a canonical\nbiadditive pairing\n\\begin{equation}\n  \\label{eq:102.star}\n  \\Ahatab \\times \\Addinf(B) \\to \\Ab,\\tag{*}\n\\end{equation}\nwhich visibly is exact with respect to the first factor, and which we\nmay equally interpret as a functor\n\\begin{equation}\n  \\label{eq:102.5}\n  L\\mapsto \\widetilde L: \\Addinf(B) \\to \\bHomex(\\Ahatab,\\Ab),\\tag{5}\n\\end{equation}\nwhere $\\bHomex$ denotes the category of \\emph{exact} (hence additive)\nfunctors from an abelian category to another one.\n\nIt can be shown that the pairing \\eqref{eq:102.star} can be extended\ncanonically to a pairing\n\\begin{equation}\n  \\label{eq:102.6}\n  \\Ahatab \\times \\Bhatab \\to \\Ab\\tag{6}\n\\end{equation}\ncommuting to small direct limits in each variable, and identifying\n(up\\pspage{379} to equivalence) each left hand factor to the category\nof functors from the other functor to \\Ab{} which commute with small\ndirect limits (much in the same way as the corresponding relationship\nbetween \\Ahat{} and \\Bhat, with \\Ab{} being replaced by \\Sets), and\nthe accordingly the functor \\eqref{eq:102.5} is equally fully\nfaithful, and extends to a fully faithful functor from \\Bhatab{} to\n$\\bHomadd(\\Ahatab,\\Ab)$, inducing in fact an equivalence between\n\\Bhatab{} and the full subcategory $\\bHom_!(\\Ahatab,\\Ab)$ of\n$\\bHom(\\Ahatab,\\Ab)$ made up by all functors $\\Ahatab\\to\\Ab$ which\ncommute to small direct limits. But for what we have in mind at\npresent, these niceties are not too relevant yet it seems -- all what\nmatters is that an object $L$ of $\\Addinf(B)$ defines an exact functor\n\\[\\widetilde L :\\Ahatab\\to\\Ab,\\]\ndepending functorially on $L$, in an infinitely additive way. Thus, as\nnoted in section \\ref{sec:92} (but where $\\Addinf(B)$ was replaced by\nthe smaller category $\\Add(B)$, which has turned out insufficient for\nour purposes), whenever we have a chain complex $L_\\bullet$ in\n$\\Addinf(B)$, we get a corresponding functor\n\\begin{equation}\n  \\label{eq:102.7}\n  \\widetilde L_\\bullet:\\Ahatab\\to\\Ch_\\bullet\\Ab\\tag{7}\n\\end{equation}\nfrom \\Ahatab{} to the category of chain complexes of \\Ab, which is\nmoreover an \\emph{exact} functor. Generalizing slightly the\nterminology introduced in section \\ref{sec:93}, where we restricted to\nchain complexes with components in $\\Add(B)$ rather than in $\\Add(B)$,\nwe'll say that $\\widetilde L_\\bullet$ is an \\emph{abelianizator for\n  $A$}, if the following diagram commutes up to isomorphism:\n\\begin{equation}\n  \\label{eq:102.8}\n  \\begin{tabular}{@{}c@{}}\n    \\begin{tikzcd}[baseline=(O.base)]\n      \\Ahat\\ar[r]\\ar[d,\"{%\n        \\begin{array}{@{}c@{}}\n          \\Wh_A \\\\ \\text{(abelianization)}\n        \\end{array}}\"'] & \\HotOf_A \\ar[r] & \\Hot \\ar[d,\"{%\n        \\begin{array}{@{}c@{}}\n          \\text{``absolute''} \\\\ \\text{abelianization} \\\\ \\text{functor}\n        \\end{array}}\" inner sep=1em] \\\\\n      \\Ahatab\\ar[r,\"\\widetilde L_\\bullet\"] &\n      \\Ch_\\bullet\\Ab\\ar[r] & |[alias=O]| \\Hotab\n    \\end{tikzcd}.\n  \\end{tabular}\\tag{8}\n\\end{equation}\nMore accurately, an abelianizator is a pair $(\\widetilde L_\\bullet,\\lambda)$,\nwhere $\\lambda$ is an isomorphism of functors $\\Ahat\\to\\Hotab$ making\nthe diagram commute. Here, I like to view the abelianization functor\n\\begin{equation}\n  \\label{eq:102.9}\n  \\Hot\\to\\Hotab\\eqdef\\D_\\bullet\\Ab\\tag{9}\n\\end{equation}\nas the one described directly in section \\ref{sec:100} via integrators\nof arbitrary modelizing objects in \\Cat, without any reference to an\nauxiliary test category such as $\\Simplex$ or the like.\n\nThe point of \\eqref{eq:102.8} is that via an ``abelianizator'' for\n$A$, we want to be able to give a)\\enspace a \\emph{simultaneous} handy\nexpression, in terms of ``computable'' chain complexes in \\Ab,\nof\\pspage{380} abelianization of homotopy types modelized by a\nvariable object $X$ in \\Ahat, and b)\\enspace we want that the chain\ncomplex in \\Ab{} expressing abelianization of $X$, should be\nexpressible in terms of the ``tautological abelianization'' $\\Wh_A(X)\n= \\bZ^{(X)}$ of $X$ itself, by a formula moreover which should make\nsense functorially with respect to an arbitrary abelian presheaf,\ni.e., an object $F$ in \\Ahatab.\n\nThe main fact I have in view here is that whenever the chain complex\n$L_\\bullet$ in $\\Addinf(B)$ is endowed with an augmentation\n\\begin{equation}\n  \\label{eq:102.10}\n  L_\\bullet\\to\\bZ_B\\tag{10}\n\\end{equation}\nturning it into a resolution of $\\bZ_B$, i.e., into a (quasi-special)\n\\emph{integrator} for $B$, then ipso facto $L_\\bullet$ is an\nabelianizator for $A$, the commutation isomorphism $\\lambda$ being\ncanonically defined by the augmentation \\eqref{eq:102.10}.\n\nSome comments, before proceeding to a proof. Presumably, the converse\nof our statement holds too -- namely that the natural functor we'll\nget from quasi-special integrators for $B$ to abelianizators\n$(L_\\bullet,\\lambda)$ for $B$ is an equivalence (even an isomorphism!)\nbetween the relevant categories. I don't feel like pursuing this --\nthe more relevant fact here, whether or not a converse as contemplated\nholds, is that we can pin down at any rate a special class of\nabelianizators for $A$, namely those which come from (quasi-special)\nintegrators for $B$, and these abelianizators are defined up to chain\nhomotopism in $\\Addinf(B)$. In this sense, \\emph{we get an existence\n  and unicity statement for abelianizators in $A$}, as strong as we\npossibly could hope for. In practical terms, it would seem, \\emph{an\n  abelianizator for $A$ will be no more no less than just a\n  \\textup(quasi-special\\textup) integrator for $B$, namely a\n  projective resolution of $\\bZ_B$ in \\Bhatab, whose components\n  satisfy a mild extra assumption besides being projective}.\n\nHere, I am struck by a slight discrepancy in terminology, as we would\nrather have a correspondence\n\\[\n\\begin{cases}\n  &\\text{integrators for $B$ $\\to$ abelianizators for $A$} \\\\\n  &\\text{quasi-special int.s for $B$ $\\to$ quasi-special abelian.s for $A$,}\n\\end{cases}\\]\nand the same for ``special'' integrators and abelianizators. As I\nstill feel that the general appellation of an ``integrator'' for\n\\emph{any} projective resolution of $\\bZ_B$ is adequate (without\ninsisting that the components should be in $\\Addinf(B)$), this kind of\nforces us to extend accordingly still the notion of an abelianizator\nfor $A$. This does make sense, using the pairing \\eqref{eq:102.6}\n(which we had dismissed as an ``irrelevant nicety for the time\nbeing''!), and the corresponding equivalence\\pspage{381}\n\\begin{equation}\n  \\label{eq:102.11}\n  \\Bhatab \\toequ \\bHom_!(\\Ahatab, \\Ab),\\tag{11}\n\\end{equation}\nwhere the index $!$ denotes the full subcategory of $\\bHom$ made up\nwith functors commuting to small direct limits. It is immediate that\nprojective objects in \\Bhatab{} give rise to objects in $\\bHom_!$\nwhich are \\emph{exact} functors from \\Ahatab{} to \\Ab, and I'll have to\ncheck that the converse also holds. If so, a chain complex in\n\\Bhatab{} with projective components can be interpreted as being just\nan \\emph{arbitrary exact functor commuting to small sums}\n\\[ \\Ahatab \\to \\Ch_\\bullet\\Ab,\\]\n(never minding whether or not it can be described ``computationally''\nin terms of objects in $\\Add(B)$ or in $\\Addinf(B)$!) -- which is all\nthat is needed in order to complete the diagram \\eqref{eq:102.8}, and\nwonder if it commutes up to isomorphism! And the most natural\nstatement here is that this is indeed so whenever this functor, viewed\nas a chain complex in the abelian category\n\\begin{equation}\n  \\label{eq:102.12}\n  \\bHom_!(\\Ahatab,\\Ab),\\tag{12}\n\\end{equation}\nis a (projective) resolution of the canonical object $\\widetilde\\bZ_B$\nof the category \\eqref{eq:102.12}, coming from the object $\\bZ_B$ of\nthe left-hand side of \\eqref{eq:102.11}. Now, this functor is just the\nfamiliar ``direct limit'' functor\n\\begin{equation}\n  \\label{eq:102.13}\n  \\widetilde\\bZ_B \\simeq \\varinjlim_B : \\Ahatab \\eqdef \\bHom(B,\\Ab)\n  \\to \\Ab,\\tag{13}\n\\end{equation}\nwhich can be equally interpreted as\n\\begin{equation}\n  \\label{eq:102.14}\n  \\widetilde \\bZ_B \\simeq p_{A!}\\supab : \\Ahatab \\to \\Ab,\\tag{14}\n\\end{equation}\nnamely (abelian) ``integration'' with respect to the map in \\Cat\n\\[p_A:A\\to\\Simplex_0.\\]\nThus, ultimately, \\emph{abelianizators for $A$} (or what we may call\n``standard abelianizators'', if there should turn out to be any\nothers, and that they are worth looking at) \\emph{turn out to be no\n  more, no less than just a projective resolution, in the category\n  \\eqref{eq:102.12} of functors from \\Ahatab{} to \\Ab{} commuting with\n  small direct limits, of the most interesting object in the category,\n  namely the functor}\n\\begin{equation}\n  \\label{eq:102.15}\n  p_{A!}\\supab \\simeq \\varinjlim_B : \\Ahatab\\to\\Ab.\\tag{15}\n\\end{equation}\nWe are far indeed from the faltering reflections of section\n\\ref{sec:91}, about computing homology and cohomology of homotopy\nmodels described in terms of test categories deduced some way or other\nfrom cellular decompositions of spheres!\n\n\\bigbreak\n\n\\presectionfill\\ondate{11.8.}\\pspage{382}\\par\n\n% 103\n\\hangsection{Integrators versus cointegrators.}\\label{sec:103}%\nIt has been over three weeks now I haven't been working on the\nnotes. Most part of this time was spent wandering in the Pyrenees with\nsome friends (a kind of thing I hadn't been doing since I was a boy),\nand touring some other friends living the simple life around there, in\nthe mountains. I was glad to meet them and happy to wander and breathe\nthe fresher air of the mountains -- and very happy too after two weeks\nto be back in the familiar surroundings of my home amidst the gentle\nhills covered with vineyards\\ldots Yesterday I resumed mathematical\nwork -- I had to spend the day doing scratchwork in order to get back\ninto it, now I feel ready to go on with the notes. I'll have to finish\nin the long last with that abelianization story I got into\nunpremeditatedly -- which turns out to be essentially the same thing\nas some systematics about (commutative) cohomology and homology, in\nthe context of ``models'' in \\Cat, or in a category \\Ahat{} (with $A$\nis \\Cat). We were out for proving a statement about ``integrators''\nfor a small category $B$ being ``abelianizators'' for the dual\ncategory $A=B\\op$. The proof I had in mind for this is somewhat\nindirect via cohomology, and follows the proof I gave myself a very\nlong time ago (in case $A\\Simplex$), that the usual semi-simplicial\nboundary operations do give the correct (topos-theoretic) cohomology\ninvariants for any object $X$ in \\Ahat{} (i.e., any semisimplicial\nset), for any locally constant coefficients on $A_{/X}$. The idea was\nto replace $A_{/X}$ by the dual category\n$(A_{/X})\\op=\\preslice{A\\op}X$ (which, according to a nice result of\nQuillen, has a homotopy type canonically isomorphic to the one defined\nby $A_{/X}$), and use the canonical functor\n\\[f = (p_X)\\op : (A_{/X})\\op \\to A\\op\\eqdef B,\\]\nwhich is a cofibration with discrete fibers, and hence gives rise, for\nany abelian presheaf $F$ on the category $C$ upstairs, to an\nisomorphism\n\\[\\mathrm R \\Gamma(C,F) \\simeq \\mathrm R\\Gamma(B,f_*(F))\\]\n(due to $\\mathrm Rf_*(F) \\fromsim f_*(F)$, as $f_*$ is exact,\ndue to the fact that $f$ is a cofibration with discrete fibers). We'll\nget Quillen's result about the isomorphism $C\\simeq C\\op$ in \\Hot, for\nany object $C$ in \\Cat, very smoothly in part \\ref{ch:VI}, as a result\nof the asphericity story of part \\ref{ch:IV}. However, I now realize\nthat the proof of the fact about abelianizators via Quillen's result\nand cohomology is rather awkward, as what we're after now is typically\na result on homology, not cohomology -- and I was really turning it\nupside down in order to fit it at all costs into the\\pspage{383} more\nfamiliar (to me) cohomology pot! Therefore, I'm not going to write out\nthis proof, as ``the'' natural proof is going to come out by itself,\nonce we got a good conceptual understanding of homology, cohomology\nand abelianization, in the context of ``spaces'' embodies by objects\nof \\Cat. Thus, I feel what is mainly needed now is an overall review\nof the relevant notions and facts along these lines -- most of which\nwe've come in touch with before, be it only ``en passant''.\n\nBefore starting, just an afterthought on terminology. It occurred to\nme that the name of an ``integrator'' (for $A$), for a projective\nresolution of the constant abelian presheaf $\\bZ_A$ in \\Ahatab, is\ninaccurate -- as it was meant to suggest that its main use is for\nallowing computation, for an arbitrary abelian presheaf (or complex of\nsuch presheaves) $F$ on $A$, of $\\mathrm R\\Gamma(A,F)$, which we were\nthinking of by that time as the ``integration'' of $F$ over $A$ (or\nover the associated topos). But it has turned out that for the sake of\ncoherence with a broader use of the notions of ``integration'' and\n``cointegration'' (compare section \\ref{sec:69}), the appropriate\ndesignation of $\\mathrm R\\Gamma(A,F)$ is ``\\emph{co}integration'' of\n$F$ over $A$, not integration. Therefore, the appropriate designation\nfor a projective resolution $L_\\bullet^A$ of $\\bZ_A$, allowing\ncomputational expression of cointegration, is ``cointegrator'' (for\n$A$) rather than ``integrator''. On the other hand, in terms of the\ndual category $B=A\\op$, it turns out that such $L_\\bullet^A$ allows\ncomputational expression of \\emph{integration} (i.e., homology) over\n$B$, and therefore it seems adequate to call $L_\\bullet^A$ also an\n\\emph{``integrator'' for $B$}. Moreover, it turns out that such an\nintegrator for $B$ is equally an ``abelianizator'' for $B$, i.e., it\nallows simultaneous computation of the ``abelianizations'' of the\nhomotopy types defined by arbitrary objects $X$ in \\Ahat, in terms of\nthe abelianization $\\Wh_A(X)=\\bZ^{(X)}$ of $X$ (cf.\\ sections\n\\ref{sec:93} and \\ref{sec:102}) -- and possibly the converse holds\ntoo. Whether this is so or not, there doesn't seem at present much\nsense to bother about abelianizators which do not come from\nintegrators, while the latter have the invaluable advantage (besides\nmere existence) of being unique up to homotopism. Thus, in practical\nterms, it would seem that abelianizators (for a given small category\n$B$) are no more no less than just integrators (for the same $B$,\ni.e., cointegrators for $A=B\\op$) -- and I would therefore suggest to\nsimply drop the designation ``abelianizator'' for the benefit of the\nsynonym ``integrator'', which fits more suggestively into the pair of\ndual notions integrator---cointegrator.\\pspage{384}\n\n% 104\n\\hangsection{Overall review on abelianization\n  \\texorpdfstring{\\textup{(1)}}{(1)}: Case of\n  pseudo-topoi.}\\label{sec:104}%\nI'll have after all to give a certain amount of functorial ``general\nnon-sense'' which I've tried to bypass so far.\n\n\\subsection{Pseudo-topoi and adjunction equivalences.}\n\\label{subsec:104.A}\nIn what follows, ordinary capital letters as $A,B,\\ldots$ will\ngenerally denote small categories (mostly objects in \\Cat), whereas\nround capital letters $\\scrA,\\scrB,\\scrM$ will denote \\scrU-categories\nwhich may be ``large'', for instance $\\scrA=\\Ahat$, $\\scrB=\\Bhat$,\netc.  For two such categories $\\scrA,\\scrB$, we denote by\n\\begin{equation}\n  \\label{eq:104.1}\n  \\bHom_!(\\scrA,\\scrB), \\quad \\bHom^!(\\scrA,\\scrB)\\tag{1}\n\\end{equation}\nthe full subcategories of the functor category $\\bHom(\\scrA,\\scrB)$,\nmade up with all functors which commute with small direct or inverse\nlimits respectively. This notation is useful mainly in case \\scrA{}\nand \\scrB{} are stable under small direct resp.\\ inverse limits, in\nwhich case the same holds true for the corresponding category\n\\eqref{eq:104.1}, because as a full subcategory of\n$\\bHom(\\scrA,\\scrB)$ (where direct resp.\\ inverse limits exist and are\ncomputed componentwise) it is stable under direct resp.\\ inverse\nlimits. Thus, the inclusion functors\n\\begin{equation}\n  \\label{eq:104.2}\n  \\bHom_!(\\scrA,\\scrB) \\to \\bHom(\\scrA,\\scrB),\\quad\n  \\bHom^!(\\scrA,\\scrB) \\to \\bHom(\\scrA,\\scrB)\\tag{2}\n\\end{equation}\ncommute with direct resp.\\ inverse limits, i.e., those limits in the\ncategories \\eqref{eq:104.1} are computed equally componentwise.\n\nThe canonical inclusion\n\\[\\scrA \\hookrightarrow \\bHom(\\scrA\\op,\\Sets)\\]\nfactors into a fully faithful inclusion functor\n\\begin{equation}\n  \\label{eq:104.3}\n  \\scrA \\hookrightarrow \\bHom^!(\\scrA\\op,\\Sets).\\tag{3}\n\\end{equation}\nLet's recall the non-trivial useful result:\n\\begin{propositionnum}\\label{prop:104.1}\n  Assume the \\scrU-category \\scrA{} is stable under small direct\n  limits, and admits a small full subcategory $A$ which is\n  ``generating for monomorphisms'', i.e., any monomorphism $i:X\\to Y$\n  in \\scrA{} such that $\\Hom(Z,i):\\Hom(Z,X)\\to\\Hom(Z,Y)$ is bijective\n  for any $Z$ in $C$, is an isomorphism. Then the fully faithful\n  functor \\eqref{eq:104.3} is an equivalence, i.e., any functor\n  \\[\\scrA\\op\\to\\Sets\\]\n  that commutes with small inverse limits is representable.\n\\end{propositionnum}\n\nFor a proof,\\scrcomment{\\textcite{SGA4vol1}} see SGA~4~I~8.12.7.\n\n\\begin{corollarynum}\\label{cor:104.prop1.1}\n  If \\scrA{} satisfies the assumptions above, then \\scrA{} is equally\n  stable under small \\emph{inverse} limits.\n\\end{corollarynum}\n\nFor\\pspage{385} the sake of brevity, we'll say that a \\scrU-category\nsatisfying the assumptions of prop.\\ \\ref{prop:104.1} is a\n\\emph{pseudo-topos} (as these conditions are satisfied for any\ntopos). We get at once the\n\\begin{corollarynum}\\label{cor:104.prop1.2}\n  Let $\\scrA,\\scrB$ be two pseudo-topoi. Then a functor from $\\scrA$\n  to $\\scrB\\op$ \\textup(resp.\\ from $\\scrB\\op$ to \\scrA\\textup) has a\n  right adjoint \\textup(resp.\\ a left adjoint\\textup) if{f} it\n  commutes to small direct limits \\textup(resp.\\ to small inverse\n  limits\\textup). Thus, taking right and left adjoints we get two\n  equivalences of categories, quasi-inverse to each other\n  \\begin{equation}\n    \\label{eq:104.4}\n    \\bHom_!(\\scrA,\\scrB\\op)\\leftrightarrows\\bHom^!(\\scrB\\op,\\scrA),\\tag{4}\n  \\end{equation}\n  and the two members of \\eqref{eq:104.4} are canonically equivalent\n  to the category\n  \\begin{equation}\n    \\label{eq:104.5}\n    \\bHom^{!!}(\\scrA\\op,\\scrB\\op; \\Sets)\\tag{5}\n  \\end{equation}\n  of functors\n  \\[\\scrA\\op\\times\\scrB\\op\\to\\Sets\\]\n  which commute with small inverse limits with respect to either\n  variable \\textup(the other being fixed\\kern1pt\\textup), \\eqref{eq:104.5}\n  being viewed as a full subcategory of $\\bHom(\\scrA\\op\\times\\scrB\\op,\n  \\Sets)$.\n\\end{corollarynum}\n\\begin{remarks}\n  \\namedlabel{rem:104.1}{1})\\enspace The first-hand side of\n  \\eqref{eq:104.4} is tautologically isomorphic to the category\n  $\\bHom^!(\\scrA\\op,\\scrB)$ (as for any two \\scrU-categories we have\n  the tautological isomorphism\n  \\begin{equation}\n    \\label{eq:104.6}\n    (\\bHom_!(\\mathscr P,\\mathscr Q))\\op \\simeq \\bHom^!(\\mathscr P\\op,\n    \\mathscr Q\\op)\\quad\\text{),}\\tag{6}\n  \\end{equation}\n  thus, the equivalence \\eqref{eq:104.4} can be seen more\n  symmetrically as an equivalence\n  \\begin{equation}\n    \\label{eq:104.4prime}\n    \\bHom^!(\\scrA\\op,\\scrB)\\simeq\\bHom^!(\\scrB\\op,scrA),\\tag{4'}\n  \\end{equation}\n  both categories being equivalent to \\eqref{eq:104.5} using the\n  equivalence \\eqref{eq:104.3} for the second, and the corresponding\n  equivalence for \\scrB{} for the first, plus the tautological\n  isomorphism\n  \\begin{equation}\n    \\label{eq:104.7}\n    \\bHom^!(\\scrP, \\bHom^!(\\scrQ,\\scrM)) \\simeq\n    \\bHom^{!!}(\\scrP, \\scrQ; \\scrM),\\tag{7}\n  \\end{equation}\n  for any three \\scrU-categories $\\scrP,\\scrQ,\\scrM$.\n\n  \\namedlabel{rem:104.2}{2})\\enspace When \\scrA{} is a topos, \\scrB{}\n  any \\scrU-category stable under small inverse limits, then we may\n  interpret the category $\\bHom^!(\\scrA\\op,\\scrB)$ as the category of\n  \\emph{\\scrB-valued sheaves} on the topos (defined by) \\scrA. When\n  \\scrA{} and \\scrB{} are both topoi, then the equivalence\n  \\eqref{eq:104.4} states that \\scrB-valued sheaves on \\scrA{} can be\n  identified with \\scrA-valued sheaves on \\scrB, and both may be\n  identified with set-valued ``bi-sheaves'' on $\\scrA\\times\\scrB$. In\n  case the topoi \\scrA, \\scrB{} are defined respectively by\n  \\scrU-sites $A$, $B$ (not necessarily small ones),\\pspage{386} these\n  bisheaves can be interpreted in a rather evident way as bisheaves on\n  $A\\times B$, namely functors\n  \\[A\\op\\times B\\op\\to\\Sets\\]\n  which are sheaves with respect to each variable (the other being\n  fixed). It is easy to check that the category of all such bisheaves\n  is again a topos, and that the latter is a $2$-product of the two\n  topoi \\scrA, \\scrB{} in the $2$-category of all topoi -- it plays\n  exactly the same geometrical role as the usual product for two\n  topological spaces\\ldots\n\\end{remarks}\n\n\\subsection{Abelianization of a pseudo-topos.}\n\\label{subsec:104.B}\nLet \\scrA{} be a pseudo-topos, and let's denote by\n\\begin{equation}\n  \\label{eq:104.8}\n  \\scrAab\\tag{8}\n\\end{equation}\nthe category of abelian group-objects in \\scrA. It is immediate that\nthe forgetful functor\n\\begin{equation}\n  \\label{eq:104.9}\n  \\scrAab\\to\\scrA\\tag{9}\n\\end{equation}\ncommutes with small direct limits (and that such limits exist in\n$\\scrAab$, whereas they exist in \\scrA{} by cor.\\ \\ref{cor:104.prop1.1}\nabove) -- thus, we may expect that this functor admits a left\nadjoint. When so, this will be denoted by\n\\begin{equation}\n  \\label{eq:104.10}\n  \\Wh_\\scrA : \\scrA\\to\\scrAab,\\tag{10}\n\\end{equation}\nwe'll write also\n\\[\\Wh(X)=\\bZ^{(X)}\\]\nwhen no confusion may arise. The abelianization functor exists for\ninstance when \\scrA{} is a topos, in this case it is well-known that\n$\\scrAab$ is not only an additive category, but an \\emph{abelian}\ncategory with small filtering direct limits which are exact, and a\nsmall generating subcategory. This in turn ensures, as well-known too,\nthat any object of $\\scrAab$ can be embedded into an injective one,\nand from this follows (cf.\\ SGA~4\nI~7.12)\\scrcomment{\\textcite{SGA4vol1}} that $\\scrAab$ admits also a\nsmall full subcategory which is \\emph{co}generating with respect to\nepimorphisms, in other words that $\\scrAab$ is not only an abelian\npseudo-topos, but that the dual category $(\\scrAab)\\op$ is a\npseudo-topos too. Conversely (kind of), without assuming \\scrA{} to be\na topos, if we know some way or other (but this may be hard to check\ndirectly\\ldots) that $(\\scrAab)\\op$ is a pseudo-topos, then it follows\nfrom cor.\\ \\ref{cor:104.prop1.2} above that the abelianization functor\n$\\Wh_\\scrA$ exists, and this in turn implies that $\\scrAab$ is a\npseudo-topos, i.e., admits a small full subcategory which is\ngenerating with respect to monomorphisms (as we see by taking such a\nfull subcategory\\pspage{387} $A$ in \\scrA, and the full subcategory in\n$\\scrAab$ generated by $\\Wh_\\scrA(A)$).\n\nLet now \\scrM{} be an \\emph{additive} \\scrU-category, which is\nmoreover a \\emph{pseudo-cotopos}, i.e., the dual category $\\scrM\\op$\nis a pseudo-topos. Using twice the corollary \\ref{cor:104.prop1.2} above,\nfor the pair of pseudotopoi $(\\scrA,\\scrM\\op)$ and\n$(\\scrAab,\\scrM\\op)$, we get the sequence of equivalences of\ncategories\n\\[\\bHom_!(\\scrA,\\scrM)\\equeq\\bHom^!(\\scrM,\\scrA)\\op \\fromequ\n\\bHom^!(\\scrM,\\scrAab)\\op \\equeq \\bHom_!(\\scrAab,\\scrM),\\]\nwhere the second equivalence of categories comes from the fact that\nany functor\n\\[f:\\scrM\\to\\scrA\\]\nfrom an \\emph{additive} category \\scrM{} to a category \\scrA, which\ncommutes with finite products, factors canonically through\n$\\scrAab\\to\\scrA$. We are interested now in the composite\nequivalence\n\\begin{equation}\n  \\label{eq:104.11}\n  \\bHom_!(\\scrA,\\scrM)\\equeq\\bHom_!(\\scrAab,\\scrM),\\tag{11}\n\\end{equation}\ndefined under the only assumption that \\scrM{} is additive and the\ncategories \\scrA, $\\scrAab$ and $\\scrM\\op$ are pseudotopoi\n(without having to assume the existence of the abelianization functor\n$\\Wh_\\scrA$). This equivalence is functorial for variable additive\npseudo-cotopos \\scrM, when we take as ``maps'' $\\scrM\\to\\scrM'$\nfunctors which commute to small direct limits (a fortiori, these are\nright exact and hence additive). In case $\\scrAab$ itself is among\nthe eligible \\scrM's, i.e., is a pseudo-cotopos (not only\npseudotopos), we may say that \\emph{$\\scrAab$ $2$-represents the\n  $2$-functor $\\scrM\\mapsto\\bHom_!(\\scrA,\\scrM)$} on the $2$-category\nof all additive pseudo-cotopoi and functors between these commuting to\nsmall direct limits. As we noticed above, the assumption just made\nimplies that $\\Wh_\\scrA$ exists. On the other hand, assuming merely\nexistence of $\\Wh_\\scrA$ (besides \\scrA{} being a pseudo-topos), which\nimplies that $\\scrAab$ is equally a pseudotopos as we say above,\nit is readily checked that the equivalence \\eqref{eq:104.11} can be\ndescribed as\n\\begin{equation}\n  \\label{eq:104.12}\n  F\\mapsto F\\circ\\Wh_\\scrA : \\bHom_!(\\scrAab,\\scrM) \\toequ\n  \\bHom_!(\\scrA,\\scrM).\\tag{12} \n\\end{equation}\nThus, we get the\n\\begin{propositionnum}\\label{prop:104.2}\n  Let \\scrA{} be a pseudotopos such that the abelianization functor\n  \\eqref{eq:104.10} exists \\textup(\\kern2pt for instance \\scrA{} a\n  topos\\textup). Then $\\scrAab$ is a pseudotopos and an additive\n  category. Moreover, for any additive category \\scrM{} which is a\n  pseudo-cotopos, the functor \\eqref{eq:104.12} is an equivalence of\n  categories. \n\\end{propositionnum}\n\\setcounter{corollarynum}{0}\n\\begin{corollarynum}\\label{cor:104.prop2.1}\n  Let\\pspage{388} \\scrA{} be a pseudotopos such that $\\scrAab$ is\n  a pseudotopos \\textup(\\kern2pt for instance, \\scrA{} is a\n  topos\\textup). Then the abelianization functor $\\Wh_\\scrA$ exists,\n  and this functor is $2$-universal for functors from \\scrA{} into\n  \\scrU-categories which are both additive and are pseudotopoi\n  \\textup(maps between these being functors which commute with small\n  direct limits\\textup).\n\\end{corollarynum}\n\nBy duality, using \\eqref{eq:104.6}, we can restate the equivalence\n\\eqref{eq:104.12} as\n\\begin{equation}\n  \\label{eq:104.13}\n  F\\mapsto F\\circ\\Wh\\op : \\bHom^!(\\scrAab\\op,\\scrN) \\toequ\n  \\bHom^!(\\scrA\\op,\\scrN),\\tag{13}\n\\end{equation}\nvalid provided \\scrA{} is a pseudo-topos, $\\Wh_\\scrA$ exists, and\n\\scrN{} is an additive category which is moreover a pseudotopos.\n\nTake for instance $\\scrN=\\Ab$, the category of abelian groups, i.e.,\n\\[\\scrN=\\scrB\\subab, \\quad\\text{where $\\scrB=\\Sets$,}\\]\nthen as already noticed above the left hand side of \\eqref{eq:104.13}\nis canonically equivalent with\n$\\bHom^!(\\scrAab\\op,\\scrB)=\\bHom^!(\\scrAab\\op,\\Sets)$, as\n$\\scrAab\\op$ is additive; on the other hand, by prop.\\\n\\ref{prop:104.1} applied to the pseudotopos $\\scrAab$ we get\n\\[\\scrAab\\toequ \\bHom^!(\\scrAab\\op,\\Sets) \\quad\\bigl(\\fromequ\n\\bHom^!(\\scrAab\\op,\\Ab)\\bigr),\\]\nand hence an equivalence\n\\begin{equation}\n  \\label{eq:104.14}\n  \\scrAab \\toequ\\bHom^!(\\scrA\\op,\\Ab), \\quad\n  F\\mapsto\\bigl(X\\mapsto\\Hom(X,F)\\bigr),\\tag{14}\n\\end{equation}\nvalid whenever \\scrA{} is a pseudotopos such that $\\Wh_\\scrA$\nexists. When \\scrA{} is a topos, this corresponds to the familiar fact\nthat an abelian group object in the category of sheaves (of sets) on a\ntopos, can be interpreted equally as a sheaf on the topos with values\nin the category \\Ab{} of abelian groups.\n\n\\subsection{Interior and exterior operations\n  \\texorpdfstring{$\\otimes_{\\bZ}$ and $\\Hom_{\\bZ}$}{tensorZ and\n    HomZ}.}\\label{subsec:104.C}\nIn the first place, I want to emphasize the basic tensor product\noperation\n\\begin{equation}\n  \\label{eq:104.15}\n  (F,G)\\mapsto F\\otimes_{\\bZ} G : \\scrAab\\times\\scrAab \\to \\scrAab\\tag{15}\n\\end{equation}\nbetween abelian group objects of the pseudotopos \\scrA, defined as\nusual argumentwise as the solution of the universal problem, expressed\nby the ``Cartan isomorphism''\n\\begin{equation}\n  \\label{eq:104.16}\n  \\Hom_\\scrAab(F\\otimes G, H) \\simeq \\Bil_{\\bZ}(F,G ; H),\\tag{16}\n\\end{equation}\nwhere we dropped the subscript $\\bZ$ in the tensor product, and where\n$\\Bil_{\\bZ}$ or simply $\\Bil$ denotes the set of maps $F\\times G\\to H$\nwhich are ``biadditive'' in the usual sense of the word. Thus, the\nexistence of \\eqref{eq:104.15}\\pspage{389} just means, by definition,\nthat for any pair $(F,G)$ of objects in \\scrAab, the functor in\n$H$\n\\[H \\mapsto \\Bil(F,G;H)\\]\nis representable. It is clear that this functor commutes with small\ninverse limits, hence by prop.\\ \\ref{prop:104.1} it is representable,\nprovided we know that \\scrAab{} is a pseudo-cotopos (for instance,\nwhen \\scrA{} is a topos, in which case the existence of tensor\nproducts is anyhow a familiar fact). The familiar Bourbaki\nconstruction of a tensor product amounts on the other hand to viewing\n$F\\otimes G$ as a quotient of $\\Wh_\\scrA(F\\times G)=\\bZ^{(F\\times G)}$ by\nsuitable ``relations'', i.e., as the cokernel of a map in\n\\scrAab\n\\[L_1\\to L_0=\\Wh_\\scrA(F\\times G),\\]\nwhere, as a matter fact, $L_1$ can be described as\n\\[L_1=\\Wh_\\scrA(F\\times F\\times G) \\times \\Wh_\\scrA(F\\times G\\times\nG).\\]\nThus, if we know beforehand that cokernels exist in \\scrAab{}\n(which would indeed follow from \\scrAab{} being a pseudotopos, but\nmay be checked more readily in terms of suitable exactness properties\nof \\scrA{} directly), plus the existence of course of $\\Wh_\\scrA$, the\ntensor product functor \\eqref{eq:104.15} exists. (On the other hand,\nno use is made here of the assumption that \\scrA{} be a pseudotopos.)\n\nLet's assume the tensor product functor \\eqref{eq:104.15} exists. Then\nit is readily checked it is associative and commutative up to\ncanonical isomorphisms, giving rise to the usual compatibilities. If\nmoreover $\\Wh_\\scrA$ exists, we readily get the canonical isomorphism\n\\begin{equation}\n  \\label{eq:104.17}\n  \\Wh_\\scrA(X\\times Y)\\eqdef\\bZ^{(X\\times Y)} \\fromsim\n  \\Wh_\\scrA(X)\\otimes \\Wh_\\scrA(Y)\\quad \\bigl(\\eqdef\n  \\bZ^{(X)}\\otimes\\bZ^{(Y)}\\bigr),\\tag{17} \n\\end{equation}\ncompatible of course with the commutativity and associativity\nisomorphisms for the operations $\\times$ and $\\otimes$. If on the\nother hand \\scrA{} admits moreover a final object (as it does if\n\\scrA{} is a pseudotopos and hence stable under small direct limits),\nthen\n\\begin{equation}\n  \\label{eq:104.18}\n  \\bZ_\\scrA \\eqdef \\Wh_\\scrA(e) = \\bZ^{(e)}\\tag{18}\n\\end{equation}\nis a two-sided unit for the tensor product operation.\n\nIn what follows, we are interested in categories of the type\n\\begin{equation}\n  \\label{eq:104.19}\n  \\scrA^\\scrM \\eqdef\\bHom_!(\\scrA,\\scrM), \\quad\\scrA_\\scrN\n  \\eqdef\\bHom^!(\\scrA\\op,\\scrN)\\tag{19} \n\\end{equation}\nwhere now \\scrA{} is assumed to be a fixed pseudotopos, and \\scrM{}\nand \\scrN{} are\\pspage{390} \\emph{additive} categories, \\scrM{} being\nmoreover a pseudo-cotopos, \\scrN{} a pseudotopos. We assume moreover\nthat $\\Wh_A$ exists, and hence the categories \\eqref{eq:104.19} can be\ninterpreted up to equivalence, via \\eqref{eq:104.12} and\n\\eqref{eq:104.13}, as\n\\begin{equation}\n  \\label{eq:104.19prime}\n  \\bHom_!(\\scrAab, \\scrM), \\quad \\bHom^!(\\scrAab\\op,\\scrN).\\tag{19'}\n\\end{equation}\nLet's remark that the dual of a category of one of the types\n\\eqref{eq:104.19} (or equivalently, \\eqref{eq:104.19prime}) is\nisomorphic to a category of the other type, more accurately, by\n\\eqref{eq:104.6} we get\n\\begin{equation}\n  \\label{eq:104.20}\n  \\bHom_!(\\scrA,\\scrM)\\op\\tosim\\bHom^!(\\scrA\\op,\\scrN),\\tag{20}\n\\end{equation}\ni.e., $(\\scrA^\\scrM)\\op\\tosim\\scrA_\\scrN$, with $\\scrN=\\scrM\\op$. In\ncase \\scrA{} is a topos, the objects of the second category\n$\\scrA_\\scrN$ in \\eqref{eq:104.19} (or equivalently, in\n\\eqref{eq:104.19prime}) can be interpreted as \\emph{\\scrN-valued\n  sheaves} on the topos \\scrA, whereas the object of the first,\n$\\scrA^\\scrM$, may be called, correspondingly, \\emph{cosheaves on\n  \\scrA{} with values in \\scrM}. Thus, in virtue of \\eqref{eq:104.20},\n\\scrM-valued cosheaves on \\scrA{} can be interpreted as\n$scrN=\\scrM\\op$-valued sheaves on \\scrA, the corresponding categories\nof cosheaves and sheaves being however \\emph{dual} to each other. In\nthe next subsection \\ref{subsec:105.D}, when $\\scrA=\\Ahat$, we'll\ninterpret moreover \\scrM-valued cosheaves on \\scrA{} (or on $A$, as\nwe'll call them equivalently) as \\scrM-valued \\emph{sheaves} on the\n(topos associated to the) dual category $B=A\\op$, and in this context\nthe difference between the categories of cosheaves and of sheaves\n(which for the time being appear as categories \\emph{dual} to each\nother) will disappear altogether, provided we allow the ground topos\n\\scrA{} to change (from $\\scrA=\\Ahat$ to the ``dual'' topos\n$\\scrB=\\Bhat$).\n\nIn terms of the expressions \\eqref{eq:104.19prime} of the category of\n``cosheaves'' and ``sheaves'' we are interested in, we want now to\ndefine an external operation of the fixed category \\scrAab{} on those\ncategories, using the tensor product operation \\eqref{eq:104.15} in\n\\scrAab. What is needed visibly for this end is that for fixed $F$,\nthe functor\n\\begin{equation}\n  \\label{eq:104.21}\n  G\\mapsto F\\otimes G\\tag{21}\n\\end{equation}\nfrom \\scrAab{} to itself should commute with small direct limits --\nhence composing it with a functor $L$ in $\\bHom_!(\\scrAab,\\scrM)$ will\nyield a functor in the same category, which will be the looked-for\nexternal tensor product $F\\oast L$, i.e.,\n\\begin{equation}\n  \\label{eq:104.22}\n  \\mathop{F\\oast L}(G) = L(F\\otimes G),\\tag{22}\n\\end{equation}\nwhich we may write more suggestively as\n\\begin{equation}\n  \\label{eq:104.22prime}\n  G * (F \\oast L) = (G \\otimes F) * L,\\tag{22'}\n\\end{equation}\nwith the notation\n\\begin{equation}\n  \\label{eq:104.23}\n  H * L \\eqdef L(H), \\quad\\text{for $H$ in \\scrAab, $L$ in\n    $\\scrA^\\scrM=\\bHom_!(\\scrA,\\scrM)$,}\\tag{23}\n\\end{equation}\nwhich\\pspage{391} will be convenient mainly in the context of the next\nsubsection (when \\scrA{} is of the type \\Ahat).\n\nThe exactness property needed for the functor \\eqref{eq:104.21} is\nequivalent with the property that for any object $H$ in \\scrAab, the\nfunctor\n\\[G\\mapsto \\Hom(F\\otimes G,H) \\simeq \\Bil(F,G;H)\\]\nfrom $\\scrAab\\op$ to \\Sets{} commute with small inverse limits. As\n\\scrAab{} is a pseudotopos (prop.\\ \\ref{prop:104.2}), this is\nequivalent by prop.\\ \\ref{prop:104.1} with this functor being\nrepresentable. By definition of $\\Bil$, we get\n\\[\\Bil(F,G;H)\\simeq\\Hom_{\\scrA\\subab\\uphat}(G, \\bHom_{\\bZ}(F,H)),\\]\nwhere the object\n\\begin{equation}\n  \\label{eq:104.24}\n  \\bHom_{\\bZ}(F,H)\\tag{24}\n\\end{equation}\nis taken in the category of presheaves $\\scrA\\subab\\uphat$ (cheating a\nlittle with universes here\\ldots). To sum up, the condition we want\nfor \\eqref{eq:104.21} just boils down to the representability of the\nabelian group objects \\eqref{eq:104.24} in $\\scrA\\subab\\uphat$, for\nany two objects $F,G$ in \\scrAab, i.e., essentially to the existence\nof ``internal $\\bHom$'s'' in the category \\scrAab{} (endowed with the\ntensor product $\\otimes_{\\bZ}$), satisfying the familiar Cartan\nisomorphism formula\n\\begin{equation}\n  \\label{eq:104.25}\n  \\Hom(F\\otimes G,H) \\simeq\\Hom(G,\\bHom(F,H)).\\tag{25}\n\\end{equation}\n\nTo sum up, what is needed for a nice formalism of interior and\nexterior tensor products and $\\Hom$'s for ``sheaves'' and\n``presheaves'' on the pseudotopos \\scrA, are the following assumptions\non \\scrA:\n\\begin{enumerate}[label=\\arabic*)]\n\\item\\label{it:104.C.1}\n  Tensor products and corresponding internal $\\bHom$'s exist in\n  \\scrAab, and\n\\item\\label{it:104.C.2}\n  the abelianization functor $\\Wh_\\scrA$ \\eqref{eq:104.15} exists,\n\\end{enumerate}\nthe latter assumption being needed in order to feel at ease with the\nequivalence between the categories \\eqref{eq:104.19} of sheaves and\ncosheaves, and their ``abelianized'' interpretations\n\\eqref{eq:104.19prime}.\n\nUnder these assumptions, we define the exterior tensor product\noperation of \\scrAab{} upon a category of cosheaves $\\scrA^\\scrM$\n\\begin{equation}\n  \\label{eq:104.26}\n  \\scrAab\\times\\scrA^\\scrM \\to \\scrA^\\scrM, \\quad\n  (F,L)\\mapsto F\\oast L,\\tag{26}\n\\end{equation}\nby formula \\eqref{eq:104.22} (which may be written also under the form\n\\eqref{eq:104.22prime}). This operation has the obvious associativity\nproperty\n\\begin{equation}\n  \\label{eq:104.27}\n  F\\oast(G\\oast L)\\simeq (F\\otimes G)\\oast L,\\tag{27}\n\\end{equation}\nand moreover the unit $\\bZ_\\scrA$ for the internal tensor product in\n\\scrAab{} operators on $\\scrA^\\scrM$ as the identity functors,\ni.e.,\\pspage{392}\n\\begin{equation}\n  \\label{eq:104.28}\n  \\bZ_\\scrA\\oast L\\simeq L.\\tag{28}\n\\end{equation}\n\nUsing the tautological duality relation \\eqref{eq:104.20} between\ncategories of cosheaves (with values in \\scrM) and categories of\nsheaves (with values in $\\scrN=\\scrM\\op$), we deduce accordingly an\nassociative and unitary operation of \\scrAab{} on any category of the\ntype $\\scrA_\\scrN$, namely \\scrN-valued sheaves on \\scrA. This\noperation is most conveniently denoted by the $\\bHom$ symbol\n\\begin{equation}\n  \\label{eq:104.29}\n  (F,K)\\mapsto \\bHom(F,K): \\scrAab\\op\\times\\scrA_\\scrN\\to\\scrA_\\scrN,\\tag{29}\n\\end{equation}\nits explicit description in terms of $K$, viewed as a functor\n\\[K:\\scrAab\\op\\to\\scrN\\]\nis by\n\\begin{equation}\n  \\label{eq:104.30}\n  \\bHom(F,L)(G)=K(G\\otimes F)\\tag{30}\n\\end{equation}\nfor $K$ in $\\scrA_\\scrN$, $F$ and $G$ in \\scrAab. This may be written\nmore suggestively as\n\\begin{equation}\n  \\label{eq:104.30prime}\n  \\Hom(G, \\bHom(F,L)) \\simeq \\Hom(G\\otimes F, K),\\tag{30'}\n\\end{equation}\nsimilar to \\eqref{eq:104.22prime}, where we use the notation $\\Hom$\n(non-bold!)\\scrcomment{In the typescript this parenthetical remark\n  says ``non-underlined!'', as internal $\\bHom$'s there are underlined\n  rather than in boldface.} in analogy to \\eqref{eq:104.23} for\ndenoting $K(H)$, namely\n\\begin{equation}\n  \\label{eq:104.31}\n  \\Hom(H,K)\\eqdef K(H).\\tag{31}\n\\end{equation}\nIf confusion is feared, we may put a subscript $\\bZ$ in all $\\Hom$'s\nand $\\bHom$'s just introduced, as well as in the internal and external\ntensor product operations $\\otimes$, $*$, $\\oast$.\n\n\\begin{comments}\n  Take for instance\n  \\[\\scrN=\\Ab,\\quad\\text{hence $\\scrA_\\scrN\\simeq\\scrAab$}\\]\n  by prop.\\ \\ref{prop:104.1} (compare \\eqref{eq:104.14}). By this\n  equivalence, the $\\Hom$ in \\eqref{eq:104.31} is just the usual\n  $\\Hom$ set corresponding to the category structure of \\scrAab{} (the\n  $\\Hom$ endowed moreover with the structure of abelian group, coming\n  from the fact that \\scrAab{} is an additive category), whereas\n  formula \\eqref{eq:104.30prime} shows that the ``external'' $\\bHom$\n  in this case is nothing but the usual internal $\\Hom$ as\n  contemplated in \\eqref{eq:104.24}. This I hope will convince the\n  reader of the adequacy of the notation used (in case of exterior\n  operation of abelian sheaves on \\scrN-valued sheaves), and of the\n  convention \\eqref{eq:104.31}. We would like to give a similar\n  justification for the notations \\eqref{eq:104.22} \\eqref{eq:104.23}\n  used in connection with operation of abelian sheaves on \\scrM-valued\n  emph{co}sheaves, by interpreting this as the internal tensor product\n  operation in \\scrAab, for suitable choice of \\scrN. This I am afraid\n  cannot be done for\\pspage{393} an arbitrary \\scrA{} satisfying our\n  assumptions, even when \\scrA{} is a topos and even when it is of the\n  special type \\Ahat, as I do not know of any \\scrM{} such that\n  \\begin{equation}\n    \\label{eq:104.star}\n    \\scrA^\\scrM\\simeq\\scrAab.\\tag{*}\n  \\end{equation}\n  However, in case $\\scrA=\\Ahat$, introducing the dual category\n  $B=A\\op$ and $\\scrB=\\Bhat$, we get (see \\ref{subsec:105.D} below)\n  \\begin{equation}\n    \\label{eq:104.starstar}\n    \\scrA^\\scrM \\equeq \\scrB_\\scrM \\equeq\n    \\scrB\\subab\\quad\\text{if}\\quad \\scrM=\\Ab,\\tag{**}\n  \\end{equation}\n  hence we do get a canonical isomorphism \\eqref{eq:104.star} provided\n  $A=B$ say and hence $\\scrA=\\scrB$. Let's look at any rate at the\n  simplest case, namely when $A$ is a final object in \\Cat, hence\n  \\scrA{} can be identified with \\Sets, and \\scrAab{} with \\Ab, the\n  identification between the categories \\Ab{} and $\\bHom_!(\\Ab,\\Ab)$\n  being obtained (we hope!) by associating to every object $L$ in \\Ab,\n  the functor\n  \\[F\\mapsto L\\otimes F: \\Ab\\to\\Ab.\\]\n  This being so, the external operation \\eqref{eq:104.22} of \\Ab{} on\n  $\\bHom_!\\equeq\\Ab$ can be interpreted (using this identification) as\n  the interior tensor product operation in \\Ab. On the other hand, the\n  operation $*$ of \\eqref{eq:104.23} is equally interpreted as nothing\n  but the tensor product in \\Ab, which justifies the notation\n  suggesting a tensor product. It would be nice checking corresponding\n  compatibilities for a general object $A$ in \\Cat{} satisfying\n  $A=A\\op$, namely a direct sum of one-object categories $A_i$ defined\n  each in terms of a \\emph{commutative} monoid $M_i$ -- I didn't work\n  it out myself, sorry!\n\n  It should be noted that the relationship between the two exterior\n  $\\Hom$'s in \\eqref{eq:104.29} and \\eqref{eq:104.31} is essentially\n  the same as between the two exterior tensor-type operations\n  \\eqref{eq:104.26} and \\eqref{eq:104.23}, $\\Hom(F,K)$ designating an\n  object in \\scrN{} and $\\bHom(F,K)$ an \\scrN-valued sheaf on \\scrA,\n  just as $F*L$ designates an object in \\scrM{} and $F\\oast L$ an\n  \\scrM-valued cosheaf on \\scrA; the graphical device of\n  \\emph{bold-facing}\\scrcomment{in the typescript: \\emph{underlining}}\n  the symbol $\\Hom$ (used for sheaves) corresponds to the device of\n  \\emph{circling} the symbol $*$ (used for cosheaves). With this\n  luxury of explanations, I hope the notations introduced here are\n  getting through\\ldots\n\\end{comments}\n\n\\bigbreak\n\n\\presectionfill\\ondate{12.8.}\\pspage{394} and \\ondate{13.8.}\\par\n\n% 105\n\\hangsection[Review (2): duality equivalences for ``algebraic'' topoi\nand \\dots]{Review \\texorpdfstring{\\textup{(2)}}{(2)}: duality\n  equivalences for ``algebraic'' topoi and abelian topoi.}\\label{sec:105}%\nLet's go on with the overall review of abelianization.\n\\addtocounter{subsection}{3}\n\n\\subsection{Duality for topoi of the type\n  \\texorpdfstring{\\Ahat}{Ahat}, and tentative generalizations.}\n\\label{subsec:105.D}\nThe main fact, it seems, which will give rise to duality statements\nfor topoi of the type \\Ahat{} is the following, rather familiar one:\n\\addtocounter{propositionnum}{2}\n\\begin{propositionnum}\\label{prop:105.3}\n  Let $A$ be a small category, \\scrM{} a \\scrU-category stable under\n  small direct limits,\n  \\begin{equation}\n    \\label{eq:105.32}\n    \\varepsilon_A:A\\hookrightarrow\\Ahat\\tag{32}\n  \\end{equation}\n  the canonical inclusion functor. Then the following functor is an\n  equivalence of categories:\n  \\begin{equation}\n    \\label{eq:105.33}\n    F\\mapsto F\\circ\\varepsilon_A: \\bHom_!(\\Ahat,\\scrM) \\to \\bHom(A,\\scrM).\\tag{33}\n  \\end{equation}\n\\end{propositionnum}\n\nAs I am at a loss to give a reference for this standard fact of\ncategory theory, I'll give in guise of a proof the indication that a\nquasi-inverse functor for \\eqref{eq:105.33} is given by the familiar\nconstruction\n\\begin{equation}\n  \\label{eq:105.34}\n  i\\mapsto i_! : \\bHom(A,\\scrM)\\to\\bHom_!(\\Ahat,\\scrM),\\tag{34}\n\\end{equation}\nwhere for any functor\n\\[i:A\\to\\scrM,\\]\nthe functor\n\\[i_!:\\Ahat\\to\\scrM\\]\nis defined by the formula\n\\begin{equation}\n  \\label{eq:105.35}\n  i_!(F) = \\varinjlim_{\\text{$a$ in $A_{/F}$}} i(a).\\tag{35}\n\\end{equation}\nIt is readily checked (and we have already used a number of times)\nthat this functor admits a right adjoint\n\\begin{equation}\n  \\label{eq:105.36}\n  i^*:\\scrM\\to\\Ahat, \\quad i^*(x)=(a \\mapsto \\Hom(i(a),x)),\\tag{36}\n\\end{equation}\nand hence $i_!$ commutes to small direct limits, i.e., is in\n$\\bHom_!(\\Ahat,\\scrM)$, hence \\eqref{eq:105.34}.\n\\begin{remark}\n  If \\scrM{} is a pseudotopos, then by prop.\\ \\ref{prop:105.3} above\n  and by corollary \\ref{cor:104.prop1.2} of prop.\\ \\ref{prop:104.1}\n  (p.\\ \\ref{p:385}) the functor\n  \\begin{equation}\n    \\label{eq:105.37}\n    i\\mapsto i^*: \\bHom(A,\\scrM) \\to \\bHom^!(\\scrM,\\Ahat)\\tag{37}\n  \\end{equation}\n  (which in any case is fully faithful) is equally an equivalence of\n  categories. \n\\end{remark}\n\nThe\\pspage{395} equivalence \\eqref{eq:105.33} of prop.\\\n\\ref{prop:105.3} can be interpreted by saying that the canonical\nfunctor \\eqref{eq:105.32} from $A$ to \\Ahat{} is \\emph{$2$-universal},\nfor functors of $A$ into \\scrU-categories stable under small direct\nlimits, taking as ``maps'' between such categories functors which\ncommute to small direct limits. Thus, the \\scrU-category \\Ahat{} may\nbe viewed as ``the'' category deduced from $A$ by adding arbitrary\ndirect limits (disregarding the direct limits which may perchance\nalready exist in $A$\\ldots).\n\nTaking the duals of the two members of \\eqref{eq:105.33}, we get an\nequivalent statement of prop.\\ \\ref{prop:105.3}:\n\\setcounter{corollarynum}{0}\n\\begin{corollarynum}\\label{cor:105.prop3.1}\n  Let \\scrN{} be a \\scrU-category stable under small inverse\n  limits. Then the functor\n  \\begin{equation}\n    \\label{eq:105.38}\n    F\\mapsto \\varepsilon_A\\op : \\bHom^!(\\Ahat\\op,\\scrN)\\to \\bHom(A\\op,\\scrN)\\tag{38}\n  \\end{equation}\n  is an equivalence of categories.\n\\end{corollarynum}\n\nIn terms of the topos\n\\[\\scrA=\\Ahat,\\]\nwe may interpret the left-hand side of \\eqref{eq:105.33} as the\ncategory of \\scrM-valued \\emph{cosheaves} on this topos, which by\nprop.\\ \\ref{prop:105.3} can be interpreted (up to equivalence) as the\ncategory of functors from $A$ to \\scrM. Dually, the left-hand side of\n\\eqref{eq:105.38} can be viewed as the category of \\scrN-valued\n\\emph{sheaves} on the topos \\scrA, which (via the right-hand side) can\nbe interpreted up to equivalence as the category of functors\n$A\\op\\to\\scrN$, i.e., as the category of \\scrN-valued\n\\emph{presheaves} on $A$. As $A$ endowed with the coarsest\n(``chaotic'') site structure is a generating site for the topos \\scrA,\nthe equivalence \\eqref{eq:105.38} may be viewed as a particular case\nof the familiar fact, according to which (up to equivalence) the\ncategory of \\scrN-valued sheaves on a topos can be constructed in\nterms of \\scrN-valued sheaves on any \\scrU-site defining this\ntopos. (When the site structure is chaotic, then those sheaves are\njust arbitrary \\scrN-valued presheaves.)\n\nAssume now that the \\scrU-category \\scrM{} is stable under \\emph{both}\ntypes of small limits (direct and inverse). Then applying\n\\eqref{eq:105.33} for $(A,\\scrM)$ and \\eqref{eq:105.38} for\n$(B,\\scrM)$ where $B=A\\op$, we get an equivalence\n\\begin{equation}\n  \\label{eq:105.39}\n  \\delta_A^\\scrM:\\bHom_!(\\Ahat,\\scrM) \\toequ\\bHom^!(\\Bhat\\op,\\scrM),\\tag{39}\n\\end{equation}\ni.e.\\ (as announced in yesterday's notes, p.\\ \\ref{p:390}), we get:\n\\begin{corollarynum}\\label{cor:105.prop3.2}\n  Let $A$ be a small category, $B=A\\op$ the dual category, \\scrM{} any\n  \\scrU-category stable under small direct and inverse limits. Then\n  the category of \\scrM-valued \\emph{cosheaves} on the topos \\Ahat{}\n  is equivalent to\\pspage{396} the category of \\scrM-valued\n  \\emph{sheaves} on the topos \\Bhat.\n\\end{corollarynum}\n\nThis equivalence, defined up to unique isomorphism, is deduced from\nthe diagram of canonical equivalences\n\\begin{equation}\n  \\label{eq:105.40}\n  \\begin{tabular}{@{}c@{}} % another non-portable diagram, sorry!\n    \\begin{tikzpicture}[commutative diagrams/every diagram,baseline=(O.base)]\n      \\node (A) at (-3.5cm,0) {\\makebox[6ex][l]{$\\bHom_!(\\Ahat,\\scrM)\\eqdef(\\Ahat)^\\scrM$}};\n      \\node (B) at (3.5cm,0) {\\makebox[6ex][r]{$(\\Bhat)_\\scrM\\eqdef\\bHom^!(\\Bhat\\op,\\scrM)$}};\n      \\node (O) at (-1.2cm,-1.2cm) {$\\bHom(A,\\scrM)$};\n      \\node (P) at (1.2cm,-1.2cm) {$\\bHom(B\\op,\\scrM)$};\n\n      \\path[commutative diagrams/.cd, every arrow, every label]\n      (A) edge node {$\\equ$} (O)\n      (B) edge node[swap] {$\\equ$} (P);\n      \\path[commutative diagrams/.cd, every arrow, every label, equal]\n      (O) to (P);\n    \\end{tikzpicture},\n  \\end{tabular}\\tag{40}\n\\end{equation}\nand depends upon the choice of a quasi-inverse of the second vertical\nequivalence in \\eqref{eq:105.40} (which choice can be made, via the\ndual of \\eqref{eq:105.35}, via the choice of small inverse limits in\n\\scrM).\n\n\\begin{remark}\n  It is felt that the way we got the equivalence \\eqref{eq:105.39} via\n  \\eqref{eq:105.40}, the role of $A$ and $B$ in it is symmetric. To\n  give a more precise statement, consider the equivalence deduced from\n  \\eqref{eq:105.39} by passing to the dual categories of the two\n  members -- using the tautological isomorphisms \\eqref{eq:104.6} of\n  page \\ref{p:385}, we get an equivalence\n  \\begin{equation}\n    \\label{eq:105.39prime}\n    (\\delta_A^\\scrM)' : \\bHom^!((\\Ahat)\\op,\\scrN) \\toequ\n    \\bHom_!(\\Bhat,\\scrN), \\quad \\text{where\n      $\\scrN=\\scrM\\op$;}\\tag{39'}\n  \\end{equation}\n  this equivalence is \\emph{canonically quasi-inverse to the\n    equivalence $\\delta_B^\\scrN$ in opposite direction}, associated to\n  the pair $(B,\\scrN=\\scrM\\op)$ instead of $(A,\\scrM)$.\n\\end{remark}\n\nIn the rest of this subsection \\ref{subsec:105.D}, we'll elaborate on\nsome particular cases of the equivalence \\eqref{eq:105.39} between\ncosheaves and sheaves.\n\n\\textbf{Case \\namedlabel{case:105.1}{1\\textsuperscript{\\b o})}.}%\n\\enspace Assume $\\scrM=\\Sets$,\nthen by prop.\\ \\ref{prop:104.1} (p.\\ \\ref{p:384}) the right-hand side\nof \\eqref{eq:105.39} is canonically equivalent to \\Bhat{} itself,\nhence we get an equivalence\n\\begin{equation}\n  \\label{eq:105.41}\n  \\Bhat \\toequ \\bHom_!(\\Ahat,\\Sets).\\tag{41}\n\\end{equation}\nIf we want to keep track of the symmetry aspect described in the\nremark above, we may consider the functor \\eqref{eq:105.41} as being\ndeduced from a canonical ``pairing'' between the categories \\Ahat{}\nand \\Bhat\n\\begin{equation}\n  \\label{eq:105.42}\n  \\delta_A : \\Ahat\\times\\Bhat\\to\\Sets,\\tag{42}\n\\end{equation}\nwhich is an object in\n\\[\\bHom_{!!}(\\Ahat,\\Bhat; \\Sets),\\]\ni.e., which commutes to small direct limits in each variable. (For\nthis interpretation, compare the dual statement contained in formula\n\\eqref{eq:104.7} of page \\ref{p:385} -- and note that\n\\eqref{eq:105.41}, being an equivalence, commutes to small direct\nlimits, i.e., is in a category $\\bHom_!(\\Bhat, \\bHom_!(\\Ahat,\\Sets))$.)\nThis\\pspage{397} pairing gives rise, in a symmetric way, to the\nfunctor \\eqref{eq:105.41} (which is an equivalence) \\emph{and} to a\nfunctor\n\\begin{equation}\n  \\label{eq:105.41prime}\n  \\Ahat\\toequ \\bHom_!(\\Bhat,\\Sets)\\tag{41'}\n\\end{equation}\nwhich (it turns out) is none other (up to canonical isomorphism) than\n\\eqref{eq:105.41} with $B$ replaced by $A$ (and hence $A$ replaced by\n$B$), and therefore is equally and equivalence. \\emph{Thus, the\n  pairing \\eqref{eq:105.42} between the two topoi \\Ahat{} and \\Bhat{}\n  has the remarkable property that it defines an equivalence of each\n  of these topoi with the category of \\textup(set-valued\\textup)\n  cosheaves on the other.} I do not know of any other example of a\npair of topoi related in such a remarkable way, which we may express\nby saying that the two topoi are ``\\emph{dual}'' to each other.\n\nWe still have to give an explicit expression for the pairing\n\\eqref{eq:105.42}, plus a convenient notation. I'll write\n\\begin{equation}\n  \\label{eq:105.43}\n  \\delta_A(F,G) \\eqdef F * G \\quad \\text{for $F$ in \\Ahat, $G$ in \\Bhat,}\\tag{43}\n\\end{equation}\nand I'll use the canonical equivalence (valid for any pair of small\ncategories $A,B$ -- not necessarily dual to each other -- and any\n\\scrU-category stable under direct limits), deduced by twofold\napplication of prop.\\ \\ref{prop:105.3}, plus the tautological\nisomorphism similar to \\eqref{eq:104.7} p.\\ \\ref{p:385}:\n\\begin{equation}\n  \\label{eq:105.44}\n  \\bHom_{!!}(\\Ahat,\\Bhat;\\scrM) \\toequ \\bHom(A\\times B,\\scrM), \\quad\n  F\\mapsto F\\circ(\\varepsilon_A\\times\\varepsilon_B),\\tag{44}\n\\end{equation}\nwhich shows that \\eqref{eq:105.42} is known up to canonical\nisomorphism when we know its restriction to the full subcategory\n$A\\times B=A\\times A\\op$, identifying as usual an object $a$ of $A$ to\nits image in \\Ahat, and similarly for $B$. If $b$ is an object of $A$,\nwe'll denote by $b\\op$ the same object viewed as an object of\n$A\\op=B$. With these conventions (including \\eqref{eq:105.43}) we get\nthe nice formula\n\\begin{equation}\n  \\label{eq:105.45}\n  a * b\\op = \\Hom_A(b,a) \\quad(\\; = \\Hom_B(a\\op,b\\op)), \\quad\n  \\text{for $a,b$ in $A$,}\\tag{45}\n\\end{equation}\nwhich has the required symmetry property -- which, for general objects\n$F$ in \\Ahat{} and $G$ in \\Bhat, can be stated as a bifunctorial\nisomorphism\n\\begin{equation}\n  \\label{eq:105.46}\n  F * G \\simeq G * F,\\tag{46}\n\\end{equation}\nwhere the operation $*$ in the first member refers to the pair $(A,B)$,\nand in the second to the pair $(B,A)$.\n\nFrom \\eqref{eq:105.45} we easily deduce the more general formula for\n$F*G$, when either $F$ or $G$ is in $A$ resp.\\ $B$, namely\\pspage{398}\n\\begin{equation}\n  \\label{eq:105.47}\n  a * G \\simeq G(a), \\quad F * b\\op \\simeq F(b).\\tag{47}\n\\end{equation}\n\\begin{remarks}\n  We are mainly interested here in abelianization and (commutative)\n  homology and cohomology, and hence in sheaves and cosheaves with\n  values in additive (even abelian) categories, we are not going to\n  use for the time being the relationship between \\Ahat{} and \\Bhat{}\n  just touched upon. We could elaborate a great deal more on it, for\n  instance introducing a canonical pairing (more accurately, a\n  bi-sheaf) with opposite variance to \\eqref{eq:105.42}\n  \\begin{equation}\n    \\label{eq:105.48}\n    \\Ahat\\op\\times\\Bhat\\op\\to\\Sets\\tag{48}\n  \\end{equation}\n  (or what amounts to the same, canonical functors adjoint to each\n  other\n  \\[\\Ahat\\op\\to\\Bhat,\\quad\\Bhat\\op\\to\\Ahat\\quad),\\]\n  deduced (via the equivalence dual to \\eqref{eq:105.44}\n  \\[\\bHom^{!!}(\\Ahat\\op,\\Bhat\\op;\\scrN) \\toequ \\bHom(A\\op\\times\n  B\\op,\\scrN)\\quad)\\]\n  from the co-pairing\n  \\[A\\op\\times B\\op=B\\times A\\to\\Sets\\]\n  given by\n  \\[(b\\op,a)\\mapsto\\Hom(b,a)\\quad(\\text{for $a,b$ in $A$}).\\]\n  The two pairings \\eqref{eq:105.42} and \\eqref{eq:105.48} can be\n  given a common interpretation as $\\Hom$-sets in a suitable category\n  \\[\\scrE=\\scrE(A),\\]\n  which is the union of the two full subcategories \\Ahat{} and\n  $\\Bhat\\op$ (which may be interpreted as deduced from $A$ by\n  adjoining respectively small direct and small inverse limits to it)\n  intersecting in the common subcategory $A$, the $\\Hom$-sets in the\n  two directions between an object $F$ of \\Ahat{} and an object $G\\op$\n  of $\\Bhat\\op$ (corresponding to an object $G$ of \\Bhat) being given\n  respectively by the pairings \\eqref{eq:105.48} and\n  \\eqref{eq:105.42}.\\footnote{\\scrcommentinline{unreadable footnote}}\n  The full relationship between these pairings is most conveniently\n  expressed, it seems, by the composition law of maps in $\\scrE(A)$,\n  and associativity for this law. The symmetry of the situation with\n  respect to the pair $(A,B)$ is expressed by the canonical\n  isomorphism of categories\n  \\[\\scrE(A)\\op\\simeq\\scrE(B)\\quad (\\text{where $B=A\\op$}).\\]\n\\end{remarks}\n\n\\textbf{Case \\namedlabel{case:105.2}{2\\textsuperscript{\\b o})}.}%\n\\enspace Of direct relevance for the abelianization story\nis the particular case of the equivalence \\eqref{eq:105.39}, obtained\nby taking\n\\[\\scrM=\\Ab.\\]\nUsing formula \\eqref{eq:104.12} (page \\ref{p:387}) for the pair\n$(\\Ahat,\\Ab)$ and formula \\eqref{eq:104.14} for \\Bhat{} in guise of\n\\scrA, we get the canonical equivalence\\pspage{399}\n\\begin{equation}\n  \\label{eq:105.49}\n  \\Bhatab \\toequ \\bHom_!(\\Ahatab,\\Ab),\\tag{49}\n\\end{equation}\nwhich should be viewed as the ``abelian'' analogon of the equivalence\n\\eqref{eq:105.41} above (corresponding to the case\n$\\scrM=\\Sets$). This equivalence again may be viewed as described (in\nanalogy to \\eqref{eq:105.45}) by a canonical pairing\n\\begin{equation}\n  \\label{eq:105.50}\n  \\Ahatab\\times\\Bhatab\\to\\Ab,\\tag{50}\n\\end{equation}\nwhich commutes to small direct limits in each variable, i.e., can be\nviewed as an object in the category of ``abelian bi-cosheaves''\n\\begin{equation}\n  \\label{eq:105.star}\n  \\bHom_{!!}(\\Ahatab,\\Bhatab;\\Ab),\\tag{*}\n\\end{equation}\nand gives rise simultaneously to the equivalence \\eqref{eq:105.49},\nand to the symmetric equivalence\n\\begin{equation}\n  \\label{eq:105.49prime}\n  \\Ahatab\\toequ\\bHom_!(\\Bhatab,\\Ab)\\tag{49'}\n\\end{equation}\nof the category of abelian sheaves on \\Ahat{} with the category of\nabelian cosheaves on \\Bhat{} (which is just \\eqref{eq:105.49} with $A$\nreplaced by $B$, up to canonical isomorphism at any rate).\n\nUsing the equivalence\n\\begin{equation}\n  \\label{eq:105.51}\n  \\bHom_{!!}(\\Ahatab,\\Bhatab;\\Ab) \\toequ \\bHom(A\\times B,\\Ab)\\tag{51}\n\\end{equation}\n(which is a particular case of the evident abelian analogon of the\nequivalence \\eqref{eq:105.44}), we see that the pairing\n\\eqref{eq:105.50} is described, up to canonical isomorphism, by its\ncomposition with\n\\[(a,b)\\mapsto (\\Wh_\\Ahat(a),\\Wh_\\Bhat(b)): A\\times B\\to\n\\Ahatab\\times\\Bhatab,\\]\nand the latter, as is readily checked, is given by\n\\begin{equation}\n  \\label{eq:105.52}\n  \\Wh_A(a) *_{\\bZ} \\Wh_B(b\\op) \\simeq \\bZ^{(\\Hom(b,a))} \\quad\\text{for\n    $a,b$ in $A$,}\\tag{52}\n\\end{equation}\nwhere we have written $\\Wh_A$ instead of $\\Wh_\\Ahat$ for brevity and\naccordingly for $B$, and where the pairing \\eqref{eq:105.50} is\ndenoted by the symbol $*_{\\bZ}$, in analogy with the notation $*$ in\n\\eqref{eq:105.43}, the index $\\bZ$ being added in order to avoid\nconfusion with the non-abelian case \\eqref{eq:105.43} (and the index\nbeing dropped when no such confusion is to be feared). The formula\n\\eqref{eq:105.52} can be written, with different notations\n\\begin{equation}\n  \\label{eq:105.52prime}\n  \\bZ^{(a)} *_{\\bZ} \\bZ^{(b\\op)} \\simeq \\bZ^{(\\Hom(b,a))}\n  \\quad\\text{for $a,b$ in $A$.}\\tag{52'}\n\\end{equation}\nComparing with the similar formula \\eqref{eq:105.45}, this suggests\nthe generalization\n\\begin{equation}\n  \\label{eq:105.53}\n  \\Wh_A(F) *_{\\bZ} \\Wh_B(G) \\simeq \\bZ^{(F*G)},\\tag{53}\n\\end{equation}\nor with the exponential notation\n\\begin{equation}\n  \\label{eq:105.53prime}\n  \\bZ^{(F)} *_{\\bZ} \\bZ^{(G)} \\simeq \\bZ^{(F*G)},\\tag{53'}\n\\end{equation}\nvalid\\pspage{400} for $F$ in \\Ahat{} and $G$ in \\Bhat. As both members\nof \\eqref{eq:105.53} commute with small direct limits in each\nvariable, the formula \\eqref{eq:105.53} follows from the particular\ncase \\eqref{eq:105.52}, in view of the equivalence of categories\n\\eqref{eq:105.51}.\n\n\\medbreak\n\n\\noindent\\textbf{Remarks.}\\enspace\\namedlabel{rem:105.1}{1})%\n\\enspace In order to appreciate the significance of the pairing\n\\eqref{eq:105.50}, we may forget altogether about the non-additive\ncategories \\Ahat{} and \\Bhat, and view \\eqref{eq:105.50} as a\nremarkable ``duality'' relationship between two additive\n\\scrU-categories, stable under small direct limits, say \\scrP{} and\n\\scrQ, endowed with a ``pairing''\n\\[\\scrP\\times\\scrQ\\to\\Ab\\quad\\text{in\n  $\\bHom_{!!}(\\scrP,\\scrQ;\\Ab)$,}\\]\ngiving rise to two functors which are \\emph{equivalences}\n\\[ \\scrQ\\toequ \\bHom_!(\\scrP,\\Ab),\\quad \\scrP\\toequ\n\\bHom_!(\\scrQ,\\Ab),\\]\nidentifying each of \\scrP, \\scrQ{} to the category of ``abelian\ncosheaves'' on the other. In the particular case \\eqref{eq:105.50},\n$\\scrP=\\Ahatab$ and $\\scrQ=\\Bhatab$ with $B=A\\op$, each of these\ncategories is even an ``abelian topos'' by which I mean an abelian\ncategory \\scrP{} stable under small filtering direct limits, with the\nlatter being \\emph{exact}, and moreover \\scrP{} admitting a small\ngenerating subcategory. (These categories are sometimes called,\nsomewhat misleadingly, ``Grothendieck categories''. Of course, an\n``abelian topos'' is by no means a category which is a topos, besides\nbeing abelian!) There are many other examples of dual pairs of abelian\ntopoi. One evident generalization is by taking\n\\[\\scrP=A_k\\uphat,\\quad\\scrQ=B_k\\uphat,\\quad\\text{where again\n  $B=A\\op$,}\\]\nwhere $k$ is any commutative ring, and $A_k\\uphat\\eqdef A_\\kMod\\uphat$\nis the category of presheaves of $k$-modules on $A$, or equivalently,\nof objects in \\Ahat{} endowed with a structure of a $k$-module -- and\naccordingly for the notation $B_k\\uphat$. Indeed, the generalities\n\\ref{subsec:104.B} and \\ref{subsec:104.C} in yesterday's notes about\nabelian sheaves and cosheaves, as well as today's, could be developed\nreplacing throughout abelian group objects and additive categories by\n$k$-module objects and $k$-linear categories. In case $k$ is not\nsupposed commutative, one still should get a duality pairing\n\\[A_{k\\op}\\uphat\\times B_k\\uphat\\to\\Ab,\\]\nwhere $k\\op$ denotes the ring opposite to $k$ (i.e., a duality pairing\nbetween presheaves on $A$ of right $k$-modules, and copresheaves on\n$A$ of left $k$-modules), given in terms of $*_{\\bZ}$ in\n\\eqref{eq:105.50} by the formula\\pspage{401}\n\\[M *_{k} N = (M*_{\\bZ} N)^\\natural,\\]\nwhere in the right-hand side $P=M*_{\\bZ}N$ is viewed as a\nbi-$k$-module via the right and left $k$-module structures on $M$ and\n$N$ respectively and bifunctoriality of $*_{\\bZ}$, and where for any\nbimodule $P$, we write\n\\[P^\\natural \\eqdef P /\n\\parbox[t]{0.65\\textwidth}{sub-$\\bZ$-module generated by elements of\n  the type $s.x-x.s$ for $x$ in $P$ and $s$ in\n  $k$.}\\]\nI confess I didn't do the checking that this does give rise indeed to\na duality pairing as desired. When $A=B=$ final category, then the\npairing above is just the pairing given by usual tensor product\n\\[(M,N)\\mapsto M\\otimes_k N\\]\nbetween right and left $k$-modules, which is immediately checked to be\ndualizing indeed. More generally, posing\n\\[\\scrP=(k\\op\\textup{-Mod}),\\quad Q=\\kMod,\\]\nit is immediately checked that for any additive category \\scrM{}\nstable under small direct limits, we get a canonical\nequivalence\\scrcomment{Clearly, the ``d'' in $k\\subd$ is for\n  ``dexter'' (on the right), and the ``s'' below is for ``sinister''\n  (on the left).}\n\\[\\bHom_!(\\scrP,\\scrM) \\toequ (k\\textup{-}\\scrM), \\quad\nF\\mapsto F(k\\subd),\\]\nwhere $(k\\textup{-}\\scrM)$ denotes the category of objects $L$ of\n\\scrM{} endowed with a structure of a ``left $k$-module in \\scrM'',\ni.e., a ring homomorphism $k\\to\\End_\\scrM(L)$, $k\\subd$ denotes $k$\nviewed as a right $k$-module, and $F(k\\subd)$ is viewed as an object\nof $(k\\textup{-}\\scrM)$ via the operations of $k$ on it coming from\nleft multiplication of $k$ upon $k\\subd$. A quasi-inverse equivalence\nis obtained by associating to an object $L$ in $(k\\textup{-}\\scrM)$\nthe functor\n\\[M\\mapsto M\\otimes_k L: (k\\op\\textup{-Mod})\\to\\scrM.\\]\nDually, we get an equivalence (if \\scrN{} stable under small inv.\\\nlimits)\n\\[\\bHom^!(\\scrQ,\\scrN) \\toequ (k\\textup{-}\\scrN), \\quad\nF\\mapsto F(k\\subs),\\]\nwhere $k\\subs$ denotes $k$ viewed as a left $k$-module, so that the\n\\emph{contravariant} functor $F$ transforms the endomorphisms of\n$k\\subs$ (obtained by \\emph{right} operation of $k$ on $k\\subs$ via\nright multiplication) into a \\emph{left} operation of $k$ on\n$F(k\\subs)$; the quasi-inverse is given by the familiar $\\Hom_k$\noperation, it associates to the left $k$-module $L$ in \\scrM{} the\nfunctor\n\\[M\\mapsto \\Hom_k(M,L): \\kMod\\to\\scrN.\\]\n\nComparing the two pairs of equivalences, we get the\nequivalence\\pspage{402}\n\\begin{equation}\n  \\label{eq:105.starbis}\n  \\bHom_!(scrP,\\scrM) \\equeq \\bHom^!(\\scrQ\\op,\\scrM),\\tag{*}\n\\end{equation}\nvalid when \\scrM{} is stable under both (small) direct and inverse\nlimits, and which should be viewed as an abelian analogon of the\nequivalence \\eqref{eq:105.39}.\n\n\\namedlabel{rem:105.2}{2})%\n\\enspace It is well-known that an abelian topos \\scrP{} is\nequivalent to a category \\kMod, for a suitable ring $k$ (not\nnecessarily commutative) if{f} it admits an object $L$ which is\n\\namedlabel{it:105.rem2.a}{a)}\\enspace generating, and\n\\namedlabel{it:105.rem2.b}{b)}\\enspace ``\\emph{ultraprojective}'',\ni.e., the functor $X\\mapsto\\Hom(L,X)$ commutes to small direct\nlimits. The condition \\ref{it:105.rem2.b} (for an object of an\n\\emph{abelian} category stable under small direct limits or\nequivalently, under small direct sums) is equivalent with $L$ being:\n\\namedlabel{it:105.rem2.b1}{b\\textsubscript{1})}\\enspace projective,\nand \\namedlabel{it:105.rem2.b2}{b\\textsubscript{2})}\\enspace of\n``\\emph{finite presentation}'', i.e., the functor $X\\mapsto\\Hom(L,X)$\ncommutes with small filtering direct limits. This observation suggests\none common feature of all the examples of abelian duality pairings\nconsidered so far, namely that the abelian topoi under consideration\nin the pairing \\emph{have a small set of ultraprojective\n  generators}. I don't know if a structure theory of such categories\n(which are the abelian analogons for topoi equivalent to topoi of the\nspecial type \\Ahat, with $A$ in \\Cat) has been worked out yet. I\ndidn't do it at any rate -- but the natural thing to expect is that\nthese abelian topoi \\scrP{} (which we may call ``\\emph{algebraic}''\nones, just as an ordinary topos equivalent to one of the type \\Ahat{}\nmay be called ``algebraic'', which equally means that the set of\nultraprojective objects in it is generating\\ldots) are exactly those\nequivalent to a category of the type\n\\[\\Homadd(P\\op,\\Ab),\\]\nwhere $P$ is any \\emph{small additive} category, and where $\\Homadd$\ndenotes the category of additive functors from one additive category\nto another. Instead of assuming $P$ small, we may as well take $P$\nmerely ``essentially small'', i.e., equivalent to a small category,\nwith the benefit that for a given \\scrP, there is a canonical choice\nof an additive category $P$ together with an equivalence\n\\[\\scrP\\toequ\\Homadd(P\\op,\\Ab),\\]\nnamely by taking\n\\[P =\n\\begin{tabular}[t]{@{}l@{}}\n  full subcategory of \\scrP{} made up with all\n  ultraprojective\\\\objects in \\scrP.\n\\end{tabular}\\]\nAs we saw earlier, in case $\\scrP=\\Ahatab$, $P$ is nothing but the\nabelian Karoubi envelope of the category $A$, namely the Karoubi\nenvelope of the additive category $\\Add(A)$ (cf.\\ sections\n\\ref{sec:93} and \\ref{sec:99}). Another choice for $P$ in this case\nwould be just $\\Add(A)$ itself, whose objects are more amenable to\ncomputations.\\pspage{403}\n\nAssociating to any small \\scrcommentinline{additive} category $P$ the\nalgebraic abelian topos $\\bHomadd(P\\op,\\Ab)$ should be viewed of\ncourse as the abelian analogon of $A\\mapsto\\Ahat$, associating to a\nsmall category $A$ the corresponding algebraic topos. It merits a\nnotation of its own, say\n\\[P\\supamp\\eqdef \\bHomadd(P\\op,\\Ab),\\]\nand as in the non-additive case, we get a canonical inclusion functor\n\\[\\varepsilon_P:P\\to P\\supamp\\]\nwhich is additive. (Its composition with the canonical functor\n$P\\supamp\\to P\\uphat$ is the canonical inclusion\npreviously denoted by $\\varepsilon_P$ too from $P$ to $P\\uphat$.) Next\nthing we'll expect, in analogy to prop.\\ \\ref{prop:105.3}, is that for\nany additive category \\scrM{} stable under small direct limits, the\nfollowing canonical functor is an equivalence of categories:\n\\begin{equation}\n  \\label{eq:105.starstar}\n  \\bHom_!(P\\supamp,\\scrM) \\toequ \\bHomadd(P,\\scrM), \\quad\n  F\\mapsto F\\circ\\varepsilon_P.\\tag{**}\n\\end{equation}\nThe proof, via construction of a quasi-inverse functor, should be\nabout the same as for prop.\\ \\ref{prop:105.3}, which should go through\nonce we get the abelian analogon of the well-known fact in \\Ahat, that\nany object $F$ in \\Ahat{} can be recovered as a direct limit in\n\\Ahat{} of objects of $A$, according to $A_{/F}$ as an indexing\ncategory -- which makes us expect that we get too:\n\\[F \\fromsim \\varinjlim_{\\text{$a$ in $P\\supamp_{/F}$}} a\\quad\n(\\text{direct limit in $P\\supamp$}).\\]\nFrom \\eqref{eq:105.starstar} we get as in cor.\\ \\ref{cor:105.prop3.1},\npassing to the dual categories, the dual equivalence\n\\[\\bHom^!({P\\supamp}\\op,\\scrN) \\toequ \\bHomadd(P\\op,\\scrN),\\]\nvalid if \\scrN{} is an additive category stable under small inverse\nlimits. Hence, if \\scrM{} is additive and stable under both types of\nlimits, the equivalence\n\\begin{equation}\n  \\label{eq:105.starstarstar}\n  \\bHom_!(P\\supamp,\\scrM)\\toequ \\bHom^!({Q\\supamp}\\op,\\scrM), \\quad\n  \\text{with $Q=P\\op$,}\\tag{***}\n\\end{equation}\nbetween abelian cosheaves on $P\\supamp$ and abelian sheaves in\n$Q\\supamp$, with values in the same additive category (in analogy to\n\\eqref{eq:105.39}). In the particular case $\\scrM=\\Ab$, this then\ngives rise to the equivalence\n\\[Q\\supamp \\equeq \\bHom_!(P\\supamp,\\Ab)\\]\nand to the corresponding pairing\n\\[P\\supamp\\times Q\\supamp\\to\\Ab\\]\nwhich is a duality, namely induces an equivalence between each abelian\ntopos\\pspage{404} $P\\supamp$, $Q\\supamp$ and the category of abelian\ncosheaves on the other.\n\nWe may call an abelian topos ``\\emph{reflexive}'' if it can be\ninserted in a pair $(\\scrP,\\scrQ)$ of dually paired abelian topoi --\nwhere \\scrQ, or the ``dual'' of \\scrP, is defined up to equivalence in\nterms of \\scrP{} as $\\bHom_!(\\scrP,\\Ab)$, the category of cosheaves on\n\\scrP{} with values in \\Ab. Thus, it seems that a sufficient condition\nfor reflexivity is ``algebraicity'' of \\scrP, namely the existence of\na small generating family made up with ultraprojective\nobjects. (NB\\enspace In the non-abelian case, it is well-known that a\ntopos \\scrA{} is ``algebraic'', i.e., equivalent to a topos \\Ahat,\nif{f} it admits such a generating family -- and as we saw in\n\\ref{case:105.1}, as a consequence of \\eqref{eq:105.39} for\n$\\scrM=\\Sets$, such a topos is indeed ``reflexive''.) I wouldn't be\ntoo surprised if this sufficient condition for reflexivity turned out\nto be necessary too, at any rate if we want a property stronger still\nthan reflexivity, namely validity of a duality equivalence\n\\eqref{eq:105.starstarstar} for sheaves and cosheaves with values in\nan arbitrary additive \\scrU-category stable under small direct and\ninverse limits, satisfying (for varying \\scrM) suitable compatibility\nassumptions.\n\n\\namedlabel{rem:105.3}{3})%\n\\enspace With respect to this duality equivalence\n\\eqref{eq:105.starstarstar}, I am a little unhappy still, as I do not\nsee how to get (for a general dual pair \\scrP, \\scrQ{} of abelian\ntopoi) a functor i one direction or the other between the two\ncategories\n\\[\\bHom_!(\\scrP,\\scrM),\\quad\\bHom^!(\\scrQ\\op,\\scrM),\\]\nin terms of just the duality pairing. The same perplexity holds in the\nnon-abelian case. This is one of the reasons that make me feel that I\nhaven't yet a thorough understanding of the duality formalism I am\ndeveloping here, except in the ``algebraic'' case (granting for the\nlatter that the tentative theory just outlined for algebraic\n\\emph{abelian} topoi is indeed correct).\n\n\\namedlabel{rem:105.4}{4})%\n\\enspace To finish with the comments on the (pre-homological)\nduality formalism for algebraic topoi and algebraic abelian topoi, I\nstill would like to add that the category $\\scrE(A)$ (union of \\Ahat{}\nand $\\Bhat\\op$, with $B=A\\op$) introduced in \\ref{case:105.1} (cf.\\\nremark on page \\ref{p:398}) admits also an abelian analogon. In the\nnon-abelian case still, the simplest way to construct the category\n$\\scrE(A)$, is via an equivalent category canonically embedded in the\ncategory $\\bHom(\\Bhat,\\Sets)$ as a strictly full subcategory\n(``strict'' referring to the fact that with any object it contains all\nisomorphic ones), namely the union $\\overline{\\scrE}(A)$ of the\n(strictly full) subcategories\\pspage{405} $\\bHom_!(\\Bhat,\\Sets)$\n(equivalent to \\Ahat) and the subcategory of representable functors\n(equivalent to $\\Bhat\\op$).\\scrcomment{There seems to be another\n  unreadable footnote here\\ldots} The intersection of these two categories\ncontains of course $A$ (embedded in $\\bHom(\\Bhat,\\Sets)$ by\nassociating to $a$ in $A$ the functor $G\\mapsto G(a)$ from\n$\\Bhat=\\bHom(A,\\Sets)$ to \\Sets), but in general need not be quite\nequivalent to $A$ -- it turns out to be the ``Karoubi envelope'' of\n$A$, obtained by adjoining to $A$ formally images (or equivalently,\ncoimages) of projectors in $A$. The more immediate interpretation of\nthis intersection, is that it is equivalent to the dual category of\nthe category of ultraprojective objects in \\Bhat{} (and the latter can\nbe viewed as $\\Kar(B)$, but formation of the Karoubi envelope up to\nequivalence commutes to taking dual categories\\ldots). All these\nconstructions immediately extend to the abelian set-up, starting with\na small \\emph{additive} category $P$, instead of $A$.\n\nAfter this endless procession of remarks, which are really digressions\nfor what we're after (namely abelianization and duality in the context\nof small categories as homotopy models), it is time to resume our main\nline of thought in this subsection, namely looking at interesting\nparticular cases for the general duality relation \\eqref{eq:105.39}.\n\n\\textbf{Case \\namedlabel{case:105.3}{3\\textsuperscript{\\b o})}.}%\n\\enspace This is the case when \\scrM{} is an \\emph{additive} category,\nstable under both types of small limits. If we assume moreover that\n\\scrM{} and $\\scrM\\op$ are both pseudotopoi, using the equivalences\n\\eqref{eq:104.12} and \\eqref{eq:104.13} (p.\\ \\ref{p:387}),\n\\eqref{eq:105.39} may be interpreted as an equivalence\n\\begin{equation}\n  \\label{eq:105.54}\n  \\bHom_!(\\Ahatab,\\scrM)\\equeq \\bHom^!(\\Bhatab,\\scrM),\\tag{54}\n\\end{equation}\ninterpreting \\scrM-valued cosheaves on the abelian topos \\Ahatab{} in\nterms of \\scrM-valued sheaves on the dual abelian topos \\Bhatab, as\nanticipated in a more general situation in the remark above (cf.\\\nformula \\eqref{eq:105.starstarstar} on page \\ref{p:403}). There,\nhowever, the assumption that \\scrM{} and/or $\\scrM\\op$ should be\npseudotopoi didn't seem to come in at all, so we expect this condition\nto be irrelevant indeed. This will of course follow, if the same holds\nfor \\eqref{eq:104.12} (hence by duality for \\eqref{eq:104.13}), namely\nthat the canonical functor\n\\begin{equation}\n  \\label{eq:105.55}\n  \\bHom_!(\\Ahatab,\\scrM)\\toequ\\bHom_!(\\Ahat,\\scrM), \\quad\n  F\\mapsto F\\circ\\Wh_A,\\tag{55}\n\\end{equation}\nis an equivalence, under the only assumption that the additive\ncategory \\scrM{} is stable under small direct limits (without assuming\nthat \\scrM{} be a pseudotopos). The line of thought of the remark\n\\ref{rem:105.2} above suggests a way for proving this, via an\nequivalence\\pspage{406}\n\\begin{equation}\n  \\label{eq:105.56}\n  \\bHom_!(\\Ahatab,\\scrM)\\toequ\\bHomadd(\\Add(A),\\scrM), \\quad\n  F\\mapsto F\\circ j_A,\\tag{56}\n\\end{equation}\nwhere\n\\[j_A: \\Add(A)\\to\\Ahatab\\]\nis the canonical inclusion functor (cf.\\ section \\ref{sec:97}). This,\nand the dual equivalence (deduced from \\eqref{eq:105.55}, taking\n$\\scrN=\\scrM\\op$)\n\\begin{equation}\n  \\label{eq:105.57}\n  \\bHom^!(\\Ahatab\\op,\\scrN)\n  \\toequ\\bHomadd(\\Add(A)\\op,\\scrN),\\tag{57}\n\\end{equation}\nvalid for any additive category stable under small inverse limits,\nwill immediately imply an equivalence \\eqref{eq:105.54} by a direct\nargument as in the remark above, without passing through the\nnon-abelian case \\eqref{eq:105.39}. At any rate, \\eqref{eq:105.56}\nimplies that \\eqref{eq:105.55} is an equivalence, as is seem by\nlooking at the commutative diagram\n\\begin{equation}\n  \\label{eq:105.58}\n  \\begin{tabular}{@{}c@{}}\n    \\begin{tikzcd}[baseline=(O.base),row sep=small,column sep=-1em]\n      & \\bHom_!(\\Ahat,\\scrM)\\ar[dr] & \\\\\n      \\bHom_!(\\Ahatab,\\scrM)\\ar[dr]\\ar[ur] & &\n      \\bHom(A,\\scrM) \\\\\n      & |[alias=O]| \\bHomadd(\\Add(A),\\scrM)\\ar[ur] &\n    \\end{tikzcd},\n  \\end{tabular}\\tag{58}\n\\end{equation}\nwhere the two right-hand arrows are equivalences, which implies that\none of the two left-hand arrows is an equivalence if{f} the other is.\n\nThus, for getting \\eqref{eq:105.54} and \\eqref{eq:105.55} without\nextraneous assumptions on \\scrM, we are left with proving\n\\eqref{eq:105.56}. Now, writing\n\\[\\scrP=\\Ahatab,\\quad P=\\Add(A),\\]\nwe do have indeed an equivalence\n\\[\\scrP\\equeq P\\supamp \\eqdef \\bHomadd(P\\op,\\Ab),\\]\nas seen from \\eqref{eq:105.57} taking $\\scrN=\\Ab$ (which satisfies the\nextra assumptions). So we may as well prove \\eqref{eq:105.56} in the\nmore general case when $P$ is any small additive category and \\scrP{}\nis defined as $P\\supamp$, namely prove the equivalence\n\\eqref{eq:105.starstar} of page \\ref{p:403} above, as I don't expect\nthe particular case at hand here to be any simpler. The suggestion for\na proof there there seems convincing, I guess I should check it works\nduring some in-between scratchwork\\ldots\n\n\\bigbreak\n\n\\presectionfill\\ondate{14.8.}\\pspage{407} and \\ondate{15.8}\\par\n\n% 106\n\\hangsection[Review (3): A formulaire for the basic integration and\n\\dots]{Review \\texorpdfstring{\\textup{(3)}}{(3)}: A formulaire for the\n  basic integration and cointegration operations \\texorpdfstring{$*$\n    and $\\Hom$}{* and Hom}.}\\label{sec:106}%\n\\phantomsection\\addcontentsline{toc}{subsection}{\\numberline {E)}A\n  formulaire around the basic operations \\texorpdfstring{$*$ and\n    $\\Hom$}{* and Hom}.}%\n\\textbf{\\namedlabel{subsec:106.E}{E)}\\enspace A formulaire around the\n  basic operations $*$ and $\\Hom$.}\\enspace I would like to dwell a\nlittle more still on the duality formalism weaving around formula\n\\eqref{eq:105.39} (p.\\ \\ref{p:395}), stating that for two given small\ncategories $A$ and $B$ dual to each other\n\\[B=A\\op, \\quad A=B\\op,\\]\nand any \\scrU-category \\scrM{} stable under both types of small\nlimits, \\scrM-valued \\emph{cosheaves} on \\Ahat{} may be interpreted as\n\\scrM-valued \\emph{sheaves} on the dual topos \\Bhat. This\nidentification preserves variance (i.e., \\eqref{eq:105.39} is an\n\\emph{equivalence} of categories, not an antiequivalence:\n\\begin{equation}\n  \\label{eq:106.59}\n  (\\Ahat)^\\scrM = \\bHom_!(\\Ahat,\\scrM) \\toequ\n  \\bHom^!((\\Bhat)\\op,\\scrM) = \\BhatM\\quad\\text{).}\\tag{59}\n\\end{equation}\nIt should not be confused with the tautological interpretation of\n\\scrM-valued cosheaves on \\Ahat{} as $\\scrM\\op$-valued sheaves on the\n\\emph{same} topos, an identification \\emph{reversing variance}, as\nexpressed by the canonical antiequivalence between the corresponding\ncategories -- an anti-isomorphism even (reflecting its tautological\nnature):\n\\begin{equation}\n  \\label{eq:106.60}\n  \\bHom_!(\\Ahat,\\scrM)\\op \\tosim \\bHom^!((\\Ahat)\\op,\\scrM\\op),\n  \\text{ i.e., }((\\Ahat)^\\scrM)\\op \\tosim \\AhatM.\\tag{60}\n\\end{equation}\nIn the latter formula, the basic topos \\Ahat{} remains the same in\nboth sides, it is the category of values that changes from \\scrM{} to\nthe dual one $\\scrM\\op$, whereas in formula \\eqref{eq:106.59} =\n\\eqref{eq:105.39}, it is the opposite. In terms of the tautological\nformula \\eqref{eq:106.60} (a particular case of formula\n\\eqref{eq:104.6} p.\\ \\ref{p:385}), the not-so-tautological formula\nrelating cosheaves and sheaves can be reformulated as a formula in\nterms of sheaves only (due to our preference for sheaves rather than\ncosheaves\\ldots):\n\\begin{equation}\n  \\label{eq:106.61}\n  \\bHom^!(\\Ahat,\\scrM)\\op \\equeq \\bHom^!(\\Bhat,\\scrM\\op),\\quad\n  \\text{i.e.,}\\quad (\\AhatM)\\op \\equeq B\\uphat_{\\scrM\\op},\\tag{61} \n\\end{equation}\nnamely \\scrM-valued sheaves on the topos \\Ahat{} can be interpreted as\nsheaves on the dual topos with values in the dual category $\\scrM\\op$,\nthis interpretation \\emph{reversing variances}. In the homology and\ncohomology formalism which is to follow, due to habits of long\nstanding, I prefer systematically to take as coefficients\n\\emph{sheaves} rather than cosheaves -- hence rule out cosheaves in\nfavor of sheaves via \\eqref{eq:106.60}. From this point of view the\nrelevant basic duality statement is \\eqref{eq:106.61} rather than\n\\eqref{eq:106.59}.\n\nOn the \\emph{cosheaves} side, yesterday's diagram \\eqref{eq:105.58} of\nequivalences gives a fourfold description of cosheaves on the topos\n\\Ahat{} with values in an \\emph{abelian} category \\scrM{} stable under\nsmall direct limits. We could still enlarge this diagram, by including\nin it a fifth category equivalent\\pspage{408} to the four others,\nnamely\n\\[\\bHomaddinf(\\Addinf(A),\\scrM),\\]\nthe category of infinitely additive functors from the infinitely\nadditive envelope of $A$ into $M$ (cf.\\ section \\ref{sec:99} p.\\\n\\ref{p:366} for description of the category $\\Addinf(A)$). Rather than\nwriting down the larger diagram here, I'll write down the dual\nenlarged one, for the dual topos \\Bhat{} and for various expressions\nof the category of \\emph{sheaves} on this topos, with values in a\ncategory \\scrM{} stable this time under small inverse limits:\n\\begin{equation}\n  \\label{eq:106.62}\n  \\begin{tabular}{@{}c@{}}\n    % again somewhat fragile\n    \\begin{tikzpicture}[commutative diagrams/every diagram,baseline=(E.base)]\n      \\node (A) at (0,1.2cm) {$\\bHom^!((\\Bhat)\\op,\\scrM)$};\n      \\node (B) at (-3.2cm,0) {$\\bHom^!((\\Bhatab)\\op,\\scrM)$};\n      \\node (C) at (2.2cm,0) {$\\bHom(B\\op,\\scrM)$};\n      \\node (D) at (-3.2cm,-1.2cm) {$\\bHommultinf(\\Addinf(B)\\op,\\scrM)$};\n      \\node (E) at (1.5cm,-1.2cm) {$\\bHomadd(\\Add(B)\\op,\\scrM)$};\n\n      \\path[commutative diagrams/.cd, every arrow, every label]\n      (A) edge node {$\\equ$} (C)\n      (B) edge node {$\\equ$} (A)\n      (B) edge node[swap] {$\\equ$} (D)\n      (D) edge node {$\\equ$} (E)\n      (E) edge node {$\\equ$} (C);\n    \\end{tikzpicture},\n  \\end{tabular}\\tag{62}\n\\end{equation}\nwhere $\\bHommultinf$ denotes the category of ``infinitely\nmultiplicative'' functors from one additive category stable under\ninfinite products to another. Recalling for the extreme right term of\n\\eqref{eq:106.62} that $B\\op=A$, we see that this term is\n\\emph{identical} to the corresponding term in the diagram (even the\nenlarged one) \\eqref{eq:105.58} -- hence, if \\scrM{} is stable under\nboth types of limits, the ten categories occurring altogether in the\ntwo diagrams are mutually equivalent (as a matter of fact, there are\nnine only which are mutually different). It may be noted that there is\nstill another pair of corresponding terms in the two diagrams for\nwhich the equivalence between them may be viewed as tautological,\nnamely\n\\[\\bHomadd(\\Add(A),\\scrM) \\equeq \\bHomadd(\\Add(B)\\op,\\scrM),\\]\ndue to the tautological equivalence of categories\n\\[\\Add(B)\\op \\equeq \\Add(B\\op) = \\Add(A).\\]\n\nAs emphasized in yesterday's notes, the canonical pairing (deduced\nfrom \\eqref{eq:106.59} by taking $\\scrM=\\Ab$)\n\\begin{equation}\n  \\label{eq:106.63}\n  \\Ahatab\\times\\Bhatab\\to\\Ab,\\quad\n  (F,G)\\mapsto F*_{\\bZ} G,\\tag{63}\n\\end{equation}\ndeserves special attention, giving rise to an equivalence between each\nof the mutually dual abelian topoi \\Ahatab, \\Bhatab{} with the\ncategory of abelian cosheaves on the other\n\\begin{equation}\n  \\label{eq:106.64}\n  \\Bhatab \\toequ \\bHom_!(\\Ahatab,\\Ab), \\quad\n  \\Ahatab \\toequ \\bHom_!(\\Bhatab,\\Ab)\\tag{64}\n\\end{equation}\n(cf.\\ \\eqref{eq:105.49} and \\eqref{eq:105.49prime} page\n\\ref{p:399}). It should be kept in mind that besides this duality\npairing between two abelian topoi, there is important\nextra\\pspage{409} structure in this abelianized duality context,\nembodied by the \\emph{tensor product structure} on both abelian topoi\n\\Ahatab{} and \\Bhatab, as contemplated in section \\ref{sec:104}\n\\ref{subsec:104.C}, in a somewhat more general context. Corresponding\nto this extra structure on \\Ahatab{} say, we saw that this category of\nabelian sheaves ``operates'' covariantly (by an operation denoted by\n$\\oast_{\\bZ}$ or simply $\\oast$) on any category of \\scrM-valued\ncosheaves on \\Ahatab, and contravariantly (by an operation denoted by\n$\\bHom_{\\bZ}$ or simply $\\bHom$, if no confusion may arise) on any\ncategory of \\scrN-valued sheaves on \\Ahatab, where \\scrM, \\scrN{} are\nadditive categories, stable under small direct resp.\\ inverse\nlimits. The latter operation (cf.\\ page \\ref{p:392})\n\\begin{equation}\n  \\label{eq:106.65}\n  (L,K) \\mapsto \\bHom_{\\bZ}(L,K) : (\\Ahatab)\\op \\times \\AhatN \\to\n  \\AhatN,\\tag{65}\n\\end{equation}\ninvolving sheaves, will be used in the sequel ``tel\nquel'',\\scrcomment{``tel quel'' = ``as is''} its\ndefinition is of a tautological character, independent of duality. As\nfor the former operation involving cosheaves, we may view it via the\nduality relation \\eqref{eq:106.59} as an operation of \\Ahatab{} on\n\\scrM-valued \\emph{sheaves} on the dual abelian topos \\Bhatab, and\nthis operation will be denoted by the same symbol $\\oast_{\\bZ}$:\n\\begin{equation}\n  \\label{eq:106.66}\n  (L,M') \\mapsto L\\oast_{\\bZ} M' : \\Ahatab \\times \\BhatM\n  \\to \\BhatM.\\tag{66} \n\\end{equation}\nReplacing $A$ by $B$ in \\eqref{eq:106.66}, we get an operation of\n\\Bhatab{} upon \\AhatM,\n\\begin{equation}\n  \\label{eq:106.67}\n  (M,L') \\mapsto M \\oast_{\\bZ} L' :\n  \\AhatM\\times\\Bhatab\\to\\AhatM.\\tag{67}\n\\end{equation}\nWhenever convenient, we'll allow ourselves to write $L'\\oast M$\ninstead of $M\\oast L'$ (which doesn't seem to lead to any trouble),\nand will henceforth (unless special need should arise) drop the\nsubscripts $\\bZ$.\n\nThus, for a given category $\\AhatM$ of \\scrM-valued sheaves on\n\\Ahatab, there is a twofold operation on this category, namely\n\\Ahatab{} itself operates (the operation defined by $L$ in \\Ahatab{}\ndepending contravariantly on $L$) as well as the dual abelian topos\n\\Bhatab{} (the operation defined by $L'$ in \\Bhatab{} depending\ncovariantly on $L'$), \\scrM{} being any additive category stable under\nsmall inverse and direct limits (in order to ensure existence of both\ntypes of operations). I would like to dwell a little more on this\ntwofold structure, as I don't feel to have understood it thoroughly\nyet. It is this second operation mainly which hasn't become really\nfamiliar yet, still less its relationship to the first, more\nfamiliar\\pspage{410} operation is understood. I'll have to play around\na little more with it for being really at ease. It's worth the while,\nas the $\\bHom$ and corresponding $\\Hom$ operation is the key operation\nfor expressing cohomology of \\Ahat{} (with coefficients in $K$), where the\n$\\oast$ and corresponding $*$ operation is the key for expressing\nhomology of \\Ahat{} (with coefficients in $M$, where $K$ and $M$ are\nthe sheaves occurring in \\eqref{eq:106.65} and \\eqref{eq:106.67}\nrespectively).\n\nA typical special case is the one when $A$ is the final category,\nhence $B=A$ and $\\AhatM\\simeq \\scrM$, in which case\n\\eqref{eq:106.65} and \\eqref{eq:106.67} are the two familiar exterior\noperations of \\Ab{} on any additive category stable under the two\ntypes of small limits\n\\[ (L,X)\\mapsto \\bHom_{\\bZ}(L,X): \\Ab\\op\\times\\scrM\\to\\scrM,\\]\nand\n\\[ (X,L)\\mapsto X\\otimes_{\\bZ} L:\\Ab\\times\\scrM\\to\\scrM,\\]\neach one of these two operations being deducible from the other by the\nusual device of replacing \\scrM{} by the dual category\n$\\scrM\\op$. When $\\scrM=\\Ab$, these are just the usual internal\n$\\Hom=\\bHom$ and tensor product operations. This very particular case\nshows at once that we shouldn't expect in general the operations\n$\\bHom_{\\bZ}(L,{-})$ of \\Ahatab{} and ${-} * L'$ of \\Bhatab{} upon\n\\AhatM{} to commute up to isomorphism -- we shouldn't expect, for a\ngiven $L$ in \\Ahatab{} or a given $L'$ in \\Bhatab{} the commutation\nrelation to hold, except when this object is ``projective of finite\npresentation'', i.e., is a direct factor of an object of $\\Add(A)$\nresp.\\ of $\\Add(B)\\equeq\\Add(A)\\op$. Another fact becoming evident by\nthis particular case, is that whereas it is true that in the\nequivalence \\eqref{eq:106.64}\n\\[\\Bhatab \\equeq \\bHom_!(\\Ahatab,\\Ab)\\]\na projective object $L'$ in \\Bhatab{} gives rise to a functor\n$\\Ahatab\\to\\Ab$ which is \\emph{exact} (besides commuting to small\ndirect limits) -- and even to a functor commuting to small inverse\nlimits if $L'$ is ultraprojective, i.e., projective and of finite\npresentation -- the converse to this (as contemplated on page\n\\ref{p:381}) does \\emph{not} hold true. Indeed, in the particular case\n$A=\\Simplex_0$, when $L'$ is just an object in \\Ab, the exactness\nproperty envisioned, i.e, exactness of the functor $M\\mapsto\nM\\otimes_{\\bZ} L'$ from \\Ab{} to itself, only means that $L'$ is a\n\\emph{flat} $\\bZ$-module (i.e., torsion-free), which does \\emph{not}\nimply that it is projective (i.e., free). \n\nThe\\pspage{411} feeling I had earlier today, that the familiar looking\noperation \\eqref{eq:106.65} $\\bHom(L,K)$ of abelian sheaves on \\Ahat{}\nupon \\scrM-valued ones (\\scrM{} an additive category stable under\nsmall inverse limits) was well-understood, whereas the less familiar\none $M*L'$ in \\eqref{eq:106.67} was not, turns out to be mistaken. In\ncomputational terms, and writing $F$ for $K$ in \\eqref{eq:106.65} and\n$M$ in \\eqref{eq:106.67}, the three basic data\n\\[\\text{$F$ in \\AhatM,} \\quad\n\\text{$L$ in \\Ahatab,} \\quad\n\\text{$L'$ in \\Bhatab}\\]\nshould surely be interpreted as just functor\n\\begin{equation}\n  \\label{eq:106.68}\n  F:A\\op\\to\\scrM, \\quad\n  L:A\\op\\to\\Ab,\\quad\n  L':B\\op=A\\to\\Ab,\\tag{68}\n\\end{equation}\nand the practical question of ``computing'' $\\bHom(L,F)$ or $F\\oast\nL'$ thus amounts to describing, directly in terms of these data, the\ncorresponding objects in \\AhatM{} as again a functor\n\\[\\bHom(L,F)\\quad\\text{or}\\quad F\\oast L':A\\op\\to\\scrM.\\]\nIt would seem that neither of the two can be expressed in simplistic\ncomputational terms, via the data \\eqref{eq:106.68}. I feel I have to\ncome to terms with this fact and get as close as I can to an explicit\nexpression of both. The point I want to make first, is that this\nquestion of expressing $\\bHom(L,F)$, or of expressing the operation\n$F\\oast L'$, is essentially the same, via replacement of \\scrM{} by\n$\\scrM\\op$, and mere interchange of $A$ and $B$. More accurately,\npassing from $F$ to the corresponding functor $F\\op$ between the dual\ncategories, we may view the data \\eqref{eq:106.68} as being functors\n\\begin{multline}\n  \\label{eq:106.68prime}\n  F\\op:B\\op\\to\\scrN,\\quad\n  L':B\\op\\to\\Ab,\\quad\n  L:A\\op\\to\\Ab\\\\\n  \\text{ (where $\\scrN=\\scrM\\op$),}\\tag{68'}\n\\end{multline}\ni.e., a set of data like \\eqref{eq:106.68}, with $(A,\\scrM)$ replaced\nby the dual pair $(B,\\scrN)$. This being understood, we have the\ntautological isomorphisms\n\\begin{equation}\n  \\label{eq:106.69}\n  \\begin{cases}\n    \\bHom(L,F)\\op \\simeq F\\op \\oast L & \\\\\n    (F\\oast L')\\op \\simeq \\bHom(L',F\\op) &\\text{,}\n  \\end{cases}\\tag{69}\n\\end{equation}\nwhere the first members involve operations relative to the pair\n$(A,\\scrM)$, the second members operations relative to the dual pair\n$(B,\\scrN)$. This makes very clear, it seems to me, that the\noperations $\\bHom$ \\eqref{eq:106.65} and $\\oast$ \\eqref{eq:106.67} may\nbe viewed as the same type of operation, simply viewed with two\ndifferent pairs of spectacles -- one being $(A,\\scrM)$, the other the\ndual pair $(B,\\scrN)$. Thus, if we got a good understanding of one of\nthe two operations, embodied by a comprehensive\nformulaire\\scrcomment{I'm leaving in ``formulaire'' (form), even\n  though ``formula'' seems to work better\\ldots} for it, by just\ndualizing we should get just as good a formulaire and corresponding\ncomprehension for the dual operation.\n\nNow, it is clear indeed that it is the operations\n\\eqref{eq:106.65}\\pspage{412} which is closer to my experience, it\nmakes sense however, independently of any duality statements, in the\nvastly more general context of topoi \\scrA{} (or even only pseudotopoi\nsatisfying some mild extra conditions, cf.\\ section \\ref{sec:104}\n\\ref{subsec:104.C}) instead of just \\Ahat, provided we make on \\scrM{}\nthe mild extra assumption of being a pseudotopos, needed in this more\ngeneral context in order to ensure equivalence between the category\n$\\scrA_\\scrM$ of \\scrM-valued sheaves, and the category\n$\\bHom^!({\\scrA\\subab}\\op,\\scrM)$ (compare \\eqref{eq:104.13} p.\\\n\\ref{p:388}). What I should do then is, first to write down a basic\n``formulaire'' for the $\\bHom$ operation in this general and familiar\ncontext, then see how it can be used for clarifying the computational\npuzzle raised on the previous page, in the case of the $\\bHom$\noperation, and finally dualize the formulaire and computational\ninsight, for getting a hold on the dual operation $\\oast$.\n\nWe'll need too the $\\Hom$ operation (non-bold-face) of\n\\eqref{eq:104.31} p.\\ \\ref{p:392}\n\\begin{equation}\n  \\label{eq:106.70}\n  (L,F)\\mapsto \\Hom(L,F) : {\\scrA\\subab}\\op \\times \\scrA_\\scrM \\to\n  \\scrM,\\tag{70} \n\\end{equation}\nwith values in \\scrM, not $\\scrA_\\scrM$, where $\\Hom(L,F)$ denotes the\nvalue on $L$ of the functor\n\\[\\widetilde F : {\\scrA\\subab}\\op\\to\\scrM\\]\ndefined by $F$, $F$ being viewed for the time being as an object in\n$\\bHom^!(\\scrA\\op,\\scrM)$:\n\\begin{equation}\n  \\label{eq:106.71}\n  F:\\scrA\\op\\to\\scrM.\\tag{71}\n\\end{equation}\n(In case $\\scrA=\\Ahat$, we get the description \\eqref{eq:106.68} of\n$F$ by taking the restriction of \\eqref{eq:106.71} to the subcategory\n$A$ of \\Ahat.)\n\nIn the following formulaire, $L$, $L'$ are objects in $\\scrA\\subab$,\n$F$ is an object in $\\scrA_\\scrM$, where \\scrM{} is an additive\ncategory stable under small inverse limits, which moreover is assumed\nto be a pseudotopos (i.e., admits a small set of objects generating\nwith respect to monomorphisms, and is stable under small direct\nlimits) in case the topos \\scrA{} is not equivalent to a category\n\\Ahat. We denote by\n\\[X\\mapsto\\bZ^{(X)}, \\quad \\scrA\\to\\scrA\\subab\\]\nthe abelianization functor, which in the case $\\scrA=\\Ahat$ is just\n``componentwise abelianization'', i.e.,\n\\[\\bZ^{(X)}(a)=\\bZ^{(X(a))}\\quad\\text{for $a$ in $A$.}\\]\nWe recall that the constant sheaf $\\bZ_\\scrA$ on \\scrA{} with value\n$\\bZ$ can be also described as\n\\begin{equation}\n  \\label{eq:106.72}\n  \\bZ_\\scrA=\\bZ^{(e)},\\tag{72}\n\\end{equation}\nwhere $e$ is the final object of \\scrA, and that the \\emph{sections}\nfunctor on \\scrA\\pspage{413} is defined as\n\\begin{equation}\n  \\label{eq:106.73}\n  \\Gamma_\\scrA(F) \\eqdef F(e);\\tag{73}\n\\end{equation}\nin case $\\scrA=\\Ahat$, this can equally be interpreted as the inverse\nlimit functor for the functor $A\\op\\to\\scrM$ defined by $F$:\n\\begin{equation}\n  \\label{eq:106.74}\n  \\Gamma_\\scrA(F) \\simeq \\varprojlim_{A\\op} F(a).\\tag{74}\n\\end{equation}\nWe are now ready to give a basic formulaire for the operations $\\bHom$\nand $\\Hom$, and their relations to the abelianization functor and to\nthe sections functor (i.e., to inverse limits, in case $\\scrA=\\Ahat$).\n\\begin{equation}\n  \\label{eq:106.75}\n  \\left\\{%\n    \\renewcommand*{\\arraystretch}{1.1}%\n    \\begin{array}{@{}r@{}rl@{}}\n      \\left\\{\\rule{0pt}{3ex}\\right. &\n      \\begin{tabular}{@{}r@{}}\n        \\textcircled{a} \\\\ \n        a')\n      \\end{tabular} &\n      \\begin{array}{@{}l@{}}\n        \\Hom(\\bZ^{(X)},F)\\simeq F(X) \\\\\n        \\bHom(\\bZ^{(X)},F)\\simeq (Y\\mapsto F(X\\times Y):\\scrA\\op\\to\\scrM)\n      \\end{array} \\\\\n      \\left\\{\\rule{0pt}{3ex}\\right. &\n      \\begin{tabular}{@{}r@{}}\n        \\textcircled{b} \\\\\n        b')\n      \\end{tabular} &\n      \\begin{array}{@{}l@{}}\n        \\Hom(L',\\bHom(L,F)) \\simeq \\Hom(L'\\otimes L,F) \\\\\n        \\bHom(L',\\bHom(L,F)) \\simeq \\bHom(L'\\otimes L,F)\n      \\end{array} \\\\\n      \\left\\{\\rule{0pt}{3ex}\\right. &\n      \\begin{tabular}{@{}r@{}}\n        c) \\\\\n        c')\n      \\end{tabular} &\n      \\begin{array}{@{}l@{}}\n        \\Hom(\\bZ_\\scrA,F)\\simeq\\Gamma_\\scrA(F) \\\\\n        \\bHom(\\bZ_\\scrA,F)\\simeq F\n      \\end{array} \\\\\n      & \\text{d)} & \\Hom(L,F)\\simeq\\Gamma_\\scrA\\bHom(L,F) \\\\\n      \\left\\{\\rule{0pt}{6ex}\\right. &\n      \\begin{tabular}{@{}r@{}}\n        \\textcircled{e} \\\\\n        $\\phantom{()}$ \\\\\n        e') \\\\\n        $\\phantom{()}$\n      \\end{tabular} &\n      \\begin{tabular}{@{}l@{}}\n        The functor $L\\mapsto\\Hom(L,F):{\\scrA\\subab}\\op\\to\\scrM$ \\\\\n        commutes to small inverse limits \\\\\n        Similar statement as e) for \\\\\n        $L\\mapsto\\bHom(L,F):{\\scrA\\subab}\\op\\to\\scrA_\\scrM$.\n      \\end{tabular}\n    \\end{array}\n  \\right.\\tag{75}\n\\end{equation}\n\\textbf{Comments on the formulaire \\eqref{eq:106.75}.}\\enspace I have\nlimited myself to chose canonical isomorphisms\n(\\hyperref[eq:106.75]{a)} to \\hyperref[eq:106.75]{d)}) and exactness\nproperties (\\hyperref[eq:106.75]{e)} and \\hyperref[eq:106.75]{e')})\nwhich seem to me the most relevant for what follows. Other exactness\nand variance properties are commutation of the functors\n\\[F\\mapsto\\Hom(L,F):\\scrA_\\scrM\\to\\scrM\\quad\\text{and}\\quad\nF\\mapsto\\bHom(L,F):\\scrA_\\scrM\\to\\scrA_\\scrM\\]\nto small inverse limits, and compatibility of formation of $\\Hom(L,F)$\nand $\\bHom(L,F)$ with functors\n\\[u:\\scrM\\to\\scrM'\\]\ncommuting to small inverse limits. As for formulæ for varying topos\n\\scrA, corresponding to a morphism of topoi, we'll come back upon this\nin a later section, in relation with the homology and cohomology\ninvariants of maps in \\Cat. Also, I am completely disregarding here\ncompatibilities between canonical isomorphisms (surely the reader\nwon't complain about this). All this as far as omissions are\nconcerned.\n\nAs\\pspage{414} for the formulas included in \\eqref{eq:106.75}, the\nthree basic ones, including all others in a more or less formal way,\nare the circled ones \\hyperref[eq:106.75]{a)},\n\\hyperref[eq:106.75]{e)} and \\hyperref[eq:106.75]{b)}. The properties\n\\hyperref[eq:106.75]{a)} and \\hyperref[eq:106.75]{e)} jointly can be\nviewed as the characterization up to canonical isomorphism, for fixed\n$F$, of the operation $\\Hom(L,F)$, i.e., of the functor\n\\[\\widetilde F: L\\mapsto\\Hom(L,F): {\\scrA\\subab}\\op\\to\\scrM,\\]\nfactoring the functor\n\\[F:\\scrA\\op\\to\\scrM\\]\nvia the abelianization functor $\\Wh_A:X\\mapsto \\bZ^{(X)}$. In terms of\na), the formula b) can be viewed as essentially the definition of\n$\\bHom(L,F)$ via $\\Hom({-},F)$, more specifically we get\n\\begin{equation}\n  \\label{eq:106.76}\n  \\bHom(L,F)(X) \\simeq \\Hom(\\bZ^{(X)},\\bHom(L,F)) \\simeq\n  \\Hom(\\bZ^{(X)}\\otimes L, F).\\tag{76}\n\\end{equation}\nTaking $L=\\bZ^{(X)}$ and using\n\\[\\bZ^{(X)}\\otimes \\bZ^{(Y)} \\simeq\\bZ^{(X\\times Y)}\\]\n(\\eqref{eq:104.17} page \\ref{p:389}), \\eqref{eq:106.76} gives\n\\hyperref[eq:106.75]{a')}, whereas \\hyperref[eq:106.75]{b')} follows\nvia \\eqref{eq:106.76} applied to both members, from associativity of the\noperation $\\otimes$. Formula \\hyperref[eq:106.75]{c)} is the\nparticular case of \\hyperref[eq:106.75]{a)} for $X=e$, in the same way\n\\hyperref[eq:106.75]{c')} follows from\n\\hyperref[eq:106.75]{a')}. Formula \\hyperref[eq:106.75]{d)} follows\nfrom \\hyperref[eq:106.75]{c)}, \\hyperref[eq:106.75]{b)} and the\nrelation\n\\[\\bZ_\\scrA\\otimes L\\simeq L.\\]\nThe exactness property \\hyperref[eq:106.75]{e')} is equivalent to the\nsimilar exactness statement for the functors\n\\[L\\mapsto\\bHom(L,F)(X)\\simeq\\Hom(\\bZ^{(X)}\\otimes L,F),\\]\nfor $X$ in \\scrA, and thus reduces to \\hyperref[eq:106.75]{e)} with\n$L$ replaced by $\\bZ^{(X)}\\otimes L$.\n\nI would like now to come back to the question of ``computation'' of\n$\\Hom(L,F)$ and $\\bHom(L,F)$. We may for this end assume \\scrA{} to be\ndescribed by a \\emph{site} $A$ -- which, in case the ``topology'' on\n$A$ defining the site structure is the chaotic one, brings us back to\nthe particular case $\\scrA=\\Ahat$ we are mainly interested in at\npresent. Accordingly, we'll consider the objects $F$ in $\\scrA_\\scrM$\nas being functors\n\\begin{equation}\n  \\label{eq:106.77}\n  F:A\\op\\to\\scrM\\tag{77}\n\\end{equation}\nsatisfying the standard exactness properties for sheaves (with respect\nto the given site structure on $A$). In terms of \\eqref{eq:106.71},\nthis is just the composition of the functor \\eqref{eq:106.71} with the\ncanonical functor\n\\begin{equation}\n  \\label{eq:106.78}\n  A\\to\\scrA=A^{\\sim},\\tag{78}\n\\end{equation}\nassociating to an object $a$ in $A$ the presheaf represented by it, in\nthe\\pspage{415} most common case when this presheaf is a sheaf for any\nchoice of $a$, otherwise we take the sheaf associated to it. In the\nfirst case (which we may reduce to if we prefer, by suitable choice of\nthe site $A$ for given topos \\scrA) the functor \\eqref{eq:106.78} is\nfully faithful and moreover and embedding, therefore, we'll identify\nan object $a$ in $A$ with the corresponding object in \\scrA. Thus, the\ndescription \\eqref{eq:106.76} of $\\bHom$ in terms of $\\Hom$ may be\ninterpreted, from this point of view, as a formula with $X=a$ in $A$,\ni.e., as describing the sheaf $\\bHom(L,F)$ as a functor on\n$A\\op$. Accordingly, the question of describing the sheaf $\\bHom(L,F)$\nis reduced to the question of describing the objects $\\Hom(L',F)$ in\n\\scrM, for $L'=\\bZ^{(X)}\\otimes L$. Thus, the main question here is to\ngive a ``computational'' description of the object $\\Hom(L,F)$ in\n\\scrM, for $L$ in $\\scrA\\subab$ and $F$ in $\\scrA_\\scrM$, i.e., $F$\nand $L$ being sheaves on $A$\n\\begin{equation}\n  \\label{eq:106.79}\n  F:A\\op\\to\\scrM,\\quad\n  L:A\\op\\to\\Ab.\\tag{79}\n\\end{equation}\nThe rule of the game here is to do so, using just\n\\hyperref[eq:106.75]{a)} in case of $X=a$ in $A$, and the exactness\nproperty \\hyperref[eq:106.75]{e)}.\n\nIt seems most convenient here to introduce again the additive envelope\n$\\Add(A)$ of the category $A$, which we'll assume to be small in what\nfollows, and the canonical additive functor\n\\begin{equation}\n  \\label{eq:106.80}\n  \\varepsilon\\subab:\\Add(A)\\to\\scrA\\subab,\\tag{80}\n\\end{equation}\nextending the functor\n\\[a\\mapsto\\bZ^{(a)}:A\\to\\scrA\\subab.\\]\nFor a given $F$ \\eqref{eq:106.77}, it follows from formula\n\\hyperref[eq:106.75]{(75 a))} that the composition\n\\[\\widetilde F\\circ\\varepsilon\\subab\\op:\\Add(A)\\op\n\\xrightarrow{\\varepsilon\\subab\\op} {\\scrA\\subab}\\op\n\\xrightarrow{\\widetilde F} \\scrM\\]\nis just the canonical extension $\\Add(F)$ of $F$ to $\\Add(A)\\op$,\nwhose value on the general object\n\\[x = \\bigoplus_{i\\in I} \\Wh_A(a_i)\\quad\n\\text{($I$ a finite indexing set)}\\]\nof $\\Add(A)$ (where $\\Wh_A(a)=\\bZ^{(a)}$ as an object in\n$\\Add(A)\\subset\\Ahatab$) is just\n\\begin{equation}\n  \\label{eq:106.81}\n  \\Add(F)(x)=\\prod_{i\\in I}F(a_i).\\tag{81}\n\\end{equation}\nNow, it is easily checked that for any object $L$ in $\\scrA\\subab$,\ni.e., any sheaf $L:A\\op\\to\\Ab$, we have a canonical isomorphism in\n$\\scrA\\subab$\n\\begin{equation}\n  \\label{eq:106.82}\n  L\\fromsim \\varinjlim_{\\text{$(x,u)$ in $\\Add(A)_{/L}$}} \\varepsilon\\subab(x)\\tag{82}\n\\end{equation}\n(compare with the similar isomorphism on page \\ref{p:403}). Using\n\\hyperref[eq:106.75]{(75~e)}, we\\pspage{416} deduce from this the\nexpression\n\\begin{equation}\n  \\label{eq:106.83}\n  \\Hom(L,F)=\\widetilde F(L)\\simeq \\varinjlim_{\\text{$(x,u)$ in\n      $\\Add(A)_{/L}$}} \\Add(F)(x),\\tag{83}\n\\end{equation}\nwhich in an evident way is functorial in $L$ for variable $L$.\n\nThis is about the best which can be done in general, it seems to me,\nby way of ``computational'' expression of $\\Hom(L,F)$ in terms of $F$\nand $L$ given as in \\eqref{eq:106.79}. Of course, the symbol\n$\\Add(A)_{/L}$ is relative to the canonical functor\n$\\varepsilon\\subab$ \\eqref{eq:106.80}, which is a full embedding in\ncase the site structure on $A$ is the chaotic one, i.e.,\n$\\scrA=\\Ahat$. In computational terms, this category is rather\nexplicit, an object of the category is just a pair\n\\[(x,u)=\\bigl((a_i)_{i\\in I}, (u_i)_{i\\in I}\\bigr)\\]\nwhere $I$ is a finite indexing set, $(a_i)_{i\\in I}$ a family of\nobjects of $A$, and for $i$ in $I$, $u_i$ is an element of $L(a_i)$ --\nI'll leave to the reader the description of maps between such\nobjects. The value of $\\Add(F)(x)$ is given by \\eqref{eq:106.81}\nabove.\n\n\\begin{remark}\n  The expression \\eqref{eq:106.83} of $\\Hom(L,F)=\\widetilde F(L)$\n  makes sense, provided only the additive category \\scrM{} is stable\n  under small inverse limits, without having to assume that \\scrM{} be\n  a pseudotopos. This makes us suspect that the functor\n  \\[\\scrP\\mapsto \\scrP\\circ\\Wh :\n  \\bHom^!(\\scrA\\subab\\op,\\scrM)\\to\\scrA_\\scrM\\]\n  is an equivalence (\\eqref{eq:104.13} p.\\ \\ref{p:388}) without this\n  extra assumption, provided \\scrA{} is an actual topos (not only a\n  pseudotopos as in loc.\\ cit.). Indeed, we get a reasonable candidate\n  for a quasi-inverse functor\n  \\[F\\mapsto\\widetilde\n  F:\\scrA_\\scrM\\to\\bHom^!(\\scrA\\subab\\op,\\scrM).\\]\n  The only point still to check, with \\eqref{eq:106.83} defining\n  $\\widetilde F$ for given $F$ in $\\scrA_\\scrM$, is that we get a\n  functorial isomorphism\n  \\[\\widetilde F(\\bZ^{(a)}) \\simeq F(a)\\]\n  for $a$ in $A$. In case $\\scrA=\\Ahat$, this follows from the fact\n  that \\eqref{eq:106.80} is fully faithful, hence $\\Add(A)_{/L}$ for\n  $L=\\bZ^{(a)}$ admits a final object -- hence the limit\n  \\eqref{eq:106.83} is the value of $\\Add(F)$ on the latter, namely\n  $F(a)$.\n\\end{remark}\n\nI feel the little program on the $\\bHom$ and $\\Hom$ operations, as\ncontemplated on page \\ref{p:412}, is by now completed; all we've got\nto do still is to dualize to get corresponding results for $*$ and\n$\\oast$. It's just a matter of essentially copying the formulaire\n\\eqref{eq:106.75}, which I'll do\\pspage{417} for the sake of getting\nmore familiar with the more unusual operations $*$ and $\\oast$. Now\nof course, we'll have to restrict to the case $\\scrA=\\Ahat$, and use\nthe interpretation \\eqref{eq:106.68} of the data $F$, $L'$ as functors\non $A\\op$ and on $A$ with values in \\scrM{} and \\Ab{} respectively,\nwhere now \\scrM{} is an additive category stables under small\n\\emph{direct} limits. By duality, the ``sections'' or ``inverse\nlimits'' functor $\\varprojlim_{A\\op}$ (or ``cointegration'') is\nreplaced by the direct limit functor $\\varinjlim_{A\\op}$ (or\n``integration''). With this in mind, we get the following\ntranscription of \\eqref{eq:106.75}:\n\\begin{equation}\n  \\label{eq:106.84}\n  \\left\\{%\n    \\renewcommand*{\\arraystretch}{1.15}%\n    \\begin{array}{@{}r@{}rl@{}}\n      \\left\\{\\rule{0pt}{3.2ex}\\right. &\n      \\begin{tabular}{@{}r@{}}\n        a) \\\\ \n        a')\n      \\end{tabular} &\n      \\begin{array}{@{}l@{}}\n        \\smash{F*\\bZ^{(b\\op)}\\simeq F(b)\\quad\\text{for any $b$ in $A$, hence\n        $b\\op$ in $B$}} \\\\\n        \\smash{F\\oast\\bZ^{(b\\op)}\\simeq(a\\mapsto F(a\\lor b)\\simeq\n        \\varinjlim_{\\text{$(x,\\alpha)$ in $\\preslice A{a\\lor\n        b}$}} F(x))}\n      \\end{array} \\\\\n      \\left\\{\\rule{0pt}{3.2ex}\\right. &\n      \\begin{tabular}{@{}r@{}}\n        b) \\\\\n        b')\n      \\end{tabular} &\n      \\begin{array}{@{}l@{}}\n        \\smash{(F*L')*L'' \\simeq F*(L'\\otimes L'')} \\\\\n        \\smash{(F\\oast L')*L'' \\simeq F\\oast(L'\\otimes L'')}\n      \\end{array} \\\\\n      \\left\\{\\rule{0pt}{3.2ex}\\right. &\n      \\begin{tabular}{@{}r@{}}\n        c) \\\\\n        c')\n      \\end{tabular} &\n      \\begin{array}{@{}l@{}}\n        \\smash{F*\\bZ_\\Bhat \\simeq \\varinjlim_{A\\op} F} \\\\\n        \\smash{F \\oast \\bZ_\\Bhat \\simeq F}\n      \\end{array} \\\\\n      & \\text{d)} &\\smash{F*L' \\simeq \\varinjlim_{A\\op} F\\oast L'} \\\\\n      \\left\\{\\rule{0pt}{6.2ex}\\right. &\n      \\begin{tabular}{@{}r@{}}\n        e) \\\\\n        $\\phantom{()}$ \\\\\n        e') \\\\\n        $\\phantom{()}$\n      \\end{tabular} &\n      \\begin{tabular}{@{}l@{}}\n        The functor $\\smash{L'\\mapsto F*L':\\Bhatab\\to\\scrM}$ \\\\\n        commutes to small direct limits \\\\\n        Similar statement as e) for \\\\\n        $\\smash{L'\\mapsto F\\oast L':\\Bhatab\\to\\AhatM}$.\n      \\end{tabular}\n    \\end{array}\n  \\right.\\tag{84}\n\\end{equation}\n\\textbf{Comments.}\\enspace This formulaire doesn't look wholly\nsymmetric to \\eqref{eq:106.75}, due to the fact that we gave\n\\eqref{eq:106.75} in a somewhat more general context than topoi of the\ntype \\Ahat{} only. This accounts for the letter $X$ or $Y$ in\n\\eqref{eq:106.75} (designating there an arbitrary object of \\Ahat)\nbeing replaced by a small letter $a$ or $b$ (designating objects in\n$A$), which allows the dualization to be done. A slight trouble then\noccurs when $A$ is not stable under binary products $a\\times b$, these\nproducts are only in \\Ahat{} not in $A$, which accounts for the\nslightly more complicated formula \\hyperref[eq:106.84]{a')} of\n\\eqref{eq:106.84} in comparison to \\hyperref[eq:106.75]{(75~a'))},\nwhose more explicit form, in the present context of data as in\n\\eqref{eq:106.68}, would be\n\\begin{equation}\n  \\label{eq:106.85}\n  \\bHom(\\bZ^{(a)},F)\\simeq\\bigl(b\\mapsto F(a\\times\n  b)\\simeq\\varprojlim_{\\text{$(x,\\alpha)$ in $A_{/a\\times b}$}}\n  F(x)\\bigr).\\tag{85} \n\\end{equation}\nAccordingly, the symbol $a\\lor b$ (``sum'') in\n\\hyperref[eq:106.84]{(84~a'))} denotes the element $(a\\op\\times\nb\\op)\\op$ of $(\\Bhat)\\op$ and can be identified with the \\emph{sum} of\n$a$ and $b$ in the category $A$\\pspage{418} whenever the sum exists in\n$A$. Accordingly, the category $\\preslice A{a\\lor b}$, dual to\n$B_{/a\\op\\times b\\op}$, can be described as\n\\begin{equation}\n  \\label{eq:106.86}\n  \\preslice A{a\\lor b}=\n  \\begin{tabular}[t]{@{}l@{}}\n    category of all triples $(x,u,v)$, with $x$ in $A$ and \\\\\n    $u:a\\to x$, $v:b\\to x$ maps in $A$,\n  \\end{tabular}\\tag{86}\n\\end{equation}\nthe maps in this category from $(x,u,v)$ to $(x',u',v')$ being just\nmaps $x\\to x'$ ``compatible'' with the pairs $\\alpha=(u,v)$ and\n$\\alpha'=(u',v')$ in the obvious way.\n\n\\begin{remarks}\n  \\namedlabel{rem:106.1}{1})\\enspace\n  An interesting particular case (although admittedly a little strange\n  looking in our modelizing context!) is the one when $A$ is an\n  additive category, hence stable under both binary sum and product\n  operation, the two operations being canonically isomorphic, and\n  written as $a\\oplus b$. In this case, comparison of\n  \\eqref{eq:106.85} and \\eqref{eq:106.86} shows that for a given\n  object $a$ in $A$, hence $a\\op$ in $B$, the operation\n  $\\Hom(\\bZ^{(a)},{-})$ on \\AhatM{} is canonically isomorphic to the\n  operation ${-}\\oast\\bZ^{(a\\op)}$. This immediately extends to a\n  canonical isomorphism\n  \\begin{equation}\n    \\label{eq:106.87}\n    \\bHom(L,F)\\simeq F\\oast\\check L \\quad\n    \\text{for $L$ in $\\Add(A)\\subset\\Ahatab$, % \\\\\n      $F$ in \\AhatM,}\n    \\tag{87}\n  \\end{equation}\n  where we have denoted by\n  \\begin{equation}\n    \\label{eq:106.88}\n    L\\mapsto\\check L: \\Add(A)\\op\\toequ \\Add(A\\op)=\\Add(B)\\tag{88}\n  \\end{equation}\n  the canonical antiequivalence between $\\Add(A)$ and $\\Add(B)$. In\n  case $A$ is the final category, namely an additive category reduced\n  to the zero object, and if we take moreover $\\scrM=\\Ab$,\n  \\eqref{eq:106.87} is the familiar formula of linear algebra, valid\n  when $L$ is a free $\\bZ$-module of finite type. It should be noted\n  that $A$ being stable under binary products, it follows that\n  $\\Add(A)$ is stable under tensor products, and similarly for\n  $\\Add(B)$, and that the equivalence \\eqref{eq:106.88} is compatible\n  with tensor products. The relation \\eqref{eq:106.87} is about the\n  only relationship I could think of between the two types of\n  operations upon a given category \\AhatM.\n\n  2)\\enspace There are still two other, more trivial operations on a\n  category \\Ahat, of a similar nature to the two operations $\\Hom$\n  and $*$ considered so far. The more familiar one is componentwise\n  tensor product\n  \\begin{equation}\n    \\label{eq:106.89}\n    (L,F)\\mapsto L\\otimes F: \\Ahatab\\times\\AhatM\\to\\AhatM,\\tag{89}\n  \\end{equation}\n  defined by\n  \\[{L\\otimes F}\\,(a) = L(a)\\otimes F(a),\\]\n  where the second member denotes external tensor product of the\n  abelian group $L(a)$ with the object $F(a)$ of \\scrM{} (defined when\n  \\scrM{} is additive and stable under small direct limits). The\n  other, deduced from \\eqref{eq:106.89} by duality\\pspage{419}\n  \\begin{equation}\n    \\label{eq:106.90}\n    (L',F)\\mapsto\\bHom(L',F) : \\Bhatab\\times\\AhatN\\to\\AhatN\\tag{90}\n  \\end{equation}\n  is defined when the additive category \\scrN{} is stable under small\n  inverse limits, and can be equally described as taking external\n  $\\Hom$'s componentwise\n  \\[\\bHom(L',F)(a) = \\Hom(L'(a),F(a)).\\]\n  These operations make sense too when \\Ahat{} is replaced by an\n  arbitrary topos \\scrA, \\Bhatab{} being replaced by the category of\n  abelian cosheaves on \\scrA. It doesn't seem worthwhile here to dwell\n  on them, as they don't seem to be so relevant for the homology and\n  cohomology formalism we want to develop in the next sections. I like\n  to point out, though, that in the cohomology formalism of ringed\n  topoi the tensor product operation \\eqref{eq:106.89} and the derived\n  operation $\\overset{\\mathrm L}{\\otimes}$ on the relevant derived\n  categories $\\D_\\bullet$ play an important role, and it is likely\n  therefore that in a more extensive development of the homology and\n  cohomology formalism within the context of topoi \\Ahat{} and maps in\n  \\Cat, the same will hold for the dual operation \\eqref{eq:106.90}\n  too.\n\n  The reader who may feel confused by the manifold use of the symbol\n  $\\bHom$ should notice that there is no possibility of confusion\n  reasonably between \\eqref{eq:106.90} and \\eqref{eq:106.65} (p.\\\n  \\ref{p:409}), as the argument $L'$ in \\eqref{eq:106.90} is in\n  \\Bhatab, whereas the argument $L$ in \\eqref{eq:106.65} is in an\n  altogether different category \\Ahatab. In the case when $A$ is the\n  final category say, hence $A=B$, and a confusion might arise, the\n  two operations turn out to be actually the same (up to canonical\n  isomorphism). A similar remark applies to the fear of confusion\n  between the kindred operations $\\otimes$ and $\\oast$. I daresay I\n  devoted a considerable amount of attention on terminology and\n  notation around the abelianization story -- and it does seem that a\n  pretty coherent formalism is emerging indeed.\n\\end{remarks}\n\n\\bigbreak\n\\presectionfill\\ondate{17.8.}\\par\n\n% 107\n\\hangsection{Review \\texorpdfstring{\\textup{(4)}}{(4)}: Case of\n  general ground ring \\texorpdfstring{$k$}{k}.}\\label{sec:107}%\n\\phantomsection\\addcontentsline{toc}{subsection}{\\numberline\n  {F)}Extension of ground ring from \\texorpdfstring{$\\bZ$ to $k$\n  \\textup($k$}{Z to k (k}-linearization\\texorpdfstring{\\textup)}{)}.}%\n\\textbf{\\namedlabel{subsec:107.F}{F)}\\enspace Extension of ground ring\n  from $\\bZ$ to $k$ ($k$-linearization).}\\enspace%\nI would like still to make a quick review of the main facts and\nformulas of the last two sections, replacing throughout the ground\nring $\\bZ$ by an arbitrary \\emph{commutative} ring $k$, and additive\ncategories \\scrM{} and additive functors between these, by\n$k$-additive categories and $k$-additive functors. This will allow us\nto check that the conceptual and notational set-up we got so far\nextends smoothly to $k$-linearization.\n\nLet's\\pspage{420} recall that a \\emph{$k$-additive category} \\scrM{}\nis an additive category endowed with the extra structure given by a\nhomomorphism of commutative rings\n\\begin{equation}\n  \\label{eq:107.91}\n  k\\to\\End(\\id_\\scrM),\\tag{91}\n\\end{equation}\nwhere the second member denotes the (commutative) ring of all\nendomorphisms of the identity functor of \\scrM{} to itself. Defining\naccordingly the notion of \\emph{$k$-additive functor} between two\n$k$-additive categories $\\scrM$, $\\scrM'$, we'll denote by\n\\begin{equation}\n  \\label{eq:107.92}\n  \\bHom_k(\\scrM,\\scrM')\\subset\\bHom(\\scrM,\\scrM')\\tag{92}\n\\end{equation}\nthe full subcategory of $\\bHom(\\scrM,\\scrM')$ made up with such\nfunctors. Thus, we get a canonical fully faithful inclusion\n\\begin{equation}\n  \\label{eq:107.93}\n  \\bHom_k(\\scrM,\\scrM') \\hookrightarrow \\bHom_{\\bZ}(\\scrM,\\scrM')\n  \\eqdef \\Homadd(\\scrM,\\scrM').\\tag{93}\n\\end{equation}\nWed defined accordingly the categories $\\bHom_{k!}$, $\\bHom_k^!$ as\nfull subcategories of \\eqref{eq:107.92}, and the category\n\\[\\bHom_k(\\scrP,\\scrQ;\\scrM) \\subset \\bBiadd(\\scrP,\\scrQ;\\scrM)\\]\nthe full subcategory of $\\bHom(\\scrP\\times\\scrQ,\\scrM)$ made up with\n\\emph{$k$-bilinear} functors, namely functors $k$-additive in each\nargument (in case $k=\\bZ$,\\scrcomment{Actually, it was previously\n  denoted by just $\\bHom(\\scrP,\\scrQ;\\scrM)$\\ldots} this is the\ncategory denoted previously by $\\bBiadd$), and similarly for the\nnotations $\\bHom_{k!!}$ and $\\bHom_k^{!!}$.\n\nIt should be noted that for a given additive category \\scrM, there is\na ``best'' choice for endowed it with a $k$-linear structure, in such\na way that any $k'$-linear structure just corresponds to ``ground ring\nrestriction'' with respect to suitable (well-defined) ring\nhomomorphism\n\\[k'\\to k;\\]\nwe just take the ``tautological'' linear structure with\n\\[k=\\End(\\id_\\scrM),\\]\nand \\eqref{eq:107.91} the identity.\n\nIf $A$ is any small category, we'll denote by\n\\begin{equation}\n  \\label{eq:107.94}\n  \\Ahatk = A\\uphat_{k\\textup{-Mod}} \\simeq \\bHom(A\\op,\\kMod)\\tag{94}\n\\end{equation}\nthe category of objects in \\Ahat{} endowed with a structure of\n$k$-module, i.e., the category of presheaves on $A$ with values in the\ncategory \\kMod{} of $k$-modules (in the given basic universe\n\\scrU). This is of course a $k$-additive category, which for $k=\\bZ$\nreduces to the category\\pspage{421} of additive presheaves on $A$:\n\\[ A\\uphat_{\\bZ} \\eqdef \\Ahatab.\\]\nWe have, for a homomorphism of commutative rings\n\\[k\\to k',\\]\na corresponding functor between additive topoi\n\\begin{equation}\n  \\label{eq:107.95}\n  \\Ahatk \\to A\\uphat_{k'}, \\quad\n  F\\mapsto F\\otimes_k k' = (a\\mapsto F(a)\\otimes_k k'),\\tag{95}\n\\end{equation}\nby which we may interpret if we wish, in a rather evident way the\n$k'$-linear topos $A\\uphat_{k'}$ as deduced from the $k$-linear one\n\\Ahatk{} by ``ground ring extension'' $k\\to k'$, namely as the\nsolution of a $2$-universal problem with respect to categories\n$\\bHom_{k!}(\\Ahatk,\\scrM)$, where \\scrM{} is a $k'$-additive category\nstable under small direct limits. The $k$-abelianization functor\n\\begin{equation}\n  \\label{eq:107.96}\n  \\Ahat\\to\\Ahatk, \\quad X\\mapsto k^{(X)}\\quad\\bigl(\\;\\simeq (a \\mapsto\n  k^{(X(a))})\\bigr)\\tag{96} \n\\end{equation}\nor $\\Wh_{\\Ahat,k}$, is defined as the composition\n\\[\\Ahat\\to A\\uphat_{\\bZ} = \\Ahatab\\to \\Ahatk,\\]\nwhere the first functor is the familiar abelianization\n$X\\mapsto \\bZ^{(X)}$, and the second is ground ring extension for\n$\\bZ\\to k$. If \\scrM{} is any $k$-additive category stable under small\ndirect limits, \\eqref{eq:107.96} gives rise to a functor which is an\nequivalence of categories $F\\mapsto(X\\mapsto F(k^{(X)}))$\n\\begin{equation}\n  \\label{eq:107.97}\n  \\bHom_{k!}(\\Ahatk,\\scrM)\\toequ\\bHom_!(\\Ahat,\\scrM) \\quad (\\;\\toequ\n  \\bHom(A,\\scrM)),\\tag{97} \n\\end{equation}\nwhere the second equivalence is the familiar one of prop.\\\n\\ref{prop:105.3} (p.\\ \\ref{p:394}), independent of any abelian\nassumptions. Dually, we get an equivalence\n\\begin{equation}\n  \\label{eq:107.98}\n  \\bHom_k^!((\\Ahatk)\\op,\\scrM)\\toequ \\bHom((\\Ahat)\\op,\\scrM)\n  \\quad(\\;\\toequ \\bHom(A\\op,\\scrM)),\\tag{98}\n\\end{equation}\nwhere \\scrM{} is any $k$-additive category stable under small inverse\nlimits. From \\eqref{eq:107.97} \\eqref{eq:107.98} and replacing in\n\\eqref{eq:107.98} $A$ by the dual category $B=A\\op$, and assuming the\n$k$-additive category \\scrM{} is stable under both types of small\nlimits, we get the duality equivalence\n\\begin{equation}\n  \\label{eq:107.99}\n  \\bHom_{k!}(\\Ahatk,\\scrM)\\equ \\bHom_k^!(\\Bhatk,\\scrM) \\quad (\\;\\equ\n  \\bHom(A,\\scrM)).\\tag{99} \n\\end{equation}\nThis may be viewed as giving two alternative descriptions, by the two\nmembers of \\eqref{eq:107.99}, of the category\n\\[\\BhatM = \\bHom(B\\op=A,\\scrM)\\]\nof \\scrM-valued presheaves on $B$ (defined without any use of the\n$k$-additive structure of \\scrM). The left-hand side interpretation\n\\eqref{eq:107.99}, via \\scrM-valued\\pspage{422} $k$-additive cosheaves\non the $k$-additive topos \\Ahatk, gives rise to the operations $*_k$\nand $\\oast_k$ of \\Ahatk{} upon \\BhatM{} (operations previously denoted\nby $*$ and $\\oast$ when $k=\\bZ$ and no confusion would arise from\ndropping subscripts), and similarly the interpretation by right-hand\nside of \\eqref{eq:107.99}, via \\scrM-valued $k$-additive sheaves on\nthe $k$-additive topos \\Bhatk, gives rise to the operations $\\Hom_k$\nand $\\bHom_k$ of \\Bhatk{} upon \\BhatM. Replacing in this comment $A$\nby $B$, hence \\Bhat{} by \\Ahat, namely in terms of operations upon the\ncategory of \\scrM-valued sheaves on the topos \\Ahat{} (or \\scrM-valued\npresheaves on $A$), we get the mutually dual pair of operations\n\\begin{equation}\n  \\label{eq:107.100}\n  \\begin{aligned}\n    (F,L')&\\mapsto F*_kL' : \\AhatM\\times\\Bhatk\\to\\scrM, \\\\\n    (F,L')&\\mapsto F\\oast_kL' : \\AhatM\\times\\Bhatk\\to\\AhatM\n  \\end{aligned}\n  \\tag{100}\n\\end{equation}\nand\n\\begin{equation}\n  \\label{eq:107.101}\n  \\begin{aligned}\n    (L,F)&\\mapsto \\Hom_k(L,F) : \\Ahatk\\times\\AhatM\\to\\scrM, \\\\\n    (L,F)&\\mapsto \\bHom_k(L,F) : \\Ahatk\\times\\AhatM\\to\\AhatM.\n  \\end{aligned}\n  \\tag{101}\n\\end{equation}\nThe operations \\eqref{eq:107.100} are ruled by formulaire\n\\eqref{eq:106.84} (with subscripts $k$ added), whereas the operations\n\\eqref{eq:107.101} are ruled by formulaire \\eqref{eq:106.75} with\nsubscripts (see moreover for the latter comments on page \\ref{p:417},\nand formula \\eqref{eq:106.85} for \\hyperref[eq:106.75]{(75~a'))}; they\nare valid provided the additive category is stable under small direct\nresp.\\ inverse limits. Moreover, we get a ``computational'' expression\nof $\\Hom_k(L,F)$ by a formula extending \\eqref{eq:106.83} which we'll\nstill have to write down, and correspondingly for $F*_kL'$ (by a dual\nformula, which we forgot to include in the previous section). To do\nso, we have to introduce still\n\\begin{equation}\n  \\label{eq:107.102}\n  \\Add_k(A)\\subset\\Ahatk,\\tag{102}\n\\end{equation}\nthe $k$-additive envelope of $A$, which may be described (beside by\nthe familiar $2$-universal property in the context of $k$-additive\ncategories and functors from $A$ into these) as the full subcategory\nof \\Ahatk{} generated by finite sums of objects of the type $k^{(a)}$\nwith $a$ in $A$ -- i.e., the general object of $\\Add_k(A)$ may be\nwritten\n\\[\\bigoplus_{i\\in I}k^{(a_i)},\\]\nwhere $(a_i)_{i\\in I}$ is any finite family of objects of $A$. When\nthe finiteness condition on $I$ is dropped, we get a larger full\nsubcategory\n\\begin{equation}\n  \\label{eq:107.103}\n  \\Addinf_k(A)\\subset\\Ahatk,\\tag{103}\n\\end{equation}\nwhich may also be interpreted as ``the'' solution of the $2$-universal\nproblem of sending $A$ into categories which are $k$-additive and\nmoreover infinitely additive, i.e., stable under small direct\nsums. Enlarging the subcategories \\eqref{eq:107.102} and\n\\eqref{eq:107.103} of \\Ahatk{} by adjoining all objects of\n\\Ahatk\\pspage{423} isomorphic to direct factors of objects in the\nconsidered subcategory, we get to (strictly) full subcategories of\n\\Ahatk{} containing the latter, which may be interpreted as being just\nthe subcategory $\\Proj(\\Ahatk)$ of \\emph{projective} objects of\n\\Ahatk{} when starting with \\eqref{eq:107.103}, and as the subcategory\n$\\UlProj(\\Ahatk)$ of \\emph{ultraprojective} objects, namely objects\nprojective and of finite presentation, when starting with\n\\eqref{eq:107.102}. These may be equally interpreted as the abstract\nKaroubi envelops of the categories \\eqref{eq:107.103} and\n\\eqref{eq:107.102}, deduced from these formally by adjoining images\n(=coimages) of projectors (or equivalently, as $2$-universal solutions\nof the $2$-universal problem of sending the given category\n\\eqref{eq:107.103} or \\eqref{eq:107.102} into ``karoubian\ncategories'', namely categories stable under images (=coimages) of\nprojectors, with maps between these being functors commuting to those\nimages or coimages of projectors):\n\\begin{equation}\n  \\label{eq:107.104}\n  \\Proj(\\Ahatk)\\equeq\\Kar(\\Addinf_k(A)), \\quad\n  \\UlProj(\\Ahatk)\\equeq\\Kar(\\Add_k(A)).\\tag{104}\n\\end{equation}\nAccordingly, these two categories may be equally described, directly\nin terms of $A$, as the solutions of the two $2$-universal problems,\nobtained from mapping $A$ into $k$-additive karoubian categories,\nwhich in the first case (corresponding to $\\Proj(\\Ahatk)$) are\nmoreover assume infinitely additive.\n\nTo sum up the situation, we get in \\Ahatk{} a diagram of four\nremarkable full subcategories \\eqref{eq:107.102}, \\eqref{eq:107.103},\n\\eqref{eq:107.104}, which may be interpreted (as well as \\Ahatk{}\nitself) as the solutions of five corresponding ``$k$-additive''\n$2$-universal problems, in terms of sending $A$ into $k$-additive\ncategories satisfying suitable extra exactness assumptions (namely\nbeing karoubian for the two categories in \\eqref{eq:107.104}, being\ninfinitely additive for the two categories $\\Addinf_k(A)$ and its\nKaroubi envelope $\\Proj(\\Ahatk)$, and being stable for small direct\nlimits in case of \\Ahatk). Including equally the non-additive\ncategories $A$ and \\Ahat{} and the functors $A\\to\\Add_k(A)$,\n$\\Ahatk\\to\\Ahat$, we get a seven term diagram of canonical functors\nbetween categories of presheaves upon $A$:\n\\begin{equation}\n  \\label{eq:107.105}\n  \\left\\{\n    \\begin{tabular}{@{}c@{}}\n      \\begin{tikzcd}[baseline=(O.base),sep=small]\n        A\\ar[d] & & \\\\\n        \\Add_k(A)\\ar[r,hook]\\ar[d,hook] &\n        \\UlProj(\\Ahatk)\\equeq\\KarAdd_k(A) \\ar[d,hook,shift right=3.5em] & \\\\\n        \\Addinf_k(A)\\ar[r,hook] &\n        \\Proj(\\Ahatk)\\equeq\\KarAddinf_k(A)\\ar[r,hook] & \\Ahatk\\ar[d] \\\\\n        & & |[alias=O]| \\Ahat\n      \\end{tikzcd},\n    \\end{tabular}\\right.\n  \\tag{105}\n\\end{equation}\nwhere the five categories in the two intermediate lines are\n$k$-additive as well as all functors between them in the diagram,\nwhich are moreover fully faithful. For any $k$-additive\\pspage{424}\ncategory \\scrM{} stable under small direct limits, taking cosheaves on\n\\Ahat{} with values in \\scrM, and their restrictions to the six other\ncategories in the diagram \\eqref{eq:107.105}, we get a transposed\nseven term diagram as follows, part of which reduces to the four term\ndiagram \\eqref{eq:105.58} (p.\\ \\ref{p:406}) in case $k=\\bZ$:\n\\begin{widematter}\n  \\begin{equation}\n  \\label{eq:107.106}\n  \\left\\{\n    \\begin{tabular}{@{}c@{}}\n      \\begin{tikzcd}[baseline=(O.base),sep=small]\n        \\bHom_!(\\Ahat,\\scrM) \\ar[d,\"\\equ\"'] & & \\\\\n        \\bHom_{k!}(\\Ahatk,\\scrM) \\ar[r,\"\\equ\"] &\n        \\bHomaddinfkar_k(\\Proj(\\Ahatk),\\scrM) \\ar[r,dash,\"\\equ\"]\n        \\ar[d,\"\\equ\"] &\n        \\bHomaddinf_k(\\Addinf_k(A),\\scrM) \\ar[d,\"\\equ\"] \\\\\n        & \\bHomaddkar_k(\\UlProj(\\Ahatk),\\scrM) \\ar[r,dash,\"\\equ\"] &\n        \\bHomadd_k(\\Add_k(A),\\scrM) \\ar[d,\"\\equ\"] \\\\\n        & & |[alias=O]| \\bHom(A,\\scrM)\n      \\end{tikzcd},\n    \\end{tabular}\\right.\n  \\tag{106}\n\\end{equation}\n\\end{widematter}\nwhere the meaning of the symbols used (such as index $k$, suffixes\n``add'' or ``addinf'' and ``kar'') for qualifying $\\bHom$ and denoting\nvarious full subcategories of $\\bHom$ categories, is clear from the\nexplanations given previously. Replacing $A$ by $B$ and\n$\\bHom_!(\\Ahat,\\scrM)$ by $\\bHom^!(\\Bhat,\\scrM)$, we get a diagram\n``dual'' to \\eqref{eq:107.106} (containing the five-term diagram\n\\eqref{eq:106.62} (p.\\ \\ref{p:408}) in case $k=\\bZ$), which we'll not\nwrite out here, valid for any $k$-additive category \\scrM{} stable\nunder small inverse limits. When \\scrM{} is a $k$-additive category\nstable under both types of small limits, then the last term of the\ndiagram \\eqref{eq:107.106} is equal to the last term of the dual one,\nhence a system of fourteen mutually equivalent categories (compare p.\\\n\\ref{p:408}, when we considered ten among them only!), expressing as\nmany ways for interpreting the notion of an \\scrM-valued copresheaf on\n$A$, i.e., an object of $\\bHom(A,\\scrM)$ (which is one among the\nfourteen\\ldots).\n\nLet's comment a little on the significance of the various five\n$k$-additive categories appearing in \\eqref{eq:107.105}. The largest\none \\Ahatk{} is there precisely as the all-encompassing category of\n$k$-additive presheaves, where to carry through all kinds of\n$k$-linear constructions between presheaves on $A$. The significance\nof the (second largest) subcategory $\\Proj(\\Ahatk)$, made up with all\nprojective objects of \\Ahatk, comes mainly from homological algebra\nand emphasis upon replacing objects of \\Ahatk{} by projective\nresolutions; these are chain complexes in $\\Proj(\\Ahatk)$, which may\nbe viewed as being defined (by any given object in \\Ahatk) ``up to\nchain homotopy''. More sweepingly still, we get from general\nprinciples the canonical equivalence of categories\n\\begin{equation}\n  \\label{eq:107.star}\n  \\D^-(\\Ahatk) \\fromequ \\mathrm K^-(\\Proj(\\Ahatk)),\\tag{*}\n\\end{equation}\nwhere $\\D^-$ designates the ``derived category bounded from\nabove''\\pspage{425} of a given \\emph{abelian} category (defined in\nterms of differential operators with degree $+1$, and\nquasi-isomorphisms between complexes with degrees bounded from above),\nwhereas $\\mathrm K^-$ designates localization of the category of\ndifferential complexes with degrees bounded from above of a given\n\\emph{additive} category, localization being taken with respect to\nhomotopisms.\n\nAs any object of $\\Proj(\\Ahatk)$ is a direct factor of an object in\n$\\Addinf_k(A)$, and hence, any object in \\Ahatk{} is isomorphic to a\nquotient of an object in $\\Addinf_k(A)$, it follows again from general\nprinciples that the categories in \\eqref{eq:107.star} are equally\nequivalent to $\\mathrm K^-(\\Addinf_k(A))$, hence\n\\begin{equation}\n  \\label{eq:107.107}\n  \\D^-(\\Ahatk) \\fromequ \\mathrm K^-(\\Proj(\\Ahatk)) \\fromequ\n  \\mathrm K^-(\\Addinf_k(A)).\\tag{107}\n\\end{equation}\nThe advantage of $\\Addinf_k(A)$ over $\\Proj(\\Ahatk)$ is that its\nobjects, and maps between objects, are more readily described in\ncomputational terms, just working with small direct sums of objects of\nthe type $k^{(a)}$ (with $a$ in $A$), and corresponding matrices, with\nentries in free $k$-modules $k^{(\\Hom(a,b))}$. Thus, if we call\n\\emph{cointegrator} (with coefficients in $k$) \\emph{for} $A$ any\nprojective resolution of the constant presheaf $k_A$ with value $k$,\nand denote such object by $L_k^A$, we may view $L_k^A$ as an object\ndetermined up to unique isomorphism, either in $\\mathrm\nK^-(\\Proj(\\Ahatk))$, or in $\\mathrm K^-(\\Addinf_k(A))$ -- and it is\nthe latter interpretation which looks the most convenient. Objects in\nthe first category, namely complexes with degrees bounded from above\nand projective components, which happen to be in the first (i.e.,\ncomponents are in $\\Addinf_k(A)$, i.e., are direct sums of objects of\nthe type $k^{(a)}$) may be called ``\\emph{quasi-special}'' (extending\nthe terminology previously used for cointegrators and integrators, in\ncase $k=\\bZ$). We'll call them \\emph{special} if the components are\neven in $\\Add_k(A)$. The category $\\Add_k(A)$ and its Karoubi envelope\n$\\UlProj(\\Ahatk)$ may be viewed both as embodying \\emph{finiteness\n  conditions}, and similarly for the two corresponding $\\mathrm K^-$\ncategories, which are of course equivalent:\n\\begin{equation}\n  \\label{eq:107.108}\n  \\mathrm K^-(\\UlProj(\\Ahatk)) \\fromequ \\mathrm K^-(\\Add_k(A)),\\tag{108}\n\\end{equation}\nand presumably the canonical functor from \\eqref{eq:107.108} to\n\\eqref{eq:107.107} is fully faithful, under suitable coherence\nconditions at any rate\\ldots\n\n\\bigbreak\n\\presectionfill\\ondate{22.8.}\\pspage{426}\\par\n\n% 108\n\\hangsection{Review \\texorpdfstring{\\textup{(5)}}{(5)}: Homology and\n  cohomology \\texorpdfstring{\\textup(absolute case\\textup)}{(absolute\n    case)}.}\\label{sec:108}%\nSince last Monday, namely for about one week, I have been mainly taken\nby a rather dense sequence of encounters and events, the center of\nwhich has been the unexpected news of my granddaughter Ella's death at\nthe age of nine, by a so-called health accident. I resumed some\nmathematical pondering last night. Today, I got a short letter from\nRonnie Brown, mainly with the announcement of the loss of his son\nGabriel, twenty years old, which occurred about the same time by a\nclimbing accident. It is a good thing that Ronnie felt like telling me\nin a few words about this, while we have never yet seen each other and\nour letters so far have been restricted to mathematics, with maybe\nsometimes some personal comments about his or my own involvement in\nmathematics. It is through these, surely, that a mutual sympathy has\ncome into being, not merely motivated by a common interest in\nmathematics -- and this sympathy I feel has been the main force giving\nlife to our correspondence while mathematically speaking more than\nonce it has been rather a ``dialogue de\nsourds''.\\scrcomment{``dialogue of the deaf''} (This is due mainly to\nmy illiteracy homotopy in theory, and to my reluctance to get really\ninvolved in any ``technical'' matters, until I am really forced to by\nwhat I am just doing.)\n\nI want now to go on with the overall review on ``abelianization'' and\nits relation to the homology and cohomology formalism for small\ncategories, serving as models for homotopy types.\n\n\\addtocounter{subsection}{6}\n\\subsection{Homology and cohomology (absolute case).}\n\\label{subsec:108.G}\nMy aim is to give a perfectly dual treatment of cohomology and\nhomology, which is one main reason why I have to take as coefficients\nfor both, not merely usual abelian presheaves on a given small\ncategory $A$, or sheaves of $k$-modules for a given ring $k$, but more\ngenerally sheaves with values in any abelian category \\scrM, stable\nunder small direct or inverse limits (according as to whether we are\ninteresting in taking homology, or cohomology invariants). It will\nthen turn out that homology of $A$ for \\scrM-valued presheaves (or\ncomplexes of such) is ``the same'' as cohomology of the dual category\n$B$, with coefficients in the corresponding $\\scrM\\op$-valued ones.\n\nAs I am a lot more familiar with cohomology, it is by this I'll begin\nagain. Here, as in the case of an arbitrary topos \\scrX, the\ncohomology invariants $\\mathrm H^i(\\scrX,F)$ with values in an abelian\nsheaf $F$ may be\\pspage{427} viewed as being just the invariants\n$\\Ext^i(\\bZ_\\scrX,F)$ in the category of all abelian sheaves, where\n$\\bZ_\\scrX$ is the constant sheaf on \\scrX{} with value $\\bZ$. The\nsimilar fact holds when $F$ is any sheaf of modules over a sheaf of\nrings $\\scrO_\\scrX$ on \\scrX, with $\\bZ_\\scrX$ being replaced by\n$\\scrO_\\scrX$ in the interpretation above:\n\\[\\mathrm H^i(\\scrX,F) \\simeq \\Ext^i_{\\scrO_\\scrX}(\\scrO_\\scrX, F),\\]\nwhich is often quite useful in the cohomology formalism. We are going\nto restrict here to the case of a constant sheaf of rings, defined by\na fixed commutative ring $k$, which will allow us to play around as\nannounced with the duality relation between $A$ and $B=A\\op$, provided\nmoreover we take more general coefficients still, namely (pre)sheaves\nwith value in a given $k$-additive category \\scrM{} stable under the\nrelevant limits. (Presumably, the case of a locally constant\ncommutative sheaf of rings could be dealt with too, but we'll not dive\ninto this here!) Another important (and by now familiar?) conceptual\npoint is that, rather than the $\\Ext^i$'s which give only partial\ninformation, we are interested in the object they come from (as the\n``cohomology objects''), namely the objects $\\mathrm\nR\\Hom_\\scrOX(L,F)$ in a suitable derived category. In the present\ncase when \\scrX{} is the topos associated to the small category $A$,\nhence the category of \\scrOX-modules has sufficiently many projective\n(namely direct sums of sheaves of the type $\\scrO_\\scrX^{(a)}$ with\n$a$ in $A$), the $\\mathrm R\\Hom_\\scrOX(L,F)$ may be computed, taking a\nprojective resolution $L_\\bullet$ of $L$, by the formula\n\\[\\mathrm R\\Hom_\\scrOX(L,F) \\simeq \\Hom_\\scrOX^\\bullet(L_\\bullet,F)\\]\n(an isomorphism in $\\D^+\\kMod$ say), and similarly when replacing $L$\nand $F$ by arguments $L_\\bullet$ and $F^\\bullet$ in $\\D^-$ and $\\D^+$\nof the category of \\scrOX-modules. As a result, we get a pairing,\ncomputable here using projective resolutions of the argument\n$L_\\bullet$:\n\\begin{equation}\n  \\label{eq:108.star}\n  (L_\\bullet,F^\\bullet)\\mapsto\\mathrm\n  R\\Hom_\\scrOX(L_\\bullet,F^\\bullet) : \\D^-(\\scrOX)\\times\\D^+(\\scrOX)\n  \\to \\D^+\\kMod,\\tag{*}\n\\end{equation}\nwhere $k$ is a commutative ring and \\scrOX{} is endowed with a\nstructure of $k$-algebra. Using $\\bHom_\\scrOX$ and its total derived\nfunctor, we get likewise\n\\begin{equation}\n  \\label{eq:108.starstar}\n  (L_\\bullet,F^\\bullet)\\mapsto\\mathrm\n  R\\bHom_\\scrOX(L_\\bullet,F^\\bullet) : \\D^-(\\scrOX)\\times\\D^+(\\scrOX)\n  \\to \\D^+(\\scrOX),\\tag{**}\n\\end{equation}\nwith\n\\[\\mathrm R\\bHom_\\scrOX(L_\\bullet,F^\\bullet) \\simeq\n\\bHom_\\scrX^{\\bullet\\bullet}(\\scrL_\\bullet,F^\\bullet),\\]\nwhere $\\scrL_\\bullet$ is a projective resolution of $L_\\bullet$, and\n$\\bHom^{\\bullet\\bullet}$ stands for the simple complex associated to\nthe double complex obtained by taking\\pspage{428} $\\bHom$'s\ncomponentwise (and we have the similar formula of course for the\n$\\Hom$'s and $\\mathrm R\\Hom$'s non-bold-faced).\n\nTaking $L_\\bullet=\\scrOX$ (or any resolution of \\scrOX), the $\\mathrm\nR\\Hom$ invariant \\eqref{eq:108.star} reduces to the total derived\nfunctor $\\mathrm R\\Gamma$ of the sections functor\n\\begin{equation}\n  \\label{eq:108.i}\n  \\mathrm R\\Hom_\\scrOX(\\scrOX,F^\\bullet)\\simeq\\mathrm R\\Gamma_\\scrX(F^\\bullet)\\tag{i}\n\\end{equation}\n(whereas $\\mathrm R\\bHom_\\scrOX(\\scrOX,F^\\bullet)\\simeq F^\\bullet$ of\ncourse), which in turn allows to give the following familiar\nexpression of $\\mathrm R\\Hom$ in terms of $\\mathrm R\\bHom$:\n\\begin{equation}\n  \\label{eq:108.ii}\n  \\mathrm R\\Hom_\\scrOX(L_\\bullet,F^\\bullet) \\simeq \\mathrm\n  R\\Gamma_\\scrX(\\mathrm R\\bHom_\\scrOX(L_\\bullet,F^\\bullet)),\\tag{ii}\n\\end{equation}\ncoming from the similar isomorphism\n$\\Hom_\\scrOX\\simeq\\Gamma_\\scrX\\bHom_\\scrOX$. All this is standard\ncohomology formalism, valid on an arbitrary ringed topos\n$(\\scrX,\\scrOX)$, except for the possibility of computing $\\RHom$ and\n$\\RbHom$ by taking \\emph{projective resolutions of the first argument}\n(rather than injective ones of the second), which is special to the\ncase when $\\scrX=\\Ahat$, to which we'll now restrict.\n\nLet now $A$ be a fixed small category, $k$ a fixed commutative ring,\n\\scrM{} a $k$-additive category, stable under small inverse limits. We\nwant to define a total derived functor of the functor\n\\begin{equation}\n  \\label{eq:108.109}\n  (L,F)\\mapsto \\Hom_k(L,F):\\Ahatk \\times \\AhatM\\to\\scrM,\\tag{109}\n\\end{equation}\nwhich should be a functor\n\\begin{equation}\n  \\label{eq:108.110}\n  (L_\\bullet,F^\\bullet)\\mapsto \\RHom_k(L_\\bullet,F^\\bullet) :\n  \\D^-(\\Ahatk)\\times \\D^+(\\AhatM) \\to \\D^+(\\scrM),\\tag{110}\n\\end{equation}\nand similarly\n\\begin{equation}\n  \\label{eq:108.111}\n  (L_\\bullet,F^\\bullet)\\mapsto\\RbHom_k(L_\\bullet,F^\\bullet) :\n  \\D^-(\\Ahatk) \\times \\D^+(\\AhatM) \\to \\D^+(\\AhatM).\\tag{111}\n\\end{equation}\nFor this, in order for $\\D^+(\\AhatM)$ to be defined, we better assume\n\\scrM{} to be an \\emph{abelian} category, hence \\AhatM{} is abelian\ntoo. Of course, we'll write\n\\begin{equation}\n  \\label{eq:108.112}\n  \\begin{aligned}\n    \\Ext_k^i(L_\\bullet,F^\\bullet) &=\n    \\mathrm H^i(\\RHom_k(L_\\bullet,F^\\bullet)), \\\\\n    \\bExt_k^i(L_\\bullet,F^\\bullet) &=\n    \\mathrm H^i(\\RbHom_k(L_\\bullet,F^\\bullet)),\n  \\end{aligned}\\tag{112}\n\\end{equation}\nthese global and local $\\Ext^i$ may be viewed as ``external''\n$\\Ext^i$'s, as contrarily to the familiar case, the components of the\ntwo arguments $L_\\bullet$ and $K^\\bullet$ are not in the same category\n-- just as the $\\Hom_k$ in \\eqref{eq:108.109} and the corresponding\n\\begin{equation}\n  \\label{eq:108.109prime}\n  \\bHom_k:\\Ahatk\\times\\AhatM\\to\\AhatM\\tag{109'}\n\\end{equation}\nhas arguments in the two different categories \\Ahatk{} and \\AhatM.\n\nAs\\pspage{429} we don't know about the existence of enough injective\nin \\AhatM, the only way for defining the pairings \\eqref{eq:108.110},\n\\eqref{eq:108.111} is now by using projective resolutions of the first\nargument, writing\n\\begin{equation}\n  \\label{eq:108.113}\n  \\begin{aligned}\n    \\RHom_k(L_\\bullet,F^\\bullet) &=\n    \\Hom_k^{\\bullet\\bullet}(\\scrL_\\bullet,F^\\bullet), \\\\\n    \\RbHom_k(L_\\bullet,F^\\bullet) &=\n    \\bHom_k^{\\bullet\\bullet}(\\scrL_\\bullet,F^\\bullet) \n  \\end{aligned}\\tag{113}\n\\end{equation}\nwhere $\\scrL_\\bullet$ is a projective resolution of $L_\\bullet$ in\n\\Ahatk. As the latter is defined up to chain homotopy, it follows that\nfor fixed $L_\\bullet$ and $F^\\bullet$, the second members of\n\\eqref{eq:108.113} are defined up to chain homotopy, i.e., they may be\nviewed as objects in $\\mathrm K^+(\\scrM)$ and $\\mathrm K^+(\\AhatM)$\nrespectively. They are defined as such, even without assuming \\scrM{}\nto be abelian and hence $\\D^+(\\scrM)$ and $\\D^+(\\AhatM)$ to be\ndefined. When we make this assumption, in order to check that the\nformulæ \\eqref{eq:108.113} do define pairings as in \\eqref{eq:108.110}\nand \\eqref{eq:108.111}, we still have to check that for a\nquasi-isomorphism\n\\[F^\\bullet\\to (F')\\bullet\\]\nin \\AhatM, the corresponding maps between $\\RHom_k$ and $\\RbHom_k$ are\nquasi-isomorphisms too. This will follow immediately, provided we\ncheck that for fixed \\emph{projective} $L$ in \\Ahatk{} and variable\n$F$ in \\AhatM, the functors\n\\[F\\mapsto\\Hom_k(L,F)\\quad\\text{and}\\quad\nF\\mapsto\\bHom_k(L,F)\\]\nfrom \\AhatM{} to \\scrM{} and \\AhatM{} respectively are exact. Now,\nthis is clear for $\\Hom_k$ when $L$ is of the type $k^{(a)}$, hence\n$\\Hom(L,F)\\simeq F(a)$, hence it follows when $L$ is a small direct\nsum of objects $k^{(a_i)}$, hence\n\\[\\Hom_k(L,F) = \\prod_i F(a_i),\\]\nprovided we make on \\scrM{} the mild extra assumption that \\emph{a\n  small direct product of epimorphisms is again an epimorphism}. As\nany projective object of \\Ahatk{} is a direct factor of a small direct\nsum as above, the exactness result we want then follows, hence the\nlooked-for pairing \\eqref{eq:108.110}. The same argument will hold for\n$\\bHom_k$, provided we check exactness of the functors\n\\[F\\mapsto \\bHom_k(k^{(a)},F)=(b\\mapsto F(a\\times b)).\\]\nHere it seems we get into trouble when $A$ is not stable under binary\nproducts -- in this case there is little chance that the functor above\nbe exact, even when restricting to the case $\\scrM=\\Ab_k \\eqdef\\kMod$,\nhence $\\AhatM=\\Ahatk$ and $L$, $F$ have values in the same category\n(namely presheaves of $k$-modules). This may seem strange, as we know\n(and recalled above) that in this standard case there is no problem\nfor defining a\\pspage{430} pairing \\eqref{eq:108.111} $\\RbHom_k$. The\npoint here is that, whereas a reasonable $\\RbHom$ can be defined\nindeed, it \\emph{cannot} be computed in terms of a projective\nresolution of the first argument as in \\eqref{eq:108.113}; or\nequivalently, that for projective $L$ it is not necessarily true that\n\\[\\bExt_k^i(L,F)=0\\quad\\text{for $i>0$;}\\]\nthis in turn relates to the observation that, contrarily to what\nhappens for the notion of injective sheaves of modules (on an\narbitrary topos), it is not true that the property for a sheaf of\nmodules to be projective is stable under localization (even for\na constant sheaf of rings $k$ on a topos \\Ahat). Indeed, the\nlocalization of $k^{(a)}$ with respect to $A_{/b}$ (with $a$ and $b$\nin $A$) is $k^{(a')}$ where $a'$ is $a\\times b$ viewed as an object in\n$A_{/b}$, and for any sheaf of $k$-modules $F$ on $A_{/b}$ we have\n\\[\\Ext_{A_{/a}}^i(k^{(a')},F) = \\mathrm H^i(A_{/a'=a\\times b},F),\\]\nwhich need not be zero for $i>0$. If it was, this would imply that\n$a\\times b$ is $k$-acyclic (rather, that its connected components\nare), a rather strong property indeed when $a\\times b$ is not in\n$A$\\ldots\n\nThus, when $A$ is not stable under binary products, it doesn't seem\nthat there exists a pairing \\eqref{eq:108.111} as I expected, except\n(possibly) when there are enough injectives in \\AhatM{} -- a case I do\nnot wish to examine for the time being, as I am mainly interested now\nin a formalism using projective resolutions instead of injective\nones. Anyhow, for the purpose of subsuming the cohomology functor\n$\\RGamma_A$ under the $\\RHom_k$ formalism, by formula\n\\begin{equation}\n  \\label{eq:108.114}\n  \\RGamma_A(F^\\bullet) = \\RHom_k(k_A,F^\\bullet) \\simeq\n  \\Hom_k^{\\bullet\\bullet}(L_\\bullet^A,F^\\bullet),\\tag{114}\n\\end{equation}\nwhere\n\\begin{equation}\n  \\label{eq:108.115}\n  L_\\bullet^A\\to k_A\\tag{115}\n\\end{equation}\nis a projective resolution of $k_A$, it is the pairing $\\RHom_k$ and\nnot $\\RbHom_k$ which is the relevant one. Let's recall that a\nprojective resolution \\eqref{eq:108.115} is called a\n\\emph{cointegrator} (for the category $A$, with coefficients in $k$),\nas by formula \\eqref{eq:108.114} it allows indeed to express\n``cointegration'' of any \\scrM-valued presheaf or complex of such\npresheaves (with degrees bounded from below).\n\nThus, for the time being we just got the pairing $\\RHom_k$ in\n\\eqref{eq:108.110}, and the corresponding functor\n\\begin{equation}\n  \\label{eq:108.116}\n  F^\\bullet\\mapsto \\RGamma_A(F^\\bullet) : \\D^+(\\AhatM) \\to \\D^+(\\scrM),\\tag{116}\n\\end{equation}\nand\\pspage{431} not the pairing $\\RbHom_k$ in \\eqref{eq:108.111}, and\nhence no formula \\eqref{eq:108.ii} (p.\\ \\ref{p:428}) relating the two\n-- which makes me feel a little silly! I'll have to come back upon\nthis later. At present, let's dualize what we got, assuming now that\n\\scrN{} is a $k$-additive abelian category stable under small\n\\emph{direct} limits, and such that \\emph{a small direct sum of\n  monomorphisms in \\scrN{} is again a monomorphism}. We then get a\npairing\n\\begin{equation}\n  \\label{eq:108.117}\n  (F_\\bullet,L'_\\bullet) \\mapsto F_\\bullet \\Last_k L'_\\bullet :\n  \\D^-(\\AhatN)\\times\\D^-(\\Bhatk) \\to \\D^-(\\scrN),\\tag{117}\n\\end{equation}\ndefined by the formula (dual to \\eqref{eq:108.112})\n\\begin{equation}\n  \\label{eq:108.118}\n  F_\\bullet \\Last_k L'_\\bullet \\simeq F_\\bullet *_k \\scrL'_\\bullet,\\tag{118}\n\\end{equation}\nwhere in the second member $\\scrL'_\\bullet$ is a projective resolution\nof $L_\\bullet$ in \\Bhatk{} ($B=A\\op$ being of course the dual category\nof $A$), and the $*_k$ denotes the simple complex associated to the\ndouble complex obtained by applying $*_k$ componentwise. Using the\ncomposite equivalence\n\\begin{multline}\n  \\label{eq:108.119}\n  F_\\bullet\\mapsto(F_\\bullet)\\op: (\\D^-(\\AhatN))\\op\\equeq\n  \\D^+((\\AhatN)\\op)\\equeq \\D^+(\\BhatM),\\\\\n  \\text{ with $\\scrM=\\scrN\\op$,}\\tag{119}\n\\end{multline}\nwe get the tautological duality isomorphism\n\\begin{equation}\n  \\label{eq:108.120}\n  \\bigl(F_\\bullet\\Last_k L'_\\bullet)\\op \\simeq \\RHom_k(L'_\\bullet,\n  (F_\\bullet)\\op),\\tag{120} \n\\end{equation}\nwhere the expression $\\Last_k$ in the first member is relative to the\npair $(A,\\scrN)$, whereas the expression $\\RHom_k$ in the second is\nrelative to the dual pair $(B,\\scrM)$. Symmetrically, we get\n\\begin{equation}\n  \\label{eq:108.120prime}\n  \\bigl(\\RHom_k(L_\\bullet,F^\\bullet)\\bigr)\\op \\simeq L_\\bullet \\Last_k\n  (F_\\bullet)\\op,\\tag{120'} \n\\end{equation}\nwhich is essentially the inverse isomorphism of \\eqref{eq:108.120},\nbut for the pair $(B,\\scrM)$ instead of $(A,\\scrN)$.\n\nWe still should dualize the functor $\\RGamma_A$ \\eqref{eq:108.116}\n(defined by \\eqref{eq:108.114}), which we do, recalling that\n$\\Gamma_A$ is just the inverse limit functor $\\varprojlim_{A\\op}$,\nwhich is dual to the direct limit functor $\\varinjlim_{A\\op}$, thus,\n``integration'' of \\scrN-valued presheaves is just (at least morally)\nthe total left derived functor of the latter, and may be denoted by\n\\begin{equation}\n  \\label{eq:108.121}\n  \\mathrm L{\\varinjlim_{A\\op}},\\tag{121}\n\\end{equation}\nwhile using for $\\RGamma_A$ the equivalent notation, dual to\n\\eqref{eq:108.121}\n\\begin{equation}\n  \\label{eq:108.122}\n  \\mathrm R{\\varprojlim_{A\\op}} = \\RGamma_A.\\tag{122}\n\\end{equation}\nI am not wholly happy, though, with the purely algebraic flavor of\nthese notations, not really suggestive of the manifold geometric\nintuitions\\pspage{432} surrounding the familiar homology and\ncohomology notations $\\mathrm H_\\bullet$ and $\\mathrm H^\\bullet$. This\nflavor is at least partially preserved, it seems to me, in the\nnotation $\\RGamma_A$ (because of the geometric intuition tied with the\nsections functor), whereas there is not yet a familiar geometric\nnotion of a ``cosections functor''. As we would like to have the\nduality symmetry reflected as perfectly as possible in the notation, I\nam going to use the notations\n\\begin{equation}\n  \\label{eq:108.123}\n  \\left\\{\n    \\begin{aligned}\n      \\RH^\\bullet(A,F^\\bullet) &= \\mathrm\n      R{\\varprojlim_{A\\op}}(F^\\bullet)\n      \\;(\\;=\\RGamma_A(F^\\bullet))\n      : \\D^+(\\AhatM)\\to\\scrM \\\\\n      \\LH_\\bullet(A,F_\\bullet) &= \\mathrm\n      L{\\varinjlim_{A\\op}}(F_\\bullet) : \\D^-(\\AhatN)\\to\\scrN.\n    \\end{aligned}\n  \\right.\\tag{123}\n\\end{equation}\nWith these notations, the duality isomorphisms\n(\\ref{eq:108.120},\\ref{eq:108.120prime}) take the form (as announced):\n\\begin{equation}\n  \\label{eq:108.124}\n  \\left\\{\n    \\begin{aligned}\n      (\\RH^\\bullet(A,F^\\bullet))\\op &\\simeq\n      \\LH_\\bullet(B,(F^\\bullet)\\op) \\\\\n      (\\LH_\\bullet(A,F_\\bullet))\\op &\\simeq\n      \\RH^\\bullet(B,(F_\\bullet)\\op)\\quad,\n    \\end{aligned}\n  \\right.\\tag{124}\n\\end{equation}\nwhere the first members are defined in terms of cohomology resp.\\\nhomology invariants with respect to the pair $(A,\\scrM)$ resp.\\\n$(A,\\scrN)$, whereas the second members denote homology resp.\\\ncohomology invariants with respect to the dual pairs $(B,\\scrN)$\nresp.\\ $(B,\\scrM)$.\n\\begin{remarks}\n  This perfect symmetry, or rather essential identity, between\n  ``homology'' or ``integration'' and ``cohomology'' or\n  ``cointegration'', is obtained here at the price of working with\n  presheaves with values in rather general abelian categories,\n  subjected to some simple exactness properties. It should be\n  remembered moreover that for the time being, $\\RH^\\bullet$ has not\n  been defined as the total right derived functor of the sections of\n  inverse limits functor, therefore the notations \\eqref{eq:108.121}\n  and \\eqref{eq:108.122} are somewhat misleading. To feel really at\n  ease, we should still work out conditions that ensure that \\AhatM{}\n  has enough injectives and that $\\RHom_k$ can be defined also using\n  such resolutions -- in which case we'll expect too to have a\n  satisfactory formalism for the $\\RbHom_k$ functor.\n\\end{remarks}\n\n\\bigbreak\n\\presectionfill\\ondate{23.8.}\\pspage{433}\\par\n\n% 109\n\\hangsection[Review (6): A further step in linearization: coalgebra\n\\dots]{Review \\texorpdfstring{\\textup{(6)}}{(6)}: A further step in\n  linearization: coalgebra structures\n  \\texorpdfstring{$P\\to P\\otimes_k P$ in \\Cat}{P->PkP in\n    (Cat)}.}\\label{sec:109}%\nI still did a little scratchwork last night, about the question of\nexistence of enough injectives or projectives in a category\n\\[\\AhatN = \\bHom(A\\op,\\scrN),\\]\nwhere \\scrN{} is a $k$-additive abelian category. Introducing the\nsmall $k$-additive category\n\\[P=\\Add_k(A),\\]\nand remembering the canonical equivalence\n\\[\\AhatN=\\bHom(A\\op,\\scrN)\\equeq \\bHom_k(P\\op,\\scrN),\\]\nthe question just stated may be viewed as a particular case of the\nsame question for a category of the type\n\\begin{equation}\n  \\label{eq:109.125}\n  \\PampN \\eqdef \\bHom_k(P\\op,\\scrN),\\tag{125}\n\\end{equation}\nwhere now $P$ is \\emph{any} small $k$-additive category. (Compare with\nthe reflections on pages \\ref{p:403}, \\ref{p:404}.) It is immediate\nthat in \\PampN{} exist all types of (direct or inverse) limits\nwhich exist in \\scrN, and they are computed ``componentwise'' for each\nargument $a$ in $P$ -- from this follows that if \\scrN{} is abelian,\nso is \\PampN.\n\\addtocounter{propositionnum}{3}\n\\begin{propositionnum}\\label{prop:109.4}\n  Assume the $k$-additive category \\scrN{} is stable under small\n  direct limits, and is abelian, and that any object of \\scrN{} is\n  isomorphic to the quotient of a projective object. Then the same\n  holds for \\PampN. Assume moreover that any projective object $x$ of\n  \\scrN{} is $k$-flat, i.e., the functor\n  \\[U\\mapsto U\\otimes_k x : \\AbOf_k\\to\\scrN\\]\n  is exact, i.e., transform monomorphisms into monomorphisms. Then for\n  any projective object $F$ in \\PampN, the functor\n  \\[L'\\mapsto F *_k L' : Q\\supamp\\to\\scrN\\quad (\\text{where\n    $Q=P\\op$})\\]\n  is exact, i.e.\\ \\textup(as it is known to commute to small direct\n  limits\\textup), it transforms monomorphisms into monomorphisms.\n\\end{propositionnum}\n\\begin{comments}\n  Here, the operation $*_k$ (similar to a tensor product) is defined\n  as in the non-additive set-up (with \\PampN, $Q\\supamp$ being\n  replaced by \\AhatN, \\Bhatk) reviewed in section \\ref{sec:107}, and\n  follows from the canonical equivalence of categories\n  \\begin{equation}\n    \\label{eq:109.star}\n    \\PampN \\fromequ \\bHom_{k!}(Q\\supamp, \\scrN)\\tag{*}\n  \\end{equation}\n  (this\\pspage{434} is formula \\eqref{eq:105.starstar} of page\n  \\ref{p:403} with $P,\\scrN$ replaced by $Q,\\scrM$). It should be\n  noted that the assumptions made in prop.\\ \\ref{prop:109.4} are the\n  weakest possible for the conclusions to hold (for any $k$-additive\n  small category $P$), as these conclusions, in case $P =$ final\n  category, just reduce to the assumptions.\n\\end{comments}\n\nHere is the outline of a proof of prop.\\ \\ref{prop:109.4}. Using only\nstability of \\scrN{} under small direct limits (besides\n$k$-additivity) we define a canonical $k$-biadditive pairing\n\\begin{equation}\n  \\label{eq:109.126}\n  P\\supamp \\times\\scrN \\to \\PampN ,\n  \\quad\n  (L,x)\\mapsto L\\otimes x\\eqdef\n  (a\\mapsto L(a)\\otimes_k x)\\tag{126}\n\\end{equation}\n(NB\\enspace I recall that $P\\supamp$ is defined as\n\\[P\\supamp = \\bHom_{\\bZ}(P\\op,\\AbOf)\\fromequ\\bHom_k(P\\op,\\AbOf_k),\\]\nhere we interpret an object of $P\\supamp$ is a $k$-additive functor\n\\[L:P\\op\\to\\AbOf_k\\;(\\;\\eqdef\\kMod)\\quad\\text{.)}\\]\nThe relevant fact here for objects of \\PampN{} of the type $L\\otimes_k\nx$ is\n\\begin{equation}\n  \\label{eq:109.127}\n  \\begin{aligned}\n    \\Hom_\\PampN(L\\otimes_kx,F) &\\simeq \\Hom_\\scrN(x,\\Hom_k(L,F)) \\\\\n    &\\simeq \\Hom_{P\\supamp}(L, \\Hom(x,F)),\n  \\end{aligned}\\tag{127}\n\\end{equation}\nwhere in the second term,\n\\[\\Hom_k(L,F)\\in\\Ob\\scrN\\]\nis defined in a way dual to $F*_k L'$ (cf.\\ comments above), using the\nequivalence (dual to \\eqref{eq:109.star} above)\n\\begin{equation}\n  \\label{eq:109.starprime}\n  \\PampN\\simeq\\bHom_k^!((P\\supamp)\\op,\\scrN),\\tag{*'}\n\\end{equation}\nwhich is defined only, however, when \\scrN{} is stable under small\ninverse limits (hence the first isomorphism in \\eqref{eq:109.127}\nmakes sense only under this extra assumption); on the other hand, in\nthe third term in \\eqref{eq:109.127}\n\\[\\Hom(x,F) \\eqdef (a\\mapsto\\Hom_\\scrN(x,F(a))\\quad\\text{in\n  $P\\supamp$,}\\]\nand the isomorphism between the first and third term in\n\\eqref{eq:109.127} makes sense and is defined without any extra\nassumption on \\scrN.\n\nWe leave to the reader to check \\eqref{eq:109.127} (where one is\nreadily reduced to the case when $L$ is an object $a$ in $P$, using\nthe commutation of the three functors obtained\n$(P\\supamp)\\op\\to\\AbOf_k$ with small inverse limits). It follows, when\n\\scrN{} is abelian:\n\\begin{equation}\n  \\label{eq:109.128}\n  \\text{$L$ projective in $P\\supamp$, $x$ projective in \\scrN}\n  \\Rightarrow\n  \\text{$L\\otimes_kx$ proj.\\ in \\PampN.}\\tag{128}\n\\end{equation}\n\nAssume now that any object of \\scrN{} is quotient of a projective\none, and let $F$ be any object in \\PampN. Formula \\eqref{eq:109.127}\nfor $L=a$ in $P$ reduces\\pspage{435} to the down-to-earth formula\n\\begin{equation}\n  \\label{eq:109.127prime}\n  \\Hom_\\PampN(a\\otimes_kx,F)\\simeq\\Hom(x,F(a)).\\tag{127'}\n\\end{equation}\nNow, let for any $a$ in $P$\n\\[x_a\\to F(a)\\]\nbe an epimorphism in \\scrN, with $x_a$ projective. From\n\\eqref{eq:109.127prime} we get a map\n\\[a\\otimes_kx_a\\to F\\]\nin \\PampN, hence a map\n\\[\\scrF = \\bigoplus_{\\text{$a$ in $P$}} a\\otimes_kx_a \\to F,\\]\nit is easily seen that this is epimorphic (because the maps $x_a\\to\nF(a)$ are), and \\scrF{} is projective as a direct sum of projective\nobjects. This proves the first statement in prop.\\\n\\ref{prop:109.4}. For the second statement, we'll use the formula\n\\begin{equation}\n  \\label{eq:109.129}\n  (L\\otimes_k) *_k L' \\simeq (L *_k L') *_k x\\tag{129}\n\\end{equation}\nfor $L$ in $P\\supamp$, $L'$ in $Q\\supamp$, and $x$ in \\scrN{} -- for\nthe proof, we may reduce to the case when $L$ is in $P$, $L'$ in\n$Q=P\\op$, say $L=a$ and $L'=b\\op$, in which case both members identify\nwith $\\Hom_P(b,a)\\otimes_k x$. To prove that for $F$ projective,\n$L'\\mapsto F*_kL'$ takes monomorphisms into monomorphisms, using that\n$F$ is a direct factor of objects of the type $a\\otimes_k x$ with $a$\nin $P$ and $x$ in \\scrN, we are reduced to the case $F=a\\otimes_kx$,\nin which case by \\eqref{eq:109.129} the functor reduces to\n\\[L'\\mapsto L'(a)\\otimes_kx,\\]\nwhich is again exact by the assumption that any projective object in\n\\scrN{} (and hence $x$) is $k$-flat.\n\\begin{remark}\n  It is not automatic that a projective object in a $k$-additive\n  abelian category be $k$-flat -- take for instance $k=\\bZ$ and\n  $\\scrN=\\AbOf_{\\bF_p}$, where $\\bF_p$ is a finite prime field, then\n  all objects in \\scrN{} are projective, whereas only the zero objects\n  are \\bZ-flat.\n\\end{remark}\n\nWe leave to the reader to write down the dual statement of prop.\\\n\\ref{prop:109.4}, concerning injectives in a category \\PampM, where\nnow \\scrM{} is a $k$-additive abelian category stable under small\ninverse limits, and possessing sufficiently many injectives (hence the\nsame holds in \\PampM), and assuming eventually that these injectives $x$\nare ``$k$-coflat'', i.e.,\n\\[U\\mapsto\\Hom_k(U,x) : \\AbOf_k\\op\\to\\scrM\\]\nis exact (i.e., transforms monomorphisms in $\\AbOf_k$ into\nepimorphisms in\\pspage{436} \\scrM), which implies that for $F$\ninjective in $P\\supamp$, the functor\n\\[L\\mapsto\\Hom_k(L,F) : P\\supamp\\to\\scrM\\]\nis exact.\n\nTo sum up, we get the\n\\begin{corollarynum}\\label{cor:109.prop4.1}\n  Let $P$ be any small $k$-additive category, and let \\scrM{} be a\n  $k$-additive category which satisfies the following assumptions:\n  \\begin{enumerate}[label=\\alph*),font=\\normalfont]\n  \\item\\label{it:109.cor1.a}\n    \\scrM{} is abelian, and stable under small inverse limits,\n  \\item\\label{it:109.cor1.b}\n    \\scrM{} has ``sufficiently many injectives'',\n  \\item\\label{it:109.cor1.c}\n    injective objects of \\scrM{} are $k$-coflat,\n  \\item\\label{it:109.cor1.d}\n    any product \\textup(with small indexing family\\textup) of\n    epimorphisms in \\scrM{} is an epimorphism.\n  \\end{enumerate}\n  Consider the $k$-biadditive pairing\n  \\begin{equation}\n    \\label{eq:109.130}\n    (L,F)\\mapsto\\Hom_k(L,F) : P\\supamp \\times\\PampM\\to\\scrM.\\tag{130}\n  \\end{equation}\n  This pairing admits a total right derived functor\n  \\begin{equation}\n    \\label{eq:109.131}\n    (L_\\bullet,F^\\bullet)\\mapsto\\RHom_k(L_\\bullet,F^\\bullet) :\n    \\D^-(P\\supamp) \\times \\D^+(\\PampM) \\to \\D^+(\\scrM),\\tag{131}\n  \\end{equation}\n  which can be computed using either projective resolutions of\n  $L_\\bullet$, or injective resolutions of $F^\\bullet$, or both\n  simultaneously.\n\\end{corollarynum}\n\nWe have a dual statement, concerning the pairing\n\\begin{equation}\n  \\label{eq:109.130prime}\n  (F,L')\\mapsto F*_kL': \\PampN\\times Q\\supamp \\to\\scrN,\n  \\quad\\text{with $Q=P\\op$,}\\tag{130'}\n\\end{equation}\ngiving rise to a total left derived functor\n\\begin{equation}\n  \\label{eq:109.131prime}\n  (F_\\bullet,L_\\bullet') \\mapsto F_\\bullet\\Last_k L_\\bullet' :\n  \\D^-(\\PampN) \\times \\D^-(Q\\supamp) \\to \\D^-(\\scrN),\\tag{131'}\n\\end{equation}\nusing projective resolutions of either $F_\\bullet$, or $L_\\bullet'$,\nor both. Here, \\scrN{} is a $k$-additive category satisfying the\nproperties dual to \\ref{it:109.cor1.a} to \\ref{it:109.cor1.d} above,\ni.e., such that $\\scrM=\\scrN\\op$ satisfies the properties stated in\nthe corollary. We have the evident duality relations between the two\nkinds of operations $\\RHom_k$ and $\\Last_k$, embodied by the formulæ\n\\eqref{eq:108.120} and \\eqref{eq:108.120prime} of page \\ref{p:431},\nwhere the categories \\Ahatk, \\AhatM, \\AhatN, etc.\\ are replaced by\n$P\\supamp$, \\PampM, \\PampN, etc.\\ (where the etc.'s refer to\nreplacement of $A$ by $B=A\\op$ and of $P$ by $Q=P\\op$).\n\nNext question is to extend the $\\RHom_k$ formalism to a $\\RbHom_k$\nformalism (and similarly from $\\Last_k$ to $\\Loast_k$), as envisioned\nyesterday. To do so, in the wholly $k$-additive set-up we are now\nworking in, we still\\pspage{437} need (in case of $\\RbHom_k$ an\n(``interior'') tensor product structure on $P\\supamp$ (and dually for\n$\\Loast$, requiring a tensor product structure on $Q\\supamp$), so as\nto give rise to a $k$-biadditive pairing\n\\begin{equation}\n  \\label{eq:109.132}\n  (L,F)\\mapsto\\bHom_k(L,F): P\\supamp\\times\\PampM\\to\\PampM,\\tag{132}\n\\end{equation}\n(and dually,\n\\begin{equation}\n  \\label{eq:109.132prime}\n  (F,L')\\mapsto F\\oast_kL' : \\PampN\\times Q\\supamp\\to\\PampN\n  \\text{ ),}\\tag{132'}\n\\end{equation}\nfor which we want to take the total right derived functor $\\RbHom_k$\n(or dually, the total left derived functor $\\Loast_k$). As we say\nyesterday, though, taking projective resolutions of $L$ will not do\n(except in very special cases, such as $P=\\Add_k(A)$ with $A$ in\n\\Cat{} stable under binary products), because for $L$ projective in\n$P\\supamp$, the functor\n\\[F\\mapsto\\bHom_k(L,F):\\PampM\\to\\PampM\\]\nhas little chance to be exact. Taking injective resolutions of\n$F_\\bullet$, however, we expected \\emph{would} do in ``reasonable''\ncases -- here the question is whether for $F$ injective, the functor\n\\[L\\mapsto\\bHom_k(L,F) \\eqdef (a\\mapsto\\Hom_k(L\\otimes_ka,F)) :\n(P\\supamp)\\op\\to\\scrM\\]\nis exact (where $L\\otimes_ka$ denotes the given tensor product within\n$P\\supamp$), i.e., whether the functors (for $F$ in \\PampM, $a$ in\n$P$)\n\\begin{equation}\n  \\label{eq:109.starbis}\n  L\\mapsto\\Hom_k(L\\otimes_ka,F) : (P\\supamp)\\op\\to\\scrM\\tag{*}\n\\end{equation}\ntransform monomorphisms of $P\\supamp$ into epimorphisms of \\scrM. When\n\\scrM{} satisfies the conditions dual to\n\\ref{it:109.cor1.a}\\ref{it:109.cor1.b}\\ref{it:109.cor1.c} in the\ncorollary, hence $L\\mapsto\\Hom_k(L,F)$ is exact when $F$ in \\PampM{}\nis injective, exactness of \\eqref{eq:109.starbis} above will follow\nfrom exactness of\n\\[L\\mapsto L\\otimes_ka : P\\supamp\\to P\\supamp.\\]\nNow, this latter exactness holds in the case we are interesting in\nmainly, when $P=\\Add_k(A)$ and hence\n$P\\supamp\\equeq\\bHom(A\\op,\\AbOf_k)$ and when tensor product for\npresheaves on $A$ is defined as usual, componentwise -- then the\nobjects of $\\Add_k(A)=P$ correspond to $k$-flat presheaves, hence\ntensor product by these is exact. Thus:\n\\begin{corollarynum}\\label{cor:109.prop4.2}\n  Assume \\scrM{} satisfies the conditions of corollary\n  \\ref{cor:109.prop4.1} above, let $A$ be any small category and\n  $P=\\Add_k(A)$. Then the pairing\n  \\[\\bHom_k:\\Ahatk\\times\\AhatM\\to\\AhatM\\]\n  \\textup(cf.\\ \\eqref{eq:108.109prime} page \\ref{p:428}\\textup) admits\n  a total right derived functor $\\RbHom_k$\n  \\eqref{eq:108.111},\\pspage{438} which may be computed using\n  injective resolutions of the second argument $F^\\bullet$ in\n  $\\RbHom_k(L_\\bullet,F^\\bullet)$ \\textup(but not, in general, by\n  using projective resolutions of $L_\\bullet$\\textup), i.e.,\n  \\begin{equation}\n    \\label{eq:109.133}\n    \\RbHom_k(L_\\bullet,F^\\bullet) \\simeq\n    \\bHom_k^{\\bullet\\bullet}(L_\\bullet,\\scrF^\\bullet),\\tag{133}\n  \\end{equation}\n  where $\\scrF^\\bullet$ is an injective resolution of $F^\\bullet$\n  \\textup(i.e., a complex in \\AhatM{} with degrees bounded from below\n  and injective components, endowed with a quasi-isomorphism\n  $F^\\bullet\\simeq\\scrF^\\bullet$\\textup).\n\\end{corollarynum}\n\nApplying now $\\RGamma_A$ to both members of \\eqref{eq:109.133}, and\nusing the similar isomorphism for $\\RHom_k$ (valid by cor.\\\n\\ref{cor:109.prop4.2}, we get the familiar formula\n\\begin{equation}\n  \\label{eq:109.134}\n  \\RHom_k(L_\\bullet,F^\\bullet)\\simeq\\RH^\\bullet(\\RbHom_k(L_\\bullet,F^\\bullet)),\\tag{134}\n\\end{equation}\n(where in accordance with \\eqref{eq:108.124}, we wrote $\\RH^\\bullet$\ninstead of $\\RGamma_A$), where however $F^\\bullet$ is now a complex of\npresheaves with values in a $k$-additive category \\scrM{} (satisfying\nthe conditions dual to \\ref{it:109.cor1.a} to \\ref{it:109.cor1.d} in\ncor.\\ \\ref{cor:109.prop4.1}), not just a presheaf of $k$-modules.\n\nReplacing \\scrM{} by a category \\scrN{} satisfying the assumptions of\ncor.\\ \\ref{cor:109.prop4.1}, we get likewise a total left derived\nfunctor\n\\begin{equation}\n  \\label{eq:109.135}\n  (F_\\bullet,L_\\bullet')\\mapsto F\\Loast_k L_\\bullet' : \\D^-(\\AhatN)\n  \\times \\D^-(\\Bhatk) \\to \\D^-(\\AhatN),\\tag{135}\n\\end{equation}\nwhich can be defined using projective resolutions of the first\nargument $F_\\bullet$ (but not by using projective resolutions of\n$L_\\bullet'$), giving rise to the isomorphism (dual to\n\\eqref{eq:109.134})\n\\begin{equation}\n  \\label{eq:109.134prime}\n  F_\\bullet \\Last_k L_\\bullet' \\simeq \\LH_\\bullet(F_\\bullet \\Loast_k\n  L_\\bullet'). \\tag{134'}\n\\end{equation}\nThe duality relationship between $\\RbHom_k$ and $\\Loast_k$ can be\nexpressed by two obvious formulæ, similar to \\eqref{eq:108.120} and\n\\eqref{eq:108.120prime} for $\\RHom_k$ and $\\Last_k$, which we leave to\nthe reader.\n\n\\begin{remarks}\n  \\namedlabel{rem:109.1}{1)}\\enspace If we want to consider\n  ``multiplicative structure'' in the purely ``$k$-linear'' set-up,\n  where the data is a small $k$-additive category $P$, rather than a\n  small category $A$ (giving rise to $P=\\Add_k(A)$), and corresponding\n  cohomology and homology operations $\\RbHom_k$ and $\\Loast_k$, not\n  only $\\RHom_k$ and $\\Last_k$, the natural thing to do, it seems, is\n  to introduce a ``\\emph{diagonal map}''\n  \\begin{equation}\n    \\label{eq:109.starbisbis}\n    P \\to P\\otimes_k P,\\tag{*}\n  \\end{equation}\n  where the tensor product in the second member can be defined in a\n  rather evident way (as solution of the obvious $2$-universal problem\n  in terms of $k$-biadditive functors on $P\\times P$), which will give\n  rise in the ``usual'' way to a tensor product operation in both\n  $P\\supamp$ and $Q\\supamp$ (where\\pspage{439} $Q=P\\op$). We'll come\n  back upon this later, I expect. This structure\n  \\eqref{eq:109.starbisbis} will be the $k$-linear analogon of the\n  usual diagonal map\n  \\begin{equation}\n    \\label{eq:109.starstar}\n    A\\to A\\times A\\tag{**}\n  \\end{equation}\n  for a small category $A$, giving rise by $k$-linearization to\n  \\[\\Add_k(A)\\to\\Add_k(A\\times A)\\equeq \\Add_k(A)\\otimes_k\\Add_k(A),\\]\n  namely a structure of type \\eqref{eq:109.starbisbis}. It just\n  occurred to me, through the reflections of these last days, that the\n  ``coalgebra structure'' \\eqref{eq:109.starbisbis} may well turn out\n  (taking $k=\\bZ$) to be the more sophisticated structure than a usual\n  coalgebra structure (cf.\\ p.\\ \\ref{p:339} \\eqref{eq:94.27}), needed\n  in order to grasp ``in linear terms'' the notion of a homotopy type,\n  possibly under restrictions such as $1$-connectedness, as pondered\n  about in section \\ref{sec:94}. This looks at any rate a more\n  ``natural'' object than the De~Rham complex with divided powers,\n  referred to in loc.\\ cit., and is more evidently adapted to our\n  point of view of using small categories as models for homotopy\n  types. The greater sophistication, in comparison to De~Rham type\n  complexes, lies in this, that here the objects serving as models\n  (whether small categories, or small additive categories endowed with\n  a diagonal map) are objects in a \\emph{$2$-category}, whereas\n  De~Rham complexes and the like are just objects in ordinary\n  categories, without any question of taking ``maps between\n  maps''. This feature implies, ``as usual'' (or in duality rather to\n  familiar situations with tensor product functors\\ldots) that the\n  (anti)commutative and associative \\emph{axioms} familiar from linear\n  algebra (in the case of usual $k$-algebras or $k$-coalgebras),\n  should be replaced by commutativity and associativity \\emph{data},\n  namely given isomorphisms (not identities) between two natural\n  functors\n  \\[P\\to P\\otimes_k P, \\quad P\\to P\\otimes_k P \\otimes_k P\\]\n  deduced from \\eqref{eq:109.starbisbis}. The axioms now will be more\n  sophisticated, they will express ``coherence conditions'' on these\n  data -- one place maybe where this is developed somewhat, in the\n  context of diagonal maps \\eqref{eq:109.starbisbis}, might be\n  Saavedra's thesis.\\scrcomment{\\textcite{Saavedra1972}; see also in\n    particular \\textcite{DeligneMilne1982,Deligne1990,Deligne2002}}\n  (The more familiar case, when starting with a tensor product\n  operation on a category, together with associativity and/or\n  commutativity data, has been done with care by various\n  mathematicians, including Mac~Lane, Bénabou, Mme~Sinh Hoang Xuan,\n  and presumably it should be enough to ``reverse arrows'' in order to\n  get ``the'' natural set of coherence axioms for a diagonal map\n  \\eqref{eq:109.starbisbis}). The ``intriguing feature'' with the\n  would-be De~Rham models for homotopy types (cf.\\ p.\\ \\ref{p:341},\n  \\ref{p:342}), namely that the latter make sense over any\\pspage{440}\n  commutative ground ring $k$, not only \\bZ, with corresponding notion\n  of ring extension $k\\to k'$, carries over to structures of the type\n  \\eqref{eq:109.starbisbis}. Indeed, for any $k$-additive category\n  $P$, it is easy to define a $k'$-additive category\n  \\[P\\otimes_kk',\\quad \\\n  \\text{for given homomorphism $k\\to k'$,}\\]\n  for instance as the solution of the obvious $2$-universal problem\n  corresponding to mapping $P$ $k$-additively into $k'$-additive\n  categories, or more evidently by taking the same objects as for $P$,\n  but with\n  \\[\\Hom_{P'}(a,b) = \\Hom_P(a,b)\\otimes_k k'.\\]\n  Thus, any ``coalgebra structure in \\Cat'' \\eqref{eq:109.starbisbis}\n  over the ground ring $k$, gives rise to a similar structure over\n  ground ring $k'$.\n\n  Of course, among the relevant axioms for the diagonal functor\n  \\eqref{eq:109.starbisbis}, is the existence of unit objects in\n  $P\\supamp$ and $Q\\supamp$, which may be viewed equally as\n  $k$-additive functors (defined up to unique isomorphism)\n  \\[P\\op\\to\\AbOf_k, \\quad P\\to\\AbOf_k,\\]\n  playing the role I would think of ``augmentation'' and\n  ``coaugmentation'' in the more familiar set-up of ordinary\n  coalgebras. Denoting these objects by $k_P$ and $k_Q$ respectively\n  (in analogy to the constant presheaves $k_A$ and $k_B$ on $A$ and\n  $B$), $\\RHom(k_P,{-})$ now allows expression of cohomology or\n  cointegration, and ${-}\\Last_k(k_Q)$ allows expression of homology\n  or integration (for complexes in \\PampM{} say). ``Constant\n  coefficients'' on $P$, i.e., in $P\\supamp$ may now be defined, as\n  objects in $P\\supamp$ of the type\n  \\[U\\otimes_k k_P,\\]\n  where $U$ is in $\\AbOf_k$, i.e., is any $k$-module, and hence we get\n  homology and cohomology invariants with coefficients in any such $U$\n  (or complexes of such), and surely too cup and cap products\\ldots\n  Also, quasi-isomorphisms of structure \\eqref{eq:109.starbisbis}\n  (with units) can now be defined in an evident way, hence a derived\n  category which merits to be understood, when $k=\\bZ$, in terms of\n  the homotopy category \\Hot. I wouldn't expect of course that for any\n  small category $A$, the abelianization $\\Add(A)$ together with its\n  diagonal map allows to recover the homotopy type, unless $A$ is\n  $1$-connected. As was the case visibly for De~Rham complexes, if we\n  hope to recover general homotopy types (not only $1$-connected\n  ones), we should work with slightly more sophisticated structures\n  still,\\pspage{441} involving a group (or better still, a groupoid)\n  and an operation of it on a structure of type\n  \\eqref{eq:109.starbisbis} (embodying a universal covering\\ldots).\n\n  Here I am getting, though, into thin air again, and I don't expect\n  I'll ponder much more in this direction and see what comes out. The\n  striking fact, however, here, is that quite unexpectedly, we get\n  further hold and food for this thin-air intuition (which came up\n  first in relation to De~Rham structures with divided powers), that\n  there may be a reasonable (and essentially just one such) notion of\n  a ``homotopy type over the ground ring $k$'' for any commutative\n  ring $k$, reducing for $k=\\bZ$ to usual homotopy types, and giving\n  rise to base change functors\n  \\[\\HotOf(k)\\to\\HotOf(k')\\]\n  for any ring homomorphism $k\\to k'$. And I wonder whether this might\n  not come out in some very simplistic way, in the general spirit of\n  our ``modelizing story'', without having to work out in full a\n  description of homotopy types by such sophisticated models as\n  De~Rham complexes with divided powers, or coalgebra structures in\n  \\Cat, and looking up maybe the relations between these. (How by all\n  means hope to recover a De~Rham structure from a stupid structure\n  \\eqref{eq:109.starbisbis}???)\n  \n  \\namedlabel{rem:109.2}{2)}\\enspace The condition \\ref{it:109.cor1.d}\n  in corollary \\ref{cor:109.prop4.1} is needed in order to ensure that\n  a derived functor $\\RHom_k(L_\\bullet,F^\\bullet)$ may be defined\n  using \\emph{projective} resolutions of $L_\\bullet$, whereas\n  conditions \\ref{it:109.cor1.b}, \\ref{it:109.cor1.c} ensure that a\n  functor $\\RHom_k$ may be defined using \\emph{injective} resolutions\n  of $F^\\bullet$. It is a well-known standard fact of homological\n  algebra that in case both methods work (namely here, when all four\n  assumptions are satisfied) that the two methods yield the same\n  result, which may equally be described by resolving simultaneously\n  the two arguments. (NB\\enspace condition \\ref{it:109.cor1.a} is\n  needed anyhow for $\\Hom_k$ to be defined and for \\PampM{} being an\n  abelian category, which allows to define $\\D^+(\\PampM)$.) Our\n  preference goes to the first method, which in case $P=\\Add_k(A)$ and\n  $L=k_A$, conduces to computation of cohomology\n  $\\RGamma_A(F^\\bullet)$ in terms of a ``cointegrator'' $L_\\bullet^A$\n  on $A$. However, when it comes to introducing the variant\n  $\\RbHom_k$, this method breaks down, as we saw, it is the other one\n  which works. We thus get a satisfactory formalism of $\\RHom_k$ and\n  $\\RbHom_k$ (including formula \\eqref{eq:109.134} relating them via\n  $\\RH^\\bullet$) using only assumptions\n  \\ref{it:109.cor1.a}\\ref{it:109.cor1.b}\\ref{it:109.cor1.c}. \n\n  \\namedlabel{rem:109.3}{3)}\\enspace If we want to extend the\n  $\\RbHom_k$ formalism to the set-up when the data $A$ is replaced by\n  a $k$-additive category $P$ endowed with a diagonal map as in remark\n  \\ref{rem:109.1}, the proof on page \\ref{p:437} shows that what is\n  needed\\pspage{442} is exactness of the functor $L\\mapsto L\\otimes a$\n  from $P\\supamp$ to $P\\supamp$, for any $a$ in $P$ -- which is a\n  ``flatness'' condition on $a$. It is easily checked that his\n  condition is satisfied provided $\\Hom_P(b,a)$ is a flat $k$-module,\n  for any $b$ in $P$ (more generally, an object $M$ in $P\\supamp$ is\n  flat for the tensor product structure in $P\\supamp$, provided $M(b)$\n  is flat for any $b$ in $P$). Thus, there will be a satisfactory\n  $\\RbHom_k$ theory provided the $k$-modules $\\Hom_P(b,a)$, for $a,b$\n  in $P$, are $k$-flat. It is immediately checked that this also means\n  that any projective object $L$ in $P\\supamp$ is ``$k$-flat'' (with\n  respect to external tensor product $U\\mapsto U\\otimes_k L :\n  \\AbOf_k\\to P\\supamp$, as in prop.\\ \\ref{prop:109.4}), or\n  equivalently still, that this holds when $L$ is any object $a$ in\n  $P$. In case $P=\\Add_k(A)$, when any object of $P$ is a finite sum\n  of objects $k^{(x)}$ with $x$ in $A$, the modules $\\Hom(b,a)$ for\n  $b,a$ in $L$ are finite sums of modules of the type\n  $\\Hom(k^{(y)},k^{(x)})=k^{(\\Hom(y,x))}$, and hence are projective,\n  not only flat. It would seem that in the general case of $P$ endowed\n  with a diagonal map, the ``natural'' assumption to make in order to\n  have everything come out just as nicely as when $P$ comes from an\n  $A$, is that the $k$-modules $\\Hom_P(b,a)$ (for $a,b$ in $P$) should\n  be projective, not only flat. Flatness however seems to be all that\n  is needed in order to ensure that when $L$ in $P\\supamp$ is\n  projective (hence $L(a)$ is flat for any $a$ in $P$) and $F$ in\n  \\PampM{} is injective, then the objects $\\Hom_k(L,F)$ and\n  $\\bHom_k(L,F)$ in \\scrM{} and \\PampM{} respectively are\n  injective. This implies that for a $k$-additive functor\n  \\[u:\\scrM\\to\\scrM'\\]\n  between categories \\scrM, $\\scrM'$ satisfying the assumptions of\n  cor.\\ \\ref{cor:109.prop4.1}, and $u$ commuting moreover to small\n  inverse limits (and hence to formation of $\\Hom_k(L,F)$), we get a\n  canonical isomorphism\n  \\begin{equation}\n    \\label{eq:109.136}\n    \\mathrm R u (\\RHom_k(L_\\bullet,F^\\bullet)) \\simeq\n    \\RHom_k(L_\\bullet,\\mathrm Ru^P(F^\\bullet)),\\tag{136}\n  \\end{equation}\n  where\n  \\[u^P:\\PampM\\to P\\supamp_{\\scrM'}\\]\n  denotes the extension of $u$, and $\\mathrm Ru$, $\\mathrm Ru^P$ are\n  the right derived functors. When $u$ is exact, we may replace\n  $\\mathrm Ru$, $\\mathrm Ru^P$ by $u$, $u^P$ (applied componentwise to\n  complexes, without any need to take an injective resolution\n  first). There is a formula as \\eqref{eq:109.136} with $\\RHom_k$\n  replaced by $\\RbHom_k$, which I skip, as well as the dual formulas.\n\\end{remarks}\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: \"main.tex\"\n%%% End:\n", "meta": {"hexsha": "cf9677daca2935f53954681388042ab14dcf0406", "size": 401872, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ps5.tex", "max_stars_repo_name": "agrothendieck/PursuingStacks", "max_stars_repo_head_hexsha": "95fe0fce58a07f842db5087dd18aca5fcb349c37", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 79, "max_stars_repo_stars_event_min_datetime": "2015-08-09T02:22:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T03:57:34.000Z", "max_issues_repo_path": "ps5.tex", "max_issues_repo_name": "ryankeleti/PursuingStacks", "max_issues_repo_head_hexsha": "95fe0fce58a07f842db5087dd18aca5fcb349c37", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-06-03T07:45:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-20T09:50:29.000Z", "max_forks_repo_path": "ps5.tex", "max_forks_repo_name": "ryankeleti/PursuingStacks", "max_forks_repo_head_hexsha": "95fe0fce58a07f842db5087dd18aca5fcb349c37", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 41, "max_forks_repo_forks_event_min_datetime": "2015-08-01T04:29:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T03:57:36.000Z", "avg_line_length": 49.8848063555, "max_line_length": 97, "alphanum_fraction": 0.7310984592, "num_tokens": 124829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.33565989834193494}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                                                                              %\n%   PAW   - Reference Manual -- LaTeX Source                                   %\n%                                                                              %\n%   Chapter 5: Vectors                                                         %\n%                                                                              %\n%   EPS file      : none\n%                                                                              %\n%   Editor: Michel Goossens / IT-AS                                            %\n%   Last Mod.: 29 July 1998 Olivier Couet                                      %\n%                                                                              %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\chapter{Vectors}\n\\label{sec:H1PVECT}\n\\index{vector}\n\\index{array}\n\\index{SIGMA}\n\\index{COMIS}\n \nVectors are named arrays of numerical data, memory resident, which can be \ncreated during a session, loaded from HBOOK objects, typed in by hand, read \nfrom disk files, operated upon using the full functionality of SIGMA or COMIS.\nVectors can be used to produce graphics output, and, if necessary, stored away\non disk files for further usage. Vectors provide a very convenient mechanism to \ntransport numerical information between different PAW objects, and to \nmanipulate mathematically their content. At the end of an interactive session,\nthey are lost, unless previously saved onto disk files.\n \nVectors can have up to 3 dimensions (in fact they are ``arrays'',\ncalled ``vectors'' for historical reasons).  They can be handled \nby using \\PAWcind{VECTOR}\\texttt{/... } commands.\n \nSimple arithmetic operations can be applied to vectors.\nIn addition, as SIGMA is part of PAW,\npowerful array manipulation operations are available,\nthrough the SIGMA, \\texttt{\\$SIGMA}\nand \\Cind{APPLICATION} \\texttt{SIGMA} commands \n(see section \\ref{sec:H2SIGMA} on page~\\pageref{sec:H2SIGMA}).\n \n\\section{Vector creation and filling}\n\\index{create!vector}\n\\index{vector!create}\n\\index{fill!vector}\n\\index{vector!fill}\n\nA vector is {\\bf created} either by the {\\bf PAW command}\n\\texttt{VECTOR/CREATE}, by the {\\bf SIGMA function} \\PAWcind{ARRAY}.\nor by the {\\bf COMIS statement} \\PAWcind{VECTOR}.\n\n\\subsection*{Example of vector creation}\n\\begin{alltt}\n\\Ucom{VECTOR/CREATE  X(100)}      will create a 100-components vector, values = 0.\n\\Ucom{SIGMA X=ARRAY(100,1#100)}   will create a 100-components vector and assign\n                            to each element the values 1,2,...100\n\\Ucom{VECTOR X(100)}              in a COMIS routine creates a 100-components vector\n                           and initialises each element to zero\n\\end{alltt}\n \nOnce the vector is created, it can be manipulated\nusing the following PAW commands:\n\n\\begin{DLtt}{12345678901234567890}\n\\item[\\texttt{VECTOR/INPUT} vlist]\n       Input from the terminal values into the vector \n       elements specified by the list \\texttt{vlist}.\n\\item[\\texttt{VECTOR/READ} vlist]\n       Values can be {\\bf read in} from a file\n       into the vector elements specified by the list vlist.\n\\item[\\texttt{VECTOR/COPY} v1 v2]\n       Values in \\texttt{v1} are copied into \\texttt{v2}.\n\\item[\\texttt{VECTOR/WRITE} vlist]\n       Values in the vector elements specified by the\n       list vlist can be {\\bf saved} on a file.\n\\item[\\texttt{VECTOR/PRINT} vlist]\n       Values of the vector elements specified in \\texttt{vlist} will be\n       {\\bf printed} on the terminal.\n\\item[\\texttt{VECTOR/LIST}]\n       A {\\bf list} of existing vectors and their\n       {\\bf characteristics} is printed on the terminal.\n\\item[\\texttt{VECTOR/DELETE}]\n       Allows global or selective deletion of vectors.\n\\end{DLtt}\n\n\\section{Vector addressing}\n\\index{vector!address}\n\\index{addressing of vectors}\n\nIndexing of vectors is possible. The \nindexing permitted in PAW can be considered as a superset\nof that permitted by FORTRAN.\n\n\\subsection*{Example of vector indices}\n\\begin{alltt}\n{\\bf Vec}            for all elements\n{\\bf Vec(13)}        for element 13\n{\\bf Vec(12:)}       for elements 12 up to the last\n{\\bf Vec(:10)}       for elements 1 to 10\n{\\bf Vec(5:8)}       for elements 5 to 8\n\\end{alltt}\n\nSub-elements of the two-dimensional vector \\texttt{Vec(3,100)}\n(3 columns by 100 rows) may be addressed by:\n\n\\subsection*{Using two-dimensional vectors}\n\\begin{alltt}\n{\\bf Vec(2,5:8)}     for elements 5 to 8 in column 2\n{\\bf Vec(2:3,5:8)}   for elements 5 to 8 columns 2 to 3\n{\\bf Vec(2,5)}       for element 5 in column 2\n{\\bf Vec(:,3)}       for all elements in row 3\n{\\bf Vec(2)}         for all elements in the 2-nd column (SPECIAL CASE)\n\\end{alltt}\n\n\\section{Vector arithmetic operations}\n\\index{vector!arithmetic}\n\\index{operation on vectors}\n \nA number of basic vector arithmetic operations is available:\n\n\\begin{DLtt}{1234567890123456789012}\n\\item[VBIAS     v1 bias v2]   \\texttt{v2(I) = bias + v1(I)}\n\\item[VSCALE    v1 scale v2]  \\texttt{v2(I) = scale * v1(I)}\n\\item[VADD      v1 v2 v3]     \\texttt{v3(I) = v1(I) + v2(I)}\n\\item[VMULTI    v1 v2 v3]     \\texttt{v3(I) = v1(I) * v2(I)}\n\\item[VSUBTR    v1 v2 v3]     \\texttt{v3(I) = v1(I) - v2(I)}\n\\item[VDIVID    v1 v2 v3]     \\texttt{v3(I) = v1(I) / v2(I), if v2(I)<>0}\n\\end{DLtt}\n \nIn all operations only the minimum vector length is considered,\ni.e. an operation between a vector \\texttt{A} of dimension 10 and a vector \n\\texttt{B} of dimension 5 will involve the first 5 elements for both vectors.\nIf the destination vector does not exist,\nit is created with the same length as specified in the source vector.\n\n\\section{Vector arithmetic operations using SIGMA}\n\\index{SIGMA}\n\nA more complete and convenient mechanism for the mathematical\nmanipulation of entire vectors is provided by SIGMA.\nSIGMA-generated arrays are stored as\nPAW vectors and therefore are accessible\nto PAW commands, and PAW vectors are accessible to SIGMA.\nThe facilities available via SIGMA are described in the next chapter.\n\n\\section{Using vectors in a COMIS routine}\n\\index{COMIS}\n\\index{KUIP!vector}\n \nThe declaration \\Ucom{VECTOR vector\\_name}\nmay be used inside a COMIS routine to address a PAW vector.\nIf the vector does not exist, it is created with the specifications\nprovided by the declared dimension.\n\n\\section{Usage of vectors with other PAW objects}\n \nVectors can be used to transport\nnumerical information between different PAW objects, and\nto manipulate mathematically their content.\n\n\\begin{DLtt}{1234567890123456789012345678901}\n\\item[\\texttt{VECTOR/HFILL} VNAME ID]\n     Each vector element of \\texttt{VNAME} \n     is used to fill the existing \\mbox{histogram \\texttt{ID}.}\n\\item[\\texttt{HISTOGRAM/GET_VECTOR/CONTENT}]\n     Provides an interface between vectors and histograms.\n\\item[\\texttt{HISTOGRAM/PUT_VECTOR/CONTENT}]\n     Provides an interface between histograms and vectors.\n\\end{DLtt}\n\n\\section{Graphical output of vectors}\n\\index{graphical!output}\n\n\\begin{DLtt}{123456789012345678901234}\n\\item[\\texttt{VECTOR/DRAW} VNAME]\n     Interprets the content of the vector \\texttt{VNAME}\n     as a histogram contents and draw a {\\bf graph}.\n\\item[\\texttt{VECTOR/PLOT} VNAME]\n     Vector elements are considered as individual values\n     to be entered into a histogram and a graph is produced.\n     If \\texttt{VNAME} is the name of a vector, then each vector element of\n     \\texttt{VNAME} is used to fill a histogram which is \n     automatically booked with 100 channels and plotted.\n     If \\texttt{VNAME} has the form \\texttt{VNAME1\\%VNAME2}\n     then a scatter-plot of vector \\texttt{VNAME1}\n     versus \\texttt{VNAME2} is plotted.\n\\end{DLtt}\n \n%See section~\\ref{sec:vectordrawplot}\n%in the tutorial section for an\n%explanation of the difference between \\texttt{VECTOR/DRAW}\n%and \\texttt{VECTOR/PLOT}.\n \nA number of graphical primitives are available in PAW.\nThose directly related to the graphical output of vectors are:\n\n\\begin{DLtt}{123456789012345678901234}\n\\Inref{GRAPH}\n\\item[GRAPH N X Y]\n     Draw a curve through a set of points defined by arrays \n     \\texttt{X} and \\texttt{Y}.\n\\Inref{HIST}\n\\item[HIST  N X Y]\n     Draw an histogram defined by arrays \\texttt{X} and \\texttt{Y}.\n\\Inref{PIE}\n\\item[PIE   X0 Y0 RAD N VAL]\n     Draw a pie chart, of \\texttt{N} slices, \n     with size of slices given in \\texttt{VAL},\n     of a radius \\texttt{RAD}, centered at \\texttt{X0}, \\texttt{Y0}.\n\\end{DLtt}\n\n\\section{Fitting the contents of a vector}\n\\index{fit!vector}\n \nA user defined (and parameter dependent) function\ncan be fitted to the points defined by the two vectors \\texttt{X}\nand \\texttt{Y} and the vector of associated errors \\texttt{EY}.\nThe general syntax of the command to fit vectors is:\n\n\\texttt{VECTOR/FIT} \\texttt{x y ey func [ chopt np par step pmin pmax errpar ]}\n\nFor more information have a look at the online help of this command in PAW.\n", "meta": {"hexsha": "8eeda9ff7e8fa84329459d57404955bff3e77226", "size": 8955, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paw/pawch5.tex", "max_stars_repo_name": "berghaus/cernlib-docs", "max_stars_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-24T12:30:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-24T12:30:01.000Z", "max_issues_repo_path": "paw/pawch5.tex", "max_issues_repo_name": "berghaus/cernlib-docs", "max_issues_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paw/pawch5.tex", "max_forks_repo_name": "berghaus/cernlib-docs", "max_forks_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3378378378, "max_line_length": 84, "alphanum_fraction": 0.6638749302, "num_tokens": 2391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.33565988981256606}}
{"text": "% !TEX root = ../zeth-protocol-specification.tex\n\n\\chapter{Security proofs of Blake2}\\label{appendix:blake}\n\nThis appendix proves the collision resistance, PRF-ness, binding and hiding properties of the \\blake{2}{} hash function in the Weakly Ideal Cipher model (WICM, see~\\cite{luykx2016security}). The proofs use definitions and results of Luykx et al.~\\cite{luykx2016security}, regarding the indifferentiability of \\blake{2}{} and a random oracle in the Weakly Ideal Cipher Model (WICM). In the following, we assume that the optimization of \\blake{2}{} for 8- to 32-bit platforms is as secure as \\blake{2}{} as described in~\\cite{luykx2016security}.\n\n\\section{Security model of Blake2}\\label{appendix:blake:secmod}\n\nThe security analysis treats \\blake{2}{} as hash function built on top of a block-cipher-based compression function in the WICM (which derives from the Ideal Cipher Model). In this section, we present the WICM and prove that \\blake{2}{} is a collision resistant PRF, and thus a commitment scheme.\n\n\\subsection{Weakly Ideal Cipher Model}\\label{appendix:blake:secmod:WICM}\n\nThe research community believes that Blake’s underlying block cipher has no known weaknesses and could reasonably be modeled as an ideal cipher~\\cite[Section 2.1]{luykx2016security}. However, \\blake{2}{} admits weak keys with a specific structure~\\cite[Section 2.1]{luykx2016security}. \\blake{2}{} is therefore more appropriately analysed in the WICM, which is an extension of the Ideal Cipher Model that represents a block cipher as a set of independent random permutations~\\cite{holenstein2011equivalence}. The WICM may also be viewed as a specialization for \\blake{2}{} of the Weak Cipher Model~\\cite{mennink2015impact}, which aims to be realistic by modeling particular characteristics, invariants or properties a block cipher may have.\n\nA number of definitions in what follows are quoted directly from Luykx et al.~\\cite{luykx2016security}.\n\n\\paragraph{The Weakly Ideal Cipher Model.}\n\nLet \\weakSet and \\strongSet be the following partition of $\\BB^{2 \\cdot \\ol}$ into weak and strong sets, where $w$ is the word length ($16 \\cdot w = 2 \\cdot \\ol$):\n\\begin{align*}\n    \\weakSet &= \\smallset{aaaabbbbccccdddd \\in \\BB^{2 \\cdot \\ol}\\ |\\ a, b, c, d \\in \\BB^w} \\\\\n    \\strongSet &= \\BB^{2 \\cdot \\ol} \\setminus \\weakSet\n\\end{align*}\n\nLet $\\blockSet(2 \\cdot \\ol, 2 \\cdot \\ol)$ denote the set of all block ciphers $\\Enc{}: \\BB^{2 \\cdot \\ol}\\times \\BB^{2 \\cdot \\ol} \\rightarrow \\BB^{2 \\cdot \\ol}$. Define $\\blockSet^{*}(2 \\cdot \\ol, 2 \\cdot \\ol)$ as the set of all block ciphers $\\Enc \\in \\blockSet(2 \\cdot \\ol, 2 \\cdot \\ol)$ with the additional restriction that $\\Enc(k_w,\\cdot)$ is \\weakSet- and \\strongSet-subspace invariant for all keys $k_w \\in \\keyspace_{weak}$. That is, inputs in \\weakSet map to \\weakSet, and likewise for \\strongSet. Here, $\\keyspace_{weak}$ is the set of weak keys, defined as\n\\[\n    \\keyspace_{weak} = \\smallset{ \\key = kkkkkkkkkkkkkkkk \\in \\BB^{2 \\cdot \\ol}\\ |\\ k \\in \\BB^w }.\n\\]\nA random $ \\Enc \\sample \\blockSet^{*}(2 \\cdot \\ol, 2 \\cdot \\ol)$ can now be modeled as follows:\n\\begin{itemize}\n    \\item on input of $(\\key, x) \\in \\keyspace_{weak} \\times \\weakSet$, $\\Enc$ generates its response $y$ randomly from \\weakSet up to repetition;\n    \\item on input of $(\\key, x) \\in \\keyspace_{weak} \\times \\strongSet$, $\\Enc$ generates its response $y$ randomly from \\strongSet up to repetition.\n\\end{itemize}\n\nFor key values $\\key \\in \\BB^{2 \\cdot \\ol} \\setminus \\keyspace_{weak}$, $\\Enc$ behaves like an ideal cipher: it either outputs a new random value or if the key-message-image tuple has already been queried the tuple's image. The case of inverse queries is analogous.\n\n\n\\blake{2C}{} is defined over the following domains and codomain:\n\\[\n    \\blake{2C}{}: \\blockSet^{*}(2 \\cdot \\ol, 2 \\cdot \\ol) \\times \\BB^{\\ol} \\times \\BB^{2 \\cdot \\ol} \\times \\BB^{\\ol/4} \\times \\BB^{\\ol/4} \\to \\BB^{\\ol}\n\\]\nWe write $\\blake{2C}{}_\\Enc(h, \\msg, t, f)$ for the output of the \\blake{2}{} compression function, defined over encryption scheme $\\Enc$ on inputs $h$, $\\msg$, $t$ and $f$. The compression function, in particular, computes the state $x = (h \\concat \\pad{0}{\\ol/2} \\concat t \\concat f) \\xor (\\pad{0}{\\ol} \\concat \\blakeIV{})$ for some $\\blakeIV{}$. It then encrypts $x$ under $\\msg$ (where $\\msg$ is treated as a key for the encryption) and splits $\\Enc(\\msg, x)$ in two same size variables, the left part $l_\\Enc$ and right part $r_\\Enc$. It finally outputs $l_\\Enc \\xor r_\\Enc \\xor h$.\\linebreak\n\n\\zeth{} uses the \\blake{2}{} compression function with a fixed encryption scheme $\\Enc^*$ based on \\chacha{} stream cipher~\\cite{bernstein2008chacha}. Thus, we write $\\blake{2C}{h, \\msg, t, f} = \\blake{2C}{}_{\\Enc^*}(h, \\msg, t, f)$.\n%\n% \\blake{2}{} is defined over the following domain and codomain:\n% \\[\n%     \\blake{2}{}: \\BB^{\\leq 2 \\cdot \\ol} \\times \\BB^{*} \\to \\BB^{\\ol}\n% \\]\n\n\\paragraph{Indifferentiability.}\n\nOne way to measure the extent to which a certain cryptographic function behaves like a random function is via the indistinguishability framework  where a distinguisher is given oracle access to either the cryptographic function or the random function with the goal of determining which one it has access to.\n\n\\begin{definition}\\label{appendix:blake:secmod:WICM:indiff}\n    Let $\\primC$ be a construction with oracle access to an ideal primitive $\\primP$. Let $\\primR$ be an ideal primitive with the same domain and codomain as $\\primC$. Let $\\simulator$ be a simulator with the same domain and codomain as $\\primP$ with oracle access to $\\primR$, and let $\\distinguisher$ be a $\\ppt$ distinguisher. The indifferentiability advantage of $\\distinguisher$ is defined as:\n    \\[\n        \\indiff_{\\primC^\\primP, \\simulator}(\\distinguisher) = \\abs*{\\prob{\\distinguisher^{\\primC^\\primP, \\primP} = 1} - \\prob{\\distinguisher^{\\primR, \\simulator^\\primR} = 1}}\n    \\]\n\\end{definition}\n\nThe distinguisher $\\distinguisher$ can query both its left oracle (either $\\primC$ or $\\primR$) and its right oracle (either $\\primP$ or \\simulator). We refer to $\\primC^\\primP,\\ \\primP$ as the real world, and to $\\primR,\\ \\simulator^\\primR$ as the simulated world; the distinguisher $\\distinguisher$ converses with either of these worlds and its goal is to tell both worlds apart.\n\n\\begin{theorem}[Indifferentiability of \\blake{2}{}~\\cite{luykx2016security}]\nLet an encryption scheme $\\Enc \\sample \\blockSet^*(2 \\cdot \\ol, 2 \\cdot \\ol)$ be a weakly ideal cipher, and consider the hash function $\\blake{2}{}_\\Enc$ that internally uses $\\Enc$. There exists a simulator $\\simulator$ such that for any distinguisher $\\distinguisher$ with total complexity $\\queryBound$, we have:\n    \\[\n        \\indiff_{\\blake{2}{}_\\Enc, \\simulator}(\\distinguisher) \\leq \\frac{\\binom q 2}{2^{2\\ol}} + \\frac{2 \\binom q 2}{2^{\\ol}} + \\frac{q}{2^{\\ol/2}}\n    \\]\n    where $\\simulator$ makes at most $O(\\queryBound^3)$ queries to a random function $\\primR$.\n\\end{theorem}\n\\begin{proof}\n    See~\\cite[Corollary 1]{luykx2016security}.\n\\end{proof}\n\nFor asymptotic security, we assume the distinguisher to be \\ppt{} and that the number of queries made is polynomial $q\\leq \\poly[\\ol]$.\n\n\\paragraph{Additional remarks.}\n\nLuykx et al.~\\cite{luykx2016security} remark that, by resorting to the WICM, they do not make stronger assumptions than those used in previous results (ICM), and, despite the fact that they give distinguishers more power (by weakening the cipher), they are able to get similar results.\n\n\\section{Security proofs}\\label{appendix:blake:proofs}\n\n\\subsection{Blake2 is a PRF}\\label{appendix:blake:proofs:prf}\n\nLuykx et al.~already prove the PRFness of \\blake{2}{} \\textit{keyed} hash function in the multi-key setting.\n\n\\begin{definition}[PRF in multi-key setting~\\cite{mouha2015multi}]\n\tLet $\\mu \\geq 1$ and $k \\sample \\keyspace^\\mu$. Let $\\primC$ be a keyed construction with key space $\\keyspace$ and with oracle access to an ideal primitive $\\primP$. Let $\\primR_1, \\ldots, \\primR_\\mu$ be random functions with the same domains and ranges as $\\primC_{\\key_1}, \\ldots, \\primC_{\\key_\\mu}$. Let $\\dist$ be a distinguisher. The PRF distinguishing advantage of $\\dist$ is defined as,\n\\[\n    \\prf_{\\primC^\\primP}(\\dist) = \\abs*{\\prob{\\distinguisher^{\\primC^\\primP_{\\key_1}, \\ldots, \\primC^\\primP_{\\key_\\mu}, \\primP} = 1} - \\prob{\\distinguisher^{\\primR_1, \\ldots, \\primR_\\mu, \\primP} = 1}}\n\\]\n\\end{definition}\n\n\\blake{2}{} supports keyed hashing by simply prepending the key to the message:\n\\[\n    \\blake{2}{}_{\\Enc,\\key}(\\msg) = \\blake{2}{}_{\\Enc}(\\key \\concat 0^{2\\ol - \\kl} \\concat \\msg)\n\\]\nwhere $\\kl \\leq 2\\ol$ denotes the key size. In other words, the key gets processed as other data and the $\\haifa$ counter and flags are designated to the key in a similar fashion as if they were for normal data blocks.\n\n\\begin{theorem}[PRF-security of \\blake{2}{} keyed mode~\\cite{luykx2016security}]\\label{appendix:th:kh-blake-prf}\nLet $\\mu \\geq 1$ and let $\\key \\sample \\left( \\BB^\\kl \\right )^\\mu$. Let an encryption scheme $\\Enc \\sample \\blockSet^*(2 \\cdot \\ol, 2 \\cdot \\ol)$ be a weakly ideal cipher, and consider the keyed hash function $\\blake{2}{}_{\\Enc, \\key}$ that internally uses $\\blake{2C}{}_\\Enc$ that internally uses $\\Enc$. For any distinguisher $\\distinguisher$ with total complexity $\\queryBound$:\n    \\[\n        \\prf_{\\blake{2}{}_{\\Enc, \\key}}(\\distinguisher) \\leq \\frac{\\binom q 2}{2^{2\\ol}} + \\frac{2 \\binom q 2}{2^{\\ol}} + \\frac{q}{2^{\\ol/2}} + \\frac{\\mu q}{2^\\kl} + \\frac{\\binom \\mu 2}{2^\\kl}\n    \\]\n\\end{theorem}\n\\begin{proof}\n    See~\\cite[Corollary 3]{luykx2016security}.\n\\end{proof}\n\n\\begin{remark}\\label{appendix:blake:proofs:kh-blake-remark}\nWe can note that in the case of keyed hashing, the key is padded only to be processed in a single block to differentiate the key from the message. The security proof of~\\cref{appendix:th:kh-blake-prf} does not rely on this padding and as such also works with no padding.\n\\end{remark}\n\n\\begin{theorem}[PRF-security of \\blake{2}{} with a single key~\\cite{luykx2016security}]\\label{appendix:th:blake-prf}\nLet $\\key \\sample \\BB^\\kl$. Let an encryption scheme $\\Enc \\sample \\blockSet^*(2 \\cdot \\ol, 2 \\cdot \\ol)$ be a weakly ideal cipher, and consider the keyed hash function $\\blake{2}{}_{\\Enc}(\\key, \\cdot) = \\blake{2}{}_\\Enc(\\key \\concat \\cdot)$ that internally uses $\\blake{2C}{}_\\Enc$ that internally uses $\\Enc$. For any distinguisher $\\distinguisher$ with total complexity $\\queryBound$:\n    \\[\n        \\prf_{\\blake{2}{}_{\\Enc}}(\\distinguisher) \\leq \\frac{\\binom q 2}{2^{2\\ol}} + \\frac{2 \\binom q 2}{2^{\\ol}} + \\frac{q}{2^{\\ol/2}} + \\frac{q}{2^\\kl}\n    \\]\n\\end{theorem}\n\\begin{proof}\n    See~\\cref{appendix:blake:proofs:kh-blake-remark} and~\\cref{appendix:th:kh-blake-prf} with $\\mu=1$.\n\\end{proof}\n\n\\begin{remark}\n  Since we analyse the security of \\blake{2}{} asymptotically, we assume that for a security parameter $\\secpar$ holds $\\ol = \\bigO{\\secpar}$, $\\kl = \\bigO{\\secpar}$, and $q = \\poly$.\n\\end{remark}\n\n\\subsection{Proof of Blake2 collision resistance}\\label{appendix:blake:proofs:colres}\n\nWe want to prove here the collision resistance of \\blake{2}{}. To do so, we are going to prove by contradiction that if \\blake{2}{} is not collision resistant, it is not indifferentiable according to~\\cref{appendix:blake:secmod:WICM:indiff}.\n\n\\begin{theorem}\n    \\blake{2}{} is collision resistant.\n     % with a security parameter of $\\secpar=\\ol/2$.\n\\end{theorem}\n\\begin{proof}[Informal proof.]\n    Let us assume that there exists a $\\ppt$ adversary $\\bdv$ which breaks the collision resistance of \\blake{2}{}. We build an adversary $\\adv$ that uses this adversary to differentiate between the real and simulated worlds. More particularly, $\\adv$ gets left and right oracles (see~\\cite[Figure 3]{luykx2016security}), which are either an oracle for a hash function and for a weakly ideal block cipher or a random oracle and an encryption simulator with oracle access to the random oracle.\n\n    On each $\\bdv$'s query $\\msg_i$, $i \\in \\range{1}{\\queryBound}$, $\\adv$ passes them to his left oracle and returns the answer $h_i$ to $\\bdv$.\n    Eventually, if $\\bdv$ finds a collision, that is a pair $(\\msg_i, \\msg_j)$ such that $\\msg_i \\neq \\msg_j$ and $h_i = h_j$, $\\adv$ guesses that his oracles were real; else $\\adv$ returns a random guess. Otherwise $\\adv$ guesses his oracles were simulated -- if the left oracle was a random oracle, the probability of finding a collision would be negligible for $\\queryBound \\leq \\poly$\\footnote{The probability would be $\\frac{\\queryBound^2}{2^{\\ol}}$ which is negligible for a polynomial number of queries $\\queryBound$. This is the sum of the probabilities of finding a collision when doing the $i^{th}$ query. Indeed, let us suppose the adversary has done $i-1$, $i>2$, queries without finding a collision, i.e.~he knows $i-1$ distinct tuples of input-output. When receiving the $i^{th}$ value, the adversary has thus $i-1$ chance to find a collision. The probability for the new output to be equal to any of the previous outputs is thus $(i-1) \\cdot \\frac{1}{2^{\\ol}}$ (as we are in the random oracle model). Summing this probability over all queries, we find the probability of finding a collision after doing $\\queryBound$ queries.}.\n\n    On the other hand, $\\bdv$ finds a collision with non-negligible probability if the oracles were real.\n    Hence, $\\adv$ wins the indifferentiability game with non-negligible advantage, which is a contradiction.\n\\end{proof}\n\n\\subsection{Blake2 as a commitment scheme}\\label{appendix:blake:proofs:comm}\n\nWe prove here that $\\blake{2}{}$ is a commitment scheme, i.e.~is binding and hiding. To do so we rely on the previous results that \\blake{2}{} is collision resistant and a \\prf.\n\n\\begin{theorem}\n    Let $\\Enc\\sample \\blockSet (2\\ol, 2\\ol) $ and for a message $x \\in \\BB^{*}$ and randomness $r \\in \\BB^{\\rl}$ commitment to $x$ using $r$ be $\\comm.\\commit{x}{r} = \\blake{2}{}_\\Enc (r \\concat x)$.\n    Then $\\comm$ is hiding and binding.\n\n    % Then $\\comm$ is hiding with security parameter $\\rl/2$ and binding with security parameter $\\rl/2$.\n\n\\end{theorem}\n\\begin{proof}[Informal proof.]\n\\emph{Hiding.}\n    A commitment scheme $\\comm$ is computationally hiding if, knowing two potential openings, a \\ppt{} adversary cannot distinguish which was committed. Let us assume that there exists a $\\ppt$ adversary $\\bdv$ which breaks the hiding property of $\\blake{2}{}$ with a non-negligible advantage $\\eta$. We build an adversary $\\adv$ that uses $\\bdv$ to break the PRF property of $\\blake{2}{}$ with advantage $\\eta/2$.\n\n    First, the \\prf{} game is initiated, that is, the challenger chooses a random encryption scheme $\\Enc$ and key $\\key \\in \\BB^\\rl$ and instantiates two oracles $\\oracle{\\blake{2}{}_k} = \\blake{2}{}_{\\Enc}(\\key, \\cdot)$ and $\\oracle{R}$ a random function. The challenger picks an oracle randomly and gives $\\adv$ access to it.\n    $\\bdv{}$ sends $\\queryBound$ oracle queries $m_1, \\ldots, m_q$ to $\\adv{}$ (adaptively) who extends them with random $r_1, \\ldots, r_q$ and sends $r_i \\| \\msg_i$ to his left oracle. Given the answer from the oracle, $\\adv$  returns them to $\\bdv$.\n    Eventually, $\\bdv{}$ then outputs two challenge messages $(\\tilde{\\msg}_0, \\tilde{\\msg}_1)$ and sends them to $\\adv$ who randomly selects message $\\tilde{\\msg}_b$, extends it with $r$ and sends $r \\| \\tilde{\\msg}_b$ to his left oracle.\n    The oracle answers with $y_b$ which is also sent to \\bdv{}.\n    Finally, \\bdv{} returns the decision bit $\\tilde{b}$ to \\adv. If $b = \\tilde{b}$, \\adv{} answers to the challenger that the oracle was instantiating the PRF. Otherwise, \\adv{} answers with a random guess.\n    The advantage of $\\adv$ equals advantage of $\\bdv$ if it interacts with a real hash function. The advantage of $\\adv$ equals half the advantage of $\\bdv$ when interacting with a random oracle and simulator.\n    % $\\adv$ wins when $\\bdv$ does and wins with probability at least $1/2$ otherwise. Hence, \\adv{} wins the PRF game with non-negligible advantage what gives a contradiction.\n\n\\emph{Binding.}\n    A commitment scheme $\\comm$ is said to be computationally binding if it is infeasible to find $x, x'$ and $r, r'$ such that $x \\neq x'$ and $\\commit{x}{r} = \\commit{x'}{r'}$. This is implied by collision resistance of \\blake{2}{}. Thus if $\\bdv$ is an algorithm that breaks the biding property with advantage $\\eta$, there is another algorithm $\\adv$ that breaks \\blake{2}{} collision resistance with the same advantage.\n\\end{proof}\n\nAssuming that \\blake{2s}{} is as secure as \\blake{2}{}, a commitment scheme based on a \\blake{2s}{}, i.e.~$\\commit{x}{r} = \\blake{2s}{}_{\\Enc}(r \\concat x)$ is hiding and binding.\n\n\\subsection{Proof of commitment scheme security}\\label{appendix:blake:full-comm}\n\nTo prove the binding and hiding property of $\\comm$ (see~\\cref{instantiation:prf-comm-crh:comm}), we introduce the following commitment scheme $\\comm^*$,\n\\begin{align*}\n\t\\comm^*.\\setup & : \\smallset{\\secparam\\ \\suchthat\\ \\secpar \\in \\NN} \\to \\BB^{*} \\\\\n\t\\comm^*.\\commit{}{} &: \\blockSet^{*}(2 \\cdot \\blakeCompLen, 2 \\cdot \\blakeCompLen) \\times \\BB^{2 \\cdot \\blakeCompLen} \\\\\n  & \\times \\left( \\BB^\\prfAddrOutLen \\times \\BB^\\prfRhoOutLen \\times \\BB^\\zvalueLen \\right ) \\times \\BB^\\noterLen \\to \\BB^\\blakeCompLen\n\\end{align*}\n\nThe commitment scheme is defined as follows,\n\\begin{align*}\n\t& \\comm^*.\\setup(\\secparam) = \\pparams^* = \\epsilon\\\\\n\t&\\comm^*.\\commit{\\msg = (\\apk, \\rrho, \\notev)}{\\noter} = \\cm{}\\\\\n\t&= \\blake{2}{}_{\\Enc^*} (\\noter \\concat \\apk \\concat \\rrho \\concat \\notev)\n\\end{align*}\n\nGiven a commitment scheme $\\comm^*$, the bijective function $\\decode{\\cdot}{\\NN}$ and $p_\\secpar{} \\in \\NN$, a prime which can be represented using $\\secpar$ bits, we define the commitment scheme $\\comm'$ as follows:\n\\begin{align*}\n    & \\comm'.\\setup(\\secparam{}) = (\\comm^*.\\setup(\\secparam{}), p_\\secpar{})\\\\\n    & \\comm'.\\commit{\\msg}{r} = \\decode{\\comm^*.\\commit{\\msg}{\\noter}}{\\NN} \\pmod{p_{\\secpar}}\\ \\text{for}\\ \\msg= (\\apk \\concat \\rrho \\concat \\notev)\n\\end{align*}\nNote that $\\comm$ (see~\\cref{instantiation:prf-comm-crh:comm}) is a particular instantiation of $\\comm'$ where $\\Enc^*$ is set as \\chacha{} encryption scheme~\\cite{bernstein2008chacha}, $k^*$ is a random key, and $p_\\secpar{}$ is $\\rCURVE$.\n\n\\begin{theorem}[Hiding]\\label{instantiation:th:com-bin-field-hiding}\n    If $\\comm^*$ is hiding then $\\comm'$ is hiding.\n\\end{theorem}\n\\begin{proof}\n\tWe prove the theorem by contradiction i.e.~we assume that there exists an adversary $\\bdv$ that breaks $\\comm'$'s hiding property and construct an adversary $\\adv$ that uses $\\bdv$ to break $\\comm^*$'s hiding property with non-negligible probability.\n\n  Let $\\cdv$ be a challenger that sets up the hiding game for $\\comm^*$ and $\\adv$.\n\tThe adversary $\\adv$, given public parameters $\\pparams^*$ of $\\comm^*$ and access to an oracle that runs the $\\commit{}{}$ algorithm of $\\comm^*$ scheme, simulates a hiding game for $\\comm'$ for $\\bdv$.\n  The adversary $\\adv$ starts by setting public parameters $\\pparams'$ for $\\comm'$ using public parameters $\\pparams^*$ given by $\\cdv$. Parameters $\\pparams'$ are passed to $\\bdv$ who outputs a pair of messages $\\msg_0, \\msg_1$.\n  The adversary $\\adv$ forwards them to the challenger who samples a bit $b$ at random and generates $\\cm{}^*= \\comm^*.\\commit{\\msg_b}{r}$ for some randomness $r$. The result is returned to \\adv{} (see~\\cref{preliminaries:definitions:commitment-hiding}).\n\tThen $\\adv{}$ passes $\\cm{}= \\decode{\\cm{}^*}{\\NN} \\pmod{p_\\secpar{}}$ to $\\bdv{}$ who returns his guess $b'$. The adversary $\\adv$ returns the same $b'$ to the challenger.\n\n\tBy construction, it is clear that $\\adv$ wins the hiding game with the same probability that $\\bdv$ wins the simulated hiding game. Since $\\bdv$'s advantage is non-negligible, this means that $\\adv$ wins the $\\comm^*$ hiding game with non-negligible probability as well.\n\\end{proof}\n\n\\begin{theorem}[Binding]\\label{instantiation:th:com-bin-field-binding}\n    Let $\\comm^*$ be a computationally binding commitment scheme and $\\comm^*.\\commit{}{}$ indifferentiable from a random oracle. Then $\\comm'$ is also computationally binding if $l = \\left \\lceil 2^{\\secpar} / p_\\secpar \\right\\rceil$ is at most $\\poly[\\secpar]$.\n\\end{theorem}\n\\begin{proof}\n\tAssume that \\adv{} asks the $\\comm'$ commit and open oracles a total of $q_\\secpar$ distinct queries. Let us denote the result of the $q_\\secpar$ queries and output of the attacker (the candidate collision) as\n  $\\left ( ( \\msg_1, \\opening_1, y_1), \\ldots , (\\msg_{q_\\secpar}, \\opening_{q_\\secpar}, y_{q_\\secpar}), \\text{out} \\right )$.\n  If \\adv{} is successful it means that it outputs $(\\msg, \\opening)$, $(\\msg', \\opening')$ such that $(\\msg, \\opening) \\neq (\\msg', \\opening')$ and $\\comm'.\\commit{\\msg}{\\opening} = \\comm'.\\commit{\\msg'}{\\opening'}$.\n\n\tBy the definition of $\\comm'$, we have that,\n\t\\[\n\t\t\\comm'.\\commit{\\msg}{\\opening} = \\decode{\\comm^*.\\commit{\\msg}{\\opening}}{\\NN} \\pmod{p_\\secpar}\n\t\\]\nHence, we have a collision in $\\comm'$ if there exists $k \\in [l]$, $l$ being the ratio of the codomains of $\\comm^*.\\commit{}{}$ and $\\comm'.\\commit{}{}$, such that,\n\t\\[\n\t\t\\abs*{\\decode{\\comm^*.\\commit{\\msg}{\\opening}}{\\NN} - \\decode{\\comm^*.\\commit{\\msg'}{\\opening'}}{\\NN}} = k \\cdot p_{\\secpar}.\n\t\\]\n\tWe show that this event is unlikely.\n\n\t% In fact, for each $i \\in [q_\\secpar]$, let $C_i$ be the event that the adversary wins at the $i^{th}$ query; i.e.~either the last commitment $y_i$, obtained by the adversary, is a $\\comm^*$ collision with one of the previous or a $\\comm'$ collision which is not a collision for $\\comm^*$. That is, $\\exists j\\leq i, \\exists k, 0\\leq k < l,\\ \\suchthat\\ y_i = y_j + k \\cdot p_\\secpar$. Hence, the adversary has $l$ ways to win.\n\n  In fact, for each $i \\in [q_{\\secpar}]$, let $C_i$ be the event that the adversary wins at the $i$-th query. That is, the last commitment $y_i$ is a $\\comm'$ collision with one of the previous $y_j$.  More precisely there exists $j \\leq i$ and $k < l$ such that $y_i = y_j + k \\cdot p_{\\secpar}$.\n\n\tSince $\\comm^*$ is a random oracle, $y_i$ is randomly selected from a set of at least $p_\\secpar$ elements. As such, we have $\\prob{C_i} \\leq i \\cdot l / p_\\secpar$.\n\n\tThus the probability of finding a collision after $q_\\secpar$ queries is\n  $\\prob{C_1 \\lor \\ldots \\lor C_{q_\\secpar}} \\leq \\sum_{i = 1}^{q_\\secpar} \\prob{C_i} = l/p_\\secpar \\cdot \\sum_{i=1}^{q_\\secpar} i$.\n  This probability is bounded by $l \\cdot \\frac{q_\\secpar(q_\\secpar+1)}{p_\\secpar}$.\n\tHowever, we allow only polynomial number of queries. Thus for $q_\\secpar = \\poly$ this probability becomes,\n\t\t\\[\n\t\t\t\\frac{2^\\secpar \\cdot \\poly}{p_\\secpar^2},\n\t\t\\]\n\twhat is negligible for $2^\\secpar / p_\\secpar \\leq \\poly$.\n\\end{proof}\n\n\\begin{remark}\\label{instantiation:remark:rbn-blackcomplen}\n\tNote that in \\zeth's commitment scheme, we set $p_\\secpar{} = \\rCURVE$ and $2^\\secpar = 2^\\blakeCompLen$. Thus, for \\BNCurve and \\BLSCurve have $l = 6$ and $l = 14$, respectively. Therefore, the probability of an attacker breaking the binding property due to reduction modulo $\\rCURVE$ increases approximately by these factors. This is still negligible.\n\\end{remark}\n\n\\begin{cor}\n    Assume that \\blake{2}{} is indifferentiable from a random oracle and a PRF, then $\\comm^*$ is computationally binding and computationally hiding. Furthermore, the reduction is \\emph{tight}. That is, the advantage of any \\ppt{} adversary against the binding (resp.~hiding) property is the same as the advantage of an adversary against collision resistance and binding (resp.~hiding).\n\\end{cor}\n", "meta": {"hexsha": "d1eaa9f794521486132e4930cbbb43aab8d70d15", "size": 23592, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "appendices/appendix04-blake.tex", "max_stars_repo_name": "clearmatics/zeth-specifications", "max_stars_repo_head_hexsha": "ba29c67587395f5c7b26b52ee7ab9cba12f1cc6b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-29T18:22:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-29T18:22:00.000Z", "max_issues_repo_path": "appendices/appendix04-blake.tex", "max_issues_repo_name": "clearmatics/zeth-specifications", "max_issues_repo_head_hexsha": "ba29c67587395f5c7b26b52ee7ab9cba12f1cc6b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2020-10-27T10:41:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-16T10:57:05.000Z", "max_forks_repo_path": "appendices/appendix04-blake.tex", "max_forks_repo_name": "clearmatics/zeth-specifications", "max_forks_repo_head_hexsha": "ba29c67587395f5c7b26b52ee7ab9cba12f1cc6b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-26T04:51:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T04:51:29.000Z", "avg_line_length": 92.8818897638, "max_line_length": 1142, "alphanum_fraction": 0.7043489318, "num_tokens": 7299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.33560890231460916}}
{"text": "\\subsection{Word vs. Instance-Based Induction}\n\\label{sec:typevsinstance}\n\nTable~\\ref{tab:results} shows that the overall many-to-one accuracy of\nour instance based induction system is comparable to\n\\cite{yatbaz-sert-yuret:2012:EMNLP-CoNLL}\\footnote{The difference is\n  not statistically significant at $p=0.05$.} and significantly higher\nthan the other published results on the Penn Treebank.  However\nFigure~\\ref{fig:perplexity} in the introduction suggests that this\nsummary hides the large difference in the answers given by the\ndifferent systems.  In this section we compare the performance of our\ninstance-based model to the word-based model of\n\\cite{yatbaz-sert-yuret:2012:EMNLP-CoNLL} on word types at different\nlevels of ambiguity using the English Penn Treebank results.\n\nWe propose the gold-tag perplexity of a word as a measure of its\ndegree of ambiguity defined as:\n\\begin{equation*} \\label{eq:tag-perp}\nGP(w) = 2^{H(p_w)} = 2^{-\\sum_{t} p_w(t)log_2 p_w(t)}\n\\end{equation*}\n\\noindent where $w$ is a word, $t$ is a tag, $p_w$ is the gold POS tag\ndistribution of the word $w$ and $H(p_w)$ is the entropy of the $p_w$\ndistribution.  A $GP$ of 1 for a word $w$ indicates that $w$ is always\nassociated with the same POS tag.  A word with $N$ equally probable\ntags would have a $GP$ of $N$.\n\nFigure~\\ref{fig:perplexity} plots the gold-tag perplexity versus the\nsmoothed \\mto\\ accuracy for the word-based and the instance-based POS\ninduction systems on the Penn Treebank.  To compose the plot, we found\nthe best mapping from the induced clusters to the gold-standard tags,\nthen we computed the \\mto\\ accuracy for each word using this mapping\nand plotted the \\mto\\ as a function of the word's $GP$.  We used the\nNadaraya-Watson kernel regression estimate\n\\cite{nadaraya1964estimating,watson1964smooth} with normal kernel of\nbandwidth 1.0 to obtain smooth regression lines.  The figure shows\nthat the performance of the instance-based induction model does not\ndegrade as much as the word-based model as the ambiguity of the words\nincrease.  However, only 14.94\\% of the instances in the PTB consists\nof words with GP greater than 1.5 and 45.71\\% consists of words with\nGP exactly 1.  Thus, the overall accuracy numbers do not adequately\nreflect the improvement on highly ambiguous words.\n\n%% In the next section we apply the instance based model on 19 corpora in 15\n%% different languages. \n\n%% Due to the one-tag-per-word nature of POS induction, the\n%% type based model significantly outperforms the instance based one on the\n%% unambiguous words.  Instance based model performs significantly better than the\n%% type based model on the ambiguous words and assigns 1.34 tags per word.  \n%% \\subsection{Clustering Concatenation of Word and Context Embeddings (${\\bf W}\\oplus{\\bf S}$)}\n%% \\label{sec:clustering-c}\n%% Two models presented in earlier sections perform POS induction either\n%% by assuming (Section~\\ref{sec:clustering-w}) or discarding\n%% (Section~\\ref{sec:clustering-c}) the one-tag-per-word assumption.  In\n%% this section we define a sparse-instance based model which clusters the\n%% concatenation of ${\\bf W}$ and ${\\bf S}$ embeddings.  This model not\n%% only tends to put instances of a word into the same cluster but\n%% also performs instance based clustering by incorporating the word\n%% and context information together.\n%%\n%% Similar to the previous models, we generate ${\\bf W}$ -- ${\\bf S}$\n%% pairs as the input to S-CODE.  For each observed ${\\bf W}$ -- ${\\bf\n%%   S}$ pair in the S-CODE input, corresponding 25-dimensional $\\phi_w$\n%% and $\\psi_c$ embeddings are concatenated to create a 50-dimensional\n%% representation.  We used the same experimental setting of the previous\n%% section and predict the instance clusters according to the majority\n%% cluster-id of the corresponding pairs.  The many-to-one accuracy of\n%% this model is \\wsxymto\\ and the V-measure is \\wsxyvm\\ .\n%% \n%% Table~\\ref{tab:bins} presents the performance of the ${\\bf\n%%   W}\\oplus{\\bf S}$ based model over the subsets and it achieves\n%% statistically better \\mto\\ than both of the ${\\bf W}$ and ${\\bf S}$\n%% based models on ambiguous words.  Due to the bias towards to the\n%% sparse clustering, sparse-instance based model statistically improves the\n%% \\mto\\ accuracy on unambiguous words compared to the ${\\bf S}$ based\n%% model but it still can not achieve the performance of the ${\\bf W}$\n%% based model.  The ${\\bf W}\\oplus{\\bf S}$ based model constructs instance \n%% based clusters that tend to assign instances of a word into the\n%% same cluster which leads to a smaller average $GP$ than the ${\\bf S}$\n%% based model as shown in Table~\\ref{tab:bins}.\n%%\n%% We don't really need this part\n%% \\subsubsection{Paradigmatic vs Syntagmatic Representations of Word Context}\n%% \\label{sec:bigram-instance}\n%% In order to compare the instance clustering performance of the\n%% paradigmatic and the syntagmatic context representations we use the\n%% same 4 models defined in Section~\\ref{sec:bigram-type}.  Following the\n%% previous section we concatenate the 25-dimensional $\\phi_x$ and\n%% $\\psi_y$ ($\\psi_{y_{1}}$ and $\\psi_{y_{2}}$ in the fourth model)\n%% embeddings of the corresponding observed pairs (tuples in the fourth\n%% model) and represent the first three models outputs with a\n%% 50-dimensional vectors (75-dimensional vectors in the fourth model).\n%% The resulting vectors are clustered using k-means algorithm with 128\n%% restarts.\n%% \\begin{table}[ht]\n%% \\centering\n%% \\small\n%% \\caption{Accuracies of the instance based S-CODE models on the gold-tag\n%%   perplexity separated subsets.}\n%% \\begin{tabular}{|l|l|l|l|}\n%% \\hline\n%% Model & \\specialcell{$GP < 1.75$\\\\$89\\%$} & \\specialcell{$GP \\ge 1.75$\\\\$11\\%$} & \\specialcell{$GP \\ge 1.0$\\\\$100\\%$}\\\\\n%% \\hline\n%% $X$ (word) - $Y$ (left bigram) & .5950 (.0051) & .4783 (.0005) & .5821 (.0041)\\\\\n%% $X$ (word) - $Y$ (right bigram) & .6239 (.0049) & .3075 (.0153) & .5891 (.0046)\\\\\n%% $X$ (word) - $Y$ (left and right bigram concatenation) & .7523 (.0065) & .4492 (.0240) & .7190 (.0049)\\\\\n%% $X$ (word) - $Y_1$, $Y_2$ (left and right bigrams) & .6697 (.0065) & .4579 (.0052) & .6464 (.0051)\\\\\n%% $X$ (word) - $Y$ (random substitutes) & .7322 (.0079) & .4671 (.0174) & .7030 (.0073)\\\\\n%% \\hline\n%% \\end{tabular}\n%% \\label{tab:instances}\n%% \\end{table}\n", "meta": {"hexsha": "a8bb8f76225def83d95bd0cdcb9376c52cac677f", "size": 6317, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "papers/coling2014/token.tex", "max_stars_repo_name": "ai-ku/upos_2014", "max_stars_repo_head_hexsha": "f4723cac53b4d550d2b0c613c9577eb247c7ff4a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-06-06T07:13:43.000Z", "max_stars_repo_stars_event_max_datetime": "2015-06-06T07:13:43.000Z", "max_issues_repo_path": "papers/coling2014/token.tex", "max_issues_repo_name": "ai-ku/upos_2014", "max_issues_repo_head_hexsha": "f4723cac53b4d550d2b0c613c9577eb247c7ff4a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "papers/coling2014/token.tex", "max_forks_repo_name": "ai-ku/upos_2014", "max_forks_repo_head_hexsha": "f4723cac53b4d550d2b0c613c9577eb247c7ff4a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.9026548673, "max_line_length": 122, "alphanum_fraction": 0.7281937629, "num_tokens": 1790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.33558004078011977}}
{"text": "\\documentclass[twocolumn]{article}\r\n\\usepackage[margin=1in]{geometry}\r\n\\usepackage{outlines}\r\n\\usepackage{amsmath}\r\n\\usepackage{gensymb}\r\n\\title{Ch. 20-21 Notes}\r\n\\author{John Yang}\r\n\\setcounter{section}{+19}\r\n\r\n\\begin{document}\r\n\\maketitle\r\n\\section{Magnetic Forces and the Magnetic Field}\r\n\\subsection{The Magnetic Field}\r\n\\begin{outline}\r\n\t\\1 The end of a compass needle that points generally in a northerly direction at most places on earth is defined to be the North magnetic pole of the compass needle\r\n\t\\1 The opposite end is defined to be its south pole. \r\n\t\\1 Magnets always occur in dipoles. If you break a permanent magnet in half you get two magnets. \r\n\t\\1 Like poles repel and unlike poles attract\r\n\t\\1 Force on a charged particle moving through a uniform field: \\[\\vec{F}_{\\text{magnet on q}}=q\\vec{v}\\times\\vec{B}\\]\r\n\t\\1 Magnetic field $\\vec{B}$ is in Teslas (T)\r\n\t\\1 Use the pointing rhr for positive charges, where the index finger is the velocity, the thumb is the force, and the other fingers are the field. The left hand can be used for negative charges but do not get confused!\r\n\\end{outline}\r\n\\subsection{Applications}\r\n\\begin{outline}\r\n\t\\1 Velocity selectors; charged particles are shot through perpendicular electric and magnetic fields; only those with a certain velocity make it through without being deflected due to imbalanced forces, given by \\(v_0=\\dfrac{E}{B}\\)\r\n\t\\1 Mass spectrometers: A charged particle is shot into a region of a uniform magnetic field at a known velocity. The semicircular radius it makes before hitting a plate depends on its mass and is given by \\(R=\\dfrac{mv}{|q|B}\\)\r\n\t\t\\2 Can be used to separate a compound into its constituent ions to find its composition. \r\n\t\\1 Hall effect: charges moving through a magnetic field experience a force, but moving magnetic fields can also induce a current. Using semiconductors, the Hall effect can be used to measure the proximity of a moving magnet by measuring the way charges move in a semiconductor in response to the change in magnetic field. \r\n\r\n\\end{outline}\r\n\\subsection{Magnetic Forces on Currents}\r\n\\begin{outline}\r\n\t\\1 Magnetic force on a current-carrying wire: \\[\\vec{F}_{\\text{magnet}}=I\\int_{\\text{wire}}d\\vec{\\ell}\\times\\vec{B}\\]\r\n\r\n\\end{outline}\r\n\\subsection{Work Done by Magnetic Forces}\r\n\\begin{outline}\r\n\t\\1 Work done by magnetic forces is always 0 because it is perpendicular to the motion of the charge. \r\n\\end{outline}\r\n\\subsection{Torque on a Current Loop in a Magnetic Field}\r\n\\begin{outline}\r\n\t\\1 Magnetic dipole moment: \\[\\vec{\\mu}\\equiv I\\vec{A}\\] where $\\vec{A}$ is the area vector. \r\n\t\\1 Torque on a current loop inside a uniform magnetic field: \\[\\vec{\\tau}=\\vec{\\mu}\\times\\vec{B}=I\\vec{A}\\times\\vec{B}\\]\r\n\t\\1 The current loop inside the magnetic field executes simple harmonic motion. \r\n\\end{outline}\r\n\\subsection{The Biot-Savart Law}\r\n\\begin{outline}\r\n\t\\1 To find the magnetic field caused by the entire wire, \\[\\vec{B}=\\dfrac{\\mu_0}{4\\pi}I\\int_{\\text{wire}}\\dfrac{d\\vec{\\ell}\\times\\vec{r}}{r^2}\\]\r\n\t\\1 Some commonly used magnetic fields: \r\n\t\t\\2 At the center of a circular loop of radius $R$ \\[\\vec{B}_{\\text{center}}=\\dfrac{\\mu_0}{4\\pi}\\dfrac{2\\pi I}{R}\\hat{k}\\]\r\n\t\t\\2 On the axis of a circular current loop \\[\\vec{B}_{axis}=\\dfrac{\\mu_0}{4\\pi}\\dfrac{I(2\\pi R)^2}{(R^2+z^2)^{3/2}}\\hat{k}\\]\r\n\t\t\\2 For a circular coil of $n$ loops, all of the same radius, multiply the preceding results by $n$\r\n\t\t\\2 A distance $d$ from an infinite wire \\[B=\\dfrac{\\mu_0}{4\\pi}\\dfrac{2I}{d}\\] use grabbing rhr for direction \r\n\t\t\\2 Inside a long solenoid having $n$ turns per meter of its length, each carrying current $I$, far from its ends \\[B=\\mu_0nI\\]\r\n\\end{outline}\r\n\\subsection{Forces of Parallel Currents on Each Other and the definition of the Ampere}\r\n\\begin{outline}\r\n\t\\1 Forces on parallel wires - attractive if currents in the same direction, repulsive if currents are antiparallel\r\n\t\\1 Two infinitely long parallel straight current carrying wires exert forces on a length $\\ell$ of either wire of magnitude \\[F=\\dfrac{\\mu_0}{4\\pi}\\dfrac{2I_1I_2}{d}\\ell\\]\r\n\r\n\\end{outline}\r\n\\subsection{Gauss' Law for the Magnetic Field}\r\n\\begin{outline}\r\n\t\\1 The flux of the magnetic field through any closed surface must always be zero: \\[\\int_{\\text{clsd surf}}\\vec{B}\\cdot d\\vec{S}=0\\text{ T}\\cdot\\text{m}^2\\]\r\n\r\n\\end{outline}\r\n\\subsection{Magnetic Poles and current loops}\r\n\\begin{outline}\r\n\t\\1 Magnetic field forms closed loops in accordance with Gauss's law for magnetic field \r\n\t\\1 Field lines come out of the north pole and enter into the south pole\r\n\\end{outline}\r\n\\subsection{Ampere's Law}\r\n\\begin{outline}\r\n\t\\1 Ampere's law is: \\[\\int_{\\text{clsd path}}\\vec{B}\\cdot d\\ell=\\mu_0I\\]\r\n\\end{outline}\r\n\\subsection{The Displacement Current and the Ampere-Maxwell Law}\r\n\\begin{outline}\r\n\t\\1 Displacement current - current due to changing electric flux, where \\[I_D\\equiv\\varepsilon_0\\dfrac{d\\Phi_{\\text{elec}}}{dt}\\]\r\n\t\\1 Ampere-Maxwell law - right side of Ampere's law should include both displacement and conduction currents: \\[\\int_{\\text{clsd path}}\\vec{B}\\cdot d\\vec{r}=\\mu_0(I+I_D)_{\\text{threading the path}}\\]\r\n\t\\1 Makwell realized that magnetic fields are produced by: \r\n\t\t\\2 Electric charges in motion (conduction current)\r\n\t\t\\2 Time-varying electric fields (displacement current)\r\n\t\\1 The magnetic field induced by the displacement current is perpendicular to the (changing) electric field that causes it\r\n\t\r\n\\end{outline}\r\n\\subsection{Magnetic Materials}\r\n\\begin{outline}\r\n\t\\1 certain materials are naturally magnetic. It depends on the relative permeability of the substance: \\[\\kappa_m=\\dfrac{\\mu}{\\mu_0}\\]\r\n\t\t\\2 Diamagnetic - $\\kappa_m$ slightly less than 1\r\n\t\t\\2 Paramagnetic - $\\kappa_m$ slightly greater than 1\r\n\t\t\\2 Ferromagnetic - $\\kappa_m$ much greater than 1\r\n\\end{outline}\r\n\\subsection{The Magnetic Field of the Earth}\r\n\\begin{outline}\r\n\t\\1 Earth has a permanent magnetic field. \r\n\t\\1 Magnetic north pole is actually the geographic south pole\r\n\t\\1 Magnetic declination - difference in angle between magnetic north and true north\r\n\\end{outline}\r\n\\section{Faraday's Law of Electromagnetic Induction}\r\n\\subsection{Faraday's Law of Electromagnetic Induction}\r\n\\begin{outline}\r\n\t\\1 A changing magnetic flux through a loop induces an electric field, called an induced electric field\r\n\t\\1 Faraday's law: \\[\\int_{\\text{clsd path}}\\vec{E}\\cdot d\\vec{\\ell}=-\\dfrac{d\\Phi}{dt}\\] where $\\Phi$ is the magnetic flux through the enclosed area \r\n\t\\1 Induced emf: \\[\\text{induced emf}\\equiv\\int_{\\text{clsd path}}\\vec{E}\\cdot d\\vec{\\ell}\\]\r\n\t\\1 Faraday's law is commonly written as \\[\\text{induced emf}=-\\dfrac{d\\Phi}{dt}\\]\r\n\t\\1 The magnetic flux is: \\[\\Phi=\\vec{B}\\cdot\\vec{A}\\]\r\n\t\\1 Changing magnetic fields give rise to induced electric fields via Faraday's law\r\n\t\\1 Changing electric fields give rise to magnetic fields via the displacement current and the Ampere-Maxwell law.\r\n\t\\1 the electric and magnetic fields are mutually perpendicular to each other\r\n\\end{outline}\r\n\\subsection{Lenz's Law}\r\n\\begin{outline}\r\n\t\\1 The induced current always will be directed so as to oppose the change in the magnetic flux that is taking place. \r\n\\end{outline}\r\n\\subsection{An ac generator}\r\n\\begin{outline}\r\n\t\\1 A coil of wire of $N$ loops (of identical area $A$) rotates in a uniform magnetic field at an angular frequency $\\omega$:\\[\\text{induced emf}=NBA\\omega\\sin(\\omega t)\\]\r\n\t\t\\2 The induced emf is sinusoidal \r\n\t\\1 When associated with a generator, we call the induced emf the source voltage\r\n\\end{outline}\r\n\\subsection{Summary of the Maxwell Equations of Electromagnetism}\r\n\\begin{outline}\r\n\t\\1 Gauss' law for electric field: \\[\\int_{\\text{clsd srfc } S}\\vec{E}\\cdot d\\vec{S}=\\dfrac{Q_{\\text{enc}}}{\\varepsilon_0}\\]\r\n\t\\1 Gauss' law for magnetic field: \\[\\int_{\\text{clsd srfc } S}\\vec{B}\\cdot d\\vec{S}=0\\text{ T}\\cdot\\text{m}^2\\]\r\n\t\\1 Ampere-maxwell law: \\[\\int_{\\text{clsd path}}\\vec{B}\\cdot d\\vec{\\ell}=\\mu_0(I+I_D)=\\mu_0I+\\mu_0\\varepsilon_0\\dfrac{d\\Phi_{\\text{elec}}}{dt}\\]\r\n\t\\1 Faraday's law: \\[\\int_{\\text{clsd path}}\\vec{E}\\cdot d\\vec{\\ell}=-\\dfrac{d\\Phi}{dt}\\]\r\n\t\\1 Light is an electromagnetic wave with its speed given by: \\[c=\\dfrac{1}{\\sqrt{\\mu_0\\varepsilon_0}}\\]\r\n\\end{outline}\r\n\\subsection{Electromagnetic Waves}\r\n\\begin{outline}\r\n\t\\1 electric field component: \\[\\dfrac{\\partial^2E_y}{\\partial x^2}-\\mu_0\\varepsilon_0\\dfrac{\\partial^2E_y}{\\partial t^2}=0\\text{ N}/(\\text{C}\\cdot\\text{m}^2)\\]\r\n\t\\1 Magnetic field component: \\[\\dfrac{\\partial^2B_z}{\\partial x^2}-\\mu_0\\varepsilon_0\\dfrac{\\partial^2B_z}{\\partial t^2}=0\\text{ T}/\\text{m}^2)\\]\r\n\t\\1 The electric field, magnetic field, and direction of propagation are all mutually orthogonal, therefore light is a transverse wave \r\n\t\\1 Acceleration of charges is light\r\n\\end{outline}\r\n\\subsection{Self-Inductance}\r\n\\begin{outline}\r\n\t\\1 Self inductance is: \\[L\\equiv\\dfrac{\\Phi}{I}\\] which is the total magnetic flux over the current. Measured in Henrys $H$\r\n\r\n\\end{outline}\r\n\\subsection{Series and Parallel Combinations of Inductors}\r\n\\begin{outline}\r\n\t\\1 Inductors add in series: \\[L_{\\text{eq}}=L_1+L_2+L_3+\\cdots\\]\r\n\t\\1 Inverses of inductors add in parallel: \\[\\dfrac{1}{L_{\\text{eq}}}=\\dfrac{1}{L_1}+\\dfrac{1}{L_2}+\\dfrac{1}{L_3}+\\cdots\\]\r\n\\end{outline}\r\n\\subsection{A Series LR Circuit}\r\n\\begin{outline}\r\n\t\\1 For a series LR Circuit, \\[I(t)=\\dfrac{V_0}{R}\\left[1-e^{-(R/L)t}\\right]\\]\r\n\t\t\\2 When I is constant, there is no voltage across the inductor. An Inductor only has an effect while the current is changing with time. For the steady-state situation, there is no potential difference across an inductor since the current no longer is changing with time. \\[V=L\\dfrac{dI}{dt}\\]\r\n\t\\1 Time constant of a LR circuit is \\[\\tau\\equiv\\dfrac{L}{R}\\]\r\n\\end{outline}\r\n\\subsection{Energy stored in a magnetic field}\r\n\\begin{outline}\r\n\t\\1 Potential energy stored by the inductor is: \\[U=\\dfrac{1}{2}LI^2\\]\r\n\t\t\\2 That is, the inductor stores energy even if the current is not changing. \r\n\t\\1 Power absorbed by the inductor: \\[P=\\dfrac{dU}{dt}=IL\\dfrac{dI}{dt}\\]\r\n\t\\1 Magnetic energy density is \\[\\dfrac{1}{2}\\dfrac{B^2}{\\mu_0}\\]\r\n\\end{outline}\r\n\\subsection{A Parallel LC Circuit}\r\n\\begin{outline}\r\n\t\\1 For a parallel LC circuit, \\[\\dfrac{d^2Q}{dt^2}+\\dfrac{1}{LC}Q=0\\text{ A}/\\text{s}\\]\r\n\t\t\\2 Which is the equation for SHM\r\n\t\\1 the charge oscillates between the inductor and the capacitor: \\[Q(t)=Q_0\\cos(\\omega t+\\phi)\\]\r\n\t\\1 The angular frequency of the charge oscillations is: \\[\\omega=\\dfrac{1}{\\sqrt{LC}}\\]\r\n\\end{outline}\r\n\\subsection{Mutual Inductance}\r\n\\begin{outline}\r\n\t\\1 an inductor near another inductor can induce a current there. \r\n\t\\1 mutual inductance \\[M_{21}\\equiv\\dfrac{\\Phi_{21}}{I_1}\\] \\[V_2\\equiv M_{21}\\dfrac{dI_1}{dt}\\] for a closed circuit near an open one \\[V_1\\equiv M_{21}\\dfrac{dI_2}{dt}\\] for a reciprocal arrangement \\[M_{21}=M_{12}\\]\r\n\t\\1 If both circuits are closed, \\[V_1=L_1\\dfrac{dI_1}{dt}+M\\dfrac{dI_2}{dt}\\] \\[V_2=L_2\\dfrac{dI_2}{dt}+M\\dfrac{dI_1}{dt}\\]\r\n\\end{outline}\r\n\\subsection{An Ideal Transformer}\r\n\\begin{outline}\r\n\t\\1 Transformers can change voltage of AC signals using mutual inductance. \r\n\\0 \\[V_1=N_1\\dfrac{d\\Phi}{dt}\\] \\[V_2=N_2\\dfrac{d\\Phi}{dt}\\] but since $\\dfrac{d\\Phi}{dt}$ is the same for all wires in the system, we can write this as \\[\\dfrac{V_1}{V_2}=\\dfrac{N_1}{N_2}\\]\r\n\t\\1 Input coil is the primary coil, the output coil is the secondary\r\n\t\\1 Step up transformers - \\(V_2>V_1\\) and \\(N_2>N_1\\)\r\n\t\\1 Step down transformers - \\(V_2<V_1\\) and \\(N_2<N_1\\)\r\n\t\\1 In a step up transformer, the output potential is greater than the input but the current is less \r\n\t\\1 In a step down transformer, the output voltage is less than the input, and the current is greater \r\n\t\\1 Transformers don't work with dc current. \r\n\\end{outline}\r\n\\end{document}", "meta": {"hexsha": "d478a03012eab6c4160efd1684067adcbe27be07", "size": 11761, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ch 20-21/ch 20-21 notes.tex", "max_stars_repo_name": "CookiePie1/PhysicsC", "max_stars_repo_head_hexsha": "80d1d884f2ef2560f2c30345acf6c10cc326b4cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch 20-21/ch 20-21 notes.tex", "max_issues_repo_name": "CookiePie1/PhysicsC", "max_issues_repo_head_hexsha": "80d1d884f2ef2560f2c30345acf6c10cc326b4cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch 20-21/ch 20-21 notes.tex", "max_forks_repo_name": "CookiePie1/PhysicsC", "max_forks_repo_head_hexsha": "80d1d884f2ef2560f2c30345acf6c10cc326b4cb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 64.2677595628, "max_line_length": 324, "alphanum_fraction": 0.7227276592, "num_tokens": 3683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.33558003255702734}}
{"text": "%!TEX root = ../thesis.tex\n\\chapter{Quad-tree mesh in 2D analysis}\n\\label{qdt_sec:main}\n\\section{Introduction}\n\\paragraph{}\nThe main objective of this chapter is to implement an adaptor that can parse the geometric information in CAD directly and to develop an automatic mesh generation algorithm based on it.\nThe IGES file introduced in Sec.~\\ref{lr_sec:IGES} is used in the proposed method as the bridge between the CAD and the numerical analysis.\nA quad-tree mesh generation algorithm described in \\ref{qt_sc:quadtree} will be adopted to generate a high quality mesh.\nEither the NURBS basis function or the traditional shape function can be used as the shape function of the SBFEM solver.\nThe geometric boundary will be translated into polylines before the meshing and the intersections are calculated based on them.\nIntersecting points on these polylines are projected back to the NURBS surface after the meshing is generated to retain the exact geometry.\n% We further extend the method to problems with singularities within the framework of linear elastic fracture mechanics.\nThe proposed method enhances the conventional SBFEM and the salient features of the method are:\n    \\begin{itemize}\n        \\item Direct using design file as geometric input\n        \\item No human effort involvement in mesh generation\n        \\item Retained exact geometry\n        \\item High quality mesh generated from the quad-tree algorithm\n    \\end{itemize}\n\\paragraph{}\nThis chapter is organized as follows.\nThe CAD output (iges file) will be introduced first.\nAfter that, an overview of the algorithm that can generate quadtree mesh will be provided.\nFurthermore, a point projection method for NURBS curve utilizing its strong convex hull property is presented.\nThe accuracy and the convergence properties of the proposed techniques are demonstrated with benchmark problems in the context of linear elasticity, followed by concluding remarks in the last section.\n\n\n\\section{CAD output in 2D}\n\\label{qt_sc:iges}\n\\input{quadtree/iges.tex}\n\n\\section{Quad-tree structure}\n\\label{qt_sc:quadtree}\n\\input{quadtree/quadtree.tex}\n\n\\section{Points projection}\n\\label{qt_sc:projection}\n\\input{quadtree/projection.tex}\n\n\n\\section{Numerical Examples}\n\\input{quadtree/ex_cantilever.tex}\n\\input{quadtree/ex_circular_hole_qdt.tex}\n\\input{quadtree/ex_bracket.tex}\n% \\input{quadtree/ex_dam.tex}\n\\input{quadtree/ex_building.tex}\n\\input{quadtree/ex_other_mesh.tex}\n\n\\section{Conclusions}\n\\paragraph{}\nIn this chapter, the IGES file is employed directly from the CAD output to represent the geometry during the preprocessing.\nThe proposed methods provides a systematic and automatic mesh generation algorithm where high quality mesh is produced efficiently.\nThe CAD design file can be used directly and the exact geometry can also be retained, which largely reduce the human efforts involved in numerical analysis.\nMoreover, it helps to reduce the analytical error as the difference in the geometric representation is minimized.\nComputational efficiency is improved via utilizing the pattern of the quadtree to prevent repeated calculation.\nPoints projection algorithm is accelerated using the strong convex hull property of the NURBS curve.\nThe accuracy, effectiveness and the convergence properties of the proposed method are demonstrated with benchmark problems in linear elasticity mechanics.\nFrom the numerical studies, it can be observed that the quadtree mesh yield better accuracy when compared to uniform mesh with same degree of freedoms.\n", "meta": {"hexsha": "293ff26044fc7d9b812c42feedbfcd25c4ba68d0", "size": 3515, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "quadtree/index.tex", "max_stars_repo_name": "fa93hws/thesis", "max_stars_repo_head_hexsha": "c397ddc18e5ff5d6e9b8d6de2e53be4c9c7b7a2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-10-30T12:14:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-30T12:14:47.000Z", "max_issues_repo_path": "quadtree/index.tex", "max_issues_repo_name": "fa93hws/thesis", "max_issues_repo_head_hexsha": "c397ddc18e5ff5d6e9b8d6de2e53be4c9c7b7a2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "quadtree/index.tex", "max_forks_repo_name": "fa93hws/thesis", "max_forks_repo_head_hexsha": "c397ddc18e5ff5d6e9b8d6de2e53be4c9c7b7a2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.5762711864, "max_line_length": 200, "alphanum_fraction": 0.8102418208, "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.33558003255702734}}
{"text": "\\documentclass[../templatetop.tex]{subfiles}\n\n\\swd{contents/02_literature_review}\n\n\\begin{document}\n\n\\section{Position estimation using parameters}\n\nAfter estimating a  set of parameters form the received signals by one of techniques described in the previous section, the next step is to estimate the position from the obtained parameters.\nPosition estimation techniques can be divide into two category depending on the presence of a database that contain the signal measurements at known positions. A techniques that makes use of such a database which is usually obtain by training phase (off-line phase) before the real time positioning start, is called mapping (fingerprinting) technique. Other techniques that do not utilize such a database commonly employ \\textit{geometric} and \\textit{statistical} techniques to estimate the position using only parameters estimates form the first step.\n\n\\noindent In the absence of a database consisting of previous taken measurements at known positions, the position of the target node should be estimated directly from the available measurements obtained in the first step. Such position techniques can be considered in two groups, geometric and statistic techniques.\n\n\\subsection{Mapping techniques}\nMapping techniques use the available database in the system as training data and estimate the position of a target node by pattern-matching algorithms, such as \\textit{K-nearest-neighbor (k-NN)}, \\textit{support vector regression (SVR)} and \\textit{neural networks}.\n\nA mapping technique can be consider as a regression scheme that maps the input vector to an output vector by using a training set. Let the training set be represented by:\n\\begin{equation}\n    \\tau = \\{(m_1, p_1), (m_1, p_1),..., (m_{N_t}, p_{N_t})\\}\n\\end{equation}\nwhere $m_i$ represents the measurement vector for $i$th position $p_i$ ($p_i=\\begin{bmatrix} x_i & y_i \\end{bmatrix}^T$ for two-dimensional positioning) and $N_t$ is the total number of training set (the size of the database). For\n\nOne of the simplest regression techniques is to estimate the position of the target node as the position vector in the training set $\\tau$ corresponding to the measurement vector that has the shortest distance to the measurement vector $m$. In other words, the position is estimated as $p_j$, with:\n\\begin{equation}\n    j = \\argmin_{i \\in \\{1,..,N_t\\}} \\lVert m - m_i \\rVert\n\\end{equation}\nwhere $\\lVert m - m_i \\rVert$ represents the Euclidean distance between $m$ and $m_i$.\n\n\\subsection{Geometric approach}\n\nA geometric positioning technique solve for the position of the target node as intersection of position lines obtained from set of measurements at a number if reference nodes. For example, the RSS and TOA give us an uncertainty in the shape of a circle while the A0A give us an uncertainty in the shape of a line. In geometric approach, the position of the target node is determined by the intersection of uncertainty regions computed on several nodes.\n\nIn case of RSS or TOA, we need to know the distance of target node and three source nodes with known position, $d_i$, as shown in figure \\ref{fig:rss_toa_position_model}.\n\n\\begin{figure}[htbp]\n    \\centering\n    \\includegraphics[width=0.5\\textwidth]{rss_toa_position_model}\n    \\caption{The reference (black) nodes measure their distances (via RSS or TOA estimation) from the target node (gray node), which results in three circles passing through the target node. The intersection of the three circles can be calculated to obtain the position of the target node, which is called trilateration}\n    \\label{fig:rss_toa_position_model}\n\\end{figure}\n\nLet $d_1$, $d_2$, $d_3$ represent the range measurement obtained from three TOA and RSS measurements. Then, the following system of equations is solved in order to estimate the position of the target node via trilateration:\n\\begin{equation}\n    d_i = \\sqrt{(x_i -x)^2 + (y_i - y)^2}  \\mbox{,i = 1,2,3}\n    \\label{eq:rss_toa_system_of_equations}\n\\end{equation}\nwhere $(x_i, y_i)$ is the known position of the $i$th reference node, and $(x,y)$ is the position of the target node.\nThe position $(x,y)$ can be solved from \\ref{eq:rss_toa_system_of_equations} as:\n\\begin{equation}\n    x = \\frac{(y_2-y_1)\\gamma_1 + (y_2-y_3)\\gamma_2}{2[(x_2-x_3)(y_2-y_1) + (x_1-x_2)(y_2-y_3)]}\n\\end{equation}\n\\begin{equation}\n    y = \\frac{(x_2-x_1)\\gamma_1 + (x_2-x_3)\\gamma_2}{2[(x_2-x_1)(y_2-y_3) + (x_2-x_3)(y_1-y_2)]}\n\\end{equation}\nwhere\n\\begin{equation}\n    \\gamma_1 = x_2^2 - x_3^2 + y_2^2 - y_3^2 + d_3^2 - d_2^2;\n\\end{equation}\n\\begin{equation}\n    \\gamma_2 = x_1^2 - x_2^2 + y_1^2 - y_2^2 + d_2^2 - d_1^2;\n\\end{equation}\n\nUsing the AOA approach, we need only two source nodes (antenna arrays) to estimate the position of the target node. As depicted in figure \\ref{fig:aoa_position_model}, each AOA gives us an uncertainty in the shape of a line; so, we can estimate the target node's position as the intersection of these two lines.\n\n\\begin{figure}[htbp]\n    \\centering\n    \\includegraphics[width=0.5\\textwidth]{aoa_position_model}\n    \\caption{The angles measured by the reference (black) nodes determine two lines, the intersection of\n    which yields the target position. This technique is called triangulation}\n    \\label{fig:aoa_position_model}\n\\end{figure}\n\nEach line give us an equation like:\n\\begin{equation}\n    \\tan{\\psi} = \\frac{y-y_1}{x-x_1}, i = 1,2\n\\end{equation}\nSolving the equation jointly, we have:\n\\begin{equation}\n    x = \\frac{x_2\\tan{\\psi_2} - x_1\\tan{\\psi_1} + y_1 - y_2}{\\tan{\\psi_2} - \\tan{\\psi_1}}\n\\end{equation}\n\\begin{equation}\n    y = \\frac{(x_2-x_1)\\tan{\\psi_2}\\tan{\\psi_1} + y_1\\tan{\\psi_2} - y_2\\tan{\\psi_1}}{\\tan{\\psi_2}-\\tan{\\psi_1}}\n\\end{equation}\n\nIn case of the TDOA, we need three source nodes with known positions to obtain two TDOAs. As explained in previous section, TDOA is time difference of arrival of transmitted signals from the target node, between two source nodes. On TDOA gives us an uncertainty region in the shape of a hyperbola.\n\n\\begin{figure}[htbp]\n    \\centering\n    \\includegraphics[width=0.5\\textwidth]{tdoa_position_model}\n    \\caption{Each TDOA determines a hyperbola. The position of the target node is estimated by intersection of these two hyperbola}\n    \\label{fig:tdoa_position_model}\n\\end{figure}\n\nThe hyperbola region is described by the following equation:\n\\begin{equation}\n    d_{i1} = d_i - d_1 = \\sqrt{(x-x_i)^2 - (y-y_i)^2} - \\sqrt{(x-x_1)^2+(y-y_1)^2}, i =2,3\n    \\label{eq:tdoa_position_model}\n\\end{equation}\nwhere\n\\begin{equation}\n    d_1 = \\sqrt{(x-x_1)^2 - (y-y_1)^2}\n\\end{equation}\nThe position of the target node is estimated by solving the two equations of \\ref{eq:tdoa_position_model} jointly.\n\nSince geometric approaches cannot cope with practical noisy eviroments, usually statistical approaches are used in practice. In this noisy framework, we define a model for noisy measurement as:\n\n\\section{Statistic approach}\nSince geometric approaches cannot cope with noisy environments, usually statistical approach are used in practice. In this noisy framework, we define a model for noisy measurement as:\n\\begin{equation}\n    z = f(x,y) + \\eta\n\\end{equation}\nwhere $z$ is the results of a noisy measurement, $f(x,y)$ is the true value of this measurement which is the function of target node's position and $\\eta$ is the noise of this measurement. For the techniques discussed in previous section, $f(x,y)$ is as follows:\n\\begin{equation}\n    f(x,y) = \\begin{cases} \\sqrt{(x-x_s)^2 + (y-y_s)^2} & \\mbox{TOA, RSS} \n    \\\\ \\arctan{\\frac{y-y_s}{x-y_s}} & \\mbox{AOA}\n    \\\\ \\sqrt{(x-x_s)^2 + (y-y_s)^2} - \\sqrt{(x-x_{cs})^2 + (y-y_{cs}^2)} & \\mbox{TDOA}\n\\end{cases}\n\\end{equation}\nwhere $(x_s,y_s)$ is the known position of the source nodes, and $(x_{cs},y_{cs})$ is the position of common source node for the TDOA technique. In vector-space notation, the cited model is changed to:\n\\begin{equation}\n    \\mathbf{z} = \\mathbf{f}(x,y) + \\mathbf{\\eta}\n\\end{equation}\nwhere $\\mathbf{z} = [z_1,...,z_{N_m}]^T$, $\\mathbf{F}(x,y) = [f_1(x,y),...,f_{N_m}(x,y)]^T$ and $\\mathbf{\\eta}=[\\eta_1,...,\\eta_{N_m}]^T$. $N_m$ equal to the number if source node in TOA, RSS amd AOA approaches, and one less than the number of source nodes in the TDOA approach. Assume that the noise which affects our measurements is known except for a set of parameters, $\\lambda$. So, we have a vector of unknown parameters, $\\theta$, as:\n\\begin{equation}\n    \\mathbf{\\theta} = [xy\\mathbf{\\lambda}^T]^T\n\\end{equation}\nwhere $(x,y)$ is the position of the target node. In such problems, we can use parametric approaches to estimate the  true value of $\\mathbf{\\theta}$. Two prevalent parametric approaches are Bayesian and Maximum-Likelihood (ML). The Bayesian approach is usefull in case of prior information about $\\mathbf{\\theta}$ is available. The ML approach find $\\mathbf{\\theta}$ which gives the maximum probability for the observations. Formally, we can define $\\mathbf{\\theta}$ estimated by the ML $\\hat{\\mathbf{\\theta}}$ as:\n\\begin{equation}\n    \\hat{\\mathbf{\\theta}}_{ML} = \\argmax_{\\theta}p(\\mathbf{z}|\\mathbf{\\theta})\n\\end{equation}\nSince the function of $f(x,y)$ is deterministic, we can express the likelihood function $p(\\mathbf{z}|\\mathbf{\\theta})$ as:\n\\begin{equation}\n    p(\\mathbf{z}|\\mathbf{\\theta}) = p_{\\eta}(\\mathbf{z} - \\mathbf{f}(x,y) | \\mathbf{\\theta}) \n    \\label{eq:probability_density_function_of_the_noise}\n\\end{equation}\nwhere $p(.|\\mathbf{\\theta})$ is the conditional probability density function of the noise given parameter vector $\\mathbf{\\theta}$.\n\\subsubsection*{Position in the presence of the independent noise}\nIn case of the independent noise for all measurement, we can express equation \\ref{eq:probability_density_function_of_the_noise} as:\n\\begin{equation}\n    p(\\mathbf{z}|\\mathbf{\\theta}) = \\prod_{i=1}^{N_m}p_{\\eta_i}(z_i-f_i(x,y) | \\mathbf{\\theta})\n\\end{equation}\nwhere $z_i$ is the $i$th measurement, $f_i(x,y)$ is the true value of the $i$th measurement and the $p_{\\eta_i}$ is the conditional probability function of the $i$th measurement. The independent noise assumption is reasonable for the AOA, TOA and RSS approaches. However, in the case of TDOA, we have correlated noise for several source node's measurements due to the presence of the common source node. For system working under LOS conditions, the majority of the noise is thermal noise. We can model the noise of the environments as Gaussian zero mean random variable as:\n\\begin{equation}\n    p_{\\eta_i} = \\frac{1}{\\sqrt{2\\pi}\\sigma_i}\\exp{-\\frac{u^2}{2\\sigma_i^2}}\n\\end{equation}\n\\end{document}", "meta": {"hexsha": "a16c31cbbd6264ee9d40cad17bfbce660618e56c", "size": 10565, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "reports/02_theory/position_estimation_using_parameters.tex", "max_stars_repo_name": "tuannv0898/uwb-ips", "max_stars_repo_head_hexsha": "656725bfbb45eae48127733b7c4a96736bfacf84", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "reports/02_theory/position_estimation_using_parameters.tex", "max_issues_repo_name": "tuannv0898/uwb-ips", "max_issues_repo_head_hexsha": "656725bfbb45eae48127733b7c4a96736bfacf84", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-13T16:22:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:22:55.000Z", "max_forks_repo_path": "reports/02_theory/position_estimation_using_parameters.tex", "max_forks_repo_name": "tuannv0898/uwb-ips", "max_forks_repo_head_hexsha": "656725bfbb45eae48127733b7c4a96736bfacf84", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-14T02:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T02:31:16.000Z", "avg_line_length": 72.3630136986, "max_line_length": 573, "alphanum_fraction": 0.7429247515, "num_tokens": 3043, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.33558003255702734}}
{"text": "\\documentclass[10pt, a4paper, twoside]{basestyle}\n\\usepackage{tkz-euclide}\n\\usetkzobj{all}\n\\usepackage[Mathematics]{semtex}\n\\usepackage{chngcntr}\n\\counterwithout{equation}{section}\n\n%%%% Shorthands.\n\n%%%% Title and authors.\n\n\\newcommand{\\point}[1]{\\mathrm{#1}}\n\\newcommand{\\bipoint}[2]{\\overrightarrow{\\point #1 \\point #2}}\n\\newcommand{\\straightline}[2]{\\point #1 \\point #2}\n\\newcommand{\\plane}[3]{\\point #1 \\point #2 \\point #3}\n\\newcommand{\\squarenorm}[1]{\\scal{#1}{#1}}\n\n\\title{%\n\\textdisplay{%\nHiding Computations in Projection%\n}%\n}\n\\author{Pascal~Leroy (pleroy)}\n\\begin{document}\n\\maketitle\nThis document describes the computations that are performed by the method\n\\texttt{VisibleSegments} of class \\texttt{Perspective} to determine the parts of\na segment that are hidden by a sphere when seen from a pinhole camera.\n\nFigure~\\ref{fig3d} illustrates an example of the problem.  The points drawn in\nblack define the problem: $\\point A$ and $\\point B$ are the extremities of the\nsegment; $\\point C$ is the centre of the sphere; $R$ is the radius of the\nsphere; and $\\point K$ is the location of the camera.  The points drawn in red\nwill be computed as part of the resolution.  Of particular interest is the plane\n$\\plane KAB$, in which we willl do much of the analysis below.  The figure shows\nthe circle formed by the intersection of this plane with the sphere, as well as\n$\\point H$, the center of that circle and the projection of $\\point C$ on\n$\\plane KAB$.\n\\begin{figure}[htb!]\n\\centering\n\\includegraphics[scale=0.35]{Perspective-hiding-3d}\n\\caption{A 3-dimensional example.  In this case, the only segment visible from\n$\\point K$ is the part of $\\straightline AB$ between $\\point B$ and the red\npoint immediately to its left.\\label{fig3d}}\n\\end{figure}\n\n\\subsection*{Camera inside the sphere}\nWe start our analysis by eliminating a case that would cause anomalies in the\nanalysis below.  If\\[\n\\scal{\\bipoint KC}{\\bipoint KC} < R^2\n\\]\nthen the camera is inside the sphere and the segment is hidden irrespective of\nits position.\n\n\\subsection*{Sphere and segment in distinct half-spaces}\nConsider the plane containing $\\point K$ and orthogonal to $\\straightline KC$;\nit separates the entire space into two half-spaces.  If the segment\n$\\straightline AB$ is entirely within the half-space that does not contain\n$\\point C$ then the segment is not hidden (remember that $\\point K$ is not\ninside the sphere).  This is the case if the following inequalities are both\ntrue:\n\\begin{align*}\n\\scal{\\bipoint KA}{\\bipoint KC} &< 0\\\\\n\\scal{\\bipoint KB}{\\bipoint KC} &< 0\\text.\n\\end{align*}\n\n\\subsection*{Projection of $\\point C$ on $\\plane KAB$}\nFor simplicity we will do the rest of our analysis in the plane $\\plane KAB$ and\nwe will often use $\\tuple{\\bipoint KA, \\bipoint KB}$ as a basis of that plane.\nLet $\\point H$ be the orthogonal projection of $\\point C$ on $\\plane KAB$.\nand define $\\ga$, $\\gb$ to be its coordinates in\n$\\tuple{\\bipoint KA, \\bipoint KB}$\n\\[\n\\bipoint KH = \\ga \\bipoint KA + \\gb \\bipoint KB\\text.\n\\]\nNote that $\\bipoint KH = \\bipoint KC + \\bipoint CH$. By definition,\n$\\bipoint CH$ is orthogonal to both $\\bipoint KA$ and $\\bipoint KB$:\n\\begin{align*}\n\\scal{\\bipoint KA}{\\bipoint CH} &= 0\\\\\n\\scal{\\bipoint KB}{\\bipoint CH} &= 0\\text.\n\\end{align*}\nDecomposing $\\bipoint CH$ we obtain:\n\\begin{align*}\n\\scal{\\bipoint KA}{\\bipoint KH} &= \\scal{\\bipoint KA}{\\bipoint KC}\\\\\n\\scal{\\bipoint KB}{\\bipoint KH} &= \\scal{\\bipoint KB}{\\bipoint KC}\\text.\n\\end{align*}\nExpanding $\\bipoint KH$ on the basis $\\tuple{\\bipoint KA, \\bipoint KB}$ gives a\nlinear system of two equations with two unknowns:\n\\begin{align*}\n\\ga \\scal{\\bipoint KA}{\\bipoint KA} + \\gb \\scal{\\bipoint KA}{\\bipoint KB}\n    &= \\scal{\\bipoint KA}{\\bipoint KC}\\\\\n\\ga \\scal{\\bipoint KA}{\\bipoint KB} + \\ga \\scal{\\bipoint KB}{\\bipoint KB}\n    &= \\scal{\\bipoint KB}{\\bipoint KC}\\text.\n\\end{align*}\nThe determinant of this system is\\[\nD = \\pascal{\\squarenorm{\\bipoint KA}} \\pascal{\\squarenorm{\\bipoint KB}} -\n    \\pascal{\\scal{\\bipoint KA}{\\bipoint KB}}^2\\text,\n\\]\nwhich is non-zero if and only if $\\point A \\neq \\point B$. The solutions are\nthus:\n\\begin{align*}\n\\ga &= \\frac\n  {\\pascal{\\squarenorm{\\bipoint KB}} \\pascal{\\scal{\\bipoint KA}{\\bipoint KC}} -\n   \\pascal{\\scal{\\bipoint KA}{\\bipoint KB}}\n   \\pascal{\\scal{\\bipoint KB}{\\bipoint KC}}}\n  {D}\\\\\n\\gb &= \\frac\n  {\\pascal{\\squarenorm{\\bipoint KA}} \\pascal{\\scal{\\bipoint KB}{\\bipoint KC}} -\n   \\pascal{\\scal{\\bipoint KA}{\\bipoint KB}}\n   \\pascal{\\scal{\\bipoint KA}{\\bipoint KC}}}\n  {D}\\text.\n\\end{align*}\nOnce $\\bipoint KH$ is determined we can compute $\\bipoint CH =\n\\bipoint KH - \\bipoint KC$.  If $\\squarenorm{\\bipoint CH} \\geq R^2$, the sphere\nis either tangent to the plane $\\plane KAB$ or doesn't intersect it. In these\ncases, there is no hiding.\n\nIf the sphere intersects $\\plane KAB$, then the intersection is a circle whose\nradius we denote by $r$ in the rest of this analysis.  The radius is such that\n$r^2 = R^2 - \\squarenorm{\\bipoint CH}$.\n\n\\subsection*{An optimization where the circle is outside the wedge $\\plane KAB$}\n\\marginfig[Circle lying outside the wedge $\\plane KAB$ on the side of\n$\\straightline KB$.\\label{figOutside}]{\n\\begin{tikzpicture}[scale=0.5]\n\\tkzInit[ymin=-7,ymax=8,xmin=-1,xmax=9]\n\\tkzClip\n\\tkzDefPoint(3,5){A}\n\\tkzDefPoint(8,0){B}\n\\tkzDefPoint(4,-3){H}\n\\tkzDefPoint(0,0){K}\n\n\\tkzDefLine[orthogonal=through H](K,B) \\tkzGetPoint{h1}\n\\tkzInterLL(H,h1)(K,B) \\tkzGetPoint{N}\n\n\\tkzDefLine[parallel=through H](K,A) \\tkzGetPoint{h2}\n\\tkzInterLL(H,h2)(K,B) \\tkzGetPoint{M}\n\n\\tkzDefPointWith[linear,K=2](H,M) \\tkzGetPoint{m}\n\n\\tkzDefPointBy[rotation=center H angle -130](N) \\tkzGetPoint{r}\n\n\\tkzDrawPoints(A,B,H,K,M,N)\n\\tkzLabelPoint[left](A){$\\point A$}\n\\tkzLabelPoint[above](B){$\\point B$}\n\\tkzLabelPoint[left](H){$\\point H$}\n\\tkzLabelPoint[above left](K){$\\point K$}\n\\tkzLabelPoint[below right](M){$\\point M$}\n\\tkzLabelPoint[above left](N){$\\point N$}\n\n\\tkzDrawLine(K,A)\n\\tkzDrawLine(K,B)\n\\tkzDrawLine(H,N)\n\\tkzDrawLine[add=0.2 and 0.5](H,M)\n\n\\tkzDrawSegment[style=dashed](H,r)\n\\tkzLabelSegment[above right](H,r){$r$}\n\n\\tkzDrawCircle[R](H,3cm)\n\n\\tkzMarkRightAngle[size=0.5](H,N,M)\n\\tkzMarkAngle[size=0.5](B,K,A)\n\\tkzLabelAngle(A,K,B){$\\gq$}\n\\tkzMarkAngle[size=0.5](B,M,m)\n\\tkzLabelAngle(B,M,m){$\\gq$}\n\n\\end{tikzpicture}\n}\nA useful optimization at this stage is to determine if the circle intersects the\nwedge $\\plane KAB$.  If it does not, then there is no hiding and the segment\n$\\straightline AB$ is entirely visible.  This can happen because the circle is\naway from the wedge on the side of $\\straightline KA$ or because it is away from\nthe wedge on the side of $\\straightline KB$.  Figure~\\ref{figOutside}\nillustrates the latter case: note that the circle must not intersect\n$\\straightline KB$, so the distance between $\\point H$ and $\\straightline KB$\nmust be at least $r$; the figure shows the case where the circle is tangent to\n$\\straightline KB$ at $\\point N$, which is the one that interests us in this\nsection.\n\nObserve that, if $\\gq$ is the angle between $\\bipoint KA$ and $\\bipoint KB$, we\nhave\n\\[\n\\scal{\\bipoint KA}{\\bipoint KB} = \\norm{\\bipoint KA} \\norm{\\bipoint KB}\n                                  \\cos \\gq\n\\]\nLet $\\point M$ be the point where $\\point H$ projects on $\\straightline KB$\nparallel to $\\straightline KA$.  Since $\\ga$ and $\\gb$ are the coordinates of\n$\\bipoint KH$ in the basis $\\tuple{\\bipoint KA, \\bipoint KB}$, we\nhave\n\\begin{equation}\n{\\bipoint HM} = \\ga {\\bipoint KA} \\label{eqnhm1}\\text,\n\\end{equation}\nand elementary trigonometry in the triangle $\\plane HNM$ yields\n\\begin{equation}\n\\scal{\\bipoint HM}{\\bipoint HM} = \\frac{r^2} {\\sin^2 \\gq} =\n                                  \\frac{r^2} {1 - \\cos^2 \\gq}\n                                  \\label{eqnhm2}\\text.\n\\end{equation}\nEliminating $\\bipoint HM$ between equations (\\ref{eqnhm1}) and (\\ref{eqnhm2}) we\nobtain the following conditions on $\\ga$ for $\\point H$ to be outside the wedge\n$\\plane KAB$ on the side of $\\straightline KB$:\n\\begin{align*}\n\\ga &\\leq 0\\\\\n\\ga^2 &\\geq r^2 \\frac{\\squarenorm{\\bipoint KB}}\n                     {\\pascal{\\squarenorm{\\bipoint KA}}\n                      \\pascal{\\squarenorm{\\bipoint KB}} -\n                     {\\pascal{\\scal{\\bipoint KA}{\\bipoint KB}}}^2}\\text.\n\\end{align*}\nIt's straightforward to prove similar conditions on $\\gb$ for the circle to be\noutside the wedge $\\plane KAB$ on the side of $\\straightline KA$.\n\n\\subsection*{Construction of the cone}\n\\marginfig[Construction of $\\point P$ and $\\point P'$ and of the cone.\n\\label{figP}]{\n\\begin{tikzpicture}[scale=0.5]\n\\tkzInit[ymin=-5,ymax=10,xmin=-4,xmax=6]\n\\tkzClip\n\\tkzDefPoint(-3,9){A}\n\\tkzDefPoint(5.5,9){B}\n\\tkzDefPoint(2,5){H}\n\\tkzDefPoint(0,-4){K}\n\n\\tkzTangent[from with R=K](H,3cm) \\tkzGetPoints{P'}{P}\n\\tkzInterLL(K,P)(A,B) \\tkzGetPoint{Q}\n\n\\tkzDefPointBy[rotation=center H angle -130](P) \\tkzGetPoint{r}\n\n\\tkzDrawPoints(A,B,H,K,P,P',Q)\n\\tkzLabelPoint[below left](A){$\\point A$}\n\\tkzLabelPoint[above left](B){$\\point B$}\n\\tkzLabelPoint[below](H){$\\point H$}\n\\tkzLabelPoint[left](K){$\\point K$}\n\\tkzLabelPoint[above left](P){$\\point P$}\n\\tkzLabelPoint[below right](P'){$\\point P'$}\n\\tkzLabelPoint[above right](Q){$\\point Q$}\n\n\\tkzDrawLine[add=0.05 and 0.05](A,B)\n\\tkzDrawLine(H,P)\n\\tkzDrawLine(K,A)\n\\tkzDrawLine(K,B)\n\\tkzDrawLine(K,P')\n\\tkzDrawLine(K,Q)\n\n\\tkzDrawSegment[style=dashed](H,r)\n\\tkzLabelSegment[left](H,r){$r$}\n\n\\tkzDrawCircle[R](H,3cm)\n\n\\tkzMarkRightAngle[size=0.5](K,P,H)\n\n\\end{tikzpicture}\n}\nRemember that the circle of centre $\\point H$ and radius $r$ is the intersection\nof the sphere with the plane $\\plane KAB$.  As shown on figure~\\ref{fig3d},\nhiding is determined by the cone of apex $\\point K$ tangent to the sphere.  This\ncone intersects $\\plane KAB$ in two straight lines that go through $\\point K$\nand are tangent to the circle at points $\\point P$ and $\\point P'$.  In this\nsection we are going to determine the coordinates of $\\point P$ and $\\point P'$\nin the basis $\\tuple{\\bipoint KA, \\bipoint KB}$.  Figure~\\ref{figP} illustrates\nthe construction of these points.\n\n$\\point P$ is characterized by the two equations:\n\\begin{align}\n\\squarenorm{\\bipoint PH} &= r^2 \\label{eqnp1}\\\\\n\\scal{\\bipoint PH}{\\bipoint KP} &= 0 \\label{eqnp2}\\text.\n\\end{align}\nEquation (\\ref{eqnp2}) may be rewritten as\n\\[\n\\scal{\\bipoint PH}{\\pascal{\\bipoint KH + \\bipoint HP}} = 0\\text,\n\\]\nwhich yields, when combined with equation (\\ref{eqnp1})\n\\begin{equation}\n\\scal{\\bipoint PH}{\\bipoint KH} = r^2 \\label{eqnp3}\\text.\n\\end{equation}\nDefine now $\\gg$ and $\\gd$ to be the coordinates of $\\bipoint PH$ in\n$\\tuple{\\bipoint KA, \\bipoint KB}$\\[\n\\bipoint PH = \\gg {\\bipoint KA} + \\gd {\\bipoint KB}\\text.\n\\]\nEquation (\\ref{eqnp3}) is linear in the coordinates of $\\point P$ and can be\nrewritten as\\[\n\\gg\\scal{\\bipoint KA}{\\bipoint KH} + \\gd\\scal{\\bipoint KB}{\\bipoint KH} =\nr^2\\text.\n\\]\nNote that $\\scal{\\bipoint KA}{\\bipoint KH}$ and\n$\\scal{\\bipoint KB}{\\bipoint KH}$ cannot both be $0$ unless $\\point K$ is on\n$\\straightline AB$, so we can either express $\\gg$ as a function of $\\gd$ or\nvice-versa.  If we do the former we obtain\\[\n\\gg = \\frac{r^2 - \\gd \\scal{\\bipoint KB}{\\bipoint KH}}\n           {\\scal{\\bipoint KA}{\\bipoint KH}}\\text.\n\\]\nEquation (\\ref{eqnp1}) is quadratic in the coordinates of $\\point P$ and can be\nrewritten as\\[\n\\pa{\\gg\\bipoint KA + \\gd \\bipoint KB}^2 = r^2\\text.\n\\]\nPluging the value of $\\gg$ above we get\n\\begin{align*}\n\\gd^2\\pa{\n \\pascal{\\squarenorm{\\bipoint KB}} \\pascal{\\scal{\\bipoint KA}{\\bipoint KH}}^2 +\n 2\\pascal{\\scal{\\bipoint KA}{\\bipoint KB}}\n  \\pascal{\\scal{\\bipoint KA}{\\bipoint KH}}\n  \\pascal{\\scal{\\bipoint KB}{\\bipoint KH}} +\n \\squarenorm{\\bipoint KA} \\pascal{\\scal{\\bipoint KB}{\\bipoint KH}}^2} +&\\\\\n2\\gd r^2\\pa{\n \\pascal{\\scal{\\bipoint KA}{\\bipoint KB}}\n \\pascal{\\scal{\\bipoint KA}{\\bipoint KH}} -\n \\pascal{\\squarenorm{\\bipoint KA}}\n \\pascal{\\scal{\\bipoint KB}{\\bipoint KH}}} +&\\\\\nr^2\\pa{\n r^2\\pascal{\\squarenorm{\\bipoint KA}} -\n \\pascal{\\scal{\\bipoint KA}{\\bipoint KH}}^2} &= 0\\text.\n\\end{align*}\nThis equation always has two solutions because the sphere intersects\n$\\plane KAB$.\n\\subsection*{Intersection of the cone and the line $\\straightline AB$}\nHaving determined the location of points $\\point P$ and $\\point P'$ we need to\nfind the points $\\point Q$ and $\\point Q'$ where the lines $\\straightline KP$\nand $\\straightline KP'$, respectively, intersect the line $\\straightline AB$.\nSince $\\point Q$ is on $\\straightline AB$ there is a $\\gl$ such that\\[\n\\bipoint AQ = \\gl \\bipoint AB\\text,\n\\]\nor equivalently\n\\begin{equation}\n\\bipoint KQ - \\bipoint KA = \\gl \\bipoint AB \\label{eqnq1}\\text.\n\\end{equation}\nWe can take the scalar product of equation (\\ref{eqnq1}) with $\\bipoint PH$, and,\nnoting that $\\bipoint KQ$ is orthogonal to $\\bipoint PH$ we obtain\\[\n-\\scal{\\bipoint KA}{\\bipoint PH} = \\gl \\scal{\\bipoint AB}{\\bipoint PH}\n\\text{, or, }\n\\gl = -\\frac{\\scal{\\bipoint KA}{\\bipoint PH}}{\\scal{\\bipoint AB}{\\bipoint PH}}\n\\text.\n\\]\nObviously there is a similar equation with $\\point P'$ which may be used to\ncompute $\\gl'$, the position of $\\point Q'$ on $\\straightline AB$.\n\nThe point $\\point Q$ is in the segment $\\straightline AB$ if and only if\n$0 \\leq \\gl \\leq 1$.  This does not tell us, however, where $\\point Q$ is\nlocated with respect to the cone, to the sphere, or for that matter if it is\nin front or behind the camera.  This is what we need to determine next.\n\n\\marginfig[Definition of $\\point S$ and $\\point T$.\\label{figST}]{\n\\begin{tikzpicture}[scale=0.5]\n\\tkzInit[ymin=-5,ymax=12,xmin=-4,xmax=6]\n\\tkzClip\n\\tkzDefPoint(2,11){A}\n\\tkzDefPoint(5,-4){B}\n\\tkzDefPoint(0,0){H}\n\\tkzDefPoint(0,6){K}\n\n\\tkzTangent[from with R=K](H,3cm) \\tkzGetPoints{P2}{P}\n\n\\tkzDefLine[orthogonal=through P](K,H) \\tkzGetPoint{p}\n\\tkzInterLL(P,p)(A,B) \\tkzGetPoint{T}\n\\tkzInterLL(P,p)(K,H) \\tkzGetPoint{q}\n\n\\tkzDefLine[orthogonal=through K](K,H) \\tkzGetPoint{k}\n\\tkzInterLL(K,k)(A,B) \\tkzGetPoint{S}\n\n\\tkzInterLL(K,P)(A,B) \\tkzGetPoint{Q}\n\n\\tkzDefPointBy[rotation=center H angle -80](P) \\tkzGetPoint{r}\n\n\\tkzDrawPoints(A,B,H,K,P,Q,S,T)\n\\tkzLabelPoint[left](A){$\\point A$}\n\\tkzLabelPoint[left](B){$\\point B$}\n\\tkzLabelPoint[left](H){$\\point H$}\n\\tkzLabelPoint[left](K){$\\point K$}\n\\tkzLabelPoint[below left](P){$\\point P$}\n\\tkzLabelPoint[left](Q){$\\point Q$}\n\\tkzLabelPoint[above right](S){$\\point S$}\n\\tkzLabelPoint[above right](T){$\\point T$}\n\n\\tkzDrawLine[add=0.2 and 3](A,B)\n\\tkzDrawLine(H,K)\n\\tkzDrawLine[add=1 and 1](K,P)\n\\tkzDrawLine[add=1 and 1](K,P2)\n\\tkzDrawLine[add=0.05 and 0.2](K,S)\n\\tkzDrawLine[add=2.2 and 0.2](P,T)\n\n\\tkzDrawSegment[style=dashed](H,r)\n\\tkzLabelSegment[above right](H,r){$r$}\n\n\\tkzDrawCircle[R](H,3cm)\n\n\\tkzMarkRightAngle[size=0.5](S,K,H)\n\\tkzMarkRightAngle[size=0.5](P,q,H)\n\n\\end{tikzpicture}\n}\n\\subsection*{Location of $\\point Q$ and $\\point Q'$}\nHaving computed the values of $\\gl$ we need to determine where $\\point Q$ is\nlocated with respect to the cone, the sphere and the camera.  To do this we are\ngoing to define two new points, $\\point S$ and $\\point T$, as shown on\nfigure~\\ref{figST}.  $\\point S$ is the intersection of $\\straightline AB$ with\nthe line orthogonal to $\\straightline KH$ at $\\point K$.  $\\point T$ is the\nintersection of $\\straightline AB$ with the line orthogonal to\n$\\straightline KH$ at $\\point P$.  We are going to find the positions of\n$\\point S$ and $\\point T$ on $\\straightline AB$, and, by comparing then with\n$\\gl$, figure out the location of $\\point Q$ with respect to $\\point S$ and\n$\\point T$.\n\nWe locate $\\point S$ on $\\straightline AB$ as follows\\[\n\\bipoint KS = \\bipoint KA + \\gs \\bipoint AB\\text.\n\\]\nTaking the scalar product of this equation with $\\bipoint KH$, and noting that\n$\\bipoint KS$ is orthogonal to $\\bipoint KH$ we obtain\\[\n\\gs = -\\frac{\\scal{\\bipoint KA}{\\bipoint KH}}\n            {\\scal{\\bipoint AB}{\\bipoint KH}}\n\\]\nSimilarly, we locate $\\point T$ on $\\straightline AB$ as\\[\n\\bipoint KT = \\bipoint KA + \\gt \\bipoint AB\\text.\n\\]\nSince $\\bipoint KT = \\bipoint KH + \\bipoint HP + \\bipoint PT$ this can be\nwritten\\[\n\\bipoint PT = \\bipoint KA + \\gt \\bipoint AB - \\bipoint KH + \\bipoint PH\n\\]\nAgain, taking the scalar product of this equation with $\\bipoint KH$, and noting\nthat $\\bipoint KT$ is orthogonal to $\\bipoint KH$ we obtain\\[\n\\gt = \\frac{\\scal{\\bipoint KH}{\\bipoint KH} - \\scal{\\bipoint PH}{\\bipoint KH} -\n            \\scal{\\bipoint KA}{\\bipoint KH}}\n           {\\scal{\\bipoint AB}{\\bipoint KH}}\n\\]\nWe can now determine if $\\point Q$ (or alternatively, $\\gl$) is an\n``interesting'' intersection, i.e., one that intersects the cone behind the\nsphere when seen from the camera.  That's because the location of $\\point S$ let\nus separate what is behind the camera from what is in front of the camera, and\nthe location of $\\point T$ determines where the cone starts (points in front\nof $\\point T$ cannot be in the cone, although they can be in the sphere).\n\nFirst, assume that $\\point A$ and $\\point B$ are in the same order as $\\point S$\nand $\\point T$ on $\\straightline AB$.  Then we have $\\gs \\leq \\gt$ and the\nintersection $\\point Q$ is farther than $\\point T$ (as seen from the camera) if\nand only if $\\gt < \\gl$.  $\\point Q$ is located on the cone and it is an\ninteresting intersection (and it participates in hiding) if it falls within the\nsegment $\\straightline AB$.  This is the situation illustrated in\nfigure~\\ref{figST}.\n\nConversely, if $\\point A$ and $\\point B$ are in the reverse order\nas $\\point S$ and $\\point T$ on $\\straightline AB$ we have $\\gt \\leq \\gs$ and\nthe intersection is farther than $\\point T$ if and only if $\\gl < \\gt$.\n\nThe same analysis must be performed for $\\gl'$ corresponding to $\\point Q'$.\n\n\\subsection*{Point at infinity}\nThere is another special case that requires some care: if the line \n$\\straightline AB$ is in ``hyperbolic'' position, i.e., intersects both halves\nof the cone, then one of the values $\\gl$, $\\gl'$ is smaller than $\\gs$ and the\nother is greater than $\\gs$ (this is the situation shown in figure~\\ref{figST}).\nExactly one of $\\gl$, $\\gl'$ will be retained by the preceding analysis.  To\naccount for the fact that the points farther than $\\point Q$ (such as $\\point B$\nin figure~\\ref{figST}) are inside the cone, we need to add to our analysis an\nextra value of $\\gl$ equal to an infinity with the sign of $\\gt - \\gs$.\n\n\\marginfig[Intersection with the sphere.\\label{figSphere}]{\n\\begin{tikzpicture}[scale=0.5]\n\\tkzInit[ymin=-5,ymax=10,xmin=-3.8,xmax=6.2]\n\\tkzClip\n\\tkzDefPoint(-3,5){A}\n\\tkzDefPoint(5.5,5){B}\n\\tkzDefPoint(2,7){H}\n\\tkzDefPoint(0,-4){K}\n\n\\tkzTangent[from with R=K](H,3cm) \\tkzGetPoints{P'}{P}\n\\tkzInterLC[R](A,B)(H,3cm) \\tkzGetPoints{Q'}{Q}\n\n\\tkzDefPointBy[rotation=center H angle 100](Q') \\tkzGetPoint{r}\n\n\\tkzDrawPoints(A,B,H,K,P,P',Q,Q')\n\\tkzLabelPoint[below left](A){$\\point A$}\n\\tkzLabelPoint[below right](B){$\\point B$}\n\\tkzLabelPoint[left](H){$\\point H$}\n\\tkzLabelPoint[left](K){$\\point K$}\n\\tkzLabelPoint[left](P){$\\point P$}\n\\tkzLabelPoint[right](P'){$\\point P'$}\n\\tkzLabelPoint[below left](Q){$\\point Q$}\n\\tkzLabelPoint[above left](Q'){$\\point Q'$}\n\n\\tkzDrawLine[add=0.05 and 0.05](A,B)\n\\tkzDrawLine(K,A)\n\\tkzDrawLine(K,B)\n\\tkzDrawLine[add=-0.9 and 0.1](K,P)\n\\tkzDrawLine[add=-0.9 and 0.1](K,P')\n\n\\tkzDrawSegment[style=dashed](H,r)\n\\tkzLabelSegment[left](H,r){$r$}\n\n\\tkzDrawCircle[R](H,3cm)\n\n\\end{tikzpicture}\n}\n\\subsection*{Intersection with the circle}\nTo complete the analysis we need to compute the intersection $\\point Q$ of the\ncircle with the line $\\straightline AB$. $\\point Q$ is on the circle, thus\n\\begin{equation}\n\\squarenorm{\\bipoint HQ} = r^2 \\label{eqnq2}\\text;\n\\end{equation}\nit is also on the line $\\straightline AB$ and therefore there is a $\\gm$ such\nthat\n\\[\n\\bipoint KQ = \\bipoint KA + \\gm \\bipoint AB\\text.\n\\]\nWe can rewrite $\\bipoint HQ$ as follows\\[\n\\bipoint HQ = \\bipoint KQ - \\bipoint KH =\n  \\bipoint KA + \\gm \\bipoint AB - \\bipoint KH =\n  \\bipoint HA + \\gm \\bipoint AB\\text.\n\\]\nInserting this value in equation (\\ref{eqnq2}) we obtain\\[\nr^2 = \\pascal{\\bipoint HA + \\gm \\bipoint AB}^2\\text,\n\\]\nmeaning that $\\gm$ is a solution of\\[\n\\gm \\squarenorm{\\bipoint AB} + 2 \\gm \\scal{\\bipoint HA}{\\bipoint AB}\n+ \\squarenorm{\\bipoint HA} - R^2 = 0\\text.\n\\]\nDepending on the location of $\\straightline AB$ with respect to the circle,\nthere can be $0$, $1$, or $2$ intersections.\n\n\\subsection*{Concluding the analysis}\nIf we take the union of the values of $\\gl$ and $\\gm$ and order them, it is\nstraightforward to find the visible segments by remembering that\n$0 \\leq \\gl,\\gm \\leq 1$ for the points that are in the segment\n$\\straightline AB$.\n\\end{document}\n", "meta": {"hexsha": "a695480fce0e30199b174c107dd9e2becbceb49f", "size": 20515, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "documentation/Perspective hiding.tex", "max_stars_repo_name": "tnuvoletta/Principia", "max_stars_repo_head_hexsha": "25cf2fb70c512cf86a842ed525f6ab10e57f937c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-02-23T19:32:16.000Z", "max_stars_repo_stars_event_max_datetime": "2015-04-07T03:55:53.000Z", "max_issues_repo_path": "documentation/Perspective hiding.tex", "max_issues_repo_name": "tnuvoletta/Principia", "max_issues_repo_head_hexsha": "25cf2fb70c512cf86a842ed525f6ab10e57f937c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "documentation/Perspective hiding.tex", "max_forks_repo_name": "tnuvoletta/Principia", "max_forks_repo_head_hexsha": "25cf2fb70c512cf86a842ed525f6ab10e57f937c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.3007662835, "max_line_length": 81, "alphanum_fraction": 0.6951011455, "num_tokens": 7045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.33549513507827744}}
{"text": "\\section{Experiments}\n\\label{sec:supp-experiments}\n\nIn the following, we provide additional details on our experimental setup regarding (a) the used attacks, especially our \\PGD-\\FConf attack including pseudo-code in \\secref{subsec:supp-experiments-attacks}, (b) training of \\AdvTrain and \\ConfTrain in \\secref{subsec:supp-experiments-training}, (c) the evaluated baselines in \\secref{subsec:supp-experiments-baselines} and (d) the used evaluation metrics in \\secref{subsec:supp-experiments-evaluation}. Afterwards, we include additional experimental results, including ablation studies in \\secref{subsec:supp-experiments-ablation}, qualitative results for analysis in \\secref{subsec:supp-experiments-analysis}, and further results for $95\\%$ and $98\\%$ true positive rate (TPR), results per attack and results per corruption on MNIST-C \\citep{MuICMLWORK2019} and Cifar10-C \\citep{HendrycksARXIV2019} in \\secref{subsec:supp-experiments-results}.\n\n\\subsection{Attacks}\n\\label{subsec:supp-experiments-attacks}\n\n\\textbf{Projected Gradient Descent (\\PGD):}\n%\nComplementary to the description of the projected gradient descent (\\PGD) attack by \\cite{MadryICLR2018} and our adapted attack, we provide a detailed algorithm in \\algref{alg:supp-pgd}. We note that the objective maximized in \\citep{MadryICLR2018} is\n\\begin{align}\n    \\mathcal{F}(x + \\delta, y) = \\cL(f(x + \\delta; w), y)\\label{eq:supp-attack}\n\\end{align}\nwhere $\\mathcal{L}$ denotes the cross-entropy loss, $f(\\cdot;w)$ denotes the model and $(x,y)$ is an input-label pair from the test set. Our adapted attack, in contrast, maximizes\n\\begin{align}\n    \\mathcal{F}(x + \\delta, y) = \\max_{k\\neq y}f_k(x + \\delta;w)\\label{eq:supp-conf-attack}\n\\end{align}\nwhere $f_k$ denotes the confidence of $f$ in class $k$. Note that the maximum over labels, \\ie, $\\max_{k\\neq y}$, is explicitly computed during optimization; this means that in contrast to \\citep{GoodfellowOPENREVIEW2019}, we do not run $(K - 1)$ targeted attacks and subsequently take the maximum-confidence one, where $K$ is the number of classes. We denote these two variants as \\PGD-\\FCE and \\PGD-\\FConf, respectively. Deviating from \\citep{MadryICLR2018}, we initialize $\\delta$ uniformly over directions and norm (instead of uniform initialization over the volume of the $\\epsilon$-ball):\n\\begin{align}\n    \\delta = u\\epsilon \\frac{\\delta'}{\\|\\delta'\\|_\\infty},\\quad\\delta' \\sim \\mathcal{N}(0, I),u\\sim U(0,1)\\label{eq:supp-initialization}\n\\end{align}\nwhere $\\delta'$ is sampled from a standard Gaussian and $u \\in [0,1]$ from a uniform distribution. We also consider zero initialization, \\ie, $\\delta = 0$. For random initialization we always consider multiple restarts, $10$ for \\PGD-\\FConf and $50$ for \\PGD-\\FCE; for zero initialization, we use $1$ restart. Finally, in contrast to \\cite{MadryICLR2018}, we run \\PGD for exactly $T$ iterations, taking the perturbation corresponding to the best objective value obtained throughout the optimization.\n\n\\begin{algorithm*}[t]\n    \\caption{\\textbf{Projected Gradient Descent (\\PGD) with Backtracking.} Pseudo-code for the used \\PGD procedure to maximize \\eqnref{eq:supp-attack} or \\eqnref{eq:supp-conf-attack} using momentum and backtracking subject to the constraints $\\tilde{x}_i = x_i + \\delta_i \\in [0,1]$ and $\\|\\delta\\|_\\infty \\leq \\epsilon$; in practice, the procedure is applied on batches of inputs. The algorithm is easily adapted to work with arbitrary $L_p$-norm; only the projections on Line \\ref{line:projection1} and \\ref{line:projection2} as well as the normalized gradient in Line \\ref{line:normalized-grad} need to be adapted.}\n    \\label{alg:supp-pgd}\n    \\begin{algorithmic}[1]\n        \\small\n        \\STATEx \\textbf{input:} example $x$ with label $y$\n        \\STATEx \\textbf{input:} number of iterations $T$\n        \\STATEx \\textbf{input:} learning rate $\\gamma$, momentum $\\beta$, learning rate factor $\\alpha$\n        \\STATEx \\textbf{input:} initial $\\delta^{(0)}$, \\eg, \\eqnref{eq:supp-initialization} or $\\delta^{(0)} = 0$\n        \\STATE $v := 0$ \\COMMENT{saves the best objective achieved}\n        \\STATE $\\tilde{x} := x + \\delta^{(0)}$ \\COMMENT{best adversarial example obtained}\n        \\STATE $g^{(-1)} := 0$ \\COMMENT{accumulated gradients}\n        \\FOR{$t = 0,\\ldots,T$}\n        \\STATE \\COMMENT{projection onto $L_\\infty$ $\\epsilon$-ball and on $[0,1]$:}\n        \\STATE clip $\\delta^{(t)}_i$ to $[-\\epsilon, \\epsilon]$\\label{line:projection1}\n        \\STATE clip $x_i + \\delta^{(t)}_i$ to $[0,1]$\n        \\STATE \\COMMENT{forward and backward pass to get objective and gradient:}\n        \\STATE $v^{(t)} := \\mathcal{F}(x + \\delta^{(t)}, y)$ \\COMMENT{see \\eqnref{eq:supp-attack} or \\eqnref{eq:supp-conf-attack}}\n        \\STATE $g^{(t)} := \\text{sign}\\left(\\nabla_{\\delta^{(t)}} \\mathcal{F}(x + \\delta^{(t)}, y)\\right)$\\label{line:normalized-grad}\n        \\STATE \\COMMENT{keep track of adversarial example resulting in best objective:}\n        \\IF{$v^{(t)} > v$}\n        \\STATE $v := v^{(t)}$\n        \\STATE $\\tilde{x} := x + \\delta^{(t)}$\n        \\ENDIF\n        \\STATE \\COMMENT{iteration $T$ is only meant to check whether last update improved objective:}\n        \\IF{$t = T$}\n        \\STATE \\textbf{break}\n        \\ENDIF\n        \\STATE \\COMMENT{integrate momentum term:}\n        \\STATE $g^{(t)} := \\beta g^{(t - 1)} + (1 - \\beta)g^{(t)}$\n        \\STATE \\COMMENT{``try'' the update step and see if objective increases:}\n        \\STATE $\\hat{\\delta}^{(t)} := \\delta^{(t)} + \\gamma g^{(t)}$\n        \\STATE clip $\\hat{\\delta}^{(t)}_i$ to $[-\\epsilon, \\epsilon]$\\label{line:projection2}\n        \\STATE clip $x_i + \\hat{\\delta}^{(t)}_i$ to $[0,1]$\n        \\STATE $\\hat{v}^{(t)} := \\mathcal{F}(x + \\hat{\\delta}^{(t)}, y)$\n        \\STATE \\COMMENT{only keep the update if the objective increased; otherwise decrease learning rate:}\n        \\IF{$\\hat{v}^{(t)} \\geq v^{(t)}$}\n        \\STATE $\\delta^{(t + 1)} := \\hat{\\delta}^{(t)}$\n        \\ELSE\n        \\STATE $\\gamma := \\nicefrac{\\gamma}{\\alpha}$\n        \\ENDIF\n        \\ENDFOR\n        \\STATE \\textbf{return} $\\tilde{x}$, $\\tilde{v}$\n    \\end{algorithmic}\n\\end{algorithm*}\n\\begin{table*}[t]\n    \\centering\n    \\begin{subfigure}{1\\textwidth}\n        \\centering\n        \\footnotesize\n        \\input{tab_mmnist_attack_99tpr}\n    \\end{subfigure}\n    \\vskip 2px\n    \\begin{subfigure}{1\\textwidth}\n        \\centering\n        \\footnotesize\n        \\input{tab_msvhn_attack_99tpr}\n    \\end{subfigure}\n    \\vskip 2px\n    \\begin{subfigure}{1\\textwidth}\n        \\centering\n        \\footnotesize\n        \\input{tab_mcifar10_attack_99tpr}\n    \\end{subfigure}\n    \\vskip -6px\n    \\caption{\\textbf{Detailed Attack Ablation Studies.} We compare our $L_\\infty$ \\PGD-\\FConf attack with $T$ iterations and different combinations of momentum, backtracking and initialization on all three datasets. We consider \\AdvTrain, \\AdvTrain trained with \\PGD-\\FConf (\\AdvTrain\\FConf), and \\ConfTrain; we report \\RTE for confidence threshold $\\tau$@$99\\%$TPR. As backtracking requires an additional forward pass per iteration, we use $T = 60$ and $T = 300$ for attacks without backtracking to be comparable to attacks with $T = 40$ and $T = 200$ with backtracking. Against \\ConfTrain, $T=1000$ iterations or more are required and backtracking is essential to achieve high \\RTE. \\AdvTrain, in contrast, is ``easier'' to attack, requiring less iterations and less sophisticated optimization (\\ie, without momentum and/or backtracking).}\n    \\label{tab:supp-experiments-attack}\n\\end{table*}\n\\begin{table}[t]\n    \\centering\n    \\begin{subfigure}[t]{1\\textwidth}\n        \\vspace*{0px}\n        \n        \\centering\n        \\footnotesize\n        \\input{tab_msvhn_training_99tpr}\n    \\end{subfigure}\n    \\vskip 2px\n    \\begin{subfigure}[t]{1\\textwidth}\n        \\vspace*{0px}\n        \n        \\centering\n        \\footnotesize\n        \\input{tab_mcifar10_training_99tpr}\n    \\end{subfigure}\n    \\vskip -6px\n    \\caption{\\textbf{Training Ablation Studies.} We report unthresholded \\RTE and \\TE, \\ie, $\\tau = 0$ (``Standard Setting''), and $\\tau$@$99\\%$TPR as well as ROC AUC (``Detection Setting'') for \\ConfTrain with various values for $\\rho$. The models are tested against our $L_\\infty$ \\PGD-\\FConf attack with $T = 1000$ iterations and zero as well as random initialization. On Cifar10, $\\rho = 10$ works best and performance stagnates for $\\rho > 10$. On SVHN, we also use $\\rho = 10$, although $\\rho = 6$ shows better results.}\n    \\label{tab:supp-experiments-training}\n\\end{table}\n\\begin{figure*}[t]\n    \\begin{subfigure}[t]{0.485\\textwidth}\n        \\vspace*{0px}\n        \n        \\centering\n        \\textbf{MNIST} (worst-case of $L_\\infty$ attacks with $\\epsilon = 0.3$)\n        \n        \\begin{subfigure}[t]{0.49\\textwidth}\n            \\vspace*{0px}\n            \n            \\centering\n            \\includegraphics[width=1\\textwidth]{fig_mnist_corr_advtrain}\n            \n            \\includegraphics[width=1\\textwidth]{fig_mnist_succ_advtrain}\n        \\end{subfigure}\n        \\begin{subfigure}[t]{0.49\\textwidth}\n            \\vspace*{0px}\n            \n            \\centering\n            \\includegraphics[width=1\\textwidth]{fig_mnist_corr_ours10}\n            \n            \\includegraphics[width=1\\textwidth]{fig_mnist_succ_ours10}\n        \\end{subfigure}\n    \\end{subfigure}\n    \\hfill\\vrule\\hfill\n    \\begin{subfigure}[t]{0.485\\textwidth}\n        \\vspace*{0px}\n        \n        \\centering\n        \\textbf{Cifar10} (worst-case of $L_\\infty$ attacks with $\\epsilon = 0.03$)\n        \n        \\begin{subfigure}[t]{0.49\\textwidth}\n            \\vspace*{0px}\n            \n            \\centering\n            \\includegraphics[width=1\\textwidth]{fig_cifar10_corr_advtrain}\n            \n            \\includegraphics[width=1\\textwidth]{fig_cifar10_succ_advtrain}\n        \\end{subfigure}\n        \\begin{subfigure}[t]{0.49\\textwidth}\n            \\vspace*{0px}\n            \n            \\centering\n            \\includegraphics[width=1\\textwidth]{fig_cifar10_corr_ours10}\n            \n            \\includegraphics[width=1\\textwidth]{fig_cifar10_succ_ours10}\n        \\end{subfigure}\n    \\end{subfigure}\n    \\vskip -6px\n    \\caption{\\textbf{Confidence Histograms.} We show histograms of confidences on correctly classified test examples (top) and on adversarial examples (bottom) for both \\AdvTrain and \\ConfTrain. Note that for \\AdvTrain, the number of successful adversarial examples is usually lower than for \\ConfTrain. For \\ConfTrain in contrast, nearly all adversarial examples are successful, while only a part has high confidence. Histograms obtained for the worst-case adversarial examples across all  tested $L_\\infty$ attacks with $\\epsilon = 0.3$ and $\\epsilon = 0.03$ on MNIST and Cifar10, respectively.}\n    \\label{fig:supp-experiments-histograms}\n\\end{figure*}\n\n\\textbf{\\PGD for $\\boldsymbol{L_p}$, $\\boldsymbol{p \\in \\{0, 1, 2\\}}$:}\n%\nBoth \\PGD-\\FCE and \\PGD-\\FConf can also be applied using the $L_2$, $L_1$ and $L_0$ norms following the description above. Then, gradient normalization in Line \\ref{line:normalized-grad} of \\algref{alg:supp-pgd}, the projection in Line \\ref{line:projection1}, and the initialization in \\eqnref{eq:supp-initialization} need to be adapted. For the $L_2$ norm, the gradient is normalized by dividing by the $L_2$ norm; for the $L_1$ norm only the $1\\%$ largest values (in absolute terms) of the gradient are kept and normalized by their $L_1$ norm; and for the $L_0$ norm, the gradient is normalized by dividing by the $L_1$ norm. We follow the algorithm of \\cite{DuchiICML2008} for the $L_1$ projection; for the $L_0$ projection (onto the $\\epsilon$-ball for $\\epsilon \\in \\mathbb{N}_0$), only the $\\epsilon$ largest values are kept. Similarly, initialization for $L_2$ and $L_1$ are simple by randomly choosing a direction (as in \\eqnref{eq:supp-initialization}) and then normalizing by their norm. For $L_0$, we randomly choose pixels with probability $(\\frac{2}{3}\\epsilon)/(HWD)$ and set them to a uniformly random values $u \\in [0,1]$, where $H \\times W \\times D$ is the image size. In experiments, we found that tuning the learning rate for \\PGD with $L_1$ and $L_0$ constraints (independent of the objective, \\ie, \\eqnref{eq:supp-attack} or \\eqnref{eq:supp-conf-attack}) is much more difficult. Additionally, \\PGD using the $L_0$ norm seems to get easily stuck in sub-optimal local optima.\n\n\\textbf{Backtracking:}\n%\n\\algref{alg:supp-pgd} also gives more details on the employed momentum and backtracking scheme. These two ``tricks'' add two additional hyper-parameters to the number of iterations $T$ and the learning rate $\\gamma$, namely the momentum parameter $\\beta$ and the learning rate factor $\\alpha$. After each iteration, the computed update, already including the momentum term, is only applied if this improves the objective. This is checked through an additional forward pass. If not, the learning rate is divided by $\\alpha$, and the update is rejected. \\algref{alg:supp-pgd} includes this scheme as an algorithm for an individual test example $x$ with label $y$ for brevity; however, extending it to work on batches is straight-forward. However, it is important to note that the learning rate is updated per test example individually. In practice, for \\PGD-\\FCE, with $T = 200$ iterations, we use $\\gamma = 0.05$, $\\beta = 0.9$ and $\\alpha = 1.25$; for \\PGD-\\FConf, with $T = 1000$ iterations, we use $\\gamma = 0.001$, $\\beta = 0.9$ and $\\alpha = 1.1$.\n\n\\textbf{Black-Box Attacks:}\n%\nWe also give more details on the used black-box attacks. For random sampling, we apply \\eqnref{eq:supp-initialization} $T = 5000$ times. We also implemented the Query-Limited (QL) black-box attack of \\cite{IlyasICML2018} using a population of $50$ and variance of $0.1$ for estimating the gradient in Line \\ref{line:normalized-grad} of \\algref{alg:supp-pgd}; a detailed algorithm is provided in \\citep{IlyasICML2018}. We use a learning rate of $0.001$ (note that the gradient is signed, as in \\citep{MadryICLR2018}) and also integrated a momentum with $\\beta = 0.9$ and backtracking with $\\alpha = 1.1$ and $T = 1000$ iterations. We use zero and random initialization; in the latter case we allow $10$ random restarts. For the Simple black-box attack we follow the algorithmic description in \\citep{NarodytskaCVPRWORK2017} considering only axis-aligned perturbations of size $\\epsilon$ per pixel. We run the attack for $T = 1000$ iterations and allow $10$ random restarts. Following, \\cite{KhouryARXIV2018}, we further use the Geometry attack for $T = 1000$ iterations. Random sampling, QL, Simple and Geometry attacks are run for arbitrary $L_p$, $p \\in \\{\\infty, 2, 1, 0\\}$. For $L_\\infty$, we also use the Square attack proposed in \\citep{AndriushchenkoARXIV2019} with $T = 5000$ iterations with a probability of change of $0.05$. For all attacks, we use \\eqnref{eq:supp-conf-attack} as objective. Finally, for $L_0$, we also use Corner Search \\cite{CroceICCV2019} with the cross-entropy loss as objective, for $T = 200$ iterations. We emphasize that, except for QL, these attacks are not gradient-based and do not approximate the gradient. Furthermore, we note that all attacks except Corner Search are adapted to explicitly attack \\ConfTrain by maximizing \\eqnref{eq:supp-conf-attack}.\n\n\\subsection{Training}\n\\label{subsec:supp-experiments-training}\n\nWe follow the ResNet-20 architecture by \\cite{HeCVPR2016} implemented in PyTorch \\citep{PaszkeNIPSWORK2017}. For training we use a batch size of $100$ and train for $100$ and $200$ epochs on MNIST and SVHN/Cifar10, respectively: this holds for normal training, adversarial training (\\AdvTrain) and confidence-calibrated adversarial training (\\ConfTrain). For the latter two, we use \\PGD-\\FCE and \\PGD\\FConf, respectively, for $T = 40$ iterations including momentum and backtracking ($\\beta = 0.9$, $\\alpha = 1.5$). For \\PGD-\\FCE we use a learning rate of $0.05$, $0.01$ and $0.005$ on MNIST, SVHN and Cifar10. For \\PGD-\\FConf we use a learning rate of $0.005$. For \\ConfTrain, we randomly switch between the initialization in \\eqnref{eq:supp-initialization} and zero initialization. For training, we use standard stochastic gradient descent, starting with a learning rate of $0.1$ on MNIST/SVHN and $0.075$ on Cifar10. The learning rate is multiplied by $0.95$ after each epoch. We do not use weight decay; but the network includes batch normalization \\citep{IoffeICML2015}. On SVHN and Cifar10, we use random cropping, random flipping (only Cifar10) and contrast augmentation during training. We always train on $50\\%$ clean and $50\\%$ adversarial examples per batch, \\ie, each batch contains both clean and adversarial examples which is important when using batch normalization.\n\n\\subsection{Baselines}\n\\label{subsec:supp-experiments-baselines}\n\nAs baseline, we use the multi-steepest descent (\\Wong) adversarial training of \\cite{MainiICML2020}, using the code and models provided in the official repository\\footnote{\\url{https://github.com/locuslab/robust_union}}. The models correspond to a LeNet-like \\cite{LecunIEEE1998} architecture on MNIST, and the pre-activation version of ResNet-18 \\cite{HeCVPR2016} on Cifar10. The models were trained with $L_\\infty$, $L_2$ and $L_1$ adversarial examples and $\\epsilon$ set to $0.3, 1.5, 12$ and $0.03, 0.5, 12$, respectively. We attacked these models using the same setup as used for standard \\AdvTrain and our \\ConfTrain. \n\nAdditionally, we compare to \\TRADES \\cite{ZhangICML2019} using the code and pre-trained models from the official repository\\footnote{\\url{https://github.com/yaodongyu/TRADES}}. The models correspond to a convolutional architecture with four convolutional and three fully-connected layers \\cite{CarliniSP2017} on MNIST, and a wide ResNet, specifically WRN-10-28 \\cite{ZagoruykoBMVC2016}, on Cifar10. Both are trained using \\emph{only} $L_\\infty$ adversarial examples with $\\epsilon = 0.3$ and $\\epsilon = 0.03$, respectively. The evaluation protocol follows the same setup as used for standard \\AdvTrain and \\ConfTrain.\n\nOn Cifar10, we also use the pre-trained ResNet-50 from \\cite{MadryICLR2018} obtained from the official repository\\footnote{\\url{https://github.com/MadryLab/robustness}}. The model was trained on $L_\\infty$ adversarial examples with $\\epsilon = 0.03$. The same evaluation as for \\ConfTrain applies.\n\nFurthermore, we evaluate two detection baseline: the Mahalanobis detector (\\Lee) of \\cite{MaICLR2018} and the local intrinsic dimensionality (\\Ma) detector of \\cite{LeeNIPS2018}.\nWe used the code provided by \\cite{LeeNIPS2018} from the official repository\\footnote{\\url{https://github.com/pokaxpoka/deep_Mahalanobis_detector}}. For evaluation, we used the provided setup, adding \\emph{only} \\PGD-\\FCE and \\PGD-\\FConf with $T=1000$, $T=200$ and $T = 40$. For $T=1000$, we used $5$ random restarts, for $T=200$, we used $25$ restarts, and for $T = 40$, we used one restart. These were run for $L_\\infty$, $L_2$, $L_1$ and $L_0$. We also evaluated distal adversarial examples as in the main paper. While the hyper-parameters were chosen considering our $L_\\infty$ \\PGD-\\FCE attack ($T = 40$, one restart) and kept fixed for other threat models, the logistic regression classifier trained on the computed statistics (\\eg, the Mahalanobis statistics) is trained for each threat model individually, resulting in an advantage over \\AdvTrain and \\ConfTrain. For worst-case evaluation, where we keep the highest-confidence adversarial example per test example for \\ConfTrain, we use the obtained detection score instead. This means, for each test example individually, we consider the adversarial example with worst detection score for evaluation.\n\n\\subsection{Evaluation Metrics}\n\\label{subsec:supp-experiments-evaluation}\n\nComplementing the discussion in the main paper, we describe the used evaluation metrics and evaluation procedure in more detail. Adversarial examples are computed on the first 1000 examples of the test set; the used confidence threshold is computed on the last 1000 examples of the test set; test errors are computed on all test examples minus the last 1000. As we consider multiple attacks, and some attacks allow multiple random restarts, we always consider the worst case adversarial example per test example and across all attacks/restarts; the worst-case is selected based on confidence.\n\n\\textbf{FPR and ROC AUC:}\n%\nTo compute receiver operating characteristic (ROC) curves, and the area under the curve, \\ie, ROC AUC, we define negatives as \\emph{successful} adversarial examples (corresponding to correctly classified test examples) and positives as the corresponding \\emph{correctly classified} test examples. The ROC AUC as well as the curve itself can easily be calculated using scikit-learn \\citep{PedregosaJMLR2011}. Practically, the generated curve could be used to directly estimate a threshold corresponding to a pre-determined true positive rate (TPR). However, this requires interpolation; after trying several interpolation schemes, we concluded that the results are distorted significantly, especially for TPRs close to $100\\%$. Thus, we follow a simpler scheme: on a held out validation set of size $1000$ (the last 1000 samples of the test set), we sorted the corresponding confidences, and picked the confidence threshold in order to obtain (at least) the desired TPR, \\eg, $99\\%$.\n\n\\begin{figure*}[t]\n    \\begin{subfigure}[t]{0.485\\textwidth}\n        \\vspace*{0px}\n        \n        \\centering\n        \\textbf{MNIST} (worst-case of $L_\\infty$ attacks with $\\epsilon = 0.3$)\n        \n        \\begin{subfigure}[t]{0.47\\textwidth}\n            \\vspace*{0px}\n            \n            \\centering\n            \\includegraphics[height=3.5cm]{fig_mnist_roc}\n        \\end{subfigure}\n        \\begin{subfigure}[t]{0.49\\textwidth}\n            \\vspace*{0px}\n            \n            \\centering\t\t\t\n            \\includegraphics[height=3.5cm]{fig_mnist_rte}\n        \\end{subfigure}\n        \\begin{subfigure}{0.925\\textwidth}\n            \\fbox{\n                \\hspace*{1.5cm}\\includegraphics[width=0.6\\textwidth]{fig_mnist_legend}\\hspace*{1.5cm}\n            }\n        \\end{subfigure}\n    \\end{subfigure}\n    \\hfill\n    \\vrule\n    \\hfill\n    \\begin{subfigure}[t]{0.485\\textwidth}\n        \\vspace*{0px}\n        \n        \\centering\n        \\textbf{Cifar10} (worst-case of $L_\\infty$ attacks with $\\epsilon = 0.03$)\n        \n        \\begin{subfigure}[t]{0.47\\textwidth}\n            \\vspace*{0px}\n            \n            \\centering\n            \\includegraphics[height=3.5cm]{fig_cifar10_roc}\n        \\end{subfigure}\n        \\begin{subfigure}[t]{0.49\\textwidth}\n            \\vspace*{0px}\n            \n            \\centering\t\t\t\n            \\includegraphics[height=3.5cm]{fig_cifar10_rte}\n        \\end{subfigure}\n        \\begin{subfigure}{0.925\\textwidth}\n            \\fbox{\n                \\hspace*{1.5cm}\\includegraphics[width=0.6\\textwidth]{fig_cifar10_legend}\\hspace*{1.5cm}\n            }\n        \\end{subfigure}\n    \\end{subfigure}\n    \\vskip -6px\n    \\caption{\\textbf{ROC and \\RTE curves.} ROC curves, \\ie FPR plotted against TPR for all possible confidence thresholds $\\tau$, and (confidence-thresholded) \\RTE curves, \\ie, \\RTE over confidence threshold $\\tau$ for \\AdvTrain and \\ConfTrain, including different $\\rho$ parameters. Worst-case adversarial examples across all $L_\\infty$ attacks with $\\epsilon = 0.3$ (MNIST) and $\\epsilon = 0.03$ (Cifar10) were tested. For evaluation, the confidence threshold $\\tau$ is fixed at $99\\%$TPR, allowing to reject at most $1\\%$ correctly classified clean examples. Thus, we also do not report the area under the ROC curve in the main paper.}\n    \\label{fig:supp-experiments-evaluation}\n\\end{figure*}\n\\begin{figure*}[t]\n    \\centering\n    \\footnotesize\n    \\begin{subfigure}{1\\textwidth}\n        \\centering\n        \\textbf{SVHN:} \\textbf{\\AdvTrain} with $L_\\infty$ \\PGD-\\FConf, $\\epsilon = 0.03$ for training \\emph{and} testing\n    \\end{subfigure}\n    \\\\[2px]\n    \\begin{subfigure}{0.19\\textwidth}\n        \\includegraphics[height=2.2cm]{fig_svhn_advtrain_0_adversarial}\n    \\end{subfigure}\n    \\begin{subfigure}{0.19\\textwidth}\n        \\includegraphics[height=2.2cm]{fig_svhn_advtrain_1_adversarial}\n    \\end{subfigure}\n    \\begin{subfigure}{0.19\\textwidth}\n        \\includegraphics[height=2.2cm]{fig_svhn_advtrain_2_adversarial}\n    \\end{subfigure}\n    \\begin{subfigure}{0.19\\textwidth}\n        \\includegraphics[height=2.2cm]{fig_svhn_advtrain_3_adversarial}\n    \\end{subfigure}\n    \\begin{subfigure}{0.19\\textwidth}\n        \\includegraphics[height=2.2cm]{fig_svhn_advtrain_4_adversarial}\n    \\end{subfigure}\n    \\\\\n    \\begin{subfigure}{0.19\\textwidth}\n        \\includegraphics[height=2.2cm]{fig_svhn_advtrain_5_adversarial}\n    \\end{subfigure}\n    \\begin{subfigure}{0.19\\textwidth}\n        \\includegraphics[height=2.2cm]{fig_svhn_advtrain_6_adversarial}\n    \\end{subfigure}\n    \\begin{subfigure}{0.19\\textwidth}\n        \\includegraphics[height=2.2cm]{fig_svhn_advtrain_7_adversarial}\n    \\end{subfigure}\n    \\begin{subfigure}{0.19\\textwidth}\n        \\includegraphics[height=2.2cm]{fig_svhn_advtrain_8_adversarial}\n    \\end{subfigure}\n    \\begin{subfigure}{0.19\\textwidth}\n        \\includegraphics[height=2.2cm]{fig_svhn_advtrain_9_adversarial}\n    \\end{subfigure}\n    \\\\[4px]\n    \\begin{subfigure}{1\\textwidth}\n        \\centering\n        \\textbf{SVHN:} \\textbf{\\ConfTrain} with $L_\\infty$ \\PGD-\\FConf, $\\epsilon = 0.03$ for training \\emph{and} testing\n    \\end{subfigure}\\\\[4px]\n    \\begin{subfigure}{0.19\\textwidth}\n        \\includegraphics[height=2.2cm]{fig_svhn_ours10_0_adversarial}\n    \\end{subfigure}\n    \\begin{subfigure}{0.19\\textwidth}\n        \\includegraphics[height=2.2cm]{fig_svhn_ours10_1_adversarial}\n    \\end{subfigure}\n    \\begin{subfigure}{0.19\\textwidth}\n        \\includegraphics[height=2.2cm]{fig_svhn_ours10_2_adversarial}\n    \\end{subfigure}\n    \\begin{subfigure}{0.19\\textwidth}\n        \\includegraphics[height=2.2cm]{fig_svhn_ours10_3_adversarial}\n    \\end{subfigure}\n    \\begin{subfigure}{0.19\\textwidth}\n        \\includegraphics[height=2.2cm]{fig_svhn_ours10_4_adversarial}\n    \\end{subfigure}\n    \\\\\n    \\begin{subfigure}{0.19\\textwidth}\n        \\includegraphics[height=2.2cm]{fig_svhn_ours10_5_adversarial}\n    \\end{subfigure}\n    \\begin{subfigure}{0.19\\textwidth}\n        \\includegraphics[height=2.2cm]{fig_svhn_ours10_6_adversarial}\n    \\end{subfigure}\n    \\begin{subfigure}{0.19\\textwidth}\n        \\includegraphics[height=2.2cm]{fig_svhn_ours10_7_adversarial}\n    \\end{subfigure}\n    \\begin{subfigure}{0.19\\textwidth}\n        \\includegraphics[height=2.2cm]{fig_svhn_ours10_8_adversarial}\n    \\end{subfigure}\n    \\begin{subfigure}{0.19\\textwidth}\n        \\includegraphics[height=2.2cm]{fig_svhn_ours10_9_adversarial}\n    \\end{subfigure}\n    \\\\[4px]\n    \\begin{subfigure}{1\\textwidth}\n        \\centering\n        \\textbf{Cifar10:} \\textbf{\\AdvTrain} with $L_\\infty$ \\PGD-\\FConf, $\\epsilon = 0.03$ for training \\emph{and} testing\n    \\end{subfigure}\n    \\\\[2px]\n    \\begin{subfigure}{0.19\\textwidth}\n        \\includegraphics[height=2.2cm]{fig_cifar10_advtrain_5_adversarial}\n    \\end{subfigure}\n    \\begin{subfigure}{0.19\\textwidth}\n        \\includegraphics[height=2.2cm]{fig_cifar10_advtrain_6_adversarial}\n    \\end{subfigure}\n    \\begin{subfigure}{0.19\\textwidth}\n        \\includegraphics[height=2.2cm]{fig_cifar10_advtrain_7_adversarial}\n    \\end{subfigure}\n    \\begin{subfigure}{0.19\\textwidth}\n        \\includegraphics[height=2.2cm]{fig_cifar10_advtrain_8_adversarial}\n    \\end{subfigure}\n    \\begin{subfigure}{0.19\\textwidth}\n        \\includegraphics[height=2.2cm]{fig_cifar10_advtrain_9_adversarial}\n    \\end{subfigure}\n    \\\\[4px]\n    \\begin{subfigure}{1\\textwidth}\n        \\centering\n        \\textbf{Cifar10:} \\textbf{\\ConfTrain} with $L_\\infty$ \\PGD-\\FConf, $\\epsilon = 0.03$ for training \\emph{and} testing\n    \\end{subfigure}\n    \\\\[2px]\n    \\begin{subfigure}{0.19\\textwidth}\n        \\includegraphics[height=2.2cm]{fig_cifar10_ours10_5_adversarial}\n    \\end{subfigure}\n    \\begin{subfigure}{0.19\\textwidth}\n        \\includegraphics[height=2.2cm]{fig_cifar10_ours10_6_adversarial}\n    \\end{subfigure}\n    \\begin{subfigure}{0.19\\textwidth}\n        \\includegraphics[height=2.2cm]{fig_cifar10_ours10_7_adversarial}\n    \\end{subfigure}\n    \\begin{subfigure}{0.19\\textwidth}\n        \\includegraphics[height=2.2cm]{fig_cifar10_ours10_8_adversarial}\n    \\end{subfigure}\n    \\begin{subfigure}{0.19\\textwidth}\n        \\includegraphics[height=2.2cm]{fig_cifar10_ours10_9_adversarial}\n    \\end{subfigure}\n    \\vskip 4px\n    \\fbox{\n        \\hspace*{3.75cm}\\includegraphics[width=0.5\\textwidth]{fig_supp_class_legend}\\hspace*{3.75cm}\n    }\n    \\caption{\\textbf{Effect of Confidence Calibration.} Confidences for classes along adversarial directions for \\AdvTrain and \\ConfTrain. Adversarial examples were computed using \\PGD-\\FConf with $T=1000$ iterations and zero initialization. For both \\AdvTrain and \\ConfTrain, we show the first ten examples of the test set on SVHN, and the first five examples of the test set on Cifar10. As can be seen, \\ConfTrain biases the network to predict uniform distributions beyond the $\\epsilon$-ball used during training ($\\epsilon = 0.03$). For \\AdvTrain, in contrast, adversarial examples can usually be found right beyond the $\\epsilon$-ball.}\n    \\label{fig:supp-experiments-analysis}\n\\end{figure*}\n\\begin{figure*}[t]\n    \\centering\n    \\footnotesize\n    \\begin{subfigure}{1\\textwidth}\n        \\centering\n        \\textbf{MNIST:} \\textbf{\\AdvTrain} with $L_\\infty$ \\PGD-\\FConf, $\\epsilon = 0.3$ for training\n    \\end{subfigure}\n    \\\\[4px]\n    \\begin{subfigure}{0.225\\textwidth}\n        \\includegraphics[height=2cm]{fig_mnist_advtrain_0_interpolation}\n    \\end{subfigure}\n    \\begin{subfigure}{0.085\\textwidth}\n        \\centering\n        \\includegraphics[height=1.25cm]{fig_mnist_advtrain_0_interpolation_0}\\\\\n        \\tiny $y{=}2$\\\\\n        $f_y{=}1$\n    \\end{subfigure}\n    \\begin{subfigure}{0.085\\textwidth}\n        \\centering\n        \\includegraphics[height=1.25cm]{fig_mnist_advtrain_0_interpolation_05}\\\\\n        \\tiny $\\tilde{y}{=}8$\\\\\n        $f_{\\tilde{y}}{=}0.995$\n    \\end{subfigure}\n    \\begin{subfigure}{0.085\\textwidth}\n        \\centering\n        \\includegraphics[height=1.25cm]{fig_mnist_advtrain_0_interpolation_1}\\\\\n        \\tiny $y{=}7$\\\\\n        $f_y{=}1$\n    \\end{subfigure}\n    %\n    \\begin{subfigure}{0.225\\textwidth}\n        \\includegraphics[height=2cm]{fig_mnist_advtrain_4_interpolation}\n    \\end{subfigure}\n    \\begin{subfigure}{0.085\\textwidth}\n        \\centering\n        \\includegraphics[height=1.25cm]{fig_mnist_advtrain_4_interpolation_0}\\\\\n        \\tiny $y{=}2$\\\\\n        $f_y{=}1$\n    \\end{subfigure}\n    \\begin{subfigure}{0.085\\textwidth}\n        \\centering\n        \\includegraphics[height=1.25cm]{fig_mnist_advtrain_4_interpolation_05}\\\\\n        \\tiny $\\tilde{y}{=}6$\\\\\n        $f_{\\tilde{y}}{=}0.4$\n    \\end{subfigure}\n    \\begin{subfigure}{0.085\\textwidth}\n        \\centering\n        \\includegraphics[height=1.25cm]{fig_mnist_advtrain_4_interpolation_1}\\\\\n        \\tiny $y{=}4$\\\\\n        $f_y{=}1$\n    \\end{subfigure}\n    \\\\[4px]\n    %\n    \\begin{subfigure}{1\\textwidth}\n        \\centering\n        \\textbf{MNIST:} \\textbf{\\ConfTrain} with $L_\\infty$ \\PGD-\\FConf, $\\epsilon = 0.3$ for training\n    \\end{subfigure}\n    \\\\[4px]\n    \\begin{subfigure}{0.225\\textwidth}\n        \\includegraphics[height=2cm]{fig_mnist_ours10_0_interpolation}\n    \\end{subfigure}\n    \\begin{subfigure}{0.085\\textwidth}\n        \\centering\n        \\includegraphics[height=1.25cm]{fig_mnist_ours10_0_interpolation_0}\\\\\n        \\tiny $y{=}2$\\\\\n        $f_y{=}1$\n    \\end{subfigure}\n    \\begin{subfigure}{0.085\\textwidth}\n        \\centering\n        \\includegraphics[height=1.25cm]{fig_mnist_ours10_0_interpolation_05}\\\\\n        \\tiny $\\tilde{y}{=}4$\\\\\n        {\\color{red}$f_{\\tilde{y}}{=}0.11$}\n    \\end{subfigure}\n    \\begin{subfigure}{0.085\\textwidth}\n        \\centering\n        \\includegraphics[height=1.25cm]{fig_mnist_ours10_0_interpolation_1}\\\\\n        \\tiny $y{=}7$\\\\\n        $f_y{=}1$\n    \\end{subfigure}\n    %\n    \\begin{subfigure}{0.225\\textwidth}\n        \\includegraphics[height=2cm]{fig_mnist_ours10_4_interpolation}\n    \\end{subfigure}\n    \\begin{subfigure}{0.085\\textwidth}\n        \\centering\n        \\includegraphics[height=1.25cm]{fig_mnist_ours10_4_interpolation_0}\\\\\n        \\tiny $y{=}2$\\\\\n        $f_y{=}1$\n    \\end{subfigure}\n    \\begin{subfigure}{0.085\\textwidth}\n        \\centering\n        \\includegraphics[height=1.25cm]{fig_mnist_ours10_4_interpolation_05}\\\\\n        \\tiny $\\tilde{y}{=}0$\\\\\n        {\\color{red}$f_{\\tilde{y}}{=}0.12$}\n    \\end{subfigure}\n    \\begin{subfigure}{0.085\\textwidth}\n        \\centering\n        \\includegraphics[height=1.25cm]{fig_mnist_ours10_4_interpolation_1}\\\\\n        \\tiny $y{=}4$\\\\\n        $f_y{=}1$\n    \\end{subfigure}\n    \\vskip 4px\n    \\fbox{\n        \\hspace*{1.9cm}\\includegraphics[width=0.7\\textwidth]{fig_supp_class_legend}\\hspace*{1.9cm}\n    }\n    \n    \\caption{\\textbf{Confidence Calibration Between Test Examples.} We plot the confidence for all classes when interpolating linearly between test examples: $(1 - \\kappa) x_1 + \\kappa x_2$ for two test examples $x_1$ and $x_2$ with $\\kappa \\in [0,1]$; $x_1$ is fixed and we show two examples corresponding to different $x_2$. Additionally, we show the corresponding images for $\\kappa = 0$, \\ie, $x_1$, $\\kappa = 0.5$, \\ie, the mean image, and $\\kappa = 1$, \\ie, $x_2$, with the corresponding labels and confidences. As can be seen, \\ConfTrain is able to perfectly predict a uniform distribution between test examples. \\AdvTrain, in contrast, enforces high-confidence predictions, resulting in conflicts if $x_1$ and $x_2$ are too close together (\\ie, within one $\\epsilon$-ball) or in sudden changes of the predicted class in between, as seen above.}\n    \\label{fig:supp-experiments-interpolation}\n\\end{figure*}\n\nIn the main paper, instead of reporting ROC AUC, we reported only confidence-thresholded robust test error (\\RTE), which implicitly subsumes the false positive rate (FPR), at a confidence threshold of $99\\%$TPR. Again, we note that this is an extremely conservative choice, allowing to reject at most $1\\%$ correctly classified clean examples. In addition, comparison to other approaches is fair as the corresponding confidence threshold only depends on correctly classified clean examples, not on adversarial examples. As also seen in \\figref{fig:supp-experiments-evaluation}, ROC AUC is not a practical metric to evaluate the detection/rejection of adversarial examples. This is because rejecting a significant part of correctly classified clean examples is not acceptable. In this sense, ROC AUC measures how well positives and negatives can be distinguished in general, while we are only interested in the performance for very high TPR, \\eg, $99\\%$TPR as in the main paper. In this document, we also report FPR to complement our evaluation using (confidence-thresholded) \\RTE.\n\n\\textbf{Robust Test Error:} \n%\nThe standard robust test error \\cite{MadryICLR2018} is the model's test error in the case where all test examples are allowed to be attacked, \\ie, modified within the chosen threat model, \\eg, for $L_p$:\n%\\vspace*{-2px}\n\\begin{align}\n\\text{``Standard'' }\\RTE = \\frac{1}{N}\\sum_{n = 1}^N \\;\\max\\limits_{\\|\\delta\\|_p\\leq \\epsilon} \\Id_{f(x_n + \\delta)\\neq y_n}\\label{eq:supp-rte}\n\\end{align}\n%\\vspace*{-2px}\nwhere $\\{(x_n,y_n)\\}_{n = 1}^N$ are test examples and labels. In practice, \\RTE is computed empirically using several adversarial attacks, potentially with multiple restarts as the inner maximization problem is generally non-convex. \n\nAs standard \\RTE does not account for a reject option, we propose a generalized definition adapted to our confidence-thresholded setting. For fixed confidence threshold $\\tau$, \\eg, at $99\\%$TPR, the confidence-thresholded \\RTE is defined as\n%\\vspace*{-2px}\n\\begin{align}\n\\RTE(\\tau) = \\frac{\n    \\sum\\limits_{n=1}^N \\;\\max\\limits_{\\|\\delta\\|_p\\leq \\epsilon, c(x_n + \\delta)\\geq \\tau} \\Id_{f(x_n + \\delta)\\neq y_n}\n}\n{\n    \\sum\\limits_{n=1}^N \\;\\max\\limits_{\\|\\delta\\|_p\\leq \\epsilon} \\Id_{c(x_n + \\delta)\\geq \\tau}\n}\\label{eq:supp-conf-rte}\n\\end{align}\n%\\vspace*{-2px}\nwith $c(x) = \\max_k f_k(x)$ and $f(x)$ being the model's confidence and predicted class on example $x$, respectively. This is the test error on test examples that can be modified within the chosen threat model \\emph{and} pass confidence thresholding. It reduces to standard \\RTE for $\\tau = 0$, is in $[0,1]$ and, thus, fully comparable to related work.\n\nAs both \\eqnref{eq:supp-rte} and \\eqnref{eq:supp-conf-rte} cannot be computed exactly, we compute\n\\begin{align}\n\\frac{\n    \\sum_{n = 1}^N \\max\\{\\Id_{f(x_n) \\neq y_n}\\Id_{c(x_n)\\geq \\tau}, \\Id_{f(\\tilde{x}_n) \\neq y_n}\\Id_{c(\\tilde{x}_n)\\geq \\tau}\\}\n}{\n    \\sum_{n = 1}^N \\max\\{\\Id_{c(x_n)\\geq \\tau}, \\Id_{c(\\tilde{x}_n)\\geq \\tau}\\}\n}\\label{eq:supp-appr-rte}\n\\end{align}\nwhich is an upper bound assuming that our attack is perfect. Essentially, this counts the test examples $x_n$ that are either classified incorrectly with confidence $c(x_n) \\geq \\tau$ or that can be attacked successfully $\\tilde{x}_n = x_n + \\delta$ with confidence $c(\\tilde{x}_n) \\geq \\tau$. This is normalized by the total number of test examples $x_n$ that have $c(x_n) \\geq \\tau$ or where the corresponding adversarial example $\\tilde{x}_n$ has $c(\\tilde{x}_n) \\geq \\tau$. It can easily be seen that $\\tau = 0$ reduces \\eqnref{eq:supp-appr-rte} to its unthresholded variant, \\ie, standard \\RTE, ensuring full comparability to related work.\n\nIn the following, we also highlight two special cases that are (correctly) taken into account by \\eqnref{eq:supp-appr-rte}: (a) if a correctly classified test example $x_n$, \\ie, $f(x_n) = y_n$, has confidence $c(x_n) < \\tau$, \\ie, is rejected, but the corresponding adversarial example $\\tilde{x}_n$ with $f(\\tilde{x}_n) \\neq y$ has $c(\\tilde{x}_n) \\geq \\tau$, \\ie, is \\emph{not} rejected, this is counted both in the numerator and denominator; (b) if an incorrectly classified test example $x_n$, \\ie, $f(x_n) \\neq y$, with $c(x_n) < \\tau$, \\ie, rejected, has a corresponding adversarial example $\\tilde{x}_n$, \\ie, also $f(\\tilde{x}_n) \\neq y$, but with $x(x_n) \\geq \\tau$, \\ie, \\emph{not} rejected, this is also counted in the numerator as well as denominator. Note that these cases are handled differently in our detection evaluation following related work \\cite{MaICLR2018,LeeNIPS2018}: negatives are adversarial examples corresponding to correctly classified clean examples that are successful, \\ie, change the label. For example, case (b) would not contribute towards the FPR since the original test example is already mis-classified. Thus, while \\RTE implicitly includes FPR as well as \\TE, it is even more conservative than just considering ``$\\text{FPR} + \\TE$''.\n\n\\subsection{Ablation Study}\n\\label{subsec:supp-experiments-ablation}\n\nIn the following, we include ablation studies for our attack \\PGD-\\FConf, in \\tabref{tab:supp-experiments-attack}, and for \\ConfTrain, in \\tabref{tab:supp-experiments-training}.\n\n\\textbf{Attack.}\n%\nRegarding the proposed attack \\PGD-\\FConf using momentum and backtracking, \\tabref{tab:supp-experiments-attack} shows that backtracking and sufficient iterations are essential to attack \\ConfTrain. On SVHN, for \\AdvTrain, the difference in \\RTE between $T=200$ and $T=1000$ iterations is only $3.7\\%$, specifically, $46.2\\%$ and $49.9\\%$. For \\ConfTrain, in contrast, using $T=200$ iterations is not sufficient, with merely $5\\%$ \\RTE. However, $T=1000$ iterations with zero initialization increases \\RTE to $22.8\\%$. For more iterations, \\ie, $T = 2000$, \\RTE stagnates with $23.3\\%$. When using random initialization (one restart), \\RTE drops to $5.2\\%$, even when using $T = 2000$ iterations. Similar significant drops are observed without backtracking. These observations generalize to MNIST and Cifar10.\n\n\\textbf{Training:}\n%\n\\tabref{tab:supp-experiments-training} reports results for \\ConfTrain with different values for $\\rho$. We note that $\\rho$ controls the (speed of the) transition from (correct) one-hot distribution to uniform distribution depending on the distance of adversarial example to the corresponding original training example. Here, higher $\\rho$ results in a sharper (\\ie, faster) transition from one-hot to uniform distribution. It is also important to note that the power transition does not preserve a bias towards the true label, \\ie, for the maximum possible perturbation ($\\|\\delta\\|_\\infty = \\epsilon$), the network is forced to predict a purely uniform distribution. As can be seen, both on SVHN and Cifar10, higher $\\rho$ usually results in better robustness. Thus, for the main paper, we chose $\\rho = 10$. Only on SVHN, $\\rho = 6$ of $\\rho = 12$ perform slightly better. However, we found that $\\rho = 10$ generalizes better to previously unseen attacks.\n\n\\begin{table*}[t]\n\t\\centering\n\t\\footnotesize\n\t\\begin{subfigure}{0.84\\textwidth}\n\t\t\\centering\n\t\t\\input{tab_mmnist_main2_99tpr}\n\t\\end{subfigure}\n\t\\vskip 2px\n\t\\begin{subfigure}{0.84\\textwidth}\n\t\t\\centering\n\t\t\\input{tab_msvhn_main2_99tpr}\n\t\\end{subfigure}\n\t\\vskip 2px\n\t\\begin{subfigure}{0.84\\textwidth}\n\t\t\\centering\n\t\t\\input{tab_mcifar10_main2_99tpr}\n\t\\end{subfigure}\n\t\\vskip -6px\n\t\\caption{\\textbf{Main Results: FPR for $99\\%$TPR.} For $\\boldsymbol{99}\\%$TPR, we report confidence-thresholded \\RTE \\emph{and} FPR for the results from the main paper. We emphasize that only \\PGD-\\FCE and \\PGD-\\FConf were used against \\Ma and \\Lee. In general, the observations of the main paper can be confirmed considering FPR. Due to the poor \\TE of \\AdvTrain, \\Wong or \\TRADES on Cifar10, these methods benefit most from considering FPR instead of (confidence-thresholded) \\RTE. \\textbf{*} Pre-trained models with different architectures.}\n\t\\label{tab:supp-experiments-99}\n\\end{table*}\n\\begin{table*}[t]\n    %\\centering\n    \\footnotesize\n    \\begin{subfigure}{0.83\\textwidth}\n        \\centering\n        \\input{tab_mmnist_main2_98tpr}\n    \\end{subfigure}\n    \\begin{subfigure}{0.08\\textwidth}\n        \\centering\n        \\input{tab_mmnist_distal_main_98tpr}\n    \\end{subfigure}\n    \\begin{subfigure}{0.075\\textwidth}\n        \\centering\n        \\input{tab_mmnist_corrupted_main_98tpr}\n    \\end{subfigure}\n    \\vskip 2px\n    \\begin{subfigure}{0.83\\textwidth}\n        \\centering\n        \\input{tab_msvhn_main2_98tpr}\n    \\end{subfigure}\n    \\begin{subfigure}{0.08\\textwidth}\n        \\centering\n        \\input{tab_msvhn_distal_main_98tpr}\n    \\end{subfigure}\n    \\hfill\n    \\vskip 2px\n    \\begin{subfigure}{0.83\\textwidth}\n        \\centering\n        \\input{tab_mcifar10_main2_98tpr}\n    \\end{subfigure}\n    \\begin{subfigure}{0.08\\textwidth}\n        \\centering\n        \\input{tab_mcifar10_distal_main_98tpr}\n    \\end{subfigure}\n    \\begin{subfigure}{0.075\\textwidth}\n        \\centering\n        \\input{tab_mcifar10_corrupted_main_98tpr}\n    \\end{subfigure}\n    \\vskip -6px\n    \\caption{\\textbf{Main Results: Generalizable Robustness for {\\color{colorbrewer1}$\\boldsymbol{98\\%}$TPR}.} While reporting results for $99\\%$TPR in the main paper, reducing the TPR requirement for confidence-thresholding to {\\color{colorbrewer1}$98\\%$TPR} generally improves results, but only slightly. We report FPR and confidence-thresholded \\RTE for $98\\%$TPR. For MNIST-C and Cifar10-C, we report mean \\TE across all corruptions. $L_\\infty$ attacks with $\\epsilon{=}0.3$ on MNIST and $\\epsilon = 0.03$ on SVHN/Cifar10 were used for training (\\textbf{\\textcolor{colorbrewer3}{seen}}). All other attacks were not used during training (\\textbf{\\textcolor{colorbrewer1}{unseen}}). \\textbf{*} Pre-trained models with different architectures.}\n    \\label{tab:supp-experiments-98}\n\\end{table*}\n\\begin{table*}[t]\n    %\\centering\n    \\footnotesize\n    \\begin{subfigure}{0.83\\textwidth}\n        \\centering\n        \\input{tab_mmnist_main2_95tpr}\n    \\end{subfigure}\n    \\begin{subfigure}{0.08\\textwidth}\n        \\centering\n        \\input{tab_mmnist_distal_main_95tpr}\n    \\end{subfigure}\n    \\begin{subfigure}{0.075\\textwidth}\n        \\centering\n        \\input{tab_mmnist_corrupted_main_95tpr}\n    \\end{subfigure}\n    \\vskip 2px\n    \\begin{subfigure}{0.83\\textwidth}\n        \\centering\n        \\input{tab_msvhn_main2_95tpr}\n    \\end{subfigure}\n    \\begin{subfigure}{0.08\\textwidth}\n        \\centering\n        \\input{tab_msvhn_distal_main_95tpr}\n    \\end{subfigure}\n    \\hfill\n    \\vskip 2px\n    \\begin{subfigure}{0.83\\textwidth}\n        \\centering\n        \\input{tab_mcifar10_main2_95tpr}\n    \\end{subfigure}\n    \\begin{subfigure}{0.08\\textwidth}\n        \\centering\n        \\input{tab_mcifar10_distal_main_95tpr}\n    \\end{subfigure}\n    \\begin{subfigure}{0.075\\textwidth}\n        \\centering\n        \\input{tab_mcifar10_corrupted_main_95tpr}\n    \\end{subfigure}\n    \\vskip -6px\n    \\caption{\\textbf{Main Results: Generalizable Robustness for {\\color{colorbrewer1}$\\boldsymbol{95\\%}$TPR}.} We report FPR and \\RTE for $\\boldsymbol{95}\\%$TPR, in comparison with $98\\%$ in \\tabref{tab:supp-experiments-98} and $99\\%$ in the main paper. For MNIST-C and Cifar10-C, we report mean \\TE across all corruptions. $L_\\infty$ attacks with $\\epsilon{=}0.3$ on MNIST and $\\epsilon = 0.03$ on SVHN/Cifar10 \\textbf{\\textcolor{colorbrewer3}{seen}} during training; all other attacks \\textbf{\\textcolor{colorbrewer1}{unseen}} during training. Results improve slightly in comparison with $98\\%$TPR. However, the improvements are rather small and do not justify the significantly increased fraction of ``thrown away'' (correctly classified) clean examples. \\textbf{*} Pre-trained models with different architectures.}\n    \\label{tab:supp-experiments-95}\n\\end{table*}\n\\begin{table}\n    \\centering\n    \\begin{subfigure}{0.235\\textwidth}\n        \\input{tab_mmnist_all_99tpr}\n    \\end{subfigure}\n    \\begin{subfigure}{0.125\\textwidth}\n        \\input{tab_msvhn_all_99tpr}\n    \\end{subfigure}\n    \\begin{subfigure}{0.125\\textwidth}\n        \\input{tab_mcifar10_all_99tpr}\n    \\end{subfigure}\n    \\hspace*{0px}\n    {\\color{gray}\\rule[-2.75cm]{1px}{5.75cm}}\n    \\hspace*{0.5px}\n    \\begin{subfigure}{0.125\\textwidth}\n        \\input{tab_mcifar10_all2_99tpr}\n    \\end{subfigure}\n    \\caption{\\textbf{Worst-Case Results Across \\textcolor{colorbrewer1}{Unseen} Attacks.} We report the (per-example) worst-case, confidence-thresholded \\RTE and FPR across \\textbf{all} unseen attacks on MNIST, SVHN and Cifar10. On Cifar10, we additionally present results for all attacks except $L_\\infty$ adversarial examples with larger $\\epsilon=0.06$ (indicated in \\textcolor{colorbrewer2}{blue}). \\ConfTrain is able to outperform all baselines, including \\Wong and \\TRADES, significantly on MNIST and SVHN. On Cifar10, \\ConfTrain performs poorly on $L_\\infty$ adversarial examples with larger $\\epsilon = 0.06$. However, excluding these adversarial examples, \\ConfTrain also outperforms all baselines on Cifar10. \\textbf{*} Pre-trained models with different architectures.}\n    \\label{tab:supp-experiments-all}\n\\end{table}\n\n\\subsection{Analysis}\n\\label{subsec:supp-experiments-analysis}\n\n\\textbf{Confidence Histograms:}\n%\nFor further analysis, \\figref{fig:supp-experiments-histograms} shows confidence histograms for \\AdvTrain and \\ConfTrain on MNIST and Cifar10. The confidence histograms for \\ConfTrain reflect the expected behavior: adversarial examples are mostly successful in changing the label, which is supported by high \\RTE values for confidence threshold $\\tau = 0$, but their confidence is pushed towards uniform distributions. For \\AdvTrain, in contrast, successful adversarial examples -- fewer in total -- generally obtain high confidence. As a result, while confidence thresholding generally benefits \\AdvTrain, the improvement is not as significant as for \\ConfTrain.\n\n\\textbf{Confidence Along Adversarial Directions:}\n%\nIn \\figref{fig:supp-experiments-analysis}, we plot the probabilities for all ten classes along an adversarial direction. We note that these directions do not necessarily correspond to successful or high-confidence adversarial examples. Instead, we chose the first 10 test examples on SVHN and Cifar10. The adversarial examples were obtained using our $L_\\infty$ \\PGD-\\FConf attack with $T = 1000$ iterations and zero initialization for $\\epsilon = 0.03$. For \\AdvTrain, we usually observe a change in predictions along these directions; some occur within $\\|\\delta\\|_\\infty \\leq \\epsilon$, corresponding to successful adversarial examples (within $\\epsilon$), some occur for $\\|\\delta\\|_\\infty > \\epsilon$, corresponding to unsuccessful adversarial examples (within $\\epsilon$). However, \\AdvTrain always assigns high confidence. Thus, when allowing larger adversarial perturbations at test time, robustness of \\AdvTrain reduces significantly. For \\ConfTrain, in contrast, there are only few such cases; more often, the model achieves a near uniform prediction for small $\\|\\delta\\|_\\infty$ and extrapolates this behavior beyond the $\\epsilon$-ball used for training. On SVHN, this behavior successfully allows to generalize the robustness to larger adversarial perturbations. Furthermore, these plots illustrate why using more iterations at test time, and using techniques such as momentum and backtracking, are necessary to find adversarial examples as the objective becomes more complex compared to \\AdvTrain.\n\n\\textbf{Confidence Along Interpolation:}\n%\nIn \\figref{fig:supp-experiments-interpolation}, on MNIST, we additionally illustrate the advantage of \\ConfTrain with respect to the toy example in Proposition \\ref{prop:toy-example}. Here, we consider the case where the $\\epsilon$-balls of two training or test examples (in different classes) overlap. As we show in Proposition \\ref{prop:toy-example}, adversarial training is not able to handle such cases, resulting in the  trade-off between accuracy in robustness reported in the literature \\citep{TsiprasARXIV2018,StutzCVPR2019,RaghunathanARXIV2019,ZhangICML2019}. This is because adversarial training enforces high-confidence predictions on both $\\epsilon$-balls (corresponding to different classes), resulting in an obvious conflict. \\ConfTrain, in contrast, enforces uniform predictions throughout the largest parts of both $\\epsilon$-balls, resolving the conflict.\n\n\\subsection{Results}\n\\label{subsec:supp-experiments-results}\n\n\\textbf{Main Results for $98\\%$ and $95\\%$ TPR:}\n%\n\\tabref{tab:supp-experiments-98} reports our main results requiring only $98\\%$TPR; \\tabref{tab:supp-experiments-95} shows results for $95\\%$TPR. This implies, that compared to $99\\%$TPR, up to $1\\%$ (or $4\\%$) more correctly classified test examples can be rejected, increasing the confidence threshold and potentially improving robustness. For relatively simple tasks such as MNIST and SVHN, where \\TE is low, this is a significant ``sacrifice''. However, as can be seen, robustness in terms of \\RTE only improves slightly. We found that the same holds for $95\\%$TPR, however, rejecting more than $2\\%$ of correctly classified examples seems prohibitive large for the considered datasets.\n\n\\textbf{Worst-Case Across \\textbf{\\textcolor{colorbrewer1}{Unseen}} Attacks:}\n%\n\\tabref{tab:supp-experiments-all} reports \\emph{per-example} worst-case \\RTE and FPR for $99\\%$TPR considering \\textbf{all} \\textcolor{colorbrewer1}{unseen} attacks. On MNIST and SVHN, \\RTE increases to nearly $100\\%$ for \\AdvTrain, both \\AdvTrainHalf and \\AdvTrainFull. \\ConfTrain, in contrast, is able to achieve considerably lower \\RTE: $23.9\\%$ on MNIST and $61.1\\%$ on SVHN. Only on Cifar10, \\ConfTrain does not result in a significant improvement; all methods, including related work such as \\Wong and \\TRADES yield \\RTE of $94\\%$ or higher. However, this is mainly due to the poor performance of \\ConfTrain against large $L_\\infty$ adversarial examples with $\\epsilon = 0.06$. Excluding these adversarial examples (right most table, indicated in \\textcolor{colorbrewer2}{blue}) shows that \\RTE improves to $77.6\\%$ for \\ConfTrain, while \\RTE for the remaining methods remains nearly unchanged. Overall, these experiments emphasize that \\ConfTrain is able to generalize robustness to previously unseen attacks.\n\n\\textbf{Per-Attack Results:}\n%\nIn \\tabref{tab:supp-experiments-main-mnist-1} to \\ref{tab:supp-experiments-main-cifar10-4}, we break down our main results regarding all used $L_p$ attacks for $p \\in \\{\\infty, 2, 1, 0\\}$. For simplicity we focus on \\PGD-\\FCE and \\PGD-\\FConf while reporting the used black-box attacks together, \\ie, taking the per-example worst-case adversarial examples across all black-box attacks. For comparison, we also include the area under the ROC curve (ROC AUC), non-thresholded \\TE and non-thresholded \\RTE. On MNIST, where \\AdvTrain performs very well in practice, it is striking that for $\\nicefrac{4}{3}\\epsilon = 0.4$ even black-box attacks are able to reduce robustness completely, resulting in high \\RTE. This observation also transfers to SVHN and Cifar10. For \\ConfTrain, black-box attacks are only effective on Cifar10, where they result in roughly $87\\%$ \\RTE with $\\tau$@$99\\%$TPR. For the $L_2$, $L_1$ and $L_0$ attacks we can make similar observations. Across all $L_p$ norms, it can also be seen that \\PGD-\\FCE performs significantly worse against our \\ConfTrain compared to \\AdvTrain, which shows that it is essential to optimize the right objective to evaluate the robustness of defenses and adversarially trained models, \\ie, maximize confidence against \\ConfTrain.\n\n\\textbf{Results on Corrupted MNIST/Cifar10:}\n%\nWe also conducted experiments on MNIST-C \\citep{MuICMLWORK2019} and Cifar10-C \\citep{HendrycksARXIV2019}. These datasets are variants of MNIST and Cifar10 that contain common perturbations of the original images obtained from various types of noise, blur or transformations; examples include zoom or motion blue, Gaussian and shot noise, rotations, translations and shear. \\tabref{tab:supp-experiments-corruption-mnist-1} to \\ref{tab:supp-experiments-corruption-cifar10-2} presents the per-corruption results on MNIST-C and Cifar10-C, respectively. Here, \\texttt{all} includes all corruptions and \\texttt{mean} reports the average results across all corruptions. We note that, due to the thresholding, different numbers of corrupted examples are left after detection for different corruptions. Thus, the distinction between \\texttt{all} and \\texttt{mean} is meaningful. Striking is the performance of \\ConfTrain on noise corruptions such as \\texttt{gaussian\\_noise} or \\texttt{shot\\_noise}. Here, \\ConfTrain is able to reject $100\\%$ of the corrupted examples, resulting in a thresholded \\TE of $0\\%$. This is in stark contrast to \\AdvTrain, exhibiting a \\TE of roughly $15\\%$ after rejection on Cifar10-C. On the remaining corruptions, \\ConfTrain is able to perform slightly better than \\AdvTrain, which is often due to higher detection rate, \\ie, higher ROC AUC. On, Cifar10, the generally lower \\TE of \\ConfTrain also contributes to the results. Overall, this illustrates that \\ConfTrain is able to preserve the inductive bias of predicting near-uniform distribution on noise similar to $L_\\infty$ adversarial examples as seen during training.\n\n\\begin{table*}[t]\n\t\\centering\n\t\\scriptsize\n    \\input{tab_mmnist_supp_99tpr_1}\n\t\\vskip -6px\n\t\\caption{\\textbf{Per-Attack Results on MNIST, Part I ($\\mathbf{L_\\infty}$).} Per-attack results considering \\PGD-\\FCE, as in \\cite{MadryICLR2018}, our \\PGD-\\FConf and the remaining black-box attacks for the $L_\\infty$ threat model. The used $\\epsilon$ values are reported in the left-most column. For the black-box attacks, we report the per-example worst-case across all black-box attacks. In addition to FPR and \\RTE, we include ROC AUC, \\TE as well as \\TE and \\RTE in the standard, non-thresholded setting, as reference.}\n\t\\label{tab:supp-experiments-main-mnist-1}\n\\end{table*}\n\\begin{table*}[t]\n    \\centering\n    \\scriptsize\n    \\input{tab_mmnist_supp_99tpr_2}\n    \\vskip -6px\n    \\caption{\\textbf{Per-Attack Results on MNIST, Part II ($\\mathbf{L_2}$).} Per-attack results considering \\PGD-\\FCE, as in \\cite{MadryICLR2018}, our \\PGD-\\FConf and the remaining black-box attacks for the $L_2$ threat model. The used $\\epsilon$ values are reported in the left-most column. For the black-box attacks, we report the per-example worst-case across all black-box attacks. In addition to FPR and \\RTE we include ROC AUC, \\TE as well as \\TE and \\RTE in the standard, non-thresholded setting, as reference.}\n    \\label{tab:supp-experiments-main-mnist-2}\n\\end{table*}\n\\begin{table*}[t]\n    \\centering\n    \\scriptsize\n    \\input{tab_mmnist_supp_99tpr_3}\n    \\vskip -6px\n    \\caption{\\textbf{Per-Attack Results on MNIST, Part III ($\\mathbf{L_1}$).} Per-attack results considering \\PGD-\\FCE, as in \\cite{MadryICLR2018}, our \\PGD-\\FConf and the remaining black-box attacks for the $L_1$ threat model. The used $\\epsilon$ values are reported in the left-most column. For the black-box attacks, we report the per-example worst-case across all black-box attacks. In addition to FPR and \\RTE we include ROC AUC, \\TE as well as \\TE and \\RTE in the standard, non-thresholded setting, as reference.}\n    \\label{tab:supp-experiments-main-mnist-3}\n\\end{table*}\n\\begin{table*}[t]\n    \\centering\n    \\scriptsize\n    \\input{tab_mmnist_supp_99tpr_4}\n    \\vskip -6px\n    \\caption{\\textbf{Per-Attack Results on MNIST, Part IV ($\\mathbf{L_0}$, Adversarial Frames).} Per-attack results considering \\PGD-\\FCE, as in \\cite{MadryICLR2018}, our \\PGD-\\FConf and the remaining black-box attacks for $L_0$ threat models and adversarial frames. The used $\\epsilon$ values are reported in the left-most column. For the black-box attacks, we report the per-example worst-case across all black-box attacks. In addition to FPR and \\RTE we include ROC AUC, \\TE as well as \\TE and \\RTE in the standard, non-thresholded setting, as reference.}\n    \\label{tab:supp-experiments-main-mnist-4}\n\\end{table*}\n\\begin{table*}[t]\n\t\\centering\n\t\\scriptsize\n    \\input{tab_msvhn_supp_99tpr_1}\n\t\\vskip -6px\n\t\\caption{\\textbf{Per-Attack Results on SVHN, Part I ($\\mathbf{L_\\infty}$).} Per-attack results considering \\PGD-\\FCE, as in \\cite{MadryICLR2018}, our \\PGD-\\FConf and the remaining black-box attacks for the $L_\\infty$ threat model. The used $\\epsilon$ values are reported in the left-most column. For the black-box attacks, we report the per-example worst-case across all black-box attacks. In addition to FPR and \\RTE we include ROC AUC, \\TE as well as \\TE and \\RTE in the standard, non-thresholded setting, as reference.}\n    \\label{tab:supp-experiments-main-svhn-1}\n\\end{table*}\n\\begin{table*}[t]\n    \\centering\n    \\scriptsize\n    \\input{tab_msvhn_supp_99tpr_2}\n    \\vskip -6px\n    \\caption{\\textbf{Per-Attack Results on SVHN, Part II ($\\mathbf{L_2}$).} Per-attack results considering \\PGD-\\FCE, as in \\cite{MadryICLR2018}, our \\PGD-\\FConf and the remaining black-box attacks for $L_2$ threat model. The used $\\epsilon$ values are reported in the left-most column. For the black-box attacks, we report the per-example worst-case across all black-box attacks. In addition to FPR and \\RTE we include ROC AUC, \\TE as well as \\TE and \\RTE in the standard, non-thresholded setting, as reference.}\n    \\label{tab:supp-experiments-main-svhn-2}\n\\end{table*}\n\\begin{table*}[t]\n    \\centering\n    \\scriptsize\n    \\input{tab_msvhn_supp_99tpr_3}\n    \\vskip -6px\n    \\caption{\\textbf{Per-Attack Results on SVHN, Part III ($\\mathbf{L_1}$, $\\mathbf{L_0}$, Adversarial Frames).} Per-attack results considering \\PGD-\\FCE, as in \\cite{MadryICLR2018}, our \\PGD-\\FConf and the remaining black-box attacks for $L_1$, $L_0$ threat models and adversarial frames. The used $\\epsilon$ values are reported in the left-most column. For the black-box attacks, we report the per-example worst-case across all black-box attacks. In addition to FPR and \\RTE we include ROC AUC, \\TE as well as \\TE and \\RTE in the standard, non-thresholded setting, as reference.}\n    \\label{tab:supp-experiments-main-svhn-3}\n\\end{table*}\n\\begin{table*}[t]\n\t\\centering\n\t\\tiny\n    \\input{tab_mcifar10_supp_99tpr_1}\n\t\\vskip -6px\n\t\\caption{\\textbf{Per-Attack Results on Cifar10, Part I ($\\mathbf{L_\\infty}$).} Per-attack results considering \\PGD-\\FCE, as in \\cite{MadryICLR2018}, our \\PGD-\\FConf and the remaining black-box attacks for $L_\\infty$ and $L_2$ threat models. The used $\\epsilon$ values are reported in the left-most column. For the black-box attacks, we report the per-example worst-case across all black-box attacks. In addition to FPR and \\RTE we include ROC AUC, \\TE as well as \\TE and \\RTE in the standard, non-thresholded setting, as reference.}\n    \\label{tab:supp-experiments-main-cifar10-1}\n\\end{table*}\n\\begin{table*}[t]\n    \\centering\n    \\scriptsize\n    \\input{tab_mcifar10_supp_99tpr_2}\n    \\vskip -6px\n    \\caption{\\textbf{Per-Attack Results on Cifar10, Part II ($\\mathbf{L_2}$).} Per-attack results considering \\PGD-\\FCE, as in \\cite{MadryICLR2018}, our \\PGD-\\FConf and the remaining black-box attacks for the $L_2$ threat model. The used $\\epsilon$ values are reported in the left-most column. For the black-box attacks, we report the per-example worst-case across all black-box attacks. In addition to FPR and \\RTE we include ROC AUC, \\TE as well as \\TE and \\RTE in the standard, non-thresholded setting, as reference.}\n    \\label{tab:supp-experiments-main-cifar10-2}\n\\end{table*}\n\\begin{table*}[t]\n    \\centering\n    \\scriptsize\n    \\input{tab_mcifar10_supp_99tpr_3}\n    \\vskip -6px\n    \\caption{\\textbf{Per-Attack Results on Cifar10, Part III ($\\mathbf{L_1}$).} Per-attack results considering \\PGD-\\FCE, as in \\cite{MadryICLR2018}, our \\PGD-\\FConf and the remaining black-box attacks for the $L_1$ threat model. The used $\\epsilon$ values are reported in the left-most column. For the black-box attacks, we report the per-example worst-case across all black-box attacks. In addition to FPR and \\RTE we include ROC AUC, \\TE as well as \\TE and \\RTE in the standard, non-thresholded setting, as reference.}\n    \\label{tab:supp-experiments-main-cifar10-3}\n\\end{table*}\n\\begin{table*}[t]\n    \\centering\n    \\scriptsize\n    \\input{tab_mcifar10_supp_99tpr_4}\n    \\vskip -6px\n    \\caption{\\textbf{Per-Attack Results on Cifar10, Part IV ($\\mathbf{L_0}$, Adversarial Frames).} Per-attack results considering \\PGD-\\FCE, as in \\cite{MadryICLR2018}, our \\PGD-\\FConf and the remaining black-box attacks for the $L_0$ threat model and adversarial frames. The used $\\epsilon$ values are reported in the left-most column. For the black-box attacks, we report the per-example worst-case across all black-box attacks. In addition to FPR and \\RTE we include ROC AUC, \\TE as well as \\TE and \\RTE in the standard, non-thresholded setting, as reference.}\n    \\label{tab:supp-experiments-main-cifar10-4}\n\\end{table*}\n\\begin{table*}\n    \\centering\n    \\scriptsize\n    \\input{tab_mmnist_corrupted_supp_99tpr_1}\n    \\caption{\\textbf{Per-Corruptions Results on MNIST-C, PART I.} Results on MNIST-C, broken down by individual corruptions (first column); \\texttt{mean} are the averaged results over all corruptions. We report ROC AUC, FPR and the true negative rate (TNR) in addition to the thresholded and unthresholded \\TE on the corrupted examples. The table is continued in \\tabref{tab:supp-experiments-corruption-mnist-2}.}\n    \\label{tab:supp-experiments-corruption-mnist-1}\n\\end{table*}\n\\begin{table*}\n    \\centering\n    \\scriptsize\n    \\input{tab_mmnist_corrupted_supp_99tpr_2}\n    \\caption{\\textbf{Per-Corruptions Results on MNIST-C, PART II.} Continued results of \\tabref{tab:supp-experiments-corruption-mnist-1} including results on MNIST-C focusing on individual corruptions. texttt{mean} are the averaged results over all corruptions. We report ROC AUC, FPR and the true negative rate (TNR) in addition to the thresholded and unthresholded \\TE on the corrupted examples.}\n    \\label{tab:supp-experiments-corruption-mnist-2}\n\\end{table*}\n\\begin{table*}\n    \\centering\n    \\tiny\n    \\input{tab_mcifar10_corrupted_supp_99tpr_1}\n    \\caption{\\textbf{Per-Corruptions Results on Cifar10-C, PART I.} Results on Cifar10-C focusing on individual corruptions (first column); texttt{mean} are the averaged results over all corruptions. We report ROC AUC, FPR and the true negative rate (TNR) in addition to the thresholded and unthresholded \\TE on the corrupted examples. The table is continued in \\tabref{tab:supp-experiments-corruption-cifar10-2}.}\n    \\label{tab:supp-experiments-corruption-cifar10-1}\n\\end{table*}\n\\begin{table*}\n    \\centering\n    \\tiny\n    \\input{tab_mcifar10_corrupted_supp_99tpr_2}\n    \\caption{\\textbf{Per-Corruptions Results on Cifar10-C, PART II} Continued results of \\tabref{tab:supp-experiments-corruption-cifar10-1} including results on Cifar10-C focusing on individual corruptions. texttt{mean} are the averaged results over all corruptions. We report ROC AUC, FPR and the true negative rate (TNR) in addition to the thresholded and unthresholded \\TE on the corrupted examples.}\n    \\label{tab:supp-experiments-corruption-cifar10-2}\n\\end{table*}\n\\FloatBarrier", "meta": {"hexsha": "72543b802222f1f9d023c8563ac5bd2c9e382ac5", "size": 65043, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/supp_experiments.tex", "max_stars_repo_name": "davidstutz/icml2020-confidence-calibrated-adversarial-training", "max_stars_repo_head_hexsha": "a8d0476f1b1986ff13280623f009fdc1a518b487", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-07-03T14:13:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T03:03:24.000Z", "max_issues_repo_path": "paper/supp_experiments.tex", "max_issues_repo_name": "davidstutz/icml2020-confidence-calibrated-adversarial-training", "max_issues_repo_head_hexsha": "a8d0476f1b1986ff13280623f009fdc1a518b487", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/supp_experiments.tex", "max_forks_repo_name": "davidstutz/icml2020-confidence-calibrated-adversarial-training", "max_forks_repo_head_hexsha": "a8d0476f1b1986ff13280623f009fdc1a518b487", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 79.2241169306, "max_line_length": 1790, "alphanum_fraction": 0.722906385, "num_tokens": 19430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.33549513507827744}}
{"text": "\\documentclass{article}\n\n\\usepackage{times}\n\\usepackage{mathpartir}\n\\usepackage{amsmath,amsfonts,amssymb}\n\\usepackage{xcolor}\n\n%% Macros here\n\\input{hts-macros}\n\n\\begin{document}\n\n\\title{Galactic type theory}\n\\author{Andrej Bauer \\and Christopher A. Stone}\n\\maketitle\n\n\\section{Universe indices}\n\\label{sec:universe-indices}\n\nThere is a pointed preorder $(\\PP, {\\leq}, \\zero)$ of \\emph{universe indices}, i.e.,\n$\\leq$ is reflexive and transitive, with a decidable equality, and a subset $\\FF \\subseteq\n\\PP$ of \\emph{fibered indices}. We use lowercase Greek letters for universe indices.\n\n\\textcolor{red}{FIX THIS PARAGRAPH, IT IS A MISLEADING EXAMPLE WHICH BREAKS THINGS.}\nFor example, we could take\n%\n\\begin{equation*}\n  \\PP = \\NN \\times \\{0,1\\}\n\\end{equation*}\n%\nwith the lexicographic order, $\\zero = (0,0)$ and $\\FF = \\NN \\times \\{0\\}$. Write\n$\\mathcal{F}_i$ for the universe indexed by $(i,0)$ and $\\mathcal{U}_j$ for the universe\nindexed by $(i,1)$. Then the poset structure of $\\PP$ reflects a hierachy of inclusions\n%\n\\begin{equation*}\n  \\mathcal{F}_0 \\leq\n  \\mathcal{U}_0 \\leq\n  \\mathcal{F}_1 \\leq\n  \\mathcal{U}_1 \\leq\n  \\cdots\n\\end{equation*}\n%\nTo express the fact that a universe may be a member of another one, and to calculate which\ndependent products may be formed and at what universe they land in, we assume given two\npartial functions\n%\n\\begin{itemize}\n  \\item $\\uClose{\\cdot}  : \\PP \\rightharpoonup \\PP$\n  \\item $\\piClose{\\cdot}{\\cdot} : \\PP \\times \\PP \\rightharpoonup \\PP$\n\\end{itemize}\n%\nwhose domains of definition are decidable and\n%\n\\begin{itemize}\n%\\item for all $\\alpha \\in \\PP$, if $\\uClose{\\alpha}$ is defined then $\\uClose{\\alpha} \\in\n%  \\FF$.\n\\item for all $\\alpha, \\beta \\in \\FF$, if $\\piClose{\\alpha}{\\beta}$ is defined then\n  $\\piClose{\\alpha}{\\beta} \\in \\FF$,\n\\end{itemize}\n%\nThat is, a dependent product of fibered types is again fibered, if it is defined, and each\nuniverse is itself fibered, as long as it is a member of a universe. It seems that these\nare non essential assumptions -- a more flexibile scheme of universe indices would work\njust as well -- but we are followng Voevodsky's HTS formulation.\n\nThe functions are \\emph{not} required to compute maximum or successor, but we use the\nsuggestive notation because in the standard case they do compute maxima and succesors. For\ninstance, we could express the fact that $\\beta$ is the index of an impredicative universe\nby setting $\\piClose{\\alpha}{\\beta} = \\beta$ for all $\\alpha \\in \\PP$.\n\n\\section{The declarative formulation}\n\\label{sec:declarative-formulation}\n\nIn this section we give the formulation of galactic type theory in a declarative way\nwhich minimizes the number of judgments, is better suited for a semantic account, but is\nnot susceptible to an algorithmic treatment.\n\n\\subsection{Syntax}\n\\label{sec:syntax}\n\nContexts:\n%\n\\begin{equation*}\n  \\G\n  \\begin{aligned}[t]\n    \\bnf   {}& \\ctxempty & & \\text{empty context}\\\\\n    \\bnfor {}& \\ctxextend{\\G}{\\x}{\\T} & & \\text{context extended with $x : T$}\n  \\end{aligned}\n\\end{equation*}\n%\nTypes:\n%\n\\begin{equation*}\n  \\T, \\U\n  \\begin{aligned}[t]\n    \\bnf   {}& \\Universe{\\alpha} & & \\text{universe}\\\\\n    \\bnfor {}& \\El{\\alpha}{\\e} & & \\text{type named by $e$}\\\\\n    \\bnfor {}& \\Unit & & \\text{the unit type}\\\\\n    \\bnfor {}& \\Prod{x}{\\T} \\U & & \\text{product}\\\\\n    \\bnfor {}& \\PrEqual{\\T}{\\e_1}{\\e_2} & & \\text{path type}\\\\\n    \\bnfor {}& \\JuEqual{\\T}{\\e_1}{\\e_2} & & \\text{equality type}\n  \\end{aligned}\n\\end{equation*}\n%\nTerms:\n%\n\\begin{equation*}\n  \\e\n  \\begin{aligned}[t]\n    \\bnf   {}&  \\x   &&\\text{variable} \\\\\n    \\bnfor {}&  \\lam{\\x}{\\T_1}{\\T_2} \\e  &&\\text{$\\lambda$-abstraction} \\\\\n    \\bnfor {}&  \\app{\\e_1}{\\x}{\\T_1}{\\T_2}{\\e_2}  &&\\text{application} \\\\\n    \\bnfor {}&  \\unitTerm  &&\\text{the element of unit type} \\\\\n    \\bnfor {}&  \\prRefl{\\T}{\\e}  &&\\text{identity path} \\\\\n    \\bnfor {}&  \\PrElim{\\T}{\\abst{x\\,y\\,p}{\\U}}{\\abst{z}{\\e_1}}{\\e_2}{\\e_3}{\\e_4}  &&\\text{path eliminator} \\\\\n    \\bnfor {}&  \\juRefl{\\T} \\e  &&\\text{reflexivity} \\\\\n    \\bnfor {}&  \\JuElim{\\T}{\\abst{x\\,y\\,p}{\\U}}{\\abst{z}{\\e_1}}{\\e_2}{\\e_3}{\\e_4}  &&\\text{equality eliminator} \\\\\n    \\bnfor {}&  \\coerce{\\alpha}{\\beta}{\\e}  &&\\text{universe coercion} \\\\\n    \\bnfor {}&  \\nUnit  &&\\text{the name of unit type} \\\\\n    \\bnfor {}&  \\nProd{\\alpha}{\\beta}{\\x}{\\e_1} \\e_2  &&\\text{the name of product type} \\\\\n    \\bnfor {}&  \\nUniverse{\\alpha} &&\\text{the name of a universe} \\\\\n    \\bnfor {}&  \\nPrEqual{\\alpha}{\\e_1}{\\e_2}{\\e_3}  &&\\text{the name of a path type} \\\\\n    \\bnfor {}&  \\nJuEqual{\\alpha}{\\e_1}{\\e_2}{\\e_3}  &&\\text{the name of an equality type}\n  \\end{aligned}\n\\end{equation*}\n%\nNote that $\\lambda$-abstraction and application are tagged with extra types not usually\nseen in type theory. An abstraction $\\lam{\\x}{\\T_1}{\\T_2} \\e$ speficies not only the type\n$\\T_1$ of $\\x$ but also the type $\\T_2$ of $e$, where $\\x$ is bound in $\\T_2$ and $\\e$.\nSimilarly, an application $\\app{\\e_1}{\\x}{\\T_1}{\\T_2}{\\e_2}$ specifies that $\\e_1$ and\n$\\e_2$ have types $\\Prod{\\x}{\\T_1} \\T_2$ and $\\T_2$, respectively. This is necessary\nbecause in the presence of exotic equalities (think ``$\\mathsf{nat} \\to \\mathsf{bool}\n\\equiv \\mathsf{nat} \\to \\mathsf{nat}$'') we must be \\emph{very} careful about\n$\\beta$-reductions.\n\nFollowing Voevodsky's HTS we include an equality eliminator. Note that it is not strictly\nnecessary because every instance of it can be derived using the reflection rule\n\\rulename{eq-reflection}. \\textcolor{red}{[XXX IS THIS TRUE?!]}\n\n\\subsection{Judgments}\n\\label{sec:judgments}\n\n\\begin{align*}\n& \\isctx{\\G} & & \\text{$\\G$ is a well formed context} \\\\\n& \\istype{\\G}{\\T} & & \\text{$\\T$ is a type in context $\\G$} \\\\\n& \\isfib{\\G}{\\T} & & \\text{$\\T$ is a fibered type in context $\\G$} \\\\\n& \\isterm{\\G}{\\e}{\\T} & & \\text{$\\e$ is a well formed term of type $\\T$ in context $\\G$} \\\\\n& \\eqtype{\\G}{\\T}{\\U} & & \\text{$\\T$ and $\\U$ are equal types in context $\\G$} \\\\\n& \\eqterm{\\G}{\\e_1}{\\e_2}{\\T} & & \\text{$e_1$ and $e_2$ are equal terms of type $\\T$ in context $\\G$}\n\\end{align*}\n\n\\subsection{Contexts}\n\\label{sec:contexts}\n\n\\begin{mathpar}\n  \\infer[\\rulename{ctx-empty}]\n  { }\n  {\\isctx{\\ctxempty}}\n\n  \\infer[\\rulename{ctx-extend}]\n  {\\isctx{\\G} \\\\\n   \\istype{\\G}{\\T}\n  }\n  {\\isctx{\\ctxextend{\\G}{\\x}{\\T}}}\n\\end{mathpar}\n\n\\subsection{Types}\n\\label{sec:types}\n\n\\begin{mathpar}\n  \\infer[\\rulename{ty-universe}]\n  {\\isctx{\\G} \\\\\n   \\alpha \\in \\PP\n  }\n  {\\istype{\\G}{\\Universe{\\alpha}}}\n\n  \\infer[\\rulename{ty-prod}]\n  {\\istype{\\G}{\\T} \\\\\n   \\istype{\\ctxextend{\\G}{\\x}{\\T}}{\\U}\n  }\n  {\\istype{\\G}{\\Prod{\\x}{\\T}{\\U}}}\n\n  \\infer[\\rulename{ty-el}]\n  {\\isterm{\\G}{\\e}{\\Universe{\\alpha}}}\n  {\\istype{\\G}{\\El{\\alpha}{\\e}}}\n\n  \\infer[\\rulename{ty-unit}]\n  {\\isctx{\\G}}\n  {\\istype{\\G}{\\Unit}}\n\n  \\infer[\\rulename{ty-paths}]\n  {\\isfib{\\G}{\\T}\\\\\n   \\isterm{\\G}{\\e_1}{\\T}\\\\\n   \\isterm{\\G}{\\e_2}{\\T}\n  }\n  {\\istype{\\G}{\\PrEqual{\\T}{\\e_1}{\\e_2}}}\n\n  \\infer[\\rulename{ty-id}]\n  {\\istype{\\G}{\\T}\\\\\n   \\isterm{\\G}{\\e_1}{\\T}\\\\\n   \\isterm{\\G}{\\e_2}{\\T}\n  }\n  {\\istype{\\G}{\\JuEqual{\\T}{\\e_1}{\\e_2}}}\n\\end{mathpar}\n\n\\subsection{Fibered types}\n\\label{sec:fibered-types}\n\n\\begin{mathpar}\n  \\infer[\\rulename{fib-universe}]\n  {\\isctx{\\G} \\\\\n   \\alpha \\in \\PP\n  }\n  {\\isfib{\\G}{\\Universe{\\alpha}}}\n\n  \\infer[\\rulename{fib-prod}]\n  {\\isfib{\\G}{\\T} \\\\\n   \\isfib{\\ctxextend{\\G}{\\x}{\\T}}{\\U}\n  }\n  {\\isfib{\\G}{\\Prod{\\x}{\\T}{\\U}}}\n\n  \\infer[\\rulename{fib-el}]\n  {\\isterm{\\G}{\\e}{\\Universe{\\alpha}} \\\\\n   \\alpha \\in \\FF\n  }\n  {\\isfib{\\G}{\\El{\\alpha}{\\e}}}\n\n  \\infer[\\rulename{fib-unit}]\n  {\\isctx{\\G} \\\\\n   \\zero\\in\\FF }\n  {\\isfib{\\G}{\\Unit}}\n\n  \\infer[\\rulename{fib-paths}]\n  {\\isfib{\\G}{\\T}\\\\\n   \\isterm{\\G}{\\e_1}{\\T}\\\\\n   \\isterm{\\G}{\\e_2}{\\T}\n  }\n  {\\isfib{\\G}{\\PrEqual{\\T}{\\e_1}{\\e_2}}}\n\n\\end{mathpar}\n\n\\subsection{Terms}\n\\label{sec:terms}\n\n\\paragraph{General terms}\n\n\\begin{mathpar}\n  \\infer[\\rulename{term-eq}]\n  {\\isterm{\\G}{\\e}{\\T} \\\\\n   \\eqtype{\\G}{\\T}{\\U}\n  }\n  {\\isterm{\\G}{\\e}{\\U}}\n\n  \\infer[\\rulename{term-var}]\n  {\\isctx{\\G} \\\\\n   (\\x{:}\\T) \\in \\G\n  }\n  {\\isterm{\\G}{\\x}{\\T}}\n\\end{mathpar}\n\n\\paragraph{Products}\n\n\\begin{mathpar}\n  \\infer[\\rulename{term-abs}]\n  {\\isterm{\\ctxextend{\\G}{\\x}{\\T}}{\\e}{\\U}}\n  {\\isterm{\\G}{(\\lam{\\x}{\\T}{\\U}{\\e})}{\\Prod{\\x}{\\T}{\\U}}}\n\n  \\infer[\\rulename{term-app}]\n  {\\isterm{\\G}{\\e_1}{\\Prod{x}{\\T} \\U} \\\\\n   \\isterm{\\G}{\\e_2}{\\T}\n  }\n  {\\isterm{\\G}{\\app{\\e_1}{\\x}{\\T}{\\U}{\\e_2}}{\\subst{\\U}{\\x}{\\e_2}}}\n\\end{mathpar}\n\n\\paragraph{Paths}\n\n\\begin{mathpar}\n  \\infer[\\rulename{term-idpath}]\n  {\\isterm{\\G}{\\e}{\\T}\\\\\n   \\isfib{\\G}{\\T}}\n  {\\isterm{\\G}{\\prRefl{\\T}{\\e}}{\\PrEqual{\\T}{\\e}{\\e}}}\n\n  \\infer[\\rulename{term-J}]\n  {\\isfib{\\G}{\\T}\n   \\\\\\\\\n   \\isfib{\n     \\ctxextend{\\ctxextend{\\ctxextend{\\G}{x}{\\T}}{y}{\\T}}{p}{\\PrEqual{\\T}{x}{y}}\n   }{\\U}\n   \\\\\n   \\isterm\n     {\\ctxextend{\\G}{z}{\\T}}\n     {\\e_1}\n     {\\substs{\\U}{z/x, z/y, (\\prRefl{\\T}{z})/p}}\n   \\\\\n   \\isterm{\\G}{\\e_3}{\\T} \\\\\n   \\isterm{\\G}{\\e_4}{\\T} \\\\\n   \\isterm{\\G}{\\e_2}{\\PrEqual{\\T}{\\e_3}{\\e_4}}\n  }\n  {\\isterm\n     {\\G}\n     {\\PrElim{\\T}\n        {\\abst{x\\,y\\,p}{\\U}}\n        {\\abst{z}{\\e_1}}\n        {\\e_2}\n        {\\e_3}{\\e_4}\n     }\n     {\\substs{\\U}{\\e_2/x, \\e_3/y, \\e_4/p}}\n  }\n\\end{mathpar}\n\n\\paragraph{Equality types}\n\n\\begin{mathpar}\n  \\infer[\\rulename{term-refl}]\n  {\\isterm{\\G}{\\e}{\\T}}\n  {\\isterm{\\G}{\\juRefl{\\T} \\e}{\\JuEqual{\\T}{\\e}{\\e}}}\n\n  \\infer[\\rulename{term-G}]\n  {\\istype{\\G}{\\T}\n   \\\\\\\\\n   \\istype{\n     \\ctxextend{\\ctxextend{\\ctxextend{\\G}{x}{\\T}}{y}{\\T}}{p}{\\JuEqual{\\T}{x}{y}}\n   }{\\U}\n   \\\\\\\\\n   \\isterm\n     {\\ctxextend{\\G}{z}{\\T}}\n     {\\e_1}\n     {\\substs{\\U}{z/x, z/y, (\\juRefl{\\T}{z})/p}}\n   \\\\\\\\\n   \\isterm{\\G}{\\e_3}{\\T} \\\\\n   \\isterm{\\G}{\\e_4}{\\T} \\\\\n   \\isterm{\\G}{\\e_2}{\\JuEqual{\\T}{\\e_3}{\\e_4}}\n  }\n  {\\isterm\n     {\\G}\n     {\\JuElim{\\T}\n        {\\abst{x\\,y\\,p}{\\U}}\n        {\\abst{z}{\\e_1}}\n        {\\e_2}\n        {\\e_3}{\\e_4}\n     }\n     {\\substs{\\U}{\\e_2/x, \\e_3/y, \\e_4/p}}\n  }\n\\end{mathpar}\n\n\\paragraph{Unit}\n\n\\begin{mathpar}\n\\infer[\\rulename{term-star}]\n  {\\isctx{\\G}}\n  {\\isterm{\\G}{\\unitTerm}{\\Unit}}\n\\end{mathpar}\n\n\\paragraph{Names}\n\n\\begin{mathpar}\n  \\infer[\\rulename{term-coerce}]\n  {\\isterm{\\G}{\\e}{\\Universe{\\alpha}}\\\\\n   \\alpha \\leq \\beta}\n  {\\isterm{\\G}{\\coerce{\\alpha}{\\beta}{\\e}}{\\Universe{\\beta}}}\n\n  \\infer[\\rulename{name-unit}]\n  {\\isctx{\\G}}\n  {\\isterm{\\G}{\\nUnit}{\\Universe{\\zero}}}\n\n  \\infer[\\rulename{name-universe}]\n  {\\isctx{\\G} \\\\ \\uClose{\\alpha} = \\beta }\n  {\\isterm{\\G}{\\nUniverse{\\alpha}}{\\Universe{\\beta}}}\n\n  \\infer[\\rulename{name-prod}]\n  {\\isterm{\\G}{\\e_1}{\\Universe{\\alpha}} \\\\\n   \\isterm{\\ctxextend{\\G}{\\x}{\\El{\\alpha}{\\e_1}}}{\\e_2}{\\Universe{\\beta}} \\\\\n   \\piClose{\\alpha}{\\beta} = \\gamma\n  }\n  {\\isterm{\\G}{(\\nProd{\\alpha}{\\beta}{\\x}{\\e_1} \\e_2)}{\\Universe{\\gamma}}}\n\n  \\infer[\\rulename{name-paths}]\n  {\\isterm{\\G}{\\e_\\T}{\\Universe{\\alpha}}\\\\\n   \\alpha\\in\\FF\\\\\n   \\isterm{\\G}{\\e_1}{\\El{\\alpha}{\\e_\\T}}\\\\\n   \\isterm{\\G}{\\e_2}{\\El{\\alpha}{\\e_\\T}}\n  }\n  {\\isterm{\\G}{\\nPrEqual{\\alpha}{\\e_T}{\\e_1}{\\e_2}}{\\Universe{\\alpha}}}\n\n  \\infer[\\rulename{name-id}]\n  {\\isterm{\\G}{\\e_\\T}{\\Universe{\\alpha}}\\\\\n   \\isterm{\\G}{\\e_1}{\\El{\\alpha}{\\e_\\T}}\\\\\n   \\isterm{\\G}{\\e_2}{\\El{\\alpha}{\\e_\\T}}\n  }\n  {\\isterm{\\G}{\\nJuEqual{\\alpha}{\\e_\\T}{\\e_1}{\\e_2}}{\\Universe{\\alpha}}}\n\n\\end{mathpar}\n\n\\subsection{Type Equality}\n\n\\paragraph{General rules}\n\n\\begin{mathpar}\n  \\infer[\\rulename{tyeq-refl}]\n  {\\istype{\\G}{\\T}}\n  {\\eqtype{\\G}{\\T}{\\T}}\n\n  \\infer[\\rulename{tyeq-sym}]\n  {\\eqtype{\\G}{\\U}{\\T}}\n  {\\eqtype{\\G}{\\T}{\\U}}\n\n  \\infer[\\rulename{tyeq-trans}]\n  {\\eqtype{\\G}{\\T}{\\T'}\\\\\n   \\eqtype{\\G}{\\T'}{\\U}}\n  {\\eqtype{\\G}{\\T}{\\U}}\n\\end{mathpar}\n\n\n\\paragraph{Type formers are congruences}\n\n\\begin{mathpar}\n  \\infer[\\rulename{tycong-el}]\n  {\\eqterm{\\G}{\\e_1}{\\e_2}{\\Universe{\\alpha}}}\n  {\\eqtype{\\G}{\\El{\\alpha}{\\e_1}}{\\El{\\alpha}{\\e_2}}}\n\n  \\infer[\\rulename{tycong-prod}]\n  {\\eqtype{\\G}{\\T_1}{\\U_1}\\\\\n   \\eqtype{\\ctxextend{\\G}{\\x}{\\T_1}}{\\T_2}{\\U_2}}\n  {\\eqtype{\\G}{\\Prod{\\x}{\\T_1}{\\T_2}}{\\Prod{\\x}{\\U_1}{\\U_2}}}\n\n  \\infer[\\rulename{tycong-paths}]\n  {\\isfib{\\G}{\\T}\\\\\n   \\isfib{\\G}{\\U}\\\\\\\\\n   \\eqtype{\\G}{\\T}{\\U}\\\\\n   \\eqterm{\\G}{\\e_1}{\\e'_1}{\\T}\\\\\n   \\eqterm{\\G}{\\e_2}{\\e'_2}{\\T}\n  }\n  {\\eqtype{\\G}{\\PrEqual{\\T}{\\e_1}{\\e_2}}\n              {\\PrEqual{\\U}{\\e'_1}{\\e'_2}}}\n\n  \\infer[\\rulename{tycong-id}]\n  {\\eqtype{\\G}{\\T}{\\U}\\\\\n   \\eqterm{\\G}{\\e_1}{\\e'_1}{\\T}\\\\\n   \\eqterm{\\G}{\\e_2}{\\e'_2}{\\T}\n  }\n  {\\eqtype{\\G}{\\JuEqual{\\T}{\\e_1}{\\e_2}}\n              {\\JuEqual{\\U}{\\e'_1}{\\e'_2}}}\n\\end{mathpar}\n\n\n\\paragraph{Computation of types from names}\n\n\\begin{mathpar}\n  \\infer[\\rulename{tyeq-el-pi}]\n  {\\isterm{\\G}{\\e_1}{\\Universe{\\alpha}} \\\\\n   \\isterm{\\ctxextend{\\G}{x}{\\El{\\alpha}{\\e_1}}}{\\e_2}{\\Universe{\\beta}} \\\\\n   \\piClose{\\alpha}{\\beta} = \\gamma}\n  {\\eqtype{\\G}{\\El{\\gamma}{(\\nProd{\\alpha}{\\beta}{\\x}{\\e_1}{\\e_2})}}\n              {\\Prod{\\x}{\\El{\\alpha}{\\e_1}}{\\El{\\beta}{\\e_2}}}}\n\n  \\infer[\\rulename{tyeq-el-unit}]\n  { }\n  {\\eqtype{\\G}{\\El{\\zero}{\\nUnit}}{\\Unit}}\n\n  \\infer[\\rulename{tyeq-el-coerce}]\n  {\\isterm{\\G}{\\e}{\\Universe{\\alpha}} \\\\\n    \\alpha \\leq \\beta\n  }\n  {\\eqtype{\\G}{\\El{\\beta}{(\\coerce{\\alpha}{\\beta}{\\e})}}\n              {\\El{\\alpha}{\\e}}}\n\n  \\infer[\\rulename{tyeq-el-paths}]\n  {\\isterm{\\G}{\\e_\\T}{\\Universe{\\alpha}}\\\\\n   \\alpha\\in\\FF\\\\\n   \\isterm{\\G}{\\e_1}{\\El{\\alpha}{\\e_\\T}}\\\\\n   \\isterm{\\G}{\\e_2}{\\El{\\alpha}{\\e_\\T}}\n  }\n  {\\eqtype{\\G}\n          {\\El{\\alpha}{(\\nPrEqual{\\alpha}{\\e_T}{\\e_1}{\\e_2})}}\n          {\\PrEqual{\\El{\\alpha}{\\e_\\T}}{\\e_1}{\\e_2}}}\n\n  \\infer[\\rulename{tyeq-el-id}]\n  {\\isterm{\\G}{\\e_\\T}{\\Universe{\\alpha}}\\\\\n   \\isterm{\\G}{\\e_1}{\\El{\\alpha}{\\e_\\T}}\\\\\n   \\isterm{\\G}{\\e_2}{\\El{\\alpha}{\\e_\\T}}\n  }\n  {\\eqtype{\\G}\n          {\\El{\\alpha}{(\\nJuEqual{\\alpha}{\\e_\\T}{\\e_1}{\\e_2})}}\n          {\\JuEqual{\\El{\\alpha}{\\e_\\T}}{\\e_1}{\\e_2}}}\n\n\\end{mathpar}\n\n\\subsection{Term Equality}\n\nGeneral rules:\n\\begin{mathpar}\n  \\infer[\\rulename{eq-refl}]\n  {\\isterm{\\G}{\\e}{\\T}}\n  {\\eqterm{\\G}{\\e}{\\e}{\\T}}\n\n  \\infer[\\rulename{eq-sym}]\n  {\\eqterm{\\G}{\\e_2}{\\e_1}{\\T}}\n  {\\eqterm{\\G}{\\e_1}{\\e_2}{\\T}}\n\n  \\infer[\\rulename{eq-trans}]\n  {\\eqterm{\\G}{\\e_1}{\\e_2}{\\T}\\\\\n   \\eqterm{\\G}{\\e_2}{\\e_3}{\\T}}\n  {\\eqterm{\\G}{\\e_1}{\\e_3}{\\T}}\n\n  \\infer[\\rulename{eq-eq}]\n  {\\eqterm{\\G}{\\e_1}{\\e_2}{\\T}\\\\\n    \\eqtype{\\G}{\\T}{\\U}}\n  {\\eqterm{\\G}{\\e_1}{\\e_2}{\\U}}\n\\end{mathpar}\n\n\n\\paragraph{Congruence rules for products}\n\n%\n\\begin{mathpar}\n  \\infer[\\rulename{cong-abs}]\n  {\\eqtype{\\G}{\\T_1}{\\U_1}\\\\\n    \\eqtype{\\ctxextend{\\G}{\\x}{\\T_1}}{\\T_2}{\\U_2}\\\\\n    \\eqterm{\\ctxextend{\\G}{\\x}{\\T_1}}{\\e_1}{\\e_2}{\\T_2}}\n  {\\eqterm{\\G}{(\\lam{\\x}{\\T_1}{\\T_2}{\\e_1})}\n              {(\\lam{\\x}{\\U_1}{\\U_2}{\\e_2})}\n              {\\Prod{\\x}{\\T_1}{\\T_2}}}\n\n  \\infer[\\rulename{cong-app}]\n  {\\eqtype{\\G}{\\T_1}{\\U_1}\\\\\n   \\eqtype{\\ctxextend{\\G}{\\x}{\\T_1}}{\\T_2}{\\U_2}\\\\\\\\\n   \\eqterm{\\G}{\\e_1}{\\e'_1}{\\Prod{\\x}{\\T_1}{\\T_2}}\\\\\n   \\eqterm{\\G}{\\e_2}{\\e'_2}{\\T_1}}\n  {\\eqterm{\\G}{(\\app{\\e_1}{\\x}{\\T_1}{\\T_2}{\\e_2})}{(\\app{\\e'_1}{\\x}{\\U_1}{\\U_2}{\\e'_2})}{\\subst{\\T_2}{\\x}{\\e_2}}}\n\\end{mathpar}\n\nThe annotations on an application really do matter for determining when two\nterms are equal. For example, if $X,Y : \\Universe{\\zero}$, $f : \\mathsf{nat}\\to X$ and $e\n: \\JuEqual{\\Universe{\\zero}}{\\mathsf{nat}{\\to}X}{\\mathsf{nat}{\\to}Y}$, then\n$(\\app{f}{\\_}{\\mathsf{nat}}{X} 0) : X$ and $(\\app{f}{\\_}{\\mathsf{nat}}{Y} 0) : Y$,\nso the two identical-but-for-annotations terms have different types and thus\ncannot be equivalent.\n\n\\paragraph{Other rules for products}\n\n%\n\\begin{mathpar}\n\\infer[\\rulename{eq-beta}]\n  {\\eqtype{\\G}{\\T_1}{\\U_1}\\\\\n    \\eqtype{\\ctxextend{\\G}{\\x}{\\T_1}}{\\T_2}{\\U_2}\\\\\n    \\isterm{\\ctxextend{\\G}{\\x}{\\T_1}}{\\e_1}{\\T_2}\\\\\n    \\isterm{\\G}{\\e_2}{\\U_1}}\n  {\\eqterm{\\G}{\\bigl(\\app{(\\lam{\\x}{\\T_1}{\\T_2}{\\e_1})}{\\x}{\\U_1}{\\U_2}{\\e_2}\\bigr)}\n              {\\subst{\\e_1}{\\x}{\\e_2}}\n              {\\subst{\\T_2}{\\x}{\\e_2}}}\n\\end{mathpar}\n\n\n\\begin{mathpar}\n  \\infer[\\rulename{eq-ext}]\n  {\\isterm{\\G}{\\e_1}{\\Prod{\\x}{\\T}{\\U}}\\\\\n   \\isterm{\\G}{\\e_2}{\\Prod{\\x}{\\T}{\\U}}\\\\\\\\\n   \\eqterm{\\ctxextend{\\G}{\\x}{\\T}}{(\\app{\\e_1}{\\x}{\\T}{\\U}{\\x})}\n          {(\\app{\\e_2}{\\x}{\\T}{\\U}{\\x})}{\\U}\n  }\n  {\\eqterm{\\G}{\\e_1}{\\e_2}{\\Prod{\\x}{\\T}{\\U}}}\n\\end{mathpar}\n\n\\paragraph{Eta rule for unit type}\n\n\\begin{mathpar}\n  \\infer[\\rulename{eta-star}]\n  {\\isterm{\\G}{\\e}{\\Unit}}\n  {\\eqterm{\\G}{\\e}{\\unitTerm}{\\Unit}}\n\\end{mathpar}\n\n\\paragraph{Congruence rules for paths}\n\n%\n\\begin{mathpar}\n\\infer[\\rulename{cong-idpath}]\n  {\\eqterm{\\G}{\\e_1}{\\e_2}{\\T}\\\\\n   \\eqtype{\\G}{\\T}{\\U}\\\\\n   \\isfib{\\G}{\\T}\\\\\n   \\isfib{\\G}{\\U}}\n  {\\eqterm{\\G}{\\prRefl{\\T}{\\e_1}}{\\prRefl{\\U}{\\e_2}}{\\PrEqual{\\T}{\\e_1}{\\e_1}}}\n\n  \\infer[\\rulename{cong-J}]\n  {\\isfib{\\G}{\\T} \\\\\n   \\isfib{\\G}{\\U}\n   \\\\\\\\\n   \\isfib{\n     \\ctxextend{\\ctxextend{\\ctxextend{\\G}{x}{\\T}}{y}{\\T}}{p}{\\PrEqual{\\T}{x}{y}}\n   }{P}\n   \\\\\n   \\isfib{\n     \\ctxextend{\\ctxextend{\\ctxextend{\\G}{x}{\\U}}{y}{\\U}}{p}{\\PrEqual{\\U}{x}{y}}\n   }{Q}\n   \\\\\\\\\n   \\eqtype{\\G}{\\T}{\\U} \\\\\n   \\eqtype{\n     \\ctxextend{\\ctxextend{\\ctxextend{\\G}{x}{\\T}}{y}{\\T}}{p}{\\PrEqual{\\T}{x}{y}}\n   }{P}{Q} \\\\\\\\\n   \\eqterm{\\ctxextend{\\G}{z}{\\T}}{\\e_1}{\\e'_1}{\\substs{P}{z/x, z/y, (\\prRefl{\\T}{z})/p}}\n   \\\\\\\\\n   \\eqterm{\\G}{\\e_3}{\\e'_3}{T} \\\\\n   \\eqterm{\\G}{\\e_4}{\\e'_4}{T} \\\\\n   \\eqterm{\\G}{\\e_2}{\\e'_2}{\\PrEqual{\\T}{\\e_3}{\\e_4}}\n  }\n  {\\eqterm\n     {\\G}\n     {\\PrElim{\\T}\n        {\\abst{x\\,y\\,p}{P}}\n        {\\abst{z}{\\e_1}}\n        {\\e_2}\n        {\\e_3}{\\e_4}\n     }\n     {\\PrElim{\\U}\n        {\\abst{x\\,y\\,p}{Q}}\n        {\\abst{z}{\\e'_1}}\n        {\\e'_2}\n        {\\e'_3}{\\e'_4}\n     }\n     {\\substs{P}{\\e_2/x, \\e_3/y, \\e_4/p}}\n  }\n\n\\end{mathpar}\n\n\n\\paragraph{Computation rule for paths}\n\n%\n\\begin{mathpar}\n  \\infer[\\rulename{eq-J}]\n  {\\isfib{\\G}{\\T}\n   \\\\\n   \\isfib{\n     \\ctxextend{\\ctxextend{\\ctxextend{\\G}{x}{\\T}}{y}{\\T}}{p}{\\PrEqual{\\T}{x}{y}}\n   }{\\U}\n   \\\\\\\\\n   \\isterm\n     {\\ctxextend{\\G}{z}{\\T}}\n     {\\e_1}\n     {\\substs{\\U}{z/x, z/y, (\\prRefl{\\T}{z})/p}}\n   \\\\\n   \\isterm{\\G}{\\e_2}{\\T}\n  }\n  {\\eqterm{\\G}\n   {\\PrElim{\\T}\n        {\\abst{x\\,y\\,p}{\\U}}\n        {\\abst{z}{\\e_1}}\n        {\\prRefl{\\T}{\\e_2}}\n        {\\e_2}\n        {\\e_2}\n   }\n   {\\subst{\\e_1}{z}{\\e_2}}\n   {\\substs{\\U}{\\e_2/x, \\e_2/x, (\\prRefl{T}{\\e_2})/p}}\n  }\n\\end{mathpar}\n\n\n\\paragraph{Congruence rules for equalities}\n\n%\n\\begin{mathpar}\n\\infer[\\rulename{cong-refl}]\n{\\eqterm{\\G}{\\e_1}{\\e_2}{\\T}\\\\\n \\eqtype{\\G}{\\T}{\\U}}\n{\\eqterm{\\G}{\\juRefl{\\T} \\e_1}{\\juRefl{\\U} \\e_2}{\\JuEqual{\\T}{\\e_1}{\\e_1}}}\n\n\\infer[\\rulename{cong-G}]\n  {\\eqtype{\\G}{\\T}{\\U} \\\\\n   \\eqtype{\n     \\ctxextend{\\ctxextend{\\ctxextend{\\G}{x}{\\T}}{y}{\\T}}{p}{\\JuEqual{\\T}{x}{y}}\n   }{\\U}{V} \\\\\\\\\n   \\eqterm{\\ctxextend{\\G}{z}{\\T}}{\\e_1}{\\e'_1}{\\substs{\\U}{z/x, z/y, (\\juRefl{\\T} z)/p}}\n   \\\\\\\\\n   \\isterm{\\G}{\\e_3}{T} \\\\\n   \\isterm{\\G}{\\e_4}{T} \\\\\n   \\eqterm{\\G}{\\e_3}{\\e'_3}{\\T} \\\\\n   \\eqterm{\\G}{\\e_4}{\\e'_4}{\\T} \\\\\n   \\eqterm{\\G}{\\e_2}{\\e'_2}{\\JuEqual{\\T}{\\e_3}{\\e_4}}\n  }\n  {\\eqterm\n     {\\G}\n     {\\JuElim{\\T}\n        {\\abst{x\\,y\\,p}{\\U}}\n        {\\abst{z}{\\e_1}}\n        {\\e_2}{\\e_3}{\\e_4}\n     }\n     {\\JuElim{\\U}\n        {\\abst{x\\,y\\,p}{V}}\n        {\\abst{z}{\\e'_1}}\n        {\\e'_2}{\\e_3'}{\\e_4'}\n     }\n     {\\substs{\\U}{\\e_2/x, \\e_3/y, \\e_4/p}}\n  }\n\\end{mathpar}\n\n\n\\paragraph{Eta rules for equalities}\n\n%\n\\begin{mathpar}\n\\infer[\\rulename{K-refl}]\n{\\isterm{\\G}{\\e_1}{\\JuEqual{\\T}{\\e_2}{\\e_2}}}\n{\\eqterm{\\G}{\\e_1}{(\\juRefl{\\T} \\e_2)}{\\JuEqual{\\T}{\\e_2}{\\e_2}}}\n\\end{mathpar}\n\n\\paragraph{Equality reflection}\n\n%\n\\begin{mathpar}\n  \\infer[\\rulename{eq-reflection}]\n  {\\isterm{\\G}{\\e}{\\JuEqual{\\T}{\\e_1}{\\e_2}}}\n  {\\eqterm{\\G}{\\e_1}{\\e_2}{\\T}}\n\\end{mathpar}\n\n\n\\paragraph{Computation rule for equality}\n\n%\n\\begin{mathpar}\n  \\infer[\\rulename{eq-G}]\n  {\\istype{\\G}{\\T}\n   \\\\\n   \\istype{\n     \\ctxextend{\\ctxextend{\\ctxextend{\\G}{x}{\\T}}{y}{\\T}}{p}{\\JuEqual{\\T}{x}{y}}\n   }{\\U}\n   \\\\\\\\\n   \\isterm\n     {\\ctxextend{\\G}{z}{\\T}}\n     {\\e_1}\n     {\\substs{\\U}{z/x, z/y, (\\juRefl{\\T} z)/p}}\n   \\\\\n   \\isterm{\\G}{\\e_2}{\\T}\n  }\n  {\\eqterm{\\G}\n   {\\JuElim{\\T}\n        {\\abst{x\\,y\\,p}{\\U}}\n        {\\abst{z}{\\e_1}}\n        {\\juRefl{\\T} \\e_2}\n        {\\e_2}\n        {\\e_2}\n   }\n   {\\subst{\\e_1}{z}{\\e_2}}\n   {\\substs{\\U}{\\e_2/x, \\e_2/x, (\\juRefl{T} \\e_2)/p}}\n  }\n\\end{mathpar}\n\n\\paragraph{Congruence rules for names}\n\n%\n\\begin{mathpar}\n\\infer[\\rulename{cong-name-prod}]\n  {\\eqterm{\\G}{\\e_1}{\\e'_1}{\\Universe{\\alpha}}\\\\\n   \\eqterm{\\ctxextend{\\G}{\\x}{\\El{\\alpha}{\\e_1}}}{\\e_2}{\\e'_2}{\\Universe{\\beta}} \\\\\n   \\piClose{\\alpha}{\\beta} = \\gamma}\n  {\\eqterm{\\G}{(\\nProd{\\alpha}{\\beta}{\\x}{\\e_1}{\\e_2})}{(\\nProd{\\alpha}{\\beta}{\\x}{\\e'_1}{\\e'_2})}{\\Universe{\\gamma}}}\n\n\\infer[\\rulename{cong-name-universe}]\n{\\isctx{\\G} \\\\\n  \\uClose{\\alpha} = \\gamma\n}\n{\\eqterm{\\G}{\\nUniverse{\\alpha}}{\\nUniverse{\\alpha}}{\\Universe{\\gamma}}}\n\n\\infer[\\rulename{cong-name-paths}]\n{\\alpha\\in\\FF\\\\\n  \\eqterm{\\G}{\\e_1}{\\e'_1}{\\Universe{\\alpha}}\\\\\n  \\eqterm{\\G}{\\e_2}{\\e'_2}{\\El{\\alpha}{\\e_1}}\\\\\n  \\eqterm{\\G}{\\e_3}{\\e'_3}{\\El{\\alpha}{\\e_1}}\n}\n{\\eqterm{\\G}{\\nPrEqual{\\alpha}{\\e_1}{\\e_2}{\\e_3}}{\\nPrEqual{\\alpha}{\\e'_1}{\\e'_2}{\\e'_3}}{\\Universe{\\alpha}}}\n\n\\infer[\\rulename{cong-name-id}]\n{ \\eqterm{\\G}{\\e_1}{\\e'_1}{\\Universe{\\alpha}}\\\\\n  \\eqterm{\\G}{\\e_2}{\\e'_2}{\\El{\\alpha}{\\e_1}}\\\\\n  \\eqterm{\\G}{\\e_3}{\\e'_3}{\\El{\\alpha}{\\e_1}}\n}\n{\\eqterm{\\G}{\\nJuEqual{\\alpha}{\\e_1}{\\e_2}{\\e_3}}{\\nJuEqual{\\alpha}{\\e'_1}{\\e'_2}{\\e'_3}}{\\Universe{\\alpha}}}\n\\end{mathpar}\n\n\n\\paragraph{Congruence rule for coercions}\n\n%\n\\begin{mathpar}\n  \\infer[\\rulename{cong-name-coerce}]\n  {\\eqterm{\\G}{\\e_1}{\\e_2}{\\Universe{\\alpha}} \\\\\n    \\alpha \\leq \\beta\n  }\n  {\\eqterm{\\G}{(\\coerce{\\alpha}{\\beta}{\\e_1})}\n              {(\\coerce{\\alpha}{\\beta}{\\e_2})}\n              {\\Universe{\\beta}}}\n\\end{mathpar}\n\n\n\\paragraph{Functoriality of coercions}\n\n%\n\\begin{mathpar}\n\\infer[\\rulename{eq-name-coerce-trivial}]\n  {\\isterm{\\G}{\\e}{\\Universe{\\alpha}}}\n  {\\eqterm{\\G}{(\\coerce{\\alpha}{\\e})}{\\e}{\\Universe{\\alpha}}}\n\n\\infer[\\rulename{eq-name-coerce-trans}]\n  {\\isterm{\\G}{\\e}{\\Universe{\\alpha}} \\\\\n    \\alpha \\leq \\beta \\leq \\gamma}\n  {\\eqterm{\\G}{\\coerce{\\beta}{\\gamma}{(\\coerce{\\alpha}{\\beta}{\\e})})}\n              {\\coerce{\\alpha}{\\gamma}{\\e}}\n              {\\Universe{\\gamma}}}\n\\end{mathpar}\n\n\n\\section{Algorithmic formulation}\n\\label{sec:bidir-type-theory}\n\nWe now define a bidirectional version of type theory amenable to algorithmic treatment. We\nreplace the equality eliminator with equality and rewrite hints.\n\n\\subsection{Syntax}\n\\label{sec:syntax-bidirectional}\n\nContexts:\n%\n\\begin{equation*}\n  \\G\n  \\begin{aligned}[t]\n    \\bnf   {}& \\ctxempty & & \\text{empty context}\\\\\n    \\bnfor {}& \\ctxextend{\\G}{\\x}{\\T} & & \\text{context extended with $x : T$}\n  \\end{aligned}\n\\end{equation*}\n%\nEquality hints:\n%\n\\begin{equation*}\n  \\H\n  \\begin{aligned}[t]\n    \\bnf   {}& \\hintempty & & \\text{empty hints}\\\\\n    \\bnfor {}& \\addhinteq{\\H}{\\e_1}{\\e_2}{\\T} & & \\text{extend hints with an equation} \\\\\n    \\bnfor {}& \\addhintrw{\\H}{\\e_1}{\\e_2}{\\T} & & \\text{extend hints with a reduction} \\\\\n  \\end{aligned}\n\\end{equation*}\n%\nTypes:\n%\n\\begin{equation*}\n  \\T, \\U\n  \\begin{aligned}[t]\n    \\bnf   {}& \\Universe{\\alpha} & & \\text{universe}\\\\\n    \\bnfor {}& \\El{\\inferred\\alpha}{\\e} & & \\text{type named by $e$}\\\\\n    \\bnfor {}& \\Unit & & \\text{the unit type}\\\\\n    \\bnfor {}& \\Prod{x}{\\T} \\U & & \\text{product}\\\\\n    \\bnfor {}& \\PrEqual{\\inferred{T}}{\\e_1}{\\e_2} & & \\text{path type}\\\\\n    \\bnfor {}& \\JuEqual{\\inferred{T}}{\\e_1}{\\e_2} & & \\text{equality type}\n  \\end{aligned}\n\\end{equation*}\n%\nTerms:\n%\n\\begin{equation*}\n  \\e\n  \\begin{aligned}[t]\n    \\bnf   {}&  \\x   &&\\text{variable} \\\\\n    \\bnfor {}&  \\equationin{\\e_1}{\\inferred{\\e_2}}{\\inferred{\\e_3}} e_4 &&\\text{use equality hint $\\e_1$ in $\\e_4$} \\\\\n    \\bnfor {}&  \\rewritein{\\e_1}{\\inferred{\\e_2}}{\\inferred{\\e_3}} e_4 &&\\text{use rewrite hint $\\e_1$ in $\\e_4$} \\\\\n    \\bnfor {}&  \\ascribe{\\e}{\\T}  &&\\text{ascribe type $\\T$ to term $\\e$} \\\\\n    \\bnfor {}&  \\lam{\\x}{\\T_1}{\\inferred{\\T_2}} \\e  &&\\text{$\\lambda$-abstraction} \\\\\n    \\bnfor {}&  \\app{\\e_1}{\\inferred\\x}{\\inferred{\\T_1}}{\\inferred{\\T_2}}{\\e_2}  &&\\text{application} \\\\\n    \\bnfor {}&  \\unitTerm  &&\\text{the element of unit type} \\\\\n    \\bnfor {}&  \\prRefl{\\inferred\\T}{\\e}  &&\\text{identity path} \\\\\n    \\bnfor {}&  \\PrElim{\\inferred\\T}{\\abst{x\\,y\\,p}{\\U}}{\\abst{z}{\\e_1}}{\\e_2}{\\inferred{\\e_3}}{\\inferred{\\e_4}}  &&\\text{path eliminator} \\\\\n    \\bnfor {}&  \\juRefl{\\inferred\\T} \\e  &&\\text{reflexivity} \\\\\n    \\bnfor {}&  \\coerce{\\inferred\\alpha}{\\beta}{\\e}  &&\\text{universe coercion} \\\\\n    \\bnfor {}&  \\nUnit  &&\\text{the name of unit type} \\\\\n    \\bnfor {}&  \\nProd{\\inferred\\alpha}{\\inferred\\beta}{\\x}{\\e_1} \\e_2  &&\\text{the name of product type} \\\\\n    \\bnfor {}&  \\nUniverse{\\alpha} &&\\text{the name of a universe} \\\\\n    \\bnfor {}&  \\nPrEqual{\\inferred\\alpha}{\\e_1}{\\e_2}{\\e_3}  &&\\text{the name of a path type} \\\\\n    \\bnfor {}&  \\nJuEqual{\\inferred\\alpha}{\\e_1}{\\e_2}{\\e_3}  &&\\text{the name of an equality type}\n  \\end{aligned}\n\\end{equation*}\n\nThe annotations marked {\\inferred{like this}} could be omitted from the initial input because they\ncan be reconstructed on the fly during type checking/synthesis. They are extremely useful during\nequivalence checking.\n\n\\subsection{Judgments}\n\\label{sec:algorithmic-judgments}\n\n\\begin{align*}\n& \\ishints{\\G}{\\H} & & \\text{$\\H$ consists of legal hints} \\\\\n& \\istypealg{\\GH}{\\T} & & \\text{$\\T$ is a well-formed type} \\\\\n& \\isfibalg{\\GH}{\\T} & & \\text{$\\T$ is a well-formed fibered type} \\\\\n& \\chkterm{\\GH}{\\e}{\\T} & & \\text{check that term $\\e$ has type $T$} \\\\\n& \\synterm{\\GH}{\\e}{\\T} & & \\text{synthesize type $\\T$ of term $e$} \\\\\n& \\eqtypealg{\\GH}{\\T}{\\U} & & \\text{$\\T$ and $\\U$ are equal types} \\\\\n& \\eqtypepath{\\GH}{\\T}{\\U} & & \\text{$\\T$ and $\\U$ are equal normal types} \\\\\n& \\eqtermalg{\\GH}{\\e_1}{\\e_2}{\\T} & & \\text{$\\e_1$ and $\\e_2$ are equal terms of type $\\T$} \\\\\n& \\eqtermext{\\GH}{\\e_1}{\\e_2}{\\T} & & \\text{$\\e_1$ and $\\e_2$ are equal terms of normal type $\\T$} \\\\\n& \\eqpath{\\GH}{\\e_1}{\\e_2}{\\T} & & \\text{$\\e_1$ and $\\e_2$ are equal normal terms of same type} \\\\\n& \\tywhnf{\\GH}{\\T_1}{\\T_2}{\\H'} & & \\text{type $\\T_1$ has a reduction step to $\\T_2$ yielding hints $\\H'$ } \\\\\n& \\tywhnfs{\\GH}{\\T_1}{\\T_2} & & \\text{type $\\T_1$ normalizes to $\\T_2$ } \\\\\n& \\whnf{\\GH}{\\e_1}{\\e_2}{\\H'} & & \\text{term $\\e_1$ has a reduction step to $\\e_2$ yielding hints $\\H'$} \\\\\n& \\whnfs{\\GH}{\\e_1}{\\e_2} & & \\text{term $\\e_1$ normalizes to $\\e_2$ }\n\\end{align*}\n\n\\subsection{Contexts with hints}\n\\label{sec:contexts-with-hints}\n\n\\begin{mathpar}\n  \\infer[\\rulename{hint-empty}]\n  {\\isctx{\\G}}\n  {\\ishints{\\G}{\\hintempty}}\n\n  \\infer[\\rulename{hint-eq}]\n  {\\ishints{\\G}{\\H} \\\\\n   \\eqterm{\\G}{\\e_1}{\\e_2}{\\T}\n  }\n  {\\ishints{\\G}{(\\addhinteq{\\H}{\\e_1}{\\e_2})}}\n\n  \\infer[\\rulename{hint-rw}]\n  {\\ishints{\\G}{\\H} \\\\\n   \\eqterm{\\G}{\\e_1}{\\e_2}{\\T}\n  }\n  {\\ishints{\\G}{(\\addhintrw{\\H}{\\e_1}{\\e_2})}}\n\n\\end{mathpar}\n%\nNote that this judgment is \\emph{not} invoked by the algorithm. It is used only in\ndescribing the conditions under which the algorithm is expected to work.\n\n\\subsection{Well-formed types}\n\\label{sec:algorithmic-types}\n\n\\begin{mathpar}\n  \\infer[\\rulename{tychk-universe}]\n  {\\alpha \\in \\PP\n  }\n  {\\istypealg{\\GH}{\\Universe{\\alpha}}}\n\n  \\infer[\\rulename{tychk-prod}]\n  {\\istypealg{\\GH}{\\T} \\\\\n   \\istypealg{\\ctxs{(\\ctxextend{\\G}{\\x}{\\T})}{\\H}}{\\U}\n  }\n  {\\istypealg{\\GH}{\\Prod{\\x}{\\T}{\\U}}}\n\n  \\infer[\\rulename{tychk-el}]\n  {\\synterm{\\GH}{\\e}{\\T}\\\\\n   \\whnfs{\\GH}{\\T}{\\Universe{\\alpha}}\n  }\n  {\\istypealg{\\GH}{\\El{\\inferred\\alpha}{\\e}}}\n\n  \\infer[\\rulename{tychk-unit}]\n  {\n  }\n  {\\istypealg{\\GH}{\\Unit}}\n\n  \\infer[\\rulename{tychk-paths}]\n  {\n   \\synterm{\\GH}{\\e_1}{\\T}\\\\\n   \\simplefib{\\T} = \\true\\\\\n   \\chkterm{\\GH}{\\e_2}{\\T}\n  }\n  {\\istypealg{\\GH}{\\PrEqual{\\inferred\\T}{\\e_1}{\\e_2}}}\n\n  \\infer[\\rulename{tychk-id}]\n  {\n   \\synterm{\\GH}{\\e_1}{\\T}\\\\\n   \\chkterm{\\GH}{\\e_2}{\\T}\n  }\n  {\\istypealg{\\GH}{\\JuEqual{\\inferred\\T}{\\e_1}{\\e_2}}}\n\\end{mathpar}\n\n\n\\subsection{Well-formed fibered types}\n\\label{sec:algorithmic-fibered-types}\n\n\\begin{mathpar}\n  \\infer[\\rulename{fibchk-universe}]\n  {\\alpha \\in \\PP\n  }\n  {\\isfibalg{\\GH}{\\Universe{\\alpha}}}\n\n  \\infer[\\rulename{fibchk-prod}]\n  {\\isfibalg{\\GH}{\\T} \\\\\n   \\isfibalg{\\ctxs{(\\ctxextend{\\G}{\\x}{\\T})}{\\H}}{\\U}\n  }\n  {\\isfibalg{\\GH}{\\Prod{\\x}{\\T}{\\U}}}\n\n  \\infer[\\rulename{fibchk-el}]\n  {\\synterm{\\GH}{\\e}{\\Universe{\\alpha}}\\\\\n   \\alpha\\in\\FF\n  }\n  {\\isfibalg{\\GH}{\\El{\\inferred\\alpha}{\\e}}}\n\n  \\infer[\\rulename{fibchk-unit}]\n  {\\zero \\in \\FF}\n  {\\isfibalg{\\GH}{\\Unit}}\n\n  \\infer[\\rulename{fibchk-paths}]\n  {\n   \\synterm{\\GH}{\\e_1}{\\T}\\\\\n   \\simplefib{\\T} = \\true\\\\\n   \\chkterm{\\GH}{\\e_2}{\\T}\n  }\n  {\\isfibalg{\\GH}{\\PrEqual{\\inferred\\T}{\\e_1}{\\e_2}}}\n\\end{mathpar}\n%\nIf we already know the given type is well-formed, there's an even simpler algorithm to see if it is fibered:\n%\n\n\\begin{align*}\n\\simplefib{\\Universe{\\alpha}}        & \\;\\mathrel{{:}{=}}\\;  \\true \\\\\n\\simplefib{\\Prod{\\x}{\\T}{\\U}}        & \\;\\mathrel{{:}{=}}\\;  \\simplefib{T}\\ \\land\\ \\simplefib{U} \\\\\n\\simplefib{\\El{\\alpha}{\\e}}          & \\;\\mathrel{{:}{=}}\\;  \\alpha\\in\\FF \\\\\n\\simplefib{\\Unit}                    & \\;\\mathrel{{:}{=}}\\;  \\zero\\in\\FF \\\\\n\\simplefib{\\PrEqual{\\T}{\\e_1}{\\e_2}} & \\;\\mathrel{{:}{=}}\\;  \\true \\\\\n\\simplefib{\\JuEqual{\\T}{\\e_1}{\\e_2}} & \\;\\mathrel{{:}{=}}\\;  \\false\n\\end{align*}\n\n\\subsection{Terms}\n\\label{sec:algorithmic-terms}\n\n\\paragraph{General rules}\n\n\\begin{mathpar}\n  \\infer[\\rulename{syn-var}]\n  {\n    (\\x {:} \\T) \\in \\G\n  }\n  { \\synterm{\\GH}{\\x}{\\T}}\n\n  \\infer[\\rulename{syn-ascribe}]\n  {\\istypealg{\\GH}{\\T} \\\\\n   \\chkterm{\\GH}{\\e}{\\T}}\n  { \\synterm{\\GH}{\\ascribe{\\e}{\\T}}{\\T} }\n\n  \\infer[\\rulename{chk-syn}]\n  { \\synterm{\\GH}{\\e}{\\U} \\\\\n    \\eqtypealg{\\GH}{\\U}{\\T}\n  }\n  { \\chkterm{\\GH}{\\e}{\\T} }\n\\end{mathpar}\n\n\\paragraph{Hints}\n\n\\begin{mathpar}\n  \\infer[\\rulename{syn-equation-hint}]\n  { \\synterm{\\GH}{\\e_1}{\\U'} \\\\\n    \\whnfs{\\GH}{\\U'}{\\JuEqual{\\U}{\\e_2}{\\e_3}} \\\\\\\\\n    \\synterm{\\ctxs{\\G}{(\\addhinteq{\\H}{\\e_2}{\\e_3})}}{\\e_4}{\\T}\n  }\n  { \\synterm{\\GH}{(\\equationin{\\e_1}{\\inferred{\\e_2}}{\\inferred{\\e_3}} \\e_4)}{\\T} }\n\n  \\infer[\\rulename{chk-equation-hint}]\n  { \\synterm{\\GH}{\\e_1}{\\U'} \\\\\n    \\whnfs{\\GH}{\\U'}{\\JuEqual{\\U}{\\e_2}{\\e_3}} \\\\\\\\\n    \\chkterm{\\ctxs{\\G}{(\\addhinteq{\\H}{\\e_2}{\\e_3})}}{\\e_4}{\\T}\n  }\n  { \\chkterm{\\GH}{(\\equationin{\\e_1}{\\inferred{\\e_2}}{\\inferred{\\e_3}} \\e_4)}{\\T} }\n\n  \\infer[\\rulename{syn-rw-hint}]\n  { \\synterm{\\GH}{\\e_1}{\\U'} \\\\\n    \\whnfs{\\GH}{\\U'}{\\JuEqual{\\U}{\\e_2}{\\e_3}} \\\\\\\\\n    \\synterm{\\ctxs{\\G}{(\\addhintrw{\\H}{\\e_2}{\\e_3})}}{\\e_4}{\\T}\n  }\n  { \\synterm{\\GH}{(\\rewritein{\\e_1}{\\inferred{\\e_2}}{\\inferred{\\e_3}} \\e_4)}{\\T} }\n\n  \\infer[\\rulename{chk-rw-hint}]\n  { \\synterm{\\GH}{\\e_1}{\\U'} \\\\\n    \\whnfs{\\GH}{\\U'}{\\JuEqual{\\U}{\\e_2}{\\e_3}} \\\\\\\\\n    \\chkterm{\\ctxs{\\G}{(\\addhintrw{\\H}{\\e_2}{\\e_3})}}{\\e_4}{\\T}\n  }\n  { \\chkterm{\\GH}{(\\rewritein{\\e_1}{\\inferred{\\e_2}}{\\inferred{\\e_3}} \\e_4)}{\\T} }\n\\end{mathpar}\n\nRules~\\rulename{chk-equation-hint} and~\\rulename{chk-reduce-hint} are among the\nfew rules that perform checking differently than the default\nRule~\\rulename{chk-syn}. When they apply, we try them first (despite\nRule~\\rulename{chk-syn} being listed first in this section). In practice, if the\nrule fails, we will not backtrack and try to check without the hint.\n\n\\paragraph{Products}\n\n\\begin{mathpar}\n  \\infer[\\rulename{syn-abs}]\n  { \\istypealg{\\GH}{\\T} \\\\\n    \\synterm{\\ctxextend{\\G}{\\x}{\\T} ; \\H}{\\e}{\\U} }\n  { \\synterm{\\GH}{(\\lam{\\x}{\\T}{\\inferred\\U} \\e)}{\\Prod{\\x}{\\T} \\U} }\n\n  \\infer[\\rulename{syn-app}]\n  { \\synterm{\\GH}{\\e_1}{\\T_1} \\\\\n    \\whnfs{\\GH}{\\T_1}{\\Prod{\\x}{\\T} \\U}\\\\\n    \\chkterm{\\GH}{\\e_2}{\\T}\n  }\n  { \\synterm{\\GH}{\\app{\\e_1}{\\inferred{\\x}}{\\inferred\\T}{\\inferred\\U}{\\e_2}}{\\subst{\\U}{\\x}{\\e_2}} }\n\\end{mathpar}\n\n\\paragraph{Unit type}\n\n\\begin{mathpar}\n  \\infer[\\rulename{syn-unit}]\n  { }\n  { \\synterm{\\GH}{\\unitTerm}{\\Unit} }\n\\end{mathpar}\n\n\\paragraph{Path type}\n\n\\begin{mathpar}\n  \\infer[\\rulename{syn-idpath}]\n  { \\synterm{\\GH}{\\e}{\\T} }\n  { \\synterm{\\GH}{\\prRefl{\\inferred\\T}{\\e}}{\\PrEqual{\\T}{\\e}{\\e}} }\n\n  \\infer[\\rulename{syn-j}]\n  {\n    \\synterm{\\GH}{\\e_2}{\\T_2}\\\\\n    \\whnfs{\\GH}{\\T_2}{\\PrEqual{\\T}{\\e_3}{\\e_4}} \\\\\n    \\isfibalg{\n      \\ctxextend{\\ctxextend{\\ctxextend{\\G}{x}{\\T}}{y}{\\T}}{p}{\\PrEqual{\\T}{x}{y}} ;\n      \\H\n    }{\\U}\n    \\\\\n    \\chkterm\n      {\\ctxextend{\\G}{z}{\\T} ; \\H}\n      {\\e_1}\n      {\\substs{\\U}{z/x, z/y, (\\prRefl{\\T}{z})/p}}\n  }\n  { \\synterm{\\GH}{\n     \\PrElim{\\inferred{\\T}}\n             {\\abst{x\\,y\\,p}{\\U}}\n             {\\abst{z}{\\e_1}}\n             {\\e_2}{\\inferred{\\e_3}}{\\inferred{\\e_4}}\n    }{\n      \\substs{\\U}{\\e_3/x, \\e_4/y, \\e_2/p}\n    }\n  }\n\\end{mathpar}\n\n\\paragraph{Equality type}\n\n\\begin{mathpar}\n  \\infer[\\rulename{syn-refl}]\n  { \\synterm{\\GH}{\\e}{\\T} }\n  { \\synterm{\\GH}{\\juRefl{\\inferred\\T}{\\e}}{\\JuEqual{\\inferred\\T}{\\e}{\\e}} }\n\n\\end{mathpar}\n\n\\paragraph{Names}\n\n\\begin{mathpar}\n  \\infer[\\rulename{syn-name-unit}]\n  { }\n  { \\synterm{\\GH}{\\nUnit}{\\Universe{\\zero}} }\n\n  \\infer[\\rulename{syn-name-universe}]\n  {\n    \\beta = \\uClose{\\alpha}\n  }\n  { \\synterm{\\GH}{\\nUniverse{\\alpha}}{\\Universe{\\beta}} }\n\n  \\infer[\\rulename{syn-name-prod}]\n  { \\synterm{\\GH}{\\e_1}{\\T_1}\\\\\n    \\whnfs{\\GH}{\\T_1}{\\Universe{\\alpha}}\\\\\\\\\n    \\synterm{\\ctxs{(\\ctxextend{\\G}{\\x}{\\El{\\alpha}{\\e_1}})}{\\H}}{\\e_2}{\\T_2}\\\\\n    \\whnfs{\\ctxs{(\\ctxextend{\\G}{\\x}{\\El{\\alpha}{\\e_1}})}{\\H}}{\\T_2}{\\Universe{\\beta}}\\\\\\\\\n    \\piClose{\\alpha}{\\beta} = \\gamma\n  }\n  { \\synterm{\\GH}{(\\nProd{\\inferred\\alpha}{\\inferred\\beta}{\\x}{\\e_1}{\\e_2})}{\\Universe{\\gamma}} }\n\n  \\infer[\\rulename{syn-name-coerce}]\n  { \\synterm{\\GH}{\\e}{\\T}\\\\\n    \\whnfs{\\GH}{\\T}{\\Universe{\\alpha}}\\\\\n    \\alpha \\leq \\beta\n  }\n  { \\synterm{\\GH}{\\coerce{\\inferred\\alpha}{\\beta}{\\e}}{\\Universe{\\beta}} }\n\n  \\infer[\\rulename{syn-name-paths}]\n  {\n   \\synterm{\\GH}{\\e_2}{\\T_2}\\\\\n   \\nameof{\\T_2} = \\e_1 : \\Universe{\\alpha}\\\\\n   \\chkterm{\\GH}{\\e_3}{\\T_2}\\\\\n   \\alpha\\in\\FF\\\\\n  }\n  {\\synterm{\\GH}{\\nPrEqual{\\inferred\\alpha}{\\inferred{\\e_1}}{\\e_2}{\\e_3}}{\\Universe{\\alpha}}}\n\n\n  \\infer[\\rulename{syn-name-id}]\n  {\n   \\synterm{\\GH}{\\e_2}{\\T_2}\\\\\n   \\nameof{\\T_2} = \\e_1 : \\Universe{\\alpha}\\\\\n   \\chkterm{\\GH}{\\e_3}{\\T_2}\\\\\n  }\n  {\\synterm{\\GH}{\\nJuEqual{\\inferred\\alpha}{\\inferred{\\e_1}}{\\e_2}{\\e_3}}{\\Universe{\\alpha}}}\n\\end{mathpar}\n\n\\subsection{Type normalization}\n\\label{sec:type-normalization}\n\n\\paragraph{Name reduction (possibly using hints)}\n\\begin{mathpar}\n  \\infer[\\rulename{tynorm-el}]\n  {\n    \\whnf\n    {\\GH}\n    {\\e}\n    {\\e'}\n    {\\H'}\n  }\n  {\n    \\whnf\n    {\\GH}\n    {\\El{\\alpha}{\\e}}\n    {\\El{\\alpha}{\\e'}}\n    {\\H'}\n  }\n\\end{mathpar}\n\n\\paragraph{Conversion from name to type}\n\n\\begin{mathpar}\n\n  \\infer[\\rulename{tynorm-pi}]\n  {\n    %\\alpha = \\piClose{\\beta}{\\gamma}  %% Guaranteed by well-formedness\n  }\n  {\n    \\tywhnf\n    {\\GH}\n    {\\El{\\alpha}{(\\nProd{\\beta}{\\gamma}{\\x}{\\e_1}{e_2})}}\n    {\\Prod{\\x}{\\El{\\beta}{\\e_1}}{\\El{\\gamma}{\\e_2}}}\n    {\\H}\n  }\n\n  \\infer[\\rulename{tynorm-unit}]\n  {\n    %\\alpha = \\zero %% Guaranteed by well-formedness\n  }\n  {\n    \\tywhnf\n    {\\GH}\n    {\\El{\\alpha}{\\nUnit}}\n    {\\Unit}\n    {\\H}\n  }\n\n  \\infer[\\rulename{tynorm-universe}]\n  {\n    %\\alpha = \\uClose(\\beta) %% Guaranteed by well-formedness\n  }\n  {\n    \\tywhnf\n    {\\GH}\n    {\\El{\\alpha}{\\nUniverse{\\beta}}}\n    {\\Universe{\\beta}}\n    {\\H}\n  }\n\n  \\infer[\\rulename{tynorm-coerce}]\n  {\n  }\n  {\n    \\tywhnf\n    {\\GH}\n    {\\El{\\alpha}{(\\coerce{\\beta}{\\gamma}{\\e}})}\n    {\\El{\\alpha}{\\e}}\n    {\\H}\n  }\n\n  \\infer[\\rulename{tynorm-paths}]\n  {\n    %\\alpha = \\beta %% Guaranteed by well-formedness\n  }\n  {\\tywhnf\n    {\\GH}\n    {\\El{\\alpha}{(\\nPrEqual{\\beta}{\\e_1}{\\e_2}{\\e_3})}}\n    {\\PrEqual{\\El{\\alpha}{\\e_1}}{\\e_2}{\\e_3}}\n    {\\H}\n  }\n\n  \\infer[\\rulename{tynorm-id}]\n  {\n    %\\alpha = \\beta %% Guaranteed by well-formedness\n  }\n  {\\tywhnf\n    {\\GH}\n    {\\El{\\alpha}{(\\nJuEqual{\\beta}{\\e_1}{\\e_2}{\\e_3})}}\n    {\\JuEqual{\\El{\\alpha}{\\e_1}}{\\e_2}{\\e_3}}\n    {\\H}\n  }\n\\end{mathpar}\n%\nIf $\\rwhint{\\nUnit}{\\mathsf{nat}} \\in \\H$, then rule ordering\nwill give us $\\whnf{\\GH}{\\El{\\zero}{\\nUnit}}{\\El{\\zero}{\\mathsf{nat}}}{\\H}$. Only\nif we were to backtrack (and we don't, in the current implementation) would we\nconsider $\\whnf{\\GH}{\\El{\\zero}{\\nUnit}}{\\Unit}{\\H}$.\n\n\\subsection{Type equality}\n\\label{sec:algorithmic-type-equality}\n\n\\paragraph{General Type equality}\n\n\\begin{mathpar}\n  \\infer[\\rulename{chk-tyeq-refl}]\n  { }\n  { \\eqtypealg{\\GH}{\\T}{\\T} }\n\n  \\infer[\\rulename{chk-tyeq-hnf}]\n  { \\whnfs{\\GH}{\\T}{\\T'}\\\\\n    \\whnfs{\\GH}{\\U}{\\U'}\\\\\n    \\eqtypepath{\\GH}{\\T'}{\\U'}\n  }\n  {\n    \\eqtypealg{\\GH}{\\T}{\\U}\n  }\n\\end{mathpar}\n%\nReflexivity is an optimization for the common case.\n\n\\paragraph{Equality of head-normal forms}\n\\begin{mathpar}\n  \\infer[\\rulename{chk-tyeq-path-refl}]\n  { }\n  { \\eqtypepath{\\GH}{\\T}{\\T} }\n\n  \\infer[\\rulename{chk-tyeq-el}]\n  { \\alpha = \\beta \\\\\n    \\eqtermalg{\\GH}{\\e_1}{\\e_2}{\\Universe{\\alpha}}\n  }\n  {\n    \\eqtypepath{\\GH}{\\El{\\alpha}{\\e_1}}{\\El{\\beta}{\\e_2}}\n  }\n\n  \\infer[\\rulename{chk-tyeq-prod}]\n  { \\eqtypealg{\\GH}{\\T_1}{\\U_1} \\\\\n    \\eqtypealg {\\ctxs{(\\ctxextend{\\G}{\\x}{\\T_1})}{\\H}}{\\T_2}{\\U_2}\n  }\n  { \\eqtypepath{\\GH}\n    {\\Prod{\\x}{\\T_1}{\\T_2}}\n    {\\Prod{\\x}{\\U_1}{\\U_2}}\n  }\n\n  \\infer[\\rulename{chk-tyeq-paths}]\n  {\\eqtypealg{\\GH}{\\T}{\\U}\\\\\n   \\eqtermalg{\\GH}{\\e_1}{\\e'_1}{\\T}\\\\\n   \\eqtermalg{\\GH}{\\e_2}{\\e'_2}{\\T}\n  }\n  {\\eqtypepath{\\GH}{\\PrEqual{\\T}{\\e_1}{\\e_2}}\n                  {\\PrEqual{\\U}{\\e'_1}{\\e'_2}}}\n\n  \\infer[\\rulename{chk-tyeq-id}]\n  {\\eqtypealg{\\GH}{\\T}{\\U}\\\\\n   \\eqtermalg{\\GH}{\\e_1}{\\e'_1}{\\T}\\\\\n   \\eqtermalg{\\GH}{\\e_2}{\\e'_2}{\\T}\n  }\n  {\\eqtypepath{\\GH}{\\JuEqual{\\T}{\\e_1}{\\e_2}}\n                   {\\JuEqual{\\U}{\\e'_1}{\\e'_2}}}\n\\end{mathpar}\n%\nThe reflexivity rule is not just an optimization, but also handles\nequivalence of base types and equivalence of universes.\n\n\\subsection{Term normalization}\n\\label{sec:term-normalization}\n\n\\paragraph{Normalization by hints}\n\\begin{mathpar}\n  \\infer[\\rulename{norm-hint}]\n  {\n    \\rwhint{\\e}{\\e'} \\in \\H \\\\\n    \\whnf\n    {\\GH}\n    {\\e'}\n    {\\e''}\n    {\\H}\n  }\n  { \\whnf\n    {\\GH}\n    {\\e}\n    {\\e''}\n    {\\H}\n  }\n\\end{mathpar}\n%\nIn the case of multiple hints for reducing $\\e'$, we try the most-recently-added hint\n(last in the sequence $\\H$) first.\n\n\\paragraph{Redices}\n\\begin{mathpar}\n  \\infer[\\rulename{norm-equation}]\n  { }\n  { \\whnf\n    {\\GH}\n    {(\\equationin{\\e_1}{\\e_2}{\\e_3} \\e_4)}\n    {\\e_4}\n    {\\H}\n  }\n\n  \\infer[\\rulename{norm-rewrite}]\n  { }\n  { \\whnf\n    {\\GH}\n    {(\\rewritein{\\e_1}{\\e_2}{\\e_3} \\e_4)}\n    {\\e_4}\n    {\\H}\n  }\n\\end{mathpar}\n\n\\begin{mathpar}\n  \\infer[\\rulename{norm-ascribe}]\n  { }\n  { \\whnf\n    {\\GH}\n    {(\\ascribe{\\e}{\\T})}\n    {\\e}\n  }\n\n  \\infer[\\rulename{norm-app-beta}]\n  { \\eqtypealg{\\GH}{\\T_1}{\\U_1}\\\\\n    \\eqtypealg{\\ctxs{\\ctxextend{\\G}{\\x}{\\T_1}}{\\H}}{\\T_2}{\\U_2}}\n  { \\whnf\n    {\\GH}\n    {\\app{(\\lam{\\x}{\\T_1}{\\T_2}{\\e_1})}{\\x}{\\U_1}{\\U_2}{\\e_2}}\n    {\\subst{\\e_1}{\\x}{\\e_2}}\n  }\n\\end{mathpar}\n\n\\begin{mathpar}\n  \\infer[\\rulename{norm-idpath}]\n  {\n    \\eqtypealg{\\GH}{\\T}{\\T'}\n  }\n  {\n    \\whnf\n    {\\GH}\n    {\\PrElim\n      {\\T}\n      {\\abst{x\\,y\\,p}{\\U}}\n      {\\abst{z}{\\e_1}}\n      {\\prRefl{\\T'}{\\e_2}}{\\e_3}{\\e_4}\n    }\n    {\\subst{\\e_1}{z}{\\e_2}}\n  }\n\\end{mathpar}\n\n\n\\begin{mathpar}\n  \\infer[\\rulename{norm-coerce-trivial}]\n  {\n    \\alpha = \\beta\n  }\n  {\n    \\whnf\n    {\\GH}\n    {(\\coerce{\\alpha}{\\beta}{\\e})}\n    {\\e}\n    {\\H}\n  }\n\\end{mathpar}\n\nRule~\\rulename{norm-coerce-trivial} makes no sense if we don't label universe coercion terms with both domain and codomain universes.\n\n\\begin{mathpar}\n  \\infer[\\rulename{norm-coerce-trans}]\n  {\n  }\n  {\n    \\whnf\n    {\\GH}\n    {\\coerce{\\beta}{\\gamma}{(\\coerce{\\alpha}{\\beta}{\\e})}}\n    {\\coerce{\\alpha}{\\gamma}{\\e}}\n    {\\H}\n  }\n\\end{mathpar}\n\n\n\\paragraph{Recursion}\n\n\\begin{mathpar}\n  \\infer[\\rulename{norm-app}]\n  {\n    \\whnf{\\GH}\n    {\\e_1}\n    {\\e'_1}\n    {\\H'}\n  }\n  {\n    \\whnf\n    {\\GH}\n    {(\\app{\\e_1}{\\x}{\\T}{\\U}{\\e_2})}\n    {(\\app{\\e'_1}{\\x}{\\T}{\\U}{\\e_2})}\n    {\\H'}\n  }\n\n \\infer[\\rulename{norm-J}]\n  {\n    \\whnf\n    {\\GH}\n    {\\e_2}\n    {\\e'_2}\n    {\\H'}\n  }\n  { \\whnf\n    {\\GH}\n    {\\PrElim\n      {\\T}\n      {\\abst{x\\,y\\,p}{\\U}}\n      {\\abst{z}{\\e_1}}\n      {\\e_2}{\\e_3}{\\e_4}\n    }\n    {\\PrElim\n      {\\T}\n      {\\abst{x\\,y\\,p}{\\U}}\n      {\\abst{z}{\\e_1}}\n      {\\e'_2}{\\e_3}{\\e_4}\n    }\n    {\\H'}\n  }\n\\end{mathpar}\n%\nBy rule priority, if $\\app{\\e_1}{\\x}{\\T}{\\U}{\\e_2}$ has no hint and we take one step to\n$\\app{\\e'_1}{\\x}{\\T}{\\U}{\\e_2}$, we will look again for a hint for that term before\napplying the other rules.\n\n\\subsection{Term equality}\n\\label{sec:algorithmic-term-equality}\n\nFor algorithmic purposes we should try to apply reflexivity and hints before doing\nanything else:\n%\n\\begin{mathpar}\n  \\infer[\\rulename{chk-eq-refl}]\n  { }\n  { \\eqtermalg{\\GH}{\\e}{\\e}{\\T} }\n\n  \\infer[\\rulename{chk-eq-hint}]\n  {\n    \\eqhint{\\e_1}{\\e_2} \\in \\H\n  }\n  { \\eqtermalg{\\GH}{\\e_1}{\\e_2}{\\T} }\n\n  \\infer[\\rulename{chk-eq-hint-sym}]\n  {\n    \\eqhint{\\e_2}{\\e_1} \\in \\H\n  }\n  { \\eqtermalg{\\GH}{\\e_1}{\\e_2}{\\T} }\n\\end{mathpar}\n%\nOtherwise, we check whether extensionality applies:\n%\n\\begin{mathpar}\n  \\infer[\\rulename{chk-eq-ext}]\n  {\n    \\whnfs{\\GH}{\\T}{\\T'} \\\\\n    \\eqtermext{\\GH}{\\e_1}{\\e_2}{\\T'}\n  }\n  {\n    \\eqtermalg{\\GH}{\\e_1}{\\e_2}{\\T}\n  }\n\\end{mathpar}\n\n\\paragraph{Extensionality}\n\n\\begin{mathpar}\n  \\infer[\\rulename{chk-eq-ext-prod}]\n  {\n    \\eqtermalg{\\ctxs{(\\ctxextend{\\G}{\\x}{\\T})}{\\H}}{(\\app{\\e_1}{\\x}{\\T}{\\U}{\\x})}{(\\app{\\e_2}{\\x}{\\T}{\\U}{\\x})}{\\U}\n  }\n  {\n    \\eqtermext{\\GH}{\\e_1}{\\e_2}{\\Prod{\\x}{\\T}{\\U}}\n  }\n\n  \\infer[\\rulename{chk-eq-ext-unit}]\n  {\n  }\n  {\n    \\eqtermext{\\GH}{\\e_1}{\\e_2}{\\Unit}\n  }\n\n  \\infer[\\rulename{chk-eq-ext-K}]\n  {\n  }\n  {\n    \\eqtermext{\\GH}{\\e_1}{\\e_2}{\\JuEqual{\\T}{\\e_3}{\\e_4}}\n  }\n\n  \\infer[\\rulename{chk-eq-ext-whnf}]\n  {\n    \\whnfs{\\GH}{\\e_1}{\\e'_1}\\\\\n    \\whnfs{\\GH}{\\e_2}{\\e'_2}\\\\\\\\\n    \\eqpath{\\GH}{\\e'_1}{\\e'_2}{\\U}\n  }\n  {\n    \\eqtermext{\\GH}{\\e_1}{\\e_2}{\\T}\n  }\n\\end{mathpar}\n%\nIn \\rulename{chk-eq-ext-whnf}, we might want to check whether $\\e'_1$ and $\\e'_2$ are the\nsame expressions before invoking the general comparison function.\n\n\\paragraph{Whnf equivalence}\n\\begin{mathpar}\n  \\infer[\\rulename{chk-eq-whnf-reflexivity}]\n  {\n  }\n  {\n    \\eqpath{\\GH}{\\e}{\\e}{\\T}\n  }\n\n  \\infer[\\rulename{chk-eq-whnf-equation}]\n  {\n    \\eqhint{\\e_1}{\\e_2} \\in \\H\n  }\n  {\n    \\eqpath{\\GH}{\\e_1}{\\e_2}{\\T}\n  }\n\n\n  \\infer[\\rulename{chk-eq-whnf-var}]\n  {\n    %(\\x{:}\\T)\\in \\G\n  }\n  {\n    \\eqpath{\\GH}{\\x}{\\x}{\\T}\n  }\n\n  \\infer[\\rulename{chk-eq-whnf-app}]\n  {\n    \\eqtypealg{\\GH}{\\T_1}{\\U_1}\\\\\n    \\eqtypealg{\\ctxs{(\\ctxextend{\\G}{\\x}{\\T_1})}{\\H}}{\\T_2}{\\U_2}\\\\\\\\\n    \\eqpath{\\GH}{\\e_1}{\\e'_1}{\\Prod{\\x}{\\T_1}{\\T_2}}\\\\\n    \\eqtermalg{\\GH}{\\e_2}{\\e'_2}{\\T_1}\\\\\n  }\n  {\n    \\eqpath{\\GH}{(\\app{\\e_1}{\\x}{\\T_1}{\\T_2}{\\e_2})}\n                {(\\app{\\e'_1}{\\x}{\\U_1}{\\U_2}{\\e'_2})}\n                {\\subst{\\T_2}{\\x}{\\e_2}}\n  }\n\n  \\infer[\\rulename{chk-eq-whnf-idpath}]\n  {\n    \\eqtypealg{\\GH}{\\T}{\\U}\\\\\n    \\eqtermalg{\\GH}{\\e_1}{\\e_2}{\\T}\n  }\n  {\n    \\eqpath{\\GH}{\\prRefl{\\T}{\\e_1}}{\\prRefl{\\U}{\\e_2}}\n                {\\PrEqual{\\T}{\\e_1}{\\e_1}}\n  }\n\n  \\infer[\\rulename{chk-eq-whnf-j}]\n  {\n   \\eqtypealg{\\GH}{\\T}{\\T'}\\\\\n   \\eqtypealg\n     {\\ctxs{(\\ctxextend{\\ctxextend{\\ctxextend{\\G}{x}{\\T}}{y}{\\T}}{p}{\\PrEqual{\\T}{x}{y}})}{\\H}}\n     {\\U}\n     {\\U'}\n   \\\\\n   \\eqtermalg\n     {\\ctxs{(\\ctxextend{\\G}{z}{\\T})}{\\H}}\n     {\\e_1}\n     {\\e'_1}\n     {\\substs{P}{z/x, z/y, (\\prRefl{\\T}{z})/p}}\n     \\\\\n   \\eqtermalg{\\GH}{\\e_3}{\\e'_3}{\\T}\\\\\n   \\eqtermalg{\\GH}{\\e_4}{\\e'_4}{\\T}\\\\\n   \\eqpath{\\GH}{\\e_2}{\\e'_2}{\\PrEqual{\\T}{\\e_3}{\\e_4}}\n  }\n  {\\eqpath\n     {\\GH}\n     {\\PrElim\n        {\\T}\n        {\\abst{x\\,y\\,p}{\\U}}\n        {\\abst{z}{\\e_1}}\n        {\\e_2}{\\e_3}{\\e_4}\n     }\n     {\\PrElim\n        {\\T'}\n        {\\abst{x\\,y\\,p}{\\U'}}\n        {\\abst{z}{\\e'_1}}\n        {\\e'_2}{\\e'_3}{\\e'_4}\n     }\n     {\\substs{P}{\\e_2/x, \\e_3/y, \\e_4/p}}\n  }\n\n  \\infer[\\rulename{chk-eq-whnf-refl}]\n  {\n    \\eqtypealg{\\GH}{\\T}{\\U}\\\\\n    \\eqtermalg{\\GH}{\\e_1}{\\e_2}{\\T}\n  }\n  {\n    \\eqpath{\\GH}{\\juRefl{\\T}{\\e_1}}{\\juRefl{\\U}{\\e_2}}\n                {\\JuEqual{\\T}{\\e_1}{\\e_1}}\n  }\n\\end{mathpar}\n\n\\paragraph{Whnf equivalence of names}\n\n\\begin{mathpar}\n  \\infer[\\rulename{chk-eq-whnf-prod}]\n  {\\alpha = \\alpha' \\\\\n   \\beta = \\beta' \\\\\\\\\n   \\eqtermalg{\\GH}{\\e_1}{\\e'_1}{\\Universe{\\alpha}}\\\\\n   \\eqtermalg{\\ctxs{(\\ctxextend{\\G}{\\x}{\\El{\\alpha}{\\e_1}})}{\\H}}{\\e_2}{\\e'_2}{\\Universe{\\beta}} \\\\\n  }\n  {\\eqpath{\\GH}\n    {(\\nProd{\\alpha}{\\beta}{\\x}{\\e_1}{\\e_2})}\n    {(\\nProd{\\alpha'}{\\beta'}{\\x}{\\e'_1}{\\e'_2})}\n    {\\Universe{\\gamma}}\n  }\n\n\\infer[\\rulename{chk-eq-whnf-universe}]\n  {\n    \\alpha = \\beta \\\\\n  }\n  {\n    \\eqpath{\\GH}{\\nUniverse{\\alpha}}{\\nUniverse{\\beta}}{\\Universe{\\gamma}}\n  }\n%% Subsumed by reflexivity rule\n  %\\infer[\\rulename{chk-eq-whnf-unit}]\n  %{\n  %}\n  %{\n    %\\eqpath{\\GH}{\\nUnit}{\\nUnit}{\\Universe{\\zero}}\n  %}\n\n\\infer[\\rulename{chk-eq-whnf-paths}]\n  {\n    \\alpha = \\alpha'\\\\\n    \\eqtermalg{\\GH}{\\e_1}{\\e'_1}{\\Universe{\\alpha}}\\\\\n    \\eqtermalg{\\GH}{\\e_2}{\\e'_2}{\\El{\\alpha}{\\e_1}}\\\\\n    \\eqtermalg{\\GH}{\\e_3}{\\e'_3}{\\El{\\alpha}{\\e_1}}\n  }\n  {\\eqpath{\\GH}{\\nPrEqual{\\alpha}{\\e_1}{\\e_2}{\\e_3}}{\\nPrEqual{\\alpha'}{\\e'_1}{\\e'_2}{\\e'_3}}{\\Universe{\\alpha}}}\n\n  \\infer[\\rulename{chk-eq-whnf-id}]\n  {\n    \\alpha = \\alpha'\\\\\n    \\eqtermalg{\\GH}{\\e_1}{\\e'_1}{\\Universe{\\alpha}}\\\\\n    \\eqtermalg{\\GH}{\\e_2}{\\e'_2}{\\El{\\alpha}{\\e_1}}\\\\\n    \\eqtermalg{\\GH}{\\e_3}{\\e'_3}{\\El{\\alpha}{\\e_1}}\n  }\n  {\\eqpath{\\GH}{\\nJuEqual{\\alpha}{\\e_1}{\\e_2}{\\e_3}}{\\nJuEqual{\\alpha'}{\\e'_1}{\\e'_2}{\\e'_3}}{\\Universe{\\alpha}}}\n\n  \\infer[\\rulename{chk-eq-whnf-coerce}]\n  {\n    \\alpha = \\alpha'\\\\\n    \\eqtermalg{\\GH}{\\e_1}{\\e'_1}{\\Universe{\\alpha}} \\\\\n  }\n  {\n    \\eqpath{\\GH}{\\coerce{\\alpha}{\\beta}{\\e_1}}\n                {\\coerce{\\alpha'}{\\beta'}{\\e'_1}}\n                {\\Universe{\\beta}}\n  }\n\n\\end{mathpar}\n\n\\paragraph{Last-ditch whnf equivalence rules}\n\nThese rules should not be necessary (due to eta), but sufficiently nasty hints might get us here.\n\n\\begin{mathpar}\n  \\infer[\\rulename{chk-eq-whnf-abs}]\n  {\\eqtypealg{\\GH}{\\T_1}{\\U_1}\\\\\n   \\eqtypealg{\\ctxs{(\\ctxextend{\\G}{\\x}{\\T_1})}{\\H}}{\\T_2}{\\U_2}\\\\\\\\\n   \\eqtermalg{\\ctxs{(\\ctxextend{\\G}{\\x}{\\T_1})}{\\H}}{\\e_1}{\\e_2}{\\T_2}\\\\\n  }\n  {\\eqpath{\\GH}{(\\lam{\\x}{\\T_1}{\\T_2}{\\e_1})}\n               {(\\lam{\\x}{\\U_1}{\\U_2}{\\e_2})}\n               {\\Prod{\\x}{\\T_1}{\\T_2}}}\n\n  \\infer[\\rulename{chk-eq-whnf-unit-right}]\n  { }\n  {\\eqpath{\\GH}{\\e}{\\unitTerm}{\\Unit}}\n\n  \\infer[\\rulename{chk-eq-whnf-unit-left}]\n  { }\n  {\\eqpath{\\GH}{\\unitTerm}{\\e}{\\Unit}}\n\n  \\infer[\\rulename{chk-eq-whnf-refl-left}]\n  { }\n  {\\eqpath{\\GH}{\\juRefl{\\T}{\\e_1}}{\\e_2}\n          {\\JuEqual{\\T}{\\e_3}{\\e_4}}}\n\n  \\infer[\\rulename{chk-eq-whnf-refl-right}]\n  { }\n  {\\eqpath{\\GH}{\\e_1}{\\juRefl{\\T}{\\e_2}}\n          {\\JuEqual{\\T}{\\e_3}{\\e_4}}}\n\\end{mathpar}\n\nWe rely heavily on the precondition that the two terms being compared are already known to be well-formed with the same type.\nRule~\\rulename{chk-eq-whnf-abs} still has to conservatively re-check the equivalence of the type annotations; in the absence of Pi injectivity, just because we know the two lambda abstractions have judgmentally equal Pi types, there's no guarantee that they are componentwise equal.\n\n\\subsection{Normalization}\n\\label{sec:normalization}\n\nWe provide a normalization procedure which ignores hints. It is used to compute whether a\nuniversally quantified equation applies in a given situation. We introduce the following\njudgments:\n%\n\\begin{align*}\n  & \\tynorm{\\T}{\\T'} && \\text{type $\\T$ normalizes to $\\T'$} \\\\\n  & \\norm{\\e}{\\e'} && \\text{term $\\e$ normalizes to $\\e'$}\n\\end{align*}\n%\nNormalization preserves well-formedness and types.\n\n\\paragraph{Types}\n\n\\begin{mathpar}\n  \\infer[\\rulename{norm-ty-universe}]\n  { }\n  { \\tynorm\n    {\\Universe{\\alpha}}\n    {\\Universe{\\alpha}}\n  }\n\n  \\infer[\\rulename{norm-ty-el-coerce}]\n  { \\norm\n    {\\e}\n    {\\coerce{\\beta}{\\gamma}{\\e'}}\n    \\\\\n    \\gamma = \\alpha\n    \\\\\n    \\tynorm{\\El{\\beta}{\\e'}}{\\T}\n  }\n  { \\tynorm\n    {\\El{\\alpha}{\\e}}\n    {\\T}\n  }\n\n  \\infer[\\rulename{norm-ty-el-unit}]\n  { \\norm{\\e}{\\nUnit}\n    \\\\\n    \\alpha = \\zero\n  }\n  { \\tynorm\n    {\\El{\\alpha}{\\e}}\n    {\\Unit}\n  }\n\n  \\infer[\\rulename{norm-ty-el-prod}]\n  { \\norm\n    {\\e}\n    {\\nProd{\\beta}{\\gamma}{\\x}{\\e_1}{\\e_2}}\n    \\\\\n    \\piClose{\\beta}{\\gamma} = \\alpha \\\\\\\\\n    \\tynorm\n    {\\El{\\beta}{\\e_1}}\n    {\\T_1} \\\\\n    \\tynorm\n    {\\El{\\gamma}{\\e_2}}\n    {\\T_2}\n  }\n  { \\tynorm\n    {\\El{\\alpha}{\\e}}\n    {\\Prod{\\x}{\\T_1} \\T_2}\n  }\n\n  \\infer[\\rulename{norm-ty-el-universe}]\n  { \\norm{\\e}{\\nUniverse{\\beta}}\n    \\\\\n    \\uClose{\\beta} = \\alpha\n  }\n  { \\tynorm\n    {\\El{\\alpha}{\\e}}\n    {\\Universe{\\beta}}\n  }\n\n  \\infer[\\rulename{norm-ty-el-paths}]\n  { \\norm\n    {\\e}\n    {\\nPrEqual{\\beta}{\\e_1}{\\e_2}{\\e_3}}\n    \\\\\n    \\beta = \\alpha\n    \\\\\\\\\n    \\tynorm\n    {\\El{\\alpha}{\\e_1}}\n    {\\T_1}\n    \\\\\n    \\norm{\\e_2}{\\e_2'}\n    \\\\\n    \\norm{\\e_3}{\\e_3'}\n  }\n  { \n    \\tynorm\n    {\\El{\\alpha}{\\e}}\n    {\\PrEqual{\\T_1}{\\e_2'}{\\e_3'}}\n  }\n\n  \\infer[\\rulename{norm-ty-el-id}]\n  { \\norm\n    {\\e}\n    {\\nJuEqual{\\beta}{\\e_1}{\\e_2}{\\e_3}}\n    \\\\\n    \\beta = \\alpha\n    \\\\\\\\\n    \\tynorm\n    {\\El{\\alpha}{\\e_1}}\n    {\\T_1}\n    \\\\\n    \\norm{\\e_2}{\\e_2'}\n    \\\\\n    \\norm{\\e_3}{\\e_3'}\n  }\n  { \n    \\tynorm\n    {\\El{\\alpha}{\\e}}\n    {\\JuEqual{\\T_1}{\\e_2'}{\\e_3'}}\n  }\n\n  \\infer[\\rulename{norm-ty-el-other}]\n  { \\norm{\\e}{\\e'}\n  }\n  { \n    \\tynorm\n    {\\El{\\alpha}{\\e}}\n    {\\El{\\alpha}{\\e'}}\n  }\n\n  \\infer[\\rulename{norm-ty-unit}]\n  {\n  }\n  { \\tynorm\n    {\\Unit}\n    {\\Unit}\n  }\n\n  \\infer[\\rulename{norm-ty-prod}]\n  { \\tynorm{\\T}{\\T'}\n    \\\\\n    \\tynorm{\\U}{\\U'}\n  }\n  { \\tynorm\n    {\\Prod{\\x}{\\T}{\\U}}\n    {\\Prod{\\x}{\\T'}{\\U'}}\n  }\n\n  \\infer[\\rulename{norm-ty-paths}]\n  { \\tynorm{\\T}{\\T'}\n    \\\\\n    \\norm{\\e_1}{\\e_1'}\n    \\\\\n    \\norm{\\e_2}{\\e_2'}\n  }\n  { \\tynorm\n    {\\PrEqual{\\T}{\\e_1}{\\e_2}}\n    {\\PrEqual{\\T'}{\\e_1'}{\\e_2'}}\n  }\n\n  \\infer[\\rulename{norm-ty-id}]\n  { \\tynorm{\\T}{\\T'}\n    \\\\\n    \\norm{\\e_1}{\\e_1'}\n    \\\\\n    \\norm{\\e_2}{\\e_2'}\n  }\n  { \\tynorm\n    {\\JuEqual{\\T}{\\e_1}{\\e_2}}\n    {\\JuEqual{\\T'}{\\e_1'}{\\e_2'}}\n  }\n\\end{mathpar}\n\n\\paragraph{General terms}\n\n\\begin{mathpar}\n  \\infer[\\rulename{norm-var}]\n  {\n  }\n  { \\norm\n    {\\x}\n    {\\x}\n  }\n\n  \\infer[\\rulename{norm-equation}]\n  { \\norm\n    {\\e_4}\n    {\\e_4'}    \n  }\n  { \\norm\n    {\\equationin{\\e_1}{\\e_2}{\\e_3}{\\e_4}}\n    {\\e_4'}\n  }\n\n  \\infer[\\rulename{norm-rewrite}]\n  { \\norm\n    {\\e_4}\n    {\\e_4'}    \n  }\n  { \\norm\n    {\\rewritein{\\e_1}{\\e_2}{\\e_3}{\\e_4}}\n    {\\e_4'}\n  }\n\n  \\infer[\\rulename{norm-ascribe}]\n  {\n    \\norm\n    {\\e}\n    {\\e'}\n  }\n  { \\norm\n    {\\ascribe{\\e}{\\T}}\n    {\\e'}\n  }\n\n  \\infer[\\rulename{norm-star}]\n  {\n  }\n  { \n    \\norm{\\unitTerm}{\\unitTerm}\n  }\n\\end{mathpar}\n\n\\paragraph{Application and $\\lambda$-abstraction}\n\n\\begin{mathpar}\n\n  \\infer[\\rulename{norm-abs}]\n  {\n    \\tynorm{\\T_1}{\\T_1'} \\\\\n    \\tynorm{\\T_2}{\\T_2'} \\\\\n    \\norm{\\e}{\\e'}\n  }\n  { \\norm\n    {\\lam{\\x}{\\T_1}{\\T_2} \\e}\n    {\\lam{\\x}{\\T_1'}{\\T_2'} \\e'}\n  }\n\n  \\infer[\\rulename{norm-app-redex}]\n  {\n    \\tynorm{\\T_1}{\\T_1'} \\\\\n    \\tynorm{\\T_2}{\\T_2'} \\\\\n    \\norm{\\e_1}{\\lam{\\x}{\\U_1}{\\U_2} \\e_1'} \\\\\\\\\n    \\T_1' \\equiv U_1 \\\\\n    \\T_2' \\equiv U_2 \\\\\n    \\norm{\\e_2}{\\e_2'} \\\\\n    \\norm{\\subst{\\e_1'}{\\x}{\\e_2'}}{\\e'}\n  }\n  { \\norm\n    {\\app{\\e_1}{\\x}{\\T_1}{\\T_2}{\\e_2}}\n    {\\e'}\n  }\n  \n  \\infer[\\rulename{norm-app-other}]\n  {\n    \\tynorm{\\T_1}{\\T_1'} \\\\\n    \\tynorm{\\T_2}{\\T_2'} \\\\\n    \\norm{\\e_1}{\\e_1'} \\\\\n    \\norm{\\e_2}{\\e_2'}\n  }\n  { \\norm\n    {\\app{\\e_1}{\\x}{\\T_1}{\\T_2}{\\e_2}}\n    {\\app{\\e_1'}{\\x}{\\T_1'}{\\T_2'}{\\e_2'}}\n  }\n\\end{mathpar}\n\n\\paragraph{Paths and equality}\n\n\n\\begin{mathpar}\n\n  \\infer[\\rulename{norm-idpath}]\n  { \\tynorm{\\T}{\\T'} \\\\\n    \\norm{\\e}{\\e'}\n  }\n  { \n    \\norm\n    {\\prRefl{\\T}{\\e}}\n    {\\prRefl{\\T'}{\\e'}}\n  }\n\n  \\infer[\\rulename{norm-refl}]\n  { \\tynorm{\\T}{\\T'} \\\\\n    \\norm{\\e}{\\e'}\n  }\n  { \n    \\norm\n    {\\juRefl{\\T}{\\e}}\n    {\\juRefl{\\T'}{\\e'}}\n  }\n\n  \\infer[\\rulename{norm-J-redex}]\n  { \\tynorm{\\T}{\\T'} \\\\\n    \\norm{\\e_2}{\\prRefl{\\T''}{\\e_2'}} \\\\\n    T' \\equiv \\T'' \\\\\\\\\n    \\norm{\\e_1}{\\e_1'} \\\\\n    \\norm{\\subst{\\e_1'}{z}{\\e_2'}}{\\e'}\n  }\n  { \n    \\norm\n     {\\PrElim{\\T}\n        {\\abst{x\\,y\\,p}{\\U}}\n        {\\abst{z}{\\e_1}}\n        {\\e_2}\n        {\\e_3}{\\e_4}\n     }\n     {\\e'}\n  }\n\n  \\infer[\\rulename{norm-J-other}]\n  { \\tynorm{\\T}{\\T'} \\\\\n    \\norm{\\e_2}{\\e_2'} \\\\\n    \\tynorm{\\U}{\\U'} \\\\\\\\\n    \\norm{\\e_1}{\\e_1'} \\\\\n    \\norm{\\e_3}{\\e_3'} \\\\\n    \\norm{\\e_4}{\\e_4'}\n  }\n  { \n    \\norm\n     {\\PrElim{\\T}\n        {\\abst{x\\,y\\,p}{\\U}}\n        {\\abst{z}{\\e_1}}\n        {\\e_2}\n        {\\e_3}{\\e_4}\n     }\n     {\\PrElim{\\T'}\n        {\\abst{x\\,y\\,p}{\\U'}}\n        {\\abst{z}{\\e_1'}}\n        {\\e_2'}\n        {\\e_3'}{\\e_4'}\n     }\n  }\n\n\\end{mathpar}\n\n\\paragraph{Coercions}\n\n\\begin{mathpar}\n  \\infer[\\rulename{norm-coerce-trivial}]\n  {\n    \\alpha = \\beta \\\\\n    \\norm{\\e}{\\e'}\n  }\n  { \n    \\norm\n    {\\coerce{\\alpha}{\\beta}{\\e}}\n    {\\e'}\n  }\n\n  \\infer[\\rulename{norm-coerce-trans}]\n  {\n    \\norm{\\e}{\\coerce{\\gamma}{\\delta}{\\e'}} \\\\\n    \\alpha = \\delta \\\\\n    \\norm{\\coerce{\\gamma}{\\beta}{\\e'}}{\\e''}\n  }\n  { \n    \\norm\n    {\\coerce{\\alpha}{\\beta}{\\e}}\n    {\\e''}\n  }\n\n  \\infer[\\rulename{norm-coerce-pi}]\n  {\n    \\norm{\\e}{\\nProd{\\gamma}{\\delta}{\\x}{\\e_1}{\\e_2}} \\\\\n    \\alpha = \\piClose{\\gamma}{\\delta} \\\\\n    \\gamma \\leq \\alpha \\\\\n    \\delta \\leq \\alpha \\\\\\\\\n    \\norm{\\coerce{\\gamma}{\\beta}{\\e_1}}{\\e_1'} \\\\\n    \\norm{\\coerce{\\delta}{\\beta}{\\e_2}}{\\e_2'}\n  }\n  { \n    \\norm\n    {\\coerce{\\alpha}{\\beta}{\\e}}\n    {\\nProd{\\beta}{\\beta}{\\x}{\\e_1'}{\\e_2'}}\n  }\n\n  \\infer[\\rulename{norm-coerce-paths}]\n  { \\norm{\\e}{\\nPrEqual{\\gamma}{\\e_1}{\\e_2}{\\e_3}} \\\\\n    \\alpha = \\gamma \\\\\\\\\n    \\norm{\\coerce{\\alpha}{\\beta}{\\e_1}}{\\e_1'} \\\\\\\\\n    \\norm{\\e_2}{\\e_2'} \\\\\n    \\norm{\\e_3}{\\e_3'}\n  }\n  { \n    \\norm\n    {\\coerce{\\alpha}{\\beta}{\\e}}\n    {\\nPrEqual{\\beta}{\\e_1'}{\\e_2'}{\\e_3'}}\n  }\n  \n  \\infer[\\rulename{norm-coerce-id}]\n  { \\norm{\\e}{\\nJuEqual{\\gamma}{\\e_1}{\\e_2}{\\e_3}} \\\\\n    \\alpha = \\gamma \\\\\\\\\n    \\norm{\\coerce{\\alpha}{\\beta}{\\e_1}}{\\e_1'} \\\\\\\\\n    \\norm{\\e_2}{\\e_2'} \\\\\n    \\norm{\\e_3}{\\e_3'}\n  }\n  { \n    \\norm\n    {\\coerce{\\alpha}{\\beta}{\\e}}\n    {\\nJuEqual{\\beta}{\\e_1'}{\\e_2'}{\\e_3'}}\n  }\n\n  \\infer[\\rulename{norm-coerce-other}]\n  { \\norm{\\e}{\\e'}  }\n  { \n    \\norm\n    {\\coerce{\\alpha}{\\beta}{\\e}}\n    {\\coerce{\\alpha}{\\beta}{\\e'}}\n  }\n\\end{mathpar}\n\n\\paragraph{Names}\n\n\\begin{mathpar}\n  \\infer[\\rulename{norm-name-unit}]\n  { }\n  { \\norm{\\nUnit}{\\nUnit} }\n\n  \\infer[\\rulename{norm-name-prod}]\n  { \\norm{\\e_1}{\\e_1'} \\\\\n    \\norm{\\e_2}{\\e_2'}\n  }\n  { \\norm\n    {\\nProd{\\alpha}{\\beta}{\\x}{\\e_1}{\\e_2}}\n    {\\nProd{\\alpha}{\\beta}{\\x}{\\e_1'}{\\e_2'}}\n  }\n\n  \\infer[\\rulename{norm-name-universe}]\n  { }\n  { \\norm{\\nUniverse{\\alpha}}{\\nUniverse{\\alpha}} }\n\n  \\infer[\\rulename{norm-name-paths}]\n  { \\norm{\\e_1}{\\e_1'} \\\\\n    \\norm{\\e_2}{\\e_2'} \\\\\n    \\norm{\\e_3}{\\e_3'}\n  }\n  { \\norm\n    {\\nPrEqual{\\alpha}{\\e_1}{\\e_2}{\\e_3}}\n    {\\nPrEqual{\\alpha}{\\e_1'}{\\e_2'}{\\e_3'}}\n  }\n\n  \\infer[\\rulename{norm-name-id}]\n  { \\norm{\\e_1}{\\e_1'} \\\\\n    \\norm{\\e_2}{\\e_2'} \\\\\n    \\norm{\\e_3}{\\e_3'}\n  }\n  { \\norm\n    {\\nJuEqual{\\alpha}{\\e_1}{\\e_2}{\\e_3}}\n    {\\nJuEqual{\\alpha}{\\e_1'}{\\e_2'}{\\e_3'}}\n  }\n\\end{mathpar}\n\n\n\\end{document}\n", "meta": {"hexsha": "4db00f2bfbe88fdb4f6631e30ecff01a62e60c2f", "size": 54642, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "archive/doc/2014-04 - hts-andromeda.tex", "max_stars_repo_name": "Andromedans/andromeda", "max_stars_repo_head_hexsha": "761b0fd07cab5cbcf68a06e79b7f27301826ca82", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 210, "max_stars_repo_stars_event_min_datetime": "2015-11-10T17:16:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:08:42.000Z", "max_issues_repo_path": "archive/doc/2014-04 - hts-andromeda.tex", "max_issues_repo_name": "anjapetkovic/andromeda", "max_issues_repo_head_hexsha": "a5c678450e6c6d4a7cd5eee1196bde558541b994", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 244, "max_issues_repo_issues_event_min_datetime": "2015-11-10T16:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-06T03:55:46.000Z", "max_forks_repo_path": "archive/doc/2014-04 - hts-andromeda.tex", "max_forks_repo_name": "anjapetkovic/andromeda", "max_forks_repo_head_hexsha": "a5c678450e6c6d4a7cd5eee1196bde558541b994", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2015-11-10T16:15:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T08:08:23.000Z", "avg_line_length": 24.4155495979, "max_line_length": 282, "alphanum_fraction": 0.5349364957, "num_tokens": 23793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.33549513507827744}}
{"text": "\\chapter{DCM for Cross Spectral Densities: Anaesthesia Depth in Rodent Data\\label{Chap:data:dcm_csd}}\n\n\\section{Overview}\n\nThis chapter describes the analysis of a 2-channel Local Field Potential (LFPs) data set using dynamic causal modelling. The LFPs were recorded from a single rodent using intracranial electrodes \\cite{dcm_ssr_anaesthesia}. We thank Marc Tittgemeyer for providing us with this data. The theory behind DCM for cross spectral densities (DCM-CSD) is described in \\cite{Friston2012439}. This DCM is a generalization of DCM for Steady State Responses to the complex domain \\cite{dcm_ssr}. The generative model now reports coherence and signal covariance as well as complex spectral densities (from which the former are derived).\n\nWe measured local field potentials from primary (A1) and secondary auditory (A2) cortex in a rodent following the application of four different doses of the anaesthetic agent Isoflurane; 1.4, 1.8, 2.4 and 2.8\\%. The rodent was presented with a white noise auditory input for several minutes at each anaesthetised level and time series recordings were obtained for the entire epoch. We performed a DCM analysis to ask whether changes in neuronal activity induced by increasing levels of Isoflurane are best accounted for by \\emph{either} extrinsic \\emph{or} intrinsic changes in connectivity.\n\nWe demonstrate in this chapter the consistency of the model comparison and conditional parameter estimates across different population models. In particular we modeled the CSD as the output of a two region network comprising either ``CMC'' or ``NMDA'' -- type neural mass models.  \n\n\nThe CMC-type neural mass model comprises four subpopulations. It is a refinement of the Jansen and Rit convolution models that explicitly accommodates the neuronal sources of forward and backward connections in cortical hierarchies \\cite{Bastos2012}. These are distinct superficial and deep pyramidal cell populations respectively that, crucially, may exhibit different spectral outputs. The CMC thus utilizes different types of subpopulations as the source of forward and backward connections. For the forward connections superficial pyramidal cells excite stellate cells and deep pyramidal neurons, while the backward connections inhibit superficial pyramidal cells and inhibitory interneurons (see \\texttt{spm\\_fx\\_cmc}).  From the graphical user interface trial specific effects can be selected for extrinsic connections or intrinsic connections, for the CMC case the intrinsic connection that is modulated is an inhibitory gain parameter on superficial pyramidal cells. The smaller this value, the greater the gain on this cell population due to the modulation. \n\nThe NMDA model uses an architecture comprising three subpopulations, each assigned to a particular cortical layer. An inhibitory interneuron subpopulation occupies agranular layers. This receives inputs from excitatory pyramidal cells, also in agranular layers which are, in turn, driven by excitatory spiny cells in the granular layer; layer IV. These three subpopulations are connected with intrinsic coupling parameters (which can be found in \\texttt{spm\\_fx\\_mnn\\_nmda}). Forward connections correspond to afferent pyramidal axons and synapse on layer IV stellate cells, while backward afferents impinge upon pyramidal and inhibitory interneurons outside of layer IV. Lateral, inter-hemispheric connections are modelled with a postsynaptic response that is elicited in all layers. The model employs Morris Lecar-type differential equations to describe the time evolution of a neuronal ensemble.  In this model, cells possess AMPA, GABAA, and NMDA-like receptor dynamics, with appropriate ion-channel time constants and a voltage dependent switch for the NMDA channel \\cite{Moran2011}. From the graphical user interface trial specific effects can be selected for extrinsic connections or intrinsic connections, for the NMDA case the intrinsic connection that is modulated is an excitatory connection operating on all intrinsic excitatory connections. The greater this value, the greater the excitatory effect due to the modulation.\n\n\\section{Main Results}\n\nUsing Bayesian model comparison we found very strong evidence (Bayes Factor$_{1,2}$ $>$ 100) in favour of a model comprising a network of two neural masses connected by forward and backward connections from A1 to A2 and A2 to A1, where the effect of anesthetic was best explained by changes in \\emph{intrinsic} connections (model 2). This outperformed a model comprising the same two neural masses with the same extrinsic connections but where the effect of isoflurane was expressed as a modulatory (B) effect on extrinsic connections – between regions (model 1).  This result was obtained for both types of neural mass models used.\n\n\\section{Using the Graphical User Interface to Obtain those Results}\n\nIn what follows, these results will be recreated step-by-step using SPM12.\nTo proceed with the data analysis, first download the data set from the SPM website\\footnote{Anaesthesia Depth in Rodent Dataset: \\url{http://www.fil.ion.ucl.ac.uk/spm/data/dcm_csd/}}. The data comprises a data file called \\texttt{dLFP\\_white\\_noise\\_r24\\_anaes.dat} and its corresponding MAT-file \\texttt{dLFP\\_white\\_noise\\_r24\\_anaes.mat}. This has been converted from ASCII data using \\texttt{spm\\_lfp\\_txt2mat\\_anaes.m} also on the website and subsequently downsampled to 125 Hz. The conversion script can be altered to suit your own conditions/sampling parameters.\n\n\\subsection{The data}\n\n\\begin{itemize}\n\\item To check data parameters after conversion using ASCII files: in the SPM M/EEG GUI press Display/M/EEG.\n\\item In our data set we can see there are five trials: four depths of anaesthetic: Iso14, Iso18, Iso24 and Iso28 and one awake trial awake.\n\\item We are going to employ a 5 sec window of data (without ripples) for the DCM – this data is from 25000 to 30000 ms.  \n\\item We are now ready to begin the DCM analysis. To open the DCM GUI press DCM in the SPM M/EEG GUI. \n\\end{itemize}\n\n\\subsection{Dynamic Causal Modelling of Cross Spectral Densities}\n\n\\begin{itemize}\n\\item Before you begin any DCM analysis you must decide on three things: the data feature from your time series, the model you wish to use and the hypothesis you wish to test. \n\\item For our long time series we will examine the steady state and so in the top panel of the DCM GUI select CSD in the data drop-down menu. \n\\item Next in the second drop down menu we select our model. For our first analysis we select the CMC model (we can toggle this button to select other types of neural masses later.) \nThen we are ready to load our data: press new data and select the file \\texttt{dLFP\\_white\\_noise\\_r24\\_anaes.mat}. \n\\item Press the red arrow to move forward. \n\\item The second panel allows you to specify the data and design. We will use 5 seconds of data towards the end of the recording for our analysis.  To specify this timing enter 25000 and 30000 in the time window. \n\\item Next we select the detrending parameters which we set to 1 for detrend, 1 for subsample (as the data has already been downsampled) and 2 for the modes (in this case this is the same as the number of channels) using the drop down menus. \n\\item We can then specify which trials we want to use. Since we are interested in the anaesthetized trials we enter [1 2 3 4] under the trials label and Iso 1.8 Iso 2.4 Iso 2.8 are our three effects in the ``between trial effects'' panel. Next we specify the design matrix. This is entered numerically in the large panel. Since we have 4 trials and 3 between trial effects (one less) we enter a matrix with rows: [0 1 0 0] (row 1), [0 0 1 0] (row 2) and [0 0 0 1] (row 3). This will allow us to examine ``main effect'' differences between the four conditions.\n\\item Press the red arrow to move forward. \n\\item The third panel contains the spec for the electromagnetic model. This is very simple for local field potential recordings. In the drop down menu select LFP. In the source names panel, enter A1 and A2. You are finished. \n\\item Press the red arrow to move forward. \n\\item At this point all that is left to specify is the neuronal model in terms of its connectivity. We wish to compare two different models so we can save the specifications so far using the save button and reload the above specs for both neuronal models. \n\\item To specify the neuronal model, load the DCM (that you just saved) as it has been so far specified. \n\\item Our first model is the extrinsic modulation model. \n\\item So we specify forward connections from A1 to A2 and backward connections from A2 to A1. \n\\item We finally specify the B effects where we enter our hypothesis of connectivity changes between trial 1 (Iso1.4\\%) trial 2 (Iso1.8\\%) trial 3 (Iso2.4\\%) and trial 4 (Iso2.8\\%). Changes will be specified relative to trial 1. \n\\item We enter the off diagonal entries to correspond to forward connections (as entered in the above panel) to specify extrinsic connectivity changes between A1 and A2 due to (anaesthetic) condition. \n\\end{itemize}\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=140mm]{dcm_csd/dcm_csd_fig1}\n\\caption{\\em Left: Graphical User Interface to specify model 1: An extrinsic modulation by Isolurance. Here the B effects are clicked along the off-diagonal positions, representing changes in forward and backward extrinsic connections across the three trial types.\nRight: Data time series for two intracranial electrode recordings from 25000 to 30000 msec. Green and Blue lines represent different electrodes, panel rows correspond to the different trials -- here recordings made at different depths of anasthaesia: trial 1 = 1.4\\% isoflurane, trial2 = 1.8\\%, trial 3 = 2.4\\% and trial 4 -2.8\\%.  \\label{dcm_ssr:fig1}}\n\\end{center}\n\\end{figure}\n\n\\begin{itemize}\n\\item Finally we enter the frequencies we are interested in: we will fit frequencies from 4 to 48 Hz. \n\\item To invert the model press the ``invert DCM'' button.\n\\item Repeat the procedure after loading the saved specs and repeating for new neuronal models as per figure~\\ref{dcm_ssr:fig2}. Here we enter our alternative hypothesis (model 2) and fit a second model where instead of extrinsic connectivity changes, the isoflurane related-changes are generated by connectivity differences within a region – we call this the intrinsic modulation model.\n\\item This is specified by selecting the diagonal elements of the B-matrices.\n\\end{itemize}\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=140mm]{dcm_csd/dcm_csd_fig2}\n\\caption{\\em GUI illustrating how to specify model 2 -- the intrinsic modulation model. Here the B effects are clicked along diagonal position, representing changes in local (within-region) coupling. The top panel contains the neural model specification. This can be toggled to select different neural mass models as the basis for the DCM -- eg. LFP or CMC type. \n \\label{dcm_ssr:fig2}}\n\\end{center}\n\\end{figure}\n\n\\subsection{Comparing models using Bayesian Model Selection}\n\n\\begin{itemize}\n\\item Once both models have run, we compare their evidences to find the best or winning model. \nTo do this press the BMS button. This will open the SPM batch tool for model selection. Specify a directory to write the output file to. For the Inference method select Fixed effects (see  \\cite{klaas_bms} for additional explanations). Then click on Data and in the box below click on New: Subject. Click on Subject and in the box below on New: Session. Click on models and in the selection window that comes up select the DCM mat files for all the models (remember the order in which you select the files as this is necessary for interpreting the results). Then run the model comparison by pressing the green Run button. You will see at the top, a bar plot of the log-model evidences for all models (Figure~\\ref{dcm_ssr:fig3}). The bottom panel displays the conditional probability, for each model assuming equal priors on model space. By convention, a model can be said to be the best among a selection of other models, with strong evidence, if its log-model evidence exceeds all other log-model evidences by at least 3. You can also compare model evidences manually if you load the DCMs into \\matlab\\ ’s workspace and find the evidence in the structure under DCM.F.\n\\item For our example we see that there is strong model in favor of model 2 (log Bayes Factor >2500); ie. Isoflorane effects are better explained by a modulation of intrinsic connections.\n\\item We repeated the steps above and inverted two models (again with either extrinsic or intrinsic modulations) using the CMC and the NMDA neural masses also. These yielded similar results in favor of model 2 – an intrinsic connectivity effect. \n\\end{itemize}\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=140mm]{dcm_csd/dcm_csd_fig3}\n\\caption{\\em  Top: a bar plot of the log-model evidences for all models. Bottom: conditional probability for each model assuming equal priors on model space. \\label{dcm_ssr:fig3}}\n\\end{center}\n\\end{figure}\n\n\\begin{itemize}\n\\item Once inverted a results tab appears which allows you to view the fits to the spectral data, posterior parameter estimates, coherence and covariance (in channel and source space) and the transfer functions between regions. You can also examine the direction of the modulating “B” effects under “trial specific effects”.\n\\item From our winning CMC model we examined the trial specific effects and found a large increase for trial 2 relative to trial 1 in A1 (top left panel). Remember for the CMC case this represents a decreases in pyramidal cell gain – and so is a net inhibitory effect, consistent with the physiological effects of Isoflurane. The effect was even larger for trial 3 compared to trial 1 and decreased to a lower level for trial 4 (as reported in \\cite{rm_massmodelspectral}). The effects were similar in A2 (bottom right panel). We found a very similar trial specific effect in the NMDA case, but here the parameter decreases as it represents a positive modulation of an excitatory connection. In other words the effect of increasing isoflurane levels inhibitory in a non-linear fashion (saturating at a level of 2.4\\%; trial 3).\n\\end{itemize}\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=140mm]{dcm_csd/dcm_csd_fig4}\n\\caption{\\em  \\label{dcm_ssr:fig4}}\n\\end{center}\n\\end{figure}\n", "meta": {"hexsha": "0fa8128bbcc5a50884bd48b1e77de42a609fc708", "size": 14368, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thirdparty/spm12/man/dcm_csd/dcm_csd.tex", "max_stars_repo_name": "spunt/bspm", "max_stars_repo_head_hexsha": "4a1b6510cb32db6e2e4dff57bb81e6ece993f9db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2015-03-26T21:29:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-12T16:18:42.000Z", "max_issues_repo_path": "software/spm12/man/dcm_csd/dcm_csd.tex", "max_issues_repo_name": "wiktorolszowy/diffusion_fMRI", "max_issues_repo_head_hexsha": "2028515a244fcec88c072d4a66b97bbc57dc15c0", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-07-06T21:37:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-06T23:53:13.000Z", "max_forks_repo_path": "software/spm12/man/dcm_csd/dcm_csd.tex", "max_forks_repo_name": "wiktorolszowy/diffusion_fMRI", "max_forks_repo_head_hexsha": "2028515a244fcec88c072d4a66b97bbc57dc15c0", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2015-03-26T21:30:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T06:47:37.000Z", "avg_line_length": 135.5471698113, "max_line_length": 1434, "alphanum_fraction": 0.7969793987, "num_tokens": 3435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.3354951350782774}}
{"text": "\\documentclass{article}\n\\usepackage[UTF8]{ctex}\n\\usepackage{hyperref}\n\\usepackage{mathtools,amsmath,amssymb}\n\\usepackage{graphicx}\n\\usepackage{listings} \n\\usepackage{tocloft}\n\\hypersetup{colorlinks=true,linkcolor=black}\n\\begin{document}\n\\title{ Laminate\\_Analysis  Introduction \\& Handbook }\n\\author{Eacaen \\\\ tianyunhu@gmail.com }\n\\maketitle\n\\includegraphics[width = .9\\textwidth]{space.jpg}\n\\newpage\n\\tableofcontents                        \n\\newpage\n\\section{Composite Material Calculation with CLT}\n\t\\subsection{class Fibre}\n\t\tThe class designed to define and change the fibre material's properties. \n\t\t\\subsubsection{eg.}\n\t\t\\begin{lstlisting}[language={Python}] \n\tf = Fibre(Ef1=74000,Ef2=74000,Gf12=30800,\\\n\t\tvf21=0.2,density=2.55)\n\t\t\\end{lstlisting}\n\n\t\\subsection{class Matrix}\n\t\tThe class designed to define and change the matrix material's properties. \n\n\t\t\\subsubsection{eg.}\t\n\t\t\\begin{lstlisting}[language={Python}] \n\tm = Matrix(Em=300,Gm=1222,vm=0.35,density=1.18)\n\t\t\\end{lstlisting}\n\n\t\\subsection{class Lamina}\n\t\tThe class is used to define the signal lamina, its properties and engineering constants.\n\n\t\tIn the lamina initialization, you need to give the Elastic moduli $E_1,E_2$, the shear moduli $G_{12}$, the major Poisson's ration $v_{21}$ or $v_{12}$. And if you want to do the strength failure analysis, you need to give the tensile strength and compressive strength parallel to the fibre $X_t,X_c$, the tensile strength and compressive strength of the unidirectional layer transverse to the fibre $Y_t,Y_c$, and the shear strength $S_{21}$. Don't forget to define the angle and thickness of the lamina.(All the constants' default value are zero 0 )\n\n\t\tAnd the second way to define from the fibre and matrix materials have been defined above, read the example to get more.\n\n\t\t\\subsubsection{eg. define lamina directly}\t\n\t\t\\begin{lstlisting}[language={Python}] \n\ta=Lamina(E1=5.4e4,E2=0.001,G12=0.001,v21=0.25,\n\tXt=1.05e3,Xc=1.05e3,Yt=28,Yc=140,S=42,\n\tangle=0,thickness=1)\n\t\t\\end{lstlisting} \n\n\t\t\\subsubsection{eg. define lamina by fibre and matrix }\n\t\t\\begin{lstlisting}[language={Python}] \n\ta = Lamina(fibre=f , angle = 0 ,thickness=1 )\n\tb = Lamina(matrix=m, angle = 90,thickness=10.0)\n\t\t\\end{lstlisting} \n\n\t\tAfter define the lamina,you can get the matrix of the lamina,like matrix\\_Q or matrix\\_Qbar, you can get more if you look for the source code.\n\t\t\n\n\t\\subsection{class Laminate}\n\t\tThe class is used to define the Laminate.\n\n\t\tAfter the laminate initialization, you need to add the lamina as the lay up order of the laminate order.Then update the laminate you define,you can get the matrix\\_ABD, the thickness and so on.\n\n\t\t\\subsubsection{eg.}\t\n\t\t\\begin{lstlisting}[language={Python}] \n\tLA = Laminate()  #laminate initialization\n\tLA.add_Lamina(a) #add lamina\n\tLA.add_Lamina(a)\n\tLA.update()      #update and start calculation\n\tLA.repalce_Lamina(0,b)\n\t#replace the first(start form 0) lamina_a with the lamina_b\n\tLA.remove_Lamina(0) #remove the first lamina\n\tLA.update() #need to update again when change the lamina\n\t\t\\end{lstlisting} \n\n\t\\subsection{class Loading}\n\t\tThe class is used to define the Loading apply to the laminate.\n\n\t\tAfter the laminate update, you can apply the load defined to the laminate, and get the stress and strain $\\sigma_1$, $\\sigma_2$,$\\tau_{12}$ in the lamina COS, the stress and strain $\\sigma_x$, $\\sigma_y$,$\\tau_{xy}$ in the laminate COS.\n\n\t\t\\subsubsection{eg.}\t\n\t\t\\begin{lstlisting}[language={Python}] \n\tLoad = Loading(1,0,0,0,0,0) #load define\n\tLoad.apple_to(LA) # load apply to laminate\n\tLoad.change_Load(2,0,0,0,0,0) #change load\n\tLoad.apple_to(LA) # load apply to laminate again\n\t\t\\end{lstlisting}\n\n\t\\subsection{class Failure\\_Criterion}\n\t\tThe class is used text the strength of the laminate use Failure\\_Criterion.You can choose which lamina to test or whole laminate. \n\n\t\t\\subsubsection{eg.}\t\n\t\t\\begin{lstlisting}[language={Python}] \n\tc=Failture_Criterion()  #Criterion initialization\n\tc.Tsai_Hill(Load,layer_num=1) \n\t#choose the strength criterion and which lamina or all\n\tr= c.ret_list #get the answers\n\t\t\\end{lstlisting}\n\t\t \t\n\t\\subsection{laminate\\_Tools Introduction}\n\t\tThis part can print, save and plot the results in excel file format, you should give a name of the results you want to save.(the default do not save,and the name without `.' in). When calling the function, you can also choose which lamina's results to show or show all the laminate. \n\n\t\t\\subsubsection{eg.}\t\n\t\t\\begin{lstlisting}[language={Python}] \n\tprint Report_strain(Load,mode='12')\n\tplot_strain(Load,mode='xy',max_ten=None,mode2='1')\n\t\t\\end{lstlisting}\t\t\n\n\n\n\n\n\\end{document}", "meta": {"hexsha": "347a300bdde9e4096bd44dab4d7dc1d9e2fd1d48", "size": 4610, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/pro_introduction.tex", "max_stars_repo_name": "Eacaen/CLT-material-properties", "max_stars_repo_head_hexsha": "6d6238f6114e0fd749f3ffa729c9fa0cf360f856", "max_stars_repo_licenses": ["FTL", "CNRI-Python", "Xnet", "X11"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2018-06-01T07:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T13:47:27.000Z", "max_issues_repo_path": "doc/pro_introduction.tex", "max_issues_repo_name": "Eacaen/CLT-material-properties", "max_issues_repo_head_hexsha": "6d6238f6114e0fd749f3ffa729c9fa0cf360f856", "max_issues_repo_licenses": ["FTL", "CNRI-Python", "Xnet", "X11"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-02-24T23:44:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-25T16:23:43.000Z", "max_forks_repo_path": "doc/pro_introduction.tex", "max_forks_repo_name": "Eacaen/CLT-material-properties", "max_forks_repo_head_hexsha": "6d6238f6114e0fd749f3ffa729c9fa0cf360f856", "max_forks_repo_licenses": ["FTL", "CNRI-Python", "Xnet", "X11"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-01-01T13:29:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T22:20:54.000Z", "avg_line_length": 41.5315315315, "max_line_length": 553, "alphanum_fraction": 0.7429501085, "num_tokens": 1383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3354951350782774}}
{"text": "\\documentclass{article}\n\\usepackage{calc}\n\\setcounter{tocdepth}{2}\n\\providecommand{\\keywords}[1]{\\textbf{\\textit{Keywords---}} #1}\n\\usepackage{tikz-cd}\n\\usepackage{tensor}\n% \\usepackage{hyperref}\n% \\usepackage{csquotes}\n\\usepackage{fancyvrb}\n\\usepackage{todonotes}\n\\usepackage{verbatim}\n\\usepackage{amsmath}\n\\usepackage{microtype}\n\\usepackage{amssymb}\n\\usepackage{amsthm}\n\\usepackage{thmtools}\n\\usepackage{nameref,hyperref}\n\\usepackage{cleveref}\n\\usepackage[utf8]{inputenc}\n\n\\newcommand{\\tens}[2]{{_{#1}}\\times_{#2}}\n\n\\declaretheorem[numberwithin=section]{theorem}\n\\declaretheorem[sibling=theorem]{exercise}\n\\declaretheorem[sibling=theorem]{example}\n\\declaretheorem[sibling=theorem]{non-example}\n\\declaretheorem[sibling=theorem]{lemma}\n\\declaretheorem[sibling=theorem]{corollary}\n\\declaretheorem[sibling=theorem]{proposition}\n\\declaretheorem[style=definition,sibling=theorem]{definition}\n\\declaretheorem[style=definition,sibling=theorem]{axiom}\n\\declaretheorem[style=definition,sibling=theorem]{notation}\n\\declaretheorem[sibling=theorem]{question}\n\\declaretheorem[style=remark,sibling=theorem]{remark}\n\\title{Using Postulated Colimits in Coq}\n\\author{Work in Progress}\n\\begin{document}\n\\maketitle\n\\begin{abstract}\n  In this talk we define and construct finite colimits in the Coq proof assistant in a context that is similar to the category of sets. First we review without proof the key mathematical ideas involved in the theory of postulated colimits as described in a note of Anders Kock. This theory gives us a way to prove results about colimits in an arbitrary sheaf topos. Then we give an inductive definition in Coq of the fundamental notion of zigzag in this theory. We finish by proving the result analogous to the (mathematically easy) result that in the category of sets pushouts of monomorphisms are monomorphisms.\n\\end{abstract}\n\\tableofcontents\n\n\\section{General References}\n\\label{sec:general-references}\n\nWe make general reference to a paper \\cite{Kock89postulatedcolimits} of Anders Kock and a master's thesis of \\cite{carvalho-coq}.\n\n\\section{Postulated Coequalisers}\n\\label{sec:postulated-coequalisers}\n\nWe will use the traditional definition to define a coequaliser.\n\n\\begin{definition}\\label{def:coequaliser}\n  The \\emph{coequaliser $q$ of a parallel pair $a,b:R \\rightrightarrows X$} is an arrow\n    \\begin{equation*}\n      \\begin{tikzcd}\n       R \\rar[yshift=0.5ex]{s} \\rar[yshift=-0.5ex][swap]{t} & X \\drar[swap]{\\forall z} \\rar[twoheadrightarrow]{q} & Q \\dar[dashed]{\\exists !\\psi}\\\\\n        & {} & Z\n      \\end{tikzcd}\n    \\end{equation*}\n    such that\n    \\begin{itemize}\n    \\item the equality $sq=tq$ holds\n    \\item for all $z:X \\rightarrow Z$ such that $sz=tz$ there exists a unique $\\psi:Q \\rightarrow Z$ such that $q\\psi = z$.\n    \\end{itemize}\n\\end{definition}\n\nWe will use the idea of a postulated coequaliser to give an explicit presentation of coequalisers in the category of sets.\nWe refer to the preprint \\cite{Kock89postulatedcolimits}.\n\n\\begin{definition}\\label{def:zigzag}\n  An \\emph{$s$-$t$-zigzag from $x\\in X$ to $y\\in X$} is a sequence $r_1,r_2,...,r_n\\in R$ such that\n  \\begin{equation*}\n    \\begin{tikzcd}[column sep=0.5cm]\n      {} & r_1 \\dlar[mapsto]{\\phi_1} \\drar[mapsto]{\\phi_2} & {} & r_2 \\dlar[mapsto]{\\phi_3} \\drar[mapsto]{\\phi_4}& {} & r_3 \\dlar[mapsto]{\\phi_5}\\drar[mapsto]{\\phi_6} &{} &...& & r_n \\dlar[mapsto]{\\phi_7}\\drar[mapsto]{\\phi_8} &{} \\\\\n      x & {} & x_1 & {} & x_2 & {} & {} & ...& {}  & {} & y\n    \\end{tikzcd}\n  \\end{equation*}\n  where the $\\phi_i\\in\\{s,t\\}$.\n\\end{definition}  \n\n\\begin{definition}\\label{def:postulated-coequaliser}\n  A cofork\n  \\begin{equation*}\n    \\begin{tikzcd}\n     R \\rar[yshift=0.5ex]{s} \\rar[yshift=-0.5ex][swap]{t} & X \\rar{q} & Q\n    \\end{tikzcd}\n  \\end{equation*}\n  is \\emph{a postulated coequaliser} iff\n  \\begin{itemize}\n  \\item the arrow $q$ is an epimorphism\n  \\item for all $x,y\\in X$ $(x)q=(y)q$ iff there exists an $s$-$t$-zigzag from $x$ to $y$.\n  \\end{itemize}\n\\end{definition}\n\nWe can use postulated coequalisers to give a concrete presentation of coequalisers due to the following result of Kock.\n\n\\begin{proposition}\\label{prop:postulated-colimits-are-colimits}\n  In a sheaf topos every postulated coequaliser is a coequaliser.\n\\end{proposition}\n\n\\section{Objoids and Mapoids}\n\\label{sec:objoids-mapoids}\n\nIn our formulation we replace a sets with objoids.\nAn objoid is a type equipped with an equivalence relation on the terms of the type.\nThis is similiar to \\cite{carvalho-coq}\n\n\\begin{verbatim}\nRecord objoid: Type :=\n  {carrier:>Type;\n   eq:carrier->carrier->Prop;\n   refl:reflexive carrier eq;\n   sym:symmetric carrier eq;\n   trans:transitive carrier eq}.\nInfix \"~\" := eq (at level 95).\n\\end{verbatim}\n\nWe replace functions with \\emph{mapoids} which are the appropriate structure preserving maps for objoids.\n\n\\begin{verbatim}\nStructure mapoid (A B:objoid) :=\n  {map:>carrier A -> carrier B;\n   pres (a1 a2:carrier A) (H:a1~a2):map a1~map a2}.\n\\end{verbatim}\n\nSometimes it is easier to use an infix for function application.\n\n\\begin{verbatim}\nDefinition application (a1:carrier A) (f1:mapoid A B) := map f1 a1.\nInfix \"|>\" := application (at level 11, left associativity).\n\\end{verbatim}\n\nWe use double pipe for composition.\n\\begin{verbatim}\nDefinition comp:=\n  {|map:=fun a:carrier A=>g(f(a));\n    pres:=comp_pres|}.\nInfix \"||>\" := comp (at level 10, right associativity).\n\\end{verbatim}\n\nFinally we assert extensionality for functions.\n\\begin{verbatim}\nAxiom mapoid_ext:\n  (forall a:carrier A, f(a)~f2(a)) -> f=f2.\nAxiom mapoid_app:\n  f=f2 -> (forall a:carrier A, f(a)~f2(a)).\n\\end{verbatim}\n\n\\section{An Inductive Definition of Zigzag}\n\\label{sec:inductive-definition-zigzag}\n\nIt turns out that we can give an inductive definition of zigzag.\nNote that in order formulate this in Coq we need to add a base case and a way to cons equivalent elements onto a zigzag.\n\\begin{verbatim}\nInductive zigzag(x1 x2:X):Prop:=\n  |xid (H:x1~x2):zigzag x1 x2\n  |xcons {x3:X}: (x1~x3)-> (zigzag x3 x2) -> zigzag x1 x2\n  |stcons{r:R}{x3:X} (H1:x1~(s(r))) (H2:x3~(t(r)))\n         (z1:zigzag x3 x2): zigzag x1 x2\n  |tscons{r:R}{x3:X} (H1:x1~(t(r))) (H2:x3~(s(r)))\n         (z1:zigzag x3 x2): zigzag x1 x2.\n\\end{verbatim}\n\n\\begin{lemma}\n  The zigzag relation is reflexive, symmetric and transitive.\n\\end{lemma}\n\nThis means that we can construct a presentation of a coequaliser as a postulated coequaliser.\n\n\\begin{verbatim}\nDefinition Q:objoid:=\n  {|carrier:=X;\n    eq:=zigzag;\n    refl:=zigzag_refl;\n    sym:=zigzag_sym;\n    trans:=zigzag_trans|}.\nDefinition q:mapoid X Q:=\n  {|map:=fun x:X => x:Q;\n    pres:=id_pres|}.\n\\end{verbatim}\n\n\\begin{proposition}\n  The postulated coequaliser is a coequaliser.\n  \\begin{proof}\n    The factorisation is given by the identity \n    \\begin{verbatim}\nDefinition fact_arrow(Z:objoid) (z:mapoid X Z):Q->Z:=\n  fun x:Q => z(x).    \nDefinition factorisation\n  (Z:objoid) (z:mapoid X Z) (H:s||>z = t||>z):mapoid Q Z:=\n  {|map:=fact_arrow Z z;\n    pres:=(fact_arrow_pres Z z H)|}.\n\\end{verbatim}\n    and the main work is to prove that $\\sim$ is preserved.\n    For this we refer to the proof in Coq.\n  \\end{proof}\n\\end{proposition}\n\n\\section{Disjoint Unions}\n\\label{sec:disjoint-unions}\n\nWe have already defined and given a concrete presentation of coequalisers.\nIn order to get all finite limits we only need to add finite coproducts.\nThe natural translation of disjoint union into type theory is:\n\\begin{verbatim}\nInductive du:Type :=\n  |b:B -> du\n  |c:C -> du.\nInductive du_eq:relation du:=\n  |beq(b1 b2:B) (H:b1~b2):du_eq (b b1) (b b2)\n  |ceq(c1 c2:C) (H:c1~c2):du_eq (c c1) (c c2).\n\\end{verbatim}\n\n\\begin{proposition}\n  The disjoint unions defined above satisfy the universal property of coproducts.\n\\end{proposition}\n\n\\section{Pushouts from Coequalisers and Coproducts}\n\\label{sec:pushouts-from-coeq-and-coprod}\n\nIn any category with finite colimits if the square\n\\begin{equation*}\n  \\begin{tikzcd}\n   A \\rar{g} \\dar{f} & B\\dar{i_1}\\\\\n   C \\rar{i_0} & Q\n  \\end{tikzcd}\n\\end{equation*}\nis a pushout then we can compute $Q$ using a disjoint union and a coequaliser\n\\begin{equation*}\n  \\begin{tikzcd}\n   {} & B \\dar{u_0} & {}\\\\\n   A \\urar{f} \\drar{g} \\rar[yshift=0.5ex]{s} \\rar[yshift=-0.5ex][swap]{t} & B\\amalg C \\rar[twoheadrightarrow]{q} & Q\\\\\n   {} & C \\uar{u_1} & {}\n  \\end{tikzcd}\n\\end{equation*}\nand where $u_0$ and $u_1$ are the coproduct inclusions $i0=u0 q$ and $i1= u1 q$.\n\n\\begin{proposition}\n  The coequaliser of $fu_0$ and $gu_1$ is the pushout of $f$ and $g$.\n\\end{proposition}\n\n\\section{Pushouts of Monomorphisms in a Topos}\n\\label{sec:pushouts-of-monomorphisms}\n\nIn a general topos we can make the following argument.\nFor simplicity we assume that we are working in the category of sets and functions.\n\n\\begin{lemma}\\label{lem:pushout-of-mono}\n  If $f$ is a monomorphism and\n  \\begin{equation*}\n    \\begin{tikzcd}\n     A \\rar{g} \\dar[rightarrowtail]{f} & C\\dar{i_1}\\\\\n     B \\rar{i_0} & Q\n    \\end{tikzcd}\n  \\end{equation*}\n  is a pushout in $Set$ then $i_1$ is a monomorphism.\n  \\begin{proof}\n    We first note that $(f,g):A \\rightarrowtail B\\times C$ is a monomorphism because $f$ is a monomorphism.\n    Next\n    \\begin{equation*}\n      \\begin{tikzcd}\n       A \\rar{g} \\dar[rightarrowtail]{f} & C\\dar{i_1} \\arrow[bend left,rightarrowtail]{ddr}{c\\mapsto \\{c\\}} & {}\\\\\n       B \\rar{i_0} \\arrow[bend right]{rrd}{\\phi_{(f,g)}} & Q \\drar[dashed]{\\psi} & {}\\\\\n       {} & {} & \\mathcal P C\n      \\end{tikzcd}\n    \\end{equation*}\n    where $\\phi_{(f,g)}(b)=\\{c\\in C|~\\exists a\\in A.~f(a)=b \\wedge g(a)=c\\}$.\n    Therefore $i_1$ is a monomorphism because $c\\mapsto \\{c\\}$ is a monomorphism.\n  \\end{proof}\n\\end{lemma}\n\nThe proof that we will generalise is more straightforward.\nWe sketch the argument below.\n\n\\begin{lemma}\\label{lem:pushout-of-mono-2}\n  If $f$ is a monomorphism and\n  \\begin{equation*}\n    \\begin{tikzcd}\n     A \\rar{g} \\dar[rightarrowtail]{f} & C\\dar{i_1}\\\\\n     B \\rar{i_0} & Q\n    \\end{tikzcd}\n  \\end{equation*}\n  is a pushout in $Set$ then $i_1$ is a monomorphism.\n  \\begin{proof}\n\n  \\end{proof}\n  Suppose that $c1,c2\\in C$ such that $i_1(c1)\\sim i_1(c2)$.\n  This means that we can find a zigzag\n  \\begin{equation*}\n    \\begin{tikzcd}[column sep=0.3cm]\n      {} & a_1 \\dlar[mapsto]{g} \\drar[mapsto]{f} & {} & a_2 \\dlar[mapsto]{f} \\drar[mapsto]{g}& {} & a_3 \\dlar[mapsto]{g}\\drar[mapsto]{f} &{} &...& & a_n \\dlar[mapsto]{f}\\drar[mapsto]{g} &{} \\\\\n      x_1 & {} & x_2 & {} & x_3 & {} & {} & ...& {}  & {} & x_{n+1}\n    \\end{tikzcd}\n  \\end{equation*}\n  where $x_1\\sim c1$, $x_{n+1}\\sim c2$ and the order of the $f$ and $g$s has been forced by the disjoint union.\n  (As well as the fact that we are starting and ending at a $g$.)\n  However since $f$ is a monomorphism we see that $a_{2i-1}\\sim a_{2i}$ and so\n  \\begin{equation*}\n    c1 \\sim x_1 \\sim x_3 \\sim x_5 \\sim ... \\sim x_{n+1}\\sim c2\n  \\end{equation*}\n  as required.\n  WARNING: this proof hides a technical problem when doing the induction that Coq does not allow us to hide.\n\\end{lemma}\n\\bibliography{references}\n\\bibliographystyle{plain}\n\n\\end{document}\n", "meta": {"hexsha": "01c7d53d5eb2cc1ae226b84e77618235ecb15259", "size": 11076, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "talk-2018-03-05/talk2018-03-05.tex", "max_stars_repo_name": "mwpb/postulated-colimits-in-coq", "max_stars_repo_head_hexsha": "590d53905436b88c0005cf27e49644ceb798144d", "max_stars_repo_licenses": ["AFL-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "talk-2018-03-05/talk2018-03-05.tex", "max_issues_repo_name": "mwpb/postulated-colimits-in-coq", "max_issues_repo_head_hexsha": "590d53905436b88c0005cf27e49644ceb798144d", "max_issues_repo_licenses": ["AFL-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "talk-2018-03-05/talk2018-03-05.tex", "max_forks_repo_name": "mwpb/postulated-colimits-in-coq", "max_forks_repo_head_hexsha": "590d53905436b88c0005cf27e49644ceb798144d", "max_forks_repo_licenses": ["AFL-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7290322581, "max_line_length": 613, "alphanum_fraction": 0.6924882629, "num_tokens": 3827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.6224593171945417, "lm_q1q2_score": 0.3354951275285708}}
{"text": "\\section{Properties of the Basic Model}\n\\label{sec:props}\n\nIt is amazing how much the semantics of \\textsection\\ref{sec:model} ``gets\nright'' out of the box, including value range analysis, internal reads, and\nSC access, all of which can be complex in other models.  In this section, we\nwalk through several litmus tests, valid rewrites and invalid rewrites.  The\nexamples show that \\ref{5a}--\\ref{5d} and \\ref{rf3}--\\ref{rf4} are\nunderstandable as \\emph{general principles}.  The interaction of these\nprinciples is limited to a single, global, pomset order.  We discuss tweaks\nto the semantics in \\textsection\\ref{sec:refine}.\n\n\\subsection{Litmus Tests}\n\\label{sec:litmus}\n\n\\citet{PughWebsite} developed a set of litmus tests for the java memory\nmodel.  Our model gives the expected result for all but cases 16, 19 and 20\n(unrolling loops): we discuss \\ref{TC16} below; \\textsc{tc19} and\n\\textsc{tc20} involve a thread join operation, which is not expressible in\nour language.  Our model also agrees with the \\oota{} examples of\n\\citet[\\textsection 4]{DBLP:conf/esop/BattyMNPS15} and the ``surprising and\ncontroversial behaviors'' of \\citet[\\textsection\n8]{Manson:2005:JMM:1047659.1040336}.  %See \\cite{DBLP:conf/esop/PaviottiCPWOB20} for an exhaustive list of litmus tests.\n\n\\myparagraph{Buffering}\n\nConsider the \\emph{store buffering} and \\emph{load buffering} litmus \\labeltext[SB]{tests}{SB}:\n\\begin{align*}\n  \\taglabel{SB/LB}\n  \\begin{gathered}\n    \\PW{x}{0}\\SEMI\n    \\PW{y}{0}\\SEMI\n    (\n    \\PW{x}{1}\\SEMI\\PR{y}{\\aReg}\n    \\PAR\n    \\PW{y}{1}\\SEMI \\PR{x}{\\aReg})\n    \\\\[-1.5ex]\n    \\hbox{\\begin{tikzinline}[node distance=.9em]\n        \\event{wx0}{\\DW{x}{0}}{}\n        \\event{wy0}{\\DW{y}{0}}{right=of wx0}\n        \\event{wx}{\\DW{x}{1}}{right=3em of wy0}\n        \\event{ry}{\\DR{y}{0}}{right=of wx}\n        \\event{wy}{\\DW{y}{1}}{right=3em of ry}\n        \\event{rx}{\\DR{x}{0}}{right=of wy}\n        \\rf[out=15,in=165]{wy0}{ry}\n        \\rf[out=10,in=170]{wx0}{rx}\n        \\wk{ry}{wy}\n        \\wk[out=-165,in=-15]{rx}{wx}\n      \\end{tikzinline}}\n  \\end{gathered}\n  &&\n  \\begin{gathered}\n    \\PR{y}{\\aReg}\\SEMI \\PW{x}{1}\n    \\PAR\n    \\PR{x}{\\aReg}\\SEMI \\PW{y}{1}\n    \\\\\n    \\hbox{\\begin{tikzinline}[node distance=.9em]\n        \\event{ry}{\\DR{y}{1}}{}\n        \\event{wx}{\\DW{x}{1}}{right=of ry}\n        \\event{rx}{\\DR{x}{1}}{right=3em of wx}\n        \\event{wy}{\\DW{y}{1}}{right=of rx}\n        \\rf{wx}{rx}\n        \\rf[out=-165,in=-15]{wy}{ry}\n      \\end{tikzinline}}\n  \\end{gathered}\n\\end{align*}\nBecause there are no intra-thread dependencies, the desired outcomes are allowed, as shown.\n\n\\myparagraph{Publication}\n\\ref{rf3}--\\ref{rf4} and \\ref{5b}--\\ref{5c} ensure correct publication,\nprohibiting stale reads:\n\\begin{gather}\n  \\taglabel{Pub1}\n  \\begin{gathered}\n    \\PW{x}{0}\\SEMI %\\PW{y}{0}\\SEMI\n    \\PW{x}{1}\\SEMI \\PW[\\mRA]{y}{1} \\PAR \\PR[\\mRA]{y}{r}\\SEMI \\PR{x}{s}\n    \\\\[-.4ex]\n    \\nonumber\n    \\hbox{\\begin{tikzinline}[node distance=1.5em]\n        \\event{wx0}{\\DW{x}{0}}{}\n        \\event{wx1}{\\DW{x}{1}}{right=of wx0}\n        \\event{wy1}{\\DWRel{y}{1}}{right=of wx1}\n        \\event{ry1}{\\DRAcq{y}{1}}{right=2.5em of wy1}\n        \\event{rx0}{\\DR{x}{0}}{right=of ry1}\n        \\sync{wx1}{wy1}\n        \\sync{ry1}{rx0}\n        \\rf{wy1}{ry1}\n        \\wk{wx0}{wx1}\n      \\end{tikzinline}}\n  \\end{gathered}\n\\end{gather}\nThis pomset is disallowed, since $(\\DR x0)$ fails to satisfy \\ref{rf4}:\n$(\\DW x0) \\lt (\\DW x1) \\lt (\\DR x0)$.  Attempting to satisfy this\nrequirement, one might order $(\\DR x0)$ before $(\\DW x1)$, but this would\ncreate a cycle.\n\n\\myparagraph{Coherence}\n\nOur model of coherence does not correspond to either Java or C11.  We have\nchosen the model to validate \\ref{CSE} (unlike C11 relaxed atomics) and the\nlocal \\drfsc{} theorem (unlike Java).\n\nSince reads are not ordered by \\ref{5b},\nwe {allow} the following unintuitive behavior. C11 includes read-read\ncoherence between relaxed atomics in order to forbid this:\n\\begin{gather*}\n  \\taglabel{Co2}\n  \\begin{gathered}\n    \\PW{x}{1}\\SEMI \\PW{x}{2}\n    \\PAR\n    \\PW{y}{x} \\SEMI \\PW{z}{x}\n    \\\\[-1ex]\n    \\hbox{\\begin{tikzinline}[node distance=1.5em]\n        \\event{a}{\\DW{x}{1}}{}\n        \\event{b}{\\DW{x}{2}}{right=of a}\n        \\wk{a}{b}\n        \\event{c}{\\DR{x}{2}}{right=3em of b}\n        \\event{d}{\\DW{y}{2}}{right=of c}\n        \\po{c}{d}\n        \\event{e}{\\DR{x}{1}}{right=of d}\n        \\event{f}{\\DW{z}{1}}{right=of e}\n        \\po{e}{f}\n        \\rf{b}{c}\n        \\rf[out=10,in=170]{a}{e}\n      \\end{tikzinline}}\n  \\end{gathered}\n\\end{gather*}\nHere, the reader sees $2$ then $1$, although they are written in the reverse\norder.\nThis behavior is allowed by Java in order to validate \\ref{CSE} without requiring\naliasing analysis.\n\nHowever, our model is more coherent than Java, which permits the following:\n\\begin{gather*}\n  \\taglabel{TC16}\n  \\begin{gathered}\n    \\PR{x}{r}\\SEMI \\PW{x}{1}\n    \\PAR\n    \\PR{x}{s}\\SEMI \\PW{x}{2}\n    \\\\[-1ex]\n    \\hbox{\\begin{tikzinline}[node distance=1.5em]\n        \\event{a1}{\\DR{x}{2}}{}\n        \\event{a2}{\\DW{x}{1}}{right=of a1}\n        \\wk{a1}{a2}\n        \\event{b1}{\\DR{x}{1}}{right=3em of a2}\n        \\event{b2}{\\DW{x}{2}}{right=of b1}\n        \\wk{b1}{b2}\n        \\rf{a2}{b1}\n        \\rf[out=-165,in=-15]{b2}{a1}\n      \\end{tikzinline}}\n  \\end{gathered}\n\\end{gather*}\nWe also forbid the \\labeltext{following}{page:coherence2}, which Java allows:\n\\begin{gather*}\n  \\taglabel{Co3}\n  \\begin{gathered}\n    \\PW{x}{1}\\SEMI \\PW[\\mRA]{y}{1}\n    \\PAR\n    \\PW{x}{2}\\SEMI \\PW[\\mRA]{z}{1}\n    \\PAR\n    \\PR[\\mRA]{z}{r} \\SEMI \n    \\PR[\\mRA]{y}{r} \\SEMI \n    \\PR{x}{r} \\SEMI \n    \\PR{x}{r}\n    \\\\[-1ex]\n    \\hbox{\\begin{tikzinline}[node distance=1.5em]\n        \\event{a1}{\\DW{x}{1}}{}\n        \\event{a2}{\\DW[\\mRA]{y}{1}}{right=of a1}\n        \\sync{a1}{a2}\n        \\event{b1}{\\DW{x}{2}}{right=3em of a2}\n        \\event{b2}{\\DW[\\mRA]{\\,z}{1}}{right=of b1}\n        \\sync{b1}{b2}\n        \\event{c1}{\\DR[\\mRA]{\\,z}{1}}{right=3em of b2}\n        \\event{c2}{\\DR[\\mRA]{y}{1}}{right=of c1}\n        \\event{c3}{\\DR{x}{2}}{right=of c2}\n        \\event{c4}{\\DR{x}{1}}{right=of c3}\n        \\sync{c1}{c2}\n        \\sync{c2}{c3}\n        \\sync[out=20,in=160]{c2}{c4}\n        \\rf[out=8,in=172]{a2}{c2}\n        \\rf{b2}{c1}\n        \\wk[out=19,in=161]{a1}{b1}\n        \\wk[out=-172,in=-8]{c4}{b1}\n      \\end{tikzinline}}\n  \\end{gathered}\n\\end{gather*}\nThe order from $(\\DR{x}{1})$ to $(\\DW{x}{2})$ is required to fulfill\n$(\\DR{x}{1})$. The outcome is disallowed due to the cycle. %by fulfillment.\nIf this outcome were allowed, then racing writes would be visible, even after\na full synchronization; this would invalidate local reasoning about data\nraces (\\textsection\\ref{sec:sc}).\n\n\\myparagraph{MCA} We present a few examples that are hallmarks of \\mca{}\narchitectures.  \n\\begin{scope}\n  \\allowdisplaybreaks\n  \\begin{gather*}\n    \\taglabel{MCA1}\n    \\begin{gathered}\n      \\IF{z}\\THEN \\PW{x}{0} \\FI \\SEMI \\PW{x}{1}\n      {\\PAR}\n      \\IF{x}\\THEN \\PW{y}{0} \\FI \\SEMI \\PW{y}{1}\n      {\\PAR}\n      \\IF{y}\\THEN \\PW{z}{0} \\FI \\SEMI \\PW{z}{1}\n      \\\\[-1ex]\n      \\hbox{\\begin{tikzinline}[node distance=1.5em]\n          \\event{a1}{\\DR{z}{1}}{}\n          \\event{a2}{\\DW{x}{0}}{right=of a1}\n          \\po{a1}{a2}\n          \\event{a3}{\\DW{x}{1}}{right=of a2}\n          \\wk{a2}{a3}\n          \\event{b1}{\\DR{x}{1}}{right=3em of a3}\n          \\event{b2}{\\DW{y}{0}}{right=of b1}\n          \\po{b1}{b2}\n          \\event{b3}{\\DW{y}{1}}{right=of b2}\n          \\wk{b2}{b3}\n          \\event{c1}{\\DR{y}{1}}{right=3em of b3}\n          \\event{c2}{\\DW{z}{0}}{right=of c1}\n          \\po{c1}{c2}\n          \\event{c3}{\\DW{z}{1}}{right=of c2}\n          \\wk{c2}{c3}\n          \\rf{a3}{b1}\n          \\rf{b3}{c1}\n          \\rf[out=173,in=7]{c3}{a1}  \n        \\end{tikzinline}}\n    \\end{gathered}\n    \\\\[1ex]\n    \\taglabel{MCA2}\n    \\begin{gathered}\n      \\PW{x}{0}\\SEMI \\PW{x}{1}\n      \\PAR\n      \\PW{y}{x}\n      \\PAR\n      \\PR[\\mRA]{y}{r} \\SEMI \\PR{x}{s}\n      \\\\[-1ex]\n      \\hbox{\\begin{tikzinline}[node distance=1.5em]\n          \\event{wx0}{\\DW{x}{0}}{}\n          \\event{wx1}{\\DW{x}{1}}{right=of wx0}\n          \\wk{wx0}{wx1}\n          \\event{rx1}{\\DR{x}{1}}{right=3em of wx1}\n          \\event{wy1}{\\DW{y}{1}}{right=of rx1}\n          \\po{rx1}{wy1}\n          \\event{ry1}{\\DRAcq{y}{1}}{right=3em of wy1}\n          \\event{rx0}{\\DR{x}{0}}{right=of ry1}\n          \\rf{wx1}{rx1}\n          \\rf{wy1}{ry1}\n          \\sync{ry1}{rx0}\n          \\wk[out=170,in=10]{rx0}{wx1}\n        \\end{tikzinline}}\n    \\end{gathered}\n  \\end{gather*}\n\\end{scope}\nThese candidate executions are invalid, due to cycles.\n\\ref{MCA1} is an example of \\emph{write subsumption}\n\\cite[\\textsection 3]{DBLP:journals/pacmpl/PulteFDFSS18}.\nIn \\ref{MCA2}, $(\\DW{x}{1})$ is delivered to the second thread, but not\nthe third; this is similar to the well know \\iriw{} (Independent\nReads of Independent Writes) litmus test, which is also disallowed by \\mca{}\narchitectures if the reads within each thread are ordered. \n\nIf $y^\\mRA$ is changed to $y^\\mRLX$ in \\ref{MCA2}, then there would be no order\nfrom $(\\DR[\\mRLX]{y}{1})$ to $(\\DR{x}{0})$, and the execution would be\nallowed.  Since read-read dependencies do not appear in pomset order, the\nexecution would still be allowed if a control or address dependency were to\nbe introduced between the reads. See example \\ref{addr2}\n(\\textsection\\ref{sec:limits}) for further discussion.\n\n\\myparagraph{Internal Reads and Value Range Analysis}\nThe JMM causality test cases \\citep{PughWebsite} are justified via\ncompiler analysis, possibly in collusion with the scheduler: If every \nobserved value can be shown to satisfy a precondition, then the precondition\ncan be dropped.  For\nexample, \\ref{TC1} determines that the following execution should be\nallowed, as it is in our model:\n\\begin{gather*}\n  \\taglabel{TC1}\n  \\begin{gathered}\n    \\PW{x}{0} \\SEMI\n    (\\PR{x}{r}\\SEMI\\IF{r\\geq0}\\THEN \\PW{y}{1} \\FI\n    \\PAR\n    \\PW{x}{y})\n    \\\\[-1ex]\n    \\hbox{\\begin{tikzinline}[node distance=1.5em]\n        \\event{wx0}{\\DW{x}{0}}{}\n        \\event{rx1}{\\DR{x}{1}}{right=3em of wx0}\n        \\event{wy1}{0\\geq0\\mid\\DW{y}{1}}{right=of rx1}\n        \\event{ry1}{\\DR{y}{1}}{right=3em of wy1}\n        \\event{wx1}{\\DW{x}{1}}{right=of ry1}\n        \\po{ry1}{wx1}\n        \\rf[out=-168,in=-12]{wx1}{rx1}\n        \\rf{wy1}{ry1}\n        \\wk[out=10,in=170]{wx0}{wx1}\n        \\wk{wx0}{rx1}\n      \\end{tikzinline}}\n  \\end{gathered}\n\\end{gather*}\nIn this example, $(\\DW{x}{0})$ ``fulfills'' the read of $x$ that is used in\nthe guard of the conditional.  This is possible when prefixing $(\\DR{x}{1})$\nperforms the substitution $[x/r]$, but does not weaken the resulting\nprecondition $(x\\geq0\\mid\\DW{y}{1})$.  Subsequently prefixing $(\\DW{x}{0})$\nsubstitutes $[0/x]$, resulting in the tautological precondition\n$(0\\geq0\\mid\\DW{y}{1})$.  Note that the execution does not have an action\n$(\\DR{x}{0})$.\n\nOur semantics is robust with respect to\nthe introduction of concurrent writes, as in \\ref{TC9}:\n\\begin{gather*}\n  \\taglabel{TC9}\n  \\begin{gathered}\n    \\PW{x}{0} \\SEMI\n    (\\PR{x}{r}\\SEMI\\IF{r\\geq0}\\THEN \\PW{y}{1} \\FI\n    \\PAR\n    \\PW{x}{y}\n    \\PAR\n    \\PW{x}{-2})\n    \\\\[-1ex]\n    \\hbox{\\begin{tikzinline}[node distance=1.5em]\n        \\event{wx0}{\\DW{x}{0}}{}\n        \\event{rx1}{\\DR{x}{1}}{right=3em of wx0}\n        \\event{wy1}{0\\geq0\\mid\\DW{y}{1}}{right=of rx1}\n        \\event{ry1}{\\DR{y}{1}}{right=3em of wy1}\n        \\event{wx1}{\\DW{x}{1}}{right=of ry1}\n        \\event{wx2}{\\DW{x}{{-2}}}{right=3em of wx1}\n        \\po{ry1}{wx1}\n        \\rf[out=-168,in=-12]{wx1}{rx1}\n        \\rf{wy1}{ry1}\n        \\wk[out=10,in=170]{wx0}{wx1}\n        \\wk{wx0}{rx1}\n        \\wk{wx1}{wx2}\n      \\end{tikzinline}}\n  \\end{gathered}\n\\end{gather*}\nThe calculation of this pomset is unchanged from \\ref{TC1}.\n\nExamples such as \\ref{TC9} present substantial difficulties in other models.\nWhen thought of in terms of compiler optimizations, \\ref{TC9} is justified by\nglobal value analysis in collusion with the thread scheduler.  This execution\nis disallowed by our event structure model \\cite{DBLP:conf/lics/JeffreyR16}.\nIt is allowed by \\citet{Pichon-Pharabod:2016:CSR:2837614.2837616}, at the\ncost of introducing \\emph{dead reads}.\n\nThe reasoning for \\ref{TC2} is similar, but in this case no value is necessary to\nsatisfy the precondition:\n\\begin{gather*}\n  \\taglabel{TC2}\n  \\begin{gathered}\n    \\PR{x}{r}\\SEMI\n    \\PR{x}{s}\\SEMI\n    \\IF{r{=}s}\\THEN \\PW{y}{1}\\FI\n    \\PAR\n    \\PW{x}{y}\n    \\\\[-1ex]\n    \\nonumber\n    \\hbox{\\begin{tikzinline}[node distance=1.5em]\n        \\event{a1}{\\DR{x}{1}}{}\n        \\event{a2}{\\DR{x}{1}}{right=of a1}\n        \\event{a3}{(x{=}x)\\land(1{=}1)\\mid\\DW{y}{1}}{right=of a2}\n        \\event{b1}{\\DR{y}{1}}{right=3em of a3}\n        \\event{b2}{\\DW{x}{1}}{right=of b1}\n        \\rf{a3}{b1}\n        \\po{b1}{b2}\n        \\rf[out=169,in=11]{b2}{a2}\n        \\rf[out=169,in=11]{b2}{a1}\n      \\end{tikzinline}}\n  \\end{gathered}\n\\end{gather*}\nNote that in \n\\begin{math}\n  \\sem{\\PR{x}{s}\\SEMI\n    \\IF{r{=}s}\\THEN \\PW{y}{1}\\FI},\n\\end{math}\nthe precondition on $(\\DW{y}{1})$ must imply $(r{=}x \\land r{=}1)$.  The\nfirst is imposed by \\ref{5a}, the second by \\ref{4c}, ensuring that the two\nreads see the same value.\n\nUsing \\armeight{} terminology, these executions involve \\emph{internal\n  reads}, which are fulfilled by a sequentially preceding write.  Read\nactions always generate an event that must be fulfilled, and therefore cannot\nbe ignored, even if they are unused.  This fact prevents internal reads from\nignoring concurrent blocking writes.\n\\begin{gather*}\n  \\taglabel{Internal1}\n  \\begin{gathered}\n    \\PW{x}{1} \\SEMI\n    \\PW[\\mRA]{a}{1} \\SEMI\n    \\IF{z^\\mRA}\\THEN  \\PW{y}{x} \\FI\n    \\PAR\n    \\IF{a^\\mRA}\\THEN  \\PW{x}{2}\\SEMI \\PW[\\mRA]{z}{1} \\FI\n    \\\\\n    \\hbox{\\begin{tikzinline}[node distance=1.2em]\n        \\event{a1}{\\DW{x}{1}}{}\n        \\event{a2}{\\DWRel{a}{1}}{right=of a1}\n        \\sync{a1}{a2}\n        \\event{b3}{\\DRAcq{a}{1}}{below right=0em and 3em of a2}\n        \\rf{a2}{b3}\n        \\event{b4}{\\DW{x}{2}}{right=of b3}\n        \\sync{b3}{b4}\n        \\event{b5}{\\DWRel{z}{1}}{right=of b4}\n        \\sync{b4}{b5}\n        \\event{a6}{\\DRAcq{b}{1}}{above right=0em and 3em of b5}\n        \\rf{b5}{a6}\n        \\event{a7}{\\DR{x}{1}}{right=of a6}\n        \\sync{a6}{a7}\n        \\event{a8}{1{=}1\\mid\\DW{y}{1}}{right=of a7}\n        \\graypo{a7}{a8}\n        \\sync[out=-18,in=-162]{a6}{a8}\n      \\end{tikzinline}}\n  \\end{gathered}\n\\end{gather*}\nHere $(\\DR{x}{1})$ violates \\ref{rf4}.  The precondition $(1{=}1)$ is\nimposed by \\ref{4c}.  The pomset becomes inconsistent if we change\n$(\\DR{x}{1})$ to $(\\DR{x}{2})$, since the precondition would change to $(2{=}1)$.\n\nInternal reads are notoriously difficult to get right.  Consider \\cite[Ex 3.6]{DBLP:journals/pacmpl/PodkopaevLV19}:\n\\begin{gather*}\n  \\taglabel{Internal2}\n  \\begin{gathered}\n    \\PR{x}{\\aReg}\\SEMI\n    \\PW[\\mRA]{y}{1}\\SEMI\n    \\PR{y}{\\bReg}\\SEMI\n    \\PW{z}{\\bReg}\n    \\PAR\n    \\PW{x}{z}\n    \\\\[-1ex]\n    \\nonumber\n    \\hbox{\\begin{tikzinline}[node distance=1.5em]\n        \\event{a1}{\\DR{x}{1}}{}\n        \\event{a2}{\\DWRel{y}{1}}{right=of a1}\n        \\sync{a1}{a2}\n        \\event{a3}{\\DR{y}{1}}{right=of a2}\n        \\event{a4}{1{=}1\\mid\\DW{z}{1}}{right=of a3}\n        \\rf{a2}{a3}\n        \\event{b1}{\\DR{z}{1}}{right=3em of a4}\n        \\event{b2}{\\DW{x}{1}}{right=of b1}\n        \\po{b1}{b2}\n        \\rf{a4}{b1}\n        \\rf[out=170,in=10]{b2}{a1}\n      \\end{tikzinline}}\n  \\end{gathered}\n\\end{gather*}\nThis behavior is allowed in our model, as it is in \\armeight.\nNote that $\\sem{\\PW{z}{\\bReg}}$ includes $(\\bReg{=}1\\mid \\DW{z}{1})$.\nPrepending a read,\n$\\sem{\\PR{y}{\\bReg} \\SEMI \\PW{z}{\\bReg}}$ may update the precondition to\n$(y{=}1\\mid \\DW{z}{1})$ without introducing order.\nFurther prepending\n$(\\DWRel{y}{1})$ results in $(1{=}1\\mid \\DW{z}{1})$.\n\nOur model drops order into actions that depend on a read that can be\nfulfilled {internally}, by a prefixed write.  This is natural consequence of\nsubstitution.  The \\armeight{} model has to jump through some hoops to ensure\nthat internal reads are handled correctly.  \\armeight{} takes the symmetric\napproach: rather than dropping order \\emph{out of} an internal read,\n\\armeight{} drops the order \\emph{into} it.  This difference complicates the\nproof of correctness for implementing our semantics on \\armeight{}\n(\\textsection\\ref{sec:arm}).\n\n\\myparagraph{SC access}\n\\ref{5d} ensures that program order between SC operations is always\npreserved.  Combined with \\ref{rf3}--\\ref{rf4}, this is\nsufficient to establish that programs with only SC access have only SC\nexecutions; for example, the executions of \\ref{SB/LB} are banned when the\nall actions are $\\mSC$.  It is also immediate that SC\nactions can be totally ordered, using any linearization of pomset order.\nJust as SC access in \\armeight{} is simplified by \\mca, it is simplified here\nby the global pomset order.\n\nSC access is not as strict as volatile access in Java.  For example, our\nmodel allows the following, since there is no order from\n$(\\DW[\\mSC]{x}{2})$ to $(\\DW{y}{1})$---recall that SC writes are \\emph{releases}.\n\\begin{gather*}\n  \\taglabel{SC1}\n  \\begin{gathered}\n    \\PR{y}{r}\\SEMI \\PW[\\mSC]{x}{1}\\SEMI \\PR{x}{s}\n    \\PAR\n    \\PW[\\mSC]{x}{2} \\SEMI \\PW{y}{1}\n    \\\\[-1ex]\n    \\hbox{\\begin{tikzinline}[node distance=1.5em]\n        \\event{a}{\\DR{y}{1}}{}\n        \\event{b}{\\DW[\\mSC]{x}{1}}{right=of a}\n        \\sync{a}{b}\n        \\event{bb}{\\DR{x}{2}}{right=of b}\n        \\wk{b}{bb}\n        \\event{d}{\\DW[\\mSC]{x}{2}}{right=3em of bb}\n        \\event{e}{\\DW{y}{1}}{right=of d}\n        \\rf{d}{bb}\n        \\rf[out=-170,in=-10]{e}{a}\n        \\wk[in=165,out=15]{b}{d}\n      \\end{tikzinline}}\n  \\end{gathered}\n\\end{gather*}\nThis execution is disallowed by\n\\citet[\\textsection8.2]{Dolan:2018:BDR:3192366.3192421}, preventing them from\nusing \\texttt{stlr} to implement volatile writes on \\armeight{}. Our\nimplementation strategy does use \\texttt{stlr} for SC writes, as is standard.\nFor further discussion, see examples \\ref{past} and \\ref{future} in\n\\textsection\\ref{sec:sc}.\n\n\\citet[\\textsection3.1]{DBLP:conf/pldi/WattPPBDFPG20} noticed a similar\ndifficulty in Javascript \\cite[\\textsection27]{ecma2019}:\n\\begin{gather*}\n  \\taglabel{SC2}\n  \\begin{gathered}\n    \\PW[\\mSC]{x}{1} \\SEMI \\PR[\\mSC]{y}{r}\n    \\PAR\n    \\PW[\\mSC]{y}{1} \\SEMI \\PW[\\mSC]{y}{2} \\SEMI \\PW{x}{2} \\SEMI \\PR[\\mSC]{x}{s}\n    \\\\[-1ex]\n    \\hbox{\\begin{tikzinline}[node distance=1.5em]\n        \\event{a}{\\DW[\\mSC]{x}{1}}{}\n        \\event{b}{\\DR[\\mSC]{y}{1}}{right=of a}\n        \\event{c}{\\DW[\\mSC]{y}{1}}{right=3em of b}\n        \\event{d}{\\DW[\\mSC]{y}{2}}{right=of c}\n        \\event{e}{\\DW{x}{2}}{right=of d}\n        \\event{f}{\\DR[\\mSC]{x}{1}}{right=of e}\n        \\sync{a}{b}\n        \\sync{c}{d}\n        \\sync[out=15,in=165]{d}{f}\n        \\rf{c}{b}\n        \\rf[out=-8,in=-172]{a}{f}\n        \\wk[in=10,out=170]{e}{a}\n        \\wk{e}{f}\n      \\end{tikzinline}}\n  \\end{gathered}\n\\end{gather*}\nThis execution is allowed both by our semantics and by \\armeight{} (using\n\\texttt{stlr} for SC writes and \\texttt{ldar} for SC reads).  However, it is\nnot allowed by Javascript 2019.  In Javascript, the rules relating SC and\nrelaxed access are subtle.  As result of these interactions, Javascript 2019\nfails to satisfy \\drfsc{} \\cite{DBLP:journals/pacmpl/WattRP19}.  The rules\nare even more complex in C11; see \\ref{SC3} and \\ref{SC4} in\n\\textsection\\ref{sec:variants} for a discussion of SC fences in C11.\nIn our model, only \\ref{5d} is required to explain SC access.\n\n\\subsection{Valid and Invalid Rewrites}\n\\label{sec:valid}\n\nWhen $\\sem{\\aCmd} \\supseteq \\sem{\\aCmd'}$, we say that $\\aCmd'$ is a\n\\emph{valid transformation} of $\\aCmd$.  In this subsection, we show the\nvalidity of specific optimizations.  \nLet $\\free(\\aCmd)$ be the set of locations and registers that occur in $\\aCmd$.\n\nThe semantics validates many peephole optimizations.  Most apply only to\nrelaxed access.\n\\begin{align*}\n  \\taglabel{RR}\n  \\sem{\\PR{\\aLoc}{\\aReg} \\SEMI \\PR{\\bLoc}{\\bReg}\\SEMI\\aCmd} &=\n  \\sem{\\PR{\\bLoc}{\\bReg}\\SEMI \\PR{\\aLoc}{\\aReg}\\SEMI\\aCmd} &&\\text{if } \\aReg\\neq\\bReg\n  \\\\\n  \\taglabel{WW}\n  \\sem{\\aLoc \\GETS \\aExp \\SEMI \\bLoc  \\GETS \\bExp\\SEMI\\aCmd} &=\n  \\sem{\\bLoc  \\GETS \\bExp\\SEMI \\aLoc \\GETS \\aExp\\SEMI\\aCmd} &&\\text{if } \\aLoc\\neq\\bLoc\n  \\\\\n  \\taglabel{RW}\n  \\sem{\\aLoc \\GETS \\aExp  \\SEMI \\PR{\\bLoc}{\\bReg} \\SEMI\\aCmd} &=\n  \\sem{\\PR{\\bLoc}{\\bReg} \\SEMI\\aLoc \\GETS \\aExp\\SEMI\\aCmd} &&\\text{if }\n  \\aLoc\\neq\\bLoc \\textand \\bReg\\not\\in\\free(\\aExp)%\\disjoint{{\\free(\\aLoc \\GETS \\aExp)}}{{\\free(\\PR{\\bLoc}{\\bReg})}}\n\\end{align*}\n\\ref{5} imposes no order between events in \\ref{RR}--\\ref{RW}.  %Note that \\ref{RR} allows aliasing.\nUsing augmentation closure, \\ref{5} also validates roach-motel reorderings \\cite{SevcikThesis}.  For\nexample, on read/write pairs:\n\\begin{align*}\n  \\tag{\\textsc{roach1}}\\label{AcqW}\n  \\sem{x^\\amode \\GETS \\aExp \\SEMI\\PR{y}{\\bReg} \\SEMI\\aCmd} &\\supseteq\n  \\sem{\\PR{y}{\\bReg}  \\SEMI x^\\amode\\GETS \\aExp \\SEMI \\aCmd} \n  &&\\text{if }\n  \\aLoc\\neq\\bLoc \\textand \\bReg\\not\\in\\free(\\aExp)%\\disjoint{{\\free(\\aLoc \\GETS \\aExp)}}{{\\free(\\PR{\\bLoc}{\\bReg})}}\n  \\\\\n  \\tag{\\textsc{roach2}}\\label{RelW}\n  \\sem{x \\GETS \\aExp \\SEMI\\PR[\\amode]{y}{\\bReg} \\SEMI\\aCmd} &\\supseteq\n  \\sem{\\PR[\\amode]{y}{\\bReg}  \\SEMI x\\GETS \\aExp \\SEMI \\aCmd} \n  &&\\text{if }\n  \\aLoc\\neq\\bLoc \\textand \\bReg\\not\\in\\free(\\aExp)%\\disjoint{{\\free(\\aLoc \\GETS \\aExp)}}{{\\free(\\PR{\\bLoc}{\\bReg})}}\n\\end{align*}\n\nRedundant load elimination \\eqref{RL} follows\nfrom \\ref{1}, taking $\\bEv\\in\\Event$, regardless of the access mode:\n\\begin{align*}\n  \\taglabel{RL}\n  \\sem{\\PR[\\amode]{\\aLoc}{\\aReg} \\SEMI \\PR[\\amode]{\\aLoc}{\\bReg}\\SEMI\\aCmd} &\\supseteq \n  \\sem{\\PR[\\amode]{\\aLoc}{\\aReg} \\SEMI \\bReg  \\GETS \\aReg\\SEMI\\aCmd}\n\\end{align*}\n\nSince \\ref{5b} does not impose order between reads of the same\nlocation, \\ref{RR} can allow the possibility that $\\aLoc=\\bLoc$.  As a\nresult, read optimizations are not limited by the power of aliasing\nanalysis.  By composing \\ref{RR} and \\ref{RL}, we validate \\ref{CSE}:\n\\begin{align*}\n  \\taglabel{CSE}\n  \\sem{r_1\\GETS \\aLoc \\SEMI\n    s\\GETS \\bLoc \\SEMI  \n    r_2\\GETS \\aLoc\\SEMI\\aCmd}\n  \\supseteq\n  \\sem{r_1\\GETS \\aLoc \\SEMI     \n    r_2\\GETS r_1\\SEMI\n    s\\GETS \\bLoc \\SEMI\\aCmd}\n  &&\\textif \\aReg_2\\neq\\bReg&&\\hbox{}\n\\end{align*}\n\nMany laws hold for the conditional, such as dead code elimination \\eqref{DC}\nand code lifting \\eqref{CL}:\n\\begin{align*}\n  \\taglabel{DC}\n  \\sem{\\IF{\\aExp}\\THEN\\aCmd\\ELSE\\bCmd\\FI} &=\n  \\sem{\\aCmd}\n  &&\\textif \\aExp \\text{ is a tautology}\n  \\\\\n  \\taglabel{CL}\n  \\sem{\\IF{\\aExp}\\THEN\\aCmd\\ELSE\\aCmd\\FI} &\\supseteq\n  \\sem{\\aCmd}\n\\end{align*}\nCode lifting also applies to program fragments inside a conditional.  For example:\n\\begin{align*}\n  \\sem{\\IF{\\aExp}\\THEN x\\GETS \\bExp \\SEMI\\aCmd\\ELSE x\\GETS \\bExp \\SEMI\\bCmd\\FI} &\\supseteq\n  \\sem{x\\GETS \\bExp \\SEMI \\IF{\\aExp}\\THEN\\aCmd\\ELSE\\bCmd\\FI}\n\\end{align*}\nWe discuss the inverse of \\ref{CL} in \\textsection\\ref{sec:refine}.\n\nAs expected, %sequential and\nparallel composition commutes with conditionals and declarations, and\nconditionals and declarations commute with each other.  For example,\nwe have \\emph{scope extrusion}~\\cite{Milner:1999:CMS:329902}:\n\\begin{align*}\n  \\taglabel{SE}\n  \\sem{\\aCmd\\PAR \\VAR\\aLoc\\SEMI\\bCmd} &=\n  \\sem{\\VAR\\aLoc\\SEMI(\\aCmd\\PAR\\bCmd)}\n  &&\\text{if } \\aLoc\\not\\in\\free(\\aCmd)\n\\end{align*}\n\n\\myparagraph{Invalid Rewrites}\n\nThe definition of location binding does not validate renaming of locations:\nif $\\aLoc\\neq\\bLoc$ then\n$\\sem{\\VAR\\bLoc\\SEMI\\aCmd}\\neq\\sem{\\VAR\\aLoc\\SEMI\\aCmd[\\aLoc/\\bLoc]}$, even\nif $\\aCmd$ does not mention~$\\aLoc$.  This is consistent with support for\naddress calculation, which is required by realistic memory allocators.\n\n\\ref{Internal2} shows that---like most relaxed models---our model\nfails to validate \\emph{thread inlining}.  The given execution is impossible\nif the first thread is split, as in\n\\begin{math}\n  \\sem{\\PR{x}{\\aReg}\\SEMI\n    \\PW[\\mRA]{y}{1}\\PAR\n    \\PR{y}{\\bReg}\\SEMI\n    \\PW{z}{\\bReg}\n    \\PAR\n    \\PW{x}{z}}.\n\\end{math}\nThe write in the first thread cannot discharge the precondition in the\nsecond, now separate.\n\nSome rewrites are invalid in a concurrent setting, such as\nrelevant read introduction:\n\\begin{displaymath}\n  \\sem{\\PR{\\aLoc}{\\aReg} \\SEMI \\IF{\\aReg {\\neq} \\aReg} \\THEN \\PW{y}{1} \\FI}\n  \\not\\supseteq\n  \\sem{\\PR{\\aLoc}{\\aReg} \\SEMI \\PR{\\aLoc}{\\bReg}  \\SEMI \\IF{\\aReg {\\neq}\\bReg} \\THEN \\PW{y}{1} \\FI}\n\\end{displaymath}\nObservationally, these are distinguished by the context %\n\\begin{math}\n  \\hole{} \\PAR \\PW{x}{1}\\PAR \\PW{x}{2}.\n\\end{math}\n\nWrite introduction is also invalid, even when duplicating an existing write:\n\\begin{displaymath}\n  \\sem{\\PW{\\aLoc}{1}} \n  \\not\\supseteq\n  \\sem{\\PW{\\aLoc}{1} \\SEMI \\PW{\\aLoc}{1}}\n\\end{displaymath}\nThese are distinguished by the context:\n\\begin{math}\n  \\hole{} \\PAR\n  \\PR{x}{r} \\SEMI\n  \\PW{x}{2} \\SEMI\n  \\PR{x}{s}\\SEMI\n  \\IF{\\aReg {=} \\bReg} \\THEN \\PW{\\cLoc}{1} \\FI.\n\\end{math}\n\n", "meta": {"hexsha": "27bdfdf6a1890c2ac116c57d749b2883f8b28bfd", "size": 24833, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "corrigendum/litmus.tex", "max_stars_repo_name": "chicago-relaxed-memory/memory-model", "max_stars_repo_head_hexsha": "fd606fdb6a04685d9bb0bee61a5641e4623b10be", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-08-13T02:36:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-25T12:46:13.000Z", "max_issues_repo_path": "corrigendum/litmus.tex", "max_issues_repo_name": "chicago-relaxed-memory/memory-model", "max_issues_repo_head_hexsha": "fd606fdb6a04685d9bb0bee61a5641e4623b10be", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "corrigendum/litmus.tex", "max_forks_repo_name": "chicago-relaxed-memory/memory-model", "max_forks_repo_head_hexsha": "fd606fdb6a04685d9bb0bee61a5641e4623b10be", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6268436578, "max_line_length": 120, "alphanum_fraction": 0.6190955583, "num_tokens": 9424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926666143434, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.335460288910284}}
{"text": "\\part{Algorithm} \\label{part:algorithm}\n% Define the structuring auto-encoder.\n\n\\chapter{Background} \\label{chap:background}\n% Motivation.\n% Why ? Neural nets, deep learning, unsupervised feature extraction, representation learning.\n% The Need for Non-Local Generalization and Distributed Representations\n% Feature learning, representation learning.\n\n%\\section{Representation learning}\n%\\section{Feature / representation learning}\n% NN is well suited for representation learning\n% We want unsupervised feature learning vs supervised vs hand-crafted\n% Representation learning\n% Learning Distributed Representations: Bengio learning deep ai\n% Representation Learning: A Review and New Perspectives\n\n\\section{Neural networks}\n% Why ? Distributed representation and computation (e.g. training on GPU, clusters) --> much what symbolic AI is not (mainly search algorithms, SAT solvers)\n% Started in the late 1950s with the perceptron.\n\n\\gls{ANNs} are a family of statistical learning models inspired by biological neural networks and are used to estimate or approximate functions that can depend on a large number of inputs and are generally unknown. It is presented as a network of interconnected neurons whose connections have numeric weights that can be tuned based on experience. It makes the neural nets adaptive to inputs and capable of learning.\n\n% What is it ? In general.\nSuch a network is composed by an input layer, a number of hidden layers and an output layer. The activation of the neurons in the input layer corresponds to the input vector, e.g. an image for computer vision, a song for \\gls{MIR}, a word vector for machine translation and sentiment analysis. A weight matrix, followed by a non-linear activation function, then transforms the vector in another representation. The output vector of the first layer is the input vector of the second, and so on until the output layer is reached. The activation of the neurons in the output layer may represent classes, probability distributions, or the estimated value of an unknown function to be learned.\n\n%{\\color{red} Picture ?}\n\n% Types: feed-forward or recurrent\nIn a feed-forward network, the connections go from one layer to the next, i.e. information only goes in one direction, forward, from the input nodes, through the hidden nodes (if any) and to the output nodes. Such networks are known to be able to approximate any function. The perceptron, the \\gls{MLP} and the \\gls{CNN} are examples of this class of networks.\nBy introducing backward connections, i.e. the connections between units form a directed cycle, we obtain a so called \\gls{RNN}. This creates an internal state of the network which allows it to exhibit dynamic temporal behavior. Unlike feed-forward neural networks, an \\gls{RNN} can use its internal memory to process arbitrary sequences of inputs. It is known to be able to approximate any program. Such networks have proven very successful for machine translation.\n\n% How to train, supervised.\nIn a supervised learning setting, the network is trained by back-propagating the error, gradient based learning method, from the output layer to the input through all the hidden layers.\nThe vanishing gradient problem, where errors shrink exponentially with the number of layers as they propagate from layer to layer, is a major issue of the algorithm \\cite{hochreiter2001vanishingGradient}. Various methods, like unsupervised pre-training or \\gls{LSTM} \\cite{hochreiter1997LSTM}, were developed to work around this problem.\n\n% How to train, unsupervised.\nHowever, in an unsupervised learning setting, there is no desired output, which implies that there is no error to back-propagate. The training algorithm should thus optimize for another objective, which represent desired properties about the output. We will introduce next such an algorithm, called an auto-encoder.\n\n\\section{Auto-encoders} \\label{sec:auto_encoders}\n% For unsupervised learning, i.e. feature extraction.\n% Auto-encoders as a manifold learning tool (Bengio review).\n\nAn auto-encoder, auto-associator or Diabolo network is an artificial neural network composed of $n$ input and output units and $m$ hidden units. It is used for learning efficient codings \\cite{bourlard1988autoencoder, hinton1994autoencoder}. The aim of an auto-encoder is to learn a distributed representation (encoding) for a set of data. An auto-encoder is trained to encode the input $\\x \\in \\R^n$ into some representation $\\z \\in \\R^m$ so that the input can be reconstructed from that representation. It is thus a generative model. Hence the target output of the auto-encoder is the auto-encoder input itself. Auto-encoders may further be stacked to form a \\gls{DBN}, while each layer can be trained separately \\cite{bengio2007DBN, ranzato2007stackedSparseAutoencoders}.\n% Stacked Auto-Encoders, not DBN\n\n%{\\color{red} Picture ?}\n\n% if linear activations are used, or only a single sigmoid hidden layer, then the optimal solution to an auto-encoder is strongly related to principal component analysis (PCA).[5]\nIf there is one linear hidden layer and the mean squared error criterion is used to train the network, then the $k$ hidden units learn to project the input in the span of the first $k$ principal components of the data \\cite{bourlard1988autoencoder}. If the hidden layer is non-linear, the auto-encoder behaves differently from \\gls{PCA}, with the ability to capture multi-modal aspects of the input distribution \\cite{japkowicz2000autoencoderPCA}.\n\nThe hope is that the code $\\z$ is a distributed representation that captures the main factors of variation in the data: because $\\z$ is viewed as a lossy representation of $\\x$, it cannot be a good representation (with small loss) for all $\\x$. So learning drives it to be one that is a good representation in particular for training examples, and hopefully for others as well (and that is the sense in which an auto-encoder generalizes), but not for arbitrary inputs.\n\nIt can typically be used for dimensionality reduction by learning a compressed ($m<n$) representation of the data. Another application is feature extraction before classification, for which we want an higher dimensionality ($m>n$) for easier separability. One serious issue with this approach is that if there is no other constraint, then an auto-encoder with $n$-dimensional input and an encoding of dimension $m \\geq n$ could potentially just learn the identity function. There are different ways that an auto-encoder with more hidden units than inputs could be prevented from learning the identity, and still capture something useful about the input in its hidden representation $\\z$.\n\n\\paragraph{Sparse auto-encoders.}\nOne strategy, based on the concept of sparse coding, is to add a sparsity constraint on the code. While an ordinary auto-encoder or an \\gls{RBM} has an encoder part which computes $P(\\z|\\x)$ and a decoder part which computes $P(\\x|\\z)$, sparse coding systems only parametrize the decoder: the encoder is implicitly defined as the solution of an optimization. A middle ground between ordinary auto-encoders and sparse coding was proposed in \\cite{lecun2006sparseAutoencoders, ranzato2007stackedSparseAutoencoders} and applied to pattern recognition and machine vision tasks. They propose to let the codes $\\z$ be free (as in sparse coding algorithms), but include a parametric encoder (as in an ordinary auto-encoder or \\gls{RBM}) and a penalty for the difference between the free non-parametric codes $\\z$ and the outputs of the parametric encoder. In this way, the optimized codes $\\z$ try to satisfy two objectives: reconstruct well the input (like in sparse coding), while not being too far from the output of the encoder (which is stable by construction, because of the simple parametrization of the encoder). See \\secref{encoder} for the definition of our encoder.\n\n\\paragraph{Denoising auto-encoders.}\nAnother strategy is to add noise in the encoding. The denoising auto-encoder thus minimizes the error in reconstructing the input from a stochastically corrupted transformation of the input \\cite{bengio2008denoisingAutoencoders}. Intuitively, a denoising auto-encoder does two things: try to encode the input (preserve the information about the input), and try to undo the effect of a corruption process stochastically applied to the input of the auto-encoder. This is essentially what a \\gls{RBM} does \\cite{hinton2002RBM}.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\chapter{Model} \\label{chap:model}\n% Step by step construction: sparse coding, dictionary learning, encoder learning, manifold learning.\n% Xavier: maybe not useful as it is just the enumeration of the sub-titles of chapter 2 --> give instead a global motivation.\n\nThis chapter presents the proposed structured auto-encoder. Built on linear regression, the model increases in complexity as desired properties about its internal representation are progressively integrated in the form of regularizations.\n\n% Plan.\n%This chapter presents the proposed structured auto-encoder. \\secref{assumptions} states the assumptions of the model. \\secref{linear_regression} reviews the basics of linear regression, the foundation of our model. \\secref{sparse_coding} introduces sparse coding, \\secref{dictionary_learning} introduces a trainable dictionary and \\secref{manifold_learning} introduces manifold learning. Last but not least, \\secref{encoder} introduces the trainable encoder. Finally, \\secref{energy_formulation} reviews the whole energy-based formulation and brings some new insights.\n\n\\section{Assumptions} \\label{sec:assumptions}\n% Xavier: needs to be improved.\n\n\\paragraph{Sparse representation.}\nWe make the hypothesis that a set of sample signals drawn from the same distribution can be sparsely represented in some frame\\footnote{A frame of a vector space is a set of vectors which may be linearly dependent. It is a generalization of a basis.}. Each signal should be approximately reconstructed by a linear combinations of a few atoms from a suitable dictionary. As we shall see, this dictionary may be adaptive and learned directly from the data. Many approaches have been developed to achieve sparse representations, e.g. sparse \\gls{PCA} \\cite{aspremont2007sparsePCA}, sparse NMF \\cite{hoyer2004sparseNMF}, K-SVD \\cite{aharon2006KSVD}. Sparse coding \\cite{olshausen1996SparseV1, mairal2008sparseCoding} is however the most popular one. Sparsity has become a concept of great interest recently, not only in machine learning but also in statistics and signal processing, in particular with the work on \\gls{CS} \\cite{candes2005CS, donoho2006CS}.\n% There is a huge body of literature on sparse coding and compressed sensing to support this hypothesis.\n% --> sparse coding.\n\n% Structured: adding similarity information between inputs.\n% Manifold: not all possible signals are reasonable / feasible.\n% Xavier: a definition of auto-encoder should be given before in the report.\n% We further assume that the subspace spanned by the data is much smaller than the Euclidean space.\n\\paragraph{Structured data.}\nOur second hypothesis is that the dataset holds some structure, in the sense that related samples are close to each other (with respect to some metric). Given a large enough training set, the structure of the data distribution should be able to be captured; i.e. a new valid sample (e.g. from the testing set) should be close to the seen examples.\nIt suggests that the data is drawn from sampling a probability distribution that has support on or near to a submanifold of the ambient space.\n% It suggests that the data lie on a lower dimensional manifold embedded in a high dimensional vector space.\nThis manifold is however often unknown and must be learned. \\gls{SOM} \\cite{kohonen1982SOM}, \\gls{LLE} \\cite{roweis2000LLE}, Laplacian Eigenmaps \\cite{belkin2001laplacianEigenmaps} and ISOMAP \\cite{tenenbaum2000isomap} are some popular techniques which learn manifolds in a \\gls{NLDR} framework. All these algorithms use the so-called locally invariant idea \\cite{lecun2006invariantMapping}, i.e. the nearby points are likely to have similar embeddings. Auto-encoders used for dimensionality reduction are able to learn a map from high to low-dimensional space with fewer hidden units than inputs. They are trained to learn to optimally encode the input vectors into a small number of dimensions and decode them back into the original space with minimal error \\cite{bourlard1988autoencoder}.\n% --> manifold learning.\n\n\\paragraph{Encoder.}\nWe further make the assumption that a simple encoder can be trained to avoid the need of an optimization process that extracts the features during testing, i.e. after the training phase. The encoder shall be more efficient, in the computational sense, than the optimization process while not degrading too much the quality of the extracted features. Note that even if this hypothesis is not verified, the algorithm is still an auto-encoder; although with an implicit encoder.\n% --> auto-encoder.\n\n\\section{Linear regression} \\label{sec:linear_regression}\n\n\\paragraph{Model.}\nGiven a set $\\set{\\x}{N} \\in \\R^n$ of $N$ signals, the subspace $\\Xx = \\spanning \\{\\x_i\\}_{i=1}^N \\subset \\R^n$ is defined as the subspace spanned by the data. Then, given a signal $\\x \\in \\Xx$ and a frame $\\D \\in \\R^{n \\times m}$, we want to find a representation $\\z \\in \\R^m$ which satisfies the linear regression model\n\\begin{equation} \\label{eqn:linear_regression}\n\t\\x = \\D \\z + \\eps,\n\\end{equation}\nwhere $\\mathbf{\\epsilon} \\in \\R^n$ is the reconstruction error, which is not negligible as long as the frame $\\D$ is not complete on $\\Xx$.\n\n\\paragraph{Capacity.} The hyper-parameter $m$ defines the learning capacity of the auto-encoder. A capacity $m < n$ is good for dimensionality reduction as it exploits the statistical regularities present in the training set while being more compact. A capacity $m > n$ is good for classification as it allows for an easier (linear) separability enabled by the higher dimensional space.\n\n\\begin{figure}[ht]\n\t\\centering\n\t\\includegraphics[height=6cm]{img/overcomplete_frame}\n\t\\caption[]{An example of overcomplete frame. While the data lies in a two-dimensional space, a four-dimensional space supported by an overcomplete frame allows a better representation.\\footnotemark}\n\t\\label{fig:overcomplete_frame}\n\\end{figure}\n\\footnotetext{Figure from Wikipedia.}\n\n\\paragraph{Completeness.}\nA frame is complete if it can represent any vector $\\x \\in \\Xx$. It is overcomplete if the removal of a vector from the frame results in a complete frame. A set of $n < m$ linearly independent vectors would indeed be overcomplete on the whole space $\\R^n$ and a set of $m=n$ linearly independent vectors, like the Fourier transform, would form a basis\\footnote{A basis is a set of linearly independent vectors who span the entire space, i.e. it is a linearly independent spanning set.} of $\\R^n$, which is obviously complete.\n\n% Complete.\nA complete frame which is not overcomplete allows bidirectional lossless transformations. Such problems are well-posed as there exists a unique solution to \\eqnref{linear_regression} with $\\eps=0$.\n\n% Not complete.\nIf the frame is not complete, there exist no solution to \\eqnref{linear_regression} with $\\eps=0$ as the system is overdetermined. An error measure, like \\eqnref{least_square} for the \\gls{OLS} method, should instead be minimized.\n\n% Overcomplete.\nIn different research, such as signal processing and function approximation, overcomplete representations have been advocated because they have greater robustness in the presence of noise, can be sparser, and can have greater flexibility in matching structure in the data. However, because of this redundancy, a signal can have multiple expressions under an overcomplete frame \\cite{lewicki2000overcompleteRepresentation}. See \\figref{overcomplete_frame} for an example of the flexibility of an overcomplete frame to represent a dataset. As there is then an infinite number of solutions to \\eqnref{linear_regression} with $\\eps=0$, i.e. the problem is ill-posed, a regularization over $\\z$ shall be introduced. Optimization techniques are then used to find the optimal solution which minimizes the sum of the error measure and the regularization term, controlled by an hyper-parameter.\n\n\\paragraph{Ordinary least squares.}\nThe method of least squares is a standard approach in regression analysis to the approximate solution of overdetermined systems. \"Least squares\" means that the overall solution minimizes the sum of the squares of the errors made in the results of every single equation, i.e. it finds\n\\begin{equation} \\label{eqn:least_square}\n\t\\z^* = \\argmin{\\z} \\normT{\\x - \\D\\z},\n\\end{equation}\nwhere $\\normT{\\cdot}$ denotes the squared $\\ell_2$, or Euclidean, norm. This problem has the closed-form solution\n\\begin{equation}\n\t\\z^* = (\\D^T\\D)^{-1} \\D^T \\x,\n\\end{equation}\nwhere $T$ denotes the matrix transpose. The primary assumption of \\gls{OLS} is that there are zero or negligible errors in the independent variable $\\D$, since this method only attempts to minimize the mean squared error in the dependent variable $\\x$. That is not an issue in an auto-encoder setting where $\\D$ is either hand-crafted or learned.\n\n% underdetermined == ill-posed ?\n\\paragraph{Regularization.}\n% L2.\nTikhonov regularization \\cite{tikhonov1963tikhonovRegularization}, or ridge regression, is the most commonly used method of regularization of ill-posed problems. It adds a prior of the form $\\lambda \\normT{\\gam \\z}$ to the minimization problem \\eqnref{least_square} as follows:\n\\begin{equation} \\label{eqn:tikhonov_regularization}\n\t\\z^* = \\argmin{\\z} \\normT{\\x - \\D\\z} + \\lambda \\normT{\\gam \\z},\n\\end{equation}\nwhere $\\gam$ is the Tikhonov matrix. This matrix is often chosen to be a multiple of the identity matrix, i.e. $\\gam = \\alpha \\mathbf{I}$, giving preference to solutions with smaller norms. In a Bayesian context, this is equivalent to placing a zero-mean normally distributed prior on $\\z$ \\cite{vogel2002inverseProblems}. In other cases, lowpass operators, e.g. a difference operator or a weighted Fourier operator, may be used to enforce smoothness if the underlying vector is believed to be mostly continuous. A regularization of this kind will be introduced in our model in \\secref{manifold_learning}. An explicit solution is given by\n\\begin{equation}\n\t\\z^* = (\\D^T\\D + \\gam^T\\gam)^{-1} \\D^T \\x.\n\\end{equation}\n\n% L1.\nAnother commonly used regularization is the \\gls{LASSO} \\cite{tibshirani1996Lasso}, which adds the prior $\\lambda \\normO{\\z}$ to the minimization problem \\eqnref{least_square} as follows:\n\\begin{equation} \\label{eqn:lasso_regularization}\n\t\\z^* = \\argmin{\\z} \\normT{\\x - \\D\\z} + \\lambda \\normO{\\z},\n\\end{equation}\nwhere $\\normO{\\z} = \\sum_{i=1}^{m} |z_i|$ is the $\\ell_1$ norm of $\\z$, also called the Taxicab or Manhattan norm.\nIn a Bayesian context, this is equivalent to placing a zero-mean Laplace prior distribution on $\\z$ \\cite{park2008BayesianLasso}. The advantage of the \\gls{LASSO} is that it promotes the simplest solutions, i.e. the solutions with many zeros. Driving parameters to zero effectively deselects the features from the regression. \\gls{LASSO} thus automatically selects the most relevant features, whereas ridge regression never fully discards any. For this reason, the \\gls{LASSO} and its variants are fundamental to the field of \\gls{CS}. A regularization of this kind will be introduced in our model in \\secref{sparse_coding}.\n\n% L1 + L2.\nAn extension of this approach is the elastic net regularization \\cite{zou2005ElasticNet} which linearly combines the $\\ell_1$ and $\\ell_2$ penalties of the \\gls{LASSO} and ridge methods as follows:\n\\begin{equation} \\label{eqn:elasticnet_regularization}\n\t\\z^* = \\argmin{\\z} \\normT{\\x - \\D\\z} + \\lambda_2 \\normT{\\z} + \\lambda_1 \\normO{\\z}.\n\\end{equation}\nThis regularization overcomes some limitations of the $\\ell_1$ penalty, e.g. the saturation which happens for high-dimensional data with few examples, or the fact that the \\gls{LASSO} tends to select only one variable and ignore the others if there is a group of highly correlated variables.\n\n\\section{Sparse coding} \\label{sec:sparse_coding}\n% What it is, why it works, why it's good.\n% paper who demonstrates that L1 penalty leads to same solution as L0 while being convex, not combinatorial\n\n% Sparse coding.\nThe main idea behind sparse coding \\cite{olshausen1996SparseV1, mairal2008sparseCoding} is to express the signal $\\x \\in \\Xx \\subset \\R^n$ as a sparse linear combination of basis functions $\\set{\\d}{m} \\in \\R^n$, or atoms, from an overcomplete dictionary $\\D \\in \\R^{n \\times m}$. The sparse code $\\z^* \\in \\R^m$ is given by\n\\begin{equation} \\label{eqn:sparsecoding}\n\t\\z^* = \\argmin{\\z} \\frac{\\lambda_d}{2} \\normT{\\x - \\D \\z} + \\lambda_z \\normZ{\\z},\n\\end{equation}\nwhere $\\normZ{\\z}$ denotes the number of non-zero elements in $\\z$.  $\\lambda_d$ and $\\lambda_z$ are the (redundant) hyper-parameters setting the trade-off between the data term, an accurate reconstruction, and the prior, a sparse solution. Overcomplete sparse representations tend to be good features for classification systems as they provide a succinct representation of the signal, are robust to noise and are more likely to be linearly separable due to their high dimensionality.\n\n% Faster sparse coding approximations.\nFinding the sparse code $\\z^*$ however requires a combinatorial search which is an NP-hard problem \\cite{natarajan1995sparseNPhard}, intractable in high dimensional spaces. Various approximations have thus been proposed. \\gls{MP} \\cite{mallat1993MatchingPursuit} offers a greedy approximation to the solution while \\gls{BP} \\cite{chen1998BasisPursuit} is the popular convex approximation\n\\begin{equation} \\label{eqn:basispursuit}\n\t\\z^* = \\argmin{\\z} \\frac{\\lambda_d}{2} \\normT{\\x - \\D \\z} + \\lambda_z \\normO{\\z},\n\\end{equation}\nwhich is the \\gls{LASSO} regularized least square problem introduced in \\eqnref{lasso_regularization}. As is now well understood \\cite{candes2005CS, donoho2006CS}, the $\\ell_1$ norm is a very good proxy for the $\\ell_0$ pseudo-norm and naturally induces sparse results. It can even be shown to recover exactly the true sparse code, i.e. the solution of \\eqnref{sparsecoding} (if there is one), under mild conditions \\cite{donoho2003OptSparse}.\n%{\\color{red}link with \\gls{RIP}}.\nA number of algorithms have been proposed to efficiently solve this problem \\cite{chen1998BasisPursuit, beck2009FISTA, ng2006EfficientSparse, li2009Coordinate}. They however still rely on computationally expensive iterative procedures which limit the system's scalability and real-time applications. While a direct method will always be preferred for feature extraction, iterative methods will still be necessary during training. Distributed computing with \\gls{GPU} or via cloud computing will hopefully accelerate the process.\n\n\\section{Dictionary learning} \\label{sec:dictionary_learning}\n\n% Why ?\n\\paragraph{Model.}\nIn classical sparse coding, the dictionary is composed of known functions such as sinusoids \\cite{bracewell1965fourier}, wavelets \\cite{mallat1999wavelet}, Gabors \\cite{gabor1946gabor}, curvelets \\cite{candes2002curvelet} or contourlets \\cite{vetterli2003contourlet}; i.e. hand-crafted features. One may also want to learn a dictionary that is adaptive to the type of data at hand. This approach may allow an even more compact representation and may lead to the discovery of previously unknown discriminative features.\n% gammatones\\footnote{A gammatone is a sinusoid (a pure tone) with an amplitude envelope which is a scaled gamma distribution function. It is used to build cochlear models.} \\cite{holdsworth1992gammatone}\n\n% How ?\nTo use the dictionary $\\D$ as an unknown variable, all the training data shall be part of the objective function as the dictionary depends on all of them. The energy function, composed by an $\\ell_2$ fidelity term and an $\\ell_1$ penalty, becomes\n\\begin{equation} \\label{eqn:en_dict}\n\t\\Eone = \\frac{\\lambda_d}{2} \\normF{\\X - \\D \\Z} + \\lambda_z \\normO{\\Z},\n\\end{equation}\nwhere $\\normF{\\cdot}$ denotes the squared Frobenius norm, $\\X = \\set{\\x}{N} \\in \\R^{n \\times N}$ is the set of training vectors and $\\Z = \\set{\\z}{N} \\in \\R^{m \\times N}$ their associated sparse codes. $N$ is naturally the number of training vectors, which should be much greater than the size $m$ of the dictionary to avoid the trivial solution where examples are copied in the dictionary. The problem to solve is then\n\\begin{equation} \\label{eqn:pr_dict}\n\t\\minimize{\\Z,\\D} \\Eone \\st \\cstd,\n\\end{equation}\nwhere the $\\ell_2$ ball constraint (usually implemented by rescaling the columns $\\d_i$ of $\\D$ at each iteration) prevents the trivial solution where the code coefficients go to zero while the bases are scaled up. While this problem is not convex, a good approximate solution can be found by iteratively minimizing for $\\Z$ and $\\D$ \\cite{olshausen1996SparseV1}.\n% Simple gradient descent or more sophisticated methods \\cite{chen1998BasisPursuit, beck2009FISTA, li2009Coordinate} for $\\z$, stochastic gradient descent for $\\D$.\n\n\\paragraph{Completeness.}\nThe learned dictionary may be seen as an overcomplete frame of the subspace $\\Xx$ spanned by the training data. The overcompleteness of the learned dictionary could indeed be tested: the frame should be able to perfectly represent any training sample, i.e. in the absence of the $\\ell_1$ regularization, the reconstruction error $\\eps$ of \\eqnref{linear_regression} should be zero.\n\n% Motivation: learned dictionaries resemble brain processing stages.\n\\paragraph{Biological motivation.}\nThere is evidence that sparse coding may be a strategy employed by the brain in the early stages of visual and auditory processing \\cite{olshausen1996SparseV1, olshausen1997SparseV1, smith2006SparseAudio}. Basis functions learned on natural images have been shown to resemble the receptive fields of neurons in the visual cortex \\cite{olshausen1996SparseV1, olshausen1997SparseV1}. Basis functions learned on natural sounds were found to be highly similar to gammatone functions \\cite{smith2006SparseAudio} which have been used to model the action of the basilar membrane in the inner ear. Moreover, learning on natural time-varying stimuli such as speech or video has been shown to produce localized bases \\cite{lewicki2000SparseSpeech, olshausen2000SparseVideo}.\n\n\\section{Manifold learning} \\label{sec:manifold_learning}\n% Further structure, geometry learning.\n% Three parts: manifold, graph and model.\n\n% Why ?\n\\paragraph{Motivation.}\n% Paper: graph regularized sparse coding.\nMost of the existing approaches to sparse coding do not consider the geometrical structure of the data space. The data is however more likely to reside on a low-dimensional submanifold embedded in the high-dimensional ambient space.\n%It has been shown that the geometrical information of the data is important for discrimination \\cite{zheng2011StructuredSparse}.\nIt has been shown that the learning performance of a sparse coding scheme can be significantly enhanced if the geometrical structure is exploited and the local invariance is considered \\cite{zheng2011StructuredSparse}.\n\n% General introduction.\n%\\paragraph{Manifold.}\n%A manifold is a topological space that resembles Euclidean space near each point, i.e. each point of an $d$-dimensional manifold has a neighborhood that is homeomorphic to the Euclidean space of dimension $d$. Lines and circles, but not figure eights, are one-dimensional manifolds. Two-dimensional manifolds are also called surfaces. Examples include the plane, the sphere, and the torus, which can all be embedded in three-dimensional real space. \\figref{manifolds} shows examples of 1D and 2D manifolds.\n\n%\\begin{figure}[ht]\n%\t\\centering\n%\t\\begin{subfigure}[b]{0.49\\textwidth}\n%\t\t\\centering\n%\t\t\\includegraphics[height=6cm]{img/circle_manifold_charts}\n%\t\t\\caption{}\n%\t\\end{subfigure}\n%\t\\begin{subfigure}[b]{0.49\\textwidth}\n%\t\t\\centering\n%\t\t\\includegraphics[height=6cm]{img/klein_bottle}\n%\t\t\\caption{}\n%\t\\end{subfigure}\n%\t\\caption[]{Examples of manifolds.\\footnotemark (a) The circle, a 1D manifold, can be mapped by four charts. (b) The klein bottle is a 2D manifold that cannot be embedded in a 3D space without self-intersection.}\n%\t\\label{fig:manifolds}\n%\\end{figure}\n%\\footnotetext{Figures from Wikipedia.}\n\n% Example close to our case.\n%Let's imagine a single handwritten digit recognition system. The input is an image of $n \\times n$ pixels which is represented by a vector $\\x \\in \\R^{n \\times n}$. However, not all vectors $\\x \\in \\R^{n \\times n}$ represent meaningful data. The vast majority indeed represents garbage. We may make the hypothesis that the set of plausible digits lies on a $d$-dimensional manifold where $d \\leq n \\times n$.\n\n% Approximate a manifold.\n%The problem is that we often ignore the shape of the embedded manifold. We only have at our disposal some samples which are drawn from it, e.g. a few examples of handwritten digits. Another example with object scanning: we obtain a discrete point cloud sampled from the surface. We do know some points on the surface, but we don't know the exact surface.\n\n%We use graphs as discrete approximations of low-dimensional manifolds embedded in high-dimensional spaces. The set of data are samples drawn from this unknown manifold.\n\n% General formulation.\n% What a graph is, generally. Not only a manifold approximation.\n\\paragraph{Similarity graphs.}\n% Paper: Pierre's review\nGraphs are generic data representation forms which are useful for describing the geometric structures of data domains in numerous applications, including social, energy, transportation, sensor, and neuronal networks \\cite{pierre2013graphs}. The connectivity and weight associated with each edge in the graph is either dictated by the physics of the problem at hand or inferred from the data.\nWeighted graphs are commonly used to represent similarities between data points in statistical learning problems for applications such as machine vision \\cite{lowe1999graphSimilarity} and automatic text classification \\cite{apte1994graphSimilarity}.\n\n%\\begin{figure}[ht]\n%\t\\centering\n%\t\\includegraphics[height=6cm]{img/example_graph}\n%\t\\caption[]{A random positive graph signal on the vertices of the Petersen graph. The height of each blue bar represents the signal value at the vertex where the bar originates.\\footnotemark}\n%\t\\label{fig:example_graph}\n%\\end{figure}\n%\\footnotetext{Figure from \\cite{pierre2013graphs}.}\n\n% We first review some basic definitions and notations from spectral graph theory and then show how we can use a graph to approximate a manifold.\n\n% Graph definition.\nFrom the set of training vectors $\\X$, we can construct an undirected, connected and weighted graph $\\G = \\{ \\V, \\mathcal{E}, \\W \\}$ which consists of a finite set of vertices $\\V$ with $|\\V| = N$, a set of edges $\\mathcal{E}$, and a weighted adjacency matrix $\\W = (w_{ij}) \\in \\R^{N \\times N}$. Each vertex $i \\in \\V$ represents a training vector $\\x_i$. If there is an edge $e = (i, j)$ connecting vertices $i$ and $j$, the entry $w_{ij}$ represents the weight of the edge; otherwise, $w_{ij} = 0$. The set of sparse codes $\\Z$ is a signal which resides on the graph, i.e. a signal with one sample $\\z_i$ at each vertex $i$ of the graph.\n\n% Distance metric: euclidean (small dim) and cosine (angular, high dim).\n% ref for why cosine is better in high dim\n% Intuition: cosine is euclidean when data projected to sphere.\n% Kernel: Gaussian or polynomial.\nWhile there exist several ways to define the edge weights when they are not naturally defined by the application, they often represent the similarity between the two vertices they connect \\cite{pierre2013graphs}. For instance, the edge weight may be inversely proportional to the Euclidean distance between the vectors:\n\\begin{equation}\n\tw_{ij} = \\exp \\left( - \\frac{\\normT{\\x_i - \\x_j}}{2\\sigma^2} \\right) \\in [0,1],\n\\end{equation}\nwhere the Gaussian kernel width $\\sigma$ controls the width of the neighborhoods and $\\inner{\\cdot}{\\cdot}$ denotes the scalar product. While the Euclidean distance is a good choice for low-dimensional data, its discriminative power vanishes in higher dimensional space \\cite{aggarwal2001highDimDistance, domingos2012pitfallsML}. An option is then to use the cosine similarity as the edge weight:\n\\begin{equation}\n\tw_{ij} = \\frac{1}{2} + \\frac{1}{2} \\cos(\\theta) = \\frac{1}{2} \\left(1 + \\frac{\\inner{\\x_i}{\\x_j}}{\\|\\x_i\\|_2 \\|\\x_j\\|_2} \\right) \\in [0,1],\n\\end{equation}\nwhere $\\theta$ is the angle between the two vectors $\\x_i$ and $\\x_j$. Another reason for the popularity of the cosine similarity is that it is very efficient to evaluate, especially for sparse vectors, as only the non-zero dimensions need to be considered. See \\cite{grady2010graphs} for other graph\nconstruction methods.\n\n% Type: KNN vs epsilon.\nA fully connected graph is usually not wanted: the number of edges are often artificially limited in order to reduce the storage and computational cost associated with the graph manipulation, effectively sparsifying the weight matrix $\\W$.\nThe $\\epsilon$-neighborhood graph is the popular approach which sets to 0 any weigh $w_{ij} < \\epsilon$ for some threshold $\\epsilon$.\nA second common method is to connect each vertex to its $k$-nearest neighbors only and drop the smallest weights; in which case \\cite{zelnik2004scale} suggests to set the Gaussian kernel scale $\\sigma$ to the mean of the $k^{\\text{st}}$ distances.\n\n\\paragraph{Graph Laplacian.}\n% The graph (normalized) Laplacian is an approximation of the Laplace-Beltrami operator. --> Dirichlet energy\n% normalized vs un-normalized, cite normalized approximates the Laplace-Beltrami operator\n% A way to test if the Laplacian is well constructed is... (see blog)\n% Another regularization on Z. Like Thikonov with the graph Laplacian as the Tikhonov matrix (difference operator). It enforces smoothness on the graph / manifold.\n% The graph Laplacian as a difference operator.\n% \\L = U \\Lambda U^*, U Fourier basis, Lamb eigenvalues / frequencies, U* inverse Fourier.\nThe unnormalized graph Laplacian, also called the combinatorial graph Laplacian, is defined as\n\\begin{equation}\n\t\\L = \\A - \\W,\n\\end{equation}\nwhere the degree matrix $\\A=(a_{ij}) \\in \\R^{N \\times N}$ is a diagonal matrix whose $i$th diagonal element $a_{ii}$ is equal to the sum of the weights of all the edges incident to vertex $i$:\n\\begin{equation}\n\ta_{ii} = \\sum\\limits_{j=1}^{N} w_{ij}.\n\\end{equation}\nThe graph Laplacian is a difference operator as it satisfies\n\\begin{equation}\n\t\\L\\z_i = \\sum\\limits_{j=1}^{N} w_{ij} (\\z_i - \\z_j).\n\\end{equation}\n\n\\paragraph{Dirichlet energy.}\nThe Dirichlet energy is a measure of the smoothness of a graph signal given by\n\\begin{equation} \\label{eqn:dirichlet_energy}\n\t\\tr(\\Z\\L\\Z^T) = \\frac{1}{2} \\sum\\limits_{i=1}^{N} \\sum\\limits_{j=1}^{N} w_{ij} \\normT{\\z_i - \\z_j} \\geq 0,\n\\end{equation}\nwhich is a suitable candidate for regularization \\cite{belkin2006manifoldRegularization}.\n%\\paragraph{Manifold assumption.}\nThe assumption that the representations $\\Z$ should be smooth on the similarity graph $\\G$ constructed by the training vectors $\\X$, usually referred to as the manifold assumption\\footnote{Because the graph is used as a proxy for the manifold.}, plays an essential role in various kinds of algorithms including dimensionality reduction algorithms \\cite{belkin2001laplacianEigenmaps}, clustering algorithms \\cite{ng2002spectralClustering} and semi-supervised learning algorithms \\cite{belkin2006manifoldRegularization, zhou2004manifoldRegularization}.\nNote that the Euler-Lagrange of the Dirichlet energy is precisely the graph Laplacian.\n% exploit the geometrical information in the data by using the manifold assumption which has been shown effective in classification and clustering tasks \\cite{belkin2006manifoldRegularization}.\n\n% Why normalized Laplacian ? Consistency.\n% Descrete graph Laplacian converges to continuous Laplace-Beltrami operator.\n% Reference: Erdos.\n% Why graphs ? To approximate the unknown manifold.\n% Correct approximation because of the consistency principle.\n% While the dataset $\\X$ is supposedly drawn from a manifold, the manifold itself is unknown.\n\\paragraph{Consistency.}\nTwo normalized graph Laplacians are found in the literature \\cite{chung1997spectralGraphTheory}:\n\\begin{equation}\n\t\\L_{sym} = \\A^{-1/2} \\L \\A^{-1/2} = \\I - \\A^{-1/2} \\W \\A^{-1/2},\n\\end{equation}\nand\n\\begin{equation}\n\t\\L_{rw} = \\A^{-1} \\L = \\I - \\A^{-1} \\W,\n\\end{equation}\nwhere $\\I$ denotes the identity matrix.\nWhile there is no convergence guarantee for the unnormalized graph Laplacian, these two normalized Laplacian can be shown to converge to the continuous Laplace-Beltrami operator as the number of samples increase \\cite{vonluxburg2008consistency}. The similarity graph is indeed a good approximation of the unknown manifold.\n\n\\paragraph{Model.}\n% Paper: By using graph Laplacian as a smooth operator, the obtained sparse representations vary smoothly along the geodesics of the data manifold.\nThe geometrical information about the data is encoded in a similarity graph constructed by the training vectors $\\X$ and the graph Laplacian is used as a smooth operator to preserve the local manifold structure. Introducing the Dirichlet energy into the objective function as an additional $\\ell_2$ regularization, similar to the Tikhonov regularization presented in \\secref{linear_regression}, gives\n\\begin{equation}\n\t\\Etwo = \\frac{\\lambda_d}{2} \\normF{\\X - \\D \\Z} + \\lambda_z \\normO{\\Z} + \\frac{\\lambda_g}{2} \\tr(\\Z^T \\L \\Z).\n\\end{equation}\nThis regularization promotes a smooth variations of the representations along the geodesics of the data manifold.\n\n\\section{Encoder} \\label{sec:encoder}\n% Auto-encoder: explicit encoder instead of implicit encoder.\n% Problem: these methods are slow at inferring sparse codes as they need iterations\n% --> train an encoder\n\n\\paragraph{Motivation.}\nIn order to avoid the iterative procedure typically required to infer the sparse code, we aim at an explicit encoder which can quickly map inputs to approximations of their sparse code. Several works \\cite{lecun2010PSD, lecun2010LISTA, lecun2013DrSAE} have been done in this direction. The addition of an explicit encoder to the sparse coding scheme bridges the gap between auto-encoders and sparse coding and is often referred to as sparse auto-encoders \\cite{bengio2009learningDeepAI}.\n% {\\color{red} [others not from LeCun?]}\n% Xavier: cite Andrew Ng. But iterative ?\n\n% 2nd motivation.\nMoreover, adding structure to the problem should enhance the behavior of the loss function and help sparse recovery \\cite{kowalski2009sparse, baraniuk2010modelCS, huang2011LearningStructuredSparsity, jenatton2011structured}.\n% {\\color{red}Then \\cite{donoho2003OptSparse} should not be strong enough.}\n\n% How ?\n\\paragraph{Model.}\nIntroducing a trainable encoder $\\E \\in \\R^{m \\times n}$, designed to predict sparse codes from input vectors with minimum error, into our model gives the energy function\n\\begin{equation} \\label{eqn:en_encoder}\n\t\\Ethree = \\frac{\\lambda_d}{2} \\normF{\\X - \\D \\Z} + \\lambda_z \\normO{\\Z} + \\frac{\\lambda_g}{2} \\tr(\\Z^T \\L \\Z) + \\frac{\\lambda_e}{2} \\normF{\\Z - \\E \\X}, %{\\color{red} + \\lambda_s \\normO{\\E \\X}},\n\\end{equation}\n%where $\\lambda_e$ and $\\lambda_s$ are two additional hyper-parameters which control the sparsity versus fidelity tradeoff. The problem is then defined by\nwhere $\\lambda_e$ is an additional hyper-parameter which controls the relative weight of the prediction error. The problem is then defined by\n\\begin{equation} \\label{eqn:pr_encoder}\n\t\\minimize{\\Z,\\D,\\E} \\Ethree \\st \\cst{\\d}{i} , \\cst{\\e}{k} ,\n\t\\ \\forallx{i}{m} , \\ \\forallx{k}{n},\n\\end{equation}\nwhere $\\e_k$ are the columns of $\\E$. %Again, the $\\ell_1$ penalty $\\normO{\\E \\X}$ regularizes the least square problem, i.e. the \\gls{LASSO} method.\n\n\\paragraph{Energy.}\nWhile it is often a good idea to control the energy, the constraint on the columns of $\\E$ is not needed in practice. While the columns of $\\D$ are constrained to a norm smaller than one, they are in practice normalized because of the $\\normO{\\Z}$ objective. The energy of a vector transformed by $\\D$ does thus not change, which means that the inferred sparse code $\\z_i$ as the same energy as its corresponding vector $\\x_i$. The encoder does then not need to add energy and will have a column norm smaller than one, even without the constraint. It has been verified empirically.\n\n\\section{Auto-encoder}\n% Reviews the whole energy-based formulation and brings some new insights.\n% Identify parts of the energy functions to equations in regression, e.g. tik, lasso, elastic.\n\n\\paragraph{Energy formulation.}\nThe energy function \\eqnref{en_encoder}, which defines our model, may be rewritten as a sum of functions of the variables $\\Z$, $\\D$ and $\\E$ as follows:\n\\begin{equation} \\label{eqn:objective}\n\tE(\\Z, \\D, \\E) =\n\t\\underbrace{\\frac{\\lambda_d}{2} \\normF{\\X - \\D \\Z}}_{\\fd} +\n\t\\underbrace{\\lambda_z \\normO{\\Z}}_{\\fz} +\n\t\\underbrace{\\frac{\\lambda_g}{2} \\tr(\\Z^T \\L \\Z)}_{\\fg} +\n\t\\underbrace{\\frac{\\lambda_e}{2} \\normF{\\Z - \\E \\X}}_{\\fe}.\n\\end{equation}\nAn advantage of energetic formulations is that it is easy to control the relative importance of the sub-objectives, whether they are fidelity or prior terms. As seen through this chapter, the model can be easily constructed by sequentially adding terms to the objective. They are as easily removed, or muted, when experimentations require it. Other advantages include good understanding, robustness, existence of solutions, design and analysis of optimization algorithms.\n\n\\paragraph{Auto-encoder model.}\nTraining the model is akin to minimize the objective function \\eqnref{objective} over the variables, or model parameters $\\Z$, $\\D$ and $\\E$:\n\\begin{multline} \\label{eqn:model}\n\t%\\text{given} \\lambda_d, \\lambda_z, \\lambda_g, \\lambda_e \\geq 0, \\X\n\t\\minimize{\\Z,\\D,\\E} \\fd + \\fz + \\fg + \\fe \\\\\n\t\\st \\cst{\\d}{i} ,\\ \\cst{\\e}{k} ,\\ \\forallx{i}{m} ,\\ \\forallx{k}{n}.\n\\end{multline}\nPosing the problem as the minimization of an objective function is a sound expression of the model. Indeed, many laws of nature are nothing but optimality conditions, often expressed in terms of a minimum energy principle.\n\nNote that the regularizations $\\fz$ and $\\fg$ on the internal representation are preventing the auto-encoder to learn the identity $\\D = \\E = \\I$.\n\n\\paragraph{Encoder.}\nThe proposed model is an auto-encoder. Given its hyper-parameters $\\lambda_d, \\lambda_z, \\lambda_g, \\lambda_e \\geq 0$ and a training set $\\X$, model \\eqnref{model} learns the auto-encoder variables, i.e. the dictionary $\\D$ and the encoder $\\E$. Then, given $\\D$ and $\\E$, the sparse and structured internal representation $\\z^*$ of an unseen sample $\\x$ is given by\n\\begin{equation} \\label{eqn:z_exact}\n\t\\z^* = \\argmin{\\z} \\frac{\\lambda_d}{2} \\normT{\\x - \\D \\z} + \\lambda_z \\normO{\\z} + \\frac{\\lambda_g}{2} \\inner{\\z}{\\L \\z} + \\frac{\\lambda_e}{2} \\normT{\\z - \\E \\x},\n\\end{equation}\nwhere the graph Laplacian $\\L$ is constructed from the data.\n\n\\paragraph{Decoder.}\nSimilarly, the mapping of a representation $\\z$ back to the input domain is given by\n\\begin{equation} \\label{eqn:x_exact}\n\t\\x^* = \\argmin{\\x} \\frac{\\lambda_d}{2} \\normT{\\x - \\D \\z} + \\frac{\\lambda_e}{2} \\normT{\\z - \\E \\x}.\n\\end{equation}\n\n\\section{Approximate schemes} \\label{sec:approximate_schemes}\n% In the next chapter ? It is not really a part of the model, but a use of it. Not really: third assumption.\n\n\\paragraph{Motivation.}\nWhile encoder \\eqnref{z_exact} extracts the exact representation given the auto-encoder model \\eqnref{model}, it is computationally heavy. We aim at a faster encoder model to infer an approximate representation $\\tilde{\\z} \\approx \\z^*$.\n\n\\paragraph{Direct encoder.}\nNeglecting some of the terms in \\eqnref{z_exact} because of our model's third assumption given in \\secref{assumptions}, the approximation:\n\\begin{equation} \\label{eqn:z_approximate}\n\t\\tilde{\\z} = \\argmin{\\z} \\frac{\\lambda_e}{2} \\normF{\\z - \\E \\x} + \\lambda_z \\normO{\\z}\n\\end{equation}\nis able to infer good enough representations. Problem \\eqnref{z_approximate} holds a closed-form solution:\n\\begin{equation} \\label{eqn:z_direct}\n\t\\tilde{\\z} = h_{\\lambda_z / \\lambda_e} (\\E \\x),\n\\end{equation}\nwhere $h_\\lambda$ is the shrinkage function defined here by\n\\begin{equation} \\label{eqn:shrinkage}\n\th_\\lambda(\\x)_k = \\sign(x_k) \\left( |x_k| - \\lambda \\right)_+ ,\n\\end{equation}\nwhere $(\\cdot)_+ = \\max(\\cdot, 0)$. Therefore, the explicit encoder formulation introduced in \\secref{encoder} allows a direct inference of the representation.\n\nNote that although the dictionary $\\D$ and the graph Laplacian $\\L$ are not used in the approximate scheme \\eqnref{z_direct}, they however add structure to the problem because $\\E$ is learned simultaneously with $\\D$ and a regularization which makes use of $\\L$. Additional structure has been shown to enhance the behavior of the loss function and help sparse recovery \\cite{kowalski2009sparse, baraniuk2010modelCS, huang2011LearningStructuredSparsity, jenatton2011structured}.\n\n\\paragraph{Direct decoder.}\nAlthough we care less about decoder \\eqnref{x_exact}, a similar approach may be used to approximate $\\x^*$:\n\\begin{equation} \\label{eqn:x_direct}\n\t\\tilde{\\x} = \\argmin{\\x} \\frac{\\lambda_d}{2} \\normT{\\x - \\D \\z} = \\D \\z.\n\\end{equation}\n\n\\chapter{Related works}\n% That is clearly not a part of the model.\n% How do we compare with other auto-encoders ?\n% Our overall model may be thought as an hybrid between a sparse and a denoising auto-encoder.\n\n\\paragraph{Standard auto-encoders.}\nAuto-encoders, as introduced by \\cite{bourlard1988autoencoder, hinton1994autoencoder}, are defined by one linear hidden layer and the mean squared error criterion is used to train the network, i.e. their model is \\eqnref{model} without any regularization.\nBecause of the lack of constraint, an auto-encoder with $n$-dimensional input and an encoding of dimension at least $n$ could potentially just learn the identity function. However, it as been shown that \\gls{SGD} with early stopping is similar to an $\\ell_2$ regularization of the parameters \\cite{zinkevich2003SGDl2regularization}.\n\n\\paragraph{Sparse auto-encoders.}\nDirect decoder \\eqnref{x_direct} is the definition used for sparse auto-encoders \\cite{lecun2006sparseAutoencoders, ranzato2007stackedSparseAutoencoders}. While the encoder definition may vary, it includes at least the first two terms of encoder \\eqnref{z_exact}, related to sparse coding.\n\n\\paragraph{Predictive sparse decomposition.}\nA technique introduced in \\cite{lecun2010PSD} which, similarly to us, adds an explicit encoder to the sparse coding scheme. Their encoder architecture is very close to direct encoder \\eqnref{z_direct}. Using sparse coding, their decoder is defined by direct decoder \\eqnref{x_direct}.\n\n\\paragraph{Denoising auto-encoders.}\nDenoising auto-encoders share the same model as the standard auto-encoders, but are trained with stochastically corrupted data  \\cite{bengio2008denoisingAutoencoders}. They thus learn to undo the effect of the corruption. In model \\eqnref{model}, the Dirichlet energy term promotes smooth variations along the data manifold. It has the effect of pushing noisy samples toward the manifold, effectively denoising them.\n%This is essentially what a \\gls{RBM} does \\cite{hinton2002RBM}.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\chapter{Optimization} \\label{chap:optimization}\n% Learning / Training\n% Non-convex problem where each sub-problem / independant variable is a convex problem --> outer loop --> objective monotically decreasing.\n% Batch (FISTA, primal-dual) and online (stochastic gradient descent) training\n% Transductive learning\n% Non-convex problem composed of convex sub-problems.\n% Derive prox and gradients.\n% Why we can use FISTA an PD ?\n% Derive FISTA and primal-dual formulations.\n\n% Three properties of non-convex optimization: monotony (of the energy function), convergence (local, global, critical points) and speed. Convergence is hard to prove.\n\nThe whole process of training the auto-encoder is to solve the non-convex optimization problem which defines model \\eqnref{model}. Because of its non-convexity, there is no guarantee to find its global minimum.\n%While there exist techniques for non-convex optimization, they are very slow.\nThe minimization will end up in a local minimum depending on the initialization. That is, given the same training data, different random initializations of the variables will lead to different solutions.\n%{\\color{red} Is there anything we can say about good enough local minima ? Or that many local minima are actually similar and we don't care in which we fall ?}\n\n\\paragraph{Convex sub-problems.}\nAs problem \\eqnref{model} is non-convex only when all the variables are taken together, a natural way is to decompose it into three convex sub-problems:\n\\begin{align}\n\t\\label{eqn:minZ}\n\t\\minimize{\\Z} & \\fd + \\fz + \\fg + \\fe , \\\\\n\t\\label{eqn:minD}\n\t\\minimize{\\D} & \\fd \\st \\cst{\\d}{i} ,\\ \\forallx{i}{m} , \\\\\n\t\\label{eqn:minE}\n\t\\minimize{\\E} & \\fe \\st \\cst{\\e}{k} ,\\ \\forallx{k}{n}.\n\\end{align}\nSub-problem \\eqnref{minZ} is an $\\ell_1$ and $\\ell_2$ regularized least squares problem while sub-problems \\eqnref{minD} and \\eqnref{minD} are constrained least squares problems. Both of which can efficiently be solved by several convex optimization methods \\cite{combettes2011proximalSplitting, beck2009FISTA, chambolle2011PrimalDual}.\n\n\\paragraph{Iterative scheme.}\nThe idea is to iteratively solve \\eqnref{minZ}, \\eqnref{minD} and \\eqnref{minE}, i.e. to minimize the objective for one variable at a time while fixing the two others. While we have no convergence guarantee, the overall loss function is guaranteed to decrease monotonically if each convex sub-problem is optimally solved, which is the case if we let each sub-minimization converge.\n\n\\paragraph{Proximal splitting.}\nProximal splitting methods are a class of algorithms designed to solve convex problems of the form\n\\begin{equation} \\label{eqn:convex_prob}\n\t\\minimize{\\x} f_1(\\x) + f_2(\\x),\n\\end{equation}\nwhere $f_1$ is a convex but non-smooth function and $f_2$ is convex and differentiable with a $\\beta$-Lipschitz continuous gradient $\\nabla f_2$, i.e.,\n\\begin{equation}\n\t\\forall(\\x,\\y) \\ \\ \\|\\nabla f_2(\\x) - \\nabla f_2(\\y) \\|_2 \\leq \\beta \\| \\x - \\y \\|_2 ,\n\\end{equation}\nwhere $\\beta \\in \\ ]0,+\\infty[$.\n\nIt can be shown \\cite{combettes2005forwardBackward} that problem \\eqnref{convex_prob} admits at least one solution and that, for any $\\gamma \\in \\ ]0,+\\infty[$, its solutions are characterized by the fixed point equation\n\\begin{equation} \\label{eqn:fixed_point}\n\tx = \\prox{\\gamma f_1} \\left( \\x - \\gamma \\nabla f_2(\\x) \\right),\n\\end{equation}\nwhere $\\prox{f}$ denotes the proximity operator of $f$, defined as the minimization problem\n\\begin{equation}\n\t\\prox{f} \\x = \\minimize{\\y} f(\\y) + \\frac{1}{2} \\normT{\\x - \\y},\n\\end{equation}\nwhich is an extension of the notion of a projection operator \\cite{moreau1962prox}.\nThe fixed point equation \\eqnref{fixed_point} suggests the possibility of iterating\n\\begin{equation}\n\t\\x^{t+1} = \\underbrace{\\prox{\\gamma_t f_1}}_\\text{backward step} \\underbrace{ \\left( \\x^t - \\gamma \\nabla f_2(\\x^t) \\right) }_\\text{forward step}\n\\end{equation}\nfor values of the step-size parameter $\\gamma_t$ in a suitable bounded interval which depends on $\\beta$. This type of scheme is known as a \\textit{forward-backward} splitting algorithm. It can be broken up into a forward (explicit) gradient\nstep using the function $f_2$, and a backward (implicit) step using the function $f_1$ \\cite{combettes2011proximalSplitting}.\n\nThe \\gls{FISTA} \\cite{beck2009FISTA} is an efficient forward-backward scheme which exploits variable time steps and multiple points. It achieves an optimal \\cite{nemirovsky1983optimalConvergence} $O(1/t^2)$ rate of convergence of the objective function.\n\n\\paragraph{Sub-problems casting.}\nTo be solved via \\gls{FISTA}, each of the minimization sub-problems \\eqnref{minZ}, \\eqnref{minD} and \\eqnref{minE} has to be cast to the form of \\eqnref{convex_prob} and provide the gradient $\\nabla f_2$, its Lipschitz constant $\\beta$ and the proximity operator of $f_1$.\n\nSub-problem \\eqnref{minZ} is split into a smooth and a non-smooth part:\n\\begin{equation}\n\t\\minimize{\\Z} \\underbrace{\\fd + \\fg + \\fe}_{f_2(\\Z)} + \\underbrace{\\fz}_{f_1(\\Z)}.\n\\end{equation}\nThe gradient $\\nabla f_2$, its Lipschitz constant $\\beta$ and the proximity operator of $f_1$ are as follows:\n\\begin{align}\n\t\\nabla f_2(\\Z) &= \\lambda_d \\D^T (\\X - \\D \\Z) + \\lambda_e (\\Z - \\E \\X) + \\lambda_g \\L \\Z \\\\\n\t\\beta &\\geq \\lambda_e + \\lambda_d \\| \\D^T \\D \\|_2 + \\lambda_g \\|\\L\\|_2 \\\\\n\t\\prox{\\beta^{-1} f_1}(\\D) &= h_{\\lambda_z / \\beta} (\\Z)\n\\end{align}\nwhere $h_\\lambda$ is the shrinkage function \\eqnref{shrinkage}.\n\nThe constraint of \\eqnref{minD} can be integrated in the loss function via the Lagrange multiplier method:\n\\begin{equation}\n\t\\minimize{\\D} \\underbrace{\\frac{\\lambda_d}{2} \\normF{\\X^T - \\Z^T\\D^T}}_{f_2(\\D)} + \\underbrace{\\iota_C(\\D)}_{f_1(\\D)},\n\\end{equation}\nwhere $\\iota_C$ is the indicator function of the subset $C \\in \\R^{n \\times m}$ defined as\n\\begin{equation}\n\t\\iota_C(\\D) = \\left\\{ \\begin{array}{rl}\n\t0, & \\text{if } \\cstd; \\\\\n\t+\\infty, & \\text{otherwise}.\n\t\\end{array}\\right.\n\\end{equation}\nThe gradient $\\nabla f_2$, its Lipschitz constant $\\beta$ and the proximity operator of $f_1$ are as follows:\n\\begin{align}\n\t\\nabla f_2(\\D) &= \\lambda_d \\Z (\\X^T - \\Z^T \\D^T) \\\\\n\t\\beta &\\geq \\lambda_d \\| \\Z \\Z^T \\|_2 \\\\\n\t\\prox{\\beta^{-1} f_1}(\\D) &= \\left\\{ \\frac{\\d_i}{\\max(1, \\|\\d_i\\|_2)} \\right\\}_{i=1}^m.\n\\end{align}\n\nSimilarly, for \\eqnref{minE}:\n\\begin{align}\n\t\\nabla f_2(\\E) &= \\lambda_e \\X (\\Z^T - \\X^T \\E^T) \\\\\n\t\\beta &\\geq \\lambda_e \\| \\X \\X^T \\|_2 \\\\\n\t\\prox{\\beta^{-1} f_1}(\\E) &= \\left\\{ \\frac{\\e_k}{\\max(1, \\|\\e_k\\|_2)} \\right\\}_{k=1}^n.\n\\end{align}\n\n%\\section{Algorithm}\n% How to write algorithms (with a frame) in Latex ?\n\n%Given the hyper-parameters $\\lambda_d \\geq 0$, $\\lambda_z \\geq 0$, $\\lambda_g \\geq 0$, $\\lambda_e \\geq 0$ and a training set $\\X \\in \\R^{n \\times N}$.\n\n%\\paragraph{Initialization}\n%Randomly initialize $\\D$ and rescale each column to unit-norm to satisfy the constraint of problem \\eqnref{model}. Initialize $\\Z$ to zero. % sparse enough, cannot practically init to full because of mem.\n\n%\\section{Convex problem}\n% What is a convex problem (objective and constraints).\n% Methods to solve: analytically or numerical schemes.\n%\\section{Numerical solvers}\n% Numerical: gradient descent --> slow --> second order methods like Newton\n% Stochastic gradient descent\n%\\section{Proximal splitting methods}\n% But our objective function is not differentiable\n% Ridge regression is, but not the LASSO regularization.\n% --> rely on a sub-gradient method, the proximity / proximal operator --> proximal splitting\n%\\subsection{Forward-backward}\n% Different basic methods to solve these problems: forward-backward, douglas-rachford\n% Explain the intuition\n%\\subsection{Douglas-Rachford}\n%\\subsection{FISTA}\n% Advanced (faster) algorithms who exlpoit variable time steps and multiple points: FISTA\n%\\section{Dual problem}\n% Introducing the dual problem (paper playing with duality)\n%\\subsection{Primal-dual}", "meta": {"hexsha": "5fa397bdd598eb62662814143d8acc69ede55cb1", "size": 55401, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "algorithm.tex", "max_stars_repo_name": "mdeff/dlaudio_report", "max_stars_repo_head_hexsha": "5ade45c45001f60b8f617898b2eadf4203ec1ff9", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-07-16T22:14:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-15T12:08:02.000Z", "max_issues_repo_path": "algorithm.tex", "max_issues_repo_name": "mdeff/dlaudio_report", "max_issues_repo_head_hexsha": "5ade45c45001f60b8f617898b2eadf4203ec1ff9", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "algorithm.tex", "max_forks_repo_name": "mdeff/dlaudio_report", "max_forks_repo_head_hexsha": "5ade45c45001f60b8f617898b2eadf4203ec1ff9", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 92.489148581, "max_line_length": 1169, "alphanum_fraction": 0.7680727785, "num_tokens": 14459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.33546028891028395}}
{"text": "% To be compiled with pdf LaTeX\r\n% This file is to be included into master file via \\input command\r\n% Note that there is no \\begin{document} \\end{document} brackets!\r\n\r\n\\newpage\r\n\\section{Laser guide star modeling}\r\n\\label{sec:lgs}\r\n\r\n\\mbox{}\r\n\r\nLaser guide star modeling and propagation to and through telescope is viewed\r\nfrom algorithmic standpoint. The formulas derived herein can be\r\nused directly for coding. No approximations are used unless necessary to\r\nreduce excessive computational complexity.\r\n\r\nThe goals of this section are\r\n\\begin{enumerate}\r\n\t\\item Find wavefront phase map in the telescope entrance pupil given the\r\n\tfollowing set of parameters:\r\n\t\\begin{itemize}\r\n\t\t\\item laser launch telescope location, pointing and focus position;\r\n\t\t\\item telescope pointing;\r\n\t\t\\item position in the telescope entrance pupil.\r\n\t\\end{itemize}\r\n\t\\item Find spot elongation and orientation in the detector focal plane.\r\n\t\\item Find photon fluxes through the wavefront sensor subapertures.\r\n\\end{enumerate}\r\n\r\n\\subsection{Nomenclature}\r\n\r\n\\mbox{}\r\n\r\n$g$-system - ``global'' or ``laboratory'' coordinate system with respect to\r\nwhich all\r\nother coordinates and coordinate systems are defined. $Z$-axis is along the\r\ntelescope optical axis at zenith position pointing towards the sky (Fig.\r\n\\ref{fig:lgs-geom}).\r\n\\\\\r\n\r\n$t$-system - ``telescope'' coordinate system such that its $z$-axis is always\r\nalong the telescope optical axis for any zenith or azimuth angle.\r\n\\\\\r\n\r\n$l$-system - ``laser launch telescope'' coordinate system such that its $z$-axis\r\nis always along the laser launch telescope optical axis.\r\n\\\\\r\n\r\n$(\\bm{o},\\mathcal{R})_{b}^{a}$ - the ``orientation pair'' consisting of the\r\norigin coordinate vector $\\bm{o}$ and rotation matrix $\\mathcal{R}$ to specify\r\ncoordinate transformation from coordinate system $a$ to coordinate system $b$\r\nor, in other words, origin and ort coordinates of $b$-system written in\r\n$a$-system.\r\n\\\\\r\n\r\n$h_{0},h_{+},h_{-}$ - median, upper and lower altitudes of the \\texttt{Na}\r\nlayer, [m].\r\n\\\\\r\n\r\n$\\texttt{Eu}(\\alpha,\\beta,\\gamma)$ - coordinate rotation by Euler angles\r\n$\\alpha,\\beta,\\gamma$, [rad].\r\n\\\\\r\n\r\n$\\beta_{t}^{g}$ - zenith angle of telescope with respect to g-system, [rad].\r\n\\\\\r\n\r\n$\\beta_{l}^{t}$ - zenith angle of the $l^{th}$ LGS with respect to $t$-system,\r\n[rad].\r\n\\\\\r\n\r\n$\\bm{r}_{l}^{t}$ - coordinates of $l^{th}$ Laser Launch Telescope (LLT)\r\nprojected to the telescope Entrance Pupil (EnP), [m].\r\n\\\\\r\n\r\n$\\bm{r}_{p}^{t}$ - coordinates of $p^{th}$ point in the EnP grid, [m].\r\n\\\\\r\n\r\n$\\bm{r}_{li}^{l}$ - coordinates of $i^{th}$ point source in the $l^{th}$ Laser\r\nGuide Star (LGS), in $l$-system, [m].\r\n\\\\\r\n\r\n$r_{lip}$ - distance from $i^{th}$ point source in the $l^{th}$ LGS to\r\n$p^{th}$ point in EnP, [m].\r\n\\\\\r\n\r\n$\\Phi_{li}$ - photon flux from $i^{th}$ point source belonging to $l^{th}$ LGS,\r\n[photons].\r\n\\\\\r\n\r\n$s^{\\texttt{Na}}$ - sodium coupling efficiency, [(photons m$^{2}$ )/(s W\r\natom)].\r\n\\\\\r\n\r\n$C^{\\texttt{Na}}$ - sodium abundance, [atoms/m$^2$].\r\n\\\\\r\n\r\n$\\lambda$ - wavelength, [m].\r\n\\\\\r\n\r\n$k = \\frac{2 \\pi}{\\lambda}$ - wave number, [rad/m].\r\n\r\n\\subsection{LGS propagation geometry}\r\n\\label{sec:lgs-geometry}\r\n\r\nGeometry of the LGS propagation problem is presented on Fig.\r\n\\ref{fig:lgs-geom}. The parameters describing the problem are chosen to 1) be\r\nclose to the ones directly measurable on real telescope, 2) be able to\r\ndescribe quite general situation.\r\n\r\n\\begin{figure}[htp]\r\n\\begin{center}\r\n \\includegraphics[width = 0.7\\textwidth]{LGS.png}\r\n\\end{center}\r\n\\caption{Geometry of laser guide star propagation to the telescope entrance\r\npupil.}\r\n\\label{fig:lgs-geom}\r\n\\end{figure}\r\n\r\nThree coordinate systems are involved:\r\n\\begin{enumerate}\r\n\t\\item Global or $g$-system is the Cartesian coordinate system with respect\r\n\tto which all other coordinate systems are defined. The orientation pair\r\n\t$(\\bm{o},\\mathcal{R})_{g}^{0}$ for this system is just ($\\bm{0},\\mathcal{I}$).\r\n\t\\item Telescope or $t$-system is the local Cartesian coordinate system\r\n\trotating with respect to the $g$-system such that the $t$-system $z$-axis is\r\n\talways along the telescope optical axis. The orientation pair\r\n\t$(\\bm{o},\\mathcal{R})_{t}^{g}$ for this system describes the telescope\r\n\tpointing. If we assume that at zenith pointing the $t$-system coincides with\r\n\tthe $g$-system, then \\\\\r\n\t\\begin{equation} \\label{eq:t-origin}\r\n\t\t\\bm{o}^{g}_{t} = \\bm{o}^{0}_{g} = \\bm{0},\r\n\t\\end{equation}\r\n\t\\begin{equation} \\label{eq:t-rotation}\r\n\t\t\\mathcal{R}^{g}_{t} = \\texttt{Eu}(\\alpha^{g}_{t},\\beta^{g}_{t},0),\r\n\t\\end{equation}\r\n\twhere Euler angles $\\alpha^{g}_{t},\\beta^{g}_{t}$ have meaning of the\r\n\ttelescope azimuth and zenith angles measured with respect to the g-system\r\n\t(note the $g$ superscript). The standard Euler rotation is\r\n\t\\begin{equation} \\label{Euler}\r\n\t\t\\texttt{Eu}(\\alpha,\\beta,\\gamma) = \\mathcal{A}_{z}(\\alpha)\r\n\t\t                                   \\mathcal{A}_{y}(\\beta)\r\n\t\t                                   \\mathcal{A}_{z}(\\gamma),\r\n\t\\end{equation}\r\n\t$$ \\mathcal{A}_{z}(\\alpha) = \\left[\r\n     \\begin{array}{crc}\r\n\t     \\cos{\\alpha} & -\\sin{\\alpha} & 0 \\\\\r\n\t     \\sin{\\alpha} & \\cos{\\alpha} & 0 \\\\\r\n\t     0 & 0 & 1 \\\\\r\n\t\t \\end{array} \\right],\r\n\t$$\r\n\t$$ \\mathcal{A}_{y}(\\beta) = \\left[\r\n     \\begin{array}{rcc}\r\n\t     \\cos{\\beta} & 0 & \\sin{\\beta} \\\\\r\n\t     0 & 1 & 0 \\\\\r\n\t     -\\sin{\\beta} & 0 & \\cos{\\beta} \\\\\r\n\t\t \\end{array} \\right].\r\n\t$$\r\n\tCoordinates of point $p$ in the entrance pupil given in $t$-system are\r\n\t$[x,y,0]_{p}^{t} = \\bm{r}_{p}^{t}$.\r\n\t\\item Laser launch telescope or $l$-system is a local Cartesian coordinate\r\n\tsystem chosen such that its $z$-axis is always along the optical axis of the\r\n\tLLT. This system is naturally defined with respect to the $t$-system because\r\n\tthe LLT is mounted on the moving main telescope mount:\r\n\t\\begin{equation} \\label{eq:l-system}\r\n\t\t(\\bm{o},\\mathcal{R})_{l}^{t} = ([x,y,0]_{l}^{t},\r\n                                 \\texttt{Eu}(\\alpha_{l}^{t},\\beta_{l}^{t},0),\r\n\t\\end{equation}\r\n\twhere $[x,y,0]_{l}^{t} = \\bm{r}_{l}^{t}$ are the $l^{th}$ LLT location in\r\n\t$t$-system (pupil\r\n\tcoordinates), $\\alpha_{l}^{t},\\beta_{l}^{t}$ are the azimuth and zenith\r\n\tangles of the LLT orientation with respect to the main telescope optical\r\n\taxis. Note that, for simplicity, we count one LGS per one LLT. In reality\r\n\tone LLT of GMT will generate a pair of LGSs. To account for this we simply\r\n\tassume that there are two differently oriented virtual LLTs at the location\r\n\tof one real LLT.\r\n\r\n\tThe LGS is modeled as a combination of the point sources (PSR) distributed\r\n\twithin the \\texttt{Na} layer. Coordinates\r\n\t$\\bm{r}_{li}^{l}, \\,\\, l =\r\n\t1,...,\\#LLT, \\,\\, i=1,...,\\#PSR$ of the sources are given in the $l$-system.\r\n\\end{enumerate}\r\n\r\nGiven orientation pair $(\\bm{o},\\mathcal{R})_{b}^{a}$ defining $b$-system\r\ncoordinates with respect to $a$-system coordinates, the transformation of\r\ncoordinates written in $b$-system into the same coordinates written in\r\n$a$-system is the \\emph{direct affine transform}: \\index{affine transform}\r\n\\begin{equation} \\label{eq:direct-affine}\r\n\t\\bm{r}^{a} = \\mathcal{R}_{b}^{a} \\bm{r}^{b} + \\bm{o}_{b}^{a}.\r\n\\end{equation}\r\nCorrespondingly, the \\emph{inverse affine transform} gives the coordinates\r\nwritten in $b$-system from the ones written in $a$-system:\r\n\\begin{equation} \\label{eq:inverse-affine}\r\n\t\\bm{r}^{b} = (\\mathcal{R}_{b}^{a})^{T} (\\bm{r}^{a} - \\bm{o}_{b}^{a}).\r\n\\end{equation}\r\n\r\n\r\n\\subsection{Finding LGS spot elongation and orientation on the detector}\r\n\\label{sec:elongation-orientation}\r\n\r\nAn important geometrical calculation needed for the theoretical evaluation of\r\nthe detector noise covariance matrix is to find the parameters of the\r\nelongated LGS image in the detector focal plane.\r\n\r\nLet a LGS is produced as a light-emitting column of length $L$ inside the\r\n\\texttt{Na} layer. We need to find the length of its image in the\r\nShack-Hartmann WFS focal plane behind a lenslet with location $\\bm{r}^{t}_{l}$\r\n(in the $t$-system)\r\nprojected on the telescope entrance pupil and the image orientation with\r\nrespect to the detector pixel grid. Let the beginning and end of the LGS light\r\ncolumn have $t$-system coordinates $\\bm{r}^{t}_{1}$ and $\\bm{r}^{T}_{2}$,\r\nrespectively. Consider vectors $\\bm{r}^{t}_{1t} =\r\n\\bm{r}^{t}_{1}-\\bm{r}^{t}_{l}$ and $\\bm{r}^{t}_{2t} =\r\n\\bm{r}^{t}_{2}-\\bm{r}^{t}_{l}$. Then, up to a scaling factor and a possible\r\nmirror flip, the LGS\r\nimage on the detector is determined by a $(\\varepsilon,\\theta)$-pair, where\r\n$\\varepsilon$ is the angular size of the LGS column as seen from the lenslet\r\ncenter $\\bm{r}_{l}^{t}$, that is, the angle between vectors $\\bm{r}^{t}_{1l}$\r\nand $\\bm{r}^{t}_{2l}$, and $\\theta$ is the angle\r\nbetween the $t$-system x-axis and the line of intersection of the $t$-system\r\nxy-plane and the plane made by vectors $\\bm{r}^{t}_{1l}$ and $\\bm{r}^{t}_{2l}$.\r\nVectors $\\bm{r}_{1,2}$ are most conveniently definable in the $l$-system,\r\nwhere\r\n\\begin{equation} \\label{eq:lgs-ends-l}\r\n\t\\bm{r}^{l}_{1,2} = [0 \\, 0 \\, z^{l}_{1,2}]^{T}.\r\n\\end{equation}\r\nThe transformation to $t$-system is\r\n\\begin{equation} \\label{eq:lgs-ends-t}\r\n\t\\bm{r}^{t}_{1,2} = \\mathcal{R}^{t}_{l} \\bm{r}^{l}_{1,2} + \\bm{o}^{t}_{l}.\r\n\\end{equation}\r\nUsing scalar and vector products we get\r\n\\begin{eqnarray} \\label{eq:epsilon-theta}\r\n\t\\hat{\\bm{r}}^{t}_{1,2} = \\frac{\\bm{r}^{t}_{1,2}}{|\\bm{r}^{t}_{1,2}|}, \\\\\r\n\t\\cos \\varepsilon = \\hat{\\bm{r}}^{t}_{1} \\cdot \\hat{\\bm{r}}^{t}_{2}, \\\\\r\n\t\\bm{p}^{t}_{12} = \\hat{\\bm{r}}^{t}_{1} \\times \\hat{\\bm{r}}^{t}_{2}, \\\\\r\n\t\\sin \\varepsilon = |\\bm{p}^{t}_{12}|, \\\\\r\n\t\\hat{\\bm{p}}^{t}_{12} = \\frac{\\bm{p}^{t}_{12}}{\\sin \\varepsilon}, \\\\\r\n\t\\hat{\\bm{x}}^{t} = [1 \\, 0 \\, 0]^{T}, \\\\\r\n\t\\cos \\theta = \\hat{\\bm{x}}^{t} \\cdot \\hat{\\bm{p}}^{t}_{12}, \\\\\r\n  \\sin \\theta = | \\hat{\\bm{x}}^{t} \\times \\hat{\\bm{p}}^{t}_{12} |.\r\n\\end{eqnarray}\r\nNote that, since $\\varepsilon$ is very small, in order to preserve accuracy,\r\nall calculations need to be done in double precision.\r\n\r\n\\subsection{Free-space propagation from LGS to telescope entrance pupil}\r\n\\label{sec:free-space-propagation}\r\n\r\nThe electric field $E$ from the LGS on the telescope entrance pupil is the\r\nsuperposition of spherical waves emitted from each point source (PS) that\r\nmakes the elongated laser guide star spot in the \\texttt{Na} layer:\r\n\\begin{equation} \\label{eq:spherical-superposition}\r\n\tE_{lp} = \\sum_{i=1}^{\\#PSR} w_{li} \\frac{\\exp(i k r_{lip})}{r_{lip}},\r\n\\end{equation}\r\nwhere $w_{li}$ is the weight describing relative intensity of the $i^{th}$ PS\r\nof the $l^{th}$ LGS, $r_{lip}$ is the distance from the $i^{th}$ PS\r\nof the $l^{th}$ LGS to $p^{th}$ point in the telescope entrance pupil. This\r\ndistance is easily found through the affine transform:\r\n\\begin{equation} \\label{eq:source-to-pupil}\r\n\t\\bm{r}_{li}^{t} = \\mathcal{R}_{l}^{t} \\bm{r}_{li}^{l} + \\bm{o}_{l}^{t},\r\n\\end{equation}\r\n$$ r_{lip} = |\\bm{r}_{li}^{t} - \\bm{r}_{p}^{t}|. $$\r\n\r\n\\subsection{Geometrical optics propagation through atmosphere}\r\n\\label{sec:geom-propagation}\r\n\r\nThe turbulent atmosphere on the way between an LGS and a telescope is modeled\r\nas a set of infinitely thin random \\emph{phase screens} (PS)\r\n\\index{phase screen}. Because of small phase perturbations caused by each\r\nlayer and because the typical scale of turbulence is much larger than a\r\nwavelength the geometrical optics model for propagation through the layers is\r\nassumed. The model is based on the following postulates:\r\n\\begin{itemize}\r\n\t\\item The propagation of the electromagnetic waves is treated as propagation\r\n\tof \\emph{rays} that are normals to the constant phase surfaces of the waves,\r\n\tthe \\emph{wavefronts}. \\index{ray} \\index{wavefront}\r\n\t\\item Rays are always straight: the phase screens are weak enough for not\r\n\tto change direction of rays, they only add a path difference\r\n\t$\\delta r_{lip,j}$:\r\n\t\\begin{equation} \\label{eq:path-diff}\r\n\t\t\\delta r_{lip,j} = \\phi_{lip,j}/k, \\,\\, j = 1,...,\\#PS,\r\n\t\\end{equation}\r\n\t$$ r_{lip}^{turb} = r_{lip}^{free} + \\sum_{j=1}^{\\#PS} \\delta r_{lip,j}. $$\r\n\twhere $\\phi_{lip,j}$ is the phase on the $j^{th}$ turbulent layer\r\n\tintersected by a ray emitting from $i^{th}$ point source of $l^{th}$ LGS\r\n\ttowards $p^{th}$ point in the entrance pupil. So, the electric field\r\n\ton the entrance pupil will be\r\n\t\\begin{equation} \\label{eq:spherical-superposition-turb}\r\n\t\tE^{turb}_{lp} =\r\n\t\t\\sum_{i=1}^{\\#PSR} w_{li}\r\n\t\t\\frac{\\exp(i k r_{lip}^{turb})}{r_{lip}^{free}}.\r\n\t\\end{equation}\r\n\\end{itemize}\r\n\r\nThus, it is necessary to find the intersection of a ray with a turbulent layer.\r\n\r\n\\subsubsection{Turbulence layers are perpendicular to the telescope optical\r\naxis.}\r\n\r\nAssume that the turbulence layers are chosen such that they are perpendicular\r\nto the telescope optical axis regardless of the pointing.\r\nIn this case the turbulence strength depends on the azimuth angle\r\n$\\beta_{t}^{g}$, namely,\r\n\\begin{equation} \\label{eq:turb-vs-beta}\r\n\tC_{n}^{2} (\\beta_{t}^{g}) = \\frac{C_{n}^{2}(0)} {\\cos \\beta_{t}^{g}}.\r\n\\end{equation}\r\n\r\nSimple geometrical analysis gives for the\r\nrelationship between the pupil and turbulence layer coordinates:\r\n\\begin{equation} \\label{eq:pupil-to-layer}\r\n  \\bm{r}^{t}_{lip,j} =\r\n  \\frac{h_{j}}{z^{t}_{li}} \\bm{r}_{p}^{t} +\r\n  (1-\\frac{h_{j}}{z^{t}_{li}})\r\n  \\left[\r\n  \\begin{array}{c}\r\n\t  x^{t}_{li} \\\\\r\n\t  y^{t}_{li} \\\\\r\n\t  0\r\n\t\\end{array}\r\n  \\right], \\,\\,\r\n  \\bm{r}^{t}_{li} =\r\n  \\left[\r\n  \\begin{array}{c}\r\n\t  x^{t}_{li} \\\\\r\n\t  y^{t}_{li} \\\\\r\n\t  z^{t}_{li}\r\n\t\\end{array}\r\n  \\right],\r\n\\end{equation}\r\nwhere $h_{j}$ is distance between the telescope and $j^{th}$ phase screen\r\nalong the telescope optical axis,\r\n$\\bm{r}^{t}_{lip,j}$ are xyz-coordinates in $t$-system of an\r\nintersection point on phase screen $j$ for a ray emitting from $i^{th}$ point\r\nsource of $l^{th}$ LGS with $t$-coordinates $\\bm{r}^{t}_{li}$ and\r\npassing through $p^{th}$ point in telescope entrance pupil with $t$-coordinates\r\n$\\bm{r}^{t}_{p}$. For the source at infinity (a natural guide star or a\r\nscientific target) Eq. (\\ref{eq:pupil-to-layer}) simplifies to\r\n\\begin{equation} \\label{eq:pupil-to-layer-inf}\r\n\t\\bm{r}^{t}_{lip,j} =\r\n\t\\left[\r\n\t\\begin{array}{c}\r\n\t\t\\cos \\alpha^{t}_{li} \\\\\r\n\t\t\\sin \\alpha^{t}_{li} \\\\\r\n\t\t0 \\\\\r\n\t\\end{array}\r\n\t\\right] h_{j} \\tan \\beta^{t}_{li} + \\bm{r}^{t}_{p},\r\n\\end{equation}\r\nwhere $(\\alpha,\\beta)^{t}_{li}$ are the angular coordinates (first and second\r\nEuler angles) of the light source. Note that in both cases the position of the\r\nray intersection with a layer can be written as $ (a \\bm{r}_{p}^{t} +\r\n\\bm{b}^{t}_{li}) $.\r\n\r\n\\subsubsection{Turbulence layers are parallel to the ground.}\r\n\r\nAssume that the layers are parallel to the ground, i.e. perpendicular to the\r\n$g$-system's $z$-axis, and have altitudes $h_{j}, \\,\\, j = 1,...,\\#PS$. In\r\nthis case the turbulence $C_{n}^{2}$ profile is not altered with the zenith\r\nangle. Direct ray tracing technique is used to find intersection with a\r\nturbulence layer.\r\n\r\nCoordinates of a ray can be described through the parametric equation:\r\n\\begin{equation} \\label{eq:ray-equation}\r\n\t\\bm{r}(t) = \\bm{i} t + \\bm{r}_{0},\r\n\\end{equation}\r\nwhere $\\bm{r}_{0}$ is the ray origin (position of the light-emitting source),\r\n$\\bm{i}$, $|\\bm{i}| = 1$ is the ray\r\ndirection vector, $t$ is the ray path length. In the case of propagation path\r\nshown of Fig. \\ref{fig:lgs-geom}\r\n$$ \\bm{r}^{l}_{0} = \\bm{r}^{l}_{li}, $$\r\nwhere $\\bm{r}_{0}$ is given in $l$-system,\r\n$$ \\bm{i}^{t} = \\frac{\\bm{r}^{t}_{p} - \\bm{r}^{t}_{li}}\r\n                 {|\\bm{r}^{t}_{p} - \\bm{r}^{t}_{li}|}, $$\r\nwhere $\\bm{i}$ is given in $t$-system. Since the turbulent layers are most\r\nconveniently defined in the $g$-system, the ray coordinates need to be\r\ntransformed into $g$-system:\r\n\\begin{equation} \\label{eq:ray-transform}\r\n\t\\bm{r}^{t}_{0} = \\mathcal{R}_{l}^{t} \\bm{r}^{l}_{0} + \\bm{o}_{l}^{t},\r\n\\end{equation}\r\n$$ \\bm{i}^{t} = \\frac{\\bm{r}^{t}_{p} - \\bm{r}^{t}_{0}}\r\n                 {|\\bm{r}^{t}_{p} - \\bm{r}^{t}_{0}|}, $$\r\n$$ \\bm{r}^{g}_{0} = \\mathcal{R}_{t}^{g} \\bm{r}^{t}_{0} + \\bm{o}_{t}^{g}, $$\r\n$$ \\bm{i}^{g} = \\mathcal{R}_{t}^{g} \\bm{i}^{t}. $$\r\nThe coordinates of ray intersection with turbulent layer are found by equating\r\n$z$-coordinate of a ray to the layer altitude:\r\n\\begin{equation} \\label{eq:layer-intersection}\r\n\tt = \\frac{h_{j}-r^{g}_{0z}}{i^{g}_{z}},\r\n\\end{equation}\r\n$$ \\bm{r}^{g}_{lip,j} = \\bm{i}^{g} t + \\bm{r}_{0}^{g}, $$\r\nwhere $x$- and $y$-coordinates of the $\\bm{r}^{g}_{lip,j}$-vector are used to\r\nfind the phase $\\phi^{turb}(\\bm{r}^{g}_{lip,j}) = k \\delta r^{turb}_{lip,j}\r\n(\\bm{r}^{g}_{lip,j})$ on the phase\r\nscreen corresponding to the ray intersection and substitute it to Eq.\r\n(\\ref{eq:spherical-superposition-turb}).\r\n\r\n\r\n\\subsection{Point source distribution in the LGS}\r\n\\label{sec:point-distribution}\r\nTBC\r\n\r\nThe positions $\\bm{r}^{l}_{li}$ and weights $w_{li}$ of point sources making\r\neach LGS are found from superposition of the intensity distribution of the laser\r\nradiation forward-propagated through atmosphere to the \\texttt{Na} layer and\r\nthe vertical distribution of the \\texttt{Na} density. A possible operation\r\nflow for defining the LGS distribution is the following:\r\n\\begin{enumerate}\r\n\t\\item Define a 3D mesh covering a part of the \\texttt{Na} layer penetrated\r\n\tby the laser radiation. Each cell of this mesh is an elementary volume for\r\n\twhich amount of laser flux is assigned.\r\n\t\\item Center of each 3D mesh cell is the candidate location of the LGS point\r\n\tsource. If flux through the cell exceeds a threshold, a point source is\r\n\tassigned for this cell.\r\n\t\\item For each mesh cell for which a point source is assigned multiply the\r\n\tcell flux by \\texttt{Na} density at the cell center taken from the\r\n\t\\texttt{Na} vertical profile. Find relative distribution of the return flux,\r\n\twhich is the source weights $\\{ w_{li} \\}_{i=1}^{\\#PSR}$:\r\n\t\\begin{equation} \\label{eq:source-weights}\r\n\t\tw_{li} = \\frac{ \\Phi_{li} C^{\\texttt{Na}}_{li} }\r\n\t\t               { \\sum_{i=1}^{\\#PSR} \\Phi_{li} C^{\\texttt{Na}}_{li} },\r\n\t\t           \\,\\, i = 1, ... , \\#PSR\r\n\t\\end{equation}\r\n\twhere $\\{ \\Phi_{li} \\}_{i=1}^{\\#PSR}$ are the cell fluxes,\r\n\t$\\{ C^{\\texttt{Na}}_{li} \\}_{i=1}^{\\#PSR}$ are the \\texttt{Na} abundances at\r\n\tthe cell locations.\r\n\\end{enumerate}\r\n\r\n\\subsection{Return flux in the entrance pupil}\r\n\\label{sec:return-flux}\r\n\r\nThe photon flux returning from each LGS point source is considered uniformly\r\ndistributed over the spherical surface of the wavefront. Since the solid angle\r\n$\\Omega$ at which the telescope is seen from the source is typically very\r\nsmall, the variation of $r^{free}_{lip}$ in the denominator of Eq.\r\n(\\ref{eq:spherical-superposition-turb}) over the pupil can be neglected. Thus,\r\nthe fraction of energy emitting from a point source that passes through the\r\ntelescope entrance pupil is\r\n\\begin{equation} \\label{eq:energy-fraction}\r\n\t\\frac{\\Omega}{4 \\pi} = \\frac{1}{4 \\pi}\r\n\t\\frac{ A_{p} }\r\n\t     { |\\bm{r}^{t}_{li}|^{2} \\cos^{2} \\beta^{t}_{li} },\r\n\\end{equation}\r\nwhere $A_{p}$ is the pupil area, $|\\bm{r}^{t}_{li}|$ is the distance from\r\npupil center to the point source, $\\beta^{t}_{li}$ is the angle between the\r\ntelescope optical axis and the direction to the point source as seen from the\r\npupil center,\r\n\\begin{equation} \\label{eq:angle-to-source}\r\n\t\\cos \\beta^{t}_{li} = \\left( \\frac{\\bm{r}^{t}_{li}}\r\n\t                                  {|\\bm{r}^{t}_{li}|} \\right)_{z}.\r\n\\end{equation}\r\nThe photon flux into the entrance pupil from a point source is\r\n\\begin{equation} \\label{eq:return-flux}\r\n\t\\Phi_{li} = \\tau T_{AOS} \\frac{T_{ATM}}{\\cos{\\beta^{g}_{li}}}\r\n\t            s^{\\texttt{Na}} C^{\\texttt{Na}}\r\n\t            P_{l} w_{li}\r\n\t            \\frac{\\Omega}{4 \\pi}, \\,\\, [\\texttt{photons}],\r\n\\end{equation}\r\nwhere \\\\\r\n\\begin{tabular}{lcll}\r\n\t&&& \\\\\r\n  Exposure time & : & $\\tau$ & = 2 ms, \\\\\r\n  Atmosphere transmittance & : & $T_{ATM}$ & = 0.89, \\\\\r\n  AO system transmittance & : & $T_{AOS}$ & = 0.448, \\\\\r\n  Sodium coupling efficiency & : & $s^{\\texttt{Na}}$ &\r\n  = 130 (photons m$^{2}$ )/(s W atom), \\\\\r\n  Sodium abundance & : & $C^{\\texttt{Na}}$ & = $2.1\\times10^{13}$ atoms/m$^2$,\\\\\r\n\tLaser power per LGS & : & $P_{l}$ & = 20 W, \\\\\r\n\t&&& \\\\\r\n\\end{tabular} \\\\\r\n$\\beta^{g}_{li}$ is the angle between zenith direction and the point source\r\ndirection as viewed from the entrance pupil center.\r\n\r\nThe fluxes from all point sources are later summed on the detector.", "meta": {"hexsha": "1368b64fb5e70e06b57d13e335364952c2c0630b", "size": 20360, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "_docGMT/LGS.tex", "max_stars_repo_name": "cmcorreia/oomao", "max_stars_repo_head_hexsha": "59787859283e89cdb8c2ee88388198f283be9abb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-10-01T18:30:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T01:19:40.000Z", "max_issues_repo_path": "_docGMT/LGS.tex", "max_issues_repo_name": "cmcorreia/oomao", "max_issues_repo_head_hexsha": "59787859283e89cdb8c2ee88388198f283be9abb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-30T17:22:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-30T17:22:35.000Z", "max_forks_repo_path": "_docGMT/LGS.tex", "max_forks_repo_name": "cmcorreia/oomao", "max_forks_repo_head_hexsha": "59787859283e89cdb8c2ee88388198f283be9abb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.5042735043, "max_line_length": 81, "alphanum_fraction": 0.6541257367, "num_tokens": 6584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3354602807656564}}
{"text": "\\chapter{Summary}\n\\label{summary}\n\n\\section{Project Summary}\nIn this thesis, the computational fluid dynamics toolbox OpenFOAM was used to simulate detonation waves within a square tube. Different solvers were tested until the hybrid solver \\verb|rhoReactingCentralFoam| was decided as best due to the use of the Kurganov and Tadmor central schemes which reproduce compressible, high speed flow with good accuracy. Different ignition methods were tested, and gradient ignition was found to produce results with the least noise. Next, the chemistry was tested for sensitivity and then matched to Chapman-Jouguet targets and the automatic time stepping algorithm was tested to determine how large the CFL number could be allowed to increase before numerical ringing and noise reduced solution accuracy. A value was found that agreed with similar detonation modeling published works. Static computational meshes were then compared to determine the required mesh resolution to resolve shock and detonation structures. The threshold for resolving finer flow field structures as well as the von Neumann spike was determined, as well as the threshold for overall convergence and detonation wave shape integrity. Detonation cells were shown to be able to form with the solver. Adaptive meshing parameters were then explored, namely refinement levels, buffer layers, and refinement/unrefinement bounds. It was shown that refinement levels and the lower refinement bound are exponential in expense and the buffer layers are linear in expense. No more than 4 buffer layers led to a significant increase in solution accuracy, and a normalized pressure gradient lower bound smaller than 0.05 would significantly increase computational cost. Refinement levels started to converge and reproduce the von Neumann spike for 4 and more levels of refinement for the 250-40-1 mesh, which corresponds to a mesh resolution of 4000-640-1 mesh, where the von Neumann spike began to resolve in the static mesh. Lastly, some AMR simulations were compared to static mesh simulations. It was found that using AMR one could potentially reduce the computational expense by 85\\% matching a static profile nearly exactly, and reduce computational expense by over 96\\% by allowing the detonation spacial position to vary while still targeting peak solution values. \n\n\n\n\\section{Next Steps}\n\\subsection{Areas to Improve}\nIncreased knowledge as to the effects of AMR in three-dimensional simulations versus the use in two-dimensional simulations may be valuable. Two-dimensional simulations were the primary target of this thesis work due to a balance of feasibility in computational time as well as sufficient expense to justify and show the benefits of AMR. \n\nAn exploration into different tracking parameters other than the normalized gradient of pressure, pressure, temperature, and velocity is useful as a more efficient parameter (i.e., determining a parameter that better describes where refinement is absolutely necessary) may further reduce computational cost. While pressure, temperature, and velocity were all tested during the thesis work, tuning them was found to be more difficult than the normalized pressure gradient. Additionally, combining parameters together may produce smarter AMR ``active'' periods as the refinement is not free and can be potentially more expensive than static mesh cases if not carefully set up. \n\nBetter load balancing in parallel computing in OpenFOAM could use improvement. Currently, intelligent setup and awareness of the detonation itself is required to ensure that the AMR does not offset considerable computational load onto one processor or another as the detonation moves through the domain. For detonation tubes, this is not a problem as long decompositions can be used to balance the processor load. However, for simulations of RDEs or rocket engine combustion chambers that can be inherently unpredictable, smart domain partitioning is difficult. Like adaptive meshing, an adaptive domain decomposition may assist with improving load balancing in these scenarios. \n\nFurther characterization as to how the base mesh affects the solution should be done. While this is seemingly obvious as increased base resolutions will help give a better solution, the AMR can unrefine back to the base resolution, so if large turbulent structures or other larger structures want to be resolved still after adaptive unrefinement, the base resolution needs to be considered. \n\nThe AMR routines in parallel can be unstable. This does not seem to affect the solution, but it is not feasible to ``babysit'' a simulation and restart it if it crashes. The crashes seem to be due to AMR cells not getting communicated correctly with MPI, leading to a disproportionate number of cell faces shared at domain-decomposed boundaries where the MPI communication is occurring. Further work here is needed, and it will likely improve as development continues on the AMR routines. \n\n\\subsection{Future Work}\nFurther work in detonation modeling in the context of RDEs is the logical next step. This technology is still emerging and having better characterization of the highly chaotic flow field inside the engine will guide better engineering design and analysis towards improved propulsion technology. AMR applied to RDE simulation in OpenFOAM will reduce computational cost, especially for three-dimensional RDE simulations. \n\nDeflagration to detonation transition modeling is another area to be explored with this solver. Characterizing this will allow the solver to be used in a wider set of scenarios, where sudden detonation of reactants is a potential concern. \n\nPersonally, I think application of AMR simulating the high-speed and chaotic environments of rocket engine combustion chambers in OpenFOAM would be really interesting. Combustion instability within these environments is still very hard to characterize and an ongoing topic of research and development within industry. \n\n\\section{Impact}\nThe targeted impact area for this research is the field of detonation modeling, with consideration for future use in RDE modeling and other propulsion systems that are expensive computationally. By utilizing the computational tools developed, tested, and validated in this project, existing research in detonation modeling using the computational fluid dynamics toolbox OpenFOAM can be performed more quickly or to a greater extent. Specifically, I showed:\n\\begin{itemize}\n\\item The solver \\verb|rhoReactingFoam| and \\verb|rhoCentralFoam| themselves are unable to model detonations accurately, or at all;\n\\item The solver \\verb|rhoReactingCentralFoam| is able to simulate detonations;\n\\item How to simulate detonations in OpenFOAM and what the parameters will do to the solution;\n\\item Detonation cells can be modeled with \\texttt{rhoReactingCentralFoam};\n\\item Results are sensitive to Arrhenius pre-exponential factor order, and care must be taken such that the shock does not decouple from the flame;\n\\item CFL number needs to be lower than typical high-speed flows due to the reactive nature of detonations;\n\\item How fine PDE/detonation tube meshes must be to resolve fine detonation and shock structure;\n\\item Certain AMR parameters have different effects computationally, and tuning certain parameters over others will optimize the overall cell count by placing refinement cells where they are truly needed;\n\\item Adaptive mesh refinement can decrease computation cost for detonation modeling up to 96\\% while remaining true to the static mesh resolution results. \n\\end{itemize}\n\n", "meta": {"hexsha": "34ea568de7b37bf1f25e0483ba77d0eeed0c4646", "size": 7579, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/chapter4.tex", "max_stars_repo_name": "duncanam/thesis", "max_stars_repo_head_hexsha": "95e0e590edec03672667f8d302d12fa4a222f258", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-05-05T17:55:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T13:37:02.000Z", "max_issues_repo_path": "doc/chapter4.tex", "max_issues_repo_name": "duncanam/thesis", "max_issues_repo_head_hexsha": "95e0e590edec03672667f8d302d12fa4a222f258", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/chapter4.tex", "max_forks_repo_name": "duncanam/thesis", "max_forks_repo_head_hexsha": "95e0e590edec03672667f8d302d12fa4a222f258", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-18T17:54:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-18T17:54:43.000Z", "avg_line_length": 180.4523809524, "max_line_length": 2270, "alphanum_fraction": 0.8264942605, "num_tokens": 1446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.3354602807656564}}
{"text": "\\documentclass[12]{scrartcl}\n\\usepackage{amssymb,amsmath,gensymb,dsfont,calc,multicol,fullpage}\n\\makeatletter\n\\newcommand\\Aboxed[1]{\n   \\@Aboxed#1\\ENDDNE}\n\\def\\@Aboxed#1&#2\\ENDDNE{%\n   &\n   \\settowidth\\@tempdima{$\\displaystyle#1{}$}\n   \\setlength\\@tempdima{\\@tempdima+\\fboxsep+\\fboxrule}\n   \\kern-\\@tempdima\n   \\boxed{#1#2}\n}\n\\makeatother\n\n\\begin{document}\n\n\\title{Homework 25, Section 4.7: 1, 4, 7, 11, 14}\n\\author{Alex Gordon}\n\\date{\\today}\n\\maketitle\n\\section*{Homework}\n\\subsection*{1.}\n$\\begin{bmatrix}  6 & 9 \\\\ -2 & -4  \\end{bmatrix} $\n\\subsection*{4.}\n(i)\n\\subsection*{7.}\nYes and no. Column A is a four dimensional subspace of $R^4$, it coincides with $R^4$. Since the null space cannot be $R^3$ (Null A has 7 entries) Nul A must be a 3 dimensional subspace of $R^7$. \n\\subsection*{11.}\n2\n\\subsection*{14. A)}\n$A = \\begin{bmatrix}  1 & 2 & 1 \\\\ 0 & 1 & 2 \\\\ -3 & -5 & 0  \\end{bmatrix} $\n\\subsection*{14. B)}\nSolving $ \\begin{bmatrix}  x_1 \\\\ x_2 \\\\ x_3  \\end{bmatrix} $ gets us $ \\begin{bmatrix}  0 \\\\ 0 \\\\ 1  \\end{bmatrix} $ and from that we can obtain $t^2 = 3(1 - 3t^2) - 2(2 + t - 5t^2) + ( 1 + 2t)$\n\n\n\n\\end{document}", "meta": {"hexsha": "ee296bd8fd02df7e10355bcfbbf81d97950097c0", "size": 1130, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "LinearAlgebra/Homework25.tex", "max_stars_repo_name": "alexggordon/latex", "max_stars_repo_head_hexsha": "7dd945f33490e6585e26cff39d9cf6ad8f582a0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LinearAlgebra/Homework25.tex", "max_issues_repo_name": "alexggordon/latex", "max_issues_repo_head_hexsha": "7dd945f33490e6585e26cff39d9cf6ad8f582a0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LinearAlgebra/Homework25.tex", "max_forks_repo_name": "alexggordon/latex", "max_forks_repo_head_hexsha": "7dd945f33490e6585e26cff39d9cf6ad8f582a0e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5405405405, "max_line_length": 196, "alphanum_fraction": 0.6389380531, "num_tokens": 492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.3354602807656564}}
{"text": "In games of imperfect information, the players are not always sure of the current state of the game. That is, a state may be indistinguishable from other states for some players. This is a classic application of a possible worlds model. In this section based on \\cite{benthem2001a}, we are going to combine game trees and possible worlds models in order to model games of imperfect information.\n\n% { \\color{red} I don't think bisimulations are important in this article. This is a introductory article on the connections between game theory and epistemic logic. Bisimulations are a more advanced tool for reducing the size of your games so that they are easier to handle. Hence, they are mostly a tool for gaining efficiency and efficiency is not in introductory topic. I would rather describe how to compute the Nash equilibrium of the Liar's dice example. }\n\n\\subsection{Perfect information game trees} \\label{seq:perfect-information}\n\n%{ \\color{red} These is possibly too much theory in this subsection but I wasn't quite sure where this subsection was headed when I started. }\n\nFirst, we consider two-player games of perfect information: Given a set $ \\atomicprops $ of atomic propositions, a game tree $ M = (S, \\{ R_{a} : a \\in A \\}, V) $ for such a game is a set $ S $ of states, a set containing one binary relation $ R_{a} \\subseteq (S \\times S) $ for each action $ a $ in the set $ A $ of all actions, and a valuation function $ V : S \\rightarrow 2^{\\atomicprops} $ \\cite{benthem2001a}. The actions are also called moves. The states are partitioned among the players, so that each state is controlled by exactly one player. We let $ \\atomicprops $ contain the propositions $ \\turn_{i} $ and $ \\win_{i} $ for each player $ i \\in I $ in the set of players $ I $. We define $ V $ such that $ \\turn_{i} $ holds of a state $ s $ if and only if player $ i $ controls $ s $. Also, we define $ V $ such that $ \\win_{i} $ holds of a state $ s $ if and only if player $ i $ wins at $ s $. Finally, we let $ \\leaf $ be true of exactly the leaves of $ M $.\n\nIn order to express properties of a state in a game $ M = (S, \\{ R_{a} : a \\in A \\}, V) $, we introduce a modal language with the following syntax, where $ a \\in A $ is any action and $ p \\in \\atomicprops $ is any proposition:\n\\begin{align*}\n\\alpha &::= a \\barspace \\alpha_{1} \\cup \\alpha_{2} \\barspace \\alpha_{1} \\alpha_{2} \\barspace \\alpha^{\\ast} \\\\\n\\beta &::= \\langle \\alpha \\rangle \\barspace [\\alpha] \\barspace \\beta_{1} \\beta_{2} \\\\\n\\gamma &::= \\beta p\n\\end{align*}\nHere, $ \\alpha $ generates formulas describing sets of sequences of actions. The Kleene star denotes arbitrary finite iteration. The symbol $ \\beta $ generates modalities and $ \\gamma $ is the starting symbol. The expression $ \\langle \\alpha \\rangle \\phi $ denotes that $ \\phi $ holds in some state resulting from performing one of the action sequences of $ \\alpha $. The expression $ [\\alpha] \\phi $ denotes that $ \\phi $ holds in all states resulting from performing all action sequences of $ \\alpha $.\n\nA \\emph{strategy} $ \\sigma : S \\rightarrow A $ for player $ i $ is a partial function from a state $ s $ with $ \\turn_{i} $ to an action available from $ s $. If every action occurs at most once in the game tree, we can view a strategy as a set of actions. With this view, a \\emph{winning strategy} $ \\sigma $ for player $ i $ is one satisfying the following \\cite{benthem2001a}:\n\\begin{gather*}\n\\WIN_{i} \\leftrightarrow (\\leaf \\wedge \\win_{i}) \\vee (\\turn_{i} \\wedge \\langle A \\rangle \\WIN_{i}) \\vee (\\neg \\turn_{i} \\wedge [A] \\WIN_{i}) \\\\\n[A^{\\ast}](\\turn_{i} \\rightarrow \\langle \\sigma \\rangle \\WIN_{i})\n\\end{gather*}\nHere, we use the shorthand notation $ A $ for the $ \\alpha $-formula $ a_{1} \\cup a_{2} \\cup \\dots $ describing the choice between all possible actions $ a_{1}, a_{2}, \\dots $. The first formula expresses that a state $ s $ is winning for player $ i $, if 1) the game ends at $ s $ with player $ i $ as the winner, or if 2) player $ i $ has a move from $ s $ that leads him to a winning state, or if 3) the opponent has the turn but all her moves lead to states that are winning for player $ i $. The second formula expresses that from every state $ s $, if player $ i $ has the turn from $ s $, then the move described by the strategy leads to a winning state.\n\n\\subsubsection*{The powers of the players}\n\nWhat can we say about the outcomes that the players can force? Define $ \\forcing{i} X $ to be the proposition that player $ i $ has a strategy from state $ s $ in $ M $ whose resulting states are always in the set $ X $ of leaves. It is obvious that $ \\forcing{i} $ is closed under superset \\cite{benthem2001a}. Let this property be C1. It is also clear that if $ \\forcing{1} X $ and $ \\forcing{2} Y $, then $ X $ and $ Y $ must overlap \\cite{benthem2001a}. Otherwise, the players could force the game to end with inconsistent outcomes. Let this property be C2. Finally, games of perfect information are \\emph{determined} meaning that for any set of leaves, one of the players must have a forcing strategy \\cite{benthem2001a}. That is, if $ \\neg \\forcing{1} X $, then $ \\forcing{2} (S - X) $ and vice versa, if we swap player $ 1 $ and player $ 2 $. We use C3 to denote determinacy. \n\n%{ \\color{red} We need this subsection so that we can contrast with games of imperfect information in later subsections. We only need to describe the \\emph{the dynamic modal language}, if we want to write down concrete strategies for our example. }\n\n%\\begin{itemize} \\color{red}\n%\\item Formal definition of perfect-information game trees\n%\\item Formal definition of strategies in perfect-information games.\n%\\item Short introduction to outcomes and powers (C1, C2, and C3).\n%\\end{itemize}\n\n\\subsection{Imperfect information game trees}\n\nFor games of imperfect information, we extend the definition of game trees from \\secref{seq:perfect-information} with possibility relations describing the states that the players cannot tell apart. Hence, a game tree $ M = (S, \\{ R_{a} : a \\in A \\}, \\{ \\sim_{i} : i \\in I \\}, V) $ of a game of imperfect information contains a possibility relation $ \\sim_{i} $ for each of the players $ i $ in the set $ I $ of players.\n\nIn order to express properties of such games, we need to add the knowledge operators of epistemic logic to the modal logic defined in \\secref{seq:perfect-information}. This allows us to write expressions like $ K_{2} \\neg K_{1} (\\langle a \\cup b \\rangle \\win_{1}) $, which states that player $ 2 $ does not know that player $ 1 $ knows that at least one of the moves $ a $ and $ b $ leads to victory of player $ 1 $.\n\nThe introduction of uncertainty renders the above definition of a strategy troublesome. This definition allows player $ i $ to play move $ a_{1} $ from the state $ s_{1} $ and move $ a_{2} $ from the state $ s_{2} $, even in situations where player $ i $ cannot distinguish $ s_{1} $ and $ s_{2} $. To avoid this counterintuitive situation, we define \\emph{uniform strategies} to be strategies where player $ i $ plays the same move from two states, if these are indistinguishable to player $ i $.\n\nThe concept of a \\emph{winning strategy} also becomes less clear with the introduction of player uncertainty. Player $ i $ may play according to a strategy $ \\sigma $ that guarantees a win but player $ i $ may not be aware of this. Is this a winning strategy? In other words, should we define winning strategies in terms of the actual outcomes or in terms of the knowledge of the outcomes? \\cite{benthem2001a} suggests that the latter seems more natural and defines the notion of \\emph{predictive strategies} which are defined as follows: A uniform strategy $ \\sigma $ for player $ i $ is predictive with respect to $ \\phi $, if during all possible plays played according to $ \\sigma $, player $ i $ always knows that the outcome satisfies $ \\phi $.\n\n\\subsubsection*{The powers of the players}\n\nSince non-uniform strategies do not model the capabilities of the players in games of imperfect information, we need to update the definition of $ \\forcing{i} $: We replace \\emph{strategy} by \\emph{uniform strategy} and leave the remaining parts of the definition unchanged. After this change, C1 and C2 still hold \\cite{benthem2001a}. However, determinacy (C3) is no longer guaranteed as shown by the example in \\figref{fig:non-determinancy}: Player $ 1 $ can force the game to end in $ \\{ s_{1}, s_{2} \\} $ or $ \\{ s_{3}, s_{4} \\} $ by playing $ c $ or $ d $, respectively. Player $ 2 $ can force the game to end in $ \\{ s_{1}, s_{3} \\} $ or $ \\{ s_{2}, s_{4} \\} $ by playing $ a $ or $ b $, respectively. Hence, we have $ \\neg \\forcing{1}\\{ s_{2}, s_{3} \\} $ but not $ \\forcing{2}\\{ s_{1}, s_{4} \\} $, which disproves C3.\n\n\\begin{figure}[htb]\n\\centering\n\\begin{tikzpicture}[->,level/.style={sibling distance = 2.5cm/#1, level distance = 1.25cm}] ]\n\\node {1}\n    child {\n        node (e1) {2}\n        child {\n            node {$ s_{1} $} edge from parent node [left] {$ a $}\n        }\n        child {\n            node {$ s_{2} $} edge from parent node [right] {$ b $}\n        }\n        edge from parent node [above left] {$ c $}\n    }\n    child {\n        node (e2) {2}\n        child {\n            node {$ s_{3} $} edge from parent node [left] {$ a $}\n        }\n        child {\n            node {$ s_{4} $} edge from parent node [right] {$ b $}\n        }\n        edge from parent node [above right] {$ d $}\n    };\n\\path (e1) edge [-, dashed] node [above] {2} (e2);\n\\end{tikzpicture}\n\\caption{Game tree of an example game with imperfect information. First,  player $ 1 $ chooses between the moves $ c $ and $ d $. Player 2 cannot distinguish these moves, so she has to blindly choose between her moves $ a $ and $ b $. This figure is inspired by \\cite[fig.~2]{benthem2001a}.}\n\\label{fig:non-determinancy}\n\\end{figure}\n\n\\subsubsection*{Limitations on the possibility relations}\n\nThe presented definition of games of imperfect information is rather broad. It allows for many different kinds of uncertainties. It is possible, that player $ i $ does not know, which move the opponent has played. This is the case of \\figref{fig:non-determinancy}. However, more exotic kinds of uncertainties are also possible: It is possible that player $ i $ does not know the outcome of a move he just played himself. It is also possible that he does not know, whose turn it is, what his available moves are, or whether the game has ended. It seem natural to impose limitations on the game trees, such that these kinds of uncertainties are impossible.\n\nFirst, it is natural to assume that the players know the outcomes of the moves they just played. If we assume that every state $ s $ is labeled with a unique atomic proposition $ s' $, then we can enforce this by requiring the following for all states $ s \\in S $ and all actions $ a \\in A $: $ \\turn_{i} \\wedge \\langle a \\rangle s' \\rightarrow \\langle a \\rangle \\know_{i} s' $. Note that this does not guarantee that the players know the outcomes of their moves, \\emph{before} they play them. This property is captured by $ \\turn_{i} \\wedge \\langle a \\rangle s' \\rightarrow \\know_{i} \\langle a \\rangle s' $.\n\nSecond, it is natural to assume that the players know, who is next to make a move. This can be enforced by demanding $ \\turn_{i} \\rightarrow \\cknow_{I} \\turn_{i} $, where $ \\cknow $ is the common knowledge operator and $ I $ is the set of players \\cite{benthem2001a}.\n\nNext, it seem natural that the players know what moves are currently possible. That is, the same set of moves should be possible from two states, if the player to move cannot tell apart these two states. Formally, we demand $ \\turn_{i} \\wedge \\langle a \\rangle \\true \\rightarrow \\know_{i} \\langle a \\rangle \\true $ for all moves $ a \\in A $ \\cite{benthem2001a}. If we instead want the currently available moves to be common knowledge, we can demand $ \\langle a \\rangle \\true \\rightarrow \\cknow_{I} \\langle a \\rangle \\true $.\n\nFinally, if all players should be aware that the game has ended and if this should be common knowledge, we can impose the following limitation: $ \\leaf \\rightarrow \\cknow_{I} \\leaf $.\n\n% { \\color{red} The interchange principle (the beer example?)}\n\n\n%\\begin{itemize} \\color{red}\n%\\item Formal definition of imperfect-information game trees\n%\\item Strategies in imperfect games (the discussion from V.3). Maybe it is better to describe this after perfect recall.\n%\\item Short introduction to outcomes and powers in imperfect games (C3 does not hold anymore).\n%\\item Remarks on the looseness of this definition: \"Players need not know what the opponent has played, or what they played themselves, they need not know if it is their turn, or whether the game has ended, etc. One can think up plausible scenarios with all of the pictures shown in Figure 6.\"\n%\\item How to restrict the imperfect-information-game-trees model to be more \"realistic\": Describe the examples from \"III.3. Constraints for special axioms\".\n%\\end{itemize}\n\n\\subsection{Liar's Dice} \\label{sec:liars-dice}\n\nAs an example of a game of imperfect information, we now consider the game Liar's Dice. In this game\\footnote{A variety of dice games are called Liar's Dice. They all have elements of concealed die rolls and deception. The variant we consider is probably the simplest.}, two players take turns rolling a single die under a cup, privately looking at the result, and then call out an outcome of the die roll. The player may lie about the outcome of the roll. Now, the opponent can accept the call and start a new round by re-rolling the die or she can challenge the call by lifting the cup. If the call was correct, she looses the game and if the call was a lie, she wins the game. In each round, a player must call out a greater outcome than the one called in the previous round.\n\nGiven a die with $ k $ faces, this can be formalised as follows \\cite{ferguson1991}. In round $n$ player $i$ has the turn and rolls the die. She observes the outcome, which is a random integer $X(n)$ taking the values from $ 1 $ to $ k $ with equal probabilities. Then she announces an integer $y(n)$ between $y(n-1)+1$ and $ k $, both inclusive, with $y(0) = 0$. The next player $j$ then announces whether she doubts or believes the claim. If $y(n)=k$ then she always doubts. If she doubts, then $j$ wins if $X(n) < y(n)$ and $i$ wins otherwise. If she believes, then round $n+1$ begins and $j$ has the turn. A game tree for this game is shown in \\figref{fig:liars-dice-tree}.\n\n\\begin{figure}[htbp]\n\\centering\n\\input{pic/liars-dice-tree.tex}\n\\caption{Game tree of the Liar's Dice game described in \\secref{sec:liars-dice}. In this instance of the game, the \"die\" has two faces. We let N, 1, and 2 denote nature, player 1, and player 2, respectively. In order to keep the figure simple, we only depict when an uncertainty first arises. These uncertainties propagate down the tree under the rule that the two players can distinguish all actions except from the ones performed by nature.}\n\\label{fig:liars-dice-tree}\n\\end{figure}\n\nWhat can we say about the uncertainties in this game? The player not rolling is uncertain about the move of nature but this is the only type of uncertainty. All players know the outcomes of their own actions. Also, because we have no vertical uncertainty lines in the game tree, all players always know, whose turn it is. Finally, all players always know the currently available moves and all players know when the game has ended.\n\nUsing backward induction (see \\secref{sec:rationality}) can we predict the outcome of the game shown in \\figref{fig:liars-dice-tree}? First, assume that each player has one util at stake and that the winner takes it all. Then, it is obvious that the two states labeled \"roll${}_{2}$\" have expected value zero, as the die alone determines the winner from these states and each outcome is equally likely. If player $ 1 $ call out \"1\" after the first roll, then player $ 2 $ always looses by lifting, so see always rolls. Hence, calling \"1\" yields player $ 1 $ zero utils in expectancy.\n\nIf player $ 1 $ rolls 1 but calls \"2\", she always looses. If player $ 2 $ rolls 2 and calls \"2\", she always wins. Hence, the expected payoff from rolling $ 1 $ is zero and the expected value from rolling 2 is one. Therefore, in expectancy, player $ 1 $ earns 0.5 utils, which causes player $ 2 $ to loose 0.5 utils, since this is a zero-sum game. Thus, having the first roll is an advantage. Also, the optimal strategy for player $ 1 $ is to be honest and the optimal strategy for player $ 2 $ is to trust the call of player $ 1 $ and roll again. Notice that these are uniform strategies.\n\n\n\\subsection{Perfect recall}\nLiar's Dice satisfies the property \\emph{Perfect Recall}~\\cite{benthem2001a}: The players remember their own previous moves, as well as the uncertainties they had at each stage. This can be shown, by looking at the game tree and verifying that, for any player $i$ and any two states related by the uncertainty relation $\\sim_i$, the sequence of moves (made by $i$) leading to each of the two states are the same. Also, the uncertainties along these sequences are the same at all stages.\n\nNote that for this game in particular, Perfect Recall by itself has little significance under the assumption that all agents are rational, since the rounds that came before the previous one shouldn't impact the decision for the current round.\n\n%{ \\color{red} Predictive strategies? Ask Nina\\dots }\n\n\\subsection{Indistinguishable actions and product update}\nWe already introduced the notion of epistemic indistinguishability between states, modelled by the possibility relations $\\sim_i$. Now, we will see that a natural next step is to add possibility relations between actions to our game models as well. With this expansion of the possibility relations, we obtain a more general model, as different actions can lead to the same outcomes. An example of indistinguishable actions in Liar's Dice are those performed by Nature, from the perspective of a player that doesn't have the turn.\n\nThe \\emph{Product Update} mechanism is described as follows \\cite{benthem2001a}:\n$$\n(x,a)\\sim_i(y,b) \\longleftrightarrow x\\sim_i y \\mbox{ and } a\\sim_i b\n$$\nwhere $(x,a)$ and $(y,b)$ are ordered pairs consisting of 1) the previous state, and 2) the last performed action. It can be used iteratively to compute the next levels of game trees. \\cite{benthem2001a} proves that the following three properties follows from Product Update:\n\\begin{enumerate}\n\\item[(a)] Perfect Recall.\n\\item[(b)] Propagation of uncertainty: If $x\\sim_i y$ then after action $a$ in both cases $(x,a)\\sim_i (y,a)$.\n\\item[(c)] Actions are either always or never distinguishable: If $(x,a)\\sim_i (y,b)$ then whenever $u\\sim_i v$ also $(u,a)\\sim_i (v,b)$.\n\\end{enumerate}", "meta": {"hexsha": "b52185255997822f22a12bf5d4a628e8d124feee", "size": 18794, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Report/imperfect-information.tex", "max_stars_repo_name": "Andefar/LiarsDice", "max_stars_repo_head_hexsha": "f47123e80283a11500232d34102db2e894a4affb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Report/imperfect-information.tex", "max_issues_repo_name": "Andefar/LiarsDice", "max_issues_repo_head_hexsha": "f47123e80283a11500232d34102db2e894a4affb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2016-11-24T13:56:28.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-01T17:21:52.000Z", "max_forks_repo_path": "Report/imperfect-information.tex", "max_forks_repo_name": "Andefar/LiarsDice", "max_forks_repo_head_hexsha": "f47123e80283a11500232d34102db2e894a4affb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 130.5138888889, "max_line_length": 972, "alphanum_fraction": 0.7290092583, "num_tokens": 4876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5926665855647394, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.33546027262102873}}
{"text": "\\section{Introduction}\r\n\r\nWeather forecast is important for people to make their schedule for the next day. Among those technical terms in the forecasting, temperature and precipitation are the most important for the public. Nowadays weather forecasts, especially the precipitation forecast is conducted with the help of satellite images of clouds. This requires knowledge in meteorology. So we wonder if we can predict whether it will rain tomorrow based on the basic weather record (like temperature, precipitation, wind), with the classification method we learned in class.\r\n\r\nWe choose Seattle for our study as it usually has half of time in a year raining, so the data are balanced. In order to make better forecasting, feature engineering is needed. Also the data comes in form of daily report by each station. Combining the weather report each day from different stations is also a challenge for our study.  The location of weather stations and relationship between variables are discussed in the section of data exploration. And we are going to use Random Forest, $k$-NN and SVM for classification. At last part we are going to use the models trained with Seattle data to predict precipitation in another city to see whether the models are generally usable.", "meta": {"hexsha": "3d29ba66acb4e656990056173ba74b84bf745d3a", "size": 1265, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Report/intro.tex", "max_stars_repo_name": "shengchenHAO/Weather-Forecast-", "max_stars_repo_head_hexsha": "0c81dd5b8b3c4572464b0e0b841ca279ecb0d650", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Report/intro.tex", "max_issues_repo_name": "shengchenHAO/Weather-Forecast-", "max_issues_repo_head_hexsha": "0c81dd5b8b3c4572464b0e0b841ca279ecb0d650", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Report/intro.tex", "max_forks_repo_name": "shengchenHAO/Weather-Forecast-", "max_forks_repo_head_hexsha": "0c81dd5b8b3c4572464b0e0b841ca279ecb0d650", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 253.0, "max_line_length": 685, "alphanum_fraction": 0.8134387352, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.3353218498639371}}
{"text": "\\chapter{Developer Documentation}\n\\label{ch:impl}\n\nCreation of the program for histopathologic cancer detection is divided into four major parts:\n\\begin{enumerate}\n\t\\itemsep0em\n\t\\item Assembling dataset structure (required for input to a convolutional neural network), image preprocessing (loading, removing noise, normalization, whitening) and data augmentation (expanding the size of the dataset by applying a series of random transformations to each image)\n\t\\item Building the convolutional neural networks (class of deep neural networks applied to analyze images), and training them on data\n\t\\item Improving prediction accuracy of networks (solving underfitting and overfitting problems) with hyperparameter tuning (choosing optimal parameters for learning algorithm) and changes to network architecture\n\t\\item Creating a graphical user interface for the program, which allows user to load histopathologic slide and select network which has to be applied on it, and to get as output category to which that slide belongs, with the additional possibility to visualize network representations (heatmaps of class activations, filters of convolutional layers and intermediate activations)\n\\end{enumerate}\nIn the remainder of this chapter each part will be thoroughly analyzed, and directory/file structure of source the code will be illustrated, as well as use-case and class diagrams. \n\nSystem requirements discussed in user documentation (\\textcolor{red}{\\hyperref[sysreq]{Section 2.1}}) apply to developer documentation as well. \n\\clearpage\n\n\\section{Program Structure}\n\nHistopathologic Cancer Detection program is divided into six major modules (\\textcolor{red}{\\autoref{fig:dirdiag}}, \\textcolor{red}{\\autoref{fig:dirdiag2}}):\n\\begin{enumerate}\n\t\\itemsep 0em\n\t\\item Data - includes dataset creation (\\textcolor{red}{\\hyperref[createdata]{Section 3.4}})\n\t\\item Models - includes creation, training and testing of CNNs (\\textcolor{red}{\\hyperref[cnn]{Section 3.5}\\textcolor{black}{,} \\\\ \\hyperref[vgg19]{Section 3.6}})\n\t\\item Experiments - includes hyperparameter tuning (\\textcolor{red}{\\hyperref[exp]{Section 3.7}})\n\t\\item Graphical User Interface - includes creation of all application windows and their interconnection (\\textcolor{red}{\\hyperref[gui]{Section 3.8}})\n\t\\item Utilities - includes dataset analysis and visualization and network performance assessment and visualization (\\textcolor{red}{\\hyperref[utils]{Section 3.9}})\n\t\\item Tests - includes unit testing of Data, Models, Experiments and Utilities (\\textcolor{red}{\\hyperref[tests]{Section 3.11}})\n\\end{enumerate}\n\n\\begin{figure}[h]\n\t\\centering\n\t\\includegraphics[scale=1.3]{code_structure_1.jpg}\n\t\\caption{Diagram of directories and Python scripts of Data, Models, Experiments and Tests modules of Histopathologic Cancer Detection}\n\t\\label{fig:dirdiag}\n\\end{figure}\n\n\\clearpage\n\n\\begin{figure}[h]\n\t\\centering\n\t\\includegraphics[scale=1.3]{code_structure_2.jpg}\n\t\\caption{Diagram of directories and Python scripts of Tests, Graphical User Interface and Utilities modules of Histopathologic Cancer Detection}\n\t\\label{fig:dirdiag2}\n\\end{figure}\n\n\\section{Use-Case Diagram}\n\nOne of the main goals of the Histopathologic Cancer Detection program was the ease of use, i.e. straightforward graphical user interface which makes complex operations look quite simple and effortless. Even though there are extremely advanced algorithms with millions of parameters behind the program, GUI was made in such a way that everyone can use it. The first step is loading the image and selecting tissue type (breast or colorectal tissue), after which classification is being done. At every step of the way, current work can be saved, and a new image can be loaded to start the process from scratch. After the classification, it is possible to visualize network representations and perform further analysis of the results by visualizing layer activations, network filters, and heatmaps (\\textcolor{red}{\\autoref{fig:usecase}}).\n\n\\begin{figure}[h]\n\t\\centering\n\t\\includegraphics[scale=1.35]{use_case.jpg}\n\t\\caption{Use-Case Diagram of Histopathologic Cancer Detection}\n\t\\label{fig:usecase}\n\\end{figure}\n\n\\section{Class Diagrams}\n\nClasses of Histopathologic Cancer Detection can be divided into two main segments: window classes and neural network classes.\n\nBaseCNN class is the common class of all neural network classes, and it contains common attributes, such as dataset name, network name, compile parameters, and common methods, such as the creation of data generators, compilation, and training of the network. Neural network classes will be discussed in more detail in \\textcolor{red}{\\hyperref[cnn]{Section 3.5}, \\hyperref[vgg19]{Section 3.6}}.\n\n\\begin{figure}[h]\n\t\\centering\n\t\\includegraphics[scale=0.6]{nets_class_diagram.png}\n\t\\caption{Class diagram of neural network classes of Histopathologic Cancer Detection}\n\t\\label{fig:class1}\n\\end{figure}\n\n\\begin{figure}\n\t\\centering\n\t\\includegraphics[scale=0.38]{main_class_diagram.png}\n\t\\caption{Class diagram of window classes of Histopathologic Cancer Detection}\n\t\\label{fig:class2}\n\\end{figure}\n\nWindow class is the base class of all window classes, and it implements common methods, such as setting up the window size and central widget. On the other side, MainWindow class is the central point of GUI, as it defines the window which appears when the program is run, and every other window is invoked from it (\\textcolor{red}{\\autoref{fig:class2}}). Window classes, along with their attributes and methods, will be discussed in more detail in \\textcolor{red}{\\hyperref[gui]{Section 3.8}}.\n\n\\section{Creation of Datasets}\n\\label{createdata}\n\nPerformance and accuracy of convolutional neural networks rely largely on datasets, i.e. on quality of available data, dataset size, class balance, etc. But before feeding data to the network, if using \\texttt{Keras} API, certain dataset structures must be satisfied. More precisely, datasets must have the following structure: train, validation, and test directories, each with a subdirectory for each class. Scripts responsible for the creation of required directory structure and distribution of data are:\n\\begin{itemize}\n\t\\itemsep 0em\n\t\\item \\texttt{break\\_his\\_dataset\\_creation.py},\n\t\\item \\texttt{nct\\_crc\\_he\\_100k\\_dataset\\_creation.py}.\n\\end{itemize} \nThey work by extracting datasets downloaded from \\cite{breakhis_bib}, \\cite{nctcrche100k_bib}, creating necessary directory tree, and distributing images between created subdirectories. After executing scripts, datasets are ready to be fed into convolutional neural networks (in order to train them), but before that, neural network architecture has to be built.\n\\clearpage\n\n\\section{CNNSimple Implementation}\n\\label{cnn}\n\nCNNSimple convolutional neural network (\\textcolor{red}{\\hyperref[src:py1]{Code 3.1}}) was created using \\texttt{Keras} Sequential model in order to classify images from NCT-CRC-HE-100K dataset, which contains 100.000 images divided into 9 tissue/cancer categories. \n\nThe convolutional base of CNNSimple is composed of four blocks of convolutional and max-pooling layers, where the first two blocks have two convolutional and one max-pooling layer, and the last two blocks have three convolutional and one max-pooling layer. Each convolutional layer has a 3$\\times$3 convolution window, uses the ReLU activation function, and the number of feature maps (filters) increases exponentially from 32 to 256. Each max-pooling layer has pool size of 2$\\times$2. \n\nClassification top of CNNSimple is composed of two fully-connected layers, each followed by a dropout layer, and an output (also fully-connected) layer. Fully-connected layers use ReLU activation function, and number of neurons grows from 512 to 1024. Dropout layers use 50\\% dropout rate (fraction of neurons which will be ignored in each passing). Output layer uses softmax activation function, and has nine neurons (one neuron per tissue/cancer subtype output). \n\\vspace{1mm}\n\\lstset{caption={CNNSimple network architecture (defined in \\texttt{cnn\\_simple.py})},label=src:py1}\n\\begin{lstlisting}[language={Python}, basicstyle=\\scriptsize]\n\tmodel = Sequential()\n\tmodel.add(Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3),     \n\t                 name='block1_conv1'))\n\tmodel.add(Conv2D(32, (3, 3), activation='relu', name='block1_conv2'))\n\tmodel.add(MaxPooling2D((2, 2), name='block1_pool'))\n\tmodel.add(Conv2D(64, (3, 3), activation='relu', name='block2_conv1'))\n\tmodel.add(Conv2D(64, (3, 3), activation='relu', name='block2_conv2'))\n\tmodel.add(MaxPooling2D((2, 2), name='block2_pool'))\n\tmodel.add(Conv2D(128, (3, 3), activation='relu', name='block3_conv1'))\n\tmodel.add(Conv2D(128, (3, 3), activation='relu', name='block3_conv2'))\n\tmodel.add(Conv2D(128, (3, 3), activation='relu', name='block3_conv3'))\n\tmodel.add(MaxPooling2D((2, 2), name='block3_pool'))\n\tmodel.add(Conv2D(256, (3, 3), activation='relu', name='block4_conv1'))\n\tmodel.add(Conv2D(256, (3, 3), activation='relu', name='block4_conv2'))\n\tmodel.add(Conv2D(256, (3, 3), activation='relu', name='block4_conv3'))\n\tmodel.add(MaxPooling2D((2, 2), name='block4_pool'))\n\tmodel.add(Flatten(name='flatten'))\n\tmodel.add(Dense(512, activation='relu', name='dense1'))\n\tmodel.add(Dropout(0.5, name='dropout1'))\n\tmodel.add(Dense(1024, activation='relu', name='dense2'))\n\tmodel.add(Dropout(0.5, name='dropout2'))\n\tmodel.add(Dense(9, activation='softmax', name='prediction'))\n\\end{lstlisting} \n\n\\section{Transfer Learning}\n\\label{vgg19}\n\nAlthough CNNs are a powerful tool for image classification, in order to achieve high accuracy, a large amount of data is required. The problem occurs when only a small dataset is available (as is often in healthcare, ex. BreakHis dataset). In such cases transfer learning can be used: take a model trained on a large dataset and transfer knowledge to a small dataset, i.e. freeze convolutional base, and only train classification top of the network. The main idea is that early layers of convolutional base learn low-level features applicable across all images, such as edges and patterns.\n\n\\subsection{VGG19Simple Implementation}\n\nVGG19Simple convolutional neural network (\\textcolor{red}{\\hyperref[src:py2]{Code 3.2}}) was created using \\texttt{Keras} Graphical API in order to classify images from BreakHis dataset, which contains 2.081 images divided into 8 tissue/cancer categories. \n\nConvolutional base of VGG19Simple is VGG19 \\cite{simonyan2014very} pre-built network pre-trained on ImageNet \\cite{deng2009imagenet} dataset (without top classification part), using imagenet weights.\n\nClassification top of VGG19Simple is composed of two fully-connected layers, each followed by a dropout layer, and an output (also fully-connected) layer. Fully-connected layers use the ReLU activation function, and the number of neurons grows from 512 to 1024. Dropout layers use a 50\\% dropout rate (fraction of neurons which will be ignored in each passing). The output layer uses softmax activation function, and has eight neurons (one neuron per tissue/cancer subtype output). \n\n\\vspace{3mm}\n\\lstset{caption={VGG19Simple network architecture (defined in \\texttt{vgg19\\_simple.py})},label=src:py2}\n\\begin{lstlisting}[language={Python}, basicstyle=\\scriptsize]\n\tinput = Input((150, 150, 3))\n\tconvolutional_base = VGG19(weights='imagenet', include_top=False,\n\t                           input_tensor=input)\n\tfor layer in convolutional_base.layers:\n\t\tlayer.trainable = False\n\tx = Flatten(name='flatten')(convolutional_base.output)\n\tx = Dense(512, activation='relu', name='dense_1')(x)\n\tx = Dropout(0.5, name='dropout_1')(x)\n\tx = Dense(1024, activation='relu', name='dense_2')(x)\n\tx = Dropout(0.5, name='dropout_2')(x)\n\tx = Dense(8, activation='softmax', name='predictions')(x)\n\t\n\tmodel = Model(input, x)\n\\end{lstlisting} \n\n\\section{Experiments and Results}\n\\label{exp}\n\nPerformance of neural networks is determined by how well will it generalize, i.e. how high accuracy will it achieve on previously unseen data (if it performs well on training data, but underachieves on test data, it is said that CNN overfits). In order to prevent overfitting, a number of techniques can be used: increase the size of the dataset, change network architecture or apply hyperparameter tuning techniques, which consist of selecting a set of optimal hyperparameters for the learning algorithms. The selection of such parameters for networks is done in \\texttt{hyperparameter\\_tuning.py}. The first step consists of defining the hyperparameter dictionary with parameters and values to be tested, such as the number of epochs for which the network is to be trained, optimization techniques, etc. The next step consists of training a network with all combinations of parameters and values defined, after which network performances are compared in order to determine the optimal hyperparameter set.\n\nCNNSimple network trained on the NCT-CRC-HE-100K dataset was trained for 35 epochs, using RMSProp optimizer with a learning rate of 0.00004, using a categorical cross-entropy loss function. Before feeding data to the network, data augmentation (applying random transformations in order to produce more images, such as translation, rotation, sheer) has been used. In order to assess the performance of the network, the accuracy metrics function was employed. CNNSimple achieved 93.89\\% validation and 94.21\\% test accuracy, and 0.24 validation and 0.06 test loss (\\textcolor{red}{\\autoref{fig:netsperf}}).\n\nVGG19Simple network trained on the BreakHis dataset was trained for 90 epochs, using RMSProp optimizer with a learning rate of 0.0001, using a categorical cross-entropy loss function. Before feeding data to the network, data augmentation (applying random transformations in order to produce more images, such as translation, rotation, sheer) has been used. In order to assess the performance of the network, the accuracy metrics function was employed. After training a network with a frozen convolutional base, the last two convolutional blocks were unfrozen, and network was trained again using RMSProp optimizer with a learning rate of 0.00004. VGG19Simple achieved 85.3\\% validation and 83.59\\% test accuracy, and 0.72 validation and 1.02 test loss (\\textcolor{red}{\\autoref{fig:netsperf}}).\n\n\\begin{figure}[h]\n\t\\centering\n\t\\subfigure[\\scriptsize CNNSimple Accuracy]{\\label{fig:a}\\includegraphics[width=72mm]{cnn_acc.png}}\n\t\\subfigure[\\scriptsize CNNSimple Loss]{\\label{fig:b}\\includegraphics[width=72mm]{cnn_loss.png}}\n\t\\subfigure[\\scriptsize VGG19Simple Accuracy]{\\label{fig:vgg19perf}\\includegraphics[width=72mm]{vgg19_acc.png}}\n\t\\subfigure[\\scriptsize VGG19Simple Loss]{\\label{fig:b}\\includegraphics[width=72mm]{vgg19_loss.png}}\n\t\\caption{CNNSimple and VGG19Simple performance on BreakHis and NCT-CRC-HE-100K train and validation datasets (respectively)}\n\t\\label{fig:netsperf}\n\\end{figure}\n\n\\begin{figure}[h]\n\t\\centering\n\t\\begin{minipage}{.5\\textwidth}\n\t\t\\centering\n\t\t\\hspace*{-0.7cm}\n\t\t\\vspace*{-0.45cm}\n\t\t\\includegraphics[scale=0.37]{cnn_cf.png}\n\t\t\\captionof{figure}{Confusion Matrix (a summary table of correct and incorrect predictions broken down by each class) of CNNSimple on NCT-CRC-HE-1OOK test dataset}\n\t\t\\label{fig:cnncf}\n\t\\end{minipage}%\n\t\\begin{minipage}{.5\\textwidth}\n\t\t\\centering\n\t\t\\hspace*{-0.7cm}\n\t\t\\includegraphics[scale=0.37]{vgg19_cf.png}\n\t\t\\captionof{figure}{Confusion Matrix of VGG19Simple on BreakHis test dataset}\n\t\t\\label{fig:vgg19cf}\n\t\\end{minipage}\n\\end{figure}\n\n\\clearpage\n\n\\section{Graphical User Interface} \n\\label{gui}\n\nIn order to make using program simple and straightforward, graphical user interface using PyQt5 has been created. Following window classes have been constructed:\n\\begin{itemize}\n\t\\itemsep 0em\n\t\\item Window class in \\texttt{window.py}, used as base class for every other window, which contains primitive functions for setting up window, creating central widget, retranslating text, etc.\n\t\\item AboutAuthorWindow class in \\texttt{about\\_author\\_window.py}, which contains two labels (containing image and CV respectively)\n\t\\item AboutDatasetsWindow class in \\texttt{about\\_datasets\\_window.py}, which contains two labels (containing dataset sample images and dataset overview numbers respectively)\n\t\\item AboutModelsWindow class in \\texttt{about\\_models\\_window.py}, which contains five labels (containing network name, network architecture, accuracy, loss and confusion matrix plots respectively)\n\t\\item SimpleWindow class in \\texttt{simple\\_window.py}, which contains one image label\n\t\\item InspectConvWindow class in \\texttt{inspect\\_conv\\_window.py}, which contains three labels (containing convolutional layer text, number text and image respectively), button (with associated action), combo box (containing network layer names)  and line edit (for filter/channel selection)\n\t\\item MainWindow class in \\texttt{main\\_window.py}, which connects every other window and provides high-level program functionality \n\\end{itemize}\nIn addition, every window-specific information is located in \\texttt{config.py}, such as window sizes, positions and names of labels, paths to images, etc. GUI component definitions are located in \\texttt{gui\\_components.py}.\n\n\\subsection{Main Window}\n\nMainWindow class is the central part of the GUI, as it defines the window which appears when the program is started. It has a menu bar from which every other window can be reached, and a central widget which contains input image, tissue-type radio buttons, classify button and output class label, and probabilities plot. Function \\emph{classifyButtonEvent}, associated with \\emph{classifyButton} is an integral part of the class, as it loads network based on the tissue type of the input image, classifies it, and writes output to labels.\n\n\n\\section{Utilities}\n\\label{utils}\n\nFor program to work seamlessly, certain utilities needed to be implemented:\n\\begin{itemize}\n\t\\itemsep 0em\n\t\\item \\texttt{dataset\\_overview.py}, used for obtaining basic information about dataset, such as sample images and image distribution per class\n\t\\item \\texttt{misc.py}, containing functions for reading file contents, loading images, etc. \n\t\\item \\texttt{predict\\_image.py}, used for predicting class to which an image belongs\n\t\\item \\texttt{save\\_model.py}, used for saving neural network information and performance after being trained, such as arguments, architecture, accuracy, loss and confusion matrix plots, filters, etc.  \n\t\\item \\texttt{visualize\\_filters.py}, used for visualizing network filter patterns\n\t\\item \\texttt{visualize\\_intermediate\\_activations\\_and\\_heatmaps.py}, used for visualizing intermediate activations of the network, and heatmaps of class activation\n\\end{itemize}\n\n\\section{Implementing Additional Features}\n\nIn addition to the ease of use of the Histopathologic Cancer Detection program, source code was written in such a way to make expanding scope (problem space) of the program by including additional features quite simple and fast. If new tissue type (ex. lung tissue), along with tissue/cancer subtype classification was to be added to the program, it would be accomplished in the following four steps:\n\\begin{enumerate}\n\t\\itemsep 0em\n\t\\item \\textbf{Creating dataset} \\\\\n\tObtaining dataset of new tissue type, and preparing dataset to be fed to \\texttt{Keras}-built CNN, which includes creating appropriate directory structure and distributing data\n\t\\item \\textbf{Building CNN} \\\\\n\tCrating new convolutional neural network class inherited from BaseCNN by defining data generator transformations, network architecture, etc.\n\t\\item \\textbf{Fine-tuning CNN} \\\\\n\tDefining hyperparameter dictionary and training neural networks in order to increase classification accuracy and prevent overfitting\n\t\\item \\textbf{Extending GUI} \\\\\n\tAdding an additional radio button to MainWindow class, and extending action associated with classify button, as well as further analysis actions, to use newly created network\n\\end{enumerate}\n\n\\section{Testing}\n\\label{tests}\n\nSource code for Histopathologic Cancer Detection can be divided into two equal chunks: code responsible for CNN-related functionality and code responsible for GUI-related functionality.\n\nThe code responsible for CNN-related functionality has been unit-tested using \\texttt{PyTest} testing framework, and has a code coverage over 93\\%. Unit tests for data module can be found in \\texttt{test\\_data.py}, unit tests for models and experiments modules can be found in \\texttt{test\\_models\\_experiments.py}, and unit tests for utilities can be found in \\texttt{test\\_utils.py}.\n\nCode responsible for GUI-related functionality has been tested manually, where numerous histopathologic slides have been loaded and classified, as well as further analyzed, in order to inspect program functionality. \n\n\\section{External Code}\n\nMain ideas for advanced use of Histopathologic Cancer Detection, i.e. for further analysis of CNN representations and visualization of heatmaps of class activations, intermediate activations and filters of convolutional layers, as well as some parts of source code, have been taken from \\cite{chollet2018deep}. The code is licensed under MIT license.", "meta": {"hexsha": "ba37e51c05bd31857cd9441d4e76eeddb2fe3458", "size": 21137, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis_paper/chapters/impl.tex", "max_stars_repo_name": "bmarko98/histopathologic-cancer-detection", "max_stars_repo_head_hexsha": "e3223856026a4bebeaeca46ea15dd42957c1e7da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-04-17T11:40:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T12:48:29.000Z", "max_issues_repo_path": "thesis_paper/chapters/impl.tex", "max_issues_repo_name": "bmarko98/histopathologic-cancer-detection", "max_issues_repo_head_hexsha": "e3223856026a4bebeaeca46ea15dd42957c1e7da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-03-03T22:19:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-03T22:19:35.000Z", "max_forks_repo_path": "thesis_paper/chapters/impl.tex", "max_forks_repo_name": "bmarko98/histopathologic-cancer-detection", "max_forks_repo_head_hexsha": "e3223856026a4bebeaeca46ea15dd42957c1e7da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 81.9263565891, "max_line_length": 1006, "alphanum_fraction": 0.7899418082, "num_tokens": 5114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3353218426814197}}
{"text": "\\chapter{Temporal resolution of pulse detection}\n\\label{ch:timeres}\n\nIn this chapter we measure the temporal localization precision once the\npresence of a signal pulse is established.\n\nTo this end, we simulate events each containing only one signal at a known\nposition. In principle we could use the LNGS data (\\autoref{sec:lngsdata}), but\nwe do not know the jitter of the trigger pulse and we may reach a temporal\nresolution below the sampling period, while in the simulation we know the exact\nactual temporal location of signals.\n\n\\section{Event simulation}\n\nEvery event is the sum of a \\SI1{PE} signal and a noise waveform. We do not add\na baseline, so the noise has mean zero and the signals taper down to zero. The\nsignals are negative. We use the same scale of the LNGS data; the scale does\nnot affect the results of this study since we are not simulating digitalization.\nThe following paragraphs describe in detail the event simulation procedure.\n\n\\subsection{Signal generation}\n\\label{sec:toysignal}\n\nWe generate the signal pulse shape according to the trigger-aligned template\nfrom \\SI1{PE} laser pulses in Tile~57, see \\autoref{sec:cctemplate} and\n\\autoref{fig:template}.\n\nThe template is sampled at \\SI1{GSa/s}, but the simulated events are sampled at\n\\SI{125}{MSa/s}, which is the sampling frequency planned for the DarkSide20k\ndigitizers. The randomly generated signal time is not required to be aligned\nwith either clock. Given the generated temporal position, we round it by excess\n\\emph{and} defect to the \\SI{1}{ns} clock tick. Then we downsample the template\nby averaging samples in groups of~8. This is done twice: once with the groups\naligned to the floor-rounded temporal position, once with the ceiling-rounded\none. Finally we interpolate linearly between the two downsampled templates.\n\\autoref{fig:interptempl} shows a series of waveforms generated following this\nprocedure. Here averaging before downsampling has the role of an antialias\nfilter. While more refined antialiasing filters exist, a simple average is\nsufficient for our application.\n\nIn each simulation event we vary the amplitude of the signal by an additive\nGaussian random variable, which has the standard deviation observed in the LNGS\ndata, \\SI{2.9}\\% of the average \\SI1{PE} amplitude. This value is obtained by\ncomputing the difference in quadrature between the ``quantile standard\ndeviations'' (see \\autoref{sec:fingerplot}) of the \\SI{1}{PE} and \\SI{0}{PE}\npeaks in the fingerplot done with a \\SI{1.5}{\\micro s} average, the same used\nfor the template in \\autoref{sec:cctemplate}, and dividing it by the median of\nthe \\SI{1}{PE} peak.\n\n\\begin{figure}\n    \n    \\widecenter{\\includempl{figinterptempl}}\n\n    \\figcaption{interptempl}{The signal template downsampled from \\SI1{GSa/s}\n    to \\SI{125}{MSa/s} and translated continuously instead of by discrete steps\n    with linear interpolation.}\n\n\\end{figure}\n\n\\subsection{Noise simulation}\n\nTo study the dependence of the algorithms on noise, we simulate three different\nnoise distributions: Gaussian white noise; noise sampled from the LNGS data;\nnoise sampled from the Proto0 data.\n\n\\stracka{Eliminare ``A persistence... in Figure 4.3''}\n\nThe white noise is generated in the simulation. The LNGS noise is sampled from\nthe pre-trigger region of Tile~57 data, the same data used for the signal\ntemplate, ignoring any event with any sample less than 700 as in\n\\autoref{sec:snrdata}. The Proto0 noise is copied from data collected operating\nTile~57 below the breakdown voltage, keeping the whole events without\nselection. A persistence plot of the Proto0 data is shown in\n\\autoref{fig:hist2dtile155759}. The spectra are shown in\n\\autoref{sec:spectrum}, the autocorrelations in \\autoref{fig:autocorrlngs}.\n\nThe preprocessing applied on the pre-trigger window of LNGS data does not fully\nreject \\SI1{PE} pulses, and spurious \\SI1{PE} pulses may appear in the\nsimulation. In the analysis we will use robust statistics, i.e., quantiles, to\ndeal with outliers caused by this or any other unanticipated feature of the\ndata.\n\nWhen the noise waveforms for multiple simulated events are extracted from the\nsame data event, we skip \\SI{1}{\\micro s} between each waveform segment in the\ndata, to avoid correlations between the simulated events.\n\nWe downsample the noise in the same way as the signal, by averaging nearby\nsamples. The noise spectra from both sources (LNGS and Proto0) decrease with\nfrequency, so an antialiasing with an average should suffice. The Proto0 data,\nas is available to us, is pre-downsampled without antialiasing from\n\\SI{250}{MSa/s} to \\SI{125}{MSa/s}.\n\n\\emph{After} downsampling, the noise obtained from data is normalized to the\ndesired variance. The order matters because downsampling with averaging reduces\nthe variance of the noise, see \\autoref{fig:noise}. We normalize the variance\nseparately for each \\emph{data} event, also fixing the mean to zero, such that\nin the simulated events the variance has a realistic variation.\n\n\\stracka{Eliminare ``we normalize... data event''}\n\n\\begin{figure}\n    \n    \\widecenter{\\includempl{fignoise}}\n    \n    \\figcaption{noise}{The LNGS and Proto0 noise at the original sampling\n    frequency (normalized to zero mean and unit variance) and downsampled.}\n\n\\end{figure}\n\n\\subsection{Event layout}\n\nEach event is the sum of a noise waveform and a shorter signal waveform. Before\nthe beginning of the signal there is a noise-only region which is chosen long\nenough for the filters to be in a stationary state when the signal occurs. The\nlength of this region is set to be \\SI{2304}{ns}, i.e., longer than the largest\nfilter-length parameter considered in our study, \\SI{2048}{ns}.\n\nThe simulation is repeated for various raw signal to noise ratios (SNR),\ncalculated as the peak height relative to the baseline of the original\n\\SI1{GSa/s} signal template over the noise standard deviation.\n\nThe reason we consider the signal amplitude at \\SI1{GSa/s} and not at the\nactual sampling frequency of the simulation is because downsampling reduces the\npeak height. For convenience, we want to keep the definition of signal height\ncomparable at different sampling frequencies.\n\n\\marginpar{I should use the peak height, averaged over continuous positioning,\nat the simulation sampling frequency, instead of at \\SI{1}{GSa/s}. Then the\ncomparisons at different sampling frequencies would need to adjust both for the\nreduction of the noise variance and of the peak height, but the definition of\nSNR would be the standard one.}\n\nSimulations with different raw SNR differ only in the multiplicative constant\nof the noise, so we use exactly the same noise and signal arrays for every SNR\nto speed up the code. This means that there is no random variation between\nresults obtained at different SNR (or with different filters), keep this in\nmind if the smoothness of some curves would seem to suggest that the Monte\nCarlo error is negligible.\n\n\\stracka{Eliminare ``keep this... is negligible''}\n\n\\autoref{fig:toyevent} shows a complete example event.\n\n\\begin{figure}\n    \n    \\widecenter{\\includempl{figtoyevent}}\n    \n    \\figcaption{toyevent}{A simulation event. The dots are the minima of the\n    filters output. The minima are searched in the shaded region only; this\n    makes no difference with high enough SNR like in this example, but in the\n    limit SNR = 0 the minimum fluctuates around uniformly: the search range\n    sets the endpoints of this distribution.}\n\n\\end{figure}\n\n\\section{Temporal localization}\n\\label{sec:temploc}\n\nTo reconstruct the time position of the signals, We run the three filters\ndescribed in \\autoref{sec:filters} (moving average, exponential moving average,\ncross correlation), and take the minimum (the signals are negative) of the\nfiltered waveform as the location of the signal. We also take the minimum of\nthe unfiltered waveform as a baseline comparison.\n\nThe minimum of the filter output occurs at a shifted position relative to the\nsignal location, but this is not a problem since the choice of the point of the\nsignal to be taken as reference is arbitrary, and, for each filter, the shift\nis constant from one event to another.\n\nTo build the template for the cross correlation filter, we first truncate it as\ndescribed in \\autoref{sec:cctemplate}, and then downsample it in the same way\nwe downsample the signal template and the noise.\n\n\\begin{figure}\n    \n    \\widecenter{\\includempl{figtoyfilttempl}}\n    \n    \\figcaption{toyfilttempl}{Some cross correlation filter templates for\n    different lengths. It may appear strange that the endpoint on the left has\n    a different height than the endpoint on the right for a given template,\n    since we choose the truncation to maximize the norm; it happens because we\n    downsample \\emph{after} truncation.}\n\n\\end{figure}\n\nTo allow for a localization more precise than the sampling clock bin, we\ninterpolate the minimum sample and its first neighbors with a parabola. We also\ntry upsampling the waveform to \\SI{1}{GSa/s} (with sample repetition) prior to\nfiltering to check if it improves performance.\n\n\\subsection{Time resolution results}\n\nAssuming Proto0 noise spectrum, we simulate 1000 events and repeat the time\nposition reconstruction varying the filter, filter length parameter, and raw\nSNR. The signal template position is generated uniformly within one clock bin.\n\\autoref{fig:lochist} shows the histograms of the temporal localization for all\nfilters for a choice of SNR and filter length.\n\n\\begin{figure}\n    \n    \\widecenter{\\includempl{figlochist}}\n    \n    \\figcaption{lochist}{Histograms of the temporal localization error, i.e.\\\n    the difference between the filter output minimum and the signal template\n    start, translated to have zero median, for a choice of SNR and filters\n    length. The error bars mark the \\SI{16}\\% and the \\SI{84}\\% quantiles. As\n    definition of temporal resolution we take half the distance between those\n    quantiles. The sampling step is \\SI{8}{ns}.}\n\n\\end{figure}\n\nWe see that the distribution of reconstructed signal time positions can be\nnon-Gaussian, so to quantify the resolution we use, instead of the standard\ndeviation, half the distance between the \\SI{16}\\% and \\SI{84}\\% quantiles,\nwhich is equivalent to a standard deviation for a Gaussian, but gives a\nmeaningful measure for the width of the distribution even when it is highly\nskewed or with heavy tails.\n\n\\stracka{Non a capo}\n\n\\autoref{fig:rescurve} shows the temporal resolution thus defined for each\nfilter, filter length, and raw SNR. The exponential moving average has a\nconsistently poor performance compared to the other filters. The cross\ncorrelation filter is the best one, with performance improving with\nfilter-length, and at a length of 96 samples (\\SI{768}{ns}) is already\npractically optimal. The moving average can get close to the cross correlation\nfilter by choosing appropriately the number of samples.\n\n\\begin{figure}\n    \n    \\widecenter{\\includempl{figrescurve}}\n    \n    \\figcaption{rescurve}{Pulse detection temporal resolution for a range of\n    raw SNR and filter lengths. The shaded region marks the sampling\n    step~\\SI{8}{ns}. The right endpoint of the cross correlation filter curves\n    is at~\\SI{2.6}{ns}.}\n\n\\end{figure}\n\nIn the experiment The online processing of the PDM output will happen in two\nsteps: the digitizers must find the signals, then send them to the front end\nprocessors (FEPs) for further analysis. The computational resources of the\ndigitizers are limited compared to those available in the FEPs.\n\nThe exponential moving average can be implemented on the digitizers with few\nlogic resources. The cross correlation with 64 samples could probably be\nperformed with the resources available on the digitizers since a computation\nwith similar complexity was implemented in firmware and run on an evaluation\ncard featuring the same FPGA installed on the DarkSide digitizer boards.\n\nThe FEPs can and should probably use the best filter, so they would run a long\ncross correlation filter, since achieving a good temporal resolution may be\nbeneficial for offline analysis.\n\nTo summarize, out of all the temporal resolution curves the most relevant are:\n%\n\\begin{itemize}\n    %\n    \\item the best time resolution we can achieve with the exponential moving\n    average and moving average;\n    %\n    \\item the long cross correlation filters;\n    %\n    \\item the 64 samples cross correlation filter.\n    %\n\\end{itemize}\n%\nWe plot these curves together in \\autoref{fig:rescomp}, adding the resolution\nplots obtained in the best configuration when changing the noise spectrum in\nthe simulation, to show the impact of the noise spectrum on the performances.\nWe note in particular that a different noise spectrum makes a large difference\nat low SNR. Finally, we plot a curve computed with and without upsampling,\nwhich shows that upsampling does not improve significantly the performance.\n\n\\begin{figure}\n    \n    \\widecenter{\\includempl{figrescomp}}\n    \n    \\figcaption{rescomp}{Pulse detection temporal resolution vs.\\ SNR for\n    various filters. The shaded region marks the sampling step~\\SI{8}{ns}. The\n    hatched band is the interval of SNR observed in Proto0; the vertical line\n    is the SNR in the LNGS data, after downsampling to~\\SI{125}{MSa/s}. Where\n    not specified, the noise is from Proto0.}\n\n\\end{figure}\n\n\\section{Data reduction}\n\nIn this section we study the effect of some data reduction strategies at the\ndigitizer level on the time resolution that can be achieved in subsequent data\nprocessing stages. We said that the digitizers must find signals in the\nwaveform stream and send them to the FEPs for further processing. Depending on\nthe background rate, the bandwidth of the connection between the digitizers and\nthe FEPs can be a bottleneck. Two possible ways of reducing the amount of\ntransmitted data are keeping only the minimum number of samples around each\nsignal, and reducing the sampling frequency. Both have an effect on the\ntemporal resolution, which we assess in the next paragraphs.\n\n\\subsection{Waveform truncation}\n\nWe repeat the simulation, as in \\autoref{sec:temploc}, but this time we use\nonly a fixed smaller number of samples in each event to compute the filter\noutput. We call this selection of samples a ``window''. On the window we run\nonly a long cross correlation filter since that is what would be done on the\nFEPs. As past and future boundary condition we use zero. We evaluate the filter\neven after the sample window end because the window can be shorter than the\nfilter.\n\nIn this study we did not attempt any optimization of the left/right balance of\nthe window. The number of samples to be stored \\emph{before} the onset of the\nsignal is driven by the requirement to allow a proper baseline subtraction\nprocedure. However, by applying the zero padding just described, we are\nimplicitly assuming that a proper baseline subtraction procedure has been\napplied prior to running the filter. Thus, we only focus on determining the\nnumber of samples that should be saved \\emph{after} the onset of the signal, by\nconsidering windows that very skewed to the right. Keep into account that the\nmeasure we are looking at, the temporal resolution, does not depend critically\non getting the baseline right.\n\nWhile the length of the window is fixed, its placement is not fixed relative to\nthe true signal location. Instead we use the temporal localization with another\nfilter feasible on the digitizers, calibrated to have the median aligned to the\nbeginning of the signal template. The window then extends for a given number of\nsamples to the left and to the right of this localization.\n\n\\stracka{Non andare a capo}\n\n\\autoref{fig:windowevent} shows this procedure graphically for a single\nevent. \\autoref{fig:windowtempres} shows the temporal resolution versus\nunfiltered SNR curves for various choices of window length, noise, and filter\nused to align the window, where for reasons of computation time the latter was\ncomputed at a fixed SNR that does not follow the value on the x-axis.\n\n\\stracka{Eliminare ``where for reasons... x-axis''}\n\n\\begin{figure}\n    \n    \\widecenter{\\includempl{figwindowevent}}\n    \n    \\figcaption{windowevent}{Left panel: a simulation event filtered with the\n    exponential moving average. Right panel: the same event filtered with a\n    long cross correlation filter, both using the whole waveform and using only\n    the samples in the shaded window, which is centered using the localization\n    from the filter in the left panel.}\n\n\\end{figure}\n\n\\begin{figure}\n    \\widecenter{\\includempl{figwindowtempres}}\n    \n    \\figcaption{windowtempres}{Pulse detection temporal resolution with a long\n    cross correlation filter applied only on a short window of samples centered\n    using a shorter cross correlation filter (left panels) or an exponential\n    moving average (right panels). The various curves correspond to different\n    window lengths, while the black dots are the resolution without windowing.}\n\n\\end{figure}\n\nFrom \\autoref{fig:windowtempres} we conclude that it would be necessary to save\nat least \\SI1{\\micro s} of waveform after the onset of the signal to avoid\ndegrading the temporal resolution. On the other hand, we also observe that the\nperformances improve quickly to almost optimal ones when increasing the window\nlength. In the top right panel, i.e., with Proto0 noise and centering with an\nexponential moving average, the resolution does not converge to the value\nwithout windowing as the window length increases. This is due to the standard\ndeviation of the distribution of the window center, \\SI{17}{Sa}, being not\nsmall enough compared to the left window margin, \\SI{32}{Sa}. This means that\nin a non-negligible fraction of cases, the window does not include the leading\nedge of the signal. We show this problem intentionally to underline the\nimportance of the left/right balance.\n\n\\subsection{Downsampling}\n\nAnother way of reducing the data throughput is downsampling. In\n\\autoref{fig:tempresdowns} we show the temporal resolution achieved with a long\ncross correlation filter at different sampling frequencies. The downsampling is\ncomputed averaging nearby samples. So, in other words, we are comparing\napplying the cross correlation at the full sampling frequency to first applying\nan antialiasing filter, downsampling and then computing the cross correlation\nwith a downsampled template. We observe that downsampling by a factor of 2 from\n\\SI{125}{MSa/s} to \\SI{62}{MSa/s} maintains almost the same temporal\nresolution, while going to \\SI{31}{MSa/s} lowers it visibly.\n\nWhen downsampling a waveform, the variance of the noise is reduced. At each\nsampling frequency the simulation sets the SNR looking at the standard\ndeviation of the already downsampled noise, so the SNR scales are off by the\nfactor of the noise amplitude reduction. To make the simulations comparable, we\nshould start from a common ``master simulation'' at \\SI{1}{GSa/s}, then\ndownsample it various times. Our code does not implement this and repeats the\nsimulation from scratch at each sampling frequency, renormalizing the\ndownsampled noise to unitary variance. To account for this, in\n\\autoref{fig:tempresdowns} we apply a correction factor on the raw SNR before\nplotting the time resolution results.\n\n\\begin{figure}\n    \n    \\widecenter{\\includempl{figtempresdowns}}\n    \n    \\figcaption{tempresdowns}{Pulse detection temporal resolution at different\n    sampling frequencies with a cross correlation filter with template length\n    \\SI{2048}{ns}. The SNR scale is at \\SI{125}{MSa/s}; curves for different\n    sampling frequencies are rescaled horizontally by the factor written in the\n    legend to account for the noise variance reduction with downsampling, as\n    described in the text.}\n\n\\end{figure}\n\nWe also check if downsampling is associated to signal to noise ratio\ndegradation in the cross correlation filter output. In\n\\autoref{tab:filtsnrdowns} we report the ratio between SNR after and before\nfiltering. It does not appear to change significantly.\n\n\\marginpar{Add digitalization to the simulation and make a plot like the one\nfor the sampling frequency but varying the number of bits at \\SI{125}{MSa/s}.\nDon't use the number of bits, use the ratio signal peak over digit which is\nwell defined.}\n\n\\begin{table}\n    \\centering\n    \n    \\begin{tabular}{c*4S[table-format=1.1]}\n        \\toprule\n               & \\multicolumn4c{SNR after over before filtering} \\\\\n        \\cmidrule(l){2-5}\n         Noise & {\\SI{1}{GSa/s}} & {\\SI{125}{MSa/s}} & {\\SI{62.5}{MSa/s}} & {\\SI{31.2}{MSa/s}} \\\\\n        \\midrule\n        Proto0 &               &             3.3 &              3.3 &              3.3 \\\\\n          LNGS &           5.6 &             5.5 &              5.7 &              6.0 \\\\\n         White &           4.3 &             4.3 &              4.2 &              4.2 \\\\\n        \\bottomrule\n    \\end{tabular}\n    \n    \\caption{\\label{tab:filtsnrdowns} Ratio of SNR after over before filtering\n    with a cross correlation filter with template length \\SI{2048}{ns}. The\n    \\SI{125}{MSa/s} column contains the actual SNR ratios of the simulations,\n    while the values for the other sampling frequencies are divided by the\n    noise standard deviation reduction with downsampling relative to\n    \\SI{125}{MSa/s} to make them comparable.}\n    \n\\end{table}\n", "meta": {"hexsha": "1ddd93c6f9daf138d14ef7cbc74f32dfdd2f4d5c", "size": 21367, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "timeres.tex", "max_stars_repo_name": "Gattocrucco/thesis", "max_stars_repo_head_hexsha": "0b8672b7dc6a4ec54c5c76ecfbb83edcf34729f7", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-15T07:16:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T07:16:46.000Z", "max_issues_repo_path": "timeres.tex", "max_issues_repo_name": "Gattocrucco/thesis", "max_issues_repo_head_hexsha": "0b8672b7dc6a4ec54c5c76ecfbb83edcf34729f7", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "timeres.tex", "max_forks_repo_name": "Gattocrucco/thesis", "max_forks_repo_head_hexsha": "0b8672b7dc6a4ec54c5c76ecfbb83edcf34729f7", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.4512471655, "max_line_length": 97, "alphanum_fraction": 0.772827257, "num_tokens": 5018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3353218354989021}}
{"text": "\\section{Understanding ``Out Of Thin Air'' using Temporal Logic}\n\\label{sec:logic}\n\nA significant challenge for a software memory model is to relax order enough\nto allow efficient implementation without admitting anomalous\nbehaviors---called \\emph{out of thin air} (\\oota) in the literature\n\\cite{vacuous,DBLP:conf/esop/BattyMNPS15,BoehmOOTA}.  The most famous example\nis \\ref{OOTA3} from \\textsection\\ref{sec:intro}.  Here we inline\ninitialization in order to fit the format of our proof rules:\n\\begin{align}\n  \\label{OOTA3} \\tag{\\textsc{oota1}}\n  \\PW{y}{0}\\SEMI \n  \\PW{y}{x}\n  \\!\\PAR\\!\n  \\PW{x}{0}\\SEMI\n  \\PR{y}{r}\\SEMI \\PW{x}{r}  \n  &&\n  \\smash{\\hbox{\\begin{tikzinline}[node distance=1.2em]\n        \\event{rx}{\\DR{x}{1}}{}\n        \\event{wy}{\\DW{y}{1}}{right=of rx}\n        \\po{rx}{wy}\n        \\event{y0}{\\DW{y}{0}}{left=of rx}\n        \\event{x0}{\\DW{x}{0}}{right=2em of wy}\n        \\event{ry}{\\DR{y}{1}}{right=2em of x0}\n        \\event{wx}{\\DW{x}{1}}{right=of ry}\n        \\po{ry}{wx}\n        \\rf[out=10,in=170]{wy}{ry}\n        \\rf[out=170,in=10]{wx}{rx}\n        \\wk[out=-15,in=-165]{y0}{wy}\n        \\wk[out=-15,in=-165]{x0}{wx}\n      \\end{tikzinline}}}\n\\end{align}\nAlthough Java does not allow \\oota{} behaviors of \\ref{OOTA3},\n\\citet{DBLP:journals/toplas/Lochbihler13} showed that it does allow \\oota\\\nbehaviors of \\ref{OOTA1}, also from \\textsection\\ref{sec:intro}.  In\n\\cite{DBLP:conf/lics/JeffreyR16}, we described a logic that rules out\n\\ref{OOTA3} but not \\ref{OOTA1} or its variant \\ref{OOTA4}.  In this section,\nwe provide a more accurate test of \\oota{} behaviors by enhancing our\nprevious logic with temporal features.\n\nOn first read, we suggest that readers skip to the examples and the\ndiscussion that follows, coming back to the definitions as necessary.\nExample~\\ref{ex:thin} discusses the canonical \\oota{} example \\ref{OOTA3};\nthe analysis is trivial and well-known \\cite{DBLP:conf/lics/JeffreyR16,\n  DBLP:conf/popl/KangHLVD17}.  Example~\\ref{ex:lochb} is more interesting.\nThere, we discuss \\ref{OOTA4}, which is a variant of\n\\citeauthor{DBLP:journals/toplas/Lochbihler13}'s \\ref{OOTA1}.\n\nThe logic given here is not meant to be definitive; in\n\\textsection\\ref{sec:limits}, we discuss \\oota{} examples that appear to\nrequire non-trivial extensions\n\\cite{DBLP:conf/esop/SvendsenPDLV18,DBLP:journals/pacmpl/ChakrabortyV19}.\n\n\\noparagraph{Definitions}\nWe adapt past linear temporal logic (\\pLTL)\n\\cite{Lichtenstein:1985:GP:648065.747612} to pomsets by dropping the previous\ninstant operator and adopting strict versions of the temporal operators.\nThe atoms of our logic are write and read events.\nGiven a pomset $\\aPS$ and event $\\aEv$, define:\\nofootnote{Let $\\FALSE$, $\\lor$,\n  $\\Rightarrow$ and $\\once$ as usual;\n  for example,\n  $\\once\\afo = \\lnot(\\always\\lnot\\afo)$.}\n\\begin{displaymath}\n  \\renewcommand{\\arraycolsep}{.2ex}\n  \\begin{array}{lrll}\n    \\aPS,\\aEv &\\models& \\DW{\\aLoc}{\\aVal} &\\text{ if } \\labelingAct(\\aEv) = \\DW{\\aLoc}{\\aVal} \\text{ and } \\TRUE \\text{ implies } \\labelingForm(\\aEv) \\\\\n    \\aPS,\\aEv &\\models& \\DR{\\aLoc}{\\aVal} &\\text{ if } \\labelingAct(\\aEv) = \\DR{\\aLoc}{\\aVal} \\text{ and } \\TRUE \\text{ implies } \\labelingForm(\\aEv) \\\\\n    \\aPS,\\aEv &\\models& \\afo\\land\\bfo &\\text{ if } \\aPS,\\aEv \\models  \\afo \\text{ and } \\aPS,\\aEv \\models  \\bfo \\\\\n    \\aPS,\\aEv &\\models& \\TRUE\\\\\n    \\aPS,\\aEv &\\models& \\lnot\\afo &\\text{ if } \\aPS,\\aEv \\not\\models \\afo \\\\\n    \\aPS,\\aEv &\\models& \\always\\afo &\\text{ if } \\forall \\bEv \\lt \\aEv.\\; \\aPS,\\bEv \\models \\afo\\\\\n    \\aPS,\\aEv &\\models& \\once\\afo &\\text{ if } \\exists \\bEv \\lt \\aEv.\\;  \\aPS,\\bEv \\models \\afo \n  \\end{array} \n\\end{displaymath}\n\nDefine $\\FALSE$, $\\lor$, and $\\Rightarrow$ as usual.\n\nLet $\\aPS \\models \\afo$ if\n$\\aPS,\\aEv \\models\\afo$, for all $\\aEv \\in \\Event$.\n\nLet $\\aPSS\\models \\afo$\nif $\\aPS \\models\\afo$, for all $\\aPS \\in \\aPSS$.\n\nLet\n\\begin{math}\n  \\afo, \\aPSS \\models \\bfo  \\text{ if } \\{ \\aPS \\mid \\aPS \\models \\afo \\} \\parallel \\aPSS \\models \\bfo.\n\\end{math}\n\nLet $\\afo$ be \\emph{downclosed} when\n$\\{ \\aPS \\mid \\aPS \\models \\afo \\}$ is.\n\nThe past operators do not include the current instant, and so\ndo \\emph{not} satisfy\n$(\\always\\afo\\Rightarrow\\once\\afo)$. The order-minimal elements always validate\n$\\always\\afo$ and invalidate\n$\\once\\afo$.\nHowever, we can prove the following:\n\\begin{align*}\n  \\tag{Induction}\n  \\aPS \\models& (\\always\\afo \\Rightarrow\\afo) \\Rightarrow\\afo\n  \\\\[-1ex]\n  \\tag{Coinduction}\n  \\aPS \\models& (\\afo \\Rightarrow\\once{\\afo}) \\Rightarrow\\lnot \\afo\n  \\\\[-1ex]\n  \\tag{Weakening}\n  \\aPS \\models& (\\afo \\Rightarrow\\once{\\bfo}) \\Rightarrow (\\once\\afo \\Rightarrow\\once{\\bfo})\n\\end{align*}\n\nWe present two additional proof rules. \nThe first provides a logical view of \\emph{$\\aLoc$-closure} (Def.~\\ref{def:rf}):\n\\begin{displaymath}\n  \\frac{\n    \\afo \\text{ is independent of } \\aLoc\n    \\qquad\n    \\aPS \\models (\\DR{\\aLoc}{\\aVal} \\Rightarrow \\once \\DW{\\aLoc}{\\aVal}) \\Rightarrow \\afo\n  }{\n    \\nu \\aLoc \\DOT \\aPS \\models \\afo\n  }\n\\end{displaymath}\n\nThe second rule describes concurrent composition, in the style of~\\citet{Abadi:1993:CS:151646.151649}.  To simplify the presentation, we\nconsider the special case with a single invariant.\n\n\\begin{proposition}%[Composition]\n  Let $\\afo$ be downclosed.  Let $\\aPSS_1, \\aPSS_2$ be\n  augmentation\\hyp{}closed. %\\footnote{$\\aPS'$ is an augmentation of $\\aPS$ if\n  Then:\n  \\begin{displaymath}\n    \\frac{\n      \\afo, \\aPSS_1 \\models\\afo\n      \\qquad\n      \\afo, \\aPSS_2 \\models\\afo\n    }{\\aPSS_1 \\parallel \\aPSS_2 \\models \\afo}\n  \\end{displaymath}\n\\end{proposition}\n\\begin{proof}[Proof sketch]\n  We will show that all downsets in the downset closures of\n  $\\aPSS_1 \\parallel \\aPSS_2$ satisfy the required property.  Proof proceeds\n  by induction on downsets of $\\aPS \\in \\aPSS_1 \\parallel \\aPSS_2$.\n  The case for empty downset  follows from assumption that  $\\afo$ is downset closed.  \n  For the inductive case, consider %$\\aPS$ in the downset closure of $\\aPSS_1 \\parallel \\aPSS_2$, i.e.\n  $\\aPS \\in \\aPS_1 \\parallel \\aPS_2$ where\n  $\\aPS_i \\in \\aPSS_i$.  Since $\\aPSS_1$ and $\\aPSS_2$ are augmentation\n  closed, we can assume that the restriction of $\\aPS$ to the events of\n  $\\aPS_i$ coincides with $\\aPS_i$, for $i=1,2$.\n  Consider a downset $\\aPS'$ derived by removing a maximal element $\\aEv$ from\n  $\\aPS$.  Suppose $\\aEv$ comes from $\\aPS_1$ (the other case is\n  symmetric). Since $\\aPS_2$ is a downset of $\\aPS'$ and $\\aPS' \\models \\afo$\n  by induction hypothesis, we deduce that $\\aPS_2 \\models \\afo$.\n  Since $\\aPS_1 \\in \\aPSS_1$, by assumption $\\afo, \\aPSS_1 \\models\\afo$ we\n  deduce that $\\aPS \\models \\afo$.\n\\end{proof}\n\n\\begin{example}\n  \\label{ex:thin}\n  \\noparagraph{Basic Examples}\n  With all variables initialized to $0$, we show that \\ref{OOTA3}\n  satisfies\n  \\begin{math}\n    \\lnot\\DW{x}{1}.\n  \\end{math}\n\n  We start with the invariant:\n  \\begin{displaymath}\n    [\\DW{x}{1}\\Rightarrow\\once\\DR{y}{1}]\n    \\land\n    [\\DW{y}{1}\\Rightarrow\\once\\DR{x}{1}]\n  \\end{displaymath}\n  This invariant holds for each thread; thus, it holds for the\n  aggregate program by composition.  Closing $y$ yields\n  \\begin{math}\n    \\DR{y}{1} \\Rightarrow \\once\\DW{y}{1}.\n  \\end{math}\n  Weakening the right conjunct: % yields\n  \\begin{math}\n    \\once\\DW{y}{1}\\Rightarrow\\once\\DR{x}{1}.\n  \\end{math}\n  Chaining these together: %yields\n  \\begin{math}\n    \\DR{y}{1} \\Rightarrow \\once\\DR{x}{1}.\n  \\end{math}\n  Weakening:  %yields\n  \\begin{math}\n    \\once\\DR{y}{1} \\allowbreak\\Rightarrow \\once\\DR{x}{1}. \n  \\end{math}\n  Chaining into the left conjunct:  %yields\n  \\begin{math}\n    \\DW{x}{1} \\Rightarrow \\once\\DR{x}{1}. \n  \\end{math}\n  Closing $x$, \n  weakening, \n  then chaining: %, yields\n  \\begin{math}\n    \\DW{x}{1} \\Rightarrow \\once\\DW{x}{1}. \n  \\end{math}\n  By coinduction, \n  \\begin{math}\n    \\lnot\\DW{x}{1}.\n  \\end{math}\n\\end{example}\n\n\\begin{example}\n  \\label{ex:lochb}\n  \\noparagraph{Lochbihler's Example} %The essential temporal property of\n  Because our language lacks object creation, we cannot consider\n  \\citeauthor{DBLP:journals/toplas/Lochbihler13}'s example (\\ref{OOTA1}) directly.  Instead we study \\ref{OOTA4}, which has the same\n  temporal structure.\n  The essential temporal property of\n  \\ref{OOTA4} is: \\emph{A write of $1$ to $y$ must be preceded by a read of\n    $1$ from $x$, and if $1$ is written to $z$ then a write of $1$ to $x$\n    must be preceded by a read of $1$ from $y$.}\n  We show an attempted execution that violates this invariant, eliding\n  initialization:\n  \\begin{gather}\n    \\label{OOTA4}\\tag{\\textsc{oota4}}\n    \\begin{gathered}\n      \\PW{y}{x}\n      \\PAR\n      \\PR{y}{r} \\SEMI \\IF{b}\\THEN  \\PW{x}{r} \\SEMI \\PW{z}{r} \\ELSE \\PW{x}{1} \\FI\n      \\PAR\n      \\PW{b}{1}\n      \\\\[-1ex]\n      \\hbox{\\begin{tikzinline}[node distance=1.5em]\n          \\event{rx}{\\DR{x}{1}}{}\n          \\event{wy}{\\DW{y}{1}}{right=of rx}\n          \\po{rx}{wy}\n          \\event{ry}{\\DR{y}{1}}{right=3em of wy} \n          \\event{wx}{\\DW{x}{1}}{right=of ry}\n          \\event{wz}{\\DW{z}{1}}{right=of wx}\n          \\event{rb}{\\DR{b}{1}}{right=of wz}\n          \\event{wb1}{\\DW{b}{1}}{right=3em of rb}\n          \\po{ry}{wx}\n          \\rf{wb1}{rb}\n          \\rf{wy}{ry}\n          \\rf[out=-170,in=-10]{wx}{rx}\n          \\po{rb}{wz}\n          \\po[out=15,in=165]{ry}{wz}\n        \\end{tikzinline}}\n    \\end{gathered}  \n  \\end{gather}\n  As we discussed in \\textsection\\ref{sec:pop} there is a dependency from\n  $(\\DR{y}{1})$ to $(\\DW{x}{1})$; thus, the outcome is disallowed.  This\n  outcome is also disallowed by our event structures model\n  \\citep[\\textsection9]{DBLP:journals/lmcs/JeffreyR19}, although the logic\n  given in that paper is insufficient to establish this fact.  The outcome is\n  \\emph{allowed} by \\citet{Manson:2005:JMM:1047659.1040336}, \\citet{DBLP:conf/esop/JagadeesanPR10},\n  \\citet{DBLP:conf/popl/KangHLVD17}, and\n  \\citet{DBLP:journals/pacmpl/ChakrabortyV19}.\n\n  To establish that this outcome is disallowed here, we prove \n  \\begin{math}\n    \\lnot\\DW{z}{1},\n  \\end{math}\n  starting with invariant:\n  \\begin{align*}\n    [\\once\\DW{y}{1} \\Rightarrow \\once\\DR{x}{1}]\n    \\land\n    [\\notonce\\DW{z}{1} \\Rightarrow (\\once\\DR{y}{1} \\land \\always(\\DW{x}{1} \\Rightarrow \\once\\DR{y}{1}))]\n  \\end{align*}\n  Closing $y$ and chaining into the left conjunct:\n  \\begin{math}\n    \\once\\DR{y}{1} \\Rightarrow \\once\\DR{x}{1}.\n  \\end{math}\n  Chaining into the right conjunct:\n  \\begin{displaymath}\n    \\notonce\\DW{z}{1} \\Rightarrow (\\once\\DR{x}{1} \\land \\always(\\DW{x}{1} \\Rightarrow \\once\\DR{x}{1}))\n  \\end{displaymath}\n  Closing $x$:\n  \\begin{math}\n    \\notonce\\DW{z}{1} \\Rightarrow (\\once\\DW{x}{1} \\land \\always(\\DW{x}{1} \\Rightarrow \\once\\DW{x}{1}).\n  \\end{math}\n  Applying coinduction to the right conjunct:\n  \\begin{displaymath}\n    \\notonce\\DW{z}{1} \\Rightarrow (\\once\\DW{x}{1} \\land \\always(\\lnot \\DW{x}{1}))\n  \\end{displaymath}\n  Simplifying:\n  \\begin{math}\n    \\notonce\\DW{z}{1} \\Rightarrow \\FALSE,\n  \\end{math}\n  as required.\n\\end{example}\n\n\\noparagraph{RFUB: Register assignment From an Unexecuted Branch}\nMany examples are superficially similar, but in fact have fewer dependencies,\nsuch as \\eqref{OOTA?} in \\textsection\\ref{sec:intro}.\n\\citeauthor{BoehmOOTA}'s [\\citeyear{BoehmOOTA}] \\ref{RFUB} example presents\nanother potential form of \\oota{} behavior.\nOur analysis shows that there is no \\oota{} behavior in\n\\ref{RFUB}, only a false dependency:\n\\begin{gather*}\n  \\tag{\\textsc{rfub}}\\label{RFUB}\n  \\sem{\\PR{y}{r}\\SEMI \\PW{x}{r}}\n  \\not\\supseteq\n  \\sem{\\PR{y}{r}\\SEMI \\IF{r \\NOTEQ 1} \\THEN \\PW{z}{1}\\SEMI \\LET{r}{1}\\FI \\SEMI \\PW{x}{r}}\n\\end{gather*}\nThe left command is half of \\ref{OOTA3}. %, from \\textsection\\ref{sec:logic}.\nThe right command is dubbed \\rfub{}, for \\emph{Register assignment From an\n  Unexecuted Branch}.  \\citeauthor{BoehmOOTA} observes that in the context\n$\\PW{x}{y} \\PAR \\hole{}$, these programs have different behaviors.  Yet the\n\\oota{} example on the left never writes $1$.  Why should the unexecuted\nbranch change that?  Because of the conditional, the write to $x$ in\n\\ref{RFUB} is independent of the read from $y$.  It useful to considering the\nHoare logic formulas satisfied by the two threads above: we have\n$\\hoare{\\TRUE}{\\ref{RFUB}}{x=1}$ for the right thread of \\ref{RFUB}, but not\n$\\hoare{\\TRUE}{\\ref{OOTA3}}{x=1}$ for the right thread of \\ref{OOTA3}.  The\nchange in the thread from \\ref{OOTA3} to \\ref{RFUB} is not a valid refinement\nunder Hoare logic; thus, it is expected that \\ref{RFUB} may have additional\nbehaviors.\n\nUnderstanding \\oota{} behavior is notoriously difficult, even for the\ngreatest minds in the field!  % We believe that \\emph{logic} is the only tool\nThis example shows the wisdom of using existing tools, such as preconditions\nand Hoare logic, to model new problems, such as relaxed memory.\n\n\\begin{comment}\n  \\color{red} Need to sort this out.\n  Alan proposes:\n\\begin{verbatim}\n     (W y 2) => <>(R x 1)\n     (W y 1) => <>(R x 0)\n     (W x 1) => <>(R y 1)\n   <>(W x 1) => not(<>(W x 2))  --- which should be???  <>(W x 0) => not(<>(W x 1))\n\\end{verbatim}\n\n  2020/09/30: This seems to go bad because of initialization...\n  The formula\n\\begin{verbatim}\n<>Wx0 => not(<>Wx1)\n\\end{verbatim}\n  does not hold for\n\\begin{verbatim}\nx=0; x=y\n\\end{verbatim}\n\n  2020/09/10:  I am worried about the compositionality of this predicate:\n\\begin{verbatim}\nI think\n   <>(W x 0 => not(<>(W x 1)))\nholds for \n   x=0; r=y \nand\n   x=1\nbut not\n   x=0; r=y || x=1\nas shown by the execution\n   Wx1 < Wx0 < Ry0\n\\end{verbatim}\n  \n  It is impossible to fulfill $(\\DR{y}{1})$ in the following\n  \\cite[RNG]{DBLP:conf/esop/SvendsenPDLV18}:\n  \\begin{align*}\n    \\taglabel{OOTA5}\n    ( \\PW{y}{x{+}1}\n    \\PAR\n    \\PW{x}{y} ) && \\hbox{\\begin{tikzinline}[node distance=1.5em]\n        \\event{rx}{\\DR{x}{1}}{}\n        \\event{wy}{\\DW{y}{2}}{right=of rx}\n        \\po{rx}{wy}\n        \\event{ry}{\\DR{y}{1}}{right=3em of wy}\n        \\event{wx}{\\DW{x}{1}}{right=of ry}\n        \\po{ry}{wx}\n        \\rf[out=170,in=10]{wx}{rx}\n      \\end{tikzinline}}\n  \\end{align*}\n  The proof proceeds as before, starting with the following invariant:\n  \\begin{gather*}\n    [\\DW{y}{2} \\Rightarrow \\once\\DR{x}{1}] \\land\n    [\\once\\DW{x}{1} \\Rightarrow \\once\\DR{y}{1}] \\land\n    [\\once\\DW{y}{1} \\Rightarrow \\once\\DR{x}{0}] \\land\n    [\\once\\DW{x}{0} \\Rightarrow \\lnot(\\once\\DW{x}{1})]\n  \\end{gather*}\n\\begin{verbatim}\n  Wy2 => <>Rx1  /\\  <>Wx1 => <>Ry1  /\\  <>Wy1 => <>Rx0  \nclose x and y                                          \n  Wy2 => <>Wx1  /\\  <>Wx1 => <>Wy1  /\\  <>Wy1 => <>Wx0  \nchain\n  Wy1 => <>Wx0  \nchain with <>Wx0 => not(<>Wx1)\n\\end{verbatim}\n\\end{comment}\n", "meta": {"hexsha": "465eab69a8dc38038ac1f7c02def89007aa4dbc5", "size": 14548, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "corrigendum/logic.tex", "max_stars_repo_name": "chicago-relaxed-memory/memory-model", "max_stars_repo_head_hexsha": "fd606fdb6a04685d9bb0bee61a5641e4623b10be", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-08-13T02:36:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-25T12:46:13.000Z", "max_issues_repo_path": "corrigendum/logic.tex", "max_issues_repo_name": "chicago-relaxed-memory/memory-model", "max_issues_repo_head_hexsha": "fd606fdb6a04685d9bb0bee61a5641e4623b10be", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "corrigendum/logic.tex", "max_forks_repo_name": "chicago-relaxed-memory/memory-model", "max_forks_repo_head_hexsha": "fd606fdb6a04685d9bb0bee61a5641e4623b10be", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1837270341, "max_line_length": 152, "alphanum_fraction": 0.6506736321, "num_tokens": 5242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3353218354989021}}
{"text": "\\documentclass[11pt,fleqn]{amsart}\n\\usepackage{graphicx,amsmath,amssymb,a4wide}\n\\usepackage[numbers,sort&compress]{natbib}\n\\usepackage[hang]{subfigure}\n\n\\renewcommand{\\div}{\\ensuremath{\\operatorname{div}}}\n\\newcommand{\\vect}[1]{\\boldsymbol{#1}}\n\\newcommand{\\mat}[1]{\\boldsymbol{#1}}\n\\newcommand{\\tens}[1]{\\boldsymbol{\\mathsf{#1}}}\n\\newcommand{\\transp}[1]{{#1}^{\\ensuremath{\\mathsf{T}}}}\n\n\\newtheorem{remark}{Remark}\n\n\\begin{document}\n\n\\title[Local flux mimetic in Matlab]{Implementation of local flux mimetic in Matlab}%\n\\author[J.~R.~Natvig]{Jostein R. Natvig}%\n\\address{SINTEF ICT, Applied Mathematics, P.O.~Box 124 Blindern, N--0314 Oslo, Norway}\n\\email[]{\\{Jostein.R.Natvig\\}@sintef.no}\n\n\n%\\begin{abstract}\n%\\end{abstract}\n\n\\maketitle\n\n\\section{Introduction}\nThe implementation of the local flux mimetic method in MRST\n\\citep{MRST} is straightforward.  The most computationally demanding\nstep is the inversion of the mixed mass matrix which has much higer\ndiimension than the regular mixed or hybrid mass matrix.  From an\nimplementation poit of view, the construction of a numbering of the\nsub-faces with corresponding mappings to nodes, faces and cells is the\nmost complex.  Furthermore, the choosing to use this scheme as either\na mimetic method or a multi-point flux scheme puts certain limitations\non its use. In the former case, the scheme is quite coumputationally\ndemanding to assemble, store and handle, while in the latter case, the\ninclusion of gravity and forcings (bc, wells, src) is not solved\n(yet).\n\n\\section{Reducing mixed hybrid system to cell pressure system}\nConsider the elliptic equation for pressure, \n\\begin{align}\n  \\label{eq:pressure}\n  \\vect{v} + \\mat{K}\\nabla p  &=  0,\\\\\n  \\nabla\\cdot\\vect{v}        &= q,\n\\end{align}\nwhere $\\mat{K}$ is the permeability tensor, $p$ is the fluid pressure\nand $\\vect{v}$ is the fluid velocity.  To discretise\n\\eqref{eq:pressure} using a local-flux mimetic method, we start by\ndecribing the mass matrix $\\mat{B}$.  If $\\mat{B}$ is exact for linear\npressures, we can expect to get a consistent discretisation of\n\\eqref{eq:pressure}.  Thus, for any linear pressure $p = p_o +\n\\vect{c}\\cdot\\vect{x}$, we get the relation\n\\begin{equation}\n  \\label{ep:exactlinear}\n  \\mat{N}\\vect{c} = -\\mat{K}\\transp{\\mat{R}}\\vect{c},\n\\end{equation}\nwhere $\\mat{N}$ is the $n\\times d$ matrix of face normals and\n$\\mat{R}$ is the corresponding matrix of vectors from the cell centre,\nwhere the cell pressure is computed, to the face centres, where the\nface pressures are computed.  To get a local expression for the face\nflux, we make the following choices: We split each $k$-gonal face into\n$k$ sub-faces, each with one corner belonging to the face.  For each\nsub-face of face $i$ , we use $\\mat{N}_i$ and $\\mat{R}_i$ as normal\nand distance. Then, we require that $\\mat{B}$ be block-diagonal with\none block for each corner in the cell.  For a regular grid, each such\ncorner will be the intersection of $d$ sub-faces, and the\ncorresponding block in \\eqref{eq:exactlinear} will be unique.  Note\nthat this matrix is not symmetric, and $\\langle\\vect{F},\\vect{G}\\rangle =\n\\transp{\\vect{F}}\\mat{B}\\vect{G}$ is not an inner-product but a\nbilinear form on sub-face-fluxes.\n\nTo derive a cell-centered scheme from the definition of $\\mat{B}$, we\nstart with the usual mimetic mixed hybrid formulation\n\\begin{equation}\n  \\label{eq:hybLinSys}\n   \\begin{bmatrix}\n     \\mat{B} & \\mat{C} & \\mat{D}\\\\\n     \\transp{\\mat{C}}  & \\mat{0} & \\mat{0}\\\\\n     \\transp{\\mat{D}} &  \\mat{0} & \\mat{0}\n   \\end{bmatrix}\n   \\begin{bmatrix}\n     \\vect{v_H}\\\\ -\\vect{p}\\\\ \\vect{\\pi}\n   \\end{bmatrix}\n   =\n   \\begin{bmatrix}\n     \\vect{0} \\\\ \\vect{q}\\\\ \\vect{0}\n   \\end{bmatrix}\n\\end{equation}\nwhere $\\mat{C}$ is block-diagonal with blocks $\\vect{e} = (1,1,\\ldots,\n1)$, that adds up sub-faces, and $\\mat{D}$ maps from cell-wise\nordering to global ordering of sub-faces. We introduce $\\mat{D_o}$\nthat maps hybrid velocities to mixed velocities\n\\begin{equation}\n\\label {eq:hybrid2mixed}\n\\vect{v_h} = \\mat{D_o}\\vect{v_m}.\n\\end{equation}\nLeft-multiplying the first equation in \\eqref{eq:hybLinSys} by\n$\\transp{\\mat{D_o}}$, substituting \\eqref{eq:hybrid2mixed}, we get\n\\begin{align*}\n  &\\transp{\\mat{D_o}}\\mat{B}\\mat{D_o}\\vect{v_m} -\n  \\transp{\\mat{D_o}}\\mat{C}\\vect{p} + \n  \\transp {\\mat{D_o}}\\vect{\\pi}=\\vect{0}\\\\\n  &\\mat{C}\\mat{D_o}\\vect{v_m} = \\vect{q}.\n\\end{align*}\nIf we can invert $\\transp{\\mat{D_m}}\\mat{B}\\mat{D_m}$, the resulting\nlinear system for cell pressures is \n%\\begin{equation*}\n%  \\transp{\\mat{C}}\\mat{D_m}[\\transp{\\mat{D_m}}\\mat{B}\\mat{D_m}]^{-1}\n%         [\\transp{\\mat{D_m}}\\mat{C}\\vect{p}-\\transp{\\mat{D_m}}\\mat{D}\\vect{\\pi}] = q,\n%\\end{equation*}\n%that reduce to \n\\begin{equation}\n  \\transp{\\mat{C}}\\mat{D_o}[\\transp{\\mat{D_o}}\\mat{B}\\mat{D_o}]^{-1}\n         [\\transp{\\mat{D_o}}\\mat{C}\\vect{p}-\\vect{\\pi_b}] = q\n\\end{equation}\nwhere the boundary pressures $\\vect{\\pi_b}$ are the only nonzero\nentries of $\\transp{\\mat{D_o}}\\mat{D}\\vect{\\pi}$.  To get an\nexpression for the flux interms of cell-pressures, we introduce\n$\\mat{C} = \\mat{C_2}\\mat{C_1}$, where $\\mat{C_1}$ is block-diagonal\nwith as many rows as faces in the grid, and as many columns as\nsub-faces in the grid.  $\\mat{C}_1\\vect{v_H}$ adds the sub-face-fluxes\nof each face.  The other matrix $\\mat{C}_2$ is the standard mimetic\n$\\mat{C}$-matrix.  We can then write \n\\begin{equation*}\n  \\vect{v} = \\transp{\\mat{C}_1}\\mat{D_o}[\\transp{\\mat{D_o}}\\mat{B}\\mat{D_o}]^{-1}\n             [\\transp{\\mat{D_o}}\\mat{C}\\vect{p}-\\vect{\\pi_b}] \n\\end{equation*}\nand \n\\begin{equation*}\n  \\mat{T} = \\transp{\\mat{C}_1}\\mat{D_o}[\\transp{\\mat{D_o}}\\mat{B}\\mat{D_o}]^{-1}\n             \\begin{bmatrix}\\transp{\\mat{D_o}}\\mat{C}\\\\-\\mat{I}_b\\end{bmatrix}\n\\end{equation*}\n\n\\section{Local flux mimetic}\nThe crucial point in the previous section is the inversion of the\nmixed mass matrix $\\transp{\\mat{D_m}}\\mat{B}\\mat{D_m}$.  The\nconstruction of the local flux mimetic is based on two ideas that\nallow a cheap inversion of this matrix.  First, the number of degrees\nof freedom in the face pressures $\\vect{\\pi}$ and half-face velocities\n$\\vect{v_h}$ is increased to one pressure and velocity per face per\nnode. Thus, for a face with $n$ corners, there are $n$ facet pressures\nand velocities , one for each facet containing exactly one face\ncorner.\n\nSecond, the mass matrix $\\mat{B}$ defining the innerproduct between\ndiscrete facet fluxes chosen to be block-diagonal with one $d$ x $d$\nblock per node in the cell.  This inner product is uniqly defined if\n$d$ facets with linearly independent normals meet in each cell-node.\n\nInversion of the mixed mass matrix\n$\\transp{\\mat{D_m}}\\mat{B}\\mat{D_m}$ amounts to inverting the diagonal\nblocks corresponding to each node in the grid.  Note that this\ncorresponds exactly to the simplest multi-point flux approximation\ncalled the O-method [].  However, this derivation yields a simpler\nstarting point for implementation on general grids.\n\nTo get a multi-point flux transmissibility $\\mat{T}$, the\ncontributions from each facet must be added for each face in the grid.\n\n\n\n\n\n{\\bf How much does it matter if facet centriods are inaccurate?}\n\n\\bibliographystyle{abbrvnat}\n\\bibliography{misc}\n\n\\end{document}\n\n%{\nCopyright 2009-2018 SINTEF ICT, Applied Mathematics.\n\nThis file is part of The MATLAB Reservoir Simulation Toolbox (MRST).\n\nMRST is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nMRST is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with MRST.  If not, see <http://www.gnu.org/licenses/>.\n%}\n", "meta": {"hexsha": "9bf753bc24c7b3cf61fe7dd3a7925afac2076153", "size": 7920, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "mrst/mrst-2018a/modules/mpfa/doc/local_flux_mimetic.tex", "max_stars_repo_name": "LukasMosser/DeepFlow", "max_stars_repo_head_hexsha": "f9ca1f31113c5370472d74d468a35a9887fbc8d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2019-05-15T01:34:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-02T18:14:22.000Z", "max_issues_repo_path": "mrst/mrst-2018a/modules/mpfa/doc/local_flux_mimetic.tex", "max_issues_repo_name": "LukasMosser/DeepFlow", "max_issues_repo_head_hexsha": "f9ca1f31113c5370472d74d468a35a9887fbc8d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mrst/mrst-2018a/modules/mpfa/doc/local_flux_mimetic.tex", "max_forks_repo_name": "LukasMosser/DeepFlow", "max_forks_repo_head_hexsha": "f9ca1f31113c5370472d74d468a35a9887fbc8d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2019-05-15T09:41:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-09T03:57:02.000Z", "avg_line_length": 41.4659685864, "max_line_length": 86, "alphanum_fraction": 0.7178030303, "num_tokens": 2497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3353044931747285}}
{"text": "\\documentclass{article}\n\n% a bunch of useful packages.\n\\usepackage[inference]{semantic}\n\\usepackage{amsmath} \\allowdisplaybreaks % lets align equations break over pages.\n\\usepackage{hyperref}\n\\usepackage[amsmath,hyperref,amsthm]{ntheorem}\n\\usepackage{thmtools}\n\\usepackage[capitalize]{cleveref}\n\\usepackage{mathpartir}\n\\usepackage{stmaryrd}\n\\usepackage{amssymb}\n\\usepackage{latexsym}\n\\usepackage{color}\n\\usepackage[usenames,dvipsnames]{xcolor} % the best way to colour text\n\\usepackage[colorinlistoftodos]{todonotes} \n\\usepackage{tikz} \\usetikzlibrary{positioning,shadows,arrows,calc,backgrounds,fit,shapes,snakes,shapes.multipart,decorations.pathreplacing,shapes.misc,patterns}\n\\usepackage{xspace}\n\\usepackage{scalerel}\n\\usepackage{bm} %bold math. a mess to use.\n\\usepackage{bussproofs} % for logic-style proofs\n\n\\hypersetup{ pdfpagemode=UseOutlines, colorlinks=true, linkcolor=red, citecolor=blue }\n\n% organise your code.\n\\input{cmds}\n\n\\title{\n\tTypesetting $\\lambda$-calculi with \\LaTeX\n}\n\\author{\n\tMarco Patrignani\n}\n\\date{}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\t\t\t\t\t\t\tDOCUMENT\t\t\t\t\t\t  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\begin{document}\n\\maketitle\n\nThis document contains a reference of the syntax and semantics for ULC and STLC.\n\nSyntax highlighting is nice way to guide you in visually separating each language; please inform me whether they cause any distraught.\n\n\\begin{center}\n\t\\Large\n\tPlease read the latex comments too.\n\\end{center}\n\\tableofcontents\n\n\\newpage\n\n\\section{\\ulc: Untyped Lambda Calculus}\n\n\\subsection{Syntax}\n% all the stuff here is wrapped in \\com{}, which is the macro i use to typeset stuff in italics, black.\n% removing that macro won't change anything visually (though if later on you want to typeset all ULC in, say, red, it's easier this way)\n% unless you want to typeset coloured stuff, do not care for \\com{}, \\src{} and \\oth{} commands\n\n% \\mid are vertical separators\n% the align* environment will align on &, which are put after the ::=, with an extra \\ for space\n\\begin{align*}\n\t\\com{t} \\bnfdef&\\\n\t\t\\com{n} \\mid \\com{\\lam{x}{t}} \\mid \\com{x} \\mid \\com{t\\ t} \\mid \\com{t \\op t} % the \\ is a single space\n\t\\\\\n\t\\com{v} \\bnfdef&\\\n\t\t\\com{n} \\mid \\com{\\lam{x}{t}}\n\t\\\\\n\t\\com{\\Omega} \\bnfdef&\\\n\t\t\\com{t} \\mid \\com{\\fail}\n\t\\\\\n\t\\com{\\evalctx} \\bnfdef&\\\n\t\t\\com{\\hole{\\cdot}} \\mid \\com{\\evalctx\\ t} \\mid \\com{(\\lam{x}{t})\\ \\evalctx} \\mid \\com{\\evalctx \\op t} \\mid \\com{n \\op \\evalctx}\n\\end{align*}\n$\\op$ ranges over $+, -, *$.\n\n\\subsection{Structural Operational Semantics}\n\n\\subsubsection{Small Step, Call by Value (SSV)}\n\\begin{align*}\n\t\\com{\\Omega\\red\\Omega} \n\t&&\n\t\\text{ judgement }\n\\end{align*}\nReductions.\n% inference rules are best put centered, with this environment\n\\begin{center}\n\t% this command is for generic inference rules. \n\t% the 4th parameter is the label, which gets referred as    tr:ssv-beta    in the first case, i.e., always add a   tr:   to what is between brackets\n\t\\typerule{SSV-Beta}{}{\n\t\t\\com{(\\lam{x}{t})~v \\red t\\subst{v}{x}}\n\t}{ssv-beta}\n\t\\typerule{SSV-Op}{}{\n\t\t\\com{n\\op n' \\red n\\llbracket\\op\\rrbracket n'} \t% llbracket rrbracket should be made into a command. try it.\n\t}{ssv-op}\n\t\\typerule{SSV-App1}{\n\t\t\\com{t_1\\red t_1'}\n\t}{\n\t\t\\com{t_1\\ t_2 \\red t_1' t_2}\n\t}{ssv-app1}\n\t\\typerule{SSV-App2}{\n\t\t\\com{t_2\\red t_2'}\n\t}{\n\t\t\\com{(\\lam{x}{t})\\ t_2 \\red (\\lam{x}{t})\\ t_2'}\n\t}{ssv-app2}\n\t\\typerule{SSV-Op1}{\n\t\t\\com{t_1\\red t_1'}\n\t}{\n\t\t\\com{t_1\\op t_2 \\red t_1'\\op t_2}\n\t}{ssv-op1}\n\t\\typerule{SSV-Op2}{\n\t\t\\com{t_2\\red t_2'}\n\t}{\n\t\t\\com{n\\op t_2 \\red n\\op t_2'}\n\t}{ssv-op2}\n\\end{center}\nFail reductions.\n\\begin{center}\n\t\\typerule{SSV-Op-fail-l}{}{\n\t\t\\com{(\\lam{x}{t})\\op t \\red\\fail}\n\t}{ssv-f-opl}\n\t\\typerule{SSV-Op-fail-r}{}{\n\t\t\\com{n\\ \\op(\\lam{x}{t}) \\red\\fail}\n\t}{ssv-f-opr}\n\t\\typerule{SSV-App-fail-fun}{}{\n\t\t\\com{n\\ t\\red\\fail}\n\t}{ssv-f-fun}\n\t\\typerule{SSV-App-fail-arg}{\n\t\t\\com{t_2\\red\\fail}\n\t}{\n\t\t\\com{(\\lam{x}{t})\\ t_2\\red\\fail}\n\t}{ssv-f-arg}\n\t\\typerule{SSV-App-fail-1}{\n\t\t\\com{t_1\\red\\fail}\n\t}{\n\t\t\\com{t_1\\ t_2\\red\\fail}\n\t}{ssv-f-app}\n\t\\typerule{SSV-Op-fail-1}{\n\t\t\\com{t_1\\red\\fail}\n\t}{\n\t\t\\com{t_1\\op t_2\\red\\fail}\n\t}{ssv-f-op1}\n\t\\typerule{SSV-Op-fail-2}{\n\t\t\\com{t_2\\red\\fail}\n\t}{\n\t\t\\com{n\\op t_2\\red\\fail}\n\t}{ssv-f-op2}\n\\end{center}\n\n\\subsubsection{Small Step, Call by Name (SSN)}\nRemove \\Cref{tr:ssv-app2} and replace \\Cref{tr:ssv-beta} with:\n\\begin{center}\n\t\\typerule{SSN-Beta}{}{\n\t\t\\com{(\\lam{x}{t})~t' \\red t\\subst{t'}{x}}\n\t}{ssn-beta}\n\\end{center}\n\n\\subsubsection{Big Step, Call by Value (SBV)}\n\\begin{align*}\n\t\\com{\\Omega\\bigs\\Omega} \n\t&&\n\t\\text{ judgement }\n\\end{align*}\nReductions.\nReductions for failing are omitted.\n\\begin{center}\n\t\\typerule{SBV-val}{}{\n\t\t\\com{v \\bigs v}\n\t}{sbv-val}\n\t\\typerule{SBV-op}{\n\t\t\\com{t \\bigs n }\n\t\t&\n\t\t\\com{t' \\bigs n'}\n\t}{\n\t\t\\com{t \\op t' \\bigs n \\llbracket \\op \\rrbracket n'}\n\t}{sbv-op}\n\t\\typerule{SBV-app}{\n\t\t\\com{t \\bigs \\lam{x}{t''}}\n\t\t&\n\t\t\\com{t' \\bigs v}\n\t\t&\n\t\t\\com{t''\\subst{v}{x} \\bigs v'}\n\t}{\n\t\t\\com{t\\ t' \\bigs v'}\n\t}{sbv-app}\n\\end{center}\n\n\\subsection{Contextual Operational Semantics, Call by Value (CSV)}\n\\begin{align*}\n\t\\com{\\Omega\\cred\\Omega} \n\t&&\n\t\\text{ judgement }\n\t\\\\\n\t\\com{\\Omega\\credp\\Omega} \n\t&&\n\t\\text{ judgement }\n\\end{align*}\nReductions.\nReductions for failing are omitted.\n\\begin{center}\n\t\\typerule{CSV-ctx}{\n\t\t\\com{t \\credp t'}\n\t}{\n\t\t\\com{\\evalctx\\hole{t} \\cred \\evalctx\\hole{t'}}\n\t}{csv-ctx}\n\\end{center}\nPlus \\Cref{tr:ssv-beta,tr:ssv-op}, changing $\\red$ with $\\credp$. \n\n\\section{\\stlc: Simply-Typed Lambda Calculus}\n\\subsection{Syntax}\nNo changes save for program state.\n\\begin{align*}\n\t\\src{\\Omega} \\bnfdef&\\\n\t\t\\src{t}\n\t\\\\\n\t\\src{\\Gamma} \\bnfdef&\\\n\t\t\\srce \\mid \\src{\\Gamma},(\\src{x:\\tau})\n\t\\\\\n\t\\src{\\tau} \\bnfdef&\\\n\t\t\\src{N} \\mid \\src{\\tau\\to\\tau}\n\\end{align*}\n\n\\subsection{Static Semantics}\n\\begin{align*}\n\t\\src{\\Gamma}\\vdash\\src{t}:\\src{\\tau} \n\t&&\n\t\\text{ judgement }\n\\end{align*}\nReductions.\n\\begin{center}\n\t\\typerule{Type-var}{\n\t\t\\src{x:\\tau}\\in\\src{\\Gamma}\n\t}{\n\t\t\\src{\\Gamma}\\vdash\\src{x}:\\src{\\tau}\n\t}{t-stlc-var}\n\t\\typerule{Type-lam}{\n\t\t\\src{\\Gamma},\\src{x:\\tau}\\vdash\\src{t}:\\src{\\tau'}\n\t}{\n\t\t\\src{\\Gamma}\\vdash\\src{\\lam{x:\\tau}{t}}:\\src{\\tau\\to\\tau'}\n\t}{t-stlc-lam}\n\t\\typerule{Type-num}{\n\t}{\n\t\t\\src{\\Gamma}\\vdash\\src{n}:\\src{N}\n\t}{t-stlc-num}\n\t\\typerule{Type-app}{\n\t\t\\src{\\Gamma}\\vdash\\src{t}:\\src{\\tau'\\to\\tau}\n\t\t&\n\t\t\\src{\\Gamma}\\vdash\\src{t'}:\\src{\\tau'}\n\t}{\n\t\t\\src{\\Gamma}\\vdash\\src{t\\ t'}:\\src{\\tau}\n\t}{t-stlc-app}\n\t\\typerule{Type-op}{\n\t\t\\src{\\Gamma}\\vdash\\src{t}:\\src{N}\n\t\t&\n\t\t\\src{\\Gamma}\\vdash\\src{t'}:\\src{N}\n\t}{\n\t\t\\src{\\Gamma}\\vdash\\src{t\\ t'}:\\src{N}\n\t}{t-stlc-op}\n\\end{center}\n\n\\subsection{Contextual Operational Semantics, Call by Value (CSV)}\nNo changes, repeated for clarity.\n\\begin{align*}\n\t\\src{\\Omega\\cred\\Omega} \n\t&&\n\t\\text{ judgement }\n\t\\\\\n\t\\src{\\Omega\\credp\\Omega} \n\t&&\n\t\\text{ judgement }\n\\end{align*}\nReductions.\nNo reductions for failing.\n\\begin{center}\n\t\\typerule{CSV-ctx}{\n\t\t\\src{t \\credp t'}\n\t}{\n\t\t\\src{\\evalctx\\hole{t} \\cred \\evalctx\\hole{t'}}\n\t}{csv-stlc-ctx}\n\t\\typerule{CSV-Beta}{}{\n\t\t\\src{(\\lam{x}{t})~v \\credp t\\subs{v}{x}}\n\t}{ssv-stlc-beta}\n\t\\typerule{CSV-Op}{}{\n\t\t\\src{n\\op n' \\credp n\\llbracket\\op\\rrbracket n'}\n\t}{ssv-srlc-op}\n\\end{center}\n\n\\end{document}", "meta": {"hexsha": "f6fa2137cf97d3169cdfe5e8392d076b4299c336", "size": 7528, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Docs/LaTex/langref.tex", "max_stars_repo_name": "erszcz/ETC", "max_stars_repo_head_hexsha": "677c763d93fae7fdc326cd9e028c0f59f1803037", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-06-28T14:17:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T14:44:41.000Z", "max_issues_repo_path": "Docs/LaTex/langref.tex", "max_issues_repo_name": "erszcz/ETC", "max_issues_repo_head_hexsha": "677c763d93fae7fdc326cd9e028c0f59f1803037", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-23T17:02:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-23T17:02:20.000Z", "max_forks_repo_path": "Docs/LaTex/langref.tex", "max_forks_repo_name": "erszcz/ETC", "max_forks_repo_head_hexsha": "677c763d93fae7fdc326cd9e028c0f59f1803037", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-29T16:39:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T16:39:16.000Z", "avg_line_length": 25.9586206897, "max_line_length": 177, "alphanum_fraction": 0.6138416578, "num_tokens": 2855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.3353044898312257}}
{"text": "%!TEX root = ../../dissertation.tex\n\n\\section{Tables and Figures}\n\n\n%\n% Tables\n%\n\\subsection{Tables}\n\n  \\begin{table}[H]\n    \\begin{tabular}{lll}\n      \\toprule\n      \\textbf{Parameter Name} & \\textbf{Value} & \\textbf{Source} \\\\\n      \\midrule\n      $\\beta$ & 0.98 & Standard \\\\\n      $r$ & 0.04 & \\\\\n      \\midrule\n      $T$ & 42 & Retirement at 60 \\\\\n      \\midrule\n      $\\tau, \\lambda$ & 0.118, 1.07 & \\cite{HeathcoteStoreslettenViolante2017} \\\\\n      \\midrule\n      $\\sigma^{HS, w}, \\sigma^{CD, w}, \\sigma^{CG, w}$ & $\\sqrt{0.011}, \\sqrt{0.011}, \\sqrt{0.0099}$ & \\cite{Guvenen2009}, \\cite{CarrollSamwick1997} \\\\\n      $\\sigma^{HS, y}, \\sigma^{CD, y}, \\sigma^{CG, y}$ & $\\sqrt{0.052}, \\sqrt{0.052}, \\sqrt{0.047}$ & \\\\\n      \\midrule\n      $\\phi_{HS}, \\phi_{CD}, \\phi_{CG}$ & 0.15, 0.15, 0.197 & \\cite{HendricksLeukhina2017} \\\\\n      $\\mu, w_{\\text{coll}}$ & 0.010, 3.55 & \\\\\n      $\\gamma_\\text{min}, \\gamma_1, \\gamma_2$ & 0.47, 4.58, 2.10 & \\\\\n      $\\alpha_{am}$, $\\alpha_{m,GPA}$ & 2.87, 1.2 & \\\\\n      $\\alpha_{kq}$, $\\alpha_{mq}$, $\\alpha_{mz}$, $\\alpha_{qz}$ & 0.0, -0.04, 0.46, -0.12 & \\\\\n      $\\mu_q$, $\\sigma_q$ & 0.53, 0.35 & \\\\\n      $\\mu_z$, $\\sigma_z$ & 0.32, 0.55 & \\\\\n      \\bottomrule\n    \\end{tabular}\n    \\caption{Previous Knowledge Parameters}\n    \\label{table:pk}\n  \\end{table}\n\n  \\begin{table}[H]\n    \\begin{tabular}{lll}\n      \\toprule\n      \\textbf{Parameter Name} & \\textbf{Value} & \\textbf{Source} \\\\\n      \\midrule\n      $\\bar{\\theta}^{HS}$, $\\bar{\\theta}^{CG}$ & 8.73, 5.06 & \\cite{PSID} \\\\\n      $\\theta_1^{HS}$, $\\theta_2^{HS}$, $\\theta_3^{HS}$ & 0.066, -0.088, 0.002 & \\\\\n      $\\theta_1^{CG}$, $\\theta_2^{CG}$, $\\theta_3^{CG}$ & 0.324, -0.624, 0.039 & \\\\\n      \\midrule\n      $\\bar{T}_C$ & 6 & College features \\\\\n      $n_c$ & 6 & \\\\\n      $n_{\\text{grad}}$ & 21 & \\\\\n      $\\underbar{d}$, $\\underbar{D}$ & -0.5, -1.975 & \\\\\n      \\bottomrule\n    \\end{tabular}\n    \\caption{Externally Calibrated Parameters}\n    \\label{table:ec}\n  \\end{table}\n\n  \\begin{table}[H]\n    \\begin{tabular}{lll}\n      \\toprule\n      \\textbf{Parameter Name} & \\textbf{Value} & \\textbf{Target} \\\\\n      \\midrule\n      $\\delta_c$, $\\delta_v$ & 0.62, 1.15 & Debt accumulation \\\\\n      $U_{HS}$, $U_{CD}$, $U_{CG}$ & 0.0, -2.97, -6.81 & Enrollment \\\\\n      $\\alpha_{km}$, $\\mu_k$, $\\sigma_k$ & 0.55, 2.57, 3.94 & Fraction with debt \\\\\n      $\\pi_e$, $\\pi_c$ & 0.30, 1.58 & Enrollment and dropout \\\\\n      \\bottomrule\n    \\end{tabular}\n    \\caption{Internally Calibrated Parameters}\n    \\label{table:ic}\n  \\end{table}\n\n  \\begin{table}[H]\n    \\begin{tabular}{lccll}\n      \\toprule\n      \\multicolumn{3}{c}{\\textbf{Moment Descriptions}} & \\textbf{Data} & \\textbf{Model} \\\\\n      \\midrule\n      \\textbf{Name} & \\textbf{Year} & \\textbf{GPA Quartile} & & \\\\\n      \\midrule\n      Time to degree & --- & --- & 4.45 & 4.73 \\\\\n      Education Fraction (HS) & --- & --- & 0.52 & 0.53 \\\\\n      Education Fraction (CD) & --- & --- & 0.23 & 0.21 \\\\\n      Education Fraction (CG) & --- & --- & 0.25 & 0.26 \\\\\n      \\midrule\n      Enrollment & --- & Quartile 1 & 0.22 & 0.18 \\\\\n                 & --- & Quartile 2 & 0.35 & 0.35 \\\\\n                 & --- & Quartile 3 & 0.55 & 0.55 \\\\\n                 & --- & Quartile 4 & 0.81 & 0.81 \\\\\n      \\midrule\n      Completion & --- & Quartile 1 & 0.02 & 0.03 \\\\\n                 & --- & Quartile 2 & 0.08 & 0.13 \\\\\n                 & --- & Quartile 3 & 0.28 & 0.30 \\\\\n                 & --- & Quartile 4 & 0.60 & 0.60 \\\\\n      \\midrule\n      College Earnings & --- & Quartile 1 & 0.65 & 0.85 \\\\\n                       & --- & Quartile 2 & 0.58 & 0.70 \\\\\n                       & --- & Quartile 3 & 0.54 & 0.59 \\\\\n                       & --- & Quartile 4 & 0.51 & 0.43 \\\\\n      \\midrule\n      Average debt & Year 1 & --- & 0.35 & 0.33 \\\\\n                   & Year 2 & --- & 0.59 & 0.50 \\\\\n                   & Year 3 & --- & 0.78 & 0.75 \\\\\n                   & Year 4 & --- & 0.95 & 1.06 \\\\\n      \\midrule\n      Fraction with debt & Year 1 & --- & 0.26 & 0.11 \\\\\n                         & Year 2 & --- & 0.34 & 0.27 \\\\\n                         & Year 3 & --- & 0.41 & 0.42 \\\\\n                         & Year 4 & --- & 0.48 & 0.52 \\\\\n      \\midrule\n      Drop out & Year 1 & --- & 0.16 & 0.15 \\\\\n               & Year 2 & --- & 0.14 & 0.10 \\\\\n               & Year 3 & --- & 0.08 & 0.07 \\\\\n               & Year 4 & --- & 0.05 & 0.05 \\\\\n               & Year 5 & --- & 0.02 & 0.03 \\\\\n      \\bottomrule\n    \\end{tabular}\n    \\caption{Data and model moments}\n    \\label{table:moments}\n  \\end{table}\n\n  \\begin{table}[H]\n    \\begin{tabular}{llll}\n      \\toprule\n      & \\textbf{AMR} & \\textbf{LC} & \\textbf{IDR} \\\\\n      \\midrule\n      Enrollment rate & 0.48 & 0.48 & 0.49 \\\\\n      Completion rate & 0.27 & 0.27 & 0.27 \\\\\n      Graduation rate & 0.56 & 0.56 & 0.56 \\\\\n      \\bottomrule\n    \\end{tabular}\n    \\caption{Student outcomes under different versions of our economy}\n    \\label{table:students}\n  \\end{table}\n\n  \\begin{table}[H]\n    \\begin{tabular}{llll}\n      \\toprule\n      & \\textbf{AMR} & \\textbf{LC} & \\textbf{IDR} \\\\\n      \\midrule\n      Fraction with debt & 0.46 & 0.46 & 0.70 \\\\\n      Average debt & \\$11,750 & \\$11,750 & \\$13,740 \\\\\n      \\bottomrule\n    \\end{tabular}\n    \\caption{Student debt decisions under plans}\n    \\label{table:debt}\n  \\end{table}\n\n  \\begin{table}[H]\n    \\begin{tabular}{llll}\n      \\toprule\n      & \\textbf{AMR} & \\textbf{LC} & \\textbf{IDR} \\\\\n      \\midrule\n      Subsidy rate & -0.13 & -0.12 & -0.06 \\\\\n      Government subsidy (per person) & -\\$0.085 & -\\$0.077 & -\\$0.072 \\\\\n      \\bottomrule\n    \\end{tabular}\n    \\caption{Government subsidy rates and per person subsidy}\n    \\label{table:cost}\n  \\end{table}\n\n  \\begin{table}[H]\n    \\begin{tabular}{lll}\n      \\toprule\n      & \\textbf{AMR} & \\textbf{IDR} \\\\\n      \\midrule\n      Quartile 1 & -0.13 & 0.11 \\\\\n      Quartile 2 & -0.13 & -0.01 \\\\\n      Quartile 3 & -0.13 & -0.07 \\\\\n      Quartile 4 & -0.13 & -0.11 \\\\\n      \\bottomrule\n    \\end{tabular}\n    \\caption{Government subsidy rates by HS GPA quartile}\n    \\label{table:subsidy_gpa}\n  \\end{table}\n\n\\clearpage\n\\newpage\n\n%\n% Figures\n%\n\\subsection{Figures}\n\n  \\begin{center}\n    \\begin{figure}[H]\n      \\includegraphics[width=\\textwidth]{images/StudentLoans/idr_enrollment_ts.pdf}\n      \\caption{\n        This figure shows how the enrollment in IDR has changed over last 4 years\n        \\tiny{Source: U.S. Department of Education, Federal Student Aid Data Center, Federal Student Loan Portfolio.}\n      }\n      \\label{fig:idr_enrollment}\n    \\end{figure}\n  \\end{center}\n\n  \\begin{center}\n    \\begin{figure}[H]\n      \\includegraphics[width=\\textwidth]{images/StudentLoans/example_loan_repayment.pdf}\n      \\caption{\n        This figure shows how the repayment burden and repayment amount differ for the AMR\n        and IDR student loan repayment plans. It also plots the history of income for the example\n        individual.\n      }\n      \\label{fig:loan_repayment}\n    \\end{figure}\n  \\end{center}\n\n  \\begin{center}\n    \\begin{figure}[H]\n      \\includegraphics[width=\\textwidth]{images/StudentLoans/GovSubsidy_Original_v_Revised.pdf}\n      \\caption{\n        This figure shows the original subsidy estimate alongside the 2017 updated estimate.\n        \\tiny{Source: GAO analysis of the U.S. Department of Educations' 2011-2017 budget estimates}\n      }\n      \\label{fig:subsidy_original_v_revised}\n    \\end{figure}\n  \\end{center}\n\n  \\begin{center}\n    \\begin{figure}[H]\n      \\includegraphics[width=\\textwidth]{images/StudentLoans/ep_vs_p.pdf}\n      \\caption{\n        {\\small This figure shows the difference between the value function under the IDR and AMR plans for\n        a college dropout 3 periods after leaving college. Behind the line is the probability\n        distribution over income levels is plotted.}\n      }\n      \\label{fig:scatter_ep_vs_p}\n    \\end{figure}\n  \\end{center}\n\n  \\begin{center}\n    \\begin{figure}[H]\n      \\includegraphics[width=\\textwidth]{images/StudentLoans/vf_vs_income_probs.pdf}\n      \\caption{\n        {\\small This figure shows the difference between the value function under the IDR and AMR plans for\n        a college dropout 3 periods after leaving college. Behind the line is the probability\n        distribution over income levels is plotted.}\n      }\n      \\label{fig:vfs_enrollment}\n    \\end{figure}\n  \\end{center}\n\n  \\begin{center}\n    \\begin{figure}[H]\n      \\includegraphics[width=\\textwidth]{images/StudentLoans/DebtByGPA.pdf}\n      \\caption{\n        {\\small This figure shows the differences in average debt among those who have positive\n        student loans and the fraction of college students who borrow for the AMR and IDR plans}\n      }\n      \\label{fig:debt_by_gpa}\n    \\end{figure}\n  \\end{center}\n\n  \\begin{center}\n    \\begin{figure}[H]\n      \\includegraphics[width=\\textwidth]{images/StudentLoans/expected_repayment.pdf}\n      \\caption{\n        {\\small This figure shows the fraction of a student loan that is expected to be repaid for\n        AMR and IDR across different loan sizes.}\n      }\n      \\label{fig:expected_repayment}\n    \\end{figure}\n  \\end{center}\n", "meta": {"hexsha": "813b714df6d590b19758a8e2e0f370d40920d79c", "size": 9099, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ms/sections/StudentLoans/tables_and_figs.tex", "max_stars_repo_name": "cc7768/Dissertation", "max_stars_repo_head_hexsha": "813210c2f92122bb0c05f6ad7f5a9ede04993781", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ms/sections/StudentLoans/tables_and_figs.tex", "max_issues_repo_name": "cc7768/Dissertation", "max_issues_repo_head_hexsha": "813210c2f92122bb0c05f6ad7f5a9ede04993781", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ms/sections/StudentLoans/tables_and_figs.tex", "max_forks_repo_name": "cc7768/Dissertation", "max_forks_repo_head_hexsha": "813210c2f92122bb0c05f6ad7f5a9ede04993781", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-12-31T22:54:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-03T18:48:22.000Z", "avg_line_length": 34.5969581749, "max_line_length": 151, "alphanum_fraction": 0.5509396637, "num_tokens": 3066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.33530448648772276}}
{"text": "\\def\\module{M4P58 Modular Forms}\n\\def\\lecturer{Dr David Helm}\n\\def\\term{Autumn 2019}\n\\def\\cover{\n$$\n\\begin{tikzpicture}[scale=3]\n\\draw [help lines] (-2.5, 0) grid (2.5, 3.5);\n\\draw [->, dashed, very thick] (-2.5, 0) to (2.5, 0);\n\\draw [->, dashed, very thick] (0, 0) to (0, 4);\n\\draw (-2, 0) arc (0:60:1);\n\\draw (-1, 0) arc (0:120:1);\n\\draw (-2, 0) arc (180:0:1);\n\\draw (-1, 0) arc (180:0:1);\n\\draw (0, 0) arc (180:0:1);\n\\draw (1, 0) arc (180:60:1);\n\\draw (2, 0) arc (180:120:1);\n\\draw (-2.45, 0) arc (0:30:0.35);\n\\draw (-2.1, 0) arc (0:100:0.35);\n\\draw (-2.45, 0) arc (180:0:0.35);\n\\draw (-2.1, 0) arc (180:0:0.35);\n\\draw (-1.75, 0) arc (180:0:0.35);\n\\draw (-1.4, 0) arc (180:0:0.35);\n\\draw (-1.05, 0) arc (180:0:0.35);\n\\draw (-0.7, 0) arc (180:0:0.35);\n\\draw (-0.35, 0) arc (180:0:0.35);\n\\draw (0, 0) arc (180:0:0.35);\n\\draw (0.35, 0) arc (180:0:0.35);\n\\draw (0.7, 0) arc (180:0:0.35);\n\\draw (1.05, 0) arc (180:0:0.35);\n\\draw (1.4, 0) arc (180:0:0.35);\n\\draw (1.75, 0) arc (180:0:0.35);\n\\draw (2.1, 0) arc (180:80:0.35);\n\\draw (2.45, 0) arc (180:150:0.35);\n\\draw (-2.4, 0) arc (0:70:0.15);\n\\draw (-2.25, 0) arc (0:140:0.15);\n\\draw (-2.4, 0) arc (180:0:0.15);\n\\draw (-2.25, 0) arc (180:0:0.15);\n\\draw (-2.1, 0) arc (180:0:0.15);\n\\draw (-1.95, 0) arc (180:0:0.15);\n\\draw (-1.8, 0) arc (180:0:0.15);\n\\draw (-1.65, 0) arc (180:0:0.15);\n\\draw (-1.5, 0) arc (180:0:0.15);\n\\draw (-1.35, 0) arc (180:0:0.15);\n\\draw (-1.2, 0) arc (180:0:0.15);\n\\draw (-1.05, 0) arc (180:0:0.15);\n\\draw (-0.9, 0) arc (180:0:0.15);\n\\draw (-0.75, 0) arc (180:0:0.15);\n\\draw (-0.6, 0) arc (180:0:0.15);\n\\draw (-0.45, 0) arc (180:0:0.15);\n\\draw (-0.3, 0) arc (180:0:0.15);\n\\draw (-0.15, 0) arc (180:0:0.15);\n\\draw (0, 0) arc (180:0:0.15);\n\\draw (0.15, 0) arc (180:0:0.15);\n\\draw (0.3, 0) arc (180:0:0.15);\n\\draw (0.45, 0) arc (180:0:0.15);\n\\draw (0.6, 0) arc (180:0:0.15);\n\\draw (0.75, 0) arc (180:0:0.15);\n\\draw (0.9, 0) arc (180:0:0.15);\n\\draw (1.05, 0) arc (180:0:0.15);\n\\draw (1.2, 0) arc (180:0:0.15);\n\\draw (1.35, 0) arc (180:0:0.15);\n\\draw (1.5, 0) arc (180:0:0.15);\n\\draw (1.65, 0) arc (180:0:0.15);\n\\draw (1.8, 0) arc (180:0:0.15);\n\\draw (1.95, 0) arc (180:0:0.15);\n\\draw (2.1, 0) arc (180:0:0.15);\n\\draw (2.25, 0) arc (180:40:0.15);\n\\draw (2.4, 0) arc (180:110:0.15);\n\\draw (-1.5, 0) to (-1.5, 3.5);\n\\draw (-0.5, 0) to (-0.5, 3.5);\n\\draw (0.5, 0) to (0.5, 3.5);\n\\draw (1.5, 0) to (1.5, 3.5);\n\\draw [very thick] (-0.5, 0.866) arc (120:60:1);\n\\draw [very thick] (-1.5, 0.866) arc (120:60:1);\n\\draw [very thick] (0.5, 0.866) arc (120:60:1);\n\\draw [->, very thick] (-1.5, 0.866) to (-1.5, 3);\n\\draw [->, very thick] (-0.5, 0.866) to (-0.5, 3);\n\\draw [->, very thick] (0.5, 0.866) to (0.5, 3);\n\\draw [->, very thick] (1.5, 0.866) to (1.5, 3);\n\\draw (0, -0.5) node{$ \\DDD = \\cbr{z \\in \\HH \\st \\tfrac{1}{2} \\le \\Re z \\le \\tfrac{1}{2}, \\ \\abs{z} \\ge 1} \\subseteq \\HH $};\n\\end{tikzpicture}\n$$\n}\n\\def\\syllabus{Modular forms of level one. Eisenstein series. Spaces of modular forms of level one. Theta series. Hecke operators of level one. $ \\L $-functions of level one. Modular forms of higher level. Spaces of modular forms of higher level. Hecke operators of higher level. $ \\L $-functions of higher level. Oldforms and newforms.}\n\\def\\thm{subsection}\n\n\\input{../style/header}\n\n% Macros\n\\newcommand{\\twobytwosmall}[4]{\n  \\begin{psmallmatrix}\n    #1 & #2 \\\\\n    #3 & #4\n  \\end{psmallmatrix}\n}\n\n\\begin{document}\n\n\\input{../style/cover}\n\n\\section{Introduction}\n\n\\lecture{1}{Friday}{04/10/19}\n\nThe following are textbooks.\n\\begin{itemize}\n\\item Serre, A course in arithmetic, 1973\n\\item J Shurman and F Diamond, A first course in modular forms, 2005\n\\end{itemize}\n\nLet\n$$ f = q\\prod_{n = 1}^\\infty \\br{1 - q^n}^2\\br{1 - q^{11n}}^2 = \\sum_{n = 1} b_nq^n = q - 2q^2 - q^3 + 2q^4 + q^5 + 2q^6 - 2q^7 + \\dots, $$\nand let $ a_n $ be the number of solutions modulo $ n $ to the elliptic curve\n$$ E = \\cbr{\\br{x, y} \\in \\ZZ \\st y^2 + y = x^3 - x^2 - 10x - 20}. $$\n\\begin{itemize}\n\\item Modulo $ 2 $, there are $ a_2 = 4 $ solutions $ \\br{0, 0} $, $ \\br{0, 1} $, $ \\br{1, 0} $, $ \\br{1, 1} $.\n\\item Modulo $ 3 $, there are $ a_3 = 4 $ solutions $ \\br{1, 0} $, $ \\br{1, -1} $, $ \\br{-1, 0} $, $ \\br{-1, -1} $.\n\\item Modulo $ 5 $, there are $ a_5 = 4 $ solutions $ \\br{0, 0} $, $ \\br{0, -1} $, $ \\br{1, 0} $, $ \\br{1, -1} $.\n\\item Modulo $ 7 $, there are $ a_7 = 9 $ solutions $ \\br{1, 3} $, $ \\br{2, 2} $, $ \\br{2, -3} $, $ \\br{-1, 1} $, $ \\br{-1, -2} $, $ \\br{-2, 1} $, $ \\br{-2, -2} $, $ \\br{-3, 1} $, $ \\br{-3, -2} $.\n\\end{itemize}\nIf $ p \\ne 11 $, then\n$$ a_p - p = -b_p. $$\nThe following are some questions.\n\\begin{itemize}\n\\item What is the relationship between $ E $ and $ f $?\n\\item Can we find similar relationships for other $ E $?\n\\item How does one prove something like this?\n\\end{itemize}\nLet\n$$ \\HH = \\cbr{x + iy \\st x, y \\in \\RR, \\ y > 0} \\subseteq \\CC. $$\nThen $ \\HH $ has an action of\n$$ \\SL_2\\br{\\RR} = \\cbr{\\twobytwo{a}{b}{c}{d} \\st a, b, c, d \\in \\RR, \\ ad - bc = 1}. $$\nModular forms are complex functions on $ \\HH $ with a high degree of symmetry. These functions are symmetric under the action of large discrete subgroups of $ \\SL_2\\br{\\RR} $, in particular\n$$ \\SL_2\\br{\\ZZ} = \\cbr{\\twobytwo{a}{b}{c}{d} \\st a, b, c, d \\in \\ZZ, \\ ad - bc = 1} \\subseteq \\SL_2\\br{\\RR}. $$\nWhy are these interesting to number theorists? Power series expansions often involve expressions of interest to number theorists. For example,\n\\begin{itemize}\n\\item Bernoulli numbers,\n\\item divisor functions $ \\sigma_k\\br{n} = \\sum_{d \\mid n} d^k $,\n\\item number of points on elliptic curves, and\n\\item traces of Galois representations.\n\\end{itemize}\n\n\\pagebreak\n\n\\section{Modular forms of level one}\n\n\\subsection{Modular forms}\n\n\\subsubsection{Modular actions}\n\n$ \\SL_2\\br{\\RR} $ acts on $ \\CC \\cup \\cbr{\\infty} $ by\n$$ \\twobytwo{a}{b}{c}{d} \\cdot z =\n\\begin{cases}\n\\dfrac{az + b}{cz + d} & z \\ne -\\dfrac{d}{c} \\\\\n\\infty & z = -\\dfrac{d}{c} \\\\\n\\dfrac{a}{c} & z = \\infty\n\\end{cases}.\n$$\nOne checks that this gives a bijection from $ \\CC \\cup \\cbr{\\infty} $ to $ \\CC \\cup \\cbr{\\infty} $, where the inverse is given by the inverse matrix $ \\twobytwosmall{d}{-b}{-c}{a} $, and\n$$ \\twobytwo{a}{b}{c}{d} \\cdot \\br{\\twobytwo{a'}{b'}{c'}{d'} \\cdot z} = \\twobytwo{a}{b}{c}{d}\\twobytwo{a'}{b'}{c'}{d'} \\cdot z. $$\nOne obtains a left action of $ \\SL_2\\br{\\RR} $ on $ \\CC \\cup \\cbr{\\infty} $. An observation is\n$$ \\Im \\twobytwo{a}{b}{c}{d}z = \\Im \\dfrac{az + b}{cz + d} = \\Im \\dfrac{\\br{az + b}\\br{c\\overline{z} + d}}{\\abs{cz + d}^2} = \\dfrac{\\Im \\br{az + b}\\br{c\\overline{z} + d}}{\\abs{cz + d}^2} = \\dfrac{\\br{ad - bc}\\Im z}{\\abs{cz + d}^2}. $$\nIn particular, if $ \\gamma = \\twobytwosmall{a}{b}{c}{d} \\in \\SL_2\\br{\\RR} $, then\n$$ \\Im \\gamma z = \\dfrac{\\Im z}{\\abs{cz + d}^2}. $$\nSo $ \\SL_2\\br{\\RR} $ preserves $ \\HH \\cup \\cbr{\\infty} $. More generally, if\n$$ \\gamma = \\twobytwo{a}{b}{c}{d} \\in \\GL_2\\br{\\RR} = \\cbr{\\twobytwo{a}{b}{c}{d} \\st a, b, c, d \\in \\RR, \\ ad - bc \\ne 0}, $$\nthen\n$$ \\Im \\gamma z = \\dfrac{\\det \\gamma\\Im z}{\\abs{cz + d}^2}. $$\nSo\n$$ \\GL_2\\br{\\RR}_+ = \\cbr{\\twobytwo{a}{b}{c}{d} \\st a, b, c, d \\in \\RR, \\ ad - bc > 0} $$\npreserves $ \\HH \\cup \\cbr{\\infty} $.\n\n\\lecture{2}{Friday}{04/10/19}\n\n\\begin{definition}\nLet $ f : \\HH \\to \\CC $, let $ \\gamma = \\twobytwosmall{a}{b}{c}{d} \\in \\GL_2\\br{\\RR}_+ $, and let $ k \\in \\ZZ $. Define\n$$ \\function[\\eval{f}_{k, \\gamma}]{\\HH}{\\CC}{z}{\\det \\gamma^{k - 1}f\\br{\\gamma z}\\br{cz + d}^{-k}}, $$\nwhere $ \\det \\gamma^{k - 1} $ is the \\textbf{fudge factor}, which is one for $ \\gamma \\in \\SL_2\\br{\\RR} $, and $ \\br{cz + d}^{-k} $ is the \\textbf{twisted action} on functions.\n\\end{definition}\n\nCheck that\n$$ \\eval{f}_{k, \\id} = f, \\qquad \\eval{\\br{\\eval{f}_{k, \\gamma}}}_{k, \\gamma'} = \\eval{f}_{k, \\gamma\\gamma'}. $$\nThis gives, for each $ k $, a left action of $ \\GL_2\\br{\\RR}_+ $ on functions $ \\HH \\to \\CC $, a \\textbf{modular action of weight $ k $}. A modular form of weight $ k $ will be a sufficiently nice function $ f : \\HH \\to \\CC $ such that $ \\eval{f}_{k, \\gamma} = f $ for all $ \\gamma \\in \\SL_2\\br{\\ZZ} $. That is, for all $ \\gamma = \\twobytwosmall{a}{b}{c}{d} \\in \\SL_2\\br{\\ZZ} $ and $ z \\in \\HH $,\n$$ f\\br{\\gamma z}\\br{cz + d}^{-k} = f\\br{z} \\qquad \\implies \\qquad f\\br{\\gamma z} = f\\br{z}\\br{cz + d}^k, $$\nthe \\textbf{modular transformation law of weight $ k $}.\n\n\\pagebreak\n\nThe following are some observations.\n\\begin{itemize}\n\\item Let $ k = 0 $. Then constant functions satisfy $ f\\br{\\gamma z} = f\\br{z} $. It will turn out that all functions of weight zero are constant.\n\\item Let $ k $ be odd, and $ \\gamma = -\\id $. Then $ \\gamma z = z $ for all $ z $ and $ cz + d = -1 $, so $ f\\br{\\gamma z} = f\\br{z}\\br{cz + d}^k $ gives $ f\\br{z} = f\\br{z}\\br{-1}^k = -f\\br{z} $, so $ f\\br{z} = 0 $ for all $ z $. So no non-zero functions $ f : \\HH \\to \\CC $ satisfy the modular transformation law of weight $ k $, for all $ \\gamma \\in \\SL_2\\br{\\ZZ} $, when $ k $ is odd.\n\\end{itemize}\n\n\\subsubsection{Review of complex analysis}\n\nLet $ f : U \\to \\CC $ for $ U \\subseteq \\CC $ open, and let $ p \\in U $.\n\n\\begin{definition}\n$ f $ is \\textbf{holomorphic} at $ p $ if\n$$ f'\\br{p'} = \\lim_{\\epsilon \\to 0, \\ \\epsilon \\in \\CC} \\dfrac{f\\br{p' + \\epsilon} - f\\br{p'}}{\\epsilon} $$\nexists for all $ p' $ in a neighbourhood of $ p $.\n\\end{definition}\n\n\\begin{proposition}\n$ f $ is holomorphic at $ p $ implies that $ f $ is continuous and infinitely differentiable at $ p $, that is $ f^{\\br{n}}\\br{p} $ exists for all $ n \\ge 0 $. Moreover, we have\n$$ f\\br{z} = \\sum_{n = 0}^\\infty \\dfrac{f^{\\br{n}}\\br{p}}{n!}\\br{z - p}^n = f\\br{p} + f'\\br{p}\\br{z - p} + \\dfrac{f''\\br{p}}{2}\\br{z - p}^2 + \\dots, $$\nfor all $ z $ in a neighbourhood of $ p $.\n\\end{proposition}\n\n\\begin{corollary}\nIf $ f $ is holomorphic and not identically zero on an open set $ U $, then the zeroes of $ f $ are isolated on $ U $.\n\\end{corollary}\n\nMore generally is the following.\n\n\\begin{definition}\n$ f $ is \\textbf{meromorphic} at $ p $ if there exists a neighbourhood $ U $ of $ p $ and $ g, h : U \\to \\CC $ holomorphic on $ U $ such that $ f = g / h $ on $ U \\setminus \\cbr{p} $. Such an $ f $ has a \\textbf{Laurent series expansion} at $ p $,\n$$ f\\br{z} = \\sum_{i = -N}^\\infty c_i\\br{z - p}^i. $$\nThe smallest $ i $ such that $ c_i \\ne 0 $ is denoted by $ \\ord_p f $, the \\textbf{order of vanishing} of $ f $ at $ p $.\n\\begin{itemize}\n\\item If $ \\ord_p f = -n $ for $ n > 0 $, we say $ f $ has a \\textbf{pole of order $ n $}.\n\\item If $ \\ord_p f = n $ for $ n > 0 $, we say $ f $ has a \\textbf{zero of order $ n $}.\n\\end{itemize}\n\\end{definition}\n\n\\begin{proposition}\n\\hfill\n\\begin{itemize}\n\\item $ \\ord_p fg = \\ord_p f + \\ord_p g $, and\n\\item $ \\ord_p \\br{f + g} \\ge \\min\\cbr{\\ord_p f, \\ord_p g} $, with equality if $ \\ord_p f \\ne \\ord_p g $.\n\\end{itemize}\n\\end{proposition}\n\nIf $ f $ is holomorphic on $ U \\setminus \\cbr{p} $ for $ U $ a neighbourhood of $ p $, then $ f $ may or may not be meromorphic at $ p $.\n\n\\begin{example*}\n$ f\\br{z} = e^{-1 / z^2} $ is holomorphic on $ \\CC \\setminus \\cbr{0} $, but not meromorphic at zero.\n\\end{example*}\n\n\\begin{theorem}\nLet $ f $ be holomorphic on $ U \\setminus \\cbr{p} $, and there exists $ n > 0 $ such that\n$$ \\lim_{x \\to p} \\br{x - p}^nf\\br{x} $$\nexists. Then $ f $ is meromorphic on $ U $, and $ \\ord_p f \\ge -n $.\n\\end{theorem}\n\n\\pagebreak\n\n\\subsubsection{Modular forms}\n\n\\begin{definition}\n$ f : \\HH \\to \\CC $ is a \\textbf{weakly modular function of weight $ k $} if\n\\begin{itemize}\n\\item $ f $ is meromorphic on $ \\HH $, and\n\\item $ f $ satisfies the modular transformation law of weight $ k $.\n\\end{itemize}\n\\end{definition}\n\nConsider $ \\gamma = \\twobytwosmall{1}{1}{0}{1} $, so $ \\gamma z = z + 1 $ and $ cz + d = 1 $. The modular transformation law gives $ f\\br{z + 1} = f\\br{z} $. Let\n$$ \\DD = \\cbr{q \\st \\abs{q} < 1}. $$\nCan define a function\n$$ \\function[g]{\\DD \\setminus \\cbr{0}}{\\HH}{q}{f\\br{\\dfrac{\\log q}{2\\pi i}}}, $$\nthat is\n$$ \\function[f]{\\HH}{\\DD \\setminus \\cbr{0}}{z}{g\\br{e^{2\\pi iz}}}, $$\nand $ q = e^{2\\pi iz} $, where $ g $ is holomorphic or meromorphic on $ \\DD \\setminus \\cbr{0} $ if and only if $ f $ is holomorphic or meromorphic on $ \\HH $.\n\n\\begin{definition}\n$ f : \\HH \\to \\CC $ is a \\textbf{modular form of weight $ k $} if\n\\begin{enumerate}\n\\item $ f $ satisfies the modular transformation law of weight $ k $,\n\\item $ f $ is holomorphic on $ \\HH $, and\n\\item $ f $ is holomorphic at $ \\infty $, so the function $ g : \\DD \\setminus \\cbr{0} \\to \\CC $, which is holomorphic on $ \\DD \\setminus \\cbr{0} $ by $ 2 $, extends to a holomorphic function on $ \\DD $.\n\\end{enumerate}\n\\end{definition}\n\n\\lecture{3}{Monday}{07/10/19}\n\nThen $ q \\to 0 $ in $ \\DD $ if and only if $ \\Im z \\to +\\infty $. Recall that a holomorphic function $ g $ on $ \\DD \\setminus \\cbr{0} $ extends to a meromorphic function on $ \\DD $ if and only if there exists $ n $ such that $ \\lim_{q \\to 0} q^ng\\br{q} $ exists. Then $ 3 $ means $ g\\br{q} $ is bounded as $ q \\to 0 $ so $ f\\br{z} $ is bounded as $ \\Im z \\to +\\infty $. For $ f $ satisfying $ 3 $, $ g : \\DD \\setminus \\cbr{0} \\to \\CC $ has a series expansion\n$$ g\\br{q} = \\sum_n a_nq^n = a_0 + a_1q + \\dots $$\nin $ q = e^{2\\pi iz} $. We call this the \\textbf{$ q $-expansion} for $ f $.\n\n\\begin{definition}\n$ f : \\HH \\to \\CC $ is a \\textbf{meromorphic modular form of weight $ k $} if the same conditions $ 1 $ to $ 3 $ hold, but with holomorphic weakened to meromorphic.\n\\end{definition}\n\n\\begin{note*}\nIf $ f $ is only meromorphic at $ \\infty $ then a finite number of negative powers of $ q $ can appear.\n\\end{note*}\n\n\\begin{example*}\n\\hfill\n\\begin{itemize}\n\\item The \\textbf{discriminant}\n$$ \\Delta\\br{z} = q\\prod_{n = 1}^\\infty \\br{1 - q^n}^{24} = q - 24q^2 + 252q^3 - 1472q^4 + \\dots $$\nis a modular form of weight twelve.\n\\item The \\textbf{$ \\j $-invariant}\n$$ \\j\\br{z} = \\dfrac{1}{q} + 744 + 196844q + 21493760q^2 + \\dots $$\nis a meromorphic modular form of weight zero.\n\\end{itemize}\n\\end{example*}\n\n\\pagebreak\n\n\\subsection{Eisenstein series}\n\n\\subsubsection{Lattice functions}\n\nHow can we construct modular forms?\n\n\\begin{definition}\nA \\textbf{lattice} in $ \\CC $ is an abelian subgroup of $ \\CC $ of the form $ \\ZZ w_1 + \\ZZ w_2 $, where $ w_1, w_2 \\in \\CC $ are $ \\RR $-linearly independent. More generally if $ V $ is an $ \\RR $-vector space, a \\textbf{lattice} $ L $ in $ V $ is a discrete abelian subgroup of $ V $ that spans $ V $ over $ \\RR $. For $ L \\subseteq \\CC $ a lattice and $ \\lambda \\in \\CC^\\times $, let\n$$ \\lambda L = \\cbr{\\lambda x \\st x \\in L} \\subseteq \\CC. $$\nWe say that $ L $ and $ \\lambda L $ are \\textbf{homothetic}. For $ z \\in \\HH $, let\n$$ \\L_{z, 1} = \\ZZ + \\ZZ z = \\cbr{az + b \\st a, b \\in \\ZZ} \\subseteq \\CC. $$\n\\end{definition}\n\nA question is when is $ \\L_{z, 1} $ homothetic to $ \\L_{z', 1} $, and what is a homothety factor?\n\\begin{itemize}\n\\item Suppose $ \\L_{z, 1} = \\lambda \\L_{z', 1} $. Then there exist $ a, b, c, d $ such that\n\\begin{equation}\n\\label{eq:1}\n\\begin{cases}\n\\lambda z' = az + b \\\\\n\\lambda = cz + d\n\\end{cases}\n\\qquad \\implies \\qquad \\twobyone{\\lambda z'}{\\lambda} = \\twobytwo{a}{b}{c}{d}\\twobyone{z}{1}.\n\\end{equation}\nOn the other hand there exist $ a', b', c', d' $ such that\n\\begin{equation}\n\\label{eq:2}\n\\begin{cases}\nz = a'\\lambda z' + b'\\lambda \\\\\n1 = c'\\lambda z' + d'\\lambda\n\\end{cases}\n\\qquad \\implies \\qquad \\twobytwo{a'}{b'}{c'}{d'}\\twobyone{\\lambda z'}{\\lambda} = \\twobyone{z}{1}.\n\\end{equation}\nBy $ \\br{\\ref{eq:1}} $ and $ \\br{\\ref{eq:2}} $,\n$$ \\twobytwo{a'}{b'}{c'}{d'}\\twobytwo{a}{b}{c}{d}\\twobyone{z}{1} = \\twobyone{z}{1}, $$\nso $ \\twobytwosmall{a}{b}{c}{d} \\in \\SL_2\\br{\\ZZ} $. Moreover $ \\br{\\ref{eq:1}} $ implies that $ z' = \\br{az + b} / \\br{cz + d} $.\n\\item Conversely, if $ \\gamma = \\twobytwosmall{a}{b}{c}{d} \\in \\SL_2\\br{\\ZZ} $, then $ \\gamma z = \\br{az + b} / \\br{cz + d} $, so\n$$ \\L_{\\gamma z, 1} = \\br{cz + d}^{-1}\\L_{az + b, cz + d}. $$\nBut certainly $ \\L_{az + b, cz + d} \\subseteq \\L_{z, 1} $. On the other hand if $ \\gamma' = \\twobytwosmall{a'}{b'}{c'}{d'} $ is inverse to $ \\gamma $,\n$$ \\twobyone{z}{1} = \\gamma'\\gamma\\twobyone{z}{1} = \\gamma\\twobyone{az + b}{cz + d} = \\twobyone{a'\\br{az + b} + b'\\br{cz + d}}{c'\\br{az + b} + d'\\br{cz + d}}, $$\nso $ z \\in \\L_{az + b, cz + d} $ and $ 1 \\in \\L_{az + b, cz + d} $. So\n$$ \\L_{az + b, cz + d} = \\L_{z, 1}, $$\nso $ \\L_{\\gamma z, 1} = \\br{cz + d}^{-1}\\L_{z, 1} $.\n\\end{itemize}\n\n\\begin{definition}\nA \\textbf{lattice function of weight $ k $} is a function $ F : \\cbr{\\text{lattices in} \\ \\CC} \\to \\CC $ such that\n$$ F\\br{\\lambda L} = \\lambda^{-k}F\\br{L}, $$\nfor all lattices $ L $. Given such an $ F $, can define\n$$ \\function[f]{\\HH}{\\CC}{z}{F\\br{\\L_{z, 1}}}. $$\n\\end{definition}\n\nIf $ F $ has weight $ k $, then\n$$ f\\br{\\gamma z} = F\\br{\\L_{\\gamma z, 1}} = F\\br{\\br{cz + d}^{-1}\\L_{z, 1}} = \\br{cz + d}^kF\\br{\\L_{z, 1}} = \\br{cz + d}^kf\\br{z}, \\qquad \\gamma = \\twobytwo{a}{b}{c}{d}. $$\n\n\\pagebreak\n\n\\subsubsection{Eisenstein series}\n\n\\lecture{4}{Friday}{11/10/19}\n\n\\begin{definition}\nFor $ L \\in \\CC $, define the \\textbf{Eisenstein series}\n$$ \\G_k\\br{L} = \\sum_{w \\in L, \\ w \\ne 0} \\dfrac{1}{w^k}, \\qquad \\g_k\\br{z} = \\G_k\\br{\\L_{z, 1}} = \\underset{\\br{m, n} \\ne \\br{0, 0}}{\\sum_{m = -\\infty}^\\infty \\sum_{n = -\\infty}^\\infty} \\dfrac{1}{\\br{mz + n}^k}. $$\n\\end{definition}\n\nThen\n$$ \\G_k\\br{\\lambda L} = \\sum_{w' \\in \\lambda L, \\ w' \\ne 0} \\dfrac{1}{w'^k} = \\sum_{w \\in L, \\ w \\ne 0} \\dfrac{1}{\\br{\\lambda w}^k} = \\lambda^{-k}\\G_k\\br{L}. $$\n\n\\begin{corollary}\n$ \\g_k $ satisfies the modular transformation law of weight $ k $.\n\\end{corollary}\n\nThe following are some questions.\n\\begin{itemize}\n\\item Does $ \\G_k $, or $ \\g_k $, converge?\n\\item Is $ \\g_k $ holomorphic, or meromorphic, on $ \\HH $?\n\\item Is $ \\g_k $ holomorphic at $ \\infty $?\n\\item What is the $ q $-expansion of $ \\g_k $?\n\\end{itemize}\n\n\\subsubsection{Convergence and holomorphy on \\texorpdfstring{$ \\HH $}{H}}\n\n\\begin{definition}\nLet $ U \\subseteq \\CC $ be open. A sequence of functions $ f_n : U \\to \\CC $ \\textbf{converges uniformly on compact sets} to $ f $ if for all $ C \\subseteq U $ compact and $ \\epsilon > 0 $, there exists $ N \\in \\ZZ $ such that for all $ n > N $,\n$$ \\abs{f\\br{z} - f_n\\br{z}} < \\epsilon, \\qquad z \\in C. $$\n\\end{definition}\n\n\\begin{theorem}\nA uniform limit of holomorphic functions is holomorphic. If $ f_n $ converges to $ f $ uniformly on compact sets and $ f_n $ is holomorphic on $ U $, then $ f $ is holomorphic on $ U $.\n\\end{theorem}\n\n\\begin{theorem}\nLet $ k \\ge 4 $. The series $ \\g_k\\br{z} $ converges absolutely and uniformly on compact subsets of $ \\HH $.\n\\end{theorem}\n\n\\begin{proof}\nLet\n$$ P_{z, r} = \\cbr{az + b \\st a, b \\in \\RR, \\ \\max\\br{\\abs{a}, \\abs{b}} = r} \\subseteq \\CC, $$\nso $ P_{z, r} = rP_{z, 1} $, and there are $ 8r $ points on $ P_{z, r} \\cap \\L_{z, 1} $. Then\n$$ \\g_k\\br{z} = \\sum_{r = 1}^\\infty \\sum_{w \\in \\L_{z, 1} \\cap P_{z, r}} \\dfrac{1}{w^k}. $$\nThe function $ z \\mapsto \\abs{z} $ attains a non-zero minimum $ \\delta\\br{z} $ on $ P_{z, 1} $, so on $ P_{z, 1} $, have $ \\abs{z} > \\delta\\br{z} $, so $ 1 / \\abs{z}^k < 1 / \\delta\\br{z}^k $. On $ P_{z, r} $, have $ \\abs{z} > r\\delta\\br{z} $, so $ 1 / \\abs{z}^k < 1 / r^k\\delta\\br{z}^k $. Let $ C \\subseteq \\HH $ be compact. Then $ z \\mapsto \\delta\\br{z} $ is a continuous function on $ C $ and attains a minimum $ \\delta_C $. For all $ z \\in C $ and $ w \\in P_{z, r} $, get $ \\abs{w} > r\\delta_C $, so\n$$ \\dfrac{1}{\\abs{w}^k} < \\dfrac{1}{r^k\\delta_C^k}. $$\nThus for $ z \\in C $, $ \\g_k\\br{z} $ is dominated by\n$$ \\sum_{r = 1}^\\infty \\dfrac{8r}{r^k\\delta_C^k} = \\dfrac{8}{\\delta_C^k}\\sum_{r = 1}^\\infty \\dfrac{1}{r^{k - 1}}, $$\nwhich converges absolutely for $ k \\ge 4 $.\n\\end{proof}\n\n\\begin{corollary}\n$ \\g_k\\br{z} $ is holomorphic on $ \\HH $.\n\\end{corollary}\n\n\\pagebreak\n\n\\subsubsection{\\texorpdfstring{$ q $}{q}-expansion and holomorphy at \\texorpdfstring{$ \\infty $}{infinity}}\n\nThe idea is to understand series of the form\n$$ \\sum_{n = -\\infty}^\\infty \\dfrac{1}{\\br{z + n}^k}. $$\n\n\\begin{theorem}\nA bounded holomorphic function on all of $ \\CC $ is constant.\n\\end{theorem}\n\n\\begin{lemma}\n\\hfill\n\\begin{enumerate}\n\\item\n$$ \\dfrac{\\pi^2}{\\sin^2 \\pi z} = \\sum_{n = -\\infty}^\\infty \\dfrac{1}{\\br{z - n}^2}. $$\n\\item\n$$ \\pi\\cot \\pi z = \\dfrac{1}{z} + \\sum_{n = 1}^\\infty \\br{\\dfrac{1}{z - n} + \\dfrac{1}{z + n}} = \\dfrac{1}{z} + \\sum_{n = 1}^\\infty \\dfrac{2z}{z^2 - n^2}. $$\n\\end{enumerate}\n\\end{lemma}\n\n\\begin{proof}\n\\hfill\n\\begin{enumerate}\n\\item The right hand side converges absolutely and uniformly on compact subsets of $ \\CC \\setminus \\ZZ $, so the right hand side is holomorphic on $ \\CC \\setminus \\ZZ $. Locally around $ z = n $, the series looks like\n$$ \\sum_{n = -\\infty}^\\infty \\dfrac{1}{\\br{z - n}^2} = \\dots + \\dfrac{1}{\\br{z - n + 1}^2} + \\dfrac{1}{\\br{z - n}^2} + \\dfrac{1}{\\br{z - n - 1}^2} + \\dots = \\dfrac{1}{\\br{z - n}^2} + h_1\\br{z}, $$\nwhere $ h_1\\br{z} $ is holomorphic in a neighbourhood of $ z = n $. Similarly, the left hand side is meromorphic on $ \\CC $, and the Laurent series near $ z = n $ is\n$$ \\dfrac{\\pi^2}{\\sin^2 \\pi z} = \\pi\\br{\\dfrac{1}{\\pi^2\\br{z - n}^2} + \\dfrac{1}{3} + \\dfrac{1}{15}\\pi^2\\br{z - n}^2 + \\dots} = \\dfrac{1}{\\br{z - n}^2} + h_2\\br{z}, $$\nwhere $ h_2\\br{z} $ is a holomorphic function. So the difference\n$$ g\\br{z} = \\sum_{n = -\\infty}^\\infty \\dfrac{1}{\\br{z - n}^2} - \\dfrac{\\pi^2}{\\sin^2 \\pi z} $$\nis meromorphic on $ \\CC $ and holomorphic on $ \\CC \\setminus \\ZZ $, and the Laurent expression around $ z = n $ is\n$$ g\\br{z} = \\dfrac{1}{\\br{z - n}^2} + h_1\\br{z} - \\br{\\dfrac{1}{\\br{z - n}^2} + h_2\\br{z}} = h_1\\br{z} - h_2\\br{z}, $$\nso $ g\\br{z} $ is holomorphic at $ z = n $ for all $ n $. Consider $ t \\to \\pm\\infty $ for $ z = a + it $. The right hand side is\n$$ R = \\sum_{n = -\\infty}^\\infty \\dfrac{1}{\\br{z - n}^2} = \\sum_{n = a - N}^{a + N} \\dfrac{1}{\\br{z - n}^2} + \\sum_{n = -\\infty}^{a - N - 1} \\dfrac{1}{\\br{z - n}^2} + \\sum_{n = a + N + 1}^\\infty \\dfrac{1}{\\br{z - n}^2} = R_0 + R_- + R_+, $$\nwhere $ R_0 $ has finitely many terms that converge to less than $ \\epsilon / 2 $ as $ t \\to \\pm\\infty $ and $ R_- + R_+ < \\epsilon / 2 $ for $ N \\gg 0 $ independent of $ t $, so $ R < \\epsilon $ converges to zero. Similarly, the left hand side is\n$$ \\abs{\\dfrac{\\pi^2}{\\sin^2 \\pi z}} = \\abs{\\dfrac{2\\pi^2}{e^{\\pi iz} - e^{-\\pi iz}}} \\to 0, $$\nso $ \\lim_{t \\to \\infty} g\\br{a + it} = 0 $. Moreover, $ g\\br{z + 1} = g\\br{z} $ for all $ z $. Then\n$$ S = \\cbr{z \\in \\CC \\st n - 1 \\le \\Re z \\le n, \\ -N \\le \\Im z \\le N}, \\qquad n \\in \\ZZ $$\nis compact, so $ \\abs{g\\br{z}} $ attains a maximum in $ S $, so $ g\\br{z} $ is bounded in $ S $, so $ g\\br{z} $ is bounded in $ \\CC $, so $ g $ is constant. Since $ \\lim_{t \\to \\infty} g\\br{a + it} = 0 $, $ g = 0 $.\n\n\\pagebreak\n\n\\lecture{5}{Friday}{11/10/19}\n\n\\item Check that the right hand side converges absolutely and uniformly on compact subsets of $ \\CC \\setminus \\ZZ $, so the right hand side is meromorphic on $ \\CC \\setminus \\ZZ $. Similarly, the left hand side is also meromorphic on $ \\CC \\setminus \\ZZ $. Comparing derivatives,\n$$ -\\dfrac{\\pi^2}{\\sin^2 \\pi z} = -\\dfrac{1}{z^2} - \\sum_{n = 1}^\\infty \\br{\\dfrac{1}{\\br{z - n}^2} + \\dfrac{1}{\\br{z + n}^2}}, $$\nso the difference is constant. Let $ z = \\tfrac{1}{2} $. The left hand side is $ \\pi\\cot \\tfrac{\\pi}{2} = 0 $ and the right hand side is\n$$ \\dfrac{2}{1} + \\br{-\\dfrac{2}{1} + \\dfrac{2}{3}} + \\br{-\\dfrac{2}{3} + \\dfrac{2}{5}} + \\dots \\to 0, \\qquad n \\to \\infty, $$\nso the difference is zero.\n\\end{enumerate}\n\\end{proof}\n\nThus\n$$ \\dfrac{1}{z} + \\sum_{n = 1}^\\infty \\br{\\dfrac{1}{z - n} + \\dfrac{1}{z + n}} = \\pi\\cot \\pi z = \\pi i\\dfrac{e^{\\pi iz} + e^{-\\pi iz}}{e^{\\pi iz} - e^{-\\pi iz}} = \\pi i\\dfrac{q + 1}{q - 1} = \\pi i - \\dfrac{2\\pi i}{1 - q} = \\pi i - 2\\pi i\\sum_{n = 0}^\\infty q^n. $$\nTake $ \\tod[k - 1]{}{z} $. For $ k \\ge 2 $ even, get\n$$ -\\br{k - 1}!\\sum_{n = -\\infty}^\\infty \\dfrac{1}{\\br{z + n}^k} = -\\br{2\\pi i}^k\\sum_{n = 1}^\\infty n^{k - 1}q^n, $$\nso\n$$ \\sum_{n = -\\infty}^\\infty \\dfrac{1}{\\br{z + n}^k} = \\dfrac{\\br{2\\pi i}^k}{\\br{k - 1}!}\\sum_{n = 1}^\\infty n^{k - 1}q^n. $$\nCollecting powers of $ q $,\n\\begin{align*}\n\\g_k\\br{z}\n& = \\underset{\\br{m, n} \\ne \\br{0, 0}}{\\sum_{m = -\\infty}^\\infty \\sum_{n = -\\infty}^\\infty} \\dfrac{1}{\\br{mz + n}^k} \\\\\n& = 2\\sum_{n = 1}^\\infty \\dfrac{1}{n^k} + 2\\sum_{m = 1}^\\infty \\sum_{n = -\\infty}^\\infty \\dfrac{1}{\\br{mz + n}^k} \\\\\n& = 2\\zeta\\br{k} + \\dfrac{2\\br{2\\pi i}^k}{\\br{k - 1}!}\\sum_{m = 1}^\\infty \\sum_{n = 1}^\\infty n^{k - 1}q^{nm} & \\zeta\\br{s} = \\sum_{n = 1}^\\infty n^{-s} \\\\\n& = 2\\zeta\\br{k} + \\dfrac{2\\br{2\\pi i}^k}{\\br{k - 1}!}\\sum_{n = 1}^\\infty \\sigma_{k - 1}\\br{n}q^n & \\sigma_{k - 1}\\br{n} = \\sum_{d \\mid n, \\ d > 0} d^{k - 1}.\n\\end{align*}\n\n\\begin{corollary}\n$ \\g_k\\br{z} $ is holomorphic at $ \\infty $. In particular, $ \\g_k $ is a modular form of weight $ k $.\n\\end{corollary}\n\n\\subsubsection{Bernoulli numbers}\n\n\\begin{definition}\nThe \\textbf{Bernoulli numbers} $ \\b_k $ are defined by\n$$ \\sum_{k = 0}^\\infty \\b_k\\dfrac{x^k}{k!} = \\dfrac{x}{e^x - 1}, $$\na formal power series with rational coefficients.\n\\end{definition}\n\nThen\n$$ \\b_0 = 1, \\qquad \\b_1 = -\\dfrac{1}{2}, \\qquad \\b_2 = \\dfrac{1}{6}, \\qquad \\b_3 = 0, \\qquad \\b_4 = -\\dfrac{1}{20}, \\qquad \\dots, $$\nwhere $ \\b_{2k} \\in \\QQ $ is interesting and $ \\b_{2k + 1} = 0 $ for $ k \\ge 1 $.\n\n\\pagebreak\n\n\\begin{proposition}\nFor all even $ k $,\n$$ \\zeta\\br{k} = -\\b_k\\dfrac{\\br{2\\pi i}^k}{2k!}. $$\n\\end{proposition}\n\n\\begin{proof}\nOn one hand,\n$$ \\pi z\\cot \\pi z = \\pi iz + \\dfrac{2\\pi iz}{e^{2\\pi iz} - 1} = \\pi iz + \\sum_{k = 0}^\\infty \\b_k\\dfrac{\\br{2\\pi iz}^k}{k!}. $$\nOn the other hand,\n\\begin{align*}\n\\pi\\cot \\pi z\n& = \\dfrac{1}{z} + \\sum_{n = 1}^\\infty \\dfrac{2z}{z^2 - n^2}\n= \\dfrac{1}{z} - \\dfrac{2z}{n^2}\\sum_{n = 1}^\\infty \\dfrac{1}{1 - z^2 / n^2} \\\\\n& = \\dfrac{1}{z} - \\sum_{n = 1}^\\infty \\dfrac{2}{z}\\sum_{k = 1}^\\infty \\br{\\dfrac{z^2}{n^2}}^k\n= \\dfrac{1}{z} - \\dfrac{2}{z}\\sum_{k = 1}^\\infty z^{2k}\\sum_{n = 1}^\\infty \\dfrac{1}{n^{2k}} \\\\\n& = \\dfrac{1}{z} - \\dfrac{2}{z}\\sum_{k = 1}^\\infty \\zeta\\br{2k}z^{2k},\n\\end{align*}\nso\n$$ \\pi iz + \\sum_{k = 0}^\\infty \\b_k\\dfrac{\\br{2\\pi iz}^k}{k!} = \\pi z\\cot \\pi z = 1 - 2\\sum_{k = 1}^\\infty \\zeta\\br{2k}z^{2k}. $$\nComparing,\n$$ \\b_{2k}\\dfrac{\\br{2\\pi i}^{2k}}{\\br{2k}!} = -2\\zeta\\br{2k}, $$\nget the desired formula.\n\\end{proof}\n\nSo\n$$ \\g_k\\br{z} = -\\b_k\\dfrac{\\br{2\\pi i}^k}{k!} + \\dfrac{2\\br{2\\pi i}^k}{\\br{k - 1}!}\\sum_{n = 1}^\\infty \\sigma_{k - 1}\\br{n}q^n. $$\nSet the \\textbf{normalised Eisenstein series}\n$$ \\E_k = \\dfrac{\\g_k}{2\\zeta\\br{k}} = 1 - \\dfrac{2k}{\\b_k}\\sum_{n = 1}^\\infty \\sigma_{k - 1}\\br{n}q^n. $$\n\n\\begin{example*}\n$$ \\E_4 = 1 + 240\\sum_{n = 1}^\\infty \\sigma_3\\br{n}q^n, \\qquad \\E_6 = 1 - 504\\sum_{n = 1}^\\infty \\sigma_5\\br{n}q^n, $$\n$$ \\E_8 = 1 + 480\\sum_{n = 1}^\\infty \\sigma_7\\br{n}q^n, \\qquad \\E_{12} = 1 + \\dfrac{65520}{691}\\sum_{n = 1}^\\infty \\sigma_{11}\\br{n}q^n. $$\n\\end{example*}\n\n$ p $ is \\textbf{regular} if $ p \\nmid \\h\\br{\\ZZ\\sbr{\\zeta_p}} $ for $ \\zeta_p^p = 1 $.\n\n\\begin{theorem}\n$ p $ is regular if and only if $ p $ does not divide the numerator of $ \\b_k $ for $ 1 \\le k < p - 1 $.\n\\end{theorem}\n\n\\lecture{6}{Monday}{14/10/19}\n\nAn observation is if $ f $ is modular of weight $ k $ and $ g $ is modular of weight $ k' $, then $ fg $ is modular of weight $ k + k' $, and if $ k = k' $, then $ f + g $ is modular of weight $ k $.\n\n\\begin{example*}\n\\hfill\n\\begin{itemize}\n\\item The discriminant\n$$ \\Delta\\br{z} = \\dfrac{\\E_4^3 - \\E_6^2}{1728} = q - 24q^2 + 252q^3 + \\dots $$\nis a modular form of weight twelve.\n\\item The $ \\j $-invariant\n$$ \\j\\br{z} = \\dfrac{\\E_4^3}{\\Delta} = \\dfrac{1}{q} + 744 + 196844q + \\dots $$\nis a meromorphic modular form of weight zero.\n\\end{itemize}\n\\end{example*}\n\n\\pagebreak\n\n\\subsection{Spaces of modular forms}\n\n\\subsubsection{The fundamental domain}\n\nThe idea is to control the action of $ \\SL_2\\br{\\ZZ} $ on $ \\HH $. If $ f : \\HH \\to \\CC $ satisfies $ f\\br{\\gamma z} = \\br{cz + d}^kf\\br{z} $ for all $ \\gamma = \\twobytwosmall{a}{b}{c}{d} \\in \\SL_2\\br{\\ZZ} $, and if $ D \\subseteq \\HH $ such that $ D $ meets every $ \\SL_2\\br{\\ZZ} $-orbit in $ \\HH $, then $ f $ is determined by its values on $ D $.\n\n\\begin{definition}\nLet $ G $ be a group acting continuously on a complex analytic space $ X $, such as $ X = \\HH $. A subset $ D \\subseteq X $ is a \\textbf{fundamental domain} for the action of $ G $ if\n\\begin{itemize}\n\\item $ D $ meets every $ G $-orbit in $ X $,\n\\item the subset $ \\cbr{x \\in D \\st \\exists g \\in G, \\ gx \\in D, \\ gx \\ne x} $ has measure zero, and\n\\item $ D $ is closed in $ X $.\n\\end{itemize}\n\\end{definition}\n\nDefine\n$$ \\DDD = \\cbr{z \\in \\HH \\st \\tfrac{1}{2} \\le \\Re z \\le \\tfrac{1}{2}, \\ \\abs{z} \\ge 1} \\subseteq \\HH, $$\nso\n$$\n\\begin{tikzpicture}[scale=2]\n\\draw [dotted, thick] (-2, 0) to (2, 0);\n\\draw [dotted, thick] (0, 0) to (0, 2);\n\\draw [dashed] (-1, 0) arc (180:0:1);\n\\draw [dashed] (-0.5, 0) to (-0.5, 2);\n\\draw [dashed] (0.5, 0) to (0.5, 2);\n\\draw (-0.5, 0.866) arc (120:60:1);\n\\draw (-0.5, 0.866) to (-0.5, 2);\n\\draw (0.5, 0.866) to (0.5, 2);\n\\fill (0, 1) circle (0.025) node[below]{$ i $};\n\\fill (-0.5, 0.866) circle (0.025) node[below left]{$ -\\tfrac{1}{2} + \\tfrac{\\sqrt{-3}}{2} = e^{\\tfrac{2\\pi i}{3}} = \\rho $};\n\\fill (0.5, 0.866) circle (0.025) node[below right]{$ \\rho' = e^{\\tfrac{\\pi i}{3}} = \\tfrac{1}{2} + \\tfrac{\\sqrt{-3}}{2} $};\n\\end{tikzpicture}.\n$$\nLet\n$$ \\S = \\twobytwo{0}{-1}{1}{0} : z \\mapsto -\\dfrac{1}{z}, \\qquad \\T = \\twobytwo{1}{1}{0}{1} : z \\mapsto z + 1, $$\nand let $ \\Gamma \\subseteq \\SL_2\\br{\\ZZ} $ be the subgroup generated by $ \\S $ and $ \\T $. We will see later that $ \\Gamma = \\SL_2\\br{\\ZZ} $.\n\n\\begin{theorem}\n\\label{thm:fundamentaldomain}\n\\hfill\n\\begin{enumerate}\n\\item For all $ z \\in \\HH $, there exists $ \\gamma \\in \\Gamma $ such that $ \\gamma z \\in \\DDD $.\n\\item Suppose $ z, z' \\in \\DDD $ and $ \\gamma \\in \\SL_2\\br{\\ZZ} $ with $ \\gamma z = z' $. Then either\n\\begin{itemize}\n\\item $ z = z' $,\n\\item $ \\Re z = \\pm\\tfrac{1}{2} $ and $ z' = z \\mp 1 $, or\n\\item $ \\abs{z} = 1 $ and $ z' = -1 / z $.\n\\end{itemize}\nIn particular, if $ z \\ne z' $, then $ z $ and $ z' $ are on the boundary of $ \\DDD $.\n\\item For $ z \\in \\DDD $, let $ \\Stab_z $ be the stabiliser of $ z $ in $ \\SL_2\\br{\\ZZ} $, that is\n$$ \\Stab_z = \\cbr{\\gamma \\in \\SL_2\\br{\\ZZ} \\st \\gamma z = z}. $$\nThen $ \\Stab_z = \\cbr{\\pm\\id} $ unless\n\\begin{itemize}\n\\item $ z = i $, where $ \\Stab_z = \\cbr{\\pm\\id, \\pm \\S} $,\n\\item $ z = \\rho $, where $ \\Stab_z = \\cbr{\\pm\\id, \\pm\\br{\\S\\T}, \\pm\\br{\\T^{-1}\\S}} $, or\n\\item $ z = \\rho' $, where $ \\Stab_z = \\cbr{\\pm\\id, \\pm\\br{\\T\\S}, \\pm\\br{\\S\\T^{-1}}} $.\n\\end{itemize}\n\\end{enumerate}\n\\end{theorem}\n\n\\begin{corollary}\n$ \\Gamma = \\SL_2\\br{\\ZZ} $.\n\\end{corollary}\n\n\\begin{proof}\nFix $ \\gamma \\in \\SL_2\\br{\\ZZ} $ and $ z \\in \\mathring{\\DDD} $ so $ \\SL_2\\br{\\ZZ}z \\cap \\DDD = \\cbr{z} $ and $ \\Stab_z = \\cbr{\\pm\\id} $. Consider $ \\gamma z $. There exists $ \\gamma' \\in \\Gamma $ such that $ \\gamma'\\gamma z \\in \\DDD $, so $ \\gamma'\\gamma z = z $. So $ \\gamma'\\gamma = \\pm\\id $, so $ \\gamma = \\pm\\gamma'^{-1} $. But $ \\gamma'^{-1} \\in \\Gamma $ and $ -\\id = \\S^2 \\in \\Gamma $, so $ \\gamma \\in \\Gamma $.\n\\end{proof}\n\n\\pagebreak\n\n\\begin{proof}[Proof of Theorem \\ref{thm:fundamentaldomain}]\nRecall that $ \\Im \\gamma z = \\Im z / \\abs{cz + d}^2 $ for $ \\gamma = \\twobytwosmall{a}{b}{c}{d} \\in \\SL_2\\br{\\ZZ} $.\n\\begin{enumerate}\n\\item As $ c $ and $ d $ vary, $ \\cbr{cz + d} $ forms a lattice in $ \\CC $, so there exist only finitely many $ c $ and $ d $ such that $ \\abs{cz + d} < 1 $. So $ \\Im \\gamma z $ attains a maximum as $ \\gamma $ varies over $ \\Gamma $, so there exists $ \\gamma \\in \\Gamma $ such that $ \\Im \\gamma z $ is maximal. There exists $ n \\in \\ZZ $ such that $ \\T^n\\gamma z $ has real part between $ -\\tfrac{1}{2} $ and $ \\tfrac{1}{2} $. Consider $ \\abs{\\T^n\\gamma z} $. If this is less than one, then\n$$ \\Im \\S\\T^n\\gamma z = \\Im \\dfrac{-1}{\\T^n\\gamma z} > \\Im \\T^n\\gamma z = \\Im \\gamma z. $$\nSince $ \\S\\T^n\\gamma \\in \\Gamma $, this contradicts maximality so $ \\abs{\\T^n\\gamma z} \\ge 1 $, so $ \\T^n\\gamma z \\in \\DDD $.\n\n\\lecture{7}{Friday}{18/10/19}\n\n\\item[$ 2, 3 $.] Let $ z, z' \\in \\DDD $ such that $ \\gamma z = z' $. Without loss of generality $ \\Im z' \\ge \\Im z $, so $ \\abs{cz + d} \\le 1 $. Note that $ \\abs{cz + d} \\ge \\Im \\br{cz + d} \\ge \\tfrac{\\sqrt{3}}{2}c $, so $ c = -1, 0, 1 $. Note that can replace $ \\gamma $ with $ -\\gamma $ if convenient.\n\\begin{itemize}[leftmargin=0.5in]\n\\item[$ c = 0 $.] $ ad = 1 $, so can assume $ a = d = 1 $, so $ \\gamma z = z + b $.\nSince $ z, z + b \\in \\DDD $, $ b = \\pm 1 $ and $ \\Re z = \\mp\\tfrac{1}{2} $.\n\\item[$ c = 1 $.] Have $ \\abs{z + d} \\le 1 $ and $ \\abs{z} \\ge 1 $, so $ d = -1, 0, 1 $.\n\\begin{itemize}[leftmargin=0.5in]\n\\item[$ d = 0 $.] $ \\abs{z} = 1 $, and $ \\gamma z = \\br{az - 1} / z = a - 1 / z $.\nThe only possibilities are\n\\begin{itemize}\n\\item $ a = 0 $ and $ \\gamma = \\S $,\n\\item $ a = 1 $ and $ \\gamma = \\T\\S $, so $ z = \\rho' $, or\n\\item $ a = -1 $ and $ \\gamma = \\T^{-1}\\S $, so $ z = \\rho $.\n\\end{itemize}\n\\item[$ d = 1 $.] $ z = \\rho $, and $ \\gamma z = \\br{\\br{b + 1}z + b} / \\br{z + 1} = b + 1 - 1 / \\br{z + 1} $, so $ b = 0 $ or $ b = -1 $.\n\\item[$ d = -1 $.] $ z = \\rho' $ is similar.\n\\end{itemize}\n\\item[$ c = -1 $.] Similar.\n\\end{itemize}\n\\end{enumerate}\n\\end{proof}\n\n\\subsubsection{Further review of complex analysis}\n\nRecall that on any compact set, a meromorphic function has only finitely many zeroes and poles. If $ f\\br{z} = g\\br{e^{2\\pi i z}} $ is meromorphic at $ \\infty $, then $ g $ is meromorphic on $ \\DD = \\cbr{\\abs{q} < 1} $, so zeroes and poles of $ g $ are discrete with respect to $ q $, and $ \\Im z \\gg 0 $ if and only if $ \\abs{q} < \\epsilon $.\n\n\\begin{definition}\nLet $ U \\subseteq \\CC $ be open, and let $ f : U \\to \\CC $ be meromorphic on $ U $. If $ f $ has a pole at $ p $, can write\n$$ f\\br{z} = \\sum_{n = \\ord_p f < 0}^\\infty a_n\\br{z - p}^n. $$\nThe coefficient $ a_{-1} $ is called the \\textbf{residue} $ \\Res_p f $ of $ f $ at $ p $.\n\\end{definition}\n\n\\begin{theorem}[Residue theorem]\nLet $ V $ be a region in $ \\CC $ whose boundary $ \\partial V $ is a simple closed curve with counterclockwise orientation. Then\n$$ \\dfrac{1}{2\\pi}\\intd{\\partial V}{}{f\\br{z}}{z} = \\sum_{p \\in V \\ \\text{pole of} \\ f} \\Res_p f. $$\n\\end{theorem}\n\n\\begin{definition}\nLet $ f $ be meromorphic on $ U \\subseteq \\CC $ open. Then the \\textbf{logarithmic derivative} $ \\d\\log f $ is the function $ f' / f $.\n\\end{definition}\n\nIf $ f\\br{z} = c_n\\br{z - p}^n + c_{n + 1}\\br{z - p}^{n + 1} + \\dots $ and $ c_n \\ne 0 $, then if $ n \\ne 0 $ then the leading term of $ f' $ is $ nc_n\\br{z - p}^{n - 1} $ and the leading term of $ f $ is $ c_n\\br{z - p}^n $, so the leading term of $ f' / f $ is $ n\\br{z - p}^{-1} $. If $ n = 0 $, then $ f' / f $ is holomorphic. So $ f' / f $ is meromorphic with simple poles precisely at the points where $ \\ord_p f \\ne 0 $, and $ \\Res_p f' / f $ at such $ p $ is $ \\ord_p f $.\n\n\\begin{theorem}[Argument principle]\n$$ \\dfrac{1}{2\\pi i}\\intd{\\partial V}{}{\\dfrac{f'\\br{z}}{f\\br{z}}}{z} = \\sum_{p \\in V \\ \\text{pole of} \\ f} \\ord_p f. $$\n\\end{theorem}\n\n\\pagebreak\n\n\\subsubsection{Controlling modular forms}\n\n\\begin{theorem}[$ k / 12 $-formula]\nLet $ f $ be a non-zero meromorphic modular form of weight $ k $. Then\n$$ \\ord_\\infty f + \\dfrac{\\ord_\\rho f}{3} + \\dfrac{\\ord_i f}{2} + \\sum_{p \\in \\SL_2\\br{\\ZZ} \\backslash \\HH, \\ p \\nsim \\cbr{i, \\rho}} \\ord_p f = \\dfrac{k}{12}. $$\n\\end{theorem}\n\n\\lecture{8}{Friday}{18/10/19}\n\n\\begin{proof}\nConsider the closed curve $ C_{N, \\epsilon} $,\n$$\n\\begin{tikzpicture}[scale=4]\n\\draw [dotted, thick] (-0.5, 0.866) arc (120:60:1);\n\\draw [dotted, thick] (-0.5, 0.866) to (-0.5, 2);\n\\draw [dotted, thick] (0.5, 0.866) to (0.5, 2);\n\\draw (-0.5, 0.916) arc (90:25:0.05);\n\\draw (-0.455, 0.89) arc (117:107.5:1);\n\\draw (-0.3, 0.955) arc (-165:15:0.05);\n\\draw (-0.205, 0.98) arc (101:92:1);\n\\draw (-0.05, 0.995) arc (180:0:0.05);\n\\draw (0.205, 0.98) arc (79:88:1);\n\\draw (0.3, 0.955) arc (-15:165:0.05);\n\\draw (0.455, 0.89) arc (63:72.5:1);\n\\draw (0.5, 0.916) arc (90:155:0.05);\n\\draw (-0.5, 1.5) to node[above]{$ \\Im z = N $} node{$ < $} (0.5, 1.5);\n\\draw (-0.5, 0.916) to (-0.5, 1.2);\n\\draw (-0.5, 1.2) arc (270:90:0.05);\n\\draw (-0.5, 1.3) to (-0.5, 1.5);\n\\draw (0.5, 0.916) to (0.5, 1.2);\n\\draw (0.5, 1.2) arc (270:90:0.05);\n\\draw (0.5, 1.3) to (0.5, 1.5);\n\\fill (0, 1) circle (0.0125) node[below]{$ i $};\n\\fill (-0.25, 0.965) circle (0.0125) node[above]{$ z $};\n\\fill (0.25, 0.965) circle (0.0125) node[below]{$ z $};\n\\fill (-0.5, 1.25) circle (0.0125) node[right]{$ z $};\n\\fill (-0.5, 0.866) circle (0.0125) node[below left]{$ \\rho $};\n\\fill (0.5, 1.25) circle (0.0125) node[right]{$ z $};\n\\fill (0.5, 0.866) circle (0.0125) node[below right]{$ \\rho' $};\n\\end{tikzpicture},\n$$\nwhere the $ z $'s are zeroes or poles of $ f $, and the circles are of radius $ \\epsilon $. Consider\n$$ \\dfrac{1}{2\\pi i}\\intd{C_{N, \\epsilon}}{}{\\dfrac{f'\\br{z}}{f\\br{z}}}{z} = \\sum_{p \\in \\SL_2\\br{\\ZZ} \\backslash \\HH, \\ p \\nsim \\cbr{i, \\rho}} \\ord_p f, \\qquad \\epsilon \\to 0. $$\nSo it suffices to show\n$$ \\lim_{\\epsilon \\to 0, \\ N \\to \\infty} \\dfrac{1}{2\\pi i}\\intd{C_{N, \\epsilon}}{}{\\dfrac{f'\\br{z}}{f\\br{z}}}{z} = -\\ord_\\infty f - \\dfrac{\\ord_\\rho f}{3} - \\dfrac{\\ord_i f}{2} + \\dfrac{k}{12}. $$\nThe vertical parts of the boundary cancel. Since $ f\\br{-1 / z} = z^kf\\br{z} $,\n$$ \\d\\br{z^kf\\br{z}} = \\br{kz^{k - 1}f\\br{z} + z^kf'\\br{z}}\\d z, $$\nso the integral over the circular part of $ \\partial\\DDD $ approaches\n\\begin{align*}\n\\dfrac{1}{2\\pi i}\\intd{\\rho}{i}{\\dfrac{f'\\br{z}}{f\\br{z}}}{z} + \\dfrac{1}{2\\pi i}\\intd{i}{\\rho'}{\\dfrac{f'\\br{z}}{f\\br{z}}}{z}\n& = \\dfrac{1}{2\\pi i}\\br{\\intd{\\rho}{i}{\\dfrac{f'\\br{z}}{f\\br{z}}}{z} - \\intd{\\rho}{i}{\\dfrac{f'\\br{-1 / z}}{f\\br{-1 / z}}}{z}} \\\\\n& = \\dfrac{1}{2\\pi i}\\intd{\\rho}{i}{\\dfrac{f'\\br{z}}{f\\br{z}} - \\dfrac{kz^{k - 1}f\\br{z} + z^kf'\\br{z}}{z^kf\\br{z}}}{z}\n= -\\dfrac{1}{2\\pi i}\\intd{\\rho}{i}{\\dfrac{k}{z}}{z}\n= \\dfrac{k}{12}.\n\\end{align*}\nSince $ \\d q = 2\\pi iq\\d z $, the top part is\n$$ \\dfrac{1}{2\\pi i}\\intd{\\tfrac{1}{2} + iN}{\\tfrac{1}{2} - iN}{\\dfrac{f'\\br{z}}{f\\br{z}}}{z} = -\\dfrac{1}{2\\pi i}\\intd{\\text{circle of radius} \\ \\epsilon}{}{\\dfrac{g'\\br{q}}{g\\br{q}}}{q} = -\\ord_\\infty f. $$\nNear $ i $, $ f' / f = \\ord_i f\\br{z - i}^{-1} + h\\br{z} $, where $ h\\br{z} $ is holomorphic such that $ h\\br{z} \\to 0 $ as $ \\epsilon \\to 0 $. Then the circle $ C_{\\epsilon, i} $ of radius $ \\epsilon $ centered at $ i $ is\n$$ \\lim_{\\epsilon \\to 0} \\dfrac{1}{2\\pi i}\\intd{C_{\\epsilon, i}}{}{\\dfrac{f'\\br{z}}{f\\br{z}}}{z} = \\lim_{\\epsilon \\to 0} \\dfrac{1}{2\\pi i}\\intd{\\text{arc of half circle centered at} \\ i}{}{\\dfrac{\\ord_i f}{z - i}}{z} = -\\dfrac{\\ord_i f}{2}. $$\nSimilarly, at $ \\rho $ and $ \\rho' $, get that the circles $ C_{\\epsilon, \\rho} $ and $ C_{\\epsilon, \\rho'} $ of radius $ \\epsilon $ centered at $ \\rho $ and $ \\rho' $ are\n$$ \\lim_{\\epsilon \\to 0} \\dfrac{1}{2\\pi i}\\intd{C_{\\epsilon, \\rho}}{}{\\dfrac{f'\\br{z}}{f\\br{z}}}{z} = \\lim_{\\epsilon \\to 0} \\dfrac{1}{2\\pi i}\\intd{C_{\\epsilon, \\rho'}}{}{\\dfrac{f'\\br{z}}{f\\br{z}}}{z} = -\\dfrac{\\ord_\\rho f}{6}, $$\nwhich gives $ -\\ord_\\rho f / 3 $.\n\\end{proof}\n\n\\pagebreak\n\n\\subsubsection{The space of holomorphic modular forms}\n\nLet\n$$ \\M_k = \\cbr{\\text{holomorphic modular forms of weight} \\ k}, $$\n$$ \\S_k = \\cbr{\\text{cusp forms of weight} \\ k} = \\cbr{f \\in \\M_k \\st \\ord_\\infty f > 0} \\subseteq \\M_k. $$\n\n\\begin{corollary}\n\\hfill\n\\begin{itemize}\n\\item $ \\M_k = 0 $ if $ k < 0 $, $ k = 2 $, or $ k $ odd.\n\\item $ \\M_0 $ are constants.\n\\item $ \\M_4 = \\CC\\E_4 $, where $ \\ord_\\rho \\E_4 = 1 $ and no other zeroes.\n\\item $ \\M_6 = \\CC\\E_6 $, where $ \\ord_i \\E_6 = 1 $ and no other zeroes.\n\\item $ \\M_8 = \\CC\\E_8 $, where $ \\ord_\\rho \\E_8 = 2 $ and no other zeroes.\n\\item $ \\M_{10} = \\CC\\E_{10} $, where $ \\ord_\\rho \\E_{10} = \\ord_i \\E_{10} = 1 $ and no other zeroes.\n\\item $ \\M_{12} = \\CC\\E_{12} \\oplus \\CC\\Delta $, where $ \\ord_\\infty \\Delta = 1 $ and no other zeroes.\n\\end{itemize}\n\\end{corollary}\n\n\\begin{corollary}\n$ \\Delta : \\M_k \\to \\S_{k + 12} $ is an isomorphism. On the other hand,\n$$ \\M_k \\cong \\CC\\E_k \\oplus \\S_k, \\qquad k \\ge 4 \\ \\text{even}, $$\nso\n$$ \\M_k \\cong \\CC\\E_k \\oplus \\dots \\oplus \\CC\\E_{k - 12r}\\Delta^r, \\qquad k - 12r = 0, 4, 6, 8, 10, 14. $$\n\\end{corollary}\n\n\\begin{corollary}\n$ \\E_4^2 = \\E_8 $ and $ \\E_4\\E_6 = \\E_{10} $.\n\\end{corollary}\n\n\\lecture{9}{Monday}{21/10/19}\n\nSo for $ k \\ge 4 $, the set\n$$\n\\begin{cases}\n\\E_k, \\dots, \\E_{k - 12\\fbr{k / 12}}\\Delta^{\\fbr{k / 12}} & k \\not\\equiv 2 \\mod 12 \\\\\n\\E_k, \\dots, \\E_{14}\\Delta^{\\fbr{k / 12} - 1} & k \\equiv 2 \\mod 12\n\\end{cases}\n$$\nis a basis for $ \\M_k $. A variant is to write $ k = 4n + 6m $ with $ m = 0, 1 $ and $ n \\ge 0 $, for $ k \\ge 4 $. Then $ \\M_k = \\CC\\E_4^n\\E_6^m \\oplus \\S_k $ gives a basis\n$$ \\E_4^n\\E_6^m, \\dots, \\E_4^{n - 3\\fbr{n / 3}}\\E_6^m\\Delta^{\\fbr{n / 3}} $$\nfor $ \\M_k $. Since $ \\Delta = \\br{\\E_4^3 - \\E_6^2} / 1728 $, we see every modular form of weight $ k $ is a polynomial in $ \\E_4 $ and $ \\E_6 $, and\n$$ \\Delta \\in q + q^2\\ZZ\\sbr{\\sbr{q}}, \\qquad \\E_4^n\\E_6^m \\in 1 + q\\ZZ\\sbr{\\sbr{q}}, \\qquad \\E_4^{n - 3}\\E_6^m\\Delta \\in q + q^2\\ZZ\\sbr{\\sbr{q}}, \\qquad \\dots $$\nhave integer coefficients.\n\n\\begin{corollary}\nIf the $ q $-expansion of $ f $ has integer coefficients, then $ f $ is an integer combination of\n$$ \\E_4^n\\E_6^m, \\dots, \\E_4^{n - 3\\fbr{n / 3}}\\E_6^m\\Delta^{\\fbr{n / 3}}. $$\n\\end{corollary}\n\n\\begin{notation*}\n$ \\M_k\\br{\\ZZ} \\subseteq \\M_k $ consists of modular forms with integer $ q $-expansions.\n\\end{notation*}\n\n\\begin{theorem}\n$ \\M_k\\br{\\ZZ} $ spans $ \\M_k $, and $ f \\in \\M_k $ lies in $ \\M_k\\br{\\ZZ} $ if and only if $ f $ is an integral polynomial in $ \\E_4, \\E_6, \\Delta $.\n\\end{theorem}\n\n\\begin{definition}\nA \\textbf{graded ring} is a ring $ R $, together with a direct sum decomposition, as abelian groups,\n$$ R = \\bigoplus_{i \\in \\ZZ} R_i, $$\nsuch that $ R_i \\cdot R_j \\subseteq R_{i + j} $ for all $ i, j \\in \\ZZ $.\n\\end{definition}\n\n\\begin{example*}\n\\hfill\n\\begin{itemize}\n\\item $ R = \\CC\\sbr{X, Y} $, where $ R_i $ are polynomials homogeneous of degree $ i $.\n\\item $ R = \\bigoplus_{k \\in \\ZZ} \\M_k $.\n\\end{itemize}\n\\end{example*}\n\n\\pagebreak\n\nLet $ \\CC\\sbr{X, Y} $ be graded with $ \\deg X = 4 $ and $ \\deg Y = 6 $. Have a homomorphism of graded rings\n$$ \\function{\\CC\\sbr{X, Y}}{\\bigoplus_{k \\in \\ZZ} \\M_k}{\\br{X, Y}}{\\br{\\E_4, \\E_6}}. $$\n\n\\begin{theorem}\nThis is an isomorphism of graded rings.\n\\end{theorem}\n\n\\begin{proof}\nThis map is surjective, since every $ f \\in \\M_k $ is a polynomial in $ \\E_4 $ and $ \\E_6 $. It remains to show this map is injective. Suppose not. There exists $ P\\br{X, Y} $, homogeneous of degree $ k $, such that $ P\\br{\\E_4, \\E_6} = 0 $. Write $ k = 4n + 6m $ with $ m = 0, 1 $. If $ P = c_0X^nY^m + \\dots + c_rX^{n - 3r}Y^{m + 2r} $ where $ r = \\fbr{n / 3} $, then\n$$ c_0\\E_4^n\\E_6^m + \\dots + c_r\\E_4^{n - 3r}\\E_6^{m + 2r} = 0. $$\nDividing by $ \\E_4^{n - 3r}\\E_6^{m + 2r} $, get $ Q\\br{\\E_4^3 / \\E_6^2} = 0 $ where $ Q\\br{X} = c_0X^r + \\dots + c_r $. Since the roots of $ Q $ are discrete, and $ \\E_4^3 / \\E_6^2 $ is non-constant, this is impossible.\n\\end{proof}\n\n\\subsubsection{The space of meromorphic modular forms}\n\n\\begin{note*}\nThe meromorphic modular forms of weight zero form a field.\n\\end{note*}\n\n\\begin{example*}\nThe $ \\j $-invariant $ \\j\\br{z} = \\E_4^3 / \\Delta = 1728\\E_4^3 / \\br{\\E_4^3 - \\E_6^2} $ is a non-constant meromorphic modular form, with a pole of order one at $ \\infty $, a zero of order three at $ \\rho $, and no other zeroes or poles.\n\\end{example*}\n\n\\begin{theorem}\n$ \\j $ gives a bijection between $ \\SL_2\\br{\\ZZ} \\backslash \\HH $ and $ \\CC $.\n\\end{theorem}\n\n\\begin{proof}\nGiven $ \\lambda \\in \\CC $, want $ z \\in \\HH $ such that $ \\j\\br{z} = \\lambda $. Consider $ g = j - \\lambda $. This is meromorphic of weight zero. This has a pole at $ \\infty $, and no other poles, and\n$$ \\ord_\\infty g + \\dfrac{\\ord_\\rho g}{3} + \\dfrac{\\ord_i g}{2} + \\sum_{p \\in \\SL_2\\br{\\ZZ} \\backslash \\HH, \\ p \\nsim \\cbr{i, \\rho}} \\ord_p g = 0. $$\nThe only possibilities are\n\\begin{itemize}\n\\item $ g $ has a zero at $ \\rho $ of order three, and no other zeroes,\n\\item $ g $ has a zero at $ i $ of order two, and no other zeroes, or\n\\item $ g $ has a simple zero somewhere else, and no other zeroes.\n\\end{itemize}\nIn each case, the zero of $ g $ is a unique $ \\SL_2\\br{\\ZZ} $-orbit on which $ \\j\\br{z} = \\lambda $. So $ \\j $ is bijective.\n\\end{proof}\n\n\\lecture{10}{Friday}{25/10/19}\n\n\\begin{theorem}\nEvery meromorphic modular form of weight zero is a rational function in $ \\j $. That is, the field of meromorphic modular forms is $ \\CC\\br{\\j} $.\n\\end{theorem}\n\n\\begin{proof}\nLet $ g $ be meromorphic of weight zero. Then $ g $ has finitely many $ \\SL_2\\br{\\ZZ} $-orbits worth of poles in $ \\HH $. Saw last time that $ \\j $ is holomorphic in $ \\HH $. If $ p $ is a pole of $ g $, then $ \\br{\\j\\br{z} - \\j\\br{p}}^{n_p} $ is holomorphic on $ \\HH $ and zero at $ z = p $. Doing this for all poles, there exists $ P \\in \\CC\\sbr{X} $ such that $ P\\br{\\j}g\\br{z} $ is holomorphic on $ \\HH $. Then for some $ m $, $ P\\br{\\j}g\\br{z}\\Delta^m $ is holomorphic of weight $ 12m $. So it suffices to show if $ h $ is holomorphic of weight $ 12m $, then $ h / \\Delta^m $ is a rational function in $ \\j $, since if $ P\\br{\\j}g\\br{z}\\Delta^m = h $ then $ P\\br{\\j}g\\br{z} \\in \\CC\\br{\\j} $, so $ g\\br{z} \\in \\CC\\br{\\j} $. Then $ h $ is a sum of terms\n$$ h = \\sum_{a, b} c_{a, b}\\E_4^a\\E_6^b, \\qquad c_{a, b} \\in \\CC, \\qquad 4a + 6b = 12m. $$\nConsidering this equation modulo four and modulo three, find $ 3 \\mid a $ and $ 2 \\mid b $, so\n$$ \\dfrac{h}{\\Delta^m} = \\sum_{a, b} c_{a, b}\\br{\\dfrac{\\E_4^3}{\\Delta}}^{\\tfrac{a}{3}}\\br{\\dfrac{\\E_6^2}{\\Delta}}^{\\tfrac{b}{2}}. $$\nSo it suffices to show $ \\E_4^3 / \\Delta $ and $ \\E_6^2 / \\Delta $ are rational functions in $ \\j $. Then $ \\j = \\E_4^3 / \\Delta $, and\n$$ \\dfrac{\\E_6^2}{\\Delta} = \\dfrac{1728\\E_6^2}{\\E_4^3 - \\E_6^2} = \\dfrac{1728\\br{\\E_6^2 - \\E_4^3} + 1728\\E_4^3}{\\E_4^3 - \\E_6^2} = -1728 + \\dfrac{1728\\E_4^3}{\\E_4^3 - \\E_6^2} = \\j - 1728. $$\n\\end{proof}\n\n\\pagebreak\n\n\\subsection{Theta series}\n\nLet $ L \\subseteq \\RR^n $ be a lattice. For $ x, y \\in L $, $ x \\cdot y \\in \\RR $. Suppose $ x \\cdot y \\in \\ZZ $ for all $ x, y \\in L $. A question is for $ n \\in \\ZZ $, how many $ x \\in L $ have $ x \\cdot x = n $? The rough idea is to form the series\n$$ \\sum_{x \\in L} q^{x \\cdot x} = \\sum_{n = 0}^\\infty a_nq^n, \\qquad a_n = \\#\\cbr{x \\in L \\st x \\cdot x = n}. $$\nWe will show that, with some slight modifications, and extra hypotheses on $ L $, this generating function turns out to be a modular form.\n\n\\subsubsection{Quadratic forms}\n\nFix a lattice $ L \\subseteq \\RR^n $, so\n$$ L = \\ZZ \\cdot e_1 \\oplus \\dots \\oplus \\ZZ \\cdot e_n. $$\nGiven these $ e_i $, form a matrix $ A $ such that $ A_{ij} = e_i \\cdot e_j $.\n\n\\begin{note*}\n$ A = B^\\intercal B $, where $ B $ is the matrix whose columns are the $ e_i $, and $ \\abs{\\det B} $ is the \\textbf{volume} of the parallelogram spanned by $ e_i $, so $ \\det A = \\det B^2 > 0 $.\n\\end{note*}\n\n\\begin{definition}\nThe \\textbf{dual lattice} $ L^\\vee $ is the set of $ y \\in \\RR^n $ such that $ y \\cdot x \\in \\ZZ $ for all $ x \\in L $.\n\\end{definition}\n\nLet $ f_1, \\dots, f_n $ be the dual basis to $ e_1, \\dots, e_n $, that is the unique set of solutions $ f_1, \\dots, f_n $ such that\n$$ f_i \\cdot e_j =\n\\begin{cases}\n1 & i = j \\\\\n0 & i \\ne j\n\\end{cases}.\n$$\nThen $ L^\\vee $ is spanned by the $ f_i $. Clearly $ f_i \\in L^\\vee $ for all $ i $. Conversely, if $ y \\in L^\\vee $, then $ y \\cdot e_i = a_i \\in \\ZZ $, then $ y = \\sum_{i = 1}^n a_if_i $.\n\n\\begin{proposition}\nLet $ C = A^{-1} $. Then\n$$ f_i = \\sum_{j = 1}^n C_{ij}e_j. $$\n\\end{proposition}\n\n\\begin{proof}\n$$ f_i \\cdot e_k = \\sum_{j = 1}^n C_{ij}e_je_k = \\sum_{j = 1}^n C_{ij}A_{jk} = \\br{CA}_{ik} =\n\\begin{cases}\n1 & i = k \\\\\n0 & i \\ne k\n\\end{cases}.\n$$\n\\end{proof}\n\n\\begin{definition}\nA lattice $ L $ is \\textbf{self-dual} if $ L^\\vee = L $ as subsets of $ \\RR^n $.\n\\end{definition}\n\n\\begin{proposition}\n$ L $ is self-dual if and only if the associated matrix $ A $ has integer entries and determinant one.\n\\end{proposition}\n\n\\begin{proof}\nClearly if $ L = L^\\vee $, then $ e_i \\cdot e_j \\in \\ZZ $, so $ A $ has integer entries. Since $ L^\\vee \\subseteq L $, $ f_i $ is an integer combination of the $ e_j $, so $ C = A^{-1} $ has integer entries. So $ \\det A = \\pm 1 $, but already saw $ \\det A > 0 $. Conversely if $ A $ has integer entries and determinant one, $ C = A^{-1} $ has integer entries. Then $ A $ has integer entries implies that $ e_i \\cdot e_j \\in \\ZZ $ for all $ i $ and $ j $, so $ e_i \\in L^\\vee $ for all $ i $, so $ L \\subseteq L^\\vee $. Similarly, $ C $ has integer entries implies that $ L^\\vee \\subseteq L $.\n\\end{proof}\n\nIf $ L $ is self-dual, get an integer-valued \\textbf{quadratic form}\n$$ \\function[\\Q_L]{\\ZZ^n}{\\ZZ}{\\br{a_1, \\dots, a_n}}{\\br{a_1e_1 + \\dots + a_ne_n} \\cdot \\br{a_1e_1 + \\dots + a_ne_n} = \\onebythree{a_1}{\\dots}{a_n}A\\threebyone{a_1}{\\vdots}{a_n}}. $$\nA question is given $ m $, how often does $ \\Q_L $ represent $ m $?\n\n\\pagebreak\n\n\\subsubsection{Fourier analysis}\n\n\\lecture{11}{Friday}{25/10/19}\n\nLet $ f : \\RR^n \\to \\CC $ be a $ \\C^\\infty $ function.\n\n\\begin{definition}\nWe will say $ f $ is \\textbf{rapidly decreasing} if for all $ m $,\n$$ \\abs{\\abs{x}^mf\\br{x}} \\to 0, \\qquad \\abs{x} \\to \\infty, $$\nwhere $ \\abs{x} = \\br{x \\cdot x}^{1 / 2} $. For $ f \\in \\C^\\infty $, rapidly decreasing, define\n$$ \\widehat{f}\\br{y} = \\intd{\\RR^n}{}{e^{-2\\pi i\\br{x \\cdot y}}}{x} : \\RR^n \\to \\CC. $$\n\\end{definition}\n\n\\begin{fact*}\n\\hfill\n\\begin{itemize}\n\\item If $ f $ is smooth and rapidly decreasing, so is $ \\widehat{f} $.\n\\item If $ f\\br{x} = e^{-\\pi\\br{x \\cdot x}} $, then $ \\widehat{f}\\br{x} = f\\br{x} $.\n\\item If $ f $ is smooth and rapidly decreasing, and $ L \\subseteq \\RR^n $ is a lattice with volume $ V $, then\n$$ \\sum_{x \\in L} f\\br{x} = \\dfrac{1}{V}\\sum_{x \\in L^\\vee} \\widehat{f}\\br{x}. $$\n\\end{itemize}\n\\end{fact*}\n\n\\subsubsection{Theta series}\n\nA crucial assumption is that $ L $ is self-dual. An assumption that can be removed is that $ L $ is even, so for all $ x \\in L $, $ \\Q_L\\br{x} \\in 2\\ZZ $.\n\n\\begin{definition}\nThe \\textbf{theta series} $ \\Theta_L $ is defined by\n$$ \\Theta_L\\br{z} = \\sum_{x \\in L} q^{\\tfrac{1}{2}x \\cdot x} = \\sum_{m = 0}^\\infty a_mq^m, \\qquad a_m = \\#\\cbr{x \\in \\ZZ^n \\st \\Q_L\\br{x} = 2m}. $$\n\\end{definition}\n\n\\begin{theorem}\n\\label{thm:thetaseries}\n$ \\Theta_L $ is modular of weight $ n / 2 $.\n\\end{theorem}\n\n\\begin{example*}\nLet $ \\Gamma_8 \\subseteq \\RR^8 $ be spanned by\n$$ e_1 = \\br{\\dfrac{1}{2}, -\\dfrac{1}{2}, -\\dfrac{1}{2}, -\\dfrac{1}{2}, -\\dfrac{1}{2}, -\\dfrac{1}{2}, -\\dfrac{1}{2}, \\dfrac{1}{2}}, \\qquad e_2 = \\br{1, 1, 0, 0, 0, 0, 0, 0}, $$\n$$ e_3 = \\br{-1, 1, 0, 0, 0, 0, 0, 0}, \\qquad e_4 = \\br{0, -1, 1, 0, 0, 0, 0, 0}, \\qquad e_5 = \\br{0, 0, -1, 1, 0, 0, 0, 0}, $$\n$$ e_6 = \\br{0, 0, 0, -1, 1, 0, 0, 0}, \\qquad e_7 = \\br{0, 0, 0, 0, -1, 1, 0, 0}, \\qquad e_8 = \\br{0, 0, 0, 0, 0, -1, 1, 0}. $$\nThen\n$$ A =\n\\begin{pmatrix}\n2 & 0 & -1 & 0 & 0 & 0 & 0 & 0 \\\\\n0 & 2 & 0 & -1 & 0 & 0 & 0 & 0 \\\\\n-1 & 0 & 2 & -1 & 0 & 0 & 0 & 0 \\\\\n0 & -1 & -1 & 2 & -1 & 0 & 0 & 0 \\\\\n0 & 0 & 0 & -1 & 2 & -1 & 0 & 0 \\\\\n0 & 0 & 0 & 0 & -1 & 2 & -1 & 0 \\\\\n0 & 0 & 0 & 0 & 0 & -1 & 2 & -1 \\\\\n0 & 0 & 0 & 0 & 0 & 0 & -1 & 2\n\\end{pmatrix},\n$$\nand\n$$ \\Q_L\\br{z_1, \\dots, z_8} = 2\\br{z_1^2 + \\dots + z_8^2 - z_1z_3 - z_2z_4 - z_3z_4 - z_4z_5 - z_6z_7 - z_7z_8}. $$\n\\end{example*}\n\nIf $ L \\subseteq \\RR^n $ is even and self-dual, and $ \\Theta_L $ is modular of weight $ n / 2 $, then the dimension is $ \\sim n / 24 $.\n\n\\begin{fact*}\nIf $ L \\subseteq \\RR^n $ is even and self-dual, then $ 8 \\mid n $.\n\\end{fact*}\n\n\\begin{proof}\nSerre V.2.1 Corollary 2.\n\\end{proof}\n\n\\pagebreak\n\n\\begin{proof}[Proof of Theorem \\ref{thm:thetaseries}]\nKnow, since $ L $ is even, that $ \\Theta_L\\br{z + 1} = \\Theta_L\\br{z} $. It suffices to show $ \\Theta_L\\br{-1 / z} = z^{n / 2}\\Theta_L\\br{z} $. Both sides are holomorphic on $ \\HH $, so it suffices to show\n$$ \\Theta_L\\br{-\\dfrac{1}{it}} = \\br{it}^{\\tfrac{n}{2}}\\Theta_L\\br{it}. $$\nFor $ t \\in \\RR^\\times $, let $ L_t = t^{1 / 2} \\cdot L $. Then $ L_t^\\vee = t^{-1 / 2} \\cdot L = L_{t^{-1}} $, so the volume of $ L_t $ is $ t^{n / 2} $. By the facts,\n$$ \\sum_{x \\in L_t} e^{-\\pi\\br{x \\cdot x}} = t^{-\\tfrac{n}{2}}\\sum_{x \\in L_{t^{-1}}} e^{-\\pi\\br{x \\cdot x}}, $$\nso\n$$ \\sum_{x \\in L} e^{-\\pi\\br{x \\cdot x}t} = t^{-\\tfrac{n}{2}}\\sum_{x \\in L} e^{-\\tfrac{\\pi\\br{x \\cdot x}}{t}}. $$\nNow return to $ \\Theta_L $. The left hand side is\n$$ \\Theta_L\\br{-\\dfrac{1}{it}} = \\sum_{x \\in L} e^{\\tfrac{1}{2} \\cdot 2\\pi i \\cdot \\br{-\\tfrac{1}{it}} \\cdot \\br{x \\cdot x}} = \\sum_{x \\in L} e^{-\\tfrac{\\pi\\br{x \\cdot x}}{t}}, $$\nand the right hand side is\n$$ \\Theta_L\\br{it} = \\sum_{x \\in L} e^{\\tfrac{1}{2} \\cdot 2\\pi i \\cdot \\br{it} \\cdot \\br{x \\cdot x}} = \\sum_{x \\in L} e^{-\\pi\\br{x \\cdot x}t}, $$\nso the result follows.\n\\end{proof}\n\n\\subsubsection{Asymptotic analysis}\n\nLet $ L \\subseteq \\RR^n $ be even and self-dual, so $ 8 \\mid n $, and let $ \\Theta_L = \\sum_{m = 0}^\\infty a_mq^m $, where $ a_m $ is the number of ways $ \\Q_L $ represents $ 2m $, so $ a_0 = 1 $. Then\n$$ \\Theta_L = \\E_{\\tfrac{n}{2}} + g, \\qquad \\E_{\\tfrac{n}{2}} \\sim \\sigma_{\\tfrac{n}{2} - 1}\\br{m} \\sim m^{\\tfrac{n}{2} - 1}, $$\nwhere $ g $ is a cusp form.\n\n\\lecture{12}{Monday}{28/10/19}\n\nLecture 12 is a problems class.\n\n\\lecture{13}{Friday}{01/11/19}\n\n\\begin{proposition}\nLet\n$$ \\E_k = \\sum_{n = 0}^\\infty a_nq^n = 1 + C\\sum_{n = 1}^\\infty \\sigma_{k - 1}\\br{n}q^n. $$\nThen there exist $ A, B \\in \\RR_{> 0} $ such that\n$$ An^{k - 1} \\le a_n \\le Bn^{k - 1}. $$\n\\end{proposition}\n\n\\begin{proof}\nSet $ A = C $. Then\n$$ \\sigma_{k - 1}\\br{n} = \\sum_{d \\mid n} d^{k - 1} \\ge n^{k - 1}, $$\nso $ a_n = C\\sigma_{k - 1}\\br{n} \\ge Cn^{k - 1} $. Consider\n$$ \\dfrac{\\sigma_{k - 1}\\br{n}}{n^{k - 1}} = \\sum_{d \\mid n} \\dfrac{d^{k - 1}}{n^{k - 1}} = \\sum_{d' \\mid n} \\dfrac{1}{d'^{k - 1}} \\le \\sum_{n = 1}^\\infty \\dfrac{1}{n^{k - 1}} = \\zeta\\br{k - 1}, $$\nso $ \\sigma_{k - 1}\\br{n} \\le \\zeta\\br{k - 1}n^{k - 1} $. So set $ B = C\\zeta\\br{k - 1} $, so $ a_n \\le Bn^{k - 1} $.\n\\end{proof}\n\n\\begin{theorem}[Hecke]\nLet $ f = \\sum_{n = 1}^\\infty a_nq^n $ be a cusp form of weight $ k $. Then\n$$ \\abs{a_n} = \\O\\br{n^{\\tfrac{k}{2}}}, $$\nthat is $ \\abs{a_n}n^{-k / 2} $ is bounded as $ n \\to \\infty $.\n\\end{theorem}\n\n\\pagebreak\n\n\\begin{proof}\n$ f / q $ is holomorphic on $ \\HH $, so $ \\abs{f / q} $ is bounded as $ q \\to 0 $, so $ \\abs{f\\br{z}} / e^{-2\\pi \\Im z} $ is bounded as $ \\Im z \\to \\infty $. That is, there exist $ M \\in \\RR $ such that $ \\abs{f\\br{z}} \\le Me^{-2\\pi \\Im z} $. Consider\n$$ \\phi\\br{z} = \\abs{f\\br{z}}\\Im z^{\\tfrac{k}{2}}, $$\nso $ \\lim_{\\Im z \\to \\infty} \\phi\\br{z} = 0 $. Note that\n$$ \\phi\\br{\\gamma z} = \\abs{f\\br{\\gamma z}}\\Im \\gamma z^{\\tfrac{k}{2}} = \\abs{f\\br{z}}\\abs{cz + d}^k\\dfrac{\\Im z^{\\tfrac{k}{2}}}{\\abs{cz + d}^{2\\tfrac{k}{2}}} = \\abs{f\\br{z}}\\Im z^{\\tfrac{k}{2}} = \\phi\\br{z}, \\qquad \\gamma = \\twobytwo{a}{b}{c}{d} \\in \\SL_2\\br{\\ZZ}. $$\nThen $ \\phi\\br{z} $ is determined by its values on the standard fundamental domain, so $ \\phi\\br{z} $ is bounded on $ \\HH $, so $ \\abs{f\\br{z}} < M'\\Im z^{-k / 2} $ for some $ M' \\in \\RR $. If $ z = x + iy $ for $ y $ fixed, then by the residue theorem,\n$$ a_m = \\dfrac{1}{2\\pi i}\\intd{C}{}{\\dfrac{f\\br{q}}{q^{m + 1}}}{q} = \\intd{-\\tfrac{1}{2}}{\\tfrac{1}{2}}{\\dfrac{f\\br{x + iy}}{e^{2\\pi i\\br{x + iy}m}}}{x}, $$\nwhere $ C $ is a circle around zero, oriented counterclockwise, so\n$$ \\abs{a_m} \\le \\intd{-\\tfrac{1}{2}}{\\tfrac{1}{2}}{\\dfrac{\\abs{f\\br{x + iy}}}{e^{-2\\pi ym}}}{x} \\le \\dfrac{\\abs{f\\br{x + iy}}}{e^{-2\\pi ym}} \\le e^{2\\pi ym}M'y^{-\\tfrac{k}{2}}. $$\nSet $ y = 1 / m $. Get $ \\abs{a_m} \\le e^{2\\pi}M'm^{k / 2} $, so $ \\abs{a_m} / m^{k / 2} $ is bounded.\n\\end{proof}\n\nHad\n$$ \\Theta_L = \\E_{\\tfrac{n}{2}} + g, \\qquad \\E_{\\tfrac{n}{2}} \\sim m^{\\tfrac{n}{2} - 1}, \\qquad g = \\O\\br{m^{\\tfrac{n}{4}}}. $$\n\n\\begin{theorem}[Deligne]\nLet $ f = \\sum_{n = 1}^\\infty a_nq^n $ be a cusp form of weight $ k $. Then\n$$ \\abs{a_n} = \\O\\br{n^{\\tfrac{k - 1}{2}}\\sigma_0\\br{n}}. $$\n\\end{theorem}\n\n\\begin{proof}\nVery rough sketch of argument.\n\\begin{itemize}[leftmargin=1in]\n\\item[Ramanujan 1910s.] Conjectured by Ramanujan for $ f = \\Delta $.\n\\item[Weil 1940s.] For an algebraic variety $ V $ over $ \\FF_q $, what can we say about $ \\#V\\br{\\FF_{q^n}} $ for various $ n $? Weil associated to $ V $ and $ \\FF_q $ a generating function called the \\textbf{zeta function} $ \\zeta_{V, q}\\br{t} $ of $ V $ over $ \\FF_q $, conjectured several things about $ \\zeta_{V, q} $, and proved in the case of curves.\n\\begin{itemize}\n\\item $ \\zeta_{V, q} $ is a rational function in $ t $.\n\\item $ \\zeta_{V, q} $ satisfies a certain symmetry under $ t \\mapsto 1 / t $.\n\\item The \\textbf{Riemann hypothesis}\n$$ \\zeta_{V, q}\\br{t} = \\dfrac{P_1\\br{t} \\dots P_{2d - 1}\\br{t}}{P_0\\br{t} \\dots P_{2d}\\br{t}}, \\qquad \\dim V = d, $$\nwhere the roots of $ P_i\\br{t} $ have absolute value $ q^{i / 2} $.\n\\end{itemize}\n\\item[Eichler-Shimura 1950s.] Let $ \\Gamma \\subseteq \\SL_2\\br{\\ZZ} $ be a nice \\textbf{congruence subgroup}. Then $ X_\\Gamma = \\Gamma \\backslash \\HH $ has the structure of an algebraic curve over $ \\QQ $, with \\textbf{good reduction} at primes $ p $ not dividing $ \\sbr{\\SL_2\\br{\\ZZ} : \\Gamma} $. Eichler, Shimura, and others studied $ \\zeta_{V, p} $ for $ V = X_\\Gamma $, and related $ \\zeta_{V, p} $ to the $ p $-th Fourier coefficients of a basis for forms of weight two and \\textbf{level} $ \\Gamma $. The \\textbf{Weil conjectures} bound $ a_p $ in terms of $ q^{1 / 2} $.\n\\item[Deligne 1960s.] Deligne showed that in weight $ k $, there exists a \\textbf{Kuga-Sato variety}, of dimension $ k - 1 $, whose zeta function has a factor coming from modular forms of weight $ k $ and level $ \\Gamma $, and showed that if the Weil conjectures, particularly the Riemann hypothesis, holds, then get the coefficient bound.\n\\item[Deligne 1970s.] The Riemann hypothesis in higher dimensions.\n\\end{itemize}\n\\end{proof}\n\n\\pagebreak\n\n\\subsection{Hecke operators}\n\n\\lecture{14}{Friday}{01/11/19}\n\nLet\n$$ \\Delta = \\dfrac{\\E_4^3 - \\E_6^2}{1728} = \\sum_{n = 1}^\\infty \\tau\\br{n}q^n = q\\prod_{m = 1}^\\infty \\br{1 - q^m}^{24} = q - 24q^2 + 252q^3 - 1472q^4 + 4830q^5 + \\dots. $$\nThen $ \\tau\\br{n} $ grows roughly like $ n^6 $ or $ n^{11 / 2 + \\epsilon} $. Mordell proved that\n\\begin{itemize}\n\\item $ \\tau\\br{mn} = \\tau\\br{n}\\tau\\br{m} $ if $ \\br{m, n} = 1 $, and\n\\item $ \\tau\\br{p^{n + 1}} = \\tau\\br{p}\\tau\\br{p^n} - p^{11}\\tau\\br{p^{n - 1}} $.\n\\end{itemize}\n\n\\begin{note*}\nIf $ \\E_k = 1 + C\\sum_n \\sigma_{k - 1}\\br{n}q^n $, set\n$$ \\E_k' = \\dfrac{1}{C} + \\sum_n \\sigma_{k - 1}\\br{n}q^n. $$\n\\begin{itemize}\n\\item If $ \\br{m, n} = 1 $, then\n$$ \\sigma_{k - 1}\\br{nm} = \\sum_{d \\mid n} \\sum_{d' \\mid m} \\br{dd'}^{k - 1} = \\br{\\sum_{d \\mid n} d^{k - 1}}\\br{\\sum_{d' \\mid m} d'^{k - 1}} = \\sigma_{k - 1}\\br{n}\\sigma_{k - 1}\\br{m}. $$\n\\item Since $ \\sigma_{k - 1}\\br{p^n} = 1 + \\dots + p^{n\\br{k - 1}} $,\n\\begin{align*}\n\\sigma_{k - 1}\\br{p}\\sigma_{k - 1}\\br{p^n}\n& = \\br{1 + p^{k - 1}}\\br{1 + \\dots + p^{n\\br{k - 1}}} \\\\\n& = 1 + 2p^{k - 1} + \\dots + 2p^{n\\br{k - 1}} + p^{\\br{n + 1}\\br{k - 1}} \\\\\n& = \\sigma_{k - 1}\\br{p^{n + 1}} + p^{k - 1}\\sigma_{k - 1}\\br{p^{n - 1}},\n\\end{align*}\nso\n$$ \\sigma_{k - 1}\\br{p^{n + 1}} = \\sigma_{k - 1}\\br{p}\\sigma_{k - 1}\\br{p^n} - p^{k - 1}\\sigma_{k - 1}\\br{p^{n - 1}}. $$\n\\end{itemize}\n\\end{note*}\n\n\\subsubsection{Correspondences}\n\n\\begin{definition}\nLet $ X $ be a set. The \\textbf{free abelian group on $ X $}, denoted $ \\ZZ X $, is the set of finite formal sums\n$$ \\sum_{i = 1}^r a_ix_i, \\qquad a_i \\in \\ZZ, \\qquad x_i \\in X, $$\nwhere $ x_i $ are distinct. Add by combining like terms.\n\\end{definition}\n\n\\begin{definition}\nA \\textbf{correspondence} on $ X $ is a homomorphism $ \\ZZ X \\to \\ZZ X $. Let\n$$ \\Corr X = \\cbr{\\text{correspondences on} \\ X}. $$\nEquivalently, a correspondence associates to each $ x \\in X $, a finite formal sum\n$$ \\sum_{i = 1}^r a_iy_i, \\qquad a_i \\in \\ZZ, \\qquad y_i \\in X. $$\n\\end{definition}\n\nIf $ X $ is a finite set $ X = \\cbr{x_1, \\dots, x_r} $, any correspondence $ T $ can be represented, in a unique way, by the matrix $ M_T $ such that\n$$ Tx_i = \\sum_{j = 1}^r \\br{M_T}_{ij}x_j, $$\nand composition of correspondences is matrix multiplication. Let $ X $ be a set, and let\n$$ \\Fun_\\CC X = \\cbr{\\text{functions} \\ X \\to \\CC}. $$\nThen $ T \\in \\Corr X $ acts on $ \\Fun_\\CC X $ as follows. If $ Tx = \\sum_i a_ix_i $ then $ \\br{Tf}x = \\sum_i a_if\\br{x_i} $. Check $ \\br{T \\circ T'}f = T\\br{T'f} $ etc. Let\n$$ \\LLL = \\cbr{\\text{lattices in} \\ \\CC}. $$\n\n\\pagebreak\n\n\\begin{example*}\n\\hfill\n\\begin{itemize}\n\\item For $ \\lambda \\in \\CC^\\times $, have\n$$ \\function[\\R_\\lambda]{\\ZZ\\LLL}{\\ZZ\\LLL}{L}{\\lambda L}. $$\n\\item For $ n \\in \\ZZ_{> 0} $, have\n$$ \\function[\\T_n]{\\ZZ\\LLL}{\\ZZ\\LLL}{L}{\\sum_{L' \\subseteq_n L} L'}, $$\nthe $ n $ \\textbf{Hecke operators}. Note that there are only finitely many $ L' \\subseteq_n L $, since if $ L' \\subseteq_n L $, then $ L' $ contains $ \\R_nL $. Then $ L / \\R_nL \\cong \\ZZ / n\\ZZ \\times \\ZZ / n\\ZZ $. The image of $ L' $ in $ L / \\R_nL $ is a subgroup $ H $ of $ \\ZZ / n\\ZZ \\times \\ZZ / n\\ZZ $ of order $ n $. The preimage of $ H $ in $ L $ is $ L' $. Thus there is a bijection\n$$ \\correspondence{\\text{subgroups of} \\ L / \\R_nL \\ \\text{of order} \\ n}{\\text{sublattices of} \\ L \\ \\text{of index} \\ n}. $$\n\\end{itemize}\n\\end{example*}\n\n\\begin{proposition}\n\\label{prop:correspondence}\n\\hfill\n\\begin{enumerate}\n\\item $ \\R_\\lambda\\R_\\mu = \\R_{\\lambda\\mu} $.\n\\item $ \\R_\\lambda\\T_n = \\T_n\\R_\\lambda $.\n\\item $ \\T_n\\T_m = \\T_{nm} $ if $ \\br{m, n} = 1 $.\n\\item $ \\T_p\\T_{p^n} = \\T_{p^{n + 1}} + p\\T_{p^{n - 1}}\\R_p $.\n\\end{enumerate}\n\\end{proposition}\n\n\\lecture{15}{Monday}{04/11/19}\n\n\\begin{corollary}\n$ \\T_p $ commute with each other for $ p $ prime, also with $ \\R_\\lambda $, and every $ \\T_n $ is a polynomial in $ \\T_p $ and $ \\R_p $ for $ p \\mid n $, so all $ \\T_n $ and $ \\R_\\lambda $ commute.\n\\end{corollary}\n\n\\begin{proposition}\nIf $ A $ is an abelian group of order $ nm $, with $ \\br{n, m} = 1 $, then $ A $ factors uniquely as $ B \\times C $, where $ B $ has order $ n $ and $ C $ has order $ m $. In particular $ B $ is the unique subgroup of $ A $ of order $ n $.\n\\end{proposition}\n\n\\begin{proof}\nWrite $ 1 = an + bm $ for $ a, b \\in \\ZZ $. Have a map\n$$ \\bijection{A}{mA \\times nA}{x}{\\br{mbx, nax}}{x + y}{\\br{x, y}}. $$\nThen $ mA $ has order $ n $ and $ nA $ has order $ m $. Clearly inverses on one side, so counting implies isomorphism.\n\\end{proof}\n\n\\begin{proof}[Proof of Proposition \\ref{prop:correspondence}]\n\\hfill\n\\begin{enumerate}\n\\item Easy.\n\\item If $ L \\in \\LLL $, then\n$$ \\R_\\lambda\\T_nL = \\R_\\lambda\\sum_{L' \\subseteq_n L} L' = \\sum_{L' \\subseteq_n L} \\R_\\lambda L' = \\sum_{L' \\subseteq_n \\R_\\lambda L} L' = \\T_n\\R_\\lambda L. $$\n\\item If $ L \\in \\LLL $, then\n$$ \\T_n\\T_mL = \\T_n\\sum_{L' \\subseteq_m L} L' = \\sum_{L' \\subseteq_m L} \\T_nL' = \\sum_{L' \\subseteq_m L} \\sum_{L'' \\subseteq_n L'} L''. $$\nAn observation is $ L'' \\subseteq_n L' \\subseteq_m L $, so $ L'' \\subseteq_{nm} L $. Then\n$$ \\T_n\\T_mL = \\sum_{L'' \\subseteq_{nm} L} c_{n, m}\\br{L'', L}L'', \\qquad c_{n, m}\\br{L'', L} = \\#\\cbr{L' \\in \\LLL \\st L'' \\subseteq_n L' \\subseteq_m L}. $$\nAn observation is that there is a bijection\n$$ \\bijection{\\cbr{\\text{lattices} \\ L' \\st L'' \\subseteq_n L' \\subseteq_m L}}{\\cbr{\\text{subgroups} \\ H \\ \\text{of} \\ L / L'' \\ \\text{of order} \\ n}}{L'}{L' / L'' \\subseteq L / L''}{\\text{preimage of} \\ H \\ \\text{under} \\ L \\to L / L''}{H}. $$\nHave $ \\br{n, m} = 1 $, then $ c_{n, m}\\br{L'', L} = 1 $ so\n$$ \\T_n\\T_mL = \\sum_{L'' \\subseteq_{nm} L} c_{n, m}\\br{L'', L}L'' = \\sum_{L'' \\subseteq_{nm} L} L'' = \\T_{nm}L. $$\n\n\\pagebreak\n\n\\item Similarly, if $ L \\in \\LLL $, then\n$$ \\T_p\\T_{p^r}L = \\sum_{L'' \\subseteq_{p^{r + 1}} L} c_{p, p^r}\\br{L'', L}L'', \\qquad c_{p, p^r}\\br{L'', L} = \\#\\cbr{L' \\in \\LLL \\st L'' \\subseteq_p L' \\subseteq_{p^r} L}. $$\nWhat is\n$$ c_{p, p^r}\\br{L'', L} = \\#\\cbr{\\text{subgroups of order} \\ p \\ \\text{in} \\ L / L''}? $$\n$ L / L'' $ is abelian of order $ p^{r + 1} $ and is generated by two elements. By the classification of finite abelian groups, every finite abelian group can be written uniquely as\n$$ \\ZZ / a_1\\ZZ \\times \\dots \\times \\ZZ / a_r\\ZZ, \\qquad a_1 \\mid \\dots \\mid a_r, $$\nup to isomorphism, and $ r $ is the minimal number of generators for such a group. So\n$$ L / L'' \\cong \\ZZ / p^a\\ZZ \\times \\ZZ / p^b\\ZZ, \\qquad a, b \\ge 0, \\qquad a + b = r + 1. $$\n\\begin{enumerate}[leftmargin=0.5in, label=Case \\arabic*.]\n\\item $ L / L'' \\cong \\ZZ / p^{r + 1}\\ZZ $ is cyclic. In this case $ c_{p, p^r}\\br{L'', L} = 1 $.\n\\item $ L / L'' \\cong \\ZZ / p^a\\ZZ \\times \\ZZ / p^b\\ZZ $ with $ a, b > 0 $. Any subgroup of order $ p $ is contained in the subgroup killed by $ p $,\n$$ p^{a - 1}\\ZZ / p^a\\ZZ \\times p^{b - 1}\\ZZ / p^b\\ZZ \\cong \\br{\\ZZ / p\\ZZ}^2. $$\nThe $ p^2 - 1 $ elements of $ \\br{\\ZZ / p\\ZZ}^2 $ other than zero each spans a subgroup of order $ p $, and two elements span the same group if and only if they differ by a scalar in $ \\br{\\ZZ / p\\ZZ}^\\times $, so there are $ \\br{p^2 - 1} / \\br{p - 1} = p + 1 $ subgroups of order $ p $ in $ \\br{\\ZZ / p\\ZZ}^2 $. In this case $ c_{p, p^r}\\br{L'', L} = p + 1 $.\n\\end{enumerate}\nThe latter case occurs if and only if $ L / L'' $ maps surjectively to $ \\br{\\ZZ / p\\ZZ}^2 \\cong L / \\R_pL $, if and only if $ \\R_pL \\supseteq L'' $. Thus\n\\begin{align*}\n\\T_p\\T_{p^r}L\n& = \\sum_{L'' \\subseteq_{p^{r + 1}} L} c_{p, p^r}\\br{L'', L}L''\n= \\sum_{L'' \\subseteq_{p^{r + 1}} L \\ \\text{cyclic}} L'' + \\br{p + 1}\\sum_{L'' \\subseteq_{p^{r + 1}} L \\ \\text{not cyclic}} L'' \\\\\n& = \\T_{p^{r + 1}}L + p\\sum_{L'' \\subseteq_{p^{r + 1}} L \\ \\text{not cyclic}} L''\n= \\T_{p^{r + 1}}L + p\\sum_{L'' \\subseteq_{p^{r - 1}} \\R_pL} L''\n= \\T_{p^{r + 1}}L + p\\T_{p^{r - 1}}\\R_pL.\n\\end{align*}\n\\end{enumerate}\n\\end{proof}\n\n\\subsubsection{Hecke operators}\n\n\\lecture{16}{Friday}{08/11/19}\n\nIf $ F : \\LLL \\to \\CC $, then\n$$ \\br{\\T_nF}\\br{L} = \\sum_{L' \\subseteq_n L} F\\br{L'}, \\qquad \\br{\\R_\\lambda F}\\br{L} = F\\br{\\R_\\lambda L}. $$\nRecall that $ F $ has weight $ k $ if $ F\\br{\\R_\\lambda L} = \\lambda^{-k}F\\br{L} $ for all $ \\lambda \\in \\CC^\\times $, if and only if\n$$ \\R_\\lambda F = \\lambda^{-k}F, \\qquad \\lambda \\in \\CC^\\times, $$\nso\n$$ \\R_\\lambda\\T_nF = \\T_n\\R_\\lambda F = \\T_n\\lambda^{-k}F = \\lambda^{-k}\\T_nF. $$\nSo the $ \\T_n $ and $ \\R_\\lambda $ preserve lattice functions of weight $ k $. Have a bijection\n$$ \\function{\\cbr{f : \\HH \\to \\CC \\st f\\br{\\gamma z} = \\br{cz + d}^kf\\br{z}}}{\\cbr{\\text{lattice functions} \\ F \\ \\text{of weight} \\ k}}{f\\br{z}}{F\\br{\\L_{z, 1}}}. $$\nOn lattice functions of weight $ k $, have\n$$ \\T_p\\T_{p^r} = \\T_{p^{r + 1}} + p^{1 - k}\\T_{p^{r - 1}}. $$\n\n\\begin{definition}\nFor $ f : \\HH \\to \\CC $ corresponding to $ F : \\LLL \\to \\CC $ of weight $ k $, define $ \\T_nf $ by\n$$ \\br{\\T_nf}\\br{z} = n^{k - 1}\\br{\\T_nF}\\br{\\L_{z, 1}} = n^{k - 1}\\sum_{L' \\subseteq_n \\L_{z, 1}} F\\br{L'}. $$\n\\end{definition}\n\n\\pagebreak\n\nOn $ f : \\HH \\to \\CC $, $ \\T_n $ satisfy\n$$ \\T_p\\T_{p^r} = \\T_{p^{r + 1}} + p^{k - 1}\\T_{p^{r - 1}}. $$\nNeed to rewrite $ \\sum_{L' \\subseteq_n \\L_{z, 1}} F\\br{L'} $ in terms of $ f $. Let\n$$ \\S^n = \\cbr{\\twobytwo{a}{b}{0}{d} \\in \\Mat_{2 \\times 2} \\ZZ \\st ad = n, \\ a, d > 0, \\ 0 \\le b < d}. $$\n\n\\begin{lemma}\nThe map\n$$ \\function{\\S^n}{\\cbr{\\text{sublattices of} \\ \\L_{z, 1} \\ \\text{of index} \\ n}}{\\twobytwo{a}{b}{0}{d}}{\\L_{az + b, d}} $$\nis a bijection.\n\\end{lemma}\n\n\\begin{proof}\nFor surjectivity, let $ L \\subseteq_n \\L_{z, 1} $. Then $ \\L_{z, 1} / L $ is a group of order $ n $. Can consider $ 1 + L \\in \\L_{z, 1} / L $. Let $ d $ be the order of $ 1 + L $, that is $ d $ is the smallest positive integer such that $ d \\in L $. Then $ d \\mid n $, so set $ a = n / d $. Let $ L' = \\ZZ + L $ be the lattice generated by $ 1 $ and $ L $. Then $ L \\subseteq_d L' $ and $ L \\subseteq_n \\L_{z, 1} $, so $ L' \\subseteq_a \\L_{z, 1} $, so $ az \\in L' $, so there exists $ b \\in \\ZZ $ such that $ az + b \\in L $. Since $ d \\in L $, without loss of generality can arrange $ 0 \\le b < d $. Now $ d \\in L $ and $ az + b \\in L $, so $ \\L_{az + b, d} \\subseteq_n \\L_{z, 1} $ and $ L \\subseteq_n \\L_{z, 1} $, so $ L = \\L_{az + b, d} $. Thus surjective, and for injectivity, can recover $ a, b, d $ from $ \\L_{az + b, d} \\subseteq \\L_{z, 1} $.\n\\end{proof}\n\nThus\n\\begin{align*}\n\\T_nf\n& = n^{k - 1}\\sum_{L' \\subseteq_n \\L_{z, 1}} F\\br{L'}\n= n^{k - 1}\\sum_{\\twobytwosmall{a}{b}{0}{d} \\in \\S^n} F\\br{\\L_{az + b, d}} \\\\\n& = n^{k - 1}\\sum_{\\twobytwosmall{a}{b}{0}{d} \\in \\S^n} d^{-k}F\\br{\\L_{\\tfrac{az + b}{d}, 1}}\n= n^{k - 1}\\sum_{\\twobytwosmall{a}{b}{0}{d} \\in \\S^n} d^{-k}f\\br{\\dfrac{az + b}{d}}.\n\\end{align*}\n\n\\begin{theorem}\nIf $ f = \\sum_{m = 0}^\\infty c_mq^m $ is modular of weight $ k $, then\n$$ \\T_nf = \\sum_{m = 0}^\\infty \\gamma_mq^m, \\qquad \\gamma_m = \\sum_{a \\mid \\br{m, n}, \\ a > 0} a^{k - 1}c_{\\tfrac{mn}{a^2}}. $$\n\\end{theorem}\n\n\\begin{proof}\n\\begin{align*}\n\\T_nf\n& = n^{k - 1}\\sum_{\\twobytwosmall{a}{b}{0}{d} \\in \\S^n} d^{-k}f\\br{\\dfrac{az + b}{d}}\n= n^{k - 1}\\sum_{\\twobytwosmall{a}{b}{0}{d} \\in \\S^n} \\sum_{m = 0}^\\infty d^{-k}c_me^{2\\pi im\\br{\\tfrac{az + b}{d}}} \\\\\n& = n^{k - 1}\\sum_{ad = n, \\ a > 0} \\sum_{b = 0}^{d - 1} \\sum_{m = 0}^\\infty d^{-k}c_mq^{\\tfrac{ma}{d}}e^{\\tfrac{2\\pi imb}{d}}\n= n^{k - 1}\\sum_{m = 0}^\\infty \\sum_{ad = n, \\ a > 0} d^{-k}c_mq^{\\tfrac{ma}{d}}\\sum_{b = 0}^{d - 1} e^{\\tfrac{2\\pi imb}{d}}.\n\\end{align*}\nThen\n$$ \\sum_{b = 0}^{d - 1} e^{\\tfrac{2\\pi imb}{d}} =\n\\begin{cases}\nd & d \\mid m \\\\\n0 & d \\nmid m\n\\end{cases},\n$$\nso\n$$ \\T_nf = n^{k - 1}\\sum_{m = 0, \\ d \\mid m}^\\infty \\sum_{ad = n, \\ a > 0} d^{1 - k}c_mq^{\\tfrac{ma}{d}} = \\sum_{a \\mid n, \\ a > 0} \\sum_{m' = 0}^\\infty a^{k - 1}c_{\\tfrac{m'n}{a}}q^{m'a}. $$\nWhich $ m' $ and $ a $ give $ q^m $? Need $ a \\mid \\br{m, n} $ for $ a > 0 $ and $ m'a = m $, so the coefficient is $ a^{k - 1}c_{mn / a^2} $. The sum of these is\n$$ \\gamma_m = \\sum_{a \\mid \\br{m, n}, \\ a > 0} a^{k - 1}c_{\\tfrac{mn}{a^2}}. $$\n\\end{proof}\n\n\\pagebreak\n\n\\begin{corollary}\n$ \\T_n $ preserves $ \\M_k $ and $ \\S_k $.\n\\end{corollary}\n\nIn the case $ n = p $,\n$$ \\T_pf = \\sum_{m = 0}^\\infty \\gamma_mq^m, \\qquad \\gamma_m =\n\\begin{cases}\nc_{mp} + p^{k - 1}c_{\\tfrac{m}{p}} & p \\mid m \\\\\nc_{mp} & p \\nmid m\n\\end{cases}.\n$$\n\n\\subsubsection{Eigenforms}\n\nAn observation is that the dimensions of $ \\M_4, \\M_6, \\M_8, \\M_{10}, \\S_{12} $ are one, so $ \\E_4, \\E_6, \\E_8, \\E_{10}, \\Delta $ are eigenvectors for $ \\T_n $ for all $ n $.\n\n\\begin{definition}\nA function $ f \\in \\M_k $ is an \\textbf{eigenform} if there exists $ \\lambda_n \\in \\CC^\\times $ such that $ \\T_nf = \\lambda_nf $ for all $ n \\in \\ZZ_{> 0} $.\n\\end{definition}\n\n\\lecture{17}{Friday}{08/11/19}\n\n\\begin{proposition}\n\\label{prop:eigenform}\nLet $ f \\in \\M_k $ be an eigenform, with $ k > 0 $, so $ \\T_nf = \\lambda_nf $ for all $ n $. Then if $ f = \\sum_m c_mq^m $, we have $ c_1 \\ne 0 $ and $ \\lambda_nc_1 = c_n $ for all $ n \\ge 1 $. In particular, if $ c_1 = 1 $, then $ c_n = \\lambda_n $ for all $ n $.\n\\end{proposition}\n\n\\begin{proof}\n$$ \\sum_{m = 0}^\\infty \\lambda_nc_mq^m = \\lambda_nf = \\T_nf = \\sum_{m = 0}^\\infty \\gamma_mq^m, \\qquad \\gamma_1 = \\sum_{a \\mid \\br{1, n}} a^{k - 1}c_n = c_n, $$\nso $ \\lambda_nc_1 = c_n $. Suppose $ c_1 = 0 $. Then $ c_n = 0 $ for all $ n \\ge 1 $, so $ f $ is constant. Since $ k \\ne 0 $, this does not happen.\n\\end{proof}\n\n\\begin{corollary}\nRecall that $ \\Delta\\br{z} = \\sum_n \\tau\\br{n}q^n $. Then\n\\begin{itemize}\n\\item $ \\tau\\br{mn} = \\tau\\br{n}\\tau\\br{m} $ if $ \\br{m, n} = 1 $, and\n\\item $ \\tau\\br{p^{r + 1}} = \\tau\\br{p}\\tau\\br{p^r} - p^{11}\\tau\\br{p^{r - 1}} $.\n\\end{itemize}\n\\end{corollary}\n\n\\begin{proof}\n$ \\Delta \\in \\S_{12} $ is one-dimensional, so there exists $ \\lambda_n $ such that $ \\T_n\\Delta = \\lambda_n\\Delta $. Proposition \\ref{prop:eigenform} implies that $ \\lambda_n = \\tau\\br{n} $ for all $ n $. Thus\n\\begin{itemize}\n\\item $ \\tau\\br{mn}\\Delta = \\lambda_{mn}\\Delta = \\T_{mn}\\Delta = \\T_m\\T_n\\Delta = \\lambda_m\\lambda_n\\Delta = \\tau\\br{m}\\tau\\br{n}\\Delta $, and\n\\item $ \\tau\\br{p^{r + 1}}\\Delta = \\T_{p^{r + 1}}\\Delta = \\T_p\\T_{p^r}\\Delta - p^{11}\\T_{p^{r - 1}}\\Delta = \\br{\\tau\\br{p}\\tau\\br{p^r} - p^{11}\\tau\\br{p^{r - 1}}}\\Delta $.\n\\end{itemize}\n\\end{proof}\n\nIn fact, the same argument shows if $ f \\in \\M_k $ for $ k > 0 $ is an eigenform, with $ q $-coefficient one, a \\textbf{normalised eigenform}, and $ f = \\sum_{n = 0}^\\infty c_nq^n $, then\n\\begin{itemize}\n\\item $ c_{nm} = c_nc_m $ if $ \\br{n, m} = 1 $, and\n\\item $ c_{p^{r + 1}} = c_pc_{p^r} - p^{k - 1}c_{p^{r - 1}} $.\n\\end{itemize}\n\n\\begin{proposition}\n$ \\E_k $ is an eigenform for all $ k $.\n\\end{proposition}\n\n\\begin{proof}\nIt suffices to show $ \\T_p\\E_k = \\lambda_p\\E_k $ for all primes $ p $. Recall that $ \\E_k $ is a constant multiple of $ \\G_k $. Now\n$$ \\br{\\T_p\\G_k}\\br{L} = \\sum_{L' \\subseteq_p L} \\sum_{w \\in L', \\ w \\ne 0} \\dfrac{1}{w^k} = \\sum_{w \\in L, \\ w \\ne 0} c_w\\dfrac{1}{w_k}, \\qquad c_w = \\#\\cbr{L' \\subseteq_p L \\st w \\in L'}. $$\nNote that $ pL \\subseteq L' \\subseteq L $. If $ w \\in pL $, then $ w \\in L' $ for all $ L' \\subseteq_p L $, and there are $ p + 1 $ of these. If $ w \\notin pL $, then $ pL \\subsetneq pL + \\ZZ w \\subsetneq L $ and $ pL \\subseteq_{p^2} L $, so $ pL \\subsetneq_p pL + \\ZZ w $ and $ pL + \\ZZ w \\subsetneq_p L $. In this case there exists a unique lattice of index $ p $ containing $ w $. Thus\n\\begin{align*}\n\\br{\\T_p\\G_k}\\br{L}\n& = \\sum_{w \\in L \\setminus pL} \\dfrac{1}{w^k} + \\br{p + 1}\\sum_{w \\in pL, \\ w \\ne 0} \\dfrac{1}{w^k}\n= \\sum_{w \\in L, \\ w \\ne 0} \\dfrac{1}{w^k} + p\\sum_{w \\in pL, \\ w \\ne 0} \\dfrac{1}{w^k} \\\\\n& = \\G_k\\br{L} + p\\sum_{w \\in L, \\ w \\ne 0} \\dfrac{1}{\\br{pw}^k}\n= \\G_k\\br{L} + p^{1 - k}\\sum_{w \\in L, \\ w \\ne 0} \\dfrac{1}{w^k}\n= \\br{1 + p^{1 - k}}\\G_k\\br{L},\n\\end{align*}\nso $ \\T_p\\E_k = \\br{1 + p^{k - 1}}\\E_k $.\n\\end{proof}\n\n\\pagebreak\n\nA question is does $ \\M_k $ have a basis of eigenforms for all $ k $? By linear algebra, there exist nice classes of operators that are guaranteed to admit bases of eigenvectors, such as self-adjoint, or more generally, normal operators.\n\n\\subsubsection{Hermitian pairings}\n\nLet $ V $ be a $ \\CC $-vector space and $ \\abr{\\cdot, \\cdot} : V \\times V \\to \\CC $ a \\textbf{Hermitian pairing}. That is,\n\\begin{itemize}\n\\item $ \\abr{\\lambda v + w, x} = \\lambda\\abr{v, x} + \\abr{w, x} $,\n\\item $ \\abr{x, y} = \\overline{\\abr{y, x}} $, and\n\\item $ \\abr{x, x} > 0 $ for all $ x \\ne 0 $.\n\\end{itemize}\n\n\\begin{example*}\nThe standard pairing\n$$ \\function{\\CC^n \\times \\CC^n}{\\CC}{\\abr{z, w}}{\\sum_{i = 1}^n z_i\\overline{w_i}}. $$\n\\end{example*}\n\n\\begin{definition}\nLet $ A : V \\to V $ be $ \\CC $-linear, and $ \\abr{\\cdot, \\cdot} : V \\times V \\to \\CC $ Hermitian. Then the \\textbf{adjoint} $ A^* : V \\to V $ is the unique linear map $ V \\to V $ such that\n$$ \\abr{Av, w} = \\abr{v, A^*w}. $$\nWe say $ A $ is \\textbf{self-adjoint} if $ A^* = A $, and \\textbf{normal} if $ A^* $ commutes with $ A $.\n\\end{definition}\n\n\\begin{theorem}\nIf $ A $ is normal, then $ A $ has a basis of eigenvectors.\n\\end{theorem}\n\n\\lecture{18}{Monday}{11/11/19}\n\n\\begin{lemma}\n$ A^{**} = A $.\n\\end{lemma}\n\n\\begin{proof}\nFor all $ v, w \\in V $,\n$$ \\abr{v, A^{**}w} = \\abr{A^*v, w} = \\overline{\\abr{w, A^*v}} = \\overline{\\abr{Aw, v}} = \\abr{v, Aw}, $$\nso $ A^{**}w = Aw $ for all $ w \\in V $.\n\\end{proof}\n\n\\begin{definition}\nIf $ W \\subseteq V $, let\n$$ W^\\perp = \\cbr{v \\in V \\st \\forall w \\in W, \\ \\abr{v, w} = 0}. $$\n\\end{definition}\n\n\\begin{proposition}\n$ \\im A^* = \\br{\\ker A}^\\perp $.\n\\end{proposition}\n\n\\begin{proof}\n$ \\abr{v, A^*w} = \\abr{Av, w} = 0 $ if $ v \\in \\ker A $. So $ \\im A^* \\subseteq \\br{\\ker A}^\\perp $, so $ \\rk A^* \\le \\rk A $. The same argument with $ A^* $ in place of $ A $ implies that $ \\rk A = \\rk A^{**} \\le \\rk A^* $. So $ \\rk A^* = \\rk A $, so $ \\im A^* = \\br{\\ker A}^\\perp $.\n\\end{proof}\n\nIn particular, $ \\im A^* \\cap \\ker A = \\cbr{0} $ and $ \\dim \\im A^* + \\dim \\ker A = \\rk A^* + n - \\rk A = n $. So\n$$ V = \\im A^* \\oplus \\ker A. $$\n\n\\begin{theorem}[Spectral theorem for normal operators]\nIf $ A $ and $ A^* $ commute, then $ A^* $ is diagonalisable.\n\\end{theorem}\n\n\\begin{proof}\nInduction on $ \\dim V $. Then $ \\dim V = 1 $ is clear. Let $ \\lambda $ be an eigenvalue of $ A $, and let $ A' = A - \\lambda\\id_V $, so $ V = \\ker A' \\oplus \\im A'^* $, where $ \\dim \\ker A' > 0 $. Then $ A $ commutes with $ A' $, and $ A'^* = A^* - \\overline{\\lambda}\\id_V $, so $ A $ commutes with $ A'^* $. So $ AA'^*v = A'^*Av $, so $ A $ preserves the image of $ A'^* $. The restriction of $ \\abr{\\cdot, \\cdot} $ to $ \\im A'^* $ is still Hermitian on $ \\im A'^* $ and the restriction of $ A $ to $ \\im A'^* $ is still normal, since its adjoint is the restriction of $ A^* $ to $ \\im A'^* $. By induction $ A $ is diagonalisable on $ \\im A'^* $ and scalar on $ \\ker A' $, so diagonalisable.\n\\end{proof}\n\nAlso the need the folllowing observation.\n\n\\begin{proposition}\nIf $ A : V \\to V $ and $ B : V \\to V $ commute, and $ V_\\lambda = \\ker \\br{A - \\lambda\\id_V} $, then $ BV_\\lambda = V_\\lambda $.\n\\end{proposition}\n\n\\begin{proof}\nIf $ v \\in V_\\lambda $, then $ ABv = BAv = B\\lambda v = \\lambda Bv $, so $ Bv \\in V_\\lambda $.\n\\end{proof}\n\n\\pagebreak\n\n\\subsubsection{The Petersson inner product}\n\nTo apply this to modular forms, we need a bilinear pairing on $ \\M_k $ or $ \\S_k $. The idea is to show that there exists a pairing $ \\abr{\\cdot, \\cdot}_k : \\S_k \\times \\S_k \\to \\CC $ such that $ \\abr{\\T_nf, g} = \\abr{f, \\T_ng} $ for all $ n $, so $ \\T_n $ are self-adjoint, hence diagonalisable.\n\n\\begin{definition}\nLet $ f, g \\in \\S_k $. The \\textbf{Petersson inner product of weight $ k $} is\n$$ \\abr{f, g}_k = \\iintd{\\DDD}{f\\br{z}\\overline{g\\br{z}}\\dfrac{y^k}{y^2}}{x}{y} = \\dfrac{i}{2}\\iintd{\\DDD}{f\\br{z}\\overline{g\\br{z}}\\dfrac{\\Im z^k}{\\Im z^2}}{z}{\\overline{z}}. $$\nHere $ z = x + iy $ and $ \\overline{z} = x - iy $, so\n$$ \\d z\\d\\overline{z} = \\br{\\d x + i\\d y} \\wedge \\br{\\d x - i\\d y} = -2i\\br{\\d x \\wedge \\d y}. $$\n\\end{definition}\n\nLet $ \\gamma = \\twobytwosmall{a}{b}{c}{d} \\in \\SL_2\\br{\\ZZ} $. Then\n$$ f\\br{\\gamma z}\\overline{g\\br{\\gamma z}}\\Im \\gamma z^k = f\\br{z}\\br{cz + d}^k\\overline{g\\br{z}\\br{cz + d}^k}\\dfrac{\\Im z^k}{\\abs{cz + d}^{2k}} = f\\br{z}\\overline{g\\br{z}}\\Im z^k, $$\nand\n$$ \\dfrac{1}{\\Im \\gamma z^2}\\d\\br{\\gamma z}\\d\\br{\\gamma \\overline{z}} = \\dfrac{1}{\\Im \\gamma z^2\\abs{cz + d}^4}\\d z\\d\\overline{z} = \\dfrac{1}{\\Im z^2}\\d z\\d\\overline{z}, $$\nso for all $ U \\subseteq \\HH $,\n$$ \\iintd{\\gamma\\br{U}}{f\\br{z}\\overline{g\\br{z}}\\dfrac{\\Im z^k}{\\Im z^2}}{z}{\\overline{z}} = \\iintd{U}{f\\br{z}\\overline{g\\br{z}}\\dfrac{\\Im z^k}{\\Im z^2}}{z}{\\overline{z}}. $$\n\n\\begin{note*}\nThis converges for $ f, g \\in \\S_k $, since $ f\\br{a + it} $ goes like $ e^{-t} $ as $ t \\to \\pm\\infty $, and the same for $ g $. If $ \\abr{f, f} = 0 $, the integrand vanishes identically, since it lives in $ \\RR_{\\ge 0} $. So $ f = 0 $ on $ \\DDD $, hence everywhere. Then\n$$ \\abr{\\lambda f, g}_k = \\lambda\\abr{f, g}_k, \\qquad \\abr{f, \\lambda g}_k = \\overline{\\lambda}\\abr{f, g}_k, \\qquad \\abr{f, g}_k = \\overline{\\abr{g, f}}_k. $$\nSo $ \\abr{\\cdot, \\cdot}_k $ is Hermitian.\n\\end{note*}\n\n\\begin{theorem}\n\\label{thm:innerproduct}\n$$ \\abr{\\T_nf, g}_k = \\abr{f, \\T_ng}_k, \\qquad f, g \\in \\S_k, \\qquad n \\in \\ZZ_{\\ge 1}. $$\n\\end{theorem}\n\n\\begin{corollary}\nEach $ \\T_n $ is diagonalisable on $ \\S_k $. Since $ \\T_n $ and $ \\T_m $ commute for all $ n $ and $ m $, $ \\T_m $ preserves eigenspaces of $ \\T_n $ for all $ m $. By induction, $ \\T_m $ preserves the simultaneous eigenspaces of $ \\T_n $ for all $ n < m $.\n\\end{corollary}\n\n\\begin{proposition}\nLet $ n > \\fbr{k / 12} + 1 $. Fix $ \\lambda_2, \\dots, \\lambda_n \\in \\CC $. The subspace $ V $ of $ \\S_k $ on which\n$$ \\T_i = \\lambda_i, \\qquad i = 2, \\dots, n $$\nis zero or one-dimensional.\n\\end{proposition}\n\n\\begin{proof}\nLet $ f \\in V $, so $ f = c_1q + c_2q^2 + \\dots $. Seen if $ \\T_if = \\lambda_if $, then $ c_i = \\lambda_ic_1 $. Also seen that if the first $ n $ Fourier coefficients of $ f $ vanishes, then $ f = 0 $, by the $ k / 12 $-formula. So $ c_1 \\ne 0 $ unless $ f = 0 $. Now if $ f, g \\in V \\setminus \\cbr{0} $, there exists $ \\lambda \\in \\CC $ such that $ f $ and $ \\lambda g $ have the same $ q $-coefficient, and thus the same first $ n $ Fourier coefficients. But then $ f - \\lambda g = 0 $.\n\\end{proof}\n\n\\begin{corollary}\n$ \\S_k $ admits a basis of eigenforms for all $ k $.\n\\end{corollary}\n\n\\begin{proof}\nLet $ n \\ge \\fbr{k / 12} + 1 $. Can diagonalise $ \\S_k $ with respect to the first $ n $ Hecke operators. Any simultaneous eigenspace for these is at most one-dimensional, and preserved by all $ \\T_n $. So each of these is actually an eigenspace for all $ \\T_n $.\n\\end{proof}\n\n\\pagebreak\n\n\\lecture{19}{Friday}{15/11/19}\n\n\\begin{note*}\nIf $ f $ and $ g $ are eigenforms, and $ f $ is not a scalar multiple of $ g $, there exists $ \\T_n $ such that $ \\T_nf = \\lambda_nf $ and $ \\T_ng = \\mu_ng $ with $ \\lambda_n \\ne \\mu_n $. Then\n$$ \\abr{\\T_nf, g}_k = \\abr{\\lambda_nf, g}_k = \\lambda_n\\abr{f, g}_k, \\qquad \\abr{f, \\T_ng}_k = \\abr{f, \\mu_ng}_k = \\overline{\\mu_n}\\abr{f, g}_k, $$\n$$ \\lambda_n\\abr{f, f}_k = \\abr{\\T_nf, f}_k = \\abr{f, \\T_nf}_k = \\overline{\\abr{\\T_nf, f}}_k = \\overline{\\lambda_n}\\abr{f, f}_k. $$\nSo $ \\lambda_n = \\overline{\\lambda_n} $ and $ \\mu_n = \\overline{\\mu_n} $. Then $ \\br{\\lambda_n - \\mu_n}\\abr{f, g}_k = 0 $, so $ \\abr{f, g}_k = 0 $.\n\\end{note*}\n\nBy the formula for $ \\T_n $ on $ q $-expansions, $ \\T_n $ takes a $ q $-expansion with integer coefficients to another such. Saw that the space of modular forms with integral $ q $-expansions is spanned by\n$$ \\E_4^n\\E_6^m, \\dots, \\E_4^{n - 3\\fbr{n / 3}}\\E_6^m\\Delta^{\\fbr{n / 3}}, \\qquad k = 4n + 6m, \\qquad n, m > 0, $$\nwhere $ m = 0, 1 $ is minimal, so the matrix of $ \\T_n $ with respect to this basis has integer entries. Thus the characteristic polynomial of $ \\T_n $ on $ \\S_k $ has integer coefficients, so the eigenvalues of $ \\T_n $ are algebraic integers.\n\n\\begin{example*}\nCan ask when modular forms are congruent modulo $ p $. In fact $ \\E_{12} \\equiv \\Delta \\mod 691 $.\n\\end{example*}\n\nRibet 1970s proved that when an Eisenstein series of suitable weight is congruent modulo $ p $ to a cusp form, can use the Galois representation attached to that cusp form to construct elements of ideal class groups of cyclotomic fields.\n\n\\subsection{\\texorpdfstring{$ \\L $}{L}-functions}\n\n\\subsubsection{Dirichlet \\texorpdfstring{$ \\L $}{L}-functions}\n\n\\begin{definition}\nLet $ \\cbr{a_n}_{n \\ge 1} $ be a sequence of complex numbers, usually algebraic integers. The \\textbf{Dirichlet series} attached to $ a_n $ is the formal series\n$$ \\sum_{n = 1}^\\infty a_nn^{-s}, $$\nthought of as a function of $ s \\in \\CC $.\n\\end{definition}\n\nIn general, if $ \\abs{a_n} \\le Cn^k $, then the corresponding series converges absolutely for $ \\Re s > k + 1 $.\n\n\\begin{example*}\n\\hfill\n\\begin{itemize}\n\\item The \\textbf{Riemann $ \\zeta $-function} is\n$$ \\zeta\\br{s} = \\sum_{n = 1}^\\infty n^{-s}. $$\n\\item Let $ \\chi : \\br{\\ZZ / N\\ZZ}^\\times \\to \\CC^\\times $ be a \\textbf{primitive character}, that is does not factor through $ \\br{\\ZZ / N\\ZZ}^\\times \\to \\br{\\ZZ / m\\ZZ}^\\times $ for $ m \\mid N $ such that $ m \\ne N $. Set\n$$ a_n =\n\\begin{cases}\n\\chi\\br{n} & \\br{n, N} = 1 \\\\\n0 & \\br{n, N} \\ne 1\n\\end{cases}.\n$$\nThen\n$$ \\L\\br{s, \\chi} = \\sum_{n = 1}^\\infty a_nn^{-s} $$\nis the \\textbf{Dirichlet $ \\L $-function} attached to $ \\chi $.\n\\end{itemize}\n\\end{example*}\n\nIn both these examples, and many others,\n\\begin{itemize}\n\\item these series have meromorphic, and often analytic, continuations to all of $ \\CC $,\n\\item there is a \\textbf{functional equation} relating values at $ s $ and $ k - s $ for some $ k $, and\n\\item there is an \\textbf{Euler product}.\n\\end{itemize}\n\n\\pagebreak\n\n\\begin{example*}\n$$ \\zeta\\br{s} = 2^s\\pi^{s - 1}\\sin \\tfrac{\\pi s}{2}\\Gamma\\br{1 - s}\\zeta\\br{1 - s}, \\qquad \\zeta\\br{s} = \\prod_{p \\ \\text{prime}} \\dfrac{1}{1 - p^{-s}}, \\qquad \\L\\br{s, \\chi} = \\prod_{p \\nmid N} \\dfrac{1}{1 - \\chi\\br{p}p^{-s}}. $$\n\\end{example*}\n\n\\subsubsection{Hecke \\texorpdfstring{$ \\L $}{L}-functions}\n\n\\begin{definition}\nLet $ f = \\sum_{n = 0}^\\infty a_nq^n \\in \\M_k $. Define the \\textbf{Hecke $ \\L $-function of weight $ k $}\n$$ \\L\\br{s, f} = \\sum_{n = 1}^\\infty a_nn^{-s}. $$\n\\end{definition}\n\n\\begin{example*}\nLet\n$$ f = \\E_k' = \\b_k\\dfrac{\\br{-1}^{\\tfrac{k}{2}}}{2k} + \\sum_{n = 1}^\\infty \\sigma_{k - 1}\\br{n}q^n. $$\nThen\n$$ \\L\\br{s, f} = \\sum_{n = 1}^\\infty \\sigma_{k - 1}\\br{n}n^{-s} = \\prod_{p \\ \\text{prime}} \\dfrac{1}{1 - \\sigma_{k - 1}\\br{p}p^{-s}} = \\prod_{p \\ \\text{prime}} \\dfrac{1}{1 - p^{-s}} \\cdot \\dfrac{1}{1 - p^{k - 1}p^{-s}} = \\zeta\\br{s}\\zeta\\br{s - k + 1}, $$\nsince $ \\sigma_{k - 1}\\br{mn} = \\sigma_{k - 1}\\br{m}\\sigma_{k - 1}\\br{n} $ for $ \\br{m, n} = 1 $ and $ \\sigma_{k - 1}\\br{p^r} = 1 + \\dots + p^{r\\br{k - 1}} $.\n\\end{example*}\n\n\\lecture{20}{Friday}{15/11/19}\n\nLet $ f = \\sum_{n = 1}^\\infty a_nq^n $ be a cusp form. Recall that Hecke implies that $ \\abs{a_n} \\le Cn^{k / 2} $, so gives absolute convergence of $ \\L\\br{s, f} $ for $ \\Re s > k / 2 + 1 $.\n\n\\begin{theorem}\n\\label{thm:lfunction}\n\\hfill\n\\begin{enumerate}\n\\item $ \\L\\br{s, f} $ extends to a holomorphic function on all of $ \\CC $.\n\\item Set\n$$ \\R\\br{s, f} = \\dfrac{\\Gamma\\br{s}}{\\br{2\\pi}^s}\\L\\br{s, f}. $$\nThen\n$$ \\R\\br{s, f} = \\br{-1}^{\\tfrac{k}{2}}\\R\\br{k - s, f}. $$\n\\item If $ f $ is a normalised eigenform, then\n$$ \\L\\br{s, f} = \\prod_{p \\ \\text{prime}} \\dfrac{1}{1 - a_pp^{-s} + p^{k - 1}p^{-2s}}. $$\n\\end{enumerate}\n\\end{theorem}\n\n\\begin{definition}\nThe infinite product $ \\prod_{n = 1}^\\infty \\br{1 + c_n} $ \\textbf{converges} if\n$$ \\lim_{N \\to \\infty} \\prod_{n = 1}^N \\br{1 + c_n} $$\nconverges to a non-zero number, if and only if $ \\sum_{n = 1}^\\infty \\log \\br{1 + c_n} $ converges. Then $ \\prod_{n = 1}^\\infty \\br{1 + c_n} $ \\textbf{converges absolutely} if\n$$ \\prod_{n = 1}^\\infty \\br{1 + \\abs{c_n}} $$\nconverges.\n\\end{definition}\n\n\\begin{lemma}\n$ \\prod_{n = 1}^\\infty \\br{1 + c_n} $ converges absolutely if and only if $ \\sum_{n = 1}^\\infty \\abs{c_n} $ converges.\n\\end{lemma}\n\n\\begin{proof}\n$$ \\sum_{n = 1}^N \\abs{c_n} \\le \\prod_{n = 1}^N \\br{1 + \\abs{c_n}} \\le \\prod_{n = 1}^N e^{\\abs{c_n}} \\le e^{\\sum_{n = 1}^\\infty \\abs{c_n}}. $$\n\\end{proof}\n\n\\pagebreak\n\n\\begin{proof}[Proof of Theorem \\ref{thm:lfunction}]\nRecall that\n$$ \\Gamma\\br{s} = \\intd{0}{\\infty}{t^{s - 1}e^{-t}}{t} $$\nis meromorphic on $ \\HH $, with poles at $ \\ZZ_{\\le 0} $ and never zero, and satisfies $ \\Gamma\\br{s + 1} = s\\Gamma\\br{s} $ so $ \\Gamma\\br{n} = \\br{n - 1}! $. Substituting $ t \\mapsto 2\\pi nt $ in $ \\Gamma\\br{s} $,\n$$ \\Gamma\\br{s} = \\intd{0}{\\infty}{\\br{2\\pi nt}^{s - 1}e^{-2\\pi nt}\\br{2\\pi n}}{t} = \\br{2\\pi n}^s\\intd{0}{\\infty}{t^{s - 1}e^{-2\\pi nt}}{t}, $$\nso\n$$ \\L\\br{s, f} = \\sum_{n = 1}^\\infty a_nn^{-s} = \\sum_{n = 1}^\\infty a_n\\dfrac{\\br{2\\pi}^s}{\\Gamma\\br{s}}\\intd{0}{\\infty}{t^{s - 1}e^{-2\\pi nt}}{t}. $$\nThen\n\\begin{align*}\n\\R\\br{s, f}\n& = \\dfrac{\\Gamma\\br{s}}{\\br{2\\pi}^s}\\L\\br{s, f}\n= \\sum_{n = 1}^\\infty a_n\\intd{0}{\\infty}{t^{s - 1}e^{-2\\pi nt}}{t}\n= \\intd{0}{\\infty}{t^{s - 1}\\sum_{n = 1}^\\infty a_ne^{-2\\pi nt}}{t}\n= \\intd{0}{\\infty}{t^{s - 1}f\\br{it}}{t} \\\\\n& = \\intd{0}{1}{t^{s - 1}f\\br{it}}{t} + \\intd{1}{\\infty}{t^{s - 1}f\\br{it}}{t}\n= \\intd{1}{\\infty}{\\br{\\dfrac{1}{t}}^{s - 1}f\\br{\\dfrac{i}{t}}}{\\br{\\dfrac{1}{t}}} + \\intd{1}{\\infty}{t^{s - 1}f\\br{it}}{t} \\\\\n& = \\intd{1}{\\infty}{\\br{t^{-s - 1}\\br{it}^kf\\br{it} + t^{s - 1}f\\br{it}}}{t}\n= \\intd{1}{\\infty}{f\\br{it}\\br{\\br{-1}^{\\tfrac{k}{2}}t^{k - s - 1} + t^{s - 1}}}{t}.\n\\end{align*}\n\\begin{enumerate}\n\\item $ \\R\\br{s, f} $ converges independently of $ s $ uniformly for $ s $ in a compact subset of $ \\CC $, so it is holomorphic in $ s $, and extends to a holomorphic function on $ \\CC $. Then\n$$ \\L\\br{s, f} = \\dfrac{\\br{2\\pi}^s}{\\Gamma\\br{s}}\\R\\br{s, f}, $$\nso $ \\L\\br{s, f} $ is holomorphic since $ \\Gamma\\br{s} $ is non-vanishing.\n\\item $ \\R\\br{s, f} $ is symmetric up to a sign under $ s \\mapsto k - s $, so\n$$ \\R\\br{s, f} = \\br{-1}^{\\tfrac{k}{2}}\\R\\br{k - s, f}. $$\n\\item Now assume $ f $ is a normalised eigenform, so $ f = \\sum_{n = 1}^\\infty a_nq^n $ with $ a_1 = 1 $ and $ \\T_nf = a_nf $. Then $ a_{nm} = a_na_m $ if $ \\br{n, m} = 1 $, so\n$$ \\L\\br{s, f} = \\sum_n a_nn^{-s} = \\prod_{p \\ \\text{prime}} \\sum_{k = 0}^\\infty a_{p^k}p^{-ks}, $$\na power series in $ p^{-s} $. Fix $ p $, and consider\n$$ \\br{1 - a_pp^{-s} + p^{k - 1}p^{-2s}}\\sum_{k = 0}^\\infty a_{p^k}p^{-ks}. $$\nThe $ p^0 $ coefficient is $ a_1 = 1 $, the $ p^{-s} $ coefficient is $ a_pp^{-s} - a_pp^{-s} = 0 $, and the $ p^{-\\br{r + 1}s} $ coefficient is\n$$ a_{p^{r + 1}}p^{-\\br{r + 1}s} - a_pa_{p^r}p^{-\\br{r + 1}s} + p^{k - 1}a_{p^{r - 1}}p^{-\\br{r + 1}s} = \\br{a_{p^{r + 1}} - a_pa_{p^r} + p^{k - 1}a_{p^{r - 1}}}p^{-\\br{r + 1}s} = 0, $$\nsince $ a_{p^{r + 1}} = a_pa_{p^r} - p^{k - 1}a_{p^{r - 1}} $. So\n$$ \\L\\br{s, f} = \\prod_{p \\ \\text{prime}} \\sum_{k = 0}^\\infty a_{p^k}p^{-ks} = \\prod_{p \\ \\text{prime}} \\dfrac{1}{1 - a_pp^{-s} + p^{k - 1}p^{-2s}}. $$\n\\end{enumerate}\n\\end{proof}\n\n\\lecture{21}{Monday}{18/11/19}\n\nLecture 21 is a problems class.\n\n\\pagebreak\n\n\\section{Modular forms of higher level}\n\n\\subsection{Modular forms}\n\n\\subsubsection{Congruence subgroups}\n\n\\lecture{22}{Friday}{22/11/19}\n\n$ \\GL_2\\br{\\QQ}_+ $ acts on $ \\HH $ by fractional linear transformations.\n\n\\begin{definition}\n$ \\Gamma\\br{N} \\subseteq \\SL_2\\br{\\ZZ} $ is the kernel of $ \\SL_2\\br{\\ZZ} \\to \\SL_2\\br{\\ZZ / N\\ZZ} $ for $ N \\in \\ZZ_{> 0} $. Alternatively,\n$$ \\Gamma\\br{N} = \\cbr{\\twobytwo{a}{b}{c}{d} \\in \\SL_2\\br{\\ZZ} \\st a \\equiv d \\equiv 1 \\mod N, \\ b \\equiv c \\equiv 0 \\mod N}. $$\n\\end{definition}\n\n\\begin{note*}\n$ \\Gamma\\br{N} \\subseteq \\SL_2\\br{\\ZZ} $ has finite index.\n\\end{note*}\n\n\\begin{definition}\n$ \\Gamma \\subseteq \\GL_2\\br{\\QQ}_+ $ is a \\textbf{congruence subgroup} if $ \\Gamma $ contains $ \\Gamma\\br{N} $ with finite index for some $ N \\in \\ZZ_{> 0} $.\n\\end{definition}\n\n\\begin{example*}\n$ \\SL_2\\br{\\ZZ} $ and $ \\Gamma\\br{N} $ are congruence subgroups. Let\n$$ \\Gamma_0\\br{N} = \\cbr{\\twobytwo{a}{b}{c}{d} \\in \\SL_2\\br{\\ZZ} \\st c \\equiv 0 \\mod N}, $$\nand\n$$ \\Gamma_1\\br{N} = \\cbr{\\twobytwo{a}{b}{c}{d} \\in \\SL_2\\br{\\ZZ} \\st a \\equiv d \\equiv 1 \\mod N, \\ c \\equiv 0 \\mod N}, $$\nso $ \\Gamma_1\\br{N} $ is the preimage of $ \\twobytwosmall{1}{b}{0}{1} \\subseteq \\SL_2\\br{\\ZZ / N\\ZZ} $ in $ \\SL_2\\br{\\ZZ} $. Then $ \\Gamma_0\\br{N} $ and $ \\Gamma_1\\br{N} $ are congruence subgroups such that\n$$ \\Gamma\\br{N} \\subseteq \\Gamma_1\\br{N} \\subseteq \\Gamma_0\\br{N} \\subseteq \\SL_2\\br{\\ZZ}. $$\n\\end{example*}\n\n\\begin{proposition}\nLet $ \\alpha \\in \\GL_2\\br{\\QQ}_+ $, and let $ \\Gamma $ be a congruence subgroup. Then $ \\alpha\\Gamma\\alpha^{-1} $ is also a congruence subgroup.\n\\end{proposition}\n\n\\begin{proof}\nNeed that there exists $ M $ with $ \\Gamma\\br{M} \\subseteq \\alpha\\Gamma\\alpha^{-1} $ with finite index. There exists $ N $ such that $ \\Gamma\\br{N} \\subseteq \\Gamma $. Note that $ \\Gamma\\br{N} = \\SL_2\\br{\\QQ} \\cap \\br{\\id_2 + N\\Mat_2 \\ZZ} $. Consider\n$$ \\alpha\\Gamma\\br{N}\\alpha^{-1} = \\SL_2\\br{\\QQ} \\cap \\br{\\id_2 + N\\alpha\\Mat_2 \\ZZ\\alpha^{-1}}. $$\nChoose $ n \\in \\ZZ $ such that $ n\\alpha $ and $ n\\alpha^{-1} $ have entries in $ \\ZZ $. Then $ n^2\\alpha^{-1}\\Mat_2 \\ZZ\\alpha \\subseteq \\Mat_2 \\ZZ $, so $ n^2\\Mat_2 \\ZZ \\subseteq \\alpha\\Mat_2 \\ZZ\\alpha^{-1} $, so $ Nn^2\\Mat_2 \\ZZ \\subseteq N\\alpha\\Mat_2 \\ZZ\\alpha^{-1} $, so\n$$ \\Gamma\\br{n^2N} = \\SL_2\\br{\\QQ} \\cap \\br{\\id_2 + Nn^2\\Mat_2 \\ZZ} \\subseteq \\SL_2\\br{\\QQ} \\cap \\br{\\id_2 + N\\alpha\\Mat_2 \\ZZ\\alpha^{-1}} = \\alpha\\Gamma\\br{N}\\alpha^{-1}. $$\nSimilarly, show\n$$ \\alpha\\Gamma\\br{n^4N}\\alpha^{-1} \\subseteq \\Gamma\\br{n^2N} \\subseteq \\alpha\\Gamma\\br{N}\\alpha^{-1}. $$\nSince $ \\Gamma\\br{n^4N} $ has finite index in $ \\Gamma\\br{N} $, $ \\Gamma\\br{n^2N} $ has finite index in $ \\alpha\\Gamma\\br{N}\\alpha^{-1} $.\n\\end{proof}\n\n\\begin{note*}\nAlso, if $ T = \\lcm\\br{M, N} $ then $ \\Gamma\\br{T} \\subseteq \\Gamma\\br{M} \\cap \\Gamma\\br{N} $, so the intersection of two congruence subgroups is a congruence subgroup.\n\\end{note*}\n\n\\begin{example*}\nLet $ \\alpha = \\twobytwosmall{p}{0}{0}{1} $. Then\n$$ \\alpha^{-1}\\SL_2\\br{\\ZZ}\\alpha = \\cbr{\\twobytwo{a}{p^{-1}b}{pc}{d} \\st \\twobytwo{a}{b}{c}{d} \\in \\SL_2\\br{\\ZZ}}, $$\nand\n$$ \\alpha^{-1}\\SL_2\\br{\\ZZ}\\alpha \\cap \\SL_2\\br{\\ZZ} = \\cbr{\\twobytwo{a}{b}{pc}{d} \\st ad - bpc = 1} = \\Gamma_0\\br{p}. $$\n\\end{example*}\n\n\\pagebreak\n\n\\subsubsection{Modular forms}\n\nRecall that for $ f : \\HH \\to \\CC $ and $ \\alpha = \\twobytwosmall{a}{b}{c}{d} \\in \\GL_2\\br{\\QQ}_+ $, we defined $ \\eval{f}_{k, \\alpha} $ by\n$$ \\eval{f}_{k, \\alpha}\\br{z} = \\det \\alpha^{k - 1}f\\br{\\alpha z}\\br{cz + d}^{-k}. $$\nSuppose we have a $ \\Gamma \\subseteq \\SL_2\\br{\\QQ} $ and $ f : \\HH \\to \\CC $ such that $ \\eval{f}_{k, \\gamma} = f $ for all $ \\gamma \\in \\Gamma $. Then if $ g = \\eval{f}_{k, \\alpha} $, then $ \\eval{g}_{k, \\alpha^{-1}\\gamma\\alpha} = g $, since\n$$ \\eval{\\br{\\eval{f}_{k, \\alpha}}}_{k, \\alpha^{-1}\\gamma\\alpha} = \\eval{f}_{k, \\gamma\\alpha} = \\eval{\\br{\\eval{f}_{k, \\gamma}}}_{k, \\alpha} = \\eval{f}_{k, \\alpha}. $$\nFix $ \\Gamma \\subseteq \\SL_2\\br{\\QQ} $ a congruence subgroup.\n\n\\begin{definition}\nA function $ f : \\HH \\to \\CC $ is a \\textbf{weakly holomorphic or meromorphic modular form of weight $ k $ and level $ \\Gamma $} if\n\\begin{itemize}\n\\item $ \\eval{f}_{k, \\gamma} = f $ for all $ \\gamma \\in \\Gamma $, and\n\\item $ f $ is holomorphic or meromorphic on $ \\HH $.\n\\end{itemize}\n\\end{definition}\n\nA question is what condition should we impose at $ \\infty $ to get a good theory?\n\n\\begin{example*}\nLet $ k \\ge 4 $ and $ N \\in \\ZZ $, and let\n$$ \\E_k^{0, 1}\\br{z} = \\sum_{\\br{m, n} \\in S^{0, 1}} \\dfrac{1}{\\br{mz + n}^k}, \\qquad S^{0, 1} = \\cbr{\\br{m, n} \\in \\ZZ^2 \\setminus \\cbr{0} \\st m \\equiv 1 \\mod N, \\ n \\equiv 0 \\mod N}. $$\nClaim that $ \\E_k^{0, 1}\\br{\\gamma z} = \\E_k^{0, 1}\\br{z} $ for $ \\gamma \\in \\Gamma\\br{N} $. Let $ \\gamma = \\twobytwosmall{a}{b}{c}{d} \\in \\Gamma\\br{N} $. Then\n\\begin{align*}\n\\E_k^{0, 1}\\br{\\gamma z}\n& = \\sum_{\\br{m, n} \\in S^{0, 1}} \\dfrac{1}{\\br{m\\br{\\tfrac{az + b}{cz + d}} + n}^k}\n= \\br{cz + d}^k\\sum_{\\br{m, n} \\in S^{0, 1}} \\dfrac{1}{\\br{m\\br{az + b} + n\\br{cz + d}}^k} \\\\\n& = \\br{cz + d}^k\\sum_{\\br{m, n} \\in S^{0, 1}} \\dfrac{1}{\\br{\\br{ma + nc}z + \\br{mb + nd}}^k}.\n\\end{align*}\nSince $ m \\equiv a \\equiv d \\equiv 1 \\mod N $ and $ n \\equiv b \\equiv c \\equiv 0 \\mod N $, $ ma + nc \\equiv 1 \\mod N $ and $ mb + nd \\equiv 0 \\mod N $, so $ \\br{ma + nc, mb + nd} \\in S^{0, 1} $. Moreover, the map\n$$ \\bijection{S^{0, 1}}{S^{0, 1}}{\\br{m, n}}{\\br{ma + nc, mb + nd}}{\\br{m'a' + n'c', m'b' + n'd'}}{\\br{m', n'}} $$\nis a bijection, where $ \\gamma^{-1} = \\twobytwosmall{a'}{b'}{c'}{d'} $. So $ \\E_k^{0, 1}\\br{\\gamma z} = \\E_k^{0, 1}\\br{z}\\br{cz + d}^k $.\n\\end{example*}\n\n\\lecture{23}{Friday}{22/11/19}\n\nEvery congruence subgroup is conjugate to a subgroup of $ \\SL_2\\br{\\ZZ} $, and $ \\twobytwosmall{1}{1}{0}{1} \\in \\SL_2\\br{\\ZZ} $ need not be in $ \\Gamma $. On the other hand, if $ \\Gamma \\subseteq \\SL_2\\br{\\ZZ} $, then $ \\Gamma $ has finite index in $ \\SL_2\\br{\\ZZ} $, so there exists a minimal $ \\n_\\Gamma > 0 $ such that $ \\twobytwosmall{1}{\\n_\\Gamma}{0}{1} \\in \\Gamma $. Then if $ f $ is weakly modular of weight $ k $ and level $ \\Gamma $, know $ f\\br{z + \\n_\\Gamma} = f\\br{z} $ for all $ z $, so $ f $ is a function of $ q^{1 / \\n_\\Gamma} $. Let $ g\\br{q^{1 / \\n_\\Gamma}} $ be a function on $ \\DD \\setminus \\cbr{0} $ such that $ f\\br{z} = g\\br{e^{2\\pi iz / \\n_\\Gamma}} $. Then if $ g $ is meromorphic on $ \\DD $, can express $ g $ as a Laurent series in $ q^{1 / \\n_\\Gamma} $. We say $ f $ is \\textbf{meromorphic at $ \\infty $}, and the series for $ q $ is its \\textbf{$ q $-expansion}.\n\n\\begin{example*}\n\\hfill\n\\begin{itemize}\n\\item For $ \\Gamma = \\Gamma_0\\br{N} $ or $ \\Gamma = \\Gamma_1\\br{N} $, $ \\n_\\Gamma = 1 $.\n\\item For $ \\Gamma = \\Gamma\\br{N} $, $ \\n_\\Gamma = N $.\n\\end{itemize}\n\\end{example*}\n\n\\subsubsection{A fundamental domain}\n\nA question is for $ \\Gamma \\subseteq \\SL_2\\br{\\ZZ} $, can we write down a fundamental domain for $ \\Gamma $? For all $ z \\in \\HH $, there exists $ \\gamma \\in \\SL_2\\br{\\ZZ} $ such that $ \\gamma z \\in \\DDD $. For $ \\Gamma \\subseteq \\SL_2\\br{\\ZZ} $, write\n$$ \\SL_2\\br{\\ZZ} = \\bigsqcup_{\\gamma_i \\in \\SL_2\\br{\\ZZ}} \\pm\\gamma_i \\cdot \\Gamma. $$\n\n\\pagebreak\n\nSet\n$$ \\DDD_\\Gamma = \\bigcup_i \\gamma_i^{-1} \\cdot \\DDD. $$\n\n\\begin{theorem}\n\\hfill\n\\begin{enumerate}\n\\item For all $ z \\in \\HH $, there exists $ \\gamma \\in \\Gamma $ such that $ \\gamma z \\in \\DDD_\\Gamma $.\n\\item The subset $ \\cbr{z \\in \\DDD_\\Gamma \\st \\Gamma \\cdot z \\cap \\DDD_\\Gamma \\ne \\cbr{z}} $ is contained in $ \\bigcup_{\\gamma_i \\in \\SL_2\\br{\\ZZ}} \\gamma_i \\cdot \\partial\\DDD $, the boundary of $ \\DDD $, so has measure zero.\n\\end{enumerate}\nThat is, $ \\DDD_\\Gamma $ is a fundamental domain for $ \\Gamma $.\n\\end{theorem}\n\n\\begin{proof}\n\\hfill\n\\begin{enumerate}\n\\item Fix $ z \\in \\HH $. There exists $ \\gamma \\in \\SL_2\\br{\\ZZ} $ such that $ \\gamma z \\in \\DDD $. Can write $ \\gamma $ as $ \\pm\\gamma_i\\gamma' $ for some $ i $ and $ \\gamma' \\in \\Gamma $. Then $ \\pm\\gamma_i\\gamma'z \\in \\DDD $, so $ \\gamma_i\\gamma'z \\in \\DDD $, so $ \\gamma'z \\in \\gamma_i^{-1}\\DDD \\subseteq \\DDD_\\Gamma $.\n\\item Let $ z \\in \\bigcup_i \\gamma_i^{-1} \\cdot \\mathring{\\DDD} $. Want $ \\Gamma \\cdot z \\cap \\DDD_\\Gamma = \\cbr{z} $. Suppose $ \\gamma z \\in \\DDD_\\Gamma $ for $ \\gamma \\in \\Gamma $. There exist $ i $ and $ j $ such that $ z \\in \\gamma_i^{-1} \\cdot \\mathring{\\DDD} $ and $ \\gamma z \\in \\gamma_j^{-1} \\cdot \\mathring{\\DDD} $, so $ \\gamma_iz, \\gamma_j\\gamma z \\in \\mathring{\\DDD} $. So $ \\gamma_iz = \\gamma_j\\gamma z $ so $ \\gamma^{-1}\\gamma_j^{-1}\\gamma_iz = z $. Then $ \\Stab_z = \\pm\\id_2 $, so $ \\gamma_i = \\pm\\gamma_j\\gamma $. Since $ \\SL_2\\br{\\ZZ} = \\bigsqcup_i \\pm\\gamma_i \\cdot \\Gamma $, this is only possible if $ i = j $. Then $ \\gamma_i = \\pm\\gamma_i\\gamma $, so $ \\gamma = \\pm\\id_2 $. So $ z = \\gamma z $.\n\\end{enumerate}\n\\end{proof}\n\n\\begin{example*}\n$ \\Gamma = \\Gamma_0\\br{2} $ has index three in $ \\SL_2\\br{\\ZZ} $. The coset representatives are\n$$ \\id_2 = \\twobytwo{1}{0}{0}{1} : z \\mapsto z, \\qquad \\S = \\twobytwo{0}{-1}{1}{0} : z \\mapsto -\\dfrac{1}{z}, \\qquad \\S\\T = \\twobytwo{0}{-1}{1}{1} : z \\mapsto -\\dfrac{1}{z + 1}, $$\nso\n$$\n\\begin{tikzpicture}[scale=2]\n\\draw [dotted, thick] (-3, 0) to (3, 0);\n\\draw [dotted, thick] (0, 0) to (0, 2);\n\\draw [dashed] (-2, 0) arc (180:0:1);\n\\draw [dashed] (-1, 0) arc (180:0:1);\n\\draw [dashed] (0, 0) arc (180:0:1);\n\\draw [dashed] (-0.7, 0) arc (180:0:0.35);\n\\draw [dashed] (-0.35, 0) arc (180:0:0.35);\n\\draw [dashed] (0, 0) arc (180:0:0.35);\n\\draw [dashed] (-0.5, 0) to (-0.5, 2);\n\\draw [dashed] (0.5, 0) to (0.5, 2);\n\\draw (0, 0) arc (0:120:0.35);\n\\draw (0, 0) arc (180:120:1);\n\\draw (-0.5, 0.3) to (-0.5, 2);\n\\draw (0.5, 0.866) to (0.5, 2);\n\\end{tikzpicture}.\n$$\n\\end{example*}\n\nA question is for a given $ \\Gamma $ and $ \\DDD_\\Gamma $, what are the ways to escape to $ \\infty $ in $ \\DDD_\\Gamma $? Let $ \\Gamma \\subseteq \\SL_2\\br{\\ZZ} $ be a congruence subgroup. Then\n$$ \\SL_2\\br{\\ZZ} \\cdot \\infty = \\cbr{\\twobytwo{a}{b}{c}{d} \\cdot \\infty} = \\cbr{\\dfrac{a}{c} \\st \\twobytwo{a}{b}{c}{d} \\in \\SL_2\\br{\\ZZ}} = \\QQ \\cup \\cbr{\\infty}. $$\n\n\\begin{definition}\nThe set of \\textbf{cusps} for $ \\Gamma $ is the set of $ \\Gamma $-orbits on $ \\QQ \\cup \\cbr{\\infty} $.\n\\end{definition}\n\n\\begin{note*}\nIf $ \\SL_2\\br{\\ZZ} = \\bigsqcup_i \\pm\\gamma_i \\cdot \\Gamma $, then $ \\cbr{\\gamma_i^{-1} \\cdot \\infty} $ is a set of representatives for the $ \\Gamma $-orbits on $ \\QQ \\cup \\cbr{\\infty} $.\n\\end{note*}\n\n\\begin{example*}\nLet $ \\Gamma = \\Gamma_0\\br{p} $ for $ p $ prime. Then\n$$ \\Gamma \\cdot \\infty = \\cbr{\\dfrac{a}{pc} \\st \\br{a, pc} = 1} \\cup \\cbr{\\infty}, \\qquad \\Gamma \\cdot 0 = \\cbr{\\dfrac{b}{d} \\st d \\nmid p}. $$\n\\end{example*}\n\n\\begin{definition}\nA weakly modular form $ f $ of weight $ k $ and level $ \\Gamma $ is \\textbf{holomorphic or meromorphic at all cusps} if for all $ \\gamma \\in \\Gamma $, $ \\eval{f}_{k, \\gamma} $ is holomorphic or meromorphic at $ \\infty $.\n\\end{definition}\n\n\\begin{note*}\nSince $ \\eval{f}_{k, \\gamma} = f $ for $ \\gamma \\in \\Gamma $, it suffices to check on a set of coset representatives for $ \\Gamma $ in $ \\SL_2\\br{\\ZZ} $.\n\\end{note*}\n\n\\begin{definition}\nA \\textbf{modular form of weight $ k $ and level $ \\Gamma $} is a weakly modular form of weight $ k $ and level $ \\Gamma $ that is holomorphic on $ \\HH $ and at all cusps.\n\\end{definition}\n\n\\pagebreak\n\n\\subsection{Spaces of modular forms}\n\n\\subsubsection{The space of holomorphic modular forms}\n\n\\lecture{24}{Monday}{25/11/19}\n\nLet\n$$ \\M_k\\br{\\Gamma} = \\cbr{\\text{holomorphic modular forms of weight} \\ k \\ \\text{and level} \\ \\Gamma}, $$\n$$ \\S_k\\br{\\Gamma} = \\cbr{f \\in \\M_k\\br{\\Gamma} \\st f \\ \\text{vanishes at all cusps}}. $$\n\n\\begin{note*}\nFor any $ \\gamma \\in \\GL_2\\br{\\QQ}_+ $, if $ f \\in \\M_k\\br{\\Gamma} $, then $ \\eval{f}_{k, \\gamma} \\in \\M_k\\br{\\gamma^{-1}\\Gamma\\gamma} $. If we consider the $ \\CC $-vector space $ \\widetilde{\\M_k} = \\bigcup_\\Gamma \\M_k\\br{\\Gamma} $, then $ \\gamma $ acts on $ \\widetilde{\\M_k} $ by $ \\gamma \\cdot f = \\eval{f}_{k, \\gamma} $. In fact, $ \\GL_2\\br{\\QQ}_+ \\subseteq \\GL_2\\br{\\AA_\\QQ^{\\fin}} $ and the action extends to this larger group. If we enlarge $ \\widetilde{\\M_k} $ in a suitable way, the correct group that acts is $ \\GL_2\\br{\\AA_\\QQ} $.\n\\end{note*}\n\nA question is what can we say about $ \\dim_\\CC \\M_k\\br{\\Gamma} $? Assume $ \\Gamma \\subseteq \\SL_2\\br{\\ZZ} $, and fix $ f \\in \\M_k\\br{\\Gamma} $. Write\n$$ \\SL_2\\br{\\ZZ} = \\bigsqcup_{j = 1}^d \\Gamma \\cdot \\alpha_j, \\qquad g = \\prod_{j = 1}^d \\eval{f}_{k, \\alpha_j}, \\qquad d = \\sbr{\\SL_2\\br{\\ZZ} : \\Gamma}. $$\n\n\\begin{proposition}\n\\hfill\n\\begin{enumerate}\n\\item $ g $ is independent of the choice of $ \\alpha_i $.\n\\item $ g \\in \\M_{kd} $.\n\\end{enumerate}\n\\end{proposition}\n\n\\begin{proof}\n\\hfill\n\\begin{enumerate}\n\\item Suppose I replace $ \\alpha_j' $ such that $ \\Gamma \\cdot \\alpha_j = \\Gamma \\cdot \\alpha_j' $. Then there exists $ \\gamma \\in \\Gamma $ such that $ \\gamma\\alpha_j = \\alpha_j' $, so $ \\eval{f}_{k, \\alpha_j'} = \\eval{\\br{\\eval{f}_{k, \\gamma}}}_{k, \\alpha_j} = \\eval{f}_{k, \\alpha_j} $. So the product defining $ g $ does not change.\n\\item For $ \\alpha \\in \\SL_2\\br{\\ZZ} $, $ \\eval{g}_{kd, \\alpha} = \\prod_{j = 1}^d \\eval{\\br{\\eval{f}_{k, \\alpha_j}}}_{k, \\alpha} = \\prod_{j = 1}^d \\eval{f}_{k, \\alpha_j\\alpha} $. Since $ \\SL_2\\br{\\ZZ} = \\bigsqcup_{j = 1}^d \\Gamma \\cdot \\alpha_j $, $ \\SL_2\\br{\\ZZ} = \\SL_2\\br{\\ZZ} \\cdot \\alpha = \\bigsqcup_{j = 1}^d \\Gamma \\cdot \\alpha_j\\alpha $. So the elements $ \\alpha_i\\alpha $ are another set of coset representatives for $ \\Gamma $ in $ \\SL_2\\br{\\ZZ} $. Since $ g $ was independent of the choice of representatives, $ \\eval{g}_{kd, \\alpha} = g $.\n\\end{enumerate}\n\\end{proof}\n\nHave\n$$ \\sum_{p \\in \\SL_2\\br{\\ZZ} \\backslash \\br{\\HH \\cup \\QQ \\cup \\cbr{\\infty}}} \\dfrac{1}{e_p}\\ord_p g = \\dfrac{kd}{12}, \\qquad e_p =\n\\begin{cases}\n\\dfrac{1}{2}\\#\\Stab_p \\in \\cbr{1, 2, 3} & p \\in \\HH \\\\\n1 & p \\in \\QQ \\cup \\cbr{\\infty}\n\\end{cases},\n$$\nso\n$$ \\dfrac{kd}{12} = \\sum_{p \\in \\SL_2\\br{\\ZZ} \\backslash \\br{\\HH \\cup \\QQ \\cup \\cbr{\\infty}}} \\dfrac{1}{e_p}\\sum_{j = 1}^d \\ord_p \\eval{f}_{k, \\alpha_j} = \\sum_{p \\in \\SL_2\\br{\\ZZ} \\backslash \\br{\\HH \\cup \\QQ \\cup \\cbr{\\infty}}} \\dfrac{1}{e_p}\\sum_{j = 1}^d \\ord_{\\alpha_jp} f. $$\nAs $ p $ runs over a set of representatives for $ \\SL_2\\br{\\ZZ} $-orbits, and $ \\alpha_j $ runs over the coset representatives for $ \\Gamma $ in $ \\SL_2\\br{\\ZZ} $, $ q = \\alpha_jp $ runs over the representatives for $ \\Gamma $-orbits, so\n$$ \\sum_{q \\in \\Gamma \\backslash \\br{\\HH \\cup \\QQ \\cup \\cbr{\\infty}}} \\dfrac{n_q}{e_q}\\ord_q f = \\dfrac{kd}{12}, \\qquad n_q = \\#\\cbr{j \\st \\alpha_jq \\in \\Gamma \\cdot q} \\ge 1. $$\n\n\\begin{corollary}\nIf $ \\ord_\\infty f \\ge kd / 12n_\\infty + 1 $ for $ f \\in \\M_k\\br{\\Gamma} $, then $ f = 0 $.\n\\end{corollary}\n\nThen\n\\begin{align*}\nn_\\infty\n& = \\#\\cbr{j \\st \\alpha_j\\infty \\in \\Gamma \\cdot \\infty}\n= \\#\\cbr{j \\st \\exists \\gamma \\in \\Gamma, \\ \\alpha_j\\infty\n= \\gamma\\infty} = \\#\\cbr{j \\st \\exists \\gamma \\in \\Gamma, \\ \\alpha_j^{-1}\\gamma \\in \\Stab_\\infty} \\\\\n& = \\#\\cbr{j \\st \\alpha_j^{-1} \\cdot \\Gamma \\subseteq \\Stab_\\infty \\cdot \\Gamma}\n= \\#\\br{\\Stab_\\infty \\cdot \\Gamma / \\Gamma}\n= \\#\\br{\\Stab_\\infty / \\br{\\Stab_\\infty \\cap \\Gamma}}\n= \\n_\\Gamma,\n\\end{align*}\nsince $ \\Stab_\\infty = \\cbr{\\twobytwosmall{1}{b}{0}{1} \\st b \\in \\ZZ} $. Since $ f $ is a power series in $ q^{1 / \\n_\\Gamma} $, and $ f $ is determined by its terms of order at most $ kd / 12\\n_\\Gamma $, $ f $ is determined by the first $ 1 + kd / 12 $ terms of its $ q $-expansion, so\n$$ \\dim_\\CC \\M_k\\br{\\Gamma} \\le 1 + \\dfrac{kd}{12}. $$\n\n\\pagebreak\n\n\\subsubsection{The space of meromorphic modular forms}\n\n\\lecture{25}{Friday}{29/11/19}\n\nLet $ \\Gamma \\subseteq \\SL_2\\br{\\ZZ} $ be a congruence subgroup. Let $ \\F\\br{\\Gamma} $ be the field of meromorphic modular forms of weight zero and level $ \\Gamma $, and let $ \\F_N = \\F\\br{\\Gamma\\br{N}} $, so $ \\F_1 = \\F\\br{\\SL_2\\br{\\ZZ}} = \\CC\\br{\\j} $. If $ M \\mid N $, then $ \\Gamma\\br{N} \\subseteq \\Gamma\\br{M} $, so $ \\F_M \\subseteq \\F_N $. Then $ \\SL_2\\br{\\ZZ} $ normalises $ \\Gamma\\br{N} $ so if $ f \\in \\F_N $, then $ \\eval{f}_{0, \\alpha} $ is modular for $ \\alpha^{-1}\\Gamma\\br{N}\\alpha = \\Gamma\\br{N} $ if $ \\alpha \\in \\SL_2\\br{\\ZZ} $.\n\n\\begin{note*}\n$ \\eval{\\br{fg}}_{0, \\alpha} = \\eval{f}_{0, \\alpha} \\cdot \\eval{g}_{0, \\alpha} $ and $ \\eval{\\br{f + g}}_{0, \\alpha} = \\eval{f}_{0, \\alpha} + \\eval{g}_{0, \\alpha} $.\n\\end{note*}\n\nThen $ \\alpha \\in \\SL_2\\br{\\ZZ} $ gives an automorphism of $ \\F_N $ fixing $ \\F_1 $. Get an action of $ \\SL_2\\br{\\ZZ} / \\Gamma\\br{N} $ on $ \\F_N $ by field automorphisms and $ \\F_1 $ is the fixed field.\n\n\\begin{theorem}[Galois theory]\nLet $ F $ be a field and $ G $ a finite group acting faithfully on $ F $ by automorphisms, that is no $ g \\in G $ acts on $ F $ as $ \\id $ except $ g = \\id_G $. Then $ F $ is a Galois extension of\n$$ F^G = \\cbr{x \\in F \\st \\forall g \\in G, \\ gx = x}, $$\nwith Galois group $ G $. In particular $ \\sbr{F : F^G} = \\#G $.\n\\end{theorem}\n\n\\begin{proposition}\n$ \\SL_2\\br{\\ZZ} / \\Gamma\\br{N} \\cong \\SL_2\\br{\\ZZ / N\\ZZ} $ acts faithfully on $ \\F_N $.\n\\end{proposition}\n\n\\begin{proof}\nUse dimension formulae for $ \\M_k\\br{\\Gamma} $ to show that for $ k \\gg 0 $ even, $ \\dim \\M_k\\br{\\Gamma\\br{N}} > \\dim \\M_k\\br{\\Gamma} $ for $ \\Gamma \\supsetneq \\Gamma\\br{N} $, so there exists $ f \\in \\M_k\\br{\\Gamma\\br{N}} $ such that the only elements of $ \\SL_2\\br{\\ZZ} $ fixing $ f $ lie in $ \\Gamma\\br{N} $. Then $ f / \\E_k $ lies in $ \\F_N $ but not in $ \\F\\br{\\Gamma} $ for $ \\Gamma \\supsetneq \\Gamma\\br{N} $. So $ f / \\E_k $ is not fixed by non-trivial elements of $ \\SL_2\\br{\\ZZ} / \\Gamma\\br{N} $.\n\\end{proof}\n\n\\begin{corollary}\n$ \\F_N / \\F_1 $ is Galois with Galois group $ \\SL_2\\br{\\ZZ / N\\ZZ} $.\n\\end{corollary}\n\nThen $ \\F_N $ is a finite and algebraic extension of $ \\CC\\br{\\j} $, of transcendence degree one over $ \\CC $. For $ \\Gamma $ arbitrary in $ \\SL_2\\br{\\ZZ} $, $ \\Gamma \\supseteq \\Gamma\\br{N} $ for some $ N $, so $ \\F\\br{\\Gamma} $ is the fixed field of $ \\Gamma / \\Gamma\\br{N} $ in $ \\F_N $. Then $ \\F\\br{\\Gamma} / \\F_1 $ is not Galois in general, but is algebraic of degree $ \\sbr{\\SL_2\\br{\\ZZ} : \\Gamma} $.\n\n\\begin{proposition}\nThere exists a unique smooth and projective algebraic curve $ X\\br{\\Gamma} $ over $ \\CC $, whose field of rational functions is $ \\F\\br{\\Gamma} $.\n\\end{proposition}\n\n\\begin{proof}\nFix $ \\Gamma $, and let $ f $ be a primitive element of $ \\F\\br{\\Gamma} $, that is $ f $ generates $ \\F\\br{\\Gamma} $ over $ \\F_1 $. Consider the polynomial\n$$ P\\br{X} = \\prod_{\\SL_2\\br{\\ZZ} = \\bigsqcup_j \\Gamma \\cdot \\alpha_j} \\br{X - \\eval{f}_{0, \\alpha_j}} = X^d + \\dfrac{G_1\\br{\\j}}{H_1\\br{\\j}}X^{d - 1} + \\dots + \\dfrac{G_d\\br{\\j}}{H_d\\br{\\j}} \\in \\F_1\\sbr{X}, \\qquad G_i, H_i \\in \\CC\\sbr{Y}. $$\nLet\n$$ Q\\br{X, Y} = H_1\\br{Y} \\dots H_d\\br{Y}\\br{X^d + \\dfrac{G_1\\br{Y}}{H_1\\br{Y}}X^{d - 1} + \\dots + \\dfrac{G_d\\br{Y}}{H_d\\br{Y}}} \\in \\CC\\sbr{X, Y}. $$\nThen $ Q\\br{X, \\j} = H_1\\br{\\j} \\dots H_d\\br{\\j} \\cdot P\\br{X} $. Since $ P\\br{f} = 0 $, $ Q\\br{f, \\j} = 0 $. Consider the map\n$$ \\function[\\phi]{\\HH}{\\CC^2}{z}{\\br{f\\br{z}, \\j\\br{z}}}. $$\nThe image is contained in the zero locus of $ Q\\br{X, Y} $, and factors through $ \\Gamma \\backslash \\HH $. The following are some issues.\n\\begin{itemize}\n\\item This map is not necessarily defined everywhere. To fix, replace $ \\CC^2 $ with $ \\CC\\PP^2 $. Then $ \\phi $ extends to $ \\Gamma \\backslash \\br{\\HH \\cup \\QQ \\cup \\cbr{\\infty}} \\to \\CC\\PP^2 $.\n\\item This map is not necessarily injective on $ \\Gamma \\backslash \\br{\\HH \\cup \\QQ \\cup \\cbr{\\infty}} $, but will be generically injective since $ f $ is primitive.\n\\item This image might be singular. There are standard ways to fix, such as normalisation. When these are fixed, the map becomes injective.\n\\end{itemize}\nThe upshot is to get a complex algebraic curve $ X\\br{\\Gamma} $ whose function field is $ \\F\\br{\\Gamma} $, whose complex points are in bijection with $ \\Gamma \\backslash \\br{\\HH \\cup \\QQ \\cup \\cbr{\\infty}} $.\n\\end{proof}\n\n$ \\M_k\\br{\\Gamma} $ is the space of sections of certain line bundles on $ X\\br{\\Gamma} $.\n\n\\pagebreak\n\n\\subsection{Hecke operators}\n\n\\lecture{26}{Friday}{29/11/19}\n\nLet $ f \\in \\M_k\\br{\\Gamma} $.\n\\begin{enumerate}\n\\item If $ \\Gamma' \\subseteq \\Gamma $, then $ f \\in \\M_k\\br{\\Gamma'} $.\n\\item If $ \\alpha \\in \\GL_2\\br{\\QQ}_+ $, then $ \\eval{f}_{k, \\alpha} \\in \\M_k\\br{\\alpha^{-1}\\Gamma\\alpha} $.\n\\item If $ \\Gamma \\subseteq \\Gamma' $, can write $ \\Gamma' = \\bigsqcup_{i = 1}^d \\Gamma \\cdot \\alpha_i $, then $ \\sum_{i = 1}^d \\eval{f}_{k, \\alpha_i} $ is independent of choices and lives in $ \\M_k\\br{\\Gamma'} $.\n\\end{enumerate}\nThe rough idea is given $ f \\in \\M_k\\br{\\Gamma} $ and $ \\Gamma' \\supseteq \\alpha^{-1}\\Gamma\\alpha $, act on it by $ \\alpha $ to get a modular form of level $ \\alpha^{-1}\\Gamma\\alpha $, using $ 2 $, and average to get a modular form of level $ \\Gamma' $, using $ 3 $. Recall that if $ H, K \\le G $ and $ g \\in G $, then the \\textbf{double coset} is\n$$ HgK = \\cbr{hgk \\st h \\in H, \\ k \\in K}. $$\nThat is, the orbit of $ G $ under the action of $ HxK $ on $ G $ such that $ \\br{h, k} \\cdot g = hgk^{-1} $.\n\n\\begin{definition}\nLet $ f \\in \\M_k\\br{\\Gamma} $, let $ \\alpha \\in \\GL_2\\br{\\QQ}_+ $, and let $ \\Gamma' $ be a congruence subgroup. Then\n$$ \\eval{f}_{k, \\Gamma\\alpha\\Gamma'} = \\sum_{i = 1}^d \\eval{f}_{k, \\alpha_i}, \\qquad \\Gamma\\alpha\\Gamma' = \\bigsqcup_{i = 1}^d \\Gamma\\alpha_i. $$\n\\end{definition}\n\nThe idea is that the $ \\alpha_i $ are of the form $ \\alpha\\beta_i $ where $ \\beta_i $ are a set of coset representatives for $ \\alpha^{-1}\\Gamma\\alpha \\cap \\Gamma' $ in $ \\Gamma' $, by the coursework, so\n$$ \\sum_{i = 1}^d \\eval{f}_{k, \\alpha_i} = \\sum_{i = 1}^d \\eval{\\br{\\eval{f}_{k, \\alpha}}}_{k, \\beta_i}, $$\nwhere\n\\begin{itemize}\n\\item acting by $ \\alpha $ gets $ \\eval{f}_{k, \\alpha} $ modular of level $ \\alpha^{-1}\\Gamma\\alpha $,\n\\item so also modular of level $ \\alpha^{-1}\\Gamma\\alpha \\cap \\Gamma $, and\n\\item averaging gets $ \\eval{f}_{k, \\Gamma\\alpha\\Gamma'} $ modular of level $ \\Gamma' $.\n\\end{itemize}\nSo the double coset $ \\Gamma\\alpha\\Gamma' $ gives a map between $ \\M_k\\br{\\Gamma} $ and $ \\M_k\\br{\\Gamma'} $.\n\n\\subsubsection{Hecke operators}\n\nRecall that\n$$ \\Gamma_1\\br{N} = \\cbr{\\twobytwo{a}{b}{c}{d} \\in \\SL_2\\br{\\ZZ} \\st a \\equiv d \\equiv 1 \\mod N, \\ c \\equiv 0 \\mod N}. $$\n\n\\begin{definition}\nFor a prime $ p \\nmid N $, define\n$$ \\function[\\T_p]{\\M_k\\br{\\Gamma_1\\br{N}}}{\\M_k\\br{\\Gamma_1\\br{N}}}{f}{\\eval{f}_{k, \\Gamma_1\\br{N}\\twobytwosmall{1}{0}{0}{p}\\Gamma_1\\br{N}}}. $$\n\\end{definition}\n\nRecall that for $ \\SL_2\\br{\\ZZ} $ we set\n$$ \\T_pf = p^{k - 1}\\sum_{\\twobytwosmall{a}{b}{0}{d} \\in \\S^p} d^{-k}f\\br{\\dfrac{az + b}{d}} = \\sum_{\\twobytwosmall{a}{b}{0}{d} \\in \\S^p} \\eval{f}_{k, \\twobytwosmall{a}{b}{0}{d}}. $$\nTo show this agrees with our new definition, we need that\n$$ \\SL_2\\br{\\ZZ}\\twobytwo{1}{0}{0}{p}\\SL_2\\br{\\ZZ} = \\bigsqcup_{\\twobytwosmall{a}{b}{0}{d} \\in \\S^p} \\SL_2\\br{\\ZZ}\\twobytwo{a}{b}{0}{d}. $$\n\n\\begin{itemize}\n\\item For the reverse containment, it suffices to show $ \\twobytwosmall{a}{b}{0}{d} \\in \\S^p $ lies in $ \\SL_2\\br{\\ZZ}\\twobytwosmall{1}{0}{0}{p}\\SL_2\\br{\\ZZ} $, and\n$$ \\twobytwo{p}{0}{0}{1} = \\twobytwo{0}{1}{-1}{0}\\twobytwo{1}{0}{0}{p}\\twobytwo{0}{-1}{1}{0}, \\qquad \\twobytwo{1}{b}{0}{p} = \\twobytwo{1}{0}{0}{1}\\twobytwo{1}{0}{0}{p}\\twobytwo{1}{b}{0}{1}, $$\nwhere $ \\twobytwosmall{0}{1}{-1}{0}, \\twobytwosmall{0}{-1}{1}{0}, \\twobytwosmall{1}{0}{0}{1}, \\twobytwosmall{1}{b}{0}{1} \\in \\SL_2\\br{\\ZZ} $.\n\n\\pagebreak\n\n\\item For disjointness, if $ \\SL_2\\br{\\ZZ}\\twobytwosmall{a}{b}{0}{d} = \\SL_2\\br{\\ZZ}\\twobytwosmall{a'}{b'}{0}{d'} $ for $ \\twobytwosmall{a}{b}{0}{d}, \\twobytwosmall{a'}{b'}{0}{d'} \\in \\S^p $, then $ \\twobytwosmall{a}{b}{0}{d}\\twobytwosmall{a'}{b'}{0}{d'}^{-1} \\in \\SL_2\\br{\\ZZ} $, so $ a = a' $ and $ d = d' $. If $ a = p $, then $ d = 1 $ and $ b = 0 $, and the same holds for $ b' $, so equal. If $ a = 1 $, have\n$$ \\twobytwo{1}{\\tfrac{b - b'}{p}}{0}{1} = \\twobytwo{1}{b}{0}{p}\\twobytwo{1}{b'}{0}{p}^{-1} \\in \\SL_2\\br{\\ZZ}, $$\nso $ p \\mid b - b' $. Since $ 0 \\le b, b' < p $, $ b = b' $.\n\\item It remains to show that $ \\SL_2\\br{\\ZZ}\\twobytwosmall{1}{0}{0}{p}\\SL_2\\br{\\ZZ} $ is the union of $ p + 1 $ left cosets. By the coursework,\n\\begin{align*}\n\\#\\cbr{\\text{cosets}}\n& = \\#\\SL_2\\br{\\ZZ} / \\br{\\twobytwo{1}{0}{0}{p}^{-1}\\SL_2\\br{\\ZZ}\\twobytwo{1}{0}{0}{p} \\cap \\SL_2\\br{\\ZZ}}\n= \\#\\SL_2\\br{\\ZZ} / \\Gamma_0\\br{p} \\\\\n& = \\sbr{\\SL_2\\br{\\ZZ} : \\Gamma_0\\br{p}}\n= \\sbr{\\SL_2\\br{\\ZZ / p\\ZZ} : \\text{upper triangular matrices modulo} \\ p}.\n\\end{align*}\nFor upper triangular matrices $ \\twobytwosmall{a}{b}{0}{a^{-1}} $ of determinant one modulo $ p $, there are $ p\\br{p - 1} $ possibilities. For $ \\SL_2\\br{\\ZZ / p\\ZZ} $, there are $ p^2 - 1 $ possibilities for the first row, the second row cannot be a multiple of the first row, so there are $ p^2 - p $ possibilities, and to get determinant one need to rescale the second row, so there are $ p $ possibilities left over, so $ \\#\\SL_2\\br{\\ZZ / p\\ZZ} = p\\br{p^2 - 1} $. Thus the index is $ p\\br{p^2 - 1} / p\\br{p - 1} = p + 1 $.\n\\end{itemize}\nExtending from $ \\T_p $ to $ \\T_n $ for $ \\br{n, N} = 1 $, we set\n$$ \\function[\\T_n]{\\M_k\\br{\\Gamma_1\\br{N}}}{\\M_k\\br{\\Gamma_1\\br{N}}}{f}{\\sum_{ad = n, \\ a \\mid d} \\eval{f}_{k, \\Gamma_1\\br{N}\\twobytwosmall{a}{0}{0}{d}\\Gamma_1\\br{N}}}. $$\n\n\\subsubsection{Diamond operators}\n\n\\lecture{27}{Monday}{02/12/19}\n\nRecall that\n$$ \\Gamma_1\\br{N} \\subseteq \\Gamma_0\\br{N} = \\cbr{\\twobytwo{a}{b}{c}{d} \\in \\SL_2\\br{\\ZZ} \\st c \\equiv 0 \\mod N}. $$\nHave a surjection\n$$ \\function{\\Gamma_0\\br{N}}{\\br{\\ZZ / N\\ZZ}^\\times}{\\twobytwo{a}{b}{c}{d}}{d}, $$\nwhere the kernel is $ \\Gamma_1\\br{N} $. So $ \\Gamma_0\\br{N} / \\Gamma_1\\br{N} \\cong \\br{\\ZZ / N\\ZZ}^\\times $.\n\n\\begin{note*}\nIf $ f \\in \\M_k\\br{\\Gamma_1\\br{N}} $ and $ \\alpha \\in \\Gamma_0\\br{N} $, then $ \\eval{f}_{k, \\alpha} $ is modular of level $ \\alpha^{-1}\\Gamma_1\\br{N}\\alpha = \\Gamma_1\\br{N} $. Moreover $ \\eval{f}_{k, \\alpha} $ depends only on the class of $ \\alpha \\in \\Gamma_0\\br{N} / \\Gamma_1\\br{N} $, that is only on the lower right entry of $ \\alpha $.\n\\end{note*}\n\n\\begin{definition}\nFor $ d \\in \\ZZ $ such that $ \\br{d, N} = 1 $, we define the \\textbf{diamond operator}\n$$ \\function[\\abr{d}]{\\M_k\\br{\\Gamma_1\\br{N}}}{\\M_k\\br{\\Gamma_1\\br{N}}}{f}{\\eval{f}_{k, \\alpha}}, $$\nwhere $ \\alpha \\in \\Gamma_0\\br{N} $ with lower right entry congruent to $ d $ modulo $ N $.\n\\end{definition}\n\nThis defines an action of $ \\br{\\ZZ / N\\ZZ}^\\times \\cong \\Gamma_0\\br{N} / \\Gamma_1\\br{N} $ on $ \\M_k\\br{\\Gamma_1\\br{N}} $. Since $ \\abr{d}\\abr{d'} = \\abr{dd'} = \\abr{d'}\\abr{d} $, and operators of finite order on a $ \\CC $-vector space are diagonalisable, $ \\M_k\\br{\\Gamma_1\\br{N}} $ splits as a direct sum of simultaneous eigenspaces for the $ \\abr{d} $. Let $ V $ be one such eigenspace. Then for each $ d \\in \\br{\\ZZ / N\\ZZ}^\\times $, there exists $ \\chi\\br{d} \\in \\CC^\\times $ such that $ \\abr{d}f = \\chi\\br{d}f $ for all $ f \\in V $. Since $ \\abr{d}\\abr{d'} = \\abr{dd'} $, $ \\chi\\br{d}\\chi\\br{d'} = \\chi\\br{dd'} $, so $ \\chi $ is a homomorphism $ \\br{\\ZZ / N\\ZZ}^\\times \\to \\CC^\\times $, that is a \\textbf{character}.\n\n\\begin{definition}\nFor any character $ \\chi : \\br{\\ZZ / N\\ZZ}^\\times \\to \\CC^\\times $, let $ \\M_k\\br{\\Gamma_1\\br{N}, \\chi} $ be the subspace of $ \\M_k\\br{\\Gamma_1\\br{N}} $ consisting of the forms $ f $ such that\n$$ \\abr{d}f = \\chi\\br{d}f, \\qquad d \\in \\br{\\ZZ / N\\ZZ}^\\times. $$\n\\end{definition}\n\nA warning is that this might be zero.\n\n\\begin{example*}\nIf $ k $ is odd and $ \\chi\\br{-1} = 1 $, this space is zero.\n\\end{example*}\n\n\\pagebreak\n\nWe have a direct sum decomposition\n$$ \\M_k\\br{\\Gamma_1\\br{N}} \\cong \\bigoplus_{\\chi : \\br{\\ZZ / N\\ZZ}^\\times \\to \\CC} \\M_k\\br{\\Gamma_1\\br{N}, \\chi}. $$\n\n\\begin{proposition}\nLet $ \\br{n, N} = 1 $ and $ f \\in \\M_k\\br{\\Gamma_1\\br{N}, \\chi} $ such that $ f = \\sum_{m = 1}^\\infty c_mq^m $. Then\n$$ \\T_nf = \\sum_{m = 1}^\\infty \\gamma_mf, \\qquad \\gamma_m = \\sum_{d \\mid \\br{n, m}} \\chi\\br{d}d^{k - 1}c_{\\tfrac{nm}{d^2}}. $$\nIn particular, if $ \\T_nf = \\lambda_nf $ for some $ n $ with $ \\br{n, N} = 1 $, then $ c_n = \\lambda_nc_1 $.\n\\end{proposition}\n\n\\subsubsection{The Petersson inner product}\n\nFix $ \\Gamma \\subseteq \\SL_2\\br{\\ZZ} $ a congruence subgroup.\n\n\\begin{definition}\nFor $ f, g \\in \\S_k\\br{\\Gamma} $ define the \\textbf{Petersson inner product of weight $ k $ and level $ \\Gamma $}\n$$ \\abr{f, g}_{k, \\Gamma} = \\dfrac{1}{\\sbr{\\SL_2\\br{\\ZZ} : \\Gamma}}\\iintd{\\DDD_\\Gamma}{f\\br{z}\\overline{g\\br{z}}\\dfrac{y^k}{y^2}}{x}{y}, $$\nwhere $ \\DDD_\\Gamma $ is a fundamental domain for $ \\Gamma $.\n\\end{definition}\n\n\\begin{note*}\nThe scaling factor ensures if $ \\Gamma' \\subseteq \\Gamma $ and $ f, g \\in \\S_k\\br{\\Gamma} $, then $ \\abr{f, g}_{k, \\Gamma'} = \\abr{f, g}_{k, \\Gamma} $.\n\\end{note*}\n\n\\begin{proposition}\nLet $ f \\in \\S_k\\br{\\Gamma} $ and $ g \\in \\S_k\\br{\\alpha^{-1}\\Gamma\\alpha} $ for $ \\alpha \\in \\GL_2\\br{\\QQ}_+ $. Then\n$$ \\abr{\\eval{f}_{k, \\alpha}, g}_{k, \\alpha^{-1}\\Gamma\\alpha} = \\abr{f, \\eval{g}_{k, \\alpha'}}_{k, \\Gamma}, \\qquad \\alpha' = \\alpha^{-1}\\det \\alpha. $$\n\\end{proposition}\n\n\\begin{proof}\nLet $ \\alpha = \\twobytwosmall{a}{b}{c}{d} $ and $ \\alpha^{-1} = \\twobytwosmall{a'}{b'}{c'}{d'} $. Set $ z' = \\alpha z $ and $ C = \\sbr{\\SL_2\\br{\\ZZ} : \\alpha^{-1}\\Gamma\\alpha} $. Have $ \\br{cz + d}\\br{c'z' + d'} = 1 $. Then\n\\begin{align*}\n\\abr{\\eval{f}_{k, \\alpha}, g}_{k, \\alpha^{-1}\\Gamma\\alpha}\n& = \\dfrac{1}{C}\\iintd{\\alpha^{-1}\\DDD_\\Gamma}{\\eval{f}_{k, \\alpha}\\br{z}\\overline{g\\br{z}}\\dfrac{y^k}{y^2}}{x}{y} \\\\\n& = \\dfrac{1}{C}\\iintd{\\DDD_\\Gamma}{\\eval{f}_{k, \\alpha}\\br{\\alpha^{-1}z'}\\overline{g\\br{\\alpha^{-1}z'}}\\dfrac{\\det \\alpha^{-k}y'^k\\abs{cz + d}^{2k}}{y'^2}}{x'}{y'} \\\\\n& = \\dfrac{1}{C}\\iintd{\\DDD_\\Gamma}{\\det \\alpha^{k - 1}f\\br{z'}\\br{cz + d}^{-k}\\overline{g\\br{\\alpha^{-1}z'}}\\det \\alpha^{-k}\\abs{cz + d}^{2k}\\dfrac{y'^k}{y'^2}}{x'}{y'} \\\\\n& = \\dfrac{1}{C}\\iintd{\\DDD_\\Gamma}{\\det \\alpha^{-1}f\\br{z'}\\overline{\\br{cz + d}^k}\\overline{g\\br{\\alpha^{-1}z'}}\\dfrac{y'^k}{y'^2}}{x'}{y'} \\\\\n& = \\dfrac{1}{C}\\iintd{\\DDD_\\Gamma}{\\det \\alpha^{-1}f\\br{z'}\\overline{\\br{c'z' + d'}^{-k}}\\br{\\det \\alpha^{-1}}^{1 - k}\\overline{\\eval{g}_{k, \\alpha^{-1}}\\br{z'}}\\overline{\\br{c'z' + d'}^k}\\dfrac{y'^k}{y'^2}}{x'}{y'} \\\\\n& = \\dfrac{1}{C}\\iintd{\\DDD_\\Gamma}{\\det \\alpha^{k - 2}f\\br{z'}\\overline{\\eval{g}_{k, \\alpha^{-1}}\\br{z'}}\\dfrac{y'^k}{y'^2}}{x'}{y'} \\\\\n& = \\det \\alpha^{k - 2}\\abr{f, \\eval{g}_{k, \\alpha^{-1}}}_{k, \\Gamma}.\n\\end{align*}\nRecall $ \\alpha' = \\alpha^{-1}\\det \\alpha $. Then\n$$ \\eval{g}_{k, \\lambda\\alpha}\\br{z} = \\det \\lambda\\alpha^{k - 1}g\\br{\\lambda\\alpha z}\\br{\\lambda cz + \\lambda d}^{-k} = \\lambda^{2k - 2}\\det \\alpha^{k - 1}g\\br{\\alpha z}\\br{cz + d}^{-k}\\lambda^{-k} = \\lambda^{k - 2}\\eval{g}_{k, \\alpha}\\br{z}, $$\nso $ \\eval{g}_{k, \\alpha'}\\br{z} = \\det \\alpha^{k - 2}\\eval{g}_{k, \\alpha^{-1}}\\br{z} $. Thus $ \\abr{\\eval{f}_{k, \\alpha}, g}_{k, \\alpha^{-1}\\Gamma\\alpha} = \\abr{f, \\eval{g}_{k, \\alpha'}}_{k, \\Gamma} $.\n\\end{proof}\n\n\\lecture{28}{Friday}{06/12/19}\n\nRecall that\n$$ \\function[\\T_p]{\\S_k\\br{\\Gamma_1\\br{N}}}{\\S_k\\br{\\Gamma_1\\br{N}}}{f}{\\eval{f}_{k, \\Gamma_1\\br{N}\\twobytwosmall{1}{0}{0}{p}\\Gamma_1\\br{N}} = \\sum_i \\eval{f}_{k, \\alpha_i}}, \\qquad \\Gamma_1\\br{N}\\twobytwo{1}{0}{0}{p}\\Gamma_1\\br{N} = \\bigsqcup_i \\Gamma_1\\br{N}\\alpha_i. $$\n\n\\pagebreak\n\nSuppose we can find $ \\alpha_i $ such that\n$$ \\Gamma_1\\br{N}\\twobytwo{1}{0}{0}{p}\\Gamma_1\\br{N} = \\bigsqcup_i \\Gamma_1\\br{N}\\alpha_i, \\qquad \\Gamma_1\\br{N}\\twobytwo{1}{0}{0}{p}\\Gamma_1\\br{N} = \\bigsqcup_i \\alpha_i\\Gamma_1\\br{N}. $$\nApplying the operation $ ' $ to the latter gives\n$$ \\Gamma_1\\br{N}\\twobytwo{p}{0}{0}{1}\\Gamma_1\\br{N} = \\bigsqcup_i \\Gamma_1\\br{N}\\alpha_i'. $$\nIf $ f, g \\in \\S_k\\br{\\Gamma_1\\br{N}} $,\n\\begin{align*}\n\\abr{\\T_pf, g}_{k, \\Gamma_1\\br{N}}\n& = \\sum_i \\abr{\\eval{f}_{k, \\alpha_i}, g}_{k, \\Gamma}, \\qquad \\Gamma \\subseteq \\Gamma_1\\br{N} \\cap \\bigcap_i \\alpha_i^{-1}\\Gamma_1\\br{N}\\alpha_i \\cap \\bigcap_i \\alpha_i'^{-1}\\Gamma_1\\br{N}\\alpha_i' \\\\\n& = \\sum_i \\abr{f, \\eval{g}_{k, \\alpha_i'}}_{k, \\Gamma}\n= \\abr{f, \\eval{g}_{k, \\Gamma_1\\br{N}\\twobytwosmall{p}{0}{0}{1}\\Gamma_1\\br{N}}}_{k, \\Gamma}\n= \\abr{f, \\eval{g}_{k, \\Gamma_1\\br{N}\\twobytwosmall{p}{0}{0}{1}\\Gamma_1\\br{N}}}_{k, \\Gamma_1\\br{N}}.\n\\end{align*}\nFor $ \\SL_2\\br{\\ZZ} $,\n$$ \\SL_2\\br{\\ZZ}\\twobytwo{p}{0}{0}{1}\\SL_2\\br{\\ZZ} = \\SL_2\\br{\\ZZ}\\twobytwo{0}{1}{-1}{0}\\twobytwo{p}{0}{0}{1}\\twobytwo{0}{-1}{1}{0}\\SL_2\\br{\\ZZ} = \\SL_2\\br{\\ZZ}\\twobytwo{1}{0}{0}{p}\\SL_2\\br{\\ZZ}, $$\nso\n$$ \\abr{\\T_pf, g}_{k, \\SL_2\\br{\\ZZ}} = \\abr{f, \\T_pg}_{k, \\SL_2\\br{\\ZZ}}, \\qquad f, g \\in \\S_k\\br{\\SL_2\\br{\\ZZ}}, $$\nwhich is Theorem \\ref{thm:innerproduct}. In general,\n$$ \\Gamma_1\\br{N}\\twobytwo{1}{0}{0}{p}\\Gamma_1\\br{N} = \\T_p\\abr{p}. $$\nWill not prove, so see Diamond and Shurman chapter $ 5 $. This argument depends on finding $ \\alpha_i $ such that\n$$ \\Gamma_1\\br{N}\\twobytwo{1}{0}{0}{p}\\Gamma_1\\br{N} = \\bigsqcup_i \\Gamma_1\\br{N}\\alpha_i = \\bigsqcup_i \\alpha_i\\Gamma_1\\br{N}. $$\n\n\\begin{lemma}\nSuch $ \\alpha_i $ exist.\n\\end{lemma}\n\n\\begin{proof}\nThis is Diamond and Shurman $ 5.5.1 $(c). Write\n$$ \\Gamma_1\\br{N}\\twobytwo{1}{0}{0}{p}\\Gamma_1\\br{N} = \\bigsqcup_{i = 1}^r \\Gamma_1\\br{N}\\gamma_i = \\bigsqcup_{j = 1}^r \\widetilde{\\gamma_j}\\Gamma_1\\br{N}. $$\nClaim that for all $ 1 \\le i \\le r $, $ \\Gamma_1\\br{N}\\gamma_i \\cap \\widetilde{\\gamma_i}\\Gamma_1\\br{N} \\ne \\emptyset $. Suppose otherwise. Then $ \\Gamma_1\\br{N}\\gamma_i \\subseteq \\bigsqcup_{j \\ne i} \\widetilde{\\gamma_j}\\Gamma_1\\br{N} $. The right hand side is stable under right multiplication by $ \\Gamma_1\\br{N} $, so\n$$ \\Gamma_1\\br{N}\\twobytwo{1}{0}{0}{p}\\Gamma_1\\br{N} = \\Gamma_1\\br{N}\\gamma_i\\Gamma_1\\br{N} = \\bigcup_{\\beta \\in \\Gamma_1\\br{N}} \\Gamma_1\\br{N}\\gamma_i\\beta \\subseteq \\bigsqcup_{j \\ne i} \\widetilde{\\gamma_j}\\Gamma_1\\br{N}. $$\nThis is impossible since $ \\widetilde{\\gamma_i} $ is in the left hand side but not the right hand side. For all $ i $, choose $ \\alpha_i $ such that $ \\alpha_i \\in \\Gamma_1\\br{N}\\gamma_i \\cap \\widetilde{\\gamma_i}\\Gamma_1\\br{N} $, so $ \\Gamma_1\\br{N}\\alpha_i = \\Gamma_1\\br{N}\\gamma_i $ and $ \\alpha_i\\Gamma_1\\br{N} = \\widetilde{\\gamma_i}\\Gamma_1\\br{N} $. Now,\n$$ \\bigsqcup_{i = 1}^r \\Gamma_1\\br{N}\\alpha_i = \\bigsqcup_{i = 1}^r \\Gamma_1\\br{N}\\gamma_i = \\Gamma_1\\br{N}\\twobytwo{1}{0}{0}{p}\\Gamma_1\\br{N} = \\bigsqcup_{i = 1}^r \\widetilde{\\gamma_i}\\Gamma_1\\br{N} = \\bigsqcup_{i = 1}^r \\alpha_i\\Gamma_1\\br{N}. $$\n\\end{proof}\n\nThe upshot is\n$$ \\abr{\\T_pf, g}_{k, \\Gamma_1\\br{N}} = \\abr{f, \\abr{p}\\T_pg}_{k, \\Gamma_1\\br{N}}, \\qquad p \\nmid N, \\qquad f, g \\in \\S_k\\br{\\Gamma_1\\br{N}}. $$\nCheck, such as by formulas on $ q $-expansions, that $ \\T_p $ and $ \\T_q $ commute for $ p, q \\nmid N $ prime, and $ \\T_p $ and $ \\abr{d} $ commute. Thus $ \\T_p $ commutes with its adjoint for all $ p $, so $ \\T_p $ is diagonalisable on $ \\S_k\\br{\\Gamma_1\\br{N}} $.\n\n\\pagebreak\n\n\\subsection{\\texorpdfstring{$ \\L $}{L}-functions}\n\n\\subsubsection{Hecke \\texorpdfstring{$ \\L $}{L}-functions}\n\n\\begin{definition}\nLet $ f = \\sum_{n = 1}^\\infty a_nq^n \\in \\S_k\\br{\\Gamma_1\\br{N}} $. Then the \\textbf{Hecke $ \\L $-function of weight $ k $ and level $ \\Gamma_1\\br{N} $} is\n$$ \\L\\br{s, f} = \\sum_{n = 1}^\\infty a_nn^{-s}. $$\n\\end{definition}\n\nThis is absolutely convergent for $ \\Re s \\gg 0 $, and has a meromorphic continuation and a functional equation. Set\n$$ \\R\\br{s, f} = N^{\\tfrac{s}{2}}\\dfrac{\\Gamma\\br{s}}{\\br{2\\pi}^s}\\L\\br{s, f}. $$\n\n\\begin{note*}\n$$ \\twobytwo{0}{-1}{N}{0}^2 = \\twobytwo{-N}{0}{0}{-N}, \\qquad \\twobytwo{0}{-1}{N}{0}\\Gamma_1\\br{N}\\twobytwo{0}{-1}{N}{0} = \\Gamma_1\\br{N}. $$\n\\end{note*}\n\nSet\n$$ \\function[\\w_N]{\\S_k\\br{\\Gamma_1\\br{N}}}{\\S_k\\br{\\Gamma_1\\br{N}}}{f}{i^kN^{1 - \\tfrac{k}{2}}\\eval{f}_{k, \\twobytwosmall{0}{-1}{N}{0}}}. $$\nThe constants are chosen so that $ \\w_N^2 = \\id $, the \\textbf{Atkin-Lehner involution}. A warning is that this does not commute with $ \\T_p $ and $ \\abr{p} $. In fact $ \\w_N\\T_p\\w_N = \\abr{p}\\T_p $ and $ \\w_N\\abr{p}\\w_N = \\abr{p}^{-1} $, and\n$$ \\R\\br{s, f} = \\R\\br{k - s, \\w_Nf}. $$\nIf $ f \\in \\S_k\\br{\\Gamma_1\\br{N}, \\chi} $ for $ \\chi : \\br{\\ZZ / N\\ZZ}^\\times \\to \\CC^\\times $ is an eigenform for all $ \\T_p $ for $ p \\nmid N $ and $ c_1 = 1 $, then using\n$$ \\T_pf = \\sum_{n = 1}^\\infty c_{np}q^n + \\chi\\br{p}c_nq^{np}, $$\nif $ \\T_pf = \\lambda_pf = \\sum_{n = 1}^\\infty \\gamma_nq^n $ for $ p \\nmid N $, then\n$$ \\gamma_n =\n\\begin{cases}\nc_{np} + \\chi\\br{p}p^{k - 1}c_{\\tfrac{n}{p}} & p \\mid n \\\\\nc_{np} & p \\nmid n\n\\end{cases}.\n$$\nThe upshot is for $ p \\nmid m $,\n$$ c_{p^{k + 1}m} = \\lambda_pc_{p^km} + \\chi\\br{p}p^{k - 1}c_{p^{k - 1}m}, \\qquad k \\ge 1, $$\nso\n$$ \\L\\br{s, f} = \\prod_{p \\nmid N} \\dfrac{1}{1 - \\lambda_pp^{-s} + \\chi\\br{p}p^{k - 1 - 2s}}\\sum_{m \\ \\text{divisible only by primes} \\ l \\mid N} c_mm^{-s}. $$\n\n\\subsubsection{Oldforms and newforms}\n\n\\lecture{29}{Friday}{06/12/19}\n\nLet $ p \\nmid N $ and $ l \\mid N $, and let\n$$ \\function[\\U_l]{\\S_k\\br{\\Gamma_1\\br{N}}}{\\S_k\\br{\\Gamma_1\\br{N}}}{f}{\\eval{f}_{k, \\Gamma_1\\br{N}\\twobytwosmall{1}{0}{0}{l}\\Gamma_1\\br{N}}}. $$\nOn $ q $-expansions, if $ f = \\sum_{n = 1}^\\infty c_nq^n $, then $ \\U_lf = \\sum_{n = 1}^\\infty c_{nl}q^n $. Then $ \\U_l $ commutes with $ \\T_p $ and $ \\abr{d} $, by checking on $ q $-expansions. A problem is that $ \\U_l $ are generally not self-adjoint or even normal. Let $ f = \\sum_n c_nq^n \\in \\S_k\\br{\\Gamma_1\\br{N}} $ be an eigenform for $ \\T_p $ and $ \\abr{d} $. Atkin-Lehner defined\n$$ \\function[\\alpha_{N, l}]{\\S_k\\br{\\Gamma_1\\br{N}}}{\\S_k\\br{\\Gamma_1\\br{Nl}}}{f}{f}, \\qquad \\function[\\beta_{N, l}]{\\S_k\\br{\\Gamma_1\\br{N}}}{\\S_k\\br{\\Gamma_1\\br{Nl}}}{f}{z \\mapsto f\\br{lz} = \\sum_n c_nq^{nl}}. $$\n\n\\pagebreak\n\nThen $ \\beta $, a multiple of $ \\eval{f}_{k, \\twobytwosmall{l}{0}{0}{1}} $, is modular of weight $ k $ and level $ \\twobytwosmall{l}{0}{0}{1}^{-1}\\Gamma\\br{N}\\twobytwosmall{l}{0}{0}{1} \\supseteq \\Gamma_1\\br{Nl} $. Check that $ \\br{\\T_p\\beta_{N, l}}\\br{f} = \\beta_{N, l}\\br{\\T_pf} $, and similarly for $ \\abr{d} $ for $ d \\in \\br{\\ZZ / Nl\\ZZ}^\\times $. Check that $ \\alpha_{N, l} $ and $ \\beta_{N, l} $ commute with $ \\T_p $, $ \\abr{d} $ for $ d \\in \\br{\\ZZ / Nl\\ZZ}^\\times $, and $ \\U_p $ for $ p \\mid N $ and $ l \\ne p $. Then $ \\U_l\\br{\\beta_{N, l}\\br{f}} = f $ and $ \\U_l\\br{\\alpha_{N, l}\\br{f}} = \\T_pf + p^k\\chi\\br{p}\\beta_{N, l}\\br{f} $, so the image of\n$$ \\function{\\S_k\\br{\\Gamma_1\\br{N}}^2}{\\S_k\\br{\\Gamma_1\\br{Nl}}}{\\br{f, g}}{\\alpha_{N, l}f + \\beta_{N, l}g} $$\nis stable under $ \\T_p $, $ \\abr{d} $, $ \\U_p $, and $ \\U_l $.\n\n\\begin{definition}\nDefine the \\textbf{oldforms}\n$$ \\S_k\\br{\\Gamma_1\\br{N}}^{\\old} = \\sum_{l \\nmid N} \\br{\\alpha_{\\tfrac{N}{l}, l}\\br{\\S_k\\br{\\Gamma_1\\br{\\dfrac{N}{l}}}} + \\beta_{\\tfrac{N}{l}, l}\\br{\\S_k\\br{\\Gamma_1\\br{\\dfrac{N}{l}}}}}, $$\nwhich is stable under $ \\T_p $, $ \\abr{d} $, and $ \\U_l $. Define\n$$ \\S_k\\br{\\Gamma_1\\br{N}}^{\\new} = \\br{\\S_k\\br{\\Gamma_1\\br{N}}^{\\old}}^\\perp, $$\nthe orthogonal complement with respect to $ \\abr{\\cdot, \\cdot}_{k, \\Gamma_1\\br{N}} $, which is stable under $ \\T_p $ and $ \\abr{d} $, and not a priori under $ \\U_p $ for $ p \\mid N $.\n\\end{definition}\n\n\\begin{theorem}[Atkin-Lehner 1979, strong multiplicity one]\nLet $ 0 \\ne f \\in \\S_k\\br{\\Gamma_1\\br{N}}^{\\new} $ and $ g \\in \\S_k\\br{\\Gamma_1\\br{N}} $. Suppose for all $ p \\nmid N $, there exist $ \\lambda_p \\in \\CC $ and $ \\chi : \\br{\\ZZ / N\\ZZ}^\\times \\to \\CC^\\times $ such that\n$$ \\T_pf = \\lambda_pf, \\qquad \\T_pg = \\lambda_pg, \\qquad \\abr{d}f = \\chi\\br{d}f, \\qquad \\abr{d}g = \\chi\\br{d}g. $$\nThen $ g $ is a scalar multiple of $ f $.\n\\end{theorem}\n\n\\begin{corollary}\n$ \\U_p $ for $ p \\mid N $ preserves, and is diagonalisable on, $ \\S_k\\br{\\Gamma_1\\br{N}}^{\\new} $.\n\\end{corollary}\n\n\\begin{corollary}\n$ \\S_k\\br{\\Gamma_1\\br{N}}^{\\new} $ breaks up as a direct sum of one-dimensional simultaneous eigenspaces for $ \\T_p $, $ \\U_l $, and $ \\abr{d} $ for $ \\br{d, N} = 1 $.\n\\end{corollary}\n\nLet $ f = \\sum_n c_nq^n $, so $ \\U_lf = \\sum_n c_{nl}q^n $, and $ \\U_lf = \\lambda_lf $ implies that $ c_{nl} = \\lambda_lc_n $.\n\n\\begin{corollary}\nIf $ f \\in \\S_k\\br{\\Gamma_1\\br{N}, \\chi} $ is an eigenform for $ \\T_p $ and $ \\U_l $, then $ c_1 \\ne 0 $.\n\\end{corollary}\n\n\\begin{definition}\nA \\textbf{newform} is an element of $ \\S_k\\br{\\Gamma_1\\br{N}}^{\\new} $ with $ c_1 = 1 $, that is an eigenform for $ \\T_p $, $ \\U_l $, and $ \\abr{d} $ for $ \\br{d, N} = 1 $.\n\\end{definition}\n\nLet $ f \\in \\S_k\\br{\\Gamma_1\\br{N}, \\chi} $ be a newform such that $ \\T_pf = \\lambda_pf $ and $ \\U_lf = \\lambda_lf $. Then\n$$ \\L\\br{s, f} = \\prod_{p \\nmid N} \\dfrac{1}{1 - \\lambda_pp^{-s} + \\chi\\br{p}p^{k - 1 - 2s}}\\prod_{l \\mid N} \\dfrac{1}{1 - \\lambda_ll^{-s}}. $$\n\n\\subsection{Fermat's last theorem}\n\nLet $ E / \\QQ $ be an elliptic curve of conductor $ N $, and let\n$$ a_p =\n\\begin{cases}\n\\#E\\br{\\FF_p} - p - 1 & p \\nmid N \\\\\n1 & E \\ \\text{has split multiplicative reduction modulo} \\ p \\\\\n-1 & E \\ \\text{has non-split multiplicative reduction modulo} \\ p \\\\\n0 & E \\ \\text{has additive reduction modulo} \\ p\n\\end{cases}.\n$$\nLet\n$$ \\L\\br{s, E} = \\prod_{p \\nmid N} \\dfrac{1}{1 - a_pp^{-s} + p^{1 - 2s}}\\prod_{l \\mid N} \\dfrac{1}{1 - a_ll^{-s}}. $$\n\n\\pagebreak\n\n\\begin{theorem}[Eichler-Shimura]\nLet $ f \\in \\S_2\\br{\\Gamma_0\\br{N}} $ be a newform with integer coefficients. There exists an elliptic curve $ E_f / \\QQ $ of conductor $ N $ such that $ \\L\\br{s, f} = \\L\\br{s, E_f} $.\n\\end{theorem}\n\nA question is that is the converse true?\n\n\\lecture{30}{Monday}{09/12/19}\n\n\\begin{theorem}[Eichler-Shimura, Deligne]\nLet $ f \\in \\S_k\\br{\\Gamma_0\\br{N}, \\chi} $ be a newform for $ k \\ge 2 $ such that $ \\T_lf = a_lf $ for all $ l \\nmid N $, and let $ p $ be a prime. There exists a unique homomorphism $ \\overline{\\rho_{f, p}} : \\Gal\\br{\\overline{\\QQ} / \\QQ} \\to \\GL_2\\br{\\overline{\\FF_p}} $ such that for all $ l \\nmid N $, $ \\overline{\\rho_{f, p}} $ is unramified at $ l $, $ \\Tr \\overline{\\rho_{f, p}}\\br{\\Frob_l} \\equiv a_l \\mod p $, and $ \\det \\overline{\\rho_{f, p}}\\br{\\Frob_l} \\equiv \\chi\\br{l}l^{k - 1} \\mod p $.\n\\end{theorem}\n\n\\begin{example*}\nIf $ f \\in \\S_2\\br{\\Gamma_0\\br{N}} $ has integer coefficients, then $ E_f\\sbr{p}\\br{\\overline{\\QQ}} \\cong \\br{\\ZZ / p\\ZZ}^2 $. Then $ \\rho_{f, p} : \\Gal\\br{\\overline{\\QQ} / \\QQ} \\to \\GL_2\\br{\\FF_p} $ gives an $ \\FF_p $-linear action of $ \\Gal\\br{\\overline{\\QQ} / \\QQ} $ on $ E_f\\sbr{p}\\br{\\overline{\\QQ}} $.\n\\end{example*}\n\nA natural question is given $ \\overline{\\rho} : \\Gal\\br{\\overline{\\QQ} / \\QQ} \\to \\GL_2\\br{\\overline{\\FF_p}} $, is $ \\overline{\\rho} = \\overline{\\rho_{f, p}} $ for some newform $ f $? If so, for which $ \\br{k, N, \\chi} $?\n\n\\begin{theorem}[Serre's conjecture 1987 and Khare-Wintenberger theorem 2005]\nLet $ \\overline{\\rho} : \\Gal\\br{\\overline{\\QQ} / \\QQ} \\to \\GL_2\\br{\\FF_p} $ be odd, that is $ \\det \\overline{\\rho}\\br{i \\mapsto -i} = -1 $.\n\\begin{itemize}\n\\item $ \\overline{\\rho} = \\overline{\\rho_{f, p}} $ for some newform $ f $.\n\\item Can take $ f $ of weight $ k_{\\overline{\\rho}} $, level $ N_{\\overline{\\rho}} $, and character $ \\chi_{\\overline{\\rho}} $, where\n\\begin{itemize}\n\\item $ 2 \\le k_{\\overline{\\rho}} \\le p $,\n\\item $ \\det \\overline{\\rho}\\br{\\Frob_l} \\equiv \\chi_{\\overline{\\rho}}\\br{l}l^{k_{\\overline{\\rho}} - 1} \\mod p $, and this condition determines $ k_{\\overline{\\rho}} $ modulo $ p - 1 $ and $ \\chi_{\\overline{\\rho}} $,\n\\item $ N_{\\overline{\\rho}} $ is the so-called \\textbf{Artin conductor} $ \\N\\br{\\overline{\\rho}} $ of $ \\overline{\\rho} $ usually, where\n$$ \\v_l\\br{\\N\\br{\\overline{\\rho}}} =\n\\begin{cases}\n0 & \\overline{\\rho} \\ \\text{is unramified at} \\ l \\\\\n1 & \\overline{\\rho}^{\\I_l} \\ \\text{has dimension one} \\\\\n\\ge 2 & \\text{otherwise}\n\\end{cases},\n$$\n\\item if $ k_{\\overline{\\rho}} = 2 $,\n$$ N_{\\overline{\\rho}} =\n\\begin{cases}\n\\dfrac{\\N\\br{\\overline{\\rho}}}{p} & \\overline{\\rho} \\ \\text{is finite at} \\ p \\\\\n\\N\\br{\\overline{\\rho}} & \\overline{\\rho} \\ \\text{is not finite at} \\ p\n\\end{cases}.\n$$\n\\end{itemize}\n\\end{itemize}\n\\end{theorem}\n\n\\begin{example*}\nIf $ \\overline{\\rho} $ comes from $ E / \\QQ $, then $ k_{\\overline{\\rho}} = 2 $, $ \\chi_{\\overline{\\rho}} $ is trivial, and $ N_{\\overline{\\rho}} \\mid \\N\\br{E} $, where $ \\N\\br{E} = \\prod_{l \\ \\text{bad for} \\ E} p^{\\v_l} $ is the \\textbf{conductor} of $ E $, and\n$$ \\v_l\\br{\\N\\br{E}} =\n\\begin{cases}\n1 & E \\ \\text{has multiplicative reduction} \\\\\n\\ge 2 & E \\ \\text{has additive reduction}\n\\end{cases}.\n$$\nMoreover, if $ \\v_l\\br{\\N\\br{E}} = 1 $ and $ p \\mid \\ord_l \\Delta_E $, then $ \\v_l\\br{N_{\\overline{\\rho}}} = 0 $.\n\\end{example*}\n\n\\begin{definition}[Frey 1985]\nSuppose $ p \\ge 5 $ and $ a^p + b^p = c^p $ for $ a, b, c $ coprime. Consider\n$$ y^2 = x\\br{x - a^p}\\br{x + b^p}, $$\nso $ \\Delta = 2^s\\br{abc}^p $.\n\\end{definition}\n\nThen $ E_{a, b, c} $ has multiplicative reduction modulo $ l $ for all $ l $, so $ \\N\\br{E_{a, b, c}} = \\rad 2abc $. Let $ \\overline{\\rho} : \\Gal\\br{\\overline{\\QQ} / \\QQ} \\to \\GL_2\\br{\\FF_p} $ giving action of $ \\Gal\\br{\\overline{\\QQ} / \\QQ} $ on $ E_{a, b, c}\\sbr{p}\\br{\\overline{\\QQ}} $. Then $ N_{\\overline{\\rho}} = 2 $, $ k_{\\overline{\\rho}} = 2 $, and $ \\chi_{\\overline{\\rho}} $ is trivial.\n\n\\begin{theorem}[Ribet 1986]\nIf $ \\overline{\\rho} $ comes from any newform, it comes from the level, weight, and character predicted by Serre.\n\\end{theorem}\n\n\\begin{corollary}\nIf $ E_{a, b, c} $ is modular, then the corresponding $ \\overline{\\rho} $ comes from a modular form in $ \\S_2\\br{\\Gamma_0\\br{2}} $.\n\\end{corollary}\n\nThe problem is $ \\dim \\S_k\\br{\\Gamma} \\le \\tfrac{1}{12}k\\sbr{\\SL_2\\br{\\ZZ} : \\Gamma} $, and $ \\sbr{\\SL_2\\br{\\ZZ} : \\Gamma_0\\br{2}} = 3 $, so $ \\dim \\S_2\\br{\\Gamma_0\\br{2}} \\le \\tfrac{1}{2} $.\n\n\\begin{theorem}[Wiles 1995 and Taylor-Wiles 1996]\nAll elliptic curves over $ \\QQ $ such that $ \\N\\br{E} $ is square-free are modular.\n\\end{theorem}\n\n\\begin{corollary}\nFermat's last theorem holds.\n\\end{corollary}\n\n\\end{document}", "meta": {"hexsha": "4cebe22a6af9d366286287b1dcc24ec72a61d663", "size": 134354, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "M4P58 Modular Forms/M4P58.tex", "max_stars_repo_name": "icl-notes/GANT", "max_stars_repo_head_hexsha": "0228d21307fbaa7971f4446d89a160d7dfc174a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2019-04-19T17:03:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-18T06:57:07.000Z", "max_issues_repo_path": "M4P58 Modular Forms/M4P58.tex", "max_issues_repo_name": "Multramate/IC-GANT", "max_issues_repo_head_hexsha": "ea1e3a1d97a2761bc1d0b60eea0c2cec91e17917", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-06T15:04:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-06T16:14:54.000Z", "max_forks_repo_path": "M4P58 Modular Forms/M4P58.tex", "max_forks_repo_name": "Multramate/IC-GANT", "max_forks_repo_head_hexsha": "ea1e3a1d97a2761bc1d0b60eea0c2cec91e17917", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-04-28T02:00:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-06T13:09:15.000Z", "avg_line_length": 57.1232993197, "max_line_length": 890, "alphanum_fraction": 0.5822826265, "num_tokens": 58569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.33530069917935457}}
{"text": "% Created: Enze Chen, August 2017\r\n% Updated: Aaron Lindenberg, 2018\r\n% Last edited: Enze Chen, February 2018\r\n%\r\n% Chapter 7 of the MSE 142 coursereader.\r\n\r\n% Uncomment the following three lines and last line to individually compile this chapter\r\n%\\documentclass[12pt, english]{book}\r\n%\\usepackage{142crstyle}\r\n%\\begin{document}\r\n\r\n\\chapter{Quantum Field Theory} \\label{ch:qft}\r\n%{ \\doublespacing \r\nOne of the greatest challenges facing scientists of the 20th century was using quantum mechanics to accurately model the behavior of subatomic particles, which usually involved painstakingly reconciling quantum mechanics with special relativity. Eventually, they developed the framework of quantum field theory (QFT), which treats particles as excited states (quanta) of the underlying \\emph{field} (hence the name).\\footnote{For an interesting explanation with helpful diagrams, see \\href{https://www.ribbonfarm.com/2015/08/20/qft/}{this post} from Brian Skinner.} We can think of a field as a network of interconnected balls and springs and the strength of the field can be measured by the amount of displacement from rest. In this chapter, we will only scratch the surface of QFT as we explore some of its most surprising and most important results. \\par \r\n\r\n\\section{Second quantization}\r\nSo far, all of the systems we have analyzed fall into the category of \\textbf{first quantization}, where we describe a quantum mechanical system by its wave function and we describe its surroundings (e.g. the potential well) using classical mechanics. While this formulation is well-defined for a single-particle system, many of its expressions grow combinatorially unwieldy for many-particle systems. In QFT, we are less concerned with the behavior of individual particles (``Which state is particle $i$ in?'') and we're more interested in the overall distribution (``How many particles are in state $\\alpha$?''). This calls for \\textbf{second quantization}, which places a QHO at each point in space such that the strength of the field is quantized. \\par \r\n\r\n\\subsection{Occupation number operator}\r\nRecall that for single particles, we used bra-ket notation to represent the quantum state as $\\ket{\\alpha}$, where $\\alpha = 0,\\ 1,\\ 2,\\ \\dots$. Now we will define the \\textbf{occupation number operator} $\\hat{n}_{\\alpha}$ to be the number of particles in the single-particle state $\\ket{\\alpha}$. These occupation numbers label the basis state, which is represented as\r\n\r\n\\begin{tcolorbox} [title=Basis vector] \\vspace{-2ex}\r\n\t\\begin{equation}\r\n\t\t\\ket{\\Psi} = \\ket{\\hat{n}_0,\\ \\hat{n}_1,\\ \\hat{n}_2,\\ \\dots,\\ \\hat{n}_{\\alpha},\\ \\dots} \\label{eq:fock}\r\n\t\\end{equation}\r\n\\end{tcolorbox} \r\n\r\nFor bosons, $\\hat{n}_{\\alpha}$ can be any non-negative integer, while for fermions $\\hat{n}_{\\alpha}$ must be 0 or 1.\\footnote{Bosons are a class of subatomic particles that have integer spins (e.g. photons, gluons, and other force carriers), while fermions are another class of subatomic particles that have non-integer spins (e.g. electrons) and obey the Pauli exclusion principle.} This formalism allows us to treat the quantum system as an ensemble of indistinguishable particles. The total number of particles is then\r\n\\begin{equation}\r\n\t\\hat{N} = \\sum_{\\alpha} \\hat{n}_{\\alpha}\r\n\\end{equation}\r\nwhich sums all the particles in all the states. \\par \r\n\r\nTo get a better understanding of the basis vectors, let's consider some special cases. First, there is a \\textbf{vacuum state} with no particles represented as\r\n\\begin{equation}\r\n\t\\ket{0} = \\ket{0,\\ 0,\\ 0,\\ \\dots}\r\n\\end{equation}\r\n\r\nThe single-particle state that we've previously encountered can be written as\r\n\\begin{equation}\r\n\t\\ket{1_{\\alpha}} = \\ket{0,\\ 0,\\ \\dots, 1_{\\alpha},\\ \\dots} = \\psi_{\\alpha}\r\n\\end{equation}\r\n\r\nFrom this point, many-particle, many-state bases can be easily deduced, and we'll leave it as an exercise to the reader to find the proper normalization coefficient. \\par \r\n\r\nNoticeably, the basis vector we defined in Equation~\\ref{eq:fock} does not have a fixed particle number. This allows us to introduce and take away particles from our quantum mechanical system, which is conveniently handled by the creation and annihilation operators. \\par \r\n\r\n\\subsection{Creation and annihilation operators}\r\n\r\nIn the previous chapter, we used the creation and annihilation operators to arrive at different energy states of the quantum harmonic oscillator. Here, since we are dealing with an ensemble of many particles in many states, we will have a different $\\ad_{\\alpha}$ and $a_{\\alpha}$ for each state $\\ket{\\alpha}$. Furthermore, the definition of the operators has changed, and now the creation operator acts as if it's truly ``creating'' another particle and adding it to the system. Formally, we have\r\n\\begin{equation}\r\n\t\\ad_{\\alpha} \\ket{\\hat{n}_1,\\ \\hat{n}_2,\\ \\dots,\\ \\hat{n}_{\\alpha},\\ \\dots} = \\sqrt{\\hat{n}_{\\alpha}+1}\\ket{\\hat{n}_1,\\ \\hat{n}_2,\\ \\dots,\\ \\hat{n}_{\\alpha}+1,\\ \\dots}\r\n\\end{equation} \r\n\r\nSimilarly, we define the annihilation operator as\r\n\\begin{equation}\r\na_{\\alpha} \\ket{\\hat{n}_1,\\ \\hat{n}_2,\\ \\dots,\\ \\hat{n}_{\\alpha},\\ \\dots} = \\sqrt{\\hat{n}_{\\alpha}}\\ket{\\hat{n}_1,\\ \\hat{n}_2,\\ \\dots,\\ \\hat{n}_{\\alpha}-1,\\ \\dots}\r\n\\end{equation} \r\n\r\nA simple demonstration of the creation operator would be to apply it to the vacuum state to obtain the single-particle state\r\n\\begin{equation}\r\n\t\\ad_{\\alpha} \\ket{0} = \\ket{1_{\\alpha}}\r\n\\end{equation}\r\n\r\nLikewise, if we apply the annihilation operator to the vacuum state, or any basis vector with zero particles in the particular state, we get zero.\r\n\\begin{equation}\r\n\ta_{\\alpha} \\ket{0} = 0, \\qquad a_{\\alpha} \\ket{\\hat{n}_1,\\ \\dots,\\ \\hat{n}_{\\alpha}=0,\\ \\hat{n}_{\\beta},\\ \\dots} = 0\r\n\\end{equation}\r\n\r\nIf we apply the annihilation operator and creation operator in succession, we obtain\r\n\\begin{equation*}\r\n\\ad_{\\alpha} a_{\\alpha} \\ket{\\hat{n}_1,\\ \\hat{n}_2,\\ \\dots,\\ \\hat{n}_{\\alpha},\\ \\dots} = \\hat{n}_{\\alpha}\\ket{\\hat{n}_1,\\ \\hat{n}_2,\\ \\dots,\\ \\hat{n}_{\\alpha},\\ \\dots}\r\n\\end{equation*}\r\n\r\nwhich gives the relation\r\n\\begin{equation}\r\n\t\\hat{n}_{\\alpha} = \\ad_{\\alpha}a_{\\alpha}\r\n\\end{equation}\r\n\r\n\r\nThis is similar to what we saw with the QHO and is another definition for the number operator. We will also state the commutation relations here without proof. Note that these are the same commutation relations as the QHO, and it's perfectly valid in QFT to consider bosons as energy quanta of an underlying field of quantum oscillators.\r\n\\begin{equation}\r\n\t\\left[\\ad_{\\alpha},\\ad_{\\beta}\\right] = \\left[a_{\\alpha},a_{\\beta}\\right] = 0, \\qquad \\left[a_{\\alpha}, \\ad_{\\beta}\\right] = \\delta_{\\alpha,\\beta}\r\n\\end{equation}\r\n\r\nWith the formal definitions of second quantization out of the way, we can proceed to a more interesting analysis. Since we have an operator that gives the number of particles of each state in our system, we can find the total energy of all the particles by a simple sum. The expression for the Hamiltonian becomes\r\n\\begin{equation}\r\n\t\\hat{H} = \\sum_{\\alpha} \\hbar\\omega_{\\alpha} \\left(\\hat{n}_{\\alpha} + \\frac{1}{2} \\right) = \\sum_{\\alpha} \\hbar\\omega_{\\alpha} \\left(\\ad_{\\alpha}a_{\\alpha} + \\frac{1}{2}\\right)\r\n\\end{equation}\r\n\r\n\r\nHere we give each quantum state its individual frequency $\\omega_{\\alpha}$. Now, as we showed in the last chapter, the Hamiltonian is a Hermitian operator, which means it should return a sensible value for the expectation. If we find the expected total energy of the vacuum state, we get the following:\r\n\\begin{align*}\r\n\t\\mel{0}{\\hat{H}}{0} &= \\sum_{\\alpha} \\hbar\\omega_{\\alpha} \\cancelto{0}{\\mel{0}{\\ad_{\\alpha}a_{\\alpha}}{0}} + \\sum_{\\alpha}\\hbar\\omega_{\\alpha}\\left(\\frac{1}{2}\\right) \\\\\r\n\t&= \\sum_{\\alpha} \\frac{\\hbar\\omega_{\\alpha}}{2} \\rightarrow \\infty\r\n\\end{align*}\r\n\r\nIn the second line, the summation of zero-point energies over an unbounded number of possible states seemingly gives infinite energy from vacuum fluctuations alone. Crazy! One of the early results of QFT was that the underlying field is in constant flux and it has physically relevant consequences. We'll see in the next section how we might resolve this ``infinite energy'' to make it physically interpretable.\r\n\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n\\section{Quantum electrodynamics}\r\nOne of the crowning achievements of QFT is the construction of \\textbf{quantum electrodynamics} (QED), which describes how light and matter interact in the quantized electromagnetic field.\\footnote{For a great introduction to QED in layman terms, see R. P. Feynman, \\href{https://en.wikipedia.org/wiki/QED:_The_Strange_Theory_of_Light_and_Matter}{\\emph{QED: The Strange Theory of Light and Matter}}. 1st ed., Princeton, NJ, Princeton University Press, 1985.} QED was the first theory to reconcile quantum mechanics and special relativity, and it led to extremely accurate calculations for the Lamb shift,\\footnote{A good description of the Lamb shift is provided by \\href{http://hyperphysics.phy-astr.gsu.edu/hbase/quantum/lamb.html}{Rod Nave}.} spontaneous emission (discussed in the next chapter), and a mysterious phenomenon called the Casimir effect, which we will discuss here. As it turns out, all of these phenomenon can be easily explained by the vacuum fluctuation energy and the way it interacts with matter.\r\n\r\n%\\subsection{Renormalization}\r\n\r\n\\begin{figure}[!h]\r\n\t\\centering\r\n\t\\subfloat[]{\\includegraphics[width=0.5\\linewidth]{casimir} \\label{casimir-fig}} \\hspace{2ex}\r\n\t\\subfloat[]{\\includegraphics[width=0.45\\linewidth]{casimir-exp} \\label{casimir-exp}}\r\n\t\\caption{\\protect\\subref{casimir-fig} A schematic of the Casimir effect observed between two metal plates. The boundary conditions at the plates allow a limited number of standing waves to exist in the middle region, which is fewer than the amount of vacuum fluctuations outside the plates. This creates a pressure difference that forces the plates together. \\protect\\subref{casimir-exp} An experimental measurement using an atomic force microscope of the Casimir force between an Al-coated sphere and an Al-coated surface. Reproduced from U. Mohideen and A. Roy, \\href{https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.81.4549}{\\emph{Phys. Rev. Lett.}} \\textbf{81}, 4549 (1998).}\r\n\t\\label{fig:casimir}\r\n\\end{figure}\r\n\r\n\\subsection{Casimir effect}\r\nIn 1948, Dutch physicist Hendrik Casimir predicted that the zero-point energy in the QED vacuum could cause a physical force between two neutral conducting plates.\\footnote{H. B. G. Casimir, \\href{http://www.dwc.knaw.nl/DL/publications/PU00018547.pdf}{\\emph{Proc. Kon. Ned. Akad. Wetensch.}} \\textbf{51}, 793 (1948)} This phenomenon became known as the \\textbf{Casimir effect} (Figure~\\ref{fig:casimir}) and can be explained using QED and second quantization. Although there are infinite vacuum fluctuations in the space outside of the plates, the reflective surface of the plates actually exclude virtual photons (manifestations of the underlying field) with wavelengths longer than the interplanar distance. Essentially you can think of the plates as nodes for the wave-like photons, so only wavelengths that line up perfectly will remain in the middle region. This reduces the energy density between the two plates, and much like normal pressure, the Casimir force pushes the two plates closer together. \\par \r\n\r\nSince we should not be merely satisfied with a description, let's try to find an analytical argument and really derive the strength of this Casimir force. Since we are working with the QED vacuum, we have to first establish the \\textbf{dispersion relation} for photons, which gives the relationship between the frequency and the wave number. Mathematically, this is written as\r\n\\begin{tcolorbox}[title=Dispersion relation] \\vspace{-2ex}\r\n\t\\begin{equation}\r\n\t\t\\omega_n = ck_n \\label{eq:dispersion}\r\n\t\\end{equation}\r\n\\end{tcolorbox}\r\n\r\nwhere $c$ is the speed of light and $k_n = n\\pi/d$. We also make use of the subscript $n$ here to index individual solutions, just like we did with the particle in a box. \\par \r\n\r\n\\subsection{Regularization and renormalization}\r\n\r\nNow we will try to find the amount of energy in between the two plates and subtract that quantity from the energy on the outside, and that should give us quantitative information about the Casimir force (its derivative will, anyways). Inside the two conducting plates, we have the following expression for the total energy:\r\n\\begin{align*}\r\n\tE_{\\text{in}} &= \\sum_{\\alpha} \\frac{\\hbar\\omega_{\\alpha}}{2} \\\\\r\n\t&= \\sum_{n=0}^{\\infty} \\frac{\\hbar c k_n}{2} \\\\\r\n\t&= \\frac{\\hbar \\pi c}{2d} \\sum_{n=1}^{\\infty} n \\numberthis \\label{eq:casimir-in}\r\n\\end{align*}\r\n\r\nWe use a discrete sum for the discrete energy levels of the bound photons, and just like before, we see that the total energy approaches infinity. Now, those of you that have taken complex analysis might see the summation and realize where this is headed---and yes indeed, it is possible to use analytical methods such as \\textbf{zeta function regularization} to evaluate the sum of natural numbers by assigning a finite value to an otherwise divergent sum.\\footnote{See \\href{https://en.wikipedia.org/wiki/1_\\%2B_2_\\%2B_3_\\%2B_4_\\%2B_\\%E2\\%8B\\%AF}{Wikipedia} for an interesting discussion about $1+2+3+4+\\cdots$.}\r\n\\begin{equation}\r\n\t \\sum_{n=1}^{\\infty} n = 1 + 2 + 3 + 4 + \\cdots = -\\frac{1}{12}   \\label{eq:sumN}\r\n\\end{equation}\r\n\r\nWe will come back to this shortly, and as bizarre as this is, I ask you to trust me for the time being. We still have to find the total energy of the virtual photons \\emph{outside} of the metal plates, which is similar to Equation~\\ref{eq:casimir-in}, except we will now take an integral (instead of a sum) because the modes are no longer confined to be integers and can be any non-negative real number. Proceeding, we have\r\n\\begin{align*}\r\n\tE_{\\text{out}} &= \\frac{\\hbar \\pi c}{2d} \\int_0^{\\infty} n \\dd{n} \\\\\r\n\t&= \\frac{\\hbar \\pi c}{2d} \\lim\\limits_{s \\rightarrow 0} \\int_0^{\\infty} ne^{-sn} \\dd{n} \\\\\r\n\t&= \\frac{\\hbar \\pi c}{2d} \\lim\\limits_{s \\rightarrow 0} \\int_0^{\\infty} \\dv{s} \\int ne^{-sn} \\dd{s} \\dd{n} \\\\\r\n\t&= -\\frac{\\hbar \\pi c}{2d} \\lim\\limits_{s \\rightarrow 0} \\dv{s} \\int_0^{\\infty} e^{-sn} \\dd{n} \\\\\r\n\t&= -\\frac{\\hbar \\pi c}{2d} \\lim\\limits_{s \\rightarrow 0} \\dv{s} \\left(-\\frac{1}{s} e^{-sn} \\bigg|_0^{\\infty} \\right) \\\\\r\n\t&= -\\frac{\\hbar \\pi c}{2d} \\lim\\limits_{s \\rightarrow 0} \\dv{s} \\left( \\frac{1}{s} \\right) \\\\\r\n\tE_{\\text{out}} &= \\frac{\\hbar \\pi c}{2d} \\lim\\limits_{s \\rightarrow 0} \\frac{1}{s^2} \\numberthis \\label{eq:casimir-out} \r\n\\end{align*}\r\n\r\nIn going from the first line to the second, we employed \\textbf{exponential regularization} to transform the integrand into something more manageable. Regularization is a common trick in QFT for dealing with infinities by employing a ``cutoff'' function to model physics at unobserved length scales. You can check for yourself that by taking the limit as $s$ approaches 0 we get back our original integral. In the third line we insert a derivative and integral with respect to $s$ to cleverly simplify our expression. These are \\emph{not} obvious steps, so don't worry if you find yourself asking how you would know to do this on your own. I wish to simply expose you to this technique, and as long as you are able to follow along, it is sufficient for this course. \\par \r\n\r\nOf course, the question we \\emph{should} be asking is how we could possibly subtract the two expressions we obtained in Equation~\\ref{eq:casimir-in} and~\\ref{eq:casimir-out}, which both approach infinity, and still get a non-zero result. As you may recall from calculus, some infinities are bigger than other infinities,\\footnote{\\href{https://en.wikipedia.org/wiki/Cantor\\%27s_diagonal_argument}{Cantor's diagonal argument} is one proof of this fact, and \\href{http://vihart.com/proof-some-infinities-are-bigger-than-other-infinities/}{Vi Hart} gives a great explanation in their video.} so as long as we can quantify \\emph{how much} greater one expression is than the other, then we can reach a finite result. This touches upon the concept of \\textbf{renormalization}, which is the other technique physicists use to handle infinities in QFT by assigning physical quantities to match observed values, thereby correcting for length-scale differences and self-interaction effects. \\par \r\n\r\nJust as we did in the derivation for $E_{\\text{out}}$, we will also apply regularization to the expression we obtained for $E_{\\text{in}}$. We will move quickly through the derivations here, and leave the details for Appendix~\\ref{sec:casimir-deriv}. Proceeding, we have:\r\n\\begin{align*}\r\n\tE_{\\text{in}} &= \\frac{\\hbar \\pi c}{2d} \\sum_{n=1}^{\\infty} n \\\\\r\n\t&= \\frac{\\hbar \\pi c}{2d} \\left( - \\lim\\limits_{s \\rightarrow 0} \\dv{s} \\sum_{n=0}^{\\infty} e^{-sn} \\right) \\\\\r\n\t&= \\frac{\\hbar \\pi c}{2d} \\left( - \\lim\\limits_{s \\rightarrow 0} \\dv{s} \\frac{1}{1-e^{-s}} \\right)\r\n\\end{align*}\r\n\r\nwhere we have used the sum of an infinite geometric series with common ratio $e^{-s}$ to arrive at the last line. Now we can evaluate the derivative to obtain\r\n\\begin{equation*}\r\n\tE_{\\text{in}} = \\frac{\\hbar \\pi c}{2d} \\left( \\lim\\limits_{s \\rightarrow 0} \\frac{e^{s}}{(e^s-1)^2} \\right)\r\n\\end{equation*}\r\n\r\nNow if we rewrite the last line using the Taylor series expansion around $s=0$, we get\r\n\\begin{align*}\r\n\tE_{\\text{in}} &= \\frac{\\hbar \\pi c}{2d} \\lim\\limits_{s \\rightarrow 0} \\left( \\frac{1+s+s^2/2 + \\cdots}{(s + s^2/2 + s^3/6 + \\cdots)^2} \\right) \\\\\r\n\t&= \\frac{\\hbar \\pi c}{2d} \\lim\\limits_{s \\rightarrow 0} \\left( \\frac{1}{s^2} - \\frac{1}{12} + \\mathcal{O}(s^2) \\right) \\numberthis \\label{eq:casimir-in2}\r\n\\end{align*}\r\n\r\nAs $s$ approaches 0, we can discard the terms of order 2 and greater, and subtract Equation~\\ref{eq:casimir-in2} from Equation~\\ref{eq:casimir-out}. This leaves us with \r\n\\begin{equation*}\r\n\tE_{\\text{out}} - E_{\\text{in}} = \\frac{\\hbar \\pi c}{2d} \\left[ \\frac{1}{s^2} - \\left( \\frac{1}{s^2} - \\frac{1}{12} \\right) \\right] = \\frac{\\hbar \\pi c}{24d}\r\n\\end{equation*}\r\n\r\n\\begin{tcolorbox}[title=Casimir force in one dimension] \\vspace{-2ex}\r\n\t\\begin{equation}\r\n\t\tF_{\\text{cas}} = -\\dv{E}{d} = -\\frac{\\hbar \\pi c}{24d^2}\r\n\t\\end{equation}\r\n\\end{tcolorbox}\r\n\r\nIn three dimensions, the Casimir force per unit area (a ``pressure'' quantity) becomes \r\n\\begin{equation*}\r\n\t\\frac{F_{\\text{cas}}}{A} = -\\frac{\\hbar\\pi^2c}{240d^4}\r\n\\end{equation*}\r\n\r\nThe negative sign here signifies an attractive force, which is what we expect if the energy density is larger on the outside of the plates than on the inside. The presence of $\\hbar$ also means $F_{\\text{cas}}$ is very small and hence only observable on the nanoscale. \\par \r\n\r\nThe Casimir effect was finally measured experimentally by Steven K. Lamoreaux in 1997,\\footnote{S. K. Lamoreaux, \\href{https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.78.5}{\\emph{Phys. Rev. Lett.}} \\textbf{78}, 5 (1997).} and the photo in Figure~\\ref{fig:casimir} is another experimental setup by Umar Mohideen that achieved measurement accuracy within 1\\% of the theoretical value. The Casimir force significantly dominates the other fundamental forces at nanometer length scales and plays an important role in the performance of nanoelectronics and nanodevices. What's perhaps most surprising about the Casimir effect is that the force can change between attractive and repulsive simply based on the geometry of the conducting plates! \\par\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n\\section{Application: Phonons}\r\nMaterials scientists typically work with condensed matter (solids and liquids) whose atom centers are analogous to the arrangement of harmonic oscillators in the quantum field. The periodicity of the atom centers in a crystal, much like what we saw in Chapter~\\ref{ch:period}, leads to distinct vibrational modes that are quantized as \\textbf{phonons} (Figure~\\ref{fig:phonons}). Nearest neighbor interactions (electrostatic forces, van der Waals forces, etc) create an energy landscape that is well approximated by a parabolic potential surface, much like the QHO. Analyzed in the framework of second quantization, phonons behave exactly like bosons, with the same Hamiltonian, creation and annihilation operators, and commutation relations. \r\n\r\n\\begin{figure}[!h]\r\n\t\\centering\r\n\t\\includegraphics[width=0.5\\linewidth]{phonons}\r\n\t\\caption{Collective vibrations in a crystal are quantized as phonons.}\r\n\t\\label{fig:phonons}\r\n\\end{figure}\r\n\r\nPhonons play a major role in the electrical conductivity, thermal conductivity, and thermal capacity of condensed matter. One of the most interesting features of phonons is when there are two different atoms vibrating next to each other, which results in two different phonon modes. The dispersion relation is given by the following equation and it is plotted in Figure~\\ref{fig:phonon-modes}.\r\n\\begin{equation}\r\n\t\\omega^2 = \\frac{C}{m_1m_2} \\left(m_1 + m_2 \\pm \\sqrt{m_1^2 + m_2^2 + 2m_1m_2\\cos(kd)}\\right)\r\n\\end{equation}\r\n\r\n\\begin{figure}[!h]\r\n\t\\centering\r\n\t\\subfloat[]{\\includegraphics[width=0.5\\linewidth]{phonon-modes} \\label{phonon-modes}} \\hspace{3ex}\r\n\t\\subfloat[]{\\includegraphics[width=0.35\\linewidth]{phonon-absorption} \\label{phonon-absorption}}\r\n\t\\caption{\\protect\\subref{phonon-modes} Dispersion relation for phonons in a solid with two atoms per unit cell. The acoustic mode governs thermomechanical properties while the optical mode governs electronic properties. \\protect\\subref{phonon-absorption} Transmissivity of a film of RbI at different temperatures, with each minimum at a photon energy equal to that of the long wavelength transverse optical phonon. Reproduced from G. O. Jones \\emph{et al.} \\href{http://rspa.royalsocietypublishing.org/content/261/1304/10}{\\emph{Proc. R. Soc. Lond.}} \\textbf{A261}, 10-27, (1961).}\r\n\t\\label{fig:phonon-modes}\r\n\\end{figure}\r\n\r\nWhen atoms are vibrating coherently (in the same direction; corresponding to the minus sign in the above equation), \\textbf{acoustic phonons} are produced, named because they regulate the speed of sound in the medium as well as the medium's mechanical and thermal properties.\\footnote{See A. A. Balandin \\href{https://www.nature.com/nmat/journal/v10/n8/full/nmat3064.html}{\\emph{Nature Materials}}, \\textbf{10}, 569-581 (2011) for a review of the thermal properties of carbon nanostructures.} On the other hand, atoms vibrating out-of-phase (in opposite directions) will produce \\textbf{optical phonons}, which interact with light in absorption and \\emph{Raman scattering}. \r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n\\section{Summary}\r\nTo recap, this chapter gave us a taste of quantum field theory and some of its important applications. Second quantization provided a suitable framework for interpreting fields with the new occupation number operator and new definitions for the creation and annihilation operators. Then we explored the strange nature of the Casimir effect using regularization and renormalization to handle various infinities. Finally, we related the theoretical framework of QFT to phonons, which are quantized lattice vibrations that govern a lot of material behavior. This chapter was largely enrichment in the context of this course, but you will definitely see more of QFT as you take more advanced courses in quantum mechanics due to its profound implications. Perturbation theory, which we will see in the next chapter, is another subfield of quantum mechanics that shares similarities with QFT.\r\n\r\n\r\n%} % for doublespacing\r\n%\\end{document}", "meta": {"hexsha": "590d00fef0af863fd49d5b27d3899613d09bf98e", "size": 23593, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/chapter_7.tex", "max_stars_repo_name": "Enze-Chen/mse_142_cr", "max_stars_repo_head_hexsha": "a98585b32f26f6c189b96345d9cc1e9727156268", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-13T17:08:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-13T17:08:24.000Z", "max_issues_repo_path": "tex/chapter_7.tex", "max_issues_repo_name": "Enze-Chen/mse_142_cr", "max_issues_repo_head_hexsha": "a98585b32f26f6c189b96345d9cc1e9727156268", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/chapter_7.tex", "max_forks_repo_name": "Enze-Chen/mse_142_cr", "max_forks_repo_head_hexsha": "a98585b32f26f6c189b96345d9cc1e9727156268", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 103.0262008734, "max_line_length": 1019, "alphanum_fraction": 0.739032764, "num_tokens": 6500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.33530069917935457}}
{"text": "% !TEX TS-program = xelatex\n% !TEX encoding = UTF-8 Unicode\n\\documentclass[11pt,a4paper,twoside]{book}\n\\usepackage{amsmath,amssymb}\n\\usepackage{empheq}\n\\usepackage[semibold]{ebgaramond}\n\\usepackage[cmintegrals,cmbraces]{newtxmath}\n\\usepackage{ebgaramond-maths}\n\\usepackage{bm}\n\\usepackage[OMLmathrm, OMLmathsfit, rmdefault=mdugm]{isomath}\n\\usepackage{tocbibind}\n\\usepackage{makeidx}\n\\makeindex\n\n\\makeatletter\n  \\DeclareSymbolFont{ntxletters}{OML}{ntxmi}{m}{it}\n  \\SetSymbolFont{ntxletters}{bold}{OML}{ntxmi}{b}{it}\n  \\re@DeclareMathSymbol{\\leftharpoonup}{\\mathrel}{ntxletters}{\"28}\n  \\re@DeclareMathSymbol{\\leftharpoondown}{\\mathrel}{ntxletters}{\"29}\n  \\re@DeclareMathSymbol{\\rightharpoonup}{\\mathrel}{ntxletters}{\"2A}\n  \\re@DeclareMathSymbol{\\rightharpoondown}{\\mathrel}{ntxletters}{\"2B}\n  \\re@DeclareMathSymbol{\\triangleleft}{\\mathbin}{ntxletters}{\"2F}\n  \\re@DeclareMathSymbol{\\triangleright}{\\mathbin}{ntxletters}{\"2E}\n  \\re@DeclareMathSymbol{\\partial}{\\mathord}{ntxletters}{\"40}\n  \\re@DeclareMathSymbol{\\flat}{\\mathord}{ntxletters}{\"5B}\n  \\re@DeclareMathSymbol{\\natural}{\\mathord}{ntxletters}{\"5C}\n  \\re@DeclareMathSymbol{\\star}{\\mathbin}{ntxletters}{\"3F}\n  \\re@DeclareMathSymbol{\\smile}{\\mathrel}{ntxletters}{\"5E}\n  \\re@DeclareMathSymbol{\\frown}{\\mathrel}{ntxletters}{\"5F}\n  \\re@DeclareMathSymbol{\\sharp}{\\mathord}{ntxletters}{\"5D}\n  \\re@DeclareMathAccent{\\vec}{\\mathord}{ntxletters}{\"7E}\n\\makeatother\n\n\\usepackage{array}\n% to produce a comma between multiple footnotes / https://tex.stackexchange.com/questions/40072/incompatibility-between-footmisc-option-multiple-and-hyperref/62091#62091\n\\let\\oldFootnote\\footnote\n\\newcommand\\nextToken\\relax\n\\renewcommand\\footnote[1]{%\n    \\oldFootnote{#1}\\futurelet\\nextToken\\isFootnote}\n\\newcommand\\isFootnote{%\n    \\ifx\\footnote\\nextToken\\textsuperscript{,}\\fi}\n\n\\defaultfontfeatures{Ligatures=TeX} % makes this a feature for all selected fonts\n\\usepackage{esint}\n\\usepackage{polyglossia}\n\\setmainlanguage{english}\n\\usepackage[text={18cm,26cm},centering]{geometry} % \n\\usepackage{natbib}\n\\usepackage{graphicx}\n\\graphicspath{{pics/}}\n\\usepackage[usenames,dvipsnames,svgnames,table]{xcolor}\n\\usepackage{hyperref}\n\\usepackage{url}\n\\usepackage[export]{adjustbox}\n\n\\hypersetup{\n  colorlinks,\n  citecolor=bleuSU,\n  linkcolor=bleuSU\n}\n\\definecolor{bleuSU}{RGB}{26,39,101}\n\n\\usepackage[normalem]{ulem}\n\\makeatletter\n\\renewcommand*{\\uuline}{%\n  \\bgroup\n  \\UL@setULdepth\n  \\markoverwith{%\n    \\lower\\ULdepth\\hbox{%\n      \\kern-.03em%\n      \\vtop{%\n        \\hrule width.2em%\n        \\kern 0.6pt % distance between the two underlines\n        \\hrule\n      }%\n      \\kern-.03em%\n    }%\n  }%\n  \\ULon\n}\n\\makeatother\n\\setlength{\\ULdepth}{-2pt}  % distance from double underline to letter\n\n\\newcommand{\\delS}{\\delta S}\n\\newcommand{\\delA}{\\delta A}\n\\newcommand{\\delh}{\\delta h}\n\\newcommand{\\delt}{\\delta t}\n\\newcommand{\\delz}{\\delta z}\n\\newcommand{\\delbx}{\\delta \\matrixsym x}\n\\newcommand{\\lp}{\\left(}\n\\newcommand{\\rp}{\\right)}\n\\newcommand{\\itA}{\\textit A}\n\\newcommand{\\itB}{\\textit B}\n\\newcommand{\\dAB}{\\mathcal D_{AB}}\n\\newcommand{\\bA}{\\matrixsym A}\n\\newcommand{\\bff}{\\matrixsym{f}}\n\\newcommand{\\bF}{\\matrixsym{F}}\n\\newcommand{\\bj}{\\matrixsym{j}}\n\\newcommand{\\bJ}{\\matrixsym J}\n\\newcommand{\\bn}{\\matrixsym{n}}\n\\newcommand{\\bN}{\\matrixsym N}\n\\newcommand{\\bp}{\\matrixsym{p}}\n\\newcommand{\\bP}{\\matrixsym{P}}\n\\newcommand{\\br}{\\matrixsym r}\n\\newcommand{\\bt}{\\matrixsym t}\n\\newcommand{\\be}{\\matrixsym e}\n\\newcommand{\\bu}{\\matrixsym u}\n\\newcommand{\\bU}{\\matrixsym U}\n\\newcommand{\\bv}{\\matrixsym v}\n\\newcommand{\\bV}{\\matrixsym V}\n\\newcommand{\\bw}{\\matrixsym w}\n\\newcommand{\\bx}{\\matrixsym x}\n\\newcommand{\\bX}{\\matrixsym X}\n\\newcommand{\\by}{\\matrixsym y}\n\\newcommand{\\pd}[2]{\\frac{\\partial #1}{\\partial #2}}\n\\newcommand{\\D}[2]{\\frac{D #1}{D #2}}\n\\newcommand{\\dd}[2]{\\frac{\\mathrm d #1}{\\mathrm d #2}}\n\\newcommand{\\dA}{\\mathrm dA}\n\\newcommand{\\dV}{\\mathrm dV}\n\\newcommand{\\dS}{\\mathrm dS}\n\\newcommand{\\prg}[1]{\\paragraph{$\\rhd$ #1}}\n\\newcommand{\\alphaijkl}{\\alpha_{ijkl}}\n\\newcommand{\\Aijkl}{A_{ijkl}}\n\\newcommand{\\delij}{\\delta_{ij}}\n\\newcommand{\\sigij}{\\sigma_{ij}}\n\\newcommand{\\sigji}{\\sigma_{ji}}\n\\newcommand{\\sigxy}{\\sigma_{xy}}\n\\newcommand{\\matL}{\\mathcal L}\n\\newcommand{\\matO}{\\mathcal O}\n\\newcommand{\\matS}{\\mathcal S}\n\\newcommand{\\kij}{k_{ij}}\n\\newcommand{\\tensor}[1]{\\smash{\\uuline{#1}{}}}\n\\setlength{\\parindent}{0pt} % remove indent\n  \n\\counterwithout{footnote}{chapter}\n\n\\begin{document}\n{\n\\title{\\textit{Physics of fluids \\& nonlinear physics}}\n%\\author{Arnaud Antkowiak \\qquad Camille Duprat}\n\\author{\n  \\textsc{Arnaud Antkowiak}\\footnote{\\href{mailto:arnaud.antkowiak@upmc.fr}{arnaud.antkowiak@upmc.fr}}\\\\ \\textsc{Sorbonne Université}\n  \\and\n  \\textsc{Camille Duprat}\\footnote{\\href{mailto:camille.duprat@ladhyx.polytechnique.fr}{camille.duprat@ladhyx.polytechnique.fr}}\\\\ \\textsc{École polytechnique}\n}\n%\\author{Arnaud Antkowiak}\n%\\affil{Sorbonne Université}\n%\\author{Camille Duprat}\n%\\affil{École polytechnique}\n\n\\date{v0.21.09$_\\text{26}$}\n\\maketitle\n\\tableofcontents\n}\n\\input{./01_equations.tex}\n\\input{./02_boundary_conditions.tex}\n\\input{./03_viscous_flows.tex}\n\\bibliographystyle{jfm}\n\\bibliography{biblio_pof}\n\\printindex\n\\end{document}\n", "meta": {"hexsha": "3fe098e6e72359a9b53899d89ff6c9586b3c5921", "size": 5179, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "lecture/physics_of_fluids.tex", "max_stars_repo_name": "antko/physics-of-fluids", "max_stars_repo_head_hexsha": "307f1c25c59345943a4bce90e031ced5dde105bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lecture/physics_of_fluids.tex", "max_issues_repo_name": "antko/physics-of-fluids", "max_issues_repo_head_hexsha": "307f1c25c59345943a4bce90e031ced5dde105bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lecture/physics_of_fluids.tex", "max_forks_repo_name": "antko/physics-of-fluids", "max_forks_repo_head_hexsha": "307f1c25c59345943a4bce90e031ced5dde105bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9691358025, "max_line_length": 169, "alphanum_fraction": 0.7310291562, "num_tokens": 1885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.33530069917935457}}
{"text": "% mainfile: ../Refinement.tex\n\\chapter{Introduction}\n\\pagestyle{scrheadings}\t\n\\setcounter{page}{0}\n\\pagenumbering{arabic} \n\\label{chp_introduction}\nModeling distributed computing systems exhibit various aspects such as modeling the components of the system and modeling the behavior and communication between the concurrent mobile components. Formal specification techniques for such systems have to be able to describe all these aspects. Unfortunately, a single specification technique that is well suited for all these aspects is not yet available. Instead, one finds techniques that are very good at describing individual aspects of system. This observation has led to research into the combination and semantic integration of specification techniques. In this thesis we research combining the two specification techniques:\n\\picalc{} and Object-Z.\n\nThe \\picalc{} is a process algebra originally introduced by Robin Milner, Joachim Parrow, and David Walker in \\cite{milner1992calculus}. The central concepts of \\picalc{} are communication via channels between different processes, creating new channels, parallel composition, and the mobility of channels, which we will use to model the mobility of components. Tool support comes through the \\picalc{} visualizer Stargazer and the bisimulation checker ABC.\n\nObject-Z \\cite{smith2000the} is an object-oriented extension of the Z formal specification language. It represents a set-theoretic and predicate language for the specification of data. It extends Z by the addition of language constructs resembling the object-oriented paradigm, most notably, classes to encapsulate a state schema, an initial state schema and operation schemas. The state schema specifies the set of the legal states. The initial state schema specifies the set of the legal initial states. The operation schemas specify the legal ways of moving from one state to another.\n\n\nThe main contribution of this thesis is to develop the combination $\\pi$-OZ and to transform it into a \\picalc{} process, similarly to the approach for CSP-OZ in \\cite{olderog}. $\\pi$-OZ is a new combination of formal techniques for the specification of components and their behavior. The basic idea is to use a \\picalc{} process to specify the behavior of an Object-Z class. This enables the mobility of Object-Z classes through the use of the state pattern \\cite{erichgamma1994}, which is a behavioral software design pattern that allows an object to alter its behavior when its state changes. Syntactically, the $\\pi$-OZ specification is divided into an OZ part specifying the data and the possible state transitions, and a $\\pi$ part specifying the behavior.  This combination is illustrated by the example of a mobile vending machine and two shops, which alternate their behavior when they connect to the mobile vending machine.\n\n Transforming the combination $\\pi$-OZ into a \\picalc{} process enables checking the simulation of mobile processes with data. The transformation gives the combination a \\picalc{} semantics. The idea is that this semantics comes from the parallel composition of the $\\pi$ part and a $\\pi$ process, representing the OZ part transformed syntactically into a \\picalc{} process.\n\n Furthermore, we investigate a failure-model and a success-model for the \\picalc{} processes and show their relation to the simulation and point out its limitations.\n\nThis thesis is divided into five chapters. Chapter 2 gives an overview of the \\picalc{} and Object-Z. Thereby, Dynamic OZ, a new extension of Object-Z is introduced to model mobile components with alternating behavior. Chapter 3 proceeds by transforming OZ class into a \\picalc{} process. Subsequently, Chapter 4 introduces the combination $\\pi$-OZ and its transformation into the \\picalc{}. Chapter 5 introduces the failure and the success refinement of the \\picalc{} and their relation to the simulation. Finally, the conclusion in Chapter 6 summarizes our results and presents future directions of our research.\n\n", "meta": {"hexsha": "78cf58f2a2d400362e021e797b6b8615888ac19c", "size": 3994, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/introduction/introduction.tex", "max_stars_repo_name": "MuhammadEkbal/thesis", "max_stars_repo_head_hexsha": "dcb71d5d7af7a8e87d7d230d58f18c01dbdfe13a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/introduction/introduction.tex", "max_issues_repo_name": "MuhammadEkbal/thesis", "max_issues_repo_head_hexsha": "dcb71d5d7af7a8e87d7d230d58f18c01dbdfe13a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/introduction/introduction.tex", "max_forks_repo_name": "MuhammadEkbal/thesis", "max_forks_repo_head_hexsha": "dcb71d5d7af7a8e87d7d230d58f18c01dbdfe13a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 173.652173913, "max_line_length": 933, "alphanum_fraction": 0.8092138207, "num_tokens": 826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.33530069111387756}}
{"text": "\\chapter{Inelastic Cosmic Ray Collisions}\\label{chap:cr}\n\nDark Matter direct detection experiments lose sensitivity to sub-GeV particles due to prohibitively small nuclear recoil energies. On the other hand, previous work such as ~\\cite{Bringmann:2018cvk, Ema:2018bih} suggests that light dark matter may naturally lead to a sub-dominant flux of higher momenta particles. This would lead to a reinterpretation of the current direct detection limits. Here we present a calculation of such a flux arising from inelastic cosmic ray collisions in the atmosphere. We also derive limits from the XENON1T experiment and forecast the reach of the LZ detector.\n\n\\section{Cosmic Ray Dark Matter Flux}\nWe distinguish two possible sources for a dark matter flux arising from the mechanism described in the Introduction: inelastic cosmic ray collisions with protons in the interstellar medium and with the atmosphere on Earth. According to our calculations, the former yields a flux several orders of magnitude lower than the latter; therefore, we may safely neglect it and focus on our modelling of interactions at the atmosphere. \n\nThe incoming cosmic ray flux is taken to be the local interstellar proton spectrum parametrised as in Ref.~\\cite{Boschini:2017fxq}; alternatively we have also checked that using the AMS02 spectrum~\\cite{Consolandi:2014uia} leads to identical results. The differential intensity $dI/dR$ as a function of particle rigidity $R$ is converted to a flux $d\\Phi_p / dT_p = 2\\pi (dR/dT_p)(dI/dR)$ per unit area, time, and kinetic energy $T_p$, over a hemispherical solid angle. We performed a Monte-Carlo simulation of this incoming flux using EPOS-LHC~\\cite{Pierog:2013ria}, as implemented in the CRMC package~\\cite{CRMC}, to simulate the collisions assuming the atmospheric nuclei target to be nitrogen at rest. The resulting $\\pi^0$ and $\\eta$ mesons undergo two subsequent two-body decays via a vector or scalar mediator~\\footnote{Here we consider only on-shell mediators though the sensitivity could in principle be extended to heavier off-shell mediators.} to a pair of dark matter particles, with a branching ratio that we keep as a free parameter. The rate of interactions is then integrated as follows over the volume of the atmosphere to obtain the total dark matter flux at the detector. \n\n\\begin{figure}[t]\n\\begin{center}\n\\includegraphics[width=0.6\\textwidth]{pion_eta_chi_no_title.pdf}\n\\end{center}\n\\caption{Dark matter flux from cosmic rays for elastic collisions in dotted orange with $m_\\chi = 1$ MeV, and for inelastic collisions with $BR(\\pi^0 \\to \\chi \\chi + ...) = 10^{-6}$ in solid green and $BR(\\eta \\to \\chi\\chi + ...) = 10^{-2}$ in solid red.\n\\label{fig:flux}}\n\\end{figure}\n\nThe differential cosmic ray flux gets attenuated through the atmosphere as a function of height $h$ from ground level: \n%\n\\begin{equation}\n\\frac{d}{dh}\\left(\\frac{d\\Phi_p}{dT_p}\\right) = \\sigma_{pN}(T_p) n_N(h) \\frac{d\\Phi_p}{dT_p} \\, ,\n\\label{eq:diff}\n\\end{equation}\n%\nwhere $\\sigma_{pN}$ is the inelastic proton-nitrogen cross-section and $n_N$ is the number density of air, taken from Ref.~\\cite{Jursa:1985}, which is assumed to be entirely nitrogen for simplicity. \\eqref{eq:diff} neglects higher order effects such as regenerations and secondary scatterings involved in a detailed cosmic ray shower model, but it is sufficient to provide a conservative estimate of our hidden sector flux. Since $\\sigma_{pN} \\simeq 255$ mb is constant to a good approximation over the relevant energy range, we may write $\\frac{d\\Phi_p}{dT_p}(T_p,h) \\equiv y(h) \\cdot \\frac{d\\Phi_p}{dT_p}(T_p)$ and solve for the attenuation factor $y(h)$. The dark matter flux at a detector located at a depth $z_d$ below ground is then given by\n%\n\\begin{align} \\frac{d \\Phi_{\\chi}}{d T_{\\chi}} &=\\int_{R_{E}}^{R_{E}+h} R^{2} d R \\int_{0}^{2 \\pi} d \\phi \\int_{\\cos \\theta_{\\max }}^{1} \\frac{d(\\cos \\theta)}{2 \\pi l\\left(R, \\theta, z_{d}\\right)^{2}} \\nonumber \\\\ & y\\left(R-R_{E}\\right) \\frac{d \\Phi_{p}}{d T_{p}} n_{N}\\left(R-R_{E}\\right) \\sigma_{p N \\rightarrow M} B R_{M \\rightarrow \\chi \\chi} \\equiv \\frac{d \\Phi_{p}}{d T_{p}} n_{N}^{0} H_{\\mathrm{eff}} \\sigma_{p N \\rightarrow M} B R_{M \\rightarrow \\chi \\chi} \\label{eq:integratedflux}\\end{align}\nwhere $R_E$ is the radius of the Earth and $\\theta_{\\mathrm{max}}$ is a maximum angle dependent on the path length attenuation through the Earth, as described in the next Section. The line of sight distance $l(R,\\theta, z_d)$ is given by \n%\n\\begin{equation}\nl^2 = (R_E - z_d)^2 + R^2 - 2(R_E - z_d)R \\cos{\\theta} \\, .\n\\end{equation}\n%\nIt determines the rate dilution factor in the emission from source to detector that we have conservatively assumed to be isotropically distributed over a hemisphere. In the last line of \\eqref{eq:integratedflux} we defined an equivalent effective height at a constant number density taken to be the ground-level value, $n_N^0 \\simeq 5\\times 10^{19} \\mathrm{ cm}^{-3}$~\\cite{Jursa:1985}. For example, with $\\cos\\theta_{\\mathrm{max}} = -1$, i.e. the Earth completely transparent to dark matter, we obtain $H_{\\mathrm{eff}} \\simeq 5$ km. \n\nThe resulting dark matter flux in the transparent Earth case is plotted in Fig. \\ref{fig:flux} in solid red for $BR(\\eta \\to \\chi \\chi + ...) = 10^{-2}$ and green for $BR(\\pi^0 \\to \\chi\\chi + ...) = 10^{-6}$, close to their experimental upper limits. The fluxes are rather insensitive to the mediator and dark matter masses when these are produced on-shell. For comparison, we show in dotted orange the up-scattered flux for $m_\\chi = 1$ MeV coming from elastic collisions of cosmic rays with interstellar dark matter, calculated as in Ref.~\\cite{Bringmann:2018cvk}. Finally we have also checked that, when restricting to an opaque Earth, the muon flux obtained in our approach is in good agreement with data~\\cite{Haino:2004nq,Tanabashi:2018oca}.\n\n\\section{Attenuation through the Earth}\n\nAs dark matter travels from the point of production through the Earth a large enough nucleus interaction cross-section can prevent it from reaching the detector. The mean free path length together with the line of sight distance through the Earth to the detector then determines the maximum polar angle at which we cut off the atmospheric volume integral in \\eqref{eq:integratedflux}. This line of sight distance through the Earth is given by\n%\n\\begin{align}\nl_E &= \\frac{1}{2}\\left( b + \\sqrt{b^2 + 4(R_E^2 - (R_E - z_d)^2)} \\right) \\, , \\nonumber \\\\\nb &\\equiv \\text{Sign}\\left[R_E - z_d - (R_E + h)\\cos\\theta \\right]  \\nonumber \\\\\n& \\quad \\quad \\quad \\times 2(R_E - z_d) \\sqrt{1 - \\frac{(R_E +h)^2 \\sin^2\\theta}{l^2}} \\, .\n\\end{align}\n%\n\nThe mean free path length is determined by solving for the kinetic energy loss assuming a uniform distribution of nuclear recoil energy in elastic scattering, $d\\sigma_{\\chi N}/dT_r = \\sigma_{\\chi N} / T_r^{\\mathrm{max}}$, following Ref.~\\cite{Bringmann:2018cvk}. Summing over the nuclei $N$, we then have\n%\n\\begin{align}\n\\frac{dT_\\chi}{dz} &= - \\sum_N n_N \\int_0^{T_r^{\\mathrm{max}}} \\frac{d\\sigma_{\\chi N}}{dT_r} T_r dT_r \\nonumber \\underset{(T_\\chi \\ll m_N) }{\\simeq} -\\frac{1}{2m_\\chi L}\\left(T_\\chi^2 + 2 m_\\chi T_\\chi \\right) \\, ,\n\\end{align}\n%\nwhere we used\n%\n\\begin{equation}\nT_r^{\\mathrm{max}} = \\frac{T_\\chi^2 + 2m_\\chi T_\\chi}{T_\\chi + (m_\\chi + m_N)^2/(2m_N)} \\, ,\n\\end{equation}\n%\nand defined the mean free path length\n%\n\\begin{equation}\nL \\equiv \\left( \\sum_N n_N \\sigma_{\\chi N} \\frac{2 m_N m_\\chi}{(m_\\chi + m_N)^2} \\right)^{-1} \\, .\n\\end{equation}\n%\nIntegrating this equation gives the incoming energy $T_\\chi^0$ that is required to arrive at the detector with energy $T_\\chi^z$ a distance $l_E$ through the Earth:\n%\n\\begin{equation}\nT_\\chi^0 = \\frac{2 m_\\chi T_\\chi^z e^{l_E/L}}{2 m_\\chi + T_\\chi^z(1-e^{l_E/L})} \\, .\n\\end{equation}\n%\nFrom this we obtain $\\theta_{\\mathrm{max}}$ when $T_\\chi^0 \\to \\infty$. The mean free path length is calculated by summing over the average number density of the elements given in Table 2 of Ref.~\\cite{Kavanagh:2016pyr}. We relate the nuclear interaction cross-section to the per nucleon spin-independent cross-section $\\sigma_\\chi^{\\mathrm{SI}}$ as\n%\n\\begin{equation}\n\\sigma_{\\chi N} = \\sigma_\\chi^{\\mathrm{SI}} A^2 \\left(\\frac{m_N}{m_p} \\frac{(m_\\chi + m_p)}{(m_\\chi + m_N)} \\right)^2 \\, .\n\\end{equation} \n%\n\nIn practise we find that at the depth of the XENON1T detector the attenuation starts cutting off the atmospheric volume integral for cross-sections above $\\sigma_\\chi^{\\mathrm{SI}} \\gtrsim 10^{-32} \\, \\mathrm{cm}^2$, with transmission falling exponentially above $\\sim 10^{-28} \\, \\mathrm{cm}^2$.\n\n\\section{Limits}\n\nFinally, we obtain the expected rate at a detector coming from our inelastic cosmic ray dark matter flux by integrating within the detector nuclear recoil thresholds $T_1$ and $T_2$:\n%\n\\begin{equation}\n\\Gamma_N = N_T \\int_{T_1}^{T_2} dT_N \\int_{T_\\chi^{\\mathrm{min}}(T_N)}^\\infty dT_\\chi \\epsilon(T_N) \\frac{d\\Phi_\\chi}{dT_\\chi} \\frac{d\\sigma_{\\chi N}}{dT_N} \\, ,\n\\end{equation}\n%\nwhere $N_T$ is the number of target atoms, $\\epsilon$ is the detector nuclear recoil energy efficiency, and\n%\n\\begin{equation}\nT_\\chi^{\\mathrm{min}} = \\left(\\frac{T_N}{2} - m_\\chi \\right)\\left(1 \\pm \\sqrt{1 + \\frac{2T_N}{m_N}\\frac{(m_\\chi + m_N)^2}{(2m_\\chi - T_N)^2}} \\right) \\, ,\n\\end{equation}\n%\nwith a plus sign if $T_\\chi > 2m_N$ and minus sign otherwise. As an illustrative example we will focus on the limits from XENON1T. Its nuclear recoil energy threshold window is from $T_1 = 4.9$ keV to $T_2 = 40.9$ keV and the detector is located at a water-equivalent depth of 3.6 km, corresponding to 1.4 km of rock~\\cite{Aprile:2018dbl}. For the 90\\% CL limits we require a total number of events $N_{90\\% \\text{ CL}} = 3.56$ for the full exposure of 278.8 days of data collection with 1.3t fiducial mass. This event count, in Table 1 of Ref.~\\cite{Aprile:2018dbl}, is the best fit given by a likelihood analysis for a 200 GeV WIMP whose recoil spectrum is comparable to that of the energetic light dark matter flux. \n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=0.615 \\textwidth]{sigma_mchi_eta_pi_no_title.pdf} \\\\\n\\hspace{-0.25cm}\\includegraphics[width=0.6 \\textwidth]{limit_no_title.pdf}\n\\end{center}\n\\caption{90\\% CL limits on the spin-independent dark matter-nucleon cross-section as a function of dark matter mass for a fixed branching ratio (\\textit{top}) and as a function of branching ratio for a fixed dark matter mass (\\textit{bottom}), as labelled. The inelastic cosmic ray dark matter limits from XENON1T~\\cite{Aprile:2018dbl} are indicated in red and green for the flux originating from meson $M=\\eta$ and $\\pi^0$ decays, respectively, and in orange for elastic cosmic ray dark matter. The dashed lines are projections for the future LZ experiment~\\cite{Akerib:2018lyp}. Other limits in grey are taken from Ref.~\\cite{Bringmann:2018cvk} (based on CRESST~\\cite{Angloher:2017sxg}, CMB~\\cite{Xu:2018efh}, and gas cloud cooling~\\cite{Bhoonah:2018wmw}), and from Milky-way satellites~\\cite{Nadler:2019zrb}. \n\\label{fig:limits}}\n\\end{figure}\n\n\nFor comparison with Ref.~\\cite{Bringmann:2018cvk}, we first assume a uniform recoil energy distribution, $d\\sigma_{\\chi N}/dT_N = \\sigma_{\\chi N} / T_{r,N}^{\\mathrm{max}}$, and similarly obtain the resulting XENON1T limits on $\\sigma_\\chi^{\\mathrm{SI}}$. This is plotted in Fig. \\ref{fig:limits} as a function of the dark matter mass for a fixed mediator mass and branching ratio values (\\textit{top}), and as a function of the meson branching ratio into dark matter for a fixed mediator and dark matter mass (\\textit{bottom}). The 90\\% CL limits on inelastic cosmic ray dark matter from $\\pi^0$ and $\\eta$ decays are shown in green and red, respectively. As mentioned previously, the dark matter flux is relatively insensitive to their masses when these are light enough to be produced on-shell. We note that despite the rate of neutral pion production being an order of magnitude larger than for $\\eta$ mesons, the branching ratio of pions is experimentally bounded to be at most $\\sim 10^{-6}$~\\cite{Tanabashi:2018oca}. The projected limits for the future LZ experiment~\\cite{Akerib:2018lyp} are shown as dashed lines; we see that they improve on the cross-section sensitivity by almost two orders of magnitude. The corresponding limits from the irreducible flux of up-scattered dark matter for $m_\\chi = 1$ MeV is given by the orange band and is independent of branching ratio. However, there is a (model-dependent) relation between the two---a dark matter coupling to nucleons will generically induce meson decay into dark matter, if kinematically allowed.\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=0.6 \\textwidth]{hadrophilic_no_title.pdf}\n\\end{center}\n\\caption{90\\% CL limits from inelastic cosmic ray dark matter flux from $\\eta$ decays in red, for a hadrophilic scalar mediator of mass $m_S$ with up-quark coupling $g_u$, setting $g_\\chi=1, m_\\chi = m_S/3$. The solid line denotes current limits from XENON1T~\\cite{Aprile:2018dbl}; the dashed line are future projections for the LZ experiment~\\cite{Akerib:2018lyp}. Current MiniBooNE limits from Ref.~\\cite{Aguilar-Arevalo:2018wea} are shown in grey.\n\\label{fig:hadrophilic}}\n\\end{figure}\n\nNext, we consider the hadrophilic scalar mediator model of Ref.~\\cite{Batell:2018fqo}. The singlet scalar $S$ couples to a Dirac fermion dark matter $\\chi$ and to the up quark through the Lagrangian terms\n%\n\\begin{align}\n\\mathcal{L} \\supset -g_\\chi S\\bar{\\chi}_L \\chi_R - g_u S \\bar{u}_L u_R + \\text{h.c.} \\, .\n\\end{align}\n%\nThe couplings to other flavours are assumed to be sub-dominant, so that we are left with four free parameters characterising the simplified model: $m_S$, $m_\\chi$, $g_u$, and $g_\\chi$. The branching ratio of $\\eta$ mesons decaying into dark matter is given by \n%\n\\begin{equation}\nBR(\\eta \\to \\pi^0 S) = \\frac{C^2 g_u^2 B^2}{16\\pi m_\\eta \\Gamma_\\eta} \\lambda^{1/2}\\left(1, \\frac{m_S^2}{m_\\eta^2}, \\frac{m_\\pi^2}{m_\\eta^2}\\right) \\, ,\n\\end{equation}\n%\nwhere $B \\simeq m_\\pi^2/(m_u+m_d)$, $C \\equiv \\sqrt{1/3} \\cos\\theta^\\prime -\\sqrt{2/3} \\sin\\theta^\\prime$ with $\\theta^\\prime \\simeq -20^\\circ$ and $\\lambda(a,b,c) = a^2 + b^2 + c^2 -2ab - 2bc - 2ac$. We assume here that $BR(S \\to \\chi \\chi) = 1$. For the differential $\\chi$-nucleus cross-section involving a scalar mediator we have \n%\n\\begin{align}\n\\frac{d\\sigma_{\\chi N}}{dT_N} &= \\frac{\\left(Z y_{Spp} + (A-Z) y_{Snn}\\right)^2 g_\\chi^2}{8\\pi} \\nonumber \\\\\n& \\times \\frac{(2m_N + T_N) (2 m_\\chi^2 + m_N T_N)}{(T_\\chi^2 + 2m_\\chi T_\\chi)(2m_N T_N + m_S^2)^2} F_H^2(\\sqrt{2 m_N T_N}) \\, ,\n\\end{align}\n%\nwhere $Z$ ($A-Z$) are the number of protons (neutrons), $y_{Spp} = 0.014 \\cdot g_u m_p/m_u$, $y_{Snn} = 0.012 \\cdot g_u m_n/m_u$, and $F_H$ is the Helm form factor~\\cite{Duda:2006uk}. Computing the rate as described above, we obtain the 90\\% CL limits shown in Fig. \\ref{fig:hadrophilic} in red on the $g_u$ vs $m_S$ plane, for $g_\\chi = 1, m_\\chi = m_S/3$. The Earth suppresses the flux significantly only for values of $g_u$ greater than displayed. The MiniBooNE limits from Ref.~\\cite{Batell:2018fqo} are shown in grey. Note that for $g_\\chi=1$ the constraints from the E787/E949 experiment are stronger than the MiniBooNE and XENON1T limits~\\cite{Batell:2018fqo}; however, they are set by invisible Kaon decays and are independent of $g_\\chi$, whereas direct detection constraints from $\\eta$ decay sources will grow quadratically with the dark matter coupling.\n\n\\section{Summary and Conclusions}\n\nAs the search for dark matter broadens, it is becoming increasingly important to maximise every resource that we have, both technological and astrophysical. In this respect cosmic rays provide a valuable tool. It has long been appreciated that cosmic rays are a natural accelerator for probing high energies, or as a background to indirect signals of dark matter decay; here we studied the potential of cosmic rays as a {\\it source} of dark matter for direct detection. This opens up the potential of extending the sensitivity of various experiments to explore complementary parameter space, as we have illustrated for the case of XENON1T. It is remarkable that in this example the resulting limits are comparable to dedicated beam dump experiments such as MiniBooNE. These limits will improve in the future with the LZ experiment, by about two orders of magnitude. In forthcoming work we also plan to study the sensitivity of neutrino detectors, as well as cosmic ray production of long-lived hidden sectors that can decay back to Standard Model particles.", "meta": {"hexsha": "0e8df688cb61cdfc70ce03f1bfa4bb4de1443607", "size": 16559, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Report/cosmicrays.tex", "max_stars_repo_name": "james-alvey-42/TransferReport", "max_stars_repo_head_hexsha": "e7acd36cf7bc0a06b2250aba43a839a963f8196a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Report/cosmicrays.tex", "max_issues_repo_name": "james-alvey-42/TransferReport", "max_issues_repo_head_hexsha": "e7acd36cf7bc0a06b2250aba43a839a963f8196a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Report/cosmicrays.tex", "max_forks_repo_name": "james-alvey-42/TransferReport", "max_forks_repo_head_hexsha": "e7acd36cf7bc0a06b2250aba43a839a963f8196a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 117.4397163121, "max_line_length": 1561, "alphanum_fraction": 0.7436439399, "num_tokens": 4932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.33524264874042736}}
{"text": "\\section{Introduction}\n\nThe parareal algorithm was originally proposed by Lions, Maday, and Turinici\n\\cite{original} as a numerical method to solve ordinary differential equations\nthat was parallel capable over the time domain. Here we intend to given a\noverview of the method, and it's properties. In section 2 we describe the\nparareal iteration, which later in 3 we discuss how to implement efficiently\nusing the parallel library OpenMP. Then in 4 we discuss the parallel efficiency\nof this implementation, and measure the scalability of it in a high performance\ncomputing context. Then in 5 and 6 we examine the analytic properties of the\nmethod, deriving stability criteria and measuring and deriving theoretical\nconvergence rates.\n", "meta": {"hexsha": "8bbaf13c1f8e304abcddce98eece21bd8b0b8e0d", "size": 736, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Report/TeXsrc/src/introduction.tex", "max_stars_repo_name": "abhijit-c/Parareal", "max_stars_repo_head_hexsha": "e64c8ae44577da7e92720aa12b12f28acb3fc473", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-08-01T19:31:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-08T13:54:15.000Z", "max_issues_repo_path": "Report/TeXsrc/src/introduction.tex", "max_issues_repo_name": "abhijit-c/Parareal", "max_issues_repo_head_hexsha": "e64c8ae44577da7e92720aa12b12f28acb3fc473", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Report/TeXsrc/src/introduction.tex", "max_forks_repo_name": "abhijit-c/Parareal", "max_forks_repo_head_hexsha": "e64c8ae44577da7e92720aa12b12f28acb3fc473", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-09-25T00:02:33.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-25T00:02:33.000Z", "avg_line_length": 56.6153846154, "max_line_length": 79, "alphanum_fraction": 0.8220108696, "num_tokens": 156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.3351205106307857}}
{"text": "\\input{../../style/preamble}\n\\input{../../latex-math/basic-math}\n\\input{../../latex-math/basic-ml}\n\\input{../../latex-math/ml-gp}\n\n\\newcommand{\\titlefigure}{figure/gp_pred/post_variance.pdf}\n\\newcommand{\\learninggoals}{\n  \\item Know how to derive the posterior process\n  \\item GPs are interpolating and spatial models\n  \\item Model noise via a nugget term\n}\n\n\\title{Introduction to Machine Learning}\n\\date{}\n\n\\begin{document}\n\n\\lecturechapter{Gaussian Process Prediction}\n\\lecture{Introduction to Machine Learning}\n\n\\begin{vbframe}{Gaussian Posterior Process And Prediction}\n\n\\vspace*{1cm}\n\n\\begin{itemize}\n  \\item So far, we have learned how to \\textbf{sample} from a GP prior.\n\\item However, most of the time, we are not interested in drawing random functions from the prior. Instead, we usually like to use the knowledge provided by the training data to predict values of $f$ at a new test point $\\xv_*$. \n\\item In what follows, we will investigate how to update the Gaussian process prior ($\\to$ posterior process) and how to make predictions.\n\\end{itemize}\n\n\\end{vbframe}\n\n\\section{Gaussian Posterior Process and Prediction}\n\n\n\\begin{vbframe}{Posterior process}\n\n% \\textbf{Noise-free Case:}\n% \n% In the noise-free case, $y^{(i)} = f(\\xi)$ ($\\epsi \\equiv 0$, no additive noise). The targets correspond to the true function values $\\yv = \\bm{f}$ (training observations) and $\\yv^* = \\bm{f}^*$ (test observations).\n% \n% \\lz \n\n\\begin{itemize}\n  \\item Let us now distinguish between observed training inputs, also denote by a design matrix $\\Xmat$, and the corresponding observed values\n  $$\n    \\bm{f} = \\left[f\\left(\\xi[1]\\right), ..., f\\left(\\xi[n]\\right)\\right]\n  $$ \n\nand one single \\textbf{unobserved test point} $\\xv_*$ with $f_* = f\\left(\\xv_*\\right).$\n\n\\item We now want to infer the distribution of $f_* | \\xv_*, \\bm{X}, \\bm{f}$.\n  $$\n    f_* = f\\left(\\xv_*\\right)\n  $$  \n  \\item Assuming a zero-mean GP prior $\\mathcal{GP}\\left(\\bm{0}, k(\\xv, \\xv^\\prime)\\right)$ we know\n\n$$\n\\begin{bmatrix}\n\\bm{f} \\\\\nf_*\n\\end{bmatrix} \\sim  \n\\mathcal{N}\\biggl(\\bm{0}, \\begin{bmatrix} \\Kmat & \\bm{k}_* \\\\ \\bm{k}_*^T & \\bm{k}_{**}\\end{bmatrix}\\biggr).\n$$\n\nHere, $\\Kmat = \\left(k\\left(\\xi, \\xv^{(j)}\\right)\\right)_{i,j}$, $\\bm{k}_* = \\left[k\\left(\\xv_*, \\xi[1]\\right), ..., k\\left(\\xv_*, \\xi[n]\\right)\\right]$ and $ \\bm{k}_{**}\\ = k(\\xv_*, \\xv_*)$. \n\n\\framebreak \n\n\\item Given that $\\bm{f}$ is observed, we can apply the general rule for condition $^{(*)}$ of Gaussian random variables and obtain the following formula: \n\n\\begin{eqnarray*}\nf_* ~|~ \\xv_*, \\Xmat, \\bm{f} \\sim \\mathcal{N}(\\bm{k}_{*}^{T}\\Kmat^{-1}\\bm{f}, \\bm{k}_{**} - \\bm{k}_*^T \\Kmat ^{-1}\\bm{k}_*).\n\\end{eqnarray*}\n\n% \\begin{eqnarray*}\n% \\bm{f}_* | \\Xmat_*, \\Xmat, \\bm{f} \\sim \\mathcal{N}(\\Kmat_{*}^{T}\\Kmat^{-1}\\bm{f}, \\Kmat_{**} - \\Kmat_*^T \\Kmat ^{-1}\\Kmat_*).\n% \\end{eqnarray*}\n\\item As the posterior is a Gaussian, the maximum a-posteriori estimate, i.e. the mode of the posterior distribution, is $\\bm{k}_{*}^{T}\\Kmat^{-1}\\bm{f}. $\n\\end{itemize}\n\n\\framebreak \n\n$^{(*)}$ General rule for condition of Gaussian random variables: \n\n\\lz \n\n  If the $m$-dimensional Gaussian vector $\\bm{z} \\sim \\mathcal{N}(\\mu, \\Sigma)$ can be partitioned with $\\bm{z} = \\left(\\bm{z}_1, \\bm{z}_2\\right)$ where $\\bm{z}_1$ is $m_1$-dimensional and $\\bm{z}_2$ is $m_2$-dimensional, and:\n$$\\left(\\mu_1, \\mu_2\\right), \\quad \\Sigma = \\begin{pmatrix} \\Sigma_{11} & \\Sigma_{12} \\\\ \\Sigma_{21} & \\Sigma_{22} \\end{pmatrix},$$\n\nthen the conditioned distribution of $\\bm{z}_2 ~|~ \\bm{z}_1 = \\bm{a}$ is a multivariate normal  \n\n$$\n  \\mathcal{N}\\left(\\mu_2 + \\Sigma_{21} \\Sigma_{11}^{-1}\\left(\\bm{a} - \\mu_1\\right), \\Sigma_{22} - \\Sigma_{21}\\Sigma_{11}^{-1}\\Sigma_{12} \\right)\n$$\n\n\\end{vbframe} \n\n\\begin{frame}{GP prediction: Two points}\n\nLet us visualize this by a simple example: \n\\begin{itemize}\n  \\item Assume we observed a single training point $\\xv = - 0.5$, and want to make a prediction at a test point $\\xv_* = 0.5$. \n  \\item Under a zero-mean GP with $k(\\xv, \\xv^\\prime) = \\exp(-\\frac{1}{2}\\|\\xv - \\xv^\\prime\\|^2)$, we compute the cov-matrix:\n  $$\n    \\begin{bmatrix} f \\\\ f_* \\end{bmatrix} \\sim \\mathcal{N}\\biggl(\\bm{0}, \\begin{bmatrix} 1 & 0.61 \\\\ 0.61 & 1\\end{bmatrix}\\biggr). \n  $$ \n  \\item Assume that we observe the point $\\fx = 1$. \n  \\item We compute the posterior distribution: \n  \\begin{eqnarray*}\n    f_* ~|~ \\xv_*, \\xv, f &\\sim& \\mathcal{N}(\\bm{k}_{*}^{T}\\Kmat^{-1}f, k_{**} - \\bm{k}_*^T \\Kmat^{-1}\\bm{k}_*) \\\\\n    &\\sim& \\mathcal{N}(0.61 \\cdot 1 \\cdot 1, 1 - 0.61 \\cdot 1 \\cdot 0.61) \\\\\n    &\\sim& \\mathcal{N}\\left(0.61, 0.6279\\right) \n  \\end{eqnarray*}\n  \\item The MAP-estimate for $\\xv_*$ is $f(\\xv_*) = 0.61$, and the uncertainty estimate is $0.6279$. \n  % what can we say about the function value at a new point $\\xv_* = -0.5$? \n  % \\item<+-> We compute the covariance function and have\n\n  % \\item<+-> After observing $\\fx = 1$ we want to predict a value for $f(\\xv_*)$. \n  % \\item<+-> We compute the posterior distribution conditioned on $\\fx = 1$\n  % \\begin{eqnarray*}\n\n  % \\end{eqnarray*}\n\\end{itemize}\n\n\\end{frame} \n\n\n\\begin{vbframe}{GP prediction: Two points}\n\n\\begin{footnotesize}\n  Shown is the bivariate normal density, and the respective marginals. \n\\end{footnotesize}\\vspace*{0.2cm}\n\n\\begin{figure}\n  \\includegraphics[width=0.8\\textwidth]{figure/gp_pred/1.pdf}\n\\end{figure}\n\n\n\\end{vbframe}\n\n\\begin{frame}{GP prediction: Two points}\n\n\\begin{footnotesize}\n  Assume we observed $\\fx = 1$ for the training point $\\xv = -0.5$.  \n\\end{footnotesize}\\vspace*{0.2cm}\n\n\\begin{figure}\n  \\includegraphics[width=0.8\\textwidth]{figure/gp_pred/2.pdf}\n\\end{figure}\n\n\\end{frame}\n\\begin{frame}{GP prediction: Two points}\n\n\\begin{footnotesize}\n  We condition the Gaussian on $\\fx = 1$.\n\\end{footnotesize}\\vspace*{0.2cm}\n\n\\begin{figure}\n  \\includegraphics[width=0.8\\textwidth]{figure/gp_pred/3.pdf}\n\\end{figure}\n\n\\end{frame}\n\n\n\\begin{frame}{GP prediction: Two points}\n\n\\begin{footnotesize}\n  We compute the posterior distribution of $f(\\xv_*)$ given that $\\fx = 1$. \n\\end{footnotesize}\\vspace*{0.2cm}\n\n\n\\begin{figure}\n  \\includegraphics[width=0.8\\textwidth]{figure/gp_pred/4.pdf}\n\\end{figure}\n\n\n\\end{frame}\n\\begin{frame}{GP prediction: Two points}\n\n\\begin{footnotesize}\n  A possible predictor for $f$ at $\\xv_*$ is the MAP of the posterior distribution.\n\\end{footnotesize}\\vspace*{0.2cm}\n\n\\begin{figure}\n  \\includegraphics[width=0.8\\textwidth]{figure/gp_pred/5.pdf}\n\\end{figure}\n\n\n\\end{frame} \n\n\\begin{frame}{GP prediction: Two points}\n\n\\begin{footnotesize}\n  We can do this for different values $\\xv_*$, and show the respective mean (grey line) and standard deviations (grey area is mean $\\pm 2 \\cdot $ posterior standard deviation). \n\\end{footnotesize}\\vspace*{0.2cm}\n\n\n\\begin{figure}\n  \\includegraphics[width=0.8\\textwidth]{figure/gp_pred/6.pdf}\n\\end{figure}\n\n\\end{frame}\n\n\\begin{vbframe}{Posterior Process}\n\n\\begin{itemize}\n  \\item We can generalize the formula for the posterior process for multiple unobserved test points: \n\n$$\n  \\bm{f}_* = \\left[f\\left(\\xi[1]_*\\right), ..., f\\left(\\xi[m]_*\\right)\\right]. \n$$\n  \\item Under a zero-mean Gaussian process, we have\n  $$\n    \\begin{bmatrix}\n    \\bm{f} \\\\\n    \\bm{f}_*\n    \\end{bmatrix} \\sim  \n    \\mathcal{N}\\biggl(\\bm{0}, \\begin{bmatrix} \\Kmat & \\Kmat_* \\\\ \\Kmat_*^T & \\Kmat_{**} \\end{bmatrix}\\biggr),\n  $$\n    with $\\Kmat_* = \\left(k\\left(\\xi, \\xv_*^{(j)}\\right)\\right)_{i,j}$, $\\Kmat_{**} = \\left(k\\left(\\xi[i]_*, \\xi[j]_*\\right)\\right)_{i,j}$.\n  \n  \\framebreak \n  \n  \\item Similar to the single test point situation, to get the posterior distribution, we exploit the general rule of conditioning for Gaussians:\n  \\begin{eqnarray*}\n    \\bm{f}_* ~|~ \\Xmat_*, \\Xmat, \\bm{f} \\sim \\mathcal{N}(\\Kmat_{*}^{T}\\Kmat^{-1}\\bm{f}, \\Kmat_{**} - \\Kmat_*^T \\Kmat ^{-1}\\Kmat_*).\n  \\end{eqnarray*}  \n  \\item This formula enables us to talk about correlations among different test points and sample functions from the posterior process. \n\\end{itemize}\n\n\\end{vbframe}\n\n\n\\section{Properties of a Gaussian Process}\n\n\\begin{vbframe}{GP as interpolator}\n\nThe \\enquote{prediction} for a training point $\\xi$ is the exact function value $\\fxi$\n\n\\vspace*{-0.8cm}\n\n\\begin{eqnarray*}\n\\bm{f} ~|~ \\Xmat, \\bm{f} \\sim \\mathcal{N}(\\Kmat\\Kmat^{-1}\\bm{f}, \\Kmat - \\Kmat^T \\Kmat^{-1} \\Kmat) = \\mathcal{N}(\\bm{f}, \\bm{0}).\n\\end{eqnarray*}\n\nThus, a Gaussian process is a function \\textbf{interpolator}.\n\n\\begin{center}\n\\includegraphics[width=0.8\\textwidth]{figure/gp_pred/gp_interpolator.pdf}\n\\end{center}\n% \\begin{footnotesize}\n% A the posterior process (black) after observing the training points (red) interpolates the training points. \n% \\end{footnotesize}\n\n\\end{vbframe}\n\n\n\\begin{vbframe}{GP as a spatial model}\n\n\\vspace*{-0.3cm}\n\n\\begin{itemize}\n  \\begin{footnotesize}\n  \\item The correlation among two outputs depends on distance of  the corresponding input points  $\\xv$ and $\\xv^\\prime$ (e.g. Gaussian covariance kernel $k(\\xv, \\xv^\\prime) = \\exp \\left(\\frac{- \\|\\xv - \\xv^\\prime\\|^2}{2 l^2}\\right)$ )\n  \\item Hence, close data points with high spatial similarity $k(\\xv, \\xv^\\prime)$ enter into more strongly correlated predictions: $\\bm{k}_*^\\top \\bm{K}^{-1} \\bm{f}$ ($\\bm{k}_* := \\left(k(\\xv, \\xv^{(1)}), ..., k(\\xv, \\xv^{(n)})\\right)$).\n  \\end{footnotesize}  \n\n\n\\begin{center}\n\\includegraphics[width=0.5\\textwidth]{figure/gp_pred/post_mean.pdf}\n\\end{center}\n\n\n\\begin{footnotesize}\nExample: Posterior mean of a GP that was fitted with the Gaussian covariance kernel with $l = 1$. \n\\end{footnotesize}\n\n\n\\framebreak \n\n\\item Posterior uncertainty increases if the new data points are far from the design points.\n\\item The uncertainty is minimal at the design points, since the posterior variance is zero at these points.\n\\end{itemize}\n\n\n\\begin{center}\n\\includegraphics[width=0.5\\textwidth]{figure/gp_pred/post_variance.pdf}\n\\end{center}\n\n\\begin{footnotesize}\nExample (continued): Posterior variance. \n\\end{footnotesize}\n\n\n\\end{vbframe}\n\n\n\\section{Noisy Gaussian Process}\n\n\\begin{vbframe}{Noisy Gaussian Process}\n\n\\begin{itemize}\n  \\item So far, we implicitly assumed that we had access to the true function value $\\fx$.\n  \\item For the squared exponential kernel, for example, we have\n  $$\n    \\cov\\left(f(\\xi), f(\\xi)\\right) = 1.\n  $$\n  \\item As a result, the posterior Gaussian process is an interpolator: \n  \\begin{center}\n    \\includegraphics[width=0.8\\textwidth]{figure/gp_pred/gp_interpolator.pdf}\n  \\end{center}\n\n\\framebreak \n\n  \\item In reality, however, this is often not the case. \n  \\item We often only have access to a noisy version of the true function value\n  $$\n    y = \\fx + \\eps, \\eps \\sim\\mathcal{N}\\left(0, \\sigma^2\\right).\n  $$\n  \\item Let us still assume that $\\fx$ is a Gaussian process.\n  \\item Then,\n  \\begin{footnotesize} \n  \\begin{eqnarray*}\n    &&\\cov(y^{(i)}, y^{(j)}) = \\cov\\left(f\\left(\\xi\\right) + \\epsilon^{(i)}, f\\left(\\xi[j]\\right) + \\epsilon^{(j)}\\right) \\\\\n    &=& \\cov\\left(f\\left(\\xi\\right), f\\left(\\xi[j]\\right)\\right) + 2 \\cdot \\cov\\left(f\\left(\\xi\\right), \\epsilon^{(j)}\\right) + \\cov\\left(\\epsilon^{(i)}, \\epsilon^{(j)}\\right) \n    \\\\ &=& k\\left(\\xi, \\xi[j]\\right) + \\sigma^2 \\delta_{ij}. \n  \\end{eqnarray*}\n  \\end{footnotesize}\n  \\item $\\sigma^2$ is called \\textbf{nugget}. \n\\end{itemize}\n\n\\framebreak \n\n\\begin{itemize}\n  \\item Let us now derive the predictive distribution for the case of noisy observations. \n  \\item The prior distribution of $y$, assuming that $f$ is modeled by a Gaussian process is then\n  $$\n    \\bm{y} = \\begin{pmatrix} \\yi[1] \\\\ \\yi[2] \\\\ \\vdots \\\\ \\yi[n] \\end{pmatrix} \\sim \\mathcal{N}\\left(\\bm{m}, \\bm{K} + \\sigma^2 \\bm{I}_n \\right),\n  $$\n  with \n  \\begin{eqnarray*}\n    \\textbf{m} &:=& \\left(m\\left(\\xi\\right)\\right)_{i}, \\quad\n    \\textbf{K} := \\left(k\\left(\\xi, \\xv^{(j)}\\right)\\right)_{i,j}. \n  \\end{eqnarray*}\n\n  \\framebreak \n  \n  \\item We distinguish again between \n  \\begin{itemize}\n    \\item observed training points $\\Xmat, \\yv$, and \n    \\item unobserved test inputs $\\Xmat_*$ with unobserved values $\\bm{f}_*$\n  \\end{itemize} \n  and get\n  $$\n  \\begin{bmatrix}\n  \\bm{y} \\\\\n  \\bm{f}_*\n  \\end{bmatrix} \\sim  \n    \\mathcal{N}\\biggl(\\bm{0}, \\begin{bmatrix} \\Kmat + \\sigma^2 \\bm{I}_n & \\Kmat_* \\\\ \\Kmat_*^T & \\Kmat_{**} \\end{bmatrix}\\biggr).\n  $$\n\n\\framebreak\n\n  \\item Similarly to the noise-free case, we condition according to the rule of conditioning for Gaussians to get the posterior distribution for the test outputs $\\bm{f}_*$ at $\\Xmat_*$: \n\n  \\begin{eqnarray*}\n    \\bm{f}_* ~|~ \\Xmat_*, \\Xmat, \\bm{y} \\sim \\mathcal{N}(\\bm{m}_{\\text{post}}, \\bm{K}_\\text{post}).\n\\end{eqnarray*}\n  with \n  \\begin{eqnarray*}\n    \\bm{m}_{\\text{post}} &=& \\Kmat_{*}^{T} \\left(\\Kmat+ \\sigma^2 \\cdot \\id\\right)^{-1}\\bm{y} \\\\\n    \\bm{K}_\\text{post} &=& \\Kmat_{**} - \\Kmat_*^T \\left(\\Kmat ^{-1} + \\sigma^2 \\cdot \\id\\right)\\Kmat_*,\n  \\end{eqnarray*}\n\\item This converts back to the noise-free formula if $\\sigma^2 = 0$.\n\n\\framebreak \n\n\\item The noisy Gaussian process is not an interpolator any more.\n\\item A larger nugget term leads to a wider ``band'' around the observed training points.\n\\item The nugget term is estimated during training.\n\n\n\\begin{center}\n    \\includegraphics[width=0.8\\textwidth]{figure/gp_pred/gp_regression.pdf}\n\\end{center}\n\\end{itemize}\n\n\\end{vbframe}\n\n\n\n\\section{Decision Theory for Gaussian Processes}\n\n\\begin{vbframe}{Risk Minimization for Gaussian Processes}\n\nIn machine learning, we learned about risk minimization. We usually choose a loss function and minimize the empirical risk  \n\n$$\n  \\riske(f) := \\sumin \\Lxyi\n$$\nas an approximation to the theoretical risk\n\n$$ \n  \\riskf := \\E_{xy} [\\Lxy] = \\int \\Lxy \\text{d}\\Pxy. \n$$\n\n\\begin{itemize}\n  \\item How does the theory of Gaussian processes fit into this theory? \n  \\item What if we want to make a prediction which is optimal w.r.t. a certain loss function? \n\\end{itemize}\n\n\\framebreak \n\n\\begin{itemize}\n  \\item The theory of Gaussian process gives us a posterior distribution \n  $$\n    p(y ~|~\\D)\n  $$\n  \\item If we now want to make a prediction at a test point $\\bm{x}_*$, we approximate the theoretical risk in a different way, by using the posterior distribution: \n  $$\n    \\mathcal{R}(y_* ~|~ \\bm{x}_*) \\approx \\int L(\\tilde y_*, y_*) p(\\tilde y_*~|~\\bm{x}_*, \\D)d\\tilde y_*. \n  $$\n  \\item The optimal prediciton w.r.t the loss function is then: \n  $$\n    \\hat y_* | \\bm{x}_* = \\argmin_{y_*} \\mathcal{R}(y_*~|~ \\bm{x}_*).\n  $$\n\\end{itemize}\n\n\n% In practical applications, we are often forced to make predictions. We need a point-like prediction that is \\enquote{optimal} in some sense. \n\n% \\lz\n\n% We define \\enquote{optimality} with respect to some loss function\n\n% $$\n% L(y_\\text{true}, y_\\text{guess}). \n% $$\n\n% \\vfill\n\n% \\begin{footnotesize}\n% Notice that we computed the predictive distribution without reference to the loss function. In non-Bayesian paradigms, the model is typically trained by minimizing the empirical risk (or loss). In contrast, in the Bayesian setting there is a clear separation between the likelihood function (used for training in addition to the prior) and the loss function.\n% \\end{footnotesize}\n\n% \\framebreak \n\n% As we do not know the true value $y_\\text{true}$ for our test input $\\bm{x}_*$, we minimize w.r.t. to the expected loss called \\textbf{risk} w.r.t. our model's opinion as to what the truth might be\n\n% $$\n% \\mathcal{R}(y_\\text{guess} | \\bm{x}_*) = \\int L(y_*, y_\\text{guess}) p(y_*|\\bm{x}_*, \\D)dy_*. \n% $$\n\n% Our best guess w.r.t. $L$ is then\n\n% $$\n% $$\n\n% For quadratic loss $L(y, y^\\prime) = (y - y^\\prime)^2$ this corresponds to the posterior mean. \n\n\\end{vbframe}\n\n\n\\endlecture\n\\end{document}\n", "meta": {"hexsha": "5367382b8ffbdb216c6523c172cc9d41a1866a02", "size": 15559, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "slides/gaussian-processes/slides-gp-prediction.tex", "max_stars_repo_name": "slds-lmu/lecture_i2ml", "max_stars_repo_head_hexsha": "b1cec2c8a8d0cff584e9f5d70c232c64d652f62c", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-10-31T11:24:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T12:31:51.000Z", "max_issues_repo_path": "slides/gaussian-processes/slides-gp-prediction.tex", "max_issues_repo_name": "slds-lmu/lecture_i2ml", "max_issues_repo_head_hexsha": "b1cec2c8a8d0cff584e9f5d70c232c64d652f62c", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 72, "max_issues_repo_issues_event_min_datetime": "2021-10-14T09:42:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T17:47:37.000Z", "max_forks_repo_path": "slides/gaussian-processes/slides-gp-prediction.tex", "max_forks_repo_name": "slds-lmu/lecture_i2ml", "max_forks_repo_head_hexsha": "b1cec2c8a8d0cff584e9f5d70c232c64d652f62c", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2021-10-15T09:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T12:31:53.000Z", "avg_line_length": 33.3169164882, "max_line_length": 360, "alphanum_fraction": 0.6656597468, "num_tokens": 5326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.3351205106307857}}
{"text": "\\documentclass[a4paper]{article}\n\n\\usepackage[T1]{fontenc}\n\\usepackage[utf8]{inputenc}\n\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{amsthm}\n\\usepackage[mathcal]{euscript}\n\n\\usepackage{url}\n\n\\newcommand{\\Fcal}{\\mathcal{F}}\n\\newcommand{\\Lcal}{\\mathcal{L}}\n\\newcommand{\\Tcal}{\\mathcal{T}}\n\\newcommand{\\Bcal}{\\mathcal{B}}\n\n\\newcommand{\\real}{\\mathbb{R}}\n\\newcommand{\\cplx}{\\mathbb{C}}\n\n\\title{Condensed notes for \\url{probability.net}}\n\\author{Nazarov Ivan}\n\n\\date{\\today}\n\n\\begin{document}\n\n\\maketitle\n\n\n\\paragraph{tut 11} % (fold)\n\\label{par:tut_11}\n\nComplex measures form a normed $\\cplx$-vector space $M_1(\\Omega, \\Fcal)$ and their\ntotal variation is always a finite measure;\n%\n$L^1_\\cplx(\\mu) \\equiv L^1_\\cplx(|\\mu|)$;\n%\nthe norm is $\\|\\mu\\| = |\\mu|(\\Omega)$;\n%\nreal valued bounded linear functionals on complex measures give signed measures;\n%\ntheir real~/~imaginary total variation can be used to decompose the complex measure\ninto a $\\cplx$-linear combination;\n%\nreverse triangle inequality: there is $S \\subseteq \\{1,\\, \\ldots,\\,N\\}$ such that\n$\\sum_{i=1}^N |z_i| \\leq \\pi |\\sum_{i \\in S} z_i|$.\n\n% paragraph tut_11 (end)\n\n\n\\paragraph{tut 12} % (fold)\n\\label{par:tut_12}\n\nAbsolute continuity of measures has a $\\varepsilon - \\delta$ continuity set-theoretic\nequivalent;\n%\nif for a finite measure $\\mu$ and $f \\in L^1_\\cplx(\\Omega, \\Fcal, \\mu)$, we have\n$\\tfrac1{d\\mu(E)} \\int_E f d\\mu \\in S$ for $S$ closed in $\\cplx$, then $f \\in S$\n$\\mu$-as;\n%\nRadon-Nikodym derivative $h$ of a complex~/~signed~/~finite measure $\\nu$ on\n$(\\Omega, \\Fcal)$ wrt. $\\sigma$-finite measure $\\mu$ is an element of $L^1_\\cplx(\\mu)$\nand respects the co-domain of $\\nu$;\n%\nthe same holds for a pair of $\\sigma$-finite measures, but $h\\colon \\Omega \\to [0, +\\infty]$;\n%\nderivative of a complex measure wrt. its total variation exists and its modulus~/~absolute\nvalue is $1$ almost surely;\n%\nset convergence holds for complex measures (via DCT);\n%\nfor any measure $\\mu$ if $d\\nu = f d\\mu$ for some complex $\\mu$-integrable $f$, then\n$\\nu$ is a complex measure, $d|\\nu| = |f| d\\mu$ and for any bounded measurable $g$ or\n$g \\in L^1_\\cplx(\\nu)$ we have $\\int g d\\nu = \\int g f d\\mu$;\n%\nComplex Lebesgue integral is defined as $\\int f d\\mu = \\int f h d|\\mu|$,\n$d\\mu = h d|\\mu|$;\n%\nComplex Lebesgue is bilinear wrt. function and measure arguments;\n%\nordinary Lebesgue is also monotone wrt. measures and linear wrt. nonnegative finite\nlinear combinations of measures;\n%\nComplex integral can be decomposed into a linear combination of ordinary Lebesgue\nintegrals wrt. finite measures based on total-variation (unique for any given complex\nmeasure);\n%\nBasically all commons sense operations and manipulations with complex integrands\nand complex measures are legal.\n\n% paragraph tut_12 (end)\n\n\n\\paragraph{tut 13} % (fold)\n\\label{par:tut_13}\n\nSimple $\\cplx$-valued functions that are also in $L^p_\\cplx(\\Omega, \\Fcal, \\mu)$ are\ndense in $L^p_\\cplx(\\mu)$;\n%\nfor any finite measure $\\mu$ on metrizable space $(\\Omega, \\Tcal)$\n(metrizability -- to get open neighborhoods of closed sets) for any measurable\n$E \\in \\Bcal(\\Omega)$ and $\\varepsilon > 0$ there are $F$ -- closed and $U$ -- open,\n$F \\subseteq E \\subseteq U$ with $\\mu(U \\setminus F) \\leq \\varepsilon$;\n%\nbounded continuous functions $C_\\cplx^b(\\Omega, \\Tcal)$ on metrizable spaces\n(or T4 for Urhyson lemma) approximate measurable indicator functions;\n%\nbounded continuous functions on metrizable spaces (T4 not enough due to measure!)\nare dense in $L^p_\\cplx(\\Omega, \\Bcal(\\Omega), \\mu)$ for $\\mu$ finite measure and\n$p < +\\infty$;\n%\nPortmanteau lemma: complex measures on metrizable space coincide if their integrals\nare equal for all continuous bounded real-valued functions;\n%\nlocally finite borel measure: every point has an open neighborhood with finite measure;\n%\ncompact sets have finite measure for any locally finite measure;\n%\nmetrizable compact ($\\sigma$-compact) topological space is separable;\n%\nin a metrizable topological space separability is equivalent to a countable base;\n%\nin a topological space with a locally finite borel measure a subset of a base with finite\nmeasure is still a topological base;\n%\non a metrizable $\\sigma$-compact topological space any locally finite measure is\ninner and outer regular;\n%\nstrongly $\\sigma$-compact topological space is the same as $\\sigma$-compact and\nlocally compact;\n%\nin a metrizable locally compact space for any $K$ -- compact, $U$ -- open, $K \\subseteq U$,\nthere is a continuous function $\\phi$ with compact support ($[\\{\\phi \\neq 0\\}]$\n-- compact in $\\Omega$) such that $1_K \\leq \\phi \\leq 1_U$;\n%\non a metrizable strongly $\\sigma$-compact topological space continuous functions\nwith compact support are dense in $L^p_\\cplx(\\Omega, \\Bcal(\\Omega), \\mu)$.\n\nLocally compact -- every open neighborhood has a compact closure;\n%\n$\\sigma$-compact -- there exists an increasing family of compact sets that covers $\\Omega$;\n%\nstrongly $\\sigma$-compact -- there is an increasing sequence of open sets with compact\nclosure that covers $\\Omega$;\n\nfor $\n  H\\vert_X\n    = \\{A\\cap X\\colon A \\in H\\}\n$ we have $\n  T_X\n    = T(H) \\vert_X\n    = T(H \\vert_X)\n$;\n%\n$H$ is a topological base on $\\Omega$ if $H$ cover $\\Omega$ and $x \\in U \\cap V$ implies $\n  \\exists W \\in H\n  \\,\\colon\\, x \\in W \\subseteq U \\cap V\n$;\n%\n$\n\\mathcal{T}(H)\n  = \\{\n    \\cup_{V \\in \\Gamma} V\n    \\colon \\Gamma \\subseteq H\n  \\}\n  = \\{\n    U \\subseteq \\Omega\n    \\colon \\forall x\\in U\\, \\exists W\\in H\n    \\colon x \\in W \\subseteq U\n  \\}\n$.\n\n% paragraph tut_13 (end)\n\n\n\\paragraph{tut 14} % (fold)\n\\label{par:tut_14}\n\nTotal variation (tv) of a $b\\colon \\real^+ \\to \\cplx$ map is non-decreasing, preserves\nright~/~left continuity if any, and\n$|b|(t) - |b|(s) = \\sup_{t_i \\in [s, t]} \\sum_i |b(t_i) - b(t_{i-1})|$;\n%\ntv of a nonnegative non-decreasing map is the map itself;\n%\ntv of a map is sub-additive and preserves order;\n%\nnondecreasing nonnegative $\\real$-valued maps (of finite variation) make Stieltjes\nmeasures, complex maps of bounded variation --- complex Stieltjes measures,\n$db((s,t]) = b(t) - b(s)$, $db(\\{0\\}) = b(0)$;\n%\ntv of a complex Stieltjes measure is the Stieltjes measure of the tv, i.e. $|db| = d|b|$;\n%\ntotal variations can be used to linearly decompose maps of finite variation;\n%\nfor measures on $\\real^+$ to be ordered it is sufficient for them to be ordered on\nhalf-intervals and at zero;\n%\ntv of a right~/~left continuous map can be computed on partitions\n$t_k = \\tfrac{k t}{2^n}$, $k=0,\\, \\ldots,\\,2^n$;\n%\ncadlag complex maps are bounded on bounded sets: for some $M\\geq 0$\n$|b(t-) \\vee b(t)| \\leq M$ for all $t \\in [0, T]$.\n\n% paragraph tut_14 (end)\n\n\n\\paragraph{tut 15} % (fold)\n\\label{par:tut_15}\n\nStieltjes (local) $L^1$-space $L^1_\\cplx(b)$ ($L^{1,loc}_\\cplx(b)$) for right continuous\n({\\bf rc}) $b\\colon \\real^+ \\to \\cplx$ of finite variation is\n$L_\\cplx^1(\\real^+, \\Bcal(\\real^+), d|b|)$ ($L_\\cplx^1(d|b|^{[0,t]})$);\n%\nfor an {\\bf rc} nonnegative nondecreasing $a$ and $f \\in L^1_\\cplx(a)$ (or $f \\geq 0$ in\n$L^{1,loc}_\\real(a)$) we have $f.a(t) = \\int_0^t f da$ {\\bf rc} map of bounded (finite)\nvariation and $d(f.a) = f da$;\n%\nfor {\\bf rc} nonnegative nondecreasing $a$ and $f \\in L^1_\\cplx(a)$ we have\n$|f.a| = |f|.a$ with $\\Delta f.a = f\\Delta a$, $\\Delta a = a(t) - a(t-)$;\n%\nfor $a\\colon \\real^+ \\to \\real^+$ {\\bf rc} nonnegative nondecreasing and\n$b\\colon \\real^+ \\to \\cplx$ {\\bf rc} of finite variation there is $f \\in L^1_\\cplx(a)$\n$da$-as unique such that $b = f.a$ and $f$ preserves the co-domain of $b$;\n%\nfor $b\\colon \\real^+ \\to \\cplx$ {\\bf rc} of finite variation there exists\n$h \\in L^{1,loc}_\\cplx(b)$ with $|h|=1$ and $b = h.|b|$ and for $f \\in L^1_\\cplx(b)$\nthe Stieltjes integral of $f$ is $f.b = (f h).|b|$, $|f.b| = |f|.|b|$ and\n$\\Delta f.b = f \\Delta b$;\n%\nfor $g \\in L^{1,loc}_\\cplx(b)$ we have $f.(g.b) = (fg).b$ for any\n$f \\in L^{1,loc}_\\cplx(g.b) \\Leftrightarrow fg \\in L^{1,loc}_\\cplx(b)$ or bounded;\n%\n$f.b$ is bilinear for $f \\in L^{1,loc}_\\cplx(b)$ and $b\\colon \\real^+ \\to \\cplx$\nis {\\bf rc} of finite variation;\n%\n$f.b = f.|b_1|^+ - f.|b_1|^- + i(f.|b_2|^+ - f.|b_2|^-)$ for $b_1 = \\Re(b)$, $b_2 = \\Im(b)$;\n%\nfor $a\\colon \\real^+ \\to \\real^+$ {\\bf rc} nonnegative and non decreasing the inverse\n$c_a(t) = \\inf\\{s \\geq 0 \\mid t < a(s) \\}$ is nonnegative, nondecreasing and right\ncontinuous, sort of generalized inverse, and $f.a(t) = ((f \\circ c_a).s)(a(t))$ for\n$f \\in L^{1,loc}_\\cplx(a)$ and also $a = c_{c_a}$;\n%\nnondecreasing maps are always measurable.\n\n% paragraph tut_15 (end)\n\n\n\\paragraph{tut 16} % (fold)\n\\label{par:tut_16}\n\nRecall:\n$\\limsup_{x\\to x_0} = \\inf_{U\\ni x_0} \\sup_{x\\in U}$,\n$A_n~\\text{i.o.} = \\cap_{n\\geq 0} \\cup_{k\\geq n} A_k$,\n$A_n~\\text{ev.} = \\cup_{n\\geq 0} \\cap_{k\\geq n} A_k$;\n%\nlsc functions ($\\{\\lambda < f\\}$ -- open in $\\Omega$) are closed under addition,\nscaling by nonnegative values, and arbitrary suprema;\n%\nlsc = - usc;\n%\n$1_U$, $U$ open, is lsc;\n%\n$1_F$, $F$ -- closed, is usc;\n%\nall usc~/~lsc maps are measurable wrt. Borel $\\sigma$-algebra;\n%\non a metrizable $\\sigma$-compact space with a locally finite measure $\\mu$ for any\n$f \\in L^1_\\real(\\Omega, \\Fcal, \\mu)$ and any $\\varepsilon > 0$ there are lsc $v$ and\nusc $u$ ($\\mu$-as having counterparts in $L^1_\\real(\\mu)$) such that $u \\leq f \\leq v$\nand $\\int (v - u) d\\mu \\leq \\varepsilon$ (Viteli-Caratheodory);\n%\na connected topological space has $\\emptyset$ and $\\Omega$ as the {\\bf only} closed\nand open;\n%\na space is connected iff whenever $\\Omega = A \\uplus B$ then either $A$ or $B$ is\n$\\emptyset$;\n%\nan interval is a subset $G$ of $\\real$ such that for all $a \\leq b \\in G$ we have\n$[a, b] \\subseteq G$;\n%\n$G$ is an intervals iff $G$ is either $(a, b]$, $(a, b)$, $[a, b)$, or $[a, b]$;\n%\na subset of $\\real$ is an interval iff it is connected;\n%\nimages of connected subsets via a continuous map are connected;\n%\nif $\\Omega$ is connected and $f$ continuous, then $[a, b] \\subseteq f(\\Omega)$ implies\nthat for any $c \\in [a, b]$ there is $z \\in \\Omega$ with $c = f(z)$;\n%\nif $a < b$, and $f$ is differentiable everywhere at $[a, b]$ with\n$\\int_a^b | f'(x)| dx < + \\infty$, then $f(b) - f(a) = \\int_a^b f'(s) ds$;\n%\non $(\\real^n, \\Bcal(\\real^n))$ for any $\\alpha > 0$ we have\n$dx({k_\\alpha \\in B})\n  = \\alpha^{-n} dx(B)\n  = \\lvert J_{k_\\alpha} \\rvert^{-1} dx(B)$;\n%\nfor complex measure $\\mu$ on $(\\real^n, \\Bcal(\\real^n))$ the maximal function\n$M\\mu(x) = \\sup_{\\varepsilon>0}\n  \\tfrac{|\\mu|(B(x,\\varepsilon))}\n        {dx(B(x,\\varepsilon))}$\nis nonnegative and lsc;\n%\n(constructive) for a collection $(B(x_i,\\varepsilon_i))_{i=1}^n$, $\\varepsilon_i > 0$\nthere exists an $S \\subseteq \\{1,\\,\\ldots,\\,n\\}$ such that\n$\\cup_{i=1}^n B(x_i,\\varepsilon_i))_{i=1}^n\n  \\subseteq \\cup_{i\\in S} B(x_i, 3\\varepsilon_i)$\nand $(B(x_i,\\varepsilon_i))_{i\\in S}$ are pairwise disjoint;\n%\nfor a complex measure $\\mu$ and any $\\lambda > 0$ we have\n$dx(\\{\\lambda < M\\mu\\}) \\leq \\tfrac{3^n}{\\lambda} \\|\\mu\\|$;\n%\nthe maximal function of $f \\in L^1_\\cplx(\\real^n, \\Bcal(\\real^n), dx)$ is\n$M f = M \\mu$ for $d\\mu = f dx$;\n%\nfor any $f \\in L^1_\\cplx(dx)$ we have\n$\\bigl\\{\n  \\lim_{\\varepsilon \\downarrow 0}\n    \\tfrac{\\int_{B(x, \\varepsilon)} |f(x) - f(y)| dy}\n          {dx(B(x, \\varepsilon)))}\n  = 0\\bigr\\}$ $dx$-a.s.\n\n% paragraph tut_16 (end)\n\n\n\\paragraph{tut 17} % (fold)\n\\label{par:tut_17}\n\nThe space of $n\\times n$ matrices $M_n(K)$, $K = \\real$ or $\\cplx$, is the same as\nthe space $M'_n(K)$ of all finite products of diagonal scaling ($H_\\alpha e_1 = \\alpha e_1$,\n$H_\\alpha e_i = e_i$, $\\alpha \\in K$), row swapping $P_{ij}$ ($P_{ij} e_i = e_j$,\n$P_{ij} e_j = e_i$, and $P_{ij} e_l = e_l$) and pivoting ($U e_1 = e_1 + e_2$, $U e_j = e_j$)\nmatrices;\n%\nif matrices with $1$ in the top left corner is in $M'_n(K)$, then $M_n(K)\\subseteq M'_n(K)$;\n%\nif matrices with $e_1$ in its first column is in $M'_n(K)$, then all matrices with\n$1$ in the top left corner are in $M'_n(K)$;\n%\nthe distribution of $X\\colon (\\Omega, \\Fcal) \\to (\\Omega', \\Fcal')$ under $\\mu$ (possibly\ncomplex), or the {\\bf image measure} of $\\mu$ under $X$, or the {\\bf pushforward} of\n$\\mu$, $X_\\sharp\\mu$, is $X(\\mu)(E) = \\mu^X(E) = \\mu(\\{X \\in E\\}) = \\mu(X^{-1}(E))$,\nand we have $Y(X(\\mu)) = Y(\\mu^X)$;\n%\n$|\\mu^X| \\leq |\\mu|^X$;\n%\na complex measure $\\mu$ on $(\\real^n, \\Bcal(\\real^n))$ is translation invariant iff\n$\\tau_\\alpha(\\mu) = \\mu$ for $\\tau_\\alpha(x) = \\alpha + x$;\n%\n$\\tau_\\alpha(dx) = dx$, $k_\\alpha(dx) = \\alpha^{-n} dx$ for $x\\mapsto k_\\alpha(x) =\n\\alpha x$, $a > 0$;\n%\nfor $X\\colon (\\Omega, \\Fcal) \\to (\\Omega', \\Fcal')$ we have $\\int_{\\Omega} (f \\circ X)\nd\\mu = \\int_{\\Omega'} f dX(\\mu)$ for measure $\\mu$ and measurable $f\\colon \\Omega' \\to\n[0, +\\infty]$ or $f\\in L^1_\\cplx(\\Omega', \\Fcal', X(\\mu))$ (iff $f\\circ X \\in\nL^1_\\cplx(\\Omega, \\Fcal, \\mu)$), or for a complex measure $\\mu$ and integrable\n$f$ (the STM);\n%\nthe \\textbf{s}tandard \\textbf{m}achine \\textbf{a}rgument: indicator $\\to$ simple\n(linearity) $\\to$ nonnegative (mct$\\uparrow$, or dct$\\to$+majorant) $\\to$ general\nintegrable, if the measurable sets are involved, then use Dynkin's lemma: if a\n$\\lambda$-system includes a $\\pi$-system, then it includes the $\\sigma$-algebra\nof the latter;\n%\nif $\\mu$ is a translation-invariant measure $(\\real^n, \\Bcal(\\real^n))$, then there\nis a unique $\\alpha \\geq 0$, such that $\\mu = \\alpha dx$ (due to translation invariance\nthe scaling in front of $\\mu$ becomes the Lebesgue measure);\n%\n$T\\colon \\real^n \\to \\real^n$ is a linear bijection iff it has a non-singular matrix\nrepresentation in, e.g., canonical bases in domain and image spaces;\n%\nthe linearity of $T$ makes the image measure $\\mu = T(dx)$ translation invariant in\n$\\real^n$ with $\\mu = \\Delta(T) dx$;\n%\nthe matrix of $T$ being composed of invertible simple matrices makes $\\Delta(T) \\neq\n0$ and $\\Delta(T_1 \\circ T_2) = \\Delta(T_1) \\Delta(T_2)$;\n%\nultimately $\\Delta(T) = \\lvert \\det T^{-1} \\rvert = \\lvert \\det T \\rvert^{-1}$ due\nto the determinant of a product being equal to the product of determinants;\n%\n$dx(T(B)) = \\lvert \\det T\\rvert dx(B)$;\n%\nany linear subspace $V$ of $\\real^n$ is closed and $dx(V) = 0$ when $\\dim V \\leq n-1$;\n\n% paragraph tut_17 (end)\n\n\n\\paragraph{tut 18} % (fold)\n\\label{par:tut_18}\n\nThe norm topology of the $K$-normed vector space is the metric topology induced by\nthe norm metric;\n%\nif $E$ and $F$ are $K$-normed spaces and $l\\colon E \\to F$ is a linear map, then\n$l$ is continuous iff $l$ is continuous at $0$, iff there is $M\\geq 0$ such that\n$\\|l(x)\\| \\leq M \\|x\\|$ for all $x\\in E$, iff\n$\\|l\\| = \\sup\\{\\|l(x)\\|\\colon x\\in E,\\, \\|x\\|=1\\} < +\\infty$;\n%\nthe norm $\\|l\\|$ of a linear map $l$ is $\\sup\\{\\|l(x)\\|\\colon x\\in E,\\, \\|x\\| \\leq 1\\}$,\n$\\sup\\{\\tfrac{\\|l(x)\\|}{\\|x\\|} \\colon x\\in E,\\, x\\neq 0\\}$, and\n$\\inf\\{M\\geq 0\\colon \\|l(x)\\| \\leq M \\|x\\|\\,\\,\\forall{x\\in E} \\}$;\n%\nfor all $x\\in E$ we have $\\|l(x)\\| \\leq \\|l\\| \\|x\\|$, and $(\\Lcal_K(E, F), \\|\\cdot\\|)$\nis a $K$-normed space.\n\nFor $E, F$ be $\\real$-normed spaces and an open $U\\subseteq E$, the map $\\phi\\colon E\\to F$\nis differentiable at $a\\in U$ iff there is $d\\phi(a) \\in \\Lcal_\\real(E, F)$ so that for any\n$\\varepsilon > 0$ there is $\\delta > 0$ such that for all $h\\in E$ with $\\|h\\| \\leq \\delta$\nand $a + h \\in U$ we have $\\|\\phi(a+h) - \\phi(a) - l(h) \\| \\leq \\varepsilon \\|h\\|$;\n%\nthe linear map $d\\phi(a)$ is unique, and the map $\\phi$ is differentiable on $U$ if\nit is differentiable at every $a\\in U$;\n%\n$\\phi\\colon U \\to F$ is $C^1$ if it is differentiable on $U$ and\n$d\\phi\\colon U \\to (\\Lcal_\\real(E, F), \\|\\cdot\\|)$ is continuous;\n%\nfor $\\real$-normed spaces $E, F, G$ with $U$ -- open in $E$, $V$ -- open in $F$, if\nmaps $\\phi\\colon U\\to F$ and $\\psi\\colon V\\to G$ are differentiable at $a\\in U$ and\n$\\phi(a)\\in V$ with $\\phi(U) \\subseteq V$, then the map $\\psi\\circ \\phi$ is differentiable\nat $a$ and $d(\\psi\\circ\\phi)(a) = d\\psi(\\phi(a)) \\circ d\\phi(a)$;\n%\nnorms on finite product spaces are topologically equivalent;\n%\nif norms $\\|\\cdot\\|$ and $N_E(\\cdot)$ induce the same topology, then the\n$id_E\\colon (E, \\|\\cdot\\|) \\to (E, N_E(\\cdot))$ is continuous, and the norms are equivalent:\nthere exist $m_E, M_E > 0$ such that $m_E\\|\\cdot\\| \\leq N_E(\\cdot) \\leq M_E \\|\\cdot\\|$;\n%\nif maps are differentiable at $a$ so are their linear combinations;\n%\nthe differential does not depend on the choice of norms in finite dimensional spaces;\n%\nif $\\phi\\colon U\\to F$ and $\\psi\\colon V\\to G$ are $C^1$, then so their composition is\n$C^1$ as well;\n%\nif $E$ is an $\\real$-normed space, $f\\colon [a, b] \\to E$ and $g\\colon [a, b] \\to \\real$\nare differentiable at every $(a, b)$ with $\\|f'(t)\\| \\leq g'(t)$, then\n$\\|f(b) - f(a)\\| \\leq g(b) - g(b)$;\n%\n$\\Rightarrow$ if $\\phi\\subseteq \\real^n \\to E$, $\\real$-normed, is differentiable at\n$a\\in U$ then all $\\tfrac{\\partial \\phi}{\\partial x_i}(a)$ exist at $a$, furthermore\n$d\\phi(a)(h) = \\sum_i \\tfrac{\\partial \\phi}{\\partial x_i}(a) h_i$;\n%\nif $d\\phi$ exists on $U$ and is continuous at $a$, then\n$\\tfrac{\\partial \\phi}{\\partial x_i}(\\cdot)$ are continuous at $a$;\n%\n$\\Leftarrow$ if $\\phi$ has all $\\tfrac{\\partial \\phi}{\\partial x_i}(\\cdot)$ on $U$ and\nthey are continuous at $a\\in U$, then $\\phi$ is differentiable at $a$ (only existence!);\n%\nif $\\tfrac{\\partial \\phi}{\\partial x_i}(\\cdot)$ are continuous on $U$ then so is $d\\phi$\non $U$;\n%\nfinally $\\phi\\colon U\\to E$ is $C^1$ on $U$ iff each\n$a\\to \\tfrac{\\partial \\phi}{\\partial x_i}(a)$ is $U$-$E$ continuous;\n%\n$l\\in \\Lcal(E, F)$ is $C^1$ and $d(l\\big\\vert_U)(a) = l$ for any $a\\in U$ -- open in $E$;\n%\n$\\phi\\colon U \\to F = \\prod_{i=1}^p F_p$ is differentiable at $a$ iff each\n$\\phi_i\\colon U\\to F_i$ is, $\\phi$ is $C^1$ on $U$ iff each $\\phi_i$ is $C_1$ on $U$,\nand $d\\phi(a) = (d\\phi_i(a))_{i=1}^n \\in \\Lcal(E, F)$;\n%\nif $\\phi\\colon U \\to \\real^n$ then\n$d\\phi(a) = (\\tfrac{\\phi_c}{\\partial x_r})_{r,c}^{n,n} \\in \\real^{n\\times n}$;\n%\nthe Jacobian of $\\phi$ is $J(\\phi)(a) = \\det d\\phi(a)$ --- the determinant of the\npartial derivative matrix.\n\nFor $\\Omega$ and $\\Omega'$ open in $\\real^n$ a bijection $\\phi\\colon \\Omega \\to \\Omega'$\nis a $C^1$-diffeomorphism between $\\Omega$ and $\\Omega'$ iff $\\phi\\colon \\Omega \\to \\real^n$\nand $\\phi^{-1}\\colon \\Omega' \\to \\real^n$ are both $C^1$;\n%\nif $\\phi$ is a $C^1$-diffeomorphism ($\\psi = \\phi^{-1}$) then\n$d\\phi(\\psi(x)) \\circ d\\psi(x) = id_{\\real^n}$ and\n$d\\psi(\\phi(x)) \\circ d\\phi(x) = id_{\\real^n}$ and\n$J(\\phi) = \\tfrac1{J(\\psi) \\circ \\phi} \\neq 0$;\n%\nif $d\\phi(a) = id_{\\real^n}$, then for all $x\\in \\Omega'$\n$\\lim_{\\varepsilon\\downarrow 0}\n  \\tfrac{\\phi(dx\\big\\vert_{\\Omega})(B(x, \\varepsilon))}\n        {dx\\big\\vert_{\\Omega'}(B(x, \\varepsilon))} = 1$;\n%\nthe matrix $A = d\\phi(x)$ is non-singular, and $\\tilde{\\phi} = \\phi \\circ A$ is $C^1$\ndiffeomorphism between $\\Omega'' = A^{-1}(\\Omega)$ and $\\Omega'$ with\n$\\tilde{\\psi} = A^{-1} \\circ \\psi$ and\n$d\\tilde{\\phi}(x) = id_{\\real^n} \\in \\Lcal(\\real^n, \\real^n)$;\n%\nhence\n$\\lim_{\\varepsilon\\downarrow 0}\n  \\tfrac{\\phi(dx\\big\\vert_{\\Omega})(B(x, \\varepsilon))}\n        {dx\\big\\vert_{\\Omega'}(B(x, \\varepsilon))}\n  = \\lvert \\det J(\\psi)(x) \\rvert$ for all $x\\in \\Omega'$;\n%\nfinally $\\phi(dx\\big\\vert_{\\Omega}) \\ll dx\\big\\vert_{\\Omega'}$ for a $C^1$-diffeomorphism\n$\\phi$ between $\\Omega$ and $\\Omega'$ and the Radon-Nikodym derivative is\n$a \\to \\lvert \\det J(\\psi)(a) \\rvert$;\n%\nthe Jacobian formula is\n$\\int_\\Omega (f\\circ \\phi) dx\\big\\vert_{\\Omega}\n  = \\int_{\\Omega'} f \\, \\phi(dx\\big\\vert_{\\Omega})\n  = \\int_{\\Omega'} f \\lvert J(\\phi^{-1})\\rvert dx\\big\\vert_{\\Omega'}$\nand\n$\\int_{\\Omega'} f dx\\big\\vert_{\\Omega'}\n  = \\int_{\\Omega} (f\\circ \\phi) \\, \\phi^{-1}(dx\\big\\vert_{\\Omega})\n  = \\int_{\\Omega} (f\\circ \\phi) \\lvert J(\\phi)\\rvert dx\\big\\vert_{\\Omega}$\n-- true for nonnegative $f$, $f\\in \\Lcal_\\cplx^1(\\Omega', \\Bcal(\\Omega'), dx)$\niff $(f \\circ \\phi) \\lvert J(\\phi) \\rvert \\in \\Lcal_\\cplx^1(\\Omega, \\Bcal(\\Omega), dx)$,\nand $f \\circ \\phi \\in \\Lcal_\\cplx^1(\\Omega, \\Bcal(\\Omega), dx)$\niff $f \\lvert J(\\phi^{-1}) \\rvert \\in \\Lcal_\\cplx^1(\\Omega', \\Bcal(\\Omega'), dx)$;\n%\n{\\bf pushforward}: $\\phi_\\sharp dx_\\Omega = \\lvert \\det J(\\phi^{-1}) \\rvert dx_{\\Omega'}$;\n%\nthe integral w.r.t. measure $\\mu$ of a {\\bf pullback} of $f\\colon \\Omega'\\to \\real$ by\n$\\phi\\colon \\Omega\\to\\Omega'$ is the integral of $f$ w.r.t the {\\bf pushforward}\nof $\\mu$ by $\\phi$: $\\int_\\Omega f\\circ \\phi d\\mu = \\int_{\\Omega'} f d\\phi_\\sharp\\mu$.\n% paragraph tut_18 (end)\n\n\n\\paragraph{tut 19} % (fold)\n\\label{par:tut_19}\n\n\n\n% paragraph tut_19 (end)\n\n\n\\paragraph{tut 20} % (fold)\n\\label{par:tut_20}\n\n\n\n% paragraph tut_20 (end)\n\\end{document}\n", "meta": {"hexsha": "e766038ed128e1038721a9cfb8fc323b9d480ccc", "size": 20472, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "scribbles/probnet-condensed-summary.tex", "max_stars_repo_name": "ivannz/general-scribbles", "max_stars_repo_head_hexsha": "48652c077fa008be5af0db8ab24e7a39f2d03fe1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-12-07T20:41:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-28T12:47:40.000Z", "max_issues_repo_path": "scribbles/probnet-condensed-summary.tex", "max_issues_repo_name": "ivannz/general-scribbles", "max_issues_repo_head_hexsha": "48652c077fa008be5af0db8ab24e7a39f2d03fe1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scribbles/probnet-condensed-summary.tex", "max_forks_repo_name": "ivannz/general-scribbles", "max_forks_repo_head_hexsha": "48652c077fa008be5af0db8ab24e7a39f2d03fe1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4090056285, "max_line_length": 93, "alphanum_fraction": 0.6415103556, "num_tokens": 7589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.33512050718409186}}
{"text": "\\chapter{Results} \\label{sec:results}\n\\epigraphhead[30]{\\epigraph{%\n\\textit{\"Even if rounding error vanished, numerical analysis would remain. Approximating numbers, the task of floating-point arithmetic, is indeed a rather small topic and may even be a tedious one.\"}}%\n{\\textsc{Lloyd N. Trefethen (1955)}}%\n}\n\n\\section{Planar maneuvers} \\label{sec:resplanar}\n\nFor the planar maneuvers, we will skip the semimajor-axis only case as explained in the previous chapter since we were not able to find a validation example, and only briefly comment the numerical results of the other two maneuvers. More details will be given for the more complicated combined maneuvers.\n\n\\subsection{Eccentricity change} \\label{sec:resecc}\n\nFor the two cases in consideration (the one described in the previous chapter and the one corresponding to a reverse change in eccentricity) we were able to recover the expected results from \\cite{pollard1997simplified} with a relative error of $10^{-4}$. This can be regarded as a nice result, given that the actual values were not present in the original paper and had to be computed or interpreted from the plots.\n\nThe same relative and absolute errors of $10^{-4}$ are obtained for the expected eccentricity after integrating the equations of motion, either with a positive or a negative change in eccentricity. This validates our intuition of reversing the direction of the thrust depending on the sign of $\\Delta e$.\n\n\\subsection{Argument of periapsis adjustment}\n\nFor the only validation example studied in this case, we were able to match the results in \\cite{ruggiero2011low} within a relative tolerance of $10^{-2}$. We observe a moderate accuracy in this case due to the fact that the time of flight given by the original paper is approximate and because of the intermediate computations needed to obtain the orbital parameters of the GTO orbit from the information given in the Soyuz User Manual. On the other hand, we did not find any validation example that did take into account the natural apsidal rotation of the orbit, so we openly question the applicability of this example. In any case, the function as it is implemented now, albeit not validated, accepts a precomputed value of $\\dot{\\omega}$.\n\nRegarding the integration of the trajectory we obtained better results and managed to approximate the final argument of periapsis with a relative error of $10^{-4}$.\n\n\\section{Non planar maneuvers} \\label{sec:resnonplanar}\n\n\\subsection{Combined semimajor axis and inclination change} \\label{sec:resedelbaum}\n\nFor all the evaluated cases we were able to recover the original results of \\cite{kechichian1997reformulation}, with a varying degree of accuracy. For both the expected time of flight $t_f$ and cost $\\Delta V$, a relative error of $10^{-5}$ was achieved for the first case, $10^{-3}$ for the second and $10^{-2}$ for the singular case. With the figures given in the original paper, we are unable to assess if the loss of accuracy is due to problems in our algorithm or simply the fact that not all decimal places are included in the text. For the sake of completeness, our results to machine precision are summarized in table~\\ref{tab:aincanares}.\n\nRegarding the numerical validation, after integrating the equations of motion for a time $t = t_f$ for the two non singular cases we recover the expected values for final semimajor axis $a$ and inclination $i$ with a relative error of $10^{-5}$ for the former and an absolute error of $10^{-3}$ for the latter. Notice that the relative error makes no sense if we are comparing to zero. The eccentricity does not experiment significant growth and stays equal to zero with an absolute tolerance of $10^{-2}$.\n\nFor completeness, we also include the plots of the time history for the semimajor axis, inclination and velocity for the two non singular cases (figures \\ref{fig:aincnumres28} and \\ref{fig:aincnumres90}), recording the evolution during the integration of the equations of motion. We notice how the semimajor axis significantly increases for the second case, and how most of the inclination change takes place at that moment.\n\n\\begin{figure}%[h]\n\\begin{subfigure}[b]{0.5\\textwidth}\n\\centering\n\\resizebox{1.0\\textwidth}{!}{\n\\input{figures/edelbaum/edelbaum_28_a.pgf}\n}\n\\end{subfigure}\n\\begin{subfigure}[b]{0.5\\textwidth}\n\\centering\n\\resizebox{1.0\\textwidth}{!}{\n\\input{figures/edelbaum/edelbaum_28_v_inc.pgf}\n}\n\\end{subfigure}\n\\caption{Evolution of the combined $a$ and $i$ transfer orbit for the case $i_0 = 28.5~\\text{deg}$}\n\\label{fig:aincnumres28}\n\\end{figure}\n\n\\begin{figure}%[h]\n\\begin{subfigure}[b]{0.5\\textwidth}\n\\centering\n\\resizebox{1.0\\textwidth}{!}{\n\\input{figures/edelbaum/edelbaum_90_a.pgf}\n}\n\\end{subfigure}\n\\begin{subfigure}[b]{0.5\\textwidth}\n\\centering\n\\resizebox{1.0\\textwidth}{!}{\n\\input{figures/edelbaum/edelbaum_90_v_inc.pgf}\n}\n\\end{subfigure}\n\\caption{Evolution of the combined $a$ and $i$ transfer orbit for the case $i_0 = 90~\\text{deg}$}\n\\label{fig:aincnumres90}\n\\end{figure}\n\nTo observe the differences between the numerical and the analytical solution, in figure~\\ref{fig:aincdiffinc90} we have plotted the difference between the analytical evolution of the inclination and the numerical solution. While this difference is small compared to the absolute value of the inclination, we notice and oscillatory behavior that is due to the differences within each revolution. In fact, we notice that the frequency of the oscillations decreases as the orbit gets larger, and then rises again.\n\n\\begin{figure}%[h]\n\\centering\n\\resizebox{1.0\\textwidth}{!}{\n\\input{figures/edelbaum/edelbaum_diff_inc_90.pgf}\n}\n\\caption{Difference between analytical and numerical value for the inclination in the combined $a$ and $i$ transfer orbit for the case $i_0 = 90~\\text{deg}$}\n\\label{fig:aincdiffinc90}\n\\end{figure}\n\n% Please add the following required packages to your document preamble:\n% \\usepackage{multirow}\n\\begin{table}%[b]\n\\centering\n\\begin{tabular}{|l|l|l|l|l|l|l|}\n\\hline\n\\multirow{2}{*}{} & \\multicolumn{3}{l|}{\\textbf{Time of flight $t_f$}}   & \\multicolumn{3}{l|}{\\textbf{Cost $\\Delta V$}}      \\\\ \\cline{2-7} \n                  & Expected    & Computed        & $\\varepsilon$       & Expected  & Computed        & $\\varepsilon$       \\\\ \\hline\n\\textbf{Case 1}   & $191.26295$ & $191.262282913$ & $0.35 \\cdot 10^{-5}$ & $5.78378$ & $5.7837714353$  & $0.15 \\cdot 10^{-5}$ \\\\ \\hline\n\\textbf{Case 2}   & $335.0$     & $335.033933749$ & $0.10 \\cdot 10^{-3}$ & $10.13$   & $10.1314261566$ & $0.14 \\cdot 10^{-3}$ \\\\ \\hline\n\\textbf{Case 3}   & $351.0$     & $351.211665646$ & $0.60 \\cdot 10^{-3}$ & $10.61$   & $10.6206407691$ & $0.10 \\cdot 10^{-2}$ \\\\ \\hline\n\\end{tabular}\n\\caption{Analytical results of the combined semimajor axis and inclination change.}\n\\label{tab:aincanares}\n\\end{table}\n\n\\subsection{Combined eccentricity and inclination change}\n\nFor each of the data points extracted from the plots in \\cite{pollard2000simplified}, we were able to recover the expected values of yaw angle $\\beta$ and cost $\\Delta V$ with a relative error of $10^{-2}$. This case is even more challenging since the precision of the extracted data is limited by the resolution of the plots, even with the help of an automated software. Again, for improving the accuracy more numerical test cases would be needed.\n\nThe results of the integration of the third case ($e_0 = 0.4, i_f = 20.0~\\text{deg}$) display similar accuracy: the expected final eccentricity and inclination are recovered with a relative error of $10^{-2}$ and $10^{-1}$ respectively. These tolerances are the worst for all the guidance laws in study, although still acceptable. The reverse change in eccentricity has been studied as well to test the algorithm against an initial circular orbit, yielding the same results.\n\nWe reproduce here the charts that can be found in \\cite{pollard2000simplified} using our own formulas, where it can be seen that the general trend of the plots is respected (figure~\\ref{fig:eccincnumcharts}). \n\n\\begin{figure}%[h]\n\\begin{subfigure}[b]{0.5\\textwidth}\n\\centering\n\\resizebox{1.0\\textwidth}{!}{\n\\input{figures/combined_ei/chart_beta.pgf}\n}\n\\end{subfigure}\n\\begin{subfigure}[b]{0.5\\textwidth}\n\\centering\n\\resizebox{1.0\\textwidth}{!}{\n\\input{figures/combined_ei/chart_dV.pgf}\n}\n\\end{subfigure}\n\\caption{Charts of yaw angle and velocity requirements in terms of inclination and eccentricity as found in  \\cite{pollard2000simplified}.}\n\\label{fig:eccincnumcharts}\n\\end{figure}\n\nOn the other hand, we also represent the evolution of the eccentricity during the integration of the equations of motion versus the theoretical trend, given by:\n\n\\[\ne = \\sin{\\left( \\pm \\frac{3}{2} f \\cos{|\\beta|} \\sqrt{\\frac{a}{\\mu}} t + \\arcsin{e_0} \\right)}\n\\]\n\n\\begin{figure}[b]\n\\centering\n\\resizebox{0.8\\textwidth}{!}{\n\\input{figures/combined_ei/eccentricity.pgf}\n}\n\\caption{Evolution of the eccentricity in the combined $e$ and $i$ transfer orbit.}\n\\label{fig:eccincecc}\n\\end{figure}\n\nThe discrepancy in the final part of the transfer corresponds with the numerical tolerance achieved for the integration.\n", "meta": {"hexsha": "51895c0c5cfc2b6083697a0bd883124d13a590ed", "size": 9090, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/chapters/03_results.tex", "max_stars_repo_name": "Juanlu001/pfc-uc3m", "max_stars_repo_head_hexsha": "c2c2c3e55d78672a26dcac9f56a15ff9c61d925a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2017-02-12T17:56:00.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-08T10:59:11.000Z", "max_issues_repo_path": "report/chapters/03_results.tex", "max_issues_repo_name": "astrojuanlu/pfc-uc3m", "max_issues_repo_head_hexsha": "c2c2c3e55d78672a26dcac9f56a15ff9c61d925a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-11-05T15:37:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-05T15:41:33.000Z", "max_forks_repo_path": "report/chapters/03_results.tex", "max_forks_repo_name": "Juanlu001/pfc-uc3m", "max_forks_repo_head_hexsha": "c2c2c3e55d78672a26dcac9f56a15ff9c61d925a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-04-10T09:35:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-18T18:55:38.000Z", "avg_line_length": 67.3333333333, "max_line_length": 743, "alphanum_fraction": 0.7588558856, "num_tokens": 2474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.33512050373739805}}
{"text": "\\documentclass[11pt,fancychapters]{article}\n\\usepackage[a4paper, total={6in, 8in}]{geometry}\n\\usepackage{cite}\n\\usepackage{color}\n\\usepackage{xcolor}\n\\usepackage{empheq}\n\\usepackage{setspace}\n\\usepackage{hyperref}\n\\usepackage{minted}\n\\usepackage{acro}\n\\usepackage{amsmath}\n\\usepackage{amsthm}\n\\usepackage{amssymb}\n\\usepackage{multirow}\n\\usepackage{graphicx}\n\\usepackage{geometry}\n\\usepackage{subcaption}\n\\usepackage{cancel}\n\\usepackage[utf8]{inputenc}\n\\usepackage[english]{babel}\n\\usepackage{tcolorbox}\n\\usepackage{hyperref}\n\\usepackage{cleveref}\n\\usepackage{parskip}\n\\usepackage{algorithm} \n\\usepackage{algpseudocode} \n\\usepackage{pgfplots}\n \\geometry{\n a4paper,\n total={170mm,257mm},\n left=20mm,\n top=20mm,\n }\n\\pgfplotsset{width=8cm,compat=1.9}\n\\newcommand{\\dbar}{{d\\mkern-7mu\\mathchar'26\\mkern-2mu}}\n\\newcommand{\\boxedeq}[2]{\\begin{empheq}[box={\\fboxsep=6pt\\fbox}]{align}\\label{#1}#2\\end{empheq}}\n\\def\\*#1{\\mathbf{#1}}\n\\def\\ab{ab}\n\\usepackage{tikz}\n\\usetikzlibrary{calc,trees,positioning,arrows,chains,shapes.geometric,%\n    decorations.pathreplacing,decorations.pathmorphing,shapes,%\n    matrix,shapes.symbols}\n\\geometry{top=1.3in,bottom=1.3in}\n\n\\begin{document}\n\\centerline{\\huge{2D Project --- 50.004 Introduction to Algorithms}}\n\n\\begin{table}[ht]\n\\centering\n\\footnotesize\n \\begin{tabular}{c c c c c c} \nV S Ragul Balaji&James Raphael Tiovalen&Anirudh Shrinivason&Jia Shuyi&Gerald Hoo&Shoham Chakraborty\n \\end{tabular}\n\\end{table}\n\n\\section{Part A --- Deterministic Graph-Based Algorithm}\n\\subsection{Overview of Algorithm}\n\nA solver for a 2-SAT problem can follow many methods. For a 2-SAT problem to be SATISFIABLE in Conjunctive Normal Form (CNF), every clause must be \\texttt{true}. Since there are only 2 literals in each clause in a 2-SAT problem, within a single clause, we notice that we can form two implications, thus converting it into an Implicative Normal Form (INF). This sets one of the literals within the clause to be \\texttt{false} and for the entire clause to be \\texttt{true}, we need the other literal to be \\texttt{true}. In other words, we are forbidding the four possible joint assignments of a pair of literals. This defines certain constraints between the variables, which can be propagated throughout the whole implication graph. Each pair of constraints can be considered to be an edge between the variables in an implication graph for the boolean satisfiability problem.\\newline\n\nTo create the implication graph, we first implement a directed graph using an adjacency list. In the \\texttt{Graph} class defined in the \\texttt{dfs/kosaraju.py} file, we create the adjacency list by defining the graph's vertices, as well as a function to add edges. Since each variable produces two literals (the variable itself and its negation), we create $2n$ vertices, where $n$ is the number of variables. These vertices are added as the keys of the dictionary $G$ defined in the \\texttt{Graph} class. The values for each key would be a list containing consecutive outgoing edges from the vertex defined in the key. This keeps the connection between each individual vertex to the other vertices.\n\n\\vspace{4mm}\n\n\\begin{figure}[h]\\label{fig}\n\\centering\n\\includegraphics[width=.9\\textwidth]{diagrams/example_cnf_solved.png}\n\\caption{Guided example of solving 2SAT by hand in polynomial time}\n\\label{fig:example_problem}\n\\end{figure}\n\n\\vspace{4mm}\n\nIn Figure~\\ref{fig:example_problem}, we demonstrate this process using an example. This example is also defined in the \\texttt{cnf/example.cnf} file. Steps 3 and 4 in Figure~\\ref{fig:example_problem} are defined in lines 110-111 in the \\texttt{kosaraju.py} file. Using the implication graph, we find the Strongly-Connected Components (SCCs) of the graph and group vertices that are along the same path using Kosaraju's Algorithm. We first create a stack and a depth-first search (DFS) is implemented to traverse through the graph. Adjacent vertices are pushed to the stack. The same procedure is executed on the inverse of the graph, where the direction of all of the edges is reversed. After that, while the stack is not empty, we pop each vertex from the stack. Using this algorithm, we can find all the SCCs of the graph.\\newline\n\nNext, we can check for contradiction in each of the SCC. If a variable and its corresponding negation is in the same SCC, the whole 2-SAT formula is deemed to be UNSATISFIABLE, as it is impossible to assign two literals to the same variable. This is because within a single SCC, you can traverse from any vertex to any other vertex. Otherwise, the formula is deemed as SATISFIABLE.\\newline\n\nIf the formula is SATISFIABLE, we can output a possible solution for the formula. We can do this by grouping the SCCs together and connect them using a directed acyclic graph. Using the graph in Figure~\\ref{fig:example_problem} as an example, going in topological order, assign $0$ to the first group of SCC (which is the left SCC in this specific case) and assign $1$ to the second group of SCC (the one highlighted by the red rectangle). We would then get the corresponding output of the variables by equating the literals in any SCC to the assigned value.\n\n\\subsection{Time Complexity Analysis}\n\nIn general, we know that 2-SAT is in P and is tractable due to the mechanism of forcing the other literal to be \\texttt{true} in a single clause by assigning a literal within that same clause as \\texttt{true}. When we pick an assignment, 3 cases could happen:\n\n\\begin{enumerate}\n    \\item We reach a contradiction. In this case, it means that there can only be a satisfying assignment if we use the other truth value for that specific variable. Thus, we can simplify the formula using this new assigned value for that variable and repeat the process.\n    \\item The ``forcing\" of the value assignment for a specific variable does not affect other variables and clauses. In this case, adopt these truth values, eliminate the clauses that they satisfy and continue the process.\n    \\item We find a satisfying assignment.\n\\end{enumerate}\n\nIn Cases 1 and 2, we have spent at most $O(n^2)$ time and have reduced the length of the formula by $\\geq 1$. Thus, in total, we have spent at most $O(n^3)$ time.\\newline\n\nIn fact, our specific implementation method of using a DFS traversal on an implication graph using Kosaraju's Algorithm would take even less time:\n\n\\begin{enumerate}\n    \\item To create the implication graph, we set up the vertices and edges in $O(V + E)$ time, where $V$ is the number of vertices and $E$ is the number of edges in the graph.\n    \\item We implement DFS to traverse through the implication graph using Kosaraju's Algorithm in $O(V + E)$ time.\n    \\item We set up the inverse/transpose implication graph in $O(V + E)$ time.\n    \\item We implement the DFS again through the inverse implication graph in $O(V + E)$ time.\n\\end{enumerate}\n\nThus, this reduction of the 2-SAT problem to finding SCCs implemented in our deterministic algorithm would cause the algorithm to take only linear time.\\newline\n\nMeanwhile, $k$-SAT problems for $k \\geq 3$ would be NP-complete (as shown by the Cook-Levin Theorem) and thus, the time taken would have non-polynomial asymptotics. This is because the size of the CNF formula is exponential in the size of the original boolean formula for $k \\geq 3$.\\newline\n\nA possible improvement that could be made would be to implement Tarjan's Algorithm to conduct the search for the Strongly-Connected Components. While both Kosaraju's Algorithm and Tarjan's Algorithm would take $O(V+E)$ time, Tarjan's Algorithm has a lower constant factor to the runtime since it would need to go through the whole graph and execute DFS only once (instead of two times for Kosaraju's Algorithm, once for the normal graph and another instance of the DFS traversal for the inverse graph).\n\n\\newpage\n\n\\section{Part B --- Randomised Algorithm}\n\\subsection{Overview of Algorithm}\n\\begin{algorithm}[H]\n\t\\caption*{\\textbf{function} RANDOM\\_WALK($\\mathbb{F}, L$)}\n\t// $\\mathbb{F}: \\textit{a list of clauses}$\\\\\n\t// $L: \\textit{a list of all variables used in } \\mathbb{F}$\n\t\\begin{algorithmic}[1]\n\t\\State Store all variables as keys in a dictionary $\\mathbb{D}$ with initial values \\textbf{false}\n\t\\For {$i \\gets 1 \\text{ to } 100\\times(L.\\textit{length})^2$}\n\t    \\State Using $\\mathbb{D}$, assign boolean values to $\\mathbb{F}$\n\t    \\State $\\mathbb{C}\\gets $ all invalid clauses in $\\mathbb{F}$\n\t    \\If {$\\mathbb{C}.length \\ne 0$}\n\t        \\State $V\\gets$ a random variable from a random clause in $\\mathbb{C}$\n\t        \\State $V\\gets \\neg V$\n\t        \\State Update $\\mathbb{D}$ with $V$\n\t   \\Else\n\t        \\State \\textbf{return} SATISFIABLE\n\t   \\EndIf\n\t\\EndFor\n\t\\State \\textbf{return} UNSATISFIABLE\n\t\\end{algorithmic} \n\\end{algorithm}\n\nFirst, we arbitrarily assign Boolean value \\texttt{false} to all $n$ variables. In each of the $100n^2$ steps, we randomly choose a variable from a randomly selected invalid clause (that is, the clause evaluates to \\texttt{false}) and negate its assignment. We then check if the resultant formula is satisfied or not. If no solution is found after $100n^2$ steps, we return UNSATISFIABLE. If at any point during the $100n^2$ steps the formula is satisfied, we return SATISFIABLE.\n\\subsection{Time Complexity Analysis}\nLet $X_i$ be the number of correct assignments at step $i$. Assuming worst-case initialization, all variables are assigned incorrectly, we have $X_0 = 0$. This forces $X_1 = 1$, since flipping any variable would give us a correct assignment.\\newline\n\nFor $1\\le i \\le n-1$, the probability for $X_i$ transiting to $X_{i+1}$ is at least $\\frac{1}{2}$ while that to $X_{i-1}$ is at most $\\frac{1}{2}$. This can be easily seen from the table below:\n\n\\begin{table}[H]\n\\centering\n\\begin{tabular}{|l|l|l|l|}\n\\hline\n\\multicolumn{2}{|l|}{Wrong Clause $A+B$}            & $A$           & $B$          \\\\ \\hline\n\\multicolumn{2}{|l|}{Actual Value}                  & T           & T          \\\\ \\hline\n\\multicolumn{2}{|l|}{Both Wrong Assignment}         & F           & F          \\\\ \\hline\n\\multicolumn{2}{|l|}{One Wrong Assignment}          & F           & T          \\\\ \\hline\n\\multirow{2}{*}{$P(X_i \\text{ to } X_{i+1})$} & Both Wrong & \\multicolumn{2}{l|}{1}   \\\\ \\cline{2-4} \n                                       & One Wrong  & \\multicolumn{2}{l|}{0.5} \\\\ \\hline\n\\multirow{2}{*}{$P(X_i \\text{ to } X_{i-1})$} & Both Wrong & \\multicolumn{2}{l|}{0}   \\\\ \\cline{2-4} \n                                       & One Wrong  & \\multicolumn{2}{l|}{0.5} \\\\ \\hline\n\\end{tabular}\n\\end{table}\nLet us suppose the worst case – that the probability $X_i$ goes up is $\\frac{1}{2}$, and down is $\\frac{1}{2}$. This process is similar to a random walk.\\newline\n\nLet $h_i$ be the expected number of steps to reach $n$ on our random walk when we start at step $i$. We have\n\\begin{equation}\\label{eqn2.1}\n    h_i = \\frac{h_{i-1}}{2} + \\frac{h_{i+1}}{2} + 1 \\quad \\Rightarrow \\quad h_i - h_{i+1} = h_{i-1} -h_i + 2.\n\\end{equation}\nUsing the base case $h_0 = h_1 + 1$, the next 2 steps are\n\\begin{align}\n    h_1 - h_2 &= h_0 - h_1 + 2 = h_1 + 1 - h_1 + 2 = 3,\\label{h1h2} \\\\\n    h_2 - h_3 &= h_1 - h_2 + 2 = 3 +2 = 5,\\label{h2h3}\n\\end{align}\nwhere Eqn.~(\\ref{h1h2}) is substituted into Eqn.~(\\ref{h2h3}). By careful observation, we formulate the following expression:\n\\begin{equation}\\label{mi}\n    h_i - h_{i+1} = 2i+1.\n\\end{equation}\nAs shown above, this expression holds for $i=1$. Assume the expression is \\texttt{true} for $h_k - h_{k+1} = 2k+1$ for some positive integer $k$, we want to prove that the expression holds for $i = k + 1$.\n\\begin{align*}\n    h_{k+1} - h_{k+2} &= h_k - h_{k+1} + 2 \\qquad \\text{By Eqn.~(\\ref{eqn2.1})}\\\\\n    &= 2k+1+2\\\\\n    &= 2(k+1) + 1.\n\\end{align*}\nThus, by mathematical induction, Eqn.~(\\ref{mi}) is true for all $k \\in \\mathbb{Z}^+$. Using Eqn.~(\\ref{mi}), we sum all the steps from $i = 0$ to $i = n$:\n\\begin{align*}\n    h_0 &= h_n + \\sum^{n-1}_{i=0}\\left(h_i - h_{i+1}\\right)\\\\\n    &= \\sum^{n-1}_{i=0}(2i+1)\\\\\n    &= n+2\\left(\\frac{n^2-n}{2}\\right)\\\\\n    &= n^2,\n\\end{align*}\nwhere $h_n = 0$.\\newline\n\nTherefore, the average time complexity of the randomised algorithm is $O(n^2)$. In other words, we will find a solution in $n^2$ steps \\textbf{on average}. If we decide to run the algorithm for $2n^2$ steps, the probability of not finding a solution is at most $\\frac{1}{2}$. Thus, if we run the algorithm for $100n^2$ steps (as it is in the pseudo-code), the probability of not finding a solution is $\\left(\\frac{1}{2}\\right)^{50} = 2^{-50}$.\n\n\n\\newpage\n\\section{Performance Comparison}\n\n\\begin{figure}[h]\n\\centering\n\\includegraphics[width=.95\\textwidth]{diagrams/test0.png}\n\\caption{Benchmarking script used to compare the speed of the two implementation in Part A and Part B. Kosaraju's Algorithm runs faster than the randomised algorithm as predicted by the algorithmic analysis. }\n\\end{figure}\n\n\\vspace{4mm}\n\nEven though the probability of not finding a solution is very small ($2^{-50}$ for $100n^2$ steps), the randomised algorithm is not a practical substitute for the deterministic one since it takes longer time than the deterministic algorithm. There is also some chance that a solution is not found and hence an incorrect conclusion/statement of the problem's satisfiability could be made. The randomised algorithm is also dependent on the size of the variables.\\newline\n\nHowever, we should not dismiss the usefulness of the idea of randomised local search entirely. We should be aware that the strategy of using randomised local search is useful to improve over naive brute-force search for NP-complete $k$-SAT problems, such as the $3$-SAT problem. In fact, for a 3-SAT problem, the naive brute-force method would take $O(2^n)$ time, while a version of the randomised local search with a clever twist (such as Sch\\\"{o}ning's stochastic local search algorithm) would take $O\\left(\\frac{4}{3}^n\\right)$ time, which is significantly better than $O(2^n)$.\n\n\\end{document}", "meta": {"hexsha": "56e8c7767dc4785e0c5d003bc97307b2ff649420", "size": 13967, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "sat-solver/50.004_report.tex", "max_stars_repo_name": "jamestiotio/DigiAlpha", "max_stars_repo_head_hexsha": "e5df3ccbaf55fe03713bae0ecdc179d40d309b83", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sat-solver/50.004_report.tex", "max_issues_repo_name": "jamestiotio/DigiAlpha", "max_issues_repo_head_hexsha": "e5df3ccbaf55fe03713bae0ecdc179d40d309b83", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sat-solver/50.004_report.tex", "max_forks_repo_name": "jamestiotio/DigiAlpha", "max_forks_repo_head_hexsha": "e5df3ccbaf55fe03713bae0ecdc179d40d309b83", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 69.835, "max_line_length": 882, "alphanum_fraction": 0.7282881077, "num_tokens": 4010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.6548947223065754, "lm_q1q2_score": 0.335120503737398}}
{"text": "\\documentclass{article}\n\\usepackage[left=6.3em,right=7em,top=7em]{geometry}\n\\usepackage{amsmath}\n\\usepackage{bcprules}\n\\usepackage{amssymb}\n\\usepackage{stmaryrd}\n\\usepackage{multicol}\n\\begin{document}\n\\section{source language $\\mathcal{T}$}\n\\begin{flalign*}\n    \\mathtt{n} ::=&\\quad n \\in \\mathcal{N} \\\\\n    \\mathtt{e} ::=&\\qquad \\mathtt{n} \\mid \\mathtt{true} \\mid \\mathtt{false} \\mid \\mathtt{()} \\mid \\mathtt{x} \\\\\n         &\\quad \\mid \\mathtt{e+e} \\mid \\mathtt{e-e} \\mid \\mathtt{e*e} \\mid \\mathtt{e/e}\\\\\n         &\\quad \\mid \\mathtt{e=e} \\mid \\mathtt{e<e} \\mid \\mathtt{e>=e} \\mid \\mathtt{not\\ e}\\\\\n         &\\quad \\mid \\mathtt{if}\\ \\mathtt{e}\\ \\mathtt{then}\\ \\mathtt{e}\\ \\mathtt{else}\\ \\mathtt{e}\\\\\n         &\\quad \\mid \\mathtt{let\\ x=e\\ in\\ e} \\mid \\mathtt{let\\ rec\\ x\\ x=e\\ in\\ e} \\mid \\mathtt{fun\\ x \\rightarrow e} \\mid \\mathtt{e\\ e}\n\\end{flalign*}\n\n\\section{Virtual Machine specificatoin}\n\\subsection{closure representation}\n\\[Q = \\left\\langle I, C, F, \\mathit{Um} \\right\\rangle\\]\n$I$ is instruction sequense, $C$ is constant table, $F$ is closure table\nand $\\mathit{Um}$ is just an information, to create upvalues, composed of index and \\textit{meta} index, which of the former represents current register value and the latter does the upvalue index.\n\n\\subsection{machine state}\n\\[S = \\left\\langle Q, \\mathtt{pc}, U, R \\right\\rangle\\]\n\\texttt{pc} is program counter which points nth instruction of $I$, $U$ is upvalues table and $R$ is register list.\n\n\\subsection{values}\n\\begin{flalign*}\n    \\mathtt{v} ::=\\quad \\mathtt{null} \\mid \\mathtt{()} \\mid \\mathtt{i} \\in \\mathcal{N} \\mid \\mathtt{true} \\mid \\mathtt{false} \\mid \\mathtt{clos}\\left(Q, U\\right)\n\\end{flalign*}\n\n\\subsection{Instructions}\n\\begin{minipage}{\\textwidth}\n    \\begin{multicols}{2}\n        \\begin{itemize}\n            \\item \\texttt{Load(a, kx)}\n\n                set \\texttt{C[kx]} to \\texttt{R[a]}\n            \\item \\texttt{SetBool(a, x, p)}\n\n                set boolean \\texttt{x > 0} to \\texttt{R[a]};\n                if \\texttt{p = 1} then \\texttt{pc++}\n            \\item \\texttt{Unit(a)}\n\n                set \\texttt{()} to \\texttt{R[a]}\n            \\item \\texttt{Clos(a, cx, p)}\n\n                create $U'$ = $U\\ @\\ \\left\\{u \\mid i_u \\in \\mathit{Um} \\wedge u = R[i_u]\\right\\}$\n                and set $\\left\\langle \\mathtt{F[cx]}, 0, U', R'\\right\\rangle$ with environment to \\texttt{R[a]}\n                if \\texttt{p=1} then the closure is recursive\n            \\item \\texttt{Upval(a, ux)}\n\n                set \\texttt{U[rx]} to \\texttt{R[a]}\n            \\item \\texttt{Add(a, b, c)}\n\n                set \\texttt{R[b] + R[c]} to \\texttt{R[a]}\n            \\item \\texttt{Sub(a, b, c)}\n\n                set \\texttt{R[b] - R[c]} to \\texttt{R[a]}\n            \\item \\texttt{Mul(a, b, c)}\n\n                set \\texttt{R[b] * R[c]} to \\texttt{R[a]}\n            \\item \\texttt{Div(a, b, c)}\n\n                set \\texttt{R[b] / R[c]} to \\texttt{R[a]}\n            \\item \\texttt{Eq(a, b)}\n\n                if \\texttt{R[a] == R[b]} then \\texttt{pc++}\n            \\item \\texttt{Lt(a, b)}\n\n                if \\texttt{R[a] < R[b]} then \\texttt{pc++}\n            \\item \\texttt{Ge(a, b)}\n\n                if \\texttt{R[a] >= R[b]} then \\texttt{pc++}\n        \\end{itemize}\n    \\end{multicols}\n\\end{minipage}\n\\begin{minipage}{\\textwidth}\n    \\begin{multicols}{2}\n        \\begin{itemize}\n            \\item \\texttt{Test(a, p)}\n\n                if \\texttt{p > 0 \\&\\& R[a] || p <= 0 \\&\\& !R[a]} then \\texttt{pc++}\n\n            \\item \\texttt{Jump(x)}\n\n                \\texttt{pc += x}\n            \\item \\texttt{Move(a, b)}\n\n                set \\texttt{R[b]} to \\texttt{R[a]}\n            \\item \\texttt{Call(a, b)}\n\n                call closure \\texttt{R[a]} with argument \\texttt{R[b]} and set return value to \\texttt{R[a]}\n            \\item \\texttt{Return(a)}\n\n                exit closure evaluation and return \\texttt{R[a]}\n            \\item \\texttt{TailCall(a, b)}\n\n                call closure \\texttt{R[a]} with argument \\texttt{R[b]} and exit closure evaluation and return \\texttt{R[a]}\n        \\end{itemize}\n    \\end{multicols}\n\\end{minipage}\n\n\\section{compilation: translate source language program to VM initial state (input bytecode)}\nCompilation is represented as equation: \\[\\llceil\\mathcal{T}, \\Sigma, Q\\rrceil = Q', \\Sigma' .\\]\n$\\Sigma$ is an environment from source language variable to register index.\n$Q_{\\mathit{init}}$ generates initial compilation state: \\[Q_{\\mathit{init}}\\left(e\\right) = \\llceil e, [], \\left\\langle [], [], [], []\\right\\rangle \\rrceil .\\]\n\n\\subsection{auxiliary funcion}\nWe define two auxiliary functions; \\textit{mtch} is to get last used register and rest instructions by pattern match, \n\n\\begin{center}\n    \\begin{minipage}{.5\\textwidth}\n        \\begin{flalign*}\n            &\\mathit{mtch}\\left(I; \\mathtt{Return\\left(a\\right)}\\right) &&=& \\left(\\mathtt{a}, I\\right)\\\\\n            &\\mathit{mtch}\\left(I; \\mathtt{TailCall\\left(a, b\\right)}\\right) &&=& \\left(\\mathtt{a}, I; \\mathtt{Call\\left(a, b\\right)}\\right)\\\\\n            &\\mathit{mtch}\\left(\\textunderscore\\right) &&=& \\mathrm{undefined}\n        \\end{flalign*}\n    \\end{minipage}\n\\end{center}\n\\textit{FV} is to get free variables.\n\\begin{center}\n    \\begin{minipage}{.5\\textwidth}\n        \\begin{flalign*}\n            &FV\\left(\\mathtt{n}\\right) \\mid FV\\left(\\mathtt{true}\\right) \\mid FV\\left(\\mathtt{false}\\right) \\mid FV\\left(\\mathtt{()}\\right) &&=& \\left\\{\\right\\}\\\\\n            &FV(\\mathtt{x}) &&=& \\left\\{\\mathtt{x}\\right\\}\\\\\n            &FV(\\mathtt{not\\ e}) &&=& FV(\\mathtt{e})\\\\\n            &FV(\\mathtt{e1 ? e2}) \\mid FV\\left(\\mathtt{e1\\ e2}\\right) &&=& FV(\\mathtt{e1}) \\cup FV(\\mathtt{e2})\\\\\n            &FV(\\mathtt{if\\ e1\\ then\\ e2\\ else\\ e3}) &&=& FV(\\mathtt{e1}) \\cup FV(\\mathtt{e2}) \\cup FV(\\mathtt{e3})\\\\\n            &FV\\left(\\mathtt{fun\\ x\\rightarrow e}\\right) &&=& FV\\left(\\mathtt{e}\\right) \\textbackslash \\left\\{\\mathtt{x}\\right\\}\\\\\n            &FV\\left(\\mathtt{let\\ x\\ =\\ e1\\ in\\ e2}\\right) &&=& FV(\\mathtt{e1}) \\cup \\left(FV\\left(\\mathtt{e2}\\right) \\textbackslash \\left\\{\\mathtt{x}\\right\\}\\right)\\\\\n            &FV\\left(\\mathtt{let\\ rec\\ f\\ x=\\ e1\\ in\\ e2}\\right) &&=& \\left(FV\\left(\\mathtt{e1}\\right) \\textbackslash \\left\\{\\mathtt{x}\\right\\} \\cup FV\\left(\\mathtt{e2}\\right)\\right) \\textbackslash \\left\\{\\mathtt{f}\\right\\}\n        \\end{flalign*}\n    \\end{minipage}\n\\end{center}\n\n\\subsection{compilation rules}\n\n\\infrule[Int]{%\n    \\mathtt{a}\\ \\mathrm{and}\\ \\mathtt{kx}\\ \\mathrm{are\\ fresh}\n}{\n    \\llceil\\mathtt{n}, \\Sigma, \\left\\langle I, C, F, \\mathit{Um}\\right\\rangle \\rrceil =%\n    \\left\\langle\n        I; \\mathtt{Load(a, kx)}; \\mathtt{Return(a)}, C; \\mathtt{kx} = \\mathtt{n}, F, \\mathit{Um}\n    \\right\\rangle, \\Sigma'\n}\n\n\\infax[Unit]{\n    \\llceil\\mathtt{()}, \\Sigma, \\left\\langle I, C, F, \\mathit{Um}\\right\\rangle \\rrceil =\n    \\left\\langle\n        I; \\mathtt{Unit(a)}; \\mathtt{Return(a)}, C, F, \\mathit{Um}\n    \\right\\rangle, \\Sigma'\n}\n\n\\infax[True]{\n    \\llceil\\mathtt{true}, \\Sigma, \\left\\langle I, C, F, \\mathit{Um}\\right\\rangle \\rrceil =\n    \\left\\langle\n        I; \\mathtt{SetBool(a, 1)}; \\mathtt{Return(a)}, C, F, \\mathit{Um}\n    \\right\\rangle, \\Sigma'\n}\n\n\\infax[False]{\n    \\llceil\\mathtt{false}, \\Sigma, \\left\\langle I, C, F, \\mathit{Um}\\right\\rangle \\rrceil =\n    \\left\\langle\n        I; \\mathtt{SetBool(a, 0)}; \\mathtt{Return(a)}, C, F, \\mathit{Um}\n    \\right\\rangle, \\Sigma'\n}\n\n\\infrule[Add]{\n        \\mathtt{a}\\ \\mathrm{is\\ fresh}\n    \\andalso Q = \\left\\langle I,C, F, \\mathit{Um} \\right\\rangle\n    \\andalso\\\\\n        \\llceil \\mathtt{e1}, \\Sigma, Q\\rrceil = \\langle I_\\mathtt{e1}, C', F', \\mathit{Um}'\\rangle, \\Sigma'\n    \\andalso \\mathit{mtch}\\left(I_\\mathtt{e1}\\right) = \\left(\\mathtt{r_\\mathtt{e1}}, I'\\right)\n    \\andalso\\\\\n        \\llceil \\mathtt{e2}, \\Sigma', \\langle I', C', F', \\mathit{Um}'\\rangle \\rrceil = \\langle I_\\mathtt{e2}, C'', F'', \\mathit{Um}''\\rangle, \\Sigma''\n    \\andalso \\mathit{mtch}\\left(I_\\mathtt{e2}\\right) = \\left(\\mathtt{r_{e2}}, I''\\right)\n}{\n    \\llceil \\mathtt{e1 + e2}, \\Sigma, Q\\rrceil = \\langle I''; \\mathtt{Add(a, r_{e1}, r_{e2})}; \\mathtt{Return(a)}, C'', F'', \\mathit{Um}''\\rangle, \\Sigma''\n}\n\n\\infrule[Sub]{\n        \\mathtt{a}\\ \\mathrm{is\\ fresh}\n    \\andalso Q = \\left\\langle I,C, F, \\mathit{Um} \\right\\rangle\n    \\andalso\\\\\n        \\llceil \\mathtt{e1}, \\Sigma, Q\\rrceil = \\langle I_\\mathtt{e1}, C', F', \\mathit{Um}'\\rangle, \\Sigma'\n    \\andalso \\mathit{mtch}\\left(I_\\mathtt{e1}\\right) = \\left(\\mathtt{r_{e1}}, I'\\right)\n    \\andalso\\\\\n        \\llceil \\mathtt{e2}, \\Sigma', \\langle I', C', F', \\mathit{Um}'\\rangle \\rrceil = \\langle I_\\mathtt{e2}, C'', F'', \\mathit{Um}''\\rangle, \\Sigma''\n    \\andalso \\mathit{mtch}\\left(I_\\mathtt{e2}\\right) = \\left(\\mathtt{r_{e2}}, I''\\right)\n}{\n    \\llceil \\mathtt{e1 - e2}, \\Sigma, Q\\rrceil = \\langle I''; \\mathtt{Sub(a, r_{e1}, r_{e2})}; \\mathtt{Return(a)}, C'', F'', \\mathit{Um}''\\rangle, \\Sigma''\n}\n\n\\infrule[Mul]{\n        \\mathtt{a}\\ \\mathrm{is\\ fresh}\n    \\andalso Q = \\left\\langle I,C, F, \\mathit{Um} \\right\\rangle\n    \\andalso\\\\\n        \\llceil \\mathtt{e1}, \\Sigma, Q\\rrceil = \\langle I_\\mathtt{e1}, C', F', \\mathit{Um}'\\rangle, \\Sigma'\n    \\andalso \\mathit{mtch}\\left(I_\\mathtt{e1}\\right) = \\left(\\mathtt{r_{e1}}, I'\\right)\n    \\andalso\\\\\n        \\llceil \\mathtt{e2}, \\Sigma', \\langle I', C', F', \\mathit{Um}'\\rangle \\rrceil = \\langle I_\\mathtt{e2}, C'', F'', \\mathit{Um}''\\rangle, \\Sigma''\n    \\andalso \\mathit{mtch}\\left(I_\\mathtt{e2}\\right) = \\left(\\mathtt{r_{e2}}, I''\\right)\n}{\n    \\llceil \\mathtt{e1 * e2}, \\Sigma, Q\\rrceil = \\langle I''; \\mathtt{Mul(a, r_{e1}, r_{e2})}; \\mathtt{Return(a)}, C'', F'', \\mathit{Um}''\\rangle, \\Sigma''\n}\n\n\\infrule[Div]{\n        \\mathtt{a}\\ \\mathrm{is\\ fresh}\n    \\andalso Q = \\left\\langle I,C, F, \\mathit{Um} \\right\\rangle\n    \\andalso\\\\\n        \\llceil \\mathtt{e1}, \\Sigma, Q\\rrceil = \\langle I_\\mathtt{e1}, C', F', \\mathit{Um}'\\rangle, \\Sigma'\n    \\andalso \\mathit{mtch}\\left(I_\\mathtt{e1}\\right) = \\left(\\mathtt{r_{e1}}, I'\\right)\n    \\andalso\\\\\n        \\llceil \\mathtt{e2}, \\Sigma', \\langle I', C', F', \\mathit{Um}'\\rangle \\rrceil = \\langle I_\\mathtt{e2}, C'', F'', \\mathit{Um}''\\rangle, \\Sigma''\n    \\andalso \\mathit{mtch}\\left(I_\\mathtt{e2}\\right) = \\left(\\mathtt{r_{e2}}, I''\\right)\n}{\n    \\llceil \\mathtt{e1 / e2}, \\Sigma, Q\\rrceil = \\langle I''; \\mathtt{Div(a, r_{e1}, r_{e2})}; \\mathtt{Return(a)}, C'', F'', \\mathit{Um}''\\rangle, \\Sigma''\n}\n\n\\infrule[Eq]{\n        \\mathtt{a}\\ \\mathrm{is\\ fresh}\n    \\andalso Q = \\left\\langle I,C, F, \\mathit{Um} \\right\\rangle\n    \\andalso\\\\\n        \\llceil \\mathtt{e1}, \\Sigma, Q\\rrceil = \\langle I_\\mathtt{e1}, C', F', \\mathit{Um}'\\rangle, \\Sigma'\n    \\andalso \\mathit{mtch}\\left(I_\\mathtt{e1}\\right) = \\left(\\mathtt{r_{e1}}, I'\\right)\n    \\andalso\\\\\n        \\llceil \\mathtt{e2}, \\Sigma', \\langle I', C', F', \\mathit{Um}'\\rangle \\rrceil = \\langle I_\\mathtt{e2}, C'', F'', \\mathit{Um}''\\rangle, \\Sigma''\n    \\andalso \\mathit{mtch}\\left(I_\\mathtt{e2}\\right) = \\left(\\mathtt{r_{e2}}, I''\\right)\n}{\n    \\llceil \\mathtt{e1 = e2}, \\Sigma, Q\\rrceil = \n    \\langle I''; \\mathtt{Eq(r_{e1}, r_{e2})}; \\mathtt{SetBool(a, 1)}; \\mathtt{SetBool(a, 0)}; \\mathtt{Return(a)}, C'', F'', \\mathit{Um}''\\rangle, \\Sigma''\n}\n\n\\infrule[Lt]{\n        \\mathtt{a}\\ \\mathrm{is\\ fresh}\n    \\andalso Q = \\left\\langle I,C, F, \\mathit{Um} \\right\\rangle\n    \\andalso\\\\\n        \\llceil \\mathtt{e1}, \\Sigma, Q\\rrceil = \\langle I_\\mathtt{e1}, C', F', \\mathit{Um}'\\rangle, \\Sigma'\n    \\andalso \\mathit{mtch}\\left(I_\\mathtt{e1}\\right) = \\left(\\mathtt{r_{e1}}, I'\\right)\n    \\andalso\\\\\n        \\llceil \\mathtt{e2}, \\Sigma', \\langle I', C', F', \\mathit{Um}'\\rangle \\rrceil = \\langle I_\\mathtt{e2}, C'', F'', \\mathit{Um}''\\rangle, \\Sigma''\n    \\andalso \\mathit{mtch}\\left(I_\\mathtt{e2}\\right) = \\left(\\mathtt{r_{e2}}, I''\\right)\n}{\n    \\llceil \\mathtt{e1 < e2}, \\Sigma, Q\\rrceil = \n    \\langle I''; \\mathtt{Lt(r_{e1}, r_{e2})}; \\mathtt{SetBool(a, 1)}; \\mathtt{SetBool(a, 0)}; \\mathtt{Return(a)}, C'', F'', \\mathit{Um}''\\rangle, \\Sigma''\n}\n\n\\infrule[Ge]{\n        \\mathtt{a}\\ \\mathrm{is\\ fresh}\n    \\andalso Q = \\left\\langle I,C, F, \\mathit{Um} \\right\\rangle\n    \\andalso\\\\\n        \\llceil \\mathtt{e1}, \\Sigma, Q\\rrceil = \\langle I_\\mathtt{e1}, C', F', \\mathit{Um}'\\rangle, \\Sigma'\n    \\andalso \\mathit{mtch}\\left(I_\\mathtt{e1}\\right) = \\left(\\mathtt{r_{e1}}, I'\\right)\n    \\andalso\\\\\n        \\llceil \\mathtt{e2}, \\Sigma', \\langle I', C', F', \\mathit{Um}'\\rangle \\rrceil = \\langle I_\\mathtt{e2}, C'', F'', \\mathit{Um}''\\rangle, \\Sigma''\n    \\andalso \\mathit{mtch}\\left(I_\\mathtt{e2}\\right) = \\left(\\mathtt{r_{e2}}, I''\\right)\n}{\n    \\llceil \\mathtt{e1 >= e2}, \\Sigma, Q\\rrceil = \n    \\langle I''; \\mathtt{Ge(r_{e1}, r_{e2})}; \\mathtt{SetBool(a, 1)}; \\mathtt{SetBool(a, 0)}; \\mathtt{Return(a)}, C'', F'', \\mathit{Um}''\\rangle, \\Sigma''\n}\n\n\\infrule[Not]{\n        \\mathtt{a}\\ \\mathrm{is\\ fresh}\n    \\andalso Q = \\left\\langle I,C, F, \\mathit{Um} \\right\\rangle\n    \\andalso\\\\\n        \\llceil \\mathtt{e}, \\Sigma, Q\\rrceil = \\langle I_\\mathtt{e}, C', F', \\mathit{Um}'\\rangle, \\Sigma'\n    \\andalso \\mathit{mtch}\\left(I_\\mathtt{e}\\right) = \\left(\\mathtt{r_e}, I'\\right)\n}{\n    \\llceil \\mathtt{not\\ e}, \\Sigma, Q\\rrceil = \\langle I'; \\mathtt{Test(r_{e}, 0)}; \\mathtt{SetBool(a, 1)}; \\mathtt{SetBool(a, 0)}; \\mathtt{Return(a)}, C', F', \\mathit{Um}'\\rangle, \\Sigma'\n}\n\n\\infrule[Fun]{\n        \\mathtt{a}\\ \\mathrm{and}\\ \\mathtt{cx}\\ \\mathrm{are\\ fresh}\n    \\andalso Q = \\left\\langle I, C, F, \\mathit{Um}\\right\\rangle\n    \\andalso fv = FV\\left(\\mathtt{fun\\ x\\rightarrow e}\\right)\n    \\andalso \\Sigma_0 = \\left\\{\\left(\\mathtt{x} = \\mathtt{i_r}\\right) \\mid \\left(\\mathtt{x} = \\mathtt{i_r}\\right) \\in \\Sigma \\wedge \\mathtt{x} \\in fv \\right\\}\n    \\andalso\\\\\n        \\Sigma' = \\left\\{ \\left(\\mathtt{x} = \\mathtt{-\\left(i + 1\\right)}\\right) \\mid \\left(\\mathtt{x} = \\mathtt{i_r}\\right)\\ \\mathrm{as}\\ \\mathit{xi} \\in \\Sigma_0 \\wedge \\mathit{xi}\\ \\mathrm{is}\\ i\\mathrm{th\\ element\\ of}\\ \\Sigma_0 \\right\\}\n    \\andalso \\mathit{Um}' = \\left\\{ \\mathtt{i} \\mid \\left(\\textunderscore = \\mathtt{i}\\right) \\in \\Sigma' \\right\\}\n    \\andalso\\\\\n        Q_{\\mathit{init}}\\left(\\mathtt{e}\\right) = \\llceil \\mathtt{e}, \\Sigma_\\mathtt{e}, \\left\\langle I_\\mathtt{e}, C_\\mathtt{e}, F_\\mathtt{e}, \\textunderscore\\right\\rangle \\rrceil\n    \\andalso \\Sigma_\\mathtt{e}' = \\Sigma_\\mathtt{e}; \\mathtt{x} = 0\n    \\andalso \\llceil \\mathtt{e}, \\Sigma_\\mathtt{e}', \\langle I_\\mathtt{e}, C_\\mathtt{e}, F_\\mathtt{e}, \\mathit{Um}' \\rangle \\rrceil%\n        = \\left\\langle I_\\mathtt{e}', C_\\mathtt{e}', F_\\mathtt{e}', \\textunderscore\\right\\rangle, \\Sigma_\\mathtt{e}''\n    \\andalso\\\\\n        \\mathit{Clos} = \\left\\langle I_\\mathtt{e}', C_\\mathtt{e}', F_\\mathtt{e}', \\mathit{Um} @ \\mathit{Um}' \\right\\rangle\n}{\n    \\llceil \\mathtt{fun\\ x \\rightarrow e}, \\Sigma, Q\\rrceil = \\langle I; \\mathtt{Clos(a, cx, 0)}; \\mathtt{Return(a)}, C, F; \\mathtt{cx} = \\mathit{Clos}, \\mathit{Um} \\rangle, \\Sigma\n}\n\n\\infrule[Call]{\n        Q = \\left\\langle I,C, F, \\mathit{Um} \\right\\rangle\n    \\andalso \\llceil \\mathtt{e1}, \\Sigma, Q\\rrceil = \\langle I_\\mathtt{e1}, C', F', \\mathit{Um}'\\rangle, \\Sigma'\n    \\andalso \\mathit{mtch}\\left(I_\\mathtt{e1}\\right) = \\left(\\mathtt{r_{e1}}, I'\\right)\n    \\andalso\\\\\n        \\llceil \\mathtt{e2}, \\Sigma', \\langle I', C', F', \\mathit{Um}'\\rangle \\rrceil = \\langle I_\\mathtt{e2}, C'', F'', \\mathit{Um}''\\rangle, \\Sigma''\n    \\andalso \\mathit{mtch}\\left(I_\\mathtt{e2}\\right) = \\left(\\mathtt{r_{e2}}, I''\\right)\n}{\n    \\llceil \\mathtt{e1\\ e2}, \\Sigma, Q\\rrceil = \\langle I''; \\mathtt{TailCall(r_{e1}, r_{e2})}, C'', F'', \\mathit{Um}''\\rangle, \\Sigma''\n}\n\n\\infrule[VarLocal]{\n    \\Sigma[\\mathtt{x}] = \\mathtt{i} \\wedge \\mathtt{i}\\geq \\mathtt{0}\n}{\n    \\llceil \\mathtt{x}, \\Sigma, \\left\\langle I, C, F, \\mathit{Um}\\right\\rangle \\rrceil =\n    \\left\\langle\n        I; \\mathtt{Move(a, i)}; \\mathtt{Return(a)}, C, F, \\mathit{Um}\n    \\right\\rangle, \\Sigma'\n}\n\n\\infrule[VarUpval]{\n    \\Sigma[\\mathtt{x}] = \\mathtt{i} \\wedge \\mathtt{i < 0}\n}{\n    \\llceil \\mathtt{x}, \\Sigma, \\left\\langle I, C, F, \\mathit{Um}\\right\\rangle \\rrceil =\n    \\left\\langle\n        I; \\mathtt{Upval(a, -i - 1)}; \\mathtt{Return(a)}, C, F, \\mathit{Um}\n    \\right\\rangle, \\Sigma'\n}\n\n\\infrule[Let]{\n        \\mathtt{a}\\ \\mathrm{and}\\ \\mathtt{b}\\ \\mathrm{are\\ fresh}\n    \\andalso Q = \\left\\langle I, C, F, \\mathit{Um} \\right\\rangle\n    \\andalso\\\\\n        \\llceil \\mathtt{e_1}, \\Sigma, Q\\rrceil = \\left\\langle I_\\mathtt{e1}, C', F', \\mathit{Um}'\\right\\rangle, \\Sigma'\n    \\andalso \\mathit{mtch}\\left(I_\\mathtt{e1}\\right) = \\left(\\mathtt{r_{e1}}, I'\\right)\n    \\andalso\\\\\n        \\llceil \\mathtt{e_2}, \\Sigma'; \\mathtt{x}=\\mathtt{a}, \\left\\langle I'; \\mathtt{Move(b, a)}, C', F', \\mathit{Um}'\\right\\rangle\\rrceil = Q', \\Sigma''\n}{\n    \\llceil \\mathtt{let\\ x=e_1\\ in\\ e_2}, \\Sigma, Q\\rrceil = Q', \\Sigma''\n}\n\n\\infrule[LetRecFun]{\n        \\mathtt{a}\\ \\mathrm{and}\\ \\mathtt{cx}\\ \\mathrm{are\\ fresh}\n    \\andalso Q = \\left\\langle I, C, F, \\mathit{Um} \\right\\rangle\n    \\andalso\\\\\n        fv = \\left(FV\\left(\\mathtt{e_1}\\right) \\textbackslash \\left\\{\\mathtt{x}\\right\\} \\cap FV\\left(\\mathtt{e_2}\\right)\\right) \\textbackslash \\left\\{f\\right\\}\n    \\andalso \\Sigma_0 = \\left\\{\\left(\\mathtt{x=i_r}\\right) \\mid \\left(\\mathtt{x=i_r}\\right) \\in \\Sigma \\wedge \\mathtt{x}\\in fv\\right\\} \\cap \\left\\{\\mathtt{\\left(f = a\\right)}\\right\\}\n    \\andalso\\\\\n    \\Sigma' = \\left\\{ \\left(\\mathtt{x} = \\mathtt{-\\left(i + 1\\right)}\\right) \\mid \\left(\\mathtt{x} = \\mathtt{i_r}\\right)\\ \\mathrm{as}\\ \\mathit{xi} \\in \\Sigma_0 \\wedge \\mathit{xi}\\ \\mathrm{is}\\ i\\mathrm{th\\ element\\ of}\\ \\Sigma_0 \\right\\}\n    \\andalso\\\\\n        \\mathit{Um}' = \\left\\{\\mathtt{i} \\mid \\left(\\mathtt{\\textunderscore = i}\\right) \\in \\Sigma'\\right\\}\n    \\andalso Q_\\mathit{init}(\\mathtt{e_1}) = \\llceil \\mathtt{e1}, \\Sigma_\\mathtt{e1}, \\left\\langle I_\\mathtt{e1}, C_\\mathtt{e1}, F_\\mathtt{e1}, \\textunderscore\\right\\rangle \\rrceil\n    \\andalso \\Sigma_\\mathtt{e1}' = \\Sigma_\\mathtt{e1}; \\mathtt{x} = \\mathtt{0}\n    \\andalso\\\\\n    \\llceil \\mathtt{e1}, \\Sigma_\\mathtt{e1}', \\left\\langle I_\\mathtt{e1}, C_\\mathtt{e1}, F_\\mathtt{e1}, \\mathit{Um}' \\right\\rangle \\rrceil = \\left\\langle I_\\mathtt{e1}', C_\\mathtt{e1}', F_\\mathtt{e1}', \\textunderscore\\right\\rangle, \\Sigma_\\mathtt{e1}''\n    \\andalso \\mathit{Clos}=\\left\\langle I_\\mathtt{e1},', C_\\mathtt{e1}', F_\\mathtt{e1}', \\mathit{Um} @ \\mathit{Um'}\\right\\rangle\n    \\andalso\\\\\n        I' = I; \\mathtt{Clos(a, cx, 1)}\n    \\andalso F' = F; \\mathtt{cx}=\\mathit{Clos}\n    \\andalso \\Sigma' = \\Sigma; \\mathtt{f=a}\n    \\andalso \\llceil \\mathtt{e2}, \\Sigma', \\left\\langle I', C, F', Um \\right\\rangle \\rrceil = Q', \\Sigma''\n}{\n    \\llceil \\mathtt{let\\ rec\\ f\\ x=e1\\ in\\ e2}, \\Sigma, Q\\rrceil = Q', \\Sigma''\n}\n\n% \\section{Evaluation: VM state transition rules}\n\n\\end{document}\n", "meta": {"hexsha": "c2c9de7c354a2ef39445286ca86ff981d4d7992a", "size": 18674, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/main.tex", "max_stars_repo_name": "Nymphium/VM-Based-Interpreter-Implementations-Example", "max_stars_repo_head_hexsha": "35b5f538b44a441d38354345edb5a15856659bbe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-06-30T06:45:33.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-30T06:45:33.000Z", "max_issues_repo_path": "doc/main.tex", "max_issues_repo_name": "Nymphium/VM-Based-Interpreter-Implementations-Example", "max_issues_repo_head_hexsha": "35b5f538b44a441d38354345edb5a15856659bbe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/main.tex", "max_forks_repo_name": "Nymphium/VM-Based-Interpreter-Implementations-Example", "max_forks_repo_head_hexsha": "35b5f538b44a441d38354345edb5a15856659bbe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.5856353591, "max_line_length": 252, "alphanum_fraction": 0.5855199743, "num_tokens": 7368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.3351013626608302}}
{"text": "\\listfiles\n\\documentclass{article}\n\\author{Arya Stark}\n\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{mathtools}\n\\usepackage{listings}\n\\usepackage{float}\n\\usepackage{tikz}\n\\usepackage{tikz,fullpage}\n\\usepackage{tkz-graph}\n\\usepackage[position=top]{subfig}\n\\usepackage{graphicx}\n\n\\DeclarePairedDelimiter\\floor{\\lfloor}{\\rfloor}\n\\DeclarePairedDelimiter\\ceil{\\lceil}{\\rceil}\n\\DeclareMathOperator{\\cl}{cl}\n\\DeclareMathOperator{\\E}{E}\n\\def\\Z{\\mathbb{Z}}\n\\def\\N{\\mathbb{N}}\n\\def\\R{\\mathbb{R}}\n\\def\\Q{\\mathbb{Q}}\n\\def\\K{\\mathbb{K}}\n\\def\\T{\\mathbb{T}}\n\\def\\B{\\mathcal{B}}\n\\def\\XX{\\mathfrak{X}}\n\\def\\YY{\\mathfrak{Y}}\n\\def\\AA{\\mathfrak{A}}\n\\def\\ZZ{\\mathfrak{Z}}\n\\def\\BB{\\mathcal{B}}\n\\def\\UU{\\mathcal{U}}\n\\def\\MM{\\mathcal{M}}\n\\def\\M{\\mathfrak{M}}\n\\def\\l{\\lambda}\n\\def\\L{\\Lambda}\n\\def\\<{\\langle}\n\\def\\>{\\rangle}\n\n\\usepackage[a4paper,margin=1in]{geometry}\n\n\\setlength{\\parindent}{0cm}\n\\setlength{\\parskip}{1em}\n\n\\title{Virtual Channels and Rebalancing in State Channel Networks}\n\\date{}\n\n\\begin{document}\n\\maketitle\n\n\\section*{Introduction}\n\nThis research note was written because there are some unsolved problems in designing state channel networks that are not well-known or being worked on. These problems reveal themselves when we consider how to build channel networks capable of expressing agents' preferences over network topology (payment capacity) and capital costs, expectation of other participants' future liveness, and minimizing blockchain fees.\n\n\\section*{Relevant Prerequisite Literature}\n\nThis section goes through relevant existing literature. Note that even if you know all this, many definitions will be used in later sections.\n\n\\subsection*{Ball-and-bead model of PCN}\n\nIn this model, edges represent two-party channel between the endpoints, and a party's balance within the channel is represented by beads near to them.\n\n\\begin{center}\n\\includegraphics[scale=0.4]{beads.png}\n\\includegraphics[scale=0.4]{beads2.png}\n\\end{center}\n\nThis shows Alice sending Bob 2 beads via Hub. The remaining capacity along this path is $\\min(2,1) = 1$.\n\n\\subsection*{Rebalancing}\n\nWe say that two payment channel networks are value-equivalent if the set of agents is the same and each agent owns the amount of beads summed over all their channels. A channel network is rebalanced when it transitions into a value-equivalent state. This transition can include on-chain transactions or not. In the following on-chain rebalance, Bob increases the capacity of the Bob $\\to$ Alice link.\n\n\\begin{center}\n\\includegraphics[scale=0.4]{on-chain-rebalancing-1.png}\n\\includegraphics[scale=0.4]{on-chain-rebalancing-2.png}\n\\end{center}\n\nThe following is an example of a rebalance that does not require on-chain transactions.\n\n\\begin{center}\n\\includegraphics[scale=0.4]{off-chain-rebalancing-1.png}\n\\includegraphics[scale=0.4]{off-chain-rebalancing-2.png}\n\\end{center}\n\nAre off-chain rebalances sufficient? In general, no.\n\n% TBW: define a $a,b$-flow, apply max-flow-min-cut theorem, etc.\n\n% Note some assumptions implicitly made when applying this theorem: the max flow might requrie very global knowledge to compute.\n\n% Fun exercise! A self-payment is a special type of off-chain rebalance. Show that any rebalance can be expressed as a series of self-payments.\n\n\\subsection*{Time-based lockup}\n\nThere are multiple ways that intermediaries can structure agreements-to-route; we go through two extremal points here. They can agree to route a single payment. When that payment completes successfully, the balances change and they are free of any further commitments. The second way is to agree to lock up funds for a certain period of time, creating a ``virtual channel\". The balances in the virtual channel can be updated instantly and many times without the intermediary's participation or knowledge. At the end of the lockup time, the final balances in the virtual channel are agreed to and we update the direct channel balances as though a single set of routed balance updates (routed payments) was made.\n\n\\subsection*{Ejection}\n\nThere is an upper bound on the fee that the intermediary can charge, since any virtual channel can be transformed into a direct channel (i.e. it can be ``ejected\") by some on-chain transactions, without disrupting the internal state of the virtual channel. Here is an example. Suppose we have this system of direct channels. (Note: we switch to labelling edges by their endpoint balances rather than using beads, due to limitations of latex).\n\n\\begin{figure}[H]\n    \\centering\n    \\begin{tikzpicture}[scale=2.75]\n        \\GraphInit[vstyle=Normal]\n        \\Vertex[x=0,y=0]{A}\n        \\Vertex[x=2,y=0]{H}\n        \\Vertex[x=4,y=0]{B}\n        \\Edge[label=$1/1$](A)(H)\n        \\Edge[label=$1/1$](H)(B)\n    \\end{tikzpicture}\n\\end{figure}\n\nHere, a virtual channel between A and B can be formed, with balance one bead for each of them, locking up two beads from H. The channel could be ejected by an on-chain transaction that transfers one bead out of the A-H channel and H-B channel and atomically updating the internal states of them.\n\n\\begin{figure}[H]\n    \\centering\n    \\begin{tikzpicture}[scale=2.75]\n        \\GraphInit[vstyle=Normal]\n        \\Vertex[x=0,y=0]{A}\n        \\Vertex[x=2,y=0]{B}\n        \\Vertex[x=4,y=0]{C}\n        \\Edge[label=$0/1$](A)(B)\n        \\Edge[label=$1/0$](B)(C)\n        \\Edge[style={bend left},label=$1/1$](A)(C)\n    \\end{tikzpicture}\n\\end{figure}\n\n\\subsection*{Intermediation Fees}\n\nFor this reason, thinking of lockups as either completely ``per-payment\" or ``time-based\" is not strictly accurate; the costs an intermediary would incur in a channel network is both the cost of re-configuring the capacity graph as well as time-based opportunity cost of having their capital in excess of payments they would want to make anyway in the network (e.g. instead of staking), however both can be avoided by on-chain transactions; the instances where on-chain transactions are avoided and off-chain fees paid instead are therefore some complex subset of transactions in general.\n\nHere is a crude fee scheme that captures some of it this: an intermediary charges some large fee $F_1$ to intermediate a virtual channel, and assumes the responsibility of ejecting the channel; if the virtual channel participants have no further use for it, they negotiate a payment of $F_2$ from the intermediary to close the virtual channel offline. If the on-chain fee is $T$, we should have $0 < F_1 - F_2 < T < F_1$. On/off-chain rebalancing is handeled by an independent protocol.\n\nAnother design: timeout by default, but eject if agreed to.\n\n\\subsection*{State Channels}\n\nBy allowing beads to be locked into complex applications (e.g. chess, prediction markets) instead of just payments, the need for virtual channels as well as for ejection is even more apparent. Beads can be freed up and re-used within a virtual channel. The time bound for an application might be long or unknown (e.g., we lock beads up in a bet of whether any US Libertarian Party ever wins a House seat in the next 10 years),\n\n\\subsection*{Multipath}\n\nTBW\n\n\\subsection*{N-Party}\n\nTBW\n\n\\subsection*{Subchannels}\n\nTBW\n\n\\subsection*{Plasma}\n\nPlasma can be used to fund channels. If all channels are funded by plasma, then rebalancing is a plasma transaction in the normal case, i.e., the entire network can be rebalanced arbitrarily in a single ethereum transaction. I claim that a super-optimized channel network that does not support funding via plasma will be much more expensive than a very suboptimal one that supports funding via plasma.\n\n\\section*{Ejection Test Cases}\n\nWe present some ejection test cases and for each one, we show that it could be the optimal way of ejecting the channel given certain assumptions about the participants' preferences over the capacity graph, on-chain fees, and expectation of other participants' future liveness.\n\n\\subsection*{Symmetric}\n\n\\begin{figure}[H]\n    \\centering\n    \\begin{tikzpicture}[scale=2.75]\n        \\GraphInit[vstyle=Normal]\n        \\SetVertexSimple\n        \\Vertex[x=0,y=0]{A}\n        \\Vertex[x=2,y=0]{B}\n        \\Vertex[x=4,y=0]{C}\n        \\Edge[label=$1/1$](A)(B)\n        \\Edge[label=$1/1$](B)(C)\n        \\Edge[style={bend left}](A)(C)\n    \\end{tikzpicture}\n    \\begin{tikzpicture}[scale=2.75]\n        \\GraphInit[vstyle=Normal]\n        \\SetVertexSimple\n        \\Vertex[x=0,y=0]{A}\n        \\Vertex[x=2,y=0]{B}\n        \\Vertex[x=4,y=0]{C}\n        \\Edge[label=$0/1$](A)(B)\n        \\Edge[label=$1/0$](B)(C)\n        \\Edge[style={bend left},label=$1/1$](A)(C)\n    \\end{tikzpicture}\n\\end{figure}\n\nReviewed previously.\n\n\\subsection*{Asymetric}\n\n\\begin{figure}[H]\n    \\centering\n    \\begin{tikzpicture}[scale=2.75]\n        \\GraphInit[vstyle=Normal]\n        \\SetVertexSimple\n        \\Vertex[x=0,y=0]{A}\n        \\Vertex[x=2,y=0]{B}\n        \\Vertex[x=4,y=0]{C}\n        \\Edge[label=$1/1$](A)(B)\n        \\Edge[label=$1/1$](B)(C)\n        \\Edge[style={bend left}](A)(C)\n    \\end{tikzpicture}\n    \\begin{tikzpicture}[scale=2.75]\n        \\GraphInit[vstyle=Normal]\n        \\SetVertexSimple\n        \\Vertex[x=0,y=0]{A}\n        \\Vertex[x=2,y=0]{B}\n        \\Vertex[x=4,y=0]{C}\n        \\Edge[label=$0/2$](A)(B)\n        \\Edge(B)(C)\n        \\Edge[style={bend left},label=$1/1$](A)(C)\n    \\end{tikzpicture}\n\\end{figure}\n\nWhat are the differences between the the assymetric and symmetric ways of ejecting? The symmetric manner might be preferred because it minimal in the number of transactions (1 vs 2). Even if we assume some mechanism to batch two sub-transactions under one (e.g. account abstraction), it is minimal in the number of ERCECOVERS (3 vs 2). On the other hand, the symmetric manner might be preferred for the more ``balanced\" resulting capacity graph.\n\n\\subsection*{Symmetric Unidirectional}\n\n\\begin{figure}[H]\n    \\centering\n    \\begin{tikzpicture}[scale=2.75]\n        \\GraphInit[vstyle=Normal]\n        \\SetVertexSimple\n        \\Vertex[x=0,y=0]{A}\n        \\Vertex[x=2,y=0]{B}\n        \\Vertex[x=4,y=0]{C}\n        \\Edge[label=$2/0$](A)(B)\n        \\Edge[label=$2/0$](B)(C)\n        \\Edge[style={bend left}](A)(C)\n    \\end{tikzpicture}\n    \\begin{tikzpicture}[scale=2.75]\n        \\GraphInit[vstyle=Normal]\n        \\SetVertexSimple\n        \\Vertex[x=0,y=0]{A}\n        \\Vertex[x=2,y=0]{B}\n        \\Vertex[x=4,y=0]{C}\n        \\Edge[label=$0/1$](A)(B)\n        \\Edge[label=$1/0$](B)(C)\n        \\Edge[style={bend left},label=$2/0$](A)(C)\n    \\end{tikzpicture}\n\\end{figure}\n\n\\subsection*{Asymmetric Unidirectional 1}\n\n\\begin{figure}[H]\n    \\centering\n    \\begin{tikzpicture}[scale=2.75]\n        \\GraphInit[vstyle=Normal]\n        \\SetVertexSimple\n        \\Vertex[x=0,y=0]{A}\n        \\Vertex[x=2,y=0]{B}\n        \\Vertex[x=4,y=0]{C}\n        \\Edge[label=$1/0$](A)(B)\n        \\Edge[label=$1/0$](B)(C)\n        \\Edge[style={bend left}](A)(C)\n    \\end{tikzpicture}\n    \\begin{tikzpicture}[scale=2.75]\n        \\GraphInit[vstyle=Normal]\n        \\SetVertexSimple\n        \\Vertex[x=0,y=0]{A}\n        \\Vertex[x=2,y=0]{B}\n        \\Vertex[x=4,y=0]{C}\n        \\Edge[label=$0/1$](A)(B)\n        \\Edge(B)(C)\n        \\Edge[style={bend left},label=$1/0$](A)(C)\n    \\end{tikzpicture}\n\\end{figure}\n\n\\subsection*{Asymmetric Unidirectional 2}\n\n\\begin{figure}[H]\n    \\centering\n    \\begin{tikzpicture}[scale=2.75]\n        \\GraphInit[vstyle=Normal]\n        \\SetVertexSimple\n        \\Vertex[x=0,y=0]{A}\n        \\Vertex[x=2,y=0]{B}\n        \\Vertex[x=4,y=0]{C}\n        \\Edge[label=$1/0$](A)(B)\n        \\Edge[label=$1/0$](B)(C)\n        \\Edge[style={bend left}](A)(C)\n    \\end{tikzpicture}\n    \\begin{tikzpicture}[scale=2.75]\n        \\GraphInit[vstyle=Normal]\n        \\SetVertexSimple\n        \\Vertex[x=0,y=0]{A}\n        \\Vertex[x=2,y=0]{B}\n        \\Vertex[x=4,y=0]{C}\n        \\Edge(A)(B)\n        \\Edge[label=$1/0$](B)(C)\n        \\Edge[style={bend left},label=$1/0$](A)(C)\n    \\end{tikzpicture}\n\\end{figure}\n\n\\subsection*{Long-Chain Large-Radius}\n\n\\begin{figure}[H]\n    \\centering\n    \\begin{tikzpicture}[scale=1.5]\n        \\GraphInit[vstyle=Normal]\n        \\SetVertexSimple\n        \\Vertex[x=0,y=0]{A}\n        \\Vertex[x=2,y=0]{B}\n        \\Vertex[x=4,y=0]{C}\n        \\Vertex[x=6,y=0]{D}\n        \\Vertex[x=8,y=0]{E}\n        \\Vertex[x=10,y=0]{F}\n        \\Edge[label=$1/0$](A)(B)\n        \\Edge[label=$1/0$](B)(C)\n        \\Edge[label=$1/0$](C)(D)\n        \\Edge[label=$1/0$](D)(E)\n        \\Edge[label=$1/0$](E)(F)\n        \\Edge[style={bend left}](A)(F)\n    \\end{tikzpicture}\n    \\begin{tikzpicture}[scale=1.5]\n        \\GraphInit[vstyle=Normal]\n        \\SetVertexSimple\n        \\Vertex[x=0,y=0]{A}\n        \\Vertex[x=2,y=0]{B}\n        \\Vertex[x=4,y=0]{C}\n        \\Vertex[x=6,y=0]{D}\n        \\Vertex[x=8,y=0]{E}\n        \\Vertex[x=10,y=0]{F}\n        \\Edge[label=$0/1$](A)(B)\n        \\Edge[label=$0/1$](B)(C)\n        \\Edge[label=$0/1$](C)(D)\n        \\Edge(D)(E)\n        \\Edge[label=$1/0$](E)(F)\n        \\Edge[style={bend left},label=$1/0$](A)(F)\n    \\end{tikzpicture}\n\\end{figure}\n\n\\subsection*{Long-Chain Short-Radius}\n\n\\begin{figure}[H]\n    \\centering\n    \\begin{tikzpicture}[scale=1.5]\n        \\GraphInit[vstyle=Normal]\n        \\SetVertexSimple\n        \\Vertex[x=0,y=0]{A}\n        \\Vertex[x=2,y=0]{B}\n        \\Vertex[x=4,y=0]{C}\n        \\Vertex[x=6,y=0]{D}\n        \\Vertex[x=8,y=0]{E}\n        \\Vertex[x=10,y=0]{F}\n        \\Edge[label=$1/0$](A)(B)\n        \\Edge[label=$1/0$](B)(C)\n        \\Edge[label=$1/0$](C)(D)\n        \\Edge[label=$1/0$](D)(E)\n        \\Edge[label=$1/0$](E)(F)\n        \\Edge[style={bend left}](C)(E)\n    \\end{tikzpicture}\n    \\begin{tikzpicture}[scale=1.5]\n        \\GraphInit[vstyle=Normal]\n        \\SetVertexSimple\n        \\Vertex[x=0,y=0]{A}\n        \\Vertex[x=2,y=0]{B}\n        \\Vertex[x=4,y=0]{C}\n        \\Vertex[x=6,y=0]{D}\n        \\Vertex[x=8,y=0]{E}\n        \\Vertex[x=10,y=0]{F}\n        \\Edge[label=$0/1$](A)(B)\n        \\Edge[label=$0/1$](B)(C)\n        \\Edge[label=$0/1$](C)(D)\n        \\Edge(D)(E)\n        \\Edge[label=$1/0$](E)(F)\n        \\Edge[style={bend left},label=$1/0$](C)(E)\n    \\end{tikzpicture}\n\\end{figure}\n\n\\subsection*{Multipath}\n\n\\begin{figure}[H]\n    \\centering\n    \\begin{tikzpicture}[scale=1.5]\n        \\GraphInit[vstyle=Normal]\n        \\SetVertexSimple\n        \\Vertex[x=2,y=0]{D}\n        \\Vertex[x=0,y=1]{A}\n        \\Vertex[x=4,y=1]{E}\n        \\Vertex[x=1,y=2]{B}\n        \\Vertex[x=3,y=2]{C}\n        \\Edge(A)(E)\n        \\Edge(A)(B)\n        \\Edge(B)(C)\n        \\Edge(C)(E)\n        \\Edge(A)(D)\n        \\Edge(D)(E)\n    \\end{tikzpicture}\n\\end{figure}\n\nBalances and ejection to be filled in.\n\n\\subsection*{Thanos Star}\n\nNew notation: a square node is not a participant, but it means that its neighbours are all connected in a direct channel.\n\n\\begin{figure}[H]\n    \\centering\n    \\begin{tikzpicture}[scale=1.5]\n        \\GraphInit[vstyle=Normal]\n        \\SetVertexSimple\n        \\Vertex[x=0,y=2.5]{A}\n        \\Vertex[x=3,y=0]{B}\n        \\Vertex[x=3,y=1]{C}\n        \\Vertex[x=3,y=2]{D}\n        \\Vertex[x=3,y=3]{E}\n        \\Vertex[x=3,y=4]{F}\n        \\Vertex[x=3,y=5]{G}\n        \\begin{scope}[VertexStyle/.append style = {rectangle}]\n        \\Vertex[x=6,y=2.5,style={color=red}]{H}\n        \\end{scope}\n        \\Edge[label=$1/1$](A)(B)\n        \\Edge[label=$1/1$](A)(C)\n        \\Edge[label=$1/1$](A)(D)\n        \\Edge[label=$1/1$](A)(E)\n        \\Edge[label=$1/1$](A)(F)\n        \\Edge[label=$1/1$](A)(G)\n        \\Edge(H)(B)\n        \\Edge(H)(C)\n        \\Edge(H)(D)\n        \\Edge(H)(E)\n        \\Edge(H)(F)\n        \\Edge(H)(G)\n    \\end{tikzpicture}\n\\end{figure}\n\n\\begin{figure}[H]\n    \\centering\n    \\begin{tikzpicture}[scale=1.5]\n        \\GraphInit[vstyle=Normal]\n        \\SetVertexSimple\n        \\Vertex[x=0,y=2.5]{A}\n        \\Vertex[x=3,y=0]{B}\n        \\Vertex[x=3,y=1]{C}\n        \\Vertex[x=3,y=2]{D}\n        \\Vertex[x=3,y=3]{E}\n        \\Vertex[x=3,y=4]{F}\n        \\Vertex[x=3,y=5]{G}\n        \\begin{scope}[VertexStyle/.append style = {rectangle}]\n        \\Vertex[x=6,y=2.5,style={color=red}]{H}\n        \\end{scope}\n        \\Edge(A)(B)\n        \\Edge(A)(C)\n        \\Edge(A)(D)\n        \\Edge[label=$2/0$](A)(E)\n        \\Edge[label=$2/0$](A)(F)\n        \\Edge[label=$2/0$](A)(G)\n        \\Edge[label=$1$](H)(B)\n        \\Edge[label=$1$](H)(C)\n        \\Edge[label=$1$](H)(D)\n        \\Edge[label=$1$](H)(E)\n        \\Edge[label=$1$](H)(F)\n        \\Edge[label=$1$](H)(G)\n    \\end{tikzpicture}\n\\end{figure}\n\nA 6-party virtual channel gets ejected into a 6-party direct channel. This manner of ejecting is minimal in number of transactions.\n\n\\section*{Other test cases}\n\n\\subsection*{Under-Capacity Three Party Channel}\n\n\\begin{figure}[H]\n    \\centering\n    \\begin{tikzpicture}[scale=1.5]\n        \\GraphInit[vstyle=Normal]\n        \\Vertex[x=0,y=0]{A}\n        \\Vertex[x=0,y=2]{B}\n        \\Vertex[x=3,y=1]{H}\n        \\Vertex[x=6,y=1]{C}\n        \\Edge[label=$1/0$](A)(H)\n        \\Edge[label=$1/0$](B)(H)\n        \\Edge[label=$1/0$](H)(C)\n    \\end{tikzpicture}\n\\end{figure}\n\nIf A,B,C form a virtual channel through H, they end up in a three-party virtual channel where A can send C one bead, and B can send C one bead, but the two cannot happen at the same time. The challenge is that it is inappropirate to represent this as a three-party channel where A and B's balances are both one.\n\n\\subsection*{Self Lock-in}\n\nTBW\n\nchannel factories: more attack surface, but root nonce => same cost of attack\n\nchannels-on-plasma spectrum\n\n\\end{document}", "meta": {"hexsha": "639f7bfe1c32c919cd100699706a1744dfe35b7b", "size": 17246, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "networks-paper.tex", "max_stars_repo_name": "L4ventures/networks-paper", "max_stars_repo_head_hexsha": "65347587c565ae38e7abbec481a998adc823bdf4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2018-08-09T01:06:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-02T05:51:12.000Z", "max_issues_repo_path": "networks-paper.tex", "max_issues_repo_name": "L4ventures/networks-paper", "max_issues_repo_head_hexsha": "65347587c565ae38e7abbec481a998adc823bdf4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-03-09T07:54:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-09T03:22:27.000Z", "max_forks_repo_path": "networks-paper/networks-paper.tex", "max_forks_repo_name": "counterfactual/research", "max_forks_repo_head_hexsha": "f6ed10464725bc3b076d22d4676d909943e69f5d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3401639344, "max_line_length": 710, "alphanum_fraction": 0.6380609997, "num_tokens": 5385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.3349377288927276}}
{"text": "\\title{LMMP: Stereo Module Testing Plan}\n\\author{\n        Ara V. Nefian \\and Michael Broxton\n}\n\\date{\\today}\n\n\\documentclass[12pt]{article}\n\n\\begin{document}\n\\maketitle\n\nThis document describes a testing plan for the LMMP stereo module.\n{\\underline {\\bf Accuracy measures}}\n\n\\begin{itemize}\n\\item {\\bf Option 1:} Short term, if ground truth data (Apollo Panoramic images) is available (Feb 15). Let the predicted horizontal and vertical\n      disparity map for the $k$th image be denoted as ${\\bf P}_{k, h}(i,j)$ and ${\\bf P}_{k, v}(i,j)$  respectively with the corresponding ground truth dispariy map ${\\bf T}_{k, h}(i,j)$ and ${\\bf T}_{k, v}(i,j)$ for all pixels $(i,j)$. \n\nThe ${\\bf average}$ ${\\bf error}$ is \n      ${\\bf E} =\\frac{1}{K}\\sum_k\\frac{\\sum_{ij} (P_{k,v}(i,j)-T_{k,v}(i,j))^2 + (P_{k,h}(i,j)-T_{k,h}(i,j))^2}{N_{k,pred}} $ where $N_{k,pred}$ \n      is the number of pixels for which the disparity map was computed in the $k$th image, and $K$ is the total number of images for \n      which we have ground truth. \n\n      The ${\\bf average}$ ${\\bf coverage}$ ${\\bf C}$ measures the number of pixels for which the disparity is determined: \n${\\bf C} = \\frac{1}{K}\\sum_k\\frac{N_{k,pred}}{N_{k,true}}$, where $N_{k, true}$ is the resolution of the ground truth images.\n  \n     The goal is to have a small average error ${\\bf E}$ and large avearge coverage ${\\bf C}$ measures.\n\n\\item {\\bf Option 2:} Very short term, before the ground truth data is made available (Jan 15th).\n                    Compute the ${\\bf E}$ measure using existing synthetic ground truth data, and the ${\\bf C}$ \n                    measure using the MOC and Apollo Metric data.\n\n\\item {\\bf Option 3:} On the longer term the ${\\bf E}$ measure will be weighted by the confidence score of the Bayesian subpixel correlator.\n\n \n       ${\\bf \\tilde E} =\\frac{1}{K}\\sum_k\\frac{\\sum_{ij} ((P_{k,v}(i,j)-T_{k,v}(i,j))^2 + (P_{k,h}(i,j)-T_{k,h}(i,j))^2)\\frac{p_{ij}}{\\sum_{ij}p_{ij}}}{N_{k,pred}} $      \n\\end{itemize}\n\n{\\underline {\\bf Performance measures}}\n Very short term (Jan 15th). Compute the number of additions, multiplications log and exp operations per pixel and run time required to generate the dense disparity map.\n%\\begin{abstract}\n%This is the paper's abstract \\ldots\n%\\end{abstract}\n\n%\\section{Introduction}\n%This is time for all good men to come to the aid of their party!\n\n%\\paragraph{Outline}\n%The remainder of this article is organized as follows.\n%Section~\\ref{previous work} gives account of previous work.\n%Our new and exciting results are described in Section~\\ref{results}.\n%Finally, Section~\\ref{conclusions} gives the conclusions.\n\n%\\section{Previous work}\\label{previous work}\n%A much longer \\LaTeXe{} example was written by Gil~\\cite{Gil:02}.\n\n%\\section{Results}\\label{results}\n%In this section we describe the results.\n\n%\\section{Conclusions}\\label{conclusions}\n%We worked hard, and achieved very little.\n\n\\bibliographystyle{abbrv}\n\\bibliography{simple}\n\n\\end{document}\nThis is never printed\n", "meta": {"hexsha": "a0dcf47e3cda7587679f6200da32700e42f19435", "size": 3000, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/book/stereo_testing_plan.tex", "max_stars_repo_name": "nasa/StereoPipeline", "max_stars_repo_head_hexsha": "8b9c0bcab258c41d10cb2973d97722765072a7bf", "max_stars_repo_licenses": ["NASA-1.3"], "max_stars_count": 29, "max_stars_repo_stars_event_min_datetime": "2015-05-06T01:28:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T22:55:29.000Z", "max_issues_repo_path": "docs/book/stereo_testing_plan.tex", "max_issues_repo_name": "imagineagents/StereoPipeline", "max_issues_repo_head_hexsha": "8b9c0bcab258c41d10cb2973d97722765072a7bf", "max_issues_repo_licenses": ["NASA-1.3"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/book/stereo_testing_plan.tex", "max_forks_repo_name": "imagineagents/StereoPipeline", "max_forks_repo_head_hexsha": "8b9c0bcab258c41d10cb2973d97722765072a7bf", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2015-01-15T04:20:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-10T01:31:17.000Z", "avg_line_length": 44.1176470588, "max_line_length": 237, "alphanum_fraction": 0.6863333333, "num_tokens": 871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.5544704649604274, "lm_q1q2_score": 0.3348623646504356}}
{"text": "\\documentclass[]{article}\n\\usepackage{lmodern}\n\\usepackage{amssymb,amsmath}\n\\usepackage{ifxetex,ifluatex}\n\\usepackage{fixltx2e} % provides \\textsubscript\n\\ifnum 0\\ifxetex 1\\fi\\ifluatex 1\\fi=0 % if pdftex\n  \\usepackage[T1]{fontenc}\n  \\usepackage[utf8]{inputenc}\n\\else % if luatex or xelatex\n  \\ifxetex\n    \\usepackage{mathspec}\n    \\usepackage{xltxtra,xunicode}\n  \\else\n    \\usepackage{fontspec}\n  \\fi\n  \\defaultfontfeatures{Mapping=tex-text,Scale=MatchLowercase}\n  \\newcommand{\\euro}{€}\n\\fi\n% use upquote if available, for straight quotes in verbatim environments\n\\IfFileExists{upquote.sty}{\\usepackage{upquote}}{}\n% use microtype if available\n\\IfFileExists{microtype.sty}{%\n\\usepackage{microtype}\n\\UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts\n}{}\n\\ifxetex\n  \\usepackage[setpagesize=false, % page size defined by xetex\n              unicode=false, % unicode breaks when used with xetex\n              xetex]{hyperref}\n\\else\n  \\usepackage[unicode=true]{hyperref}\n\\fi\n\\hypersetup{breaklinks=true,\n            bookmarks=true,\n            pdfauthor={},\n            pdftitle={Foo},\n            colorlinks=true,\n            citecolor=blue,\n            urlcolor=blue,\n            linkcolor=magenta,\n            pdfborder={0 0 0}}\n\\urlstyle{same}  % don't use monospace font for urls\n\\setlength{\\parindent}{0pt}\n\\setlength{\\parskip}{6pt plus 2pt minus 1pt}\n\\setlength{\\emergencystretch}{3em}  % prevent overfull lines\n\\setcounter{secnumdepth}{5}\n\n\\title{Foo}\n\\date{}\n\\usepackage{graphicx}\n\\usepackage[all]{hypcap}\n\\usepackage{tikz}\n\\usepackage{standalone}\n\\usepackage[sort&compress, numbers]{natbib}\n\\usepackage{minted}\n\n\\begin{document}\n\\maketitle\n\n\\section{Math}\\label{math}\n\n\\begin{equation}\\label{eq:ellipse}\nAx^2 + Bxy + Cy^2 + Dx + Ey + F = 0\n\\end{equation}\n\nRefering equation \\eqref{eq:ellipse}, \\(\\forall n, x_i^n = x_i\\).\n\n\\section{Image}\\label{image}\n\nSee following figure(\\autoref{fig:xor}).\n\n\\begin{figure}[h]\\centering\\includegraphics[width=\\textwidth]{.//assets/images/xor.png}\\caption{Figure Example}\\label{fig:xor}\\end{figure}\n\n\\section{Tex2img}\\label{tex2img}\n\nSee following figure(\\autoref{fig:test}).\n\n\\begin{figure}[h]\\centering\\input{./misc/test.tex}\\caption{Test tex figure}\\label{fig:test}\\end{figure}\n\n\\section{Gist}\\label{gist}\n\n\\inputminted[mathescape, linenos, frame=lines, framesep=2mm]{Python}{.gist-cache/cache.7aeefc0de1bb10005514355a5c4a5dfe-1c74b8336494cb0e9c6d-xor-5d.py}\n\n\\section{Post Link}\\label{post-link}\n\n\\href{http://localhost:4000/2015/04/29/foo/}{Foo}\n\nAwesome paper\\cite{mikolov2013efficient}.\n\n\\bibliographystyle{unsrt}\n\n\\bibliography{assets/printables/references}\n\n\\renewcommand{\\thefootnote}{}\n\n\\footnotetext{Online version at \\url{http://localhost:4000/2015/04/29/foo/}}\n\n\\end{document}\n", "meta": {"hexsha": "9bceef6250468a28c851ff33c4f3f89d3fa8f4d2", "size": 2754, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "test/test-site/_expected/full/assets/printables/2015-04-29-foo.tex", "max_stars_repo_name": "wantee/octopress-printable", "max_stars_repo_head_hexsha": "9c5a13fb0e3f4472c88c844a257d3b86e8e3ef04", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test-site/_expected/full/assets/printables/2015-04-29-foo.tex", "max_issues_repo_name": "wantee/octopress-printable", "max_issues_repo_head_hexsha": "9c5a13fb0e3f4472c88c844a257d3b86e8e3ef04", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test-site/_expected/full/assets/printables/2015-04-29-foo.tex", "max_forks_repo_name": "wantee/octopress-printable", "max_forks_repo_head_hexsha": "9c5a13fb0e3f4472c88c844a257d3b86e8e3ef04", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8181818182, "max_line_length": 151, "alphanum_fraction": 0.723674655, "num_tokens": 916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.3348623646504356}}
{"text": "\\chapter{Principal component analysis}\n\\label{pca}\n\n\nThe origins of principal component analysis are usually traced to \\cite{Pearson:1901} who was concerned with the fitting planes in the analysis of covariance matrices by orthogonal least squares.   Much development of the technique is ascribed to \\cite{Hotelling:1933}, who, working with the correlation matrix provided another development of the technique which is more familiar.    As a technique in its own right it has received book length treatment by \\cite{Jackson:1991} and \\cite{Jolliffe:1986}; another excellent exposition is given in \\cite{Flury:1988} who also develops one generalisation of the technique to multiple groups.   The theory underlying principal components is important in a wide range of areas, consequently this chapter will examine some of the underlying theory as well as considering conventional approaches to principal component analysis.   An \\textbf{R}-centric selection of recent extensions to the technique will also be considered in the next chapter.\n\nPrincipal component analysis can be performed for a variety of reasons, one can perhaps consider its use in one of three ways.   Arguably the most common use is in terms of dimension reduction.   Principal component analysis can be thought of as a data analytic method which provides a specific set of projections\\index{projections} which represent a given data set in fewer dimensions.   This has obvious advantages when it is possible to reduce dimensionality to two or three as visualisation becomes very straightforward but it should be acknowledged that reduced dimensionality has advantages beyond visualisation.  Another rationale for conducting principal components analysis is to transform correlated variables into uncorrelated ones, in other words to \\emph{sphere} the data.   Whilst univariate data can be standardised by centering and scaling, in a multivariate context one may also wish to ``standardise'' the correlation between variables to zero.    The final rationale for the technique is that it finds linear combinations of data which have relatively large (or relatively small) variability.\n\n\\input{defs/pcbasic}\n\nWe are going to illustrate Principal Component Analysis by reference to three sets of data.   The first was presented by \\cite{Karlis+etal:2003} and relates to Heptathalon results from the Sydney Olympics in 2000.   In this event, athletes compete in seven different sporting activities, and clearly for the purposes of the competition a decision has to be made as to who is the best heptathelete overall.  For sporting purposes, points are awarded for performance in each event and summed.   In essence, a one dimensional composite variable has to be created from the results for the seven events before a decision can be made as to who wins the medals.   We are not necessarily going to challenge the way the International Olympic Committee calculates scores, but clearly a linear combination which achieved maximum separation of athletes might be interesting.   A trivial linear combination would be to take $\\boldsymbol{e} = \\frac{1}{n}\\boldsymbol{1}$.   However, the aim of any projection method is to find an \\emph{interesting} projection of the data.   All we need to do is decide what we mean by \\emph{interesting}.   As mentioned earlier, one use of principal components is to find projections where the variance is maximised, thus maximising the separation between heptatheletes.  \n\nThe second rather well used set of data relates to carapace measurements the painted turtle \\textit{Chrysemys picta marginata} first reported by \\cite{Jolicoeur+Mosimann:1960}.   These data contain 3 variables recording the shell length, width and height for 24 male and 24 female turtles.   We will consider these data partly because the turtles are cute, but mainly because it affords some consideration of the role of standardisation.   Standardising by subtracting mean and dividing by the standard deviation can be a rather brutal approach, it is possible to take the natural logarithms of these anatomical measures which allows a different insight into the relationship between the measures.\n\nFinally, we will investigate some gene expression data.   In microarray experiments, one typically collects data from a relatively small number of individuals, but records information on gene expression of a large number of genes and therefore have a data matrix $\\boldsymbol{X}$ where $n << p$.   Dimension reduction is a central concern at some stage of the analysis, either on the whole set of genes or on a selected subset.   As might become clear, groups of genes which can be identified analytically as co-expressing are referred to as eigengenes.   We will therefore consider some of the issues surrounding the interpretation of principal components in high dimensions.\n\nSome other data sets will be included to illustrate specific points where necessary, and the excercises will also develop other data sets.\n\n%Signature components - linear combinations of the genes that belong to that ocmponent  The first pc is the best 1d representation of a signature component, if genes in a signature component are tightly expressed they will show high correlelation with the pc.  But orthogality, lack of correlation and indepence may be unnecessary requirements. - find loadings and rotate   Simple pca cannot be used with p >> n    -- but we don't want to explain max variance we really want max correlation.\n\n\n\\section{Derivation of Principal Components}\n\nWe will firstly consider the derivation of population principal components in the style proposed by \\cite{Hotelling:1933} as a way of finding linear combinations with maximum variance.   Given that we have a random vector $\\boldsymbol{x} \\in \\mathbb{R}^{P}$, we wish to consider the vector of transformed variables $\\boldsymbol{z} = \\boldsymbol{\\alpha}^{T}(\\boldsymbol{x} - \\boldsymbol{\\bar{x}})$, and so we wish to find $\\alpha$ such that the $\\mbox{Var}(z)$ is maximised.  By convention, we insist that $\\boldsymbol{\\alpha}$ is orthonormal, i.e. in addition to being a vector of unit length we require that $\\boldsymbol{\\alpha}^{T}\\boldsymbol{\\alpha} = 1$.   To find an expression for $\\mbox{Var}(z)$ in terms of the original variables $\\boldsymbol{x}$, firstly by considering the following relationship:\n\\begin{displaymath}\n\\mbox{Var}(\\boldsymbol{z}) = \\mbox{Var}(\\boldsymbol{\\alpha}^{T}\\boldsymbol{x}) = E(\\boldsymbol{\\alpha}^{T}\\boldsymbol{x})^{2}\n\\end{displaymath}\nHence,\n\\begin{displaymath}\n\\sum_{i+1}^{n}(\\boldsymbol{z}_{i} - \\boldsymbol{\\bar{z}})^{2} = \\sum_{i=1}^{n}\\boldsymbol{\\alpha}^{T}\\left[(\\boldsymbol{x}_{i} - \\boldsymbol{\\bar{x}})(\\boldsymbol{x}_{i} - \\boldsymbol{\\bar{x}})^{T}\\right] \\boldsymbol{\\alpha}\n\\end{displaymath}\nand premultiplying both sides by $\\frac{1}{n-1}$ gives us an estimate of the variance of the transformed variables in terms of the original variables.  To find $\\boldsymbol{\\alpha}$ in order to maximise the variance we therefore wish to find:  \n\\begin{equation}\n\\mbox{max}(\\boldsymbol{\\alpha}^{T}\\boldsymbol{\\hat{\\Sigma}}\\boldsymbol{\\alpha})\n\\end{equation}\nsubject to the side condition that $\\boldsymbol{\\alpha}^{T}\\boldsymbol{\\alpha}= 1$.   Considering the first principal component, we wish to maximise $\\mbox{Var}(z_{1}) = \\boldsymbol{\\alpha}_{1}^{T}\\boldsymbol{\\hat{\\Sigma}}\\boldsymbol{\\alpha}_{1}$; it can be shown that this problem can be specified by incorporating a Lagrange multiplier.   Consider maximising the expression $\\varphi$ given below, where $\\lambda$ is a Lagrange multiplier:\n\\begin{equation}\n\\varphi_{1} = \\boldsymbol{\\alpha}_{1}^{T}\\boldsymbol{\\hat{\\Sigma}}\\boldsymbol{\\alpha}_{1} - \\lambda_{1}(\\boldsymbol{\\alpha}_{1}^{T}\\boldsymbol{\\alpha}_{1} - 1)\n\\end{equation}\nwhich can be solved by differentiation with respect to $\\boldsymbol{\\alpha}_{1}$.   The differential gives us a system of linear equations as follows:\n\\begin{equation}\n\\frac{\\partial \\varphi_{1}}{\\partial \\boldsymbol{\\alpha}_{1}} = 2 \\Sigma \\boldsymbol{\\alpha}_{1} - 2 \\lambda \\boldsymbol{\\alpha}_{1}\n\\end{equation}\nand setting the derivative equal to zero gives:\n\\begin{equation}\n\\boldsymbol{\\Sigma} \\boldsymbol{\\alpha}_{1} = \\lambda_{1} \\boldsymbol{\\alpha}_{1}\n\\end{equation}\nwhich is easily rearranged to give:\n\\begin{equation}\n(\\boldsymbol{\\Sigma} - \\lambda_{1} \\boldsymbol{I})\\boldsymbol{\\alpha} = 0.\n\\end{equation}\n\nWe have $p$ equations and $p$ unknowns, but we can find non-trivial solutions where $\\boldsymbol{\\alpha} \\neq \\boldsymbol{0}$ noting that if  $\\boldsymbol{a}_{1}^{T}\\boldsymbol{a}= 1$ then $\\boldsymbol{\\Sigma} - \\lambda \\boldsymbol{I}$ is singular which therefore implies that:\n\\begin{equation}\n|\\boldsymbol{\\Sigma} - \\lambda_{1} \\boldsymbol{I}| = 0\n\\end{equation}\n\nThis looks like an eigenproblem, so $\\lambda_{1}$ can be found as the largest eigenvalue of $\\boldsymbol{\\Sigma}$, and $\\boldsymbol{\\alpha}_{1}$ as the corresponding eigenvector.\n\nFor the second principal component, as we are going to assume orthogonality, we wish to add the side condition that $\\mbox{Cor}(z_{1},z_{2}) = 0$.   We therefore need to solve:\n\n\\begin{equation}\n\\varphi_{2} = \\boldsymbol{\\alpha}_{2}^{T}\\boldsymbol{\\hat{\\Sigma}}\\boldsymbol{\\alpha}_{2} - \\lambda_{2}(\\boldsymbol{\\alpha}_{2}^{T}\\boldsymbol{\\alpha}_{2} - 1) - \\mu(\\alpha_{1}^{T}\\boldsymbol{\\Sigma}\\boldsymbol{\\alpha_{2}})\n\\end{equation}\nwhere differentiating now gives:\n\\begin{equation}\n\\label{pca2diff}\n\\frac{\\partial \\varphi_{2}}{\\partial \\boldsymbol{\\alpha}_{2}} = 2 \\Sigma \\boldsymbol{\\alpha}_{2} - 2 \\lambda_{2} \\boldsymbol{\\alpha}_{2} - \\mu \\boldsymbol{\\Sigma} \\boldsymbol{\\alpha}_{1}\n\\end{equation}\nbut as we assume $\\mbox{Cor}(z_{1},z_{2}) = 0$ we take $\\boldsymbol{\\alpha}_{2}^{T}\\boldsymbol{\\Sigma}\\boldsymbol{\\alpha}_{1} = \\boldsymbol{\\alpha}_{1}^{T}\\boldsymbol{\\alpha}_{2} = 0$ implying that $\\boldsymbol{\\alpha}_{1}^{T}\\boldsymbol{\\alpha}_{2} = \\boldsymbol{\\alpha}_{2}^{T}\\boldsymbol{\\alpha}_{1} = 0$ hence we can premultiply our equation in \\ref{pca2diff} by $\\boldsymbol{\\alpha}_{2}$ giving:\n\\begin{equation}\n\\label{pca2diff2}\n2 \\boldsymbol{\\alpha}_{2}^{T} \\Sigma \\boldsymbol{\\alpha}_{2} - 2 \\boldsymbol{\\alpha}_{2}^{T} \\lambda_{2} \\boldsymbol{\\alpha}_{2} - \\mu \\boldsymbol{\\alpha}_{2}^{T} \\boldsymbol{\\Sigma} \\boldsymbol{\\alpha}_{1}\n\\end{equation}\nwhich implies that $\\mu=0$, and that $\\lambda_{2}$ is also an eigenvalue of $\\boldsymbol{\\Sigma}$.\n\nClearly in any formal sense we should continue this process, but the apparent pattern can be demonstrated.   To find further principal components we need to take the spectral decomposition of the covariance matrix, subject to normalising the eigenvectors to have unit length.   In order to find principal components which have maximum variance subject to the condition of being orthogonal to any previous principal component we only need to solve:\n\\begin{displaymath}\n|\\boldsymbol{\\Sigma} - \\lambda \\boldsymbol{I}| = 0\n\\end{displaymath}\nand to find:\n\\begin{displaymath}\n\\boldsymbol{\\Sigma} \\boldsymbol{\\alpha} = \\lambda \\boldsymbol{\\alpha}\n\\end{displaymath}\n\nOf some interest to us is that if any matrix $\\boldsymbol{\\Sigma}$ is symmetric (which will always be the case for correlation and covariance matrices), the normalised eigenvectors corresponding to unequal eigenvalues are orthonormal.\n\nIn practice, we don't know $\\Sigma$ and we have to estimate it from our data with a suitable estimate.   We can consider a number of possibilities, indeed we will examine robust estimators later.   However, most development of principal components assume the unbiased estimator $\\boldsymbol{S} = \\frac{1}{n-1} \\boldsymbol{X}^{T}\\boldsymbol{X}$, where $\\boldsymbol{X}$ is a matrix of mean centred data, although we will note later that one of the \\textbf{R} functions actually uses $\\boldsymbol{S} = \\frac{1}{n} \\boldsymbol{X}^{T}\\boldsymbol{X}$.   $\\boldsymbol{\\mu}$ is readily estimated from the sample mean.   However, before considering applications to sample principal components, we make a few comments on the geometry of this technique.\n\n\\subsection{A little geometry}\n\nWhilst we have covered the variance maximising property of principal components, it is possible to consider the technique from a geometric perspective.   Geometry is perhaps rather more important in recent developments in principal components, details on the concept of \\emph{self-consistency} are given by \\cite{Flury:1997}. For now, we note that from a geometrical perspective we wish to minimise the perpendicular distance between points and the new projection, the same problem \\cite{Pearson:1901} was solving.\n\nConsider the vector of observations $\\boldsymbol{x} = (x_{1}, \\ldots, x_{p}) \\in \\mathbb{R}_{p}$   We want to project these obsevations onto $\\lambda \\boldsymbol{\\alpha}$, and in doing so to find the best fitting $q$ dimensional subspace.   Denoting the projection of $\\boldsymbol{x}$ by $P\\boldsymbol{x}$, we therefore wish to minimise:\n\\begin{displaymath}\n(\\boldsymbol{z} - P\\boldsymbol{x})^{T}(\\boldsymbol{z} - P\\boldsymbol{x})\n\\end{displaymath}\n\nIdeally, we wish the projection to be performed in terms of $\\boldsymbol{\\alpha} = (\\alpha_{1}, \\ldots, \\alpha_{q})$, although with a $p$ dimensional representation this can clearly take the form $(\\alpha_{1}, \\ldots, \\alpha_{q}, \\alpha_{q+1}, \\alpha_{p})$.  \n\nThe projection can be given as \n\\begin{displaymath}\nP\\boldsymbol{x} = \\boldsymbol{x} \\boldsymbol{\\alpha}^{T}\\boldsymbol{\\alpha}\n\\end{displaymath}\nwhere $\\boldsymbol{\\alpha}^{T}\\boldsymbol{\\alpha}$ can be described as the projection matrix.   We can rewrite this as:\n\\begin{displaymath}\nP\\boldsymbol{x} = \\sum_{1}^{q} (x_{i} \\boldsymbol{\\alpha}_{i}^{T})\\boldsymbol{\\alpha}_{i}.   \n\\end{displaymath}\nWe can therefore rewrite $\\boldsymbol{z} - P\\boldsymbol{x}$ as \n\\begin{displaymath}\n\\boldsymbol{z} - P\\boldsymbol{x} = \\sum_{q+1}^{p}(x_{i}^{T} \\boldsymbol{\\alpha}_{i})\\boldsymbol{\\alpha}_{i}\n\\end{displaymath}\nClearly\n\\begin{displaymath}\n(\\boldsymbol{z} - P\\boldsymbol{x})^{T}(\\boldsymbol{z} - P\\boldsymbol{x}) = \\sum_{q+1}^{p}(x_{i}^{T}\\boldsymbol{\\alpha}_{i})^{2}\n\\end{displaymath}\n\nConsequently, we wish to minimise \n\n\\begin{displaymath}\n\\sum_{j=1}^{p} \\sum_{i=1}^{n} (x_{j}^{T}\\alpha_{i})^{2}\n\\end{displaymath}\n\nWhich is Pearson's orthogonal least squares problem.  However, we can find a link with Hotelling's approach by noting that $\\sum_{j=1}^{n}x_{j}^{T}x_{j} = \\sum_{j=1}^{p} \\sum_{i=1}^{n} (x_{j}^{T}a_{i})^{2}$ our problem can also be expressed as one where we wish to maximise\n\n\\begin{displaymath}\n\\sum_{j=1}^{p} \\sum_{i=1}^{n} (x_{j}^{T}\\boldsymbol{\\alpha}_{i})^{2}\n\\end{displaymath}\n\nNoting that this last term is $\\sum_{i=1}^{q} \\boldsymbol{\\alpha}_{i}^{T} \\boldsymbol{X}\\boldsymbol{X}^{T} \\boldsymbol{\\alpha}_{i}$, it might be apparent that we actually seek to find $\\boldsymbol{\\alpha}$, subject to $\\boldsymbol{\\alpha}^{T}\\boldsymbol{\\alpha} = \\delta$ to maximise $\\boldsymbol{\\alpha}^{T}\\boldsymbol{\\Sigma}\\boldsymbol{\\alpha}$ which looks like a familiar problem!\n\nIt may now be noted that the eigenvectors are related to the angle between the untransformed data and the principal component.   Assuming we have $j = 1, \\ldots, p$ variables, and $k = 1, \\ldots, p$ projections, this angle is given by:\n\\begin{equation}\n\\cos \\theta_{jk} = \\alpha_{jk}\n\\end{equation}\nThis is reasonably convenient to plot in 2-dimensions.   Given simulating bivariate data $\\boldsymbol{x} = (x_{1}, x_{2})$, the angle between $x_{1}$ and the first principal component is given by $\\cos \\theta_{11} = \\alpha_{11}$.   Rather conveniently, this is implicit in the slope \\verb+b=+ supplied to \\verb+abline()+.   An illustration of orthogonal projection can be explored using the following code.   This should be contrasted with the least squares fit.\n\n\\begin{figure}\n\\includegraphics[width = 0.7\\textwidth]{images/ProjDist}\n\\caption{Illustration of perpendicular distance}\n\\label{projection}\n\\end{figure}\n\n\\singlespacing\n\\begin{verbatim}\nrequire(MASS)\nX <- scale(mvrnorm(25, c(2,2), matrix(c(1,0.8,0.8,1),2,2)))\neqscplot(X)\nX.cov <- cov(X)\nX.ed <- eigen(X.cov)\nproj <- X.ed$vec[,1] %*% t(X.ed$vec[,1])\ny <- t(proj %*% t(X))\nabline(a=0,b=X.ed$vec[2,1]/X.ed$vec[1,1])\narrows( X[,1], X[,2], y[,1],y[,2], length = 0.05, col = \"green\")\n\\end{verbatim}\n\\onehalfspacing\n\nPlotting the ordinary least squares solutions is easy enough, although when regression X[,1] on X[,2] the gradient needs to be inverted (or the axes reversed).\n\n\\singlespacing\n\\begin{verbatim}\n## plot the ols of X[,2] on X[,1]\neqscplot(X)\nX2.lm <- lm(X[,2] ~ X[,1])\nabline(X2.lm, col = \"red\", lwd = 2)\narrows(X[,1],X[,2], X[,1], predict(X2.lm),  length = 0.01, col = \"red\")\npoints(X[,1],X[,2], pch = 16)\n## plot the ols of X[,1] on X[,2]\neqscplot(X)\nX1.lm <- lm(X[,1] ~ X[,2])\nabline(0, 1/coef(X1.lm)[2], col = \"blue\")## need to invert the gradient\narrows(X[,1],X[,2], predict(X1.lm), X[,2],  length = 0.01, col = \"blue\")\npoints(X[,1],X[,2], pch = 16)\n\\end{verbatim}\n\\onehalfspacing\n\n\nIt is informative to contrast the line plotted in figure \\ref{projection} with those produced by linear regression of $x$ on $y$ as well as $y$ on $x$.\nThe matrix $ \\boldsymbol{a} \\boldsymbol{a}^{T} $ can be referred to as the projection matrix.   \n\n\\subsection{Principal Component Stability}\n\\label{sec:pcastability}\n\nWhilst considering the geometry, it is useful to motivate some ideas about the differences between population and sample principal components by simulating three datasets from the same parameters.   For population 1, we draw from standard normal variables with correlation of 0.9, for population 2 the variables are uncorrelated.   In other words, $\\boldsymbol{\\mu}_{1} = \\boldsymbol{\\mu}_{2} = (0,0)^{T}$, $\\boldsymbol{\\Sigma}_{1} = \\left(\\begin{array}{rr} 1 & 0.9 \\\\ 0.9 & 1 \\end{array} \\right)$ but $\\boldsymbol{\\Sigma}_{2} = \\left(\\begin{array}{rr} 1 & 0 \\\\ 0 & 1 \\end{array} \\right)$\n\nSimulating the data is simple enough, for example:\n\\singlespacing\n\\begin{verbatim}\nX <- mvrnorm(100, c(0,0), matrix(c(1,.9,.9,1),2,2))\nV <- var(X)\neV <- eigen(V)\n\\end{verbatim}\n\\onehalfspacing\n\n\\singlespacing\n\\begin{verbatim}\nplot(X, xlim = c(-3,3), ylim = c(-3,3))\nabline(a=0,b=eV$vec[2,1]/eV$vec[1,1])\nabline(a=0,b=eV$vec[2,2]/eV$vec[1,2])\n\\end{verbatim}\n\\onehalfspacing\n\nJust so the eigenvalues don't feel left out, we can add constant density ellipses to these plots, details on these were given in \\ref{cdellipse}.  Essentially, we can define a constant density ellipse from the ``centre'' as $\\pm c \\sqrt{\\lambda_{i}} \\boldsymbol{\\alpha}_{i}$, here we take $c=1.96$.   In the code snippet below, \\verb+x+ and \\verb+y+ are the coordinates of an ellipse scaled from a unit circle by the two eigenvalues.   These are then rotated by the angles of the eigenvectors:\n\n\\singlespacing\n\\begin{verbatim}\ntheta <- seq(0,(2*pi),length=101)\nx <- 1.96 * sqrt(eV$val[1]) * cos(theta)\ny <- 1.96 * sqrt(eV$val[2]) * sin(theta)\nnewxy <- cbind(x,y) %*% t(eV$vec)\nlines(newxy)\n\\end{verbatim}\n\\onehalfspacing\n\nWe now consider figure \\ref{pcastabsynth}, which overlays three samples from each of the two populations specified.   The semi-major axis, the contribution to the first principal component has been denoted with solid lines, the semi-minor axis, the contribution to the second principal component, has been denoted by dotted lines.   It should be very apparent that there is some variation in the orientation of the axes, as might be expected the eigenanalysis varies slightly according to sample properties.   However, the right hand side of the plot is intended to illustrate the problem of sphericity.   Without a strong correlation structure, the angles subtended by the principal components varies massively.\n\n\\begin{figure}\n\\includegraphics[width = 0.9\\textwidth]{images/pcastability}\n\\caption{Artificially generated data indicating stablity of pca solution}\n\\label{pcastabsynth}\n\\end{figure}\n\nWhilst this is an artificial example in many senses (not only are the data simulated but we have only two variables), but the problem is an important one.   In particular, when exploring dimension reduction properties of principal components we have to be attendant to the possibility of partial sphericity; that some of the $q+1, \\ldots, p$ principal components essentially exhibit this behaviour.   We consider specific hypothesis tests for this problem later.\n\n\nFinally, whilst talking about projections, we make one comment in relation to projection pursuit.   This technique will be considered further in the next chapter.   Suffice to say here that projection pursuit is a generic set of techniques which aims to find ``interesting'' projections of data.   The user decides on the dimensionality of the projection and selects a suitable criterion of interestingness.  \\cite{Bolton+Krzanowski:1999} give results interpreting principal components analysis within this framework, the criterion (projection pursuit index) in this case is given by:\n\n\\begin{displaymath}\nI = max(\\boldsymbol{e} \\boldsymbol{S} \\boldsymbol{e}^{T}); \\boldsymbol{e}\\boldsymbol{e}^{T}=1,\n\\end{displaymath}\nwhere $\\boldsymbol{S}$ is the sample covariance matrix.   This index is the minimum of the maximised log-likelihood over all projections when normality is assumed.\n\nHowever, they go on to imply that more ``interesting'' projections are less likely to have normally distributed data by showing that in terms of the likelihood$\\mathscr{L}(\\boldsymbol{e})$, this decreases as $\\boldsymbol{e} \\boldsymbol{S} \\boldsymbol{e}^{T}$ increases.  Assuming the usual maximum likelihood estimators for $\\boldsymbol{\\mu}$ and $\\boldsymbol{\\Sigma}$:\n\\begin{eqnarray*}\n\\mathscr{L}(\\boldsymbol{e}) &=& max \\mathscr{L} (\\boldsymbol{x}; \\boldsymbol{\\mu}, \\boldsymbol{\\Sigma}, \\boldsymbol{e})\\\\\n&=& - \\frac{n}{2} \\left[ p + p \\log \\left(\\frac{2 \\pi n}{n-1}\\right) \\right] - \\frac{n}{2} \\log |\\boldsymbol{e} \\boldsymbol{S} \\boldsymbol{e}^{T}|\n\\end{eqnarray*}\nIn other words, under normality, the most ``interesting'' projection is the one with the maximised likelihood.\n\n\n\\section{Some properties of principal components}\n\nBefore considering some examples of principal component analysis we first consider a number of fundamental properties.\n\n\\input{defs/prcompdef.tex}\n\nA number of key propeties immediately follow from their derivation from the spectral decomposition:\n\n\\input{defs/prcompbasics}\n\nOne property we will make repeated use of concerns the proportion of variance explained by each principal component:\n\n\\input{defs/eigentrace}\n\nIn other words, equation~\\ref{eigentrace} indicates that the \\emph{total variance} can be explained by the sum of the eigenvalues.   In the case of principal components formed from the correlation matrix $\\boldsymbol{R}$ this will be equal to the number of variables.\n\n\n\\input{defs/eigenproducts}\nTheorem \\ref{th:eigenproduct} indicates that we can find an estimate of the \\emph{generalised variance} from the product of the eigenvalues.   Along with theorem \\ref{th:eigentrace} we find that the generalised variance and the sum of variances are unchanged by the principal component transformation.   \n\nFinally, a note is needed on scale-invariance.   \\cite{Flury:1997} describes this last as an anti-property.   Principal components are not-invariant to changes of scale.   Standardising variables is rather a brutal way of dealing with this.   Explanations are given in most multivariate textbooks, for example both formal and information explanaitions are given by [page 219] \\cite{Mardia+etal:1979}.   Nevertheless, if variables are recorded on widely differing scales, a principal component analysis of the covariance matrix will largely reflect the variables with the numerically greatest variance.   It is therefore important that the variables are in some sense comparable; this can either be achieved by standardising, or by some gentler transformation.   We will find that the heptathalon data has to be standardised, whereas it is possible to take logs of the turtle data.\n\n\nFinally, we consider one important property, which is more in the \\cite{Pearson:1901} sense.   \n\n\\begin{theorem}\nThe first $k$ principal components have smaller mean squared departure from the population (or sample) variables than any other $k$-dimensional subspace.\n\\end{theorem}\nProof: [page 220] \\cite{Mardia+etal:1979}\n\nThis property is rather important when considering the dimension reducing properties of principal component as it does not require any distributional assumptions.\n\n\n\n\\section{Illustration of Principal Components}\n\n We define the sample principal components by $\\boldsymbol{e}$ and $\\ell$.\n\nHaving now hopefully explained the rationale behind principal components analysis, we consider some illustrative analysis before considering further inferential developments.\n\n\\subsection{An illustration with the Sydney Heptatholon data}\n\nBefore doing anything else with these data, it needs to be noted that in the three running events, better performance is indicated by a lower measure (time), whereas in the jumping and throwing events good performance is indicated by a higher measure (distance).   It seems sensible to introduce a scale reversal so that good performance is in some way at the top of any given scale.   A convenient way of doing this is to multiply the times of the running events by $-1$.\n\n\\singlespacing\n\\begin{verbatim}\nhept.df <- read.csv(\"Heptatholon.csv\", row.names = 1)\nhept.df$X100mHurdles.S. <- hept.df$X100mHurdles.S. * -1\nhept.df$X200m.sec. <- hept.df$X200m.sec. * -1\nhept.df$r800m.s. <- hept.df$r800m.s. * -1\n\\end{verbatim}\n\\onehalfspacing\n\nThese variables are clearly incomparably in any sense.    It is also clear that we need to work with the correlation matrix for these data, there is considerable difference in the scales (running 800 metres tends to take rather longer than running 100 metres).   We will also centre the variables using \\verb+scale()+ which saves us a little work later on.  \n\n\\singlespacing\n\\begin{verbatim}\nhep.scale <- scale(hept.df[,-1])\nhept.cormat <- cor(hept.df[,-1])\nhep.ev <- eigen(hept.cormat)\n\\end{verbatim}\n\\onehalfspacing\n\nOur principal component analysis then basically consists of extracting \\verb+hep.ev$values+ contains the eigenvalues, and \\verb+hep.ev$vectors+ contains the eigen vectors.   Our first set of loadings are given by the first row of the eigenvectors, we can form the first linear combination:\n\n\\singlespacing\n\\begin{verbatim}\n> hep.ev$vectors[,1]\n> z1 <- hep.scale %*% hep.ev$vectors[,1]\n\\end{verbatim}\n\\onehalfspacing\n\nin a similar manner it is possible to form $z_{2}$ and so on.  \n\n\nThis means that the proportion of total variance explained by each linear combination can be given by $\\frac{\\lambda_{i}}{ \\sum_{i=1}^{p} \\lambda_{i}}$\n, which can be calculated for our heptathalon data with \\verb+hep.ev$values/sum(hep.ev$values)+.   It is also conventional to produce a ``scree'' plot of this information with something like \\verb+plot(hep.ev$values, type = \"b\")+ which graphically represents the amount of variance explained by each linear combination.\n\n%par(las = 1)\n%plot(hep.ev$values, type = \"b\", main = \"Scree plot from Heptathalon data\", ylab = \"Variance explained\", xlab = \"Principal component\", pch = 16)\n\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width = 0.5\\textwidth]{images/HeptathScree} \n\\caption{Scree plot displaying the amount of variation explained by each of the seven principal components formed from the correlation matrix of the Sydney Heptathalon data}\n\\label{screeplot}\n\\end{center}\n\\end{figure}\n\n\n\\subsection{Principal component scoring}\n\nAs stated at the start of the chapter, the principal component scores are essentially derived from the mean centered data.   \n\nIn other words, we found:\n\n\\begin{equation}\n\\label{pcascore}\n\\boldsymbol{z} =  \\boldsymbol{E}^{T}(\\boldsymbol{x}-\\boldsymbol{\\mu})\n\\end{equation}\n\nIt is possible (although somewhat unusual in this context) to find scores from the standardised data\n\n\\begin{equation}\n\\boldsymbol{z} =  \\boldsymbol{E}^{T}(\\boldsymbol{x}-\\boldsymbol{\\mu})  \\boldsymbol{\\Lambda}^{-1/2}\n\\end{equation}\n\nIt should be noted that \\cite{Rencher:2002} really doesn't approve of this latter effort, it essentially leaves us looking at the correlation between the standardised data and the principal component scores.   We therefore consisder the more usual scores given in equation \\ref{pcascore}.   The first four eigenvectors are given as follows:\n\n\\singlespacing\n\\begin{verbatim}\n$vectors\n           [,1]        [,2]        [,3]         [,4]\n[1,] -0.4656494  0.28868133  0.32883275 -0.003922038  \n[2,] -0.2455859 -0.56442826 -0.10737271 -0.610427608  \n[3,] -0.4195748 -0.07137064 -0.52173345  0.235891780 \n[4,] -0.4330174 -0.02204083  0.51825157  0.357022268 \n[5,] -0.4630436  0.11516723  0.12459693 -0.480637087 \n[6,] -0.3228125  0.38161226 -0.56832241  0.091073036 \n[7,] -0.2017272 -0.65849286 -0.03216966  0.452710298 \n\\end{verbatim}\n\\onehalfspacing\n\nSo to find the first principal component we only need to compute the following:\n\n\\begin{displaymath}\nz_{i1} = a_{11} x_{i1} + a_{12} x_{i2} + a_{13} x_{i3} + \\ldots\n\\end{displaymath}\n\nwhich means that the first principal component can be given as:\n\n\\begin{displaymath}\nZ_{i1} = -0.4656 \\times x_{1} - 0.2456 \\times x_{2} - 0.4196 \\times x_{3} + \\ldots\n\\end{displaymath}\n\nClearly this can also be calculated as matrix product $\\boldsymbol{X}\\boldsymbol{a}$.\n\n\\singlespacing\n\\begin{verbatim}\nhep.ev$vectors[,1] ## first vector of pc loadings\nscores <- hep.scale %*% hep.ev$vectors\npar(mfrow = c(3,3))\napply(scores, 2, qqnorm)\nscoresR <- hep.scale %*% (hep.ev$vectors %*% diag(hep.ev$values^-0.5))\n\\end{verbatim}\n\\onehalfspacing\n\nIf we wished, we can carry out further investigation of the principal component scores.\n\n\n\\subsection{Prepackaged PCA function 1: \\texttt{princomp()}}\n\nIn practice it will come as no surprise to learn that there are prepackaged functions in \\textbf{R} for carrying out a principal components analysis.   \\verb+princomp()+ has been provided for comparability with S-Plus.  We will find out later that the preferred function uses the singular value decomposition.   However, there are good reasons for examining \\verb+princomp()+ first.    It is based on carrying out an eigen decomposition, by default of the covariance matrix and it should be noted that the covariance matrix esimated by \\verb+cov.wt+ uses the divisor $N$, rather than the unbiased version $N-1$.    It is possible to supply robust estimates of the covariance matrix via \\verb+covmat+, this does allow a form of robust principal components and as we work through the heptathalon data we will find out that this may indeed be useful.  \nIt is possible to call \\verb+princomp()+   with the specification \\verb+cor=TRUE+ to use the sample correlation matrix rather than sample covariance matrix.\n\nThe main results can be accessed via \\verb+summary()+ and \\verb+print()+.   The eigenvectors are extracted and printed with a degree of pretty printing using \\verb+loadings()+.   If necessary, the square roots of the eigenvalues (i.e. the standard deviations of each principal component) are stored within the princomp object and can be extracted manually using \\verb+$sdev+.   The principal component scores themselves can be accessed via \\verb+$scores+ if these have been requested.    There are also graphical methods associated with \\verb+princomp()+ objects, \\verb+plot()+ produces a screeplot, \\verb+biplot()+ produces a biplot, we explain this tool further in section~\\ref{prcomp}.   However, we note an important aspect of eigenanalysis, which is very clearly stated in the helpfile and will be quite important later:\n\\begin{quote}\nThe signs of the columns of the loadings and scores are arbitrary, and so may differ between different programs for PCA, and even  between different builds of R.\n\\end{quote}\nThis is a point we will return to a few times particularly when considering bootstrapping!\n\nExecuting a principal component analysis is therefore trivial, as demonstrated in the following code snippet.   We extract the principal component scores and create qq plots; as demonstrated in chapter 2 any univariate linear combination of multivariate normal data should be normally distributed.  \n\n\\singlespacing\n\\begin{verbatim}\nhept.princomp <- princomp(hept.df[,-1], scale = TRUE)\nsummary(hept.princomp)\nplot(hept.princomp) ## produces scree plot\npar(mfrow = c(3,3))\napply(hept.princomp$scores, 2, qqnorm)\n\\end{verbatim}\n\\onehalfspacing\n\n\n\\subsection{Inbuilt functions 2: \\texttt{prcomp()}}\n\\label{prcomp}\n\nThe preferred \\textbf{R} function for a conventional principal component analysis is \\verb+prcomp()+.   There are a number of differences in use and extraction, but the rather more important difference is that it is based upon a singular value decomposition of the data.   The singular value decomposition was outlined in Section~\\ref{svd}.   Whilst discussing the singular value decomposition in this context it is convenient to introduce the biplot.   \\cite{Gabriel:1971} introduced the biplot as a means of representing either a matrix of rank two, or a rank two approximation to a matrix of rank greater than two.   The idea is to display vectors for each row and vectors for each column are displayed on the same plot, illustrating features of either a rank two matrix or a rank two approximation.   Whilst we illustrate it in detail here, it has application in areas other than with principal components.\n\nAs discussed earlier, we consider data matrix $\\boldsymbol{X}$; it's decomposition is given by:\n\\begin{displaymath}\n\\boldsymbol{X} = \\sum_{i=1}^{p} \\lambda_{i} \\boldsymbol{u}_{i} \\boldsymbol{v}_{i}^{T}\n\\end{displaymath}\nand hence for the biplot, where we specifically require a rank two solution:\n\\begin{displaymath}\n\\boldsymbol{X} = \\sum_{i=1}^{2} \\lambda_{i} \\boldsymbol{u}_{i} \\boldsymbol{v}_{i}^{T} = \n\\left( \\boldsymbol{u}_{1},  \\boldsymbol{u}_{2} \\right) \n\\left( \\begin{array}{cc} \\lambda_{1} & 0 \\\\ 0 & \\lambda_{2} \\end{array} \\right) \\left( \\begin{array}{c} \\boldsymbol{v}_{1}^{T} \\boldsymbol{v}_{2}^{T} \\end{array} \\right)\n\\end{displaymath}\n\nBased on this decomposition, we have a choice of plots.   In general, we can plot:\n\\begin{displaymath}\n\\boldsymbol{g}_{i}^{T} = \\lambda_{1}^{1-\\zeta} u_{1i}, \\lambda_{1}^{1-\\zeta} u_{2i}\n\\end{displaymath}\nfor the observations\nand\n\\begin{displaymath}\n\\boldsymbol{h}^{T}_{j} = \\lambda_{1}^{\\zeta} q_{1j} \\lambda_{2}^{\\zeta} q_{2j}\n\\end{displaymath}\nfor the columns.\nwhere $0 \\leq \\zeta \\leq 1$.   \\cite{Gabriel:1971} essentially gave proposals for $\\zeta = 0$, $\\zeta = 0.5$ and $\\zeta = 1$.   In \\textbf{R}, these can be set with the argument \\verb+scale+ which takes the range $0 \\leq \\mbox{scale} \\leq 1$.   The default is \\verb+scale = 1+ which implies $\\boldsymbol{H}^{T}\\boldsymbol{H} = \\boldsymbol{I}$; more notably this means that the inner products between variables approximate covariances and distances between observations approximate Mahalanobis distance.    By default, observations are scaled up by $\\sqrt{n}$, variables are scaled down by $\\sqrt{n}$\n\nIt is possible to adjust \\verb+choices=c(1,2)+ if you don't really want a biplot but want to examine the projection of what are in this context other principal components.\n\n\n\\singlespacing\n\\begin{verbatim}\npairs(turtles[,-1],\n   lower.panel = function(x, y){ points(x, y,\n   pch = unclass(turtles[,1]),\n   col = as.numeric(turtles[,1]))},\n   main = \"Pairwise scatter plots for painted turtles\")\n\\end{verbatim}\n\\onehalfspacing\n\nWe follow \\cite{Flury:1997} in transforming these data onto the log scale (and multiplying them by 10).   This is quite common in allometric applications, where the $\\log$ transformation may suffice in terms of bringing all variables onto a comparable scale.\n\n\\singlespacing\n\\begin{verbatim}\ndata(turtles)\n  turtles.m <- subset(turtles, turtles$Gender == \"Male\")\n  turtles.m <- 10 * log(turtles.m[,-1])\n  turtles.m.prcomp <- prcomp(turtles.m)\n  summary(turtles.m.prcomp)\nplot(turtles.m.prcomp)\nturtles.m.prcomp$sdev^2 ## extract eigenvalues\npar(xpd = NA)\nbiplot(turtles.m.prcomp)\n\\end{verbatim}\n\\onehalfspacing\n\n%turtles.prcomp <- prcomp(turtles[,-1])\n%plot(turtles.prcomp$x[,1], turtles.prcomp$x[,2],\n% col = as.numeric(turtles[,1]),\n% pch = as.numeric(turtles[,1]))\n\nWe can illustrate the biplot as follows by carrying out the various computations by hand within \\textbf{R}:\n\n\\singlespacing\n\\begin{verbatim}\nturtles.svd <- svd(turtles.m)\nH <- cbind(turtles.svd$u[,1], turtles.svd$u[,2]) * sqrt(24)\ng1 <- turtles.svd$d[1] * turtles.svd$v[,1] / sqrt(24)\ng2 <- turtles.svd$d[2] * turtles.svd$v[,2] / sqrt(24)\nplot(H)\npar(new = TRUE)\nplot(c(-arrx,arrx),c(-arry,arry), type = \"n\",\n  xaxt = \"n\", yaxt = \"n\")\naxis(3)\naxis(4)\narrows(0, 0, arrx, arry)\n\\end{verbatim}\n\\onehalfspacing\n\n\n\\section{Principal Components Regression}\n\nFinally, we say a few words about principal components regression, and illustrate the use of principal components in bioinformatics with the superpc package.\n\n\n\\section{``Model'' criticism for principal components analysis}\n\nThis section has deliberately given a provocative title.   ``Model'' criticism clearly requires some kind of model, it is worth giving some thought to whether we are using a principal components model in the context of a model or not.   It is possible to use the technique as a data analytical technique, particularly when used for data reduction there is no necessity to assume multivariate normality.   However, when we are using it in the context of a multivariate normal distribution, it is important to be aware of a number of key distributional results on the asymptotic distribution of the eigenvalues and eigenvectors of a covariance matrix.\n\n\n\\subsection{Distribution theory for the Eigenvalues and Eigenvectors of a covariance matrix}\n\n\\cite{Girshink:1939,Anderson:1963} give results for asymptotic distributions in connection with the covariance matrix.   Firstly, we comment on the existence of maximum likelihood estimators for the eigendecomposition of a covariance matrix:\n\n\\input{defs/evalmle}\n\nTheorem \\label{th:evalmle} indicates that our sample eigenvalues are the maximum likelihood estimators of their corresponding population counterparts.   In most inferential situations we would wish to qualify such an estimator with guidance as to the level of associated uncertainty.   Firstly, we wish to establish the distribution of the eigenvalues.\n\n\\input{defs/pcasymptotics}\n\nTheorem \\ref{pcasymptotics} indicates that for large $n$, the eigenvalues $\\lambda_{i}$ are independently distributed.   We can therefore obtain standard errors for the eigenvalues as follows:\n%\\subsection{Confidence intervals for the eigenvalues and eigenvectors}\n%\\label{pcaconfint}\n\\begin{displaymath}\nse(\\lambda_{j}) = \\sqrt{2/n} \\lambda_{j},\n\\end{displaymath}\ngiving confidence intervals:\n\\begin{displaymath}\n\\frac{\\ell_{i}}{1 + \\sqrt{2/n} z_{\\alpha/2}} \\leq \\lambda_{i} \\leq \\frac{\\ell_{i}}{1 + \\sqrt{2/n} z_{1-\\alpha/2}}\n\\end{displaymath}\nand the standard error for the corresponding eigenvectors are given by: \n\\begin{displaymath}\nse(\\alpha) = \\left( \\frac{1}{n} \\lambda_{j} \\sum_{j+1; j \\neq h}^{p} \\frac{\\lambda_{j}}{(\\lambda_{j} - \\lambda_{h})^2} \\alpha_{jh}^{2} \\right)^{1/2}.\n\\end{displaymath}\n\n\nWe can illustrate calculation of these standard errors, as well as estimation of associated confidence intervals by adapting code written by Marco Bee  to accompany \\cite{Flury:1997}).   This code will be set out at an S3 class in \\textbf{R}.   Firstly therefore, we set out a container:\n\\singlespacing\n\\begin{verbatim}\nlpc <- function(X){\n  UseMethod(\"lpc\", X)\n}\n\\end{verbatim}\n\\onehalfspacing\n\nAnd now we can write out a default method which calculates the relevant confidence intervals:\n\\singlespacing\n\\begin{verbatim}\nlpc.default <- function(X)\n{\nn <- dim(X)[1]; p <- dim(X)[2]  # number of observations \nX.prcomp <- prcomp(X)\nevals <- X.prcomp$sdev^2 \nOnes <- matrix(1, p, p) \nLambda <- Ones * evals\nQ <- (t(Lambda) - Lambda + diag(p))^(-2) - diag(p) # nifty trick\nTheta1 <- sweep(Q, 2, evals, FUN=\"*\") \nTheta <- Theta1 * evals # compute matrix of theta-coefficients\nstdeB <- matrix(0,p,p)      \n   h <- 1\n      while (h <= p){ \n      V <- X.prcomp$rotation %*% \n          (Theta[, h] * t(X.prcomp$rotation))  \n      stdeB[, h] <- sqrt(diag(V)/n)\n      h <- h + 1 \n      }                         \nstdelam <- sqrt(2/n) * evals\nresults <- list(\"eigenvectors\" = X.prcomp$rotation, \n  \"eigenvalues\" = X.prcomp$sdev^2,\n  \"stdeB\" = stdeB, \"stdelam\" = stdelam)\n  class(results) <- \"lpc\"\n  results\n}\n\\end{verbatim}\n\\onehalfspacing\n\nHaving returned the standard error we can write a simpler print function which displays the eigenvectors and eigenvalues along with their associated standard error:\n\\onehalfspacing\n\\begin{verbatim}\nprint.lpc <- function(x) {\nprint(x[1]) ## eigenvectors\nprint(x[2]) ## eigenvalues\ncat(\"standard errors for eigenvector coefficients:\")\nprint(x[3])\ncat(\"standard errors for eigenvalues:\")\nprint(x[4])\ncat(\"\\n\\n\")\ninvisible(x)\n}\n\\end{verbatim}\n\\onehalfspacing\n\nSo for example, with the turtles data:\n\\singlespacing\n\\begin{verbatim}\n> lpc(subset(turtles, turtles$Gender == \"Male\")[,-1])\n$eigenvectors\n          [,1]        [,2]        [,3]\n[1,] 0.8401219  0.48810477 -0.23653541\n[2,] 0.4919082 -0.86938426 -0.04687583\n[3,] 0.2285205  0.07697229  0.97049145\n\n$eigenvalues\n[1] 195.274633   3.688564   1.103833\n\nstandard errors for eigenvector coefficients:$stdeB\n           [,1]       [,2]       [,3]\n[1,] 0.01442666 0.04469703 0.07885419\n[2,] 0.02487011 0.01592627 0.13874655\n[3,] 0.01513963 0.15478836 0.01276277\n\nstandard errors for eigenvalues:$stdelam\n[1] 56.370931  1.064797  0.318649\n\n\\end{verbatim}\n\\onehalfspacing\n\nAnd if we wanted to estimate the confidence intervals we can write an associated \\verb+summary+ method which will do the additional calculations and return the results.   Note in the code below that we have allowed for a \\emph{Bonferroni} adjustment.   If we wish to adjust for making $m$ comparisons we can replace $z_{\\frac{\\alpha}{2}}$ with $z_{\\frac{\\alpha}{2m}}$  \n\n\\singlespacing\n\\begin{verbatim}\nsummary.lpc <- function(x, alpha = 0.05, bonferroni = FALSE) {\nif (!is.null(alpha)){ ## calculate ci if asked\n  if (bonferroni == TRUE) {alpha = alpha / length(x[[2]])}\n  z <- abs(qnorm((1-alpha)/2))\n}\nprint(x[1]) ## eigenvectors\n\nif (!is.null(alpha)){\ncat(round(alpha * 100), \"\\% CI: \\n \")\nveclo <- x[[1]] - z * x[[3]]\nvechi <- x[[1]] + z * x[[3]]\nprint(veclo)\nprint(vechi)\ncat(\"\\n\")\n} \n\nprint(x[2]) ## eigenvalues\n\nif (!is.null(alpha)){\ncat(round(alpha * 100), \"\\% CI: \\n \")\nvallo <- x[[2]] - z * x[[4]]\nvalhi <- x[[2]] + z * x[[4]]\nprint(vallo)\nprint(valhi)\ncat(\"\\n\")\n} \n\ncat(\"standard errors for eigenvector coefficients:\")\nprint(x[3])\n\ncat(\"standard errors for eigenvalues:\")\nprint(x[4])\ncat(\"\\n\\n\")\ninvisible(x)\n}\n\\end{verbatim}\n\\onehalfspacing\n\n%This should place some cautions on arbitrary cutoffs, e.g. Kaiser.\n\n\n\\section{Sphericity}\n\\label{Sphericity}\n\nWe preface this section on sphericity with some results concerning covariance / correlation matrices which are of less than full rank.   If a symmetric positive definite matrix (correlation and covariance matrices are at least semi-definite).   If such a matrix is of full rank $p$ then all the eigen values are positive.   \n%If the matrix is of rank $m < p$ then there will be $m$ positive eigenvalues and $p-m$ zero eigenvalues.   We will consider this sphericity problem in some detail later.\n%We preface comments on sphericity with one point concerning the rank of the covariance or correlation matrix.   \nIf the rank of the covariance or correlation matrix $m < p$ then the last $p-m$ eigenvalues are identically zero.   The converse of this theorem is that any non-zero eigen value can be considered to be \\emph{significantly} non-zero.\n\nHowever, we are now going to consider sphericity, where there are not $p$ distinct eigenvalues.   We highlighted earlier the potential problem of sphericity and the effect on a resultant principal component analysis.\nClearly there is little point carrying out a principal component analysis under conditions of sphericity.   We can consider three possiblilites, where $\\boldsymbol{R} = \\boldsymbol{I}$, which can arise either because $\\boldsymbol{S} = s \\boldsymbol{I}$ or the more general possibility that $\\boldsymbol{S}$ is diagonal.\n\n\nWe firstly consider the most general possibility, that $\\boldsymbol{\\Sigma} \\propto \\sigma \\boldsymbol{I}$ where $\\sigma$ is unspecified.   However, this test is equivalent to examining whether all the roots of $|\\boldsymbol{\\Sigma} - \\lambda \\boldsymbol{I}| = 0$ are equal.   In this eventuality, the arithmetic and geometric means will be identical\n\nWe firstly consider a general test for sphericity proposed by \\cite{Mauchly:1940}\n\n\n\\begin{theorem}\nWe consider that:\n\\label{th:sphericity}\n\\begin{displaymath}\n\\frac{\\prod_{j=1}^{p} \\lambda_{i}^{1/j}}{\\sum_{j=1}^{p} \\lambda_{i}^{1/j}} = \\frac{\\lvert \\boldsymbol{\\Sigma} \\rvert^{1/j}}{\\frac{1}{j} tr(\\boldsymbol{\\Sigma})}\n\\end{displaymath}\n\nThis yields the following test statistic.   Under the null hypothesis $H_{0}: \\boldsymbol{S} = \\sigma \\boldsymbol{I}$, the test statistic $m$ given by:\n\\begin{equation}\nm = \\frac{\\lvert \\boldsymbol{S} \\boldsymbol{\\Sigma}_{0}^{-1} \\rvert^{n/2}}\n{ \\left[ \\frac{1}{p} trace(\\boldsymbol{S} \\boldsymbol{\\Sigma}_{0}^{-1} )^{pn/2} \\right] } \n\\end{equation}\n\\end{theorem}\n\n\nThis is pre-implemented in \\textbf{R} for manova type objects, therefore if we fit a null manova object we can carry out this test:\n\n\\singlespacing\n\\begin{verbatim}\nobj <- manova(as.matrix(turtles.m) ~ 1)\nmauchly.test(obj)\n\n        Mauchly's test of sphericity\n\ndata:  SSD matrix from manova(as.matrix(turtles.m) ~ 1) \n= 101.1821, p-value < 2.2e-16\n\\end{verbatim}\n\\onehalfspacing\n\nAnd so we have evidence (provided the test assumptions are met) that the turtle data are not spherical.\n\n\nFor completeness, we mention here another test for sphericity is given by [see section 1.9] \\cite{Morrison:2005} based upon the determinant of the correlation matrix.\n\n\\begin{definition}\n\\label{morrison}\nUnder the null hypothesis $H_{0}: \\boldsymbol{R} = \\boldsymbol{I}$, the test statistic $w$ given by:\n\\begin{displaymath}\nw = -\\left( n - \\frac{2p + 5}{6} \\right) \\log \\lvert \\boldsymbol{R} \\rvert\n\\end{displaymath}\nhas a $\\chi^{2}$ distribution with $\\frac{1}{2}p(p-1)$ degrees of freedom.\n\\end{definition}\n\nThis test is quite simply coded up in \\textbf{R}.\n\n\\singlespacing\n\\begin{verbatim}\nmorrison <- function(data){\n  n <- dim(data)[1]; p <- dim(data)[2];\n  wnm <- -(n - (2 * p)/6) * log(det(cor(data)))\n    cat(paste(\"wnm = \", wnm, \"\\n\"))\n    cat(paste(\"df = \", p * (p - 1) * 0.5, \"\\n\"))\n    cat(paste(\"Chisq density = \", dchisq(wnm, p * (p - 1) * 0.5) , \"\\n\"))\n}\n\\end{verbatim}\n\\onehalfspacing\n\nAgain, this test confirms non-sphericity of the Turtles data.\n\n\\subsection{Partial sphericity}\n\nIt is usually the case that partial sphericity is or more practical concern than more complete independence of the data.   We will consider more heuristic methods for selecting the dimensionality of a principal component projection later, but clearly the eigenvectors of principal components with equal eigenvalues are too poorly defined to be of any practical use.   We are therefore interested in partial sphericity, where $\\lambda_{q+1} = \\lambda_{q+2} = \\ldots = \\lambda_{p}$\n\n%We highlighted in theorem \\ref{pca:lowrank} that whenever the covaraiance matrix had rank $r<p$ there were $r$ principal components.   More notably, we highlighted the problem in \\label{sec:pcastability} of sphericity.   In practice, we may be more concerned about partial sphericity; whilst the first $q$ eigenvalues are distinct we may be concerned that the smallest eigenvalues, $q+1, \\ldots, p$, are equal.   \n\nWhere we have partial sphericity, we may note the following theorem:\n\n\\begin{theorem}\nFor normal data, where the eigenvalues of $\\boldsymbol{\\Sigma}$ are not distinct then the m.l.e. of $\\bar{\\lambda}$ is the corresponding arithmetic mean of the sample eigenvalues, and the corresponding eigenvectors are maximum likelihood estimators although they are not unique.\n\\end{theorem}\nProof: See \\cite{Anderson:1963}\n\nThe asymptotic theory set out above leads to a number of possible tests for partial sphericity.   One likelihood ratio can be considered as follows:\n\n\\input{defs/pcapartialsplrt}\n\nIt is reasonably straightforward to start coding a function to execute this in \\textbf{R}, a sketch of such a function is illustrated here:\n\\singlespacing\n\\begin{verbatim}\nspher <- function(X, q){\n  p <- dim(X)[2]; n <- dim(X)[1]; r <- p-q\n  X.prcomp <- prcomp(X)\n  evals <- X.prcomp$sdev^2\n  retain <- evals[1:q]; discard <- evals[-(1:q)]\n  lambdahat <- mean(discard)\n  bit <- sum(lambdahat / (retain - lambdahat) )^2\n  corr <- n - 1 - q - (2 * r^2 + r + 2)/(6*r) + bit\n  product <- prod(discard / lambdahat)\n  lrt <- -corr * log(product)\n  df <- 0.5 * (r-1) * (r+2)\n    cat(paste(\"-2log L = \", lrt, \"\\n\") )\n    cat(paste(\"df = \", df, \"\\n\") )\n    cat(paste(\"Chisq density \", dchisq(lrt, df ), \"\\n\" ))\n    ##return(lrt)\n}\n\\end{verbatim}\n\\onehalfspacing\n\nWe illustrate this with the turtle data.   Recalling that the first eigenvalue was 2.33, considerably greater than the second and third eigenvalues of 0.06 and 0.036.\n\n\\singlespacing\n\\begin{verbatim}\n> spher(turtles.m, 1)\n-2log L =  1.34290454195737 \ndf =  2 \nChisq density  0.255482988814162 \n\\end{verbatim}\n\\onehalfspacing\n\nSo in this case we cannot reject $H_{0}$ and have no evidence that the second and third eigenvalues are distinct.   We might be included to consider the possibility here that that $\\lambda_{2} = \\lambda_{3}$ and would therefore be somewhat wary of the resultant eigenvectors.\n\n\nA simpler explanation is given in [page 622] \\cite{Flury:1997}, which follows from that given in [page 475] \\cite{Anderson:1984}, and is given in slightly different form in [page 235] \\cite{Mardia+etal:1979}.%##mkb <- n* p * (a - 1 - log(g) ) ##mkb pg 235\nThis relies on a log likelihood statistic derived as a ratio of arithmetic to geometric means of the eigenvalues.\n\n\\singlespacing\n\\begin{verbatim}\nfunction(X, q){\n  p <- dim(X)[2];  n <- dim(X)[1];  r <- p-q\n  X.prcomp <- prcomp(X)\n  evals <- X.prcomp$sdev^2\n  q1 <- q+1\n    discard <- evals[q1:p]\n    a <- sum(discard) / r\n    g <- prod(discard)^(1/r)\n    s <- n * r * log(a / g)\n    df <- 0.5 * r * (r+1)\n  cat(paste(\"-log L = \", s, \"\\n\") )\n  cat(paste(\"df = \", df, \"\\n\") )\n  cat(paste(\"Chisq density \", dchisq(lrt, df ), \"\\n\" ))\n  ##return(s)\n}\n\\end{verbatim}\n\\onehalfspacing\n\nAsymptotically, this value can be considered to follow a $\\chi^{2}_{\\frac{1}{2}(p-q)(p-q+1) - 2}$ distribution under the null hypothesis.   It can be seen that is related to the test of complete sphericity.   This test can be used with the turtle data and again confirms the possible that the second and third principal components can be considered spherical and should not be interepreted further.\n\n\n%Yet another likelihood ratio test exists for this.\n\n%\\begin{displaymath}\n%\\Lambda = \\frac{|\\boldsymbol{S}|^{n/2}}{\\prod s_{ij}^{n/2}} = |\\boldsymbol{R}|^{n/2} < c\n%\\end{displaymath}\n%$-2 \\log \\Lambda \\sim \\chi^{2}$ with Bartlett continuity corrections\n\n%In the case of the latter, $\\lambda = 1 + (p-1) \\rho$, eigenvectors = $\\frac{1}{\\sqrt{p}}$\n\n\n\\subsection{High Dimensional Tests for Sphericity}\n\nHaving (hopefully) demonstrated the importance of sphericity in conventional principal components analysis we refer to results which carry out analagous procedures in high dimensions.   Whilst the asymptotic tests above rely on $n \\to \\infty$, it can be problematic where $p > n$.   More recent work therefore examines how one might carry out tests for this eventually.   We firstly consider testing whether $\\boldsymbol{\\Sigma} \\propto \\boldsymbol{I}$ \n\n\\begin{theorem}\nA test for $\\boldsymbol{\\Sigma} \\propto \\boldsymbol{I}$ which is reliable whenever $p > n$ can be given as follows:\n\\begin{equation}\nU = \\frac{1}{p} trace \\left( (\\frac{\\boldsymbol{S}}{(1/p)trace(\\boldsymbol{S})} - \\boldsymbol{I} )^{2} \\right)\n\\end{equation}\nIn this case, it may be noted that $\\frac{np}{2} U$ asymptotically follows a $\\chi^{2}$ distribution with $\\frac{1}{2}p(p+1)-1$ degrees of freedom. \n\nProof: See \\cite{Ledoit+Wolf:2002}, following work by \\cite{John:1971,John:1972}\n\\end{theorem}\n\nThis can be very simply estimated in \\textbf{R}:\n\n\\singlespacing\n\\begin{verbatim}\nJohnsU <- function(data){\n  p <- dim(data)[2]\n  S <- cov(data)\n  traceS <- sum(diag(S))\n  traceSI <- sum(diag(S-diag(rep(1, p))))\n    u <- 1/p * traceS / (1/p*traceSI^2)\n    test <- n * p * 0.5 * u\n    df <- (0.5 * p * (p+1)) - 1\n  cat(paste(\"U = \", test, \"\\n\") )\n  cat(paste(\"df = \", df, \"\\n\") )\n  cat(paste(\"Chisq density \", dchisq(test, df ), \"\\n\" ))\n}\n\\end{verbatim}\n\\onehalfspacing\n\nSo we can estimate the sphericity quite simply\n\n\\singlespacing\n\\begin{verbatim}\nJohnsU(khan$train)\n\\end{verbatim}\n\\onehalfspacing\n\nWhich appears to indicate little evidence for sphericity.\n\nTesting the correlation matrix is not quite so straighforward to expansion of $p$ relative to $n$.    $\\boldsymbol{\\Sigma} = \\boldsymbol{I}$\n\n\\begin{theorem}\nA test for $\\boldsymbol{\\Sigma} = \\boldsymbol{I}$ which is reliable whenever $p > n$ is given by:\n\\begin{equation}\n\\label{ledoit}\nW = \\frac{1}{p} trace \\left\\{ \\left( \\boldsymbol{S} - \\boldsymbol{I} \\right)^{2} \\right\\} - \\frac{p}{n} \\left\\{ \\frac{1}{p} trace(\\boldsymbol{S}) \\right\\}^{2} + \\frac{p}{n}\n\\end{equation}\nUnder $H_{0}$, assuming multivariate normality $\\frac{nm}{2} W \\rightarrow ^{d} \\chi^{2}_{p(p+1)/2-1}$\n\nProof: \\cite{Ledoit+Wolf:2002}\n\\end{theorem}\n\n\\singlespacing\n\\begin{verbatim}\nledoitwolf <- function(data){\n  n <- dim(data)[1]; p <- dim(data)[2] \n  S <- cor(data)\n  traceS <- sum(diag(S))\n  SI <- crossprod(S - diag(rep(1, p)))   \n  traceSI <- sum(diag(SI))\n    w <- 1/p*traceSI - p/n*(1/p*traceS)^2 + p/n\n    test <- n * p * 0.5 * w\n    df <- (0.5 * p * (p+1))\n  cat(paste(\"U = \", test, \"\\n\") )\n  cat(paste(\"df = \", df, \"\\n\") )\n  cat(paste(\"Chisq density \", dchisq(test, df ), \"\\n\" ))\n}\n\\end{verbatim}\n\\onehalfspacing\n\n\nHowever, we can consider results based on those indicated in  \\ref{morrison} which can be used to test whether $\\boldsymbol{R} = \\boldsymbol{I}$.  \n\n\\begin{theorem}\nA test statistic for sphericity is given by:\n\\begin{displaymath}\nt = \\sum_{i=2}^{p} \\sum_{j=1}^{i-1} r_{ij}^{2} - \\frac{p(p-1)}{2n}\n\\end{displaymath}\nWhich is asymptotically normal with zero mean and variance:\n\\begin{displaymath}\n\\sigma_{t}^{2} = \\frac{p(p-1)(n-1)}{n^{2}(n+2)}\n\\end{displaymath}\nProof: See \\cite{Schott:2005}\n\\end{theorem}\n\n\nThis is simply illustrated in \\textbf{R}.\n\n\\singlespacing\n\\begin{verbatim}\nschott <- function(data){\n  n <- dim(data)[1]; p <- dim(data)[2]\n  R <- cor(data)\n  R[lower.tri(R) == FALSE] <- NA\n  red <- na.omit(as.vector(R))\n   tnm <- sum(red^2) \n   cf <- (p * (p-1)) / (2 * n)\n   test <- tnm - cf\n   sigma2 <- (p * (p-1) * (n-1)) / (n^2 * (n+2) )\n  cat(paste(\"tnm = \", tnm, \"cf = \", cf,  \"\\n\") )\n  cat(paste(\"Normal density \", dnorm(test, sqrt(sigma2) ), \"\\n\" ))\n}\n\\end{verbatim}\n\\onehalfspacing\n\nAgain, a call to \\verb+schott(khan$train)+ confirms that these data are non-spherical.\n\nAs before, perhaps we are more interested in the generalisations of these statistics, i.e. we are concerned with partial sphericity and wish to determine whether the smallest $p-q$ eigenvalues of $\\boldsymbol{\\Sigma}$ are equal.\n\n\\begin{theorem}\nGeneralising equation \\ref{ledoit}, a test for partial sphericity can be based upon the following test statistic:\n\\begin{equation}\nu = \\frac{ (1/p) \\sum_{i=q+1}^{p} \\lambda_{i}}{\\left[(1/p) \\sum_{i=q+1}^{p} \\lambda_{i} \\right]^{2}} - 1\n\\end{equation}\nwhere $\\frac{n-q}{u}$\\footnote{check this} can be compared with a $\\chi^{2}$ distribution with $p(p+1)/2 - 1$ degrees of freedom.     \n\\end{theorem}\nProof: \\cite{Schott:2006}\n\nAgain, this test can be coded up in \\textbf{R} and examined in the context of the khan data.\n\n\\singlespacing\n\\begin{verbatim}\nschottpartial <- function(X, q){\n  p <- dim(X)[2]; n <- dim(X)[1]; r <- p-q\n  X.prcomp <- prcomp(X)\n  evals <- X.prcomp$sdev^2\n  discard <- evals[-(1:q)]\n  u <- (sum(discard^2) / r) / (sum(discard) / r)^2  - 1\n  df <- 0.5 * r * (r+1) - 1\n    cat(paste(\"u = \", u, \"\\n\") )\n    cat(paste(\"df = \", df, \"\\n\") )\n    cat(paste(\"Chisq density \", dchisq(u * (n-q), df ), \"\\n\" ))\n    ##return(lrt)\n}\n\\end{verbatim}\n\\onehalfspacing\n\n\n\n\nIt is bearing in mind that just because the smallest $p-q$ eigenvalues indicate the corresponding principal components explain very little of the variation, they do not necessarily contain any useful information.\n\n\n%library(made4)\n%data(khan)\n%khan.coa<-ord(khan$train, classvec=khan$train.classes, type=\"pca\")  \n%khan.coa$ord$eig\n%dim(khan$train)\n\n\n%\\begin{displaymath}\n%U_{r} \\left( \\frac{\n%\\frac{1}{r}  sum_{i+q+1}^{p} \\lambda_{i}^{2} }\n%{(\\frac{1}{r} sum_{i+q+1}^{p} \\lambda)^{2}} - 1 \\right)\n%\\end{displaymath}\n%where $r = p-q$, i.e. we are looking for a test to reject the $r$th smallest eigenvalues.   It can be shown that testing $(n-q) U_{r} > \\chi^{2}_{\\frac{r(r+1)}{2}-1, 1-\\alpha}$, where $\\alpha$ is the required significance level and \n\n\n\n\\section{How many components to retain}\n\nWe have considered formal hypothesis testing for sphericity and partial sphericity.   This may well indicate that it is not sensible to include a number of principal components in a given representation of multivariate data.   However, we may not really be interested in modelling multivariate normality.   We may not like asymptotics.   We will consider a few further results on selecting the number of principal components in any given projection of the data.\n\nWhilst principal components have optimality properties in terms of providing the best lower dimensional projection in terms of mean squared error.   Nevertheless, they are often used, however informally, in an inferential role.   Consideble care is needed in their interpretation.   It is important to note that we are working with sample principal components, these can be somewhat unstable relative to the puted underlying population components.   It makes little sense to attempt anything resembling inferential work without considering the stability of a particular principal component solution.   Typically, having decided how best to scale the data, the next most important question surrounds how many components need to be retained.   We will first consider some of the more informal procedures used to guide this judgement, and will subsequently consider methods derived from normal theory inference.\n\n\n\n\\subsection{Data analytic diagnostics}\n\nA number of proposals have been made in the literature concerning decisions surrounding the ``number of components'' to retain.  The following are some of the more popular proposals:\n\n%\\begin{itemize}\n%\\item Retaining enough components to explain more than x\\% of the variation, where x has been determined \\textit{a priori} and is in the order of 80 or 90\\%.\n%\\item Looking for a change in the slope of the scree plot - the last components where the line flattens are usually discarded\n%\\item Interpreting the scree plot in the presence of monte carlo simulations\n%\\item Retaining all components explaining an above average amount of variation (i.e. in the case of components derived from the correlation matrix this is all components with an eigenvalue above 1)\n%\\item Broken stick approach\n%\\item Using the empirical distribution function, i.e. bootstrapping\n%\\end{itemize}\n\n\n\\subsection{Proportion of variance explained}\n\\label{propexpl}\n\nThe proportion of variance explained is a rather informal method for selecting $q$, the number of dimensions in the principal component projection required to adequately explain the data.   Essentially, one decides \\textit{a priori} that a certain amount of variance is to be explained, and only accepts solutions meeting that requirement.   It is however consistent with the exploratory nature to which principal component analysis is often applied.\n\n\nWe can however, using the asymptotic theory set out above, develop a confidence interval for the proportion of variance explained.   %We suggested in section \\ref{propexpl} that one might choose the dimensionality of the solution based on whether it meets some predetermined arbitrary proportion of variance.  We have confidence intervals for these values as well.\n\n\\input{defs/pcpropexpl}\nHence we can derive a confidence interval for $\\pi$ as follows.\n\nThis can be illustrated as follows:\n\n\\singlespacing\n\\begin{verbatim}\nvals <-  hep.ev$values^2\nq <- 3\nalpha <- 0.95\nalpha <- 1 - (1-alpha)/2\n\npi <- sum(vals[1:q]) / sum(vals)\nalpha <- sum(vals[1:q]^2) / sum(vals^2)## by vector recycing\neta2 <- pi^{2} - 2 * alpha * pi + alpha^2\ncat(pi, eta2)\ncat(\"\\n\")\ncat(pi + qnorm(alpha)*eta2)\ncat(\"\\n\")\ncat(pi - qnorm(alpha) * eta2)\ncat(\"\\n\")\n\\end{verbatim}\n\\onehalfspacing\n\n\n\n\n\n\\subsection{Change in slope of the scree plot}\n\\label{screeslope}\n\n\\cite{Cattell:1966} proposed the scree plot in the context of (principal component extracted) factor analysis.   Without wishing to add to the confusion between the two techniques, it has become a fairly standard technique for assessing the adequacy of a number of dimension reducing techniques.   Both \\texttt{prcomp} and \\texttt{princomp} objects have a plot method which yields a scree plot, the idea is to select components up to the point where the slope changes direction.\n\n\\singlespacing\n\\begin{verbatim}\nplot(hept.princomp)\n\\end{verbatim}\n\\onehalfspacing\n\n\\subsection{Interpreting the scree plot in the presence of simulations}\n\\label{screemc}\n\nIt is possible to extend the basic scree plot idea.   \\cite{Horn:1965} suggested simulating data from a multivariate normal having the same sample size, the same number of variables, the same means and variances but having zero covariances.   There are a couple of manifestations of this approach within various \\textbf{R} packages, for example \\verb+psy+ package contains a ready made function.   The scree plot of with zero correlation is expected to be a straight line, it can be compared with the scree plot from the observed data.   It is possible to extend this to a full Monte Carlo test, the code listing below goes someway towards this.\n\n\\singlespacing\n\\begin{verbatim}\nHorn <- function(data, reps){\np <- dim(data)[2]\nn <- dim(data)[1]\nVarmat <- matrix(0,p,p)\nMean <- mean(data)\ndiag(Varmat) <- diag(var(data))\n\nEvals <- princomp(data, cor = TRUE)$sdev^2\nidx <- barplot(Evals, names.arg = paste(\"PC\", c(1:7)), \nxlab = \"Component\", ylab = \"Proportion of trace\", \nmain = \"Proportion of trace explained\")\n\nresults <- matrix(0,reps,p)\n  for (i in 1:reps){\n  SimData <- mvrnorm(n, Mean, Varmat)\n  ExpEvalsH <- princomp(SimData, cor = TRUE)$sdev^2\n  results[i,] <- ExpEvalsH\n  lines(idx, ExpEvalsH, type = \"b\", pch = 16)\n  }\n\nlines(idx, apply(results, 2, mean), type = \"b\", col = \"red\")\n\nlegend(\"topright\", lty = 1, pch = 16, legend = \"Expected values\")\nResults <- data.frame(Evals = Evals, ExpEvalsH = ExpEvalsH)\n}\n\nHorn(hept.df[-1], 10)\n\\end{verbatim}\n\\onehalfspacing\n\n\\includegraphics[width = 0.7\\textwidth]{images/Horn}\n\n\n\\subsection{Broken Stick}\n\\label{brokenstick}\n\nAnother approach to assessing the proportion of variation explained has been made by \\cite{Jolliffe:1986} who suggests using a ``broken stick'' approach.   The idea here is that if any unit is randomly divided into $p$ segments, the expected length of the $k$th longest segment is:\n\\begin{equation}\n\\label{stick}\nl_{k} = \\left(\\frac{1}{p} \\right) \\sum_{i=k}^{p} \\left( \\frac{1}{i} \\right)\n\\end{equation}\nIf we assume that the total variance, $trace{\\boldsymbol{S}} = \\sum_{j=1}^{p}$, is the ``stick'', we can use this approach to estimate an expected size of each eigenvalue.   A rather simple function to calculate the expected values indicated by \\ref{stick} is given below, the expected values are plotted alongside the observed values from a \\texttt{princomp()} object created from the Heptathalon data.   It should be noted that \\texttt{princomp()} returns the standard deviations (\\verb+$sdev+), these have therefore been squared to recoved the eigenvalues $\\lambda_{i}$.\n\n\\singlespacing\n\\begin{verbatim}\n> stickometer <- function(p){\n  vec <- 1 / (1:p)\n  stick <- vector(\"numeric\", p) \n  stick[1] <- sum(vec)\n     for (i in 2:p){\n     stick[i] <- sum(vec[-(1:(i-1))])}\n  stick <- 1/p * stick\n  names(stick) <- paste(\"Comp.\", c(1:p), sep = \"\")\n  return(stick)\n}\n> \n> stick <- stickometer(7)\n> proptrace <- hep.princomp$sdev^2 / sum(hep.princomp$sdev^2)\n>\n> stick\n> proptrace\n> \n> idx <- barplot(proptrace, names.arg = paste(\"PC\", c(1:7)), \n> xlab = \"Component\", ylab = \"Proportion of trace\", \n> main = \"Proportion of trace explained\")\n> lines(idx, stick, type = \"b\", pch = 16)\n> legend(\"topright\", lty = 1, pch = 16, legend = \"Expected values\")\n\\end{verbatim}\n\\onehalfspacing\n\n\\includegraphics[width = 0.7\\textwidth]{images/stick}\n\nExamination of the results (numbers or the plot) suggest that the first and seventh components are accounting for slightly more variation than would be expected purely by chance.\n\n\\subsection{Kaiser Criterion}\n\\label{kaiser}\n\nThe Kaiser Criteria is a rather inflexible criteria widely met in many sofware packages.   Basically it amounts to retaining all components where the eigenvalue is greater than the mean of the eigenvalues.   In the case of principal components based on the correlation matrix this clearly means retaining all components where the eigenvalue is greater than one.  Whilst one may not wish to assume multivariate normality, the asymptotics considered next provide a clear warning that population eigenvalues greater than one could clearly be realised in a sample with values below one.\n\n\nKarlis provide some caveats on the use of this criteriosn.\n\n\\subsection{Cross validation}\n\nCross-validation in the context of principal components was proposed by \\cite{Wold:1976,Wold:1978} and developed by \\cite{Eastment+Krzanowski:1982}.   In essence, the sample can be randomly split into $g$ groups, the loadings can be estimated from reduced sets omitting each of the $g$ groups in turn, but the predicted values can be found from these $g$ groups using the loadings estimated from the other rows.   The value for $(\\boldsymbol{\\hat{x}} - \\boldsymbol{x})$ can be estimated from equation \\ref{Qstats}, and the PRESS statistic estimated.\n\n\n\\singlespacing\n\\begin{verbatim}\npcaxv <- function(X){\n  UseMethod(\"pcaxv\", X)\n}\n\\end{verbatim}\n\\onehalfspacing\n\nIt is useful to create an \\texttt{S3} object to carry out this procedure.   The working function is given by:\n\n\\singlespacing\n\\begin{verbatim}\npcaxv.default <- function(X, g = 5){\n    N <- dim(X)[1]\n    p <- dim(X)[2]\n      index <- sample(c(1:N) )\n      groups <- gl(g, N %/% g)\n         Q <- matrix(0, g, p)\n           for (i in 1:g){\n           dot <- prcomp(X[-index[groups == i],])\n         Q[i,] <- colSums((as.matrix(scale(X))[index[groups == i],]\n                       %*% dot$rotation)^2)}\n    colmeans <- colSums(Q) / N\n  PRESS <- cumsum(colmeans[c(p:1)])/ c(1:p)\n  PRESS <- PRESS[c(p:1)]\n  names(PRESS) <- paste(\"C\", c(0:(p-1)))\n  results <- list(\"PRESS\" = PRESS, \n    dm = pcaxvconstants(N,p)$dm, dr = pcaxvconstants(N,p)$dr)\nclass(results) <- \"pcaxv\"\nresults\n}\n\\end{verbatim}\n\\onehalfspacing\n\nThe function \\verb+pcaxvconstants()+ calculates some constants that can be used in the summary function.   A suitable print function for use with cross-validation objects created here can be given as follows:\n\n\\singlespacing\n\\begin{verbatim}\nprint.pcaxv <- function(x){\ncat(\"Components Removed \\n\")\n  print(x[[1]])\n  cat(\"\\n\")\n  invisible(x)\n}\n\\end{verbatim}\n\\onehalfspacing\n\n[page 354] \\cite{Jackson:1991} refers to a $W$ statistic (without giving any idea as to its origin or distribution.   The idea behind this $W$ statistic however is that for any component where $W > 1$ we have evidence to retain the component, where $W < 1$ we have an adequate representation of our data swarm without that component.   The constants calculated earlier are basically $D_{M} = n + p - 2(p-q)$, $D_{R} = p (n - 1) - \\sum_{i=1}^{(p-q)}(n + p - 2i)$, and $W$ is given by:\n\n\\begin{equation}\nW = \\frac{ (PRESS((p-q)-1) - PRESS(p-q))/D_{M}(p-q)}{PRESS(p-q)/D_{R}(p-q)}\n\\end{equation}\n\n\\singlespacing\n\\begin{verbatim}\nsummary.pcaxv <- function(x){\n  cat(\"PRESS for components Removed \\n\")\n  print(x[[1]])\n  cat(\"\\n\")\n    wl <- length(x$PRESS)-1\n    w <- rep(NA, wl)\n       for (i in 1:wl){\n       w[i] <- ((x$PRESS[i] - x$PRESS[i+1]) / x$dm[i+1] ) / \n             (x$PRESS[i+1] / x$dr[i+1] ) }\n    names(w) <- paste(\"C\", c(1:wl))\n  cat(\"W for components included \\n\")\n  print(w)\ninvisible(x)\n}\n\\end{verbatim}\n\\onehalfspacing\n\n\nThese are rather interesting concepts in practice.   For example, considering the \\verb+turtle+ data examined earlier:\n\n\\singlespacing\n\\begin{verbatim}\n> turtle.xv <- pcaxv(as.matrix(log(turtles[,-1])))\n> turtle.xv\nPRESS for components Removed \n       C 0        C 1        C 2 \n0.97916667 0.05952219 0.06118754 \n\nW for components included \n        C 1         C 2 \n29.00900476 -0.02605895 \n\\end{verbatim}\n\\onehalfspacing\n\nWhich appears to provide strong evidence that the turtle data can be represented by one principal component.\n\nOne little glurp can happen with the $W$ statistic.   Consider the water strider data given in \\cite{Flury:1997}.\n\n\\singlespacing\n\\begin{verbatim}\ndata(strider)\ndot <- pcaxv(as.matrix(log(strider)))\nsummary(dot)\nPRESS for components Removed \n       C 0        C 1        C 2        C 3        C 4        C 5 \n0.98863636 0.27912037 0.23714880 0.15109046 0.10068831 0.05974256 \n\nW for components included \n       C 1        C 2        C 3        C 4        C 5 \n11.8809534  0.6686066  1.6310744  0.9662281  0.6690516 \n\\end{verbatim}\n\\onehalfspacing\n\nIt can be seen that the second component has a $W$ below 1, but for the third is clearly above 1, and for the fourth is is very close to 1.   \\cite{Jackson:1991} suggests that this may be due to the presence of outliers - this is left as an exercise for further examination.\n\n\nThe following functions (a) need tidying up and (b) support the pcaxv function - they're left here for tidiness only;\n\n\\singlespacing\n\\begin{verbatim}\nrtota <- function(N, p, q){\n  rtot <- 0\n  for (i in 1:q){\n  rtot <- rtot + N + p - 2 * i\n  }\nrtot\n}\n\n\npcaxvconstants <- function(N,p){\n  dm <- N + p - 2 * (p - c(p:1))\n  dm[1] <- NA\n    dr <- rep(0,p)\n    dr[1] <- p * (N-1)\n  for (i in 2:p){\n  dr[i] <- p * (N - 1) - rtota(N, p, i-1)\n}\nresults <- list(dm = dm, dr = dr)\n}\n\\end{verbatim}\n\\onehalfspacing\n\n\n\n\\subsection{Bootstrapping}\n\\label{bootstrap}\n\nWe discuss standard errors derived from asymptotic theory in the next section, but clearly there are limitations in having to assume multivariate normality.   Bootstrapping avoids any such assumptions, we can make inference based upon an empirical distribution function.   For tidiness, we will make a little function that calls \\texttt{prcomp()} and returns the eigenvalues and eigenvectors only:\n\n\\singlespacing\n\\begin{verbatim}\ntheta <- function(x.data, x){\neta <- prcomp(x.data[x,])\nreturn(cbind(eta[[1]], eta[[2]]))\n}\n\\end{verbatim}\n\\onehalfspacing\n\nHowever, whilst computer power might be cheap, nothing in life is free and the problem with eigenvectors is the arbitrariness of the signs.   Accordingly, it is completely unacceptable to use bootstrapping without checking for inversions of eigenvectors.   Below we consider carrying out some boostrapping, plot the results and identify the most unreasonably volatile eigenvector.   We can use the sign of this eigenvector to adjust the signs of all the other components of this eigenvector and hence obtain bootstrap estimates of the eigenvectors.\n\nThen we call the function with our data, and tell it how many sets of bootstraps we want:\n\n\\singlespacing\n\\begin{verbatim}\n> library(boot)\n> hep.boot <- boot(hep.scale, theta, R = 50, sim = \"ordinary\")\n> eigen.bootplot(hep.boot,8,7)\n\\end{verbatim}\n\\onehalfspacing\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width = 0.7\\textwidth]{images/boottraceplot}\n\\caption{Trace of bootstrap iterations for first eigenvector}\n\\label{boottrace}\n\\end{center}\n\\end{figure}\n\nIt is quite clear that we need to invert some eigenvectors.   One approach is to identify one coefficient within an eigenvector and whenever this is below zero to multiply the entire vector by the scalar -1.   \n\n\\singlespacing\n\\begin{verbatim}\n> idx <- hep.boot$t[,8] < 0\n> hep.boot$t[idx,c(8:14)] <- hep.boot$t[idx,c(8:14)] * -1\n> eigen.bootplot(hep.boot,8,7)\n\\end{verbatim}\n\\onehalfspacing\n\nIn this way we can obtain additional information on the variability of our principal component analysis.\n\n\n\n\n\\subsection{Other structure matrices}\n\n\nWe might also be interested in testing for other structure matrices, such as equi-correlation.   See \\cite{Lawley:1963}.\n\n\\begin{eqnarray*}\n\\bar{r}_{k} = \\frac{1}{p-1} \\sum_{i=1; i \\neq k}^{p} r_{ik}; k = 1, \\ldots, p\\\\\n\\bar{r} = \\frac{2}{p(p-1)} \\sum_{i<k} \\sum r_{ik}\\\\\n\\hat{alpha} = \\frac{(p-1)^{2} \\left[ 1 - (1 - \\bar{r})^{2} \\right] }{\np - (p - 2)(1 - \\bar{r})^{2}}\n\\end{eqnarray*}\n\nwhere $\\frac{n-1}{(1-\\bar{r})^{2}} \\alpha$ follows a $T^{2}$ distribution.\n\nProof: JW 489  \n\n\\begin{verbatim}\nmean(spot[lower.tri(spot)])\n\\end{verbatim}\n\n\n\n\n\\subsection{Forward search}\n\nA more recent proposal for assessing the stability of principal component solution is the forward search \\cite{Atkinson+etal:2004}.\n\n\n\\subsection{Assessing multivariate normality}\n\\label{mahalpca}\n\nIf we are prepared to entertain the idea that our data might be multivariate normal, it is very simple to obtain distance measures from the principal component scores and examine the adequacy of a representation in this context (clearly this might not be so useful if we are cannot assume multivariate normality).   Given a random vector $\\boldsymbol{x}$ having mean $\\boldsymbol{\\mu}$ and covariance matrix $\\boldsymbol{\\Sigma}$, \\cite{Flury:1997} (page 608-609) demonstrates the relationship between the principal component scores $z_{j}$ and the mahalanobis distance $\\delta^{2}(\\boldsymbol{x}, \\boldsymbol{\\mu})$ (which he calls the squared standard distance).   \n\n\\begin{theorem}\n\\begin{equation}\n\\label{Qstats}\n\\delta^{2}(\\boldsymbol{x}, \\boldsymbol{\\mu}) = (\\boldsymbol{x} -  \\boldsymbol{\\mu}) \\boldsymbol{\\Sigma}^{-1} (\\boldsymbol{x} -  \\boldsymbol{\\mu}) = \\sum_{j=1}^{p} \\frac{z_{j}^{2}}{\\lambda_{j}}\n\\end{equation}\nwhere $\\boldsymbol{z} = (z_{1}, \\ldots, z_{p})^{T} = \\boldsymbol{E}(\\boldsymbol{x}- \\boldsymbol{\\mu})$, and $\\boldsymbol{\\Sigma} = \\boldsymbol{E \\Lambda E}^{T}$ as above.   \n\\end{theorem}\nProof: See \\cite{Flury:1997}\n\nWe can use our principal component representation to partition the mahalanobis distance.   We want $\\delta_{a}^{2} =  \\sum_{j=1}^{q} \\frac{z_{j}^{2}}{\\lambda_{j}}$ corresponding to the distance encapsulated in our first $q$ principal components, and $\\delta_{b}^{2} =  \\sum_{j=q+1}^{p} \\frac{z_{j}^{2}}{\\lambda_{j}}$ corresponding to the distances encapsulated by the last $(p-q)$ principal components.   \\cite{Flury:1997} indicates that these can be represented by $\\chi^{2}$ random variables with respectively $q$ and $p-q$ degrees of freedom which lends itself to diagnostic assesment of the adequacy of the principal component representation.   It should perhaps be noted that this is a large sample approximation, \\cite{Gnanadesikan:1977} (page 172) suggests $n = 25$ is adequate in the bivariate case.   \\cite{Bilodeau+Brenner:1999} (page 186) therefore indicate the use of the Beta distribution, with $\\alpha = \\frac{p-2}{2p}$ and $\\beta = \\frac{n - p - 2}{2(n - p - 1)}$.   \n\n\nIt is possible to write a simple function to extract the distances associated with accepted and rejected principal component (and the total distance) which can then be used in various diagnostic plots.\n\n\\singlespacing\n\\begin{verbatim}\n> princomp2dist <- function(obj.princomp, retain){\n scores <- t(t(obj.princomp$scores^2) / obj.princomp$sdev)\n dtot <- apply(scores, 1, sum)\n d1 <- apply(scores[,c(1:retain)], 1, sum)\n d2 <- apply(scores[,-c(1:retain)], 1, sum)\n dists <- data.frame(dtot = dtot, d1 = d1, d2 = d2)\n return(dists)\n}\n\n> hept.princomp <- princomp(hept.df[-1], scores = TRUE, scale = TRUE)\n> ## form a princomp object\n> hept.m <- princomp2dist(hept.princomp, 3)\n> ## extract distances based on 3 component representation\n\\end{verbatim}\n\\onehalfspacing\n\nHaving obtained the distances, we only need some suitable method of investigation.   The most useful are qq-plots.   Given we have only 26 rows and 9 columns, we will use a modified verion of the \\texttt{qqbeta} function given by \\cite{Bilodeau+Brenner:1999}.   This plots the Mahalanobis distance against a suitable beta distribution.\n\n\\singlespacing\n\\begin{verbatim}\n> qqbetaM <- function(x, p) {\n  n <- length(x)\n  a <- p/2\n  b <- (n-p-1)/2\n  alpha <- 0.5*(a-1)/a\n  beta <- 0.5*(b-1)/b\n  x <- sort(x)\n  y <- qbeta(((1:n)-alpha)/(n-alpha-beta+1),a,b)*(n-1)^2/n\n  plot(x,y,xlab=\"Mahalanobis distances\",ylab=\"Beta quantiles\")\n}\n> qqbetaM(hept.m$dtot,  7)\n\\end{verbatim}\n\\onehalfspacing\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width = 0.6\\textwidth]{images/qqd1}\n\\caption{Mahalanobis distance from three component representation of the Heptathalon data versus theoretical quantiles of the Beta(1.5, 10) distribution}\n\\label{qqd1}\n\\end{center}\n\\end{figure}\n\nIt is reasonably clear from figure \\ref{qqd1} that there are reasons to doubt multivariate normality, particularly in relation to outliers.    \n\nNevertheless, if we persevere, the adequacy of the $q=3$ dimensional representation can be considered.   Plotting $\\delta_{a}^{2}$ against  $\\delta_{b}^{2}$ provides one way of identifying those points not well represented by the three dimensional projection.\n\n\\singlespacing\n\\begin{verbatim}\n> plot(hept.m$d1, hept.m$d2, \n  xlab = \"Represented by q\", ylab = \"Not represented by q\", \n  main = \"Mahalanobis distances\")\n> identify(hept.m$d1, hept.m$d2, row.names(hept.df))\n\\end{verbatim}\n\\onehalfspacing\n\n%It is equally possible to consider the mahalanobis distance in conventional desnsity plots.\n\n%\\singlespacing\n%\\begin{verbatim}\n%library(MASS)\n%truehist(hept.m$dtot, nbins = 9, ylim = c(0,0.1))\n%curve(dchisq(x, df = 7), add = TRUE)\n%\\end{verbatim}\n%\\onehalfspacing\n\n%\\includegraphics{images/d1d2}\n\n%It should be noted that our ``outlier'' is only an outlier in the sense that she is not adequately represented by the first three principal components.   \n\nHowever, qq plots of the data do tend to suggest that she could be considered an outlier.   This takes us back to the start of the chapter; in this case we may wish to consider a robust principal component analysis.\n\n\\singlespacing\n\\begin{verbatim}\n> hep.princomp <- princomp(hept.df[-1], cor = TRUE)\n> hep.cor.rob <- cov.rob(hept.df[,-1], cor = TRUE)$cor\n> hep.princomp.rob <- princomp(cov = hep.cor.rob)\n> hep.princomp\n> hep.princomp.rob\n> loadings(hep.princomp)\n> loadings(hep.princomp.rob)\n\\end{verbatim}\n\\onehalfspacing\n\nIn this case it should be seen that there is only a slight difference between the estimates for the eigenvalues, but the loadings do alter somewhat.   Further methods for robust principal components will be considered in the next chapter.\n\n\n\\section{Interpreting the principal components}\n\nThis is the area that gets principal components a bad name.   Sometimes referred to as \\textit{reification}, we look at the loadings on the various components, and try to suggest a concept that the component may be referring to.    Factor analysis does something similar.\n\nIt is worth at this point considering the correlation between a given variable and the principal component score (or projection of the data in $q$ dimensional subspace).\n\n\\begin{definition}\nThe univariate correlation between a variable and it's principal compnent projection can be given by:\n\\begin{displaymath}\n\\rho_{z,x_{k}} = \\frac{e_{i}, \\lambda_{i}}{\\sqrt{\\sigma_{kk}}}\n\\end{displaymath}\n\\end{definition}\n\\textbf{Proof}:[page 462] \\cite{Johnson+Wichern:2002}\n\nIt should be noted that this only measures the unvariate contribution of $x$ to $z$, something \\cite{Rencher:2002} feels is useless but something which may serve as a means to an end.\n\nThe corresponding measure for principal component analysis based on the correlation matrix is given by:\n$\\rho_{z, x_{standardised}} = e_{ik} \\sqrt{\\lambda_{i}}$\n\n\n\\section{Exercises}\n\n\\begin{enumerate}\n\n\\item Consider data $\\boldsymbol{X} = \\left( \\begin{array}{ccc} 1 & 2 & 3 \\\\ 1 & 2 & 3 \\end{array} \\right) $.   Find the covariance and correlation matrix for these data.\n\n\\item Consider $\\boldsymbol{S} = \\left( \\begin{array}{cc} 5 & 2 \\\\ 2 & 1 \\end{array} \\right) $.   Convert $\\boldsymbol{S}$ into $\\boldsymbol{R}$.   Calculate the principal components from each matrix.   Comare and contrast.   \n\n\\item Calculate $\\rho_{z, x}$\n\n\\item S = diag(2,4,2), what are evals and evecs\n\n\\item Couple of questions on equicorrelation matrices\n\n\\item Estimate Sx and Sx.\n\n\\item Carapace data - how many pcs (sphericity test, bootstrap, scree, blah blah blah)\n\n\\end{enumerate}\n\n%%% Local Variables: ***\n%%% mode:latex ***\n%%% TeX-master: \"../book.tex\"  ***\n%%% End: ***\n", "meta": {"hexsha": "4cecd2de743d19cfd10c52f4c23d2c350056cfd9", "size": 81088, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/prcompchapter.tex", "max_stars_repo_name": "phewson/mvstats", "max_stars_repo_head_hexsha": "f39ab1c1b97c89e26c708bd6d532fe13c063a95c", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/prcompchapter.tex", "max_issues_repo_name": "phewson/mvstats", "max_issues_repo_head_hexsha": "f39ab1c1b97c89e26c708bd6d532fe13c063a95c", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2020-08-28T16:37:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-28T16:49:11.000Z", "max_forks_repo_path": "chapters/prcompchapter.tex", "max_forks_repo_name": "phewson/mvstats", "max_forks_repo_head_hexsha": "f39ab1c1b97c89e26c708bd6d532fe13c063a95c", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.4528675016, "max_line_length": 1291, "alphanum_fraction": 0.7293680939, "num_tokens": 22950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.33486236465043556}}
{"text": "\\documentclass[12pt]{article}\n\n\\usepackage{headerfooter}\n\\usepackage{epsfig}\n\\usepackage{verbatimfiles}\n\\usepackage{fullpage}\n\\usepackage{amsmath}\n\n\\newcommand{\\HRule}{\\rule{\\linewidth}{.3mm}}\n\n\\bibliographystyle{plain}\n\\begin{document}\n\n\\begin{center}\n{\\bf \\Large Uniaxial Return Mapping Algorithm}\n\n{\\bf August 21, 2001} \n\n{\\bf Michael H. Scott} \n\n{\\bf PEER, University of California, Berkeley}\n\\end{center}\n\nThis document outlines the return mapping algorithm for a rate-independent\nuniaxial material\nmodel with combined isotropic and kinematic hardening. The algorithm and its\nderivation are given in Simo and Hughes~\\cite{Simo:1998}.\n\nThe material parameters are the elastic modulus, $E$, yield stress,\n$\\sigma_y$, isotropic hardening modulus, $H_{iso}$, and kinematic hardening\nmodulus, $H_{kin}$. Path dependence is tracked by the plastic strain,\n$\\varepsilon^p$, internal hardening variable, $\\alpha$, and back\nstress, $\\kappa$.\n\n\\section*{Model Description}\nThe model assumes an elastic stress-strain relationship with elastic modulus $E$.\nThe onset of plastic flow occurs upon yielding, after which the elastoplastic\ntangent is given by $\\frac{E(H_{iso}+H_{kin})}{E+H_{iso}+H_{kin}}$, as shown\nin figure~\\ref{fig:StressStrain}.\n\n\\begin{figure}[htpb]\n\\begin{center}\n\\input{./fig_files/StressStrain.pstex_t}\n\\end{center}\n\\caption{Elastic and elastoplastic tangent}\n\\label{fig:StressStrain}\n\\end{figure}\n\nIsotropic hardening can be thought of as an ``expansion'' of the elastic region.\nThe internal hardening variable, $\\alpha$, tracks the growth of the elastic\nregion.\nKinematic hardening corresponds to a ``translation'' of the elastic region.\nThe back stress, $\\kappa$, is the center of the elastic region. When there is\nno kinematic hardening, $\\kappa$ is zero.\nThese two hardening rules are shown in figure~\\ref{fig:HardeningBehavior}, and\nthey can be combined to give mixed hardening behavior.\n\n\\begin{figure}[htpb]\n\\begin{center}\n\\input{./fig_files/HardeningBehavior.pstex_t}\n\\end{center}\n\\caption{Isotropic and kinematic hardening behavior}\n\\label{fig:HardeningBehavior}\n\\end{figure}\n\n\\section*{Continuum Equations}\n\n\\begin{enumerate}\n\\item{} Elastic stress-strain relationship\n\\begin{equation}\n\\sigma = E \\left( \\varepsilon-\\varepsilon^p \\right)\n\\end{equation}\n\n\\item{} Flow rule\n\\begin{equation}\n\\dot{\\varepsilon}^p = \\gamma \\mbox{sign}\\left( \\sigma-\\kappa \\right)\n\\end{equation}\n\n\\item{} Isotropic and kinematic hardening laws\n\\begin{align}\n\\dot{\\alpha} &= \\gamma \\\\\n\\dot{\\kappa} &= \\gamma H_{kin} \\mbox{sign}\\left( \\sigma-\\kappa \\right)\n\\end{align}\n\n\\item{} Yield condition\n\\begin{equation}\nf(\\sigma, \\kappa, \\alpha) = \\left| \\sigma-\\kappa \\right| -\n\\left( \\sigma_y + H_{iso}\\alpha \\right) \\leq 0\n\\end{equation}\n\n\\item{} Kuhn-Tucker complementary conditions\n\\begin{align}\n\\gamma &\\geq 0 \\\\\nf(\\sigma, \\kappa, \\alpha) &\\leq 0 \\\\\n\\gamma f(\\sigma, \\kappa, \\alpha) &= 0\n\\end{align}\n\n\\item{} Consistency condition\n\\begin{equation}\n\\gamma \\dot{f}(\\sigma, \\kappa, \\alpha) = 0 \\:\\:\\:\\:\\:\n\\mbox{(if $f(\\sigma, \\kappa, \\alpha)$ = 0)}\n\\end{equation}\n\n\\end{enumerate}\n\n\\section*{Return Mapping Algorithm}\n\n\\begin{enumerate}\n\n\\item{} Committed state at time $t_n$\n\\begin{equation}\n\\left\\{ \\varepsilon_n^p, \\alpha_n, \\kappa_n \\right\\}\n\\end{equation}\n\n\\item{} Given trial strain at time $t_{n+1}$,\n\\begin{equation}\n\\varepsilon_{n+1} = \\varepsilon_n + \\Delta\\varepsilon_n,\n\\end{equation}\n\n\\noindent determine the corresponding stress, $\\sigma_{n+1}$, and\ntangent, $D_{n+1}$; proceed to step 3.\n\n\\item{} Compute trial stress and test for plastic loading\n\\begin{align}\n\\sigma_{n+1}^{trial} &= E \\left( \\varepsilon_{n+1} - \\varepsilon_n^p \\right) \\\\\n\\xi_{n+1}^{trial} &= \\sigma_{n+1}^{trial} - \\kappa_n \\\\\nf_{n+1}^{trial} &= \\left| \\xi_{n+1}^{trial} \\right| -\n                  \\left( \\sigma_y + H_{iso}\\alpha_n \\right)\n\\end{align}\n\n\\begin{center}\nIf $f_{n+1} \\leq 0$, this is an elastic step; set\n$\\sigma_{n+1} = \\sigma_{n+1}^{trial}, D_{n+1} = E$, and exit. \\\\\nElse, this is a plastic step; proceed to step 4.\n\\end{center}\n\n\\item{} Return mapping\n\\begin{align}\n\\Delta\\gamma &= \\frac{f_{n+1}^{trial}}{E+H_{iso}+H_{kin}} \\\\\n\\sigma_{n+1} &= \\sigma_{n+1}^{trial} - \\Delta\\gamma E \\mbox{sign}(\\xi_{n+1}^{trial}) \\\\\n\\varepsilon_{n+1}^p &= \\varepsilon_n^p + \\Delta\\gamma \\mbox{sign}(\\xi_{n+1}^{trial}) \\\\\n\\kappa_{n+1} &= \\kappa_n + \\Delta\\gamma H_{kin} \\mbox{sign}(\\xi_{n+1}^{trial}) \\\\\n\\alpha_{n+1} &= \\alpha_n + \\Delta\\gamma \\\\\nD_{n+1} &= \\frac{E(H_{iso}+H_{kin})}{E+H_{iso}+H_{kin}}\n\\end{align}\n\n\\end{enumerate}\n\n\\begin{thebibliography}{99}\n\\bibitem{Simo:1998} J.C. Simo and T.J.R. Hughes,\n\\emph{Computational Inelasticity}. Springer-Verlag, 1998.\n\\end{thebibliography}\n\n\\end{document}\n", "meta": {"hexsha": "68e8e415af599615701e521f3146ff59ad24e679", "size": 4683, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "OpenSees/SRC/doc/ReturnMap.tex", "max_stars_repo_name": "kuanshi/ductile-fracture", "max_stars_repo_head_hexsha": "ccb350564df54f5c5ec3a079100effe261b46650", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-03-05T16:25:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-17T14:12:03.000Z", "max_issues_repo_path": "SRC/doc/ReturnMap.tex", "max_issues_repo_name": "steva44/OpenSees", "max_issues_repo_head_hexsha": "417c3be117992a108c6bbbcf5c9b63806b9362ab", "max_issues_repo_licenses": ["TCL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SRC/doc/ReturnMap.tex", "max_forks_repo_name": "steva44/OpenSees", "max_forks_repo_head_hexsha": "417c3be117992a108c6bbbcf5c9b63806b9362ab", "max_forks_repo_licenses": ["TCL"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-09-21T03:11:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-19T07:29:37.000Z", "avg_line_length": 30.2129032258, "max_line_length": 87, "alphanum_fraction": 0.708306641, "num_tokens": 1576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.33486236465043556}}
{"text": "\\documentclass{article}\n\\usepackage[utf8]{inputenc}\n\n\\title{PS8_Cocklin}\n\\author{connorcocklin }\n\\date{March 2019}\n\n\\usepackage{natbib}\n\\usepackage{graphicx}\n\n\\begin{document}\n\n\\maketitle\n\n\\section{Summary Table}\nThe true values for Beta were [1.5 -1 -.25 0.75 3.5 -2 0.5 1 1.25 2]. The beta hat regression found coefficients incredibly close to the true numbers stated for Beta. All values have been rounded to the nearest thousandth. \n\n\\begin{table}[!htbp] \\centering \n  \\caption{} \n  \\label{} \n\\begin{tabular}{@{\\extracolsep{5pt}}lc} \n\\\\[-1.8ex]\\hline \n\\hline \\\\[-1.8ex] \n & \\multicolumn{1}{c}{\\textit{Dependent variable:}} \\\\ \n\\cline{2-2} \n\\\\[-1.8ex] & y \\\\ \n\\hline \\\\[-1.8ex] \n X1 & 1.501$^{***}$ \\\\ \n  & (0.002) \\\\ \n  & \\\\ \n X2 & $-$0.991$^{***}$ \\\\ \n  & (0.003) \\\\ \n  & \\\\ \n X3 & $-$0.247$^{***}$ \\\\ \n  & (0.003) \\\\ \n  & \\\\ \n X4 & 0.744$^{***}$ \\\\ \n  & (0.003) \\\\ \n  & \\\\ \n X5 & 3.504$^{***}$ \\\\ \n  & (0.003) \\\\ \n  & \\\\ \n X6 & $-$1.999$^{***}$ \\\\ \n  & (0.003) \\\\ \n  & \\\\ \n X7 & 0.502$^{***}$ \\\\ \n  & (0.003) \\\\ \n  & \\\\ \n X8 & 0.997$^{***}$ \\\\ \n  & (0.003) \\\\ \n  & \\\\ \n X9 & 1.256$^{***}$ \\\\ \n  & (0.003) \\\\ \n  & \\\\ \n X10 & 1.999$^{***}$ \\\\ \n  & (0.003) \\\\ \n  & \\\\ \n\\hline \\\\[-1.8ex] \nObservations & 100,000 \\\\ \nR$^{2}$ & 0.971 \\\\ \nAdjusted R$^{2}$ & 0.971 \\\\ \nResidual Std. Error & 0.500 (df = 99990) \\\\ \nF Statistic & 338,240.000$^{***}$ (df = 10; 99990) \\\\ \n\\hline \n\\hline \\\\[-1.8ex] \n\\textit{Note:}  & \\multicolumn{1}{r}{$^{*}$p$<$0.1; $^{**}$p$<$0.05; $^{***}$p$<$0.01} \\\\ \n\\end{tabular} \n\\end{table} \n\n\\end{document}\n", "meta": {"hexsha": "ecc5cab9911f96383f9f4b607041357dac00834a", "size": 1529, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ProblemSets/PS8/PS8_Cocklin.tex", "max_stars_repo_name": "connorcocklin/DScourseS19", "max_stars_repo_head_hexsha": "9ad16e78d6b98acabbd4aeb78230451fc0597370", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProblemSets/PS8/PS8_Cocklin.tex", "max_issues_repo_name": "connorcocklin/DScourseS19", "max_issues_repo_head_hexsha": "9ad16e78d6b98acabbd4aeb78230451fc0597370", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProblemSets/PS8/PS8_Cocklin.tex", "max_forks_repo_name": "connorcocklin/DScourseS19", "max_forks_repo_head_hexsha": "9ad16e78d6b98acabbd4aeb78230451fc0597370", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5352112676, "max_line_length": 223, "alphanum_fraction": 0.491824722, "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.33486236465043556}}
{"text": "\\section{Monte-Carlo Methods}\n\\subsection{Exercise 5.1}\n\\subsubsection*{Q}\nConsider the diagrams on the right in Figure 5.1. Why does the estimated value function jump up for the last two rows in the rear? Why does it drop off for the whole last row on the left? Why are the frontmost values higher in the upper diagrams than in the lower?\n\n\\subsubsection*{A}\n\\begin{itemize}\n    \\item Policy is to hit unless $S \\geq 20$. So you run a rik of going bust if you have 12-19, but you most likely win when you stick on 20 or 21\n    \\item Drops off because dealer has a usable ace\n    \\item Frontmost higher because you're less likely to go bust, but you still might get to 20 or 21 ($\\pi$ always hits here).\n\\end{itemize}\n\n\\subsection{Exercise 5.2}\n\\subsubsection*{Q}\nSuppose every-visit MC was used instead of first-visit MC on the blackjack task. Would you expect the results to be very different? Why or why not?\n\n\\subsubsection*{A}\nResults would be the same because this game is memoryless (cards are drawn with replacement).\n\n\\subsection{Exercise 5.3}\n\\subsubsection*{Q}\nWhat is the backup diagram for Monte Carlo estimation of $q_\\pi$?\n\n\\subsubsection*{A}\nThe same as the one shown in the book for state valus, only we have state-action pairs instead of states.\n\n\\subsection{Exercise 5.4}\n\\subsubsection*{Q}\nWhat is the equation analogous to (5.6) for \\emph{action} values $Q(s, a)$ instead of state values $V(s)$, again given returns generated using $b$?\n\\subsubsection*{A}\nWe condition on taking action $a$ in state $s$.\n\\[\n    q_\\pi(s, a) = \\Epi{}[\\rho_{t+1:T-1} G_t | S_t = s, A_t = s]\n\\]\nwith returns generated from $b$. We estimate this quantity by\n\\[\n    Q(s, a) = \\frac{\\sum_{t \\in \\mathcal{T}(s, a)} \\rho_{t+1:T-1} G_t}{\\sum_{t \\in \\mathcal{T}(s, a)} \\rho_{t+1:T-1}}\n\\]\nwhere $\\mathcal{T}(s, a)$ now contains timestamps of visits to state-action pairs.\n\n\\subsection{Exercise 5.5}\n\\subsubsection*{Q}\nIn learning curves such as those shown in Figure 5.3 error generally decreases with training, as indeed happened for the ordinary importance-sampling method. But for the weighted importance-sampling method error first increased and then decreased. Why do you think this happened?\n\n\\subsubsection*{A}\nWhen there are fewer episodes the importance sampling ratios will be zero with higher probability since the behaviour policy will stick on values smaller than 20 (since it is random). Zero happens to be close to $v_\\pi(s)$.\\\\\n\nThis effect lessens as we get more diversity in the episode trajectories.\\\\\n\nThen after this the error reduces because the variance in the estimator reduces.\n\n\\subsection{Exercise 5.6}\n\\subsubsection*{Q}\nThe results with Example 5.5 and shown in Figure 5.4 used a first-visit MC method. Suppose that instead an every-visit MC method was used on the same problem. Would the variance of the estimator still be infinite? Why or why not?\n\\subsubsection*{A}\nYes, all terms in the sum are $\\geq 0$ and there woud just be more of them.\n\n\\subsection{Exercise 5.7}\n\\subsubsection*{Q}\nModify the algorithm for first-visit MC policy evaluation (Section 5.1) to use the incremental implementation for sample averages described in Section 2.4.\n\n\\subsubsection*{A}\nAlgo is the same apart from \n\\begin{itemize}\n    \\item Initialise $V(s) = 0 \\quad \\forall s \\in S$\n    \\item Don't need \\emph{Returns(s)} lists.\n    \\item Remove the last two lines and put in \\[ V(S_t) \\leftarrow V(S_t) + \\frac{1}{T- t}[ G_t - V(S_t) ] \\]\n\\end{itemize}\n\n\\subsection{Exercise 5.8}\n\\subsubsection*{Q}\nDerive the weighted-average update rule (5.8) from (5.7). Follow the pattern of the derivation of the unweighted rule (2.3).\n\n\\subsubsection*{A}\nHave $C_0 = 0$, $C_n = \\sum_{k = 1}^n W_k$ and \n\\[\n    V_{n+1} = \\frac{\\sum_{k = 1}^n W_kG_k}{C_n}.\n\\]\nTherefore,\n\\begin{align}\n    C_n V_{n+1} &= \\sum_{k+1}^{n-1}W_kG_k + W_kG_k\\\\\n                &= C_{n-1}V_n + W_nG_n \\\\\n                &= (C_n - W_n)V_n + W_nG_n.\n\\end{align}\nFinally\n\\[\n    V_{n+1} = V_n + \\frac{W_n}{C_n}[G_n - V_n].\n\\]\n\n\\subsection{Exercise 5.9}\n\\subsubsection*{Q}\nIn the boxed algorithm for off-policy MC control, you may have been expecting the W update to have involved the importance-sampling ratio $\\pi(A_t|S_t)$, but instead it involves $1/b(A_t|S_t)$. Why is this nevertheless correct?\n\n\\subsubsection*{A}\n$\\pi$ is greedy, so \n\\[\n    \\pi(a | s) = \\mathds{1}\\{a = \\argmax_{a'} Q(s, a')\\}.\n\\]\n\n\\subsection{Exercise 5.10 (programming): Racetrack}\n\\subsubsection*{Q}\nConsider driving a race car around a turn like those shown in Figure 5.5. You want to go as fast as possible, but not so fast as to run off the track. In our simplified racetrack, the car is at one of a discrete set of grid positions, the cells in the diagram. The velocity is also discrete, a number of grid cells moved horizontally and vertically per time step. The actions are increments to the velocity components. Each may be changed by +1, -1, or 0 in each step, for a total of nine ($3 \\times 3$) actions. Both velocity components are restricted to be nonnegative and less than 5, and they cannot both be zero except at the starting line. Each episode begins in one of the randomly selected start states with both velocity components zero and ends when the car crosses the finish line. The rewards are -1 for each step until the car crosses the finish line. If the car hits the track boundary, it is moved back to a random position on the starting line, both velocity components are reduced to zero, and the episode continues. Before updating the car’s location at each time step, check to see if the projected path of the car intersects the track boundary. If it intersects the finish line, the episode ends; if it intersects anywhere else, the car is considered to have hit the track boundary and is sent back to the starting line. To make the task more challenging, with probability 0.1 at each time step the velocity increments are both zero, independently of the intended increments. Apply a Monte Carlo control method to this task to compute the optimal policy from each starting state. Exhibit several trajectories following the optimal policy (but turn the noise off for these trajectories).\n\\subsubsection*{A}\n\\ProgrammingExercise\\\\\n\\includegraphics[width=\\textwidth]{\\ProjectDir/data/exercise_output/ex_5_10/track_1_trajectories.eps}\n\n\\includegraphics[width=\\textwidth]{\\ProjectDir/data/exercise_output/ex_5_10/track_2_sample_trajectory.eps}\n\n\\subsection{*Exercise 5.11}\n\\subsubsection*{Q}\nModify the algorithm for off-policy Monte Carlo control (page 110) to use the idea of the truncated weighted-average estimator (5.10). Note that you will first need to convert this equation to action values.\n\n\\subsubsection*{A}\n... ", "meta": {"hexsha": "5581bc93643ba113a9f24ebdd538f73d6317f927", "size": 6680, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "exercises/chapters/chapter5/chapter5_content.tex", "max_stars_repo_name": "ElliotMunro200/reinforcement_learning_an_introduction", "max_stars_repo_head_hexsha": "c4fccb46a4bb00955549be3505144ec49f0132e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 234, "max_stars_repo_stars_event_min_datetime": "2018-09-01T00:26:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T03:55:50.000Z", "max_issues_repo_path": "exercises/chapters/chapter5/chapter5_content.tex", "max_issues_repo_name": "15779235038/reinforcement_learning_an_introduction", "max_issues_repo_head_hexsha": "a0ac9e5da6eaeae14d297a560c499d1a6e579c2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2018-11-29T21:04:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T17:11:50.000Z", "max_forks_repo_path": "exercises/chapters/chapter5/chapter5_content.tex", "max_forks_repo_name": "15779235038/reinforcement_learning_an_introduction", "max_forks_repo_head_hexsha": "a0ac9e5da6eaeae14d297a560c499d1a6e579c2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 63, "max_forks_repo_forks_event_min_datetime": "2018-07-31T04:53:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T04:03:43.000Z", "avg_line_length": 58.5964912281, "max_line_length": 1706, "alphanum_fraction": 0.7431137725, "num_tokens": 1827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.33486236465043556}}
{"text": "\\section{Introduction}\n\\label{sec:introduction}\n\nKleene~\\cite{KleeneSC:intint} introduced realizability as a model of\nintuitionistic arithmetic based on partial computable functions. The\nidea has since been studied and generalized by various\nauthors~\\cite{TroelstraA:rea,HylandJ:efft,HylandJ:trit,OostenJ:exer}.\nBuilding on the idea of \\emph{typed realizability} by\nLongley~\\cite{Longley00}, we have constructed a tool \\RZ to\ntranslate mathematical theories into specifications for code,\nexplaining what is necessary in order to believe that we have a correct\nimplementation of the mathematical theory.\n\nAs the realizability interpretation validates the laws of\n\\emph{intuitionistic} logic, our input theories are intuitionistic or\nconstructive. Thus, \\RZ extracts the computational\nmeaning of a constructive theory and expresses it as a programming\nspecification.\n\nWe emphasize that \\RZ does \\emph{not} extract programs from proofs---in\nfact, there is no way to write a proof in our system. We just\ndetermine what the programs are supposed to do, i.e., we provide\nspecifications for them. We leave it to the programmer, or to another\ntool, to construct the programs as he or she sees fit. This leaves\nthe programmer completely free to write efficient programs\nthat need not correspond directly to a formal proof.\n\nThe original aim of \\RZ was to aid development of data structures\nfor computable mathematics. If one sets out to actually compute\nrealizability interpretations of theories of constructive mathematics,\none quickly wishes for an automated way of doing it. With a tool like\nRZ it is much easier to experiment and try out variations of a theory\nuntil a suitable specification is obtained.  It also appears that\nRZ can be used to explain and teach constructive mathematics to\nprogrammers, who are typically trained in classical mathematics; \nit translates constructive statements into easily understood\nrequirements about programs (expressed in classical logic).\n\n%We assume throughout that we have chosen a fixed programming\n%language~$\\PL$. %Any ML-like language will do~\\cite{milner+:definition}. \nOur implementation of \\RZ produces interfaces in Objective\nCaml~\\cite{ocaml} but could easily be adopted to other similar typed\nlanguages.  The essential features we require of the target language\nare product, function, and sum types, as well as support for module\ninterfaces.\n\nThe paper is organized as follows. Section~\\ref{sec:realizability}\ncontains a brief overview of realizability. In\nSection~\\ref{sec:theories-signatures} we describe theories and\nsignatures, which are the inputs and the outputs of RZ, respectively. In\nSection~\\ref{sec:implementation} we discuss various point of\nimplementation. In Section~\\ref{sec:examples} we show typical examples\nand conclude with Section~\\ref{sec:conclusion}.\n\n\n%%% Local Variables: \n%%% mode: latex\n%%% TeX-master: \"case\"\n%%% End: \n", "meta": {"hexsha": "f31b1a2918a86ecaa4ccbe1d5b6cf616039b0b48", "size": 2892, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "private/clase/intro.tex", "max_stars_repo_name": "andrejbauer/rz", "max_stars_repo_head_hexsha": "d92cacaf78fb50d61fc6712c74b8fdaf5d2c6d28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-08-28T10:12:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-07T21:04:22.000Z", "max_issues_repo_path": "private/clase/intro.tex", "max_issues_repo_name": "andrejbauer/rz", "max_issues_repo_head_hexsha": "d92cacaf78fb50d61fc6712c74b8fdaf5d2c6d28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "private/clase/intro.tex", "max_forks_repo_name": "andrejbauer/rz", "max_forks_repo_head_hexsha": "d92cacaf78fb50d61fc6712c74b8fdaf5d2c6d28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.2, "max_line_length": 74, "alphanum_fraction": 0.8067081604, "num_tokens": 665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.33486235575795464}}
{"text": "\\documentclass[12pt]{article}\n\n\\usepackage[margin=1.9cm, letterpaper]{geometry}\n\\usepackage{fontspec}\n\\usepackage{mathtools}\n\\usepackage{pgfplots}\n\n\\pgfplotsset{compat=newest}\n\n\\title{EXPERIMENT 2: \\protect\\\\ Electrostatic Potential \\protect\\\\ and Fields}\n\\date{February 5, 2019}\n\\author{Michael Kwok | Partner: Cyrus Diego }\n\n\\begin{document}\n\\maketitle\n\\pagebreak\n\n\\section{Introduction}\n\nIn this experiment, we are investigating the effect of Gauss’ laws using a circular and parallel plate capacitor by measuring the potential differences between two conductors in both cases. Due to the relatively simple shapes of the capacitors (two concentric circles and two parallel rectangles), the results can easily be correlated to Gauss’ laws. Since this experiment is conducted with a DC power source as the source of charge, we will be using electrostatic equations which are defined below,\n\n\\textbf{Bold} variables represent vectors\n\n\\begin{equation} \\label{eq:ln_eq}\n    \\ln r = \\ln \\frac{A}{B}(\\frac{V_r-V_B}{V_0})+\\ln B\n\\end{equation}\n\nwhere $r$  is the distance of the test point from the center of the circle, $A$\nand $B$ are the calculated radii, $V_r$, $V_B$, $V_0$ are the measured voltages.\n\nThe equation used to find the strength of the electric field would be:\n\n\\begin{equation} \\label{eq:ef_strength}\n    E=-\\frac{\\Delta V}{\\Delta S}\n\\end{equation}\n\n\\section{Methods}\n\nFor part 1, connect the power supply to both leads of the capacitor, and a\nvoltmeter with the ground side connected to the negative end of the power\nsupply, and the probe on the appropriate slot of the voltmeter. Record the\nvoltages at the appropriate distances from the centre of the capacitor, in this\ncase every 0.5 cm. Adjust precision of voltmeter as necessary. We opted on\nrecording up to 3 significant digits whenever possible.\n\nFor part 2, like the first part, the power supply leads should be connected to\nboth plates, and the voltmeter with the ground connected to the negative end as\nwell. Probe the conductive sheet at regular intervals in a grid pattern,\nrecording the voltage in each spot.\n\n\\section{Results}\n\\begin{center}\n\\begin{tabular}{ |r|r| }\n    \\hline\n    Radius (cm) & $V_r - V_B$ (V) \\\\ \\hline\n    2.5 & 3.55\\\\\n    3.0 & 3.22\\\\\n    3.5 & 4.0\\\\\n    \\hline\n\\end{tabular}\n\\begin{tabular}{ |r|r| }\n    \\hline\n    $\\frac{V_r-V_B}{V_0}$ & $\\ln r$ (V) \\\\ \\hline\n    2.5 & 3.55\\\\\n    3.0 & 3.22\\\\\n    3.5 & 4.0\\\\\n    \\hline\n\\end{tabular}\n\\end{center}\n\n% Graph test\n\\begin{tikzpicture}\n    \\begin{axis}[\n      domain=-1:1,\n      samples=101,\n      smooth,\n      no markers,\n      ]\n      \\addplot {x};\n    \\end{axis}\n  \\end{tikzpicture}\n  \n\\section{Discussion}\n\\section{Conclusion}\n\\pagebreak\n\\section*{References}\n\\pagebreak\n\\section*{Appendix}\n\\end{document}", "meta": {"hexsha": "11d9135cfe585758e344c9985fcaf61ad4464053", "size": 2757, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "LabReports/PHYS230/LAB1.tex", "max_stars_repo_name": "n30phyte/SchoolDocuments", "max_stars_repo_head_hexsha": "79652ec7e3345d67e67f0cffe3bea468708622bd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LabReports/PHYS230/LAB1.tex", "max_issues_repo_name": "n30phyte/SchoolDocuments", "max_issues_repo_head_hexsha": "79652ec7e3345d67e67f0cffe3bea468708622bd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LabReports/PHYS230/LAB1.tex", "max_forks_repo_name": "n30phyte/SchoolDocuments", "max_forks_repo_head_hexsha": "79652ec7e3345d67e67f0cffe3bea468708622bd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9775280899, "max_line_length": 499, "alphanum_fraction": 0.7199854915, "num_tokens": 823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704502361149, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.33486235575795453}}
{"text": "\\documentclass[11pt]{article}\n\\usepackage{geometry}                % See geometry.pdf to learn the layout options. There are lots.\n\\geometry{a4paper}                   % ... or a4paper or a5paper or ... \n%\\geometry{landscape}                % Activate for for rotated page geometry\n%\\usepackage[parfill]{parskip}    % Activate to begin paragraphs with an empty line rather than an indent\n\\usepackage{graphicx}\n\\usepackage{amssymb}\n\\usepackage{amsmath}\n\\usepackage{lipsum}\n\\usepackage{authblk}\n%\\usepackage{amsaddr}\n\\usepackage{epstopdf}\n\\usepackage{booktabs}\n\\usepackage{xcolor}\n\\usepackage{fancyhdr}\n\\usepackage[yyyymmdd,hhmmss]{datetime}\n\\pagestyle{fancy}\n\\rfoot{Compiled on \\today\\ at \\currenttime}\n\\cfoot{}\n\\lfoot{Page \\thepage}\n\\RequirePackage[colorinlistoftodos,prependcaption,textsize=tiny]{todonotes} % look for '\\todo'\n\\definecolor{darkred}{rgb}{0.4,0.0,0.0}\n\\definecolor{darkgreen}{rgb}{0.0,0.4,0.0}\n\\definecolor{darkblue}{rgb}{0.0,0.0,0.4}\n\\usepackage[bookmarks,linktocpage,colorlinks,\n    linkcolor = darkred,\n    urlcolor  = darkblue,\n    citecolor = darkgreen]{hyperref}\n\n%\\DeclareGraphicsRule{.tif}{png}{.png}{`convert #1 `dirname #1`/`basename #1 .tif`.png}\n\n\\renewcommand{\\headrulewidth}{0pt}\n\\fancyhead[L]{\n%\\includegraphics[width=4cm]{/Users/tomluu/Research/talks/fzjTemplate/uniBonn_logo.jpg}\n}\n\\fancyhead[R]{\n\\includegraphics[width=4cm]{figs/fzj_logo.jpg}\n}\n\\pagestyle{plain}\n\n\\title{Tower of operators}\n\\author[1,2]{Thomas Luu}\n\\affil[1]{Institute for Advanced Simulation 4\\\\\nForschungszentrum J\\\"ulich, Germany}\n\\affil[2]{Rheinische Friedrich-Williams-Universit\\\"at Bonn, Germany}\n\n%\\email{t.luu@fz-juelich.de}\n\\date{}                                           % Activate to display a given date or no date\n\n\n\\begin{document}\n\\maketitle\n\\begin{center}\nemail: \\href{mailto:t.luu@fz-juelich.de}{t.luu@fz-juelich.de}\n\\end{center}\n\\abstract{\nHere I try to determine the scattering amplitude for an interaction of the type\n\\begin{displaymath}\nV(p',p)=C_0+\\frac{C_2}{2}\\left(p'^2+p^2\\right)\n\\end{displaymath}\nand I assume a hard-cutoff regulator.\n}\n\n\\thispagestyle{fancy}\n\n\\clearpage{}\n%\\tableofcontents\n%\\newpage\n\n\\section{Interaction}\nI assume an interaction of the form\n\\begin{equation}\\label{eqn:potential}\nV(p',p)=\\left(C_0+C_2\\frac{\\left(p'^2+p^2\\right)}{2}\\right)f_\\Lambda(p')f_\\Lambda(p)\n\\end{equation}\nwith an implicit hard-cutoff regulator at some scale $\\Lambda$,\n\\begin{equation}\nf_\\Lambda(p)=\\Theta\\left(|p|-\\Lambda\\right)\\ .\n\\end{equation}\n Note that this interaction is a sum of separable terms, and there is NO delta function (we are in momentum space).  The coefficients $C_n$ are bare parameters and must be ``renormalized\"\n \n \\section{T-matrix}\n The T-matrix is defined as\n \\begin{equation}\n T(p',p;E)\\equiv V(p',p)+\\int \\frac{d^3q}{(2\\pi)^3} V(p',q) G_0(q;E) T(q,p;E)\\ ,\n \\end{equation}\n where\n \\begin{equation}\n G_0(q;E)=\\frac{1}{E-q^2/m+i\\epsilon}\\ .\n \\end{equation}\n Another relation, which is actually more useful when deriving the T-matrix, is the expression for the fully interacting propagator, which I write in operator form\n \\begin{equation}\\label{eqn:full G}\n \\hat G(E)\\equiv \\frac{1}{E-\\hat H_0-\\hat V+i\\epsilon}=\\hat G_0(E)+\\hat G_0(E)\\hat T(E)\\hat G_0(E)\\ .\n \\end{equation}\n \n \\subsection{Summing the T-matrix}\nI can sum the T-matrix to all orders in $V(p',p)$ since $V(p',p)$ is a sum of separable terms.   I will present my derivations (based off eq.~\\eqref{eqn:full G}) for the full T-matrix in later sections, but only express the result here\n\\begin{multline}\\label{eqn:T-matrix 1}\nT(p',p;E)=\\\\\n\\frac{\\mathbb{C}_0+\\mathbb{C}_2\\frac{\\left(p'^2+p^2\\right)}{2}+\\mathbb{X}_4\\  p'^2p^2}\n{1-C_0I_0(E)-C_2I_2(E)-\\frac{1}{4}C^2_2\\left[I_0(E)I_4(E)-I_2(E)^2\\right]}f_\\Lambda(p')f_\\Lambda(p)\\ ,\n\\end{multline}\nwhere\n\\begin{align}\n\\mathbb{C}_0&=C_0+\\frac{1}{4}C^2_2I_4(E)\\\\\n\\mathbb{C}_2&=C_2-\\frac{1}{2}C^2_2I_2(E)\\\\\n\\mathbb{X}_4&=\\frac{1}{4}C^2_2I_0(E)\\ ,\n\\end{align}\nand\\footnote{I assume we are in the infinite-volume, continuum limit, and therefore perform the integrals in a spherical basis.}\n\\begin{equation}\nI_n(E)\\equiv \\frac{1}{2\\pi^2}\\int_0^\\Lambda dq\\frac{q^{2+n}}{E-q^2/m+i\\epsilon}\\ .\n\\end{equation}\nNote that the solution to the T-matrix has an \\emph{induced} higher-order term $\\mathbb{X}_4p'^2p^2$.  \n\nWe can also relate all terms $I_{n>0}(E)$ to $I_0(E)$,\n\\begin{align}\nI_2(E)&=-\\frac{m}{6\\pi^2}\\Lambda^3+[mE]\\  I_0(E)\\\\\nI_4(E)&=-\\frac{m}{10\\pi^2}\\Lambda^5-[mE]\\ \\frac{m}{6\\pi^2}\\Lambda^3+[mE]^2\\ I_0(E)\\ .\n\\end{align}\nAnd finally, we have that\n\\begin{equation}\nI_0(E)=-\\frac{m}{2\\pi^2}\\Lambda -i \\frac{m}{4\\pi}\\sqrt{mE}+\\frac{m}{2\\pi^2\\Lambda}mE+\\mathcal{O}(\\Lambda^{-3})\\ .\n\\end{equation}\nWith these relations, the \\emph{denominator} in eq.~\\eqref{eqn:T-matrix 1} becomes\n\\begin{multline}\\label{eqn:denominator}\n1-C_0 I_0(E)-C_2 \\left([mE]\\ I_0(E) -\\frac{\\Lambda ^3 m}{6 \\pi ^2}\\right)\\\\\n+C_2^2 \\left(I_0(E) \\left(\\frac{\\Lambda ^5 m}{40 \\pi\n   ^2}-\\frac{\\Lambda ^3 m\\ [mE]}{24 \\pi ^2}\\right)+\\frac{\\Lambda ^6 m^2}{144 \\pi\n   ^4}\\right)\n   \\end{multline}\n\n\\section{Scattering amplitude near threshold}\nNear threshold I set everything on-shell, $p'=p=\\sqrt{mE}$.  In this limit, the \\emph{numerator} of eq.~\\eqref{eqn:T-matrix 1} becomes\n\\begin{equation}\\label{eqn:numerator}\nC_0+C_2 p^2+C_2^2 \\left(\\frac{\\Lambda ^3 m p^2}{24 \\pi ^2}-\\frac{\\Lambda ^5 m}{40 \\pi\n   ^2}\\right)\\ .\n   \\end{equation}\n% and one has that\n%\\begin{equation}\n%T(p'=p; E=p^2/m)\\equiv T(p)=\\frac{4\\pi/m}{p\\cot \\delta -ip}\n%\\end{equation}\n%or equivalently\n%\\begin{equation}\n%p\\cot \\delta -ip=\\frac{4\\pi}{m\\ T(p)}\\ .\n%\\end{equation}\n%Plugging everything in, I get\n%\\begin{multline}\\label{eqn:matching 1}\n%p\\cot \\delta -ip=\\\\\n%\\frac{4\\pi}{m}\\frac{1-(C_0 +C_2 p^2)I_0(E)+C_2 \\frac{\\Lambda ^3 m}{6 \\pi ^2}\n%+C_2^2 \\left(I_0(E) \\left(\\frac{\\Lambda ^5 m}{40 \\pi\n%   ^2}-\\frac{\\Lambda ^3 mp^2}{24 \\pi ^2}\\right)+\\frac{\\Lambda ^6 m^2}{144 \\pi\n%   ^4}\\right)}{C_0+C_2 p^2+C_2^2 \\left(\\frac{\\Lambda ^3 m p^2}{24 \\pi ^2}-\\frac{\\Lambda ^5 m}{40 \\pi\n%   ^2}\\right)}\n%   \\end{multline}\n%   \nNow I define the renormalized coefficients,\n\\begin{align}\nC_0(\\Lambda)&=C_0-C_2^2\\frac{\\Lambda^5 m}{40 \\pi^2}\\\\\nC_2(\\Lambda)&=C_2\\left(1+C_2\\frac{\\Lambda^3 m}{24\\pi^2}\\right)\\ ,\n\\end{align}\nwhich means eq.~\\eqref{eqn:numerator} becomes\n\\begin{equation}\n\\sum_{n=0,1}C_{2n}(\\Lambda)p^{2n}\\ .\n\\end{equation}\nThe denominator, eq.~\\eqref{eqn:denominator}, becomes\n\\begin{multline}\n1-I_0(E)\\sum_{n=0,1}C_{2n}(\\Lambda)p^{2n}+\\frac{\\Lambda ^3 m}{6 \\pi ^2}C_2 \\left(1+\nC_2 \\frac{\\Lambda ^3 m}{24 \\pi\n   ^2}\\right)\\\\\n   =1-I_0(E)\\sum_{n=0,1}C_{2n}(\\Lambda)p^{2n}+C_2(\\Lambda) \\frac{\\Lambda ^3 m}{6 \\pi ^2}\\ .\n\\end{multline}\nSo the full on-shell T-matrix near threshold is\n\\begin{equation}\nT(E=p^2/m)=-\\frac{4\\pi/m}{p\\cot \\delta -ip}=\\frac{\\sum_{n=0,1}C_{2n}(\\Lambda)p^{2n}}{1-I_0(E)\\sum_{n=0,1}C_{2n}(\\Lambda)p^{2n}+C_2(\\Lambda) \\frac{\\Lambda ^3 m}{6 \\pi ^2}}\\ .\n\\end{equation}\nThis expression is \\emph{almost} like eq.(1) of Beane et al. (hep-lat0312004) ``Two-Nucleons on a Lattice\",\n\\begin{displaymath}\n\\mathcal{A}=\\frac{\\sum C_{2 n}(\\mu) p^{2 n}}{1-I_{0} \\sum C_{2 n}(\\mu) p^{2 n}}\\ ,\n\\end{displaymath}\nexcept for the extra \\emph{induced} term $C_2(\\Lambda) \\frac{\\Lambda ^3 m}{6 \\pi ^2}$ in the denominator.  \n\n\\section{So do we have a ``Tower of Interactions\"?}\nI \\emph{suspect} what happens (this is by no means a proof) is that as we include more terms in our potential, eq.~\\eqref{eqn:potential}, the induced term gets pushed to higher and higher order.  One must be consistent in adding more terms into the potential, however (i.e. derivative expansion w/ Galilean invariance, etc. . .--essentially pionless EFT).  \n\nFor example, if we include a $C_4$ term into our potential, then I suspect we would get for the scattering amplitude\n \\begin{equation}\n \\frac{\\sum_{n=0,1,2}C_{2n}(\\Lambda)p^{2n}}{1-I_0(E)\\sum_{n=0,1,2}C_{2n}(\\Lambda)p^{2n}+C_4(\\Lambda) \\mathcal{C}\\Lambda^5}\\ ,\n \\end{equation}\n where $\\mathcal{C}$ is some coefficient.  If this is true (and I'm not going to even attempt to prove this), then only in the limit of an ``infinite tower of interactions\" do we recover Beane et al.'s expression,\n\\begin{equation}\n\\frac{\\sum C_{2 n}(\\Lambda) p^{2 n}}{1-I_{0}(E) \\sum C_{2 n}(\\Lambda) p^{2 n}}\\ ,\n\\end{equation}\n\n\\section{Summing the T-matrix}\nLater. . .\n\n%Then eq.~\\eqref{eqn:matching 1} becomes\n%\\begin{align}\\label{eqn:matching 2}\n%p\\cot \\delta -ip&=\n%\\frac{4\\pi}{m}\\frac{1-I_0(E)\\sum_{n=0,1}C_{2n}(\\Lambda)p^{2n}+C_2 \\frac{\\Lambda ^3 m}{6 \\pi ^2}\\left(1+\n%C_2 \\frac{\\Lambda ^3 m}{24 \\pi\n%   ^2}\\right)}{\\sum_{n=0,1}C_{2n}(\\Lambda)p^{2n}}\\\\\\\n%   &=\\frac{4\\pi}{m}\\left(\\frac{1}{\\sum_{n=0,1}C_{2n}(\\Lambda)p^{2n}}-I_0(E)+\\frac{C_2 \\frac{\\Lambda ^3 m}{6 \\pi ^2}\\left(1+\n%C_2 \\frac{\\Lambda ^3 m}{24 \\pi\n%   ^2}\\right)}{\\sum_{n=0,1}C_{2n}(\\Lambda)p^{2n}}\\right)\n%\\end{align}\n%\\subsection{}\n\n%\\newpage\n%\\appendix\n\n%\\clearpage\n%\\bibliography{references}\n\n\\end{document}  \n", "meta": {"hexsha": "f6d79e26c5896e81a1f405bbdc3b3a3dc42a352c", "size": 8887, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "notes/towerOps.tex", "max_stars_repo_name": "ckoerber/luescher-nd", "max_stars_repo_head_hexsha": "d1bc6bff0c6ee9f4dc0d1d0bb4bcfa842c44cceb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-04-12T22:19:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-26T14:06:49.000Z", "max_issues_repo_path": "notes/towerOps.tex", "max_issues_repo_name": "ckoerber/luescher-nd", "max_issues_repo_head_hexsha": "d1bc6bff0c6ee9f4dc0d1d0bb4bcfa842c44cceb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2019-12-16T19:49:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-02T00:50:31.000Z", "max_forks_repo_path": "notes/towerOps.tex", "max_forks_repo_name": "ckoerber/luescher-nd", "max_forks_repo_head_hexsha": "d1bc6bff0c6ee9f4dc0d1d0bb4bcfa842c44cceb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3348837209, "max_line_length": 357, "alphanum_fraction": 0.6757060875, "num_tokens": 3469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.33468867895652665}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n\\chapter{Kind Inference for Datatypes}\n\\label{chap:kindinference}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n\nIn recent years, languages like Haskell have seen a dramatic surge of new\nfeatures that significantly extends the expressive power of their type systems.\nWith these features, the challenge of \\emph{kind inference} for datatype\ndeclarations has presented itself and become a worthy research problem on its\nown.\n\nIn this chapter, we apply promotion to kind inference for datatypes. Inspired by\nprevious research on type-inference, we offer declarative specifications for\nwhat datatype declarations should be accepted, both for \\hne and for a more\nadvanced system we call \\tit, based on the extensions in modern Haskell,\nincluding a limited form of dependent types. We believe these formulations to be\nnovel and without precedent, even for \\hne. These specifications are\ncomplemented with implementable algorithmic versions. We study \\emph{soundness},\n\\emph{completeness} and the existence of \\emph{principal kinds} in these\nsystems, proving the properties where they hold. This work can serve as a guide\nboth to language designers who wish to formalize their datatype declarations and\nalso to implementors keen to have principled inference of principal types.\n\n\\input{Gen/KindInference/introduction.lhstex}\n\\input{Gen/KindInference/haskell98.lhstex}\n\\input{Gen/KindInference/haskell98_algo.lhstex}\n\\input{Gen/KindInference/haskell98_tparm.lhstex}\n\\input{Gen/KindInference/typeintype.lhstex}\n\\input{Gen/KindInference/typeintype_algo.lhstex}\n\\input{Gen/KindInference/extension.lhstex}\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: \"../Thesis\"\n%%% org-ref-default-bibliography: \"../Thesis.bib\"\n%%% End:", "meta": {"hexsha": "55ad871fc095626afe61e03d9a626139d2e39816", "size": 1820, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Sources/KindInference.tex", "max_stars_repo_name": "xnning/Dissertation", "max_stars_repo_head_hexsha": "bcdca568b3e89ba9cc0e4e9858a34e7c008a4ebb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-09-07T00:43:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T23:07:52.000Z", "max_issues_repo_path": "Sources/KindInference.tex", "max_issues_repo_name": "xnning/Dissertation", "max_issues_repo_head_hexsha": "bcdca568b3e89ba9cc0e4e9858a34e7c008a4ebb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sources/KindInference.tex", "max_forks_repo_name": "xnning/Dissertation", "max_forks_repo_head_hexsha": "bcdca568b3e89ba9cc0e4e9858a34e7c008a4ebb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-15T08:46:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T08:46:35.000Z", "avg_line_length": 50.5555555556, "max_line_length": 80, "alphanum_fraction": 0.743956044, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.33468867895652665}}
{"text": "\\section{Performance Measurement}\n\nIn this section, we will outline some basics of several of the more useful \nprofilers available in \\thispackage.\n\n\\subsection{flips and flops}\n\n\\thispackage offers two high-level utilities for measuring floating point \nperformance data: \\code{system.flips()} and \\code{system.flops()}.  \nThe former captures floating point instruction measurements; a \\textit{flip} is \nthe rate of floating point instructions (flpins), or the number of flpins per \nsecond.  Perhaps the more well-known measurement is the rate of floating point \n\\emph{operations}.  Like its cousin \\code{system.flips()}, the \\thispackage \nfunction \\code{system.flops()} will measure both the number of floating point \noperations as well as their rate --- the number of floating point operations \nper second, or flops.\n\nGenerally, reports of flops (or flips) are not given, but Mega-flops (Mflops); \nas the name implies, 1 Mflop is 1,000,000 flops.\n\n\n\n\\paragraph{Theoretical flops}\n\nA processor has a theoretical peak number of flops, which is typically much \nhigher than what is found experimentally.  Still, understanding the peak flops \nof a system can be useful in understanding ``good'' flops performance of a \nprogram (just understand that it will always be lower in practice than the \ntheoretical peak).\n\nThe equation below demonstrates how to compute the peak Mflops of a processor:\n\\begin{align*}\n\\text{Mflops} = \\text{(\\# cores)} * \\text{(Speed in Mhz)} *\n\\text{(\\# of SSE units per core)} *  \\text{(\\# SSE operations per cycle)}\n\\end{align*}\n\nsingle precision Mflops (divide by 2 for double precision).  So for this Intel \nSandy Bridge Core i7 as a reference, the theoretical peak is:\n\\begin{align*}\n\\text{Mflops} &= (4) * (2800 Mhz) * 2 * 2\n\\end{align*}\n\nwhich is roughly 45 single precision Gflops, or 22.5 double precision Gflops \n--- 22,500,000,000 floating point operations per second!\n\nSee where your computer stacks up against the fastest supercomputers in the \nworld at \\href{http://www.top500.org/}{top500.org}.  For instance, again using \nthis laptop as a reference, and using theoretical flops as a proxy for running \nthe Linpack benchmark (which is not really fair, we grant), we would crush \nevery supercomputer on the list from June 1997, but wouldn't make the cut for \nJune 1999.\n\n\n\n\\subsection{Cache Misses and Cache Hits}\n\n\\paragraph{Memory and Cache}\n\nComputers operate at \\emph{billions} of cycles per second.  Of course, those  \noperations occur on data.  A useful abstraction we use in thinking about \nprocessing data is you load the stuff up into RAM and then the processor does \nthings to it.  This is usually fine, or at least convenient, but it's not \naccurate, as you are probably aware.  \n\n\\begin{figure}[ht]\n  \\centering\n  \\includegraphics[scale=.54]{./include/pics/memory}\n  \\caption{Computer Memory Hierarchy}\n  \\label{fig:mem}\n\\end{figure}\nAnother more accurate abstraction is that shown in Figure~\\ref{fig:mem}.  In a \nsense, the magic really happens when things get into the CPU registers.  But \nsomething that's in RAM that you want to operate on, as it's headed to the CPU, \ngets cached into various levels of (comparatively) fast access storage along \nthe way.  Understanding this behavior, and writing your code to take advantage \nof it, can have \\emph{tremendous} impacts on performance.\n\n\\begin{figure}[ht]\n  \\centering\n  \\includegraphics[scale=.54]{./include/pics/cache}\n  \\caption{Detailed Computer Memory Hierarchy}\n  \\label{fig:mem2}\n\\end{figure}\nA more detailed presentation of Figure~\\ref{fig:mem} is that found in \nFigure~\\ref{fig:mem2}.  Here we see a more accurate presentation; for example, \nL3 cache (if it exists) is shared by all cores on a moder CPU, with L2 private, \nand L1 split into data and instruction caches.  The lookup costs in terms of \nprocessor cycles are provided for each type of memory.  These ``times'' are \npresented in terms of the CPU cycle for mostly historical reasons, though there \nis benefit to thinking in these terms (for example, when trying to minimize \nwait cycles).  Though note that a faster processor could actually \n\\emph{increase} these costs, specifically RAM to L3 lookups.\n\nIf you are unfamiliar with the importance (or existence) of cache, I would \nstrongly encourage you to experiment with this great\n\\href{http://www.overbyte.com.au/misc/Lesson3/CacheFun.html}%\n{interactive visualization} \nshowing (relative) speeds of cache misses. It too involves some simplifications \nof how modern hardware actually works, so if this is at all confusing, let us \nall take a moment to pity the tragic life of the computer engineer.  Another \ngreat resource is this\n\\href{http://www.eecs.berkeley.edu/~rcs/research/interactive_latency.html}%\n{interactive visualization} showing memory and cache latency numbers by year.\n\n\n\n\n\n\\paragraph{Cache Misses} Fundamentally, a cache miss occurs when the cache \nneeds some piece of data to pass along to registers, but it isn't immediately \navailable and the computer has to go digging through RAM (or god help you, \ndisk) to get it.  Cache misses are bad and reduce performance.  You can't get \nrid of them completely, unless your entire problem --- copies and all --- \ncomfortably fits into cache, but you can eliminate \\emph{unnecessary} cache \nmisses being aware of how your data and algorithms interact with cache.  See \nthe demo \\code{cache_access.r} in \\thispackage for an example of good versus \nbad cache access.\n", "meta": {"hexsha": "e4122c7948aedb15886f0fd1795b62de9026734b", "size": 5451, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "vignettes/include/03-background.tex", "max_stars_repo_name": "wrathematics/pbdPAPI", "max_stars_repo_head_hexsha": "cb3fad3bccd54b7aeeef9e687b52d938613a356e", "max_stars_repo_licenses": ["Intel", "BSD-3-Clause"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2015-02-14T17:00:51.000Z", "max_stars_repo_stars_event_max_datetime": "2016-02-01T20:13:43.000Z", "max_issues_repo_path": "vignettes/include/03-background.tex", "max_issues_repo_name": "QuantScientist3/pbdPAPI", "max_issues_repo_head_hexsha": "708bee501de20eb82829e03b92b24b6352044f49", "max_issues_repo_licenses": ["Intel", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vignettes/include/03-background.tex", "max_forks_repo_name": "QuantScientist3/pbdPAPI", "max_forks_repo_head_hexsha": "708bee501de20eb82829e03b92b24b6352044f49", "max_forks_repo_licenses": ["Intel", "BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-09-05T05:21:14.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-28T16:17:37.000Z", "avg_line_length": 46.1949152542, "max_line_length": 80, "alphanum_fraction": 0.766831774, "num_tokens": 1354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.3346886718591733}}
{"text": "\\section{{\\Large$\\langle j_0\\rangle$ }Form factors for 3d transition elements and their ions}\n\\begin{table}[H]\n\\caption{\\noindent $\\langle j_0\\rangle$ Form factors for 3d transition elements and their ions\\hfill}\n\\label{3dj0}\n\\vspace{2mm}\n{\\tablesize\n\\begin{tabular}{lrrrrrrr}\n\\hline\nIon&\n\\multicolumn{1}{c}{A}&\\multicolumn{1}{c}{a}&\n\\multicolumn{1}{c}{B}&\\multicolumn{1}{c}{b}&\n\\multicolumn{1}{c}{C}&\\multicolumn{1}{c}{c}&\\multicolumn{1}{c}{D}\\\\\n\\hline\\\\[-2ex]\nSc0 &$0.2512$ &$90.0296$ &$0.3290$ &$39.4021$ &$0.4235$ &$14.3222$ &$-0.0043$ \\\\\nSc1 &$0.4889$ &$51.1603$ &$0.5203$ &$14.0764$ &$-0.0286$ &$0.1792$ &$0.0185$ \\\\\nSc2 &$0.5048$ &$31.4035$ &$0.5186$ &$10.9897$ &$-0.0241$ &$1.1831$ &$0.0000$ \\\\\nTi0 &$0.4657$ &$33.5898$ &$0.5490$ &$9.8791$ &$-0.0291$ &$0.3232$ &$0.0123$ \\\\\nTi1 &$0.5093$ &$36.7033$ &$0.5032$ &$10.3713$ &$-0.0263$ &$0.3106$ &$0.0116$ \\\\\nTi2 &$0.5091$ &$24.9763$ &$0.5162$ &$8.7569$ &$-0.0281$ &$0.9160$ &$0.0015$ \\\\\nTi3 &$0.3571$ &$22.8413$ &$0.6688$ &$8.9306$ &$-0.0354$ &$0.4833$ &$0.0099$ \\\\\nV0 &$0.4086$ &$28.8109$ &$0.6077$ &$8.5437$ &$-0.0295$ &$0.2768$ &$0.0123$ \\\\\nV1 &$0.4444$ &$32.6479$ &$0.5683$ &$9.0971$ &$-0.2285$ &$0.0218$ &$0.2150$ \\\\\nV2 &$0.4085$ &$23.8526$ &$0.6091$ &$8.2456$ &$-0.1676$ &$0.0415$ &$0.1496$ \\\\\nV3 &$0.3598$ &$19.3364$ &$0.6632$ &$7.6172$ &$-0.3064$ &$0.0296$ &$0.2835$ \\\\\nV4 &$0.3106$ &$16.8160$ &$0.7198$ &$7.0487$ &$-0.0521$ &$0.3020$ &$0.0221$ \\\\\nCr0 &$0.1135$ &$45.1990$ &$0.3481$ &$19.4931$ &$0.5477$ &$7.3542$ &$-0.0092$ \\\\\nCr1 &$-0.0977$ &$0.0470$ &$0.4544$ &$26.0054$ &$0.5579$ &$7.4892$ &$0.0831$ \\\\\nCr2 &$1.2024$ &$-0.0055$ &$0.4158$ &$20.5475$ &$0.6032$ &$6.9560$ &$-1.2218$ \\\\\nCr3 &$-0.3094$ &$0.0274$ &$0.3680$ &$17.0355$ &$0.6559$ &$6.5236$ &$0.2856$ \\\\\nCr4 &$-0.2320$ &$0.0433$ &$0.3101$ &$14.9518$ &$0.7182$ &$6.1726$ &$0.2042$ \\\\\nMn0 &$0.2438$ &$24.9629$ &$0.1472$ &$15.6728$ &$0.6189$ &$6.5403$ &$-0.0105$ \\\\\nMn1 &$-0.0138$ &$0.4213$ &$0.4231$ &$24.6680$ &$0.5905$ &$6.6545$ &$-0.0010$ \\\\\nMn2 &$0.4220$ &$17.6840$ &$0.5948$ &$6.0050$ &$0.0043$ &$-0.6090$ &$-0.0219$ \\\\\nMn3 &$0.4198$ &$14.2829$ &$0.6054$ &$5.4689$ &$0.9241$ &$-0.0088$ &$-0.9498$ \\\\\nMn4 &$0.3760$ &$12.5661$ &$0.6602$ &$5.1329$ &$-0.0372$ &$0.5630$ &$0.0011$ \\\\\nFe0 &$0.0706$ &$35.0085$ &$0.3589$ &$15.3583$ &$0.5819$ &$5.5606$ &$-0.0114$ \\\\\nFe1 &$0.1251$ &$34.9633$ &$0.3629$ &$15.5144$ &$0.5223$ &$5.5914$ &$-0.0105$ \\\\\nFe2 &$0.0263$ &$34.9597$ &$0.3668$ &$15.9435$ &$0.6188$ &$5.5935$ &$-0.0119$ \\\\\nFe3 &$0.3972$ &$13.2442$ &$0.6295$ &$4.9034$ &$-0.0314$ &$0.3496$ &$0.0044$ \\\\\nFe4 &$0.3782$ &$11.3800$ &$0.6556$ &$4.5920$ &$-0.0346$ &$0.4833$ &$0.0005$ \\\\\nCo0 &$0.4139$ &$16.1616$ &$0.6013$ &$4.7805$ &$-0.1518$ &$0.0210$ &$0.1345$ \\\\\nCo1 &$0.0990$ &$33.1252$ &$0.3645$ &$15.1768$ &$0.5470$ &$5.0081$ &$-0.0109$ \\\\\nCo2 &$0.4332$ &$14.3553$ &$0.5857$ &$4.6077$ &$-0.0382$ &$0.1338$ &$0.0179$ \\\\\nCo3 &$0.3902$ &$12.5078$ &$0.6324$ &$4.4574$ &$-0.1500$ &$0.0343$ &$0.1272$ \\\\\nCo4 &$0.3515$ &$10.7785$ &$0.6778$ &$4.2343$ &$-0.0389$ &$0.2409$ &$0.0098$ \\\\\nNi0 &$-0.0172$ &$35.7392$ &$0.3174$ &$14.2689$ &$0.7136$ &$4.5661$ &$-0.0143$ \\\\\nNi1 &$0.0705$ &$35.8561$ &$0.3984$ &$13.8042$ &$0.5427$ &$4.3965$ &$-0.0118$ \\\\\nNi2 &$0.0163$ &$35.8826$ &$0.3916$ &$13.2233$ &$0.6052$ &$4.3388$ &$-0.0133$ \\\\\nNi3 &$0.0012$ &$34.9998$ &$0.3468$ &$11.9874$ &$0.6667$ &$4.2518$ &$-0.0148 $ \\\\\nNi4 &$-0.0090$ &$35.8614$ &$0.2776$ &$11.7904$ &$0.7474$ &$4.2011$ &$-0.0163$ \\\\\nCu0 &$0.0909$ &$34.9838$ &$0.4088$ &$11.4432$ &$0.5128$ &$3.8248$ &$-0.0124$ \\\\\nCu1 &$0.0749$ &$34.9656$ &$0.4147$ &$11.7642$ &$0.5238$ &$3.8497$ &$-0.0127$ \\\\\nCu2 &$0.0232$ &$34.9686$ &$0.4023$ &$11.5640$ &$0.5882$ &$3.8428$ &$-0.0137$ \\\\\nCu3 &$0.0031$ &$34.9074$ &$0.3582$ &$10.9138$ &$0.6531$ &$3.8279$ &$-0.0147$ \\\\\nCu4 &$-0.0132$ &$30.6817$ &$0.2801$ &$11.1626$ &$0.7490$ &$3.8172$ &$-0.0165$ \\\\\n\\hline\\\\[-2ex]\n\\end{tabular}\n}\n\\end{table}\n\\section{{\\large$\\langle j_0\\rangle$ }Form factors for 4d transition elements and their ions}\n\\begin{table}[H]\n\\caption{\n$\\langle j_0\\rangle$ form factors for 4d atoms and ions}\\vspace{2mm}\n\\label{4dj0}\n{\\tablesize\n\\begin{tabular}{lrrrrrrr}\n\\hline\nIon&\n\\multicolumn{1}{c}{A}&\\multicolumn{1}{c}{a}&\n\\multicolumn{1}{c}{B}&\\multicolumn{1}{c}{b}&\n\\multicolumn{1}{c}{C}&\\multicolumn{1}{c}{c}&\\multicolumn{1}{c}{D}\\\\\n\\hline\\\\[-2ex]\nY0 &$0.5915$ &$67.6081$ &$1.5123$ &$17.9004$ &$-1.1130$ &$14.1359$ &$0.0080$ \\\\\nZr0 &$0.4106$ &$59.9961$ &$1.0543$ &$18.6476$ &$-0.4751$ &$10.5400$ &$0.0106$ \\\\\nZr1 &$0.4532$ &$59.5948$ &$0.7834$ &$21.4357$ &$-0.2451$ &$9.0360$ &$0.0098$ \\\\\nNb0 &$0.3946$ &$49.2297$ &$1.3197$ &$14.8216$ &$-0.7269$ &$9.6156$ &$0.0129$ \\\\\nNb1 &$0.4572$ &$49.9182$ &$1.0274$ &$15.7256$ &$-0.4962$ &$9.1573$ &$0.0118$ \\\\\nMo0 &$0.1806$ &$49.0568$ &$1.2306$ &$14.7859$ &$-0.4268$ &$6.9866$ &$0.0171$ \\\\\nMo1 &$0.3500$ &$48.0354$ &$1.0305$ &$15.0604$ &$-0.3929$ &$7.4790$ &$0.0139$ \\\\\nTc0 &$0.1298$ &$49.6611$ &$1.1656$ &$14.1307$ &$-0.3134$ &$5.5129$ &$0.0195$ \\\\\nTc1 &$0.2674$ &$48.9566$ &$0.9569$ &$15.1413$ &$-0.2387$ &$5.4578$ &$0.0160$ \\\\\nRu0 &$0.1069$ &$49.4238$ &$1.1912$ &$12.7417$ &$-0.3176$ &$4.9125$ &$0.0213$ \\\\\nRu1 &$0.4410$ &$33.3086$ &$1.4775$ &$9.5531$ &$-0.9361$ &$6.7220$ &$0.0176$ \\\\\nRh0 &$0.0976$ &$49.8825$ &$1.1601$ &$11.8307$ &$-0.2789$ &$4.1266$ &$0.0234$ \\\\\nRh1 &$0.3342$ &$29.7564$ &$1.2209$ &$9.4384$ &$-0.5755$ &$5.3320$ &$0.0210$ \\\\\nPd0 &$0.2003$ &$29.3633$ &$1.1446$ &$9.5993$ &$-0.3689$ &$4.0423$ &$0.0251$ \\\\\nPd1 &$0.5033$ &$24.5037$ &$1.9982$ &$6.9082$ &$-1.5240$ &$5.5133$ &$0.0213$ \\\\\n\\hline\\\\[-2ex]\n\\end{tabular}\n}\n\\end{table}\n\\section{{\\large$\\langle j_0\\rangle$ }Form factors for 5d transition elements and their ions}\n\\begin{table}[H]\n \\caption{$\\langle j_0\\rangle$ form factors for the 5d electrons of transition atoms and ions from Hf to Re.\\cite{kob:11}}\n\\label{5dj0} \\vspace{1ex}\n{\\tablesize\n\\begin{tabular}{llrrrrrrrrr}\n\\hline\n\\multicolumn{1}{c}{ Ion}&\\multicolumn{1}{c}{ Config}&\\multicolumn{1}{c}{ A }&\\multicolumn{1}{c}{  a }&\\multicolumn{1}{c}{B }&\\multicolumn{1}{c}{ b }&\\multicolumn{1}{c}{ C }&\\multicolumn{1}{c}{ c }&\\multicolumn{1}{c}{ D }&\\multicolumn{1}{c}{ d }&\\multicolumn{1}{c}{E }\\\\\n\\hline\nHf2 & 6s05d2 &$0.4229$ &$50.465$ &$0.7333$ &$23.865$ &$-0.3798$ &$4.051$ &$0.2252$ &$2.497$ &$-0.0018$ \\\\\nHf3 & 6s05d1 &$0.3555$ &$40.954$ &$0.8483$ &$21.726$ &$-0.4116$ &$4.305$ &$0.2101$ &$2.349$ &$-0.0023$ \\\\\nTa2 & 6s05d3 &$0.3976$ &$45.095$ &$0.7746$ &$21.028$ &$-0.6098$ &$3.471$ &$0.4395$ &$2.570$ &$-0.0020$ \\\\\nTa3 & 6s05d2 &$0.3611$ &$36.921$ &$0.8579$ &$19.195$ &$-0.4945$ &$3.857$ &$0.2781$ &$2.303$ &$-0.0026$ \\\\\nTa4 & 6s05d1 &$0.3065$ &$31.817$ &$0.9611$ &$17.749$ &$-0.5463$ &$3.979$ &$0.2816$ &$2.232$ &$-0.0030$ \\\\\nW0 & 6s05d6 &$0.3990$ &$73.810$ &$0.7138$ &$22.815$ &$-2.0436$ &$2.710$ &$1.9319$ &$2.559$ &$-0.0023$ \\\\\nW0 & 6s15d5 &$0.3811$ &$62.707$ &$0.7523$ &$21.434$ &$-12.5449$ &$2.702$ &$12.4130$ &$2.674$ &$-0.0023$ \\\\\nW0 & 6s25d4 &$0.3653$ &$53.965$ &$0.7926$ &$20.078$ &$-0.8142$ &$3.030$ &$0.6581$ &$2.476$ &$-0.0023$ \\\\\nW0 & 6s05d5 &$0.4077$ &$51.367$ &$0.7436$ &$20.256$ &$-9.8283$ &$2.780$ &$9.6788$ &$2.740$ &$-0.0021$ \\\\\nW0 & 6s15d4 &$0.3834$ &$46.233$ &$0.7890$ &$19.278$ &$-1.4650$ &$2.947$ &$1.2945$ &$2.628$ &$-0.0022$ \\\\\nW2 & 6s05d4 &$0.3876$ &$40.340$ &$0.8008$ &$18.621$ &$-1.3911$ &$2.995$ &$1.2048$ &$2.627$ &$-0.0023$ \\\\\nW3 & 6s05d3 &$0.3610$ &$33.519$ &$0.8717$ &$17.176$ &$-0.6183$ &$3.445$ &$0.3883$ &$2.276$ &$-0.0028$ \\\\\nW4 & 6s05d2 &$0.3221$ &$29.047$ &$0.9574$ &$15.979$ &$-0.6287$ &$3.597$ &$0.3525$ &$2.174$ &$-0.0033$ \\\\\nW5 & 6s05d1 &$0.2725$ &$25.966$ &$1.0558$ &$14.954$ &$-0.6990$ &$3.643$ &$0.3745$ &$2.145$ &$-0.0037$ \\\\\nRe0 & 6s05d7 &$0.3807$ &$63.042$ &$0.7497$ &$19.967$ &$-6.5300$ &$2.501$ &$6.4013$ &$2.451$ &$-0.0028$ \\\\\nRe0 & 6s15d6 &$0.3691$ &$53.934$ &$0.7837$ &$18.790$ &$-9.1491$ &$2.558$ &$8.9983$ &$2.517$ &$-0.0027$ \\\\\nRe0 & 6s25d5 &$0.3548$ &$47.108$ &$0.8210$ &$17.769$ &$-9.8674$ &$2.599$ &$9.6938$ &$2.556$ &$-0.0027$ \\\\\nRe0 & 6s05d6 &$0.3944$ &$45.427$ &$0.7742$ &$17.948$ &$-3.1692$ &$2.653$ &$3.0028$ &$2.521$ &$-0.0026$ \\\\\nRe0 & 6s15d5 &$0.3736$ &$41.151$ &$0.8160$ &$17.158$ &$-7.0396$ &$2.642$ &$6.8523$ &$2.577$ &$-0.0026$ \\\\\nRe2 & 6s05d5 &$0.3825$ &$36.336$ &$0.8218$ &$16.636$ &$-8.7220$ &$2.657$ &$8.5201$ &$2.601$ &$-0.0026$ \\\\\nRe3 & 6s05d4 &$0.3585$ &$30.671$ &$0.8863$ &$15.527$ &$-0.8682$ &$3.047$ &$0.6263$ &$2.280$ &$-0.0030$ \\\\\nRe4 & 6s05d3 &$0.2974$ &$27.372$ &$0.9826$ &$14.807$ &$-1.8869$ &$2.840$ &$1.6100$ &$2.476$ &$-0.0031$ \\\\\nRe5 & 6s05d2 &$0.3143$ &$23.522$ &$1.0276$ &$13.505$ &$-0.7438$ &$3.393$ &$0.4059$ &$2.030$ &$-0.0041$ \\\\\nRe6 & 6s05d1 &$0.2146$ &$22.496$ &$1.1616$ &$13.064$ &$-1.0455$ &$3.162$ &$0.6734$ &$2.196$ &$-0.0041$ \\\\\n\\hline\n\\end{tabular}\n}\n\\end{table}\n\\begin{table}[H]\n \\caption{$\\langle j_0\\rangle$ form factors for the 5d electrons of transition atoms and ions from Os to Au.\\cite{kob:11}}\n \\label{5dj0b}\n \\vspace{1ex}\n{ \\tablesize\n\\begin{tabular}{llrrrrrrrrr}\n\\hline\n\\multicolumn{1}{c}{ Ion}&\\multicolumn{1}{c}{ Config}&\\multicolumn{1}{c}{ A }&\\multicolumn{1}{c}{  a }&\\multicolumn{1}{c}{B }&\\multicolumn{1}{c}{ b }&\\multicolumn{1}{c}{ C }&\\multicolumn{1}{c}{ c }&\\multicolumn{1}{c}{ D }&\\multicolumn{1}{c}{ d }&\\multicolumn{1}{c}{E}\\\\\n\\hline\nOs0 & 6s05d8 &$0.3676$ &$54.835$ &$0.7793$ &$17.716$ &$-2.0669$ &$2.418$ &$1.9224$ &$2.247$ &$-0.0034$ \\\\\nOs0 & 6s15d7 &$0.3571$ &$47.458$ &$0.8123$ &$16.770$ &$-1.2072$ &$2.556$ &$1.0404$ &$2.211$ &$-0.0033$ \\\\\nOs0 & 6s25d6 &$0.3467$ &$41.778$ &$0.8458$ &$15.918$ &$-5.6370$ &$2.459$ &$5.4472$ &$2.381$ &$-0.0032$ \\\\\nOs0 & 6s05d7 &$0.3837$ &$40.665$ &$0.8006$ &$16.096$ &$-3.5305$ &$2.487$ &$3.3488$ &$2.366$ &$-0.0030$ \\\\\nOs0 & 6s15d6 &$0.3666$ &$36.997$ &$0.8390$ &$15.425$ &$-2.6944$ &$2.537$ &$2.4916$ &$2.360$ &$-0.0031$ \\\\\nOs2 & 6s05d6 &$0.3786$ &$33.005$ &$0.8412$ &$14.990$ &$-7.0632$ &$2.503$ &$6.8462$ &$2.433$ &$-0.0030$ \\\\\nOs3 & 6s05d5 &$0.3557$ &$28.222$ &$0.9002$ &$14.140$ &$-2.5972$ &$2.601$ &$2.3444$ &$2.376$ &$-0.0032$ \\\\\nOs4 & 6s05d4 &$0.3337$ &$24.723$ &$0.9655$ &$13.288$ &$-0.9653$ &$2.906$ &$0.6698$ &$2.117$ &$-0.0037$ \\\\\nOs5 & 6s05d3 &$0.3055$ &$22.152$ &$1.0395$ &$12.529$ &$-0.9158$ &$3.016$ &$0.5750$ &$2.032$ &$-0.0042$ \\\\\nOs6 & 6s05d2 &$0.2714$ &$20.218$ &$1.1211$ &$11.851$ &$-0.9773$ &$3.050$ &$0.5894$ &$2.005$ &$-0.0046$ \\\\\nOs7 & 6s05d1 &$0.2101$ &$19.108$ &$1.2240$ &$11.347$ &$-1.2543$ &$2.933$ &$0.8250$ &$2.088$ &$-0.0048$ \\\\\nIr0 & 6s05d9 &$0.3564$ &$48.464$ &$0.8049$ &$15.923$ &$-2.5258$ &$2.265$ &$2.3675$ &$2.121$ &$-0.0040$ \\\\\nIr0 & 6s15d8 &$0.3492$ &$42.195$ &$0.8350$ &$15.113$ &$-5.1496$ &$2.279$ &$4.9686$ &$2.201$ &$-0.0038$ \\\\\nIr0 & 6s25d7 &$0.3400$ &$37.499$ &$0.8675$ &$14.402$ &$-2.3703$ &$2.370$ &$2.1661$ &$2.177$ &$-0.0037$ \\\\\nIr0 & 6s05d8 &$0.3744$ &$36.764$ &$0.8240$ &$14.576$ &$-8.8616$ &$2.303$ &$8.6664$ &$2.255$ &$-0.0035$ \\\\\nIr0 & 6s15d7 &$0.3604$ &$33.570$ &$0.8597$ &$13.993$ &$-2.1686$ &$2.412$ &$1.9518$ &$2.188$ &$-0.0036$ \\\\\nIr2 & 6s05d7 &$0.3802$ &$30.032$ &$0.8550$ &$13.567$ &$-1.6185$ &$2.488$ &$1.3866$ &$2.162$ &$-0.0035$ \\\\\nIr3 & 6s05d6 &$0.3678$ &$25.828$ &$0.9065$ &$12.788$ &$-0.8587$ &$2.745$ &$0.5883$ &$1.960$ &$-0.0040$ \\\\\nIr4 & 6s05d5 &$0.3969$ &$22.050$ &$0.9310$ &$11.768$ &$-0.7090$ &$3.017$ &$0.3857$ &$1.778$ &$-0.0047$ \\\\\n\\hline\n\\end{tabular}\n}\n\\end{table}\n\\section{{\\large$\\langle j_0\\rangle$ }Form factors for Rare earth ions}\n\\begin{table}[H]\n\\caption{$\\langle j_0\\rangle$ form factors for the 4f electrons of rare earth ions}\n\\label{re4fj0}\n{\\tablesize\n\\begin{tabular}{lrrrrrrr}\n\\hline\nIon&\n\\multicolumn{1}{c}{A}&\\multicolumn{1}{c}{a}&\n\\multicolumn{1}{c}{B}&\\multicolumn{1}{c}{b}&\n\\multicolumn{1}{c}{C}&\\multicolumn{1}{c}{c}&\\multicolumn{1}{c}{D}\\\\\n\\hline\\\\[-2ex]\nCe2 &$0.2953$ &$17.6846$ &$0.2923$ &$6.7329$ &$0.4313$ &$5.3827$ &$-0.0194$ \\\\\nNd2 &$0.1645$ &$25.0453$ &$0.2522$ &$11.9782$ &$0.6012$ &$4.9461$ &$-0.0180$ \\\\\nNd3 &$0.0540$ &$25.0293$ &$0.3101$ &$12.1020$ &$0.6575$ &$4.7223$ &$-0.0216$ \\\\\nSm2 &$0.0909$ &$25.2032$ &$0.3037$ &$11.8562$ &$0.6250$ &$4.2366$ &$-0.0200$ \\\\\nSm3 &$0.0288$ &$25.2068$ &$0.2973$ &$11.8311$ &$0.6954$ &$4.2117$ &$-0.0213$ \\\\\nEu2 &$0.0755$ &$25.2960$ &$0.3001$ &$11.5993$ &$0.6438$ &$4.0252$ &$-0.0196$ \\\\\nEu3 &$0.0204$ &$25.3078$ &$0.3010$ &$11.4744$ &$0.7005$ &$3.9420$ &$-0.0220$ \\\\\nGd2 &$0.0636$ &$25.3823$ &$0.3033$ &$11.2125$ &$0.6528$ &$3.7877$ &$-0.0199$ \\\\\nGd3 &$0.0186$ &$25.3867$ &$0.2895$ &$11.1421$ &$0.7135$ &$3.7520$ &$-0.0217$ \\\\\nTb2 &$0.0547$ &$25.5086$ &$0.3171$ &$10.5911$ &$0.6490$ &$3.5171$ &$-0.0212$ \\\\\nTb3 &$0.0177$ &$25.5095$ &$0.2921$ &$10.5769$ &$0.7133$ &$3.5122$ &$-0.0231$ \\\\\nDy2 &$0.1308$ &$18.3155$ &$0.3118$ &$7.6645$ &$0.5795$ &$3.1469$ &$-0.0226$ \\\\\nDy3 &$0.1157$ &$15.0732$ &$0.3270$ &$6.7991$ &$0.5821$ &$3.0202$ &$-0.0249$ \\\\\nHo2 &$0.0995$ &$18.1761$ &$0.3305$ &$7.8556$ &$0.5921$ &$2.9799$ &$-0.0230$ \\\\\nHo3 &$0.0566$ &$18.3176$ &$0.3365$ &$7.6880$ &$0.6317$ &$2.9427$ &$-0.0248$ \\\\\nEr2 &$0.1122$ &$18.1223$ &$0.3462$ &$6.9106$ &$0.5649$ &$2.7614$ &$-0.0235$ \\\\\nEr3 &$0.0586$ &$17.9802$ &$0.3540$ &$7.0964$ &$0.6126$ &$2.7482$ &$-0.0251$ \\\\\nTm2 &$0.0983$ &$18.3236$ &$0.3380$ &$6.9178$ &$0.5875$ &$2.6622$ &$-0.0241$ \\\\\nTm3 &$0.0581$ &$15.0922$ &$0.2787$ &$7.8015$ &$0.6854$ &$2.7931$ &$-0.0224$ \\\\\nYb2 &$0.0855$ &$18.5123$ &$0.2943$ &$7.3734$ &$0.6412$ &$2.6777$ &$-0.0213$ \\\\\nYb3 &$0.0416$ &$16.0949$ &$0.2849$ &$7.8341$ &$0.6961$ &$2.6725$ &$-0.0229$ \\\\\nPr3 &$0.0504$ &$24.9989$ &$0.2572$ &$12.0377$ &$0.7142$ &$5.0039$ &$-0.0219$ \\\\\n\\hline\\\\[-2ex]\n\\end{tabular}\n}\n\\vspace{2mm}\n\\end{table}\n\\begin{table}[H]\n \\caption{$\\langle j_0\\rangle$ form factors for the 5d electrons of rare earth ions.\\cite{kob:12}}\n \\vspace{1ex}\n \\label{re5dj0}\n{\\tablesize\n\\begin{tabular}{llrrrrrrrrr}\n\\hline\n\\multicolumn{1}{c}{ Ion}&\\multicolumn{1}{c}{ Config}&\\multicolumn{1}{c}{ A }&\\multicolumn{1}{c}{  a }&\\multicolumn{1}{c}{B }&\\multicolumn{1}{c}{ b }&\\multicolumn{1}{c}{ C }&\\multicolumn{1}{c}{ c }&\\multicolumn{1}{c}{ D }&\\multicolumn{1}{c}{ d }&\\multicolumn{1}{c}{E}\\\\\n\\hline\nLa2 & 4f05d1 &$0.5488$ &$63.822$ &$0.7238$ &$34.429$ &$-6.0375$ &$7.092$ &$5.7655$ &$6.839$ &$-0.0008$ \\\\\nCe2 & 4f15d1 &$0.4959$ &$63.797$ &$0.7571$ &$34.334$ &$-5.9903$ &$6.595$ &$5.7381$ &$6.370$ &$-0.0009$ \\\\\nCe3 & 4f05d1 &$1.2395$ &$35.447$ &$-1.6420$ &$4.939$ &$1.9467$ &$3.715$ &$-0.5481$ &$2.671$ &$0.0020$ \\\\\nPr2 & 4f25d1 &$0.4568$ &$63.765$ &$0.7795$ &$34.094$ &$-5.1096$ &$6.186$ &$4.8743$ &$5.950$ &$-0.0011$ \\\\\nPr3 & 4f15d1 &$0.7735$ &$40.670$ &$0.6284$ &$21.775$ &$-7.2962$ &$6.114$ &$6.8955$ &$5.866$ &$-0.0015$ \\\\\nPr4 & 4f05d1 &$1.3076$ &$27.762$ &$-3.2363$ &$4.278$ &$4.3424$ &$3.471$ &$-1.4168$ &$2.758$ &$0.0018$ \\\\\nNd2 & 4f35d1 &$1.2972$ &$27.071$ &$-2.4336$ &$4.208$ &$3.2415$ &$3.271$ &$-1.1081$ &$2.568$ &$0.0016$ \\\\\nNd3 & 4f25d1 &$0.6179$ &$41.924$ &$0.7344$ &$23.743$ &$-5.2140$ &$5.726$ &$4.8631$ &$5.427$ &$-0.0016$ \\\\\nNd4 & 4f15d1 &$1.2972$ &$27.071$ &$-2.4336$ &$4.208$ &$3.2415$ &$3.271$ &$-1.1081$ &$2.568$ &$0.0016$ \\\\\nPm3 & 4f35d1 &$0.5149$ &$42.825$ &$0.8077$ &$24.559$ &$-3.6851$ &$5.432$ &$3.3642$ &$5.053$ &$-0.0018$ \\\\\nSm2 & 4f55d1 &$0.3908$ &$63.383$ &$0.8062$ &$32.974$ &$-5.5271$ &$5.174$ &$5.3313$ &$5.015$ &$-0.0013$ \\\\\nSm3 & 4f45d1 &$0.4725$ &$42.826$ &$0.8301$ &$24.562$ &$-3.0608$ &$5.170$ &$2.7600$ &$4.755$ &$-0.0019$ \\\\\nEu2 & 4f65d1 &$0.3827$ &$63.023$ &$0.8044$ &$32.481$ &$-1.8540$ &$5.066$ &$1.6682$ &$4.618$ &$-0.0014$ \\\\\nEu3 & 4f55d1 &$0.3784$ &$44.430$ &$0.9025$ &$25.126$ &$-3.1521$ &$4.871$ &$2.8731$ &$4.511$ &$-0.0020$ \\\\\nGd0 & 4f85d1 &$0.4982$ &$104.440$ &$0.5928$ &$44.451$ &$-14.5061$ &$4.692$ &$14.4155$ &$4.664$ &$-0.0008$ \\\\\nGd0 & 6s14f75d1 &$0.4132$ &$75.211$ &$0.7389$ &$33.606$ &$-1.8951$ &$4.755$ &$1.7441$ &$4.411$ &$-0.0013$ \\\\\nGd2 & 4f75d1 &$0.3745$ &$62.755$ &$0.8026$ &$32.071$ &$-8.6327$ &$4.644$ &$8.4569$ &$4.560$ &$-0.0014$ \\\\\nGd3 & 4f65d1 &$0.3587$ &$44.300$ &$0.9082$ &$24.875$ &$-2.6769$ &$4.664$ &$2.4120$ &$4.274$ &$-0.0020$ \\\\\nGd4 & 4f55d1 &$0.4512$ &$32.712$ &$0.9183$ &$19.602$ &$-2.8665$ &$4.569$ &$2.4997$ &$4.098$ &$-0.0027$ \\\\\nTb0 & 4f95d1 &$0.5057$ &$104.335$ &$0.5796$ &$43.869$ &$-1.6061$ &$4.572$ &$1.5212$ &$4.339$ &$-0.0008$ \\\\\nTb0 & 6s14f95d1 &$0.4131$ &$74.925$ &$0.7311$ &$33.131$ &$-1.2648$ &$4.612$ &$1.1216$ &$4.133$ &$-0.0013$ \\\\\nTb2 & 4f85d1 &$0.3734$ &$62.276$ &$0.7955$ &$31.562$ &$-3.4780$ &$4.492$ &$3.3105$ &$4.298$ &$-0.0014$ \\\\\nTb3 & 4f75d1 &$0.3223$ &$44.892$ &$0.9303$ &$24.826$ &$-3.9948$ &$4.375$ &$3.7443$ &$4.140$ &$-0.0021$ \\\\\nTb4 & 4f65d1 &$0.3614$ &$33.730$ &$0.9844$ &$19.945$ &$-2.6536$ &$4.355$ &$2.3105$ &$3.892$ &$-0.0028$ \\\\\nDy2 & 4f95d1 &$0.3754$ &$61.715$ &$0.7859$ &$31.049$ &$-1.7452$ &$4.388$ &$1.5853$ &$4.024$ &$-0.0014$ \\\\\nDy3 & 4f85d1 &$0.3014$ &$45.110$ &$0.9392$ &$24.622$ &$-3.2549$ &$4.203$ &$3.0163$ &$3.936$ &$-0.0021$ \\\\\nHo3 & 4f95d1 &$0.2974$ &$44.755$ &$0.9335$ &$24.262$ &$-2.3286$ &$4.079$ &$2.0998$ &$3.728$ &$-0.0021$ \\\\\nEr3 & 4f105d1 &$0.2916$ &$44.550$ &$0.9304$ &$23.933$ &$-1.3854$ &$4.035$ &$1.1655$ &$3.468$ &$-0.0021$ \\\\\nTm2 & 4f125d1 &$0.4067$ &$59.305$ &$0.7386$ &$29.168$ &$-0.3795$ &$4.593$ &$0.2356$ &$2.956$ &$-0.0015$ \\\\\nTm3 & 4f115d1 &$0.3302$ &$42.750$ &$0.8905$ &$23.057$ &$-0.5894$ &$4.397$ &$0.3708$ &$2.923$ &$-0.0022$ \\\\\nTm4 & 4f105d1 &$0.2406$ &$35.005$ &$1.0453$ &$19.560$ &$-4.5727$ &$3.572$ &$4.2895$ &$3.383$ &$-0.0027$ \\\\\nYb2 & 4f135d1 &$0.4170$ &$58.627$ &$0.7233$ &$28.615$ &$-0.3308$ &$4.553$ &$0.1919$ &$2.742$ &$-0.0015$ \\\\\nYb3 & 4f125d1 &$0.3498$ &$41.749$ &$0.8666$ &$22.455$ &$-0.4923$ &$4.434$ &$0.2780$ &$2.671$ &$-0.0022$ \\\\\nLu2 & 4f145d1 &$0.4216$ &$58.262$ &$0.7131$ &$28.218$ &$-0.3048$ &$4.446$ &$0.1715$ &$2.593$ &$-0.0015$ \\\\\nLu3 & 4f135d1 &$0.3217$ &$42.404$ &$0.8845$ &$22.448$ &$-0.4726$ &$4.258$ &$0.2686$ &$2.566$ &$-0.0022$ \\\\\n\\hline\n\\end{tabular}\n}\n\\end{table}\n\\section{{\\large$\\langle j_0\\rangle$ }Form factors for Actinide ions}\n\\begin{table}[H]\n\\caption{$\\langle j_0\\rangle$ Form factors for 5f electrons of actinide ions}\\vspace{2mm}\n\\label{acj0}\n{\\tablesize\n\\begin{tabular}{lrrrrrrr}\n\\hline\nIon&\n\\multicolumn{1}{c}{A}&\\multicolumn{1}{c}{a}&\n\\multicolumn{1}{c}{B}&\\multicolumn{1}{c}{b}&\n\\multicolumn{1}{c}{C}&\\multicolumn{1}{c}{c}&\\multicolumn{1}{c}{D}\\\\\n\\hline\\\\[-2ex]\nU3 &$0.5058$ &$23.2882$ &$1.3464$ &$7.0028$ &$-0.8724$ &$4.8683$ &$0.0192$ \\\\\nU4 &$0.3291$ &$23.5475$ &$1.0836$ &$8.4540$ &$-0.4340$ &$4.1196$ &$0.0214$ \\\\\nU5 &$0.3650$ &$19.8038$ &$3.2199$ &$6.2818$ &$-2.6077$ &$5.3010$ &$0.0233$ \\\\\nNp3 &$0.5157$ &$20.8654$ &$2.2784$ &$5.8930$ &$-1.8163$ &$4.8457$ &$0.0211$ \\\\\nNp4 &$0.4206$ &$19.8046$ &$2.8004$ &$5.9783$ &$-2.2436$ &$4.9848$ &$0.0228$ \\\\\nNp5 &$0.3692$ &$18.1900$ &$3.1510$ &$5.8500$ &$-2.5446$ &$4.9164$ &$0.0248$ \\\\\nNp6 &$0.2929$ &$17.5611$ &$3.4866$ &$5.7847$ &$-2.8066$ &$4.8707$ &$0.0267$ \\\\\nPu3 &$0.3840$ &$16.6793$ &$3.1049$ &$5.4210$ &$-2.5148$ &$4.5512$ &$0.0263$ \\\\\nPu4 &$0.4934$ &$16.8355$ &$1.6394$ &$5.6384$ &$-1.1581$ &$4.1399$ &$0.0248$ \\\\\nPu5 &$0.3888$ &$16.5592$ &$2.0362$ &$5.6567$ &$-1.4515$ &$4.2552$ &$0.0267$ \\\\\nPu6 &$0.3172$ &$16.0507$ &$3.4654$ &$5.3507$ &$-2.8102$ &$4.5133$ &$0.0281$ \\\\\nAm2 &$0.4743$ &$21.7761$ &$1.5800$ &$5.6902$ &$-1.0779$ &$4.1451$ &$0.0218$ \\\\\nAm3 &$0.4239$ &$19.5739$ &$1.4573$ &$5.8722$ &$-0.9052$ &$3.9682$ &$0.0238$ \\\\\nAm4 &$0.3737$ &$17.8625$ &$1.3521$ &$6.0426$ &$-0.7514$ &$3.7199$ &$0.0258$ \\\\\nAm5 &$0.2956$ &$17.3725$ &$1.4525$ &$6.0734$ &$-0.7755$ &$3.6619$ &$0.0277$ \\\\\nAm6 &$0.2302$ &$16.9533$ &$1.4864$ &$6.1159$ &$-0.7457$ &$3.5426$ &$0.0294$ \\\\\nAm7 &$0.3601$ &$12.7299$ &$1.9640$ &$5.1203$ &$-1.3560$ &$3.7142$ &$0.0316$ \\\\\n\\hline\\\\[-2ex]\n\\end{tabular}\n}\n\\end{table}\n\\section{{\\large $\\langle j_2\\rangle$} Form factors for 3d transition elements and their ions}\n\\label{3dj2}\n\\begin{table}[H]\n\\caption{\n$\\langle j_2\\rangle$ form factors for 3d transition elements and their ions}\n \\vspace{2mm}\n{\\tablesize\n\\begin{tabular}{lrrrrrrr}\n\\hline\nIon&\n\\multicolumn{1}{c}{A}&\\multicolumn{1}{c}{a}&\n\\multicolumn{1}{c}{B}&\\multicolumn{1}{c}{b}&\n\\multicolumn{1}{c}{C}&\\multicolumn{1}{c}{c}&\\multicolumn{1}{c}{D}\\\\\n\\hline\\\\[-2ex]\nSc0 &$10.8172$ &$54.3270$ &$4.7353$ &$14.8471$ &$0.6071$ &$4.2180$ &$0.0011$ \\\\\nSc1 &$8.5021$ &$34.2851$ &$3.2116$ &$10.9940$ &$0.4244$ &$3.6055$ &$0.0009$ \\\\\nSc2 &$4.3683$ &$28.6544$ &$3.7231$ &$10.8233$ &$0.6074$ &$3.6678$ &$0.0014$ \\\\\nTi0 &$4.3583$ &$36.0556$ &$3.8230$ &$11.1328$ &$0.6855$ &$3.4692$ &$0.0020$ \\\\\nTi1 &$6.1567$ &$27.2754$ &$2.6833$ &$8.9827$ &$0.4070$ &$3.0524$ &$0.0011$ \\\\\nTi2 &$4.3107$ &$18.3484$ &$2.0960$ &$6.7970$ &$0.2984$ &$2.5476$ &$0.0007$ \\\\\nTi3 &$3.3717$ &$14.4441$ &$1.8258$ &$5.7126$ &$0.2470$ &$2.2654$ &$0.0005$ \\\\\nV0 &$3.8099$ &$21.8313$ &$2.4026$ &$7.5458$ &$0.4464$ &$2.6628$ &$0.0017$ \\\\\nV1 &$4.7474$ &$23.3226$ &$2.3609$ &$7.8082$ &$0.4105$ &$2.7063$ &$0.0014$ \\\\\nV2 &$3.4386$ &$16.5303$ &$1.9638$ &$6.1415$ &$0.2997$ &$2.2669$ &$0.0009$ \\\\\nV3 &$2.3005$ &$14.6821$ &$2.0364$ &$6.1304$ &$0.4099$ &$2.3815$ &$0.0014$ \\\\\nV4 &$1.8377$ &$12.2668$ &$1.8247$ &$5.4578$ &$0.3979$ &$2.2483$ &$0.0012$ \\\\\nCr0 &$3.7600$ &$20.1267$ &$2.1006$ &$6.8020$ &$0.4266$ &$2.3941$ &$0.0019$ \\\\\nCr1 &$3.7768$ &$20.3456$ &$2.1028$ &$6.8926$ &$0.4010$ &$2.4114$ &$0.0017$ \\\\\nCr2 &$2.6422$ &$16.0598$ &$1.9198$ &$6.2531$ &$0.4446$ &$2.3715$ &$0.0020$ \\\\\nCr3 &$1.6262$ &$15.0656$ &$2.0618$ &$6.2842$ &$0.5281$ &$2.3680$ &$0.0023$ \\\\\nCr4 &$1.0293$ &$13.9498$ &$1.9933$ &$6.0593$ &$0.5974$ &$2.3457$ &$0.0027$ \\\\\nMn0 &$2.6681$ &$16.0601$ &$1.7561$ &$5.6396$ &$0.3675$ &$2.0488$ &$0.0017$ \\\\\nMn1 &$3.2953$ &$18.6950$ &$1.8792$ &$6.2403$ &$0.3927$ &$2.2006$ &$0.0022$ \\\\\nMn2 &$2.0515$ &$15.5561$ &$1.8841$ &$6.0625$ &$0.4787$ &$2.2323$ &$0.0027$ \\\\\nMn3 &$1.2427$ &$14.9966$ &$1.9567$ &$6.1181$ &$0.5732$ &$2.2577$ &$0.0031$ \\\\\nMn4 &$0.7879$ &$13.8857$ &$1.8717$ &$5.7433$ &$0.5981$ &$2.1818$ &$0.0034$ \\\\\nFe0 &$1.9405$ &$18.4733$ &$1.9566$ &$6.3234$ &$0.5166$ &$2.1607$ &$0.0036$ \\\\\nFe1 &$2.6290$ &$18.6598$ &$1.8704$ &$6.3313$ &$0.4690$ &$2.1628$ &$0.0031$ \\\\\nFe2 &$1.6490$ &$16.5593$ &$1.9064$ &$6.1325$ &$0.5206$ &$2.1370$ &$0.0035$ \\\\\nFe3 &$1.3602$ &$11.9976$ &$1.5188$ &$5.0025$ &$0.4705$ &$1.9914$ &$0.0038$ \\\\\nFe4 &$1.5582$ &$8.2750$ &$1.1863$ &$3.2794$ &$0.1366$ &$1.1068$ &$-0.0022$ \\\\\nCo0 &$1.9678$ &$14.1699$ &$1.4911$ &$4.9475$ &$0.3844$ &$1.7973$ &$0.0027$ \\\\\nCo1 &$2.4097$ &$16.1608$ &$1.5780$ &$5.4604$ &$0.4095$ &$1.9141$ &$0.0031$ \\\\\nCo2 &$1.9049$ &$11.6444$ &$1.3159$ &$4.3574$ &$0.3146$ &$1.6453$ &$0.0017$ \\\\\nCo3 &$1.7058$ &$8.8595$ &$1.1409$ &$3.3086$ &$0.1474$ &$1.0899$ &$-0.0025$ \\\\\nCo4 &$1.3110$ &$8.0252$ &$1.1551$ &$3.1792$ &$0.1608$ &$1.1301$ &$-0.0011$ \\\\\nNi0 &$1.0302$ &$12.2521$ &$1.4669$ &$4.7453$ &$0.4521$ &$1.7437$ &$0.0036$ \\\\\nNi1 &$2.1040$ &$14.8655$ &$1.4302$ &$5.0714$ &$0.4031$ &$1.7784$ &$0.0034$ \\\\\nNi2 &$1.7080$ &$11.0160$ &$1.2147$ &$4.1031$ &$0.3150$ &$1.5334$ &$0.0018$ \\\\\nNi3 &$1.4683$ &$8.6713$ &$1.1068$ &$3.2574$ &$0.1794$ &$1.1058$ &$-0.0023$ \\\\\nNi4 &$1.1612$ &$7.7000$ &$1.0027$ &$3.2628$ &$0.2719$ &$1.3780$ &$0.0025$ \\\\\nCu0 &$1.9182$ &$14.4904$ &$1.3329$ &$4.7301$ &$0.3842$ &$1.6394$ &$0.0035$ \\\\\nCu1 &$1.8814$ &$13.4333$ &$1.2809$ &$4.5446$ &$0.3646$ &$1.6022$ &$0.0033$ \\\\\nCu2 &$1.5189$ &$10.4779$ &$1.1512$ &$3.8132$ &$0.2918$ &$1.3979$ &$0.0017$ \\\\\nCu3 &$1.2797$ &$8.4502$ &$1.0315$ &$3.2796$ &$0.2401$ &$1.2498$ &$0.0015$ \\\\\nCu4 &$0.9568$ &$7.4481$ &$0.9099$ &$3.3964$ &$0.3729$ &$1.4936$ &$0.0049$ \\\\\n\\hline\\\\[-2ex]\n\\end{tabular}\n}\n\\end{table}\n\\section{{\\large $\\langle j_2\\rangle$} Form factors for 4d transition elements}\n\\begin{table}[H]\n\\caption{$\\langle j_2\\rangle$ form factors for 4d atoms and ions}\\vspace{2mm}\n\\label{4dj2}\n{\\tablesize\n\\begin{tabular}{lrrrrrrr}\n\\hline\nIon&\n\\multicolumn{1}{c}{A}&\\multicolumn{1}{c}{a}&\n\\multicolumn{1}{c}{B}&\\multicolumn{1}{c}{b}&\n\\multicolumn{1}{c}{C}&\\multicolumn{1}{c}{c}&\\multicolumn{1}{c}{D}\\\\\n\\hline\\\\[-2ex]\nY0 &$14.4084$ &$44.6577$ &$5.1045$ &$14.9043$ &$-0.0535$ &$3.3189$ &$0.0028$ \\\\\nZr0 &$10.1378$ &$35.3372$ &$4.7734$ &$12.5453$ &$-0.0489$ &$2.6721$ &$0.0036$ \\\\\nZr1 &$11.8722$ &$34.9200$ &$4.0502$ &$12.1266$ &$-0.0632$ &$2.8278$ &$0.0034$ \\\\\nNb0 &$7.4796$ &$33.1789$ &$5.0884$ &$11.5708$ &$-0.0281$ &$1.5635$ &$0.0047$ \\\\\nNb1 &$8.7735$ &$33.2848$ &$4.6556$ &$11.6046$ &$-0.0268$ &$1.5389$ &$0.0044$ \\\\\nMo0 &$5.1180$ &$23.4217$ &$4.1809$ &$9.2080$ &$-0.0505$ &$1.7434$ &$0.0053$ \\\\\nMo1 &$7.2367$ &$28.1282$ &$4.0705$ &$9.9228$ &$-0.0317$ &$1.4552$ &$0.0049$ \\\\\nTc0 &$4.2441$ &$21.3974$ &$3.9439$ &$8.3753$ &$-0.0371$ &$1.1870$ &$0.0066$ \\\\\nTc1 &$6.4056$ &$24.8243$ &$3.5400$ &$8.6112$ &$-0.0366$ &$1.4846$ &$0.0044$ \\\\\nRu0 &$3.7445$ &$18.6128$ &$3.4749$ &$7.4201$ &$-0.0363$ &$1.0068$ &$0.0073$ \\\\\nRu1 &$5.2826$ &$23.6832$ &$3.5813$ &$8.1521$ &$-0.0257$ &$0.4255$ &$0.0131$ \\\\\nRh0 &$3.3651$ &$17.3444$ &$3.2121$ &$6.8041$ &$-0.0350$ &$0.5031$ &$0.0146$ \\\\\nRh1 &$4.0260$ &$18.9497$ &$3.1663$ &$6.9998$ &$-0.0296$ &$0.4862$ &$0.0127$ \\\\\nPd0 &$3.3105$ &$14.7265$ &$2.6332$ &$5.8618$ &$-0.0437$ &$1.1303$ &$0.0053$ \\\\\nPd1 &$4.2749$ &$17.9002$ &$2.7021$ &$6.3541$ &$-0.0258$ &$0.6999$ &$0.0071$ \\\\\n\\hline\\\\[-2ex]\n\\end{tabular}\n}\n\\end{table}\n\\section{{\\large $\\langle j_2\\rangle$} Form factors for 5d Transition elements}\n\\begin{table}[H]\n \\caption{$\\langle j_2\\rangle$ form factors for the 5d electrons of transition atoms and ions from Hf to Re.\\cite{kob:11}}\n \\label{5dj2}\n \\vspace{1ex}\n {\\tablesize\n\\begin{tabular}{llrrrrrrrrr}\n\\hline\n\\multicolumn{1}{c}{ Ion}&\\multicolumn{1}{c}{ Config}&\\multicolumn{1}{c}{ A }&\\multicolumn{1}{c}{  a }&\\multicolumn{1}{c}{B }&\\multicolumn{1}{c}{ b }&\\multicolumn{1}{c}{ C }&\\multicolumn{1}{c}{ c }&\\multicolumn{1}{c}{ D }&\\multicolumn{1}{c}{ d }&\\multicolumn{1}{c}{E}\\\\\n\\hline\nHf2 & 6s05d2 &$9.6670$ &$33.435$ &$5.2429$ &$13.529$ &$-0.5533$ &$1.402$ &$0.4934$ &$1.254$ &$-0.0033$ \\\\\nHf3 & 6s05d1 &$7.5646$ &$27.367$ &$5.0743$ &$12.402$ &$-0.4133$ &$1.742$ &$0.3163$ &$1.437$ &$-0.0012$ \\\\\nTa2 & 6s05d3 &$8.1746$ &$29.871$ &$4.9405$ &$12.188$ &$-1.1294$ &$1.254$ &$1.0658$ &$1.181$ &$-0.0046$ \\\\\nTa3 & 6s05d2 &$6.5998$ &$25.026$ &$4.7913$ &$11.303$ &$-0.7801$ &$1.529$ &$0.6820$ &$1.382$ &$-0.0019$ \\\\\nTa4 & 6s05d1 &$5.5048$ &$21.620$ &$4.6734$ &$10.556$ &$-0.2181$ &$2.100$ &$0.0810$ &$1.049$ &$-0.0016$ \\\\\nW0 & 6s05d6 &$8.4216$ &$64.652$ &$7.6983$ &$23.124$ &$2.3605$ &$8.583$ &$-0.3876$ &$4.620$ &$0.0033$ \\\\\nW0 & 6s15d5 &$6.9289$ &$53.425$ &$7.2157$ &$20.016$ &$5.7754$ &$6.543$ &$-4.2114$ &$5.854$ &$0.0036$ \\\\\nW0 & 6s25d4 &$5.4017$ &$47.110$ &$6.9113$ &$18.760$ &$7.0586$ &$6.363$ &$-5.4525$ &$5.802$ &$0.0040$ \\\\\nW0 & 6s05d5 &$5.6854$ &$44.743$ &$6.8903$ &$18.753$ &$7.8523$ &$6.308$ &$-6.3447$ &$5.842$ &$0.0038$ \\\\\nW0 & 6s15d4 &$4.5118$ &$41.281$ &$6.7136$ &$17.964$ &$7.6331$ &$6.269$ &$-6.0365$ &$5.758$ &$0.0042$ \\\\\nW2 & 6s05d4 &$7.0301$ &$26.990$ &$4.6604$ &$11.083$ &$-0.8220$ &$1.145$ &$0.7581$ &$1.042$ &$-0.0068$ \\\\\nW3 & 6s05d3 &$5.8036$ &$22.969$ &$4.5243$ &$10.361$ &$-0.7897$ &$1.388$ &$0.6927$ &$1.248$ &$-0.0031$ \\\\\nW4 & 6s05d2 &$4.9006$ &$20.117$ &$4.4360$ &$9.765$ &$-2.0009$ &$1.497$ &$1.8714$ &$1.431$ &$-0.0014$ \\\\\nW5 & 6s05d1 &$4.1973$ &$17.967$ &$4.3791$ &$9.255$ &$-1.8830$ &$1.603$ &$1.7205$ &$1.518$ &$-0.0004$ \\\\\nRe0 & 6s05d7 &$6.7574$ &$55.529$ &$6.7931$ &$20.125$ &$2.3113$ &$7.529$ &$-0.5004$ &$4.412$ &$0.0037$ \\\\\nRe0 & 6s15d6 &$5.5830$ &$46.852$ &$6.4516$ &$17.855$ &$5.0609$ &$6.037$ &$-3.5427$ &$5.312$ &$0.0040$ \\\\\nRe0 & 6s25d5 &$4.4322$ &$41.798$ &$6.2063$ &$16.844$ &$9.8763$ &$5.751$ &$-8.3294$ &$5.406$ &$0.0043$ \\\\\nRe0 & 6s05d6 &$4.7231$ &$40.130$ &$6.2139$ &$16.902$ &$8.8240$ &$5.766$ &$-7.3608$ &$5.396$ &$0.0042$ \\\\\nRe0 & 6s15d5 &$3.7875$ &$37.254$ &$6.0587$ &$16.264$ &$6.9896$ &$5.786$ &$-5.4457$ &$5.279$ &$0.0045$ \\\\\nRe2 & 6s05d5 &$3.0708$ &$33.896$ &$5.9941$ &$15.817$ &$6.7816$ &$5.768$ &$-5.2056$ &$5.231$ &$0.0047$ \\\\\nRe3 & 6s05d4 &$1.7870$ &$31.248$ &$5.9068$ &$15.160$ &$17.4262$ &$5.551$ &$-15.6856$ &$5.339$ &$0.0053$ \\\\\nRe4 & 6s05d3 &$4.4033$ &$18.733$ &$4.1971$ &$9.047$ &$-2.3106$ &$1.352$ &$2.1866$ &$1.299$ &$-0.0025$ \\\\\nRe5 & 6s05d2 &$3.8162$ &$16.843$ &$4.1400$ &$8.605$ &$-4.0882$ &$1.443$ &$3.9333$ &$1.408$ &$-0.0012$ \\\\\nRe6 & 6s05d1 &$3.3349$ &$15.341$ &$4.1015$ &$8.213$ &$-2.3511$ &$1.531$ &$2.1651$ &$1.459$ &$-0.0003$ \\\\\n\\hline\n\\end{tabular}\n}\n\\end{table}\n\\begin{table}[H]\n \\caption{$\\langle j_\\rangle$ form factors for the 5d electrons of transition atoms and ions from Os to Au.\\cite{kob:11}}\n\\label{5dj2b} \\vspace{1ex}\n{\\tablesize\n\\begin{tabular}{llrrrrrrrrr}\n\\hline\n\\multicolumn{1}{c}{ Ion}&\\multicolumn{1}{c}{ Config}&\\multicolumn{1}{c}{ A }&\\multicolumn{1}{c}{  a }&\\multicolumn{1}{c}{B }&\\multicolumn{1}{c}{ b }&\\multicolumn{1}{c}{ C }&\\multicolumn{1}{c}{ c }&\\multicolumn{1}{c}{ D }&\\multicolumn{1}{c}{ d }&\\multicolumn{1}{c}{E }\\\\\n\\hline\nOs0 & 6s05d8 &$5.5418$ &$48.893$ &$6.0803$ &$17.984$ &$2.2542$ &$6.853$ &$-0.5285$ &$4.095$ &$0.0040$ \\\\\nOs0 & 6s15d7 &$4.6511$ &$41.610$ &$5.8194$ &$16.062$ &$6.7172$ &$5.447$ &$-5.2689$ &$4.986$ &$0.0043$ \\\\\nOs0 & 6s25d6 &$3.7421$ &$37.491$ &$5.6137$ &$15.256$ &$10.0488$ &$5.293$ &$-8.5683$ &$4.991$ &$0.0046$ \\\\\nOs0 & 6s05d7 &$4.0236$ &$36.272$ &$5.6349$ &$15.338$ &$8.6568$ &$5.318$ &$-7.2505$ &$4.980$ &$0.0044$ \\\\\nOs0 & 6s15d6 &$3.2611$ &$33.818$ &$5.4945$ &$14.808$ &$5.7610$ &$5.391$ &$-4.2811$ &$4.827$ &$0.0048$ \\\\\nOs2 & 6s05d6 &$2.7289$ &$30.900$ &$5.4357$ &$14.396$ &$18.6546$ &$5.151$ &$-17.1708$ &$4.993$ &$0.0050$ \\\\\nOs3 & 6s05d5 &$4.5913$ &$19.692$ &$4.0615$ &$8.862$ &$-0.9950$ &$1.086$ &$0.9081$ &$0.986$ &$-0.0077$ \\\\\nOs4 & 6s05d4 &$3.9724$ &$17.514$ &$3.9817$ &$8.421$ &$-0.7719$ &$1.264$ &$0.6552$ &$1.107$ &$-0.0042$ \\\\\nOs5 & 6s05d3 &$3.4764$ &$15.826$ &$3.9241$ &$8.032$ &$-0.6854$ &$1.397$ &$0.5394$ &$1.184$ &$-0.0024$ \\\\\nOs6 & 6s05d2 &$3.0642$ &$14.479$ &$3.8847$ &$7.686$ &$-4.7235$ &$1.384$ &$4.5485$ &$1.352$ &$-0.0012$ \\\\\nOs7 & 6s05d1 &$2.7164$ &$13.366$ &$3.8554$ &$7.370$ &$-5.0211$ &$1.439$ &$4.8166$ &$1.405$ &$-0.0004$ \\\\\nIr0 & 6s05d9 &$4.6102$ &$43.878$ &$5.4892$ &$16.394$ &$2.1707$ &$6.423$ &$-0.4761$ &$3.722$ &$0.0043$ \\\\\nIr0 & 6s15d8 &$3.9372$ &$37.508$ &$5.2846$ &$14.661$ &$3.7267$ &$5.263$ &$-2.3158$ &$4.416$ &$0.0045$ \\\\\nIr0 & 6s25d7 &$3.2263$ &$33.922$ &$5.1086$ &$13.921$ &$6.5993$ &$4.978$ &$-5.1841$ &$4.549$ &$0.0048$ \\\\\nIr0 & 6s05d8 &$3.4956$ &$32.991$ &$5.1369$ &$13.998$ &$8.3991$ &$4.924$ &$-7.0561$ &$4.612$ &$0.0047$ \\\\\nIr0 & 6s15d7 &$2.8732$ &$30.809$ &$5.0094$ &$13.522$ &$6.8656$ &$4.933$ &$-5.4669$ &$4.526$ &$0.0050$ \\\\\nIr2 & 6s05d7 &$2.4419$ &$28.356$ &$4.9470$ &$13.222$ &$4.7478$ &$5.029$ &$-3.3259$ &$4.393$ &$0.0052$ \\\\\nIr3 & 6s05d6 &$1.5883$ &$25.969$ &$4.8472$ &$12.711$ &$5.6507$ &$4.949$ &$-4.1190$ &$4.388$ &$0.0056$ \\\\\nIr4 & 6s05d5 &$3.5964$ &$16.439$ &$3.7872$ &$7.873$ &$-1.2303$ &$1.092$ &$1.1232$ &$1.003$ &$-0.0068$ \\\\\n\\hline\n\\end{tabular}\n}\n\\end{table}\n\\section{{\\large $\\langle j_2\\rangle$} Form factors for 4f electrons of rare earth ions}\n\\begin{table}[H]\n\\caption{$\\langle j_2\\rangle$ form factors for 4f electrons of rare-earth ions}\n\\vspace{2mm}\n\\label{re4fj2}\n{\\tablesize \n\\begin{tabular}{lrrrrrrr}\n\\hline\nIon&\n\\multicolumn{1}{c}{A}&\\multicolumn{1}{c}{a}&\n\\multicolumn{1}{c}{B}&\\multicolumn{1}{c}{b}&\n\\multicolumn{1}{c}{C}&\\multicolumn{1}{c}{c}&\\multicolumn{1}{c}{D}\\\\\n\\hline\\\\[-2ex]\nCe2 &$0.9809$ &$18.0630$ &$1.8413$ &$7.7688$ &$0.9905$ &$2.8452$ &$0.0120$ \\\\\nNd2 &$1.4530$ &$18.3398$ &$1.6196$ &$7.2854$ &$0.8752$ &$2.6224$ &$0.0126$ \\\\\nNd3 &$0.6751$ &$18.3421$ &$1.6272$ &$7.2600$ &$0.9644$ &$2.6016$ &$0.0150$ \\\\\nSm2 &$1.0360$ &$18.4249$ &$1.4769$ &$7.0321$ &$0.8810$ &$2.4367$ &$0.0152$ \\\\\nSm3 &$0.4707$ &$18.4301$ &$1.4261$ &$7.0336$ &$0.9574$ &$2.4387$ &$0.0182$ \\\\\nEu2 &$0.8970$ &$18.4429$ &$1.3769$ &$7.0054$ &$0.9060$ &$2.4213$ &$0.0190$ \\\\\nEu3 &$0.3985$ &$18.4514$ &$1.3307$ &$6.9556$ &$0.9603$ &$2.3780$ &$0.0197$ \\\\\nGd2 &$0.7756$ &$18.4695$ &$1.3124$ &$6.8990$ &$0.8956$ &$2.3383$ &$0.0199$ \\\\\nGd3 &$0.3347$ &$18.4758$ &$1.2465$ &$6.8767$ &$0.9537$ &$2.3184$ &$0.0217$ \\\\\nTb2 &$0.6688$ &$18.4909$ &$1.2487$ &$6.8219$ &$0.8888$ &$2.2751$ &$0.0215$ \\\\\nTb3 &$0.2892$ &$18.4973$ &$1.1678$ &$6.7972$ &$0.9437$ &$2.2573$ &$0.0232$ \\\\\nDy2 &$0.5917$ &$18.5114$ &$1.1828$ &$6.7465$ &$0.8801$ &$2.2141$ &$0.0229$ \\\\\nDy3 &$0.2523$ &$18.5172$ &$1.0914$ &$6.7362$ &$0.9345$ &$2.2082$ &$0.0250$ \\\\\nHo2 &$0.5094$ &$18.5155$ &$1.1234$ &$6.7060$ &$0.8727$ &$2.1589$ &$0.0242$ \\\\\nHo3 &$0.2188$ &$18.5157$ &$1.0240$ &$6.7070$ &$0.9251$ &$2.1614$ &$0.0268$ \\\\\nEr2 &$0.4693$ &$18.5278$ &$1.0545$ &$6.6493$ &$0.8679$ &$2.1201$ &$0.0261$ \\\\\nEr3 &$0.1710$ &$18.5337$ &$0.9879$ &$6.6246$ &$0.9044$ &$2.1004$ &$0.0278$ \\\\\nTm2 &$0.4198$ &$18.5417$ &$0.9959$ &$6.6002$ &$0.8593$ &$2.0818$ &$0.0284$ \\\\\nTm3 &$0.1760$ &$18.5417$ &$0.9105$ &$6.5787$ &$0.8970$ &$2.0622$ &$0.0294$ \\\\\nYb2 &$0.3852$ &$18.5497$ &$0.9415$ &$6.5507$ &$0.8492$ &$2.0425$ &$0.0301$ \\\\\nYb3 &$0.1570$ &$18.5553$ &$0.8484$ &$6.5403$ &$0.8880$ &$2.0367$ &$0.0318$ \\\\\nPr3 &$0.8734$ &$18.9876$ &$1.5594$ &$6.0872$ &$0.8142$ &$2.4150$ &$0.0111$ \\\\\n\\hline\\\\[-2ex]\n\\end{tabular}\n}\n\\end{table}\n%\n\\section{{\\large $\\langle j_2\\rangle$} Form factors for 5d electrons of rare earth elements}\n\\begin{table}[H]\n \\caption{$\\langle j_2\\rangle$ form factors of the 5d electrons of rare earth ions.\\cite{kob:12}}\n \\vspace{1ex}\n \\label{re5dj2}\n{\\tablesize\n\\begin{tabular}{llrrrrrrrrr}\n\\hline\n\\multicolumn{1}{c}{ Ion}&\\multicolumn{1}{c}{ Config}&\\multicolumn{1}{c}{ A }&\\multicolumn{1}{c}{  a }&\\multicolumn{1}{c}{B }&\\multicolumn{1}{c}{ b }&\\multicolumn{1}{c}{ C }&\\multicolumn{1}{c}{ c }&\\multicolumn{1}{c}{ D }&\\multicolumn{1}{c}{ d }&\\multicolumn{1}{c}{E}\\\\\n\\hline\nLa2 & 4f05d1 &$12.9681$ &$48.694$ &$9.8018$ &$22.831$ &$-0.5443$ &$4.354$ &$0.2584$ &$2.743$ &$-0.0001$ \\\\\nCe2 & 4f15d1 &$12.6550$ &$47.222$ &$9.3025$ &$21.878$ &$-0.6896$ &$3.762$ &$0.4405$ &$2.849$ &$0.0000$ \\\\\nCe3 & 4f05d1 &$8.7013$ &$35.824$ &$8.5894$ &$18.242$ &$-0.6110$ &$4.306$ &$0.2181$ &$2.336$ &$-0.0003$ \\\\\nPr2 & 4f25d1 &$12.4487$ &$45.891$ &$8.8239$ &$21.010$ &$-17.0630$ &$3.120$ &$16.8417$ &$3.095$ &$0.0001$ \\\\\nPr3 & 4f15d1 &$8.5203$ &$34.877$ &$8.2069$ &$17.602$ &$-0.5841$ &$3.958$ &$0.2347$ &$2.302$ &$-0.0002$ \\\\\nPr4 & 4f05d1 &$6.3910$ &$28.309$ &$7.6746$ &$15.204$ &$-0.6973$ &$4.010$ &$0.2304$ &$2.119$ &$-0.0004$ \\\\\nNd2 & 4f35d1 &$6.2640$ &$27.628$ &$7.3661$ &$14.731$ &$-0.6560$ &$3.743$ &$0.2354$ &$2.073$ &$-0.0003$ \\\\\nNd3 & 4f25d1 &$8.3541$ &$34.036$ &$7.8675$ &$17.031$ &$-0.5998$ &$3.584$ &$0.2896$ &$2.326$ &$0.0000$ \\\\\nNd4 & 4f15d1 &$6.2640$ &$27.628$ &$7.3661$ &$14.731$ &$-0.6560$ &$3.743$ &$0.2354$ &$2.073$ &$-0.0003$ \\\\\nPm3 & 4f35d1 &$8.2028$ &$33.286$ &$7.5637$ &$16.518$ &$-0.8756$ &$3.105$ &$0.6007$ &$2.486$ &$0.0002$ \\\\\nSm2 & 4f55d1 &$12.0956$ &$42.678$ &$7.6076$ &$18.857$ &$-1.4355$ &$2.749$ &$1.2720$ &$2.547$ &$0.0001$ \\\\\nSm3 & 4f45d1 &$8.1212$ &$32.502$ &$7.2340$ &$15.990$ &$-5.8639$ &$2.698$ &$5.6142$ &$2.630$ &$0.0003$ \\\\\nEu2 & 4f65d1 &$12.0033$ &$41.860$ &$7.2896$ &$18.289$ &$-1.4882$ &$2.592$ &$1.3411$ &$2.425$ &$0.0000$ \\\\\nEu3 & 4f55d1 &$8.0653$ &$31.753$ &$6.9151$ &$15.484$ &$-5.5701$ &$2.578$ &$5.3406$ &$2.515$ &$0.0003$ \\\\\nGd0 & 4f85d1 &$22.2510$ &$65.913$ &$7.5925$ &$23.045$ &$-3.5803$ &$1.952$ &$3.5355$ &$1.930$ &$-0.0010$ \\\\\nGd0 & 6s14f75d1 &$14.0295$ &$48.586$ &$7.3596$ &$18.927$ &$-5.1053$ &$2.242$ &$5.0055$ &$2.211$ &$-0.0004$ \\\\\nGd2 & 4f75d1 &$11.9202$ &$41.129$ &$7.0021$ &$17.772$ &$-5.3982$ &$2.392$ &$5.2663$ &$2.354$ &$-0.0001$ \\\\\nGd3 & 4f65d1 &$8.0082$ &$31.074$ &$6.6281$ &$15.022$ &$-1.9932$ &$2.515$ &$1.7825$ &$2.354$ &$0.0003$ \\\\\nGd4 & 4f55d1 &$5.8839$ &$25.328$ &$6.3297$ &$13.143$ &$-1.1650$ &$2.597$ &$0.8829$ &$2.219$ &$0.0004$ \\\\\nTb0 & 4f95d1 &$22.4050$ &$65.581$ &$7.3158$ &$22.565$ &$-4.9513$ &$1.745$ &$4.9149$ &$1.732$ &$-0.0014$ \\\\\nTb0 & 6s14f85d1 &$14.0011$ &$48.000$ &$7.0994$ &$18.468$ &$-0.6304$ &$2.188$ &$0.5431$ &$1.960$ &$-0.0007$ \\\\\nTb2 & 4f85d1 &$11.8504$ &$40.480$ &$6.7412$ &$17.303$ &$-11.6794$ &$2.248$ &$11.5615$ &$2.233$ &$-0.0002$ \\\\\nTb3 & 4f75d1 &$7.9534$ &$30.456$ &$6.3665$ &$14.596$ &$-0.8418$ &$2.508$ &$0.6482$ &$2.145$ &$0.0002$ \\\\\nTb4 & 4f65d1 &$5.8406$ &$24.788$ &$6.0831$ &$12.775$ &$-2.0431$ &$2.400$ &$1.7828$ &$2.221$ &$0.0004$ \\\\\nDy2 & 4f95d1 &$11.7905$ &$39.898$ &$6.5024$ &$16.874$ &$-11.5993$ &$2.115$ &$11.4943$ &$2.102$ &$-0.0003$ \\\\\nDy3 & 4f85d1 &$7.8866$ &$29.902$ &$6.1361$ &$14.212$ &$-12.5093$ &$2.229$ &$12.3329$ &$2.210$ &$0.0002$ \\\\\nHo3 & 4f95d1 &$7.8279$ &$29.392$ &$5.9224$ &$13.854$ &$-3.0002$ &$2.151$ &$2.8393$ &$2.080$ &$0.0001$ \\\\\nEr3 & 4f105d1 &$7.7700$ &$28.922$ &$5.7263$ &$13.523$ &$-4.1104$ &$2.035$ &$3.9640$ &$1.990$ &$0.0000$ \\\\\nTm2 & 4f125d1 &$11.6672$ &$38.468$ &$5.8888$ &$15.774$ &$-4.8013$ &$1.717$ &$4.7296$ &$1.697$ &$-0.0012$ \\\\\nTm3 & 4f115d1 &$7.7142$ &$28.488$ &$5.5450$ &$13.214$ &$-5.7987$ &$1.923$ &$5.6660$ &$1.895$ &$-0.0002$ \\\\\nTm4 & 4f105d1 &$5.6664$ &$23.000$ &$5.2790$ &$11.534$ &$-3.2389$ &$1.988$ &$3.0496$ &$1.919$ &$0.0002$ \\\\\nYb2 & 4f135d1 &$11.6437$ &$38.074$ &$5.7103$ &$15.455$ &$-2.9992$ &$1.582$ &$2.9369$ &$1.554$ &$-0.0017$ \\\\\nYb3 & 4f125d1 &$7.6609$ &$28.088$ &$5.3775$ &$12.926$ &$-5.9455$ &$1.817$ &$5.8255$ &$1.793$ &$-0.0004$ \\\\\nLu2 & 4f145d1 &$11.6308$ &$37.717$ &$5.5427$ &$15.158$ &$-6.0682$ &$1.432$ &$6.0147$ &$1.420$ &$-0.0024$ \\\\\nLu3 & 4f135d1 &$7.6106$ &$27.715$ &$5.2212$ &$12.656$ &$-2.1969$ &$1.729$ &$2.0887$ &$1.671$ &$-0.0007$ \\\\\n\\hline\n\\end{tabular}\n}\n\\end{table}\n\\section{{\\large $\\langle j_2\\rangle$} Form factors for 5f electrons  of actinide ions}\n\\begin{table}[H]\n\\caption{$\\langle j_2\\rangle$ Form factors for actinide ions}\\vspace{2mm}\n\\label{acj2}\n{\\tablesize\n\\begin{tabular}{lrrrrrrr}\n\\hline\nIon&\n\\multicolumn{1}{c}{A}&\\multicolumn{1}{c}{a}&\n\\multicolumn{1}{c}{B}&\\multicolumn{1}{c}{b}&\n\\multicolumn{1}{c}{C}&\\multicolumn{1}{c}{c}&\\multicolumn{1}{c}{D}\\\\\n\\hline\\\\[-2ex]\nU3 &$4.1582$ &$16.5336$ &$2.4675$ &$5.9516$ &$-0.0252$ &$0.7646$ &$0.0057$ \\\\\nU4 &$3.7449$ &$13.8944$ &$2.6453$ &$4.8634$ &$-0.5218$ &$3.1919$ &$0.0009$ \\\\\nU5 &$3.0724$ &$12.5460$ &$2.3076$ &$5.2314$ &$-0.0644$ &$1.4738$ &$0.0035$ \\\\\nNp3 &$3.7170$ &$15.1333$ &$2.3216$ &$5.5025$ &$-0.0275$ &$0.7996$ &$0.0052$ \\\\\nNp4 &$2.9203$ &$14.6463$ &$2.5979$ &$5.5592$ &$-0.0301$ &$0.3669$ &$0.0141$ \\\\\nNp5 &$2.3308$ &$13.6540$ &$2.7219$ &$5.4935$ &$-0.1357$ &$0.0493$ &$0.1224$ \\\\\nNp6 &$1.8245$ &$13.1803$ &$2.8508$ &$5.4068$ &$-0.1579$ &$0.0444$ &$0.1438$ \\\\\nPu3 &$2.0885$ &$12.8712$ &$2.5961$ &$5.1896$ &$-0.1465$ &$0.0393$ &$0.1343$ \\\\\nPu4 &$2.7244$ &$12.9262$ &$2.3387$ &$5.1633$ &$-0.1300$ &$0.0457$ &$0.1177$ \\\\\nPu5 &$2.1409$ &$12.8319$ &$2.5664$ &$5.1522$ &$-0.1338$ &$0.0457$ &$0.1210$ \\\\\nPu6 &$1.7262$ &$12.3240$ &$2.6652$ &$5.0662$ &$-0.1695$ &$0.0406$ &$0.1550$ \\\\\nAm2 &$3.5237$ &$15.9545$ &$2.2855$ &$5.1946$ &$-0.0142$ &$0.5853$ &$0.0033$ \\\\\nAm3 &$2.8622$ &$14.7328$ &$2.4099$ &$5.1439$ &$-0.1326$ &$0.0309$ &$0.1233$ \\\\\nAm4 &$2.4141$ &$12.9478$ &$2.3687$ &$4.9447$ &$-0.2490$ &$0.0215$ &$0.2371$ \\\\\nAm5 &$2.0109$ &$12.0534$ &$2.4155$ &$4.8358$ &$-0.2264$ &$0.0275$ &$0.2128$ \\\\\nAm6 &$1.6778$ &$11.3372$ &$2.4531$ &$4.7247$ &$-0.2043$ &$0.0337$ &$0.1892$ \\\\\nAm7 &$1.8845$ &$9.1606$ &$2.0746$ &$4.0422$ &$-0.1318$ &$1.7227$ &$0.0020$ \\\\\n\\hline\\\\[-2ex]\n\\end{tabular}\n}\n\\end{table}\n\\section{{\\large$\\langle j_4\\rangle$} Form factors for 3d atoms and ions}\n\\begin{table}[H]\n\\caption{$\\langle j_4\\rangle$ form factors for 3d atoms and ions}\\vspace{2mm}\n\\label{3dj4}\n{\\tablesize\n\\begin{tabular}{lrrrrrrr}\n\\hline\nIon&\n\\multicolumn{1}{c}{A}&\\multicolumn{1}{c}{a}&\n\\multicolumn{1}{c}{B}&\\multicolumn{1}{c}{b}&\n\\multicolumn{1}{c}{C}&\\multicolumn{1}{c}{c}&\\multicolumn{1}{c}{D}\\\\\n\\hline\\\\[-2ex]\nSc0 &$1.3420$ &$10.2000$ &$0.3837$ &$3.0786$ &$0.0468$ &$0.1178$ &$-0.0328$ \\\\\nSc1 &$7.1167$ &$15.4872$ &$-6.6671$ &$18.2692$ &$0.4900$ &$2.9917$ &$0.0047$ \\\\\nSc2 &$-1.6684$ &$15.6475$ &$1.7742$ &$9.0624$ &$0.4075$ &$2.4116$ &$0.0042$ \\\\\nTi0 &$-2.1515$ &$11.2705$ &$2.5149$ &$8.8590$ &$0.3555$ &$2.1491$ &$0.0045$ \\\\\nTi1 &$-1.0383$ &$16.1899$ &$1.4699$ &$8.9239$ &$0.3631$ &$2.2834$ &$0.0044$ \\\\\nTi2 &$-1.3242$ &$15.3096$ &$1.2042$ &$7.8994$ &$0.3976$ &$2.1562$ &$0.0051$ \\\\\nTi3 &$-1.1117$ &$14.6349$ &$0.7689$ &$6.9267$ &$0.4385$ &$2.0886$ &$0.0060$ \\\\\nV0 &$-0.9633$ &$15.2729$ &$0.9274$ &$7.7315$ &$0.3891$ &$2.0530$ &$0.0063$ \\\\\nV1 &$-0.9606$ &$15.5451$ &$1.1278$ &$8.1182$ &$0.3653$ &$2.0973$ &$0.0056$ \\\\\nV2 &$-1.1729$ &$14.9732$ &$0.9092$ &$7.6131$ &$0.4105$ &$2.0391$ &$0.0067$ \\\\\nV3 &$-0.9417$ &$14.2045$ &$0.5284$ &$6.6071$ &$0.4411$ &$1.9672$ &$0.0076$ \\\\\nV4 &$-0.7654$ &$13.0970$ &$0.3071$ &$5.6739$ &$0.4476$ &$1.8707$ &$0.0081$ \\\\\nCr0 &$-0.6670$ &$19.6128$ &$0.5342$ &$6.4779$ &$0.3641$ &$1.9045$ &$0.0073$ \\\\\nCr1 &$-0.8309$ &$18.0428$ &$0.7252$ &$7.5313$ &$0.3828$ &$2.0032$ &$0.0073$ \\\\\nCr2 &$-0.8930$ &$15.6641$ &$0.5590$ &$7.0333$ &$0.4093$ &$1.9237$ &$0.0081$ \\\\\nCr3 &$-0.7327$ &$14.0727$ &$0.3268$ &$5.6741$ &$0.4114$ &$1.8101$ &$0.0085$ \\\\\nCr4 &$-0.6748$ &$12.9462$ &$0.1805$ &$6.7527$ &$0.4526$ &$1.7999$ &$0.0098$ \\\\\nMn0 &$-0.5452$ &$15.4713$ &$0.4406$ &$4.9024$ &$0.2884$ &$1.5430$ &$0.0059$ \\\\\nMn1 &$-0.7947$ &$17.8673$ &$0.6078$ &$7.7044$ &$0.3798$ &$1.9045$ &$0.0087$ \\\\\nMn2 &$-0.7416$ &$15.2555$ &$0.3831$ &$6.4693$ &$0.3935$ &$1.7997$ &$0.0093$ \\\\\nMn3 &$-0.6603$ &$13.6066$ &$0.2322$ &$6.2175$ &$0.4104$ &$1.7404$ &$0.0101$ \\\\\nMn4 &$-0.5127$ &$13.4613$ &$0.0313$ &$7.7631$ &$0.4282$ &$1.7006$ &$0.0113$ \\\\\nFe0 &$-0.5029$ &$19.6768$ &$0.2999$ &$3.7762$ &$0.2576$ &$1.4241$ &$0.0071$ \\\\\nFe1 &$-0.5109$ &$19.2501$ &$0.3896$ &$4.8913$ &$0.2810$ &$1.5265$ &$0.0069$ \\\\\nFe2 &$-0.5401$ &$17.2268$ &$0.2865$ &$3.7422$ &$0.2658$ &$1.4238$ &$0.0076$ \\\\\nFe3 &$-0.5507$ &$11.4929$ &$0.2153$ &$4.9063$ &$0.3468$ &$1.5230$ &$0.0095$ \\\\\nFe4 &$-0.5352$ &$9.5068$ &$0.1783$ &$5.1750$ &$0.3584$ &$1.4689$ &$0.0097$ \\\\\nCo0 &$-0.4221$ &$14.1952$ &$0.2900$ &$3.9786$ &$0.2469$ &$1.2859$ &$0.0063$ \\\\\nCo1 &$-0.4115$ &$14.5615$ &$0.3580$ &$4.7170$ &$0.2644$ &$1.4183$ &$0.0074$ \\\\\nCo2 &$-0.4759$ &$14.0462$ &$0.2747$ &$3.7306$ &$0.2458$ &$1.2504$ &$0.0057$ \\\\\nCo3 &$-0.4466$ &$13.3912$ &$0.1419$ &$3.0110$ &$0.2773$ &$1.3351$ &$0.0093$ \\\\\nCo4 &$-0.4091$ &$13.1937$ &$-0.0194$ &$3.4169$ &$0.3534$ &$1.4214$ &$0.0112$ \\\\\nNi0 &$-0.4428$ &$14.4850$ &$0.0870$ &$3.2345$ &$0.2932$ &$1.3305$ &$0.0096$ \\\\\nNi1 &$-0.3836$ &$13.4246$ &$0.3116$ &$4.4619$ &$0.2471$ &$1.3088$ &$0.0079$ \\\\\nNi2 &$-0.3803$ &$10.4033$ &$0.2838$ &$3.3780$ &$0.2108$ &$1.1036$ &$0.0050$ \\\\\nNi3 &$-0.4014$ &$ 9.0462$ &$0.2314$ &$3.0753$ &$0.2192$ &$1.0838$ &$0.0060$ \\\\\nNi4 &$-0.3509$ &$8.1572$ &$0.2220$ &$2.1063$ &$0.1567$ &$0.9253$ &$0.0065$ \\\\\nCu0 &$-0.3204$ &$15.1324$ &$0.2335$ &$4.0205$ &$0.2312$ &$1.1957$ &$0.0068$ \\\\\nCu1 &$-0.3572$ &$15.1251$ &$0.2336$ &$3.9662$ &$0.2315$ &$1.1967$ &$0.0070$ \\\\\nCu2 &$-0.3914$ &$14.7400$ &$0.1275$ &$3.3840$ &$0.2548$ &$1.2552$ &$0.0103$ \\\\\nCu3 &$-0.3671$ &$14.0816$ &$-0.0078$ &$3.3149$ &$0.3154$ &$1.3767$ &$0.0132$ \\\\\nCu4 &$-0.2915$ &$14.1243$ &$-0.1065$ &$4.2008$ &$0.3247$ &$1.3516$ &$0.0148$ \\\\\n\\hline\\\\[-2ex]\n\\end{tabular}\n}\n\\end{table}\n\\section{{\\large$\\langle j_4\\rangle$} Form factors 4d atoms and ions}\n\\begin{table}[H]\n\\noindent\\caption{$\\langle j_4\\rangle$ form factors for 4d atoms and ions}\\\n\\label{4dj4}\n \\vspace{1ex}\n{\\tablesize\n\\begin{tabular}{lrrrrrrr}\n\\hline\nIon&\n\\multicolumn{1}{c}{A}&\\multicolumn{1}{c}{a}&\n\\multicolumn{1}{c}{B}&\\multicolumn{1}{c}{b}&\n\\multicolumn{1}{c}{C}&\\multicolumn{1}{c}{c}&\\multicolumn{1}{c}{D}\\\\\n\\hline\\\\[-2ex]\nY0 &$-8.0767$ &$32.2014$ &$7.9197$ &$25.1563$ &$1.4067$ &$6.8268$ &$-0.0001$ \\\\\nZr0 &$-5.2697$ &$32.8680$ &$4.1930$ &$24.1833$ &$1.5202$ &$6.0481$ &$-0.0002$ \\\\\nZr1 &$-5.6384$ &$33.6071$ &$4.6729$ &$22.3383$ &$1.3258$ &$5.9245$ &$-0.0003$ \\\\\nNb0 &$-3.1377$ &$25.5948$ &$2.3411$ &$16.5686$ &$1.2304$ &$4.9903$ &$-0.0005$ \\\\\nNb1 &$-3.3598$ &$25.8202$ &$2.8297$ &$16.4273$ &$1.1203$ &$4.9824$ &$-0.0005$ \\\\\nMo0 &$-2.8860$ &$20.5717$ &$1.8130$ &$14.6281$ &$1.1899$ &$4.2638$ &$-0.0008$ \\\\\nMo1 &$-3.2618$ &$25.4862$ &$2.3596$ &$16.4622$ &$1.1164$ &$4.4913$ &$-0.0007$ \\\\\nTc0 &$-2.7975$ &$20.1589$ &$1.6520$ &$16.2609$ &$1.1726$ &$3.9427$ &$-0.0008$ \\\\\nTc1 &$-2.0470$ &$19.6830$ &$1.6306$ &$11.5925$ &$0.8698$ &$3.7689$ &$-0.0010$ \\\\\nRu0 &$-1.5042$ &$17.9489$ &$0.6027$ &$9.9608$ &$0.9700$ &$3.3927$ &$-0.0010$ \\\\\nRu1 &$-1.6278$ &$18.5063$ &$1.1828$ &$10.1886$ &$0.8138$ &$3.4180$ &$-0.0009$ \\\\\nRh0 &$-1.3492$ &$17.5766$ &$0.4527$ &$10.5066$ &$0.9285$ &$3.1555$ &$-0.0009$ \\\\\nRh1 &$-1.4673$ &$17.9572$ &$0.7381$ &$9.9444$ &$0.8485$ &$3.1263$ &$-0.0012$ \\\\\nPd0 &$-1.1955$ &$17.6282$ &$0.3183$ &$11.3094$ &$0.8696$ &$2.9089$ &$-0.0006$ \\\\\nPd1 &$-1.4098$ &$17.7650$ &$0.7927$ &$9.9991$ &$0.7710$ &$2.9297$ &$-0.0006$ \\\\\n\\hline\\\\[-2ex]\n\\end{tabular}\n}\n\\end{table}\n\\section{{\\large$\\langle j_4\\rangle$} Form factors for 5d atoms and ions}\n\\begin{table}[H]\n \\caption{$\\langle j_4\\rangle$ form factors for the 5d electrons of transition atoms and ions from Hf to Re.\\cite{kob:11}}\n\\label{5dj4}\n \\vspace{1ex}\n {\\tablesize\n\\begin{tabular}{llrrrrrrrrr}\n\\hline\n\\multicolumn{1}{c}{ Ion}&\\multicolumn{1}{c}{ Config}&\\multicolumn{1}{c}{ A }&\\multicolumn{1}{c}{  a }&\\multicolumn{1}{c}{B }&\\multicolumn{1}{c}{ b }&\\multicolumn{1}{c}{ C }&\\multicolumn{1}{c}{ c }&\\multicolumn{1}{c}{ D }&\\multicolumn{1}{c}{ d }&\\multicolumn{1}{c}{E }\\\\\n\\hline\nHf2 & 6s05d2 &$-2.5342$ &$43.826$ &$1.8466$ &$10.393$ &$0.7761$ &$4.888$ &$-0.0327$ &$1.589$ &$0.0017$ \\\\\nHf3 & 6s05d1 &$-2.3574$ &$32.651$ &$1.8717$ &$8.476$ &$0.6367$ &$3.953$ &$-0.1133$ &$2.169$ &$0.0017$ \\\\\nTa2 & 6s05d3 &$-2.1974$ &$38.294$ &$1.6220$ &$8.838$ &$0.6836$ &$4.212$ &$-0.0539$ &$1.746$ &$0.0016$ \\\\\nTa3 & 6s05d2 &$-2.0884$ &$29.531$ &$1.7145$ &$7.385$ &$1.1809$ &$2.994$ &$-0.7705$ &$2.577$ &$0.0016$ \\\\\nTa4 & 6s05d1 &$-2.0226$ &$24.035$ &$1.7084$ &$6.594$ &$1.1799$ &$2.775$ &$-0.8384$ &$2.430$ &$0.0020$ \\\\\nW0 & 6s05d6 &$-2.1307$ &$79.955$ &$1.4055$ &$11.876$ &$0.8808$ &$4.969$ &$-0.0120$ &$0.419$ &$0.0051$ \\\\\nW0 & 6s15d5 &$-1.9667$ &$60.069$ &$1.3446$ &$9.992$ &$0.7861$ &$4.554$ &$-0.0197$ &$1.087$ &$0.0021$ \\\\\nW0 & 6s25d4 &$-1.8575$ &$47.554$ &$1.3868$ &$8.437$ &$0.6537$ &$3.939$ &$-0.0570$ &$1.722$ &$0.0015$ \\\\\nW0 & 6s05d5 &$-2.0231$ &$46.962$ &$1.3937$ &$9.263$ &$0.7420$ &$4.332$ &$-0.0288$ &$1.327$ &$0.0018$ \\\\\nW0 & 6s15d4 &$-1.9122$ &$39.952$ &$1.4385$ &$8.019$ &$0.6336$ &$3.725$ &$-0.0819$ &$1.868$ &$0.0015$ \\\\\nW2 & 6s05d4 &$-1.9355$ &$33.935$ &$1.5020$ &$7.541$ &$0.6453$ &$3.375$ &$-0.1601$ &$2.110$ &$0.0015$ \\\\\nW3 & 6s05d3 &$-1.8752$ &$26.706$ &$1.5440$ &$6.585$ &$5.9785$ &$2.575$ &$-5.6111$ &$2.516$ &$0.0018$ \\\\\nW4 & 6s05d2 &$-1.8309$ &$22.142$ &$1.5605$ &$5.935$ &$1.4898$ &$2.482$ &$-1.1930$ &$2.266$ &$0.0022$ \\\\\nW5 & 6s05d1 &$-1.7958$ &$18.987$ &$1.5913$ &$5.419$ &$2.0498$ &$2.278$ &$-1.8262$ &$2.156$ &$0.0026$ \\\\\nRe0 & 6s05d7 &$-1.8013$ &$63.944$ &$1.1773$ &$9.808$ &$0.7912$ &$4.380$ &$-0.0155$ &$0.795$ &$0.0027$ \\\\\nRe0 & 6s15d6 &$-1.7056$ &$49.628$ &$1.2209$ &$8.231$ &$0.6637$ &$3.836$ &$-0.0443$ &$1.514$ &$0.0015$ \\\\\nRe0 & 6s25d5 &$-1.6402$ &$40.319$ &$1.3192$ &$7.064$ &$0.8659$ &$2.901$ &$-0.4299$ &$2.306$ &$0.0013$ \\\\\nRe0 & 6s05d6 &$-1.7723$ &$40.683$ &$1.2795$ &$7.798$ &$0.6385$ &$3.630$ &$-0.0656$ &$1.686$ &$0.0015$ \\\\\nRe0 & 6s15d5 &$-1.6968$ &$34.939$ &$1.3535$ &$6.851$ &$1.7292$ &$2.681$ &$-1.3118$ &$2.445$ &$0.0014$ \\\\\nRe2 & 6s05d5 &$-1.7305$ &$30.305$ &$1.3808$ &$6.606$ &$1.5787$ &$2.630$ &$-1.1785$ &$2.378$ &$0.0015$ \\\\\nRe3 & 6s05d4 &$-1.6969$ &$24.325$ &$1.4088$ &$5.901$ &$1.5067$ &$2.424$ &$-1.1834$ &$2.209$ &$0.0019$ \\\\\nRe4 & 6s05d3 &$-1.6679$ &$20.454$ &$1.4439$ &$5.357$ &$0.8175$ &$2.321$ &$-0.5685$ &$1.976$ &$0.0024$ \\\\\nRe5 & 6s05d2 &$-1.6427$ &$17.722$ &$1.4880$ &$4.916$ &$0.5419$ &$2.189$ &$-0.3694$ &$1.781$ &$0.0029$ \\\\\nRe6 & 6s05d1 &$-1.6211$ &$15.673$ &$1.5419$ &$4.548$ &$1.9205$ &$1.833$ &$-1.8287$ &$1.766$ &$0.0034$ \\\\\n\\hline\n\\end{tabular}\n}\n\\end{table}\n\\begin{table}[H]\n \\caption{$\\langle j_4\\rangle$ form factors for the 5d electrons of transition atoms and ions from Os to Au.\\cite{kob:11}}\n\\label{5dj4b} \\vspace{1ex}\n{\\tablesize\n\\begin{tabular}{llrrrrrrrrr}\n\\hline\n\\multicolumn{1}{c}{ Ion}&\\multicolumn{1}{c}{ Config}&\\multicolumn{1}{c}{ A }&\\multicolumn{1}{c}{  a }&\\multicolumn{1}{c}{B }&\\multicolumn{1}{c}{ b }&\\multicolumn{1}{c}{ C }&\\multicolumn{1}{c}{ c }&\\multicolumn{1}{c}{ D }&\\multicolumn{1}{c}{ d }&\\multicolumn{1}{c}{E }\\\\\n\\hline\nOs0 & 6s05d8 &$-1.5677$ &$53.075$ &$1.0631$ &$8.143$ &$0.6808$ &$3.771$ &$-0.0308$ &$1.243$ &$0.0017$ \\\\\nOs0 & 6s15d7 &$-1.5109$ &$42.193$ &$1.1910$ &$6.850$ &$2.4597$ &$2.602$ &$-2.0163$ &$2.444$ &$0.0011$ \\\\\nOs0 & 6s25d6 &$-1.4734$ &$34.814$ &$1.2105$ &$6.165$ &$0.9468$ &$2.534$ &$-0.5773$ &$2.131$ &$0.0015$ \\\\\nOs0 & 6s05d7 &$-1.5777$ &$35.746$ &$1.2222$ &$6.650$ &$1.7260$ &$2.590$ &$-1.2942$ &$2.360$ &$0.0012$ \\\\\nOs0 & 6s15d6 &$-1.5274$ &$30.891$ &$1.2364$ &$6.044$ &$1.4100$ &$2.431$ &$-1.0480$ &$2.188$ &$0.0016$ \\\\\nOs2 & 6s05d6 &$-1.5637$ &$27.292$ &$1.2627$ &$5.880$ &$1.3526$ &$2.393$ &$-1.0026$ &$2.146$ &$0.0017$ \\\\\nOs3 & 6s05d5 &$-1.5453$ &$22.300$ &$1.3058$ &$5.301$ &$0.7208$ &$2.294$ &$-0.4480$ &$1.881$ &$0.0022$ \\\\\nOs4 & 6s05d4 &$-1.5267$ &$18.972$ &$1.3619$ &$4.834$ &$3.0121$ &$1.938$ &$-2.8240$ &$1.877$ &$0.0027$ \\\\\nOs5 & 6s05d3 &$-1.5094$ &$16.573$ &$1.4158$ &$4.458$ &$0.8448$ &$1.797$ &$-0.7349$ &$1.638$ &$0.0033$ \\\\\nOs6 & 6s05d2 &$-1.4938$ &$14.751$ &$1.4678$ &$4.149$ &$0.8091$ &$1.535$ &$-0.7720$ &$1.442$ &$0.0041$ \\\\\nOs7 & 6s05d1 &$-0.0341$ &$37.994$ &$-1.4680$ &$13.159$ &$1.5216$ &$3.898$ &$-0.0308$ &$0.550$ &$0.0083$ \\\\\nIr0 & 6s05d9 &$-1.3913$ &$45.243$ &$1.0627$ &$6.722$ &$2.5141$ &$2.534$ &$-2.0510$ &$2.383$ &$0.0009$ \\\\\nIr0 & 6s15d8 &$-1.3605$ &$36.399$ &$1.0953$ &$5.990$ &$1.7223$ &$2.353$ &$-1.3416$ &$2.162$ &$0.0014$ \\\\\nIr0 & 6s25d7 &$-1.3382$ &$30.628$ &$1.1376$ &$5.420$ &$1.4261$ &$2.160$ &$-1.1282$ &$1.974$ &$0.0019$ \\\\\nIr0 & 6s05d8 &$-1.4233$ &$31.680$ &$1.1221$ &$5.872$ &$2.2721$ &$2.301$ &$-1.8973$ &$2.163$ &$0.0015$ \\\\\nIr0 & 6s15d7 &$-1.3875$ &$27.660$ &$1.1508$ &$5.362$ &$0.6586$ &$2.302$ &$-0.3554$ &$1.810$ &$0.0020$ \\\\\nIr2 & 6s05d7 &$-1.4233$ &$24.796$ &$1.1799$ &$5.246$ &$3.2548$ &$2.072$ &$-2.9649$ &$1.997$ &$0.0020$ \\\\\nIr3 & 6s05d6 &$-1.4149$ &$20.563$ &$1.2388$ &$4.761$ &$1.1780$ &$1.928$ &$-0.9708$ &$1.761$ &$0.0026$ \\\\\nIr4 & 6s05d5 &$-1.4039$ &$17.664$ &$1.2993$ &$4.371$ &$3.5599$ &$1.661$ &$-3.4340$ &$1.625$ &$0.0033$ \\\\\n\\hline\n\\end{tabular}\n}\n\\end{table}\n\\section{{\\large$\\langle j_4\\rangle$} Form factors for 4f electrons of rare earth ions}\n\\begin{table}[H]\n\\caption{$\\langle j_4\\rangle$ form factors for rare earth ions}\\vspace{2mm}\n\\label{rej4}\n{\\tablesize\n\\begin{tabular}{lrrrrrrr}\n\\hline\nIon&\n\\multicolumn{1}{c}{A}&\\multicolumn{1}{c}{a}&\n\\multicolumn{1}{c}{B}&\\multicolumn{1}{c}{b}&\n\\multicolumn{1}{c}{C}&\\multicolumn{1}{c}{c}&\\multicolumn{1}{c}{D}\\\\\n\\hline\\\\[-2ex]\nCe2 &$-0.6468$ &$10.5331$ &$0.4052$ &$5.6243$ &$0.3412$ &$1.5346$ &$0.0080$ \\\\\nNd2 &$-0.5744$ &$10.9304$ &$0.4210$ &$6.1052$ &$0.3124$ &$1.4654$ &$0.0081$ \\\\\nNd2 &$-0.5416$ &$12.2043$ &$0.3571$ &$6.1695$ &$0.3154$ &$1.4847$ &$0.0098$ \\\\\nNd3 &$-0.4053$ &$14.0141$ &$0.0329$ &$7.0046$ &$0.3759$ &$1.7074$ &$0.0209$ \\\\\nSm2 &$-0.4150$ &$14.0570$ &$0.1368$ &$7.0317$ &$0.3272$ &$1.5825$ &$0.0192$ \\\\\nSm3 &$-0.4288$ &$10.0525$ &$0.1782$ &$5.0191$ &$0.2833$ &$1.2364$ &$0.0088$ \\\\\nEu2 &$-0.4145$ &$10.1930$ &$0.2447$ &$5.1644$ &$0.2661$ &$1.2054$ &$0.0065$ \\\\\nEu3 &$-0.4095$ &$10.2113$ &$0.1485$ &$5.1755$ &$0.2720$ &$1.2374$ &$0.0131$ \\\\\nGd2 &$-0.3824$ &$10.3436$ &$0.1955$ &$5.3057$ &$0.2622$ &$1.2032$ &$0.0097$ \\\\\nGd3 &$-0.3621$ &$10.3531$ &$0.1016$ &$5.3104$ &$0.2649$ &$1.2185$ &$0.0147$ \\\\\nTb2 &$-0.3443$ &$10.4686$ &$0.1481$ &$5.4156$ &$0.2575$ &$1.1824$ &$0.0104$ \\\\\nTb3 &$-0.3228$ &$10.4763$ &$0.0638$ &$5.4189$ &$0.2566$ &$1.1962$ &$0.0159$ \\\\\nDy2 &$-0.3206$ &$12.0714$ &$0.0904$ &$8.0264$ &$0.2616$ &$1.2296$ &$0.0143$ \\\\\nDy3 &$-0.2829$ &$9.5247$ &$0.0565$ &$4.4292$ &$0.2437$ &$1.0665$ &$0.0092$ \\\\\nHo2 &$-0.2976$ &$9.7190$ &$0.1224$ &$4.6345$ &$0.2279$ &$1.0052$ &$0.0063$ \\\\\nHo3 &$-0.2717$ &$9.7313$ &$0.0474$ &$4.6378$ &$0.2292$ &$1.0473$ &$0.0124$ \\\\\nEr2 &$-0.2975$ &$9.8294$ &$0.1189$ &$4.7406$ &$0.2116$ &$1.0039$ &$0.0117$ \\\\\nEr3 &$-0.2568$ &$9.8339$ &$0.0356$ &$4.7415$ &$0.2172$ &$1.0281$ &$0.0148$ \\\\\nTm2 &$-0.2677$ &$9.8883$ &$0.0925$ &$4.7838$ &$0.2056$ &$0.9896$ &$0.0124$ \\\\\nTm3 &$-0.2292$ &$9.8948$ &$0.0124$ &$4.7850$ &$0.2108$ &$1.0071$ &$0.0151$ \\\\\nYb2 &$-0.2393$ &$9.9469$ &$0.0663$ &$4.8231$ &$0.2009$ &$0.9651$ &$0.0122$ \\\\\nYb3 &$-0.2121$ &$8.1967$ &$0.0325$ &$3.1533$ &$0.1975$ &$0.8842$ &$0.0093$ \\\\\nPr3 &$-0.3970$ &$10.9919$ &$0.0818$ &$5.9897$ &$0.3656$ &$1.5021$ &$0.0110$ \\\\\n\\hline\\\\[-2ex]\n\\end{tabular}\n}\n\\end{table}\n\\section{{\\large$\\langle j_4\\rangle$} Form factors for 4f electrons of actinide ions}\n\\begin{table}[H]\n\\caption{$\\langle j_4\\rangle$ Form factors for actinide ions}\\vspace{2mm}\n\\label{acj4}\n{\\tablesize\n\\begin{tabular}{lrrrrrrr}\n\\hline\nIon&\n\\multicolumn{1}{c}{A}&\\multicolumn{1}{c}{a}&\n\\multicolumn{1}{c}{B}&\\multicolumn{1}{c}{b}&\n\\multicolumn{1}{c}{C}&\\multicolumn{1}{c}{c}&\\multicolumn{1}{c}{D}\\\\\n\\hline\\\\[-2ex]\nU3 &$-0.9859$ &$16.6010$ &$0.6116$ &$6.5147$ &$0.6020$ &$2.5970$ &$-0.0010$ \\\\\nU4 &$-1.0540$ &$16.6055$ &$0.4339$ &$6.5119$ &$0.6746$ &$2.5993$ &$-0.0011$ \\\\\nU5 &$-0.9588$ &$16.4851$ &$0.1576$ &$6.4397$ &$0.7785$ &$2.6402$ &$-0.0010$ \\\\\nNp3 &$-0.9029$ &$16.5858$ &$0.4006$ &$6.4699$ &$0.6545$ &$2.5631$ &$-0.0004$ \\\\\nNp4 &$-0.9887$ &$12.4415$ &$0.5918$ &$5.2941$ &$0.5306$ &$2.2625$ &$-0.0021$ \\\\\nNp5 &$-0.8146$ &$16.5809$ &$-0.0055$ &$6.4751$ &$0.7956$ &$2.5623$ &$-0.0004$ \\\\\nNp6 &$-0.6738$ &$16.5531$ &$-0.2297$ &$6.5055$ &$0.8513$ &$2.5528$ &$-0.0003$ \\\\\nPu3 &$-0.7014$ &$16.3687$ &$-0.1162$ &$6.6971$ &$0.7778$ &$2.4502$ &$0.0000$ \\\\\nPu4 &$-0.9160$ &$12.2027$ &$0.4891$ &$5.1274$ &$0.5290$ &$2.1487$ &$-0.0022$ \\\\\nPu5 &$-0.7035$ &$16.3601$ &$-0.0979$ &$6.7057$ &$0.7726$ &$2.4475$ &$0.0000$ \\\\\nPu6 &$-0.5560$ &$16.3215$ &$-0.3046$ &$6.7685$ &$0.8146$ &$2.4259$ &$0.0001$ \\\\\nAm2 &$-0.7433$ &$16.4163$ &$0.3481$ &$6.7884$ &$0.6014$ &$2.3465$ &$0.0000$ \\\\\nAm3 &$-0.8092$ &$12.8542$ &$0.4161$ &$5.4592$ &$0.5476$ &$2.1721$ &$-0.0011$ \\\\\nAm4 &$-0.8548$ &$12.2257$ &$0.3037$ &$5.9087$ &$0.6173$ &$2.1881$ &$-0.0016$ \\\\\nAm5 &$-0.6538$ &$15.4625$ &$-0.0948$ &$5.9971$ &$0.7295$ &$2.2968$ &$0.0000$ \\\\\nAm6 &$-0.5390$ &$15.4491$ &$-0.2689$ &$6.0169$ &$0.7711$ &$2.2970$ &$0.0002$ \\\\\nAm7 &$-0.4688$ &$12.0193$ &$-0.2692$ &$7.0415$ &$0.7297$ &$2.1638$ &$-0.0011$ \\\\\n\\hline\\\\[-2ex]\n\\end{tabular}\n}\n\\end{table}\n\\section{{\\large $\\langle j_6\\rangle$} Form factors for 4f electrons of rare earth ions}\n\\begin{table}[H]\n\\caption{$\\langle j_6\\rangle$ Form factors for rare earth ions}\\vspace{2mm}\n\\label{rej6}\n{\\tablesize\n\\begin{tabular}{lrrrrrrr}\n\\hline\nIon&\n\\multicolumn{1}{c}{A}&\\multicolumn{1}{c}{a}&\n\\multicolumn{1}{c}{B}&\\multicolumn{1}{c}{b}&\n\\multicolumn{1}{c}{C}&\\multicolumn{1}{c}{c}&\\multicolumn{1}{c}{D}\\\\\n\\hline\\\\[-2ex]\nCe2 &$-0.1212$ &$7.9940$ &$-0.0639$ &$4.0244$ &$0.1519$ &$1.0957$ &$0.0078$ \\\\\nNd2 &$-0.1600$ &$8.0086$ &$0.0272$ &$4.0284$ &$0.1104$ &$1.0682$ &$0.0139$ \\\\\nNd3 &$-0.0416$ &$8.0136$ &$-0.1261$ &$4.0399$ &$0.1400$ &$1.0873$ &$0.0102$ \\\\\nSm2 &$-0.1428$ &$6.0407$ &$0.0723$ &$2.0329$ &$0.0550$ &$0.5134$ &$0.0081$ \\\\\nSm3 &$-0.0944$ &$6.0299$ &$-0.0498$ &$2.0743$ &$0.1372$ &$0.6451$ &$-0.0132$ \\\\\nEu2 &$-0.1252$ &$6.0485$ &$0.0507$ &$2.0852$ &$0.0572$ &$0.6460$ &$0.0132$ \\\\\nEu3 &$-0.0817$ &$6.0389$ &$-0.0596$ &$2.1198$ &$0.1243$ &$0.7639$ &$-0.0001$ \\\\\nGd2 &$-0.1351$ &$5.0298$ &$0.0828$ &$2.0248$ &$0.0315$ &$0.5034$ &$0.0187$ \\\\\nGd3 &$-0.0662$ &$6.0308$ &$-0.0850$ &$2.1542$ &$0.1323$ &$0.8910$ &$0.0048$ \\\\\nTb2 &$-0.0758$ &$6.0319$ &$-0.0540$ &$2.1583$ &$0.1199$ &$0.8895$ &$0.0051$ \\\\\nTb3 &$-0.0559$ &$6.0311$ &$-0.1020$ &$2.2365$ &$0.1264$ &$1.1066$ &$0.0167$ \\\\\nDy2 &$-0.0568$ &$6.0324$ &$-0.1003$ &$2.2396$ &$0.1401$ &$1.1062$ &$0.0109$ \\\\\nDy3 &$-0.0423$ &$6.0376$ &$-0.1248$ &$2.2437$ &$0.1359$ &$1.2002$ &$0.0188$ \\\\\nHo2 &$-0.0725$ &$6.0453$ &$-0.0318$ &$2.2428$ &$0.0738$ &$1.2018$ &$0.0252$ \\\\\nHo3 &$-0.0289$ &$6.0504$ &$-0.1545$ &$2.2305$ &$0.1550$ &$1.2605$ &$0.0177$ \\\\\nEr2 &$-0.0648$ &$6.0559$ &$-0.0515$ &$2.2303$ &$0.0825$ &$1.2638$ &$0.0250$ \\\\\nEr3 &$-0.0110$ &$6.0609$ &$-0.1954$ &$2.2242$ &$0.1818$ &$1.2958$ &$0.0149$ \\\\\nTm2 &$-0.0842$ &$4.0699$ &$0.0807$ &$0.8492$ &$-0.2087$ &$0.0386$ &$0.2095$ \\\\\nTm3 &$-0.0727$ &$4.0730$ &$0.0243$ &$0.6888$ &$3.9459$ &$0.0023$ &$-3.9076$ \\\\\nYb2 &$-0.0739$ &$5.0306$ &$0.0140$ &$2.0300$ &$0.0351$ &$0.5080$ &$0.0174$ \\\\\nYb3 &$-0.0345$ &$5.0073$ &$-0.0677$ &$2.0198$ &$0.0985$ &$0.5485$ &$-0.0076$ \\\\\nPr3 &$-0.0224$ &$7.9931$ &$-0.1202$ &$3.9406$ &$0.1299$ &$0.8938$ &$0.0051$ \\\\\n\\hline\\\\[-2ex]\n\\end{tabular}\n}\n\\end{table}\n\\section{{\\large$\\langle j_6\\rangle$} Form factors for 4f electrons of actinide ions}\n\\begin{table}[H]\n\\caption{$\\langle j_6\\rangle$ Form factors for actinide ions}\\vspace{2mm}\n\\label{acj6}\n{\\tablesize\n\\begin{tabular}{lrrrrrrr}\n\\hline\nIon&\n\\multicolumn{1}{c}{A}&\\multicolumn{1}{c}{a}&\n\\multicolumn{1}{c}{B}&\\multicolumn{1}{c}{b}&\n\\multicolumn{1}{c}{C}&\\multicolumn{1}{c}{c}&\\multicolumn{1}{c}{D}\\\\\n\\hline\\\\[-2ex]\nU3 &$-0.3797$ &$9.9525$ &$0.0459$ &$5.0379$ &$0.2748$ &$1.6072$ &$0.0016$ \\\\\nU4 &$-0.1793$ &$11.8961$ &$-0.2269$ &$5.4280$ &$0.3291$ &$1.7008$ &$0.0030$ \\\\\nU5 &$-0.0399$ &$11.8909$ &$-0.3458$ &$5.5803$ &$0.3340$ &$1.6448$ &$0.0029$ \\\\\nNp3 &$-0.2427$ &$11.8444$ &$-0.1129$ &$5.3774$ &$0.2848$ &$1.5676$ &$0.0022$ \\\\\nNp4 &$-0.2436$ &$9.5988$ &$-0.1317$ &$4.1014$ &$0.3029$ &$1.5447$ &$0.0019$ \\\\\nNp5 &$-0.1157$ &$9.5649$ &$-0.2654$ &$4.2599$ &$0.3298$ &$1.5494$ &$0.0025$ \\\\\nNp6 &$-0.0128$ &$9.5692$ &$-0.3611$ &$4.3035$ &$0.3419$ &$1.5406$ &$0.0032$ \\\\\nPu3 &$-0.0364$ &$9.5721$ &$-0.3181$ &$4.3424$ &$0.3210$ &$1.5233$ &$0.0041$ \\\\\nPu4 &$-0.2394$ &$7.8367$ &$-0.0785$ &$4.0243$ &$0.2643$ &$1.3776$ &$0.0012$ \\\\\nPu5 &$-0.1090$ &$7.8188$ &$-0.2243$ &$4.1000$ &$0.2947$ &$1.4040$ &$0.0015$ \\\\\nPu6 &$-0.0001$ &$7.8196$ &$-0.3354$ &$4.1439$ &$0.3097$ &$1.4027$ &$0.0020$ \\\\\nAm2 &$-0.3176$ &$7.8635$ &$0.0771$ &$4.1611$ &$0.2194$ &$1.3387$ &$0.0018$ \\\\\nAm3 &$-0.3159$ &$6.9821$ &$0.0682$ &$3.9948$ &$0.2141$ &$1.1875$ &$-0.0015$ \\\\\nAm4 &$-0.1787$ &$7.8805$ &$-0.1274$ &$4.0898$ &$0.2565$ &$1.3152$ &$0.0017$ \\\\\nAm5 &$-0.0927$ &$6.0727$ &$-0.2227$ &$3.7840$ &$0.2916$ &$1.3723$ &$0.0026$ \\\\\nAm6 &$0.0152$ &$6.0788$ &$-0.3549$ &$3.8610$ &$0.3125$ &$1.4031$ &$0.0036$ \\\\\nAm7 &$0.1292$ &$6.0816$ &$-0.4689$ &$3.8791$ &$0.3234$ &$1.3934$ &$0.0042$ \\\\\n\\hline\\\\[-2ex]\n\\end{tabular}\n}\n\\end{table}\n\n", "meta": {"hexsha": "2a63cfcacfda27f428195db83cd80116b8c5d8e1", "size": 57986, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/ffacts/texes/fftable.tex", "max_stars_repo_name": "ccdc-opensource/ccsl", "max_stars_repo_head_hexsha": "47f0d0e63d22c9c578bfe038f1baa4e389d87081", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/ffacts/texes/fftable.tex", "max_issues_repo_name": "ccdc-opensource/ccsl", "max_issues_repo_head_hexsha": "47f0d0e63d22c9c578bfe038f1baa4e389d87081", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/ffacts/texes/fftable.tex", "max_forks_repo_name": "ccdc-opensource/ccsl", "max_forks_repo_head_hexsha": "47f0d0e63d22c9c578bfe038f1baa4e389d87081", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 66.9584295612, "max_line_length": 269, "alphanum_fraction": 0.5272307109, "num_tokens": 32228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3346886718591733}}
{"text": "\\documentclass[main_zanardi.tex]{subfiles}\n\n\\begin{document}\n\n\n% Zanardi è uno iettatore come Pauli\n\n\\paragraph{Questions}\n\nHow do we implement the POVM we described last time? That is left to the experimentalists.\n\n\\paragraph{Proof of the theorem}\n\nThis is useful because it shows us technicques, tools.\n\nWe have these \\( E _{i}  \\) from the POVM.\n\nWe wish to prove\n\n\\begin{equation}\n  \\cos ^{-1} \\abs{\\braket{\\phi}{\\psi}}\n  = \\cos ^{-1} \\qty(\\sqrt{p_i ^{\\mathbb{E}} (\\phi)} \\sqrt{p_i(\\psi)^{\\mathbb{E}}})\n\\end{equation}\n\n\\begin{align}\n  \\abs{\\braket{\\phi}{\\psi}} &= \\abs{\\sum_i \\bra{\\phi} E_i \\ket{\\psi}}  \\\\\n  &\\leq \\sum_i \\abs{\\bra{\\phi} \\sqrt{E _{i} } \\sqrt{E _{i}} \\ket{\\psi}}  \\\\\n  &= \\sum _{i} \\abs{\\braket{\\hat{\\phi_i}}{\\hat{\\psi_i}}}  \\\\\n  &\\leq \\sum_i \\norm{\\sqrt{E_i} \\ket{\\phi}}\\norm{\\sqrt{E_i} \\ket{\\psi}}  \\\\\n  &= \\sum_i \\sqrt{\\ev{E_i}{\\phi}} \\sqrt{\\ev{E_i}{\\psi}}  \\\\\n  &= \\sum_i \\sqrt{p_i ^{\\mathbb{E}} (\\phi)} \\sqrt{p_i(\\psi)^{\\mathbb{E}}}\n\\end{align}\n\nso we just apply the \\( \\cos ^{-1} \\) to both sides.\n\n\\begin{equation}\n  \\mathbb{E} = \\qty{\\ketbra{\\phi} | , \\qty{\\ketbra{\\phi_i}} \\text{span } \\ketbra{\\phi}^{\\perp}}\n\\end{equation}\n\nso the first term just gives us the upper bound, the other terms in the sum are 0: the inequality is saturated. We can just measure the projector associated with the state we want to know about.\n\n\\paragraph{Infinitesimal distance}\n\nWhat is \\( \\dd _{B} \\qty(\\vec{p} , \\vec{p} + \\dd{\\vec{p}}) \\)?\n\n\\begin{align}\n  \\cos ^{-1} \\qty{\\sum_i \\sqrt{p_i(p_i + \\dd{p}_i)}}\n  &= \\cos ^{-1} \\qty{\\sum_i p_i \\sqrt{1 + \\frac{\\dd{p}_i }{p_i}}}  \\\\\n  &\\sim \\cos ^{-1} \\qty(\\sum_i p_i \\qty(1 + \\underbrace{\\cancelto{0}{\\frac{1}{2} \\frac{\\dd{p}_i}{p_i}}}_{\\substack{\\text{The probabilities}\\\\ \\text{are normalized}}}     - \\frac{1}{8} \\qty(\\frac{\\dd{p_i}}{p_i})^{2} ))\n\\end{align}\n\nbut the term \\( \\sum_i \\dd{p}_i \\) vanishes, so we have\n\n\\begin{equation}\n  \\cos \\dd{s} = 1 - \\frac{1}{8}\\frac{\\dd{p}_i ^{2} }{p_i}\n\\end{equation}\n\nbut \\( \\cos \\dd{s} \\sim 1 - 1/2 \\dd{s}^{2} _{B}  \\), so\n\n\\begin{equation} \\label{eq:fisher-metric}\n  \\dd{s}^{2}_{B}  = \\frac{1}{4} \\sum_i  \\frac{\\qty(\\dd{p}_i)^{2} }{p_i}\n\\end{equation}\n\nThis is the \\emph{Fisher metric}. More differential-geometry-like: take some \\( \\lambda \\in \\mathcal{M} = \\qty{\\text{manifold of control parameters of dimension N}} \\), such that \\( p_i = p_i(\\lambda) \\) and  \\( \\dd{p}_i = \\sum_\\mu (\\partial_\\mu p_i) \\dd{\\lambda_\\mu} \\).\n\nThen\n\n\\begin{equation}\n  g _{\\mu \\nu} = \\frac{1}{4} \\sum_i \\frac{(\\partial_\\mu p_i)(\\partial_\\nu p_i)}{p_i}\n\\end{equation}\n\n\\begin{equation}\n  \\dd{s}_B ^2 = g _{\\mu \\nu} \\dd{\\lambda}_\\mu \\dd{\\lambda}_\\nu\n\\end{equation}\n\n\\section{Parameter estimation}\n\nTake a random variable \\( x \\) distributed according to \\(p_\\theta (x)\\) (a one-parameter distribution, with \\(\\theta\\) as the parameter), and let \\(\\Theta\\) be an estimator for the parameter \\(\\theta\\): then \\( \\expval{\\Theta} = \\theta = \\int  p_\\theta(x) \\Theta(x) \\dd{x}  \\).\n\nWe prove a super-famous bound. Differentiate the previous equation wrt \\( \\theta \\).\n\n\\begin{subequations}\\label{eq:classical-crao-start}\n\\begin{align}\n  1 &= \\int  p' _\\theta (x) \\Theta (x) \\dd{x}   \\\\\n  &= \\braket{\\frac{p'_\\theta}{p_\\theta}}{\\Theta}_p \\label{eq:classical-crao-start-subeq}\n\\end{align}\n\\end{subequations}\n\n\\textbf{Claim}: the notation \\( \\braket{f}{g}_p = \\int  p_\\theta f g \\dd{x}  \\) defines a scalar product.\n\n\\begin{greenbox}\n  \\textbf{Proof: }\n  The axioms for a real scalar product are symmetry, linearity, and positive definiteness. The first two come from the properties of the regular product \\(fg\\); the interesting one to prove is the third. It is true since \\(p_ \\theta \\geq 0\\), and then \\(\\forall f: \\int  p_ \\theta f^2  \\dd{x} \\geq 0 \\), also (modulo equality almost everywhere) \\(\\braket{f}{f}=0 \\iff f=0\\).\n\\end{greenbox}\n\nWe can subtract \\( \\theta \\) from \\(\\Theta \\rightarrow \\overline{\\Theta} = \\Theta - \\theta \\) leaving the result unchanged, since it holds for any estimator: we restrict ourselves to \\emph{unbiased} ones. \n\n% When differentiting in  \\eqref{eq:classical-crao-start} the additional terms are\n%\n% \\begin{equation}\n%   -\\partial _ \\theta \\int  p_ \\theta \\theta \\dd{x} = - \\theta \\int  p' _ \\theta \\dd{x}\n%   - \\int p_ \\theta \\dd{x} = - 1\n% \\end{equation}\n\n\\begin{align}\n  1 &\\leq \\norm{\\frac{p_\\theta '}{p_\\theta}}^{2}_p \\norm{\\Theta}^2_p  \\\\\n  &= \\qty(\\int  p_\\theta \\frac{(p_\\theta ')^2}{p_\\theta^2} \\dd{x} )\n  \\qty(\\int p_\\theta (\\Theta(x) - \\theta)^2 \\dd{x} )  \\\\\n  &= F \\var{\\Theta}\n\\end{align}\n\nWhere \\( F \\) is just the Fischer metric. (To check: \\( \\bar{\\Theta} = \\Theta - \\theta \\) )\n\nBut this means \\(\\var{\\Theta} \\geq F ^{-1} \\): this is the \\emph{Cramer-Rao} inequality.\n\n\\subsection{Quantize it!}\n\nUnbiased estimator \\( \\Tr (\\rho_\\theta ' \\hat{\\Theta}) = 1 \\).\n\nWe can do \\( \\Tr (\\rho_\\theta \\rho_\\theta ^{-1} \\rho_\\theta ' \\hat{\\Theta}) = 1 \\)\n\nBut this is noncommutative! We can do\n\n\\begin{equation} \\label{eq:SLD-def}\n  L_\\rho (x)  = \\frac{1}{2} \\qty(\\rho X + X \\rho) = \\rho'\n\\end{equation}\n\nThis is the Symmetric Logarithmic Derivative, SLD.\n(recall the logarithmic derivative \\( \\rho' / \\rho = \\dv*{\\log \\rho}{x} \\) ).\n\nNow\n\n\\begin{equation}\n  \\frac{1}{2} \\Tr \\qty[\\qty(\\rho x + x \\rho) \\bar{\\Theta}] = \\Re \\Tr (\\rho X \\Theta)\n\\end{equation}\n\nand we can take this equation in absolute value. Then,\n\n\\begin{equation}\n  1 \\leq \\abs{\\Tr (\\rho X \\bar{\\Theta})}^{2} = \\abs{\\braket{X}{\\bar{\\Theta}}}^{2}_{\\rho}\n\\end{equation}\n\nAnd like before\n\n\\begin{equation}\n  1 \\leq \\norm{X}^{2} _{\\rho}  \\norm{\\bar{\\Theta}}^{2} _{\\rho}\n  = \\Tr (\\rho X^2 ) Tr(\\rho (\\Theta - \\theta)^2)\n\\end{equation}\n\nso then \\( \\var{\\Theta} \\geq 1/F_Q \\).\n\n\\textbf{Claim}: take \\( \\rho = \\sum_i \\ketbra{i} \\), then \\( X _{ij} = 2\\bra{i}\\rho' \\ket{j}/\\qty(p_i + p_j) \\).\n\nSo we can compute\n\n\\begin{align}\n  F_Q &= \\Tr(\\rho X^2) = \\sum_i p_i \\ev{X^2}{i}  \\\\\n  &= \\sum _{ij} p_i \\bra{i} X \\ketbra{j} X \\ket{i}  \\\\\n  &= \\sum _{ij} p_i \\frac{2}{p_i + p_j} \\bra{i} \\rho' \\ketbra{j} \\rho' \\ket{i} \\frac{2}{p_i + p_j}  \\\\\n  &= 2 \\sum _{ij} \\frac{\\abs{\\bra{i} \\rho' \\ket{j}}^2 }{p_i + p_j}\n\\end{align}\n\nThis is Quantum Fischer. It really is the result of \\emph{classical} optimization.\n\nThe denominator diverges! but the numerator goes to zero quadratically (?).\n\n\\paragraph{Fischer metric for pure states}\n\nTake \\( \\rho_\\theta = \\ketbra{\\psi_\\theta} \\) gound-eigenstate of a many-body system.\n\n\\begin{equation}\n  F_Q ^{\\text{pure}} \\sim \\braket{\\psi_\\theta'}{\\psi_\\theta'} - \\abs{\\braket{\\psi_\\theta'}{\\psi_\\theta}}^2\n\\end{equation}\n\nwhere \\( \\psi' = \\partial_\\theta \\psi \\). This is a way to solve the Lyapunov equation \\( L_\\theta (\\rho) = \\rho' \\).\n\n\\( \\Pi = \\ketbra{\\psi} \\). Then \\(\\Pi ^2 = \\Pi\\), we differentiate it.\nSo \\( \\Pi' \\Pi + \\Pi \\Pi' = \\Pi' \\): in the pure state case, the solution is then just \\( \\Pi ' = X \\).\n\n\\textbf{Claim}: we can calculate  \\( F_Q =  \\Tr \\qty(\\rho \\qty(\\rho')^2)\\)...\n\n\\begin{greenbox}\n  \\textbf{Proof}\n  The derivative of \\( \\rho \\) is \\( \\rho' = \\ketbra{\\psi}{\\psi'} + \\ketbra{\\psi'}{\\psi} \\).\n  We also know, by differentiating \\(1 = \\braket{\\psi}{\\psi} \\), that \\(\\braket{\\psi}{\\psi'} = - \\braket{\\psi'}{\\psi} \\). Therefore \\(\\braket{\\psi}{\\psi'} = s\\) is purely imaginary, \\(s = -s^*\\).\n\n  Then computing \\( \\Tr(\\rho \\rho' \\rho')\\) (in a basis consisting of \\(\\ket{\\psi } \\) and other perpendicular vectors, whose contribution is null because of the first term \\(\\rho\\)) we get:\n\n\\begin{subequations}\n\\begin{align}\n   \\Tr(\\rho \\rho' \\rho')\n   &= \\bra{\\psi} \\qty(\\ketbra{\\psi}{\\psi'} + \\ketbra{\\psi'}{\\psi})^2 \\ket{\\psi}   \\\\\n   &= \\cancelto{1}{\\braket{\\psi}{\\psi}}\\braket{\\psi'}{\\psi}\\braket{\\psi'}{\\psi}\n   + \\cancelto{1}{\\braket{\\psi}{\\psi}}\\braket{\\psi'}{\\psi'}\\cancelto{1}{\\braket{\\psi}{\\psi}} \\nonumber \\\\\n   &+ \\braket{\\psi}{\\psi'}\\cancelto{1}{\\braket{\\psi}{\\psi}}\\braket{\\psi'}{\\psi}\n   + \\braket{\\psi}{\\psi'}\\braket{\\psi}{\\psi'}\\cancelto{1}{\\braket{\\psi}{\\psi}} \\\\\n   &= \\braket{\\psi'}{\\psi}^2\n   + \\braket{\\psi'}{\\psi'} + \\braket{\\psi}{\\psi'}\\braket{\\psi'}{\\psi}\n   + \\braket{\\psi}{\\psi'}^2  \\\\\n   &= \\braket{\\psi'}{\\psi'} + s^2 + (-s)^2 + s(-s)  \\\\\n   &= \\braket{\\psi'}{\\psi'} + s^2  \\\\\n   &= \\braket{\\psi'}{\\psi'} - \\abs{\\braket{\\psi}{\\psi'}}^2\n\\end{align}\n\\end{subequations}\n\nsince \\(s^2 \\) must be real and negative.\n\n\\end{greenbox}\n\\end{document}\n", "meta": {"hexsha": "a93d3b7df731aad64f5f4069ae076a5ad23deee9", "size": 8293, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "info_Q/zanardi/zanardi2.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "info_Q/zanardi/zanardi2.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "info_Q/zanardi/zanardi2.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 39.4904761905, "max_line_length": 374, "alphanum_fraction": 0.6101531412, "num_tokens": 3136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073802837477, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.33458382603660647}}
{"text": "\\chapter{Advanced Definition Principles}\\label{HOLdefinitions}\n\n\\section{Datatypes}\\label{sec:datatype}\n\\index{type definitions, in HOL logic@type definitions, in \\HOL{} logic!algebraic types}\n\\index{Datatype@\\ml{Datatype}|(}\n\\index{Hol_datatype@\\ml{Hol_datatype}|see{\\ml{Datatype}}}\n\\index{algebraic data types|see{\\ml{Datatype}}}\n\\index{data types!definition in HOL@definition in \\HOL{}}\n\\index{data types!definition in HOL@definition in \\HOL{}|seealso{\\ml{Datatype}}}\n\nAlthough the \\HOL{} logic provides primitive definition principles allowing new types to be introduced, the level of detail is very fine-grained.\n%\nThe style of datatype definitions in functional programming languages provides motivation for a high level interface for defining algebraic datatypes.\n\nThe \\verb+Datatype+ function supports the definition of such data types; the specifications of the types may be recursive, mutually recursive, nested recursive, and involve records.\n%\nThe syntax of declarations that \\verb+Datatype+ accepts is found in Table~\\ref{datatype}.%\n\\footnote{\\HOL{} also supports another syntax for datatype definition through the \\ml{Hol_datatype} entrypoint. %\nFor more details on this syntax, see \\ml{Hol_datatype}'s entry in \\REFERENCE.}\n\n\\newcommand{\\itelse}[3]{\\mbox{$\\mathtt{if}\\ {#1}\\ \\mathtt{then}\\ {#2}\\ \\mathtt{else}\\ {#3}$}}\n\n\\newcommand{\\bk}{\\char'134}\n\\newcommand{\\ident}      {\\mbox{\\it ident}}\n\\newcommand{\\clause}     {\\mbox{\\it clause}}\n\\newcommand{\\type}       {\\mbox{\\it hol\\_type}}\n\\newcommand{\\tyspec}     {\\mbox{\\it ty-spec}}\n{\n\\newcommand{\\binding} {\\mbox{\\it binding}}\n\\newcommand{\\recdspec}  {\\mbox{\\it record-spec}}\n\\newcommand{\\constr} {\\mbox{\\it constructor-spec}}\n\n\\begin{table}[htbp]\n\\begin{center}\n\\begin{tabular}{|rcl|}\n\\hline\n\\multicolumn{3}{|l|}\n{\\texttt{Datatype `}[\\binding\\ \\texttt{;}]$^*$ \\binding\\texttt{`}}\\\\\n& &\\\\\n\\binding & \\verb+::=+ & \\ident\\ \\verb+=+ \\constr\\\\\n         & \\verb+|+   & \\ident\\ \\verb+=+ \\recdspec\\\\\n& & \\\\\n\\constr & \\verb+::=+ & [\\clause{} \\verb+|+]$^*$ \\clause \\\\\n& & \\\\\n\\clause & \\verb+::=+ & \\ident{} \\tyspec$^*$\\\\\n& & \\\\\n\\tyspec & \\verb+::=+ & \\verb+(+ \\type{} \\verb+)+ \\quad\\verb+|+\\quad \\mbox{\\it atomic-type}\\\\\n& & \\\\\n\\recdspec & \\verb+::=+ & \\verb+<|+ [\\ident\\ \\verb+:+ \\type\\ \\verb+;+]$^*$\n                                   \\ident\\ \\verb+:+ \\type\\ \\verb+|>+\\\\\n\n\\hline\n\\end{tabular}\n\\caption{Datatype Declaration. An \\textit{atomic-type} is a single token that denotes a \\type{} (\\eg, \\holtxt{num}, \\holtxt{real}, or \\holtxt{'a}).}\\label{datatype}\n\\end{center}\n\\end{table}\n}\n\n\n\\index{type definitions, in HOL logic@type definitions, in \\HOL{} logic!maintenance of TypeBase@maintenance of \\ml{TypeBase}}\n\\index{TypeBase@\\ml{TypeBase}}\n%\n\\HOL{} maintains an underlying database of datatype facts called the\n\\ml{TypeBase}.  This database is used to support various high-level\nproof tools (see Section~\\ref{sec:bossLib}), and is augmented whenever\na \\verb+Datatype+ declaration is made.  When a datatype is\ndefined by \\verb+Datatype+, the following information is derived\nand stored in the database.\n\n\\begin{itemize}\n\\item initiality theorem for the type\n\\item injectivity of the constructors\n\\item distinctness of the constructors\n\\item structural induction theorem\n\\item case analysis theorem\n\\item definition of the `case' constant for the type\n\\item congruence theorem for the case constant\n\\item definition of the `size' of the type\n\\end{itemize}\n\nWhen the \\HOL{} system\nstarts up, the \\ml{TypeBase} already contains the relevant entries for\nthe types \\holtxt{bool}, \\holtxt{prod}, \\holtxt{num}, \\holtxt{option},\nand \\holtxt{list}.\n\n\\paragraph{Example: Binary trees}\nThe following ML declaration of a data type of binary trees\n\\begin{hol}\n\\begin{verbatim}\n  datatype ('a,'b) btree = Leaf of 'a\n                         | Node of ('a,'b) btree * 'b * ('a,'b) btree\n\\end{verbatim}\n\\end{hol}\n\\noindent would be declared in \\HOL{} as\n\\begin{hol}\n\\begin{verbatim}\n   Datatype `btree = Leaf 'a | Node btree 'b btree`\n\\end{verbatim}\n\\end{hol}\n\\noindent Note that any type parameters for the new type are not\nmentioned: the type variables are always ordered alphabetically.\n\nThis subtle point bears repeating: the format of datatype definitions\ndoes not have enough information to always determine the order of\narguments to the introduced type operators. Thus, when defining a type\nthat is polymorphic in more than one argument, there is a question of\nwhat the order of the new operator's arguments will be.  For another\nexample, if one defines\n%\n\\begin{hol}\n\\begin{verbatim}\n   Datatype `sum = C1 'left | C2 'right`;\n\\end{verbatim}\n\\end{hol}\n%\nand then writes \\ml{('a,'b)sum}, will the \\ml{'a} value be under the\n\\ml{C1} or \\ml{C2} constructor?\nThe system chooses to make the arguments corresponding to variables appear in the order given by the dictionary ordering of the names of the variables occurring in the definition.\nThus, in the example given, the \\ml{'a} of \\ml{('a,'b)sum} will be the argument to the \\holtxt{C1} constructor because \\holtxt{'left} comes before \\holtxt{'right} in the standard (ASCII) dictionary ordering.\n\n\\subsection{Further examples}\n\n In the following, we shall give an overview of the kinds of types that\n may be defined by \\ml{Datatype}.\n\n To start, enumerated types can be defined as in the following example:\n\\begin{hol}\n\\begin{verbatim}\n  Datatype\n    `enum = A1  | A2  | A3  | A4  | A5\n          | A6  | A7  | A8  | A9  | A10\n          | A11 | A12 | A13 | A14 | A15\n          | A16 | A17 | A18 | A19 | A20\n          | A21 | A22 | A23 | A24 | A25\n          | A26 | A27 | A28 | A29 | A30`\n\\end{verbatim}\n\\end{hol}\n%\nOther non-recursive types may be defined as well:\n\\begin{hol}\n\\begin{verbatim}\n  Datatype\n    `foo = N num\n         | B bool\n         | Fn ('a -> 'b)\n         | Pr ('a # 'b)`\n\\end{verbatim}\n\\end{hol}\n%\nTurning to recursive types, we have already seen a type of binary\ntrees having polymorphic values at internal nodes. This time, we will\ndeclare it in ``paired'' format.\n\\begin{hol}\n\\begin{verbatim}\n  Datatype\n    `tree = Leaf 'a\n          | Node (tree # 'b # tree)`\n\\end{verbatim}\n\\end{hol}\n%\nThis specification seems closer to the declaration that one might make\nin ML, but can be more difficult to deal with in proof than the curried format\nused above.\n\nThe basic syntax of the named lambda calculus is easy to describe:\n%\n\\begin{hol}\n\\begin{verbatim}\n  Datatype\n    `lambda = Var string\n            | Const 'a\n            | Comb lambda lambda\n            | Abs lambda lambda`\n\\end{verbatim}\n\\end{hol}\n%\nThe syntax for `de Bruijn' terms is roughly similar:\n%\n\\begin{hol}\n\\begin{verbatim}\n  Datatype\n    `dB = Var string\n        | Const 'a\n        | Bound num\n        | Comb dB dB\n        | Abs dB`\n\\end{verbatim}\n\\end{hol}\n%\nArbitrarily branching trees may be defined by allowing a node to hold\nthe list of its subtrees. In such a case, leaf nodes do not need to be\nexplicitly declared.\n%\n\\begin{hol}\n\\begin{verbatim}\n  Datatype `ntree = Node 'a (ntree list)`\n\\end{verbatim}\n\\end{hol}\n%\nA type of `first order terms' can be declared as follows:\n%\n\\begin{hol}\n\\begin{verbatim}\n  Datatype\n    `term = Var string\n          | Fnapp (string # term list)`\n\\end{verbatim}\n\\end{hol}\n%\nMutally recursive types may also be defined. The following, extracted by\nElsa Gunter from the Definition of Standard ML, captures a subset of\nCore ML.\n%\n\\begin{hol}\n\\begin{verbatim}\n  Datatype\n    `atexp = var_exp string\n           | let_exp dec exp ;\n\n       exp = aexp    atexp\n           | app_exp exp atexp\n           | fn_exp  match ;\n\n     match = match  rule\n           | matchl rule match ;\n\n      rule = rule pat exp ;\n\n       dec = val_dec   valbind\n           | local_dec dec dec\n           | seq_dec   dec dec ;\n\n   valbind = bind  pat exp\n           | bindl pat exp valbind\n           | rec_bind valbind ;\n\n       pat = wild_pat\n           | var_pat string`\n\\end{verbatim}\n\\end{hol}\n%\nSimple record types may be introduced using the \\holtxt{<| ... |>} notation.\n%\n\\begin{hol}\n\\begin{verbatim}\n  Datatype\n    `state = <| Reg1 : num; Reg2 : num; Waiting : bool |>`\n\\end{verbatim}\n\\end{hol}\n%\nThe use of record types may be recursive. For example, the following\ndeclaration could be used to formalize a simple file system.\n%\n\\begin{hol}\n\\begin{verbatim}\n  Datatype\n    `file = Text string | Dir directory\n       ;\n     directory = <| owner : string ;\n                    files : (string # file) list |>`\n\\end{verbatim}\n\\end{hol}\n\n\\subsection{Type definitions that fail}\n\n Now we address some types that cannot be declared with \\ml{Datatype}.\nIn some cases they cannot exist in HOL at all; in others, the type\ncan be built in the HOL logic, but \\ml{Datatype} is not able to make\nthe definition.\n\nFirst, an empty type is not allowed in HOL, so the following attempt\nis doomed to fail.\n%\n\\begin{hol}\n\\begin{verbatim}\n  Datatype `foo = A foo`\n\\end{verbatim}\n\\end{hol}\n%\nSo called `nested types', which are occasionally quite useful, cannot\nat present be built with \\ml{Datatype}:\n%\n\\begin{hol}\n\\begin{verbatim}\n  Datatype\n    `btree = Leaf 'a\n           | Node (('a # 'a) btree)`\n\\end{verbatim}\n\\end{hol}\n%\nTypes may not recurse on either side of function arrows.  Recursion on\nthe right is consistent (see the theory \\theoryimp{inftree}), but\n\\ml{Datatype} is not capable of defining algebraic types that\nrequire it.  Thus, examples such as the following will fail:\n%\n\\begin{hol}\n\\begin{verbatim}\n  Datatype\n    `flist = Nil\n           | Cons 'a ('b -> flist)`\n\\end{verbatim}\n\\end{hol}\n%\nRecursion on the left must fail for cardinality reasons. For\nexample, HOL does not allow the following attempt to model the untyped\nlambda calculus as a set (note the \\holtxt{->} in the clause for the\n\\holtxt{Abs} constructor):\n%\n\\begin{hol}\n\\begin{verbatim}\n  Datatype\n    `lambda = Var string\n            | Const 'a\n            | Comb lambda lambda\n            | Abs (lambda -> lambda)`\n\\end{verbatim}\n\\end{hol}\n\n\\subsection{Theorems arising from a datatype definition}\n\nThe consequences of an invocation of \\ml{Datatype} are stored in the current theory segment and in \\ml{TypeBase}.\nThe principal consequences of a datatype definition are the primitive recursion and induction theorems.\nThese provide the ability to define simple functions over the type, and an induction principle for the type.\n\\index{induction theorems, in HOL logic@induction theorems, in \\HOL{} logic!for algebraic data types}\nThus, for a type named \\holtxt{ty}, the primitive recursion theorem is stored under \\ml{ty\\_Axiom} and the induction theorem is put under \\ml{ty\\_induction}.\nOther consequences include the distinctness of constructors (\\ml{ty\\_distinct}), and the injectivity of constructors (\\verb+ty_11+).\nA `degenerate' version of \\ml{ty\\_induction} is also stored under \\ml{ty\\_nchotomy}: it provides for reasoning by cases on the construction of elements of \\ml{ty}.\nFinally, some special-purpose theorems are stored: for example, \\ml{ty\\_case\\_cong} holds a congruence theorem for ``case'' statements on elements of \\ml{ty}.\nThese case statements are defined by \\ml{ty\\_case\\_def}.\nAlso, a definition of the ``size'' of the type is added to the current theory, under the name \\ml{ty\\_size\\_def}.\n\nFor example, invoking\n%\n\\begin{hol}\n\\begin{verbatim}\n  Datatype `tree = Leaf num | Node tree tree`\n\\end{verbatim}\n\\end{hol}\n%\nresults in the definitions\n%\n\\begin{hol}\n\\begin{verbatim}\n  tree_case_def =\n    |- (!a f f1 a. tree_CASE (Leaf a) f f1 = f a) /\\\n       !f f1 a0 a1. tree_CASE (Node a0 a1) f f1 = f1 a0 a1\n\n  tree_size_def\n    |- (!a. tree_size (Leaf a) = 1 + a) /\\\n       !a0 a1. tree_size (Node a0 a1) = 1 + (tree_size a0 + tree_size a1)\n\\end{verbatim}\n\\end{hol}\n%\nbeing added to the current theory.\nThe case constant (here \\holtxt{tree_CASE}) allows pretty case-expressions; see Section~\\ref{CaseExp} below.\nThe following theorems about the datatype are also proved and stored in the current theory.\n%\n\\begin{hol}\n\\begin{verbatim}\n  tree_Axiom\n    |- !f0 f1.\n       ?fn. (!a. fn (Leaf a) = f0 a) /\\\n            !a0 a1. fn (Node a0 a1) = f1 a0 a1 (fn a0) (fn a1)\n  tree_induction\n    |- !P. (!n. P (Leaf n)) /\\\n           (!t t0. P t /\\ P t0 ==> P (Node t t0)) ==> !t. P t\n  tree_nchotomy\n    |- !t. (?n. t = Leaf n) \\/ ?t' t0. t = Node t' t0\n  tree_11\n    |- (!a a'. (Leaf a = Leaf a') = (a = a')) /\\\n       !a0 a1 a0' a1'. (Node a0 a1 = Node a0' a1') = (a0=a0') /\\ (a1=a1')\n  tree_distinct\n    |- !a1 a0 a. ~(Leaf a = Node a0 a1)\n  tree_case_cong\n    |- !M M' f f1.\n        (M = M') /\\\n        (!a. (M' = Leaf a) ==> (f a = f' a)) /\\\n        (!a0 a1. (M' = Node a0 a1) ==> (f1 a0 a1 = f1' a0 a1))\n          ==>\n        (tree_CASE M f f1 = tree_CASE M' f' f1')\n\\end{verbatim}\n\\end{hol}\n%\nWhen a type involving records is defined, many more definitions are\nmade and added to the current theory.\n\nA mutually recursive type definition results in the above\ntheorems and definitions being added for each of the defined types.\n\n\\section{Record Types}\\label{sec:records}\n\\index{type definitions, in HOL logic@type definitions, in \\HOL{} logic!record types}\n\\index{record types}\n\nRecord types are convenient ways of bundling together a number of\ncomponent types, and giving those components names so as to facilitate\naccess to them.  Record types are semantically equivalent to big pair\n(product) types, but the ability to label the fields with names of\none's own choosing is a great convenience.  Record types as\nimplemented in \\HOL{} are similar to C's \\texttt{struct} types and to\nPascal's records.\n\nDone correctly, record types provide useful maintainability features.\nIf one can always access the {\\tt fieldn} field of a record type by\nsimply writing {\\tt record.fieldn}, then changes to the type that\nresult in the addition or deletion of other fields will not invalidate\nthis reference.  One failing in SML's record types is that they do not\nallow the same maintainability as far as (functional) updates of\nrecords are concerned.  The HOL implementation allows one to write\n\\begin{hol}\n\\begin{verbatim}\n  rec with fieldn := new_value\n\\end{verbatim}\n\\end{hol}\nwhich replaces the old value of {\\tt fieldn} in the record {\\tt rec}\nwith {\\tt new\\_value}.  This expression will not need to be changed if\nanother field is added, modified or deleted from the record's original\ndefinition.\n\n\\paragraph{Defining a record type}\nRecord types are defined with the function \\texttt{Datatype}, as\npreviously discussed.  For example, to create a record type called\n{\\tt person} with boolean, string and number fields called {\\tt\n  employed}, {\\tt name} and {\\tt age}, one would enter:\n\\begin{hol}\n\\begin{verbatim}\n  Datatype\n    `person = <| employed : bool ;\n                 age : num ;\n                 name : string |>`\n\\end{verbatim}\n\\end{hol}\nThe order in which the fields are entered is not significant. As well\nas defining the type (called {\\tt person}), the datatype definition\nfunction also defines two other sets of constants.  These are the\nfield access functions and functional update functions.  The field\naccess functions have names of the form\n   $\\langle$\\textsl{record-type\\/}$\\rangle$\\verb|_|$\\langle$\\textsl{field\\/}$\\rangle$.\nThese functions can be used directly, or one can use standard field\nselection notation to access the values of a record's field.  Thus,\none would write the expression: \\holtxt{bob.employed} in order\nto return the value of {\\tt bob}'s {\\tt employed} field.  The\nalternative, \\holtxt{person\\_employed bob}, works, but would be\nprinted using the first syntax, with the full-stop.\\index{record types!field selection notation}\n\nThe functional update functions are given the names\n\\mbox{``$\\langle$\\textsl{record-type}$\\rangle$\\texttt{\\_}$\\langle$\\textsl{field}$\\rangle$\\texttt{\\_fupd}''}\nfor each field in\nthe type.  They take two arguments, a function and a record to be\nupdated.  The function parameter is an endomorphism on the field type,\nso that the resulting record is the same as the original, except that\nthe specified field has had the given function applied to it to\ngenerate the new value for that field.  They can be written with the\nkeyword \\texttt{with} and the \\texttt{updated\\_by} operator.  Thus\n%\n\\begin{hol}\n\\begin{verbatim}\n  bob with employed updated_by $~\n\\end{verbatim}\n\\end{hol}\\noindent\n%\nis a record value identical to the \\texttt{bob} except that the\nboolean value in the \\texttt{employed} field has been inverted.\n\nAdditionally, there is syntactic sugar available to let one write a\nrecord with one of its fields replaced by a specific value.  This is\ndone by using the \\holtxt{:=} operator instead of\n\\holtxt{updated\\_by}:\n%\n\\begin{hol}\n\\begin{verbatim}\n  bob with employed := T\n\\end{verbatim}\n\\end{hol}\n%\nThis form is translated at parse-time to be a use of the corresponding\nfunctional update, along with a use of the \\textsf{K}-combinator from\nthe \\texttt{combin} theory.  Thus, the above example  is really\n%\n\\begin{hol}\n\\begin{verbatim}\n  bob with employed updated_by (K T)\n\\end{verbatim}\n\\end{hol}\n%\nwhich is in turn a pretty form of\n%\n\\begin{hol}\n\\begin{verbatim}\n  person_employed_fupd (K T) bob\n\\end{verbatim}\n\\end{hol}\n%\nIf a chain of updates is desired, then multiple updates can be\nspecified inside \\holtxt{<|}-\\holtxt{|>} pairs, separated by\nsemi-colons, thus:\n%\n\\begin{hol}\n\\begin{verbatim}\n  bob with <| age := 10; name := \"Child labourer\" |>\n\\end{verbatim}\n\\end{hol}\n%\nBoth update forms (using \\texttt{updated\\_by} and \\texttt{:=}) can be\nused in a chain of updates.\n\n\\paragraph{Specifying record literals}\n\nThe parser accepts lists of field specifications between\n\\holtxt{<|}-\\holtxt{|>} pairs without the \\holtxt{with} keyword.\nThese translate to sequences of updates of an arbitrary value\n(literally, the HOL value \\holtxt{ARB}), and are treated as literals.\nThus,\n%\n\\begin{hol}\n\\begin{verbatim}\n  <| age := 21; employed := F; name := \"Layabout\" |>\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph{Using the theorems produced by record definition}\n\nAs well as defining the type and the functions described above, record\ntype definition also proves a suite of useful theorems.  These are all\nare saved (using {\\tt save\\_thm}) in the current segment.  %\n%\n\\index{TypeBase@\\ml{TypeBase}}\n%\nSome are also added to the \\ml{TypeBase}'s simplifications for the\ntype, so they will be automatically applied when simplifying with the\n\\ml{srw\\_ss()} simpset, or with the tactics \\ml{RW\\_TAC} and\n\\ml{SRW\\_TAC} (see Section~\\ref{sec:simpLib}).\n\nAll of the theorems are saved under names that begin with the name of\nthe type.  The list below is a sample of the theorems proved.  The\nidentifying strings are suffixes appended to the name of the type in\norder to generate the final name of the theorem.\n\n\\newcommand{\\rewruse}{This theorem is installed in the \\texttt{TypeBase}.}\n\\newcommand{\\field}[1]{\\mbox{\\it field}_{#1}}\n\\newcommand{\\update}{\\mbox{\\tt\\_fupd}}\n\n\\begin{description}\n\\item[\\texttt{\\_accessors}] The definitions of the accessor functions.\n  \\rewruse\n\\item[\\texttt{\\_fn\\_updates}] The definitions of the functional update\n  functions.\n\\item[\\texttt{\\_accfupds}] A theorem that states simpler forms for\n  expressions that are of the form $\\field{i}\\, (\\field{j}\\update\\;f\\; r)$.  If\n  $i = j$, then the RHS is $f (\\field{i}(r))$, if not, it is $(\\field{i}\\;r)$.\n  \\rewruse\n\\item[\\texttt{\\_component\\_equality}] A theorem stating that $(r_1 =\n  r_2) \\equiv \\bigwedge_i (\\field{i}(r_1) = \\field{i}(r_2))$.\n\\item[\\texttt{\\_fupdfupds}] A thereom stating that $\\field{i}\\update\n  \\;f \\,(\\field{i}\\update \\;g\\;r) = \\field{i}\\update\\;(f \\circ g)\\;r$.\n  \\rewruse\n\\item[\\texttt{\\_fupdcanon}] A theorem that states commutativity results\n  for all possible pairs of field updates.  They are constructed in\n  such a way that if used as rewrites, they will canonicalise\n  sequences of updates. Thus, for all $i < j$, \\[\n  \\field{j}\\update\\;f\\;(\\field{i}\\update\\;g\\;r) =\n  \\field{i}\\update\\;g\\;(\\field{j}\\update\\;f\\;r)\n  \\] is generated.\n \\rewruse\n\\end{description}\n\n\\paragraph{Big records} The size of certain theorems proved in the\nrecord type package increases as the square of the number of fields in\nthe record.  (In particular, the update canonicalisation and\n\\texttt{acc\\_fupd} theorems have this property.) To avoid inefficiency\nwith big records, the implementation of record types uses a more\nefficient underlying representation when the number of fields grows\ntoo large.  The exact point at which this optimisation is applied is\ncontrolled by the reference variable\n\\texttt{Datatype.big\\_record\\_size}.  This value is initialised to 20,\nbut users can change it as they choose.\n\nUnfortunately, the big record representation has the drawback that\nevery update and accessor function has two forms: different terms that\nare printed the same.  One form is a simple constant, and is the form\nproduced when a term is parsed.  The other is more complicated, but\nallows for the use of smaller theorems when record values are\nsimplified.  Therefore, it is recommended that new, user-proved\ntheorems that mention big records' fields or field updates be passed\nthrough a phase of simplification (\\texttt{SIMP\\_RULE}), applying the\n\\texttt{TypeBase}'s rewrites, before they are saved.\n\nThe pretty-printing of big records can be controlled with the\n\\texttt{pp\\_bigrecs} trace-flag.\n\\index{Datatype@\\ml{Datatype}|)}\n\n\n\\section{Quotient Types}\\label{quotients}\n\\index{type definitions, in HOL logic@type definitions, in \\HOL{} logic!quotients|(}\n\\index{quotient types, definition of}\n\n\\HOL{} provides a library for defining new types which are quotients\nof existing types, with respect to partial equivalence relations.\nThis library is described in {\\it ``Higher Order Quotients in Higher\nOrder Logic''} [HOQ], from which the following description is taken.\n\nThe quotient library is accessed by opening {\\tt quotientLib},\nwhich makes all its tools and theorems accessable.\n\nThe definition of new types corresponding to the quotients of\nexisting types by equivalence relations is called ``lifting''\nthe types from a lower, more representational level to a higher,\nmore abstract level.  Both levels describe similar objects, but\nsome details which are apparent at the lower level are no longer\nvisible at the higher level.  The logic is simplified.\n\nSimply forming a new type does not complete the quotient operation.\nRather, one wishes to recreate the\n%significant parts of the\npre-existing logical environment at the new,\nhigher, and more abstract level.  This includes not only the new\ntypes, but also new versions of the constants that form and\nmanipulate values of those types, and also new versions of the\ntheorems that describe properties of those constants.  All of these\n%must be recreated at the higher level, in order to\nform a logical layer, above which all the lower representational details\nmay be safely and forever forgotten.\n\nThis can be done in a single call of the\nmain tool of this package.\n\n\\begin{hol}\n\\begin{verbatim}\ndefine_quotient_types :\n        {types: {name: string,\n                 equiv: thm} list,\n         defs: {def_name: string,\n                fname: string,\n                func: Term.term,\n                fixity: Parse.fixity} list,\n         tyop_equivs : thm list,\n         tyop_quotients : thm list,\n         tyop_simps : thm list,\n         respects : thm list,\n         poly_preserves : thm list,\n         poly_respects : thm list,\n         old_thms : thm list} ->\n        thm list\n\\end{verbatim}\n\\end{hol}\n{\\tt define\\_quotient\\_types} takes a single argument which is a\nrecord with the following fields.\n\n{\\it types\\/} is a list of records, each of which contains two fields:\n{\\it name}, which is the name of a new quotient type to be created, and\n{\\it equiv}, which is\neither 1)\na theorem that a binary relation {\\it R\\/}\nis an equivalence relation\n(see [HOQ] \\S 4)\nof the form\n$$\n\\mbox{\\tt |-}\\\n\\forall x\\ y.\\ R\\ x\\ y \\ \\Leftrightarrow \\\n                (R\\ x = R\\ y),\n$$\nor 2)\na theorem that {\\it R\\/} is a nonempty partial equivalence relation,\n(see [HOQ] \\S 5)\nof the form\n$$\n\\mbox{\\tt |-}\\\n(\\exists x.\\ R\\ x\\ x) \\ \\wedge \\\n(\\forall x\\ y.\\ R\\ x\\ y \\ \\Leftrightarrow \\\n                R\\ x\\ x \\wedge R\\ y\\ y \\wedge (R\\ x = R\\ y)).\n$$\nThe process of forming the new quotient types is described\nin [HOQ] \\S 8.\n\n{\\it defs\\/} is a list of records specifying the constants to be lifted.\nEach record contains the following four fields:\n{\\it func\\/} is an HOL term, which must be a single constant, which is the\nconstant to be lifted.\n{\\it fname\\/} is the name of the new constant being defined as the lifted version of {\\it func}.\n{\\it fixity\\/} is the HOL fixity of the new constant being created,\nas specified in the HOL structure {\\tt Parse}.\n{\\it def\\_name} is the name under which the new constant definition is to\nbe stored in the current theory.\nThe\nprocess of defining lifted constants\nis described in [HOQ] \\S 9.\n\n{\\it tyop\\_equivs\\/} is a list of conditional equivalence theorems\nfor type operators (see [HOQ] \\S 4.1).\nThese are used for bringing into regular form\ntheorems on new type operators, so that they can be lifted\n(see [HOQ] \\S 11 and \\S 12).\n\n{\\it tyop\\_quotients\\/} is a list of conditional quotient theorems\nfor type operators (see [HOQ] \\S 5.2).\nThese are used for lifting both constants and theorems.\n\n{\\it tyop\\_simps\\/} is a list of theorems used to simplify type operator\nrelations and map functions, e.g.,\nfor pairs,\n{\\tt |- (\\$= \\#\\#\\# \\$=) = \\$=} and\n{\\tt |- (I \\#\\# I) = I}.\n\nThe rest of the arguments refer to the general process of lifting theorems\nover the quotients being defined,\nas described in [HOQ] \\S 10.\n\n{\\it respects\\/} is a list of theorems about the respectfulness of the\nconstants being lifted.\nThese theorems are described in\n[HOQ] \\S 10.1.\n\n{\\it poly\\_preserves\\/} is a list of theorems about the preservation of\npolymorphic constants in the HOL logic\nacross a quotient operation.\n%as if they were definitions across the quotient operation.\nIn other words, they state that any quotient operation preserves these\nconstants as a homomorphism.\nThese theorems are described in\n[HOQ] \\S 10.2.\n\n{\\it poly\\_respects\\/} is a list of theorems showing the respectfulness\nof the polymorphic constants mentioned in {\\it poly\\_preserves}.\nThese are\ndescribed in\n[HOQ] \\S 10.3.\n\n{\\it old\\_thms\\/} is a list of theorems concerning the lower, representative\ntypes and contants, which are to be automatically lifted and proved at the\nhigher, more abstract quotient level.\nThese theorems are described in\n[HOQ] \\S 10.4.\n\n{\\tt define\\_quotient\\_types} returns a list of theorems, which are the\nlifted versions of the {\\it old\\_thms}.\n\nA similar function,\n{\\tt define\\_quotient\\_types\\_rule}, takes a single argument which is a\nrecord with the same fields as above except for {\\it old\\_thms},\nand returns an SML function of type {\\tt thm -> thm}.\nThis result, typically called {\\tt LIFT\\_RULE},\nis then used to lift the old theorems individually, one at a time.\n\nFor backwards compatibility with\nthe excellent quotients package\n{\\tt EquivType}\ncreated by\nJohn Harrison\n%to whom much credit is due, and\n(which provided much inspiration),\nthe following function is also provided:\n\n\\begin{hol}\n\\begin{verbatim}\ndefine_equivalence_type :\n        {name: string,\n         equiv: thm,\n         defs: {def_name: string,\n                fname: string,\n                func: Term.term,\n                fixity: Parse.fixity} list,\n         welldefs : thm list,\n         old_thms : thm list} ->\n        thm list\n\\end{verbatim}\n\\end{hol}\n\\noindent\nThis function is limited to a single quotient type, but may be\nmore convenient when the generality of {\\tt define\\_quotient\\_types}\nis not needed.\nThis function is defined in terms of {\\tt define\\_quotient\\_types} as\n\n\\begin{hol}\n\\begin{verbatim}\nfun define_equivalence_type {name,equiv,defs,welldefs,old_thms} =\n    define_quotient_types\n     {types=[{name=name, equiv=equiv}], defs=defs, tyop_equivs=[],\n      tyop_quotients=[FUN_QUOTIENT],\n      tyop_simps=[FUN_REL_EQ,FUN_MAP_I], respects=welldefs,\n      poly_preserves=[FORALL_PRS,EXISTS_PRS],\n      poly_respects=[RES_FORALL_RSP,RES_EXISTS_RSP],\n      old_thms=old_thms};\n\\end{verbatim}\n\\end{hol}\n\\index{type definitions, in HOL logic@type definitions, in \\HOL{} logic!quotients|)}\n\n\n\\section{Case Expressions}\\label{CaseExp}\n\\index{case expressions|(}\n\nWithin the HOL{} logic, case expressions provide a very compact and convenient notation for multi-way selection among the values of several expressions.\nThis is modeled on the case constructs in functional programming languages such as Standard ML.\nSuch case expressions can simplify the expression of complicated branches between different cases or combinations of cases.\nThe basic syntax (where the non-terminal $\\mathit{term}$ stands for any \\HOL{} term) is\n\\begin{eqnarray*}\n\\mathit{term} & ::= & \\texttt{case}\\;\\mathit{term}\\;\\texttt{of}\\;\\mathit{cases}\\\\\n\\mathit{cases} &::= & \\mathit{case}_1 \\;\\mathit{morecases}\\\\\n\\mathit{case}_1 & ::= & \\texttt{\\bfseries |}\\;\\mathit{case} \\;\\;\\;|\\;\\;\\;\\mathit{case}\\\\\n\\mathit{morecases} & ::= & \\varepsilon\\;\\;\\;|\\;\\;\\;\\texttt{|}\\;\\mathit{case}\\;\\mathit{morecases}\\\\\n\\mathit{case} & ::= & \\mathit{term} \\;\\texttt{=>}\\; \\mathit{term}\n\\end{eqnarray*}\nThe choice in the rule for the first case ($\\mathit{case}_1$) allows the use of more uniform syntax, where every case is preceded by a vertical bar.\nOmitting the bar, which is what the pretty-printer does when the syntax is printed, conforms with the syntax used by SML.\n\nBased on the value of a test expression, a list of pattern expressions\nare considered in sequence to see if they match the test expression.\nThe first pattern which successfully matches causes its associated result\nexpression to be evaluated and its value yielded as the value of the\nentire case expression.  For example,\n%\n\\begin{hol}\n\\begin{verbatim}\n  case n of\n     0 => \"none\"\n   | 1 => \"one\"\n   | 2 => \"two\"\n   | _ => \"many\"\n\\end{verbatim}\n\\end{hol}\n%\n\nThis could have been expressed using several ``if--then--else'' constructs,\nbut the case expression is much more compact and clean, with the\nselection between various choices made clearly evident.\n\nIn addition to literals as patterns, as above, patterns may be\nconstructor expressions.  Many standard HOL{} types have constructors,\nincluding \\ml{num}, \\ml{list}, and \\ml{option}.\n%\n\\begin{hol}\n\\begin{verbatim}\n  case spouse(employee) of\n   | NONE   => \"single\"\n   | SOME s => \"married to \" ++ name_of s\n\\end{verbatim}\n\\end{hol}\n(This example uses the optional bar in front of the first case.)\n\nHOL{} supports a rich structure of case expressions using a single\nnotation.  The format is related to that of definitions of recursive\nfunctions, as described in Section~\\ref{TFL}.  In addition, case\nexpressions may contain literals as patterns, either singly or as\nelements of deeply nested patterns.\n\nCase expressions may test values of any type.  If the test expression\nis a type with constructors, then the patterns may be expressed\nusing the constructors applied to arguments, as for example \\ml{SOME s}\nin the example above.  A free variable within the constructor pattern,\nfor example \\ml{s} in the pattern \\ml{SOME s}, becomes bound to the\ncorresponding value within the value of the test expression, and\ncan be used within the associated result expression for that pattern.\n\nIn addition to the constructors of standard types in HOL{},\nconstructor patterns may also be used for types created by use of the\ndatatype definition facility described in Section~\\ref{sec:datatype},\nincluding user-defined types.\n\nWhether or not the test expression is a type with constructors,\nthe patterns may be expressed using the appropriate literals of that type,\nif any such literals exist.\nA complex pattern may contain either or both of literals and constructor\npatterns nested within it.\nHowever, literals and constructors may not be mixed as alternatives of\neach other within the same case expression,\nexcept insofar as a particular pattern may be both a literal\nand also a (0-ary) constructor of its type, as for example \\ml{0} (zero)\nis both a literal and a constructor of the type \\ml{num}.\nHere is an example of this kind of improper mixture.\n%\n\\begin{hol}\n\\begin{verbatim}\n  case n of\n     0 => \"none\"\n   | 1 => \"one\"\n   | 2 => \"two\"\n   | SUC m => \"many\"\n\\end{verbatim}\n\\end{hol}\n%\nIn this pattern, the constructor pattern \\ml{SUC m} is given as\nan alternative to the literal patterns \\ml{1} and \\ml{2}.\nThis makes this attempted case expression invalid.\nDeleting either group of rows would resolve the conflict,\nand make the expression valid.\nNote that the pattern \\ml{0} is acceptable to either group.\n\nPatterns can be nested as well, as shown in the next example, where\nthe function \\ml{parents} returns a pair containing the person's father\nand/or mother, where each is represented by \\ml{NONE} if deceased.\n%\n\\begin{hol}\n\\begin{verbatim}\n  case parents(john) of\n     (NONE,NONE) => \"orphan\"\n   | _ => \"not an orphan\"\n\\end{verbatim}\n\\end{hol}\n%\nThis shows the nesting of option patterns within a pair pattern,\nand also the use of a wildcard \\ml{\\_} to match the cases not given.\n\nIf the set of patterns is sparse, there may be several new rows generated\nautomatically to fill it out, and possibly some new variables or the\n\\ml{ARB} constant to properly represent the case expression.\n%\n\\begin{hol}\n\\begin{verbatim}\n- ``case a of\n      (1, y, z) => y + z\n    | (x, 2, z) => x - z\n    | (x, y, 3) => x * y``;\n> val it =\n    ``case a of\n        (1,2,3) => 2 + 3\n      | (1,2,z) => 2 + z\n      | (1,y,3) => y + 3\n      | (1,y,z) => y + z\n      | (x,2,3) => x - 3\n      | (x,2,z') => x - z'\n      | (x,y',3) => x * y'\n      | (x,y',z') => ARB`` : term\n\\end{verbatim}\n\\end{hol}\n\nThis is just a brief description of some of the\nexpressive capabilities of the case expression with patterns.\nMany more examples of patterns are provided in Section~\\ref{TFL}\non the definition of recursive functions.\n\n\\index{case expressions|)}\n\n\n\\section{Recursive Functions}\\label{TFL}\n\nHOL{} provides a function definition mechanism based on the\nwellfounded recursion theorem proved in \\theoryimp{relationTheory},\ndiscussed in Section~\\ref{relation}.  \\ml{Define} takes a high-level,\npossibly recursive, specification of a function, and attempts to\ndefine the function in the logic. \\ml{Define} may be used to define\nabbreviations, recursive functions, and mutually recursive\nfunctions. An induction theorem may be generated as a by-product of\n\\ml{Define}'s activity. This induction theorem follows the recursion\nstructure of the function, and may be useful when proving properties\nof the function. \\ml{Define} is not always successful in attempting\nto make the specified definition, usually because an automatic\ntermination proof fails; in that case, another entrypoint, \\ml{Hol\\_defn},\nwhich defers the termination proof to the user, can be used.\nThe technology underlying \\ml{Define} and \\ml{Hol\\_defn} is explained\nin detail in Slind~\\cite{slind-thesis}.\n\n\n\\index{Define@\\ml{Define}}\n\n In particular, \\ml{Define} takes as input a quotation representing a\nconjunction of equations. The specified function(s) may be phrased\nusing ML-style pattern-matching. A call\n\\ml{Define `}\\textit{spec}\\ml{`} should conform with the grammar in Table\n\\ref{define:syntax}.\n\\begin{table}[htbp]\n\\begin{center}\n$\n\\begin{array}{|rll|}\n\\hline\n\\mathit{spec} & ::= &  \\mathit{eqn} \\\\\n              & \\mid  & (\\mathit{eqn}) \\land \\mathit{spec} \\\\\n  & & \\\\\n\\mathit{eqn} & ::= & \\mathit{alphanumeric}\\ \\mathit{pat} \\ldots \\mathit{pat} = \\mathit{term} \\\\\n  & & \\\\\n  & & \\\\\n\\mathit{pat} & ::= & \\mathit{variable} \\\\\n    & \\mid   & \\mathit{wildcard} \\\\\n    & \\mid   & \\mathit{cname} \\\\\n    & \\mid   & (\\mathit{cname}_n\\ \\mathit{pat}_1 \\ldots \\mathit{pat}_n) \\\\\n  & & \\\\\n\\mathit{cname} & ::= & \\mathit{alphanumeric} \\mid \\mathit{symbolic} \\\\\n  & & \\\\\n\\mathit{wildcard} & ::=  & \\_\\!\\_ \\\\\n                  & \\mid & \\_\\!\\_ \\mathit{wildcard} \\\\\n  & & \\\\\n\\hline\n\\end{array}\n$\n\\caption{Syntax of Function Declaration}\\label{define:syntax}\n\\end{center}\n\\end{table}\n\n\\paragraph{Pattern Expansion}\nIn general, \\ml{Define} attempts to derive exactly the specified\nconjunction of equations. However, the rich syntax of patterns allows\nsome ambiguity. For example, the input\n%\n\\begin{hol}\n\\begin{verbatim}\n  Define `(f 0 _ = 1)\n    /\\    (f _ 0 = 2)`\n\\end{verbatim}\n\\end{hol}\n%\nis ambiguous at \\holtxt{f 0 0}: should the result be \\holtxt{1} or\n\\holtxt{2}?  This ambiguity is dealt with in the usual way for compilers and\ninterpreters for functional languages: namely, the conjunction of\nequations is treated as being applied left-conjunct first, followed\nby processing the right conjunct. Therefore, in the example above, the\nvalue of \\holtxt{f 0 0} is \\holtxt{1}. In the implementation,\nambiguities arising from such overlapping patterns are systematically\ntranslated away in a pre-processing step.\n\n Another case of ambiguity in patterns is shown above: the specification\nis incomplete since it does not tell how \\holtxt{f} should behave when\napplied to two non-zero arguments: e.g., \\holtxt{f (SUC m) (SUC n)}. In the\nimplementation, such missing clauses are filled in, and have the value\n\\holtxt{ARB}. This `pattern-completion` step is a way of turning descriptions\nof partial functions into total functions suitable for HOL. However,\nsince the user has not completely specified the function, the system\ntakes that as a hint that the user is not interested in using the\nfunction at the missing-but-filled-in clauses, and so such clauses are\ndropped from the final theorem.\n\nIn summary, \\ml{Define} will derive the unambiguous and complete\nequations\n%\n\\begin{hol}\n\\begin{verbatim}\n  |- (f 0 (SUC v4) = 1) /\\\n     (f 0 0 = 1) /\\\n     (f (SUC v2) 0 = 2)\n     (f (SUC v2) (SUC v4) = ARB)\n\\end{verbatim}\n\\end{hol}\n%\nfrom the above ambiguous and incomplete equations. The odd-looking\nvariable names are due to the pre-processing steps described above. The\nabove result is only an intermediate value: in the final result returned\nby \\ml{Define}, the last equation is droppped since it was not\nspecified by the original input.\n\\begin{hol}\n\\begin{verbatim}\n  |- (f 0 (SUC v4) = 1) /\\\n     (f 0 0 = 1) /\\\n     (f (SUC v2) 0 = 2)\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph{Termination}\n\nWhen processing the specification of a recursive function, \\ml{Define}\nmust perform a termination proof. It automatically constructs\ntermination conditions for the function, and invokes a termination\nprover in an attempt to prove the termination conditions.  If the\nfunction is primitive recursive, in the sense that it exactly follows\nthe recursion pattern of a previously declared HOL datatype, then this\nproof always succeeds, and \\ml{Define} stores the derived equations in\nthe current theory segment.\nOtherwise, the function is not an\ninstance of primitive recursion, and the termination prover may\nsucceed or fail. If the termination proof fails, then \\ml{Define} fails.\nIf it succeeds, then \\ml{Define} stores the specified equations in the\ncurrent theory segment. An induction theorem customized for the defined\nfunction is also stored in the current segment. Note, however, that an\ninduction theorem is not stored for primitive recursive functions, since\nthat theorem would be identical to the induction theorem resulting from\nthe declaration of the datatype.\n\n\n\\paragraph{Storing definitions in the theory segment}\n\n \\ml{Define} automatically generates names with which to store the\ndefinition and, (if it exists) the associated induction theorem, in\nthe current theory. The name for storing the definition is built by\nconcatenating the name of the function with the value of the reference\nvariable \\ml{Defn.def\\_suffix}. The name for storing the induction theorem\nis built by concatenating the name of the function with the value of\nthe reference variable \\ml{Defn.ind\\_suffix}. For mutually recursive\nfunctions, where there is a choice of names, the name of the function\nin the first clause is taken.\n\n Since the names used to store elements in the current theory segment\nare transformed into ML bindings after the theory is exported, it is\nrequired that every invocation of \\ml{Define} generate names that are\nvalid ML identifiers. For this reason, \\ml{Define} requires\nalphanumeric function names. If one wishes to define symbolic\nidentifiers, the ML function \\ml{xDefine} should be used.\n\n\\index{xDefine@\\ml{xDefine}}\n\\begin{hol}\n\\begin{verbatim}\n  xDefine : string -> term quotation -> thm\n\\end{verbatim}\n\\end{hol}\nThe \\ml{xDefine} function is identical to\n\\ml{Define} except that it takes an explicit name to use when\nstoring the definition in the current theory.\n\n\\subsection{Function definition examples}\n We will give a number of examples that display the range of functions\nthat may be defined with \\ml{Define}. First, we have a recursive function\nthat uses ``destructors'' in the recursive call.\n\n\\begin{hol}\n\\begin{verbatim}\n  Define\n    `fact x = if x = 0 then 1 else x * fact(x-1)`;\n\n  Equations stored under \"fact_def\".\n  Induction stored under \"fact_ind\".\n  > val it = |- fact x = (if x = 0 then 1 else x * fact (x - 1)) : thm\n\\end{verbatim}\n\\end{hol}\n%\nSince \\holtxt{fact} is not\nprimitive recursive, an induction theorem for \\holtxt{fact} is generated and\nstored in the current theory.\n%\n\\begin{hol}\n\\begin{verbatim}\n  - DB.fetch \"-\" \"fact_ind\";\n\n  > val it =\n     |- !P. (!x. (~(x = 0) ==> P (x - 1)) ==> P x) ==> !v. P v : thm\n\\end{verbatim}\n\\end{hol}\n\nNext we have a recursive function with relatively complex\npattern-matching. We omit to examine the generated induction\ntheorem.\n%\n\\begin{hol}\n\\begin{verbatim}\n  Define `(flatten  []           = [])\n     /\\   (flatten ([]::rst)     = flatten rst)\n     /\\   (flatten ((h::t)::rst) = h::flatten(t::rst))`;\n\n  Equations stored under \"flatten_def\".\n  Induction stored under \"flatten_ind\".\n\n  > val it =\n      |- (flatten [] = []) /\\\n         (flatten ([]::rst) = flatten rst) /\\\n         (flatten ((h::t)::rst) = h::flatten (t::rst)) : thm\n\\end{verbatim}\n\\end{hol}\n\nNext we define a curried recursive function, which uses\nwildcard expansion and pattern-matching pre-processing.\n%\n\\begin{hol}\n\\begin{verbatim}\n  Define `(min (SUC x) (SUC y) = min x y + 1)\n     /\\   (min  ____    ____   = 0)`;\n\n  Equations stored under \"min_def\".\n  Induction stored under \"min_ind\".\n\n  > val it =\n      |- (min (SUC x) (SUC y) = min x y + 1) /\\\n         (min (SUC v2) 0 = 0) /\\\n         (min 0 v1 = 0) : thm\n\\end{verbatim}\n\\end{hol}\n\n Next we make a primitive recursive definition. Note that no\ninduction theorem is generated in this case.\n%\n\\begin{hol}\n\\begin{verbatim}\n  Define `(filter P [] = [])\n    /\\    (filter P (h::t) = if P h then h::filter P t else filter P t)`;\n\n  Definition has been stored under \"filter_def\".\n\n  > val it =\n     |- (!P. filter P [] = []) /\\\n        !P h t. filter P (h::t) =\n                 (if P h then h::filter P t else filter P t) : thm\n\\end{verbatim}\n\\end{hol}\n\n\\ml{Define} may also be used to define mutually recursive functions.\nFor example, we can define a datatype of propositions and a function for\nputting a proposition into negation normal form as follows.\nFirst we define a datatype, named \\ml{prop}, of boolean formulas:\n%\n\\begin{hol}\n\\begin{verbatim}\n  Datatype\n    `prop = VAR 'a\n          | NOT prop\n          | AND prop prop\n          | OR  prop prop`;\n\\end{verbatim}\n\\end{hol}\n%\nThen two mutually recursive functions \\holtxt{nnfpos} and \\holtxt{nnfneg}\nare defined:\n%\n\\begin{hol}\n\\begin{verbatim}\n  Define\n     `(nnfpos (VAR x)   = VAR x)\n   /\\ (nnfpos (NOT p)   = nnfneg p)\n   /\\ (nnfpos (AND p q) = AND (nnfpos p) (nnfpos q))\n   /\\ (nnfpos (OR p q)  = OR  (nnfpos p) (nnfpos q))\n\n   /\\ (nnfneg (VAR x)   = NOT (VAR x))\n   /\\ (nnfneg (NOT p)   = nnfpos p)\n   /\\ (nnfneg (AND p q) = OR  (nnfneg p) (nnfneg q))\n   /\\ (nnfneg (OR p q)  = AND (nnfneg p) (nnfneg q))`\n\\end{verbatim}\n\\end{hol}\n%\nThe system makes the definition and returns the theorem\n%\n\\begin{hol}\n\\begin{verbatim}\n  |- (nnfpos (VAR x) = VAR x) /\\\n     (nnfpos (NOT p) = nnfneg p) /\\\n     (nnfpos (AND p q) = AND (nnfpos p) (nnfpos q)) /\\\n     (nnfpos (OR p q) = OR (nnfpos p) (nnfpos q)) /\\\n     (nnfneg (VAR x) = NOT (VAR x)) /\\\n     (nnfneg (NOT p) = nnfpos p) /\\\n     (nnfneg (AND p q) = OR (nnfneg p) (nnfneg q)) /\\\n     (nnfneg (OR p q) = AND (nnfneg p) (nnfneg q)) : thm\n\\end{verbatim}\n\\end{hol}\n\n\\ml{Define} may also be used to define non-recursive functions.\n%\n\\begin{hol}\n\\begin{verbatim}\n  Define\n    `f x (y,z) = (x + 1 = y DIV z)`;\n\\end{verbatim}\n\\end{hol}\n\n\\ml{Define} may also be used to define non-recursive functions\nwith complex pattern-matching. The pattern-matching pre-processing of\n{Define} can be convenient for this purpose, but can also generate a\nlarge number of equations. For example:\n%\n\\begin{hol}\n\\begin{verbatim}\n  Define\n    `(g (0,_,_,_,_) = 1) /\\\n     (g (_,0,_,_,_) = 2) /\\\n     (g (_,_,0,_,_) = 3) /\\\n     (g (_,_,_,0,_) = 4) /\\\n     (g (_,_,_,_,0) = 5)`\n\\end{verbatim}\n\\end{hol}\n%\nyields a definition with thirty-one clauses.\n\n\n\\subsection{When termination is not automatically proved}\n\nIf the termination proof for a prospective definition\nfails, the invocation of \\ml{Define} (or \\ml{xDefine}) fails. In such\nsituations, the \\ML{} function \\ml{Hol\\_defn} should be used.\n%\n\\index{Hol_defn@\\ml{Hol\\_defn}}\n\n\\begin{hol}\n\\begin{verbatim}\n  Hol_defn : string -> term quotation -> Defn.defn\n\\end{verbatim}\n\\end{hol}\n\n\\ml{Hol\\_defn} makes the requested definition, but defers the proof of\ntermination to the user. For setting up termination proofs, there are\nseveral useful entrypoints, namely\n\\begin{hol}\n\\begin{verbatim}\n  Defn.tgoal  : Defn.defn -> GoalstackPure.proofs\n  Defn.tprove : Defn.defn * tactic -> thm * thm\n\\end{verbatim}\n\\end{hol}\n\\ml{Defn.tgoal} is analogous to \\ml{set\\_goal} and \\ml{Defn.tprove} is\nanalogous to \\ml{prove}. Thus, \\ml{Defn.tgoal} is used to take the\nresult of \\ml{Hol\\_defn} and set up a goal for proving termination\nof the definition.\n\n\\paragraph{Example.} An invocation of {\\small\\verb+Define+} on\nthe following equations for Quicksort will currently fail, since the\ntermination proof is currently beyond the capabilities of the naive termination\nprover. Instead, we make an application of {\\small\\verb+Hol_defn+}:\n\n\\setcounter{sessioncount}{0}\n\\begin{session}\n\\begin{verbatim}\n val qsort_def =\n  Hol_defn \"qsort\"\n    `(qsort ord [] = []) /\\\n     (qsort ord (h::t) =\n         qsort ord (FILTER (\\x. ord x h) t)\n         ++ [h] ++\n         qsort ord (FILTER (\\x. ~(ord x h)) t))`\n\\end{verbatim}\n\\end{session}\nwhich returns the following value of type \\ml{defn}, but does not try\nto prove termination.\n\\begin{session}\n\\begin{verbatim}\n  HOL function definition (recursive)\n\n  Equation(s) :\n   [...] |- qsort ord [] = []\n   [...]\n  |- qsort ord (h::t) =\n     qsort ord (FILTER (\\x. ord x h) t) ++ [h] ++\n     qsort ord (FILTER (\\x. ~ord x h) t)\n\n  Induction :\n   [...]\n  |- !P.\n       (!ord. P ord []) /\\\n       (!ord h t.\n          P ord (FILTER (\\x. ~ord x h) t) /\\\n          P ord (FILTER (\\x. ord x h) t) ==>\n          P ord (h::t)) ==>\n       !v v1. P v v1\n\n  Termination conditions :\n    0. !t h ord. R (ord,FILTER (\\x. ~ord x h) t) (ord,h::t)\n    1. !t h ord. R (ord,FILTER (\\x. ord x h) t) (ord,h::t)\n    2. WF R\n\\end{verbatim}\n\\end{session}\n\nThe type \\ml{defn} has a prettyprinter installed for it: the above\noutput is typical, showing the components of a \\ml{defn} in an understandable\nformat. Although it is possible to directly work with elements of\ntype \\ml{defn}, it is more convenient to invoke\n\\ml{Defn.tgoal}, which sets up a termination proof in a goalstack.\n%\n\\begin{session}\n\\begin{verbatim}\n  Defn.tgoal qsort_def;\n\n  > val it =\n    Proof manager status: 1 proof.\n    1. Incomplete:\n         Initial goal:\n         ?R.\n           (!t h ord. R (ord,FILTER (\\x. ~ord x h) t) (ord,h::t)) /\\\n           (!t h ord. R (ord,FILTER (\\x. ord x h) t) (ord,h::t)) /\\ WF R\n\\end{verbatim}\n\\end{session}\n%\nThe goal is to find a wellfounded relation on the arguments to \\holtxt{qsort}\nand show that the arguments to \\holtxt{qsort} are in the relation.\nThe function \\ml{WF\\_REL\\_TAC} is almost invariably used at this point to\ninitiate the termination proof. Clearly, \\ml{qsort} terminates because the list\nargument gets shorter. Invoking \\ml{WF\\_REL\\_TAC} with the appropriate\nmeasure function results in two subgoals, both of which are easy to\nprove.\n\n\\begin{session}\n\\begin{verbatim}\n  - e (WF_REL_TAC `measure (LENGTH o SND)`);\n  OK..\n  2 subgoals:\n  > val it =\n     !t h ord. LENGTH (FILTER (\\x. ord x h) t) < LENGTH (h::t)\n\n     !t h ord. LENGTH (FILTER (\\x. ~ord x h) t) < LENGTH (h::t)\n\\end{verbatim}\n\\end{session}\n%\nExecution of \\ml{WF\\_REL\\_TAC} has automatically proved the\nwellfoundedness of the termination relation\n\\holtxt{measure (LENGTH o SND)}\nand the remainder of the goal has been simplified into a\npair of easy goals. Once both goals are proved, we can encapsulate\nthe termination proof with \\ml{tDefine}, which takes a quotation\n(representing desired recursion equations) and a tactic $t$,\ndefines the specified function, calculates the termination conditions,\nand applies $t$ to them. If the termination conditions are proved by\n$t$ then the recursion equations and induction theorem are stored\nin the current theory segment before the recursion equations are returned:\n\n\\begin{session}\n\\begin{verbatim}\n  - val qsort_def =  tDefine \"qsort\"\n     `(qsort ord [] = []) /\\\n      (qsort ord (h::t) =\n          qsort ord (FILTER (\\x. ord x h) t) ++ [h] ++\n          qsort ord (FILTER (\\x. ~(ord x h)) t))`\n     (WF_REL_TAC `measure (LENGTH o SND)` THEN ...);\n\n  > val qsort_def =\n      |- (qsort ord [] = []) /\\\n         (qsort ord (h::t) =\n            qsort ord (FILTER (\\x. ord x h) t) ++ [h] ++\n            qsort ord (FILTER (\\x. ~ord x h) t)) : thm\n\\end{verbatim}\n\\end{session}\n\nThe custom induction theorem for a function can be obtained by using \\holtxt{fetch},\nwhich returns named elements in the specified theory.\\footnote{In a call to \\texttt{fetch}, the\nfirst argument denotes a theory; the current theory may be specified by \\texttt{\"-\"}.}\n\\begin{session}\n\\begin{verbatim}\n  - fetch \"-\" \"qsort_ind\";\n  >  val qsort_ind =\n      |- !P.\n           (!ord. P ord []) /\\\n           (!ord h t.\n              P ord (FILTER (\\x. ~ord x h) t) /\\\n              P ord (FILTER (\\x. ord x h) t) ==> P ord (h::t))\n            ==>\n           !v v1. P v v1  : thm\n\\end{verbatim}\n\\end{session}\n\n\\noindent The induction theorem produced by \\holtxt{Define} and \\holtxt{tDefine} can\nbe applied by \\ml{recInduct}. See Section \\ref{sec:bossLib} for details.\n\n\\subsubsection{Techniques for proving termination}\n\nThere are two problems to deal with when trying to prove termination.\nFirst, one has to understand, intuitively and then mathematically,\nwhy the function under consideration terminates. Second, one must\nbe able to phrase this in \\HOL. In the following, we shall give a few\nexamples of how this is done.\n\nThere are a number of basic and advanced means of specifying wellfounded\nrelations. The most common starting point for dealing with termination\nproblems for recursive functions is to find some function, known as a a\n\\emph{measure} under which the arguments of a function call are larger\nthan the arguments to any recursive calls that result.\n\nFor a very simple starter example, consider the following definition\nof a function that computes the greatest common divisor of two\nnumbers:\n%\n\\setcounter{sessioncount}{0}\n\\begin{session}\n\\begin{verbatim}\n  - val gcd_defn =\n      Hol_defn \"gcd\"\n         `(gcd (0,n) = n) /\\\n          (gcd (m,n) = gcd (n MOD m, m))`;\n\n  - Defn.tgoal gcd_defn;\n\n  > val it =\n      Proof manager status: 1 proof.\n      1. Incomplete:\n           Initial goal:\n           ?R. WF R /\\ !v2 n. R (n MOD SUC v2,SUC v2) (SUC v2,n)\n\\end{verbatim}\n\\end{session}\n%\nThe invocation \\holtxt{gcd(m,n)} recurses in its first argument, and\nsince we know that \\holtxt{m} is not 0, it is the case that\n\\holtxt{n MOD m} is smaller than \\holtxt{m}. The way to phrase the\ntermination of \\holtxt{gcd} in HOL is to use a `measure` function\nto map from the domain of \\holtxt{gcd}---a pair of numbers---to a number.\nThe definition of {measure} in \\HOL{} is equivalent to\n%\n\\begin{hol}\n\\begin{verbatim}\n  |- measure f x y = (f x < f y).\n\\end{verbatim}\n\\end{hol}\n%\nNow we must pick out the argument position to measure and\ninvoke \\ml{WF\\_REL\\_TAC}:\n\\begin{session}\n\\begin{verbatim}\n  - e (WF_REL_TAC `measure FST`);\n  OK..\n  1 subgoal:\n  > val it =\n     !v2 n. n MOD SUC v2 < SUC v2\n\\end{verbatim}\n\\end{session}\n%\nThis goal is easy to prove with a few simple arithmetic facts.\n\n\\paragraph{Weighting Functions}\n\nSometimes one needs a measure function that is itself recursive.  For\nexample, consider a type of binary trees and a function that\nlinearizes trees. The algorithm works by rotating the tree until it\ngets a \\holtxt{Leaf} in the left branch, then it recurses into the right\nbranch. At the end of execution the tree has been linearized.\n\\setcounter{sessioncount}{0}\n\\begin{session}\n\\begin{verbatim}\n  - Datatype\n      `btree = Leaf | Brh btree btree`;\n\n  - val Unbal_defn =\n      Hol_defn \"Unbal\"\n        `(Unbal Leaf = Leaf)\n     /\\  (Unbal (Brh Leaf bt) = Brh Leaf (Unbal bt))\n     /\\  (Unbal (Brh (Brh bt1 bt2) bt) = Unbal (Brh bt1 (Brh bt2 bt)))`;\n\n  - Defn.tgoal Unbal_defn;\n\n  > val it =\n      Proof manager status: 1 proof.\n      1. Incomplete:\n         Initial goal:\n          ?R. WF R /\\\n              (!bt. R bt (Brh Leaf bt)) /\\\n              !bt bt2 bt1. R (Brh bt1 (Brh bt2 bt)) (Brh (Brh bt1 bt2) bt)\n\\end{verbatim}\n\\end{session}\n%\nSince the size of the tree is unchanged in the last clause in the\ndefinition of \\holtxt{Unbal}, a simple size measure will not work. Instead, we\ncan assign weights to nodes in the tree such that the recursive calls of\n\\holtxt{Unbal} decrease the total weight in every case. One such assignment is\n%\n\\begin{session}\n\\begin{verbatim}\n  Define\n   `(Weight (Leaf) = 0) /\\\n    (Weight (Brh x y) = (2 * Weight x) + (Weight y) + 1)`\n\\end{verbatim}\n\\end{session}\n%\nNow we can invoke \\ml{WF\\_REL\\_TAC}:\n%\n\\begin{session}\n\\begin{verbatim}\n  e (WF_REL_TAC `measure Weight`);\n  OK..\n\n  2 subgoals:\n  > val it =\n   !bt. Weight bt < Weight (Brh Leaf bt)\n\n   !bt bt2 bt1.\n      Weight (Brh bt1 (Brh bt2 bt)) < Weight (Brh (Brh bt1 bt2) bt)\n\\end{verbatim}\n\\end{session}\n%\nBoth of these goals are quite easy to prove.\n%\nThe technique of `weighting` nodes in a datatype in order to prove\ntermination also goes by the name of \\emph{polynomial interpretation}. It\nmust be admitted that finding the correct weighting for a termination\nproof is more an art than a science. Typically, one makes a guess and\nthen tries the termination proof to see if it works.\n\n\\paragraph{Lexicographic Combinations}\n\nOccasionally, there's a combination of factors that complicate the\ntermination argument. For example, the following specification\ndescribes a naive pattern matching algorithm on strings (represented\nas lists here). The function takes four arguments: the first, $p$,\nis the remainder of the pattern being matched. The second,\n$\\mathit{rst}$, is the remainder of the string being searched.  The third\nargument, $p_0$, holds the original pattern to be matched.\nThe fourth argument, $s$, is the string being searched.\n%\n\\setcounter{sessioncount}{0}\n\\begin{session}\n\\begin{verbatim}\n  val match_defn =\n    Hol_defn \"match\"\n      `(match [] __ __ __ = T)  /\\\n       (match __ [] __ __ = F)  /\\\n       (match (a::pp) (b::ss) p0 s =\n         if a=b then match pp ss p0 s\n           else\n         if NULL(s) then F\n           else\n         match p0 (TL s) p0 (TL s))`;\n\n  - val Match = Define `Match pat str = match pat str pat str`;\n\\end{verbatim}\n\\end{session}\n%\nThe first clause of the definition states that if $p$ becomes exhausted, then a match has\nbeen found;  the function returns \\holtxt{T}. The second clause represents the case\nwhere $s$ becomes exhausted but $p$ is not, in which case the function returns\n\\holtxt{F}. The remaining case is when there's more searching to do; the function\nchecks if the head of the pattern $p$ is the same as the head of\n$\\mathit{rst}$. If yes, then the search proceeds recursively, using the\ntail of $p$ and the tail of $\\mathit{rst}$. If no, that means that $p$ has\nfailed to match, so the algorithm advances one character ahead in\n$\\mathit{s}$ and starts matching from the beginning of $p_0$. If\n$\\mathit{s}$ is empty, however, then we return \\holtxt{F}. Note that\n$\\mathit{rst}$ and $s$ both represent the string being\nsearched: $\\mathit{rst}$ is a `local` version of $s$: we recurse into\n$\\mathit{rst}$  as long as there are matches with the pattern $p$. However,\nif the search eventually fails, then $s$, which `remembers` where the search\nstarted from, is used to restart the search.\n\nSo much for the behaviour of the function. Why does it terminate? There\nare two recursive calls. The first call reduces the size of $p$ and $\\mathit{rst}$, and\nleaves the other arguments unchanged. The second call can increase the\nsize of $p$ and $\\mathit{rst}$, but reduces the size $s$. This is a classic situation\nin which to use a  lexicographic ordering: some arguments to the function are reduced in\nsome recursive calls, and some others are reduced in other recursive calls.\nRecall that \\holtxt{LEX} is an infix operator, defined in \\ml{pairTheory} as follows:\n%\n\\begin{hol}\n\\begin{verbatim}\n  |- LEX R1 R2 = \\(x,y) (p,q). R1 x p \\/ ((x=p) /\\ R2 y q)\n\\end{verbatim}\n\\end{hol}\n%\nIn the second recursive call, the length of \\holtxt{s} is reduced, and in\nthe first it stays the same. This motivates having the length of the\n$s$ be the first component of the lexicographic\ncombination, and the length of $\\mathit{rst}$ as the second\ncomponent. Formally, we want to map from the four-tuple of\narguments into a lexicographic combination of relations.\nThis is enabled by \\holtxt{inv\\_image} from \\ml{relationTheory}:\n%\n\\begin{hol}\n\\begin{verbatim}\n   |- inv_image R f = \\x y. R (f x) (f y)\n\\end{verbatim}\n\\end{hol}\n%\nThe desired relation maps from the four-tuple of arguments into a pair\nof numbers $(m,n)$, where $m$ is the length of the fourth argument, and\n$n$ is the length of the second argument. These lengths are then\ncompared lexicographically with respect to less-than ($<$).\n\\begin{session}\n\\begin{verbatim}\n  Defn.tgoal match_defn;\n\n  - e (WF_REL_TAC `inv_image($< LEX $<) (\\(w,x,y,z). (LENGTH z,LENGTH x))`);\n  OK..\n  2 subgoals:\n  > val it =\n   !s ss a b.\n     (a=b) ==> LENGTH s < LENGTH s \\/ LENGTH ss < LENGTH (b::ss)\n\n   !ss s a b.\n     ~(a = b) /\\ ~NULL s ==>\n     LENGTH (TL s) < LENGTH s \\/\n     (LENGTH (TL s) = LENGTH s) /\\ LENGTH (TL s) < LENGTH (b::ss)\n\\end{verbatim}\n\\end{session}\n%\nThe first subgoal needs a case-split on \\holtxt{s} before it is proved by\nrewriting, and the second is also easy to prove by rewriting.\n\n\\subsubsection{How termination conditions are synthesized}\n\n\\index{congruence rules!in termination analysis|(}\nIt is occasionally important to understand, at least in part, how\n\\ml{Hol\\_defn} constructs termination constraints. In some cases, it is\neven necessary for users to influence this process in order to have correct\ntermination constraints extracted. The process is driven by so-called\n\\emph{congruence theorems} for particular \\HOL{} constants.\nFor example, consider the following recursive definition of factorial:\n%\n\\begin{hol}\n\\begin{verbatim}\n  fact n = if n=0 then 1 else n * fact (n-1)\n\\end{verbatim}\n\\end{hol}\n%\nIn the absence of knowledge of how the `if-then-else` construct\naffects the \\emph{context} of recursive calls, \\ml{Hol\\_defn} would\nextract the termination constraints:\n%\n\\begin{hol}\n\\begin{verbatim}\n  0. WF R\n  1. !n. R (n - 1) n\n\\end{verbatim}\n\\end{hol}\n%\nwhich are unprovable, because the \\emph{context} of the recursive call has not\nbeen taken account of. This example is in fact not a problem for HOL,\nsince the following congruence theorem is known to \\ml{Hol\\_defn}:\n%\n\\begin{hol}\n\\begin{verbatim}\n |- !b b' x x' y y'.\n      (b = b') /\\\n      (b' ==> (x = x')) /\\\n      (~b' ==> (y = y')) ==>\n       ((if b then x else y) = (if b' then x' else y'))\n\\end{verbatim}\n\\end{hol}\n%\nThis theorem is understood by \\ml{Hol\\_defn} as an ordered sequence\nof instructions to follow when the termination condition extractor\nhits an `if-then-else`. The theorem is read as follows: when an\ninstance `\\texttt{if} $B$ \\texttt{then} $X$ \\texttt{else} $Y$` is\nencountered while the extractor traverses the function definition,\ndo the following:\n\\begin{enumerate}\n\n\\item Traverse $B$ and extract termination conditions\n     $\\mathit{TCs}(B)$ from any recursive calls in it.\n     This returns a theorem $\\mathit{TCs}(B) \\vdash B = B'$.\n\n\\item Assume $B'$ and extract termination conditions from any\n  recursive calls in $X$. This returns a theorem\n  $\\mathit{TCs}(X) \\vdash X = X'$.\n\n\\item Assume $\\neg B'$ and extract termination conditions from any\n   recursive calls in $Y$. This returns a theorem\n   $\\mathit{TCs}(Y) \\vdash Y = Y'$.\n\n\\item  By equality reasoning with (1), (2), and (3), derive the theorem\n\\[\\mathit{TCs}(B) \\cup \\mathit{TCs}(X) \\cup \\mathit{TCs}(Y)\n  \\vdash\n  (\\mathtt{if}\\ B\\ \\mathtt{then}\\ X\\ \\mathtt{else}\\ Y) =\n  (\\mathtt{if}\\ B'\\ \\mathtt{then}\\ X'\\ \\mathtt{else}\\ Y')\n\\]\n\\item Replace \\texttt{if} $B$ \\texttt{then} $X$ \\texttt{else} $Y$ by\n\\texttt{if} $B'$ \\texttt{then} $X'$ \\texttt{else} $Y'$.\n\n\\end{enumerate}\n\n\nThe termination conditions are accumulated until the\nextraction process finishes, and appear as hypotheses in the final\nresult. Thus the extracted termination conditions for \\holtxt{fact} are\n%\n\\begin{hol}\n\\begin{verbatim}\n   0. WF R\n   1. !n. ~(n = 0) ==> R (n - 1) n\n\\end{verbatim}\n\\end{hol}\n%\nand are easy to prove. The notion of \\emph{context} of a recursive call\nis defined by  the set of congruence rules used in extracting termination\nconditions. This set can be obtained by invoking \\holtxt{DefnBase.read\\_congs},\nand manipulated by \\holtxt{DefnBase.add\\_cong},\n\\holtxt{DefnBase.drop\\_cong} and \\holtxt{DefnBase.export\\_cong}.\nThe `add' and `drop' functions only affect the current state of the congruence database; in contrast, the `export' function provides a way for theories to specify that a particular theorem should be added to the congruence database in all descendent theories.\n\\index{congruence rules!in termination analysis|)}\n\n\n\n\\paragraph{Higher Order Recursion and Congruence Rules}\n\nA `higher-order` recursion is one in which a higher-order function is\nused to apply the recursive function to arguments. In order for the\ncorrect termination conditions to be proved for such a recursion,\ncongruence rules for the higher order function must be known to the\ntermination condition extraction mechanism. Congruence rules for\ncommon higher-order functions, \\eg, \\holtxt{MAP}, \\holtxt{EVERY}, and\n\\holtxt{EXISTS} for lists, are already known to the\nmechanism. However, at times, one must manually prove and install a\ncongruence theorem for a new user-defined higher-order function.\n\nFor example, suppose we define a higher-order function \\holtxt{SIGMA} for\nsumming the results of a function in a list.\n%\n\\setcounter{sessioncount}{0}\n\\begin{session}\n\\begin{verbatim}\n  Define `(SIGMA f [] = 0) /\\\n          (SIGMA f (h::t) = f h + SIGMA f t)`;\n\\end{verbatim}\n\\end{session}\n%\nWe then use \\holtxt{SIGMA} in the definition of a function for\nsumming the results of a function in a arbitrarily\n(finitely) branching tree.\n%\n\\begin{session}\n\\begin{verbatim}\n  Datatype `ltree = Node 'a (ltree list)`;\n\n  Defn.Hol_defn\n    \"ltree_sigma\"\n    `ltree_sigma f (Node v tl) = f v + SIGMA (ltree_sigma f) tl`;\n\\end{verbatim}\n\\end{session}\n%\nIn this definition, \\holtxt{SIGMA} is applied to a partial application\n\\holtxt{(ltree\\_sigma f)} of the function being defined. Such a situation\nis called a \\emph{higher-order recursion}. Since the recursive call of\n\\holtxt{ltree\\_sigma} is not fully applied, special efforts have\nto be made to extract the correct termination conditions. Otherwise,\nthe following unhappy situation results:\n%\n\\begin{session}\n\\begin{verbatim}\n  HOL function definition (recursive)\n\n  Equation(s) :\n    [..] |- ltree_sigma f (Node v tl)\n              = f v + SIGMA (\\a. ltree_sigma f a) tl\n\n  Induction :\n    [..] |- !P. (!f v tl. (!a. P f a) ==> P f (Node v tl)) ==> !v v1. P v v1\n\n  Termination conditions :\n    0. WF R\n    1. !tl v f a. R (f,a) (f,Node v tl) : defn\n\\end{verbatim}\n\\end{session}\n%\n\\index{congruence rules!in termination analysis}\nThe termination conditions for \\holtxt{ltree\\_sigma} seem to\nrequire finding a wellfounded relation \\holtxt{R} such that the pair\n\\holtxt{(f,a)} is \\holtxt{R}-less than\n\\holtxt{(f, Node v tl)}. However, this is a hopeless task, since there is no\nrelation between \\holtxt{a} and \\holtxt{Node v tl}, besides the fact\nthat they are both \\holtxt{ltree}s. The termination condition extractor\nhas not performed properly, because it didn't know a congruence rule\nfor \\holtxt{SIGMA}. Such a congruence theorem is the following:\n%\n\\begin{hol}\n\\begin{verbatim}\n  SIGMA_CONG =\n   |- !l1 l2 f g.\n       (l1=l2) /\\ (!x. MEM x l2 ==> (f x = g x)) ==>\n       (SIGMA f l1 = SIGMA g l2)\n\\end{verbatim}\n\\end{hol}\n%\nOnce \\ml{Hol\\_defn} has been told about this theorem, via \\ml{DefnBase}'s \\ml{add\\_cong} or \\ml{export\\_cong} functions, the termination conditions extracted for the definition are now provable, since \\holtxt{a} is a proper subterm of \\holtxt{Node v tl}.\n%\n\\begin{session}\n\\begin{verbatim}\n  val _ = DefnBase.add_cong SIGMA_CONG;\n\n  Defn.Hol_defn\n    \"ltree_sigma\"\n    `ltree_sigma f (Node v tl) = f v + SIGMA (ltree_sigma f) tl`;\n\n  > val it =\n      HOL function definition (recursive)\n\n      Equation(s) :  ...  (* as before *)\n      Induction :    ...  (* as before *)\n\n      Termination conditions :\n        0. WF R\n        1. !v f tl a. MEM a tl ==> R (f,a) (f,Node v tl)\n\\end{verbatim}\n\\end{session}\n\n\\subsection{Recursion schemas}\n\nIn higher order logic, very general patterns of recursion, known as\n\\emph{recursion schemas} or sometimes \\emph{program schemas}, can be\ndefined. One example is the following:\n%\n\\[\n  \\konst{linRec} (x) =\n    \\itelse{d(x)}{e(x)}{f(\\konst{linRec}(g\\; x))}\n\\]\n%\nIn this specification, the variables $d$, $e$, $f$, and $g$ are\nfunctions, that, when instantiated in different ways, allow\n\\konst{linRec} to implement different recursive functions. In this,\n\\konst{linRec} is like many other higher order functions. However,\nnotice that if $d(x) = \\konst{F}$, $f(x) = x+1$, and\n$g(x) = x$, then the resulting instantiation of\n\\konst{linRec} could be used to obtain a contradiction:\n%\n\\[\n  \\konst{linRec} (x) = \\konst{linRec}(x) + 1\n\\]\n%\nThis is not, however, derivable in \\HOL{}, because recursion schemas\nare defined by instantiating the wellfounded recursion theorem, and\ntherefore certain abstract termination constraints arise that\nmust be satisfied before recursion equations can be used in an\nunfettered manner. The entrypoint for defining a schema is\n\\ml{TotalDefn.DefineSchema}. On the \\konst{linRec} example it\nbehaves as follows (note that the schematic variables should\nonly occur on the right-hand side of the definition when making\nthe definition of a schema):\n%\n\\setcounter{sessioncount}{0}\n\\begin{session}\n\\begin{verbatim}\n  - TotalDefn.DefineSchema\n      `linRec (x:'a) = if d(x) then e(x) else f(linRec(g x))`;\n\n  <<HOL message: Definition is schematic in the following variables:\n      \"d\", \"e\", \"f\", \"g\">>\n\n  Equations stored under \"linRec_def\".\n  Induction stored under \"linRec_ind\".\n  > val it =\n     [..]\n    |- linRec d e f g x = if d x then e x else f (linRec d e f g (g x))\n\\end{verbatim}\n\\end{session}\n%\nThe hypotheses of the returned theorem hold the abstract termination\nconstraints. A similarly constrained induction theorem is also\nstored in the current theory segment.\n%\n\\begin{session}\n\\begin{verbatim}\n  hyp it;\n  > val it = [``!x. ~d x ==> R (g x) x``, ``WF R``] : term list\n\\end{verbatim}\n\\end{session}\n%\nThese constraints are abstract, since they place termination requirements\non variables that have not yet been instantiated. Once instantiations\nfor the variables are found, then the constraints may be eliminated\nby finding a suitable wellfounded relation for \\holtxt{R} and then\nproving the other constraints.\n\n\\section{Inductive Relations}\n\\index{inductive relations|(}\n\n\\index{Hol_reln, defining inductive relations@\\ml{Hol\\_reln}, defining inductive relations}\n\\index{inductive relations!Hol_reln (ML function)@\\ml{Hol\\_reln} (ML function)}\nInductive definitions are made with the function \\ml{Hol\\_reln}, found\nin the \\ml{bossLib} structure, and the resulting definitions and\ntheorems are handled with functions defined in the library\n\\ml{IndDefLib}. The \\ml{Hol\\_reln} function takes a\nterm quotation as input and attempts to define the relations there\nspecified.  The input term quotation must parse to a term that\nconforms to the following grammar:\n\\newcommand{\\nonterm}[1]{\\ensuremath{\\langle\\mathit{#1}\\rangle}}\n\\begin{eqnarray*}\n   \\nonterm{inputFormat} &::=& \\nonterm{clause} \\;\\holtxt{/\\bk}\\; \\nonterm{inputFormat} \\;\\;|\\;\\; \\nonterm{clause}\\\\\n   \\nonterm{clause}       &::=& (\\holtxt{!}x_1 \\dots\n   x_n. \\;\\;\\nonterm{hypothesis} \\;\\holtxt{==>}\n   \\;\\nonterm{conclusion})\\\\\n   &|& (\\holtxt{!}x_1\\dots x_n.\\;\\;\\nonterm{conclusion})\\\\\n   \\nonterm{conclusion}   &::=& \\nonterm{con} \\;\\mathit{sv_1}\\; \\mathit{sv_2} \\dots\\\\\n   \\nonterm{hypothesis}   &::=& \\mbox{any term}\\\\\n   \\nonterm{con}          &::=& \\mbox{a new relation constant}\n\\end{eqnarray*}\nThe (optional) $\\mathit{sv}_i$ terms that appear after a constant name\nare so-called ``schematic variables''.  The same variables must always\nfollow all new constants throughout the definition.  These variables\nand the names of the constants-to-be must not be quantified over in\neach {\\nonterm{clause}}.  A {\\nonterm{clause}} should have no other\nfree variables.  Any that occur will be universally quantified as part\nof the process of definition, and a warning message emitted.\n(Universal quantifiers at the head of the clause can be used to bind\nfree variables, but it is also permissible to use existential\nquantification in the hypotheses.  If a clause has no free variables,\nit is permissible to have no universal quantification.)\n\nA successful invocation of \\ml{Hol\\_reln} returns three theorems\n$(\\mathit{rules},\\mathit{ind},\\mathit{cases})$. Each is also stored in\nthe current theory segment.\n\\begin{itemize}\n\\item $\\mathit{rules}$ is a conjunction of implications\nthat will be the same as the input term quotation; the theorem is\nsaved under the name \\ml{<stem>\\_rules}, where \\ml{<stem>} is the name of the\nfirst relation defined by the function.\n\\item $\\mathit{ind}$ is the induction principle for the relations,\nsaved under the name \\ml{<stem>\\_ind}.\n\\item $\\mathit{cases}$ is the so-called `cases' or `inversion' theorem\n  for the relations, saved under the name \\ml{<stem>\\_cases}. A cases\n  theorem is of the form\n%\n\\begin{verbatim}\n   (!a0 .. an.  R1 a0 .. an = <R1's first rule possibility> \\/\n                              <R1's second rule possibility> \\/ ...)\n                   /\\\n   (!a0 .. am.  R2 a0 .. am = <R2's first rule possibility> \\/\n                              <R2's second rule possibility> \\/ ...)\n                   /\\\n   ...\n\\end{verbatim}\n%\nand is used to decompose an element in the relation into the\npossible ways of obtaining it by the rules.\n\\end{itemize}\n\n\\index{xHol_reln, defining inductive relations@\\ml{xHol\\_reln}, defining inductive relations}\n\\index{inductive relations!xHol_reln (ML function)@\\ml{xHol\\_reln} (ML function)}\nIf the ``stem'' of the first constant defined in a set of clauses is such that resulting \\ML{} bindings in an exported theory file will result in illegal \\ML{}, then the \\ml{xHol\\_reln} function should be used.\nThe \\ml{xHol\\_reln} function is analogous to the \\ml{xDefine} function for defining recursive functions (see Section~\\ref{TFL}).\n\n\\paragraph{Strong Induction Principles}\nSo called ``strong'' versions of induction principles (in which instances of the relation being defined appear as extra hypotheses), are automatically proved when a definition is made with \\ml{Hol\\_reln}. The strong induction principle for a relation is used when the \\ml{Induct\\_on} tactic is used.\n\n\\paragraph{Adding Monotone Operators}\n\\index{inductive relations!monotone operators for}\nNew constants may occur recursively throughout rules' hypotheses, as\nlong as it can be shown that the rules remain monotone with respect to\nthe new constants.  \\ml{Hol\\_reln} automatically attempts to prove such\nmonotonicity results, using a set of theorems held in a reference\n\\ml{IndDefLib.the\\_monoset}.  Monotonicity theorems must be of the form\n\\[\n\\mathit{cond}_1 \\land \\cdots \\land \\mathit{cond}_m \\Rightarrow\n(\\mathit{Op}\\;\\mathit{arg}_1 \\dots \\mathit{arg}_n \\Rightarrow\n\\mathit{Op}\\;\\mathit{arg}'_1 \\dots \\mathit{arg}'_n)\n\\]\nwhere each $\\mathit{arg}$ and $\\mathit{arg}'$ term must be a variable,\nand where there must be as many $\\mathit{cond}_i$ terms as there are\narguments to $\\mathit{Op}$ that vary.  Each $\\mathit{cond}_i$ must be\nof the form \\[ \\forall \\vec{v}. \\;\\mathit{arg}\\;\\vec{v} \\Rightarrow\n\\mathit{arg}'\\;\\vec{v}\n\\]\nwhere the vector of variables $\\vec{v}$ may be empty, and where the\n$\\mathit{arg}$ and $\\mathit{arg}'$ may actually be reversed (as in the\nrule for negation).\n\nFor example, the monotonicity rule for conjunction is\n\\[\n(P \\Rightarrow P') \\land (Q \\Rightarrow Q') \\Rightarrow (P \\land Q\n\\Rightarrow P' \\land Q')\n\\]\nThe monotonicity rule for the \\holtxt{EVERY} operator in the theory of\nlists (see Section~\\ref{sec:list}), is\n\\[\n(\\forall x. \\;P(x) \\Rightarrow Q(x)) \\Rightarrow\n(\\holtxt{EVERY}\\;P\\;\\ell \\Rightarrow \\holtxt{EVERY}\\;Q\\;\\ell)\n\\]\nWith a monotonicity result available for an operator such as\n\\holtxt{EVERY}, it is then possible to write inductive definitions\nwhere hypotheses include mention of the new relation as arguments to\nthe given operators.\n\n\\index{export_mono (ML function)@\\ml{export\\_mono} (\\ML{} function)}\nMonotonicity results that the user derives may be stored in the global\n\\ml{the\\_monoset} variable by using the \\ml{export\\_mono} function.\nThis function takes a string naming a theorem in the current theory\nsegment, and adds that theorem to the monotonicity theorems\nimmediately, and in such a way that this situation will also obtain when\nthe current theory is subsequently reloaded.\n\n\\paragraph{Examples}\n\nA simple example of defining two mutually recursive relations is\nthe following:\n%\n\\setcounter{sessioncount}{0}\n\\begin{session}\n\\begin{verbatim}\n  Hol_reln\n    `EVEN 0 /\\\n     (!n. ODD n ==> EVEN (n + 1)) /\\\n     (!n. EVEN n ==> ODD (n + 1))`;\n\\end{verbatim}\n\\end{session}\n%\nThe result is three theorems\n%\n\\begin{session}\n\\begin{verbatim}\n  > val it =\n    (|- EVEN 0 /\\\n        (!n. ODD n ==> EVEN (n + 1)) /\\\n        (!n. EVEN n ==> ODD (n + 1)),\n\n     |- !EVEN' ODD'.\n           EVEN' 0 /\\\n           (!n. ODD' n ==> EVEN' (n + 1)) /\\\n           (!n. EVEN' n ==> ODD' (n + 1))\n           ==>\n           (!a0. EVEN a0 ==> EVEN' a0) /\\\n           (!a1. ODD a1 ==> ODD' a1),\n\n     |- (!a0. EVEN a0 = (a0 = 0) \\/\n                        ?n. (a0 = n + 1) /\\ ODD n) /\\\n        (!a1. ODD a1 = ?n. (a1 = n + 1) /\\ EVEN n)\n    ) : thm * thm * thm\n\\end{verbatim}\n\\end{session}\n%\nThe next example shows how to inductively define the reflexive and\ntransitive closure of relation $R$. Note that \\holtxt{R}, as a\nschematic variable, is not quantified in the rules. This is\nappropriate because it is \\holtxt{RTC R} that has the inductive\ncharacterisation, not \\holtxt{RTC} itself.\n%\n\\begin{session}\n\\begin{verbatim}\n  - Hol_reln `(!x. RTC R x x) /\\\n             (!x z. (?y. R x y /\\ RTC R y z) ==> RTC R x z)`;\n\n  > val it =\n     (|- !R. (!x. RTC R x x) /\\\n             !x z. (?y. R x y /\\ RTC R y z) ==> RTC R x z,\n\n      |- !R RTC'.\n           (!x. RTC' x x) /\\\n           (!x z. (?y. R x y /\\ RTC' y z) ==> RTC' x z)\n           ==>\n           (!a0 a1. RTC R a0 a1 ==> RTC' a0 a1),\n\n      |- !R a0 a1. RTC R a0 a1 = (a1 = a0) \\/ ?y. R a0 y /\\ RTC R y a1\n     ) : thm * thm * thm\n\\end{verbatim}\n\\end{session}\n%\nThe \\ml{Hol\\_reln} function may be used to define multiple relations,\nas in the definition of \\holtxt{EVEN} and \\holtxt{ODD}.  The relations\nmay or may not be mutually recursive.  The clauses for each relation\nneed not be contiguous.\n\n\\subsection{Proofs with Inductive Relations}\n\\index{inductive relations!performing proofs}\n\nThe ``rules'' theorem of an inductive relation provides a straightforward way of proving arguments belong to a relation.\nIf confronted with a goal of the form \\holtxt{R~x~y}, one might make progress by performing a \\ml{MATCH\\_MP\\_TAC} (or perhaps, an \\ml{HO\\_MATCH\\_MP\\_TAC}) with one of the implications in the ``rules'' theorem.\n\nThe ``cases'' theorem can be used for the same purpose because it is an equality, of the general form \\holtxt{R~x~y~$\\iff$\\dots}.\nBecause the right-hand side of this theorem will often include other occurrences of the relation, it is generally not safe to simply rewrite with it.\n\\index{SimpLHS@\\ml{SimpLHS}}\\index{SimpRHS@\\ml{SimpRHS}}%\n\\index{Once (controlling rewrite applications)@\\ml{Once} (controlling rewrite applications)}%\nThe rewriting-control directives \\ml{Once}, \\ml{SimpLHS} and \\ml{SimpRHS} can be useful here.\n\\index{FULL_SIMP_TAC@\\ml{FULL\\_SIMP\\_TAC}}\nIn addition, the ``cases'' theorem can be used as an ``elimination'' form: if one has an assumption of the form \\holtxt{R~x~y}, rewriting this (perhaps with \\ml{FULL\\_SIMP\\_TAC} if the term occurs in the goal's assumptions) into the possible ways it may have come about is often a good approach.\n\nInductive relations naturally also support proof by induction.\nBecause an inductive relation is the least relation satisfying the given rules, one can use induction to show goals of the form\n\\begin{alltt}\n   \\(\\forall\\)x y. R x y \\(\\Rightarrow\\) P\n\\end{alltt}\nwhere \\holtxt{P} is an arbitrary predicate likely including references to variables \\holtxt{x} and \\holtxt{y}.\n\nThe low-level approach to goals of this form is to apply\n\\begin{verbatim}\n   HO_MATCH_MP_TAC R_ind\n\\end{verbatim}\n\\index{Induct_on (ML induction tactic)@\\ml{Induct\\_on} (\\ML{} induction tactic)}\nA slightly more high-level approach is use the \\ml{Induct\\_on} tactic, which will actually use the automatically generated ``strong'' induction principle.%\n\\footnote{Thus, to get the equivalent of the \\ml{Induct_on} call, one might write something like \\ml{HO_MATCH_MP_TAC~(theorem \"R_strongind\")}.}\n(This tactic is also used to perform structural inductions over algebraic data types; see Section~\\ref{sec:bossLib}.)\nWhen performing a rule induction, the quotation passed to \\ml{Induct\\_on} should be of the constant being used.\nFor the sake of aesthetics, the constant may also be applied to arguments.\nThus, one can write\n\\begin{verbatim}\n   Induct_on `R`\n\\end{verbatim}\nor\n\\begin{verbatim}\n   Induct_on `R x y`\n\\end{verbatim}\nand the effect will be the same.\n\\index{inductive relations|)}\n\n\n%%% Local Variables:\n%%% mode: latex\n%%% mode: visual-line\n%%% TeX-master: \"description\"\n%%% End:\n", "meta": {"hexsha": "32b1a500a3807673563e735b85a9cae11d221fb5", "size": 79009, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Manual/Description/definitions.tex", "max_stars_repo_name": "talsewell/HOL", "max_stars_repo_head_hexsha": "cf6117411499c814fa92f2756179a146b35de043", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Manual/Description/definitions.tex", "max_issues_repo_name": "talsewell/HOL", "max_issues_repo_head_hexsha": "cf6117411499c814fa92f2756179a146b35de043", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Manual/Description/definitions.tex", "max_forks_repo_name": "talsewell/HOL", "max_forks_repo_head_hexsha": "cf6117411499c814fa92f2756179a146b35de043", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8512126866, "max_line_length": 299, "alphanum_fraction": 0.7008442076, "num_tokens": 22699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.3345838170744818}}
{"text": "\\documentclass[12pt, titlepage]{article}\n\\usepackage[english]{babel}\n\\usepackage[utf8]{inputenc}\n\n\\usepackage{graphicx} %graphics files inclusion\n% \\usepackage{subfig} %subfigures\n\\usepackage{amsmath} %advanced maths\n\\usepackage{amssymb} %additional math symbols\n\\usepackage{dsfont}  %contains \\mathds{1}\n\\usepackage{algpseudocode}\n\\usepackage{url}\n\n\\usepackage{dirtree} %directory tree visualisation\n\n\\usepackage[draft]{todonotes}   % notes showed\n\n\\usepackage[ruled,vlined]{algorithm2e}\n\\newcommand\\mycommfont[1]{\\footnotesize\\ttfamily\\textcolor{blue}{#1}}\n\\SetCommentSty{mycommfont}\n\n\\usepackage{xcolor, colortbl}\n\\usepackage{pdfpages}\n\n\\newcommand{\\lnorm}[1]{\\left\\lVert#1\\right\\rVert^2}\n\\newcommand{\\norm}[1]{\\left\\lVert#1\\right\\rVert}\n\n\\algnewcommand\\algorithmicforeach{\\textbf{for each:}}\n\\algnewcommand\\ForEach{\\item[ \\algorithmicforeach]}\n\\author{Radek Bartyzal}\n\n\\begin{document}\n\\begin{titlepage}\n    \\centering\n    \\vfill\n    {\\bfseries\\Huge\n        Adam: a method for stochastic optimization \\\\\n    }    \n        \\vskip1cm\n        \n    {\\bfseries\\Large \n    Czech Technical University in Prague\\\\ \n    Faculty of Informatics\\\\ \n    \\vskip1cm\n    Radek Bartyzal\\\\\n    }    \n    \\vskip1cm\n    October 21, 2018\n    \\vfill\n\n    \\vfill\n    \\vfill\n\\end{titlepage}\n\n\\tableofcontents\n\n\\section{Prerequisites}\nThe following text assumes that the reader is familiar with these terms:\n\n\\begin{itemize}\n\\item Neural Networks: Chapter 1 of \\cite{cit:nn} \n\\item Backpropagation: Chapter 2 of \\cite{cit:nn}\n\\end{itemize}\n\n\\section{Optimization of neural networks}\\label{sec:optim}\nTraining of a neural network consists of minimization of its loss function $L$. An example of such loss function is:\n\n\\begin{tabbing}\n$w$ = weights \\hspace{40mm} \\= $b$ = biases\\\\\n$n$ = number of inputs \\> $x$ = one input\\\\\n$a$ = output of network for $x$\\\\\n$y(x)$ = desired output for $x$\n\\end{tabbing}\n$$\nL(w,b) = \\frac{1}{2n} \\sum_x{ \\| y(x) - a \\|^2}\n$$\n\nBy using the backpropagation algorithm we are able to calculate the gradient of the loss function with regards to every parameter. We can use this gradient to update the parameters.\nThey are updated by a taking a small step in the opposite direction of the gradient since that is the direction in which the loss function decreases the most in its value. The size of the step is controlled by a parameter $\\eta$ called \\textit{learning rate}. This is a general description of a \\textit{Gradient Descent} algorithm, however there are many different ways how to calculate the actual step and we will present the ones most relevant to this work.\n\n\\section{Gradient Descent variants}\\label{sec:sgd_variants}\nThere are three variants of the basic gradient descent algorithm and all of them share the following inputs:\n\n\\begin{equation}\n\\begin{aligned}\n\\theta_0 &\\quad \\text{Initial parameters}\\\\\nN &\\quad \\text{Number of training examples}\\\\\nx_i,\\ \\forall i <  N &\\quad \\text{Training examples}\\\\\n\\hat{y}_i,\\ \\forall i < N &\\quad \\text{Labels for the training examples}\\\\\nT &\\quad \\text{Number of epochs}\n\\end{aligned}\n\\end{equation}\n\n\n\\begin{itemize}\n\\item \\textbf{Batch Gradient Descent (BGD)} shown as Algorithm \\ref{alg:BGD} calculates the step as an average of gradients over all the training examples. This approach unfortunately does not scale well because from a certain point you cannot load the whole dataset into memory making each single update extremely slow. Another problem is that it does not allow \\textit{online learning} meaning we cannot simply continue training with newly arrived data points.\n\n\\begin{algorithm}\n  \\label{alg:BGD}\n  \\caption{Batch Gradient Descent}\n  \\DontPrintSemicolon\n  \\For{$t\\gets 1$ \\KwTo $T$}\n  {\n  $g = 0$\\;\n  \\ForEach{$i \\in \\text{dataset}$}\n    {\n     $g = g + \\nabla L(\\hat{y}_i,f(\\theta_{t-1}, x_i))$\\;\n    }\n  $g = \\frac{1}{N} g$\\;\n  $\\theta_t = \\theta_{t-1} - \\eta g$\n  }\n\\end{algorithm}\n\n\\item \\textbf{Stochastic Gradient Descent (original SGD)} shown as Algorithm \\ref{alg:SGD} updates the parameters with the gradient of every training example sequentially. The training data is shuffled between epochs to add an element of randomness resulting in increased chances of finding a better local minimum. This approach alleviates both mentioned problems of BGD, unfortunately it introduces its own one. Due to the frequent updates, the global loss tends to have a very high variance which may help it escape local minima but it also complicates convergence. \n\n\\begin{algorithm}\n  \\label{alg:SGD}\n  \\caption{Stochastic Gradient Descent}\n  \\DontPrintSemicolon\n  $\\theta = \\theta_0$\\;\n  \\For{$t\\gets 1$ \\KwTo $T$}\n  {\n  $\\mathit{shuffle(dataset)}$\\;\n  \\ForEach{$i \\in \\text{dataset}$}\n    {\n     $g = \\nabla L(\\hat{y}_i,f(\\theta, x_i))$\\;\n     $\\theta = \\theta - \\eta g$\\;\n    }\n  }\n\\end{algorithm}\n\n\\item \\textbf{Mini-batch Stochastic Gradient Descent (SGD)} described in Algorithm \\ref{alg:mini_SGD} is the logical combination of the two mentioned methods. By updating the parameters after each mini batch of size $B$ the algorithm achieves significantly less variance of the loss while keeping the advantage of frequent updates. It also leverages the fast matrix operations available on current graphical processors. The new hyperparameter $B$ can be selected based on the size of the dataset and available memory to strike a balance between speed and variance. This algorithm is generally referred to as SGD because due to the strong disadvantages of both BGD and original SGD they are very rarely used.\n\n\\begin{algorithm}\n  \\label{alg:mini_SGD}\n  \\caption{Mini-batch Stochastic Gradient Descent}\n  \\DontPrintSemicolon\n  $\\theta = \\theta_0$\\;\n  \\For{$t\\gets 1$ \\KwTo $T$}\n  {\n  $\\mathit{shuffle(dataset)}$\\;\n  \\ForEach{$\\text{mini\\_batch} \\in \\text{dataset}$}\n  {\n  $g = 0$\\;\n  \\ForEach{$i \\in \\text{mini\\_batch}$}\n    {\n     $g = g + \\nabla L(\\hat{y}_i,f(\\theta, x_i))$\\;\n    }\n  $g = \\frac{1}{B} g$\\;\n  $\\theta = \\theta - \\eta g$\n  }\n  }\n\\end{algorithm}\n\\end{itemize}\n\nEven though the SGD fixes the mentioned imperfections, it still has two significant problems:\n\n\\begin{itemize}\n\\item Finding a good learning rate can prove to be difficult, but we can offload this task to a \\textit{learning rate scheduler} that changes it during training based both on elapsed time steps and past performance  \\cite{darken1992learning}. Although the adaptable learning rate performs much better than a constant one, the fact that it is identical for all parameters causes problems in situation where each example while having a high dimension has only few non-zero features. Therefore some features occur more frequently than others which is not reflected in the applied learning rate. That results in slower updates to the less frequent features.\n\n\\item The loss function of a deep neural network is undoubtedly very complex which brings many challenges to optimization. The most profound difficulty in optimizing such a high dimensional non-convex function is however believed to stem from an extensive number of saddle points surrounded by large plateaus with high error \\cite{dauphin2014identifying}. This is where the loss function increases in some dimensions while it is constant or decreasing in other dimensions. A simple three dimensional example can be a slowly descending valley with steep slopes on both sides. The problem stems from the small decrease in value in the one dimension that actually leads to a minimum. An intuitive explanation of what will happen is that the SGD will keep jumping across the valley while moving very slowly in the desired direction.\n\\end{itemize} \n\nThe following methods alleviate one or both of the described issues \\cite{ruder2016overview}.\n\n\\section{AdaGrad}\nAdaGrad is an adaptive gradient method attempting to solve the issue of some features appearing less frequently than others \\cite{duchi2011adaptive}. The general idea is for the learner to give larger weight to infrequent features when they appear. \n\nThis is implemented by taking note of the past gradient updates and using the sum of the squared past gradients to divide the actual learning rate. \n\nWe start with a gradient of the loss function $L$ with respect to a parameter $i$ at time $t$:\n\n\\begin{equation}\\label{eq:gradient}\ng_{t,i} = \\nabla_{\\theta} L(\\theta_{t,i})\n\\end{equation}\n\nThe classic mini-batch SGD update would look like this:\n\n\\begin{equation}\\label{eq:sqd_update}\n\\theta_{t+1,i}^{SGD} = \\theta_{t,i} - \\eta g_{t,i}\n\\end{equation}\n\nHowever the AdaGrad update leverages the past gradient update information to adaptively change the learning rate for each of the parameters separately:\n\n\\begin{equation}\\label{eq:adagrad_update}\n\\theta_{t+1,i}^{AdaGrad} = \\theta_{t,i} - \\frac{\\eta}{\\sqrt{ \\sum_{\\tau=1}^t{g_{\\tau,i}^2}} + \\epsilon} g_{t,i}\n\\end{equation}\n\nThe epsilon is used to prevent division by an extremely small number. Even though this new update rule nicely adapts to each parameter, their learning rates keep getting smaller with increasing time steps. This is caused by the sum of squared gradients that can only increase with time resulting in a smaller and smaller effective learning rate, possibly reaching zero and stopping the training entirely. Another issue is the sensitivity to the initial setting of the learning rate. If the gradients are too large at the beginning, the parameter updates will be small for the rest of the training \\cite{zeiler2012adadelta}.\n\n\n\\section{RMSProp and AdaDelta}\nBoth RMSProp and AdaDelta have been invented around the same time to solve the mentioned issue of AdaGrad's diminishing learning rate. The RMSProp has been introduced by G. Hinton in his course at University of Toronto \\cite{rmsprop}. It is slightly simpler than AdaDelta \\cite{zeiler2012adadelta} while using the same idea which is why we will discuss it here.\n\nThe central idea is to use a decaying running average of past squared gradients representing gradients from a certain time window instead of using all of them. This ensures that the training will not slow down after a large number of updates.\n\nThe running average of past gradients can be effectively calculated as:\n\n\\begin{equation}\\label{eq:running_avg}\n\\mathbb{E}[g^2]_t = \\gamma \\mathbb{E}[g^2]_{t-1} + (1 - \\gamma) g_t^2\n\\end{equation}\n\nThen we just replace the summation term in the AdaGrad update rule with this running average estimate:\n\n\\begin{equation}\\label{eq:rmsprop_update}\n\\theta_{t+1}^{RMSProp} = \\theta_{t} - \\frac{\\eta}{\\sqrt{\\mathbb{E}[g^2]_t} + \\epsilon} g_{t}\n\\end{equation}\n\nThe decay rate $\\gamma$ is recommended to be set to $0.9$ while a good default learning rate is $0.001$. These methods are generally much less sensitive to a different initial learning rates making hyper-parameter tuning easier \\cite{zeiler2012adadelta}.\n\n\\section{Adam}\nThe Adam (adaptive moment estimator) method is an improvement of the previously mentioned RMSProp with an addition of an estimate of the first order momentum \\cite{kingma2014adam}.\n\nJust as the RMSProp the Adam calculates the decaying running average of the squared past gradients, here called $v_t$. It also calculates the running average of the gradients themselves, called $m_t$ the same way. The $m_t$ and $v_t$ estimate the first and second order moments of the gradient corresponding to the mean and the uncentered variance.\n\n\\begin{equation}\\label{eq:adam_moments}\n\\begin{aligned}\nm_t &= \\beta_1 m_{t-1} + (1 - \\beta_1) g_t\\\\\nv_t &= \\beta_2 v_{t-1} + (1 - \\beta_2) g_t^2\n\\end{aligned}\n\\end{equation}\n\nThe $m_t$ and $v_t$ are unfortunately biased toward zero at the start of training due to their initialization to zero vectors. To correct that bias the Adam algorithm divides the moment estimates with a time sensitive term approaching $1$ with increasing number of time steps:\n\n\\begin{equation}\\label{eq:adam_moments}\n\\begin{aligned}\n\\hat{m_t} &= \\frac{m_t}{(1 - \\beta_1^t)}\\\\\n\\hat{v_t} &= \\frac{v_t}{(1 - \\beta_2^t)}\n\\end{aligned}\n\\end{equation}\n\n\nThese bias corrected moment estimates are then used in the actual update rule similarly to the RMSProp and AdaDelta algorithms:\n\n\\begin{equation}\\label{eq:adam_update}\n\\theta_{t+1}^{Adam} = \\theta_{t} - \\frac{\\eta}{\\sqrt{v_t} + \\epsilon} m_t\n\\end{equation}\n\nThe recommended default values for the hyper-parameters are $\\beta_1 = 0.9$, $\\beta_2 = 0.999$, $\\epsilon = 10^{-8}$.\nThe positive aspects of the second order moment dividing the learning rate have been explained in the previous sections. The addition of the first order moment can be understood as a momentum term. It aims to solve the problem SGD has with getting out of saddle points. \nThe effects of momentum can be presented on the example with the slowly descending valley given at the end of Section \\ref{sec:sgd_variants}. \n\nIf we imagine a ball without momentum in such valley, it will keep going up the opposing sides while slowly moving through the valley. If we add momentum to the ball, it will dampen its oscillation while increasing the speed of movement in the direction of consistent decrease in function value. We can compare that to adding weight to the ball. \n\nTransferring the example to the effects on optimization, the updates in the dimensions where the gradient directions keep changing will be smaller while the updates in the dimensions that are consistently going a certain direction will become incrementally larger.\n\nA follow-up research into Adam has uncovered several convergence issues and possible areas of improvement which led to the introduction of new versions such as:\n\n\\begin{itemize} \n\\item \\textbf{NAdam:} Adapt the momentum term with the Nesterov accelerated gradient method \\cite{dozat2016incorporating}.\n\\item \\textbf{AdamW:} Claims to fix the weight decay calculation \\cite{loshchilov2017fixing}.\n\\item \\textbf{AmsGrad:} Finds errors in the proof of Adam's convergence and claims to improve it by introducing AmsGrad algorithm \\cite{reddi2018convergence}.\n\\end{itemize}\n\nTo the contrary of the numerous papers claiming to improve the original Adam algorithm, experimental results show that it in many cases works better or at least as well as its newer variants. While some of them look promising, there is no single variant dominating others at all tested optimization tasks \\cite{adam-variants}.\n\n\\section{Conclusion}\n\nThe Adam algorithm remains as one of the best ways to train neural networks. However the mini batch SGD is also still extensively used because it is well understood and achieves very good results with a properly tuned learning rate schedule.\n\n\n\n\\begin{thebibliography}{0}\n  \\bibitem[1]{cit:nn} Nielsen, Michael A. Neural networks and deep learning. Vol. 25. USA: Determination press, 2015.\n  \n  \\bibitem[2]{darken1992learning} Darken, Christian, Joseph Chang, and John Moody. \"Learning rate schedules for faster stochastic gradient search.\" Neural Networks for Signal Processing [1992] II., Proceedings of the 1992 IEEE-SP Workshop. IEEE, 1992.\n  \n  \\bibitem[3]{dauphin2014identifying} Dauphin, Yann N., et al. \"Identifying and attacking the saddle point problem in high-dimensional non-convex optimization.\" Advances in neural information processing systems. 2014.\n  \n  \\bibitem[4]{ruder2016overview} Ruder, Sebastian. \"An overview of gradient descent optimization algorithms.\" arXiv preprint arXiv:1609.04747 (2016).\n  \n  \\bibitem[5]{zeiler2012adadelta} Zeiler, Matthew D. \"ADADELTA: an adaptive learning rate method.\" arXiv preprint arXiv:1212.5701 (2012).\n  \n  \\bibitem[6]{kingma2014adam} Kingma, Diederik P., and Jimmy Ba. \"Adam: A method for stochastic optimization.\" arXiv preprint arXiv:1412.6980 (2014).\n  \n  \\bibitem[7]{dozat2016incorporating} Dozat, Timothy. \"Incorporating nesterov momentum into adam.\" (2016).\n  \n  \\bibitem[8]{loshchilov2017fixing} Loshchilov, Ilya, and Frank Hutter. \"Fixing weight decay regularization in adam.\" arXiv preprint arXiv:1711.05101 (2017).\n  \n  \\bibitem[9]{reddi2018convergence} Reddi, Sashank J., Satyen Kale, and Sanjiv Kumar. \"On the convergence of adam and beyond.\" (2018).\n  \n  \\bibitem[10]{adam-variants} FastAI’s experimental results of Adam variants [online]. \\url{http:\n//www.fast.ai/2018/07/02/adam-weight-decay/}, [Online; accessed\n2018-October-21].\n\n  \\bibitem[11]{rmsprop} G. Hinton’s lecture introducing RMSProp [online]. \\url{http:\n//www.cs.toronto.edu/˜tijmen/csc321/slides/lecture_slides_\nlec6.pdf}, [Online; accessed 2018-October-21].\n\n  \\bibitem[12]{duchi2011adaptive} Duchi, John, Elad Hazan, and Yoram Singer. \"Adaptive subgradient methods for online learning and stochastic optimization.\" Journal of Machine Learning Research 12.Jul (2011): 2121-2159.\n\n\n  \n  \n  \n  \n  \\end{thebibliography}\n\n\n \n\\end{document}\n", "meta": {"hexsha": "558bd49071f2840459d02191f1041f9e138b199c", "size": 16600, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "talks/Adam/handout/Adam_handout.tex", "max_stars_repo_name": "BartyzalRadek/lets-talk-ml", "max_stars_repo_head_hexsha": "b1584ea86ba60d4d2554be7de2cc332b4e1d5ebc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-02T00:49:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-02T00:49:46.000Z", "max_issues_repo_path": "talks/Adam/handout/Adam_handout.tex", "max_issues_repo_name": "BartyzalRadek/lets-talk-ml", "max_issues_repo_head_hexsha": "b1584ea86ba60d4d2554be7de2cc332b4e1d5ebc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "talks/Adam/handout/Adam_handout.tex", "max_forks_repo_name": "BartyzalRadek/lets-talk-ml", "max_forks_repo_head_hexsha": "b1584ea86ba60d4d2554be7de2cc332b4e1d5ebc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-04-29T07:00:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-29T07:00:39.000Z", "avg_line_length": 55.1495016611, "max_line_length": 828, "alphanum_fraction": 0.761746988, "num_tokens": 4396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.3345838170744818}}
{"text": "\\chapter{Objects of Arrays}\n\n\\index{array!of cards}\n\nIn the previous chapter, we defined a class to represent cards and used an array of \\java{Card} objects to represent a deck.\nIn this chapter, we take additional steps toward object-oriented programming.\n\nFirst we define a class to represent a deck of cards.\nThen we present algorithms for shuffling and sorting decks.\nFinally, we introduce \\java{ArrayList} from the Java library and use it to represent collections of cards.\n\n%While reading the following sections, we recommend that you create a {\\tt Deck.java} file and paste in all the examples.\n%You will need {\\tt Card.java} from the previous chapter for it to compile.\n\n%The code for this chapter is in {\\tt Card.java} and {\\tt Deck.java}, which are in the directory {\\tt ch13} in the repository for this book.\n%Instructions for downloading this code are on page~\\pageref{code}.\n\n\n\\section{Decks of Cards}\n\\label{deck}\n\n\\index{Deck}\n\\index{class!Deck}\n\nHere is the beginning of a \\java{Deck} class that encapsulates an array of \\java{Card} objects:\n\n\\begin{code}\npublic class Deck {\n    private Card[] cards;\n\n    public Deck(int n) {\n        this.cards = new Card[n];\n    }\n\n    public Card[] getCards() {\n        return this.cards;\n    }\n}\n\\end{code}\n\n\\index{constructor}\n\\index{memory diagram}\n\\index{diagram!memory}\n\nThe constructor initializes the instance variable with an array of \\java{n} cards, but it doesn't create any \\java{Card} objects.\nFigure~\\ref{fig.deckobject} shows what a \\java{Deck} looks like with no cards.\n\n\\begin{figure}[!ht]\n\\begin{center}\n\\includegraphics{figs/deckobject.pdf}\n\\caption{Memory diagram of an unpopulated \\java{Deck} object.}\n\\label{fig.deckobject}\n\\end{center}\n\\end{figure}\n\nWe'll add another constructor that creates a standard 52-card array and populates it with \\java{Card} objects:\n\n\\begin{code}\npublic Deck() {\n    this.cards = new Card[52];\n    int index = 0;\n    for (int suit = 0; suit <= 3; suit++) {\n        for (int rank = 1; rank <= 13; rank++) {\n            this.cards[index] = new Card(rank, suit);\n            index++;\n        }\n    }\n}\n\\end{code}\n\nThis method is similar to the example in Section~\\ref{cardarray}; we just turned it into a constructor.\nWe can use it to create a complete \\java{Deck} like this:\n\n\\begin{code}\nDeck deck = new Deck();\n\\end{code}\n\n\\index{printDeck}\n\nNow that we have a \\java{Deck} class, we have a logical place to put methods that pertain to decks.\nLooking at the methods we have written so far, one obvious candidate is \\java{printDeck} from Section~\\ref{cardarray}.\nHere's how it looks, rewritten as an instance method of \\java{Deck}:\n\n\\begin{code}\npublic void print() {\n    for (Card card : this.cards) {\n        System.out.println(card);\n    }\n}\n\\end{code}\n\n%\\begin{code}\n%public void print() {\n%    for (int i = 0; i < this.cards.length; i++) {\n%        System.out.println(this.cards[i]);\n%    }\n%}\n%\\end{code}\n\nNotice that when we transform a static method into an instance method, the code is shorter.\n\nHere's how we invoke it:\n\n\\begin{code}\ndeck.print();\n\\end{code}\n\n\n\\section{Shuffling Decks}\n\\label{shuffle}\n\n\\index{shuffle}\n\nFor most card games, you have to shuffle the deck; that is, put the cards in a random order.\nIn Section~\\ref{random} we saw how to generate random numbers, but it is not obvious how to use them to shuffle a deck.\n\nOne possibility is to model the way humans shuffle; for example, we could divide the deck in two halves and then choose alternately from each one.\nSince humans usually don't shuffle perfectly, after about seven iterations the order of the deck is pretty well randomized.\n\nBut a computer program would have the annoying property of doing a perfect shuffle every time, which is not very random.\nIn fact, after eight perfect shuffles, you would find the deck back in the order you started in!\nFor more on this, see \\url{https://en.wikipedia.org/wiki/Faro_shuffle}.\n\n\\index{pseudocode}\n\nA better shuffling algorithm is to traverse the deck one card at a time, and at each iteration, choose two cards and swap them.\nTo outline this algorithm, we'll use a combination of Java statements and English comments.\nThis technique is sometimes called {\\bf pseudocode}.\n\n\\index{shuffle}\n\n\\begin{code}\npublic void shuffle() {\n    for each index i {\n        // choose a random number between i and length - 1\n        // swap the ith card and the randomly-chosen card\n    }\n}\n\\end{code}\n\n\\index{helper method}\n\\index{method!helper}\n\nThe nice thing about pseudocode is that it often makes clear what other methods you are going to need.\nIn this case, we need a method that chooses a random integer in a given range and a method that takes two indexes and swaps the cards at those positions.\n\n\\begin{code}\nprivate static int randomInt(int low, int high) {\n    // return a random number between low and high, \n    // including both\n}\n\nprivate void swapCards(int i, int j) {\n    // swap the ith and the jth cards in the array\n}\n\\end{code}\n\n\\index{randomInt}\n\\index{swapCards}\n\nMethods like \\java{randomInt} and \\java{swapCards} are called {\\bf helper methods}, because they help you solve parts of the problem.\nHelper methods are often \\java{private}, because they are only used by methods in the class, and are not needed by client users of the class. Clients need not know about these methods - they are private to the \\java{Deck} class.\n\n\\index{top-down design}\n\\index{design process}\n\nThe process of writing pseudocode first and then writing helper methods to make it work is a kind of {\\bf top-down design} (see \\url{https://en.wikipedia.org/wiki/Top-down_and_bottom-up_design}).\nIt is an alternative to ``incremental development'' and ``encapsulation and generalization'', the other design processes you have seen in this book.\n\nOne of the exercises at the end of the chapter asks you to write the helper methods \\java{randomInt} and \\java{swapCards}, and use them to implement \\java{shuffle}.\n\nWhen you do the exercise, notice that \\java{randomInt} is a class method and \\java{swapCards} is an instance method.\nDo you understand why?\n\n\n\\section{Selection Sort}\n\\label{sorting}\n\n\\index{selection sort}\n\\index{sort!selection}\n\nNow that we have shuffled the deck, we need a way to put it back in order.\nThere is an algorithm for sorting that is ironically similar to the algorithm for shuffling.\nIt's called {\\bf selection sort}, because it works by traversing the array repeatedly and selecting the lowest (or highest) remaining card each time.\n\nDuring the first iteration, we find the lowest card and swap it with the card in the 0th position.\nDuring the $i$th iteration, we find the lowest card to the right of $i$ and swap it with the $i$th card.\nHere is pseudocode for selection sort:\n\n\\begin{code}\npublic void selectionSort() {\n    for each index i {\n        // find the lowest card at or to the right of i\n        // swap the ith card and the lowest card found\n    }\n}\n\\end{code}\n\nAgain, the pseudocode helps with the design of the helper methods.\nFor this algorithm we can reuse \\java{swapCards} from the previous section, so we only need a method to find the lowest card; we'll call it \\java{indexLowest}.\n\n\\begin{code}\nprivate int indexLowest(int low, int high) {\n    // find the lowest card between low and high\n}\n\\end{code}\n\n%slr: 1-14-20\nThe method \\java{indexLowest} is an \\textbf{instance} method which means the instance \\java{this} is available (in scope).  Thus the \\java{Card} array is available inside the method as \\java{this.cards}.\n%slr: end 1-14-20\n\nOne of the exercises at the end of the chapter asks you to write \\java{indexLowest}, and then use it and \\java{swapCards} to implement \\java{selectionSort}.\n\n\n\\section{Merge Sort}\n\\label{mergesort}\n\n\\index{efficiency}\n\nSelection sort is a simple algorithm, but it is not very efficient.\nTo sort $n$ items, it has to traverse the array $n-1$ times.\nEach traversal takes an amount of time proportional to $n$.\nThe total time, therefore, is proportional to $n^2$.\n\n\\index{merge sort}\n\\index{sort!merge}\n\nWe will develop a more efficient algorithm called {\\bf merge sort}.\nTo sort $n$ items, merge sort takes time proportional to $n \\log_2 n$.\nThat may not seem impressive, but as $n$ gets big, the difference between $n^2$ and $n \\log_2 n$ can be enormous.\n\nFor example, $\\log_2$ of one million is around 20.\nSo if you had to sort a million numbers, merge sort would require 20 million steps.\nBut selection sort would require one trillion steps!\n\nThe idea behind merge sort is this: if you have two decks, each of which has already been sorted, you can quickly merge them into a single, sorted deck.\nTry this out with a deck of cards:\n\n\\begin{enumerate}\n\n\\item Form two decks with about 10 cards each, and sort them so they are face up with the lowest cards on top.\nPlace the decks in front of you.\n\n\\item Compare the top card from each deck and choose the lower one.\nFlip it over and add it to the merged deck.\n\n\\item Repeat step 2 until one of the decks is empty.\nThen take the remaining cards and add them to the merged deck.\n\n\\end{enumerate}\n\n%slr: 1-14-20  maybe embed video?\n\nThe result should be a single sorted deck.\nIn the next few sections, we'll explain how to implement this algorithm in Java.\n\n\n\\section{Subdecks}\n\n\\index{subdeck}\n\\label{subdeck}\n\nThe first step of merge sort is to split the deck into two ``subdecks'', each with about half of the cards.\nSo we need a method that takes a deck, and a range of indexes, and returns a new deck that contains the specified subset of cards.\n\n\\begin{code}\npublic Deck subdeck(int low, int high) {\n    Deck sub = new Deck(high - low + 1);\n    for (int i = 0; i < sub.cards.length; i++) {\n        sub.cards[i] = this.cards[low + i];\n    }\n    return sub;\n}\n\\end{code}\n\n%slr: 1-14-20 added last two sentences to paragraph\nThe first line creates an unpopulated \\java{Deck} object that contains an array of \\java{null} references.\nInside the \\java{for} loop, the subdeck gets populated with references to \\java{Card} objects.  \nThe expression \\java{sub.cards.length} uses the 'dot operator' to access \\java{sub}'s \\java{cards} instance variable which yields an array of \\java{Card}.  Then, using the dot operator again, we obtain the array's length.\n\n\\index{off-by-one}\n\nThe length of the subdeck is \\java{high - low + 1}, because both the low card and the high card are included.\nThis sort of computation can be confusing, and forgetting the ``\\java{+ 1}'' often leads to {\\bf off-by-one} errors.\nDrawing a picture is usually the best way to avoid them.\n\n%For example, to select the middle three of five values in an array, we need \\java{3 - 1 + 1} values.\n%\n%\\begin{center}\n%\\begin{tabular}{ccccc}\n%\\hline\n%\\multicolumn{1}{|c|}{} & \\multicolumn{1}{c|}{X} & \\multicolumn{1}{c|}{X} & \\multicolumn{1}{c|}{X} & \\multicolumn{1}{c|}{} \\\\\n%\\hline\n%0                      & 1                      & 2                      & 3                      & 4                     \\\\\n%\\end{tabular}\n%\\end{center}\n\n\\index{constructor}\n\\index{overload}\n\nFigure~\\ref{fig.subdeck} is a memory diagram of a subdeck with \\java{low = 0} and \\java{high = 4}.\nThe result is a hand with five cards that are {\\em shared} with the original deck; that is, they are aliased.\n\n\\begin{figure}[!ht]\n\\begin{center}\n\\includegraphics{figs/subdeck.pdf}\n\\caption{Memory diagram showing the effect of \\java{subdeck}.}\n\\label{fig.subdeck}\n\\end{center}\n\\end{figure}\n\n\\index{aliasing}\n\\index{reference}\n\nNote that the items of \\java{sub} are aliases of corresponding items of \\java{cards}. Aliasing might not be a good idea, because changes to shared cards would be reflected in multiple decks.\nBut since \\java{Card} objects are immutable, this kind of aliasing is not a problem.\nAnd it saves some memory because we don't create duplicate \\java{Card} objects.\n\n\n\\section{Merging Decks}\n\n\\index{merge}\n\nThe next helper method we need is \\java{merge}, which takes two sorted subdecks and returns a new deck containing all cards from both decks, in order.\nHere's what the algorithm looks like in pseudocode, assuming the subdecks are named \\java{d1} and \\java{d2}:\n\n\\begin{code}\nprivate static Deck merge(Deck d1, Deck d2) {\n    // create a new deck, d3, big enough for all the cards\n\n    // use the index i to keep track of where we are at in\n    // the first deck, and the index j for the second deck\n    int i = 0;\n    int j = 0;\n\n    // the index k traverses the result deck\n    for (int k = 0; k < d3.length; k++) {\n        // if d1 is empty, use top card from d2\n        // if d2 is empty, use top card from d1\n        // otherwise, compare the top two cards\n\n        // add lowest card to the new deck at k\n        // increment i or j (depending on deck)\n    }\n    // return the new deck\n}\n\\end{code}\n\nAn exercise at the end of the chapter asks you to implement \\java{merge}.\nIt's a little tricky, so be sure to test it with different subdecks.\nOnce your \\java{merge} method is working, you can use it to write a simplified version of merge sort:\n\n\\begin{code}\npublic Deck almostMergeSort() {\n    // divide the deck into two subdecks\n    // sort the subdecks using selectionSort\n    // merge the subdecks, return the result\n}\n\\end{code}\n\nIf you have working versions of \\java{subdeck}, \\java{selectionSort}, and \\java{merge}, you should have no trouble getting this method working.\nBut it is still not very efficient, because it uses \\java{selectionSort} to sort the subdecks.\nWe can make it more efficient if we use \\java{mergeSort} instead, but that means we have to make it recursive!\n\n\\section{Adding Recursion}\n\nTo make \\java{mergeSort} work recursively, you have to add a base case; otherwise it repeats forever.\n\nThe simplest base case is a subdeck with 1 cards.\nIf there is only one card, it can't be out of order, so we consider it sorted.\nAnd if it is already sorted, we can just return it.\n\nAnd it will turn out to be convenient if we handle another base case, a subdeck with 0 cards.\nBy the same logic, if there are no cards, they can't be out of order.\nSo we consider an empty deck to be sorted, and return it.\n\nWith these base cases, a recursive version of \\java{mergeSort} looks like this:\n\n\\begin{code}\npublic Deck mergeSort() {\n    // if the deck has 0 or 1 cards, return it\n    // otherwise, divide the deck into two subdecks\n    // sort the subdecks using mergeSort\n    // merge the subdecks\n    // return the result\n}\n\\end{code}\n\n\\index{leap of faith}\n\n%slr:  comment out 'leap of faith' and related discussion in next three paragraphs\n%As usual, there are two ways to think about recursive programs: you can follow the flow of execution, or you can make the ``leap of faith'' (see Section~\\ref{leap_of_faith}).\n%This example should encourage you to make the leap of faith.\n\n%When you use \\java{selectionSort} to sort the subdecks, you don't feel compelled to follow the flow of execution.\n%You assume it works because you already debugged it.\n%When you make \\java{mergeSort} recursive, you just replace one sorting algorithm with another.\n%There is no reason to read the program differently.\n%\n%Well, almost.\n%You have to think about the base cases and make sure that you reach them.\n%But other than that, writing the recursive version should be no problem.\n%The most difficult part of merge sort is the \\java{merge} method, and that part is not recursive.\n\n%As an exercise at the end of this chapter, you'll have a chance to finish it off.\n\n\n\\section{Static Context}\n\nFigure~\\ref{fig.deck} shows a UML class diagram for \\java{Deck}, including the instance variable, \\java{cards}, and the methods we have so far.\nIn UML diagrams, \\java{private} attributes and methods begin with a minus sign (\\java{-}) and \\java{static} methods are underlined.\n\n\\index{UML}\n\\index{class diagram}\n\\index{diagram!class}\n\n\\begin{figure}[!ht]\n\\begin{center}\n\\includegraphics{figs/deck.pdf}\n\\caption{UML diagram for the \\java{Deck} class.}\n\\label{fig.deck}\n\\end{center}\n\\end{figure}\n\nThe helper methods \\java{randomInt} and \\java{merge} are \\java{static}, because they do not read or write any instance variables.\nAll other methods are instance methods, because they access the instance \\java{this} and its instance variable \\java{cards}.\n\nWhen you have static methods and instance methods in the same class, it is easy to get them confused.\n\nTo invoke an instance method, you need an instance:\n\n\\begin{code}\nDeck deck = new Deck();\ndeck.print();  // correct\n\\end{code}\n\n\\java{Deck} with a capital \\java{D} is a class, and \\java{deck} with a lowercase \\java{d} is an object.\n\nIf you try to invoke \\java{print} like this:\n\n\\begin{code}\nDeck.print();  // wrong!\n\\end{code}\n\n% DW suggested that at some point we should warn students\n% about using \\java{this} in a static method\n\n\\index{static context}\n\\index{this}\n\nYou get an compiler error like this:\n\n\\begin{stdout}\nNon-static method print() cannot be referenced from a\nstatic context.\n\\end{stdout}\n\nBy ``static context'', the compiler means you are trying to invoke a method in a context that requires a static method.\n\nOn the other hand, if you have a \\java{Deck} object, you can use it to invoke a static method:\n\n\\begin{code}\nDeck deck = new Deck();\nint i = deck.randomInt(0, 51);  // legal, but not good style\n\\end{code}\n\nThis is legal, but it is not considered good style, because someone reading this code would expect \\java{randomInt} to be an instance method.\n\n%slr:  1-14-20\nA much more common and better way of accessing static methods if by using the class itself:\n\n\\begin{code}\nint i = Deck.randomInt(0, 51);  // invoke static method via the class\n\\end{code}\n\nAnother common error is to use \\java{this} in a static method.\nFor example, if you write something like this:\n\n\\begin{code}\nprivate static Deck merge(Deck d1, Deck d2) {\n    return this.cards;  // wrong!\n}\n\\end{code}\n\nYou get a compiler error like this:\n\n\\begin{stdout}\nNon-static variable this cannot be referenced from a\nstatic context.\n\\end{stdout}\n\nThe problem is that \\java{cards} is an instance variable, so it is ``non-static'', so you can't access it from a static method.\nIn general, you can't use \\java{this} in a static method, because a static method is not invoked on an object.\n\nFor beginners, error messages about non-static context can be confusing and frustrating.\nWe hope this section helps.\n\n%\\index{sort!Arrays}\n%\\index{array!sorting}\n\n%Normally we wouldn't implement two different sorting algorithms in the same class.\n%Our goal with \\java{Deck} was to demonstrate static methods and different ways of solving the same problem.\n%In practice, we could just write a single \\java{sort} method that uses \\java{java.util.Arrays}.\n%\n%\\begin{code}\n%public void sort() {\n%    Arrays.sort(this.cards);\n%}\n%\\end{code}\n\n\n\\section{Piles of Cards}\n\n\\index{War (card game)}\n\nNow that we have classes that represent cards and decks, let's use them to make a game.\nOne of the simplest card games that children play is called ``War'' (see \\url{https://en.wikipedia.org/wiki/War_(card_game)}).\n\nInitially, the deck is divided evenly into two piles, one for each player.\nDuring each round, each player takes the top card from their pile and places it, face up, in the center.\nWhoever has the highest ranking card, ignoring suit, takes the two cards and adds them to the bottom of their pile.\nThe game continues until one player has won the entire deck.\n\nWe could use the \\java{Deck} class to represent the individual piles.\nHowever, our implementation of \\java{Deck} uses a \\java{Card} array, and the length of an array can't change.\nAs the game progresses, we need to be able to add and remove cards from the piles.\n\n\\index{ArrayList}\n\\index{collection}\n\nWe can solve this problem with an \\java{ArrayList}, which is in the \\java{java.util} package.\nAn \\java{ArrayList} is a {\\bf collection}, which is an object that contains other objects.\nIt provides methods to add and remove elements, and it grows and shrinks automatically.\n\n%The Java library includes many other collections (see \\url{https://thinkjava.org/collections}).\n%For our purposes, \\java{ArrayList} is a good choice because it provides methods to add and remove elements, and it grows and shrinks automatically.\n\n\\index{Pile}\n\\index{class!Pile}\n\nWe define a new class named \\java{Pile} to represent a pile of cards.\nIt uses an \\java{ArrayList} to store \\java{Card} objects.\n\n\\begin{code}\npublic class Pile {\n    private ArrayList<Card> cards;\n\n    public Pile() {\n        this.cards = new ArrayList<Card>();\n    }\n}\n\\end{code}\n\n\\index{angle brackets}\n\\index{brackets!angle}\n\\index{\\textless\\textgreater\\ angle brackets}\n\nWhen you declare an \\java{ArrayList}, you specify the type it contains in angle brackets (\\java{<>}).\nThis declaration says that \\java{cards} is not just an \\java{ArrayList}; it's an \\java{ArrayList} of \\java{Card} objects.\n\nThe constructor initializes \\java{this.cards} with an empty \\java{ArrayList}.\n\n%Java collections can only store objects, not primitives like \\java{int}.\n%But you can use wrapper classes, for example \\java{ArrayList<Integer>}.\n\nNow let's think about the methods we need to play the game.\n\nAt the beginning of each round, each player draws a card from the top of their pile.\nSo we define a method to do that:\n\n%TODO: ML suggests renaming this drawCard.  I am inclined to agree.\n\n\\begin{code}\npublic Card popCard() {\n    return this.cards.remove(0);  // from the top of the pile\n}\n\\end{code}\n\n\\java{popCard} removes the \\java{Card} at the beginning of the \\java{ArrayList}, which we think of as the top of the pile.\n\nBecause we use \\java{ArrayList.remove}, it automatically shifts the remaining cards to fill the gap.\n\nAt the end of each round, the winner adds cards to the bottom of their pile.\nSo we define a method to do that:\n\n\\begin{code}\npublic void addCard(Card card) {\n    this.cards.add(card);        // to the bottom of the pile\n}\n\\end{code}\n\n\\java{ArrayList} provides a method, \\java{add}, that adds an element to the end of the collection, which we think of as the bottom of the pile.\n\nTo know when to stop the game, have to check if one of the piles is empty.\nHere's a method to do that: \n\n\\begin{code}\npublic boolean isEmpty() {\n    return this.cards.isEmpty();\n}\n\\end{code}\n\nSo far, these methods don't do very much; they just invoke methods on the instance variable, \\java{cards}.\nMethods like these are called {\\bf wrapper methods} because they wrap one method with another.\n\n% TODO: Change the code to get rid of size (unless we need it somewhere else) and change empty to isEmpty\n\n%\\begin{code}\n%public int size() {\n%    return this.cards.size();\n%}\n%\\end{code}\n\nFinally, to start the game, we need to divide the deck into two equal parts.\nWe can do that with \\java{subdeck} from Section~\\ref{subdeck} and a new method, \\java{addDeck}:\n\n\\begin{code}\npublic void addDeck(Deck deck) {\n    for (Card card : deck.getCards()) {\n        this.cards.add(card);\n    }\n}\n\\end{code}\n\n\\java{addDeck} takes a \\java{Deck} object, loops through the cards, and adds them to the \\java{Pile}.\nNotice that it does not remove the cards from the \\java{Deck}, so the \\java{Deck} and the \\java{Pile} share cards.\nBut that won't be a problem because cards are immutable.\n\n\n\\section{Playing War}\n\nNow we can use \\java{Deck} and \\java{Pile} to implement the game.\nWe'll start by creating a deck and shuffling:\n\n\\begin{code}\nDeck deck = new Deck();\ndeck.shuffle();\n\\end{code}\n\nThen we divide the \\java{Deck} into two piles:\n\n\\begin{code}\nPile p1 = new Pile();\np1.addDeck(deck.subdeck(0, 25));\n\nPile p2 = new Pile();\np2.addDeck(deck.subdeck(26, 51));\n\\end{code}\n\nThe game itself is a loop that repeats until one of the piles is empty.\nAt each iteration, we draw a card from each pile and compare their ranks.\n\n\\begin{code}\nwhile (!p1.isEmpty() && !p2.isEmpty()) {\n    // pop a card from each pile\n    Card c1 = p1.popCard();\n    Card c2 = p2.popCard();\n\n    // compare the cards ignoring suit\n    int diff = c1.getRank() - c2.getRank();\n    if (diff > 0) {\n        p1.addCard(c1);\n        p1.addCard(c2);\n    } else if (diff < 0) {\n        p2.addCard(c1);\n        p2.addCard(c2);\n    } else {  \n        // it's a tie\n    }\n\\end{code}\n\nIf the two cards have the same rank, it's a tie.\nIn that case, each player draws four more cards.\nWhoever has the higher fourth card takes all cards in play.\nIf there's another tie, they draw another four cards, and so on.\n\nOne of the exercises at the end of this chapter asks you to implement the \\java{else} block when there's a tie.\n\nAfter the \\java{while} loop ends, we display the winner based on which pile is not empty.\n\n\\begin{code}\nif (p2.isEmpty()) {\n    System.out.println(\"Player 1 wins!\");\n} else {\n    System.out.println(\"Player 2 wins!\");\n}\n\\end{code}\n\n\\java{ArrayList} provides many other methods that we didn't use for this example.\nTake a minute to read the documentation, which you can find by doing a web search for ``Java ArrayList''.\n\n\n\\section{Vocabulary}\n\n\\begin{description}\n\n\\term{pseudocode}\nA way of designing programs by writing rough drafts in a combination of English and Java.\n\n\\term{helper method}\nA method that implements part of a more complex algorithm; often it is not particularly useful on its own.\n\n\\term{top-down design}\nBreaking down a problem into sub-problems, and solving each sub-problem one at a time.\n\n\\term{selection sort}\nA simple sorting algorithm that searches for the smallest or largest element $n$ times.\n\n\\term{merge sort}\nA recursive sorting algorithm that divides an array into two parts, sorts each part (using merge sort), and merges the results.\n\n\\term{off-by-one}\nA common programming mistake that results in iterating one time too many, or too few.\n\n\\term{static context}\nThe parts of a class that run without reference to a specific instance of the class.\n\n\\term{collection}\nA Java library class, like \\java{ArrayList}, that represents a group of objects.\n\n\\term{wrapper method}\nA method that calls another method without doing much additional work.\n\n%\\term{insertion sort}\n%Another sorting algorithm that inserts elements into place, one at a time.\n\n\\end{description}\n\n\n\\section{Exercises}\n\nThe code for this chapter is in the {\\tt ch13} directory of {\\tt ThinkJavaCode2}.\nSee page~\\pageref{code} for instructions on how to download the repository.\nBefore you start the exercises, we recommend that you compile and run the examples.\n\n\n\\begin{exercise}  %%V6 Ex13.5\n\nWrite a \\java{toString} method for the \\java{Deck} class.\nIt should return a single string that represents the cards in the deck.\nWhen it's printed, this string should display the same results as the \\java{print} method in Section~\\ref{deck}.\n\n\\index{StringBuilder}\n\\index{efficiency}\n\n{\\it Hint:} You can use the \\java{+} operator to concatenate strings, but it is not very efficient.\nConsider using \\java{java.lang.StringBuilder} instead; see Section~\\ref{stringbuilder}.\n\n\\end{exercise}\n\n\n\\begin{exercise}  %%V6 Ex13.2\n\\label{ex.shuffle}\n\nThe goal of this exercise is to implement the shuffling algorithm from this chapter.\n\n\\begin{enumerate}\n\n% TODO: Do we need to clarify the instructons for finding the starter code?\n\n\\item In the repository for this book, you should find the file named {\\tt Deck.java}.\nCheck that you can compile it in your environment.\n\n\\item Implement the \\java{randomInt} method.\nYou can use the \\java{nextInt} method provided by \\java{java.util.Random}, which we saw in Section~\\ref{random}.\n\n{\\it Hint:} To avoid creating a \\java{Random} object every time \\java{randomInt} is invoked, consider defining a class variable.\n\n\\item Write a \\java{swapCards} method that takes two indexes and swaps the cards at the given locations.\n\n\\item Fill in the \\java{shuffle} method using the algorithm in Section~\\ref{shuffle}.\n\n\\end{enumerate}\n\n\\end{exercise}\n\n\n\\begin{exercise}  %%V6 Ex13.3\n\nThe goal of this exercise is to implement the sorting algorithms from this chapter.\nUse the {\\tt Deck.java} file from the previous exercise, or create a new one from scratch.\n\n% TODO: Again, we could provide clearer instructions for setting up the exercises.\n\n\\begin{enumerate}\n\n\\item Implement the \\java{indexLowest} method.\nUse the \\java{Card.compareTo} method to find the lowest card in a given range of the deck, from \\java{lowIndex} to \\java{highIndex}, including both.\n\n\\item Fill in \\java{selectionSort} using the algorithm in Section~\\ref{sorting}.\n\n\\item Using the pseudocode in Section~\\ref{mergesort}, implement the \\java{merge} method.\nThe best way to test it is to build and shuffle a deck.\nThen use \\java{subdeck} to form two small subdecks, and use selection sort to sort them.\nFinally, pass the two halves to \\java{merge} and see if it works.\n\\index{testing}\n\n\\item Fill in \\java{almostMergeSort}, which divides the deck in half, then uses \\java{selectionSort} to sort the two halves, and uses \\java{merge} to create a new, sorted deck.\nYou should be able to reuse code from the previous step.\n\n\\item Implement \\java{mergeSort} recursively.\nRemember that \\java{selectionSort} is a modifier and \\java{mergeSort} is a pure method, which means that they get invoked differently:\n\n\\begin{code}\ndeck.selectionSort();      // modifies an existing deck\ndeck = deck.mergeSort();   // replaces old deck with new\n\\end{code}\n\n\\end{enumerate}\n\n\\end{exercise}\n\n\n\\begin{exercise}\n\n%%V6 Ex13.1\nYou can learn more about the sorting algorithms presented in this chapter at \\url{https://www.toptal.com/developers/sorting-algorithms}.\nThis site provides explanations of the algorithms, along with animations that show how they work.\nIt also includes an analysis of their efficiency.\n\n%%V6 Ex13.4\nFor example, ``insertion sort'' is an algorithm that inserts elements into place, one at a time.\nRead about it on the website and play the animations.\nThen write a method named \\java{insertionSort} that implements this algorithm.\n\nOne goal of this exercise is to practice top-down design.\nYour solution should use a helper method, named \\java{insert}, that implements the inner loop of the algorithm.\n\\java{insertionSort} should invoke this method $n-1$ times.\n\n\n\\end{exercise}\n\n\n\\begin{exercise}  %%V6.5 NEW\n\n%TODO: Clarify setup instructions\n\nFind and open the file \\java{War.java} in the repository.\nThe \\java{main} method contains all the code from the last section of this chapter.\nCheck that you can compile and run this code before proceeding.\n\nThe program is incomplete; it does not handle the case when two cards have the same rank.\nFinish implementing the \\java{main} method, beginning at the line that says: \\java{// it's a tie}.\n\nWhen there's a tie, draw three cards from each pile and store them in a collection, along with the original two.\nThen draw one more card from each pile and compare them.\nWhoever wins the tie takes all ten of these cards.\n\nIf one pile does not have at least four cards, the game ends immediately.\nIf a tie ends with a tie, draw three more cards, and so on.\n\nNotice that this program depends on \\java{Deck.shuffle} so you might have to do Exercise~\\ref{ex.shuffle} first.\n\n\\end{exercise}\n\n", "meta": {"hexsha": "38a271e51c0288a223d3fbb8331bb4aaefd5722f", "size": 30936, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ch13.tex", "max_stars_repo_name": "StevenLRichardson/ThinkJava2Trinket", "max_stars_repo_head_hexsha": "540f35463dbab881cf2557553e93df28b37a4f32", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-29T10:05:31.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-29T10:05:31.000Z", "max_issues_repo_path": "ch13.tex", "max_issues_repo_name": "StevenLRichardson/ThinkJava2Trinket", "max_issues_repo_head_hexsha": "540f35463dbab881cf2557553e93df28b37a4f32", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch13.tex", "max_forks_repo_name": "StevenLRichardson/ThinkJava2Trinket", "max_forks_repo_head_hexsha": "540f35463dbab881cf2557553e93df28b37a4f32", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1401869159, "max_line_length": 228, "alphanum_fraction": 0.7350336178, "num_tokens": 7858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.3345838170744818}}
{"text": "\\documentclass[onecolumn]{paper}\n\\usepackage{tabularx}\n\\usepackage{color}\n\\begin{document}\n\t\t\n\t\t\\section{Unequal Probabilities After Crash and Encryption}\n\t\t\n\t\tConsider following scenario:\n\t\t\n\t\t1) There are two equivalent states: Both logs are empty but residual blocks are $b_1$ and $b_2$.\n\t\t\n\t\t2) User attempts to write $b_1$.\n\t\t\n\t\t3) Crash happens after write but before sync.\n\t\t\n\t\t4) After reboot, new header is persisted but the new block didn't.\n\t\t\n\t\t5) After recovery, one state has empty log, and other has a valid transaction.\\\\\n\t\t\n\t\t{\\bf Why didn't we encounter this during proofs?}\n\t\t\n\t\tThis dichotomy will manifest itself in refinement of abstract tokens.\n\t\t\n\t\tFirst state will require abstract token to be CrashAfter since transaction is committed after recovery.\n\t\t\n\t\tSecond state will require abstract token to be CrashBefore since transaction is rolled back after recovery.\n\t\t\n\t\tThis conflict would appear in the proof of two abstract tokens refined from two related states being the same.\n\t\t\n\t\tI didn't encounter this because I didn't do that proof yet. If I attempted, it probably wouldn't go through.\\\\\n\t\t\n\t\t{\\bf How can we solve this?}\\\\\n\t\tWhat needs to be fixed is that, with the same reboot function, both states either should roll back or keep the transaction.\n\t\tAbove requirement means that, there shouldn't be a case where newly written block to log is exactly equal to the already existing block.\n\t\tThere are two ways to achieve this:\\\\\n\t\t\n\t\t1) Design a log that {\\bf guarantees} that requirement.\n\t\t\n\t\tI did it back in the day but it was very complicated. I expect it to be practically infeasible to reason about that log. That is why we didn't pursue this. \n\t\tCould be an interesting side project though.\\\\\n\t\t\n\t\t2) Design a log where this case is an {\\bf exponentially unlikely} event. \n\t\tThis makes it reasonable to exclude such cases from our proofs.\n\t\t\n\t\tThis is the approach we take with hash collisions and encryption achieves this.\n\t\tIf we encrypt each transaction with a fresh key, above situation only happens when $encrypt(k_1, b_1) = encrypt (k_2, b_2)$ where $k_1 \\ne k_2$. This is exponentially unlikely as far as I am aware.\\\\\n\t\t\n\t\t{\\bf How can we capture this?}\\\\\t\t\n\t\tWe can't introduce an axiom that says \n\t\t\n\t\t$\\forall\\ k_1\\ k_2\\ b_1\\ b_2,\\ k_1 \\ne k_2 \\rightarrow encrypt(k_1, b_1) \\ne encrypt(k_2, b_2)$\\\\\n\t\t\n\t\tAt first glance it looks fine because key and block are abstract types. \n\t\tTherefore you can't construct an example where $k_1 \\ne k_2\\ \\wedge\\ encrypt(k_1, b_1) = encrypt(k_2, b_2)$ which would allow you to prove False.\n\t\t \n\t\tStill, this isn't kosher because it makes our model not fit the world. There is no such encrypt function that satisfies the above axiom. Assuming it would make our proofs meaningless, since they are not about our world anymore.\\\\\n\t\t\n\t\tAnother way to achieve it is how we achieved it with hashing. Keep a record of each encryption done, when you see a collision like above, let program get stuck. This is the implementation I had before, which I scrapped recently. \n\t\t\n\t\tThis was also the reason why our GetKey was weird. We needed to know that there won't be a collision when we encrypt our data with the generated key. I could be able to get rid of that weirdness thanks to we moving to simulations from bisimulations.\n\t\tBisimulations required total correctness, simulations require partial correctness.\\\\\n\t\t\n\t\tAlthough above approach plays nice with 95\\% of the project, it has a problem with write/extend special case NI proofs' transfer.\n\t\tOne requirements of the transfer lemma for spacial case is \"if $s_1$ and $s_2$ are equivalent states and you can run $write(a, b_1)$ from $s_1$, then you can run $write(a, b_2)$ from $s_2$ with the same oracle.\"\n\t\t\n\t\tTo show that you can run $write(a, b_2)$ from $s_2$, you need to prove that there won't be any collision when you encrypt $b_2$ with a newly generated key. It is the same key that is generated in $write(a, b_1)$, since the oracles are the same.\n\t\t\n\t\tSuccess of first execution gives you the fact that there is no collision when you encrypt $b_1$. However, there is no way to prove from the stated fact that there won't be a collision when you encrypt $b_2$. This will prevent you from proving the desired property.\\\\\n\t\t\n\t\t{\\bf I currently have no solution to this. I will keep thinking and keep you updated about it. If anything comes to your mind, please let me know.}\\\\\n\t\t \n\t\t{\\color{red} \\bf Nickolai:} Thanks, I think the problem makes more sense now.\n\t\tIn terms of how to solve it..  What about putting the ciphertext into the oracle when encrypt is invoked?\n\t\tWhat I mean is..  When the application calls encrypt(), you choose a ciphertext non-deterministically (i.e., through the oracle).  This gives you the freedom to, in the proof, manipulate the ciphertext chosen for any particular encryption.\n\t\tIf you had this degree of freedom, then, when proving this case, you could demonstrate a second execution by showing another choice of encrypted result in the other oracle, so that the execution of the recovery code goes down the same path.\n\t\tThat is, if in execution 1 you saw encrypt(k1, b1) = encrypt(k2, b2), then you can make it also be equal in execution 2.\n\t\tAnd similarly if you saw the two encryptions be non-equal in execution 1, you can make them be non-equal in execution 2.\n\t\tThe only constraint on this new oracle feature is that you can't choose colliding ciphertexts.\n\t\tThis means that, to give you this necessary degree of freedom, you have to choose fresh keys often enough so that you're never constrained too much by prior encryptions.\\\\\n\t\t\n\t\t{\\color{blue} \\bf Atalay:} This may not work due to following problem.\n\t\t\n\t\tFramework requires oracles to be independent of the confidential data. This means you should be able to execute $write(a, b_1)$ from $s_1$, and $write(a, b_2)$ from $s_2$ with the same oracle. If oracle supplies the fresh key and the ciphertext, then it will be encrypt(k, b1) = encrypt(k, b2). Only way this being true is that, somehow, encrypt function of $s_1$ is different than one in $s_2$. I am not entirely sure what this entails and can this difference be a source of leakage.\n\t\t\n\t\t\n\t\t\\subsection{Oracle Chosen Ciphertext Approach}\n\t\tThe system (lowest layer) allows encrypting at most one block (plaintext) with a particular key.  The state tracks key $\\rightarrow$ option (plaintext * ciphertext) for this purpose.  If this mapping contains None for some key, then calling encrypt(key, plaintext) chooses a random ciphertext (supplied by the oracle) and puts Some (plaintext, ciphertext) into that state under the corresponding key.\n\t\t\n\t\tIf this mapping contains Some \\_, it's not legal to call encrypt anymore for that key.  So, for that matter, keygen() and encrypt() can be combined, so that this combined function returns the fresh key and the ciphertext all at once.\n\t\t\n\t\tdecrypt(key, ciphertext) can be called only if that mapping contains precisely that ciphertext for that key, in which case it returns the corresponding plaintext.  Otherwise, calling decrypt is not allowed (if the mapping is None or contains some other ciphertext).\n\t\t\n\t\tThe implication of this model of encryption is that two blocks (b1 and b2) will have precisely the same ciphertext (supplied by the identical oracle) in the two executions, if these blocks are encrypted with the same key.\n\t\t\n\t\tTo achieve the constraint of at most one block (plaintext) per key, I'm thinking the file system generates a fresh key every time it needs to encrypt a block.  Whenever the file system needs to write some block to the log, it encrypts it with a fresh key, and stores the key wherever it's already storing the address that goes along with this block.  On recovery, decrypting blocks is straightforward: just use each block's key, after validating that these are indeed the correct blocks (i.e., hash matches).\n\t\t\n\t\tIn practice, it might be a bit silly to generate a fresh key for each block, so a realistic implementation would probably use the same key but a fresh IV (based on a monotonically increasing counter) for each block.\n\t\t\n\t\tIt might even be worth modeling that IV-based optimization, because it would allow the file system to not store a separate key for each block in the log, and instead just have the header store the key and the first sequence number for the logged blocks.  This way, on recovery, the file system code will decrypt using sequence numbers starting from the first one, and it doesn't require additional per-block overhead for a key or IV.\n\t\tBut I think this \"in practice\" comment is just an optimization if the idea above makes sense.\\\\\n\t\t\n\t\t{\\bf All possible histories are related problem}\n\t\t\n\t\tThink our FS but abstractions are \"collapsed\". So there is base layers (disk, crypto etc.) And a single layer of abstraction above the entire implementation (file disk).\n\t\t\n\t\tSince file disk doesn't have a notion of encryption, base layer states with different \"encryption histories\" will refine the same file disk. More precisely, any combination of \"chosen ciphertexts\" as the history will be a valid refinement.\n\t\t\n\t\tThis means no matter what the oracle chooses as ciphertext for the result of the new encryption, there will be two related states where it will cause a collision in only one of them.\n\t\t\n\t\tI think above example is a strong evidence of why \"ciphertext choosing\" approaches may not work.\n\t\tNo matter what the choice is, there will be a related state where it is used.\n\t\t\n\t\t\\subsection{Excluding Colliding Oracles Approach}\n\t\tAnother approach we can take is excluding series of events that leads to a collision in encryption from our theorems. Similar to hashing, our theorems will have a condition that say \"if there is no collisions, ...\" To justify this approach, probability of it happening should be exponentially low.\n\t\t{\\color{red} I don't know the probability of it yet.} \n\t\t\n\t\tIf probability is not low enough, then we can add a scheme where encryption history only consists of last (2 * \\# of blocks in the log) encryption results. It is an upper bound on how many blocks can be on the disk at any given time. Since this is much much smaller than possible combinations, I think it would be justifiable to assume such collision won't appear on the log.\n\t\t\n\t\tApart from that, plan is same with hashing. System keeps track of encryption results and if it sees a collision, it gets stuck.\n\t\n\t\tOur premise will look like this:\n\t\t\\begin{verbatim}\n\t\t\t(forall k, In (NewKey k) oracle -> (encrypt k v2) doesn't collide in s2) ->\n\t\t\tNI statement for (write a v1, write a v2) holds.\n\t\t\\end{verbatim} \n\n\\end{document}\n", "meta": {"hexsha": "4817f642a4baeb2bcaa315db1e9d776dcde71998", "size": 10635, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "writing/encryption-discussion.tex", "max_stars_repo_name": "Atalay-Ileri/Disksec-Doc", "max_stars_repo_head_hexsha": "28befcf9571b0308bcabd229ab6dcba8acb6c503", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "writing/encryption-discussion.tex", "max_issues_repo_name": "Atalay-Ileri/Disksec-Doc", "max_issues_repo_head_hexsha": "28befcf9571b0308bcabd229ab6dcba8acb6c503", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "writing/encryption-discussion.tex", "max_forks_repo_name": "Atalay-Ileri/Disksec-Doc", "max_forks_repo_head_hexsha": "28befcf9571b0308bcabd229ab6dcba8acb6c503", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 83.0859375, "max_line_length": 510, "alphanum_fraction": 0.7590973202, "num_tokens": 2546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3345838170744818}}
{"text": "\\section{Theory: Angle-Informed Importance Maps for CADIS and FW-CADIS}\n\\label{sec:methodtheory}\n\nThere exist methods to generate\nvariance reduction parameters\nfor deep penetration radiation transport problems with strong anisotropy in the\nflux. These methods have shown to have varying success, and may not be fully\nautomated. The solution proposed in this dissertation is a formulation that we\nhave named the $\\Omega$-CADIS-methods. This section will commence with a brief\ndiscussion of the foundational research\non which the $\\Omega$-CADIS-methods are built.\nThat discussion serves as a primer for the subsequent section, which\nis an introduction to the $\\Omega$-CADIS-methods and a discussion on how they differ\nfrom their predecessors.\n\n\\subsection{Previous Work}\n\\label{sec:omegabknd}\n\nAs discussed in Sections \\ref{sec:CADIS}\nthrough \\ref{sec:AngleVR}, the existing gold standard for automatically\ngenerating variance reduction parameters for deep penetration\nfixed-source radiation transport problems are\nCADIS and FW-CADIS. Both of these methods are very effective at\ngenerating variance reduction parameters for local and global solutions,\nrespectively. However, CADIS and FW-CADIS have only been implemented\nto perform variance reduction in\nspace and energy, not angle. As a result, solutions for problems with\nstrong anisotropy in the flux are not always optimized with these methods,\nresulting in slow convergence times and low FOM values.\nProblems with strong anisotropies in the flux require more than just\nspace- and energy- variance reduction techniques.\nA number of angle-informed variance reduction methods have been\ninvestigated, most notably AVATAR, LIFT, and a modified version of\nCADIS using AVATAR-type angular parameters.\n\nLIFT, AVATAR, and Simple Angular CADIS all showed that by including angular\ninformation into Monte Carlo variance reduction parameters the FOM can be\nimproved. However, none of these methods used the actual angular flux to\ncalculate the variance reduction parameters for the problem they were\noptimizing. Without explicitly using the angular flux solutions they were\nlimited in which types of problems they were applicable, because some assumption\nof the degree of anisotropy of the flux was made. Further, LIFT and\nSimple Angular CADIS showed that by including substantial angular biasing in the\nweight windows in problems where the approximation to the angular flux is not\nsufficient, the FOM can decrease not unsubstantially, defeating the purpose of using\nthese methods.\n\n\\subsection{The $\\Omega$ Methods}\n\\label{sec:omegaintro}\n\nThe foundation of the $\\Omega$-methods is built upon CADIS and FW-CADIS. As with\nboth methods,\nthe $\\Omega$-methods will use a version of the adjoint scalar flux to\nconsistently bias a Monte Carlo problem with the intention of reducing the\nvariance. In Section \\ref{sec:Importance} the concept of importance was\nintroduced. Notably, it was shown that the adjoint flux is a good marker\nfor the likelihood of particles to contribute to a tally, which is the\nparticle's importance. It was also shown that the\nproduct of the forward and adjoint fluxes generates a pseudo-particle flux called\nthe contributon flux, where contributons are ``importance particles''.\nThese importance particles can be used to show preferential flow paths from a\nsource to a tally or desired location.\n\nBy using a version of the adjoint scalar flux that has been formulated with the\ncontributon flux, the direction of particle flow will be incorporated into the\nimportance map and, consequently, the\nvariance reduction parameters. By using this variant of the adjoint scalar flux,\nthe method, like traditional CADIS, will show increasing importance as the\nparticles travel near the adjoint source. However, because this variant of the adjoint\nflux incorporates directionality of the particle flow, not all regions near the\nadjoint source are equally important. In this way, the adjusted flux\nincorporates features from both the adjoint- and contributon- fluxes.\n\nThe adjusted adjoint scalar flux quantity, or the $\\Omega$-adjoint\nscalar flux, is\n%\n\\begin{equation}\n  \\phi^{\\dagger}_{\\Omega}(\\vec {r} ,E)  = \\frac{\\int_{\\Omega}{\\psi^{\\dagger}\n                             (\\vec{r}, E, \\hat\\Omega)\n                             \\psi(\\vec{r}, E, \\hat\\Omega)} d\\hat{\\Omega}}\n                             {\\int_{\\Omega}\\psi(\\vec{r}, E, \\hat\\Omega)\n                             d\\hat{\\Omega}}.\n\\label{eq:omega_basic}\n\\end{equation}\n%\nThe $\\Omega$-flux is a hybridization of the adjoint scalar flux and the contributon\nflux. It is both a normalized contributon flux and a forward-weighted\nadjoint flux. As a result, it should inherit some of the advantages of\neach of the traditional\nadjoint and the contributon fluxes. Because it maintains dimensionality of the\ntraditional adjoint scalar flux, it can be used in place of the standard adjoint\nscalar flux in both\nCADIS and FW-CADIS variance reduction parameter generation.\nThis means that the method can capitalize on existing infrastructure used to\ngenerate variance reduction parameters for CADIS and FW-CADIS, and only the\nsoftware handling the transport and flux-generation requires modification.\n\n\\subsubsection{CADIS-$\\Omega$}\n\\label{sec:cadomega}\n\nAs with CADIS, CADIS-$\\Omega$ consistently biases a problem's source and\nparticle weights according to their importance. However, CADIS-$\\Omega$\nuses the\n$\\Omega$-adjoint scalar flux rather than the standard adjoint scalar flux\nto generate the biased source distribution, weight windows,\nand the particle birth weights. Furthermore, because $\\phi_{\\Omega}^{\\dagger}$\nis used to calculate these values in CADIS-$\\Omega$,\nthe consistent-biasing hallmark for\nwhich CADIS is known is maintained.\nThe adjusted\nformulation of CADIS using the $\\Omega$ fluxes is given by Eqs.\n\\eqref{eq:CADISomegamethod}.\n%\n\\begin{subequations}\n\\label{eq:CADISomegamethod}\n%\nThe biased source distribution used by CADIS-$\\Omega$ is formulated just as it\nis in CADIS, except the adjusted adjoint fluxes are used:\n\\begin{equation}\n\\begin{split}\n  \\hat{q}_{\\Omega}  & = \\frac{\\phi_{\\Omega}^{\\dagger}(\\vec {r} ,E)q(\\vec {r} ,E)}\n               {\\iint\\phi_{\\Omega}^{\\dagger}(\\vec {r} ,E)\n               q(\\vec {r} ,E) dE d\\vec{r}} \\\\\n               & = \\frac{\\phi_{\\Omega}^{\\dagger}(\\vec {r} ,E)q(\\vec {r},E)}\n               {R_{\\Omega}}.\n\\end{split}\n\\end{equation}\n%\nThe  starting weights of the particles sampled from the\nbiased source distribution, $\\hat{q}$ are given by\n\\begin{equation}\n\\begin{split}\n  w_{0, \\Omega}  & = \\frac{q}{\\hat{q}_{\\Omega}} \\\\\n  & = \\frac{R_{\\Omega}}{\\phi_{\\Omega}^{\\dagger}(\\vec {r} ,E)} ,\n\\end{split}\n\\end{equation}\n%\nand the new target weights for the particle are\n\\begin{equation}\n  \\hat{w}_{\\Omega} = \\frac{R_{\\Omega}}{\\phi_{\\Omega}^{\\dagger}(\\vec{r} ,E)} .\n\\end{equation}\n\\label{eq:cadomega_eqns}\n\\end{subequations}\n\n\\subsubsection{FW-CADIS-$\\Omega$}\n\\label{sec:fwcadomega}\n\nFW-CADIS differs from CADIS in that it requires a forward deterministic\ncalculation to generate $q^{\\dagger}$, which is used as the source distribution\nin the adjoint deterministic problem (recall that CADIS sets\n$q^{\\dagger}=\\sigma_d$). Depending on the type of global\nresponse desired, FW-CADIS runs a deterministic forward calculation to\napproximate the global response in the problem. The inverse of these responses\nis then used to generate the biased adjoint source distribution for the adjoint\ndeterministic run. Therefore, the behavior of FW-CADIS-$\\Omega$\nin the forward biasing\nportion of the calculation will remain unchanged from FW-CADIS.\n%\n\\begin{subequations}\nThe generalized form for the adjoint source definition is given by the fraction\nof the response in a region of phase space, $P$, over the total response in the\nproblem, or\n\\begin{equation*}\n  { q^{\\dagger}_{\\Omega}} (P) = { q^{\\dagger}} (P)=\\frac{\\sigma_d(P)}{R} .\n\\end{equation*}\n%\nWhen applied to the spatially-dependent global dose, $\\int\n\\phi(\\vec{r},E)\\sigma_d(\\vec{r},E) dE$, the adjoint source will be\n\\begin{equation*}\n  { q^{\\dagger}_{\\Omega} }(\\vec { r } ,E) = { q^{\\dagger} }(\\vec { r } ,E)\n  =\\frac { \\sigma _{ d }(\\vec { r } ,E) }{ \\int {\n  \\sigma _{ d }(\\vec { r } ,E)\\psi (\\vec { r } ,E,) } dE } .\n\\end{equation*}\n%\nThe adjoint source for the spatially-dependent total flux $\\int \\phi(\\vec{r},E)\ndE $ is\n\\begin{equation*}\n  { q^{\\dagger}_{\\Omega} }(\\vec { r }) = { q^{\\dagger} }(\\vec { r })\n  =\\frac { 1 }{ \\int { \\phi (\\vec { r } ,E) } dE } .\n\\end{equation*}\n%\nThe adjoint source for the energy- and spatially-dependent flux\n$\\phi(\\vec{r},E)$ is\n\\begin{equation*}\n  { q^{\\dagger}_{\\Omega} }(\\vec { r } ,E) = { q^{\\dagger} }(\\vec { r } ,E)=\\frac { 1 }{\\phi (\\vec { r } ,E) } .\n\\end{equation*}\n\\label{eq:fwcadomega_eqns}\n\\end{subequations}\n\nOne advantage of FW-CADIS-$\\Omega$ is that, from a transport perspective, the\n$\\Omega$-method is no more expensive than standard FW-CADIS. Because both\nversions require a forward and adjoint deterministic calculation, an extra\ntransport step is not required as it is for CADIS-$\\Omega$. This is attractive,\nbut the nature of FW-CADIS might not be the most well-suited for the\n$\\Omega$-methods. Because FW-CADIS attempts to evenly distribute particles\nthroughout the problem using the forward-biased adjoint fluxes,\nthe additional forward normalization with the $\\Omega$-methods will likely skew\nthe particle distribution in the problem in the forward direction,\nand it may place too great of\nimportance on the forward-moving particles in generating the variance reduction\nparameters.\n", "meta": {"hexsha": "afe934f71e5bb985f15b15899ee4328aba25188d", "size": 9549, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/methodology/theory.tex", "max_stars_repo_name": "rachelslaybaugh/munk-disseration", "max_stars_repo_head_hexsha": "e6dc6d6a8d5613cb30bca7dc4a2d419ad1b36e65", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/methodology/theory.tex", "max_issues_repo_name": "rachelslaybaugh/munk-disseration", "max_issues_repo_head_hexsha": "e6dc6d6a8d5613cb30bca7dc4a2d419ad1b36e65", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/methodology/theory.tex", "max_forks_repo_name": "rachelslaybaugh/munk-disseration", "max_forks_repo_head_hexsha": "e6dc6d6a8d5613cb30bca7dc4a2d419ad1b36e65", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.2722772277, "max_line_length": 111, "alphanum_fraction": 0.7487695047, "num_tokens": 2519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3345421819483951}}
{"text": "% !TeX root = ../main.tex\n\n\\section{Results}\n\\subsection{Data set}\n\\begin{frame}\n    \\frametitle{Epinions data set}\n    \\vspace{-2cm}\n    \\begin{columns}\n    \\column{0.5\\textwidth}\n    \\begin{table}\n        \\centering\n        \\caption{Epinions Sample}\n        \\small\n        \\begin{tabular}{ |c|c|c| }\n            \\hline\n            \\textbf{user} & \\textbf{item} & \\textbf{Rating} \\\\\n            \\hline\n            36153 & 62461 & 5 \\\\\n            \\hline\n            427 & 38005 & 5  \\\\\n            \\hline\n            751 & 53361 & 4 \\\\\n            \\hline\n            11001 & 118950 & 4 \\\\\n            \\hline\n            1169 & 66176 & 5 \\\\\n            \\hline\n            9808 & 84459 & 2 \\\\\n            \\hline\n            85 & 7446 & 4 \\\\\n            \\hline\n            14717 & 3397 & 2 \\\\\n            \\hline\n        \\end{tabular}\n    \\end{table}\n    \\column{0.5\\textwidth}\n    \\begin{table}\n        \\centering\n        \\caption{Epinions Descriptive}\n        \\small\n        \\begin{tabular}{ |c|c|c|c| }\n            \\hline\n            &\\textbf{Ratings Matrix} & \\textbf{Train} & \\textbf{Test}\\\\\n            \\hline\n            count & 664824 & 520203 & 144621\\\\\n            \\hline\n            mean & 3.9917 & 3.99 & 3.9975\\\\\n            \\hline\n            std & 1.2068 & 1.2072 & 1.2053\\\\\n            \\hline\n            min & 1 & 1 & 1\\\\\n            \\hline\n            25\\% & 3 & 3 & 3\\\\\n            \\hline\n            50\\% & 4 & 4 & 4\\\\\n            \\hline\n            75\\% & 5 & 5 & 5\\\\\n            \\hline\n            max & 5 & 5 & 5\\\\\n            \\hline\n        \\end{tabular}\n    \\end{table}\n\\end{columns}\n\\end{frame}\n\\subsection{Evaluation Metrics}\n\\begin{frame}[t]\n    \\vspace{-1cm}\n    \\hspace{15mm}\\underline{\\textbf{Single Model}}  \\hspace{5cm}\\underline{\\textbf{Combined Models}}\n    \\frametitle{Evaluation Metrics}\n    \\begin{columns}\n    \\column{0.4\\textwidth}\n    \\begin{flalign*}\n            RMSE &= \\sqrt{\\frac{\\sum_{(u,i) \\in \\mathcal{T}(r_{u,i} - \\hat{r}_{u,i})^2}}{n}} \\\\\n            MAE  &= \\frac{\\sum_{(u,i) \\in \\mathcal{T}\\left|r_{u,i} - \\hat{r}_{u,i}\\right|}}{n} \\\\\n            RMSUE &= \\frac{1}{n}\\sum_{u \\in \\mathcal{T}}\\sqrt{\\frac{\\sum_{i \\in \\mathcal{I}_u(r_{u,i} - \\hat{r}_{u,i})^2}}{n_u}} \\\\\n            MAUE &= \\frac{1}{n}\\sum_{u \\in \\mathcal{T}}\\frac{\\sum_{i \\in \\mathcal{I}_u\\mathopen|r_{u,i} - \\hat{r}_{u,i}\\mathclose|}}{n_u}\\\\\n    \\end{flalign*}\n    \\vspace{3cm}\n    \\column{0.6\\textwidth}\n    \\small\n    \\begin{flalign*}\n        RMSE_{Total} &= \\sqrt{\\frac{n_{KNN}*RMSE_{KNN}^2 + n_{R-KNN}*RMSE_{R-KNN}^2}{n_{KNN} + n_{R-KNN}}}\\\\\n        MAE_{Total} &= \\frac{n_{KNN}*MAE_{KNN} + n_{R-KNN}*MAE_{R-KNN}}{n_{KNN} + n_{R-KNN}}\n    \\end{flalign*}\n    \\centering\n    \\footnotesize\n    \\begin{itemize}\n        \\item $\\mathcal{T}$ is the test set\n        \\item $r_{u,i}$ is the truth value of a rating for $user_u$ to $item_i$\n        \\item $\\hat{r_{u,i}}$ is the prediction value of a rating for $user_u$ to $item_i$\n        \\item $n$ is the number of rating predictions\n    \\end{itemize}\n    \\vspace{5cm}\n    \\end{columns}\n\\end{frame}\n\n\\subsection{Results}\n\\begin{frame}\n    \\frametitle{Volume of Predictions}\n    \\vspace{-1.6cm}\n    \\begin{table}\n\\centering\n\\caption{Ratings Predicted with KNN and Recursive-KNN}\n\\footnotesize\n\\begin{tabular}{ccc|ccc|c}\n\\multicolumn{3}{c|}{\\textbf{USERS}}            & \\multicolumn{3}{c|}{\\textbf{ITEMS}}            &                          \\\\ \\cline{1-6}\n\\textbf{KNN} & \\textbf{R-KNN} & \\textbf{TOTAL} & \\textbf{KNN} & \\textbf{R-KNN} & \\textbf{TOTAL} & \\textbf{SIMILARITY}      \\\\ \\hline\n88379        & 34392          & 122771         & 89800        & 33315          & 123115         & Adjusted Cosine          \\\\\n100311       & 24122          & 124433         & 100311       & 24122          & 124433         & Cosine                   \\\\\n100311       & 24122          & 124433         & 100311       & 24122          & 124433         & Jaccard                  \\\\\n93924        & 29747          & 123671         & 94528        & 29203          & 123731         & MAD                      \\\\\n93924        & 29747          & 123671         & 94528        & 29203          & 123731         & MSD                      \\\\\n88379        & 34392          & 122771         & 89800        & 33315          & 123115         & Modified Adjusted Cosine \\\\\n100311       & 24122          & 124433         & 100311       & 24122          & 124433         & Modified Cosine          \\\\\n59017        & 40470          & 99487          & 54644        & 34096          & 88740          & Modified Pearson 1       \\\\\n89936        & 28183          & 118119         & 84511        & 24357          & 108868         & Modified Pearson 2       \\\\\n89936        & 28183          & 118119         & 84511        & 24357          & 108868         & Pearson\n\\end{tabular}\n\\end{table}\n\\end{frame}\n\\begin{frame}[t]\n    \\frametitle{User-based KNN and Total RMSE}\n    \\vspace{-0.7cm}\n    \\begin{columns}\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{KNN}}\n    \\begin{figure}\n    \\centering\n    \\includegraphics[width=1\\textwidth,height=0.6\\textheight]{User_RMSE_KNN.eps}\n    \\end{figure}\n    \\centering\n    \\tiny\n    Modified cosine at K=100, RMSE=1.1479835373\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{Total}}\n    \\begin{figure}\n    \\centering\n    \\includegraphics[width=1\\textwidth,height=0.6\\textheight]{evaluation_user_rmse.eps}\n    \\end{figure}\n    \\centering\n    \\tiny\n    Modified cosine at K=100 \\& M=3, RMSE=1.1604146071\n\\end{columns}\n\\end{frame}\n\\begin{frame}[t]\n    \\frametitle{User-based KNN and Total MAE}\n        \\vspace{-0.7cm}\n        \\begin{columns}\n            \\column{0.5\\textwidth}\n            \\centering\n            \\underline{\\textbf{KNN}}\n        \\begin{figure}\n        \\centering\n        \\includegraphics[width=1\\textwidth,height=0.6\\textheight]{User_MAE_KNN.eps}\n        \\end{figure}\n        \\centering\n        \\tiny\n        Jaccard coefficient at K=50, MAE=0.8518433005\n            \\column{0.5\\textwidth}\n            \\centering\n            \\underline{\\textbf{Total}}\n        \\begin{figure}\n        \\centering\n        \\includegraphics[width=1\\textwidth,height=0.6\\textheight]{evaluation_user_mae.eps}\n        \\end{figure}\n        \\centering\n        \\tiny\n        Jaccard coefficient at K=50 \\& M=3, MAE=0.854066176\n    \\end{columns}\n\\end{frame}\n\\begin{frame}[t]\n    \\frametitle{User-based KNN and Recursive-KNN RMSUE}\n    \\vspace{-0.7cm}\n    \\begin{columns}\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{KNN}}\n    \\begin{figure}\n    \\centering\n    \\includegraphics[width=1\\textwidth,height=0.6\\textheight]{User_RMSUE_KNN.eps}\n    \\end{figure}\n    \\centering\n    \\tiny\n    Modified cosine at K=100, RMSUE=1.0031145695\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{Recursive-KNN}}\n    \\begin{figure}\n    \\centering\n    \\includegraphics[width=1\\textwidth,height=0.6\\textheight]{evaluation_user_rmsue.eps}\n    \\end{figure}\n    \\centering\n    \\tiny\n    Modified cosine at K=100 \\& M=3, RMSUE=0.9089525549\n\\end{columns}\n\\end{frame}\n\\begin{frame}[t]\n    \\frametitle{User-based KNN and Recursive-KNN MAUE}\n    \\vspace{-0.7cm}\n    \\begin{columns}\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{KNN}}\n    \\begin{figure}\n    \\centering\n    \\includegraphics[width=1\\textwidth,height=0.6\\textheight]{User_MAUE_KNN.eps}\n    \\end{figure}\n    \\centering\n    \\tiny\n    Cosine similarity at K=50, MAUE=0.8819077974\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{Recursive-KNN}}\n    \\begin{figure}\n    \\centering\n    \\includegraphics[width=1\\textwidth,height=0.6\\textheight]{evaluation_user_maue.eps}\n    \\end{figure}\n    \\centering\n    \\tiny\n    Adjusted cosine at K=75 \\& M=20, MAUE=0.8558869566\n\\end{columns}\n\\end{frame}\n\\begin{frame}[t]\n    \\frametitle{Item-based KNN and Total RMSE}\n    \\vspace{-0.7cm}\n    \\begin{columns}\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{KNN}}\n    \\begin{figure}\n    \\centering\n    \\includegraphics[width=1\\textwidth,height=0.6\\textheight]{Item_RMSE_KNN.eps}\n    \\end{figure}\n    \\centering\n    \\tiny\n    Adjusted cosine at K=95, RMSE=1.2984970982\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{Total}}\n    \\begin{figure}\n    \\centering\n    \\includegraphics[width=1\\textwidth,height=0.6\\textheight]{evaluation_item_rmse.eps}\n    \\end{figure}\n    \\centering\n    \\tiny\n    Adjusted cosine at K=100 \\& M=3, RMSE=1.3155259043\n\\end{columns}\n\\end{frame}\n\\begin{frame}[t]\n    \\frametitle{Item-based KNN and Total MAE}\n        \\vspace{-0.7cm}\n        \\begin{columns}\n            \\column{0.5\\textwidth}\n            \\centering\n            \\underline{\\textbf{KNN}}\n        \\begin{figure}\n        \\centering\n        \\includegraphics[width=1\\textwidth,height=0.6\\textheight]{Item_MAE_KNN.eps}\n        \\end{figure}\n        \\centering\n        \\tiny\n        Modified adjusted cosine at K=15, MAE=0.9499219326\n            \\column{0.5\\textwidth}\n            \\centering\n            \\underline{\\textbf{Total}}\n        \\begin{figure}\n        \\centering\n        \\includegraphics[width=1\\textwidth,height=0.6\\textheight]{evaluation_item_mae.eps}\n        \\end{figure}\n        \\centering\n        \\tiny\n        Adjusted cosine at K=100 \\& M=3, MAE=0.9707211649\n    \\end{columns}\n\\end{frame}\n\\begin{frame}[t]\n    \\frametitle{Item-based KNN and Recursive-KNN RMSUE}\n    \\vspace{-0.7cm}\n    \\begin{columns}\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{KNN}}\n    \\begin{figure}\n    \\centering\n    \\includegraphics[width=1\\textwidth,height=0.6\\textheight]{Item_RMSUE_KNN.eps}\n    \\end{figure}\n    \\centering\n    \\tiny\n    Adjusted cosine at K=100, RMSUE=1.0328968801\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{Recursive-KNN}}\n    \\begin{figure}\n    \\centering\n    \\includegraphics[width=1\\textwidth,height=0.6\\textheight]{evaluation_item_rmsue.eps}\n    \\end{figure}\n    \\centering\n    \\tiny\n    Adjusted cosine at K=100 \\& M=3, RMSUE=1.0367245756\n\\end{columns}\n\\end{frame}\n\\begin{frame}[t]\n    \\frametitle{Item-based KNN and Recursive-KNN MAUE}\n    \\vspace{-0.7cm}\n    \\begin{columns}\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{KNN}}\n    \\begin{figure}\n    \\centering\n    \\includegraphics[width=1\\textwidth,height=0.6\\textheight]{Item_MAUE_KNN.eps}\n    \\end{figure}\n    \\centering\n    \\tiny\n    Modified adjusted cosine at K=30, MAUE=0.9318609947\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{Recursive-KNN}}\n    \\begin{figure}\n    \\centering\n    \\includegraphics[width=1\\textwidth,height=0.6\\textheight]{evaluation_item_maue.eps}\n    \\end{figure}\n    \\centering\n    \\tiny\n    Adjusted cosine at K=90 \\& M=3, MAUE=0.9864005988\n\\end{columns}\n\\end{frame}\n", "meta": {"hexsha": "a680bf208ce67ef70877ce967199bc769d3d9586", "size": 10872, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "dipoma_presentation/sections/section_4.tex", "max_stars_repo_name": "tseste/Recursive-K-Nearest-Neighbors", "max_stars_repo_head_hexsha": "5e35c643dc8c530102554492c56bfcf05b242298", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-06T16:08:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T16:08:44.000Z", "max_issues_repo_path": "dipoma_presentation/sections/section_4.tex", "max_issues_repo_name": "tseste/Recursive-K-Nearest-Neighbors", "max_issues_repo_head_hexsha": "5e35c643dc8c530102554492c56bfcf05b242298", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dipoma_presentation/sections/section_4.tex", "max_forks_repo_name": "tseste/Recursive-K-Nearest-Neighbors", "max_forks_repo_head_hexsha": "5e35c643dc8c530102554492c56bfcf05b242298", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0455927052, "max_line_length": 139, "alphanum_fraction": 0.554727741, "num_tokens": 3679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.3345421819483951}}
{"text": "%!TEX root = ../data-imputation.tex\n\\section{Discussion}\n\\label{sec:discussion}\n\nWe investigated the performance of classical and modern imputation approaches on a large number of heterogeneous data sets under realistic conditions. In the following, we highlight some of the key findings.\n\n\\subsection{Simpler Imputation Methods Yield Competitive Results}\n%\nWhen evaluating imputation quality, our results demonstrate that simple supervised learning methods achieve competitive results, and in many cases, outperform modern generative deep learning-based approaches. In particular, in the MCAR and MAR setting, we see in Figures \\ref{fig:fully_observed_impute_rank_boxplot} and \\ref{fig:corrupted_impute_rank_boxplot} that $k$-NN, random forest, and the discriminative DL approach are, for at least $50\\%$ of the cases, among the better ranks one, two, or three. Random forest tends to achieve the best rank more often. This effect is largely independent of whether the imputation methods are trained on complete or incomplete data.\n\nThis finding is in line with \\cite{Imputation_Benchmark_3, Imputation_Benchmark_2, Imputation_Benchmark_4}. In these previous studies, the authors report that $k$-NN imputation is the best choice in most situations. However, \\cite{Imputation_Benchmark_2, Imputation_Benchmark_4} did not incorporate a random forest imputation method. Other comparisons show a slight advantage of discriminative deep learning methods over random forests \\citep{biessmann2019datawig}, but these experiments were conducted on a much smaller selection of data sets.\n\nFor categorical columns (see Figure \\ref{fig:fully_observed_impute_rank_boxplot} and \\ref{fig:corrupted_impute_rank_boxplot}, upper row) in the more challenging imputation settings MAR or MNAR with large missingness fractions, the mean/mode imputation tends to achieve better ranks. This effect can be attributed to the fact that the sets of observed categorical values often have small cardinality. Especially for skewed distributions, using the most frequent value to substitute missing values is a good approximation of the ground truth. If the training data contains a large fraction of missing values, the underlying dependencies exploited by learning algorithms are difficult to capture. For this reason, mean/mode scores for higher MNAR missing values in $75\\%$ of the cases on rank two or better (visualized in Figure \\ref{fig:corrupted_impute_rank_boxplot}). \\cite{Imputation_Benchmark_3} did not explicitly calculate the ranks but their plots show the same tendency.\n\nSince GAIN failed in about $33\\%$ of settings when training data was complete, this could be a reason why, in most cases, GAIN achieves the worst ranks (see Figure \\ref{fig:fully_observed_impute_rank_boxplot}). This is supported by the fact that GAIN does not fail for settings with incomplete training data, and often shows better ranks (see Figure \\ref{fig:corrupted_impute_rank_boxplot}).\n\nAll in all, using random forest, discriminate DL, or $k$-NN are good choices in most experimental settings and promise the best imputation quality. However, incorporating the model's training and inference time, presented in Table \\ref{tab:time}, shows that the discriminative DL approach is substantially slower for training and inference than the other two methods. This is because we used the expensive default model optimization of AutoKeras. Exploring fewer hyperparameters could decrease its imputation performance drastically. The training duration's high variance indicates that trying a large number of hyperparameters is necessary for good performance because early stopping would finish the training if the model converges. $k$-NN's standard deviation for inference is in contrast to random forest very high. This is expected as the inference time grows exponentially with the number of training data points. We conclude that given the similar performance of $k$-NN and random forests when the training data set is large, random forests (or similar methods) should be preferred over naive $k$-NN implementations. Alternatively, one might use appropriate speedups for the nearest neighbor search, such as $kd$-trees or approximate nearest neighbor search.\n\nTo summarize, the best performing imputation approach is random forest. It not only ranks best in most experimental settings, but it also shows a good balance of training, including optimizing hyperparameters and inference time that is not influenced by the training set size. However, when coping with data sets that miss $30\\%$ or more values of the pattern MNAR, imputing categorical columns with their mode is very often the best choice.\n\n\n\\subsection{Substantial Downstream Improvements when Imputation Method was Trained on Complete Data}\n%\nOur results show that imputation can have a substantial positive impact on predictive performance in downstream ML tasks. We observe improvements in the downstream task of 10\\% to 20\\% in more than 75\\% of our experiments. This holds for most imputation methods; we did not observe a clear advantage for an imputation method overall. Taking into account the considerable differences in wall-clock run time, our results indicate that also when choosing an imputation method that is both fast and improves downstream predictive performance random forests would be the preferred imputation method.\n\nThe positive impact of imputation on downstream performance is most pronounced when the imputation methods were trained on fully observed data. When imputation methods were trained on incomplete data, the positive impact of imputing missing values in the test data was substantially lower, sometimes even negative. While this might seem a disadvantage we emphasize that in many application use cases we can ensure that the training data be fully observed, for instance by acquiring more data before training the imputation as well as the downstream ML model.\n\n\n\\subsection{Limitations}\n\\label{sec:limitations}\n%\nBecause one of the main goals of this study is a comprehensive comparison of imputation methods on a large number of data sets and missingness conditions, we made some decisions that limit our results.\n\nFirstly, the used data sets consist of a maximum of $25$ features and $100k$ observations. For this reason, we can not conclude from our experiments how the imputation methods perform on large-scale data sets. Further, our data sets only contain numerical or categorical columns and no image- or text-based data, e.g., used in other deep learning-based imputation approaches \\citep{Biessmann2018a}. However, in that work, the authors only considered text data as an input field to an imputation method, not as a column that could be imputed. Generally, most modern ML applications that involve text data are based on rather sophisticated natural language models. Combinations of such models with tabular data are an important field of research \\citep{Yin2020} but beyond the scope of most imputation research so far.\n\nSecondly, to measure the imputation impact on the downstream performance, we discarded and imputed values in only a single column. Therefore, the impact depends heavily on the chosen column's importance (e.g., see \\cite{Jenga}). Generally, the impact when using an imputation model could vary when multiple columns are affected by missing values.\n", "meta": {"hexsha": "080979288647a4cf71ca92c85c3a82c36f033b83", "size": 7341, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/sections/discussion.tex", "max_stars_repo_name": "se-jaeger/data-imputation-paper", "max_stars_repo_head_hexsha": "498d2d871302d917f58ecf6a9576e3a3451c5faa", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-01-18T09:59:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T10:01:45.000Z", "max_issues_repo_path": "paper/sections/discussion.tex", "max_issues_repo_name": "se-jaeger/data-imputation-paper", "max_issues_repo_head_hexsha": "498d2d871302d917f58ecf6a9576e3a3451c5faa", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/sections/discussion.tex", "max_forks_repo_name": "se-jaeger/data-imputation-paper", "max_forks_repo_head_hexsha": "498d2d871302d917f58ecf6a9576e3a3451c5faa", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 198.4054054054, "max_line_length": 1265, "alphanum_fraction": 0.8195068792, "num_tokens": 1498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.3345421782571985}}
{"text": "\\documentclass[nofootinbib,amssymb,amsmath]{revtex4}\n\\usepackage{mathtools}\n\\usepackage{amsthm}\n\\usepackage{algorithm}\n\\usepackage{algpseudocode}\n\\usepackage{lmodern}\n\\usepackage{graphicx}\n\\usepackage{color}\n\n%Put an averaged random variable between brackets\n\\newcommand{\\ave}[1]{\\left\\langle #1 \\right\\rangle}\n\\newcommand{\\HC}{\\texttt{HaplotypeCaller}}\n\\newcommand{\\Mutect}{\\texttt{Mutect}}\n\\newcommand{\\code}[1]{\\texttt{#1}}\n\\newcommand{\\mc}[1]{\\mathcal{#1}}\n\n\n\\newtheorem{lemma}{Lemma}\n\\newtheorem{corollary}{Corollary}\n\n\\def\\SL#1{{\\color [rgb]{0,0,0.8} [SL: #1]}}\n\\def\\DB#1{{\\color [rgb]{0,0.8,0} [DB: #1]}}\n\n\\begin{document}\n\n\\title{Pair HMM probabilistic realignment in HaplotypeCaller and Mutect}\n\\author{David Benjamin\\footnote{The author took no part in development of the methods described below -- credit belongs to several others on the GATK team. }}\n\\email{davidben@broadinstitute.org}\n\\affiliation{Broad Institute, 75 Ames Street, Cambridge, MA 02142}\n\n\\date{\\today}\n\n\\begin{abstract}\nAfter generating candidate haplotypes, the GATK tools \\HC~and \\Mutect~realign reads against these haplotypes to obtain a matrix of likelihoods for each read to be derived from each haplotype.  Here we describe the probabilistic model specifying this likelihood as well as its computational implementation.  We do not describe the translation of this implementation into native code optimized for vectorized architectures.\n\\end{abstract}\n\n\\maketitle\n\n\\section{The Pair HMM model}\nWe want to calculate the probability $P( \\mc{R} | \\mc{H})$ of read $\\mc{R}$ to be sequenced from haplotype $\\mc{H}$, where the haplotypes are sufficiently long that reads are contained within them.  This likelihood is the sum of likelihoods of all possible alignments $\\mc{A}$ of $\\mc{R}$ to $\\mc{H}$:\n\n\\begin{equation}\nP(\\mc{R} | \\mc{H}) = \\sum_{\\mc{A}} P(\\mc{R}, \\mc{A} | \\mc{H})\n\\end{equation}\n\nWe represent alignments as sequences\n\\begin{equation}\n{\\rm alignment} = \\{ (i_1, j_1, s_1), (i_2, j_2, s_2) \\ldots (i_N, j_N, s_N) \\},\n\\end{equation}\nwhere $i$ and $j$ represent positions within the read and haplotype, respectively, and $s_n \\in \\{ M, I, D \\}$ represents the states of match, insertion, and deletion of the read relative to the haplotype.  For example, an alignment $\\{ (1,10, M), (2,11, M), (3,12, M), (4,13, M), (4,14, D), (4,15, D), (5,16, M), (6,17, M), (7,17, I), (8,18, M) \\}$ means that positions 1 - 4 of the read match positions 10 - 13 of the haplotype, followed by a two-base deletion (advancing from 13 to 15 in the haplotype without advancing in the read), followed by a match of read positions 5 - 6 with haplotype positions 16 - 17, followed by an insertion at read position 7, followed by a match.  The allowable transitions $(i_n, j_n) \\rightarrow (i_{n+1}, j_{n+1})$ are\n\\begin{itemize}\n\\item $(i, j, M/D/I) \\rightarrow (i+1, j+1, M)$: match of read position $i+1$ with haplotype position $j + 1$\n\\item $(i, j, M/D) \\rightarrow (i, j+1, D)$: deletion after read position $i$ -- haplotype position $j+1$ is deleted\n\\item $(i, j, M/I) \\rightarrow (i + 1, j, I)$: insertion at read position $i + 1$\n\\end{itemize}\nNote that the state label $s$ seems redundant because it can be reconstructed from the sequence of $i$ an $j$.  While this is true, our model treats indel starts differently from indel continuations, and by including the state label we can distinguish these conveniently\\footnote{That is, we can tell which type of transition it is by looking back one unit instead of two.  Thus we have a first-order Markov model instead of a second-order Markov model.}.  These transitions are illustrated as a finite state machine in Figure \\ref{fig:fsm}.\n\n\\begin{figure}\n\\center\n\\includegraphics[scale=0.35]{finite_state.png}\n\\caption{Finite state machine of transitions among match, insertion, and deletion alignment states.  In the absence of per-base BQSR indel qualities transition probabilities are parametrized  by two constants, the indel start probability $\\delta$ and the indel continuation probability $\\epsilon$, such that $T_{MI} = T_{MD} = \\delta$, $T_{MM} = 1 - 2 \\delta$, $T_{II} = T_{DD} = \\epsilon$, $T_{IM} = T_{DM} = 1 - \\epsilon$, and $T_{ID} = T_{DI} = 0$.}\n\\label{fig:fsm}\n\\end{figure}\n\nThe read-alignment likelihood has two components.  First is the probability of the sequence of match, insertion, and deletion states, which is\n\\begin{equation}\nP(\\mc{A}) = \\prod_k T_{s_k, s_{k+1}},\n\\end{equation}\nwhere $T$ is a matrix of state transition probabilities\\footnote{The gap continuation probability corresponds to a phred-scaled quality that is set by the \\code{gcpHMM} argument, which is 10 by default, implying that $T_{DD} = T_{II} = 10^{-10/10} = 1/10$ and $T_{DM} = T_{IM} = 1 - T_{II}$.  The indel start transitions are derived from the read's BQSR base insertion and base deletion qualities, if they exist, or a phred-scaled indel start quality of 45 if they do not.  In production at the Broad Institute bams do not have BQSR indel qualities, hence the constant default is used.  That is, $T_{MD} = T_{MI} = 10^{-4.5}$ and $T_{MM} = 1 - 2 \\times 10^{-4.5}$.}\\footnote{The elements of $T$ are either empirical or, (sometimes) in the case of indel start transitions, derived from BQSR.  However in principle all elemnts of $T$ could be learned by applying the Baum-Welch algorithm to some known training data.  For example, one could use a haploid cell line, for which any assembly region has a single haplotype.}.  The index $k$ runs from 1 to the number of states in the alignment, that is, the read length plus the number of deleted reference bases.  Next is the emission probability of the read bases given the haplotype bases they align to and the base qualities:\n\\begin{equation}\nP(\\mc{R} | \\mc{A}, \\mc{H}) = \\prod_k P(r_{i_k} | h_{j_k}, q_{i_k})^{{\\rm I}[s_k = M]},\n\\end{equation}\nwhere $r_m$ and $h_n$ are the $m$th read bases and $n$th haplotype base and $q_m$ is the quality of the read's $m$th base.  Note that this only includes alignments in the match state.  The per-base emission is given directly from the definition of base quality:\n\\begin{equation}\nP(b_2 | b_1, q) = \\left\\{ \\begin{array}{cc} \\epsilon(q)/3 & (b_1 \\ne b_2) \\\\ 1 - \\epsilon(q) & (b_1 = b_2)  \\end{array} \\right.\n\\end{equation}\nwhere $\\epsilon(q) = 10^{-q/10}$ is the error rate implied by the phred-scaled quality $q$.\n\n\\section{Dynamic Programming}\n\nDefine the matrices $M$, $I$ and $D$ by $M_{ij} = $ the total likelihood of \\textit{all} paths from the beginning of the read to position $i$ that end in a match state, and likewise for $D$ and $I$.  Then the recursions\n\\begin{align}\nM_{ij} =& P(r_i | h_j, q_i) \\left( M_{i-1,j-1} T_{MM} + I_{i-1,j-1} T_{IM} + D_{i-1,j-1} T_{DM} \\right) \\label{match} \\\\\nI_{ij} =& M_{i-1,j} T_{MI} + I_{i-1,j} T_{II} \\label{ins} \\\\\nD_{ij} =& M_{i,j-1} T_{MD} + D_{i, j - 1} T_{DD} \\label{del}\n\\end{align}\ndefine the entire pair HMM algorithm:\n\n\\begin{algorithm}\n\\begin{algorithmic}[1]\n\\State Initialize $M_{0,j} = I_{0,j} = 0$ and $D_{0,j} = 2^{1020}/|\\mc{H}|$ for $1 \\le j \\le |\\mc{H}|$.\n\\For{$1 \\le i \\le | \\mc{R} |$}\n\t\\For{$1 \\le j \\le | \\mc{H} |$}\n\t\t\\State Calculate $M_{ij}$ via Equation \\ref{match}.\n\t\t\\State Calculate $I_{ij}$ via Equation \\ref{ins}.\n\t\t\\State Calculate $D_{ij}$ via Equation \\ref{del}.\n\t\\EndFor\n\\EndFor\n\\State Total likelihood $P(\\mc{R} | \\mc{H})$ is $\\sum_j \\left(M_{\\mc{R},j} + I_{\\mc{R},j} \\right)$.\n\\end{algorithmic}\n\\caption{Pair HMM algorithm}\n\\label{pairHMM}\n\\end{algorithm}\n\nThat the $i = 0$ rows of $M$ and $I$ are initialized to zero corresponds to starting at an imaginary position one base before the read start in a deletion state\\footnote{Since $T_{DI} = 0$ this means that an alignment may not start with an insertion, though it may begin with one.  This limitation is unnecessary and could be fixed by initializing the $i = 0$ row of $I$ to a non-zero value as well.}.  The factor of $1/|\\mc{H}|$ corresponds to a flat prior on which $j$ an alignment starts at.  This is important for a local alignment because we don't want to penalize reads that start in the middle of the haplotype.  The curious factor of $2^{1020}$ is a huge number to prevent underflow -- all multiplications are by numbers less than 1, so we needn't worry about overflow -- which is a much more efficient approach than performing the computation in log space.  The omission of $D$ from the returned value recognizes the fact that a terminal deletion is meaningless.\n\nFinally, we note a shortcut that the GATK exploits: when two consecutive haplotypes of the same length\\footnote{The condition on the same length could easily be relaxed simply by accounting for the constant $1/|\\mc{H}|$ initialization.}  agree up to the $k$th position, the first $k$ columns of $M$, $D$ and $I$ are recycled and the inner loop is over $k < j \\le \\mc{H}$.\n\n\\end{document}", "meta": {"hexsha": "d2efbd4616ea58b038aa9602324d6c2ea20eca57", "size": 8820, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/pair_hmm.tex", "max_stars_repo_name": "sunboy0523/gatk", "max_stars_repo_head_hexsha": "f06971ac0824ad7da38b878334df377c30457a23", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1273, "max_stars_repo_stars_event_min_datetime": "2015-10-13T18:11:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T09:25:13.000Z", "max_issues_repo_path": "docs/pair_hmm.tex", "max_issues_repo_name": "sunboy0523/gatk", "max_issues_repo_head_hexsha": "f06971ac0824ad7da38b878334df377c30457a23", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6471, "max_issues_repo_issues_event_min_datetime": "2015-10-08T02:31:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T17:55:25.000Z", "max_forks_repo_path": "docs/pair_hmm.tex", "max_forks_repo_name": "sunboy0523/gatk", "max_forks_repo_head_hexsha": "f06971ac0824ad7da38b878334df377c30457a23", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 598, "max_forks_repo_forks_event_min_datetime": "2015-10-14T19:16:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:03:03.000Z", "avg_line_length": 80.9174311927, "max_line_length": 1273, "alphanum_fraction": 0.7164399093, "num_tokens": 2777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6688802735722129, "lm_q2_score": 0.5, "lm_q1q2_score": 0.33444013678610646}}
{"text": "\\documentclass[11pt]{amsart}\n\\usepackage{geometry}                % See geometry.pdf to learn the layout options. There are lots.\n\\geometry{letterpaper}                   % ... or a4paper or a5paper or ... \n%\\geometry{landscape}                % Activate for for rotated page geometry\n%\\usepackage[parfill]{parskip}    % Activate to begin paragraphs with an empty line rather than an indent\n\\usepackage{graphicx}\n\\usepackage{amssymb}\n\\usepackage{epstopdf}\n\\DeclareGraphicsRule{.tif}{png}{.png}{`convert #1 `dirname #1`/`basename #1 .tif`.png}\n\n\\title{Brief Article}\n\\author{The Author}\n%\\date{}                                           % Activate to display a given date or no date\n\n\\begin{document}\n\\maketitle\n%\\section{}\n%\\subsection{}\n\n$P(football \\mod \\Theta_0)=2.40/6.0=0.40 $\n\n\\end{document}  ", "meta": {"hexsha": "d45d42f7cd6f91d62d4ab054ad4069d46ab06984", "size": 800, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "LATEX/Latex sandbox.tex", "max_stars_repo_name": "albertocottica/comparing-policies-online-communities", "max_stars_repo_head_hexsha": "938d79c42003827006e2993320697d59658eb0f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-05-06T17:24:25.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-06T17:24:25.000Z", "max_issues_repo_path": "LATEX/Latex sandbox.tex", "max_issues_repo_name": "albertocottica/comparing-policies-online-communities", "max_issues_repo_head_hexsha": "938d79c42003827006e2993320697d59658eb0f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LATEX/Latex sandbox.tex", "max_forks_repo_name": "albertocottica/comparing-policies-online-communities", "max_forks_repo_head_hexsha": "938d79c42003827006e2993320697d59658eb0f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3636363636, "max_line_length": 105, "alphanum_fraction": 0.65125, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3342836977684117}}
{"text": "\\documentclass[english]{article}\n\\usepackage[T1]{fontenc}\n\\usepackage[utf8]{inputenc}\n\\usepackage{csquotes, caption}\n\\usepackage[colorlinks=true, citecolor = blue]{hyperref}      % hyperlinks\n\\usepackage{multirow, amssymb, amsmath, graphicx, arydshln, url}\n\\usepackage[T1]{fontenc}\n\\usepackage{natbib}\n\n\\title{Supporting Information for ``Modelling publication bias and \\textit{p}-hacking''\\\\ by Jonas Moss and Riccardo De Bin}\n\n\\author{}\n\n\\date{}\n\n\\begin{document}\n\n\\maketitle\n\n\n\\section*{Web Appendix A}\n\nAs mentioned in Section 2, any \\textit{p}-hacking model can be written on the form of a selection model. Observe that\n\\begin{eqnarray*}\n\\int_{[0,1]}f_\\alpha^{\\star}(x_{i}\\mid\\theta_{i},\\eta_{i}, u_i)d\\omega(\\alpha) & = & \\int_{[0,1]}f(x_{i}\\mid\\theta_{i})P(u_i\\in\\left[0,\\alpha\\right]\\mid\\theta_{i},\\eta_{i})^{-1}d\\omega(\\alpha)\\\\\n & = & f(x_{i}\\mid\\theta_{i})\\int_{[0,u_i)}P(u_i\\in\\left[0,\\alpha\\right]\\mid\\theta_{i},\\eta_{i})^{-1}d\\omega(\\alpha).\n\\end{eqnarray*}\nwhere $f_\\alpha^{\\star}$ is the density $f^{\\star}$ truncated so that the \\textit{p}-value associated to $x_i$, $u_i$, lies in the interval $\\left[0,\\alpha\\right)$. This is a publication bias model if $$h(u_i)=\\int_{[0,u_i]}P(u_i\\in\\left[0,\\alpha\\right]\\mid\\theta_{i},\\eta_{i})^{-1}d\\omega(\\alpha)$$ is bounded for each $u_i$ and $h(u_i)$ is independent of $\\theta_{i},\\eta_{i}$. While $h(u_i)$ can be bounded, it is typically dependent of $\\theta_{i},\\eta_{i}$, with the fixed effect model under complete selection for significance being a notable exception.\n\nOn the other hand, any selection model $f(x_{i};\\theta_{i},\\eta_{i})\\rho(u_i)$ with $I =\\int f(x;\\theta_{i},\\eta_{i})\\rho(u_i)du_i<\\infty$ can be written as a mixture model. For then there is a finite measure $d\\omega(\\alpha;\\theta_{i},\\eta_{i})$ satisfying \n\\[\n\\rho(u_i)=\\int_{[0,u_i)}\\frac{1}{P(u_i\\in\\left[0,\\alpha\\right)\\mid\\theta,\\eta)}d\\omega(\\alpha;\\theta_{i},\\eta_{i})\n\\]\nJust take $d\\omega(\\alpha;\\theta_{i},\\eta_{i})=d\\rho(\\alpha)P(u_i\\in\\left[0,\\alpha\\right)\\mid\\theta_{i},\\eta_{i})$, where $d\\rho(\\alpha)$ is defined by $\\int_{0}^{u_i}d\\rho(\\alpha)=\\rho(u_i)$. The size of the measure is\n\\begin{eqnarray*}\n\\int_{0}^{1}d\\omega(\\alpha;\\theta_{i},\\eta_{i}) & = & \\int_{0}^{1}P(u_i\\in\\left[0,\\alpha\\right)\\mid\\theta_{i},\\eta_{i})d\\rho(\\alpha)\\\\\n & = & \\int_{0}^{1}f(u_i;\\theta_{i},\\eta_{i})\\int_{0}^{u_i}d\\rho(\\alpha)du_i\\\\\n & = & I\n\\end{eqnarray*}\nHence $I_{\\theta,\\eta}d\\omega'(\\alpha;\\theta_{i},\\eta_{i})$ is a probability measure. This probability measure makes \n\\[\nI^{-1}f(x_{i};\\theta_{i},\\eta_{i})\\rho(u_i)=\\int_{[0,1]}f_\\alpha(x_{i};\\theta_{i},\\eta_{i})d\\omega'(\\alpha)\n\\]\nas can be seen by the following computation,\n\\begin{eqnarray*}\nI^{-1}f(x_{i};\\theta_{i},\\eta_{i})\\rho(u_i) & = & I^{-1}\\int_{[0,u_i)}\\frac{f(x_{i};\\theta_{i},\\eta_{i})}{P(u_i\\in\\left[0,\\alpha\\right)\\mid\\theta_{i},\\eta_{i})}d\\omega(\\alpha)\\\\\n & = & I^{-1}\\int_{[0,1]}\\frac{f(x_{i};\\theta,\\eta)1_{\\left[0,\\alpha\\right)}(u_i)}{P(u_i\\in\\left[0,\\alpha\\right)\\mid\\theta_{i},\\eta_{i})}d\\omega(\\alpha)\\\\\n & = & I^{-1}\\int_{[0,1]}f_\\alpha(x_{i};\\theta_{i},\\eta_{i})d\\omega(\\alpha)\\\\\n & = & \\int_{[0,1]}f_\\alpha(x;\\theta_{i},\\eta_{i})d\\omega'(\\alpha)\n\\end{eqnarray*}\n\nProposition 1 shows the form of the one-sided normal step function selection probability publication bias model when it is written as a mixture model of the form (5). But most such mixture models are not true \\textit{p}-hacking models, as the mixing probabilities $\\pi_{i}^{\\star}$ depend on $\\theta$. There is no way for the \\textit{p}-hacker to know\n$\\theta$, so we cannot regard the publication bias model as a \\textit{p}-hacking model.\n\n\\newpage\n\n\\section*{Web Appendix B}\n\n%\\subsection*{Inverse Gamma prior on $\\tau^2$}\n\n\\begin{table}[ht]\n\\centering\n\\caption*{\\noindent Table C.1: {\\bf Inverse Gamma prior, no publication bias, no \n                    \\textit{p}-hacking.} Posterior means and \n                    standard deviations from the \\textit{p}-hacking and \n                    publication bias models when the data are simulated \n                    from the normal random effects meta-analysis model.}\n\\label{tab:Simulation_ph}\n\\begin{tabular}{lllrrrrrr}\n   \\multicolumn{3}{r}{\\textbf{True values}} & \n       \\multicolumn{2}{c}{\\textbf{\\textit{p}-hacking model}} &\n       \\multicolumn{2}{c}{\\textbf{Public. bias model}} &\n       \\multicolumn{2}{c}{\\textbf{Classical model}}\\\\$\\tau$ & $\\theta_0$ & $n$ & \\multicolumn{1}{c}{$\\widehat{\\theta_0}$} & \\multicolumn{1}{c}{$\\widehat{\\tau}$} & \\multicolumn{1}{c}{$\\widehat{\\theta_0}$} & \\multicolumn{1}{c}{$\\widehat{\\tau}$} & \\multicolumn{1}{c}{$\\widehat{\\theta_0}$} & \\multicolumn{1}{c}{$\\widehat{\\tau}$} \\\\ \n   \\hline\n  \\multirow{9}{*}{$0.1$} & \\multirow{3}{*}{$0$} & 5 & -0.03 (0.08) & 0.18 (0.08) & -0.06 (0.06) & 0.14 (0.07) & 0.00 (0.07) & 0.20 (0.09) \\\\ \n  & & 30 & -0.02 (0.03) & 0.08 (0.03) & -0.02 (0.03) & 0.07 (0.03) & 0.00 (0.03) & 0.10 (0.04) \\\\ \n  & & 100 & -0.01 (0.02) & 0.08 (0.02) & -0.02 (0.02) & 0.07 (0.02) & 0.00 (0.02) & 0.09 (0.02) \\\\ \n   \\cdashline{3-9}\n & \\multirow{3}{*}{$0.2$} & 5 & 0.12 (0.08) & 0.20 (0.07) & 0.08 (0.06) & 0.15 (0.06) & 0.19 (0.08) & 0.18 (0.07) \\\\ \n  & & 30 & 0.17 (0.04) & 0.09 (0.04) & 0.15 (0.03) & 0.08 (0.04) & 0.20 (0.03) & 0.09 (0.03) \\\\ \n  & & 100 & 0.18 (0.02) & 0.09 (0.03) & 0.17 (0.02) & 0.09 (0.03) & 0.20 (0.02) & 0.09 (0.02) \\\\ \n   \\cdashline{3-9}\n & \\multirow{3}{*}{$0.8$} & 5 & 0.78 (0.07) & 0.20 (0.10) & 0.64 (0.13) & 0.32 (0.14) & 0.79 (0.07) & 0.18 (0.08) \\\\ \n  & & 30 & 0.80 (0.04) & 0.10 (0.04) & 0.79 (0.04) & 0.10 (0.04) & 0.80 (0.03) & 0.10 (0.04) \\\\ \n  & & 100 & 0.80 (0.02) & 0.09 (0.03) & 0.80 (0.02) & 0.09 (0.03) & 0.80 (0.02) & 0.09 (0.03) \\\\ \n  \\cline{2-9}\n\\multirow{9}{*}{$0.5$} & \\multirow{3}{*}{$0$} & 5 & -0.08 (0.20) & 0.56 (0.22) & -0.24 (0.18) & 0.50 (0.21) & -0.03 (0.21) & 0.58 (0.21) \\\\ \n  & & 30 & -0.03 (0.08) & 0.50 (0.07) & -0.14 (0.08) & 0.46 (0.07) & 0.00 (0.08) & 0.50 (0.07) \\\\ \n  & & 100 & -0.02 (0.05) & 0.50 (0.04) & -0.08 (0.06) & 0.48 (0.04) & 0.00 (0.05) & 0.50 (0.04) \\\\ \n   \\cdashline{3-9}\n & \\multirow{3}{*}{$0.2$} & 5 & 0.16 (0.24) & 0.60 (0.19) & -0.04 (0.20) & 0.58 (0.2) & 0.20 (0.24) & 0.60 (0.19) \\\\ \n  & & 30 & 0.16 (0.08) & 0.52 (0.07) & 0.03 (0.09) & 0.50 (0.07) & 0.19 (0.08) & 0.52 (0.07) \\\\ \n  & & 100 & 0.18 (0.06) & 0.51 (0.04) & 0.10 (0.06) & 0.50 (0.04) & 0.20 (0.06) & 0.50 (0.04) \\\\ \n   \\cdashline{3-9}\n & \\multirow{3}{*}{$0.8$} & 5 & 0.73 (0.26) & 0.61 (0.17) & 0.40 (0.28) & 0.74 (0.18) & 0.75 (0.25) & 0.58 (0.17) \\\\ \n  & & 30 & 0.77 (0.09) & 0.53 (0.07) & 0.60 (0.12) & 0.60 (0.09) & 0.79 (0.08) & 0.51 (0.07) \\\\ \n  & & 100 & 0.80 (0.06) & 0.52 (0.04) & 0.71 (0.07) & 0.55 (0.04) & 0.81 (0.05) & 0.51 (0.04) \\\\ \n  \\hline\n\\end{tabular}\n\\end{table}\n\n\n\n\\begin{table}[ht]\n\\centering\n\\caption*{\\noindent Table C.2: {\\bf Inverse Gamma prior, publication bias.} \n                    Posterior means and standard deviations from the \n                    \\textit{p}-hacking, publication bias, and uncorrected models \n                    when the data are simulated from the publication \n                    bias model with cutoffs at $0.025$ and $0.05$, \n                    with selection probabilities equal to $1$, $0.7$, \n                    and $0.1$ in the intervals $[0, 0.025)$, $[0.025, 0.05)$, \n                    and $[0.5, 1]$.} \n\\label{tab:Simulation_pb}\n\\begin{tabular}{lllrrrrrr}\n   \\multicolumn{3}{r}{\\textbf{True values}} & \n       \\multicolumn{2}{c}{\\textbf{\\textit{p}-hacking model}} &\n       \\multicolumn{2}{c}{\\textbf{Public.\\ bias model}} &\n       \\multicolumn{2}{c}{\\textbf{Uncorrected model}}\\\\$\\tau$ & $\\theta_0$ & $n$ & \\multicolumn{1}{c}{$\\widehat{\\theta_0}$} & \\multicolumn{1}{c}{$\\widehat{\\tau}$} & \\multicolumn{1}{c}{$\\widehat{\\theta_0}$} & \\multicolumn{1}{c}{$\\widehat{\\tau}$} & \\multicolumn{1}{c}{$\\widehat{\\theta_0}$} & \\multicolumn{1}{c}{$\\widehat{\\tau}$} \\\\ \n   \\hline\n  \\multirow{9}{*}{$0.1$} & \\multirow{3}{*}{$0$} & 5 & -0.02 (0.11) & 0.21 (0.08) & 0.00 (0.08) & 0.16 (0.07) & 0.12 (0.08) & 0.22 (0.10) \\\\ \n  & & 30 & 0.03 (0.05) & 0.12 (0.04) & 0.02 (0.04) & 0.10 (0.03) & 0.14 (0.04) & 0.15 (0.04) \\\\ \n  & & 100 & 0.02 (0.02) & 0.11 (0.03) & 0.01 (0.02) & 0.09 (0.02) & 0.13 (0.02) & 0.16 (0.02) \\\\\n   \\cdashline{3-9}\n & \\multirow{3}{*}{$0.2$} & 5 & 0.12 (0.13) & 0.29 (0.10) & 0.10 (0.07) & 0.21 (0.09) & 0.33 (0.06) & 0.16 (0.07) \\\\ \n  & & 30 & 0.22 (0.05) & 0.12 (0.05) & 0.19 (0.05) & 0.10 (0.04) & 0.33 (0.03) & 0.06 (0.03) \\\\ \n  & & 100 & 0.23 (0.03) & 0.11 (0.03) & 0.19 (0.05) & 0.09 (0.03) & 0.33 (0.02) & 0.04 (0.02) \\\\\n   \\cdashline{3-9}\n & \\multirow{3}{*}{$0.8$} & 5 & 0.79 (0.11) & 0.21 (0.10) & 0.65 (0.17) & 0.31 (0.13) & 0.80 (0.10) & 0.19 (0.07) \\\\ \n  & & 30 & 0.80 (0.03) & 0.10 (0.04) & 0.80 (0.03) & 0.10 (0.05) & 0.80 (0.03) & 0.10 (0.04) \\\\ \n  & & 100 & 0.80 (0.02) & 0.09 (0.03) & 0.80 (0.02) & 0.10 (0.03) & 0.80 (0.02) & 0.09 (0.03) \\\\ \n  \\cline{2-9}\n\\multirow{9}{*}{$0.5$} & \\multirow{3}{*}{$0$} & 5 & 0.30 (0.26) & 0.53 (0.20) & 0.03 (0.22) & 0.55 (0.19) & 0.40 (0.22) & 0.48 (0.20) \\\\ \n  & & 30 & 0.34 (0.10) & 0.47 (0.08) & 0.00 (0.17) & 0.49 (0.08) & 0.42 (0.09) & 0.42 (0.09) \\\\ \n  & & 100 & 0.35 (0.05) & 0.46 (0.04) & 0.00 (0.10) & 0.49 (0.05) & 0.43 (0.04) & 0.42 (0.04) \\\\ \n   \\cdashline{3-9}\n & \\multirow{3}{*}{$0.2$} & 5 & 0.48 (0.22) & 0.55 (0.19) & 0.17 (0.22) & 0.61 (0.19) & 0.55 (0.19) & 0.47 (0.21) \\\\ \n  & & 30 & 0.52 (0.09) & 0.43 (0.08) & 0.18 (0.16) & 0.51 (0.09) & 0.57 (0.08) & 0.37 (0.08) \\\\ \n  & & 100 & 0.50 (0.05) & 0.43 (0.05) & 0.20 (0.13) & 0.50 (0.05) & 0.56 (0.04) & 0.38 (0.04) \\\\ \n   \\cdashline{3-9}\n & \\multirow{3}{*}{$0.8$} & 5 & 0.81 (0.22) & 0.52 (0.20) & 0.48 (0.27) & 0.68 (0.21) & 0.85 (0.20) & 0.47 (0.18) \\\\ \n  & & 30 & 0.91 (0.09) & 0.45 (0.07) & 0.69 (0.18) & 0.57 (0.11) & 0.93 (0.08) & 0.42 (0.07) \\\\ \n  & & 100 & 0.91 (0.05) & 0.44 (0.04) & 0.75 (0.13) & 0.53 (0.08) & 0.93 (0.05) & 0.41 (0.04) \\\\ \\hline\n\\end{tabular}\n\\end{table}\n\n\\begin{table}[ht]\n\\centering\n\\caption*{\\noindent Table C.3: {\\bf  Inverse Gamma prior, \\textit{p}-hacking.} Posterior means and \n                    standard deviations from the \\textit{p}-hacking, \n                    publication bias, and uncorrected models when the data are simulated \n                    from the \\textit{p}-hacking model with cutoffs at\n                    $0.025$ and $0.05$, with \\textit{p}-hacking probabilities\n                    equal to $0.6$, $0.3$, and $0.1$ for $\\alpha = 0.025, 0.05$, and $1$} \n\\label{tab:Simulation_ph}\n\\begin{tabular}{lllrrrrrr}\n   \\multicolumn{3}{r}{\\textbf{True values}} & \n       \\multicolumn{2}{c}{\\textbf{\\textit{p}-hacking model}} &\n       \\multicolumn{2}{c}{\\textbf{Public. bias model}} &\n       \\multicolumn{2}{c}{\\textbf{Uncorrected model}}\\\\$\\tau$ & $\\theta_0$ & $n$ & \\multicolumn{1}{c}{$\\widehat{\\theta_0}$} & \\multicolumn{1}{c}{$\\widehat{\\tau}$} & \\multicolumn{1}{c}{$\\widehat{\\theta_0}$} & \\multicolumn{1}{c}{$\\widehat{\\tau}$} & \\multicolumn{1}{c}{$\\widehat{\\theta_0}$} & \\multicolumn{1}{c}{$\\widehat{\\tau}$} \\\\ \n   \\hline\n  \\multirow{9}{*}{$0.1$} & \\multirow{3}{*}{$0$} & 5 & -0.06 (0.13) & 0.28 (0.07) & 0.04 (0.07) & 0.17 (0.05) & 0.29 (0.07) & 0.15 (0.08) \\\\ \n  & & 30 & -0.02 (0.07) & 0.13 (0.04) & 0.02 (0.06) & 0.06 (0.02) & 0.28 (0.02) & 0.06 (0.03) \\\\ \n  & & 100 & -0.01 (0.04) & 0.10 (0.04) & -0.01 (0.05) & 0.05 (0.03) & 0.29 (0.01) & 0.03 (0.02) \\\\ \n   \\cdashline{3-9}\n & \\multirow{3}{*}{$0.2$} & 5 & 0.13 (0.15) & 0.29 (0.09) & 0.09 (0.07) & 0.22 (0.08) & 0.35 (0.06) & 0.14 (0.06) \\\\ \n  & & 30 & 0.18 (0.06) & 0.11 (0.04) & 0.15 (0.05) & 0.09 (0.03) & 0.34 (0.02) & 0.04 (0.01) \\\\ \n  & & 100 & 0.20 (0.03) & 0.09 (0.04) & 0.16 (0.04) & 0.08 (0.03) & 0.34 (0.01) & 0.02 (0.01) \\\\ \n   \\cdashline{3-9}\n & \\multirow{3}{*}{$0.8$} & 5 & 0.78 (0.08) & 0.20 (0.08) & 0.63 (0.14) & 0.32 (0.12) & 0.78 (0.08) & 0.19 (0.07) \\\\ \n  & & 30 & 0.79 (0.04) & 0.10 (0.04) & 0.79 (0.04) & 0.10 (0.04) & 0.79 (0.03) & 0.10 (0.04) \\\\ \n  & & 100 & 0.80 (0.02) & 0.10 (0.02) & 0.80 (0.02) & 0.10 (0.03) & 0.80 (0.02) & 0.09 (0.02) \\\\ \n  \\cline{2-9}\n\\multirow{9}{*}{$0.5$} & \\multirow{3}{*}{$0$} & 5 & 0.06 (0.20) & 0.47 (0.19) & 0.02 (0.10) & 0.35 (0.21) & 0.37 (0.12) & 0.27 (0.18) \\\\ \n  & & 30 & 0.07 (0.09) & 0.44 (0.09) & -0.25 (0.19) & 0.36 (0.11) & 0.37 (0.05) & 0.24 (0.10) \\\\ \n  & & 100 & 0.06 (0.06) & 0.44 (0.04) & -0.36 (0.15) & 0.37 (0.06) & 0.36 (0.03) & 0.25 (0.05) \\\\ \n   \\cdashline{3-9}\n & \\multirow{3}{*}{$0.2$} & 5 & 0.24 (0.21) & 0.52 (0.20) & 0.05 (0.12) & 0.47 (0.21) & 0.45 (0.13) & 0.33 (0.18) \\\\ \n  & & 30 & 0.24 (0.10) & 0.47 (0.08) & -0.20 (0.20) & 0.46 (0.11) & 0.45 (0.06) & 0.29 (0.08) \\\\ \n  & & 100 & 0.23 (0.06) & 0.47 (0.04) & -0.30 (0.15) & 0.48 (0.06) & 0.46 (0.04) & 0.28 (0.04) \\\\\n   \\cdashline{3-9}\n & \\multirow{3}{*}{$0.8$} & 5 & 0.69 (0.18) & 0.60 (0.20) & 0.31 (0.19) & 0.74 (0.19) & 0.76 (0.14) & 0.51 (0.18) \\\\ \n  & & 30 & 0.80 (0.10) & 0.51 (0.08) & 0.39 (0.25) & 0.66 (0.12) & 0.85 (0.08) & 0.44 (0.07) \\\\ \n  & & 100 & 0.81 (0.05) & 0.50 (0.04) & 0.43 (0.19) & 0.65 (0.09) & 0.86 (0.04) & 0.43 (0.03) \\\\ \n  \\hline\n\\end{tabular}\n\\end{table}\n\n\\newpage\n\n%\\subsection*{Uniform prior on $\\tau$}\n\n\n\\begin{table}[ht]\n\\centering\n\\caption*{\\noindent Table C.4: {\\bf Uniform prior, no publication bias, no \n                    \\textit{p}-hacking.} Posterior means and \n                    standard deviations from the \\textit{p}-hacking and \n                    publication bias models when the data are simulated \n                    from the normal random effects meta-analysis model.}\n\\label{tab:Simulation_ph}\n\\begin{tabular}{lllrrrrrr}\n   \\multicolumn{3}{r}{\\textbf{True values}} & \n       \\multicolumn{2}{c}{\\textbf{\\textit{p}-hacking model}} &\n       \\multicolumn{2}{c}{\\textbf{Public. bias model}} &\n       \\multicolumn{2}{c}{\\textbf{Classical model}}\\\\$\\tau$ & $\\theta_0$ & $n$ & \\multicolumn{1}{c}{$\\widehat{\\theta_0}$} & \\multicolumn{1}{c}{$\\widehat{\\tau}$} & \\multicolumn{1}{c}{$\\widehat{\\theta_0}$} & \\multicolumn{1}{c}{$\\widehat{\\tau}$} & \\multicolumn{1}{c}{$\\widehat{\\theta_0}$} & \\multicolumn{1}{c}{$\\widehat{\\tau}$} \\\\ \n   \\hline\n  \\multirow{9}{*}{$0.1$} & \\multirow{3}{*}{$0$} & 5 & -0.03 (0.07) & 0.17 (0.06) & -0.06 (0.07) & 0.12 (0.05) & -0.01 (0.08) & 0.18 (0.07) \\\\ \n  & & 30 & -0.02 (0.03) & 0.08 (0.03) & -0.02 (0.03) & 0.07 (0.03) & 0.00 (0.04) & 0.10 (0.03) \\\\ \n  & & 100 & -0.01 (0.02) & 0.08 (0.03) & -0.02 (0.02) & 0.07 (0.03) & 0.00 (0.02) & 0.10 (0.03) \\\\ \n   \\cdashline{3-9}\n & \\multirow{3}{*}{$0.2$} & 5 & 0.12 (0.09) & 0.21 (0.09) & 0.09 (0.07) & 0.16 (0.08) & 0.19 (0.08) & 0.18 (0.08) \\\\ \n  & & 30 & 0.17 (0.03) & 0.09 (0.04) & 0.15 (0.03) & 0.09 (0.03) & 0.20 (0.03) & 0.10 (0.03) \\\\ \n  & & 100 & 0.18 (0.02) & 0.09 (0.03) & 0.17 (0.02) & 0.09 (0.03) & 0.20 (0.02) & 0.09 (0.02) \\\\ \n   \\cdashline{3-9}\n & \\multirow{3}{*}{$0.8$} & 5 & 0.77 (0.09) & 0.20 (0.08) & 0.62 (0.14) & 0.31 (0.13) & 0.77 (0.08) & 0.18 (0.07) \\\\ \n  & & 30 & 0.80 (0.04) & 0.10 (0.04) & 0.80 (0.04) & 0.10 (0.04) & 0.80 (0.03) & 0.10 (0.04) \\\\ \n  & & 100 & 0.80 (0.02) & 0.10 (0.02) & 0.80 (0.02) & 0.10 (0.03) & 0.80 (0.02) & 0.10 (0.02) \\\\ \n  \\cline{2-9}\n\\multirow{9}{*}{$0.5$} & \\multirow{3}{*}{$0$} & 5 & -0.03 (0.20) & 0.55 (0.19) & -0.21 (0.17) & 0.49 (0.19) & 0.01 (0.20) & 0.57 (0.19) \\\\ \n  & & 30 & -0.02 (0.10) & 0.51 (0.08) & -0.13 (0.10) & 0.48 (0.08) & 0.00 (0.10) & 0.51 (0.08) \\\\ \n  & & 100 & -0.02 (0.05) & 0.50 (0.04) & -0.08 (0.05) & 0.48 (0.04) & 0.00 (0.05) & 0.50 (0.04) \\\\ \n   \\cdashline{3-9}\n & \\multirow{3}{*}{$0.2$} & 5 & 0.20 (0.22) & 0.57 (0.19) & -0.02 (0.17) & 0.57 (0.19) & 0.24 (0.21) & 0.57 (0.18) \\\\ \n  & & 30 & 0.17 (0.10) & 0.52 (0.08) & 0.05 (0.10) & 0.50 (0.08) & 0.20 (0.10) & 0.51 (0.08) \\\\ \n  & & 100 & 0.19 (0.06) & 0.51 (0.04) & 0.11 (0.06) & 0.50 (0.04) & 0.20 (0.06) & 0.50 (0.04) \\\\ \n   \\cdashline{3-9}\n & \\multirow{3}{*}{$0.8$} & 5 & 0.74 (0.23) & 0.61 (0.23) & 0.41 (0.24) & 0.75 (0.23) & 0.77 (0.22) & 0.58 (0.22) \\\\ \n  & & 30 & 0.79 (0.10) & 0.53 (0.07) & 0.60 (0.14) & 0.61 (0.08) & 0.81 (0.10) & 0.51 (0.07) \\\\ \n  & & 100 & 0.78 (0.06) & 0.52 (0.04) & 0.70 (0.07) & 0.55 (0.04) & 0.80 (0.06) & 0.51 (0.04) \\\\ \n  \\hline\n\\end{tabular}\n\\end{table}\n\n\n\n\\begin{table}[ht]\n\\centering\n\\caption*{\\noindent Table C.5: {\\bf Uniform prior, publication bias.} \n                    Posterior means and standard deviations from the \n                    \\textit{p}-hacking, publication bias, and uncorrected models \n                    when the data are simulated from the publication \n                    bias model with cutoffs at $0.025$ and $0.05$, \n                    with selection probabilities equal to $1$, $0.7$, \n                    and $0.1$ in the intervals $[0, 0.025)$, $[0.025, 0.05)$, \n                    and $[0.5, 1]$.} \n\\label{tab:Simulation_pb}\n\\begin{tabular}{lllrrrrrr}\n   \\multicolumn{3}{r}{\\textbf{True values}} & \n       \\multicolumn{2}{c}{\\textbf{\\textit{p}-hacking model}} &\n       \\multicolumn{2}{c}{\\textbf{Public.\\ bias model}} &\n       \\multicolumn{2}{c}{\\textbf{Uncorrected model}}\\\\$\\tau$ & $\\theta_0$ & $n$ & \\multicolumn{1}{c}{$\\widehat{\\theta_0}$} & \\multicolumn{1}{c}{$\\widehat{\\tau}$} & \\multicolumn{1}{c}{$\\widehat{\\theta_0}$} & \\multicolumn{1}{c}{$\\widehat{\\tau}$} & \\multicolumn{1}{c}{$\\widehat{\\theta_0}$} & \\multicolumn{1}{c}{$\\widehat{\\tau}$} \\\\ \n   \\hline\n  \\multirow{9}{*}{$0.1$} & \\multirow{3}{*}{$0$} & 5 & -0.01 (0.11) & 0.24 (0.09) & -0.01 (0.08) & 0.18 (0.08) & 0.13 (0.09) & 0.24 (0.10) \\\\ \n  & & 30 & 0.02 (0.05) & 0.12 (0.04) & 0.01 (0.04) & 0.10 (0.03) & 0.13 (0.04) & 0.16 (0.04) \\\\ \n  & & 100 & 0.03 (0.03) & 0.12 (0.03) & 0.01 (0.02) & 0.10 (0.02) & 0.14 (0.02) & 0.16 (0.02) \\\\ \n   \\cdashline{3-9}\n & \\multirow{3}{*}{$0.2$} & 5 & 0.16 (0.13) & 0.27 (0.08) & 0.12 (0.06) & 0.21 (0.06) & 0.33 (0.06) & 0.15 (0.06) \\\\ \n  & & 30 & 0.23 (0.05) & 0.12 (0.05) & 0.19 (0.06) & 0.10 (0.04) & 0.33 (0.03) & 0.06 (0.02) \\\\ \n  & & 100 & 0.24 (0.03) & 0.10 (0.03) & 0.20 (0.04) & 0.10 (0.03) & 0.33 (0.02) & 0.04 (0.02) \\\\ \n   \\cdashline{3-9}\n & \\multirow{3}{*}{$0.8$} & 5 & 0.80 (0.07) & 0.19 (0.08) & 0.66 (0.13) & 0.31 (0.13) & 0.80 (0.07) & 0.18 (0.07) \\\\ \n  & & 30 & 0.80 (0.03) & 0.10 (0.04) & 0.79 (0.04) & 0.11 (0.04) & 0.80 (0.03) & 0.10 (0.04) \\\\ \n  & & 100 & 0.80 (0.02) & 0.09 (0.03) & 0.80 (0.02) & 0.09 (0.02) & 0.80 (0.02) & 0.09 (0.02) \\\\ \n  \\cline{2-9}\n\\multirow{9}{*}{$0.5$} & \\multirow{3}{*}{$0$} & 5 & 0.36 (0.24) & 0.54 (0.20) & 0.07 (0.23) & 0.57 (0.18) & 0.45 (0.21) & 0.47 (0.22) \\\\ \n  & & 30 & 0.39 (0.10) & 0.47 (0.08) & 0.04 (0.17) & 0.51 (0.08) & 0.45 (0.08) & 0.42 (0.08) \\\\ \n  & & 100 & 0.36 (0.06) & 0.48 (0.04) & 0.00 (0.12) & 0.51 (0.05) & 0.43 (0.05) & 0.43 (0.05) \\\\ \n   \\cdashline{3-9}\n & \\multirow{3}{*}{$0.2$} & 5 & 0.41 (0.22) & 0.53 (0.18) & 0.11 (0.20) & 0.58 (0.18) & 0.49 (0.17) & 0.46 (0.20) \\\\ \n  & & 30 & 0.50 (0.08) & 0.45 (0.08) & 0.15 (0.18) & 0.52 (0.09) & 0.55 (0.07) & 0.39 (0.08) \\\\ \n  & & 100 & 0.51 (0.05) & 0.43 (0.05) & 0.17 (0.13) & 0.51 (0.06) & 0.56 (0.04) & 0.38 (0.05) \\\\\n  \\cdashline{3-9}\n & \\multirow{3}{*}{$0.8$} & 5 & 0.86 (0.16) & 0.52 (0.19) & 0.51 (0.23) & 0.70 (0.20) & 0.89 (0.15) & 0.49 (0.17) \\\\ \n  & & 30 & 0.90 (0.09) & 0.46 (0.07) & 0.67 (0.19) & 0.58 (0.11) & 0.92 (0.08) & 0.43 (0.06) \\\\ \n  & & 100 & 0.91 (0.05) & 0.44 (0.04) & 0.76 (0.11) & 0.52 (0.07) & 0.93 (0.04) & 0.41 (0.03) \\\\ \\hline\n\\end{tabular}\n\\end{table}\n\n\\begin{table}[ht]\n\\centering\n\\caption*{\\noindent Table C.6: {\\bf Uniform prior, \\textit{p}-hacking.} Posterior means and \n                    standard deviations from the \\textit{p}-hacking, \n                    publication bias, and uncorrected models when the data are simulated \n                    from the \\textit{p}-hacking model with cutoffs at\n                    $0.025$ and $0.05$, with \\textit{p}-hacking probabilities\n                    equal to $0.6$, $0.3$, and $0.1$ for $\\alpha = 0.025, 0.05$, and $1$} \n\\label{tab:Simulation_ph}\n\\begin{tabular}{lllrrrrrr}\n   \\multicolumn{3}{r}{\\textbf{True values}} & \n       \\multicolumn{2}{c}{\\textbf{\\textit{p}-hacking model}} &\n       \\multicolumn{2}{c}{\\textbf{Public. bias model}} &\n       \\multicolumn{2}{c}{\\textbf{Uncorrected model}}\\\\$\\tau$ & $\\theta_0$ & $n$ & \\multicolumn{1}{c}{$\\widehat{\\theta_0}$} & \\multicolumn{1}{c}{$\\widehat{\\tau}$} & \\multicolumn{1}{c}{$\\widehat{\\theta_0}$} & \\multicolumn{1}{c}{$\\widehat{\\tau}$} & \\multicolumn{1}{c}{$\\widehat{\\theta_0}$} & \\multicolumn{1}{c}{$\\widehat{\\tau}$} \\\\ \n   \\hline\n  \\multirow{9}{*}{$0.1$} & \\multirow{3}{*}{$0$} & 5 & -0.07 (0.14) & 0.28 (0.08) & 0.04 (0.07) & 0.17 (0.07) & 0.29 (0.06) & 0.15 (0.09) \\\\ \n  & & 30 & -0.02 (0.08) & 0.13 (0.05) & 0.00 (0.07) & 0.07 (0.03) & 0.29 (0.03) & 0.05 (0.04) \\\\ \n  & & 100 & -0.01 (0.04) & 0.11 (0.04) & -0.02 (0.05) & 0.06 (0.02) & 0.28 (0.01) & 0.03 (0.02) \\\\ \n   \\cdashline{3-9}\n & \\multirow{3}{*}{$0.2$} & 5 & 0.11 (0.13) & 0.28 (0.09) & 0.09 (0.05) & 0.20 (0.05) & 0.34 (0.05) & 0.13 (0.05) \\\\ \n  & & 30 & 0.20 (0.05) & 0.11 (0.05) & 0.16 (0.06) & 0.09 (0.04) & 0.34 (0.02) & 0.04 (0.02) \\\\ \n  & & 100 & 0.20 (0.03) & 0.09 (0.03) & 0.17 (0.04) & 0.08 (0.03) & 0.34 (0.01) & 0.02 (0.01) \\\\ \n   \\cdashline{3-9}\n & \\multirow{3}{*}{$0.8$} & 5 & 0.79 (0.09) & 0.20 (0.08) & 0.64 (0.15) & 0.32 (0.13) & 0.80 (0.08) & 0.19 (0.07) \\\\ \n  & & 30 & 0.79 (0.03) & 0.09 (0.04) & 0.79 (0.03) & 0.10 (0.04) & 0.80 (0.03) & 0.09 (0.04) \\\\ \n  & & 100 & 0.80 (0.02) & 0.09 (0.03) & 0.80 (0.02) & 0.10 (0.02) & 0.80 (0.02) & 0.09 (0.02) \\\\ \n  \\cline{2-9}\n\\multirow{9}{*}{$0.5$} & \\multirow{3}{*}{$0$} & 5 & 0.04 (0.23) & 0.47 (0.20) & -0.01 (0.14) & 0.37 (0.22) & 0.34 (0.12) & 0.30 (0.23) \\\\ \n  & & 30 & 0.08 (0.10) & 0.43 (0.08) & -0.23 (0.17) & 0.35 (0.10) & 0.37 (0.06) & 0.23 (0.09) \\\\ \n  & & 100 & 0.06 (0.06) & 0.44 (0.05) & -0.36 (0.14) & 0.37 (0.06) & 0.37 (0.03) & 0.25 (0.05) \\\\ \n   \\cdashline{3-9}\n & \\multirow{3}{*}{$0.2$} & 5 & 0.22 (0.22) & 0.53 (0.18) & 0.06 (0.11) & 0.45 (0.22) & 0.44 (0.13) & 0.33 (0.19) \\\\ \n  & & 30 & 0.24 (0.10) & 0.47 (0.07) & -0.18 (0.18) & 0.45 (0.09) & 0.45 (0.05) & 0.28 (0.08) \\\\ \n  & & 100 & 0.23 (0.05) & 0.47 (0.04) & -0.31 (0.18) & 0.47 (0.06) & 0.45 (0.03) & 0.28 (0.04) \\\\ \n   \\cdashline{3-9}\n & \\multirow{3}{*}{$0.8$} & 5 & 0.71 (0.23) & 0.61 (0.18) & 0.34 (0.25) & 0.74 (0.18) & 0.78 (0.18) & 0.53 (0.16) \\\\ \n  & & 30 & 0.82 (0.09) & 0.50 (0.08) & 0.43 (0.24) & 0.66 (0.12) & 0.87 (0.08) & 0.43 (0.06) \\\\ \n  & & 100 & 0.79 (0.05) & 0.50 (0.04) & 0.41 (0.17) & 0.65 (0.08) & 0.84 (0.05) & 0.42 (0.03) \\\\ \n\\hline\n\\end{tabular}\n\\end{table}\n\n\\newpage\n\n\\section*{Web Appendix C}\n\nRecall that a density $f(x;\\theta)$ is identifiable if $f(x;\\theta_{1})=f(x;\\theta_{2})$\nfor all $x$ implies that $\\theta_{1}=\\theta_{2}.$ Call a density\n$f(x;\\theta)$ \\textit{strongly identifiable} if $f(x;\\theta_{1})/f(x;\\theta_{2})$\nbeing constant for all $x$ in an open interval $I$ implies that\n$\\theta_{1}=\\theta_{2}$.\n\\paragraph{Proposition A.}\\label{prop:identifiable}\n\nLet $f(x;\\theta)$ be a family of densities on $\\mathbb{R}$, $-\\infty=a_{1}<a_{2}<\\ldots<a_{k+1}=\\infty$\na sequence of cutoffs, and $f_{[a_{i},a_{i+1})}(x;\\theta)$ the density\n$f$ truncated to $[a_{i},a_{i+1})$. Let $\\lambda_{i},k=1,\\ldots k$\nbe positive numbers satisfying $\\sum_{i=1}^{k}\\lambda_{i}=1$. Then\nthe mixture\n\\[\ng(x;\\lambda,\\theta)=\\sum_{i=1}^{k}\\lambda_{i}f_{[a_{i},a_{i+1})}(x;\\theta)\n\\]\nis identifiable in $(\\lambda,\\theta)$ if $f(x;\\theta)$ is strongly\nidentifiable in $\\theta$.\n\n\\paragraph{Proof.}\nAssume that $g(x;\\lambda_{1},\\theta_{1})=g(x;\\lambda_{2},\\theta_{2})$.\nThen $$\\lambda_{1i}f_{[a_{i},a_{i+1})}(x;\\theta_{1})=\\lambda_{2i}f_{[a_{i},a_{i+1})}(x;\\theta_{2})$$\nfor all $i$, thus\n\\[\n\\frac{\\lambda_{1i}}{\\lambda_{2i}}=\\frac{f_{[a_{i},a_{i+1})}(x;\\theta_{1})}{f_{[a_{i},a_{i+1})}(x;\\theta_{2})}.\n\\]\nThis implies that $f(x;\\theta_{1})/f(x;\\theta_{2})$ is constant for\n$x\\in[a_{i},a_{i+1})$. But since $f(x;\\theta)$ is strongly identifiable,\n$\\theta_{1}=\\theta_{2}$, and, consequently, $\\lambda_1 = \\lambda_2$.\n\n\nIf $f(x;\\theta)$ is real analytic and nowhere zero, $f(x;\\theta_{1})/f(x;\\theta_{2})$\nis also real analytic and nowhere zero. By the Identity Theorem \\citep[Corollary 1.2.6]{Krantz2002-bt}, if the ratio\n$f(x;\\theta_{1})/f(x;\\theta_{2})$ is constant on some interval $I$,\nthen $f(x;\\theta_{1})/f(x;\\theta_{2})$ is constant everywhere, hence\n$f(x;\\theta_{1})=f(x;\\theta_{2})$ everywhere. Thus a family of real\nanalytic nowhere zero densities is identifiable if and only if it is\nstrongly identifiable. Every exponential family of densities on the form\n\\[\nf(x;\\theta)=h(x)\\exp(\\eta(\\theta)^{T}T(x)-A(\\theta))\n\\]\nsatisfies this property, provided only that $h$ is nowhere zero real analytic\nand $T$ is real analytic. In particular, the normal family satisfies\nthe properties.\n\nNot every density is strongly identifiable. For instance, mixtures of uniforms are not strongly identifiable. And indeed, Proposition A fails when $f$ is a mixture of uniforms.\n\n\n\n\n% \\section*{Web Appendix C}\n\n% \\subsubsection*{Graphical representation of selection models}\n\n% It is handy to visualize selection models and their selection sets using directed acyclic graphs. To this end recall that a Bayesian network is a directed acyclic graph $G$ together with a probability density $p$ satisfying the property that $p(x)=\\prod_{v\\in V(G)}p(x_{v}\\mid x_{\\textrm{pa}(v)})$, where $V(G)$ is the set of vertices in $G$ and $x_{\\textrm{pa}(v)}$ are the parents of $x_{v}$ in $G$ \\citep{Pearl2014}. Transforming a Bayesian network for $p$ into a Bayesian network for $q_{H}$ is easy, just add the following to $G$: (i) The selection variable vertex $s$, and (ii) arrows $x$ to $s$ for each $x$ that $s$ depends on. Then\n% \\begin{equation}\n% q_{H}(x\\mid s=1)=\\frac{p(s=1\\mid x_{\\textrm{pa}(s)})}{p(s=1\\mid H^{c})}\\prod_{v\\in V(G)}p(x_{v}\\mid x_{\\textrm{pa}(v)})\\label{eq:DAG, selection model}.\n% \\end{equation}\n\n% To visualize the selection set $H$, start by drawing a dashed plate around the vertices in $H$. In plate notation \\citep{buntine1994operations}, a solid plate represents variables that are sampled together. The dashed plate does almost the same, for recall that $H$ contains all the elements that are sampled together until $s=1$. The semantic difference between a dashed and a solid plate is that every sample in a solid plate is observed, but only one of potentially many samples in a dashed plate is observed. The following bare-bones example should make things clear.\n\n% Figure \\ref{fig:Plate notation, simple example} displays the directed acyclic graphs of $p$ and the selection models when $H = \\emptyset$, $H=\\left\\{ x,\\theta\\right\\}$, and $H=\\left\\{ x\\right\\}$, respectively. The marginal distribution of $\\theta$ is not the same for $H=\\left\\{ x\\right\\}$ and $H=\\left\\{ x,\\theta\\right\\} $, as $q_{\\left\\{ x,\\theta\\right\\} }(\\theta) = p(\\theta)\\frac{p(s=1\\mid\\theta)}{p(s=1)}$ and $q_{x}(\\theta) = \\int\\frac{p(s=1\\mid x)}{p(s=1\\mid\\theta)}p(x,\\theta)dx=p(\\theta)$, i.e., it is affected by the selection mechanism $s$.\n\n% \\subsubsection*{Example}\\label{exa:Marginal density of theta}\n% Let $p(x,\\theta)=p(x\\mid\\theta)p(\\theta)$ be a density and $s$ be a function of $x$ only, so that $p(s=1\\mid x,\\theta)=p(s=1\\mid x)$.\n% The possible selection models are\n% \\begin{eqnarray*}\n% q_{\\emptyset}(x,\\theta) = q_{\\theta}(x,\\theta) & = & p(x,\\theta)\\\\\n% q_{(x,\\theta)}(x,\\theta) & = & \\frac{p(s=1\\mid x)}{p(s=1)}p(x,\\theta)\\\\\n% q_{x}(x,\\theta) & = & \\frac{p(s=1\\mid x)}{p(s=1\\mid\\theta)}p(x,\\theta)\n% \\end{eqnarray*}\n\n% \\begin{figure}\n% \\begin{center}     \n%  \\includegraphics{plots/figure_A.jpg}\n% \\end{center}\n% \\caption{\\label{fig:Plate notation, simple example} Three simple selection models. {\\bf (left)} the original $p(x,\\theta)$; {\\bf (middle)} the model $q_{\\left\\{ x,\\theta\\right\\} }$, where $\\theta$ and $x$ are\n% sampled together until $s=1$; {\\bf (right)} the model $q_{x}$, where only $x$ is sampled until $s=1$.}\n% \\end{figure}\n\n% Let $f(x,\\theta\\mid\\eta)=f(x\\mid\\theta,\\eta)p(\\theta)$ be the joint density of a random effects meta-analysis, where $x$ is the effect size, $\\theta$ is the study-specific parameter of interest, and $\\eta$ is a study-specific nuisance parameter such as the sample size of the study. The left plot of Figure \\ref{fig:Plate notation, simple example} is a visualization of $f(x,\\theta)$. If we have more than one study to analyse, we will have to work with product density $\\prod_{i=1}^{n}f(x_{i},\\theta_{i}\\mid\\eta_{i})$ instead of the stand-alone density $f(x,\\theta\\mid\\eta)$. This is visualised in the middle plot of Figure \\ref{fig:Plate notation, simple example}  by drawing a solid plate around the pair $(x,\\theta)$. When we are dealing with a fixed effects meta-analysis, in which $\\theta$ is fixed, the plate should be drawn around $x$ only (Figure \\ref{fig:Plate notation, simple example}, right graph). \n\n% \\subsubsection*{Graphical representation of the publication bias and $p$-hacking models}\n\n% To visualize selection models based on \\textit{p}-values, we must make some modifications to the original graph: (i) Add the \\textit{p}-value node $u$; (ii) Add an arrow from $x$ to $u$; (iii) Since the \\textit{p}-value $u$ usually depends on more information than just $x$, such as the standard deviation of $x$, add an arrow from $\\eta$ (which represents the extra information) to $u$ as well; (iv) Add the selection node $s$ and an arrow from $u$ to $s$. If $u$ is the only parent of $s$, we are dealing with selection models only based on \\textit{p}-values.\n\n% The placement of dashed and solid plates depends on which model we want to use. The idea behind the publication bias model is that a completely new study is done whenever the last one failed to be published. This implies that $\\theta$ and $x$ are sampled together. The left plot of Figure \\ref{fig:Plate notation, publication bias and p-hacking} shows the direct acyclic graph of the normal publication bias model defined in Proposition 3 in the main text. In this particular case, $\\eta$ corresponds to $\\sigma$, the standard deviation. Moreover, $u$ is a \\textit{p}-value, $\\theta_{0}$ is the mean of the effect size distribution, $\\tau$ is the standard deviation of the effect size distribution, and $\\rho$ is the selection probability function. The variable $Z$ lives on the unit interval, and encodes the editor's decision to publish: If the observed \\textit{p}-value is less than $Z$, the study is published. Importantly, $Z$ is placed inside the selection set because a new \\textit{p}-value cut-off decision is made for each study received. Since $x$ and $\\theta$ are sampled together, the selection mechanism modifies $p(\\theta)$.%, as can be seen in the example \\ref{exa:Publication bias, theta distribution} here below.\n\n% In the \\textit{p}-hacking scenario, the \\textit{p}-hacker will hack his study all the way to significance, regardless of $\\theta$. This means that $\\theta$ and $x$ are sampled separately and $\\theta$ must be placed outside the selection set. Moreover, the decision of how much to \\textit{p}-hack is not reevaluated at each attempt. Consequently, the random variable that controls the \\textit{p}-hacking decisions, analogously to the publication bias model, $Z$, is also placed outside the selection graph. This is the case, for example, of an author who decides to \\textit{p}-hack to level $\\alpha$ ($Z = \\alpha$): he acts on $x$ to obtain the desired \\textit{p}-value, whatever the sampled $\\theta$ is. The graphical representation of this model is shown in the right plot of Figure \\ref{fig:Plate notation, publication bias and p-hacking}. Since $x$ and $\\theta$ are not sampled together, the selection mechanism does not modify $p(\\theta)$.\n\n% \\begin{figure}\n% \\begin{center}\n% \\includegraphics{plots/figure_B.jpg}\n% \\end{center}\n% \\caption{\\label{fig:Plate notation, publication bias and p-hacking} Directed acyclic graphs for: {\\bf (left)}\n% the publication bias model; {\\bf (right)} the \\textit{p}-hacking model. The dashed plates enclose the selection sets and the the solid plates enclose variables that are repeated together.}\n% \\end{figure}\n\n\n\\bibliographystyle{biom}\n\\bibliography{main.bib}\n\n\\end{document}", "meta": {"hexsha": "52331d9c6712e83812293a6ec1190eb63c3b0e35", "size": 32027, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "supportingInformation_toEditLayout.tex", "max_stars_repo_name": "JonasMoss/p-hacking", "max_stars_repo_head_hexsha": "38c4e854cb9b6f8675ca384c3031db0d5ff9e642", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-14T23:18:58.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-14T23:18:58.000Z", "max_issues_repo_path": "supportingInformation_toEditLayout.tex", "max_issues_repo_name": "JonasMoss/p-hacking", "max_issues_repo_head_hexsha": "38c4e854cb9b6f8675ca384c3031db0d5ff9e642", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-07-29T11:31:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-06T14:38:26.000Z", "max_forks_repo_path": "supportingInformation_toEditLayout.tex", "max_forks_repo_name": "JonasMoss/p-hacking", "max_forks_repo_head_hexsha": "38c4e854cb9b6f8675ca384c3031db0d5ff9e642", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 75.0046838407, "max_line_length": 1231, "alphanum_fraction": 0.5682705217, "num_tokens": 14669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381667555713, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.33426585926624786}}
{"text": "\\documentclass[landscape,twocolumn]{article}\n\\usepackage{biblatex, booktabs, hyperref, graphicx, mathtools, pgfplots, pgfplotstable}\n\\addbibresource{references.bib}\n\\pgfplotsset{compat = 1.16}\n\\pgfplotstableread[col sep=comma]{../Output/results.csv}\\results{}\n\\pgfplotstableread[col sep=comma]{../Output/Naive Bayes.csv}\\naivebayes{}\n\\pgfplotstableread[col sep=comma]{../Output/Logistic Regression.csv}\\logisticregression{}\n\\pgfplotstableread[col sep=comma]{../Output/SVM.csv}\\svm{}\n\\title{COMP5318 Assignment 1}\n\\author{Nicholas Grasevski (ngra5777, 500710654)}\n\\begin{document}\n\\maketitle\n\\begin{abstract}\n\tIn this report several image classifiers are benchmarked against a grayscale image dataset. With the help of some feature engineering, a Support Vector Machine with Radial Basis Function kernel is the highest performing classifier with 89.5\\% accuracy on the test set.\n\\end{abstract}\n\n\\section{Introduction}\nObject recognition is one of the biggest subfields of computer vision, with many practical applications such as computer aided diagnosis~\\cite{doi2007computer}, face detection~\\cite{hjelmaas2001face}, Optical Character Recognition~\\cite{mori1999optical} and so on.\n\nThe current state of the art in object recognition is Convolutional Neural Networks~\\cite{iandola2016squeezenet}. The convolutional neural network takes in the raw pixel data and applies several layers of `convolution' transformations, which aggregate nearby pixels into higher order features in a hierarchical fashion. Prior to the prevalence of GPU based neural network training, the previous state of the art was to apply some hand crafted transformations to the input image to extract higher order features~\\cite{rybski2010visual}, and then pass the encoded features through a classical machine learning algorithm such as a generalized linear model~\\cite{ebrahimzadeh2014efficient}.\n\nThe aim of this study is to compare and contrast several different machine learning algorithms when applied to an object detection problem. This should provide insight into their relative ability to capture the information in the data, with the help of some standard hand crafted feature transformations.\n\n\\section{Methods}\n\\begin{figure}[ht]\n\t\\includegraphics[width=\\linewidth]{../Dataset_image}\n\t\\caption{Grayscale $28 \\times 28$ images of clothing.}\\label{fig:images}\n\\end{figure}\n\nSeveral machine learning algorithms were benchmarked against a corpus of $28 \\times 28$ grayscale images. Examples of the images can bee seen in figure~\\ref{fig:images}. There are 10 classes in total:\n\\begin{enumerate}\n\t\\item T-shirt/Top\n\t\\item Trouser\n\t\\item Pullover\n\t\\item Dress\n\t\\item Coat\n\t\\item Sandal\n\t\\item Shirt\n\t\\item Sneaker\n\t\\item Bag\n\t\\item Ankle Boot\n\\end{enumerate}\n\n30,000 of these images are used for training and hyperparameter tuning using 10-fold cross-validation, and 2,000 are used as a hold-out set to evaluate the best classifier according to the cross validation results.\n\nThe performance is evaluated primarily based on top-1 accuracy, as defined in equation~\\ref{eq:accuracy}:\n\n\\begin{equation}\n\t\\label{eq:accuracy}\n\t\\text{Accuracy} = \\frac{\\text{Number of correct classifications}}{\\text{Total number of test examples used}}\n\\end{equation}\n\nThe training and inference time cost of each algorithm is also evaluated. The experiment was performed on a 16-inch 2019 MackBook Pro, with a 2.3GHz 8-Core Intel Core i9 and 32 GB 2667 MHz DDR4 RAM\\@.\n\n\\subsection{Preprocessing}\nThe images were preprocessed by first getting the Histogram of Oriented Gradients descriptor, and then passing the descriptor into a Principal Component Analysis.\n\n\\subsubsection{Histogram of Oriented Gradients}\n\\begin{figure}[ht]\n\t\\includegraphics[width=\\linewidth]{../Output/hog}\n\t\\caption{Histogram of Oriented Gradients transformation.}\\label{fig:hog}\n\\end{figure}\n\nThe input data was preprocessed using a feature descriptor called `Histogram of Oriented Gradients' (HOG)~\\cite{dalal2005histograms}. It performs the following steps:\n\\begin{description}\n\t\\item[Gamma compression] First, the square root of the raw pixel data is taken to reduce the influence of illumination effects.\n\t\\item[Gradient computation] The horizontal and vertical gradients between adjacent pixels are calculated, resulting in each cell having a 2D gradient vector.\n\t\\item[Orientation binning] The orientations of these vectors are discretized, into 8 bins in our case, corresponding to bins from 0 to 180 degrees.\n\t\\item[Cell histogram] These discretized orientations are then aggregated by `cells', which in our case are $4 \\times 4$ pixel areas, and collected in a histogram, with each pixel orientation contributing to the histogram according to its magnitude.\n\t\\item[Descriptor blocks] The cells are then grouped into `blocks', which in our case are $3 \\times 3$ cell areas, in a sliding window fashion.\n\t\\item[Block normalization] The cells in each block are normalized against one another using the $L_1$ norm in our case.\n\t\\item[Object detection] Finally, the overlapping normalized blocks are flattened into a feature vector, to be fed into a machine learning algorithm.\n\\end{description}\n\nThe HOG descriptor achieves the following tasks:\n\n\\begin{description}\n\t\\item[Normalization] The block descriptor normalization provides better invariance to illumination, shadowing, and edge contrast.\n\t\\item[Feature Extraction] The raw pixel data is distilled to a more meaningful representation of the object edges, as can be seen in figure~\\ref{fig:hog}.\n\\end{description}\n\n\\subsubsection{Principal Component Analysis}\nThe output dimension of the HOG descriptor with the aforementioned parameters is 1800 ($\\text{9 cells per block} \\times \\text{25 blocks} \\times \\text{8 orientations}$) which is more than double the original flattened dimension ($28 \\times 28$). This can cause:\n\n\\begin{description}\n\t\\item[Slow training] It is computationally intensive to work with these additional dimensions.\n\t\\item[High variance] Having extra artificial dimensions increases the chances of overfitting.\n\\end{description}\n\nTo mitigate these problems, a Principal Component Analysis (PCA)~\\cite{wold1987principal} is performed, wherein the input data is factorized into a set of 3 matrices, known as Singular Value Decomposition~\\cite{golub1971singular}, as shown in equation~\\ref{eq:svd}:\n\n\\begin{equation}\n\t\\label{eq:svd}\n\t\\textbf{X}=\\textbf{U}\\Sigma\\textbf{W}^T\n\\end{equation}\n\nWhere $\\textbf{X}$ is the input features, $\\textbf{U}$ is an n-by-n matrix, $\\Sigma$ is an n-by-p rectangular diagonal matrix of positive numbers $\\sigma_{\\left(k\\right)}$, and $\\textbf{W}$ is a p-by-p matrix. We can then truncate the $\\textbf{W}$ matrix to include only the $L$ largest singular values and their singular vectors, as in equation~\\ref{eq:trunc}:\n\n\\begin{equation}\n\t\\label{eq:trunc}\n\t\\textbf{T}_L=\\textbf{X}\\textbf{W}_L\n\\end{equation}\n\nFrom this truncated form, we will take the first 128 principal components of the data, thus resulting in a net reduction of the dimension of the original data by a factor of 6.\n\n\\subsection{Algorithms}\n\\begin{table*}\n\t\\begin{tabular}{ccccc}\n\t\t\\textbf{Name} & \\textbf{Train Time} & \\textbf{Train Space} & \\textbf{Predict Time} & \\textbf{Predict Space} \\\\\\toprule\n\t\tLogistic Regression & $\\mathcal{O}\\left(n^2d\\right)$ & $\\mathcal{O}\\left(nd\\right) $ & $\\mathcal{O}\\left(d\\right)$ & $\\mathcal{O}\\left(d\\right)$\\\\\n\t\tNaive Bayes & $\\mathcal{O}\\left(nd\\right)$ & $\\mathcal{O}\\left(d\\right)$ & $\\mathcal{O}\\left(d\\right)$ & $\\mathcal{O}\\left(d\\right)$\\\\\n\t\tSVM & $\\mathcal{O}\\left(n^3d\\right)$ & $\\mathcal{O}\\left(nd\\right)$ & $\\mathcal{O}\\left(nd\\right)$ & $\\mathcal{O}\\left(nd\\right)$\\\\\n\t\\end{tabular}\n\t\\caption{Computational complexity of different algorithms for $n$ features and $d$ dimensions.}\\label{tab:algorithms}\n\\end{table*}\n\nSeveral different algorithms are applied in turn to the preprocessed data, and a grid of their hyperparameters are explored. A stratified 10-fold cross validation is performed on each hyperparameter combination and the highest scoring (algorithm, hyperparameter) combination is retrained on the entire training set and evaluated on the test set.\n\nIn real world applications, time and memory are not infinite and the machine learning is bound by the physical limitations of the hardware. Table~\\ref{tab:algorithms} shows the computational complexity of the various algorithms.\n\n\\subsubsection{Logistic Regression}\nLogistic Regression is a generalization of linear regression to estimate the probability of a given class~\\cite{wright1995logistic}. It models a probability by applying the softmax function (or sigmoid in the binary case) to a linear model, as in equation~\\ref{eq:lr}:\n\n\\begin{equation}\n\t\\label{eq:lr}\n\t\\Pr\\left(Y_i=c\\right)=\\frac{e^{\\beta_c \\cdot \\textbf{X}_i}}{\\sum_h{e^{\\beta_h \\cdot \\textbf{X}_i}}}\n\\end{equation}\n\nWhere $Y_i$ is the label of a given sample, $\\textbf{X}_i$ is the input vector, and $\\beta_c$ is the weight vector from the fitted model for the given class $c$.\n\nIt fits a linear decision boundary such that the logistic loss is minimized, as defined in equation~\\ref{eq:logisticregression}:\n\n\\begin{equation}\n\t\\label{eq:logisticregression}\n\tL\\left(y,p\\right)=-\\sum{y\\log{p}}\n\\end{equation}\n\nWhere $L$ is the loss, $y$ is the ground truth (as a one hot class vector) and $p$ is the predicted probability (as a softmax vector). It is normally trained using batch gradient descent. Although the training for Logistic Regression is slower and more memory intensive than Naive Bayes, the inference complexity is identical, making it a relatively efficient machine learning algorithm.\n\n\n\\subsubsection{Naive Bayes}\nNaive Bayes is a generative model that uses Bayes' Theorem to calculate the probability of a given class given the input variables~\\cite{rish2001empirical}. The algorithm assumes that the input variables are conditionally independent, ie $\\Pr\\left(A,B|Y\\right)=\\Pr\\left(A|Y\\right)\\Pr\\left(B|Y\\right)$, yielding a closed-form solution to the probability calculation, as can be seen in equation~\\ref{eq:naivebayes}:\n\n\\begin{equation}\n\t\\label{eq:naivebayes}\n\t\\Pr\\left(C_k|x_1,\\ldots,x_n\\right)=\\frac{1}{Z}\\Pr\\left(C_k\\right)\\prod_{i=1}^n{\\Pr\\left(x_i|C_k\\right)}\n\\end{equation}\n\nFor class $C$, where the evidence $Z=\\Pr\\left(\\textbf{X}\\right)=\\sum_k{\\Pr\\left(C_k\\right)\\Pr\\left(\\textbf{x}|C_k\\right)}$ is a scaling factor dependent only on $x_1,\\ldots,x_n$, that is, a constant if the values of the feature variables are known.\n\nThis simple formulation makes training Naive Bayes very computationally efficient and also easily parallelizable, thanks to the conditional independence assumption. However, the assumption rarely holds in practise, leading to poor performance compared to more sophisticated techniques.\n\n\\subsubsection{Support Vector Machine}\nSupport Vector Machine is a supervised learning algorithm which produces a non-probabilistic classifier, attempting to separate the classes by a set of hyperplanes. It can be used as a linear classifier, or for any nonlinear `kernel' satisfying Mercer's condition~\\cite{noble2006support}.\n\nThis gives it more predictive power compared to Naive Bayes (which can only predict based on statistically independent variables) and Logistic Regression (which can only predict a linear decision boundary). However the additional power afforded by nonlinearity comes at a cost, as the resultant optimization problem must be solved using a quadratic programming algorithm such as coordinate descent, which typically has cubic time complexity.\n\nFurthermore the inference time can be an order of magnitude slower compared to Naive Bayes and Logistic Regression. More than one weight vector is required, and the number of weight vectors required is proportional to the size of the input data.\n\n\\section{Experiments and results}\n\\begin{figure}\n\t\\begin{tikzpicture}\n\t\t\\begin{axis}[\n\t\t\ttitle={Accuracy},\n\t\t\tybar, nodes near coords,\n\t\t\tlegend style={legend pos={outer north east}},\n\t\t\txlabel={Model},\n\t\t\txtick=data,\n\t\t\txticklabels from table={\\results}{name},\n\t\t\tx tick label style={rotate=90,anchor=east},\n\t\t\tylabel={Accuracy (\\%)}\n\t\t\t]\n\t\t\t\\addplot table[x expr=\\coordindex, y expr=100*\\thisrow{test_acc}]{\\results};\n\t\t\t\\addplot table[x expr=\\coordindex, y expr=100*\\thisrow{cv_acc}]{\\results};\n\t\t\t\\legend{Test,CV}\n\t\t\\end{axis}\n\t\\end{tikzpicture}\n\t\\caption{Comparison of accuracy.}\\label{fig:accuracy}\n\\end{figure}\n\n\\begin{figure}\n\t\\begin{tikzpicture}\n\t\t\\begin{axis}[\n\t\t\ttitle={Time},\n\t\t\tybar, nodes near coords,\n\t\t\tlegend style={legend pos={outer north east}},\n\t\t\txlabel={Model},\n\t\t\txtick=data,\n\t\t\txticklabels from table={\\results}{name},\n\t\t\tx tick label style={rotate=90,anchor=east},\n\t\t\tylabel={Time (s)}\n\t\t\t]\n\t\t\t\\addplot table[x expr=\\coordindex, y expr=\\thisrow{fit_time_seconds}]{\\results};\n\t\t\t\\addplot table[x expr=\\coordindex, y expr=\\thisrow{inf_time_seconds}]{\\results};\n\t\t\t\\legend{Fit,Predict}\n\t\t\\end{axis}\n\t\\end{tikzpicture}\n\t\\caption{Comparison of time.}\\label{fig:time}\n\\end{figure}\n\n\\begin{table*}\n\t\\pgfplotstabletypeset[\n\tcolumns={name,test_acc,cv_acc,fit_time_seconds,inf_time_seconds},\n\tcolumns/name/.style={string type,column name=Model},\n\tcolumns/test_acc/.style={multiply by=100,column name={Test Acc\\%}},\n\tcolumns/cv_acc/.style={multiply by=100,column name={CV Acc\\%}},\n\tcolumns/fit_time_seconds/.style={column name={Fit Time (s)}},\n\tcolumns/inf_time_seconds/.style={column name={Inf Time (s)}},\n\tevery head row/.style={after row=\\toprule},\n\t]{\\results}\n\t\\caption{Comparison of machine learning algorithms.}\\label{tab:results}\n\\end{table*}\n\nAs can be seen in table~\\ref{tab:results}, there is a tradeoff between training speed and accuracy. Naive Bayes is by far the fastest to train, but does not achieve great accuracy. SVM is the slowest to train, but is highly accurate by comparison. Logistic Regression is slow to train, but notably has similar inference speed to Naive Bayes, due to the same algorithmic complexity during inference.\n\nAlthough naive bayes has the lowest accuracy, it is still decent. This is testament to the effectiveness of the feature engineering and preprocessing that was done to normalize the data and extract meaningful independent features.\n\n\n\\subsection{Logistic Regression}\n\\begin{table*}\n\t\\pgfplotstabletypeset[\n\tcolumns={param_C,param_penalty,mean_test_score,std_test_score,mean_fit_time,std_fit_time,mean_score_time,std_score_time},\n\tcolumns/param_C/.style={column name=C},\n\tcolumns/param_penalty/.style={string type,column name=Penalty},\n\tcolumns/mean_test_score/.style={multiply by=100,column name={Acc\\%}},\n\tcolumns/std_test_score/.style={multiply by=100,column name=STD},\n\tcolumns/mean_fit_time/.style={column name={Fit Time (s)}},\n\tcolumns/std_fit_time/.style={column name=STD},\n\tcolumns/mean_score_time/.style={column name={Score Time (s)}},\n\tcolumns/std_score_time/.style={column name=STD},\n\tevery head row/.style={after row=\\toprule},\n\t]{\\logisticregression}\n\t\\caption{Logistic Regression cross validation results.}\\label{tab:logisticregression}\n\\end{table*}\n\nAs per table~\\ref{tab:logisticregression}, two parameters were tuned for logistic regression:\n\n\\begin{description}\n\t\\item[C] Inverse of regularization strength. A regularization strength of 1 (corresponding to the uniform prior) performed best, making a good balance between bias and variance.\n\t\\item[Penalty] What type of regularization to use. $L_1$ and $L_2$ regularization were both attempted (corresponding to assumptions of laplacian and gaussian noise respectively), with $L_2$ performing consistently better. Perhaps the images naturally had some gaussian noise, allowing the $L_2$ penalty to account for that noise more effectively than the $L_1$ penalty. It is also conceivable that the sparseness enforced by the $L_1$ penalty is undesirable as the input data is continuous numerical data, so taking individual points (pixel groups in this case, due to the HOG transform) and discarding the surrounding context may cause overfitting when generalizing to the test data.\n\\end{description}\n\n\n\\subsection{Naive Bayes}\n\\begin{table*}\n\t\\pgfplotstabletypeset[\n\tcolumns={mean_test_score,std_test_score,mean_fit_time,std_fit_time,mean_score_time,std_score_time},\n\tcolumns/mean_test_score/.style={multiply by=100,column name={Acc\\%}},\n\tcolumns/std_test_score/.style={multiply by=100,column name=STD},\n\tcolumns/mean_fit_time/.style={column name={Fit Time (s)}},\n\tcolumns/std_fit_time/.style={column name=STD},\n\tcolumns/mean_score_time/.style={column name={Score Time (s)}},\n\tcolumns/std_score_time/.style={column name=STD},\n\tevery head row/.style={after row=\\toprule},\n\t]{\\naivebayes}\n\t\\caption{Naive Bayes cross validation results.}\\label{tab:naivebayes}\n\\end{table*}\n\nBeing a simple algorithm, no hyperparameters were tuned for Naive Bayes. As per table~\\ref{tab:naivebayes}, Both training and inference time were infinitesimal, thanks to the linear time complexity of the algorithm.\n\n\n\\subsection{Support Vector Machine}\n\\begin{table*}\n\t\\pgfplotstabletypeset[\n\tcolumns={param_C,param_kernel,mean_test_score,std_test_score,mean_fit_time,std_fit_time,mean_score_time,std_score_time},\n\tcolumns/param_C/.style={column name=C},\n\tcolumns/param_kernel/.style={string type,column name=Kernel},\n\tcolumns/mean_test_score/.style={multiply by=100,column name={Acc\\%}},\n\tcolumns/std_test_score/.style={multiply by=100,column name=STD},\n\tcolumns/mean_fit_time/.style={column name={Fit Time (s)}},\n\tcolumns/std_fit_time/.style={column name=STD},\n\tcolumns/mean_score_time/.style={column name={Score Time (s)}},\n\tcolumns/std_score_time/.style={column name=STD},\n\tevery head row/.style={after row=\\toprule},\n\t]{\\svm}\n\t\\caption{SVM cross validation results.}\\label{tab:svm}\n\\end{table*}\n\nAs per table~\\ref{tab:svm}, two main hyperparameters were tested for SVM:\\@\n\n\\begin{description}\n\t\\item[C] Inverse of regularization strength. In this case, a regularization strength of 10 performed marginally better than other settings.\n\t\\item[Kernel] Which kernel type to use. The Radial Basis Function performed the best. This makes sense because intuitively it is grouping together images which have edges in similar locations, whereas the linear kernel (ie no kernel) would mostly classify based on the overall contrast of each group of pixels in the image, with no consideration for the proximity of said groups of pixels. The polynomial kernel also performed well, the default setting is degree 3, perhaps degree 2 could provide better results. The sigmoid kernel performed worst.\n\\end{description}\n\n\\section{Conclusion}\nOut of the algorithms applied, Support Vector Machine achieved the highest accuracy at the expense of a relatively long training time. Naive Bayes was by far the fastest in both training and inference, due to the efficient time complexity of the algorithm. Further improvements would be to consider convolutional neural networks in order to automatically extract similar features to the HOG descriptor via backpropagation and stochastic gradient descent. Furthermore, GPU acceleration could be utilized to achieve fast training and inference by parallelizing the pixel-wise operations which are very common in computer vision.\n\n\\printbibliography\\appendix\n\\section{Running the code}\n\\begin{description}\n\t\\item[Dependencies] \\texttt{pip3 install h5py pandas scikit-image scikit-learn}\n\t\\item[Usage] Run the steps in the notebook sequentially to get the tuning and evaluation results.\n\\end{description}\n\nDetailed cross validation results will be written as csv files to \\texttt{Output} for each respective classifier, along with the final predictions as \\texttt{Output/predicted\\_labels.h5}. Note that the \\texttt{ALGORITHMS} parameter can be modified at will to change the grid search process, for example to speed up the runtime of the script by excluding certain algorithms or hyperparameter combinations.\n\n\\end{document}\n", "meta": {"hexsha": "638ee2d2b3a9e7739caed41a71fdb5059799e628", "size": 19809, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/report.tex", "max_stars_repo_name": "grasevski/COMP5318-assignment1", "max_stars_repo_head_hexsha": "db47c31cf614685ff35f07d7f6abd108c5909e9e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "report/report.tex", "max_issues_repo_name": "grasevski/COMP5318-assignment1", "max_issues_repo_head_hexsha": "db47c31cf614685ff35f07d7f6abd108c5909e9e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/report.tex", "max_forks_repo_name": "grasevski/COMP5318-assignment1", "max_forks_repo_head_hexsha": "db47c31cf614685ff35f07d7f6abd108c5909e9e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 66.2508361204, "max_line_length": 686, "alphanum_fraction": 0.7831288808, "num_tokens": 5005, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381667555713, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.33426585926624786}}
{"text": "% Copyright 2021 UChicago Argonne, LLC\n% Author:\n% - Haoyu Wang and Roberto Ponciroli, Argonne National Laboratory\n% - Andrea Alfonsi, Idaho National Laboratory\n\n% Licensed under the Apache License, Version 2.0 (the \"License\");\n% you may not use this file except in compliance with the License.\n% You may obtain a copy of the License at\n\n%   https://www.apache.org/licenses/LICENSE-2.0.txt\n\n% Unless required by applicable law or agreed to in writing, software\n% distributed under the License is distributed on an \"AS IS\" BASIS,\n% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n% See the License for the specific language governing permissions and\n% limitations under the License.\n\n\\section{Input of FARM for RAVEN}\n\nIn this section, the external matrices file structure, FARM model definition, and input/output file example will be \ndiscussed. In order to run FARM, two XML files are required:\n\\begin{itemize}\n  \\item External Matrices File (See Section \\ref{ExtMatFileStructure}), and\n  \\item Input File (See Section \\ref{InputFile})\n\\end{itemize}\nCurrently two version of Reference Governor SIMO are provided: paramterized version, and unparameterized version. \n\\begin{itemize}\n  \\item Parameterized Version: Multiple state-space representations profiles are provided in the external matrices file, \n  labeled by a parameter \"ActuatorParameter\". The FARM will select the closest profile based on the value of input \n  variable \"PwrSet\".\n  \\item Unparameterized Version: Single state-space representation profile is provided, and will be used in all the time.\n\\end{itemize}\n\n\\subsection{External Matrices File Structure}\n\\label{ExtMatFileStructure}\nAs discussed in \\ref{RG_SIMO}, the state space matrices \\begin{math} \\textbf{A} \\end{math}, \n\\begin{math} \\textbf{B} \\end{math}, \\begin{math} \\textbf{C} \\end{math} are required for the FARM to run. \nIn addition, the norminal values of \n\\begin{math} u \\end{math}, \n\\begin{math} \\overrightarrow{x} \\end{math}, \n\\begin{math} \\overrightarrow{y} \\end{math} needs to be known for the following equations at \n\\begin{math}k=0 \\end{math} to be satisfied:\n\\begin{itemize}\n  \\item \\begin{math} \\overrightarrow{x}[k+1]=\\textbf{A}*\\overrightarrow{0}+\\textbf{B}*0 \\end{math}\n  \\item \\begin{math} \\overrightarrow{0}=\\textbf{C}*\\overrightarrow{0} \\end{math}\n\\end{itemize}\nIn addition, the latest value of \\begin{math} \\overrightarrow{x} \\end{math} needs to be known as the current system state \nif no other values are provided in the Input File.\\newline\n\n\\subsubsection{Parameterized External Matrices File}\n\\label{ParaExtMatFile}\nThe following Listing \\ref{lst:ParaExtXMLExample} is a example external matrices file for Parameterized Reference \nGovernor with necessary information:\n\n\\begin{lstlisting}[style=XML,morekeywords={anAttribute}, \n  caption=Parameterized External Matrices File Example., label=lst:ParaExtXMLExample]\n<DataObjectMetadata name=\"rom_stats\">\n  <DMDrom type=\"Static\">\n    <DMDcModel>\n      <dmdTimeScale>1800 1810\n      <UNorm>\n        <realization ActuatorParameter=\"-1.15e+01\" sample=\"0\">-4.68e-02</realization>\n        <realization ActuatorParameter=\"-3.45e+01\" sample=\"1\">-4.30e-01</realization>\n      </UNorm>\n      <XNorm>\n        <realization ActuatorParameter=\"-1.15e+01\" sample=\"0\">2.55e+01 0.00e+00</realization>\n        <realization ActuatorParameter=\"-3.45e+01\" sample=\"1\">2.55e+01 0.00e+00</realization>\n      </XNorm>  \n      <YNorm>\n        <realization ActuatorParameter=\"-1.15e+01\" sample=\"0\">3.20e+01 2.55e+01</realization>\n        <realization ActuatorParameter=\"-3.45e+01\" sample=\"1\">3.20e+01 2.55e+01</realization>\n      </YNorm>\n      <XLast>\n        <realization ActuatorParameter=\"-1.15e+01\" sample=\"0\">2.44e+01 4.12e+01</realization>\n        <realization ActuatorParameter=\"-3.45e+01\" sample=\"1\">2.19e+01 1.38e+02</realization>\n      </XLast>\n      <Atilde>\n        <realization ActuatorParameter=\"-1.15e+01\" sample=\"0\">\n          <imaginary>0.00e+00 0.00e+00 0.00e+00 0.00e+00</imaginary>\n          <matrixShape>2,2</matrixShape>\n          <real>1.00e+00 -1.18e-01 -6.25e-05 4.14e-03</real>\n        </realization>\n        <realization ActuatorParameter=\"-3.45e+01\" sample=\"1\">\n          <imaginary>0.00e+00 0.00e+00 0.00e+00 0.00e+00</imaginary>\n          <matrixShape>2,2</matrixShape>\n          <real>1.00e+00 -5.61e-02 -6.90e-05 1.32e-01</real>\n        </realization>\n      </Atilde>\n      <Btilde>\n        <realization ActuatorParameter=\"-1.15e+01\" sample=\"0\">\n          <imaginary>0.00e+00 0.00e+00</imaginary>\n          <matrixShape>2,1</matrixShape>\n          <real>-2.01e-04 -4.21e+00</real>\n        </realization>\n        <realization ActuatorParameter=\"-3.45e+01\" sample=\"1\">\n          <imaginary>0.00e+00 0.00e+00</imaginary>\n          <matrixShape>2,1</matrixShape>\n          <real>-2.31e-04 -3.71e+00</real>\n        </realization>\n      </Btilde>\n      <Ctilde>\n        <realization ActuatorParameter=\"-1.15e+01\" sample=\"0\">\n          <imaginary>0.00e+00 0.00e+00 0.00e+00 0.00e+00</imaginary>\n          <matrixShape>2,2</matrixShape>\n          <real>-1.00e+00 1.00e+00 -3.48e-10 1.10e-16</real>\n        </realization>\n        <realization ActuatorParameter=\"-3.45e+01\" sample=\"1\">\n          <imaginary>0.00e+00 0.00e+00 0.00e+00 0.00e+00</imaginary>\n          <matrixShape>2,2</matrixShape>\n          <real>-1.00e+00 1.00e+00 -5.85e-10 7.81e-18</real>\n        </realization>\n      </Ctilde>\n    </DMDcModel>\n  </DMDrom> \n</DataObjectMetadata>\n\\end{lstlisting}\n\nAs one can see, all the required information for FARM are included in the \\xmlNode{DMDcModel} block. \nIndeed, the name of this block and its parent blocks is flexible:\n\\begin{itemize}\n  \\item \\xmlNode{DataObjectMetadata}, Root element of XML file, other names are acceptable.\n  \\item \\xmlNode{DMDrom}, Child 1 level element of XML file, other names are acceptable.\n  \\item \\xmlNode{DMDcModel}, Child 2 level element of XML file, other names are acceptable.\n\\end{itemize}\n\nAs long as the following keywords and inputs are the Child 3 level elements of this XML file, the information can \nbe processed for FARM execution:\n\\begin{itemize}\n  \\item \\xmlNode{dmdTimeScale}, \\xmlDesc{float vector, required parameter}, \n  the time step marks used in DMDc calculation. \n  At least two consecutive time step value are required to calculate the discrete time interval;\n\\end{itemize}\n\nSome items (\\xmlNode{UNorm}, \\xmlNode{XNorm}, \\xmlNode{YNorm}, \\xmlNode{XLast}, \\xmlNode{Atilde}, \\xmlNode{Btilde}, \n\\xmlNode{Ctilde}) contains multiple \\xmlNode{realization} nodes, in the format of \n\\xmlNode{realization ActuatorParameter=\"some float value\" sample=\"some integer value\"}, and the corresponding \nvalues are indexed by this ActuatorParameter. \n\\begin{itemize}\n  \\item \n  \\begin{itemize}\n    \\item The \\xmlNode{ActuatorParameter} attribute share the same unit with the input variable \"PwrSet\", and the \n    parameterized Reference Governor SIMO will select the realization whose \\xmlNode{ActuatorParameter} value is \n    closest to the input variable \"PwrSet\";\n    \\item The \\xmlNode{sample} attribute contains a consecutive integer value starting from 0.\n  \\end{itemize}\n\\end{itemize}\nAll the following items should share the same list of \\xmlNode{ActuatorParameter} attribute:\n\\begin{itemize}\n  \\item \\xmlNode{UNorm}, \\xmlDesc{float scalar, required parameter}, \n  the norminal value of system actuation variable \\begin{math} u \\end{math};\n  \\item \\xmlNode{XNorm}, \\xmlDesc{float vector, required parameter}, \n  the norminal value of system state vector \\begin{math} \\overrightarrow{x}\\in\\mathbb{R}^n \\end{math};\n  \\item \\xmlNode{YNorm}, \\xmlDesc{float vector, required parameter}, \n  the norminal value of system output vector \\begin{math} \\overrightarrow{y}\\in\\mathbb{R}^p \\end{math};\n  \\begin{itemize}\n    \\item Note: the \\xmlNode{YNorm} must have at least realization that is within the range defined by \n    \"Min\\_Target\" and \"Max\\_Target\" in the definition of Reference Governor SIMO EnternalModel. \n    See Listing \\ref{lst:Para_RGSIMOExample} in Section \\ref{ParaInputFile}.\n  \\end{itemize}\n  \\item \\xmlNode{XLast}, \\xmlDesc{float vector, required parameter}, \n  the latest value of system state vector \\begin{math} \\overrightarrow{x}\\in\\mathbb{R}^n \\end{math}, \n  \\textbf{without norminal value subtraction};\n\n  \\item \\xmlNode{Atilde}, \\xmlDesc{complex matrix, required parameter}, \n  the state matrix \\begin{math} \\textbf{A}\\in\\mathbb{C}^{n \\times n} \\end{math}:\n  \\begin{itemize}\n    \\item \\xmlNode{imaginary}, \\xmlDesc{float matrix, optional parameter}, \n    the imaginary part of state matrix \\begin{math} \\textbf{A} \\end{math}. The matrix are flattened \n    column-by-column, i.e. the order is \n\n    \\begin{math} A_{11} A_{21} ... A_{n1} \\end{math} \\begin{math}A_{12} A_{22} ... A_{n2} ... \\end{math}\n    \\item \\xmlNode{matrixShape}, \\xmlDesc{int vector, required parameter}, \n    the shape of matrix, defined as \\xmlNode{matrixShape}Number of Rows,Number of Columns\\xmlNode{/matrixShape}\n    \\item \\xmlNode{real}, \\xmlDesc{float matrix, required parameter}, \n    the real part of state matrix \\begin{math} \\textbf{A} \\end{math}. The matrix are flattened \n    column-by-column, i.e. the order is \n\n    \\begin{math} A_{11} A_{21} ... A_{n1} \\end{math} \\begin{math}A_{12} A_{22} ... A_{n2} ... \\end{math}\n  \\end{itemize}\n  \n  \\item \\xmlNode{Btilde}, \\xmlDesc{complex matrix, required parameter}, \n  the input matrix \\begin{math} \\textbf{B}\\in\\mathbb{C}^{n \\times 1} \\end{math}:\n  \\begin{itemize}\n    \\item \\xmlNode{real}, \\xmlDesc{float matrix, required parameter}, \n    the real part of input matrix \\begin{math} \\textbf{B} \\end{math}. The matrix are flattened \n    column-by-column, i.e. the order is \n\n    \\begin{math} B_{11} B_{21} ... B_{n1} \\end{math} \\begin{math}B_{12} B_{22} ... B_{n2} ... \\end{math}\n    \\item \\xmlNode{matrixShape}, \\xmlDesc{int vector, required parameter}, \n    the shape of matrix, defined as \\xmlNode{matrixShape}Number of Rows,Number of Columns\\xmlNode{/matrixShape}\n    \\item \\xmlNode{imaginary}, \\xmlDesc{float matrix, optional parameter}, \n    the imaginary part of input matrix \\begin{math} \\textbf{B} \\end{math}. The matrix are flattened \n    column-by-column, i.e. the order is \n\n    \\begin{math} B_{11} B_{21} ... B_{n1} \\end{math} \\begin{math}B_{12} B_{22} ... B_{n2} ... \\end{math}\n  \\end{itemize}\n  \n  \\item \\xmlNode{Ctilde}, \\xmlDesc{complex matrix, required parameter}, \n  the output matrix \\begin{math} \\textbf{C}\\in\\mathbb{C}^{p \\times n} \\end{math}:\n  \\begin{itemize}\n    \\item \\xmlNode{real}, \\xmlDesc{float matrix, required parameter}, \n    the real part of output matrix \\begin{math} \\textbf{C} \\end{math}. The matrix are flattened \n    column-by-column, i.e. the order is \n\n    \\begin{math} C_{11} C_{21} ... C_{n1} \\end{math} \\begin{math}C_{12} C_{22} ... C_{n2} ... \\end{math}\n    \\item \\xmlNode{matrixShape}, \\xmlDesc{int vector, required parameter}, \n    the shape of matrix, defined as \\xmlNode{matrixShape}Number of Rows,Number of Columns\\xmlNode{/matrixShape}\n    \\item \\xmlNode{imaginary}, \\xmlDesc{float matrix, optional parameter}, \n    the imaginary part of output matrix \\begin{math} \\textbf{C} \\end{math}. The matrix are flattened \n    column-by-column, i.e. the order is \n\n    \\begin{math} C_{11} C_{21} ... C_{n1} \\end{math} \\begin{math}C_{12} C_{22} ... C_{n2} ... \\end{math}\n  \\end{itemize}\n    \n\\end{itemize}\n\nThis external matrices file example can be found in the following directory, which is automatically generated by a \nDynamic Mode Decomposition with Control (DMDC)(\\cite{proctor2016dynamic} and \\cite{wang2020DMDc}) post processor, \nand contains some information that is not necessary for FARM:\n\\begin{itemize}\n  \\item /raven/plugins/FARM/tests/RefGov\\_para\\_xmlABC\\_Test/DMDcCxCoeff\\_TES\\_para.xml\n\\end{itemize}\n\nThis external matrices file represents a thermal energy storage (TES) model, with:\n\\begin{itemize}\n  \\item One(1) system actuation variable \\begin{math} u \\end{math}\n  \\begin{itemize}\n    \\item Power set point, measured in Mega Watts (MW);\n  \\end{itemize}\n  \\item Two(2)-element system state vector \\begin{math} \\overrightarrow{x}\\in\\mathbb{R}^2 \\end{math}\n  \\item Two(2)-element system output vector \\begin{math} \\overrightarrow{y}\\in\\mathbb{R}^2 \\end{math}\n  \\begin{itemize}\n    \\item \\begin{math} y_1 \\end{math}, Hot fluid tank height, measured in Meter (m);\n    \\item \\begin{math} y_2 \\end{math}, Cold fluid tank height, measured in Meter (m);\n  \\end{itemize}\n\\end{itemize}\n\nIn addition, the state-space representations are parameterized by 20 charging(-)/discharging(+) power levels, \nand the values in \\xmlNode{ActuatorParameter} attribute are measured in Mega Watts (MW).\n\n\\subsubsection{Unparameterized External Matrices File}\n\\label{UnparaExtMatFile}\nThe following Listing \\ref{lst:UnparaExtXMLExample} is a example external matrices file for Unparameterized Reference \nGovernor with necessary information:\n\n\\begin{lstlisting}[style=XML,morekeywords={anAttribute}, \n  caption=Unparameterized External Matrices File Example., label=lst:UnparaExtXMLExample]\n<DataObjectMetadata name=\"rom_stats\">\n  <DMDrom type=\"Static\">\n    <DMDcModel>\n      <dmdTimeScale>1800 1810\n      <UNorm>\n        <realization sample=\"0\">-3.50e+00</realization>\n      </UNorm>\n      <XNorm>\n        <realization sample=\"0\">2.55e+01 0.00e+00</realization>\n      </XNorm>\n      <XLast>\n        <realization sample=\"0\">2.09e+00 9.15e+02</realization>\n      </XLast>\n      <YNorm>\n        <realization sample=\"0\">3.20e+01 2.55e+01</realization>\n      </YNorm>\n      <Atilde>\n        <realization sample=\"0\">\n          <imaginary>0.00e+00 0.00e+00 0.00e+00 0.00e+00</imaginary>\n          <matrixShape>2,2</matrixShape>\n          <real>1.00e+00 -1.33e-02 -5.56e-05 -4.57e-01</real>\n        </realization>\n      </Atilde>\n      <Btilde>\n        <realization sample=\"0\">\n          <imaginary>0.00e+00 0.00e+00</imaginary>\n          <matrixShape>2,1</matrixShape>\n          <real>-1.75e-04 -6.25e+00</real>\n        </realization>\n      </Btilde>\n      <Ctilde>\n        <realization sample=\"0\">\n          <imaginary>0.00e+00 0.00e+00 0.00e+00 0.00e+00</imaginary>\n          <matrixShape>2,2</matrixShape>\n          <real>-1.00e+00 1.00e+00 -3.76e-11 -4.86e-17</real>\n        </realization>\n      </Ctilde>\n    </DMDcModel>\n  </DMDrom>\n</DataObjectMetadata>\n\\end{lstlisting}\n\nAs one can see, all the required information for FARM are included in the \\xmlNode{DMDcModel} block. \nIndeed, the name of this block and its parent blocks is flexible:\n\\begin{itemize}\n  \\item \\xmlNode{DataObjectMetadata}, Root element of XML file, other names are acceptable.\n  \\item \\xmlNode{DMDrom}, Child 1 level element of XML file, other names are acceptable.\n  \\item \\xmlNode{DMDcModel}, Child 2 level element of XML file, other names are acceptable.\n\\end{itemize}\n\nAs long as the following keywords and inputs are the Child 3 level elements of this XML file, the information can \nbe processed for FARM execution:\n\\begin{itemize}\n  \\item \\xmlNode{dmdTimeScale}, \\xmlDesc{float vector, required parameter}, \n  the time step marks used in DMDc calculation. \n  At least two consecutive time step value are required to calculate the discrete time interval;\n\\end{itemize}\n\nSome items (\\xmlNode{UNorm}, \\xmlNode{XNorm}, \\xmlNode{YNorm}, \\xmlNode{XLast}, \\xmlNode{Atilde}, \\xmlNode{Btilde}, \n\\xmlNode{Ctilde}) contains one \\xmlNode{realization} nodes, in the format of \n\\xmlNode{realization sample=\"0\"}, and the corresponding value are contained in the \\xmlNode{realization} node. \n\nAll the following items have the \\xmlNode{realization sample=\"0\"} node:\n\\begin{itemize}\n  \\item \\xmlNode{UNorm}, \\xmlDesc{float scalar, required parameter}, \n  the norminal value of system actuation variable \\begin{math} u \\end{math};\n  \\item \\xmlNode{XNorm}, \\xmlDesc{float vector, required parameter}, \n  the norminal value of system state vector \\begin{math} \\overrightarrow{x}\\in\\mathbb{R}^n \\end{math};\n  \\item \\xmlNode{YNorm}, \\xmlDesc{float vector, required parameter}, \n  the norminal value of system output vector \\begin{math} \\overrightarrow{y}\\in\\mathbb{R}^p \\end{math};\n  \\begin{itemize}\n    \\item Note: the \\xmlNode{YNorm} values must be within the range defined by \"Min\\_Target\" and \"Max\\_Target\" in the \n    definition of Reference Governor SIMO EnternalModel. See Listing \\ref{lst:Unpara_RGSIMOExample} in Section \n    \\ref{UnParaInputFile}.\n  \\end{itemize}\n  \\item \\xmlNode{XLast}, \\xmlDesc{float vector, required parameter}, \n  the latest value of system state vector \\begin{math} \\overrightarrow{x}\\in\\mathbb{R}^n \\end{math}, \n  \\textbf{without norminal value subtraction};\n\n  \\item \\xmlNode{Atilde}, \\xmlDesc{complex matrix, required parameter}, \n  the state matrix \\begin{math} \\textbf{A}\\in\\mathbb{C}^{n \\times n} \\end{math}:\n  \\begin{itemize}\n    \\item \\xmlNode{imaginary}, \\xmlDesc{float matrix, optional parameter}, \n    the imaginary part of state matrix \\begin{math} \\textbf{A} \\end{math}. The matrix are flattened \n    column-by-column, i.e. the order is \n\n    \\begin{math} A_{11} A_{21} ... A_{n1} \\end{math} \\begin{math}A_{12} A_{22} ... A_{n2} ... \\end{math}\n    \\item \\xmlNode{matrixShape}, \\xmlDesc{int vector, required parameter}, \n    the shape of matrix, defined as \\xmlNode{matrixShape}Number of Rows,Number of Columns\\xmlNode{/matrixShape}\n    \\item \\xmlNode{real}, \\xmlDesc{float matrix, required parameter}, \n    the real part of state matrix \\begin{math} \\textbf{A} \\end{math}. The matrix are flattened \n    column-by-column, i.e. the order is \n\n    \\begin{math} A_{11} A_{21} ... A_{n1} \\end{math} \\begin{math}A_{12} A_{22} ... A_{n2} ... \\end{math}\n  \\end{itemize}\n  \n  \\item \\xmlNode{Btilde}, \\xmlDesc{complex matrix, required parameter}, \n  the input matrix \\begin{math} \\textbf{B}\\in\\mathbb{C}^{n \\times 1} \\end{math}:\n  \\begin{itemize}\n    \\item \\xmlNode{real}, \\xmlDesc{float matrix, required parameter}, \n    the real part of input matrix \\begin{math} \\textbf{B} \\end{math}. The matrix are flattened \n    column-by-column, i.e. the order is \n\n    \\begin{math} B_{11} B_{21} ... B_{n1} \\end{math} \\begin{math}B_{12} B_{22} ... B_{n2} ... \\end{math}\n    \\item \\xmlNode{matrixShape}, \\xmlDesc{int vector, required parameter}, \n    the shape of matrix, defined as \\xmlNode{matrixShape}Number of Rows,Number of Columns\\xmlNode{/matrixShape}\n    \\item \\xmlNode{imaginary}, \\xmlDesc{float matrix, optional parameter}, \n    the imaginary part of input matrix \\begin{math} \\textbf{B} \\end{math}. The matrix are flattened \n    column-by-column, i.e. the order is \n\n    \\begin{math} B_{11} B_{21} ... B_{n1} \\end{math} \\begin{math}B_{12} B_{22} ... B_{n2} ... \\end{math}\n  \\end{itemize}\n  \n  \\item \\xmlNode{Ctilde}, \\xmlDesc{complex matrix, required parameter}, \n  the output matrix \\begin{math} \\textbf{C}\\in\\mathbb{C}^{p \\times n} \\end{math}:\n  \\begin{itemize}\n    \\item \\xmlNode{real}, \\xmlDesc{float matrix, required parameter}, \n    the real part of output matrix \\begin{math} \\textbf{C} \\end{math}. The matrix are flattened \n    column-by-column, i.e. the order is \n\n    \\begin{math} C_{11} C_{21} ... C_{n1} \\end{math} \\begin{math}C_{12} C_{22} ... C_{n2} ... \\end{math}\n    \\item \\xmlNode{matrixShape}, \\xmlDesc{int vector, required parameter}, \n    the shape of matrix, defined as \\xmlNode{matrixShape}Number of Rows,Number of Columns\\xmlNode{/matrixShape}\n    \\item \\xmlNode{imaginary}, \\xmlDesc{float matrix, optional parameter}, \n    the imaginary part of output matrix \\begin{math} \\textbf{C} \\end{math}. The matrix are flattened \n    column-by-column, i.e. the order is \n\n    \\begin{math} C_{11} C_{21} ... C_{n1} \\end{math} \\begin{math}C_{12} C_{22} ... C_{n2} ... \\end{math}\n  \\end{itemize}\n    \n\\end{itemize}\n\nThis external matrices file example can be found in the following directory, which is automatically generated by a \nDynamic Mode Decomposition with Control (DMDC)(\\cite{proctor2016dynamic} and \\cite{wang2020DMDc}) post processor, \nand contains some information that is not necessary for FARM:\n\\begin{itemize}\n  \\item /raven/plugins/FARM/tests/RefGov\\_unpara\\_xmlABC\\_Test/DMDcCxCoeff\\_TES\\_unpara.xml\n\\end{itemize}\n\nThis external matrices file represents a thermal energy storage (TES) model, with:\n\\begin{itemize}\n  \\item One(1) system actuation variable \\begin{math} u \\end{math}\n  \\begin{itemize}\n    \\item Charging(-)/Discharging(+) Power setpoint, measured in Mega Watts (MW);\n  \\end{itemize}\n  \\item Two(2)-element system state vector \\begin{math} \\overrightarrow{x}\\in\\mathbb{R}^2 \\end{math}\n  \\item Two(2)-element system output vector \\begin{math} \\overrightarrow{y}\\in\\mathbb{R}^2 \\end{math}\n  \\begin{itemize}\n    \\item \\begin{math} y_1 \\end{math}, Hot fluid tank height, measured in Meter (m);\n    \\item \\begin{math} y_2 \\end{math}, Cold fluid tank height, measured in Meter (m);\n  \\end{itemize}\n\\end{itemize}\n\nThe state-space representation listed in this external matrices file is linearized at a charging power of 218.5 MW.\n\n\\subsection{Input of Reference Governor SIMO ExternalModel}\n\\label{InputFile}\nThe input of Reference Governor SIMO is an XML file. \n\n\\subsubsection{Input File for Parameterized Reference Governor SIMO ExternalModel}\n\\label{ParaInputFile}\nAn example of the input structure is given in Listing \\ref{lst:Para_RGSIMOExample}.\nThe following section will discuss the different keywords in the input and describe how they are used in this FARM plugin.\n\n\\begin{lstlisting}[style=XML,morekeywords={anAttribute},\ncaption=Reference Governor SIMO ExternalModel Example., label=lst:Para_RGSIMOExample]\n  <ExternalModel name=\"RG1\" subType=\"FARM.RefGov_parameterized_SIMO\">\n    <outputVariables>V, V_min, V_max</outputVariables>\n    <variables>PwrSet, V, V_min, V_max</variables>\n    <constant varName=\"MOASsteps\"> 360 </constant>\n    <constant varName=\"Min_Target1\"> 2.5 </constant>\n    <constant varName=\"Max_Target1\"> 55. </constant>\n    <constant varName=\"Min_Target2\"> 2.5 </constant>\n    <constant varName=\"Max_Target2\"> 55. </constant>\n    <constant varName=\"Sys_State_x\"> 30., 0 </constant>\n  </ExternalModel>\n\\end{lstlisting}\n\nAs one can see, all the specifications of the Reference Governor SIMO plugin are given in the \\xmlNode{ExternalModel} \nblock. \n\\begin{itemize}\n  \\item The \\xmlNode{subType} attribute should be set as \"FARM.RefGov\\_parameterized\\_SIMO\" to call the parameterized \n  Reference Governor SIMO external model.\n\\end{itemize}\n\nInside the \\xmlNode{ExternalModel} block, the XML nodes that belong to this plugin only (and not to the ExternalModel) \nare:\n\\begin{itemize}\n  \\item \\xmlNode{outputVariables}, \\xmlDesc{3-element string, required parameter}, the names of output variables:\n  \\begin{itemize}\n    \\item Adjusted actuation variable \\begin{math} u \\end{math}, \n    any user-defined name is allowed(e.g. V);\n    \\item Lower limit of adjusted actuation variable \\begin{math} u \\end{math}, \n    any user-defined name is allowed (e.g. V\\_min);\n    \\item Upper limit of adjusted actuation variable \\begin{math} u \\end{math}, \n    any user-defined name is allowed (e.g. V\\_max);\n  \\end{itemize}\n  The order of the 3 variables should be strictly followed.\n  \n  \\item \\xmlNode{variables}, \\xmlDesc{4-element string, required parameter}, the names of: \n  \\begin{itemize}\n    \\item Original actuation variable \\begin{math} r \\end{math}, \n    any user-defined name is allowed (e.g. PwrSet);\n    \\item The 3 output variables in \\xmlNode{outputVariables}\n  \\end{itemize}\n  The order of the 4 variables should be strictly followed.\n  \n  \\item \\xmlNode{constant varName=\"MOASsteps\"}, \\xmlDesc{integer, required parameter},  \n  the $\\textbf{g}$ value of steps to predict in the future (e.g. 360);\n  \n  \\item And 2*p blocks of \\xmlNode{constant} regarding the constraints on system output vector \n  \\begin{math} \\overrightarrow{y}\\in\\mathbb{R}^p \\end{math}\n  \\begin{itemize}\n    \\item \\xmlNode{constant varName=\"Min\\_Target1\"}, \\xmlDesc{float, required parameter}, \n    the lower constraint on output \\begin{math} y_1 \\end{math} (e.g. 2.5);\n    \\item \\xmlNode{constant varName=\"Max\\_Target1\"}, \\xmlDesc{float, required parameter}, \n    the upper constraint on output \\begin{math} y_1 \\end{math} (e.g. 50.);\n    \\item \\xmlNode{constant varName=\"Min\\_Target2\"}, \\xmlDesc{float, required parameter}, \n    the lower constraint on output \\begin{math} y_2 \\end{math} (e.g. 2.5);\n    \\item \\xmlNode{constant varName=\"Max\\_Target2\"}, \\xmlDesc{float, required parameter}, \n    the upper constraint on output \\begin{math} y_2 \\end{math} (e.g. 50.);\n    \\item ...\n    \\item \\xmlNode{constant varName=\"Min\\_Targetp\"}, \\xmlDesc{float, required parameter}, \n    the lower constraint on output \\begin{math} y_p \\end{math} (not shown in Listing \n    \\ref{lst:Para_RGSIMOExample} due to $p=2$);\n    \\item \\xmlNode{constant varName=\"Max\\_Targetp\"}, \\xmlDesc{float, required parameter}, \n    the upper constraint on output \\begin{math} y_p \\end{math} (not shown in Listing \n    \\ref{lst:Para_RGSIMOExample} due to $p=2$);\n  \\end{itemize}\n  \\item \\xmlNode{constant varName=\"Sys\\_State\\_x\"}, \\xmlDesc{float vector, optional parameter},\n  the current system state vector \\begin{math} x \\end{math} (e.g. 30., 0) before subtracting \n  the value in \\xmlNode{XNorm} in the External Matrice File (See Section \\ref{ParaExtMatFile}). \n  If not supplied, the FARM will automatically use the the value in \\xmlNode{XLast} in the \n  External Matrice File (See Section \\ref{ParaExtMatFile}).\n\\end{itemize}\nThis external model definition example can be found in the following directory:\n\\begin{itemize}\n  \\item /raven/plugins/FARM/tests/test\\_RefGov\\_para\\_xmlABC.xml\n\\end{itemize}\n\nand it is designed for a thermal energy storage (TES) simulation, with:\n\\begin{itemize}\n  \\item One(1) input variable:\n  \\begin{itemize}\n    \\item PwrSet, Charging(-)/Discharging(+) Power setpoint, measured in Mega Watts (MW);\n  \\end{itemize}\n  \\item Three(3) output variables:\n  \\begin{itemize}\n    \\item V, Adjusted Charging(-)/Discharging(+) Power setpoint, measured in Mega Watts (MW);\n    \\item V\\_min, Admissible power setpoint lower limit, measured in Mega Watts (MW);\n    \\item V\\_max, Admissible power setpoint upper limit, measured in Mega Watts (MW);\n  \\end{itemize}\n  \\item MOASsteps \\begin{math} g=360 \\end{math}, will project for the next 360 discrete time steps;\n  \\item Two(2) pairs of system output constraints:\n  \\begin{itemize}\n    \\item \\begin{math} y_1 \\end{math}, Hot fluid tank height, measured in Meter (m);\n    \\item \\begin{math} y_2 \\end{math}, Cold fluid tank height, measured in Meter (m);\n  \\end{itemize}\n\\end{itemize}\n\n\\subsubsection{Input File for Unparameterized Reference Governor SIMO ExternalModel}\n\\label{UnparaInputFile}\nAn example of the input structure is given in Listing \\ref{lst:Unpara_RGSIMOExample}.\nThe following section will discuss the different keywords in the input and describe how they are used in this FARM plugin.\n\n\\begin{lstlisting}[style=XML,morekeywords={anAttribute},\ncaption=Reference Governor SIMO ExternalModel Example., label=lst:Unpara_RGSIMOExample]\n  <ExternalModel name=\"RG1\" subType=\"FARM.RefGov_unparameterized_SIMO\">\n    <outputVariables>V, V_min, V_max</outputVariables>\n    <variables>PwrSet, V, V_min, V_max</variables>\n    <constant varName=\"MOASsteps\"> 360 </constant>\n    <constant varName=\"Min_Target1\"> 2.5 </constant>\n    <constant varName=\"Max_Target1\"> 55. </constant>\n    <constant varName=\"Min_Target2\"> 2.5 </constant>\n    <constant varName=\"Max_Target2\"> 55. </constant>\n    <constant varName=\"Sys_State_x\"> 30., 0 </constant>\n  </ExternalModel>\n\\end{lstlisting}\n\nBeing similar to Listing \\ref{lst:Para_RGSIMOExample}, all the specifications of the Reference Governor SIMO plugin \nare given in the \\xmlNode{ExternalModel} block. The only difference is \n\\begin{itemize}\n  \\item The \\xmlNode{subType} attribute should be set as \"FARM.RefGov\\_unparameterized\\_SIMO\" to call the unparameterized \n  Reference Governor SIMO external model.\n\\end{itemize}\n\nThis external model definition example can be found in the following directory:\n\\begin{itemize}\n  \\item /raven/plugins/FARM/tests/test\\_RefGov\\_unpara\\_xmlABC.xml\n\\end{itemize}\n\nand it is designed for the same thermal energy storage (TES) simulation described in Section \\ref{ParaInputFile}.\n\n\\subsection{Input File Example with FARM.RefGov\\_parameterized\\_SIMO ExternalModel}\n\nA complete input file example using the external model \"FARM.RefGov\\_parameterized\\_SIMO\" can be found in the \nfollowing directory, and it will be discussed in this section:\n\\begin{itemize}\n  \\item /raven/plugins/FARM/tests/test\\_RefGov\\_para\\_xmlABC.xml\n\\end{itemize}\nThis RAVEN input file simulates the feedback from RefGov\\_parameterized\\_SIMO ExternalModel. The key factors are:\n\\begin{itemize}\n  \\item External matrices file in Listing \\ref{lst:ParaExtXMLExample} is used;\n  \\item External model defined in Listing \\ref{lst:Para_RGSIMOExample} is used;\n  \\item Twenty(20) random input values (uniformly distributed over range [-2000, +2000] MegaWatts) will be generated, \n  and fed into the external model as \"PwrSet\";\n  \\item The external model will perform the calculation, and print the three(3) outputs(V, V\\_min, V\\_max) associated \n  with each input value of PwrSet to a file \"RefGovOutput.csv\".\n\\end{itemize}\nThe example input file is shown in Listing \\ref{lst:InputRGSIMOExample}:\n\n\\begin{lstlisting}[style=XML,morekeywords={anAttribute},\ncaption=Input File Example using RefGov.RefGov\\_SIMO ExternalModel., label=lst:InputRGSIMOExample]\n<Simulation verbosity=\"silent\">\n  <TestInfo>\n    <name>plugins/FARM.RefGov_parameterized_SIMO</name>\n    <author>HaoyuWang</author>\n    <created>2021-02-01</created>\n    <classesTested>Models.ExternalModel</classesTested>\n    <description>\n      This is a test run of parameterized reference governor. It loads ABC matrices from external xml file and calculate the feedback from RefGov_parameterized_SIMO external model.\n    </description>\n    <requirements> </requirements>\n  </TestInfo>\n  <!-- TestInfo is the description part of input xml file, won't run -->\n  \n  <RunInfo>\n    <WorkingDir>RefGov_para_xmlABC_Test</WorkingDir>\n    <Sequence>\n      RGrun,\n      printTOfile\n    </Sequence>\n  </RunInfo>\n \n  <Files>\n    <Input name=\"ABCMatrices\" type=\"\">DMDcCxCoeff_TES_para.xml</Input>\n  </Files>\n\n  <Models>\n    <ExternalModel name=\"RG1\" subType=\"FARM.RefGov_parameterized_SIMO\">\n      <!-- 3 output variables -->  \n      <outputVariables>V, V_min, V_max </outputVariables>\n      <!-- 4 variables: Issued Setpoint(PwrSet), Adjusted Setpoint(V1), bounds of V1(V1min & V1max) -->\n      <variables> PwrSet, V, V_min, V_max </variables>\n      <!-- steps in MOAS calculation, \"g\" value -->\n      <constant varName=\"MOASsteps\"> 360 </constant>\n      <!-- lower and upper bounds for y vector, will be internally checked -->\n      <constant varName=\"Min_Target1\"> 2.5 </constant> \n      <constant varName=\"Max_Target1\"> 55. </constant> \n      <constant varName=\"Min_Target2\"> 2.5 </constant> \n      <constant varName=\"Max_Target2\"> 55. </constant> \n      <!-- System state vector \"x\", optional, with elements separated by comma(,) -->\n      <constant varName=\"Sys_State_x\"> 30.,0 </constant>     \n    </ExternalModel>\n  </Models>\n \n  <Distributions>\n    <Uniform name=\"one\">\n      <lowerBound>-2000</lowerBound>\n      <upperBound>2000</upperBound>\n    </Uniform>\n  <!-- distribution for PwrSet sampling -->\n  </Distributions>\n\n  <Samplers>\n    <MonteCarlo name=\"RG_Sampler\">\n      <samplerInit>\n        <limit>20</limit>\n      </samplerInit>\n      <variable name=\"PwrSet\">\n        <distribution>one</distribution>\n      </variable>\n    </MonteCarlo>\n  <!-- A MonteCarlo sampler for PwrSet sampling  -->\n  </Samplers>\n\n  <DataObjects>\n    <PointSet name=\"RGInput\">\n      <Input>PwrSet </Input>\n      <Output>OutputPlaceHolder</Output>\n    </PointSet>\n    <PointSet name=\"RGOutput\">\n      <Input>PwrSet </Input>\n      <Output>V, V_min, V_max </Output>\n    </PointSet>\n  <!-- input and output pointsets for RG -->\n  </DataObjects>\n\n  <Steps>\n    <MultiRun name=\"RGrun\">\n      <Input  class=\"DataObjects\" type=\"PointSet\">RGInput</Input>\n      <Input  class=\"Files\" type=\"\">ABCMatrices</Input>\n      <Model  class=\"Models\"  type=\"ExternalModel\">RG1</Model>\n      <Sampler  class=\"Samplers\"  type=\"MonteCarlo\">RG_Sampler</Sampler>\n      <Output class=\"DataObjects\" type=\"PointSet\">RGOutput</Output>\n    </MultiRun>\n    <!-- MultiRun step to execute the plugin for multiple times -->\t\n    <IOStep name=\"printTOfile\">\n      <Input  class=\"DataObjects\" type=\"PointSet\">RGOutput</Input>\n      <Output class=\"OutStreams\"  type=\"Print\">RefGovOutput</Output>\n  </IOStep>\n  <!-- IOStep to dump the RGOutput to RefGovOutput.csv-->\n  </Steps>\n\n  <OutStreams>\n    <Print name=\"RefGovOutput\">\n      <type>csv</type>\n      <source>RGOutput</source>\n      <what>input,output</what>\n    </Print>\n  </OutStreams>\n</Simulation>\n\\end{lstlisting}\nThe output is a csv file, containing 10 rows of input-outputs (PwrSet - V - V\\_min - V\\_max). The data and plot are included \nin Figure \\ref{fig:RGSIMOoutput}. \n\nAs one can see, the V\\_min and V\\_max placed limits on the adjusted actuation variable V:\n\\begin{itemize}\n  \\item when original actuation variable(PwrSet) exceeds the upper limit(V\\_max), the actuation variable(V) is adjusted to \n  V\\_max;\n  \\item when original actuation variable(PwrSet) undergoes the lower limit(V\\_min), the actuation variable(V) is adjusted to \n  V\\_min;\n  \\item when original actuation variable(PwrSet) is within the range of [V\\_min, V\\_max], the actuation variable V has the \n  same value as PwrSet.\n\\end{itemize}\n\n\n\\begin{figure}[h]\n  \\centerline{\\includegraphics[width=6in]{include/RefGovOutput.png}}\n  \\caption{Data and Plot from example RefGov\\_parameterized\\_SIMO input file.}\n  \\label{fig:RGSIMOoutput}\n\\end{figure}\n\n", "meta": {"hexsha": "48f346828a5b51a78e2b49911cf7fd6caddf9791", "size": 33744, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/include/InputExample.tex", "max_stars_repo_name": "Argonne-National-Laboratory/FARM", "max_stars_repo_head_hexsha": "d478f9acd3af8e7078feae03548e4e52eead5f61", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-02-23T18:36:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-26T21:27:16.000Z", "max_issues_repo_path": "doc/include/InputExample.tex", "max_issues_repo_name": "Argonne-National-Laboratory/FARM", "max_issues_repo_head_hexsha": "d478f9acd3af8e7078feae03548e4e52eead5f61", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-02-25T15:47:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-25T22:22:46.000Z", "max_forks_repo_path": "doc/include/InputExample.tex", "max_forks_repo_name": "Argonne-National-Laboratory/FARM", "max_forks_repo_head_hexsha": "d478f9acd3af8e7078feae03548e4e52eead5f61", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-26T21:27:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-26T21:27:19.000Z", "avg_line_length": 49.550660793, "max_line_length": 180, "alphanum_fraction": 0.7107041252, "num_tokens": 10155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.3342658502355507}}
{"text": "\\documentstyle[11pt,reduce]{article}\n\n\\title{SETS: A Basic Set Theory Package}\n\n\\author{Francis J. Wright \\\\\nSchool of Mathematical Sciences \\\\\nQueen Mary and Westfield College \\\\\nUniversity of London \\\\\nMile End Road, London E1 4NS, UK. \\\\\nEmail: {\\tt F.J.Wright@QMW.ac.uk}}\n\n\\begin{document}\n\\maketitle\n\n\\begin{abstract}\n  The SETS package for \\REDUCE 3.5 and later versions provides\n  algebraic-mode support for set operations on lists regarded as sets\n  (or representing explicit sets) and on implicit sets represented by\n  identifiers.  It provides the set-valued infix operators (with\n  synonyms) {\\tt union}, {\\tt intersection} ({\\tt intersect}) and {\\tt\n  setdiff} (\\verb|\\|, {\\tt minus}) and the Boolean-valued infix\n  operators (predicates) {\\tt member}, {\\tt subset\\_eq}, {\\tt subset},\n  {\\tt set\\_eq}.  The union and intersection operators are n-ary and\n  the rest are binary.  A list can be explicitly converted to the\n  canonical set representation by applying the operator {\\tt mkset}.\n  (The package also provides an operator not specifically related to\n  set theory called {\\tt evalb} that allows the value of any\n  Boolean-valued expression to be displayed in algebraic mode.)\n\\end{abstract}\n\n\n\\section{Introduction}\n\nREDUCE has no specific representation for a set, neither in algebraic\nmode nor internally, and any object that is mathematically a set is\nrepresented in REDUCE as a list.  The difference between a set and a\nlist is that in a set the ordering of elements is not significant and\nduplicate elements are not allowed (or are ignored).  Hence a list\nprovides a perfectly natural and satisfactory representation for a set\n(but not vice versa).  Some languages, such as Maple, provide\ndifferent internal representations for sets and lists, which may allow\nsets to be processed more efficiently, but this is not {\\em\nnecessary}.\n\nThis package supports set theoretic operations on lists and represents\nthe results as normal algebraic-mode lists, so that all other REDUCE\nfacilities that apply to lists can still be applied to lists that have\nbeen constructed by explicit set operations.  The algebraic-mode set\noperations provided by this package have all been available in\nsymbolic mode for a long time, and indeed are used internally by the\nrest of REDUCE, so in that sense set theory facilities in REDUCE are\nfar from new.  What this package does is make them available in\nalgebraic mode, generalize their operation by extending the arity of\nunion and intersection, and allow their arguments to be implicit sets\nrepresented by unbound identifiers.  It performs some simplifications\non such symbolic set-valued expressions, but this is currently rather\n{\\it ad hoc\\/} and is probably incomplete.\n\nFor examples of the operation of the SETS package see (or run) the\ntest file {\\tt sets.tst}.  This package is experimental and\ndevelopments are under consideration; if you have suggestions for\nimprovements (or corrections) then please send them to me (FJW),\npreferably by email.  The package is intended to be run under\n\\REDUCE 3.5 and later versions; it may well run correctly under earlier\nversions although I cannot provide support for such use.\n\n\n\\section{Infix operator precedence}\n\nThe set operators are currently inserted into the standard REDUCE\nprecedence list (see page 28, \\S2.7, of the REDUCE 3.6 manual) as\nfollows:\n\\begin{verbatim}\nor and not member memq = set_eq neq eq >= > <= < subset_eq\nsubset freeof + - setdiff union intersection * / ^ .\n\\end{verbatim}\n\n\n\\section{Explicit set representation and {\\tt mkset}}\n\nExplicit sets are represented by lists, and this package does not\nrequire any restrictions at all on the forms of lists that are\nregarded as sets.  Nevertheless, duplicate elements in a set\ncorrespond by definition to the same element and it is conventional\nand convenient to represent them by a single element, i.e.\\ to remove\nany duplicate elements.  I will call this a normal representation.\nSince the order of elements in a set is irrelevant it is also\nconventional and may be convenient to sort them into some standard\norder, and an appropriate ordering of a normal representation gives a\ncanonical representation.  This means that two identical sets have\nidentical representations, and therefore the standard REDUCE equality\npredicate ({\\tt =}) correctly determines set equality; without a\ncanonical representation this is not the case.\n\nPre-processing of explicit set-valued arguments of the set-valued\noperators to remove duplicates is always done because of the obvious\nefficiency advantage if there were any duplicates, and hence explicit\nsets appearing in the values of such operators will never contain any\nduplicate elements.  Such sets are also currently sorted, mainly\nbecause the result looks better.  The ordering used satisfies the {\\tt\nordp} predicate used for most sorting within REDUCE, except that\nexplicit integers are sorted into increasing numerical order rather\nthan the decreasing order that satisfies {\\tt ordp}.\n\nHence explicit sets appearing in the result of any set operator are\ncurrently returned in a canonical form.  Any explicit set can also be\nput into this form by applying the operator {\\tt mkset} to the list\nrepresenting it.  For example\n\\begin{verbatim}\nmkset {1,2,y,x*y,x+y};\n\n{x + y,x*y,y,1,2}\n\\end{verbatim}\n\nThe empty set is represented by the empty list \\verb|{}|.\n\n\n\\section{Union and intersection}\n\nThe operator {\\tt intersection} (the name used internally) has the\nshorter synonym {\\tt intersect}.  These operators will probably most\ncommonly be used as binary infix operators applied to explicit sets,\ne.g.\n\\begin{verbatim}\n{1,2,3} union {2,3,4};\n\n{1,2,3,4}\n\n{1,2,3} intersect {2,3,4};\n\n{2,3}\n\\end{verbatim}\nThey can also be used as n-ary operators with any number of arguments,\nin which case it saves typing to use them as prefix operators (which\nis possible with all REDUCE infix operators), e.g.\n\\begin{verbatim}\n{1,2,3} union {2,3,4} union {3,4,5};\n\n{1,2,3,4,5}\n\nintersect({1,2,3}, {2,3,4}, {3,4,5});\n\n{3}\n\\end{verbatim}\nFor completeness, they can currently also be used as unary operators,\nin which case they just return their arguments (in canonical form),\nand so act as slightly less efficient versions of {\\tt mkset} (but\nthis may change), e.g.\n\\begin{verbatim}\nunion {1,5,3,5,1};\n\n{1,3,5}\n\\end{verbatim}\n\n\n\\section{Symbolic set expressions}\n\nIf one or more of the arguments evaluates to an unbound identifier\nthen it is regarded as representing a symbolic implicit set, and the\nunion or intersection will evaluate to an expression that still\ncontains the union or intersection operator.  These two operators are\nsymmetric, and so if they remain symbolic their arguments will be\nsorted as for any symmetric operator.  Such symbolic set expressions\nare simplified, but the simplification may not be complete in\nnon-trivial cases.  For example:\n\\begin{verbatim}\na union b union {} union b union {7,3};\n\n{3,7} union a union b\n\na intersect {};\n\n{}\n\\end{verbatim}\n\nIn implementations of REDUCE that provide fancy display using\nmathematical notation, such as PSL-REDUCE~3.6 for MS-Windows, the\nempty set, union, intersection and set difference are all displayed\nusing their conventional mathematical symbols, namely $\\emptyset$,\n$\\cup$, $\\cap$, $\\setminus$.\n\nA symbolic set expression is a valid argument for any other set\noperator, e.g.\n\\begin{verbatim}\na union (b intersect c);\n\nb intersection c union a\n\\end{verbatim}\n\nIntersection distributes over union, which is not applied by default\nbut is implemented as a rule list assigned to the variable {\\tt\nset\\_distribution\\_rule}, e.g.\n\\begin{verbatim}\na intersect (b union c);\n\n(b union c) intersection a\n\na intersect (b union c) where set_distribution_rule;\n\na intersection b union a intersection c\n\\end{verbatim}\n\n\n\\section{Set difference}\n\nThe set difference operator is represented by the symbol \\verb|\\| and\nis always output using this symbol, although it can also be input using\neither of the two names {\\tt setdiff} (the name used internally) or\n{\\tt minus} (as used in Maple).  It is a binary operator, its operands\nmay be any combination of explicit or implicit sets, and it may be\nused in an argument of any other set operator.  Here are some\nexamples:\n\\begin{verbatim}\n{1,2,3} \\ {2,4};\n\n{1,3}\n\n{1,2,3} \\ {};\n\n{1,2,3}\n\na \\ {1,2};\n\na\\{1,2}\n\na \\ a;\n\n{}\n\na \\ {};\n\na\n\n{} \\ a;\n\n{}\n\\end{verbatim}\n\n\n\\section{Predicates on sets}\n\nThese are all binary infix operators.  Currently, like all REDUCE\npredicates, they can only be used within conditional statements ({\\tt\nif}, {\\tt while}, {\\tt repeat}) or within the argument of the {\\tt\nevalb} operator provided by this package, and they cannot remain\nsymbolic -- a predicate that cannot be evaluated to a Boolean value\ncauses a normal REDUCE error.\n\nThe {\\tt evalb} operator provides a convenient shorthand for an {\\tt\nif} statement designed purely to display the value of any Boolean\nexpression (not only predicates defined in this package).  It has some\nsimilarity with the {\\tt evalb} function in Maple, except that the\nvalues returned by {\\tt evalb} in REDUCE (the identifiers {\\tt true}\nand {\\tt false}) have no significance to REDUCE itself.  Hence, in\nREDUCE, use of {\\tt evalb} is {\\em never\\/} necessary.\n\\begin{verbatim}\nif a = a then true else false;\n\ntrue\n\nevalb(a = a);\n\ntrue\n\nif a = b then true else false;\n\nfalse\n\nevalb(a = b);\n\nfalse\n\nevalb 1;\n\ntrue\n\nevalb 0;\n\nfalse\n\\end{verbatim}\nI will use the {\\tt evalb} operator in preference to an explicit {\\tt\nif} statement for purposes of illustration.\n\n\n\\subsection{Set membership}\n\nSet membership is tested by the predicate {\\tt member}.  Its left\noperand is regarded as a potential set element and its right operand\n{\\em must\\/} evaluate to an explicit set.  There is currently no sense\nin which the right operand could be an implicit set; this would\nrequire a mechanism for declaring implicit set membership (akin to\nimplicit variable dependence) which is currently not implemented.  Set\nmembership testing works like this:\n\\begin{verbatim}\nevalb(1 member {1,2,3});\n\ntrue\n\nevalb(2 member {1,2} intersect {2,3});\n\ntrue\n\nevalb(a member b);\n\n***** b invalid as list\n\\end{verbatim}\n\n\n\\subsection{Set inclusion}\n\nSet inclusion is tested by the predicate {\\tt subset\\_eq} where {\\tt a\nsubset\\_eq b} is true if the set $a$ is either a subset of or equal to\nthe set $b$; strict inclusion is tested by the predicate {\\tt subset}\nwhere {\\tt a subset b} is true if the set $a$ is {\\em strictly\\/} a\nsubset of the set $b$ and is false is $a$ is equal to $b$.  These\npredicates provide some support for symbolic set expressions, but this\nis not yet correct as indicated below.  Here are some examples:\n\\begin{verbatim}\nevalb({1,2} subset_eq {1,2,3});\n\ntrue\n\nevalb({1,2} subset_eq {1,2});\n\ntrue\n\nevalb({1,2} subset {1,2});\n\nfalse\n\n\nevalb(a subset a union b);\n\ntrue\n\nevalb(a\\b subset a);\n\ntrue\n\nevalb(a intersect b subset a union b);  %%% BUG\n\nfalse\n\\end{verbatim}\n\nAn undecidable predicate causes a normal REDUCE error, e.g.\n\\begin{verbatim}\nevalb(a subset_eq {b});\n\n***** Cannot evaluate a subset_eq {b} as Boolean-valued set\n expression\n\nevalb(a subset_eq b);  %%% BUG\n\nfalse\n\\end{verbatim}\n\n\n\\subsection{Set equality}\n\nAs explained above, equality of two sets in canonical form can be\nreliably tested by the standard REDUCE equality predicate ({\\tt =}).\nThis package also provides the predicate {\\tt set\\_eq} to test\nequality of two sets not represented canonically.  The two predicates\nbehave identically for operands that are symbolic set expressions\nbecause these are always evaluated to canonical form (although\ncurrently this is probably strictly true only in simple cases).  Here\nare some examples:\n\\begin{verbatim}\nevalb({1,2,3} = {1,2,3});\n\ntrue\n\nevalb({2,1,3} = {1,3,2});\n\nfalse\n\nevalb(mkset{2,1,3} = mkset{1,3,2});\n\ntrue\n\nevalb({2,1,3} set_eq {1,3,2});\n\ntrue\n\nevalb(a union a = a\\{});\n\ntrue\n\\end{verbatim}\n\n\n\\section{Installation}\n\nThe source file {\\tt sets.red} can be read into REDUCE when required\nusing {\\tt IN}.  If the ``professional'' version is being used this\nshould be done with {\\tt ON COMP} set, but it is much better to\ncompile the code as a {\\tt FASL} file using {\\tt FASLOUT} and then\nload it with {\\tt LOAD\\_PACKAGE} (or {\\tt LOAD}).  See the REDUCE\nmanual and implementation-specific guide for further details.\n\nThis package has to redefine the REDUCE internal procedure {\\tt\nmk!*sq} and a warning about this can be expected and ignored.  I\nbelieve (and hope!) that this redefinition is safe and will not have\nany unexpected consequences for the rest of REDUCE.\n\n\n\\section{Possible future developments}\n\n\\begin{itemize}\n\\item Unary union/intersection to implement repeated\n  union/intersection on a set of sets.\n\\item More symbolic set algebra, canonical forms for set expressions,\n  more complete simplification.\n\\item Better support for Boolean variables via a version (evalb10?)\n  of {\\tt evalb} that returns 1/0 instead of {\\tt true}/{\\tt false},\n  or predicates that return 1/0 directly.\n\\end{itemize}\n\n\\end{document}\n", "meta": {"hexsha": "5d8040479377448b777818a559facf7c8c720955", "size": 13010, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "packages/misc/sets.tex", "max_stars_repo_name": "arthurcnorman/general", "max_stars_repo_head_hexsha": "5e8fef0cc7999fa8ab75d8fdf79ad5488047282b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "packages/misc/sets.tex", "max_issues_repo_name": "arthurcnorman/general", "max_issues_repo_head_hexsha": "5e8fef0cc7999fa8ab75d8fdf79ad5488047282b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "packages/misc/sets.tex", "max_forks_repo_name": "arthurcnorman/general", "max_forks_repo_head_hexsha": "5e8fef0cc7999fa8ab75d8fdf79ad5488047282b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0501193317, "max_line_length": 71, "alphanum_fraction": 0.7575710992, "num_tokens": 3270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.3342658502355507}}
{"text": "\\documentclass[12pt]{amsart}\n\n\n% PACKAGES\n\\usepackage{url}\n\\usepackage{amsmath}\n\\usepackage{amsthm}\n\\usepackage{amssymb}\n\n% for underscores https://texfaq.org/FAQ-underscore\n\\usepackage{lmodern}\n\\usepackage[T1]{fontenc}\n\\usepackage{textcomp}\n\\usepackage{lineno}\n\n\\usepackage[\nbookmarksopen,\nbookmarksdepth=2,\n%breaklinks=true\ncolorlinks=true,\nurlcolor=blue]{hyperref}\n\n% GLOBAL FORMATTING\n%\\linenumbers\n\\parindent=0pt\n\\parskip=0.5\\baselineskip\n\\raggedbottom\n\n% TITLE AUTHOR DATE\n\\title{Controlled natural language for type theory}\n\n\\date{November 17, 2019}\n\\author{Thomas Hales}\n\n% THEOREMS \n\\newtheorem{definition}{Definition}\n\\newtheorem{theorem}[definition]{Theorem}\n\\newtheorem{lemma}[definition]{Lemma}\n\\newtheorem{specification}[definition]{Specification}\n\n% COMMANDS\n\\renewcommand{\\iff}{\\leftrightarrow}\n\\newcommand{\\Prop}{\\text{\\tt Prop}}\n\\newcommand{\\Type}{\\text{\\tt Type}}\n\\newcommand{\\fld}{\\textasciicircum}\n\\newcommand{\\dequiv}{\\mathrel{:=}} %{\\mathrel{:\\equiv}}\n\\newcommand{\\Nat}{\\ensuremath{{\\mathbb N}}}\n\\newcommand{\\Real}{\\ensuremath{{\\mathbb R}}}\n\\newcommand{\\df}[1]{\\text{\\bf #1}}\n\\newcommand{\\h}[1]{\\text{#1}}\n\\newcommand{\\join}{\\lor}\n\\newcommand{\\Mid}{\\mathrel{\\|}}\n\\newcommand{\\comment}[1]{\\%- \\nobreak{#1}}\n\\renewcommand{\\~}{\\ }\n\\newcommand{\\ignore}[1]{}\n%\\newcommand{\\remark}[1]{(#1)}\n\\renewcommand{\\_}{\\textunderscore}\n\\renewcommand\\labelitemi{-}\n\\renewcommand{\\qed}{\\ensuremath{\\square}}\n\n% ENVIRONMENTS\n\n% \\leavevmode\\par is to make remark work when it is the first item in a subsection.\n\\newenvironment{remark}\n{\\leavevmode\\par\\begin{tabular}{|p{13cm}}\\parskip=\\baselineskip{\\bf Remark.}}\n{\\end{tabular}}\n\n\\newenvironment{oblongo}{}{}\n\n\\newenvironment{prule}%\n               {\\begin{itemize}}%\n               {\\end{itemize}}\n\\newcommand{\\ptem}{\\item}\n\\newcommand{\\nt}[1]{{\\tt #1}}\n\\newcommand{\\rw}{$\\quad\\to\\quad$}\n\n\n\n% DOCUMENT\n\n\\begin{document}\n\\maketitle\n\n\\section{Introduction}\n\nThis abstract describes the current designs and development of a\ncontrolled natural language for mathematics that compiles to the Lean\nproof assistant.  We call this language Colada (short for\n\\emph{Co}ntrolled \\emph{la}nguage \\emph{da}ta).\n\nThe design of language grows out of previous controlled natural\nlanguages for mathematics (specifically, Forthel-Naproche-SAD), as\ndescribed in Peter Koepke's AITP 2019 talk.  We use\nForthel-Naproche-SAD (or simply Forthel) as a generic name for any of\nthe dialect inspired by Forthel, and our language Colada is one of\nthose dialects. This document will refer to the Colada language as\n\\emph{our dialect}.\n\nDocuments in our dialect are written in a specially prepared \\LaTeX\\ file.\nThe output of the file will eventually be a type-checked Lean file,\nalthough parts of this process are still under development.  (Checking\nmathematical proofs is not currently part of our intended project;\ntype-checked Lean we exclude proof-checking.)\n\n\\subsection{Controlled Natural Languages (CNL)}\\label{sub:CNL}\n\nBy controlled natural language for mathematics (CNL), we mean an\nartificial language for the communication of mathematics that is (1)\ndesigned in a deliberate and explicit way with precise\ncomputer-readable syntax and semantics, (2) based on a single natural\nlanguage (which for us will be  English), and (3) broadly\nunderstood at least in an intuitive way by mathematically literate\nspeakers of the natural language.\n\nCNLs can achieve a much higher degree of English fluency than other\nproof-checking languages such as the \\emph{Mizar} and DeBruijn's\n\\emph{vernacular}.  Some other proof languages are purely stylistic,\nsuch as \\emph{structured derivations}.  \n\nAt AITP 2019 Peter Koepke displayed a short proof from Rudin's {\\it\n  Principles of mathematical analysis} that he modified with Steffen\nFrerix so that it can be read and checked by their system. Their\nmodified proof is written in fluent English, is typeset by \\LaTeX, and\nyet is fully checkable. (The target of their language is first-order\nlogic.)\n\nIt is our belief that controlled natural languages are undervalued\ntechnologies in AITP.  Following a divide-and-conquer strategy, our\nbasic aim is to develop a technology that lies roughly at the midpoint\nbetween current practice of research mathematicians and the current\npractice within the proof assistant community.  \n\n\\subsection{Lean}\n\nLean theorem prover is a proof assistant built on the\nfoundations of calculus of inductive constructions.\n\nThe eventual target of our CNL is Lean.\n\nWhy is Lean the target?  We wanted something more powerful than \nfirst-order logic as used in other Forthel dialects.\nMany mathematicians are finding it a good system\nfor research-level mathematics.  There is also the M.K. argument\nthat if we succeed in bridging the gap between English and Lean,\nthen automated translation tools will eventually give us translations\nfrom Lean to other proof assistants.\n\n\n\\subsection{Research to Date}\n\nThis abstract describes the current stage of a project that is\nintended to continue over a period of years.\n\nOur specific research contributions to date are as follows.\n\n\\subsubsection{A design and specification of a controlled natural\n  language}\n\nLike other Forthel dialects, our grammar is not a context-free.\nHowever, it is similar to a context-free grammar by being described as\na collection of terminal and nonterminal symbols and production rules.\nHowever, the grammar grows as a document is parsed by the addition of\nnew production rules, which are described in the document.\n\nOur dialect can be viewed as a fusion of three different syntaxes:\nForthel-Naproche-SAD syntax, \\LaTeX\\ syntax, and Lean theorem-prover\nsyntax.  \n\nThe lexical structure of our dialect is specified in sedlex, a lexical\ngenerator tool for OCaml.\n\nOur dialect has been specified in menhir, an OCaml-based\nparser-generator tool for LR(1) grammars.  (Although our dialect is\nnot an LR(1) grammar, which prevents menhir from automatically\ngenerating a parser, the software checks that we have a well-formed\ngrammar.)\n\nOur grammar is both complex and recursive to an extraordinary degree.\nThe grammar has about 350 nonterminals and about 700 production\nrules.  The grammar has about 150 context-dependent key words.  (This\nis before any of the user-defined grammar extensions.)  However, we\nfeel that a some complexity is justified (and even required) to\ncapture widespread mathematical idioms and formulas, the syntax of type\ntheory (for us, the calculus of inductive constructions), and their\ninteractions.\n\nWe keep most features of Forthel, such its handling of synonyms, noun\nphrases, verbs, and adjectives; and its grammar extension mechanisms.\nWe add additional features such as operator precedence parsing (with\nuser-specified precendence levels and associativities); scoping;\nsyntax for \\LaTeX\\ macros; and dependent type theory including\ninductive types and mutual inductive types, structures, and lambda\nterms.\n\nA parser for our grammar has been implemented in OCaml, building on\nthe parser combinator library that John Harrison wrote to parse HOL\nLight.  However, this parser is still at an early stage. For example,\nit is still not capable of transforming a syntax tree of a parsed\ndocument into expressions that can be processed Lean. (Building this\ncapability will be a major project.)\n\nWe try to make the grammar unambiguous by always taking the longest\nmatch possible in a greedy way.  By greedy, we mean that we take\nthe longest match of a given production rule when it occurs \neven if doing so produces a match for the enclosing production rule \nof suboptimal length. Whenever this is not the desired behavior,\nthe author of the document must insert parentheses.\n\nAnd if, for example, a symbol has been assigned several meanings, it\nis always the most recently declared that wins out.\n\n\n\\subsubsection{\\TeX to raw controlled natural language syntax}\n\n\nWe have written a software program takes a specially prepared\n\\LaTeX\\ file as input and strips away the non-semantic content and\noutputs raw (such as headers, spaces and other layout, graphics,\nremarks, and dollar signs).\n\nTo create a specially prepared \\LaTeX\\ file, the author imports a\npackage \\verb!\\usepackage{cnl}!. Then any text that appears within the\n\\emph{cnl} \\LaTeX\\ environment is handled as controlled natural\nlanguage.  Arbitrary \\LaTeX\\ and graphics may appear outside the CNL\nenvironment.  The key to beautifully typeset \\TeX\\ documents is an\ndual expansion system for macros.  The \\TeX\\ engine expands macros in\nthe usual way, but the CNL engine expands some macros according to an\nindependent semantic specification.\n\n\\section{examples}\n\nOne project we have started is the translation of the number theory\nPlanet Math files to our CNL dialect.\n\nWe have been using a 30-page CNL file (for debugging) that \ngives many elementary definitions of groups, rings, fields, real numbers, etc.\nIt goes as far as statements of Sylow's theorems in group theory.\n\n\n\\section{motivation and summary}\n\nThis is part of the Formal Abstracts project.\n\nA CNL fixes a problem we encountered early on in the Formal Abstracts\nproject.   If we leave out proofs, we need more eyes, but Lean\nis not written for human eyes (or only as a secondary objective).  \nLean is optimized for writing \ncomputer-checked proofs.  \nOne can often not tell what the idea of a proof is by reading a Lean file.\nTherefore we need a language that all mathematicians can read.\n\nOur language is already finding uses at this early stage of\ndevelopment.  For example, our tool can reveal to the author of a\n\\LaTeX\\ document which terms and symbols are being used without\ndefinition.  Ultimately each symbol, word, and phrase can be traced\nits source either as a keyword of our dialect or as author-supplied.\n\nI thank the Thang Long University Formal Abstracts team for feedback,\nin their use of the software.  I thank Jesse Han, who wrote a\npreliminary version of the parser using Haskell's megaparsec parser\ncombinator library.  I thank Peter Koepke for inspiring this project\nand for many conversations.  I thank many others at the project github page.\n\nbibliography\n\nLean proof assistant.\n\nCiC.\n\nMy blog post on CNL and github.\n\nKoepke AITP and github\n\\footnote{\\href{http://aitp-conference.org/2019/aitp19-proceedings.pdf}{AITP\n    2019 proceedings}, page 84}\n\nPaskevich thesis and paper\n\nGlushkov and history.\n\n\\end{document}\n", "meta": {"hexsha": "c0a15b41866611fc88164451a0ea130a01fa8502", "size": 10342, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "documentation/tex/aitp-2020-cnl-cic-expanded.tex", "max_stars_repo_name": "HoanNguyen92/CNL-CIC", "max_stars_repo_head_hexsha": "b521d3393339e5dd3b7f5cd21ba81a758bd5c55c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2019-06-27T16:34:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-07T18:13:04.000Z", "max_issues_repo_path": "documentation/tex/aitp-2020-cnl-cic-expanded.tex", "max_issues_repo_name": "HoanNguyen92/CNL-CIC", "max_issues_repo_head_hexsha": "b521d3393339e5dd3b7f5cd21ba81a758bd5c55c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2019-10-17T06:09:51.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-25T15:51:32.000Z", "max_forks_repo_path": "documentation/tex/aitp-2020-cnl-cic-expanded.tex", "max_forks_repo_name": "HoanNguyen92/CNL-CIC", "max_forks_repo_head_hexsha": "b521d3393339e5dd3b7f5cd21ba81a758bd5c55c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2019-06-27T16:34:53.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-15T01:30:32.000Z", "avg_line_length": 36.8042704626, "max_line_length": 83, "alphanum_fraction": 0.7847611681, "num_tokens": 2543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.3342658502355507}}
{"text": "%\n% revised at Jan 21th, 2009\n% does not change too much on the content, only get\n% mild modification on the multi-system discussion. However,\n% this part is still not very satisfied. I do not think it\n% has been clearly discussed.\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% outline for this chapter:\n%\n%  1  the angular operator; expression, some concrete characters and relation with H\n%  2  the eigen value and eigen function of angular operator\n%  3  angular operator in multi-particle system\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\chapter{Angular Momentum}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Definition of angular momentum operator}\n%\n%  1  the expression of  l, l^{2} and l_{x},l_{y},l_{z},l_{+},l_{z}\n%  2  hermite character\n%  3  commute relationship\n%  4  expression under sphere coordinates\n\n\nIn classical mechanics, the angular momentum is defined as\n$\\overrightarrow{l} = \\overrightarrow{r}\\times\\overrightarrow{p}$,\nin quantum mechanics; the angular momentum operator is defined as\n$\\hei{l} = \\hei{r}\\times\\hei{p}$. So we have:\n\\begin{equation}\\label{}\n\\begin{aligned}\n         \\hat{l}_{x} &= y\\hat{p}_{z} -  z\\hat{p}_{y} \\nonumber \\\\\n         \\hat{l}_{y} &= z\\hat{p}_{x} -  x\\hat{p}_{z} \\nonumber \\\\\n         \\hat{l}_{z} &= x\\hat{p}_{y} -  y\\hat{p}_{x}\n \\end{aligned}\n\\end{equation}\n\nFirst we can prove that \\heit{l} is hermite. Actually if the\n$\\hat{l}_{x}, \\hat{l}_{y}$ and $\\hat{l}_{z}$ are hermite, the\n\\heit{l} is hermite.\n\nFor $\\hat{l}_{\\alpha} = x_{\\beta}\\hat{p}_{\\gamma} -\nx_{\\gamma}\\hat{p}_{\\beta}$; we have:\n\\begin{align}\\label{}\n\\hat{l}_{\\alpha}^{+} &= \\{x_{\\beta}\\hat{p}_{\\gamma}\\}^{+} -\n\\{x_{\\gamma}\\hat{p}_{\\beta}\\}^{+} \\nonumber \\\\\n&=\\hat{p}_{\\gamma}x_{\\beta} - \\hat{p}_{\\beta}x_{\\gamma} \\nonumber \\\\\n&=x_{\\beta}\\hat{p}_{\\gamma} - x_{\\gamma}\\hat{p}_{\\beta} \\nonumber \\\\\n&=\\hat{l}_{\\alpha}\n\\end{align}\nHere we note that $[x_{\\alpha}, p_{\\beta}] =\n-i\\hbar\\delta_{\\alpha\\beta}$. Therefore, the \\heit{l} is hermite.\n\nThen we concentrate on the commutative relationship between\n$\\hat{l}_{\\alpha}$ and $x_{\\beta}$:\n\\begin{align}\\label{}\n[\\hat{l}_{x}, x] &= 0  &  [\\hat{l}_{x}, y] &= i\\hbar z  &\n[\\hat{l}_{x}, z] &= -i\\hbar y  \\nonumber \\\\\n[\\hat{l}_{y}, x] &= -i\\hbar z  &  [\\hat{l}_{y}, y] &= 0  &\n[\\hat{l}_{y}, z] &=  i\\hbar x  \\nonumber \\\\\n[\\hat{l}_{z}, x] &= i\\hbar y  &  [\\hat{l}_{z}, y] &= -i\\hbar x  &\n[\\hat{l}_{z}, z] &= 0  \\nonumber \\\\\n\\end{align}\nIn short, we use the formula below to totally express the above\nequations:\n\\begin{equation}\\label{}\n[\\hat{l}_{\\alpha}, x_{\\beta}] =\ni\\hbar\\varepsilon_{\\alpha\\beta\\gamma} x_{\\gamma}\n\\end{equation}\n$\\varepsilon_{\\alpha\\beta\\gamma}$ is a three rank antisymmetric unit\ntensor, within it if two index number are changed from the order of\n$\\alpha, \\beta, \\gamma$ it equals to -1; if changed twice it equals\nto $+1$. Thus this is similar to the sign changing in the\ndeterminant.\n\nFor example, for the tensor we have:\n\\begin{equation}\\label{}\n\\varepsilon_{\\alpha\\beta\\gamma} = 1, \\quad\n\\varepsilon_{\\alpha\\gamma\\beta} =\\varepsilon_{\\beta\\alpha\\gamma}\n=\\varepsilon_{\\gamma\\beta\\alpha}= -1, \\quad\n\\varepsilon_{\\gamma\\alpha\\beta}= 1\n\\end{equation}\n\nFor the commutation between $\\hat{l}_{\\alpha}$ and\n$\\hat{p}_{\\beta}$; we also have similar expressions:\n\\begin{align}\\label{}\n[\\hat{l}_{\\alpha}, \\hat{p}_{\\beta}] &=\ni\\hbar\\varepsilon_{\\alpha\\beta\\gamma} \\hat{p}_{\\gamma} \\nonumber \\\\\n[\\hat{l}_{\\alpha}, \\hat{l}_{\\beta}] &=\ni\\hbar\\varepsilon_{\\alpha\\beta\\gamma} \\hat{l}_{\\gamma}\n\\end{align}\n\nFor the expression above, we can see that $\\hat{l}_{x}, \\hat{l}_{y},\n\\hat{l}_{z}$ can not commuted with each other, thus they can not\nshare the same eigen states. This is an important extinguishment\nbetween angular momentum and momentum, where the $\\hat{p}_{x},\n\\hat{p}_{y}, \\hat{p}_{z}$ could commute with each other.\n\nOn the other hand, we can see that for some specific systems (which\nincludes all the quantum system in quantum chemistry, so that's\nenough) the \\heit{l} commutes with the $\\hat{H}$. Since that we can\nwrite the $\\hat{H}$ as the sum of $\\hat{T}$ and $\\hat{V}(r)$; they\ncan be taken into account respectively.\n\\begin{align}\\label{}\n[\\hat{V}(r), \\hei{l}] &= [\\hat{V}(r), \\hei{r}\\times\\hei{p}] \\nonumber \\\\\n&=[\\hat{V}(r), \\hei{r}]\\times\\hei{p} + \\hei{r}\\times[\\hat{V}(r), \\hei{p}] \\nonumber \\\\\n&=\\hei{r}\\times[\\hat{V}(r), \\hei{p}]\n\\end{align}\nIf $\\hat{V}(r)$ is some polynomial function of $\\hat{R}$ (such as in\nmolecule Hamiltonian, the $\\hat{V}(r) = \\hat{R}^{-1}$), the\n$[\\hat{V}(r), \\hei{p}]$ is some function of $\\hat{R}$ and $\\hei{r}$\naccording to the (\\ref{OPERATORMOREeq:8}); thus this term is $0$.\n\nOn the other hand, for the kinetic operator of $\\hat{T}$:\n\\begin{align}\\label{}\n[\\hat{T}, \\hei{l}] &= [\\hat{T}, \\hei{r}\\times\\hei{p}] \\nonumber \\\\\n&=[\\hat{T}, \\hei{r}]\\times\\hei{p} + \\hei{r}\\times[\\hat{T}, \\hei{p}] \\nonumber \\\\\n&=[\\hat{T}, \\hei{r}]\\times\\hei{p}\n\\end{align}\nFrom the (\\ref{OPERATORMOREeq:9}) we have known that $[\\hei{r},\n\\hei{p}\\cdot\\hei{p}] =-2i\\hbar\\hei{p}$, thus this term is $0$.\n\nConsequently, the angular momentum is able to commute with the\n$\\hat{H}$.\n\nOn the other hand, it's easy to get this only from physical guess.\nSince the angular momentum describes the rotation states of the\nquantum particle, while if the rotation does not affect the overall\nenergy state, it can be expected that the Hamiltonian operator\ncommutes with the angular momentum operator.\n\n Similar to the kinetic operator, we can define the operator\nof the square of the modulus of the angular momentum vector, that\nis:\n\\begin{equation}\\label{}\n\\hat{l}^{2} = \\hei{l}\\cdot\\hei{l} = \\hat{l}^{2}_{x} +\n\\hat{l}^{2}_{y} + \\hat{l}^{2}_{z}\n\\end{equation}\n\nIt's easy to see that $\\hat{l}^{2}$ is a hermite operator. For the\n$\\hat{l}^{2}$, it can prove that:\n\\begin{equation}\\label{}\n[\\hat{l}^{2}, \\hat{l}_{\\alpha}] = 0 \\quad \\text{$\\alpha = x, y, z$}\n\\end{equation}\nSince for any arbitrary $\\alpha$ and $\\beta$, we have:\n\\begin{eqnarray}\n% \\nonumber to remove numbering (before each equation)\n  [\\hat{l}_{\\alpha}, \\hat{l}^{2}_{\\beta}] &=&  \\hat{l}_{\\beta}[\\hat{l}_{\\alpha}, \\hat{l}_{\\beta}] + [\\hat{l}_{\\alpha},\n  \\hat{l}_{\\beta}]\\hat{l}_{\\beta} \\nonumber \\\\\n   &=& i\\hbar\\varepsilon_{\\alpha\\beta\\gamma}\\hat{l}_{\\beta} \\hat{l}_{\\gamma}  + i\\hbar\n   \\varepsilon_{\\alpha\\beta\\gamma}\\hat{l}_{\\gamma}\\hat{l}_{\\beta} \\nonumber \\\\\n\\end{eqnarray}\nIf we have $\\alpha = x$, as the $\\beta = y, z$, it has:\n\\begin{align}\\label{}\n  [\\hat{l}_{x}, \\hat{l}^{2}_{y}] &= i\\hbar\\hat{l}_{y} \\hat{l}_{z}  + i\\hbar\n   \\hat{l}_{z}\\hat{l}_{y} \\nonumber \\\\\n  [\\hat{l}_{x}, \\hat{l}^{2}_{z}] &= -i\\hbar\\hat{l}_{z} \\hat{l}_{y}  - i\\hbar\n   \\hat{l}_{y}\\hat{l}_{z}\n\\end{align}\n\nTherefore, we can know that:\n\\begin{equation}\\label{}\n[\\hat{l}_{x}, \\hat{l}^{2}] = [\\hat{l}_{x}, \\hat{l}^{2}_{y}] +\n[\\hat{l}_{x}, \\hat{l}^{2}_{z}] + [\\hat{l}_{x}, \\hat{l}^{2}_{x}] = 0\n\\end{equation}\n\nSimilarly, we know that $[\\hat{l}^{2}, \\hat{l}_{\\alpha}] = 0$.\n\non the other hand, it can see that if $[\\hei{l}, \\hat{H}] = 0$, the\n$[\\hat{l}^{2}, \\hat{H}] = 0$.\n\\begin{align}\\label{}\n[\\hat{H}, \\hat{l}^{2}] &= [\\hat{H}, \\hei{l}^{2}] \\nonumber \\\\\n&=[\\hat{H}, \\hei{l}]\\cdot\\hei{l} + \\hei{l}\\cdot[\\hat{H}, \\hei{l}]\n\\end{align}\n\nThus, within the quantum chemistry; we can arrive two important\nconclusions:\n\\begin{align}\\label{}\n[\\hat{H}, \\hei{l}] &= 0 \\nonumber \\\\\n[\\hat{H}, \\hat{l}^{2}] &= 0\n\\end{align}\n\nNext, let's introduce another two operators based on the $\\hei{l}$:\n\\begin{align}\\label{}\n\\hat{l}_{+} &= \\hat{l}_{x} + i\\hat{l}_{y}  \\nonumber \\\\\n\\hat{l}_{-} &= \\hat{l}_{x} - i\\hat{l}_{y}\n\\end{align}\nFor both of the new operators, it's easy to prove the commutative\nrelationship for them:\n\\begin{equation}\\label{}\n[\\hat{l}_{+}, \\hat{l}_{-}] = 2\\hbar\\hat{l}_{z}, \\quad [\\hat{l}_{z},\n\\hat{l}_{+}] = \\hbar\\hat{l}_{+}, \\quad [\\hat{l}_{z}, \\hat{l}_{-}] =\n-\\hbar\\hat{l}_{-}\n\\end{equation}\n\nFurthermore, we can show that:\n\\begin{equation}\\label{ANGULAReq:3}\n\\hat{l}^{2} = \\hat{l}_{+}\\hat{l}_{-} + \\hat{l}^{2}_{z} - \\hat{l}_{z}\n=\\hat{l}_{-}\\hat{l}_{+} + \\hat{l}^{2}_{z} + \\hat{l}_{z}\n\\end{equation}\n\nIn the following content, we can see that why we introduce both of\nthe two new operators.\n\nLastly, since that we always use the spheral coordinates to\nrepresent the angular momentum operator, its form is listed below:\n\\begin{align}\\label{ANGULAReq:1}\n\\hat{l}_{x} &=i\\hbar\\left\\{\\sin\\varphi \\frac{\\partial}{\\partial\n\\theta} + \\cot\\theta\\cos\\varphi \\frac{\\partial}{\\partial\\varphi} \\right\\}       \\nonumber \\\\\n\\hat{l}_{y} &=i\\hbar\\left\\{-\\cos\\varphi \\frac{\\partial}{\\partial\n\\theta} + \\cot\\theta\\sin\\varphi \\frac{\\partial}{\\partial\\varphi}\n\\right\\} \\nonumber \\\\\n\\hat{l}_{z} &= -i\\hbar\n\\frac{\\partial}{\\partial\\varphi}\n\\end{align}\n\n\\begin{equation}\\label{ANGULAReq:2}\n\\hat{l}^{2}\n=-\\hbar^{2}\\left\\{\\frac{1}{\\sin\\theta}\\frac{\\partial}{\\partial\\theta}\n\\left(\\sin\\theta\\frac{\\partial}{\\partial\\theta}\\right)\n+\\frac{1}{\\sin^{2}\\theta}\\frac{\\partial^{2}}{\\partial\\varphi^{2}}\n\\right\\}\n\\end{equation}\n\nTo get the result has to change from the Cartesian coordinate to the\nspheral coordinates. Thus we have to use some basic differential\nrelationships. For the $\\frac{\\partial}{\\partial x}$, we have:\n\\begin{equation}\\label{}\n\\frac{\\partial}{\\partial x} = \\frac{\\partial}{\\partial\nr}\\frac{\\partial r}{\\partial x} +\n\\frac{\\partial}{\\partial\\theta}\\frac{\\partial\\theta}{\\partial x} +\n\\frac{\\partial}{\\partial\\varphi}\\frac{\\partial\\varphi}{\\partial x}\n\\end{equation}\nThe $\\frac{\\partial}{\\partial y}$ and $\\frac{\\partial}{\\partial z}$\nare similar to the expression above. By inserting the above\ntransformation into the $\\hat{l}_{\\alpha}$, we can immediately get\nthe (\\ref{ANGULAReq:1}).\n\nHowever, if we adopt the same procedure to deduce the\n$\\frac{\\partial^{2}}{\\partial x^{2}}$, it will be very complicated.\nHowever, we can use the $\\hat{l}_{+}$ and $\\hat{l}_{+}$ to avoid\nsuch trouble.\n\nDirectly from the (\\ref{ANGULAReq:1}), we can get the expression for\nthe $\\hat{l}_{+}$ and $\\hat{l}_{+}$:\n\\begin{equation}\\label{}\n\\hat{l}_{\\pm} = e^{\\pm i\\varphi}\\left\\{\\pm \\frac{\\partial}{\\partial\n\\theta} + i\\cot\\theta \\frac{\\partial}{\\partial\\varphi} \\right\\}\n\\end{equation}\nThus from the (\\ref{ANGULAReq:3}) we can easily get the expression\nfor the $\\hat{l}^{2}$ as shown in (\\ref{ANGULAReq:2}).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Eigen value of angular momentum operator}\n%\n% eigen value for l^{2} and l_{z}\n% since the CSCCO has pickup the l^{2} and l_{z}, thus it's\n%  impossible to discuss the the eigen value for l_{x} and l_{y}.\n%  but we can talk about their matrix elements\n%\nHere in this section we begin to concentrate on the eigen value of\nthe angular momentum operator. There has some classical methods\ntackle down this problem, so we will follow these methods.\n\nFirst, let's concentrate on the eigen value of $\\hat{l}_{z}$. Since\nthat $\\hat{l}_{z}$ has a simple expression which is shown in\n(\\ref{ANGULAReq:1}), also the $\\hat{l}_{z}$ can commute with\n$\\hat{H}$; it's picked up into the CSCCO for $\\hat{H}$. Thus its\neigen function is:\n\\begin{align}\\label{}\n-i\\hbar\\frac{\\partial \\Psi}{\\partial\\varphi} &= l_{z}\\Psi\n\\Rightarrow\n\\nonumber \\\\\n\\frac{\\partial \\ln\\Psi}{\\partial\\varphi} &= \\frac{il_{z}}{\\hbar}\n\\Rightarrow\n\\nonumber \\\\\n\\Psi &= C exp(il_{z}\\varphi/\\hbar)\n\\end{align}\n\nNow we have to determine the $l_{z}$ and $C$. $C$ can be fixed by\nnormalization condition; yet for the $l_{z}$, to ensure that\n$\\hat{l}_{z}$ is a hermite operator (see the book by JinYan\nZeng(Volume I)\\cite{ZengJinYan} to get more details), the eigen\nstate of $\\Psi$ has to satisfy: $\\Psi(\\varphi + 2\\pi) =\n\\Psi(\\varphi)$. Therefore the $l_{z}$ has to be:\n\\begin{equation}\\label{}\n\\frac{l_{z}}{\\hbar} = m \\quad (m=0, \\pm 1, \\pm 2, \\cdots)\n\\end{equation}\nThus the eigen state for the $\\hat{l}_{z}$ is:\n\\begin{align}\\label{ANGULAReq:6}\n\\Psi &= C exp(im\\varphi) \\nonumber \\\\\n&= \\frac{1}{\\sqrt{2 \\pi}} exp(im\\varphi)\n\\end{align}\n\nHere there's something so interesting that need to elucidate.\nAlthough judging from the normal experience that there should has no\ndifference between $\\hat{l}_{x}$, $\\hat{l}_{y}$ and $\\hat{l}_{z}$;\ntherefore the $\\hat{l}_{y}$ and $\\hat{l}_{x}$ should be able to get\ntheir corresponding eigen states. However, there's an important\npoint we have previously made; that the $\\hat{l}_{x}$, $\\hat{l}_{y}$\nand $\\hat{l}_{z}$ can not commute with each other. Thus, if the\n$\\hat{l}_{z}$ is picked out into the complete set of dynamic\noperators for $\\hat{H}$, we can not use this Hilbert space to\ncompose the eigen states for $\\hat{l}_{y}$ and $\\hat{l}_{z}$.\n\nSecondly, we are going to turn to the $\\hat{l}^{2}$. Since that\n$\\hat{l}^{2}$ also commutes with $\\hat{H}$, so it's selected into\nthe complete set of dynamic operators for $\\hat{H}$, just like\n$\\hat{l}_{z}$.\n\nHowever, because the expression of the $\\hat{l}^{2}$ (see the\n\\ref{ANGULAReq:2}) is very complicated, it's hard to get the eigen\nvalues directly from solving the eigen function like the procedure\ndone to the $\\hat{l}_{z}$. Nevertheless, from the expression of\n(\\ref{ANGULAReq:3}), we can see that $\\hat{l}^{2}$ can de directly\nrelated to the $\\hat{l}_{z}$ and $\\hat{l}_{z}^{2}$, while their\neigen values are easily gained. Therefore, can we find out a way to\nachieve the eigen value but avoid to solve the eigen function of\n$\\hat{l}^{2}$?\n\nHere, to get through the answer we must use the operator of\n$\\hat{l}_{+}$ and $\\hat{l}_{-}$, and that's the reason why we\nintroduce both of the two operators.\n\nNow let's go to see more details for $\\hat{l}_{+}$ and\n$\\hat{l}_{-}$. First we suggest some wave functions of $\\psi_{m}$\nwhose eigen values for $\\hat{l}_{z}$ are labeled as $m$:\n\\begin{align}\\label{}\n\\hat{l}_{z}\\hat{l}_{+} &= \\hat{l}_{+}\\hat{l}_{z} + \\hbar\\hat{l}_{+}\n\\Rightarrow \\nonumber \\\\\n\\hat{l}_{z}\\hat{l}_{+}\\psi_{m} &= (\\hat{l}_{+}\\hat{l}_{z} +\n\\hbar\\hat{l}_{+})\\psi_{m} \\Rightarrow \\nonumber \\\\\n&=m\\hbar\\hat{l}_{+}\\psi_{m} + \\hbar\\hat{l}_{+}\\psi_{m} \\nonumber \\\\\n&=(m+1)\\hbar\\hat{l}_{+}\\psi_{m}\n\\end{align}\nThus we can see that $\\hat{l}_{+}\\psi_{m}$ is also some eigen\nfunction for the $\\hat{l}_{z}$, while whose eigen value is\n$(m+1)\\hbar$. That means, after the operation on the $\\hat{l}_{+}$,\nthe $\\hat{l}_{+}\\psi_{m}$ increase its $m$ value by $1$.\n\nthe $\\hat{l}_{-}$ has likewise the same procedure to reach the\nresult:\n\\begin{equation}\\label{}\n\\hat{l}_{z}\\hat{l}_{-}\\psi_{m} = (m-1)\\hbar\\hat{l}_{-}\\psi_{m}\n\\end{equation}\nThus the $\\hat{l}_{+}\\psi_{m}$ decrease its $m$ value by $1$.\n\nFor this reason, the $\\hat{l}_{+}$ is called ``up operator'', and\nthe $\\hat{l}_{-}$ is called ``down operator''.\n\nNow let's go to see the eigen values for the $\\hat{l}^{2}$. Since\nthat $\\hat{l}_{z}$ possesses no speciality among $\\hat{l}_{x}$,\n$\\hat{l}_{y}$ and $\\hat{l}_{z}$; thus for a common system, different\n$l_{z}$ value for $\\hat{l}_{z}$ may correspond to the same eigen\nvalue for $\\hat{l}^{2}$. This is similar to the case of the three\ndimensional wave function in the cubic box (see the previous\nchapter), where whose wave function is:\n\\begin{align}\\label{}\n\\Psi (x,y,z) &=\n\\frac{\\sqrt{8}}{l^{3}}\\sin\\left(\\frac{n_{1}\\pi}{l}x\\right)\n\\sin\\left(\\frac{n_{2}\\pi}{l}y\\right)\n\\sin\\left(\\frac{n_{3}\\pi}{l}z\\right) \\nonumber \\\\\nE (n_{1},n_{2},n_{3}) &=\n\\frac{\\pi^{2}\\hbar^{2}}{2ml^{2}}(n_{1}^{2}+n_{2}^{2}+n_{3}^{2})\n\\end{align}\nIn this case there's also no speciality between x, y and z, so for\nthe $n^{2} = n_{1}^{2}+n_{2}^{2}+n_{3}^{2}$; different $n_{i}$ may\ncorrespond to the same $n^{2}$.\n\nNow let's consider a system, whose wave function are the eigen\nfunctions both for the $\\hat{l}_{z}$ and $\\hat{l}^{2}$.  Now we can\nsee that if the eigen value for the $\\hat{l}^{2}$ is fixed up, there\nmust have maximum number of $\\overline{m}$: $l_{z} =\n\\overline{m}\\hbar$. Because that $\\hat{l}^{2}-\\hat{l}^{2}_{z} =\n\\hat{l}^{2}_{y} + \\hat{l}^{2}_{x}$, the eigen values for the\n$\\hat{l}^{2}$ should always larger than (or at least equal to)\n$\\overline{m}^{2}$. Similarly there must have a minimum number of\n$\\underline{m}$, $l_{z} = \\underline{m}\\hbar$. Here, we do not know\nwhether they equal to each other, but actually their absolute value\nshould equal to each other; since that both of the two directions\nfor the $\\hat{l}_{z}$ are identical.\n\nSuggest that as the eigen value of $\\hat{l}^{2}$ is fixed up to\n$l^{2}$, and the eigen state of $\\psi$ gives $\\overline{m}$\n($\\hat{l}_{z}\\psi = \\overline{m}\\hbar\\psi$); here we have:\n\\begin{align}\\label{}\n\\hat{l}_{+}\\psi &= 0 \\rightarrow \\nonumber \\\\\n\\hat{l}_{-}\\hat{l}_{+}\\psi\n&=(\\hat{l}^{2}-\\hat{l}_{z}^{2}-\\hat{l}_{z})\\psi= 0 \\rightarrow \\nonumber \\\\\nl^{2} &= \\overline{m}(\\overline{m}+1)\n\\end{align}\n\nSimilarly for the $\\psi^{'}$ which gives $\\underline{m}$\n($\\hat{l}_{z}\\psi^{'} = \\underline{m}\\hbar\\psi^{'}$); we have:\n\\begin{align}\\label{}\n\\hat{l}_{-}\\psi^{'} &= 0 \\rightarrow \\nonumber \\\\\n\\hat{l}_{+}\\hat{l}_{-}\\psi^{'}\n&=(\\hat{l}^{2}-\\hat{l}_{z}^{2}+\\hat{l}_{z})\\psi^{'}= 0 \\rightarrow \\nonumber \\\\\nl^{2} &= \\underline{m}(\\underline{m}-1)\n\\end{align}\n\nThus we have $\\overline{m}(\\overline{m}+1) =\n\\underline{m}(\\underline{m}-1)$. This yields that $\\overline{m} =-\n\\underline{m}$, another solution is abandoned.\n\nAnyway, for a specific eigen value of $l$, $l^{2} =\n\\overline{m}(\\overline{m}+1)$; the eigen function corresponding to\nthe $\\hat{l}_{z}$ are $2\\overline{m}+1$ folds of degenerate; their\n$m$ can adopt $m=-\\overline{m}, -\\overline{m}+1, \\cdots, 0, 1,\n\\cdots, \\overline{m}$.\n\nNext let's consider the matrix elements for the $\\hat{l}_{x}$ and\n$\\hat{l}_{y}$ for the same system, where we choose the\n$(\\hat{H},\\hat{l}_{z})$ as the CSCCO. Therefore, the wave functions\n$\\psi_{1}, \\psi_{2}, \\cdots, \\psi_{n}$ are the eigen vectors for\nthem $(\\hat{H},\\hat{l}_{z})$.\n\nFirst for the different $\\psi$ and $\\psi^{'}$, which hold different\nenergy level, since $\\hat{l}_{x}$ commuted with the Hamiltonian\noperator, it's easy to see that $\\bra{\\psi^{'}}\\hat{l}_{x}\\ket{\\psi}\n= 0$ ($\\hat{l}_{y}$ is same).\n\\begin{align}\\label{}\n\\bra{\\psi^{'}}\\hat{H}\\hat{l}_{x}\\ket{\\psi} &=\n\\bra{\\psi^{'}}\\hat{l}_{x}\\hat{H}\\ket{\\psi} \\nonumber \\\\\n&=E\\bra{\\psi^{'}}\\hat{l}_{x}\\ket{\\psi}\n\\end{align}\nWhile on the other hand, we have:\n\\begin{align}\\label{}\n\\bra{\\psi^{'}}\\hat{H}\\hat{l}_{x}\\ket{\\psi} &=\n\\bra{\\psi}\\hat{H}\\hat{l}_{x}\\ket{\\psi^{'}} \\nonumber \\\\\n&=\\bra{\\psi}\\hat{l}_{x}\\hat{H}\\ket{\\psi^{'}} \\nonumber \\\\\n&=E^{'}\\bra{\\psi}\\hat{l}_{x}\\ket{\\psi^{'}} \\nonumber \\\\\n&=E^{'}\\bra{\\psi^{'}}\\hat{l}_{x}\\ket{\\psi}\n\\end{align}\nThus we can have that :\n\\begin{equation}\\label{}\n(E-E^{'})\\bra{\\psi^{'}}\\hat{l}_{x}\\ket{\\psi} = 0 \\Rightarrow\n\\bra{\\psi^{'}}\\hat{l}_{x}\\ket{\\psi} = 0\n\\end{equation}\n\nHence, we will consider the wave functions which occupy the same\nenergy level and have different z directional angular momentum\n($l_{z}(m)$ is different).\n\nNow we will achieve this through $\\hat{l}_{+}$ and $\\hat{l}_{-}$.\nSince $\\hat{l}_{+}\\ket{\\psi_{m}} = c\\ket{\\psi_{m+1}}$, and\n$\\hat{l}_{-}\\ket{\\psi_{m}} = c\\ket{\\psi_{m-1}}$; only these\n$\\bra{\\psi_{m}}\\hat{l}_{+}\\ket{\\psi_{m-1}}$ and\n$\\bra{\\psi_{m}}\\hat{l}_{-}\\ket{\\psi_{m+1}}$ do not equal to $0$.\n\nSo far we have:\n\\begin{equation}\\label{}\n\\hat{l}^{2} = \\hat{l}_{+}\\hat{l}_{-} + \\hat{l}^{2}_{z} - \\hat{l}_{z}\n\\end{equation}\nwe can multiply the operator with $\\ket{\\psi_{m}}$, whose eigen\nvalue for $\\hat{l}^{2}$ is $l(l+1)$, and $l_{z}$ is $m$; we\nintegrate it:\n\\begin{align}\\label{}\n\\bra{\\psi_{m}}\\hat{l}^{2}\\ket{\\psi_{m}} &= \\sum_{i}^{n}\n\\bra{\\psi_{m}}\\hat{l}_{+}\\ket{\\psi_{i}}\n\\bra{\\psi_{i}}\\hat{l}_{-}\\ket{\\psi_{m}} +\n\\bra{\\psi_{m}}\\hat{l}^{2}_{z}\\ket{\\psi_{m}} -\n\\bra{\\psi_{m}}\\hat{l}_{z}\\ket{\\psi_{m}} \\nonumber \\\\\nl(l+1) &= \\bra{\\psi_{m}}\\hat{l}_{+}\\ket{\\psi_{m-1}}\n\\bra{\\psi_{m-1}}\\hat{l}_{-}\\ket{\\psi_{m}} + m^{2} -m\n\\end{align}\nSince we have $\\hat{l}_{+} = \\hat{l}_{-}^{+}$, we have:\n\\begin{equation}\\label{}\n\\bra{\\psi_{m}}\\hat{l}_{+}\\ket{\\psi_{m-1}} =\n\\bra{\\psi_{m-1}}\\hat{l}_{-}\\ket{\\psi_{m}}^{*}\n\\end{equation}\nHence we have:\n\\begin{equation}\\label{}\n|\\bra{\\psi_{m}}\\hat{l}_{+}\\ket{\\psi_{m-1}}|^{2} = l(l+1)-m^{2}+m\n\\end{equation}\n$\\bra{\\psi_{m}}\\hat{l}_{+}\\ket{\\psi_{m-1}}= \\sqrt{(l+m)(l-m+1)}$.\n\nSince that $\\hat{l}_{+} = \\hat{l}_{x} + i\\hat{l}_{y}$, and\n$\\hat{l}_{-} = \\hat{l}_{x} - i\\hat{l}_{y}$; now we can get:\n\\begin{align}\\label{}\n\\bra{\\psi_{m}}\\hat{l}_{x}\\ket{\\psi_{m-1}} &=\n\\frac{1}{2}\\sqrt{(l+m)(l-m+1)} \\nonumber \\\\\n\\bra{\\psi_{m}}\\hat{l}_{y}\\ket{\\psi_{m-1}} &=\n-\\frac{1}{2}i\\sqrt{(l+m)(l-m+1)}\n\\end{align}\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Eigen functions for the $\\hat{l}_{z}$ and $\\hat{l}^{2}$}\n%\n% Eigen functions for the $\\hat{l}_{z}$ and $\\hat{l}^{2}$\n%\n%\n%\n\nIn the last section, the eigen functions for the $\\hat{l}_{z}$ has\nbeen easily got:\n\\begin{align}\\label{}\n-i\\hbar\\frac{\\partial \\Psi}{\\partial\\varphi} &= l_{z}\\Psi\n\\Rightarrow \\nonumber\n\\\\\n\\Psi &= C exp(il_{z}\\varphi/\\hbar)\n\\end{align}\nNow we begin to derive the eigen function for the $\\hat{l}^{2}$.\n\nFor the $\\hat{l}^{2}$(whose expression under sphere coordinate can\nsee \\ref{ANGULAReq:2}), we can safely presume that it's eigen\nfunction is $Y(\\theta, \\varphi)$($\\hat{l}^{2}$ is only function of\n$\\theta$ and  $\\varphi$); furthermore, the $Y(\\theta, \\varphi)$ can\nbe split into:\n\\begin{equation}\\label{ANGULAReq:5}\nY(\\theta, \\varphi) = \\Theta (\\theta)\\Phi_{m}(\\varphi)\n\\end{equation}\nWe can have this because judging from (\\ref{ANGULAReq:2}) the\nvariables of $\\theta$ and  $\\varphi$ can be separated from each\nother. Here the $\\Phi_{m}(\\varphi)$ adopts the form in\n(\\ref{ANGULAReq:6}).\n\nMoreover, suggest we have such the eigen functions for the\n$\\hat{l}^{2}$:\n\\begin{equation}\\label{ANGULAReq:4}\n\\hat{l}^{2}Y(\\theta, \\varphi) = \\lambda \\hbar^{2}Y(\\theta, \\varphi)\n\\end{equation}\nNow by bring the sphere coordinate expression of the $\\hat{l}^{2}$\nand (\\ref{ANGULAReq:5}) into (\\ref{ANGULAReq:4}), we can have:\n\\begin{align}\\label{}\n-\\Phi_{m}\\times\\frac{\\hbar^{2}}{\\sin\\theta}\\frac{d}{d\n\\theta}\\left(\\sin\\theta\\frac{d\\Theta}{d \\theta}\\right) +\n\\frac{\\Theta}{\\sin^{2}\\theta}(\\hat{l}^{2}_{z}\\Phi_{m}) &=\n\\lambda \\hbar^{2}\\Theta \\Phi_{m} \\nonumber \\\\\n-\\Phi_{m}\\times\\frac{\\hbar^{2}}{\\sin\\theta}\\frac{d}{d\n\\theta}\\left(\\sin\\theta\\frac{d\\Theta}{d \\theta}\\right) +\n\\frac{\\Theta}{\\sin^{2}\\theta}m^{2}\\hbar^{2}\\Phi_{m} &=\n\\lambda \\hbar^{2}\\Theta \\Phi_{m} \\nonumber \\\\\n\\frac{1}{\\sin\\theta}\\frac{d}{d\n\\theta}\\left(\\sin\\theta\\frac{d\\Theta}{d \\theta}\\right) +\n\\left(\\lambda - \\frac{m^{2}}{\\sin^{2}\\theta}\\right)\\Theta &= 0\n\\end{align}\n\nHowever, this function is not easy to gain its solution. So we make\n$\\xi = \\cos \\theta$ (here we have $0\\leq\\theta\\leq\\pi$). Thus:\n\\begin{align}\\label{}\n\\frac{d\\Theta}{d \\xi} = -\\frac{1}{\\sin \\theta}\\frac{d\\Theta}{d\n\\theta}\n\\end{align}\nThen we have:\n\\begin{align}\\label{}\n\\frac{1}{\\sin\\theta}\\frac{d}{d\n\\theta}\\left(-\\sin^{2}\\theta\\frac{d\\Theta}{d \\xi}\\right) +\n\\left(\\lambda - \\frac{m^{2}}{(1-\\xi^{2})}\\right)\\Theta &= 0\n\\nonumber \\\\\n\\frac{d}{d \\xi}\\left((1-\\xi^{2})\\frac{d\\Theta}{d \\xi}\\right) +\n\\left(\\lambda -\n\\frac{m^{2}}{(1-\\xi^{2})}\\right)\\Theta &= 0 \\nonumber \\\\\n(1-\\xi^{2})\\frac{d^{2}\\Theta}{d \\xi^{2}} - 2\\xi\\frac{d\\Theta}{d \\xi}\n+ \\left(\\lambda - \\frac{m^{2}}{(1-\\xi^{2})}\\right)\\Theta &= 0\n\\end{align}\n\nThis is the associated Legendre function. Under the condition of\n$0\\leq\\theta\\leq\\pi$, the function has only one meaningful physical\nsolution, and this solution requires that $\\lambda = l(l+1)$ and\n$|m| \\leq l$; here the $\\lambda$ is the eigen value for the\n$\\hat{l}^{2}$, which is in agreement with the answer we found out in\nthe last section.\n\nIn this case, the solution is a polynomial:\n\\begin{equation}\\label{}\nP^{m}_{l}(\\cos\\theta) \\quad |m| \\leq l\n\\end{equation}\nBy normalized condition, we can finally get the expression for the\n$\\Theta$:\n\\begin{equation}\\label{}\n\\Theta(\\theta) =\n(-1)^{m}\\sqrt{\\frac{2l+1}{2}\\frac{(l-m)!}{(l+m)!}}P^{m}_{l}(\\cos\\theta)\n\\end{equation}\n\nTherefore, the eigen function for the $\\hat{l}^{2}$ is:\n\\begin{equation}\\label{}\nY^{m}_{l}(\\theta, \\varphi) =\n(-1)^{m}\\sqrt{\\frac{2l+1}{4\\pi}\\frac{(l-m)!}{(l+m)!}}P^{m}_{l}(\\cos\\theta)e^{im\\pi}\n\\end{equation}\n\nHere we note that different $Y^{m}_{l}$ are orthogonal with each\nother:\n\\begin{equation}\\label{}\n\\int_{0}^{2\\pi}\\int_{0}^{\\pi}Y^{m^{'}}_{l^{'}}Y^{m}_{l}\\sin\\theta\nd\\theta d\\varphi = \\delta_{l^{'}l}\\delta_{m^{'}m}\n\\end{equation}\nThis is important in understanding the orthogonal characters of\nconcrete wave functions.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{ Coupling between two angular momentums}\n%\n% 1  to choose the L^{2} and L_z into the CSCCO\n%    because they can commute with the \\hat{H}\n%\n%\nNow let's consider a system, which is composed by two subsystems. If\nthere's no interactions between the two subsystems, the total\nangular momentum $\\hat{L}$ for the whole system will simply be the\naddition between the two subsystems; each subsystem is a fully\nconserved system:\n\\begin{equation}\\label{ANGULAReq:7}\n\\hat{\\mathbf{L}} = \\hat{\\mathbf{L}}_{1} + \\hat{\\mathbf{L}}_{2}\n\\end{equation}\n\nOn the other hand, if there exists some interactions between the two\nsubsystems, the (\\ref{ANGULAReq:7}) can not be applied anymore;\nthat's because the angular momentum for each subsystem is not\nconserved anymore.\n\nHowever, the weight of $\\hat{\\mathbf{L}}$ on each specific\ndirection, namely the $\\hat{\\mathbf{L}}_{x}$, $\\hat{\\mathbf{L}}_{y}$\nand $\\hat{\\mathbf{L}}_{z}$ can be still made certain:\n\\begin{align}\\label{}\n\\hat{\\mathbf{L}}_{x} &= \\hat{\\mathbf{L}}_{1x} +\n\\hat{\\mathbf{L}}_{2x} \\nonumber \\\\\n\\hat{\\mathbf{L}}_{y} &= \\hat{\\mathbf{L}}_{1y} +\n\\hat{\\mathbf{L}}_{2y} \\nonumber \\\\\n\\hat{\\mathbf{L}}_{z} &= \\hat{\\mathbf{L}}_{1z} +\n\\hat{\\mathbf{L}}_{2z}\n\\end{align}\nThis relation is obvious because the angular momentum operator is\nthe vector operator, so it obeys the rules for the vectors. For this\nreason, we can select the $\\hat{\\mathbf{L}}_{z}$ into the CSCCO.\n\nOn the other hand, even though the total angular momentum is not the\nconserved physical quantity anymore, the $\\hat{L}^{2}$ can still\ncommute with the Hamiltonian, thus we can select the $\\hat{L}^{2}$\ninto the CSCCO, too:\n\\begin{equation}\\label{}\n\\hat{L}^{2} = \\hat{\\mathbf{L}}_{x}^{2} + \\hat{\\mathbf{L}}_{y}^{2} +\n\\hat{\\mathbf{L}}_{z}^{2}\n\\end{equation}\n\nFor the $\\hat{\\mathbf{L}}_{z}$, it's eigen value and eigen states\nare straightforward. Here we remember that different subsystem has\nits own $l_{z}$, and they do not affect the others:\n\\begin{equation}\\label{}\n[\\hat{\\mathbf{L}}_{1z}, \\hat{\\mathbf{L}}_{2z}] = 0 \\Rightarrow L_{z}\n= L_{z1} + L_{z2}\n\\end{equation}\nNevertheless, for the $\\hat{L}^{2}$ there does not have such clear\nrelations. Therefore, we should solve this question in another way.\n\nIf we select the $\\hat{L}_{1}^{2}$, $\\hat{L}_{2}^{2}$,\n$\\hat{\\mathbf{L}}_{1z}$ and $\\hat{\\mathbf{L}}_{2z}$ into the CSCCO,\n(this can be done for that all of the four operators are commuting\nwith the Hamiltonian, and also they are commuting with each other),\nany quantum state related to the angular momentum will be determined\nby $L^{2}_{1},L^{2}_{2},L_{1z},L_{2z}$. Therefore for the fixed\nvalue of $L_{1}, L_{2}$, they will be $(2L_{1}+1)(2L_{2}+1)$\ndifferent states.\n\nOn the other hand, we can express the quantum states by choosing\nanother representation, which is derived from the operators of\n$\\hat{L}^{2}_{1}$, $\\hat{L}^{2}_{2}$, $\\hat{L}^{2}$ and\n$\\hat{\\mathbf{L}}_{z}$. Here the quantum states can be labeled by\n$L^{2}_{1},L^{2}_{2},L^{2},L_{z}$. Similarly, for the fixed value of\n$L_{1}, L_{2}$, they will be $(2L_{1}+1)(2L_{2}+1)$ different\nstates.\n\nWe can determine these states by the way below. By addition between\ndifferent $L_{1z}$ and $L_{2z}$, we can get the $L_{z}$:\n\\begin{center}\\label{ANGULARTABLE:1}\n\\begin{tabular}{c c c}\n  \\hline\n  % after \\\\: \\hline or \\cline{col1-col2} \\cline{col3-col4} ...\n  $L_{1z}$ & $L_{2z}$ & $L_{z}$ \\\\\n  \\hline\n  $L_{1}$     & $L_{2 }$     & $L_{1}+L_{2}$ \\\\\n  $L_{1}-1$   & $L_{2 }$     & $L_{1}+L_{2}-1$ \\\\\n  $L_{1}$     & $L_{2 }-1$   & $L_{1}+L_{2}-1$ \\\\\n  $L_{1}-2$   & $L_{2 }$     & $L_{1}+L_{2}-2$ \\\\\n  $L_{1}-1$   & $L_{2 }-1$   & $L_{1}+L_{2}-2$ \\\\\n  $L_{1}$     & $L_{2 }-2$   & $L_{1}+L_{2}-2$ \\\\\n  $\\cdots$    & $\\cdots$     & $\\cdots$ \\\\\n  \\hline\n\\end{tabular}\n\\end{center}\n\nHere we can see that for same $L_{z}$, it's always corresponding to\nmany states. These states must have different $L$ value (since that\nfor a fixed $L$, its angular momentum on z axis must be different.\nHence there's no two states can share the same $L_{z}$ if they have\nshared the same $L$), thus we can count the number of states as the\nchange of $L_{z}$. For example, as $L_{z} = L_{1}+L_{2}-2$, there\nmust have three states which possess different $L$, and because the\n$L \\geq L_{z}$; thus the three states must be $L = L_{1}+L_{2}$, $L\n= L_{1}+L_{2}-1$ and $L = L_{1}+L_{2}-2$. Therefore, if the number\nof states for the $L_{z}$ continues to grow, there implies it has\nnew states of different $L$.\n\nSuch continuing will be stopped at $L_{z} = |L_{1} - L_{2}|$. As the\n$L_{z}$ decreases, the number of states do not grow. This implies\nthat the eigen value of $\\hat{L}$ for the whole system will be:\n\\begin{equation}\\label{}\nL = L_{1}+L_{2}, L_{1}+L_{2}-1, L_{1}+L_{2}-2, \\cdots, |L_{1} -\nL_{2}|\n\\end{equation}\nHere the $L_{1}$ and $L_{2}$ has to give to be certain.\n\nThis phenomenon can be well understood by the \"vector model\" of\nangular momentum. Since that the angular momentum is some vector, as\nthe angular momentum in the subsystems take same direction, they\nwill give the maximum angular momentum addition for the whole; and\nif they take opposite direction, they will give the minimum angular\nmomentum for the whole. This coincides with the conclusion above.\n\n\n\n%%% Local Variables: \n%%% mode: latex\n%%% TeX-master: \"../../main\"\n%%% End: \n", "meta": {"hexsha": "5430cd099a484846f2ad020316f747295aa46eda", "size": 30049, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "theory/physics/angular.tex", "max_stars_repo_name": "murfreesboro/fenglai-note", "max_stars_repo_head_hexsha": "7bdf943f681e54948cd68775a31e4c93a53a13f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-16T07:23:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T07:23:48.000Z", "max_issues_repo_path": "theory/physics/angular.tex", "max_issues_repo_name": "murfreesboro/fenglai-note", "max_issues_repo_head_hexsha": "7bdf943f681e54948cd68775a31e4c93a53a13f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "theory/physics/angular.tex", "max_forks_repo_name": "murfreesboro/fenglai-note", "max_forks_repo_head_hexsha": "7bdf943f681e54948cd68775a31e4c93a53a13f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.6191135734, "max_line_length": 118, "alphanum_fraction": 0.630403674, "num_tokens": 10508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.33426584249280383}}
{"text": "\\chapter{Functional Renormalization and Quantum Gravity}\\label{chap:EHT}\nAfter the formal introduction of the physical and mathematical concepts in the last chapters, we are now able to motivate and formulate the key idea of the Asymptotic Safety approach to quantum gravity, which aims at finding a quantum field theoretical description of gravity within the language of the Functional Renormalization Group. This chapter briefly discusses the requirements for the existence of such a theory. We proceed by solving the flow equation for quantum gravity within the Einstein-Hilbert truncation in a transverse-traceless spin-two graviton approximation and investigate its fixed point structure. \n\\vspace{-0.6cm}\n\\section{Asymptotic Safety}\nAsymptotic Safety generalizes the concept of Asymptotic Freedom known as a property of certain gauge theories. The latter one is based on the idea, that the interaction of particles becomes asymptotically weak in the high-energy limit. In the language of the FRG this means, that the UV behavior of such theories is governed by a non-interacting, Gaussian fixed point,  allowing perturbative calculations. Maybe the most popular example for an asymptotically free theory is Quantum  Chromodynamics (QCD), the theory of the strong interaction. In 1978,  Steven Weinberg proposed the Asymptotic Safety scenario for gravity, based on the existence of an interacting, Non-Gaussian fixed point, rendering the theory non-perturbatively renormalizable in the UV \\cite{Weinberg1980}. The main advantage compared to other approaches is, that there is no need to introduce new symmetries, extra dimensions or other additional complications. The key requirements for an asymptotically safe quantum field theory of gravity can be summarized as follows: \n\\begin{enumerate}\n\t\\item The existence of an UV-attractive NGFP of the Renormalization Group flow of $\\Gammak$ has to be guaranteed. \n\t\\item For the predictivity of the theory, it is crucial to be able to fix the trajectory $\\Gammak$ by a finite amount of measurements, i.\\,e. the corresponding UV hypersurface $\\Sigma_{\\mathrm{UV}}$ of the NGFP should be of finite dimension: \n\t\\begin{equation*}\n\t\t\\operatorname{dim}\\Sigma_{\\mathrm{UV}} < \\infty.\n\t\\end{equation*} \n\\end{enumerate} \nWe want to probe these requirements in the following by computing the running of the Newton constant $G_k$ and the cosmological constant $\\Lambda_k$ in a pure-gravity setting. \\\\\nFor a more detailed discussion of current Asymptotic Safety research, we refer the interested reader to \\cite{Eichhorn2018}. Recently, very detailed textbooks covering both, the physical and the mathematical concepts of Asymptotic Safety, have been released. For a complete treatment of the subject it is worth to have a look at \\cite{Percacci2017} or \\cite{ReuterSaueressig_2019}.\n\\vspace{-0.6cm}\n\\section{Einstein-Hilbert Truncation}\nSolving the flow equation analytically is nothing but impossible. Therefore it is unavoidable to truncate the initially infinite dimensional theory space to a finite subspace, to be able to find approximated solutions. It is important, that all terms, that are invariant under the imposed symmetry, i.\\,e. invariant under diffeomorphism transformations, need to be taken into account. The easiest truncation fulfilling this requirement is the \\textit{Einstein-Hilbert truncation}. In 1996, Martin Reuter was the first to successfully investigate quantum gravity within the Einstein-Hilbert truncation \\cite{Reuter1996}. He was able to prove the existence of a NGFP for a pure-gravity setting. This truncation takes only the scalar curvature $\\Ricci$ and the cosmological constant $\\Lambda$ into account and therefore the truncated subspace is $2$-dimensional\\footnote{Recently, more sophisticated truncations including higher-order curvature terms ($\\Ricci^2$, $f(\\Ricci)$, $R^{\\mu\\nu}R_{\\mu\\nu}$ \\dots) have been investigated, see e.\\,g. \\cite{AlkoferSaueressig2018}.}.\\\\ The full Einstein-Hilbert  truncation reads:\n\\begin{align}\n\t\\Gammak = 2\\kappa^2Z_{h,k} \\int_x \\sqrt{g} \\ [-\\mathcal{R} + 2\\Lambda_k] + \\mathcal{S}_{\\text{gf}} + \\mathcal{S}_{\\text{gh}},\n\\label{eqn:EHtruncation}\n\\end{align}\nwhere we abbreviated $\\kappa^2 = \\left(32\\pi G\\right)^{-1}$. Since we don't need to consider the gauge fixing action $\\mathcal{S}_{\\text{gf}}$ and the Non-Abelian ghost action $\\mathcal{S}_{\\text{gh}}$ for the calculation performed in this chapter, we won't specify their explicit forms at this point. We will come back to this discussion at the beginning of chapter \\ref{chap:Matter}.\\\\\n The index $k$ indicates the \\textit{running} i.\\,e. the scale dependence of the cosmological constant and the wave function renormalization $Z_{h,k}$. It is quite convenient to define the running Newton coupling as \n \\begin{equation}\n \tG_k = G \\cdot \\left(Z_{h,k}\\right)^{-1}.\n \\end{equation}\nUp to this point, we did not care about the dimensionality of the two couplings. As already mentioned, one usually works with dimensionless couplings when solving the flow equation. \\\\\nWe therefore define the dimensionless renormalized cosmological constant \n\\begin{align}\n\t\\lambda_k = \\Lambdak\\cdot k^{-2}\n\\end{align}\nand Newton constant\n\\begin{align}\n\tg_k = G_k\\cdot k^{d-2} \\ \\overset{(d=4)}{=} \\ G_k\\cdot k^{2}.\n\\end{align}\nAfter these redefinitions, we can already compute the l.\\,h.\\,s. of the flow equation, i.\\,e. the scale derivative w.\\,r.\\,t. the RG time $t$. The derivative only acts on $\\lambda_k$ and $g_k$.\n\\begin{align}\n\t\\partial_{t}\\Gamma_{k} = 2\\kappa^2 Z_{k,h}\\int_x \\sqrt{g} \\left\\{\\eta_h\\mathcal{R}+2\\left(k^2(\\partial_t\\lambda_k) + \\Lambda_k(2 - \\eta_h)\\right)\\right\\}.\n\t\\label{eqn:LHS}\n\\end{align}\nHere we introduced the \\textit{anomalous dimension} $\\eta_h$, defined as\n\\begin{align}\n\t\\eta_h=-\\partial_t \\ln Z_{h,k} = -\\frac{\\partial_tZ_{h,k}}{Z_{h,k}}.\n\\end{align} \nWe find terms of order $\\sim\\sqrt{g}$ and order $\\sim\\sqrt{g}\\Ricci$. The r.\\,h.\\,s. of the flow equation is assumed to admit an expansion in terms of invariants, which will also be of order $\\sim\\sqrt{g}$ and $\\sim\\sqrt{g}\\mathcal{R}$ since we are working in the Einstein-Hilbert truncation\\footnote{There will also appear terms of higher order in curvature, but we will drop them.}. This will allow us to determine the $\\beta$-function for $\\lambda_k$ and the explicit form of $\\eta_h$ by a comparison of the terms of these orders on both sides of the flow equation.\nThe $\\beta$-function for $g_k$ follows directly from the anomalous dimension:\n\\begin{align}\n\t\\beta_g = \\partial_t g_k = \\left(2 + \\eta_h\\right)g_k.\n\t\\label{eqn:beta_gk}\n\\end{align}\nAt this point, we want to use the idea of the background field approximation. We assume a linear split of the metric into a background field $\\bar{g}$ and a fluctuation field $h$, as described in  equation (\\ref{eqn:metric_split}). The approximation at this point is, that in the following, we set all fluctuations to zero, i.\\,e. we evaluate all derivatives etc. at $g=\\bar{g}$. We will critically review this approximation in chapter \\ref{chap:BGindependence}. In general, there is no conceptual need to fix the background metric, it nevertheless is really useful to choose specific classes of backgrounds for certain computations, since this can simplify calculations a lot. We exploit the freedom of choosing a spherical background. On the four-sphere $\\mathbb{S}^4$, which is a maximally symmetric space\\footnote{Maximally symmetric spaces are characterized by the fact, that they have the same number of symmetries as ordinary Euclidean space.}, the Riemann tensor and the Ricci tensor can be written as multiples of the curvature scalar:\n\\begin{equation}\n\\begin{aligned}\n\t\\bar{R}_{\\mu\\nu} &= \\frac{1}{4} \\ \\bar{g}_{\\mu\\nu} \\bar{\\mathcal{R}}\\\\[10pt]\n\t\\bar{R}_{\\mu\\nu\\rho\\sigma} &= \\frac{1}{12} \\ (\\bar{g}_{\\mu\\rho}\\bar{g}_{\\nu\\sigma} - \\bar{g}_{\\mu\\sigma}\\bar{g}_{\\nu\\rho}) \\bar{\\mathcal{R}}.\n\\end{aligned}\t\n\\end{equation}\nThe bar in this notation refers to the background $\\bar{g}$. The inversion of the two-point function on general curved backgrounds is non-trivial. We need to find a suitable tensor basis for the decomposition of the metric fluctuation $h_{\\mu\\nu}$. We choose a \\textit{York decomposition} and find:\n\\begin{equation}\n\th_{\\mu v}=h_{\\mu v}^{\\mathrm{TT}}+\\bar{\\nabla}_{\\mu} \\xi_{v}+\\bar{\\nabla}_{v} \\xi_{\\mu}+\\left(\\bar{\\nabla}_{\\mu} \\bar{\\nabla}_{v}-\\frac{1}{d} \\bar{g}_{\\mu v} \\bar{\\Delta}\\right) \\sigma+\\frac{1}{d} \\bar{g}_{\\mu v} h.\n\t\\label{eqn:York}\n\\end{equation}\nHere, $ h_{\\mu\\nu}^{\\text{TT}}$ is a transverse-traceless, spin-two degree of freedom, $\\xi_{\\mu}$ is transverse and carries a spin-one d.\\,o.\\,f. and $\\sigma$ and $h$ have spin zero. For a more detailed motivation of the York decomposition, we refer to appendix \\ref{chap:AppA}.\\\\\nAs a further approximation, we only take the contribution from the spin-two graviton mode $h_{\\mu\\nu}^{\\text{TT}}$ into account\\footnote{This choice is motivated by the fact, that the spin-two mode carries the most degrees of freedom. From the $10$ initial d.\\,o.\\,f. in this decomposition, $4$ can be removed via gauge fixing, the remaining $6$ are divided into $5$ from the $h_{\\mu\\nu}^{\\text{TT}}$ mode and $1$ for the trace mode $h$.}. The other modes are included later on in chapter \\ref{chap:Matter}, when we couple matter to the system. \\\\\nOur starting point for the computation of the r.\\,h.\\,s. of the flow equation is the transverse-traceless graviton two-point function:\n\\begin{align}\n\\Gamma_{k, h^{\\text{TT}}h^{\\text{TT}}}^{(2)} = \\frac{Z_k}{32\\pi}\\left(\\bar{\\Delta} - 2\\Lambda_k+\\frac{2}{3}\\bar{\\mathcal{R}}\\right).\n\\end{align}\nHere, we used the definition of the Laplace operator, given by $\\Delta = -\\nabla^2$. We use a regulator of the form \n\\begin{align}\nR_k  = \\eval{\\Gamma_{h^{\\text{TT}}h^{\\text{TT}}}^{(2)}}_{\\Lambda_k=\\bar{\\mathcal{R}}=0} \\cdot r_k\\left(\\frac{\\bar{\\Delta}}{k^2}\\right),\n\\end{align}\nwith a Litim-type shape function (\\ref{eqn:Litim}). This allows us to determine the full propagator\n\\begin{equation}\n\tG_{k, h^{\\text{TT}}h^{\\text{TT}}} := \\left(\\Gamma_{k, h^{\\text{TT}}h^{\\text{TT}}}^{(2)} + R_k\\right)^{-1} = \\frac{32\\pi}{Z_{h,k}}\\left(\\bar{\\Delta}\\left(1+r_k\\right) -2\\Lambda_k + \\frac{2}{3}\\bar{\\mathcal{R}}\\right)^{-1}\n\\end{equation}\nand the scale derivative of the regulator\n\\begin{equation}\n\t\\partial_t R_k =  \\frac{Z_{h,k}}{32\\pi}\\bar{\\Delta}\\left(\\partial_tr_k - \\eta_hr_k\\right).\n\\end{equation}\nThe computation of the r.\\,h.\\,s. of the flow equation is in general very hard because it involves the computation of a functional trace of a function depending on the Laplacian on a curved background. We can use \\textit{heat-kernel techniques} to solve such equations. Heat-kernel computations are based on a curvature expansion in powers of the curvature scalar $\\mathcal{R}$. For more details, have a look at the second part of appendix \\ref{chap:AppA}.\\\\\nThe previously obtained results lead us to\n\\begin{equation}\n\\frac{1}{2}\\operatorname{Tr}\\left[G_{k, h^{\\text{TT}}h^{\\text{TT}}}\\ \\partial_t R_k\\right] = \\frac{1}{2}\\operatorname{Tr}\\left[\\frac{\\bar{\\Delta}\\left(\\partial_t r_k - \\eta_h r_k\\right)}{\\bar{\\Delta}(1+r_k)-2\\Lambda_k+\\frac{2}{3}\\bar{\\mathcal{R}}}\\right].\n\\end{equation}\nWe proceed by expanding this expression around vanishing curvature:\n\\begin{align}\n\\resizebox{.9 \\textwidth}{!}{$\n\\frac{1}{2}\\operatorname{Tr}\\left[G_{k, h^{\\text{TT}}h^{\\text{TT}}}\\ \\partial_t R_k\\right] = \\frac{1}{2}\\operatorname{Tr}\\left[\\frac{\\bar{\\Delta}\\left(\\partial_t r_k - \\eta_h r_k\\right)}{\\bar{\\Delta}(1+r_k)-2\\Lambda_k}\\right] - \\frac{1}{3}\\bar{\\mathcal{R}}\\operatorname{Tr}\\left[\\frac{\\bar{\\Delta}\\left(\\partial_t r_k - \\eta_h r_k\\right)}{\\left(\\bar{\\Delta}(1+r_k)-2\\Lambda_k\\right)^2}\\right] + \\mathcal{O}(\\mathcal{R}^2).$\n}\n\\end{align}\nWe evaluate these two terms separately using the heat-kernel formulas presented in appendix \\ref{chap:AppA}. The result for the first term reads\n\\begin{align}\n\\frac{1}{2}\\operatorname{Tr}\\left[\\frac{\\bar{\\Delta}\\left(\\partial_t r_k - \\eta_h r_k\\right)}{\\bar{\\Delta}(1+r_k)-2\\Lambda_k}\\right] &= \\frac{1}{2}\\frac{1}{(4\\pi)^2}\\int_x \\sqrt{\\bar{g}} \\left[5\\Phi_2^1(-2\\Lambda_k) - \\frac{5}{6}\\bar{\\mathcal{R}}\\Phi^1_1(-2\\Lambda_k)\\right] \\\\[10pt]\n&= \\frac{1}{2}\\frac{1}{(4\\pi)^2}\\int_x \\sqrt{\\bar{g}}\\left[\\frac{1}{1-2\\lambda_k}\\left(5\\left(1-\\frac{\\eta_h}{6}\\right) - \\frac{5}{3}\\bar{\\Ricci}\\left(1-\\frac{\\eta_h}{4}\\right)\\right)\\right],\\nonumber\n\\label{eqn:hk41_test}\n\\end{align}\nwith the definition of threshold functions \n\\begin{equation}\n\\begin{aligned}\n\t\\Phi_n^p(\\omega) &= \\frac{1}{\\Gamma(n)}\\int_0^{\\infty}\\dd z \\ z^{n-1} \\frac{z(-2zr_k(z)-\\eta_{\\Psi}r_k(z))}{(z(1+r_k(z))+\\omega)^p}\\\\[10pt] \n\t&= \\frac{1}{\\Gamma(n)}\\frac{1}{\\left(1+\\omega\\right)^p}\\left(\\frac{2}{n} - \\frac{\\eta_{\\Psi}}{n(n+1)}\\right).\n\\end{aligned}\n\\label{eqn:threshold}\n\\end{equation}\nIn the last step, we evaluated the threshold functions for the Litim-type shape function. We used $\\eta_\\Psi$, since we want to keep this formula as general as possible and we will use it multiple times for different fields throughout this thesis. Analogously, the second term in our expansion reads\n\\begin{align}\n\t-\\frac{1}{3}\\bar{\\mathcal{R}}\\operatorname{Tr}\\left[\\frac{\\bar{\\Delta}\\left(\\partial_t r_k - \\eta_h r_k\\right)}{\\left(\\bar{\\Delta}(1+r_k)-2\\Lambda_k\\right)^2}\\right] &= -\\frac{1}{2}\\frac{1}{(4\\pi)^2}\\int_x \\sqrt{\\bar{g}} \\ \\frac{10}{3}\\bar{\\Ricci}\\ \\Phi_2^2(-2\\Lambda_k)\\\\\n\t&=  -\\frac{1}{2}\\frac{1}{(4\\pi)^2}\\int_x \\sqrt{\\bar{g}}\\left[\\frac{1}{(1-2\\lambda_k)^2}\\left( \\frac{10}{3}\\bar{\\Ricci}\\left(1-\\frac{\\eta_h}{6}\\right)\\right)\\right].\\nonumber\n\t\\label{eqn:hk42}\n\\end{align}\nWith these results, we are able to determine the $\\beta$-function for the cosmological constant, simply by comparing the order $\\sim\\sqrt{\\bar{g}}$ terms occurring on the l.\\,h.\\,s. of the flow equation and the results from the heat-kernel expansion of the functional trace:\n\\begin{align}\n\t\\beta_{\\lambda} = \\partial_t\\lambda_k = -4\\lambda_k + \\frac{\\lambda_k}{g_k} \\partial_t g_k + \\frac{5}{4\\pi}g_k\\frac{1-\\frac{\\eta_h}{6}}{1-2\\lambda_k}.\n\\end{align}\nAdditionally, we find an expression for the anomalous dimension $\\eta_h$ by comparing the terms of order $\\sim\\sqrt{\\bar{g}}\\bar{\\Ricci}$:\n\\begin{align}\n\\eta_h = -\\frac{5g_k}{3\\pi} \\left(\\frac{1-\\frac{\\eta_h}{4}}{1-2\\lambda_k} + 2\\frac{1-\\frac{\\eta_h}{6}}{(1-2\\lambda_k)^2}\\right).\t\n\\end{align}\nTo find the fixed points for this truncated solution, we use \\verb|Mathematica| to solve the equation\n\\begin{equation}\n\t\\vec{\\beta} = \\begin{pmatrix}\\beta_g\\\\ \\beta_{\\lambda}\\end{pmatrix} \\overset{!}{=}  \\begin{pmatrix}0\\\\ 0\\end{pmatrix}.\n\\end{equation}\nWe arrive at the following values for the Newton coupling and the cosmological constant at the NGFP:\n\\begin{align}\n\t(g_k^*, \\lambda_k^*) = (0.86, 0.18).\n\\end{align}\nThe critical exponents of the fixed point are given by the complex conjugated pair\n\\begin{align}\n\t\\theta_{1,2} = 2.9 \\pm 2.6i. \n\\end{align}\n\\begin{figure}[t]\n\\centering\n\t\\includegraphics[width=0.8\\textwidth]{figs/Plots/EH_NoMatter}\n\t\\caption[Flow diagram for the Einstein-Hilbert truncation in $h^{\\mathrm{TT}}$ approximation]{Flow diagram  for the Einstein-Hilbert truncation in $h^{\\mathrm{TT}}$ approximation as computed in this work. The flow points towards the infrared. The postulated UV-attractive Non-Gaussian fixed point (blue dot) is clearly visible. }\n\t\\label{fig:flow_diag}\n\\hrulefill\t\n\\end{figure}\nThe corresponding flow diagram is depicted in figure  (\\ref{fig:flow_diag}). The \\enquote{swirl} around the NGFP is explained by the fact, that $\\mathfrak{Im}\\ \\theta_{1,2} \\neq 0$. The visualization and the plotting of the diagram was done in \\verb|Python|.\\\\\nBased on the results obtained in the scope of this calculation, we can confirm the existence of a UV-attractive Non-Gaussian fixed point for this truncated pure-gravity system, providing a good starting point for further analysis. As a first extension of this truncation, we want to go beyond the $h^{\\mathrm{TT}}$ approximation by taking the contributions for the other modes into account. Then, we will investigate the impact of minimally coupled matter fields on the system. All these calculations will be explained in full detail in the next chapter. ", "meta": {"hexsha": "85588aaf7463a8dfbc89a9995488bb0bcaa7ceb1", "size": 16203, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Thesis/content/04_eh_truncation.tex", "max_stars_repo_name": "mathieukaltschmidt/BSc-Thesis", "max_stars_repo_head_hexsha": "d930ee60ab526835c904252e68272408f3d6a16f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-22T15:05:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-22T15:05:57.000Z", "max_issues_repo_path": "Thesis/content/04_eh_truncation.tex", "max_issues_repo_name": "mathieukaltschmidt/BSc-Thesis", "max_issues_repo_head_hexsha": "d930ee60ab526835c904252e68272408f3d6a16f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Thesis/content/04_eh_truncation.tex", "max_forks_repo_name": "mathieukaltschmidt/BSc-Thesis", "max_forks_repo_head_hexsha": "d930ee60ab526835c904252e68272408f3d6a16f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-25T05:06:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-25T05:06:03.000Z", "avg_line_length": 115.7357142857, "max_line_length": 1117, "alphanum_fraction": 0.7374560267, "num_tokens": 4925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.33417736014226873}}
{"text": "\\documentclass[../notes.tex]{subfiles}\n\n\\pagestyle{main}\n\\renewcommand{\\chaptermark}[1]{\\markboth{\\chaptername\\ \\thechapter\\ (#1)}{}}\n\\setcounter{chapter}{33}\n\n\\begin{document}\n\n\n\n\n\\chapter{Geometric Optics}\n\\section{Mirrors}\n\\begin{itemize}\n    \\item \\marginnote{8/12:}Take what we know about reflection and refraction and apply it to mirrors and lenses.\n    \\item Bathroom mirror: A flat piece of glass with a shiny background behind it.\n    \\item Spherical mirror: Some part of a reflective sphere.\n    \\item Relating the \\textbf{radius of curvature} and the distance to the \\textbf{focal point}, or the \\textbf{focal length}, of a concave spherical mirror.\n    \\begin{figure}[h!]\n        \\centering\n        \\begin{tikzpicture}[\n            scale=1.3,\n            pics/point/.style args={#1:#2}{code={\n                \\coordinate (#2);\n                \\node [circle,fill=pix,inner sep=1.5pt,label={#1:$#2$}] {};\n            }}\n        ]\n            \\footnotesize\n            \\def\\r{30}\n            \\draw [name path=axis] (0,0) -- (4,0) node[right]{axis};\n    \n            \\draw [blx,thick] (2.5,1) arc[start angle=45,end angle=-45,radius={2^0.5}];\n    \n            \\draw [very thin,dashed] (1.5,0) pic{point=below:C} -- ++(\\r:2^0.5) pic{point=right:A};\n            \\pic at ({1.5+2^0.5},0) {point=below right:V};\n    \n            \\draw [\n                rex,thick,-latex,name path=ray,postaction={decorate},decoration={\n                    markings,mark=at position 0.1 with \\arrow{latex}\n                }\n            ]\n                (A) ++(-2.7,0) coordinate (1)\n                -- (A) node[circle,fill=pix,inner sep=1.5pt]{}\n                -- ++({180+2*\\r}:2)\n            ;\n    \n            \\path [name intersections={of=axis and ray,by=F}] pic at (F) {point=below:F};\n            \\pic [draw,angle eccentricity=1.3,pic text={$\\theta$}] {angle=1--A--C};\n            \\pic [draw,angle eccentricity=1.3,pic text={$\\theta$}] {angle=C--A--F};\n            \\pic [draw,angle eccentricity=1.3,pic text={$\\theta$}] {angle=F--C--A};\n        \\end{tikzpicture}\n        \\caption{Spherical mirror analysis.}\n        \\label{fig:sphericalMirror}\n    \\end{figure}\n    \\begin{itemize}\n        \\item For a distant source $s$, we can approximate the rays as parallel.\n        \\item Consider one specific ray.\n        \\item Drawing a normal to the surface of the spherical mirror, this normal will be a radius passing through the \\textbf{center of curvature}.\n        \\item It follows by the law of reflection and the alternate interior angle theorem that all $\\theta$ are equal.\n        \\item This makes $\\triangle CFA$ isosceles.\n        \\item Now assume \\textbf{paraxial rays}.\n        \\item Then $\\triangle CFA$ converges to a line segment (a radius) with midpoint $F$.\n        \\item Therefore,\n        \\begin{equation*}\n            f = \\frac{R}{2}\n        \\end{equation*}\n        for a concave spherical mirror.\n    \\end{itemize}\n    \\item \\textbf{Radius of curvature}: The radius of the sphere into which the spherical mirror would fit. \\emph{Denoted by} $\\bm{R}$.\n    \\item \\textbf{Focal point}: The point where parallel rays converge, after reflecting off of a curved mirror. \\emph{Denoted by} $\\bm{F}$.\n    \\item \\textbf{Focal length}: The distance from the focal point to the mirror. \\emph{Denoted by} $\\bm{f}$.\n    \\item \\textbf{Center of curvature}: The center of the sphere into which the spherical mirror would fit. \\emph{Denoted by} $\\bm{C}$.\n    \\item \\textbf{Paraxial ray}: A ray that is close to the mirror axis.\n    \\item Alternatively, if you look at a convex mirror, it appears (via ray tracing) that all rays of light originated from the focal point.\n    \\begin{itemize}\n        \\item The image in this type of mirror will be a virtual image.\n        \\item In this case, we say that $f=-R/2$.\n    \\end{itemize}\n    \\item A spherical mirror does not focus all rays to a \\emph{single} point --- the rays only go to \\emph{approximately} the same point.\n    \\begin{itemize}\n        \\item The farther the rays get from being paraxial, the more they diverge from the focal point.\n    \\end{itemize}\n    \\item To have a true focal point, we need a parabolic mirror.\n    \\item Unfortunately, parabolic mirrors are hard to make.\n    \\item \\textbf{Ray tracing}: Take a few \\textbf{principal rays} and see where the image forms.\n    \\begin{figure}[h!]\n        \\centering\n        \\begin{tikzpicture}[\n            scale=2.5,\n            pics/point/.style args={#1:#2}{code={\n                \\coordinate (#2);\n                \\node [circle,fill=pix,inner sep=1.5pt,label={#1:${\\color{black}#2}$}] {};\n            }}\n        ]\n            \\footnotesize\n            \\draw [name path=axis] (0,0) -- (3.5,0) node[right]{axis};\n    \n            \\draw [blx,thick,name path=mirror] (2,1) arc[start angle=45,end angle=-45,radius={2^0.5}];\n    \n            \\draw [grx,ultra thick,-stealth] (0.5,0) node[above left,black]{object} edge [black,thin,->,out=90,in=180,shorten >=2pt] (0.5,0.4) -- ++(0,{2^0.5/2}) coordinate (P1);\n    \n            \\path [name path=Afinder] (P1) -- ++(4,0);\n            \\draw [\n                rex,thick,-latex,postaction={decorate},\n                decoration={markings,mark=at position 0.2 with \\arrow{latex}},\n                name intersections={of=mirror and Afinder,by=A},name path=parallel\n            ] (P1) -- (A) -- ++(-120:2);\n            \\draw [\n                rex,thick,-latex,postaction={decorate},\n                decoration={markings,mark=at position 0.2 with \\arrow{latex}},\n                name intersections={of=mirror and axis,by=V},name path=central\n            ] (P1) -- (V) pic{point={[xshift=-2pt,yshift=2pt]below right:V}} -- (P1 |- 0,{-2^0.5/2});\n            \\path [name intersections={of=axis and parallel,by=F},name path=Fmirror] (P1) -- ($(P1)!1.5!(F)$);\n            \\draw [\n                rex,thick,-latex,line join=bevel,postaction={decorate},\n                decoration={markings,mark=at position 0.2 with \\arrow{latex}},\n                name intersections={of=mirror and Fmirror}\n            ] (P1) -- (intersection-1) -- ++(-2,0);\n            \\path [name intersections={of=parallel and central,by={,,I}},name path=Imirror] (P1) -- ($(P1)!2!(I)$);\n            \\draw [\n                rex,thick,postaction={decorate},\n                decoration={\n                    markings,\n                    mark=at position 0.33 with \\arrow{latex},\n                    mark=at position 0.85 with \\arrowreversed{latex}\n                },\n                name intersections={of=axis and Imirror,by=C},name intersections={of=mirror and Imirror}\n            ] (P1) -- (intersection-1) pic at (C) {point={[xshift=2pt,yshift=2pt]below left:C}};\n    \n            \\draw [grx,ultra thick,stealth-] (I) node[below left,yshift=-1mm,black,fill=white,inner sep=1.5pt]{image} edge[black,thin,->,out=90,in=180,shorten >=2pt] (I |- 0,-0.1) -- (I |- 0,0);\n            \\pic at (F) {point={[fill=white,circle,inner sep=0pt,xshift=1pt,yshift=0pt]below right:F}};\n        \\end{tikzpicture}\n        \\caption{Ray tracing a concave mirror.}\n        \\label{fig:rayTracing}\n    \\end{figure}\n    \\item \\textbf{Principal ray}: A ray with well-understood geometry.\n    \\item \\textbf{Focal ray}: A ray that goes through the focal point.\n    \\begin{itemize}\n        \\item Will be reflected out as a parallel ray.\n    \\end{itemize}\n    \\item \\textbf{Central ray}: A ray that hits the center of the mirror.\n    \\begin{itemize}\n        \\item Will be reflected out with the same incident angle relative to the axis.\n    \\end{itemize}\n    \\item \\textbf{Radial ray}: A ray that passes through the center of curvature.\n    \\begin{itemize}\n        \\item It follows a \\emph{radius} of the sphere of curvature.\n        \\item Will be reflected such that it heads right back to where it started.\n    \\end{itemize}\n    \\item Calculating the location of the image in a spherical mirror.\n    \\begin{figure}[h!]\n        \\centering\n        \\begin{tikzpicture}[\n            scale=2.5,\n            pics/point/.style args={#1:#2}{code={\n                \\coordinate (#2);\n                \\node [circle,fill=pix,inner sep=1.5pt,label={#1:${\\color{black}#2}$}] {};\n            }}\n        ]\n            \\footnotesize\n            \\draw [name path=axis] (0,0) -- (3.5,0) node[right]{axis};\n    \n            \\draw [blx,thick,name path=mirror] (2,1) arc[start angle=45,end angle=-45,radius={2^0.5}];\n    \n            \\draw [grx,ultra thick,-stealth] (0.5,0) coordinate (Q1) node[below left,black]{$Q$} node[above left,black]{object} edge [black,thin,->,out=90,in=180,shorten >=2pt] (0.5,0.4) -- ++(0,{2^0.5/2}) coordinate (P1) node[above left,black]{$P$};\n    \n            \\path [name path=Afinder] (P1) -- ++(4,0);\n            \\path [name intersections={of=mirror and Afinder,by=A},name path=parallel] (P1) -- (A) -- ++(-120:2);\n            \\draw [\n                rex,thick,-latex,postaction={decorate},\n                decoration={markings,mark=at position 0.2 with \\arrow{latex}},\n                name intersections={of=mirror and axis,by=V},name path=central\n            ] (P1) -- (V) pic{point={[xshift=-2pt,yshift=2pt]below right:V}} -- (P1 |- 0,{-2^0.5/2});\n            \\path [name intersections={of=parallel and central,by={,,I}},name path=Imirror] (P1) -- ($(P1)!2!(I)$);\n            \\draw [\n                rex,thick,postaction={decorate},\n                decoration={\n                    markings,\n                    mark=at position 0.33 with \\arrow{latex},\n                    mark=at position 0.85 with \\arrowreversed{latex}\n                },\n                name intersections={of=axis and Imirror,by=C},name intersections={of=mirror and Imirror}\n            ] (P1) -- (intersection-1) pic at (C) {point={[xshift=2pt,yshift=2pt]below left:C}};\n    \n            \\draw [grx,ultra thick,stealth-] (I) coordinate (P2) node[below=1pt,xshift=-1pt,black]{$P'$} node[below right,xshift=4mm,black]{image} edge[black,thin,->,out=135,in=0,shorten >=2pt] (I |- 0,-0.1) -- (I |- 0,0) coordinate (Q2) node[above,black]{$Q'$};\n    \n            \\path [name intersections={of=axis and parallel,by=F}] (F) pic {point={[fill=white,circle,inner sep=0pt,xshift=1pt,yshift=0pt]below right:F}};\n            \\pic [draw,angle radius=2mm] {right angle=C--Q1--P1};\n            \\pic [draw,angle radius=2mm] {right angle=C--Q2--P2};\n            \\pic [draw,angle radius=4mm,angle eccentricity=1,pic text={=},pic text options={rotate=160,yshift=-0.5pt}] {angle=P1--C--Q1};\n            \\pic [draw,angle radius=4mm,angle eccentricity=1,pic text={=},pic text options={rotate=-20,yshift=-0.5pt}] {angle=P2--C--Q2};\n            \\pic [draw,angle radius=6mm,angle eccentricity=1,pic text={\\large--},pic text options={rotate=170}] {angle=P1--V--Q1};\n            \\pic [draw,angle radius=6mm,angle eccentricity=1,pic text={\\large--},pic text options={rotate=190}] {angle=Q2--V--P2};\n    \n            \\draw [very thin,|-|] (P1) ++(0,0.4) -- node[above]{$s$} ++(1.92,0);\n            \\draw [very thin,|-|] (P2) ++(0,-0.8) -- node[below]{$s'$} ++(0.76,0);\n        \\end{tikzpicture}\n        \\caption{Deriving the mirror equation.}\n        \\label{fig:mirrorEquation}\n    \\end{figure}\n    \\begin{itemize}\n        \\item The image in a spherical mirror will be an inverted, \\textbf{real} image.\n        \\item Two principal rays define where the image is.\n        \\item Considering the image of the top point in our object, choose to analyze a central ray and a radial ray.\n        \\item Then $\\triangle PVQ$ and $\\triangle P'VQ'$ are similar, and $\\triangle PCQ$ and $\\triangle P'CQ'$ are similar.\n        \\item It follows that\n        \\begin{align*}\n            \\frac{\\overline{PQ}}{{\\color{white}(}\\overline{P'Q'}{\\color{white})}} &= \\frac{\\overline{QV}}{{\\color{white}(}\\overline{Q'V}{\\color{white})}} = \\frac{s}{s'}&\n            \\frac{\\overline{PQ}}{{\\color{white}(}\\overline{P'Q'}{\\color{white})}} &= \\frac{\\overline{QC}}{{\\color{white}(}\\overline{Q'C}{\\color{white})}} = \\frac{s-R}{R-s'}\n        \\end{align*}\n        \\item Thus, we have the following, which can be solved for the mirror equation.\n        \\begin{equation*}\n            \\frac{s}{s'} = \\frac{s-R}{R-s'}\n        \\end{equation*}\n    \\end{itemize}\n    \\item \\textbf{Real image}: An image that could be substituted for an image on a screen in real space.\n    \\item \\textbf{Object distance}: The distance from an object to a spherical mirror. \\emph{Denoted by} $\\bm{s}$.\n    \\item \\textbf{Image distance}: The distance from an object's image to the mirror. \\emph{Denoted by} $\\bm{s'}$.\n    \\item \\textbf{Mirror equation}: The formula\n    \\begin{equation*}\n        \\frac{1}{s}+\\frac{1}{s'} = \\frac{1}{f}\n    \\end{equation*}\n    \\item \\textbf{Lateral magnification}: The ratio of the distance from the object to the mirror and the distance from the image to the mirror. \\emph{Denoted by} $\\bm{m}$.\n    \\begin{itemize}\n        \\item Mathematically,\n        \\begin{equation*}\n            m = \\frac{-s'}{s}\n        \\end{equation*}\n        \\item If $m<0$, the image is inverted.\n        \\item If $m>0$, the image is upright.\n        \\item Sign convention: $s,s'$ are positive in front of the mirror and negative behind the mirror.\n    \\end{itemize}\n    \\item Check the above equations on the example of a plane mirror.\n    \\begin{itemize}\n        \\item For a plane mirror, $R=\\infty$, so $\\frac{1}{f}=0$.\n        \\item It follows by the mirror equation that $s'=-s$.\n        \\item Therefore, $m=1$, as desired.\n    \\end{itemize}\n    \\item \\marginnote{8/13:}Ray tracing a convex mirror.\n    \\begin{figure}[H]\n        \\centering\n        \\begin{tikzpicture}[\n            scale=2.5,\n            pics/point/.style args={#1:#2}{code={\n                \\coordinate (#2);\n                \\node [circle,fill=pix,inner sep=1.5pt,label={#1:${\\color{black}#2}$}] {};\n            }}\n        ]\n            \\footnotesize\n            \\draw [name path=axis] (0,0) -- (3.5,0) node[right]{axis};\n    \n            \\draw [blx,thick,name path=mirror] (2,1) arc[start angle=135,end angle=225,radius={2^0.5}];\n    \n            \\draw [grx,ultra thick,-stealth] (0.5,0) node[above left,black]{object} edge [black,thin,->,out=90,in=180,shorten >=2pt] (0.5,0.4) -- ++(0,{2^0.5/2}) coordinate (P1);\n    \n            \\path [name path=Afinder] (P1) -- ++(4,0);\n            \\draw [\n                rex,thick,-latex,postaction={decorate},\n                decoration={markings,mark=at position 0.2 with \\arrow{latex}},\n                name intersections={of=mirror and Afinder,by=A},name path=parallel\n            ] (P1) -- (A) -- ++(120:1);\n            \\draw [\n                rex,thick,-latex,postaction={decorate},\n                decoration={markings,mark=at position 0.2 with \\arrow{latex}},\n                name intersections={of=mirror and axis,by=V},name path=central\n            ] (P1) -- (V) -- (P1 |- 0,{-2^0.5/2});\n            \\path [name path=Ffinder] (A) -- ++(-60:1);\n            \\draw [rex,thick,dashed,name intersections={of=Ffinder and axis,by=F}] (A) -- (F) pic{point=below:F};\n            \\path [name path=P2finder] (V) -- ++($(V)-(P1)+(0,2^0.5)$);\n            \\draw [rex,thick,dashed,name intersections={of=P2finder and Ffinder,by=P2}] (V) -- (P2);\n    \n            \\draw [grx,ultra thick,-stealth] (P2 |- 0,0) -- (P2) node[above right,black]{image} edge [out=-90,in=0,->,black,thin,shorten >=2pt] (P2 |- 0,0.1);\n        \\end{tikzpicture}\n        \\caption{Ray tracing a convex mirror.}\n        \\label{fig:rayTracingConvex}\n    \\end{figure}\n    \\begin{itemize}\n        \\item Upright, smaller, virtual image.\n    \\end{itemize}\n\\end{itemize}\n\n\n\n\\section{Lenses}\n\\begin{itemize}\n    \\item \\marginnote{8/12:}\\textbf{Double convex} (lens): A lens with two convex exterior surfaces. \\emph{Also known as} \\textbf{convex} (lens), \\textbf{converging} (lens), \\textbf{positive} (lens).\n    \\item \\textbf{Double concave} (lens): A lens with two concave exterior surfaces. \\emph{Also known as} \\textbf{concave} (lens), \\textbf{diverging} (lens), \\textbf{negative} (lens).\n    \\item \\textbf{Plano convex} (lens): A lens with one concave exterior surface and one flat exterior surface.\n    \\begin{figure}[h!]\n        \\centering\n        \\begin{tikzpicture}[scale=1.3]\n            \\footnotesize\n            \\draw [name path={axis}] (0,0) -- (6,0) node[right]{axis};\n    \n            \\draw [very thin,dashed]\n                (1,0) coordinate (C) node[circle,fill=pix,inner sep=1.5pt,label={below:$C$}]{}\n                ++(30:-0.5) -- ++(30:0.5) -- node[below]{$R$} ++(30:{2^0.5}) coordinate (V)\n                -- ++(30:1) coordinate (B)\n                (V) -- ++(1.5,0) coordinate (D)\n            ;\n    \n            \\draw [rex,thick,postaction={decorate},decoration={markings,mark=at position 0.1 with \\arrow{latex}},-latex,name path={ray}] (V) ++(-2.2,0) coordinate (A) -- (V) -- ++(3.5,-1.3);\n            \n            \\draw [blx,thick] (2,1) arc[start angle=45,end angle=-45,radius={2^0.5}] -- node[below left,black,text height=1.5ex,text depth=0.25ex]{$1$} node[below right,black,text height=1.5ex,text depth=0.25ex]{$n$} node[below right,xshift=5mm,black,text height=1.5ex,text depth=0.25ex]{$1$} cycle;\n    \n            \\path [name intersections={of=axis and ray,by=F}] (F) node [circle,fill=pix,inner sep=1.5pt,label={below:$F$}] {};\n            \\draw [very thin,|-|] (-0.15,0) -- node[left]{$y$} (-0.15,0 |- V);\n            \\draw [very thin,|-|] (V |- 0,1.3) -- node[above]{$f$} (F |- 0,1.3);\n            \\pic [draw,angle eccentricity=1.3,angle radius=6mm,pic text={$\\theta_1$}] {angle=A--V--C};\n            \\pic [draw,angle eccentricity=1.2,angle radius=1cm,pic text={$\\theta_1$}] {angle=D--V--B};\n            \\pic [draw,angle eccentricity=1.3,angle radius=1cm,pic text={$\\theta_\\text{def}$}] {angle=F--V--D};\n            \\pic [draw,angle eccentricity=1.41,angle radius=5mm,pic text={$\\theta_2$},pic text options={fill=white,inner sep=1.5pt}] {angle=F--V--B};\n        \\end{tikzpicture}\n        \\caption{Plano convex lens analysis.}\n        \\label{fig:planoConvexLens}\n    \\end{figure}\n    \\begin{itemize}\n        \\item Clearly, $\\theta_\\text{def}=\\theta_2-\\theta_1$ and $\\sin\\theta_1=y/R$.\n        \\item If this is a \\textbf{thin lens}, then we can invoke the small angle approximation and say that $\\theta_1\\approx y/R$.\n        \\item By Snell's Law, $\\sin\\theta_2=n\\sin\\theta_1$.\n        \\item Invoking the SAA again, we have that $\\theta_2=n\\theta_1$.\n        \\item It follows that\n        \\begin{align*}\n            \\theta_\\text{def} &= \\theta_2-\\theta_1\\\\\n            &= n\\theta_1-\\theta_1\\\\\n            &= (n-1)\\theta_1\\\\\n            &= (n-1)\\cdot\\frac{y}{r}\n        \\end{align*}\n        \\item Therefore, since $\\sin\\theta_\\text{def}=\\frac{y}{f}$ (i.e., with the SAA $\\theta_\\text{def}=y/f$), we have that\n        \\begin{align*}\n            f &= \\frac{y}{\\theta_\\text{def}}\\\\\n            &= \\frac{y}{(n-1)\\cdot y/R}\\\\\n            &= \\frac{R}{n-1}\n        \\end{align*}\n        \\item More commonly, we express this with\n        \\begin{equation*}\n            \\frac{1}{f} = (n-1)\\cdot\\frac{1}{R}\n        \\end{equation*}\n    \\end{itemize}\n    \\item \\textbf{Thin lens}: A lens where $\\theta$'s are small.\n    \\item If you substitute a convex lens for the plano convex lens, everything gets doubled.\n    \\begin{itemize}\n        \\item Importantly, we now have\n        \\begin{equation*}\n            \\frac{1}{f} = (n-1)\\cdot\\frac{2}{R}\n        \\end{equation*}\n    \\end{itemize}\n    \\item We can also generalize a convex lens to a lens with two convex sides of varying radii of curvature on its two sides.\n    \\item \\textbf{Lens maker's equation}: The following formula.\n    \\begin{equation*}\n        \\frac{1}{f} = (n-1)\\cdot\\left( \\frac{1}{R_1}+\\frac{1}{R_2} \\right)\n    \\end{equation*}\n    \\begin{itemize}\n        \\item Notice that if, for instance, the first side is planar, then $R_1=\\infty$ and the $1/R_1$ term disappears.\n        \\item Sign convention: $R_1,R_2$ are positive for convex lenses and negative for concave lenses.\n    \\end{itemize}\n    \\item Remember that knowing the focal length of a lens allows us to ray trace.\n    \\begin{figure}[h!]\n        \\centering\n        \\begin{tikzpicture}[\n            pics/point/.style args={#1:#2}{code={\n                \\coordinate (#2);\n                \\node [circle,fill=pix,inner sep=1.5pt,label={#1:${\\color{black}#2}$}] {};\n            }}\n        ]\n            \\footnotesize\n            \\fill [blz] (3,1) arc[start angle=30,end angle=-30,radius=2] arc[start angle=210,end angle=150,radius=2];\n            \\draw [name path=axis] (0,0) -- (6,0) node[right]{axis};\n            \\draw [blx,thick] (3,1) arc[start angle=30,end angle=-30,radius=2] arc[start angle=210,end angle=150,radius=2];\n    \n            \\draw [grx,ultra thick,-stealth] (1,0) node[above left,black]{object} edge [black,thin,->,out=90,in=180,shorten >=2pt] (1,0.55) -- ++(0,0.9) coordinate (P1);\n            \\draw [grx,ultra thick,-stealth] (5,0) node[below right,black]{image} edge [black,thin,->,out=-90,in=0,shorten >=2pt] (5,-0.55) -- ++(0,-0.9) coordinate (P2);\n    \n            \\draw [rex,thick,-latex,postaction={decorate},decoration={markings,mark=at position 0.2 with \\arrow{latex}},name path=parallel] (P1) -- (3.05,0.9) -- ($(3.05,0.9)!1.5!(P2)$);\n            \\draw [rex,thick,-latex,postaction={decorate},decoration={markings,mark=at position 0.2 with \\arrow{latex}}] (P1) -- ($(P1)!1.3!(P2)$);\n            \\draw [rex,thick,-latex,postaction={decorate},decoration={markings,mark=at position 0.2 with \\arrow{latex}},name path=focal] (P1) -- (2.95,-0.9) -- ($(2.95,-0.9)!1.6!(P2)$);\n    \n            \\path [name intersections={of=parallel and axis}] (intersection-1) pic{point=above right:F};\n            \\path [name intersections={of=focal and axis}] (intersection-1) pic{point=below left:F};\n        \\end{tikzpicture}\n        \\caption{Convex lens rays.}\n        \\label{fig:lensRaysConvex}\n    \\end{figure}\n    \\begin{itemize}\n        \\item Central rays in thin lenses have negligible lateral displacement.\n        \\item An image through a convex lens will be an inverted real image.\n    \\end{itemize}\n    \\item \\marginnote{8/13:}Ray tracing a concave lens.\n    \\begin{itemize}\n        \\item Upright, smaller, virtual image.\n    \\end{itemize}\n    \\item Note that the lens maker's equation used by \\textcite{bib:YoungFreedman} is $1/f=(n-1)(1/R_1-1/R_2)$, along with a complicated sign convention.\n    \\begin{itemize}\n        \\item The textbook uses this formula because it follows from the study of thick lenses, with which many older textbooks start.\n    \\end{itemize}\n    \\item A concave mirror and a plano convex lens with a mirrored background image the same way.\n    \\begin{itemize}\n        \\item A convex lens mirrors the same way as both, but with the image on the other side of the lens as opposed to the same side of the apparatus.\n    \\end{itemize}\n    \\item Therefore, the lens equation is also analogously\n    \\begin{equation*}\n        \\frac{1}{s}+\\frac{1}{s'} = \\frac{1}{f}\n    \\end{equation*}\n    \\begin{itemize}\n        \\item However, this equation comes with the sign convention that $s$ is positive in front of the lens and negative behind the lens, and $s'$ is positive behind the lens and negative in front of the lens.\n    \\end{itemize}\n    \\item Similarly,\n    \\begin{equation*}\n        m = \\frac{-s'}{s}\n    \\end{equation*}\n    for lenses, with the new sign convention.\n    \\item Note that the focal length is positive for convex lenses and negative for concave lenses.\n    \\item Just like mirrors can image images from other mirrors, lenses can image images from other lenses.\n    \\begin{itemize}\n        \\item You do it the same way, too --- one at a time.\n    \\end{itemize}\n    \\item Example: Suppose that you have two identical thin lenses, $\\SI{15}{\\centi\\meter}$ apart, with focal length $\\SI{10}{\\centi\\meter}$ each. Place an object $\\SI{15}{\\centi\\meter}$ to the left of the left lens. How does it image?\n    \\begin{figure}[h!]\n        \\centering\n        \\begin{tikzpicture}[\n            pics/point/.style args={#1:#2}{code={\n                \\coordinate (#2);\n                \\node [circle,fill=pix,inner sep=1.5pt,label={#1:${\\color{black}#2}$}] {};\n            }},\n            every node/.style={black}\n        ]\n            \\footnotesize\n            \\fill [blz] (2,1) arc[start angle=30,end angle=-30,radius=2] arc[start angle=210,end angle=150,radius=2];\n            \\fill [blz] (3.5,1) arc[start angle=30,end angle=-30,radius=2] arc[start angle=210,end angle=150,radius=2];\n            \\draw [name path=axis] (0,0) -- (6,0) node[right]{axis};\n            \\draw [blx,thick] (2,1)   node[above]{$1$} arc[start angle=30,end angle=-30,radius=2] node[below]{$f=\\SI{10}{\\centi\\meter}$} arc[start angle=210,end angle=150,radius=2];\n            \\draw [blx,thick] (3.5,1) node[above]{$2$} arc[start angle=30,end angle=-30,radius=2] node[below]{$f=\\SI{10}{\\centi\\meter}$} arc[start angle=210,end angle=150,radius=2];\n    \n            \\pic at (1,0) {point=below:F_1};\n            \\pic at (3,0) {point=below:F_1};\n            \\pic at (2.5,0) {point=below:F_2};\n            \\pic at (4.5,0) {point=below:F_2};\n    \n            \\draw [grx,ultra thick,-stealth] (0.5,0) -- ++(0,0.8) node[above right=-2pt,black]{object} edge [black,thin,->,out=-90,in=0,shorten >=2pt] (0.5,0.4);\n            \\draw [grx,ultra thick,-stealth] (4.1,0) -- ++(0,-0.64) node[below right=-2pt,black]{image} edge [black,thin,->,out=90,in=0,shorten >=2pt] (4.1,-0.3);\n    \n            \\draw (0,-1.7) -- node[below=6mm]{$\\si{\\centi\\meter}$} ++(6,0);\n            \\foreach \\x [evaluate=\\x as \\num using int(\\x*10)] in {0,0.5,...,6} {\n                \\draw (\\x,-1.6) -- ++(0,-0.2) node[below]{$\\num$};\n            }\n        \\end{tikzpicture}\n        \\caption{Imaging two lenses.}\n        \\label{fig:twoLensImage}\n    \\end{figure}\n    \\begin{itemize}\n        \\item Image location:\n        \\begin{itemize}\n            \\item For lens 1, we have $f=\\SI{10}{\\centi\\meter}$ and $s=\\SI{15}{\\centi\\meter}$, so $s'=\\SI{30}{\\centi\\meter}$ by the lens equation.\n            \\item For lens 2, we still have $f=\\SI{10}{\\centi\\meter}$ but now we have have $s=\\SI{-15}{\\centi\\meter}$, so $s'=\\SI{6}{\\centi\\meter}$ by the lens equation.\n        \\end{itemize}\n        \\item Magnification:\n        \\begin{align*}\n            m_\\text{total} &= m_1m_2\\\\\n            &= \\left( -\\frac{\\SI{30}{\\centi\\meter}}{\\SI{15}{\\centi\\meter}} \\right)\\left( -\\frac{\\SI{6}{\\centi\\meter}}{\\SI{-15}{\\centi\\meter}} \\right)\\\\\n            &= -\\frac{4}{5}\n        \\end{align*}\n        \\item Thus, the total image is inverted, $4/5$ times the size of the original, and $\\SI{6}{\\centi\\meter}$ to the right of the rightmost lens.\n    \\end{itemize}\n    \\item Mirrors and lenses have limitations.\n    \\begin{itemize}\n        \\item Thus, it does make sense to use multiple mirrors/lenses in some circumstances.\n        \\item Compensating for the paraxial approximation: When you need a sharper focus in good cameras.\n        \\item Compensating for the dependence of $n$ on frequency: Have any single lens do less work.\n    \\end{itemize}\n\\end{itemize}\n\n\n\n\\section{Chapter 34: Geometric Optics}\n\\emph{From \\textcite{bib:YoungFreedman}.}\n\\begin{itemize}\n    \\item \\marginnote{8/16:}\\textbf{Point object}: A theoretical object consisting only of a zero-dimensional point.\n    \\item \\textbf{Extended object}: An object that is not a point object.\n    \\item \\textbf{Diffuse} (surface): A surface which scatters incoming rays in uncorrelated directions.\n    \\item \\textbf{Virtual image}: An image for which the outgoing rays do not pass through the image point.\n    \\item \\textbf{Real image}: An image for which the outgoing rays do pass through the image point.\n    \\item \"When the center of curvature C is on the same side as the outgoing light, the radius of curvature is positive; otherwise, it is negative\" \\parencite[1112]{bib:YoungFreedman}.\n    \\item \\textbf{Lateral magnification}: The ratio of image height to object height.\n    \\item \\textbf{Erect} (image): An image that is oriented in the same direction as the object.\n    \\begin{itemize}\n        \\item Such as when an image arrow points in the same direction as the object arrow.\n    \\end{itemize}\n    \\item \\textbf{Inverted} (image): An image that is oriented in the opposite direction relative to the object.\n    \\begin{itemize}\n        \\item Such as when an image arrow points in the opposite direction as the object arrow.\n    \\end{itemize}\n    \\item \\textbf{Spherical aberration}: The smearing out of the image \"point\" from a zero-dimensional point due to the approximations made in deriving the mirror equation.\n    \\item If you remove part of a spherical mirror, a full image is still formed, just a dimmer one. This is because light rays from any object point reflect off of \\emph{all} parts of the mirror to converge to the image point. However, without all of the mirror, fewer light rays will be reflected, but no paths will be entirely eliminated.\n    \\item Measure $s$ and $s'$ to where the mirror intersects the optic axis.\n    \\item \\textbf{Virtual focal point}: The focal point of a convex mirror, lying behind it.\n    \\item \"When the object distance $s$ is positive, a convex mirror \\emph{always} forms an erect, virtual, reduced, reversed image\" \\parencite[1120]{bib:YoungFreedman}.\n\\end{itemize}\n\n\n\n\n\\end{document}", "meta": {"hexsha": "ed5cb46002ec23acd018595709fa38866953e5b3", "size": 29237, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Notes/Chapter34/chapter34.tex", "max_stars_repo_name": "shadypuck/PHYS13300Notes", "max_stars_repo_head_hexsha": "61c7dcb457b6ce79feba5d9a46e991c88cdcde68", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Notes/Chapter34/chapter34.tex", "max_issues_repo_name": "shadypuck/PHYS13300Notes", "max_issues_repo_head_hexsha": "61c7dcb457b6ce79feba5d9a46e991c88cdcde68", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Notes/Chapter34/chapter34.tex", "max_forks_repo_name": "shadypuck/PHYS13300Notes", "max_forks_repo_head_hexsha": "61c7dcb457b6ce79feba5d9a46e991c88cdcde68", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 58.2410358566, "max_line_length": 341, "alphanum_fraction": 0.5991380785, "num_tokens": 9090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.3340176695579735}}
{"text": "\\chapter{DERIVATION OF THE $\\Upsilon$ FUNCTION}%\r\n\\label{appendixB}\r\n\r\n%\\clearpage %remove this command if your appendix doesn't start with a landscaped page!!!!!\r\n%\\thispagestyle{plain}\r\n%\\begin{landscape}\r\n%\\begin{figure}\r\n\r\n% \\begin{center}\r\n  %  \\includegraphics[width=6in]{LaTeX2e_logo.eps}\r\n   % \\caption{\\LaTeX 2\\ensuremath{\\epsilon.} logo}\\label{biglogo}\r\n  %\\end{center}\r\n%\\end{figure}\r\n%\\end{landscape}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n%ADD LABEL\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nWe first decompose the sum of the double exponential random variables.\r\n\r\nThe memoryless property of exponential random variables yields $(\\xi^{+}-\\xi^{-}|\\xi^{+}>\\xi^{-})=^{d}\\xi^{+}$ and $(\\xi^{+}-\\xi^{-}|\\xi^{+}<\\xi^{-})=^{d}-\\xi^{-}$, thus leading to the conclusion that\r\n\r\n\\begin{equation*}\r\n\\xi^{+}-\\xi^{-} =\\left\\{\r\n\\begin{array}{rl}\r\n\\xi^{+} & \\text{with probability $\\eta_{2}/(\\eta_{1}+\\eta_{2})$ }\\\\\r\n-\\xi^{-} & \\text{with probability $\\eta_{1}/(\\eta_{1}+\\eta_{2})$ }\r\n\\end{array}\\right\\}.\r\n\\end{equation*}\r\n\r\nbecause the probabilities of the events $\\xi^{+}>\\xi^{-}$ and $\\xi^{+}<\\xi^{-}$ are $\\eta_{2}/(\\eta_{1}+\\eta_{2})$ and $\\eta_{1}/(\\eta_{1}+\\eta_{2})$, respectively. The following proposition extends (B.1.)\r\n\r\nProposition B.1. For every $n\\geq1$, we have the following decomposition\r\n\r\n\\begin{equation*}\r\n\\sum_{i=1}^{n}Y_{i}=^{d}\\left\\{\r\n\\begin{array}{rl}\r\n\\sum_{i=1}^{k}\\xi_{i}^{+} & \\text{with probability $P_{n,k},k=1,2,...,n$ }\\\\\r\n-\\sum_{i=1}^{k}\\xi_{i}^{-} & \\text{with probability $Q_{n,k},k=1,2,...,n$ }\r\n\\end{array}\\right\\}.\r\n\\end{equation*}\r\n\r\nwhere $P_{n,k}$ and $Q_{n,k}$ are given by\r\n\r\n$$P_{n,k}=\\sum_{i=k}^{n-1}\\binom {n-k-1} {i-k}\\binom {n} {i}(\\frac{\\eta_{1}}{\\eta_{1}+\\eta_{2}})^{i-k}(\\frac{\\eta_{2}}{\\eta_{1}+\\eta_{2}})^{n-i}p^{i}q^{n-i}$$\r\n\r\n$$1\\leq k\\leq n-1$$\r\n\r\n$$Q_{n,k}=\\sum_{i=k}^{n-1}\\binom {n-k-1} {i-k}\\binom {n} {i}(\\frac{\\eta_{1}}{\\eta_{1}+\\eta_{2}})^{n-i}(\\frac{\\eta_{2}}{\\eta_{1}+\\eta_{2}})^{i-k}p^{n-i}q^{i}$$\r\n\r\n$$1\\leq k\\leq n-1, P_{n,n}=p^{n},Q_{n,n}=q^{n}$$\r\n\r\nand $\\binom{0}{0}$ is defined to be one. Hence $\\xi_{i}^{+}$ and $\\xi_{i}^{-}$ are i.i.d. exponential random variables with rates $\\eta_{1}$ and $\\eta_{2}$, respectively.\r\n\r\nAs a key step in deriving closed-form solutions for call and put options, this proposition indicates that the sum of the i.i.d. double exponential random variable can be written, in distribution, as a randomly mixed gamma random variable. To prove Proposition B.1, the following lemma is needed.\r\n\r\nLemma B.1.\r\n\r\n$$\\sum_{i=1}^{n}\\xi_{i}^{+}-\\sum_{i=1}^{n}\\xi_{i}^{-}$$\r\n\r\n\\begin{equation*}\r\n=^{d}\\left\\{\r\n\\begin{array}{rl}\r\n\\sum_{i=1}^{k}\\xi_{i} & \\text{with probability $\\binom {n-k+m-1} {m-1}(\\frac{\\eta_{1}}{\\eta_{1}+\\eta_{2}})^{n-k}(\\frac{\\eta_{2}}{\\eta_{1}+\\eta_{2}})^{m}, k=1,...,n$ }\\\\\r\n-\\sum_{i=1}^{l}\\xi_{i} & \\text{with probability $\\binom {n-l+m-1} {n-1}(\\frac{\\eta_{1}}{\\eta_{1}+\\eta_{2}})^{n}(\\frac{\\eta_{2}}{\\eta_{1}+\\eta_{2}})^{m-l}, l=1,...,m$ }\r\n\\end{array}\\right\\}.\r\n\\end{equation*}\r\n\r\nWe prove it by introducing the random variables $A(n,m) = \\sum_{i=1}^{n}\\xi_{i}-sum_{j=1}^{m}\\tilde{\\xi}_{j}$ Then\r\n\r\n\\begin{equation*}\r\nA(n,m) =^{d}\\left\\{\r\n\\begin{array}{rl}\r\nA(n-1,m-1)+\\xi^{+} & \\text{with probability $\\eta_{2}/(\\eta_{1}+\\eta_{2})$ }\\\\\r\nA(n-1,m-1)-\\xi^{-} & \\text{with probability $\\eta_{1}/(\\eta_{1}+\\eta_{2})$ }\r\n\\end{array}\\right\\}.\r\n\\end{equation*}\r\n\r\n\\begin{equation*}\r\n =^{d}\\left\\{\r\n\\begin{array}{rl}\r\nA(n,m-1) & \\text{with probability $\\eta_{2}/(\\eta_{1}+\\eta_{2})$ }\\\\\r\nA(n-1,m) & \\text{with probability $\\eta_{1}/(\\eta_{1}+\\eta_{2})$ }\r\n\\end{array}\\right\\}.\r\n\\end{equation*}\r\n\r\nvia B.1.. Now suppose horizontal axis that are representing the number of $\\{\\zeta_{i}^{+}\\}$ and vertical axis representing the number of $\\{\\zeta_{i}^{-}\\}$. Suppose we have a random walk on the integer lattice points. Starting from any point $(n,m),n,m \\geq 1$, the random walk goes either one step to the left with probability $\\eta_{1}/(\\eta_{1}+\\eta_{2})$ or one step down with probability $\\eta_{2}/(\\eta_{1}+\\eta_{2})$, and the random walks stops once it reaches the horizontal or vertical axis. For any path from (n,m) to (k,0) , $1 \\geq k \\geq n$, it must reach (k,1) first before it makes a final move to (k,0). Furthermore, all the paths going from (n,m) to (k,1) must have exactly n-k lefts and m-1 downs, whence the total number of such paths is $\\binom {n-k+m-1}{m-1}$. Similarly the total number of paths from (n,m) to (0,l) , $1 \\geq l \\geq m$, is $\\binom {n-l+m-1}{n-1}$. Thus\r\n\r\n\\begin{equation*}\r\nA(n,m)=^{d}\\left\\{\r\n\\begin{array}{rl}\r\n\\sum_{i=1}^{k}\\xi_{i} & \\text{with probability $\\binom {n-k+m-1} {m-1}(\\frac{\\eta_{1}}{\\eta_{1}+\\eta_{2}})^{n-k}(\\frac{\\eta_{2}}{\\eta_{1}+\\eta_{2}})^{m}, k=1,...,n$ }\\\\\r\n-\\sum_{i=1}^{l}\\xi_{i} & \\text{with probability $\\binom {n-l+m-1} {n-1}(\\frac{\\eta_{1}}{\\eta_{1}+\\eta_{2}})^{n}(\\frac{\\eta_{2}}{\\eta_{1}+\\eta_{2}})^{m-l}, l=1,...,m$ }\r\n\\end{array}\\right\\}.\r\n\\end{equation*}\r\n\r\nand the lemma is proven.\r\n\r\nNow, let's prove the proposition B.1. By the same analogy used in Lemma B.1 to compute probability $P_{n,m},1\\geq k \\geq n$, the probability weight assigned to $\\sum_{i=1}^{k}\\xi_{i}^{+}$ when we decompose $\\sum_{i=1}^{k}Y_{i}$, it is equivalent to consider the probability of the random walk ever reach (k,0) starting from the point (i,n-i) being $\\binom {n}{i}p^{i}q^{n-i}$. Note that the point (k,0) can only be reached from point (i,n-i) such that $k \\geq i \\geq n-1$, because the random walk can only go left or down, and stops once it reaches the horizontal axis. Therefore, for $1 \\geq k \\geq n-1$, (B3) leads to\r\n\r\n$$P_{n,k}=\\sum_{i=k}{n-1}P(going from (i,n-i) to (k,0)). P(starting from (i,n-i))$$\r\n\r\n$$=\\sum_{i=k}^{n-1}\\binom {i+(n-i)-k-1} {(n-i)-1}\\binom {n} {i}(\\frac{\\eta_{1}}{\\eta_{1}+\\eta_{2}})^{i-k}(\\frac{\\eta_{2}}{\\eta_{1}+\\eta_{2}})^{n-i}p^{i}q^{n-i}$$\r\n\r\n$$=\\sum_{i=k}^{n-1}\\binom {n-k-1} {n-i-1}\\binom {n} {i}(\\frac{\\eta_{1}}{\\eta_{1}+\\eta_{2}})^{i-k}(\\frac{\\eta_{2}}{\\eta_{1}+\\eta_{2}})^{n-i}p^{i}q^{n-i}$$\r\n\r\n$$=\\sum_{i=k}^{n-1}\\binom {n-k-1} {i-k}\\binom {n} {i}(\\frac{\\eta_{1}}{\\eta_{1}+\\eta_{2}})^{i-k}(\\frac{\\eta_{2}}{\\eta_{1}+\\eta_{2}})^{n-i}p^{i}q^{n-i}$$\r\n\r\nOf course $P_{n,n}=p^{n}$. Similarly, we can compute $Q_{n,k}$:\r\n\r\n$$Q_{n,k}=\\sum_{i=k}{n-1}P(going from (n-i,i) to (0,k)). P(starting from (n-i,i))$$\r\n\r\n$$=\\sum_{i=k}^{n-1}\\binom {i+(n-i)-k-1} {(n-i)-1}\\binom {n} {n-i}(\\frac{\\eta_{1}}{\\eta_{1}+\\eta_{2}})^{n-i}(\\frac{\\eta_{2}}{\\eta_{1}+\\eta_{2}})^{i-k}p^{n-i}q^{i}$$\r\n\r\n$$=\\sum_{i=k}^{n-1}\\binom {n-k-1} {i-k}\\binom {n} {i}(\\frac{\\eta_{1}}{\\eta_{1}+\\eta_{2}})^{n-i}(\\frac{\\eta_{2}}{\\eta_{1}+\\eta_{2}})^{i-k}p^{n-i}q^{i}$$\r\n\r\nwith $Q_{n,n}=q^{n}$. Incidentally, we have also got $\\sum{k=1}{n}(P_{n,k}+Q_{n,k})=1$\r\n\r\nB.2. Let's develop now the results on Hh functions.\r\nFirst of all, note that $Hh_{n}(x)\\rightarrow 0$, as $x \\rightarrow \\infty$, for $n \\geq -1$; and $Hh_{n}(x) \\rightarrow \\infty$, as $x \\rightarrow -\\infty$, for $n \\geq -1$; and $Hh_{0}(x)=\\sqrt{2\\pi} \\phi(-x) \\rightarrow \\sqrt{2\\pi}$, as $x \\rightarrow -\\infty$. Also, for every $n \\geq -1$, as $x \\rightarrow \\infty$,\r\n\r\n$$lim Hh_{n}(x)/\\{\\frac{1}{x^{n+1}}e^{-\\frac{x^{2}}{2}}\\}=1$$\r\n\r\nand as $x \\rightarrow \\infty$\r\n\r\n$$Hh_{n}(x)=O(|x|^{n})$$\r\n\r\nHere (B4) is clearly true for $n=-1$, while for $n \\geq 0$ note that as $x\\rightarrow _\\infty$,\r\n\r\n$$Hh_{n}(x)=\\frac{1}{n!}\\int_{x}{\\infty}(t-x)^{n}e^{-\\frac{t^{2}}{2}}dt$$\r\n\r\n$$\\leq \\frac{2^{n}}{n!}\\int_{-\\infty}^{\\infty}|t|^{n}e^{-t^{2}}{2}dt+\\frac{2^{n}}{n!}\\int{-\\infty}{\\infty}|x|^{n}e^{-t^{2}}{2}dt=O(|x|^{n})$$\r\n\r\nFor option pricing it is important to evaluate the integral $I_{n}(c;\\alpha;\\beta;\\delta)$,\r\n\r\n$$I_{n}(c;\\alpha;\\beta;\\delta)=\\int_{c}{\\infty}e^{\\alpha x}Hh_{n}(\\beta x-\\delta)dx, n\\geq 0$$\r\n\r\nfor arbitrary constants $\\alpha, c$ and $\\beta$.\r\n", "meta": {"hexsha": "ddc2b6e19b65abbeb2ed4a73a0818e94299c908d", "size": 7921, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "code/matlab/lidar/crown_segmentation/temp/proposal/appendix/appendixF.tex", "max_stars_repo_name": "mshahriarinia/neonDSR", "max_stars_repo_head_hexsha": "1fbb1938637cd3b2b510874b2062c66063e57ad2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-12-17T17:00:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-28T14:28:35.000Z", "max_issues_repo_path": "code/matlab/lidar/crown_segmentation/temp/proposal/appendix/appendixF.tex", "max_issues_repo_name": "mshahriarinia/neonDSR", "max_issues_repo_head_hexsha": "1fbb1938637cd3b2b510874b2062c66063e57ad2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/matlab/lidar/crown_segmentation/temp/proposal/appendix/appendixF.tex", "max_forks_repo_name": "mshahriarinia/neonDSR", "max_forks_repo_head_hexsha": "1fbb1938637cd3b2b510874b2062c66063e57ad2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-12-13T13:57:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T01:36:28.000Z", "avg_line_length": 55.7816901408, "max_line_length": 895, "alphanum_fraction": 0.5702562808, "num_tokens": 3193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.33401766605198013}}
{"text": "\\chapter{step} \\label{stepN}\n\n\\section{Introduction}\n\n\\txs{} provides commands for randomly stepping through a model; however, it may be possible to do this more efficiently when a model is in LPE form.\nThis hypothesis has been put to the test by developing dedicated stepper functionality.\n\nEarly results of the LPE stepper showed equal to worse performance.\nThe LPE stepper was therefore extended with a preparatory step in which `possible successors' are calculated.\nMaking use of the extra information, the LPE stepper frequently outperforms the original \\txs{} stepper.\n\n\\section{Formal background}\n\n\\subsection{Possible successors}\n\nConsider summands $s_\\alpha$ and $s_\\beta$, referencing their elements conform \\ref{summandelements}.\nSummand $s_\\beta$ is said to be a \\emph{possible successor} of $s_\\alpha$ if the following expression \\emph{could be} satisfiable:\n\\begin{align*}\ng_\\alpha \\land {g_\\beta}[v \\rightarrow q(v) \\;|\\; v \\in \\varsof{g_\\beta} \\setminus P][p \\rightarrow v_\\alpha(p) \\;|\\; p \\in P]\n\\end{align*}\n\nwhere $q(v)$ is a bijective function that relates variable $v$ to a fresh variable.\n\n\\section{Algorithm}\n\n\\subsection{Preparation}\n\nThe algorithm computes all possible successors for each summand.\n(In actuality, the algorithm can compute possible successors of a sequence of summands of arbitrarily chosen length $n \\geq 1$.\nUnsurprisingly, when choosing $n > 1$ cases in which the costs to compute possible successors are prohibitive are far from uncommon.)\n\n\\subsection{Step}\n\nLet $\\Sigma$ be a set of tuples $\\shPair{\\sigma}{h}$ in which $\\sigma$ is a model state and $h$ is the history of summands that led to $\\sigma$.\nInitially, $\\Sigma = \\{\\;\\shPair{\\sigma_0}{[\\;]}\\;\\}$ where $\\sigma_0$ is the initial state as defined by the LPE model.\n\n\\subsubsection{1. Compute \\istep{}-closure}\n\nLet $T$ be the set of all \\istep{} summands of the LPE.\nApply each $t \\in T$ to each $\\sigma \\in \\Sigma$.\nAny new state $\\sigma'$ that is produced by some $t \\in T$ is added to $\\Sigma$ as $\\shPair{\\sigma'}{[t]}$.\nThis is repeated until $\\Sigma$ no longer changes.\n\n\\subsubsection{2. Find an enabled summand}\n\nLet $\\overline{T}$ be the set of all non-\\istep{} summands of the LPE.\n\nConsider the summands in $\\overline{T}$ in a random order, and let the summand under consideration be $u$.\nDetermine whether there is a $\\shPair{\\sigma}{[t]} \\in \\Sigma$ so that $u$ is enabled when the current state is $\\sigma$.\nIf so, find a \\emph{random} variable-to-value mapping $C$ so that $g_u[\\; x_u(i) \\mapsto C(i) \\;|\\; i \\in [1,\\cdots{},m_u] \\;]$ holds when the current state is $\\sigma$.\nRemember $u$ and $C$ (in particular, add it to the random trace that is being constructed) and continue with the next part of the algorithm immediately.\n\nIf no $u$ and $C$ can be found, the algorithm reports a deadlock and terminates.\n\nIt is also possible that the maximum length of the trace has been reached, in which case the algorithm also terminates.\n\n\\subsubsection{3. Determine next states}\n\nIn this part of the algorithm, the new value of $\\Sigma$ is computed.\n\nFor each $\\shPair{\\sigma}{[t]} \\in \\Sigma$, look up the possible successors of $t$.\nFor each possible successor $p$ of $t$, check if the channel of $p$ is the same as the channel of $u$ (that is, if $c_{p} = c_{u}$), then check if $g_p[\\; x_p(i) \\mapsto C(i) \\;|\\; i \\in [1,\\cdots{},m_p] \\;]$ holds when the current state is $\\sigma$:\n\\begin{itemize}\n\\item If the equation holds, apply the summand $p$ to $\\sigma$ to find the next state $\\sigma'$.\nAdd $\\shPair{\\sigma'}{[p]}$ to the new value of $\\Sigma$.\n\\item If the equation does not hold, nothing is added to the new value of $\\Sigma$.\n\\end{itemize}\n\n\\clearpage\n\\section{Benchmark results}\n\nThe performance of the LPE stepper has been compared to the performance of the original stepper of \\txs{}.\nBecause the LPE stepper only works for LPEs, the performance of the original stepper has been measured for both unchanged input models and linearized input models.\n\nFigure~\\ref{steppers:fig} shows two bars per model: the blue bar is the time that the original stepper of \\txs{} required to generate a 100-step trace from the linearized input model as a fraction of $\\Delta t$, the time that the original stepper of \\txs{} required to generate a 100-step trace from the unchanged input model.\nSimilarly, the yellow bar is the time that the LPE stepper required to generate a 100-step trace from the linearized input model (obviously, this is a precondition on the input of the LPE stepper) as a fraction of $\\Delta t$.\nThe figure also includes the range of the standard deviation.\n\n\\begin{figure}[!ht]\n\\begin{center}\n\\includegraphics[width=1\\linewidth]{charts/steppers-comparison}\n\\caption{Relative performance of different steppers}\n\\label{steppers:fig}\n\\end{center}\n\\end{figure}\n\nAs can be seen in the figure, for 7 out of 14 models the deviation ranges of the measured times overlap, and so we cannot conclude a performance improvement.\nFor all other models, however, the LPE stepper actually outperforms the original stepper, even though the performance is only impressive for the Adder, Adder3, and ReadWrite models.\n\nThe Bakery model has a very large standard deviation.\nThis deviation results from the long preparatory step that the model requires -- it is quite a large model -- and from the way in which benchmark measurements were taken:\n\\begin{enumerate}\n\\item The LPE stepper was instructed to generate a 100-step trace.\nThe required time $\\Delta t _ {100}$ was measured.\n\\item The LPE stepper was instructed to generate a 0-step trace.\nThe required time $\\Delta t _ {0}$ was measured.\n\\item $\\Delta t$ was computed by subtracting $\\Delta t _ {0}$ from $\\Delta t _ {100}$.\n\\end{enumerate}\nNaturally, the impact of the deviation in $\\Delta t _ {0}$ becomes stronger as the value of $\\Delta t _ {0}$ increases relative to $\\Delta t _ {100} - \\Delta t _ {0}$.\n\n", "meta": {"hexsha": "518d2d8b4c3b73c8f0e4aab7dc4b72574095acc8", "size": 5891, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "sys/lpeops/tex/lpeopsDoc/stepN.tex", "max_stars_repo_name": "ikbendedjurre/TorXakis", "max_stars_repo_head_hexsha": "a791ce9960e88df576733404fe4d60114c35e50a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 44, "max_stars_repo_stars_event_min_datetime": "2017-06-09T08:17:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-08T02:17:01.000Z", "max_issues_repo_path": "sys/lpeops/tex/lpeopsDoc/stepN.tex", "max_issues_repo_name": "ikbendedjurre/TorXakis", "max_issues_repo_head_hexsha": "a791ce9960e88df576733404fe4d60114c35e50a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 746, "max_issues_repo_issues_event_min_datetime": "2017-06-13T07:36:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T19:14:31.000Z", "max_forks_repo_path": "sys/lpeops/tex/lpeopsDoc/stepN.tex", "max_forks_repo_name": "ikbendedjurre/txs-develop", "max_forks_repo_head_hexsha": "bc11f4b93a15e220bf6941d395d5b4cd361bfe74", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2017-11-16T11:33:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-26T16:33:36.000Z", "avg_line_length": 58.3267326733, "max_line_length": 326, "alphanum_fraction": 0.744355797, "num_tokens": 1546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3340176625459868}}
{"text": "%!TEX root = ../main.tex\n\\section{Checking the Productivity of Corecursive Functions}\n\\label{sec:productivity}\n\nBefore delving into a description of our proposal for a productivity checking algorithm for definitions with copatterns, we will discuss the properties of other approaches, and why they may or may not be desirable.\n\n\\subsection{Lazy Evaluation: The Haskell Approach}\nIt may be compelling to think that we can simply model coinductive data in the same way as it is done in Haskell, by evaluating all expressions lazily. Then any productivity algorithm would work for Haskell as well, making the result more generally applicable. The lazy evaluation approach, however, is insufficient in several aspects.\n\nFirst and foremost, if we insist on making no distinction between inductive and coinductive data in our type system (Haskell makes no distinction), subject reduction is lost in a dependently typed system\\,\\citep{Abel13Copatterns}. The problem lies in the fact that coinductive data is modeled as the \\emph{construction} of infinite trees, making dependent pattern matching possible on codata. Consider the type \\texttt{U} in Figure~\\ref{fig:subject_reduction_problem}, with inhabitant \\texttt{u}. Even though it should not hold, the equality \\texttt{u = C u} in the type of \\texttt{eqU} holds when we allow dependent pattern matching on \\texttt{x} in \\texttt{eq}, since it allows the type system to reduce \\texttt{x} to \\texttt{C y}. In this case the type of \\texttt{refl} in \\texttt{eq} becomes \\texttt{C y = force (C y)}, which should hold. However, if we replace the right-hand side of \\texttt{eqU} with \\texttt{refl}, a type error occurs since \\texttt{u} is not equal to \\texttt{C u}. Consequently, the type of \\texttt{eq} changes when we do dependent pattern matching on its input, \\texttt{x}, which means that subject reduction is lost. This problem is explained in greater detail by Abel et al.\\,\\citep{Abel13Copatterns}, and is also discussed in a correspondence initiated by Danielsson on the Agda mailing list\\,\\citep{OuryCounterexample}. Naturally, we want to preserve subject reduction in the Idris type system. When we are able to distinguish between inductive and coinductive data, one solution to this problem is to not allow dependent pattern matching on coinductive data. This approach, which is also implemented in Idris, is discussed in Section~\\ref{sec:copatterns_in_idris}.\n\n\\begin{figure}\n\\begin{alltt}\ndata U : Type where         -- No distinction between data and codata\n  C : U -> U\n\nfix : (a -> a) -> a\nfix f = f (fix f)\n\nu : U\nu = fix u\n\nforce : U -> U\nforce x = case x of\n            C y => C y\n\neq : (x : U) -> x = force x\neq x = case x of\n         C y => refl\n\neqU : u = C u\neqU = eq u\n\\end{alltt}\n\\caption{Oury's counterexample\\,\\citep{OuryCounterexample} in a dependently typed language with Haskell-like syntax. Here, \\texttt{=} denotes propositional equality, with the sole constructor \\texttt{refl}. Dependent pattern matching happens with \\texttt{case} expressions.}\n\\label{fig:subject_reduction_problem}\n\\end{figure}\n\nAnother argument against the Haskell approach is that the core type theory underlying Idris is intended to have the Church-Rosser property\\,\\citep{BradyIdrisImpl13}, meaning that distinct reduction strategies lead to the same normal form. Furthermore, the total part of Idris is intended to be strongly normalizing, such that it enjoys the \\emph{strong} Church-Rosser property\\,\\citep{Turner04totalfunctional}. This means that not only will every reduction strategy leading to a normal form lead to the same normal form, but \\emph{any} reduction strategy must lead to a normal form. In Haskell, many definitions will lead to a normal form under lazy evaluation, while eager evaluation would lead to infinite recursion. Therefore, exploiting lazy evaluation in the total part of Idris would mean that it would no longer have the strong Church-Rosser property.\n\n\\subsection{Productivity Checking with Sized Types}\nAs shown by Abel and Pientka\\,\\citep{Abel13Wellfounded}, verifying the productivity of coinductive definitions with copatterns is indeed possible using sized types. Thus, the main argument against using sized types is one of usability, from the point of view of the Idris user. Thibodeau\\,\\citep{Thibodeau11} emphasizes that size annotations generally make the code harder to read and seem unnecessary (see Section~\\ref{sec:related_work}). In our own experience, size annotations place quite a burden of bookkeeping upon the user, as they have a tendency to become a tool that is used to satisfy the productivity checker, instead of leading to clearer type specifications. Because totality is optional in Idris for definitions that to not appear in types (as opposed to in Agda, for instance), this means that in a practical programming setting, some users would most likely be inclined to switch off productivity checking for coinductive definitions, or refrain from using them entirely.\n\nThis argument is only valid as long as we have no way to fully reconstruct all size annotations. Once we do (if ever), the burden of sized types can be placed entirely upon the compiler. At such point, totality checking with sized types would become a practical approach.\n\n\\subsection{Guarded Corecursion}\n\\label{sec:guarded_cored}\nIn its original form presented by Coquand\\,\\citep{Coquand94} and Gim\\'{e}nez\\,\\citep{Gimenez95}, the guardedness condition is generally too restrictive, as discussed in Section~\\ref{sec:related_work}. The work done on the ESFP system by Telford and Turner\\,\\citep{Telford97ensuringstreams,Telford98ensuringthe} makes the guardedness criterion more generally applicable, even though some problems still remain, such as handling indirect application of corecursive functions. An example of this problem is the \\texttt{g} function in Figure~\\ref{fig:TelfordTurnerProblems}, the guardedness of which cannot be determined due to the indirect call to another function. In this case, this other function is the identity function, but the point is that the result of \\texttt{(fst~funPair)} could have been any function. The function \\texttt{f} is not considered guarded within their system because forward references may not be made to the rest of the process, i.e. the head of \\texttt{f} cannot refer to the tail of \\texttt{f}.\n\n\\begin{figure}\n\\begin{alltt}\n-- f = 1 :: 1 :: \\ldots                            -- g = 1 :: 1 :: \\ldots\nf = (head (tail f)) :: (1 :: f)                 g = 1 :: ((fst funPair) g)\n                                                where funPair = (id, id)\n\\end{alltt}\n\\caption{Two types of corecursive functions not deemed productive by the extended guardedness criterion by Telford and Turner\\,\\citep[Section~6.3]{Telford98ensuringthe}. Here, \\texttt{::} is the cons operator for a hypothetical definition of streams without copatterns, and \\texttt{id} is the identity function. The functions \\texttt{head} and \\texttt{tail} are defined by pattern matching.} \n\\label{fig:TelfordTurnerProblems}\n\\end{figure}\n\nAbel\\,\\citep{Abel99terminationchecking} argues that termination analysis should abstract from the syntactic structure of the program being analyzed to avoid making the outcome of the analysis susceptible to small changes in program structure. While this is true, non-syntactic checks can require the user to pay more attention to the productivity checker, which might not always be advantageous. \n\n\\paragraph{}\nWhat we ultimately seek is a productivity checking algorithm for definitions with copatterns that covers as many realistic cases as possible, without burdening the user too much. In the following, we will provide a detailed description of our proposal.\n%An explanation of our proposal for productivity checking in collaboration with size-change termination.\n% Why not guardedness?\n% Why not sized types? \n% Why not the haskell way?\n\\subsection{Proposed Solution}\nThe basic idea of our proposal is \\textit{time measurement}. We wish to always know how many observations we can safely make on a given recursive reference. To do so, we use time as an analogy. When defining what happens at a given time, we can only refer to what has happened earlier. Since anything we observe must exist before we can observe it, any observation on a coinductive instance happens after this instance is created. We will explain this using days as our time unit. To define what happens on any given day, we can only refer to what has happened on previous days. If we translate the days to numbers, where later days are given higher numbers, we can express this idea of only being able to reference back in time with an inequality.\n\nIf a given function \\texttt{f} ``is created'' on day $\\tau$, then the first observation on \\texttt{f} is takes place on day $\\tau+1$, the second observation on day $\\tau+2$ etc. If we wish to define the result of an observation on any given day $\\tau+n$ we can only refer to observations made on an earlier day $\\phi$. We know that $\\phi$ is an earlier day if $\\tau+n\\, \\textgreater \\,\\phi$ holds. Any observation that complies with this definition is said to be \\emph{time consistent}, as it makes no references to something that has not yet happened. If we think of observations as places in time, if we cannot refer to something that has not yet happened, we cannot refer to an observation that is unsafe to make. Therefore, any observation that is time consistent is also safe. As such, we can see time consistency as equivalent to productivity.\n\nIn Figure~\\ref{fig:zeros} we decorate a definition \\texttt{zeros} with \\emph{time measures}. Since \\texttt{zeros} is the starting point, we give it a base measure $\\tau$. Any \\texttt{head} or \\texttt{tail} observations happens one day later than \\texttt{zeros}, so they both get time measure $\\tau+1$. To determine if \\texttt{zeros} is productive, we examine the right hand sides of the observations. The \\texttt{head} observation is simple to establish, as there are no corecursive calls. Therefore it gets the time measure $stable$, because we assume that \\texttt{Z} is always known. We use this measure for any reference that is known not to be corecursive. The numeric value $stable$ can thus be thought of as negative infinity. In the \\texttt{tail} observation we have a corecursive reference to \\texttt{zeros}. This gets the time measure $\\tau$ which is the time at which \\texttt{zeros} is ``created''. To determine productivity, we must ensure that observations are only defined by what has already happened. Defining this notion as an inequality, we can see that \\texttt{zeros} is productive because in the \\texttt{head} case $\\tau+1\\,\\textgreater\\,stable$ holds, and in the \\texttt{tail} case $\\tau+1\\,\\textgreater\\,\\tau$ holds. Note that all of these annotations can be inferred.\n\n\\begin{figure}\n\\begin{tabular}{l c}\n\n\\begin{minipage}{3in}\n\\begin{Verbatim}[commandchars=\\\\\\{\\},codes={\\catcode`$=3\\catcode`_=8}]\nzeros : Stream Nat\nhead zeros = Z\ntail zeros = zeros\n\\end{Verbatim}\n\\end{minipage} &\n\\begin{minipage}{3in}\n\\begin{Verbatim}[commandchars=\\\\\\{\\},codes={\\catcode`$=3\\catcode`_=8}]\nzeros$_{\\tau}$ : Stream Nat\nhead$_{\\tau+1}$ zeros$_{\\tau}$ = Z$_{stable}$\ntail$_{\\tau+1}$ zeros$_{\\tau}$ = zeros$_{\\tau}$\n\\end{Verbatim}\n\\end{minipage}\n\n\\end{tabular}\n\\caption{An infinite stream of zeros. To the left is the implementation, and to the right is the implementation decorated with time measures.}\n\\label{fig:zeros}\n\\end{figure}\n\nIn Figure~\\ref{fig:zerosprime} a diverging implementation of \\texttt{zeros}, called \\texttt{zeros'}, is shown. To establish that \\texttt{zeros'} is not productive, we decorate the program in the same fashion as above. This time the recursive reference in the \\texttt{tail} case has time measure $\\tau+1$ rather than $\\tau$, because we make an observation on \\texttt{zeros'} on the right-hand side of the \\texttt{tail} observation. For this to be productive, $\\tau+1\\,\\textgreater\\,\\tau+1$ must hold, which it clearly does not. Therefore we can say that \\texttt{zeros'} is not productive, since the definition of \\texttt{tail zeros'} is not complete at the time when the \\texttt{tail} observation is made on \\texttt{zeros'} on the right-hand side.\n\n\\begin{figure}\n\\begin{tabular}{l c}\n\n\\begin{minipage}{3in}\n\\begin{Verbatim}[commandchars=\\\\\\{\\},codes={\\catcode`$=3\\catcode`_=8}]\nzeros' : Stream Nat\nhead zeros' = Z\ntail zeros' = tail zeros'\n\\end{Verbatim}\n\\end{minipage} &\n\\begin{minipage}{3in}\n\\begin{Verbatim}[commandchars=\\\\\\{\\},codes={\\catcode`$=3\\catcode`_=8}]\nzeros'$_{\\tau}$ : Stream Nat\nhead$_{\\tau+1}$ zeros'$_{\\tau}$ = Z$_{stable}$\ntail$_{\\tau+1}$ zeros'$_{\\tau}$ = tail$_{\\tau+1}$ zeros'$_{\\tau}$\n\\end{Verbatim}\n\\end{minipage}\n\n\\end{tabular}\n\\caption{A non-productive implementation of \\texttt{zeros}.}\n\\label{fig:zerosprime}\n\\end{figure}\n\n\\subsubsection{Coinductive Definitions with Coinductive Parameters}\n\nSometimes we want to write definitions that depend on other functions with coinductive parameters. When decorating \\texttt{nats} in Figure~\\ref{fig:nats_productivity}, we cannot give the right-hand side of the \\texttt{tail} observation an accurate time measure since we do not know what \\texttt{map} does to \\texttt{nats}. We must first analyze \\texttt{map} to see the effect it has on its coinductive argument.\n\n\\begin{figure}\n\\begin{Verbatim}[commandchars=\\\\\\{\\},codes={\\catcode`$=3\\catcode`_=8}]\nnats$_{\\tau}$ : Stream Nat\nhead$_{\\tau+1}$ nats$_{\\tau}$ = Z$_{stable}$\ntail$_{\\tau+1}$ nats$_{\\tau}$ = (map S nats)$_{?}$\n\\end{Verbatim}\n\\caption{A \\texttt{Stream} of all the natural numbers, annotated with time measures.}\n\\label{fig:nats_productivity}\n\\end{figure}\n\nWhen analysing \\texttt{map}, a new time measure is introduced for each coinductive argument to the function. This measure is not used for checking the productivity \\texttt{map} itself, but is used for callers of \\texttt{map} to see how many observations \\texttt{map} makes on a given argument. Consequently, in addition to checking the productivity of \\texttt{map}, we also create a \\textit{specification} for \\texttt{map} which other functions can use to determine whether a call to \\texttt{map} would lead to a productive definition. A specification can be saved in an internal hidden type for later use by the productivity checker.\n\n\\begin{figure}\n\\begin{Verbatim}[commandchars=\\\\\\{\\},codes={\\catcode`$=3\\catcode`_=8}]\nmap$_{\\phi, \\upsilon}$ : (a -> b) -> Stream a -> Stream b\nhead$_{\\phi+1}$ (map f s)$_{\\phi}$ = f (head$_{\\upsilon+1}$ s$_{\\upsilon}$)$_{stable}$\ntail$_{\\phi+1}$ (map f s)$_{\\phi}$ = map f (tail$_{\\upsilon+1}$ s$_{\\upsilon}$)$_{\\phi}$\n\\end{Verbatim}\n\\caption{The map function for Streams.}\n\\label{fig:map}\n\\end{figure}\n\nMaking the specification is fairly simple. Since we are interested in knowing how many new observations \\texttt{map} possibly makes on an argument, the greatest number of observations made on each coinductive argument must be identified. In the case of \\texttt{map}, the greatest number of observations made on the stream argument (which is given time measure $\\upsilon$) is $\\upsilon+1$, which tells us that \\texttt{map} performs at most one observation on this argument. This does not finish the specification, however. While it is true that \\texttt{map} does make one observation on its stream argument, it does not do so until \\texttt{map} itself is observed. This means that any reference to \\texttt{map} would need one more observation on its left-hand side to invoke the observations \\texttt{map} makes. So even though \\texttt{map} adds one observation, it does so one day later. This delay of the observation counteracts the observation map makes. We model this counteraction by subtracting one from the time measure given to $\\upsilon$ in the specification.\n\nThis gives us $\\upsilon+1-1$ or just $\\upsilon$, which means that according to its specification, \\texttt{map} does not perform any additional observations on its input. We can now complete the annotation of \\texttt{nats} from Figure~\\ref{fig:nats_productivity}. As the specification of \\texttt{map} tells us that any input remains unchanged, we know that the time measure of the call to \\texttt{map} with \\texttt{nats} as input in Figure~\\ref{fig:natsComplete} is $\\tau$. We can therefore conclude that \\texttt{nats} is productive, as $\\tau+1\\,\\textgreater\\,\\tau$.\n\n\\begin{figure}\n\\begin{Verbatim}[commandchars=\\\\\\{\\},codes={\\catcode`$=3\\catcode`_=8}]\nnats$_{\\tau}$ : Stream Nat\nhead$_{\\tau+1}$ nats$_{\\tau}$ = Z$_{stable}$\ntail$_{\\tau+1}$ nats$_{\\tau}$ = (map S nats$_{\\tau}$)$_{\\tau}$\n\\end{Verbatim}\n\\caption{A \\texttt{Stream} of all the natural numbers, fully annotated with time measures.}\n\\label{fig:natsComplete}\n\\end{figure}\n\n\\subsubsection{Mutual Recursion}\nFor checking the productivity of mutually recursive coinductive definitions, we assume that we know which definitions refer to each other. Similar to the previous example, a specification is made for each function that can then be used to check the productivity of the callers. These specifications do not specify what happens to the input, but what happens to a specific call. Consider the two mutually recursive definitions \\texttt{f} and \\texttt{g} in Figure~\\ref{fig:mutRec1}. For \\texttt{f} we define specification $\\tau_{g}$ saying what happens to the time measure $\\tau$ in \\texttt{g}, and vice versa we define $\\upsilon_{f}$ for \\texttt{g}. For the \\texttt{tail} case in \\texttt{f} to be productive we need that $\\tau+1\\,\\textgreater\\,\\tau_{g}$ and for \\texttt{g} we need $\\upsilon+1\\,\\textgreater\\,\\upsilon_{f}+1$ to hold.\n\n\\begin{figure}\n\\begin{Verbatim}[commandchars=\\\\\\{\\},codes={\\catcode`$=3\\catcode`_=8}]\nf$_{\\tau,\\upsilon_{f}}$ : Stream Nat\nhead$_{\\tau+1}$ f$_{\\tau}$ = Z$_{stable}$\ntail$_{\\tau+1}$ f$_{\\tau}$ = g$_{\\tau_{g}}$\n\ng$_{\\upsilon,\\tau_{g}}$  : Stream Nat\nhead$_{\\upsilon+1}$ g$_{\\upsilon}$ = Z$_{stable}$\ntail$_{\\upsilon+1}$ g$_{\\upsilon}$ = tail$_{\\upsilon_{f}+1}$ f$_{\\upsilon_{f}}$\n\\end{Verbatim}\n\\caption{Two mutually corecursive definitions.}\n\\label{fig:mutRec1}\n\\end{figure}\n\nCreating these specifications is again simple, and inferrable. To find $\\upsilon_{f}$ we examine the references to \\texttt{g} in \\texttt{f}. The \\texttt{tail} observation has one observation on the left-hand side and none on the right-hand side. For the same reason as with \\texttt{map}, we subtract one for the left-hand side observations and add one for the right-hand side observations. This means that $\\upsilon_{f} = \\upsilon - 1$. Using the same approach for finding $\\tau_{g}$ we get that $\\tau_{g} = \\tau$. We can now substitute these values into the inequalities from earlier and get that $\\tau+1\\,\\textgreater\\,\\tau$ and $\\upsilon+1\\,\\textgreater\\,\\upsilon - 1$. Therefore \\texttt{f} and \\texttt{g} are productive.\n\n\\subsubsection{Known Limitations}\nWe have discovered a few limitations to this approach. In this section we will present them and discuss possible solutions.\n\nOur approach does not solve the problems discussed in Section~\\ref{sec:guarded_cored} directly. The first is if an observation refers to something that is trivially productive, but under more observations. Consider the example in Figure~\\ref{fig:forwardRef}. This definition is productive, but will be discarded by our approach as it does not hold that $\\tau+1\\,\\textgreater\\,\\tau+2$. It is, however, easily solvable due to our use of copatterns. Since \\texttt{head tail h} is directly defined, \\texttt{head h} can be said to be productive if \\texttt{head tail h} is productive.\n\n\\begin{figure}\n\\begin{Verbatim}[commandchars=\\\\\\{\\},codes={\\catcode`$=3\\catcode`_=8}]\nh$_{\\tau}$ : Stream Nat\nhead$_{\\tau+1}$ h$_{\\tau}$         = head$_{\\tau+2}$ tail$_{\\tau+1}$ h$_{\\tau}$\nhead$_{\\tau+2}$ tail$_{\\tau+1}$ h$_{\\tau}$ = Z$_{stable}$\ntail$_{\\tau+2}$ tail$_{\\tau+1}$ h$_{\\tau}$ = tail$_{\\tau+1}$ h$_{\\tau}$\n\\end{Verbatim}\n\\caption{An example of a productive definition our productivity checking algorithm would discard.}\n\\label{fig:forwardRef}\n\\end{figure}\n\nAnother limitation is functions returning arbitrary functions. In Figure~\\ref{fig:funList}, we cannot give an accurate time measure to \\texttt{(funPair) i} because we do not know anything about what \\texttt{fst funPair} does to \\texttt{i}. A possible solution is estimating a worst case scenario for \\texttt{funPair}. This, however, involves a lot of unfolding, at the risk of making the productivity checker very slow, while still not providing a very accurate analysis. We have not been able to find a desirable solution to this problem.\n\n\\begin{figure}\n\\begin{Verbatim}[commandchars=\\\\\\{\\},codes={\\catcode`$=3\\catcode`_=8}]\ni$_{\\tau}$ : Stream Nat\nhead$_{\\tau+1}$ (i)$_{\\tau}$ = Z$_{\\tau-1}$\ntail$_{\\tau+1}$ (i)$_{\\tau}$ = (fst funPair) i$_{?}$\n\nfunPair : (Stream a, Stream a)\nfunPair = (id, id)\n\\end{Verbatim}\n\\caption{Another example of a productive definition discarded by our productivity checking algorithm.}\n\\label{fig:funList}\n\\end{figure}\n\n\\subsubsection{Possible Algorithm}\nWe are convinced that time consistency is determinable by a machine. All analysis is syntactical which means that the user of the language does not have to annotate anything. To support this claim, we have made a natural language description of a possible algorithm. \n\nA specification is considered a function from a time measure to a new time measure, reflecting the changes described by the specification. Note that destructors can be considered to be coinductive functions with a specification saying that one observation is made on its input, thus increasing the time by one. For ease of reading, we define the following function which will be referred to several times as \\textit{calculate}:\n\n\\paragraph{\nGiven a coinductive definition with time measure $\\phi$, if the definition is passed as an argument to any other coinductive definitions, apply the specifications of these definitions to $\\phi$ and return the result. If it is not passed to any other coinductive definitions, just return $\\phi$.}\n\\paragraph{f: Coinductive Definition}\n\\begin{enumerate}\n\\item Create a time measure $\\tau$ for the definition.\n\\item For each observation in the definition do:\n\\begin{enumerate}\n\\item Count the number of left-hand side destructors and add this number to $\\tau$. This is the time of this observation. \n\\item Find all corecursive references on the right-hand side. Calculate the time measure of all these references using \\textit{calculate}.\n\\item Find all non-corecursive references on the right-hand side. Assign them the time measure $stable$.\n\\item The time of the observation (from (a)) must be greater than the greatest time measure on the right-hand side.\n\\end{enumerate}\n\\item If 2.(d) holds for all observations, the definition is time consistent.\n\\end{enumerate}\n\n\\paragraph{g: Coinductive Definitions with Coinductive Parameters}\n\\begin{enumerate}\n\\item Check the productivity of the definition itself using $f$, ignoring the coinductive parameters.\n\\item For each input parameter create a time measure.\n\\item For each observation in the definition do:\n\\begin{enumerate}\n\\item Count the number of left-hand side destructors. This is the time offset.\n\\item For each reference to the coinductive input do:\n\\begin{enumerate}\n\\item Calculate the time measure of the reference using \\textit{calculate}.\n\\item Subtract the offset from the result.\n\\end{enumerate}\n\\item For each input, find the greatest time measure.\n\\end{enumerate}\n\\item The specification of the definition is made up of the greatest time measure for each coinductive parameter.\n\\end{enumerate}\n\\paragraph{h: Mutually Corecursive Definition}\n\\begin{enumerate}\n\\item For each mutually corecursive definition $k$ do:\n\\begin{enumerate}\n\\item Check the productivity of $k$ itself using $f$, ignoring the mutually corecursive references.\n\\item Create a time measure for every definition with which $k$ is mutually corecursive.\n\\item For each observation on $k$ with mutually corecursive references do:\n\\begin{enumerate}\n\\item Count the number of left-hand side destructors. This is the time offset.\n\\item Calculate the time measure of each reference using $calculate$.\n\\item Subtract the offset from these time measures.\n\\end{enumerate}\n\\item For each definition with which $k$ is mutually corecursive, find the greatest time measure. These are the local time measures of other definitions within $k$, indicating the effect $k$ has on these other definitions.\n\\item For each observation on $k$ with mutually corecursive references do:\n\\begin{enumerate}\n\\item Count the number of left-hand side destructors. This is the time of this observation.\n\\item Look up the time measure for $k$ in the specification for the function defining each mutually corecursive reference.\n\\item Calculate the time measures of the mutually corecursive references using $calculate$ with the time measure for $k$ as input in each case.\n\\item The time of the observation must be greater than the greatest time measure given on the right-hand side.\n\\end{enumerate}\n\\item If the condition in 1.e.iv. holds for all observations this definition is time consistent.\n\\end{enumerate}\n\\end{enumerate}\n", "meta": {"hexsha": "cc00eff60b3e2f23218436fc74d0f245d5c6ed28", "size": 25080, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/sections/productivity.tex", "max_stars_repo_name": "tdidriksen/copatterns", "max_stars_repo_head_hexsha": "7e12781ad0174a5f57bf57f6f1077e134b6de9dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-27T15:37:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-27T15:37:01.000Z", "max_issues_repo_path": "report/sections/productivity.tex", "max_issues_repo_name": "tdidriksen/copatterns", "max_issues_repo_head_hexsha": "7e12781ad0174a5f57bf57f6f1077e134b6de9dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/sections/productivity.tex", "max_forks_repo_name": "tdidriksen/copatterns", "max_forks_repo_head_hexsha": "7e12781ad0174a5f57bf57f6f1077e134b6de9dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 92.5461254613, "max_line_length": 1694, "alphanum_fraction": 0.7629186603, "num_tokens": 6415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.3340176555340001}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\marginpar{Thursday\\\\ 2021-2-11, \\\\ compiled \\\\ \\today}\n\n% We have seen that there are two possibilities: either the accretion flow reaches the surface, or a shock forms.\nIf we consider accretion onto a NS we must account for the fact that the \\(B\\) field shapes the trajectories of the particles, making them not straight lines anymore. \n\nThe typical stopping length is \\(y_0 \\approx \\rho \\lambda _s \\sim \\SI{50}{g cm^{-2}}\\) typically. \nThe magnetic field of a NS is typically strong enough to even curve the trajectories of protons, which become helixes. This means that \\(\\lambda _s\\) decreases: the distance travelled between interactions is shorter, therefore \\(y_0\\) also decreases, reaching \\(30 \\divisionsymbol \\SI{40}{g cm^{-2}}\\) typically. \n\nThe thing we want to calculate is the \\textbf{flux escaping the column}: how much energy per unit area and unit time is escaping? This will dictate the luminosity. \n\nThe column depth is defined as \n%\n\\begin{align}\ny(z) = \\int_{z}^{\\infty } \\rho (z' ) \\dd{z'} \\leq y_0 \n\\,,\n\\end{align}\n%\nwhere \\(z\\) is the vertical axis along the accretion column (which is parallel to the local normal to the surface). \n\nLet us also define \\(\\Gamma _{\\text{coul}}\\), the heat released per unit time and volume by Coulomb collisions. We assume that this is uniform in the stopping region --- it does not depend on \\(z\\) --- and that it is zero elsewhere: if we are in a steady state, in which the heat introduced by \\(\\Gamma _{\\text{coul}}\\) is balanced by radiative losses (mostly due free-free emission and Compton scattering of electrons), then the following holds:\n%\n\\begin{align}\n\\Gamma _{\\text{coul}} = \\begin{cases}\n    \\frac{L _{\\text{acc}} \\rho }{A y_0 } & y \\leq y_0   \\\\\n    0 & y > y_0 \n\\,,\n\\end{cases}\n\\end{align}\n%\nwhere, as usual, \\(L _{\\text{acc}} \\approx \\eta \\dot{M} c^2\\), while \\(A\\) is the cross-sectional area of the accretion region. Since \\(y_0 / \\rho = \\lambda _S\\), the expression just amounts to a normalized luminosity per unit volume.  \n\nWe should also consider magnetic effects on the cross-section: the main one is a resonance at the cyclotron energy \n%\n\\begin{align}\nE_c = \\hbar \\frac{e B}{m_e} \\approx \\frac{B}{\\SI{e12}{G}} \\times \\SI{11.6}{keV}\n\\,.\n\\end{align}\n\nIt is a fact that the stopping layer the optical depth is quite large,  --- this is mostly due to electron scattering, which dominates among the radiative processes. \nTherefore, we can use the diffusion approximation to relate the radiative flux to the radiative energy density \\(U_{\\text{rad}} = a T _{\\text{rad}}^{4}\\):\\footnote{We are not actually assuming that the radiation is distributed as a blackbody: we are using the relation \\(U _{\\text{rad}} = aT _{\\text{rad}}^{4}\\) as a \\emph{definition} for the parameter \\(T _{\\text{rad}}\\), which is the equivalent temperature that a blackbody spectrum with the same energy density would be described by. }\n%\n\\begin{align}\nF _{\\text{rad}} = - \\frac{c}{3} \\dv{U _{\\text{rad}}}{\\tau }\n\\,.\n\\end{align}\n\nSince scattering dominates, the differential optical depth element is \n%\n\\begin{align}\n\\dd{\\tau } = \\frac{\\sigma _T}{m_p} \\dd{y}\n\\,.\n\\end{align}\n\nIn the diffusion equation we can write a simple expression for the radiative flux at a height \\(y\\) if we assume that it is equal to all the heat released by collisions up to that height:\n%\n\\begin{align}\nF _{\\text{rad}} (y) = \\int_{y_0 }^{y} \\Gamma _{\\text{coul}} \\dd{z} \n= \\frac{L _{\\text{acc}} \\rho }{A y_0 } \\qty(y - y_0 )\n\\,,\n\\end{align}\n%\nfrom which we can integrate in order to calculate the energy density: expressing everything as a function of \\(y\\) we have\n%\n\\begin{align}\n- \\frac{c}{3} \\dv{U _{\\text{rad}}}{y } = F _{\\text{rad}} = \\frac{\\sigma _T}{m_p} \\frac{L _{\\text{acc}} \\rho }{A y_0 } \\qty(y - y_0 )\n\\,.\n\\end{align}\n\nThe flux changes linearly, so the energy density will change quadratically. \nOnce we compute \\(U _{\\text{rad}}\\) we can solve the energy equation --- Compton cooling depends on \\(U _{\\text{rad}}\\) --- and calculate the electron temperature \\(T_e\\), which in general will be different from the ``fictional'' \\(T _{\\text{rad}}\\). \n\nIn order to compute the pressure we make the assumption that the electrons form an ideal gas in \\emph{hydrostatic equilibrium}: then\n%\n\\begin{align}\nP(y) = \\frac{k_B \\rho T_e}{\\mu m_p} = \n\\begin{cases}\n    \\frac{GM}{R^2} y + \\frac{\\rho_0 v^2}{y_0 } y & 0 < y \\leq y_0  \\\\\n    \\frac{GM}{R^2} y + \\rho_0 v^2 & y > y_0 \n\\,.\n\\end{cases}\n\\end{align}\n\nThe term \\(\\rho_0 v^2 (y/y_0 )\\) describes the \\emph{ram pressure} of the gas.\n\n\\subsection{Shocks}\n\nIf the accretion rate is high enough (typically we need to require \\(\\dot{M} \\gtrsim \\SI{2e16}{g /s}\\)) then protons are stopped above the photosphere and a shock forms. \nThe flow is cool and supersonic above the shock; hot and subsonic below the shock. \n\nLet us start with a toy model for a 1D shock: we consider a fluid with a pressure \\(P\\), velocity \\(v\\) and density \\(\\rho \\) moving in one dimension, along the \\(x\\) axis. We assume that at \\(x = 0\\) there is a shock; we label quantities pertaining to \\(x < 0\\) with a ``1'', and ones for \\(x > 0\\) with a ``2''. \nThe continuity equation tells us \n%\n\\begin{align}\n\\dv{}{x} \\qty(\\rho v)\n= 0 \\implies \\rho_1 v_1 = \\rho_2 v_2 \n\\overset{\\text{def}}{=} J\n\\,.\n\\end{align}\n\nThe Euler equation tells us that \n%\n\\begin{align}\n\\rho v \\dv{v}{x} + \\dv{P}{x} = f_x \\implies \\dv{}{x} \\qty(P + \\rho v^2) = f_x\n\\marginnote{Using the continuity equation, \\(\\rho v \\partial v = \\partial (\\rho v^2) -v \\partial (\\rho v) = \\partial (\\rho v^2)\\).}\n\\,,\n\\end{align}\n%\nwhere \\(f_x\\) is the force per unit volume. \nThis equation can be integrated in a small region around the shock: \\([- \\dd{x}, \\dd{x}]\\). \nIn reality the shock is not infinitesimal, but it can be typically approximated as such since it is very small compared to other characteristic length scales. \nThe integral of \\(f_x\\) is of the order of \\(2 f_x \\dd{x}\\), which is vanishingly small:\\footnote{We make the assumption that \\(f_x\\) does not diverge, that is, we assume that there are no impulsive forces. } therefore, we find \n%\n\\begin{align}\nP_1 + \\rho_1 v_1^2 = P_2 + \\rho_2 v_2^2 \\overset{\\text{def}}{=} I\n\\,.\n\\end{align}\n\nThe energy equation, under the assumption that the shock be \\textbf{adiabatic} (no heat is conduced across it) reads, in terms of the internal energy \\(\\epsilon \\): \n%\n\\begin{align}\n\\dv{}{x} \\qty(v \\qty(\\frac{\\rho v^2}{2} + \\rho \\epsilon + P)) = f_x v\n\\,,\n\\end{align}\n%\nwhich can be simplified if we consider an ideal monoatomic gas: with these assumptions we can use the equations \\(\\rho \\epsilon = \\frac{3}{2} n k_B T\\) and \\(P = n k_B T = \\frac{2}{3} \\rho \\epsilon \\), therefore the energy equation becomes \n%\n\\begin{align}\n\\dv{}{x} \\qty[ \\rho v \\qty( \\frac{v^2}{2} + \\frac{5}{2} \\frac{P}{\\rho } )] &= f_x v  \\\\\n\\rho v \\dv{}{x} \\qty[ \\frac{v^2}{2} + \\frac{5}{2} \\frac{P}{\\rho }]&= f_x v \n\\marginnote{Continuity equation.}\n\\,.\n\\end{align}\n\nWe integrate this across the shock as well: this yields \n%\n\\begin{align}\n\\frac{1}{2} v_1^2 + \\frac{5}{2} P_1 =\n\\frac{1}{2} v_2^2 + \\frac{5}{2} P_2\n\\overset{\\text{def}}{=} E \n\\,.\n\\end{align}\n\nThese three conservation equations for \\(J\\), \\(I\\) and \\(E\\) are known as the \\textbf{Rankine-Hugoniot} equations. \n\nSince the flow is adiabatic we have the relation \\(P = K \\rho^{\\gamma }\\): then, the adiabatic sound speed is given by \n%\n\\begin{align}\nc_s^2 = \\eval{\\dv{P}{\\rho }}_{\\text{adiabatic}} = \\gamma K \\rho^{\\gamma -1} = \\frac{5}{3} \\frac{P}{\\rho }\n\\,.\n\\end{align}\n\nWe can get some interesting quantities in terms of the Rankine-Hugoniot invariants: the first is \n%\n\\begin{align}\n\\frac{I}{Jv} = \\frac{P}{\\rho v^2} + 1 = \\frac{3}{5 M^2} + 1 \n\\,,\n\\end{align}\n%\nwhere \\(M = v / c_s\\) is the Mach number of the flow. \n\nAlso, the energy invariant can be written as \n%\n\\begin{align}\nE &= \\frac{v^2}{2} + \\frac{5}{2} \\qty(\\frac{Iv}{J} - v^2)  \\\\\nv^2 - \\frac{5I}{4J} v + \\frac{E}{2} &= 0 \n\\,.\n\\end{align}\n\nThe two roots of this equation, \\(v_{1, 2}\\), correspond to the flow speed up- and downstream of the shock.\n\\todo[inline]{I believe this can be justified by saying that this might well not be the case and the up and downstream are both regulated by the same velocity, only then we would not have a shock but just a regular point in the flow.}\n\nThe sum of the two roots of a quadratic equation \\(\\alpha v^2 + \\beta v + \\gamma = 0 \\) is given by \\(v_1 + v_2 = - \\beta / 2 \\alpha \\), therefore \n%\n\\begin{align}\nv_1 + v_2 = \\frac{5I}{4J}\n\\,.\n\\end{align}\n\nDividing through by \\(v_1 \\) and using the relation for the Mach number we found before, we get \n%\n\\begin{align}\n1 + \\frac{v_2}{v_1 } = \\frac{5}{4} \\frac{I}{J v_1 }\n= \\frac{5}{4} \\qty( \\frac{3}{5 M_1^2}  + 1)\n\\,.\n\\end{align}\n\nIf we suppose that \\(x<0\\) is a hypersonic region, so that \\(M_1 \\gg 1\\) (we have a \\textbf{strong shock}), we can neglect the \\(M_1^{-2}\\) term and see that \n%\n\\begin{align}\n1 + \\frac{v_2}{v_1 } \\approx \\frac{5}{4} \\implies 4 v_2 = v_1 \n\\,.\n\\end{align}\n\nWith the continuity equation and the energy equation we can see that this also means \\(\\rho_2 = 4 \\rho_1 \\) and \\(P_2 = \\frac{3}{4} \\rho_1 v_1^2\\). \nThe temperature in the shock region can be calculated from the ideal gas law: \n%\n\\begin{align}\nT_2 = \\frac{\\mu m_p P_2 }{k_B \\rho_2 } = \\frac{3}{16} \\frac{\\mu m_p}{k_B} v_1^2\n\\,.\n\\end{align}\n\nIn the case of column accretion, typically the velocity will be of the order of the free-fall velocity: \\(v_1 \\sim \\sqrt{ 2GM / R}\\), and the temperature below the shock will then be of the order \n%\n\\begin{align}\nT_2 \\sim \\SI{4e11}{K} \\times \\qty( \\frac{M}{M_{\\odot}} ) \\qty( \\frac{R}{\\SI{e6}{cm}})^{-1}\n\\,.\n\\end{align}\n\nAn important fact to note is that the shock is collisionless, so the electron and proton temperatures are not equalized: because of this, in the previous expression we must replace \\(m_p\\) with \\(m_e\\) if we are looking for the electron temperature, and we find a value \\(\\sim 2000\\) times smaller.\nIn a collisionless shock, the mediators of the interaction are photons, as opposed to particle-particle collisions.\n\nWe expect to see very hard radiation coming from the protons in the accretion region as long as this region is optically thin; if it is thick and radiation pressure dominates over gas pressure the picture changes: in the latter case the electron temperature is even lower than what this model provides, and the radiation becomes near-thermal. \n\n\\end{document}\n", "meta": {"hexsha": "29493e3ba6410dd674e42076df443923f460800d", "size": 10432, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ap_third_semester/compact_objects/dec23.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "ap_third_semester/compact_objects/dec23.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ap_third_semester/compact_objects/dec23.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 47.8532110092, "max_line_length": 489, "alphanum_fraction": 0.6836656442, "num_tokens": 3365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6477982043529715, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.334017655534}}
{"text": "\\section{Helicity amplitudes}\n\\label{sect:helampconventions}\n\\index{helicity amplitudes}\n\nThis section will deal with some details related to helicity amplitudes\nand their relations to partial wave amplitudes. In particular \nthe sign conventions are described and\nthe relations between the Jackson~\\cite{Jack64} and the \nJackob-Wick~\\cite{Jaco59} conventions\nfor the helicity formalism is explained.\n\nThis section is not meant as a complete guide to the use of\nhelicity amplitudes. There are several references that gives a \ngood introduction to the use of helicity amplitudes for describing\nthe dynamics of particle decays. Richman~\\cite{Rich84} gives\na pedagogical introduction following the conventions of\nJacob and Wick~\\cite{Jaco59}. Jackson~\\cite{Jack64} uses a slightly\ndifferent choice of conventions. One of the main purposes of this section is\nto describe these conventions and establish a map between the two\nconventions. Both of these conventions are used in the literature\nand, unfortunately, it is not always clear which convention is used. \n\nThe origin of the choice of conventions comes from how the \nEuler angles are chosen. To make sure that there is no ambiguity\nabout definitions and conventions the next section provides definitions\nfor the terminology used. \n\n\\subsection{Preliminaries and definitions}\n\nA few definitions are stated explicitly here as to avoid\nconfusion about what conventions are used.\n\nFirst, the basis vectors $\\hat x$, $\\hat y$, and $\\hat z$ are\nsaid to form a right handed coordinate system if rotating the\n$\\hat x$-axis 90 degrees counter-clockwise, as seen from the positive\n$\\hat z$ directions, will take it to the direction of the $\\hat y$\ndirections. It is assumed that $\\hat x$, $\\hat y$, and $\\hat z$ are\nmutually orthogonal. If the coordinate system is not right handed it is \nleft handed -- there is no other alternative. In the discussion\nbelow all coordinate systems considered are right handed.\n\nThe Euler angles, $\\alpha$, $\\beta$, and $\\gamma$ defines a \nrotation $R(\\alpha,\\beta,\\gamma)$ by\n\\begin{equation}\nR(\\alpha,\\beta,\\gamma)\\equiv R_{z'}(\\gamma)R_{y'}(\\beta)R_{z}(\\alpha)\n\\end{equation}\nwhere this means that a rotation by $\\alpha$ is first performed around the \n$z$-axis. Then a rotation by $\\beta$ around the $y'$-axis is done. Where\nthe $y'$-axis is the new axis as obtained after the first rotation.\nLast the rotation around the new $z$-axis, $z'$, is performed by an\namount given by $\\gamma$. Note that these rotations are not according to\na fixed set of rotation axis. This is inconvenient as the rotation operators\nthat we have are with respect to a fixed coordinate system. However, \nthere is a simple way of rewriting the Euler rotation in terms of\nrotations around a fixed coordinate system,\n\\begin{equation}\nR(\\alpha,\\beta,\\gamma)=R_{z}(\\alpha)R_{y}(\\beta)R_{z}(\\gamma).\n\\end{equation}\nSee e.g. Sakurai~\\cite{Sakurai} page 171-174 for illustrations of the\nrotations.\n\nThe $D^{J}_{m,m'}(\\alpha,\\beta,\\gamma)$ functions are defined by\n\\begin{equation}\nD^{J}_{m,m'}(\\alpha,\\beta,\\gamma)\\equiv \n             \\langle Jm|R(\\alpha,\\beta,\\gamma)|Jm'\\rangle.\n\\end{equation}\nUsing $d^{J}_{m,m'}(\\beta)\\equiv \\langle Jm|e^{-i\\beta J_y}|Jm'\\rangle$\\$ we\ncan write\n\\begin{equation}\nD^{J}_{m,m'}(\\alpha,\\beta,\\gamma)=\n       e^{-im\\alpha}d^{J}_{m,m'}(\\beta)e^{-im'\\gamma}.\n\\end{equation}\n\n\\subsection{Plane wave states}\n\nThe state $\\Psi_{p\\lambda}$ denotes a state with momentum $p$\nalong the $z$-axis with helicity $\\lambda$. This state is obtained\nby applying a boost $L(p)$ along the $z$-axis to the state \n$|J=s\\quad m=\\lambda\\rangle$, where $|J m\\rangle$ are the \ncanonical angular momentum states. The total angular momentum,\n$s$, is suppressed in the notation below.\n\nFollowing Jacob and Wick~\\cite{Jaco59} we define the states $\\chi_{p\\lambda}$\nwhich have momentum $p$ along the negative $z$-direction\n\\begin{equation}\n\\chi_{p\\lambda}=(-1)^{s-\\lambda}e^{-i\\pi J_y}\\Psi_{p\\lambda}.\n\\end{equation}\n\nFirst we will verify that this state has the properties that\nwe expect; \n\n\\begin{eqnarray}\nJ_z\\chi_{p\\lambda} & = & J_z(-1)^{s-\\lambda}e^{-i\\pi J_y}\\Psi_{p\\lambda}\\nonumber\\\\\n                   & = & (-1)^{s-\\lambda}e^{-i\\pi J_y} e^{i\\pi J_y} \n                          J_z e^{-i\\pi J_y}\\Psi_{p\\lambda}\\nonumber\\\\\n                   & = & (-1){s-\\lambda}e^{-i\\pi J_y}(-1)J_z\\Psi_{p\\lambda}\\nonumber\\\\\n                   & = & -\\lambda \\chi_{p\\lambda}\n\\end{eqnarray}\nshows that the eigen value of $J_z$ is $-\\lambda$ as expected. Further, we look\nat the application of the lowering operator, $J_{-}=J_x-iJ_y$, on the \nstate $\\chi_{p\\lambda}$\n\\begin{eqnarray}\nJ_-\\chi_{p\\lambda} & = & (-1)^{s-\\lambda}(J_x-iJ_y)e^{-i\\pi J_y}\\Psi_{p\\lambda}\\nonumber\\\\\n                   & = & (-1)^{s-\\lambda}e^{-i\\pi J_y}e^{i\\pi J_y}(J_x-iJ_y)\n                                         e^{-i\\pi J_y}\\Psi_{p\\lambda}\\nonumber\\\\\n                   & = & (-1)^{s-\\lambda}e^{-i\\pi J_y}(-J_x-iJ_y)\\Psi_{p\\lambda}\\nonumber\\\\\n                   & = & -(-1)^{s-\\lambda}e^{-i\\pi J_y}J_+\\Psi_{p\\lambda}\\nonumber\\\\\n                   & = & -(-1)^{s-\\lambda}e^{-i\\pi J_y}\\sqrt{(s-\\lambda)(s+\\lambda+1)}\n                            \\Psi_{p\\lambda+1}\\nonumber\\\\\n\t           & = & \\sqrt{(s-\\lambda)(s+\\lambda+1)}(-1)^{s-(\\lambda+1)}\n                         e^{-i\\pi J_y}\\Psi_{p\\lambda+1}\n\\end{eqnarray}\nwhich shows that the application of $J_-$ on $\\Psi_{p\\lambda}$ behaves\nas expected for a particle with helicity $\\lambda$ along the \nnegative $z$-direction. Note in particular that the factor $(-1)^{\\lambda}$\nis important to ensure the right phase when applying the lowering\noperators. \nIn fact, the properties that we have demonstrated above almost shows\nthe following property. If $p=0$, i.e. the particle is at rest, then\n\\begin{equation}\n\\chi_{0\\lambda}=\\Psi_{0-\\lambda}.\n\\label{eq:statesame}\n\\end{equation}\nThe properties of the lowering\nand raising operators and $J_z$ that we have shown above shows that the\nstates $\\chi_{0\\lambda}$ and $\\Psi_{0-\\lambda}$ differs at most by a \nphase and that this phase is independent of $\\lambda$. However, it\nis easiest to show Eq.~\\ref{eq:statesame} using the Wigner \n$d$-functions\n\\begin{equation}\n\\chi_{0\\lambda}=(-1)^{s-\\lambda}e^{-i\\pi J_y}\\Psi_{0\\lambda}\n = (-1)^{s-\\lambda}\\sum_{\\lambda'}d^s_{\\lambda'\\lambda}(\\pi)\\Psi_{0\\lambda'}\n = \\Psi_{0-\\lambda}\n\\end{equation}\nsince\n\\begin{equation}\nd^s_{mm'}(\\pi)=(-1)^{s-\\lambda}\\delta_{m,-m'}.\n\\end{equation}\n\nAn alternative way to define the states $\\chi_{p\\lambda}$ is by\n\\begin{equation}\n\\chi_{p\\lambda}=(-i)^{2s}e^{-i\\pi J_x}\\Psi_{p\\lambda}.\n\\label{eq:newdef}\n\\end{equation}\nwe find that\n\\begin{equation}\n\\chi_{0\\lambda}=(-i)^{2s}e^{-i\\pi J_x}\\Psi_{0\\lambda}=\n(-i)^{2s}\\sum_{\\lambda'}\\tilde d^s_{\\lambda'\\lambda}(\\pi)\\Psi_{0\\lambda'}=\\Psi_{0-\\lambda}\n\\end{equation}\nwhere\n\\begin{equation}\n\\tilde d^s_{m'm}(\\theta)=\\langle j m'|e^{-i\\theta J_x}|j m\\rangle.\n\\end{equation}\nThe $\\tilde d$ function is similar to the standard Wigner $d$ function \nexcept that it refers to expectation values for rotations around the \n$x$-axis instead of the $y$-axis. An explicit formula for the \n$\\tilde d$ function is given by\n\\begin{eqnarray}\n\\tilde d^j_{m'm}(\\theta)& = & \\nonumber\n\\sum {\\sqrt{(j+m)!(j-m)!(j+m')!(j-m')!}\\over (m+m'+k)!(j-m'-k)!k!(j-m-k)!}\\times\\\\\n& &\\left(\\cos{\\theta\\over 2}\\right)^{m'+m+2k}\n\\left(-i\\sin{\\theta\\over 2}\\right)^{2j-2k-m'-m}\n\\end{eqnarray}\nfrom which it is easy to show that\n\\begin{equation}\n\\tilde d^j_{m'm}(\\pi)=(-1)^{2j}\\delta_{m',-m}\n\\end{equation}\n\nIt is straight forward to show that the application of the raising and\nlowering operators as well as the operators $J_z$ on the state defined\nby Eq.~\\ref{eq:newdef} is what is expected.\nNote in particular that there is no longer any need for phase factors\nto get the right phase on the different helicity states. This is\nparticularly useful because it allows us to simply interpret\nthe states $\\chi_{p\\lambda}$ in the rest frame of the particle with the\nmomentum $p$ along the negative $z$ direction. That is, the state\n$\\chi_{p\\lambda}$ is equal to $|J=s\\quad m=\\lambda\\rangle$ \nin a coordinate system that \nhas been rotated by $\\pi$ around the $x$ axis. This is very important\nbecause it tells us how to construct the coordinates systems in\nsequential decays when applying the helicity formalism, this will\nbe discussed further below.\n\nWe now define the two particle plane wave states when particle\nA is along the positive $z$-direction by\n\\begin{equation}\n|p\\lambda_{A}\\lambda_{B}\\rangle=\\Psi_{p\\lambda_{A}}\\chi_{p\\lambda_{B}}.\n\\end{equation}\nApplying $J_z$ to this state we find \n\\begin{equation}\nJ_z|p\\lambda_{A}\\lambda_{B}\\rangle=\n(\\lambda_A-\\lambda_B)|p\\lambda_{A}\\lambda_{B}\\rangle\n\\end{equation}\nStates where the relative momentum, $p$, is not along the $z$-axis are\nobtained by rotating the state $|p\\lambda_{A}\\lambda_{B}\\rangle$.\nLet $\\theta$ and $\\phi$ denote the polar coordinates for particle A, then\nthe we define the state $|p\\theta\\phi\\lambda_{A}\\lambda_{B}\\rangle$ by\n\\begin{eqnarray}\n|p\\theta\\phi\\lambda_{A}\\lambda_{B}\\rangle=R(\\alpha,\\beta,\\gamma)\n             |p\\lambda_{A}\\lambda_{B}\\rangle\n\\end{eqnarray}\nwhere $R(\\alpha,\\beta,\\gamma)$ is an Euler rotation. Here there is a \nchoice of conventions. Jackson~\\cite{Jack64} takes \n$\\alpha=\\phi$, $\\beta=\\theta$, and $\\gamma=0$ while Jacob \nand Wick~\\cite{Jaco59} uses $\\alpha=\\phi$, $\\beta=\\theta$, and $\\gamma=-\\phi$.\nThe choice of the angle $\\gamma$ is arbitrary but has to be used \nconsistently. \n\nWe have now defined the state $|p\\theta\\phi\\lambda_A\\lambda_B\\rangle$\nand explored its properties in some detail. This state is used as the\nfinal state in the two body decays in the helicity formalism. \n\nBefore we are ready to use these states we need to construct a set\nof states that are labeled by $p$, $\\lambda_A$, and $\\lambda_B$ and\nhave definite values of $J$ and $m$, i.e., are eigenstates of\n$J^2$ and $J_z$. That such states exists is obvious since $p$,\n$\\lambda_A$, and $\\lambda_B$ are invariant under rotations. We \ndenote these states by $|pJM\\lambda_A\\lambda_B\\rangle$. The relation\nbetween these states and the plane wave states created above is given by\n\\begin{equation}\n|pJM\\lambda_A\\lambda_B\\rangle=\\sqrt{{2J+1}\\over{ 4\\pi}}\n\\int_{d\\Omega}D^{*J}_{M\\lambda_A-\\lambda_B}(\\phi,\\theta,-\\phi)\n|p\\theta\\phi\\lambda_A\\lambda_B\\rangle.\n\\label{eq:planewaveexpansion}\n\\end{equation}\nNote that the states $|pJM\\lambda_A\\lambda_B\\rangle$ are independent \nof the choice of Euler angles.\n\n\n\\subsection{Helicity amplitudes}\n\nWe will now consider the decay $C\\rightarrow A+B$. The initial\nparticle, $C$, is assumed to be in the state $|J M\\rangle$ and the \nfinal state, $A+B$, is $|pJM\\lambda_A\\lambda_B\\rangle$. We will assume\nthat the interaction $U$ that causes this transition is invariant\nunder rotation, but is otherwise arbitrary. We which to evaluate\nthe matrix element \n\\begin{equation}\nM=\\langle pJM\\lambda_A\\lambda_B\\rangle | U | J M \\rangle.\n\\end{equation}\nTo do this we insert the identity written as\n\\begin{equation}\nI=\\sum_{p'J'M'\\lambda_A'\\lambda_B'}\n|p'J'M'\\lambda_A'\\lambda_B'\\rangle\\langle p'J'M'\\lambda_A'\\lambda_B'|\n\\end{equation}\nand use Eq.~\\ref{eq:planewaveexpansion}.\n\\begin{eqnarray}\nM & = & \\langle p\\theta\\phi \\lambda_A \\lambda_B | U | J M \\rangle\\nonumber \\\\\n  & = & \\sum_{p'J'M' \\lambda_A' \\lambda_B'}\n        \\langle p\\theta\\phi \\lambda_A \\lambda_B |\n        p'J'M'\\lambda_A'\\lambda_B'\\rangle\\langle p'J'M'\\lambda_A'\\lambda_B'|\n        U | J M \\rangle \\nonumber\\\\\n  & = & \\langle p\\theta\\phi \\lambda_A \\lambda_B |\n        pJM\\lambda_A\\lambda_B\\rangle\\langle pJM\\lambda_A\\lambda_B|\n        U | J M \\rangle \\nonumber\\\\\n  & = & \\sqrt{2J+1\\over 4\\pi}\\langle p\\theta\\phi \\lambda_A \\lambda_B |\n       \\int_{d\\Omega'}D^{*J}_{M,\\lambda_A-\\lambda_B}(\\phi',\\theta',-\\phi')\n       |p\\theta'\\phi'\\lambda_A\\lambda_B\\rangle\n       \\langle pJM\\lambda_A\\lambda_B|U | J M \\rangle\\nonumber \\\\\n  & = & \\sqrt{2J+1\\over 4\\pi}D^{*J}_{M,\\lambda_A-\\lambda_B}(\\phi,\\theta,-\\phi)\n        H_{\\lambda_A\\lambda_B}\n\\label{eq:helicityformula}\n\\end{eqnarray}\nwhere the helicity amplitudes are defined by \n\\begin{equation}\nH_{\\lambda_A\\lambda_B}=\\langle pJM\\lambda_A\\lambda_B|U | J M \\rangle. \n\\end{equation}\n\n\n\n\\subsection{Helicity amplitudes and sequential decays}\n\nThe previous section explained how the helicity formalism \nis used to calculate the amplitudes for a two body decay, $A\\rightarrow B+C$.\nIt is straight forward to now to use this in sequential decays.\nThe only thing that requires a it of care is the construction \nof the coordinate systems in which the decay angles are measured.\n\nTo explain how to use the helicity formalism in sequential decays \nwe will consider the decay chain $A\\rightarrow B+C$, $B\\rightarrow D+E$, \nand $C\\rightarrow F+G$. The initial particle, $A$, is in the \nstate $|J=J_A\\quad m=\\lambda_A\\rangle$. The amplitudes for\nthe decay $A\\rightarrow B+C$ is now given by\n\\begin{equation}\nA^{A\\rightarrow B+C}_{\\lambda_A\\lambda_B\\lambda_C}=\n\\sqrt{2J_A+1\\over 4\\pi} D^{*J_A}_{\\lambda_A,\\lambda_B-\\lambda_C}\n(\\phi_B,\\theta_B,-\\phi_B)H^{A}_{\\lambda_B\\lambda_C}\n\\end{equation}\nwhere $\\theta_B$ and $\\phi_B$ are the polar angles of particle\n$B$ in the rest frame of particle $A$. \n\nSimilarly, we can write the amplitude for the decay of particle $B$\n\\begin{equation}\nA^{B\\rightarrow D+E}_{\\lambda_B\\lambda_D\\lambda_E}=\n\\sqrt{2J_B+1\\over 4\\pi} D^{*J_B}_{\\lambda_B,\\lambda_D-\\lambda_E}\n(\\phi_D,\\theta_D,-\\phi_D)H^{B}_{\\lambda_D\\lambda_E}.\n\\end{equation}\nThe coordinate system in which the angles $\\theta_D$ and $\\phi_D$\nare measured is obtained by rotating the coordinate system of the\nparent particle, $A$, using the same Euler angles as was used\nwhen calculating the amplitude for the decay of particle $A$.\nThis means that the coordinate system for particle $B$ is obtained\nby doing the rotation $R(\\phi_B,\\theta_B,\\phi_B)$ of the \ncoordinate system of particle $A$.\n\nIn the same way we obtain the amplitude for the decay of particle\n$C$,\n\\begin{equation}\nA^{C\\rightarrow F+G}_{\\lambda_C\\lambda_F\\lambda_G}=\n\\sqrt{2J_C+1\\over 4\\pi} D^{*J_C}_{\\lambda_C,\\lambda_F-\\lambda_G}\n(\\phi_F,\\theta_F,-\\phi_F)H^{C}_{\\lambda_F\\lambda_G}.\n\\end{equation}\nAs discussed above the coordinate system for the second particle,\nhere particle $C$ in the decay of particle $A$, is obtained by rotating\nthe coordinates system of the first particle, $B$, by $\\pi$ around\nits $x$ axis. I.e. the $x$-axis of particles $B$ and $C$ frames are\nparallel. \n\n\\subsubsection{Jackson convention}\n\nIn the Jackson convention the Euler rotation is taken to be\n$R(\\phi,\\theta,0)$ where the angles $(\\theta,\\phi)$ are the \npolar coordinates for $\\vec p$. This is a \nrotation first by $\\phi$ around the \n$z$-axis and then a rotation by $\\theta$ around the new $y$-axis.\nThe new $y$-axis is in the direction of $z\\times \\vec p$ and \nthe new $x$-axis is therefore in the direction $(z\\times \\vec p)\\times \\vec p$.\n\nThis is a simple geometrical construction that allows the construction \nof the coordinate system used with the Jackson convention for the\nEuler rotations.\n\n\\subsubsection{Jacob-Wick convention}\n\nThe coordinate system used in the Jacob-Wick convention is obtained by\nperforming an additional rotation of $-\\phi$ around the new $z$-axis\nas obtained in the Jackson conventions. \n\nIn the sense that there is a simple geometrical construction for the \ncoordinate system in the Jackson convention if might be argued that\nthis convention is somewhat simpler to use. \n\n%Consider the decay $A\\rightarrow BC$. The particle $A$ is\n%described by the state $|J,m_z=\\lambda_A\\rangle$ in the \n%coordinate system $x$, $y$, and $z$. As conventional, the \n%$z$ axis has been chosen as the quantization axis.\n%\n%\\begin{figure}\n%\\begin{center}\n%\\psfig{figure=helamp.eps,height=2.5in}\n%\\caption{The state of the initial particle, A, with total angular\n%momentm $J$ and spin projection $\\lambda_A=m_z$ along the\n%$z$-axis is labeled by $|J,m_z=\\lambda_A\\rangle$ in the \n%coordinate system shown in the figure. The decay products, B and C,\n%are back to back in the rest frame of particle A and the\n%angles $(\\theta_A,\\phi_A)$ and $(\\pi-\\theta_A,\\pi+\\phi_A)$\n%gives the polar coordinates for B and C respectively. \n%\\label{fig:helamp}}\n%\\end{center}\n%\\end{figure}\n%\n%Particle $B$, produced in the decay, will have a direction\n%which will be labeled $\\hat p$. The polar coordinates for \n%this direction, as measured in $A$'s coordinate system will\n%be labeled $\\theta_A$ and $\\phi_A$, see Figure~\\ref{fig:helamp}. \n%To write down the\n%amplitude for this decay a choice of Euler angles has to be\n%made that rotates the original $z$ axis to the directions $\\hat p$.\n%This can be accomplished by chosing $\\alpha=\\phi_A$ and\n%$\\beta=\\theta_A$. However, the azimuthal angle $\\gamma$ around \n%the new $z$ axis, $z'$, is arbitrary. This is the source \n%of conventions for the helicity formalism. The two common\n%conventions are the Jackson convention which takes $\\gamma=0$\n%and the Jacob-Wick convention which takes $\\gamma=-\\phi_A$.\n%\n%Given the choice of the Euler angels, $\\alpha$, $\\beta$, and $\\gamma$\n%the amplitude for the decay can be written as\n%\\begin{eqnarray}\n%A_{\\lambda_A\\lambda_B\\lambda_C}&=&\n%\\sqrt{2J+1 \\over 4\\pi}H_{\\lambda_B\\lambda_C}\n%D^{J*}_{\\lambda_A,\\lambda_B-\\lambda_C}(\\alpha,\\beta,\\gamma)\\nonumber\\\\\n%&=&\\sqrt{2J+1 \\over 4\\pi}H_{\\lambda_B\\lambda_C}\n%e^{i\\lambda_A\\alpha+i(\\lambda_B-\\lambda_C)\\gamma}\n%d^{J}_{\\lambda_A,\\lambda_B-\\lambda_C}(\\beta)\\label{eq:helamp}\n%\\end{eqnarray}\n%Using the explicit choices for the Euler angles according to the \n%conventions we obtain the amplitudes according to the two\n%different conventions\n%\\begin{eqnarray}\n%A^{\\rm Jack}_{\\lambda_A\\lambda_B\\lambda_C}&=&\n%\\sqrt{2J+1 \\over 4\\pi}H^{\\rm Jack}_{\\lambda_B\\lambda_C}\n%e^{i\\lambda_A\\phi_A}\n%d^{J}_{\\lambda_A,\\lambda_B-\\lambda_C}(\\beta) \\label{eq:helampjackson}\\\\\n%A^{\\rm JW}_{\\lambda_A\\lambda_B\\lambda_C}&=&\n%\\sqrt{2J+1 \\over 4\\pi}H^{\\rm JW}_{\\lambda_B\\lambda_C}\n%e^{i\\phi_A(\\lambda_A-(\\lambda_B-\\lambda_C))}\n%d^{J}_{\\lambda_A,\\lambda_B-\\lambda_C}(\\beta)\\label{eq:helampJacobwick}\n%\\end{eqnarray}\n%Since both of these amplitudes describe the same physics\n%process it is tempting to equate the two amplitudes and \n%determine the relation between $H^{Jack}_{\\lambda_B\\lambda_C}$\n%and $H^{JW}_{\\lambda_B\\lambda_C}$. But this in not correct\n%since, they don't in fact describe the same system! This is\n%due to different phases that has been picked up by different\n%rotations in the two conventions.\n%\n%The Euler angles describes how the coordinate system that particle\n%A is at ret in is related to coordinate systems for the \n%particles B and C. To derive the relation between the Jackson\n%and Jacob-Wick conventions it is sufficient to study the\n%simple case of $\\theta_A=\\phi_A=0$. First we consider the\n%Jackson convention. For particle B the Euler angles will\n%be $\\alpha=0$, $\\beta=0$, and $\\gamma=0$. This means that\n%the cordinate system in the rest frame of particle B has\n%$z_B$ parallel to $z$ and that $x_B$ and $y_B$ are also\n%parallel to the orixinal $x$ and $y$ axis. However, for \n%particle B the angles are $\\alpha=\\pi$, $\\beta=\\pi$, and $\\gamma=0$..\n%This means that the new $z$-axis, $z_C$ is in the direction oposite\n%to the original $z$ axis. The new $x$-axis, $x_C$ is parallel to the \n%old and the new $y$ axis, $y_C$, is in the oposite direction\n%to the old $y$-axis. This is illustrated in \n%Figure~\\ref{fig:helampjackson}.\n%\n%\\begin{figure}\n%\\begin{center}\n%\\psfig{figure=helampjackson.eps,height=1.5in}\n%\\caption{The coordinate systems in the Jackson convention for the\n%case of $\\theta_A=\\phi_A=0$.\n%\\label{fig:helampjackson}}\n%\\end{center}\n%\\end{figure}\n%\n%Next consider the Jacob-Wick convention. Here the difference it that\n%$\\gamma$ is taken to $-\\alpha$. This will not affect the coordinate system for\n%particle B since $\\alpha=0$. However, for particle C $\\alpha=\\pi$\n%so here there is an additional rotation of $\\pi$ around the new \n%$z$ axis. This means that the new $y$-axis $y_C$ is parallel to the\n%old $y$ axis, and that $x_C$ is anti-parallel to original $x$\n%axis, see Figure~\\ref{fig:helampJacobwick}. \n%\n%\\begin{figure}\n%\\begin{center}\n%\\psfig{figure=helampjacobwick.eps,height=1.5in}\n%\\caption{The coordinate systems in the Jacob-Wick convention for the\n%case of $\\theta_A=\\phi_A=0$.\n%\\label{fig:helampJacobwick}}\n%\\end{center}\n%\\end{figure}\n%\n%Since the coordinate systems for the particles in the \n%final states are not the same in the Jackson and the Jacob-Wick\n%convention it is clear that the amplitudes in \n%Eq.~\\ref{eq:helampjackson} and Eq.~\\ref{eq:helampJacobwick}\n%don't describe the same reaction. But it is straight\n%forward to relate the to conventions. In fact, all we have to do\n%to compare the two conventions is to rotate particle C by \n%an angle of $\\pi$ around the $x_C$ axis. This rotation simply\n%picks up a phase of $e^{i\\pi\\lambda_C}$ which allows us to relate \n%the helicity ampitudes of the Jackson and the Jacob-Wick conventions \n%according to\n%\\begin{equation}\n%H^{\\rm Jack}_{\\lambda_B\\lambda_C}=e^{i\\pi\\lambda_C}H^{\\rm JW}_{\\lambda_B\\lambda_C}.\n%\\end{equation}\n%This shows that there are phase differences between the two conventions.\n%Note that this phase difference is easily observable in decays. E.g.\n%in the decay of a scalar to two vector particles where each of the\n%vectors decays to a pair of scalars this phase difference leads\n%to angular distributions that has the wrong sign of the angle\n%$\\chi$\\footnote{$\\chi$ is the azimuthal angle between the decay planes \n%of the two vector mesons.}  \n%if the phases are picked according to the wrong convention. \n%\n%Also care has to be taken when converting from the helicty\n%basis to the partial wave basis using the Jacob Wick transformation.\n%If the helicity ampitudes are given in the Jackson convention\n%the Jacob Wick formula needs to be modified with the\n%appropriate phases. (Actually, I still have to convince myself that\n%the Jacob Wick transformation is correct for the Jacob-Wick convention\n%for helicity amplitudes.)\n%\n%Now consider the case of non zero angles $\\theta_A$ and $\\phi_A$ for\n%the direction, $\\hat p$, of particle B. With a little thought\n%it is easy to convince oneself that the direction of the $y_B$ is\n%along $z\\times\\hat p$ an consequently that the direction of \n%$y_B$ is $(z\\times\\hat p)\\times \\hat p$. Now applying this to \n%particle C which is in the direction of $-\\hat p$ we find that \n%$x_C$ is parallel to $x_B$. This is just in agreement with what we\n%saw in the special case studied above. \n%\n%In the Jacob-Wick convention an additional rotation of $-\\phi_A$\n%is applied around the $z_B$ as comapred to the Jackson conventions.\n%For particle C this rotation is $-\\pi-\\phi_A$ around the $x_C$\n%axis. This gives an relative rotation of $\\pi$ as compared to the\n%Jackson convention, which shows that $y_B$ and $y_C$ are \n%parallel. Again this is consistent with the special case studied\n%above.\n%\n%It is now simple to explain in words exactly what the helicity amplitude\n%$A_{\\lambda_A\\lambda_B\\lambda_C}$ means. (Note that we have suppresed\n%the dependence on the Euler angles to simplify the notation.)\n%Intuitively it is simply the amplitude for a state with spin\n%projection $\\lambda_A$ along the $z$ axis to decay to two \n%particles with helicity $\\lambda_B$ and $\\lambda_C$ respectively.\n%As we have noticed above this leaves important phases\n%unspecified. But it is easy to specify these phase by noting that\n%state of the final state particle is nothing but the canonical\n%state $|J_B,m_z=\\lambda_B\\rangle$ and $|J_C,m_z=\\lambda_C\\rangle$\n%repectively for particle B and C. These states are defined in the \n%local coordinate system as specified by the Euler angels.\n%\n%\\subsection{Example.}\n%\n%The have a concrete example to discuss, the decay \n%$B\\rightarrow D^{*+}D^{*-}$ with $D^{*+}\\rightarrow D^0\\pi^+$ and\n%$D^{*-}\\rightarrow \\bar D^0\\pi^-$ is considered.\n%\n%First we discuss how the coordinate systems are set up in the\n%two different conventions. This is shown in \n%figures~\\ref{fig:jackson} and~\\ref{fig:jacobwick}.\n%In both conventions the z axis of the coordinate system that \n%describes the decay of the $D^*$'s is along the direction of\n%the flight of the $D^*$. But in the Jacob-Wick convention the\n%direction of the y axises are parallel while in the Jackson convention the\n%direction of the x axises are parallel. \n%\n%\\begin{figure}\n%\\begin{center}\n%\\psfig{figure=jackson.eps,height=2.0in}\n%\\caption{The coordinate systems in the Jackson convention. The two\n%x axises are parallel.\n%\\label{fig:jackson}}\n%\\end{center}\n%\\end{figure}\n%\n%\\begin{figure}\n%\\begin{center}\n%\\psfig{figure=jacobwick.eps,height=2.0in}\n%\\caption{The coordinate systems in the Jacob-Wick convention. The two\n%y axises are parallel.\n%\\label{fig:jacobwick}}\n%\\end{center}\n%\\end{figure}\n\n\n\\subsection{Explicit representations of SU(2)}\n\nThis section describes the explicit representations of SU(2) that\nare used in the generator. As usual $\\hbar=1$.\n\n\\subsubsection{$J=1/2$}\n\n\\begin{equation}\nS_n={1\\over 2}\\gamma_0\\gamma_5 n\\!\\!\\!/.\n\\end{equation}\n\n\\subsubsection{$J=1$}\n\nWe will consider the representation of spin 1. \n\\begin{equation}\nJ_x=\\left[\\begin{array}{rrr}\n          0 & 0 & 0  \\\\\n          0 & 0 &-i  \\\\\n          0 & i & 0  \\\\\n          \\end{array}\\right],\\quad\nJ_y=\\left[\\begin{array}{rrr}\n          0 & 0 & i  \\\\\n          0 & 0 & 0  \\\\\n          -i& 0 & 0  \\\\\n          \\end{array}\\right],\\quad\nJ_z=\\left[\\begin{array}{rrr}\n          0 &-i & 0  \\\\\n          i & 0 & 0  \\\\\n          0 & 0 & 0  \\\\\n          \\end{array}\\right]\n\\end{equation}\n \nFrom these explicit representations it is trivial to show that they\nobey the standard commutation relations, e.g.,\n\\begin{equation}\n[J_x,J_y]=iJ_z\n\\end{equation}\nFurther we find, as expected, that\n\\begin{equation}\nJ^2=J_x^2+J_y^2+J_z^2=2I\n\\end{equation}\nsuch that $J^2=j(j+1)$ which shows that this in fact is a \nrepresentation of spin 1. The raising and lowering operators\nare as usual given by\n\n\\begin{equation}\nJ_+=J_x+iJ_y=\\left[\\begin{array}{rrr}\n          0 & 0 &-1  \\\\\n          0 & 0 &-i  \\\\\n          1 & i & 0  \\\\\n          \\end{array}\\right],\\quad\nJ_-=J_x-iJ_y\\left[\\begin{array}{rrr}\n          0 & 0 & 1  \\\\\n          0 & 0 &-i  \\\\\n          -1& i & 0  \\\\\n          \\end{array}\\right]\n\\end{equation}\nIt is also convenient to evaluate the expression for a finite rotation\n\\begin{equation}\nR_z(\\theta)=e^{-i\\theta J_z}=\\left[\\begin{array}{ccc}\n\t\\cos\\theta & -\\sin\\theta & 0 \\\\\n\t\\sin\\theta &  \\cos\\theta & 0 \\\\\n\t 0         &  0          & 1 \\\\\n\t\\end{array}\\right].\n\\end{equation}\nOf course we could have guessed the form of $R_z(\\theta)$, but an\nexplicit evaluation of $e^{-i\\theta J_z}$ is possible through\ndirect evaluation of the series expansion, but is more elegantly \ndone using Cayley-Hamilton's theorem.\\footnote{Cayley-Hamilton's \ntheorem states that if $P_A(\\lambda)=det(\\lambda I-A)$ then $P_A(A)=0$\nfor any symmetric matrix $A$. This means that if $A$ has dimension\n$n$ then $A^k$ can be written as a linear combination of $A^i$ for\n$i<n$. In particular it can be shown that $f(A)=q(A)$ where $q$\nis a polynomial of degree $<n$. The polynomial $q(A)$ is defined\nby  \n\\begin{equation}\n{d^jf\\over dz^j}(\\lambda_k)={d^jq\\over dz^j}(\\lambda_k)\n\\end{equation}\nwhere $\\lambda_k$ are the eigen values of $A$, with multiplicity\n$n_k$ and $j=0..n_k-1$.\n}\n\nThe states\n\\begin{equation}\n\\epsilon_+={1\\over\\sqrt{2}}\\left[\\begin{array}{r}\n          -1  \\\\\n          -i  \\\\\n          0  \\\\\n          \\end{array}\\right],\\quad\n\\epsilon_0=\\left[\\begin{array}{r}\n          0  \\\\\n          0  \\\\\n          1  \\\\\n          \\end{array}\\right],\\quad\n\\epsilon_-={1\\over\\sqrt{2}}\\left[\\begin{array}{r}\n          1  \\\\\n          -i  \\\\\n          0  \\\\\n          \\end{array}\\right]\n\\label{eq:spinonestates}\n\\end{equation}\n\nare easily seen to satisfy \n\\begin{equation}\nJ_z\\epsilon_{\\lambda}=\\lambda\\epsilon_{\\lambda}\n\\end{equation}\nand therefore form a helicity eigenstate basis for a particle\nwith $J=1$ moving in the direction of the positive $z$-axis.\n\n\\subsection{Projections of helicity amplitudes}\n\nThis section shows how the helicity amplitudes are related to the\ninvariant amplitudes. Consider the decay of a scalar to two\nvector particles. Let the final states of the two vector particles\nbe denoted by $\\epsilon^1_{s_1}$ and $\\epsilon^2_{s_2}$ and $\\vec p$\nbe the relative momentum of the two particles in the parents\nrest frame. The amplitude for this process is then written as\n\\begin{equation}\nA_{s_1s_2}=\\epsilon^{1*}_{is_1}\\epsilon^{2*}_{js_2}M_{ij}(\\vec p)\n\\end{equation}\nwhere $M_{ij}(p)$ is a rank 2 tensor as a function of the available\nmomenta in the process, i.e., a function of $\\vec p$. The most\ngeneral form of M is given by\n\\begin{equation}\nM_{ij}=a\\delta_{ij}+b\\epsilon_{ijk}p_k+cp_ip_j.\n\\end{equation}\nThe coefficients $a$, $b$, and $c$ are the invariant amplitudes, we \nwand to relate them to helicity amplitudes. First we note that there\nare three invariant amplitudes, this is the same as the number of \nhelicity amplitudes. \n\nFrom Eq.~\\ref{eq:helicityformula} the amplitude is given by\n\\begin{equation}\nA_{\\lambda_1\\lambda_2}=\\sqrt{2J+1\\over 4\\pi}H_{\\lambda_1\\lambda_2}\nD^{*J}_{M\\lambda_1-\\lambda_2}(\\phi,\\theta,-\\phi).\n\\end{equation}\n\nWhen relating the helicity amplitudes to the invariant amplitudes\nit is sufficient to look at one kinematic configuration, we chose\nthe simplest possible in which $\\theta=\\phi=0$. From the\ndefinition of the $D$ function it is obvious that \n$D^{*J}_{M\\lambda_1-\\lambda_2}(0,0,0)=\\delta_{M,\\lambda_1-\\lambda_2}$.\nThis gives\n\\begin{equation}\nH_{\\lambda_1\\lambda_2}=\\sqrt{4\\pi\\over 2J+1}A_{\\lambda_1\\lambda_2}.\n\\end{equation}\nThis allows us to simply evaluate the helicity amplitudes from the\ninvariant amplitudes if we chose the states, $\\epsilon^1$ and $\\epsilon^2$,\nto correspond to the states in the helicity formalism. \nFor $\\epsilon^1$ we take the states given by~\\ref{eq:spinonestates}\n\\begin{equation}\n\\epsilon^1_+={1\\over\\sqrt{2}}\\left[\\begin{array}{r}\n          -1  \\\\\n          -i  \\\\\n          0  \\\\\n          \\end{array}\\right],\\quad\n\\epsilon^1_0=\\left[\\begin{array}{r}\n          0  \\\\\n          0  \\\\\n          1  \\\\\n          \\end{array}\\right],\\quad\n\\epsilon^1_-={1\\over\\sqrt{2}}\\left[\\begin{array}{r}\n          1  \\\\\n          -i  \\\\\n          0  \\\\\n          \\end{array}\\right].\n\\end{equation}\nThe states for the second particle have to satisfy \n$\\chi_{0\\lambda}=\\Psi_{0-\\lambda}$ which gives\n\\begin{equation}\n\\epsilon^2_+={1\\over\\sqrt{2}}\\left[\\begin{array}{r}\n          1  \\\\\n          -i  \\\\\n          0  \\\\\n          \\end{array}\\right],\\quad\n\\epsilon^2_0=\\left[\\begin{array}{r}\n          0  \\\\\n          0  \\\\\n          1  \\\\\n          \\end{array}\\right],\\quad\n\\epsilon^2_-={1\\over\\sqrt{2}}\\left[\\begin{array}{r}\n          -1  \\\\\n          -i  \\\\\n          0  \\\\\n          \\end{array}\\right].\n\\end{equation}\nNote that this is consistent with Eq.~\\ref{eq:newdef}.\nNow it is straight forward to evaluate the helicity amplitudes\n\\begin{eqnarray}\n H_{++} & = & \\sqrt{4\\pi\\over 3}(-a-ib), \\\\\n H_{00} & = & \\sqrt{4\\pi\\over 3}(a+c),\\\\\n H_{--} & = & \\sqrt{4\\pi\\over 3}(-a+ib).\n\\end{eqnarray}\nThese equations are easily inverted to give\n\\begin{eqnarray}\n a & = & -{1\\over2}\\sqrt{3\\over 4\\pi}(H_{++}+H_{--}), \\\\\n b & = & \\phantom{-}{i\\over2}\\sqrt{3\\over 4\\pi}(H_{++}-H_{--}), \\\\\n c & = & \\phantom{-{1\\over2}}\\sqrt{3\\over 4\\pi}(H_{00}+{1\\over 2}(H_{++}+H_{--})), \\\\\n\\end{eqnarray}\n\n\n\\subsection{Jacob-Wick transformation}\n\\index{Jacob-Wick transformation}\n\\index{partial wave amplitudes}\n\\label{sect:jacobwick}\n\nThis section derives the relation between partial wave amplitudes \nand helicity amplitudes. \n\nThe amplitude for a decay, given the partial wave amplitudes $M_{Ls}$,\nis given by\n$$A(\\Omega,m1,m2,m3)=\\sum_{L,s}C_{s_2s_3}(s\\ m_s;m_2\\ m_3)\n                               C_{Ls}(s_1\\ m_1;m_L\\ m_s)Y^{m_L}_L(\\Omega)\n                               M_{Ls}.$$\n\n\n\\subsection{{\\tt HELAMP} and {\\tt PARTWAVE} model implementations}\n\\index{HELAMP}\n\\index{PARTWAVE}\n\nThe two models {\\tt HELAMP} and {\\tt PARTWAVE} implements generic\ntwo body decays where the amplitudes are specified by the\nhelicity and partial wave amplitudes respectively. The partial\nwave model uses the translation to helicity amplitudes as given in\nSect.~\\ref{sect:jacobwick}. Henceforth, this section will focus\nin the description of the evalution of helicity amplitudes.\n\n EvtGen uses a set of states, that are not the same as the helicity\nstates. In this section it is important to distinguish between these two\nsets of states. The basis states used by EvtGen will be called\n$|n\\rangle$ and the helicity states will be denoted $|\\lambda, s\\rangle$,\nor simply $|\\lambda\\rangle>$. \n\n We consider the decay of the form $A\\rightarrow B C$ where the state\nof the initial particle is given by $|n_A\\rangle$ and the two particles\nin the final state are labeled by $|n_B\\rangle$ and $|n_C\\rangle$. \nFor convenience we label the final state $|n_B, n_C\\rangle=|n_B\\rangle\n\\otimes |n_C\\rangle$. Given this notation we write the amplitude that\nwe need to implement as \n$$A^{B\\rightarrow BC}_{n_A,n_B,n_C}=\\langle n_B, n_C|H|n_A\\rangle.$$\nUsing the completeness of the basis states we write\n\\begin{eqnarray}\nA^{B\\rightarrow BC}_{n_A,n_B,n_C}&=&\\sum_{\\lambda_A,\\lambda_B,\\lambda_C}\\langle n_B, n_C|\\lambda_B\\rangle\\langle\\lambda_B|\\lambda_C\\rangle\\langle\\lambda_C|H|\\lambda_A\\rangle\\langle\\lambda_A|n_A\\rangle\\\\\n                                 &=&\\sum_{\\lambda_A,\\lambda_B,\\lambda_C}\\langle n_B|\\lambda_B\\rangle \\langle n_C|\\lambda_C\\rangle\\langle\\lambda_B|\\langle\\lambda_C|H|\\lambda_A\\rangle\\langle\\lambda_A|n_A\\rangle\\\\\n                                 &=&\\sum_{\\lambda_A,\\lambda_B,\\lambda_C}R^{*}_{n_B\\lambda_B} R^{*}_{n_C\\lambda_C}\\langle\\lambda_B|\\langle\\lambda_C|H|\\lambda_A\\rangle R_{\\lambda_A n_A}\n\\end{eqnarray}\nWhere \n\\begin{eqnarray}\nR_{n_A\\lambda_A} & = & \\langle \\lambda_A | n_A \\rangle \\\\ \nR_{n_B\\lambda_B} & = & \\langle \\lambda_B | n_B \\rangle \\\\\nR_{n_C\\lambda_C} & = & \\langle \\lambda_C | n_C \\rangle\n\\end{eqnarray}\n\n\n\n\n\n\n", "meta": {"hexsha": "f058e3c54062a892efa9dcccb3123026dfcd0d86", "size": 34027, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "EvtGen1_06_00/doc/evt_helamp.tex", "max_stars_repo_name": "klendathu2k/StarGenerator", "max_stars_repo_head_hexsha": "7dd407c41d4eea059ca96ded80d30bda0bc014a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-12-24T19:37:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T06:57:20.000Z", "max_issues_repo_path": "EvtGen1_06_00/doc/evt_helamp.tex", "max_issues_repo_name": "klendathu2k/StarGenerator", "max_issues_repo_head_hexsha": "7dd407c41d4eea059ca96ded80d30bda0bc014a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EvtGen1_06_00/doc/evt_helamp.tex", "max_forks_repo_name": "klendathu2k/StarGenerator", "max_forks_repo_head_hexsha": "7dd407c41d4eea059ca96ded80d30bda0bc014a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.3748443337, "max_line_length": 210, "alphanum_fraction": 0.7027360625, "num_tokens": 10508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.3340076981155336}}
{"text": "%\n% Apostol_Solutions_Vol2.tex \n%\n\\documentclass[twoside]{amsart}\n\\usepackage{amssymb,latexsym}\n\\usepackage{times}\n\n%\\usepackage{graphics}\n\n\\oddsidemargin-0.15cm\n\\evensidemargin-0.15cm\n\\topmargin-1.8cm     %I recommend adding these three lines to increase the \n\\textwidth17.5cm   %amount of usable space on the page (and save trees)\n\\textheight24.5cm  \n\\parindent0.0em\n\n%This next line (when uncommented) allow you to use encapsulated\n%postscript files for figures in your document\n%\\usepackage{epsfig}\n\n%plain makes sure that we have page numbers\n\\pagestyle{plain}\n\n\\theoremstyle{plain}\n\\newtheorem{theorem}{Theorem}\n\\newtheorem{axiom}{Axiom}\n\\newtheorem{lemma}{Lemma}\n\\newtheorem{proposition}{Proposition}\n\n\\theoremstyle{definition}\n\\newtheorem{definition}{Definition}\n\n\\title{\tSolutions to \\emph{ Calculus \\textsc{ Volume 2} Multi-Variable Calculus and Linear Algebra, with Applications to Differential Equations and Probability } by Tom Apostol }\n\n\\author{\n  Ernest Yeung - Praha 10, \\v Cesk\\`a Republika \n       }\n%\\date{Winter 2006}\n\n%This defines a new command \\questionhead which takes one argument and\n%prints out Question #. with some space.\n\\newcommand{\\questionhead}[1]\n  {\\bigskip\\bigskip\n   \\noindent{\\small\\bf Question #1.}\n   \\bigskip}\n\n\\newcommand{\\problemhead}[1]\n  {\\bigskip\\bigskip\n   \\noindent{\\small\\bf Problem #1.}\n   \\medskip}\n\n\\newcommand{\\exercisehead}[1]\n  {\n   \\noindent{\\small\\bf Exercise #1.}\n   \\smallskip}\n\n\\newcommand{\\solutionhead}[1]\n  {\\medskip\\bigskip\n   \\noindent{\\small\\bf Solution #1.}\n   \\medskip}\n\n\n%-----------------------------------\n\\begin{document}\n%-----------------------------------\n\n\\maketitle\n\n\\section*{ 1.5 Exercises - Introduction, The definition of a linear space, Examples of linear spaces, Elementary consequences of the axioms }\n\nRecall the following:\n\\begin{definition}[Linear Space.] \\quad \\\\\n  Let $V$ be a nonempty set of objects.  \\\\\n  Linear space if a set $V$ that satisfies the following ten axioms. \n  \\begin{enumerate}\n  \\item (closure under addition) $\\forall x,y \\in V, x+y \\in V$  \n  \\item (closure under scalar multiplication) $\\forall x \\in V, \\alpha x \\in V$  \n  \\item (Additive commutativity) $\\forall x, y \\in V, x+y = y+x$ \n  \\item (Additive Associativity) $\\forall x,y \\in V, (x+y) + z = x + (y+z)$  \n  \\item (Additive Identity Existence) $\\exists 0 \\in V$ such that \n\\[\nx+ 0 = x, \\forall x \\in V\n\\]\n\\item (Additive Inverse Existence) $\\exists (-1) x $ such that \n\\[\nx + (-1)x = 0 \n\\]\n\\item (Scalar Associativity) $\\forall x \\in V, \\forall \\alpha, \\beta \\in \\mathbb{R} \\text{ or } \\alpha, \\beta \\in \\mathbb{C}$\n\\[\n(\\alpha \\beta)x = \\alpha (\\beta x)\n\\]\n\\item (distributivity for addition in $V$) $\\forall x, y \\in V; \\forall a \\in \\mathbb{R}$ or $\\forall a \\in \\mathbb{C}$, \n\\[\na(x+y) = ax + ay\n\\]\n\\item (distributivity for addition of numbers) $\\forall x \\in V, \\forall a, b \\in \\mathbb{R}$ or $\\forall a,b \\in \\mathbb{C}$,\n\\[\n(a+b)x = ax+bx\n\\]\n\\item (Multiplicative identity existence) $\\forall x \\in V, 1 x =x$\n  \\end{enumerate}\n\\end{definition}\n\n\\exercisehead{1}\nConsider $x = \\frac{p}{q}, y = \\frac{r}{s} \\in V$ where $p,q,r,s$ are polynomials.  $ps+rq, qs$ are polynomials as well.  \n\\[\n\\begin{gathered}\nx+y = \\frac{p}{q} + \\frac{r}{s} = \\frac{ ps + rq}{qs} \\in V  \\\\\n\\alpha \\in \\mathcal{R}, \\quad \\alpha p \\text{ is a polynomial } \\\\\n\\alpha x = \\frac{ \\alpha p }{q} \\in V \\\\\nx+ y = \\frac{ ps + rq}{qs} = \\frac{rq +ps}{qs} = r+ p \\\\\n(x +y ) + z = \\left( \\frac{p}{q} + \\frac{r}{s} \\right) + \\frac{t}{v} = \\frac{p}{q} + \\left( \\frac{r}{s} + \\frac{t}{v} \\right) = x + (y+z)  \\\\\nx + 0 = \\frac{p}{q} + \\frac{0}{q} = \\frac{p}{q} = x \\text{ so } \\frac{0}{q} \\in V \\text{ if } q \\neq 0 \\\\\nx + (-1)x = \\frac{p}{q} + (-1) \\frac{p}{q} = \\frac{0}{q} = 0 \\\\\n(\\alpha \\beta)x = \\frac{ (\\alpha \\beta )p}{q} = \\frac{ \\alpha (\\beta p) }{q} = \\alpha (\\beta x ) \\, \\text{ (follows from associativity of real or complex numbers) } \\\\\n\\alpha( x+ y) = \\alpha x + \\alpha y \\text{ and } (\\alpha + \\beta)x = \\alpha x + \\beta x \\text{ follows from distributivity for real numbers } \\\\\n\\text{ Consider } x = \\frac{p}{q} = \\left( \\frac{q}{q} \\right) \\frac{p}{q} = (1)x, \\, \\frac{q}{q} \\in V\n\\end{gathered}\n\\]\n\n\\exercisehead{3} All $f$ with $f(0) = f(1)$ \\medskip \\\\\n$f(0) + g(0) = (f+g)(0) = f(1) + g(1) = (f+g)(1)$ \\smallskip \\\\\n$af(0) = (af)(0) = af(1) = (af)(1)$ \\smallskip \\\\\n$f(x) + g(x) = (f+g)(x) = g(x) + f(x) = (g+f)(x)$ \\smallskip \\\\\n$(f(x) +g(x))+h(x) = ((f+g)+h)(x) = f(x) + (g(x) +h(x)) = (f+ (g+h))(x)$ \\smallskip \\\\\n$0(x) = 0$  \\quad $(f+0)(x) = f(x) + 0(x) = f(x)$ \\smallskip \\\\\n$(-1)f(x) = (-f)(x)$ \\quad \\quad \\quad $(f+(-1)f)(x) = (f-f)(x) = f(x) + (-1)f(x) = 0 = 0(x)$  \\smallskip \\\\\n$(\\alpha \\beta)f(x) = \\alpha (\\beta f(x)) = \\alpha (\\beta f)(x)$ \\smallskip \\\\\n$a(f+g)(x) = a(f(x) + g(x)) = af(x) + ag(x) = (af+ag)(x)$ \\smallskip \\\\\n$(a+b)f(x) = af(x) + bf(x) = (af)(x) + (bf)(x) = (af+bf)(x)$ \\smallskip \\\\\n$(1f)(x) = f(x)$\n\n\\exercisehead{4} All $f$ with $2f(0) = f(1)$ \\medskip \\\\\n$2(f+g)(0) = 2f(0) + 2g(0) = f(1) + g(1) = (f+g)(1)$ \\smallskip \\\\\n$2(\\alpha f)(0) = 2\\alpha f(0) = \\alpha f(1) =(\\alpha f)(1)$ \\\\\n$f+g = g+f, (f+g) + h = f + (g+h)$ follow from properties of the reals.  \\\\\n$20(0) = 0 = 0(1)$; \\quad $(f+0)(x) = f(x) + 0 =f(x)$ \\\\\n$(f+(-f))(x) = f(x) + -f(x) = 0 $ \\\\\n$(\\alpha \\beta) f(x) = \\alpha (\\beta f(x) )$ \\\\\n$a(f+g)(x) = (af)(x) + (ag)(x), (a+b)f(x) = af(x) + bf(x)$ follow from properties of the reals.  \\\\\n$1x = x$\n\n\\exercisehead{5} All $f$ with $f(1) = 1 + f(0)$\n\\[\nf(1) +g(1) = (f+g)(1) = 1+f(0) + 1 + g(0) = 2 + (f+g)(0)\n\\]\nSo closure under addition is violated.  \n\n\\exercisehead{6} All step functions defined on $[0,1]$.\n\n\\exercisehead{8} Even functions, $f(-x) = f(x)$.  \n\\[\n\\begin{gathered}  \n  (f+g)(-x) = f(-x) + g(-x) = f(x) + g(x) \\\\\n  (\\alpha f)(-x) = \\alpha f(-x) = \\alpha f(x) = (\\alpha f)(x) \\\\\n  (f+g)(x) = f(x) + g(x) = g(x) + f(x) = (g+f)(x) \\, \\text{ (follows from commutativity of real numbers) } \\\\\n  \\begin{aligned}\n     ((f+g)+h)(-x) & = (f+g)(-x) +h(-x) = f(x) + g(x) + h(x) = f(x)+ (g+h)(x) = (f+(g+h))(x) \\\\\n    & \\quad \\text{ (follows from associativity of real numbers) } \n  \\end{aligned} \\\\\n  \\text{ if } 0(-x) = 0(x) = 0 \\, \\forall x \\in D \\text{ so $0$ exists and } (f+0)(x) = f(x) + 0(x) = f(x)  \\\\\n  (-f)(-x) = -f(-x) = -f(x) \\text{ so }  (f+-f)(x) = f(x) - f(x) = 0(x) \\\\\n  \\alpha (\\beta f)(-x) = \\alpha (\\beta(f(-x))) = \\alpha (\\beta f(x) ) = \\alpha(\\beta f)(x)  \\\\\n  ((\\alpha \\beta) f)(-x) = (\\alpha \\beta) f(-x) = (\\alpha \\beta)f(x) = ((\\alpha \\beta)f)(x) \\, \\text{ (from associativity of the real numbers) }  \\\\\n  \\alpha (f+g)(x) = \\alpha (f(x)+g(x)) = (\\alpha f)(x) + (\\alpha g)(x) = (\\alpha f + \\alpha g)(x) \\\\\n  (\\alpha + \\beta)f(x) = \\alpha f(x) + \\beta f(x) = (\\alpha f)(x) + (\\beta f)(x) = (\\alpha f +\\beta f)(x) \\\\\n  1 f(x) = 1 (f(x)) = f(x)\n\\end{gathered}\n\\]\n\n\\exercisehead{22} All vectors $(x,y,z)$ in $V_3$ with $z=0$.  \\smallskip \\\\\nThis space is closed under addition and scalar multiplication since \n\\[\n\\begin{gathered}\n  (x_1,y_1,0) + (x_2,y_2,0) = (x_1+x_2, y_1+y_2,0) \\\\\n  k(x,y,0) = (kx,ky,0)\n\\end{gathered}\n\\]\nboth belong to this space.  \\\\\n\nAdditive commutativity, additive associativity, scalar associativity, distributivity in addition in $V$, and distributivity in addition of numbers are satisfied automatically, since all vectors in this subset belong to $V_3$, a linear space.  \n\n$(0,0,0)$ belongs to this space, since $z=0$, so existence of an additive identity is fulfilled. \\\\\n\n$(-x,-y,0) = -(x,y,0)$ belongs in this space and so the existence of an additive inverse for each element $(x,y,0)$ in this space is fulfilled.  \\\\\n\n$1(x,y,0) = (x,y,0)$, and so multiplicative identity existence is fulfilled.  \\\\\nThis is a linear space.  Note that we could've also said that this space is exactly $V_2$, and $V_2$ is a linear space. \n\n\\exercisehead{23} All vectors $(x,y,z)$ in $V_3$ with $x=0$ or $y=0$.  \\smallskip \\\\\nConsider $(0,y_1,z_1) + (x_2,0,z_2) = (x_2, y_1,z_1+z_2)$.  This vector does not belong to this space.  This is not a linear space.  \n\n\\exercisehead{24} All vectors $(x,y,z)$ in $V_3$ with $y=5x$.  \\smallskip \\\\\nThis space is closed under addition and scalar multiplication since \n\\[\n\\begin{gathered}\n  (x_1,5x_1,0) + (x_2,5x_2,0) = (x_1+x_2,5x_1+5x_2,0) \\Longrightarrow 5x_1 + 5x_2 = 5(x_1+x_2) \\\\\n  k(x_1,5x_1,z_1) \\Longrightarrow k 5x_1 = 5(kx_1)\n\\end{gathered}\n\\]\n\nAdditive commutativity, additive associativity, scalar associativity, distributivity in addition in $V$, and distributivity in addition of numbers are satisfied automatically, since all vectors in this subset belong to $V_3$, a linear space.  \\\\\n\n$(0,5(0),0)$ belongs to this space, so existence of an additive identity is fulfilled. \\\\\n\n$(-x,5(-x),-z) = -(x,5x,z)$ belongs in this space and so the existence of an additive inverse for each element in this space is fulfilled.  \\\\\n\n$1(x,5x,z) = (x,5x,z)$, and so multiplicative identity existence is fulfilled.  \\\\\nThis is a linear space.  \n\n\\exercisehead{25} All vectors $(x,y,z)$ in $V_3$ with $3x + 4y = 1 \\, z=0$.  \\smallskip \\\\\nConsider closure: \n\\[\n\\begin{gathered}\n(x_1,y_1,0) + (x_2,y_2,0) = (x_1+x_2, y_1+y_2,0) \\\\\n  z_3 = 0; \\quad 3(x_1+x_2) + 4(y_1+y_2) = 2\n\\end{gathered}\n\\]\nClosure under addition is not satisfied.  Thus, this is not a linear space.  \n\n\\exercisehead{26} All vectors $(x,y,z)$ in $V_3$ which are scalar multiples of $(1,2,3)$.    \\smallskip \\\\\nClosure is fulfilled since $x+y= a(1,2,3) +b(1,2,3) = (a+b)(1,2,3)$, which is a scalar multiple of $(1,2,3)$, and $ax = ab(1,2,3)$, which is another scalar multiple of $(1,2,3)$.  \\\\\n\nAdditive commutativity, additive associativity, scalar associativity, distributivity in addition in $V$, and distributivity in addition of numbers are satisfied automatically, since all vectors in this subset belong to $V_3$, a linear space.  \\\\\n\n$\\exists \\, 0$ since $0(1,2,3) = 0$ is a scalar multiple of $(1,2,3)$.  \\\\\n\n$\\exists \\, -1x \\, \\forall \\, x$, since $(-1)a(1,2,3)$ is a scalar multiple of $(1,2,3)$.  \\\\\n\n$1(a(1,2,3)) = (a(1,2,3))$ is a scalar multiple of $(1,2,3)$ and so multiplicative identity existence is satisfied.   \\\\\nThis is a linear space.  \n\n\n\\exercisehead{28} All vectors in $V_n$ that are linear combinations of $2$ given vectors $A$ and $B$.   \\medskip \\\\\n$a_1 A + b_1 B + a_2 A + b_2 B = (a_1 + a_2)A + (b_1 + b_2)B$ belongs in this space.  \\smallskip \\\\\n$c(aA+ bB) = (ca)A + (cb)B$ belongs in this space. \\smallskip \\\\\n$x+y = y+x, \\, (x+y) + z = x +(y+z)$ follow since the vectors belong in $V_n$, a linear space.  \\smallskip \\\\\n$0A + 0B =0$; \\quad $a_1 A + b_1 B + 0A + 0B = a_1 A + b_1 B$ \\smallskip \\\\\n$-a_1 A + -b_1 B$ belongs in this space and $a_1 A + b_1 B + -a_1 A + -b_1 B = (a_1 - a_1)A + (b_1 - b_1)B = 0$ \\smallskip \\\\\n$(ab)x = a(bx), \\, a(x+y) = ax + ay, \\, (a+b)x = ax + bx, \\, 1x = x$ follow since the vectors in this space belong in $V_n$, a linear space.  \n\n\\exercisehead{29} Let $V = \\mathbb{R}^+$, let $x ``+''y = xy$ and $a ``\\cdot'' x = x^a$ \\medskip \\\\\n$x ``+'' y = xy \\in \\mathbb{R}^+$ \\smallskip \\\\\n$a ``\\cdot'' x = x^a = e^{a\\ln{x}} > 0$ \\quad $a ``\\cdot'' x \\in \\mathbb{R}^+$ \\smallskip \\\\\n$x ``+'' y = xy = yx = y ``+''x$ \\smallskip \\\\\n$(x ``+'' y) ``+'' z = xyz = x(yz) = x ``+'' (y ``+'' z)$ \\smallskip \\\\\n$x ``+'' ``0'' = x1 = x$ so $''0'' = 1 \\in \\mathbb{R}^+$ \\smallskip \\\\\n$''(-1)x'' = \\frac{1}{x} \\in \\mathbb{R}^+$ \\quad \\, $x ``+'' ``(-1)x'' = x \\frac{1}{x} = 1 = ``0''$ \\smallskip \\\\\n$(ab)x = x^{ab} = (x^b)^a = a(bx)$ \\smallskip \\\\\n$a ``\\cdot'' (x ``+'' y) = a ``\\cdot'' (xy) = (xy)^a = x^a y^a = (a ``\\cdot x) ``+'' (a ``\\cdot'' y)$ \\smallskip \\\\\n$(a+b) ``\\cdot'' x = x^{a+b} = x^a x^b = x^a ``+'' x^b = a ``\\cdot'' x ``+'' b ``\\cdot'' x$ \\smallskip \\\\\n$1 ``\\cdot'' x = x^1 = x$\n\nThis is indeed a linear space.  \n\n\\exercisehead{30}\n\\begin{enumerate}\n  \\item From Axiom 5,6, the Additive Identity Existence and Additive Inverse Existence, that $\\exists \\, 0 \\in V$ s.t. $x+0=x, \\, \\forall \\, x \\in V$ and $\\exists \\, (-1)x$ s.t. $x + (-1)x = 0$, then, using associativity, commutativity, and distributivity for addition of numbers, \n\\[\nx + 0 = x = x + (x +(-1)x) = 2x + (-1)x = (2 +(-1))x = 1x\n\\]\n  \\item If Ax.6 is replaced by Ax.6', $\\forall \\, x \\in V, \\quad \\exists \\, y \\in V$ s.t. $x+y=0$, \n\\[\nx+0 = x = x + (x+y) = 2x + y = x\n\\]\nSo Ax.10 does not hold since $2x +y =x$.  \n\\end{enumerate}\n\n\\exercisehead{31}\n\\begin{enumerate}\n  \\item $(x_1,x_2) + (y_1,y_2) = (x_1 + y_1, x_2 + y_2) \\quad \\quad \\quad a(x_1,x_2) = (ax_1,0)$.  \\\\\nNot a linear space: violates Additive Inverse existence, which demands $\\exists \\, (-1)x$ s.t. $x+(-1)x =0$, not $\\exists \\, y$ s.t. $x+y=0$, so that for $(-1)x = (-x_1,0)$, $(x_1,x_2) + (-1)x = (0,x_2) \\neq 0$ and Multiplicative identity existence, since $1x = (x_1,0) \\neq x$.  \\medskip \n  \\item $(x,1,x_2) + (y_1,y_2) = (x_1+y_1,0)$ \\quad \\quad \\quad $a(x_1,x_2) = (ax_1, ax_2)$\\\\\nNot a linear space: violates distributivity in addition of numbers, because \\\\\n$(a+b)x = ((a+b)x_1,(a+b)x_2)$ but $ax + bx = (ax_1 + bx_1,0)$ \\medskip \n  \\item $(x,1,x_2) + (y_1,y_2) = (x_1,x_2+y_2)$ \\quad \\quad \\quad $a(x_1,x_2) = (ax_1, ax_2)$ \\\\\nNot a linear space because it violates Additive Commutativity of elements.\n$(x_1,x_2) + (y_1, y_2) = (x_1, x_2+y_2)$ but \\\\\n$(y_1,y_2) + (x_1,x_2) = (y_1,x_2 +y_2)$  \\medskip \n  \\item $(x,1,x_2) + (y_1,y_2) = (|x_1+y_1|,|y_1+y_2|)$ \\quad \\quad \\quad $a(x_1,x_2) = (|ax_1|, |ax_2|)$ \\\\\nNot a linear linear space because it violates Distributivity for addition of numbers: \n\\[\n\\begin{gathered}\n  (a+b)(x_1,x_2) = (|(a+b)x_1|, |(a+b)x_2|) \\\\\n  ax+bx = (|ax_1|,|ax_2|) + (|bx_1|,|bx_2|) \\\\\n\\text{ but } |(a+b)x_1 |\\leq |ax_1| + |bx_1| \\text{ in general }\n\\end{gathered}\n\\]\n\\end{enumerate}\n\n\\exercisehead{32} Theorem 1.3. \n\\begin{enumerate}\n\\item $0x = 0$ \n\\item $a0=0$ \n\\item $(-a)x = -(ax) = a(-x)$\n\\item If $ax=0$, then either $a=0$ or $x=0$ \n\\item If $ax = ay$ and $a\\neq 0$, then $x=y$\n\\item If $ax = bx$ and $x\\neq 0$, then $a=b$\n\\item $-(x+y) = (-x) + (-y) = -x-y$ \n\\item $x+x=2x,x+x+x=3x, \\sum_{j=1}^n x = nx$\n\\end{enumerate} \\quad \\smallskip\n\nPart (d), or part 4, is proven by considering this: \\\\\nIf $ax =0$, \\\\\n\\quad then if $a=0$ and $x=0$, done.  \\\\\nIf $a\\neq 0$, \n\\quad $ax + a0 = a(x+0) =0$ \\\\\nsince $a$ is a real number, $\\exists \\frac{1}{a} \\in \\mathbb{R}$ s.t. $\\left(\\frac{1}{a} \\right) a = 1$ \n\\[\n\\Longrightarrow 1(x+0) = x+0 = x = \\frac{1}{a} 0 =0\n\\]\nIf $x\\neq 0$, suppose $a\\neq 0$.  \n\\[\n\\frac{1}{a} ax = 1x = x = \\frac{1}{a} 0 = 0 \n\\]\nBut $0$ is unique.  Contradiction.  So $a=0$ and that's okay, since by part (a) or part (1) of Thm. 1.3., $0x =0$.  \\\\\n\nFor part (e), or part 5, if $ax=ay, \\, a\\neq 0$, then subtract $ay$ from both sides to get $ax - ay =0 = a(x-y) =0$.  Use distributivity to get $ax-ay = a(x-y) = 0$.  Since $a\\neq 0$, then from part (d) or part 4, $x-y=0$ must be true.  Then $-y = -x$ or, multiplying both sides by $-1$, $y=x$.   \\\\\n\nFor part (f), or part 6, if $ax=ay$, subtract $bx$ from both sides and use distributivity to get $ax-bx = (a-b)x = 0$.  Since $x \\neq 0$, then by part (d), or part 4, $a-b=0$.  Add $b$ to both sides to get $a=b$.   \\\\\n\nFor part (g), or part 7, note that from the existence of an additive inverse, $x + -x =0$.  Consider $x + (-1)x =0$.  $x=1x$ by the existence of a multiplicative identity, and so using distributivity, $1x + (-1)x = (1+-1)x = 0x =0$.  Then $(-1)x$ is also an additive inverse for all $x \\in V$.  But additive inverses are unique, by theorem, so $(-1)x = -x$.  Using that and distributivity, we get $(-x)+(-y) = (-1)x + (-1)y = (-1)(x+y) = -(x+y)$.  $-x-y = -(x+y)$ because \\\\\n$x+y + -(x+y) = 0 = x - x + y -y = x +y -x -y $, where we used additive commutativity at the last step.  Then subtract $x+y$ from both sides to get $-x-y = -(x+y)$.   \\\\\n\nFor part (h), or part 8, use the existence of a multiplicative identity and distributivity to get $x+x = 1x +1x = (1+1)x = 2x$.  \\\\\nNow, we'll use induction.  Assume the $n$th case, that $\\sum_{j=1}^n x = nx$.  \\\\\nConsider $\\sum_{j=1}^{n+1}x$.  $\\sum_{j=1}^{n+1}x = \\sum_{j=1}^n x + x = nx+x = nx+1x = (n+1)x$.  Done.  \n\n\\section*{ 1.10 Exercises - Subspaces of a linear space, Dependent and independent sets in a linear space, Bases and dimension, Components }\n\n\\exercisehead{1} $x=0$\n\\[\n\\begin{gathered}\n  (0,y_1,z_1) + (0,y_2,z_2) = (0,y_1 + y_2, z_1 + z_2) \\in S \\\\\n  k(0,y,z) = (0,ky,kz) \\in S\n\\end{gathered}\n\\]\nYes, $S$ is a subspace.  \n\\[\n\\begin{gathered}\n  (0,y,z) = y(0,1,0) + z(0,0,1) \\in S \\\\\n  0 = y(0,1,0) + z(0,0,1) \\quad \\Longrightarrow z = 0 \\, \\quad y = 0 \n\\end{gathered}\n\\]\n$\\boxed{ dim{S} = 2 }$\n\n\\exercisehead{2} $x+y = 0$ \n\\[\n\\begin{gathered}\n\\begin{gathered}\n  (x_1 + x_2,y_1 + y_2, z_1 + z_2) \\in S \\text{ since } \\\\\n  x_1 + x_2 + y_1 + y_2 = 0 + 0 = 0 \n\\end{gathered} \\quad \\quad \\quad \\quad \n\\begin{gathered}\n  k(x,y,z) \\in S \\text{ since } \\\\\n  kx + k y = k(x+y) = 0 \n\\end{gathered}\n\\end{gathered}\n\\]\nYes, $S$ is a subspace. \n\\[\n\\begin{gathered}\n  (x,y,z) = (x,-x,z) = x(1,-1,0) + z(0,0,1) \\\\\n  0 = x(1,-1,0) + z(0,0,1) \\Longrightarrow z =0, \\, x =0 \n\\end{gathered}\n\\]\n$\\boxed{ dim{S} = 2 }$\n\n\\exercisehead{3} $x+y+z =0$ \n\\[\n\\begin{gathered}\n  \\begin{gathered}\n    (x_1 + x_2, y_1 + y_2,z_1 + z_2) \\in S \\text{ since } \\\\\n    x_1 + x_2 + y_1 + y_2 + z_1 + z_2 = 0 + 0 =0 \n    \\end{gathered} \\quad \\quad \\quad \\quad \n  \\begin{gathered}\n    k(x,y,z) \\in S \\text{ since } \\\\\n    k(x+y+z) = kx+ky+kz = 0\n  \\end{gathered}\n\\end{gathered}\n\\]\nYes, $S$ is a subspace.  \n\\[\n\\begin{gathered}\n  (x,y,-(x+y)) = x(1,0,-1) + y(0,1,-1) \\\\\n  0 = x(1,0,-1) + y(0,1,-1) \\Longrightarrow x = 0, \\, y = 0\n\\end{gathered}\n\\]\n$\\boxed{ dim{S} = 2 }$\n\n\\exercisehead{4} $x=y$ \n\\[\n\\begin{gathered}\n  \\begin{gathered}\n    (x_1 + x_2, y_1 + y_2,z_1 + z_2) \\in S \\text{ since } \\\\\n    x_1 + x_2 =y+1 + y+2 \n    \\end{gathered} \\quad \\quad \\quad \\quad \n  \\begin{gathered}\n    k(x,y,z) \\in S \\text{ since } \\\\\n    kx = ky \n  \\end{gathered}\n\\end{gathered}\n\\]\nYes, $S$ is a subspace.  \n\\[\n\\begin{gathered}\n  (x,y,z) = (x,x,z) = x(1,1,0) + z(0,0,1) \\\\\n  0 = x(1,1,0) + z(0,0,1) \\Longrightarrow x = 0, \\, z = 0\n\\end{gathered}\n\\]\n$\\boxed{ dim{S} = 2 }$\n\n\\exercisehead{5} $x=y=z$\n\\[\n\\begin{gathered}\n  \\begin{gathered}\n    (x_1 + x_2, y_1 + y_2,z_1 + z_2) \\in S \\text{ since } \\\\\n    x_1 + x_2 =y+1 + y+2 =z_1 + z_2 \n    \\end{gathered} \\quad \\quad \\quad \\quad \n  \\begin{gathered}\n    k(x,y,z) \\in S \\text{ since } \\\\\n    kx = ky = kz \n  \\end{gathered}\n\\end{gathered}\n\\]\nYes, $S$ is a subspace.  \n\\[\n\\begin{gathered}\n  (x,y,z) = x(1,1,1) \\\\\n  0 = x(1,1,1)  \\Longrightarrow x = 0, \n\\end{gathered}\n\\]\n$\\boxed{ dim{S} = 1 }$\n\n\\exercisehead{6} $x=y$ or $x=z$ \\medskip \\\\\nIf $x_1 + y_1$ \\\\\n\\quad If $x_2 = y_2$, $x_1 + x_2 = y_1 + y_2$ \\\\\n\\quad \\quad else if $x_2 = z_2$, $\\begin{aligned}\n  & x_1 + x_2 \\text{ may not equal } y_1 + y_2 \\\\ \n  & x_1 + x_2 \\text{ may not equal } z_1 + z_2 \n\\end{aligned}$\nNo, $S$ is not a subspace.  \n\n\\exercisehead{7} $x^2 -y^2 = 0$\n\\[\n(x_1 + x_2)^2 - (y_1^2 + y_2^2) = 2x_1 x_2 - 2y_1 y_2 \\text{ maybe not equal to zero } \n\\]\n$S$ not a subspace.  \n\n\\exercisehead{8} $x+y=1$\n\\[\n\\begin{gathered}\n  (x_1 + x_2, y_1 + y_2,z_1 + z_2 ) \\notin S \\text{ since } \\\\\n  x_1 + x_2 + y_1 + y_2 = 2 \n\\end{gathered}\n\\]\nNo $S$ is not a subspace.  \n\n\\exercisehead{9} $y=2x$ and $z=3x$\n \\[\n\\begin{gathered}\n  \\begin{gathered}\n    (x_1 + x_2, y_1 + y_2 , z_1 + z_2) \\in S \\text{ since } \\\\\n    y_1 + y_2 = 2x_1 + 2x_2 = 2(x_1 + x_2) \\\\\n    z_1 + z_2 = 3x_1 + 3x_2 = 3(x_1+  x_2 ) \n  \\end{gathered} \\quad \\quad \\quad \\quad \n  \\begin{gathered}\n  (kx,ky,kz) \\in S \\text{ since }  \\\\\n  ky = k 2x = 2kx \\\\\n  kz = k3x = 3kx \n\\end{gathered}\n\\end{gathered}\n\\]\n$S$ is a subspace.  \n\\[\n\\begin{gathered}\n  (x,y,z) = x(1,2,3) \\\\\n  0 = x(1,2,3) \\Longrightarrow x = 0\n\\end{gathered}\n\\]\n$\\boxed{ dim{S} = 1 }$ \n\n\\exercisehead{10} \n\\[\n\\begin{aligned}\n  x+y+z & = 0 \\\\\n  x-y-z & = 0 \n\\end{aligned} \\Longleftrightarrow \n\\begin{aligned}\n  x &= 0 \\\\\ny & = -z\n\\end{aligned}\n\\]\n\\[\n\\begin{gathered}\n  (x_1+x_2, y_1 + y_2,z_1 + z_2) \\in S \\text{ since } \\\\\n  x_1 + x_2 = 0 \\\\\n  y_1 + y_2 = -z_1 -z_2 = -(z_1 + z_2) \\\\\n  k(x,y,z) \\in S \\text{ since } \\\\\n  kx = 0 \\quad \\quad ky = -kz\n\\end{gathered} \\quad \\quad \\quad \\quad \n\\begin{gathered}\n  y(0,1,-1) = (x,y,z) \\\\\n  0 = y(0,1,-1) \\Longrightarrow y = 0 \n\\end{gathered}\n\\]\nYes $S$ is a subspace and $\\boxed{ dim{S} = 1 }$ \\medskip \\\\\n\nFor Exercises 11-20, in the $P_n$ space, we will use the $\\{ u_k \\}$ basis extensively, where $u_k = t^k$ \\quad $k = 0,1,\\dots, n$.  It could be shown that this forms a basis, specifically it forms an independent set, by differentiating a degree $n$ polynomial and set it to $0$, and then repeating the differentiation.    \\\\\n\\exercisehead{11}$f(0)=0$\n\\[\n\\begin{gathered}\n  \\begin{gathered}\n  f+g = \\sum_{j=1}^n a_j x^j  + \\sum_{j=1}^n b_j x^j = \\sum_{j=1}^n (a_j + b_j)x^j \\in S \\text{ since } \\\\\n  (f+g)(0)= 0\n\\end{gathered} \\quad \\quad \\quad \n  \\begin{gathered}\n    kf = \\sum_{j=1}^n ka_k x^k \\in S \\text{ since } \\\\\n    kf(0) = 0 \n  \\end{gathered}\n\\end{gathered}\n\\]\nYes $S$ is a subspace.  \n\\[\n\\begin{gathered}\n  f = \\sum_{j=1}^n a_j x^j \\\\\n  0 = \\sum_{j=1}^n a_j x^j  \\Longrightarrow a_j = 0  \n\\end{gathered}\n\\]\n$\\boxed{ dim{S} = n }$\n\n\\exercisehead{12} $f'(0) = 0$ \n\\[\n\\begin{gathered}\n  (f+g)' = f' + g' \\Longrightarrow (f+g)'(0) = f'(0) + g'(0) = 0 \\\\\n  (kf)' = kf' \\Longrightarrow kf'(0) = 0 \n\\end{gathered}\n\\]\nYes $S$ is a subspace.  \n\\[\n\\begin{gathered}\n  \\begin{aligned}  \n    f & = \\sum_{j=0}^n a_j x^j  \\\\\n    f' & = \\sum_{j=1}^n j a_j x^{j-1} \n  \\end{aligned} \n  \\quad \\quad \\quad f'(0) = 0 \\Longrightarrow a_1 = 0 \\\\\n  \\begin{gathered}\n  f= a_0 + \\sum_{j=2}^n a_j x^j  \\\\\n  0 = a_0 + \\sum_{j=2}^n a_j x^j \\Longrightarrow a_j = 0, \\quad j = 0, 2, 3,\\dots n\n\\end{gathered}\n\\end{gathered}\n\\]\n$\\boxed{ dim{S} = n }$\nNote that for the last step, we could've sited the fact that a subset of an independent set, such as the $\\{ t^k \\}$ basis for $P_n$, is an independent set, by definition, and so if that subset spans $S$, this subset will be a basis for $S$.  \n\n\\exercisehead{13} $f''(0) = 0$ \n\\[\n\\begin{gathered}\n  (f+g)'' = f'' + g'' \\Longrightarrow (f+g)''(0) = f''(0) + g''(0) = 0 \\\\\n  (kf)'' = kf'' \\Longrightarrow kf''(0) = 0 \n\\end{gathered}\n\\]\nYes $S$ is a subspace.  \n\\[\n\\begin{gathered}\n  f'' = \\sum_{j=2}^n j (j-1) a_j x^{j-2} \\quad \\, \\Longrightarrow f= a_0 + a_1 x + \\sum_{j=3}^n a_j x^j \\\\\n  f''(0) = a_2 = 0 \n\\end{gathered}\n\\]\nThen $f$ is a linear combination of $\\{ 1,x,x^3, x^4, \\dots, x^n \\}$, $dim{S} = n$\n\n\\exercisehead{14} $f(0) + f'(0) = 0$\n\\[\n\\begin{gathered}\n  f+g + f' +g' = (f+g) + (f+g)' \\Longrightarrow (f+g)(0) + (f+g)'(0) = 0 + 0 = 0 \\\\\n  kf + (kf)' = k(f+f') \\Longrightarrow k f(0) + (kf)'(0) = k(f(0) + f'(0)) = 0 \n\\end{gathered}\n\\]\nYes $S$ is a subspace.  \n\\[\n\\begin{gathered}\n  f+ f' = \\sum_{j=0}^n a_j x^j + \\sum_{j=1}^n j a_j x^{j-1} \\\\\n  (f+f')(0) = a_0 + a_1 = 0 \\Longrightarrow a_0 = -a_1 \n\\end{gathered} \\quad \\quad \\quad \nf = a_0 (1-x) + \\sum_{j=2}^n a_j x^j \n\\]\nIf $f=0$, $a_j = 0$ for $j=2,3,\\dots n$, by taking $j=2,3,\\dots n$ derivatives.  $a_0 = 0$ for $f(0) = 0$.  Thus $\\{ 1-x,x^2, x^3, \\dots, x^n \\}$ is independent and span $S$ and thus form a basis.  \\\\\n$\\boxed{ dim{S} = n }$\n\n\\exercisehead{15} $f(0) = f(1)$ \n\\[\n\\begin{gathered}\n  (f+g)(0) = f(0) + g(0) + f(1) +g(1) = (f+g)(1) \\\\\n  kf(0)  = kf(1) \n\\end{gathered}\n\\]\nYes $S$ is a subspace.  \n\\[\n\\begin{gathered}\n  f = \\sum_{j=0}^n a_j x^j \\\\\n  f(0) = a_0 = f(1) = a_0 + \\sum_{j=1}^n a_j \\\\\n  \\Longrightarrow \\sum_{j=1}^n a_j =0 \\text{ or } a_1 = -\\sum_{j=2}^n a_j \\\\\n  \\Longrightarrow f = a_0 + \\sum_{j=2}^n a_j (x^j - x) \n\\end{gathered} \\quad \\quad \\quad \\begin{gathered}\n  \\text{ By differentiating } \\\\\n  f' = (a_0)' + a_2 (2x-1) + a_3(3x^2 - 1) \\dots \\\\\n  f'' = a_2 (2) + a_3 x \\\\\n  f'' = \\sum_{j=2}^n a_j (jx^{j-2}) = 0 \\text{ if } f = 0 \n\\end{gathered}\n\\]\nThen $\\{ x^{j-2} \\}$ is a subset of a basis for $P_n$.  \\\\\n$a_j = 0$ for $j=2,\\dots n$.  \\\\\n\\quad \\, Then $a_0 =0 $.  \\\\\n\\quad Thus, $\\{ 1, x^j - x \\}$ is independent and spans $S$.  Then $\\{ 1, x^j -x \\}$ forms a basis for $S$.  \\\\\n$\\boxed{ dim{S} = n }$\n\n\\exercisehead{16} $f(0) = f(2)$\n\\[\n\\begin{gathered}\n  f(0) + g(0) = (f+g)(0) = f(2) + g(2) = (f+g)(2) \\\\\n  kf(0) = kf(2) \n\\end{gathered}\n\\]\nYes $S$ is a subspace.  \n\\[\n\\begin{gathered}\n\\begin{gathered}\n  f = \\sum_{j=0}^n a_j x^j \\\\\n  f(0) = a_0 = a_0 + \\sum_{j=1}^n a_j 2^j \\Longrightarrow 2a_1 + \\sum_{j=2}^n 2^j a_j = 0 \\text{ or } a_1 = -\\sum_{j=2}^n 2^{j-1}a_j \\\\\n  \\Longrightarrow f = a_0 + \\sum_{j=2}^n a_j (x^j - 2^{j-1}x )\n\\end{gathered} \\\\\n\\begin{gathered}\n  f'' = \\sum_{j=2}^n a_j j(j-1)x^{j-2} \\text{ and } f'' = 0 \\text{ if } f = 0 \n\\end{gathered}\n\\end{gathered}\n\\]\n$\\mathcal{B}_{S_1} = \\{ 1, x, \\dots, x^{n-2} \\}$ is a subset of the basis $\\{ 1, x, \\dots, x^n \\} = \\mathcal{B}_{P_n}$ for $P_n$.  Then $\\mathcal{B}_{S_1}$ is independent, and so $a_j = 0$ for $j=2,\\dots n$.  Then for $f=0$, $a_0 = 0$.  Thus $\\{ 1, x^2-2x, x^3 - 2^2x,\\dots, x^j - 2^{j-1}x, \\dots, x^n - 2^{n-1} x \\}$ is independent and spans $S$ and thus forms a basis for $S$.  \\\\\n$\\boxed{ dim{S} = n }$\n\n\\exercisehead{17} $f$ is even.  $f(-x) = f(x)$\n\\[\n\\begin{gathered}\n  (f+g)(-x) = f(-x) + g(-x) = f(x) + g(x) = (f+g)(x) \\\\\n  kf(-x) = kf(x)\n\\end{gathered}\n\\]\nYes $S$ is a subspace.  \n\\[\n\\begin{gathered}\nf(-x) = \\sum_{j=0}^n a_j x^j (-1)^j = f(x) = \\sum_{j=0}^n a_j x^j  \\Longrightarrow \\sum_{j=0}^n a_j x^j ((-1)^j - 1) =0 \n\\end{gathered}\n\\]\n$\\frac{n}{2} + 1$ if $n$ is even, is the number of possibly nonzero coefficients for $f$.  \\\\\n$\\frac{n-1}{2} + 1 = \\frac{n+1}{2}$ if $n$ is odd, is the number of possibly nonzero coefficients for $f$.  \\medskip \\\\\nThen $\\frac{n}{2}$ or $\\frac{n-1}{2}$, if $n$ is even, or $n$ is odd, respectively, are the number of needed elements for a subset from the basis $\\mathcal{B}_{P_n}$ to span $f$ and form a basis for $S$.\n\n\\exercisehead{18} $f$ is odd.  $f(-x) = f(x)$\n\\[\n\\begin{gathered}\n  (f+g)(-x) = f(-x) + g(-x) = -f(x) - g(x) = -(f+g)(x) \\\\\n  kf(-x) = -kf(x)\n\\end{gathered}\n\\]\nYes $S$ is a subspace.  \n\\[\n\\begin{gathered}\nf(-x) = \\sum_{j=0}^n a_j x^j (-1)^j = -f(x) = -\\sum_{j=0}^n a_j x^j  \\Longrightarrow \\sum_{j=0}^n a_j x^j ((-1)^j + 1) =0 \n\\end{gathered}\n\\]\n$\\frac{n}{2}$ if $n=2K$ is even, is the number of possibly nonzero coefficients for $f$.  \\\\\n$\\frac{n+1}{2}  = \\frac{n+1}{2}$ if $n=2K-1$ is odd, is the number of possibly nonzero coefficients for $f$.  \\medskip \\\\\nThen $\\frac{n}{2}$ or $\\frac{n+1}{2}$, if $n$ is even, or $n$ is odd, respectively, are the number of needed elements for a subset from the basis $\\mathcal{B}_{P_n}$ to span $f$ and form a basis for $S$.\n\n\\exercisehead{19}   $f$ has degree $\\leq k$, where $k < n$ or $f=0$\n\\[\n\\begin{gathered}\n  f = \\sum_{j=0}^k a_j x^j; \\quad \\quad \\, g = \\sum_{j=0}^k b_j x^j \\\\\n  f+g = \\sum_{j=0}^k (a_j +b_j) x^j \\text{ even if } a_j + b_j = 0 \\text{ for any or all } j, \\, f+g \\text{ has degree } \\leq k \\text{ or } f = 0 \\\\\n\\sum_{j=0}^k c_0 a_j x^j \\in S \n\\end{gathered}\n\\]\n$f$ is spanned by $\\mathcal{B}_S = \\{ x^j \\}, \\, j = 0, 1, \\dots , k$ which is a subset of $\\mathcal{B}_{P_n}$, which is a basis for $P^n$.  Then $\\mathcal{B}_S$ is independent.  \\\\\n\\quad Then $\\mathcal{B}_S$ is a basis for $S$.  \\\\\n$dim{S} = k+1$\n\n\\exercisehead{20} Consider \n\\[\n\\begin{gathered}\n  f  +g = \\left( \\sum_{j=0}^{k-1} a_j x^j + a_k x^k  \\right) + \\left( \\sum_{j=0}^{k-1} b_j x^j + -a_k x^k \\right) = \\sum_{j=0}^{k-1} (a_j + b_j)x^j \\text{ with } a_{k-1} + b_{k-1} \\neq 0 \\\\\n  f+g \\notin S\n\\end{gathered}\n\\]\nThus $S$ is not a subspace.  \n\n\\exercisehead{21} \n\\begin{enumerate}\n\\item $\\{ 1 ,t^2, t^4 \\}$ \\\\\n$f = a_0 + a_2 t^2 + a_4 t^4$, \\quad $\\boxed{dim{S} = 3}$\n\\item $\\{ t, t^3, t^5 \\}$ \\\\\n  $f = a_1 t + a_3 t^3 + a^5 t^5$, \\quad $\\boxed{ dim{S} = 3}$\n\\item $\\{ t,t^2 \\}$ \\\\\n  $f = a_1 t + a_2 t^2$, $\\boxed{ dim{S} = 2 }$\n\\item $\\{ 1 + t, (1+t)^2 \\}$ \n\\[\na_1 (1+t) + a_2 (1+t)^2 = a_1 (1+t) + a_2 (1+2t + t^2) = (a_1 + a_2) + (a_1 + 2a_2)t + a_2 t^2\n\\]\nIf $a_1(1+t) + a_2(1+t)^2 = 0$, $a_2 = 0$, $a_1 = 0$ so $(1+t), (1+t)^2$ is independent, $\\boxed{ dim{S} = 2 }$\n\\end{enumerate}\n\n\\exercisehead{22} In this exercise, $L(S)$ denotes the subspace spanned by a subset $S$ of a linear space $V$.  \n\\begin{enumerate}\n\\item $x \\in S$, \\quad \\, $1x \\in L(S) \\Longrightarrow S \\subseteq L(S)$\n\\item If $S = \\{ x_1, \\dots, x_n \\}$ \\\\\n  \\quad $x = \\sum a_j x_j  \\in L(S)$ \\medskip \\\\\n  $S \\subseteq T \\Longrightarrow x_j \\in T$ \\\\ \n  $T$ is a subspace of $V$ \\,  $\\Longrightarrow \\sum a_j x_j \\in T$ ($T$ is closed under addition and scalar multiplication).  so $x \\in T$ \\\\\n  $\\boxed{ L(S) \\subseteq T }$\n\\item If $S$ is a subspace of $V$, $S$ is closed under addition and scalar multiplication.  \\smallskip \\\\\n  \\quad \\, Repeatedly apply addition and scalar multiplication closure for each $x_j \\in S$ and $\\forall \\, a_j \\in \\mathbb{R}$, so that $\\sum a_j x_j \\in S$, \\quad $\\forall \\, a_j \\in \\mathbb{R}$, $\\forall \\, x_j \\in S$.  \\medskip \\\\\n  $\\Longrightarrow L(S) \\subseteq S$ \\medskip \\\\\n\n$S \\subseteq L(S)$ (as proven in part(a), or part (1), of this exercise).  \\medskip \\\\\n$L(S) = S$ if $S$ is a subspace of $V$.   \\\\\n\nIf $L(S) = S$, \\, $\\forall \\, \\sum a_j x_j \\in S$, the $S$ is closed under addition and scalar multiplication.  Then $S$ is a subspace of $V$, by theorem.  \n\\item Suppose $S = \\{ x_1, x_2, \\dots, x_m \\}$ \\\\\n  Then since $S \\subseteq T$, \\, $T = \\{ x_1, x_2, \\dots, x_m, \\dots x_n \\}$ \n\\[\n\\sum_{j=1}^m a_j x_j = \\sum_{j=1}^n a_j x_J \\in L(T) \\text{ with } a_j = 0 \\text{ for } j = m+1, m+2, \\dots, n \\Longrightarrow L(S) \\subseteq L(T)\n\\]\n\\item If $x_1, x_2 \\in S \\bigcap T$, then $\\begin{aligned}\n  & x_1 \\in S \\bigcap x_2 \\in S \\\\\n  & x_1 \\in T \\bigcap x_2 \\in T\n\\end{aligned}$.  Since $S,T$ are subspaces, $x_1 + x_2, cx_1 \\in S \\bigcap x_1 + x_2, cx_1 \\in T$ \\\\\n  Then $x_1 + x_2, c x_1 \\in S \\bigcap T$.  So $S \\bigcap T$ is a subspace. \n\\item Consider $x \\in L(S \\bigcap T)$.  \\\\\n  $x = \\sum a_j x_j$; where $x_j \\in S \\bigcap T$ \\\\\n  Since $\\forall \\, x_j \\in S$, then $x \\in L(S)$.  Since $\\forall \\, x_j \\in T$, then $x\\in L(T)$.  \\\\\n\\quad Thus $x\\in L(S) \\bigcap L(T)$.  \\quad $\\Longrightarrow L(S\\bigcap T) \\subseteq L(S) \\bigcap L(T)$\n\\item Example of when $L(S\\bigcap T) \\neq L(S) \\bigcap L(T)$. \\\\\nSuppose $S = \\{ x_1, x_2 \\}$, \\, $T = \\{ x_3 \\}$ and $x_1 + x_2 = x_3$.  \\\\\n$S \\bigcap T = \\emptyset$.  $L(S \\bigcap T) = \\emptyset$, but $L(S) \\bigcap L(T) = \\{ kx_3 | k \\in \\mathbb{R} \\} = L(T)$\n\\end{enumerate}\n\n\\exercisehead{23}\n\\begin{enumerate}\n\\item $\\{ 1, e^{ax}, e^{bx} \\}$, \\, $a \\neq b$ \n\\[\n\\begin{gathered}\na_0 + a_1 e^{ax} + a_2 e^{bx} =0 \\xrightarrow{ \\frac{d}{dx} } a_1 a e^{ax} + a_2 be^{bx} = 0  \\text{ or } a_1 a = -a_2 b e^{(b-a)x}\n\\end{gathered}\n\\]\nSince $x$ arbitrary, $a_1 = a_2 = 0$.  \\\\\n$\\Longrightarrow \\{ 1, e^{ax}, e^{bx} \\}$ independent.  $\\boxed{ dim{S} = 3 }$\n\\item $\\{ e^{ax}, xe^{ax} \\}$\n\\[\na_1 e^{ax} + a_2 xe^{ax} = 0 \\text{ or } a_1 = -a_2 x\n\\]\n$x$ arbitrary, so $a_1 = a_2 = 0$.  $\\{ e^{ax}, xe^{ax} \\}$ independent.  $\\boxed{ dim{S} = 2 }$\n\\item $\\{ 1, e^{ax}, xe^{ax} \\}$\n\\[\n\\begin{gathered}\n  a_0 + a_1 e^{ax} + a_2 xe^{ax} = 0 \\xrightarrow{ \\frac{d}{dx} } aa_1 e^{ax} + a_2 e^{ax} + a_2 a x e^{ax} = 0 \\\\\n  aa_1 + a_2 + a_2 ax = 0 \\text{ or } a_2 ax = -(aa_1 + a_2) \\\\\n  x \\text{ arbitrary, so } a_2 = 0, \\, a_1 =0 \n\\end{gathered}\n\\]\nThen $a_0 =0$ and so $\\{ 1, e^{ax}, x e^{ax} \\}$ independent.  $\\boxed{ dim{S} = 3}$\n\\item $\\{ e^{ax}, xe^{ax}, x^2 e^{ax} \\}$.  \n\\[\na_0 e^{ax} + a_1 xe^{ax} + a_2 x^2 e^{ax} = 0 = a_0 + a_1 x + a_2 x^2\n\\]\n$1,x,x^2$ are a subset of independent $\\mathcal{B}_{P_n}$ and so $1,x,x^2$ are independent $\\Longrightarrow a_0 = a_1 = a_2 =0$, and so $\\{ e^{ax}, xe^{ax}, x^2 e^{ax} \\}$ independent.  $\\boxed{ dim{S} = 3}$.  \n\\item $\\{ e^x, e^{-x}, \\cosh{x} \\}$ \\\\\n  $\\cosh{x} = \\frac{e^x + e^{-x} }{ 2}$ dependent.  $\\boxed{ dim{S} = 2}$\n\\item $\\{ \\cos{x}, \\sin{x} \\}$ \n\\[\na\\cos{x} + b\\sin{x} =0 \\text{ or } b\\sin{x} = -a \\cos{x}\n\\]\nIf $\\cos{x} = 0$, then $\\sin{x} = 1$, so $b=0$.  Otherwise, \\\\\n$b\\tan{x} = -a$.  But $x$ arbitrary $\\Longrightarrow a=0, \\, b =0$ \n\nSo $\\{ \\cos{x}, \\sin{x} \\}$ independent.  $\\boxed{ dim{S} = 2}$\n\\item $a \\cos^2{x} + b\\sin^2{x} = 0$, so then if $\\cos^2{x} \\neq 0$, we have $b\\tan^2{x} = -a$.  Since $x$ is arbitrary, $a=b=0$.  Then $\\{ \\cos^2{x}, \\sin^2{x} \\}$ independent.  $\\boxed{ dim{S} = 2}$\n\\item $\\{ 1, \\cos{2x}, \\sin^2{x} \\}$ \n\\[\n\\cos{2x} = 1 - 2\\sin^2{x}\n\\]\nSo the set is dependent.  $\\boxed{ dim{S} = 2}$, since $\\{ 1, \\sin^2{x} \\}$ independent ($\\{ \\cos^2{x}, \\sin^2{x} \\}$ were independent and $1= \\cos^2{x} + \\sin^2{x}$).  \n\\item $\\{ \\sin{x}, \\sin{2x} \\}$\n\\[\na\\sin{x} + b \\sin{2x} = \\sin{x} (a+b2\\cos{x}) =0 \n\\]\nIf $\\sin{x}, \\cos{x} \\neq 0$, $a+b2\\cos{x} =0$ or $2b\\cos{x} = -a$.  Since $x$ is arbitrary, $a=b=0$  So then $\\{ \\sin{x},\\sin{2x} \\}$ is independent.  $\\boxed{ dim{S} =2}$\n\\item $\\{ e^x \\cos{x}, e^{-x} \\sin{x} \\}$\n\\[\nae^x \\cos{x} + be^{-x} \\sin{x} = 0 \\text{ or } b \\tan{x} = -a e^{2x}\n\\]\nSince $x$ arbitrary, $a=b=0$.  $\\boxed{ dim{S} =2} $\n\\end{enumerate}\n\n\\exercisehead{24}\n\\begin{enumerate}\n\\item Consider $\\mathcal{B}_S$, basis for $S$ and $\\mathcal{B}_V$ basis for $V$.  $|\\mathcal{B}_V| = n$ finite.  \\\\\n  If $S$ is infinite-dimensional, then $\\exists \\, x_{n+1} \\in \\mathcal{B}_S$ s.t. $x_{n+1} \\notin \\mathcal{B}_V$ since $\\mathcal{B}_V$ finite.  Then $\\exists \\, x_{n+1} \\in S$ s.t. $x_{n+1} \\notin V$.  But $S \\subseteq V$ \\\\\n  $\\Longrightarrow S$ is finite-dimensional.  \\\\\n\nConsider $\\mathcal{B}_S = \\{ x_1,\\dots, x_m \\}$ and $\\mathcal{B}_V = \\{ y_1,\\dots, y_n \\}$.  \\\\\n\\quad $\\forall \\, x_j$, $x_j \\in V$, since $S \\subseteq V$.  \\smallskip \\\\\nSuppose $m > n$.  Then $\\mathcal{B}_S$ linearly dependent, by Thm. 12.10 of Vol.1 (a.k.a. Thm. 1.7 of Vol. 2).  This contradicts the fact that $\\mathcal{B}_S$ is an independent basis.  $\\Longrightarrow dim{S} \\leq dim{V}$\n\\item If $S=V$, then by Thm. 12.10 of Vol.1, $\\mathcal{B}_S$ must also contain exactly $n$ vectors, since it's a basis for $V=S$.  \\\\\n\nIf $dim{S} = dim{V}$, then since $\\mathcal{B}_S$ is a set of $n$ linearly independent elements, it forms a basis for $V$. \\\\  Then $\\forall\\, y \\in V$, $y \\in L(\\mathcal{B}_S)=S$.  \\\\\n\\quad $V \\subseteq S$  $\\Longrightarrow V = S$.  \n\\item Use Thm. 12.10 of Vol.1 (a.k.a. Thm. 1.7 of Vol.2): Any set of linear independent elements is a subset of some basis for $V$.  \n\\item Consider $\\mathcal{B}_V = \\{ y_1, \\dots, y_n \\}$ \\\\\n  Suppose $\\{ y_1 + y_2, y_1 - y_2 \\} = \\mathcal{B}_S$ \\medskip \\\\\n  $y_1 + y_2, y_1 - y_2 \\notin \\mathcal{B}_V$ because if they were, they'd make $\\mathcal{B}_V$ dependent.  \n\\end{enumerate}\n\n\\section*{ 2.4 Exercises - Linear Transformations and Matrices, Null space and range, Nullity and rank }\n\n\\exercisehead{1} $T(x,y)= (y,x)$\n\\[\nT(a(x_1,x_2) +b(y_1,y_2)) = T(ax_1 + by_1, ax_2 + by_2) = (ax_2 + by_2, ax_1+by_1) = a(x_2,x_1) + b(y_2,y_1) = aT(x_1,x_2) + bT(y_1,y_2)\n\\]\n$T$ is linear.  \n\n$T(x,y) = (y,x) =0$.  $nullspace{T} = \\{ 0 \\}$; \\quad $ker{T} = 0$ \\\\\n$T(x,y) = (y,x) = y(1,0) + x(0,1)$.  $range{T} = V_2$.  $rank{T} =2$\n\n\\exercisehead{2} $T(x,y) = (x,-y)$\n\\[\nT(a(x_1,x_2) +b(y_1,y_2)) = (ax_1 + by_1, -(ax_2 + by_2)) = a(x_1,-x_2) + b(y_1,-y_2) = aT(x_1,x_2) + bT(y_1,y_2)\n\\]\n$T$ is linear.  \n\n$(x,-y) =0$.  $nullspace{T} = \\{ 0 \\}$; \\quad $ker{T} = 0$ \\\\\n$(x,-y) = x(1,0) + -y(0,1)$   $range{T} = V_2$; \\quad $rank{T} = 2$\n\n\\exercisehead{3} $T(x,y) = (x,0)$.\n\\[\nT(a(x_1,x_2)+b(y_1,y_2)) = (ax_1+by_1,0) = a(x_1,0) + b(y_1,0) = aT(x_1,x_2) + bT(y_1,y_2)\n\\]\n$T$ is linear.  \n\n$T(x,y) = (x,0) = 0$ $\\Longrightarrow x=0$, \\quad $y \\in \\mathbb{R}$.  $nullspace{T} = L(\\{ (0,1) \\})$ \\quad $ker{T}=1$ \\\\\n$T(x,y) = (x,0) = x(1,0)$  \\quad $range{T} = L(\\{ (1,0) \\})$.  $rank{T} =1$ \n\n\\exercisehead{4} $T(x,y) = (x,x)$ \n\\[\nT(a(x_1,x_2)+b(y_1,y_2)) = (ax_1+by_1,ax_1 + by_1) = a(x_1,x_1) + b(y_1,y_1) = aT(x_1,x_2) + bT(y_1,y_2)\n\\]\n$T$ is linear.  \n\n$T(x,y) = (x,x) = 0$ $\\Longrightarrow x=0$, \\quad $y \\in \\mathbb{R}$.  $nullspace{T} = L(\\{ (0,1) \\})$ \\quad $ker{T}=1$ \\\\\n$T(x,y) = (x,x) = x(1,1)$  \\quad $range{T} = L(\\{ (1,1) \\})$.  $rank{T} =1$ \n\n\\exercisehead{5} $T(x,y) = (x^2,y^2)$\n\\[\n\\begin{gathered}\nT(a(x_1,x_2)+b(y_1,y_2)) = ((ax_1+by_1)^2,(ax_2 +by_2)^2) = \\\\\n= (a^2 x_1^2,a^2 x_2^2) +(2abx_1 y_1,2abx_2 y_2) +(b^2 y_1^2,b^2 y_2^2) \\neq aT(x_1,x_2) + bT(y_1,y_2)\n\\end{gathered}\n\\]\n$T$ is not linear.  \n\n\\exercisehead{6} $T(x,y) = (e^x,e^y)$  \n\\[\nT(a(x_1,x_2) +b(y_1,y_2)) = (e^{ax_1 + by_1}, e^{ax_2 +by_2}) \\neq aT(x_1,x_2) + bT(y_1,y_2) \n\\]\n$T$ is not linear.  \n\n\\exercisehead{7} $T(x,y) = (x,1)$\n\\[\nT(a(x_1,x_2) + b(y_1,y_2) ) = (ax_1 + by_1,1) \\neq a(x_1,1) + b(y_1,1) = aT(x_1,x_2) + bT(y_1,y_2)\n\\]\n$T$ is not linear.  \n\n\\exercisehead{8} $T(x,y) = (x+1,y+1)$\n\\[\nT(a(x_1,x_2) + b(y_1,y_2)) = (ax_1 + by_1 + 1, ax_2 + by_2,1) \\neq aT(x_1,x_2) + bT(y_1,y_2)\n\\]\n$T$ is not linear.  \n\n\\exercisehead{9} $T(x,y) = (x-y,x+y)$\n\\[\n\\begin{gathered}\nT(a(x_1,x_2)+b(y_1,y_2)) = (ax_1+by_1-ax_2 - by_2,ax_1 + by_1 +ax_2 + by_2) =  \\\\\n= a(x_1-x_2,x_1+x_2) + b(y_1-y_2,y_1+y_2) = aT(x_1,x_2) + bT(y_1,y_2)\n\\end{gathered}\n\\]\n$T$ is linear.  \n\n$T(x,y) = (x-y,x+y) = 0$ $\\Longrightarrow x=y=0$, \\quad  $nullspace{T} = \\{ 0 \\}$ \\quad $ker{T}=1$ \\\\\n$T(x,y) = (x-y,x+y) = x(1,1)+y(-1,1)$  \\quad $range{T} = L(\\{ (1,1),(-1,1) \\})$.  $rank{T} =2$ \n\n\\exercisehead{10} $T(x,y) = (2x-y,x+y)$\n\\[\n\\begin{gathered}\nT(a(x_1,x_2)+b(y_1,y_2)) = (2(ax_1 + by_1) - (ax_2 + by_2), ax_1+by_1 + ax_2 +by_2) = \\\\\n = a(2x_1-x_2,x_1+x_2) + b(2y_1-y_2,y_1+y_2) = aT(x_1,x_2) + bT(y_1,y_2)\n\\end{gathered}\n\\]\n$T$ is linear.  \n\n$(2x-y,x+y) = 0$ \\quad $nullspace{T} = \\{ 0 \\}$.  \\quad $ker{T} =0$ \\\\\n$x(2,1) + y(-1,1) = (2x-y,x+y)$ \\quad $range{T} = L( \\{ (2,1), (-1,1) \\} )$.  $rank{T} = 2$\n\n\\exercisehead{11} $T$ rotates every point through the same angle $\\phi$ about the origin.  That is, $T$ maps a point with polar coordinates $(r,\\theta)$ onto the point with polar coordinates $(r,\\theta + \\phi)$, where $\\phi$ is fixed.  Also, $T$ maps $0$ onto itself.  \n\nAmazingly, $T$ \\textbf{ is linear }.  What's required to show this is persistence.  \n\n\\[\n\\begin{gathered}\n  \\begin{aligned}\n    x & = (r_1 \\cos{\\theta_1}, r_1 \\sin{\\theta_1} ) \\\\\n    y & = (r_1,\\sin{\\theta_2}, r_2 \\sin{\\theta_2})  \n\\end{aligned} \\\\\n  ax+by = (ar_1 \\cos{\\theta_1} + br_2 \\cos{\\theta_2}, ar_1 \\sin{\\theta_1} + br_2 \\sin{\\theta_2} ) \\\\\n  \\begin{aligned}\n  |ax+by|^2 & = (ar_1c_1 + br_2 c_2)^2 + (ar_1s_1 + br_2s_2)^2 = \\\\\n  & = a^2 r_1^2 c_1^2 + 2abr_1r_2 c_1c_2 + b^2 r_2^2 c_2^2 + a^2 r_1^2 s_1^2 + 2abr_1 s_1r_2 s_2 + b^2 r_2^2 s_2^2 = \\\\\n  & = a^2 r_1^2 + b^2 r_2^2 + 2abr_1 r_2 c(\\theta_1-\\theta_2)\n  \\end{aligned} \\\\\n  \\text{ argument of } ax + by = \\arctan{ \\left( \\frac{ar_1 s\\theta_1 + br_2 s\\theta_2}{ ar_1 c\\theta_1 + br_2 c\\theta_2} \\right) }\n\\end{gathered}\n\\]\nSo $|T(ax+by)| = |ax+by|$, but the argument of $T(ax+by) = \\arctan{ \\left( \\frac{ar_1 s\\theta_1 + br_2 s\\theta_2}{ ar_1 c\\theta_1 + br_2 c\\theta_2} \\right) } + \\phi$.  \n\nConsider now $aT(x) + bT(y) = a(r_1,\\theta_1+\\phi) + b(r_2,\\theta_2+\\phi)$.\n\\begin{multline*}\n  \\sqrt{ (ar_1 c(\\theta_1 + \\phi) + br_2 c(\\theta_2 + \\phi))^2 + (ar_1 s(\\theta_1+ \\phi) + br_2 s(\\theta_2 + \\phi))^2 } = \\\\\n  = \\sqrt{ (ar_1)^2 + (br_2)^2 + 2abr_1r_2(c(\\theta_1 + \\phi)c(\\theta_2 + \\phi) + s(\\theta_1 + \\phi)s(\\theta_2+\\phi) ) } = \\sqrt{ (ar_1)^2 + (br_2)^2 + 2abr_1r_2c(\\theta_1 - \\theta_2) }\n\\end{multline*}\nThe length is the same for $T(ax+by)$ and $aT(x) + bT(y)$. \n\nThe argument of $aT(x) + bT(y)$ is the following: \n\\begin{multline*}\n  \\frac{ar_1 (s\\theta_1 c\\phi + c\\theta_1 s\\phi) + br_2 (s\\theta_2 c\\phi + c\\theta_2 s\\phi) }{ ar_1 (c\\theta_1 c\\phi -s(\\theta_1) s\\phi) + br_2 (c\\theta_2 c\\phi - s\\theta_2 s\\phi) } = \\frac{ar_1 (s\\theta_1 + c\\theta_1 \\tan{\\phi}) + br_2 (s\\theta_2 + c\\theta_2 \\tan{\\phi} )}{ ar_1 (c\\theta_1 - s(\\theta_1) \\tan{\\phi}) + br_2 (c\\theta_2 - s\\theta_2 \\tan{\\phi} ) } = \\\\\n  = \\frac{ ar_1 s\\theta_1 + br_2 s\\theta_2 + ar_1 c\\theta_1 \\tan{\\phi} + br_2 c\\theta_2 \\tan{\\phi} }{ ar_1 c\\theta_1 + br_2 c\\theta_1 - ar_1 s\\theta_1 \\tan{\\phi} - br_2 s\\theta_2 \\tan{\\phi} }\n\\end{multline*}\n\nBeforehand, recall this trigonometric identity:\n\\[\n\\tan{(x+y)} = \\frac{ \\sin{(x+y)} }{\\cos{ (x+y)} } = \\frac{ \\sin{x} \\cos{y} + \\sin{y} \\cos{x} }{ \\cos{x} \\cos{y} - \\sin{x} \\sin{y} } = \\frac{ \\tan{x} + \\tan{y} }{ 1 - \\tan{x} \\tan{y} }\n\\]\n\nThus \n\\begin{multline*}\n  \\tan{ \\left( \\arctan{ \\left( \\frac{ar_1 s\\theta_1 + br_2 s\\theta_2}{ ar_1 c\\theta_1 + br_2 c\\theta_2} \\right) } + \\phi \\right) } = \\frac{ \\frac{ ar_1 s\\theta_1 + br_2 s\\theta_2}{ ar_1 c\\theta_1 + br_2 c\\theta_2 } + \\tan{\\phi_1} }{ 1 - \\left( \\frac{ ar_1 s\\theta_1 + br_2 s\\theta_2}{ ar_1 c\\theta_1 + br_2 c\\theta_2 } \\right) \\tan{\\phi} } = \\\\\n  = \\frac{ ar_1 s\\theta_1 + br_2 s\\theta_2 + ar_1 c\\theta_1 \\tan{\\phi} + br_2 c\\theta_2 \\tan{\\phi} }{ ar_1 c\\theta_1 + br_2 c\\theta_1 - ar_1 s\\theta_1 \\tan{\\phi} - br_2 s\\theta_2 \\tan{\\phi}} \n\\end{multline*}\nSo the arguments for $T(ax+by)$ and $aT(x)+bT(y)$ are, amazingly, the same, modulo some $2\\pi$ periodicity.    \n\nThus, \\emph{rotations are linear transformations.}  \n\n$nullspace{T} = \\{ 0 \\}$.  $null{T} =0$ \\\\\n$range{T} = \\{ (r,\\theta) \\}$.  $rank{T} = 2$\n\n\\exercisehead{12} $T$ maps each point onto its reflection with respect to a fixed line through the origin.  \\\\\nWe showed above that rotations are linear transformations.  Then without loss of generality, consider reflection about the $x$-axis.  \n\\[\n\\begin{gathered}\n  T(a(x_1,x_2) + b(y_1,y_2)) = (ax_1 + by_1,-ax_2 -by_2) = a(x_1,-x_2) + b(y_1,-y_2) \\\\\n  aT(x_1,x_2) + bT(y_1,y_2) = a(x_1,-x_2) + b(y_1,y-2)\n\\end{gathered}\n\\]\nSo reflection about the $x$ axis is linear.  \\\\\nSuppose $R$ is the rotation of the fixed line into the $x$-axis and $R$ is length preserving.  Then for $R^{-1}TR$, reflection about any fixed axis, ($R^{-1}$ is linear too, since it's just a rotation in the opposite direction of $R$)\n\\[\nR^{-1}TR(ax+by) = R^{-1}T(aRx+bRy) = R^{-1}(aTRx+bTRy) = aR^{-1}TRx + bR^{-1}TRy\n\\]\n$T$ is linear. \n\n$null{T} = 0$  \\quad $nullspace{T} =\\{ 0 \\}$ \\\\\n$rank{T} =2$ \\quad $range{T} = \\{ (x,y) \\}$\n\n\\exercisehead{13} $T$ maps every point onto the point $(1,1)$.  \\\\\n$T(ax+by) = (1,1) \\neq aT(x) + bT(y) = (a+b)(1,1)$ \\\\\n$T$ is nonlinear.  \n\n\\exercisehead{14} $T(r,\\theta) = (2r, \\theta)$ \\\\\n\\[\n\\begin{gathered}\nT(x_1)+T(x_2) = 2 r_1 e^{i \\theta_1} + 2 r_2 e^{i \\theta_2} = 2 (r_1 e^{i \\theta} + r_2 e^{i \\theta_2} ) \\\\\nT(x_1+y_1) = T(r_1 e^{i \\theta_1} + r_2 e^{i \\theta_2} ) \\text{ so } \\\\\n|r_1 e^{i \\theta_1} + r_2 e^{i \\theta_2} | = \\sqrt{ r_1^2 +r_2^2 + 2 r_1 r_2 \\cos{(\\theta_1 - \\theta_2)} } = |T(x_1)+T(x_2)| \\\\\n\\text{ we see that the argument remains unchanged, while the magnitude is multiplied by $2$ in each case } \\\\\n\\begin{aligned}\n  & null T = 0 \\quad & nullspace T = \\{ 0 \\} \\\\\n  & rank T = 2 \\quad & range T = \\{ (r,\\theta) \\} \n\\end{aligned}\n\\end{gathered}\n\\]\n\n\\exercisehead{15} $T (a(r,\\theta) ) = (ar, 2 \\theta) = a(r,2 \\theta) = a T(r,\\theta) $.  \\\\\nConsider this counterexample, where $x_1 = 1 \\vec{e}_x, x_2 = 1 \\vec{e}_x $.  Not linear.  \n\n\\exercisehead{16} $T(x,y,z) = (z,y,x)$.  \n\\[\n\\begin{gathered}\n  T(ax) = aT(x), T(x_1+ x_2, y_1+y_2, z_1 +z_2) = (z_1,y_1,x_1) + (z_2, y_2,x_2) \\Longrightarrow \\text{ linear } \\\\ \n  T(x) = 0 \\text{ when } x = 0 \\\\\n  \\begin{aligned}\n    & nullspace T = \\{ 0 \\} \\quad & range T = V_3  \\\\\n    & null T = 0 & rank T = 3\n  \\end{aligned}\n\\end{gathered}\n\\]\n\n\\exercisehead{17} $T(x,y,z) = (x,y,0) $.  \n\\[\n\\begin{gathered}\n\\begin{aligned}\n  T(a(x,y,z)) & = a(x,y,0) = aT(x,y,z); T(x_1+x_2, y_1 +y_2, z_1 +z_2 ) = \\\\ \n  & = (x_1 +x_2, y_1+y_2, 0) = T(x_1,y_1,z_1) = T(x_2,y_2,z_2) \n\\end{aligned} \\\\ \n\\Longrightarrow \\text{ $T$ linear } \\\\\n  T(x,y,z) = 0 \\text{ if } x = y = 0 \\\\\n\\begin{aligned}\n  & nullspace T = L(\\{ (0,0,1) \\}) \\quad & null T = 1  \\\\\n  & range T = L(\\{ (1,0,0),(0,1,0) \\}) & rank T = 2 \n\\end{aligned}\n\\end{gathered}\n\\]\n\n\\exercisehead{18} $T(x,y,z) = (x,2y,3z)$.  \n\\[\n\\begin{gathered}\n  T(ax) = (ax, 2ay, 3az) = aT(x); T(x_1+x_2) = (x_1+ x_2, 2(y_1 +y_2), 3(z_1 +z_2)) = T(x_1)+T(x_2) \\\\\n  T(x) = 0 \\text{ when } x = y= z = 0 \\\\ \n  \\begin{aligned}\n&    nullspace T = \\{ 0 \\}  \\quad & null T = 0 \\\\\n    & range T = V_3 \\quad & rank T = 3 \n  \\end{aligned}\n\\end{gathered}\n\\]\n\n\\exercisehead{19} $T(x,y,z) = (x,y,1)$.  \\\\\n$T(x_1) + T(x_2)  = (x_1+x_2, y_1+y_2, 2) \\neq T(x_1+x_2)$ \n$T$ is not linear.  \n\n\\exercisehead{20} $T(x,y,z) = (x+1,y+1,z-1)$\n\\[\n\\begin{gathered}\n  T(ax+by) = (ax_1+by_1+1, ax_2 + by_2 +1, ax_3 + by_3 - 1) \\neq aT(x)  +bT(y) = \\\\\n  = a(x_1+1,x_2+1, x_3-1) + b(y_1 +1,y_2 + 1, y_3-1)\n\\end{gathered}\n\\]\n\n\\exercisehead{21} $T(x,y,z) = (x+1,y+2,z+3)$\n\\[\nT(ax+by) = (ax_1+by_1+1,ax_2+by_2 +2,ax_3+by_3+3) \\neq aT(x) + bT(y) = a(x_1+1,x_2+2,x_3+3) + b(y_1+1,y_2+2,y_3+3)\n\\]\n\n\\exercisehead{22} $T(x,y,z) = (x,y^2,z^3)$\n\\[\n\\begin{gathered}\n  T(ax+by) = (ax_1+by_1,(ax_2+by_2)^2,(ax_3+by_3)^3) = (ax_1+by_1,a^2 x_2^2 + 2abx_2y_2 + b^2y_2^2, a^2x_3^2+2abx_3y_3+b^2y_3^2) \\neq \\\\\n  \\neq aT(x) + bT(y)  = a(x_1,x_2^2,x_3^2) + b(y_1,y_2^2,y_3^2) \n\\end{gathered}\n\\]\n\n\\exercisehead{23} $T(x,y,z) = (x+z,0,x+y)$\n\\[\nT(ax+by) = (ax_1+by_1+ax_3 +by_3,0,ax_1+by_1+ax_2+by_2) = a(x_1+x_3,0,x_1+x_2) + b(y_1+y_3,0,y_1+y_2) = aT(x) + bT(y)\n\\]\n$T$ is linear.  \n\n$(x+z,0,x+y) =0$ \\quad \\, $\\begin{aligned}\n  x & = -z \\\\\n  x & = -y\n\\end{aligned}$ \\quad $(x,y,z) = x(1,-1,-1) \\Longrightarrow nullspace{T} = L(\\{ (1,-1,-1) \\})$ \\quad $ker{T} =1$ \\\\\n$(x+z,0,x+y) = (x+z)(1,0,0) + (x+y)(0,0,1)$ \\quad $range{T} = L(\\{ (1,0,0),(0,0,1) \\})$, \\quad $rank{T} =2$\n\n\\exercisehead{24} \\quad \\\\ $\\begin{aligned}\n  p(x) & = \\sum_{j=0}^n a_j x^j \\\\\n  q(x) & = \\sum_{j=0}^n b_j x^j \n\\end{aligned}$ \\quad \\quad $\\begin{gathered}\n  (p+q)(x) = \\sum_{j=0}^n (a_j +b_j)x^j \\\\\n  cp(x) = c\\sum_{j=0}^n a_j x^j = \\sum_{j=0}^n ca_j x^j\n\\end{gathered}$ \\quad \\quad \\\\ \n$\\begin{gathered}\n  T(p+q) = \\sum_{j=0}^n (a_j +b_j)(x+1)^j = \\sum_{j=0}^n a_j (x+1)^j + \\sum_{j=0}^n b_j(x+1)^j = T(p) + T(q) \\\\\n  T(cp) = \\sum_{j=0}^n ca_j (x+1)^j = c \\sum_{j=0}^n a_j(x+1)^j = cT(p)\n\\end{gathered}$\\\\\n$T$ linear.  \n\nConsider $\\sum_{j=0}^n a_j (x+1)^j =0$.  Apply differentiation repeatedly to get $a_j =0, \\, \\forall \\, j=0,\\dots,n$.  \\\\ $nullspace{T} = \\{ 0 \\}$.  \\quad $null{T} =0$.  \\\\\n$\\sum_{j=0}^n a_j(x+1)^j = \\sum_{j=0}^n b_j x^j $.  $range{T} = L(\\{(x+1)^j| j=0,\\dots, n \\})$;  \\quad $rank{T} = n+1$\n\n\\exercisehead{25} On $(-1,1)$, $f \\in V; \\quad g = T(f)$, $g(x) = xf'(x)$ \n\\[\n\\begin{gathered}\n  T(f+g) = x(f'+g') = xf' + xg' = T(f) + T(g) \\\\\n  T(af) = x(af)' = axf' = aT(f) \n\\end{gathered}\n\\]\n$T(f) = xf'(x) = 0$  $x$ is arbitrary, consider $x\\neq 0$.  $f'(x) =0 \\Longrightarrow f(x) = c_0$.   \\\\\n$nullspace{T} = \\{ 1 \\}$, \\quad $null{T} = 1$ \\\\\n$range{T} = V$ \\quad $rank{T} = dim{V} -1 \\to \\infty$\n\n\\exercisehead{26} $g(x) = \\int_a^b f(t) \\sin{ (x-t)} dt$ for $a\\leq x \\leq b$ \n\\[\n\\begin{gathered}\n  T(f+g) = \\int_a^b (f(t)+g(t)) \\sin{(x-t)} dt = \\int_a^b f(t) \\sin{(x-t)} dt + \\int_a^b g(t) \\sin{(x-t)} dt \\\\\n  T(cf) = \\int_a^b cf(t) \\sin{(x-t)} dt \n\\end{gathered}\n\\]\n$T$ is linear.  \n\n\\[\n\\begin{gathered}\n  g(x) = \\int_a^b f(t) (s(x) c(t) - c(x) s(t))dt = s(x) \\int_a^b f(t) c(t) dt - c(x) \\int_a^b f(t) s(t) dt = k_1s(x) + k_2c(x)  \\\\\n  Range{T} = L(\\{ \\sin{x},\\cos{x} \\}); \\quad \\, rank{T} = 2\n\\end{gathered}\n\\]\nFor the nullspace, now $g(x) = s(x) \\int_a^b f(t) c(t) dt - c(x) \\int_a^b f(t) s(t) dt$.  If we take a look at \\textbf{ Exercise 29} of this section, then we see the \\textbf{answer: by the orthogonality of $\\sin$'s and $\\cos$'s}, $\\sin{nt}$ and $\\cos{nt}$ will be orthogonal to $\\cos{t}$ and $\\sin{t}$ for $n =2,\\dots$.  So depending upon $a$ and $b$, at least the integration over a period of $1$ will result in zero for both $\\int f c$ and $\\int f s$.  Then for the ``ends'' of the integration bound that don't make a full period, make $f(t) =0$.  Since $n=2,\\dots \\to \\infty$ for $\\sin{nt}$, $\\cos{nt}$ for the choice of $f(t)$, \\\\\n$nullspace{T} = L(\\{ \\sin{nt},\\cos{nt}| n =2,\\dots \\})$, \\quad \\, $ker{T} = \\infty$\n\n\\exercisehead{27} $T(y) = y'' + Py' + Qy$, $P,Q$ fixed constants.  \\\\\n\\begin{align*} \n T(a y_1 + b y_2) & = a y_1'' + by_2 '' + P(ay_1' + by_2') + Q(ay_1 + by_2 ) = \\\\\n & a(y_1''+ Py_1' +Qy_1 ) + b(y_2''+Py_2' + Qy_2 ) = aT(y_1) +bT(y_2) \\\\ \\\\\n & \\text{ $T$ is linear } \\\\\n & \\begin{aligned}\n   & nullspace T = L(\\{ x,1 \\}) \\quad & null{T} = 2 \\\\\n   & range T = V \\quad & rank T = \\infty \n\\end{aligned}\n\\end{align*}\n\n\\exercisehead{28} If $x=x_k$ is a convergent sequence with limit $a$, by definition, \n\\[\n\\forall n \\in \\mathbb{N}, \\exists m = m(n) \\in \\mathbb{N} \\text{ such that } |a -x_k| < \\frac{1}{n} \\, \\forall k \\geq m \n\\]\n\\[\n\\begin{gathered}\n  T(x) = y_k; cT(x) = cy_k = c(a- x_k) = ca - cx_k \\\\ \n  \\text{ ($cx_k$ understood to mean that each $x_k$ term in the sequence is multiplied by $c$) } \\\\\n  \\begin{aligned}\n    &\\text{ Consider } |cx_k - ca | = |c| |x_k -a | < \\frac{ |c| }{ n} \\text{ for } k \\geq m \\\\\n    & \\text{ Consider } \\frac{n}{ |c|} = n_1.  \\exists m_1 = m_1(n_1) \\text{ such that } |cx_k - ca| < \\frac{1}{n_1} \n  \\end{aligned} \\\\\n  \\text{ Thus $cx_k$ is convergent with limit $ca$ and so $T(cx) = cT(x)$. }\n\\end{gathered}\n\\]\n\\[\n\\begin{gathered}\n\\text{ Consider two convergent sequences $x_k$ and $y_k$ with limits $a$ and $b$ respectively.  Then by definition, } \\\\\n\\begin{aligned}\n  & \\forall n \\in \\mathbb{N}, \\exists m_1 = m_1(n) \\in \\mathbb{N}, |a-x_k| < \\frac{1}{2n}, k \\geq m_1 \\\\\n  & \\forall n \\in \\mathbb{N}, \\exists m_2 = m_2(n) \\in \\mathbb{N}, |b-y_k| < \\frac{1}{2n}, k \\geq m_2\n\\end{aligned} \\\\\n\\text{ For } k \\geq \\max(m_1,m_2) \\\\ \n|a+b - (x_k + y_k) | = |(a- x_k) + (b- y_k )| \\leq |a-x_k| + |b- y_k| < \\frac{1}{2n} + \\frac{1}{2n} = \\frac{1}{n} \\\\\n\\text{ so when we consider $T(x+y)$, $T(x+y) = a+b - (x+y)$, } \\\\\n\\text{ with $a +b - (x+y)$ convergent sequence defined as above, with limit $0$. } \\\\\n\\text{ so } T(x+y) \\text{ is convergent with limit $0$ just like $T(x)+T(y)$.  $T$ is linear. }\n\\end{gathered}\n\\]\n\nWe consider a convergent sequence to be a zero if it is an additive identity to each term in the sequence.  Then $nullspace T = \\text{ space of all sequences consisting of the same term for each term }$.  Also, $range T =$ space of all convergent sequences with limit $0$. \n\n\\exercisehead{29} \n\\begin{enumerate}\n\\item \\[\n\\begin{gathered}\n  \\text{ If } \\int_{-\\pi}^{\\pi} f = \\int_{-\\pi}^{\\pi} fc = \\int_{-\\pi}^{\\pi} fs = 0 \\text{ and } \\int_{-\\pi}^{\\pi} g = \\int_{-\\pi}^{\\pi} gc = \\int_{-\\pi}^{\\pi} gs = 0 \\\\\n  \\int_{-\\pi}^{\\pi} f +g = \\int_{-\\pi}^{\\pi} (f+g)c = \\int_{-\\pi}^{\\pi} (f+g)s = 0 \\text{ and } \\int_{-\\pi}^{\\pi} kf = \\int_{-\\pi}^{\\pi} kfc = \\int_{-\\pi}^{\\pi} kfs = 0 \n\\end{gathered}\n\\]\n(by linearity of integration operation).  Then $S$ is closed under addition and scalar multiplication.  $S$ is a subspace of $V$.  \n\\item \\[\n\\begin{aligned}\n  & \\int_{-\\pi}^{\\pi} c(nt) = \\left. \\frac{1}{n} s(nt) \\right|_{-\\pi}^{\\pi} = 0  \\\\\n  & \\int_{-\\pi}^{\\pi} s(nt) = \\left. \\frac{-c(nt)}{n} \\right|_{-\\pi}^{\\pi} = \\frac{ - (c(n\\pi) - c(-n\\pi))}{n} = 0 \n\\end{aligned}\n\\]\nIn general,\n\\[\n\\begin{aligned}\n & \\int_{-\\pi}^{\\pi} c(nt) c(mt) = \\int_{-\\pi}^{\\pi} \\frac{1}{2} (\\cos{(n-m)t} + \\cos{(n+m)t} ) dt = 0 + 0 = 0  \\\\\n & \\int_{-\\pi}^{\\pi} s(nt) c(mt) = \\int_{-\\pi}^{\\pi} \\frac{1}{2} (\\sin{(n+m)t} + \\sin{(n-m)t} ) dt = 0 + 0 = 0 \\\\\n & \\int_{-\\pi}^{\\pi} s(nt) s(mt) = \\int_{-\\pi}^{\\pi} \\frac{1}{2} (\\cos{(n-m)t} - \\cos{(n+m)t} ) dt = 0 + 0 = 0 \n\\end{aligned}\n\\]\nSo $S$ contains the functions $f(x) = \\cos{nx}$ and $f(x) = \\sin{nx}$, since they satisfy the requirements.  \n\\item As seen above, the set $\\mathcal{B}_S = \\{ \\sin{nx},\\cos{nx} | n = 2, \\dots \\}$ consists of orthogonal functions with an inner product defined as $\\int$ over a period.  Thus, they are independent of each other (orthogonal elements are independent).  They belong to $S$ and $S$, being a subspace, must include all linear combinations of them, and so $S$ is at least infinitely dimensional, since it must contain $\\mathcal{B}_S$ in its basis.  \n\\item \\[\n\\begin{aligned}\n  T(V) & = g(x) = \\int_{-\\pi}^{\\pi} (1+\\cos{(x-t)})f(t) dt = \\int_{-\\pi}^{\\pi} (1+\\cos{x}\\cos{t} + \\sin{x}\\sin{t})f(t) dt = \\\\\n  & = \\int_{-\\pi}^{\\pi} f(t) dt + \\left( \\int_{-\\pi}^{\\pi} \\cos{t} f(t) dt \\right) \\cos{x} + \\left( \\int_{-\\pi}^{\\pi} f(t) \\sin{t} dt \\right) \\sin{x} \n\\end{aligned}\n\\]\n$\\mathcal{B}_{T(V)} = \\{ 1, \\cos{x}, \\sin{x} \\}$; \\quad $rank{T(V)} = 3 $\n\\item $T(S) = 0 \\Longrightarrow nullspace{T} = S$\n\\item $T(f) = cf$.  Note that $cf \\in \\mathcal{B}_{T(V)}$.  \n\\[\n\\boxed{\n\\begin{aligned}\n  T(1) & = 2\\pi (1) \\\\\n  T(s) & = \\pi s \\\\\n  T(c) & = \\pi c\n\\end{aligned}\n}\n\\]\n\\end{enumerate}\n\n\\exercisehead{30} We want the following: Let $T: V\\to W$ be a linear transformation of a linear space $V$ into a linear space $W$.  If $V$ is infinite-dimensional, prove that at least one of $T(V)$, or $N(T)$, is infinite-dimensional.  \n\nAssume $dim{N(T)} = k, \\, dim{T(V)} = r$.  \\\\\nLet $e_1,\\dots, e_k$ be a basis for $N(T)$.  \\\\\nLet $e_1, \\dots, e_k, e_{k+1}, \\dots, e_{k+n}$ be independent elements in $V$, where $n>r$. \\smallskip \\\\\nConsider $x = \\sum_{j=1}^{k+n} a_j e_j$\n\\[\nT(x) = a_j \\sum_{j=1}^{k+n} T(e_j) = a_j \\sum_{j=k+1}^{k+n} T(e_j) (\\text{since } e_1, \\dots, e_k \\in N(T) ) \n\\]\n$x\\in V$, so $T(x) \\in T(V)$.  Since $dim{T(V)} = r$, and $n>r$, $\\{ T(e_j) | j = k+1, \\dots, k+n \\}$ must be dependent (Apostol's Thm.1.5 of Vol.2: any set of $r+1$ elements of a $dim = r$ space is dependent).  \\smallskip \\\\\nThen $\\exists \\, \\{ a_j \\}$, $a_j$'s not all zero, s.t. \n\\[\n\\begin{gathered}\n  \\sum_{j=k+1}^{k+n} a_j T(e_j) = T \\sum_{j=k+1}^{k+n} (a_j e_j) = 0 \\\\\n \\Longrightarrow \\sum_{j=k+1}^{k+n} a_j e_j \\in N(T) \\text{ so } \\sum_{j=k+1}^{k+n} a_j e_J = \\sum_{j=1}^n a_j e_j \n\\end{gathered}\n\\]\n $\\Longrightarrow \\sum_{j=1}^{k+n} a_j e_j =0$ is a nontrivial representation of $0$.  Then $e_1, \\dots, e_{k+n}$ are dependent.  Contradiction.  \n\n\n%-----------------------------------%-----------------------------------%-----------------------------------\n\\section*{ 2.8 Exercises - Introduction, Motivation for the choice of axioms for a determinant function, A set of axioms for a determinant function, Computation of determinants, }\n%-----------------------------------%-----------------------------------%-----------------------------------\n\\exercisehead{1} $V = \\{ 0,1 \\}$\n\\[\n\\begin{aligned}\n  T_1(0,1) & = 0,0 \\\\\n T_2(0,1) & = 0,1 \\\\\n T_3(0,1) & = 1,0 \\\\\n T_4(0,1) & = 1,1 \n\\end{aligned}\n\\quad \\quad \\quad \n\\begin{matrix}\n  0,1 & T_1 & T_2 & T_3 & T_4 \\\\\n  T_1 & 0,0 & 0,0 & 1,0 & 0,0 \\\\\n  T_2 & 0,0 & 0,1 & 1,0 & 1,1 \\\\\n  T_3 & 1,1 & 1,0 & 0,1 & 0,0 \\\\\n  T_4 & 1,1 & 1,1 & 1,1 & 1,1 \n\\end{matrix}\n\\]\n$T_2, T_3$ are one-to-one, by inspection.  $T_2^{-1} = T_2$; $T_3^{-1} = T_3$\n\n\\exercisehead{2} $V = \\{ 0,1,2 \\}$.  Note, there are obviously $3^3 =27$ possible ranges and thus $27$ possible functions (since for each element in $V$, there are $3$ possible values it could be mapped to).  \\\\\nConsider only the $6$ that are one-to-one (choice of $3$ values, then $2$ values, then $1$ value at each subsequent stage).  \n\n\\[\n\\begin{aligned}\n  T_1(0,1,2) & = 0,1,2 \\\\\n  T_2(0,1,2) & = 0,2,1 \\\\\n  T_3(0,1,2) & = 1,0,2 \\\\\n  T_4(0,1,2) & = 1,2,0 \\\\\n  T_5(0,1,2) & = 2,0,1 \\\\\n  T_6(0,1,2) & = 2,1,0 \n\\end{aligned}\n\\quad \\quad \\quad \\begin{matrix}\n  0,1,2 & T_1 & T_2 & T_3 & T_4 & T_5 & T_6 \\\\\n  T_1 & 0,1,2 & 0,2,1 & 1,0,2 & 1,2,0 & 2,0,1 & 2,1,0 \\\\\n  T_2 & 0,2,1 & 0,1,2 & 2,0,1 & 2,1,0 & 1,0,2 & 1,2,0 \\\\\n  T_3 & 1,0,2 & 1,2,0 & 0,1,2 & 0,2,1 & 2,1,0 & 2,0,1 \\\\\n  T_4 & 1,2,0 & 1,0,2 & 2,1,0 & 2,0,1 & 0,1,2 & 0,2,1 \\\\\n  T_5 & 2,0,1 & 2,1,0 & 0,2,1 & 0,1,2 & 1,2,0 & 1,0,2 \\\\\n  T_6 & 2,1,0 & 2,0,1 & 1,2,0 & 1,0,2 & 0,2,1 & 0,1,2 \n\\end{matrix}\n\\quad \\quad \\quad \n\\begin{aligned}\nT_1^{-1} & = T_1 \\\\\nT_2^{-1} & = T_2 \\\\\nT_3^{-1} & = T_3 \\\\\nT_4^{-1} & = T_5 \\\\\nT_5^{-1} & = T_4 \\\\\nT_6^{-1} & = T_6 \\\\\n\\end{aligned}\n\\]\n\n\\exercisehead{3} $T(x,y) = (y,x)$\nSuppose $T(x_1,y_1) = (y_1,x_1) = T(x_2,y_2) = (y_2,x_2)$.  \\\\\nThen $y_1 = y_2$, $x_1 = x_2$ $\\to (x_1,y_1) = (x_2,y_2)$\n\n$\\boxed{ T \\text{ is one-to-one on $V$ }; \\quad \\quad T(V_2) = V_2, \\, (u,v) = (y,x) }$ \\\\\n$\\boxed{ T^{-1} = T }$ (by inspection).  \n\n\\exercisehead{4} $T(x,y) = (x,-y)$ \\\\\nSuppose $T(x_1,y_1) = (x_1,-y_1) = T(x_2,y_2) = (x_2,-y_2)$ \\\\\nThen $x_1= x_2$, $-y_1 = -y_2$ or $y_1 = y_2$ $\\Longrightarrow (x_1,y_1) = (x_2,y_2)$ \\\\\n$\\boxed{ T \\text{ is one-to-one on $V$ }, \\quad \\quad T(V_2) = V_2, \\, (u,v) = (x,-y) }$ \\\\\n$\\boxed{ T^{-1} = T }$\n\n\\exercisehead{5} $T(x,y) = (x,0)$.   \\\\\nNote that $T(x,1) = (x,0) = T(x,2)$.  $T$ is not one-to-one.  \n\n\\exercisehead{6} $T(x,y) = (x,x)$.  Note that $T(x,1) = T(x,2) = (x,x)$.  $T$ is not one-to-one.  \n\n\\exercisehead{7} $T(x,y) = (x^2,y^2)$.  $T(x,y) = T(x,-y) = (x^2, (-y)^2) = (x^2, y^2)$.  $T$ is not one-to-one.  \n\n\\exercisehead{8} $T(x,y) = (e^x,e^y)$.  \\\\\nSuppose $T(x_1,y_1) = T(x_2,y_2)$.  \\\\\nThen $e^{x_1} = e^{x_2}$, $e^{y_1} = e^{y_2}$ and since $e^x$ is one-to-one, $\\forall \\, x \\in \\mathbb{R}$, $x_1 = x_2$.  \\\\\n$\\boxed{ \\text{ $T$ is one-to-one }}$.  $u=e^x, \\, v = e^y$, $u,v \\in \\mathbb{R}^+$.  $\\boxed{ T^{-1}(x,y) = (\\ln{x}, \\ln{y}) }$\n\n\\exercisehead{9} $T(x,y) = (x,1)$\n$T(x,1) = T(x,2) = (x,1)$, so $T$ is not one-to-one.  \n\n\\exercisehead{10} $T(x,y) = (x+1,y+1)$.  \\\\\nIf $T(x_1,y_1) = (x_1 + 1, y_1 + 1) = T(x_2,y_2) = (x_2 +1,y_2+1)$, \\\\\n\\quad then $x_1 = x_2, \\, y_1 = y_2$, $(x_1,y_1) = (x_2,y_2)$.  $T$ is one-to-one.  \\\\\n$u = x+1, \\, v = y+1$.  $T^{-1}(x,y) = (x-1,y-1)$\n\n\\exercisehead{11} $T(x,y) = (x-y,x+y)$.   \\\\\nIf $T(x_1,y_1) = (x_1 - y_1, x_1 + y_1) = T(x_2,y_2) = (x_2 - y_2, x_2 + y_2)$  \\\\\n$\\begin{aligned}\n  x_1 - y_1 & = x_2 - y_2 \\\\\n  x_1 + y_1 & = x_2 + y_2 \n\\end{aligned}$ \\quad then $x_1 = x_2, \\, y_1 = y_2$.  $T$ is one-to-one.  \n\n$\\begin{aligned}\n  u & = x - y \\\\\n  v & = x+y \n\\end{aligned}$ \\quad $T(V_2) = L(\\{ (1,1), (-1,1) \\} )$; $T^{-1}(x,y) = \\left( \\frac{x+y}{2} , \\frac{-x+y}{2} \\right)$\n\n\\exercisehead{12} $T(x,y) = (2x- y, x+y)$ \\\\\nIf $T(x_1,y_1) = (2x_1 - y_1, x_1+ y_1) = T(x_2, y_2) = (2x_2 -y_2, x_2 + y_2) $  \\\\\n$\\begin{aligned}\n  2x_1 - y_1 & = 2x_2 - y_2 \\\\\n  x_1 + y_1 & = x_2 + y_2 \n\\end{aligned}$ \\quad so $\\begin{aligned}\n  x_1 & = x_2 \\\\\n y_1 & = y_2 \n\\end{aligned}$ \\quad $T$ is one-to-one.  \n\n$\\begin{aligned}\n  u & = 2x -y \\\\\n  v & = x+y \n\\end{aligned}$ \\quad $T(V_2) = L(\\{ (2,1), (-1,1) \\} )$.  $T^{-1}(x,y) = \\left( \\frac{x+y}{3} , \\frac{x-2y}{-3} \\right)$\n\n\\exercisehead{13} $T(x,y,z) = (z,y,x)$ \\\\\nIf $T(x_1,y_1,z_1) = (z_1,y_1,x_1) = T(x_2,y_2,z_2) = (z_2,y_2,x_2)$ \\\\\n\\quad then $\\begin{aligned}\n  z_1 & = z_2 \\\\\n  y_1 & = y_2 \\\\\n  x_1 & = x_2 \n\\end{aligned}$ \\, $\\Longrightarrow T$ is one-to-one.  \\\\\n$T(V_3) = V_3$, $u=z, \\, v = y, \\, w = z$.  $T^{-1} = T$\n\n\\exercisehead{14} $T(x,y,z) = (x,y,0)$ \\\\\n$T(x,y,1) = T(x,y,2) = (x,y,0)$.  $T$ is not one-to-one.  \n\n\\exercisehead{15} $T(x,y,z) = (x,2y, 3z)$ \\\\\n$T(x_1,y_1,z_1) = (x_1,2y_1,3z_1) = T(x_2,y_2,z_2) = (x_2,2y_2,3z_2)$\n\\[\n\\begin{aligned}\n  x_1 & = x_2 \\\\\n  2y_1 & = 2y_2 \\\\\n  3z_1 & = 3z_2 \n\\end{aligned}\n\\quad \\Longrightarrow \n\\begin{aligned}\n  x_1 & = x_2 \\\\\n  y_1 & = y_2 \\\\\n  z_1 & = z_2 \n\\end{aligned} \\quad \\Longrightarrow \\text{ $T$ is one-to-one }\n\\]\n\\[\n\\begin{aligned}\n  u & = x \\\\\n  v & = 2y \\\\\n  w & = 3z \n\\end{aligned} \\quad T(V_3) = V_3 \\quad T^{-1}(x,y,z) = \\left( x, \\frac{y}{2}, \\frac{z}{3} \\right)\n\\]\n\n\\exercisehead{16} $T(x,y,z) = (x,y,x+y+z)$\n$T(x_1,y_1,z_1) = (x_1,y_1,x_1+ y_1+z_1) = T(x_2,y_2,z_2) = (x_2,y_2,x_2+y_2+z_2) $ \\\\\n\\[\n\\begin{aligned}\n  x_1 & = x_2 \\\\\n  y_1 & = y_2 \\\\\n  x_1 + y_1 + z_1 & = x_2 + y_2 + z_2 \n\\end{aligned}\n\\quad \\Longrightarrow z_1 = z_2 \\text{ so $T$ is one-to-one }\n\\]\n\n\\exercisehead{17} $T(x,y,z) = (x+1,y+1,z-1)$ \\\\\n$T(x_1,y_1,z_1) = (x_1 + 1, y_1 + 1 , z_1 -1) = T(x_2,y_2,z_2) = (x_2 + 1 , y_2 + 1 , z_2 - 1 )$ \n\\[\n\\Longrightarrow \\begin{aligned}\n  x_1 & = x_2 \\\\\n  y_1 & = y_2 \\\\\n  z_1 & = z_2 \n\\end{aligned} \\quad \\, \\text{ $T$ is one-to-one }\n\\]\n$T(V_3) = V_3 + (1,1,-1)$; $\\boxed{ T^{-1}(x,y,z) = (x-1,y-1,z+1) }$\n\n\\exercisehead{18} $T(x,y,z) = (x+1,y+2,z+3)$ \\\\\n$T(x_1,y_1,z_1) = (x_1 + 1, y_1 + 2, z_1 + 3) = T(x_2,y_2,z_2) = (x_2 + 1, y_2 + 2, z_2 + 3)$\n\\[\n\\Longrightarrow \\begin{aligned}\n  x_1 & = x_2 \\\\\n  y_1 & = y_2 \\\\\n  z_1 & = z_2 \n\\end{aligned}\n\\quad \\quad \\text{ $T$ is one-to-one }\n\\]\n$T(V_3) = V_3 + (1,2,3) $  \\quad \\, $\\boxed{ T^{-1}(x,y,z) = (x-1,y-2,z-3) }$\n\n\\exercisehead{19} $T(x,y,z) = (x,x+y, x+y+z)$ \\\\\n$T(x_1,y_1,z_1) = (x_1,x_1+ y_1, x_1+ y_1 + z_1) = T(x_2,y_2,z_2) = (x_2,x_2+y_2,x_2+y_2 + z_2)$\n\\[\n\\begin{aligned}\n  x_1 & = x_2 \\\\\n  y_1 & = y_2 \\\\\n  z_1 & = z_2 \n\\end{aligned} \\quad \\text{ $T$ is one-to-one } \\quad \\quad \\begin{gathered}\n  T(V_3) = L( \\{ (1,1,1), (0,1,1), (0,0,1) \\} ) \\\\\n  T^{-1}(x,y,z) = (x,y-x, z- y)\n\\end{gathered}\n\\]\n\n\\exercisehead{20} $T(x,y,z) = (x+y,y+z,x+z)$\n\\[\n\\begin{gathered}\n  T(x_1,y_1,z_1) = (x_1 + y_1,y_1 + z_1,x_1 + z_1) = T(x_2,y_2,z_2) = (x_2 + y_2,y_2 + z_2, x_2 + z_2) \\\\\n  \\Longrightarrow \\begin{aligned}\n    x_1 + y_1 & = x_2 + y_2 \\\\\n    y_1 + z_1 & = y_2 + z_2 \\\\\n    x_1 + z_1 & = x_2 + z_2 \n\\end{aligned} \\text{ or } \\begin{aligned}\n    x_1 - z_1 & = x_2  - z_2 \\\\\n    x_1 + z_1 & = x_2 + z_2 \n\\end{aligned} \\quad \\Longrightarrow x_1 = x_2 , \\, y_1  = y_2, \\, z_1 = z_2 \\text{ so that $T$ is one-to-one } \\\\\n  T(V_3) = L(\\{ (1,0,1), (1,1,0), (0,1,1) \\} ) \\\\\n \\boxed{ T^{-1}(x,y,z) = \\left( \\frac{x+z -y }{2}, \\frac{x+y-z}{2}, \\frac{y+z- x}{2} \\right) }\n\\end{gathered}\n\\]\n\n\\exercisehead{21} \n\\[\n\\begin{gathered}\n  T^m T^n  = T^m T T^{n-1} = (T^m T) T^{n-1} = T^{m+1} T^{n-1} = \\dots = T^{m+n} T^0 = T^{m+n} 1 = T^{m+n } \\\\\n  \\begin{aligned}\n    (T^n)^{-1}T^n & = (T^{-1})^n T^n = (T^{-1})(T^{-1})^{n-1} T (T^{n-1}) = \\dots = \\\\\n    & = \\underbrace{ (T^{-1})\\dots (T^{-1})}_{n \\text{ times }} \\underbrace{ T \\dots (T) }_{ n \\text{ times } } = \\underbrace{ (T^{-1}) \\dots (T^{-1}) }_{ n -1 \\text{ times } } (T^{-1} T ) \\underbrace{ T \\dots (T) }_{n -1 \\text{ times } } = \\underbrace{ (T^{-1}) \\dots (T^{-1} ) }_{ n-1 \\text{ times } } 1 \\underbrace{ T \\dots (T) }_{ n-1 \\text{ times } } = \\dots = T^{-1} T = 1\n\\end{aligned}\n\\end{gathered}\n\\]\n\n\\exercisehead{22} \n\\[\n\\begin{aligned}\n  (ST)^n & = (ST)(ST)^{n-1} = \\dots = \\underbrace{ (ST) \\dots (ST)}_{ n \\text{ times } } = \\\\\n  & = (ST) \\dots (ST)(ST) = (ST) \\dots (S(TS)T) = (ST) \\dots (ST)(SSTT) = \\dots = \\\\\n  & = SST(ST) \\dots (ST)T = \\dots = S^n T^n \n\\end{aligned}\n\\]\n\n\\exercisehead{23} $(T^{-1}S^{-1})(ST) = T^{-1}S^{-1} ST = T^{-1} 1 T = 1$, so $(ST)^{-1} = T^{-1}S^{-1}$.  Its uniqueness is guaranteed by theorem (left inverses, if they exist, are unique).  \n\n\\exercisehead{24}   $(ST)^{-1}ST = (ST)^{-1} TS = 1$.  \\\\\n\\emph{ Since left inverses are unique }(this theorem is important to use here), then $(TS)^{-1} = (ST)^{-1} \\Longrightarrow S^{-1}T^{-1} = T^{-1}S^{-1}$\n\n\\exercisehead{25} \n\\[\n\\begin{gathered}\n  (S+T)(S+T) = S^2 + ST + TS + T^2 = S^2 + 2ST + T^2 \\\\\n  \\begin{aligned}\n    (S+T)^3 & = (S^2 + ST + TS + T^2)(S+T) = S^3 + STS + TS^2 + T^2 S + S^2 T + ST^2 + TST + T^3 = \\\\\n    & = S^3 + 3S^2 T + 3T^2 S + T^3 \n\\end{aligned}\n\\end{gathered}\n\\]\n\\exercisehead{26} $\\begin{aligned}\n  S(x,y,z) & = (z,y,x) \\\\\n  T(x,y,z) & = (x,x+y,x+y+z)\n\\end{aligned}$\n\\begin{enumerate}\n\\item \\[\n\\begin{aligned}\n  (ST) & = (x+y+z,x+y,x) \\\\\n  (TS) & =  (z,z+y, x+y+z) \\\\\n  ST- TS & =  (x+y,x-z,-y-z) \\\\\n  S^2 & =  1  \n  \\end{aligned} \\quad \\quad \\quad \n\\begin{aligned}\n  T^2 & =  (x,2x+y,3x+2y+z) \\\\\n  (ST)^2 & =  (3x + 2y + z, 2x + 2y + z , x+y+z ) \\\\\n  (TS)^2 & =  (x+y+z, x+2y + 2z, x + 2y + 3z ) \\\\\n  (ST - TS)^2 & =  (2x + y- z, x+ 2y + z, -x + 2z + y ) \n\\end{aligned}\n\\]\n\\item If $S(x_1,y_1,z_1) = (z_1,y_1, x_1) = S(x_2,y_2,z_2) = (z_2,y_2,x_2)$, then $z_1 = z_2, \\, y_1 = y_2, \\, x_1 = x_2 $ \\\\\n  If $T(x_1,y_1,z_1) = (x_1,x_1 + y_1, x_1 + y_1 + z_1) = T(x_2,y_2,z_2) = (x_2, x_2 + y_2, x_2 + y_2 + z_2)$, then $x_1 = x_2, \\, y_1 = y_2, \\, z_1 = z_2 $.  Thus $S,T$ are one-to-one.  \n\\[\n\\begin{aligned}\n  & (S^{-1}) = S \\\\ \n  & (T^{-1})(x,y,z) = (x,y-x, z-y) \\\\\n  & (ST)^{-1} = T^{-1}S^{-1} = T^{-1} S \\quad \\quad & T^{-1}S(x,y,z) = (z,y-z,x-y) \\\\\n  & (TS)^{-1} = S^{-1}T^{-1} \\quad \\quad & S^{-1} T^{-1}(x,y,z) = S(x,y-x,z-y) = (z-y, y-x,x)\n\\end{aligned}\n\\]\n\\item $\\begin{aligned}\n  (T-1)(x,y,z) & = (0,x,x+y) \\\\\n  (T-1)^2(x,y,z) & = (0,0,x) \\\\\n  (T-1)^3(x,y,z) & = (0,0,0) \\text{ and for all higher powers }\n\\end{aligned}$\n\\end{enumerate}\n\n\\exercisehead{27} $T(p) = q(x) = \\int_0^x p(t) dt $ \n\\[\nDT(p) = \\frac{d}{dx} \\int_0^x p(t) dt = p(x) \\quad (\\text{by first fundamental thm. of calculus})\n\\]\n$TD(p) = \\int_0^x dt p'(t)$ \\\\\nSuppose $p=x+1$, $p' = 1$.  $\\int_0^x dt 1 = x \\neq p$\n\\[\n\\begin{aligned}\n  & nullspace{TD} = \\{ c_0 | \\text{ where } c_0 \\in \\mathbb{R} \\} \\\\\n  & range{TD} = \\{ \\text{ all polynomials $p$ s.t. $p(0) = 0$ } \\}\n\\end{aligned}\n\\]\n\n\\exercisehead{28} Let $V$ be linear space of all real polynomials $p(x)$.  \\\\\n$\\begin{aligned}\n  & D \\equiv \\text{ differential operator } \\\\\n  & T \\text{ is a linear map from $p(x)$ onto $xp'(x)$ }\n\\end{aligned}$\n\\begin{enumerate}\n  \\item $p(x) = 2 + 3x - x^2 + 4x^3$ \\\\\n    $D,T, DT, TD, DT-TD, T^2 D^2 - D^2 T^2$.  \n\\[\n\\begin{aligned}\n  Dp & = 3 - 2x + 12x^2 \\\\\n  Tp & = 3x - 2x^2 + 12 x^3 \\\\\n  DTp & = 3 - 4x + 36 x^2 \\\\\n  TDp & = -2x + 24x^2 \n\\end{aligned} \\quad \\quad \\quad \n\\begin{aligned}\n  DT - TD & = 3 - 2x + 12x^2 \\\\ \n  T^2 D^2 - D^2 T^2 & = 24x - (-8 + 216x ) = 8 - 192x \n\\end{aligned}\n\\]\n  \\item We want $T(p) = p$.  Try $p = \\sum_{j=0}^n a_j x^j$.  \n\\[\nT(p) = x \\sum_{j=0}^n j a_j x^{j-1} = \\sum_{j=0}^n ja_j x^j = \\sum_{j=0}^n a_j x^j \\Longrightarrow \\begin{aligned}\n\\sum_{j=0}^n a_j (j-1)x^j & = 0 \\\\\na_j(j-1) x^j & = 0 \n\\end{aligned} \\Longrightarrow j = 1 \n\\]\n$p=a_1 x$\n  \\item We want $(DT - 2D)(p) = 0$ or $DT(p) - 2D(p)$ \n\\[\n\\begin{gathered}\nDT(p) = \\sum_{j=0}^n j^2 a_j x^{j-1} = 2\\sum_{j=0}^n j a_j x^{j-1} \\Longrightarrow \\sum_{j=0}^n (j^2 - 2j)a_j x^{j-1} = \\sum_{j=0}^n j (j-2) a_j x^{j-1} = 0  \\\\\nj=2,0 \\text{ so that } p = a_2 x^2 + a_0 \n\\end{gathered}\n\\]\n\\item We want $(DT - TD)^n(p) = D^n(p)$.  \n\\[\n\\begin{gathered}\n\\begin{aligned}\n  & D\\sum_{j=0}^n a_j x^j = \\sum_{j=0}^n j a_j x^{j-1} \\\\\n  & (DT) \\sum_{j=0}^n a_j x^j = \\sum_{j=0}^n j^2 a_j x^{j-1} \\\\\n  & TD = \\sum_{j=0}^n j(j-1) a_j x^{j-1}\n\\end{aligned} \\quad \\quad \\quad (DT -TD)p = \\sum_{j=0}^n j a_j x^{j-1} = Dp  \\\\\n D^n  = (DT- TD)^n \\quad \\forall \\, p \\in V\n\\end{gathered}\n\\]\n\\end{enumerate}\n\n\\exercisehead{29} $xp(x)$.  $T(p) = xp$.  \\\\\n$\\begin{aligned}\n  DT(p) & = D(xp) = p + xp' \\\\\n  TD(p) & = Tp' = xp' \n\\end{aligned} \\quad \\Longrightarrow (DT- TD)(p) = p$\n\\[\n\\begin{gathered}\n  T^n(p) = T^{n-1}(xp) = \\dots = T(x^{n-1} p ) = x^n p \\\\\n  \\begin{aligned}\n    DT^n(p) & = nx^{n-1} p + x^n p' \\\\\n    T^n D(p) & = T^n(p') = T^{n-1} (xp')  = \\dots = T(x^{n-1} p') = x^n p' \n\\end{aligned} \\quad \\quad \\, \\Longrightarrow (DT^n - T^n D)(p) = nx^{n-1} p = nT^{n-1} (p)\n\\end{gathered}\n\\]\n\n\\exercisehead{30} \n\\[\n\\begin{gathered}\n\\begin{aligned}\n  & n =1 , \\, ST-  TS = 1 \\\\\n  & n=2 , \\, ST^2 - T^2 S = ST^2 + T(1-ST) = T + T = 2T \n\\end{aligned} \\\\\n\\text{ Assume the $n$th case, } ST^n - T^n S = nT^{n-1} \\\\\nST^{n+1} - T^{n+1}S = ST^n T + T^n(1-ST) = (nT^{n-1})T + T^n = (n+1)T^n \n\\end{gathered}\n\\]\n\n\\exercisehead{31} $p(x) = \\sum_{j=0}^n c_j x^j$.  \\quad \\, \\\\\n$\\begin{aligned}\n  Rp & = r & = r(x) & = p(0) \\\\ \n  Sp & = s & = s(x) & = \\sum_{k=1}^n c_k x^{k-1} \\\\\n  Tp & = t & = t(x) & = \\sum_{k=0}^n c_k x^{k+1} \n\\end{aligned}$.  \n\\begin{enumerate}\n\\item $p(x) = 2 + 3x - x^2 + x^3$.  We want to know $R,S,T,ST,TS,(TS)^2,T^2 S^2, S^2 T^2, TRS, RST$.  \n\\[\n\\begin{aligned}\n  Rp & = p(0) = 2 \\\\\n  Sp & = 3 - x + x^2 \\\\ \n  Tp & = 2x + 3x^2 - x^3 + x^4 \n\\end{aligned} \\quad \\quad \\, \n\\begin{aligned}\nST(p) & = 2 + 3x - x^2 + x^3 \\\\ \nTS(p) & = 3x - x^2 + x^3 \\\\ \n(TS)^2(p) & = 3x - x^2 + x^3 \n\\end{aligned} \\quad \\quad \\, \n\\begin{aligned}\nT^2 S^2 & = T^2 ( -1 + x) = - x^2 + x^3 \\\\\nS^2 T^2 & = S^2 (2x^2 + 3x^3 - x^4 + x^5) = 2 + 3x - x^2 + x^3 \\\\\nTRSp & = 3x \\\\\nRSTp & = 2 \n\\end{aligned}\n\\]\n\\item $R,S,T$ linear?  \n\\[\n  R(c_1 p_1 + c_2 p_2) = (c_1 p_1 + c_2 p_2)(0) = c_1 p_1(0) + c_2 p_2(0) = c_1 R(p_1) + c_2 R(p_2) \n \\]\n\\[\n\\begin{gathered}\n  c_1 S(p_1) + c_2 S(p_2) = c_1 \\sum_{j=1}^{n_1} a_j x^{j-1} + c_2 \\sum_{j=1}^{n_2} b_j x^{j-1} = \\sum_{j=1}^{n_2} h_j x^{j-1} = S(c_1 p_1 + c_2 p_2 ) \\\\\n  \\text{ where $n_2 \\geq n_1$, without loss of generality, and } h_j  = \\begin{cases} c_1 a_j + c_2 b_j & \\text{ for } j = 0, \\dots n_1 \\\\ \n    c_2 b_j & \\text{ for } j = n_1 + 1 \\dots n_2 \n\\end{cases} \\\\\n  \\text{ and indeed }, c_1 p_1 + c_2 p_2 = \\sum_{j=0}^{n_2} h_j x^j  \n\\end{gathered}\n\\]\n\\[\n\\begin{gathered}\n  c_1 p_1 + c_2 p_2  = c_1 \\sum_{j=0}^n a_j x^j + c_2 \\sum_{j=0}^{n_2} b_j x^j = \\sum_{j=0}^{n_1} c_1 a_j x^j + \\sum_{j=0}^{n_2} c_2 b_j x^j = \\sum_{j=0}^{n_2} h_j x^j \\\\\n  h_j = \\begin{cases} c_1 a_j + c_2 b_j & \\text{ for } j = 0, \\dots , n_1 \\\\\n    c_2 b_j & \\text{ for } j = n_1 + 1, \\dots n_2 \n\\end{cases} \n\\end{gathered}\n\\]\n\\[\n\\begin{aligned}\n  T(c_1p_1 + c_2 p_2) & = \\sum_{j=0}^n h_j  x^{j+1} = \\sum_{j=0}^{n_1} (c_1 a_j + c_2 b_j) x^{j+1} + \\sum_{j=n_1+1}^{n_2} (c_2 b_j) x^{j+1} \\\\\n  & = c_1 \\sum_{j=0}^{n_1} a_j x^{j+1} + c_2 \\sum_{j=0}^{n_2} b_j x^{j+1} = c_1 T(p_1) + c_2 T(p_2) \n\\end{aligned}\n\\]\n\\item \n\\[\nRp = p(0)  \\Longrightarrow \\begin{aligned}\n  & nullspace{R} = \\{ p | \\text{ polynomial $p$ of degree $\\geq 1$ } \\} \\\\\n  & range{R} = \\{ c_0 | c_0 \\in \\mathbb{R} \\}\n\\end{aligned}\n\\]\n\\[\nSp = \\sum_{k=1}^n c_k x^{k-1} \\quad \\Longrightarrow \\begin{aligned}\n  & nullspace{S} = \\{ c_0 | c_0 \\in \\mathbb{R} \\} \\\\\n  & range{S} = \\{ p | \\text{ polynomial $p$ of degree $n-1$ } \\} = V \n\\end{aligned}\n\\]\n\\[\nTp = \\sum_{j=0}^n c_j x^{j+1} \\quad \\, \\begin{aligned}\n  & nullspace{T}  = 0 \\\\\n  & range{T}  = \\{ p | \\text{ polynomial of degree } \\geq 1 \\}\n\\end{aligned}\n\\]\n\\item $T$ is linear.  $nullspace{T} = 0$.  By thm., $T$ is one-to-one.  This thm. for linear transformations is very useful because we simply need to check if the nullspace only contains $0$.  \n\\item If $n\\geq 1$, $(TS)^n = \\boxed{ (1-R)^n }$ since $TS(p) = p - R(p) = (1-R)(p)$.  \\\\\n  $S^n T^n = 1$  \n\\end{enumerate}\n\\exercisehead{32} If $x = \\{ x_j \\}$ is a convergent sequence, $\\lim_{j \\to \\infty} x_j = a$, let $T(x) = \\{ y_n \\}$, $y_n = a-x_n$ for $n\\geq 1 $.  \\\\$V$ = linear space of all real convergent sequences $\\{ x_j \\}$.   \\\\\n$T$ is linear, since \n\\[\n\\begin{aligned}\nT(c_1 x_1 + c_2 x_2) & = \\{ c_1 a_1 + c_2 a_2 - (c_1 x_{1j} + c_2 x_{2j} ) \\}= \\{ c_1 ( a_1 - x_{1j}) + c_2 (a_2 - x_{2j}) \\} = c_1 \\{ (a_1 - x_{1j} ) \\} + c_2 \\{ (a_2 - x_{2j} ) \\} = \\\\\n& = c_1 T(x_1) + c_2 T(x_2) \n\\end{aligned}\n\\]\nwhere $\\lim_{j\\to \\infty} (c_1 x_{1j} + c_2 x_{2j} ) = c_1 a_1 + c_2 a_2 $.   \\\\\nNote that all sequences of a constant number, constant sequences, get mapped to the same sequence of zeroes.  Thus, $T$ is not one-to-one.  \n\n%-----------------------------------%-----------------------------------%-----------------------------------\n\\section*{ 2.12 Exercises - Linear transformations with prescribed values, Matrix representations of linear transformations, Construction of a matrix representation in diagonal form }\n%-----------------------------------%-----------------------------------%-----------------------------------\n\\exercisehead{1}\n\\begin{enumerate}\n  \\item $a_{ij} = \\delta_{ij}$\n  \\item  $a_{ij} =0 $ \n  \\item  $a_{ij} = c\\delta_{ij}$\n\\end{enumerate}\n\n\\exercisehead{2} \n\\begin{enumerate}\n\\item $\\left[ \\begin{matrix} 1 & 0 & 0 \\\\ 0 & 1 & 0 \\end{matrix} \\right]$\n\\item $\\left[ \\begin{matrix} 0 & 1 & 0 & 0 & 0 \\\\ 0 & 0 & 1 & 0 & 0 \\\\ 0 & 0 & 0 & 1 & 0 \\end{matrix} \\right]$\n\\item $\\left[ \\begin{matrix} 0 & 1 & 0 \\\\ 0 & 0 & 1 \\end{matrix} \\right]$\n\\end{enumerate}\n\n\\exercisehead{3} \n\\begin{enumerate}\n\\item $\\begin{aligned}\n  T(3i - 4j) & = -5 i + 7 j \\\\\n  T^2(3i -4j) & = 9i - 12 j \n\\end{aligned}$\n\\item $T = \\left[ \\begin{matrix} 1 & 2 \\\\ 1 & -1 \\end{matrix} \\right]$ \\quad \\, $T^2 = \\left[ \\begin{matrix} 1 & 2 \\\\ 1 & -1 \\end{matrix} \\right]\\left[ \\begin{matrix} 1 & 2 \\\\ 1 & -1 \\end{matrix} \\right] = \\left[ \\begin{matrix} 3 & 0 \\\\ 0 & 3 \\end{matrix} \\right]$ \n\\item \n\\[\n\\begin{gathered}\n  \\begin{aligned}\n    e_1 & = i - j \\\\\n    e_2 & = 3i + j \n  \\end{aligned} \\\\\n  \\begin{aligned}\n    T(e_1) & = T(i-j) = i + j - 2i + j = -i + 2j = - \\left( \\frac{ e_1 + e_2 }{4} \\right) + 2 \\left( \\frac{ e_2 - 3e_1 }{4} \\right) & = \\frac{ -7e_1 + e_2 }{4} \\\\\n    T(e_2) & = T(3i+j) = 3i + 3j + 2i - j = 5i + 2j = 5 \\left( \\frac{ e_1 + e_2 }{4} \\right) + 2 \\left( \\frac{ e_2 - 3e_1 }{4} \\right) & = \\frac{-e_1 + 7 e_2 }{4}\n\\end{aligned} \\\\\nT = \\frac{1}{4} \\left[ \\begin{matrix} -7 & -1 \\\\ 1 & 7 \\end{matrix} \\right], \\quad \\quad \\, T^2 = 12 \\left[ \\begin{matrix} 1 & \\\\ & 1 \\end{matrix} \\right]\n\\end{gathered}\n\\]\n\\end{enumerate}\n\n\\exercisehead{4} \n\\[\nT = 2 \\left[ \\begin{matrix} -1 & 0 \\\\ 0 & 1 \\end{matrix} \\right] \\quad \\quad \\quad T^2 = 4 \\left[ \\begin{matrix} 1 & \\\\ & 1 \\end{matrix} \\right]\n\\]\n\n\\exercisehead{5} $T:V_3 \\to V_3$ be a linear transformation s.t. \\\\\n\\begin{enumerate} \n\\item  $\\begin{matrix}\n  T(k) & = 2i + 3j + 5k \\\\ \n  T(j+k) & = i \\\\\n  T(i+j+k) & = j -k\n\\end{matrix}$ \\quad \\quad \\quad $\\Longrightarrow T(i+2j + 3k) = \\boxed{ 3i + 4j + 4k }$\n\\[\n\\begin{aligned}\n  T(i) & = -i + j -k \\\\\n  T(j) & = -i - 3j -5k \\\\\n  T(k) & = 2i + 3j + 5k \n\\end{aligned} \n\\quad \\quad \\,\nT(c_1 i + c_2 j + c_3 k ) = (-c_1 -c_2 + 2c_3)i + (c_1 - 3c_2 + 3c_3)j + (-c_1 -5 c_2 + 5c_3)k = 0 \n\\]\nSo we have a system of linear equations, \\\\\n$\\begin{aligned}\n  & -c_1 - c_2 + 2c_3 = 0 \\\\\n  & c_1 - 3c_2 + 3c_3 = 0 \\\\\n  & -c_1 - 5c_2 + 5c_3 = 0 \n\\end{aligned}$ to solve, which could be done by Gauss-Jordan or simply to add them up cleverly to get $c_3 = 0$ first, and then $c_2,c_1 =0$.  \\\\\n$\\Longrightarrow nullspace{T} = 0, \\quad null{T} = 0$.  $range{T} = V_3, \\quad rank{T} = 3$\n\\item $T = \\left[ \\begin{matrix} -1 & -1 & 2 \\\\\n    1 & -3 & 3 \\\\\n    -1 & -5 & 5 \\end{matrix} \\right]$\n\\end{enumerate}\n\n\\exercisehead{6} \n\\[\n\\begin{aligned}\n  e_1 & = (2,3,5) \\\\\n  e_2 & = (1,0,0) \\\\\n  e_3 & = (0,1,-1)\n\\end{aligned} \\quad \\quad \\quad \n\\begin{aligned}\n  T(e_1) & = 2(-1,1,-1) + 3(-1,-3,5) + 5(2,3,5) =(5,8,8) = 2e_1 + 2e_3+ e_2 \\\\\n  T(e_2) & = (-1,1,-1) = -e_2 + e_3 \\\\\n  T(e_3) & = (-1,-3,-5) + (-2,-3,-5) = (-3,-6,-10) = -2e_1 + 2 e_2\n\\end{aligned}\n\\]\n\\[\nT = \\left[ \\begin{matrix} 2 & 0 & -2 \\\\\n    1 & -1 & 1 \\\\\n    2 & 1 & 0 \n\\end{matrix} \\right]\n\\]\n\n\\exercisehead{7} Given $T(0)  = (0,0), \\, T(j) = (1,1), \\, T(k) = (1,-1)$\n\\begin{enumerate}\n\\item $T(4i - j + k ) = (-1,-1) + (1,-1) = (0,-2)$ \\\\\nDetermine the nullspace of $T$ by considering \n\\[\nT(x) = \\left[ \\begin{matrix} 0 & 1 & 1 \\\\\n  0 & 1 & -1 \\end{matrix} \\right]\\left[ \\begin{matrix} c_1 \\\\ c_2 \\\\ c_3 \\\\ \\end{matrix} \\right] = 0 \\Longrightarrow \\left[ \\begin{matrix} 0 & 1 & 0 \\\\\n    0 & 0 & -2 \\end{matrix} \\right] = \\left[ \\begin{matrix} 0 & 1 & 0 \\\\ 0 & 0 & 1 \\end{matrix} \\right]\n\\]\nSo then $nullspace{T} = L(\\{ (1,0,0) \\} )$.  \\\\\n$\\begin{aligned}\n  & null{T} = 1 \\\\\n  & range{T} = 2 \n\\end{aligned}$ \\quad \\quad (by nullity-rank thm.)\n\\item $T = \\left[ \\begin{matrix} 0 & 1 & 1 \\\\\n  0 & 1 & -1 \\end{matrix} \\right]$\n\\item $\\begin{aligned}\n  w_1 & = (1,1) \\\\\n  w_2 & = (1,2)\n\\end{aligned}$ \\quad \\quad $\\begin{aligned}\n  & T(i) = 0 \\\\\n  & T(j) = w_1 \\\\\n  & T(k) = 3w_1 - 2w_2\n\\end{aligned}$ \\quad \\quad $T = \\left[ \\begin{matrix} 0 & 1 & 3 \\\\\n0 & 0 & -2 \\end{matrix} \\right]$\n\\item \n\\[\n\\boxed{ \\begin{aligned}\n    e_1 & = i \\\\\n    e_2 & = j \\\\\n    e_3 & = \\frac{ 3j - k }{2}\n\\end{aligned} }\n\\]\n\\end{enumerate}\n\n\\exercisehead{8} Given $\\begin{aligned} T(i) & = (1,0,1) \\\\ T(j) & = (-1,0,1) \\end{aligned}$,\n\\begin{enumerate}\n\\item $T(2i - 3j) = (2,0,2) + (3,0,-3) = (5,0,-1)$.  \n$\\left[ \\begin{matrix} 1 & -1 \\\\ 0 & 0 \\\\ 1 & 1 \\end{matrix} \\right] \\xrightarrow{ \\text{ Gauss-Jordan elimination } } \\left[ \\begin{matrix} 2 & 0 \\\\ 0 & 0 \\\\ 0 & 2 \\end{matrix} \\right] \\left[ \\begin{matrix} c_1 \\\\ c_2 \\end{matrix} \\right]$ $\\Longrightarrow c_1 = c_2 =0$.  \\\\\nSo then $\\begin{aligned}\n  null{T} & = 0 \\\\\n  rank{T} & = 2 \n\\end{aligned}$\n\\item Again, $T = \\left[ \\begin{matrix} 1 & -1 \\\\ 0 & 0 \\\\ 1 & 1 \\end{matrix} \\right]$\n\\item \\[\n\\begin{aligned}\n  e_1 & = \\frac{ i - j }{2} \\\\\n  e_2 & = \\frac{ i + j }{2}\n\\end{aligned} \\quad \\quad \\begin{aligned}\n  T(e_1) = T\\left( \\frac{ i - j }{2} \\right) & = (1,0,0) \\\\\n  T\\left( \\frac{ i + j }{2} \\right) & = (0,0,1) = w_2 = k \n\\end{aligned} \\quad \\quad \\, \\begin{aligned}\n  w_1 & = (1,0,0) \\\\\n  w_2 & = (0,0,1) = k \\\\\n  w_3 & = (0,1,0)\n\\end{aligned}\n\\]\n\\end{enumerate}\n\n\\exercisehead{9} Given \\\\\n$\\begin{aligned}\n  T(i) & = (1,0,1) \\\\\n  T(j) & = (1,1,1) \n\\end{aligned}$ \n\\begin{enumerate}\n\\item  $T(2i-3j) = (2,0,2) - (3,3,3) = (-1,-3,-1)$.  By inspection of the matrix for $T$, $\\begin{aligned} null{T} & =0 \\\\ rank{T} & = 2 \\end{aligned}$.  \n\\item $T = \\left[ \\begin{matrix} 1 & 1 \\\\ 0 & 1 \\\\ 1 & 1 \\end{matrix} \\right]$\n\\item Note that \n\\[\n\\begin{aligned}\n  T(j-i) & = (0,1,0) \\\\\n  T(i) & = (1,0,1)\n\\end{aligned} \\quad \\quad \\quad \\begin{aligned}\n  w_1 & = (1,0,1) \\\\\n  w_2 & = (0,1,0) \\\\\n  w_3 & = (0,0,1)\n\\end{aligned} \\quad \\quad \\quad \\Longrightarrow \\left[ \\begin{matrix} 1 & 0 \\\\ 0 & 1 \\\\ 0 & 0 \\end{matrix} \\right]\n\\]\n\\end{enumerate}\n\n\\exercisehead{10} Let $V$ and $W$ be linear spaces, each with dimension $2$.  \n\\begin{enumerate}\n\\item Given $\\begin{aligned}\n  T(e_1 + e_2) & = 3e_1 + 9e_2 \\\\\n  T(3e_1 + 2e_2) & = 7e_1 + 23 e_2 \n\\end{aligned}$, then $\\begin{aligned}\n  T(-e_2) & = -2e_1 + -4e_2 = -(2e_1 + 4 e_2) \\\\\n  T(e_1) & = e_1 + 5 e_2 \n\\end{aligned}$, so that $\\boxed{ T(e_2 - e_1) = e_1 - e_2 }$.  By inspection of matrix $T$, $\\begin{aligned}\n  null{T} & = 0 \\\\\n  rank{T} & = 2 \n\\end{aligned}$\n\\item $T = \\left[ \\begin{matrix} 1 & 2 \\\\ 5 & 4 \\end{matrix} \\right]$\n\\item With a basis of $(e_1,e_2)$ for $V$ and a desired basis of the form $(e_1 + ae_2, 2e_1 + be_2)$ for $W$, \n\\[\n\\begin{aligned}\n  T(e_1) & = e_1 + 5 e_2 \\quad \\quad & \\Longrightarrow a = 5 \\\\\n  T(e_2) & = 2e_1 + 4 e_2 \\quad \\quad & \\Longrightarrow b =4 \n\\end{aligned}\n\\]\n\\end{enumerate}\n\n\\exercisehead{11} $(\\sin{x}, \\cos{x})$\n\\[\nD(s,c) = (c,-s) \\Longrightarrow D= \\left[ \\begin{matrix} 0 & -1 \\\\ 1 & 0 \\end{matrix} \\right] \\quad \\quad D^2 = \\left[ \\begin{matrix} -1 & 0 \\\\ 0 & -1 \\end{matrix} \\right]\n\\]\n\n\\exercisehead{12} $(1,x,e^x)$ \\\\\n\\[\nD(1,x,e^x) = (0,1,e^x) \\quad \\quad \\, D = \\left[ \\begin{matrix} 0 & 1 & 0 \\\\ 0 & 0 & 0 \\\\ 0 & 0 & 1 \\end{matrix} \\right] \\quad \\quad D^2 = \\left[ \\begin{matrix} & 1 & \\\\ & & \\\\ & & 1 \\end{matrix} \\right] \\left[ \\begin{matrix} & 1 & \\\\ & & \\\\ &  & 1 \\end{matrix}\\right] = \\left[ \\begin{matrix} & & \\\\ & & \\\\ & & 1 \\end{matrix} \\right]\n\\]\n\n\\exercisehead{13} $(1,1+x,1+x+e^x)$\n\\[\nD(1,1+x,1+x+e^x) \\quad \\quad D= \\left[ \\begin{matrix} 0 & 1 & 1 \\\\ 0 & 0 & -1 \\\\ 0 & 0 & 1 \\end{matrix} \\right] \\quad \\quad \\, D^2 = \\left[ \\begin{matrix} & 1 & 1 \\\\ & & -1 \\\\ &  & 1 \\end{matrix} \\right]\\left[ \\begin{matrix} & 1 & 1 \\\\ & & - 1 \\\\ & & 1 \\end{matrix}\\right] = \\left[ \\begin{matrix} & & \\\\ & & -1 \\\\ & & 1 \\end{matrix} \\right]\n\\]\n\n\\exercisehead{14} $(e^x,xe^x)$ \n\\[\nD(e^x,xe^x) = (e^x, e^x + xe^x) \\quad \\quad \\, D = \\left[ \\begin{matrix} 1 & 1 \\\\ 0 & 1 \\end{matrix} \\right] \\quad \\quad \\, D^2  = \\left[ \\begin{matrix} 1 & 1 \\\\ & 1 \\end{matrix} \\right]\\left[ \\begin{matrix} 1 & 1 \\\\ & 1 \\end{matrix} \\right] = \\left[ \\begin{matrix} 1 & 2 \\\\ & 1 \\end{matrix} \\right]\n\\]\n\n\\exercisehead{15} $(-c,s)$.  \n\\[\nD(-c,s) = (s,c) \\quad \\quad \\, D = \\left[ \\begin{matrix} 0 & -1 \\\\ 1 & 0 \\end{matrix} \\right] \\quad \\quad \\, D^2 = \\left[ \\begin{matrix} & -1 \\\\ 1 &  \\end{matrix} \\right]\\left[ \\begin{matrix} & -1 \\\\ 1 & \\end{matrix} \\right] = \\left[ \\begin{matrix} -1 & \\\\ & -1 \\end{matrix} \\right]\n\\]\n\n\\exercisehead{16} $(\\sin{x},\\cos{x} ,x \\sin{x}, x\\cos{x})$\n\\[\n\\begin{gathered}\nD(s,c,xs,xc) = (c,-s,s+xc,c+-xs) \\quad \\quad \\, \\\\\nD= \\left[ \\begin{matrix} 0 & -1 & 1 & 0 \\\\ 1 & 0 & 0 & 1 \\\\ 0 & 0 & 0 & -1 \\\\ 0 & 0 & 1 & 0 \\end{matrix} \\right] \\quad \\quad \\, D^2 = \\left[ \\begin{matrix} & -1 & 1 & \\\\ 1 & & & 1 \\\\ & & & -1 \\\\ & & 1 & \\end{matrix} \\right]\\left[ \\begin{matrix} & -1 & 1 & \\\\ 1 & & & 1 \\\\ & & & -1 \\\\ & & 1 & \\end{matrix} \\right] = \\left[ \\begin{matrix} -1 & & -2 \\\\ & -1 & 2 \\\\ & & -1 & \\\\ & & & -1 \\end{matrix} \\right]\n\\end{gathered}\n\\]\n\n\\exercisehead{17} $(e^x \\sin{x}, e^x \\cos{x})$\n\\[\nD(e^x s,e^x c) = (e^x s + e^x c, e^x c - e^x s) \\quad \\quad D = \\left[ \\begin{matrix} 1 & -1 \\\\ 1 & 1 \\end{matrix} \\right] \\quad \\quad \\, D^2 = \\left[ \\begin{matrix} 1 & -1 \\\\ 1 & 1 \\end{matrix} \\right]\\left[ \\begin{matrix} 1 & -1 \\\\ 1 & 1 \\end{matrix} \\right] = \\left[ \\begin{matrix} & -2 \\\\ 2 & \\end{matrix} \\right]\n\\]\n\n\\exercisehead{18} $(e^{2x} \\sin{3x}, e^{2x} \\cos{3x} )$\n\\[\nD(e^{2x}s, e^{2x}c ) = (2e^{2x}s + 3e^{2x} c, 2e^{2x}c + - 3 e^{2x} s )  \\quad \\quad \\, D = \\left[ \\begin{matrix} 2 & -3 \\\\ 3 & 2 \\end{matrix} \\right] \\quad \\quad \\, D^2 = \\left[ \\begin{matrix} 2 & -3 \\\\ 3 & 2 \\end{matrix} \\right]\\left[ \\begin{matrix} 2 & -3 \\\\ 3 & 2 \\end{matrix} \\right] = \\left[ \\begin{matrix} -5 & -12 \\\\ 12 & -5 \\end{matrix} \\right]\n\\]\n\n\\exercisehead{19} $(1,x,x^2,x^3)$.  $T(p) = xp'$.   \\\\\n$\\begin{aligned}\n  D(1,x,x^2,x^3) & = (0,1,2x,3x^2) \\\\\n  T(1,x,x^2,x^3) &=  (0,x,2x^2, 3x^3) \n\\end{aligned}$ \n\\begin{enumerate}\n\\item $T = \\left[ \\begin{matrix} 0 & 0 & 0 & 0 \\\\ 0 & 1 & 0 & 0 \\\\ 0 & 0 & 2 & 0 \\\\ 0 & 0 & 0 & 3 \\end{matrix} \\right]$\n\\item $DT = \\left[ \\begin{matrix} 0 & 1 & 0 & 0 \\\\ 0 & 0 & 4 & 0 \\\\ 0 & 0 & 0 & 9 \\\\ 0 & 0 & 0 & 0 \\end{matrix} \\right]$\n\\item $TD = \\left[ \\begin{matrix} 0 & 0 & 0 & 0 \\\\ 0 & 0 & 2 & 0 \\\\ 0 & 0 & 0 & 6 \\\\ 0 & 0 & 0 & 0 \\end{matrix} \\right]$\n\\item $TD - DT = \\left[ \\begin{matrix} 0 & - 1 & 0 & 0 \\\\ 0 & 0 & -2 & 0 \\\\ 0 & 0 & 0 & -3 \\\\ 0 & 0 & 0 & 0 \\end{matrix} \\right]$ \n\\item $T^2 = \\left[ \\begin{matrix} & & & \\\\ & 1 & &  \\\\ & & 2 & \\\\ & & & 3 \\end{matrix} \\right]\\left[ \\begin{matrix} & & & \\\\ & 1 & &  \\\\ & & 2 & \\\\ & & & 3 \\end{matrix} \\right] = \\left[ \\begin{matrix} & & & \\\\ & 1 & & \\\\ & & 4 & \\\\ & & & 9 \\end{matrix} \\right]$ \n\\item \\[\n\\begin{aligned}\n  T^2 D^2 & = \\left[ \\begin{matrix} & & & \\\\ & 1 & & \\\\ & & 4 & \\\\ & & & 9 \\end{matrix} \\right]\\left[ \\begin{matrix} & & 2 & \\\\ & & 6 & \\\\ & & & \\\\ & & & \\end{matrix} \\right] = \\left[ \\begin{matrix} & & & \\\\ & & & 6 \\\\ & & & \\\\ & & & \\end{matrix} \\right] \\\\ \n  D^2 T^2 & = \\left[ \\begin{matrix} & & 2 & \\\\ & & & 6 \\\\ & & & \\\\ & & & \\end{matrix} \\right]\\left[ \\begin{matrix} & & & \\\\ & 1 & & \\\\ & & 4 & \\\\ & & & 9 \\end{matrix} \\right] = \\left[ \\begin{matrix} & & 8 & \\\\ & & & 54 \\\\ & & & \\\\ & & & \\end{matrix} \\right]\n\\end{aligned}\n \\quad \\quad T^2 D^2 - D^2 T^2 = \\left[ \\begin{matrix} & & -8 & \\\\ & & & -48 \\\\ & & & \\\\ & & & \\end{matrix} \\right]\n\\]\n\\end{enumerate}\n\n\\exercisehead{20} $TD = \\left[ \\begin{matrix} & & & \\\\ & & 2 & \\\\ & & & 6 \\\\ & & & \\end{matrix} \\right]$.  \\\\\nNote that $(TD)(x^3,x^2,x,1) = (6x^2, 2x, 0 , 0)$, so if we let $\\begin{aligned}\n  w_1 & = x^2 \\\\ \n  w_2 & = x\n\\end{aligned}$, then $(TD) = \\left[ \\begin{matrix} 6 & & & \\\\ & 2 & & \\end{matrix} \\right] $\n\n%-----------------------------------%-----------------------------------%-----------------------------------\n\\section*{ 2.16 Exercises - Linear spaces of matrices, Isomorphism between linear transformations and matrices, Multiplication of matrices }\n%-----------------------------------%-----------------------------------%-----------------------------------\n\n\\exercisehead{1} $A = \\left[ \\begin{matrix} 1 & -4 & 2 \\\\ -1 & 4 & -2 \\end{matrix} \\right]$, \\quad $B = \\left[ \\begin{matrix} 1 & 2 \\\\ -1 & 3 \\\\ 5 & -2 \\end{matrix} \\right]$, \\quad $C = \\left[ \\begin{matrix} 2 & 2 \\\\ 1 & -1  \\\\ 1 & -3 \\end{matrix} \\right]$\n\\[\n\\begin{gathered}\n  B+ C = \\left[ \\begin{matrix} 3 & 4 \\\\ 0 & 2 & 6 & -5 \\end{matrix} \\right] \\\\\n  \\begin{aligned}\n    AB & = \\left[ \\begin{matrix} 1 & -4 & 2 \\\\ -1 & 4 & -2 \\end{matrix} \\right] \\left[ \\begin{matrix} 1 & 2 \\\\ -1 & 3 \\\\ 5 & -2 \\end{matrix} \\right] = \\left[ \\begin{matrix} 15 & - 14 \\\\ -15 & 14 \\end{matrix} \\right] \\\\\n    BA & = \\left[ \\begin{matrix} 1 & 2 \\\\ -1 & 3 \\\\ 5 & -2 \\end{matrix} \\right] \\left[ \\begin{matrix} 1 & -4 & 2 \\\\ -1 & 4 & -2 \\end{matrix} \\right] = \\left[ \\begin{matrix} -1 & 4 & -2 \\\\ -4 & 16 & -8 \\\\ 7 & -28 & 14 \\end{matrix} \\right] \\\\\n    \\end{aligned} \\quad \\quad \\quad \n  \\begin{aligned}\n    AC & = \\left[ \\begin{matrix} 1 & -4 & 2 \\\\ \n\t-1 & 4 & -2 \\end{matrix} \\right] \\left[ \\begin{matrix} 2 & 2 \\\\\n\t 1 & -1 \\\\\n\t 1 & -3 \\end{matrix} \\right] = \\left[ \\begin{matrix} 0 & 0 \\\\ 0 & 0 \\end{matrix} \\right] \\\\\n    CA & = \\left[ \\begin{matrix} 2 & 2 \\\\ 1 & -1 \\\\ 1 & -3 \\end{matrix} \\right] \\left[ \\begin{matrix} 1 & -4 & 2 \\\\ -1 & 4 & -2 \\end{matrix} \\right] = \\left[ \\begin{matrix} 0 & 0 & 0 \\\\ 2 & -8 & 4 \\\\ 4 & - 16 & 8 \\end{matrix} \\right]\n  \\end{aligned} \\\\\nA(2B-3C) = 2AB - 3AC = \\left[ \\begin{matrix} 30 & - 28 \\\\ -30 & 28 \\end{matrix} \\right] + \\left[ \\begin{matrix} 0 & 0 \\\\ 0 & 0 \\end{matrix} \\right] = \\left[ \\begin{matrix} 30 & -28 \\\\ -30 & 28 \\end{matrix} \\right]  \n\\end{gathered}\n\\]\n\n\\exercisehead{2} $A = \\left[ \\begin{matrix} 0 & 1 \\\\ 0 & 2 \\end{matrix} \\right]$  \n\\begin{enumerate}\n  \\item $AB = \\left[ \\begin{matrix} & 1 \\\\ & 2 \\end{matrix} \\right] \\left[ \\begin{matrix} b_{11} & b_{12} \\\\ b_{21} & b_{22} \\end{matrix} \\right] = \\left[ \\begin{matrix} b_{21} & b_{22} \\\\ 2b_{21} & 2b_{22} \\end{matrix} \\right] = 0 $ \\\\\n   $\\Longrightarrow b_{21} = b_{22} =0$ or $\\left[ \\begin{matrix} b_{11} & 0 \\\\ b_{21} & 0 \\end{matrix} \\right]$\n  \\item $BA = \\left[ \\begin{matrix} b_{11} & b_{12} \\\\ b_{21} & b_{22} \\end{matrix} \\right]\\left[ \\begin{matrix} & 1 \\\\ & 2 \\end{matrix} \\right] = \\left[ \\begin{matrix} & b_{11} + 2b_{12} \\\\ & b_{21} + 2b_{22} \\end{matrix} \\right] \\Longrightarrow \\begin{aligned}\nb_{11} & = -2b_{12} \\\\\nb_{21} & = -2b_{22}\n\\end{aligned}$\n\\[\n\\left[ \\begin{matrix} b_{11} & b_{11}/-2 \\\\ b_{21} & b_{21}/-2 \\end{matrix} \\right] = b_{11} \\left[ \\begin{matrix} 1 & -1/2 \\\\ 0 & 0 \\end{matrix} \\right] + b_{21} \\left[ \\begin{matrix} 0 & 0 \\\\ 1 & -1/2 \\end{matrix} \\right]\n\\]\n\\end{enumerate}\n\n\\exercisehead{3} \n\\begin{enumerate}\n\\item $\\left[ \\begin{matrix} & & 1 & \\\\ 1 & & & \\\\ & 1 & & \\\\ & & & 1 \\end{matrix} \\right] \\left[ \\begin{matrix} a \\\\ b \\\\ c \\\\ d \\end{matrix} \\right] = \\left[ \\begin{matrix} 1 \\\\ 9 \\\\ 6 \\\\ 5 \\end{matrix} \\right] \\Longrightarrow \\begin{aligned} c & = 1 \\\\ a & = 9 \\\\ b & = 6 \\\\ d & = 5 \\end{aligned}$\n\\item \\[\n\\left[ \\begin{matrix} a & b & c & d \\\\ 1 & 4 & 9 & 2 \\end{matrix} \\right] \\left[ \\begin{matrix} 1 & & 2 & \\\\ & & 1 & & \\\\ & 1 & & \\\\ & & 1 & \\end{matrix} \\right]  = \\left[ \\begin{matrix} 1 & & 6 & 6 \\\\ 1 & 9 & 8 & 4 \\end{matrix} \\right] \\quad \\quad \\quad \\begin{aligned} a & =1 \\\\ c & = 0 \\\\ b & = 6 \\\\ d & =-2 \\end{aligned}\n\\]\n\\end{enumerate}\n\n\\exercisehead{4} $AB-BA$\n\\begin{enumerate}\n\\item \\[ \\begin{aligned}\n  A & = \\left[ \\begin{matrix} 1 & 2 & 2 \\\\ 2 & 1 & 2  \\\\ 1 & 2 & 3 \\end{matrix} \\right] \\\\\n  B & = \\left[ \\begin{matrix} 4 & 1 & 1 \\\\ -4 & 2 & 0 \\\\ 1 & 2 & 1 \\end{matrix} \\right] \\end{aligned} \\quad \\quad \\, \\begin{aligned} BA & = \\left[ \\begin{matrix} 4 & 1 & 1 \\\\ -4 & 2 & 0 \\\\ 1 & 2 & 1 \\end{matrix} \\right]\\left[ \\begin{matrix} 1 & 2 & 2 \\\\ 2 & 1 & 2 \\\\ 1 & 2 & 3 \\end{matrix} \\right] = \\left[ \\begin{matrix} 7 & 11 & 13 \\\\ & -6 & -4 \\\\ 6 & 6 & 9 \\end{matrix} \\right] \\\\\n  AB & = \\left[ \\begin{matrix} -2 & 9 & 3 \\\\ 6 & 10 & 4 \\\\ -1 & 11 & 4 \\end{matrix} \\right] \\\\\n AB - BA & = \\boxed{ \\left[ \\begin{matrix} -9 & -2 & -10 \\\\ 6 & 16 & 8 \\\\ -7 & 5 & -5 \\end{matrix} \\right] } \\end{aligned} \\]\n\\item \\[ \\begin{aligned}\n  A & = \\left[ \\begin{matrix} 2 & 0 & 0 \\\\ 1 & 1 & 2 \\\\ -1 & 2 & 1 \\end{matrix} \\right] \\\\\n  B & = \\left[ \\begin{matrix} 3 & 1 & -2 \\\\ 3 & -2 & 4 \\\\ -3 & 5 & 11 \\end{matrix} \\right]\n\\end{aligned} \\quad \\quad \\,  \\begin{aligned} AB & = \\left[ \\begin{matrix} 2 & 0 & 0 \\\\ 1 & 1 & 2 \\\\ -1 & 2 & 1 \\end{matrix} \\right] \\left[ \\begin{matrix} 3 & 1 & -2 \\\\ 3 & -2 & 4 \\\\ -3 & 5 & 11 \\end{matrix} \\right] = \\left[ \\begin{matrix} 6 & 2 & -4 \\\\ 0 & 9 & 24 \\\\ 0 & 0 & 21 \\end{matrix} \\right] \\\\\n  BA & = \\left[ \\begin{matrix} 3 & 1 & -2 \\\\ 3 & -2 & 4 \\\\ -3 & 5 & 11 \\end{matrix} \\right]\\left[ \\begin{matrix} 2 & 0 & 0 \\\\ 1 & 1 & 2 \\\\ -1 & 2 & 1 \\end{matrix} \\right] = \\left[ \\begin{matrix} 9 & -3 & 0 \\\\ 0 & 6 & 0 \\\\ -12 & 27 & 21 \\end{matrix} \\right] \\\\\n  AB - BA & = \\left[ \\begin{matrix} 6 & 2 & -4 \\\\ 0 & 9 & 24 \\\\ 0 & 0 & 21 \\end{matrix} \\right] - \\left[ \\begin{matrix} 9 & -3 & 0 \\\\ 0 &  6 & 0  \\\\ -12 & 27 & 21 \\end{matrix} \\right] = \\left[ \\begin{matrix} -3 & 5 & -4 \\\\ 0 & 3 & 24 \\\\ 12 & -27 & 0 \\end{matrix} \\right] \\end{aligned} \\] \n\\end{enumerate}\n\n\\exercisehead{5} $A^n A^m = A^{m+n}$.  \\\\\nMatrix multiplication is associative; $A^n A^m = A^{n-1} (AA^m) =A^{n-1} A^{m+1} = \\dots = A^0 A^{m+n} = A^{m+n}$\n\n\\exercisehead{6} $A = \\left[ \\begin{matrix} 1 & 1 \\\\ & 1 \\end{matrix} \\right]$ \\quad \\quad $A^2 = \\left[ \\begin{matrix} 1 & 2 \\\\ & 1 \\end{matrix} \\right]$ \\\\\n\\[\n\\begin{gathered}\n  A^3  = \\left[ \\begin{matrix} 1 & 2 \\\\ & 1 \\end{matrix} \\right]\\left[ \\begin{matrix} 1 & 1 \\\\ & 1 \\end{matrix} \\right] = \\left[ \\begin{matrix} 1 & 3 \\\\ & 1 \\end{matrix} \\right] \\\\\n  \\text{ Assume $n$th case is true } A^n = \\left[ \\begin{matrix} 1 & n \\\\ & 1 \\end{matrix} \\right] \\quad \\quad \\, A^{n+1} = A A^n = \\left[ \\begin{matrix} 1 & 1 \\\\ & 1 \\end{matrix} \\right]\\left[ \\begin{matrix} 1 & n \\\\ & 1 \\end{matrix} \\right] = \\left[ \\begin{matrix} 1 & n+1 \\\\ & 1 \\end{matrix} \\right]\n\\end{gathered}\n\\]\n\n\\exercisehead{7} $A = \\left[ \\begin{matrix} \\cos{\\theta} & -\\sin{\\theta} \\\\ \\sin{\\theta} & \\cos{\\theta} \\end{matrix} \\right]$ \n\\[\n\\begin{gathered}\n  A^2 = \\left[ \\begin{matrix} c & -s \\\\ s & c \\end{matrix} \\right] \\left[ \\begin{matrix} c & -s \\\\ s & c \\end{matrix} \\right] = \\left[ \\begin{matrix} c^2 - s^2 & -2sc \\\\ 2sc & -s^2 + c^2 \\end{matrix} \\right] = \\left[ \\begin{matrix} \\cos{(2\\theta)} & - \\sin{(2\\theta) } \\\\ \\sin{(2\\theta) } & \\cos{(2\\theta) } \\end{matrix} \\right] \\\\\n  \\text{ Assume $n$th case is true}: A^n = \\left[ \\begin{matrix} \\cos{(n\\theta)} & -\\sin{(n\\theta)} \\\\ \\sin{(n\\theta)} & \\cos{(n\\theta)} \\end{matrix} \\right] \\\\\n  \\begin{aligned}\n  A^{n+1} & = \\left[ \\begin{matrix} \\cos{\\theta} & -\\sin{\\theta} \\\\ \\sin{\\theta} & \\cos{\\theta} \\end{matrix} \\right] \\left[ \\begin{matrix} \\cos{ (n\\theta)} & -\\sin{ (n\\theta) } \\\\ \\sin{(n \\theta) } & \\cos{ (n\\theta) } \\end{matrix} \\right] = \\left[ \\begin{matrix} \\cos{(n\\theta) } \\cos{\\theta} - \\sin{(n\\theta)} \\sin{\\theta} & -\\cos{\\theta}\\sin{(n\\theta)} - \\sin{\\theta} \\cos{(n\\theta)} \\\\\n      \\cos{(n\\theta) }\\sin{\\theta} + \\cos{\\theta} \\sin{(n\\theta) } & - \\sin{\\theta} \\sin{(n\\theta)} + \\cos{(n\\theta)}\\cos{\\theta} \\end{matrix} \\right] \\\\\n  & = \\left[ \\begin{matrix} \\cos{ (n+1) \\theta} & -\\sin{ (n+1)\\theta} \\\\ \n      \\sin{(n+1)\\theta} & \\cos{(n+1)\\theta} \\end{matrix} \\right]\n  \\end{aligned}\n\\end{gathered}\n\\]\n\n\\exercisehead{8} Let $A = \\left[ \\begin{matrix} 1 & 1 & 1 \\\\ 0 & 1 & 1 \\\\ 0 & 0 & 1 \\end{matrix} \\right]$ \n\\[\n\\begin{aligned}\n  A^2 & = \\left[ \\begin{matrix} 1 & 1 & 1 \\\\ 0 & 1 & 1 \\\\ 0 & 0 & 1 \\end{matrix} \\right] \\left[ \\begin{matrix} 1 & 1 & 1 \\\\ 0 & 1 & 1 \\\\ 0 & 0 & 1 \\end{matrix} \\right]  = \\left[ \\begin{matrix} 1 & 2 & 3 \\\\ 0 & 1 & 2 \\\\ 0 & 0 & 1 \\end{matrix} \\right] \\\\ \n  A^3 & = \\left[ \\begin{matrix} 1 & 1 & 1 \\\\ 0 & 1 & 1 \\\\ 0 & 0 & 1 \\end{matrix} \\right] \\left[ \\begin{matrix} 1 & 2 & 3 \\\\ 0 & 1 & 2 \\\\ 0 & 0 & 1 \\end{matrix} \\right] = \\left[ \\begin{matrix} 1 & 3 & 6 \\\\ 0 & 1 & 3 \\\\ 0 & 0 & 1 \\end{matrix} \\right] \\\\\n  A^4 & = \\left[ \\begin{matrix} 1 & 1 & 1 \\\\ 0 & 1 & 1 \\\\ 0 & 0 & 1 \\end{matrix} \\right] \\left[ \\begin{matrix} 1 & 3 & 6 \\\\ 0 & 1 & 3 \\\\ 0 & 0 & 1 \\end{matrix} \\right] = \\left[ \\begin{matrix} 1 & 4 & 10 \\\\ 0 & 1 & 4 \\\\ 0 & 0 & 1 \\end{matrix} \\right] \n\\end{aligned}\n \\quad \\quad \n\\begin{aligned}\n  & \\text{ (Assume $n$th case is true ) } \\\\\n  A^n & = \\left[ \\begin{matrix} 1 & n & \\frac{ n(n+1)}{2} \\\\ & 1 & n \\\\ & & 1 \\end{matrix} \\right] \\\\\n  A^{n+1} & = \\left[ \\begin{matrix} 1 & 1 & 1 \\\\ & 1 & 1 \\\\ & & 1 \\end{matrix} \\right]\\left[ \\begin{matrix} 1 & n & \\frac{n (n+1)}{2} \\\\ & 1 & n \\\\ & & 1 \\end{matrix} \\right] = \\left[ \\begin{matrix} 1 & n+1 & \\frac{ n^2 + n}{2} + \\frac{2n}{2} + \\frac{2}{2} \\\\\n      & 1 & n+1 \\\\\n      & & 1 \\end{matrix} \\right] = \\\\\n  & = \\left[ \\begin{matrix} 1 & n +1 & \\frac{ (n+2)(n+1)}{2} \\\\ & 1 & n+1 \\\\ & & 1 \\end{matrix} \\right]\n\\end{aligned}\n\\]\n\n\\exercisehead{9} Given $\\left[ \\begin{matrix} 1 & 0 \\\\ -1 & 1 \\end{matrix} \\right]$ \n\\[\nA^2 = \\left[ \\begin{matrix} 1 & 0 \\\\ -1 & 1 \\end{matrix} \\right] \\left[ \\begin{matrix} 1 & 0 \\\\ -1 & 1 \\end{matrix} \\right] = \\left[ \\begin{matrix} 1 & 0 \\\\ -2 & 1 \\end{matrix} \\right] = \\left[ \\begin{matrix} 2 & 0 \\\\ -2 & 2 \\end{matrix} \\right] - \\left[ \\begin{matrix} 1 & \\\\ & 1 \\end{matrix} \\right]\n\\]\nConsider that \n\\[\n\\begin{aligned}\n  A^3 & = 2A^2 - A = 2(2A -1) - A = 3A - 2 \\\\\n  A^4 & = (2A-1)(2A-1) = 4A^2 - 4A + 1 = 4(2A -1) - 4A + 1 = 4A -3 \n\\end{aligned}\n\\]\nThen assume the $n$th case, that $A^n = nA - (n-1)$.  \\\\\n\\[\n\\begin{aligned}\n  A^{n+1} & = nA^2 - (n-1)A = n(2A - 1) - (n-1)A = 2nA - n - nA + A = \\\\\n  & = (n+1)A - n\n\\end{aligned}\n\\]\nSo for $n=100$, we have $A^{100} = \\left[ \\begin{matrix} 1 & \\\\ 100 & 1 \\end{matrix} \\right]$\n\n\\exercisehead{10} If $A = \\left[ \\begin{matrix} a & b \\\\ c & d \\end{matrix} \\right]$, \n\\[\nA^2 = \\left[ \\begin{matrix} a^2 + bc & ab + bd \\\\ ac + cd & bc + d^2 \\end{matrix} \\right] = \\left[ \\begin{matrix} a^2 + bc & b(a+d) \\\\ (a+d)c & bc + d^2 \\end{matrix} \\right]\n\\]\nIf $b=0, d =0, a =0$, so $c=0$.  So the only other way for $A^2 = 0$ is for $a = -d \\neq 0$.  $a^2 + bc = 0$ or $a^2 = -bc$.   \\\\\nFor instance,\n\\[\n\\left[ \\begin{matrix} 1 & \\pm 1 \\\\ \\mp 1 & -1 \\end{matrix} \\right]\\left[ \\begin{matrix} 1 & \\pm 1 \\\\ \\mp 1 & - 1 \\end{matrix} \\right] = \\left[ \\begin{matrix} 0 & 0 \\\\ 0 & 0 \\end{matrix} \\right]\n\\]\n\n\\exercisehead{11} Let \\[\n\\begin{gathered}\n  A_{ij} = a_{ij} \\quad \\quad \\, \\begin{aligned} (E_{11})_{ij} & = \\delta_{1i} \\delta_{1j} \\\\ \n (E_{12})_{ij} & = \\delta_{1i} \\delta_{2j} \\\\ \n (E_{21})_{ij} & = \\delta_{2i} \\delta_{1j} \\\\ \n (E_{22})_{ij} & = \\delta_{2i} \\delta_{2j} \\\\ \n\\end{aligned}\n\\end{gathered}\n\\]\n\\begin{enumerate}\n\\item If $AB-BA = [A,B] = 0$ \\, $\\forall \\, B \\in M_{22}$, then since $E_{ij} \\in M_{22}$, $[A,E_{ij}] =0$ \\, $\\forall \\, i = 1,2,3,4$.  \\\\\n\n If $[A,E_{ij}] = 0$, then since $\\forall \\, B \\in M_{22}$, $B = \\sum b_{ij} E_{ij}$, so that \n\\[\n[A,B] = [A, \\sum b_{ij} E_{ij} ] = \\sum b_{ij} [A,E_{ij} ] = 0 \n\\]\n\\item Given $[A,E_{ij}] = 0$, \n\\[\n\\begin{aligned}\n  (AE_{lm})_{ij} & = \\sum_{k=1}^2 a_{ik} (E_{lm})_{kj} = \\sum_{k=1}^2 a_{ik} \\delta_{lk} \\delta_{mj} = \\\\\n  & = a_{il} \\delta_{mj} \\\\\n  (E_{lm} A)_{ij} & = \\sum_{k=1}^2 (E_{lm})_{ik} a_{kj} = \\sum_{k=1}^2 \\delta_{li} \\delta_{mk} a_{kj} = \\\\\n  & = \\delta_{li} a_{mj}\n\\end{aligned} \\quad \\quad \\, \\Longrightarrow (AE_{lm} - E_{lm} A)_{ij} = a_{il} \\delta_{mj} - \\delta_{li} a_{mj} = 0 \\text{ or } a_{il} \\delta_{mj} = \\delta_{li} a_{mj} \n\\]\n\\[\n\\begin{aligned}\n  & \\text{ if } m = j, \\, a_{il} = \\delta_{li} a_{jj}, \\quad \\, & \\begin{aligned} & \\text{ if } l = i, \\, a_{ii} = a_{jj} \\\\ & \\text{ if } l \\neq i , \\, a_{il} = 0 \\end{aligned} \\\\ \n  & \\text{ if } m \\neq j , \\, \\delta_{li} a_{mj} = 0 , \\quad \\, & \\begin{aligned} & \\text{ if } l = i, \\, a_{mj} = 0 \\\\ & \\text{ if } l \\neq i, \\, a_{mj} \\text{ unknown } \\end{aligned}\n\\end{aligned}\n\\]\n$i,j$ is completely arbitrary, and $(AE_{lm} - E_{lm} A)_{ij}  =0 $ must be true $\\forall \\, i = 1,2, \\, j = 1,2$, then $\\left[ \\begin{matrix} a & 0 \\\\ 0 & a \\end{matrix} \\right] = a I $ is the $A$.  \n\\end{enumerate}\n\n\\exercisehead{12} Suppose $A$ s.t. $A^2 = I$. \\\\\n$(A^2)_{ij} = \\sum_{k=1}^2 a_{ik} a_{kj} = \\delta_{ij}$ \n\\[\n\\begin{aligned}\n  & \\text{ if } i = j, & \\sum_{k=1}^2 a_{ik} a_{ki} = 1 & \\Longrightarrow a_{i1} a_{1i} + a_{i2} a_{2i} = 1 \\\\\n  & \\text{ if } i \\neq j, & \\sum_{k=1}^2 a_{ik} a_{kj} = 0 & \\Longrightarrow a_{i1} a_{1j} = -a_{i2} a_{2j} \n\\end{aligned}\n\\]\nIf $a_{11} = 0$, $a_{12}a_{21} = 1$ but $0 = -a_{12} a_{21}$.  Similar if $a_{22} =0$.  Then $a_{11}, a_{22} \\neq 0$ \\\\\n\nIf $a_{12} =0$, \\\\\n\\phantom{If }$\\begin{aligned}\n  a_{11}^2 & = 1 \\\\ \n a_{22}^2 & = 1 \n\\end{aligned}$\n\n\\phantom{If } if $a_{21} =0 $, then $A = \\pm \\left[ \\begin{matrix} 1 & 0 \\\\ 0 & -1 \\end{matrix} \\right]$, $\\pm \\left[ \\begin{matrix} 1 & 0 \\\\ 0 & 1 \\end{matrix} \\right]$ \\\\\n\\phantom{ If If } if $a_{21} \\neq 0$, $a_{21}a_{11} = - a_{22} a_{21} \\Longrightarrow a_{11} = -a_{22}$ \\\\\nIf $a_{21} =0$, $a_{11}^2 = a_{22}^2 = 1$ \\\\\n\\quad \\, if $a_{21} \\neq 0$, then $a_{11} a_{12} = -a_{12} a_{22} \\Longrightarrow a_{11} = - a_{22}$ \n\nIf $a_{12}, a_{21} \\neq 0$, then \\\\\n$\\begin{aligned}\na_{11}^2 + a_{12}a_{21} &= 1\na_{22}^2 + a_{12}a_{21} &= 1\n\\end{aligned}$  \n\\[\n\\Longrightarrow \\left[ \\begin{matrix} \\sqrt{ 1 - bc} & b \\\\ c & -\\sqrt{ 1 - bc} \\end{matrix} \\right]\n\\]\n\n\\exercisehead{13} Given \\\\\n$A = \\left[ \\begin{matrix} 2 & -1 \\\\ -2 & 3 \\end{matrix} \\right]$, \\, $B = \\left[ \\begin{matrix} 7 & 6 \\\\ 9 & 8 \\end{matrix} \\right]$.  Find $2\\times 2$ matrices $C$ and $D$ s.t. $\\begin{aligned} AC & = B \\\\ DA & = B \\end{aligned}$  \n\\[\nA^{-1} = \\frac{1}{4} \\left[ \\begin{matrix} 3 & 1 \\\\ 2 & 2 \\end{matrix} \\right] \\quad \\quad \\, \\begin{aligned} & A^{-1} AC = C = A^{-1} B \\\\ & DAA^{-1} = D = BA^{-1} \\end{aligned} \\quad \\quad \\, \\begin{aligned} & \\frac{1}{4} \\left[ \\begin{matrix} 3 & 1 \\\\ 2 & 2 \\end{matrix} \\right] \\left[ \\begin{matrix} 7 & 6 \\\\ 9 & 8 \\end{matrix} \\right] = \\frac{1}{4} \\left[ \\begin{matrix} 30 & 26 \\\\ 32 & 28 \\end{matrix} \\right] & = C \\\\ & \\left[ \\begin{matrix} 7 & 6 \\\\ 9 & 8 \\end{matrix} \\right] \\frac{1}{4} \\left[ \\begin{matrix} 3 & 1 \\\\ 2 & 2 \\end{matrix} \\right] = \\frac{1}{4} \\left[ \\begin{matrix} 33 & 19 \\\\ 43 & 25 \\end{matrix} \\right] & = D\n\\end{aligned}\n\\]\n\n\\exercisehead{14} \\begin{enumerate}\n\\item \\[\n\\begin{aligned}\n  AB & = \\left[ \\begin{matrix} 1 & -1 \\\\ 0 & 2 \\end{matrix} \\right]\\left[ \\begin{matrix} 1 & 0 \\\\ 1 & 2 \\end{matrix} \\right]  & = \\left[ \\begin{matrix} 0 & -2 \\\\ 2 & 4 \\end{matrix} \\right] \\\\ BA & = \\left[ \\begin{matrix} 1 & 0 \\\\ 1 & 2 \\end{matrix} \\right]\\left[ \\begin{matrix} 1 & - 1 \\\\ 0 & 2 \\end{matrix} \\right] & = \\left[ \\begin{matrix} 1 & -1 \\\\ 1 & 3 \\end{matrix} \\right] \n\\end{aligned} \\quad \\quad \\, AB \\neq BA\n\\]\n\\item \\[ \\begin{aligned}\n  & (A+B)^2  = A^2 + AB + BA + B^2 \\\\\n  & (A+B)(A-B) = A^2 - AB + BA - B^2\n\\end{aligned}\n\\]\n\\item $[A,B] =0$\n\\end{enumerate}\n\n\n%-----------------------------------%-----------------------------------%-----------------------------------\n\\section*{ 2.20 Exercises - Systems of linear equations, Computation techniques, Inverses of square matrices }\n%-----------------------------------%-----------------------------------%-----------------------------------\n\n\\exercisehead{1} \n\\[\n\\begin{gathered}\n  \\left[ \\begin{matrix} 1 & 1 & 3 \\\\ 2 & -1 & 4 \\\\ & -1 & 1 \\end{matrix} \\right] \\left[ \\begin{matrix} x \\\\ y \\\\ z \\end{matrix} \\right] = \\left[ \\begin{matrix} 5 \\\\ 11 \\\\ 3 \\end{matrix} \\right] \\\\\n  \\left[ \\begin{matrix} 1 & 1 & 3 \\\\ 2 & -1 & 4  \\\\ & -1 & 1 \\end{matrix} \\right| \\left. \\begin{matrix} 5 \\\\ 11 \\\\3 \\end{matrix} \\right] = \\left[ \\begin{matrix} 1 & 0 & 4 \\\\ 2 & 0 & 3 \\\\ & -1 & 1 \\end{matrix} \\right| \\left. \\begin{matrix} 8 \\\\ 8 \\\\ 3 \\end{matrix} \\right] = \\left[ \\begin{matrix} 1 & 0 & 0 \\\\ 0 & 0 & 1 \\\\ 0 &  1 & 0 \\end{matrix} \\right| \\left. \\begin{matrix} 8/5 \\\\ 8/5 \\\\ -7/5 \\end{matrix} \\right]\n\\end{gathered}\n\\]\n\n\\exercisehead{2} Solution doesn't exist since \n\\[\n\\begin{aligned}\n  5x + 3y + 3z & = 2 \\\\\n  3x + 2y + z & = 1 \n\\end{aligned} \\quad \\quad \\, \\Longrightarrow x+ y - z = 0 \\text{ but } x + y - z = 1 \n\\]\n\n\\exercisehead{3}\n\\[\n\\left[ \\begin{matrix} 3 & 2 & 1 \\\\ 5 & 3 & 3 \\\\ 7 & 4 & 5 \\end{matrix} \\right| \\left. \\begin{matrix} 1 \\\\ 2 \\\\ 3 \\end{matrix} \\right] = \\left[ \\begin{matrix} 0 & 2 & -8 \\\\ 0 & 3 & -12 \\\\ 1 & 0 & 3 \\end{matrix} \\right| \\left. \\begin{matrix} -2 \\\\ -3 \\\\ 1 \\end{matrix} \\right] = \\left[ \\begin{matrix} 0 & 0 & 0 \\\\ 0 & 1 & -4 \\\\ 1 & 0 & 3 \\end{matrix} \\right| \\left. \\begin{matrix} 0 \\\\ -1 \\\\ 1 \\end{matrix} \\right] \n\\]\n\\[\n\\begin{aligned}\n  x & = 1 - 3z \\\\\n  y & = -1 + 4 z \n\\end{aligned} \\quad \\Longrightarrow \\boxed{\\left( \\begin{matrix} x \\\\ y \\\\ z \\end{matrix} \\right) = \\left( \\begin{matrix} 1 \\\\ -1 \\\\ 0 \\end{matrix} \\right) + z \\left( \\begin{matrix} -3 \\\\ 4 \\\\ 1 \\end{matrix} \\right) }\n\\]\n\n\\exercisehead{4}\n\\[\n\\left[ \\begin{matrix} 7 & 4 & 5 \\\\ 1 & 1 & -1 \\end{matrix} \\right| \\left. \\begin{matrix} 3 \\\\ 0 \\end{matrix} \\right] = \\left[ \\begin{matrix} 0 & -3 & 12 \\\\ 1 & 1 & -1 \\end{matrix} \\right| \\left. \\begin{matrix} 3 \\\\ 0 \\end{matrix} \\right] = \\left[ \\begin{matrix} 1 & 0 & 3 \\\\ 0 & 1 & -4 \\end{matrix} \\right| \\left. \\begin{matrix} 1 \\\\ -1 \\end{matrix} \\right]\n\\]\n\\[\n\\begin{aligned}\n  x + 3z & = 1 \\\\\n  y - 4 z & = -1 \n\\end{aligned} \\quad \\, \\boxed{ \\left( \\begin{matrix} x \\\\ y \\\\ z \\end{matrix} \\right) = \\left( \\begin{matrix} 1 \\\\ -1 \\\\ 0 \\end{matrix} \\right) + z\\left( \\begin{matrix} -3 \\\\ 4 \\\\ 1 \\end{matrix} \\right) }\n\\]\n\n\\exercisehead{5} \n\\[\n\\left[ \\begin{matrix} 3 & -2 & 5 & 1 \\\\ 1 & 1 & -3 & 2 \\\\ 6 & 1 & -4 & 3 \\end{matrix} \\right| \\left. \\begin{matrix} 1 \\\\ 2 \\ 7 \\end{matrix} \\right] = \\left[ \\begin{matrix} 0 & -5 & 14 & -5 \\\\ 1 & 1 & -3 & 2 \\\\ 0 & -5 & 14 & -9 \\end{matrix} \\right| \\left. \\begin{matrix} -5 \\\\ 2 \\ -5 \\end{matrix} \\right] = \\left[ \\begin{matrix} 0 & 0 & 0 & 4 \\\\ 1 & 1 & -3 & 0 \\\\0 & -5 & 14 & 0 \\end{matrix} \\right| \\left. \\begin{matrix} 0 \\\\ 2 \\ -5 \\end{matrix} \\right]  \\quad \\, \\Longrightarrow \\boxed{ \\left( \\begin{matrix} x \\\\ y \\\\ z \\\\ u \\end{matrix} \\right) = \\left( \\begin{matrix} 1 \\\\ 1 \\\\ 0 \\\\ \\end{matrix} \\right) + z \\left( \\begin{matrix} 1/5 \\\\ 14/5 \\\\ 1 \\\\ 0 \\end{matrix} \\right) }\n\\]\n\n\\exercisehead{6}\n\\[\n\\left[ \\begin{matrix} 1 & 1 & -3 & 1 \\\\ 2 & -1 & 1 & -2 \\\\ 7 & 1 & -7 & 3  \\end{matrix} \\right| \\left. \\begin{matrix} 5 \\\\ 2 \\\\ 3 \\end{matrix} \\right] = \n\\left[ \\begin{matrix} 1 & 1 & -3 & 1 \\\\ 0 & -3 & 7 & -4 \\\\ 0 & -6 & 14 & -4  \\end{matrix} \\right| \\left. \\begin{matrix} 5 \\\\ -8 \\\\ -32 \\end{matrix} \\right] = \\left[ \\begin{matrix} 1 & 1 & -3 & 1 \\\\ 0 & 0 & 0 & -2 \\\\ 0 & -1 & 7/3 & -2/3  \\end{matrix} \\right| \\left. \\begin{matrix} 5 \\\\ 8 \\\\ -16/3 \\end{matrix} \\right] = \\left[ \\begin{matrix} 1 & 0 & -2/3 & 0 \\\\ 0 & 0 & 0 & 1 \\\\ 0 & 1 & -7/3 & 0  \\end{matrix} \\right| \\left. \\begin{matrix} 1 \\\\ -4 \\\\ 8 \\end{matrix} \\right]\n\\]\n\\[\n\\begin{aligned}\n  x + \\frac{-2}{3} z & = 1 \\\\\n  u & = -4 \\\\\n  y - \\frac{7}{3} z & = 8 \n\\end{aligned} \\quad \\, \\boxed{ \\left( \\begin{matrix} x \\\\ y \\\\ z \\\\ u \\end{matrix} \\right)  = \\left( \\begin{matrix} 1 \\\\ 8 \\ 0 \\\\ -4 \\end{matrix} \\right) + z \\left( \\begin{matrix} 2/3 \\\\ 7/3  \\\\ 1 \\\\ 0 \\end{matrix} \\right) }\n\\]\n\n\\exercisehead{7}\n\\[\n\\left[ \\begin{matrix} 1 & 1 & 2 & 3 & 4 \\\\ 2& 2 & 7 & 11 & 14 \\\\ 3& 3& 6 & 10 & 15 \\end{matrix} \\right| \\left. \\begin{matrix} 0 \\\\ 0 \\\\ 0 \\end{matrix} \\right] = \\left[ \\begin{matrix} 1 & 1 & 2 & 3 & 4 \\\\ 0 & 0 & 3 & 5 & 6 \\\\ 0 & 0 & 0 & 1 & 3 \\end{matrix} \\right| \\left. \\begin{matrix} 0 \\\\ 0 \\\\ 0 \\end{matrix} \\right]  \\Longrightarrow \\begin{aligned} x + y & = -v \\\\ z & = 3v \\\\ u & = -3v \\end{aligned} \\Longrightarrow \\boxed{ \\left( \\begin{matrix} x \\\\ y \\\\ z \\\\ u \\\\ v \\end{matrix} \\right) = x \\left( \\begin{matrix} 1 \\\\ - 1 \\\\ 0 \\\\ 0 \\\\ 0 \\end{matrix} \\right) + v \\left( \\begin{matrix} 0 \\\\ -1 \\\\ 3 \\\\ -3 \\\\ 1 \\end{matrix} \\right) } \n\\]\n\n\\exercisehead{8} \n\\[\n\\left[ \\begin{matrix} 1 & -2 & 1 & 2 \\\\ 2 & 3 & -1 & -5 \\\\ 4 & -1 & 1 & -1 \\\\ 5 & -3 & 2 & 1 \\end{matrix} \\right| \\left. \\begin{matrix} -2 \\\\ 9 \\\\ 5 \\\\ 3 \\end{matrix} \\right] = \\left[ \\begin{matrix} 1 & -2 & 1 & 2 \\\\ 0 & 7 & -3 & -9 \\\\ 0 & 7 & -3 & -9 \\\\ 0 & 7 & -3 & -9 \\end{matrix} \\right| \\left. \\begin{matrix} -2 \\\\ 13 \\\\ 13 \\\\ 13 \\end{matrix} \\right] \\Longrightarrow \\begin{aligned} x + \\frac{1}{7} z - \\frac{4}{7} u & = \\frac{12}{7} \\\\ y + \\frac{-3}{7} z - \\frac{9}{7} u & = \\frac{13}{7} \\end{aligned} \\]\n\\[\n\\Longrightarrow \\boxed{ \\left[ \\begin{matrix} x \\\\ y \\\\ z \\\\ u \\end{matrix} \\right] = \\left( \\begin{matrix} 12/7 \\\\ 13/7 \\\\ 0 \\\\ 0 \\end{matrix} \\right) + z \\left( \\begin{matrix} -1/7 \\\\ 3/7 \\\\ 1 \\\\ 0 \\end{matrix} \\right) + u \\left( \\begin{matrix} 4/7 \\\\ 9/7 \\\\ 0 \\\\ 1 \\end{matrix} \\right) }\n\\]\n\n\\exercisehead{9} \n\\[\n\\left[ \\begin{matrix} 1 & 1 & 2 \\\\ 2 & -1 & 3 \\\\ 5 & -1 & a \\end{matrix} \\right. \\left| \\begin{matrix} 2 \\\\ 2 \\\\ 6 \\end{matrix} \\right] = \\left[ \\begin{matrix} 1 & 1 & 2 \\\\ 0 & -3 \\\\ &  -1 \\\\ 0 & -6 & a - 10 \\end{matrix} \\right| \\left. \\begin{matrix} 2 \\\\ -2 \\\\ -4 \\end{matrix} \\right] \\quad \\, \\text{ if } a - 8 \\neq 0, \\quad \\, \\left( \\begin{matrix} x \\\\ y \\\\ z \\end{matrix} \\right) = \\left( \\begin{matrix} 4/3 \\\\ 2/3 \\\\ 0 \\end{matrix} \\right)\n\\]\n\\[\n\\text{ if } a = 8, \\quad \\, \\left[ \\begin{matrix} 1 & 1 & 2 \\\\ & -3 & -1 \\end{matrix} \\right| \\left. \\begin{matrix} 2 \\\\ -2 \\end{matrix} \\right] = \\left[ \\begin{matrix} 1 & 0 & 5/3 \\\\ & 1 & 1/3 \\end{matrix} \\right. \\left| \\begin{matrix} 4/3 \\\\ 2/3 \\end{matrix} \\right] \\Longrightarrow \\left( \\begin{matrix} x \\\\ y \\\\ z \\end{matrix} \\right) = z \\left( \\begin{matrix} -5/3 \\\\ -1/3 \\\\ 1 \\end{matrix} \\right) + \\left( \\begin{matrix} 4/3 \\\\ 2/3 \\\\ 0 \\end{matrix} \\right) \n\\]\n\n\\exercisehead{10} \n\\begin{enumerate}\n\\item  \\[\n\\left( \\begin{matrix} x \\\\ y \\\\ z \\\\ u \\end{matrix} \\right) = \\left( \\begin{matrix} -5/7 \\\\ 9/7 \\\\ 0 \\\\ 0 \\end{matrix} \\right) + z \\left( \\begin{matrix} 4/7 \\\\ 11/7 \\\\ 1 \\\\ 0 \\end{matrix} \\right) +  u \\left( \\begin{matrix} 0 \\\\ -1 \\\\ 0 \\\\ 1 \\end{matrix} \\right)\n\\]\n\\item \n\\[\n\\left[ \\begin{matrix} 5 & 2 & -6 2 \\\\ 1 & -1 & 1 & -1 \\\\ 1 & 1 & 1 & 0 \\end{matrix} \\right| \\left. \\begin{matrix} -1 \\\\ -2 \\\\ 6 \\end{matrix} \\right] = \\left[ \\begin{matrix} 0 & -3 & -11 & 2 \\\\ 0 & -2 & 0 & -1 \\\\ 1 & 1 & 1 & 0 \\end{matrix} \\right. \\left| \\begin{matrix} -31 \\\\ -8 \\\\ 6 \\end{matrix} \\right] = \\left[ \\begin{matrix} 0 & 0 & -11 & 7/2 \\\\ 0 & 1 & 0 & 1/2 \\\\ 1 & 0 & 1 & -1/2 \\end{matrix} \\right. \\left| \\begin{matrix} -19 \\\\ 4 \\\\ 2 \\end{matrix} \\right] = \\left[ \\begin{matrix} 1 & 0 & 0 & -2/11 \\\\ 0 & 1 & 0 & 1/2 \\\\ 0 & 0 & -1 & 7/22 \\end{matrix} \\right. \\left| \\begin{matrix} 3/11 \\\\ 4 \\\\ -19/11 \\end{matrix} \\right] \\\\\n\\]\n\\[\n\\boxed{ \\left( \\begin{matrix} x \\\\ y \\\\ z \\\\ u \\end{matrix} \\right) = \\left( \\begin{matrix} 3/11 \\\\ 4 \\\\ 19/11 \\\\ 0 \\end{matrix} \\right) + u \\left( \\begin{matrix} 2/11 \\\\ -1/2 \\\\ 7/22 \\\\ 1 \\end{matrix} \\right) }\n\\]\n\\end{enumerate}\n\n\\exercisehead{11} \n\\[\n\\left[ \\begin{matrix} a & b \\\\ c & d \\end{matrix} \\right] \\left[ \\begin{matrix} d & -b \\\\ -c & a \\end{matrix} \\right] = \\left[ \\begin{matrix} ad -bc & -ba + ba \\\\ cd -cd & -bc + ad \\end{matrix} \\right] = (ad-bc) I \n\\] \nIf $ad-bc \\neq 0$, then for $A = \\left[ \\begin{matrix} a & b \\\\ c & d \\end{matrix} \\right]$, \n\\[\nA^{-1} = \\frac{1}{ad-bc} \\left[ \\begin{matrix} d & -b \\\\ -c & a \\end{matrix} \\right] \n\\]\notherwise, if $ad-bc =0$, $\\left[ \\begin{matrix} a & b \\\\ c & d \\end{matrix} \\right] \\left[ \\begin{matrix} d & -b \\\\ -c & a \\end{matrix} \\right] = 0$ \\\\\n\nUse thm. from determinants.\n\\[\n\\begin{gathered}\n  det(AA^{-1}) = det{A} det{A^{-1}} = det{I} = 1 \\\\\n  det{A}, \\, det{A^{-1}} \\neq 0 \n\\end{gathered}\n\\]\n\n\\exercisehead{12} $\\left[ \\begin{matrix} 2 & 3 & 4 \\\\ 2 & 1 & 1 \\\\ -1 & 1 & 2 \\end{matrix} \\right]$.  \n\\[\n\\begin{gathered}\n  \\left[ \\begin{matrix} 2 & 3 & 4 \\\\ 2 & 1 & 1 \\\\ -1 & 1 & 2 \\end{matrix} \\right. \\left| \\begin{matrix} 1 & & \\\\ & 1 & \\\\ & & 1 \\end{matrix} \\right] =   \\left[ \\begin{matrix} 0 & 5 & 8 \\\\ 0 & 3 & 5 \\\\ -1 & 1 & 2 \\end{matrix} \\right. \\left| \\begin{matrix} 1 & & 2 \\\\ & 1 & 1 \\\\ & & 1 \\end{matrix} \\right] =   \\left[ \\begin{matrix} 0 & 1 & 8/5 \\\\ 0 & 0 & 1/5 \\\\ 1 & -1 & 2 \\end{matrix} \\right. \\left| \\begin{matrix} 1/5 & 0 & 2/5  \\\\ -3/5  & 1 & 4/5 \\\\ & & -1 \\end{matrix} \\right] = \\\\\n=   \\left[ \\begin{matrix} 0 & 1 & 0 \\\\ 0 & 0 & 1 \\\\ 1 & -1 & 0 \\end{matrix} \\right. \\left| \\begin{matrix} 5 & -8 & -6 \\\\ -3 & 5 & 4 \\\\ -6 & 10 & 7 \\end{matrix} \\right] =   \\left[ \\begin{matrix} 0 & 1 & 0 \\\\ 0 & 0 & 1 \\\\ 1 & 0 & 0 \\end{matrix} \\right. \\left| \\begin{matrix} 5 & -8 & -6 \\\\ -3 & 5 & 4 \\\\ -3  & 5 & 4  \\end{matrix} \\right] =   \n\\end{gathered}\n\\]\n\\[\n\\Longrightarrow \\boxed{ \\left[ \\begin{matrix} -1 & 2 & 1 \\\\ 5 & -8 & -6 \\\\ -3 & 5 & 4 \\end{matrix} \\right] }\n\\]\n\n\\exercisehead{13} \n\\[\n\\begin{gathered}\n    \\left[ \\begin{matrix} 1 & 2 & 2 \\\\ 2 & -1 & 1 \\\\ 1 & 3 & 2 \\end{matrix} \\right. \\left| \\begin{matrix} 1 & & \\\\ & 1 & \\\\ & & 1 \\end{matrix} \\right] = \n  \\left[ \\begin{matrix} 1 & 0 & 2 \\\\ 0 & -1 & -3 \\\\ 0 & 1 & 0 \\end{matrix} \\right. \\left| \\begin{matrix} 3 & & -2 \\\\ -6 & 1 & 4 \\\\ -1 & 0 & 1 \\end{matrix} \\right] = \n  \\left[ \\begin{matrix} 1 & 0 & 2 \\\\ 0 & 0 & -3 \\\\ 0 & 1 & 0 \\end{matrix} \\right. \\left| \\begin{matrix} 3 & & 2 \\\\ -7 & 1 & 5 \\\\ -1 & & 1 \\end{matrix} \\right] =\n  \\left[ \\begin{matrix} 1 &  &  \\\\  &  & 1 \\\\  & 1 &  \\end{matrix} \\right. \\left| \\begin{matrix} -5/3 & 2/3 & 4/3 \\\\ 7/3 & -1/3 & -5/3 \\\\ -1 & & 1 \\end{matrix} \\right] \\\\\n  \\boxed{ \\left[ \\begin{matrix} \\frac{-5}{3} & \\frac{2}{3} & \\frac{4}{3} \\\\ -1 & 0 & 1 \\\\ \\frac{7}{3} & \\frac{-1}{3} & \\frac{-5}{3} \\end{matrix} \\right] }\n\\end{gathered}\n\\]\n\n\\exercisehead{14} \n\\[\n\\begin{gathered}\n  \\left[ \\begin{matrix} 1 & -2 & 1 \\\\ -2 & 5 & -4 \\\\ 1 & -4 & 6 \\end{matrix} \\right. \\left| \\begin{matrix} 1 & & \\\\ & 1 & \\\\ & & 1 \\end{matrix} \\right] = \n    \\left[ \\begin{matrix} 1 & 0 & -3 \\\\ 0 & 1 & -2 \\\\ 0 & -2 & 5 \\end{matrix} \\right. \\left| \\begin{matrix} 5 & 2 & \\\\ 2 & 1 & \\\\ -1 & & 1 \\end{matrix} \\right] = \n  \\left[ \\begin{matrix} 1 &  &  \\\\  & 1 &  \\\\  &  & 1 \\end{matrix} \\right. \\left| \\begin{matrix} 14 & 8 & 3 \\\\ 8 & 5 & 2 \\\\ 3 & 2  & 1 \\end{matrix} \\right]  \\\\\n  \\boxed{ \\left[ \\begin{matrix} 14 & 8 & 3 \\\\ 8 & 5 & 2 \\\\ 3 & 2 & 1 \\end{matrix} \\right] }\n\\end{gathered}\n\\]\n\n\\exercisehead{15} \n\\[\n\\begin{gathered}\n  \\left[ \\begin{matrix} 1 & 2 & 3 & 4 \\\\ & 1 & 2 & 3 \\\\ & & 1 & 2 \\\\ & & & 1 \\end{matrix} \\right. \\left| \\begin{matrix} 1 & & & \\\\ & 1 & & \\\\ & & 1 & \\\\ & & & 1 \\end{matrix} \\right] = \n  \\left[ \\begin{matrix} 1 &  & -1 & -2 \\\\ & 1 &  & -1 \\\\ & & 1 &  \\\\ & & & 1 \\end{matrix} \\right. \\left| \\begin{matrix} 1 & -2  & & \\\\ & 1 & -2 & \\\\ & & 1 & -2 \\\\ & & & 1 \\end{matrix} \\right] = \n  \\left[ \\begin{matrix} 1 &  &  & -2 \\\\ & 1 &  &  \\\\ & & 1 &  \\\\ & & & 1 \\end{matrix} \\right. \\left| \\begin{matrix} 1 & -2 & 1 & -2 \\\\ & 1 & -2 & 1 \\\\ & & 1 & -2 \\\\ & & & 1 \\end{matrix} \\right] = \\\\\n \\boxed{ \\left[ \\begin{matrix} 1 & -2 & 1 & 0 \\\\ & 1 & -2 & 1 \\\\ & & 1 & -2 \\\\ 1 \\end{matrix} \\right] }\n\\end{gathered}\n\\]\n\n\\exercisehead{16} $\\left[ \\begin{matrix} & 1 & & & &  \\\\ 2 & 0 & 2 & & & \\\\ & 3 & & 1 & & \\\\ & & 1 & & 2 & \\\\ & & & 3 & & 1 \\\\ & & &  & 2 & \\end{matrix} \\right]^{-1} = \\left[ \\begin{matrix} & 1/2 & & -1 & & 1 \\\\ 1 & & & & & \\\\ & & & 1 & & -1 \\\\ -3 & & 1 & & & \\\\ & & & & & 1/2 \\\\ 9 & & -3 & & 1 & \\end{matrix} \\right] $\n\n\n%-----------------------------------%-----------------------------------%-----------------------------------\n\\section*{ 2.21 Miscellaneous exercises on matrices }\n%-----------------------------------%-----------------------------------%-----------------------------------\n\n\\exercisehead{3} Use the eigenvalue method.  \n\\[\n\\begin{aligned}\n  \\left[ \\begin{matrix} 1 & 2 \\\\ 5 & 4 \\end{matrix} \\right]\\left[ \\begin{matrix} x \\\\ y \\end{matrix} \\right] = -\\left[ \\begin{matrix} x \\\\ y \\end{matrix} \\right]  & \\Longrightarrow \\left[ \\begin{matrix} x \\\\ y \\end{matrix} \\right] = \\left[ \\begin{matrix} 1 \\\\ -1 \\end{matrix} \\right] \\\\\n  \\left[ \\begin{matrix} 1 & 2 \\\\ 5 & 4 \\end{matrix} \\right] \\left[ \\begin{matrix} x \\\\ y \\end{matrix} \\right] = 6 \\left[ \\begin{matrix} x \\\\ y \\end{matrix} \\right] & \\Longrightarrow \\begin{aligned} x + 2y & = 6x \\\\ 2y & = 5x \\end{aligned} \\quad \\, \\left[ \\begin{matrix} x \\\\ y \\end{matrix} \\right] = \\left[ \\begin{matrix} 2 \\\\ 5 \\end{matrix} \\right] \n\\end{aligned}\n\\]\nIndeed, we obtain $P$ since\n\\[\n\\begin{gathered}\n  \\left[ \\begin{matrix} 1 & 2 \\\\ 5 & 4 \\end{matrix} \\right] \\left[ \\begin{matrix} \\frac{2}{\\sqrt{29} } & \\frac{1}{\\sqrt{2}} \\\\ \\frac{5}{\\sqrt{29}} & \\frac{-1}{\\sqrt{2}} \\end{matrix} \\right] = \\left[ \\begin{matrix} \\frac{12}{\\sqrt{29}} & \\frac{-1}{\\sqrt{2}} \\\\ \\frac{30}{\\sqrt{29}} & \\frac{-1}{\\sqrt{2}} \\end{matrix} \\right] \\\\\n  \\frac{1}{ \\frac{-7 }{\\sqrt{58}} } \\left[ \\begin{matrix} \\frac{-1}{\\sqrt{2}} & \\frac{-1}{\\sqrt{2}} \\\\ \\frac{-5}{\\sqrt{29}} & \\frac{2}{\\sqrt{29}} \\end{matrix} \\right] \\left[ \\begin{matrix} 1 & 2 \\\\ 5 & 4 \\end{matrix} \\right] \\left[ \\begin{matrix} \\frac{2}{\\sqrt{29}} & \\frac{1}{\\sqrt{2}} \\\\ \\frac{5}{\\sqrt{29}} & \\frac{-1}{\\sqrt{2}}\\end{matrix} \\right] = \\left[ \\begin{matrix} 6 & \\\\ & -1 \\end{matrix} \\right] \\\\\n\\boxed{ P = \\left[ \\begin{matrix} \\frac{2}{\\sqrt{29}} & \\frac{1}{\\sqrt{2}} \\\\ \\frac{5}{\\sqrt{29}}  & \\frac{-1}{\\sqrt{2}} \\end{matrix} \\right] }\n\\end{gathered}\n\\]\n\n\\exercisehead{4} $(A^2)_{ij} = \\sum_{k=1}^2 a_{ik} a_{kj} = a_{il} a_{1j} + a_{i2} a_{2j} = a_{ij} $ \\\\\nIf $i = j$, $a_{i1} a_{1i} + a_{i2} a_{2i} = a_{ii}$ \\\\\n\\quad \\, it must be that $i=1$ or $i=2$.  Then rewrite as $a_{ii}^2 + a_{ij} a_{ji} = a_{ii}$ \\\\\nIf $i \\neq j$.  $a_{i1} a_{1j} + a_{i2}a_{2j} = a_{ij}$ \\\\\n\\quad \\, it must be that $i=1$ or $i=2$ and $j=2$ or $j=1$, respectively.  then \n\\[\na_{ii} a_{ij} + a_{ij} a_{jj} = a_{ij}\n\\]\nIf $a_{ij} = 0$, $a_{ii}^2 = a_{ii}$.  \\quad \\, $a_{ii} = 1$\n\\[\n\\left[ \\begin{matrix} 1 & a \\\\ 0 & 1 \\end{matrix} \\right] \\left[ \\begin{matrix} 1 & a \\\\ 0 & 1 \\end{matrix} \\right] = \\left[ \\begin{matrix} 1 & 2a \\\\ 0 & 1 \\end{matrix} \\right] = A \\Longrightarrow a = 2a, \\text{ so } a =0\n\\]\nIf $a_{ij} \\neq 0$, $a_{ii} + a_{jj} =1$ \\\\\nNote that $a_{ij}, a_{ji}$ must be both nonzero for the following: \n\\[\n\\begin{gathered}\n  a_{ii}^2 - a_{ii} + a_{ij} a_{ji} = 0 \\\\\n  \\begin{aligned}\n    a_{ii} & = \\frac{ 1 \\pm \\sqrt{ 1 - 4 a_{ij} a_{ji} } }{ 2 } \\\\\n    a_{jj} & = 1 - a_{ii} = \\frac{ 1 \\mp \\sqrt{ 1 - 4a_{ij} a_{ji} } }{ 2}\n\\end{aligned}\n\\end{gathered}\n\\]\n\n\\exercisehead{5} $A^2 = A$\n\\[\n\\begin{aligned}\n  (A+I)^2 & = 3A + I \\\\\n  (A+I)^3 & = (3A+I)(A+I) = 7A + I \\\\\n  (A+I)^{k+1} & = (I +(2^k - 1)A)(A+I) = A(1 + 2^k - 1) + I + (2^k -1)A = (2^{k+1} -1)A + I \n\\end{aligned}\n\\]\n\n\\exercisehead{6} \\quad \\\\ $\\begin{aligned} x' & = a(x-vt) \\\\ y' & = y \\\\ z' & = z \\\\ t'  & = a(t-vx/c^2) \\end{aligned}$ \n\\[\n\\begin{aligned}\n  L(v) & = a \\left[ \\begin{matrix} 1 & -v \\\\ -vc^{-2} & 1 \\end{matrix} \\right] \\\\\n  L(v)L(u) & = a \\left[ \\begin{matrix} 1 & -v \\\\ -vc^{-2} & 1 \\end{matrix} \\right] b \\left[ \\begin{matrix} 1 & -u \\\\ -uc^{-2} & 1 \\end{matrix} \\right] = ab \\left[ \\begin{matrix} 1 + uv /c^2 & -u -v \\\\ \\frac{ -v - u}{c^2} & \\frac{uv}{c^2} + 1 \\end{matrix} \\right] \\\\\n  & = \\frac{c}{\\sqrt{ c^2 - v^2} } \\frac{c}{\\sqrt{ c^2 - u^2} } \\left( 1 + \\frac{uv}{c^2} \\right) \\left[ \\begin{matrix} 1 & \\frac{ - (u+v)}{ 1 + uv/c^2 } \\\\ \\frac{ -(u+v) }{ 1 + \\frac{uv}{c^2} } & 1 \\end{matrix} \\right]\n\\end{aligned}\n\\]\n\\[\n\\begin{aligned}\n\\gamma & = \\frac{1}{ \\sqrt{ 1 - \\left( \\frac{w}{c} \\right)^2 } } = \\left( 1 - \\left( \\frac{ -(u+v) /c }{ (1 + \\frac{uv}{c^2} ) }\\right)^2 \\right)^{-1/2}  = \\left( \\left( 1 + \\frac{2uv}{c^2} + \\frac{u^2 v^2 }{c^4} - \\left( \\frac{u^2 + 2uv + v^2}{c^2} \\right) \\right)/\\left( 1 + \\frac{uv}{c^2} \\right)^2 \\right)^{-1/2} =  \\\\\n& = \\left( \\left( 1 + \\frac{u^2 v^2}{c^2} - \\frac{u^2}{c^2} - \\frac{v^2}{c^2} \\right)/\\left( 1 + \\frac{uv}{c^2} \\right)^2 \\right)^{-1/2}\n\\end{aligned}\n\\]\n\n\n\\exercisehead{7} \\begin{enumerate} \\item $(A^T)_{ij} = A_{ji}$ \\\\\n$  (A^T)^T_{ij} = (A^T)_{ji} = A_{ij} \\Longrightarrow (A^T)^T = A$\n\\item $(A+B)^T_{ij} = (A+B)_{ji} = A_{ji} + B_{ji} = A^T_{ij} + B^T_{ij} \\Longrightarrow (A+B)^T = A^T + B^T$\n\\item $(cA)^T_{ij} = (cA)_{ji} = c_A{ji} = c(A^T)_{ij}$\n\\item $(AB)^T_{ij} = (AB)_{ji} = \\sum_{k} a_{jk} b_{ki} = \\sum_k b_{ki} a_{jk} = \\sum_k (B^T)_{ik} (A^T)_{kj} = (B^T A^T)_{ij}$\n\\item $A^{-1}A =1 \\Longrightarrow (A^{-1} A)^T = A^T (A^{-1})^T = 1$  then $(A^{-1})^T = (A^T)^{-1}$ (recall that a right inverse is also a left inverse).  \n\\end{enumerate}\n\n\\exercisehead{8} $\\left[ \\begin{matrix} \\cos{\\theta} & - \\sin{\\theta} \\\\ \\sin{\\theta} & \\cos{\\theta} \\end{matrix} \\right] \\left[ \\begin{matrix} \\cos{\\theta} & \\sin{\\theta} \\\\ -\\sin{\\theta} & \\cos{\\theta} \\end{matrix} \\right] = \\left[ \\begin{matrix} 1 & 0 \\\\ 0 & 1 \\end{matrix} \\right]$\n\\[\nA_i A_j = \\sum_{k=1}^n a_{ik} a_{jk} = \\sum_{k=1}^n a_{ik} a_{kj}^T = (AA^T)_{ij} = \\delta_{ij}\n\\]\n\n\\exercisehead{9} \\begin{enumerate} \\item If $\\begin{aligned} AA^T & = 1 \\\\ BB^T & = 1 \\end{aligned}$, \\, $(A+B)(A+B)^T = 2 + BA^T + AB^T$ \\item $(AB)(AB)^T = (AB)B^T A^T = 1$ \\item $B$ is given to be orthogonal.\\end{enumerate}\n\n\\exercisehead{10} \n\\begin{enumerate}\n  \\item \\[\n\\left[ \\begin{matrix} 1 & 1 \\\\ 1 & -1 \\end{matrix} \\right]  \\, \\left[ \\begin{matrix} 1 & 1 \\\\ -1 & 1 \\end{matrix} \\right]  \\, \\left[ \\begin{matrix} 1 & -1 \\\\ 1 & 1 \\end{matrix} \\right]  \\, \\left[ \\begin{matrix} 1 & -1 \\\\ 1 & -1 \\end{matrix} \\right]  \\, \\left[ \\begin{matrix} -1 & 1 \\\\ 1 & 1 \\end{matrix} \\right]  \\, \\left[ \\begin{matrix} -1 & 1 \\\\ -1 & -1 \\end{matrix} \\right]  \\, \\left[ \\begin{matrix} -1 & -1 \\\\ 1 & -1 \\end{matrix} \\right]  \\, \\left[ \\begin{matrix} -1 & -1 \\\\ -1 & -1 \\end{matrix} \\right]  \\,\n\\]\n\\item $(X+Y)\\cdot (X+Z) = X^2 + X\\cdot Z + Y \\cdot X + Y \\cdot Z = X^2 $ Lemma 1 is true.  \\\\\nLemma 2 \\quad $(x_i + y_i)(x_i + z_i) = x_i^2 + x_i (z_i + y_i)  + y_i z_i $ \n\\[\n\\begin{matrix}\n & x_i & y_i & z_i & \\, \\\\\n&  1 & 1 & 1 & 4 \\\\\n&  1 & 1 & -1 & 0 \\\\\n&  1 & -1 & -1 & 0 \\\\\n&  1 & -1 & 1 & 0 \\\\\n&  -1 & 1 & 1 & 0 \\\\\n&  -1 & -1 & 1 & 0 \\\\\n&  -1 & 1 & -1 & 0 \\\\\n&  -1 & -1 & -1 & 4\n\\end{matrix}\n\\]\nAssume $A$ is Hadamard.  \\\\\n\\quad Then by Lemma 1, $(A_i + A_j) \\cdot (A_i + A_k) = A_i^2 = n $, \\, $i,j,k$ distinct.  \\[ \\begin{aligned}\n  (A_i + A_j) \\cdot (A_i + A_k) & = A_i^2 + A_i \\cdot A_k + A_j \\cdot A_i + A_j \\cdot A_k = \\sum_{l=1}^n a_{il}^2 + \\sum_{l=1}^n a_{il} a_{kl} + \\sum_{l=1}^n a_{jl} a_{il} + \\sum_{l=1}^n a_{jl} a_{kl} = \\\\\n  & = \\sum_{l=1}^n (a_{il} + a_{jl})(a_{il} + a_{kl})\n\\end{aligned}\n\\]\nBy Lemma 2, $(a_{il} + a{jl})(a_{il} + a_{kl}) = 0 \\text{ or } 4 $ \\\\\n\\quad then $(A_i + A_j) \\cdot (A_i + A_k) = \\sum_{l=1}^n (a_{il} + a_{jl}) (a_{il} + a_{kl}) = 4m$, where $m\\leq n $ \\\\\n$\\Longrightarrow \\boxed{ n = 4m} $\n\\end{enumerate}\n\n%-----------------------------------%-----------------------------------%-----------------------------------\n\\section*{ 3.6 Exercises - Introduction, Motivation for the choice of axioms for a determinant function, A set of axioms for a determinant function, Computation of determinants, }\n%-----------------------------------%-----------------------------------%-----------------------------------\n\n\\exercisehead{1} \\begin{enumerate}\n\\item $\\left| \\begin{matrix} 2 & 1 & 1 \\\\ 1 & 4 & -4 \\\\ 1 & 0 & 2 \\end{matrix} \\right|$ \n\\[\n\\left| \\begin{matrix} 0 & 1 & -3 \\\\ 0 & 4 & -6 \\\\ 1 & 0 & 2 \\end{matrix} \\right| = \\left| \\begin{matrix} 0 & 1 & -3 \\\\ 0 & 0 & -6 \\\\ 1 & 0 & 2 \\end{matrix} \\right| = \\left| \\begin{matrix} 1 & 0 & 2 \\\\ 0 & 1 & -3 \\\\ 0 & 0 & -6 \\end{matrix} \\right| = \\boxed{ 6 } \n\\]\n\\item $ \\left| \\begin{matrix} 3 & 0 & 8 \\\\ 5 & 0 & 7 \\\\ -1 & 4 & 2 \\end{matrix} \\right| = 3(-28) + 8 (20) = 4 ( -3 (7) + 2 (20) ) = \\boxed{ 76 } $\n\\item $\\left| \\begin{matrix} a & 1 & 0 \\\\ 2 & a & 2 \\\\ 0 & 1 & a \\end{matrix} \\right| = a(a^2 - 2) - 1 (2a) = a(a^2 -4) = a(a-2)(a+2)$\n\\end{enumerate}\n\n\\exercisehead{2} Given $det{ \\left[ \\begin{matrix} x & y & z \\\\ 3 & 0 & 2 \\\\ 1 & 1 & 1 \\end{matrix} \\right]} = 1$,  \n\\begin{enumerate}\n\\item $\\left[ \\begin{matrix} 2x & 2y & 2z \\\\ \\frac{3}{2} & 0 & 1 \\\\ 1 & 1 & 1 \\end{matrix} \\right]$ \n\\[\n\\left| \\begin{matrix} 2x & 2y & 2z \\\\ \\frac{3}{2} & 0 & 1 \\\\ 1 & 1 & 1 \\end{matrix} \\right| = 2\\left( \\frac{1}{2} \\right) det{A} = 1 \n\\]\n\\item $\\left[ \\begin{matrix} x & y & z \\\\ 3x+3 & 3y & 3z + 2 \\\\ x + 1 & y + 1 & z + 1 \\end{matrix} \\right]$ \n\\[\n\\left| \\begin{matrix} x & y & z \\\\ 3x + 3 & 3y & 3z + 2 \\\\ x + 1 & y + 1 & z + 1 \\end{matrix} \\right| = \\left| \\begin{matrix} x & y & z \\\\ 3x + 3 & 3y & 3z + 2  \\\\ x & y & z \\end{matrix} \\right| + \\left| \\begin{matrix} x & y & z \\\\ 3x+ 3 & 3y & 3z + 2 \\\\ 1 & 1 & 1 \\end{matrix} \\right| = 0 + \\left| \\begin{matrix} x & y & z \\\\ 3x & 3y & 3z \\\\ 1 & 1 & 1 \\end{matrix} \\right| + \\left| \\begin{matrix} x & y & z \\\\ 3 & 0 & 2 \\\\ 1 & 1 & 1 \\end{matrix} \\right| = \\boxed{ 1 } \n\\]\n\\item $\\left[ \\begin{matrix} x - 1 & y -1 & z -1 \\\\ 4 & 1 & 3 \\\\ 1 & 1 & 1 \\end{matrix} \\right]$ \n\\[\n\\left| \\begin{matrix} x - 1 & y - 1 & z - 1 \\\\ 4 & 1 & 3 \\\\ 1 & 1 & 1 \\end{matrix} \\right| = \\left| \\begin{matrix} x & y & z \\\\ 4 & 1 & 3 \\\\ 1 & 1 & 1 \\end{matrix} \\right| + \\left| \\begin{matrix} -1 & - 1 & -1 \\\\ 4 & 1 & 3 \\\\ 1 & 1 & 1 \\end{matrix} \\right| = \\left| \\begin{matrix} x & y & z \\\\ 3 + 1 & 0 + 1 & 2 + 1 \\\\ 1 & 1 & 1 \\end{matrix} \\right| = \\boxed{ 1 } \n\\]\n\\end{enumerate}\n\n\\exercisehead{3}\n\\begin{enumerate}\n\\item \\[\n  \\begin{gathered}\n\\left| \\begin{matrix} 1 & 1 & 1 \\\\ 0 & b-a & c-a \\\\ 0 & b^2 - a^2 & c^2 - a^2 \\end{matrix} \\right| = \\left| \\begin{matrix} 1 & 1 & 1 \\\\ 0 & b-a & c-a \\\\ 0 & 0 & (c^2 - a^2)-(c-a)(b+a) \\end{matrix} \\right| = (b-a)((c-a)(c+a) - (c-a)(b+a)) = \\\\ \n= \\boxed{ (b-a)(c-a)(c-b)  }\n\\end{gathered}\n\\]\n\\item \\[\n      \\left| \\begin{matrix} 1 & 1 & 1 \\\\ a & b & c \\\\ a^3 & b^3 & c^3 \\end{matrix} \\right|  = \\left| \\begin{matrix} 1 & 1 & 1 \\\\ 0 & b-a & c-a \\\\ 0 & b^3 -a^3 & c^3 -a^3 \\end{matrix} \\right| = \\left| \\begin{matrix} 1 & 0 & 0 \\\\ 0 & (b-a) & c-a \\\\ 0 & (b-a)(b^2 + ba + a^2) & (c-a)(c^2 + ca + a^2) \\end{matrix} \\right| \\\\\n\\]\n\\[\n      \\text{ subtract the second column off the third column modulo a factor }  \\\\\n\\]\n\\[\n\\begin{aligned}\n & \\begin{gathered}\n      \\left( \\begin{matrix} 0 - 0 \\\\ c-a - (c-a) \\\\ (c-a)( c^2 + ca + a^2 - (b^2 + ba +a^2) ) \\end{matrix} \\right)\n\\end{gathered} \\\\\n    & = \\left| \\begin{matrix} 1 & 0 & 0 \\\\ 0 & (b-a) & 0 \\\\ 0 & (b-a)(b^2 +ba +a^2) & (c-a)(c^2 -b^2 +ca - ab) \\end{matrix} \\right|  = \\quad \\left| \\begin{matrix} 1 & 0 & 0 \\\\ 0 & (b-a) & 0 \\\\ 0 & 0 & (c-a)(c-b)(c+b +a) \\end{matrix} \\right| \\\\\n    & = (a+b+c)(c-a)(c-b)(b-a)\n  \\end{aligned}\n  \\]\n\\[\n\\begin{aligned}\n\\left| \\begin{matrix} 1 & 1 & 1 \\\\ a^2 & b^2 & c^2 \\\\ a^3 & b^3 & c^3 \\end{matrix} \\right| & = \\left| \\begin{matrix} 1 & 1 & 1 \\\\ 0 & b^2 -a^2 & c^2 -a^2 \\\\ 0 & b^3 -a^3 & c^3 -a^3 \\end{matrix} \\right| = \\left| \\begin{matrix} 1 & 0 & 0 \\\\ 0 & (b-a)(b+a) & (c-a)(c+a) \\\\ 0 & (b-a)(b^2 +ba +a^2) & (c-a)(c^2 +ca +a^2) \\end{matrix} \\right|  \\\\\n& \\begin{gathered}\n  \\text{ subtract the second column off the third column modulo a factor } \\\\\n  \\left( \\begin{matrix} 0 \\\\ (c-a)(c+a) \\\\ (c-a)(c^2 +ca +a^2) \\end{matrix} \\right) - \\frac{ (c-a)(c+a)}{(b-a)(b+a)} \\left( \\begin{matrix} 0 \\\\ (b-a)(b+a) \\\\ (b-a)(b^2 +ba +a^2) \\end{matrix} \\right) = \\\\ \n  = \\left( \\begin{matrix} 0 \\\\ 0 \\\\ (c-a)(c^2 + ac + a^2 - \\frac{ (c+a)}{(b+a)} (b^2 +ba +a^2) ) \\end{matrix} \\right) = \\left( \\begin{matrix} 0 \\\\ 0 \\\\ \\frac{ (c-a)}{ (b+a)} (c-b)(ac +ab +bc) \\end{matrix} \\right) \n\\end{gathered} \\\\\n& = (b-a)(c-a)(c-b)(ac+ab+bc)\n\\end{aligned}\n\\]\n\\end{enumerate}\n\n\\exercisehead{4}\n\\begin{enumerate}\n\\item \n  \\[\n  \\left| \\begin{matrix} 1 & -1 & 1 & 1 \\\\ 1 & -1 & -1 & -1 \\\\ 1 & 1 & -1 & -1 \\\\ 1 & 1 & 1 & -1 \\end{matrix} \\right| = \\left| \\begin{matrix} 1 & 1 & 1 & 1 \\\\ -1 & -1 & 1 & 1 \\\\ 1 & -1 & -1 & 1 \\\\ 1 & -1 & -1 & -1 \\end{matrix} \\right| = \\left| \\begin{matrix} 1 & 1 & 1 & 1 \\\\ 0 & 0 & 2 & 2 \\\\ 2 & 0 & 0 & 2 \\\\ 2 & 0 & 0 & 0 \\end{matrix} \\right| = \\left| \\begin{matrix} 0 & 1 & 1 & 1 \\\\ 0 & 0 & 2 & 2 \\\\ 0 & 0 & 0 & 2 \\\\ 2 & 0 & 0 & 0 \\end{matrix} \\right| = (-1) 8\n  \\]\n\\item \n  \\[\n  \\begin{aligned}\n    \\left| \\begin{matrix} 1 & 1 & 1 & 1 \\\\ a & b & c & d \\\\ a^2 & b^2 & c^2 & d^2 \\\\ a^3 & b^3 & c^3 & d^3 \\end{matrix} \\right| & = \\left| \\begin{matrix} 1 & 1 & 1 & 1 \\\\ 0 & b-a & c-a & d-a \\\\ 0 & b^2 - a^2 & c^2 - a^2 & d^2 -a^2 \\\\ 0 & b^3 -a^3 & c^3 -a^3 & d^3 - a^3  \\end{matrix} \\right| = \\left| \\begin{matrix} 1 & 0 & 0 & 0 \\\\ 0 & b-a & b^2 -a^2 & b^3 -a^3 \\\\ 0 & c-a & c^2 - a^2 & c^3 -a^2 \\\\ 0 & d-a & d^2 -a^2 & d^3 -a^3 \\end{matrix} \\right|  \\\\\n      & = (b-a)(c-a)(d-a) \\left| \\begin{matrix} 1 & 0 & 0 & 0 \\\\ 0 & 1 & (b+a) & b^2 + ba +a^2 \\\\ 0 & 1 & (c+a) & c^2 + ac + a^2 \\\\ 0 & 1 & (d+a) & d^2 + ad + a^2 \\end{matrix} \\right| = \n\\end{aligned}\n\\]\n\\[\n\\begin{aligned}\n      &  \\text{ (Now I use the addition of column $ \\begin{matrix} 0 \\\\ 1 \\\\ 1 \\\\ 1 \\end{matrix} $, which doesn't change the determinant) } \\\\\n &   \\quad \\\\ \n      & = (b-a)(c-a)(d-a) \\left| \\begin{matrix} 1 & 0 & 0 & 0 \\\\ 0 & 1 & b & (b+a)b \\\\ 0 & 1 & c & (c+a)c \\\\ 0 & 1 & d & (d+a)d \\end{matrix} \\right|  = \\\\\n    & \\quad \\quad = (b-a)(c-a)(d-a) \\left| \\begin{matrix} 1 & 0 & 0 & 0 \\\\ 0 & 1  & 0 & 0 \\\\ 0 & 0 & c-b & (c+a)c - (b+a)b \\\\ 0 & 0 & d- b & (d+a)d - (b+a)b \\end{matrix} \\right| \\\\\n\\end{aligned}\n\\]\n\\[\n\\begin{aligned}\n      & (b-a)(c-a)(d-a) \\left| \\begin{matrix} 1 & 0 & 0 & 0 \\\\ 0 & 1 & 0 & 0 \\\\ 0 & 0 & c-b & c^2 - b^2 \\\\ 0 & 0 & d-b & d^2 - b^2 \\end{matrix} \\right| = \\\\\n    & \\quad \\quad = (b-a)(c-a)(d-a)(c-b)(d-b)\\left| \\begin{matrix} 1 & 0 & 0 & 0 \\\\ 0 & 1 & 0 & 0 \\\\ 0 & 0 & 1 & c+b \\\\ 0 & 0 & 1 & d+b \\end{matrix} \\right| = \\\\\n    & \\boxed{ (b-a)(c-a)(d-a)(c-b)(d-b) (d-c) }\n  \\end{aligned} \\]\n\\item \n\\item \\[\n  \\begin{aligned}\n\\left| \\begin{matrix} a & 1 & 0 & 0 & 0 \\\\ 4 & a & 2 & 0 & 0 \\\\ 0 & 3 & a & 3 & 0 \\\\ 0 & 0 & 2 & a & 4 \\\\ 0 & 0 & 0 & 1 & a \\end{matrix} \\right| & = \\left| \\begin{matrix} a & 1 & & & \\\\ & a-\\frac{4}{a} & 2 & & \\\\ & 3 & a & 3 & \\\\ & & 2 & a & 4 \\\\ & & & 1 & a \\end{matrix} \\right| = \\left|  \\begin{matrix} a & 0 & & & \\\\ & a-\\frac{4}{a} & 2 & & \\\\ & 3 & a & 3 & \\\\ & & 2 & a - \\frac{4}{a} & 4 \\\\ & & & 0  & a \\end{matrix} \\right|  \\\\\n& = \\left|  \\begin{matrix} a &  & & & \\\\ & a-\\frac{4}{a} &  & & \\\\ & 0 & a-\\frac{12}{a-\\frac{4}{a}} & 0 & \\\\ & & 0 & a-\\frac{4}{a} & 0 \\\\ & & & 0 & a \\end{matrix} \\right| = \\\\ \n& = a^2 (a-\\frac{4}{a})^2 \\left( a - \\frac{12}{a-\\frac{4}{a}} \\right) = a^2 (a-\\frac{4}{a})(a^2 -4 - 12 )  \\\\\n& = a(a^2 - 4)(a^2 -16)\n  \\end{aligned}\n\\]\n\\item \\[\n  \\begin{aligned}\n    \\left| \\begin{matrix} 1 & 1 & 1 & 1 & 1 & 1 \\\\ 1 & 1 & 1 & -1 & -1 & -1 \\\\ 1 & 1 & -1 & -1 & 1 & 1 \\\\ 1 & -1 & -1 & 1 & -1 & 1 \\\\ 1 & -1 & 1 & -1 & 1 & 1 \\\\ 1 & -1 & -1 & 1 & 1 & -1 \\end{matrix} \\right|  & = \\left| \\begin{matrix} 1 & & & & & \\\\ 0 & 0 & 0 & -2 & -2 & -2 \\\\ & & -2 & -2 & & \\\\ & -2 & -2 & & -2 & \\\\ & -2 & & -2 & & \\\\ & -2 & -2 & & & -2 \\end{matrix} \\right| = \\left| \\begin{matrix} 1 & & & & & \\\\ & 2 & 2 & -2 & -2 & 0 \\\\ & & -2 & -2 & & \\\\ & -2 & -2 & & -2 &  \\\\ & -2 & & -2 & & \\\\ & 0 & 0 & & & -2 \\end{matrix} \\right|  \\\\\n    & = \\left| \\begin{matrix} 1 & & & & & \\\\ & 2 & & & & \\\\ & & -2 & -2 & & \\\\ & & & -2 & -4 &  \\\\ & & 0 & -6 & -2 & \\\\ 0 & & 0 &  & & -2 \\end{matrix} \\right| = (1)(2)(-2)(-2)(10)(-2) = -160\n  \\end{aligned}\n  \\] \n\\end{enumerate}\n\n\\exercisehead{5}  Consider $A = (a_{ij})$ s.t. $a_{ij} = 0$ whenever $i<j$.   \\\\\nSuppose $a_{11} = 0$.  Then $a_{1j} = 0$, $\\forall \\, j \\leq n$, since a row of $A$ is entirely zero, by homogeneity property of determinants, $det{A} =0$.   \\\\\nSuppose $a_{ii} =0$ for some $1 < i \\leq n$.  \\\\\n\\quad \\, then $i$ rows have $n-(i-1)$ components equal to zero.  Therefore, these $i$ rows can span a psace of at most $i-1$ dimensions.  \\\\\n\\quad \\quad \\, then the $i$ rows are dependent.  Then $det{A} =0 $ by Thm. (the determinant vanishes if its rows are dependent).   \\\\\n\\quad Then assume $a_{ii}$ nonzero $\\forall \\, i \\leq n$ \\\\\n\nLet $A_n = B_n + C_n$, where $B_n = \\left[ \\begin{matrix} 0 & 0 & \\dots & 0 & a_{nn} \\end{matrix} \\right]$ and $C_n = \\left[ \\begin{matrix} a_{n1} & a_{n2} & \\dots & a_{n, \\, n-1} & 0 \\end{matrix} \\right]$ \n\\[\n\\begin{aligned}\n  det{(A)} & = det{ (A_1, A_2, \\dots, A_n) } = det{ ( A_1, \\, A_2, \\dots, B_n + C_n) } = det{(A_1, A_2, \\dots, B_n)} + det{ (A_1, A_2, \\dots, C_n) } = \\\\\n  & = det{( A_1, A_2, \\dots , B_n ) }\n\\end{aligned}\n\\]\nAlso, $A_{n-1} = B_{n-1} + C_{n-1}$, where $B_{n-1} = \\left[ \\begin{matrix} 0 & 0 & \\dots & a_{n-1,n-1} & 0 \\end{matrix} \\right]$ and $C_{n-1} = \\left[ \\begin{matrix} a_{n-1,1} & a_{n-1,2} & \\dots & a_{n-1, \\, n-2} & 0 & 0 \\end{matrix} \\right]$ \n\\[\n\\begin{aligned}\n  det{(A)} & = det{ (A_1, A_2, \\dots, A_{n-1}, B_n ) } = det{ ( A_1, \\, A_2, \\dots, B_{n-1} + C_{n-1}, B_n) } = \\\\ \n  & = det{(A_1, A_2, \\dots, B_{n-1}, B_n)} + det{ (A_1, A_2, \\dots, C_{n-1}, B_n) } = \\\\\n  & = det{( A_1, A_2, \\dots , B_{n-1}, B_n ) }\n\\end{aligned}\n\\]\nThen $det{A} = det{ (B_1, B_2, \\dots, B_n) }$.  \\\\\nBy homogeneity of determinants, $det{A} = \\prod{i=1}^n a_{ii} det{I} = \\prod_{i=1}^n a_{ii}$\n\n\\exercisehead{6} \\[\n\\begin{aligned}\n  F & = f_1 g_2 - f_2 g_1 \\\\\n  F' & = f_1' g_2 + f_1 g_2' - f_2' g_1 - f_2 g_1' = f_1' g_2 - f_2' g_1 + f_1 g_2' - f_2 g_1' = \\\\\n  & = \\left| \\begin{matrix} f_1' & f_2' \\\\ g_1 & g_2 \\end{matrix} \\right| + \\left| \\begin{matrix} f_1 & f_2 \\\\ g_1' & g_2' \\end{matrix} \\right|\n\\end{aligned}\n\\]\n\n\\exercisehead{7} \n\\[\n\\begin{aligned}\n  F & = f_1 \\left| \\begin{matrix} g_2 & g_3 \\\\ h_2 & h_3 \\end{matrix} \\right| - f_2 \\left| \\begin{matrix} g_1 & g_3 \\\\ h_1 & h_3 \\end{matrix} \\right| + f_3 \\left| \\begin{matrix} g_1 & g_2 \\\\ h_1 & h_2 \\end{matrix} \\right| \\\\\n  F' &  = \\left| \\begin{matrix} f_1' & f_2' & f_3' \\\\ g_1 & g_2 & g_3 \\\\ h_1 & h_2 & h_3 \\end{matrix} \\right| + f_1 \\left( \\left| \\begin{matrix} g_2' & g_3' \\\\ h_2 & h_3 \\end{matrix} \\right| + \\left| \\begin{matrix} g_2 & g_3 \\\\ h_2' & h_3' \\end{matrix} \\right| \\right) - f_2 \\left( \\left| \\begin{matrix} g_1' & g_3' \\\\ h_1 & h_3 \\end{matrix} \\right| + \\left| \\begin{matrix} g_1 & g_3 \\\\ h_1' & h_3' \\end{matrix} \\right| \\right) + f_3 \\left( \\left| \\begin{matrix} g_1' & g_2' \\\\ h_1 & h_2 \\end{matrix} \\right| + \\left| \\begin{matrix} g_1 & g_2 \\\\ h_1' & h_2' \\end{matrix} \\right| \\right) = \\\\\n  & = \\left| \\begin{matrix} f_1' & f_2' & f_3' \\\\ g_1 & g_2 & g_3 \\\\ h_1 & h_2 & h_3 \\end{matrix} \\right| + \\left| \\begin{matrix} f_1 & f_2 & f_3 \\\\ g_1' & g_2' & g_3' \\\\ h_1 & h_2 & h_3 \\end{matrix} \\right| + \\left| \\begin{matrix} f_1 & f_2 & f_3  \\\\ g_1 & g_2 & g_3 \\\\ h_1' & h_2' & h_3' \\end{matrix} \\right|\n\\end{aligned}\n\\]\n\n\\exercisehead{8} Using the previous results:\n\\begin{enumerate}\n\\item \\[\nF' = \\left| \\begin{matrix} f_1' & f_2' \\\\ f_1' & f_2' \\end{matrix} \\right| + \\left| \\begin{matrix} f_1 & g_1 \\\\ f_2'' & g_2'' \\end{matrix} \\right| = \\boxed{ \\left| \\begin{matrix} f_1 & g_1 \\\\ f_2'' & g_2'' \\end{matrix} \\right| }\n\\]\n\\item\n\\[\n\\begin{aligned}\n  F = \\left| \\begin{matrix} f_1 & f_2 & f_3 \\\\ f_1' & f_2' & f_3' \\\\ f_1'' & f_2'' & f_3'' \\end{matrix} \\right| ] \\Longrightarrow  \\left| \\begin{matrix} f_1 & f_2 & f_3 \\\\ f_1' & f_2' & f_3' \\\\ f_1'' & f_2'' & f_3'' \\end{matrix} \\right|\n\\end{aligned}\n\\]\n\\end{enumerate}\n\n\n\\exercisehead{9}\n\\begin{enumerate}\n\\item \\[ \n  \\begin{aligned}\n    & ( U +V)_{ij} = u_{ij} + v_{ij} = \\begin{cases} u_{ij} & \\text{ if $i < j$ }  \\\\ 0 & \\text{ otherwise } \\end{cases} +  \\begin{cases} v_{ij} & \\text{ if $i < j$ }  \\\\ 0 & \\text{ otherwise } \\end{cases} =  \\begin{cases} u_{ij} +v_{ij} & \\text{ if $i < j$ }  \\\\ 0 & \\text{ otherwise } \\end{cases}  \\\\\n    & (UV)_{ij} = \\sum_{k=1}^n u_{ik} v_{kj} \\sum_{i<k} u_{ik} v_{kj} = \\sum_{i<k, k<j} u_{ik} v_{kj} = \\begin{cases} \\sum_{i<k, k<j} u_{ik} v_{kj} & \\text{ if $ i \\leq j$ } \\\\ 0 & \\text{ otherwise } \\end{cases}\n  \\end{aligned} \\]\n\\item \\[ det(UV) = \\prod_{i=1}^n \\left( \\sum_{i<k, k<j}^n u_{ik} v_{ki} \\right) = \\prod_{i=1}^n u_{ii}v_{ii} = \\left( \\prod_{i=1}^n u_{ii} \\right)\\left( \\prod_{i=1}^n v_{ii} \\right) = det U det V \\]\n\\item Suppose $U U^{-1} = 1$.  \n\\[x\ndet 1 = 1 = (det U)(det U^{-1}), \\text{ $U$ and $1$ are 2 $n \\times n$ triangular matrices }\n\\]\n$U^{-1}$ exists since $det U \\neq 0$.  \n\\[\ndet U^{-1} = 1/ det U\n\\]\n\\end{enumerate}\n\n\\exercisehead{10}\nUse the cofactor matrix to get the inverse, that $\\frac{ (cof A)^T }{det A} = A^{-1}$.  \n\\[\n\\begin{gathered}\ndet A = 16, \\quad det A^{-1} = \\frac{1}{16} \\\\\n\\left( \\begin{matrix} \\frac{1}{2} & \\frac{-3}{4} & \\frac{1}{8} & \\frac{1}{16} \\\\ 0 & \\frac{1}{2} & \\frac{-3}{4} & \\frac{1}{8} \\\\ 0 & 0 & \\frac{1}{2} & \\frac{-3}{4} \\\\ 0 & 0 & 0 & \\frac{1}{2} \\end{matrix} \\right) \\left( \\begin{matrix} 2 & 3 & 4 & 5 \\\\ 0 & 2 & 3 & 4 \\\\ 0 & 0 & 2 & 3 \\\\ 0 & 0 & 0 & 2 \\end{matrix} \\right)\n\\end{gathered}\n\\]\n\n%-----------------------------------%-----------------------------------%-----------------------------------\n\\section*{ 3.11 Exercises - The product formula for determinants, The determinant of the inverse of a nonsingular matrix, Determinants and independence of vectors, The determinant of a block-diagonal matrix }\n%-----------------------------------%-----------------------------------%-----------------------------------\n\n\\exercisehead{1}\n\\begin{enumerate}\n\\item If $A = \\left[ \\begin{matrix} 1 & 3 \\\\ 2 & 5 \\end{matrix} \\right]$; $B = \\left[ \\begin{matrix} -4 & 2 \\\\ 3 & 6 \\end{matrix} \\right]$; $A+B = \\left[ \\begin{matrix} -3 & 5 \\\\ 5 & 11 \\end{matrix} \\right]$  $\\begin{aligned} det{A} & = -1 \\\\ det{B} & = -30 \\end{aligned}$  $det{(A+B)} = -58$\n\\item $det{(A+B)^2} = det{(A+B)(A+B)} = det{(A+B)} det{(A+B)} = (det{(A+B)})^2$\n\\item If $A =\\left[ \\begin{matrix} 1 & 1 \\\\ -1 & 1 \\end{matrix} \\right]$; $B = \\left[ \\begin{matrix} -1 & 2 \\\\ 1 & -1 \\end{matrix} \\right]$, $A+B = \\left[ \\begin{matrix} 0 & 3 \\\\ 0 & 0 \\end{matrix} \\right]$  \n\\[\n\\begin{gathered}\n  \\begin{aligned}\n    A^2 & = \\left[ \\begin{matrix} 1 & 1 \\\\ -1 & 1 \\end{matrix} \\right]\\left[ \\begin{matrix} 1 & 1 \\\\ -1 & 1 \\end{matrix} \\right] = \\left[ \\begin{matrix} 0 & 2 \\\\ -2 & 0 \\end{matrix} \\right] \\\\\n    B^2 & = \\left[ \\begin{matrix} -1 & 2 \\\\ 1 & -2 \\end{matrix} \\right]  \\left[ \\begin{matrix} -1 & 2 \\\\ 1 & -2 \\end{matrix} \\right] = \\left[ \\begin{matrix} 3 & -4 \\\\ -2 & 3 \\end{matrix} \\right]\n\\end{aligned} \\quad \\quad \\, A^2 + 2AB + B^2 = \\left[ \\begin{matrix} 0 & 2 \\\\ -2 & 0 \\end{matrix} \\right] + 2 \\left[ \\begin{matrix} 0 & 1 \\\\ 2 & -3 \\end{matrix} \\right] + \\left[ \\begin{matrix} 3 & -4 \\\\ -2 & 3 \\end{matrix} \\right] = \\left[ \\begin{matrix} 0 & 2 \\\\ -2 & 0 \\end{matrix} \\right] + \\left[ \\begin{matrix} 0 & 2 \\\\ 4 & -6 \\end{matrix} \\right] + \\left[ \\begin{matrix} 3 & -4 \\\\ -2 & 3 \\end{matrix} \\right] = \\left[ \\begin{matrix} 3 & 0 \\\\ 0 & -3 \\end{matrix} \\right] \\\\\n\\Longrightarrow det{(A^2 + 2AB + B^2)} = -9\n\\end{gathered}\n\\]\n\\item likewise, $det{(A^2 + B^2)} = det{ \\left[ \\begin{matrix} 3 & -2 \\\\ -4 & 3 \\end{matrix} \\right]} = 1$\n\\end{enumerate}\n\n\\exercisehead{2} \\begin{enumerate}\n\\item Assume $A$ is $n\\times n$, $B$ is $m\\times m$, and $C$ is $p \\times p$.  \\\\\n$\\left[ \\begin{matrix} A & 0 \\\\ 0 & B \\end{matrix} \\right]$ is a $n+m \\times n+m$ matrix, $D$.  \\smallskip \\\\\n\\quad $\\left[ \\begin{matrix} A & & \\\\ & B & \\\\ & & C \\end{matrix} \\right] = \\left[ \\begin{matrix} D & \\\\ & C \\end{matrix} \\right]$.  Then by Thm. 3.7, $det{\\left[ \\begin{matrix} D & 0 \\\\ 0 & C \\end{matrix} \\right]}  = det{D} det{C}$ \\smallskip \\\\\n$det{D} = det{ \\left[ \\begin{matrix} A & 0 \\\\ 0 & B \\end{matrix} \\right]} = det{A} det{B} $ \\, (by Thm. 3.7).  Then $det{ \\left[ \\begin{matrix} A & & \\\\ & B & \\\\ & & C \\end{matrix} \\right]} = det{A} det{B} det{C}$\n\\item Assume $det{\\left[ \\begin{matrix} A_1 & & & \\\\ & A_2 & & \\\\ & & \\ddots & \\\\ & & & A_n \\end{matrix} \\right]} = \\prod_{i=1}^n det{A_i}$.  \\smallskip \\\\\n\nConsider $det{ \\left[ \\begin{matrix} A_1 & & & \\\\ & A_2 & & \\\\ & & \\ddots & \\\\ & & & A_{n+1} \\end{matrix} \\right]}$ \\\\\nNow $\\left[ \\begin{matrix} A_1 & & & \\\\ & A_2 & & \\\\ & & \\ddots & \\\\ & & & A_n \\end{matrix} \\right] = D_n$, a square matrix of size $\\sum_{i=1}^n N_i \\times \\sum_{i=1}^n N_i$ where $N_i = $ size of matrix $A_i$.  \\\\\n$det{\\left[ \\begin{matrix} D_n & \\\\ & A_{n+1} \\end{matrix} \\right]} = det{D_n}det{A_{n+1}}$ by Thm. 3.7.  $det{D_n}$, by induction assumption, is $det{D_n} = \\prod_{i=1}^n det{A_i}$.  $\\Longrightarrow det{ \\left[ \\begin{matrix} A_1 & & & \\\\ & A_2 && \\\\ & & \\ddots & \\\\ & & & A_{n+1} \\end{matrix} \\right]} = \\prod_{i=1}^{n+1} det{A_i}$\n\\end{enumerate}\n\n\\exercisehead{3} \\[\n\\begin{aligned}\n  & det{A} = det{ \\left[ \\begin{matrix} 1 & & & \\\\ & 1 & &  \\\\ a & b & c & d \\\\ e & f & g & h \\end{matrix} \\right]} = det{ \\left[ \\begin{matrix} 1 & & & \\\\ & 1 & & \\\\ & & c & d \\\\ & & g & h \\end{matrix} \\right]} =det{\\left[ \\begin{matrix} c & d \\\\ g & h \\end{matrix}\\right]} \\\\\n  & det{B} = det{ \\left[ \\begin{matrix} a & b & c & d \\\\ e & f & g & h \\\\ 0 & 0 & 1 & 0 \\\\ 0 & 0 & 0 & 1 \\end{matrix} \\right]} = \\left| \\begin{matrix} a & b & & \\\\ e & f & & \\\\ 0 & 0 & 1 & 0 \\\\ 0 & 0 & 0 & 1 \\end{matrix} \\right| = det{ \\left[ \\begin{matrix} a & b \\\\ e & f \\end{matrix} \\right]}\n\\end{aligned}\n\\]\n\n\\exercisehead{4} If $X = \\left[ \\begin{matrix} & A & \\\\ & & I_m \\end{matrix} \\right]$ where $A$ is $(n-m) \\times n$ and $I$ is $m \\times m$, then $\\forall \\, a_{ij}$ entry, $(n-m) + 1 \\leq i \\leq n$, $(n-m) + 1 \\leq j \\leq n$.  \n\n$[0 \\, 0 \\, \\ldots \\, 0, \\, -a_{ij}, \\, 0, \\dots \\, 0 ]$ could be added to the $i$th row since Gauss-Jordan row operations do not change the determinant, by determinant properties.  Then $det{X} = \\left[ \\begin{matrix} A_{n-m} & \\\\ & I_m \\end{matrix} \\right]$.  By Thm. 3.7, $det{X} = det{A_{n-m}}$.  \\\\\n\nSimilarly for $Y = \\left[ \\begin{matrix} I_m & \\\\ & A \\end{matrix} \\right]$.\n\n\\exercisehead{5} $ A = \\left[ \\begin{matrix} a & b & 0 & 0 \\\\ c & d & 0 & 0 \\\\ e & f & g & h \\\\ x & y & z & w \\end{matrix} \\right]$  \\quad \\, $det{A} = det{ \\left[ \\begin{matrix} a & b \\\\ c & d \\end{matrix} \\right]}det{\\left[ \\begin{matrix} g & h \\\\ z & w \\end{matrix} \\right]}$\n\n\\exercisehead{6} $A = \\left[ \\begin{matrix} B & 0 \\\\ C & D \\end{matrix} \\right]$ where $B$ is $m\\times m$, $C,D$ are $(n-m)\\times (n-m)$.  \n\\[\n\\begin{gathered}\n  det{A} = f(A_1, A_2, \\dots, A_n), \\quad \\, A_i = C_i + D_i, \\quad m+1 \\leq i \\leq n \\\\\n  det{A} = f(A_1, A_2, \\dots, A_n) = f(A_1, A_2, \\dots, C_{m+1} + D_{m+1}, \\dots, A_n) = \\\\\n  = f(A_1, A_2, \\dots, C_{m+1}, \\dots, A_n) + f(A_1, A_2, \\dots, D_{m+1}, \\dots , A_n)\n\\end{gathered}\n\\]\nConsider $A_1, A_2, \\dots, C_{m+1}$, $m+1$ rows with $m$ possibly nonzero components.  Then $A_1, \\dots, C_{m+1}$ span at most a $dim{m}$ subspace.  Then $A_1, \\dots, C_{m+1}$ dependent.  By Thm., $f(A_1, A_2, \\dots, C_{m+1}, \\dots, A_n) =0$\n\\[\ndet{A} = f(A_1, A_2, \\dots, D_{m+1}, \\dots, A_n)\n\\]\nLikewise for $i = m +2, \\dots, n$\n\\[\n\\Longrightarrow det{A} = f(A_1, A_2, \\dots, D_{m+1}, \\dots , D_n) = det{B}det{D}\n\\]\n(By Thm. for det of block-diagonal matrices)\n\n\\exercisehead{7} \\begin{enumerate}\n\\item $\\left| \\begin{matrix} 1 & -1 & 0 \\\\ 0 & 1 & -1 \\\\ 2 & 3 & -1 \\end{matrix} \\right| = \\left| \\begin{matrix} 1 & -1 & 0 \\\\ 0 & 1 & -1 \\\\ 0 & 5 & -1 \\end{matrix} \\right| = \\left| \\begin{matrix} 1 & -1 & 0 \\\\ 0 & 1 & -1 \\\\ 0 & 0 & 4 \\end{matrix} \\right| =4 $\n\\item $\\left| \\begin{matrix} 1 & -1 & 2 & 1 \\\\ -1 & 2 & -1 & 0 \\\\ 3 & -1 & 1 & 0 \\\\ 1 & 0 & 0 & 1 \\end{matrix} \\right| = \\left| \\begin{matrix} 0 & -1 & 2 & 0 \\\\ 0 & 2 & -1 & 1 \\\\ 0 & -1 & 1 & -3 \\\\ 1 & 0 & 0 & 1 \\end{matrix} \\right| = \\left| \\begin{matrix} 0 & -1 & 2 & 0 \\\\ 0 & 0 & 3 & 1 \\\\ 0 & 0 & -1 & -3 \\\\ 1 & 0 & 0 & 1 \\end{matrix} \\right| = \\left| \\begin{matrix} 0 & -1 & 2 & 0 \\\\ 0 & 0 & 0 & -8 \\\\ 0 & 0 & -1 & -3 \\\\ 1 & 0 & 0 & 1 \\end{matrix} \\right| = \\left| \\begin{matrix} 1 & 0 & 0 & 1 \\\\ 0 & -1 & 0 & 0 \\\\ 0 & 0 & -1 & -3 \\\\ 0 & 0 & 0 & -8 \\end{matrix} \\right| = -8$\n\\item $\\left| \\begin{matrix} 1 & 0 & 0 & 0 1 \\\\ 1 & 1 & 0 & 0 & 0 \\\\ 1 & 0 & 1 & 0 & 1 \\\\ 1 & 1 & 0 & 1 & 1 \\\\ 0 & 1 & 0 & 1 & 0 \\end{matrix} \\right| = \\left| \\begin{matrix} 0 & 0 & 0 & 0 & 1 \\\\ 1 & 0 & 0 & 0 & 0 \\\\ 0 & 0 & 1 & 0 & 1 \\\\ 0 & 0 & 0 & 0 & 1 \\\\ 0 & 1 & 0 & 1 & 0 \\end{matrix} \\right| = \\left| \\begin{matrix} 0 & 0 & 0 & 0 & 1 \\\\ 1 & 0 & 0 & 0 & 0 \\\\ 0 & 0 & 1 & 0 & 0 \\\\ 0 & 0 & 0 & 0 & 0 \\\\ 0 & 1 & 0 & 1 & 0 \\end{matrix} \\right| = 0 $\n\\end{enumerate}\n\n%-----------------------------------%-----------------------------------%-----------------------------------\n\\section*{ 3.17 Exercises - Expansion formulas for determinants.  Minors and cofactors.  3.13 Existence of the determinant function, The determinant of a transpose, The cofactor matrix, Cramer's rule }\n%-----------------------------------%-----------------------------------%-----------------------------------\n\n\\exercisehead{1} \\begin{enumerate}\n\\item $\\left[ \\begin{matrix} 1 & 2 \\\\ 3 & 4 \\end{matrix} \\right]$ \\quad \\quad \\, $cof{A} = \\left[ \\begin{matrix} 4 & -3 \\\\ -2 & 1 \\end{matrix} \\right]$\n\\item $\\left[ \\begin{matrix} 2 & -1 & 3 \\\\ 0 & 1 & 1 \\\\ -1 & -2 & 0 \\end{matrix} \\right]$  \\quad \\quad \\, $cof{A} =  \\left[ \\begin{matrix} 2 & -1 & 1 \\\\ -6 & 3 & 5 \\\\ -4 & -2 & 2 \\end{matrix} \\right]$\n\\item $\\left[ \\begin{matrix} 3 & 1 & 2 & 4 \\\\ 2 & 0 & 5 & 1 \\\\ 1 & -1 & -2 & 6 \\\\ -2 & 3 & 2 & 3 \\end{matrix} \\right]$ \\quad \\quad \\, $cof{A} = \\left[ \\begin{matrix} 109 & 113 & -41 & -13 \\\\ -40 & -92 & 74 & 16 \\\\ -41 & -79 & 7 & -47 \\\\ -50 & 38 & 16 & 20 \\end{matrix} \\right]$\n\\end{enumerate}\n\n\\exercisehead{2} \\begin{enumerate}\n\\item $\\frac{1}{-2} \\left[ \\begin{matrix} 4 & -3 \\\\ -2 & 1 \\end{matrix} \\right]$ \n\\item $\\frac{1}{8} \\left[ \\begin{matrix} 2 & -6 & -4 \\\\ -1 & 3 & -2 \\\\ 1 & 5 & 2 \\end{matrix} \\right]$\n\\item $\\frac{1}{184} \\left[ \\begin{matrix} 109 & -40 & -41 & -50 \\\\ 113 & -92 & 79 & 38 \\\\ -41 & 74 & 7 & 16 \\\\ -13 & 16 & -47 & 20 \\end{matrix} \\right]$\n\\end{enumerate}\n\n\\exercisehead{3} Note that for $\\lambda I - A$, $det{(\\lambda I - A) } = 0 = det{(A - \\lambda I)}$ \\begin{enumerate}\n\\item \\[\n\\left| \\begin{matrix} - \\lambda & 3 \\\\ 2 & -1 - \\lambda \\end{matrix} \\right| = 0 \\Longrightarrow \\lambda + \\lambda^2 - 6 = 0 = (\\lambda + 3)(\\lambda - 2) = 0\n\\]\n\\item \\[\n\\begin{gathered}\n  \\left[ \\begin{matrix} 1 & 0 & 2 \\\\ 0 & -1 & -2 \\\\ 2 & -2 & 0 \\end{matrix} \\right]  \\\\\n  \\begin{aligned}\n  \\left| \\begin{matrix} 1 - \\lambda & & 2 \\\\ & -1 -\\lambda & -2 \\\\ 2 & -2 & -\\lambda \\end{matrix} \\right| & = (1-\\lambda) (\\lambda ( 1 + \\lambda ) -4 ) + 2 ( 2 (1+ \\lambda ) ) = \\\\\n  & = (1 - \\lambda ) ( \\lambda^2 + \\lambda - 4) + 4 (1 + \\lambda ) = (1- \\lambda) ( \\lambda^2 + \\lambda - 4) + 4 (1+ \\lambda ) = \\\\\n  & = -\\lambda^3 + 9 \\lambda = \\lambda ( -\\lambda^2 + 9) \\Longrightarrow \\boxed{ \\lambda = \\pm 3, 0 }\n\\end{aligned}\n\\end{gathered}\n\\]\n\\item \\[\n\\begin{gathered}\n\\left| \\begin{matrix} 11 - \\lambda & -2 & 8 \\\\ 19 & -3-\\lambda & 14 \\\\ -8 & 2 & -5 - \\lambda \\end{matrix} \\right| = \\left| \\begin{matrix} 3 - \\lambda & 0 & 3 - \\lambda \\\\ 19 & -3 -\\lambda & 14 \\\\ -8 & 2 & -5 - \\lambda \\end{matrix} \\right| = \\left| \\begin{matrix} 0 & 0 & 3 - \\lambda \\\\ 5 & -3 - \\lambda & 14 \\\\ \\lambda - 3 & 2 & -5 - \\lambda \\end{matrix} \\right| \\\\ \n= (3- \\lambda ) (10 + \\lambda^2 - 9 ) = (3-\\lambda ) (1 + \\lambda^2) \\\\\n\\boxed{ \\lambda = 3 , \\pm i }\n\\end{gathered}\n\\]\n\\end{enumerate}\n\n\\exercisehead{4} \n\\begin{enumerate}\n\\item $((cof{A})^T)_{ij} = (cof{A})_{ji} = (-1)^{i+j} det{A_{ji}} = (-1)^{i+j}det{(A_{ji})^T} = (-1)^{i+j} det{(A^T)_{ij}} = cof{(A^T)_{ij}}$\n\\item See Part (c), and then use $A(cof{A})^T = (det{A})I$, Thm. 3.12.  \n\\item $((cof{A})^T A)_{ij} = \\sum_k (cof{A})^T_{ik} a_{kj} = \\sum_k a_{kj} (cof{A})_{ki}$ \\smallskip \\\\\nRecall that column expansions can be done on determinants, and that $det{A} = det{A^T}$.  \\\\\n\nConsider $B$ matrix whose $j$th column is equal to the $i$th column for some $j\\neq i$, \\\\\n\\quad but remaining rows are the same as $A$.  \\\\\n\\quad \\, then $det{B} =0$ \n\\[\n\\begin{gathered}\n\\begin{aligned}\n  det{B} & = \\sum_{k}^n b_{kj} cof{b_{kj}} \\quad \\, \\text{ ($j$th column expansion of $B$) } \\\\\n  b_{kj} & = a_{ij} \\\\ \n  cof{b_{kj}} & = cof{a_{kj}} \\quad \\, \\text{ (since $B$ differs from $A$ only in the $j$th column) }\n\\end{aligned} \\\\\n\\Longrightarrow \\sum_k^n a_{ij} cof{a_{kj}} = 0 \n\\end{gathered}\n\\]\nIf $i=j$, $\\sum_k a_{ki} (cof{A})_{ki} = det{A}$ (by $i$th column expansion of $det{A}$)\n\\end{enumerate}\n\n\\exercisehead{5}\\begin{enumerate}\n\\item $\\begin{aligned}\n  x + 2y + 3z & = 8 \\\\\n  2x -y + 4z & = 7 \\\\\n  -y + z & = 1 \n\\end{aligned}$ $\\Longrightarrow \\left[ \\begin{matrix} 1 & 2 & 3 \\\\ 2 & -1 & 4 \\\\ & -1 & 1 \\end{matrix} \\right]\\left[ \\begin{matrix} x \\\\ y \\\\ z \\end{matrix} \\right] = \\left[ \\begin{matrix} 8 \\\\ 7 \\\\ 1 \\end{matrix} \\right]$ \n\\[\n\\begin{aligned}\nx & =\\frac{1}{-7} \\left| \\begin{matrix} 8 & 2 & 3 \\\\ 7 & -1 & 4 \\\\ 1 & -1 & 1 \\end{matrix} \\right| = \\frac{1}{-7} \\left| \\begin{matrix} 0 & 10 & -5 \\\\ 0 & 6 & -3  \\\\ 1 & -1 & 1 \\end{matrix} \\right| = \\frac{1}{-7} \\left| \\begin{matrix} 1 & -1 & 1 \\\\ 0 & 10 & -5 \\\\ 0 & 6 & -3 \\end{matrix} \\right| = 0 \\\\\ny & = \\frac{1}{-7} \\left| \\begin{matrix} 1 & 8 & 3 \\\\ 2 & 7 & 4 \\\\ & 1 & 1 \\end{matrix} \\right| = \\frac{1}{-7} \\left| \\begin{matrix} 1 & 0 & -5 \\\\ 2 & 0 & -3 \\\\ & 1 & 0 \\end{matrix} \\right| = -7 /-7 = 1 \\\\\nz & = \\frac{1}{-7} \\left| \\begin{matrix} 1 & 2 & 8 \\\\ 2 & -1 & 7 \\\\ & -1 & 1 \\end{matrix} \\right| = \\frac{-1}{7} \\left| \\begin{matrix} 1 & 0 & 10 \\\\ 0 & -1 & -13 \\\\ & - 1 & 1 \\end{matrix} \\right| = \\frac{-14}{-7} = 2 \n\\end{aligned}\n\\]\n\\item $\\begin{aligned}\n  x + y + 2z & = 0 \\\\\n  3x - y -z & = 3 \\\\\n  2x + 5y + 3z & =4 \n\\end{aligned}$ $\\Longrightarrow \\left[ \\begin{matrix} 1 & 1 & 2 \\\\ 3 & -1 & -1 \\\\ 2 & 5  & 3 \\end{matrix} \\right]\\left[ \\begin{matrix} x \\\\ y \\\\ z \\end{matrix} \\right] = \\left[ \\begin{matrix} 0 \\\\ 3 \\\\ 4 \\end{matrix} \\right]$ \n\\[\n\\begin{gathered}\n  \\left| \\begin{matrix} 1 & 1 & 2 \\\\ 3 & -1 & -1 \\\\ 2 & 5 & 3 \\end{matrix} \\right| = \\left| \\begin{matrix} 1 & 1 & 2 \\\\ 0 & -4 & -7 \\\\ 0 & 3 & -1 \\end{matrix} \\right| = 25 \\\\\n  \\begin{aligned}\n    & \\left| \\begin{matrix} 0 & 1 & 2 \\\\ 3 & -1 & -1 \\\\ 4 & 5 & 3 \\end{matrix} \\right| = \\left| \\begin{matrix} 0 & 1 & 2 \\\\ 3 & 0 & 1 \\\\ 4 & 0 & -7 \\end{matrix} \\right| = -(-21 -4) = 25 & \\Longrightarrow \\boxed{ x = 1 } \\\\ \n    & \\left| \\begin{matrix} 1 & 0 & 2 \\\\ 3 & 3 & -1 \\\\ 2 & 4 & 3 \\end{matrix} \\right| = \\left| \\begin{matrix} 1 & 0 & 2 \\\\ 0 & 3 & -7 \\\\ 0 & 4 & -1 \\end{matrix} \\right| = 25 & \\Longrightarrow \\boxed{ y = 1 }\n\\end{aligned} \\\\\n  \\boxed{ z = -1 }\n\\end{gathered}\n\\]\n\\end{enumerate}\n\n\\exercisehead{6} \n\\begin{enumerate}\n\\item Vector form of lines: $tA + P_1= X$; \\, $A = P_2 - P_1$.  \n\\[\n\\begin{gathered}\n  \\begin{aligned}\n    & t \\left( \\begin{matrix} x_2 - x_1 \\\\ y_2 - y_1 \\end{matrix} \\right) + \\left( \\begin{matrix} x_1 \\\\ y_1 \\end{matrix}\\right) = \\left( \\begin{matrix} x \\\\ y \\end{matrix} \\right) \\\\\n    & t \\left( \\begin{matrix} x_2 - x_1 \\\\ y_2 - y_1 \\end{matrix} \\right) + -\\left( \\begin{matrix} x-x_1 \\\\ y-y_1 \\end{matrix} \\right) = 0  \n\\end{aligned}\n\\end{gathered}\n\\]\nThen $A, X-P_1$ are linearly dependent.  \\\\\nThen if $A$, $X-P_1$ form rows of a matrix, \n\\[\n\\left| \\begin{matrix} x-x_1 & y-y_1 \\\\ x_2-x_1 & y_2 - y_1 \\end{matrix} \\right| = 0 \n\\]\nAlso\n\\[\nt \\left( \\begin{matrix} x_2 \\\\ t_2 \\end{matrix} \\right) + (1-t)\\left( \\begin{matrix} x_1 \\\\ t_1 \\end{matrix} \\right) - \\left( \\begin{matrix} x \\\\ y \\end{matrix} \\right) = 0 \n\\]\nwe can extend this to say\n\\[\n\\begin{aligned}\n  t \\left( \\begin{matrix} x_2 \\\\ y_2 \\\\ 1 \\end{matrix} \\right) + (1-t) \\left( \\begin{matrix} x_1 \\\\ y_1 \\\\ 1 \\end{matrix} \\right) - \\left( \\begin{matrix} x_1 \\\\ y_1 \\\\ 1 \\end{matrix} \\right) & = 0 = \\\\\n  = tX_2 + (1-t)X_1 - X & = 0 \n\\end{aligned}\n\\]\n$X,X_1,X_2$ are dependent, and so if $X,X_1,X_2$ form rows of a matrix, then \n\\[\n\\left| \\begin{matrix} x & y & 1 \\\\ x_1 & y_1 & 1 \\\\ x_2 & y_2 & 1 \\end{matrix} \\right| = 0 \n\\]\n\\item Recall the vector form for planes: $P = \\{ X | X = P + sA + tB \\}$, $A,B$ are independent.  \n\\[\n\\begin{gathered}\nX = \\left( \\begin{matrix} x \\\\ y \\\\ z \\end{matrix} \\right) = \\left( \\begin{matrix} x_0 \\\\ y_0 \\\\ z_0 \\end{matrix} \\right) + s \\left( \\begin{matrix} x_1 - x_0 \\\\ y_1 - y_0 \\\\ z_1 - z_0 \\end{matrix} \\right) + t \\left( \\begin{matrix} x_2 - x_0 \\\\ y_2 - y_0 \\\\ z_2 - z_0 \\end{matrix} \\right) = P + sA + tB \\\\\n0 = P-X + sA + tB\n\\end{gathered}\n\\] \n$P-X, A,B$ are dependent.  Then consider $P-X,A,B$ to be rows of a matrix.  Then \n\\[\n\\left| \\begin{matrix} x_0 - x & y_0 - y & z_0 - z \\\\ x_1 - x_0 & y_1 - y_0 & z_1 - z_0 \\\\ x_2 - x_0 & y_2 - y_0 & z_2 - z_0 \\end{matrix} \\right| = 0 \n\\]\nWe could also rewrite this equation like this:\n\\[\n\\begin{gathered}\n  \\left( \\begin{matrix} x \\\\ y \\\\ z \\end{matrix} \\right) - \\left( \\begin{matrix} x_0 \\\\ y_0 \\\\ z_0 \\end{matrix} \\right) - s \\left( \\begin{matrix} x_1 \\\\ y_1 \\\\ z_1 \\end{matrix} \\right) + s \\left( \\begin{matrix} x_0 \\\\ y_0 \\\\ z_0 \\end{matrix} \\right) - t \\left( \\begin{matrix} x_2 \\\\ y_2 \\\\ z_2 \\end{matrix} \\right)  + t \\left( \\begin{matrix} x_0 \\\\ y_0 \\\\ z_0 \\end{matrix} \\right) = 0 \\\\\n  \\left( \\begin{matrix} x \\\\ y \\\\ z \\end{matrix} \\right) + (t+s-1) \\left( \\begin{matrix} x_0 \\\\ y_0 \\\\ z_0 \\end{matrix} \\right) -t \\left( \\begin{matrix} x_2 \\\\ y_2 \\\\ z_2 \\end{matrix} \\right) - s\\left( \\begin{matrix} x_1 \\\\ y_1 \\\\ z_1 \\end{matrix} \\right) = 0 \n\\end{gathered}\n\\]\nExtend by $1$ for a new row.  \n\\[\n  \\left( \\begin{matrix} x \\\\ y \\\\ z \\\\ 1 \\end{matrix} \\right) + (t+s-1) \\left( \\begin{matrix} x_0 \\\\ y_0 \\\\ z_0 \\\\ 1 \\end{matrix} \\right) -t \\left( \\begin{matrix} x_2 \\\\ y_2 \\\\ z_2 \\\\ 1 \\end{matrix} \\right) - s\\left( \\begin{matrix} x_1 \\\\ y_1 \\\\ z_1 \\\\ 1 \\end{matrix} \\right) = 0 \n\\]\nThis shows that these 4 vectors are linearly dependent.  Consider the vectors as rows of matrix to obtain:\n\\[\n\\left| \\begin{matrix} x & y & z & 1 \\\\ x_0 & y_0 & z_0 & 1 \\\\ x_1 & y_1 & z_1 & 1 \\\\ x_2 & y_2 & z_2 & 1 \\end{matrix} \\right| = 0 \n\\]\n\\item We have 3 noncollinear points that satisfy some specific equation for a circle in the $x-y$ plane.  \n\\[\n(x-x_0)^2 + (y-y_0)^2 = \\rho^2 = (x^2 - 2xx_0 + x_0^2) + (y^2 - 2yy_0 + y_0^2) \\text{ or } x^2 - 2x_0 x + y^2 - 2y_0 y - (\\rho^2 - x_0^2 - y_0^2) = 0\n\\]\nSo $x_0, y_0$, the coordinates for the origin, and $\\rho$, the radius of the circle, are 3 unknowns and 3 equations are needed.  To fix the ``scale'' of the coordinates, we need a 4th equation.  \n\\[\n\\Longrightarrow \\begin{aligned} x_1^2 - 2x_0 x_1 + y_1^2 - 2y_0 y_1 - (\\rho^2 - x_0^2 - y_0^2) & = 0 \\\\\n  x_2^2 - 2x_0 x_2 + y_2^2 - 2y_0 y_2 - (\\rho^2 - x_0^2 - y_0^2) & = 0 \\\\\nx_3^2 - 2x_0 x_3 + y_3^2 - 2y_0 y_3 - (\\rho^2 - x_0^2 - y_0^2) & = 0 \\\\\nx^2 - 2x_0 x + y^2 - 2y_0 y - (\\rho^2 - x_0^2 - y_0^2) & = 0\n\\end{aligned} \\quad \\, \\Longrightarrow \\left( \\begin{matrix} x^2 + y^2 \\\\ x_1^2 + y_1^2 \\\\ x_2^2 + y_2^2 \\\\ x_3^2 + y_3^2 \\end{matrix} \\right) -2x_0 \\left( \\begin{matrix} x \\\\ x_1 \\\\ x_2 \\\\ x_3 \\end{matrix} \\right) - 2y_0 \\left( \\begin{matrix} y \\\\ y_1 \\\\ y_2 \\\\ y_3 \\end{matrix} \\right) - (\\rho^2 - x_0^2 - y_0^2) \\left( \\begin{matrix} 1 \\\\ 1 \\\\ 1 \\\\ 1 \\end{matrix} \\right) = 0 \n\\]\n\\textbf{Notice} how $x_j^2$ and $y_j^2$ must be ``\\emph{correlated}'' in that their relative values are not independent, but must be $1$ to $1$.   \\\\\n\nWe can also consider ``getting rid'' of the $\\rho^2$ unknown by taking an equation minus the previous equation:\n\\[\n\\begin{aligned}\n  x_1^2 - 2x_1 x_0 + x_0^2 + y_1^2 -2y_1 y_0 + y_0^2 & = \\rho^2 \\\\ \n  - (x^2 - 2x x_0 + x_0^2 + y^2 - 2y y_0 + y_0^2 & = \\rho^2 ) \\\\\n  \\Longrightarrow x_1^2 - x^2 + -2x_0(x_1-x) + y_1^2 - y^2 + -2y_0(y_1-y) & = 0\n\\end{aligned}\n\\]\nSo that we get\n\\[\n\\begin{aligned}\n\\left( \\begin{matrix} x_1^2 - x^2 \\\\ x_2^2 - x_1^2 \\\\ x_3^2 - x_2^2 \\\\ x^2 - x_3^2 \\end{matrix} \\right) + -2x_0 \\left( \\begin{matrix} x_1 - x \\\\ x_2 - x_1 \\\\ x_3 - x_2 \\\\ x - x_3 \\end{matrix} \\right) + \\left( \\begin{matrix} y_1^2 - y^2 \\\\ y_2^2 - y_1^2 \\\\ y_3^2 - y_2^2 \\\\ y^2 - y_3^2 \\end{matrix} \\right) + -2y_0 \\left( \\begin{matrix} y_1 - y \\\\ y_2 - y_1 \\\\ y_3 - y_2 \\\\ y - y_3 \\end{matrix} \\right) = 0 \n\\end{aligned}\n\\]\n\\end{enumerate}\nThus, these 4 vectors above are linearly dependent, which implies\n\\[\n\\boxed{ \\left| \\begin{matrix}  x_1^2 - x^2 & x_2^2 - x_1^2 & x_3^2 - x_2^2 & x^2 - x_3^2 \\\\ x_1 - x & x_2 - x_1 & x_3 - x_2 & x - x_3 \\\\ y_1^2 - y^2 & y_2^2 - y_1^2 & y_3^2 - y_2^2 & y^2 - y_3^2 \\\\ y_1 -y & y_2 - y_1 & y_3 - y_2 & y - y_3  \\end{matrix} \\right| = 0 }\n\\]\n\n\\exercisehead{7} $F(x) = det{ [f_{ij}(x)]}$  \n\\[\n\\begin{aligned}\n  & i= 1 \\quad \\, & f_{11} \\Longrightarrow |f_{11}| = F(x) \\quad \\, \\Longrightarrow F'(x)  = f'_{11} = det{A_1} \\\\\n  & i = 2  \\quad \\, & \\left| \\begin{matrix} f_{11} & f_{12} \\\\ f_{21} & f_{22} \\end{matrix} \\right| = f_{11} f_{22} - f_{12} f_{21} = F(x) \\\\ \n  & \\quad \\, & \\begin{gathered}\n    F'(x) = f_{11}' f_{22} + f_{11}f_{22}'  -f_{12}'f_{21} -f_{12} f_{21}' \\\\\n    \\left| \\begin{matrix} f_{11}' & f_{12}' \\\\ f_{21} & f_{22} \\end{matrix} \\right| + \\left| \\begin{matrix} f_{11} & f_{12} \\\\ f_{21}' & f_{22}' \\end{matrix} \\right| = |A_1| + |A_2| = f_{11}' f_{22} - f_{21}f_{12}' + f_{11}f_{22}' - f_{12}f_{21}' = F'(x)\n\\end{gathered}\n\\end{aligned}\n\\]\nAssume $n$ case is true.  \n\\[\n\\begin{aligned}\n  F(x) & = det{ (f_{ij}(x))} = \\sum_{k=1}^{n+1} f_{n+1,\\, k} (-1)^{n+1+k} det{(f)_{n+1, \\, k} } \\\\\n  F'(x) & = \\sum_{k=1}^{n+1}f_{n+1,k}' cof{(f)_{n+1,k}} + \\sum_{k=1}^{n+1} f_{n+1,k}(-1)^{n+1+k} (det{(f)_{n+1,k}})'\n\\end{aligned}\n\\]\n$\\sum_{k=1}^{n+1} f_{n+1,k}' cof{(f)_{n+1,k}} = det{A_{n+1}}$, matrix obtained by differentiating the $n+1$ row of $[f_{ij}]$ \\\\\n$(det{(f)_{n+1,k}})' = \\sum_{l=1}^n det{B_l}$ where $B_l$ is the matrix obtained by differentiating the $l$th row of $(f)_{n+1,k}$, $l=1,\\dots, n$\n\\[\n\\begin{gathered}\n\\begin{aligned}\n  \\sum_{k=1}^{n+1} f_{n+1,k}(-1)^{n+1+k} (det{(f)_{n+1,k}})' & = \\sum_{k=1}^{n+1}f_{n+1,k}(-1)^{n+1+k} \\sum_{l=1}^n det{B_l} = \\sum_{l=1}^n \\sum_{k=1}^{n+1} f_{n+1,k}(-1)^{n+k+1} det{B_l} = \\\\\n  & = \\sum_{l=1}^n det{A_l} \n\\end{aligned} \\\\\n\\Longrightarrow F'(x) = det{A_{n+1}} + \\sum_{l=1}^n det{A_l} = \\boxed{ \\sum_{l=1}^{n+1} det{A_l} }\n\\end{gathered}\n\\]\n\n\\exercisehead{8} Consider $W(x) = [u_j^{(i-1)}(x)]$.  \\\\\n$|W(x)| = |[ u_j^{(i-1)}(x)]|$\nUse Ex.7: $F'(x) = \\sum_{i=1}^n det{A_i(x)}$, where $A_i(x)$ is the matrix obtained by differentiating the functions in the $i$th row of $[f_{ij}(x)]$, then \\\\\n\n$|W(x)|' = \\sum_{i=1}^n det{A_i(x)}$, where $A_i(x)$ is the matrix obtained by differentiating the functions in the $i$th row of $[u_j^{(i-1)}(x)]$.  \\smallskip \\\\\n\nFor $i=1, \\dots, n-1$, $i+1 = 2,\\dots, n$ and there's a $k=i+1$ row s.t. $k=2,\\dots, n$ so that $det{A_i}=0$,  \\smallskip \\\\\n\nFor $i=n$, $[u_j^{(n-1)}(x)]' = [u_j^{(n)}(x)]$ and for $k=1,\\dots, n-1$, $[u_j^{(k-1)}(x)]$ is different from $[u_j^{(n)}(x)]$.  \\\\\n$\\Longrightarrow |W(x)|' = det{A_n(x)}$, where $A_n(x)$ is the matrix obtained by differentiating the functions in the $n$th row of $[u_j^{(i-1)}(x)]$\n\n%-----------------------------------%-----------------------------------%-----------------------------------\n\\section*{ 4.4 Exercises - Linear transformations with diagonal matrix representations, Eigenvectors and eigenvalues of a linear transformations, Linear independence of eigenvectors corresponding to distinct eigenvalues }\n%-----------------------------------%-----------------------------------%-----------------------------------\n\\exercisehead{1} \\begin{enumerate}\n\\item $\\begin{aligned} T(x) & = \\lambda x \\\\ aT(x) & = (a\\lambda)x \\end{aligned}$\n\\item $\\begin{aligned} T_1(x) & = \\lambda_1 x \\\\ T_2(x) & = \\lambda_2 x \\end{aligned} \\quad \\, (aT_1 + bT_2)(x) = a\\lambda_1 x + b\\lambda_2 x = (a\\lambda_1 + b\\lambda_2)x$\n\\end{enumerate}\n\n\\exercisehead{2} \\[\n\\begin{aligned}\n  T(x) & = \\lambda x \\\\ \n  T^2(x) & = T(T(x)) = T(\\lambda x) = \\lambda T(x) = \\lambda^2 x \\\\\n  T^n(x) & = \\lambda^n x \\\\\n  T^{n+1}(x) & = T(T^n(x)) = T(\\lambda^n x) = \\lambda^n \\lambda x = \\lambda^{n+1} x \n\\end{aligned}\n\\]\nLet $P(x) = \\sum_{j=0}^N a_j x^j$ \\\\\n\\phantom{Let} $P(T)(x) = \\sum_{j=0}^N a_j T^j(x)$. \\\\\n\nIf $x$ is an eigenvector, $P(T)(x) = \\sum_{j=0}^N a_j T^j(x) = \\sum_{j=0}^N a_j \\lambda^j (x) = P(\\lambda)x$.  \n\n\\exercisehead{3} $V = V_2(\\mathbb{R})$, plane as a real linear space.  \\\\\n$T = $ rotation of $V$ through an angle of $\\frac{\\pi}{2}$ radians.  \n\\[\n\\begin{gathered} \n  T = \\left[ \\begin{matrix} 0 & - 1 \\\\ 1 & 0 \\end{matrix} \\right] \\text{ or } \\begin{aligned} T(e_1) & = e_2 \\\\ T(e_2) & = -e_1 \\end{aligned} \\quad \\quad \\, \\Longrightarrow \\begin{aligned} T^2(x) & = T^2(x_1 e_1 + x_2 e_2 ) = T(x_1 e_2 + x_2 (-e_1)) = \\\\ & = -x_1 e_1 + x_2 (-e_2) = -x \\end{aligned}\n\\end{gathered}\n\\]\n\n\\exercisehead{4} \\[\n\\begin{gathered} \n  \\begin{aligned} T^2x_{\\lambda} & = \\lambda^2 x_{\\lambda} \\\\ T^2 - \\lambda^2 I = (T+\\lambda I)(T- \\lambda I)  \\end{aligned} \\\\\n  det{(T^2 - \\lambda^2 I) } = 0 = det{(T+\\lambda I)} det{(T-\\lambda I) } = 0 \n\\end{gathered}\n\\]\n$det{(T+\\lambda I)}$ or $det{(T-\\lambda I)}$ is zero, so $\\lambda$ or $-\\lambda$ is an eigenvalue of $T$.  \n\n\\exercisehead{5} Let $V$ be the linear space of all real functions differentiable on $(0,1)$.  \\\\\nLet $f \\in V$.  \\\\\nDefine $g = T(f)$ s.t. $g(t) = tf'(t)$ $\\, \\forall \\, t \\in (0,1)$ \\\\\nSuppose $f$ is an eigenfunction of $T$.  \n\\[\ng(t) = T(f)(t) = tf'(t)  = \\lambda f(t) \\Longrightarrow \\boxed{ f(t) = c_0 t^{\\lambda} }\n\\]\nIn solving this ordinary differential equation, $\\lambda \\in \\mathbb{R}$\n\n\\exercisehead{6} $V = p(x)$ of degree $\\leq n$.  \\\\\n$p \\in V$, $q = T(p)$ s.t. $q(t) = p(t+1)$ $\\, \\forall \\, t$ \n\\[\n\\begin{gathered}\n  p(t) = \\sum_{j=0}^N a_j t^j \\\\\n  T(p(t)) = q(t) = p(x+1) = \\sum_{j=0}^N a_j(t+1)^j  = \\lambda \\sum_{j=0}^N a_j t^j \n\\end{gathered}\n\\]\n\n\\[\n\\begin{aligned}\n  & N =0 \\quad & a_0 = \\lambda a_0  \\Longrightarrow \\lambda =1 \\\\\n  & \\quad \\\\\n  & N =1 \\quad & \\begin{gathered} \n    \\begin{aligned} \n      & a_1 (t+1) + a_0 = \\lambda (a_1 t + a_0 ) \\\\\n      & t (a_1 (1-\\lambda)) + a_1 + a_0 (1-\\lambda) = 0 \n\\end{aligned} \\\\\n    \\begin{aligned} & \\text{ if } a_1 = 0, \\, \\text{ then } a_0  =0 \\text{ or } \\lambda = 1 \\\\\n      & \\text{ if } \\lambda = 1, \\, a_1 = 0 \n\\end{aligned}\n\\end{gathered} \\\\ \n  & \\quad \\\\\n  & N = 2 \\quad & \\begin{gathered}\n\\begin{aligned} \n  & a_2 (t+1)^2 + a_1 (t+1) + a_0 = \\lambda (a_2 t^2 + a_1 t + a_0 ) \\\\\n  & a_2 (t^2 + 2t + 1) + a_1 (t+1) + a_0 = \\lambda (a_2 t^2 + a_1 t + a_0 ) \\\\\n  & t^2 (a_2 (1-\\lambda)) + t (2a_2 + a_1(1-\\lambda) ) +a_2 + a_1 + (1-\\lambda)a_0 = 0 \n\\end{aligned} \\\\\n\\begin{aligned}\n  \\text{ if } a_2 = 0, \\, \\text{ we're left with $N=1$ case } \\\\\n  \\text{ if } \\lambda =1, \\, a_2 = 0; \\, \\text{ we're left with $N=1$ case.}\n\\end{aligned}\n\\end{gathered}\n\\end{aligned}\n\\]\nAssume $\\sum_{j=0}^N a_j(t+1)^j = \\lambda \\sum_{j=0}^N a_j t^j, \\, a_j =0 \\quad \\forall \\, j = 1,\\dots N$\n\\[\n\\begin{gathered}\n  \\sum_{j=0}^{N+1} a_j (t+1)^j = \\lambda \\sum_{j=0}^{N+1} a_j t^j \\\\\n  \\sum_{j=0}^{N+1} a_j \\sum_{k=0}^j \\binom{j}{k} t^k = \\lambda \\sum_{j=0}^{N+1} a_j t^j \\\\\n  \\sum_{j=0}^{N+1} a_j \\sum_{k=0}^j \\binom{j}{k} t^k - \\lambda a_j t^j = 0 \n\\end{gathered}\n\\]\n$a_{N+1}(1-\\lambda) =0$.  \\\\\nIf $\\lambda = 1$, $t^N: \\, a_{N+1}(N+1) + a_N - \\lambda a_N = 0$; \\quad $a_{N+1} =0$, and then we could rewrite the equation, and coefficients, as $N$th case, which we've shown to yield only $a_0$ to be nonzero.  \n\n\\exercisehead{7} Let $V = $ linear space of functions continuous on $(-\\infty, \\infty)$ s.t. $\\exists \\, \\int_{-\\infty}^x f(t) dt $ $\\quad \\forall \\, x \\in \\mathbb{R}$  \\\\\nIf $f \\in V$, let $g= T(f)$ s.t. $g(x) = \\int_{-\\infty}^x f(t) dt $  \n\\[\n\\begin{gathered}\n  T(f)(x) = g(x) = \\int_{-\\infty}^x f(t) dt = \\lambda f(x) \\\\\n  \\Longrightarrow f(x) = \\lambda f'(x)  \\Longrightarrow \\boxed{ f(x) = c_0e^{\\lambda x} } \\\\\n  \\int_{-\\infty}^x f(t) dt = \\left. \\left( \\frac{ c_0 e^{\\lambda t} }{ \\lambda } \\right) \\right|_{-\\infty}^x = \\frac{c_0 e^{\\lambda x} }{\\lambda} - \\lim_{t \\to -\\infty} \\frac{c_0 e^{\\lambda t}}{\\lambda} \n\\end{gathered}\n\\]\nA limit only exists if $\\lambda > 0$.\n\n\\exercisehead{8} \\[\n\\begin{gathered}\n  g(x) = T(f)(x) = \\int_{-\\infty}^x tf(t) dt = \\lambda f(x)  \\\\\n  xf(x) = \\lambda f'(x) \\\\\n \\text{ if } \\lambda \\neq 0, \\,  \\ln{ \\left( \\frac{ f(x) }{ f(0) } \\right) } = \\frac{ \\frac{1}{2} x^2 }{ \\lambda } \\, \\Longrightarrow \\boxed{ f(x) = c_0 e^{ \\frac{x^2 }{ 2 \\lambda } } } \\\\\n \\int_{-\\infty}^x t c_0 e^{ t^2 / 2\\lambda } dt = c_0 e^{ x^2 / 2 \\lambda } - \\lim_{t \\in - \\infty} c_0 e^{t^2 / 2\\lambda } \n\\end{gathered}\n\\]\nLimit only exists if $\\lambda < 0$.\n\n\\exercisehead{9} \\[\n\\begin{aligned}\n  T(f) & = f'' = \\lambda f \\\\\n  f(t) & = c_n \\sin{nt} \\quad \\, f(0) = f(\\pi) =0  \\\\\n  f''(t) & = -n^2 c_n \\sin{nt} = \\lambda f \\quad \\, \\Longrightarrow \\lambda_n =-n^2\n\\end{aligned}\n\\]\n\n\\exercisehead{10} $T(x) = (y_n)$.  $y_n = a-x_n$; \\quad $n\\geq 1$  \\\\\n$T((x_n)) = (a-x_n) = \\lambda(x_n)$ \\\\\n\nThe sequences are equal, so $a-x_n = \\lambda x_n$ or $a= (\\lambda +1)x_n$.  \\\\\n$(x_n)$ is a convergent sequence, so \n\\[\nx_n - a= x_n - (\\lambda +1)x_n = -\\lambda x_n \\text{ must go to zero }\n\\]\nSo $\\lim_{n\\to \\infty} x_n =0 , \\, a=0$.  Then by $a = (\\lambda +1)x_n$, $\\lambda = -1$ for nonzero $x_n$.  \n\\[\n\\boxed{ \\lambda = -1, \\, (x_n) \\text{ s.t. } \\lim_{n\\to \\infty} x_n = 0 \\text{ and } x_n \\text{ nonconstant } }\n\\]\nIf $x_n$ is constant, $a= (\\lambda +1)a \\, \\Longrightarrow \\lambda =0$.  \n\\[\n\\boxed{ \\lambda = 0, \\quad \\, x_n = a , \\, (x_n) \\text{ is a constant sequence } }\n\\]\n\n\\exercisehead{11}$T(x) = \\lambda x$; $T(y) = \\mu y$.  \n\\[\n\\begin{gathered}\n  T(ax+ by) = \\beta(ax+ by) = a\\lambda x + b \\mu y  \\\\\n  a(\\beta - \\lambda) x + b(\\beta - \\mu) y = 0 \n\\end{gathered}\n\\]\nUse Thm., Thm. 4.2: Let $u_1, u_2, \\dots, u_k$ be eigenvectors of linear linear transformation $T: S \\to V$.  \\\\\nAssume corresponding eigenvalues $\\lambda_1, \\lambda_2, \\dots, \\lambda_k$ distinct.  \\\\\n\\quad Then $u_1, u_2, \\dots, u_k$ are independent.  \n\\[\n\\Longrightarrow x,y \\text{ independent }  \\quad \\, \\beta- \\lambda = \\beta - \\mu = 0 \n\\] \nIf $\\lambda = \\beta, \\, \\mu \\neq \\beta$ or  $\\mu = \\beta, \\, \\lambda \\neq \\beta$.  (given that $\\lambda, \\mu$ distinct).  \n\n\\exercisehead{12} Suppose $x,y \\in S$, so $\\begin{aligned} T(x) & = \\lambda x \\\\ T(y) & = \\mu y \\end{aligned}$  \\\\\nSuppose $\\lambda \\neq \\mu$.  \\\\\nSuppose $ax + by \\in S$ for some $a,b \\in \\mathbb{R}$.  Then by definition of $S$, $ax+ by$ is an eigenvector of $T$.  \\\\\n\\quad Then by Exercise 11, $a$ or $b$ is zero.  Suppose $b=0$.  \n\\[\n\\begin{aligned}\n  & T(ax+by) = \\beta(ax+by) = aT(x) + bT(y) = a\\lambda x + b \\mu y \\\\\n  & T(ax) = \\beta (ax) = a\\lambda x = \\lambda (ax) \n\\end{aligned}\n\\]\n$ax$ nonzero, so $\\beta = \\lambda$.  \\\\\n\nSo if $x\\in S$, so is $ax \\in S$, $a\\neq 0$ and $T(x) = cx = T(ax) = c(ax)$  \\\\\n\\quad This must be true $\\forall \\, x \\in S \\Longrightarrow T(x) = cx \\quad \\, \\forall \\, x \\in S$.  \n\n%-----------------------------------%-----------------------------------%-----------------------------------\n\\section*{ 4.8 Exercises - The finite-dimensional case.  Characteristic polynomials.  Calculation of eigenvalues and eigenvectors in the finite-dimensional case.  Trace of a matrix }\n%-----------------------------------%-----------------------------------%-----------------------------------\n\n\\exercisehead{1} \\begin{enumerate}\n\\item $\\left[ \\begin{matrix} 1 & 0 \\\\ 0 & 1 \\end{matrix} \\right]$  $\\lambda_{1,2} = 1$  \\quad \\, $\\zeta_{\\lambda=1} = \\left[ \\begin{matrix} 1 \\\\ 0 \\end{matrix} \\right], \\, \\left[ \\begin{matrix} 0 \\\\ 1 \\end{matrix} \\right]$; \\quad \\, $E(1) = 2$\n\\item $\\left[ \\begin{matrix} 1 & 1 \\\\ 0 & 1 \\end{matrix} \\right]$\n\\[\n\\begin{gathered}\n  \\left| \\begin{matrix} \\lambda -1 & - 1 \\\\ 0 & \\lambda - 1 \\end{matrix} \\right| = (\\lambda -1)^2 = 0 \\\\\n  \\left[ \\begin{matrix} 1 & 1 \\\\ 0 & 1 \\end{matrix} \\right] \\left[ \\begin{matrix} x_1 \\\\ x_2 \\end{matrix} \\right] = \\left[ \\begin{matrix} x_1 \\\\ x_2 \\end{matrix} \\right] \\quad \\, \\Longrightarrow \\zeta_{\\lambda =1} = \\left[ \\begin{matrix} 1 \\\\ 0 \\end{matrix} \\right]; \\quad \\, E(1) = 1 \n\\end{gathered}\n\\]\n\\item $\\left[ \\begin{matrix} 1 & 0 \\\\ 1 & 1 \\end{matrix} \\right]$  \n\\[\n\\begin{gathered}\n  \\left| \\begin{matrix} \\lambda -1 & 0 \\\\ -1 & \\lambda - 1 \\end{matrix} \\right| = (\\lambda -1)^2 = 0 \\\\\n  \\boxed{ \\lambda =1, \\quad \\, \\zeta_{\\lambda =1 } = \\left[ \\begin{matrix} 0 \\\\ 1 \\end{matrix} \\right]; \\quad \\, E(1) = 1 }\n\\end{gathered}\n\\]\n\\item $\\left[ \\begin{matrix} 1 & 1 \\\\ 1 & 1 \\end{matrix} \\right]$\n\\[\n\\begin{gathered}\n  \\left| \\begin{matrix} \\lambda - 1 & -1 \\\\ -1 & \\lambda - 1 \\end{matrix} \\right| = (\\lambda -1)^2 - 1 = (\\lambda -2)\\lambda = 0 ; \\quad \\, \\lambda = 0, \\, 2 \\\\\n  \\begin{aligned} \\lambda & = 2, \\, \\zeta_{\\lambda =2 } = \\frac{1}{\\sqrt{2}} \\left[ \\begin{matrix} 1 \\\\ 1 \\end{matrix} \\right]; \\quad \\, & E(2) & = 1 \\\\ \n    \\lambda & = 0, \\, \\zeta_{\\lambda =0} = \\frac{1}{\\sqrt{2}} \\left[ \\begin{matrix} 1 \\\\ -1 \\end{matrix} \\right]; \\quad \\, & E(0) & =1 \\end{aligned}\n\\end{gathered}\n\\]\n\\end{enumerate}\n\n\\exercisehead{2} $\\left[ \\begin{matrix} 1 & a \\\\ b & 1 \\end{matrix} \\right]$; \\, $a>0 , \\, b>0$ \n\\[\n\\begin{gathered}\n  \\left| \\begin{matrix} \\lambda - 1 & -a \\\\ -b & \\lambda -1 \\end{matrix} \\right| = (\\lambda -1)^2 -ab = \\lambda^2 - 2\\lambda + 1 -ab =0 \\quad \\quad \\, \\lambda_{\\pm} = \\frac{ 2 \\pm \\sqrt{ 4 - 4(1)(1-ab) }}{2} = 1 \\pm \\sqrt{ab} \\\\\n \\quad \\, \\\\\n \\left[ \\begin{matrix} 1 & a \\\\ b & 1 \\end{matrix} \\right] \\left[ \\begin{matrix} x_1 \\\\ x_2 \\end{matrix} \\right] = (1 \\pm \\sqrt{ab} )\\left[ \\begin{matrix} x_1 \\\\ x_2 \\end{matrix} \\right] \\Longrightarrow \\begin{aligned} x_1 + a x_2 & = (1 \\pm \\sqrt{ab} ) x_1 \\\\ bx_1 + x_2 & = (1\\pm \\sqrt{ab})x_2 \\end{aligned} \\\\\n \\quad \\, \\\\\n \\boxed{ \\lambda_{\\pm} = 1 \\pm \\sqrt{ab}; \\quad \\, \\zeta_{\\lambda = 1 \\pm \\sqrt{ab}} = \\left( \\begin{matrix} \\sqrt{a} \\\\ \\pm \\sqrt{b} \\end{matrix} \\right) \\quad \\, E(1 \\pm \\sqrt{ab}) = 1  }\n\\end{gathered}\n\\]\n\n\\exercisehead{3} $\\left[ \\begin{matrix} c{\\theta} & - s{\\theta} \\\\ s{\\theta} & c{\\theta} \\end{matrix} \\right]$\n\\[\n\\left| \\begin{matrix} \\lambda - c{\\theta} & s{\\theta} \\\\ -s{\\theta} & \\lambda - c{\\theta} \\end{matrix} \\right| = \\lambda^2  -2\\lambda c{\\theta} + 1 = 0 \\Longrightarrow \\lambda = c{\\theta} \\pm i s{\\theta}\n\\]\n\\[\n\\begin{aligned}\n  & \\text{ if } \\theta = 2\\pi n, \\quad & \\lambda = 1, \\, \\xi_{\\lambda =1} = \\left[ \\begin{matrix} 1 \\\\ 0 \\end{matrix} \\right], \\, \\left[ \\begin{matrix} 0 \\\\ 1 \\end{matrix} \\right] \\\\ \n  & \\text{ if } \\theta \\neq 2 \\pi n, \\quad & \\lambda = e^{-\\pm i \\theta} \\quad \\begin{gathered}\n    \\left[ \\begin{matrix} c{\\theta} & -s{\\theta} \\\\ s{\\theta} & c{\\theta} \\end{matrix} \\right] \\left[ \\begin{matrix} x \\\\ y \\end{matrix} \\right] = e^{ \\pm i \\theta} \\left[ \\begin{matrix} x \\\\ y \\end{matrix} \\right] \\Longrightarrow \\xi_{\\lambda = e^{\\pm i \\theta} } = 1/\\sqrt{2} \\left[ \\begin{matrix} 1 \\\\ \\pm i \\end{matrix} \\right]\n\\end{gathered}\n\\end{aligned}\n\\]\n\n\\exercisehead{4} $A = \\left[ \\begin{matrix} a & b \\\\ c & d \\end{matrix} \\right]$ \n\\[\n\\begin{aligned}\n  P_1 & = \\left[ \\begin{matrix} 0 & 1 \\\\ 1 & 0 \\end{matrix} \\right] \\\\ \n  P_2 & = \\left[ \\begin{matrix} 0 & -i \\\\ i & 0 \\end{matrix} \\right] \\\\ \n  P_3 & = \\left[ \\begin{matrix} 1 & 0 \\\\ 0 & -1 \\end{matrix} \\right]\n\\end{aligned} \\quad \\quad \\, \\begin{aligned}\n  |\\lambda I - P_1 | & = \\lambda^2 - 1 = 0 \\\\ \n  |\\lambda I - P_2 | & = \\lambda^2 - 1 = 0 \\\\ \n  |\\lambda I - P_3 | & = (\\lambda -1)(\\lambda +1) = 0 \n\\end{aligned}\n\\]\n\\[\n\\begin{gathered}\n  \\left| \\begin{matrix} \\lambda - a & -b \\\\ -c & \\lambda -a \\end{matrix} \\right| = \\lambda^2 - (a+d)\\lambda + (ad-bc) = 0 = (\\lambda -\\lambda_1)(\\lambda - \\lambda_2) = \\lambda^2 - (\\lambda_1 + \\lambda_2) \\lambda + \\lambda_1 \\lambda_2 \\\\\n  \\Delta = ad-bc = -1 \\Longrightarrow a=-d \\\\\n  \\boxed{ A = \\left[ \\begin{matrix} a & b \\\\ c & -a \\end{matrix} \\right] } \\text{ where } a^2 + bc = 1 \n\\end{gathered}\n\\]\n\n\\exercisehead{5}\n\\[\n\\begin{gathered}\n  det{(A -\\lambda I)} = \\lambda^2 - (a+d)\\lambda + (ad-bc) = 0 \\Longrightarrow \\lambda = \\frac{ (a+d) \\pm \\sqrt{ (a+d)^2 - 4(1)(ad-bc) } }{ 2} \\\\ \n  \\begin{aligned}\n    & \\text{ if } \\sqrt{ (a+d)^2 - 4(ad-bc) } > 0, \\, \\lambda \\text{ real and distinct } \\\\ \n    & \\text{ if } \\sqrt{ (a+d)^2 - 4(ad-bc) } = 0, \\, \\lambda \\text{ real and equal } \\\\ \n    & \\text{ if } \\sqrt{ (a+d)^2 - 4(ad-bc) } < 0, \\, \\lambda \\text{ complex conjugates }\n\\end{aligned}\n\\end{gathered}\n\\]\n\n\\exercisehead{6} \\[\n\\begin{aligned}\n  & \\left[ \\begin{matrix} 1 & 1 & 1 \\\\ a & b & c \\\\ d & e & f \\end{matrix} \\right] \\left[ \\begin{matrix} 1 \\\\ 1 \\\\ 1 \\end{matrix} \\right] = 3 \\left[ \\begin{matrix} 1 \\\\ 1 \\\\ 1 \\end{matrix} \\right] & \\quad \\, \\begin{aligned} a + b+ c & = 3 \\\\ d + e + f & = 3 \\end{aligned} \\\\\n  & \\left[ \\begin{matrix} 1 & 1 & 1 \\\\ a & b & c \\\\ d & e & f \\end{matrix} \\right] \\left[ \\begin{matrix} 1 \\\\ 0 \\\\ -1 \\end{matrix} \\right] = 0 \\left[ \\begin{matrix} 1  \\\\ 0 \\\\ -1 \\end{matrix} \\right] & \\quad \\, \\begin{aligned} a - c & = 0 \\\\ d - f & = 0 \\end{aligned} \\quad \\, \\begin{aligned} a & = c \\\\ d & = f \\end{aligned} \\\\\n  & \\left[ \\begin{matrix} 1 & 1 & 1 \\\\ a & b & c \\\\ d & e & f \\end{matrix} \\right] \\left[ \\begin{matrix} 1 \\\\ -1 \\\\ 0 \\end{matrix} \\right] = 0 \\left[ \\begin{matrix} 1 \\\\ -1 \\\\ 0 \\end{matrix} \\right] & \\quad \\, \\begin{aligned} a & = b \\\\ d & = e \\end{aligned}\n\\end{aligned}\n\\]\n\\[\na = b= c = d = e = f = 1 \n\\]\n\n\\exercisehead{7} \\begin{enumerate}\n\\item $\\left[ \\begin{matrix} 1 & 0 & 0 \\\\ -3 & 1 & 0 \\\\ 4 & -7 & 1 \\end{matrix} \\right]$\n\\[\n\\left| \\begin{matrix} 1 - \\lambda & & \\\\ -3 & 1-\\lambda & \\\\ 4 & -7 & 1- \\lambda \\end{matrix}  \\right| = \\left| \\begin{matrix} 1 - \\lambda & & \\\\ & 1- \\lambda & \\\\ & & 1- \\lambda \\end{matrix} \\right| = 0 \\,  \\quad \\Longrightarrow \\lambda =1\n\\]\n\\[\n\\left[ \\begin{matrix} 1 & 0 & 0 \\\\ -3 & 1 & 0 \\\\ 4 & -7 & 1 \\end{matrix} \\right]\\left[ \\begin{matrix} x_1 \\\\ x_2 \\\\ x_3 \\end{matrix} \\right] = \\left[ \\begin{matrix} x_1 \\\\ x_2 \\\\ x_3 \\end{matrix} \\right]  \\quad \\, \\Longrightarrow \\begin{aligned} x_1 & = 0 \\\\ x_2 & =0 \\\\ x_3 & = 1 \\end{aligned} \\quad \\, \\Longrightarrow \\zeta_{\\lambda =1} = \\left[ \\begin{matrix} 0 \\\\ 0 \\\\ 1 \\end{matrix} \\right]\n\\]\n\\item $\\left[ \\begin{matrix} 2 & 1 & 3 \\\\ 1 & 2 & 3 \\\\ 3 & 3 & 20 \\end{matrix} \\right]$\n\\[\n\\left| \\begin{matrix} 2- \\lambda & 1 & 3 \\\\ 1 & 2-\\lambda & 3 \\\\ 3 & 3 & 20 - \\lambda \\end{matrix} \\right| = \\left| \\begin{matrix} 1 - \\lambda & 1 & 3 \\\\ -1 + \\lambda & 2 - \\lambda & 3 \\\\ 0 & 3 & 20-\\lambda \\end{matrix} \\right| = \\left| \\begin{matrix} 1 - \\lambda & 1 & 3 \\\\ 0 & 3-\\lambda & 6 \\\\ 0 & 3 & 20 -\\lambda \\end{matrix} \\right| = \\left| \\begin{matrix} 1-\\lambda & & \\\\ & 3- \\lambda & 6 \\\\ & 3 & 20 - \\lambda \\end{matrix} \\right|\n\\]\n\\[\n\\begin{gathered}\n(1-\\lambda)((3-\\lambda)(20-\\lambda) -18) = (1-\\lambda)(60 - 23 \\lambda + \\lambda^2 - 18) = (1-\\lambda)(42 -23 \\lambda + \\lambda^2) = (1-\\lambda)(\\lambda -21)(\\lambda - 2) = 0 \\\\\n  \\Longrightarrow \\lambda = 1, \\, 2, \\, 21 \n\\end{gathered}\n\\]\n\\item $\\left[ \\begin{matrix} 5 & -6 & -6 \\\\ -1 & 4 & 2 \\\\ 3 & -6 & -4 \\end{matrix} \\right]$ \n\\[\n\\begin{gathered}\n  \\left| \\begin{matrix} \\lambda -5 & 6 & 6 \\\\ 1 & \\lambda -4 & -2 \\\\ -3 & 6 & \\lambda +4 \\end{matrix} \\right| = \\left| \\begin{matrix} \\lambda -2 & 0 & -\\lambda + 2 \\\\ 0 & \\lambda -4 & -1 \\\\ 0 & 6 & \\lambda + 1 \\end{matrix} \\right| = (\\lambda -2)^2 (\\lambda -1 ) \\\\ \n  \\Longrightarrow \\xi_{\\lambda =1} = \\frac{1}{\\sqrt{19}} \\left[ \\begin{matrix} 3 \\\\ -1 \\\\ 3 \\end{matrix} \\right] , \\, \\xi_{\\lambda =2} = \\frac{1}{\\sqrt{18}} \\left[ \\begin{matrix} 4 \\\\ 1 \\\\ 1 \\end{matrix} \\right], \\, \\frac{1}{\\sqrt{2}} \\left[ \\begin{matrix} 0 \\\\ 1 \\\\ -1 \\end{matrix} \\right]\n\\end{gathered}\n\\] \n\\end{enumerate}\n\n\\exercisehead{8} \\begin{enumerate}\n\\item $\\left[ \\begin{matrix} & & 1 & \\\\ & & & 1 \\\\ 1 & & & \\\\ & 1 & & \\end{matrix} \\right]$\n\\[\n\\left| \\begin{matrix} -\\lambda & & 1 & \\\\ & -\\lambda & & 1 \\\\ 1 & & -\\lambda & \\\\ & 1 & & -\\lambda \\end{matrix} \\right|  = \\left| \\begin{matrix} -\\lambda & & 1 - \\lambda^2 & \\\\ & -\\lambda & & 1-\\lambda^2 \\\\ 1 & & 0 & \\\\ & 1 & & 0 \\end{matrix} \\right| = (1-\\lambda^2)^2 \\Longrightarrow \\lambda = \\pm 1\n\\]\n\\item $\\left[ \\begin{matrix} 1 & & & \\\\ & 1 & & \\\\ & & -1 & \\\\ & & & -1 \\end{matrix} \\right]$ \\quad $\\Longrightarrow (\\lambda-1)^2(\\lambda+1)^2 = 0 \\text{ so } \\lambda = \\pm 1$\n\\item $\\left[ \\begin{matrix} & 1 & & \\\\ 1 & & & \\\\ & & & 1 \\\\ & & 1 & \\end{matrix} \\right]$ \n\\[\n\\left| \\begin{matrix} \\lambda & -1  & & \\\\ -1 & \\lambda & & \\\\ & & \\lambda & -1  \\\\ & & -1 & \\lambda \\end{matrix} \\right| = (\\lambda^2-1)(\\lambda^2 -1) \\Longrightarrow \\lambda = \\pm 1 \n\\]\n\\item $\\left[ \\begin{matrix} & -i & & \\\\ i & & & \\\\ & & & -i \\\\ & & i & \\end{matrix} \\right]$ \n\\[\n\\left| \\begin{matrix} -\\lambda & -i & & \\\\ - & -\\lambda & & \\\\ & & -\\lambda & -i \\\\ & & i & -\\lambda \\end{matrix} \\right| = \\left| \\begin{matrix} -\\lambda & -i \\\\ i & -\\lambda \\end{matrix} \\right|^2 = (\\lambda^2 - 1)^2 \n\\]\n\\item $\\left[ \\begin{matrix} 1 & & & \\\\ & -1 & & \\\\ & & 1 & \\\\ & & & -1 \\end{matrix} \\right] \\Longrightarrow ((\\lambda +1)(\\lambda - 1))^2 = 0$\n\\end{enumerate}\n\n\\exercisehead{10}\n\n\\exercisehead{11} Let $(AB)x = \\lambda x$\n\\[\nA^{-1}(AB)x = \\lambda (A^{-1}x) = BX\n\\]\nLet $x= Ay$\n\\[\n\\lambda (A^{-1} A y) = BA y = \\lambda y \n\\]\nSo if $\\lambda$ is eigenvalue of $AB$, $\\lambda$ is also an eigenvalue of $BA$ ($A$ is invertible).\n\n\\exercisehead{13}\n\n\\exercisehead{14} \\begin{enumerate}\n\\item \\[\ntr{(A+B)} = \\sum_{i=1}^N (A+B)_{ii} = \\sum_{i=1}^N (a_{ii} + b_{ii}) = \\sum_{i=1}^N a_{ii} + \\sum_{i=1}^N b_{ii} = tr{A} + tr{B}\n\\]\n\\item \\[\ntr{(cA)} = \\sum_{i=1}^N (cA)_{ii} = \\sum_{i=1}^N c a_{ii} = c\\sum_{i=1}^N a_{ii} = c tr{A}\n\\]\n\\item $tr{(AB)} = \\sum_{j=1}^N (AB)_{jj} = \\sum_{j=1}^N \\sum_{k=1}^N a_{jk}b_{kj} = \\sum_{k=1}^N \\sum_{j=1}^N b_{kj} a_{jk} = \\sum_{j=1}^N (BA)_{jj} = tr{(BA)}$\n\\item $tr{A^T} = \\sum_{j=1}^N (A^T)_{jj} = \\sum_{j=1}^N a_{jj} = tr{A}$\n\\end{enumerate}\n\n%-----------------------------------%-----------------------------------%-----------------------------------\n\\section*{ 4.10 Exercises - Matrices representing the same linear transformation.  Similar matrices. }\n%-----------------------------------%-----------------------------------%-----------------------------------\n\n\\exercisehead{1} Given \n\\[\n\\begin{aligned}\n  A & = \\left[ \\begin{matrix} 1 & 1 \\\\ 0 & 1 \\end{matrix} \\right] \\\\\n  B & = \\left[ \\begin{matrix} 1 & 0 \\\\ 0 & 1 \\end{matrix} \\right]\n\\end{aligned} \\quad \\, \\begin{aligned} f(\\lambda) & = \\lambda^2 - 2\\lambda + 1 \\\\ g(\\lambda) & = (\\lambda -1)^2 \\end{aligned} \n \\quad \\, \\begin{gathered} \\left[ \\begin{matrix} 1 \\\\ 0 \\end{matrix} \\right] = x_{\\lambda =1 } \\\\ \\zeta_{\\lambda =1 } = \\left[ \\begin{matrix} 1 \\\\ 0 \\end{matrix} \\right], \\, \\left[ \\begin{matrix} 0 \\\\ 1 \\end{matrix} \\right] \\end{gathered}\n\\]\n\nSuppose $C^{-1}BC = A$.  \\smallskip \\\\\n\\quad \\quad $ C^{-1}C = I = A$.  But $A \\neq I$.  \\\\\n\\quad Contradiction.  So $\\nexists$ $C$ invertible s.t. $C^{-1}BC =A$  \n\n\\exercisehead{2} \\begin{enumerate}\n\\item $A = \\left[ \\begin{matrix} 1 & 0 \\\\ 1 & 3 \\end{matrix} \\right]$ \n\\[\n\\begin{gathered}\n  \\left| \\begin{matrix} \\lambda - 1 & \\\\ -1 & \\lambda -3 \\end{matrix} \\right| = (\\lambda - 1)( \\lambda -3 ) \\quad \\quad \\, \\Longrightarrow \\begin{aligned} \\xi_{\\lambda = 1} & = \\frac{2}{ \\sqrt{5}} \\left[ \\begin{matrix} 1 \\\\ -1/2 \\end{matrix} \\right] \\\\ \\xi_{\\lambda =3} & = \\left[ \\begin{matrix} 0 \\\\ 1 \\end{matrix} \\right] \\end{aligned} \\\\ \n  \\boxed{ C = \\left[ \\begin{matrix} 2 /\\sqrt{5} & 0 \\\\ -1/\\sqrt{5} & 1 \\end{matrix} \\right] }  \n\\end{gathered}\n\\]\n\\[\n\\begin{gathered}\n \\text{ indeed, } \\frac{1}{ 2/\\sqrt{5}} \\left[ \\begin{matrix} 1 & 0 \\\\ 1/\\sqrt{5} & 2/\\sqrt{5} \\end{matrix} \\right] \\left[ \\begin{matrix} 1 & \\\\ 1 & 3 \\end{matrix} \\right] C = I \n\\end{gathered}\n\\]\n\\item \\[\n\\begin{gathered}\n  A = \\left[ \\begin{matrix} 1 & 2 \\\\ 5 & 4 \\end{matrix} \\right] \\\\\n  \\left| \\begin{matrix} \\lambda - 1 & -2 \\\\ -5 & \\lambda -4 \\end{matrix} \\right| = \\lambda^2 - 5\\lambda +4 -10 = (\\lambda - 6)(\\lambda + 1) \\\\ \n  \\left[ \\begin{matrix} 1 & 2 \\\\ 5 & 4 \\end{matrix} \\right] \\left[ \\begin{matrix} x_1 \\\\ x_2 \\end{matrix} \\right] = -1,6 \\left[ \\begin{matrix} x_1 \\\\ x_2 \\end{matrix} \\right] \\quad \\Longrightarrow \\begin{aligned} \\xi_{\\lambda = -1} & = \\frac{1}{ \\sqrt{2}} \\left[ \\begin{matrix} 1 \\\\ & -1 \\end{matrix} \\right] \\\\ \\xi_{\\lambda =6} & = \\frac{1}{ \\sqrt{29}} \\left[ \\begin{matrix} 2 \\\\ 5 \\end{matrix} \\right] \\end{aligned} \n\\end{gathered}\n\\]\n\\[\n\\begin{gathered}\n  C = \\left[ \\begin{matrix} 1/\\sqrt{2} & 2/\\sqrt{29} \\\\ -1/\\sqrt{2} & 5/\\sqrt{29} \\end{matrix} \\right] \\\\\n  \\text{ indeed, } 1/(7/\\sqrt{2}\\sqrt{29}) \\left[ \\begin{matrix} 5/\\sqrt{29} & -2/\\sqrt{29} \\\\ 1/\\sqrt{2} & 1/\\sqrt{2} \\end{matrix} \\right] \\left[ \\begin{matrix} 1 & 2 \\\\ 5 & 4 \\end{matrix} \\right]C = \\left[ \\begin{matrix} -1 & \\\\ & 6 \\end{matrix} \\right] \n\\end{gathered}\n\\]\n\\item $A = \\left[ \\begin{matrix} 2 & 1 \\\\ -1 & 4 \\end{matrix} \\right]$\n\\[\n\\begin{gathered}\n  \\left| \\begin{matrix} \\lambda - 2 & -1 \\\\ 1 & \\lambda -4 \\end{matrix} \\right| = (\\lambda -3)^2 \\\\  \n\\end{gathered}\n\\]\nSuppose nonsingular $C$ exists, s.t. $C^{-1}AC =3 I \\Longrightarrow A = 3I$.  Contradiction.  \n\\item \\[\n\\begin{gathered}\n  A = \\left[ \\begin{matrix} 2 & 1 \\\\ -1 & 0 \\end{matrix} \\right] \\quad \\quad \\, \\Longrightarrow \\left| \\begin{matrix} \\lambda -2 & -1 \\\\ 1 & \\lambda \\end{matrix} \\right| = \\lambda^2 - 2\\lambda + 1 = (\\lambda -1)^2\n\\end{gathered}\n\\]\nSuppose nonsingular $C$ exists s.t. $C^{-1}AC = I \\Longrightarrow A = I$.  Contradiction.  \n\\end{enumerate}\n\n\\exercisehead{3} \\[\n\\begin{aligned}\n  & [y_1,y_2] = [x_1,x_2]A \\\\ \n  & [z_1,z_2] = [x_1,x_2]B \\\\ \n  & [z_1,z_2] = [y_1,y_2]C = [x_1,x_2]B = [x_1,x_2]AC \n\\end{aligned} \\quad \\quad \\, \\begin{aligned} B & = AC \\\\ A^{-1} B & = C \\end{aligned} \n\\]\n\n\\exercisehead{4} \n\\begin{enumerate}\n\\item \\[\n  \\begin{gathered}\n    A = \\left[ \\begin{matrix} 0 & 0 & 1 \\\\ 0 & 1 & 0 \\\\ 1 & 0 & 0 \\end{matrix} \\right] \\quad \\quad \\, \\Longrightarrow \\left| \\begin{matrix} \\lambda & 0 & -1 \\\\ 0 & \\lambda - 1 & 0 \\\\ -1 & 0 & \\lambda \\end{matrix} \\right| = \\lambda^3 - \\lambda^2 - \\lambda +1 \\\\\n    \\lambda^3 - \\lambda^2 - \\lambda +1 = (\\lambda-1)^2 (\\lambda +1)\n\\end{gathered}\n\\]\nNote that we could still obtain the following independent eigenvectors: $ \\left[ \\begin{matrix} 1 \\\\ 0 \\\\ 1 \\end{matrix} \\right], \\,  \\left[ \\begin{matrix} 0 \\\\ 1 \\\\ 0 \\end{matrix} \\right], \\,  \\left[ \\begin{matrix} 1 \\\\ 0 \\\\ -11 \\end{matrix} \\right]$ \n\\item \\[\n\\begin{gathered}\n  A = \\left[ \\begin{matrix} 1 & -1 & -1 \\\\ 1 & 3 & 1 \\\\ -1 & -1 & 1 \\end{matrix} \\right] \\quad \\quad \\, \\Longrightarrow f(\\lambda) = \\lambda^3 - 5 \\lambda^2 + 8 \\lambda -4 = \\\\\n  = (\\lambda^2 - 4 \\lambda +4)(\\lambda -1) = (\\lambda -2)^2 (\\lambda-1) \n\\end{gathered}\n\\]\n\\[\n\\Longrightarrow x_{\\lambda =2} = \\left[ \\begin{matrix} 1 \\\\ -1 \\\\ 0 \\end{matrix} \\right], \\quad \\, x_{\\lambda =2} = \\left[ \\begin{matrix} 1 \\\\ 0 \\\\ -1 \\end{matrix} \\right], \\quad \\, x_{\\lambda =1} = \\left[ \\begin{matrix} -1 \\\\ 1 \\\\ -1 \\end{matrix} \\right]\n\\]\n\\end{enumerate}\n\n\\exercisehead{5} Generally, we'll have \n\\[\nC^{-1}AC = \\lambda I + \\left[ \\begin{matrix} & \\\\ 1 & \\end{matrix} \\right] \\Longrightarrow A = \\lambda I + C \\left[ \\begin{matrix} & \\\\ 1 & \\end{matrix} \\right] C^{-1}\n\\]\n\\[\n\\begin{gathered}\n  \\left[ \\begin{matrix} a & b \\\\ c & d \\end{matrix} \\right] \\left[ \\begin{matrix} & \\\\ 1 & \\end{matrix} \\right] C^{-1} = \\left[ \\begin{matrix} b & 0 \\\\ d & 0 \\end{matrix} \\right] \\frac{1}{det{C}} \\left[ \\begin{matrix} d & -b \\\\ -c & a \\end{matrix} \\right] = \\\\\n  = \\frac{1}{det{C}} \\left[ \\begin{matrix} bd & -d^2 \\\\ d^2 & -bd \\end{matrix} \\right]\n\\end{gathered}\n\\]\n\\begin{enumerate}\n\\item So for $A = \\left[ \\begin{matrix} 2 & -1 \\\\ 0 & 2 \\end{matrix} \\right]$.  Then $d=0, \\, b = 1, \\, c=-1$ for $C$.  \n\\item For $A = \\left[ \\begin{matrix} 2 & 1 \\\\ -1 & 4 \\end{matrix} \\right] \\Longrightarrow \\lambda = 3$.  So $bd =-1$, \\, $ad-bc = -1$.  \n\\[\n\\begin{aligned}\n  & \\text{ if $b=1$, \\, $d = -1$, \\, $-a-c=-1$ } \\quad a+c=1 \\\\\n  & \\text{ if $b=-1$, \\, $d=1$, \\, $a+c=-1$ } \n\\end{aligned}\n\\]\n\\end{enumerate}\n\n\\exercisehead{6} \\[\n\\begin{gathered}\n  \\left[ \\begin{matrix} 0 & -1 & \\\\ & & 1 \\\\ -1 & -3 & 5 \\end{matrix} \\right] \\Longrightarrow \\left| \\begin{matrix} \\lambda & 1 & \\\\ & \\lambda & -1 \\\\ 1 & 3 & \\lambda -3 \\end{matrix} \\right| = (\\lambda -1)^3 \\\\ \n  \\Longrightarrow \\frac{1}{\\sqrt{3}} \\left[ \\begin{matrix} 1 \\\\ -1 \\\\ -1 \\end{matrix} \\right]\n\\end{gathered}\n\\]\nSuppose $C^{-1}AC = I$.  $A=CC^{-1} = 1$ so diagonalizing matrix cannot exist for this $A$.  \n\n\\textbf{CHECK} this result.  \n\n\\exercisehead{7}\\begin{enumerate}\n\\item $\\forall$ matrix $A$, we can always consider the characteristic polynomial $|\\lambda I -A| = f(\\lambda)$.  So $\\exists \\, n$ roots, $\\lambda_j \\in \\mathbb{C}$ \nIf $\\lambda_j \\neq 0$, \\, $\\forall \\, j=1,\\dots, n$, then $det{(C^{-1}AC)} = det{A} = det{(\\Lambda)} = \\prod_{j=1} \\lambda_j \\neq 0$.  So $A$ nonsingular.  \n\nIf $A$ nonsingular, $det{A} \\neq 0$, so \n\\[\ndet{A} = det{ (C^{-1}AC)} = det{\\Lambda \\neq 0} \\quad \\, \\Longrightarrow \\lambda_j \\neq \\, \\forall \\, j\n\\]\n\\item $A$ nonsingular, \n\\[\ndet{(AA^{-1})}= det{A}det{A^{-1}} = det{C^{-1}AC} det{D^{-1}AD} = det{\\Lambda_A}det{\\Lambda_A} = \\prod_{j=1}^n \\lambda_j \\prod_{k=1}^n b_k = 1\n\\]\n$\\lambda_j$, $b_k$ distinct, so $b_k = \\frac{1}{ \\lambda_j}$\n\\end{enumerate}\n\n\\exercisehead{8}\n\\begin{enumerate}\n\\item $A^2=-1$ so $A^{-1} = -A$, so $A$ nonsingular.  \n\\item $det{A^2} = (det{A})^2 = (-1)^n$.  $(det{A})^2 >0$, so $(-1)^n = 1$; \\, $n$ even.  \n\\item $A x= \\lambda x$ \\\\\n  $A^2 x = -x = \\lambda^2 x$ \\quad $\\lambda^2 = -1$\n\\item $det{A} =1$  From fundamental theorem of algebra, roots of the characteristic polynomial must come in complex conjugate pairs.  We already showed that the eigenvalues are purely imaginary.  So there must be a whole number of pairs of complex conjugate eigenvalues that multiply together to get ${-1}$.  \\textbf{CHECK} this result.  \n\\end{enumerate}\n\n%-----------------------------------%-----------------------------------%-----------------------------------\n\\section*{ 5.5 Exercises - Eigenvalues and inner products, Hermitian and skew-Hermitian transformations, Eigenvalues and eigenvectors of Hermitian and skew-Hermitian operators, Orthogonality of eigenvectors corresponding to distinct eigenvalues }\n%-----------------------------------%-----------------------------------%-----------------------------------\n\n\\exercisehead{1}\n\\[\n\\begin{aligned}\n  & \\text{ if } T(x) = \\lambda x, (T(x),y) = (\\lambda x, y) = \\lambda (x,y) \\, \\forall y \\in E \\\\\n  & \\text{ if } (T(x),y) = (\\lambda x,y) \\, \\forall y \\in E \\\\\n  & \\quad \\Longrightarrow (T(x) - \\lambda x,y) = 0 \\, \\forall y \\in E \\\\\n  & \\quad \\quad \\Longrightarrow T(x) = \\lambda x\n\\end{aligned}\n\\]\n\n\\exercisehead{2}\n\\[\n\\begin{aligned}\n  & (T(x),y) = (cx,y) = c(x,y) \\\\\n  & (x,T(y)) = (x,cy) = \\bar{c} (x,y) \\\\\n  & \\text{ since $V$ is a real Euclidean space $c \\in \\mathbb{R}$ for $(T(x),y), (x,T(y)) \\in \\mathbb{R}$ }\n\\end{aligned}\n\\]\n\n\\exercisehead{3}\n\\begin{enumerate}\n\\item \\quad Assume $T:V \\to V$ is a Hermitian transformation.   \\\\\n\nUse induction: \n\\[\n\\begin{aligned}\n  (Tx,y) & = (x,Ty) \\\\\n  (T^2 x,y) & = (Tx,Ty) = (x,T^2 y) \\\\\n  (T^{n+1} x, y ) & = (Tx,T^n y) = (x,T^{n+1} y) \n\\end{aligned}\n\\]\n$T^{-1}$ is Hermitian since\n\\[\n  (T^{-1}x,y) = (T^{-1}x, TT^{-1} y) = (TT^{-1} x, T^{-1} y) = (x,T^{-1}y)\n\\]\n\\emph{Neat trick, no?}\n\\item $  (T(x),y) = -(x,T(y)) $.  Now $(T^2(x),y) = - (T(x),T(y)) = (-1)^2 (x,T^2(y)) $.  \\\\\nAssume the $n$th case, $(T^n(x),y) = (-1)^n(x,T^n(y))$, i.e. $T^n$ is Hermitian (skew-Hermitian) if $n$ is even (odd).  Then consider that\n\\[\n(T^{n+1}(x),y) = -(T^n(x),T(y)) = - (-1)^{n} (x,T^{n+1}(y)) = (-1)^{n+1} (x,T^{n+1}(y))\n\\]\n\\[\n(T^{-1}(x), y) = (T^{-1}(x), TT^{-1}y) = -(TT^{-1}(x), T^{-1}(y)) = -(x,T^{-1}(y))\n\\]\nSo $T^{-1}$ is skew-Hermitian.  \n\\end{enumerate}\n\n\\exercisehead{4} \n\\begin{enumerate} \n\\item \\[\n  \\begin{aligned} ((aT_1+bT_2)(x),y) & = (aT_1(x)+bT_2(x),y) = a(T_1(x),y) + b(T_2(x),y) = (x,(aT_1)(y)) + (x,(bT_2)y) = \\\\ \n& = (x, (aT)(y) + (bT_2)(y))  = (x,(aT_1+bT_2)y) \n  \\end{aligned}\n  \\]\n\\item \\[\n\\begin{gathered}\n  (T_1 T_2(x),y) = (T_2(x),T_1(y)) = (x,T_2 T_1(y)) \\\\\n\\text{ if } T_1 T_2 =T_2 T_1; T_1 T_2 \\text{ is Hermitian } \n\\end{gathered}\n\\]\n\\end{enumerate}\n\n\\exercisehead{5}\nLet $V = V_3(\\mathbb{R})$.  \n\\[\n\\begin{aligned}\n  (T(x),y) &= \\sum_{j=1}^3 (T(x))_j y_j = x_1 y_1 + x_2 y_2 -x_3 y_3  \\\\\n  & = x_1 y_1 + x_2 y_2 +x_3 (-y_3) = (x,T(y))\n\\end{aligned}\n\\]\n\n  \\exercisehead{6}\n$\\int_0^1 f(t)dt = F(1)-F(0) = 0, F(1)= F(0)$, likewise, for $g \\in V$, $\\int_0^1 g(t)dt = G(1)-G(0) = 0, G(1)= G(0)$.  \nThe trick is to use integration by parts\n\\[\n\\begin{aligned}\n  (Tf,g) & = \\int_0^1 (Tf)(t)g(t) dt = \\int_0^1 \\int_0^t f(x)dx g(t) dt = \\\\ \n& = \\int_0^1 F(t)g(t) dt - F(0) \\int_0^1 g(t)dt = \\left. F(t)G(t) \\right|_0^1 - \\int_0^1 f(t)G(t) dt = -(f,Tg)\n\\end{aligned}\n\\]\n\n\\exercisehead{7}\n\\begin{enumerate}\n  \\item \\[ \\begin{aligned} (Tf,g) & = \\int_{-1}^1 Tf(t)g(t) dt = \\int_{-1}^1 f(-t)g(t) dt = \\int_1^{-1}f(t)g(-t)(-dt) = \\int_{-1}^1 f(t)g(-t)dt = \\\\\n    & = (f,Tg) \\\\\n  \\end{aligned} \\] \n    \\item \\[\n      \\begin{gathered}\n\t(Tf,g) = \\int_{-1}^1 f(t)f(-t)g(t) dt \\text{ but } (f,Tg) = \\int_{-1}^1 f(t)g(t)g(-t) dt \\\\\n\t\\Longrightarrow \\text{ Neither symmetric nor skew-symmetric (choose different coefficients for $f$ and $g$ ) } \n      \\end{gathered}\n      \\]\n    \\item \\[\n\\begin{aligned}\n  (Tf,g) & = \\int_{-1}^1 Tf(t) g(t) dt = \\int_{-1}^1 (f(t) + f(-t)) g(t) dt = \\int_{-1}^1 fg + - \\int_1^{-1} f(t)g(-t)dt = \\\\\n  & = \\int_{-1}^1 f(t)(g(t) + g(-t))dt = (f,Tg) \n\\end{aligned}\n\\]  Hermitian.  \n    \\item \\[\n\\begin{aligned}\n  (Tf,g) & = \\int_{-1}^1 (f(t)-f(-t)) g(t) dt = \\int_{-1}^1 fg - \\int_{-1}^1 f(-t)g(t) dt = \\\\\n  & = \\int_{-1}^1 fg - \\int_1^{-1} f(t) g(-t) (-dt) = \\int_{-1}^1 f(g(t) - g(-t)) dt = (f,Tg)\n\\end{aligned}\n\\] Hermitian.  \n\\end{enumerate}\n\n\\exercisehead{8} Given $(f,g) = \\int_a^b f(t)g(t) w(t) dt$, $T(f)  = \\frac{ (pf')' + qf }{ w } $ \n\\[\n\\begin{gathered}\n  (Tf,g) = \\int_a^b (Tf)(t) g(t) w(t) dt = \\int_a^b \\frac{ (pf')'(t) + q(t)f(t) }{w(t) } g(t) w(t) dt = \\int_a^b ((pf')'+qf )g \\\\\n  \\int_a^b (pf')'g = \\left. (pf')g \\right|_a^b - \\int_a^b (pf')g' = - \\int_a^b (pf')g' \\\\\n  \\quad \\\\ \n  \\text{ since $f,g$ satisfy } \\begin{aligned} p(a) f(a) & = 0 \\\\\n    p(b) f(b) & = 0 \\end{aligned} \\\\\n  \\quad \\\\\n  \\int_a^b (pf')g' = \\left. pg' f \\right|_a^b - \\int_a^b (pg')' f = 0 - \\int_a^b (pg')'f \\\\\n\\Longrightarrow (Tf,g) = \\int_a^b (pg')'f + qfg = \\int_a^b wf \\frac{ ((pg')' +qg )}{w} = (f,Tg)\n\\end{gathered}\n\\]\n\\exercisehead{9} Let $V$ be a subspace of a complex Euclidean space $E$.  \\\\\nLet $T: V \\to E$ be a linear transformation and define a scalar-valued function $Q$ on $V$ as follows: \n\\[\nQ(x) = (T(x),x) \\quad \\, \\forall \\, x \\in V\n\\]\n\\begin{enumerate}\n\\item $T$ Hermitian.  \n\\[\n(Tx,x) = (x,Tx) = \\overline{ (Tx,x)} = \\overline{Q(x)} = Q(x) \\Longrightarrow Q(x) \\in \\mathbb{R}\n\\]\n\\item \n\\[\n(Tx,x) = - (x,Tx) = - \\overline{(Tx,x)} = - \\overline{Q(x)} = Q(x) \\Longrightarrow Q(x) \\text{ pure imaginary }\n\\]\n\\item \n\\[\n\\begin{aligned}\n  Q(tx) & = (T(tx),tx) = (tTx,tx) \\quad \\, \\text{(since $T$ is linear)} \\\\\n  Q(tx) & = t(Tx,tx) = t\\overline{(tx,Tx)} = t\\overline{t} (Tx,x) = t\\overline{t}Q(x)\n\\end{aligned}\n\\]\n\\item \\[\n\\begin{gathered}\n  \\begin{aligned} Q(x+y) & = (T(x+y),x+y) = (Tx+Ty,x+y) = (Tx,x+y) + (Ty,x+y) = \\\\\n    & = \\overline{(x+y,Tx)} + \\overline{(x+y,Ty)} = \\overline{(x,Tx)} + \\overline{(y,Tx)} + \\overline{(x,Ty)} + \\overline{(y,Ty)} = \\\\\n    & = (Tx,x) + (Tx,y) + (Ty,x) + (Ty,y) = Q(x) + Q(y) + (T(x),y) + (T(y),x) \n\\end{aligned} \\\\\n  \\begin{aligned}\nQ(x+ty)  = Q(x) + Q(ty) + (T(x),ty) +(T(ty),x) = Q(x) + t\\overline{t}Q(y) + \\overline{t}(T(x),y) + t(T(y),x)\n\\end{aligned}\n\\end{gathered}\n\\]\n\\item Suppose $T(x) = y \\neq 0$ for some $x \\in V$, \\, $y \\in E$, \\, $x \\neq 0$ \n\\[\n(T(x),x) = (y,x) = 0 \n\\]\n$y\\neq x$, otherwise $(x,x) = 0$; \\, $x = 0$.  Contradiction.  Done.  \n\\[\n\\begin{gathered}\n  \\begin{aligned}\n    Q(ax+by) & = (T(ax+by),ax+by) = |a|^2(T(x),x) + \\overline{b}a(T(x),y) + b\\overline{a}(T(y),x) + |b|^2 (T(y),y) \\\\ & = a\\overline{b}(T(x),y) + b\\overline{a}(T(y),x) = 0 \\end{aligned} \\\\\n  \\begin{aligned}\n     \\text{ Let } &  a = 1, \\, b = -1 \\\\\n     & -(T(x),y) = (T(y),x)  = (y,y) > 0 \\\\\n     \\text{ Let } & a\\overline{b} = i \\\\\n     & (T(x),y) = (T(y),x) = (y,y) > 0 \n  \\end{aligned}\n\\end{gathered}\n\\]\nContradiction.  Thus $y=0$.  \n\\item \\[\n\\begin{gathered}\n  Q(x+ty) = Q(x) + t\\overline{t}Q(y) + \\overline{t}(T(x),y) + t(T(y),x) \\\\\n  Q \\in \\mathbb{R} \\Longrightarrow  \\overline{Q(x+ty)} = Q(x+ty) \\Longrightarrow t(y,T(x)) + \\overline{t} (x,T(y)) = \\overline{t} (T(x),y) + t(T(y),x) \\\\\n  \\Longrightarrow t((y,T(x)) - (T(y),x)) + \\overline{t} ((x,T(y)) - (T(x),y)) = 0  \\\\\n\\quad \\\\\n\\text{ Suppose $t = a+bi$, $a,b$ arbitrary } \\\\\n\\Longrightarrow \\begin{aligned} \n  (y,T(x)) - (T(y),x) + ((x,T(y))- (T(x),y)) &= 0 \\\\ \n  (y,T(x)) - (T(y),x) - ((x,T(y))- (T(x),y)) &= 0 \\\\\n\\end{aligned} \\quad \\, \\Longrightarrow (y,T(x)) - (T(y),x) = 0 \\text{ so $T$ is Hermitian.}\n\\end{gathered}\n\\]\n\\end{enumerate}\n\n\\exercisehead{10} Legendre polynomials: \n\\[\nP_n(t) = \\frac{1}{2^n n!} f_n^{(n)}(t) \\text{ where } f_n(t) = (t^2-1)^n \n\\]\n\\begin{enumerate}\n\\item \\[\n(t^2-1)f_n'(t) = (t^2 -1)(n)(t^2-1)^{n-1}(2t) = 2nt(t^2-1)^n = 2ntf_n(t)\n\\]\n\\item Leibniz's formula.  If $h(x) = f(x)g(x)$, prove that the $n$th derivative of $n$ is given by the formula.\n\\[\nh^{(n)}(x) = \\sum_{k=0}^n \\binom{n}{k} f^{(k)}(x) g^{(n-k)}(x)\n\\]\nso then\n\\[\n\\begin{gathered}\n  \\begin{aligned} \n    ((t^2-1)f_n'(t))^{(n+1)} & = \\sum_{k=0}^{n+1} \\binom{n+1}{k} (t^2-1)^{(k)} (f_n'(t))^{(n+1-k)} = \\\\\n    & = (t^2-1)f_n^{(n+2)}(t) + (n+1)2t f_n^{(n+1)}(t) + \\frac{(n+1)n}{2} 2 f_n^{(n)}(t) \n  \\end{aligned} \\quad \\quad \\quad \\, \\begin{aligned} (t^2-1)' &= 2t \\\\ (t^2-1)'' & = 2 \\\\ (t^2-1)'' & = 0 \\end{aligned} \\\\\n  \\quad \\\\ \n  (2ntf_n(t))^{(n+1)} = (2n)(t(f_n(t))^{(n+1)} + (n+1)(f_n(t))^{(n)}) \\\\\n  \\Longrightarrow (t^2-1)f_n^{(n+2)}(t) + 2t (n+1)f_n^{(n+1)}(t) + (n+1)nf_n^{(n)}(t) = (2n) (tf_n^{(n+1)}(t) + (n+1)(f_n(t))^{(n)})\n\\end{gathered}\n\\]\n\\item $P_n(t) = \\frac{1}{2^n n!}f_n^{(n)}(t) $ \n\\[\n\\begin{gathered}\n  \\Longrightarrow (t^2-1)P_n'' + 2t(n+1)P_n' + (n+1)nP_n = (2n)(tP_n' + (n+1)P_n) \\\\\n  \\Longrightarrow (t^2-1)P_n'' + 2tP_n' - (n+1)nP_n = 0 \\text{ or } \\boxed{ ((t^2-1)P_n')' = n(n+1)P_n }\n\\end{gathered}\n\\]\n\\end{enumerate}\n\n%-----------------------------------%-----------------------------------%-----------------------------------\n\\section*{ 5.11 Exercises - Existence of an orthonormal set of eigenvectors for Hermitian and skew-Hermitian operators acting on finite-dimensional spaces; Matrix representations for Hermitian and skew-Hermitian operators;  Hermitian and skew-Hermitian matrices.  The adjoint of a matrix;  Diagonalization of a Hermitian or skew-Hermitian matrix; Unitary matrices.  Orthogonal matrices }\n%-----------------------------------%-----------------------------------%-----------------------------------\n\n\\exercisehead{1}\\begin{enumerate}\n\\item $\\left[ \\begin{matrix} 0 & 1 & 2 \\\\ 1 & 0 & 3 \\\\ 2 & 3 & 4 \\end{matrix} \\right]$.  Symmetric.  Hermitian.  \n\\item $\\left[ \\begin{matrix} 0 & i & 2 \\\\ i & 0 & 3 \\\\ -2 & -3 & 4i \\end{matrix} \\right]$.  Skew-Hermitian.  \n\\item $\\left[ \\begin{matrix} 0 & i & 2 \\\\ -i & 0 & 3 \\\\ -2 & -3 & 0 \\end{matrix} \\right]$.  Skew-symmetric.\n\\item $\\left[ \\begin{matrix} 0 & 1 & 2 \\\\ -1 & 0 & 3 \\\\ -2 & -3 & 0 \\end{matrix} \\right]$.  Skew-Hermitian.  Skew-symmetric.  \n\\end{enumerate}\n\n\\exercisehead{2} \n\\begin{enumerate}\n\\item \\[\n  \\left[ \\begin{matrix} \\cos{\\theta} & - \\sin{\\theta} \\\\ \\sin{\\theta} & \\cos{\\theta} \\end{matrix} \\right]   \\left[ \\begin{matrix} \\cos{\\theta} &  \\sin{\\theta} \\\\ -\\sin{\\theta} & \\cos{\\theta} \\end{matrix} \\right] = \\left[ \\begin{matrix} 1 & 0 \\\\ 0 & 1 \\end{matrix} \\right] \n\\]\n\\item \\[   \\left[ \\begin{matrix} \\cos{\\theta} & - \\sin{\\theta} \\\\ \\sin{\\theta} & \\cos{\\theta} \\end{matrix} \\right] \\left[ \\begin{matrix} r \\cos{\\alpha} \\\\ r\\sin{\\alpha} \\end{matrix} \\right] = \\left[ \\begin{matrix} r \\cos{\\alpha} \\cos{\\theta} - r \\sin{\\alpha} \\sin{\\theta} \\\\ r \\cos{\\alpha} \\sin{\\theta} + r \\sin{\\alpha} \\cos{\\theta} \\end{matrix} \\right] = r \\left[ \\begin{matrix} \\cos{ (\\alpha + \\theta) } \\\\ \\sin{ (\\alpha + \\theta) } \\end{matrix} \\right] \n\\]\n\\end{enumerate}\n\n\\exercisehead{3} \n\\begin{enumerate}\n\\item $\\left[ \\begin{matrix} 1 & 0 & 0 \\\\ 0 & 1 & 0 \\\\ 0 & 0 & -1 \\end{matrix} \\right]$ (reflection in the $xy$-plane).  \n  \\[\n  \\left[ \\begin{matrix} 1 & & \\\\ & 1 & \\\\ & & -1 \\end{matrix} \\right] \\left[ \\begin{matrix} 1 & & \\\\ & 1 & \\\\ & & - 1 \\end{matrix} \\right] = \\left[ \\begin{matrix} 1 & & \\\\ & 1 & \\\\ & & 1 \\end{matrix} \\right] \\quad \\quad \\, \n  \\begin{aligned} \n    & \\left[ \\begin{matrix} 1 &  & \\\\ & 1 & \\\\ & & -1 \\end{matrix} \\right] \\left[ \\begin{matrix} 1 \\\\ 0 \\\\ 0 \\end{matrix} \\right] = \\left[ \\begin{matrix} 1 \\\\ 0 \\\\ 0 \\end{matrix} \\right]  \\\\ \n    & \\left[ \\begin{matrix} 1 &  & \\\\ & 1 & \\\\ & & -1 \\end{matrix} \\right] \\left[ \\begin{matrix} 0 \\\\ 1 \\\\ 0 \\end{matrix} \\right] = \\left[ \\begin{matrix} 0 \\\\ 1 \\\\ 0 \\end{matrix} \\right] \\\\ \n    & \\left[ \\begin{matrix} 1 &  & \\\\ & 1 & \\\\ & & -1 \\end{matrix} \\right] \\left[ \\begin{matrix} 0 \\\\ 0 \\\\ 1 \\end{matrix} \\right] = \\left[ \\begin{matrix} 0 \\\\ 0 \\\\ -1 \\end{matrix} \\right] \n    \\end{aligned} \n\\]\n  \\item $\\left[ \\begin{matrix} 1 & 0 & 0 \\\\ 0 & -1 & 0 \\\\ 0 & 0 & -1 \\end{matrix} \\right]$ (reflection through the $x$-plane).  \n    \\[\n    \\left[ \\begin{matrix} 1 & & \\\\ & -1 & \\\\ & & -1 \\end{matrix} \\right] \\left[ \\begin{matrix} 1 & & \\\\ & -1 & \\\\ & & - 1 \\end{matrix} \\right] = \\left[ \\begin{matrix} 1 & & \\\\ & 1 & \\\\ & & 1 \\end{matrix} \\right] \\quad \\quad \\, \n    \\begin{aligned} \n      & \\left[ \\begin{matrix} 1 &  & \\\\ & -1 & \\\\ & & -1 \\end{matrix} \\right] \\left[ \\begin{matrix} 1 \\\\ 0 \\\\ 0 \\end{matrix} \\right] = \\left[ \\begin{matrix} 1 \\\\ 0 \\\\ 0 \\end{matrix} \\right]  \\\\ & \\left[ \\begin{matrix} 1 &  & \\\\ & -1 & \\\\ & & -1 \\end{matrix} \\right] \\left[ \\begin{matrix} 0 \\\\ 1 \\\\ 0 \\end{matrix} \\right] = -\\left[ \\begin{matrix} 0 \\\\ 1 \\\\ 0 \\end{matrix} \\right] \\\\ \n      & \\left[ \\begin{matrix} 1 &  & \\\\ & -1 & \\\\ & & -1 \\end{matrix} \\right] \\left[ \\begin{matrix} 0 \\\\ 0 \\\\ 1 \\end{matrix} \\right] = \\left[ \\begin{matrix} 0 \\\\ 0 \\\\ -1 \\end{matrix} \\right] \n\\end{aligned}\n\\]\n\\item $\\left[ \\begin{matrix} -1 & 0 & 0 \\\\ 0 & -1 & 0 \\\\ 0 & 0 & -1 \\end{matrix} \\right]$ (reflection through the origin).  \n  \\[\n  \\left[ \\begin{matrix} -1 & & \\\\ & -1 & \\\\ & & -1 \\end{matrix} \\right] \\left[ \\begin{matrix} -1 & & \\\\ & -1 & \\\\ & & - 1 \\end{matrix} \\right] = \\left[ \\begin{matrix} 1 & & \\\\ & 1 & \\\\ & & 1 \\end{matrix} \\right] \\quad \\quad \\, \\left[ \\begin{matrix} -1 & & \\\\ & -1 & \\\\ & & -1 \\end{matrix} \\right] i,j,k = -i,j,k)\n\\]\n\\item $\\left[ \\begin{matrix} 1 & 0 & 0 \\\\ 0 & \\cos{\\theta} & -\\sin{\\theta} \\\\ 0 & \\sin{\\theta} & \\cos{\\theta} \\end{matrix} \\right]$ (rotation about the $x$-axis).  \n\\[\n\\begin{gathered}\n  \\left[ \\begin{matrix} 1 & 0 & 0 \\\\ 0 & \\cos{\\theta} & - \\sin{\\theta} \\\\ 0 & \\sin{\\theta} & \\cos{\\theta} \\end{matrix} \\right] \\left[ \\begin{matrix} 1 & 0 & 0 \\\\ 0 & \\cos{\\theta} & + \\sin{\\theta} \\\\ 0 & -\\sin{ \\theta} & \\cos{\\theta} \\end{matrix} \\right] = \\left[ \\begin{matrix} 1 & 0 & 0 \\\\  0 & 1 & 0 \\\\ 0 & 0 & 1 \\end{matrix} \\right] \\\\\n  \\begin{aligned}\n    & \\left[ \\begin{matrix} 1 & 0 & 0 \\\\ 0 & \\cos{\\theta} & - \\sin{\\theta} \\\\ 0 & \\sin{\\theta} & \\cos{\\theta} \\end{matrix} \\right] \\left[ \\begin{matrix} 1 \\\\ 0 \\\\ 0 \\end{matrix} \\right] = \\left[ \\begin{matrix} 1 \\\\ 0 \\\\ 0 \\end{matrix} \\right] \\\\\n    & \\left[ \\begin{matrix} 1 & 0 & 0 \\\\ 0 & \\cos{\\theta} & - \\sin{\\theta} \\\\ 0 & \\sin{\\theta} & \\cos{\\theta} \\end{matrix} \\right] \\left[ \\begin{matrix} 0 \\\\ 1 \\\\ 0 \\end{matrix} \\right] = \\left[ \\begin{matrix} 0 \\\\ \\cos{\\theta} \\\\ \\sin{\\theta} \\end{matrix} \\right] \\\\ \n    & \\left[ \\begin{matrix} 1 & 0 & 0 \\\\ 0 & \\cos{\\theta} & - \\sin{\\theta} \\\\ 0 & \\sin{\\theta} & \\cos{\\theta} \\end{matrix} \\right] \\left[ \\begin{matrix} 0 \\\\ 0 \\\\ 1 \\end{matrix} \\right] = \\left[ \\begin{matrix} 0 \\\\ -\\sin{\\theta} \\\\ \\cos{\\theta} \\end{matrix} \\right]\n  \\end{aligned}\n\\end{gathered}\n\\]\n\\item $\\left[ \\begin{matrix} -1 & 0 & 0 \\\\ 0 & \\cos{\\theta} & - \\sin{\\theta} \\\\ 0 & \\sin{\\theta} & \\cos{\\theta} \\end{matrix} \\right]$ (rotation about $x$-axis followed by reflection in the $yz$-plane).  \n\\[\n\\begin{gathered}\n  \\left[ \\begin{matrix} -1 & 0 & 0 \\\\ 0 & \\cos{\\theta} & - \\sin{\\theta} \\\\ 0 & \\sin{\\theta} & \\cos{\\theta} \\end{matrix} \\right]\\left[ \\begin{matrix} -1 & 0 & 0 \\\\ 0 & \\cos{\\theta} & \\sin{\\theta} \\\\ 0 & -\\sin{\\theta} & \\cos{\\theta} \\end{matrix} \\right] = \\left[ \\begin{matrix} 1 & & \\\\ & 1 & \\\\ & & 1 \\end{matrix} \\right]\n  \\left[ \\begin{matrix} -1 & & \\\\ & 1 & \\\\ & & 1 \\end{matrix} \\right]\\left[ \\begin{matrix} 1 & & \\\\ & c_{\\theta} & -s_{\\theta} \\\\ & s_{\\theta} & c_{\\theta} \\end{matrix} \\right] = \\left[ \\begin{matrix} -1 & 0 & 0 \\\\ 0 & \\cos{\\theta} & - \\sin{\\theta} \\\\ 0 & \\sin{\\theta} & \\cos{\\theta} \\end{matrix} \\right] = \\\\ = \\text{(reflection in the $yz$-plane)}\\text{(rotation about $x$-axis)}\n\\end{gathered}\n\\]\n\\end{enumerate}\n\n\\exercisehead{4} A real orthogonal matrix $A$ is called \\emph{proper} if $det{A} =1$, and \\emph{improper} if $det{A} =-1$.  \n\\begin{enumerate}\n\\item \\[\n\\begin{gathered}\n  \\left[ \\begin{matrix} a & b \\\\ c & d \\end{matrix} \\right]  \\left[ \\begin{matrix} a & c \\\\ b & d \\end{matrix} \\right] = \\left[ \\begin{matrix}a^2 + b^2 & ac + bd \\\\ ac+ bd & c^2 + d^2 \\end{matrix} \\right] \\Longrightarrow \\begin{aligned} ac + bd & = 0 \\\\ a^2 + b^2 & =1 \\\\ ad-bc & =1 \\end{aligned} \\\\\n  \\quad \\\\\n\\Longrightarrow  \\cos^2{\\theta} \\left( \\frac{-c}{\\sin{\\theta}} \\right) - \\sin{\\theta} c = 1 \\quad \\, \\Longrightarrow \\begin{aligned} a & = \\cos{\\theta} \\\\ b & = \\sin{\\theta} \\\\ c & = -\\sin{\\theta} \\\\ d & = \\cos{\\theta} \\end{aligned}\n\\end{gathered}\n\\]\n\\item \\[\n\\begin{aligned}\n  \\left[ \\begin{matrix} 1 & \\\\ & -1 \\end{matrix} \\right]   \\left[ \\begin{matrix} 1 & \\\\ & -1 \\end{matrix} \\right] & =   \\left[ \\begin{matrix} 1 & \\\\ & 1 \\end{matrix} \\right] \\\\ \n    \\left[ \\begin{matrix} -1 & \\\\ & 1 \\end{matrix} \\right]   \\left[ \\begin{matrix} -1 & \\\\ & 1 \\end{matrix} \\right] & =   \\left[ \\begin{matrix} 1 & \\\\ & 1 \\end{matrix} \\right] \\\\ \n\\end{aligned} \\quad \\quad \\, \\begin{aligned}\n  & det{ \\left[ \\begin{matrix} 1 & 0 \\\\ 0 & -1 \\end{matrix} \\right]} = -1 \\\\ \n  &  det{ \\left[ \\begin{matrix} -1 & 0 \\\\ 0 & 1 \\end{matrix} \\right]} = -1 \n\\end{aligned}\n\\]\nFrom previous part, all improper $2\\times 2$ matrices: \\[\n\\left[ \\begin{matrix} \\cos{\\theta} & \\sin{\\theta} \\\\ \\sin{\\theta} & -\\cos{\\theta} \\end{matrix} \\right]\n\\]\n\\end{enumerate}\n\n\\exercisehead{13} If $A$ is a real skew-symmetric matrix, prove that both $I-A$ and $I+A$ are nonsingular and that $(I-A)(I+A)^{-1}$ is orthogonal.  \\\\\n\nNote: Notice the difference between skew-Hermitian and skew symmetric and use eignevalue eqn. and one-to-one.  \\\\\n\nSkew-Hermitian matrices must be square matrices (from how Skew-Hermitian operators, $T$, are defined as $T:V\\to V$).  \\\\\nFor skew-symmetric matrices, eigenvalues must equal zero, since $-\\lambda = \\overline{\\lambda}$\n\n\\[\n\\begin{gathered}\n  C^{-1}AC = \\Lambda =0  \\\\\n  \\begin{aligned}\n    det{(1 \\pm A)} & = det{ (C^{-1} C)}det{(1\\pm A)} = det{(C^{-1})} det{(1\\pm A)} det{C} = \\\\\n    & = det{( 1 \\pm C^{-1}AC)}= det{(1\\pm 0)} = \\boxed{ 1}\n  \\end{aligned}\n\\end{gathered}\n\\]\nTo prove orthogonality of $(I-A)(I+A)^{-1}$, use $(AB)^T = B^T A^T$ extensively.  \n\nWe know that $A$ is real skew-symmetric, so that $A = -A^T$.  \n\\[\n\\begin{aligned}\n  (1+A)(1+A)^{-1} & =1 \\\\ \n  ((1+A)(1+A)^{-1})^T = ((1+A)^{-1})^T (1+A^T)  = 1^T = 1\n\\end{aligned}\n\\]\nThus,\n\\[\n\\begin{gathered}\n  (1-A)(1+A)^{-1}((1+A)^{-1}(1-A))^T = \\\\ \n  \\begin{aligned}\n    & = (1-A)(1+A)^{-1}(1-A^T)((1+A)^{-1})^T = (1-A) \\left( (1+A)^{-1} (1+A) \\right) ((1+A)^{-1})^T = \\\\\n    & = (1-A) ((1+A)^{-1})^T = (1+A^T)((1+A)^{-1})^T = (1+A)^T((1+A)^{-1})^T = ((1+A)^{-1}(1+A))^T = 1^T = 1\n  \\end{aligned}\n\\end{gathered}\n\\]\nNote that we have $((1-A)(1+A)^{-1})^T = ((1+A)^{-1}(1-A))^T$ because if $(1+A)^{-1} = B$, \n\\[\n\\begin{gathered}\n  \\begin{aligned}\n  (1+A)B & = B + AB = 1 \\\\\n  B(1+A) & = B + BA = 1 \\quad \\, \\text{(since a left inverse is a right inverse)} \n\\end{aligned} \\quad \\quad \\, \\Longrightarrow BA = AB \\\\\n  (1-A)(1+A)^{-1} = (1-A)B = B - AB = B - BA = B(1-A) = (1+A)^{-1}(1-A)\n\\end{gathered}\n\\]\n\n\\exercisehead{14} \\begin{enumerate}\n\\item Counterexample: \\[\n\\begin{gathered}\n  \\begin{aligned}\n    A & = \\left[ \\begin{matrix} 1 & \\\\ & e^{-i 2\\pi /3} \\end{matrix} \\right]  \\\\\n    A^* & = \\left[ \\begin{matrix} 1 & \\\\ & e^{i 2\\pi /3 } \\end{matrix} \\right]\n  \\end{aligned} \\quad \\quad \\, \n  \\begin{aligned}\n    B & = \\left[ \\begin{matrix} e^{i 2\\pi/3} & \\\\ & 1 \\end{matrix} \\right] \\\\\n    B^* & = \\left[ \\begin{matrix} e^{ -i 2\\pi /3} & \\\\  & 1 \\end{matrix} \\right]\n  \\end{aligned} \n\\quad \\quad \\, \n\\begin{aligned}\n  (A+B) & =  \\left[ \\begin{matrix} 1 + e^{i 2\\pi /3} & \\\\ & 1 + e^{-i2\\pi/3} \\end{matrix} \\right] \\\\\n  A^*+B^* = (A+B)^* & = \\left[ \\begin{matrix} 1 + e^{-i 2\\pi/3} & \\\\ & 1 + e^{i2\\pi/3} \\end{matrix} \\right]\n\\end{aligned} \\\\ \n(A+B)(A^* +B^*) = \\left[ \\begin{matrix} 2 + e^{i2\\pi/3} + e^{-i2\\pi/3} & \\\\ & 2 + e^{i2\\pi/3} + e^{-i2\\pi/3} \\end{matrix} \\right]\n\\end{gathered}\n\\]\n\\item If $A$ and $B$ are unitary, then $AB$ is unitary.  \\[\n\\begin{gathered}\n  AA^* = BB^* = 1 \\\\\n  (AB)(AB)^* = (AB) B^* A^* = A(BB^*)A^* = A1A^* = 1\n\\end{gathered}\n\\]\n\\item \n\\item\n\\end{enumerate}\n\n%-----------------------------------%-----------------------------------%-----------------------------------\n\\section*{ 5.15 Exercises - Quadratic forms, Reduction of a real quadratic form to a diagonal form, Applications to analytic geometry }\n%-----------------------------------%-----------------------------------%-----------------------------------\n\n\\exercisehead{1} $4x_1^2 + 4 x_1 x_2 + x_2^2$.  $ \\left[ \\begin{matrix} 4 & 2 \\\\ 2 & 1 \\end{matrix} \\right] = A$\n\\[\n\\begin{gathered}\n  \\left| \\begin{matrix} 4-\\lambda & 2 \\\\ 2 & 1-\\lambda \\end{matrix} \\right| = 4 - 5 \\lambda + \\lambda^2 -4 = \\lambda (\\lambda -5) \\\\\n  \\xi_{\\lambda =5} = \\left[ \\begin{matrix} 2/\\sqrt{5} \\\\ 1/\\sqrt{5} \\end{matrix} \\right]; \\quad \\xi_{\\lambda=0} = \\left[ \\begin{matrix} 1/\\sqrt{5} \\\\ -2/\\sqrt{5} \\end{matrix} \\right] \\\\\n  C = \\frac{1}{ \\sqrt{5}} \\left[ \\begin{matrix} 2 & 1 \\\\ 1 & -2 \\end{matrix} \\right]\n\\end{gathered}\n\\]\n\n\\exercisehead{2} $\\quad x_1 x_2$  $\\quad \\quad A= \\left[ \\begin{matrix} 0 & 1/2 \\\\ 1/2 & 0 \\end{matrix} \\right]$.  $\\lambda = \\frac{1}{2}, -\\frac{1}{2}$.  \\medskip \\\\\n$\\quad \\xi_{\\lambda = 1/2} = \\left[ \\begin{matrix} 1/\\sqrt{2} \\\\ 1/\\sqrt{2} \\end{matrix} \\right], \\quad \\xi_{\\lambda = -1/2} = \\left[ \\begin{matrix} 1/\\sqrt{2} \\\\ -1/\\sqrt{2} \\end{matrix} \\right]$\n\n\n\\exercisehead{3} $x_1^2 + 2x_1 x_2 - x_2^2$.  $A = \\left[ \\begin{matrix} 1 & 1 \\\\ 1 & -1 \\end{matrix} \\right]$  \n\n\\exercisehead{4} $34 x_1^2 -24 x_1 x_2 + 41 x_2^2$.  $\\quad A = \\left[ \\begin{matrix} 34 & -12 \\\\ -12 & 41 \\end{matrix} \\right]$.  \\\\\n\n$\\left| \\begin{matrix} \\lambda -34 & 12 \\\\ 12 & \\lambda -41 \\end{matrix} \\right| = \\lambda^2 - 75 \\lambda + 34(41) - 144 = \\lambda^2 - 75 \\lambda +1250 $.  $\\boxed{ \\lambda = 50,25 }$  \n\\[\n\\boxed{ \n\\begin{aligned}\n  \\xi_{\\lambda =50} & = \\frac{1}{5} \\left[ \\begin{matrix} 3 \\\\ -4 \\end{matrix} \\right] \\\\\n  \\xi_{\\lambda =25} & = \\frac{1}{5} \\left[ \\begin{matrix} 4 \\\\ 3 \\end{matrix} \\right] \n\\end{aligned}\n\\quad \\quad \\quad C = \\frac{1}{5} \\left[ \\begin{matrix}\n    3 & 4 \\\\\n    -4 & 3 \n\\end{matrix} \\right] }\n\\]\n\\exercisehead{5} $x_1^2 + x_1 x_2 + x_1 x_3 + x_2 x_3$.  \n\\[\n\\begin{gathered}\n  A = \\left[ \\begin{matrix} 1 & 1 & 1 \\\\ 1 & 0 & 1 \\\\ 1 & 1 & 0 \\end{matrix} \\right] \\quad \\, \\Longrightarrow \\left| \\begin{matrix} \\lambda - 1 & -1 & -1 \\\\ -1 & \\lambda & -1 \\\\ -1 & -1 & \\lambda \\end{matrix} \\right| = \\left| \\begin{matrix} \\lambda & -1 & 0 \\\\ -1 & \\lambda - 2 & 0 \\\\ & 0 & \\lambda + 1 \\end{matrix} \\right| = (\\lambda + 1)(\\lambda^2 - 2\\lambda - 1) \\\\\n  \\begin{aligned}\n    \\xi_{\\lambda = -1} & = \\frac{1}{\\sqrt{2}} \\left[ \\begin{matrix} 0 \\\\ 1 \\\\ -1 \\end{matrix} \\right] \\\\\n    \\xi_{\\lambda = 1 \\pm \\sqrt{2}} & = \\frac{1}{2} \\left[ \\begin{matrix} \\pm \\sqrt{2} \\\\ 1 \\\\ 1 \\end{matrix} \\right] \n  \\end{aligned} \\quad \\quad \\, \n  C = \\left[ \\begin{matrix} 0 & \\sqrt{2}/2 & -\\sqrt{2}/2 \\\\ 1/\\sqrt{2} & 1/2 & 1/2 \\\\ -1/\\sqrt{2} & 1/2 & 1/2 \\end{matrix} \\right]\n\\end{gathered}\n\\]\n\n\\exercisehead{6} $2x_1^2 + 4x_1 x_3 + x_2^2 - x_3^2$\n\\[\n\\begin{gathered}\nA =   \\left[ \\begin{matrix} 2 & & 2 \\\\ & 1 & \\\\ 2 & & -1 \\end{matrix} \\right]  \\quad \\, \\Longrightarrow \\left| \\begin{matrix} \\lambda - 2 & & -2 \\\\ & \\lambda - 1 & \\\\ -2 & & \\lambda + 1 \\end{matrix} \\right| = (\\lambda -1)(\\lambda - 3)(\\lambda + 2) \\\\ \n\\quad  \\\\\n\\begin{aligned}\n  \\xi_{\\lambda = 1} = (0,1,0) \\\\\n  \\xi_{\\lambda =3} = \\frac{1}{\\sqrt{5}} (2,0,1) \\\\\n  \\xi_{\\lambda =-2} = \\frac{1}{\\sqrt{5}}(1,0,-2) \n\\end{aligned} \\quad \\, \\Longrightarrow C = \\left[ \\begin{matrix} 0 & 2/\\sqrt{5} & 1/\\sqrt{5} \\\\ 1 & 0 & 0 \\\\ 0 & 1/\\sqrt{5} & -2/\\sqrt{5} \\end{matrix} \\right]\n\\end{gathered}\n\\]\n\n\n\\exercisehead{7} $3x_1^2 + 4x_1 x_@ + 8 x_1 x_3 + 4 x_2 x_3 + 3x_3^2$.  \n\\[\n\\begin{gathered}\n  A = \\left[ \\begin{matrix} 3 & 2 & 4 \\\\ 2 & 0 & 2 \\\\ 4 & 2 & 3 \\end{matrix} \\right] \\\\\n  \\begin{aligned}\n  det{ (\\lambda I -A)} & = \\left| \\begin{matrix} \\lambda - 3 &  -2 & -4 \\\\ -2 & \\lambda & -2 \\\\ -4 & -2 & \\lambda -3 \\end{matrix} \\right|  = \\left| \\begin{matrix} \\lambda + 1 & -2 & 0 \\\\ -2 \\lambda -2 & \\lambda & -2 \\lambda -2 \\\\ 0 & -2 & \\lambda + 1 \\end{matrix} \\right| = \\left| \\begin{matrix} \\lambda +1 & -2 & 0 \\\\ -2 \\lambda -2 & \\lambda -4 & 0 \\\\ 0 & -2 & \\lambda + 1 \\end{matrix} \\right| = \\\\\n  & = (\\lambda +1)(\\lambda -4) (\\lambda +1) + 2 (\\lambda+1)(-2\\lambda -2) = (\\lambda +1)(\\lambda^2 - 3 \\lambda -4 -4 \\lambda -4 ) = (\\lambda+1)^2(\\lambda -8) \n  \\end{aligned} \n\\end{gathered}\n\\]\n\\[\n\\begin{aligned}\n  & \\left[ \\begin{matrix} 3 & 2 & 4 \\\\ 2 & 0 & 2 \\\\ 4 & 2 & 3 \\end{matrix} \\right] \\left[ \\begin{matrix} x_1 \\\\ x_2 \\\\ x_3 \\end{matrix} \\right] = -1 \\left[ \\begin{matrix} x_1 \\\\ x_2 \\\\ x_3 \\end{matrix} \\right] \\quad \\, \\Longrightarrow \\begin{aligned} 4 x_1 + 2 x_2 + 4 x_3 & = 0 \\\\ 2 x_1 + x_2 + 2x_3 & = 0 \\end{aligned} \\quad \\, \\\\\n  & \\Longrightarrow \\xi_{\\lambda =-1}  = \\frac{1}{\\sqrt{2}} \\left[ \\begin{matrix} 1 \\\\ 0 \\\\ -1 \\end{matrix} \\right] \\\\\n  & \\left[ \\begin{matrix} 3 & 2 & 4 \\\\ 2 & 0 & 2 \\\\ 4 & 2 & 3 \\end{matrix} \\right] \\left[ \\begin{matrix} x_1 \\\\ x_2 \\\\ x_3 \\end{matrix} \\right] = 9 \\left[ \\begin{matrix} x_1 \\\\ x_2 \\\\ x_3 \\end{matrix} \\right] \\quad \\, \\Longrightarrow \\left| \\begin{matrix} -5 & 2 & 4 \\\\ 2 & -8 & 2 \\\\ 4 & 2 & -5 \\end{matrix} \\right| = \\left| \\begin{matrix} 0 & -18 & 9 \\\\ 1 & -4 & 1 \\\\ 0 & 18 & -9 \\end{matrix} \\right| = \\left| \\begin{matrix} & 2 & -1 \\\\ 1 & 0 & -1 \\\\ & & \\end{matrix} \\right| \\\\\n  & \\Longrightarrow \\xi_{\\lambda = 8}  = \\frac{1}{3} \\left[ \\begin{matrix} 2 \\\\ 1 \\\\ 2 \\end{matrix} \\right] \\\\\n  & \\left| \\begin{matrix} e_1 & e_2 & e_3 \\\\ 1 & 0 & -1 \\\\ 2 & 1 & 2 \\end{matrix} \\right| = (1,-4,1) \\Longrightarrow \\xi_{\\lambda = -1} = \\frac{1}{3\\sqrt{2}} \\left[ \\begin{matrix} 1 \\\\ -4 \\\\ 1 \\end{matrix} \\right]\n\\end{aligned}\n\\]\n\\[\n\\boxed{ C = \\left[ \\begin{matrix} 1 /\\sqrt{2} & 1 /3\\sqrt{2} & 2/3 \\\\ 0 & -4/3\\sqrt{2} & 1/3 \\\\ -1/\\sqrt{2} & 1/3\\sqrt{2} & 2/3 \\end{matrix} \\right] }\n\\]\n\\exercisehead{8} $y^2 - 2xy + 2x^2 - 5 = 0$.  \n\\[\n\\begin{gathered}\n  \\left[ \\begin{matrix} 2 & -1 \\\\ -1 & 1 \\end{matrix} \\right]  \\quad \\, \\Longrightarrow \\left| \\begin{matrix} \\lambda -2 & 1 \\\\ 1 & \\lambda - 1 \\end{matrix} \\right| = \\lambda^2 -3 \\lambda + 1 = 0 \\\\\n  \\Longrightarrow \\lambda = \\frac{3 \\pm \\sqrt{5}}{2} \\\\ \n  \\quad \\, \\\\\n  \\left[ \\begin{matrix} 2 & -1 \\\\ -1 & 1 \\end{matrix} \\right] \\left[ \\begin{matrix} x_1 \\\\ x_2 \\end{matrix} \\right] = \\frac{3 \\pm \\sqrt{5}}{2} \\left[ \\begin{matrix} x_1 \\\\ x_2 \\end{matrix} \\right]  \\Longrightarrow \\begin{aligned} \\xi_{\\lambda = \\frac{ 3 + \\sqrt{5}}{2} } & = \\frac{1}{ \\sqrt{ \\frac{ 5 - \\sqrt{5}}{2} } } \\left[ \\begin{matrix} 1 \\\\ \\frac{1- \\sqrt{5}}{2} \\end{matrix} \\right]  \\\\\n    \\xi_{ \\lambda = \\frac{3- \\sqrt{3}}{2} } & = \\frac{1}{ \\sqrt{ 5 + \\sqrt{5}}{2} } \\left[ \\begin{matrix} 1 \\\\ \\frac{1 + \\sqrt{5}}{2} \\end{matrix} \\right] \\\\\n\\end{aligned} \\\\\n  \\Longrightarrow C = \\left[ \\begin{matrix} \\frac{1 }{\\sqrt{ \\frac{ 5 - \\sqrt{5}}{2} }} & \\frac{1}{ \\sqrt{ \\frac{ 5 + \\sqrt{5}}{2} } } \\\\ \\sqrt{ \\frac{2}{ 5 - \\sqrt{5}} } \\left( \\frac{1 - \\sqrt{5}}{2} \\right) & \\sqrt{\\frac{2}{5 + \\sqrt{5}} } \\frac{1+ \\sqrt{5}}{2} \\end{matrix} \\right]\n\\end{gathered}\n\\]\n\\[\n\\Longrightarrow \\frac{3+\\sqrt{5}}{2} x^2 + \\frac{ 3 - \\sqrt{5}}{2} y^2 = 5 \n\\]\nEllipse centered about $(0,0)$.  \n\n\\exercisehead{9} $y^2 - 2xy + 5x = 0$ \n\\[\n\\begin{gathered}\n  \\left[ \\begin{matrix} 0 & -1 \\\\ -1 & 1 \\end{matrix} \\right] = A \\\\\n  | \\lambda I -A | = \\left| \\begin{matrix} \\lambda & 1 \\\\ 1 & \\lambda - 1 \\end{matrix} \\right| = \\lambda^2 - \\lambda - 1  \\quad \\, \\Longrightarrow \\lambda = \\frac{ 1 \\pm \\sqrt{ 1 - 4 (1)(-1) } }{2} = \\frac{ 1 \\pm \\sqrt{5}}{2} \\\\\n  \\left[ \\begin{matrix} 0 & -1 \\\\ -1 & 1 \\end{matrix} \\right]\\left[ \\begin{matrix} x \\\\ y \\end{matrix} \\right] = \\frac{ 1 +\\sqrt{5} }{2} \\left[ \\begin{matrix} x \\\\ y \\end{matrix} \\right] \\quad \\, \\Longrightarrow \\xi_{\\lambda = \\frac{1 + \\sqrt{5}}{2}} = \\frac{1}{\\sqrt{ \\frac{ 5 + \\sqrt{5} }{2} }} \\left[ \\begin{matrix} 1 \\\\ \\frac{ 1 + \\sqrt{5}}{ -2} \\end{matrix} \\right] \\\\\n    \\left[ \\begin{matrix} 0 & -1 \\\\ -1 & 1 \\end{matrix} \\right]\\left[ \\begin{matrix} x \\\\ y \\end{matrix} \\right] = \\frac{1 - \\sqrt{5}}{2} \\left[ \\begin{matrix} x \\\\ y \\end{matrix} \\right] \\quad \\Longrightarrow \\xi_{\\lambda = \\frac{ 1 - \\sqrt{5}}{2}} = \\frac{1}{ \\sqrt{ \\frac{5 - \\sqrt{5}}{2}} } \\left[ \\begin{matrix} 1 \\\\ \\frac{-1 + \\sqrt{5} }{2} \\end{matrix} \\right]  \n\\end{gathered}\n\\]\n\\[\n\\Longrightarrow C = \\left[ \\begin{matrix} \\sqrt{ \\frac{2}{ 5+ \\sqrt{5}} } & \\sqrt{ \\frac{2}{ 5 - \\sqrt{5}} } \\\\ \\sqrt{ \\frac{2}{ 5+ \\sqrt{5}} } \\left( \\frac{ 1 + \\sqrt{ 5 } }{-2} \\right) & \\sqrt{ \\frac{ 2}{ 5- \\sqrt{5}} } \\left( \\frac{ -1 + \\sqrt{5}}{2} \\right)  \\end{matrix} \\right]\n\\]\n\\[\n\\begin{gathered}\n  y^2 - 2xy + 5x = 0 \\Longrightarrow \\\\ \n  \\frac{ 1 + \\sqrt{5}}{2} x^2 + \\frac{ 1 - \\sqrt{5}}{2} y^2 + 5 \\left( \\sqrt{ \\frac{2}{ 5 + \\sqrt{5}} } x + \\sqrt{ \\frac{2}{ 5 - \\sqrt{5}} } y \\right) = \\frac{1 + \\sqrt{5}}{2} x^2+ 5 \\sqrt{ \\frac{2}{ 5 + \\sqrt{5}}} x + \\frac{1 - \\sqrt{5}}{2} y^2 + 5 \\sqrt{ \\frac{2}{ 5 - \\sqrt{5}} } y = 0 = \\\\\n    = \\frac{ 1 + \\sqrt{5}}{2} \\left( x^2 + 5 \\sqrt{ \\frac{2}{ 5 + \\sqrt{5}}} \\left( \\frac{2}{ 1 + \\sqrt{5}} \\right) x \\right) + \\frac{ 1- \\sqrt{5}}{2} \\left( y^2 + 5 \\sqrt{ \\frac{2}{ 5- \\sqrt{5}}} \\left( \\frac{2}{ 1 - \\sqrt{5} } \\right) y \\right) = 0 \\\\ \n    \\Longrightarrow \\frac{ 1 + \\sqrt{5}}{2} \\left( x + 5 \\sqrt{ \\frac{ 2 }{5 + \\sqrt{5}}} \\left( \\frac{1}{ 1 + \\sqrt{5}} \\right) \\right)^2 + \\left( \\frac{ 1 - \\sqrt{5}}{2} \\right)\\left( y + 5 \\sqrt{ \\frac{2}{5- \\sqrt{5}} } \\left( \\frac{1}{ 1 - \\sqrt{5}} \\right) \\right)^2 = \\\\\n    = \\frac{ 1 + \\sqrt{5}}{40 + 16 \\sqrt{5}} 5^2 + \\frac{ (1- \\sqrt{5}) 5^2 }{ 40 - 16 \\sqrt{5}} \\\\\n    CY = X \\Longrightarrow C \\left[ \\begin{matrix} -5 \\sqrt{ \\frac{ 2}{ 5 + \\sqrt{5}}} \\left( \\frac{1}{ 1 + \\sqrt{5}} \\right) \\\\ -5 \\sqrt{ \\frac{ 2}{ 5- \\sqrt{5}} } \\left( \\frac{1 }{ 1 - \\sqrt{5}} \\right) \\end{matrix} \\right] = \\left[ \\begin{matrix} \\frac{5}{2} \\\\ \\frac{5}{2} \\end{matrix} \\right]\n\\end{gathered}\n\\]\nEllipse centered at $(5/2,5/2)$.  \n\n\\exercisehead{10} $y^2 -2xy + x^2 - 5x = 0$.  \n\\[\n\\begin{gathered}\n  A = \\left[ \\begin{matrix} 1 & -1 \\\\ -1 & 1 \\end{matrix} \\right] \\\\\n  \\left| \\begin{matrix} 1-\\lambda & -1 \\\\ -1 & 1-\\lambda \\end{matrix} \\right| = 1 - 2\\lambda + \\lambda^2 - 1 = \\lambda( \\lambda -2) \\Longrightarrow \\lambda = 0,2 \\\\\n  \\left[ \\begin{matrix} 1 & -1 \\\\ -1 & 1 \\end{matrix} \\right] \\left[ \\begin{matrix} x_1 \\\\ x_2 \\end{matrix} \\right] = 0 \\Longrightarrow \\xi_{\\lambda =0 } = \\frac{1}{\\sqrt{2}} \\left[ \\begin{matrix} 1 \\\\ 1 \\end{matrix} \\right] \\\\\n  \\text{ similarly, } \\xi_{\\lambda = 2 }  = \\frac{1}{\\sqrt{2} } \\left[ \\begin{matrix} 1 \\\\ -1 \\end{matrix} \\right] \\\\\n  C = \\frac{1}{\\sqrt{2} }\\left[ \\begin{matrix} 1 & 1 \\\\ 1 & -1 \\end{matrix} \\right] \\Longrightarrow 2x_2^2 - \\frac{5x_2}{\\sqrt{2}} = \\frac{5}{\\sqrt{2}} x_1 \\\\\n    \\Longrightarrow \\boxed{ \\frac{2\\sqrt{2}}{5} \\left( x_2 - \\frac{5}{ 4 \\sqrt{2}} \\right)^2 = x_1 + \\frac{5}{ 8\\sqrt{2}} } \\\\\n    C \\left[ \\begin{matrix} x_1 \\\\ x_2 \\end{matrix} \\right] = \\left[ \\begin{matrix} x \\\\ y \\end{matrix} \\right] = C \\left[ \\begin{matrix} -\\frac{5}{8\\sqrt{2}} \\\\ \\frac{5}{4 \\sqrt{2}} \\end{matrix} \\right] \\\\\n \\Longrightarrow   (x,y) = \\left( \\frac{5}{16}, \\frac{-15}{16} \\right)\n\\end{gathered}\n\\]\nThe vertex of the parabola in $(x,y)$ coordinates is $\\left( \\frac{5}{16}, \\frac{-15}{16} \\right)$.\n\n\\exercisehead{11} $5x^2 - 4xy + 2y^2 -6 = 0$.  \\medskip \\\\\n$\\left[ \\begin{matrix} 5 & -2 \\\\ -2 & 2 \\end{matrix} \\right] = A \\quad $ $\\quad \\left| \\begin{matrix} 5 - \\lambda & -2 \\\\ -2 & 2-\\lambda \\end{matrix} \\right| = 10 - 7 \\lambda + \\lambda^2 -4 = (\\lambda-6)(\\lambda -1 )$  \n\n\\[\n\\begin{aligned}\n  \\lambda = 1 & \\quad \\left[ \\begin{matrix} 4 & -2 \\\\ -2 & 1 \\end{matrix} \\right] \\left[ \\begin{matrix} x_1 \\\\ x_2 \\end{matrix} \\right] = 0 & \\xi_{\\lambda = 1 } = \\frac{1}{ \\sqrt{5} } \\left[ \\begin{matrix} 1 \\\\ 2 \\end{matrix} \\right] \\\\\n  \\lambda = 6 & \\quad \\left[ \\begin{matrix} -1 & -2 \\\\ -2 & -4 \\end{matrix} \\right] \\left[ \\begin{matrix} x_1 \\\\ x_2 \\end{matrix} \\right] = 0 & \\xi_{  \\lambda = 6 } = \\frac{1}{ \\sqrt{5}} \\left[ \\begin{matrix} 2 \\\\ -1 \\end{matrix} \\right] \n\\end{aligned}\n\\]\n\n\\[\n\\begin{gathered}\n  x_1^2 + 6x_2^2 = 6 \\\\\n  \\frac{x_1^2}{ 6 } + x_2^2  = 1 \n\\end{gathered}\n\\]\nEllipse centered at $(0,0)$ in both sets of coordinates.  \n\n\\exercisehead{12} $19 x^2 + 4xy + 16 y^2 -212 x + 104y =356$.  \n\\[\n\\begin{gathered}\n  \\left[ \\begin{matrix} 19 & 2 \\\\ 2 & 16 \\end{matrix} \\right] \\quad \\left| \\begin{matrix} 19-\\lambda & 2 \\\\ 2 & 16 -\\lambda \\end{matrix} \\right| = (\\lambda -15)(\\lambda-20) \\\\\n  \\begin{aligned}\n  \\xi_{\\lambda = 15} & = \\frac{1}{\\sqrt{5}} \\left[ \\begin{matrix} -1 \\\\ 2 \\end{matrix} \\right] \\\\ \n  \\xi_{\\lambda = 20 } & = \\frac{1}{ \\sqrt{5}} \\left[ \\begin{matrix} 2 \\\\ 1 \\end{matrix} \\right]  \n  \\end{aligned} \\\\\n  YC^{-1} = X \\text{ so } \\\\\n  [x \\quad  y ] = [ x_1 \\quad x_2 ] \\frac{1}{ \\sqrt{5}} \\left[ \\begin{matrix} -1 & 2 \\\\ 2 & 1 \\end{matrix} \\right] = \\left[ \\frac{ -x_1 + 2x_2}{ \\sqrt{5}}, \\, \\frac{2x_1 + x_2}{ \\sqrt{5}} \\right] \\\\\n  \\Longrightarrow 15 x_1^2 + 20 x_2^2 + -212 \\left( \\frac{ -x_1 + 2x_2 }{ \\sqrt{5}} \\right) + 104 \\left( \\frac{2x_1 + x_2}{ \\sqrt{5}} \\right) =356 \\\\\n  \\Longrightarrow \\frac{ \\left( x_1 + \\frac{14}{\\sqrt{5}} \\right)^2 }{ \\left( \\frac{403}{5} \\right)} + \\frac{ \\left( x_2 - \\frac{8}{\\sqrt{5}} \\right)^2 }{ \\left( \\frac{1209}{20} \\right) } =1 \n\\end{gathered}\n\\]\nSuppose we want to know what the center is in terms of the original $(x,y)$ coordinates.  Use $C$.  \n\\[\n\\begin{gathered}\nC \\left[ \\begin{matrix} x_1 \\\\ x_2 \\end{matrix} \\right] = \\frac{1}{\\sqrt{5}} \\left[ \\begin{matrix} -1 & 2 \\\\ 2  & 1 \\end{matrix} \\right] \\left[ \\begin{matrix} x_1 \\\\ x_2 \\end{matrix} \\right] = \\frac{1}{\\sqrt{5}} \\left[ \\begin{matrix} -x_1 + 2x_2 \\\\ 2x_1 + x_2 \\end{matrix} \\right] = \\\\\n\\xrightarrow{ (x_1,x_2) = \\left( \\frac{-14}{ \\sqrt{5}}, \\frac{8}{\\sqrt{5}} \\right)} = \\left[ \\begin{matrix} 6 \\\\ -4 \\end{matrix} \\right]\n\\end{gathered}\n\\]\nThus, we have an ellipse centered at $(6,-4)$.  \n\n\\exercisehead{13} $9x^2 + 24xy +16 y^2 - 52 x + 14y = 6$  \\medskip \\\\\n$\\left[ \\begin{matrix} 9 & 12 \\\\ 12 & 16 \\end{matrix} \\right]$  $\\quad \\quad \\xi_{\\lambda = 25} = \\frac{1}{5} \\left[ \\begin{matrix} 3 \\\\ 4 \\end{matrix} \\right]; \\quad \\xi_{\\lambda = 0 } = \\frac{1}{5} \\left[ \\begin{matrix} 4 \\\\ -3 \\end{matrix} \\right]$  \n\n\\[\n\\begin{gathered}\n  X = YC^{-1} \\Longrightarrow [ x \\quad y ] = [ x_1 \\quad x_2 ] \\frac{1}{5} \\left[ \\begin{matrix} 4 & -3 \\\\ 3 & 4 \\end{matrix} \\right] = \\frac{1}{5} [ 4 x_1 + 3 x_2, \\quad -3x_1 + 4 x_2 ] \\\\\n  \\Longrightarrow 25 x_2^2 - 52 \\left( \\frac{ 4x_1 + 3x_2}{ 5 } \\right) + 14 \\left( \\frac{-3x_1 + 4x_2}{ 5 } \\right) = 6 \\\\\n  \\Longrightarrow \\frac{1}{2} (x_2 - \\frac{12}{5} )^2 = \\frac{1}{5} + x_1 \n\\end{gathered}\n\\]\nTo get the center in terms of the $(x,y)$ original coordinates,\n\\[\n\\begin{gathered}\nC \\left[ \\begin{matrix} x_1 \\\\ x_2 \\end{matrix} \\right] = \\frac{1}{5} \\left[ \\begin{matrix} 4 & 3 \\\\ -3 & 4 \\end{matrix} \\right] \\left[ \\begin{matrix} x_1 \\\\ x_2 \\end{matrix} \\right] = \\frac{1}{5} \\left[ \\begin{matrix} 4 x_1 + 3 x_2 \\\\ -3 x_1 + 4 x_2 \\end{matrix} \\right] \\\\\n\\xrightarrow{ (x_1,x_2) = \\left( \\frac{-1}{5} , \\frac{2}{5} \\right)} = \\left[ \\begin{matrix} 2/25 \\\\ 11/25 \\end{matrix} \\right]\n\\end{gathered}\n\\]\nThus we have a parabola centered at $\\left( \\frac{2}{25}, \\frac{11}{25} \\right)$.  \n\n\\exercisehead{14} $5x^2 + 6xy + 5y^2 - 2 =0$  \n\\[\n\\begin{gathered}\n  A = \\left[ \\begin{matrix} 5 & 3 \\\\ 3 & 5 \\end{matrix} \\right] \\\\\n  \\lambda = 2, 8 \\quad \\quad \\xi_{\\lambda = 2 } = \\frac{1}{ \\sqrt{2}} \\left[ \\begin{matrix} 1 \\\\ -1 \\end{matrix} \\right] \\quad \\xi_{\\lambda = 8 } = \\frac{1}{ \\sqrt{2}} \\left[ \\begin{matrix} 1 \\\\ 1 \\end{matrix} \\right] \\\\\n  \\Longrightarrow  2x_1^2 + 8 x_2^2 - 2 = 0  \\\\\n  \\Longrightarrow \\boxed{ x_1^2 + 4 x_2^2 = 1 } \n\\end{gathered}\n\\]\nThus we have an ellipse centered about the origin in both coordinate axes.  \n\n\\exercisehead{15} $x^2 + 2xy + y^2 -2x + 2y + 3 =0$  \n\\[\n\\begin{gathered}\n  A = \\left[ \\begin{matrix} 1 & 1 \\\\ 1 & 1 \\end{matrix} \\right] \\quad \\quad \\left| \\begin{matrix} 1-\\lambda & 1 \\\\ 1 & 1 - \\lambda \\end{matrix} \\right| = \\lambda ( \\lambda - 2 ) \\\\\n  \\text{ Directly from the characteristic function, } \\\\\n  \\Longrightarrow \n  \\begin{aligned} \n    \\left[ \\begin{matrix} 1 & 1 \\\\ 1 & 1 \\end{matrix} \\right] \\left[ \\begin{matrix} x_1 \\\\ x_2 \\end{matrix} \\right] = 0 & \\quad \\frac{1}{\\sqrt{2}} \\left[ \\begin{matrix} 1 \\\\ -1 \\end{matrix} \\right] = \\xi_{\\lambda =0 } \\\\\n    \\left[ \\begin{matrix} -1 & 1 \\\\ 1 & -1 \\end{matrix} \\right] \\left[ \\begin{matrix} x_1 \\\\ x_2 \\end{matrix} \\right] = 0 & \\quad \\xi_{\\lambda = 2 } = \\frac{1}{\\sqrt{2}} \\left[ \\begin{matrix} 1 \\\\ 1 \\end{matrix} \\right]  \n  \\end{aligned} \\\\\n  YC^T = X = [x \\quad y ] = [x_1 \\quad x_2 ] \\frac{1}{\\sqrt{2}} \\left[ \\begin{matrix} 1 & -1 \\\\ 1 & 1 \\end{matrix} \\right] = \\begin{cases} x & = \\frac{1}{\\sqrt{2}} (x_1 + x_2 ) \\\\ y & = \\frac{1}{\\sqrt{2}} (-x_1 + x_2) \\end{cases} \\\\\n  \\Longrightarrow 2x_2^2 + -\\frac{2}{\\sqrt{2}} (x_1 + x_2 ) + \\frac{2}{\\sqrt{2}} (-x_1 +x_2 ) + 3 = 0 \\\\\n  \\boxed{ \\frac{\\sqrt{2}}{ 2 } x_2^2 + \\frac{3\\sqrt{2}}{ 4} = x_1 }\n\\end{gathered}\n\\]\n\n\\[\nC\\left[ \\begin{matrix} x_1 \\\\ x_2 \\end{matrix} \\right] = \\frac{1}{\\sqrt{2}} \\left[ \\begin{matrix} 1 & 1 \\\\ -1 & 1 \\end{matrix} \\right] \\left[ \\begin{matrix} x_1 \\\\ x_2 \\end{matrix} \\right] = \\frac{1}{\\sqrt{2}} \\left[ \\begin{matrix} x_1 + x_2 \\\\ -x_1 + x_2 \\end{matrix} \\right] = \\left[ \\begin{matrix} x \\\\ y \\end{matrix} \\right] \n\\]\nFor vertex at $\\left( \\frac{3\\sqrt{2}}{4} , 0 \\right)$ in $(x_1,x_2)$ coordinates, vertex has $\\left( \\frac{3}{4} , \\frac{-3}{4} \\right)$ as $(x,y)$ coordinates. \n\n\\exercisehead{16} $2x^2 + 4xy + 5 y^2 - 2x - y -4 = 0$.  \n\\[\n\\begin{gathered}\n  A = \\left[ \\begin{matrix} 2 & 2 \\\\ 2 & 5 \\end{matrix} \\right] \\\\\n  \\begin{aligned}\n    \\left| \\begin{matrix} 2 - \\lambda & 2 \\\\ 2 & 5 - \\lambda \\end{matrix} \\right| & = (2-\\lambda)(5- \\lambda) - 4 = 10 - 7\\lambda + \\lambda^2 -4 = 6 - 7 \\lambda + \\lambda^2 = (\\lambda - 6 )(\\lambda -1 ) \\\\\n  \\end{aligned} \\\\\n    \\xi_{\\lambda = 1 } = \\frac{1}{\\sqrt{5}} \\left[ \\begin{matrix} 2 \\\\ -1 \\end{matrix} \\right] \\quad \\xi_{\\lambda =6} = \\frac{1}{\\sqrt{5}} \\left[ \\begin{matrix} 1 \\\\ 2 \\end{matrix} \\right] \\\\\n    C = \\frac{1}{\\sqrt{5}} \\left[ \\begin{matrix} 2 & 1 \\\\ -1 & 2 \\end{matrix} \\right] \\\\\n    YC^T = X = [ 2x_1 + x_2 , \\quad -x_1 + 2x_2 ] \\frac{1}{\\sqrt{5}} \\\\\n    x_1^2 + 6x_2^2 - 2 \\left( \\frac{ 2x_1 + x_2 }{ \\sqrt{5}} \\right) - \\left( \\frac{ -x_1 + 2 x_2 }{ \\sqrt{5}} \\right) - 4 = 0 \\\\\n    \\Longrightarrow x_1^2 - \\frac{3x_1}{\\sqrt{5}} + 6 x_2^2 - \\frac{4 x_2}{\\sqrt{5}} = 4 \\Longrightarrow \\frac{ \\left( x_1 - \\frac{3}{ 2\\sqrt{5}} \\right)^2}{ \\left( \\frac{55}{12} \\right)} +  \\frac{ \\left( x_2 - \\frac{1}{3\\sqrt{5}} \\right)^2  }{ \\left( \\frac{55}{72} \\right) } = 1 \n\\end{gathered}\n\\]\n\nTo find the center of the ellipse in terms of $(x,y)$, \n\\[\n\\begin{gathered}\n  C \\left[ \\begin{matrix} x_1 \\\\ x_2 \\end{matrix} \\right] = \\frac{1}{\\sqrt{5}} \\left[ \\begin{matrix} 2 & 1 \\\\ -1 & 2 \\end{matrix} \\right] \\left[ \\begin{matrix} x_1 \\\\ x_2 \\end{matrix} \\right] = \\frac{1}{\\sqrt{5}} \\left[ \\begin{matrix} 2x_1 + x_2 \\\\ -x_1 + 2x_2 \\end{matrix} \\right] = \\left[ \\begin{matrix} x \\\\ y \\end{matrix} \\right] \\\\\n  \\xrightarrow{ (x_1,x_2) = \\left( \\frac{3}{2\\sqrt{5}}, \\frac{1}{3\\sqrt{5}} \\right) } \\, \\left( \\frac{2}{3}, \\frac{-1}{6} \\right)\n\\end{gathered}\n\\]\nFor the center of an ellipse at $\\left( \\frac{3}{2\\sqrt{5}}, \\frac{1}{3\\sqrt{5}} \\right)$ in $(x_1,x_2)$ coordinates, the center of the ellipse in $(x,y)$ coordinates is $\\left( \\frac{2}{3}, - \\frac{1}{6} \\right)$.  \n\n\n\\exercisehead{17} $x^2 + 4xy -2y^2 - 12 =0$  \\\\\n$\\left[ \\begin{matrix} 1 & 2 \\\\ 2 & -2 \\end{matrix} \\right]$  $\\left| \\begin{matrix} 1 - \\lambda & 2 \\\\ 2 & -2 -\\lambda \\end{matrix} \\right| = (1-\\lambda)(-2-\\lambda) - 4 = (\\lambda+3)(\\lambda-2)$.  \\medskip \\\\\n$\\lambda = 2,-3$  $\\quad \\quad \\xi_{\\lambda =2} = \\frac{1}{ \\sqrt{5}} \\left[ \\begin{matrix} 2 \\\\ 1 \\end{matrix} \\right] \\quad \\xi_{\\lambda =-3} = \\frac{1}{ \\sqrt{5}} \\left[ \\begin{matrix} -1 \\\\ 2 \\end{matrix} \\right]$.  \n\\[\n\\begin{gathered}\n  C = \\frac{1}{ \\sqrt{5}} \\left[ \\begin{matrix} 2 & -1 \\\\ 1 & 2 \\end{matrix} \\right] \\\\\n  YC^{-1} = X = [x \\, y ] = [ x_1 \\, x_2 ] C = \\frac{1}{ \\sqrt{5}} [ 2x_1 - x_2 , x_1 + 2x_2 ] \\\\\n  \\Longrightarrow 2x_1^2 - 3x_2^2 - 12 = 0 \\Longrightarrow \\boxed{ \\frac{x_1^2}{6} - \\frac{x_2^2}{ 4 } = 1 }\n\\end{gathered}\n\\]\n\n\\exercisehead{18} $xy + y - 2x - 2 = 0$  \n\\[\n\\begin{gathered}\n  A = \\left[ \\begin{matrix} 0  & 1/2 \\\\ 1/2 & 0 \\end{matrix} \\right] \\quad \\quad \\left| \\begin{matrix} - \\lambda & 1/2 \\\\ 1/2 & -\\lambda \\end{matrix} \\right| = \\lambda^2 - \\frac{1}{4} = 0 \\quad \\quad \\\\ \n  \\lambda = \\pm 1/2 \\quad \\quad \\xi_{\\lambda = 1/2} = \\frac{1}{ \\sqrt{2}} \\left[ \\begin{matrix} 1 \\\\ 1 \\end{matrix} \\right] \\quad \\xi_{\\lambda = -1/2} = \\frac{1}{\\sqrt{2}} \\left[ \\begin{matrix} 1 \\\\ -1 \\end{matrix} \\right]  \\\\\n    \\begin{aligned}\n      C & = \\frac{1}{\\sqrt{2}} \\left[ \\begin{matrix} 1 & 1 \\\\ 1 & -1 \\end{matrix} \\right] \\\\\n      & YC^{-1} = X = [x \\, y ] = [ x_1 \\, x_2 ] \\frac{1}{ \\sqrt{2}} \\left[ \\begin{matrix} 1 & 1 \\\\ 1 & -1 \\end{matrix} \\right] = \\left( \\frac{ x_1 + x_2 }{ \\sqrt{2} }, \\frac{ x_1 - x_2}{ \\sqrt{2}} \\right) \n    \\end{aligned} \\\\\n    \\Longrightarrow \\frac{1}{2} x_1^2 + \\frac{-1}{2} x_2^2 + \\frac{x_1 - x_2}{ \\sqrt{2} } - 2 \\left( \\frac{ x_1 + x_2}{ \\sqrt{2} }\\right) = 2 \\\\\n    \\Longrightarrow \\left( x_1 - \\frac{1}{\\sqrt{2}} \\right)^2 + - \\left( x_2 + \\frac{3}{\\sqrt{2}} \\right)^2 = 4 + \\frac{1}{2} - \\frac{9}{2} = 0 \\\\\n \\text{ Suppose two lines are the asymptotic limit of a hyperbola.  Then these lines are ``hyperbolas.''  } \\\\\n \\boxed{ \\pm \\left( x_1 - \\frac{1}{ \\sqrt{2}} \\right) = \\left( x_2 + \\frac{3}{\\sqrt{2}} \\right) }\n\\end{gathered}\n\\]\nIf we want to get what the center of this ``hyperbola'' is in terms of coordinates in the original $x,y$ axis (we already have them for $(x_1,x_2)=Y$ and that is $\\left( \\frac{1}{\\sqrt{2}}, -\\frac{3}{\\sqrt{2}} \\right)$, then apply $C$ as a transformation.  \n\\[\nC (x_1, x_2) = \\frac{1}{\\sqrt{2}} \\left[ \\begin{matrix} 1 & 1 \\\\ 1 & -1 \\end{matrix} \\right] \\frac{1}{\\sqrt{2}} \\left[ \\begin{matrix} 1 \\\\ -3 \\end{matrix} \\right] = \\left[ \\begin{matrix} -1 \\\\ 2 \\end{matrix} \\right]\n\\]\nThe center is $(-1,2)$ in $(x,y)$ coordinates.  \n\n\\exercisehead{19} $2xy - 4x + 7y + c =0$.  \n\\[\n\\begin{gathered}\n  \\left[ \\begin{matrix} 0 & 1 \\\\ 1 & 0 \\end{matrix} \\right] \\\\\n  \\left| \\begin{matrix} \\lambda & -1 \\\\ -1 & \\lambda \\end{matrix} \\right| = \\lambda^2 - 1 = 0 \\quad \\quad \\, \\begin{aligned} \\xi_{\\lambda = 1} & = \\frac{1}{\\sqrt{2}} \\left[ \\begin{matrix} 1 \\\\ 1 \\end{matrix} \\right] \\\\ \\xi_{\\lambda = -1} & = \\frac{1}{\\sqrt{2}} \\left[ \\begin{matrix} 1 \\\\ -1 \\end{matrix} \\right] \\end{aligned} \\quad \\,   \\Longrightarrow C = \\frac{1}{\\sqrt{2}} \\left[ \\begin{matrix} 1 & 1 \\\\ 1 & -1 \\end{matrix} \\right] \\\\\n  \\xrightarrow{ CY = X} \\frac{1}{\\sqrt{2}} \\left[ \\begin{matrix} 1 & 1 \\\\ 1 & -1 \\end{matrix} \\right] \\left[ \\begin{matrix} y_1 \\\\ y_2 \\end{matrix} \\right] = \\left[ \\begin{matrix} x_1 \\\\ x_2 \\end{matrix} \\right] = \\left( \\begin{matrix} \\frac{1}{\\sqrt{2}} (y_1 + y_2) \\\\ \\frac{1}{\\sqrt{2}} (y_1 - y_2) \\end{matrix} \\right) \\\\ \nx^2 + - y^2 - 4 \\left( \\frac{1}{\\sqrt{2}} (x+y)\\right) + 7 \\frac{1}{\\sqrt{2}} (x-y) + c = x^2 + \\frac{3}{\\sqrt{2}} x + - y^2 - \\frac{11}{\\sqrt{2}} y + c = 0 \\\\\n\\left( x+ \\frac{3}{2 \\sqrt{2}} \\right)^2 - \\left( y + \\frac{11}{2 \\sqrt{2}} \\right)^2 + c =0 \\quad \\Longrightarrow \\boxed{ c = -14 }\n\\end{gathered}\n\\]\n\n\\exercisehead{20} Note that \n\\[\nax^2 +bxy +cy^2 = 1 = X AX^T \\text{ where} A = \\left[ \\begin{matrix} a & b/2 \\\\ b/2 & c \\end{matrix} \\right], \\quad X = \\left[ \\begin{matrix} x & y \\end{matrix} \\right]\n\\]\n$A$ symmetric, by theorem, $A$ can be diagonalized into its eigenvalues.  By thm., $XAX^T = Y\\Lambda Y^T$ where $Y$ is an orthonormal coordinate transformation.  \n\\[\n|\\lambda -A | = (\\lambda - a)(\\lambda - c) - \\frac{b^2}{4} = (\\lambda - \\lambda_+)(\\lambda - \\lambda_-)\n\\]\nSo $\\lambda_+ \\lambda_- = ac - \\frac{b^2}{4}$ (this had been the smart way to see this: you can do algebra to get)\n\\[\n\\lambda_{\\pm} = \\frac{ (a+c) \\pm \\sqrt{ (a-c)^2 + b^2 }}{2} \n\\]\nThen using eigenvectors as basis,\n\\[\nax^2  + bxy + cy^2 = \\frac{ z^2}{ 1/ \\lambda_+} + \\frac{ w^2 }{ 1/\\lambda_-} = 1\n\\]\nFrom geometry, the area of an ellipse is $\\pi ab$, where $a,(b)$ is the half of semi-major (minor) axis\n\\[\n\\text{ ellipse area } = \\pi \\sqrt{ \\frac{1}{ \\lambda_+ } }\\sqrt{ \\frac{1}{ \\lambda_-} } = \\pi \\frac{1}{ \\sqrt{ ac - \\frac{b^2}{4} } } = \\frac{ 2 \\pi }{ \\sqrt{ 4ac - b^2} }\n\\]\n\n\n%-----------------------------------%-----------------------------------%-----------------------------------\n\\section*{ 5.20 Exercises - Eigenvalues of a symmetric transformation obtained as values of its quadratic form; Extremal properties of eigenvalues of a symmetric transformation; The finite-dimensional case; Unitary transformations }\n%-----------------------------------%-----------------------------------%-----------------------------------\n\n\\exercisehead{1} \\begin{enumerate}\n\\item \\[\n\\begin{gathered}\n  (T(x),T(x)) = (x,x) = |c|^2(x,x) \\\\\n  (x,x) > 0 \\text{ if } x \\neq 0, \\, \\text{ so } \\boxed{ |c|^2 = 1  }\n\\end{gathered}\n\\]\n\\item $V$ one-dim.  $T:V \\to V$.  \\\\\n  $T$ unitary, $T$ linear.  $x \\in V$; \\, $x = ae_1$; $T(x) = T(ae_1) = aT(e_1)$.  $T(e_1) \\in V$; \\, $T(e_1) = \\mu e_1$.   \\smallskip \\\\\n  $T(x) = a\\mu e_1 = \\mu x$.  Since $T$ unitary, by above $|\\mu | =1$.  If $V$ real, $\\mu$ real, so $\\mu = \\pm 1$.  \n\\end{enumerate}\n\n\\exercisehead{2} \n\\begin{enumerate}\n\\item $A$ real, orthogonal.  $AA^* = A\\overline{A}^T = AA^T = 1$.  Thus, $A$ unitary.  \\\\\n  $\\Longrightarrow$ eigenvalue $\\lambda$ of $A$ s.t. $|\\lambda| =1$.  \\\\\n  If $\\lambda \\in \\mathbb{R}$, \\, $\\lambda = \\pm 1$.  \n\\item \n\\item If $n=2s +1$ odd, suppose $\\lambda_1$ is eigenvalue of $A$.  If $\\lambda_1$ real, done.  If $\\lambda_1$ non-real, \\smallskip \\\\\n  \\quad \\quad \\, then $\\overline{\\lambda_1}$ is an eigenvalue (by previous part).  \\smallskip \\\\\n  \\quad \\quad Continue, until $n$th eigenvalue (we've already checked $s$ pairs of eigenvalues to be non-real).  If $\\lambda_n$ non-real, $\\overline{\\lambda}_n$ is an eigenvalue.  Then there are $2s+2$ eigenvalues.  But we're given that $n$ odd.  Contradiction.  Thus $\\lambda_n$ real.  \n\\end{enumerate}\n\n\\exercisehead{3}$T$ or thogonal.  Then $m(T) = A$ has at least one real eigenvalue, $|\\lambda_n| = 1$. \n\\[\n\\begin{gathered}\n\\text{Given } det{A} = 1, \\, det{A} = 1 = \\left( \\prod_{i=1}^s |\\lambda_i|^2 \\right) \\lambda_n = (1) \\lambda_n\n\\end{gathered}\n\\]\nSince suppose there are $s$ complex eigenvalues.  Then there are $s$ complex conjugate eigenvalues.  Then there are at most $n-2s = (\\text{odd}-\\text{even}) = \\text{odd}$ number of real eigenvalues.  Since $det{A} =1$, and $\\left( \\prod_{i=1}^s |\\lambda_i|^2 \\right) =1$ already ($T$ orthogonal), there can only be an even number of real eigenvalues equal to $-1$.  Then there must be at least one eigenvalue equal to $1$.  \n\n\\exercisehead{4} $A$ real, orthogonal, then $A$ unitary.  Then for eigenvalues $\\lambda$ of $A$, $|\\lambda|=1$.  Consider all complex $\\lambda$ of $A$; they come in complex conjugate pairs, and so if there are $s$ conjugate pairs, $\\prod_{i=1}^s |\\lambda_s|^2 = 1$.  \n\nConsider all real eigenvalues of $A$.  Then $\\lambda =\\pm 1$.  If $-1$ is an eigenvalue of multiplicity of $k$, then there are $k$ diagonal entries of $-1$ for diagonalized $A$.  Thus, all possible eigenvalues are considered, so $det{A} = \\prod_{i=1}^s |\\lambda_s|^2 (1)(-1)^k = 1(1)(-1)^k = (-1)^k$  \n\n\\exercisehead{5} Given that $T$ linear and norm-preserving,\n\\[\n\\begin{gathered}\n  \\begin{aligned}\n  (T(x+by),T(x+by)) & = \\| T(x) \\|^2 + b(T(y),T(x)) + \\overline{b}(T(x),T(y)) + |b|^2 \\| T(t) \\|^2 = \\| T(x+by) \\|^2 = \\\\\n    = \\| x + by \\|^2 & = \\| x\\|^2 + \\overline{b} (x,y) + b(y,x) + |b|^2 \\|y \\|^2\n  \\end{aligned} \\\\\n\\quad \\, \\\\\n\\begin{aligned}\n  \\| T(x) \\|^2 & = \\| x \\|^2  \\\\\n  \\| T(y) \\|^2 & = \\| y \\|^2\n\\end{aligned} \\quad \\, \\text{ as well } \\Longrightarrow b \\left( (T(y),T(x)) - (y,x) \\right) + \\overline{b} \\left( (T(x),T(y)) - (x,y) \\right) = 0 \n\\end{gathered}\n\\]\n$b$, $\\overline{b}$ are independent since $b=s+ti$ and $s,t$ are two arbitrary real numbers.  So $(T(x),T(y)) = (x,y)$, so $T$ unitary.  \n\n\\exercisehead{6}  $T:V \\to V$ unitary, Hermitian.  \n\\[\n\\begin{gathered}\n  (T(x),y) = (x,T(y)) \\quad \\, \\text{(Hermitian)} \\\\\n  (T^2(x),y) = (T(x),T(y)) = (x,T^2(y)) = (x,y) \\quad \\, \\Longrightarrow (T^2(x) - x, y) =0 \n\\end{gathered}\n\\]\nLet $y=x$.  \n\\[\n((T^2-I)(x),x) = Q_1(x) =0 \\quad \\, \\forall \\, x \\in V\n\\]\nThen $T^2 - I = 0$ (as previously shown for $Q_1(x) =0 \\, \\forall \\, x \\in V$), or $T^2 -I$.  \n\n\\exercisehead{7} $(e_1, \\dots, e_n), \\, (u_1, \\dots, u_n)$ are 2 orthonormal bases for Euclidean space $V$.  \\smallskip \\\\\n$e_j \\in V$ so $e_j \\sum_{k=1}^n a_{jk} u_k$.  \n\\[\n\\begin{aligned}\n  (e_i,e_j) & = (e_j,e_i) = \\left( \\sum_{l=1}^n a_{il} u_l , \\sum_{k=1}^n a_{jk} u_k \\right) = \\sum_{l=1}^n \\sum_{k=1}^n a_{il} \\overline{a}_{jk} (u_l,u_k)  = \\\\ \n    & = \\sum_{k=1}^n a_{ik} \\overline{a}_{jk}\n\\end{aligned}\n\\]\n$\\Longrightarrow \\, A$ is unitary, $T$ s.t. $m(T) = A$ is unitary (isomorphism).  \n\n\\exercisehead{8} $\\left[ \\begin{matrix} a & \\frac{1}{2}i & \\frac{1}{2} a(2i-1) \\\\ ia & \\frac{1}{2} (1+i) & \\frac{1}{2}a (1-i) \\\\ a & \\frac{-1}{2} & \\frac{1}{2} a(2-i) \\end{matrix} \\right]$  \n\\[\n\\sum_{k=1}^n a_{ki} \\overline{a}_{kj} = \\sum_{k=1}^3 a_{ki} \\overline{a}_{kj} = (e_i,e_j)\n\\]\n\\[\na^2 + ia(-ia) + a^2 = 3 a^2 = 1 \\quad \\, \\Longrightarrow a^2 = \\frac{1}{3} \n\\]\n$(a,ia,a)$, $\\left( \\frac{1}{2} i , \\frac{1}{2} (1+ i) , \\frac{-1}{2} \\right)$, $\\frac{a}{2} \\left( 2i -1, 1-i, 2- i \\right)$ are orthogonal to each other through $(x,y)$ inner product on complex Euclidean $V$.   If $a= \\pm \\sqrt{1/3}$, columsn of $A$ will be normalized.  \\smallskip \\\\\n$\\Longrightarrow A^T A = I$, so $A$ unitary.  \n\n\\exercisehead{9} $A$ skew-Hermitian, $\\Lambda = C^* AC$.  \n\\[\n\\begin{aligned}\n  det{(1 \\pm A)}  = det{(C^*C)} det{(1 \\pm A)} = det{(1 \\pm C^*AC)} = det{(1\\pm A)} = \\prod_{j=1}^n (1 \\pm \\lambda_j)\n\\end{aligned}\n\\]\nIf $\\lambda_j \\in \\mathbb{C}$, $\\lambda_j$ purely imaginary and $\\overline{\\lambda}_j$ is also an eigenvalue.  \n\\[\n(1\\pm \\lambda_j)(1 \\pm \\overline{\\lambda}_j) = 1 \\pm (\\lambda_j + \\overline{\\lambda}_j) + |\\lambda_j|^2 = 2\n\\]\nIf $\\lambda_j \\in \\mathbb{R}$, $\\lambda_j = 0$.  $1 \\pm \\lambda_j =1$\n\\[\n\\Longrightarrow det{(1\\pm A)} \\neq 0 \\text{ so } 1 \\pm A \\text{ nonsingular}\n\\]\n\nLet $B = (1+ A)^{-1}$.  Use the fact that a left inverse is also a right inverse (theorem) extensively.  \n\\[\n\\begin{aligned}\n  (1+A)B = B + AB & = 1 \\\\ \n  B(1+A) = B + BA & = 1 \n\\end{aligned} \\quad \\Longrightarrow AB = BA \\quad \\quad \\, \\begin{aligned}\n  ((1+A)B)* = B^*(1+A^*) = B^* + B^*A^* &  = 1 \\\\ \n  (B(1+A))^* = (1+A^*)B^* = B^* + A^*B^* & = 1\n\\end{aligned} \\quad \\Longrightarrow B^*A^* = A^*B^*\n\\]\nso\n\\[\nB(1-A) = B - BA = B - AB = (1-A)B\n\\]\nThus, using $A = -A^*$, since $A$ skew-Hermitian,\n\\[\n\\begin{gathered}\n  (1-A)(1+A)^{-1}((1-A)(1+A)^{-1})* = (1-A)B((B(1-A))^*) = (1-A)B(1-A^*)B^* = (1-A)B(1+A)B^* = \\\\\n  = (1-A)B^* = (1+A^*)B^* = 1\n\\end{gathered}\n\\]\n$(1-A)(1+A)^{-1}$ unitary.  \n\n\\exercisehead{10} $A$ unitary, $I+A$ nonsingular.  Let $(1+A)^{-1} = B$.  \nUsing this fact\n\\[\n\\begin{gathered}\n  B(1+A) = B(AA^* + A) = BA(1+A^*) = 1 = 1* = (1+A)(A^*B^*) \\\\\n  \\Longrightarrow A^*B^* = B^*A^*= B\n\\end{gathered}\n\\]\nThen \n\\[\n((1-A)B)^* = B^*(1-A^*) = B^* - A^* B^* = (A-1)A^*B^* = -(1-A)B^*A^* = -(1-A)B\n\\]\nThus $(1-A)B$ is skew-Hermitian.  \n\n\\exercisehead{11} $A$ Hermitian, so $A = A^*$.  Let $B = (A-i)^{-1}$\n\\[\n\\begin{gathered}\n  B(A-i) = 1= (A-i)B \\Longrightarrow AB = BA \\\\\n  (B(A-i))^* = 1 = (A^* +i )B^* = A^* B^* + i B^* = B^* A^* + i B^* \\quad \\, \\Longrightarrow A^*B^* = B^*A^*\n\\end{gathered}\n\\]\nThen\n\\[\n\\begin{gathered}\n  B(A+i)(B(A+i))^* = (A+i)B(A+i)^*B^* = (A+i)B(A-i)B^* = (A^*+i)1B^* = 1\n\\end{gathered}\n\\]\n\n\\exercisehead{12} $A$ unitary, so by theorem, there exists a complete set of orthonormal eigenvectors that form a basis for $V$, $\\{ u_1, \\dots, u_n \\}$.  \\\\\nSuppose $A$ was defined in the $\\{ e_1, \\dots, e_n \\}$ basis.  Then they are related through some matrix $C$ (most general assumption to make):\n\\[\n[ u_1 , \\dots, u_n ] = [ e_1, \\dots, e_n ]C  \\quad \\, \\Longrightarrow u_j = \\sum_{i=1}^n \\sum_{i=1}^n c_{ij} e_i\n\\]  \n\\[\n\\begin{aligned}\n  (u_j,u_k) & = \\left( \\sum_{i=1}^n c_{ij} e_i, \\sum_{l=1}^n c_{lk} e_l \\right) = \\sum_{i=1}^n \\sum_{l=1}^n c_{ij} \\overline{c}_{lk} (e_i,e_l) = \\sum_{i=1}^n c_{ij} \\overline{c}_{ik} = \\\\\n  & = \\sum_{l=1}^n (C^*)_{kl} c_{lj} = (u_k,u_j)\n\\end{aligned}\n\\]\nHence $C^*C=1$, so $C$ is unitary.  \\\\\nRecall what the entries of matrix $A$ are, evaluated from the inner product in a certain chosen basis:\n\\[\n\\begin{gathered}\n  Ae_l = \\sum_{m=1}^n a_{lm} e_m \\\\\n  (Ae_k,e_l) = \\left( \\sum_{m=1}^n a_{km} e_m, e_l \\right) = a_{kl}\n\\end{gathered}\n\\]\nThus,\n\\[\n\\begin{aligned}\n  (CAC^*)_{ij} \\sum_{k=1}^n C_{ik} (AC^*)_{kj} & = \\sum_{k=1}^n C_{ik} \\sum_{l=1}^n a_{kl} \\overline{C}_{jl} = \\sum_{k=1}^n \\sum_{l=1}^n c_{ik} a_{kl} \\overline{c}_{jl} = \\sum_{k=1}^n \\sum_{l=1}^n c_{ik} (Ae_k,e_l)\\overline{c}_{jl} = \\\\ \n  & = \\left( A\\sum_{k=1}^n c_{ik}e_k, \\sum_{l=1}^n c_{jl} e_l \\right) = \\left( Au_i \\right)\n\\end{aligned}\n\\]\n\n\\exercisehead{13} A square matrix is called \\emph{normal} if $AA^* = A^*A$.  Determine which of the following types of matrices are normal.  \n\\begin{enumerate}\n\\item Hermitian matrices.  $AA^* = A^*A$ since $A=A*$\n\\item Skew-Hermitian matrices.  $AA^* = -A^*(-A) = A^* A$\n\\item Symmetric matrices.  \n\\item Skew-symmetric matrices.  \n\\item Unitary matrices.  \n\\item\n\\end{enumerate}\n\n\\exercisehead{14} If $A$ is a normal matrix ($AA^* = A*A$) and if $U$ is a unitary matrix, prove that $U^*AU$ is normal.  \n\\[\n\\begin{aligned}\n  (U^*AU)(U^*AU)^* & = U^*AUU^*A^*U = U^*AA^*U = U^*A^*AU = U^*A^*UU^*AU = \\\\\n  & = (U^*AU)^*(U^*AU)\n\\end{aligned}\n\\]\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\\section*{ 6.21 Exercises - Linear equations of second order with analytic coefficients, The Legendre equation, The Legendre polynomials, rodrigues' formula for the Legendre polynomials }\n\n\\exercisehead{1} \n\\begin{itemize}\n\\item[a.]From (6.35) $(1-x^2)y'' - 2xy' + \\alpha (\\alpha +1) y=0$.  \\\\\nIf $\\alpha =0$, $(1-x^2)y'' - 2xy' =0$, $y'=v$, so $\\frac{v'}{v} = \\frac{2x}{1-x^2} $ \\, $\\Longrightarrow \\ln{ \\left( \\frac{v}{v_0} \\right)} = -\\ln{ ( 1 - x^2) }$ or $\\frac{v}{v_0} = \\frac{1}{1-x^2} $\n\n\\[\ny- y_0 = + v_0 \\int \\frac{1}{1-x^2} dx = +v_0 \\left( \\ln{ \\left( \\frac{x}{\\sqrt{ 1-x^2} } + \\frac{1}{\\sqrt{1- x^2} } \\right) }\\right) = \\frac{v_0}{2} \\ln{ \\left( \\frac{1+x}{1-x} \\right) }\n\\]\nWe did this integral by considering the following: $\\begin{aligned}x &= \\sin{\\theta} \\\\ dx & =\\cos{\\theta} d\\theta \\end{aligned}$.  So \n\\[\n\\int \\frac{1}{1-x^2} dx = \\int \\frac{ c(\\theta) d\\theta }{ \\cos^2{\\theta} } = \\int \\sec{\\theta} d\\theta = \\ln{ (\\tan{\\theta} + \\sec{\\theta} ) }\n\\] \nsince $(\\ln{(\\tan{\\theta} + \\sec{\\theta} ) } )' = \\left( \\frac{1}{ \\tan{\\theta} + \\sec{\\theta} } \\right) (\\sec^2{\\theta} + \\tan{\\theta} \\sec{\\theta} )$\n\nNow by Apostol's notation, \\\\\n$u_1$ is the power series solution with $a_0 =1, \\, a_1 =0$ \\\\ \n$u_2$ is the power series solution with $a_0 =0, \\, a_1 =1$ \\\\\n\nMy notation:\\\\\n$u_1$ is the power series solution with $a_0 =0, \\, a_1 =1$ \\\\ \n$u_2$ is the power series solution with $a_0 =1, \\, a_1 =0$ \\\\ \n\nSince $(1-x^2)y'' - 2xy'=0$, $1-x^2, -2x$ analytic (have power series representation).  \n\n\\[\n\\begin{aligned}\n  y & = \\sum_{n=0}^{\\infty} a_n x^n \\\\\n  y' & = \\sum_{n=1}^{\\infty} na_n x^{n-1} \\\\ \n  y'' & = \\sum_{n=2}^{\\infty} n (n-1) a_n x^{n-2} = \\sum_{n=0}^{\\infty} (n+2)(n+1)a_{n+2}x^n \n\\end{aligned}\n\\]\n\\[\n\\Longrightarrow\n\\begin{gathered}\n  2a_2 + 2(3) a_3x + \\sum_{n=2}^{\\infty} ((n+2)(n+1) a_{n+2} - n(n-1)a_n) x^n = 2 \\sum_{n=1}^{\\infty} n a_n x^n \\\\ \n  \\text{ or } 2a_2 + 2 (3a_3 - a_1) x = \\sum_{n=2}^{\\infty} ((n+2)(n+1) a_{n+2} - n(n+1)a_n) x^n = 0 \n\\end{gathered}\n\\]\nSo $a_2=0$, $a_3 = a_1/3$, $a_{n+2} = \\frac{na_n}{n+2}$.  \n\\[\na_{2m+1} = \\frac{(2m-1)a_{2m-1} }{2m+1} = \\frac{ (2m-1)}{2m+1} \\frac{2m-3}{2m-1} a_{2m-3} = \\frac{1}{2m+1} a_1 \n\\]\n\\[\n\\Longrightarrow \\boxed{ y = a_1 \\sum_{m=0}^{\\infty} \\frac{x^{2m+1}}{2m+1} }\n\\]\nIndeed, since \n\\[\n\\begin{aligned}\n  \\int \\frac{1}{1+x} & = \\ln{(1+x)} = \\int \\sum (-x)^j = \\sum \\frac{(-1)^j x^{j+1} }{ j+1} \\\\\n  \\int \\frac{1}{1-x} & = - \\ln{ (1-x)} = \\int \\sum (x^j) = \\sum \\frac{ x^{j+1}}{ j+1}\n\\end{aligned}\n\\]\nSo that\n\\[\n\\frac{1}{2} ( \\ln{(1+x)} - \\ln{(1-x)} ) = \\frac{1}{2} \\sum_{m=0}^{\\infty} \\frac{2x^{2m+1} }{ 2m+1} \n\\]\n\\item[b.] \n\\[\n\\begin{aligned}\n  u_2'  = \\frac{1}{2} \\left( \\frac{1}{1+x} + \\frac{1}{1-x} \\right) = \\frac{1}{2} \\left( \\frac{ 1 - x + 1 + x}{1-x^2} \\right) = \\frac{1}{1-x^2} \n\\end{aligned}\n\\]\n\\[\n\\begin{aligned}\n  u_2'' & = \\frac{1}{2} \\left( \\frac{-1}{ (1+x)^2} + \\frac{1}{ (1-x)^2} \\right) \\\\ \n  (1-x^2) u_2'' & = \\frac{1}{2} \\left( \\frac{-1(1-x)}{1+x} + \\frac{1+x}{1-x} \\right) = \\frac{1}{2} \\left( \\frac{ -(1-2x + x^2) + 1 + 2x + x^2  }{ 1-x^2} \\right) = \\frac{2x}{1-x^2}\n\\end{aligned}\n\\]\n\\end{itemize}\n\n\\exercisehead{2} Let $\\alpha =1$.  Then $(1-x^2)y'' - 2xy' +2y =0$.  \n\\[\n\\begin{aligned}\n  f(x) & = 1 - \\frac{x}{2} \\log{ \\frac{1+x}{1-x} } \\\\ \n  f'(x) & = - \\frac{1}{2} \\log{ \\frac{ 1 + x}{1-x} } - \\frac{x}{1-x^2} \\\\ \n  f''(x) & = \\frac{-1}{1-x^2} - \\frac{1}{1-x^2} + \\frac{ - 2x^2}{(1-x^2)^2} = \\frac{-2}{1-x^2} + \\frac{-2x^2}{(1-x^2)^2}\n\\end{aligned}\n\\]\n\\[\n\\Longrightarrow \\frac{-2}{1-x^2} + \\frac{-2x^2}{ (1-x^2)^2} + \\frac{2x^2}{1-x^2} + \\frac{ 2x^4}{ (1-x^2)^2} + \\frac{2x^2}{1-x^2} + x\\log{ \\frac{1+x}{1-x} } + \\frac{2x^2}{1-x^2} + 2 - x \\log{ \\frac{1+x}{1-x} } = 0 \n\\]\nConsider the general theory for Legendre equation: $ (1-x^2)y'' - 2xy' + \\alpha (\\alpha +1) y=0$.  Let $\\lambda = \\alpha (\\alpha +1)$.  $1-x^2,-2x,\\lambda$ analytic, so $\\exists \\, y = \\sum_{n=0}^{\\infty} a_n x^n$.  \n\\[\n\\begin{gathered}\n  \\Longrightarrow 2a_2 + 3(2) a_3 x + \\sum_{n=2}^{\\infty} ((n+2)(n+1)a_{n+2} - n(n-1) a_n) x^n + \\sum_{n=2}^{\\infty} \\lambda a_n x^n + \\lambda a_1 x + \\lambda a_0 = \\\\\n  = 2 \\sum_{n=1}^{\\infty} n a_n x^n = 2 \\sum_{n=2}^{\\infty} n a_n x^n + 2a_1 x\n\\end{gathered}\n\\]\n\\[\n\\Longrightarrow \\begin{aligned} a_2 & = \\frac{-\\lambda a_0 }{2} \\\\ a_3 & = \\frac{ (2-\\lambda) a_1}{6} \\end{aligned} \\quad \\, a_{n+2} = \\frac{ (n(n+1)- \\lambda )a_n}{ (n+2)(n+1)} = \\frac{(n-\\alpha)(n+1 + \\alpha)a_n}{(n+2)(n+1)}\n\\]\n\nIf $\\alpha =1$, $\\lambda =2$, \n\\[\na_{n+2} = \\frac{n-1}{n+1} a_n, \\quad \\, a_3 =0, \\quad a_2 = -a_0 \\Longrightarrow a_{2m} = \\frac{1}{2m-1} (-a_0)\n\\]\nSo that\n\\[\n y = -a_0 \\sum_{m=0}^{\\infty} \\frac{x^{2m}}{ 2m-1} \n\\]\nIndeed,\n\\[\n\\frac{x}{2} \\log{ \\left( \\frac{1+x}{1-x} \\right) } = \\frac{x}{2} \\sum_{m=0}^{\\infty} \\frac{ 2x^{2m+1}}{ 2m+1} = \\sum_{m=1}^{\\infty} \\frac{x^{2m}}{ 2m-1}, \n\\]\nso $f(x) = -\\sum_{m=0}^{\\infty} \\frac{x^{2m}}{2m-1}$.  \n\n\\exercisehead{3} \n\\begin{itemize}\n\\item[a.]\n\\[\n((x-a)(x-b)y')' - cy =0 = ((At + B -a)(At + B-b)y')' -cy = 0 \n\\]\nLet $x = At + B$, $c = \\alpha (\\alpha +1)$, \\, $\\frac{1}{A} = \\frac{dt}{dx}$.  \n\n\\[\n(At)^2 + 2ABt + B^2 - (At+B)(b+a) + ab = A^2 ( t^2-1)\n\\]\n\\[\n\\Longrightarrow 2AB - A(b+a) = 0 = A(2B- (b+a)) \\quad \\, \\Longrightarrow \\boxed{ B = \\frac{b+a}{2}, \\, A = \\frac{b-a}{2} }\n\\]\nsince \n\\[\n\\begin{gathered}\n  B^2 - B(b+a) + ab = -A^2 \\\\ \n  \\Longrightarrow \\frac{ (b+a)^2}{4} - \\frac{ (b+a)^2}{2} + ab = \\frac{ - (b^2 + 2ab + a^2)}{4} = ab = \\frac{ - (b^2 + -2ab+a^2) }{4} = \\frac{ -(b-a)^2}{4} = -A^2\n\\end{gathered}\n\\]\n\\item[b.] \\[\nx(x-1)y'' + (2x-1) y' - 2y = 0 = ((x^2-x)y')' - 2y = (x(x-1)y')' - 2y\n\\]\nfor $x = \\frac{t+1}{2}$\n\\[\n\\Longrightarrow ((t^2-1)y')' - 2y = 0\n\\]\n\\end{itemize}\n\n\\exercisehead{4} $y'' - 2xy' + 2\\alpha y=0$\n\\[\n\\sum_{n=0}^{\\infty} ((n+2)(n+1) a_{n+2} - 2na_n + 2\\alpha a_n)x^n \\Longrightarrow a_{n+2} = \\frac{ 2(n-\\alpha) a_n}{(n+2)(n+1)}\n\\]\nFor $n= 2m$\n\\[\n\\begin{aligned}\na_{2m} & = \\frac{ 2(2m-2-\\alpha) a_{2m-2}}{ (2m)(2m-1)} = \\frac{ -2( \\alpha - 2(m-1) )}{ (2m)(2m-1) } a_{2(m-1)} = \\\\\n& = \\frac{ (-2)^m ( \\alpha - 2(m-1))( \\alpha - 2(m-2) ) \\dots \\alpha }{ (2m)!} a_0 \n\\end{aligned}\n\\]\n\nFor $n=2m+1$\n\\[\n\\begin{aligned}\n  a_{2m+1} & = \\frac{ 2 ( 2m-1 - \\alpha) a_{2m-1} }{ (2m+1)(2m) } = \\frac{ (-2)( \\alpha - (2m-1)) a_{2m-1}}{ (2m+1)(2m) } = \\\\\n  & = \\frac{ (-2)^m ( \\alpha - (2m-1))(\\alpha - (2m-3))\\dots (\\alpha -1) a_1 }{ (2m+1)! }\n\\end{aligned}\n\\]\n\\[\n\\begin{aligned}\n  y & = u_1 + u_2 \\\\ \n  & = \\boxed{ \\sum_{m=1}^{\\infty} \\frac{ (-2)^m (\\alpha - (2m-1))(\\alpha - (2m-3)) \\dots ( \\alpha - 1)}{ (2m+1)! } x^{2m+1} + \\sum_{m=0}^{\\infty} \\frac{ (-2)^m (\\alpha - 2(m-1))(\\alpha - 2(m-2)) \\dots \\alpha}{ (2m+2)!} x^{2m} }\n\\end{aligned} \n\\]\n\n$u_1$ has $a_0=0$, $u_2$ has $a_1 =0$.  \n\nSince\n\\[\n\\begin{aligned}\nu_1(0) & = 0 \\\\\nu_1'(0) & = 1 \n\\end{aligned} \\quad \\, \\begin{aligned} u_2(0) & = 1 \\\\ u_2'(0) & = 0 \\end{aligned}\n\\]\nwhen $\\alpha \\in \\mathbb{Z}^+$, then one of these $u_1, u_2$ is a polynomial, since $a_{n+2} = \\frac{ 2(n-\\alpha) a_n }{ (n+2)(n+1) }$  \n\n\\exercisehead{5} For $xy'' + (3+x^3)y' + 3x^2 y =0$, assume an analytic expansion.  \n\\[\n\\begin{aligned}\n  y & = \\sum_{n=0}^{\\infty} a_n x^n = \\sum_{n=2}^{\\infty} a_{n-2} x^{n-2} \\\\ \n  y' & = \\sum_{n=1}^{\\infty} a_n n x^{n-1} = \\sum_{n=3}^{\\infty} a_{n-2} (n-2) x^{n-3} = \\sum_{n=0}^{\\infty} a_{n+1} ( n+1) x^n \\\\ \n  y'' & = \\sum_{n=2}^{\\infty} n (n-1) a_n x^{n-2} = \\sum_{n=1}^{\\infty} ( n+1)n a_{n+1} x^{n-1} \n\\end{aligned}\n\\]\n\n\\[\n\\begin{gathered}\n  2a_2 x + 3(2) a_3 x^2 + 3a_1 + 3a_2 ( 2) x + 3a_3 (3) x^2 + 3a_0 x^2 + \\sum_{n=3}^{\\infty} \\left( (n+1) n a_{n+1} + 3a_{n+1} (n+1) + a_{n-2} ( n-2) + 3a_{n-2} \\right) x^n = 0 \n\\end{gathered}\n\\]\n\\[\n\\Longrightarrow \\begin{gathered}\n a_1 = 0 \\\\\n8a_2 = 0 \\\\\n(15 a_3 + 3a_0) = 0 \\text{ or } a_3 = \\frac{-a}{5}\n\\end{gathered} \\quad \\quad \\, \\begin{aligned} (n+1)(n+3) a_{n+1} & = -a_{n-2} (n+1) \\\\\n  a_{n+1} & = \\frac{-a_{n-2} }{n+3}\n\\end{aligned}\n\\]\n\\[\n\\Longrightarrow a_{3j} = \\frac{-a_{3(j-1)} }{3j+2} = \\frac{ (-1)^2 a_{3(j-2) } }{ (3j+2) (3j-1) } = \\frac{ (-1)^j a_0 }{ (3j+2) (3j-1) \\dots (8)(5) }\n\\]\n\\[\n\\boxed{ y = a_0 \\lbrace 1  + \\sum_{j=1}^{\\infty} \\frac{ (-1)^j }{ (3j+2)(3j-1)\\dots (8)(5) } x^{3j} \\rbrace}\n\\]\n\n%Now for \n%\\[\n%\\begin{aligned}\n%  y & = x^{-2} \\sum_{n=0}^{\\infty} a_n x^n \\\\ \n%  y' & = -2x^{-3} \\sum_{n=0}^{\\infty} a_n x^n  + x^{-2} \\sum_{n=1}^{\\infty} n a_n x^{n-1} = -2 \\sum_{n=-3}^{\\infty} a_{n+3} x^n + \\sum_{n=-2}^{\\infty} (n+3) a_{n+3} x^n \\\\\n%  y'' & = 6x^{-4} \\sum_{n=0}^{\\infty} a_n x^n + -4 x^{-3} \\sum_{n=1}^{\\infty} na_n x^{n-1} + x^{-2} \\sum_{n=2}^{\\infty} n (n-1) a_n x^{n-2} = \\\\\n%  & = 6 \\sum_{n=-3}^{\\infty} a_{n+3} x^{n-1} - 4 \\sum_{n=-2}^{\\infty} (n+3) a_{n+3} x^{n-1} + \\sum_{n=-1}^{\\infty} (n+3)(n+2) a_{n+3} x^{n-1}\n%\\end{aligned}\n%\\]\n%Writing out the terms, I obtained\n%\\[\n%\\begin{gathered}\n%  a_0 = 0 \\\\\n%a_1 = 0 \\\\\n%a_3 + a_0 = 0 \n%\\end{gathered}\n%\\quad \\quad \\, \\begin{aligned}\n%  a_{n+3} & = \\frac{-a_n}{n+3} \\\\ \n%  a_{3j+2} & = \\frac{ -a_{3j-1} }{ 3j+2} = \\frac{ (-1)^2 a_{3(j-2) + 2} }{(3j+2)(3 (j-1) +2) } = \\frac{ (-1)^j a_2 }{ (3j+2)(3j-1) \\dots (8)(5) }\n%\\end{aligned}\n%\\]\n%\n%\\[\n%\\boxed{ y = x^{-2} a_2 \\lbrace \\sum_{j=0}^{\\infty} \\frac{ (-1)^j }{ (3j+2)(3j-1)\\dots (8)(5) }x^{3j+2} \\rbrace }\n%\\]\n\n%Essentially the same answer was obtained.  \n\nTo obtain the solution with even-powered terms, consider first possible simple pole at 0 from the form of the differential equation:\n\\[\ny'' + \\left( \\frac{3}{x} + x^2 \\right)y' + 3xy = 0 \n\\]\nThen consider the following:\n\\[\n\\begin{aligned}\n  y & = \\sum_{n=0}^{\\infty} a_n x^{n-2} = \\sum_{n=-1}^{\\infty} a_{n+1} x^{n-1} \\\\ \n  y' & = \\sum{n=-1}^{\\infty} ( n-1) a_{n+1} x^{n-2} = \\sum_{n=-4}^{\\infty} (n+2) a_{n+4} x^{n+1} \\\\ \n  y'' & = \\sum_{n=-4}^{\\infty} (n+2)(n+1) a_{n+4} x^{n+1}\n\\end{aligned}\n\\]\nThen for the first few terms,\n\\[\n\\begin{gathered}\n  (-2)(-3) a_0 x^{-4} + (-1)(-2)a_1 x^{-3} + 3(-2) a_0 x^{-4} + 3(-1)a_1 x^{-3} 3a^3 x^{-1} + (-2a_0)x^{-1} + 3a_0 x^{-1} = 0 \\\\\n  \\Longrightarrow a_1 = 0, \\quad \\, a_3 = \\frac{- a_0 }{ 3}\n\\end{gathered}\n\\]\n\\[\n\\boxed{ y = x^{-2} a_0 \\left( 1 + \\sum_{j=1}^{\\infty} \\frac{ (-1)^j }{ 3^j j! } x^{3j} \\right) }\n\\]\n\n\\exercisehead{6} $x^2 y'' + x^2 y' - ( \\alpha x + 2)y =0$.  $\\left( \\frac{ \\alpha x + 2}{x^2} \\right)$ analytic except at $x=0$.  \n\\[\n\\begin{aligned}\n  y & = \\sum_{n=0}^{\\infty} a_n x^n = \\sum_{n=1}^{\\infty} a_{n-1} x^{n-1} \\\\ \n  y' & = \\sum_{n=1}^{\\infty} n a_n x^{n-1}  = \\sum_{n=2}^{\\infty} (n-1) a_{n-1} x^{n-2} \\\\ \n  y'' & = \\sum_{n=2}^{\\infty} n (n-1) a_n x^{n-2} \n\\end{aligned}\n\\]\n\\[\n\\begin{gathered}\n  \\sum_{n=2}^{\\infty} (n(n-1) a_n + (n-1)a_{n-1} )x^n = \\sum_{n=1}^{\\infty} \\alpha a_{n-1} x^n + \\sum_{n=0}^{\\infty} 2a_n x^n  = \\\\\n  = \\sum_{n=2}^{\\infty} (\\alpha a_{n-1} + 2a_n)x^n + \\alpha a_1 x + 2a_1 x + 2a_0 \n\\end{gathered}\n\\]\n\\[\n(n-2)(n+1) a_n = (\\alpha + -n) a_{n-1} \\text{ or } a_n = \\frac{ (\\alpha + 1 - n) a_{n-1}}{ (n-2)(n+1) }\n\\]\n$\\frac{a_n}{a_{n-1}} = \\frac{ \\alpha - (n-1) }{ (n-2 )(n+1) } \\to 0$ as $n \\to \\infty$, so this power series converges $\\forall \\, x$.  \n\nAlso $a_0 = a_1 =0$.  \n\nBy recursion,\n\\[\na_n = \\frac{ (\\alpha + 1 - n )(\\alpha + 2 - n) \\dot ( \\alpha -2) }{ (n-2)! (n+1)! } (3(2)) a_2\n\\]\nThen,\n\\[\n\\begin{aligned}\n  y & = a_2 \\left( x^2 + \\sum_{n=3}^{\\infty} \\frac{ ( \\alpha + 1 - n)(\\alpha + 2 -n) \\dot (\\alpha -2) }{ (n-2)! (n+1)! } 6 x^n \\right)  = a_2 \\left( x^2 + \\sum_{n=1}^{\\infty} \\frac{ (\\alpha - n - 1) (\\alpha -n) \\dots (\\alpha -2)}{ n! (n+3)! } 6 x^{n+2} \\right) = \\\\\n  & = \\boxed{ a_2 x^2 \\left( 1 + \\sum_{n=1}^{\\infty} \\frac{ (\\alpha - n -1) (\\alpha -n) \\dots ( \\alpha -2) }{ n! ( n+3)!}  6 x^n \\right) }\n\\end{aligned}\n\\]\n\n\\exercisehead{7} Leibniz's formula for $n$th derivative of a product is the following: if $h(x) = f(x) g(x)$, then\n\\[\nh^{(n)}(x)  = \\sum_{k=0}^n \\binom{n}{k} f^{(k)}(x) g^{(n-k)}(x)\n\\]\n\\begin{itemize}\n  \\item[a.] For\n\\[\n\\begin{aligned}\n  A(x) & = \\sum_{n=0}^{\\infty} a_n (x-x_0)^n \\\\ \n  B(x) & = \\sum_{n=0}^{\\infty} b_n (x-x_0)^n \n\\end{aligned}\n\\]\nand $C(x) = A(X) B(x)$, then\n\\[\nC^{(n)}(x) = \\sum_{k=0}^n \\binom{n}{k} A^{(k)}(x) B^{(n-k)}(x)\n\\]\n  \\item[b.] Given that \n\\[\n\\begin{aligned}\n  A^{(k)}(x_0) & = k! a_k \\\\ \n  B^{(n-k)}(x_0) & = (n-k)! b_{n-k}\n\\end{aligned}\n\\]\nThen \n\\[\nC^{(n)}(x_0) = \\sum_{k=0}^n \\binom{n}{k} k! a_k (n-k)! b_{n-k} = n! \\sum_{k=0}^n a_k b_{n-k}\n\\]\n\\[\nC^{(n)}(x_0) = n! c_n \\text{ so } c_n = \\sum_{k=0}^n a-k b_{n-k}\n\\]\n\\end{itemize}\n\n\\exercisehead{8}\n\\begin{itemize}\n\\item[a.] By Rodrigues' formula, $P_n(x) = \\frac{1}{2^n n!} \\frac{d^n}{dx^n} (x^2-1)^n $.  $(x^2-1) = (x-1)(x+1)$.  By Leibniz's formula,\n\\[\n\\frac{d^n}{dx^n} (x-1)^n(x+1)^n = \\sum_{k=0}^n \\binom{n}{k} \\frac{d^k}{dx^k}(x-1)^n \\frac{d^{n-k}}{dx^{n-k}} (x+1)^n\n\\]\n\\[\nP_n(x) = \\frac{1}{2^n} (x+1)^n + \\frac{1}{2^n n!} \\sum_{k=0}^{n-1} \\frac{d^k}{dx^k}(x-1)^n \\frac{d^{n-k}}{dx^{n-k} }(x+1)^n = \\frac{ (x+1)^n}{ 2^n} + (x-1)Q_n(x)\n\\]\n$Q_n(x)$ is a polynomial.  \n\\item[b.] $P_n(1) = 1$.  $P_n(-1) = 0 + \\frac{1}{2^n n!}(-2)^n n! = (-1)^n$ where we considered when $k=0$, for $\\frac{d^n}{dx^n}(x+1)^n = n!$.  \n\\item[c.]\n\\end{itemize}\n\n\\exercisehead{9} \\begin{itemize}\n\\item[a.] Now $(1-x^2)y'' + -2xy' + \\alpha (\\alpha +1) y=0$, or $((1-x^2)y')' = -\\alpha (\\alpha +1)y$.  \n\\[\n\\begin{aligned}\n  & -m (m+1) P_m = ((1-x^2)P_m')' \\\\ \n  & -m(m+1) P_m P_n = ((1-x^2)P_m')' P_n = ((1-x^2)P_m'P_n)' - (1-x^2)P_m' P_n'\n\\end{aligned}\n\\]\n\\[\n\\begin{aligned}\n  & n(n+1)P_n P_m = -((1-x^2)P_n' P_m)' + (1-x^2)P_n' P_m' \\\\ \n  & \\Longrightarrow ((1-x^2)(P_nP_m' - P_n'P_m))' = (n(n+1)- m(m+1))P_n P_m\n\\end{aligned}\n\\]\n\\item[b.] If $n\\neq m$, $\\int_{-1}^1 P_n P_m = 0$\n\\end{itemize}\n\n\\exercisehead{10} \\begin{itemize}\n\\item[a.] $f(x) = (x^2-1)^n = (x-1)^n (x+1)^n$.  Using Leibniz's rule again,\n\\[\nf^{(n-1)} = \\sum_{k=0}^{n-1} \\frac{d^k}{dx^k} (x-1)^n \\frac{d^{n-1 +k}}{ dx^{n-1+k}} (x+1)^n\n\\]\nFor $f^{(n-1)}(1)=0$, $f^{(n-1)}(-1)=0$.  Then\n\\[\n\\int_{-1}^1 f^{(n)} f^{(n)} = \\left. f^{(n-1)}f^{(n)} \\right|_{-1}^1 - \\int_{-1}^1 f^{(n-1)} f^{(n+1)} = -\\int_{-1}^1 f^{(n-1)} f^{(n+1)}\n\\]\n\nNow\n\\[\nf^(2n)(x) = \\frac{d^{2n}}{ dx^{2n}} (x^2-1)^n = \\sum_{k=0}^{2n} \\binom{2n}{k} \\frac{d^k }{dx^k}(x-1)^n \\frac{d^{2n-k}}{ dx^{2n-k}} (x+1)^n = (2n)!\n\\]\nfor the $k=n$ term.  \n\\[\n\\int_{-1}^1 f^{(n)} f^{(n)} = \\int_{-1}^1 f^{(2n)} f^{(0)} (-1)^n = (2n)! \\int_{-1}^1 (1-x^2)^n dx = 2(2n)! \\int_0^1 (1-x^2)^n dx\n\\]\n\\item[b.] Now $P_n(x) = \\frac{1}{2^n n!} \\frac{d^n}{dx^n} ( x^2-1)^n$.  \n\\[\n\\begin{aligned}\n  \\int_{-1}^1 (P_n(x))^2 dx &= \\frac{1}{ 2^{2n} (n!)^2} \\int_{-1}^1 f^{(n)}f^{(n)} = \\frac{1}{ 2^{2n}(n!)^2} 2(2n)! \\int_0^1 (1-x^2)^n dx  = \\frac{2 (2n)! }{2^{2n} (n!)^2} \\int_0^{\\pi/2} \\sin^{2n+1}{t} dt = \\\\\n  & = \\frac{2 (2n)!}{ 2^{2n} (n!)^2} \\frac{ (2n)!!}{ (2n+1)!!} = \\frac{2(2n)! 2^n n! 2^{n+1}}{ 2^{2n}(n!)^2 (2n+2)! } (n+1)! = \\frac{ 2^2(n+1)}{(2n+2)(2n+1)} = \\\\\n  & = \\boxed{ \\frac{2}{2n+1}}\n\\end{aligned}\n\\]\n\\end{itemize}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\\section*{ 6.24 Exercises - The method of Frobenius, The Bessel equation }\n\n\\exercisehead{1} \\begin{itemize}\n\\item[(a)] Given $g(x) = x^{1/2} f(x)$, \\, $x^2 y'' + xy' + (x^2 - \\alpha^2)y=0$ that $f$ must satisfy, \\\\\n$\\begin{aligned} g' & = \\frac{1}{2} x^{-1/2} f + x^{1/2} f' \\\\ y'' & = \\frac{-1}{4} x^{-3/2} f + x^{-1/2} f' + x^{1/2} f'' \\end{aligned}$, we want $g$ to satisfy $y'' + \\left( 1 + \\frac{1- 4 \\alpha^2}{4x^2} \\right) y =0$.  \n\nNow \n\\[\n\\begin{gathered}\n  f'' + \\frac{f'}{x} + \\left( 1 - \\frac{\\alpha^2}{x^2} \\right) f = 0 \\\\\n  g'' = \\frac{-1}{4x^{-3/2}} f + x^{1/2} \\left( \\frac{ \\alpha^2}{x^2} - 1 \\right) f \\\\\n    g'' + g = x^{1/2} \\left( \\frac{\\alpha^2}{x^2} - \\frac{1}{4 x^2} \\right) f = g \\left( \\frac{4\\alpha^2 - 1 }{ 4 x^2} \\right)\n\\end{gathered}\n\\]\n\\item[(b)]\n\\item[(c)] $J_p(x) = \\left( \\frac{x}{2} \\right)^p \\sum_{n=0}^{\\infty} \\frac{(-1)^n}{n! \\Gamma(n+1+\\alpha) } \\left( \\frac{x}{2} \\right)^{2n}$.  Also, \\\\\n$\\Gamma\\left( n+1 + \\frac{1}{2} \\right) = \\left( n+\\frac{1}{2}\\right)\\left( n-1 + \\frac{1}{2} \\right) \\dots \\left( 1+ \\frac{1}{2} \\right) \\left( \\frac{1}{2} \\right) \\Gamma\\left( \\frac{1}{2} \\right)$\n\n\\[\n\\begin{aligned}\n  J_{1/2}(x) & = \\left( \\frac{2}{x} \\right)^{1/2} \\sum_{n=0}^{\\infty} \\frac{(-1)^n }{ n! (n+\\frac{1}{2}) (n-1 + \\frac{1}{2} )\\dots ( 1 + \\frac{1}{2} )( \\frac{1}{2} ) \\Gamma\\left( \\frac{1}{2} \\right) } \\left( \\frac{x}{2} \\right)^{2n+1} = \\\\\n  & = \\left( \\frac{2}{\\pi x} \\right)^{1/2} \\sum_{n=0}^{\\infty} \\frac{ (-1)^n }{ (2n+1)!}x^{2n+1} = \\left( \\frac{2}{\\pi x} \\right)^{1/2} \\sin{x}\n\\end{aligned}\n\\]\n\nNow for $\\alpha = \\frac{-1}{2}$, consider \\\\\n$\\Gamma(n+1 - 1/2) = \\Gamma\\left( n+\\frac{1}{2} \\right) = \\left( n + \\frac{1}{2} - 1 \\right) \\left( n -2 + \\frac{1}{2} \\right) \\dots \\left( 2 + \\frac{1}{2} \\right) \\left( 1 + \\frac{1}{2} \\right) \\left( \\frac{1}{2} \\right) \\Gamma\\left( \\frac{1}{2} \\right)$\n\\[\n\\begin{aligned}\n  J_{-1/2}(x) = \\left( \\frac{2}{x} \\right)^{1/2} \\sum_{n=0}^{\\infty} \\frac{(-1)^n }{ n! \\Gamma\\left( n + \\frac{1}{2} \\right) } \\left( \\frac{x}{2} \\right)^{2n} = \\left( \\frac{2}{x} \\right)^{1/2} \\sum_{n=0}^{\\infty} \\frac{ (-1)^n  x^{2n} }{ (2n)! \\Gamma(1/2)} = \\left( \\frac{2}{\\pi x} \\right)^{1/2} \\cos{x}\n\\end{aligned}\n\\]\n\\end{itemize}\n\n\n\n%-----------------------------------%-----------------------------------%-----------------------------------\n\\section*{ 8.3 Exercises - Functions from $\\mathbb{R}^n$ to $\\mathbb{R}^m$.  Scalar and vector fields, Open balls and Open sets } \n%-----------------------------------%-----------------------------------%-----------------------------------\n\n\\exercisehead{1}\nLet $f$ be a scalar field defined on a set $S$ and let $c$ be a given real number.  The set of all points $x$ in $S$ such that $f(x) = c$ is called a level set of $f$.  \\\\\n\\phantom{ Let f} See sketch.  \n\n\\exercisehead{2} Let $S$ be the set of all points $(x,y)$ in the plane satisfying the given inequalities.  \\\\\n\\phantom{Exercise head Let S } See sketch.  \n\n\\exercisehead{3} \\emph{Proofs are hard!}  I \\emph{read} the \\emph{examples at the end of Section 8.2}, particularly the example on the 2-dim. \\emph{Cartesian product}: it helps.  In fact, we'll review it right now.  \\bigskip \\\\ \n$A_1, A_2 \\subseteq \\mathbb{R}^1 $ \\\\\n\\quad \\quad $A_1 \\times A_2 = \\{ (a_1,a_2) | a_1 \\in A_1, \\, A_2 \\in A_2 \\}$ \\\\\nIf $A_1, \\, A_2$ are open subsets of $\\mathbb{R}^1$, \\\\\n\\quad \\phantom{ If } Choose any $a \\in A_1 \\times A_2$ \\medskip \\\\\n\\emph{ Want:} $a$ is an int. pt. of $A_1 \\times A_2$ \\bigskip \\\\\n\nSince \\\\\n\\phantom{ Sinc } $A_1, A_2$ open in $\\mathbb{R}^1$, $\\exists \\, B(a_1;r_1)$, $\\exists \\, B(a_2;r_2)$ \\\\\n\\phantom{ Sinc } Let $r = min\\{ r_1, r_2 \\}$ \\medskip \\\\\n\\emph{ Want:} $B(a;r) \\subseteq A_1 \\times A_2$  \\bigskip \\\\\n\nIf $(x_1,x_2) = x \\in B(a;r)$, \\\\\n\\phantom{ If } $\\| x - a \\| < r $, so $|x_1 - a_1| < r$, $|x_2 - a_2 | < r_2$, \\\\\n\\quad \\phantom{ If } then $\\begin{aligned}\n  & x_1 \\in B(a_1;r_1) \\\\\n  & x_2 \\in B(a_2; r_2) \n\\end{aligned} $ \\quad $\\Longrightarrow \\begin{aligned}\n  & x_1 \\in A_1 \\\\\n  & x_2 \\in A_2 \n\\end{aligned}$ \\bigskip \\\\\nWe then get what we want: $(x_1,x_2) \\in A_1 \\times A_2$ so that any $x \\in B(a;r)$ belongs in $S$, which means, by def., that $B(a;r) \\subseteq S$  \\\\\n\nOnward with the problem:  \\\\\n\nLet $S$ be the set of all points $(x,y,z)$ in 3-space.  \\begin{enumerate}\n\\item $z^2 - x^2 - y^2 - 1 > 0 $\n\\item $ |x| < 1, \\, |y| <1 , \\, $ and $|z| < 1$ Consider $a \\in S$\nWe must use the fact that an open rectangular box is a basic open set.  \n\nLet $a \\in S$, $a = (a_1,a_2,a_3)$ \\\\\nLet $\\rho_i = \\begin{cases} 1 - a_i & \\text{ if } a_i \\geq 0 \\\\ |-1-a_i| & \\text{ if } a_i < 0 \\end{cases}$ and $R_a = \\prod_{i=1}^3 (a_i - \\rho_i, a_i + \\rho_i)$  \\\\\n\nConsider $b \\in R_a$.  \\\\\n\nIf $a_i \\geq 0$,  \\\\\n\\quad \\, if $b_i \\geq a_i$, $b_i - a_i < 1 - a_i$ or $b_i < 1$ \\\\\n\\quad \\, if $b_i < a_i$, $\\begin{aligned} & \\text{ if } b_i > 0, & a_i - b_i > 0 \\text{ or } 1 > a_i > b_i \\\\\n  & \\text{ if } b_i < 0, & -b_i < a_i - b_i < 1 - a_i < 1 \\end{aligned}$ \\\\\n\nIf $a_i < 0$, \\\\\n\\quad \\, if $b_i > a_i$, $\\begin{aligned} & \\text{ if } b_i > 0, & b_i - a_i < 1 +  a_i \\text{ or } b_i < 1 + 2a_i < 1 \\\\\n  & \\text{ if } b_i < 0, & -b_i < -a < 1 \\, (\\text{since} |a_i|<1) \\end{aligned}$\n\\quad \\, if $b_i < a_i$, $a_i - b_i < 1+a_i$ or $-b_i < a_i -b_i < 1 + a_i <1$. \\\\\n\nThen, $\\boxed{ |b_i|<1 }$ for \\emph{each and every possible case}.  Then $R_a \\subseteq S$, so $\\forall \\, a \\in S$ is an int. pt. (since $\\forall \\, a$, $\\exists$ open rectangle $R_a$, that is completely contained in $S$).  Then $S$ is open.  \n\n%\\[\n%\\begin{gathered}\n%  \\| x - a \\|^2 = (x_1-a_1)^2 + (x_2 - a_2)^2 + (x_3 - a_3)^2 \\\\\n%  x_1^2 - 2x_1 a_1 + a_1^2 < 2 (1- x_1 a_1) < 4 \\quad \\, \\text{ (since $2 > 1 - x_1 a_1 > 0 $ ) }\n%\\end{gathered}\n%\\]\n\\item $x+y+z < 1$\n\\item $|x| \\leq 1, \\, |y| < 1$, and $|z| < 1$  \\medskip \\\\\nConsider $a_0 = (1,a_2,a_3)$, $1 > a_2,a_3 > 0$.  \\\\\n$a_0 \\in S$, but for $B(a_0,1/2)$, $(5/4,a_2,a_3) \\in B(a_0,1/2)$ and $(5/4,a_2,a_3) \\notin S$.  $\\boxed{ \\text{ So $S$ is not open. }}$   \\\\\n\nOr\\dots \\\\\n\nAn open set has every element to be interior to it (definition).  \\\\\nAn interior pt. is a pt. s.t. $\\exists$ some open basic set containing the pt. and is a subset of the set.  \\\\\n\nWe must show $\\nexists$ any open basic set for a pt. in this set.  \\\\\nSince every open rectangle contains an open ball and every open ball contains an open rectangle, we only need to consider open rectangles.   \\\\\n\nConsider $(1,y_0,z_0)\\in S$. \\\\\nConsider open rectangle containing $1$.  I claim that at best, $\\left( 1 - \\frac{1}{n}, 1 + \\frac{1}{n} \\right), \\, n\\in \\mathbb{Z}^+$, since by Archimedes property of real numbers,\n\n\\begin{theorem}[Apostol's Archimedes property of real numbers, pp. 26, Thm. 1.30, Vol. 1] If $x>0$ and if $y$ is an arbitrary real number, $\\exists \\, n\\in \\mathbb{Z}^+$ s.t. $nx > y$.  We want $i \\in (a_i, b_i)$ i.e. $a_i < 1 < b_i$\n\\end{theorem}\nConsider open interval containing $1$; $1 \\in (a_i,b_i)$.  Then $a_i < 1 < b_i$.  But $(a_i,b_i)$ always contains pts. not belonging to $S_i$: $nx <y$ (existence of $n$ \\emph{ guaranteed by Archimedes prop. of reals thm.}).  \n\\[\nnb_i > (n+1) \\Longrightarrow b_i > 1 + \\frac{1}{n} > 1\n\\]\nThen $\\nexists$ open interval containing $1$ completely contained in $S$.  $(1,y_0,z_0)$ is not an interior pt.  $S$ is not open.  \n\n\n\n%$a\\in S$.  Then $|a_{1,2,3}| < 1$.  \\medskip \\\\\n%$r^2 > 0$, so we can say $r^2 = r_1^2 + r_2^2 + r_3^2$  \\bigskip \\\\\n%Consider $|x-a_1| < r_1^2$, just one component, without loss of generality.  \n%\\[\n%|x - a_1 | > ||x|-|a_1|| = \\begin{cases} \n%  |x|-|a_1| & \\text{ if } |x| >|a_1| \\\\\n%  |a_1|-|x| & \\text{ if } |a_1| > |x| \n%\\end{cases}\n%\\]\n%If $|a_1| > |x|$, we're done, since $1 > |a_1| > |x|$ (and so we get what we want, $1 > |x|$ ). \\\\\n%If $|x| > |a_1|$, then consider $r_1 > |x-a_1| > |x| - |a_1| \\Longrightarrow r_1 + |a_1| > |x|$.  Let $r_1 = 1 - |a_1|$, which is okay, since $|a_1|<1$, so that $r_1>0$ and $r$ \\textbf{ can depend upon } $a$, \\textbf{ just not } $x$, because $x$ \\textbf{ must be completely arbitrary}. \\medskip \\\\\n%$r_1 + |a_1| = 1 - |a_1| + |a_1| =1 > |x|$ \\medskip \\\\\n%This must be true for all three components of $x \\in B(a;r)$; so we've found a $B(a;r)$ s.t. $\\forall \\, x \\in B(a;r)$, $x \\in S$, so then $B(a;r) \\subseteq S$, so then $S$ is an open set.  \n%  For $a \\in S$, consider $B(a;r)$ $\\Longrightarrow \\|x - a \\| < r$ or $(x_1 -a_1)^2 + (x_2 -a_2)^2 + (x_3 -a_3)^2 < r^2$\n%\\[\n%\\begin{gathered}\n%  |a_2|,|a_3| < 1, \\text{ so then } |x_2 -a_2| > ||x_2|-|a_2|| > \\begin{\n%\n%\n%\\end{gathered}\n%\\]\n\\item $x+y+z < 1$ and $x>0, \\, y > 0 , \\, z>0$ \\\\\n\nConsider $x \\in S$.  Then $x+y+z <1$.  \\\\\nConsider $\\prod_{j=1}^3 (x_j - \\delta_j, x_j+\\delta_j)$.  \n\\[\n\\begin{gathered}\n  \\sum_{j=1}^3 x_j + \\delta_j = \\sum_{j=1}^3 x_j + \\sum_{j=1}^3 \\delta_j \\\\\n  0 < x + y + z < 1 \\text{ so let } 1 - \\sum_{j=1}^3 (x_j) = \\epsilon(x) > 0 \\\\\n    \\text{ We can choose } \\sum_{j=1}^3 \\delta_j = \\delta \\text{ s.t. } \\epsilon(x) > \\delta > 0 \n\\end{gathered}\n\\]\nFurthermore, by Archimedes axiom, we can choose $\\delta_j >0$ s.t. $x_j - \\delta_j >0$ \\\\\n$\\Longrightarrow \\, \\forall \\, x \\in S$, we can construct an open rectangle $\\prod_{j=1}^3 (x_j-\\delta_j, x_j+ \\delta_j) = R(x)$ s.t. $R(x) \\subseteq S$.\n\\item $x^2 +4y^2 +4z^2 - 2x + 16y + 40z + 113 < 0$\n\\[\n\\begin{gathered}\n  x^2 + 4 y^2 + 4 z^2 - 2x + 16y + 40 z + 113 = (x-1)^2 -1 + 4 (y+2)^2-16 + 4(z+5)^2 - 100 + 113 = \\\\\n   = (x-1)^2 + 4(y+2)^2 +4 (z+5)^2 -4 < 0 \\quad   \\Longrightarrow \\frac{ (x-1)^2 }{2^2 } + (y+2)^2 + (z+5)^2 < 1 \n\\end{gathered}\n\\]\nThus, $S$ is, by definition, a \\textbf{basic open set}, a basic open sphere.  By theorem, \\textbf{a basic open sphere is an open set}.\n\\end{enumerate}\n\n\\exercisehead{4} \n\\begin{enumerate}\n\\item $A$ is an open set in $n$-space and $x \\in A$.  Given $A$ is open, $A - \\{ x\\} \\subset A$.  \\medskip \\\\\nConsider $a \\in A - \\{ x \\}$.  Then $a \\in A$ so, $\\exists B_a(a,r_a) \\subseteq A$.  \\\\\n\\quad \\quad \\, If $x \\notin B_a(a,r_a)$, we're done.  \\\\\n\\quad \\quad \\, If $x \\in B_a(a,r_a)$, consider $r_{ax} = \\| a- x \\|$ \\\\\n\\quad \\quad \\quad \\, $\\forall \\, x_a \\in B_a(a,r_{ax})$, $\\| x_a - a \\| < r_{ax}$ also $\\| x_a - a \\| < r_{ax} < r_a$, so $x_a \\in A$ \\\\\n$\\Longrightarrow B_a(a,r_{ax}) \\subseteq A$ and $B_a(a,r_{ax}) \\subseteq A - \\{ x \\}$ since we constructed $B_a$ s.t. $x \\notin B_a$\n\\item $A$ open.  Let $B$ have endpoints $b_1,\\, b_2$ \\medskip \\\\\n  $A-\\{ b_1 \\}$ open.  $A - \\{ b_1 \\} - \\{ b_2 \\} = A'$ open.  \\\\\n  $A' - int{B} = A-B$ open since open set minus an open set is open, since union of $2$ open sets is an open set.  \n\nWe could also directly say, since we're dealing with intervals in one-dimension, $A=(a_A, b_A)$, $B = [a_B, b_B]$.  $\\begin{aligned}\n  & b_B < b_A \\\\\n  & a_A < a_B\n\\end{aligned}$.  \\smallskip \\\\\n$B$ is a closed subinterval of $A$.  \\\\\n$A-B = (a_A,a_B) \\bigcup (b_B,b_A)$\n\\item $\\forall \\, x \\in A \\bigcup B$, $x \\in A$ or $x \\in B$.  Since $A,B$ are open, $x$ is int. to $A$, or int. to $B$. \\\\\nExplicitly, if $\\exists \\, B(x,r) \\subseteq A, \\, B$ then $B(x,r) \\subseteq A, \\, B \\subseteq A \\bigcup B$.  \\\\\nThen $x$ is interior to $A\\bigcup B$.  $\\Longrightarrow A \\bigcup B$ open.  \n\n$\\forall \\, x \\in A \\bigcap B$, $x \\in A$ and $x \\in B$.  \\\\\n\\quad Since $x \\in A$ and $x \\in B$, $\\exists \\, B(x,r_A) \\subseteq A$; \\, $B(x,r_B) \\subseteq B$ or \\\\\n\\quad \\quad \\quad \\, $(x-r_A,x+r_A) \\subseteq A$ ; \\quad \\, $(x-r_B, x+r_B) \\subseteq B$ \\smallskip \\\\\nLet $r_m = \\min{ (r_A,r_B) }$ \\\\\nSo then $(x-r_m,x+r_m) \\subseteq A$ and $(x-r_m,x+r_m) \\subseteq B$ $\\Longrightarrow (x-r_m,x+r_m) \\subseteq A \\bigcap B$\n\\item $\\mathbb{R}^1$ is open (since $\\forall \\, B(x;r) \\subseteq \\mathbb{R}^1$ ) \\\\\n  $A = [a_A,b_A]$ is a closed interval.  \\\\\n  Let $\\mathbb{R}^1 - A = \\mathbb{R}^-$ \\\\\n  $\\forall \\, x \\in \\mathbb{R}^-$, $x \\in \\mathbb{R}^1$ so $B(x;r) \\subseteq \\mathbb{R}^1$.  \\medskip \\\\\n  Suppose $x \\in \\mathbb{R}^-$, so $x > b_A$ or $x < a_A$ (otherwise $x \\in A$).  \\medskip \\\\\n  \\quad \\quad If $x > b_A$, then let $r_1 = x - b_A$, \\\\\n  $(x-r_1,x+r_1) \\subseteq \\mathbb{R}^-$ since $(x-r_1,x+r_1) \\subseteq \\mathbb{R}$ and $\\forall \\, x_1 \\in (x-r_1, x+r_1)$, $x_1 > b_A$ \\\\\n  \\quad \\quad If $x < a_A$, then let $r_1 = a_A - x$ \\\\\n  $(x-r_1,x+r_1) \\subseteq \\mathbb{R}^-$ since $(x-r_1,x+r_1) \\subseteq \\mathbb{R}$ and $\\forall \\, x_1 \\in (x-r_1, x+r_1)$, $x_1 < a_A$\n\\end{enumerate} \n\n\\exercisehead{5} Prove the following properties of open sets in $\\mathbb{R}^n$\n\\begin{enumerate}\n\\item The empty set $\\emptyset$ is open.  \\medskip \\\\\nLet $a \\in \\emptyset$ \\\\\n\\phantom{ Let } Then $B(a;r) \\subseteq \\emptyset$ since there are no $a \\in \\emptyset$,  $\\Longrightarrow \\, a$ is an interior pt. of $\\emptyset$.  \\\\\n\nOr \\dots \\\\\n\nConsider $a \\in \\emptyset$ \\\\\nConsider $B(a;r) = \\emptyset$.  Then $B(a;r) \\subseteq \\emptyset$.  So $\\emptyset$ is open.\n\\item $\\mathbb{R}^n$ is open.  \\bigskip \\\\\n  Consider $a \\in \\mathbb{R}^n$.  Consider $B(a;r)$.  So for $x \\in B(a;r)$, then $\\| x-a \\| < r$.  \\\\\n  $\\Longrightarrow |x_j - a_j| < r_j$ \\\\\n  $x_j \\in \\mathbb{R}$ \\quad \\, $\\forall \\, x_j $ s.t. $|x_j - a_j| < r_j$ defines an open interval on $\\mathbb{R}^1$, and so by induction, the Cartesian product of $n$ open intervals is an open $n$-ball.  So $\\mathbb{R}^n$ is open.  \\\\\n\nOr \\dots \\\\\n\nConsider $a \\in \\mathbb{R}^n$.  \\\\\nConsider $B(a;r)$.  Since $\\forall \\, y \\in B(a;r)$, $y\\in \\mathbb{R}^n$.  $B(a;r) \\subseteq \\mathbb{R}^n$.  $\\mathbb{R}^n$ open.  \n\\item Consider $\\{ W_j \\}$, collection of open sets.  \\\\\nConsider $y\\in \\bigcup_j W_j$.  Then $y \\in W_j$ for some $j$.  Since $W_j$ open, $\\exists \\, B(y;\\rho) \\subseteq W_j$.  \\\\\n$W_j \\subseteq \\bigcup_j W_j$, so $B(y,\\rho) \\subseteq \\bigcup_j W_j$.  $\\bigcup_j W_j$ is open.  \n\\item Consider $\\{ W_j | j =1, \\dots, n\\}$, finite collection of open sets.    \\\\\n  Consider $ y \\in \\bigcap_{j=1}^n W_j$.  \\\\\n$y \\in W_i$, \\, $\\forall \\, i =1, \\dots, n$.  Then since $\\forall \\, i$, $W_i$ open, $\\exists \\, B_i(y,\\rho_i) \\subseteq W_i$.  \\\\\n  By Thm., $\\exists$ \\, open set $B(y,\\rho) \\subseteq \\bigcap_{i=1}^n B_i(y, \\rho_i)$.  Then $B(y,\\rho) \\subseteq \\bigcap_{i=1}^n B_i(y,\\rho_i) = \\bigcap_{i=1}^n W_i $\n\\item Let $W_k = \\left( \\frac{-1}{k}, \\frac{1}{k} \\right)$; $k \\geq 1$ \\\\\nThen $\\bigcap_k W_k = \\{ 0 \\}$, which is not open.  \n\\end{enumerate}\n\n\\exercisehead{7} \\begin{enumerate}\n\\item $(A \\bigcup \\{ x \\})^c = A^c \\bigcup (\\mathbb{R} - x)$ \\\\\n  $A^c$ open.  $\\mathbb{R}^n - x$ open.  (since $\\{ x \\}$ is closed).  Then, by thm., the intersection of these two open sets, $A^c \\bigcap (\\mathbb{R} - x)$ is open.  Then, by definition, $A \\bigcup \\{ x \\}$ is closed.  \n\\item $\\mathbb{R} - [a,b] = [a,b]^c$.  \\\\\n  Consider $y \\in \\mathbb{R} - [a,b]$ \\smallskip \\\\\nIf $y > b$, then  \\\\\n\\quad \\, $ y -b > 0$, so $\\exists \\, N \\in \\mathbb{Z}^+$ s.t. $y-b > \\frac{1}{N}$.  $y > \\frac{1}{N} + b$ (Archimedes prop. of real numbers).   \\\\\n\\quad \\quad \\, $ y \\in \\left( \\frac{1}{N} + b, y+1 \\right)$ is open and $\\left( \\frac{1}{N} + b, y +1 \\right) \\subseteq \\mathbb{R} - [a,b]$   \\smallskip \\\\\nIf $y<a$, then \\\\\n\\quad \\, $a - y >0$, so $\\exists \\, N \\in \\mathbb{Z}^+$ s.t. $a-y > \\frac{1}{N}$ or $a - \\frac{1}{N} >y$ \\\\\n\\quad \\, $y \\in \\left( y -1, a-\\frac{1}{N} \\right) \\subseteq \\mathbb{R} - [a,b]$ \\\\\nthen $\\mathbb{R} - [a,b]$ open.  $[a,b]$ closed (by definition).  \n\\item $(A \\bigcup B)^c = A^c \\bigcap B^c$.  $A,B$ closed, so $A^c$, $B^c$ open.  $A^c \\bigcap B^c$, intersection of 2 open sets, is open.  \\\\\n  \\quad \\, then $A \\bigcup B$ closed.  \\smallskip \\\\\n$(A \\bigcap B)^c = A^c \\bigcap B^c$.  $A^c, B^c$ open.  $A^c \\bigcup B^c$ open.  Then $(A \\bigcap B)$ closed.  \n\\end{enumerate}\n\n\\exercisehead{8} \\begin{enumerate}\n\\item $\\emptyset^c = \\mathbb{R}^n$ and $\\mathbb{R}^n$ open.  $\\emptyset$ closed.  \n\\item $(\\mathbb{R}^n)^c = \\emptyset$ and $\\emptyset$ open.  $\\mathbb{R}^n$ closed.  \n\\item $(\\bigcap_i A_i)^c = \\bigcup_i A_i^c$.  $A_i^c$ open, so $\\bigcup_i A_i^c$ open.  $\\bigcap_i A_i$ closed.  \n\\item $(\\bigcup_{i=1}^n A_i)^c = \\bigcap_{i=1}^n A_i^c$.  $A_i^c$ open, so $\\bigcap_{i=1}^n A_i^c$ open.  $\\bigcup_{i=1}^n A_i$ closed.  \n\\item $\\bigcup_{i=1}^{\\infty} \\{ i \\} = \\mathbb{Z}^+$ is closed since $\\left( \\bigcup_{i=1}^{\\infty} \\{ i \\} \\right)^c = \\bigcup_{i=1}^{\\infty} (i,i+1)$ is open.  \n\\end{enumerate}\n\n\\exercisehead{9} Let $S$ be a subset of $\\mathbb{R}^n$ \n\\begin{enumerate}\n\\item Prove that both $int{S}$ and $ext{S}$ are open sets.  \\medskip \\\\\n%If $int{S} = \\emptyset$, $\\emptyset$ is open; done.  \\smallskip \\\\\n%Consider $a \\in int{S}$ \\\\\n%\\phantom{Consider} By def. of $int{S}$, $\\exists \\, B(a;r)$ s.t. $B(a;r) \\subseteq int{S}$.  Then $int{S}$ open.  \\medskip \\\\\n%If $ext{S} = \\emptyset$, $\\emptyset$ is open; done.  \\smallskip \\\\\n%$\\forall \\, b \\in ext{S}$, $\\exists \\, B(b;r)$ s.t. $a \\notin B(b;r)$ where $a \\in S$ \\\\\n%$b$ itself must be $b \\notin S$, otherwise $b \\in B(b;r)$ and $b \\in S$  \\medskip \\\\\n%If $x_b \\in B(b;r)$, consider $r_{xb} = \\| x_b - b \\|, \\, B(x_b;r_{xb})$ \\smallskip \\\\\n%$B(x_b;r_{xb}) \\subseteq B(b;r)$ since $\\| x_b - b_b \\| < r_{xb} = \\| x_b - b \\| < r$ so $b_b \\in B(x_b;r_{xb})$, $b_b \\notin S$ \\smallskip \\\\\n%$\\Longrightarrow B(x_b,r_{xb})$ contains no pts. in $S$ $\\Longrightarrow x_b \\in ext{S}$ \\\\\n%\\quad \\quad \\, $\\Longrightarrow B(b;r)$ contains only pts. in $ext{S}$, i.e. $B(b;r) \\subseteq ext{S} \\xrightarrow{ \\text{ (by def. of open set) } } ext{S}$ open.  \n\\emph{Want}: $int{S}$ is open, i.e. $\\forall \\, a \\in int{S}$, $\\exists \\, B(a;r) \\subseteq int{S}$ i.e. \\\\\n\\quad \\quad $\\forall \\, x_1 \\in B(a;r), \\, x_1 \\in int{S}$ \\\\\n\\quad \\quad $x_1 \\in int{S}$ if $\\exists \\, B(x_1;r_1) \\subseteq S$ \\smallskip \\\\\n\nConsider $a\\in int{S}$, then $\\exists \\, B(a;r) \\subseteq S$  \\\\\n\\quad \\, Consider $x_1 \\in B(a;r)$.  If $\\| x_1 - a\\| < r$ consider $\\forall \\, x_2$ s.t. $\\| x_2 - x_1 \\| < \\| x_1 - a \\| = r_1 <r$.  \\\\\n\\quad \\quad Then $x_2 \\in B(a;r)$, so $B(x_1,r_1) \\subseteq B(a;r) \\subseteq S$ \\\\\n\\quad \\quad \\, $\\Longrightarrow \\forall \\, x_1 \\in int{S}$ for $x_1 \\in B(a;r)$, so $B(a;r) \\subseteq int{S}$.  \\medskip \\\\\n\n\\emph{Want}: $ext{S}$ is open, i.e. $\\forall \\, a \\in ext{S}$, $\\exists \\, B(a;r) \\subseteq ext{S}$ i.e. \\\\\n\\quad \\quad $\\forall \\, x_1 \\in B(a;r), \\, x_1 \\in ext{S}$ \\\\\n\\quad \\quad $x_1 \\in ext{S}$ if $\\exists \\, B(x_1;r_1)$ s.t. $\\forall \\, x_2 \\in B(x_1,r_1)$, $x_2 \\notin S$.  \\smallskip \\\\\n\nConsider $a\\in ext{S}$, then $\\exists \\, B(a;r)$ s.t. $\\forall \\, x_1 \\in B(a,r)$, $x_1 \\notin S$  \\\\\n\\quad \\, Consider $x_1 \\in B(a;r)$.  If $\\| x_1 - a\\| < r$ consider $\\forall \\, x_2$ s.t. $\\| x_2 - x_1 \\| < \\| x_1 - a \\| = r_1 <r$.  \\\\\n\\quad \\quad Then $x_2 \\in B(a;r)$, so $x_2 \\notin S$.  so then $\\exists \\, B(x_1,r_1)$ s.t. $\\forall \\, x_2 \\in B(x_1,r_1)$, $x_2 \\notin S$ \\\\\n\\quad \\quad \\, $\\Longrightarrow \\forall \\, x_1 \\in ext{S}$, so $B(a;r) \\subseteq ext{S}$.  $ext{S}$ open.   \n\\item Prove that $\\mathbb{R}^n = (int{S}) \\bigcup (ext{S}) \\bigcup \\partial S$, a union of disjoint sets, and use this to deduce that boundary $\\partial S$ is always a closed set.  \\medskip \\\\\n\nSuppose $a_e \\in ext{S}$.  Then $\\exists \\, B(a_e,r)$ s.t. $\\forall \\, x_e \\in B(a_e,r)$, $x_e \\notin S$.  \\\\\nThen $\\forall \\, R > 0$, $B(a_e, R)$ will contain $x_{eR} \\in B(a_e,R)$ s.t. $x_{eR} \\notin S$. (all open $n$-balls will either contain $B(a_e,r)$ or be a part of $B(a_e,r)$).  So $\\nexists \\, B(a_e,R)$ s.t. $B(a_e,r) \\subseteq S$.  $a_e \\notin int{S}$ \\smallskip \\\\\n\nIf $a_{in} \\in int{S}$, suppose $a_{in} \\in  ext{S}$.  Then $a_{in} \\notin int{S}$.  Contradiction.  $a_{in} \\notin ext{S}$.  \\medskip \\\\\n\\quad \\quad $int{S}, \\, ext{S}$ are open and disjoint.  \\medskip \\\\\n\nSuppose $a_{bd} \\in \\partial S$.  $\\begin{aligned}\n  & \\text{ $a_{bd}$ is not interior to $S$, so $a_{bd} \\notin int{S}$ }\\\\\n  & \\text{ $a_{bd}$ is not exterior to $S$, so $a_{bd} \\notin ext{S}$}\n\\end{aligned} $\n\nLet $x \\in \\mathbb{R}^n$.  Consider $B(x,r_0)$.  If $B(x,r_0) \\subseteq S$, then $x\\in int{S}$.  If $\\forall \\, x_1 \\in B(x,r_0)$, $x_1 \\notin S$.  Then $x\\in ext{S}$.  \\smallskip \\\\\n\\quad \\quad Otherwise, $B(x,r_0)$ may contain $x_{1a} \\in S$ and $x_{1b} \\in S^c$.  Then $x$ is neither interior or exterior to $S$.  So $x \\in \\partial S$ \\smallskip \\\\\n\n$\\Longrightarrow x \\in int{S} \\bigcup ext{S} \\bigcup \\partial S$, $\\mathbb{R}^n \\subseteq int{S} \\bigcup ext{S} \\bigcup \\partial S$.  \\medskip \\\\\nSince $\\forall \\, x \\in int{S} \\bigcup ext{S} \\bigcup \\partial S$, $x \\in \\mathbb{R}^n$, then $int{S} \\bigcup ext{S} \\bigcup \\partial S \\subseteq \\mathbb{R}^n$.  \\smallskip \\\\\n\\quad \\quad \\quad $\\Longrightarrow \\mathbb{R}^n = int{S} \\bigcup ext{S} \\bigcup \\partial S$ a union of disjoint sets.  \\smallskip \\\\\n\n$(int{S} \\bigcup ext{S})^c = \\partial S$, $int{S} \\bigcup ext{S}$ is open so $\\partial S$ is closed, since its complement is open.  \n\\end{enumerate}\n\n\\exercisehead{10} \\textbf{Want:} $x =$ boundary pt. of $S$ $=$ b.p. of $S$, neither interior nor exterior to $S$.  \\smallskip \\\\\n$\\forall \\, B(x)$, $\\exists \\, a_i \\in B(x)$, s.t. $a_i \\in int{S} \\subseteq S$.  Then $x$ cannot be an exterior pt.  \\\\\n$\\forall \\, B(x)$, $\\exists \\, a_e \\in B(x)$, s.t. $a_e \\in ext{S}$.  Then $a_e \\notin S$ and so $x$ is not interior, by definition.  $x$ is a boundary pt.  \n\n\\exercisehead{11} $\\mathbb{R}^n - S = S^c$.  \\\\\nLet $x \\in int{S^c}$.  Then $\\exists$ open $V$ s.t. $x\\in V$ and $V \\subseteq S^c$.   \\smallskip \\\\\nThen $\\forall \\, x_1 \\in V$, $x_1 \\notin S$, so $x$ is an exterior pt. to $S$.  $x \\in ext{S}$, so $int{S^c} \\subseteq ext{S}$.  \\\\\nLet $x \\in ext{S}$.  Then $\\exists \\, B(x)$ s.t. $B(x) \\subseteq S^c$.  By def., $x \\in int{S}^c$. \\\\\n\\quad \\, $ext{S} \\subseteq int{S^c}$\n\\[\n\\Longrightarrow ext{S} = int{S^c}\n\\]\n\n\\exercisehead{12}  Suppose $S$ closed.  Let $y$ be a boundary pt. of $S$.  \\\\\nSuppose $y \\notin S$.  Then $y\\in S^c$, $S^c$ open.  \\\\\n\\quad So by def. of open set, $\\exists \\, U$ s.t. $y\\in U$ and $U \\subseteq S^c$.  But $y$ is then an exterior pt., contradicting the definition of a boundary pt. for $y$.   \\smallskip \\\\\nThen $y \\in S$, so that $S = int{S} \\bigcup \\partial S$ \\\\\n\nSuppose $int{S} \\bigcup \\partial S =S$ \\\\\n\\quad Consider any $z \\in S^c$.  \\\\\nThen $z$ has to be either a boundary pt. of $S^c$ or interior pt. of $S^c$.  \\\\\n\\quad $z$ cannot be a boundary pt. of $S^c$ (we already showed that $\\begin{aligned} ext{S} & = int{S^c} \\\\ ext{S^c} & = int{S} \\end{aligned}$), because then $z\\in \\partial S$ and hence belong to $S$.  \\\\\nThen $z$ is interior to $S^c$.  $S^c = int{S^c}$, so $S^c$ open.  $S$ closed.  \n\n\n%-----------------------------------%-----------------------------------%-----------------------------------\n\\section*{ 8.5 Exercises - Limits and continuity }\n%-----------------------------------%-----------------------------------%-----------------------------------\n\n\\exercisehead{1} \n\\begin{enumerate}\n  \\item $f(x,y)$ is continuous $\\forall \\, (x,y) \\in \\mathbb{R}^2$ \n  \\item $(x,y) \\neq (0,0)$\n  \\item $y\\neq 0$\n\\item $y\\neq 0$, $\\frac{x^2}{y} \\neq \\frac{\\pi}{2} + \\pi k$, $k \\in \\mathbb{Z}$\n\\item $x\\neq 0$\n\\item $(x,y) \\neq (0,0)$\n\\item $\\frac{x+y}{1 - xy} \\neq \\frac{\\pi}{2} + \\pi k$, \\, $k\\in \\mathbb{Z}$, $xy\\neq 1$\n\\item $(x,y) \\neq (0,0)$\n\\item $f = \\exp{(y^2 \\ln{x}) }$, $x\\neq 0$\n\\item $ y \\neq 0$, $\\frac{x}{y} \\geq 0$\n\\end{enumerate}\n\n\\exercisehead{2}$ \\lim_{x\\to a} f(x,y), \\, \\lim_{y\\to b} f(x,y)$ exist, so $\\lim_{x\\to a} f(x,y) =f(a,y)$ and $\\lim_{y\\to b} f(x,y) = f(x,b)$.  \\medskip \\\\\nSince $\\lim_{x\\to x_0} f(x) = f(x_0)$, where $x_0 = (a,b)$, which is equivalent to saying \n\\[\n\\forall \\, \\epsilon > 0, \\, \\exists \\, \\delta > 0 \\text{ s.t. } |f(x) -L| < \\epsilon \\text{ if } \\| x - x_0 \\| < \\delta\n\\]\nthen \\\\\nConsider $\\frac{\\epsilon }{2} > 0$.  $\\exists \\, \\delta_y > 0$ s.t. $|f(x,y) - f(x,b)| < \\frac{ \\epsilon}{2}$ if $|y-b| <\\delta_y$ (since $\\lim_{y\\to b} f(x,y)$ exists).   \\\\\nConsider $\\frac{\\epsilon }{2} > 0$.  $\\exists \\, \\delta_{xy} > 0$ s.t. $|f(x,y) - L| < \\frac{ \\epsilon}{2}$ if $\\| (x,y) - (a,b) \\| <\\delta_{xy}$ (since $\\lim_{x\\to x_0} f(x)=L$).  \n\\[\n\\begin{gathered}\n  |f(x,b)-L| = |f(x,b) -f(x,y) + f(x,y) - L | < |f(x,y) - f(x,b) | + |f(x,y) - L | < \\frac{\\epsilon}{2} + \\frac{\\epsilon}{2} = \\epsilon \\text{ whenever } \\\\\n  |y-b| < \\delta_y \\text{ and } \\sqrt{ (x-a)^2 + (y-b)^2 } < \\delta_{xy} \\\\\n  \\text{ then } |x-a| < \\delta_{xy}\n\\end{gathered}\n\\]\nSo $\\forall \\, \\epsilon > 0$, $\\exists \\, \\delta_{xy} = \\delta_x(\\epsilon)$ s.t. $|f(x,b)-L| <\\epsilon$ whenever $|x-a| < \\delta_x(\\epsilon)$.  \\\\\n\\phantom{ So } We just proved $\\lim_{x\\to a} \\lim_{y\\to b} f(x,y) = \\lim_{x\\to a} f(x,b) = L$\n\nSimilarly, we get the same result for $lim_{y\\ to b} f(a,y)$.  Thus, $\\lim_{x\\to a} \\lim_{y\\to b} f(x,y) = \\lim_{y\\to b} \\lim_{x\\to a} f(x,y) = L$ whenever $\\lim_{x\\to x_0} f(x) = L$\n\n\\exercisehead{3} $f(x,y) = \\frac{(x-y)}{x+y}$ \n\\[\n\\begin{aligned}\n  & \\lim_{y\\to 0} f = 1 \\\\\n  & \\lim_{x\\to 0} f = -1\n\\end{aligned}\n\\]\n\n\\exercisehead{4} $f(x,y) = \\frac{x^2 y^2}{ x^2 y^2 + (x-y)^2 }$ \n\\[\n\\begin{aligned}\n  & \\lim_{x\\to 0} f = 0 \\\\\n  & \\lim_{y \\to 0} f = 0 \n\\end{aligned}\\quad \\quad \\quad \\text{ but if } y = x, f = \\frac{x^4}{x^4 + 0} = 1\n\\]\n\n\\exercisehead{5} $0 < x \\sin{\\frac{1}{y}} < x$ \\quad $x \\to 0$, so by squeeze principle, $x \\sin{\\frac{1}{y}} \\to 0$.  \\\\\n\\quad \\quad $\\to \\lim_{x\\to 0} f =0$\n\n$\\lim_{y\\to 0} f$ undefined, since \\\\\n\\quad Consider $|y| < \\frac{1}{n}$ or $n < \\frac{1}{|y|}$ \\\\\n\\quad \\quad For $y >0$, $\\sin{\\frac{1}{y}} > \\sin{n}$ \\\\\n\\quad \\quad For $y <0$, $|\\sin{\\frac{1}{y}}| = \\sin{ \\frac{-1}{y} } > \\sin{n}$ \n\n$\\forall \\, \\delta = \\frac{1}{n}, \\exists \\, \\epsilon = \\epsilon(\\delta) = \\sin{(1/\\delta)}$ s.t. $|\\sin{1/y}| > \\epsilon$ if $|y| < \\frac{1}{n}$ \\\\\n\\quad Then $\\lim_{y\\to 0} \\lim_{x\\to 0} f = 0 \\neq \\lim_{x\\to 0} \\lim_{y\\to 0} f$\n\n\\exercisehead{6} $(x,y) \\neq (0,0)$, let $f(x,y) = \\frac{ x^2 - y^2}{x^2 + y^2}$ \\\\\nIf $y=mx$, $f\\to \\frac{ x^2 (1-m^2)}{ x^2(1+m^2)} = \\frac{1-m^2}{1+m^2}$.  If $y=0$, $f = 1$.  If $x=0$, $f=-1$, so there's no way to define $f(0,0)$ to be single valued.  \n\n\\exercisehead{7} Consider $y=kx$; $k\\in \\mathbb{R}$. \\\\\nFor $k=0$, $y=0$ and $f(x,y) =0$, if $y=0$ \\\\\nFor $k \\gtrless 0$, $x \\lessgtr 0$, $y<0$, so $f(x,y) =0$.  \\medskip \\\\\nConsider the limit as $x \\to 0$.  $\\epsilon$ can be as small as you want. \\\\\n\\quad \\quad Then we must have $|x| < \\epsilon < |k|$.  \\\\\n\\quad \\quad \\quad then $x^2 < kx$ \\\\\n\\quad Thus $y=kx > x^2$, so $f(x,y) =0$ for any straight line through the origin.  \n\nConsider $|x| < \\epsilon =1$ \n\\[\nx^4 < x^2\n\\]\nSo $y= x^4 < x^2 \\to f(x,y) = 1$ \\\\\n\\quad So, $f$ is discontinuous at $(0,0)$.  $f(0,0)$ depends upon path taken.  \n\n\\exercisehead{8} Change to polar coordinates.  Then \n\\[\nf(x,y) = \\frac{ \\sin{(x^2 + y^2)} }{ (x^2 + y^2)} = f(r,\\theta) = \\frac{ \\sin{ r^2}}{r^2}\n\\]\nThen regardless of what value of $\\theta$, $\\lim_{r\\to 0} \\frac{\\sin{r^2}}{r^2} = \\boxed{1}$.  \n\n\\exercisehead{9} Let $f$ be a scalar field continuous at an interior pt. $a$ of a set $S$ in $\\mathbb{R}^n$.  $f(a) \\neq 0$ (given).  \n\nContinuity of $f$ at $a$ means that \n\\[\n\\lim_{x\\to a} f(x) = f(a) \\Longrightarrow \\forall \\, \\epsilon > 0, \\, \\exists \\, \\delta > 0 \\text{ s.t. } | f(x)  - f(a) | < \\epsilon \\text{ whenever } \\| x- a\\| < \\delta \n\\]\nLet $\\epsilon = \\frac{f(a)}{2}$, $\\exists \\, \\delta = \\delta(\\epsilon; a)$ s.t. $\\begin{cases} f(x) -f(a) < \\frac{f(a)}{2} & \\text{ if } f(x) > f(a) \\\\ -f(x) + f(a) < \\frac{ f(a)}{2} & \\text{ if } f(x) < f(a) \\end{cases}$,  \\smallskip \\\\\n\\quad \\quad so $\\frac{f(a)}{2} < f(x) < \\frac{3f(a)}{2}$ for $\\forall \\, x$ s.t. $\\| x- a\\| < \\delta(\\epsilon; a)$.  \\medskip \\\\\n$\\delta(\\epsilon;a)$ defines a $B(a) \\subseteq \\mathbb{R}^n$ s.t. $f(x)$ has the same sign as $f(a)$.  \n\n\n%-----------------------------------%-----------------------------------%-----------------------------------\n\\section*{ 8.9 Exercises - The derivative of a scalar field with respect to a vector, Directional derivatives and partial derivatives, Partial derivatives of higher order }\n%-----------------------------------%-----------------------------------%-----------------------------------\n\n\\exercisehead{1} $f(x) = a\\cdot x$\n\\[\nf'(x;y) = \\lim_{h\\to 0} \\frac{ f(x+hy) - f(x)}{h} = \\lim_{h\\to 0} \\frac{ a\\cdot (x+hy) - a\\cdot x }{ h } = \\boxed{ a\\cdot y}\n\\]\n\n\\exercisehead{2} $f(x) = \\| x \\|^4$ \n\\begin{enumerate}\n\\item \\[\n  f'(x,y) = \\lim_{h\\to 0} \\frac{f(x+hy) -f(x) }{h} = \\lim_{h\\to 0} \\frac{ \\|x+h y\\|^4 - \\| x \\|^4 }{h} = \\boxed{ 4 x^2 (x\\cdot y) }\n\\]\n\\item $n=2$\n\\[\nf'(2i+3j; xi +yj)= 6 = 4(13) (2x+3y) \\Longrightarrow \\frac{3}{26} = 2x + 3y \\Longrightarrow \\boxed{ y= \\frac{-2x}{3} + \\frac{1}{26} }\n\\]\n\\item $n=3$\n\\[\nf'(i+2j+3k;xi +yj+zk) = 0 =4 (1^2 + 2^2 + 9)(x+2y+3z) \\Longrightarrow \\boxed{ x+2y+ 3z =0}\n\\]\n\\end{enumerate}\n\n\\exercisehead{3} \n\\[\n\\begin{aligned}\nf'(x,y) & = \\lim_{h\\to 0} \\frac{f(x+hy)-f(x)}{h} = \\lim_{h\\to 0} \\frac{ (x+hy)\\cdot T(x+hy) - x\\cdot T(x)}{h} = \\lim_{h\\to 0} \\frac{ (x+hy) \\cdot (T(x) + hT(y) ) - x\\cdot T(x) }{h} = \\\\\n& = \\lim_{h\\to 0} \\frac{ hy\\cdot T(x) + hx\\cdot T(y) + h^2 y T(y) }{h} = \\boxed{ y\\cdot T(x) + x\\cdot T(y) }\n\\end{aligned}\n\\]\n\n\\exercisehead{4} $f(x,y) = x^2 + y^2 \\sin{(xy)}$\n\\[\n\\begin{aligned}\n  & \\partial_x f = 2x + y^3 \\cos{(xy)} \\\\\n  & \\partial_y f = 2y \\sin{(xy)} + xy^2 \\cos{(xy)}\n\\end{aligned}\n\\]\n\n\\exercisehead{5} $f(x,y) = \\sqrt{ x^2 + y^2 }$ \n\\[\n  \\partial_x f = \\frac{x}{f}; \\quad \\partial_y f = \\frac{y}{f}\n\\]\n\n\\exercisehead{6} $f(x,y) = \\frac{x}{\\sqrt{ x^2+ y^2 }}$ \n\\[\n\\begin{aligned}\n  & \\partial_x f = \\frac{1}{f} + \\frac{-x^2}{(x^2 + y^2)^{3/2} } \\\\\n  & \\partial_y f = \\frac{-xy}{ (x^2 +y^2)^{3/2} }\n\\end{aligned}\n\\]\n\n\\exercisehead{7} $f(x,y) = \\frac{x+y}{x-y}$, \\quad $x \\neq y$\n\\[\n\\begin{aligned}\n  & \\partial_x f = \\frac{1}{x-y} + \\frac{-(x+y)}{(x-y)^2} = \\frac{-2y}{(x-y)^2} \\\\\n  & \\partial_y f = \\frac{1}{x-y} + \\frac{-(x+y)}{(x-y)^2}(-1) = \\boxed{ \\frac{2x}{(x-y)^2} }\n\\end{aligned}\n\\]\n\n\\exercisehead{8} $f(x) = a\\cdot x$; $a$ fixed.  \n\\[\n\\boxed{ \\partial_{x_j} f = a_j }\n\\]\n\n\\exercisehead{9} $f(x) = \\sum_{i=1}^n \\sum_{j=1}^n a_{ij} x_i x_j$, $a_{ij} = a_{ji}$\n\\[\n\\partial_{x_k} f(x) = \\sum_{i=1}^n \\sum_{j=1}^n a_{ij} \\delta_{ik} x_j + \\sum_{i=1}^n \\sum_{j=1}^n a_{ij} x_i \\delta_{jk} = \\sum_{j=1}^n a_{kj} x_j + \\sum_{i=1}^n a_{ik}x_i = \\boxed{ 2 \\sum_{j=1}^n a_{kj} x_j }\n\\]\n\n\\exercisehead{10} $f(x,y) = x^4+y^4 - 4x^2 y^2$\n\\[\n\\begin{aligned}\n  & \\partial_x f = 4x^3 - 8xy^2 \\\\\n   & \\partial_y f = 4 y^3 - 8x^2 y\n\\end{aligned} \\quad \\quad \\quad \n\\begin{aligned}\n  & \\partial_{yx}^2 f = -16 xy \\\\\n  & \\partial_{xy}^2 f = -16 xy \n\\end{aligned}\n\\]\n\n\\exercisehead{11} $f(x,y) = \\log{(x^2 + y^2)}$ \n\\[\n\\begin{aligned}\n  & \\partial_x f = \\frac{2x}{x^2 +y^2} \\\\\n  & \\partial_y f = \\frac{2y}{x^2 + y^2}\n\\end{aligned} \\quad \\quad \\quad \n\\begin{aligned}\n  & \\partial_{yx} f = \\frac{-4xy}{ (x^2 +y^2)^2 } \\\\\n  & \\partial_{xy} f = \\frac{-4xy}{ (x^2 +y^2)^2 }\n\\end{aligned}\n\\]\n\n\\exercisehead{12} $f(x,y) = \\frac{1}{y} \\cos{x^2}$ ; \\, $y\\neq 0$ \n\\[\n\\begin{aligned}\n  & \\partial_x f = \\frac{-2x \\sin{x^2}}{y } \\\\\n  & \\partial_y f = \\frac{-1}{y^2} \\cos{x^2} \n\\end{aligned} \\quad \\quad \\quad \n\\begin{aligned}\n  & \\partial_{yx} f = \\frac{2x \\sin{x^2}}{y^2} \\\\\n  & \\partial_{xy} f = \\frac{2x \\sin{x^2}}{y^2 }\n\\end{aligned}\n\\]\n\n\\exercisehead{13} $f(x,y) = \\tan{(x^2/y)}$; \\, $y\\neq 0$ \n\\[\n\\begin{aligned}\n  & \\partial_x f = \\frac{2x}{y} \\sec{ (x^2/y)} \\\\\n  & \\partial_y f = \\frac{-x^2}{y^2} \\sec{ (x^2/y)}\n\\end{aligned}\n\\]\n\n\\exercisehead{14} $f(x,y) = \\arctan{ (y/x)}$ \n\\[\n\\begin{aligned}\n  & \\partial_x f = \\frac{1}{1 + (y/x)^2} \\left( \\frac{-y}{x^2} \\right) \\\\\n  & \\partial_y f = \\frac{1}{ 1 + (y/x)^2 } \\left( \\frac{1}{x} \\right)\n\\end{aligned}\n\\]\n\n\\exercisehead{15} $f(x,y) = \\arctan{ \\left( \\frac{x+y}{ 1-xy } \\right) }$\n\\[\n\\begin{gathered}\n  \\partial_x f = \\frac{1}{ 1 + \\left( \\frac{ x+y}{ 1-xy} \\right)^2 } = \\left( \\frac{1}{1-xy} + \\frac{ -(x+y)}{(1-xy)^2} ((-y) \\right) = \\frac{ 1 - xy + xy + y^2 }{ 1 + x^2 y^2 + x^2 + y^2 } = \\frac{ 1  +y^2}{ 1 + x^2 y^2 + x^2 + y^2 } \\\\\n  \\partial_y f = \\frac{ 1 + x^2 }{ 1 + x^2 y^2 + x^2 + y^2 } \\quad \\text{ (by label symmetry!) }\n\\end{gathered}\n\\]\n\n\\exercisehead{16} $f(x,y) = e^{y^2} \\ln{x}$ \\, $x>0$\n\\[\n\\begin{aligned}\n  \\partial_x f = y^2 x^{y^2 - 1} \\\\\n  \\partial_y f = x^{y^2} 2y \\ln{x}\n\\end{aligned}\n\\]\n\n\\exercisehead{17} $f(x,y) = \\arccos{ \\sqrt{x/y}}$; \\, $y\\neq 0$ \n\\[\n\\begin{aligned}\n  & \\partial_x f = \\frac{-1}{ \\sqrt{ 1 - x/y} } \\frac{ 1/2}{ \\sqrt{ xy}} = \\frac{-1/2}{ \\sqrt{ xy - x^2 }} \\\\\n  & \\partial_y f = \\frac{ -1}{ \\sqrt{ 1 - x/y} } \\frac{ \\sqrt{x} (-1/2)}{ y^{3/2}} = \\frac{ (1/2) \\sqrt{x}/y}{ \\sqrt{ y- x} }\n\\end{aligned}\n\\]\n\n\\exercisehead{18} $v(r,t) = t^n e^{-r^2/4t}$ \n\\[\n\\begin{gathered}\n  \\partial_r v = \\frac{-1r}{2t} t^n e^{-r^2/4t} = \\frac{-r}{2t} t^n e^{-r^2/4t} \\\\\n  r^2 \\partial_r v = \\frac{-r^3}{2t} t^n e^{-r^2/4t} \\\\\n  \\partial_r (r^2 \\partial_r v ) = \\frac{-3r^2}{2t} t^n e^{-r^2/4t} + \\frac{-r^3}{2t} t^n \\left( \\frac{-r}{2t} \\right) e^{-r^2/4t} \\\\\n  \\frac{1}{r^2} \\partial_r (r^2 \\partial_r v) = \\frac{-3}{2t} t^n e^{-r^2/4t} + \\frac{r^2 t^n }{4t^2} e^{-r^2/4t} \n\\end{gathered} \\quad \\quad \\quad \n\\begin{gathered}\n  \\partial_t v = nt^{n-1} e^{-r^2/4t} + t^n \\left( \\frac{r^2}{4t^2} \\right) e^{-r^2/4t} \\\\\n  \\boxed{ n = -3/2 }\n\\end{gathered}\n\\]\n\n\\exercisehead{19} $z = u(x,y) e^{ax+by}$; \\, $\\frac{\\partial^2 u}{ \\partial x \\partial y} = 0$ \n\\[\n\\begin{aligned}\n  & \\partial_x z = \\partial_x u e^{ax + by} + az \\\\\n  & \\partial_y z = (\\partial_y u)e^{ax + by} + bz \\\\\n  & \\partial_{xy}^2 z = a(\\partial_y u) e^{ax+by} + b(\\partial_x u) e^{ax+ by} + bau e^{ax+by} \\\\\n  & \\partial_{xy}^2 z - \\partial_x z - \\partial_y z + z = a (\\partial_y u )e^{ax + by} + b(\\partial_x u )+abz - (\\partial_x u)e^{ax+ by} - az - (\\partial_y u) e^{ax+by} - bz + z = 0  \\\\\n  & \\boxed{ a = 1; \\, b=1 }\n\\end{aligned}\n\\]\n\n\\exercisehead{20} \n\\begin{enumerate}\n\\item $f'(x,y) = 0$ \\, $\\forall \\, x \\in B(a)$ \\, $\\forall \\, y$ \\\\\nRecall Thm. 8.4, Mean-value Thm. for derivatives of scalar fields.  Assume $\\exists \\, f'(a+ty;y)$ \\, $\\forall \\, t \\in [0,1]$.  Then $\\exists \\, $ some $\\theta \\in (0,1)$ s.t. \n\\[\nf(a+y) - f(a) = f'(z;y), \\text{ where } z = a+\\theta y\n\\]\n\\begin{proof}\n  Let $g(t) = f(a+ty)$ \\\\\n  \\phantom{ Let } Use one-dim. mean-value thm. to $g$ on $[0,1]$. \n\\[\ng(1) - g(0) = g'(\\theta), \\, \\theta \\in (0,1)\n\\]\n\\end{proof}\n\\[\n\\begin{gathered}\n  x = a +y \\\\\n  y = x'; \\quad 0 \\leq |x'| < r \\\\\n  \\exists \\, f'(x,y) = f'(a+ty;y) \\, \\forall \\, t \\in [0,1] \\\\\n  (\\text{ since } |ty| = t|y| < tr < r ) \\\\\n  \\Longrightarrow f'(a+ty; y) = 0 = f(a+y) - f(a) \\\\\n  f(a) = f(x), \\forall \\, x \\in B(a)\n\\end{gathered}\n\\]\n\\item Suppose we consider $x = a+ x'$ where $|x'| < r$ and $x' \\parallel y$.  \n\\[\n\\begin{aligned}\n  f'(x,y) & = f'(a+x',y) = f'(a+|x'|\\frac{y}{|y|},y ) = \\\\\n  & = \\lim_{h \\to 0} \\frac{ f(a+ |x'|e_y, +h|y|e_y ) - f(a + |x'|e_y ) }{ h }  = \\lim_{ |y|h \\to 0} \\frac{ f(a+ |x'|e_y + (h|y| )e_y ) - f(a + |x'|e_y) }{ h|y|/|y| } = \\\\\n  & = |y| f'(a+ |x'|e_y, e_y)\n\\end{aligned}\n\\]\n\\[\n\\begin{gathered}\n  \\exists \\, |y| f'(a + t|x'| e_y, e_y) \\, \\forall \\, t \\in [0,1], \\text{ since } f'(x,y) = 0 \\quad \\forall \\, x \\in B(a) \\\\\n  0 = |y| f'(a+ t |x'|e_y,e_y) = f(a+ |x'|e_y) - f(a) \\Longrightarrow f(a+|x'|e_y) = f(a)\n\\end{gathered}\n\\]\n$f = f(a) = $ constant $\\forall \\, x \\in B(a)$ s.t. $x= a+ke_y$ \\quad $0 \\leq |k| < r$\n\\end{enumerate}\n\n\\exercisehead{21}\n\\begin{enumerate}\n\\item A set $S$ in $\\mathbb{R}^n$ is convex if $\\forall \\, a,b \\in S$, \n\\[\nta + (1-t) b \\in S \\quad \\forall \\, t \\in [0,1]\n\\]\n\nConsider $x_1,x_2 \\in b(a)$; \\quad $\\begin{aligned}\n  & x_1 = a+x_1' \\\\\n  & x_2 = a+x_2'\n\\end{aligned}$ \\quad and \\quad $\\begin{aligned}\n  & \\| x_1 - a \\| < r \\\\\n  & \\| x_2 - a \\| < r\n\\end{aligned}$\n\\[\n\\begin{gathered}\n  \\begin{aligned}\n    tx_2 + (1-t)x_1 - a & = t(a+x_2') + (1-t)(a+x_1') - a = at + x_2' t + a - at + x_1' - tx_1' - a = \\\\\n    & = x_1'(1-t) + x_2' t \n  \\end{aligned} \\\\\n  \\| tx_2 + (1-t)x_1 -a \\| = \\| x_1' (1-t) + x_2' t \\| \\leq  (1-t) \\| x_1' \\| + t \\| x_2' \\| < (1-t) r + tr = r  \n\\end{gathered}\n\\]\nSo $tx_2 + (1-t)x_1 \\in S$ \\quad $\\forall \\, t \\in [0,1]$.  So an $n$-ball is a convex set.  \n\\item Consider $x\\in S$.  Then for some $a,b \\in S$, $k\\in [0,1]$, $x = a + k(b-a)$.  \n\\[\n\\begin{gathered}\n  f'(x;y) = f'(a+k(b-a),y) \\xrightarrow{ \\text{ choose } y = b-a } f'(a+ k (b-a), b-a) \\text{ exists } \\\\\n  \\Longrightarrow f'(a + \\theta(b-a),b-a) = 0 = f(b) -f(a) \\Longrightarrow f(b) = f(a)\n\\end{gathered}\n\\]\nThis must be true for all pairs of $a,b \\in S$ since $x$ was arbitrarily chosen from $S$.  $f$ is constant on $S$.  \n\\end{enumerate}\n\n\\exercisehead{22}\n\\begin{enumerate}\n\\item \n\\[\n\\begin{gathered}\n  f'(a;y) = \\lim_{ h \\to 0 } \\frac{ f(a+hy) - f(a) }{h } \\\\\n  f'(a,-y) = \\lim_{h\\to 0} \\frac{ f(a-hy) - f(a) }{h} = - \\lim_{-h \\to 0} \\frac{ f(a+(-h)y ) - f(a) }{-h} = -f'(a,y) \\\\\n  \\text{ so if } f'(a,y) > 0, \\quad f'(a,-y) < 0 \n\\end{gathered}\n\\]\n\\item $f(x) = x\\cdot y$ because \n\\[\nf'(x;y) = \\lim_{h\\to 0 } \\frac{ f(x+hy) - f(x) }{h} = \\lim_{h\\to 0} \\frac{ x\\cdot y + hy^2 - x\\cdot y}{h} = y^2 > 0\n\\]\n\\end{enumerate}\n\n%-----------------------------------%-----------------------------------%-----------------------------------\n\\section*{ 8.14 Exercises - Directional derivatives and continuity, The total derivative, The gradient of a scalar field, A sufficient condition for differentiability } \n%-----------------------------------%-----------------------------------%-----------------------------------\n\nLet's review a number of important concepts with $R^n$ fields.  Differentiability must be redefined through a $n-dim$ Taylor expansion.    \n\n\\begin{definition}[Definition of a Differentiable Scalar Field] \\quad \\\\\nLet $f:S \\to \\mathbb{R}$ \\\\\nLet $a$ be an int. pt. of $S$.  \\\\\nLet $B(a;r)$ s.t. $B(a;r) \\subseteq S$ \\\\\nLet $v$ s.t. $\\| v \\| < r$, so $a+v \\in B(a;r)$  Then \\medskip \\\\\n$f$ diff. at $a$ \\\\\n\\phantom{ f diff} if $\\exists \\, T_a, \\, E$ s.t. \\\\\n\\phantom{ f diff if } linear $T_a:\\mathbb{R}^n \\to \\mathbb{R}$ \\\\\n\\phantom{ f diff if } scalar $E(a,v), \\, E(a,v) \\to 0$ as $\\| v \\| \\to 0$  and \n\\begin{equation}\n  f(a+v) = f(a) + T_a(v) + \\| v\\| E(a,v)\n\\end{equation}\n\\end{definition}\n\nThe next theorem shows that if the total derivative exists, it is unique.  It also tells us how to compute $T_a(y), \\, \\forall \\, y \\in \\mathbb{R}^n$.  \n\n\\begin{theorem}[Uniqueness of total derivative]\nAssume $f$ diff. at $a$ with total derivative $T_a$ \\\\\n\\phantom{Assu} Then $\\exists \\, f'(a;y) \\, \\forall y \\in \\mathbb{R}^n$ and \n\\[\nT_a(y) = f'(a;y)\n\\]\nAlso, \n\\[\n\\begin{gathered}\n  f'(a;y) = \\sum_{j=1}^{n} D_j f(a) y_j \\text{ for } \\\\\n  y = (y_1 , \\dots , y_j , \\dots , y_n) \n\\end{gathered}\n\\]\n\\end{theorem}\n\n\\begin{proof} \\quad \\\\\n  If $y=0$, \\quad \\, $T_a(0) = 0$ and $f'(a;0)=0$.  Done.  \\bigskip \\\\\n  Suppose $y\\neq 0$ \\\\\n  \\[\n\\begin{gathered}\n  f(a+v) = f(a) +T_a(v) + \\| v \\| E(a,v) \\quad \\quad \\, \\text{ (since we assume $f$ diff. ) } \\medskip \\\\\n  v = hy \\\\\n\\Longrightarrow \\frac{ f(a+hy) - f(a) }{ h } = \\frac{1}{h} T_a(hy) + \\frac{ \\| hy \\| }{ h } E(a,hy) \\xrightarrow{ h\\to 0 } f'(a,y)  = T_a(y)  + 0 \\\\\n\\end{gathered}\n\\]\nNow use linearity of $T_a$: \\[ T_a(y) = \\sum T_a (y_j e_j) = \\sum y_j T_a(e_j) = \\sum y_j f'(a;e_j) = \\sum y_j D_j f(a) \\]\n\\end{proof}\n\nThen the gradient was introduced, $\\nabla f(a) = (\\partial_1 f(a), \\dots, \\partial_n f(a) )$ so that \\\\\n$f'(a;y) = \\sum_{j=1}^n \\partial_j f(a) y_j =\\nabla f(a) \\cdot y $  so then also\n\\[\n\\Longrightarrow f(a+v) = f(a) + \\nabla f(a) \\cdot v + \\| v \\| E(a;v)\n\\]\n\n\\begin{theorem}[Differentiability implies Continuity] \\quad \\\\\nIf a scalar field $f$ is differentiable at $a$, then $f$ is cont. at $a$\n\\end{theorem}\n\n\\begin{proof}\n  Since $f$ is diff. \\\\\n$|f(a+v) -f(a)| = |\\nabla f(a) \\cdot v + \\| v \\| E(a,v) | $\\\\\nBy Cauchy-Schwarz inequality, \\medskip \\\\\n$0\\leq | f(a+v) -f(a) | \\leq \\| \\nabla f(a) \\| \\| v \\| + \\| v \\| |E(a;v) |$ \\medskip \\\\\nAs $v\\to 0$, $|f(a+v) - f(a)| \\to 0$ so $f$ cont. at $a$.  \n\\end{proof}\n\n\\quad \\bigskip \\\\\nIf $f$ is diff. at $a$, then all its partials exist (but the converse isn't true).  \\\\\n\\phantom{If} existence of partials doesn't necessarily imply $f$ is diff. \\\\\ne.g. $f(x,y) = \\frac{ xy^2}{ x^2 + y^4}$ \\quad \\bigskip \\\\\n\n\\begin{theorem}[Sufficient Condition for Differentiability] \\quad \\\\\nAssume $\\exists \\, \\partial_1 f , \\dots , \\partial_n f$ in some $n$-ball $B(a)$ and are cont. at $a$.  Then $f$ diff. at $a$.  \n\\end{theorem}\n\n\\begin{proof} \\quad \\\\\nLet $\\lambda = \\| v \\|$; then $v = \\lambda u$, \\quad $\\| u \\| = 1$ \\\\\nExpress $f(a+v) -f(a)$ as a telescoping sum.  \n\\[\nf(a+v)-f(a) = f(a + \\lambda u ) -f(a) = \\sum_{k=1}^n \\left( f(a+\\lambda v_k) - f(a+\\lambda v_{k-1}) \\right) \n\\]\\quad \\\\\nwhere $\\{ v_k \\}$ s.t. $\\begin{aligned}\n    v_0 & = 0 \\\\\n    v_n & = u \n  \\end{aligned}$.  Then choose the $v_k$'s s.t. \n\\[\n\\begin{gathered}\n  v_k = v_{k-1} + u_k e_k \\\\\n \\quad \\quad \\quad \\, v_1 = u_1 e_1; \\quad v_2 = u_1 e_1 + u_2 e_2 , \\dots , \\, v_n = u_1 e_1 + \\dots + u_n e_n  \\\\\n  \\begin{aligned}\nf(a+\\lambda v_k) - f(a+\\lambda v_{k-1} )  & = f(a+ \\lambda v_{k-1} + \\lambda u_k e_k) - f(a+\\lambda v_{k-1} ) = \\\\\n& = f(b_k + \\lambda u_k e_k) - f(b_k)\n\\end{aligned} \n\\end{gathered}\n\\]\n$b_k, \\, b_k + \\lambda u_k e_k$ differ only by their $k$th component so apply the mean value theorem \n\\[\n\\begin{gathered}\n  \\Longrightarrow f(b_k + \\lambda u_k e_k) - f(b_k) = (\\lambda u_k) \\partial_k f(c_k) \\\\\n\\quad \\\\\n\\text{ as $b_k \\to a$, as $\\lambda \\to 0$, so $c_k \\to a$ } \\\\\n\\Longrightarrow f(a+v) -f(a) = \\lambda \\sum_{k=1}^n u_k \\partial_k f(c_k) \n\\end{gathered}\n\\]\n\\quad \\\\\nNow $\\nabla f(a) \\cdot v = \\lambda \\sum u_k \\partial_k f(a) $.  \\\\\n$\\Longrightarrow f(a+v) -f(a) - \\nabla f(a) \\cdot v = \\lambda \\sum u_k (\\partial_k f(c_k) - \\partial_k f(a) ) = E(a,v)$ \\medskip \\\\\n$c_k \\to a$ as $\\| v \\| \\to 0$, and given $\\partial_k f$ are cont., $E(a,v) \\to 0$ as $\\| v \\| \\to 0$.  \\\\\nBy def. of diff., $f$ is diff.  \n\\end{proof}\n\n\\exercisehead{1} \n\\begin{enumerate}\n  \\item $f(x,y) = x^2 +y^2 \\sin{(xy)}$ \n\\[\n\\nabla f = (2x+y^2 \\cos{(xy)}, 2y \\sin{(xy)} + y^2 x \\cos{(xy)} )\n\\]\n  \\item $f(x,y) = e^x \\cos{y}$ \n\\[\n\\nabla f = (e^x \\cos{y}, -e^x \\sin{y} )\n\\]\n  \\item $f(x,y,z) = x^2 y^3 z^4 $\n\\[\n\\nabla f = (2xy^3 z^4, 3x^2 y^2 z^4, 4x^2 y^3 z^3 )\n\\]\n  \\item $f(x,y,z) = x^2 - y^2 + 2z^2$ \n\\[\n\\nabla f = (2x,-2y,4z)\n\\]\n  \\item $f(x,y,z) = \\log{(x^2 + 2y^2 - 3z^2)}$\n\\[\n\\nabla f  = \\frac{1}{f} (2x,4y, -6z)\n\\]\n  \\item $f(x,y,z) = e^{(ln{x}) e^{z \\ln{y}} }$\n\\[\n\\nabla f = f \\left( \\frac{e^z \\ln{y}}{x} , (\\ln{x}) e^{z\\ln{y}} \\left( \\frac{z}{y} \\right), (\\ln{x})(\\ln{y}) e^{z\\ln{y}} \\right)\n\\]\n\\end{enumerate}\n\n\\exercisehead{2} \n\\begin{enumerate}\n\\item $f(x,y,z) = x^2 + 2y^2 + 3z^2$ at $(1,1,0)$ in the direction of $i-j+2k$.  \n\\[\nf'(a,y) = \\nabla f(a) \\cdot y \n\\]\n\\item $\\nabla f = (2x,4y,6z)$  $\\nabla f(1,1,0) = (2,4,0)$.  $\\nabla f(a) \\cdot y = \\boxed{ -2} $\n\\end{enumerate}\n\n\\exercisehead{3} $f(x,y) = 3x^2 +y^2$; $x^2 + y^2 = 1$ \n\\[\n\\begin{gathered}\n  (\\nabla f)\\cdot y = |\\nabla f||y| \\cos{\\theta} \\\\\n  |\\nabla f| = \\sqrt{ 36x^2 + 4(1-x^2)} = \\sqrt{ 32 x^2 +4 } = 2 \\sqrt{ 8x^2 + 1}; \\quad |\\nabla f| \\text{ maximized when $x = \\pm 1 $ } \\\\\n  (\\pm 1,0), \\quad y \\parallel (\\pm 1,0)\n\\end{gathered}\n\\]\n\n\\exercisehead{4} $(1,2)$, $+2$ towards $(2,2)$; $-2$ towards $(1,1)$.  \n\\[\n\\begin{gathered}\n  \\nabla f(a) \\cdot y = \\nabla f(a) \\cdot (1,0) = 2; \\quad \\nabla f(a) \\cdot (0,-1) = -2 \\Longrightarrow \\nabla f(a) = 2(1,1) \\\\\n  \\nabla f(a) \\cdot \\frac{ (4,6) - (1,2) }{5} = \\nabla f (a) \\cdot (3,4)/5 = \\boxed{ \\frac{14}{5} }\n\\end{gathered}\n\\]\n\n\\exercisehead{5} $a,b,c$ s.t. $f(x,y,z) = axy^2 + byz + cz^2 x^3 $, \\quad $(1,2,-1)$\n\\[\n\\begin{gathered}\n  \\nabla f = (ay^2 + 3cz^2 x^2 , 2axy + bz, by + 2czx^3) \\\\\n  \\nabla f(1,2,-1) = (4a + 3c, 4a +-b, 2b - 2c ) \\\\\n  \\nabla f(1,2-1) \\cdot e_z = 2b - 2c = 64 \\Longrightarrow b-c = 32 \n\\end{gathered}\n\\]\n\\textbf{ Maximum value means $\\nabla f$ only has components in the $z$-direction}.\n\\[\n\\begin{aligned}\n  & \\partial_x f = 4a + 3c = 0  \\\\\n  & \\partial_y f = 4a - b = 0 \n\\end{aligned} \\quad \\quad \\quad \n\\boxed{ c=-8; \\quad b = 24; \\quad a =6 }\n\\]\n\n\\exercisehead{6} $f'(a,y) = 1$; $f'(a,z)=2$ where $y = 2i + 3j$, $z = i + j$\n\\[\n\\begin{aligned}\n  & (\\partial_x f)(2) + (\\partial_y f)(3) = 1 \\\\\n  & (\\partial_x f)(1) + (\\partial_y f)(1) = 2 \n\\end{aligned} \\quad \\quad \\quad \n\\begin{aligned}\n  & \\partial_y f = -3 \\\\\n  & \\partial_x f = 5\n\\end{aligned}\n\\]\n\n\\exercisehead{7} Let $f$ and $g$ denote scalar fields that are differentiable on an open set $S$.  \n\\begin{enumerate}\n  \\item \n\\[\n\\begin{gathered}\n  \\nabla f(a) = \\sum (\\partial_j f)(a) e_j \\\\\n  (\\partial_j f)(a) = f'(a_j e_j) \\\\\n  \\text{ if $f$ const., $f'(a;e_j) = 0$ } \\\\\n  \\Longrightarrow \\nabla f(a) = 0 \n\\end{gathered}\n\\]\nWe can also do the following: if $\\nabla f = 0$, $f'(a;y) = \\nabla f(a) \\cdot y = 0$, \\, $\\forall \\, y$.  Then, from Exercise 20 of Sec. 8.9, $f$ is constant on this open set $S$. \n\nIf $f$ is constant on $S$, $f(a+v) = f(a)$ for $f(a+v) = f(a) + T_a(v) + \\| v \\| E(a,v)$\n\\[\n\\begin{gathered}\n  T_a(y) = - \\| y \\| E(a,y) \\\\\n  E(a,y) \\to 0 \\text{ as } y\\to 0 \n\\end{gathered}\n\\]\nBy uniqueness of the total derivative, $\\nabla f(a) = 0$, \\, $\\forall \\, a \\in S$.  \n  \\item $\\nabla$ is a linear transformation.  $\\Longrightarrow \\nabla (f+g) = \\nabla f + \\nabla g$ \n  \\item $\\nabla$ is a linear transformation.  $\\Longrightarrow \\nabla (cf) = c \\nabla f $\n  \\item \n\\[\n\\begin{gathered}\n  (fg)(a+v) -(fg)(a) = \\nabla (fg)(a) \\cdot v + E_{fg}(a;v) = f(a+v)g(a+v) - f(a)g(a) = \\\\\n  \\begin{aligned}\n    & = f(a+v)g(a+v) - f(a)g(a+v) + f(a) g(a+v) - f(a)g(a) = \\\\ \n    & = g(a+v)(f(a+v) - f(a)) + f(a)(g(a+v) - g(a)) = \\\\\n    & = g(a+v) ( (\\nabla f)(a) + E_f(a;v) ) + f(a) ((\\nabla g) (a) + E_g(a;v) ) \n  \\end{aligned} \\\\\n\\text{ Let $\\| v \\| \\to 0$, so that $(\\nabla(fg))(a) = g(a) (\\nabla f)(a) + f(a) (\\nabla g)(a) $ }\n\\end{gathered}\n\\]\n  \\item \n\\[\n\\begin{gathered}\n\\begin{aligned}  \n  \\left( \\frac{f}{g} \\right)(a+v) - \\left(\\frac{f}{g} \\right)(a) & = \\frac{ f(a+v)}{ g(a+v)} - \\frac{ f(a) }{ g(a) } = \\frac{ g(a) f(a+v) - g(a+v)f(a) }{ g(a)g(a+v) } = \\\\\n  &  = \\frac{ g(a) f(a+v) - g(a) f(a) + g(a) f(a) - g(a+v)f(a) }{ g(a)g(a+v) } = \\\\\n  & = \\frac{ g(a) ( (\\nabla f)(a) \\cdot v + E_f(a;v) ) - f(a)( (\\nabla g)(a) \\cdot v + E_g (a;v) ) }{ g(a) g(a+v) } = \\\\\n  & = \\nabla \\left( \\frac{f}{g} \\right) \\cdot v + E_{f/g}(a;v) \n\\end{aligned} \\\\\n\\text{ Let $\\| v \\| \\to 0$  } \\Longrightarrow \\frac{ g(a) \\nabla f(a) - f(a) \\nabla g(a) }{ g^2(a) } = \\nabla \\left( \\frac{f}{g} \\right)(a) \n\\end{gathered}\n\\]\n\\end{enumerate}\n\n\\exercisehead{8} In $\\mathbb{R}^3$, let $r(x,y,z) = xi + yj + zk$, and let $r(x,y,z) = \\| r(x,y,z) \\|$\n\\begin{enumerate}\n\\item $\\nabla r = \\nabla \\sqrt{ x^2 + y^2 + z^2} = \\frac{1}{ \\sqrt{ x^2 + y^2 + z^2 }} (x,y,z) = \\frac{ \\vec{r}}{r}$\n\\item Use induction. \\[\n\\begin{aligned}\n  & \\nabla (r^2) = r \\frac{\\vec{r}}{r} + r \\frac{\\vec{r}}{r} = 2 \\vec{r} \\\\\n  & \\nabla (r^3) = 2\\vec{r} r + r^2 \\frac{ \\vec{r}}{r} = 3r \\vec{r} \\\\\n  &  \\nabla (r^{n+1}) = nr^{n-2} \\vec{r} r + r^{n-1} \\frac{\\vec{r}}{r} = (n+1) r^{n-1} \\vec{r}\n\\end{aligned}\n\\]\n\\item $n=0$.  $\\nabla (1) =0$\n\\[\n\\begin{aligned}\n  & \\nabla (r^{-1}) = \\nabla \\frac{1}{ \\sqrt{ x^2 + y^2 + z^2 } } = \\frac{-\\vec{r}}{r^2} \\\\\n  & \\nabla (r^{-2}) = \\nabla \\frac{1}{ x^2 + y^2 + z^2 } = (-2) \\vec{r} r^{-4} \n\\end{aligned}\n\\]\nThen $\\nabla (r^{n+1})  = (n+1) r^{n-1} \\vec{r}$, where we reuse the induction step above, because no reference was made to whether $n$ was positive or negative.  \\\\\n\\phantom{Then} So the formula is still valid when $n$ is a negative integer (by induction).  \n\\item $\\nabla f = \\vec{r}$\n\\[\n\\begin{gathered}\n  \\partial_x f = x \\quad \\, \\partial_y f = y \\quad \\, \\partial_z f = z \\\\\n  \\boxed{ \\frac{1}{2} x^2 + \\frac{1}{2} y^2 + \\frac{1}{2} z^2 =  f }\n\\end{gathered}\n\\]\n\\end{enumerate}\n\n\\exercisehead{9} Given $n$ independent vectors, $y_1, \\dots, y_n$, then by Thm., $y_1, \\dots, y_n$ for a basis for $\\mathbb{R}^n$.  \\medskip \\\\\n$f'(x,y) = \\nabla f(x) \\cdot y$, so $f'(x,y)$ is linear.  Then $\\forall \\, y \\in \\mathbb{R}^n$, $y=\\sum a_j y_j$ and \n\\[\nf'(x,y) = \\nabla f(x) \\cdot \\sum a_j y_j = \\sum a_j \\nabla f(x) \\cdot y_j = 0\n\\]\nThen from Exercise 20 of Sec. 8.9, $f$ is constant on $B(a)$.  \n\n\\exercisehead{10}\n\\begin{enumerate}\n\\item Consider $x \\in B(a)$, \\, $x = a + x'$.  \n\\[\n\\begin{gathered}\n  f'(x;y) = f'(a+x',y) = \\nabla f(x) \\cdot y \\\\\n  \\text{ Let } y = x' \\Longrightarrow f'(a+x';x') \\\\\n  \\text{ By mean value thm.}, f'(a+ \\theta x'; x') = f(a+x') - f(a) \\\\\n  f'(a+x';x') = \\nabla f(x) \\cdot x' = 0 \\Longrightarrow f(a+x') = f(a) \n\\end{gathered}\n\\]\nThis must be true $\\forall \\, x'$ s.t. $|x'| < r$ for $B(a;r)$.  Then $f$ is constant on $B(a)$.\n\\item \\[\n\\begin{gathered}\n  \\lim_{h\\to 0} \\frac{ f(a+hy) - f(a)}{h} = f'(a;y) \\leq 0 \\\\\n  f'(a;y) = \\nabla f(a) \\cdot y = |\\nabla f(a)| |y| \\cos{\\theta} \\leq 0 \n\\end{gathered}\n\\]\nConsider when $\\frac{-\\pi/2} < \\theta < \\pi/2$, $|y| \\neq 0$.  Then $|\\nabla f(a)| = 0$.  \n\\end{enumerate}\n\n\\exercisehead{11} Consider the following six statements about a scalar field $f:S \\to \\mathbb{R}$, where $S \\subseteq \\mathbb{R}^n$ and $a \\in int{S}$.  \n\\begin{enumerate}\n  \\item \\begin{enumerate}\n\\item $f$ continuous at $a$ \n\\item $f$ is differentiable at $a$\n\\item $\\exists \\, f'(a,y)$ \\, $\\forall \\, y \\in \\mathbb{R}^n$.  \n\\item All the first-order partial derivatives of $f$ exist in a neighborhood of $a$ and are continuous at $a$.  \n\\item $\\nabla f(a) =0 $\n\\item $f(x) = \\| x - a\\|$ for all $x$ in $\\mathbb{R}^n$.  \n\\end{enumerate}\n\\end{enumerate}\n\n(b) imples (a),(c), because differentiability implies continuity and differentiability through the total derivative gave what the directional derivative would be $\\forall \\, y \\in \\mathbb{R}^n$.  (d) imples (a),(b),(c) because (d), by theorem, is a sufficient condition for differentiability, and thus differentiability implies (a),(c).  (e) doesn't tell us anything because we need a scalar function $E(a;v)$ as well for differentiability.  (f) is a continuous function, so (f) imples (a).  \n\n%-----------------------------------%-----------------------------------%-----------------------------------\n\\section*{ 8.17 Exercises - A chain rule for derivatives of scalar fields, Applications to geometry.  Level sets.  Tangent planes. }\n%-----------------------------------%-----------------------------------%-----------------------------------\n\n\\exercisehead{1} \n\\begin{enumerate}\n\\item \\[ \\begin{aligned}\n  & u = f(x,y) \\\\\n  & u = F(t)\n\\end{aligned} \\quad \\quad \\quad \\begin{aligned} \n  x & = X(t) \\\\\n  y & = Y(t) \n\\end{aligned} \\] \\\\\n  \\[\n\\nabla f(r) \\cdot r'(t) = (\\partial_x f) x' + (\\partial_y f)y' = F'(t) = u'\n\\]\n\\item \n\\[\n\\begin{aligned}\n  & F(t) = u = f(x,y) = f(r(t)) \\\\\n  & F'(t) = \\nabla f(r) \\cdot r'(t) = (\\partial_x f) x' + (\\partial_y f) y' \n\\end{aligned}\n\\]\n\\[\n\\begin{gathered}\n  \\nabla f(r) = \\nabla f(r(t)) \\\\\n  \\frac{d}{dt} \\nabla f(r(t)) = \\frac{d}{dt} (\\partial_x f, \\partial_y f) = ((\\partial_{xx}^2 f) x' + (\\partial_{yx}^2 f) y', (\\partial_{xy}^2 f) x' + (\\partial_{yy}^2 f) y' ) \\\\\n  \\begin{aligned}\n    F''(t) & = \\left( \\frac{d}{dt} \\nabla f(r(t)) \\right) \\cdot r'(t) + \\nabla f(r) \\cdot r''(t) = \\\\\n    & = (\\partial_{xx}^2 f) x'^2 + \\left( (\\partial^2_{yx} f) + \\partial^2_{xy} f \\right) x'y' + (\\partial_{yy}^2 f) y'^2 + (\\partial_x f) x'' + \\partial_y f y''\n  \\end{aligned}\n\\end{gathered}\n\\]\n\\end{enumerate}\n\n\\exercisehead{2}\n\\begin{enumerate}\n\\item $f(x,y) = x^2 +y^2$, \\quad $X(t) = t, Y(t) = t^2$ \n\\[\n\\begin{aligned}\n  \\partial_x f & = 2x \\\\\n  \\partial_y f & = 2y \n\\end{aligned} \\quad \\quad \\quad \n\\begin{aligned}\n  X' & = 1 \\\\\n  Y' & = 2t \n\\end{aligned}\n\\]\n\\[\n\\begin{aligned}\n  & F'(t) = 2x (1) + 2y 2t = 2t + 4 t^3 \\\\\n  & F''(t) = 2 + 12 t^2 \n\\end{aligned}\n\\]\n\\item $f(x,y) = e^{xy} \\cos{(xy^2)}$; $X(t) = \\cos{t}$, $Y(t) = \\sin{t}$\n\\[\n\\begin{aligned}\n  & \\partial_x f = y f + -e^{xy} \\sin{(xy^2)} y^2 \\\\\n  & \\partial_y f = xf + -e^{xy} \\sin{(xy^2)} 2yx\n\\end{aligned} \\quad \\quad \\quad \n\\begin{aligned}\n  & X' = -s = -y \\\\\n  & Y' = c= x \n\\end{aligned} \\quad \\quad \\quad \n\\begin{aligned}\n  X'' & = -c = -x \\\\\n  Y'' &= -s = - y\n\\end{aligned}\n\\]\n\\[\nF'(t) = -y^2 f + e^{xy} \\sin{(xy^2)}y^3 + x^2 f + -e^{xy} \\sin{(xy^2)} 2yx^2 \n\\]\n\\emph{ This is the answer I got}.  Note that I tried it 2 ways: using the formula $(\\partial_{xx}^2 f) x'^2 + (\\partial_{yx}^2 f + \\partial_{xy}^2 f )x'y' + (\\partial^2_{yy} f) y'^2 + (\\partial_x f) x'' + (\\partial_y f) y''$, and second, taking our answer $F'(t) = G(t)$ and then applying $\\partial g_x x' + \\partial g_y y'$ on it (which seemed clever).    \n\\[\n\\begin{gathered}\n  \\begin{aligned}\n    \\partial_x g & = 4xf + (2x^2 - 1)( yf - y^2 e^{xy} \\sin{(xy^2)} ) + (3y^3 - 2y )y e^{xy} \\sin{(xy^2) } + (3y^3 - 2y)e^{xy} \\cos{(xy^2)} y^2 = \\\\\n    & = 4xf + 2x^2 y f - yf - 2x^2 y^2 e^{xy} \\sin{(xy^2)} + y^2 e^{xy} \\sin{(xy^2)} + 3y^4 e^{xy} \\sin{(xy^2)} -2y^4 e^{xy} \\sin{(xy^2)} + 3y^5 f - 2y^3 f \\\\\n    & = f(4x  + 2x^2 y - y +3y^5 - 2y^3) + e^{xy} \\sin{(xy^2)} ( -2x^2 y^2 + y^2 + y^4) \n  \\end{aligned} \\\\\n\\begin{aligned}\n  \\partial_y g & = (2x^2 - 1)( xf - 2yx e^{xy} \\sin{ (xy^2)} ) + (9y^2 - 2) e^{xy} \\sin{(xy^2) } + (3y^3 - 2y ) e^{xy} x \\sin{(xy^2 )} + (3y^3 - 2y) e^{xy} \\cos{(xy^2) } 2yx = \\\\\n  &= (2x^3 - x + 6y^4 x - 4y^2 x ) f + e^{xy} \\sin{(xy^2)} (-2yx (2x^2-  1) + 9y^2 - 2 + 3y^3 x - 2yx)\n\\end{aligned}\n\\end{gathered}\n\\]\n\\begin{multline*}\n  \\partial_x g x' + \\partial_y g y'  = (-12 y^5 + 14 y^3 - 4y + 7x - 9x^3 ) e^{xy} \\sin{(xy^2)} + f (9x^6 - 11 x^4 + 3x^2 - 4xy)\n\\end{multline*}\n\\item $f(x,y) = \\log{ \\left( \\frac{(1+e^{x^2} ) }{ 1 + e^{y^2} } \\right) } = \\log{ (1 + e^{x^2 }) } - \\log{ (1 + e^{y^2 } )}$ \n\\[\n\\begin{aligned}\n  X(t) & = e^t \\\\\n  Y(t) & = e^{-t} \n\\end{aligned} \\quad \\quad \n\\begin{aligned}\n  X' & = X \\\\\n  Y' & = -Y \n\\end{aligned} \\quad \\quad \n\\begin{aligned}\n  X'' & = X \\\\\n  Y'' & = Y \n\\end{aligned}\n\\]\n\\[\n\\begin{aligned}\n  & \\partial_x f = \\frac{1}{ 1 + e^{x^2 } } ( 2xe^{x^2 } ) \\\\\n  & \\partial_y f = \\frac{ - 2y e^{y^2 }}{ 1 + e^{y^2 } } \n\\end{aligned} \\quad \\quad \\quad \nF'(t) = \\boxed{ \\frac{ 2x^2 e^{x^2 }}{ 1 + e^{x^2 } } + \\frac{ 2 y^2 e^{y^2 }}{ 1 + e^{y^2 } } }\n\\]\n\\[\n\\begin{aligned}\n  & \\partial_{xx} f = (2) \\left( \\frac{ (e^{x^2 } + 2x^2 e^{x^2 } )( 1 + e^{x^2 }) - (2x e^{x^2 }) ( xe^{x^2 }) }{ (1+ e^{x^2 })^2 } \\right) = (2) \\left( \\frac{ e^{x^2 } + 2 x^2 e^{x^2 } + e^{2x^2 } }{ ( 1 + e^{x^2 })^2 } \\right) \\\\\n  & \\partial_{yy} f = (-2) \\left( \\frac{ e^{y^2} + 2y^2 e^{y^2} + e^{2y^2 } }{ (1+e^{y^2})^2 } \\right) \\\\\n  & \\partial_{xy} f = 0 \n\\end{aligned}\n\\]\n\\begin{multline*}\n  (\\partial_{xx}^2 f) x'^2 + ((\\partial_{yx}^2 f + \\partial_{xy}^2 f) x' y' + (\\partial_{yy}^2 f ) y'^2 + (\\partial x f) x'' + \\partial y f y'' = \\\\\n  = (2) \\frac{ e^{x^2} + 2x^2 e^{x^2 } + e^{2x^2 } }{ (1+e^{x^2})^2 } (x^2 ) + (-2) \\frac{ e^{y^2 } + 2y^2 e^{y^2 } + e^{2y^2 } }{ (1+e^{y^2} )^2 } y^2 + \\frac{ 2x e^{x^2 }(1+e^{x^2 }) }{ (1+e^{x^2 })^2 } x + \\frac{ -2y e^{y^2} ( 1 + e^{y^2 }) }{ ( 1 + e^{y^2 })^2 } y = \\\\\n  = \\boxed{ \\frac{ 4x^2 e^{x^2 } ( 1 + x^2 + e^{x^2 } ) }{ (1+e^{x^2})^2 } + \\frac{ -4 y^2 e^{y^2} ( 1 + y^2 + e^{y^2} ) }{ (1+e^{y^2})^2 }  }\n\\end{multline*}\n\\end{enumerate}\n\n\\exercisehead{3}\n\\begin{enumerate}\n\\item \n\\[\n\\begin{gathered}\n  \\nabla f = (3,-5,2) \\\\\n  N = (2x, 2y, 2z) = 2r \\\\\n  \\nabla f \\cdot \\frac{ (2,2,1) }{3 } = (3,-5,2) \\cdot (2,2,1)/3 = \\boxed{ -2/3} \n\\end{gathered}\n\\]\nIt should be noted that the normal to a sphere is the position vector.  \n\\item \\[\n\\begin{gathered}\n  \\nabla f = (2x,-2y,0) \\\\\n  x^2 + y^2 + z^2 = 4 \\text{ is a sphere } \\\\\n  \\nabla f \\cdot \\frac{ (x,y,z)}{r} = \\frac{2x^2  -2y^2 }{r}\n\\end{gathered}\n\\]\n\\item $x^2 + y^2 = 25$ and $2x^2 + 2(z^2 - x^2) - z^2 = 25$\n\\[\n\\begin{gathered}\n  \\nabla f = (2x,2y,-2z) \\\\\n  T = \\frac{ (1, \\frac{ \\mp x }{ \\sqrt{ 25 - x^2 } }, 0  ) }{ \\sqrt{ 1 + \\frac{ x^2 }{ 25 - x^2 } } } = \\frac{ \\left( 1 , \\frac{ \\mp x }{ \\sqrt{ 25 - x^2 } }, 0 \\right) }{ \\sqrt{ 25 /(25-x^2 ) } } = \\left( \\frac{ \\sqrt{ 25 - x^2 }}{5} , \\frac{ \\mp x }{ 5}, 0 \\right) \\\\\n  \\Longrightarrow \\nabla f \\cdot T = \\left( \\frac{ 2x \\sqrt{ 25 - x^2 }}{5} , \\frac{ -2 \\sqrt{ 25 -x^2 } x }{5 }, 0 \\right) = \\left( \\frac{ 6 }{5} 4 , \\frac{ -2 (4) 3 }{ 5 }, 0 \\right) = \\left( \\frac{ 24}{5} + \\frac{-24}{5} + 0 \\right) =0 \n\\end{gathered}\n\\]\n\\end{enumerate}\n\n\\exercisehead{4} \n\\begin{enumerate}\n  \\item Find a vector $V(x,y,z)$ normal to the surface\n\\[\nz = \\sqrt{ x^2 +y^2} + (x^2 + y^2)^{3/2}\n\\]\nat a general point $(x,y,z)$ of the surface, $(x,y,z) \\neq (0,0,0)$ \\medskip \\\\\n\\[\n\\begin{gathered}\n  0 = \\sqrt{ x^2 + y^2 } + (x^2 + y^2)^{3/2} -z = f(r) \\\\\n  \\Longrightarrow \\nabla f = \\left( \\frac{ x}{\\sqrt{ x^2 +y^2 } } + 3x(x^2 + y^2)^{1/2}, \\frac{y}{\\sqrt{ x^2 + y^2 }} + 3y (x^2 + y^2)^{1/2}, -1 \\right)\n\\end{gathered}\n\\]\n\\item \\[\n\\begin{gathered}\n  \\nabla f \\cdot e_z = |\\nabla f| \\cos{\\theta_z} \\Longrightarrow \\cos{\\theta_z} = \\frac{-1}{ \\sqrt{ \\frac{ (x+3x^3 + 3xy^2 )^2 }{ x^2 + y^2} + \\frac{ (y + 3yx^2 + 3y^3 )^2 }{ x^2 + y^2 } + 1 } } \\\\\n  \\cos{ \\theta_z} = \\frac{ -1 }{ \\sqrt{ (1 + 3(x^2 + y^2))^2 + 1 } }\n\\end{gathered}\n\\]\n\\[\n\\begin{gathered}\n\\lim_{y \\to 0} \\cos{\\theta_z} = \\frac{-1}{ \\sqrt{ ( 1 + 3 (x^2))^2 + 1 } } \\xrightarrow{ x \\to 0} = \\frac{-1}{\\sqrt{2}} \\\\\n\\lim_{x\\to 0} \\lim_{y\\to 0} \\cos{\\theta_z} = \\boxed{ \\sqrt{-1}{\\sqrt{2}} }\n\\end{gathered}\n\\]\n$\\cos{\\theta_z}$ is differentiable at $(x,y) = (0,0)$ (we can observe that the partial derivatives exist and are continuous at $(0,0)$), so $\\cos{\\theta_z}$ is continuous at $(x,y) = (0,0)$.  \n\\end{enumerate}\n\n\\exercisehead{5} $\n\\begin{aligned}\n  & e^u \\cos{v} = x \\\\\n  & e^u \\sin{v} = y \n\\end{aligned}  $ \\quad \\quad \\, $\\begin{aligned}\n  & u = u(x,y) \\\\\n  & v = v(x,y) \n\\end{aligned}$ \n\\[\n\\begin{aligned}\n  x^2 + y^2 & = e^{2u} \\\\\n  \\ln{ (x^2 + y^2) } & = 2u \n\\end{aligned}  \\Longrightarrow \\boxed{ \\frac{1}{2} \\ln{(x^2 + y^2)} = u } \\quad \\quad \\quad \\begin{aligned}\n  \\sin{v} & = \\frac{ y}{\\sqrt{ x^2 + y^2 } } \\\\\n   \\cos{v} & = \\frac{x}{\\ sqrt{ x^2 + y^2 } } \n\\end{aligned} \\Longrightarrow \\tan{v} = \\frac{y}{x} \n\\]\n\\[\n\\begin{aligned}\n  & \\nabla U = \\left( \\frac{x}{ x^2 + y^2 } , \\frac{y}{ x^2 + y^2 } \\right) \\\\\n  & \\nabla V = \\left( \\frac{ -y/x^2 }{ 1 + (y/x)^2 }, \\frac{1/x}{ 1 + (y/x)^2 } \\right)\n\\end{aligned} \\Longrightarrow \\nabla U \\cdot \\nabla V = 0 \n\\]\n\n\\exercisehead{6} $f(x,y) = \\sqrt{ |xy|}$ \n\\begin{enumerate}\n\\item \\[\n\\begin{aligned}\n  & \\text{ if } x \\gtrless 0, \\, y \\gtrless 0, \\quad & f=(xy)^{1/2} \\quad & \\partial_x f = \\frac{1}{2} \\sqrt{ \\frac{y}{x}}  \\quad \\quad & \\partial_y f = \\frac{1}{2} \\sqrt{ \\frac{x}{y} } \\\\\n  & \\text{ if } x > 0, \\, y < 0 , \\quad & f= (x(-y))^{1/2} \\quad & \\partial_x f = \\frac{1}{2} \\left( \\frac{|y|}{x} \\right)^{1/2} \\quad & \\partial_y f = \\frac{-1}{2} \\left( \\frac{x}{|y|} \\right)^{1/2} \\\\\n  & \\text{ if } x <0, \\, y > 0, \\quad & f = (-xy)^{1/2} \\quad & \\partial_x f = \\frac{-1}{2} \\left( \\frac{y}{|x|} \\right)^{1/2} \\quad & \\partial_y f = \\frac{1}{2} \\left( \\frac{|x|}{y} \\right)^{1/2}\n\\end{aligned}\n\\]\n\\item Does the surface $z= f(x,y)$ have a tangent plane at the origin?\n\\[\n\\begin{gathered}\n  z = f(x,y) \\\\\n  g = f(x,y) -z \\Longrightarrow \\nabla g = (\\partial_x f, \\partial_y f,-1)\n\\end{gathered}\n\\]\nFor $x=y$,\n\\[\n\\nabla g(0,0,0) = \\left( \\frac{1}{2}, \\frac{1}{2}, -1 \\right)\n\\]\nBut when approaching from the $x$ or $y$ axis, $\\nabla g = (0,0,-1)$.  A tangent plane cannot be defined at the origin.  \n\\end{enumerate}\n\n\\exercisehead{7} Given surface $z = xy$, $z = y_0 x,\\, y = y_0$ and $z = x_0 y, \\, x = x_0$ intersect at $(x_0,y_0, z_0)$ and lie on the surface.  We want to show that the tangent plane to this surface at $(x_0,y_0,z_0)$ contains these 2 lines.  \n\nNote that the 2 lines could be reexpressed in vector form:\n\\[\n\\begin{gathered}\n  x (1,0,y_0) + (0,y_0,0) \\\\\n  y(0,1,x_0) + (x_0,0,0) \n\\end{gathered}\n\\]\nRewrite the surface equation so to get the gradient\n\\[\n\\begin{gathered}\n  0 = xy - z \\\\\n  \\nabla f = (y,x,-1) \n\\end{gathered}\n\\]\n\\[\n\\begin{gathered}\n\\begin{aligned}\n  & \\nabla f(r_0) = (y_0,x_0,-1) \\\\\n  & \\nabla f(r_0) \\cdot (x,y,z) = y_0 x + x_0 y - z = x_0 y_0 \n\\end{aligned} \\\\\n\\nabla f(r_0) \\cdot (1,0,y_0) = \\nabla f(r_0) \\cdot (0,1,x_0) = 0  \\text{ and note that } \\begin{aligned}\n  & (0,y_0,0) \\in S \\\\\n  & (x_0,0,0) \\in S\n\\end{aligned}\n\\end{gathered}\n\\]\nSo indeed, the tangent plane contains these lines.  \n\n\\exercisehead{8} $xyz = a^3$  $(x_0,y_0, z_0)$, $\\nabla f = (yz, xz, xy)$\n\\[\ny_0 z_0 x + x_0 z_0 y + x_0 y_0 z = 3a^3\n\\]\nVolume of the tetrahedron: \n\\[\nV = \\frac{1}{3} B h = \\frac{1}{3} \\left( \\frac{1}{2} x y \\right) h = \\frac{1}{6} xyz = \\frac{1}{6} (3x_0)(3y_0)(3z_0) = \\boxed{ \\frac{9a^3}{2} }\n\\]\n\n\\exercisehead{9} We want a pair of linear Cartesian equations for the line tangent to $x^2 +y^2 +2z^2 = 4$, $z = e^{x-y}$ at pt. $(1,1,1) = P_1$\n\nWe calculate the gradients for the 2 surfaces, so to get the normal to these surfaces.  \n\\[\n\\begin{gathered}\n  \\nabla f= (2x,2y,4z) \\quad \\quad \\quad \\nabla g = (e^{x-y}, -e^{x-y}, -1 ) \\\\\n  \\xrightarrow{ (1,1,1) } \\nabla f(1,1,1) = 2(1,1,2) \\quad \\quad \\quad \\nabla g(1,1,1) = (1,-1,-1)\n\\end{gathered}\n\\]\nWe know the general form of the equation for the line with these normals, $N$, will be $X\\cdot N = X\\cdot P_1$.  Then\n\\[\n\\boxed{ \\begin{gathered}\n    x - y -z = -1 \\\\\n    x + y+ 2z =4 \n\\end{gathered} }\n\\]\n\n\\exercisehead{10} Find a constant $c$ s.t. at any pt. of intersection, the corresponding tangent planes will be $\\perp$ to each other. \n\\[\n\\begin{gathered}\n\\begin{aligned}\n  & (x-c)^2 + y^2 + z^2 = 3 \\\\\n  & x^2 + (y-1)^2 + z = 1 \n\\end{aligned} \\quad \\quad \\quad \n\\begin{aligned}\n  & \\nabla f = 2 (x-c, y,z) \\\\\n  & \\nabla g = 2 (x,y-1,z)\n\\end{aligned} \\\\\n\\text{ tangent planes are $\\perp$ to each other } \\Longrightarrow \\nabla f \\cdot \\nabla g  = x(x-c) + y(y-1) + z^2 = x^2 - xc + y^2 -y + z^2 = 0 \\\\\n\\Longrightarrow y = xc\n\\end{gathered}\n\\]\nWe have the intersection condition, and so solving for the system of 2 linear equations, with $y=xc$, \n\\[\n\\boxed{ c = \\pm \\sqrt{3}}\n\\]\n\n\\exercisehead{11} Without loss of generality, choose the origin to make the ellipse symmetrical and the major axis to lie on the $x$ axis. \n\\[\n\\begin{gathered}\n  R = (x,y) \\\\\n  \\begin{aligned}\n    F_1 & = (ae,0) \\\\\n    F_2 & = (-ae,0) \n  \\end{aligned} \\quad \\quad \\, \\begin{aligned}\n    & |R- F_1| = r_1 = \\sqrt{ (x-ae)^2 + y^2 } \\\\\n    & |R-F_2| = r_2 = \\sqrt{ (x+ae)^2 + y^2 }\n\\end{aligned} \\quad \\quad \\begin{aligned}\n    & R - F_1 = (x-ae,y) \\\\ \n    & R - F_2 = (x+ae,y) \n\\end{aligned} \\\\\n\\begin{aligned}\n  & \\nabla |R-F_1| = \\frac{ (x-ae, y) }{ \\sqrt{ (x-ae)^2 + y^2 } } = \\frac{ R-F_1}{r_1} \\\\\n  & \\nabla |R- F_2| =  \\frac{ (x+ae,y) }{ \\sqrt{ (x+ae)^2 + y^2 } } =  \\frac{ R-F_2}{r_2} \n\\end{aligned}\n\\end{gathered}\n\\]\n\\[\n\\begin{gathered}\n  r_1 + r_2 = K \\\\\n  \\frac{ x^2}{a^2} + \\frac{y^2}{b^2} = 1 \\quad \\quad \\, \\begin{aligned}\n    & y^2 = b^2 \\left( 1 - \\frac{x^2}{a^2} \\right) \\\\\n    & y = \\pm b \\sqrt{ 1 - \\frac{x^2}{a^2} }\n  \\end{aligned} \\quad \\quad \\, \\frac{dy}{dx} = \\frac{ \\mp bx/a^2}{ \\sqrt{ 1 - (x/a)^2 }} = \\frac{-b^2}{a^2} \\frac{x}{y} \\\\\nR' = (1, \\frac{-b^2}{a^2 } \\frac{x}{y} )\n\\end{gathered}\n\\]\n\\[\nR' \\cdot \\nabla (|R-F_1| + |R-F_2|) = R' \\cdot \\left( \\frac{R - F_1}{r_1} + \\frac{R-F_2}{r_2} \\right) = \\frac{ R' \\cdot kR + R' \\cdot( -F_1 r_2 - F_2 r_1 ) }{ r_1 r_2 } \n\\]\nConsider $R' \\cdot k R + r_2 (-F_1 \\cdot R') - r_1 (R'\\cdot F_2) = K (x -\\frac{b^2}{a^2} x ) + r_2 (-ae) - r_1 (-ae)$\n\\[\n\\begin{gathered}\n  r_{1,2} = \\sqrt{ (x \\mp ae)^2 + b^2 - \\frac{b^2 x^2}{a^2} } = \\sqrt{ x^2 \\mp 2xae + a^2 e^2 + b^2 - \\frac{b^2 x^2}{a^2} } = \\sqrt{ e^2 x^2 \\mp 2xae + a^2 } = a \\mp xe \\\\\n  \\begin{aligned}\n    & r_2 - r_1 = 2xe \\\\\n    & r_2 + r_1 = 2a \n  \\end{aligned} \\\\\n  \\Longrightarrow R'\\cdot kR + r_2 (-F_1 \\cdot R') - r_1 (R' \\cdot F_2) = 2ax e^2 + (-ae)(2xe) = 0 \n\\end{gathered}\n\\]\nThus $T\\cdot (\\nabla r_1 + r_2 ) = 0$.  This means that $T\\cdot \\nabla r_1 = -T\\cdot \\nabla r_2$.  As we had shown above, $\\nabla r_{1,2}$ is in the direction from the respective foci to the arbitrary point $(x,y)$ and both $\\nabla r_1$ and $\\nabla r_2$ are of length $1$.  Thus $T\\cdot \\nabla r_1 = -T \\cdot \\nabla r_2$ geometrically says that the angle between $\\nabla r_1$ and the tangent line is equal to the angle between $\\nabla r_2$ and the tangent line.  \n\n\\exercisehead{12} $f=f(x,y,z)$\n\\[\n\\begin{gathered}\n  \\partial_z f = k_0 z \\Longrightarrow f = k_1 z^2 g(x,y) + h(x,y) \\\\\n  f(0,0,a) = k_1 a^2 g(0,0) + h(0,0) = f(0,0,-a)\n\\end{gathered}\n\\]\n\n\\section*{ 8.22 Exercises - Derivatives of vector fields, Differentiability implies continuity, The chain rule for derivatives of vector fields, Matrix form of the chain rule }\n\n\\exercisehead{1} Recall \n\\[\n(Dh(a))_{jk} = \\sum_{l=1}^n (Df(b))_{jl} (Dg(a))_{lk} = (\\partial_k h_j(a)) = \\sum_{l=1}^n (\\partial_l f_j(b)) (\\partial_k g_l(a))\n\\]\n\\begin{enumerate}\n\\item \\[\n\\begin{gathered}\n  \\partial_x f = \\partial_t F \\partial_x g \\Longrightarrow \\frac{ \\partial f}{\\partial x } = F'(g(x,y)) \\frac{ \\partial g}{\\partial x } \\\\\n  \\frac{\\partial f}{\\partial y} = F'(g(x,y)) \\frac{ \\partial g}{\\partial y}\n\\end{gathered}\n\\]\n\\item \\[\n  \\begin{aligned}\n    F(t) & = e^{\\sin{t}} \\\\\n    g(x,y) & = \\cos{ (x^2 + y^2) }\n  \\end{aligned} \n\\quad \\quad \\quad \\begin{aligned}\n  & \\frac{ \\partial f}{\\partial x} = -\\cos{t} e^{\\sin{t} } \\sin{(x^2 + y^2 )} 2x \\\\\n  & \\frac{ \\partial f}{ \\partial y } = -\\cos{t} e^{\\sin{t}} \\sin{(x^2 + y^2) } 2y \n\\end{aligned}\n\\]\n\\end{enumerate}\n\n\\exercisehead{2} Given\n\\[\n\\begin{aligned}\n  u & = \\frac{x-y}{2} \\\\\n  v & = \\frac{x+y}{2}\n\\end{aligned} \\quad \\quad \\quad \nf(u,v) \\to F(x,y), \\quad F(x,y) = f(u(x,y), v(x,y) )\n\\]\n\\[\n\\begin{aligned}\n  & \\partial_x F = \\partial_u f \\partial_x u + \\partial_v f \\partial_x v & = \\frac{1}{2} \\partial_u f + \\frac{1}{2} \\partial_v f \\\\\n  & \\partial_y F = \\partial_u f \\partial_y u + \\partial_v f \\partial_y v & = -\\frac{1}{2} \\partial_u f + \\frac{1}{2} \\partial_v f \n\\end{aligned}\n\\]\n\n\\exercisehead{3} Given \n\\[\nu = f(x,y) \\quad \\quad \n\\begin{aligned}\n  & x = X(s,t) \\\\\n  & y = Y(s,t)\n\\end{aligned} \\quad \\quad \\quad u = F(s,t) = f(x(s,t),y(s,t))\n\\]\n\\begin{enumerate}\n\\item \\[\n\\begin{aligned}\n  & \\partial_s F = \\partial_x f \\partial_s x + \\partial_y f \\partial_s y \\\\\n  & \\partial_t F = \\partial_x f \\partial_t x + \\partial_y f \\partial_t y\n\\end{aligned}\n\\]\n\\item To get to the second order partial derivatives, it seems that a direct application of the partial derivatives is needed: there's not a way to reformulate a matrix chain rule for second order partial derivatives, until maybe the Hessian matrix.  \n\\[\n\\begin{gathered}\n  \\partial_{ss}^2 f  = \\partial^2_{xs} F \\partial_s x + \\partial_x f \\partial_{ss}^2 x + \\partial_{ys}^2 F \\partial_s y + \\partial_y f \\partial_{ss}^2 y  \\medskip \\\\\n  \\begin{gathered}\n    \\partial_s f  = \\partial_x f \\partial_s x + \\partial_y f \\partial_s y  \\\\\n    \\begin{aligned}\n      \\Longrightarrow \\partial_{xs} f & = \\partial_{xx} f \\partial_s x + \\partial_x f \\partial_s \\partial_x x + \\partial_{xy} f \\partial_s y + \\partial_y f \\partial_s \\partial_x y = \\\\\n      & = \\partial_{xx} f \\partial_s x + \\partial_{xy} f \\partial_s y \n    \\end{aligned} \n  \\end{gathered} \\\\\n\\begin{aligned}\n  \\Longrightarrow \\partial_{ss}^2 f & = (\\partial_{xx}^2 f \\partial_s x + \\partial_{xy}^2 f \\partial_s y) \\partial_s x + \\partial_x f \\partial_{ss}^2 x + (\\partial_{yx}^2 f \\partial_s x + \\partial_{yy}^2 f \\partial_s y)\\partial_s y + (\\partial_y f)(\\partial_{ss}^2 y) = \\\\ \n  & = (\\partial_{xx}^2 f)(\\partial_s x)^2 + 2\\partial_{xy}^2 f \\partial_s y \\partial_s x + \\partial_{yy}^2 f (\\partial_s y)^2 + (\\partial_x f) \\partial_{ss}^2 x + (\\partial_y f)(\\partial_{ss}^2 y )\n\\end{aligned}\n\\end{gathered}\n\\]\n\\item By label symmetry:\n\\[\n\\partial_{tt}^2 f = (\\partial_{xx}^2 f)(\\partial_t x)^2 + 2\\partial_{xy}^2 f \\partial_t y \\partial_t x + \\partial_{yy}^2 f (\\partial_t y)^2 + (\\partial_x f) \\partial_{tt}^2 x + (\\partial_y f)(\\partial_{tt}^2 y )\n\\]\nLet's calculate $\\partial_{st}^2 F$\n\\[\n\\begin{aligned}\n  \\partial_{st}^2 F & = \\partial_{xs}^2 f \\partial_t x + \\partial_x f \\partial_{st}^2 x + \\partial_{ys}^2 f \\partial_t y + \\partial_y f \\partial_{st}^2 y = \\\\\n  & = (\\partial_{xx}^2 f \\partial_s x + \\partial_{xy}^2 f \\partial_s y) \\partial_t x + \\partial_x f \\partial_{st}^2 x + ( \\partial_{yx}^2 f \\partial_s x + \\partial_{yy}^2 f \\partial_s y ) \\partial_t y + \\partial_y f \\partial_{st}^2 y = \\\\\n  & = \\partial_{xx}^2 f \\partial_s x \\partial_t x + \\partial_{xy}^2 f ( \\partial_s y \\partial_t x + \\partial_s x \\partial_t y) + \\partial_{yy}^2 f \\partial_s y \\partial_t y + \\partial_x f \\partial_{st}^2 x + \\partial_y f \\partial_{st}^2 y \n\\end{aligned}\n\\]\n\\end{enumerate}\n\n\\exercisehead{4} \\begin{enumerate}\n  \\item \\[\n\\begin{gathered}\n  \\begin{aligned}\n    & X(s,t) = s +t \\\\\n    & Y(s,t) = st \n  \\end{aligned} \\quad \\quad \n\\begin{aligned}\n  & \\partial_s X = \\partial_t X = 1 \\\\\n  & \\partial_s Y = t \\quad \\partial_t Y = s \n\\end{aligned} \\quad \\quad \n  \\begin{aligned}\n    & \\partial_s F = \\partial_x f + t \\partial_y f \\\\\n    & \\partial_t F = \\partial_x f + s \\partial_y f \n\\end{aligned} \\\\\n  \\begin{aligned}\n    & \\partial_{ss}^2 f = (\\partial_{xx}^2 f) + 2 \\partial_{xy}^2 f t + \\partial_{yy}^2 f t^2 \\\\ \n    & \\partial_{tt}^2 f = (\\partial_{xx}^2 f) + 2 \\partial_{xy}^2 f s + \\partial_{yy}^2 f s^2 \\\\\n    & \\partial_{st}^2 f = \\partial_{xx}^2 f + \\partial_{xy}^2 f(t+s) + \\partial_{yy}^2 f ts \n  \\end{aligned}\n\\end{gathered}\n\\]\n  \\item \\[\n\\begin{gathered}\n  \\begin{aligned}\n    X(s,t) & = st \\\\\n    Y(x,t) & = s/t \n  \\end{aligned} \\quad \\quad \n\\begin{aligned}\n  & X_s = t \\\\\n  & X_t = s \n\\end{aligned} \\quad \\quad \n\\begin{aligned}\n  & Y_s = 1/t \\\\ \n  & Y_t = -s/t\n\\end{aligned} \\quad \\quad \n\\begin{aligned}\n  & \\partial_s F = \\partial_x f t + \\partial_y f (1/t) \\\\\n  & \\partial_t F = \\partial_x f s + \\partial_y f (-s/t^2) \n\\end{aligned} \\\\\n\\begin{aligned}\n  \\partial_{ss}^2 F & = (\\partial_{xx}^2 f)(t^2) + 2 \\partial_{xy}^2 f \\left( \\frac{1}{t} \\right) t + \\partial_{yy}^2 f (1/t)^2 \\\\\n  \\partial_{tt}^2 F & = (\\partial_{xx}^2 f)s^2 + 2 \\partial_{xy}^2 f \\left( \\frac{-s}{t} \\right) s + \\partial_{yy}^2 f \\left( \\frac{-s}{t^2} \\right)^2 \\\\\n  \\partial_{st}^2 F & = \\partial_{xx}^2 f ts + \\partial_{xy}^2 f \\left( \\frac{1}{t} s + t \\left( \\frac{-s}{t^2} \\right) \\right) + \\partial_{yy}^2 f \\frac{1}{t} \\left( \\frac{-s}{t^2 } \\right) + \\partial_x f + \\partial_y f \\left( \\frac{-1}{t^2} \\right) \n\\end{aligned}\n\\end{gathered}\n\\]\n  \\item \\[\n\\begin{gathered}\n  \\begin{aligned}\n    X(s,t) & = \\frac{s-t}{2} \\\\\n    Y(s,t) & = \\frac{s+t}{2} \n\\end{aligned} \\quad \\quad \\begin{aligned} x_s & = 1/2 \\\\ x_t & = -1/2 \\end{aligned} \\quad \\quad \\begin{aligned} Y_s & = 1/2 \\\\ Y_t & = 1/2 \\end{aligned} \\quad \\quad \\begin{aligned} \\partial_s F & = \\partial_x f 1/2 + \\partial_y f 1/2 \\\\ \\partial_t F & = \\partial_x f (-1/2) + \\partial_y f 1/2 \\end{aligned} \\\\ \n  \\begin{aligned}\n    \\partial_{ss}^2 F & = \\left(\\frac{1}{2} \\right) ((\\partial_{xx}^2 f + \\partial_{xy} f )1/2 + (\\partial_{yx}^2 f + \\partial_{yy}^2 ) 1/2) = \\frac{1}{4} (\\partial_{xx}^2 f + \\partial_{xy}^2 f + \\partial_{yx}^2 f + \\partial_{yy}^2 f ) \\\\\n    \\partial_{tt}^2 F & = \\frac{1}{4} (\\partial_{xx}^2 f - \\partial_{xy}^2 f - \\partial_{yx}^2 f + \\partial_{yy}^2 f ) \\\\\n    \\partial_{st}^2 F  & = \\frac{1}{4} ( -\\partial_{xx}^2 f + \\partial_{xy}^2 - \\partial_{yx}^2 f + \\partial_{yy}^2 f )\n  \\end{aligned}\n\\end{gathered}\n\\]\n\\end{enumerate}\n\n\\exercisehead{5} {\\large You cannot interchange $\\partial_x$ and $\\partial_r$, $\\partial_x$ and $\\partial_{\\theta}$, etc.}\n\\[\n\\begin{aligned}\n  \\partial_r \\phi & = \\partial_x f \\partial_r x + \\partial_y f \\partial_{\\theta} y = f_x c + f_y s \\\\\n  \\partial_{\\theta} \\phi & = \\partial_x f \\partial_{\\theta} x + \\partial_y f \\partial_{\\theta} y = -f_x rs + f_y rc\n\\end{aligned}\n\\]\nNotice that the above formulas give a prescription or algorithm for computing the $\\partial_r$ or $\\partial_{\\theta}$ of functions of $x,y$.  Notice also that $f_x, f_y$ are each composite functions.  \n\n\\[\n\\begin{aligned}\n  \\partial_{r\\theta}^2 \\phi & = \\partial_r (-f_x rs + f_y rc) = -\\partial_r f_x rs - f_x s + \\partial_r f_y fc + f_y c = \\\\\n  & = -(f_{xx} c + f_{yx} s) rs - f_x s + (f_{xy} c + f_{yy} s)rc + f_y c = \\\\\n  & = -f_{xx} rcs - f_{yx} r s^2 + f_{xy} rc^2 + f_{yy} rsc - f_x s + f_y c \n\\end{aligned}\n\\]\n\\[\n\\begin{aligned}\n  \\partial_{\\theta r}^2 \\phi & = \\partial_{\\theta} (f_x c + f_y s) = \\partial_{\\theta} f_x c - f_x s + \\partial_{\\theta} f_y s + f_y c = \\\\\n  & = (-f_{xx} rs + f_{yx} rc )c  -f_x s + (-f_{xy} rs + f_{yy} rc )s + f_y c = \\\\\n  & = -f_{xx} rsc + f_{yx} rc^2 - f_x s - f_{xy} rs^2 + f_{yy} rcs + f_y c \n\\end{aligned}\n\\]\n\\[\n\\begin{aligned}\n  \\partial_{rr}^2 \\phi & = \\partial_r (f_x c + f_y s) = \\\\\n  & = \\partial_r f_x c + \\partial_r f_y s = (f_{xx} c + f_{yx} s) c + (f_{xy}c + f_{yy} s) s = f_{xx} c^2 + f_{yx} sc + f_{xy} cs + f_{yy} s^2 \n\\end{aligned}\n\\]\n\n\\exercisehead{6} Given $u = f(x,y,z)$, $\\begin{aligned} x & = X(r,s,t) \\\\\n  y & = Y(r,s,t) \\\\\n  z & = Z(r,s,t) \n\\end{aligned}$ \\quad \\quad $u = F(r,s,t)$ \n\\[\n\\begin{aligned}\n  \\partial_r F & = \\partial_x F \\partial_r x + \\partial_y F \\partial_r y + \\partial_z F \\partial_r z \\\\\n  \\partial_s F & = \\partial_x F \\partial_s x + \\partial_y F \\partial_s y + \\partial_z F \\partial_s z \\\\\n  \\partial_t F & = \\partial_x F \\partial_t x + \\partial_y F \\partial_t y + \\partial_z F \\partial_t z \n\\end{aligned}\n\\]\n\n\\exercisehead{7}\n\\begin{enumerate}\n\\item Given $\\begin{aligned}\n  & X(r,s,t) = r + s+ t \\\\\n  & Y(r,s,t) = r + -2s+ 3t \\\\\n  & Z(r,s,t) = 2r + s+ -t \n\\end{aligned}$ \n\\[\n\\begin{aligned}\n  & \\partial_r F = \\partial_x F + \\partial_y F + 2 \\partial_z F \\\\ \n  & \\partial_s F = \\partial_x F + -2\\partial_y F +  \\partial_z F \\\\ \n  & \\partial_t F = \\partial_x F + 3 \\partial_y F - \\partial_z F  \n\\end{aligned}\n\\]\n\\item Given $\\begin{aligned}\n  & X(r,s,t)  = r^2  + s^2+ t^2 \\\\\n  & Y(r,s,t)  = r^2  - s^2- t^2 \\\\\n  & Z(r,s,t)  = r^2  - s^2+ t^2 \n\\end{aligned}$\n\\[\n\\begin{aligned}\n  & \\partial_r F = 2r(\\partial_x F + \\partial_y F +  \\partial_z F) \\\\ \n  & \\partial_s F = 2s (\\partial_x F + -\\partial_y F -  \\partial_z F) \\\\ \n  & \\partial_t F = 2t (\\partial_x F - \\partial_y F + \\partial_z F )\n\\end{aligned}\n\\]\n\\end{enumerate}\n\n\\exercisehead{8} $u = f(x,y,z)$ \\quad $\\begin{aligned}\n  x  & = X(s,t) \\\\\n  y & = Y(s,t) \\\\\n  z & = Z(s,t)\n\\end{aligned}$ \\quad $u = F(s,t)$ \n\\[\n\\begin{aligned}\n  & \\partial_s F = \\partial_x F \\partial_s X + \\partial_y F \\partial_s Y + \\partial_z F \\partial_s Z \\\\\n  & \\partial_t F = \\partial_x F \\partial_t X + \\partial_y F \\partial_t y + \\partial_z F \\partial_t Z\n\\end{aligned}\n\\]\n\n\\exercisehead{9}\n\\begin{enumerate}\n  \\item $\\begin{aligned}\n    & X(s,t) = s^2 + t^2 \\\\\n    & Y(s,t) = s^2 - t^2 \\\\\n    & Z(s,t) = 2st \n\\end{aligned}$ \\quad \\quad \\quad $\n\\begin{aligned}\n  & \\partial_s F = 2s(\\partial_x F + \\partial_y F) + 2t \\partial_z F \\\\\n  & \\partial_t F = 2t (\\partial_x F - \\partial_y F) + 2s \\partial_z F \n\\end{aligned}\n$\n  \\item $\\begin{aligned}\n    & X(s,t) = s + t \\\\\n    & Y(s,t) = s - t \\\\\n    & Z(s,t) = st    \n\\end{aligned}$ \\quad \\quad \\quad $\n\\begin{aligned}\n  & \\partial_s F = (\\partial_x F + \\partial_y F ) + t \\partial_z F \\\\\n  & \\partial_t F = (\\partial_x F - \\partial_y F) + s \\partial_z F\n\\end{aligned}$\n\\end{enumerate}\n\n\\exercisehead{10} Given $u = f(x,y)$; \\quad $\\begin{aligned}\n  & x = X(r,s,t) \\\\\n  & y = Y(r,s,t)\n\\end{aligned}$ \\quad $u = F(r,s,t)$ \\quad $\\Longrightarrow \\begin{aligned}\n  & \\partial_r F = \\partial_x F \\partial_r x + \\partial_y F \\partial_r y \\\\\n  & \\partial_s F = \\partial_x F \\partial_s x + \\partial_y F \\partial_s y \\\\ \n  &  \\partial_t F = \\partial_x F \\partial_t x + \\partial_y F \\partial_t y \\\\ \n\\end{aligned}$ \n\n\\exercisehead{11}  \\begin{enumerate}\n\\item Given $X(r,s,t) = r+s$, $Y(r,s,t) = t$ \\quad \\quad $\\Longrightarrow \\begin{aligned}\n  & \\partial_r F = \\partial_x F  \\\\\n  & \\partial_s F = \\partial_x F \\\\\n  & \\partial_t F = \\partial_y F\n\\end{aligned}$\n\\item Given $X(r,s,t) = r+s+t$, $Y(r,s,t) = r^2 + s^2 + t^2$ \\quad \\quad $\\Longrightarrow \\begin{aligned}\n  & \\partial_r F = \\partial_x F + \\partial_y F(2r) \\\\\n  & \\partial_s F = \\partial_x F + 2s \\partial_y F \\\\\n  & \\partial_t F = \\partial_x F + 2t \\partial_y F \n\\end{aligned}$\n\\item Given $X(r,s,t) = r/s$, $Y(r,s,t) = s/t$ \\quad \\quad $\\Longrightarrow \\begin{aligned}\n  & \\partial_r F = \\frac{1}{s} \\partial_x F \\\\\n  & \\partial_s F = \\partial_x F (-r/s^2) + \\partial_y F /t \\\\\n  & \\partial_t F = \\partial_y F (-s/t^2)\n\\end{aligned}$\n\\end{enumerate}\n\n\\exercisehead{12} $h(x) = f(g(x))$ \\quad \\, $g= (g_1,\\dots, g_n)$\n\\[\n\\nabla h(a) \\Longrightarrow \\partial_k h(a) = \\sum_{l=1}^n \\partial_l f \\partial_k g_l \\text{ or } \\nabla h(a) = \\sum_{l=1}^n \\partial_l f \\nabla g_l\n\\]\n\n\\exercisehead{13}\n\\begin{enumerate}\n\\item $f(x,y,z) = xi + yj +zk$\n\\[\nDf(x) = \\left[ \\begin{matrix} \\nabla f_x(x) \\\\ \\nabla f_y(x) \\\\ \\nabla f_z(x) \\end{matrix} \\right] = \\left[ \\begin{matrix} \n    \\partial_x f_x & \\partial_y f_x & \\partial_z f_x \\\\\n    \\partial_x f_y & \\partial_y f_y & \\partial_z f_y \\\\\n    \\partial_x f_z & \\partial_y f_z & \\partial_z f_z \n\\end{matrix} \\right] = \\left[ \\begin{matrix} 1 & & \\\\ & 1 & \\\\ & & 1 \\end{matrix} \\right]\n\\]\n\\item $f = (x+c_x, y+c_y, z+c_z)$ where $c_z, c_y, c_z$ are constants.  \n\\item \\[\n\\begin{gathered}\nDf(x) = \\left[ \\begin{matrix} \\nabla f_x(x) \\\\ \\nabla f_y(x) \\\\ \\nabla f_z(x) \\end{matrix} \\right] = \\left[ \\begin{matrix} \n    \\partial_x f_x & \\partial_y f_x & \\partial_z f_x \\\\\n    \\partial_x f_y & \\partial_y f_y & \\partial_z f_y \\\\\n    \\partial_x f_z & \\partial_y f_z & \\partial_z f_z \n\\end{matrix} \\right] = \\left[ \\begin{matrix} p(x) & & \\\\ & q(y) & \\\\ & & r(z) \\end{matrix} \\right] \\\\\n\\Longrightarrow f(x) = ((\\int p(x) dx + x_0), (\\int q(y) dy + y_0), (\\int r(z) dz + z_0 ) ) \\\\\n\\text{ where $x_0, y_0, z_0$ are constants. }\n\\end{gathered}\n\\]\n\\end{enumerate}\n\n\\exercisehead{14} Given $f: \\mathbb{R}^2 \\to \\mathbb{R}^2$, $g: \\mathbb{R}^3 \\to \\mathbb{R}^2$ \\quad $\\begin{aligned}\n  f(x,y) & = (e^{x+2y}, \\sin{(y+2x)}) \\\\\n  g(u,v,m) & = ((u+2v^2 + 3w^3), (2v- u^2) )\n\\end{aligned}$ \n\\begin{enumerate}\n\\item $Df(x,y), Dg(u,v,w)$ \\quad $\\Longrightarrow Df = \\left[ \\begin{matrix} e^{x+2y} & 2 e^{x + 2y} \\\\\n    2 \\cos{(y+2x)} & \\cos{(y+2x)} \\end{matrix} \\right]$ \\quad \\quad $Dg = \\left[ \\begin{matrix} 1 & 4v & 9w^2 \\\\ -2u & 2 & 0 \\end{matrix} \\right]$ \n\\item $h(u,v,w) = f(g(u,v,w))$\n\\[\n\\begin{aligned}\nf(g(u,v,w)) & = (e^{u + 2v^2 + 3w^3 + 2(2v - u^2) }, \\sin{( 2v - u^2 + 2(u + 2v^2 + 3w^3) ) } ) = \\\\\n& = (e^{u + 2v^2 + 3w^3 + 4v - 2u^2 }, \\sin{(2v - u^2 + 2u + 4v^2 + 6w^3 ) } ) \n\\end{aligned}\n\\]\n\\item \n\\[\n\\begin{gathered}\n  \\begin{aligned}\n  Dh & = Df Dg = \\left[ \\begin{matrix} e^{x+ 2y} & 2e^{x+2y} \\\\\n      2\\cos{ (y+2x)} & \\cos{(y+ 2x) } \n\\end{matrix} \\right]\\left[ \\begin{matrix} 1 & 4v & 9w^2 \\\\\n      -2u & 2 & 0 \\end{matrix} \\right] = \\\\\n  & = \\left[ \\begin{matrix} e^{x+2y} (1-4u) & e^{x+2y} (4v +4) & 9 w^2 e^{x+2y} \\\\\n      \\cos{(y+2x)} (2-2u) & \\cos{(y+2x) }(8v + 2) & 18 w^2 \\cos{(y+ 2x) } \\end{matrix} \\right] \n\\end{aligned} \\\\\n  Dh(1,-1,1) = \\left[ \\begin{matrix} -3 & 0 & 9 \\\\\n      0 & -6 \\cos{9} & 18 \\cos{9} \\end{matrix} \\right]\n\\end{gathered}\n\\]\n\\end{enumerate}\n\n\\exercisehead{15} Given \\\\\n$\\begin{aligned}\n  f & = ((x^2 + y + z),(2x + y+z^2)) \\\\\n  g & = (uv^2 w^2 , w^2 \\sin{v}, u^2 e^v )\n\\end{aligned}$\n\\begin{enumerate}\n\\item $Df = \\left[ \\begin{matrix} 2x & 1 & 1 \\\\ 2 & 1 & 2z \\end{matrix} \\right]$ \\quad \\quad $Dg = \\left[ \\begin{matrix} v^2 w^2 & 2uvw^2 & 2uv^2 w \\\\ \n    0 & w^2 \\cos{v} & 2w \\sin{v} \\\\ 2u e^v & u^2 e^v & 0 \\end{matrix} \\right]$ \n\\item \\[\n\\begin{aligned}\n  h(u,v,w) & = f[g(u,v,w)] = ((uv^2 w^2)^2 + w^2 \\sin{v} + u^2 e^v, 2uv^2 w^2 + w^2 \\sin{v} + u^4 e^{2v} ) = \\\\\n  & = (u^2 v^4 w^4 + w^2 \\sin{v} + u^2 e^v, 2uv^2 w^2 + w^2 \\sin{v} + u^4 e^{2v} )\n\\end{aligned}\n\\]\n\\item \\begin{multline*}\n  Dh(u,0,w) = \\left[ \\begin{matrix} 2x & 1 & 1 \\\\ 2 & 1 & 2z \\end{matrix} \\right]\\left[ \\begin{matrix} v^2 w^2 & 2uvw^2 & 2uv^2 w \\\\ 0 & w^2 \\cos{v} & 2w \\sin{v} \\\\ 2u e^v & u^2 e^v & 0 \\end{matrix} \\right] = \\\\\n  = \\left[ \\begin{matrix} 2xv^2 w^2 + 2u e^v & 4x uvw^2 + w^2 \\cos{v} + u^2 e^v & 4xu v^2 w + 2w \\sin{v} \\\\ 2v^2 w^2 + 4z ue^v & 4uvw^2 + w^2 \\cos{v} + 2z u^2 e^v & 4uv^2 w + 2w \\sin{v} \\end{matrix} \\right] = \\left[ \\begin{matrix} 2u & w^2 + u^2 & 0 \\\\ 4(u^3) & w^2 + 2u^4 & 0 \\end{matrix} \\right]\n\\end{multline*}\n\\end{enumerate}\n\n\\section*{ 8.24 Miscellaneous exercises - Sufficient conditions for the equality of mixed partial derivatives }\n\n\\exercisehead{2} $f = \\frac{ y (x^2 - y^2)}{ x^2 +y^2 }$.  \n\\[\nf_1 = (y) \\frac{ 2x (x^2 + y^2) - (2x)(x^2 - y^2) }{ (x^2 + y^2)^2} = \\frac{ 4 x^3 y}{ (x^2 +y^2)^2 }\n\\]\n\\[\nf_2 = \\frac{ ( (x^2 -y^2 ) - 2y^2 )(x^2 + y^2) - 2y^2 (x^2 - y^2 ) }{ (x^2 + y^2 )^2} = \\frac{ x^4 - 4 x^2 y^2 - y^4 }{ (x^2 +y^2 )^2 }\n\\]\n\\[\nD_{2,1} f= 4x^3 \\frac{ (x^2 +y^2)^2 - 2(x^2 + y^2 )( 2y) y }{ (x^2 +y^2)^4} = \\frac{ x^4 - 4x^2 y^2 - y^4}{ (x^2 +y^2)^2 }\n\\]\n\\[\n\\begin{aligned}\n  D_{1,2} f & = \\frac{ (4x^3 - 8xy^2) (x^2 + y^2)^2 - 2(x^2 + y^2) (2x) ( x^4 - 4x^2 y^2 - y^4) }{ (x^2 +y^2)^4 }  = \\\\\n  & = \\frac{ 4x(x^2 - 2y^2)(x^2 + y^2) - 4x (x^4 - 4x^2 y^2 - y^4) }{ (x^2  +y^2)^3}  = \\frac{ 4xy^2 ( 3x^2  -y^2) }{ (x^2  +y^2)^3 }\n\\end{aligned}\n\\]\nFrom the above results, clearly,\n\\[\n\\lim_{x \\to 0} f_1 =  0, \\quad \\, \\lim_{y\\to 0} f_1 = 0 \n\\]\nSo that $\\boxed{ f_1(0,0) = 0 }$, while\n\\[\n\\lim_{x \\to 0 } f_2 = -1 \\quad \\, \\lim_{y\\to 0} f_2 =  1 \n\\]\nso $f_2(0,0)$ undefined.  \n\n\\[\n\\lim_{x \\to 0} f_{12} =0 \\quad \\, \\lim_{ y\\to 0} f_{12} = 0 \n\\]\nso that $\\boxed{ f_{12}(0,0)= 0}$, but\n\\[\n\\lim_{x\\to 0} f_{21} =0 \\quad \\, \\lim_{y \\to 0} f_{21} = \\frac{4x^3}{x^4} = \\frac{4}{x} \\xrightarrow{ x\\to 0} \\infty\n\\]\n\n\\exercisehead{3} Given $f(x,y) = \\frac{ xy^3 }{ x^3 + y^6 }$ if $(x,y) \\neq (0,0)$, $f(0,0) = 0$\n\\begin{itemize}\n\\item[a.]\n\\[\n\\begin{aligned}\n  f'(0;a) & = \\lim_{h\\to 0} \\frac{ f(x+ha) - f(x)}{h} = \\lim_{h\\to 0 } \\frac{f(ha) - f(0) }{ h } = \\lim_{h\\to 0} \\left( \\frac{ h a_x h^3 a_y^3 }{ h^3 a_x^3 + h^6 a_y^6 } \\right)/h = \\lim_{h\\to 0} \\frac{ h^3 a_x a_y^3 }{ h^3 a_x^3 + h^6 a_y^6 } = \\\\\n    & = \\lim_{h\\to 0} \\frac{ a_x a_y^3 }{ a_x^3 + h^3 a_y^6} = \\frac{ a_y^3}{a_x^2 }\n\\end{aligned}\n\\]\nSo $f'(0;a) = \\frac{ a_y^3}{a_x^2 }$ if $a_x \\neq 0$, $f'(0;a) = 0$ if $a_x = 0$\n\\item[b.] If $x=y^2$, then \n\\[\nf(x,y) = \\frac{ xy^3}{x^3 + y^6} = \\frac{ y^5 }{ 2y^6} = \\frac{1}{ 2y} \\xrightarrow{ y\\to 0 } \\infty \\text{ not } 0\n\\]\nSo $f(x,y)$ is not continuous at $(0,0)$.  \n\\end{itemize}\n\n\\exercisehead{4} $f(x,y) = \\int_0^{\\sqrt{xy}} e^{-t^2} dt$ for $x>0$; $y>0$.  \\\\\nLet $u = u(x,y) = \\sqrt{ xy}$ and then we can use chain rule.  \n\\[\n\\partial_x f = \\partial_u f \\partial_x u = \\boxed{ e^{-xy} \\frac{1}{2} \\sqrt{ y/x} } \\quad \\quad \\partial_y f = e^{-xy} \\frac{1}{2} \\sqrt{ x/y} \\text{ by label symmetry }\n\\]\n\n\\exercisehead{5} Given $u = f(x,y)$; $\\begin{aligned}\n  x & = x(t) \\\\\n  y & = y(t) \n\\end{aligned}$ and $u=F(t)$.  \n\\[\n\\begin{aligned}\n  F'(t) & = (\\partial_x u) x' + (\\partial_y u )y' =  x' u_x + y' u_y \\\\\n  F''(t) & = x''u_x + x'(x'u_{xx} + y'u_{yx}) + y'' u_y + y'(x' u_{xy} + y' u_{yy}) = x'' u_x + y'' u_y + x'^2 u_{xx} + y'^2 u_{yy} + (x'y')(u_{yx} + u_{xy})\n\\end{aligned}\n\\]\n\\[\n\\begin{aligned}\n  F'''(t) & = \\begin{aligned} & \\quad \\\\\n    & x'' u_x + x''(x' u_{xx} + y'u_{yx}) + y''' u_y + y'' (x' u_{xy} + y' u_{yy}) + \\\\\n  & \\, + 2 x' x'' u_{xx} + 2y' y'' u_{yy} + x'^2 ( x'u_{xxx} + y' u_{yxx}) + y'^2 ( x' u_{xyy} + y' u_{yyy}) + \\\\\n  & \\, + (x'' y' + x' y'') (u_{yx} + u_{xy} ) + (x'y') (x' u_{xyx} + y' u_{yyx} + x' u_{xxy} + y' u_{yxy}) = \\end{aligned} \\\\\n  & = \\begin{aligned} & \\quad \\\\\n    &  x'' u_x + y''' u_y + x'^3 u_{xxx} + y'^3 u_{yyy} + 3x'' x' u_{xx} + 3y'' y' u_{yy} + \\\\\n  & \\, + 2x'' y' u_{yx} + 2y'' x' u_{xy} + x' y'' u_{yx} + x'' y' u_{xy} + \\\\\n  & \\, + x'^2 y' u_{yxx} + y'^2 x' u_{xyy} + x'^2 y' u_{xyx} + x'y'^2 u_{yxy} + x' y'^2 u_{yyx} + x'^2 y' u_{xxy} \\end{aligned}\n\\end{aligned}\n\\]\n\n\\exercisehead{6} Given $\\begin{aligned}\n  & x = u + v \\\\\n  & y = uv^2 \n\\end{aligned}$ \\quad $f(x,y)$ into $g(u,v)$, and \n\\[\n\\frac{ \\partial f}{ \\partial y } = \\frac{ \\partial^2 f }{ \\partial^2 x } = \\frac{ \\partial^2 f }{ \\partial y^2 } = \\frac{ \\partial^2 f }{ \\partial x \\partial y } = \\frac{ \\partial^2 f }{ \\partial y \\partial x } = 1 \n\\]  \nSo \n\\[\n\\begin{aligned}\n  & \\partial_u y = v^2 \\\\\n  & \\partial_u x = 1 \n\\end{aligned} \\quad \\quad \\quad \n\\begin{aligned}\n  & \\partial_u g = \\partial_x f \\partial_u x + \\partial_y f \\partial_u y = \\partial_x f + v^2 \\partial_y f \\\\\n  & \\partial_v g = \\partial_x f \\partial_v x + \\partial_y f \\partial_v y = \\partial_x f(1) + 2vu \\partial_y f = \\partial_x f + 2vu \\partial_y f \n\\end{aligned}\n\\]\n\\[\n\\begin{aligned}\n  \\frac{ \\partial^2 g}{ \\partial v \\partial u } & = \\partial_v (\\partial_x f ) + 2v \\partial_y f + v^2 \\partial_v (\\partial_y f) = \\\\\n  & = (\\partial_{xx}^2 f + 2vu \\partial_{yx}^2 f ) + 2v (\\partial_y f) + v^2 (\\partial_{xy}^2 f + 2vu \\partial_{yy}^2 f ) = \\\\\n  & = (\\partial_{xx}^2 f + 2vu \\partial_{yx}^2 f + v^2 \\partial_{xy}^2 f + 2vu \\partial_{yy}^2 f + 2v (\\partial_y f) \n\\end{aligned}\n\\]\nSo for $u=1$, $v=1$\n\\[\n\\frac{ \\partial^2 g}{ \\partial v \\partial u } = 1 + 2 + 1(1) + 2(1)(1)(1) + 2 (1)(1) = \\boxed{ 8 }\n\\]\n\n\\exercisehead{7} Given $\\begin{aligned}\n  & x = uv \\\\\n  & y = \\frac{1}{2} (u^2 - v^2)\n\\end{aligned}$\n\\begin{enumerate}\n\\item Assume equality of mixed partials.  \n\\[\n\\begin{aligned}\n  & \\partial_u x = v \\\\\n  & \\partial_v x = u \n\\end{aligned} \\quad \\quad \n\\begin{aligned}\n  & \\partial_u y = u \\\\\n  & \\partial_v y = -v  \n\\end{aligned} \\quad \\quad \n\\begin{aligned}\n  & \\frac{ \\partial g }{ \\partial u } = v \\partial_x f + u \\partial_y f \\\\\n  & \\frac{ \\partial g}{ \\partial v} = u \\partial_x f - v \\partial_y f \n\\end{aligned}\n\\]\n\\[\n\\begin{aligned}\n  \\partial_u \\partial_v g & = \\partial_x f + u \\partial_u (\\partial_x f ) + - v \\partial_u (\\partial_y f ) = \\\\\n  & = \\partial_x f + u (v \\partial_{xx}^2 f + u \\partial_{yx}^2 f ) + -v (v \\partial_{xy}^2 f + u \\partial_{yy}^2 f ) = \\\\\n  & = \\boxed{ \\partial_x f + uv \\partial_{xx}^2 f + 2y \\partial_{xy}^2 f - x \\partial_{yy}^2 f  }\n\\end{aligned}\n\\]\n\\item Given $\\| \\nabla f(x,y) \\|^2 = (\\partial_x f)^2 + (\\partial_y f)^2 = 2$\n\\[\n\\begin{gathered}\n  a \\left( \\frac{ \\partial g}{ \\partial u } \\right)^2 + - b \\left( \\frac{ \\partial g}{ \\partial v} \\right)^2 = u^2 + v^2 = a (v^2 (\\partial_x f)^2 + u^2 (\\partial_y f)^2 + 2 vu \\partial_x f \\partial_y f ) + -b (u^2 (\\partial_x f)^2 + v^2 (\\partial_y f)^2 - 2uv \\partial_x f \\partial_y f) \\\\\n  \\Longrightarrow a = -b \\text{ since $u,v$ are independent } \\\\\n\\quad \\\\\n(\\partial_x f)^2 ( av^2 + au^2) + (\\partial_y f)^2 (au^2 + av^2) = a ((\\partial_x f)^2 + (\\partial_y f)^2 ) (u^2 + v^2) = u^2 + v^2  \\\\\n\\Longrightarrow \\boxed{ a = 1/2 }\n\\end{gathered}\n\\]\n\\end{enumerate}\n\n\\exercisehead{8} Given that \n\\[\n(F(x) + G(y))^2 e^{ z(x,y) } = 2F'(x) G'(y); \\quad F(x) + G(y) \\neq 0 \\text{ or } e^{z(x,y)} = \\frac{ 2F'(x) G'(y) }{ (F+G)^2 }\n\\]\nso\n\\[\n\\begin{gathered}\n  z(x,y) = \\ln{ (2F'G' /(F+G)^2 ) } = \\ln{ F' } + \\ln{G'} - 2\\ln{ (F+G) } \\\\\n  \\partial_x z = \\frac{1}{F'}F'' - \\frac{2}{F+G} F' \\\\ \n  \\Longrightarrow \\partial_{yx}^2 z = \\frac{ -2F'G' }{ F+G} = -e^{z(x,y) } \\neq 0 \n\\end{gathered}\n\\]\n\n\\exercisehead{9}\n\n\\exercisehead{11} \n\\[\n\\begin{aligned}\n  (\\nabla f)_i & = \\partial_i ((r \\times A)_j (r \\times B)_j) = \\partial_i (\\epsilon_{jkl} x_k A_l)(\\epsilon_{jmn} x_m B_n) = \\\\\n  & = \\epsilon_{jik}A_k \\epsilon_{jmn} x_m B_n  + \\epsilon_{jkl} x_k A_l \\epsilon_{jim} B_m = \\\\\n  &= \\epsilon_{ijk} A_j \\epsilon_{kmn}x_m B_n + \\epsilon_{ijk} B_j \\epsilon_{klm} x_l A_m \n\\end{aligned}\n\\]\nSo for $f(x,y,z) = (r\\times A)\\cdot (r\\times B)$,\n\\[\n\\boxed{ \\nabla f(x,yz) = B \\times(r\\times A) + A \\times (r\\times B) }\n\\]\n\n\\exercisehead{12}\n\\begin{enumerate}\n  \\item \\[\n\\partial_i \\left( \\frac{1}{r} \\right) = \\frac{-1}{r^2} \\frac{1}{2} \\left( \\frac{ 2x_i }{r} \\right) = \\frac{-x_i}{r^3} \n\\]\n\\[\n\\boxed{ A \\cdot \\nabla \\left( \\frac{1}{r} \\right) = \\frac{-A\\cdot r}{r^3}  }\n\\]\n  \\item \\[\n\\partial_i \\left( \\frac{-a_j x_j}{r^3} \\right) = \\frac{-a_i}{r^3} + -a_j x_j \\left( \\frac{-3}{r^4} \\right) \\left( \\frac{x_i}{r} \\right) = \\frac{-a_i}{r^3} + \\frac{3a_j x_j x_i }{r^5} \n\\]\n\\[\n\\boxed{ B\\cdot \\nabla \\left( A \\cdot \\nabla \\left( \\frac{1}{r} \\right) \\right) = \\frac{-A\\cdot B}{r^3} + \\frac{ 3(A\\cdot x)(x\\cdot B) }{r^5} }\n\\]\n\\end{enumerate}\n\n\\exercisehead{13} \n\\[\n\\begin{gathered}\n  (x-a)^2 + (y-b)^2 + (z-c)^2 = 1 \\text{ or } x^2 + y^2 + z^2 -2xa - 2by - 2zc + a^2 + b^2 +c^2 = 1 \\\\\n\\text{ consider pts. of intersection, with $x^2 + y^2 + z^2 = 1$ } \\Longrightarrow 2xa + 2by + 2zc = a^2 + b^2 + c^2 \n\\end{gathered}\n\\]\n\\[\n\\begin{gathered}\n  \\begin{aligned}\n    & \\text{ Let } f(x,y,z) = x^2 + y^2 + z^2 -1 \\quad \\Longrightarrow \\nabla f = 2 (x,y,z) \\\\\n    &  \\text{ Let } g(x,y,z) = (x-a)^2 + (y-b)^2 + (z-c)^2 - 1 \\quad \\Longrightarrow \\nabla g = 2(x-a,y-b,z-c)\n\\end{aligned} \\\\\n\\begin{aligned}\n  \\text{ orthogonality condition: } \\nabla g \\cdot \\nabla f & = 0 = x(x-a) + y(y-b)+(z-c)z = 1 - ax - by - cz = \\\\\n  & = 1 - \\left( \\frac{ a^2 + b^2 + c^2 }{2} \\right) = 0 \n\\end{aligned} \\\\\n\\Longrightarrow \\boxed{ 2 = a^2 + b^2 + c^2 } \n\\end{gathered}\n\\]\n$2 = a^2 + b^2 + c^2$ describes a sphere of radius $\\sqrt{2}$ and center at the origin.  \n\n\\exercisehead{14} \n\\[\nz^2 + 2xz + y = 0 \\quad \\Longrightarrow \\begin{aligned} z & = \\frac{-2x \\pm \\sqrt{ 4x^2 - 4(1)(y) } }{2(1) } = \\\\\n  & = -x \\pm \\sqrt{ x^2 - y } \\end{aligned}\n\\]\nConsider parametrizing the position vector for the surface by the $x$ coordinate:\n\\[\n\\begin{aligned}\n  r & = (x,f(x), -x \\pm \\sqrt{ x^2 - y } ) \\\\\n  r' & = (1,f', -1 \\pm \\frac{1}{ 2 \\sqrt{ x^2 - y }} (2x- y') )\n\\end{aligned}\n\\]\nNow consider the position vector for points contained in the ``cylinder.''  Note that the $z$ coordinate does not depend upon $x$ for this cylinder because it looks the same in each $x-y$ plane for each $z$ coordinate.  \n\\[\n\\begin{aligned}\n  r & = (x,y,z) \\\\\n  r' & = (1,f',0)\n\\end{aligned}\n\\]\nThese two tangent vectors must coincide (since the $x$ coordinate and $y$ coordinate are the same, $1$ and $f'$, respectively).  \n\\[\n\\begin{gathered}\n  0 = -1 \\pm \\frac{1}{ 2 \\sqrt{ x^2 - y }} (2x- y') \\text{ or } 4 = \\frac{ 4x^2 - 4xy' + y'^2 }{ x^2 - y} \\\\\n  \\Longrightarrow 4x^2 - 4y = 4x^2 - 4xy' + y'^2 \\text{ or } y'^2 - 4xy' + 4y = 0 \\\\\n  \\Longrightarrow y' = \\frac{ 4x \\pm \\sqrt{ 16x^2 - 4(1)(4y)} }{2} = 2x \\pm 2 \\sqrt{ x^2 - y } \n\\end{gathered}\n\\]\nA solution to this ordinary differential equation is $\\boxed{ y = x^2 }$\n\n\\section*{ 9.3 Exercises - Partial differential equations, A first-order partial differential equation with constant coefficients }\n\n\\exercisehead{1} $4 \\partial_x f + 3 \\partial_y f =0$ \n\\[\n\\begin{gathered}\n  g(3x- 4y ) = f(x,y) \\\\\n  f(x,0) = \\sin{x} = g(3x) \\Longrightarrow \\boxed{ g(3x - 4 y) = \\sin{(x - \\frac{4}{3} y ) } }\n\\end{gathered}\n\\]\n\n\\exercisehead{2} $5\\partial_x f - 2 \\partial_y f = 0$ \n\\[\n\\begin{gathered}\ng(2x + 5y) = f(x,y) \\\\\n\\partial_x f(x,0) = 2\\left. g'(2x + 5y) \\right|_{y=0} = 2g'(2x) = e^x \\text{ or } g(u) =  e^{u/2} +C \\\\\n\\boxed{ g(2x+5y) = e^{(x + \\frac{5}{2} y ) } + -1} \n\\end{gathered}\n\\]\n\n\\exercisehead{3} \\begin{enumerate}\n\\item If $u(x,y) = f(xy)$, then consider that $xy=$ const. represent level curves for $f$ (because if $f(xy) = f(const.)$, then, ``obviously,'' $f(const.) = $ another constant.  \n\nParametrize $r$ by $x$\n\\[\nr = (x,y) = (x, \\frac{+k}{m} ); \\quad \\, r' = (1, \\frac{-k}{x^2} ) = (1,\\frac{-y}{x} ) \\text{ where } y = \\frac{k}{x}\n\\] \n\\[\n(\\nabla u ) \\cdot r' = \\partial_x u + \\frac{-y}{x} \\partial_y u = 0 \\text{ or } x \\partial_x u - y \\partial_y u = 0 \n\\]\n\\[\n\\begin{gathered}\n  u(x,x) = x^4 e^{x^2} \\quad \\, \\partial \\, x \\\\\n  u(x,x) = f(xx) = f(x^2 ) = (x^2)^2 e^{x^2} \\Longrightarrow \\boxed{ f(xy) = (xy)^2 e^{xy} }\n\\end{gathered}\n\\]\n\\item  $v(x,y) = f\\left( \\frac{x}{y} \\right)$ for $y\\neq 0$ \\\\\n$\\frac{x}{y} = $ const., then $f$ const.  $\\nabla f \\cdot r' = 0 $ on these level curves with $\\frac{x}{y} = $ const.; $r = (x,y) = (x,\\frac{x}{k} )$; $r' = (1,1/k)$ or $(1,\\frac{y}{x})$\n\\[\n\\Longrightarrow \\partial_x v + \\frac{y}{x} \\partial_y v = 0 \\text{ or } x \\partial_x v + y \\partial_y v = 0 \n\\]\n\\[\n\\begin{gathered}\n  \\partial_x v(x,1/x) = 1/x; \\quad \\, \\partial_x v = \\frac{1}{y} f'\\left( \\frac{x}{y} \\right) \\xrightarrow{ y = 1/x} x f'(x^2) = \\frac{1}{x} \\text{ or } f'(x^2) = \\frac{1}{x^2} \\text{ or } f(x) = \\ln{x} + C \\\\\n  f\\left( \\frac{x}{y} \\right) = \\ln{\\frac{x}{y}} + C = v(x,y) \\quad \\, \\\\ \n\\text{ Since } v(1,1) = 2 \\Longrightarrow \\boxed{ v(x,y) = \\ln{ \\frac{x}{y} } + 2  }\n\\end{gathered}\n\\]\n\\end{enumerate}\n\n\\exercisehead{4}$\\frac{ \\partial^2 g(x,y) }{ \\partial x \\partial y } = 0$ \\\\\n$\\partial_y g(x,y) = \\psi_2(y)$ for $\\partial_{xy}^2 g = 0$; \\quad $g(x,y) = \\phi_2(y) + \\phi_1(x)$ for $\\phi_2'(y) = \\psi_2(y)$\n\n\\exercisehead{5} $ a=1$, \\, $b=-2$, \\, $c = -3$ \\\\\nConsider the general problem: $a \\partial_{xx}^2 f + b \\partial_{xy}^2 f + c \\partial_{yy}^2 f = 0$ \\quad \\, $\\begin{aligned} x & = Au + Bv \\\\ y & = Cu + D v \\end{aligned}$, \\quad \\, $g(u,v) = f(Au + Bv, Cu + Dv)$ \\medskip \\\\\n$\\frac{\\partial^2 g }{ \\partial u \\partial v } = 0$ (assume equality of mixed partials)\n\\[\n\\begin{gathered}\n\\begin{aligned}\n  \\partial_v g & = B \\partial_x f + D \\partial_y f \\\\\n  \\partial_u g & = A \\partial_x f + C \\partial_y f \n\\end{aligned} \\quad \\quad \\, \n\\begin{aligned}\n  \\partial_{uv}^2 g & = B(A \\partial_{xx} f + C \\partial_{yx} f ) + D(A \\partial_{xy} f + C \\partial_{yy} f) = 0 = \\\\\n  & = AB \\partial_{xx}^2 f + (BC +DA) \\partial_{xy}^2 f + DC \\partial_{yy}^2 f = 0 \n\\end{aligned} \\\\\n\\Longrightarrow \\begin{gathered} AB = a \\\\ BC + DA = b \\\\ DC = c \\end{gathered}\n\\end{gathered}\n\\]\n\\[\n\\begin{gathered}\n  \\partial_{uv}^2 g = 0 \\Longrightarrow \\partial_v g = h(v) \\text{ or } g = H(v) + l(u) \\\\\n  \\begin{aligned}\n  g(u,v) & = H_1(v) + l_1(u) = H_1\\left( \\frac{Cx-Ay }{BC - AD } \\right) + l_1 \\left( \\frac{Dx - By }{ AD - BC } \\right) \\\\\n  & = H(Cx- Ay ) + l(Dx - By)\n\\end{aligned}\n\\end{gathered}\n\\]\n\n\\exercisehead{6} $u(x,y) = xy f\\left( \\frac{x+y}{xy} \\right)$\n\\[\n\\begin{gathered}\n  x^2 \\partial_x u + - y^2 \\partial_y u = G(x,y) u \\, \\Longrightarrow \\begin{aligned}\n    \\partial_x u(x,y) & = y f\\left( \\frac{x+y}{xy} \\right) + xy f'\\left( \\frac{1}{y} + \\frac{1}{x} \\right)\\left( \\frac{-1}{x^2} \\right) = y f\\left( \\frac{x+y}{xy} \\right) + \\frac{-1}{x} y f'\\left( \\frac{1}{y} + \\frac{1}{x} \\right) \\\\\n    \\partial_y u(x,y) & = x f\\left( \\frac{x+y}{xy} \\right) + xy f'\\left( \\frac{x+y}{xy} \\right) \\left( \\frac{-1}{y^2} \\right)\n\\end{aligned} \\\\\n  \\Longrightarrow x^2 \\partial_x - y^2 \\partial_y u = x^2 y f - xyf' - y^2x f + xyf' = (x-y)u \\quad \\, \\boxed{ G = x-y } \n\\end{gathered}\n\\]\n\n\\exercisehead{7} $\\begin{aligned}\n  x & = e^s \\\\\n  y & = e^t\n\\end{aligned}$ \\quad \\, $f(x,y) \\Longrightarrow g(s,t)$ \\quad \\, $g(x,t) = f(e^s, e^t)$\n\\[\n\\begin{gathered}\n  x^2 \\partial_{xx}^2 f + y^2 \\partial_{yy}^2 f + x\\partial_x f + y \\partial_y f = 0 \\\\\n  \\begin{aligned}\n    \\partial_s g & = x\\partial_x f \\\\\n    \\partial_{ss}^2 g & = x\\partial_x f + x(x\\partial_{xx}^2 f ) \n\\end{aligned} \\quad \\quad \\, \\begin{aligned} \\partial_t g & = y \\partial_y f \\\\ \\partial_{tt}^2 g & = y \\partial_y f + y^2 \\partial_{yy}^2 f \\end{aligned} \\medskip \\\\\n  \\boxed{ \\partial_{ss}^2 g + \\partial_{tt}^2 g = x\\partial_x f + x^2 \\partial_{xx}^2 f + y \\partial_y f + y^2 \\partial_{yy}^2 f = 0 }\n\\end{gathered}\n\\]\n\n\\exercisehead{8} $f(tx) = t^p f(x)$ \\quad $\\forall \\, t > 0 , \\, \\forall \\, x \\in S$ s.t. $tx \\in S$  \nFor fixed $x$, define $g(t) = f(tx)$; \n\\[\n\\begin{gathered}\n  \\begin{aligned}\n    g(t) & = f(tx) = t^p f(x) \\\\\n    g'(t) & = pt^{p-1} f(x) \n\\end{aligned} \\quad \\quad \\, \\Longrightarrow g'(1) = p f(x) = f'(x) = (\\nabla f )\\cdot x \\quad \\, \\text{ (by definition of total derivative ) }\n\\end{gathered}\n\\]\n\n\\exercisehead{9} Given $g(t) = f(tx) - t^p f(x)$, note that we want $g(t) = 0$.  \n\\[\ng'(t) = \\frac{d}{dt} f(tx) - p t^{p-1} f(x) \n\\]\nIt is very \\textbf{ useful } to recall the \\emph{total derivative} definition.\n\\[\n\\frac{d}{dt} f(tx) = \\lim_{\\Delta t \\to 0 } \\frac{ f((t+\\Delta t) x ) - f(tx) }{ \\Delta t} = \\lim_{\\Delta t \\to 0} \\frac{f(tx + \\Delta t x) - f(tx) }{ \\Delta t} = \\left( (\\nabla f)(tx) \\right) \\cdot x \n\\]\nUse the fact that we're given: $x\\cdot (\\nabla f)(x) = pf(x)$, so that $tx\\cdot \\nabla f(tx) = pf(tx)$\n\\[\n\\begin{aligned}\n  g'(t) & = x \\cdot (\\nabla f)(tx) - p t^{p-1} f(x) = \\frac{p}{t} (f(tx) - t^p f(x)) = \\\\\n  & = \\frac{p}{t} g(t)\n\\end{aligned} \\quad \\quad \\, \\Longrightarrow \\begin{gathered} \n  \\frac{g'}{g} = \\frac{p}{t} \\\\\n  \\ln{g} = p \\ln{t} +C \\\\\n  g = K t^p \n\\end{gathered}\n\\]\nNow $g(1) = 0$ (by plugging into the given $g(t) = f(tx) - t^p f(x)$).  But $g(1) = 0$ if $K=0$ \\smallskip \\\\\n$\\Longrightarrow g = 0 \\quad \\forall \\, t$\n\n\\exercisehead{10} \n\\[\n\\begin{gathered}\n  \\begin{aligned}\n    g'(1) & = pf = x\\partial_x f + y \\partial_y f \\\\\n    g''(1) & = p (x\\partial_x f + y \\partial_y f) = x \\partial_x (x \\partial_x f + y \\partial_y f) + y \\partial_y (x \\partial_x f + y \\partial_y f ) = \\\\\n    & = x (\\partial_x f + x \\partial_{xx}^2 f + y \\partial_{xy}^2 f ) + y (x \\partial_{yx}^2 f + \\partial_y f + y\\partial_{yy}^2 f ) = x \\partial_x f + x^2 \\partial_{xx}^2 f + 2xy \\partial_{xy}^2 f + y \\partial_y f + y^2 \\partial_{yy}^2 f\n\\end{aligned} \\\\\n  \\Longrightarrow x^2 \\partial_{xx}^2 f + 2xy \\partial_{xy}^2 f + y^2 \\partial_{yy}^2 f + (pf ) = p^2 f \\text{ or } \n\\boxed{ x^2 \\partial_{xx}^2 f + 2xy \\partial_{xy}^2 f + y^2 \\partial_{yy}^2 f = p(p-1) f }\n\\end{gathered}\n\\]\n\n\n\n\\section*{ 9.5 Exercises - The one-dimensional wave-equation }\n\n\\exercisehead{4} \n\\[\n\\begin{gathered}\n\\begin{aligned}\n  \\partial_{xx}^2 f & = \\frac{1}{r} \\partial_r g + \\frac{-x}{r^2} \\left( \\frac{x}{r} \\right) \\partial_r g + \\frac{x}{r} \\left( \\frac{x}{r} \\partial_{rr}^2 g + \\frac{-y}{r^2 } \\partial_{\\theta r}^2 g \\right) + \\frac{2y}{r^3} \\left( \\frac{x}{r}\\right) \\partial_{\\theta} g + \\frac{-y}{r^2} \\left( \\frac{x}{r} \\partial_{r\\theta}^2 g + \\frac{-y}{r^2} \\partial_{\\theta \\theta}^2 g \\right) \\\\\n  \\partial_{yy}^2 f & = \\frac{1}{r} \\partial_r g + \\frac{-y}{r^2} \\left( \\frac{y}{r} \\right) \\partial_r g + \\frac{y}{r} \\left( \\frac{y}{r} \\partial_{rr}^2 g + \\frac{x}{r^2} \\partial_{ \\theta r}^2 g \\right) + \\frac{-2x}{r^3 }\\left( \\frac{y}{r} \\right) \\partial_{\\theta} g + \\frac{x}{r^2} \\left( \\frac{y}{r} \\partial_{r\\theta}^2 g + \\frac{x}{r^2} \\partial_{\\theta \\theta}^2 g \\right)\n\\end{aligned} \\\\\n\\begin{aligned}\n\\partial_{xx}^2 f + \\partial_{yy}^2 f  & = \\frac{2}{r} \\partial_r g - \\frac{ \\partial_r g }{ r} + \\partial_{rr}^2 g + \\frac{1}{r^2} \\partial_{\\theta \\theta}^2 g = \\frac{1}{r} \\partial_r g + \\partial_{rr}^2 g + \\frac{1}{r^2} \\partial_{\\theta \\theta}^2 g = \\\\\n& = \\frac{1}{r} \\partial_r (r \\partial_r g ) + \\frac{1}{r^2} \\partial_{\\theta \\theta}^2 g \n\\end{aligned}\n\\end{gathered}\n\\]\n\n\\exercisehead{5} We want for \\\\\n$\\begin{aligned}\n  x & = \\rho \\cos{\\theta} \\sin{\\phi } \\\\\n  y & = \\rho \\sin{\\theta} \\sin{\\phi } \\\\\n  z & = \\rho \\cos{\\phi }\n\\end{aligned}$ \\quad \\quad \\, $f(x,y,z) \\to F(\\rho, \\theta, \\phi)$ \\\\\n\nBut first, consider $\\begin{aligned} x & = r \\cos{\\theta} \\\\ y & = r\\sin{\\theta} \\end{aligned}$ so that $f(x,y,z) \\to g(r,\\theta, z)$ \n\\begin{enumerate}\n\\item \\[\n\\nabla^2 f = \\frac{1}{r} \\partial_r (r\\partial_r g) + \\frac{1}{r^2} \\partial_{\\theta \\theta}^2 g + \\partial_{zz}^2 g = \\frac{ \\partial_r g }{r} + \\partial_{rr}^2 g + \\frac{1}{r^2} \\partial_{\\theta \\theta}^2 g + \\partial_{zz}^2 g \n\\]\n\\item $\\begin{aligned} z & = \\rho \\cos{\\phi} \\\\ r & = \\rho \\sin{\\phi} \\end{aligned}$, so \n\\[\n\\frac{1}{r^2} \\partial_{\\theta \\theta}^2 g = \\frac{1}{ \\rho^2 \\sin^2{\\phi} } \\partial_{\\theta \\theta}^2 g \n\\]\nNote that, except for a change in notation, this transformation is the same as that used in (a).  \n\\[\n\\begin{gathered}\n  \\partial_{zz}^2 g + \\partial_{rr}^2 g = \\frac{1}{\\rho } \\partial_{\\rho} (\\partial \\partial_{\\rho} g ) + \\frac{1}{\\rho^2} \\partial_{\\phi \\phi}^2 g \\\\\n  \\frac{1}{r} \\partial_r g = \\frac{1}{\\rho \\sin{\\phi}} \\left( \\rho \\sin{\\phi} \\partial_{\\rho} g + \\frac{\\rho \\cos{\\phi}}{\\rho^2} \\partial_{\\phi} g \\right) = \\frac{1}{\\rho} \\partial_{\\rho} g + \\frac{ \\cos{\\phi} }{ \\rho^2 \\sin{\\phi} } \\partial_{\\phi} g \\\\\n  \\nabla^2 f = \\partial_{\\rho \\rho}^2 F + \\frac{2}{\\rho} \\partial_{\\rho} F + \\frac{1}{\\rho^2} \\partial_{\\phi \\phi}^2 F + \\frac{\\cos{\\phi} }{ \\rho^2 \\sin{\\phi}} \\partial_{\\rho} F + \\frac{1}{\\rho^2 \\sin{\\phi}} \\partial_{\\theta \\theta}^2 g \n\\end{gathered}\n\\]\n\\end{enumerate}\n\n\\section*{ 9.8 Exercises - Derivatives of functions defined implicitly, Worked examples }\n\n\\exercisehead{1} \n\\[\n\\begin{aligned}\n  & x + y = uv \\\\\n  & xy = u -v \n\\end{aligned} \\quad \\,\n\\begin{aligned}\n  x & = X(u,v) \\\\\n  y & = Y(u,v)\n\\end{aligned}\n\\quad \\quad \\, \n\\partial_u : \\, \\begin{aligned}\n  x_u + y_u & = v \\\\\n  x_u y + x y_u & = 1 \n\\end{aligned}\n\\quad \\, \\partial_v : \\,  \n\\begin{aligned}\n  x_v + y_v & = u \\\\\n  x_v y + x y+v & = -1 \n\\end{aligned}\n\\]\n\\[\n\\begin{aligned}\n  \\left[ \\begin{matrix} 1 & 1 \\\\ y & x \\end{matrix} \\right]\\left[ \\begin{matrix} x_u \\\\ y_u \\end{matrix} \\right] & = \\left[ \\begin{matrix} v \\\\ 1 \\end{matrix} \\right] \\\\\n  \\left[ \\begin{matrix} 1 & 1 \\\\ y & x \\end{matrix} \\right]\\left[ \\begin{matrix} x_v \\\\ y_v \\end{matrix} \\right] & = \\left[ \\begin{matrix} u \\\\ -1 \\end{matrix} \\right]\n\\end{aligned} \\quad \\quad \\, \n\\begin{aligned}\n  \\frac{1}{ x- y} \\left[ \\begin{matrix} x &  -1 \\\\ -y & 1 \\end{matrix} \\right]\\left[ \\begin{matrix} v \\\\ 1 \\end{matrix} \\right] & = \\left( \\begin{matrix} xv - 1 \\\\ -vy + 1 \\end{matrix} \\right) \\left( \\frac{1}{x-y} \\right) \\\\\n  \\frac{1}{x-y} \\left[ \\begin{matrix} x & -1 \\\\ - y & 1 \\end{matrix} \\right] \\left[ \\begin{matrix} u \\\\ -1 \\end{matrix} \\right] & = \\left[ \\begin{matrix} ux + 1 \\\\ -uy -1 \\end{matrix} \\right]\\frac{1}{x-y}\n\\end{aligned}\n\\]\n\\[\n\\boxed{ \\begin{aligned} x_u & = \\frac{1}{x-y} (xv-1) \\\\ y_u & = \\frac{-vy + 1 }{ x-y} \\end{aligned} \\quad \\quad \\, \\begin{aligned} x_v & = \\frac{1}{x-y} (ux +1) \\\\ y_v & = \\frac{1}{x-y}(-uy - 1) \\end{aligned} }\n\\]\n\n\\exercisehead{5}  Given \n\\[\n\\begin{aligned}\n  & F(u,v) = 0 \\\\\n  & u = u(x,y,z) = xy \\\\ \n  & v = v(x,y,z) = \\sqrt{ x^2 + z^2 }\n\\end{aligned} \\quad \\quad \\,\n\\begin{aligned}\n  \\partial_x u & = y \\\\\n \\partial_y u & = x \\\\\n \\partial_z u & = 0 \\\\\n\\end{aligned}\n\\quad \\quad \\, \n\\begin{aligned}\n  \\partial_x v & = \\frac{ 1}{ 2 \\sqrt{ x^2 + z^2 } } (2x) = \\frac{x}{ \\sqrt{ x^2 + z^2 }} \\\\\n  \\partial_y v & = 0 \\\\\n  \\partial_z v & = \\frac{z}{ \\sqrt{ x^2 + z^2 } }\n\\end{aligned}\n\\]\n\\[\n\\begin{aligned}\n  & \\partial_x f = \\partial_x u \\partial_u F + \\partial_x v \\partial_v F = y \\partial_u F + \\frac{x}{v} \\partial_v F \\\\\n  & \\partial_y f = \\partial_y u \\partial_u F + \\partial_y v \\partial_v F = x \\partial_u F  \\\\\n  & \\partial_z f = \\partial_z u \\partial_u F + \\partial_z v \\partial_v F = \\frac{z}{v} \\partial_v F \n\\end{aligned}\n\\]\nSince $F = f = 0$, $\\nabla f \\cdot R' = 0$, so $\\nabla f$ is a normal vector to this surface.  \n\nWe're given\n\\[\nx = 1 , \\, y = 1 , \\, z = \\sqrt{3} \\quad \\quad \\, \n\\begin{aligned}\n  & D_1 F(1,2) = 1 \\\\\n  & D_2 F(1,2) = 2 \n\\end{aligned}\n\\]\nso then\n\\[\n\\begin{aligned}\n  \\nabla f & = (y \\partial_u F + \\frac{x}{v} \\partial_v F , x \\partial_u F, \\frac{z}{v} \\partial_v F ) = \\\\\n  & = (1 + \\frac{1}{2} 2 , 1(1) , \\frac{\\sqrt{3}}{2} 2 ) =\\boxed{ (2,1,\\sqrt{3}) }  \\\\\n  & \\Longrightarrow \\frac{ (2,1,\\sqrt{3} ) }{ 2 \\sqrt{2} } = \\boxed{ \\left( \\frac{1}{\\sqrt{2}} , \\frac{1}{ 2 \\sqrt{2}}, \\frac{1}{2} \\sqrt{ \\frac{3}{2} } \\right) }\n\\end{aligned}\n\\]\n\n\\exercisehead{6} \n\\[\n\\begin{aligned}\n  & x^2 - y \\cos{(uv)} + z^2 = 0 \\\\\n  & x^2 + y^2 - \\sin{ (uv)} + 2z^2  = 2 \\\\\n  & xy - \\sin{u} \\cos{v} + z = 0 \n\\end{aligned} \\quad \\quad \\, \n\\begin{aligned}\n  & x = x(u,v) \\\\ \n  & y = y(u,v) \\\\\n  & z = z(u,v) \n\\end{aligned} \\quad \\quad \\, \\text{ we want } \\begin{aligned} & \\partial_u x \\\\ & \\partial_v x \\end{aligned} \\text{ at } \\begin{aligned}\nx = y & = 1 \\\\ u & = \\pi/2 \\\\ v & = 0 \\\\ z & = 0 \\end{aligned} \n\\]\n\\[\n\\begin{gathered}\n\\partial_u \\, : \\, \\begin{aligned} & 2xx_u - y_u \\cos{(uv)} + y \\sin{(uv)} v + 2zz_u = 0 \\\\\n & 2x x_u + 2y y_u - \\cos{(uv)} (v) + 4 z z_u = 0 \\\\ & x_u y + xy_u - \\cos{u}\\cos{v} + z_u = 0 \\end{aligned} \\text{ or } \\\\\n(2x,2x, y) x_u + (-\\cos{(uv)},2y,x) y_u + (2z,4z,1) z_u = (-y\\sin{(uv)}v, v\\cos{(uv)}, \\cos{u} \\cos{v} )\n\\end{gathered}\n\\]\n\\[\n\\begin{gathered}\n  x_u = \\frac{ \\left| \\begin{matrix} -y \\sin{(uv)}v & v \\cos{(uv)} & \\cos{u} \\cos{v} \\\\ -\\cos{(uv)} & 2y & x \\\\ 2z & 4z & 1 \\end{matrix} \\right| }{ \\left| \\begin{matrix} 2x & 2x & y \\\\ -\\cos{(uv)} & 2y & x \\\\ 2z & 4z & 1 \\end{matrix} \\right| }  \\\\\n  \\text{ Note that } -y\\sin{(uv)} v = v\\cos{(uv)} = \\cos{u}\\cos{v} = 0 \\\\\n  \\Longrightarrow x_u = 0 \n\\end{gathered}\n\\]\n\\[\n\\begin{gathered}\n  \\partial_v \\, : \\, \\begin{aligned} & 2xx_v - y_v \\cos{(uv)} + y \\sin{(uv)} u + 2zz_v = 0 \\\\ & 2xx_v  + 2 y y_v - \\cos{(uv)} u + 4zz_v = 0 \\\\ & x_v y + xy_v + \\sin{u} \\sin{v} + z_v = 0 \\end{aligned} \\text{ or } \\\\\n  (2x,2x,y)x_v + (-\\cos{(uv)} , 2y, x ) y_v + (2z,4z,1) z_v = (-y\\sin{(uv)} u, \\cos{(uv)} u , -\\sin{u} \\sin{v} ) \n\\end{gathered}\n\\]\n\\[\n\\begin{aligned}\n  x_v & = \\frac{ \\left| \\begin{matrix} -yu \\sin{(uv)} & u \\cos{(uv)} & - \\sin{u} \\sin{v} \\\\ -\\cos{(uv)} & 2y & x \\\\ 2z & 4z & 1 \\end{matrix} \\right| }{ \\left| \\begin{matrix} 2x & 2x & y \\\\ - \\cos{(uv) } & 2y & x \\\\ 2z & 4z & 1 \\end{matrix} \\right| }  = \\frac{ \\left| \\begin{matrix} 0 & \\pi/2 & 0 \\\\ -1 & 2 & 1 \\\\ 0 & 0 & 1 \\end{matrix} \\right| }{ \\left| \\begin{matrix} 2 & 2 & 1 \\\\ -1 & 2 & 1 \\\\ 0 & 0 & 1 \\end{matrix} \\right| } \\\\ & = \\boxed{ \\pi/12}\n\\end{aligned}\n\\]\n\n\\section*{ 9.13 Exercises - Maxima, minima, and saddle points.  Second-order Taylor formula for scalar fields.  The nature of a stationary point determined by the eigenvalues of the Hessian matrix.  Second-derivative test for extrema of functions of two variables.  }\n\n\\exercisehead{1} $z= x^2 + (y-1)^2$\n\\[\n\\begin{gathered}\n  \\begin{aligned}\n    & f(x,y) = x^2 + (y-1)^2 \\\\ \n    & \\nabla f = (2x,2(y-1)) =0 \\text{ where } (x,y) = (0,1) \n  \\end{aligned} \\quad \\, \nf \\geq 0 \\text{ and } f= 0 \\text{ when } (x,y) = (0,1)\n\\end{gathered}\n\\]\n$(0,1)$ is an abs. min.  \n\n\\exercisehead{2} $z=x^2 - (y-1)^2$\n\\[\n\\nabla f = (2x, -2(y-1)) = 0 \\text{ when } (x,y) = (0,1) \\quad \\, \n\\begin{aligned}\n  & \\text{ For $(x,y)$ } = (t,1), \\, f(t,1) = t^2 \\geq 0 \\\\ \n  & \\text{ For $(x,y)$ } = (0,1 +\\delta), \\, f(0,1+\\delta) = -\\delta^2 < 0 \n\\end{aligned}\n\\]\nSo $(0,1)$ is a saddle pt.  \n\n\\exercisehead{3} $z = 1 + x^2 - y^2$ \n\\[\n\\nabla f = (2x,-2y) =0 \\text{ when } (x,y) = (0,0) \\quad \\, \\begin{aligned} & \\text{ For } (x,y) = (0,u), \\, z = 1 + -u^2 \\leq 1 \\\\ & \\text{ For } (x,y) = (t,0), \\, z = 1 + t^2 \\geq 1 \\end{aligned}\n\\]\nSo $(0,0)$ is a saddel pt.  \n\n\\exercisehead{4} $z = (x-y+1)^2$\n\\[\n\\begin{gathered}\n  \\nabla f = (2(x-y+1), 2(x-y+1)(-1)) = 0 \\text{ when } y = x + 1 \\\\ \n  f \\geq 0 \\, \\forall \\, (x,y), \\text{ so } (x,x+1) \\text{ is an abs. min. since $f(x,x+1) =0$ }\n\\end{gathered}\n\\]\n\n\\exercisehead{5} $ z= 2x^2 - xy - 3y^2 - 3x +7y$  \n\\[\n\\nabla f = (4x - y -2, -x + 2y +1) =0 \\text{ where } \\begin{aligned} y & = 4x - 2 \\\\ y & = \\frac{x-1}{2} \\end{aligned} \\text{ so } \\begin{aligned} x & = 3/7 \\\\ y & = - 2/7 \\end{aligned}\n\\]\n\\[\nH = \\left[ \\begin{matrix} 4 & -1 \\\\ -1 & 2 \\end{matrix} \\right] \\Longrightarrow (\\lambda -4)(\\lambda -2) - 1 = (\\lambda -7)(\\lambda+1)\n\\]\nSo we have a saddle point at $(3/7,-2/7)$.\n\n\\exercisehead{6} For $z = x^2 - xy + y^2 - 2x+y$, \n\\[\n\\nabla f = (2x - y-2, -x+2y + 1 ) =0 \n\\]\nso the critical point is at $(x,y) = (1,0)$.  \n\nThe Hessian matrix is \n\\[\nH = \\left[ \\begin{matrix} 2 &  -1 \\\\ -1 & 2 \\end{matrix} \\right]\n\\]\nSo $\\lambda =  1, +3$ are the eigenvalues.  $(1,0)$ is a relative minimum.  \n\n\\exercisehead{7} For $z = x^3- 3xy^2 + y^3$, \n\\[\n\\nabla f  =(3x^2 - 3y^2, -6xy + 3y^2) = 3(x^2- y^2, -2xy + y^2) = 0\n\\]\nThen because $y^2 - 2xy=0$, $(x,y) = (0,0)$.  \n\nThe Hessian matrix is \n\\[\nH = \\left[ \\begin{matrix} 6x & - 6 y \\\\ -6y & - 6x + 6y \\end{matrix} \\right]\n\\]\n\nFor $(x,y) = (0,0)$, by theorem, the Hessian matrix doesn't give a definite conclusion.  Then resort to the definitions of saddle points, relative minima, relative maxima.  \n\nNow $z = x^3-  3xy^2 + y^3 = y^2(y-3x) + x^3$.  $z(0,0) = 0$.  \n\nConsider $(x,y) = (\\delta, \\epsilon)$.  Then \\\\\n\n$z = \\epsilon^2(\\epsilon -3 \\delta) + \\delta^3$\n\nSo for $y=3x$,  \\\\\n\n$\\forall \\, E > 0 , \\, \\exists \\delta >0$ s.t. \\\\\n\\quad \\quad \\, if $ 0 < x < \\delta $, then $0<z < 2 \\delta = E(\\delta)$, \\\\\n\\quad \\quad \\, if $- \\delta < x < 0$, then $-E(\\delta) = -2\\delta^3 < z < 0$\n\nSo in the neighborhood of $(0,0)$, there exist pts. above and below $z=0$.  By definition, $(0,0)$ is a saddle point.  \n\n\\exercisehead{8} For $z = x^2 y^3 (6-x-y)$,\n\\[\n\\nabla f = (12 xy^3 - 3x^2 y^3 - 2xy^4, 18 x^2 y^2 - 3x^3 y^2 - 4x^2 y^3) = 0 \n\\]\nWith\n\\[\n\\begin{aligned}\n  & 12 xy^3 - 3x^2 y ^3 - 2xy^4 = xy^3(12-3x - 2y) = 0 \\\\\n  & x^2 y ^2 ( 18 - 3x - 4y ) = 0 \n\\end{aligned}\n\\]\nSo $(x,y) = (2,3)$ or $(x,0)$, $(0,y)$ are the critical points.  \n\nThe Hessian matrix is \n\\[\nH = \\left[ \\begin{matrix} 12 y^3 - 6xy^3 - 2y^4 & 36 xy^2 - 9x^2 y^2 - 8xy^3 \\\\ 36 xy^2 - 9x^2 y^2 - 8xy^3 & 36 x^2  y - 6 x^3 y - 12 x^2 y^2 \\end{matrix} \\right]\n\\]\n\nNow\n\\[\n\\begin{aligned}\n  & A = D_{1,1}f = 2y^3 (6-3x - y) \\\\ \n  & B = D_{1,2}f = xy^2 (36 - 9x - 8y) \\\\ \n  & C = D_{2,2}f = 6x^2 y(6-x-2y)\n\\end{aligned}\n\\]\nFor $(2,3)$, $\\Delta < 0$.  $(2,3)$ is a saddle point.  \n\nLooking at the Hessian matrix, the definitions must be used to determine if the critical points are saddle points, relative maxima, or relative minima.  \n\nConsider $(x,0)$, $z(x,0) = 0$.  \n\nConsider $|y| < \\delta_2$.  \n\n$z = y^3 x^2(6-x-y)$\n\nChoose $\\delta_2$, s.t. $\\delta_2 < |6-x|$ (since $\\delta_2$ is arbitrarily small, we can make this choice).  \n\nThen for fixed $x$, either $6-x < 0$, or $6-x >0$.  \n\nBut for $|y| < \\delta_2$, $y >0$, or $y<0$, either $z<0$, $z>0$, since $y$ or $-y$ allowed, for $|y| < \\delta_2$.  \n\\[\n|z| = |y^3| |x^2| |6-x-y| < \\delta_2^3 2 |6-x| x^2 = E(x,\\delta_2)\n\\]\n\n$\\forall \\, E > 0, \\, \\exists \\delta_2 >0$ s.t. for $|y| < \\delta_2$, $|z| < E(x,\\delta_2)$ and in this neighborhood, $\\exists \\, (x,y)$ s.t. $z<0$ and $(x,y)$ s.t. $z>0$.  \n\n$(x,0)$ are saddle points.  \n\n$(0,y)$, $z(0,y) =0$.  \n\nFor $|x| < \\delta_1$, \n\n$z = x^2  y^3 (6-y-x)$.  \n\nConsider $\\delta_1 < |6-y|$.  \n\nFor $y< 0$, $y>6$, $z<0$ for infinitesimal neighborhood about $z$ (with $\\delta_1 < |6-y|$).  \n\nFor $(0,y)$, $y<0$, $y>6$, $z(0,y)$ a relative minimum.  \n\nLikewise, for $0<y<6$, $z>0$ for infinitesimal neighborhood about $z$, (with $\\delta_1 < |6-y|$), so $z(0,y)$ a relative maximum.  \n\nFor $(0,6)$, $z(x,6) = 216 x^2 ( -x) = -216 x^3$.  $\\forall \\, E > 0$, $\\exists \\, \\delta_1 >0$ s.t. $|z| < E$ when $|x| < \\delta_1$, \\\\\n\nFor $|x| < \\delta_1$, both $x,-x$ fulfill the condition, so that \\\\\n\\quad \\, $\\exists$ pts. $(x,6)$, $(-x,6)$ in this neighborhood such that $z<0$, $z>0$, respectively.\n\n$(0,6)$ a saddle point.  \n\n\\exercisehead{9} $z = x^3 + y^3 - 3xy$\n\\[\n\\begin{gathered}\n  \\nabla f = (3x^2 - 3y, 3y^2 - 3x) = 0 \\Longrightarrow \\begin{aligned} x^2 = y \\\\ y^2 = x \\end{aligned} \\Longrightarrow (0,0), (1,1) \\\\ \n|Df| = \\left| \\begin{matrix} 6x & -3 \\\\ -3 7 6y \\end{matrix} \\right| = 36xy - 9 \n\\end{gathered}\n\\]\n\\[\n\\begin{gathered}\n  (1,1) \\text{ minimum since } Df(1,1) = 27 \\text{ and } D_{1,1}f(1,1) = 6 > 0 \\\\\n  (0,0) \\text{ saddle pt. since } Df(0,0) = -9 < 0 \n\\end{gathered}\n\\]\n\n\\exercisehead{10} $z= \\sin{x} \\cosh{y} $\n\\[\n\\begin{gathered}\n  \\nabla f = (\\cos{x} \\cosh{y}, \\sin{x} \\sinh{y} ) \\quad \\quad \\, |Df| = \\left| \\begin{matrix} -\\sin{x} \\cosh{y} & \\cos{x}\\sinh{y} \\\\ \\cos{x} \\sinh{y} & \\sin{x} \\cosh{y} \\end{matrix} \\right| = -\\sin^2{x} \\cosh^2{y} + -\\cos^2{x} \\sinh^2{y}  \\\\\n  \\nabla f =0 \\Longrightarrow (x,y) = \\left( \\left( \\frac{2j-1}{2} \\right) \\pi , 0 \\right) \\\\ \n  Df\\left( \\left( \\frac{2j-1}{2} \\right) \\pi , 0 \\right) = -1  \\quad \\Longrightarrow  \\left( \\left( \\frac{2j-1}{2} \\right) \\pi , 0 \\right) \\text{ is a saddle pt. }\n\\end{gathered}\n\\]\n\\exercisehead{11} $z= e^{(2x + 3y)}(8x^2 - 6xy + 3y^2) = fe^g$.  It helps alot to make these notation substitutions.  \n\\[\n\\begin{gathered}\n  \\begin{aligned}\n    f_x = 16x - 6y \\\\\n    f_y = -6x + 6y \n  \\end{aligned} \\quad \\quad \\nabla z = (f_x e^g + 2f e^g, f_y e^g + 3fe^g ) \\\\\n  \\xrightarrow{ \\nabla z}  \\begin{aligned} (f_x + 2f) e^g = 0 \\\\ (f_y + 3f)e^g = 0 \\end{aligned} \\Longrightarrow (0,0), \\, (\\frac{-1}{4}, \\frac{-1}{2} )  \n\\end{gathered}\n\\]\n\\[\n\\begin{gathered}\n  D_{ij}z = \\left| \\begin{matrix} 16e^g + 4f_x e^g + 4 fe^g & -6e^g + 2f_y e^g + 3f_x e^g + 6f e^g \\\\ -6e^g + 3f_x e^g + 2f_y e^g + 6fe^g & 6e^g + 6f_y e^g + 9f e^g \\end{matrix} \\right| \\\\\n  D_{ij}z(0,0) = \\left| \\begin{matrix} 16 & -6 \\\\ -6 & 6 \\end{matrix} \\right| = 96 - 36 = 60  \\quad \\quad \\, \\text{ $(0,0)$ is a minimum } \\\\\n  D_{ij}z(\\frac{-1}{4}, \\frac{-1}{2}) = e^{-4} \\left| \\begin{matrix} 16 & -9 \\\\ -6 & \\frac{-3}{2} \\end{matrix} \\right| = e^{-4}(-24-54) < 0 \\quad \\quad \\, \\text{ $(\\frac{-1}{4}, \\frac{-1}{2})$ is a saddle pt. }\n\\end{gathered}\n\\]\n\n\\exercisehead{12} $z= (5x + 7y -25) e^{-(x^2 + xy+ y^2) } = f e^{-g}$.  Using these shorthand, substitution notation helps with the calculation.  \n\\[\n\\begin{gathered}\n  \\nabla z = ( 5e^{-g} + fe^{-g}(-2x-y), 7e^{-g} + fe^{-g}(-x-y) ) \\\\ \n  \\nabla z = 0 \\Longrightarrow \\begin{aligned} 5 + (-2x-y)f = 0 \\\\ 7 + (-x-2y)f = 0 \\end{aligned} \\Longrightarrow \\boxed{ (x,y) = (1,3), \\left( \\frac{-1}{26}, \\frac{-3}{26} \\right) }\n\\end{gathered}\n\\]\n\\[\n\\begin{gathered}\n  D_{ij} z = \\\\ \ne^{-g} \\left[ \\begin{matrix} 5(-2-y) 2 + f (-2x-y)^2 + f (-2) & 7 (-2x-y) + 5 (-x-2y) + f (-x-2y)(-2x -y) - f \\\\ 7 (-2x-y) + 5 (-x-2y) + f (-x-2y)(-2x -y) - f & 7 (-x-2y) 2 + (-x-2y)^2 f + -2f \\end{matrix} \\right] \\\\\n  D_{ij} z(1,3) = e^{-2g} \\left| \\begin{matrix} -27 & -36 \\\\ -36 & -51 \\end{matrix} \\right| > 0 \\Longrightarrow \\text{ $(1,3)$ is a maximum } \\\\ \n  D_{ij} z(\\frac{-1}{26}, \\frac{-3}{26} ) = \\left| \\begin{matrix} \\frac{25}{26} + 52 & \\frac{35}{26} + 26 \\\\ \\frac{35}{26} + 26 & \\frac{49}{26} +52 \\end{matrix} \\right| > 0 \\Longrightarrow \\text{ $(\\frac{-1}{26}, \\frac{-3}{26} )$ is a minimum.} \n\\end{gathered}\n\\]\n\n\\exercisehead{13} $z= \\sin{x} \\sin{y} \\sin{ (x+y) }$, \\quad $0 \\leq x \\leq \\pi$, \\, $0\\leq y \\leq \\pi$  \n\n\n\\exercisehead{21} \\emph{Method of least squares.}  Given $n$ distinct numbers $x_1, \\dots, x_n$ and $n$ further numbers $y_1, \\dots, y_n$, and $f(x) = ax +b$ fitting form,\n\\[\n\\begin{gathered}\n  E(a,b) = \\sum_{i=1}^n (f(x_i) -y_i)^2 = \\sum_{i=1}^n (ax_i +b - y_i)^2 \\\\ \n  \\nabla E = 0 \\Longrightarrow  \\begin{aligned}\n    \\partial_a E & = \\sum_{i=1}^n 2 (ax_i + b - y_i) x_i = 2 \\left( a \\sum x_i^2 + b \\sum x_i - \\sum y_i x_i \\right) = 0 \\\\\n    \\partial_b E & = \\sum_{i=1}^n 2 (ax_i + b- y_i) = 2 \\left( a \\sum x_i + nb + - \\sum y_i \\right) = 0 \n  \\end{aligned}\n\\end{gathered}\n\\]\n \n\\[\n\\begin{aligned}\n  X^2 & = \\sum x_i^2 \\\\ \n  \\overline{X} & = \\frac{1}{n} \\sum x_i \\\\ \n  \\overline{Y} & = \\frac{1}{n} \\sum y_i\n\\end{aligned} \\quad \\quad \\, \\Longrightarrow \\left[ \\begin{matrix} X^2 & n \\overline{X} \\\\ n \\overline{X} & n \\end{matrix} \\right] \\left[ \\begin{matrix} a \\\\ b \\end{matrix} \\right] = \\left[ \\begin{matrix} \\sum y_i x_i \\\\ n \\overline{Y} \\end{matrix} \\right]\n\\]\n\\[\n\\Longrightarrow \\left[ \\begin{matrix} a \\\\ b \\end{matrix} \\right] = \\left( \\frac{1}{ nX^2 - n^2 \\overline{X}^2 } \\right) \\left[ \\begin{matrix} n & - n\\overline{X} \\\\ -n \\overline{X} & X^2 \\end{matrix} \\right] \\left[ \\begin{matrix} \\sum y_i x_i \\\\ n \\overline{Y} \\end{matrix} \\right] = \\left[ \\begin{matrix} n \\sum y_i x _i - n^2 \\overline{X} \\overline{Y} \\\\ -n \\overline{X} \\sum y_i x_i + n X^2 \\overline{Y} \\end{matrix} \\right] \\left( \\frac{1}{ nX^2 - n^2 \\overline{X}^2 } \\right)\n\\]\nSuppose $ \\begin{aligned} \n  u_i & = x_i - \\overline{X} \\\\ \n  u_i^2 & = x_i^2 - 2x_i \\overline{X} + \\overline{X}^2 \\quad \\quad \\, \\Longrightarrow \\sum u_i^2 = X^2 - 2n\\overline{X}^2 + n\\overline{X}^2 = X^2 - n\\overline{X}^2 \\\\ \n  \\sum y_i u_i & = \\sum y_i (x_i - \\overline{X} ) = \\sum y_i x_i - \\overline{X} \\overline{Y} n \n\\end{aligned}$\n\\[\n\\Longrightarrow a = \\sum y_i u_i / \\sum u_i^2 \n\\]\nThen use $an\\overline{X} + nb - n\\overline{Y} = 0$ or $b = \\overline{Y} -a\\overline{X}$ to get $b$.  \n\n\\exercisehead{22} $f(x,y) = ax + by +c$.  $E(a,b,c) = \\sum_{i=1}^n (f(x_i,y_i) - z_i)^2 = \\sum_{i=1}^n (ax_i + by_i + c - z_i)^2$.  $(x_i,y_i)$ are $n$ given distinct pts.  $z_1, \\dots, z_n$ are $n$ given real numbers.  \n\\[\n\\begin{aligned}\n  & \\partial_a E = 0 = 2 \\sum (ax_i + by_i +c - z_i ) x_i \\Longrightarrow & a \\sum x_i^2 + b \\sum x_i y_i + c \\sum x_i - \\sum z_i x_i = 0 \\\\\n  & \\partial_b E = 0 = 2 \\sum (ax_i + b y_i + c - z_i ) y_i \\Longrightarrow & a \\sum x_i y_i + b \\sum y_i^2 + c \\sum y_i - \\sum z_i y_i = 0 \\\\\n  & \\partial_c E = 0 = 2 \\sum (ax_i + b y_i + c - z_i ) \\Longrightarrow & a \\sum x_i + b \\sum y_i + nc - \\sum z_i = 0  \\text{ or } c = \\overline{Z} - a\\overline{X} - b \\overline{Y}\n\\end{aligned}\n\\]\nThen rewrite the above equations substituting the expression for $c$.  \n\\[\n\\begin{gathered}\n  aX^2 + b \\sum x_i y_i + cn \\overline{X} = \\sum z_i x_i = aX^2 + b \\sum x_i y_i + n \\overline{X} (\\overline{Z} - a\\overline{X} - b\\overline{Y}) = \\\\\n  = a(X^2 - n\\overline{X}^2 ) + b ( \\sum x_i y_i - n \\overline{X} \\overline{Y}) + n\\overline{X}\\overline{Z} \\\\ \n  a\\sum x_i y_i  + bY^2 + cn \\overline{Y} = \\sum z_i y_i = a ( \\sum x_i y_i - n\\overline{X} \\overline{Y}) + b (Y^2 - n \\overline{Y}^2 ) + n\\overline{Y} \\overline{Z} \n\\end{gathered}\n\\]\nThen \\[\n\\left[ \\begin{matrix} X^2 - n \\overline{X}^2 & \\sum x_i y_i - n\\overline{X} \\overline{Y} \\\\ \\sum x_i y_i - n \\overline{X} \\overline{Y} & Y^2 - n\\overline{Y}^2 \\end{matrix} \\right]\\left[ \\begin{matrix} a \\\\ b \\end{matrix} \\right] = \\left[ \\begin{matrix} \\sum z_i x_i - n \\overline{X} \\overline{Z} \\\\ \\sum z_i y_i - n \\overline{Y} \\overline{Z} \\end{matrix} \\right] = \\left[ \\begin{matrix} \\sum u_i z_i \\\\ \\sum v_i z_i \\end{matrix} \\right]\n\\]\n\nNote that for $u_i = x_i - \\overline{X}$, $v_i = y_i - \\overline{Y}$, we already showed in the previous exercise, Exercise 21, that $ \\begin{aligned} X^2 - n\\overline{X}^2  & = \\sum u_i^2 \\\\ Y^2 - n\\overline{Y}^2 & = \\sum v_i^2 \\end{aligned} $\n\\[\n\\sum u_i v_i = \\sum (x_i-\\overline{X})(y_i - \\overline{Y}) = \\sum x_i y_i - n \\overline{X} \\overline{Y} - n \\overline{X} \\overline{Y} + \\overline{X} \\overline{Y} n = \\sum x_i y_i - n \\overline{X} \\overline{Y}\n\\]\n\nSo let $\\Delta = \\left| \\begin{matrix} \\sum u_i^2 & \\sum u_i v_i \\\\ \\sum u_i v_i & \\sum v_i^2 \\end{matrix} \\right|$ and use Cramer's rule to obtain\n\\[\n\\begin{aligned}\n  & \\boxed{ a = \\frac{1}{ \\Delta } \\left| \\begin{matrix} \\sum u_i z_i & \\sum u_i v_i \\\\ \\sum v_i z_i & \\sum v_i^2 \\end{matrix} \\right| } \\\\ \n  &  \\boxed{ b = \\frac{1}{\\Delta } \\left|  \\begin{matrix} \\sum v_i z_i & \\sum u_i v_i \\\\ \\sum u_i z_i & \\sum u_i^2 \\end{matrix} \\right| } \\\\\n  & \\boxed{ c = \\overline{Z} - a \\overline{X} - b \\overline{Y} }\n\\end{aligned}\n\\]\n\n\\exercisehead{23} $z_1, \\dots, z_n$ are $n$ distinct pts. in $m$-space.  \\\\\nLet $x\\in \\mathbb{R}^m$, let $f(x) = \\sum_{k=1}^n \\| x - z_k \\|^2 = \\sum_{k=1}^n \\sum_{j=1}^m (x_j - (z_k)_j)^2$ \n\\[\n\\begin{gathered}\n  \\text{ Now } \\partial_i f = \\sum_{k=1}^n 2 (x_i - (z_k)_i) \\\\ \n  \\text{ Conditions we want: } \\nabla f = 0 \\Longrightarrow \\sum_{k=1}^n (x_i - (z_k)_i) = 0 \\Longrightarrow nx_i - \\sum_{k=1}^n (z_k)_i =0 \\\\ \n  \\Longrightarrow x_i = \\frac{1}{n} \\sum_{k=1}^n (z_k)_i \\text{ or } x = \\frac{1}{n} \\sum_{k=1}^n z_k \\\\\n  \\partial_{ij} f = \\partial_i \\sum_{k=1}^n 2 (x_j - (z_k)_j) = \\sum_{k=1}^n 2(1) \\delta_{ij} = 2n \\delta_{ij}\n\\end{gathered}\n\\]\n$H$ is diagonalized and $\\lambda_j > 0$, $\\forall \\, j = 1, \\dot, m$.  By Thm., $a = \\frac{1}{n} \\sum_{k=1}^n z_k$, (the centroid) is a minimum.  \n\n\\exercisehead{25} $f(x,y,z) = x^4 + y^4 + z^4 - 4xyz$.  \n\\[\n\\nabla f = (4x^3 - 4 yz, 4 y^3 + -4xz ,4 z^3 - 4xy) = 0 = (x^3 - yz, y^3 -xz, z^3- xy) \\quad \\quad \\, \\Longrightarrow \\begin{aligned} x^3 & = yz \\\\ y^3 & = xz \\\\ z^3 & = xy \\end{aligned} \\quad \\, \\text{ thus } \\nabla f (1,1,1) = 0 \n\\]\n\\[\n\\begin{gathered}\n  H = \\left[ \\begin{matrix} 12 x^2 & -4 z & -4 y \\\\ -4 z & 12 y^2 & -4x \\\\ -4 y & -4x & 12 z^2 \\end{matrix} \\right] = 4 \\left[ \\begin{matrix} 3x^2 & -z & -y \\\\ -z & 3y^2 & -x \\\\ -y & -x & 3z^2 \\end{matrix} \\right]  \\quad \\quad \\, H(a) = 4 \\left[ \\begin{matrix} 3 & -1 & -1 \\\\ -1 & 3 & -1 \\\\ -1 & -1 & 3 \\end{matrix} \\right]  \\\\  \n  | \\lambda I - H | = \\left| \\begin{matrix} \\lambda -12 & 4 & 4 \\\\ 4 & \\lambda -12 & 4 \\\\ 4 & 4 & \\lambda -12 \\end{matrix} \\right| = (\\lambda - 16)^2 (\\lambda -4) = 0 \\\\\n  \\Longrightarrow \\lambda = 16, 4\n\\end{gathered}\n\\]\n\n$a=(1,1,1)$ is a minimum, by theorem.  \n\n\\section*{ 9.15 Exercises - Extrema with constraints.  Lagrange's multipliers}\n\n\\exercisehead{1} Given $f(x,y)= z= xy$ and $g(x,y) = 0 = x+y - 1 $  \n\\[\n\\begin{gathered}\n  \\begin{aligned}\n    \\nabla f & = (y,x) \\\\ \n    \\nabla g & = (1,1)\n  \\end{aligned} \\quad \\, \\Longrightarrow \\nabla f = \\lambda \\nabla g = (y,x) = \\lambda (1,1) = (1-x,x) \\\\\n  \\Longrightarrow 1 - x = x \\text{ so that } \\begin{aligned} x & = \\frac{1}{2} \\\\ y & = \\frac{1}{2} \\end{aligned}  \\quad \\quad \\, \n\\boxed{ z= \\frac{1}{4} }\n\\end{gathered}\n\\]\n\n\\exercisehead{2} \n\\[\n\\begin{aligned}\n  f(x,y) & = r = \\sqrt{ x^2 +y^2 } \\\\ \n  g(x,y) & = 5x^2 + 6xy + 5y^2 - 8 \n\\end{aligned} \\quad \\quad \\, \\begin{aligned} \\nabla f & = \\frac{ (x,y) }{r} = \\lambda (10x + 6y, 10 y + 6x) \\\\ \\nabla g & = (10x + 6y , 10y + 6x) \\end{aligned}\n\\]\n\\[\n\\begin{gathered}\n  \\nabla f = \\frac{ (x,y)}{r} = \\lambda (10x + 6y, 10y + 6x) \\quad \\quad \\, \\Longrightarrow \\frac{x}{r} \\left( \\frac{1}{10x+6y } \\right) = \\frac{y}{r} \\left( \\frac{1}{ 10y + 6x} \\right) \\text{ or } x^2 = y^2  \\\\\n  g(x, \\pm x) = 5x^2 \\pm 6 x^2 + 5x^2 -8 = 0 \\Longrightarrow 10x^2 \\pm 6x^2 =8 \\text{ or } x = \\pm \\frac{1}{\\sqrt{2}}, \\, \\pm \\sqrt{2} \n\\end{gathered}\n\\]\n\\[\n\\begin{aligned}\n  & r \\text{ maximum }, 2, \\text{ when } (\\sqrt{2}, \\pm \\sqrt{2}), (-\\sqrt{2}, \\pm \\sqrt{2}) \\\\ \n  & r \\text{ minimum }, 1, \\text{ when } ( \\frac{1}{\\sqrt{2}}, \\pm \\frac{1}{\\sqrt{2}} ), ( \\frac{1}{\\sqrt{2}}, \\pm \\frac{1}{\\sqrt{2}} )\n\\end{aligned}\n\\]\n\\exercisehead{3} $a,b>0$\n\\begin{enumerate}\n\\item \\[\n\\begin{aligned}\n  f & = z = \\frac{x}{a} + \\frac{y}{b} \\\\ \n  \\nabla f & = \\left( \\frac{1}{a}, \\frac{1}{b} \\right) \n\\end{aligned}  \\quad \\quad \\, \\begin{aligned} g(x,y) & = x^2 + y^2 = 1 \\\\ \\nabla g & = (2x, 2y) \\end{aligned}\n\\]\n\\[\n\\begin{gathered}\n  \\nabla f = \\lambda \\nabla g \\Longrightarrow \\begin{aligned} \\frac{1}{a} & = \\lambda 2x \\\\ \\frac{1}{b} & = \\lambda 2y \\end{aligned} \\text{ or } \\frac{y}{x} = \\frac{a}{b} \\quad \\quad \\,  \n \\text{ so then } x^2 \\left( 1 + \\frac{a^2}{b^2} \\right) = 1 \\text{ or } \\begin{aligned} x & = \\frac{ \\pm b }{ \\sqrt{ a^2 + b^2 }} \\\\ y & = \\frac{ \\pm a }{ \\sqrt{ a^2 +b^2 } } \\end{aligned} \n\\end{gathered}\n\\]\n\\[\n\\boxed{ z = \\frac{ \\sqrt{ b^2 + a^2 }}{ ab} , \\, - \\frac{ \\sqrt{ b^2 + a^2 }}{ab}  }\n\\]\nGeometrically, consider lines of $bz - \\frac{b}{a} x = y$ inside a circular region of $x^2 + y^2 =1$.  \n\\item \\[\n \\begin{aligned}\n   f & = z = x^2 + y^2 \\\\ \n   \\nabla f & = 2 (x,y) \n \\end{aligned} \\quad \\quad \\, \\begin{aligned} g(x,y) & = \\frac{x}{a} + \\frac{y}{b} -1 \\\\ \\nabla g & = \\left( \\frac{1}{a}, \\frac{1}{b} \\right) \\end{aligned} \\quad \\quad \\,\n  \\nabla f = \\lambda \\nabla g \\Longrightarrow 2(x,y) = \\lambda \\left( \\frac{1}{a}, \\frac{1}{b} \\right)  \\text{ or } \\frac{a}{b} = \\frac{y}{x} \n\\]\n\\[\n\\begin{gathered}\n  \\text{ Plug back into $g(x,y)$:} \\Longrightarrow \\begin{aligned} x & = \\frac{ ab^2 }{ a^2 + b^2 } \\\\ y & = \\frac{ ba^2}{a^2 + b^2 } \\end{aligned} \n\\quad \\quad \\,   \\text{ minimum at } \\left( \\frac{ ab^2}{b^2 + a^2}, \\frac{ ba^2 }{ a^2 + b^2 } \\right) \\quad \\, z = \\frac{ a^2 b^2 }{ a^2 + b^2 }\n\\end{gathered}\n\\]\nGeometrically, consider points on a line defined by $g(x,y)$, $y = b - \\frac{bx}{a}$.  Then $f$ defines circles of increasing radius.  Obviously, we can make the radius for $f$, $z$, as large as we want.  \n\\end{enumerate} \n\n\\exercisehead{4}\n\n\\exercisehead{5} \n\\[\n\\begin{gathered}\n  \\begin{aligned}\n    f(x,y,z) & = x - 2y + 2z \\\\ \n    \\nabla f & = (1,-2,2) \n  \\end{aligned} \\quad \\quad \\begin{aligned} g & = x^2 + y^2 + z^2 -1 = 0 \\\\ \\nabla g & = (2x,2y,2z) \\end{aligned} \\xrightarrow{ \\nabla f = \\lambda \\nabla g } \\frac{1}{2x} = \\frac{-1}{y} = \\frac{1}{z} \\\\ \n  \\begin{aligned} 2x & = z \\\\ z & = -y \\end{aligned} \\quad \\Longrightarrow z = \\frac{ \\pm 2}{3}  \n\\end{gathered}\n\\]\n\\[\n\\begin{aligned}\n  f\\left( \\frac{1}{3}, \\frac{-2}{3}, \\frac{2}{3} \\right) & = 3 \\\\ \n  f\\left( \\frac{-1}{3}, \\frac{2}{3}, \\frac{-2}{3} \\right) & = -3 \n\\end{aligned}\n\\]\n\n\\exercisehead{6}  \n\\[\n\\begin{aligned}\n  f & = \\sqrt{ x^2 +y^2 + z^2 } \\\\ \n  \\nabla f & = \\frac{ (x,y,z) }{4} \\end{aligned} \\quad \\quad \\, \\begin{aligned} g & = z^2 - xy - 1 \\\\ \\nabla g & = (-y, -x, 2z) \\end{aligned}\n\\]\n\\[\n\\begin{gathered}\n  \\xrightarrow{ \\nabla f = \\lambda \\nabla g } \\frac{x}{-y} = \\frac{y}{ -x} = \\frac{1}{2} \\Longrightarrow \\begin{aligned} x^2 & = y^2 \\\\ y & = \\frac{-x}{2} \\end{aligned} \\text{ so } x= y = 0 \\\\ \n  \\Longrightarrow z = 1,-1 \\text{ or } (0,0,\\pm 1) \\text{ are the points where the distance is minimized. } \n\\end{gathered}\n\\]\n\n\\exercisehead{7} \\[\n\\begin{aligned}\nf(x,y) & = \\sqrt{ (x-1)^2 + y^2 } \\\\ \n\\nabla f & = \\frac{ (x-1, y) }{ \\sqrt{ (x-1)^2 + y^2 } } \\end{aligned} \\quad \\, \\begin{aligned} g(x,y) & = 4x- y^2 \\\\ \\nabla g  & = (4,-y) \\end{aligned}  \\quad \\, \\xrightarrow{ \\nabla f = \\lambda \\nabla g } \\begin{aligned}\n  \\frac{ (x-1)}{\\sqrt{ (x-1)^2 + y^2 } } & = 4 \\lambda  \\\\ \\frac{y }{ \\sqrt{ (x-1)^2 +y^2  } } & = -2y \\lambda \\end{aligned}\n\\]\n$x > 0$, but if $ y \\neq 0$, the equations imply $x=-1$.  \n\\[\n\\Longrightarrow (x,y) = (1,0) \\text{ is the point of shortest distance on the parabola to $(1,0)$ }\n\\]\n\n\\exercisehead{8} Given the constraining surfaces\n\\[\n\\begin{aligned}\n  x^2 - xy + y^2 - z^2 = 1 \\\\ \n  x^2 + y^2 = 1 \n\\end{aligned} \\text{ or } xy + z^2 = g = 0 \n\\]\nThen we want to minimize $f = \\sqrt{ x^2 + y^2 + z^2 }$.  $\\nabla f = \\frac{(x,y,z)}{f} $ \n\\[\n\\begin{gathered}\n  \\nabla g_1 = (y,x,2z) \\xrightarrow{ \\nabla f = \\lambda \\nabla g } \\begin{aligned} \\frac{x}{f} = \\lambda y \\\\ \\frac{y}{f} = \\lambda x \\\\ \\frac{z}{f} = \\lambda 2z \\end{aligned} \\\\ \n  \\text{ Suppose } z \\neq 0, \\, \\text{ then } \\frac{1}{2f} = \\lambda \\Longrightarrow \\begin{aligned} \\frac{y}{f} = \\frac{x}{2f} \\\\ \\frac{x}{f} = \\frac{1}{2f} y \\end{aligned} \\text{ or } \\begin{aligned} y = \\frac{x}{2} \\\\ x = \\frac{y}{2} \\end{aligned} \\text{ Contradiction. }\n\\end{gathered}\n\\]\nThen $z=0$.  \n\\[\n\\begin{gathered}\n  \\text{ Suppose $x,y \\neq 0$} \\Longrightarrow \\frac{x}{y} = \\frac{y}{x} \\text{ or } x^2 = y^2 \\\\ \n  \\Longrightarrow 2x^2 = 1 \\text{ or } x = \\frac{ \\pm 1}{\\sqrt{2}} \\text{ but } z^2 = - xy = 0 \\quad \\text{ Contradiction.}\n\\end{gathered}\n\\]\nThen $x=0$ or $y=0$, so that $\\lambda = 0$\n\\[\n\\boxed{ (0,\\pm 1,0), (\\pm 1, 0 , 0) }\n\\]\n\n\\exercisehead{9} \n\\[\n\\begin{aligned}\n  f(x,y,z) & = x^a y^b z^c \\\\ \n  \\nabla f & = f \\left( \\frac{a}{x}, \\frac{b}{y}, \\frac{c}{z} \\right)\n\\end{aligned} \\quad \\, \\begin{aligned}  g & = x + y + z - 1 \\\\ \\nabla g & = (1,1,1) \\end{aligned} \\xrightarrow{ \\nabla f = \\lambda \\nabla g } \\frac{af}{x} = \\frac{bf}{y} = \\frac{cf}{z} \n\\]\nIf $x,y,z \\neq 0$ then \n\\[\n\\begin{aligned} \n  y & = \\frac{bx}{a} \\\\ \n  z & = \\frac{cx}{a} \\end{aligned} \\Longrightarrow x + \\frac{bx}{a}  + \\frac{cx}{a} = 1 \\\\ \n\\text{ so that the maximum occurs at } (x,y,z) = \\frac{ 1}{ a+b+c} (a,b,c) \\text{ and } f = \\frac{ a^a b^b c^c }{ (a+b+c)^{a+b+c} }\n\\]\n\n\\exercisehead{10} Consider the ellipsoid $\\frac{x^2}{a^2} + \\frac{y^2}{b^2} + \\frac{z^2}{c^2} - 1 = g_1$.  Then ellipsoid will have the same normal at a point on the ellipsoid as the tangent plane through the same point.  Thus, we want\n\\[\n\\nabla g_1 = 2 \\left( \\frac{x}{a^2}, \\frac{y}{b^2}, \\frac{z}{c^2} \\right)\n\\]\nto be a normal that defines a plane through $(x,y,z)$, that's on the ellipsoid, in the $uvw$ plane.\n\\[\n\\Longrightarrow \\frac{xu}{a^2} + \\frac{yv}{b^2} + \\frac{zw}{c^2} = 1 \n\\]\nThe volume of the tetrahedron is\n\\[\n\\begin{aligned}\n  V  = \\int_0^{a^2/x} du \\int_0^{ \\frac{b^2}{y} \\left( 1 - \\frac{xu}{a^2} \\right) } dv \\int_0^{ \\frac{c^2}{z} \\left( 1 - \\frac{xu}{a^2} - \\frac{yv}{b^2} \\right) } dv = \\frac{(abc)^2}{6 xyz} \\quad \\quad \\quad \\,    \\nabla V = \\frac{(abc)^2}{6} \\left( \\frac{-1}{ x^2 y z}, \\frac{-1}{ xy^2 z}, \\frac{-1}{xyz^2} \\right) \n\\end{aligned}\n\\]\n\\[\n\\begin{gathered}\n  \\xrightarrow{  \\nabla V = \\lambda \\nabla g_1 } \\begin{aligned} \\frac{ (abc)^2 }{6} \\left( \\frac{-1}{ x^2 y z} \\right) = \\lambda 2 \\frac{x}{a^2} \\\\  \\frac{ (abc)^2 }{6} \\left( \\frac{-1}{ x y^2 z} \\right) = \\lambda 2 \\frac{y}{b^2} \\\\   \\frac{ (abc)^2 }{6} \\left( \\frac{-1}{ x y z^2} \\right) = \\lambda 2 \\frac{z}{c^2} \\end{aligned} \\text{ so } \\begin{aligned} y^2 = \\left( \\frac{bx}{a} \\right)^2 \\\\ z^2 = \\left( \\frac{c}{a} x \\right)^2 \\end{aligned} \\quad \\quad \\, \n  \\xrightarrow{ \\frac{x^2}{a^2} + \\frac{y^2}{b^2} + \\frac{z^2}{c^2} = 1 } \\begin{aligned} x = \\frac{a}{\\sqrt{3}} \\\\ y = \\frac{b}{\\sqrt{3}} \\\\ z = \\frac{c}{ \\sqrt{3}} \\end{aligned} \n\\end{gathered}\n\\]\n\\[\n\\boxed{ V = abc \\frac{\\sqrt{3}}{2} }\n\\]\n\n\\exercisehead{12} Consider the conic section as a quadratic form.  \n\\[\nAx^2 + 2Bxy + Cy^2 = 1 \\text{ where } A > 0 \\text{ and } B^2 < AC \\quad \\Longrightarrow T = \\left[ \\begin{matrix} A & B \\\\ B & C \\end{matrix} \\right]\n\\]\nNote that $det{T} = AC - B^2$, so normalize $T$ by $det{T}$ so to obtain only pure rotation, no ``amplification.''  \n\\[\n\\begin{gathered}\n  T \\to T = \\frac{1}{ AC - B^2} \\left[ \\begin{matrix}  \\lambda -A & - B \\\\ -B & \\lambda -C \\end{matrix} \\right] =0 \\Longrightarrow \\lambda_{\\pm} = \\frac{ (A+C) \\pm \\sqrt{ (A-C)^2 + 4B^2 } }{2 (AC-B^2) } \n\\end{gathered}\n\\]\nWe don't need to find the eigenvectors.  By theorem, we can find a $C$ s.t. $Y=XC$ and $Y$ are the coordinates in which $T$ is diagonalized.  \n\\[\n\\begin{gathered}\n\\lambda_+ u^2 + \\lambda_- v^2 = 1 \\Longrightarrow \\frac{ u^2}{ 1/\\lambda_+ } + \\frac{v^2}{ 1/\\lambda_- } =1\n\\end{gathered}\n\\]\nImmediately we recognize this to be the equation of an ellipse.  The $T$ rotation does not amplify distances since $det{T} =1$, and so distances from the origin to the conic section are preserved.  Then we can immediately name the minimum and maximum distances:\n\\[\nM^2, m^2 = 1/ \\frac{ (A+C) + \\sqrt{ (A-C)^2 + 4B^2 } }{2 (AC-B^2) }, 1/\\frac{ (A+C) - \\sqrt{ (A-C)^2 + 4B^2 } }{2 (AC-B^2) }  \n\\]\n\n\\exercisehead{13} Let $X = (x,y)$ be a point on the ellipse.  \\\\\nThe line is given by the set $\\{ (0,4) + s(1,-1) | s\\in \\mathbb{R} \\}$.  \\\\\nThe normal to the line is $(1,1)/\\sqrt{2}$, so connect a point on the ellipse to the line by a perpendicular distance $t$ by the following:\n\\[\nX = t \\frac{ (1,1)}{\\sqrt{2} } = (0,4) + s(1,-1) \n\\]\nso that \n\\[\n\\begin{gathered}\n  \\frac{ t (1,1) }{ \\sqrt{2} } = (0,4) + (s,-s)  - (x,y) = (s-x, 4-s -y) \\\\ \n  \\begin{aligned}\n\\frac{t}{\\sqrt{2}} & = s -x \\\\ \n\\frac{t}{\\sqrt{2}} & = 4 - s - y \\end{aligned} \\Longrightarrow \\sqrt{2} t = 4 - x -y \\text{ so let } f(x,y) = t = \\frac{4- x -y }{ \\sqrt{2}} \n\\end{gathered}\n\\]\n\\[\n\\begin{gathered}\n  \\nabla f = \\left( \\frac{-1}{\\sqrt{2}}, \\frac{-1}{\\sqrt{2}} \\right) \\quad \\quad \\, \\begin{aligned} g(x,y) & = \\frac{x^2}{4} + y^2 - 1 = 0 \\\\ \\nabla g & = \\left( \\frac{x}{2} , 2y \\right) \\end{aligned} \\quad  \\quad \\, \\Longrightarrow \\frac{x}{2} = 2y \\quad \\quad \\, \n  \\Longrightarrow 16y^2/4 + y^2 = 5y^2 = 1 \n\\end{gathered}\n\\]\nThus, the points that extremize $f$ are $(x,y) = \\left( \\frac{4}{\\sqrt{5}}, \\frac{1}{\\sqrt{5}} \\right), \\left( \\frac{-4}{\\sqrt{5}}, \\frac{-1}{\\sqrt{5}} \\right)$.  \n\\[\n\\boxed{ t_{min} = \\frac{ 4 - \\sqrt{5}}{\\sqrt{2}}, \\quad \\, t_{max} = \\frac{ 4 + \\sqrt{5}}{\\sqrt{2}} }\n\\]\n\n\\section*{ 10.5 Exercises - Introduction, Paths and line integrals, Other notations for line integrals, Basic properties of line integrals }\n\n\\exercisehead{1} $f= ((x^2-2xy),(y^2 - 2xy))$ from $(-1,1)$ to $(1,1)$; \\quad $y = x^2$ \\smallskip \\\\\n$\\alpha(x) = (x,x^2)$; \\quad $\\alpha' = (1,2x)$\n\\[\n\\begin{gathered}\n  \\int ((x^2 - 2xy),(y^2 - 2xy))\\cdot (1,2x) dx = \\int (x^2 - 2xy + 2xy^2 - 4x^2 y ) dx = \\\\\n_{-1}^1 (x^2  - 2x^3 + 2x^5 - 4x^4) dx = \\left. \\left( \\frac{1}{3} x^3 - \\frac{2}{4} x^4 + \\frac{2}{6} x^6 - \\frac{4}{5} x^5 \\right) \\right|_{-1}^1 = \\frac{1}{3} (1-(-1)) - \\frac{4}{5} (1-(-1)) = \\frac{2}{3} - \\frac{8}{5} = \\boxed{ \\frac{-14}{15} }\n\\end{gathered}\n\\]\n\n\\exercisehead{2} $f=(2a-y,x)$ along the path described by $\\alpha = (a(t-\\sin{t}), a(1-\\cos{t}))$ \\quad $0 \\leq t \\leq 2 \\pi$ \\\\\n$f(t) = (2a - a(1-\\cos{t}), a(t- \\sin{t})) = (a+a\\cos{t}, a(t-\\sin{t}))$ \\smallskip \\\\\n$\\alpha'(t) =(a(1-\\cos{t}), a\\sin{t})$\n\\[\n\\begin{gathered}\n  \\int f(t) \\cdot \\alpha'(t) dt = \\int_0^{2\\pi} (a^2 ( 1- \\cos^2{t}) + a^2 ( t\\sin{t} - \\sin^2{t}) ) dt = a^2 \\int_0^{2\\pi} (1+ t\\sin{t} - 1) dt = \\\\\n  = a^2 \\int_0^{2\\pi} t \\sin{t} dt = a^2 \\left( \\left. \\left( -t \\cos{t} \\right) \\right|_0^{2\\pi} - \\int_0^{2\\pi} -\\cos{t} dt \\right) = a^2 ( -2\\pi) + 0 = \\boxed{ -2\\pi a^2 } \n\\end{gathered}\n\\]\n\n\\exercisehead{3} $f(x,y,z) =((y^2- z^2), 2yz, -x^2)$; \\quad $\\alpha(t) = (t,t^2, t^3)$, \\quad $0\\leq t \\leq 1$ \\smallskip \\\\\n$f[\\alpha(t)] = ((t^4 - t^6), 2t^5, -t^2)$ \\quad \\, $\\alpha'(t) = (1,2t, 3t^2)$\n\\[\n\\int_0^1 f(\\alpha(t))\\cdot \\alpha'(t) dt = \\int_0^1 (t^4 - t^6 + 4t^6 - 3t^4) dt = \\left. \\left( (-2)\\frac{1}{5} t^5 + \\frac{1}{7} 3t^7 \\right) \\right|_0^1 = \\frac{-2}{5} + \\frac{3}{7} = \\boxed{ \\frac{1}{35} }\n\\]\n\n\\exercisehead{4} $f = (x^2 + y^2, x^2 - y^2)$ from $(0,0)$ to $(2,0)$ along the curve $y= 1 - |1-x|$.  \n\\[\n|1-x| = \\begin{cases} 1-x & \\text{ if } 1 - x > 0 \\text{ or } 1 > x \\\\ -(1-x) & \\text{ if } 1 - x < 0 \\text{ or } 1 < x \\quad \\end{cases} \\quad \\, y = \\begin{cases} x & 1 > x \\\\ 2-x & 1 < x \\end{cases}\n\\]\n\\[\n\\begin{aligned}\n  \\text{For} x<1, & \\\\\n  & \\alpha(x) = (x,x) \\\\ \n  & \\alpha'(x) = (1,1)\n\\end{aligned} \\quad \\quad \\, \\begin{aligned}\n  \\text{ For } x > 1, & \\\\ \n & \\alpha(x) = (x,(2-x)) \\\\ \n  & \\alpha'(x) = (1, -1)\n\\end{aligned}\n\\]\n\\[\n\\begin{aligned}\n  \\int f\\cdot \\alpha'(x) dx & = \\int_0^1 ((x^2 + y^2) + (x^2 - y^2)) dx + \\int_1^2 ((x^2 + y^2) - (x^2 - y^2)) dx = \\int_0^1 2x^2 dx + \\int_1^2 2(2-x)^2 dx = \\\\\n  & = \\left. \\frac{2}{3} x^3 \\right|_0^1 + 2 \\left. \\left( \\frac{1}{3} (2-x)^3 (-1) \\right) \\right|_1^2 = \\frac{2}{3} + \\left( \\frac{-2}{3} \\right) (0 - 1^3 ) = \\frac{2}{3} + \\frac{2}{3} = \\boxed{ \\frac{4}{3} }\n\\end{aligned}\n\\]\n\n\\exercisehead{5} $f = (x+y, x-y)$ \\quad  $b^2 x^2 + a^2 y^2 = a^2 b^2$ \\quad \\, $\\Longrightarrow \\left( \\frac{x}{a} \\right)^2 + \\left( \\frac{y}{b} \\right)^2 = 1$.  From the ellipse equation, parametrize by $\\theta$.  \\quad $\\Longrightarrow \\begin{aligned} x & = a \\cos{\\theta} \\\\ y & = b \\sin{\\theta} \\end{aligned}$ \n\\[\n\\begin{aligned}\n  \\alpha(\\theta) & = (a \\cos{\\theta}, b \\sin{\\theta} ) \\\\\n  \\alpha'(\\theta) & = (-a\\sin{\\theta}, b \\cos{\\theta})d\\theta\n\\end{aligned}\n\\]\n\\[\n\\begin{gathered}\n  \\int_0^{2\\pi} f(\\theta)\\cdot \\alpha'(\\theta) d\\theta = \\int_0^{2\\pi} \\left( (a\\cos{\\theta} + b \\sin{\\theta})(-a\\sin{\\theta})d\\theta + (a\\cos{\\theta} - b \\sin{\\theta})b\\cos{\\theta} d\\theta \\right) = \\\\\n%   = \\int_0^{2\\pi} \\left( -a^2 \\cos{\\theta} \\sin{\\theta} - ab \\sin^2{\\theta} + ab \\cos^2{\\theta}-b^2 \\sin{\\theta} \\cos{\\theta} \\right) d\\theta = \\\\\\int_{-\\pi/2}^{\\pi/2} \\cos{t} a \\cos{t} dt = a \\int_{-\\pi/2}^{\\pi/2} \\frac{ 1 + \\cos{2t}}{2}  = \\frac{a \\pi}{2} = \\\\ %\n  = (-a^2-b^2) \\int_0^{2\\pi} \\cos{\\theta}\\sin{\\theta} d\\theta + ab \\int_0^{2\\pi} (\\cos^2{\\theta} - \\sin^2{\\theta}) d\\theta = \\\\\n  = \\left. (-a^2 - b^2)\\left( \\frac{ \\sin^2{\\theta}}{2} \\right) \\right|_0^{2\\pi} + ab \\left. \\left( \\frac{ \\sin{2\\theta} }{2} \\right) \\right|_0^{2\\pi } = \\boxed{ 0 } \n\\end{gathered}\n\\]\n\n\\exercisehead{6} Given $f = (2xy, x^2 + z, y)$ from $x_1 = (1,0,2)$ to $x_2 = (3,4,1)$, use vector calculus and analytic geometry to form a line with direction vector $P = x_2 - x_1 = (2,4,-1)$.  Thus, the line is described by $x= tP + x_1$, where $t$ is the parameter.  \n\\[\nx = tP + x_1 \\quad \\Longrightarrow \\begin{aligned} x & = 2t + 1 \\\\ y & = 4t \\\\ z & = -t + 2 \\end{aligned}\n\\]\n\\[\n\\begin{aligned}\n  f(t) & = (2 ( 2t+ 1)(4t), ((2t+1)^2 + (-t+2)), 4t) = (16t^2 + 8t, 4t^2 + 3t + 3, 4t ) \\\\ \n  \\alpha'(t) & = (2,4,-1)\n\\end{aligned}\n\\]\n\\[\n\\begin{gathered}\n  \\int_0^1 f(t) \\cdot \\alpha'(t) dt = \\int_0^1 ( 32t^2 + 16t + 16t^2 + 12t + 12 - 4t) dt = \\int_0^1 dt ( 48t^2 + 24 t + 12) = \\\\\n  = \\left. \\left( \\frac{48}{3} t^3 + \\frac{24}{2} t^2 + 12t \\right) \\right|_0^1 = 16 + 12 + 12 = \\boxed{ 40 } \n\\end{gathered}\n\\]\n\n\\exercisehead{7} $f(x,y,z) = (x,y,(xz-y))$ from $(0,0,0)$ to $(1,2,4)$ along a line segment.  \\smallskip \\\\\n$\\begin{aligned} x_1 & = (0,0,0) \\\\ x_2 & = (1,2,4) \\end{aligned}$  \\quad \\, $P = x_2 - x_1 = x_2$.  The line is described by $Pt+x_1 = x = Pt$, so $\\left[ \\begin{matrix} x \\\\ y \\\\ z \\end{matrix} \\right] = \\left[ \\begin{matrix} t \\\\ 2t \\\\ 4t \\end{matrix} \\right]$\n\\[\n\\int_0^1 f(t) \\cdot \\alpha'(t)dt = \\int (t + 4t + (4t^2 - 2t) 4 ) dt = \\int (t + 4t + 16 t^2 - 8t) dt = \\int_0^1 (-3t + 16 t^2 ) dt = \\left. \\left( \\frac{-3t^2}{2} + \\frac{ 16 t^3}{2} \\right) \\right|_0^1 = \\boxed{ \\frac{23}{6} }\n\\]\n\n\\exercisehead{8} Given $f(x,y,z) = (x,y,(xz-y))$ along the path described by $\\alpha(t) = (t^2 + 2t, 4t^3)$; \\quad $0 \\leq t \\leq 1$ \n\\[\n\\begin{aligned}\n  \\alpha'(t) & = (2t, 2, 12t^2) \\\\\n  f(t) & = (t^2, 2t, (4t^2 t^3 - 2t)) = (t^2, 2t, (4t^5 - 2t)) \\\\\n  \\int f(t) \\cdot \\alpha'(t) dt & = \\int_0^1 ( 2t^3 + 4t + 12t^2 ( 4t^5 - 2t) ) dt = \\left. \\left( \\frac{2}{4} t^4 + \\frac{4}{2} t^2 + \\frac{48}{8} t^8 - \\frac{24 t^4}{4} \\right) \\right|_0^1 = \\boxed{ \\frac{5}{2} }\n\\end{aligned}\n\\]\n\n\\exercisehead{9} Given $\\int_C (x^2 - 2xy) dx + (y^2-  2xy) dy$; where $C$ is a path from $(-2,4)$ to $(1,1)$ along the parabola $y=x^2$ parametrize to $x$.  \n\\[\n\\begin{gathered}\n  \\int_C ((x^2 - 2x (x^2))dx + (x^4-2x(x^2 ))2x dx) = \\int_{-2}^1 (x^2 - 2x^3 + 2x^5 - 4x^4) dx = \\left. \\left( \\frac{1}{3} x^3 - \\frac{2}{4} x^4 + \\frac{2}{6} x^6 - \\frac{4x^5}{5} \\right) \\right|_{-2}^1 = \\\\ \n  = \\frac{1}{3} (1 - (-8)) - \\frac{1}{2} ( 1 - 16) + \\frac{1}{3} (1- 64) - \\frac{4}{5} (1- (-32)) = 3 + \\frac{15}{2} - \\frac{63}{3} - \\frac{4}{5}(33) = \\boxed{ \\frac{-369}{10} }\n\\end{gathered}\n\\]\n\n\\exercisehead{10} $\\int_C \\frac{ (x+y) dx - (x-y)dy}{x^2 + y^2 }$ where $C$ is the circle $x^2 + y^2 = a^2$ or $\\left( \\frac{x}{a} \\right)^2 + \\left( \\frac{y}{a} \\right)^2 =1$.  Let $\\begin{aligned} \\frac{x}{a} & = \\cos{\\theta} \\\\ \\frac{y}{a} & = \\sin{\\theta} \\end{aligned}$ \\quad \\, $\\begin{aligned} \\frac{dx}{d\\theta} & = -a \\sin{\\theta} \\\\ \\frac{dy}{d\\theta} & = a \\cos{\\theta} \\end{aligned}$ \n\\[\n\\Longrightarrow \\int_0^{2\\pi} \\left(  (a \\cos{\\theta} + a\\sin{\\theta} )(-a \\sin{\\theta})d\\theta- (a\\cos{\\theta} - a\\sin{\\theta})a \\cos{\\theta} d\\theta\\right)/a^2 = (-1)(2\\pi) = \\boxed{ - 2\\pi }\n\\]\n\n\\exercisehead{11} $\\int_F \\frac{dx + dy}{ |x| + |y| }$, where $F = A+B+C+D$, where \n\\[\n\\begin{aligned}\n  & A: \\, y = -x + 1 \\\\ \n  & B: \\, y = x + 1 \\\\  \n  & C: \\, y = -x - 1 \\\\ \n  & D: \\, y = x - 1 \n\\end{aligned}\n\\]\nSo\n\\[\n\\begin{aligned}\n  & \\int_A \\left( \\frac{dx}{ x + (-x+1) } + \\frac{-dx}{ x + (-x +1) } \\right) = 0 \\\\ \n  & \\int_B  \\frac{ 2 dx }{ -x + x+ 1 } = 2 \\int_0^{-1} \\frac{dx}{1} = 2(-1) = -2 \\\\\n  & \\int_C \\frac{dx - dx}{ -x + x+ 1} = 0 \\\\\n  & \\int_D \\frac{  2 dx }{ x + (-x+1)} = 2 \\int_0^1 \\frac{dx}{1} = 2 (1) =2 \n\\end{aligned} \\quad \\quad \\, \\Longrightarrow \\boxed{ \\int_F \\frac{ dx + dy }{ |x| + |y|} = 0 }\n\\]\n\n\\exercisehead{12} \n\\begin{enumerate}\n\\item Given that we want to compute $\\int_C y dx + z dy + x dz$, on the intersection of $x+ y = 2$ or $y = 2-x$ and $x^2 + y^2 + z^2 = 2 (x+y) = 2(2) = 4$, then\n\\[\n\\begin{aligned}\n  dx & = dx \\\\ \n  dy & = -dx \\\\ \n  \\frac{ dz}{dx} 2z & = -4x + 4 \\text{ or } dz  = \\frac{-4x + 4}{ 2 \\sqrt{ 4x - 2x^2} } dx\n\\end{aligned} \n\\]\nand\n\\[\nz^2 = 4 - x^2 - y^2 = 4 - x^2 - (2-x)^2 = -2x^2 + 4x\n\\]\n\\[\n\\begin{gathered}\n  \\int_0^2 (2-x)dx+ \\sqrt{ 4x - 2x^2} (-dx) + x \\frac{ 2 ( 1- x)}{\\sqrt{ 4x - 2x^2} } dx + \\int_2^0 \\left( (2-x) dx + - \\sqrt{ 4x - 2x^2} (-dx) + \\frac{x 2(1-x) }{ - \\sqrt{ 4x - 2x^2} } dx \\right) = \\\\\n  = 2 \\int_0^2 \\frac{ - (4x - 2x^2) + 2x - 2x^2}{ \\sqrt{ 4x - 2x^2} } dx = (-4) \\int_0^2 (x/\\sqrt{4x - 2x^2} ) dx \n\\end{gathered}\n\\]\nLet $u = \\frac{x}{2}$.  Then $2du = dx$.  \n\\[\n\\begin{gathered}\n  \\Longrightarrow (-4) \\int_0^1 (2u)(2 du) / \\sqrt{2} \\sqrt{ 4u -(2u)^2}  = -4 \\sqrt{2} \\int_0^1 \\frac{ \\sqrt{u}}{ \\sqrt{ 1 - u } } du = -4 \\sqrt{2} \\int_0^{\\pi/2} \\frac{\\sin{\\theta} }{\\cos{\\theta} } 2 \\sin{\\theta} \\cos{\\theta} d\\theta = \\\\\n  = \\left. -8\\sqrt{2} \\left( \\frac{1}{2} \\left( \\frac{\\pi}{2} - 9 \\right) \\frac{-\\sin{2\\theta}}{4} \\right) \\right|_0^{\\pi/2} = \\boxed{ -2 \\sqrt{2} \\pi } \\\\\n\\quad \\\\ \n\\text{ since } \\begin{aligned} u & = \\sin^2{\\theta} \\\\\ndu & = 2 \\sin{\\theta} \\cos{\\theta} d\\theta \\end{aligned} \\text{ and } \\\\\n\\sqrt{ 1 - u }  = \\sqrt{ 1 - \\sin^2{\\theta}} = \\cos{\\theta} \n\\end{gathered}\n\\]\n\\item With $x^2 + y^2 = 1$, $z=xy$, let $x = \\cos{\\theta}$, $y = \\sin{\\theta}$, $z= \\cos{\\theta}\\sin{\\theta}$, so that \n\\[\n\\begin{gathered}\n  \\int_C y dx + z dy + x dz = \\int_0^{2\\pi} ( \\sin{\\theta} (-\\sin{\\theta})d\\theta + \\cos{\\theta} \\sin{\\theta} \\cos{\\theta} d\\theta + \\cos{\\theta}(-\\sin^2{\\theta} + \\cos^2{\\theta}) d\\theta = \\\\\n  = \\int_0^{2\\pi} (-\\sin^2{\\theta} + \\cos^2{\\theta} \\sin{\\theta} - \\sin^2{\\theta} \\cos{\\theta} + \\cos^3{\\theta} ) d\\theta = \\\\ \n  = \\left. \\left( (-1)\\left( \\frac{1 -\\cos{2\\theta} }{2} \\right) + \\frac{-\\cos^3{\\theta}}{3} - \\frac{1}{3} \\sin^3{\\theta} + \\sin{\\theta} - \\frac{1}{3} \\sin^3{\\theta} \\right) \\right|_0^{2\\pi} = \\boxed{ - \\pi}\n\\end{gathered}\n\\]\n\\end{enumerate}\n\n\\section*{ 10.9 Exercises - The concept of work as a line integral, Line integrals with respect to arc length, Further applications of line integrals }\n\n\\exercisehead{1} $f(x,y,z) = (x,y,(xz-y))$ \n\\[\n\\begin{gathered}\n  \\begin{aligned}\n    x_1 & = (0,0,0) \\\\\n    x_2 & = (1,2,4)\n  \\end{aligned} \\quad \\quad \\, \\begin{aligned}\n    P & = x_2 - x_1 = x_2 \\\\ \n    x & = tx_2 + x_1; \\quad \\, 0 \\leq t \\leq 1 \n  \\end{aligned} \\\\\n\\int f\\cdot ds = \\int f\\cdot \\frac{ds}{dt} dt = \\int_0^1 (t,2t, t(4t) - 2t)\\cdot (1,2,4) dt = \\int_0^1 (t + 4t + 16t^2 -8t) dt = \\frac{-3}{2} + \\frac{16}{3} = \\boxed{ \\frac{23}{6} }\n\\end{gathered}\n\\]\n\n\\exercisehead{2} $f(x,y) = ((x^2 - y^2),2xy)$ \n\\[\n\\begin{gathered}\n  \\begin{aligned}\n    & A: \\, r= (a,ta) \\quad &  \\\\  \n    & B: \\, r= (a(1-t),a) \\quad &  \\\\\n    & C: \\, r= (0,a(1-t)) \\quad &  \\\\\n    & D: \\, r = (at,0) \\quad &\n  \\end{aligned} \\\\\n\\begin{aligned}\n  & A: \\, \\int_0^1 (a^2 - a^2 t^2, 2ta^2)\\cdot (0,a) dt = \\int_0^1 2t a^3 dt = a^3 \\\\ \n  & B: \\, \\int_0^1 ((a^2 ( 1-2t +t^2)-a^2),2a(1-t)a) \\cdot (-a,0) dt = -a\\int_0^1 a^2 ( -2t + t^2) dt = -a^3 \\left. \\left( -t^2 + \\frac{1}{3} t^3 \\right) \\right|_0^1 = \\frac{2}{3} a^3 \\\\\n  & C: \\, \\int_0^1 (-a^2 ( 1-2t + t^2), 0)\\cdot (0,-a) = 0 \\\\\n  & D: \\,  \\int_0^1 (a^2 t^2 ,0)\\cdot (a,0) dt = a^3 \\frac{1}{3}\n\\end{aligned} \\\\\n \\Longrightarrow \\int_C f\\cdot ds = \\boxed{ 2a^3 }\n\\end{gathered}\n\\]\n\n\\exercisehead{3} $f(x,y) = (cxy,x^6 y^2)$  \\quad $c>0$.  $(0,0)$ to line $x=1$ via $y=ax^b$; \\, $a>0, \\, b>0$.  \n\\[\n\\begin{gathered}\n\\begin{aligned}\n  W & = \\int f\\cdot ds = \\int (cx(ax^b),x^6 a^2 x^{2b} )\\cdot (1,bax^{b-1}) = \\int (acx^{b+1} + a^3 b x^{3b+5}) dx = \\\\ \n  &  = \\frac{ac}{b+2} + \\frac{a^3b}{3b+ 6} = \\frac{3ac}{ 3(b+2)} + \\frac{a^3b}{3(b+2)} = \\frac{3ac + a^3 b }{3(b+2)} \n\\end{aligned} \\\\\n\\Longrightarrow \\frac{3c}{a^2} = 2 \\Longrightarrow \\boxed{ a = \\sqrt{ \\frac{3c}{2} } }\n\\end{gathered}\n\\]\n\n\\exercisehead{4} $ f= (yz, xz, x(y+1))$.  \\quad $\\begin{aligned} a & = (0,0,0) \\\\ b & = (1,1,1) \\\\ c & = (-1,1,-1) \\end{aligned}$ \\\\\n\\[\n\\begin{gathered}\n\\begin{aligned}\n  & A: \\, (b-a) = b; \\quad & r = tb \\quad &  \\\\\n  & B: \\, (c-b) = (-2,0,-2); \\quad & r = t(-2,0,-2) + b \\quad &  \\\\ \n  & C: \\, (a-c) = -c; \\quad & r = t(-c) + c = c(1-t) \\quad & \n\\end{aligned} \\\\\n\\begin{aligned}\n  & A: \\, \\int (t^2 ,t^2, t(t+1))\\cdot (1,1,1) dt = \\int_0^1 t^2 + t^2 + t^2 + t = \\left. \\left( t^3 + \\frac{1}{2} t^2 \\right) \\right|_0^1 = \\frac{3}{2} \\\\\n  & B: \\, \\begin{aligned} \\int (1 (-2t + 1), (-2t +1), (-2t+1)(2)) \\cdot (-2,0,-2) dt & = \\int (-2t +1)(-2) + (-2)(-2t+1) = \\\\ & = \\int (-2)(-2t +1)(3) = -6 \\left. ( -t^2 + t) \\right|_0^1 = 0 \\end{aligned} \\\\\n  & C: \\, \\begin{gathered} \\int ((1-t)(-1)(1-t), -1(1-t)(-1)(1-t), (-1)(1-t)((1-t) +1))\\cdot (1,-1,1)  = \\\\ \n    = \\int - (1-t)^2 + (1-t)^2 (-1) + (-1)(1-t)^2 - (1-t) = \\int -3 (1-2t + t^2 ) -1 +t = \\int -3t^2 + 7t -4 = \\\\\n    = \\left. \\left( - t^3 + \\frac{7t^2}{2} - 4t \\right) \\right|_0^1 = \\frac{-3}{2} \\end{gathered}\n\\end{aligned} \\\\\n\\int f \\cdot ds = \\boxed{ 0 } \n\\end{gathered}\n\\]\n\n\\exercisehead{5} $f = (y-z,z-x,x-y)$ \n\\[\n\\begin{gathered}\n  x^2 + y^2 + z^2 = 4 \\\\\n  x^2 + y^2 \\sec^2{\\theta} = 4 \n\\end{gathered} \\quad \\, z = y \\tan{\\theta} \\quad \\quad \\, \\begin{aligned} x & = 2 \\cos{\\phi} \\\\ y \\sec{\\theta} & = 2 \\sin{\\phi} \\\\ z & = 2 \\sin{\\phi} \\sin{\\theta} \\end{aligned}\n\\]\n\\[\n\\begin{gathered}\n  f = \\left( \\frac{ 2 \\sin{\\phi} }{ \\sec{\\theta}} - 2 \\sin{\\phi} \\sin{\\theta}, 2 \\sin{\\phi} \\sin{\\theta} - 2 \\cos{\\phi}, 2 \\cos{\\phi} - \\frac{ 2\\sin{\\phi}}{\\sec{\\theta}} \\right)  \\\\\n  \\frac{ds}{d\\phi} = ( - 2 \\sin{\\phi}, \\frac{ 2 \\cos{\\phi}}{\\sec{\\theta} } , 2\\cos{\\phi} \\sin{\\theta} )\n\\end{gathered}\n\\]\n\\[\n\\begin{aligned}\n  \\int f\\cdot ds & = \\int 4 ( \\sin{\\phi} (\\cos{\\theta} - \\sin{\\theta})(-\\sin{\\phi}) + (\\sin{\\phi}\\sin{\\theta} - \\cos{\\phi})(\\cos{\\phi} \\cos{\\theta}) + (\\cos{\\phi} - \\sin{\\phi}\\cos{\\theta}) \\cos{\\phi} \\sin{\\theta} ) d\\phi = \\\\\n  & = 4 \\int (-\\sin^2{\\phi} ( \\cos{\\theta} - \\sin{\\theta} ) + -\\cos^2{\\phi}( \\cos{\\theta} - \\sin{\\theta}) = 4 \\int (-\\cos{\\theta} + \\sin{\\theta} ) d\\phi = \\boxed{ 8 \\pi (\\sin{\\theta} - \\cos{\\theta} ) }\n\\end{aligned}\n\\]\n\n\\exercisehead{6} $f = (y^2,z^2,x^2)$.  $\\begin{aligned} & x^2 + y^2 + z^2 = a^2 \\\\ & x^2 + y^2 = ax \\end{aligned}$ \\quad \\, $\\Longrightarrow \\left( x - \\frac{a}{2} \\right)^2 + y^2 = \\left( \\frac{a}{2} \\right)^2$.  \\quad \\, $\\begin{aligned} & x - \\frac{a}{2} = \\frac{a}{2} \\cos{\\phi} \\\\ & y = \\frac{a}{2} \\sin{\\phi} \\\\ & z^2 = a^2 - a \\left( \\frac{a}{2} \\left( \\cos{\\phi} + 1 \\right) \\right) \\end{aligned}$ \n\\[\n\\begin{aligned}\n  f & = \\left( \\left( \\frac{a}{2} \\right)^2 \\sin^2{\\phi}, \\frac{a^2}{2} (1-\\cos{\\phi}), \\left( \\frac{a}{2} \\right)^2 (\\cos{\\phi} + 1 )^2 \\right) \\\\\n  r' & = \\left( \\frac{-a}{2} \\sin{\\phi}, \\frac{a}{2} \\cos{\\phi}, \\frac{a^2}{4} \\sin{\\phi}/z \\right) \\\\\n  f\\cdot r' & = \\left( \\frac{a}{2} \\right)^3 \\sin^3{\\phi} + \\frac{a^3}{4} (\\cos{\\phi} - \\cos^2{\\phi}) + \\left( \\frac{a}{2} \\right)^4 \\frac{ (\\cos{\\phi} +1)^2 \\sin{\\phi} }{z} \n\\end{aligned}\n\\]\n\\[\n\\begin{gathered}\n  \\sin^3{\\phi} = \\sin{\\phi} (1-\\cos^2{\\phi}) \\xrightarrow{ \\int } - \\cos{\\phi} + \\frac{1}{3} \\cos^3{\\phi} \\xrightarrow{ \\int_0^{2\\pi}} 0 \\\\\n  \\int_0^{2 \\pi} \\cos{\\phi} = 0 \\\\\n  \\int_0^{2\\pi} \\cos^2{\\phi} = \\boxed{ \\pi } \\\\\n  z \\geq 0, \\quad \\Longrightarrow z = \\frac{a}{2} \\sqrt{ 1 + \\cos{\\phi}} = \\frac{a}{2} \\sqrt{ 2 \\cos^2{ \\phi/2}} = \\frac{a}{\\sqrt{2}} |\\cos{\\phi/2} | \\text{ and  so } \n\\end{gathered}\n\\]\n\\[\n\\begin{gathered}\n  \\left( \\frac{a}{2} \\right)^4 (1+ \\cos{\\phi})^2 = \\left( \\frac{a^2}{4} + \\frac{a^2}{4} \\cos{\\phi} \\right)^2 = \\left( \\frac{a^2 }{4} + \\frac{a^2}{4} - \\frac{z^2}{2} \\right)^2 = \\frac{ (a^2 - z^2)^2 }{2^2} \\quad \\text{ so that } \\\\\n  \\int \\left( \\frac{a}{2} \\right)^4 \\frac{ (1+\\cos{\\phi})^2 \\sin{\\phi}}{z} = \\int \\frac{ (a^2 -z^2)^2 \\sin{\\phi}}{z} = \\int \\frac{ (a^4 - 2a^2 z^2 + z^4)\\sin{\\phi} }{z} \n\\end{gathered}\n\\]\n\\[\n\\begin{aligned}\n  \\int \\sin{\\phi/2}\\cos{\\phi/2}/|\\cos{\\phi/2}| & = \\int_0^{\\pi} \\sin{\\phi/2} - \\int_{\\pi}^{2\\pi} \\sin{\\phi/2} = \\left. -2 \\cos{\\phi/2} \\right|_0^{\\pi} + \\left. 2 \\cos{\\phi/2} \\right|_{\\pi}^{2\\pi} = (-2)(-1) + 2(-1) = 0 \\\\\n  \\int z \\sin{\\phi} & = \\int_0^{2\\pi} \\frac{a}{\\sqrt{2}} \\sqrt{ 1 - \\cos{\\phi} }\\sin{\\phi} = \\frac{a}{\\sqrt{2}} \\left. (1- \\cos{\\phi} )^{3/2} \\frac{2}{3} \\right|_0^{2\\pi} = 0 \\\\\n  \\int z^3 \\sin{\\phi} & = \\int_0^{2\\pi} \\left( \\frac{a}{\\sqrt{2}} \\sqrt{ 1 - \\cos{\\phi}} \\right)^3 \\sin{\\phi} = \\left. \\frac{a^3}{2^{3/2}} (1-\\cos{\\phi})^{5/2} \\frac{2}{5} \\right|_0^{2\\pi} = 0 \n\\end{aligned}\n\\]\nSo we finally get \n\\[\n\\int f \\cdot r' d\\phi = -a^3 (\\pi)/4\n\\]\nSince we had gone counterclockwise, the exercise asked for the clockwise direction, so reverse the sign to get $\\boxed{ \\frac{ a^3 \\pi}{4} }$\n\n\\exercisehead{7} $\\int_C (x+y)ds$.  \n\\[\n\\begin{aligned}\n  a & = (0,0) \\\\ \n  b & = (1,0) \\\\\n  c & = (0,1)\n\\end{aligned} \\quad \\, \\begin{aligned} & A: \\, b - a = b \\\\ & B: \\, c-b = (-1,1) \\\\ & C: \\, a-c = -c \\end{aligned} \\quad \\, \\begin{aligned} r & = bt + a = bt \\\\ r & = (-1,1)t + (1,0) \\\\ r & = -ct + c = c(1-t) \\end{aligned} \\quad \\, \\begin{aligned} |r'| & = |b| = 1 \\\\ |r'| & = \\sqrt{2} \\\\ |r'| & = 1 \\end{aligned} \\quad \\, \\begin{aligned} (x+y) & = t \\\\ (x+y) & = -t + 1 + t = 1 \\\\ (x+y) & = 1 - t \\end{aligned}\n\\]\n\\[\n\\int_C (x+y)ds = \\frac{1}{2} t^2 + t\\sqrt{2} + t - \\frac{1}{2}t^2 = \\sqrt{2}  + 1 \n\\]\n\n\\exercisehead{8} $\\int_C y^2 dx$ \\quad $\\alpha(t) = (a(t-\\sin{t}), a(1-\\cos{t}))$, \\quad $0\\leq t \\leq 2\\pi$\n\\[\n\\begin{gathered}\n\\begin{aligned}\n  \\alpha' & = (a(1-c(t)), a(s(t))) \\\\\n  \\alpha'^2 & = a^2 (1 - 2c + c^2 + s^2) = a^2  2 (1-c)\n\\end{aligned} \\\\\n\\begin{aligned}\n  \\int a^2 ( 1 - 2c + c^2) (a\\sqrt{2} \\sqrt{ 1 - c } ) dt & = a^3 \\sqrt{2} \\int (1-c)^{5/2} dt  = \\\\\n  & = a^3 \\sqrt{2} \\int_0^{2\\pi} \\left( 2 \\sin^2{ \\left( \\frac{t}{2} \\right) } \\right)^{5/2} dt = a^3 2^{1/2} 2^{5/2} \\int_0^{2\\pi } \\sin^5{\\left( \\frac{t}{2} \\right)} dt \n\\end{aligned} \\quad \\quad \\, \\\\\n\\text{ since } \\begin{aligned} \\cos{(2t)} & = \\cos^2{t} - \\sin^2{t} \\\\ &  =1 - 2 \\sin^2{t} \\end{aligned} \\quad \\, \\text{ or } 2 \\sin^2{t} = 1-\\cos{(2t)} \n\\end{gathered}\n\\]\nNow\n\\[\n\\sin^5{\\left( \\frac{t}{2} \\right)} = (1-\\cos^2{\\left( \\frac{t}{2} \\right)})^2 \\sin{\\left( \\frac{t}{2} \\right) } = \\left( 1 - 2 \\cos^2{\\left(\\frac{t}{2} \\right)} + \\cos^4{\\left( \\frac{t}{2} \\right)} \\right)\\sin{\\left( \\frac{t}{2} \\right)}\n\\]\nSo\n\\[\n\\begin{gathered}\n  \\int_0^{2\\pi} \\sin^5{\\left( \\frac{t}{2} \\right)} dt = \\left. (-2\\cos{(t/2)} ) \\right|_0^{2\\pi} + \\left. \\left( (4)(1/3) \\cos^3{(t/2)} + \\frac{-2}{5} \\cos^5{(t/2)} \\right) \\right|_0^{2\\pi} = (-2) \\left( (-2) + \\frac{4}{3} + \\frac{-2}{5} \\right) = \\frac{32}{15} \\\\\n  \\int_C y^2 ds = 8 a^3 \\frac{32}{15} = \\boxed{ \\frac{256}{15} a^3  }\n\\end{gathered}\n\\]\n\n\\exercisehead{9} $\\int_C (x^2 + y^2) ds$ where $C$ has the vector equation $\\alpha(t) = (a(\\cos{t} + t\\sin{t}), a(\\sin{t} - t\\cos{t}) )$, \\, $0 \\leq t \\leq 2\\pi$ \\\\\n\\[\n\\alpha'(t) = (a((-s +s + tc), c- c + ts) ) = a(tc,ts) = at(c,s)  \\quad \\quad \\, \\| a' \\| at \n\\]\n\\[\n\\begin{gathered}\n  x^2 + y^2 = a^2 ( c^2 + 2tcs + t^2 s^2 + s^2 - 2tsc + t^2c^2 ) = a^2(1+t^2) \\\\\n  \\int_C a^2 (1+t^2) at dt = a^3 \\int (t+t^3)dt = a^3 \\left( \\frac{1}{2} (2\\pi)^2 + \\frac{1}{4} (2\\pi)^4 \\right) = \\boxed{ a^3 \\frac{(2\\pi)^2}{2} \\left( 1 + \\frac{ (2\\pi)^3}{2} \\right) }\n\\end{gathered}\n\\]\n\n\\exercisehead{10} $\\int_C z dx$ \\quad \\, $\\alpha(t) = (t\\cos{t}, t\\sin{t},t)$\n\\[\n\\begin{gathered}\n  \\alpha' = (\\cos{t} + -t\\sin{t}, \\sin{t} + t\\cos{t},1) \\quad \\quad \\, |\\alpha'|^2 = c^2 - 2tsc + t^2 s^2 + s^2 + 2sct + t^2 c^2 + 1 = 2 +t^2 \\\\ \n  \\int t \\sqrt{ 2+ t^2} dt = \\left. \\left( \\frac{1}{3} (2+t^2)^{3/2} \\right) \\right|_0^{t_0} = \\boxed{ \\frac{ (2+t_0^2)^{3/2} - 2^{3/2}}{3} }\n\\end{gathered}\n\\]\n\n\\exercisehead{11} \n\\begin{enumerate}\n\\item\n\\[\n\\begin{gathered}\n  \\begin{aligned}\n    r & = a(\\cos{t},\\sin{t}) \\\\ \n    r' & = a(-\\sin{t}, \\cos{t}) \\\\ \n    \\| \\alpha'(t) \\| & = \\| r'(t) \\| = a \\end{aligned}  \\quad \\, t \\in [ 0,\\pi ] \\quad \\, \\begin{aligned} \\overline{z} & = 0  \\\\ \n    \\overline{y} & = \\frac{1}{ \\pi a} \\int_0^{\\pi} a\\sin{t} a dt = \\left. \\frac{-a}{\\pi} \\cos{t} \\right|_0^{\\pi} = \\frac{2a}{\\pi} \\\\\n    \\overline{x} & = \\frac{1}{ \\pi a} \\int_0^{\\pi} a \\cos{t} a dt = 0 \n\\end{aligned}\n\\end{gathered}\n\\]\n\\item \\[  \\left( \\frac{M}{\\pi a} \\right) \\int_0^{\\pi} a^2 \\sin^2{t} (a) dt = \\frac{a^2 M}{\\pi} \\int_0^{\\pi} \\frac{1 - \\cos{2t}}{2} dt = \\boxed{ \\frac{1}{2} M a^2 } \\]\n\\end{enumerate} \n\n\\exercisehead{12} $\\rho = |x|+|y|$  \\quad \\quad $\\begin{aligned} r & = a (\\cos{t}, \\sin{t}) \\\\ r' & = a(-s(t),c(t)) \\\\ \\| \\alpha'(t) \\| & = \\| r'(t) \\| = a \\end{aligned}$  \\quad \\, $t \\in [0, 2\\pi]$\n\\[\n\\begin{aligned}\n  &  \\int_0^{\\pi/2} (a\\cos{t} + a \\sin{t} )a dt = \\left. a^2 (\\sin{t} - \\cos{t} ) \\right|_0^{\\pi/2} = a^2 ( 1 - (-1)) = 2a^2 \\\\ \n  &  \\int_{\\pi/2}^{\\pi} (-a\\cos{t} + a \\sin{t} )a dt = \\left. a^2 (-\\sin{t} - \\cos{t} ) \\right|_{\\pi/2}^{\\pi} = -a^2 ( -1 + (-1)) = 2a^2 \\\\ \n  &  \\int_{\\pi}^{3\\pi/2} (-a\\cos{t} - a \\sin{t} )a dt = \\left. -a^2 (\\sin{t} - \\cos{t} ) \\right|_{\\pi}^{3\\pi/2} = -a^2 ( -1 - (-(-1))) = 2a^2 \\\\ \n   &  \\int_{3\\pi/2}^{2\\pi} (a\\cos{t} - a \\sin{t} )a dt = \\left. a^2 (\\sin{t} + \\cos{t} ) \\right|_{3\\pi/2}^{2\\pi} = a^2 ( 1 + 1) = 2a^2 \\\\ \n\\end{aligned} \\Longrightarrow \\boxed{ M = 8a^2}\n\\]\n\n\\[\n\\begin{aligned}\n  & \\int_0^{\\pi/2} (a^2 \\sin^2{t})( a\\cos{t} + a \\sin{t}) adt = a^4 \\int_0^{\\pi/2} \\sin^2{t} \\cos{t} + \\sin{t}(1- \\cos^2{t}) dt = a^4 \\left. \\left( \\frac{\\sin^3{t}}{3} + - \\cos{t} + \\frac{1}{3} \\cos^3{t} \\right) \\right|_0^{\\pi/2} = a^4 \\\\\n  &  \\int_{\\pi/2}^{\\pi} (a^2 \\sin^2{t})( -a\\cos{t} + a \\sin{t}) adt = a^4 \\int_{\\pi/2}^{\\pi} (-\\sin^2{t} \\cos{t} + \\sin{t}(1- \\cos^2{t})) dt = \\\\\n  & = a^4 \\left. \\left( \\frac{-\\sin^3{t}}{3} + - \\cos{t} + \\frac{1}{3} \\cos^3{t} \\right) \\right|_{\\pi/2}^{\\pi}  = a^4  \\\\\n  &  \\int_{\\pi}^{3\\pi/2} (-a^2 \\sin^2{t})( a\\cos{t} + a \\sin{t}) adt  = -a^4 \\left. \\left( \\frac{-\\sin^3{t}}{3} + - \\cos{t} + \\frac{1}{3} \\cos^3{t} \\right) \\right|_{\\pi}^{3\\pi/2} = -a^4 \\left( \\frac{-1}{3} + -1 + \\frac{1}{3} \\right) = a^4 \\\\ \n  &   \\int_{3\\pi/2}^{2\\pi} (a^2 \\sin^2{t})( a\\cos{t} - a \\sin{t}) adt  = a^4 \\left. \\left( \\frac{\\sin^3{t}}{3} +  \\cos{t} - \\frac{1}{3} \\cos^3{t} \\right) \\right|_{3\\pi/2}^{2\\pi} = a^4 \\\\ \n  & \\Longrightarrow \\boxed{ I = 4a^4}\n\\end{aligned}\n\\]\n\n\\exercisehead{13} Notice that we have the plane cut through the center of the sphere: like a conic section, we obtain a circle with perpendicular $\\frac{1}{\\sqrt{3}}(1,1,1)$.  \n\\[\n\\begin{aligned}\n  x^2 + y^2 + z^2 & = 1 \\\\ \n  x+ y+z & = 0 \n\\end{aligned} \\quad \\quad \\Longrightarrow x^2 + y^2 + xy = \\frac{1}{2} \\Longrightarrow \\begin{aligned} 2x + 2y y_x + y + xy_x & =0  \\\\ y_x & = \\frac{ - y -2x }{ x + 2y } \\end{aligned}\n\\]\n\\[\n\\begin{aligned}\n  r & = (x,y,z) \\\\ \n  r_x & = \\left( 1 , \\frac{ -y -2x }{ x + 2y}, -1 - \\left( \\frac{ - y - 2x}{ x+2y} \\right) \\right) = \\left( 1, - \\frac{ (y+2x)}{ x+2y} , \\frac{ x-y}{ x+2y} \\right) \\\\\n  r_x^2 & = 1 + \\frac{ (y+2x)^2}{ (x+2y)^2} + \\frac{ (x-y)^2}{(x+2y)^2} = \\left( \\frac{ 3 }{ 2-3x^2} \\right) \\\\\n  |r_x| & = \\frac{ \\sqrt{3}}{ \\sqrt{ 2-3x^2}}\n\\end{aligned}\n\\]\n\nI guess that $x$ ranges between $\\pm \\sqrt{ \\frac{2}{3} }$.  \\\\\nWe're given that the mass density is $x^2$.  If we go around the circle on one branch, one semicircle, from $-\\sqrt{2/3}$ to $\\sqrt{2/3}$ in $x$, and then around in the same direction on the other branch, other semicircle, from $\\sqrt{2/3}$ to $-\\sqrt{2/3}$ in $x$, then we calculate for this branch the same number.  So do the calculation for one semicircle.\n\n\\[\n\\begin{aligned}\n  \\int \\frac{x^2}{ \\sqrt{ 2- 3x^2}} dx & = \\int \\frac{ \\sqrt{ \\frac{3}{2} } x^2 }{ \\sqrt{ 1 - \\left( \\sqrt{ \\frac{3}{2} } x \\right)^2 } } = \\int_{-\\pi/2}^{\\pi/2} \\frac{ \\sqrt{ \\frac{3}{2} } \\frac{2}{3} \\sin^2{\\theta} \\sqrt{ \\frac{2}{3} } \\cos{\\theta} d\\theta}{ \\sqrt{ 1 - \\sin^2{\\theta} } } = \\\\ \n  & = \\int_{-\\pi/2}^{\\pi/2} \\frac{2}{3} \\sin^2{\\theta} d\\theta = \\frac{2}{3} \\left. \\left( \\frac{ \\theta - \\sin{2\\theta}/2}{ 2} \\right) \\right|_{-\\pi/2}^{\\pi/2} = \\boxed{ \\pi/3} \n\\end{aligned} \\quad \\quad \\text{ where } \\begin{aligned}\n    \\sqrt{ \\frac{3}{2} } x & = \\sin{\\theta} \\\\ \n    \\sqrt{ \\frac{3}{2} } dx & = \\cos{\\theta} d\\theta\n  \\end{aligned} \\\\\n\\]\n$ \\Longrightarrow M = \\boxed{ \\frac{2 \\pi}{3} }$\n\n\\exercisehead{14} \\textbf{??? (work on it)} Given $x^2  +y^2 = z^2$, $y^2 = x$, $(0,0,0)$ to $(1,1,\\sqrt{2})$, curve is parametrized s.t.\n\\[\n\\alpha = \\alpha(y) = (y^2, y, y\\sqrt{ 1 +y^2})\n\\]\nWe want $z$-coordinate of the centroid for a uniform wire.  \n\nConsider mass on infinitesimal segment $\\lambda ds$.  \n\nWeight each $\\lambda ds$ with corresponding $z$-coordinate: $z\\lambda dx$\n\nNow $\\alpha'(y) = (2y, 1, \\sqrt{1 +y^2} + \\frac{ y^2}{\\sqrt{ 1 + y^2} } )$.  \n\\[\n\\begin{gathered}\n  \\| \\alpha'(y) \\|^2 = 7y^2 + 2 + \\frac{y^4}{ 1 + y^2} \\\\\n  ds = \\| \\alpha'(y) \\| dy \\\\\nz = y \\sqrt{ 1 + y^2 }\n\\end{gathered}\n\\]\nThen \n\\[\n\\begin{gathered}\n  \\int z ds = \\int y \\sqrt{ 8y^4 + 9y^2 + 2 } dy = \\int y 2 \\sqrt{2} \\sqrt{ (y^2 + \\frac{9}{16} )^2 - \\frac{17}{16^2} } dy \\\\ \n  \\begin{aligned} u & = y^2 + 9/16 \\\\ du & = 2 y dy \\end{aligned} \\quad \\, \\begin{aligned} y & = 0 \\Longrightarrow u = 9/16 \\\\ y & = 1 \\Longrightarrow u = 25/16 \\end{aligned}\n\\end{gathered}\n\\]\n\nNow\n\\[\n\\int \\sqrt{ u^2 + \\beta} = \\frac{1}{2} ( u \\sqrt{ u^2 + \\beta} + \\beta \\ln{ ( u + \\sqrt{ u^2 + \\beta} ) } )\n\\]\n\nSo then \n\\[\n\\int z ds = \\sqrt{2} \\int_{9/16}^{25/16} \\sqrt{ u^2 - \\frac{17 }{16^2} } du  = \\sqrt{ 2}/2 \\left( \\frac{25}{16^2} 4 \\sqrt{38} - \\frac{9}{16} \\frac{8}{16} + \\frac{-17}{16} \\ln{ \\left( \\frac{ 25+ 4 \\sqrt{38} }{ 17}  \\right) } \\right)\n\\]\nsince $\\begin{aligned} 25^2 -17 = 608 = 38 * 16 \\\\ 81 - 17 =64 \\end{aligned}$\n\nHowever, $M = \\lambda \\int ds = \\lambda \\int \\frac{ \\sqrt{ 8y^4 + 9y^2 + 2 } }{ \\sqrt{ y^2 + 1 } } dy $  and we need to divide by $M$.  \n\n\\exercisehead{15} Given $r=(a\\cos{t},a\\sin{t},bt)$, recall that \n\\[\nM = \\sqrt{ a^2 + b^2 } \\int_0^{2\\pi} (a^2 + b^2 t^2) dt = \\sqrt{ a^2 + b^2 }(2\\pi a^2 + \\frac{8}{3} \\pi^3 b^2)\n\\]\n\\[\n\\begin{gathered}\n  \\begin{aligned}\n  \\overline{x}M & = \\int_C x (x^2 + y^2 + z^2) ds = \\sqrt{ a^2 + b^2 } \\int_0^{2\\pi} a \\cos{t} (a^2 + b^2 t^2) dt = \\sqrt{ a^2 + b^2} \\int_0^{2\\pi} ab^2 t^2 \\cos{t} dt = \\\\\n  & = \\left( \\sqrt{ a^2 +b^2 } ab^2 \\right) \\left. (t^2 \\sin{t} + 2t \\cos{t} - 2\\sin{t} ) \\right|_0^{2\\pi} = \\sqrt{ a^2 + b^2} ab^2 (2 (2\\pi)) = \\boxed{ 4 \\pi \\sqrt{a^2 + b^2 } ab^2 }\n  \\end{aligned} \\\\\n  \\begin{aligned}\n    \\overline{y}M & = \\int_C y (x^2 + y^2 + z^2)ds = \\sqrt{ a^2 +b^2 } \\int_0^{2\\pi} a\\sin{t} (a^2 + b^2 t^2)dt = \\\\\n    & = \\sqrt{ a^2 + b^2} ab^2 \\left. \\left( -t^2 \\cos{t} + 2t \\sin{t} + 2\\cos{t} \\right) \\right|_0^{2\\pi} = \\boxed{ \\sqrt{ a^2 + b^2 }ab^2 (-(2\\pi)^2) }\n\\end{aligned}\n\\end{gathered}\n\\]\n\n\\exercisehead{16} \n\\[\n\\begin{gathered}\n  \\begin{gathered}\n    I_x  = \\int_C (y^2 + z^2)(x^2 + y^2 +z^2) ds = \\sqrt{a^2 + b^2} \\int_C (a^2 \\sin^2{t} + b^2 t^2) (a^2 +b^2 t^2) dt = \\\\\n    \\begin{aligned}\n    & = \\rho_0^2 \\int_C (a^4 \\sin^2{t} + a^2 b^2 t^2 + a^2 b^2 t^2 \\sin^2{t} + b^4 t^4 ) dt  = \\rho_0^2 \\int_C a^4 \\left( \\frac{1 - \\cos{2t}}{2} \\right) + a^2 b^2 t^2 + a^2 b^2 t^2 \\left( \\frac{ 1 - \\cos{(2t)}}{2} \\right) + b^4 t^4 dt = \\\\\n    & = \\rho_0^2 \\left( \\frac{a^4(2\\pi)}{2} + \\frac{ a^2 b^2 (2\\pi)^3}{3}  + \\frac{ a^2 b^2 (2\\pi)^3}{2(3)}  + \\frac{b^4 (2\\pi)^5}{5}  - \\frac{ \\pi a^2 b^2}{2}  \\right)  = \\boxed{ \\sqrt{ a^2 + b^2 } \\left( \\pi a^4 +  \\frac{(2\\pi)^3a^2 b^2}{2} + \\frac{ (2\\pi)^5 b^4}{5} - \\frac{\\pi (a^2 b^2)}{2} \\right)}\n  \\end{aligned} \\end{gathered}\\\\\n  \\begin{gathered}\n    I_y  = \\int_C (x^2 + z^2)(x^2 +y^2+z^2) ds = \\rho_0^2 \\int_C (a^2 \\cos^2{t} + b^2 t^2 ) (a^2 + b^2 t^2) dt = \\\\\n    \\begin{aligned}\n    & = \\rho_0^2 \\int_C ( a^4 \\cos^2{t} + a^2 b^2 t^2 + a^2 b^2 t^2 \\cos^2{t} + b^4 t^4 ) dt = \\rho_0^2 \\int_C a^4 \\left( \\frac{ 1 + \\cos{2t} }{2} \\right) + a^2 b^2 t^2 + a^2 b^2 t^2 \\left( \\frac{1 + \\cos{(2t)} }{2} \\right) + b^4 t^4 dt = \\\\\n    & = \\rho_0^2 \\left( \\frac{ a^4 (2\\pi)}{2} + \\frac{ a^2 b^2 (2\\pi)^3}{3}  + \\frac{a^2 b^2 (2\\pi)^3}{2 (3)}  + \\frac{a^2 b^2 \\pi}{2}  + \\frac{ b^4 (2\\pi)^5}{5} \\right) = \\boxed{ \\sqrt{ a^2 + b^2 } \\left( \\pi a^4 + \\frac{ (2\\pi)^3 a^2 b^2}{2} + \\frac{ (2\\pi)^5 b^4}{5} + \\frac{ \\pi a^2 b^2 }{2} \\right) }\n  \\end{aligned} \\end{gathered}\n\\end{gathered}\n\\]\n\n\\section*{ 10.13 Exercises - Open connected sets.  Independence of the path.  The second fundamental theorem of calculus for line integrals.  Applications to mechanics.  }\n\n\\exercisehead{1} Recall the lesson of the preceding sections.  \n\nLet $S$ be an open set in $\\mathbb{R}^n$.  The set $S$ is called connected if every pair of points in $S$ can be joined by a piecewise smooth path whose graph lies in $S$.  That is, for every pair of points $a$ and $b$ in $S$ there is a piecewise smooth path $\\alpha$ defined on an interval $[a,b]$ such that $\\alpha(t) \\in S$ for each $t \\in [a,b]$ with $\\alpha(a) = a$, $\\alpha(b) = b$.  \n\n\\begin{enumerate}\n\\item $S = \\{ (x,y) | x^2 + y^2 \\geq 0 \\}$ connected.  \\\\\nConsider $(x_1,y_1) = (r_1,\\theta_1)$  $(x_2,y_2) = (r_2,\\theta_2)$  \n\nSuppose $r_2>r_1$.  Let $\\alpha_1 = (r\\cos{\\theta_2}, r \\sin{\\theta_2})$ s.t. $r_1 \\leq r \\leq r_2$  \\\\\nThen consider $\\alpha_2 = (r_1 \\cos{\\theta}, r_1 \\sin{\\theta})$ s.t. $\\theta: \\theta_2 \\to \\theta_1$  \n\\item $S = \\{ (x,y) | x^2 + y^2 > 0 \\}$ connected.  \\\\\nSee part(a), with $\\alpha_1$, $\\alpha_2$  \n\\item $S = \\{ (x,y) | x^2 + y^2 < 1 \\}$ connected.  \\\\\nSee part(a), with $\\alpha_1, \\alpha_2$ but with $r_1,r_2 <1$  \n\\item $S = \\{ (x,y) | 1 < x^2 + y^2 < 2 \\}$ connected.  \\\\\nSee part (a), with $\\alpha_1$, $\\alpha_2$, but with $1 < r_1,r_2 <2$  \n\\end{enumerate}\n\n\\exercisehead{2} $f = (P,Q) = \\left( \\frac{ \\partial \\varphi}{\\partial x }, \\frac{ \\partial \\varphi}{ \\partial y } \\right)$  \n\nSince $\\frac{ \\partial P}{\\partial y}$, $\\frac{ \\partial Q}{ \\partial x}$ continuous, then by Apostol Vol. 2, Thm. 8.12, $\\frac{ \\partial P}{\\partial y} = \\frac{ \\partial }{ \\partial y} \\left( \\frac{ \\partial \\varphi }{ \\partial x} \\right)  = \\frac{ \\partial^2 \\varphi }{ \\partial x \\partial y} = \\frac{ \\partial Q}{ \\partial x} $  \n\n\\exercisehead{3}\n\\begin{enumerate}\n\\item  $\\frac{ \\partial P }{\\partial y} = 1$  \\\\\n$\\frac{ \\partial Q}{\\partial x} = -1$  $f(x,y) = y\\mathbf{i} - x \\mathbf{j}$ \\\\\n Consider a square contour lying on $x$ and $y$ axes.  \n\\[\n\\begin{aligned}\n  \\int_{(0,0)}^{(1,0)} f dx & = 0 \\\\ \\int_{(1,1)}^{(0,1)} 1 dy & = -1  \\end{aligned}\\quad \\, \\begin{aligned}\n  \\int_{(1,0)}^{(1,1)} (-1) dy & = -1 \\\\ \\int_{(0,1)}^{(0,0)} 0 = 0 \n\\end{aligned}\n\\]\nSo then $\\int_C f \\cdot ds = -2$\n\\item $f(x,y) = y \\mathbf{i} + (xy-x)\\mathbf{j}$  $\\frac{ \\partial P}{\\partial y} = 1$  $\\frac{ \\partial Q}{ \\partial x} = y-1$  \n\\[\n\\begin{aligned}\n  \\int_{(0,0)}^{(1,0)} f dx & = 0 \\\\ \\int_{(1,1)}^{(0,1)} 1 dx & = -1=-1  \\end{aligned}\\quad \\, \\begin{aligned}\n  \\int_{(1,0)}^{(1,1)} (y-1) dy & = 1/2-1=-1/2 \\\\ \\int_{(0,1)}^{(0,0)} 0 = 0 \n\\end{aligned}\n\\]\n$\\int_C f\\cdot ds = -3/2$ \\end{enumerate}\n\n\\exercisehead{4} $f(x,y,z) = P(x,y,z) \\mathbf{i} + Q(x,y,z) \\mathbf{j} + R(x,y,z)\\mathbf{k}$  \\\\\n We're given that \n\\[\n\\partial_y P, \\partial_z P, \\partial_x Q, \\partial_z Q, \\partial_x P, \\partial_y R\n\\]\nare cont.  \n\nNow\n\\[\nf= \\nabla \\varphi = (P,Q,R) = (\\partial_x \\varphi, \\partial_y \\varphi, \\partial_z \\varphi)\n\\]\n\\[\n\\begin{aligned}\n  & \\partial_y P = \\partial_y \\partial_x \\varphi = \\partial_x \\partial_y \\varphi = \\partial_x Q \\\\  \n  & \\partial_z P = \\partial_z \\partial_x \\varphi = \\partial_x \\partial_z \\varphi = \\partial_x R \\\\\n  & \\partial_z Q = \\partial_z \\partial_y \\varphi = \\partial_y \\partial_z \\varphi = \\partial_x R \n\\end{aligned}\n\\]\n\n\\exercisehead{6} \\begin{enumerate}\n\\item $P = y$, \\quad $Q=z$.  \\\\\n$\\partial_y P = 1$ \\quad $\\partial_x Q = 0$  Not conservative.  \n\\item Since $f\\cdot d\\alpha = f\\cdot \\alpha'(t) dt$  \n\\[\n\\alpha(t) = (\\cos{t}, \\sin{t} ,e^t) \\Longrightarrow \\alpha'(t) = (-\\sin{t}, \\cos{t}, e^t ) \n\\]\n$f=(y,z,yz)$.  \n\\[\n\\begin{gathered}\n  f \\cdot \\alpha'(t) = (-\\sin^2{t} + e^t \\cos{t} + \\sin{t} e^{2t} ) \\\\ \n\\begin{aligned}  \\int_0^{\\pi} (-\\sin^2{t} + e^t \\cos{t} + \\sin{t} e^{2t} ) dt & = - \\pi + \\left. \\left( \\frac{ e^t \\sin{t} + e^t \\cos{t}  }{2} + \\left( e^{2t} \\sin{t} + \\frac{ -e^{2t} \\cos{t} }{2} \\right)/ (5/2) \\right) \\right|_0^{\\pi} = \\\\\n  & = \\boxed{ - \\pi + \\left( \\frac{ e^{ \\pi }(-1) - 1}{2} \\right) + \\frac{2}{5} \\left( \\frac{ -e^{2\\pi } + 1}{2} \\right) } \\end{aligned}\n\\end{gathered}\n\\]\n\\end{enumerate}\n\n\\section*{ 11.9 Exercises - Introduction.  Partitions of rectangles.  Step functions.  The double integral of a step function.  The definition of the double integral of a function defined and bounded on a rectangle.  Upper and lower double integrals.  Evaluation of a double integral by repeated one-dimensional integration.  Geometric interpretation of the double integral as a volume.  Worked examples.  }\n\n\\exercisehead{1} \n\\[\n\\begin{gathered}\n  A(y) = \\int_0^1 yx(x+y) dx = \\frac{y}{3} + \\frac{y^2}{2} \\\\\n  \\int_0^1 A(y) dy = \\frac{1}{6} + \\frac{1}{6} = \\frac{1}{3}\n\\end{gathered}\n\\]\n\n\\exercisehead{2} \n\\[\n\\begin{gathered}\n  A(y) = \\int_0^1 dx (x^3 + 3x^2 y + y^3) = \\frac{1}{4} + y + y^3 \\\\\n  \\int_0^1 A(y) = \\frac{1}{4} + \\frac{1}{2} + \\frac{1}{4} = \\boxed{1}\n\\end{gathered}\n\\]\n\n\\exercisehead{3} \n\\[\n\\begin{gathered}\n  A(y) = \\int_0^1 (\\sqrt{y} + x - 3xy^2) dx = \\sqrt{y} + \\frac{1}{2} - \\frac{3}{2} y^2 \\\\\n  \\int_1^3 \\sqrt{ y} + \\frac{1}{2} - \\frac{3}{2} y^2 = \\left. \\left( \\frac{2}{3} y^{3/2} + \\frac{y}{2} - \\frac{y^3}{2} \\right) \\right|_1^3 = 2 \\sqrt{3} + \\frac{-2}{3} + \\frac{3}{2} - \\frac{1}{2} - \\frac{27}{2} + \\frac{1}{2} = \\boxed{ 2\\sqrt{3} -\\frac{38}{3} }\n\\end{gathered}\n\\]\n\n\\exercisehead{4} \\[\n\\begin{gathered}\n  A(y) = \\int_0^{\\pi} \\sin^2{x} \\sin^2{y} dx = \\sin^2{y} \\frac{\\pi}{2} \\\\ \n  \\int A(y)dy = \\frac{\\pi}{2} \\left( \\frac{\\pi}{2} \\right) = \\frac{\\pi^2}{4}\n\\end{gathered}\n\\]\n\n\\exercisehead{5} \n\\[\n\\begin{gathered}\n  A(y) = \\int_0^{\\pi/2} \\sin{(x+y)} dx = \\left. -\\cos{(x+y)} \\right|_0^{\\pi/2} = \\cos{y} - \\cos{\\left( \\frac{\\pi}{2} + y \\right) } = \\cos{y} + \\sin{y} \\\\\n  \\int_0^{\\pi/2} A(y) dy = \\left. + \\sin{y}\\right|_0^{\\pi/2} - \\left. \\cos{y} \\right|_0^{\\pi/2} = \\boxed{ 2} \n\\end{gathered}\n\\]\n\n\\exercisehead{6} Split the integral up into 4 parts.  Given $\\iint_Q |\\cos{(x+y)}| dx dy$ where $Q = [0,\\pi]\\times [0,\\pi]$\n\\[\n\\begin{gathered}\n  \\begin{aligned}\n    & A(x) = \\int_0^{-x + \\pi/2} \\cos{(x+y)} dy = 1 - \\sin{x} \\\\ \n    & A(x) = \\int_{-x+\\pi/2}^{\\pi} -\\cos{(x+y)} dy = \\left. \\sin{(x+y)} \\right|_{\\pi}^{\\pi/2 - x} = 1 - \\sin{(x+\\pi)} = 1 + \\sin{x} \n\\end{aligned} \\quad \\quad \\, \\Longrightarrow 2 \\\\ \n  \\begin{aligned}\n    & A(x) = \\int_0^{-x + 3\\pi/2} -\\cos{(x+y)} dy = \\left. \\sin{(x+y)} \\right|_{3\\pi/2 - x}^0 = \\sin{x} - (-1) =  1 + \\sin{x} \\\\ \n    & A(x) = \\int_{-x+3\\pi/2}^{\\pi} \\cos{(x+y)} dy = \\left. \\sin{(x+y)} \\right|_{-x+3\\pi/2}^{\\pi} = \\sin{(x+\\pi)} - (-1) = 1 - \\sin{x}\n  \\end{aligned}  \\quad \\quad \\, \\Longrightarrow 2 \\\\ \n  \\int_0^{\\pi} A(x) = \\boxed{ 2 \\pi }\n\\end{gathered}\n\\]\n\n\\exercisehead{7} $\\iint_Q f(x+y) dx dy$ and $Q = [0,2]\\times [0,2]$, $f(t)$ greatest integer $\\leq t$\n\\[\n\\begin{aligned}\n  y <1 & \\\\ \n  & A(y) = \\int_{1-y}^{2-y} 1 dx + \\int_{2-y}^2 2 dx  = 2-y - (1-y) + 2 (2-(2-y)) = 2y +1 \\\\\n  y > 1 & \\\\ \n  & \\begin{gathered}\n    A(y) = \\int_0^{2-y} dx + \\int_{2-y}^{3-y}2dx = \\int_{3-y}^2 3 dy = 2-y + 2 (3-y-(2-y)) + 3(2-(3-y)) = 2y + 1 \\\\ \n  \\end{gathered} \n\\end{aligned}\n\\]\n\\[\n\\int_0^2 (2y+1) = \\boxed{ 6 }\n\\]\n\n\\exercisehead{8} $\\iint_Q y^{-3} e^{tx/y} dx dy$, and $Q = [0,t]\\times [1,t]$, $t>0$\n\\[\n\\begin{gathered}\n  \\int_0^t y^{-3} e^{tx/y} dx = \\left. \\left( \\frac{ y^{-3} e^{tx/y} }{ t/y} \\right) \\right|_0^t = \\frac{ y^{-3} e^{t^2/y}}{ t/y} - \\frac{y^{-2}}{t} \\\\ \n  \\int_1^t y^{-2} e^{t^2/y} dy = \\left. \\frac{ -e^{t^2/y}}{t^2} \\right|_1^t = \\frac{-e^t }{t^2} + \\frac{e^{t^2}}{t^2} \\\\ \n  \\int_1^t y^{-2}/t dy = \\left. \\frac{-1}{yt} \\right|_1^t = \\frac{-1}{t^2} + \\frac{1}{t} \\\\ \n  \\Longrightarrow \\boxed{ -\\frac{e^t}{t^3} + \\frac{e^{t^2}}{t^3} + \\frac{-1}{t} + \\frac{1}{t^2} }\n\\end{gathered}\n\\]\n\n\\exercisehead{9} $Q$ rectangle, $Q = [a,b] \\times [c,d]$.  \n\\[\n\\iint_Q f(x)g(y) dxdy = \\int \\left( \\int_a^b f(x) dx \\right) g(y) dy = \\left( \\int_a^b f(x) dx \\right) \\int_c^d g(y) dy\n\\]\nAssume $\\int_a^b f(x) dx = A$ exists.  \n\n\\exercisehead{10} $f(x,y) = \\begin{cases} 1 - x - y & \\text{ if } x + y \\leq 1 \\\\ 0 & \\text{ otherwise } \\end{cases}$\n\\[\n\\begin{gathered}\n  A(y) = \\int_0^{1-y} (1-x-y) dx = 1- y - \\frac{1}{2} ( 1- 2y + y^2) - y (1-y) = \\frac{1}{2} - y + \\frac{1}{2} y^2 \\\\ \n  \\int_0^1 A(y) dy = \\frac{1}{2} -\\frac{1}{2} + \\frac{1}{6} = \\boxed{ 1/6}\n\\end{gathered}\n\\]\nIndeed, vol. of tetrahedron $= \\frac{1}{3} Bh = \\frac{1}{3} \\left( \\frac{1}{2} (1)(1) \\right) = 1/6$\n\n\\exercisehead{11} If $x < \\frac{1}{\\sqrt{2}}$ \n\\[\n\\begin{gathered}\n  A(x) = \\int_{x^2}^{2x^2} (x+y) dy = x x^2 + \\frac{1}{2} (4x^4 - x^4) = x^3 \\left( 1 + \\frac{3}{2} x \\right) \\\\ \n\\Longrightarrow \\int_0^{1/\\sqrt{2}} A(x) dx \\left. \\left( \\frac{1}{4} x^4 + \\frac{3}{10} x^5 \\right) \\right|_0^{1/\\sqrt{2}} = \\frac{1}{4} \\left( \\frac{1}{4} \\right) + \\frac{3}{10} \\left( \\frac{1}{4} \\right) \\left( \\frac{\\sqrt{2}}{2} \\right) = \\frac{1}{16} + \\frac{3\\sqrt{2}}{80}\n\\end{gathered}\n\\]\nWhen $x > 1/\\sqrt{2}$, \\\\\n\\[\n\\begin{gathered}\n  A(x) = \\int_{x^2}^1 (x+y) dy = (x)(1-x^2) + \\frac{1}{2} (1-x^4) = x - x^3 + \\frac{1}{2} - \\frac{x^4}{2} \\\\ \n  \\int_{1/\\sqrt{2}}^1 ( x - x^3 + \\frac{1}{2} - \\frac{x^4}{2} ) dx = \\frac{1}{2} (1- \\frac{1}{2} ) - \\frac{1}{4} ( 1- \\frac{1}{4} ) + \\frac{1}{2} ( 1 - \\frac{1}{\\sqrt{2}} ) - \\frac{1}{10} ( 1 - \\frac{1}{4\\sqrt{2}} ) = \\frac{ 84}{160} + \\frac{-16\\sqrt{2}}{80} \n\\end{gathered}\n\\]\nSo we get $\\boxed{ \\frac{21}{40} - \\frac{\\sqrt{2}}{5} }$\n\n\\exercisehead{12} $f(x,y) = \\begin{cases} x^2 + y^2 & \\text{ if } x^2 + y^2 \\leq 1 \\\\ 0 & \\text{ otherwise } \\end{cases}$\n\\[\n\\begin{gathered}\n  A(x) = \\int_{-\\sqrt{ 1 = x^2}}^{\\sqrt{ 1- x^2} } (x^2 + y^2) dy = 2x^2 \\sqrt{ 1 - x^2} + \\frac{1}{3} \\left( (\\sqrt{ 1 - x^2} )^3 - (-\\sqrt{ 1 - x^2} )^3  \\right) = \\frac{4}{3} x^2 \\sqrt{ 1 - x^2} + \\frac{2}{3} \\sqrt{ 1 - x^2} \\\\ \n  \\text{ Now } \\\\ \n  \\begin{aligned}\n    & \\int_{-1}^1 x^2 \\sqrt{ 1 - x^2} = \\int_{-\\pi/2}^{\\pi/2} \\sin^2{\\theta} \\cos^2{\\theta} d\\theta = \\int_{-\\pi/2}^{\\pi/2} \\left( \\frac{\\sin{2\\theta}}{2} \\right)^2 d\\theta = \\frac{1}{4} \\int_{-\\pi/2}^{\\pi/2} \\left( \\frac{1 - \\cos{4\\theta} }{2} \\right) = \\pi/8 \\\\ \n    & \\int \\sqrt{ 1 - x^2} dx = \\int_{-\\pi/2}^{\\pi/2} \\cos^2{\\theta} d\\theta = \\pi/2\n  \\end{aligned} \\\\ \n  \\Longrightarrow \\frac{4}{3} \\left( \\frac{\\pi}{8} \\right) + \\frac{2}{3} \\left( \\frac{ \\pi }{2} \\right) = \\boxed{ \\pi/2}\n\\end{gathered}\n\\]\n\n\\exercisehead{13} Split the integral up into 2 parts.\n\\[\n\\begin{gathered}\n  \\begin{aligned} \n    & \\int_1^y (x+y)^{-2} dx = - \\left. (x+y)^{-1} \\right|_1^y = - (2y)^{-1} + (y+1)^{-1} \\\\ \n    & \\int_1^2 \\int_1^y (x+y)^{-2} dx dy = \\frac{-1}{2} \\ln{2} + \\ln{\\left( \\frac{3}{2} \\right) } \n\\end{aligned} \\\\ \n  \\begin{aligned}\n    & \\int_{y/2}^2 (x+y)^{-2} dx = \\left. -(x+y)^{-1} \\right|_{y/2}^2 = -(2+y)^{-1} + \\left( \\frac{3y}{2} \\right)^{-1} \\\\ \n    & \\int_2^4 \\int_{y/2}^2 (x+y)^{-2} dx dy = \\left. -\\ln{(2+y)} \\right|_2^4 + \\frac{2}{3} \\ln{2} = - \\ln{6} + 2\\ln{2} + \\frac{2}{3} \\ln{2}\n  \\end{aligned}\n\\end{gathered}\n\\]\nAdd the two up to get $\\boxed{ \\frac{\\ln{2}}{6} }$ (it may help to remember that $\\ln{3} + -\\ln{6} = \\ln{3} + \\ln{1/6} = \\ln{1/2} = -\\ln{2}$)\n\n\\exercisehead{14}  $Q = [0,1] \\times [0,1]$ and $f(x,y) = \\begin{cases} 1 & \\text{ if } x = y \\\\ 0 & \\text{ if } x \\neq y \\end{cases}$ \\\\\n\nLet $D = \\{ (x,y) | x = y \\}$, $D = $ ``diagonal'' of $Q$.  \\\\\n$D$ has content zero as it's the graph of a continuous function $y=x$, \\, $0\\leq x \\leq 1$.  \\smallskip \\\\\n$f$ discontinuous only on $D$.   \\\\ so $f$ continuous on $D$, with $D$ of content zero, so $f$ integrable on $R$.  \n\\[\n\\iint_{Q-D} f = 0 \\text{ since } f = 0 \\quad \\forall \\, (x,y) \\in Q - D\n\\]\n\n\\section*{ 11.15 Exercises - Integrability of continuous functions.  Integrability of bounded functions with discontinuities.  Double integrals extended over more general regions.  Applications to area and volume.  Worked examples.  }\n\n\\exercisehead{1} \n\\[\n\\begin{gathered}\n  \\int_0^x x\\cos{(x+y)} dy = \\left. x \\sin{(x+y)} \\right|_0^x = x (\\sin{2x} - \\sin{x} ) \\\\\n  \\int_0^{\\pi} dx x (\\sin{2x} - \\sin{x}) = \\left. \\left( \\frac{x \\cos{2x}}{-2} + \\frac{ \\sin{2x}}{4 } + x \\cos{x} - \\sin{x} \\right) \\right|_0^{\\pi} = \\frac{ \\pi }{-2} - \\pi = \\boxed{ \\frac{ -3 \\pi }{2} }\n\\end{gathered}\n\\]\n\n\\exercisehead{2} \n\\[\n\\begin{gathered}\n  \\int_0^{x+1} (1+x) \\sin{y} dy = (1+x) ( 1 - \\cos{(x+1)} ) \\\\\n  \\int_0^1 (1+x) - (1+x) \\cos{(x+1)} = 1 + \\frac{1}{2} - \\left. (1+x)\\sin{(x+1)} - \\cos{(x+1)} \\right|_0^1 = \\frac{3}{2} - 2\\sin{2} - \\cos{2} + \\sin{1} + \\cos{1}\n\\end{gathered}\n\\]\n\n\\exercisehead{3} $\\iint_S e^{x+y} dx dy$ where $S = \\{ (x,y) | |x|+|y| \\leq 1 \\}$\n\\[\n\\begin{gathered}\n  \\begin{gathered}\n    \\int_{-1+x}^{1-x} e^{x+y} dy = e^x (e^{1-x} - e^{-1+x} ) = e^1 - e^{-1 + 2x} \\\\\n    \\int_0^1 (e^{+1} - e^{-1 + 2x} ) dx = e - \\frac{ e^{-1}}{2} (e^2 - 1) = \\frac{e}{2} + \\frac{e^{-1}}{2} \n  \\end{gathered} \\quad \\quad \\, \n  \\begin{gathered}\n    \\int_{-x-1}^{1+x} e^{x+y} dy = e^x (e^{1+x} - e^{-x-1} ) = e^{1+ 2x} - e^{-1} \\\\\n    \\int_{-1}^0 (e^{1+2x} - e^{-1} ) dx = \\frac{e^1}{2} (1- e^{-2}) - e^{-1}(1) = \\frac{-3e^{-1}}{2} + \\frac{e^1}{2}\n  \\end{gathered} \\\\\n  \\Longrightarrow \\boxed{ e - e^{-1} }\n\\end{gathered}\n\\]\n\n\\exercisehead{4} $\\iint_S x^2 y^2 dx dy$  and $\\begin{aligned} xy & = 1 \\\\ xy & = 2 \\\\ y & = x \\\\ y & = 4x \\end{aligned} \\quad \\quad \\, \\begin{aligned} y & = \\frac{1}{x} \\ y & = \\frac{2}{x} \\end{aligned}$ \n\\[\n\\begin{aligned}\n  & I: \\,  (1/2,2) \\to (1/\\sqrt{2}, 2\\sqrt{2}) & \\\\\n   & &  \\begin{gathered} \\int_{1/x}^{4x} x^2 y^2 dy = x^2 \\frac{1}{3} \\left( 64 x^3 - \\frac{1}{x^3} \\right) \\\\ \n    \\frac{1}{3} \\int_{1/2}^{1/\\sqrt{2}} \\left( 64 x^5 - \\frac{1}{x} \\right) dx = \\left. \\frac{1}{3} \\left( \\frac{64 x^6}{6} - \\ln{x} \\right) \\right|_{1/2}^{1/\\sqrt{2}} = \\frac{1}{3} \\left( \\frac{4}{3} - \\frac{1}{6} \\right) - \\frac{1}{3} \\left( \\ln{\\frac{1}{\\sqrt{2}} } - \\ln{ \\frac{1}{2} } \\right) = \\\\\n    = \\frac{7}{18} - \\frac{1}{3} \\left( \\frac{1}{2} \\ln{2} \\right) \\end{gathered}  \n\\end{aligned}\n\\]\n\n\\[\n\\begin{aligned}\n  & II: \\, & (1/\\sqrt{2},2\\sqrt{2}) \\to (1,1) & \\quad \\begin{gathered} \\int_{1/x}^{2/x} x^2 y^2 dy = x^2 \\frac{1}{3} \\left( \\frac{8}{x^3} - \\frac{1}{x^3} \\right) = \\frac{7}{3} \\frac{1}{x} \\\\ \\int_{1/\\sqrt{2}}^1 \\frac{7}{3} \\frac{1}{x} = \\frac{7}{3} - \\ln{ \\frac{1}{\\sqrt{2}}} = \\frac{7}{6} \\ln{2} \\end{gathered} \\\\ \n  & \\quad \\\\\n  & III: \\, & (1,1) \\to (\\sqrt{2},\\sqrt{2}) & \\quad \\begin{gathered} \\int_x^{2/x} x^2 y^2 dy = x^2 \\frac{1}{3} \\left( \\frac{8}{x^3} - x^3 \\right) = \\frac{8}{3} \\frac{1}{x} - \\frac{1}{3} x^5 \\\\ \n    \\int_1^{\\sqrt{2}} \\frac{8}{3} \\frac{1}{x} - \\frac{1}{3} x^5 = \\frac{8}{3} \\ln{\\sqrt{2}} - \\left. \\frac{1}{18} x^6 \\right|_1^{\\sqrt{2}} = \\frac{4}{3} \\ln{2} - \\frac{7}{18} \\end{gathered}\n\\end{aligned}\n\\]\n\\[\n\\Longrightarrow \\frac{4}{3} \\ln{2} - \\frac{7}{18} + \\frac{7}{6} \\ln{2} +  \\frac{7}{18} - \\frac{1}{6} \\ln{2} = \\boxed{ \\frac{7}{3} \\ln{2} }\n\\]\n\n\\exercisehead{5} $ \\iint_S (x^2 - y^2) dx dy$.  \n\\[\n\\begin{gathered}\n  \\int_0^{\\sin{x}} (x^2 - y^2) dy = x^2 \\sin{x} - \\frac{1}{3} \\sin^3{x} = x^2 \\sin{x} - \\frac{1}{3} (1- \\cos^2{x}) \\sin{x}\\\\\n  \\int x^2 \\sin{x} = - x^2 \\cos{x} + 2x \\sin{x} + 2\\cos{x} \\\\ \n  \\iint_S (x^2 - y^2) dx dy = -\\pi^2 (-1) + 2 ((-1)-1) + \\frac{1}{3} (-1-1) + \\left. \\left( \\frac{ \\cos^3{x}}{-9} \\right) \\right|_0^{\\pi} = \\pi^2 + -4 - \\frac{2}{3} + \\frac{2}{9} = \\boxed{ \\frac{-40}{9} + \\pi^2 }\n\\end{gathered}\n\\]\n\\exercisehead{6} $x+2y + 3z = 6$ $\\Longrightarrow z = \\frac{ 6 - x - 2y}{3}$\n\\[\n\\begin{gathered}  \n  \\int_0^{3- \\frac{x}{2} } \\left( \\frac{ 6- x - 2y}{3} \\right) dy = \\frac{1}{3} \\left( 6 \\left( 3 - \\frac{x}{2} \\right) - x \\left( 3 - \\frac{x}{2} \\right) - \\left( 3 - \\frac{x}{2} \\right)^2 \\right) = \\frac{1}{3} \\left( 18 - 3x -3x + \\frac{x^2}{2} - \\left( 9 - 3x + \\frac{x^2}{4} \\right) \\right) = \\\\\n  = \\frac{1}{3} \\left( 9 - 3x + \\frac{x^2}{4} \\right) \\\\ \n  \\int_0^6 \\frac{1}{3} \\left( 9 - 3x + \\frac{x^2}{4} \\right) = \\frac{1}{3} \\left( 9 (6) - \\frac{3 (6)^2}{2} + \\frac{1}{12}6^3 \\right) = \\frac{1}{3}(6) (9-9 + 3 ) = \\boxed{ 6}\n\\end{gathered}\n\\]\nIndeed, $\\frac{1}{3} BH = \\frac{1}{3} ( 9)(2) = 6$\n\n\\exercisehead{7} \\[\n\\begin{gathered}\n  \\int_{-x}^x (x^2 - y^2) dy = x^2 ( x - (-x)) - \\frac{1}{3} (x^3 - (-x)^3 ) = 2x^3 - \\frac{1}{3} (x^3 + x^3) = \\frac{4}{3} x^3 \\\\ \n  \\int_1^3 \\frac{4}{3} x^3 dx = \\left. \\frac{1}{3} x^4 \\right|_1^3 = \\frac{1}{3} (81 - 1) = \\boxed{ \\frac{80}{3} }\n\\end{gathered}\n\\]\n\n\\exercisehead{8}\\begin{enumerate}\n\\item \\[\n\\begin{gathered}\n  \\int_{-1}^1 (x^2 + y^2) dy = x^2 (2) + \\frac{1}{3} (1^3 - (-1)^3) = 2x^2 + \\frac{2}{3} \\\\ \n  \\int_{-1}^1 2x^2 + \\frac{2}{3} = \\frac{2}{3} (2) + \\frac{2}{3} (2) = \\boxed{ 8/3} \n\\end{gathered}\n\\]\n\\item $f(x,y) = 3x + y$.  $S = \\{ (x,y) | 4x^2 + 9y^2 \\leq 36, \\, x > 0, \\, y > 0 \\}$.  Thus, $y^2 \\leq 4 - \\frac{4}{9} x^2$\n\\[\n\\begin{gathered}\n  \\int_0^{2\\sqrt{ 1 - (x/3)^2}} (3x+ y)dy = 3x 2\\sqrt{ 1 - \\left( \\frac{x}{3} \\right)^2} + \\frac{1}{2} 4 (1- \\left( \\frac{x}{3} \\right)^2 ) = 6x \\sqrt{ 1 - \\left( \\frac{x}{3} \\right)^2 } + 2 ( 1 - \\left( \\frac{x}{3} \\right)^2 ) \\\\\n\\int_0^3 6x \\sqrt{ 1- \\left( \\frac{x}{3} \\right)^2 } + 2 (1 - \\frac{x^2}{9} ) = \\left. -18 (1- \\frac{x^2}{9} )^{3/2} \\right|_0^3 + 2 (3) - \\frac{2}{27} (27) = \\boxed{ 22 } \\\\\n\\text{ since } ((1- \\frac{x^2}{9} )^{3/2} )' = \\frac{3}{2} ( 1 - \\frac{x^2}{9} )^{1/2} (\\frac{-2x}{9} ) = \\frac{-x}{3}(1-\\frac{x^2}{9} )^{1/2}\n\\end{gathered}\n\\] \n\\item \\[\n\\begin{gathered}\n  \\int_{-\\sqrt{ 16 - x^2}}^{\\sqrt{ 16 - x^2}} (y+2 x + 20) dy = (2x+ 20) (2\\sqrt{ 16 - x^2}) = 4x \\sqrt{ 16 - x^2} + 40 \\sqrt{ 16 - x^2} \\\\\n  \\int_{-4}^4 4 x \\sqrt{ 16 - x^2} + 40 \\sqrt{ 16 - x^2} = \\int_0^{\\pi} (16 \\cos{\\theta} 4 \\sin{\\theta} + 40 (4) \\sin{\\theta}) 4 \\sin{\\theta} d\\theta = \\frac{640}{2} \\pi = \\boxed{ 320 \\pi } \\\\\n  \\text{ since } \\quad \n\\begin{aligned}\n  x & = 4 \\cos{\\theta} \\\\\n  dx & = -4 \\sin{\\theta} d\\theta\n\\end{aligned}\n\\end{gathered}\n\\]\n\\end{enumerate}\n\n\\exercisehead{9} $\\int_0^1 \\left( \\int_0^y f(x,y) dx \\right) dy = \\int_0^1 \\left( \\int_x^1 f(x,y) dy \\right) dx$ \\exercisehead{10} $\\int_0^2 \\left( \\int_{y^2}^{2y} f(x,y)dx \\right) dy = \\int_0^4 \\left( \\int_{x/2}^{\\sqrt{x}} f(x,y) dy \\right) dx $ \\exercisehead{11} $ \\int_1^4 \\left( \\int_{\\sqrt{x}}^2 f(x,y) dy \\right) dx = \\int_0^2 \\left( \\int_0^{y^2} f(x,y) dx \\right) dy$  \\\\\n\\exercisehead{12} $\\int_1^2 \\left( \\int_{2-x}^{\\sqrt{ 2x - x^2}} f(x,y) dy \\right) dx = \\int_0^1 \\left( \\int_{2-y}^{\\sqrt{ 1 - y^2} + 1 } f(x,y)dx \\right) dy $   \\exercisehead{13} $ \\int_{-6}^2 \\left( \\int_{(x^2-4)/4 }^{2-x} f(x,y) dy \\right) dx = \\int_{-1}^0 \\left( \\int_{ - \\sqrt{ 4y + 4 } }^{\\sqrt{4y+4}} f(x,y) dx \\right) dy + \\int_0^8 \\left( \\int_{-\\sqrt{ 4y + 4}}^{2-y} f(x,y) dx \\right) dy$  \\exercisehead{14} $\\int_1^e \\left( \\int_0^{\\log{x}} f(x,y) dy \\right) dx = \\int_0^1 \\left( \\int_{e^y}^e f(x,y) dx \\right) dy$  \\exercisehead{15} $\\int_{-1}^1 \\left( \\int_{-\\sqrt{ 1 -x^2} }^{1-x^2} f(x,y)dy \\right) dx = \\int_0^1 \\left( \\int_{-\\sqrt{ 1 - y}}^{\\sqrt{ 1- y}} f(x,y)dx \\right) dy + \\int_{-1}^0 \\left( \\int_{-\\sqrt{ 1 - y^2}}^{\\sqrt{ 1 - y^2}} f(x,y) dx \\right) dy$  \\exercisehead{16} $\\int_0^1 \\left( \\int_{x^3}^{x^2} f(x,y)dy \\right) dx = \\int_0^1 \\left( \\int_{\\sqrt{y}}^{y^{1/3}} f(x,y)dx \\right) dy $ \n\n\\exercisehead{17} Consider that $\\sin{(\\pi- x)} = -1 \\sin{(-x)} = \\sin{x} = y$.  This way, we get the ``branch'' of values for $\\pi/2 < x < \\pi$ and $0 < y < 1$.  \n\\[\n\\int_0^{\\pi} \\left( \\int_{-\\sin{(x/2)}}^{\\sin{x}} f(x,y)dy \\right) dx = \\int_0^1 \\left( \\int_{\\arcsin{y}}^{\\pi - \\arcsin{y}} f(x,y)dx \\right) dy + \\int_{-1}^0 \\int_{2 \\arcsin{(-y)}}^{\\pi} f(x,y) dx dy\n\\]\n\n\\exercisehead{18} $\\int_0^4 \\left( \\int_{-\\sqrt{ 4 - y}}^{(y-4)/2} f(x,y) dx \\right) dy = \\int_{-2}^0 \\left( \\int_{2x + 4}^{4-x^2} f(x,y)dy \\right) dx$\n\n\\exercisehead{19} \n\\[\n\\begin{gathered}\n  V = \\int_0^1 \\left( \\int_0^y (x^2 + y^2) dx \\right) dy + \\int_1^2 \\left( \\int_0^{2-y} (x^2 + y^2) dx \\right) dy = \\int_0^1 \\left( \\int_x^{-2x} (x^2 + y^2) dy \\right) dx \\\\\n\\quad \\, \\\\ \n\\begin{gathered}\n  \\int_x^{2-x} (x^2 + y^2) dy  = x^2 ( 2-x-x) + \\frac{1}{3} ( (2-x)^3 - x^3) = x^2 ( 2-  2x ) + \\frac{1}{3} ( 8 - 4x (3) + 3(2) x^2 - x^3 - x^3) = \\\\\n  = 2x^2 - 2x^3 + \\frac{8}{3} - 4x + 2x^2 - \\frac{2x^3}{3} = \\frac{-8}{3} x^3 + 4x^2 - 4x + \\frac{8}{3} \\\\\n  \\xrightarrow{ \\int_0^1 } \\frac{-2}{3} + \\frac{4}{3} - 2 + \\frac{8}{3} = \\boxed{ \\frac{4}{3} }\n\\end{gathered}\n\\end{gathered}\n\\]\n\n\\exercisehead{21} \n\\begin{enumerate}\n\\item $V = \\int_1^2 \\left( \\int_x^{x^3} f(x,y) dy \\right) dx + \\int_2^8 \\left( \\int_x^8 f(x,y) dy \\right) dx = \\int_1^8 \\left( \\int_{y^{1/3}}^y f(x,y) dx \\right) dy $\n\\item\n\\end{enumerate}\n\n\\exercisehead{22} $I= \\int_{-1/2}^1 \\left( \\int_0^x e^{-y^2} dy \\right) dx$ \n\\[\n\\begin{gathered}\n  \\int_{-1/2}^1 \\left( \\int_0^x e^{-y^2} dy \\right) dx = \\int_0^1 \\left( \\int_0^x e^{-y^2} dy \\right) dx + \\int_{-1/2}^0 \\left( \\int_0^x e^{-y^2} dy \\right) dx \\\\ \n  \\begin{aligned}\n    \\int_0^1 \\left( \\int_0^x e^{-y^2} dy \\right) dx & = \\int_0^1 \\left( \\int_y^1 e^{-y^2} dx \\right) dy = \\int_0^1 e^{-y^2} (1-y) dy = A + \\int_0^1 -ye^{-y^2} dy = \\\\\n    & = A + \\left. \\left( \\frac{e^{-y^2}}{2} \\right) \\right|_0^1 = A + \\frac{e^{-1}}{2} - \\frac{1}{2}\n  \\end{aligned}\n\\end{gathered}\n\\]\n\\[\n\\begin{gathered}\n  \\text{ since } \\begin{aligned} z & = -x \\\\ dz & = -dx \\end{aligned} \\\\ \n  \\begin{aligned} \n    \\int_{-1/2}^0 \\left( \\int_0^x e^{-y^2} dy \\right) dx  & = -\\int_{1/2}^0 \\left( \\int_0^{-x} e^{-y^2} dy \\right) dx = \\int_0^{1/2} \\left( \\int_0^{-x} e^{-y^2} dy \\right) dx = -\\int_0^{1/2} \\left( \\int_{-x}^0 e^{-y^2} dy \\right) dx = \\\\\n    & = - \\int_{-1/2}^0 \\left( \\int_{-y}^{1/2} e^{-y^2} dx \\right) dy =  -\\int_{-1/2}^0 e^{-y^2} \\left( \\frac{1}{2} - (-y) \\right) dy = \\\\\n    & = \\frac{-1}{2} \\int_{-1/2}^0 e^{-y^2} dy + - \\int_{-1/2}^0 y e^{-y^2} dy = \\frac{1}{2} \\int_{1/2}^0 e^{-y^2} (+dy) + - \\left. \\left( \\frac{-e^{-y^2}}{2} \\right) \\right|_{-1/2}^0 = \\\\ \n    & = \\frac{-1}{2} \\int_0^{1/2} e^{-y^2} dy + \\frac{1}{2} + \\frac{-e^{-1/4}}{2}\n    \\end{aligned}\n\\end{gathered}\n\\]\n\\[\n\\Longrightarrow I = 2A + e^{-1} - 1 + - B + 1 - e^{-1/4} = \\boxed{ 2A - B + e^{-1} - e^{-1/4} }\n\\]\n\n\n\\exercisehead{23} \\begin{enumerate}\n\\item Suppose $S$ is a type $I$ region, without loss of generality.  \\\\\nUse the geometry of similar triangles.  Thus, observe that the cross-sectional area is a projection of plane region $S$ (from the geometry of similar triangles).  Now express this mathematically.  \n\\[\nA = \\int_a^b dx \\int_{\\phi_1(x)}^{\\phi_2(x)} dy = \\int_a^b \\int_{\\phi_1(x)}^{\\phi_2{x}} dy dx\n\\]\n\\[\n\\int_{ at /h}^{bt/h} dx \\int_{\\phi_1(x) \\left( \\frac{t}{h} \\right)}^{ \\phi_2(x) \\left( \\frac{t}{h} \\right)} dy = \\int_{ at /h}^{bt/h} dx \\int_{\\phi_1}^{\\phi_2} dY \\frac{t}{h} = \\left( \\frac{t}{h} \\right)^2 \\int_a^b dX \\int_{\\phi_1}^{\\phi_2} dY = \\left( \\frac{t}{h} \\right)^2 A\n\\]\n\\item $\\int_0^h \\frac{t^2}{h^2} A = \\boxed{ \\frac{1}{3} hA }$\n\\end{enumerate}\n\n\\exercisehead{24} \n\\[\n\\int_0^1 \\left( \\int_x^a e^{m(a-x)} f(x) dy \\right) dx = \\int_0^1 e^{m(a-x)} f(x)(a-x) dx\n\\]\n\n\n\\section*{ 11.18 Exercises - Further applications of double integrals, Two theorems of Pappus }\n\n\\exercisehead{1} \\[\n\\begin{gathered}\n  \\int_{-2}^1 \\int_{x^2}^{2-x} x dy dx = \\int_{-2}^1 x((2-x) -x^2) = \\left. \\left( x^2  - \\frac{1}{3} x^3 - \\frac{1}{4} x^4 \\right) \\right|_{-2}^1 = 1 - 4 - \\frac{1}{3}(1+8) -\\frac{1}{4} (1-16) = -9/4 \\\\\n  \\begin{aligned}\n    \\int_{-2}^1 \\int_{x^2}^{2-x} y dy dx  &= \\int_{-2}^1 \\frac{1}{2} ((2-x)^2 - x^4) dx = \\int_{-2}^1 \\frac{1}{2} (4-4x + x^2 - x^4) dx = 2 (1+2) - \\left. x^2 \\right|_{-2}^1 + \\left. \\frac{1}{8} x^3 \\right|_{-2}^1 - \\left. \\frac{1}{10} x^5 \\right|_{-2}^1 = \\\\\n    & = 6 + \\frac{1}{6} ( 1 + 8 ) -\\frac{1}{10} (1+32) = \\frac{72}{10} \n\\end{aligned} \\\\ \n\\int_2^1 \\int_{x^2}^{2-x} dy dx = \\int_{-2}^1 (2-x-x^2) = 2(1+2) - \\frac{1}{2} (1-4) - \\frac{1}{3} ( 1 - (-8)) = 9/2 \n\\end{gathered}\n\\]\n\\[\n\\overline{x} = -1/2, \\, \\overline{y} = 8/5\n\\]\n\n\\exercisehead{2} $\\begin{aligned} y^2 & = x  +3 \\quad \\, & (-3,0), \\, (1, \\pm 2) \\\\ y^2 & = 5-x \\quad \\, & (1,\\pm2), \\, (5,0) \\end{aligned}$\n\\[\n\\begin{aligned}\n  \\int_{-2}^2 \\left( \\int_{y^2 - 3}^{5-y^2} dx \\right) dy & = \\int_{-2}^2 5- y^2 - (y^2 - 3) dy = \\int_{-2}^2 8 - 2y^2 dy = 8(4) - \\left. \\frac{2}{3} y^3 \\right|_{-2}^2 = 32 - \\frac{2}{3} ( 8 - (-8)) = \\\\\n  &  = \\frac{ 96 - 32}{3} = \\boxed{ \\frac{64}{3} } \n\\end{aligned}\n\\]\n\\[\n\\begin{aligned}\n  \\int_{-2}^2 \\left( \\int_{y^2 -3}^{5-y^2} x dx \\right) dy & = \\int_{-2}^2 \\frac{1}{2} ( 25 - 10y^2 + y^4 - (y^4 - 6y^2 +9)) dy = \\frac{1}{2} \\int_{-2}^2 (16 - 4y^2 ) dy = \\frac{1}{2} \\left( 16(4) - \\left. \\frac{4}{3} y^3 \\right|_{-2}^2 \\right) = \\\\ \n  & = \\frac{1}{2} (64 - 4/3(16)) = \\frac{1}{2} \\left( \\frac{ 192 - 64 }{3} \\right) = \\frac{1}{6} (128) = \\frac{64}{3}\n\\end{aligned}\n\\]\n\\[\n\\int_{-2}^2 \\int_{y^2-3}^{5-y^2} ydx dy = \\int_{-2}^2 8y -2y^3 = 0 \n\\]\n\\[\n\\overline{x} = 1, \\, \\quad \\overline{y} =0 \n\\]\n\n\\exercisehead{3} $\\begin{aligned} x - 2y + 8 & = 0 \\quad \\, & x & =-2 \\\\ x+ 3y + 5 & = 0 \\quad \\, & x & =4 \\end{aligned}$\n\\[\n\\int_{-2}^4 \\int{\\frac{5+x}{-3}}^{\\frac{x+8}{2}} dy dx = \\int_{-2}^4 \\left( \\frac{3x + 24 + 10 + 2x }{6} \\right) dx = \\int_{-2}^4 \\left( \\frac{5x + 34}{6} \\right) dx = \\left. \\frac{5 x^2}{12} \\right|_{-2}^4 + \\frac{17}{3} (6) = \\frac{5}{12}(12) + 34 = -39 \n\\]\n\\[\n\\overline{x}A = \\int_{-2}^4 dx \\left( \\frac{5x^2 + 34 x}{6} \\right) = \\left. \\frac{1}{6} \\left( \\frac{5}{3} x^3 + 17 x^2 \\right) \\right|_{-2}^4 = \\frac{1}{6} \\left( \\frac{5}{3} ( 64 + 8 ) + 17 (16-4) \\right) = \\frac{1}{6} ( 120 + 17 (12) ) = 54\n\\]\n\\[\n\\begin{aligned}\n  \\overline{y}A & = \\int_{-2}^4 dx \\frac{1}{2} \\left( \\frac{(x^2 + 16x + 64)}{4} -\\frac{25 + 10x + x^2}{9} \\right) = \\int_{-2}^4 \\frac{dx}{2} \\left( \\frac{ 9x^2 + 9(16x) + 9(64) - 100 - 40 x - 4x^2 }{36} \\right)= \\\\ \n  & = \\frac{1}{2(36)} \\int_{-2}^4 dx ( 5x^2 + 18(8x) - 8(5x) + 9(4)(16) - 4(25) ) = \\left. \\frac{1}{36} \\left( \\frac{5}{3} x^3 + 52 x^2 + 119 (4x) \\right) \\right|_{-2}^4 = \\\\\n  & = \\frac{1}{ 2(36) } \\left( \\frac{5}{3} (64 + 8) + 52 (16 -4) + 119(4)(6) \\right) = \\boxed{ 50} \n\\end{aligned}\n\\]\n\\[\n\\boxed{ \\overline{y} = \\frac{50}{39} \\quad \\, \\overline{x} = \\frac{18}{13} }\n\\]\n\n\\exercisehead{4} $y = \\sin^2{x}$; \\quad $ y = 0$; \\, $ 0 \\leq x \\leq \\pi$\n\\[\n\\begin{aligned}\n  & \\int_0^{\\pi} \\int_0^{\\sin^2{x}} dy dx = \\int_0^{\\pi} \\sin^2{x} dx = \\int_0^{\\pi} \\left( \\frac{1 - \\cos{2x}}{2} \\right) dx = \\frac{\\pi}{2} \\\\ \n  & \\int_0^{\\pi} \\int_0^{\\sin^2{x}} x dy dx = \\int_0^{\\pi} x \\sin^2{x} dx = \\int_0^{\\pi} x \\left( \\frac{ 1-  \\cos{2x}}{2} \\right) dx = \\frac{\\pi^2}{4 } - \\left. \\frac{1}{2} \\left( \\frac{ x\\sin{2x}}{2} + \\frac{\\cos{2x}}{4} \\right) \\right|_0^{\\pi} = \\frac{ \\pi^2}{4} \\quad \\, \\\\ \n  & \\int_0^{\\pi} \\int_0^{\\sin^2{x}} y dy dx = \\int_0^{\\pi} \\frac{1}{2} \\sin^4{x} dx = \\frac{1}{2} \\int_0^{\\pi} \\left( \\frac{ 1 - \\cos{2x} }{2} \\right)^2 dx = \\frac{1}{8} \\int_0^{\\pi} 1 - 2 \\cos{2x} + \\cos^2{2x} = \\frac{1}{8} (\\pi + \\frac{\\pi}{2} ) = \\frac{3\\pi}{16} \\quad \\,\n\\end{aligned}\n\\]\n\\[\n\\overline{x} =  \\pi^2/4 / \\pi/2 = \\boxed{ \\pi/2 } \\quad \\,  \\overline{y} =   \\frac{ \\frac{3\\pi}{16} }{ \\frac{ \\pi}{2} } = \\boxed{ \\frac{3}{8 } }\n\\]\n\n\\exercisehead{5} \\[\n\\begin{gathered}\n  \\int_0^{\\pi/4} \\int_{\\sin{x}}^{\\cos{x}} dy dx = \\int_0^{\\pi/4} \\cos{x} - \\sin{x} = \\left. (\\sin{x} + \\cos{x} ) \\right|_0^{\\pi/4} = \\sqrt{2} - 1 \\\\ \n  \\int_0^{\\pi/4} \\int_{\\sin{x}}^{\\cos{x}} x dy dx = \\int_0^{\\pi/4} x (\\cos{x} - \\sin{x}) dx = \\left. (x\\sin{x} + \\cos{x} + x\\cos{x} - \\sin{x} ) \\right|_0^{\\pi/4} = \\frac{\\pi}{2} \\frac{\\sqrt{2}}{2} - 1 \\quad \\quad \\, \\boxed{ \\overline{x} = \\frac{ \\frac{ \\pi \\sqrt{2}}{4} - 1 }{ \\sqrt{ 2}- 1} } \\\\ \n  \\int_0^{\\pi/4} \\frac{1}{2} (\\cos^2{x} - \\sin^2{x}) dx = \\frac{1}{2} \\int_0^{\\pi/4} \\cos{2x} dx = \\left. \\frac{1}{4} \\sin{2x} \\right|_0^{\\pi/4} = \\frac{1}{4} \\quad \\quad \\, \\boxed{ \\overline{y} = \\frac{1/4}{ \\sqrt{2}- 1} }\n\\end{gathered}\n\\]\n\n\\exercisehead{6} $\\begin{aligned} y & = \\log{x} \\\\ y & = 0 \\end{aligned}$, \\quad $1 \\leq x \\leq a$.  \n\\[\n\\begin{gathered}\n  \\int_1^a \\int_0^{\\log{x}} dy dx = \\int_1^a \\log{x} dx = \\left. ( x\\log{x} - x ) \\right|_1^a = a \\log{a} - a + 1 \\\\ \n  \\int_1^a \\int_0^{\\log{x}} x dy dx = \\int_1^a x dx \\log{x}=  \\left. \\left( \\frac{x^2 \\log{x}}{2} - \\frac{x^2}{4} \\right) \\right|_1^a = \\frac{a^2 \\log{a} }{2} - \\frac{ (a^2 -1)}{4} \\quad \\, \\Longrightarrow \\boxed{ \\overline{x} = \\frac{ \\left( \\frac{ 2a^2 \\log{a} - (a^2-1)}{4} \\right) }{ a\\log{a} - a + 1 } } \\\\ \n  \\begin{aligned}\n\\int_1^a \\int_0^{\\log{x}} y dy dx & = \\int_1^a \\frac{1}{2} (\\log{x})^2 dx = \\left. \\frac{1}{2} \\left( (\\log{x})^2 x - 2x \\log{x} + 2x \\right) \\right|_1^a = \\frac{1}{2} (a(\\log{a})^2 - 2a \\log{a} + 2a - 2 ) = \\\\\n &  = \\frac{1}{2} a (\\log{a})^2 - a \\log{a} + a - 1 \n\\end{aligned}\\\\ \n  \\begin{aligned} ((\\log{x})^2 x )' & = (\\log{x})^2 + 2(\\log{x}) \\\\ \n    (x\\log{x} - x)' & = \\log{x}\n\\end{aligned} \\quad \\quad \\, \\Longrightarrow \\boxed{ \\overline{y} = \\frac{ \\frac{1}{2} a (\\log{a})62 - a\\log{a} + a - 1 }{ a \\log{a} - a + 1 } }\n\\end{gathered}\n\\]\n\n\\exercisehead{7} $ \\sqrt{x} + \\sqrt{y} =1$ or $\\sqrt{y} = 1 - \\sqrt{x}$.  $x=0, y=0$.  So $y = 1 - 2\\sqrt{x} + x$.  \n\\[\n\\begin{gathered}\n  \\int_0^1 \\int_0^{1-2\\sqrt{x} + x } dy dx = \\int_0^1 (1-2\\sqrt{x} + x) = \\left. (x- \\frac{4}{3} x^{3/2} + \\frac{1}{2} x^2 ) \\right|_0^1 = 1 - \\frac{4}{3} + \\frac{1}{2} = \\boxed{ \\frac{1}{6} } \\\\ \n  \\begin{aligned}\n    \\int_0^1 \\int_0^{1-2\\sqrt{x} + x} y dy dx & = \\int_0^1 dx \\frac{1}{2} ( 1 -4 \\sqrt{x} + 2x + 4x - 4x^{3/2} + x^2) = \\int_0^1 dx \\frac{1}{2} ( 1 - 4 x^{1/2} + 6x - 4x^{3/2} + x^2) = \\\\\n    & = \\frac{1}{2} \\left. (x- \\frac{8}{3} x^{3/2} + 3x^2 - \\frac{8x^{5/2}}{5} + \\frac{1}{3} x^3 ) \\right|_0^1 =  \\frac{1}{30} \n\\end{aligned} \\\\ \n  \\Longrightarrow \\boxed{ \\overline{y} = 1/5 } \\\\ \n  \\int_0^1 \\int_0^{1-2\\sqrt{x} + x} x dy dx = \\int_0^1 x (1-2\\sqrt{x} + x) dx = \\left. \\left( \\frac{1}{2} x^2 - 2\\frac{2}{5} x^{5/2} + \\frac{1}{3} x^3 \\right) \\right|_0^1 = \\frac{1}{3} \\\\ \n  \\Longrightarrow \\boxed{ \\overline{ x} = 1/5 }\n\\end{gathered}\n\\]\n\n\\exercisehead{8} $x^{2/3} + y^{2/3} = 1$ or $\\begin{aligned} y^{2/3} & = 1 - x^{2/3} \\\\ y & = (1-x^{2/3})^{3/2} \\end{aligned}$ and $x =0$, \\, $ y=0$.  \n\\[\n\\begin{gathered}\n  \\text{ Since } \\begin{aligned} u & = 1 - x^{2/3} \\quad \\quad \\, \\text{ or } x^{2/3} = 1 - u \\\\ du & = \\frac{-2}{3} x^{-1/3} dx \\\\ & \\frac{-3}{2} du ( \\sqrt{ 1 - u } ) = dx \\end{aligned} \\\\ \n  \\int_0^1 \\int_0^{(1-x^{2/3})^{3/2} } dy dx = \\int_0^1 (1-x^{2/3})^{3/2} dx = \\int_1^0 u^{3/2} \\left( \\frac{-3}{2} \\right) du (1-u)^{1/2} \n\\end{gathered}\n\\]\n\\[\n\\begin{gathered}\n\\begin{aligned}\n  \\int u^{3/2} (1-u)^{1/2} & = \\int u^{3/2} \\left( \\frac{-2}{3} (1-u)^{3/2} \\right)' = u^{3/2} \\frac{-2}{3} (1-u)^{3/2} - \\int \\frac{3}{2} u^{1/2} \\frac{-2}{3} (1-u)(1-u)^{1/2} = \\\\\n  & = \\frac{-2}{3} u^{3/2} (1-u)^{3/2} + \\int (u^{1/2} (1-u)^{1/2} - u^{3/2} (1-u)^{1/2} ) \n\\end{aligned} \\\\\n\\Longrightarrow 2 \\int u^{3/2}(1-u)^{1/2} = \\frac{-2}{3} u^{3/2} (1-u)^{3/2} + \\int u^{1/2} (1-u)^{1/2} \n\\end{gathered}\n\\]\n\\[\n\\int u^{1/2} (1-u)^{1/2} = \\int (u-u^2)^{1/2} = \\int \\left( \\frac{1}{4} - \\left( \\frac{1}{2} - u\\right)^2 \\right)^{1/2} = \\frac{1}{2} \\int \\sqrt{ 1 - (1-2u)^2 }\n\\]\n\\[\n\\begin{gathered}\n\\text{ Since } \\begin{aligned} x & = (1-2u) \\\\ dx & = -2 du \\end{aligned} \\quad \\text{ and } \\quad \\begin{aligned} x &= \\sin{\\theta} \\\\ dx & = \\cos{\\theta} d\\theta \\end{aligned} \\text{ then } \\\\ \n\\int \\sqrt{ 1 - (1-2u)^2 } = \\int \\frac{dx}{-2} \\sqrt{ 1 - x^2} = \\int \\frac{ \\cos{\\theta} d\\theta}{-2} \\cos{\\theta} = \\int \\frac{ 1 + \\cos{2\\theta} }{-4}  = \\frac{-1}{4} ( \\theta + \\frac{ \\sin{2\\theta}}{2} )\n\\end{gathered}\n\\]\n\\[\n\\begin{gathered}\n  \\begin{aligned}\n    \\int_0^1 u^{3/2} (1-u)^{1/2} du & = \\frac{1}{2} \\int_0^1 u^{1/2} (1-u)^{1/2} = \\frac{1}{4} \\int_0^1 \\sqrt{ 1 - (1-2u)^2 } = \\frac{-1}{8} \\int_1^{-1} dx \\sqrt{ 1 - x^2} = \\\\\n    & = \\frac{-1}{8} \\int_{\\pi/2}^{-\\pi/2} \\left( \\frac{1+ \\cos{2\\theta}}{2} \\right) d\\theta = \\\\ \n    & = \\frac{-1}{16} \\left. \\left( \\theta + \\frac{ \\sin{2\\theta}}{2} \\right) \\right|_{\\pi/2}^{-\\pi/2} = \\frac{-1}{16} \\left( \\frac{-\\pi}{2} - \\frac{\\pi}{2} \\right) = \\boxed{ \\pi/16} \n  \\end{aligned} \\\\\n  \\Longrightarrow A = \\frac{3}{2} \\frac{\\pi}{16} = \\boxed{ \\frac{3\\pi}{32} }\n\\end{gathered}\n\\]\n\\[\n\\begin{gathered}\n  \\begin{aligned}\n  \\int_0^1 \\int_0^{(1-x^{2/3})^{3/2}} x dy dx & = \\int_0^1 x(1-x^{2/3})^{3/2} dx = \\int_1^0 \\frac{-3}{2} du \\sqrt{ 1-  u} u^{3/2} (1-u)^{3/2} = \\frac{3}{2} \\int_0^1 du(1 -2u + u^2) u^{3/2} = \\\\ \n  & = \\frac{3}{2} \\int_0^1 du (u^{3/2} - 2u^{5/2} + u^{7/2} ) = \\\\\n  & = \\frac{3}{2} \\left( \\frac{2}{5} - 2 \\left( \\frac{2}{7} \\right) + \\frac{2}{9} \\right) = \\frac{3}{2} \\left( \\frac{2}{5} - \\frac{4}{7} + \\frac{2}{9} \\right) = \\frac{8}{105}\n  \\end{aligned} \\\\\n  \\Longrightarrow \\boxed{ \\overline{x} = 256\\pi/315 }\n\\end{gathered}\n\\]\n\\[\n\\begin{gathered}\n  \\begin{aligned}\n    \\int_0^1 \\int_0^{(1-x^{2/3})^{3/2}} y dy dx & = \\int_0^1 \\frac{1}{2} ( 1 - x^{2/3})^3 dx = \\frac{1}{2} \\int_0^1 ( 1 + 3 (-x^{2/3} ) + 3 x^{4/3} - x^2 ) dx = \\\\ \n    & = \\frac{1}{2} \\left( 1 + -3 \\left( \\frac{ 3 (1)^{5/3}}{5} \\right) + 3 \\frac{3}{7} - \\frac{1}{3} \\right) = \\frac{1}{2} \\left( 1 + \\frac{ -9}{5} + \\frac{9}{7} + \\frac{-1}{3} \\right) = \\frac{1}{2} \\left( \\frac{-4}{5} + \\frac{9}{7} - \\frac{1}{3}  \\right) = \\frac{8}{105}\n  \\end{aligned} \\\\\n  \\Longrightarrow \\boxed{ \\overline{y} = 256\\pi/315 }\n\\end{gathered}\n\\]\n\n\\exercisehead{9} $\\int_0^2 \\int_0^{ x(2-x)} \\left( \\frac{ 1 - y}{ 1+ x} \\right) dy dx = \\int_0^{2} \\frac{1}{1+x} \\int_0^{x(2-x)} (1-y)dy dx$\n\\[\n\\begin{gathered}\n  \\frac{1}{2} ( x(2-x))^2 = \\frac{1}{2} x^2 (4- 4x + x^2) = 2x^2 - 2x^3 + \\frac{1}{2} x^4 \\\\ \n\\int_0^{x(2-x)} (1-y)dy =   2x - x^2 - 2x^2 + 2x^3 - \\frac{1}{2} x^4 = 2x - 3x^2 + 2x^3 - \\frac{1}{2} x^4 = \\\\ \n= \\frac{-1}{2} x^4 - \\frac{1}{2} x^3 + \\frac{5}{2} x^3 + \\frac{5}{2} x^2 - \\frac{11}{2} x^2 - \\frac{11}{2} x + \\frac{15}{2} x = \\left( \\frac{-1}{2} x^3 + \\frac{5}{2} x^2 - \\frac{11}{2} x \\right) (x+1) + \\frac{15}{2} x \n\\end{gathered}\n\\]\n\\[\n\\begin{gathered}\n  \\int_0^2 \\frac{1}{1+x} \\int_0^{x(2-x)} (1-y)dy dx = \\int_0^2 \\frac{1}{1+x} \\left( \\left( \\frac{-1}{2} x^3 + \\frac{5}{2} x^2 - \\frac{11x}{2} \\right)(x+1) + \\frac{15x}{2} \\right) = \\\\\n  = \\int_0^2 dx \\left( \\left( \\frac{-1}{2} x^3 + \\frac{5}{2} x^2 - \\frac{11x}{2} \\right) + \\frac{15x}{12(1+x)} \\right) = \\\\\n  = \\frac{-1}{8}(16) + \\frac{5}{6} (8) -\\frac{11}{4} (4) + \\frac{15}{2} \\left( 2 + \\left. \\ln{(1+x)} \\right|_0^2 \\right) = -2 + \\frac{20}{3} - 11 + \\frac{15}{2} (2 - \\ln{(3)}) = \\boxed{ \\frac{26}{3} + \\frac{-15}{2} \\ln{3} }\n\\end{gathered}\n\\]\n\n\\exercisehead{10} \\[\n\\begin{aligned}\n  & \\int_0^a \\int_0^b (xy) dy dx = \\int_0^a x \\frac{1}{2} b^2 dx = \\frac{1}{4} a^2 b^2 \\\\ \n  & \\int_0^a \\int_0^b (xy^2) dy dx = \\int_0^a x \\frac{1}{3} b^3 dx = \\frac{1}{6} a^2 b^3 \\\\ \n  & \\int_0^a \\int_0^b x^2 y dy dx = \\int_0^a x^2 \\frac{1}{2} b^2 = \\frac{1}{6} b^2 a^3 \n\\end{aligned}\n\\]\n\\[\n\\boxed{ \\overline{x} = \\frac{ \\frac{1}{6} b^2 a^3 }{ \\frac{1}{4} a^2 b^2 } = \\frac{2}{3} a \\quad \\, \\overline{y} = \\frac{ \\frac{1}{6} a^2 b^3 }{ \\frac{1}{4} a^2 b^2 } = \\frac{2}{3} b }\n\\]\n\n\\exercisehead{11} \\quad \\\\ \n$\\begin{aligned} \ny & = \\sin^2{x} \\\\ \ny & = -\\sin^2{x} \\end{aligned}$ \\quad \\, $-\\pi \\leq x \\leq \\pi$; \\, $f(x,y) = 1$  \n\\[\n\\begin{aligned}\n  I_x & = \\int_{-\\pi}^{\\pi} \\left( \\int_{-\\sin^2{x}}^{\\sin^2{x} } y^2 dy \\right) dx = \\int_{-\\pi}^{\\pi} \\frac{1}{3} 2 \\sin^6{x} dx = \\frac{2}{3} \\int_{-\\pi}^{\\pi} \\left( \\frac{1- \\cos{2x}}{2} \\right)^3 = \\\\\n  & = \\frac{1}{12} \\int_{-\\pi}^{\\pi} 1 + -3\\cos{2x} + 3 \\cos^2{2x} + \\cos^3{2x}  = \\boxed{ \\frac{5 \\pi}{12} } \n\\end{aligned}\n\\]\n\\[\n\\begin{aligned}\n  I_y & = \\int_{-\\pi}^{\\pi} \\int_{-\\sin^2{x}}^{\\sin^2{x}} x^2 dy dx = \\int_{-\\pi}^{\\pi} x^2 2\\sin^2{x} dx = 2 \\int_{-\\pi}^{\\pi} 2x^2 \\left( \\frac{1- \\cos{2x}}{2} \\right) dx = \\\\\n  &  = \\int_{-\\pi}^{\\pi} x^2 - x^2 \\cos{2x}= \\boxed{ \\frac{2\\pi^3}{3} - \\pi }\n\\end{aligned}\n\\]\n\n\\exercisehead{12} $\\frac{x}{a} + \\frac{y}{b} = 1$, \\, $\\frac{x}{c} + \\frac{y}{b} = 1$, \\, $y =0, \\, 0 < c < a, \\, b > 0 ;  \\, f(x,y) = 1$\n\n\\[\nI_y = \\int_0^b \\left( \\int_{ c(1 - y/b )}^{a(1 - y/b)} x^2 dx \\right) dy  = \\int_0^b \\left( \\frac{ a^3 (1-y/b)^3 - c^3(1-y/b)^3 }{3} \\right) dy = \\left. \\left( \\frac{a^3 - c^3}{3} \\right)(-b)\\left( 1 - \\frac{y}{b} \\right)^4/b \\right|_a^b = \\boxed{ (a^3 - c^3) \\frac{b}{12} }\n\\]\n\\[\nI_x = \\int_0^b y^2 (a-c) (1- y/b) dy = (a-c) \\left( \\frac{1}{3} b^3 - \\frac{1}{4} \\frac{b^4}{b} \\right) = \\boxed{ (a-c)(b^3)/12 }\n\\]\n\n\\exercisehead{13} $(x-r)^2 + (y-r)^2 = r^2$, $y=0, \\, x=0$.  $0 \\leq x \\leq r$, $0 \\leq y \\leq r$.  So we want the piece of the graph that is the ``lower left-hand corner'' of the ``complement'' of the circle centered at $(r,r)$, with radius $r$.  Be careful about this point.  \n\\[\n\\begin{aligned}\n  & \\text{ since } \\begin{aligned} x -r & = r \\sin{\\theta} \\\\ dx & = r \\cos{\\theta} d\\theta \\end{aligned} \\\\\n  I_x & = \\int_0^r \\int_0^{r - \\sqrt{ r^2 - (x-r)^2} } y^2 dy dx = \\int_0^r \\frac{1}{3} r^3 \\left( 1 - \\sqrt{ 1 - \\left( \\frac{x-r}{r} \\right)^2 } \\right)^3 dx = \\frac{r^4}{3} \\int_{-\\pi/2}^0 (1-\\cos{\\theta})^3 \\cos{\\theta} d\\theta = \\\\\n  & = \\frac{r^4}{3} \\int_{-\\pi/2}^0 c - 3c^2 + 3c^3 - c^4 = \\boxed{ r^4 \\left( 1 - \\frac{5\\pi}{16} \\right) }\n\\end{aligned} \n\\]\nSince \n\\[\n\\begin{aligned}\n  & \\int_{-\\pi/2}^0 c = \\left. s \\right|_{-\\pi/2}^0 = -(-1) = 1 \\\\ \n  & \\int_{-\\pi/2}^0 c^2 = \\int_{-\\pi/2}^0 \\frac{1 + \\cos{2\\theta}}{2} d\\theta = \\frac{\\pi}{4} \\\\ \n  & \\int_{-\\pi/2}^0 c^3 = \\int_{-\\pi/2}^0 c(1-s^2) = 1 - \\frac{1}{3} ( 0 - (-1)) = 2/3 \\\\\n  & \\int_{-\\pi/2}^0 c^4 = \\int_{-\\pi/2}^0 \\left( \\frac{1 + \\cos{2\\theta}}{2} \\right)^2 d\\theta = \\int_{-\\pi/2}^0 \\frac{1}{4} (1 + 2\\cos{2\\theta} + \\cos^2{2\\theta} ) d\\theta = \\frac{1}{4} \\left( \\frac{\\pi}{2} + \\frac{\\pi}{4} \\right) = \\frac{3\\pi}{16} \n\\end{aligned}\n\\]\n\\[\n\\begin{aligned}\n  I_y & = \\int_0^r \\int_0^{r - \\sqrt{ r^2 - (x-r)^2} } x^2 dy dx = \\int_0^r x^2 r \\left( 1 - \\sqrt{ 1 - \\left( \\frac{x-r}{r} \\right)^2} \\right) dx = \\int_{-\\pi/2}^0 (r^2)(\\sin{\\theta} +1)^2 r(1-\\cos{\\theta}) r\\cos{\\theta} d\\theta = \\\\\n  & = r^4 \\int_{-\\pi/2}^0 (s^2 + 2s +1)(1-c) c d\\theta = r^4 \\int_{-\\pi/2}^0 (s^2 c + 2sc + c - c^2 s^2 - 2sc^2 - c^2 ) d\\theta = \\boxed{ r^4 \\left( 1 - \\frac{5\\pi}{16} \\right) }\n\\end{aligned}\n\\]\nSince\n\\[\n\\begin{aligned}\n  & \\int_{-\\pi/2}^0 s^2 c = \\left. \\frac{1}{3} s^3 \\right|_{-\\pi/2}^0 = \\frac{1}{3} \\\\ \n  & \\int c = \\left. \\frac{1}{2} s^2 \\right|_{-\\pi/2}^0 = \\frac{-1}{2} \\\\ \n  & \\int c = 1 \n\\end{aligned} \\quad \\quad \\, \n\\begin{aligned} \n  & \\int c^2 s^2 = \\int \\left( \\frac{ \\sin{2\\theta}}{2} \\right)^2 = \\frac{1}{4} \\int_{-\\pi/2}^0 \\frac{1 - \\cos{4\\theta} }{2} = \\frac{\\pi}{16} \\\\ \n  & \\int sc^2 = \\left. \\left( \\frac{-1}{3} c^3 \\right) \\right|_{-\\pi/2}^0 = -1/3 \\\\ \n  & \\int c^2 = \\pi/4 \n\\end{aligned}\n\\]\n\n\\exercisehead{16} $y = \\sqrt{ 2x}$, \\, $y=0$, \\, $ 0 \\leq x \\leq 2$, \\, $f(x-y) = |x-y|$\n\\[\n\\begin{aligned}\n  I_y & = \\int_0^2 \\int_0^x x^2 dy dx ( x-y) + \\int_0^2 \\int_x^{\\sqrt{ 2x}} x^2 dy dx ( y -x ) = \\\\\n  & = \\int_0^2 \\left( x^3 (x) - x^2 \\frac{1}{2} x^2 \\right) + \\int_0^2 x^2 \\left( \\frac{1}{2} ((2x) - x^2) \\right) - x^3 (\\sqrt{ 2x} - x )  = \\\\ \n  & = \\frac{1}{10} \\left. x^5 \\right|_0^2 + \\frac{1}{4} \\left. x^4 \\right|_0^2 - \\frac{1}{10} \\left. x^5 \\right|_0^2 - \\sqrt{2} \\left. \\frac{2x^{9/2}}{9} \\right|_0^2 + \\frac{1}{5} 2^5 = 4- \\frac{2^6}{9} + \\frac{2^5}{5} = \\boxed{ \\frac{148}{45} } \\\\\n\\end{aligned} \n\\]\n\\[\n\\begin{aligned} \n I_x & = \\int_0^2 \\int_0^x y^2 dy dx (x-y) + \\int_0^2 \\int_x^{\\sqrt{2x}} y^2 dy dx (y-x) = \\\\\n & = \\int_0^2 \\left( \\left. \\frac{1}{3} y^3 \\right|_0^x x - \\frac{1}{4} \\left. y^4 \\right|_0^4 \\right) dx + \\int_0^2 \\left( \\left. \\frac{1}{4} y^4 \\right|_x^{\\sqrt{2x}} - x \\left. \\frac{1}{3} y^3 \\right|_x^{\\sqrt{2x}} \\right) dx = \\\\\n  & = \\int_0^2 \\left( \\frac{1}{3} x^4 - \\frac{1}{4} x^4 \\right) dx + \\int_0^2 \\frac{1}{4} (4x^2 - x^4) - \\frac{x}{3} (2^{3/2} x^{3/2} - x^3 ) = \\\\\n  & = \\int_0^2 \\left( \\frac{1}{12} x^4 + x^2 - \\frac{x^4}{4} - \\frac{2^{3/2}}{3} x^{5/2} + \\frac{x^4}{3} \\right) = \\int_0^2 \\frac{1}{6} x^4 + x^2 - \\frac{2^{3/2}}{3} x^{5/2} = \\\\\n  & = \\frac{1}{30} (2^5) + \\frac{1}{3} 2^3 - \\frac{2^{3/2}}{3} \\frac{2}{7} 2^{7/2} = \\boxed{ \\frac{24}{35} }\n\\end{aligned}\n\\]\n\n\n\\exercisehead{17} Let $S$ be thin plate of mass $m$.  \\\\\nLet the center of mass of thin plate $S$ be located at the coordinate axis origin.  \\\\\nLet $L_0, L$ be parallel to the $x$ axis.  \\\\\nLet $h$ be the perpendicular distance of $L$ from $L_0$, with the sign of $h$ included.  \\\\\nSince $m$ is the mass, $\\int_a^b \\int_{\\phi_1(x)}^{\\phi_2(x)} dy dx = m $ \\\\ \nSince CM is at $(0,0)$, $\\overline{y} = 0 = \\int_a^b \\int_{\\phi_1(x)}^{\\phi_2(x)} y dy dx = 0$\n\\[\n\\text{ moment of inertia about $L$ } = \\int_a^b \\int_{\\phi_1(x)}^{\\phi_2(x)} (y-h)^2 dy dx = \\int_a^b \\int_{\\phi_1(x)}^{\\phi_2(x)} y^2 - 2yh + h^2 dy = \\boxed{ I_{L_0} + mh^2 } \n\\]\n\n\\exercisehead{18} The perpendicular direction is given by the following:\n\\[\n(\\cos{(\\alpha + \\pi/2)}, \\sin{(\\alpha + \\pi/2)} ) = (-\\sin{\\alpha}, \\cos{\\alpha})\n\\]\nThen\n\\[\n(x,y) \\cdot (-\\sin{\\alpha}, \\cos{\\alpha}) = - x \\sin{\\alpha} + y \\cos{\\alpha} = \\delta\n\\]\nWe want to find the square of the above quantity, $\\delta^2$.\n\\[\n\\begin{gathered}\n  \\int_{-b\\sqrt{ 1 - \\left( \\frac{x}{a} \\right)^2 }}^{ b \\sqrt{ 1 - \\left( \\frac{x}{a} \\right)^2}} (x^2 \\sin^2{\\alpha} + -2xy \\sin{\\alpha} \\cos{\\alpha} + y^2 \\cos^2{\\alpha} ) dy = 2x^2 \\sin^2{\\alpha} b \\sqrt{ 1 - (x/a)^2} + \\frac{ \\cos^2{\\alpha}}{3} \\left( 2  b^3 \\left( 1 - \\left( \\frac{x}{a} \\right)^2 \\right)^{3/2} \\right) \\\\ \n  \\text{ Let } \\left( \\frac{x}{a} \\right) = \\sin{t} \\\\ \n  \\int a^2 \\sin^2{t} \\cos^2{t} a dt = a^2 \\int \\left( \\frac{\\sin{2t}}{2} \\right)^2 dt = \\frac{a^2}{4} \\int \\frac{ 1 - \\cos{4t}}{2} dt = \\frac{a^2 \\pi }{8 } \\\\\n  \\int_{-\\pi/2}^{\\pi/2} \\cos^3{t} a \\cos{t} dt = a \\int_{-\\pi/2}^{\\pi/2} \\frac{1 + 2 \\cos{2t} + \\cos^2{2t}}{4 } = a \\left( \\frac{\\pi}{4} + \\frac{\\pi}{8} \\right) = \\frac{ a 3 \\pi }{ 8 }  \\\\\n\\Longrightarrow 2 b \\sin^2{\\alpha} \\frac{ a^3 \\pi }{8} + \\frac{2}{3} \\cos^2{\\alpha} b^3 a \\frac{3\\pi}{8} = \\frac{1}{4} \\pi ab ( a^2 \\sin^2{\\alpha} + b^2 \\cos^2{\\alpha} )\n\\end{gathered}\n\\]\nWith $m = \\pi ab$, the area of the ellipse, we get the desired answer.  \n\n\n\\exercisehead{19}  We want $\\int_0^h \\int_0^h \\sqrt{ x^2 + y^2} dx dy$.  \n\\[\n\\int_0^h \\sqrt{ x^2 + y^2} dx = \\left. \\left( \\frac{x}{2} \\sqrt{ x^2  +y^2} + \\frac{y^2}{2} \\ln{ (x+ \\sqrt{ x^2 +y^2 } )}\\right) \\right|_0^h = \\frac{1}{2} \\left( h \\sqrt{ h^2 +y^2} + y^2 \\ln{( \\frac{h}{y} + \\sqrt{ 1 + \\left( \\frac{ h}{y} \\right)^2 } )} \\right)\n\\]\nsince, recall\n\\[\n(\\ln{ (x + \\sqrt{ x^2 + y^2} )})' = \\frac{ 1 + \\frac{ x }{\\sqrt{ x^2 + y^2}} }{ x + \\sqrt{ x^2  +y^2} } = \\frac{1}{\\sqrt{ x^2 + y^2} } \\quad \\, \\text{ and } \\quad \\, (x\\sqrt{ x^2  +y^2} )' = \\sqrt{ x^2 + y^2} + \\frac{ x^2}{ \\sqrt{ x^2 + y^2}}\n\\]\n\\[\n\\begin{gathered}\n  \\int_0^h y^2 \\ln{ \\left( \\frac{h}{y} + \\sqrt{ 1 + \\left( \\frac{h}{y} \\right)^2 } \\right) } dy \\xrightarrow{ u = \\frac{h}{y} } \\int_{\\infty}^1 \\left( \\frac{h}{u} \\right)^2 \\ln{ (u + \\sqrt{ 1 + u^2} )} \\frac{-h}{u^2} du = h^3 \\int_1^{\\infty} \\frac{ \\ln{ ( u + \\sqrt{ 1 + u^2} )}}{u^4} du \n\\end{gathered}\n\\]\n\\[\n\\begin{gathered}\n  \\int \\frac{ \\ln{ (u + \\sqrt{ 1 + u^2})}}{ u^4} = \\int \\left( \\frac{u^{-3}}{-3} \\right)' \\ln{(u+ \\sqrt{ 1 + u^2})} = \\frac{u^{-3}}{-3} \\ln{ ( u + \\sqrt{ 1 + u^2})} - \\int \\frac{u^{-3}}{-3} \\frac{1}{ \\sqrt{ 1 + u^2} }\n\\end{gathered}\n\\]\n\\[\n\\begin{gathered}\n  \\text{ If we make the following substitution, } \\begin{aligned} y & = \\frac{1}{u} \\\\ du & = \\frac{-1}{y^2} dy \\end{aligned} \\\\\n\\begin{aligned}\n  \\int \\frac{u^{-3}}{ \\sqrt{ 1 + u^2 } } & = \\int \\frac{u^{-4}}{ \\sqrt{ 1 + \\left( \\frac{1}{u} \\right)^2} } = \\int \\frac{y^4 \\left( \\frac{-1}{y^2} \\right) dy }{ \\sqrt{ 1 + y^2 } } = \\int \\frac{-y^2}{ \\sqrt{ 1 + y^2}} dy = - \\left( y \\sqrt{ 1 + y^2}  - \\int \\sqrt{ 1 + y^2 } \\right) = \\\\\n  & = -y \\sqrt{ 1 + y^2} + \\frac{1}{2} ( y \\sqrt{ 1 + y^2} + \\ln{ ( y + \\sqrt{ 1 + y^2} ) } )  = \\frac{-1}{2} y \\sqrt{ 1 + y^2} + \\frac{1}{2} \\ln{ (y + \\sqrt{ 1 + y^2} ) }\n\\end{aligned} \\\\\n\\left. h^3 \\left( \\frac{u^{-3}}{-3} \\ln{ ( u + \\sqrt{ 1 + u^2} ) } \\right|_1^{\\infty} + \\left. \\frac{1}{3} \\left( \\frac{ - \\sqrt{ 1 + \\left( \\frac{1}{u} \\right)^2} }{ 2u} + \\frac{1}{2} \\ln{ \\left( \\frac{1}{u} + \\sqrt{ 1 + \\left( \\frac{1}{u} \\right)^2} \\right) } \\right) \\right) \\right|_1^{\\infty} = \\frac{h^3}{6} ( \\sqrt{ 2} + \\ln{ (1+ \\sqrt{2})} )\n\\end{gathered}\n\\]\n\\[\n\\Longrightarrow \\frac{1}{4} ( h^3 \\sqrt{2} + h^3 \\ln{ (1+\\sqrt{2})}) + \\frac{h^3}{12} (\\sqrt{2} + \\ln{(1+\\sqrt{2})} ) = \\boxed{ \\frac{h^3}{3} (\\sqrt{2} + \\ln{(1+\\sqrt{2})} ) }\n\\]\n\n\\exercisehead{20} Let $P_0 = (0,h)$.  We want\n\\[\n\\int_{-R}^R \\int_{-\\sqrt{ R^2 - x^2}}^{\\sqrt{R^2 - x^2 }} (x^2 + (y-h)^2) dy dx\n\\]\n\\[\n\\begin{gathered}\n  \\int_{-\\sqrt{R^2 - x^2} }^{\\sqrt{ R^2 - x^2}} (x^2 + (y-h)^2) dy = 2x^2 \\sqrt{ R^2 - x^2} + \\frac{1}{3} (( \\sqrt{ R^2-x^2} - h )^3 - (-\\sqrt{ R^2 - x^2 } - h )^3 ) = \\\\\n  =  2 x^2 \\sqrt{ R^2-x^2 }+\\frac{2}{3} ((R^2-x^2)^{3/2} + 3 \\sqrt{ R^2-x^2} h^2 )  = \\frac{4}{3} x^2 \\sqrt{ R^2-x^2} + \\left( \\frac{2}{3} R^2 + 2h^2 \\right) \\sqrt{ R^2-x^2}\n\\end{gathered}\n\\]\n\\[\n\\begin{gathered}\n  \\text{ Since } \\begin{aligned} x & = R \\sin{\\theta} \\\\ dx & = R \\cos{\\theta} d\\theta \\end{aligned} \\\\ \n  \\begin{gathered}\n  \\int_{-R}^{R} x^2 \\sqrt{ R^2- x^2} = \\int_{-\\pi/2}^{\\pi/2} R^2 \\sin^2{\\theta} R^2 \\cos^2{\\theta} d\\theta = R^4 \\int_{-\\pi/2}^{\\pi/2} \\left( \\frac{\\sin{2\\theta}}{2} \\right)^2 d\\theta = \\frac{R^4}{4} \\int_{-\\pi/2}^{\\pi/2} \\left( \\frac{ 1 - \\cos{4\\theta}}{2} \\right) d\\theta = \\frac{R^4}{8} \\pi  \n  \\end{gathered} \\\\\n  \\begin{gathered}\n    \\int_{-\\pi/2}^{\\pi/2} \\sqrt{ R^2 - x^2} = \\int_{-\\pi/2}^{\\pi/2} \\cos{\\theta} R \\cos{\\theta} d\\theta (R) = R^2 \\int_{-\\pi/2}^{\\pi/2} \\frac{1 + \\cos{2\\theta} }{2} d\\theta = R^2 \\frac{\\pi}{2} \n  \\end{gathered} \\\\\n  \\Longrightarrow \\frac{4}{3} \\frac{ R^4 \\pi}{8} + \\left( \\frac{2}{3} R^2 + 2h^2 \\right) R^2 \\frac{\\pi}{2} = \\frac{ R^4 \\pi}{6} + \\frac{ \\pi R^4}{3} + h^2 R^2 \\pi = \\frac{ \\pi R^4}{2} + \\pi R^2 h^2 \n\\end{gathered}\n\\]\nNow \n\\[\n\\iint dy dx = \\pi r^2\n\\]\nSo then the average of $\\delta^2$ is $\\boxed{ \\frac{R^2}{2} + h^2 }$\n\n\\exercisehead{21} \n\\[\n\\begin{aligned}\n  A & = [0,4] \\times [0,1] \\\\ \n  B & = [2,3] \\times [1,3] \\\\ \n  C & = [2,4] \\times [3,4]\n\\end{aligned} \n\\]\n\\begin{enumerate}\n  \\item $A \\cup B$ \\[\n\\frac{ 4(2,\\frac{1}{2} ) + (2)(\\frac{5}{2}, \\frac{4}{2} ) }{ 4+2} = \\frac{ \\frac{1}{2} ( 16 + 10, 10) }{6} = \\left( \\frac{13}{6} , 1 \\right)\n\\]\n  \\item $A \\cup C$ \\[\n\\frac{ 4 \\left( \\frac{4}{2}, \\frac{1}{2} \\right) + 2 \\left( \\frac{6}{2}, \\frac{7}{2} \\right) }{ 4 + 2 } = \\frac{ (8,2) + (6,7) }{6}  = \\left( \\frac{7}{3}, \\frac{3}{2} \\right)\n\\]\n  \\item $B \\cup C$, \\[\n\\frac{ 2 \\left( \\frac{5}{2}, \\frac{4}{2} \\right) + 2 \\left( \\frac{6}{2}, \\frac{7}{2} \\right) }{2 + 2 } = \\left( \\frac{11}{4} , \\frac{11}{4} \\right)\n\\]\n  \\item $A \\cup B \\cup C$\\[\n\\frac{ 4 ( 2,\\frac{1}{2} ) + 4 ( \\frac{11}{4}, \\frac{11}{4} ) }{ 8 } = \\boxed{ \\left( \\frac{19}{8}, \\frac{13}{8} \\right) }\n\\]\n\\end{enumerate}\n\n\\exercisehead{22} \\quad \\\\ $\\begin{aligned}\n   \\text{ rectangle } R: & \\, \\text{ area } A_R & = 1(2) \\quad \\, (\\overline{x},\\overline{y})_R = (0,-1) \\\\ \n   \\text{ triangle } T: & \\, \\text{ area} A_T & = \\frac{1}{2}(1)h = \\frac{h}{2} \\quad \\, \\overline{x}_T = 0 \n\\end{aligned}$\n\\[\n\\overline{y}_T A_T = \\int_0^h \\int_0{ \\left( \\frac{y}{h} -1 \\right)/2 }^{ \\left( \\frac{y}{h} - 1 \\right)/(-2) } y dx dy = \\int_0^h \\frac{y}{-2} \\left( \\frac{y}{h} - 1 + \\left( \\frac{y}{h} - 1 \\right) \\right) = \\int_0^h y - \\frac{y^2}{h} = \\frac{1}{6} h^2 \n\\]\n\\[\n\\overline{y}_T = \\frac{ \\frac{1}{6}h^2 }{h/2} = \\frac{1}{3} h \n\\]\nCondition for centroid to lie on the common edge, with the common edge located at the origin:\n\\[\n0 = \\frac{ \\left( \\frac{h}{2} \\right)\\left( \\frac{h}{3} \\right) + 2 (-1) }{ h /2 + 2} \\Longrightarrow \\boxed{ h = 2\\sqrt{3}}\n\\]\n\n\\exercisehead{23} \n\\[\n\\begin{aligned}\n  \\text{ isosceles triangle $T$ }: & A_T = \\frac{1}{2} 2r h = rh \\quad \\, \\begin{gathered}  \n    \\overline{y}_T A_T = \\int_0^h \\int_{ \\left( \\frac{y}{h} - 1 \\right)(r) }^{ \\left( \\frac{y}{h} - 1 \\right) (-r) } y dx dy = \\int_0^h y r \\left( \\left( \\frac{y}{h} -1 \\right)(-1) - \\left( \\frac{y}{h} - 1 \\right) \\right) dy = \\\\ \n    = 2 (-r) \\int_0^h \\frac{y^2}{h} - y dy = (-r) \\left( \\frac{1}{h} \\frac{1}{3}h^3 - \\frac{1}{2}h^2 \\right) = \\frac{1}{3} h^2 r \\\\ \n    \\Longrightarrow \\overline{y}_T  = h^2 r /3rh = h /3 \n\\end{gathered} \\\\ \n  \\text{ semicircular disk $D$ }: & A_D = \\frac{1}{2} \\pi r^2; \\quad \\, (2\\pi \\overline{y})A = 2 \\pi \\overline{y} \\frac{\\pi}{2} r^2 = \\frac{4}{3} \\pi r^3\n\\end{aligned}\n\\]\nCondition for centroid to lie in triangle:\n\\[\n\\frac{ (rh) \\left( \\frac{h}{3} \\right) + \\left( \\frac{1}{2} \\pi r^2 \\right) \\left( \\frac{-4r}{3 \\pi } \\right) }{ (rh) + \\frac{1}{2} \\pi r^2 } \\geq 0 \\quad \\text{ or } \\frac{r}{3} \\left( h^2 + -2r^2 \\right) \\geq 0  \\, \\Longrightarrow \\boxed{ h > \\sqrt{2} r }\n\\]\n\n\\section*{ 11.22  Green's theorem in the plane.  Some applications of Green's theorem.  A necessary and sufficient condition for a two-dimensional vector field to be a gradient. }\n\n\\exercisehead{1} Green's theorem: $\\int_C P dx + Q dy = \\iint_R \\left( \\frac{\\partial Q}{\\partial x} - \\frac{ \\partial P}{\\partial y } \\right) dx dy $.  Thus\n\\[\n\\oint_C y^2 dx + x dy = \\iint_R (1-2y)dx dy\n\\]\n\\begin{enumerate}\n\\item $\\int_0^2 \\int_0^2 (1-2y)dy dx = 4-4(2) = -4$\n\\item $\\int_{-1}^1 \\int_{-1}^1 (1-2y)dy dx = 4 $\n\\item $ \\int_{-2}^0 \\int_{-2-x}^{2+x} (1-2y) dy dx + \\int_0^2 \\int_{-2+x}^{2-x} (1-2y) dy dx = \\int_{-2}^0 (2(2+x)) dx + \\int_0^2 (4-2x) dx = \\int_{-2}^0 (4+2x)dx + 4(2)-4 = \\boxed{ 8 } $\n\\item $\\int_{-2}^2 \\int_{-\\sqrt{ 4 -x^2}}^{\\sqrt{ 4- x^2}} (1-2y)dy dx = \\int_{-2}^2 2 \\sqrt{ 4- x^2} dx = \\int_{-\\pi/2}^{\\pi/2} 8 \\cos^2{\\theta} d\\theta = \\boxed{ 4 \\pi} $ where we used \\\\\n  $\\begin{aligned} x & = 2\\sin{\\theta} \\\\ dx & = 2 \\cos{\\theta} d\\theta \\end{aligned}$\n\\item $\\alpha(t) = (2\\cos^3{t},2\\sin^3{t}) = 2(\\cos^3{t}, \\sin^3{t})$, \\, $ 0 \\leq t \\leq 2\\pi$\n\\end{enumerate}\n\n\\exercisehead{2} \\quad \\\\\n$\\begin{aligned}\n  P(x,y) & = x e^{-y^2} \\\\ \n  Q(x,y) & = -x^2 y e^{-y^2} + \\frac{1}{x^2+y^2}\n\\end{aligned}$ \\quad \\quad \\, $\\oint P dx + Q dy = \\iint \\left( \\frac{ \\partial Q}{\\partial x } - \\frac{ \\partial P }{ \\partial y} \\right) dx dy$ \\\\\n\\[\n\\begin{gathered}\n  \\begin{aligned} Q_x & = -2xy e^{-y^2} + \\frac{-2x}{ (x^2 +y^2)^2 } \\\\ \n    P_y & = x e^{-y^2} (-2y) \\end{aligned} \\\\ \n  \\int_{-a}^a \\int_{-a}^a \\frac{-2x}{ (x^2 + y^2)^2 } dx dy = \\int_{-a}^a \\left. \\left( \\frac{1}{x^2 + y^2} \\right) \\right|_{-a}^a dy = \\int_{-a}^a \\frac{1}{ a^2 + y^2} - \\frac{1}{a^2 + y^2} = 0 \n\\end{gathered}\n\\]\n\n\\exercisehead{3} $n I_z = \\oint_C x^3 dy - y^3 dx = \\iint_R (3x^2 + 3y^2) dy dx = 3 I_z$  \\, $n=3$\n\n\\exercisehead{4} $f = (v,u)$, \\, $g= ((u_x - u_y), v_x - v_y)$\n\\[\n\\begin{gathered}\n  (f\\cdot g) = vu_x - vu_y + uv_x - uv_y = (uv)_x - (uv)_y = Q_x - P_y \\\\ \n  \\iint_R (f\\cdot g) dx dy = \\int (uv,uv)\\cdot ds = \\int (uv,uv) \\cdot (-\\sin{t},\\cos{t}) dt = \\int_0^{2\\pi} (-\\sin^2{t} + \\sin{t} \\cos{t} dt = \\boxed{ - \\pi }\n\\end{gathered}\n\\]\n\n\\exercisehead{5} $f,g \\in \\mathcal{C}^1$, $f,g$ on open connected set $S$ in the plane.  \n\\[\n\\begin{gathered}\n  \\oint_C f\\nabla g \\cdot d\\alpha = \\oint_C fg_x dx + fg_y dy = \\iint_R (f_x g_y + fg_{xy}) - (f_y g_x + fg_{yx}) = \\\\\n  = \\iint_R -(g_x f_y + gf_{xy}) + (g_y f_x + gf_{yx}) = \\iint_R (-gf_y)_x - (-gf_x)_y = \\oint -gf_x dx - gf_y dy = -\\oint g(\\nabla f) \\cdot d\\alpha\n\\end{gathered}\n\\]\nSince $f_{xy} = f_{yx}$; \\, $g_{xy} = g_{yx}$.  \n\n\\exercisehead{6} \\begin{enumerate}\n\\item $\\oint_C uv dx + uv dy = \\iint (\\partial_x (uv) - \\partial_y (uv) ) dx dy = \\iint v(\\partial_x u - \\partial_y u) + u (\\partial_x v - \\partial_y v) dx dy$\n\\item \\[\n\\begin{gathered}\n  \\frac{1}{2} \\oint_C (v \\partial_x u - u \\partial_x v ) dx + (u \\partial_y v - v \\partial_y u ) dy = \\frac{1}{2} \\iint (u_x v_y + uv_{xy} - v_x u_y - vu_{xy} ) - (v_y u_x + vu_{yx} - u_y v_x - uv_{yx} ) = \\\\\n  = \\frac{1}{2} \\iint u (v_{xy} + v_{yx}) - v(u_{xy} + u_{yx} ) = \\iint u\\partial_{yx} v - v \\partial_{yx} u \n\\end{gathered}\n\\]\n\\end{enumerate}\n\nNote the formulation of normal derivatives.  Note that $ds$ refers to the arc length.  \n\\[\n\\begin{gathered}\n  \\int_C (P dx + Q dy ) = \\int_C f\\cdot T ds \\\\ \n  T \\equiv \\text{ unit tangent vector to $C$ } \n\\end{gathered} \\quad \\quad \\, \\begin{aligned} \\alpha(t) & = (X(t),Y(t) ) \\\\ n(t) & = \\frac{1}{ \\| \\alpha'(t) \\| } (Y'(t), X'(t)) \\text{ whenever } \\| \\alpha'(t) \\| \\neq 0  \\end{aligned}\n\\]\nSo the normal derivative is defined as \n\\[\n\\frac{ \\partial \\psi }{ \\partial n} = \\nabla \\psi \\cdot n \n\\]\n\\exercisehead{7} \\[\n\\begin{gathered}\n  \\int_C P dx + Q dy = \\int_C (P,Q) \\cdot \\left( \\frac{ds}{dt} \\right) dt = \\int_C \\left( P \\frac{dx}{dt} + Q \\frac{dy}{dt} \\right) dt = \\int_C (Q Y' + (-P)(-X'))dt = \\\\\n  = \\int_C (Q,-P)\\cdot \\frac{ (Y',-X')}{ \\| \\alpha'(t) \\|} \\| \\alpha'(t) \\| dt = \\int_C f\\cdot n ds\n\\end{gathered}\n\\]\n\n\\exercisehead{8} \\begin{enumerate}\n\\item \\[\n  \\begin{gathered}\n    \\oint_C \\frac{\\partial g}{\\partial n} ds = \\oint_C \\nabla \\cdot n ds = \\oint_C \\nabla g \\cdot \\frac{ (Y', -X')}{\\| \\alpha'(t) \\| } \\| \\alpha'(t) \\| dt = \\\\\n    = \\oint_C (g_x Y' + -g_y X')dt = \\oint_C g_x dy + - g_y dx = \\iint (g_{xx} - (-g_{yy})) dx dy = \\iint \\nabla^2 g dx dy \n\\end{gathered}\n  \\]\n\\item \\[\n\\begin{gathered}\n  \\oint_C f \\nabla g \\cdot n ds = \\oint_C f \\nabla g \\cdot \\frac{ (Y',-X') }{ \\| \\alpha'(t) \\| } \\| \\alpha'(t) \\| dt = \\oint_C f(g_x dy - g_y dx) = \\\\\n  = \\iint (fg_x)_x - (-fg_y)_y = \\iint f_x g_x + fg_{xx} + f_y g_y + f g_{yy} = \\iint (\\nabla f \\cdot \\nabla g + f(\\nabla^2 g) ) dx dy \\\\\n  \\Longrightarrow \\oint_C f \\frac{\\partial g}{\\partial n} ds = \\iint_R (f\\nabla^2 g + \\nabla f \\cdot \\nabla g ) dx dy \n\\end{gathered}\n\\]\n\\item Use previous part, (b), of this exercise, Exercise 8.  \n\\[\n\\begin{aligned}\n  \\oint_C \\left( f \\frac{ \\partial g }{\\partial n} \\right) ds & = \\iint_R (f\\nabla^2 g + \\nabla f\\cdot \\nabla g ) dx dy \\\\ \n  \\oint_C \\left( g \\frac{ \\partial f }{\\partial n} \\right) ds & = \\iint_R (g\\nabla^2 f + \\nabla g\\cdot \\nabla f ) dx dy \\\\ \n\\end{aligned} \\quad \\quad \\, \\Longrightarrow \\oint_C \\left( f \\frac{ \\partial g}{\\partial n} - g \\frac{ \\partial f}{ \\partial n } \\right) ds = \\iint_R ( f \\nabla^2 g - g \\nabla^2 f) dx dy \n\\]\n\\end{enumerate}\n\n\\exercisehead{9}  $P(x,y) dx + Q(x,y) dy = 0$.   \\\\\n$\\mu(x,y)$ is an integration factor, so $\\mu P dx + \\mu Q dy = 0$ leads to $\\phi{(xy)} =C$ s.t. $\\begin{aligned} \\phi_x & = \\mu P \\\\ \\phi_y & = \\mu Q \\end{aligned}$ \\smallskip \\\\\nSlope of $\\phi(x,y) = c$ at $(x,y)$ is $\\tan{\\theta}$, so $\\tan{\\theta} = \\frac{ dY /dt}{ dX /dt}$ \\smallskip \\\\\n$ n =(\\sin{\\theta}, -\\cos{\\theta})$\n\n\\[\n\\begin{gathered}\n  \\frac{ \\partial \\phi}{ \\partial n} = \\nabla \\phi \\cdot n = (\\nabla \\phi) \\cdot (\\sin{\\theta}, -\\cos{\\theta}) = \\phi_x \\sin{\\theta} - \\phi_y \\cos{\\theta} = \\mu P \\sin{\\theta} - \\mu Q \\cos{\\theta} = \\\\\n  = \\mu (P \\sin{\\theta} - Q \\cos{\\theta}) = \\mu(x,y) g(x,y) \\\\ \n\\Longrightarrow g = P \\sin{\\theta} - Q \\cos{\\theta} \\\\\n\\begin{aligned}\n  \\sin{\\theta} & = \\frac{- P}{ \\sqrt{ P^2 + Q^2 }} \\text{ or }  \\frac{ P}{\\sqrt{ P^2 + Q^2 } } \\\\ \n  \\cos{\\theta} & = \\frac{ Q}{ \\sqrt{ P^2 + Q^2} } \\text{ or } \\frac{ Q}{ \\sqrt{ P^2 + Q^2 } }\n\\end{aligned} \\Longrightarrow g = -\\sqrt{ P^2 + Q^2 } \\text{ or } \\sqrt{ P^2 + Q^2 }\n\\end{gathered}\n\\]\n\n\\section*{ 11.25 Exercises - Green's theorem for multiply connected regions.  The winding number.  }\n\n\\exercisehead{1}\n\\begin{enumerate}\n\\item  Note that \n\\[\n\\begin{aligned}\n  & \\partial_x Q = \\frac{ -x }{ x^2 + y^2 } \\left( \\frac{1}{x} + \\frac{ (-1)(2x) }{ x^2 + y^2 } \\right) = \\frac{-x}{ x^2 + y^2 } \\left( \\frac{ x^2  +y^2 - 2x^2 }{ x(x^2 + y^2 )} \\right) = \\frac{ x^2 - y^2 }{ (x^2 + y^2)^2 } \\\\\n  &  \\partial_y P = \\partial_y \\left( \\frac{y}{ x^2 + y^2 } \\right) = - \\left( \\frac{ y^2 - x^2 }{ (x^2 + y^2)^2 } \\right)\n\\end{aligned}\n\\]\nNote that $\\partial_x Q, \\, \\partial_y P$ is not continuous at $(0,0)$.  \n\\[\n\\begin{gathered}\n  \\text{ So then for } \\begin{aligned} x &= \\cos{t} \\\\ y & = \\sin{t} \\end{aligned} \\quad \\quad \\, \\begin{aligned} P(x,y) & = \\frac{y}{ x^2 + y^2 } \\\\ Q(x,y) & = \\frac{-x}{x^2 + y^2 } \\end{aligned}  \\\\\n  \\begin{aligned}\n    \\int_C P dx & = \\int_0^{2\\pi} \\sin{t} (-\\sin{t}) dt = -\\pi \\\\\n    \\int_C Q dx & = \\int_0^{2\\pi} -\\cos{t} (\\cos{t}) dt = - \\pi \n\\end{aligned} \\\\\n  \\int_C P dx + Q dy = - 2\\pi \n\\end{gathered}\n\\]\n$+$ sign occurs when $C$ is in the clockwise direction, since if $x= \\cos{t}$, $y= -\\sin{t}$, then $\\int_C P dx + Q dy = 2\\pi$ and all clockwise direction, piecewise smooth Jordan curves whose interior contains $(0,0)$ can be deformed into a circle (by Thm.).\n\\item By Thm., we can pick any piecewise smooth Jordan curve whose interior doesn't contain $(0,0)$.  \n\nRecall Green's theorem.  \n\\[\n\\int_C P dx + Q dy = \\iint_R \\left( \\frac{ \\partial Q }{ \\partial y} - \\frac{ \\partial P }{ \\partial x } \\right) = 0 \n\\]\nSince $\\frac{ \\partial Q}{ \\partial y}, \\, \\frac{ \\partial P}{ \\partial x }$, is continuous everywhere in $C \\cup int{C}$, where $(0,0) \\notin C$\n\\end{enumerate}\n\n\\exercisehead{2} \\[\n\\begin{gathered}\n  f = \\left( \\frac{ \\partial (\\ln{r} )}{ \\partial y}\\, , - \\frac{ \\partial (\\ln{r})}{ \\partial x } \\right)  \\quad \\quad \\, \\begin{aligned} x & = a \\cos{t} \\\\ y &  = a \\sin{t} \\end{aligned} \\quad \\, \\alpha = (x,y)  \\quad \\quad \\, \\sqrt{ x'^2  +y'^2 } = \\| \\alpha' \\| =a \\\\\n  \\begin{aligned}\n  \\ln{r} = \\ln{ \\sqrt{ x^2 + y^2 }} = \\frac{1}{2} \\ln{ (x^2 + y^2 )} \\\\\n  (\\ln{r})_x = \\frac{1}{2} \\frac{ 1 }{ x^2 + y^2 } (2x) = \\frac{x}{ x^2 + y^2 } \n\\end{aligned} \\quad \\, \n\\end{gathered}\n\\]\n\\[\n\\begin{aligned}\n  \\int f \\cdot ds & = \\int f \\cdot \\frac{dr}{dt} dt = \\int \\left( \\frac{ \\partial (\\ln{r})}{\\partial y} a (-\\sin{t}) + \\frac{ - \\partial (\\ln{r})}{ \\partial x} a \\cos{t} \\right) dt = \\int \\frac{ \\partial (\\ln{r})}{ \\partial y } \\frac{dx}{dt} + \\frac{ - \\partial (\\ln{r} )}{ \\partial x } \\frac{dy}{dt} dt = \\\\\n  & = \\int \\frac{ y}{ x^2 + y^2 } dx + \\frac{-x}{ x^2 + y^2 } dy = \\boxed{ - 2\\pi } \\text{ as shown in the previous exercise, Exercise 1. }\n\\end{aligned}\n\\]\n\n\\exercisehead{5}\n\\begin{enumerate}\n\\item $I_1 - I_3 = 12 - 15 = -3$  \n\\item One possible solution is this: Draw a large curve around all 3 points, for $I_1 + I_2 + I_3 = 37$.  Then circle around, inside, point 1, three times, in a clockwise fashion, to obtain $-3I_1 = -36$.  \n\\end{enumerate}\n\n\\exercisehead{6} $\\alpha(t) = (X(t),Y(t))$ if $a \\leq t \\leq b$  \\quad \\quad \\, $ n = \\frac{ (Y'(t),X'(t))}{ \\sqrt{ X'^2 + Y'^2}}$\n\\[\n\\begin{gathered}\n\\begin{aligned}\n  W(\\alpha_0; P_0) & = \\frac{1}{2\\pi} \\int_a^b \\frac{ (X(t) - x_0) Y'(t) - (Y(t) - y_0)X'(t) }{ (X(t) - x_0)^2 + (Y(t) - y_0)^2 } dt = \\\\ \n  & = \\frac{1}{2\\pi} \\int_a^b \\frac{ (r(t) - P_0) \\cdot n}{ \\| r(t) - P_0 \\|^2 } \\| \\alpha'(t) \\| dt = \\frac{1}{2\\pi} \\int_a^b \\left( \\frac{ r(t) - P_0 }{ \\| r(t) - P_0 \\| } \\right) \\frac{ n }{ \\| r(t) - P_0 \\| } ds \n\\end{aligned} \\\\\n  I_k = \\oint_{C_k} P dx + Q dy \\\\ \n  \\begin{aligned}\n  P(x,y) & = -y \\left( \\frac{1}{ (x-1)^2 + y^2 } + \\frac{1}{ x^2 + y^2} + \\frac{1}{ (x+1)^2 + y^2 } \\right) = \\\\ \n  &  = - y \\left( \\frac{1}{ \\| (x,y) - (1,0) \\|^2 } + \\frac{1}{ \\| (x,y) - (0,0) \\|^2 } + \\frac{1}{ \\| (x,y) - (-1,0) \\|^2 } \\right) \n\\end{aligned} \\\\\n  Q(x,y) = \\frac{ (x-1) }{ \\| (x,y) - (1,0) \\|^2 } + \\frac{ x}{ \\| (x,y) - (0,0) \\|^2 } + \\frac{ x+1}{ \\| (x,y) - (-1,0) \\|^2 }\n\\end{gathered}\n\\]\n\\[\n\\begin{aligned}\n  & C_1 \\text{ is the smallest circle,} x^2 + y^2 = \\left( \\frac{1}{ 2\\sqrt{2}} \\right)^2 \\\\\n  & C_2: \\, x^2 + y^2 = 2^2 \\\\\n  & \\quad \\, \\\\\n  & C_3: \\, \\begin{aligned} (x-1)^2  + y^2 & = \\left( \\frac{1}{2} \\right)^2 \\\\ x^2 + y^2 & = \\left( \\frac{1}{2} \\right)^2 \\\\ (x+1)^2 + y^2 & = \\left( \\frac{1}{2} \\right)^2 \\end{aligned}\n\\end{aligned} \\quad \\quad \\, \n\\begin{aligned}\n  I_2 & = 6 \\pi \\\\ \n  I_3 & = 2 \\pi \n\\end{aligned}\n\\]\n\n$I_k = \\oint_{C_k} P dx + Q dy = \\int \\left( \\frac{ (x,y) - (1,0)}{ \\| (x,y) - (1,0) \\|^2 } + \\frac{ (x,y) - (0,0) }{ \\| (x,y) - (0,0) \\|^2 } + \\frac{ (x,y) - (-1,0)}{ \\| (x,y) - (-1,0) \\|^2 } \\right) \\cdot n ds $ \\\\\n$I_2$ wraps around 3 holes, $(1,0), (0,0), (-1,0)$.   \\\\\n$I_3$ wraps around $(0,0)$ clockwise and around $(1,0), (-1,0)$ counterclockwise.  The wrap around $(0,0)$ and $(1,0)$ cancel each other and so the result is we wrap around $(-1,0)$.  \n\\[\n\\Longrightarrow \\boxed{ I_1 = 2\\pi }\n\\]\n\n\\section*{ 11.28 Exercises - Change of variables in a double integral, Special cases of the transformation formula }\n\n\\exercisehead{1} $S = \\{ (x,y) | x^2 + y^2 \\leq a^2 \\}$ where $a >0$.  \\\\\nRecall,\n\\[\n\\idotsint_{\\mathcal{D}} f(\\phi(u)) |det{D \\phi(u)} | du_1, \\dots, du_n = \\idotsint_{\\mathcal{D}} f(x) dx_1, \\dots, dx_n \\quad \\quad \\, \\phi(\\mathcal{D}) = \\mathcal{D}^*\n\\]\n\\[\n\\begin{aligned}\n  x & = r\\cos{\\theta} \\\\ \n  y & = r\\sin{\\theta}\n\\end{aligned} \\quad \\quad \\, \\left| \\begin{matrix} \\cos{\\theta} & - r\\sin{\\theta} \\\\ \\sin{\\theta} & r\\cos{\\theta} \\end{matrix} \\right| = r > 0 \\quad \\quad \\, \\iint_S f(x,y) dx dy = \\int_0^{2\\pi} \\int_0^a f(r\\cos{\\theta},r\\sin{\\theta})r dr d\\theta\n\\]\n\\exercisehead{2} $S = \\{ (x,y) | x^2  +y^2 \\leq 2 x \\}$\n\\[\n\\begin{gathered}\n  (x-1)^2  + y^2 = 1 \\\\ \n  (1,0)\n\\end{gathered} \\quad \\, \\begin{aligned}\n  x-1 & = r \\cos{\\theta} \\\\ \n  x & = r\\cos{\\theta} + 1 \\\\ \n  y & = r\\sin{\\theta} \n\\end{aligned} \\quad \\, \\iint_S f(x,y) dx dy = \\int_0^{2\\pi} \\int_0^1 f(r\\cos{\\theta}  +1, r\\sin{\\theta}) r dr d\\theta\n\\]\n\n\\exercisehead{3} $S = \\{ (x,y) | a^2 \\leq x^2 + y^2 \\leq b^2 \\}$ where $0 < a < b$\n\\[\n\\iint_S f(x,y) dx dy = \\int_0^{2\\pi} \\int_a^b f(r\\cos{\\theta}, r\\sin{\\theta})r dr d\\theta\n\\]\n\n\\exercisehead{4} $S = \\{ (x,y) | 0 \\leq y \\leq 1 - x, \\, 0 \\leq x \\leq 1 \\}$\n\\[\n\\begin{gathered}\n  r\\sin{\\theta} \\leq 1 - r\\cos{\\theta} \\Longrightarrow r \\leq \\frac{1}{ \\sin{\\theta} + \\cos{\\theta} }, \\, \\text{ since } \\sin{\\theta}, \\cos{\\theta} \\geq 0 \\\\\n  \\int_0^{\\pi/4} \\int_0^{\\frac{1}{\\sin{\\theta} + \\cos{\\theta}}} f(r\\cos{\\theta}, r\\sin{\\theta}) rdr d\\theta\n\\end{gathered}\n\\]\n\n\\exercisehead{5} $S = \\{ (x,y) | x^2 \\leq y \\leq 1, \\, - 1 \\leq x \\leq 1 \\}$\nConsider imaginary angular wedges dividing up the parabolic region.  Then we identify 3 regions since each region have different boundaries.  \n\\[\n\\begin{gathered}\n  y = 1 = r\\sin{\\theta} \\text{ or } r =\\csc{\\theta} \\\\ \n  x^2 = r^2 \\cos^2{\\theta} = r\\sin{\\theta} \\text{ or } r = \\tan{\\theta} \\csc{\\theta}\n\\end{gathered}\n\\]\nObserve that $y=x$ or $\\theta = \\frac{\\pi}{4}$, and $y=-x$ or $\\theta = \\frac{-\\pi}{4}$, divide up the regions.  \n\\[\n\\int_0^{\\pi/4} \\int_0^{\\tan{\\theta} \\csc{\\theta}} f(r\\cos{\\theta}, r\\sin{\\theta}) rdr d\\theta + \\int_{\\frac{\\pi}{4}}^{ \\frac{3\\pi}{4} } \\int_0^{\\csc{\\theta}} f(r\\cos{\\theta}, r\\sin{\\theta}) rdr d\\theta + \\int_{\\frac{3\\pi}{4} }^{\\pi} \\int_0^{\\tan{\\theta} \\csc{\\theta}} f(r\\cos{\\theta},r\\sin{\\theta}) r dr d\\theta\n\\]\n\n\\exercisehead{6} Note that $\\sqrt{ 2ax - x^2} = \\sqrt{ a^2 - (a-x)^2}$.  Then\n\\[\n\\begin{gathered}\n  y^2 = a^2 - (a-x)^2 \\\\ \n  (x-a)^2 + y^2 = a^2 \n\\end{gathered} \\quad \\quad \\, \n\\begin{gathered}\n  x - a =r \\cos{\\theta} \\\\ \n  y = r \\sin{\\theta} \\\\\n  x^2 = (a + r\\cos{\\theta})^2 = a^2 + 2ar \\cos{\\theta} + r^2 \\cos^2{\\theta} \n\\end{gathered}\n\\]\n\\[\n\\int_0^{2a} \\left( \\int_0^{\\sqrt{ 2ax - x^2}} (x^2 + y^2 ) dy \\right) dx = \\int_0^{\\pi} d\\theta \\int_0^a r dr (a^2 + 2ar\\cos{\\theta} + r^2 ) = a^2 \\frac{ a^2 \\pi}{2} + \\int_0^{\\pi} \\frac{2a\\cos{\\theta} a^3}{3} d\\theta + \\frac{ a^4 \\pi}{4} = \\boxed{ \\frac{3a^4 \\pi}{4} } \n\\]\n\n\n\\exercisehead{7} $x=a \\Longrightarrow r\\cos{\\theta} =a \\text{ or } r = a \\sec{\\theta}$\n\\[\n\\begin{gathered}\n  \\int_0^a \\left( \\int_0^x \\sqrt{ x^2 + y^2} dy \\right) dx = \\int_0^{\\pi/4} d\\theta \\int_0^{a \\sec{\\theta}} r^2 dr = \\int_0^{\\pi/4} \\frac{ a^3 \\sec^3{\\theta}}{3}  \\\\\n  \\text{ Now } \\int \\sec^3{\\theta} = \\int \\sec{\\theta}(1 + \\tan^2{\\theta}) \\text{ and } \\\\ \n  \\begin{gathered}\n    \\int \\sec{\\theta} = \\ln{ | \\sec{\\theta} + \\tan{\\theta} |} \\\\\n    \\int (\\sec{\\theta} \\tan^2{\\theta}) = \\int (\\sec{\\theta})' \\tan{\\theta} = \\sec{\\theta} \\tan{\\theta} - \\int \\sec{\\theta} \\sec^2{\\theta} \n  \\end{gathered} \\Longrightarrow \\int \\sec^3{\\theta} = \\frac{ \\sec{\\theta} \\tan{\\theta} + \\ln{ |\\sec{\\theta} +\\tan{\\theta} } }{2} \\\\ \n  \\Longrightarrow \\frac{a^3}{3} \\int_0^{\\pi/4} \\sec^3{\\theta} d\\theta = \\frac{ a^3 (\\sqrt{2} + \\ln{ |\\sqrt{2} + 1 | } ) }{6} \n\\end{gathered}\n\\]\n\n\\exercisehead{8} \n\\[\n\\begin{gathered}\n\\text{ Since } \n  y = r \\sin{\\theta} = x^2 = r^2 \\cos^2{\\theta} \\text{ or } r = \\tan{\\theta} \\sec{\\theta}  \\\\ \n  \\int_0^{\\pi/4} d\\theta \\int_0^{\\tan{\\theta} \\sec{\\theta} } \\frac{1}{r} r dr = \\int_0^{\\pi/4} d\\theta \\tan{\\theta} \\sec{\\theta} = \\boxed{ \\sqrt{2} - 1 } \n\\end{gathered}\n\\]\n\n\\exercisehead{9}\n\\[\n\\int_0^a \\left( \\int_0^{\\sqrt{ a^2 - y^2}} (x^2 +y^2) dx \\right) dy = \\int_0^{\\pi/2} \\int_0^a r^2 r dr d\\theta = \\frac{ a^4 \\pi}{8 }\n\\]\n\n\\exercisehead{10} After sketching a box with vertices at $(0,0), (1,0), (0,1), (1,1)$, it's very clear that in polar coordinates, we must divide the region into 2 parts by the $y=x$ line since each region have different boundaries for $r$.  \n\\[\n\\begin{gathered}\n  \\int_0^1 \\left( \\int_0^x f(x,y) dy \\right) dx = \\int_0^{\\pi/4} d\\theta \\int_0^{\\sec{\\theta}} f(r\\cos{\\theta}, r\\sin{\\theta}) r dr + \\int_0^{\\pi/4} d\\theta \\int_0^{\\csc{\\theta}} f(r\\cos{\\theta}, r\\sin{\\theta}) r dr \\text{ since } \\\\ \n  \\begin{aligned}\n    x & = 1 = r \\cos{\\theta} \\\\ \n    y & = 1 = r \\sin{\\theta} \n  \\end{aligned}\n\\end{gathered}\n\\]\n\n\\exercisehead{11} $\\int_0^2 \\left( \\int_x^{x\\sqrt{3}} f(\\sqrt{ x^2 + y^2} ) dy \\right) dx = \\int_{\\pi/4}^{\\pi/3} \\int_0^{2 \\sec{\\theta} } f(r) r dr d\\theta$ \n\\[\n\\begin{gathered}\n  x = 2 = r\\cos{\\theta} \\\\ \n  r = 2\\sec{\\theta}\n\\end{gathered}\n\\]\n\n\\exercisehead{12} $\\int_0^1 \\left( \\int_{1-x}^{\\sqrt{ 1 - x^2}} f(x,y) dy \\right) = \\int_0^{\\pi/2} d\\theta \\int_{\\frac{1}{ \\sin{\\theta} + \\cos{\\theta}}}^1 f(r\\cos{\\theta}, r\\sin{\\theta}) rdr$ since\n\\[\n\\begin{gathered}\n  y = 1 - x = r\\sin{\\theta} = 1 - r \\cos{\\theta} \\\\\n  r = \\frac{1}{ \\sin{\\theta} + \\cos{\\theta} }\n\\end{gathered}\n\\]\n\n\\exercisehead{13} $\\int_0^1 \\left( \\int_0^{x^2} f(x,y) dy \\right) dx = \\int_0^{\\pi/4} \\int_{\\sec{\\theta}}^{\\tan{\\theta} \\sec{\\theta}} f(r\\cos{\\theta}, r\\sin{\\theta}) r dr d\\theta$ since\n\\[\n\\begin{gathered}\n  y = x^2 = r\\sin{\\theta} = r^2 \\cos^2{\\theta} \\\\ \n  \\Longrightarrow r = \\tan{\\theta} \\sec{\\theta} \n\\end{gathered} \\quad \\quad \\, \n\\begin{gathered}\n  1 = x = r \\cos{\\theta} \\\\ \n   r = \\sec{\\theta}\n\\end{gathered}\n\\]\n\n\\exercisehead{14} Let $\\begin{aligned} x + y & =  u \\\\ x - y & =v \\end{aligned}$ \n\\[\n\\begin{gathered}\n  \\left[ \\begin{matrix} 1 & 1 \\\\ 1 & -1 \\end{matrix} \\right] \\left[ \\begin{matrix} x \\\\ y \\end{matrix} \\right] = \\left[ \\begin{matrix} u \\\\ v \\end{matrix} \\right]  \\quad \\, \\Longrightarrow \\left[ \\begin{matrix} x \\\\ y \\end{matrix} \\right] = \\frac{1}{-2} \\left[ \\begin{matrix} 1 & -1 \\\\ -1 & 1 \\end{matrix} \\right] \\left[ \\begin{matrix} u \\\\ v \\end{matrix} \\right] \\\\\n  J = \\left| \\begin{matrix} \\frac{1}{2} & \\frac{1}{2} \\\\ \\frac{1}{2} & \\frac{-1}{2} \\end{matrix} \\right| = \\frac{-1}{2}\n\\end{gathered}\n\\]\nSketch the transformation of $S$ to obtain a rectangle with vertices $(\\pi,\\pi), (3\\pi,\\pi), (\\pi,-\\pi), (3\\pi,-\\pi)$.  \n\\[\n\\int_{\\pi}^{3\\pi} du \\int_{-\\pi}^{\\pi} dv v^2 \\sin^2{u} \\left( \\frac{-1}{2} \\right) = \\frac{-1}{2} \\int_{\\pi}^{3\\pi} \\left( \\frac{ 1 - \\cos{2u}}{2} \\right) \\frac{2}{3} \\pi^3 = \\boxed{ - \\frac{ \\pi^4}{3}}\n\\]\n\n\n\\exercisehead{15} \\[\n\\begin{gathered}\n  (0,0), (2,10), (3,17), (1,7) \\Longrightarrow (0,0), (4,2)  \\\\\n  \\begin{aligned} u & = ax + by \\\\ v & = cx + dy \\end{aligned} \\quad \\quad \\begin{aligned} \\left( \\begin{matrix} 4 \\\\ 0 \\end{matrix} \\right) & = \\left( \\begin{matrix} a 2 + b 10 \\\\ c 2 + d 10 \\end{matrix} \\right) \\\\ \\left( \\begin{matrix} 0 \\\\ 2 \\end{matrix} \\right) & = \\left( \\begin{matrix} a + 7b \\\\ c + 7 d \\end{matrix} \\right) \\end{aligned} \\quad \\, \\Longrightarrow \\begin{aligned} b & = -1 \\quad \\, a & = 7 \\\\ d & = 1 \\quad \\, c & = -5 \\end{aligned} \\\\\n  \\left[ \\begin{matrix} 7 & - 1 \\\\ -5 & 1 \\end{matrix} \\right] \\left[ \\begin{matrix} x \\\\ y \\end{matrix} \\right] = \\left[ \\begin{matrix} u \\\\ v \\end{matrix} \\right] \\quad \\quad \\, \\frac{1}{2} \\left[ \\begin{matrix} 1 & 1 \\\\ 5 & 7 \\end{matrix} \\right] \\left[ \\begin{matrix} u \\\\ v \\end{matrix} \\right] = \\left( \\begin{matrix} \\frac{ u + v }{2} \\\\ \\frac{ 5u + 7v }{2} \\end{matrix} \\right) = \\left( \\begin{matrix} x \\\\ y \\end{matrix} \\right) \n\\end{gathered}\n\\]\n\\[\n\\int_0^2 \\int_0^4 \\frac{ 5 u^2 + 12 uv + 7 v^2 }{ 8} du dv = \\int_0^2 \\frac{5}{24} \\left.  u^3 \\right|_0^4 + \\frac{3}{4} \\left. u^2 v \\right|_0^4 + \\frac{7}{8}  v^2 (4) dv = \\frac{ 5}{3} 16 + 24 + \\frac{ 28}{3} = \\boxed{ 60 } \n\\]\n\\exercisehead{16} If $r > 0$, let $I(r) = \\int_{-r}^r e^{-u^2} du$.  \n\\begin{enumerate}\n\\item \\[\nI^2(r) = \\left( \\int_{-r}^r e^{-u^2} du \\right)^2 = \\left( \\int_{-r}^r e^{-x^2} dx \\right) \\left( \\int_{-r}^r e^{-y^2} dy \\right) = \\int_{-r}^r dy \\int_{-r}^r dy \\int_{-r}^r e^{-x^2 - y^2} dx = \\int_{-r}^r \\int_{-r}^r e^{-x^2 - y^2} dx dy \n\\]\n\\item Let $C_1$ have radius $a$, $C_2$ have radius $b$, $C_1 \\subset R \\subset C_2$, and since $e^{-(x^2 + y^2)} > 0$, \\, $\\forall \\, x ,y \\in \\mathbb{R}$, then\n\\[\n\\iint_{C_1} e^{-(x^2 + y^2)} dx dy < I^2(r) < \\iint_{C_2} e^{ - (x^2 + y^2)} dx dy\n\\]\n\\item \\[\n\\begin{gathered}\n  \\int_0^{2\\pi} \\int_0^a e^{-r^2} dr r d\\theta = \\left. \\int_0^{2\\pi} \\left( \\frac{ e^{-r^2}}{ -2} \\right) \\right|_0^a d\\theta = \\left. \\left( \\frac{ e^{-a^2 } - 1 }{ -2} \\right) \\right|_0^{2\\pi} = 2\\pi \\left( \\frac{ 1 - e^{-a^2}}{2} \\right) \\xrightarrow{ a \\to \\infty} \\pi \\\\\n  I(r) \\to \\sqrt{ \\pi} \\text{ as } r \\to \\infty \\\\\n  I(r) = \\int_{-r}^r e^{-u^2} du = 2 \\int_0^r e^{-u^2} du = \\sqrt{ \\pi } \\quad \\quad \\, \\int_0^r e^{-u^2} du = \\frac{ \\sqrt{ \\pi} }{2} \n\\end{gathered}\n\\]\n\\item \\[\n  \\begin{gathered}\n    \\Gamma(s) = \\int_{0^+}^{\\infty} t^{s-1} e^{-t} dt \\\\\n    \\Gamma{\\left( \\frac{1}{2} \\right)} = \\int_0^{\\infty} t^{-1/2} e^{-t} dt = \\int_0^{\\infty} u^{-1} e^{-u^2} 2u du = 2 \\int_0^{\\infty} e^{-u^2} du = 2 \\frac{ \\sqrt{ \\pi} }{2} = \\sqrt{ \\pi } \\\\\n    \\text{ since } \\begin{aligned} t & = u^2 \\\\ dt & = 2u du \\end{aligned}\n  \\end{gathered}\n  \\]\n\\end{enumerate}\n\n\\exercisehead{17} $\\begin{aligned} x & = u + v \\\\ y & = v - u^2 \\end{aligned}$ \n\\begin{enumerate}\n  \\item $det{ D \\phi} = \\left| \\begin{matrix} 1 & 1 \\\\ -2u & 1 \\end{matrix} \\right| = 1 + 2u$\n  \\item \\[ \n    \\begin{aligned}\n      & (u,0) \\Longrightarrow (u , -u^2) \\quad  u & \\in [0,2] \\\\ \n      & (0,v) \\Longrightarrow (v,v) \\quad v & \\in [0,2] \\\\ \n      & (u,2-u) \\Longrightarrow (u + 2 -u, 2 - u -u^2) = (2, -(u+\\frac{1}{2})^2 + \\frac{9}{4}) \\quad u & \\in [0,2] \n\\end{aligned} \\]\n  \\item \\[\n\\begin{gathered}\n  \\iint_T du dv (1+ 2u) = \\int_0^2 \\int_0^{2-u} (1+2u) dv du = \\left. (2u - \\frac{1}{2} u^2 ) \\right|_0^2 + \\int_0^2 2u (2-u) du = \\frac{14}{3} \\\\ \n  \\int_0^2 dx \\int_{-x^2}^x dy = \\int_0^2 dx ( x+x^2) = \\left. \\left( \\frac{1}{2} x^2 + \\frac{1}{3} x^3  \\right) \\right|_0^2 = \\frac{14}{3}\n\\end{gathered}\n\\]\n  \\item \\[\n\\begin{gathered}\n  \\iint_S (x-y+1)^{-2} dx dy = \\int_0^2 \\int_0^{2-u} (u+v -v + u^2 + 1 )^{-2} (1+2u) du dv = \\int_0^2 dv \\int_0^{2-v} \\frac{1+ 2u}{ (u^2 + u +1)^2} du = \\\\\n  = \\int_0^2 dv \\left. \\left( \\frac{-1}{ u^2 + u + 1 } \\right) \\right|_0^{2-v}   = \\int_0^2 dv \\left( 1 - \\frac{1}{ 4 - 4v + v^2 + 2 -v + 1 } \\right) \\\\ \n  \\text{ Now } \\\\\n  \\int_0^2 \\frac{ 1}{ 7 - 5v + v^2}  = \\int_0^2 \\frac{1}{ (v- \\frac{5}{2} )^2 + \\frac{3}{4} } = \\int \\frac{4/3}{ \\left( \\frac{2}{\\sqrt{3}} (v-\\frac{5}{2}) \\right)^2 + 1  } = \\left. \\frac{ 4}{3} \\left( \\frac{ \\arctan{ \\frac{2}{\\sqrt{3}} (v-\\frac{5}{2} ) } }{ 2 /\\sqrt{3}} \\right) \\right|_0^2 = \\\\\n  = \\frac{2\\sqrt{3}}{3} \\left( \\arctan{ \\left( \\frac{-1}{\\sqrt{3}} \\right) } - \\arctan{ \\left( \\frac{5}{\\sqrt{3}} \\right) } \\right) \\\\\n  \\Longrightarrow \\iint_S (x-y+1)^{-2} dx dy = 2 - \\frac{2 \\sqrt{3}}{3} \\left( \\arctan{ \\left( \\frac{-1}{\\sqrt{3}} \\right) } - \\arctan{ \\left( \\frac{5}{\\sqrt{3} } \\right) } \\right)\n\\end{gathered}\n\\]\n\\end{enumerate}\n\n\\exercisehead{18} $\\begin{aligned} x & = u^2 - v^2 \\\\ y & = 2uv \\end{aligned}$ \n\\begin{enumerate}\n\\item $J(u,v) = det{D\\phi} = \\left| \\begin{matrix} 2u & -2v \\\\ 2v & 2u \\end{matrix} \\right| = 4 u^2 + 4 v^2 = 4(u^2 + v^2)$\n\\item Note the transformation of the boundaries.  \\[\n\\begin{aligned}\n  & (u,1), \\, u & \\in [1,2] \\quad & \\begin{aligned} x & = u^2 - 1 \\\\ y & = 2u \\end{aligned} \\quad & x & = \\frac{y^2 }{4} - 1 \\quad & \\begin{aligned} y & \\in [2,4] \\\\ x & \\in [0,3] \\end{aligned} \\\\ \n  & (2,v), \\, v & \\in [1,3] \\quad & \\begin{aligned} x & = 4 - v^2 \\\\ y & = 4 v \\end{aligned} \\quad & x & = 4 - \\frac{y^2}{16} \\quad & \\begin{aligned} y & \\in [4,12] \\\\ x & \\in [-5,3] \\end{aligned} \\\\\n  & (u,3), \\, u & \\in [1,2] \\quad & \\begin{aligned} x & = u^2 - 9 \\\\ y & = 6u \\end{aligned} \\quad & x & = \\frac{y^2}{36} - 9 \\quad & \\begin{aligned} y & \\in [6,12] \\\\ x & \\in [-8,-5] \\end{aligned} \\\\ \n  & (1,v), \\, v & \\in [1,3] \\quad & \\begin{aligned} x & = 1 - v^2 \\\\ y & = 2v \\end{aligned} \\quad & x & = 1 - \\frac{y^2}{4} \\quad & \\begin{aligned} y & \\in [2,6] \\\\ x & \\in [-8,0] \\end{aligned}\n\\end{aligned}\n\\]\n\\item \\[\nx^2 + y^2 = u^4 - 2u^2 v^2 + v^4 + 4u^2 v^2 = (u^2 + v^2)^2 = 1 \\Longrightarrow u^2 + v^2 = 1 \n\\]\nCircle is invariant under ``hyperbolic'' transformation.  \n\\[\n\\begin{aligned}\n  \\int_{-1}^1 \\int_{-\\sqrt{ 1 - u^2}}^{\\sqrt{ 1 - u^2}} (u^2 - v^2)(2uv) 4 (u^2 + v^2) du dv & = 8 \\int_{-1}^1 du \\int_{-\\sqrt{ 1 - u^2}}^{\\sqrt{ 1 - u^2 }} (u^2 - v^2)(uv) dv = \\\\\n  & = 8 \\int_{-1}^1 du \\left( \\frac{u^3}{2} ((1-u^2) - (1-u^2) ) - u \\frac{1}{4} (0) \\right) = \\boxed{ 0 } \n\\end{aligned}\n\\]\n\\end{enumerate}\n\n\\exercisehead{19} \\[\n\\begin{gathered}\n  I(p,r) = \\iint_R \\frac{ dx dy }{ (\\rho^2 + x^2 + y^2 )^p } = \\int_0^{2\\pi} d\\theta \\int_0^R \\frac{ rdr }{ (p^2 + r^2)^p } = \\begin{cases} \\int_0^{2\\pi} d\\theta \\left. \\frac{ (p^2  +r^2)^{-p+1}}{ 2(1-p)} \\right|_0^R = \\frac{ \\pi}{ 1 - p } ((p^2 + R^2)^{-p + 1} - (p^2)^{-p+1} ) \\\\\n    \\int_0^{2\\pi} d\\theta \\frac{ \\ln{ 1^2 + R^2}}{2 }  = \\pi \\ln{ ( 1 + R^2) } \n\\end{cases} \\\\ \n  R \\to \\infty, \\, \\text{ if } p > 1, \\, \\lim_{R \\to \\infty} I(p,r) = \\frac{- \\pi}{1-p} p^{2 - 2p }\n\\end{gathered}\n\\]\n\n\\exercisehead{20} Let $u = x+y$.  Note that the region in $xy$ is a rectangle starting from $P = (0,-1)$ and spanned by $a = (1,1), \\, b = (-1,1)$.  \n\\[\n\\begin{gathered}\n  \\left( \\begin{matrix} x \\\\ y \\end{matrix} \\right) = \\left( \\begin{matrix} 0 \\\\ -1 \\end{matrix} \\right) + s \\left( \\begin{matrix} 1 \\\\ 1 \\end{matrix} \\right) + t \\left( \\begin{matrix} -1 \\\\ 1 \\end{matrix} \\right) \\quad \\quad \\, det{D \\phi} = \\left| \\begin{matrix} 1 & -1 \\\\ 1 & 1 \\end{matrix} \\right| = 1 + 1 = 2 \\\\ \n  \\begin{aligned}\n    x & = s + -t \\\\ \n    y & = -1 + s +t \n  \\end{aligned} \\quad \\quad \\, x+ y = 2s - 1 \\\\\n  \\Longrightarrow \\iint_S f(x+y) dy dx = \\int_0^1 \\int_0^1 f(2s- 1) 2ds dt = 2 \\int_0^1 f(2s-1) ds = \\int_{-1}^1 f(u) du \n\\end{gathered}\n\\]\n\n\\exercisehead{21} Look at what we want.  We eventually want $ax+by = u \\sqrt{ a^2 + b^2}$.  Then try that substitution.  \n\nAlso note that we want $J(x,y) = det{D\\phi} \\neq 0$ for all points considered.  We are given that $a^2 +b^2  \\neq 0$.  Then try to get that as a nonzero factor for $J$, the Jacobian.  \n\n\\[\n\\begin{gathered}\n  \\begin{aligned} ax + by & = Au  \\\\ cx + dy & = Av \\end{aligned} \\quad \\, \\Longrightarrow \\begin{gathered} A = \\sqrt{ a^2 + b^2 } \\\\ \\left[  \\begin{matrix} a & b \\\\ c & d \\end{matrix} \\right] \\left[ \\begin{matrix} x \\\\ y \\end{matrix} \\right] = \\left[ \\begin{matrix} A u \\\\ A v \\end{matrix} \\right] \\end{gathered} \\\\\n  \\Longrightarrow \\left[ \\begin{matrix} x \\\\ y \\end{matrix} \\right] = \\frac{1}{ ad - bc} \\left[ \\begin{matrix} d & -b \\\\ -c & a \\end{matrix} \\right] \\left[ \\begin{matrix} A u \\\\ Av \\end{matrix} \\right]  \\\\\n\\text{ We want $ad-bc \\neq 0 $ so simply use our hypothesis: $a^2 + b^2 \\neq 0 $.  Then $d = a, \\, c = -b$ } \\\\\n\\Longrightarrow \\left( \\begin{matrix} x \\\\ y \\end{matrix} \\right) = \\frac{1}{A} \\left( \\begin{matrix} ua - bv \\\\ ub+av \\end{matrix} \\right) \\quad \\quad det{ D \\phi} = \\left| \\begin{matrix} \\frac{a}{A} & \\frac{-b}{A} \\\\ \\frac{b}{A} & \\frac{a}{A}\\end{matrix} \\right| = 1 \n\\end{gathered}\n\\]\nLet's observe how the circular region in $xy$ changes with $uv$.  \n\\[\nx^2 + y^2 = 1 = \\frac{ a^2 u ^2 - 2ab uv + b^2 v^2 }{ A^2} + \\frac{ b^2 u ^2 + 2abuv + a^2 v^2 }{A^2} = u^2 + v^2 = 1\n\\]\nAmazing!  The circle is invariant under a normalized linear transformation of nonzero determinant.  \n\\[\n\\Longrightarrow \\int_{-1}^1 \\int_{-\\sqrt{ 1 - u^2}}^{ \\sqrt{ 1 - u^2}} f(u+c) dv du = 2 \\int_{-1}^1 \\sqrt{ 1 - u^2 } f(u \\sqrt{ a^2 + b^2 } )du \n\\]\n\n\\exercisehead{22} From the given problem, we obviously want to make the substitution $u = yx$.    Consider the transformed boundaries and the Jacobian for this transformation.    \n\\[\n\\begin{aligned}\n  xy & = 1 \\quad \\, & u  = 1 \\\\ \n  xy & = 2 \\quad \\, & u = 2 \\\\ \n  y & =x \\quad \\, u & = x^2 \\\\ \n  y & = 4x \\quad \\, u & = 4x^2 \n\\end{aligned} \\quad \\quad \\, \\begin{gathered}\n  \\left( \\begin{matrix} x \\\\ y \\end{matrix} \\right) = \\left( \\begin{matrix} x \\\\ u/x \\end{matrix} \\right) \\end{gathered}  \\\\\ndet{ D \\phi} = \\left| \\begin{matrix} 1 & 0 \\\\ -u /x^2 & 1/x \\end{matrix} \\right| = \\frac{1}{x} \n\\]\nSketch the transformed region in the $xu$ plane, with boundaries as described above.  Then clearly,\n\\[\n\\int_1^2 du \\int_{ \\frac{ \\sqrt{u}}{2} }^{ \\sqrt{u }} f(u) \\frac{1}{x} dx = \\int_1^2 du \\left(\\ln{ (\\sqrt{ u} )} - \\ln{ \\left( \\frac{ \\sqrt{u}}{2} \\right) } \\right) f(u) = \\int_1^2 du \\left( \\frac{1}{2} \\ln{u} - \\frac{1}{2} \\ln{u} + \\ln{2} \\right) f(u) = \\ln{2} \\int_1^2 f(u) du\n\\]\n\n\\section*{ 11.34 Exercises - Proof of the transformation formula in a special case, Proof of the transformation formula in the general case, Extensions to higher dimensions, Change of variables in an $n$-fold integral, Worked examples }\n\n\\exercisehead{1} $z = xy$.  Note that $z=0$ implied $x=0$ or $y=0$.  \n\\[\n\\iiint_S xy^2 z^3 dx dy dz = \\int_0^1 \\int_0^x \\int_0^{xy} xy^2 z^3 dz dy dx = \\int_0^1 \\int_0^x \\frac{xy^2}{4} (xy)^4 dy dx = \\int_0^1 \\frac{ x^5}{4} \\frac{x^7}{7} dx = \\frac{1}{28} \\frac{1}{13} = \\frac{1}{364}\n\\]\n\n\\exercisehead{2} $z = 1- x-y$.  $z=0$ defines a boundary, so $y= 1-x$.  \n\\[\n\\begin{gathered}\n  \\iiint_S (1+x+y + z)^{-3} dx dy dz = \\int_0^1 dx \\int_0^{1-x} dy \\int_0^{1-x-y} (1+ x+y+z)^{-3} dz = \\\\\n  = \\int_0^1 dx \\int_0^{1-x} dy \\left( \\frac{ 1/-2}{ (1+x+y+ (1-x-y))^2 } - \\frac{ 1/-2 }{ (1+x+y)^{-2}} \\right) = \\\\\n  = \\frac{-1}{2} \\int_0^1 dx \\left( \\frac{1}{4} (1-x) + \\left. (1+x+y)^{-1} \\right|_0^{1-x} \\right) = \\frac{-1}{2} \\left( \\frac{1}{4} (1- 1/2) + 1/2(1) - \\ln{2} \\right) = \\boxed{ \\frac{-1}{2} \\left( \\frac{5}{8}  -\\ln{2} \\right) }\n\\end{gathered}\n\\]\n\n\\exercisehead{3} $J = r^2 \\sin{\\theta}$  (polar coordinates).  Note $x\\leq 0, \\, y \\leq 0, \\, z \\leq 0$\n\\[\n\\begin{gathered}\n  \\int_0^{\\pi/2} d\\theta \\int_0^{\\pi/2} d\\phi \\int_0^1 r \\cos{\\phi} \\sin{\\theta} r \\sin{\\phi} \\sin{\\theta} r \\cos{\\theta} r^2 \\sin{\\theta} dr = \\int_0^{\\pi/2} \\int_0^{\\pi/2} d\\phi \\frac{1}{6} \\sin^3{\\theta} \\cos{\\theta} \\cos{\\phi} \\sin{\\phi} = \\\\\n   = \\frac{1}{6} \\int_0^{\\pi/2} d\\theta \\sin^3{\\theta} \\cos{\\theta} \\frac{1}{2} = \\boxed{ \\frac{1}{48 } }\n\\end{gathered}\n\\]\n\n\\exercisehead{4} $\\begin{aligned} x & = au \\\\ y & = bv \\\\ z & = cw \\end{aligned}$ \\quad \\, $J = abc$\n\\[\n\\Longrightarrow \\int_0^{\\pi} d\\theta \\int_0^{2\\pi} d\\phi \\int_0^1 (u^2 + v^2 + w^2 ) abc r^2 \\sin{\\theta} dr  = \\int_0^{\\pi} d\\theta \\int_0^{2\\pi} d\\phi \\sin{\\theta} \\frac{ abc}{5} = \\frac{2\\pi}{5} abc (2) = \\boxed{  \\frac{ 4 \\pi abc}{5 } }\n\\]\n\n\\exercisehead{5} $z^2 = x^2 + y^2 = r^2$.  $z=r$\n\\[\n\\iiint_S \\sqrt{ x^2  +y^2} dx dy dz = \\int_0^1 dz \\int_0^{2\\pi} d\\phi \\int_0^z r^2 dr = \\frac{1}{3} \\frac{1}{4} 2\\pi = \\boxed{ \\frac{ \\pi}{6}}\n\\]\n\nFor exercises 6,7,8, I think you have to sketch the region and surmise the new boundaries intuitively from the sketch.  I don't see a formula you could simply plug in to determine the new regions and boundaries.  \n\n\\exercisehead{6} \n\\[\n\\iiint_S (x^2 +y^2) dx dy dz = \\int_0^2 \\int_0^{2\\pi} \\int_0^{\\sqrt{ 2z }} r^2 ( rdr) d\\phi dz = \\int_0^2 2\\pi \\frac{1}{4} (2z)^2 = \\frac{ 16 \\pi }{3} \n\\]\n\n\\exercisehead{7}\n\n\\exercisehead{10} \n\\[\n\\iiint_S (x^2 + y^2) dx dy dz =\\int_0^2 \\int_0^{2\\pi} \\int_0^{\\sqrt{2z}} r^2 ( r dr) d\\phi dz = \\int_0^2 2\\pi \\frac{1}{4} (2z)^2 = \\boxed{ \\frac{16 \\pi }{3 }}\n\\]\n\n\\exercisehead{13} \n\\[\n\\iiint_S dx dy dz = \\int_0^{\\pi} d\\theta \\int_0^{2\\pi} d\\phi \\int_0^a r^2 \\sin{\\theta} = \\frac{ a^3}{3} (2\\pi)(2) = \\frac{ 4 \\pi a^3 }{3 }\n\\]\n\\exercisehead{14} \\[\n\\iiint_S dx dy dz = \\int_0^{\\pi} d\\theta \\int_0^{2\\pi} d\\phi \\int_a^b r^2 \\sin{\\theta} = \\frac{4\\pi}{3} (b^3 - a^3 )\n\\]\n\n\\exercisehead{15} Let $\\sqrt{ a^2 + b^2 + c^2 } = \\delta$ s.t. $\\delta > R$.\n\nSince the sphere $S$ of integration is rotationally symmetric, \\textbf{do a rotation so that} so that $(a,b,c) = (0,0,\\delta)$ \\large{ it's a lot easier! }\n\n\\large{ \\textbf{ Tip: } Take advantage of symmetries, particularly spherical symmetries, and make problems easier by choosing a convenient rotation of the coordinate axes. }\n\\normalsize\n\\[\n\\begin{gathered}\n  \\int_0^{\\pi} d\\theta \\int_0^{2\\pi} d\\phi \\int_0^R r^2 \\sin{\\theta} dr ( x^2 +y^2 + (z-\\delta)^2 )^{-1/2} = \\int_0^{\\pi} d\\theta \\int_0^{2\\pi} d\\phi \\int_0^R r^2 \\sin{\\theta} dr (r^2 + \\delta^2 - 2r\\delta \\cos{\\theta})^{-1/2} = \\\\\n = \\int_0^{2\\pi} d\\phi \\int_0^R r \\left. \\frac{ (r^2 + \\delta^2 - 2r \\delta \\cos{\\theta})^{1/2}}{ \\delta} \\right|_0^{\\pi} = \\int_0^{2\\pi} d\\phi \\int_0^R \\frac{r}{\\delta} \\left( (r^2 + \\delta^2 + 2r\\delta )^{1/2} - (r^2 + \\delta^2 - 2r\\delta)^{1/2} \\right) \\\\\n \\text{ since  $\\delta > R$, then $((r - \\delta)^2)^{1/2} = |r- \\delta| = \\delta - r$, so then } \\\\ \n = 2\\pi \\int_0^R \\frac{r}{\\delta} ((r+\\delta) - (\\delta - r) ) = \\boxed{ \\frac{ 4\\pi }{3} \\frac{R^2}{\\delta} }\n\\end{gathered}\n\\]\n\n\\exercisehead{16} $\\begin{aligned} x & = a \\rho \\cos^m{ \\theta} \\sin^n{\\phi} \\\\ y & = b\\rho \\sin^m{\\theta} \\sin^n{\\phi} \\\\ z & = c\\rho \\cos^n{\\phi} \\end{aligned}$  \n\\[\n\\begin{gathered}\n  det{J} = \\left| \\begin{matrix} a c^m{\\theta} s^n{\\phi} & na\\rho c^m{\\theta} s^{n-1}{\\phi} c{\\phi} & -m a\\rho c^{m-1}{\\theta} s{\\theta} s^n{\\phi}  \\\\ bs^m{\\theta} s^n{\\phi} & nb \\rho s^m{\\theta} s^{n-1}{\\phi}c{\\phi} & mb\\rho s^{m-1}{\\theta} s^n{\\phi} c{\\theta} \\\\ cc^n{\\phi} & - nc\\rho c^{n-1}{\\phi} s{\\phi} & 0 \\end{matrix} \\right| = \\\\ \n  = ac^m{\\theta} s^n{\\phi} (mnbc \\rho^2 c^{n-1}{\\phi} s{\\phi} s^{m-1}{\\theta} s^n{\\phi} c{\\theta} + - na \\rho (c^m{\\theta} s^{n-1}{\\phi} c{\\phi})( - mbc \\rho s^{m-1}{\\theta} s^n{\\phi} c^n{\\phi} c{\\theta}) + \\\\\n  + -ma\\rho c^{m-1}{\\theta}s{\\theta}s^m{\\phi}((-bnc\\rho s^m{\\theta} c^{n-1}{\\phi} s^n{\\phi} s^{\\phi} ) - nb \\rho c c^n{\\phi} s^m{\\theta} s^{n-1}{\\phi} c{\\phi}) = \\\\\n  = abcmn\\rho^2 ( c^{m+1}(\\theta) s^{m-1}{\\theta} s^{2n+1}{\\phi} c^{n-1}{\\phi} + c^{m+1}{\\theta} s^{m-1}{\\theta} s^{2n-1}{\\phi} c^{n+1}{\\phi} + \\\\\n  + c^{m-1}{\\theta} s{\\theta} s^n{\\phi}( s^m{\\theta} s^{n+1}{\\phi} c^{n-1}{\\phi} + s^m{\\theta} s^{n-1}{\\phi} c^{n+1}{\\phi} ) ) = \\\\\n  = abcmn \\rho^2 (c^{m+1}{\\theta} s^{m-1}{\\theta} s^{2n-1}{\\phi} c^{n-1}{\\phi} + c^{m-1}{\\theta} s^{m+1}{\\theta} s^{2n-1}{\\phi} c^{n-1}{\\phi} ) =  \\\\\n  = \\boxed{ abcmn \\rho^2 (c^{m-1}{\\theta} s^{m-1}{ \\theta} s^{2n-1}{\\phi} c^{n-1}{\\phi} ) }\n\\end{gathered}\n\\]\n\n\\exercisehead{17} \n\\[\n\\begin{gathered}\n  I_x = \\iiint_S (y^2 + z^2) f(x,y,z) dx dy dz =  \\iiint_S y^2 f(x,y,z) dx dy dz + \\iiint_S z^2 f(x,y,z) dx dy dz = I_{xy} + I_{xz} \\\\ \n  I_y = \\iiint_S (x^2 + z^2) f(x,y,z) dx dy dz = \\iiint_S x^2 f(x,y,z) dx dy dz + \\iiint_S z^2 f(x,y,z) dx dy dz = I_{yz} + I_{yx} \\\\ \n  I_z = \\iiint_S (x^2 + y^2) f(x,y,z) dx dy dz = \\iiint_S x^2 f(x,y,z) dx dy dz + \\iiint_S y^2 f(x,y,z) dx dy dz = I_{zy} + I_{zx}\n\\end{gathered}\n\\]\n\n\\exercisehead{18} The condition for the paraboloid and sphere to meet is the following:\n\\[\nx^2 + y^2 = 4z = 5 - z^2 \\Longrightarrow z^2 + 4z - 5 = 0 \\text{ or } (z+5)(z-1) = 0\n\\]\n\\[\n\\begin{aligned}\nV & = \\int_0^2 \\int_0^{2\\pi} \\int_{\\frac{r^2}{4}}^{ \\sqrt{ 5- r^2}} r dz d\\phi dr = \\int_0^2 2\\pi r \\left( \\sqrt{ 5- r^2} - \\frac{r^2}{4} \\right) = \\\\\n& = 2\\pi \\left. \\left( \\frac{-1}{3} (5-r^2)^{3/2} - r^4/16 \\right) \\right|_0^2 = 2\\pi (\\frac{-1}{3} (1-5^{3/2} ) - 16/16) = \\boxed{ \\frac{ 2\\pi }{3} (5^{3/2} - 4)  }\n\\end{aligned}\n\\]\n\n\\exercisehead{20} \n\\[\n\\int_0^{2\\pi} \\int_0^{\\pi} \\int_a^b r^2 ( r^2 \\sin{\\theta}) dr d\\theta d\\phi = \\frac{1}{5} (b^5- a^5) (2)(2\\pi) = \\boxed{ \\frac{ 4 \\pi (b^5 - a^5) }{5}  }\n\\]\n\n\\exercisehead{21} \n\\[\n\\begin{gathered}\n  \\int_0^h \\int_0^{2\\pi} \\int_0^z  r dr d\\phi dz = \\int_0^h \\frac{ 2\\pi}{2} z^2 dz = \\frac{ \\pi }{3} h^3 = M \\\\ \n  \\overline{z} M = \\int_0^h \\int_0^{2\\pi} \\int_0^z r z dr d\\phi dz = \\int_0^h dz 2\\pi \\frac{1}{2} z^3 = \\frac{ \\pi }{4} h^4\n\\end{gathered}\n\\]\n$\\overline{z} = \\frac{3h}{4}$ so centroid is $\\frac{h}{4}$ away from base.  \n\n\n\\exercisehead{22} Note the symmetry in $\\phi$ and $r$.\n\\[\n\\begin{gathered}\n  M = \\int_0^h \\int_0^{2\\pi} \\int_0^z (h-z) r dr d\\phi dz = \\int_0^h dz (2\\pi) (h-z)\\frac{1}{2} z^2 = (2\\pi) \\left( \\frac{h}{6} h^3 - \\frac{h^4}{8} \\right) = (2\\pi h^4)\\left( \\frac{1}{24} \\right) = \\boxed{ \\frac{ \\pi h^4 }{ 12} } \\\\ \n  \\begin{aligned}\n  \\overline{z} M & = \\int_0^h \\int_0^{2\\pi} \\int_0^z (h-z) z r dr d\\phi dz = 2\\pi \\int_0^h dz (h-z) z \\frac{1}{2} z^2 = \\pi \\left. \\left( \\frac{ z^4}{4} h - \\frac{1}{5} z^5 \\right) \\right|_0^h = \\\\ \n  & = \\pi (h^5) (1/4 - 1/5) \n\\end{aligned} \\\\\n  \\Longrightarrow \\overline{z} = \\frac{3}{5} h \n\\end{gathered}\n\\]\nCenter of mass is $\\frac{2}{5} h$ from the base.  \n\n\\exercisehead{23} Note symmetry in $\\phi$ and $r$.  \n\\[\n\\begin{gathered}\n  M = \\int_0^h \\int_0^{2\\pi} \\int_0^z r r dr d\\phi dz = \\int_0^h 2 \\pi \\left. \\frac{r^3}{3} \\right|_0^z dz = \\frac{2\\pi}{3} \\frac{ h^4 }{4} = \\frac{ \\pi h^4 }{6} \\\\ \n  \\overline{z} M = \\int_0^h \\int_0^{2\\pi} \\int_0^z r z r dr d\\phi dz = 2\\pi \\int_0^h z \\frac{1}{3} z^3 = \\left. \\frac{2 \\pi }{3} \\frac{1}{5} z^5 \\right|_0^h = \\frac{2\\pi }{15} h^5 \\\\ \n\\end{gathered} \\quad \\Longrightarrow   \\overline{z} = \\frac{4 h }{5} \n\\]\n$\\frac{h}{5}$ from base.  \n\n\\exercisehead{24} Consider concentric hemispheres of radii $a$ and $b$, where $0<a<b$.  \n\\[\n\\begin{gathered}\n  M  = \\int_0^{\\pi/2} d\\theta \\int_0^{2\\pi} d\\phi \\int_a^b r^2 \\sin{\\theta} = \\frac{ b^3 - a^3}{3} (2\\pi) \\\\ \n  \\overline{z} M = \\int_0^{\\pi/2} d\\theta \\int_0^{2\\pi} d\\phi \\int_a^b r^2 \\sin{\\theta} (r \\cos{\\theta}) = \\int_0^{\\pi/2} d\\theta 2\\pi \\frac{b^4 - a^4}{4} \\sin{\\theta} \\cos{\\theta} = \\frac{\\pi}{4} (b^4- a^4) \n\\end{gathered} \\quad \\Longrightarrow \\overline{z} = \\frac{ 3}{8} \\frac{ b^4 - a^4}{b^3 - a^3 }\n\\]\n\n\\exercisehead{25} I tried cylindrical coordinates first.  Didn't help.   \\\\\n\\textbf{ Tip: } quickly switch and try another way, another set of coordinates, if one way doesn't work.  \\[\n\\begin{gathered}\n  M = \\int_0^1 dz \\int_0^1 dy \\int_0^1 dx (x^2 + y^2 +z^2) = 1 \\\\ \n  \\overline{x} M = \\int_0^1 dz \\int_0^1 dy \\int_0^1 dx x (x^2 + y^2 + z^2) = \\frac{1}{4} + \\frac{1}{2} \\left( \\frac{1}{3} \\right) + \\frac{1}{2} \\left( \\frac{1}{3} \\right) = \\frac{7}{12} \n\\end{gathered}\n\\]\nBy label symmetry of $x,y,z$, $\\overline{x} = \\overline{y} = \\overline{z} = \\frac{7}{12} $  \n\n\\exercisehead{26}  Note that $\\frac{r}{z} = \\frac{a}{h}$  \n\\[\n\\begin{gathered}\n\\begin{aligned}\n  I_{cone, z} & = \\int_0^h \\int_0^{2\\pi} \\int_0^{ \\frac{a}{h} z} r^2 ( rdr ) dz \\frac{M}{V} = 2\\pi \\int_0^h \\frac{1}{4} \\left( \\frac{a}{h} \\right)^4 z^4 dz \\frac{M}{V}  = \\frac{ \\pi}{10} \\left( \\frac{a}{h} \\right)^4 h^5 \\frac{M}{V}  = \\frac{ 3a^2 }{10} M \n\\end{aligned} \\\\\nV  = \\int_0^h \\int_0^{2\\pi} d\\phi \\int_0^{az/h} rdr dz = 2\\pi \\frac{ a^2 }{ 2h^2 } \\frac{1}{3} h^3 = \\frac{ \\pi a^2 h }{3} \n\\end{gathered}\n\\]\n\\[\n\\begin{aligned}\n  I_x + I_y & = \\iiint \\frac{M}{V} (y^2 + z^2 + x^2 + z^2 ) dx dy dz = \\frac{M}{V} \\iiint (x^2 + y^2 + 2z^2) dx dy dz = \\\\ \n  & = \\frac{M}{V} \\left( \\frac{ \\pi a^4 h }{10} + 2 \\int_0^h \\int_0^{2\\pi} d\\phi \\int_0^{\\frac{az}{h} } z^2 r dr dz \\right) = \\frac{M}{V} \\left( \\frac{ \\pi a^4 h }{10 } + 2 \\int_0^h 2\\pi \\frac{1}{2} \\frac{a^2 }{h^2} z^4 dz \\right) = \\frac{M}{V} \\left( \\frac{ \\pi a^4 h }{10} + \\frac{ 2 \\pi a^2 }{5h^2} h^5 \\right) = \\\\\n  & = 2I_x \n\\end{aligned}\n\\]\n\\[\n\\Longrightarrow I_x = \\frac{ M}{ 2 \\left( \\frac{ \\pi a^2 h}{3} \\right)} (\\pi a^2 h ) \\left( \\frac{a^2 }{10} + \\frac{ 2h^2 }{5} \\right) = \\boxed{ \\frac{3M}{2} \\left( \\frac{a^2}{10} + \\frac{ 2h^2}{5} \\right) }\n\\]\n\n\n\\exercisehead{27} $f = M / \\frac{4}{3} \\pi R^3 = M/V$\n\\[\n\\begin{aligned}\n  I & = \\iiint (x^2 + y^2 ) \\frac{M}{V} dx dy dz = \\int_0^{\\pi} d\\theta \\int_0^{2\\pi} d\\phi \\int_0^R r^2 ( \\sin{\\theta}) \\frac{M}{V} r^2 \\sin^2{\\theta} = \\frac{2\\pi M}{V} \\int_0^{ \\pi} \\sin{\\theta} (1- \\cos^2{\\theta}) \\frac{R^5}{5} = \\\\\n  & = \\frac{ 2 \\pi M }{ 5 V } R^5 \\left( 2 + \\frac{1}{3} (-2) \\right) = \\frac{ 2 \\pi M R^5 }{ 5 \\frac{4 \\pi }{3} R^3 } \\left( \\frac{4}{3} \\right) = \\boxed{ \\frac{2}{5}  M R^2 } \n\\end{aligned}\n\\]\n\nAnother way, which is quite clever, is the following.  Consider that \n\\[\n2(x^2 + y^2 + z^2) = x^2 + y^2 + z^2 + x^2 + x^2 + y^2 \n\\]\nThen\n\\[\n2 \\iiint (x^2 + y^2 + z^2 ) \\frac{M}{V} dx dy dz = 2 \\int_0^{\\pi} d\\theta \\int_0^{2\\pi} d\\phi \\int_0^R r^2 \\frac{M}{V} r^2 \\sin{\\theta} = \\frac{ 8 \\pi M }{5V} R^5 = I_z + I_y + I_x \n\\]\nBy spherical symmetry, $I_z = I_y$.  So then $I = \\frac{ 8 \\pi M R^5 }{ 15 \\left( \\frac{ 4 \\pi R^3 }{3} \\right) } = \\frac{ 2 M R^2 } {5 } $ \n\n\\exercisehead{28} \n\\[\n\\begin{gathered}\n  M = \\int_{-h}^h dz \\int_0^{2\\pi} d\\phi \\int_0^a r r dr = 2h (2\\pi) \\frac{a^3}{3} \\\\ \n  I_z = \\int_{-h}^h dz \\int_0^{2\\pi} d\\phi \\int_0^a r^2 r dr r   = (2h)(2\\pi) \\frac{1}{5} a^5 = \\boxed{ \\frac{3 M a^2}{5} }\n\\end{gathered}\n\\]\n\n\\exercisehead{29} \n\\[\n\\begin{gathered}\n  V_{cap} = \\left( \\frac{4\\pi R^3}{3} \\right) \\frac{1}{2} = \\frac{ 2\\pi R^3 }{3} \\quad \\quad \\, c = \\frac{M}{V} = \\text{ mass density } \\\\ \n  V_{cylinder} = \\pi \\left( \\frac{1}{2} \\right)^2 2 = \\frac{\\pi}{2} \\\\ \n  \\overline{z} M = \\int_0^{\\pi/2} d\\theta \\int_0^{2\\pi} d\\phi \\int_0^R  r \\cos{\\theta} r^2 \\sin{\\theta} dr \\frac{M}{V} = \\frac{ 2 \\pi R^4 }{4} \\frac{1}{2} \\frac{M}{V} = \\frac{ \\pi R^4 }{ 4 } \\frac{M}{V} \\\\\n  \\overline{z} = \\frac{ \\pi R^4 }{ 4 \\left( \\frac{ 2 \\pi R^3}{3} \\right) } = \\frac{ 3 R }{8}\n\\end{gathered}\n\\]\nCondition wanted is for center of mass of the mushroom to be at $z=0$, for this particular choice of coordinates.  \n\\[\n\\frac{ c \\frac{ \\pi R^4}{4} + \\left( c \\frac{\\pi}{2} \\right) (-1) }{ c V + c\\frac{\\pi}{2}  } = \\frac{ \\frac{ \\pi R^4 }{4 } + \\frac{-\\pi}{2} }{ \\frac{ 2\\pi R^3 }{3} + \\frac{\\pi}{2} } = 0 \\Longrightarrow R^4 = 2 \\text{ or } \\boxed{ R = 2^{1/4} }\n\\]\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\\section*{ 12.4 Exercises - Parametric representation of a surface, The fundamental vector product, The fundamental vector product as a normal to the surface }\n\n\\exercisehead{1} \\emph{Plane}:\n\\[\n\\mathbf{r}(u,v) = (x_0 + a_1 u + b_1 v )\\mathbf{i} + (y_0 + a_2 u + b_2 v) \\mathbf{j} + (z_0  + a_3 u + b_3 v) \\mathbf{k} \\Longrightarrow \\begin{aligned} x & = x_0 + a_1 u + b_1 v \\\\ y & = y_0 + a_2 u + b_2 v \\\\ z & z_0 + a_3 u + b_3 v \\end{aligned}\n\\]\nThen get $u,v$ in terms of $x,y$.  \n\\[\n\\begin{gathered}\n  \\left[ \\begin{matrix} a_1 & b_1 \\\\ a_2 & b_2 \\end{matrix} \\right] \\left[ \\begin{matrix} u \\\\ v \\end{matrix} \\right] = \\left[ \\begin{matrix} x-x_0 \\\\ y - y_0 \\end{matrix} \\right] \\\\ \n  \\Longrightarrow \\left[ \\begin{matrix} u \\\\ v \\end{matrix} \\right] = \\frac{1}{ a_1 b_@ - b_1 a_2 } \\left[ \\begin{matrix} b_2 & -b_1 \\\\ -a_2 & a_1 \\end{matrix} \\right] \\left[ \\begin{matrix} x-x_0 \\\\ y- y_0 \\end{matrix} \\right] = \\frac{1}{ a_1 b_2 - b_1 a_2 } \\left[ \\begin{matrix} b_2 ( x-x_0) - b_1 (y_1 - y_0 ) \\\\ -a_2 (x-x_0) + a_1 ( y-y_0) \\end{matrix} \\right]\n\\end{gathered}\n\\]\nSo then\n\\[\n(a_1 b_2 - b_1 a_2) (z-z_0) = (a_3 b_2 - b_3 a_2)(x-x_0) + (b_3a_1 - a_3 b_1)(y-y_0)\n\\]\n\\[\n\\begin{aligned}\n  \\partial_u r_u & = (a_1,a_2,a_3) \\\\ \n  \\partial_v r_v & = (b_1,b_2,b_3) \n\\end{aligned}\n\\]\n\\[\n\\partial_u r \\times \\partial_v r = \\left| \\begin{matrix} e_1 & e_2 & e_3 \\\\ a_1 & a_2 & a_3 \\\\ b_1 & b_2 & b_3 \\end{matrix} \\right| = (a_2 b_3 - a_3 b_2, a_3 b_1 - a_1 b_3, a_1 b_2 - a_2 b_1 )\n\\]\n\n\\exercisehead{2} \\emph{Elliptic paraboloid}: $\\mathbf{r}(u,v) = au \\cos{v} \\mathbf{i} + bu \\sin{v} \\mathbf{j} + u^2 \\mathbf{k}$.  \nThen\n\\[\n\\begin{aligned}\n  x & = au \\cos{v} \\\\\n  y & = bu \\sin{v} \\\\ \n  z & = u^2\n\\end{aligned} \\Longrightarrow \\boxed{ \\left( \\frac{x}{a} \\right)^2 + \\left( \\frac{y}{b} \\right)^2 = z  }\n\\]\n\\[\n\\begin{aligned}\n  \\partial_u r & = (a \\cos{v}, b\\sin{v} , 2u) \\\\ \n  \\partial_v r & = (-au \\sin{v}, bu \\cos{v}, 0 )\n\\end{aligned} \\Longrightarrow \\left| \\begin{matrix} e_1 & e_2 & e_3 \\\\ a\\cos{v} & b\\sin{v} & 2 u \\\\ -au \\sin{v} & bu \\cos{v} & 0 \\end{matrix} \\right| = \\boxed{ ( -2bu^2 \\cos{v}, -2u^2 a \\sin{v}, abu) }\n\\]\n\n\\exercisehead{3} \\emph{Ellipsoid}: $\\mathbf{r}(u,v) = (a\\sin{u}\\cos{v}, b\\sin{u} \\sin{v}, c\\cos{u})$.  \n\\[\n\\Longrightarrow \\left( \\frac{x}{a} \\right)^2 + \\left( \\frac{y}{b} \\right)^2 + \\left( \\frac{z}{c} \\right)^2 = 1 \n\\]\nNow\n\\[\n\\begin{aligned}\n  \\partial_u r & = (ac(u)c(v), bc(u)s(v), -cs(u) ) \\\\ \n  \\partial_v r & = (-as(u)s(v), bs(u)c(v),0) \n\\end{aligned}\n\\]\n\\[\n\\Longrightarrow \\left| \\begin{matrix} e_1 & e_2 & e_3 \\\\ ac(u)c(v) & bc(u)s(v) & -cs(u) \\\\ -as(u)s(v) & bs(u)c(v) & 0 \\end{matrix} \\right| = \\boxed{(bcs^2(u)c(v), acs^2(u)s(v), ab(c(u))s(u)) }\n\\]\n\n\\exercisehead{4}\\emph{Surface of revolution:} $\\mathbf{r}(u,v) = (u\\cos{v}, u \\sin{v}, f(u))$.  $x^2 + y^2 = u^2$ so then\n\\[\n\\boxed{ f(\\sqrt{ x^2 + y^2}) = z }\n\\]\n\\[\n\\begin{aligned}\n  \\partial_u r & = ( \\cos{v}, \\sin{v}, f'(u) ) \\\\ \n  \\partial_V r & = (-u\\sin{v}, u \\cos{v} ,0 ) \n\\end{aligned}\n\\]\n\\[\n\\partial_u r \\times \\partial_v r = \\left| \\begin{matrix} e_1 & e_2 & e_3 \\\\ \\cos{v} & \\sin{v} & f'(u) \\\\ -u \\sin{v} & u \\cos{v} & 0 \\end{matrix} \\right| = \\boxed{ (-f' u\\cos{v}, -f'u\\sin{v}, u ) }\n\\]\n\n\\exercisehead{5} \\emph{Cylinder}: $\\boxed{ y^2 + z^2 = a^2}$  \n\\[\n\\mathbf{r}(u,v) = (u, a\\sin{v}, a\\cos{v} )\n\\begin{aligned}\n  \\partial_u r & = ( 1,0,0) \\\\ \n  \\partial_v r & = (0 , a\\cos{v}, -a\\sin{v} )\n\\end{aligned}\n\\]\n\\[\n\\Longrightarrow \\left| \\begin{matrix} e_1 & e_2 & e_3 \\\\ 1 & 0 & 0 \\\\ 0 & a \\cos{v} & -a\\sin{v} \\end{matrix} \\right| = (0, a \\sin{v}, a\\cos{v})\n\\]\n\n\\exercisehead{6} \\emph{Torus}: $\\mathbf{r}(u,v) = ((a+b\\cos{u})\\sin{v}, (a+b\\cos{u}) \\cos{v}, b\\sin{u})$, \\, $0<b<a$.\n\\[\nx^2  +y^2 = (a+b\\cos{u})^2 = (a+\\sqrt{ b^2 - z^2} )^2 \n\\]\n\\[\n\\begin{aligned}\n  \\partial_u r & = (-bs(u)s(v), -bs(u)c(v), bc(u) ) \\\\\n  \\partial_v r & ((a+bc(u))c(v), (a+bc(u))(-s(v)), 0)\n\\end{aligned}\n\\]\n\\[\n\\begin{gathered}\n\\left| \\begin{matrix} e_1 & e_2 & e_3 \\\\ -bs(u)s(v) & -bs(u)c(v) & bc(u) \\\\ (a+bc(u))c(v) & (a+bc(u))(-s(v)) & 0 \\end{matrix} \\right| = \\\\\n= (b(a+bc(u))c(u)s(v), b(a+bc(u))c(u)c(v), (a+bc(u))(bs(u)s^2(v) + bs(u)c^2(v))) \n\\end{gathered}\n\\]\n\\[\n\\Longrightarrow \\boxed{ (a + b\\cos{(u)} )b (\\cos{(u)}\\sin{(v)}, \\cos{(u)} \\cos{(v)}, \\sin{(u)} ) }\n\\]\n\n\\exercisehead{7}$\\mathbf{r}(u,v) = (a\\sin{u}\\cosh{v}, b\\cos{u}\\cosh{v}, c\\sinh{v})$  \n\\[\n\\begin{aligned}\n  \\partial_u r & = (ac(u)\\cosh{(v)}, -bs(u)\\cosh{v},0) \\\\ \n  \\partial_v r & = (as(u)\\sinh{(v)}, bc(u)\\sinh{v},c\\cosh{v} )\n\\end{aligned}\n\\]\n\\[\n\\begin{gathered}\n \\partial_u r \\times \\partial_v r  = \\left| \\begin{matrix} e_1 & e_2 & e_3 \\\\ a c(u) \\cosh{(v)} & -b s(u)\\cos{(v)} & 0 \\\\ as(u) \\sinh{(v)} & bc(u) \\sinh{v} & c\\cosh{v} \\end{matrix} \\right| = \\\\\n = (-bc\\sin{u}\\cosh^2{v}, ac\\cos{u}\\cosh^2{v}, ab\\cos^2{u} \\cosh{v}\\sinh{v}+ab\\sin^2{u} \\cosh{v}\\sinh{v}) \\end{gathered}\n\\]\n\\[\n\\| \\partial_u r \\times \\partial_v r \\| = \\boxed{ ab c \\cosh{v} \\left( \\left( \\frac{\\sin^2{u}}{a^2 } + \\frac{ \\cos^2{u}}{b^2} \\right)\\cosh^2{v} + \\frac{ \\sinh^2{v}}{c^2} \\right)^{1/2} }\n\\]\n\n\\exercisehead{8} $\\mathbf{r}(u,v) = (u+v,u-v,4v^2)$\n\\[\n\\begin{aligned}\n  \\partial_u r & = (1,1,0) \\\\ \n  \\partial_v r & = (1,-1,8v)\n\\end{aligned} \\Longrightarrow \\left| \\begin{matrix} e_1 & e_2 & e_3 \\\\ 1 & 1 & 0 \\\\ 1 & -1 & 8v \\end{matrix} \\right| = (8v,-8v,-2)\n\\]\n\\[\n\\| \\partial_u r \\times \\partial_v r \\| = \\sqrt{ 64 v^2 + 64 v^2 + 4 } = 2 \\sqrt{ 1 + 32 v^2}\n\\]\n\n\\exercisehead{9} $\\mathbf{r}(u,v) = ((u+v), u^2  +v^2, u^3 + v^3)$ \n\\[\n\\begin{gathered}\n\\begin{aligned}\n  \\partial_u r & = (1 , 2u, 3u^2) \\\\ \n  \\partial_v r & ( 1,2v, 3v^2) \n\\end{aligned} \\Longrightarrow \\left| \\begin{matrix} e_1 & e_2 & e_3 \\\\ 1 & 2u & 3u^2 \\\\ 1 & 2v & 3v^2 \\end{matrix} \\right| = (6uv^2 - 6vu^2, 3u^2- 3v^2, 2v - 2u) =  \\\\\n = (v-u) (6uv, -3(u+v), 2) \n\\end{gathered}\n\\]\n\\[\n\\Longrightarrow |v-u| \\sqrt{ 36u^2 v^2 + 9(u^2 + 2uv + v^2) + 4}\n\\]\n\n\\exercisehead{10} $\\mathbf{r}(u,v) = (u\\cos{v}, u\\sin{v}, \\frac{1}{2} u^2 \\sin{2v} )$.\n\\[\n\\begin{gathered}\n\\begin{aligned}\n  \\partial_u r & = (c(v), s(v), u s(2v) ) \\\\ \n  \\partial_v r & = (-us(v), uc(v), u^2 c(2v) )\n\\end{aligned} \\Longrightarrow \\partial_u r \\times \\partial_v r = \\left| \\begin{matrix} e_1 & e_2 & e_3 \\\\ c(v) & s(v) & us(2v) \\\\ -us(v) & u c(v) & u^2 c(2v) \\end{matrix} \\right| =  \\\\\n= (u^2 s(v)c(2v) - u^2 c(v) s(2v), -u^2 c(2v) c(v)  - u^2 s(2v)s(v) , u ) = (u^2 s(-v), -u^2 c(v), u ) \n\\end{gathered}\n\\]\n\\[\n\\| \\partial_u r \\times \\partial_v r \\|   = \\sqrt{ u^4 s^2(v) + u^4 c^2(v) + u^2 } = \\boxed{ u \\sqrt{ u^2 + 1}}\n\\]\n\n\\section*{ 12.6 Exercises - Area of a parametric surface }\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\\exercisehead{2} $S=r(T)$ \\\\\n$x^2 + y^2 = a^2$ represents $T$.  \\\\\n$x+y+z = a$ is $S$.  \n\nUsing $z = a-x-y$, $r = (x,y,a-x-y)$.  Then $\\begin{aligned} \\partial_x r & = (1,0,-1) \\\\ \\partial_y r & = (0,1,-1) \\end{aligned}$ $\\Longrightarrow \\left| \\begin{matrix} e_x & e_y & e_z \\\\ 1 & 0 & -1 \\\\ 0 & 1 & -1 \\end{matrix} \\right| = (1,1,1)$  \n\\[\n\\| \\partial_x r \\times \\partial_y r \\| = \\sqrt{ 1 + 1 + 1 } = \\sqrt{3}\n\\]\n\\[\n\\iint_T \\sqrt{3} dx dy = \\boxed{ \\sqrt{3} \\pi a^2 }\n\\]\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\\exercisehead{4} $z^2 = 2xy$ $x=2, \\, y=1$.  Then $2 z \\partial_x z = 2y$ or $\\partial_x z = \\frac{y}{z}$.  Similarly $\\partial_y z = \\frac{x}{z}$.  \n\\[\n\\left| \\begin{matrix} e_1 & e_2 & e_3 \\\\ 1 & 0 & \\frac{y}{z} \\\\ 0 & 1 & \\frac{x}{z} \\end{matrix} \\right| = ( \\frac{-y}{z}, \\frac{-x}{z}, 1 ) \\Longrightarrow \\| \\partial_x r \\times \\partial_y r \\|^2 = \\frac{y^2}{z^2} + \\frac{x^2 }{z^2} + \\frac{z^2}{z^2} = \\frac{ (x+y)^2}{z^2}\n\\]\n\\[\n\\| \\partial_x r \\times \\partial_y \\| = \\frac{x+y}{z} = \\frac{x+y}{ \\sqrt{2} \\sqrt{xy}} = \\frac{1}{\\sqrt{2}} \\left( \\sqrt{ \\frac{x}{y} } + \\sqrt{ \\frac{y}{x} } \\right)\n\\]\n$\\int a(S) = \\iint \\frac{1}{\\sqrt{2}} \\left( \\sqrt{ \\frac{x}{y} } + \\sqrt{ \\frac{y}{x} } \\right) dx dy $ so with\n\\[\n\\begin{aligned}\n& \\int \\sqrt{ \\frac{x}{y} } dx = \\left. \\frac{ \\frac{2}{3} x^{3/2}}{ \\sqrt{y}} \\right|_0^2 = \\frac{ \\frac{2}{3} 2 \\sqrt{2} }{\\sqrt{y}} = \\frac{ 4 \\sqrt{2}}{ 3} y^{-1/2} \\xrightarrow{ \\int dy } \\left. \\frac{4\\sqrt{2}}{3}  2 y^{1/2} \\right|_0^1 = \\frac{8\\sqrt{2}}{3} \\\\\n& \\int \\sqrt{ \\frac{y}{x}} = \\left. \\frac{ \\frac{2}{3} y^{3/2}}{\\sqrt{x} } \\right|_0^1 = \\frac{2}{3 \\sqrt{x}}\\xrightarrow{ \\int dx} \\frac{2}{3} \\left. 2 x^{1/2} \\right|_0^2 = \\frac{4\\sqrt{2}}{3}\n\\end{aligned}\n\\]\n\\[\n\\Longrightarrow a(S) = \\frac{1}{\\sqrt{2} } \\left( \\frac{8\\sqrt{2}}{3}  + \\frac{4 \\sqrt{2}}{3} \\right) = \\boxed{4}\n\\]\n\n\\exercisehead{5} $\\mathbf{r} = (u\\cos{v},u\\sin{v},u^2)$\n\\begin{itemize}\n\\item[a.]\n$x^2  +y^2 = z$.  $u$ is radius, $v$ is angle in $x-y$ plane.  \n\n\n\n\n\n\n\n\n\n\n\n\n\\item[b.] \\[\n\\begin{aligned}\n  \\partial_u r & = (c,s,2u) \\\\ \n  \\partial_v r & = (-us, uc,0)\n\\end{aligned} \\Longrightarrow \\partial_u r \\times \\partial_v r = \\left| \\begin{matrix} e_1 & e_2 & e_3 \\\\ c & s & 2u \\\\ -us & uc & 0 \\end{matrix} \\right| = (-2u^2 c, -2u^2s, u)\n\\]\n\\item[c.] $\\| \\partial_u r \\times \\partial_v r \\|^2 = 4u^4 + u^2$\n\\[\na(S) = \\iint u \\sqrt{ ( 1 + 4u^2) } du dv = \\left. 2\\pi \\frac{2}{3} ( 1 + 4u^2)^{3/2} \\left( \\frac{1}{8} \\right) \\right|_0^4 = \\frac{\\pi}{6} ((1 + 64)^{3/2} - 1 ) = \\frac{\\pi}{6} (65 \\sqrt{65} - 1 )\n\\]\n$\\boxed{n=6}$\n\\end{itemize}\n\n\\exercisehead{6} $x^2  +y^2 = z^2$.  \\\\\n$x^2  + y^2 + z^2 = 2ax$ $\\Longrightarrow x^2  - 2ax + a^2 + y^2 +z^2 = a^2 = (x-a)^2 + y^2 + z^2 = a^2$ \n\nDetermine where sphere and cone intersect: $z^2 =ax$, so then $y^2 = ax - x^2 = x(a-x)$.  Since $x > 0$, $a-x>0$, $a>x$\n\\[\n\\Longrightarrow y = \\pm \\sqrt{ x ( a-x)} = \\pm \\sqrt{ \\frac{-a^2}{4} + ax - x^2 + \\frac{a^2}{4} } = \\sqrt{ \\frac{a^2 }{4} - \\left( \\frac{a}{2} - x\\right)^2 }\n\\] \nNow $ 2z \\partial_x z = 2x$.  Then\n\\[\n\\left| \\begin{matrix} e_1 & e_2 & e_3 \\\\ 1 & 0 & \\frac{x}{z} \\\\ 0 & 1 & \\frac{y}{z} \\end{matrix} \\right| = ( \\frac{-x}{z}, \\frac{-y}{z}, 1 ) \\quad \\, \\Longrightarrow \\| \\partial_x r \\times \\partial_y r \\|^2 = \\frac{x^2}{z^2 } + \\frac{y^2}{z^2} + \\frac{z^2}{z^2} = 2 \n\\]\n\\[\n\\begin{aligned}\n  a(S) & = \\iint \\sqrt{2} dx dy = \\sqrt{2} \\int_0^1 \\int_{-\\sqrt{x(a-x)}}^{\\sqrt{ x(a-x)}} dy dx = 2 \\sqrt{2} \\int_0^a dx \\sqrt{ \\frac{a^2}{4} - \\left( \\frac{a}{2} - x \\right)^2 } = 2\\sqrt{2} \\int_{-a/2}^{a/2} \\sqrt{ \\frac{a^2}{4} - x^2 } = \\\\\n  & = a\\sqrt{2} \\int_{-a/2}^{a/2} \\sqrt{ 1 - \\left( \\frac{2x}{a} \\right)^2} \\xrightarrow{\\begin{aligned} u & = \\frac{2x}{a} \\\\ \\frac{a}{2} du & = dx \\end{aligned}} \\frac{a^2 \\sqrt{2}}{2} \\int_{-1}^1 \\sqrt{ 1 - u^2 } du \\\\ \n & \\xrightarrow{ \\begin{aligned} u & = \\sin{\\theta} \\\\ du & = \\cos{\\theta} d\\theta \\end{aligned}}  = \\frac{a^2\\sqrt{2}}{2} \\int_{-\\pi/2}^{\\pi/2} \\cos^2{\\theta} d\\theta = \\frac{a^2 \\sqrt{2}}{2} \\int_{-\\pi/2}^{\\pi/2} \\frac{ 1 + \\cos{2\\theta}}{2} = \\boxed{ \\frac{ \\sqrt{2} \\pi a^2}{4} }\n\\end{aligned}\n\\]\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n%\\begin{abstract}\n\n%\\end{abstract}\n%\t\\section*{\\sffamily \\textsc{}}{S: }\t\t% {\\scshape\t }\n\n\t%\t\\section*{\\sffamily \\textmd{}\t}\t% {\\mdseries }\n\n%\\begin{definition}\\label{D: }\n%\\begin{notation}\n%\\begin{theorem}\\label{T: }\n\n%\n%\tthebibliography\n%\tThere are fewer than 10 references in this article, so Latex will make room for single-digit numbering by providing the argument 9 to the bibliography environment; use 99 if the number of references is between 10 and 99.  \n%\n%\\begin{thebibliography}{9}\n%\t\\bibitem\n\t\n%\t\\bibitem\t\n\n%\\end{thebibliography}\n\n\\end{document} \n\n", "meta": {"hexsha": "27746cf44f7311e2f336694c3a731395cc30779f", "size": 507376, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "LaTeX_and_pdfs/Apostol_Solutions_Vol2.tex", "max_stars_repo_name": "wacfeldwang333/mathphysics", "max_stars_repo_head_hexsha": "59eb794dfa46e2b80e43df0440bb8ec3c472d973", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50, "max_stars_repo_stars_event_min_datetime": "2017-01-10T14:24:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:19:23.000Z", "max_issues_repo_path": "LaTeX_and_pdfs/Apostol_Solutions_Vol2.tex", "max_issues_repo_name": "wacfeldwang333/mathphysics", "max_issues_repo_head_hexsha": "59eb794dfa46e2b80e43df0440bb8ec3c472d973", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2017-09-29T09:29:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T03:12:29.000Z", "max_forks_repo_path": "LaTeX_and_pdfs/Apostol_Solutions_Vol2.tex", "max_forks_repo_name": "wacfeldwang333/mathphysics", "max_forks_repo_head_hexsha": "59eb794dfa46e2b80e43df0440bb8ec3c472d973", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25, "max_forks_repo_forks_event_min_datetime": "2018-01-21T05:33:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T20:15:13.000Z", "avg_line_length": 51.0746929736, "max_line_length": 915, "alphanum_fraction": 0.5248040901, "num_tokens": 237013, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.3340076908173147}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n% \\section*{Thu Oct 17 2019}\n\n% \\marginpar{Thursday \\\\ 2019-10-17, \\\\ compiled \\\\ \\today}\n\n\\section{Measuring distances} \\label{sec:measuring-distances}\n\nWe want to be able to compute the comoving radius, given our knowledge of the evolution of the distribution of energy density in time.\n\n% We will neglect spatial curvature. \nWe have shown that the luminosity distance is given by:\n%\n\\begin{equation}\n  d_L \\equiv \\sqrt{\\frac{L}{4 \\pi \\ell}}\n  = a_0 (1+z) r(z)\n\\,.\n\\end{equation}\n\nAlso recall \\emph{conformal time} \\(\\eta\\), which is defined by its relation to cosmic time, \\(a(\\eta ) \\dd{\\eta} = \\dd{t}\\): it allows us to write the FLRW metric as\n%\n\\begin{equation}\n  \\dd{s^2} = a^2(\\eta ) \\qty(c^2 \\dd{\\eta^2} - \\frac{\\dd{r^2} }{1 - k r^2} - r^2 \\dd{\\Omega^2} )\n\\,.\n\\end{equation}\n\nThis is very important when we talk about massless particles, with no intrinsic length scale: the photon, which is our primary tool for astrophysical observations, is one of them.\nThis can be written in terms of the variable \\(\\chi\\): \n%\n\\begin{equation}\n  \\dd{s^2}  = a^2(\\eta ) \\qty(c^2 \\dd{\\eta^2} - \\dd{\\chi^2} - f^2_k (\\chi ) \\dd{\\Omega^2})\n\\,,\n\\end{equation}\n%\nwhere \\(f_k(\\chi )=r\\) is equal to \\(\\sin(\\chi ) \\), \\(\\chi \\) or \\(\\sinh(\\chi )\\) if \\(k\\) is equal to \\(1\\), \\(0\\) or \\(-1\\); in other words we either have \\(\\chi = \\arcsin(r)\\), \\(\\chi = r\\) or \\(\\chi = \\operatorname{arcsinh}(r)\\).\n\nIf we look at photons moving radially we do not need to account for the angular part, and we find\n%\n\\begin{equation}\n  \\dd{s^2} = 0 = a^2(\\eta ) \\qty(c^2 \\dd{\\eta^2} - \\dd{\\chi^2})\n\\,,\n\\end{equation}\n%\ntherefore \\(c^2 \\dd{\\eta^2} = \\dd{\\chi^2}\\):  we get \\(c \\qty(\\eta (t_0 ) - \\eta (t_e)) = \\chi (r_e) - \\chi (r_0 )\\), where a subscript \\(e\\) means ``emission'', while a subscript \\(0\\) means detection. \nWe are choosing the negative sign when simplifying the square, since the problem we are considering is that of radiation starting from an astrophysical source and coming towards us: its radial coordinate \\(\\chi \\) decreases when the temporal coordinate \\(\\eta \\) increases. \n\nThis means that we can find out the comoving distance \\(\\Delta \\chi \\) between two events by calculating the difference between their comoving times \\(\\Delta \\eta \\).\nThis is what was meant by the fact that this expression of the metric is useful for massless particles: the scale factor gets factored out, we can write the expression in a very simple way.\n\n\\begin{equation}\n  \\dd{\\eta} = \\frac{\\dd{t} }{a}  = \\frac{\\dd{a} }{a \\dot{a} }\n\\,,\n\\end{equation}\n%\nand now recall \\((1+z) = a_0 / a\\): we differentiate this with respect to time to find\n%\n\\begin{equation}\n  \\dv{z}{t} = - \\frac{a_0 }{a^2} \\dot{a} = - \\frac{a_0 H(z)}{a}\n\\,,\n\\end{equation}\n%\n% \\begin{equation}\n%   \\frac{\\dd{a}}{a^2} = \\frac{\\dd{a} (1+z)^2}{a^2} = - \\frac{\\dd{z}}{ a_0 }\n% \\,,\n% \\end{equation}\n% %\n% which means \n% %\n% \\begin{equation}\n%   \\dd{e} = - \\frac{\\dd{z}}{a_0 H(z)}\n%   \\,.\n% \\end{equation}\nwhich means \n%\n\\begin{align}\n\\dd{\\eta } = \\frac{ \\dd{t}}{a} = - \\frac{ \\dd{z}}{a_0 H(z)}\n\\marginnote{Took the inverse of the equation, split the differentials, used the definition of \\(\\eta \\)}\n\\,,\n\\end{align}\n%\nso we get our final expression: \n%\n\\begin{align}\n\\dd{ \\chi  } = \\frac{c \\dd{z}}{a_0 H(z)} \\marginnote{Used the fact that \\(\\dd{\\chi } = - c \\dd{\\eta }\\).}[.2cm]\n\\,.\n\\end{align}\n\nSo, if we can find a way to parametrize the Hubble parameter \\(H(z)\\) in terms of the redshift we will be able to measure distances.\n% \\todo[inline]{??? probabily there is wrong stuff here}\n\nThe Hubble parameter is given by \n%\n\\begin{equation}\n  H^2= \\frac{8 \\pi G}{3} \\rho - \\frac{k c^2}{a^2}\n\\,,\n\\end{equation}\n%\nwhere the density comes from several components: \\(\\rho (t) = \\rho _r (t) + \\rho _m (t) + \\rho _\\Lambda \\), where the first term is the density of radiation and scales like \\(a^{-4}\\), the second is the density of matter and scales like \\(a^{-3}\\), the third is the density of dark energy and is constant.\n\nIn terms of the redshift, they scale like \\((1+z)^{4}\\), \\((1+z)^{3}\\) (and \\((1+z)^{0}\\)) respectively.\n\nWe express the Hubble parameter as a multiple of its value now: \\(H(z) = H_0 E(z)\\), where \\(E(z)\\) is a dimensionless function.\n\nRecall the definition of \\(\\Omega (t)\\): it describes the ratio of the density of a certain type of fluid to the critical density. We can look at the \\(\\Omega_i (t)\\) for \\(i\\) corresponding to matter, radiation and so on: \n%\n\\begin{equation}\n  \\Omega _i (z) = \\frac{8 \\pi G \\rho _i (z)}{3 H^2(z)}\n  = \\frac{8 \\pi G \\rho_{i}(z=0)}{3 H_0 ^2} \\times  \\frac{\\rho _i (z) / \\rho_{i}(z=0)}{E^2(z)}\n  = \\Omega _{i,0} \\frac{(1+z)^{\\alpha }}{E^2(z)}\n\\,,\n\\end{equation}\n\nwhere \\(\\alpha \\) is the exponent of the scaling of the fluid: \\(\\alpha = 4\\) for radiation, \\(\\alpha = 3\\) for matter, \\(\\alpha = 0\\) for the cosmological constant \\(\\Lambda \\), while for spatial curvature \\(\\alpha = 2\\).\n\nFor the \\(\\Omega \\) corresponding to the curvature we define: \\(\\Omega _k = - k c^2/(a^2 H^2)\\) (see equation \\eqref{eq:spatial-curvature-effective-density}).\n\nWe must have \n%\n\\begin{equation}\n  1 = \\Omega _r + \\Omega _m + \\Omega _\\Lambda + \\Omega _k\n\\,.\n\\end{equation}\n\nWe can write an expression for \\(E^2(z)\\) by taking the ratio of the densities at emission versus now:\n%\n\\begin{equation}\n  E^2(z) = \\frac{H^2}{H_0^2} = \n  \\Omega _{\\Lambda , 0} +  \\Omega_{m, 0} (1+z)^{3} \n  +\\Omega_{r, 0} (1+z)^4 + \\Omega _{k, 0} (1+z)^2\n\\,,\n\\end{equation}\n%\nand to get \\(E\\) we just take the square root.\n\nNow we can finally compute our integral \n%\n\\begin{equation}\n  \\chi (z) = \\frac{c}{a_0 H_0 } \\int_{0}^{z} \\frac{\\dd{z'} }{E(z')}\n\\,,\n\\end{equation}\n%\n\ntherefore \n%\n\\begin{equation}\n  r = f_k \\qty(\\frac{c}{a_0 H_0 } \\int_0^z \\frac{\\dd{z'}   }{E(z')})\n\\,.\n\\end{equation}\n%\n\nThis does depend on \\(k\\), but the differences between positive and negative curvature are only relevant starting from third order: regardless of the curvature, \\(f_k\\) is close to the identity for small \\(z\\).\nIf the curvature is zero, we get the comoving distance:\n%\n\\begin{align}\nd_C = r a_0 = \\frac{c}{H_0 } \\int_{0}^{z} \\frac{ \\dd{z'}}{E(z')}\n\\,.\n\\end{align}\n\nIf the curvature is not zero, we can still define a useful distance: the \\emph{transverse comoving distance}, \n%\n\\begin{align}\nd_M = a_0 r = a_0 f_k \\qty(\\frac{c}{a_0 H_0 } \\int_0^z \\frac{\\dd{z'}   }{E(z')})\n\\,;\n\\end{align}\n%\nfor \\(k=0\\) these two coincide.\n\n% \\todo[inline]{Right? I didn't write this down but it seems natural.}\n\n% Two weeks ago we defined the luminosity distance: now we can compute it.\n\nNow,  suppose we are looking at a certain far-away object with angular size \\(\\Delta \\theta \\) and linear size \\emph{at emission} of \\(\\Delta x\\): then the \\emph{angular diameter distance} is given, in the small-angle approximation, by\n%\n\\begin{equation}\nd_A = \\frac{ \\Delta x}{\\Delta \\theta } = a(t_e) r\n= \\frac{a_0 r_z}{1+z} = \\frac{d_M}{1+z}\n\\,.\n\\end{equation}\n\nSince the luminosity distance is given by \n%\n\\begin{equation}\n d_L = a_0 (1+z) r = d_M (1+z)\n\\,\n\\end{equation}\n%\ntheir ratio is  \n%\n\\begin{equation}\n  \\frac{d_L}{d_A} = (1+z)^2\n\\,.\n\\end{equation}\n\n% \\todo[inline]{This part is kind of confused, I think the concepts are well explained but there is some reorganization to do.}\n\n% \\todo[inline]{Add summary of cosmological distances, with explanation of their physical meaning, drawing from \\cite{hoggDistanceMeasuresCosmology2000} and \\cite{davisExpandingConfusionCommon2004}.}\n\n\\begin{figure}\n\\begin{tabular}{p{2.5cm}p{5cm}p{7cm}}\nDistance name & Formula & Description\\\\\n\\hline\nComoving \\newline distance  & \\(d_C = r a_0\\) \\newline \\( = \\frac{c}{H_0 }\\int_{0}^{z} \\frac{ \\dd{z'}}{E(z')}\\) & Distance in comoving coordinates multiplied by the current scale factor: if the expansion of the universe froze during our measurement, this is the distance we would measure between the two events. Assumes \\(k=0\\). \\\\ \\hline\nTransverse \\newline comoving \\newline  distance  & \\(d_M = r a_0\\) \\newline \\( = a_0 f_k \\qty(\\frac{c}{H_0 a_0  }\\int_{0}^{z} \\frac{ \\dd{z'}}{E(z')})\\) & Generalization of the comoving distance to \\(k \\neq 0\\). \\\\ \\hline\nLuminosity \\newline  distance  & \\(d_L = d_M (1+z)\\)\n\\newline \\(= \\sqrt{L / (4 \\pi \\ell)}\\) & Distance defined so that the radiative intensity we measure follows the inverse square law. \\\\ \\hline\nAngular \\newline diameter \\newline  distance  & \\(d_A = d_M (1+z)^{-1}\\)\n\\newline \\(= \\Delta x / \\Delta \\theta \\) & Distance defined by the ratio of a far-away object's size (measured using the scale factor at the time of the emission of the radiation we observe now) to its angular size.\n\\end{tabular}\n\\label{tab:cosmological-distances}\n\\caption{A summary of the cosmological distances we defined, drawing on the summary by Hogg \\cite[]{hoggDistanceMeasuresCosmology2000}.}\n\\end{figure}\n\n\\section{The cosmological constant} \\label{sec:cosmological-constant}\n\nEinstein thought that the universe had to be static: it was a common notion at the time that it should be, almost a philosophical principle.\\footnote{An interesting historical fact: this was corroborated by a calculation error on Einstein's part, which was later pointed out by Friedmann. Einstein thought \\cite{einsteinCommentFriedmannPaper1922} that \\(\\nabla_{\\mu } T^{\\mu \\nu }= 0\\) implied \\(\\partial_{t} \\rho =0\\), while Friedmann pointed out \\cite{friedmannAlexanderFriedmann1922} that the correct equation reads \\( \\partial_{t} \\qty(\\sqrt{-g} \\rho ) =0\\): the density of the universe is not forced to be time independent if the determinant of the metric changes accordingly. Even the best make mistakes.}\nNow we know that the universe is neither static nor stationary.\\footnote{The distinction between static and stationary is subtle but significant \\cite{ludvigsenGeneralRelativityGeometric1999}: \\emph{stationarity} is about the existence of a timelike Killing vector, while \\emph{staticity} is about the timelike Killing vector being orthogonal to spacelike submanifolds. \nA concrete example: Schwarzschild geometry is both static and stationary, Kerr geometry is stationary but not static, FLRW geometry is neither, since there is no timelike Killing vector field.}\n\nSo, he sought static solutions (\\(a = \\const\\)) for matter (\\(P=0\\)) to the Friedmann equations \\eqref{eq:friedmann-equations}: if we set \\(\\dot{a} = \\ddot{a} = 0\\) \nthe third equation becomes \\(\\dot{\\rho}= 0\\), the second equation gives us \\(\\rho \\equiv 0\\), and from the first we must also have \\(k=0\\): the only way to have a static matter-filled universe is for the density of matter to be zero, and for the spatial curvature to be also zero.\n\nIn order to satisfy what he thought was an empirical fact, Einstein modified his equations in order to get a static non-empty solution.\n\nThe Einstein equations, from which the Friedmann ones are derived, read \n%\n\\begin{equation}\n  G_{\\mu \\nu } = 8 \\pi G T_{\\mu \\nu }\n\\,,\n\\end{equation}\n%\nwhen \\(c=1\\), where the Einstein tensor \\(G_{\\mu \\nu }\\) can be defined in terms of the Ricci curvature tensor \\(R_{\\mu \\nu }\\) and the scalar curvature \\(R\\) as:\n%\n\\begin{equation}\n  G_{ \\mu \\nu } = R_{\\mu \\nu } - \\frac{1}{2} g_{\\mu \\nu }R\n\\,.\n\\end{equation}\n\nThis peculiar construction is the only one which can be made in terms of the curvature tensor and which is covariantly constant: \\(\\nabla_{\\mu } G^{\\mu \\nu } = 0\\). \nThis is a necessary condition since \\(\\nabla_{\\mu } T^{\\mu \\nu }=0\\): the Einstein equations state that they are proportional, so if we take the covariant derivative of the equations we must get the identity \\(0=0\\).\n% \\footnote{This is the historical approach; nowadays it is more common for people to start by assuming that the Einstein equations hold; to derive the law \\(\\nabla_\\mu T^{\\mu \\nu } = 0\\) from there. }\n\n% \\begin{bluebox}\n% Here, \\(R = g^{\\mu \\nu } R_{\\mu \\nu }\\) is the scalar curvature, while \\(R_{\\mu \\nu } = R^{\\rho }_{\\mu \\rho \\nu }\\) is the Ricci tensor, and finally \\(R^{\\mu }_{\\nu \\rho \\sigma }\\) is the Riemann tensor, defined in terms of the affine connection \\(\\Gamma^{\\mu }_{\\nu \\rho }\\) as \n% %\n% \\begin{align}\n% R^{\\mu }_{\\nu \\rho \\sigma } = -2 \\qty(\\Gamma^{\\mu }_{\\nu [\\rho , \\sigma ]} + \\Gamma^{\\alpha }_{\\nu [\\rho } \\Gamma^{\\mu }_{\\sigma ] \\alpha })\n% \\,,\n% \\end{align}\n% %\n% where commas denote coordinate differentiation. The connection \\(\\Gamma^{ \\mu }_{\\nu \\rho } \\) \n% \\end{bluebox}\n\nEinstein added a term \\(- \\Lambda g_{\\mu \\nu }\\) to the LHS of the Einstein equations, with \\(\\Lambda \\) a constant scalar. This is allowed since \n\n\\begin{enumerate}\n  \\item it is tensorial (since it is a scalar multiple of the metric, which is a tensor);\n  \\item it is symmetric;\n  \\item it has zero covariant divergence, since \\(\\Lambda \\) is constant and the metric is covariantly constant \\(\\nabla_{\\mu } g^{\\mu \\nu } = 0\\).\n\\end{enumerate}\n\nThen, we can rewrite the EE in two equivalent ways: either \n%\n\\begin{align}\n\\widetilde{G}_{\\mu \\nu } &= 8 \\pi G T_{\\mu \\nu } &\\text{with}&& \\widetilde{G}_{\\mu \\nu } &= G_{\\mu \\nu } - \\Lambda g_{\\mu \\nu }  \\\\\nG_{\\mu \\nu } &= 8\\pi G \\widetilde{T}_{\\mu \\nu } &\\text{with}&& \n\\widetilde{T}_{\\mu \\nu } &= T_{\\mu \\nu } + \\frac{\\Lambda g_{\\mu \\nu }}{8 \\pi G} \n\\,.\n\\end{align}\n%\n\nIn the first interpretation, the cosmological constant is an intrinsic geometric property of spacetime; in the second interpretation cosmological constant is a particular kind of fluid, with the property of its contribution to the stress-energy tensor always being a constant multiple of the metric. \n\nIn order to find out what the properties of this fluid are, we compare its stress-energy tensor to a generic ideal fluid tensor: \n%\n\\begin{equation}\nT_{\\mu \\nu }^{\\text{(generic)}} = \\left[\\begin{array}{cccc}\n\\rho & 0 & 0 & 0 \\\\ \n0 & P & 0 & 0 \\\\ \n0 & 0 & P & 0 \\\\ \n0 & 0 & 0 & P\n\\end{array}\\right]\n\\qquad \\qquad\nT^{(\\Lambda )}_{\\mu \\nu } = \\frac{\\Lambda g_{\\mu \\nu }}{8 \\pi G} = \\frac{\\Lambda}{8 \\pi G} \\left[\\begin{array}{cccc}\n1 & 0 & 0 & 0 \\\\ \n0 & -1 & 0 & 0 \\\\ \n0 & 0 & -1 & 0 \\\\ \n0 & 0 & 0 & -1\n\\end{array}\\right]\n\\,,\n\\end{equation}\n%\nso the corrections to the stress energy tensor must be \\(\\rho \\rightarrow \\rho + \\Lambda/ 8 \\pi G \\) and \\(P \\rightarrow P - \\Lambda  / 8 \\pi G\\), or, in other words, the density and pressure of the ``cosmological constant fluid'' are \\(\\rho_{\\Lambda } = - P_{\\Lambda } = \\Lambda/8\\pi G\\).\nThis proves that the equation of state of the cosmological constant is \\(w = -1\\).\n\nInserting this into the Friedmann equations we get: \n%\n\\begin{align}\n  \\qty(\\frac{\\dot{a} }{a})^2 &= \n  \\frac{8 \\pi G}{3} \\rho + \\frac{\\Lambda }{3}\n  - \\frac{k}{a^2} \\label{eq:friedmann-1-cosmological-constant}\\\\\n  \\frac{\\ddot{a}}{a}  &= - \\frac{4 \\pi G}{3} \\rho + \\Lambda \\label{eq:friedmann-2-cosmological-constant}\\\\\n \\dot{\\rho} &= -3 \\frac{\\dot{a}}{a }\\qty(\\widetilde{\\rho} + \\widetilde{P}) = -3 \\frac{\\dot{a}}{a} \\qty(\\rho + P)\\label{eq:friedmann-3-cosmological-constant}\n\\,,\n\\end{align}\n%\nand we can see that in the third equation, the effect of the source is encompassed in a term \\(\\widetilde{\\rho }  + \\widetilde{P} \\): the two \\(\\Lambda \\) terms cancel, since they are opposite.\nFor a cosmological constant-dominated universe --- that is, for a universe in which the only fluid behaves like the cosmological constant -- we have \\(\\dot{\\rho} = \\dot{P} = 0\\). \n\nSo, proceeding with the derivation by Einstein, we set \\(\\dot{a}= \\ddot{a} =0 \\): for the first Friedmann equation we get \n%\n\\begin{equation}\n  \\frac{8 \\pi G}{3} \\rho + \\frac{\\Lambda}{3} = \\frac{k}{a^2}\n\\,,\n\\end{equation}\n%\nand for the second: \n%\n\\begin{equation}\n  4 \\pi G \\rho = \\Lambda \n\\,.\n\\end{equation}\n\nSo, we substitute the expression for \\(4 \\pi G \\rho \\) into the first Friedmann equation: \n%\n\\begin{equation}\n  \\frac{2}{3} \\qty(4 \\pi G \\rho ) + \\frac{\\Lambda}{3} =\n  \\Lambda \\qty(\\frac{1}{3}+ \\frac{2}{3}) = \\Lambda = \\frac{k}{a^2}\n\\,.\n\\end{equation}\n\nWhat are the physical conclusions to draw? \nSince we want matter in the universe we must have \\(\\rho >0\\), which implies \\(\\Lambda >0\\), which implies \\(k =1\\): so the universe must be closed. \n\nFriedmann studied perturbations around this solution and found it to be unstable: so, it is not suitable as a description of the universe.\nThis, combined with the observations by Hubble of an expanding universe, prompted the scientific community to discard the idea of a stationary universe in favor of an expanding one.\n\nEinstein probably \\cite{autInvestigatingLegendEinstein2018} called the introduction of the cosmological constant into the equation his ``greatest blunder''; however in modern cosmology the idea of a cosmological constant has gained new vigor: we observe the universe's expansion to be accelerated, that is \\(\\ddot{a} > 0\\), and the only way for this to be the case if \\(\\rho >0\\) is if \\(\\Lambda > 0\\) as well. \nIt is the only kind of fluid which has a repulsive gravitational effect.\n\nAs opposed to the approach by Einstein, in which the cosmological constant was inserted to stationarize the universe, we make it a measurable parameter of our theory.\n\nA candidate for the cosmological constant term, which is a kind of intrinsic energy of space, is the vacuum energy in Quantum Field Theory: however, the estimate we get when trying to make this quantitative is around \\num{e120} times the measured value of \\(\\Lambda \\).\n\n% The next topic is a solution of the Friedmann equations.\n% We will try to do it with \\(p=0\\): \\(\\rho \\propto a^{-3}\\).\n\n\\end{document}\n", "meta": {"hexsha": "8af984ec543585fff8897327ce8a2d3877d55fdc", "size": 17388, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ap_first_semester/astrophysics_cosmology/17oct.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "ap_first_semester/astrophysics_cosmology/17oct.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ap_first_semester/astrophysics_cosmology/17oct.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 49.8223495702, "max_line_length": 711, "alphanum_fraction": 0.6772486772, "num_tokens": 5598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.3339086035868219}}
{"text": "%\n%  set up at April 4th, 2009\n%\n%\n%\n\\chapter{Second Quantization Methods}\n%\n%\n%\nThe second Quantization methods is one of the powerful tools used in\nrelativistic quantum theory and quantum field theory, where the\nphysical problems that actually involves creation or destruction of\nparticles, photons, etc. In a majority of the applications of the\nsecond quantization techniques to quantum-chemical problems, no\nelectrons or other particles are created or destroyed. Thus, this\nmethod usually serve merely as a convenient and operationally useful\napproach. However, this methods deeply simplifies the discussion about \nthe system involving many identical interacting particles; e.g., the electrons\nin the molecules.\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{General Discussion}\n%\n%\n%\nNow let's define some operator which is called ``creation operator'':\n$\\hat{r}^{+}$. This operator is used to generate an electron which is on orbital\nof $\\varphi_{r}$. Here we note that compared with traditional notion which\nrequires the label of electron, the creation operator does not need it anymore.\nHence we can generally express the Slater determinant of $\\Phi$ as:\n\\begin{equation}\n \\label{second_quantization_general_discussion:1}\n\\Phi = \\frac{1}{\\sqrt[2]{n!}} \\left | \\begin{array}{cccc}\n  \\varphi_{1}(1) & \\varphi_{2}(1) & \\cdots & \\varphi_{n}(1) \\\\\n  \\varphi_{1}(2) & \\varphi_{2}(2) & \\cdots & \\varphi_{n}(2) \\\\\n  \\cdots & \\cdots & \\cdots & \\cdots                        \\\\\n  \\varphi_{1}(n) & \\varphi_{2}(n) & \\cdots & \\varphi_{n}(n)\n\\end{array} \\right | =\n\\hat{n}^{+}\\cdots\\hat{3}^{+}\\hat{2}^{+}\\hat{1}^{+}\\ket{vac}\n\\end{equation}\nAgain we follow the convention that to use a, b, c etc. to designate the virtual\norbitals, the i, j, k etc. to refer to the occupied orbitals; and p,\nq, r etc. to specify the general orbitals. What's more, we note that\n$\\hat{2}^{+}\\hat{1}^{+}\\ket{vac}$ denotes that firstly to generate an electron\nin the $\\varphi_{1}$, then to generate another electron in $\\varphi_{2}$. \n\nCompared with the traditional Slater determinant expression in\n(\\ref{second_quantization_general_discussion:1}), the most important thing is\nthat the Slater determinant satisfies the Pauli principle that if we exchange\ntwo electrons in the wave function, then the wave function should change its\nsign. Hence how can we express it in the second quantization?\n\nFor the creation operator, it generally follows the rule that:\n\\begin{equation}\n  \\label{second_quantization_general_discussion:2}\n\\hat{r}^{+}\\hat{s}^{+} + \\hat{s}^{+}\\hat{r}^{+} = [\\hat{r}^{+}\\hat{s}^{+}]_{+}\n= 0\n\\end{equation}\nWe note that it gives the Pauli principle. Let's generally consider some wave\nfunction in second quantization: $\\Phi\n=\\hat{r}^{+}\\cdots\\hat{s}^{+}\\hat{t}^{+}\\hat{u}^{+}\\ket{vac}$, \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n\n%%% Local Variables: \n%%% mode: latex\n%%% TeX-master: \"../../main\"\n%%% End: \n", "meta": {"hexsha": "5f8aa3b76987ef79b81979dab20d08a39ac9af4e", "size": 2930, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "theory/chemistry/second.tex", "max_stars_repo_name": "murfreesboro/fenglai-note", "max_stars_repo_head_hexsha": "7bdf943f681e54948cd68775a31e4c93a53a13f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-16T07:23:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T07:23:48.000Z", "max_issues_repo_path": "theory/chemistry/second.tex", "max_issues_repo_name": "murfreesboro/fenglai-note", "max_issues_repo_head_hexsha": "7bdf943f681e54948cd68775a31e4c93a53a13f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "theory/chemistry/second.tex", "max_forks_repo_name": "murfreesboro/fenglai-note", "max_forks_repo_head_hexsha": "7bdf943f681e54948cd68775a31e4c93a53a13f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5945945946, "max_line_length": 80, "alphanum_fraction": 0.6883959044, "num_tokens": 815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3335470282764615}}
{"text": "\\chapter{State of the Art}\n\nIn this section, the background to the state of the art in machine learning and recommendation systems will be presented.\nIn particular, the use of machine learning algorithms as the content filtering component of recommendation systems will be discussed.\nThe different approaches to machine learning and recommendation systems will also be introduced and then discussed in detail.\n\n\\section{Background}\nIn 1947, Alan Turing presented a lecture to the London Mathematical Society in which he theorised that it would be possible for a machine to learn from it's experiences.\nIn Turing's example, he proposed that learning was a prerequisite for a true intelligent system \\cite{Turing1946}.\nTuring further expanded on the concept of an intelligent machine in his 1950 paper in which he proposed a theoretical test, called the \"imitation game\", to identify whether machines could be considered intelligent \\cite{Turing1950}.\nThis test has since become known as the Turing test.\n\nMachine learning and recommendation systems can be viewed as semi-intelligent machines which try to learn from data fed into them\\cite{mlTutorial}.\nThese machines are replacements for human operators who would have had to classify data or suggest recommendations in the past.\nOne of the main reasons machines are used, instead of humans for this task is largely due to the volume of data available\\cite{lops}.\nAnother factor to consider is the quality of results obtained from the system.\nHumans, for example, can possibly be biased in their opinion when presenting their results or findings.\nA machine on the other hand should generate it's results using the model it has created using only the data that has been presented to it.\nThis approach is less likely to be skewed by a bias when the model has been created using a balanced dataset\\cite{FProvost2000}.\n\n\\section{Machine Learning}\nMachine learning is an interdisciplinary field concerned with the study of self learning systems.\nMachine learning has applications in fields such as: statistics, mathematics, computer vision, game theory, information retrieval, software engineering, sentiment analysis, and artificial intelligence\\cite{mlTutorial}.\n\nMachine learning algorithms try to build a model of a dataset by learning the patterns in the data.\nThe resulting model created by many machine learning algorithms can then output seemingly intelligent results for data that it has never seen before.\n\nMachine learning can be split into three different types of learning:\n\\begin{itemize}\n    \\item Supervised learning\n    \\item Reinforced learning\n    \\item Unsupervised learning\n\\end{itemize}\n\n\\subsection{Supervised learning}\nSupervised learning is a machine learning technique which tries to create a model which maps inputs to desired outputs.\nThis can be represented as a function f(x) which maps an input \\(x_i\\) to an output \\(y_i\\).\nThis is achieved by using a training set T = \\((x_i, y_i)\\) and a learning algorithm.\nThe learning algorithm produces a function \\(\\hat{f}(x_i)\\) which can then be modified in response to the difference between \\(y_i - \\hat{f}(x_i)\\)\\cite{mlTutorial}.\n\n\\subsection{Reinforced learning}\nReinforced learning is a machine learning technique where the machine interacts with an environment and produces actions \\(a_i\\).\nThis set of actions interact with the environment which in turn results in the machine receiving rewards \\(r_i\\) from a rewards function.\nThe machine tries to learn how to create actions which maximizes the future return on rewards\\cite{mlTutorial}.\n\n\\subsection{Unsupervised learning}\nUnsupervised learning is a machine learning technique which tries to find hidden patterns in data.\nAn unsupervised learning algorithm receives inputs \\(x_i\\) but receives no desired outputs nor rewards.\nThe machine tries to build a probabilistic model of the data or it uses clustering to partition the data in categories\\cite{mlTutorial}.\n\nThe main difference between unsupervised techniques and other techniques is the lack of a clear measure of success.\nThis poses a problem when comparing the accuracy of different unsupervised techniques.\nThe effectiveness of unsupervised techniques therefore relies heavily on heuristic approaches when judging their quality\\cite{elementsStat}.\n\nThe research conducted in this project is focused on the unsupervised approach to machine learning.\nDue to the fact that there is no gold standard to compare the quality of the similarity results, their effectiveness will be a matter of opinion.\nWhere possible the results will also be compared against any possible meta-data to help judge their effectiveness.\n\n\\section{Recomendation Systems}\nRecommendation systems are algorithms and techniques which try to generate recommendations for users.\nThe design of recommendation systems is an interdisciplinary field which touches upon information retrieval, human computer interaction, machine learning, data mining, etc.\nThese systems often try to generate recommendations based on similarities between users or between content.\nThere are two main approaches used in recommendation systems\\cite{recHandbookIntro}:\n\n\\begin{itemize}\n    \\item Collaborative-filtering\n    \\item Content-filtering\n\\end{itemize}\n\n\\subsection{Collaborative-filtering}\nCollaborative-filtering is an approach used by recommendation systems which tries to generate recommendations by comparing user data with other users.\nThe rationale behind this approach is to find similarities and differences  between different groups of users and build a user model.\nOnce users have been grouped together, recommendations can be generated based on what similar users have liked and disliked.\nThis type of recommendation system has been used extensively by Amazon when generating recommendations\\cite{recHandbookIntro}.\n\nThe main problem with this approach is that it requires a huge amount of initial data in order to generate appropriate recommendations.\n\n\\subsection{Content-filtering}\nContent-filtering is an approach used by recommendation systems which learns to generate recommendations based on a users previous interactions with an item.\nThis approach tries to learn the features of items in order to generate recommendations for items with similar features\\cite{recHandbookIntro}.\n\nUnlike collaborative-filtering a huge amount of user data is not required for content-filtering.\nThe recommendations for this approach can be generated by building a model using the individual item features.\n\nThe research conducted in this project is focused entirely on the information filtering component of a content-filtering recommendation system.\nThe research project conducted was based on a potential user being a student.\nHowever all of the algorithms investigated could be used in content-filtering recommendation systems to filter recommendations based on the content of the items.\n\n\\section{State of the Art}\nThis research project is investigating the performance of Latent Dirichlet Allocation (LDA), k-Nearest-Neighbour (k-NN) and Word2Vec as the content-filtering component of a recommendation system.\nEach of these algorithms have applications in information retrieval and are not just confined to the field of recommendations systems nor to an educational corpus.\n\n\\subsection{Latent Dirichlet Allocation}\nLDA is a probabilistic model for any discrete data. In this research project and in most of the literature reviewed, textual data has been used.\nLDA was introduced in 2004 by Blei, Ng and Jordan as an improvement on Deerwester's Latent Semantic Indexing (LSI) and on Hofmann's later Probabilistic Latent Semantic Indexing (pLSI).\nLDA was created in response to two problems identified with pLSI; the number of parameters in the model grew linearly with the size of the corpus, and it was unclear as to how to assign a probability to a document that the model had never seen before\\cite{LDAintro}.\n\nLDA is hierarchical model which assumes that documents contain a mixture of topics and that topics are a mixture of word probabilities.\nLDA is also a bag-of-words (bow) model which assumes that the topics are generated first and then documents are generated from these topics.\nThese assumptions are used when inferring topics as it is a reversing of the generation process\\cite{LDAintro}.\n\nLDA has been used in the past on a corpus of 17,000 articles from the magazine Science, with 100 topics.\nThe LDA model that was generated using this corpus was fed an unseen article on genome mapping and sequencing.\nThe distribution of topics in the article were then calculated and graphed.\nIt was found that the topics which seemed to be about; genetics, evolution, disease, and computers had a high concentration in the article\\cite{ACMTopicModel}.\n\nIn a similar study to the above, LDA was applied to 21,434 articles from Science to create 50 topics.\nThe purpose of this experiment was to infer the most relevant topics from a document and then to find the most similar documents.\nAn article on Statistical Significance in Protein and DNA sequencing was used to generate recommendations for articles related to protein sequencing, genome sequencing and sampling strategies.\n\nThis research project used the LDA implementation from the Gensim Python library.\nGensim is a library which was originally created in 2008 to find similar articles in the Czech Digital Mathematics Library.\nGensim was chosen as it allows the creation of an LDA model which is memory independent of the size of the input corpus.\nAs the original intention for Gensim was to generate recommendations for academic articles, this influenced the choice of the library.\\cite{rehurek_lrec}\n\n\n\\subsection{k-Nearest-Neighbours}\nk-Nearest-Neighbours is a model free algorithm for classification and pattern recognition.\nIn k-Nearest-Neighbour classifiers when given a query point \\textit{x}, the \\textit{k} nearest points in distance to \\textit{x} are used to classify \\textit{x}.\nWhen \\textit{k} is 1, the query point \\textit{x} is classified as being the same as the point nearest to it.\nWhen \\textit{k} is a value greater than 1 a simple majority vote of the \\textit{k} nearest points can be used to classify \\textit{x}.\\cite{elementsStat}\n\nWhen k-Nearest-Neighbours is applied to high-dimensional feature space, the distance between the k-nearest-neighbours can be quite high, causing bias and a degradation of performance.\\cite{elementsStat}\nAn approach to try and overcome the distance problem is to weight each of the k nearest neighbours vote based on their distance to the query point \\textit{x}.\\cite{top10datamining}\n\nDespite the simplicity of the approach used by k-NN it has been featured as one of the top algorithms to use in data-mining.\\cite{top10datamining}\nFor this research project k-NN was not used to classify documents into predefined classes.\nInstead k-NN was used to find the k-nearest documents to a query document.\nThis clustering of documents is based on the assumption that the k-nearest documents in feature space will be similar to the query document.\n\n\\subsection{Word2Vec}\nWord2Vec is an algorithm introduced in 2013 by Mikolov which uses a simple neural network to learn continuous vector representations of words.\nThese vector representations of words can be used to describe the similarity between words.\nWords which are spatially close in this representation can described as being semantically close, while words which are spatially distant can be described as being semantically different.\nWe also have the benefit of being able to apply algebraic operations to these  word vectors.\nThis was shown intuitively by Mikolov as: \\textit{King - Man + Woman” = Queen} and by \\textit{Madrid - Spain + France = Paris}.\n\nBy training the word vectors using a neural network we are able to learn the multiple degrees of similarity between words\\cite{Mikolov1}.\nThe result is a vector representation which can encode linguistic patterns and regularities.\\cite{Mikolov2}\nA small problem with Mikolov's original word2vec paper was that the algorithm created a word based model.\nThe algorithm was later extended by Mikolov to allow word and phrase based models.\\cite{Mikolov2}\n\nThe research project conducted used the word2vec implementation from the Gensim Python library.\nThe Gensim library contains a word2vec and a doc2vec implementation. The word2vec implementation follows Mikolov's original word base model while the doc2vec implementation is based on Mikolov's later phrase base model.\\cite{radimDoc2Vec}\nThe later doc2vec implementation is the one which is being investigated by this project.\n\n\n\\section{Conclusion}\nThe field of machine learning and recommendation systems is vast and the number of techniques and approaches which could be used is equally as vast.\nFrom the research conducted the scope of this project has been narrowed down to focus on the performance of three relevant algorithms: LDA, k-NN, and word2vec.\nThese three algorithms are quite different in their implementations and have different applications outside the scope of this project.\nIt is hoped that by focusing the research on these algorithms, it will be possible to successfully analyse the performance of some of the best algorithms, to use for the content-filtering component of a recommendation system.\n", "meta": {"hexsha": "eee1e74670a559dcc8684dcbb99d2493839066ca", "size": 13288, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/Latex/Chapters/Chapter2.tex", "max_stars_repo_name": "PinPinIre/Final-Year-Project-Report", "max_stars_repo_head_hexsha": "b4b661d4381a74c7f81e07d1e13d5b4970d60d94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Latex/Chapters/Chapter2.tex", "max_issues_repo_name": "PinPinIre/Final-Year-Project-Report", "max_issues_repo_head_hexsha": "b4b661d4381a74c7f81e07d1e13d5b4970d60d94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-03-27T23:16:53.000Z", "max_issues_repo_issues_event_max_datetime": "2015-03-27T23:16:53.000Z", "max_forks_repo_path": "src/Latex/Chapters/Chapter2.tex", "max_forks_repo_name": "PinPinIre/Final-Year-Project-Report", "max_forks_repo_head_hexsha": "b4b661d4381a74c7f81e07d1e13d5b4970d60d94", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 86.8496732026, "max_line_length": 266, "alphanum_fraction": 0.8175045154, "num_tokens": 2686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499943, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.33354702155516663}}
{"text": "\\documentclass[12pt]{article}\n\n\\usepackage{SteveStyle}\n\n\n\\begin{document}\n\n\n \n%\\renewcommand{\\qedsymbol}{\\filledbox}\n%Good resources for looking up how to do stuff:\n%Binary operators: http://www.access2science.com/latex/Binary.html\n%General help: http://en.wikibooks.org/wiki/LaTeX/Mathematics\n%Or just google stuff\n \n\\title{\\texttt{Math 470}}\n\\author{Stephen Fay}\n\\date{May 1st - August 31st}\n\\maketitle\n\n\n\\begin{abstract}\nIn this project we explore geometric properties of numerical integrators applied to Hamiltonian ordinary differential equations; we study the n-body problem, chosen for it's wealth of symmetries and chaotic behavior. We combine symplectic numerical schemes \\cite{Numerical} with projections onto invariant manifolds, which we obtain with well known symmetry methods for dimensionality reduction \\cite{Symmetry-methods}. Using backward error analysis we show that the projections violate symplecticity; postulating that projection methods may give rise to an attractor - a subset of the preserved manifold, we investigate the Lyapunov spectrum of our modified equations but find evidence that for $n\\geq 3$ the projection methods make the equations \\textit{more} chaotic. \n\\end{abstract}\n\n\\tableofcontents\n\n\\section{Lie Symmetries for Solving DEs}\n\n\\subsection{Preliminaries.}\n\nThis section draws largely from \\cite{R-Steinhour},\\cite{Symmetry-methods}.\\\\ We start by considering first order differential equations of the form\n\\begin{equation}\\label{eq:first order equation}\n    \\frac{dy}{dx} = \\omega(x,y)\\qquad,\\quad \\R \\supset D \\to \\R\n\\end{equation}\n\nA \\tbf{symmetry} of an ode \\eqref{eq:first order equation} is a diffeomorphism $\\Gamma : \\R^2\\to\\R^2$ with $(x,y)\\mapsto (\\hat x,\\hat y)$ such that the differential equation is preserved.\n\n$$\\frac{d\\hat y}{d\\hat x} = \\omega(\\hat x,\\hat y)$$\n\nwe can simplify the above equation to obtain\\\\ \\textit{The \\tbf{symmetry condition}} \\eqref{eq:the symmetry condition}. We derive a formula by taking the total derivative with respect to $x$, the quotient \n\n\\begin{equation}\\label{eq:the symmetry condition}\n    \\frac{d\\hat y}{d\\hat x} = \\frac{dx \\partial_x \\hat y + dy \\partial_y\\hat y}{dx \\partial_x \\hat x + dy\\partial_y \\hat y} = \\frac{D_x \\hat y}{D_x \\hat x} = \\frac{\\partial_x \\hat y + \\frac{dy}{dx}\\partial_y\\hat y}{\\partial_x \\hat x + \\frac{dy}{dx}\\partial_y\\hat x} = \\omega(\\hat x,\\hat y)\n\\end{equation}\n\nIt is clear that the set of symmetries $\\{\\Gamma : \\R^2\\to\\R^2 | \\eqref{eq:the symmetry condition}\\,\\,\\text{holds} \\}$ is closed under composition and inverses, and thus forms a group. Lie groups are continuous groups which are also smooth manifolds. An \\textit{invariant point} is mapped to it's self by every lie symmetry. An \\textit{invariant solution} of some symmetry $\\Gamma$ is mapped to it's self by $\\Gamma$, so $S_1 = \\{(x,f(x)) : x\\in \\R\\}$ is invariant iff $\\Gamma(x,f(x)) = (x' , f( x'))$.  \n\nGiven a group $G$ acting on the plane $\\R^2$, the symmetries $S$ of a differential equation, this can be written $G\\acts S$ or $G\\to \\Sym(S)\\subset \\text{Diffeomorphisms}( \\R^2\\to\\R^2 )$. The \\textit{orbit} of an element $(x,y)$ is the set of elements $G \\cdot (x,y) = \\{(\\hat x, \\hat y) : \\exists \\Gamma\\in G | \\Gamma (x,y) = (\\hat x,\\hat y) \\}$. \n\nThe action of a one parameter (denoted by $\\epsilon$) lie group for sufficiently small $\\epsilon$ can be approximated by the Taylor expansion\n\n\\begin{equation}\\label{eq:one param lie group taylor}\n    \\Gamma_\\epsilon : (x,y)\\mapsto (\\hat x,\\hat y)_\\epsilon\\suchthat \\begin{cases}\\hat x = x + \\epsilon \\xi(x,y) + O(\\epsilon^2)\\qquad : \\quad \\frac{d\\hat x}{d\\epsilon} = \\xi(\\hat x,\\hat y) \\\\ \\hat y = y + \\epsilon\\eta(x,y) + O(\\epsilon^2) \\qquad :\\quad \\frac{d\\hat y}{d\\epsilon} = \\eta(\\hat x,\\hat y) \\end{cases}\n\\end{equation}\n\nLocally, the orbit $(\\hat x(\\epsilon),\\hat y(\\epsilon))$ of a lie group action is a parameturized smooth surface - in this case it is a curve since we only consider a one-parameter lie group. \n\nWe introduce the \\tbf{characteristic} $\\mathcal Q(x,y,y')=\\eta(x,y)-y'\\xi(x,y)$ and the \\tbf{reduced characteristic} $\\mathcal{\\overline Q}(x,y;\\omega(x,y)) = \\eta(x,y)-\\omega(x,y)\\xi(x,y)$ as a tool to help us talk about invariant solutions concisely. An \\textit{invariant point} is mapped to it's self by every symmetry, so we require that $\\xi(x,y) = \\eta(x,y) = 0$. The condition for an \\textit{invariant solution} is weaker, we do not require that every point on the solution is invariant, only that the action of the infinitesimal lie group generator is along the solution; in other words, given the solution curve $y=f(x)$ the solution is invariant under the lie symmetry parameturized by $\\epsilon$ if and only if $\\mathcal{\\overline Q}(x,f(x)) \\equiv 0$. \n\n\n(\\cite{Symmetry-methods} p19 thought 21 and 31 for linearized characteristic)\n\nThe $n$-th \\tbf{jet-space} $J^n$ of an ode $\\dot y(t) = \\omega(t,y,y',y'',\\cdots,y^{(n)})$ is the $n+2$ dimensional Euclidean space spanned by $t,y$ and the first $n$ derivatives of $y$, i.e. it is spanned by the variables $(t,y,y^{(1)},y^{(2)},\\cdots,y^{(n)})$. Each solution curve $y(t)$ defines a curve parameturzied by $t$ in the jet space called the \\tbf{lift}. The ode defines a hyper-surface $S$ on the jet-space. The map which brings each solution curve to it's lift is injective, and the image of the solution set in the jet-space is $S$. The extension of the action $\\Gamma$ to all derivatives of order $n$ or less is the $n$-th \\tbf{prolongation} of $\\Gamma$; $\\Gamma$ maps solution curves to solution curves, thus it's prolongation maps $S$ to it's self. \n\n\\subsection{Lie Groups and Algebras.}\n\nA \\tbf{group} $G$ is a set together with a binary operation $\\ast : G \\to \\text{End} (G)$ or $\\ast : G\\times G \\to G$. Axioms : identity, asociativity, closed under composition and inverses. \n\nA \\tbf{Lie Group} is an infinite group which is also a \\tbf{differentiable manifold}. We restrict our attention to manifolds embedded in an ambiant space $\\R^n$. Therefore a Lie Group is a differentiable manifold $\\mathcal M\\subset \\R^n$ with a binary operation $\\ast : \\mathcal M \\to \\{f:\\mathcal M \\to \\mathcal M : f\\,\\text{ is a bijective diffeomorphism}\\}$. The binary operation $\\ast$ takes an element $g\\in \\mathcal M$ to a \\textit{bijective diffeomorphism} $f_g$ of the manifold $G$. We can think about a lie group abstractly as a group $G$ with a map $F : G\\to \\mathcal M \\times \\text{diff} (\\mathcal M)$. So $F(g) = \\{m_g,f_g\\}$, the image of $g\\in G$ is a point $m_g\\in\\mathcal M$ and a diffeomorphism $f_g : \\mathcal M \\to \\mathcal M$. The identity of the lie group is $F(\\unit_G) = \\{p , \\unit_{\\text{diff}(\\mathcal M)}\\}$. Sometimes we wish to only consider the group properties of some specific lie group, to consider only the group structure (without the manifold), in which case we can view the lie group as, more fundamentaly, a continuous group which admits a faithful and continuous (or is it sensible to use differentiable) representation on the bijective diffeomorphisms of some differentiable manifold. We have set ourselves up to define the lie algebra. \n\nA \\tbf{Lie Algebra} $\\mathfrak g$ of a lie group $G$ is the tanjent space at the identity $T_p\\mathcal M$ together with an alternating bi-linear map $\\mathfrak g\\times \\mathfrak g \\to \\mathfrak g$ , $(a,b)\\mapsto [a,b]$ called the \\tbf{lie bracket}, the lie bracket operator is induced by the group binary operation $\\ast$. \n\n \n\\subsection{Canonical Coordinates}\n\\tbf{Canonical Coordinates} are a coordinate system $(r(x,y),s(x,y)) =\\Phi (x,y)$ such that $\\Phi\\circ \\Gamma_\\epsilon (x,y) = (\\hat r, \\hat s) = (r(\\hat x,\\hat y),s(\\hat x,\\hat y)) = (r,s+\\epsilon)$; The necessary and sufficient condition for a coordinate system to be canonical with respect to some lie symmetry (in the plane) is \n\n\\begin{equation}\\label{eq:canonical coordinates condition}\n    \\frac{d\\hat r}{d\\epsilon}\\bigg|_{\\epsilon=0}=0,\\quad \\frac{d\\hat s}{d\\epsilon}\\bigg|_{\\epsilon=0}=1\n\\end{equation}\n\nif we can find functions $r(x,y)$ and $s(x,y)$ such that \\eqref{eq:canonical coordinates condition} holds, then we can integrate the differential equation \\eqref{eq:first order equation} directly by quadrature. Using the chain rule we see that \\eqref{eq:canonical coordinates condition} becomes\n\\begin{equation}\\label{eq:canonical coordinates 2}\n    \\xi\\,\\partial_xr + \\eta\\,\\partial_yr = 0\\qquad,\\qquad \\xi\\,\\partial_xs + \\eta\\,\\partial_ys = 1\n\\end{equation}\nwe impose the extra condition that the jacobian of the change of coordinates is non-degenerate\n$$\n\\left|D\\Phi \\right| = r_xs_y - r_ys_x \\neq 0\n$$\nCurves of constant $r$ are locally invariant under the orbits of the lie group, by definition their tangents coincide $\\frac{dr}{d\\epsilon}=0$, hence $r$ is refered to as an \\textit{invariant canonical coordinate}. \n\nA non-constant function $\\phi(x,y)$ is called a \\textit{first integral} of a first order ODE \n$$\\frac{dy}{dx} = f(x,y)$$\nif it's value is constant on any solution $y=y(x)$. Hence it's gradient will be perpendicular to the tanjent vectors of the solution\n$$(1,f(x,y)) \\cdot \\nabla \\phi = \\phi_x + f(x,y)\\phi_y = 0$$\nthe general solution can be written as level curves of the first integral $\\phi(x,y)=c$. Hence we can find the \\textit{invariant canonical coordinate} by solving \\eqref{eq:solves r} which follows from \\eqref{eq:canonical coordinates 2} and the above identity\n\\begin{equation}\\label{eq:solves r}\n    \\frac{dy}{dx} = \\frac{\\eta(x,y)}{\\xi(x,y)}\n\\end{equation}\nonce we have found $r$ we use $r(x,y)$ to find $y(r,x)$ or $x(r,y)$, then using \n$$1 = \\frac{ds}{d\\epsilon} = \\frac{\\frac{dx}{d\\epsilon}}{\\xi(x,y)} = \\frac{\\frac{dy}{d\\epsilon}}{\\eta(x,y)}$$\n\nwe can integrate with respect to $\\epsilon$ to recover  \n\n\\begin{equation}\\label{eq:solving for s}(r,x) = \\int \\frac{dx}{\\xi(x,y(r,x))} = \\int \\frac{dy}{\\eta(x(r,y),y)}\n\\end{equation} \n\n\\subsection{Finding symmetries, the linearised symmetry condition.}\n\nWhen looking for symmetries, we are essentially looking for a vector field satisfying  the \\textit{linearised symmetry condition}\\eqref{eq:linearised symmetry condition}, which is arrived at by substituting the Taylor expansion of $\\Gamma_\\epsilon$ \\eqref{eq:one param lie group taylor} into the symmetry condition \\eqref{eq:the symmetry condition} and equating the order $\\epsilon^1$ terms\n\n\\begin{equation}\\label{eq:linearised symmetry condition}\n    \\eta_x + (\\eta_y - \\xi_x)\\omega - \\xi_y\\omega^2 = \\xi \\omega_x + \\eta \\omega_y\n\\end{equation}\n\npractically this is useful because \\eqref{eq:linearised symmetry condition} is often easier to solve by Anzats than the original symmetry condition \\eqref{eq:the symmetry condition}\n\n(p39ish of \\cite{Symmetry-methods}). We can view a lie symmetry as being generated by an \\tbf{infinitesimal generator} of a lie group in the plane. The infinitesimal generator is defined as follows\n\n\\begin{equation}\\label{eq:infinitesimal operator}\n    X = \\xi(x,y)\\partial_x + \\eta(x,y)\\partial_y\n\\end{equation}\n\nhence the, the canonical coordinates $r(x,y),s(x,y)$ can be rewritten $Xr = 0\\qquad Xs = 1$. A lie symmetry generated by $X$ acts on a the Hilbert space $\\mathcal H$ of smooth function $F : \\R^2 \\to \\R$ be written in terms of it's generator\n\n\\begin{equation}\\label{eq:generator of lie symmetry}\n    F(\\Gamma_\\epsilon (x,y)) = F(\\hat x,\\hat y) = F(e^{\\epsilon X}\\hat x , e^{\\epsilon X}\\hat y) = e^{\\epsilon X} F(x,y)\n\\end{equation}\n\nWe can recover $\\Gamma_\\epsilon$ thanks to the correspondence between a lie symmetry $\\Gamma_\\epsilon$ and it's tanjent field $(\\xi,\\eta)$, which is also the tanjent field of $e^{\\epsilon X}$. So $\\Gamma_\\epsilon = e^{\\epsilon X}$ \n\n\\subsection{Noether's Theorem}\n\nThere is a statement of Noether's theorem in \\cite{Numerical} (Hairer \\& Lubich - geometric numerical integration) at the bottom of page 210. Another statement of Noether's theorem can be found on page 88 of \\cite{Arnold} (Arnold, mathematical methods of classical mechanics). \n\nOne statement of Noether's theorem \\cite{Arnold}.\n\nLet $M$ be a smooth manifold and $\\mathcal L : TM\\to \\R$ a smooth function on it's tanjent bundle. Let $h^s : M\\to M$ be a smooth map and $h^s_* : TM\\to TM$ is the canonical extension of $h^s$ to $TM$ (Levi-Civita connection).\n\n\\textbf{Definition} A Lagrangian system $(M,\\mathcal L)$ \\textit{admits the mapping h} if for any vector $v_q\\in TM$\n\n$$\\mathcal L(v_q) = \\mathcal L(h_*v_q)$$\n\n\\textbf{Noether's Theorem.} If the system $(M,\\mathcal L)$ admits the one parameter lie group of diffeomorphisms $h^s : M\\to M$, $s\\in \\R$, then the Lagrangian of the system of equations corresponding to $\\mathcal L$ has the first integral $I : TM\\to \\R$. \n\nIn local coordinates, let $M = \\R^n$ be coordinate space. Let $q : \\R^2\\to M\\,,\\,q(s,t) = h^s\\phi(t)$, where we denote the time derivative $\\partial_t q =: \\dot q$, $q$ is a solution to Lagrange's equations for any fixed $s$. Since $h^s_*$ preserved $\\mathcal L(q,\\dot q)$. Making use of the Euler-Lagrange equations \\eqref{eq:euler lagrange} we have \n\n\\begin{equation}\\label{eq:noether derivaiton}\n\\frac{\\partial \\mathcal L}{\\partial s} = \\frac{\\partial \\mathcal L}{\\partial q}\\frac{\\partial q}{\\partial s} + \\frac{\\partial \\mathcal L}{\\partial \\dot q}\\frac{\\partial^2 q}{\\partial t\\partial s} = \n\\left(\\frac{\\partial}{\\partial t} \\frac{\\partial \\mathcal L}{\\partial \\dot q}\\right) \\frac{\\partial q}{\\partial s} + \\frac{\\partial \\mathcal L}{\\partial \\dot q}\\left( \\frac{\\partial }{\\partial t}\\frac{\\partial q}{\\partial s} \\right) \n= \n\\frac{\\partial}{\\partial t}\\left( \\frac{\\partial \\mathcal L}{\\partial \\dot q}\\frac{\\partial q}{\\partial s} \\right) = 0\n\\end{equation}\n\nintegrating with respect to $dt$ we obtain the first integral \\eqref{eq:first integral noether}\n\n\\begin{equation}\\label{eq:first integral noether}\n    I(q,\\dot q) = \\frac{\\partial \\mathcal L}{\\partial\\dot q}\\frac{\\partial q}{\\partial s} = \\text{cnst. wrt } t\n\\end{equation}\n\n\\subsubsection{A basic example of Noether's theorem applied to a Lagrangian system}\nWe start with a simple version of the theorem, applied to Lagrangian systems for many bodies \\cite{Morin}.\n\n\\begin{equation}\\label{eq:lagrangian}\n    \\lag = T - U\n\\end{equation}\n\nmotion is described by the Euler-Lagrange equation which occurs when the action $\\int_{t_0}^{t_f} \\lag dt$ is stationary\n\n\\begin{equation}\\label{eq:euler lagrange}\n    \\frac{d}{dt}\\frac{\\partial \\L}{\\partial \\dot q} = \\frac{\\partial \\L}{\\partial q}\n\\end{equation}\n\nwith the added condition, typical of many body and other systems\n\n\\begin{equation}\\label{eq:lagrangian added conditions}\n    \\dot p = \\frac{\\partial \\L}{\\partial q} \\qquad\\qquad p = \\frac{\\partial \\L}{\\partial \\dot q}\n\\end{equation}\n\nOne parameter lie groups of symmetries lead to conserved quantities. Each symmetry $\\Gamma_\\epsilon : (q,\\dot q)\\mapsto (q(\\epsilon),\\dot q(\\epsilon))$ which preserves the Lagrangian $\\frac{\\partial}{\\partial\\epsilon}\\L(q(\\epsilon,t),\\dot q(\\epsilon,t)) = 0$ implies a conserved quantity. To see this we take the partial derivative\n\n\\begin{equation}\\label{eq:noether's theorem 1 derivation}\n\\frac{\\partial }{\\partial \\epsilon} \\L(q,\\dot q) = \\frac{\\partial q}{\\partial \\epsilon} \\frac{\\partial \\L}{\\partial q} + \\frac{\\partial \\dot q}{\\partial \\epsilon}\\frac{\\partial \\L}{\\partial \\dot q} = \\frac{\\partial q}{\\partial \\epsilon}\\frac{\\partial p}{\\partial t} + p \\frac{\\partial^2 q}{\\partial t \\partial \\epsilon} = \\frac{\\partial }{\\partial t}\\left( p \\frac{\\partial q}{\\partial \\epsilon} \\right) = 0\n\\end{equation}\n\n\\tbf{Example} As an illustration, consider the free particle Lagrangian, $U(q,\\dot q) = C$, then the Lagrangian admits the symmetry\n\n$$\\Gamma_\\epsilon : (p,q)\\mapsto (\\hat p,\\hat q) = (p,q + v\\epsilon) \\quad \\RA \\begin{cases} \\partial_\\epsilon \\hat p = 0\\\\ \\partial_\\epsilon \\hat q = v \\end{cases}$$\n\nwhere $v$ is some (constant wrt $t$ and $\\epsilon$) translation vector $v$. We verify that $\\partial_\\epsilon \\L = 0$\n\n$$\\partial_\\epsilon \\L = \\frac{\\partial q}{\\partial \\epsilon}\\frac{\\partial \\L}{\\partial q} + \\frac{\\partial^2 q}{\\partial \\epsilon\\partial t}\\frac{\\partial \\L}{\\partial \\left( \\partial_t q \\right)} = v\\frac{\\partial \\L}{\\partial q} + \\frac{\\partial v}{\\partial t}\\frac{\\partial \\L}{\\partial \\left(\\partial_t q\\right)} = -v\\nabla U + 0\\cdot \\frac{\\partial \\L}{\\partial (\\partial_t q)} = 0$$\n\nhence applying \\eqref{eq:noether's theorem 1 derivation} we find that the momentum of such a system is conserved\n\n\\begin{equation}\\label{eq:momentum conserved}\n    \\partial_t \\left(p\\frac{\\partial q}{\\partial \\epsilon}\\right) = \\partial_t (pv) = 0 \\RA \\partial_t p = 0\n\\end{equation}\n\n\\tbf{Example} Another example is conservation of angular momentum, in the single body problem. Here we take $q = (x,y,z)$ and $p = \\mu \\dot q$ where mu is the (reduced) mass. The Lagrangian here is given in Cartesian coordinates \n\n\\begin{equation}\\label{eq:lagrangian one body problem}\n    \\lag = T - U = \\frac{\\dot q^2}{2\\mu} - U(|q|)\n\\end{equation}\n\nwe show that the angular momentum operator $L^2 = \\left(\\vec{r} \\times \\vec{p}\\right)^2$ is a symmetry of the Lagrangian. Using the identity (I derived it from an equation in Townsend \\cite{Townsend}) $\\vec r\\times\\vec p = \\vec r^2\\vec p^2 - (\\vec r\\cdot \\vec p)^2$ we derive conservation of momentum, \\tbf{[see also if you can find how conservation of momentum in the z direction works, try the generator $-y\\partial_x + x\\partial_y$ ... ]}\n\n\\section{Celestial mechanics, the N-Body problem.}\n\nIn this section we introduce the n-body problem in Euclidean space starting with 2 bodies, then 3 and then $n$. We look at the symmetries of the Lagrangian and find the first integrals in each case. \n\n\\subsection{The Kepler Problem}\n\nThe Hamiltonian for the two body problem is\n\n\\begin{equation}\\label{eq:hamiltonian kepler}\n    H(p,q) = E = \\frac{p_1^2}{2m_1} + \\frac{p_2^2}{2m_2} - \\frac{G m_1m_2}{|q_2-q_1|}\n\\end{equation}\n\nwith $\\xi := |q_2-q_1|$ and $\\eta := -Gm_1m_2$ we obtain with $\\xi_1 = q_{21} - q_{11}$ and $\\xi_2 = q_{22} - q_{12}$, so $\\xi = \\sqrt{\\xi_1^2 + \\xi_2^2}$. \n\n\\begin{equation}\\label{eq:nabla hamiltonian kepler}\n    \\nabla H_{kepler}(p,q) = \\begin{pmatrix} \n    \\frac{p_{11}}{m_1} & \\frac{p_{12}}{m_1} & \\frac{p_{21}}{m_2} & \\frac{p_{22}}{m_2} & \n    \\frac\\eta{\\xi^3} \\xi_1 & \\frac\\eta{\\xi^3} \\xi_2 & -\\frac\\eta{\\xi^3} \\xi_1 & -\\frac\\eta{\\xi^3} \\xi_2 \n    \\end{pmatrix}\n\\end{equation}\n\nWe compute the the hessian $D^2 H$, see (...resources, places in document and outside...)\n\n\\begin{equation}\\label{eq:hessian of hamiltonian kepler}\n    D^2 H =\n    \\left(\\begin{array}{cccc|cccc}\n    1/m_1 & 0 & 0 & 0    &    0 & 0 & 0 & 0\\\\\n    0 & 1/m_1 & 0 & 0    &    0 & 0 & 0 & 0\\\\\n    0 & 0 & 1/m_2 & 0    &    0 & 0 & 0 & 0\\\\\n    0 & 0 & 0 & 1/m_2    &    0 & 0 & 0 & 0\\\\\n    \\hline \n    0 & 0 & 0 & 0        &    \\frac{-\\eta}{\\xi^3} + \\frac{\\eta}{\\xi^5}\\xi_1^2 & \\frac{\\eta}{\\xi^5}\\xi_1\\xi_2 & \\frac{\\eta}{\\xi^3} - \\frac{\\eta}{\\xi^5}\\xi_1^2 & \\frac{-\\eta}{\\xi^5}\\xi_1\\xi_2 \\\\\n    0 & 0 & 0 & 0        &    \\frac{\\eta}{\\xi^5}\\xi_1\\xi_2 & \\frac{-\\eta}{\\xi^3} + \\frac{\\eta}{\\xi^5}\\xi_2^2 & \\frac{-\\eta}{\\xi^5}\\xi_1\\xi_2 & \\frac{\\eta}{\\xi^3} - \\frac{\\eta}{\\xi^5}\\xi_2^2 \\\\\n    0 & 0 & 0 & 0        &    \\frac{\\eta}{\\xi^3} - \\frac{\\eta}{\\xi^5}\\xi_1^2 & \\frac{-\\eta}{\\xi^5}\\xi_1\\xi_2 & \\frac{-\\eta}{\\xi^3} + \\frac{\\eta}{\\xi^5}\\xi_1^2 & \\frac{\\eta}{\\xi^5}\\xi_1\\xi_2 \\\\\n    0 & 0 & 0 & 0        &    \\frac{-\\eta}{\\xi^5}\\xi_1\\xi_2 & \\frac{\\eta}{\\xi^3} - \\frac{\\eta}{\\xi^5}\\xi_2^2 & \\frac{\\eta}{\\xi^5}\\xi_1\\xi_2 & \\frac{-\\eta}{\\xi^3} + \\frac{\\eta}{\\xi^5}\\xi_2^2\n    \\end{array}\\right)\n\\end{equation}\n\nThe angular momentum \n\n\\begin{equation}\\label{eq:angular momentum kepler}\n    L(p,q) = \\sum q_i\\wedge p_i = \\begin{vmatrix} q_{11} & p_{11}\\\\ q_{12} & p_{12} \\end{vmatrix} + \\begin{vmatrix} q_{21} & p_{21}\\\\ q_{22} & p_{22} \\end{vmatrix} = q_{11}p_{12} - q_{12}p_{11} + q_{21}p_{22} - q_{22}p_{21}\n\\end{equation}\n\nso \n\n\\begin{equation}\\label{eq:nabla l kepler}\n    \\nabla L(p,q) = \n    \\begin{pmatrix} \n    -q_{12} & q_{11} & -q_{22} & q_{21} &\n    p_{12} & -p_{11} & p_{22} & -p_{21}\n    \\end{pmatrix}\n\\end{equation}\n\nand the hessian is\n\n\\begin{equation}\\label{eq:hessian of angular momentum kepler}\nD^2L(p,q) = \n\\left(\\begin{array}{cccc|cccc}\n    0 & 0 & 0 & 0    &    0 & -1 & 0 & 0\\\\\n    0 & 0 & 0 & 0    &    1 & 0 & 0 & 0\\\\\n    0 & 0 & 0 & 0    &    0 & 0 & 0 & -1\\\\\n    0 & 0 & 0 & 0    &    0 & 0 & 1 & 0\\\\\n    \\hline\n    0 & 1 & 0 & 0    &    0 & 0 & 0 & 0\\\\\n    -1 & 0 & 0 & 0    &    0 & 0 & 0 & 0\\\\\n    0 & 0 & 0 & 1    &    0 & 0 & 0 & 0\\\\\n    0 & 0 & -1 & 0    &    0 & 0 & 0 & 0\n\\end{array}\\right)\n\\end{equation}\n\nit is evident that $D^3L =0$\n\n\n\\subsection{N bodies.}\nWe use the notation \n\n$$\n\\xi_{ij} := q_j - q_i \\qquad \\prescript{}{k}{\\xi_{ij}} := \\prescript{}{k}{q_j} - \\prescript{}{k}{q_i} \\qquad\\qquad \\xi_{ij}\\in\\R^3\\quad,\\,\\, \\prescript{}{k}{\\xi_{ij}} \\in \\R\n$$\n\nEach point-mass is described by 6 dimensions of phase space, so this is a 6$n$ dimensional ODE. The Lagrangian is \n\n\\begin{equation}\\label{eq:lagrangian n bodies}\n    \\mathcal L(q,\\dot q) = T - U = \\sum_i \\frac{1}{2}m_i \\dot q_i^T\\dot q_i - \\sum_{i<j}\\frac{Gm_im_j}{\\sqrt{\\xi_{ij}^T\\xi_{ij}}}\n\\end{equation}\n\ntaking the partial derivative with respect to $\\prescript{}{k}{q}_{i}$ (rem $k\\in\\{x,y,z\\}$) we get\n\n\\begin{equation}\\label{eq:partial lagrangian wrt qi}\n    \\frac{\\partial L}{\\partial \\prescript{}{k}{q}_i} = \\sum_{\\stackrel{j=1}{j\\neq i}}^n \\frac{Gm_im_j}{\\left( \\xi_{ij}^T\\xi_{ij} \\right)^{3/2}} \\prescript{}{k}{\\xi}_{ij}\n\\end{equation}\n\n\n\\subsubsection{Symmetries of the n-body problem.}\nEnergy, total momentum, total angular momentum. \n\nThe Lagrangian is invariant with respect to the lie group of \\tbf{translations} in any direction $x_i \\in \\{x,y,z\\}$, this is an abelian group of symmetries of the form $\\Gamma_s : (q,\\dot q)\\mapsto (q+vs,\\dot q)$, we show that the Lagrangian is invariant\n\n$$\n\\frac{\\partial\\mathcal L(q(t,s),\\dot q(t,s))}{\\partial s} = \\frac{\\partial\\mathcal L}{\\partial q}\\frac{\\partial q}{\\partial s} = \n\\sum_{k\\in\\{x,y,z\\}} v_k\\left( \\sum_{i=1}^n \\frac{\\partial\\mathcal L}{\\partial \\prescript{}{k}{q_i}}\n\\right)\n= \\sum_{k\\in\\{x,y,z\\}} v_k\\left(\n\\sum_{i=1}^n \\left[\n\\sum_{\\stackrel{j=1}{j\\neq i}}^n \\frac{Gm_im_j}{\\left( \\xi_{ij}^T\\xi_{ij} \\right)^{3/2}}\\prescript{}{k}{\\xi}_{ij}\n\\right] \\right)\n$$\n$$\n= \\sum_{k\\in\\{x,y,z\\}} v_k\\left(\n\\sum_{i,j} \\frac{Gm_im_j}{\\left(\\xi_{ij}^T\\xi_{ij}\\right)^{3/2}}\\left[ \\prescript{}{k}{\\xi}_{ij} + \\prescript{}{k}{\\xi}_{ji} \\right]\n\\right) = 0\n$$\n\nBy Noether's theorem \\eqref{eq:first integral noether} we have\n\\begin{equation}\\label{eq:conserved total momentum}\n    \\frac{\\partial L}{\\partial \\dot q}^T \\vec v = \\text{cnst.} \\RA \\sum_i m_iq_i = \\text{cnst.}\n\\end{equation}\n\nThis is a statement of conservation of total linear momentum an n-3 dimensional first integral. \n\nOur system is conservative, autonomous: the Lagrangian $L(q,\\dot q,t)$ does not depend explicitly on time translations\n$$\\frac{\\partial\\mathcal L}{\\partial t} = 0$$\ntherefore the \\tbf{energy} is conserved\n\\begin{equation}\\label{eq:conservation of energy noether}\n\\frac{\\partial\\mathcal L}{\\partial \\dot q}\\frac{\\partial q}{\\partial t} = \\sum_i m_i\\dot q_i^T \\dot q_i = 2T = \\text{cnst.}\\end{equation}\n\nThe Lagrangian is invariant with respect to total \\tbf{rotations}, rotations about any axis can be expressed as compositions of rotations about the x, y and z axes. It is sufficient to show that the Lagrangian is invariant under rotations about the z axis. The generator or rotations about the z axis is the operator \\eqref{eq:generator rotations z}\n\n\\begin{equation}\\label{eq:generator rotations z}\n    \\sum_i \\left(\\prescript{}{y}{q}_i \\frac{\\partial}{\\partial \\prescript{}{x}{q}_i} - \\prescript{}{x}{q}_i \\frac{\\partial}{\\partial \\prescript{}{y}{q}_i} \\right)\n\\end{equation}\n\napplying this to the Lagrangian of the system we obtain\n\n\\begin{equation}\\label{eq:rotate lagrangian}\n\\begin{split}\n&   \\sum_i\\left(\n    \\sum_{\\stackrel{j}{j\\neq i}}\\left[\n    \\prescript{}{y}{q}_i \\frac{Gm_im_j}{(\\xi_{ij}^T\\xi_{ij})^{3/2}}\\prescript{}{x}{\\xi}_{ij} - \\prescript{}{x}{q}_i \\frac{Gm_im_j}{(\\xi_{ij}^T\\xi_{ij})^{3/2}} \\prescript{}{y}{\\xi}_{ij}\n    \\right]\\right)\n    =\\\\\n&   \\sum_{i<j\\leq n}\\left(\n    \\frac{Gm_im_j}{(\\xi_{ij}^T\\xi_{ij})^{3/2}} \\left[\n    \\prescript{}{y}{q}_i \\prescript{}{x}{\\xi}_{ij} - \\prescript{}{x}{q}_i \\prescript{}{y}{\\xi}_{ij} + \\prescript{}{y}{q}_j \\prescript{}{x}{\\xi}_{ji} - \\prescript{}{x}{q}_j \\prescript{}{y}{\\xi}_{ji}\n    \\right]\\right) = 0\n\\end{split}\n\\end{equation}\n\nFrom this we obtain the conservation law \n\n\\begin{equation}\\label{eq:conservation of z angular momentum}\n    \\text{cnst.} = \\frac{\\partial\\mathcal L}{\\partial \\dot q}\\sum_i \\left( \\prescript{}{y}{q}_i \\frac{\\partial q}{\\partial \\prescript{}{x}{q}_i} - \\prescript{}{x}{q}_i \\frac{\\partial q}{\\partial \\prescript{}{y}{q}_i} \\right)\n    =\n    \\sum_i \\left( \\prescript{}{x}{p}_i\\prescript{}{y}{q}_i - \\prescript{}{y}{p}_i \\prescript{}{x}{q}_i \\right)\n\\end{equation}\n\nHence the \\tbf{angular momentum} in the z direction is conserved $L_z = \\text{cnst}$. We can apply the same argument for $L_x$ and $L_y$. Thus we have found three more first integrals.\n\n\\section{Numerical Integration, Theory}\n\n\n\\subsection{Symplectic Manifolds and Symplectic Transformations}\n[pointers for research in this section : \\cite{Omar},\\cite{Numerical},\\cite{Duruisseaux}]\n\nA \\tbf{Symplectic Manifold} is an even dimentional manifold which admits a \\tbf{symplectic form} - a closed non-degenerate (skew-symmetric) 2-form $\\omega^2 : TM\\otimes TM \\to \\R$. Non-degenerate means that for each vector $\\rho_p\\in T_p M\\quad \\exists \\rho_p' : \\omega_p(\\rho,\\rho')\\neq 0$. \n\nA \\tbf{Symplectic Transformation} is a map which preserves the symplectic form, in $\\R^{2d}$ this is a map $g$ such that $\\omega(\\xi,\\eta) = \\omega(g'(\\xi),g'(\\eta))$. The canonical symplectic form can be written as an anti-symmetric matrix $\\omega(\\xi,\\eta) = \\xi^T J \\eta$ where the matrix $J$ is\n\\begin{equation}\\label{eq:matrix J}\n    J = \\begin{pmatrix} 0 & I\\\\ -I& 0 \\end{pmatrix}\\in \\R^{2d\\times 2d}\\qquad\\quad \\text{note that}\\quad J^{-1} = -J = J^T = \\begin{pmatrix} 0& -I\\\\ I&0 \\end{pmatrix}\n\\end{equation}\n\nThe \\tbf{flow} of a system $\\dot y = f(y)$ is a function $\\phi_t$ which time evolves the system by $t$; it is the map\n\\begin{equation}\\label{eq:flow}\\psi_t : y_0\\mapsto y(t)\\qquad \\text{if} y_0 = y(0)\\end{equation}\nWith regard a hamiltonian system, $\\dot y = J^{-1}\\nabla H(y=(p,q))$. When the system is autonomous (or conservative $H = cnst$) then we can express the time evolution operator in terms of the hamiltonian equation by exponentiation\n\\begin{equation}\\label{eq:time evolution autonomous hamiltonian}\n    \\psi_t(y) = e^{J^{-1}\\nabla H t}(y)\n\\end{equation}\n\nWe refer to the maps $\\Phi : y_n\\mapsto y_{n+1}$ as the \\tbf{numerical flow} or \\tbf{discrete flow}. \n\n\\subsection{Lagrangian systems are Hamiltonian systems.}\nWe show that Lagrangian systems are Hamiltonian, by constructing a Hamiltonian system from a Lagrangian one (Hamiltonian systems however are not generally Lagrangian). Lagrangian systems are characterised by\n\n$$\n\\L(q,\\dot q) = T - U\\qquad \\L : TM \\to \\R\n$$\n\nthe manifold $M$ is called the configuration manifold, in local coordinates $q = q_1,...,q_d$ is a basis for $U_\\alpha$ - one of the coordinate charts in the atlas $\\phi_\\alpha : U_\\alpha\\hookrightarrow M$. From the Lagrangian we define the `conjugate' momentum to be\n\n$$\np_k := \\frac{\\partial L}{\\partial \\dot q_k}\n$$\n\nthus we define our Hamiltonian function \n\n$$\nH(p,q) = p^T\\dot q(p,q) - \\L(q,\\dot q)\n$$\n\nAn important distinction between Lagrangian and Hamiltonian systems is that the phase space of a Lagrangian system is always the tanjent bundle of some configuration manifold, whereas Hamiltonian systems are defined on arbitrary symplectic manifolds. In other words, the $q$ in a Lagrangian represents postition and the $p$ has to do with change in $\\dot q$; whereas I think in Hamiltonian systems $p$ and $q$ are more abstract...?\n\n\n\\subsection{Hamiltonian systems and Symplecticity.}\n\nThe following proofs and theorems draw heavily from \\cite{Numerical}.\n\n\\tbf{Theorem} (Poincar\\'e). Let $H(p,q)$ be twice continuously differentiable on $U\\subset \\R^{2d}$. Then for each fixed t, the flow $\\psi_t$ is a symplectic transformation. To see this we observe that $D\\psi_t \\equiv \\frac{\\partial \\psi_t}{\\partial y_0}$ at $t=0$ is trivially the identity map\n\n\\begin{equation}\\label{eq:time flow jacobian at t=0}\n\\frac{\\partial \\psi_t}{\\partial y_0}\\bigg|_{t=0} = \\unit \\quad\\RA\\quad \\frac{\\partial \\psi_t}{\\partial y_0}^T J \\frac{\\partial \\psi_t}{\\partial y_0}\\bigg|_{t=0} = J\n\\end{equation}\n\nwe take the time derivative of the symplectic form applied to the Jacobian \n\n\\begin{equation}\\label{eq:time derivative of symplectic form applied to jacobian of flow}\n    \\frac{d}{dt}\\left( \\frac{\\partial \\psi_t}{\\partial y_0}^T J \\frac{\\partial \\psi_t}{\\partial y_0} \\right)\n    =\n    \\left( \\frac{\\partial^2 \\psi_t}{\\partial t \\partial y_0} \\right)^T J \\frac{\\partial \\psi_t}{\\partial y_0} + \\frac{\\partial \\psi_t}{\\partial y_0}^T J \\left( \\frac{\\partial^2 \\psi_t}{\\partial t \\partial y_0} \\right)\n\\end{equation}\n\nby the equality of mixed partials we obtain \\eqref{eq:hamiltonian systems mixed partials} from the equation of motion\n\n\\begin{equation}\\label{eq:hamiltonian systems mixed partials}\n\t\\frac{\\partial^2 \\psi_t}{\\partial t\\partial y_0} = \\frac{\\partial }{\\partial y_0} \\frac{\\partial \\psi_t}{\\partial t} = \\frac{\\partial}{\\partial y_0} J^{-1}\\nabla H(\\psi_t) = J^{-1} D^2H \\frac{\\partial \\psi_t}{\\partial y_0}\n\\end{equation}\n\nsubstituting \\eqref{eq:hamiltonian systems mixed partials} into \\eqref{eq:time derivative of symplectic form applied to jacobian of flow} we get \\eqref{eq:time derivative of symplectic form applied to jacobian of flow evaluated}, which evaluates to zero since $J^{-T} = J$ and $J^2 = -\\unit$.\n\n\\begin{equation}\\label{eq:time derivative of symplectic form applied to jacobian of flow evaluated}\n    \\frac{d}{dt}\\left( \\frac{\\partial \\psi_t}{\\partial y_0}^T J \\frac{\\partial \\psi_t}{\\partial y_0} \\right) = \n    \\frac{\\partial \\psi_t}{\\partial y_0}^T D^2H J^{-T} J \\frac{\\partial \\psi_t}{\\partial y_0} \\,\\,+\\,\\, \n    \\frac{\\partial \\psi_t}{\\partial y_0}^T J J^{-1} D^2H \\frac{\\partial \\psi_t}{\\partial y_0} = 0\n\\end{equation}\n\nIt follows from \\eqref{eq:time derivative of symplectic form applied to jacobian of flow evaluated} and \\eqref{eq:time flow jacobian at t=0} that the flow is symplectic \\eqref{eq:hamiltonian flow is symplectic}.\n\n\\begin{equation}\\label{eq:hamiltonian flow is symplectic}\n    \\frac{\\partial \\psi_t}{\\partial y_0}^T J \\frac{\\partial \\psi_t}{\\partial y_0} = J\n\\end{equation}\n\n\\qed\n\nWe define what it means to be \\tbf{locally hamiltonian} and then prove a slightly weaker version of the converse of Pointcar\\'e's above theorem, that symplectic systems are locally hamiltonian. A system $y' = f(y) \\,\\,\\big|\\,\\, f : U\\subset\\R^{2d} \\to \\R^{2d}$ is said to be locally hamiltonian if for each $y_0\\in U$ there exists an open neighbourhood $N_{y_0}\\subset \\R^{2d}$ containing $y_0$ and some function $H_{y_0} : N_{y_0}\\to \\R$ such that $f(y) = J^{-1}\\nabla H(y)\\quad\\forall y\\in N_{y_0}$. Locally hamiltonian systems defined over simply connected domains are globally hamiltonian; more precisely if the vector field (or one form) of the system is exact and locally hamiltonian, then the  system is globally hamiltonian. \n\n\\tbf{Lemma.} \\textit{(Integrability Lemma) \\cite{Numerical} Let $D\\subset \\R^{2n}$ open, $f: D\\to \\R^{2d}$ differentiable and such that the Jacobian $f'(y)$ is symmetric, $\\frac{\\partial f_j}{\\partial k} = \\frac{\\partial f_k}{\\partial j}$. For every $y_0\\in D$ there exists a real valued differentiable function $H$ defined in a neighbourhood of $y_0\\in N_{y_0}\\subset D$, with $H:N_{y_0}\\to\\R$ such that $f = \\nabla H$. In other words the differential form $f_1(y)dy_1 + \\cdots f_{2d}(y)dy_{2d} = dH$ is a total differential ($dH$ is exact, but it is only defined locally on some simply connected domain aka trivial deRham cohomology).} \n\n\\textit{Proof.} Consider a ball $N_{y_0}\\subset D$ around $y_0$, assume $y_0=0$ and let \n\n$$\nH(y) = \\int_0^1 (y)^Tf(ty) dt + \\text{cnst.}\n$$\n\ntaking the partial derivatives we obtain\n\n\\begin{equation}\\label{eq:hamiltonian differential}\n\\begin{split}\n    \\frac{\\partial H}{\\partial y_k} & = \\int_0^1 f_k(ty) + t y^T\\frac{\\partial f}{\\partial y_k}(ty) dt \\\\\n    & \\stackrel{\\text{symmetry}}{=} \\int_0^1 f_k(ty) + t\\sum_i y_i\\frac{\\partial f_k}{\\partial y_i} dt = \\int_0^1 f_k(ty) + t D f_k(ty) y\\\\\n    & = \\int_0^1 \\frac{d}{dt}\\left( t f_k(ty) \\right) dt = f_k(y)\n\\end{split}\n\\end{equation}\n\nthus $dH = \\sum f_k dy_k$\n\n\\qed\n\n\\tbf{Theorem.} \\textit{Symplectic systems are locally hamiltonian (the converse follows from Pointcar\\'e's theorem above). Consider the ode $\\frac{dy}{dt} = f(y)$ with $f : U\\subset \\R^{2d}\\to \\R^{2d}$, the system is symplectic.} The flow is $\\phi_t$ and by commutativity of the differential operators $\\partial_t$ and $\\partial_{y_0}$ we have \\eqref{eq:mixed partials}\n\\begin{equation}\\label{eq:mixed partials}\n\\partial_t \\frac{\\partial \\phi_t}{\\partial y_0} = \\frac{\\partial }{\\partial y_0}\\frac{\\partial \\phi_t}{\\partial t} = \\frac{\\partial }{\\partial y_0}f\\left(y(t)=\\phi_t(y_0)\\right) = Df \\frac{\\partial \\phi_t}{\\partial y_0}\n\\end{equation}\n\nby the integrability lemma, we need only show that $JDf$ is symmetric to establish the existence of $H$, since the flow generated by $f$ is symplectic by assumption we have \\eqref{eq:symplectic flow equation 1} \n\n\\begin{equation}\\label{eq:symplectic flow equation 1}\n    0 = \\partial_t \\left( \\frac{\\partial \\phi_t}{\\partial y_0}^T J \\frac{\\partial \\phi_t}{\\partial y_0} \\right) = \n    \\left( \\frac{\\partial^2 \\phi_t}{\\partial t\\partial y_0} \\right)^T J \\frac{\\partial \\phi_t}{\\partial y_0} + \\frac{\\partial \\phi_t}{\\partial y_0}^T J \\left( \\frac{\\partial^2 \\phi_t}{\\partial t\\partial y_0} \\right)\n\\end{equation}\n\nsubstituting \\eqref{eq:mixed partials} into the RHS of \\eqref{eq:symplectic flow equation 1} we obtain \\eqref{eq:symplectic flow antisymmetry}\n\n\\begin{equation}\\label{eq:symplectic flow antisymmetry}\n    0 = \\frac{\\partial \\phi_t}{\\partial y_0}^T \\left(\n    Df^T J + JDf\n    \\right)\\frac{\\partial \\phi_t}{\\partial y_0}\\quad \\stackrel{J = -J^T}{\\Longrightarrow}\\quad Df^T J^T = (JDf)^T = JDf\n\\end{equation}\n\nThus $JDf$ is symmetric, by the integrability lemma $\\exists H$ such that in some neighbourhood of $y_0$ (and for sufficiently small time $t$) $\\nabla H = f$\n\n\\qed\n\n\\textbf{Theorem} (see also Thm 2.8 p187 in \\cite{Numerical}). \\textit{Symplectic bijections of the manifold $M$, map hamiltonian systems to hamiltonian systems. The converse it also true: bijective diffeomorphisms on a symplectic manifold which map hamiltonian flows to hamiltonian flows are symplectic.}\n\n\\textit{Proof} $(\\RA)$ Let $\\psi : M \\to M \\quad,\\quad \\psi : y\\mapsto z$ be a bijective symplectic diffeomorpism. Then the hamiltonian flow $\\dot y = J^{-1}\\nabla_y H(y)$ is mapped to $\\dot z = J^{-1}\\nabla_z K(z)$, where $K \\circ \\psi(y) = H(y)$. We note that since $\\psi$ is bijective there exists an inverse and that, by the inverse function theorem $D(\\psi^{-1})\\Big|_{\\psi(p)} = (D\\psi)^{-1}\\Big|_{\\psi(p)} : T_{\\psi(p)}M \\to T_pM$. We make an important observation \\eqref{eq:important observation 1}\n\n\\begin{equation}\\label{eq:important observation 1}\n    \\nabla K(z) = \\nabla_z H\\circ \\psi^{-1}(z) = \\left(\\nabla_y H^T \\frac{\\partial \\psi^{-1}}{\\partial z_1},\\cdots , \\nabla_yH^T \\frac{\\partial \\psi^{-1}}{\\partial z_{2d}}\\right)^T = D\\psi^{-T} \\nabla H\n\\end{equation}\n\nby definition of symplecticity we have \\eqref{eq:symplecticity condition}\n\\begin{equation}\\label{eq:symplecticity condition}\n    D\\psi^TJD\\psi = J \\stackrel{()^{-1}}{\\Longleftrightarrow} D\\psi^{-1}J^{-1}D\\psi^{-T} = J^{-1} \\LRA J^{-1} = D\\psi J^{-1} D\\psi^T\n\\end{equation}\n\nwith the two above observations we see that \n\\begin{equation}\\label{eq:important observation 2}\n    \\dot z = D\\psi \\dot y = D\\psi J^{-1}\\nabla H \\overset{\\eqref{eq:important observation 1}}{\\longlongeq} D\\psi J^{-1} D\\psi^T \\nabla K = J^{-1}\\nabla K\n\\end{equation}\n\n$(\\LA)$ Conversely we see that if $\\psi$ maps hamiltonian flows to hamiltonian flows, $\\psi : y\\mapsto z$ so by assumption we start from \\eqref{eq:important observation 2}, which holds for any hamiltonian flow $H$ and thus\n$$D\\psi J^{-1}D\\psi^T = J^{-1} \\LRA D\\psi^T JD\\psi = J$$\nthe form is preserved.\n\n\\qed\n\n\\tbf{Corollary} \\textit{Liouville's Theorem: It follows that the volume is preserved.} $\\det(J) = 1$ thus\n\n$$\n\\det(D\\psi_t^TJD\\psi_t) = \\det(D\\psi_t)^2 = 1 \\RA \\det(D\\psi_t)=\\pm 1\n$$\n\n$D\\psi_t$ is continuous wrt $t$ and $D\\psi_{t=0}=\\unit$ thus $\\det (D\\psi_t)\\equiv 1\\quad\\forall t$\n\n\\qed\n\n\\subsection{Symplectic Geometry}\n\n\\tbf{In this section (for now) I will make some statements without proving them, and the content will be in my own words and only exists for the benefit of my understanding, so it's likely not to be too coherent... I'm just using this section to offload some thoughts I have while playing with the ideas on paper that are in the textbook (Arnold \\cite{Arnold} and Koszul Zou intro to symp geo \\cite{KoszulZou})}\n\nSymplectic manifolds have a non degenerate two forms $\\omega^2$ which can be represented in some basis as a matrix $J$, so $\\omega^2(\\xi,\\eta) = \\xi^TJ\\eta$. We can write this form as\n\n$$\\omega^2 = d\\tbf p \\wedge d\\tbf q = dp_1\\wedge dq_1 + \\cdots + d p_d\\wedge dq_d$$\n\nsince the symplectic form is preserved then so are the wedges of the symplectic form so $\\omega^2\\wedge\\omega^2 = 2\\sum_{i<j}p_i\\wedge q_i\\wedge p_j\\wedge q_j$, furthermore, the volume form is preserved since $\\omega^2\\wedge \\cdots \\wedge \\omega^2$ (d times) is $(d!) \\cdot dp_1\\wedge dq_1\\wedge \\cdots \\wedge dp_d\\wedge dq_d = dV$, thus hamiltonian flows preserve volume in phase space. (notation here gets confusing cause d is overloaded.) \n\n\n\\subsection{Survey of Classical Integration methods}\n\\subsubsection{Types of integrators}\n\n\\textbf{Def} : a \\textbf{symmetric} method is one that is time reversible: if you propagate a point forward $n$ timesteps then backward $n$ time-steps using the same method you end up in the same spot. Formally, the numerical flow $\\phi_h$ is symmetric \\tbf{......................[EXPOUND]} \n\n``Numerical experiments indicate that symmetric methods applied to integrable and near-integrable reversible systems share similar properties to symplectic methods applied to (near-)integrable Hamiltonian systems: linear error growth, long-time near-conservation of first integrals, existence of invariant tori. The present chapter gives a theoretical explanation of the good long-time behaviour of symmetric methods. The results and techniques are largely analogous to those of the previous chapter - the extent of the analogy may indeed be seen as the most surprising feature of this chapter.\" (\\cite{Numerical} intro to chapter XI)\n\n\\textbf{Def} : a method $\\phi_h : y_n\\mapsto y_{n+1}$ is \\textbf{symplectic} if the numerical flow is symplectic. Rem, the numerical flow can be approximated by a series expansion $\\phi_h(y) = y + hf(y) + h^2d_2(y) + O(h^3)$. We say that a method is symplectic to $k$th order if the first $k$ terms of the modified equation of the numerical flow are symplectic? - or do we say this when the numerical flow is actually symplectic; I'm pretty sure it's just when the first $k$ terms are syplectic. \n\n\\subsubsection{Explicit Euler}\nThis is the most straight forward method. For the ODE $y' = f(y,t)$ the explicit euler method is defined\n\\begin{equation}\\label{eq:explicit euler}\ny_{n+1} = \\phi_h(y_n , n\\cdot h) = y + h f(y_n, n\\cdot h)\n\\end{equation}\n\n\\subsubsection{Str\\\"omer Verlet}\nThe (explicit one-step) Str\\\"omer Verlet method is a symplectic integrator, who's numerical flow is given below for the $n$-body problem $\\phi_h : (p_n,q_n)\\mapsto (p_{n+1},q_{n+1})$\n\\begin{equation}\\label{eq:stromer verlet n body}\n\\begin{split}\n    & p_{n+1/2} = p_n - \\frac{h}{2}\\frac{\\partial H}{\\partial q}(q_n)\\\\\n    & q_{n+1} = q_n + h \\frac{\\partial H}{\\partial p}(p_{n+1/2})\\\\\n    & p_{n+1} = p_n - \\frac{h}{2}\\left( \\frac{\\partial H}{\\partial q}(q_n) + \\frac{\\partial H}{\\partial q}(q_{n+1}) \\right)\n\\end{split}\n\\end{equation}\n\nIn section \\ref{section:truncated modified equations} we show that the numerical flow belonging to this scheme is symplectic up to order $O(h^2)$. \n\n\\subsubsection{Explicit Midpoint rule}\nEstimate the midpoint, use gradient at this point to find multiplied by the stepsize $h$ to determine where to next.\n\n\n\n\n\\subsection{Kepler Projection Methods Experiment.}\n\\subsubsection{Aim}\nTo find some numerical evidence for or against the hypothesis, to generate ideas for where to go next, to gain intuitive understanding of which numerical integrators work better for this type of problem, do error analysis. \n\n\\subsubsection{Theory / Hypothesis}\n\nThe setup is the two body or Kepler problem with point masses $m_1,m_2$ the hamiltonian is the usual one with parameters $p_{11},p_{12},p_{21},p_{22},q_{11},q_{12},q_{21},q_{22}$. The total mass is denoted $M$, and the reduced mass $\\mu$, the reduced velocity is an $\\R^2$ vector and is denoted $v$ and the reduced distance $r$. \n\nThe Kepler problem is given by the ode\n\\begin{equation}\\label{eq:ode kepler}\n    \\dot y = (\\dot p,\\dot q) = J^{-1}\\nabla H(p,q)\n\\end{equation}\nwhere $J = \\left[\\begin{array}{c|c}0&\\unit\\\\\\hline-\\unit&0\\end{array}\\right]$ is the canonical symplectic form and $H$ is the Kepler hamiltonian.\n\nWe can solve it analytically, see \\cite{WBell} page 129. \n\nThere is a theorem which states that syplectic flow which conserve all first integrals (invariants) of a Hamiltonian system (Find the theorem and name it, state it formally and possibly prove it!) must be exact, i.e. there is a unique syplectic flow which conserves all first integrals. The projection methods' numerical flow conserves all invariants, is not exact and hence is not symplectic. \n\n\nOur ode \\eqref{eq:ode kepler} can either be viewed as an 8 dimensional beast or, when put into the inertial CM frame we can reduce the dimensions to 4, in which case it is the same ode as of a single reduced mass orbiting a central potential in the plane. We do not reduce the dimensions for the integration schemes for we wish to use similar integrators for the n-body problem. With every integration step we project onto the the $L-E$-manifold, the intersection of the energy and angular momentum first integrals. In the following numerical experiments, we are looking for evidence of an attracting sub-manifold of the $L-E$-manifold. This is the main hypothesis : the numerical flow of projection methods creates attractors.\n\n\\subsubsection{Method}\n\nWe use the following methods to try and gauge what is going on.\n\nThe acceleration of a point mass travelling in a circle is $a_c = v^2/|r|$ (inwards), the centripetal acceleration of the reduced mass is $GM/{|r|^2}$. We define the \\tbf{k-factor} as the quantity $k(p,q) = v^2 - \\frac{GM}{|r|}$. Hence, when the orbit is circular this quantity goes to zero $k\\to 0$. If the orbit is elliptical and highly eccentric, we should observe this quantity oscillating wildly up and down with each orbit, the $k$-factor for the exact flow, for such an orbit should be a periodic and un-damped. We use this quantity to see if an integration scheme is pulling the orbit into a circular one. \n\nAnother quantity we are interested in is the \\tbf{angle} between the first-integral level surfaces $L$ and $E$ onto which we are projecting. Using the euclidean metric induced by the $(p,q)$ coordinate system we define the angle between these manifolds at a point $p$ as the arc-cosine of the absolute value of the dot product of their area-forms. Taking the absolute value gives us the acute angle. The dot product of the area forms are the same as the dot product of their Hodge-duels which are parallel to the gradients of the first integral functions. So the acute angle of surfaces $H=cnst$ and $L=cnst$ with area forms $\\omega_H,\\omega_L$ resp. are given by \n\n\\begin{equation}\\label{eq:angle between level sets}\n    \\theta_p = \\arccos{|\\omega_H(p) \\cdot \\omega_L(p)|} = \\arccos|\\star \\omega_H(p) \\cdot \\star\\omega_L(p)| = \\arccos\\left| \\frac{\\nabla H \\cdot \\nabla L }{|\\nabla H| |\\nabla L|} \\right|_p\n\\end{equation}\n\nThe projection methods used are given in detail above.\n\nThe \n\n\\tbf{Error analysis}. For the syplectic integrators we can do some backward error analysis, comparing the truncated modified vector field with the exact one. And second since there is an analytic solution to the Kepler problem we can just compare our results with the exact solution and obtain the global error of each method. \n\n\\subsubsection{Results, Observations, Remarks, Speculation.}\n\n\n\nFor reference the k-factor is \n\n\\begin{equation}\n    v^2 - \\frac{G M}{r}\\qquad:\\quad M = m_1+m_2\n\\end{equation}\n\nThe experiments which generated the pngs in gallary exp kepler where set in the following starting configurations (initial conditions).\n\\tbf{Configuration 1}\n\n\\begin{python}\np1,p2,q1,q2 = [0.4,0.0] , [-0.4,0.0] , [0,-1] , [0,1]\ny = [p1,p2,q1,q2] # supervector\nm1,m2 = 1.0 , 1.4\nE = -0.563\nL = 0.800\n\\end{python}\n\nThe integration constants use are \\pyth{STEPS} and the time-step is $h =$ \\pyth{H} specified in the graphs in title of energy plots.\n\nStarting configuration, same energy and ang momentum as in configuration 1, the program puts us automatically into CM frame. We are in same starting position but not same starting momentum.\n\n\\begin{python}\np1,p2,q1,q2 = [0.3 , 0.07] , [-0.5 , 0] , [0,-1] , [0,1]\ny = [p1,p2,q1,q2] # supervector\nm1,m2 = 1.0 , 1.4\nE = -0.563\nL = 0.800\n\\end{python}\n\n\\tbf{Configuration 3}\n\n\\begin{python}\np1,p2,q1,q2 = [0.8 , 0.0] , [-0.8 , 0] , [0,-1] , [0,1]\ny = [p1,p2,q1,q2] # supervector\nm1,m2 = 1.0 , 1.4\nE = \nL = \n\\end{python}\n\n\\tbf{Configuration 4}\n\n\\begin{python}\np1,p2,q1,q2 = [0.4,0.1] , [-0.4,-0.1] , [0,-1] , [0,1]\ny = [p1,p2,q1,q2] # supervector\nm1,m2 = 1 , 1.4\nE = \nL =\n\\end{python}\n\n\n\\subsubsection{Remarks}\n\n\\tbf{Exp Euler}\nThe method performed poorly in general. However when integrated with very small time steps, it did conserve the angles between invariant level sets slightly better than when combined with a projection method. There was no drift in the mean although the amplitude did increase. \n\nWhen combined with a projection, the angles between invariant level sets tend to orthonormalize and the k-factor goes to zero, which means the orbit becomes circular after a long time. \n\n\\tbf{Str\\\"omer Verlet}\nThe Str\\\"omer Verlet scheme on it's own perserves all six of the quantities for a long time. Of special interest is that the plots of the k-factor and the angles between invarient level sets are preserved over long time periods even with large steps, this is expected because the roughly elliptic orbits of the modified equation \\eqref{eq:stromer verlet modified equation} are integrated exactly and are not pulled toward circular orbits. The same goes for the angles betweent he invarient level sets, these are preserved very well over long time periods as demonstrated the figure \\pyth{invarients_config4_stromer_verlet_None_h=0.05_STEPS=100000.png}. \n\nUpon inspection of the plots (see fig \\ref{fig:numerical experiments kepler}, see also \\href{https://github.com/dcxSt/numerical_integrators/tree/master/figures/gallary}{many more plots online}) we observe that in every starting configuration, no matter the integrator, the projection methods invariable maximized the orthogonality of the invariant level sets (energy and angular momentum) who's intersection constitutes the invariant manifold onto which we are projecting.  \n\n\n\n\\subsection{Projection Methods}\n\nNote on notation: in the following subsections we use $2d$ and $n$ interchangeably to denote the dimension of the hamiltonian system. I hope this does not cause confusion, (Note to self: refactor and homogenise notation when writing final draft if this work ends up being something I'm proud of) \n\n\\subsubsection{First method. The \\textit{Naive} Projection Method}\n\\begin{equation}\\label{eq:projection ivp}\n    p = y(0) \\qquad y' = \\nabla \\beta\n\\end{equation}\nthen the projection is defined\n\\begin{equation}\\label{eq:projection}\n    \\rho_E(p) = y(t) \\qquad\\text{such that $t$ satisfies} \\quad\\beta(y(t)) = E\n\\end{equation}\nWe can approximate the flow of this system to first order by Taylor expantion\n\\begin{equation}\\label{eq:projection taylor expansion}\n    y(t) = p + \\nabla \\beta(p) t + O(t^2)\n\\end{equation}\nsince $\\beta(\\rho_E(p))=E$ by definition we can use the approximation \\eqref{eq:projection taylor expansion} we find an approximate solution for the projection onto the manifold $\\beta=E$ by solving the following equation \\eqref{eq:projection approximation} for $\\lambda$\n\\begin{equation}\\label{eq:projection approximation}\n    E = \\beta(\\rho_E(p)) \\approx \\beta(p + \\lambda\\nabla\\beta(p)) \\approx \\beta(p) + D\\beta(p) \\lambda \\nabla \\beta(p) = \\beta(p) + \\lambda \\left(\\nabla\\beta(p)\\right)^T\\nabla\\beta(p)\n\\end{equation}\nusing \\eqref{eq:projection approximation} to estimate $\\lambda$, the approximate projection operator is\n\\begin{equation}\\label{eq:approximate projection operator}\n    \\widetilde\\rho_E(p) := p + \\lambda\\nabla\\beta(p) \\qquad \\text{with}\\qquad \\lambda := \\frac{E - \\beta(p)}{\\nabla\\beta\\cdot\\nabla\\beta\\big|_p}\n\\end{equation}\nGiven a set of $s$ first integrals $\\{\\beta_i\\}_{i=1}^s$ we modify the numerical flow to preserve the quantities $\\beta_i = E_i$. Given $\\Phi_h : y_n \\mapsto y_{n+1}$\n\\begin{equation}\\label{eq:modified numerical flow}\n    \\widetilde \\Phi_h(y_n) := \\tilde y_{n+1} = y_{n+1} + \\sum_{i=1}^s \\lambda_{E_i}\\nabla\\beta_i(y_{n+1})\n    = y_{n+1} + \\sum_{i=1}^s \\frac{E_i - \\beta_i(y_{n+1})}{\\nabla\\beta_i(y_{n+1})^2}\\nabla\\beta_i(y_{n+1})\n\\end{equation}\ninstead you can evaluate iteratively $f(y_{n+1}')$.\n\n\\tbf{Implementation of the naive projection method for the kepler problem.}\n\\begin{python}\\label{code:naive projection method kepler}\ndef naive_projection(y,first_integrals=[(get_energy,nabla_H),\n                                        (get_total_angular_momentum,nabla_l)]):\n    # apply each projection one after the other \n    for i,j in first_integrals:\n        fint,nabla_fint = i,j(y) \n        lambda_i = fint(Y0) - fint(y) \n        lambda_i /= supervec_norm(nabla_fint)\n        y = y + lambda_i*nabla_fint \n        \n    return\n\\end{python}\n\n\\subsubsection{Naive Symmetric Method.}\nI got this method from \\cite{hairer2002geometric} page 1003, algorithm 3.2. \n\nGiven the invariant level surfaces given by our first integrals $\\{y:\\beta_i(y) = c_i \\forall i \\leq m\\}$ we define the function $g : \\R^{2d}\\to\\R^m$ such that $g(y) = (\\beta_1(y) - c_1 , \\cdots , \\beta_m - c_m)$. Hence the invariant manifold is given by $\\{y : g(y)=0\\}$. We denote the Jacobian $G := g'$. The algorithm \\cite{hairer2002geometric} is essentialy the same as the naive one only this time we over-shoot by double instead of landing on the manifold. \n\\begin{itemize}\n    \\item $\\hat y_n = y_n + G^T(y_n)$ \n\\end{itemize}\n\n\n\\subsubsection{Better algorithm for projection methods of first integrals. The \\textit{Parallel} projection method.}\n\nThe above method has a weakness, while it is successful in preserving the energy manifold, it in-fact takes us off of the other invariants (in our example linear momentum is not conserved, which is a quantity that even the explicit Euler integrator doesn't have any trouble with). Our problem now is that we have a set of level sets $\\{\\beta_i(y) = c_i\\}^s_{i=1}$ where the $\\beta_i$ are first integrals and $c_i$ are constants, and we wish to preserve all of them. We solve this by modifying the projection \\eqref{eq:modified numerical flow} so that we for each projection $\\rho_{E_i}$ we are projection onto the level set $\\beta_i=c_i$ along the intersection of the other conserved level sets, so $\\beta_j(p) = \\beta_j(\\rho_{E_i}(p))$. In this section explore one algorithm that does this. \n\nWe wish to find an easy to implement projection $\\widetilde \\rho_E^{(2)}$ which projects the point $p$ onto the manifold $\\beta_i=c_i$ while conserving $\\beta_j(p)\\forall j\\neq i$. We modify the projection operator $\\widetilde \\rho_E$ from equation \\eqref{eq:approximate projection operator} (re-written):\n$$\n\\widetilde \\rho_{E_i}(p) = p + \\lambda \\nabla \\beta_i(p)\\qquad \\text{with}\\qquad \\lambda := \\frac{E - \\beta_i(p)}{\\nabla \\beta_i(p) \\cdot \\nabla \\beta_i(p)}\n$$\n\nWe refine the projection iteratively with respect to it's components, each of which is associated with a first integral. We start by initializing our set $\\{\\nabla \\beta_1' ,\\cdots , \\nabla\\beta_s'\\} := \\{\\nabla \\beta_1 ,\\cdots ,\\nabla \\beta_s \\}$, we start with $j=1$. For each $i\\neq j$ we redefine the set, projecting each vector with the operator $\\hat P_{j,\\{\\nabla\\beta_1',\\cdots,\\nabla\\beta_s'\\}}$ which we write $\\hat P_{j}$ for short; defined as follows\n\n\\begin{equation}\\label{eq:first coefficient}\n    \\hat P_j : \\nabla\\beta_i' \\mapsto \\nabla\\beta_i' - \\alpha_{ij}\\nabla\\beta_j' \\qquad\\text{with}\\qquad \\alpha_{ij} = \\frac{\\nabla\\beta_j \\cdot\\nabla\\beta_i'}{\\nabla\\beta_j\\cdot\\nabla\\beta_j'} \n\\end{equation}\n\nThis formula is derived from $\\nabla\\beta_j\\cdot (\\nabla\\beta_i - \\alpha_{ij}\\nabla\\beta_j')  = 0$, we can also find it by finding the optimal $a_{ij}$ which minimizes $(\\nabla\\beta_i - a_{ij}\\nabla\\beta_j')^T(\\nabla\\beta_i - a_{ij}\\nabla\\beta_j')$. \n\nApplying the operators $\\{\\hat P_1 , \\hat P_2,\\cdots ,\\hat P_s \\}$ one by one to the set $\\{\\nabla\\beta_1,\\cdots,\\nabla\\beta_s\\}$ iteratively (we remark that $\\hat P_j$ is defined with respect to the set $\\{\\nabla\\beta_i'\\}_{i=1}^s$, here each time the next $\\hat P_{j+1}$ operator is applied to the set we use the output of the previous operator to define it, hence the method is recursive and lends it's self to for loops)\n\nNow we find the proper coefficient $\\lambda_i'$ in order to land near-to (on up to first order expansion) the conserved manifold - i.e. the intersection of each of the first integrals $\\beta_i(y_n) = \\beta_i(y_0)$. Since $\\lambda_i\\nabla\\beta_i$ reaches the desired tanjent space, want the $\\lambda_i\\nabla\\beta_i$ component of $\\lambda_i'\\nabla\\beta_i'$ to be the same size. Hence $\\lambda_i'$ must satisfy \\eqref{eq:lambda prime condition} and thus \\eqref{eq:lambda prime formula}\n\n\\begin{equation}\\label{eq:lambda prime condition}\n    \\left( \\lambda_i'\\nabla\\beta_i' \\right)^T \\left( \\lambda_i\\nabla\\beta_i \\right) = \\lambda_i^2 \\nabla\\beta_i^T\\nabla\\beta_i \\quad\\RA\\quad \\lambda_i' := \\lambda_i \\frac{\\nabla\\beta_i^T \\nabla\\beta_i}{\\nabla\\beta_i^T \\nabla\\beta_i'}\n\\end{equation}\n\nby substituting in the value of $\\lambda_i$ from equation \\eqref{eq:approximate projection operator} we obtain\n\n\\begin{equation}\\label{eq:lambda prime formula}\n    \\lambda_i'(p) = \\frac{E_i - \\beta_i(p)}{\\nabla\\beta_i^T \\nabla\\beta_i'}\n\\end{equation}\n\nHence we can express our new operator in a notationally condense form using the expressions from equations \\eqref{eq:lambda prime formula}, \\eqref{eq:fisrt coefficient}\n\n\\begin{equation}\\label{eq:new approximate projection}\n    \\widetilde\\rho^{(2)}(p) = \n    \\sum_{i=1}^s \\widetilde\\rho_{E_i}^{(2)}(p) \\approx p + \\sum_{i=1}^s \\left( \\lambda_i' \\nabla\\beta_i' \\right)\n\\end{equation}\n\nTo summarise, this projection \\eqref{eq:new approximate projection} can be thought of as concatenation of many projections $\\widetilde\\rho_{E_i}$ which project onto the desired level set $\\beta_i(p)=E_i$ while preserving all other conserved quantities to first order. \n\nFor the actual implementation of the algorithm there is a fear that the denominator of the expression for $\\lambda_i$ will vanish - that $\\nabla\\beta_i^T\\nabla\\beta_i'=0$ i.e. that $\\nabla\\beta_i$ and $\\nabla\\beta_i'$ are perpendicular, this may arise in the case where two level sets of invariants are parallel or almost parallel at a point $p$. If this were to happen our projection operator might become really big, which is not what we want, the aim of this approximate projection is to apply small rectifications to our solutions at every time-step (or perhaps every few steps).  Thus we may consider adding a small but non-zero term $\\epsilon \\left|E_i - \\beta_i(p) \\right|$ to the denominator of $\\lambda_i'$  \\eqref{eq:new approximate projection with blowup safeguard}. (choice of epsilon to be determined experimentally), Note that $\\nabla\\beta_i^T\\nabla\\beta_i'\\geq 0$ I THINK, THIS HAS YET TO BE PROVEN, BUT WILL PROBABLY NEVER GET ROUND TO IT BECAUSE THERE ARE MORE PRESSING MATTERS TO ATTEND TO! since we define $\\nabla\\beta'$ by projection $\\nabla\\beta$ onto a surface. I just added a try catch for overflow. Also this paragraph, is the only thing that needs to change in this subsection.\n\n\\begin{equation}\\label{eq:new approximate projection with blowup safeguard}\n    \\widetilde \\rho^{(3)} : p \\mapsto p + \\sum_{i=1}^s \\left( \\frac{E_i - \\beta_i(p)}{\\nabla\\beta_i^T\\nabla\\beta_i' + \\epsilon\\left|E_i - \\beta_i(p)\\right|} \\nabla\\beta_i' \\right)\n\\end{equation}\n\nIn practice we can substitute the $\\epsilon$ on the denominator with a conditional statement. \n\nA weakness of this algorithm is that it does not work when the function $\\nabla \\beta=0_V$, i.e. when the level set is defined at an extrema of the first integral. However this happens very rarely \\tbf{(according to something I read, find it and cite it! )}. %\\cite{...}.\n\n\\tbf{Implementation of this algorithm in python for the kepler problem.}\n\\begin{python}\ndef parallel_projection(y,first_integrals=[(get_energy,nabla_H),\n                                            (get_lin_mom_x,nabla_lin_x),\n                                            (get_lin_mom_y,nabla_lin_y)]):\n    global overflow_count\n    \n    # first compute the gradients\n    fivag = [(i(y),i(Y0),j(y)) for i,j in first_integrals]\n    finty,fint0,beta = [j for i,j,k in fivag],[i for i,j,k in fivag],[k for i,j,k in fivag]\n    beta_prime = [j[:] for j in beta] # copy of the gradients to be modified\n    \n    \n    # for each j, project all the i's out of the j surface\n    for j in range(len(fivag)):\n        for i in range(len(fivag)):\n            if j != i:\n                try:\n                    beta_i_prime = beta_prime[i] - supervec_dot(beta[j],beta_prime[i]) / supervec_dot(beta[j],beta_prime[j]) * beta_prime[j]\n                    beta_prime[i] = beta_i_prime \n                except OverflowError(\"overflow, probably the manifolds have small angle\"):\n                    overflow_count+=1 \n    \n    y_proj = y[:] \n    # project along each axis\n    for e0,ey,b_i_p,b_i in zip(finty,fint0,beta_prime,beta):\n        try:\n            lambda_i = (e0 - ey) / supervec_dot(b_i_p,b_i)\n            y_proj += lambda_i * b_i_p \n        except OverflowError(\"overflow in computing lambda_i\"):\n            overflow_count+=1\n            \n    return y_proj\n\\end{python}\n\n\\subsubsection{Standard Projection Method}\n\nSee algorithm 4.2 on page 110 of \\cite{Numerical}.\n\n[explain the implementation of this thing : by means of newton iterations the projection numerically optimizes the closest distance to the conserved manifold and projects onto it.] \n\n\n\\subsubsection{Modified differential equation, turn the manifold into an attractor?? by modifying the equation.}\n\nBy modifying the equation and turning the conserved manifold (intersection of first integral level sets) into an attractor, we hope that the flow and the numerical flow of the modified equation in regions near the attracting manifold will mirror the numerical flow of other methods combined with the projection methods described above. \n\n[answer the question - why would you use my methods instead of the standard projection methods? Because the numerical flow of the modified equation is closer to my methods than it is to the standard projection method.]\n\n[Describe how the equation is modified]\n\n\\subsubsection{Infidelity of the projections, `difference flow' (made up term).}\n\nDiscuss and motivate the formula you found for this flow which represents your best guess of how the flow is affected, the following differential equation is something I derived which I think describes the `error flow' induced by the projections. I hope to be able to use this to show that some exact solutions are stable under projection and other are not, as further evidence for the existence of an invariant manifold. \n\n\\begin{equation}\\label{eq:differnece flow}\n\\dot y = D^2\\beta \\nabla\\beta - \\frac{\\nabla\\beta^T D^2\\beta \\nabla\\beta}{\\nabla\\beta^T\\nabla\\beta} \\nabla\\beta : TM\\to TM : M = \\{x\\in\\R^{2d} : \\beta(x) = \\text{cnst} \\}\n\\end{equation}\n\ngeneralised\n\n\\begin{equation}\\label{eq:difference flow many}\n\\dot y = \\sum_{i=1}^n D^2\\beta_i \\nabla\\beta_i - \\frac{\\nabla\\beta_i^T D^2\\beta_i\\nabla\\beta_i}{\\nabla\\beta_i^T\\nabla\\beta_i} \\nabla\\beta_i : TM\\to TM : M = \\left\\{x\\in\\R^{2d} : \\begin{cases}\\beta_1(x)=\\text{cnst}\\\\\\cdots\\\\\\beta_n(x)=\\text{cnst}\\end{cases}\\right\\}\n\\end{equation}\n\nI hypothesise that this flow is qualitatively similar to the projected flow vector field minus the exact flow vector field.\n\nWe turn the conserved manifold into an attractor by modifying the differential equation, although this does not preserve the syplectic form, I haven't seen it mentioned anywhere...\n\n\\subsection{Second order Conservation of invariants via method of Local coordinates.}\n\nI remember reading a theorem that said if the flow is syplectic (= locally hamiltonian) and all the invariants are preserved, then it is exact, therefore must this method be non-syplectic? If this is the case is it true then our flow does not preserve any syplectic form and therefore even if we stay on a manifold the volume will not be preserved, it may become squished. \n\n\n\\subsubsection{Implementation of projection Algorithm. (See documentation on site, link to github repo readme / documentation)}\n\nTo start off we implement this for the Kepler problem. I have already done this for a single conserved quantity. I will take a small step and implement the projection method for two conserved quantities - Energy and Angular momentum. \n\nThe gradients vector fields of an energy first integral is just the gradient of the hamiltonian. The gradient of the total angular momentum first integral is given by \nFALSE\n\\begin{equation}\\label{eq:first integral gradient total angular momentum}\n    \\nabla L(p_{11},p_{12},p_{21},p_{22},q_{11},q_{12},q_{21},q_{22}) = \\begin{pmatrix} -q_{12} & q_{12} & -q_{22} & q_{21} & p_{12} & -p_{11} & p_{22} & -p_{12} \\end{pmatrix}\n\\end{equation}\n\n\n\\tbf{Figure out whether the symplectic two form being preserved is the same as all the Pointcar\\'e symmetries being preserved - what does this even mean}\n\n\\section{Backward Error Analysis}\n\nBackward error analysis dates back to the 1960s, it is very useful for studying the qualitative behaviour of numerical methods, and when statements over very long time intervals are needed. For formal analysis the modified equation - a formal series in powers of $h$ (the step size) has to be truncated. The error induced by such a truncation can be made exponentially small, and the results remain valid on exponentially long time intervals. See introduction of chapter IX of \\cite{Numerical}, page 337.\n\nWe start with a differential equation \n\n\\begin{equation}\\label{eq:exact equation}\n    \\frac{d}{dt}y = \\dot y = f(y)\n\\end{equation}\n\nand a numerical flow $\\phi_h : y_n\\mapsto y_{n+1}$ which we assume can be expanded as follows\n\n\\begin{equation}\\label{eq:numerical flow}\n    \\phi_h(y) = y + hf(y) + h^2d_2(y) + h^3d_3(y) + O(h^4)\n\\end{equation}\n\nour goal is to find a modified equation who's exact flow is the numerical flow of our original equation. We wish to find an equation for which the curve $\\widetilde y(t)$ is a solution, which is exactly a solution to the numerical flow so that $\\widetilde y(hn) = \\phi_h^n(y_0)$. Assuming $\\dot{\\widetilde y}$ is analytic in $\\widetilde y$ we write the modified equation in Taylor form\n\n\\begin{equation}\\label{eq:modified equation general formula} \n    g(\\widetilde y) := \\frac{d}{dt}\\widetilde y = \\dot{\\widetilde y} = f(\\widetilde y) + hf_2(\\widetilde y) + h^2f_3(\\widetilde y) + h^3f_4(\\widetilde y) + O(h^4)\n\\end{equation}\n\nTo find the relationship between coefficients of the modified equation \\eqref{eq:modified equation general formula} and those of our numerical flow \\eqref{eq:numerical flow} Taylor expand $\\widetilde y(t+h)$ about $\\widetilde y(t)$. Equating the exact flow of the modified equation the numerical flow for a single step we obtain\n\n\\begin{equation}\\label{eq:modified and numerical taylor}\n    \\begin{split}\n    \\widetilde y(t+h) &= \\widetilde y(t) + h\\dot{\\widetilde y}(t) + \\frac{h^2}{2!} \\ddot{\\widetilde y}(t) + O(h^3)\\\\\n    &= \\widetilde y(t) + hg(\\widetilde y) + \\frac{h^2}{2!}g^{(1)}(\\widetilde y)g(\\widetilde y) + O(h^3)\\\\\n    &= \\widetilde y(t) + hf(\\widetilde y) + h^2d_2(\\widetilde y) + h^3d_3(\\widetilde y) + O(h^3) = \\phi_h(\\widetilde y(t))\n    \\end{split}\n\\end{equation}\n\nEquating like powers of $h$ we obtain a recurrence relation for finding $f_n$ in terms of $\\{f_i\\}_{i<n}$. We obtain the following recurrence relations:\n\n\\begin{equation}\\label{eq:f_2}\n    f_2(y) = d_2(y) - \\frac{1}{2} f^{(1)} f(y)\n\\end{equation}\n\n\\begin{equation}\\label{eq:f_3}\n    f_3(y) = d_3(y) - \\frac{1}{6}\\left( f^{(2)} (f , f)(y) + f^{(1)} f^{(1)} f(y) \\right) - \\frac{1}{2}\\left( f^{(1)} f_2(y) + f_2^{(1)}  f(y) \\right)\n\\end{equation}\n\n\\begin{equation}\\label{eq:f_4}\n\\begin{split}\n    f_4(y) = & d_4 - \\frac{1}{2}\\left( f_3^{(1)} f + f_2^{(1)} f_2 + f^{(1)} f_3 \\right)\\\\\n             & - \\frac{1}{6}\\Big( f_2^{(2)}(f,f) + f^{(2)}f_2 f + f^{(2)} f f_2\\\\\n             & \\qquad\\quad + f_2^{(1)} f^{(1)} f + f^{(1)}f_2^{(1)}f + f^{(1)}f^{(1)}f_2\n             \\Big)\\\\\n             & - \\frac{1}{24}\\Big(\n             f^{(3)}(f,f,f) + f^{(2)}f^{(1)}(f,f) + 2 f^{(2)}(f,f^{(1)}f) \\\\\n             &\\qquad\\quad + f^{(1)}f^{(2)}(f,f) + f^{(1)}f^{(1)}f^{(1)}f\n             \\Big)\n\\end{split}\n\\end{equation}\netc.\n\nRem. if $y\\in\\R^n$ then $f:\\R^n \\to \\R^n$ and $f^{(1)}:\\R^{n \\otimes 2}\\to\\R^n$ and so $f^{(k)} : \\R^{n\\otimes k}\\to\\R^n$. \n\nFor any hamiltonian system \n\\begin{equation}\\label{eq:hamiltonian system ode}\n    (\\dot p,\\dot q) = J^{-1}\\nabla H(p,q) \\qquad \\leftrightarrow \\qquad \\dot y = f(y)\n\\end{equation}\n\nwe calculate the first and second derivatives of $f = J^{-1}\\nabla H$\n\\begin{equation}\\label{eq:first and second derivatives of gradient hamiltonian}\n    f^{(1)} = J^{-1}D^2 H \\qquad\\qquad f^{(2)} = D J^{-1}D^2 H\\quad \\Big| \\left[ DJ^{-1}D^2H \\right]_{q_k} = \\frac{\\partial}{\\partial q_k} J^{-1}D^2H\n\\end{equation}\n\nthus for equation \\eqref{eq:f_2} we get\n\\begin{equation}\\label{eq:hamiltonian fprime of f}\n    f^{(1)}f(y) = J^{-1}D^2HJ^{-1}\\nabla H(p,q)\n\\end{equation}\nwe compute the components of \\eqref{eq:hamiltonian fprime of f}\n\\begin{equation}\\label{eq:hamiltonian fprime of f component pk}\n    \\left[f^{(1)}f\\right]_{p_k} = \\left[ J^{-1}D^2HJ^{-1}\\nabla H(p,q) \\right]_{p_k} = \\sum_{i=0}^d \\frac{\\partial^2 H}{\\partial p_i\\partial q_k}\\frac{\\partial H}{\\partial q_i} \n    - \\sum_{i=0}^d \\frac{\\partial^2 H}{\\partial q_i \\partial q_k}\\frac{\\partial H}{\\partial p_i}\n\\end{equation}\nand \n\\begin{equation}\\label{eq:hamiltonian fprime of f component qk}\n    \\left[f^{(1)}f\\right]_{q_k} = \\left[ J^{-1}D^2HJ^{-1}\\nabla H(p,q) \\right]_{q_k} = -\\sum_{i=0}^d \\frac{\\partial^2 H}{\\partial p_i\\partial p_k} \\frac{\\partial H}{\\partial q_i}\n    + \\sum_{i=0}^d \\frac{\\partial^2 H}{\\partial q_i \\partial p_k} \\frac{\\partial H}{\\partial p_i}\n\\end{equation}\n\nNote that in the equations \\eqref{eq:hamiltonian fprime of f component pk} and \\eqref{eq:hamiltonian fprime of f component qk} we can either think of $p_i$ and $q_i$ as individual components, or in the case of the n body problem in $6d$ dimensions $d=n$ the equations also work with $p_i,q_i\\in \\R^3$. With reference to the $n$-body problem we make use of the following identities \\eqref{eq:hamiltonian simplification identities} and \\eqref{eq:hamiltonian computed term qi} to simplify \\eqref{eq:hamiltonian fprime of f component qk}\n\\begin{equation}\\label{eq:hamiltonian simplification identities}\n    \\frac{\\partial^2H}{\\partial p_i\\partial q_k} = 0\\quad,\\quad \\frac{\\partial^2 H}{\\partial p_i\\partial p_k} = \\frac{\\delta_{ik}}{m_k}\\unit \\quad,\\quad \n    \\frac{\\partial^2 H}{\\partial q_i\\partial q_k} = \\frac{Gm_im_k}{\\left(\\xi_{jk}^T\\xi_{jk}\\right)^{3/2}}\\left( \\frac{3 \\xi_{jk}\\xi_{jk}^T}{\\xi_{jk}^T\\xi_{jk}} - \\unit_{3\\times 3} \\right) \\quad i\\neq k\n\\end{equation}\n\\begin{equation}\\label{eq:hamiltonian computed term qi}\n    \\frac{\\partial^2 H}{\\partial q_i^2} =  \\sum_{\\stackrel{j}{j\\neq i}} \\frac{Gm_im_j}{\\left(\\xi_{ij}^T\\xi_{ij}\\right)^{3/2}}\\left(\n    \\unit_{3\\times 3} - \\frac{3}{\\xi_{ij}^T\\xi_{ij}} \\xi_{ij}\\xi_{ij}^T \n    \\right)\n\\end{equation}\n\nThus \\eqref{eq:hamiltonian fprime of f component pk} and \\eqref{eq:hamiltonian fprime of f component qk} become \\eqref{eq:hamiltonian n body fprime of f}\n\\begin{equation}\\label{eq:hamiltonian n body fprime of f}\n    \\left[f^{(1)}f\\right]_{p_k} = \\sum_{\\stackrel{i=1}{i\\neq k}}^d \\frac{Gm_im_k}{\\left(\\xi_{ik}^T\\xi_{ik}\\right)^{3/2}}\\left( \n    \\frac{3\\xi_{ik}^T\\dot\\xi_{ik}}{\\xi_{ik}^T\\xi_{ik}}\\xi_{ik} - \\dot\\xi_{ik}\n    \\right) \\quad,\\quad\n    \\left[ f^{(1)}f \\right]_{q_k} = \\sum_{\\stackrel{i=1}{i\\neq k}} \\frac{G m_i}{\\left(\\xi_{ik}^T\\xi_{ik}\\right)^{3/2}}\\xi_{ik}\n\\end{equation}\n\n\n\n\n\\subsection{Algorithm for finding modified equation coefficients.}\nThe following section outlines the algorithms implemented for the calculations needed for the above. The source code is written in python and is available \\href{https://github.com/dcxSt/numerical_integrators/blob/master/modified_equations.py}{here} in the \\pyth{modified_equations.py} script. \n\nThe function \\pyth{next_gamma} enables us to find an expression for the $n$-th total derivative of \\eqref{eq:modified equation general formula} wrt $t$ : $\\frac{d^n}{dt^n}g(\\widetilde y)$, in terms of it's self and it's derivatives wrt $\\widetilde y$. We use the notation $g^{(n)}:= \\frac{d^n}{d{\\widetilde y}}g$. The algorithm is straightforward because $\\frac{d}{dt}g^{(n)}(\\widetilde y(t)) = g\\cdot g^{(n+1)}$. We represent the polynomial in $g$ and it's derivatives $g^{(n)}$ with a list who's elments are coefficients of $g^{(n)}$ together with multiplicities, the format is \\pyth{[[multiplicity , (coef g**1,coef g**2,...) ] , ...]}. For example \\eqref{eq:example format repr g polynomial} \n\n\\begin{equation}\\label{eq:example format repr g polynomial}\n    3\\cdot g g g^{(1)} g^{(2)} g^{(4)} + 2\\cdot g g^{(1)} \\longleftrightarrow \\text{\\pyth{[ [3,(2,1,1,0,1)] , [2,(1,1)] ]}}\n\\end{equation}\n\n\\pyth{next_gamma} works simply by taking an expression such as the RHS of \\eqref{eq:example format repr g polynomial} and returning the list representing it's total derivative wrt $t$.\n\nThe function \\pyth{gamma_to_pihsr} converts expressions in terms of $g$ and it's derivatives into expressions in terms of $\\{f,f_1,f_2,...\\}$ and their derivatives by means of convolutions. And the function \\pyth{expand_taylor_ytilde} takes a natural number $n$ and returns the $n$-th order polynomial approximation of $\\widetilde y(t)$, the output of this method is displayed in figure \\ref{fig:polynomial recurrence relations}\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=0.9\\linewidth]{Figures/truncated_polynomial_coefficients.png}\n    \\caption{Polynomials recurrence relations.}\n    \\label{fig:polynomial recurrence relations}\n\\end{figure}\n\n\\subsection{Truncated modified equations for integrators}\n\\label{section:truncated modified equations}\nNote on the notation, we make no distinction between $D^2H = \\nabla^2H = \\nabla^2H^T$, these are used interchangeable and denote the Hessian of the Hamiltonian. Reminder : the modified equation is given by $\\widetilde y$, this gives us\n\n$$\\dot{\\widetilde y} = g(\\widetilde y) = f(\\widetilde y) + hf_2(\\widetilde y) + h^2f_3(\\widetilde y) + \\cdots$$\n\nsee above sections for more context.\n\n\\subsubsection{Explicit Euler}\n\nThe numerical flow can be written exactly \\eqref{eq:modified numerical flow explicit euler} since $d_2,d_3,... \\equiv 0$\n\n\\begin{equation}\\label{eq:modified numerical flow explicit euler}\n    \\phi_h : (p,q) \\mapsto (p,q) + h\\left( -\\frac{\\partial H}{\\partial q}, \\frac{\\partial H}{\\partial p} \\right)\n\\end{equation}\n\nUsing the expressions \\eqref{eq:f_2} for $f_2$ and \\eqref{eq:f_3} for $f_3$, and with the hamiltonian expressions \\eqref{eq:hamiltonian system ode} and \\eqref{eq:first and second derivatives of gradient hamiltonian} for the first two derivatives of the infinitesimal propagator $J^{-1}\\nabla H$ we obtain $f^{(1)},f^{(2)}$, the terms of the modified equation read\n\n\\begin{equation}\\label{eq:modified equation general formula explicit euler f2}\n    f_2 = -\\frac{1}{2}J\\nabla^2HJ\\nabla H = \\frac{1}{2}\\left( H_{qq}H_p \\,\\,,\\,\\, H_{pp}H_q \\right)\n\\end{equation}\n\n\\begin{equation}\\label{eq:modified equation general formula explicit euler f3}\n\\begin{split}\n    f_3 = &\\,\\, -\\frac{1}{6}\\left( \n    J^{-1}D^3H \\left( J^{-1}\\nabla H , J^{-1}\\nabla H\\right) + J^{-1}D^2H J^{-1}D^2H J^{-1}\\nabla H\\right)\\\\\n    &\\,\\, + \\frac{1}{4} \\left( \n    J^{-1}D^3H (J^{-1}\\nabla H\\, ,\\, J^{-1}) + 2\\left( J^{-1}D^2H \\right)^2 J^{-1}\\nabla H\n    \\right)\n\\end{split}\n\\end{equation}\n\nTo second order the explicit Euler modified equation reads\n\n$$\ng(\\widetilde y) = f(\\widetilde y) + h\\frac{1}{2}\\left( H_{qq}H_p , H_{pp}H_q \\right) + O(h^2)\n$$\n\n\\subsubsection{Str\\\"omer Verlet}\nThe Str\\\"omer Verlet scheme \\eqref{eq:stromer verlet n body} has numerical flow \n$$\\phi_h : (p,q) \\mapsto (p,q) + hf^h(p,q) + h^2d_2^h(p,q) + h^3d_3^h(p,q) + O(h^4)$$\ntruncated to $O(h^3)$. Naturally the $O(h)$ term is the gradient $J^{-1}\\nabla H$; assuming, as it is in the $n$ body problem, that the mixed partials of the hamiltonian evaluate to zero $H_{pq}=H_{qp}=0$ the $O(h^2)$ and $O(h^3)$ terms read\n\\begin{equation}\\label{eq:stromer verlet d2 and d3}\n    d_2(p_n,q_n) = -\\frac{1}{2}\\left( \n    H_{qq}H_p \\,\\,\n    ,\\,\\,\n    H_{pp}H_q \\right)\n    \\qquad\n    d_3(p_n,q_n) = -\\frac{1}{4}\\left(\n    H_{qqq}(H_p,H_p) + \\frac{1}{3}H_{qq}H_{pp}H_q\n    \\,\\,,\\,\\, 0\\right)\n\\end{equation}\n\nThe above equations are evaluated at $(p,q)$. For the $n$ body problem these terms are straightforward to compute. Furthermore, we notice that $d_2 = -\\frac{1}{2} J^{-1}D^2HJ^{-1}\\nabla H = -\\frac{1}{2}f^{(1)}f$. \\tbf{(IMPORTANT! ARE THE EXPANSIONS OF SYMMETRIC NUMERICAL METHODS ODD FUNCTIONS, I THINK I MISUNDERSTAND THIS)} \n\nWe calculate the Jacobian \\eqref{eq:jacobian of stromer verlet numerical flow}\n\\begin{equation}\\label{eq:jacobian of stromer verlet numerical flow}\n    \\frac{\\partial \\phi_h(p,q)}{\\partial (p,q)} = \\frac{\\partial(p_{n+1},q_{n+1})}{\\partial (p_n,q_n)} = \\unit +\n    h\\begin{pmatrix} 0 & -H_{qq}\\\\ H_{pp} & 0 \\end{pmatrix} - \n    \\frac{h^2}{2} \\begin{pmatrix} H_{qq}H_{pp} & H_{qqq}H_p\\\\ 0 & H_{pp}H_{qq} \\end{pmatrix} + O(h^3)\n\\end{equation}\n\nwe show that the flow is symplectic to first order \\eqref{eq:stromer verlet symplecticity criterion} (confusingly this means $O(h^2)$ in the below equation. In fact, due to the symmetry of the Str\\\"omer Verlet scheme - symplecticity is preserved to 2nd order $O(h^3)$). For reference there are slightly easier ways of showing symplecticity in chapter VI of \\cite{Numerical}, but we use the Taylor expansions to illustrate that symplecticity is broken by the projections. \n\n\\begin{equation}\\label{eq:stromer verlet symplecticity criterion}\n\\begin{split}\n\\frac{\\partial(p_{n+1},q_{n+1})}{\\partial(p_n,q_n)}^T J\\frac{\\partial(p_{n+1},q_{n+1})}{\\partial(p_n,q_n)} & = J + h\\nabla^2H J^{-T}J + JJ^{-1}\\nabla^2H + h^2\\nabla^2HJ\\nabla^2H\\\\ &\\quad - \\frac{h^2}{2}\n\\left[\n\\begin{pmatrix} H_{pp}H_{qq} & 0\\\\ H_p^TH_{qqq} & H_{qq}H_{pp} \\end{pmatrix}J + J\\begin{pmatrix} H_{qq}H_{pp} & H_{qqq}H_p \\\\ 0 & H_{pp}H_{qq} \\end{pmatrix}\n\\right] + O(h^3)\\\\ & = J + O(h^3)\n\\end{split}\n\\end{equation}\n\nUsing \\eqref{eq:f_2}, \\eqref{eq:f_3}, \\eqref{eq:stromer verlet d2 and d3} we obtain the modified equations \\eqref{eq:stromer verlet modified eq f2}, \\eqref{eq:stromer verlet modified eq f3}\n\n\\begin{equation}\\label{eq:stromer verlet modified eq f2}\n    f_2 = 0\n\\end{equation}\n\nin words: \\eqref{eq:stromer verlet modified eq f2} is the conjugation of the Hessian of the hamiltonian, acting on the gradient of the hamiltonian. We rewrite \\eqref{eq:f_3} for ease of reference.\n\n$$f_3(y) = d_3(y) - \\frac{1}{6}\\left( f^{(2)} (f , f)(y) + f^{(1)} f^{(1)} f(y) \\right)$$\n\nThe followin identities \\eqref{eq:identity number 1},\\eqref{eq:identity number 2} come from from the fact that $H_{ppp} = H_{pq} = 0$ that there is only 1 out of 8 quadrants of the tensor $\\nabla^3H$ which is not empty: $H_{qqq}$, \n\\begin{equation}\\label{eq:identity number 1}\n    J^{-1}\\nabla^3 H(J^{-1}\\nabla H,J^{-1}\\nabla H) = (H_{qqq}(H_p,H_p) \\,,\\, 0)\n\\end{equation}\n\\begin{equation}\\label{eq:identity number 2}\n    J\\nabla^2HJ\\nabla^2HJ\\nabla H = J\\left[\\begin{array}{c;{2pt/2pt}c} H_{pp} & 0 \\\\ \\hdashline[2pt/2pt] 0 & H_{qq}\\end{array}\\right] J\\left[\\begin{array}{c;{2pt/2pt}c} H_{pp} & 0 \\\\ \\hdashline[2pt/2pt] 0 & H_{qq}\\end{array} \\right] J \\begin{bmatrix} H_p \\\\ H_q \\end{bmatrix}\n    = \\left( -H_{qq}H_{pp}H_q\\,\\,,\\,\\, H_{pp}H_{qq}H_p \\right)\n\\end{equation}\n\n\\begin{equation}\\label{eq:stromer verlet modified eq f3}\n\\begin{split}\n    f_3 & = -\\frac{1}{4}\\left( H_{qqq}(H_p,H_p) + \\frac{1}{3}H_{qq}H_{pp}H_q \\,,\\, 0\\right)\\\\\n    &\\quad +\\frac{1}{6} \\left(J\\nabla^3 H(J\\nabla H,J\\nabla H) + J\\nabla^2HJ\\nabla^2HJ\\nabla H \\right)\\\\\n    & = \\left( \\frac{11}{12}H_{qq}H_{pp}H_q -\\frac{7}{12} H_{qqq}(H_p,H_p) \\,\\,,\\,\\, - \\frac{5}{6}H_{pp}H_{qq}H_p \\right)  \\text{wrong need to revise this}\n\\end{split}\n\\end{equation}\n\n\n\n\\subsubsection{Modified equations for the Numerical flow of Projection methods}\n\n\\begin{equation}\\label{eq:naive projection method}\n    \\rho(y) = y + Dg^T \\mu \\qquad, g:\\R^{2d}\\to\\R^m\\quad g=0\\quad\\text{defines a manifold}\n\\end{equation}\n\nAbove $\\mu$ is an appropriate $m$-vector, it's components are of the form $\\frac{\\beta_0 - \\beta(y)}{\\nabla\\beta(y)^2}\\nabla\\beta(y)$, where $\\beta$ is a first integral and $\\beta_0$ is the constant value that defines an invariant level set wrt to $\\beta$.\n\nWe wish to study the behaviour of the projection methods we have analytically, in order to do so, we find equations for the modified numerical flow and doubly modify the modified equations.\n\nGiven the naive projection method \\eqref{eq:naive projection method}, which we use in conjunction with a numerical flow \\eqref{eq:numerical flow expansion}\n\n\\begin{equation}\\label{eq:numerical flow expansion}\n    \\phi_h(y) = y + hf(y) + h^2d_2(y) + h^3d_3(y) + O(h^4)\n\\end{equation}\n\nOur new flow is $\\hat \\phi_h := \\rho\\circ\\phi_h$. To simplify notation for the time being we assume $m=1$ and there is only one first integral, that we project onto a $2d-1$ dimensional invariant level surface defined by $\\mathfrak b := \\{y : \\beta(y) = \\beta_0\\}$. \n\n\\begin{equation}\\label{eq:modified numerical flow projected}\n    \\hat \\phi_h(y) = \\phi_h(y) + \\frac{\\beta_0 - \\beta(\\phi_h(y))}{\\nabla\\beta(\\phi_h(y))^2}\\nabla\\beta(\\phi_h(y))\n\\end{equation}\n\nexpanding we find\n\n\\begin{equation}\\label{eq:projection modification} \n\\frac{\\beta(\\phi_h(y))}{\\nabla\\beta(\\phi_h(y))^2}\\nabla\\beta(\\phi_h(y))\n= \\frac{\\beta(y + hf + h^2d_2 + h^3d_3 + o(h^4))}{\\nabla\\beta(y + hf + h^2d_2+O(h^3))^2}\\nabla\\beta(y + hf + h^2d_2 + O(h^3)) \n\\end{equation}\n\nwe expand each term in taylor series. Reminder : since $\\beta$ is a first integral and $f$ is along the conserved manifold, we have that $\\nabla\\beta(y)^T f(y) = 0$ or in shorthand $\\nabla\\beta^Tf =0$ (In the following equations we omit the arguments $y$). \n\n\\begin{equation}\\label{eq:term 1 e}\n\\begin{split}\n    \\beta(\\phi_h(y)) = & \\, \\beta(y) + \\cancel{h\\nabla\\beta^T f} + \\frac{h^2}{2}\\left[ D^2\\beta(f,f) + 2\\nabla\\beta^T d_2 \\right]\\\\\n    & + \\frac{h^3}{3!}\\left[ D^3\\beta(f,f,f) + 6D^2\\beta(d_2,f) + 6\\nabla\\beta^T d_3 \\right] + O(h^4)\n\\end{split}\n\\end{equation}\n\n\\begin{equation}\\label{eq:nabla beta expanded} \n    \\nabla\\beta(\\phi_h(y)) = \\nabla\\beta(y) + hD^2\\beta f + \\frac{h^2}{2}\\left[ D^3\\beta(f,f) + 2 D^2\\beta d_2 \\right] + O(h^3) \n\\end{equation} \n\nsquaring \\eqref{eq:nabla beta expanded} we obtain the denominator \\eqref{eq:term denominator}\n\n\\begin{equation}\\label{eq:term denominator}\n    |\\nabla\\beta|^2 \\circ \\phi_h(y) = |\\nabla\\beta|^2 + h \\nabla\\beta^T \\left(D^2\\beta f\\right) +\n    h^2\\left(\\nabla\\beta^T\\left( D^3\\beta(f,f) + 2 D^2\\beta d_2  \\right) + \\left( D^2\\beta f \\right)^2\\right) + O(h^3)\n\\end{equation}\n\nwe define $\\alpha_1 := D^2\\beta f$ and $\\alpha_2 := \\frac{1}{2}\\left( D^3\\beta(f,f) + 2 D^2\\beta d_2 \\right)$ and equation \\eqref{eq:term denominator} simplifies to \\eqref{eq:term denominator simplified}\n\n\\begin{equation}\\label{eq:term denominator simplified}\n    |\\nabla\\beta|^2 \\circ \\phi_h(y) = |\\nabla\\beta|^2 \\left( 1 - 2h\\frac{\\nabla\\beta^T\\alpha_1}{|\\nabla\\beta|^2} + h^2\\frac{2\\nabla\\beta^T\\alpha_2 + |\\alpha_1|^2}{|\\nabla\\beta|^2} \\right) + O(h^3)\n\\end{equation}\n\nusing the identity $\\frac{1}{1+x} = 1 - x + x^2 - x^3 + x^4 - ...$ we obtain an expression\n\\begin{equation}\\label{eq:term denominator expansion}\n    \\frac{1}{|\\nabla\\beta\\circ\\phi_h(y)|^2} = \\frac{1}{|\\nabla\\beta|^2}\\left(\n    1 - 2h\\frac{\\nabla\\beta^T\\alpha_1}{|\\nabla\\beta|^2} + h^2\\left[ \\frac{4\\left( \\nabla\\beta^T\\alpha_1\\right)^2}{|\\nabla\\beta|^4} - \\frac{2\\nabla\\beta^T\\alpha_2 + \\alpha_1^2}{|\\nabla\\beta|^2} \\right]\n    \\right) + O(h^3)\n\\end{equation}\n\ncombining \\eqref{eq:term 1 e} and \\eqref{eq:term denominator expansion} we obtain the coefficients $\\lambda_2$ and $\\lambda_3$ as in \\eqref{eq:lambda 2} and \\eqref{eq:lambda 3} in terms of $f = J^{-1}\\nabla H$, using these we derive an $O(h^3)$ expression for the pertubation \\eqref{eq:oh3 projective pertubation}\n\n\\begin{equation}\\label{eq:lambda 2}\n    \\lambda_2 := \\frac{ \\nabla^2\\beta \\left( J^{-1} \\nabla H , J^{-1} \\nabla H\\right) }{2|\\nabla\\beta|^2} + \\frac{\\nabla\\beta^T d_2}{|\\nabla\\beta|^2}\n\\end{equation}\n\n\\begin{equation}\\label{eq:lambda 3}\n\\begin{split}\n    \\lambda_3 := &\\,\\, \\frac{D^3\\beta \\left( J^{-1} \\nabla H\\, ,\\, J^{-1} \\nabla H \\, , \\, J^{-1}\\nabla H \\right)}{6 |\\nabla\\beta|^2} + \\frac{D^2\\beta\\left( J^{-1}\\nabla\\beta\\, , \\, d_2 \\right)}{|\\nabla\\beta|^2} + \\frac{\\nabla\\beta^T d_3}{|\\nabla\\beta|^2} \\\\\n    &\\,\\, - \\frac{\\nabla\\beta^T \\left( D^2\\beta J^{-1} \\nabla H \\right)}{|\\nabla\\beta|^2} \\cdot \\frac{D^2\\beta\\left( J^{-1} \\nabla H\\, , \\, J^{-1}\\nabla H\\right) + 2\\nabla\\beta^T d_2}{|\\nabla\\beta|^2}\n\\end{split}\n\\end{equation}\n\nTherefore\n\n\\begin{equation}\\label{eq:oh3 projective pertubation}\n    \\frac{\\beta(y) - \\beta(\\phi_h(y))}{\\nabla\\beta^T\\nabla\\beta(\\phi_h(y))}\\nabla\\beta(\\phi_h(y)) = - h^2 \\lambda_2 \\nabla\\beta(y) - h^3\\left( \\lambda_3\\nabla\\beta(y) + \\lambda_2 D^2\\beta J^{-1}\\nabla H(y)  \\right)  + O(h^4)\n\\end{equation}\n\nThus the numerical flow \\eqref{eq:modified numerical flow projected} expanded becomes\n\n\\begin{equation}\\label{eq:expanded projection modified equation flow}\n    \\hat \\phi_h(y) = y + hf(y) + h^2\\left( d_2(y) - \\lambda_2\\nabla\\beta \\right) + h^3\\left( d_3(y) - \\lambda_3\\nabla\\beta - \\lambda_2\\nabla^2\\beta J^{-1}\\nabla H \\right) + O(h^4)\n\\end{equation}\n\nwe can also define modified terms of the numerical flow \n\n\\begin{equation}\\label{eq:modified numerical flow terms of the equation}\n\\begin{split}\n    \\hat d_2 &:= d_2 - \\lambda_2\\nabla\\beta \\\\\n    \\hat d_3 &:= d_3 - \\lambda_3\\nabla\\beta - \\lambda_2\\nabla^2\\beta J^{-1}\\nabla H\n\\end{split}\n\\end{equation}\n\nand so the terms of the modified equation also change \n\n\\begin{equation}\\label{eq:modified equation for general projection method f2}\n    \\hat f_2(y) = \\hat d_2(y) - \\frac{1}{2} f^{(1)}f(y) = d_2 - \\lambda_2\\nabla\\beta - \\frac{1}{2}f^{(1)}f\n\\end{equation}\n\n\\begin{equation}\\label{eq:modified equation for general projection method first few terms}\n    \\dot{\\widetilde{y}} = g(\\widetilde{y}) = f(\\widetilde y) + h\\left( d_2(\\widetilde y) - \\lambda_2\\nabla\\beta(\\widetilde y) - \\frac{1}{2}f^{(1)}f(\\widetilde y) \\right) + O(h^2)\n\\end{equation}\n\nWhen we project onto multiple manifolds, for the naive projection method this means, we will assume that the other projection methods' qualitative behaviour is the same as for the naive method (which is easiest to analyze), having obtained evidence for this in the Kepler integration experiments (there are a tonne of pngs you can look at on the \\href{https://github.com/dcxSt/numerical_integrators}{github repo} in \\texttt{./figures/}). For multiple projections for the naive projection method it suffices to make the following substitution \n\n$$\\lambda_2\\nabla\\beta \\longleftrightarrow \\sum_i \\lambda_{2,i}\\nabla\\beta_i$$\n\ngiven that we projection onto a set of first integrals $\\{\\beta_i\\}$. The substitution is similarly linear for higher order terms. \n\n\n\\subsubsection{Calculations of projection terms.}\n\nWe calculate $\\lambda_2$ \\eqref{eq:lambda 2} for the energy manifold \\eqref{eq:lambda 2 energy first integral}\n\\begin{equation}\\label{eq:lambda 2 energy first integral}\n    \\lambda_2 = \\nabla^2H \\left( J\\nabla H , J\\nabla H \\right) = \\left( H_q^TH_{pp}H_q \\,\\,,\\,\\, H_p^TH_{qq}H_p \\right)\n\\end{equation}\n\nThe gradient and Hessian of the angular momentum we calculated for the two body problem in two dimensions \\eqref{eq:nabla l kepler},\\eqref{eq:hessian of angular momentum kepler}, it is similar the $n$ body problem in three dimensions. We calculate the hessian of the $x,y,z$ componants of angular momentum $L_3 = p_1x_2 - p_2x_1$ \n\n\\begin{equation}\\label{eq:lambda 2 angular momentum first integral}\n    \\lambda_2 = \\nabla^2L_z \\left( J\\nabla H , J\\nabla H \\right) = \n\\end{equation}\n\n\n\\section{Chaos, the Lyapunov spectrum and do the projection methods give rise to an attractor?}\n\nIn this section we search for an attractor in the modified (with projection terms) Kepler and n-body equations. My suspicions where first aroused by the stabilizing of some solutions in the Kepler problem when running some numerical experiments, the orbits with low eccentricity seemed to converge onto circular orbits (figure \\ref{fig:numerical experiments kepler}), this is what prompted the search for an attractor. Liouville's theorem states that phase space volume is conserved in Hamiltonian systems, this result also follows from symplecticity and conservation of the symplectic two form; it follows from Liouville's theorem that symplectic systems do not have attractors In fact, the chaotic ones are often ergodic on their conserved manifolds (LAST LINE: EITHER GET RID OF THIS GLIB STATEMENT OR MAKE IT RIGOROUS). \n\n\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=0.47\\linewidth]{Figures/kepler_experiments/invarients_config1_exp_euler_Naive_h_001_STEPS_100000.png}\n    \\includegraphics[width=0.47\\linewidth]{Figures/kepler_experiments/invarients_config4_stromer_verlet_None_h_005_STEPS_100000.png}\n    \\caption{Numerical Experiments with Kepler System. Left: projection method. Right: Str\\\"omer Verlet symplectic integrator.}\n    \\label{fig:numerical experiments kepler}\n\\end{figure}\n\n\nIn this section we look for evidence of an attractor, analytically in the modified equations and numerically in experiments. \n\nAn \\textbf{Attractor} is DEFINE ATTRACTOR (I think it's just a submanifold embedded in the phase space which attracts things, it has a basin of attraction)\n\nThe \\textbf{basin of attraction} of an attractor DEFINE BASIN OF ATTRACTOR (PROBABLY EXACTLY WHAT I THINK IT IS)\n\n\n\n\\subsection{Lyapunov Exponents}\nIn this section we use the notation of \\cite{PikovskyPoliti}.\n\n\\tbf{Def.} \n\nTHEOREM, IN HAMILTONIAN SYSTEMS, THE LYAPUNOV EXPONENTS ARE THE SAME EVERYWHERE\n\n\\subsubsection{Gramm Schmidt decomposition : Algorithm for finding Lyapunov exponents 1}\n\n\nIMPLEMENT SPECTRUM FINDER OF LYAPUNOV EXPONENTS, FIND THE SPECTRUM FOR SOME SYMPLECTIC METHOD, THE BIGGEST ONE SHOULD BE POSITIVE AND THEIR SUM SHOULD ADD TO ZERO.\n\n\n\\subsection{Calculating Lyapunov exponents for symplectic integrators.}\nWe expect the Lyapunov spectrum to be independent of initial conditions. \n\n\\subsection{Implementation of modified equations for the Kepler problem.}\nWe implement the modified equations, expanded to second order, and integrate them with a small step size to see if they behave similarly to the integrators with larger step-sizes. A welcome side-effect of implementing these is that the code provides us with strong evidence that the results from the previous section, `Backwards Error Analysis' are correct. \n\n% put a table here with the results of your tests\n% put a table here with the results of your tests\n% put a table here with the results of your tests\n% put a table here with the results of your tests\n\n\\subsubsection{Implementing the modified equation integrator for the Explicit Euler method (no projection)}\nThe modified equation is\n$$g(\\widetilde y) = f(\\widetilde y) - \\frac{1}{2}f^{(1)}f(y) + O(h^2) = J^{-1}\\nabla H - \\frac{1}{2}J^{-1}\\nabla^2 H J^{-1}\\nabla H$$\n\nwe integrate with 100* smaller step-sizes.\n\n\n\\subsubsection{Implementing the modified equation integrator for the Str\\\"omer Verlet method}\nWe implement the `Projected Str\\\"omer Verlet' modified equation with $h=0.1$ and integrate it using the explicit Euler method but with a much smaller step-size. For ease of reference the `Projected Str\\\"omer Verlet' method is written below \\eqref{write this equation below}.\n\n%\\subsubsection{Implementing the modified equation for Explicit Euler integrator with projection}\n\n%\\subsubsection{Implementing the modified equation for Str\\\"omer Verlet integrator with projection}\n\n\\subsubsection{Implementing exaggerated modified equations}\nWe then multiply the $O(h^2)$ projection terms by a constant to make them more pronounced, to see if this would give me an attractor. (this ended up being very messy and didn't give me results I'd hoped it would)\n\n\n\\section{Conclusions}\n\\subsection{Mathematical Conclusions}\nDid some theoretical and applied mathematics: studied ordinary differential equations paying attention to symmetries (important in physics), hamiltonian systems \\& symplectic manifolds. \n\nWhat did I learn about numerical integrators (history + people, how the methods evolved, why they evolved, for what where they used in the early days)?\n\nWhat did I learn about symplectic geometry (as an old field, as a theory that comes from mathematical physics and that was a generalization from Hamiltonians, how it's worded today in terms of exterior calculus skew-symmetric two-forms, about the emerging field of geometric information theory)?\n\nWhat did you read about that was out of your depths (renormalization of manifolds, ...)?\n\n\\subsection{Critical analysis of learning and process}\nOne of the aims of this project was to learn how to do research independently. I can't make up my mind whether the problem stems from disorganization, or some deeper lack of connection with the subject matter which prevents flow; or perhaps it is just a normal part of the learning process to struggle and feel somewhat inadequate at times.\n\nI read a lot of random articles that were only vaguely relevant to what I was working on, many things I read I also didn't understand. Don't know if this is a good or bad thing.\n\nThere where periods when I felt inspired and spent hours reading or coding at a time, and there were periods when I felt uninspired and either did something else or forced myself to do research despite myself. I'm struggling to find a good balance between straining myself and doing too little work; when you feel lethargic is it the case that you should force yourself to work until you are more inspired or should will that just demotivate you? And when you *are* motiviated should you keep working until you don't? - this strikes me as counter-productive because ideally you want to finnish well with a good idea of what you want to do next, rather than keep going until you trail off. The question of finding inspiration and flow has been plaguing me for a while but I don't seem to have made much headway answering it - am I asking the wrong question?\n\n*different take on same theme as above paragraph:* \nI'm disappointed that I didn't end up getting completely absolved by the project, I think my approach to learning is definitely improving (becomming more effective) and there where times when all I could think about was the project and what I was currently doing, but this feeling didn't permeate everything. What I mean to say is that the project was enjoyable but not something I would loose sleep over, or wake up in the middle of the night with a revelation about, as was the case in high-school sometimes I lay awake for hours thinking about math, and on a few occasions it woke me up up at 3am and I would just start writing math for the next couple hours; this level of inspiration is something I'm trying to master and tame so as to be able to make more of it and get it on demand, I haven't got there yet - my aim is to try achieve this before end of undergrad. \n\n**Future work.**\nIt seems I opened some doors which lead down various avenues of exploration: I want to learn more about Lie groups \\& algebras (this is what I'm currently reading about), hamiltonian systems, the poisson braket, numerical schemes ++; then I also want to capitalize on my code to make more simulations of realistic n-body problems such as earth / sun / moon system, or a real solar system, or satalites and display the Lyapunov of different integrators for these types of problem with different integrators. I also want to read more articles about integration methods to know more about the context into which my project fits so that I can write something reasonable if I make an article for arxiv or to send to journals.\n\n\\subsection{Skills acquired}\nGot better at reading literature. More coding is never a bad thing, I actually had quite a bit of fun coding.\n\n\n\\subsection{Future work}\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Articles to refrence that I have not added to bibtex yet}\nCOMMENTED ARTICLE HERE\n%\\href{https://iopscience.iop.org/article/10.1088/0951-7715/3/2/001/pdf?casa_token=IcqtzV26vEMAAAAA:XQVhqcUQ_u24pqr29K8_U0uz0hHPzSwnWfWMHVbIYVfR1CP4oU7VDSg1tF8hE7A2EwsWJbfTIvc}{https://iopscience.iop.org/article/10.1088/0951-7715/3/2/001/pdf?casa_token=IcqtzV26vEMAAAAA:XQVhqcUQ_u24pqr29K8_U0uz0hHPzSwnWfWMHVbIYVfR1CP4oU7VDSg1tF8hE7A2EwsWJbfTIvc}\n\n\\bibliographystyle{plain}\n\\bibliography{MyBibliography}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\newpage\n\\appendix\n% All the information that is required to follow your work but that is too detailed for the main text.\n\n\\section{Peter E. Hydon, Symmetry Methods for Differential Equations - A Beginner's Guide}\n\n\\section{Geometric Numerical Integrations - Structure Preserving Algorithms for Ordinary Differential Equations.}\n\n\\section{Papers}\n\n\\section{Appendix B - Log}\n\n\\subsection{Friday 8 May 2020}\n\\subsubsection{Goals}\n\\begin{itemize}\n    \\item skim `Numerical integration structure preserving...' book\n    \\item understand what a symplectic manifold is abstractly and wrt hamiltonian systems\n    \\item read a little about symplectic transformations\n    \\item re-read ex undergrad paper on numerical integration\n    \\item read Omar's paper once though (just skim)\n    \\item skim `symmetry methods...' book once more and finish in-depth reading of chapter 2\n\\end{itemize}\n\n\\subsubsection{Log}\nWent on a Wikipedia spree : KAM, Pertubation theory, Numerical Integration, Hamiltonian mechanics, Fiber bundle, Jet bundle, Spray, Riemannian geometry, Symplectic vector space, Symplectic matrix, Symplectic - learned some meta-things perhaps slightly meta / intangible but nevertheless I think useful knowledge. \n\n\n\\subsection{Weekly Goals - week of 2020.05.11}\nRead in depth symmetry methods for differential equations, answering all the questions. \n\nSkim-read one chapter of the numerical methods for integration every day. \n\nAt the end of each day do a review session where you go over what you learned. \n\nDo this at the end of the week too, this one you document. \n\n\\subsection{Monday 11 May 2020}\nRead mainly the symmetry book today. \n\n\\subsection{Thursday 11 May 2020}\nGoal for week : implement the runga-kunga methods from \\cite{Duruisseaux} and see what you can find on the projection methods discussed with Gantumur during the meeting. \n\n\n\\subsection{Weekly Review - week of 2020.05.11}\n\n\\subsection{Weekly Goals - week of 2020.05.18}\n\n\\section{Appendix C}\\label{appendix c}\n\\subsection{Random Attractors}\nHere are twelve of my favourite random attractors generated using code form \\href{http://paulbourke.net/fractals/lyapunov/}{Paul Bourke's website}, thank you Paul Bourke. The way the algorithm works is it randomly generates a 5th order (non linear) ODE in two variables, then solves for the trajectories of several randomly generated points. Most of the time the orbits tend to infinity, sometimes there is an integer dimensional (Hausdorff dimension) attractor, but sometimes these equations give rise to a strange attractors (\\ref{fig:random chaotic attractors} , \\ref{fig:random chaotic attractors2}). \n\n\\newpage\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=0.47\\linewidth]{Figures/random_attractors/18842.png}\n    \\includegraphics[width=0.47\\linewidth]{Figures/random_attractors/2494.png}\n    \\includegraphics[width=0.47\\linewidth]{Figures/random_attractors/4547.png}\n    \\includegraphics[width=0.47\\linewidth]{Figures/random_attractors/63041.png}\n    \\includegraphics[width=0.47\\linewidth]{Figures/random_attractors/76507.png}\n    \\includegraphics[width=0.47\\linewidth]{Figures/random_attractors/78151.png}\n    \\caption{Random Chaotic Attractors}\n    \\label{fig:random chaotic attractors}\n\\end{figure}\n\n\\newpage\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=0.47\\linewidth]{Figures/random_attractors/84148.png}\n    \\includegraphics[width=0.47\\linewidth]{Figures/random_attractors/882.png}\n    \\includegraphics[width=0.47\\linewidth]{Figures/random_attractors/79621.png}\n    \\includegraphics[width=0.47\\linewidth]{Figures/random_attractors/8584.png}\n    \\includegraphics[width=0.47\\linewidth]{Figures/random_attractors/862.png}\n    \\includegraphics[width=0.47\\linewidth]{Figures/random_attractors/54966.png}\n    \\caption{Random Chaotic Attractors}\n    \\label{fig:random chaotic attractors2}\n\\end{figure}\n\n\n\n\\newpage\n\n\\subsection{Henon-Heiles Attractor}\n``The H\\'enon-Heiles model was created for describing stellar motion, followed for a very long time, inside the gravitational potential $U_0(r,z)$ of a galaxy with cylindrical symmetry (H\\'enon \\& Heiles 1964). Extensive numerical experimentations should help to answer the question, if there exists, besides the known invariants $H$ and $L$, a \\textit{third} invariant. Despite endless tentatives of analytical calculations during many decades, such a formula had not been found.\n\nAfter a reduction of dimension, a Hamiltonian in two degrees of freedom of the form\n\\begin{equation}\\label{eq:heinon heiles hamiltonian}H(p,q) = \\frac{1}{2} \\left( p_1^2 + p_2^2 \\right) + U(q)\n\\end{equation}\n\nis obtained and the question is, if such an equation has a \\textit{second} invariant. Here H\\'enon and Heiles put aside the astronomical origin of the problem and choose\n$$U(q) = \\frac{1}{2}\\left( q_1^2 + q_2^2 \\right) + q_1^2q_2 - \\frac{1}{3}q_2^3$$\nWhen $U$ approaches $\\frac{1}{6}$, the level curves of $U$ tend to an equilateral triangle, whose verties are saddle points of $U$. The corresponding system has solutions with nontrivial properties. For given initial values with $H(p_0,q_0)<\\frac{1}{6}$ and $q_0$ inside the triangle $U \\leq \\frac{1}{6}$, the solution stays there and moves somehow like a mass point gliding on this surface (see figure \\ref{fig:hennon-heiles pointcare cuts}).\n\n\\textbf{Poincar\\'e Cuts.} We fix the energy $H_0$ and put $q_{10} = 0$. Then for any point $P_0 = (q_{20} , p_{20})$, we obtain $p_{10}$ from \\eqref{eq:heinon heiles hamiltonian} as $p_{10} = \\sqrt{2H_0 - 2U_0 - p_{20}^2}$, where we choose the positive root. We then follow the solution until it hits again the surface $q_1 = 0$ in the positive direction $p_1 > 0$ and obtain a point $P_1 = (q_{21},p_{21})$; in the same way we compute $P_2 = (q_{22},p_{22})$, etc. For the same initial values and with $H_0 \\in [\\frac{1}{12} , \\frac{1}{6}]$, the solution gives the Pointcar\\'e cuts below (fig \\ref{fig:hennon-heiles pointcare cuts})\" \\cite{Numerical}\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=0.88\\linewidth ]{\"Figures/pointcare cuts hennon-heiles/hennon-heiles_pointcare_cuts\"}\n    \\caption{Hennon-Heiles System, Pointcar\\'e Cuts}\n    \\label{fig:hennon-heiles pointcare cuts}\n\\end{figure}\n\n\\subsection{Other Stuff}\n\nSome symplectic integrators have cool graphical properties, here is a figure of the symplectic Str\\\"omer Verlet method applied to the kepler problem.\n\n\n\\end{document}", "meta": {"hexsha": "a722232ca6355eb67fa076feac1a6782197ec734", "size": 100840, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/main.tex", "max_stars_repo_name": "dcxSt/numerical_integrators", "max_stars_repo_head_hexsha": "7b7e2fbfa7c4df981e86934446d87272965baf28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tex/main.tex", "max_issues_repo_name": "dcxSt/numerical_integrators", "max_issues_repo_head_hexsha": "7b7e2fbfa7c4df981e86934446d87272965baf28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-06T19:32:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-06T19:32:38.000Z", "max_forks_repo_path": "tex/main.tex", "max_forks_repo_name": "dcxSt/numerical_integrators", "max_forks_repo_head_hexsha": "7b7e2fbfa7c4df981e86934446d87272965baf28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 69.9306518724, "max_line_length": 1277, "alphanum_fraction": 0.7113447045, "num_tokens": 32510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.3335470215551666}}
{"text": "\\documentclass[revision-guide.tex]{subfiles}\n%% Current Author: LT\n\\setcounter{chapter}{1}\n\\begin{document}\n\\chapter{Gravitational Fields}\n\\spec{recall and use the fact that the gravitational field strength g is equal to the force per unit mass and hence that weight W = mg}\n\nA \\textbf{field} is a region where a particle experiences a force. If this is applied to gravitation, then we can say that a\n\\textbf{gravitational} field is a region where a \\textbf{mass}\nexperiences a force.\n\nYou can only tell if a field exists when it exerts a force on something.\nIt is a way of envisaging (seeing in your mind's eye) the size and the\ndirection of the force that would be exerted on a particle when placed\nin that field.\n\nA gravitational field is produced by anything with mass.\n\nTherefore, a gravitational field is a way of envisaging what would\nhappen to a mass if it were placed in the field due to another mass.\n\nThe field is usually represented by lines which show both the\n\\textbf{direction} and \\textbf{strength} of the field.\n\nThe \\textbf{strength} of a gravitational field (the field strength) at\nany point is the force felt \\textbf{per unit mass} at that point. This\nis a \\textbf{definition.}\n\nIt can be written as a word equation:\n\nGravitational field strength at a point (N/kg)= Force felt by mass (measured\nin Newtons)/Size of mass (measured in kilograms)\n\nOr in symbols:\n\n\\[g = \\frac{F}{m} \\]\n\nThe force, F, felt by any object on the surface of the Earth due to the\ngravitational field strength of the Earth is known as its\n\\textbf{weight.} It is given the symbol \\textbf{W}.\n\nThis means that we can re-write equation above for the field strength at\nthe surface of the Earth by putting W instead of F.\n\n\\[g = \\frac{W}{m}\\]\n\nThis then rearranges to an equation that you have all seen before:\n\n\\[W = mg\\]\n\nThus the weight of an object on the surface of the Earth is its mass\nmultiplied by the gravitational field strength g.\n\n\\spec{recall that the weight of a body appears to act from its centre of gravity}\n\nThe centre of gravity of an object is the point where the weight acts or\nappears to act.\n\nThus, when you draw a free-body force diagram for any object in a\ngravitational field, you draw \\textbf{one} arrow from the centre of\ngravity of the object to represent the force due to the field. On the\nEarth this is, of course, the weight and the arrow points vertically\ndownwards.\n\n\\spec{sketch the field lines for a uniform gravitational field (such as near the surface of the Earth)}\n\nA uniform field is a field where the field strength is the same at all\npoints in the field.\n\nThis means that for a gravitational field the force felt per unit mass\n(see definition) is the same at all points.\n\nThe surface of the Earth is a very good approximation to a uniform\nfield.\n\nTherefore if you draw a diagram of the Earth's gravitational field at\nthe Earth's surface over a small area, it will look like Figure \\ref{fig:uniform-field}\n\n\\begin{figure}[!h]\n\t\\begin{center}\n\t\t\\includegraphics[width=\\textwidth]{figs/chapt-2/uniform-field.pdf}\n\t\\end{center}\n\t\\caption{Uniform Field}\n\t\\label{fig:uniform-field}\n\\end{figure}\n\nAs you can see, the field lines are \\textbf{parallel} and\n\\textbf{evenly-spaced.} This is always the case for a uniform field.\n\n\\spec{explain the distinction between gravitational field strength and force and explain the concept that a field has independent properties.}\n\nThere is a very important distinction to make between\n\\textbf{gravitational field strength} and \\textbf{force} at this point:\nThe field strength at any point is the same for all bodies in the field\nand is the force felt per kilogram, but the force is different and\ndepends on the size of the mass there.\n\nThis is best illustrated with an example: If a mass of 60kg is in the\nEarth's gravitational field at the surface of the Earth, then we can\ncalculate the force acting on it, its weight, using equation (3):\n\n\\[W = mg = \\SI{60}{\\kg} \\times \\SI{9.8}{\\N\\per\\kg} = \\SI{590}{\\N}\\]\n\nSo the force felt by the 60kg mass is 590N but the field strength for\nthe mass \\textbf{and for any other mass} is 9.8Nkg\\textsuperscript{-1}.\nSo the field strength is fixed by your position in the field and the\nsize of the mass that is exerting the field, and nothing else. The force\ndepends on the mass in the field as well.\n\n\\end{document}\n", "meta": {"hexsha": "858f02ebb7b44400c987b6ede8111089debf5671", "size": 4317, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "2-gravitational-fields.tex", "max_stars_repo_name": "sirioq/physics-PreU", "max_stars_repo_head_hexsha": "d0f993750d660df38f05085ccf3b351d2ea3dd7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2017-03-13T19:37:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T21:47:07.000Z", "max_issues_repo_path": "2-gravitational-fields.tex", "max_issues_repo_name": "sirioq/physics-PreU", "max_issues_repo_head_hexsha": "d0f993750d660df38f05085ccf3b351d2ea3dd7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2016-12-19T16:46:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-24T08:14:03.000Z", "max_forks_repo_path": "2-gravitational-fields.tex", "max_forks_repo_name": "sirioq/physics-PreU", "max_forks_repo_head_hexsha": "d0f993750d660df38f05085ccf3b351d2ea3dd7d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 22, "max_forks_repo_forks_event_min_datetime": "2016-12-19T16:16:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-09T13:48:59.000Z", "avg_line_length": 38.8918918919, "max_line_length": 142, "alphanum_fraction": 0.7667361594, "num_tokens": 1095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.33354701819451904}}
{"text": "%% -----------------------------------------------------------------------------\n\\subsection{\\Aname{}\\ Theorems}\n\n\\begin{theorem}\\label{A-sync}\n  If\\/ $\\fwellformedO{\\sexpr_0}{\\stoptional}$\n  then\\/ $\\fwellformed{\\fforget{\\sexpr_0}}{\\stoptional}$\n  and\\/ $\\sexpr_0 \\credAanns \\sexpr_1$\n  iff\\/ $\\fforget{\\sexpr_0} \\credA \\fforget{\\sexpr_1}$\n\\end{theorem}\n\\begin{lamportproof}\n  By the definition of $\\credAanns$.\n\\end{lamportproof}\n\n\\begin{theorem}[type soundness]\\label{A-S-type-soundness}\n  If\\/ $\\fwellformed{\\sexpr_0}{\\stype_0}$\n  then one of the following holds:\n  \\begin{itemize}\n    \\item $\\sexpr_0 \\rredA \\svalue_0$ and\\/ $\\snil \\sWTA \\svalue_0 : \\stype_0$\n    \\item $\\sexpr_0$ diverges\n    \\item $\\sexpr_0 \\rredA\n      \\ctx_0[\\edynb{\\sbnd_1}{\\ctx[\\sexpr_1]}]$ and\\/ $\\sexpr_1 \\nredAD\n      \\tagerrorD$\n    \\item $\\sexpr_0 \\rredA \\divisionbyzeroerror$\n    \\item $\\sexpr_0 \\rredA \\boundaryerror{\\sblist_1}{\\svalue_1}$\n  \\end{itemize}\n\\end{theorem}\n\\begin{lamportproof}\n  By progress and preservation lemmas (\\lemmaref{A-type-progress} and \\lemmaref{A-type-preservation}).\n\\end{lamportproof}\n\n\\begin{theorem}[dynamic soundness]\\label{A-D-type-soundness}\n  If\\/ $\\fwellformed{\\sexpr_0}{\\tdyn}$\n  then one of the following holds:\n  \\begin{itemize}\n    \\item $\\sexpr_0 \\rredA \\svalue_0$ and\\/ $\\snil \\sWTA \\svalue_0 : \\tdyn$\n    \\item $\\sexpr_0$ diverges\n    \\item $\\sexpr_0 \\rredA \\ctx_0[\\sexpr_1]$ and\\/ $\\sexpr_1\n      \\nredAD \\tagerrorD$\n    \\item $\\sexpr_0 \\rredA \\divisionbyzeroerror$\n    \\item $\\sexpr_0 \\rredA \\boundaryerror{\\sblist_1}{\\svalue_1}$\n  \\end{itemize}\n\\end{theorem}\n\\begin{lamportproof}\n  By progress and preservation lemmas (\\lemmaref{A-type-progress} \\& \\lemmaref{A-type-preservation}).\n\\end{lamportproof}\n\n\\begin{theorem}[incomplete monitoring]\\label{A-incomplete-monitoring}\n  There exist\\/ $\\sexpr_0,\\sexpr_1,\\sowner_0,\\stoptional$\n  such that\\/ $\\fwellformedO{\\obars{\\sexpr_0}{\\sowner_0}}{\\stoptional}$\n  and\\/ $\\sexpr_0 \\rredAanns \\sexpr_1$\n  and\\/ $\\cdot; \\sowner \\not \\sWSOP \\sexpr_1$.\n\\end{theorem}\n\\begin{lamportproof}\n{\\newcommand{\\thetype}{(\\tfun{\\tint}{\\tint})}\n  \\newcommand{\\thefun}{\\efun{\\svar_0}{(\\esum{\\tint}{\\svar_0}{1})}}\n \\newcommand{\\theargval}{\\efun{\\svar_1}{0}}\n \\newcommand{\\theexprA}{\\estab{\\obnd{\\sowner_0}{\\thetype}{\\sowner_1}}{\\obars{\\edynb{\\obnd{\\sowner_1}{\\thetype}{\\sowner_2}}{\\obars{\\thefun}{\\sowner_2}}}{\\sowner_1}}}\n  \\newcommand{\\theexprB}{\\obars{\\eapp{\\tdyn}{\\sexpr_0}{(\\thefun)}}{\\sowner_0}}\n\n  Let\\/\n\n  $\\begin{array}{lll}\n   \\sexpr_f & \\eeq & \\theexprA\\\\\n    \\sexpr_0 & \\eeq & \\theexprB \\\\\n    \\svalue_f & \\eeq & \\obars{\\ehist{\\eset{\\obnd{\\sowner_0}{\\thetype}{\\sowner_1},\n                \\obnd{\\sowner_1}{\\thetype}{\\sowner_2}}}{\\obbars{\\thefun}{\\fconcat{\\sowner_2}{\\sowner_1}}}}{\\sowner_0}\\\\\n    \\sexpr_1 & \\eeq &\n    \\obars{\\eapp{\\tdyn}{\\svalue_0}{(\\theargval)}}{\\sowner_0} \n  \\end{array}$\n \n   \\smallskip\n  With a straight-forward application of the reduction rules we obtain:\n\n  \\(\\begin{array}[t]{l@{~}l}\n    \\obars{\\sexpr_f}{\\sowner_0}\n    & \\rredAanns \\obars{\\estab{\\obnd{\\sowner_0}{\\thetype}{\\sowner_1}}{\\obars{\\emon{\\obnd{\\sowner_1}{\\thetype}{\\sowner_2}}{\\obars{\\thefun}{\\sowner_2}}}{\\sowner_1}}}{\\sowner_0}\n    \\\\\n    & \\rredAanns \\obars{\\ehist{\\eset{\\obnd{\\sowner_0}{\\thetype}{\\sowner_1}, \\obnd{\\sowner_1}{\\thetype}{\\sowner_2}}}{\\obbars{\\thefun}{\\fconcat{\\sowner_2}{\\sowner_1}}}}{\\sowner_0}\n    \\\\\n    & \\eeq \\svalue_f\n    \\\\\n    \\zerowidth{\\mbox{therefore}}\n    \\\\\n    \\sexpr_0\n    & \\rredAanns \\sexpr_1 \n  \\end{array}\\)}\n\\end{lamportproof}\n\n\\begin{theorem}[sound and complete blame]\\label{A-correct-blame}\n  If\\/ $\\cdot; \\sownertop \\sWL \\sexpr_0$ and\\/\n      \\(\\sexpr_0\n        \\rredAanns  \\boundaryerror{\\obnd{\\sowner_0}{\\stype_1}{\\sowner_1}}{\\svalue_1}\\)\n          then\n          \\begin{itemize}\n            \\item\n              either\\/ $\\fhasbnd{\\obnd{\\sowner_0}{\\stype_1}{\\sowner_1}}{\\sexpr_0}$\n              or\\/\n              $\\fhasbnd{\\obnd{\\sowner_1}{\\stype_1}{\\sowner_0}}{\\sexpr_0}$,\n              and\n             \\item $\\fblistsenders{\\sblist_1}=  \\fvalueowners{\\svalue_1}$\n          \\end{itemize}\n\\end{theorem}\n\n{\\newcommand{\\Abcbeo}{$\\sexpr_0 \\rredAanns \\ctx_0[\\edynb{\\obnd{\\sowner_1}{\\stype_1}{\\sowner_2}}{\\svalue_1}] \\credAanns \\boundaryerror{\\sblist_1}{\\svalue_1}$}\n\\newcommand{\\Abcitems}{%\n  \\begin{enumerate}\n    \\item\n      \\(\\forall\\,\\sbnd_1 \\in \\sblist_1\\),  either\\/ \\(\\fhasbnd{\\sexpr_0}{\\sbnd_1}\\) or \\(\\fhasbnd{\\sexpr_0}{\\fflip{\\sbnd_1}}\\)\n    \\item\n      one of the following holds:\n      \\begin{enumerate}\n        \\item\n          $\\svalue_1 \\not\\in (\\ehist{\\sblist}{\\obbars{\\svalue}{\\sownerlist}})$\n          and\\/ $\\snil; \\sowner_2 \\sWLA \\svalue_1$\n        \\item\n          $\\svalue_1 \\eeq (\\ehist{\\sblist_2}{\\obbars{\\svalue_2}{\\sownerlist_2\\sowner_2}})$\n          and\\/ $\\fbndeqowners{\\sblist_2}{\\fconcat{\\sowner_2}{\\sownerlist_2\\sowner_2}}$\n          and\\/ $\\snil; \\flast{\\sowner_3} \\sWLA \\svalue_2$\n      \\end{enumerate}\n  \\end{enumerate}}\n\n\\begin{theorem}[blame correctness]\\label{A-S-blame-correctness}\n  If\\/ $\\fwellformedO{\\obars{\\sexpr_0}{\\sowner_0}}{\\stoptional}$ then one of the following holds:\n  \\begin{itemize}\n    \\item $\\sexpr_0 \\rredAanns \\svalue_0$ and\\/ $\\snil; \\sowner_0 \\sWLA \\svalue_0$\n    \\item $\\sexpr_0$ diverges\n    \\item $\\sexpr_0 \\rredAanns \\tagerrorD$\n    \\item $\\sexpr_0 \\rredAanns \\divisionbyzeroerror$\n    \\item \\Abcbeo{} and furthermore: \\Abcitems\n  \\end{itemize}\n\\end{theorem}\n\\begin{lamportproof}\\leavevmode\n  \\step{1}{\\suffices{\\assume{\\Abcbeo} \\prove{\\Abcitems}}}\n    \\begin{pfproof}\n      by \\lemmaref{A-label-progress} and \\lemmaref{A-label-preservation}\n    \\end{pfproof}\n  \\step{2}{$\\obnd{\\sowner_1}{\\sowner_2} \\sWLA \\stype_1$ and\\/ $\\sowner_2 \\sWLA \\svalue_1$}\n    \\begin{pfproof}\n      by \\lemmaref{A-label-preservation}\n    \\end{pfproof}\n  \\step{3}{\\(\\forall \\sbnd_1 \\in \\sblist_1\\)  either \\(\\sbnd_1 \\in \\sexpr_0\\) or \\(\\fflip{\\sbnd_1} \\in \\sexpr_0\\)}\n    \\begin{pfproof}\n      by \\lemmaref{A-source-boundary}\n    \\end{pfproof}\n  \\step{4}{either\\/ $\\sblist_1 \\eeq \\obnd{\\sowner_1}{\\sowner_2}$\n           \\\\ or\\/ $\\svalue_1 \\eeq (\\ehist{\\sblist_0}{\\svalue_0})$ and\\/ $\\sblist_1 \\eeq \\fconcat{\\obnd{\\sowner_1}{\\sowner_2}}{\\sblist_0}$}\n    \\begin{pfproof}\n      by the definition of\\/ $\\credAanns$\n    \\end{pfproof}\n\\end{lamportproof}}\n\n\\begin{corollary}[minimal blame info]\n  If\\/ $\\fwellformed{\\sexpr_0}{\\stoptional}$\n  and\\/ $\\sexpr_0 \\rredA \\boundaryerror{\\sblist_1}{\\svalue_1}$\n  then\\/ $\\sblist_1 \\neq \\snil$\n\\end{corollary}\n\\begin{lamportproof}\n  by \\theoremref{A-S-blame-correctness}\n\\end{lamportproof}\n\n\\begin{corollary}[blame/ownership match]\n  If\\/ $\\sownerenv_0; \\sowner_0 \\sWLA \\sexpr_0$\n  then for all subterms\\/ $(\\ehist{\\sblist_1}{\\sexpr_1})$\n  there exists\\/ $\\sownerlist_1$\n  such that\\/ $\\sexpr_1 \\eeq \\obbars{\\sexpr_2}{\\sownerlist_1}$\n  and\\/ $\\fbndeqowners{\\sblist_1}{\\sownerlist_1}$\n\\end{corollary}\n\\begin{lamportproof}\n  by definition of $\\sWLA$\n\\end{lamportproof}\n\n\\begin{theorem}\\label{A-S-mon-limit}\n  If\\/ $\\fwellformed{\\sexpr_0}{\\stype_0}$\n  and\\/ $\\sexpr_0 \\rredA \\svalue_1$\n  then\\/ $\\fmondepth{\\svalue_1} \\leq 2$\n\\end{theorem}{\n\\begin{lamportproof}\n  \\step{0}{\\suffices{if $\\edynb{\\sbnd_0}{\\svalue_2} \\nredAS \\svalue_3$ then $\\fmondepth{\\svalue_3} \\leq 2$}}\n    \\begin{pfproof}\n      because the only way to increase the $\\smondepth$ of a value is by crossing\n      a boundary\n    \\end{pfproof}\n  \\qedstep\n    \\begin{pfproof}\n      by \\lemmaref{A-D-mon-limit} and the definition of $\\nredAD$\n    \\end{pfproof}\n\\end{lamportproof}}\n\n\\begin{theorem}\\label{A-D-mon-limit}\n  If\\/ $\\fwellformed{\\sexpr_0}{\\tdyn}$\n  and\\/ $\\sexpr_0 \\rredA \\svalue_1$\n  then\\/ $\\fmondepth{\\svalue_1} \\leq 1$\n\\end{theorem}{\n\\begin{lamportproof}\n  \\step{0}{\\suffices{if $\\estab{\\sbnd_0}{\\svalue_2} \\nredAD \\svalue_3$ then $\\fmondepth{\\svalue_3} \\leq 1$}}\n    \\begin{pfproof}\n      because the only way to increase the $\\smondepth$ of a value is by crossing\n      a boundary\n    \\end{pfproof}\n  \\qedstep\n    \\begin{pfproof}\n      by definition of $\\nredAD$\n    \\end{pfproof}\n\\end{lamportproof}}\n\n%% -----------------------------------------------------------------------------\n\\subsection{\\Aname{}\\ Lemmas}\n\n\\begin{lemma}[$\\sWTA$ progress]\\label{A-type-progress}\n  If\\/ $\\snil \\sWTA \\sexpr_0 : \\toptional$\n  then one of the following holds:\n  \\begin{itemize}\n    \\item\n      $\\sexpr_0 \\in \\svalue$\n    \\item\n      $\\sexpr_0 \\in \\eerr$\n    \\item\n      $\\exists\\,\\sexpr_1$\n      such that\\/ $\\sexpr_0 \\credA \\sexpr_1$\n  \\end{itemize}\n\\end{lemma}{\n  \\newcommand{\\shortpf}{By case analysis of $\\sexpr_0$.}\n\\begin{lamportproof*}\n  \\shortpf\n\\mainproof\n  \\shortpf\n\n  By \\lemmaref{A-decomposition} it suffices to consider the following cases.\n\n  \\step{0}{\\case{$\\sexpr_0 \\in \\svalue$}}\n    \\begin{pfproof}\n      \\qedstep\n    \\end{pfproof}\n\n  \\step{1}{\\case{$\\sexpr_0 \\eeq \\ctx_0[\\eerr]$}}\n    \\begin{pfproof}\n      \\qedstep\n    \\end{pfproof}\n\n  \\step{2}{\\case{$\\sexpr_0 \\eeq \\ctx_0[\\eapp{{\\stype_1}}{\\svalue_0}{\\svalue_1}]$}}\n    \\begin{pfproof}\n      \\step{2.0}{$\\svalue_0 \\in (\\efun{\\tann{\\svar}{\\stype}}{\\sexpr}) \\cup (\\emon{\\sbnd}{\\svalue})$}\n        \\begin{pfproof}\n          by \\lemmaref{A-typed-hole} and inversion $\\sWTA$\n        \\end{pfproof}\n      \\step{2.1}{\\scase{$\\svalue_0 \\eeq \\efun{\\tann{\\svar_2}{\\stype_2}}{\\sexpr_2}$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              $\\sexpr_0 \\nredAS \\ctx_0[\\esubst{\\sexpr_2}{\\svar_2}{\\svalue_1}]$\n            \\end{pfproof}\n        \\end{pfproof}\n      \\step{2.2}{\\scase{$\\svalue_0 \\eeq \\emon{\\obnd{\\sowner_0}{(\\tfun{\\stype_1}{\\stype_2})}{\\sowner_1}}{\\svalue_2}$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              $\\sexpr_0 \\nredAS \\ctx_0[\\edynb{\\obnd{\\sowner_0}{\\stype_1}{\\sowner_1}}{(\\eapp{\\tdyn}{\\svalue_2}{(\\estab{\\obnd{\\sowner_1}{\\stype_1}{\\sowner_0}}{\\svalue_1})})}]$\n            \\end{pfproof}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{3}{\\case{$\\sexpr_0 \\eeq \\ctx_0[\\eapp{{\\stype_1}}{\\svalue_0}{\\svalue_1}]$}}\n    \\begin{pfproof}\n      \\step{3.0}{\\scase{$\\svalue_0 \\eeq \\ehopt{\\sblist_0}{(\\efun{\\tann{\\svar_2}{\\stype_2}}{\\sexpr_2})}$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              $\\sexpr_0 \\nredAD \\ctx_0[\\eprehist{\\sblist_0}{(\\esubst{\\sexpr_2}{\\svar_2}{\\svalue_1})}]$\n            \\end{pfproof}\n        \\end{pfproof}\n      \\step{3.1}{\\scase{$\\svalue_0 \\eeq \\ehopt{\\sblist_0}{(\\emon{\\obnd{\\sowner_0}{(\\tfun{\\stype_1}{\\stype_2})}{\\sowner_1}}{\\svalue_2})}$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              $\\sexpr_0 \\nredAD \\ctx_0[\\eprehist{\\sblist_0}{(\\estab{\\obnd{\\sowner_0}{\\stype_2}{\\sowner_1}}{(\\eapp{\\fforget{\\stype_2}}{\\svalue_2}{(\\edynb{\\obnd{\\sowner_1}{\\stype_1}{\\sowner_0}}{\\svalue_1})})})}]$\n            \\end{pfproof}\n        \\end{pfproof}\n      \\step{3.2}{\\scase{$\\svalue_0 \\not\\in (\\ehopt{\\sblist}{(\\efun{\\tann{\\svar}{\\stype}}{\\sexpr})}) \\cup (\\ehopt{\\sblist}{(\\emon{\\sbnd}{\\svalue})})$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              $\\sexpr_0 \\nredAD \\ctx_0[\\tagerrorD]$\n            \\end{pfproof}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{4}{\\case{$\\sexpr_0 \\eeq \\ctx_0[\\eunopt{\\stoptional}{\\svalue_0}]$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\lemmaref{A-typed-hole} and \\lemmaref{A-delta-type-progress}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{5}{\\case{$\\sexpr_0 \\eeq \\ctx_0[\\ebinopt{\\stoptional}{\\svalue_0}{\\svalue_1}]$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\lemmaref{A-typed-hole} and \\lemmaref{A-delta-type-progress}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{6}{\\case{$\\sexpr_0 \\eeq \\ctx_0[{\\edynb{\\obnd{\\sowner_0}{\\stype_0}{\\sowner_1}}{\\svalue_0}}]$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\lemmaref{A-typed-hole} and \\lemmaref{A-dyn-type-progress}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{7}{\\case{$\\sexpr_0 \\eeq \\ctx_0[{\\estab{\\obnd{\\sowner_0}{\\stype_0}{\\sowner_1}}{\\svalue_0}}]$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\lemmaref{A-typed-hole} and \\lemmaref{A-sta-type-progress}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{8}{\\case{$\\sexpr_0 \\eeq \\ctx_0[\\eprehist{\\sblist_0}{\\svalue_0}]$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          $\\sexpr_0 \\nredAD \\ctx_0[\\faddtrace{\\sblist_0}{\\svalue_0}]$\n        \\end{pfproof}\n    \\end{pfproof}\n\n\\end{lamportproof*}}\n\n\\begin{lemma}[$\\sWTA$ type preservation]\\label{A-type-preservation}\n  If\\/ $\\snil \\sWTA \\sexpr_0 : \\stoptional$\n  and\\/ $\\sexpr_0 \\credA \\sexpr_1$\n  then\\/ $\\snil \\sWTA \\sexpr_1 : \\stoptional$.\n\\end{lemma}{\n  \\newcommand{\\shortpf}{By \\lemmaref{A-S-rr-preservation} and \\lemmaref{A-D-rr-preservation}.}\n\\begin{lamportproof*}\n  \\shortpf\n\\mainproof\n  \\shortpf\n\\end{lamportproof*}}\n\n\\begin{lemma}[$\\nredAS$ preservation]\\label{A-S-rr-preservation}\n  If\\/ $\\snil \\sWTA \\sexpr_0 : \\stype_0$\n  and\\/ $\\sexpr_0 \\nredAS \\sexpr_1$\n  then\\/ $\\snil \\sWTA \\sexpr_1 : \\stype_0$.\n\\end{lemma}{\n  \\newcommand{\\shortpf}{By case analysis of $\\nredAS$.}\n\\begin{lamportproof*}\n  \\shortpf\n\\mainproof\n  \\shortpf\n\n  \\step{0}{\\case{\\(\n   \\sdeltaA(\\sunop, \\svalue_0) \\mbox{ is defined}\n  \\)\\\\and \\(\n   \\eunopt{\\stoptional}{\\svalue_0} \\nredAS \\sdeltaA(\\sunop, \\svalue_0)\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\lemmaref{A-delta-type-preservation}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{1}{\\case{\\(\n   \\efst{\\stype_0}{(\\emon{\\obnd{\\sowner_0}{\\stype_1}{\\sowner_1}}{\\svalue_0})}\n   \\nredAS\n   \\edynb{\\obnd{\\sowner_0}{\\stype_0}{\\sowner_1}}{(\\efst{\\tdyn}{\\svalue_0})}\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          \\begin{mathpar}\n            \\inferrule*{\n              \\inferrule*{\n                \\inferrule*{\n                  \\mbox{by inversion $\\sWTA$}\n                }{\n                  \\snil \\svalue_0 : \\tdyn\n                }\n              }{\n                \\snil \\sWTA \\efst{\\tdyn}{\\svalue_0} : \\tdyn\n              }\n            }{\n              \\snil \\sWTA \\edynb{\\obnd{\\sowner_0}{\\stype_0}{\\sowner_1}}{(\\efst{\\tdyn}{\\svalue_0})} : \\stype_0\n            }\n          \\end{mathpar}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{2}{\\case{\\(\n   \\esnd{\\stype_0}{(\\emon{\\obnd{\\sowner_0}{\\stype_1}{\\sowner_1}}{\\svalue_0})}\n   \\nredAS\n   \\edynb{\\obnd{\\sowner_0}{\\stype_0}{\\sowner_1}}{(\\esnd{\\tdyn}{\\svalue_0})}\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          \\begin{mathpar}\n            \\inferrule*{\n              \\inferrule*{\n                \\inferrule*{\n                  \\mbox{by inversion $\\sWTA$}\n                }{\n                  \\snil \\svalue_0 : \\tdyn\n                }\n              }{\n                \\snil \\sWTA \\esnd{\\tdyn}{\\svalue_0} : \\tdyn\n              }\n            }{\n              \\snil \\sWTA \\edynb{\\obnd{\\sowner_0}{\\stype_0}{\\sowner_1}}{(\\esnd{\\tdyn}{\\svalue_0})} : \\stype_0\n            }\n          \\end{mathpar}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{3}{\\case{$\\ebinopt{\\stoptional}{\\svalue_0}{\\svalue_1} \\nredAS \\sdeltaA(\\sbinop, \\svalue_0, \\svalue_1)$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\lemmaref{A-delta-type-preservation}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{4}{\\case{$\\eapp{{\\stype_0}}{(\\efun{\\tann{\\svar_1}{\\stype_1}}{\\sexpr_1})}{\\svalue_2} \\nredAS \\esubst{\\sexpr_1}{\\svar_1}{\\svalue_2}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\lemmaref{A-type-substitution}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{5}{\\case{\\(\n   \\eapp{\\stype_0}{(\\emon{\\obnd{\\sowner_0}{(\\tfun{\\stype_1}{\\stype_2})}{\\sowner_1}}{\\svalue_0})}{\\svalue_1}\n    \\\\ \\nredAS \\edynb{\\obnd{\\sowner_0}{\\stype_0}{\\sowner_1}}{(\\eapp{\\tdyn}{\\svalue_0}{(\\estab{\\obnd{\\sowner_1}{\\stype_1}{\\sowner_0}}{\\svalue_1})})}\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          \\begin{mathpar}\n            \\inferrule*{\n              \\inferrule*{\n                \\inferrule*{\n                  \\mbox{by inversion $\\sWTA$}\n                }{\n                  \\snil \\sWTA \\svalue_0 : \\tdyn\n                }\n                \\\\\n                \\inferrule*{\n                  \\inferrule*{\n                    \\mbox{by inversion $\\sWTA$}\n                  }{\n                    \\snil \\sWTA \\svalue_1 : \\stype_1\n                  }\n                }{\n                  \\snil \\sWTA \\estab{\\obnd{\\sowner_1}{\\stype_1}{\\sowner_0}}{\\svalue_1} : \\tdyn\n                }\n              }{\n                \\snil \\sWTA \\eapp{\\tdyn}{\\svalue_0}{(\\estab{\\obnd{\\sowner_1}{\\stype_1}{\\sowner_0}}{\\svalue_1})} : \\tdyn\n              }\n            }{\n              \\snil \\sWTA \\edynb{\\obnd{\\sowner_0}{\\stype_0}{\\sowner_1}}{(\\eapp{\\tdyn}{\\svalue_0}{(\\estab{\\obnd{\\sowner_1}{\\stype_1}{\\sowner_0}}{\\svalue_1})})} : \\stype_0\n            }\n          \\end{mathpar}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{6}{\\case{\\(\\edynb{\\sbnd_0}{\\svalue_0} \\nredAS \\svalue_1\\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\lemmaref{A-dyn-type-preservation}\n        \\end{pfproof}\n    \\end{pfproof}\n\n\\end{lamportproof*}}\n\n\\begin{lemma}[$\\nredAD$ preservation]\\label{A-D-rr-preservation}\n  If\\/ $\\snil \\sWTA \\sexpr_0 : \\tdyn$\n  and\\/ $\\sexpr_0 \\nredAD \\sexpr_1$\n  then\\/ $\\snil \\sWTA \\sexpr_1 : \\tdyn$.\n\\end{lemma}{\n  \\newcommand{\\shortpf}{By case analysis of $\\nredAD$.}\n\\begin{lamportproof*}\n  \\shortpf\n\\mainproof\n  \\shortpf\n\n  \\step{0}{\\case{$\\eunopt{\\stoptional}{\\svalue_0} \\nredAD \\tagerrorD$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          $\\snil \\sWTA \\tagerrorD : \\tdyn$\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{1}{\\case{$\\eunopt{\\stoptional}{\\svalue_0} \\nredAD \\sdeltaA(\\sunop, \\svalue_0)$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\lemmaref{A-delta-type-preservation}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{2}{\\case{\\(\n    \\efst{\\tdyn}{(\\ehopt{\\sblist_0}{(\\emon{\\obnd{\\sowner_1}{\\stype_0}{\\sowner_2}}{\\svalue_1})})}\n    \\nredAD\n    \\eprehist{\\sblist_0}{(\\estab{\\sbnd_7}{(\\efst{\\ftypefst{\\stype_0}}{\\svalue_1})})}\n  \\)\\\\where \\(\n    \\sbnd_7 \\sassign \\obnd{\\sowner_1}{\\ftypefst{\\stype_0}}{\\sowner_2}\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          \\begin{mathpar}\n            \\inferrule*{\n              \\inferrule*{\n                \\inferrule*{\n                  \\inferrule*{\n                    \\mbox{by inversion $\\sWTA$}\n                  }{\n                    \\snil \\sWTA \\svalue_1 : \\stype_0\n                  }\n                }{\n                  \\snil \\sWTA \\efst{\\ftypefst{\\stype_0}}{\\svalue_1} : \\ftypefst{\\stype_0}\n                }\n              }{\n                \\snil \\sWTA \\estab{\\sbnd_7}{(\\efst{\\ftypefst{\\stype_0}}{\\svalue_1})} : \\tdyn\n              }\n            }{\n              \\snil \\sWTA \\eprehist{\\sblist_0}{(\\estab{\\sbnd_7}{(\\efst{\\ftypefst{\\stype_0}}{\\svalue_1})})} : \\tdyn\n            }\n          \\end{mathpar}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{3}{\\case{\\(\n    \\esnd{\\tdyn}{(\\ehopt{\\sblist_0}{(\\emon{\\obnd{\\sowner_1}{\\stype_0}{\\sowner_2}}{\\svalue_1})})}\n    \\nredAD\n    \\eprehist{\\sblist_0}{(\\estab{\\sbnd_7}{(\\esnd{\\ftypesnd{\\stype_0}}{\\svalue_1})})}\n  \\)\\\\where \\(\n    \\sbnd_7 \\sassign \\obnd{\\sowner_1}{\\ftypesnd{\\stype_0}}{\\sowner_2}\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          \\begin{mathpar}\n            \\inferrule*{\n              \\inferrule*{\n                \\inferrule*{\n                  \\inferrule*{\n                    \\mbox{by inversion $\\sWTA$}\n                  }{\n                    \\snil \\sWTA \\svalue_1 : \\stype_0\n                  }\n                }{\n                  \\snil \\sWTA \\esnd{\\ftypesnd{\\stype_0}}{\\svalue_1} : \\ftypesnd{\\stype_0}\n                }\n              }{\n                \\snil \\sWTA \\estab{\\sbnd_7}{(\\esnd{\\ftypesnd{\\stype_0}}{\\svalue_1})} : \\tdyn\n              }\n            }{\n              \\snil \\sWTA \\eprehist{\\sblist_0}{(\\estab{\\sbnd_7}{(\\esnd{\\ftypesnd{\\stype_0}}{\\svalue_1})})} : \\tdyn\n            }\n          \\end{mathpar}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{4}{\\case{$\\ebinopt{\\stoptional}{\\svalue_0}{\\svalue_1} \\nredAD \\tagerrorD$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          $\\snil \\sWTA \\tagerrorD : \\tdyn$\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{5}{\\case{$\\ebinopt{\\stoptional}{\\svalue_0}{\\svalue_1} \\nredAD \\sdeltaA(\\sbinop, \\svalue_0, \\svalue_1)$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\lemmaref{A-delta-type-preservation}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{6}{\\case{\\(\n   \\eapp{\\tdyn}{(\\ehopt{\\sblist_0}{(\\efun{\\svar_1}{\\sexpr_1})})}{\\svalue_2}\n    \\\\\\nredAD \\eprehist{\\sblist_0}{(\\esubst{\\sexpr_1}{\\svar_1}{\\svalue_2})}\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\lemmaref{A-type-substitution}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{7}{\\case{\\(\n   \\eapp{\\tdyn}{(\\ehopt{\\sblist_0}{(\\emon{\\obnd{\\sowner_0}{(\\tfun{\\stype_1}{\\stype_0})}{\\sowner_1}}{\\svalue_0})})}{\\svalue_1}\n    \\\\ \\nredAD \\eprehist{\\sblist_0}{(\\estab{\\obnd{\\sowner_0}{\\stype_0}{\\sowner_1}}{(\\eapp{{\\stype_0}}{\\svalue_0}{(\\edynb{\\obnd{\\sowner_1}{\\stype_1}{\\sowner_0}}{\\svalue_1})})})}\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          \\begin{mathpar}\n            \\inferrule*{\n              \\inferrule*{\n                \\inferrule*{\n                  \\mbox{by inversion $\\sWTA$}\n                }{\n                  \\snil \\sWTA \\svalue_0 : \\tfun{\\stype_1}{\\stype_0}\n                }\n                \\\\\n                \\inferrule*{\n                  \\inferrule*{\n                    \\mbox{by inversion $\\sWTA$}\n                  }{\n                    \\snil \\sWTA \\svalue_1 : \\tdyn\n                  }\n                }{\n                  \\snil \\sWTA \\edynb{\\obnd{\\sowner_1}{\\stype_1}{\\sowner_0}}{\\svalue_1} : \\stype_1\n                }\n              }{\n                \\snil \\sWTA \\eapp{{\\stype_0}}{\\svalue_0}{(\\edynb{\\obnd{\\sowner_1}{\\stype_1}{\\sowner_0}}{\\svalue_1})} : \\stype_0\n              }\n            }{\n              \\snil \\sWTA \\eprehist{\\sblist_0}{(\\estab{\\obnd{\\sowner_0}{\\stype_0}{\\sowner_1}}{(\\eapp{{\\stype_0}}{\\svalue_0}{(\\edynb{\\obnd{\\sowner_1}{\\stype_1}{\\sowner_0}}{\\svalue_1})})})} : \\tdyn\n            }\n          \\end{mathpar}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{8}{\\case{\\(\\estab{\\sbnd_0}{\\svalue_0} \\nredAD \\svalue_1\\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\lemmaref{A-sta-type-preservation}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{9}{\\case{\\(\n   \\eprehist{\\sblist_0}{\\svalue_0} \\nredAD \\faddtrace{\\sblist_0}{\\svalue_0}\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\lemmaref{A-addtrace-type-preservation}\n        \\end{pfproof}\n    \\end{pfproof}\n\n\\end{lamportproof*}}\n\n\\begin{lemma}[unique decomposition]\\label{A-decomposition}\n  If\\/ $\\snil \\sWTA \\sexpr_0 : \\toptional$ then either:\n  \\begin{itemize}\n    \\item\n      $\\sexpr_0 \\in \\svalue$\n    \\item\n      $\\sexpr_0 \\eeq \\ctx_0[\\eapp{\\toptional}{\\svalue_0}{\\svalue_1}]$\n    \\item\n      $\\sexpr_0 \\eeq \\ctx_0[\\eunopt{\\stoptional}{\\svalue_0}]$\n    \\item\n      $\\sexpr_0 \\eeq \\ctx_0[\\ebinopt{\\stoptional}{\\svalue_0}{\\svalue_1}]$\n    \\item\n      $\\sexpr_0 \\eeq \\ctx_0[\\edynb{\\sbnd_1}{\\svalue_1}]$\n    \\item\n      $\\sexpr_0 \\eeq \\ctx_0[\\estab{\\sbnd_1}{\\svalue_1}]$\n    \\item\n      $\\sexpr_0 \\eeq \\ctx_0[\\eprehist{\\sblist_1}{\\svalue_1}]$\n    \\item\n      $\\sexpr_0 \\eeq \\ctx_0[\\eerr]$\n  \\end{itemize}\n\\end{lemma}{\n  \\newcommand{\\shortproof}{By induction on the structure of $\\sexpr_0$.}\n\\begin{lamportproof*}\n  \\shortproof\n\\mainproof\\leavevmode\n  \\shortproof\n\n  \\step{0}{\\case{$\\sexpr_0 \\eeq \\svar_0$}}\n    \\begin{pfproof}\n      \\absurdstep\n        \\begin{pfproof}\n          $\\snil \\sWTA \\sexpr_0 : \\toptional$\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{1}{\\case{$\\sexpr_0 \\eeq \\svalue_0$}}\n    \\begin{pfproof}\n      \\qedstep\n    \\end{pfproof}\n\n  \\step{2}{\\case{$\\sexpr_0 \\eeq \\epair{\\sexpr_1}{\\sexpr_2}$}}\n    \\begin{pfproof}\n      \\step{2.0}{\\scase{$\\sexpr_1 \\not\\in \\svalue$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              by \\pfih\n            \\end{pfproof}\n        \\end{pfproof}\n      \\step{2.1}{\\scase{$\\sexpr_1 \\in \\svalue$ and $\\sexpr_2 \\not\\in \\svalue$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              by \\pfih\n            \\end{pfproof}\n        \\end{pfproof}\n      \\step{2.2}{\\scase{$\\sexpr_1 \\in \\svalue$ and $\\sexpr_2 \\in \\svalue$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              $\\sexpr_0 \\in \\svalue$\n            \\end{pfproof}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{3}{\\case{$\\sexpr_0 \\eeq \\eapp{\\toptional}{\\sexpr_1}{\\sexpr_2}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{4}{\\case{$\\sexpr_0 \\eeq \\eunopt{\\stoptional}{\\sexpr_1}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{5}{\\case{$\\sexpr_0 \\eeq \\ebinopt{\\stoptional}{\\sexpr_1}{\\sexpr_2}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{6}{\\case{$\\sexpr_0 \\eeq \\edynb{\\sbnd_1}{\\sexpr_1}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{7}{\\case{$\\sexpr_0 \\eeq \\estab{\\sbnd_1}{\\sexpr_1}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{8}{\\case{$\\sexpr_0 \\eeq \\eprehist{\\sblist_1}{\\sexpr_1}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{9}{\\case{$\\sexpr_0 \\in \\eerr$}}\n    \\begin{pfproof}\n      \\qedstep\n    \\end{pfproof}\n\n\\end{lamportproof*}}\n\n\\begin{lemma}\\label{A-typed-hole}\\leavevmode\n  If\\/ $\\snil \\sWTA \\ctx_0[\\sexpr_0] : \\toptional$\n  then one of the following holds:\n  \\begin{itemize}\n    \\item $\\snil \\sWTA \\sexpr_0 : \\tdyn$\n    \\item $\\exists\\,\\stype_0~.~\\snil \\sWTA \\sexpr_0 : \\stype_0$\n  \\end{itemize}\n\\end{lemma}{\n\\newcommand{\\shortproof}{By induction on the structure of $\\ctx_0$ and case analysis of $\\sWTA$.}\n\\begin{lamportproof*}\n  \\shortproof\n\\mainproof\n  \\shortproof\n\n  \\step{0}{\\case{$\\ctx_0 \\eeq \\ctxhole$}}\n    \\begin{pfproof}\n      \\qedstep\n    \\end{pfproof}\n\n  \\step{1}{\\case{$\\ctx_0 \\eeq \\epair{\\ctx_1}{\\sexpr_2}$}}\n    \\begin{pfproof}\n      \\step{1.0}{$\\snil \\sWTA \\ctx_1[\\sexpr_0] : \\toptional$}\n        \\begin{pfproof}\n          by inversion $\\sWTA$\n        \\end{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{2}{\\case{$\\ctx_0 \\eeq \\epair{\\svalue_1}{\\ctx_2}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{3}{\\case{$\\ctx_0 \\eeq \\eapp{\\toptional}{\\ctx_1}{\\sexpr_2}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{4}{\\case{$\\ctx_0 \\eeq \\eapp{\\toptional}{\\svalue_1}{\\ctx_2}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{5}{\\case{$\\ctx_0 \\eeq \\eunopt{\\stoptional}{\\ctx_1}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{6}{\\case{$\\ctx_0 \\eeq \\ebinopt{\\stoptional}{\\ctx_1}{\\sexpr_2}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{7}{\\case{$\\ctx_0 \\eeq \\ebinopt{\\stoptional}{\\svalue_1}{\\ctx_2}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{8}{\\case{$\\ctx_0 \\eeq \\edynb{\\sbnd_1}{\\ctx_1}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{9}{\\case{$\\ctx_0 \\eeq \\estab{\\sbnd_1}{\\ctx_1}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{10}{\\case{$\\ctx_0 \\eeq \\eprehist{\\sblist_1}{\\ctx_1}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n\\end{lamportproof*}}\n\n\\begin{lemma}[$\\sWTA$ replacement]\\label{A-type-replacement}\\leavevmode\n  \\begin{itemize}\n    \\item\n      If\\/ $\\snil \\sWTA \\ctx_0[\\sexpr_0] : \\toptional$\n      and the derivation contains a proof of\\/ $\\snil \\sWTA \\sexpr_0 : \\stype_0$\n      and\\/ $\\snil \\sWTA \\sexpr_1 : \\stype_0$\n      then\\/ $\\snil \\sWTA \\ctx_0[\\sexpr_1] : \\toptional$.\n    \\item\n      If\\/ $\\snil \\sWTA \\ctx_0[\\sexpr_0] : \\toptional$\n      and the derivation contains a proof of\\/ $\\snil \\sWTA \\sexpr_0 : \\tdyn$\n      and\\/ $\\snil \\sWTA \\sexpr_1 : \\tdyn$\n      then\\/ $\\snil \\sWTA \\ctx_0[\\sexpr_1] : \\toptional$.\n  \\end{itemize}\n\\end{lemma}{\n  \\newcommand{\\shortproof}{By induction on $\\ctx_0$.}\n\\begin{lamportproof*}\n  \\shortproof\n\\mainproof\n  \\shortproof\n\n  \\step{0}{\\case{$\\ctx_0 \\eeq \\ctxhole$}}\n    \\begin{pfproof}\n      \\qedstep\n    \\end{pfproof}\n\n  \\step{1}{\\case{$\\ctx_0 \\eeq \\epair{\\ctx_1}{\\sexpr_2}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{2}{\\case{$\\ctx_0 \\eeq \\epair{\\svalue_1}{\\ctx_2}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{3}{\\case{$\\ctx_0 \\eeq \\eapp{\\toptional}{\\ctx_1}{\\sexpr_2}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{4}{\\case{$\\ctx_0 \\eeq \\eapp{\\toptional}{\\svalue_1}{\\ctx_2}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{5}{\\case{$\\ctx_0 \\eeq \\eunopt{\\stoptional}{\\ctx_1}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{6}{\\case{$\\ctx_0 \\eeq \\ebinopt{\\stoptional}{\\ctx_1}{\\sexpr_2}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{7}{\\case{$\\ctx_0 \\eeq \\ebinopt{\\stoptional}{\\svalue_1}{\\ctx_2}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{8}{\\case{$\\ctx_0 \\eeq \\edynb{\\sbnd_1}{\\ctx_1}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{9}{\\case{$\\ctx_0 \\eeq \\estab{\\sbnd_1}{\\ctx_1}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{10}{\\case{$\\ctx_0 \\eeq \\eprehist{\\sblist_1}{\\ctx_1}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n\\end{lamportproof*}}\n\n\\begin{lemma}\\label{A-delta-type-progress}\\leavevmode\n  \\begin{itemize}\n    \\item\n      If\\/ $\\snil \\sWTA \\eunopt{\\stype_1}{\\svalue_0} : \\stype_0$\n      then\\/ $\\eunopt{\\stype_1}{\\svalue_0} \\nredAS \\sexpr_1$.\n    \\item\n      if\\/ $\\snil \\sWTA \\ebinopt{\\stype_1}{\\svalue_0}{\\svalue_1} : \\stype_0$\n      then\\/ $\\ebinopt{\\stype_1}{\\svalue_0}{\\svalue_1} \\nredAS \\sexpr_1$.\n    \\item\n      If\\/ $\\snil \\sWTA \\eunopt{\\tdyn}{\\svalue_0} : \\tdyn$\n      then\\/ $\\eunopt{\\tdyn}{\\svalue_0} \\nredAD \\sexpr_1$.\n    \\item\n      if\\/ $\\snil \\sWTA \\ebinopt{\\tdyn}{\\svalue_0}{\\svalue_1} : \\tdyn$\n      then\\/ $\\ebinopt{\\tdyn}{\\svalue_0}{\\svalue_1} \\nredAD \\sexpr_1$.\n  \\end{itemize}\n\\end{lemma}{\n  \\newcommand{\\shortpf}{By case analysis of $\\sdeltaA$, $\\sWTA$, and $\\nredAD$.}\n\\begin{lamportproof*}\n  \\shortpf\n\\mainproof\n  \\shortpf\n\n  \\step{0}{\\case{\\(\n   \\snil \\sWTA \\efst{\\stype_0}{\\svalue_0}\n  \\)}}\n    \\begin{pfproof}\n      \\step{0.0}{$\\svalue_0 \\in \\epair{\\svalue}{\\svalue} \\cup \\emon{\\obnd{\\sowner}{\\tpair{\\stype}{\\stype}}{\\sowner}}{\\svalue}$}\n        \\begin{pfproof}\n          by $\\sWTA$ canonical forms\n        \\end{pfproof}\n      \\step{0.1}{\\scase{$\\svalue_0 \\eeq \\epair{\\svalue_1}{\\svalue_2}$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              $\\efst{\\stype_0}{\\svalue_0} \\nredAS \\svalue_1$\n            \\end{pfproof}\n        \\end{pfproof}\n      \\step{0.2}{\\scase{$\\svalue_0 \\eeq \\emon{\\obnd{\\sowner_0}{\\tpair{\\stype_1}{\\stype_2}}{\\sowner_1}}{\\svalue_1}$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              $\\efst{\\stype_0}{\\svalue_0} \\nredAS \\edynb{\\obnd{\\sowner_0}{\\stype_0}{\\sowner_1}}{(\\efst{\\tdyn}{\\svalue_0})}$\n            \\end{pfproof}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{1}{\\case{\\(\n   \\snil \\sWTA \\esnd{\\stype_0}{\\svalue_0}\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          similar to the $\\sfst$ case\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{2}{\\case{\\(\n   \\snil \\sWTA \\efst{\\tdyn}{\\svalue_0}\n  \\)}}\n    \\begin{pfproof}\n      \\step{2.0}{\\scase{$\\svalue_0 \\eeq \\epair{\\svalue_1}{\\svalue_2}$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              $\\efst{\\tdyn}{\\svalue_0} \\nredAD \\svalue_1$\n            \\end{pfproof}\n        \\end{pfproof}\n      \\step{2.1}{\\scase{$\\svalue_0 \\eeq \\ehopt{\\sblist_0}{(\\emon{\\obnd{\\sowner_1}{\\tpair{\\stype_1}{\\stype_2}}{\\sowner_2}}{\\svalue_1})}$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              $\\efst{\\tdyn}{\\svalue_0} \\nredAD \\eprehist{\\sblist_0}{(\\estab{\\obnd{\\sowner_1}{\\stype_1}{\\sowner_2}}{(\\efst{\\stype_1}{\\svalue_1})})}$\n            \\end{pfproof}\n        \\end{pfproof}\n      \\step{2.2}{\\scase{$\\svalue_0 \\not\\in \\epair{\\svalue}{\\svalue} \\cup (\\emon{\\obnd{\\sowner}{\\tpair{\\stype}{\\stype}}{\\sowner}}{\\svalue})$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              $\\efst{\\tdyn}{\\svalue_0} \\nredAD \\tagerrorD$\n            \\end{pfproof}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{3}{\\case{\\(\n   \\snil \\sWTA \\esnd{\\tdyn}{\\svalue_0}\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          similar to the $\\sfst$ case\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{4}{\\case{$\\snil \\sWTA \\ebinopt{\\stype_1}{\\svalue_0}{\\svalue_1} : \\stype_0$}}\n    \\begin{pfproof}\n      \\step{4.0}{$\\svalue_0 \\in \\sint$ and $\\svalue_1 \\in \\sint$}\n        \\begin{pfproof}\n          by $\\sWTA$ canonical forms\n        \\end{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          $\\ebinopt{\\stype_1}{\\svalue_0}{\\svalue_1} \\nredAS \\sdeltaA(\\sbinop, \\svalue_0, \\svalue_1)$\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{5}{\\case{$\\snil \\sWTA \\ebinopt{\\tdyn}{\\svalue_0}{\\svalue_1} : \\tdyn$}}\n    \\begin{pfproof}\n      \\step{5.0}{\\scase{$\\svalue_0 \\in \\sint$ and $\\svalue_1 \\in \\sint$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              $\\ebinopt{\\tdyn}{\\svalue_0}{\\svalue_1} \\nredAD \\sdeltaA(\\sbinop, \\svalue_0, \\svalue_1)$\n            \\end{pfproof}\n        \\end{pfproof}\n      \\step{5.1}{\\scase{$\\svalue_0 \\not\\in \\sint$ or $\\svalue_1 \\not\\in \\sint$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              $\\ebinopt{\\tdyn}{\\svalue_0}{\\svalue_1} \\nredAD \\tagerrorD$\n            \\end{pfproof}\n        \\end{pfproof}\n    \\end{pfproof}\n\n\\end{lamportproof*}}\n\n\\begin{lemma}\\label{A-delta-type-preservation}\\leavevmode\n  \\begin{itemize}\n    \\item\n      If\\/ $\\snil \\sWTA \\eunopt{\\stype_1}{\\svalue_0} : \\stype_0$\n      and\\/ $\\eunopt{\\stype_1}{\\svalue_0} \\nredAS \\sexpr_1$\n      then\\/ $\\snil \\sWTA \\sexpr_1 : \\stype_0$.\n    \\item\n      If\\/ $\\snil \\sWTA \\ebinopt{\\stype_1}{\\svalue_0}{\\svalue_1} : \\stype_0$\n      and\\/ $\\ebinopt{\\stype_1}{\\svalue_0}{\\svalue_1} \\nredAS \\sexpr_2$\n      then\\/ $\\snil \\sWTA \\sexpr_2 : \\stype_0$.\n    \\item\n      If\\/ $\\snil \\sWTA \\eunopt{\\tdyn}{\\svalue_0} : \\tdyn$\n      and\\/ $\\eunopt{\\tdyn}{\\svalue_0} \\nredAD \\sexpr_1$\n      then\\/ $\\snil \\sWTA \\sexpr_1 : \\tdyn$.\n    \\item\n      If\\/ $\\snil \\sWTA \\ebinopt{\\tdyn}{\\svalue_0}{\\svalue_1} : \\tdyn$\n      and\\/ $ \\ebinopt{\\tdyn}{\\svalue_0}{\\svalue_1} \\nredAD \\sexpr_2$\n      then\\/ $\\snil \\sWTA \\sexpr_2 : \\tdyn$.\n  \\end{itemize}\n\\end{lemma}{\n  \\newcommand{\\shortpf}{By case analysis of $\\sdeltaA$ and $\\sWTA$.}\n\\begin{lamportproof*}\n  \\shortpf\n\\mainproof\n  \\shortpf\n\n  \\step{0}{\\case{\\(\n   \\snil \\sWTA \\efst{\\stype_0}{\\svalue_0} : \\stype_0\n  \\)}}\n    \\begin{pfproof}\n      \\step{0.0}{\\scase{$\\efst{\\stype_0}{\\epair{\\svalue_1}{\\svalue_2}} \\nredAS \\svalue_1$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              by inversion $\\sWTA$\n            \\end{pfproof}\n        \\end{pfproof}\n      \\step{0.1}{\\scase{\\(\n       \\efst{\\stype_0}{(\\emon{\\obnd{\\sowner_0}{\\tpair{\\stype_1}{\\stype_2}}{\\sowner_1}}{\\svalue_1})}\n        \\\\\\nredAS \\edynb{\\obnd{\\sowner_0}{\\stype_1}{\\sowner_1}}{(\\efst{\\tdyn}{\\svalue_1})}\n      \\)}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              \\begin{mathpar}\n                \\inferrule*{\n                  \\inferrule*{\n                    \\inferrule*{\n                      \\inferrule*{\n                        \\mbox{by inversion $\\sWTA$}\n                      }{\n                        \\snil \\sWTA \\svalue_1 : \\tdyn\n                      }\n                    }{\n                      \\snil \\sWTA \\efst{\\tdyn}{\\svalue_1} : \\tdyn\n                    }\n                  }{\n                    \\snil \\sWTA \\edynb{\\obnd{\\sowner_0}{\\stype_1}{\\sowner_1}}{(\\efst{\\tdyn}{\\svalue_1})} : \\stype_1\n                  }\n                  \\\\\n                  \\inferrule*{\n                    \\mbox{by inversion $\\sWTA$}\n                  }{\n                    \\stype_1 \\subteq \\stype_0\n                  }\n                }{\n                  \\snil \\sWTA \\edynb{\\obnd{\\sowner_0}{\\stype_1}{\\sowner_1}}{(\\efst{\\tdyn}{\\svalue_1})} : \\stype_0\n                }\n              \\end{mathpar}\n            \\end{pfproof}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{1}{\\case{$\\snil \\sWTA \\esnd{\\stype_0}{\\svalue_0} : \\stype_0$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          similar to $\\sfst$\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{2}{\\case{$\\snil \\sWTA \\esum{\\stype_1}{\\svalue_0}{\\svalue_1} : \\stype_0$}}\n    \\begin{pfproof}\n      \\step{2.0}{$\\esum{\\stype_1}{\\svalue_0}{\\svalue_1} \\nredAS \\sdeltaA(\\ssum, \\svalue_0, \\svalue_1)$}\n      \\step{2.1}{$\\stype_0 \\in \\tint \\cup \\tnat$}\n        \\begin{pfproof}\n          by inversion $\\sWTA$\n        \\end{pfproof}\n      \\step{2.2}{\\scase{$\\stype_0 \\eeq \\tint$}}\n        \\begin{pfproof}\n          \\step{2.2.0}{$\\snil \\sWTA \\svalue_0 : \\tint$ and $\\snil \\sWTA \\svalue_1 : \\tint$}\n            \\begin{pfproof}\n              by inversion $\\sWTA$\n            \\end{pfproof}\n          \\step{2.2.1}{$ \\svalue_0 \\in \\sint$ and $\\svalue_1 \\in \\sint$}\n            \\begin{pfproof}\n              by $\\sWTA$ canonical forms\n            \\end{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              $\\snil \\sWTA \\sdeltaA(\\sbinop, \\svalue_0, \\svalue_1) : \\tint$\n            \\end{pfproof}\n        \\end{pfproof}\n      \\step{2.3}{\\scase{$\\stype_0 \\eeq \\tnat$}}\n        \\begin{pfproof}\n          \\step{2.3.0}{$\\snil \\sWTA \\svalue_0 : \\tnat$ and $\\snil \\sWTA \\svalue_1 : \\tnat$}\n            \\begin{pfproof}\n              by inversion $\\sWTA$\n            \\end{pfproof}\n          \\step{2.3.1}{$ \\svalue_0 \\in \\snat$ and $\\svalue_1 \\in \\snat$}\n            \\begin{pfproof}\n              by $\\sWTA$ canonical forms\n            \\end{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              $\\snil \\sWTA \\sdeltaA(\\sbinop, \\svalue_0, \\svalue_1) : \\tnat$\n            \\end{pfproof}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{3}{\\case{$\\snil \\sWTA \\equotient{\\stype_1}{\\svalue_0}{\\svalue_1} : \\stype_0$}}\n    \\begin{pfproof}\n      \\step{3.0}{$\\equotient{\\stype_1}{\\svalue_0}{\\svalue_1} \\nredAS \\sdeltaA(\\squotient, \\svalue_0, \\svalue_1)$}\n      \\step{3.1}{$\\stype_0 \\in \\tint \\cup \\tnat$}\n        \\begin{pfproof}\n          by inversion $\\sWTA$\n        \\end{pfproof}\n      \\step{3.2}{\\scase{$\\stype_0 \\eeq \\tint$}}\n        \\begin{pfproof}\n          \\step{3.2.0}{$\\snil \\sWTA \\svalue_0 : \\tint$ and $\\snil \\sWTA \\svalue_1 : \\tint$}\n            \\begin{pfproof}\n              by inversion $\\sWTA$\n            \\end{pfproof}\n          \\step{3.2.1}{$ \\svalue_0 \\in \\sint$ and $\\svalue_1 \\in \\sint$}\n            \\begin{pfproof}\n              by $\\sWTA$ canonical forms\n            \\end{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              $\\sdeltaA(\\sbinop, \\svalue_0, \\svalue_1) \\in \\sint \\cup \\divisionbyzeroerror$\n            \\end{pfproof}\n        \\end{pfproof}\n      \\step{3.3}{\\scase{$\\stype_0 \\eeq \\tnat$}}\n        \\begin{pfproof}\n          \\step{3.3.0}{$\\snil \\sWTA \\svalue_0 : \\tnat$ and $\\snil \\sWTA \\svalue_1 : \\tnat$}\n            \\begin{pfproof}\n              by inversion $\\sWTA$\n            \\end{pfproof}\n          \\step{3.3.1}{$ \\svalue_0 \\in \\snat$ and $\\svalue_1 \\in \\snat$}\n            \\begin{pfproof}\n              by $\\sWTA$ canonical forms\n            \\end{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              $\\sdeltaA(\\sbinop, \\svalue_0, \\svalue_1) \\in \\snat \\cup \\divisionbyzeroerror$\n            \\end{pfproof}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{4}{\\case{$\\snil \\sWTA \\efst{\\tdyn}{\\svalue_0} : \\tdyn$}}\n    \\begin{pfproof}\n      \\step{4.0}{\\scase{\\(\n        \\svalue_0 \\eeq \\ehopt{\\sblist_0}{\\epair{\\svalue_1}{\\svalue_2}}\n      \\)\\\\and \\(\n        \\efst{\\tdyn}{\\svalue_0} \\nredAD \\faddtrace{\\sblist_0}{\\svalue_1}\n      \\)}}\n        \\begin{pfproof}\n          \\step{4.0.0}{$\\snil \\sWTA \\svalue_1 : \\tdyn$}\n            \\begin{pfproof}\n              by inversion $\\sWTA$\n            \\end{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              by \\lemmaref{A-addtrace-type-preservation}\n            \\end{pfproof}\n        \\end{pfproof}\n      \\step{4.1}{\\scase{\\(\n        \\svalue_0 \\eeq \\ehopt{\\sblist_0}{(\\emon{\\obnd{\\sowner_1}{\\tpair{\\stype_1}{\\stype_2}}{\\sowner_2}}{\\svalue_1})}\n      \\)\\\\and \\(\n        \\efst{\\tdyn}{\\svalue_0} \\nredAD \\eprehist{\\sblist_0}{(\\estab{\\obnd{\\sowner_1}{\\stype_1}{\\sowner_2}}{(\\efst{\\stype_1}{\\svalue_1})})}\n      \\)}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              \\begin{mathpar}\n                \\inferrule*{\n                  \\inferrule*{\n                    \\inferrule*{\n                      \\inferrule*{\n                        \\mbox{by inversion $\\sWTA$}\n                      }{\n                        \\snil \\sWTA \\svalue_1 : \\tdyn\n                      }\n                    }{\n                      \\snil \\sWTA \\efst{\\stype_1}{\\svalue_1} : \\tdyn\n                    }\n                  }{\n                    \\snil \\sWTA \\estab{\\obnd{\\sowner_1}{\\stype_1}{\\sowner_2}}{(\\efst{\\stype_1}{\\svalue_1})} : \\tdyn\n                  }\n                }{\n                  \\snil \\sWTA \\eprehist{\\sblist_0}{(\\estab{\\obnd{\\sowner_1}{\\stype_1}{\\sowner_2}}{(\\efst{\\stype_1}{\\svalue_1})})} : \\tdyn\n                }\n              \\end{mathpar}\n            \\end{pfproof}\n        \\end{pfproof}\n      \\step{4.2}{\\scase{\\(\n        \\svalue_0 \\not\\in (\\ehopt{\\sblist}{\\epair{\\svalue}{\\svalue}}) \\cup (\\ehopt{\\sblist}{(\\emon{\\sbnd}{\\svalue})})\n      \\)\\\\and \\(\n        \\efst{\\tdyn}{\\svalue_0} \\nredAD \\tagerrorD\n      \\)}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              $\\snil \\sWTA \\tagerrorD : \\tdyn$\n            \\end{pfproof}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{5}{\\case{$\\snil \\sWTA \\esnd{\\tdyn}{\\svalue_0} : \\tdyn$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          similar to $\\sfst$\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{6}{\\case{$\\snil \\sWTA \\esum{\\tdyn}{\\svalue_0}{\\svalue_1} : \\tdyn$}}\n    \\begin{pfproof}\n      \\step{6.0}{$\\esum{\\tdyn}{\\svalue_0}{\\svalue_1} \\nredAD \\sdeltaA(\\sbinop, \\svalue_0, \\svalue_1)$}\n      \\step{6.1}{$\\sdeltaA(\\sbinop, \\svalue_0, \\svalue_1) \\in \\sint$}\n        \\begin{pfproof}\n          by definition $\\sdeltaA$\n        \\end{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          $\\snil \\sWTA \\sdeltaA(\\sbinop, \\svalue_0, \\svalue_1) : \\tdyn$\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{7}{\\case{$\\snil \\sWTA \\equotient{\\tdyn}{\\svalue_0}{\\svalue_1} : \\tdyn$}}\n    \\begin{pfproof}\n      \\step{7.0}{$\\equotient{\\tdyn}{\\svalue_0}{\\svalue_1} \\nredAD \\sdeltaA(\\sbinop, \\svalue_0, \\svalue_1)$}\n      \\step{7.1}{$\\sdeltaA(\\sbinop, \\svalue_0, \\svalue_1) \\in \\sint \\cup \\divisionbyzeroerror$}\n        \\begin{pfproof}\n          by definition $\\sdeltaA$\n        \\end{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          $\\snil \\sWTA \\sdeltaA(\\sbinop, \\svalue_0, \\svalue_1) : \\tdyn$\n        \\end{pfproof}\n    \\end{pfproof}\n\n\\end{lamportproof*}}\n\n\\begin{lemma}\\label{A-dyn-type-progress}\n  If\\/ $\\snil \\sWTA \\edynb{\\sbnd_0}{\\svalue_0} : \\stype_0$\n  and\\/ $\\sbnd_0 \\eeq \\obnd{\\sowner_0}{\\stype_0}{\\sowner_1}$\n  then\\/ $\\exists\\,\\sexpr_1$\n  such that\\/ $\\edynb{\\sbnd_0}{\\svalue_0} \\nredAS \\sexpr_1$.\n\\end{lemma}{\n  \\newcommand{\\shortproof}{By case analysis of $\\fshallow{\\tagof{\\stype_0}}{\\svalue_0}$.}\n\\begin{lamportproof*}\n  \\shortproof\n\\mainproof\n  \\shortproof\n\n  \\step{0}{\\case{$\\fshallow{\\tagof{\\stype_0}}{\\ehopt{\\sblist_2}{(\\efun{\\svar_1}{\\sexpr_1})}}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          $\\edynb{\\sbnd_0}{\\svalue_0} \\nredAS \\emon{\\sbnd_0}{\\svalue_0}$\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{1}{\\case{$\\fshallow{\\tagof{\\stype_0}}{\\efun{\\tann{\\svar_1}{\\stype_1}}{\\sexpr_1}}$}}\n    \\begin{pfproof}\n      \\absurdstep\n        \\begin{pfproof}\n          $\\snil \\sWTA \\edynb{\\sbnd_0}{\\svalue_0} : \\stype_0$\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{2}{\\case{$\\fshallow{\\tagof{\\stype_0}}{\\ehopt{\\sblist_2}{(\\emon{\\sbnd_1}{\\svalue_1})}}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          $\\edynb{\\sbnd_0}{\\svalue_0} \\nredAS \\emon{\\sbnd_0}{\\svalue_0}$\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{3}{\\case{$\\fshallow{\\tagof{(\\tpair{\\stype_1}{\\stype_2})}}{\\ehopt{\\sblist_2}{\\epair{\\svalue_1}{\\svalue_2}}}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          $\\edynb{\\sbnd_0}{\\svalue_0} \\nredAS \\emon{\\sbnd_0}{\\svalue_0}$\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{4}{\\case{$\\fshallow{\\tagof{\\tint}}{\\ehopt{\\sblist_1}{\\svalue_1}}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          $\\edynb{\\sbnd_0}{\\svalue_0} \\nredAS \\svalue_1$\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{5}{\\case{$\\fshallow{\\tagof{\\tnat}}{\\ehopt{\\sblist_1}{\\svalue_1}}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          $\\edynb{\\sbnd_0}{\\svalue_0} \\nredAS \\svalue_1$\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{6}{\\case{$\\neg\\fshallow{\\tagof{\\stype_0}}{\\svalue_0}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          $\\edynb{\\sbnd_0}{\\svalue_0} \\nredAS \\boundaryerror{\\sbnd_0}{\\svalue_0}$\n        \\end{pfproof}\n    \\end{pfproof}\n\n\\end{lamportproof*}}\n\n\\begin{lemma}\\label{A-sta-type-progress}\n  If\\/ $\\snil \\sWTA \\estab{\\sbnd_0}{\\svalue_0} : \\tdyn$\n  and\\/ $\\sbnd_0 \\eeq \\obnd{\\sowner_0}{\\stype_0}{\\sowner_1}$\n  then\\/ $\\exists\\,\\sexpr_1$\n  such that\\/ $\\estab{\\sbnd_0}{\\svalue_0} \\nredAD \\sexpr_1$.\n\\end{lemma}{\n  \\newcommand{\\shortproof}{By case analysis on $\\svalue_0$.}\n\\begin{lamportproof*}\n  \\shortproof\n\\mainproof\n  \\shortproof\n\n  \\step{0}{\\case{$\\svalue_0 \\in \\ehopt{\\sblist_2}{(\\efun{\\svar}{\\sexpr})}$}}\n    \\begin{pfproof}\n      \\absurdstep\n        \\begin{pfproof}\n          $\\snil \\sWTA \\estab{\\sbnd_0}{\\svalue_0} : \\tdyn$\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{1}{\\case{$\\svalue_0 \\in \\efun{\\tann{\\svar}{\\stype}}{\\sexpr}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          $\\estab{\\sbnd_0}{\\svalue_0} \\nredAD \\emon{\\sbnd_0}{\\svalue_0}$\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{2}{\\case{$\\svalue_0 \\eeq \\emon{\\sbnd_1}{\\svalue_1}$}}\n    \\begin{pfproof}\n      \\step{2.0}{\\scase{\\(\n       \\svalue_1 \\eeq \\ehopt{\\sblist_2}{\\svalue_2}\n      \\)\\\\and \\(\n       \\svalue_2 \\in (\\efun{\\svar}{\\sexpr}) \\cup \\epair{\\svalue}{\\svalue}\n      \\)}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              $\\estab{\\sbnd_0}{\\svalue_0} \\nredAD \\eprehist{\\fconcat{\\sbnd_0}{\\fconcat{\\sbnd_1}{\\sblist_2}}}{\\svalue_0}$\n            \\end{pfproof}\n        \\end{pfproof}\n      \\step{2.1}{\\scase{\\(\n       \\svalue_1 \\eeq \\ehopt{\\sblist_2}{(\\emon{\\sbnd_3}{\\svalue_2})}\n      \\)\\\\and \\(\n       \\svalue_2 \\in (\\efun{\\tann{\\svar}{\\stype}}{\\svalue}) \\cup \\epair{\\svalue}{\\svalue}\n      \\)}}\n        \\begin{pfproof}\n          $\\estab{\\sbnd_0}{\\svalue_0} \\nredAD \\eprehist{\\fconcat{\\sbnd_0}{\\fconcat{\\sbnd_1}{\\sblist_2}}}{(\\emon{\\sbnd_3}{\\svalue_2})}$\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{3}{\\case{$\\svalue_0 \\eeq \\epair{\\svalue_1}{\\svalue_2}$}}\n    \\begin{pfproof}\n      \\step{3.0}{$\\stype_0 \\eeq \\tpair{\\stype_1}{\\stype_2}$}\n        \\begin{pfproof}\n          by inversion $\\sWTA$\n        \\end{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          $\\estab{\\sbnd_0}{\\svalue_0} \\nredAD \\emon{\\sbnd_0}{\\svalue_0}$\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{4}{\\case{$\\svalue_0 \\in \\sint$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          $\\estab{\\sbnd_0}{\\svalue_0} \\nredAD \\svalue_0$\n        \\end{pfproof}\n    \\end{pfproof}\n\n\\end{lamportproof*}}\n\n\\begin{lemma}\\label{A-dyn-type-preservation}\\leavevmode\n  If\\/ $\\snil \\sWTA \\edynb{\\sbnd_0}{\\svalue_0} : \\stype_0$\n  and\\/ $\\sbnd_0 \\eeq \\obnd{\\sowner_0}{\\stype_0}{\\sowner_1}$\n  and\\/ $\\edynb{\\sbnd_0}{\\svalue_0} \\nredAS \\sexpr_1$\n  then\\/ $\\snil \\sWTA \\sexpr_1 : \\stype_0$.\n\\end{lemma}{\n  \\newcommand{\\shortproof}{By case analysis of $\\nredAS$.}\n\\begin{lamportproof*}\n  \\shortproof\n\\mainproof\n  \\shortproof\n\n  \\step{0}{\\case{\\(\n    \\edynb{\\sbnd_0}{\\svalue_0} \\nredAS \\emon{\\sbnd_0}{\\svalue_0}\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          \\begin{mathpar}\n            \\inferrule*{\n              \\inferrule*{\n                \\mbox{by inversion $\\sWTA$}\n              }{\n                \\snil \\sWTA \\svalue_0 : \\tdyn\n              }\n            }{\n              \\snil \\sWTA \\emon{\\sbnd_0}{\\svalue_0} : \\stype_0\n            }\n          \\end{mathpar}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{2}{\\case{\\(\n    \\edynb{\\sbnd_0}{\\ehopt{\\sblist_1}{\\sint_0}} \\nredAS \\sint_0\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by case analysis of $\\fshallow{\\tagof{\\stype_0}}{\\sint_0}$\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{3}{\\case{\\(\n    \\edynb{\\sbnd_0}{\\svalue_0} \\nredAS \\boundaryerror{\\sbnd_0}{\\svalue_0}\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          $\\snil \\sWTA \\boundaryerror{\\sbnd_0}{\\svalue_0} : \\stype_0$\n        \\end{pfproof}\n    \\end{pfproof}\n\n\\end{lamportproof*}}\n\n\\begin{lemma}\\label{A-sta-type-preservation}\n  If\\/ $\\snil \\sWTA \\estab{\\sbnd_0}{\\svalue_0} : \\tdyn$\n  and\\/ $\\sbnd_0 \\eeq \\obnd{\\sowner_0}{\\stype_0}{\\sowner_1}$\n  and\\/ $\\estab{\\sbnd_0}{\\svalue_0} \\nredAD \\sexpr_1$\n  then\\/ $\\snil \\sWTA \\sexpr_1$.\n\\end{lemma}{\n  \\newcommand{\\shortproof}{By case analysis of $\\nredAD$.}\n\\begin{lamportproof*}\n  \\shortproof\n\\mainproof\n  \\shortproof\n\n  \\step{0}{\\case{\\(\n    \\svalue_0 \\in (\\efun{\\tann{\\svar}{\\stype}}{\\sexpr}) \\cup (\\epair{\\svalue}{\\svalue})\n  \\) \\\\ and \\(\n    \\estab{\\sbnd_0}{\\svalue_0} \\nredAD \\emon{\\sbnd_0}{\\svalue_0}\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          \\begin{mathpar}\n            \\inferrule*{\n              \\inferrule*{\n                \\mbox{by inversion $\\sWTA$}\n              }{\n                \\snil \\sWTA \\svalue_0 : \\stype_0\n              }\n            }{\n              \\snil \\sWTA \\emon{\\sbnd_0}{\\svalue_0} : \\tdyn\n            }\n          \\end{mathpar}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{1}{\\case{\\(\n    \\svalue_0 \\in (\\efun{\\svar}{\\sexpr}) \\cup (\\epair{\\svalue}{\\svalue})\n  \\) \\\\ and \\(\n    \\estab{\\sbnd_0}{(\\emon{\\sbnd_1}{(\\ehopt{\\sblist_2}{\\svalue_0})})} \\nredAD \\eprehist{\\fconcat{\\sbnd_0}{\\fconcat{\\sbnd_1}{\\sblist_2}}}{\\svalue_0}\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          \\begin{mathpar}\n            \\inferrule*{\n              \\inferrule*{\n                \\mbox{by inversion $\\sWTA$}\n              }{\n                \\snil \\sWTA \\svalue_0 : \\tdyn\n              }\n            }{\n              \\snil \\sWTA \\eprehist{\\fconcat{\\sbnd_0}{\\fconcat{\\sbnd_1}{\\sblist_2}}}{\\svalue_0} : \\tdyn\n            }\n          \\end{mathpar}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{2}{\\case{\\(\n    \\svalue_0 \\in (\\efun{\\tann{\\svar}{\\stype}}{\\sexpr}) \\cup (\\epair{\\svalue}{\\svalue})\n  \\) \\\\ and \\(\n    \\estab{\\sbnd_0}{(\\emon{\\sbnd_1}{(\\ehopt{\\sblist_2}{(\\emon{\\sbnd_3}{\\svalue_0})})})} \\nredAD \\eprehist{\\fconcat{\\sbnd_0}{\\fconcat{\\sbnd_1}{\\sblist_2}}}{(\\emon{\\sbnd_3}{\\svalue_0})}\n  \\)\\\\ and \\(\n    \\sbnd_3 \\eeq \\obnd{\\sowner_4}{\\stype_3}{\\sowner_5}\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          \\begin{mathpar}\n            \\inferrule*{\n              \\inferrule*{\n                \\inferrule*{\n                  \\mbox{by inversion $\\sWTA$}\n                }{\n                  \\snil \\sWTA \\svalue_0 : \\stype_3\n                }\n              }{\n                \\snil \\sWTA \\emon{\\sbnd_3}{\\svalue_0} : \\tdyn\n              }\n            }{\n              \\snil \\sWTA \\eprehist{\\fconcat{\\sbnd_0}{\\fconcat{\\sbnd_1}{\\sblist_2}}}{(\\emon{\\sbnd_3}{\\svalue_0})} : \\tdyn\n            }\n          \\end{mathpar}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{3}{\\case{\\(\n    \\estab{\\sbnd_0}{\\sint_0} \\nredAD \\sint_0\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          $\\snil \\sWTA \\sint_0 : \\tdyn$\n        \\end{pfproof}\n    \\end{pfproof}\n\n\\end{lamportproof*}}\n\n\\begin{lemma}\\label{A-addtrace-type-preservation}\n  If\\/ $\\snil \\sWTA \\eprehist{\\sblist_0}{\\svalue_0} : \\tdyn$\n  then\\/ $\\snil \\sWTA \\faddtrace{\\sblist_0}{\\svalue_0} : \\tdyn$.\n\\end{lemma}{\n  \\newcommand{\\shortpf}{By case analysis of $\\saddtrace$.}\n\\begin{lamportproof*}\n  \\shortpf\n\\mainproof\n  \\shortpf\n\n  \\step{0}{\\case{\\(\\faddtrace{\\snil}{\\svalue_0} \\feq \\svalue_0\\)}}\n    \\begin{pfproof}\n      \\qedstep\n    \\end{pfproof}\n\n  \\step{1}{\\case{\\(\n    \\faddtrace{\\sblist_0}{\\obbars{\\ehist{\\sblist_1}{\\svalue_1}}{\\sownerlist_2}}\n    \\feq\n    \\ehist{\\fconcat{\\sblist_0}{\\sblist_1}}{\\obbars{\\svalue_1}{\\sownerlist_2}}\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by $\\snil \\sWTA \\svalue_1 : \\tdyn$\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{2}{\\case{\\(\n    \\faddtrace{\\sblist_0}{\\svalue_1}\n    \\feq\n    \\ehist{\\sblist_0}{\\svalue_1}\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by $\\snil \\sWTA \\svalue_1 : \\tdyn$\n        \\end{pfproof}\n    \\end{pfproof}\n\n\\end{lamportproof*}}\n\n\\begin{lemma}\\label{A-type-substitution}\\leavevmode\n  \\begin{itemize}\n    \\item\n      If\\/ $\\fcons{\\tann{\\svar_0}{\\stype_0}}{\\stypeenv_0} \\sWTA \\sexpr_1 : \\toptional$\n      and\\/ $\\snil \\sWTA \\svalue_0 : \\stype_0$\n      then\\/ $\\stypeenv_0 \\sWTA \\esubst{\\sexpr_1}{\\svar_0}{\\svalue_0} : \\toptional$\n    \\item\n      If\\/ $\\fcons{\\tann{\\svar_0}{\\tdyn}}{\\stypeenv_0} \\sWTA \\sexpr_1 : \\toptional$\n      and\\/ $\\snil \\sWTA \\svalue_0 : \\tdyn$\n      then\\/ $\\stypeenv_0 \\sWTA \\esubst{\\sexpr_1}{\\svar_0}{\\svalue_0} : \\toptional$\n  \\end{itemize}\n\\end{lemma}{\n  \\newcommand{\\shortpf}{By induction on $\\sexpr_1$.}\n\\begin{lamportproof*}\n  \\shortpf\n\\mainproof\n  \\shortpf\n\n  \\step{0}{\\case{$\\sexpr_1 \\eeq \\svar_2$}}\n    \\begin{pfproof}\n      \\step{0.0}{\\scase{$\\svar_0 \\eeq \\svar_2$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              {$\\esubst{\\sexpr_1}{\\svar_0}{\\svalue_0} \\eeq \\svalue_0$}\n            \\end{pfproof}\n        \\end{pfproof}\n      \\step{0.1}{\\scase{$\\svar_0 \\neq \\svar_2$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              {$\\esubst{\\sexpr_1}{\\svar_0}{\\svalue_0} \\eeq \\sexpr_1$}\n            \\end{pfproof}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{1}{\\case{$\\sexpr_1 \\eeq \\sint_0$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          {$\\esubst{\\sexpr_1}{\\svar_0}{\\svalue_0} \\eeq \\sexpr_1$}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{2}{\\case{$\\sexpr_1 \\eeq \\efun{\\svar_2}{\\sexpr_2}$}}\n    \\begin{pfproof}\n      \\step{2.0}{\\scase{$ \\svar_0 \\eeq \\svar_2$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              by \\pfih\n            \\end{pfproof}\n        \\end{pfproof}\n      \\step{2.1}{\\scase{$\\svar_0 \\neq \\svar_2$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              {$\\esubst{\\sexpr_1}{\\svar_0}{\\svalue_0} \\eeq \\sexpr_1$}\n            \\end{pfproof}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{3}{\\case{$\\sexpr_1 \\eeq \\efun{\\tann{\\svar_2}{\\stype_2}}{\\sexpr_2}$}}\n    \\begin{pfproof}\n      \\step{3.0}{\\scase{$ \\svar_0 \\eeq \\svar_2$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              by \\pfih\n            \\end{pfproof}\n        \\end{pfproof}\n      \\step{3.1}{\\scase{$\\svar_0 \\neq \\svar_2$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              {$\\esubst{\\sexpr_1}{\\svar_0}{\\svalue_0} \\eeq \\sexpr_1$}\n            \\end{pfproof}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{3}{\\case{$\\sexpr_1 \\eeq \\epair{\\sexpr_2}{\\sexpr_3}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{4}{\\case{$\\sexpr_1 \\eeq \\eapp{\\toptional}{\\sexpr_2}{\\sexpr_3}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{5}{\\case{$\\sexpr_1 \\eeq \\eunopt{\\stoptional}{\\sexpr_2}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{6}{\\case{$\\sexpr_1 \\eeq \\ebinopt{\\stoptional}{\\sexpr_2}{\\sexpr_3}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{7}{\\case{$\\sexpr_1 \\eeq \\edynb{\\sbnd_2}{\\sexpr_2}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{8}{\\case{$\\sexpr_1 \\eeq \\estab{\\sbnd_2}{\\sexpr_2}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{9}{\\case{$\\sexpr_1 \\eeq \\ehist{\\sblist_2}{\\svalue_2}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{10}{\\case{$\\sexpr_1 \\eeq \\eprehist{\\sblist_2}{\\sexpr_2}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n\\end{lamportproof*}}\n\n%\\begin{lemma}[inversion]\\label{$\\sWTA$ inversion}\\leavevmode\n%\\end{lemma}\n%\\begin{lemma}[canonical forms]\\label{$\\sWTA$ canonical forms}\\leavevmode\n%\\end{lemma}\n\n\\begin{lemma}[$\\sWLA$-progress]\\label{A-label-progress}\n  If\\/ $\\snil \\sWTA \\sexpr_0 : \\toptional$\n  and\\/ $\\snil; \\ownertop \\sWLA \\sexpr_0$\n  then one of the following holds:\n  \\begin{itemize}\n    \\item\n      $\\sexpr_0 \\in \\obbars{\\svalue}{\\sownerlist}$\n    \\item\n      $\\sexpr_0 \\in \\ctx\\ctxbars{\\eerr}{\\sowner}$\n    \\item\n      $\\exists\\,\\sexpr_1$\n      such that\\/ $\\sexpr_0 \\credA \\sexpr_1$\n  \\end{itemize}\n\\end{lemma}{\n  \\newcommand{\\shortpf}{By case analysis of $\\sexpr_0$.}\n\\begin{lamportproof*}\n  \\shortpf\n\\mainproof\n  \\shortpf\n\n  By \\lemmaref{A-label-decomposition}, it suffices to consider the following cases.\n\n  \\step{0}{\\case{$\\sexpr_0 \\in \\obbars{\\svalue}{\\sownerlist}$}}\n    \\begin{pfproof}\n      \\qedstep\n    \\end{pfproof}\n\n  \\step{1}{\\case{$\\sexpr_0 \\in \\ctx\\ctxbars{\\eerr}{\\sowner}$}}\n    \\begin{pfproof}\n      \\qedstep\n    \\end{pfproof}\n\n  \\step{2}{\\case{$\\sexpr_0 \\eeq \\ctx\\ctxbars{\\eapp{{\\stype_0}}{\\obbars{\\svalue_0}{\\sownerlist_0}}{\\svalue_1}}{\\sowner_1}$}}\n    \\begin{pfproof}\n      \\step{2.0}{$\\svalue_0 \\in (\\efun{\\tann{\\svar}{\\stype}}{\\sexpr}) \\cup (\\emon{\\sbnd}{\\svalue})$}\n        \\begin{pfproof}\n          by $\\sWTA$ inversion and canonical forms\n        \\end{pfproof}\n      \\step{2.1}{\\scase{\\(\n        \\svalue_0 \\eeq \\efun{\\tann{\\svar_2}{\\stype_2}}{\\sexpr_2}\n      \\)}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              $\\sexpr_0 \\nredAS \\ctx\\ctxbars{\\obbars{\\esubst{\\sexpr_2}{\\svar_2}{\\obars{\\svalue_1}{\\fconcat{\\sowner_1}{\\frev{\\sownerlist_0}}}}}{\\sownerlist_0}}{\\sowner_1}$\n            \\end{pfproof}\n        \\end{pfproof}\n      \\step{2.2}{\\scase{\\(\n        \\svalue_0 \\eeq \\emon{\\obnd{\\sowner_2}{(\\tfun{\\stype_2}{\\stype_3})}{\\sowner_3}}{\\obars{\\svalue_2}{\\sowner_4}}\n      \\)}}\n        \\begin{pfproof}\n          \\step{2.2.0}{\\pflet{\\(\n            \\sbnd_3 \\sassign \\obnd{\\sowner_2}{\\stype_3}{\\sowner_3}\n          \\) \\\\ and \\(\n            \\sbnd_4 \\sassign \\obnd{\\sowner_3}{\\stype_2}{\\sowner_2}\n          \\)}}\n          \\qedstep\n            \\begin{pfproof}\n              \\(\\sexpr_0 \\nredAS\n                \\ctx\\ctxbars{\\obbars{\\edynb{\\sbnd_3}{\\obars{\\eapp{\\tdyn}{\\svalue_2}{(\\estab{\\sbnd_4}{\\obbars{\\svalue_1}{\\fconcat{\\sowner_1}{\\fconcat{\\sowner_1}{\\frev{\\sownerlist_0}}}}})}}{\\sowner_4}}}{\\sownerlist_0}}{\\sowner_1}\n              \\)\n            \\end{pfproof}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{3}{\\case{$\\sexpr_0 \\eeq \\ctx\\ctxbars{\\eapp{\\tdyn}{\\obbars{\\svalue_0}{\\sownerlist_0}}{\\svalue_1}}{\\sowner_1}$}}\n    \\begin{pfproof}\n      \\step{3.0}{\\scase{$\\svalue_0 \\eeq \\ehopt{\\sblist_2}{\\obbars{\\efun{\\svar_2}{\\sexpr_2}}{\\sownerlist_3}}$}}\n        \\begin{pfproof}\n          \\step{3.0.0}{\\pflet{\\(\n            \\svalue_2 \\sassign \\faddtrace{\\frev{\\sblist_2}}{\\obbars{\\svalue_1}{\\fconcat{\\sowner_1}{\\fconcat{\\frev{\\sownerlist_0}}{\\frev{\\sownerlist_3}}}}}\n          \\)}}\n          \\qedstep\n            \\begin{pfproof}\n              \\(\\sexpr_0 \\nredAD\n                \\ctx\\ctxbars{\\obars{\\eprehist{\\sblist_2}{\\obbars{\\esubst{\\sexpr_2}{\\svar_2}{\\svalue_1}}{\\sownerlist_3}}}{\\sownerlist_0}}{\\sowner_1}\n              \\)\n            \\end{pfproof}\n        \\end{pfproof}\n      \\step{3.1}{\\scase{\\(\n        \\svalue_0 \\eeq \\ehopt{\\sblist_2}{\\obbars{\\emon{\\obnd{\\sowner_3}{\\obars{\\tfun{\\stype_2}{\\stype_3}}{\\sowner_4}}{\\sowner_4}}{\\obars{\\svalue_2}{\\sowner_5}}}{\\sownerlist_6}}\n      \\)}}\n        \\begin{pfproof}\n          \\step{3.1.0}{\\pflet{\\(\n            \\sbnd_7 \\sassign \\obnd{\\sowner_3}{\\stype_3}{\\sowner_4}\n          \\) \\\\and \\(\n            \\sbnd_8 \\sassign \\obnd{\\sowner_4}{\\stype_2}{\\sowner_3}\n          \\) \\\\and \\(\n            {\\stype_4} \\sassign \\fforget{\\stype_3}\n          \\)}}\n          \\qedstep\n            \\begin{pfproof}\n              \\(\\sexpr_0 \\nredAD\n                \\ctx\\ctxbars{\\obbars{\\eprehist{\\sblist_2}{\\obbars{\\estab{\\sbnd_7}{\\obars{\\eapp{{\\stype_4}}{\\svalue_2}{(\\edynb{\\sbnd_8}{\\obbars{\\svalue_2}{\\flast{\\sownerlist_6}}})}}{\\sowner_3}}}{\\sownerlist_6}}}{\\sownerlist_0}}{\\sowner_1}\n              \\)\n            \\end{pfproof}\n        \\end{pfproof}\n      \\step{3.2}{\\scase{$\\svalue_0 \\not\\in (\\efun{\\svar}{\\sexpr}) \\cup (\\emon{\\sbnd}{\\svalue})$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              $\\sexpr_0 \\nredAD \\ctx\\ctxbars{\\tagerrorD}{\\sowner_0}$\n            \\end{pfproof}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{4}{\\case{$\\sexpr_0 \\eeq \\ctx\\ctxbars{\\eunopt{\\stoptional}{\\obbars{\\svalue_0}{\\sownerlist_0}}}{\\sowner_1}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\lemmaref{A-typed-hole} and \\lemmaref{A-delta-label-progress}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{5}{\\case{$\\sexpr_0 \\eeq \\ctx\\ctxbars{\\ebinopt{\\stoptional}{\\obbars{\\svalue_0}{\\sownerlist_0}}{\\obbars{\\svalue_1}{\\sownerlist_1}}}{\\sowner_2}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\lemmaref{A-typed-hole} and \\lemmaref{A-delta-label-progress}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{6}{\\case{$\\sexpr_0 \\eeq \\ctx\\ctxbars{\\edynb{\\sbnd_0}{\\obbars{\\svalue_1}{\\sownerlist_1}}}{\\sowner_2}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\lemmaref{A-typed-hole} and \\lemmaref{A-dyn-label-progress}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{7}{\\case{$\\sexpr_0 \\eeq \\ctx\\ctxbars{\\estab{\\sbnd_0}{\\obbars{\\svalue_1}{\\sowner_1}}}{\\sowner_2}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\lemmaref{A-typed-hole} and \\lemmaref{A-sta-label-progress}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{8}{\\case{$\\sexpr_0 \\eeq \\ctx\\ctxbars{\\eprehist{\\sblist_0}{\\svalue_0}}{\\sowner_2}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          \\(\\sexpr_0 \\nredAD \\ctx\\ctxbars{\\faddtrace{\\sblist_0}{\\svalue_0}}{\\sowner_2}\\)\n        \\end{pfproof}\n    \\end{pfproof}\n\n\\end{lamportproof*}}\n\n\\begin{lemma}[$\\sWLA$-preservation]\\label{A-label-preservation}\n  If\\/ $\\snil \\sWTA \\sexpr_0 : \\toptional$\n  and\\/ $\\snil; \\ownertop \\sWLA \\sexpr_0$\n  and\\/ $\\sexpr_0 \\credA \\sexpr_1$\n  then\\/ $\\snil; \\ownertop \\sWLA \\sexpr_1$\n\\end{lemma}{\n  \\newcommand{\\shortpf}{By \\lemmaref{A-S-label-preservation} and \\lemmaref{A-D-label-preservation}.}\n\\begin{lamportproof*}\n  \\shortpf\n\\mainproof\n  \\shortpf\n\\end{lamportproof*}}\n\n\\begin{lemma}\\label{A-S-label-preservation}\n  If\\/ $\\snil \\sWTA \\sexpr_0 : \\stype_0$\n  and\\/ $\\snil; \\sowner_0 \\sWLA \\sexpr_0$\n  and\\/ $\\sexpr_0 \\nredAS \\sexpr_1$\n  then\\/ $\\snil; \\sowner_0 \\sWLA \\sexpr_1$\n\\end{lemma}{\n  \\newcommand{\\shortpf}{By case analysis of $\\nredAS$.}\n\\begin{lamportproof*}\n  \\shortpf\n  \\mainproof\n  \\shortpf\n\n  \\step{0}{\\case{\\(\n    \\sdeltaA(\\sunop, \\svalue_0) \\mbox{ is defined}\n  \\)\\\\and \\(\n    \\obars{\\eunopt{\\stype_1}{\\svalue_0}}{\\sowner_0}\n    \\nredAS\n    \\obars{\\sdeltaA(\\sunop, \\svalue_0)}{\\sowner_0}\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\lemmaref{A-delta-label-preservation}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{1}{\\case{\\(\n    \\sdeltaA(\\sbinop, {\\svalue_0}, {\\svalue_1}) \\mbox{ is defined}\n  \\)\\\\and \\(\n    \\obars{\\ebinopt{\\stype_1}{\\svalue_0}{\\svalue_1}}{\\sowner_0}\n    \\nredAS\n    \\obars{\\sdeltaA(\\sbinop, {\\svalue_0}, {\\svalue_1})}{\\sowner_0}\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\lemmaref{A-delta-label-preservation}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{2}{\\case{\\(\n    \\obars{\\eapp{{\\stype_0}}{\\obbars{\\efun{\\tann{\\svar_0}{{\\stype_1}}}{\\sexpr_0}}{\\sownerlist_0}}{\\svalue_1}}{\\sowner_1}\n    \\nredAS\n    \\obars{\\esubst{\\sexpr_0}{\\svar_0}{\\obbars{\\svalue_1}{\\fconcat{\\sowner_1}{\\frev{\\sownerlist_0}}}}}{\\fconcat{\\sownerlist_0}{\\sowner_1}}\n  \\)}}\n    \\begin{pfproof}\n      \\step{2.0}{$\\sownerlist_0 \\eeq \\sowner_1 \\cdots \\sowner_1$}\n        \\begin{pfproof}\n          by inversion $\\sWLA$\n        \\end{pfproof}\n      \\step{2.1}{$\\snil; \\sowner_0 \\sWLA \\obbars{\\svalue_1}{\\fconcat{\\sowner_1}{\\frev{\\sownerlist_0}}}$}\n        \\begin{pfproof}\n          by \\stepref{2.0} and inversion $\\sWLA$\n        \\end{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\lemmaref{A-label-substitution}\n          \\begin{mathpar}\n            \\inferrule*{\n              \\inferrule*{\n                \\mbox{by \\lemmaref{A-label-substitution}}\n              }{\n                \\snil; \\sowner_1 \\sWLA \\esubst{\\sexpr_0}{\\svar_0}{\\obbars{\\svalue_1}{\\fconcat{\\sowner_1}{\\frev{\\sownerlist_0}}}}\n              }\n            }{\n              \\snil; \\sowner_1 \\sWLA \\obars{\\esubst{\\sexpr_0}{\\svar_0}{\\obbars{\\svalue_1}{\\fconcat{\\sowner_1}{\\frev{\\sownerlist_0}}}}}{\\fconcat{\\sownerlist_0}{\\sowner_1}}\n            }\n          \\end{mathpar}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{3}{\\case{\\(\n    \\obars{\\eapp{{\\stype_0}}{\\obbars{\\emon{\\obnd{\\sowner_0}{\\obars{\\tfun{\\stype_1}{\\stype_2}}{\\sowner_1}}{\\sowner_1}}{\\obars{\\svalue_0}{\\sowner_2}}}{\\sownerlist_3}}{\\svalue_1}}{\\sowner_4}\n    \\\\\\nredAS\n    \\obars{\\edynb{\\obnd{\\sowner_0}{\\stype_0}{\\sowner_1}}{\\obars{\\eapp{\\tdyn}{\\svalue_0}{(\\estab{\\obnd{\\sowner_1}{\\stype_1}{\\sowner_0}}{\\obbars{\\svalue_1}{\\fconcat{\\sowner_4}{\\frev{\\sownerlist_3}}}})}}{\\sowner_2}}}{\\fconcat{\\sownerlist_3}{\\sowner_4}}\n  \\)}}\n    \\begin{pfproof}\n      \\step{3.0}{\\(\n        \\sowner_1 \\eeq \\sowner_2\n      \\)\\\\ and \\(\n        \\sownerlist_3 \\eeq \\sowner_4 \\cdots \\sowner_4\n      \\)}\n        \\begin{pfproof}\n          by inversion $\\sWLA$\n        \\end{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          \\begin{mathpar}\n            \\inferrule*{\n              \\inferrule*{\n                \\inferrule*{\n                  \\inferrule*{\n                    \\inferrule*{\n                      \\mbox{by inversion $\\sWLA$}\n                    }{\n                      \\snil; \\sowner_1 \\sWLA \\svalue_0\n                    }\n                    \\\\\n                    \\inferrule*{\n                      \\inferrule*{\n                        \\inferrule*{\n                          \\mbox{by inversion $\\sWLA$}\n                        }{\n                          \\snil; \\sowner_0 \\sWLA \\svalue_1\n                        }\n                      }{\n                        \\snil; \\sowner_0 \\sWLA \\obbars{\\svalue_1}{\\fconcat{\\sowner_4}{\\frev{\\sownerlist_3}}}\n                      }\n                    }{\n                      \\snil; \\sowner_1 \\sWLA \\estab{\\obnd{\\sowner_1}{\\stype_1}{\\sowner_0}}{\\obbars{\\svalue_1}{\\fconcat{\\sowner_4}{\\frev{\\sownerlist_3}}}}\n                    }\n                  }{\n                    \\snil; \\sowner_1 \\sWLA \\eapp{\\tdyn}{\\svalue_0}{(\\estab{\\obnd{\\sowner_1}{\\stype_1}{\\sowner_0}}{\\obbars{\\svalue_1}{\\fconcat{\\sowner_4}{\\frev{\\sownerlist_3}}}})}\n                  }\n                }{\n                  \\snil; \\sowner_1 \\sWLA \\obars{\\eapp{\\tdyn}{\\svalue_0}{(\\estab{\\obnd{\\sowner_1}{\\stype_1}{\\sowner_0}}{\\obbars{\\svalue_1}{\\fconcat{\\sowner_4}{\\frev{\\sownerlist_3}}}})}}{\\sowner_2}\n                }\n              }{\n                \\snil; \\sowner_0 \\sWLA \\edynb{\\obnd{\\sowner_0}{\\stype_0}{\\sowner_1}}{\\obars{\\eapp{\\tdyn}{\\svalue_0}{(\\estab{\\obnd{\\sowner_1}{\\stype_1}{\\sowner_0}}{\\obbars{\\svalue_1}{\\fconcat{\\sowner_4}{\\frev{\\sownerlist_3}}}})}}{\\sowner_2}}\n              }\n            }{\n              \\snil; \\sowner_0 \\sWLA \\obars{\\edynb{\\obnd{\\sowner_0}{\\stype_0}{\\sowner_1}}{\\obars{\\eapp{\\tdyn}{\\svalue_0}{(\\estab{\\obnd{\\sowner_1}{\\stype_1}{\\sowner_0}}{\\obbars{\\svalue_1}{\\fconcat{\\sowner_4}{\\frev{\\sownerlist_3}}}})}}{\\sowner_2}}}{\\fconcat{\\sownerlist_3}{\\sowner_4}}\n            }\n          \\end{mathpar}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{4}{\\case{\\(\n    \\obars{\\edynb{\\obnd{\\sowner_0}{\\stype_0}{\\sowner_1}}{\\obbars{\\svalue_0}{\\sownerlist_2}}}{\\sowner_3}\n    \\nredAS\n    \\sexpr_2\n  \\)}}\n    \\begin{pfproof}\n      by \\lemmaref{A-dyn-label-preservation}\n    \\end{pfproof}\n\n\\end{lamportproof*}}\n\n\\begin{lemma}\\label{A-D-label-preservation}\n  If\\/ $\\snil \\sWTA \\sexpr_0 : \\tdyn$\n  and\\/ $\\snil; \\sowner_0 \\sWLA \\sexpr_0$\n  and\\/ $\\sexpr_0 \\nredAD \\sexpr_1$\n  then\\/ $\\snil; \\sowner_0 \\sWLA \\sexpr_1$\n\\end{lemma}{\n  \\newcommand{\\shortpf}{By case analysis of $\\nredAD$.}\n\\begin{lamportproof*}\n  \\shortpf\n  \\mainproof\n  \\shortpf\n\n  \\step{0}{\\case{\\(\n    \\svalue_0 \\not\\in \\emon{\\obnd{\\sowner}{\\tpair{\\stype}{\\stype}}{\\sowner}}{\\svalue}\n  \\)\\\\and \\(\n    \\sdeltaA(\\sunop, {\\svalue_0}) \\mbox{ is not defined}\n  \\)\\\\and \\(\n    \\obars{\\eunopt{\\tdyn}{\\svalue_0}}{\\sowner_0}\n    \\nredAD\n    \\obars{\\tagerrorD}{\\sowner_0}\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n    \\end{pfproof}\n\n  \\step{1}{\\case{\\(\n    \\sdeltaA(\\sunop, {\\svalue_0}) \\mbox{ is defined}\n  \\)\\\\and \\(\n    \\obars{\\eunopt{\\tdyn}{\\svalue_0}}{\\sowner_0}\n    \\nredAD\n    \\obars{\\sdeltaA(\\sunop, {\\svalue_0})}{\\sowner_0}\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\lemmaref{A-delta-label-preservation}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{2}{\\case{\\(\n    \\obars{\\efst{\\tdyn}{\\obbars{\\ehopt{\\sblist_0}{\\obbars{\\emon{\\obnd{\\sowner_1}{\\obars{\\tpair{\\stype_0}{\\stype_1}}{\\sowner_2}}{\\sowner_2}}{\\obars{\\svalue_1}{\\sowner_3}}}{\\sownerlist_4}}}{\\sownerlist_5}}}{\\sowner_6}\n    \\nredAD\n    \\\\\\obars{\\eprehist{\\sblist_0}{\\obbars{\\estab{\\obnd{\\sowner_1}{\\stype_0}{\\sowner_2}}{\\obars{\\efst{{\\stype_0}}{\\svalue_1}}{\\sowner_3}}}{\\sownerlist_4}}}{\\fconcat{\\sownerlist_5}{\\sowner_6}}\n  \\)}}\n    \\begin{pfproof}\n      \\step{2.0}{\\(\n        \\sownerlist_5 \\eeq \\sowner_6 \\cdots \\sowner_6\n      \\)\\\\ and \\(\n        \\fbndeqowners{\\sblist_0}{\\sownerlist_4}\n      \\)\\\\and \\(\n        \\flast{\\sownerlist_4} \\eeq \\sowner_1\n      \\)\\\\and \\(\n        \\sowner_2 \\eeq \\sowner_3\n      \\)}\n        \\begin{pfproof}\n          by inversion $\\sWLA$\n        \\end{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          \\begin{mathpar}\n            \\inferrule*{\n              \\inferrule*{\n                \\inferrule*{\n                  \\inferrule*{\n                    \\inferrule*{\n                      \\inferrule*{\n                        \\mbox{by inversion $\\sWLA$}\n                      }{\n                        \\snil; \\sowner_2 \\sWLA \\svalue_1\n                      }\n                    }{\n                      \\snil; \\sowner_2 \\sWLA \\efst{{\\stype_0}}{\\svalue_1}\n                    }\n                  }{\n                    \\snil; \\sowner_2 \\sWLA \\obars{\\efst{{\\stype_0}}{\\svalue_1}}{\\sowner_3}\n                  }\n                }{\n                  \\snil; \\flast{\\sownerlist_4} \\sWLA \\estab{\\obnd{\\sowner_1}{\\stype_0}{\\sowner_2}}{\\obars{\\efst{{\\stype_0}}{\\svalue_1}}{\\sowner_3}}\n                }\n              }{\n                \\snil; \\sowner_6 \\sWLA \\eprehist{\\sblist_0}{\\obbars{\\estab{\\obnd{\\sowner_1}{\\stype_0}{\\sowner_2}}{\\obars{\\efst{{\\stype_0}}{\\svalue_1}}{\\sowner_3}}}{\\sownerlist_4}}\n              }\n            }{\n              \\snil; \\sowner_6 \\sWLA \\obars{\\eprehist{\\sblist_0}{\\obbars{\\estab{\\obnd{\\sowner_1}{\\stype_0}{\\sowner_2}}{\\obars{\\efst{{\\stype_0}}{\\svalue_1}}{\\sowner_3}}}{\\sownerlist_4}}}{\\fconcat{\\sownerlist_5}{\\sowner_6}}\n            }\n          \\end{mathpar}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{3}{\\case{\\(\n    \\obars{\\esnd{\\tdyn}{\\obbars{\\ehopt{\\sblist_0}{\\obbars{\\emon{\\obnd{\\sowner_1}{\\obars{\\tpair{\\stype_0}{\\stype_1}}{\\sowner_2}}{\\sowner_2}}{\\obars{\\svalue_1}{\\sowner_3}}}{\\sownerlist_4}}}{\\sownerlist_5}}}{\\sowner_6}\n    \\nredAD\n    \\\\\\obars{\\eprehist{\\sblist_0}{\\obbars{\\estab{\\obnd{\\sowner_1}{\\stype_1}{\\sowner_2}}{\\obars{\\esnd{{\\stype_1}}{\\svalue_1}}{\\sowner_3}}}{\\sownerlist_4}}}{\\fconcat{\\sownerlist_5}{\\sowner_6}}\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          similar to $\\sfst$\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{4}{\\case{\\(\n    \\sdeltaA(\\sbinop, {\\svalue_0}, {\\svalue_1}) \\mbox{ is not defined}\n  \\)\\\\and \\(\n    \\obars{\\ebinopt{\\tdyn}{\\svalue_0}{\\svalue_1}}{\\sowner_0}\n    \\nredAD\n    \\obars{\\tagerrorD}{\\sowner_0}\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n    \\end{pfproof}\n\n  \\step{5}{\\case{\\(\n    \\sdeltaA(\\sbinop, {\\svalue_0}, {\\svalue_1}) \\mbox{ is defined}\n  \\)\\\\and \\(\n    \\obars{\\ebinopt{\\tdyn}{\\svalue_0}{\\svalue_1}}{\\sowner_0}\n    \\nredAD\n    \\obars{\\sdeltaA(\\sbinop, {\\svalue_0}, {\\svalue_1})}{\\sowner_0}\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\lemmaref{A-delta-label-preservation}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{6}{\\case{\\(\n    \\obars{\\eapp{\\tdyn}{\\obbars{\\ehopt{\\sblist_0}{\\obbars{\\efun{\\svar_0}{\\sexpr_0}}{\\sownerlist_1}}}{\\sownerlist_2}}{\\svalue_1}}{\\sowner_3}\n    \\nredAD\n    \\\\\\obars{\\eprehist{\\sblist_0}{\\obbars{\\esubst{\\sexpr_0}{\\svar_0}{\\faddtrace{\\frev{\\sblist_0}}{\\obbars{\\svalue_1}{\\fconcat{\\sowner_3}{\\fconcat{\\frev{\\sownerlist_2}}{\\frev{\\sownerlist_1}}}}}}}{\\sownerlist_1}}}{\\fconcat{\\sownerlist_2}{\\sowner_3}}\n  \\)}}\n    \\begin{pfproof}\n      \\step{6.0}{\\(\n        \\sownerlist_2 \\eeq \\sowner_3 \\cdots \\sowner_3\n      \\)\\\\and \\(\n        \\fbndeqowners{\\sblist_0}{\\sownerlist_1}\n      \\)\\\\and \\(\n        \\snil; \\flast{\\sownerlist_1} \\sWLA \\efun{\\svar_0}{\\sexpr_0}\n      \\)}\n      \\step{6.1}{\\(\n        \\snil; \\flast{\\sownerlist_1} \\sWLA \\faddtrace{\\frev{\\sblist_0}}{\\obbars{\\svalue_1}{\\fconcat{\\sowner_3}{\\fconcat{\\frev{\\sownerlist_2}}{\\frev{\\sownerlist_1}}}}}\n      \\)}\n      \\qedstep\n        \\begin{pfproof}\n          \\begin{mathpar}\n            \\inferrule*{\n              \\inferrule*{\n                \\inferrule*{\n                  \\mbox{by \\lemmaref{A-label-substitution}}\n                }{\n                  \\snil; \\flast{\\sownerlist_1} \\sWLA \\esubst{\\sexpr_0}{\\svar_0}{\\faddtrace{\\frev{\\sblist_0}}{\\obbars{\\svalue_1}{\\fconcat{\\sowner_3}{\\fconcat{\\frev{\\sownerlist_2}}{\\frev{\\sownerlist_1}}}}}}\n                }\n              }{\n                \\snil; \\sowner_3 \\sWLA \\eprehist{\\sblist_0}{\\obbars{\\esubst{\\sexpr_0}{\\svar_0}{\\faddtrace{\\frev{\\sblist_0}}{\\obbars{\\svalue_1}{\\fconcat{\\sowner_3}{\\fconcat{\\frev{\\sownerlist_2}}{\\frev{\\sownerlist_1}}}}}}}{\\sownerlist_1}}\n              }\n            }{\n              \\snil; \\sowner_3 \\sWLA \\obars{\\eprehist{\\sblist_0}{\\obbars{\\esubst{\\sexpr_0}{\\svar_0}{\\faddtrace{\\frev{\\sblist_0}}{\\obbars{\\svalue_1}{\\fconcat{\\sowner_3}{\\fconcat{\\frev{\\sownerlist_2}}{\\frev{\\sownerlist_1}}}}}}}{\\sownerlist_1}}}{\\fconcat{\\sownerlist_2}{\\sowner_3}}\n            }\n          \\end{mathpar}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{7}{\\case{\\(\n    \\obars{\\eapp{\\tdyn}{\\obbars{\\ehopt{\\sblist_0}{\\obbars{\\emon{\\obnd{\\sowner_1}{\\obars{\\tfun{\\stype_0}{\\stype_1}}{\\sowner_2}}{\\sowner_2}}{\\obars{\\svalue_0}{\\sowner_3}}}{\\sownerlist_4}}}{\\sownerlist_5}}{\\svalue_1}}{\\sowner_6}\n    \\nredAD\n    \\\\\\obars{\\eprehist{\\sblist_0}{\\obbars{\\estab{\\obnd{\\sowner_1}{\\stype_1}{\\sowner_2}}{\\obars{\\eapp{{\\stype_1}}{\\svalue_0}{(\\edynb{\\obnd{\\sowner_2}{\\stype_0}{\\sowner_1}}{\\obars{\\svalue_2}{\\flast{\\sownerlist_4}}})}}{\\sowner_3}}}{\\sownerlist_4}}}{\\fconcat{\\sownerlist_5}{\\sowner_6}}\n  \\)}}\n    \\begin{pfproof}\n      \\step{7.0}{\\(\n        \\sownerlist_5 \\eeq \\sowner_6 \\cdots \\sowner_6\n      \\)\\\\and \\(\n        \\fbndeqowners{\\sblist_0}{\\sownerlist_4}\n      \\)\\\\and \\(\n        \\sowner_1 \\eeq \\flast{\\sownerlist_4}\n      \\)\\\\and \\(\n        \\sowner_2 \\eeq \\sowner_3\n      \\)}\n        \\begin{pfproof}\n          by inversion $\\sWLA$\n        \\end{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          \\begin{mathpar}\n            \\inferrule*{\n              \\inferrule*{\n                \\inferrule*{\n                  \\inferrule*{\n                    \\inferrule*{\n                      \\mbox{by inversion $\\sWLA$}\n                    }{\n                      \\snil; \\sowner_2 \\sWLA \\svalue_0\n                    }\n                    \\\\\n                    \\inferrule*{\n                      \\inferrule*{\n                        \\mbox{by inversion $\\sWLA$}\n                      }{\n                        \\snil; \\sowner_1 \\sWLA \\svalue_2\n                      }\n                    }{\n                      \\snil; \\sowner_2 \\sWLA \\edynb{\\obnd{\\sowner_2}{\\stype_0}{\\sowner_1}}{\\obars{\\svalue_2}{\\flast{\\sownerlist_4}}}\n                    }\n                  }{\n                    \\snil; \\sowner_2 \\sWLA \\eapp{{\\stype_1}}{\\svalue_0}{(\\edynb{\\obnd{\\sowner_2}{\\stype_0}{\\sowner_1}}{\\obars{\\svalue_2}{\\flast{\\sownerlist_4}}})}\n                  }\n                }{\n                  \\snil; \\flast{\\sownerlist_4} \\sWLA \\estab{\\obnd{\\sowner_1}{\\stype_1}{\\sowner_2}}{\\obars{\\eapp{{\\stype_1}}{\\svalue_0}{(\\edynb{\\obnd{\\sowner_2}{\\stype_0}{\\sowner_1}}{\\obars{\\svalue_2}{\\flast{\\sownerlist_4}}})}}{\\sowner_3}}\n                }\n              }{\n                \\snil; \\sowner_6 \\sWLA \\eprehist{\\sblist_0}{\\obbars{\\estab{\\obnd{\\sowner_1}{\\stype_1}{\\sowner_2}}{\\obars{\\eapp{{\\stype_1}}{\\svalue_0}{(\\edynb{\\obnd{\\sowner_2}{\\stype_0}{\\sowner_1}}{\\obars{\\svalue_2}{\\flast{\\sownerlist_4}}})}}{\\sowner_3}}}{\\sownerlist_4}}\n              }\n            }{\n              \\snil; \\sowner_6 \\sWLA \\obars{\\eprehist{\\sblist_0}{\\obbars{\\estab{\\obnd{\\sowner_1}{\\stype_1}{\\sowner_2}}{\\obars{\\eapp{{\\stype_1}}{\\svalue_0}{(\\edynb{\\obnd{\\sowner_2}{\\stype_0}{\\sowner_1}}{\\obars{\\svalue_2}{\\flast{\\sownerlist_4}}})}}{\\sowner_3}}}{\\sownerlist_4}}}{\\fconcat{\\sownerlist_5}{\\sowner_6}}\n            }\n          \\end{mathpar}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{8}{\\case{\\(\n    \\obars{\\estab{\\obnd{\\sowner_1}{\\stype_0}{\\sowner_2}}{\\obbars{\\svalue_0}{\\sowner_3}}}{\\sowner_0}\n    \\nredAD\n    \\sexpr_2\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\lemmaref{A-sta-label-preservation}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{9}{\\case{\\(\n    \\obars{\\eprehist{\\sblist_0}{\\svalue_0}}{\\sowner_1}\n    \\\\\\nredAD \\obars{\\faddtrace{\\sblist_0}{\\svalue_0}}{\\sowner_1}\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\lemmaref{A-addtrace-label-preservation}\n        \\end{pfproof}\n    \\end{pfproof}\n\n\\end{lamportproof*}}\n\n\\begin{lemma}\\label{A-label-decomposition}\n  If\\/ $\\snil \\sWTA \\sexpr_0 : \\toptional$\n  and\\/ $\\snil; \\sowner_0 \\sWLA \\sexpr_0$\n  then either:\n  \\begin{itemize}\n    \\item\n      $\\sexpr_0 \\in \\obbars{\\svalue}{\\sownerlist}$\n    \\item\n      $\\sexpr_0 \\eeq \\ctx_0\\ctxbars{\\eapp{\\toptional}{\\obars{\\svalue_0}{\\sownerlist_0}}{\\obars{\\svalue_1}{\\sowner_1}}}{\\sowner_2}$\n    \\item\n      $\\sexpr_0 \\eeq \\ctx_0\\ctxbars{\\eunopt{\\stoptional}{\\obbars{\\svalue_0}{\\sownerlist_0}}}{\\sowner_1}$\n    \\item\n      $\\sexpr_0 \\eeq \\ctx_0\\ctxbars{\\ebinopt{\\stoptional}{\\obbars{\\svalue_0}{\\sownerlist_0}}{\\obbars{\\svalue_1}{\\sownerlist_1}}}{\\sowner_2}$\n    \\item\n      $\\sexpr_0 \\eeq \\ctx_0\\ctxbars{\\edynb{\\sbnd_1}{\\obbars{\\svalue_1}{\\sownerlist_0}}}{\\sowner_1}$\n    \\item\n      $\\sexpr_0 \\eeq \\ctx_0\\ctxbars{\\estab{\\sbnd_1}{\\obbars{\\svalue_1}{\\sownerlist_0}}}{\\sowner_1}$\n    \\item\n      $\\sexpr_0 \\eeq \\ctx_0\\ctxbars{\\estab{\\sbnd_1}{\\obbars{\\svalue_1}{\\sownerlist_0}}}{\\sowner_1}$\n    \\item\n      $\\sexpr_0 \\eeq \\ctx_0\\ctxbars{\\eprehist{\\sblist_1}{\\obbars{\\svalue_1}{\\sownerlist_0}}}{\\sowner_1}$\n    \\item\n      $\\sexpr_0 \\eeq \\ctx_0\\ctxbars{\\eerr}{\\sowner_0}$\n  \\end{itemize}\n\\end{lemma}{\n  \\newcommand{\\shortproof}{By induction on the structure of $\\sexpr_0$.}\n\\begin{lamportproof*}\n  \\shortproof\n\\mainproof\\leavevmode\n  \\shortproof\n\n  \\step{0}{\\case{$\\sexpr_0 \\eeq \\svar_0$}}\n    \\begin{pfproof}\n      \\absurdstep\n        \\begin{pfproof}\n          $\\snil; \\sowner_0 \\sWLA \\sexpr_0$\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{1}{\\case{$\\sexpr_0 \\in \\obbars{\\svalue}{\\sownerlist}$}}\n    \\begin{pfproof}\n      \\qedstep\n    \\end{pfproof}\n\n  \\step{2}{\\case{$\\sexpr_0 \\eeq \\epair{\\sexpr_1}{\\sexpr_2}$}}\n    \\begin{pfproof}\n      \\step{2.0}{$\\snil \\sWTA \\sexpr_1 : \\toptional$ and $\\snil \\sWTA \\sexpr_2 : \\toptional$}\n        \\begin{pfproof}\n          by inversion $\\sWTA$\n        \\end{pfproof}\n      \\step{2.1}{$\\snil; \\sowner_0 \\sWLA \\sexpr_1$ and $\\snil; \\sowner_0 \\sWLA \\sexpr_2$}\n        \\begin{pfproof}\n          by inversion $\\sWLA$\n        \\end{pfproof}\n      \\step{2.2}{\\scase{$\\sexpr_1 \\not\\in \\obbars{\\svalue}{\\sownerlist}$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              by \\pfih\n            \\end{pfproof}\n        \\end{pfproof}\n      \\step{2.3}{\\scase{$\\sexpr_1 \\in \\obbars{\\svalue}{\\sownerlist}$ and $\\sexpr_2 \\not\\in \\obbars{\\svalue}{\\sownerlist}$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              by \\pfih\n            \\end{pfproof}\n        \\end{pfproof}\n      \\step{2.4}{\\scase{$\\sexpr_1 \\in \\obbars{\\svalue}{\\sownerlist}$ and $\\sexpr_2 \\in \\obbars{\\svalue}{\\sownerlist}$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              $\\sexpr_0 \\in \\svalue$\n            \\end{pfproof}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{3}{\\case{$\\sexpr_0 \\eeq \\eapp{\\toptional}{\\sexpr_1}{\\sexpr_2}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{4}{\\case{$\\sexpr_0 \\eeq \\eunopt{\\stoptional}{\\sexpr_1}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{5}{\\case{$\\sexpr_0 \\eeq \\ebinopt{\\stoptional}{\\sexpr_1}{\\sexpr_2}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{6}{\\case{$\\sexpr_0 \\eeq \\edynb{\\obnd{\\sowner_0}{\\stype_0}{\\sowner_1}}{\\obars{\\sexpr_1}{\\sowner_1}}$}}\n    \\begin{pfproof}\n      \\step{6.0}{$\\snil; \\sowner_1 \\sWLA \\sexpr_1$}\n        \\begin{pfproof}\n          by inversion $\\sWLA$\n        \\end{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{7}{\\case{$\\sexpr_0 \\eeq \\estab{\\sbnd_1}{\\sexpr_1}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{8}{\\case{$\\sexpr_0 \\eeq \\eprehist{\\sblist_1}{\\obbars{\\sexpr_1}{\\sownerlist_2}}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n\\end{lamportproof*}}\n\n\\begin{lemma}\\label{A-labeled-hole}\n  If\\/ $\\snil; \\sowner_0 \\sWLA \\ctx_0[\\sexpr_0]$\n  then\\/ $\\exists\\,\\sowner_1$\n  such that\\/ $\\snil; \\sowner_1 \\sWLA \\sexpr_0$\n\\end{lemma}{\n\\newcommand{\\shortproof}{By induction on the structure of $\\ctx_0$.}\n\\begin{lamportproof*}\n  \\shortproof\n\\mainproof\n  \\shortproof\n\n  \\step{0}{$\\ctx_0 \\eeq \\ctxhole$}\n    \\begin{pfproof}\n      \\qedstep\n    \\end{pfproof}\n\n  \\step{1}{$\\ctx_0 \\eeq \\epair{\\ctx_1}{\\sexpr_2}$}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{2}{$\\ctx_0 \\eeq \\epair{\\sexpr_1}{\\ctx_2}$}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{3}{$\\ctx_0 \\eeq \\eunopt{\\stoptional}{\\ctx_1}$}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{4}{$\\ctx_0 \\eeq \\ebinopt{\\stoptional}{\\ctx_1}{\\sexpr_2}$}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{5}{$\\ctx_0 \\eeq \\ebinopt{\\stoptional}{\\sexpr_1}{\\ctx_2}$}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{6}{$\\ctx_0 \\eeq \\edynb{\\obnd{\\sowner_0}{\\stype_0}{\\sowner_2}}{\\obars{\\ctx_1}{\\sowner_3}}$}\n    \\begin{pfproof}\n      \\step{6.0}{$\\snil; \\sowner_2 \\sWLA \\ctx_1[\\sexpr_0]$}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{7}{$\\ctx_0 \\eeq \\estab{\\obnd{\\sowner_0}{\\stype_0}{\\sowner_2}}{\\obars{\\ctx_1}{\\sowner_3}}$}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{8}{$\\ctx_0 \\eeq \\obars{\\ctx_1}{\\sowner_0}$}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{9}{$\\ctx_0 \\eeq \\eprehist{\\sblist_1}{\\obbars{\\ctx_1}{\\sownerlist_1}}$}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n\\end{lamportproof*}}\n\n\\begin{lemma}[$\\sWLA$ replacement]\\label{A-label-replacement}\n  If\\/ $\\snil; \\sowner_0 \\sWLA \\ctx_0[\\sexpr_0]$\n  and the derivation contains a proof of\\/ $\\snil; \\sowner_1 \\sWLA \\sexpr_0$\n  and\\/ $\\snil; \\sowner_1 \\sWLA \\sexpr_1$\n  then\\/ $\\sownerenv_0; \\sowner_0 \\sWLA \\ctx_0[\\sexpr_1]$\n\\end{lemma}{\n\\newcommand{\\shortproof}{By induction on the structure of $\\ctx_0$.}\n\\begin{lamportproof*}\n  \\shortproof\n\\mainproof\n  \\shortproof\n\n  \\step{0}{$\\ctx_0 \\eeq \\ctxhole$}\n    \\begin{pfproof}\n      \\qedstep\n    \\end{pfproof}\n\n  \\step{1}{$\\ctx_0 \\eeq \\epair{\\ctx_1}{\\sexpr_2}$}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{2}{$\\ctx_0 \\eeq \\epair{\\sexpr_1}{\\ctx_2}$}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{3}{$\\ctx_0 \\eeq \\eunopt{\\stoptional}{\\ctx_1}$}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{4}{$\\ctx_0 \\eeq \\ebinopt{\\stoptional}{\\ctx_1}{\\sexpr_2}$}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{5}{$\\ctx_0 \\eeq \\ebinopt{\\stoptional}{\\sexpr_1}{\\ctx_2}$}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{6}{$\\ctx_0 \\eeq \\edynb{\\obnd{\\sowner_0}{\\stype_0}{\\sowner_2}}{\\obars{\\ctx_1}{\\sowner_3}}$}\n    \\begin{pfproof}\n      \\step{6.0}{$\\snil; \\sowner_2 \\sWLA \\ctx_1[\\sexpr_0]$}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{7}{$\\ctx_0 \\eeq \\estab{\\obnd{\\sowner_0}{\\stype_0}{\\sowner_2}}{\\obars{\\ctx_1}{\\sowner_3}}$}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{8}{$\\ctx_0 \\eeq \\obars{\\ctx_1}{\\sowner_0}$}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{9}{$\\ctx_0 \\eeq \\eprehist{\\sblist_1}{\\obbars{\\ctx_1}{\\sownerlist_1}}$}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n\\end{lamportproof*}}\n\n\\begin{lemma}[$\\sdeltaA$ label progress]\\label{A-delta-label-progress}\\leavevmode\n  \\begin{itemize}\n    \\item\n      If\\/ $\\snil \\sWTA \\eunopt{\\stype_1}{\\svalue_0} : \\stype_0$\n      and\\/ $\\snil; \\sowner_0 \\sWLA \\eunopt{\\stype_1}{\\svalue_0}$\n      and\\/ $\\obars{\\eunopt{\\stype_1}{\\svalue_0}}{\\sowner_0} \\nredAS \\obars{\\sexpr_1}{\\sowner_0}$.\n    \\item\n      if\\/ $\\snil \\sWTA \\ebinopt{\\stype_1}{\\svalue_0}{\\svalue_1} : \\stype_0$\n      and\\/ $\\snil; \\sowner_0 \\sWLA \\ebinopt{\\stype_1}{\\svalue_0}{\\svalue_1}$\n      and\\/ $\\obars{\\ebinopt{\\stype_1}{\\svalue_0}{\\svalue_1}}{\\sowner_0} \\nredAS \\obars{\\sexpr_2}{\\sowner_0}$.\n    \\item\n      If\\/ $\\snil \\sWTA \\eunopt{\\tdyn}{\\svalue_0} : \\tdyn$\n      and\\/ $\\snil; \\sowner_0 \\sWLA \\eunopt{\\tdyn}{\\svalue_0}$\n      then\\/ $\\obars{\\eunopt{\\tdyn}{\\svalue_0}}{\\sowner_0} \\nredAD \\obars{\\sexpr_1}{\\sowner_0}$.\n    \\item\n      if\\/ $\\snil \\sWTA \\ebinopt{\\tdyn}{\\svalue_0}{\\svalue_1} : \\tdyn$\n      and\\/ $\\snil; \\sowner_0 \\sWLA \\ebinopt{\\tdyn}{\\svalue_0}{\\svalue_1}$\n      then\\/ $\\obars{\\ebinopt{\\tdyn}{\\svalue_0}{\\svalue_1}}{\\sowner_0} \\nredAD \\obars{\\sexpr_2}{\\sowner_0}$.\n  \\end{itemize}\n\\end{lemma}{\n  \\newcommand{\\shortpf}{By case analysis of $\\sdeltaA$, $\\sWTA$, $\\sWLA$, and $\\nredAD$.}\n\\begin{lamportproof*}\n  \\shortpf\n\\mainproof\n  \\shortpf\n\n  \\step{0}{\\case{$\\snil \\sWTA \\eunopt{\\stype_1}{\\svalue_0} : \\stype_0$}}\n    \\begin{pfproof}\n      \\step{0.0}{$\\svalue_0 \\in (\\obbars{\\epair{\\svalue}{\\svalue}}{\\sownerlist}) \\cup (\\obbars{\\emon{\\obnd{\\sowner}{\\obars{\\tpair{\\stype}{\\stype}}{\\sowner}}{\\sowner}}{\\svalue}}{\\sownerlist})$}\n        \\begin{pfproof}\n          by $\\sWTA$ inversion and canonical forms\n        \\end{pfproof}\n      \\step{0.1}{\\scase{$\\svalue_0 \\eeq \\obbars{\\epair{\\svalue_1}{\\svalue_2}}{\\sownerlist_0}$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              $\\obars{\\eunopt{\\stype_1}{\\svalue_0}}{\\sowner_0} \\nredAS \\obars{\\sdeltaA(\\sunop, \\svalue_0)}{\\sowner_0}$\n            \\end{pfproof}\n        \\end{pfproof}\n      \\step{0.2}{\\scase{$\\svalue_0 \\eeq \\obbars{\\emon{\\obnd{\\sowner_1}{\\obars{\\tpair{\\stype_1}{\\stype_2}}{\\sowner_2}}{\\sowner_2}}{\\svalue_1}}{\\sownerlist_3}$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              $\\obars{\\efst{{\\stype_0}}{\\svalue_0}}{\\sowner_0} \\nredAS \\obbars{\\edynb{\\obnd{\\sowner_1}{\\stype_0}{\\sowner_2}}{(\\efst{\\tdyn}{\\svalue_1})}}{\\fconcat{\\sownerlist_3}{\\sowner_1}}$\n              \\\\(and similarly for $\\ssnd$)\n            \\end{pfproof}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{1}{\\case{$\\snil \\sWTA \\ebinopt{\\stype_1}{\\svalue_0}{\\svalue_1} : \\stype_0$}}\n    \\begin{pfproof}\n      \\step{2.0}{$\\svalue_0 \\in \\obbars{\\sint}{\\sownerlist}$ and $\\svalue_1 \\in \\obbars{\\sint}{\\sownerlist}$}\n        \\begin{pfproof}\n          by $\\sWTA$ inversion and canonical forms\n        \\end{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          $\\obars{\\ebinopt{\\stype_1}{\\svalue_0}{\\svalue_1}}{\\sowner_0} \\nredAS \\obars{\\sdeltaA(\\sbinop, \\svalue_0, \\svalue_1)}{\\sowner_0}$\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{2}{\\case{$\\snil \\sWTA \\eunopt{\\tdyn}{\\svalue_0} : \\tdyn$}}\n    \\begin{pfproof}\n      \\step{2.0}{\\scase{$\\svalue_0 \\in \\ehopt{\\sblist}{\\obbars{\\emon{\\sbnd}{\\obars{\\svalue}{\\sowner}}}{\\sownerlist}}$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              by definition $\\nredAD$\n            \\end{pfproof}\n        \\end{pfproof}\n      \\step{2.1}{\\scase{$\\svalue_0 \\in \\ehopt{\\sblist}{\\obbars{\\epair{\\svalue}{\\svalue}}{\\sownerlist}}$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              $\\obars{\\eunopt{\\tdyn}{\\svalue_0}}{\\sowner_0} \\nredAD \\obars{\\sdeltaA(\\sunop, \\svalue_0)}{\\sowner_0}$\n            \\end{pfproof}\n        \\end{pfproof}\n      \\step{2.2}{\\scase{$\\fremtrace{\\svalue_0} \\not\\in \\epair{\\svalue}{\\svalue} \\cup (\\emon{\\sbnd}{\\obars{\\svalue}{\\sowner}})$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              $\\obars{\\eunopt{\\tdyn}{\\svalue_0}}{\\sowner_0} \\nredAD\n              \\obars{\\tagerrorD}{\\sowner_0}$\n            \\end{pfproof}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{3}{\\case{$\\snil \\sWTA \\ebinopt{\\tdyn}{\\svalue_0}{\\svalue_1} : \\tdyn$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by definition $\\nredAD$\n        \\end{pfproof}\n    \\end{pfproof}\n\n\\end{lamportproof*}}\n\n\\begin{lemma}[$\\sdeltaA$ label preservation]\\label{A-delta-label-preservation}\\leavevmode\n  \\begin{itemize}\n    \\item\n      If\\/ $\\snil; \\sowner_0 \\sWLA \\eunopt{\\stoptional}{\\svalue_0}$\n      and\\/ $\\obars{\\eunopt{\\stoptional}{\\svalue_0}}{\\sowner_0} \\nredAX \\obars{\\sexpr_1}{\\sowner_0}$\n      then\\/ $\\snil; \\sowner_0 \\sWLA \\sexpr_1$.\n    \\item\n      If\\/ $\\snil; \\sowner_0 \\sWLA \\ebinopt{\\stoptional}{\\svalue_0}{\\svalue_1}$\n      and\\/ $\\obars{\\ebinopt{\\stoptional}{\\svalue_0}{\\svalue_1}}{\\sowner_0} \\nredAX \\obars{\\sexpr_1}{\\sowner_0}$\n      then\\/ $\\snil; \\sowner_0 \\sWLA \\sexpr_1$.\n  \\end{itemize}\n\\end{lemma}{\n\\newcommand{\\shortproof}{By case analysis of $\\nredAX$.}\n\\begin{lamportproof*}\n  \\shortproof\n\\mainproof\n  \\shortproof\n\n  \\step{0}{\\(\n    \\obars{\\efst{{\\stype_0}}{\\obbars{\\epair{\\svalue_1}{\\svalue_2}}{\\sownerlist_1}}}{\\sowner_0}\n    \\nredAS\n    \\obars{\\obbars{\\svalue_1}{\\sownerlist_1}}{\\sowner_0}\n  \\)}\n    \\begin{pfproof}\n      \\step{0.0}{\\(\n        \\snil; \\sowner_0 \\sWLA {\\svalue_0}\n      \\)\\\\and \\(\n        \\sownerlist_1 \\eeq \\sowner_0 \\cdots \\sowner_0\n      \\)}\n        \\begin{pfproof}\n          by inversion $\\sWLA$\n        \\end{pfproof}\n      \\qedstep\n    \\end{pfproof}\n\n  \\step{1}{\\(\n    \\obars{\\efst{{\\stype_0}}{\\obbars{\\emon{\\obnd{\\sowner_1}{\\obars{\\tpair{\\stype_1}{\\stype_2}}{\\sowner_2}}{\\sowner_2}}{\\obars{\\svalue_1}{\\sowner_2}}}{\\sownerlist_3}}}{\\sowner_0}\n    \\nredAS\n    \\obars{\\edynb{\\obnd{\\sowner_1}{\\stype_0}{\\sowner_2}}{\\obars{\\efst{\\tdyn}{\\svalue_0}}{\\sowner_2}}}{\\fconcat{\\sownerlist_3}{\\sowner_0}}\n  \\)}\n    \\begin{pfproof}\n      \\step{1.0}{\\(\n        \\sownerlist_3 \\eeq \\sowner_0 \\cdots \\sowner_0\n      \\)\\\\and \\(\n        \\sowner_0 \\eeq \\sowner_1\n      \\)}\n        \\begin{pfproof}\n          by inversion $\\sWLA$\n        \\end{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          \\begin{mathpar}\n            \\inferrule*{\n              \\inferrule*{\n                \\inferrule*{\n                  \\inferrule*{\n                    \\mbox{by inversion $\\sWLA$}\n                  }{\n                    \\snil; \\sowner_0 \\sWLA {\\svalue_0}\n                  }\n                }{\n                  \\snil; \\sowner_0 \\sWLA \\efst{\\tdyn}{\\svalue_0}\n                }\n              }{\n                \\snil; \\sowner_0 \\sWLA \\edynb{\\obnd{\\sowner_1}{\\stype_0}{\\sowner_2}}{\\obars{\\efst{\\tdyn}{\\svalue_0}}{\\sowner_2}}\n              }\n            }{\n              \\snil; \\sowner_0 \\sWLA \\obars{\\edynb{\\obnd{\\sowner_1}{\\stype_0}{\\sowner_2}}{\\obars{\\efst{\\tdyn}{\\svalue_0}}{\\sowner_2}}}{\\fconcat{\\sownerlist_3}{\\sowner_0}}\n            }\n          \\end{mathpar}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{2}{\\(\n    \\obars{\\efst{\\tdyn}{\\obbars{\\ehopt{\\sblist_0}{\\obbars{\\epair{\\svalue_1}{\\svalue_2}}{\\sownerlist_1}}}{\\sownerlist_2}}}{\\sowner_0}\n    \\nredAD\n    \\obars{\\faddtrace{\\sblist_0}{\\obbars{\\svalue_1}{\\sownerlist_1}}}{\\fconcat{\\sownerlist_2}{\\sowner_0}}\n  \\)}\n    \\begin{pfproof}\n      \\step{2.0}{\\(\n        \\sownerlist_2 \\eeq \\sowner_0 \\cdots \\sowner_0\n      \\)\\\\and \\(\n        \\fbndeqowners{\\sblist_0}{\\sownerlist_1}\n      \\)\\\\and \\(\n        \\snil; \\flast{\\sownerlist_1} \\sWLA \\svalue_1\n      \\)}\n        \\begin{pfproof}\n          by inversion $\\sWLA$\n        \\end{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\lemmaref{A-addtrace-label-preservation}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{3}{\\(\n    \\obars{\\efst{\\tdyn}{\\obbars{\\ehopt{\\sblist_0}{\\obbars{\\emon{\\obnd{\\sowner_1}{\\obars{\\tpair{\\stype_1}{\\stype_2}}{\\sowner_2}}{\\sowner_2}}{\\obars{\\svalue_1}{\\sowner_3}}}{\\sownerlist_4}}}{\\sownerlist_5}}}{\\sowner_0}\n    \\nredAD\n    \\\\\\obars{\\eprehist{\\sblist_0}{\\obbars{\\estab{\\obnd{\\sowner_1}{\\stype_1}{\\sowner_2}}{\\obars{\\efst{\\fforget{\\stype_1}}{\\svalue_1}}{\\sowner_3}}}{\\sownerlist_4}}}{\\fconcat{\\sownerlist_5}{\\sowner_0}}\n  \\)}\n    \\begin{pfproof}\n      \\step{1.0}{\\(\n        \\sownerlist_5 \\eeq \\sowner_0 \\cdots \\sowner_0\n      \\)\\\\and \\(\n        \\fbndeqowners{\\sblist_0}{\\sownerlist_4}\n      \\)\\\\and \\(\n        \\flast{\\sownerlist_4} \\eeq \\sowner_1\n      \\)\\\\and \\(\n        \\snil; \\sowner_2 \\sWLA \\svalue_1\n      \\)}\n        \\begin{pfproof}\n          by inversion $\\sWLA$\n        \\end{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          \\begin{mathpar}\n            \\inferrule*{\n              \\inferrule*{\n                \\inferrule*{\n                  \\inferrule*{\n                    \\inferrule*{\n                      \\mbox{by inversion $\\sWLA$}\n                    }{\n                      \\snil; \\sowner_0 \\sWLA \\svalue_1\n                    }\n                  }{\n                    \\snil; \\sowner_0 \\sWLA \\efst{\\fforget{\\stype_1}}{\\svalue_1}\n                  }\n                }{\n                  \\snil; \\sowner_0 \\sWLA \\estab{\\obnd{\\sowner_1}{\\stype_1}{\\sowner_2}}{\\obars{\\efst{\\fforget{\\stype_1}}{\\svalue_1}}{\\sowner_3}}\n                }\n              }{\n                \\snil; \\sowner_0 \\sWLA \\eprehist{\\sblist_0}{\\obbars{\\estab{\\obnd{\\sowner_1}{\\stype_1}{\\sowner_2}}{\\obars{\\efst{\\fforget{\\stype_1}}{\\svalue_1}}{\\sowner_3}}}{\\sownerlist_4}}\n              }\n            }{\n              \\snil; \\sowner_0 \\sWLA \\obars{\\eprehist{\\sblist_0}{\\obbars{\\estab{\\obnd{\\sowner_1}{\\stype_1}{\\sowner_2}}{\\obars{\\efst{\\fforget{\\stype_1}}{\\svalue_1}}{\\sowner_3}}}{\\sownerlist_4}}}{\\fconcat{\\sownerlist_5}{\\sowner_0}}\n            }\n          \\end{mathpar}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{4}{$\\obars{\\esnd{\\toptional}{\\svalue_0}}{\\sowner_0} \\nredAX \\obbars{\\sexpr_2}{\\sowner_0}$}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          similar to $\\sfst$ cases\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{5}{$\\obars{\\esum{\\stoptional}{\\svalue_0}{\\svalue_1}}{\\sowner_0} \\nredAX \\obars{\\sint_2}{\\sowner_0}$}\n    \\begin{pfproof}\n      \\qedstep\n    \\end{pfproof}\n\n  \\step{3}{$\\obars{\\equotient{\\stoptional}{\\svalue_0}{\\svalue_1}}{\\sowner_0} \\nredAX \\obars{\\divisionbyzeroerror}{\\sowner_0}$}\n    \\begin{pfproof}\n      \\qedstep\n    \\end{pfproof}\n\n  \\step{4}{$\\obars{\\equotient{\\stoptional}{\\obbars{\\sint_1}{\\sowner_1}}{\\obbars{\\sint_2}{\\sowner_2}}}{\\sowner_0} \\nredAX \\obars{\\floorof{\\sint_1 / \\sint_2}}{\\sowner_0}$}\n    \\begin{pfproof}\n      \\qedstep\n    \\end{pfproof}\n\n\\end{lamportproof*}}\n\n\\begin{lemma}\\label{A-dyn-label-progress}\n  If\\/ $\\snil \\sWTA \\edynb{\\sbnd_0}{\\svalue_0} : \\stype_0$\n  and\\/ $\\snil; \\sowner_0 \\sWLA \\edynb{\\sbnd_0}{\\svalue_0}$\n  then\\/ $\\obars{\\edynb{\\sbnd_0}{\\svalue_0}}{\\sowner_0} \\nredAS \\obars{\\sexpr_1}{\\sowner_0}$.\n\\end{lemma}{\n  \\newcommand{\\shortproof}{By inversion of $\\sWTA$ and case analysis of $\\fshallow{\\tagof{\\stype_0}}{\\svalue_0}$.}\n\\begin{lamportproof*}\n  \\shortproof\n\\mainproof\n  \\shortproof\n  % maybe should go by possible values, show which are contradictory ... that way there's no question we missed any\n\n  \\step{0}{\\(\n    \\sbnd_0 \\eeq \\obnd{\\sowner_0}{\\stype_0}{\\sowner_1}\n  \\)\\\\and \\(\n    \\sowner_0; \\sowner_1 \\sWL \\stype_0\n  \\)\\\\and \\(\n    \\snil; \\sowner_1 \\sWLA \\svalue_0\n  \\)\\\\and \\(\n    \\svalue_0 \\eeq \\obbars{\\svalue_1}{\\sowner_1}\n  \\)}\n    \\begin{pfproof}\n      by inversion $\\sWLA$\n    \\end{pfproof}\n\n  \\step{2}{\\case{\\(\n    \\fshallow{\\tagof{\\stype_0}}{\\svalue_1}\n  \\)\\\\and \\(\n    \\fremtrace{\\svalue_1} \\in \\obbars{\\efun{\\svar}{\\sexpr}}{\\sownerlist} \\cup \\obbars{\\epair{\\svalue}{\\svalue}}{\\sownerlist} \\cup \\obbars{\\emon{\\sbnd}{\\svalue}}{\\sownerlist}\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          $\\obars{\\edynb{\\sbnd_0}{\\svalue_0}}{\\sowner_0} \\nredAS \\obars{\\emon{\\sbnd_0}{\\svalue_0}}{\\sowner_0}$\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{4}{\\case{$\\svalue_1 \\in \\sint$ and $\\fshallow{\\tagof{\\tint}}{\\svalue_1}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          $\\obars{\\edynb{\\sbnd_0}{\\svalue_0}}{\\sowner_0} \\nredAS \\obars{\\svalue_1}{\\sowner_0}$\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{5}{\\case{$\\svalue_1 \\in \\snat$ and $\\fshallow{\\tagof{\\tnat}}{\\svalue_1}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          $\\obars{\\edynb{\\sbnd_0}{\\svalue_0}}{\\sowner_0} \\nredAS \\obars{\\svalue_1}{\\sowner_0}$\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{6}{\\case{$\\neg\\fshallow{\\tagof{\\stype_0}}{\\svalue_1}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          $\\obars{\\edynb{\\sbnd_0}{\\svalue_0}}{\\sowner_0} \\nredAS \\obars{\\boundaryerror{\\sbnd_0}{\\svalue_0}}{\\sowner_0}$\n        \\end{pfproof}\n    \\end{pfproof}\n\n\\end{lamportproof*}}\n\n\\begin{lemma}\\label{A-sta-label-progress}\n  If\\/ $\\snil \\sWTA \\estab{\\sbnd_0}{\\svalue_0} : \\tdyn$\n  and\\/ $\\snil; \\sowner_0 \\sWLA \\estab{\\sbnd_0}{\\svalue_0}$\n  then\\/ $\\obars{\\estab{\\sbnd_0}{\\svalue_0}}{\\sowner_0} \\nredAD \\obars{\\sexpr_1}{\\sowner_0}$.\n\\end{lemma}{\n  \\newcommand{\\shortproof}{By case analysis on $\\svalue_0$.}\n\\begin{lamportproof*}\n  \\shortproof\n\\mainproof\n  \\shortproof\n\n  \\step{0}{\\(\n    \\sbnd_0 \\eeq \\obnd{\\sowner_0}{\\stype_0}{\\sowner_1}\n  \\)\\\\and \\(\n    \\sowner_0; \\sowner_1 \\sWL \\stype_0\n  \\)\\\\and \\(\n    \\snil; \\sowner_1 \\sWLA \\svalue_0\n  \\)\\\\and \\(\n    \\svalue_0 \\eeq \\obbars{\\svalue_1}{\\sownerlist_2}\n  \\)}\n    \\begin{pfproof}\n      by inversion $\\sWLA$\n    \\end{pfproof}\n\n  \\step{2}{\\case{$\\svalue_1 \\in \\efun{\\svar}{\\sexpr}$}}\n    \\begin{pfproof}\n      \\absurdstep\n        \\begin{pfproof}\n          $\\snil \\sWTA \\estab{\\sbnd_0}{\\svalue_0} : \\tdyn$\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{3}{\\case{$\\svalue_1 \\in \\efun{\\tann{\\svar}{\\stype}}{\\sexpr}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          $\\obars{\\estab{\\sbnd_0}{\\svalue_0}}{\\sowner_0} \\nredAD \\obars{\\emon{\\sbnd_0}{\\svalue_0}}{\\sowner_0}$\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{4}{\\case{$\\svalue_1 \\in \\epair{\\svalue}{\\svalue}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          $\\obars{\\estab{\\sbnd_0}{\\svalue_0}}{\\sowner_0} \\nredAD \\obars{\\emon{\\sbnd_0}{\\svalue_0}}{\\sowner_0}$\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{5}{\\case{$\\svalue_1 \\eeq \\emon{\\sbnd_1}{\\obbars{\\ehopt{\\sblist_2}{\\obbars{\\svalue_2}{\\sownerlist_3}}}{\\sownerlist_4}}$}}\n    \\begin{pfproof}\n      \\step{5.0}{\\scase{$\\svalue_2 \\in (\\efun{\\svar}{\\sexpr}) \\cup (\\epair{\\svalue}{\\svalue})$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              \\(\\obars{\\estab{\\sbnd_0}{\\svalue_0}}{\\sowner_0}\n                \\nredAD\n                \\obars{\\eprehist{\\fconcat{\\sbnd_0}{\\sbnd_1}{\\sblist_2}}{\\obbars{\\svalue_2}{\\fconcat{\\sownerlist_3}{\\fconcat{\\sownerlist_4}{\\sownerlist_2}}}}}{\\sowner_0}\n              \\)\n            \\end{pfproof}\n        \\end{pfproof}\n      \\step{5.1}{\\scase{$\\svalue_2 \\in (\\efun{\\tann{\\svar}{\\stype}}{\\sexpr})$}}\n        \\begin{pfproof}\n          \\absurdstep\n            \\begin{pfproof}\n              $\\snil \\sWTA \\svalue_0 : \\stype_0$\n            \\end{pfproof}\n        \\end{pfproof}\n      \\step{5.2}{\\scase{$\\svalue_2 \\eeq (\\emon{\\sbnd_5}{\\obbars{\\svalue_3}{\\sownerlist_6}})$}}\n        \\begin{pfproof}\n          \\step{5.2.0}{\\sscase{$\\svalue_3 \\in (\\efun{\\tann{\\svar}{\\sexpr}}) \\cup \\epair{\\svalue}{\\svalue}$}}\n            \\begin{pfproof}\n              \\(\\obars{\\estab{\\sbnd_0}{\\svalue_0}}{\\sowner_0}\n                \\nredAD\n                \\obars{\\eprehist{\\fconcat{\\sbnd_0}{\\fconcat{\\sbnd_1}{\\sblist_2}}}{\\obbars{\\svalue_2}{\\fconcat{\\sownerlist_3}{\\fconcat{\\sownerlist_4}{\\sownerlist_2}}}}}{\\sowner_0}\n              \\)\n            \\end{pfproof}\n          \\step{5.2.1}{\\sscase{$\\svalue_3 \\not\\in (\\efun{\\tann{\\svar}{\\sexpr}}) \\cup \\epair{\\svalue}{\\svalue}$}}\n            \\begin{pfproof}\n              \\absurdstep\n                \\begin{pfproof}\n                  $\\snil \\sWTA \\svalue_1 : \\stype_0$\n                \\end{pfproof}\n            \\end{pfproof}\n        \\end{pfproof}\n      \\step{5.3}{\\scase{otherwise}}\n        \\begin{pfproof}\n          \\absurdstep\n            \\begin{pfproof}\n              $\\snil \\sWTA \\svalue_1 : \\stype_0$\n            \\end{pfproof}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{6}{\\case{$\\svalue_1 \\eeq \\ehopt{\\sblist_0}{\\obbars{\\sint_1}{\\sownerlist_1}}$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          $\\obars{\\estab{\\sbnd_0}{\\svalue_0}}{\\sowner_0} \\nredAD \\obars{\\sint_1}{\\sowner_0}$\n        \\end{pfproof}\n    \\end{pfproof}\n\n\\end{lamportproof*}}\n\n\\begin{lemma}\\label{A-dyn-label-preservation}\\leavevmode\n  If\\/ $\\snil \\sWTA \\edynb{\\sbnd_0}{\\svalue_0} : \\stype_0$\n  and\\/ $\\snil; \\sowner_0 \\sWLA \\edynb{\\sbnd_0}{\\svalue_0}$\n  and\\/ $\\obars{\\edynb{\\sbnd_0}{\\svalue_0}}{\\sowner_0} \\nredAS \\obars{\\sexpr_1}{\\sowner_0}$\n  then\\/ $\\snil; \\sowner_0 \\sWLA \\sexpr_1$.\n\\end{lemma}{\n  \\newcommand{\\shortproof}{By case analysis of $\\nredAS$.}\n\\begin{lamportproof*}\n  \\shortproof\n\\mainproof\n  \\shortproof\n\n  \\step{0}{\\(\n    \\sbnd_0 \\eeq \\obnd{\\sowner_0}{\\stype_0}{\\sowner_1}\n  \\)\\\\and \\(\n    \\sowner_0; \\sowner_1 \\sWL \\stype_0\n  \\)\\\\and \\(\n    \\snil; \\sowner_1 \\sWLA \\svalue_0\n  \\)}\n    \\begin{pfproof}\n      by inversion $\\sWLA$\n    \\end{pfproof}\n\n  \\step{2}{\\case{\\(\n    \\obars{\\edynb{\\sbnd_0}{\\svalue_0}}{\\sowner_0} \\nredAS \\obars{\\emon{\\sbnd_0}{\\svalue_0}}{\\sowner_0}\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          \\begin{mathpar}\n            \\inferrule*{\n              \\inferrule*{\n                \\mbox{by inversion $\\sWLA$}\n              }{\n                \\snil; \\sowner_1 \\sWLA \\svalue_0\n              }\n            }{\n              \\snil; \\sowner_0 \\sWLA \\emon{\\sbnd_0}{\\svalue_0}\n            }\n          \\end{mathpar}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{4}{\\case{\\(\n    \\obars{\\edynb{\\sbnd_0}{\\svalue_0}}{\\sowner_0}\n    \\nredAS\n    \\obars{\\sint_1}{\\sowner_0}\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n    \\end{pfproof}\n\n  \\step{5}{\\case{\\(\n    \\obars{\\edynb{\\sbnd_0}{\\svalue_0}}{\\sowner_0}\n    \\nredAS\n    \\obars{\\boundaryerror{\\sbnd_0}{\\svalue_0}}{\\sowner_0}\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n    \\end{pfproof}\n\n\\end{lamportproof*}}\n\n\\begin{lemma}[\\asym-$\\ssta$ preservation]\\label{A-sta-label-preservation}\n  If\\/ $\\snil \\sWTA \\estab{\\sbnd_0}{\\svalue_0} : \\tdyn$\n  and\\/ $\\snil; \\sowner_0 \\sWLA \\estab{\\sbnd_0}{\\svalue_0}$\n  and\\/ $\\obars{\\estab{\\sbnd_0}{\\svalue_0}}{\\sowner_0} \\nredAD \\obars{\\sexpr_1}{\\sowner_0}$\n  then\\/ $\\snil; \\sowner_0 \\sWLA \\sexpr_1$.\n\\end{lemma}{\n  \\newcommand{\\shortproof}{By case analysis of $\\nredAD$.}\n\\begin{lamportproof*}\n  \\shortproof\n\\mainproof\n  \\shortproof\n\n  \\step{0}{\\(\n    \\sbnd_0 \\eeq \\obnd{\\sowner_0}{\\stype_0}{\\sowner_1}\n  \\)\\\\and \\(\n    \\snil; \\sowner_1 \\sWLA \\svalue_0\n  \\)}\n    \\begin{pfproof}\n      by inversion $\\sWLA$\n    \\end{pfproof}\n\n  \\step{1}{\\case{\\(\n    \\obars{\\estab{\\sbnd_0}{\\svalue_0}}{\\sowner_0}\n    \\nredAD\n    \\obars{\\emon{\\sbnd_0}{\\svalue_0}}{\\sowner_0}\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          \\begin{mathpar}\n            \\inferrule*{\n              \\inferrule*{\n                \\mbox{by inversion $\\sWLA$}\n              }{\n                \\snil; \\sowner_1 \\sWLA \\svalue_0\n              }\n            }{\n              \\snil; \\sowner_0 \\sWLA \\emon{\\sbnd_0}{\\svalue_0}\n            }\n          \\end{mathpar}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{2}{\\case{\\(\n    \\obars{\\estab{\\sbnd_0}{\\obbars{\\emon{\\sbnd_1}{\\obbars{\\ehopt{\\sblist_2}{\\svalue_2}}{\\sownerlist_4}}}{\\sownerlist_5}}}{\\sowner_0}\n    \\nredAD\n    \\obars{\\eprehist{\\fconcat{\\sbnd_0}{\\fconcat{\\sbnd_1}{\\sblist_2}}}{\\obbars{\\svalue_2}{\\fconcat{\\sownerlist_4}{\\fconcat{\\sownerlist_5}{\\sowner_0}}}}}{\\sowner_0}\n  \\)}}\n    \\begin{pfproof}\n      \\step{2.0}{\\(\n        \\fbndeqowners{\\sblist_2}{\\sownerlist_4}\n      \\)}\n        \\begin{pfproof}\n          by inversion $\\sWLA$\n        \\end{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          \\begin{mathpar}\n            \\inferrule*{\n              \\inferrule*{\n                \\inferrule*{\n                  \\mbox{by inversion $\\sWLA$}\n                }{\n                  \\snil; \\flast{\\sownerlist_4} \\sWLA \\svalue_2\n                }\n              }{\n                \\snil; \\sowner_0 \\sWLA \\eprehist{\\fconcat{\\sbnd_0}{\\fconcat{\\sbnd_1}{\\sblist_2}}}{\\obbars{\\svalue_2}{\\fconcat{\\sownerlist_4}{\\fconcat{\\sownerlist_5}{\\sowner_0}}}}\n              }\n            }{\n              \\snil; \\sowner_0 \\sWLA \\obars{\\eprehist{\\fconcat{\\sbnd_0}{\\fconcat{\\sbnd_1}{\\sblist_2}}}{\\obbars{\\svalue_2}{\\fconcat{\\sownerlist_4}{\\fconcat{\\sownerlist_5}{\\sowner_0}}}}}{\\sowner_0}\n            }\n          \\end{mathpar}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{4}{\\case{\\(\n    \\obars{\\estab{\\sbnd_0}{\\svalue_0}}{\\sowner_0} \\nredAD \\obars{\\sint_1}{\\sowner_0}\n  \\)}}\n    \\begin{pfproof}\n      qedstep\n    \\end{pfproof}\n\n\\end{lamportproof*}}\n\n\\begin{lemma}\\label{A-addtrace-label-preservation}\n  If\\/ $\\snil \\sWTA \\eprehist{\\sblist_0}{\\svalue_0} : \\tdyn$\n  and\\/ $\\snil; \\sowner_0 \\sWLA \\eprehist{\\sblist_0}{\\svalue_0}$\n  then\\/ $\\snil; \\sowner_0 \\sWLA \\faddtrace{\\sblist_0}{\\svalue_0}$.\n\\end{lemma}{\n  \\newcommand{\\shortpf}{By case analysis of $\\saddtrace$.}\n\\begin{lamportproof*}\n  \\shortpf\n\\mainproof\n  \\shortpf\n\n  \\step{0}{\\case{\\(\\faddtrace{\\snil}{\\svalue_0} \\feq \\svalue_0\\)}}\n    \\begin{pfproof}\n      \\qedstep\n    \\end{pfproof}\n\n  \\step{1}{\\case{\\(\n    \\faddtrace{\\sblist_0}{\\obbars{\\ehist{\\sblist_1}{\\svalue_1}}{\\sownerlist_2}}\n    \\feq\n    \\ehist{\\fconcat{\\sblist_0}{\\sblist_1}}{\\obbars{\\svalue_1}{\\sownerlist_2}}\n  \\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          \\step{1.0}{$\\fbndeqowners{\\sblist_0}{\\sownerlist_2}$}\n            \\begin{pfproof}\n              by inversion $\\sWLA$\n            \\end{pfproof}\n          \\qedstep\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{2}{\\case{\\(\n    \\faddtrace{\\sblist_0}{\\svalue_1}\n    \\feq\n    \\ehist{\\sblist_0}{\\svalue_1}\n  \\)\\\\and \\(\n    \\svalue_0 \\not\\in \\ehist{\\sblist}{\\svalue}\n  \\)}}\n    \\begin{pfproof}\n      \\step{2.0}{\\(\n        \\svalue_1 \\eeq \\obbars{\\svalue_2}{\\sownerlist_2}\n      \\)\\\\and \\(\n        \\fbndeqowners{\\sblist_0}{\\sownerlist_2}\n      \\)}\n        \\begin{pfproof}\n          by inversion $\\snil; \\sowner_0 \\sWLA \\esuffix{\\sblist_0}{\\svalue_1}$\n        \\end{pfproof}\n      \\qedstep\n    \\end{pfproof}\n\n\\end{lamportproof*}}\n\n\\begin{lemma}\\label{A-label-substitution}\\leavevmode\n  If\\/ $\\fcons{\\tann{\\svar_0}{\\stype_0}}{\\stypeenv_0} \\sWTA \\sexpr_1 : \\toptional$\n  and\\/ $\\fcons{\\tann{\\svar_0}{\\sowner_0}}\\sownerenv_0; \\sowner_1 \\sWLA \\sexpr_1$\n  and\\/ $\\snil \\sWTA \\svalue_0 : \\toptional'$\n  and\\/ $\\snil; \\sowner_0 \\sWLA \\svalue_0$\n  then\\/ $\\stypeenv_0 \\sWTA \\esubst{\\sexpr_1}{\\svar_0}{\\svalue_0} : \\toptional$\n  and\\/ $\\sownerenv_0 \\sWLA \\esubst{\\sexpr_1}{\\svar_0}{\\svalue_0}$.\n\\end{lemma}{\n  \\newcommand{\\shortproof}{By induction on the structure of $\\sexpr_0$.}\n\\begin{lamportproof*}\n  \\shortproof\n\\mainproof\n  \\shortproof\n\n  \\step{0}{$\\sexpr_0 \\eeq \\svar_2$}\n    \\begin{pfproof}\n      \\step{0.0}{\\scase{$\\svar_0 \\eeq \\svar_2$}}\n        \\begin{pfproof}\n          \\qedstep\n        \\end{pfproof}\n      \\step{0.1}{\\scase{$\\svar_0 \\neq \\svar_2$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              $\\esubst{\\sexpr_1}{\\svar_0}{\\svalue_0} \\eeq \\sexpr_1$\n            \\end{pfproof}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{1}{\\case{$\\sexpr_0 \\in \\sint$}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          $\\esubst{\\sexpr_1}{\\svar_0}{\\svalue_0} \\eeq \\sexpr_1$\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{2}{\\case{\\(\n    \\sexpr_0 \\eeq \\efun{\\svar_2}{\\sexpr_2}\n  \\)\\\\or\\(\n    \\sexpr_0 \\eeq \\efun{\\tann{\\svar_2}{\\stype_2}}{\\sexpr_2}\n  \\)}}\n    \\begin{pfproof}\n      \\step{2.0}{\\scase{$\\svar_0 \\eeq \\svar_2$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              $\\esubst{\\sexpr_1}{\\svar_0}{\\svalue_0} \\eeq \\sexpr_1$\n            \\end{pfproof}\n        \\end{pfproof}\n      \\step{2.1}{\\scase{$\\svar_0 \\neq \\svar_2$}}\n        \\begin{pfproof}\n          \\qedstep\n            \\begin{pfproof}\n              by \\pfih\n            \\end{pfproof}\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{3}{\\case{\\(\\sexpr_0 \\eeq \\epair{\\sexpr_1}{\\sexpr_2}\\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{4}{\\case{\\(\\sexpr_0 \\eeq \\eapp{\\toptional}{\\sexpr_1}{\\sexpr_2}\\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{5}{\\case{\\(\\sexpr_0 \\eeq \\eunopt{\\stoptional}{\\sexpr_1}\\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{6}{\\case{\\(\\sexpr_0 \\eeq \\ebinopt{\\stoptional}{\\sexpr_1}{\\sexpr_2}\\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{7}{\\case{\\(\\sexpr_0 \\eeq \\edynb{\\sbnd_1}{\\sexpr_1}\\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{8}{\\case{\\(\\sexpr_0 \\eeq \\estab{\\sbnd_1}{\\sexpr_1}\\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{9}{\\case{\\(\\sexpr_0 \\eeq \\obars{\\sexpr_1}{\\sowner_1}\\)}}\n    \\begin{pfproof}\n      \\step{9.0}{$\\sowner_0 \\eeq \\sowner_1$}\n        \\begin{pfproof}\n          by inversion $\\sWLA$\n        \\end{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{10}{\\case{\\(\\sexpr_0 \\eeq \\eprehist{\\sblist_1}{\\obbars{\\sexpr_1}{\\sownerlist_1}}\\)}}\n    \\begin{pfproof}\n      \\step{10.0}{$\\snil; \\flast{\\sownerlist_1} \\sWLA \\sexpr_1$}\n        \\begin{pfproof}\n          by inversion $\\sWLA$\n        \\end{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n  \\step{11}{\\case{\\(\\sexpr_0 \\eeq \\ehist{\\sblist_1}{\\obbars{\\sexpr_1}{\\sownerlist_1}}\\)}}\n    \\begin{pfproof}\n      \\qedstep\n        \\begin{pfproof}\n          by \\pfih\n        \\end{pfproof}\n    \\end{pfproof}\n\n\\end{lamportproof*}}\n\n\\begin{lemma}[boundary preservation]\\label{A-source-boundary}\\leavevmode\n  If\\/ $\\fwellformedO{\\sexpr_0}{\\stoptional}$\n  and\\/ $\\sexpr_0 \\rredA \\ctx_0[{\\edynb{\\sbnd_1}{\\svalue_1}}]$\n  then either\\/ $\\fhasbnd{\\sexpr_0}{\\sbnd_1}$ or $\\fhasbnd{\\sexpr_0}{\\fflip{\\sbnd_1}}$.\n\\end{lemma}{\n  \\newcommand{\\shortpf}{By case analysis of $\\nredAS$ and $\\nredAD$, evaluation does not create new labels and only creates a new boundary by flipping an existing boundary.}\n\\begin{lamportproof*}\n  \\shortpf\n\\mainproof\n  \\shortpf\n\n\\end{lamportproof*}}\n\n\\begin{lemma}\\label{A-mon-compat}\\leavevmode\n      If\\/ $\\fwellformedO{\\sexpr_0}{\\stoptional}$\n      and\\/ $\\sexpr_0 \\rredA \\ctx[\\emon{\\obnd{\\sowner_0}{\\stype_0}{\\sowner_2}}{\\svalue_0}]$\n      and\\/ $\\fshallow{\\tagof{\\tpair{\\stype_1}{\\stype_2}}}{\\svalue_0}$\n      then\\/ $\\stype_0 \\in \\obars{\\tpair{\\stype}{\\stype}}{\\sowner}$\n\\end{lemma}{\n\\begin{lamportproof}\n  Surface expressions do not contain monitors, and $\\nredAD$ and $\\nredAS$ only\n  create monitors with compatible types and values.\n\\end{lamportproof}}\n\n", "meta": {"hexsha": "62e70600cdce14f77dfd0c5f70d103764570e9fb", "size": 116835, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tr-A-proof.tex", "max_stars_repo_name": "nuprl/gfd-oopsla-2019", "max_stars_repo_head_hexsha": "9b77f6e1b1660bdbd78aa1d76ce9c019261054df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-10-24T12:19:27.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-24T12:19:27.000Z", "max_issues_repo_path": "tr-A-proof.tex", "max_issues_repo_name": "nuprl/gfd-oopsla-2019", "max_issues_repo_head_hexsha": "9b77f6e1b1660bdbd78aa1d76ce9c019261054df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tr-A-proof.tex", "max_forks_repo_name": "nuprl/gfd-oopsla-2019", "max_forks_repo_head_hexsha": "9b77f6e1b1660bdbd78aa1d76ce9c019261054df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4196224256, "max_line_length": 312, "alphanum_fraction": 0.5539949501, "num_tokens": 46349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3335396073205423}}
{"text": "%!TEX root = kPtx_paper.tex\n\\section*{Results}\n\n\nFigure \\ref{fig:ErrorMap} shows simulated excitation patterns and error maps for the reference spatial and k-space domain designs. \nBoth designs were performed with 16 parallel threads and the 64$\\times$64$\\times$48 grid size (3 mm isotropic resolution), \nand the excitation patterns were evaluated against the target pattern on a 128$\\times$128$\\times$96 grid size (1.5 mm iso-resolution). \nThe k-space domain design used patch and inclusion widths of 4.\nThe calculated root-mean-squared errors (RMSEs) were 2.42\\% (spatial domain) and 2.68\\% (k-space domain), \nrespectively. \nFor both design methods, most of the errors appeared at the edges of the transition band, \nand errors elsewhere were lower than 5\\% of the target flip angle. \nThis indicates uniform inner volume excitation while maintaining the outer volume intact. \nThe parallelized k-space domain design required 2.9 seconds computation versus 31.8 seconds for the spatial domain method, a 91\\% decrease.\n\n\n\\subsection*{k-Space Algorithm Parameters}\nFigure \\ref{fig:ComputationTime}a plots mean computation time versus number of parallel threads,\nholding the patch and inclusion widths fixed at 4 cycles/FOV. \nThe computation time decreased rapidly with increasing thread number up to 12 threads, \nand then plateaued, likely due to the overhead involved in initiating threads after that point.\nBased on this result, the number of threads was held fixed at 16 for subsequent designs when off-resonance was not compensated.\n\n\\par Figure \\ref{fig:ComputationTime}b plots mean computation time and RMSE with different patch widths. \nThe computation time decreased up to a patch width of 4 cycles/FOV (corresponding to $4^3 = 64$ simultaneously solved columns of $\\bm{W}$) \nand then increased sharply for larger patch widths. \nRMSE decreased slowly as the patch width increased since the number of excitation trajectory points included in the calculation of weights for each \ntarget point increases on average (and especially for target locations in the middle of each patch) as the patch width increases, \neven when the inclusion width stays fixed.\nBased on this result, a patch width of 4 cycles/FOV was used for subsequent designs.\n\n\\par Figure \\ref{fig:ComputationTime}c plots mean computation time and RMSE with different inclusion widths. \nThe solid lines and dashed lines were obtained with patch widths of 4 and 8 cycles/FOV, respectively. \nComputation time increased and error decreased with increasing inclusion width,\nsince more excitation trajectory points were included in each target location's calculation for increasing inclusion width,\ncorresponding to an increased $\\bm{S}^H\\bm{S}$ matrix size. \nThe RMSE was only slightly lower for a patch width of 8 versus 4 cycles/FOV, \nbut the computation time was much higher for 8 cycles/FOV, across all inclusion widths. \nThe knees in the curves occurred approximately at an inclusion width of 4 cycles/FOV,\nso this value was used in subsequent designs. \n\n\\par Table \\ref{fig:wsize} lists the size of the final matrix $\\bm{W}$ in gigabytes,\nversus inclusion width.\nAs inclusion width increases, more excitation trajectory points are used in the solution of the weights for each target location,\nuntil the entire trajectory is used for each location (Inclusion width = $\\infty$ in the table),\ncorresponding to a full solution. \nWith the inclusion width of 4 cycles/FOV used here, \nthe matrix size was 98\\% smaller than that of a full solution.  \n\n\n\n\n\n\\subsection*{L-Curves}\nFigure \\ref{fig:LCurves} plots flip angle RMSE versus RF RMS amplitude for the spatial domain method\nand different configurations of the k-space domain method.\nThe spatial domain method achieves the best overall tradeoff between error and RMS amplitude (dashed black curve),\nwhich is matched by the k-space domain method when all target locations are solved simultaneously with\nall excitation trajectory points included and exact $\\bm{S}^H\\bm{S}$ matrix construction (orange curve). \nWhen the inclusion and patch widths are limited to 4 cycles/FOV but the $\\bm{S}^H\\bm{S}$ \nmatrices are still constructed exactly, there is an increase in error and RMS amplitude (solid blue curve). \nHowever, a larger penalty is incurred by interpolating the entries of the $\\bm{S}^H\\bm{S}$ matrices (dashed orange curve)\nthan by limiting the inclusion and patch widths.\nCombining interpolation of the $\\bm{S}^H\\bm{S}$ matrix entries and patch and inclusion widths of 4 cycles/FOV yield \nthe dashed blue curve, which has a higher error and RF amplitude than when interpolation or small patch and inclusion widths are\nused alone.\nOverall, these results and the results in Figure \\ref{fig:ComputationTime} and Table \\ref{fig:wsize}\nshow that the k-space domain method allows a tradeoff between computation time and memory usage versus\nexcitation error and RMS RF amplitude.\nThe dots on the spatial domain and k-space domain curves indicate the knees of of the curves corresponding to\nthe $\\lambda$ values used for the designs in Figures \\ref{fig:ErrorMap}, \\ref{fig:ComputationTime}, \\ref{fig:kspace_PTX_Acceleration}, and \\ref{fig:kspace_PTX_B0}.\nNote that the RMSE's in Figure \\ref{fig:LCurves} are slightly lower for the spatial domain designs\nand slightly higher for the k-space domain designs compared to other figures,\nbecause the flip angle errors in Figure \\ref{fig:LCurves} were calculated using \nspatial domain non-uniform fast Fourier transforms instead of Bloch equation simulations, \nto provide a more direct measure of the design error. \n\n\n\n\\subsection*{Gibbs Ringing}\nFigure \\ref{fig:GibbsRing}a shows slices of the excitation error pattern produced by pulses designed by the spatial domain method\non a 32$\\times$32$\\times$24 grid, which were Bloch-simulated on the original 128$\\times$128$\\times$96 grid. \nThere is significant Gibbs ringing in the pattern (indicated by the red arrows),\nand the pulses incur a higher RMSE (4.64\\%) than pulses designed using either the spatial domain method with a finer 64$\\times$64$\\times$48 grid\n(2.66\\%; Figure \\ref{fig:GibbsRing}b) or the k-space domain method with a 32$\\times$32$\\times$24 grid (3.00\\%; Figure \\ref{fig:GibbsRing}c). \nGibbs ringing is not apparent in either the 64$\\times$64$\\times$48 spatial domain error pattern or the 32$\\times$32$\\times$24 k-space domain error pattern. \nThe RMS RF amplitudes of the low resolution designs were both 0.005. \nNote that the error of the 64$\\times$64$\\times$48 spatial domain design is slightly higher than designs presented in other figures\ndue to the lower-resolution excitation trajectory. \nFrom a spatial domain point of view, \nthe Gibbs ringing in the low-resolution spatial domain design was caused by the design's inability to observe and limit the ringing in the low-resolution design grid. \nFrom a k-space domain point of view, the Gibbs ringing in \nFigure \\ref{fig:GibbsRing}a was due to implicit circulant end conditions at the edges of excitation k-space in the low-resolution\nspatial domain design,\nwhich led RF samples at one edge of k-space to wrap-around and affect target locations at the opposite edge of k-space. \nThis effect is mitigated using a high-resolution spatial domain design grid, as illustrated in Figure \\ref{fig:GibbsRing}b. \nHowever, even for a low-resolution k-space domain design there is no wrap-around effect in excitation k-space \nbecause the trajectory points that are incorporated in the weights solution for each patch of target locations are explicitly specified to be those in the immediate vicinity of \nthe target points, without circulant end conditions. \n%Particularly, for the instance problems whose patches are at the edges of the k-space FOV, the excitation trajectory points at the other ends of the k-space FOV will not be incorporated into the design.    \n\n%Due to implicit circulant end conditions in k-space for the spatial domain design, t\n\n\n\n\\subsection*{Excitation k-Space Undersampling}\nFigure \\ref{fig:kspace_PTX_Acceleration} compares excitation error patterns produced by spatial domain-designed pulses (top row)\nand k-space domain-designed pulses (middle row),\nfor different trajectory reduction factors which resulted in the SPINS trajectories plotted in the third row. \nFor each design the k-space domain-designed pulses had higher error, \nbut error increased smoothly with increasing reduction factor, as it did for the spatial domain designs. \n\n\n\n\n\\subsection*{Off-Resonance}\nFigure \\ref{fig:kspace_PTX_B0}a shows the off-resonance maps containing a Gaussian distortion which was centered above the frontal sinus,\nand scaled to peak amplitudes of 0, 200, and 400 Hz for the pulse designs and Bloch simulations. \nFigure \\ref{fig:kspace_PTX_B0}b shows excitation error patterns and RMSEs for spatial domain designs with off-resonance compensation,\nand k-space domain designs without and with off-resonance compensation. \nWithout off-resonance compensation, \nthe k-space domain-designed pulses produced large ($>$ 10\\% of $M_0$) excitation errors both inside and outside the target ellipse. \nWhen the off-resonance map was incorporated in the spatial domain and k-space domain designs, \nthe distortion was nearly fully corrected when it had a peak amplitude of 200 Hz. \nWhen the map was scaled to a peak of 400 Hz, some large errors remained, with the k-space domain-designed pulses achieving slightly lower RMSE. \n%It was also able to provide excitation pattern comparable to spatial domain design with 400 Hz maximum off-resonance. The k-space domain design has a weaker performance with higher off-resonance due to the fact that the time segmentation approximation in Ref \\cite{fessler2005toeplitz} was meant to approximate forward models from RF to excitation patterns and does not serve as an accurate approximation to the backward model as we need in the k-space domain design.", "meta": {"hexsha": "b5eb2ee60fda8c9632b433f44ef597000279327b", "size": 9873, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "manuscript/Manuscript_r0/Result.tex", "max_stars_repo_name": "wgrissom/kpTx", "max_stars_repo_head_hexsha": "b0f89ad298c8814570fa6df758d97ea3832b28d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-11-17T21:17:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T20:54:24.000Z", "max_issues_repo_path": "manuscript/Manuscript_r0/Result.tex", "max_issues_repo_name": "wgrissom/kpTx", "max_issues_repo_head_hexsha": "b0f89ad298c8814570fa6df758d97ea3832b28d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-01T10:38:17.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-03T11:18:22.000Z", "max_forks_repo_path": "manuscript/Manuscript_r0/Result.tex", "max_forks_repo_name": "wgrissom/kpTx", "max_forks_repo_head_hexsha": "b0f89ad298c8814570fa6df758d97ea3832b28d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 78.3571428571, "max_line_length": 468, "alphanum_fraction": 0.7984401904, "num_tokens": 2289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804478040617, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.3335122786560005}}
{"text": "\\chapter{Conclusions}\n\\label{ch:end}\n\nWe studied the effect of electrical noise on the identification and\nreconstruction of output pulses in DarkSide20k silicon photomultipliers (SiPM)\nTiles in \\autoref{ch:snr}, \\ref{ch:timeres} and~\\ref{ch:rate}, and measured the\ncorrelated noise of a Tile in \\autoref{ch:anal}. In the following paragraphs we\nsummarize and comment the results from all chapters.\n\nThe main takeaway from \\autoref{ch:snr} is in \\autoref{fig:changebs}. The\nmaximum signal to noise ratio (SNR) that can be reached with filtering on that\ndata is~19, shown on the left panel with the cross correlation filter and\nprecise baseline calculation. However the constraints of the available\nresources on the digitizers may turn out to impose a moving average filter with\nimprecise baseline, lowering the SNR to~13, as shown in the central panel. So\nthe SNR at the digitizer stage can be as low as \\SI{65}\\% of the optimal one.\n\nIn the DarkSide collaboration it was proposed to use an ``autoregressive moving\naverage'' (ARMA) filter to implement a long cross correlation filter in the\ndigitizers. The ARMA combines linearly two filters: 1)~a cross correlation with\na template only for the peak of the pulse, and 2)~an autoregressive filter, run\non the \\emph{temporally reversed} waveform. This reproduces a cross correlation\nwith the peak template plus an exponentially decaying tail. Although the\nasymptotical complexity of the algorithm is excellent on paper, the actual\namount of logic resources necessary for the implementation on FPGA may exceed\nthe available ones, mainly due to the necessity of keeping a buffer for the\ntemporal reversal, and to glue appropriately the reversed temporal slices with\ndynamical boundary conditions or partially overlapping slices. From\n\\autoref{fig:changebs} it is clear that a simple moving average can achieve\nperformances comparable to a cross correlation filter, thus it may not be\nnecessary to devise a way to implement the cross correlation filter on the\ndigitizers.\n\nIn \\autoref{ch:timeres} there are various things to learn:\n\n\\begin{itemize}\n    \n    \\item The temporal resolution diverges below a certain SNR, giving a\n    somewhat rigid bound on the working point, and the behavior at low SNR\n    heavily depends on the noise spectrum, \\autoref{fig:rescomp}. The\n    DarkSide20k simulation currently implements only white noise.\n    \n    \\item For what concerns temporal resolution, it is sufficient to extract\n    \\SI{1}{\\micro s} of waveform per pulse from the digitizers,\n    \\autoref{fig:windowtempres}.\n    \n    \\item Downsampling from \\SI{125}{MSa/s} to \\SI{62.5}{MSa/s} does not\n    deteriorate the temporal resolution, \\autoref{fig:tempresdowns} and\n    \\autoref{tab:filtsnrdowns}. If a compromise with the data rate is\n    necessary, \\SI{31.2}{MSa/s} might still be good enough.\n    \n    \\item Upsampling is not necessary, \\autoref{fig:rescomp}.\n    \n\\end{itemize}\n\nThe temporal resolution required by the specifications of DarkSide20k is\n\\SI{10}{ns} \\cite[30]{aalseth2018}. A worse resolution would decrease the\nselective power of pulse shape discrimination (PSD). With the noise spectrum of\nthe Proto0 prototype, we find that the temporal resolution reaches \\SI{10}{ns}\nat pre-filter SNR 2.6, to be compared with the SNR observed in the Proto0 data\nof at least 3.3, see \\autoref{fig:rescomp}.\n\nChapter~\\ref{ch:rate} has its own summary in \\autoref{sec:rateconcl}. In\ngeneral the formula for the fake rate is sufficiently precise, but there is an\nexception with higher rate than expected that should be investigated better,\nsee \\autoref{fig:fakerate}. With the tested filter, which matches the one\nmentioned above for the $\\mathrm{SNR} = 13$ figure, the fake rate is\n\\SI{10}{cps} with the threshold set at 5 filtered noise standard deviations\n(including baseline subtraction), to be compared to the maximum total primary\nnoise rate required, \\SI{250}{cps/PDM} \\cite[30]{aalseth2018}.\n\nThe chapter on correlated noise contains more material, so it includes a rather\nlong discussion of the results in \\autoref{sec:analconcl}. To summarize\nfurther:\n\n\\begin{itemize}\n    \n    \\item Compared to the Fondazione Bruno Kessler (FBK) Tiles, the analyzed\n    LFoundry Tile has similar direct cross talk (DiCT) and much less\n    afterpulsing (AP).\n    \n    \\item The afterpulse models should be studied and validated better.\n    \n    \\item It should be determined whether Tile~21 enters a nonlinear regime\n    between \\SI{7.5}{VoV} and \\SI{9.5}{VoV}, or if the \\SI{9.5}{VoV} data is\n    mislabeled.\n    \n    \\item Tile~21 should be analyzed with charge spectrum methods and the\n    results compared to ours.\n    \n    \\item The SiPM simulation must be consistent with the model used in the\n    analysis of real data.\n    \n\\end{itemize}\n\nWe put upper bounds on the dark count rate (DCR), respectively \\SI{50}{cps},\n\\SI{170}{cps}, and~\\SI{120}{cps} at overvoltages \\SI{5.5}V, \\SI{7.5}V,\nand~\\SI{9.5}V, to be compared with the required upper limit \\SI{250}{cps}. We\ngive upper bounds for AP probabilities of \\SI{2.5}\\%, \\SI{3.5}\\% and\n\\SI{6.5}\\%, and estimate DiCT probabilities \\SI{20}\\%, \\SI{30}\\% and~\\SI{50}\\%.\nThese are the probabilities of said noises being generated by a \\SI1{PE} pulse.\nThe DarkSide20k specifications require the sum of correlated noise\nprobabilities to be less than \\SI{60}\\% \\cite[30]{aalseth2018} in order to\navoid performance degradation, mainly dynamic range reduction on ionization\nsignals, where there is a lot of pile-up. Furthermore, some safety margin\nshould be considered for the aging of the SiPMs, which is not well studied, in\ncase the correlated noise probability turned out to increase with time. Recall\nthat, for a correlated noise probability $p$, the ratio of total pulses to\nprimary pulses is $1/(1-p)$, which diverges quite fast as $p$ goes to~1.\n\\cite[8]{gola2019} mention that in practice the maximum manageable probability\nis \\SI{50}\\%.\n\n\\marginpar{Explain the stuff from Simone in the TF2 report.}\n", "meta": {"hexsha": "3d0a699f84694ec790f40ad175600e0d20f62ee8", "size": 5996, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "end.tex", "max_stars_repo_name": "Gattocrucco/thesis", "max_stars_repo_head_hexsha": "0b8672b7dc6a4ec54c5c76ecfbb83edcf34729f7", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-15T07:16:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T07:16:46.000Z", "max_issues_repo_path": "end.tex", "max_issues_repo_name": "Gattocrucco/thesis", "max_issues_repo_head_hexsha": "0b8672b7dc6a4ec54c5c76ecfbb83edcf34729f7", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "end.tex", "max_forks_repo_name": "Gattocrucco/thesis", "max_forks_repo_head_hexsha": "0b8672b7dc6a4ec54c5c76ecfbb83edcf34729f7", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.5964912281, "max_line_length": 79, "alphanum_fraction": 0.7645096731, "num_tokens": 1575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.33351227107778236}}
{"text": "%-----------------------------------------------------------------------------\n%\n%               Template for sigplanconf LaTeX Class\n%\n% Name:         sigplanconf-template.tex\n%\n% Purpose:      A template for sigplanconf.cls, which is a LaTeX 2e class\n%               file for SIGPLAN conference proceedings.\n%\n% Guide:        Refer to \"Author's Guide to the ACM SIGPLAN Class,\"\n%               sigplanconf-guide.pdf\n%\n% Author:       Paul C. Anagnostopoulos\n%               Windfall Software\n%               978 371-2316\n%               paul@windfall.com\n%\n% Created:      15 February 2005\n%\n%-----------------------------------------------------------------------------\n\n\\documentclass[nocopyrightspace,blockstyle,numbers]{sigplanconf}\n\n% The following \\documentclass options may be useful:\n\n% preprint      Remove this option only once the paper is in final form.\n% 10pt          To set in 10-point type instead of 9-point.\n% 11pt          To set in 11-point type instead of 9-point.\n% numbers       To obtain numeric citation style instead of author/year.\n\n\\usepackage{amsmath}\n\\usepackage[utf8]{inputenc}\n\n\\newcommand{\\cL}{{\\cal L}}\n\n\\begin{document}\n\n\\special{papersize=8.5in,11in}\n\\setlength{\\pdfpageheight}{\\paperheight}\n\\setlength{\\pdfpagewidth}{\\paperwidth}\n\n\\conferenceinfo{CONF 'yy}{Month d--d, 20yy, City, ST, Country}\n\\copyrightyear{20yy}\n\\copyrightdata{978-1-nnnn-nnnn-n/yy/mm}\n\\copyrightdoi{nnnnnnn.nnnnnnn}\n\n% Uncomment the publication rights you want to use.\n%\\publicationrights{transferred}\n%\\publicationrights{licensed}     % this is the default\n%\\publicationrights{author-pays}\n\n%\\titlebanner{banner above paper title}        % These are ignored unless\n%\\preprintfooter{short description of paper}   % 'preprint' option specified.\n\n\\title{Coq's Prolog and application to defining semi-automatic tactics}\n%\\subtitle{Subtitle Text, if any}\n\n\\authorinfo{Théo Zimmermann \\and Hugo Herbelin}\n           {IRIF, Université Paris Diderot, Université Sorbonne Paris-Cité\\\\ $\\Pi R ^2$, INRIA}\n           {theo.zimmermann@univ-paris-diderot.fr / hugo.herbelin@inria.fr}\n%\\authorinfo{Name1}\n%           {Affiliation1}\n%           {Email1}\n%\\authorinfo{Name2\\and Name3}\n%           {Affiliation2/3}\n%           {Email2/3}\n\n\\maketitle\n\n\\begin{abstract}\n  We report on a work-in-progress to re-implement Coq's \\texttt{apply}\n  tactic in order to embed some form of simple automation. We design\n  it in a declarative way, relying on \\texttt{typeclasses eauto}, a tactic\n  which gives access to the proof-search mechanism behind type classes.\n  We qualify this mechanism of ``Coq's Prolog'' and describe it in a\n  generic way and explain how it can be used to support the\n  construction of automatic and semi-automatic tactics.\n\\end{abstract}\n\n%\\category{CR-number}{subcategory}{third-level}\n\n% general terms are not compulsory anymore,\n% you may leave them out\n%\\terms\n%term1, term2\n\n\\keywords\napply, automation, Coq, proof assistant, reflection,\ntype theory, views.\n\n\\section{Introduction}\n\nSince version 8.2 \\cite{coq86manual}, Coq has included a type class\nmechanism which can intervene during type-inference. The resolution\nphase of this mechanism is also accessible via the user-side tactic\n\\texttt{typeclasses eauto}. In fact \\texttt{typeclasses eauto}\nimplements a general Prolog-like proof-search mechanism that can be\ninstrumented to do much more. While by default, it uses the specific\n\\texttt{typeclass\\_instances} hint database, one can use it with\nalternative hint databases. In this case, despite the name of the\ntactic, it has nothing to do with the type class mechanism anymore\n(apart from the underlying implementation). It can be viewed as a\nre-implementation of the former \\texttt{eauto} tactic, dating back\nfrom Coq version 5.10.\n\nMany partially automated tactics have already been built upon Coq's type\nclass mechanism. One example is the re-implementation of the \\texttt{rewrite}\ntactic \\cite{sozeau2010new}, which relies on the mechanism in\na second phase of constraint resolution. Another is our \\texttt{transfer}\nlibrary \\cite{zimmermann}. We argue that both of these applications (and\nmany others) abuse the type class mechanism, by polluting the\n\\texttt{typeclass\\_\\\\instances} hint database, when they should instead\ndefine their own disjoint hint databases and rely on the underlying\nProlog-like proof-search mechanism that is made accessible via the\n\\texttt{typeclasses eauto} tactic.\n\nWe demonstrate the usefulness of this ``Coq's Prolog'' with a small\nre-implementation of the \\texttt{apply} tactic. This tactic is parame\\-trized\nby a set of ``views'' à la SSReflect \\cite{gonthier} which it is\nable to apply automatically. It also demonstrates a new way of instrumenting\n\\texttt{typeclasses eauto} to progress on a goal instead of solving it\n(``forward mode'', proposed in particular by Michael Soegtrop\non the Coq-Club mailing list).\n\n\\section{Presentation of Coq's Prolog}\n\nThe \\texttt{typeclasses eauto} tactic is documented in the chapter on\ntype classes of Coq's user manual \\cite[Chapter~20]{coq86manual}.\nLike \\texttt{eauto}, it is possible to specify on which hint database it\nshould operate using the \\texttt{with myhintdb} clause.\nBy default, the proof-search depth is unbounded and the traversing\nstrategy is depth-first. It is also possible to limit the proof-search\ndepth, and an alternative iterative-deepening traversing strategy exists.\n\nMost hints are lemmas which can be read as Prolog Horn clauses.\nFor instance:\n\n\\begin{verbatim}\nLemma or_introl : forall A B, A -> A \\/ B.\n\\end{verbatim}\ncan be read as the clause\\footnote{We introduce the Prolog predicate\n  \\texttt{prove} to denote the idea that the hints are used when looking\n  for a proof of a statement. When using \\text{typeclasses eauto} to\n  solve type class goals, there is always a head-constant (the type class)\n  which can serve the same role as \\texttt{prove} but when using it on\n  non-type-class goals, it is not necessarily the case.}:\n\n\\begin{verbatim}\nprove(or(A,B)) :- prove(A).\n\\end{verbatim}\nSuch hints can be introduced with the \\texttt{Hint Resolve} command:\n\n\\begin{verbatim}\nHint Resolve or_introl : myhintdb.\n\\end{verbatim}\n\nSome more complex hints can be introduced thanks to the\n\\texttt{Hint Extern} command. One very special application of\nsuch external hints is to put some sub-goals ``on the shelf'':\n\n\\begin{verbatim}\nHint Extern 0 (solveLater _) =>\n  unfold solveLater; shelve : myhintdb.\n\\end{verbatim}\n\nThe shelf is a special place in the Coq proof engine which is\nnormally reserved to sub-goals that will be solved by solving other\nsub-goals that depend on them. It can be instrumented to temporarily\nstore away some sub-goals that we want to keep for later (at which\ntime they will be ``unshelved'').\nThe ``unshelve'' tactical can be used to put back in the list of\nsub-goals to solve those which had been shelved by the tactic it is\napplied on.\nThus, a combination of the previous external hint plus a call to\n\\texttt{unshelve typeclasses eauto with myhintdb} is a way to use\nthis Prolog-like proof-search mechanism in forward mode, instead of\nthe normal solving mode.\n\nFinally, a control operator on the search space is available. It is\nnot comparable to Prolog's cut operator in that it allows to specify\nregular expressions of search-paths which should be cut but does\nnot restrict backtracking. It is still\nlimited in that regular expressions can only talk about hints\ndeclared with \\texttt{Hint Resolve} and not \\texttt{Hint Extern}.\nAdditionally, there is no negative expressions and even if regular\nexpressions are known to be closed under complement, the construction\nrequires to know all the alphabet, which is not the case here since\nnew hints can be added dynamically. We can expect to see improvements\nin control operators for \\texttt{typeclasses eauto} in the next versions\nof Coq. Here is an example\\footnote{Be careful when using it that the\nprecedence levels are not what one would expect. They should get fixed\nin Coq 8.7 but, in the meantime, the best way of writing\nforward-compatible code is to parenthesize everything.}\nof using this control operator to forbid any proof using \\texttt{or\\_introl} twice:\n\n\\begin{verbatim}\nHint Cut [(_*) or_introl (_*) or_introl] : myhintdb.\n\\end{verbatim}\n\n\\section{An \\texttt{apply} tactic with views}\n\nOur work is part of a larger effort to make the life of mathematicians\nusing Coq easier. The specific issue we address here is to design an\nextension of the \\texttt{apply} tactic which embeds some bits of\ntrivial reasoning, such as reasoning modulo symmetry of equations\n(identifying \\texttt{u = t} and \\texttt{t = u}).\nThere is already a little bit of hard-coded trivial reasoning in the\ncurrent implementation (automatic decomposition of single-constructor\ninductive types): for instance it supports applying a theorem\nof the form \\verb|A -> B /\\ C| to a goal of the form \\texttt{B}.\n\nSSReflect defines views which are basically small theorems of\nthe form \\texttt{A -> B} where \\texttt{A} is a different way of\nviewing \\texttt{B}. Our re-implementation of \\texttt{apply} tries to\nsolve the problem we were describing by allowing the user to\nparametrize it with such ``views''. Without any view, it is less\npowerful than the current implementation (because of the absence of\ndecomposition of single-constructor inductive types). With many\nviews, it can be much more powerful. The various levels of\nparametrization could reveal especially useful for teaching (from a\nlevel where everything must be done by hand, to a level where most\ndetails are handled automatically).\n\nGiven the inspiration source we described in the previous paragraph,\nan obvious application of our work will be to support automatic\ninsertion of views in the context of small scale reflection. In\nparticular, it will be possible to simply register the reflection\nlemma:\n\n\\begin{verbatim}\nLemma andP : forall b1 b2 : bool, reflect\n  (b1 = true /\\ b2 = true) ((b1 && b2) = true).\n\\end{verbatim}\nin a special hint database and \\texttt{apply} will know about it\nand use it when necessary.\n\nThere are two main ideas in our implementation. The first is that\nwe are launching a proof search to prove that the theorem\nwe wish to apply implies the current goal:\n\n\\begin{verbatim}\n?prove : arrow theorem goal\n\\end{verbatim}\nwhere \\texttt{arrow} is a relation that is definitionally equal to Coq's implication.\nWe use it because otherwise the proof-search mechanism would introduce\nthe premise \\texttt{theorem} in the proof context and then try\nto prove \\texttt{goal} with it, and this is not what we want.\n\nThe second is that although we cannot actually prove this implication\nmost of the time, we can provide an incomplete proof and let the\nuser fill the holes (this is after all the principle of\n\\texttt{apply}):\n\n\\begin{verbatim}\nsolveLater A -> arrow B C -> arrow (A -> B) C\n\\end{verbatim}\nwhere \\texttt{solveLater} is a dummy constant introduced to call the\nexternal hint we described earlier, which will shelve the sub-goal\n\\texttt{A} until the full search succeeds and then unshelve it for the\nuser to prove. In fact, because the conclusion \\texttt{B} might be\ndependent on the premise \\texttt{A}, we rather write:\n\n\\begin{verbatim}\nforall (t : T), arrow (U t) V ->\n  arrow (forall x : T, U x) V\n\\end{verbatim}\nand then shelve \\texttt{t}.\nA few other generic rules are present, one of them allowing to\ngo under quantifiers and, of course, the reflexivity of arrow:\n\n\\begin{verbatim}\n(forall x : A, arrow (f x) (g x)) ->\n  arrow (forall x : A, f x) (forall x : A, g x)\n\narrow T T\n\\end{verbatim}\n\nWith these rules only, we can reproduce the behavior of\n\\texttt{apply}, except for the built-in handling of\nsingle-constructor inductive types.\nActually already at that point, we do not reproduce the\nexact same behavior because our implementation allows\napplying a theorem \\texttt{forall x y, P x y}\nto a goal \\texttt{forall x, P x 0}.\n\nWith this basic infrastructure in place, we can start\nadding views, such as:\n\n\\begin{verbatim}\narrow P P' -> arrow (P /\\ Q) P'\narrow Q Q' -> arrow (P /\\ Q) Q'\n\\end{verbatim}\nwhich will be useful in emulating the current behavior\nof \\texttt{apply}. We can also add a very simple rule to\nhandle symmetry (one could think of more complex and\npowerful ways):\n\n\\begin{verbatim}\narrow (u = t) (t = u)\n\\end{verbatim}\nand finally, we register some more generic rules like:\n\n\\begin{verbatim}\nreflect P b -> arrow P (b = true)\nreflect b P -> arrow (b = true) P\n\\end{verbatim}\nso that people can easily extend the hint database with\nexisting reflection lemmas such as the one seen above.\n\n\\section{Conclusion}\n\nThis work is very preliminary but shows an interesting path\nto removing some of the hindrances there are in using\nboth SSReflect and vanilla Coq.\nIt is also a demonstration of the power of\n\\texttt{typeclasses eauto}, even when not working with\ntype classes.\nSometimes, the type class mechanism has been used while what\nwas really wanted was this Coq's Prolog that it gives access to.\nOne such example is the implementation of \\texttt{rewrite}:\nit probably could and should be based on a specific hint\ndatabase instead of the \\texttt{typeclass\\_instances} database.\n\nWe are planning first to continue to test and improve our\nre-implementation of \\texttt{apply}. We would in particular like\nto have views for applying a theorem modulo commutativity /\nassociativity. We are also planning to merge this work with our\nprevious work on applying theorems modulo isomorphisms\n\\cite{zimmermann}. A lot of ideas from this earlier work were\nreused here and the two implementations could very likely be\ncombined together.\n\n%\\appendix\n%\\section{Appendix Title}\n\n%This is the text of the appendix, if you need one.\n\n%\\acks\n\n%Acknowledgments, if needed.\n\n% We recommend abbrvnat bibliography style.\n\n\\bibliography{coq-prolog}\n\\bibliographystyle{abbrvnat}\n\n% The bibliography should be embedded for final submission.\n\n%\\begin{thebibliography}{}\n%\\softraggedright\n\n%\\bibitem[Smith et~al.(2009)Smith, Jones]{smith02}\n%P. Q. Smith, and X. Y. Jones. ...reference text...\n\n%\\end{thebibliography}\n\n\n\\end{document}\n", "meta": {"hexsha": "7e27b71ea2b1a6c2c7af4084a9cc3d5f77b264b9", "size": 14099, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/abstract/coq-prolog.tex", "max_stars_repo_name": "Zimmi48/TTT2017", "max_stars_repo_head_hexsha": "f43fe0328551c0b3ea05a6e9125305df0cf56573", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/abstract/coq-prolog.tex", "max_issues_repo_name": "Zimmi48/TTT2017", "max_issues_repo_head_hexsha": "f43fe0328551c0b3ea05a6e9125305df0cf56573", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/abstract/coq-prolog.tex", "max_forks_repo_name": "Zimmi48/TTT2017", "max_forks_repo_head_hexsha": "f43fe0328551c0b3ea05a6e9125305df0cf56573", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2729805014, "max_line_length": 95, "alphanum_fraction": 0.7540960352, "num_tokens": 3534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.33351227107778236}}
{"text": "% BEGIN LICENSE BLOCK\n% Version: CMPL 1.1\n%\n% The contents of this file are subject to the Cisco-style Mozilla Public\n% License Version 1.1 (the \"License\"); you may not use this file except\n% in compliance with the License.  You may obtain a copy of the License\n% at www.eclipse-clp.org/license.\n% \n% Software distributed under the License is distributed on an \"AS IS\"\n% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.  See\n% the License for the specific language governing rights and limitations\n% under the License. \n% \n% The Original Code is  The ECLiPSe Constraint Logic Programming System. \n% The Initial Developer of the Original Code is  Cisco Systems, Inc. \n% Portions created by the Initial Developer are\n% Copyright (C) 2006 Cisco Systems, Inc.  All Rights Reserved.\n% \n% Contributor(s): \n% \n% END LICENSE BLOCK\n\n%----------------------------------------------------------------------\n\\chapter{The Integer Sets Library}\n\\label{icsets}\n\\index{library!ic_sets|(}\n%HEVEA\\cutdef[1]{section}\n%----------------------------------------------------------------------\n\n\n%----------------------------------------------------------------------\n\\section{Why Sets}\n%----------------------------------------------------------------------\n\n\\index{finite sets}\nThe {\\em ic_sets} library is a solver for constraints over the domain\nof finite sets of integers.\nModelling with sets is useful for problems where one is not\ninterested in each item as a specific individual, but in a\ncollection of item where no specific distinction is made and thus\nwhere symmetries among the element values need to be avoided.\n\n\n%----------------------------------------------------------------------\n\\section{Finite Sets of Integers}\n%----------------------------------------------------------------------\n\nIn the context of the {\\em ic_sets} library, (ground) integer sets are\nsimply sorted, duplicate-free lists of integers e.g.\n\\begin{quote}\\begin{verbatim}\nSetOfThree = [1,3,7]\nEmptySet = []\n\\end{verbatim}\\end{quote}\nLists which contain non-integers, are unsorted or contain duplicates,\nare not sets in the sense of this library.\n\n\n%----------------------------------------------------------------------\n\\section{Set Variables}\n\\index{set variable}\n%----------------------------------------------------------------------\n\n%\\subsection{Declaring}\nSet variables are variables which can eventually take a ground integer\nset as their value.  They are characterized by a lower bound (the set\nof elements that are definitely in the set) and an upper bound (the\nset of elements that may be in the set).  A set variable can be\ndeclared as follows: \n\\begin{quote}\\begin{verbatim}\nSetVar :: []..[1,2,3,4,5,6,7]\n\\end{verbatim}\\end{quote}\n%If the lower bound is the empty set (like in this case) this can be written as \n%\\begin{verbatim}\n%        SetVar subset [1,2,3,4,5,6,7]\n%\\end{verbatim}\nIf the lower bound is the empty set and the upper bound is a set of\nconsecutive integers, one can also declare it like\n\\begin{quote}\\begin{verbatim}\nintset(SetVar, 1, 7)\n\\end{verbatim}\\end{quote}\nwhich is equivalent to the above.    \n\\quickref{Declaring Set Variables}{\n\\begin{description}\n\\item[\\biptxtrefni{?Set :: ++Lwb..++Upb}{::/2!ic_sets}{../bips/lib/ic_sets/NN-2.html}]\n\\index{::/2@\\texttt{::/2}!ic_sets} Set is an integer set within the given bounds \n\\item[\\biptxtref{intset(?Set, +Min, +Max)}{intset/3}{../bips/lib/ic_sets/intset-3.html}]\n         Set is a set containing numbers between Min and Max \n\\item[\\biptxtref{intsets(?Sets, ?N, +Min, +Max)}{intsets/4}{../bips/lib/ic_sets/intsets-4.html}]\n         Sets is a list of N sets containing numbers between Min and Max \n\\end{description}\n}\n\nThe system prints set variables in a particular way, for instance:\n\\begin{quote}\\begin{verbatim}\n?- lib(ic_sets).\n?- X :: [2,3]..[1,2,3,4].\nX = X{[2, 3] \\/ ([] .. [1, 4]) : _308{[2 .. 4]}}\n\\end{verbatim}\\end{quote}\nThe curly brackets contain the description of the current domain\nof the set variable in the form of\n\\begin{enumerate}\n\\item the lower bound of the set (values which definitely are in the set)\n\\item the union symbol \\verb.\\/.\n\\item the set of optional values (which may or may not be in the set)\n\\item a colon\n\\item a finite domain variable indicating the admissible cardinality for the set\n\\end{enumerate}\n\n\n%----------------------------------------------------------------------\n\\section{Constraints}\n%----------------------------------------------------------------------\n\n\\index{membership constraint}\n\\index{cardinality constraint}\nThe constraints that {\\em ic_sets} implements are the usual relations\nover sets.\nThe membership (in/2, notin/2) and cardinality constraints\n(\\#/2) establish\nrelationships between set variables and integer variables:\n\\quickref{Membership and Cardinality Constraints}{\n\\begin{description}\n\\item[\\biptxtrefni{?X in ?Set}{in/2!ic_sets}{../bips/lib/ic_sets/in-2.html}]\n         \\index{in/2@\\texttt{in/2}!ic_sets} The integer X is member of the integer set Set \n\\item[\\biptxtrefni{?X notin ?Set}{notin/2!ic_sets}{../bips/lib/ic_sets/notin-2.html}]\n         \\index{notin/2@\\texttt{notin/2}!ic_sets} The integer X is not a member of the integer set Set \n%\\item[\\biptxtref{membership_booleans(?Set, ?BoolArr)}{membership_booleans/2!ic_sets}{../bips/lib/ic_sets/membership_booleans-2.html}]\n%         BoolArr is an array of booleans describing Set \n\\item[\\biptxtrefni{\\#(?Set, ?Card)}{\\#/2!ic_sets}{../bips/lib/ic_sets/H-2.html}]\n         \\index{\\#/2@\\texttt{\\#/2}!ic_sets} Card is the cardinality of the integer set Set \n\\end{description}\n}\n\\begin{quote}\\begin{verbatim}\n?- X ::[]..[1, 2, 3], 2 in X, 3 in X, #(X, 2).\nX = [2, 3]\nYes (0.01s cpu)\n\n?- X :: []..[1, 2, 3, 4], 3 in X, 4 notin X.\nX = X{[3] \\/ ([] .. [1, 2]) : _2161{1 .. 3}}\nYes (0.00s cpu)\n\\end{verbatim}\\end{quote}\nPossible constraints between two sets are equality, inclusion/subset\nand disjointness:\n\\index{inclusion constraint}\n\\index{disjointness constraint}\n\\index{subset constraint}\n\\begin{quote}\\begin{verbatim}\n?- X subset [1, 2, 3, 4].\nX = X{([] .. [1, 2, 3, 4]) : _2139{0 .. 4}}\nYes (0.00s cpu)\n\n?- X :: []..[1, 2, 3, 4], Y :: []..[3, 4, 5, 6], X subset Y.\nX = X{([] .. [3, 4]) : _2176{0 .. 2}}\nY = Y{([] .. [3, 4, 5, 6]) : _2367{0 .. 4}}\nThere are 4 delayed goals.\nYes (0.00s cpu)\n\n?- X :: [2] .. [1, 2, 3, 4], Y :: [3] .. [1, 2, 3, 4], X disjoint Y.\nX = X{[2] \\/ ([] .. [1, 4]) : _2118{1 .. 3}}\nY = Y{[3] \\/ ([] .. [1, 4]) : _2213{1 .. 3}}\nThere are 2 delayed goals.\nYes (0.00s cpu)\n\\end{verbatim}\\end{quote}\n\\quickref{Basic Set Relations}{\n\\begin{description}\n\\item[\\biptxtrefni{?Set1 sameset ?Set2}{sameset/2!ic_sets}{../bips/lib/ic_sets/sameset-2.html}]\n         \\index{sameset/2@\\texttt{sameset/2}!ic_sets} The sets Set1 and Set2 are equal \n\\item[\\biptxtrefni{?Set1 disjoint ?Set2}{disjoint/2!ic_sets}{../bips/lib/ic_sets/disjoint-2.html}]\n         \\index{disjoint/2@\\texttt{disjoint/2}!ic_sets} The integer sets Set1 and Set2 are disjoint \n\\item[\\biptxtrefni{?Set1 includes ?Set2}{includes/2!ic_sets}{../bips/lib/ic_sets/includes-2.html}]\n         \\index{includes/2@\\texttt{includes/2}!ic_sets} Set1 includes (is a superset) of the integer set Set2 \n\\item[\\biptxtrefni{?Set1 subset ?Set2}{subset/2!ic_sets}{../bips/lib/ic_sets/subset-2.html}]\n         \\index{subset/2@\\texttt{subset/2}!ic_sets} Set1 is a (non-strict) subset of the integer set Set2 \n\\item[\\biptxtrefni{intersection(?Set1, ?Set2, ?Set3)}{intersection/3!ic_sets}{../bips/lib/ic_sets/intersection-3.html}]\n         \\index{intersection/3@\\texttt{intersection/3}!ic_sets} Set3 is the intersection of the integer sets Set1 and Set2 \n\\item[\\biptxtrefni{union(?Set1, ?Set2, ?Set3)}{union/3!ic_sets}{../bips/lib/ic_sets/union-3.html}]\n         \\index{union/3@\\texttt{union/3}!ic_sets} Set3 is the union of the integer sets Set1 and Set2 \n\\item[\\biptxtrefni{difference(?Set1, ?Set2, ?Set3)}{difference/3!ic_sets}{../bips/lib/ic_sets/difference-3.html}]\n         Set3 is the difference of the integer sets Set1 and Set2 \n\\item[\\biptxtrefni{symdiff(?Set1, ?Set2, ?Set3)}{symdiff/3!ic_sets}{../bips/lib/ic_sets/symdiff-3.html}]\n         \\index{symdiff/3@\\texttt{symdiff/3}!ic_sets} Set3 is the symmetric difference of the integer sets Set1 and Set2 \n\\end{description}\n}\nPossible constraints between three sets are for example\nintersection, union, difference and symmetric difference.\nFor example:\n\\begin{quote}\\begin{verbatim}\n?- X :: [2, 3] .. [1, 2, 3, 4],\n   Y :: [3, 4] .. [3, 4, 5, 6],\n   ic_sets : intersection(X, Y, Z).\nX = X{[2, 3] \\/ ([] .. [1, 4]) : _2127{2 .. 4}}\nY = Y{[3, 4] \\/ ([] .. [5, 6]) : _2222{2 .. 4}}\nZ = Z{[3] \\/ ([] .. [4]) : _2302{[1, 2]}}\nThere are 6 delayed goals.\nYes (0.00s cpu)\n\\end{verbatim}\\end{quote}\n\\Note{Note that we needed to qualify the intersection/3 constraint with\nthe {\\em ic_sets} module prefix because of a name conflict with a predicate from\nthe {\\em lists} library of the same name.}\n\\Note{Note the lack of a complement constraint: this is because the complement\nof a finite set is infinite and cannot be represented. Complements can be\nmodelled using an explicit universal set and a difference constraint.}\n\n\\ignore{\n\\subsection{Domain Access}\n\n\\begin{description}\n\\item[\\biptxtref{potential_members(?Set, -List)}{potential_members/2}{../bips/lib/ic_sets/potential_members-2.html}]\n         List is the list of elements of whose membership in Set is currently uncertain \n\\item[\\biptxtref{set_range(?Set, -Lwb, -Upb)}{set_range/3}{../bips/lib/ic_sets/set_range-3.html}]\n         Lwb and Upb are the current lower and upper bounds on Set \n\\end{description}\n}\n\nFinally, there are a number of n-ary constraints that apply to lists of sets:\ndisjointness, union and intersection. For example:\n\\quickref{N-ary Set Relations}{\n\\begin{description}\n\\item[\\biptxtref{all_disjoint(+Sets)}{all_disjoint/1}{../bips/lib/ic_sets/all_disjoint-1.html}]\n         Sets is a list of integers sets which are all disjoint \n\\item[\\biptxtref{all_union(+Sets, ?SetUnion)}{all_union/2}{../bips/lib/ic_sets/all_union-2.html}]\n         SetUnion is the union of all the sets in the list Sets \n\\item[\\biptxtref{all_intersection(+Sets, ?SetIntersection)}{all_intersection/2}{../bips/lib/ic_sets/all_intersection-2.html}]\n         SetIntersection is the intersection of all the sets in the list Sets \n\\end{description}\n}\n\\begin{quote}\\begin{verbatim}\n?- intsets(Sets, 5, 1, 5), all_intersection(Sets, Common).\nSets = [_2079{([] .. [1, 2, 3, 4, 5]) : _2055{0 .. 5}}, ... ]\nCommon = Common{([] .. [1, 2, 3, 4, 5]) : _3083{0 .. 5}}\nThere are 24 delayed goals.\nYes (0.00s cpu)\n\\end{verbatim}\\end{quote}\n\n\n\n%----------------------------------------------------------------------\n%\\section{Set Expressions}\n%----------------------------------------------------------------------\n\nIn most positions where a set or set variable is expected one can also\nuse a set expression. A set expression is composed from ground sets\n(integer lists), set variables, and the following set operators:\n\\begin{quote}\\begin{verbatim}\nSet1 /\\ Set2       % intersection\nSet1 \\/ Set2       % union\nSet1 \\ Set2        % difference\n\\end{verbatim}\\end{quote}\nWhen such set expressions occur, they are translated into auxiliary\n\\bipref{intersection/3}{../bips/lib/ic_sets/intersection-3.html},\n\\bipref{union/3}{../bips/lib/ic_sets/union-3.html} and\n\\bipref{difference/3}{../bips/lib/ic_sets/difference-3.html}\nconstraints, respectively.\n\n\n%----------------------------------------------------------------------\n\\section{Search Support}\n%----------------------------------------------------------------------\n\nThe\n\\bipref{insetdomain/4}{../bips/lib/ic_sets/insetdomain-4.html}\npredicate can be used to enumerate all ground instantiations of a set\nvariable, much like\n\\bipref{indomain/1}{../bips/lib/ic/indomain-1.html}\nin the finite domain case. \nHere is an example of the default enumeration strategy:\n\\begin{quote}\\begin{verbatim}\n?-  X::[]..[1,2,3], insetdomain(X,_,_,_), writeln(X), fail.\n[1, 2, 3]\n[1, 2]\n[1, 3]\n[1]\n[2, 3]\n[2]\n[3]\n[]\n\\end{verbatim}\\end{quote}\nOther enumeration strategies can be selected (see the Reference Manual\non insetdomain/4).\n\n\n%\\begin{description}\n%\\item[\\biptxtref{insetdomain(?Set, ?CardSel, ?ElemSel, ?Order)}{insetdomain/4}{../bips/lib/ic_sets/insetdomain-4.html}]\n%         Instantiate Set to a possible value \n%\\end{description}\n\n\n%----------------------------------------------------------------------\n\\section{Example}\n%----------------------------------------------------------------------\n\n\\index{Steiner problem}\nThe following program computes so-called Steiner triplets.\nThe problem is to compute triplets of numbers between 1 and N,\nsuch that any two triplets have at most one element in common.\n\\begin{code}\n:- lib(ic_sets).\n:- lib(ic).\n\nsteiner(N, Sets) :-\n        NB is N * (N-1) // 6,           % compute number of triplets\n        intsets(Sets, NB, 1, N),        % initialise the set variables\n        ( foreach(S,Sets) do\n            #(S,3)                      % constrain their cardinality\n        ),\n        ( fromto(Sets,[S1|Ss],Ss,[]) do\n            ( foreach(S2,Ss), param(S1) do\n                #(S1 /\\verb.\\. S2, C),         % constrain the cardinality\n                C #=< 1                 % of pairwise intersections\n            )\n        ),\n        label_sets(Sets).               % search\n\nlabel_sets([]).\nlabel_sets([S|Ss]) :-\n        insetdomain(S,_,_,_),\n        label_sets(Ss).\n\\end{code}\nRunning this program yields the following first solution:\n\\begin{quote}\\begin{verbatim}\n?- steiner(9,X).\n\nX = [[1, 2, 3], [1, 4, 5], [1, 6, 7], [1, 8, 9],\n     [2, 4, 6], [2, 5, 8], [2, 7, 9], [3, 4, 9],\n     [3, 5, 7], [3, 6, 8], [4, 7, 8], [5, 6, 9]] More? (;)\n\\end{verbatim}\\end{quote}\n\n\n%----------------------------------------------------------------------\n\\section{Weight Constraints}\n\\label{weight-constraint}\n\\index{weight constraint}\n%----------------------------------------------------------------------\n\n\\index{knapsack}\n\\index{bin packing}\nAnother constraint between sets and integers is the weight/3 constraint.\nIt allows the association of weights to set elements, and can help when\nsolving problems of the knapsack or bin packing type.\nThe constraint takes a set and an array of element weights and\nconstrains the weight of the whole set:\n\\begin{quote}\\begin{verbatim}\n?- ic_sets:(Container :: [] .. [1, 2, 3, 4, 5]),\n   Weights = [](20, 34, 9, 12, 19),\n   weight(Container, Weights, W).\nContainer = Container{([] .. [1, 2, 3, 4, 5]) : _2127{0 .. 5}}\nWeights = [](20, 34, 9, 12, 19)\nW = W{0 .. 94}\nThere is 1 delayed goal.\nYes (0.01s cpu)\n\\end{verbatim}\\end{quote}\nBy adding a capacity limit and a search primitive, we can solve a\nknapsack problem:\n\\begin{quote}\\begin{verbatim}\n?- ic_sets:(Container :: [] .. [1, 2, 3, 4, 5]),\n   Weights = [](20, 34, 9, 12, 19),\n   weight(Container, Weights, W),\n   W #=< 50,\n   insetdomain(Container,_,_,_).\nWeights = [](20, 34, 9, 12, 19)\nW = 41\nContainer = [1, 3, 4]\nMore (0.00s cpu)\n\\end{verbatim}\\end{quote}\n\nBy using the heuristic options provided by insetdomain, we can\nimplement a greedy heuristic, which finds the optimal solution\n(in terms of greatest weight) straight away:\n\\index{greedy heuristic}\n\\begin{quote}\\begin{verbatim}\n?- ic_sets:(Container :: [] .. [1, 2, 3, 4, 5]),\n   Weights = [](20, 34, 9, 12, 19),\n   weight(Container, Weights, W),\n   W #=< 50,\n   insetdomain(Container,decreasing,heavy_first(Weights),_).\nW = 48\nContainer = [1, 3, 5]\nWeights = [](20, 34, 9, 12, 19)\nMore (0.00s cpu)\n\\end{verbatim}\\end{quote}\n\\quickref{Set Weight Constraint}{\n\\begin{description}\n\\item[\\biptxtref{weight(?Set, ++ElementWeights, ?Weight)}{weight/3}{../bips/lib/ic_sets/weight-3.html}]\n         According to the array of element weights, the weight of set Set1 is Weight \n\\end{description}\n}\n\n\n\\section{Exercises}\n\n\\begin{enumerate}\n\n\\item\n\nConsider the knapsack problem in section~\\ref{weight-constraint}.\nSuppose that the items each have an associated profit, namely 17, 38, 18, 10\nand 5, respectively.  Which items should be included to maximise profit?\n\n\n\\item\n\nWrite a predicate which, given a list of sizes of items and a list of\ncapacities of buckets, returns a list of (ground) sets indicating which\nitems should go into each bucket.  Obviously each item should go into\nexactly one bucket.\n\nTry it out with 5 items of sizes 20, 34, 9, 12 and 19, into 3 buckets of\nsizes 60, 20 and 20.\n\n\\end{enumerate}\n\n\\index{library!ic_sets|)}\n\n%HEVEA\\cutend\n", "meta": {"hexsha": "36386aa61adf0927d6474759a50c75b75897634f", "size": 16403, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "usr/eclipseclp/documents/tutorial/setsolver.tex", "max_stars_repo_name": "lambdaxymox/barrelfish", "max_stars_repo_head_hexsha": "06a9f54721a8d96874a8939d8973178a562c342f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 111, "max_stars_repo_stars_event_min_datetime": "2015-02-03T02:57:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T23:57:09.000Z", "max_issues_repo_path": "usr/eclipseclp/documents/tutorial/setsolver.tex", "max_issues_repo_name": "lambdaxymox/barrelfish", "max_issues_repo_head_hexsha": "06a9f54721a8d96874a8939d8973178a562c342f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2016-03-22T14:44:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-18T13:30:29.000Z", "max_forks_repo_path": "usr/eclipseclp/documents/tutorial/setsolver.tex", "max_forks_repo_name": "lambdaxymox/barrelfish", "max_forks_repo_head_hexsha": "06a9f54721a8d96874a8939d8973178a562c342f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 55, "max_forks_repo_forks_event_min_datetime": "2015-02-03T05:28:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T05:00:03.000Z", "avg_line_length": 39.5253012048, "max_line_length": 134, "alphanum_fraction": 0.6337865025, "num_tokens": 4818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3334810397620536}}
{"text": "\\section{Theoretical Foundations}\n\\label{sec:Theoretical_Foundations}\nIn this experiment the speed of sound in various solids and liquids was determined. This section summarizes the theory and formulas necessary to understand the following experiments on ultrasound in section \\ref{sec:Evaluation}.\n\n%-------------------------------------------------------------------------------------------\n\\subsection{Wave Propagation}\n\\label{subsec:Wave_Propagation}\nWave propagation is the way in which waves travel. It can be distinguished between transverse waves and longitudinal waves. These waveforms are defined as follows:\n\n\\textbf{Transverse wave:} The displacement of the medium the wave travels through is perpendicular to the direction in which the wave propagates. Figure \\ref{fig:transverse} shows a graphical representation of this sinusoidal waveform in a rope \\cite{waves}.\n\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[scale=0.4]{transverse}\n\t\\caption{Representation of a periodic transverse sinusoidal wave in a rope. The up and down motion of the rope is perpendicular to the direction in which the wave propagates. This leads to each particle of the rope moving up and down \\cite{waves}. - partially modified}\n\t\\label{fig:transverse}\n\\end{figure}\n\n\\textbf{Longitudinal wave:} The displacement of the medium the wave travels through is parallel to the direction in which the wave propagates. Sound waves in air behave like this. The air molecules oscillate back and forth and their energy is propagated in the same direction as their motion. Figure \\ref{fig:longitudinal} shows a graphical representation of this waveform in a mechanical spring \\cite{waves}.\n\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[scale=0.45]{longitudinal}\n\t\\caption{Representation of a longitudinal wave in a mechanical spring. The elastic deflection (compression and extension) of the spring is parallel to the direction in which the wave propagates. This produces areas of increased and decreased pressure \\cite{waves}.}\n\t\\label{fig:longitudinal}\n\\end{figure}\n\n\\newpage\n%-------------------------------------------------------------------------------------------\n\\subsection{Reflection and Refraction}\n\\label{subsec:Reflection_and_Refraction}\nSimilar to optics, reflection and refraction also occur when sound waves hit the boundary between two different media. Contrary to optics, the refraction index is not the important quantity. The phase velocity leads to refraction and the impedance leads to reflection. It can be distinguished between a vertical and an oblique angle of incidence. The following two sections explain this in more detail \\cite{ultrasound}.\n\n%-------------------------------------------------------------------------------------------\n\\subsubsection{Vertical Angle of Incidence}\n\\label{subsubsec:Vertical_Angle_of_Incidence}\nA sound wave with the pressure $\\hat{p}_e$ and velocity $v_e$ that travels trough a medium with the impedance $Z_1$ hits a boundary between two media with a vertical angle of incidence. This results in a different ratio between the pressure $\\hat{p}_t$ and velocity $v_t$ in the medium with the impedance $Z_2$. At the same time the pressure and the velocity have to be equal at the boundary between the two media. This leads to a third reflected partial wave. Figure \\ref{fig:vertical_angle_of_incidence} shows the just described phenomenon \\cite{ultrasound}.\n\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[scale=1.5]{vertical_angle_of_incidence}\n\t\\caption{Representation of a sound wave $e$ in blue that hits a boundary between the two media with the impedances $Z_1$ and $Z_2$. The transmitted wave $t$ is shown in green and the reflected partial wave $r$ is shown in red \\cite{ultrasound}. - partially modified}\n\t\\label{fig:vertical_angle_of_incidence}\n\\end{figure}\n\nThe calculation of the amplitude reflection coefficient $r$ is shown in equation \\ref{eq:vertical_reflection} and the amplitude transmission coefficient $t$ is shown in equation \\ref{eq:vertical_transmission}. They can be derived by utilizing the continuity conditions that are valid at the interface between the two media \\cite{ultrasound}.\n\n\\begin{equation}\nr = \\dfrac{\\hat{p}_r}{\\hat{p}_e} = \\dfrac{Z_2-Z_1}{Z_2+Z_1}\n\\label{eq:vertical_reflection}\n\\end{equation}\n\\begin{equation}\nt = \\dfrac{\\hat{p}_t}{\\hat{p}_e} = \\dfrac{2 Z_2}{Z_2+Z_1}\n\\label{eq:vertical_transmission}\n\\end{equation}\nwhere:\n\\begin{multicols}{2}\n\\begin{conditions}\n\tr & reflection coefficient \\\\\n\tt & transmission coefficient \\\\\n\tZ_1 \\text{, } Z_2 & medium impedance\n\\end{conditions}\n\\begin{conditions}\n\t\\hat{p}_r & reflected pressure \\\\\n\t\\hat{p}_t & transmitted pressure \\\\\n\t\\hat{p}_e & pressure amplitude\n\\end{conditions}\n\\end{multicols}\n\nIf $Z_2$ is smaller than $Z_1$ the reflection coefficient turns out negative which means the reflected wave is phase-shifted by 180\\textdegree\\ \\cite{ultrasound}.\n\\newpage\n%-------------------------------------------------------------------------------------------\n\\subsubsection{Oblique Angle of Incidence}\n\\label{subsubsec:Oblique_Angle_of_Incidence}\nThe reflection and transmission coefficients of a sound wave $e$ that hits an interface between two media with an oblique angle $\\alpha$ depend on this angle of incidence. Furthermore, the transmitted wave will be refracted. If the medium $Z_2$ happens to be a solid, a transversal and a longitudinal wave will form. Figure \\ref{fig:oblique_angle_of_incidence} shows this phenomenon which is called \\flqq mode conversion\\frqq\\ \\cite{ultrasound}.\n\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[scale=1.5]{oblique_angle_of_incidence}\n\t\\caption{Representation of a sound wave $e$ shown in blue that hits an interface between the two media $Z_1$ and $Z_2$ with an oblique angle of incidence. The reflected wave $r$ is shown in red and the refracted transverse and longitudinal waves are shown in green \\cite{ultrasound}.}\n\t\\label{fig:oblique_angle_of_incidence}\n\\end{figure}\n\nTo calculate the angle of reflection shown in equation \\ref{eq:oblique_angle_of_incidence} and the refraction shown in equation \\ref{eq:oblique_refraction}, the same known laws from optics apply. Equation \\ref{eq:oblique_refraction} allows the use of the transversal or longitudinal sound velocity for the variable $c_2$ depending on the desired result \\cite{ultrasound}.\n\n\\begin{equation}\n\\alpha = \\alpha^\\prime\n\\label{eq:oblique_angle_of_incidence}\n\\end{equation}\n\\begin{equation}\n\\dfrac{\\sin{(\\alpha)}}{\\sin{(\\beta)}} = \\dfrac{c_1}{c_2}\n\\label{eq:oblique_refraction}\n\\end{equation}\nwhere:\n\\begin{multicols}{2}\n\\begin{conditions}\n\t\\alpha & angle of incidence \\\\\n\t\\beta & angle of refraction\n\\end{conditions}\n\\begin{conditions}\n\t\\alpha^\\prime & angle of reflection \\\\\n\tc_1 \\text{, } c_2 & sound velocity in the medium\n\\end{conditions}\n\\end{multicols}\n\n\n%-------------------------------------------------------------------------------------------\n\\subsection{Total Internal Reflection}\n\\label{subsec:Total_Internal_Reflection}\nTotal internal reflection can take place at the interface between two media. This happens when the following equation is valid:\n\n\\[\n\\sin{(\\alpha_\\text{crit})} = \\dfrac{c_1}{c_2}\n\\]\n\nThis is a variation of the above shown equation \\ref{eq:oblique_refraction}. Thus, the angle of refraction $\\beta$ has to be 90\\textdegree\\ for the equation to be valid. For $\\alpha \\geq \\alpha_\\text{crit}$ the wave is totally reflected \\cite{ultrasound}.\n\n%-------------------------------------------------------------------------------------------\n\\subsection{Absorption}\n\\label{subsec:Absorption}\nSound waves are attenuated when they propagate in a medium due to absorption and scattering. Absorption usually converts a part of the ultrasound wave into heat. Scattering leads a particle that has been excited by the incoming wave to emit a wave in all direction itself. Equation \\ref{eq:absorption} shows the exponential attenuation for monochromatic radiation. The \\textbf{higher the frequency}, the \\textbf{stronger the absorption} and scattering \\cite{ultrasound}.\n\n\\begin{equation}\n\\hat{p}(x) = \\hat{p}_0 \\cdot e^{-\\mu x}\n\\label{eq:absorption}\n\\end{equation}\nwhere:\n\\begin{multicols}{2}\n\\begin{conditions}\n\t\\hat{p}(x) & attenuated amplitude \\\\\n\t\\mu & attenuation coefficient in m$^{-1}$\n\\end{conditions}\n\\begin{conditions}\n\t\\hat{p}_0 & initial amplitude \\\\\n\tx & distance in m\n\\end{conditions}\n\\end{multicols}\n\n%-------------------------------------------------------------------------------------------\n\\subsection{Ultrasound Generation}\n\\label{subsec:Ultrasound_Generation}\nUltrasound can be generated and received by using a ultrasonic transducer. In this experiment the piezoelectric effect is used in the ultrasonic transducer. Certain crystals expand proportional to the applied voltage. Contrary to this, the piezoelectric transducer induces a voltage when deformed. Thus, it can be used as a transmitter or receiver \\cite{ultrasound}.\n\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[scale=1.5]{ultrasound_generation}\n\t\\caption{Graphical representation of a piezoelectric transducer. The active part is the thin piezo disk at the bottom of the transducer. The mechanical dimensions determine the resonance frequency of the oscillation. The transducer is impedance matched to the amplifier \\cite{ultrasound}.}\n\t\\label{fig:ultrasound_generation}\n\\end{figure}\n\n\\newpage\n%-------------------------------------------------------------------------------------------\n\\subsection{Ultrasound Measurement}\n\\label{subsec:Ultrasound_Measurement}\nThere are two common ways to measure ultrasound, the A-Scan and the B-Scan. This experiment uses the A-Scan as measurement method and therefore only this one will be explained.\n\nThe A-Scan is a one-dimensional procedure where short ultrasound impulses ($f > 20 \\text{kHz}$) are transmitted. These are partially reflected on the interfaces between media and are received again by the transmitter. From the time difference between the sent impulse and the received echo and a known distance, the sound velocity of a medium can be determined. Equation \\ref{eq:sound_velocity} shows this relationship \\cite{ultrasound}.\n\n\\begin{equation}\nc_m = \\dfrac{2x}{\\Delta t}\n\\label{eq:sound_velocity}\n\\end{equation}\nwhere:\n\\begin{multicols}{2}\n\t\\begin{conditions}\n\t\tc_m & sound velocity of a medium in $\\,^{\\text{m}}\\!/_{\\text{s}}$ \\\\\n\t\t\\Delta t & time difference in s\n\t\\end{conditions}\n\t\\begin{conditions}\n\t\tx & distance to interface in m\n\t\\end{conditions}\n\\end{multicols}\n\nThis technique is often used to check the integrity of materials. If the part has defects such as cracks or inclusions of different substances, there are detectable echoes. Furthermore, the wall thickness of work pieces can be determined by this method \\cite{ultrasound}.\n", "meta": {"hexsha": "167e319badae536dc2b9e2935b7ebec172075271", "size": 10741, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "glaL4_W_12_Ultrasound/sections/theoretical_foundations.tex", "max_stars_repo_name": "MuellerDominik/Physics-Laboratory-Notebooks", "max_stars_repo_head_hexsha": "02836870e6d97a29b1857c956fbd58eb5933eede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "glaL4_W_12_Ultrasound/sections/theoretical_foundations.tex", "max_issues_repo_name": "MuellerDominik/Physics-Laboratory-Notebooks", "max_issues_repo_head_hexsha": "02836870e6d97a29b1857c956fbd58eb5933eede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "glaL4_W_12_Ultrasound/sections/theoretical_foundations.tex", "max_forks_repo_name": "MuellerDominik/Physics-Laboratory-Notebooks", "max_forks_repo_head_hexsha": "02836870e6d97a29b1857c956fbd58eb5933eede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 61.3771428571, "max_line_length": 560, "alphanum_fraction": 0.7329857555, "num_tokens": 2577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3334810312880515}}
{"text": "\\subsubsection{\\stid {3.01} xSDK Sub-project: multiprecision} \n\\paragraph{Overview} \nWithin the past years, hardware vendors have started designing low precision special function units \nin response to the demand of the Machine Learning community for high compute power\nin low precision formats. At the same time, the gap between compute power\non the one hand and memory bandwidth on the other hand keeps increasing, \nmaking data access and communication prohibitively expensive compared to arithmetic operations.\nHaving the choice between ignoring the hardware trends and continuing the traditional path\nor adjusting the software stack to the changing hardware designs, the US Exascale Computing Project\ndecided to build a multiprecision focus effort to take on the challenge of designing and engineering novel algorithms capable to exploit the compute power available in low precision and to adjust the communication format to application specific needs.\nAs part of the xSDK project, the multiprecision focus effort is a coordinated effort creating synergies via cross-institutional collaboration.\n\n\\paragraph{Key Challenges}\nGenerally, there exists a strong relationship between the precision used in arithmetic operations and the accuracy of the computed result. Since scientific applications need to provide high quality output, replacing high precision formats with low precision formats throughout a complete application code is generally not feasible. Instead, to utilize lower precision formats, the underlying numerical algorithms have to be redesigned to employ low precision formats for the most time-consuming parts while preserving  high accuracy in the solution. In this context, the arithmetic operations are only one aspect. As the execution time of many scientific applications is dominated by communication and memory access, the algorithm redesign also has to include strategies for compressing data to reduce the pressure on the memory bandwidth. This aspect becomes even more relevant as the arithmetic power continues to grow faster than the memory bandwidth, therewith widening the gap between arithmetic performance and memory performance, see Figure~\\ref{fig:xsdk-machinebalance}.\n\n\\begin{figure}[htb]\n\t\\centering\n\t\\includegraphics[width=.8\\columnwidth]{projects/2.3.3-MathLibs/2.3.3.01-xSDK/xSDK-machinebalance.pdf}\n\t%\\includegraphics[width=.8\\columnwidth]{xSDK-machinebalance.pdf}\n\t\\caption{\\label{fig:xsdk-machinebalance} Evolution of the machine balance of processors over different hardware generations.}\n\\end{figure}\n\n\n\\paragraph{Solution Strategy}\nIn the multiprecision effort, the team assesses current status and functionalities, advances the theoretical knowledge on multiprecision algorithms, designs prototype implementations and multiprecision interoperability layers, deploys production-ready multiprecision algorithms in the xSDK math libraries, ensures multiprecision cross-library interoperability and integrates multiprecision algorithms into ECP application projects. The long list of project activities is organized in a multi-phase approach:\nThe first stage is dedicated to the exploration of the design space and existing research efforts focusing on low precision, mixed precision, and extended precision. To this end, the effort  includes internationally-renown external experts for mixed precision algorithms. In the second stage, the multiprecision effort increasingly focuses on developing production code ready to be used in the ECP application projects. Relevant algorithmic functionality includes sparse linear algebra, multigrid methods, preconditioners, iterative solvers, low-rank approximations, and mixed precision machine learning.\nOn the hardware side, special focus is put on low-precision special function units like NVIDIA’s tensor cores that -- originally designed for machine learning algorithms -- offer about an order of magnitude higher arithmetic performance than conventional fp64 units. \nIn the third phase of the multiprecision effort, the project team will aid the ECP application projects with the adoption of multiprecision functionality and continue to adapt to new hardware technologies.\n\n\n\\paragraph{Recent Progress}\nAs a first step, the multiprecision team surveyed the state of the art in terms of mixed precision algorithms, low precision and extended precision algorithms, and the algorithmic needs of the ECP application projects. The results of this landscape assessment are made publicly available as ``A Survey of Numerical Methods Utilizing Mixed Precision Arithmetic''~\\cite{Anztetal2020}.\nA more compact version of this survey -- exclusively focusing on numerical linear algebra -- has been submitted as a journal article.\n\nBased on the findings of the multiprecision landscape assessment, we created a set of cross-institutional focus groups that address different algorithms and aspects of the ECP software ecosystem including dense and sparse direct solvers, eigensolvers, Krylov-based iterative solvers, multigrid methods, preconditioners, Fast Fourier Transform, and machine learning technology. Orthogonal to those, we created focus groups on the design on a memory accessor that separates the arithmetic precision from the communication precision, and the efficient realization of multiprecision basic building blocks like sparse matrix vector multiply.\nIn bi-weekly virtual meetings, the progress on the different efforts is presented and discussed as many of these efforts are closely related. As another integral part of the bi-weekly phone calls we established a series of short talks where each meeting is commenced by an invited talk presenting an idea, success story, or progress update on mixed precision functionality to the audience. \n\nFollowing the idea of decoupling the memory precision from the arithmetic precision to reduce the pressure on the memory bandwidth, the team released an accessor design document detailing the implementation and usage of a memory accessor that compresses data, e.g. by converting to a lower precision format, before invoking memory operations.\nThe document has been made available to the ECP community.\n\n\\paragraph{Next Steps}\n\nOur next efforts include \n\\begin{itemize}\n    \\item the publication of a compacted version of the multiprecision landscape assessement as a scientific journal paper,\n    \\item the deployment of the accessor separating memory precision and arithmetic precision in the Ginkgo library with support for AMD GPUs, NVIDIA GPUs, and multicore CPUs,  \n    \\item the implementation of compressed basis Krylov solvers that utilize the memory accessor to compact the Krylov search directions,\n    \\item the advancement of multiprecision capabilities for solvers, preconditioners, and other ECP-relevant kernels in xSDK libraries, including\n    \\subitem - the design and implementation of mixed precision eigensolvers,\n    \\subitem - the research and realization of mixed precision multigrid solvers,\n    \\subitem - the design and implementation of mixed precision sparse factorizations.\n\\end{itemize}\n\n", "meta": {"hexsha": "1ee3af29fe5640f1e62349f7a998fad5c8e51555", "size": 7062, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "projects/2.3.3-MathLibs/2.3.3.01-xSDK/2.3.3.01-xsdk-multiprecision.tex", "max_stars_repo_name": "klondikemike/ECP-ST-CAR-PUBLIC", "max_stars_repo_head_hexsha": "a6840615223d1f1ce240dba38d0b2821925c270d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "projects/2.3.3-MathLibs/2.3.3.01-xSDK/2.3.3.01-xsdk-multiprecision.tex", "max_issues_repo_name": "klondikemike/ECP-ST-CAR-PUBLIC", "max_issues_repo_head_hexsha": "a6840615223d1f1ce240dba38d0b2821925c270d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "projects/2.3.3-MathLibs/2.3.3.01-xSDK/2.3.3.01-xsdk-multiprecision.tex", "max_forks_repo_name": "klondikemike/ECP-ST-CAR-PUBLIC", "max_forks_repo_head_hexsha": "a6840615223d1f1ce240dba38d0b2821925c270d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 130.7777777778, "max_line_length": 1078, "alphanum_fraction": 0.8292268479, "num_tokens": 1312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3334810228140493}}
{"text": "\\paragraph{Influence of Blur Factor} \\label{influence_of_blur_factor}\nThe blur factor for a sliding window filter is expanding the interval that is accepting time series windows. A too small\ninterval can lead to many false positive classifications and a too large interval may lead to too much 1NN-DTW calls.\nThe underlying time series measure for a sliding window filter is affecting the best performing blur factor for the\nfilter. Eleven different blur factors were tested for the two different underlying time series measures. The influence of\nthe blur factor for the filter is tested for the two underlying time series measures and compared to the\ndominating configuration without filter. The right plot of figure \\ref{fig:blur_factor_result} illustrates the influence\nof the blur factor on the $F_{1}score_{\\mu}$. Only the LNCE estimate is reaching with the given blur factors the same\n$F_{1}score_{\\mu}$ as the dominating configuration without filter. However, the two filter types come also with small\nblur factors very close to the top $F_{1}score_{\\mu}$ value.\n\n\\begin{figure}[H]\n    \\begin{center}\n        \\resizebox {\\textwidth} {!} {\n            \\begin{tabular}{cc}\n                \\resizebox {!} {\\height} {\n                    \\begin{tikzpicture}\n                        \\begin{axis}[\n                            legend pos=south east,\n                            xmin=100,\n                            xmax=300,\n                            ymin=0.6,\n                            ymax=0.75,\n                            xlabel=filter interval size in \\%,\n                            ylabel=$F_{1}score_{\\mu}$,\n                            width=\\axisdefaultwidth,\n                            height=0.7*\\axisdefaultheight]\n                            \\addplot[blue, ultra thick] table {../data/fig/blur_factor_result/lnce.dat};\n                            \\addlegendentry{LNCE}\n                            \\addplot[red, ultra thick] table {../data/fig/blur_factor_result/var.dat};\n                            \\addlegendentry{VAR}\n                            \\addplot[dotted, black, domain=100:300] {0.738393631276109};\n                            \\addlegendentry{No Filter}\n                        \\end{axis}\n                    \\end{tikzpicture}\n                } &\n                \\resizebox {!} {\\height} {\n                    \\begin{tikzpicture}\n                        \\begin{axis}[\n                            legend pos=south east,\n                            xmin=100,\n                            xmax=300,\n                            ymin=0,\n                            ymax=5500,\n                            xlabel=filter interval size in \\%,\n                            ylabel=\\# 1NN-DTW calls,\n                            width=\\axisdefaultwidth,\n                            height=0.7*\\axisdefaultheight]\n                            \\addplot[blue, ultra thick] table {../data/fig/nnc_calls_result/lnce.dat};\n                            \\addlegendentry{LNCE}\n                            \\addplot[red, ultra thick] table {../data/fig/nnc_calls_result/var.dat};\n                            \\addlegendentry{VAR}\n                            \\addplot[dotted, black, domain=100:300] {4893};\n                            \\addlegendentry{No Filter}\n                        \\end{axis}\n                    \\end{tikzpicture}\n                }\n            \\end{tabular}\n        }\n    \\end{center}\n    \\caption{The left plot shows the $F_{1}score_{\\mu}$ depending on the blur factor that expands the size of the filter\n    interval in \\%. The right plot shows the amount of 1NN-DTW calls depending on the blur factor that expands the size\n    of the filter interval in \\%.}\n    \\label{fig:blur_factor_result}\n\\end{figure}\n\nThe left plot of figure \\ref{fig:blur_factor_result} and also table \\ref{tab:result} shows that the presented\nfilters can reach the same $F_{1}score_{\\mu}$ value as the dominating simulation without filter. The question remains on\nhow often are the presented filters block the 1NN-DTW calls. The right plot of figure \\ref{fig:blur_factor_result}\nillustrates the influence of the blur factor on the amount of 1NN-DTW calls. All two filter types remain clearly below\nthe amount of 1NN-DTW calls of the dominating configuration without filter. Figure \\ref{fig:blur_factor_tradeoff}\ncombines both plots of figure \\ref{fig:blur_factor_result} to trade-off curves for both filters.\n\n\\begin{figure}[H]\n    \\begin{center}\n        \\resizebox {\\textwidth} {!} {\n            \\begin{tabular}{cc}\n                \\resizebox {!} {\\height} {\n                    \\begin{tikzpicture}\n                        \\begin{axis}[\n                            legend pos=south west,\n                            xlabel=$F_{1}score_{\\mu}$,\n                            ylabel=\\# blocked 1NN-DTW calls,\n                            width=\\axisdefaultwidth,\n                            height=\\axisdefaultwidth]\n                            \\addplot[blue, only marks, mark=*] table[y=Y] {../data/fig/nnc_calls_result/tradeoff-lnce.dat};\n                            \\addplot[gray, domain=0.7:0.74] {-83543.0872*x^2+55746.6816*x+4892.4835};\n                            \\addlegendentry{LNCE}\n                        \\end{axis}\n                    \\end{tikzpicture}\n                } &\n                \\resizebox {!} {\\height} {\n                    \\begin{tikzpicture}\n                        \\begin{axis}[\n                            legend pos=south west,\n                            xlabel=$F_{1}score_{\\mu}$,\n                            ylabel=\\# blocked 1NN-DTW calls,\n                            width=\\axisdefaultwidth,\n                            height=\\axisdefaultwidth]\n                            \\addplot[red, only marks, mark=*] table[y=Y] {../data/fig/nnc_calls_result/tradeoff-var.dat};\n                            \\addplot[gray, domain=0.63:0.74] {-34477.4805*x^2+20729.4890*x+4884.5834};\n                            \\addlegendentry{VAR}\n                        \\end{axis}\n                    \\end{tikzpicture}\n                }\n            \\end{tabular}\n        }\n    \\end{center}\n    \\caption{Trade-off between the $F_{1}score_{\\mu}$ and the amount of blocked 1NN-DTW calls for both filter\n    types. The gray graphs are quadratic regressions to illustrate the trade-off as curve on the observed intervals.}\n    \\label{fig:blur_factor_tradeoff}\n\\end{figure}\n", "meta": {"hexsha": "1346a4961e7aa0cedab2768d46cb16579fff6c8f", "size": 6370, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "bachelor-thesis/experiment/evaluation/influence_of_sliding_window_filter/influence_of_blur_factor.tex", "max_stars_repo_name": "GordonLesti/SlidingWindowFilter", "max_stars_repo_head_hexsha": "22c11f2912a5c523ae8ad85a849e2d0b123536ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-06-22T09:37:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-14T11:43:53.000Z", "max_issues_repo_path": "bachelor-thesis/experiment/evaluation/influence_of_sliding_window_filter/influence_of_blur_factor.tex", "max_issues_repo_name": "GordonLesti/SlidingWindowFilter", "max_issues_repo_head_hexsha": "22c11f2912a5c523ae8ad85a849e2d0b123536ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bachelor-thesis/experiment/evaluation/influence_of_sliding_window_filter/influence_of_blur_factor.tex", "max_forks_repo_name": "GordonLesti/SlidingWindowFilter", "max_forks_repo_head_hexsha": "22c11f2912a5c523ae8ad85a849e2d0b123536ec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-11T23:15:57.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-11T23:15:57.000Z", "avg_line_length": 56.3716814159, "max_line_length": 123, "alphanum_fraction": 0.5370486656, "num_tokens": 1405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.3334348807301059}}
{"text": "\\chapter{How to model a system}\\label{How to model a system}\n\\begin{aquote}{The Chemical Basis of Morphogenesis. A. Turing 1952.}\n\\textit{This model will be a simplification and an idealization, and consequently a falsification. It is to be hoped that the features retained for discussion are those of greatest importance in the present state of knowledge.}\n\\end{aquote}\n\\begin{aquote}{Empirical Model-Building and Response Surfaces. G. Box \\& N. Draper 1987.}\n\\textit{All models are wrong, but some are useful.}\n\\end{aquote}\nModelling a system, whether it be physical, chemical, or biological, is, in some ways, more of art than a science. You try and strip away all extraneous information and mathematically describe that which is left. Sometimes there are physical laws to help you, \\eg gravity, conservation of energy and mass. Other times we only have experimental intuition, \\eg predator-prey interactions from population data. In either case, the central idea of modelling is that it should always form part of a cyclical process \\see{Modelling_loop}.\n\nYou try to start with physical intuition (experiment), represent the important parts mathematically (model), hopefully reproduce reality (test) and, finally, use your mathematical model to predict unknown outcomes (predict). These prediction can then feed back into experiment and the process begins anew.\n\\begin{figure}[!!!h!!!tb]\n\\centering\n\\includegraphics[width=\\tp]{../Pictures/Modelling_loop.png}\n\\caption{\\label{Modelling_loop}Diagram of the modelling cycle.}\n\\end{figure}\n\nIn this chapter we are going to review some of the methods that can be used to produce a mathematical interpretation of reality.\n\n\\section{Physical laws}\n\\begin{defin}\nA \\textbf{constitutive relation} (or `physical law') is a rule that the modeller adds to the system based on their experimental experience, which relates interacting components.\n\\end{defin}\nPhysics has many laws such as: conservation of energy, general relativity and the laws of thermodynamics. There is (as yet) no fundamental reason for these laws to hold. We just take them as laws because they fit the data that we observe.\n\nHere are just a few examples of the laws that you might come across.\n\\begin{itemize}\n\n\\item \\textbf{Newton's Law of Cooling.}\n\n\\textit{The rate of cooling of a body is proportional to the difference between the bodies temperature and the temperature of its environment.}\n\n\\COL{Let $T$ and $T_e$ be the temperatures of the object and the environment, respectively, then\n\\bb\n\\dot{T}=k(T_e-T),\\label{Law_of_cooling}\n\\ee\nwhere $k$ is defined to be the heat transfer coefficient.}\n\\begin{example}[frametitle=Cooling tea]\\label{Cooling_tea}\nSuppose I prepare two cups of tea at exactly the same time, so initially they both start at $100^o$C. I quickly add enough milk to cup 1 to cool it to $90^o$C. Ten minutes later I add milk to cup 2, which cools cup 2 by $10^o$C. Which cup is hotter at that point?\n\\COL{\nThe general solution to \\eqn{Law_of_cooling} is\n\\bb\nT(t)=T_e+\\l T(0)-T_e\\r e^{-kt},\n\\ee\nwhere $T(0)$ is the initial temperature. For cup 1 we have\n\\bb\nT_1(10)=T_{e}+\\l 90-T_{e}\\r e^{-k10}.\n\\ee\nFor cup 2 we have\n\\bb\nT_2(10)=T_{e}+\\l 100-T_{e}\\r e^{-k10}-10.\n\\ee\nSubtracting $T_1$ from $T_2$ gives\n\\bb\nT_1(10)-T_2(10)=10\\l 1- e^{-k10}\\r>0.\n\\ee\nSince $\\exp(0)=1$ and $\\exp(-kt)$ is a strictly monotonically decreasing function of time. Hence, cup 1 is hotter than cup 2 at time $t=10$ minutes. This means that the earlier you put your milk in the hotter your tea will stay!\n\nNote that neither the ambient temperature, nor the heat transfer coefficient were needed.}\n\\end{example}\n\n\\item \\textbf{Newton's Second Law of Motion}\n\n\\textit{The rate of change of momentum of a body is directly proportional to the force applied to the body.}\n\n\\COL{This is the standard $F=ma$ that everyone knows and loves (assuming that the mass remains that same throughout the interaction), where the acceleration, $a$, is the second derivative of the location with respect to time, $a=\\ddot{x}$.}\n\n\n\\item \\textbf{Newton's Law of Gravitation}\\footnote{Newton devised the laws of optics, the laws of motion and invented calculus practically on a dare... then he turned 26. What have you done today? }\n\n\\textit{A particle attracts every other particle in the universe using a force that is directly proportional to the product of their masses and inversely proportional to the square of the distance between their centres.}\n\n\\COL{Suppose body $i$ has mass $m_i$ and is at position $\\bm{r}_i=(x_i,y_i)$. Body $i$ is then separated from body $j$ by a distance $r_{ij}=\\sqrt{\\l x_i-x_j\\r^2+\\l y_i-y_j \\r^2}=|\\bm{r}_i-\\bm{r}_j|$. Let $G$ be the universal gravitational constant then the force, $\\bm{F}_{ij}$, acting on body $i$ from body $j$ is\n\\bb\n\\bm{F}_{ij}=-G\\frac{m_im_j}{r^2_{ij}}\\bm{\\hat{r}}_{ji},\n\\ee\nwhere \n\\bb\n\\bm{\\hat{r}}_{ji}=\\frac{r_i-r_j}{|r_i-r_j|}\n\\ee\nis the unit vector from body $j$ to body $i$.\n\nNote that the force is vector valued quantity because it has a magnitude, but also a direction, as it acts in the direction of the line joining the bodies.}\n\\begin{figure}[!!!h!!!tb]\n\\centering\n\\includegraphics[width=\\ttp]{../Pictures/Three_body_problem.png}\n\\caption{\\label{Three_body}Schematic diagram of the three-body problem.}\n\\end{figure}\n\n\n\\begin{example}[frametitle=Three body problem]\\label{Three_body_problem}\nWe can combine the Second Law of Motion and the Law of Gravitation in order to predict the position of planets interacting through their gravitational fields \\see{Three_body}. Consider three planets with the same mass, $m$, and positions $\\bm{r}_1(t)$, $\\bm{r}_2(t)$ and $\\bm{r}_3(t)$, respectively. Further, we note that since we are dealing with acceleration (a second order equation) we will need to specify two initial conditions, the position and velocity. Let the initial positions be $\\bm{r}_i(0)=\\bm{r}_{i0}$ and the initial velocities $\\dot{\\bm{r}}_i(0)=\\bm{v}_{i0}$.\\COL{ The governing equations are\n\\begin{align}\n&m\\ddot{\\bm{r}}_1=-G\\frac{m^2}{|\\bm{r}_1-\\bm{r}_2|^3}\\l\\bm{r}_1-\\bm{r}_2\\r-G\\frac{m^2}{|\\bm{r}_1-\\bm{r}_3|^3}\\l\\bm{r}_1-\\bm{r}_3\\r,\\label{g1}\\\\\n&m\\ddot{\\bm{r}}_2=-G\\frac{m^2}{|\\bm{r}_2-\\bm{r}_1|^3}\\l\\bm{r}_2-\\bm{r}_1\\r-G\\frac{m^2}{|\\bm{r}_2-\\bm{r}_3|^3}\\l\\bm{r}_2-\\bm{r}_3\\r\\label{g2},\\\\\n&m\\ddot{\\bm{r}}_3=-G\\frac{m^2}{|\\bm{r}_3-\\bm{r}_1|^3}\\l\\bm{r}_3-\\bm{r}_1\\r-G\\frac{m^2}{|\\bm{r}_3-\\bm{r}_2|^3}\\l\\bm{r}_3-\\bm{r}_2\\r\\label{g3}.\n\\end{align}\nwhere we remember that this is a vector equation, $\\bm{r}_i=(x_i,y_i)$, so there are actually six, second order ODEs here, rather than three.}\n\nThe three body problem illustrates chaotic behaviour, in the sense that the outcome is extremely sensitive to the initial conditions. This can be seen in the simulations of \\fig{Three_body_sim}.\n\nSimulation tip:\n\\begin{itemize}\n\\item when solving \\eqnto{g1}{g3} numerically we could separate each equation into its Cartesian components and reduce the second order equation to two first order equations. Namely, we would introduce $(v_{ix},v_{iy})=(\\dot{x}_i,\\dot{y}_i)$. Thus, we would have a system of twelve ODEs to solve, with variables\n\\bb\n(x_1,y_1,v_{1x},v_{1y},x_2,y_2,v_{2x},v_{2y},x_3,y_3,v_{3x},v_{3y}).\n\\ee\nHowever, since $x_i$ and $y_i$ are perpendicular Cartesian coordinates it turns out to be a good idea to use complex numbers. Specifically, instead of writing two ODEs for each of $x_i$ and $y_i$ we can simply solve one ODE in terms of the complex quantity $\\bm{r}_i=x_i+Iy_i$, which can be handled by numerical solvers. Thus, we simplify the numerical solution from twelve to six equations.\n\\end{itemize}\n\\end{example}\n\\begin{figure}[!!!h!!!tb]\n\\centering\n\\includegraphics[width=\\tp]{../Pictures/Three_body_sim.png}\n\\caption{\\label{Three_body_sim}Two simulations of the three body problem. The green and red trajectories are identically initiated. The blue trajectory is initiated at $(-1,0.01)$ in the left figure and at $(-1,0)$ in the right figure.}\n\\end{figure}\n\\item \\textbf{Hooke's law}\n\n\\textit{The force, $F$, needed to extend or compress a spring by some distance, $x$, scales linearly with respect to that distance,}\n\\COL{\n\\bb\nF=kx.\n\\ee\n\nThe constant of proportionality, $k$, defined by this law is known as the spring constant and is measured in units of Force per distance, \\eg N/m.\n\nDepending on the material Hooke's law only holds true for small extensions and compressions. For example, this law suggests that given enough force a spring can pass through itself. Further, biological materials may not follow the law because they break if stretched too far (\\eg bone), or they may grow, or permanently deform\\footnote{Consider, for example, the ear. Small earrings to not stretch the skin very much and, thus, once the earring is removed the skin can heal. Alternatively, people who use large gauge earrings stretch their ear holes beyond the elastic limit of the skin so that they have a permanent hole. }, thus, reducing the force needed to give the same extension (\\eg skin).\n}\n\n\\end{itemize}\n\\subsubsection{Pendulums}\\label{Pendulums_section}\nIn this section we take an extended look at pendulums depending on Hooke's law and simple Newtonian mechanics. Specifically, we consider a spring, oscillating up and down, and a bob, oscillating side to side \\see{Pendulums}.\n\\begin{figure}[!!!h!!!tb]\n\\centering\n\\subfigure[\\label{Spring}]{\\includegraphics[width=\\ttp]{../Pictures/Spring.png}}\n\\subfigure[\\label{Bob}]{\\includegraphics[width=\\ttp]{../Pictures/Pendulum.png}}\n\\caption{Two types of pendulums: (a) an oscillating spring. (b) a weight on a string.\\label{Pendulums}}\n\\end{figure}\n\n\\COL{Assuming that the spring conforms to Hooke's Law and applying Newton's Second Law of motion the equation of motion for the spring is\n\\bb\nm\\ddot{y}=-ky,\\label{Spring_eqn}\n\\ee\nwhere $y$ is the vertical displacement of the spring, $m$ is the mass attached to the spring and $k$ is the spring constant. The negative sign shows that the force is always directed to the resting position of the spring (here, taken to be the origin). If the negative sign was not there then we would be saying that the pendulums position would grow exponentially with an applied force, which is not very realistic.\n\nThe pendulum bob is slightly more complicated as we have to account for two-dimensional motion. Complicating the matter further is that the pendulum weight is confined to move on the arc of a circle, meaning that problem is easier to solve in polar coordinates.\n\nTo derive the equations of motion we split the component of force acting on the pendulum into components acting along the radial and angular directions of the system, as shown in \\fig{Bob}. Critically, we only need to consider the angular acceleration, which can be derived to be $r\\ddot{\\theta}$. The derivation will be seen on problem sheet two. Using Newton's Second Law again we derive that\n\\bb\nmr\\ddot{\\theta}=-mg\\sin(\\theta).\\label{Bob_eqn}\n\\ee\nOne interesting point we can immediately see from \\eqn{Bob_eqn} is that the mass of the pendulum does not influence the solution of the equation, which can be compared with the dependence of \\eqn{Spring_eqn} on the mass. \n\nEquation \\ref{Bob_eqn} can be solved directly in terms of `elliptic integrals', but this accounts to little more than integrating the equation twice and leaving the equation written in integral form. More insight to the solution can be gained if the angle of oscillation is small. In this case we can linearise the right-hand side of \\eqn{Bob_eqn} by using Taylor series about zero, \\ie $\\sin(\\theta)\\approx\\theta$. Hence, \\eqn{Bob_eqn} can be approximated by\n\\bb\nr\\ddot{\\theta}=-g\\theta\\label{Bob_eqn_approx},\n\\ee\nwhich can be seen to be analogous to \\eqn{Spring_eqn}.\n\nIf the different pendulums are displaced and released from rest then the amount of error introduced into the equation is determined by the initial displacement. \\fig{Different_ICs} compares\\footnote{Comparing $y$ and $\\theta$ is a little dodgy as $y$ is a dimensional length and the $\\theta$ is dimensionless, as we work in radians. However, if this bothers you we can fix this is in either of two ways. Either, we consider $y$ normalised by its natural length (taken here to be of unit length, regardless of the dimensions involved), or, we can consider \\fig{Different_ICs} comparing \\eqn{Bob_eqn} and its approximation in \\eqn{Bob_eqn_approx}.} \\eqns{Spring_eqn}{Bob_eqn} with different initial conditions. Thus, we see that increasing the initial amplitude of the bob pendulum causes the wave length of the oscillation to increase, or frequency of oscillation to decrease.}\n\\begin{figure}[!!!h!!!tb]\n\\centering\n\\subfigure[\\label{IC_0.1}]{\\includegraphics[width=\\ttp]{../Pictures/Comparing_pendulums_IC_1.png}}\n\\subfigure[\\label{IC_1}]{\\includegraphics[width=\\ttp]{../Pictures/Comparing_pendulums_IC_10.png}}\n\\caption{\\label{Different_ICs}Comparing \\eqns{Spring_eqn}{Bob_eqn} with initial conditions (a) $y=0.1=\\theta$ and (b) $y=1=\\theta$. Parameter values $r=g=k=m=1$.}\n\\end{figure}\n\n\\begin{defin}\nAny system defined by an equation of the form\n\\bb\n\\ddot{u}=-k^2u.\\label{SHM}\n\\ee\nis said to under go \\textbf{simple harmonic motion}.\n\\end{defin}\nEquation \\ref{SHM} can be solved to produce the solution\n\\bb\nu=A\\cos(kt)+B\\sin(kt),\n\\ee\nwhere $A$ and $B$ are specified through the initial conditions.\n\n%\\subsection{Euler-Bernoulli beam}\n\\section{Law of Mass Action}\nAll of the above physical laws are very specific in their application. In this section we will learn about a much more general technique that will allow us to build an ODE system out of multiple interacting populations. These populations could represent chemical compounds, humans, cells or animals as well as different states within a population \\ie infected humans and susceptible humans. The law presented in this section is applied whenever the populations of the system are able to: (i) change identities; (ii) create more population members; or (iii) cause populations to decay. Specific examples of each of these interactions are, respectively: (i) susceptible humans becoming infected through interactions with a diseased person; (ii) animals giving birth; (iii) predators eating prey. Note that a change-of-identity interaction can itself be thought as a combination of creation and degradation operations. For example, in the above case of infection a member of the susceptible human population is removed from the system, whilst an infected human is added to the system. Thus, all interactions can be made through combining creation and degradation operations.\n\nWe use chemical reaction notation to specify the outcomes of population interactions. Consider a system composed of $n$ different interacting populations $(u_1,\\dots,u_n)$. We assume that all interactions between the population elements lead to the creation, or destruction, of one (or more) of the $n$ populations. \n\\begin{defin}\nA \\textbf{rate equation} specifies that an interaction involves $a_1$ members of population $u_1$, $a_2$ members of population $u_2$, etc. and produces $b_1$ members of population $u_1$, $b_2$ members of population $u_2$, etc. The equation is written as\n\\bb\na_1u_1+a_2u_2+\\dots+a_nu_n \\stackrel{r}{\\rightarrow} b_1u_1+b_2u_2+\\dots+b_nu_n,\n\\ee\nwhere $r>0$ is the \\textbf{reaction rate}.\n\\end{defin}\nNote that some of the $a_i$ and $b_i$ values can be zero.\n\n\\begin{example}[frametitle=Reaction equation examples]\\label{Reaction equation examples}\n\\begin{itemize}\n\\item \\textbf{Birth}\n\nTwo agents of population $u$ come together to produce a third,\n\\COL{\\bb\n2u\\stackrel{r}{\\rightarrow}3u.\n\\ee}\n\\item \\textbf{Death}\n\nAn agent of population $u$ dies (or is destroyed) due to natural causes,\n\\COL{\n\\bb\nu\\stackrel{r}{\\rightarrow}\\slashed{0}.\n\\ee}\n\n\\item \\textbf{Predation}\n\nA predator population, $v$, converts energy from eating prey, $u$, into offspring,\n\\COL{\n\\bb\nu+v\\stackrel{r}{\\rightarrow}2v.\n\\ee}\n\n\\item \\textbf{Infection}\n\nConsider a population of infected people, $I$, who are able to infect a susceptible population, $S$. Further, over time, the infected people recover and become susceptible again,\n\\COL{\\begin{align}\nI+S&\\stackrel{r_1}{\\rightarrow}2I,\\\\\nI&\\stackrel{r_2}{\\rightarrow}S.\n\\end{align}}\n\\end{itemize}\n\\end{example}\n\nRate equations provide a rigorous way of defining all of the interactions a system is assumed to undergo. However, we still require a method of converting the rate equation into an ODE. This is the power of the Law of Mass Action.\n\\begin{defin}\nThe \\textbf{Law of Mass Action} states that production rate of a reaction is directly proportional to the product of the input population sizes. Specifically, if \n\\bb\na_1u_1+a_2u_2+\\dots+a_nu_n \\stackrel{r}{\\rightarrow} b_1u_1+b_2u_2+\\dots+b_nu_n \\nonumber\n\\ee\nis the reaction of interest then the production rate is proportional to\n\\bb\nru_1^{a_1}u_2^{a_2}\\dots u_n^{a_n}\n\\ee\nand the accompanying ODEs are\n\\begin{align}\n&\\dot{u}_1=(b_1-a_1)ru_1^{a_1}u_2^{a_2}\\dots u_n^{a_n},\\\\\n&\\dot{u}_2=(b_2-a_2)ru_1^{a_1}u_2^{a_2}\\dots u_n^{a_n},\\\\\n&\\vdots\\\\\n&\\dot{u}_n=(b_n-a_n)ru_1^{a_1}u_2^{a_2}\\dots u_n^{a_n}.\n\\end{align}\n\\end{defin}\nNote that in converting from reaction equation to the ODE of $u_i$ we to account for the stoichiometry, \\ie $(a_i-b_i)$. Further, when multiple reactions are considered, the terms arising from the Law of Mass Action are simply added together as independent terms.\n\n\\begin{example}[frametitle=Law of Mass Action examples]\\label{Law of Mass Action examples}\n\\begin{itemize}\n\\item \\textbf{Birth}\n\\COL{\\begin{align}\n2u&\\stackrel{r}{\\rightarrow}3u,\\nonumber\\\\\n\\implies &\\dot{u}=ru^2.\n\\end{align}}\n\\item \\textbf{Death}\n\\COL{\\begin{align}\nu&\\stackrel{r}{\\rightarrow}\\slashed{0},\\nonumber\\\\\n\\implies &\\dot{u}=-ru.\n\\end{align}}\n\n\\item \\textbf{Predation}\n\\COL{\\begin{align}\nu+v&\\stackrel{r}{\\rightarrow}2v,\\nonumber\\\\\n\\implies &\\dot{u}=-ruv,\\\\\n&\\dot{v}=ruv.\n\\end{align}}\n\n\\item \\textbf{Infection}\n\\COL{\\begin{align}\nI+S&\\stackrel{r_1}{\\rightarrow}2I,\\quad I\\stackrel{r_2}{\\rightarrow}S,\\nonumber\\\\\n\\implies &\\dot{S}=-r_1IS+r_2I,\\\\\n&\\dot{I}=r_1IS-r_2I.\n\\end{align}}\n\\end{itemize}\n\\end{example}\n\n\n\n\\begin{example}[frametitle=Zombies]\\label{Zombies}\nHumans, $H$, and zombies, $Z$, interact through the following three interactions \\see{Zombie_picture}:\n\\begin{enumerate}\n\\item humans kill zombies at a rate $a$;\n\\item zombies kill humans at a rate $b$;\n\\item zombies infect humans at a rate $c$.\n\\end{enumerate}\nThe reaction equations for this system are,\n\\COL{\\begin{align}\n&H+Z\\stackrel{a}{\\rightarrow}H;\\\\\n&H+Z\\stackrel{b}{\\rightarrow}Z;\\\\\n&H+Z\\stackrel{c}{\\rightarrow}2Z.\n\\end{align}\n}\\COL{The ODE form of the system is\n\\begin{align}\n&\\dot{H}=-bHZ-cHZ=-\\alpha HZ\\\\\n&\\dot{Z}=-aHZ+cHZ=\\beta HZ.\n\\end{align}\nSince $\\alpha=b+c>0$ the population of $H$ is always decreasing. However, $\\beta=c-a$, which could be either positive or negative. Critically, if $\\beta>0\\implies c>a$ then the zombie population will grow. Alternatively, if $\\beta<0 \\implies c<a$ then  the zombie population decreases. Thus, the survival of the human race all depends on the sign of $c-a$, which, explicitly, is the `net rate increase of zombies', \\ie zombie production minus zombie destruction.}\n\\end{example}\n\\begin{figure}[!!!h!!!tb]\n\\centering\n\\includegraphics[width=\\tp]{../Pictures/Zombies.png}\n\\caption{\\label{Zombie_picture} Possible outcomes of human-zombie interactions.}\n\\end{figure}\n\n\\section{Check list}\nBy the end of this chapter you should be able to:\n\\begin{todolist}\n\\item define all of the constitutive laws;\n\\item solve problems involving Newton's laws, Hooke's law and simple harmonic motion;\n\\item convert a system of population interactions into reaction equations;\n\\item convert reaction equations into ODEs using the Law of Mass Action.\n\\end{todolist}\n\n\n\n\n", "meta": {"hexsha": "4e11d165f1a9abaad71ad01568c470c18c5aa905", "size": 19702, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Latex/How_to_model_a_system.tex", "max_stars_repo_name": "ThomasEWoolley/Modelling_with_Differential_Equations", "max_stars_repo_head_hexsha": "250ed551fa3f09e285ebcd7b2b3d86d01d9ee8e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Latex/How_to_model_a_system.tex", "max_issues_repo_name": "ThomasEWoolley/Modelling_with_Differential_Equations", "max_issues_repo_head_hexsha": "250ed551fa3f09e285ebcd7b2b3d86d01d9ee8e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Latex/How_to_model_a_system.tex", "max_forks_repo_name": "ThomasEWoolley/Modelling_with_Differential_Equations", "max_forks_repo_head_hexsha": "250ed551fa3f09e285ebcd7b2b3d86d01d9ee8e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 62.3481012658, "max_line_length": 1171, "alphanum_fraction": 0.7567252056, "num_tokens": 5656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.3334348807301059}}
{"text": "\n\\chapter{Multimodal Hashing for Aligned Data}\n\\label{chap:smh}\n\n % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %\n\\section{Introduction}\n\nAs of now, almost all existing \\mbox{HFL} methods assume that the data are unimodal, meaning that both the queries and the candidates are of the same modality. They cannot be adapted easily for multimodal search which is often encountered in many multimedia retrieval, image analysis and data mining applications. Take crossmodal multimedia retrieval for example, using an image about a historic event as query, one may want to retrieve relevant text articles that can provide more detailed information about the event. Obviously, existing unimodal methods cannot be applied directly to multimodal similarity search because they assume that all the data are of the same modality.  Designing \\mbox{HFL} methods for multimodal data is thus a very worthwhile direction to pursue.\n\nRecently, \\mbox{Bronstein} \\etal~\\cite{bronstein2010cvpr} proposed a general framework which is referred to as \\textit{multimodal hashing} (\\mbox{MH}). As illustrated in Figure~\\ref{smh:fig:framework} for the bimodal case, \\mbox{MH} functions hash documents of different modalities into a common Hamming space so that fast similarity search can be performed. The key challenge of \\mbox{MH} is to learn effective hash functions for multiple modalities efficiently from the provided information.\n\n\\begin{figure}[htb]\n\\centering\n\\epsfig{figure=fig/mh_illustration, width=0.7\\textwidth}\n\\caption{Illustration of the multimodal hashing framework. Under this framework, similar documents (with bounding boxes of the same color) of different modalities are hashed to nearby points in the Hamming space whereas dissimilar documents (with bounding boxes of different colors) are hashed to points far apart.}\n\\label{smh:fig:framework}\n\\end{figure}\n\nIn this chapter, we study a simple case of multimodal hashing, in which the data from different modalities are aligned. For example, suppose there are two modalities, i.e., image and text, if each image has been aligned with one and only one text article and vice versa, we consider the data to be aligned. The alignment can be determined by applications at hand, e.g, an image and a text can be paired if they are referring to the same object. To learn \\mbox{MH} functions for these data, we first give a basic model which learns hash functions through spectral analysis of the correlation between modalities. Besides the basic method which can only handle vectorial data and is linear, we provide a kernel extension to handle nonvectorial data and incorporate nonlinearity. We further incorporate \\textit{Laplacian} regularization for situations in which side information is also available in the data.\n\n%In the second method, the hash functions are learned by minimizing the multimodal reconstruction error. More specifically, given a collection of pairwise distance within each modality and pairwise relations across modalities, the model aims at minimizing the squared error between the pairwise reconstructive distance (normalized Hamming distance) computed based on the hash codes and the original distance as well as relations.\n\n%The third method is based on latent factor models.\n\nThe rest of this chapter is organized as follows. In Section~\\ref{smh:relatedwork}, we introduce some related work. We then present our model, \\textit{spectral multimodal hashing}, in Section~\\ref{smh:SMH}. Empirical studies conducted on real-world data sets are presented in Section~\\ref{smh:exps}, before we conclude this chapter in Section~\\ref{smh:conclusion}.\n\n % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %\n\\section{Related Work}\n\\label{smh:relatedwork}\n\n\n\n%\\footnote{It is straightforward to extend the problem formulation to more than two modalities, but we focus on the bimodel case in this paper for notational simplicity.}\nUnder the framework of multimodal hashing, we first introduce a recent work called cross modal similarity sensitive hashing (\\mbox{CMSSH})~\\cite{bronstein2010cvpr}, which is, to the best of our knowledge, the first work on multimodal hashing. \n\nSuppose we have two sets of $N$ data points each from two modalities (\\aka feature spaces), $\\mathcal{X} = \\{\\x_i\\in\\mathbb{R}^{D_x}\\}_{i=1}^{N}$ and $ \\mathcal{Y} = \\{\\y_i\\in\\mathbb{R}^{D_y}\\}_{i=1}^{N}$, and the corresponding points $(\\x_i,\\y_i)$ are paired.  For applications studied in this paper, a pair $(\\x_i,\\y_i)$ may represent a multimedia document where $\\x_i$ is an image and $\\y_i$ is the corresponding text article.  For notational convenience, we denote the data sets as matrices $\\X\\in\\mathbb{R}^{D_x\\times N}$ and $\\Y\\in\\mathbb{R}^{D_y\\times N}$ where each column corresponds to a data point. Without loss\nof generality, we assume that $\\X,\\Y$ have been normalized to have zero mean.\n\nCMSSH works as follows: Given a set of similar pairs $\\{(\\x_i,\\y_i)\\}$ and a set of dissimilar pairs $\\{(\\x_j,\\y_j)\\}$, where $\\x\\in\\mathcal{X}$ and $\\y\\in\\mathcal{Y}$ belong to two different modalities, \\mbox{CMSSH} constructs two mapping functions $\\xi:\\mathcal{X}\\rightarrow\\mathbb{H}^{M}$ and $\\eta:\\mathcal{Y}\\rightarrow\\mathbb{H}^{M}$ such that, with high probability, the Hamming distance is small for similar points and large for dissimilar points. Specifically, the $m$th bit of Hamming representation $\\mathbb{H}^{M}$ for $\\mathcal{X}$ and $\\mathcal{Y}$ can be defined by two functions, $\\xi_ {m}$ and $\\eta_{m}$, which are parameterized by projections $p_{m}$ and $q_{m}$, respectively. In their paper, $\\xi_{m}$ and $\\eta_{m}$ are assumed to have the form $\\xi_{m}(\\x) = \\sgn(\\p_{m}^{T}\\x+a_{m})$ and $\\eta_{m}(\\y) =\\sgn(\\q_{m}^{T}\\y+b_{m})$, where $\\p_{m}$ and $\\q_{m}$ are $D_{x}$- and $D_{y}$-dimensional unit vectors, $a_{m}$ and $b_{m}$ are scalars.\n\nA method based on boosting is used to learn the mapping functions.  The algorithm is briefly described here.  First, it initializes the weight of each point pair to $w_{m}(k) = 1/K$ where $K$ is the total number of point pairs. Then, for the ${m}$th bit, it selects $\\xi_{m}$ and $\\eta_{m}$ that maximize the following objective function:\n$$\\sum\\nolimits_{k=1}\\nolimits^{K}\\left(w_{m}(k)s_k\\sgn(\\p_{m}^{T}\\x_k+a_{m})\\sgn(\\q_{m}^{T}\\y_k+b_{m})\\right),\\nonumber$$\nwhere $s_k=1$ if the $k$th pair is a similar pair and $s_k = -1$ otherwise. Since maximizing the objective function above is difficult, the $\\sgn(\\cdot)$ operator and bias terms $a_{m},b_{m}$ are dropped to give the following approximate objective function for maximization:\n$$\n\\sum\\nolimits_{k=1}\\nolimits^{K}w_{m}(k)s_k(\\p_{m}^{T}\\x_k)(\\q_{m}^{T}\\y_k) = \\p_{m}^{T}\\left(\\sum\\nolimits_{k=1}\\nolimits^{K}w_{m}(k)s_k\\x_k\\y_k^{T}\\right)\\q_{m}.\n$$\nIt is easy to see that the $\\p_{m}$ and $\\q_{m}$ that maximize the above objective are the largest left and right singular vectors of $\\C = \\sum_{k=1}^{K}w_{m}(k)s_k\\x_k\\y_k^{T}$. After obtaining $\\p_{m}$ and $\\q_{m}$, the algorithm updates the weights with the update rule $w_{m+1}(k) = w_{m}(k)\\exp(-s_{k}\\xi_{m}(\\x)\\eta_{m}(\\y))$ and then proceeds to learn $\\p_{m+1},\\q_{m+1}$ for the $(m+1)$st bit.\n\nRoughly speaking, \\mbox{CMSSH} tries to map similar points to similar codes and dissimilar points to different codes by exploiting pairwise relations across different modalities. However, it ignores relational information within the same modality which could be very useful for hash function learning~\\cite{weiss2008nips,he2010kdd}. Furthermore, \\mbox{CMSSH} can only handle vectorial data which might not be available in many applications.\n\nRecently, Kumar \\etal extended spectral hashing~\\cite{weiss2008nips} to the multi-view case, leading to a method called cross-view hashing (\\mbox{CVH})~\\cite{kumar2011ijcai}. The objective of \\mbox{CVH} is to minimize the inter-view and intra-view Hamming distances for similar points and maximize those for dissimilar points. The optimization problem is relaxed to several generalized eigenvalue problems which can be solved by off-the-shelf methods.\n\n % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %\n\\section{Spectral Multimodal Hashing}\n\\label{smh:SMH}\n\nIn this section, we first formulate the multimodal hashing problem as a discrete embedding problem and show that it can be approximately solved by spectral decomposition followed by thresholding, which is similar to spectral hashing~\\cite{weiss2008nips} for unimodal data. But unlike spectral hashing, our focus is multimodal data, which are often encountered in a vast range of multimedia applications. Therefore, we call the proposed method \\textit{spectral multimodal hashing} (\\mbox{SMH}). In the following, we first give a basic \\mbox{SMH} model in Section~\\ref{smh:Ssmh:FORMULATION} and then present the other two models as extensions in Section~\\ref{smh:Ssmh:EXT}.\n\n%present a basic multimodal hashing model in Section~\\ref{sec:ssmh:smh}. In Section~\\ref{sec:ssmh:ksmh}, we introduce its kernel extension (\\mbox{KSMH}) which enables us to deal with nonvectorial data as well as nonlinearity.  At last, to exploit side information in the form of labels or pairwise similarity relations between points, we further extend \\mbox{KSMH} by introducing two novel regularizers and propose a regularized \\mbox{KSMH} (\\mbox{RKSMH}) model in Section~\\ref{sec:ssmh:rksmh}.\n\n\n\\subsection{Formulation}\n\\label{smh:Ssmh:FORMULATION}\n\nLet there be two data matrices $\\X^{D_x\\times N}$ and $\\Y^{D_y\\times N}$ from different modalities and the corresponding points $(\\x_i,\\y_i)$ be paired. For applications studied in this paper, a pair $(\\x_i,\\y_i)$ may represent a multimedia document where $\\x_i$ is an image and $\\y_i$ is the corresponding text article. Without loss of generality, we assume that $\\X,\\Y$ have been normalized to have zero mean. We want to learn two sets of hash functions $\\{h_{m}\\}_{m=1}^{M}$ and $\\{g_{m}\\}_{m=1}^{M}$ to give $M$-bit binary codes of $\\X$ and $\\Y$, respectively. \n\nIn this paper, we use thresholded linear projection to define the hash functions. More specifically, the $m$th hash functions for both modalities are defined as follows:\n\\begin{align}\nh_{m}(\\x)=\\sgn(\\x^T\\w_{x}^{(m)}+t_x),\\ \\ %\\mbox{or}\ng_{m}(\\y)=\\sgn(\\y^T\\w_{y}^{(m)}+t_y)\\nonumber,\n\\end{align}\nwhere $\\w_{x}^{(m)}\\in\\mathbb{R}^{D_{x}},\\w_{y}^{(m)}\\in\\mathbb{R}^{D_{y}}$ correspond to two projection directions. The corresponding Hamming bits can be obtained as\n\\begin{align}\n\\label{eqn:bit}\nb_{m}(\\x) = \\frac{1+h_{m}(\\x)}{2}, \\ \\ \n%\\mbox{or}\nb_{m}(\\y)= \\frac{1+g_{m}(\\y)}{2}.\n\\end{align}\n%$(1+h_{m}(\\x))/2$ and $(1+g_{m}(\\y))/2$.\n\nLet the binary vectors $\\h(\\x) = (h_{1}(\\x),\\dots,h_{M}(\\x))^T$ and $\\g(\\y) = (g_{1}(\\y)\\dots,g_{M}(\\y))^T$ denote the projections of points $\\x$ and $\\y$.  \nThe goal of our basic \\mbox{SMH} model is to seek the projections that maximize the correlation between variables in the projected space (Hamming space). Intuitively, two hash codes are more correlated in the Hamming space if the corresponding points in the original space are similar and less correlated otherwise. Moreover, the hash codes should be balanced in the sense that each bit has equal chance of being 1 and $-1$ and the hash bits should be independent of each other~\\cite{weiss2008nips}. As a result, \\mbox{SMH} can be formulated as the following constrained optimization problem:\n\\begin{eqnarray}\n\\max_{\\{\\w_{x}^{(m)},\\w_{y}^{(m)}\\}_{m=1}^{M}}& \\frac{\\mathbb{E}(\\h^{T}\\g)}{\\sqrt{\\mathbb{E}(\\h^{T}\\h)\\mathbb{E}(\\g^{T}\\g)}}\\\\\n\\subto&  \\sum_{i=1}^N h_{m}(\\x_i) =0, \\ m=1,\\dots,M\\nonumber\\\\\n&\\sum_{i=1}^N g_{m}(\\y_i) =0, \\ m=1,\\dots,M\\nonumber\\\\\n&\\sum_{i=1}^{N}h_{m}(\\x_i)h_{n}(\\x_i) =0, \\ \\forall m\\neq n\\nonumber\\\\\n&\\sum_{i=1}^{N}g_{m}(\\y_i)g_{n}(\\y_i) =0, \\ \\forall m\\neq n,\\nonumber\n\\label{eqn:cmh1}\n\\end{eqnarray}\nwhere the expectation is taken with respect to the data distribution in the corresponding feature space. This problem is difficult to solve even without the constraints since the objective function is non-differentiable. Moreover, the balancing constraints make the problem NP-hard~\\cite{weiss2008nips}.\n\nSimilar to~\\cite{wang2010cvpr}, we relax the problem by dropping the $\\sgn(\\cdot)$ operator, the thresholds $ t_x $ and $ t_y $ and the balancing constraints.  Instead, we implicitly enforce the constraints by preprocessing the data through mean-centering.  Hence we arrive at the following optimization problem for one bit:\\footnote{For notational simplicity, we omit the indices of the hash functions.}\n\\begin{eqnarray}\n\\label{eqn:cca1}\n\\max_{\\w_{x},\\w_{y}}& \\mathbb{E}(\\w_{x}^{T}\\x \\, \\w_{y}^{T}\\y)\\\\\n\\subto&  \\mathbb{E}((\\w_{x}^{T}\\x)^2)=1, \\, \\mathbb{E}((\\w_{y}^{T}\\y)^2)=1,\\nonumber\n\\end{eqnarray}\nwhich in fact is the standard form of \\emph{canonical correlation analysis} (\\mbox{CCA})~\\cite{hotelling1936cca}. Approximating the expectation by empirical expectation, we rewrite Problem~(\\ref{eqn:cca1}) as follows:\n\\begin{eqnarray}\n\\label{eqn:csmh:optprob}\n\\max_{\\w_{x},\\w_{y}}& \\w_{x}\\C_{xy}\\w_{y}\\\\\n\\subto&  \\w_{x}\\C_{xx}\\w_{x}=1, \\, \\w_{y}\\C_{yy}\\w_{y}=1, \\nonumber\n\\end{eqnarray}\nwhere $\\C_{xy} = \\frac{1}{N}\\X\\Y^{T}$, $\\C_{xx} = \\frac{1}{N}\\X\\X^{T}$, and $\\C_{yy} = \\frac{1}{N}\\Y\\Y^{T}$.\n\nThis problem is equivalent to the following generalized eigenvalue problem:\n\\begin{align}\n\\label{eqn:csmh:wx}\n\\C_{xy}\\C_{yy}^{-1}\\C_{xy}^{T}\\w_{x} = \\lambda^2\\C_{xx}\\w_{x}.\n\\end{align}\nThe solution $\\w_{x}$ is the eigenvector that corresponds to the largest eigenvalue.  With the $\\w_{x}$ thus computed, we can compute $\\w_{y}$ as\n\\begin{align}\n\\label{eqn:csmh:wy}\n\\w_{y} = \\frac{1}{\\lambda}\\C_{yy}^{-1}\\C_{yx}\\w_{x}.\n\\end{align}\n\nWith projection vectors $ \\w_x $ and $ \\w_y $ computed, one common approach of getting the binary codes is simply using the $ \\sgn(\\cdot) $ operator. However, this may separate the points located near the boundary, impairing the model especially when the data distribution is dense in that area. To overcome this shortcoming, we use two thresholds, a fixed threshold of zero and a learned threshold, to get the binary codes.\n\nThe learning-based threshold can be obtained as follows. For each projection, we first divide the range of projected values into $ N_b $ bins and then calculate the relative data density of each bin as $ P_{t} = N_t/N, t=1,\\dots,N_b, $ with $ N_t $ stands for the number of points in the $ t $th bin. The cost of cutting the $ t $th bin is defined as follows,\n\\begin{align}\nC_t = \\left(\\sum\\nolimits_{\\hat{t}=1}^{t-1}P_{\\hat{t}}\\right)^2 +   \\left(\\sum\\nolimits_{\\hat{t}=t+1}^{N_b}P_{\\hat{t}}\\right)^2 + P_t,\\nonumber\n\\end{align}\nwhich measures the relative density of the $ t $th bin and the relative density of its both sides. Intuitively, if $ C_{t} $ is small, a boundary cutting through the $ t $th bin will separate a sparse area and make the points located evenly at its both sides. Actually, $ C_t $ is an adapted surrogate of the average size of a proper hash bucket which should be as small as possible for nearest neighbor search~\\cite{cayton2007nips}. We then use the center of the bin with the smallest $ C_t $ as the threshold and denote it as $ t_x $ or $ t_y $.\n\nNow we are ready to generate binary bits with 0 and $ t_x $. For example, given $ \\w_x $ and $ \\x^{*} $, we have\n\\begin{align}\n\\label{eqn:csmh:hg1}\nh_1(\\x^{*}) = \\sgn(\\w_{x}^{T}\\x^{*}), \\ \\ h_2(\\x^{*}) = \\sgn(\\w_{x}^{T}\\x^{*}-t_x),\n\\end{align}\nand given $ \\w_y $ and $ \\y^{*} $, we have\n\\begin{align}\n\\label{eqn:csmh:hg2}\ng_1(\\y^{*}) = \\sgn(\\w_{y}^{T}\\y^{*}), \\ \\ g_2(\\y^{*}) = \\sgn(\\w_{y}^{T}\\y^{*}-t_y).\n\\end{align}\n\n\n\n%We adopt a alternating algorithm to find the best threshold. First initialize $t_y=0$, we change the value of $t_x$ gradually from the centers.\n%\n%We first sort the values $\\w_x^T\\x $, then we get a vector of threshold values $[\\w_x^T\\x_1-0.1,(\\w_x^T\\x_1+\\w_x^T\\x_2)/2, (\\w_x^T\\x_2+\\w_x^T\\x_3)/2, \\dots, (\\w_x^T\\x_{n-1}+\\w_x^T\\x_n)/2, \\w_x^T\\x_n+0.001]$. For the first threshold, the initial precision is evaluated. For a new threshold $t_x^{*}$, only check those affected point pairs with one end point $\\x_{*}$, the precision can be changed to $\\frac{total \\# of point pairs * previous precision +2(\\# of correct pair-\\# of incorrect pair)}{total \\# of point pairs}$. Given each point is involved in only a small number of points, the algorithm can be very efficient with complexity $O(Nd+P)$, where $P$ is the total number of pairs and $d$ is the average number of pairs a point is involved in.\n\n%Another extension is to generate multiple bits using one eigenvector. One bit uses threshold 0 and the other uses the threshold learned. This combination is also possible and might be useful.\n%\n%CCA may also depend on the first few eigenvectors. Let's try.\n%\n%We can compare these two approaches to see which is better.\n\n\n\n\n\n\nThe basic \\mbox{SMH} algorithm is summarized in Algorithm~\\ref{algorithm:cmh}.\n\n\\begin{algorithm}[ht]\n\\caption{Algorithm of \\mbox{SMH}}\n\\label{algorithm:cmh}\n\\begin{algorithmic}\n\\STATE {\\bfseries Input:} \\\\\n$\\X$, $\\Y$ -- data matrices\n\\\\ $M$ -- number of hash functions\n\\STATE {\\bfseries Procedure:}\n\\STATE Compute $\\C_{xx},\\C_{xy},\\C_{yy}$.\n\\STATE Obtain $M$ eigenvectors corresponding to the $M$ largest eigenvalues of the generalized eigenvalue problem~(\\ref{eqn:csmh:wx}) as $\\w_{x}$'s.\n \\STATE Obtain the corresponding $\\w_{y}$'s using Equation~(\\ref{eqn:csmh:wy}).\n \\STATE Learn thresholds $ t_x $ and $ t_y $.\n \\STATE Obtain the hash codes of points $\\x^{*}$ and $\\y^{*}$ using Equations~(\\ref{eqn:csmh:hg1}),~(\\ref{eqn:csmh:hg2}) \\& (\\ref{eqn:bit}).\n\n\n\\end{algorithmic}\n\\end{algorithm}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Extensions}\n\\label{smh:Ssmh:EXT}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Kernel \\mbox{SMH}}\n\\label{smh:Ssmh:EXT:KSMH}\n\nThe \\mbox{SMH} model presented in the previous subsection has two limitations.  First, it can only handle vectorial data.  Second, the projection before thresholding is linear.  In this subsection, we propose a kernel extension of \\mbox{SMH}, abbreviated as \\mbox{KSMH} thereafter, to overcome these limitations. % by taking the kernel approach~\\cite{shawe2004book}.\n\nLet $\\mathcal{K}(\\cdot,\\cdot)$ be a valid kernel function and $\\phi(\\cdot)$ be the corresponding function that maps data points in the original input space to the kernel-induced feature space. In the sequel, we use $\\Ph(\\X) = [\\phi(\\x_1),\\dots,\\phi(\\x_{N})]$ and $\\Ph(\\Y) = [\\phi(\\y_1),\\dots,\\phi(\\y_{N})]$ to denote the data matrices in the kernel-induced feature space.\n\n%Suppose we have a set of $P$ landmark points\\footnote{*** You should explain what landmark points are and why they are needed.} $\\hat{\\mathcal{X}} \\subset\\mathcal{X}$, which can also be represented by $\\hat{\\X}$ in the original input space and $\\Ph(\\hat{\\X})$ in the kernel-induced feature space.  For the other modality, we define $\\hat{\\mathcal{Y}},\\hat{\\Y}$ and $\\Ph(\\hat{\\Y})$ similarly.\n\nTaking the kernel approach~\\cite{scholkopf2001colt}\\cite{kulis2009nips}, we represent $\\w_{x}$ and $\\w_{y}$ as linear combinations of two groups of landmark points in the kernel-induced feature space, i.e.,\n\\begin{align}\n\\w_{x} = \\Ph(\\hat{\\X})^{T}\\alpp, \\ \\\n\\w_{y} = \\Ph(\\hat{\\Y})^{T}\\bett,\\nonumber\n\\end{align}\nwhere $ \\hat{\\X}\\in\\mathbb{R}^{D_x\\times P}$ and $\\hat{\\X}\\in\\mathbb{R}^{D_x\\times P} $ are two landmark sets, in which the points are randomly chosen from $ \\X $ and $ \\Y  $, respectively. We note that although the landmark points should be sampled from the corresponding data distribution and be sufficiently representative, it is enough in practice to select the landmarks randomly from the training set. $\\alpp\\in\\mathbb{R}^{P\\times 1},\\bett\\in\\mathbb{R}^{P\\times 1}$ are combination coefficients. To reduce the computational cost, $P$ is usually a small number compared to $N$.\n\nThe objective function of Problem~(\\ref{eqn:cmh1}) can now be rewritten as\n\\begin{align}\n\\frac{\\alpp^{T}\\K_{\\hat{x}x}\\K_{y\\hat{y}}\\bett}{\\sqrt{\\alpp^{T}\\K_{\\hat{x}x}\\K_{x\\hat{x}}\\alpp\\bett^{T}\\K_{\\hat{y}y}\\K_{y\\hat{y}}\\bett}},\n\\label{eqn:kcsmh:obj1}\n\\end{align}\nwhere $\\K_{\\hat{x}x} = \\K_{x\\hat{x}}^{T} = \\Ph(\\hat{\\X})^{T}\\Ph(\\X)$ and $\\K_{\\hat{y}y} = \\K_{y\\hat{y}}^{T} = \\Ph(\\hat{\\Y})^{T}\\Ph(\\Y)$.\n\nSince the objective function above can lead to degenerate solutions as discussed in~\\cite{hardoon2004nc}, we penalize the norms of $\\w_{x}$ and $\\w_{y}$ in the denominator of (\\ref{eqn:kcsmh:obj1}) and arrive at the following alternative form:\n\\begin{align}\n\\frac{\\alpp^{T}\\K_{\\hat{x}x}\\K_{y\\hat{y}}\\bett}{\\sqrt{\\alpp^{T}(\\K_{\\hat{x}x}\\K_{x\\hat{x}}+\\kappa\\K_{\\hat{x}\\hat{x}})\\alpp\\bett^{T}(\\K_{\\hat{y}y}\\K_{y\\hat{y}}+\\kappa\\K_{\\hat{y}\\hat{y}})\\bett}},\n\\label{eqn:kcsmh:obj2}\n\\end{align}\nwhere $\\K_{\\hat{x}\\hat{x}} = \\Ph(\\hat{\\X})^{T}\\Ph(\\hat{\\X}),\\K_{\\hat{y}y}= \\Ph(\\hat{\\Y})^{T}\\Ph(\\hat{\\Y})$ and $\\kappa>0$ is a regularization parameter.\n%\n%We are now ready to formulate \\mbox{KSMH} as the following constrained optimization problem:\n%\\begin{eqnarray}\n%\\max_{\\alpp,\\bett}& \\alpp^{T}\\K_{\\hat{x}x}\\K_{y\\hat{y}}\\bett\\\\\n%\\subto&  \\alpp^{T}(\\K_{\\hat{x}x}\\K_{x\\hat{x}}+\\kappa\\K_{\\hat{x}\\hat{x}})\\alpp=1\\nonumber\\\\\n%&  \\bett^{T}(\\K_{\\hat{y}y}\\K_{y\\hat{y}}+\\kappa\\K_{\\hat{y}\\hat{y}})\\bett=1.\\nonumber\n%\\end{eqnarray}\n\nAfter some simple relaxations and manipulations similar to \\mbox{SMH}, $\\alpp$ can be obtained by solving the following generalized eigenvalue problem:\n\\begin{align}\n\\label{eqn:kcsmh:alpha}\n\\K_{\\hat{x}x}\\K_{y\\hat{y}}(\\K_{\\hat{y}y}\\K_{y\\hat{y}} + \\kappa\\K_{\\hat{y}\\hat{y}})^{-1}\\K_{\\hat{y}y}\\K_{x\\hat{x}}\\alpp =\\lambda^2(\\K_{\\hat{x}x}\\K_{x\\hat{x}} + \\kappa\\K_{\\hat{x}\\hat{x}})\\alpp.\n\\end{align}\nAfter obtaining $\\alpp$, we compute\n\\begin{align}\n\\label{eqn:kcsmh:beta}\n\\bett =\\frac{1}{\\lambda} (\\K_{\\hat{y}y}\\K_{y\\hat{y}}+\\kappa\\K_{\\hat{y}\\hat{y}})^{-1}\\K_{\\hat{y}y}\\K_{x\\hat{x}}\\alpp.\n\\end{align}\n\nWe can also learn the thresholds $ t_x $ and $ t_y $ using the same approach presented in the last section.  For any new point $\\x^{*}$, two bits of binary code can be obtained as\n\\begin{align}\n\\label{eqn:kcsmh:hg1}\nh_1(\\x^{*}) = \\sgn(\\k_{x^{*}}^{T}\\alpp), \\ \\ h_2(\\x^{*}) = \\sgn(\\k_{x^{*}}^{T}\\alpp-t_x)\n\\end{align}\nand for $ \\y^{*} $, we have\n\\begin{align}\n\\label{eqn:kcsmh:hg2}\ng_1(\\y^{*}) = \\sgn(\\k_{y^{*}}^{T}\\bett), \\ \\ g_2(\\y^{*}) = \\sgn(\\k_{y^{*}}^{T}\\bett-t_y),\n\\end{align}\nwhere $\\k_{y^{*}} = \\Ph(\\hat{\\X})^{T}\\phi(\\x^{*})$ and $\\k_{y^{*}} = \\Ph(\\hat{\\Y})^{T}\\phi(\\y^{*})$.\n\nThe algorithm of \\mbox{KSMH} is summarized in Algorithm~\\ref{algorithm:kcmh}.\n\n\\begin{algorithm}[ht]\n\\caption{Algorithm of \\mbox{KSMH}}\n\\label{algorithm:kcmh}\n\\begin{algorithmic}\n\\STATE {\\bfseries Input:} \\\\\n$\\X$, $\\Y$ -- data matrices\n\\\\$\\mathcal{K}(\\cdot,\\cdot)$ -- kernel function\n\\\\ $M$ -- number of hash functions\n\\\\ $\\kappa$ -- regularization parameter\n\\STATE {\\bfseries Procedure:} \\\\\n\n   \\STATE Compute $\\K_{\\hat{x}x}, \\K_{\\hat{y}y}, \\K_{\\hat{x}\\hat{x}}, \\K_{\\hat{y}\\hat{y}}$.\n   \\STATE Obtain $M$ eigenvectors corresponding to the $M$ largest eigenvalues of the generalized \\STATE eigenvalue problem~(\\ref{eqn:kcsmh:alpha}) as $\\alpp$'s.\n   \\STATE Obtain the corresponding $\\bett$'s using Equation~(\\ref{eqn:kcsmh:beta}).\n   \\STATE Learn thresholds $ t_x $ and $ t_y $.\n   \\STATE Obtain the hash codes of points $\\x^{*}$ and $\\y^{*}$ using Equations~(\\ref{eqn:kcsmh:hg1}), (\\ref{eqn:kcsmh:hg2}) \\& (\\ref{eqn:bit}).\n\n\\end{algorithmic}\n\n\\end{algorithm}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Regularized kernel \\mbox{SMH}}\n\\label{smh:Ssmh:EXT:RKSMH}\n\nBoth \\mbox{SMH} and \\mbox{KSMH} proposed above aim at maximizing the correlation between variables in different modalities while ignoring the relational information within each modularity.  Moreover, it is unclear how to make use of side information such as labels in the two models in case such information is available in the data.\n\nInspired by~\\cite{blaschko2008ecml}, we further extend \\mbox{KSMH} by adding two \\textit{Laplacian} regularization terms to the objective~(\\ref{eqn:kcsmh:obj2}). We name this new model \\mbox{RKSMH}, whose objective is:\n\\begin{align}\n\\frac{\\alpp^{T}\\K_{\\hat{x}x}\\K_{y\\hat{y}}\\bett}{\\sqrt{\\alpp^{T}(\\K_{\\hat{x}x}\\R_{x}\\K_{x\\hat{x}}+\\kappa\\K_{\\hat{x}\\hat{x}})\\alpp\\bett^{T}(\\K_{\\hat{y}y}\\R_{y}\\K_{y\\hat{y}}+\\kappa\\K_{\\hat{y}\\hat{y}})\\bett}},\\nonumber\n\\end{align}\nwhere $\\R_{x} = (\\I+\\gamma\\mathcal{L}_{x}),\\R_{y} = (\\I+\\gamma\\mathcal{L}_{y})$, $\\gamma>0$ is a parameter controlling the impact of regularization, and $\\mathcal{L}_{x},\\mathcal{L}_{y}$ are graph \\textit{Laplacians}~\\cite{chung1997spectral} that incorporate some information about $\\X$ and $\\Y$, respectively. We note that the \\textit{Laplacian} matrix is defined as $\\mathcal{L} = \\D-\\W$, where $\\D$ is a diagonal matrix with $D(i,i) = \\sum_{j=1}^{N}W(i,j)$.\\footnote{To avoid being cluttered, we omit the subscripts here.} We note that the \\textit{Laplacian} matrix can be computed efficiently by using an anchor graph~\\cite{liu2010icml}.\n\nThe regularizers $ \\R_{x} $ and $ \\R_{y} $ not only can exploit relational information of a single modality but can also incorporate into the model side information when it is available. For example, $\\mathcal{L}_{x}$ can incorporate structural or geometric information in the input space $ \\X $ by defining $\\W_{x}$ as\n\\begin{align}\n\\label{eqn:wfeature}\nW_{x}(i,j) = \\left\\{ \\begin{array}{ll}\n\\exp\\left(-\\frac{d^2(\\x_i,\\x_j)}{\\sigma^2}\\right) & \\textrm{if $\\x_i,\\x_j$ are neighbors}\\\\\n0 & \\textrm{otherwise}\n\\end{array} \\right.\n\\end{align}\nwhere $d(\\cdot,\\cdot)$ is the Euclidean distance between two points and $\\sigma$ is a user-specified width parameter. In our experiments, we regard two points as neighbors if either one is among the $K$ nearest neighbors of the other one in the feature space. We call this type of \\textit{Laplacian} the feature-based \\textit{Laplacian}.\n\n\n$\\mathcal{L}_{x}$ can also be used to incorporate side information such as labels by defining $\\W_{x}$ as\n\\begin{align}\n\\label{eqn:wlabel}\nW_{x}(i,j) = \\left\\{ \\begin{array}{ll}\n1 & \\textrm{if $\\x_i$ and $\\x_j$ have the same label}\\\\\n0 & \\textrm{otherwise}\n\\end{array} \\right.\n\\end{align}\nWe call this \\textit{Laplacian} the label-based \\textit{Laplacian} thereafter. Note that $\\mathcal{L}_{y}$ can be defined similarly.\n\nIn \\mbox{RKSMH}, $\\alpp$ can be obtained by solving the following generalized eigenvalue problem:\n\\begin{align}\n\\label{eqn:lrkcsmh:alpha}\n\\K_{\\hat{x}x}\\K_{y\\hat{y}}(\\K_{\\hat{y}y}\\R_{y}\\K_{y\\hat{y}} + \\kappa\\K_{\\hat{y}\\hat{y}})^{-1}\\K_{\\hat{y}y}\\K_{x\\hat{x}}\\alpp= \\lambda^2(\\K_{\\hat{x}x}\\R_{x}\\K_{x\\hat{x}} + \\kappa\\K_{\\hat{x}\\hat{x}})\\alpp,\n\\end{align}\nand $\\bett$ can be computed as\n\\begin{align}\n\\label{eqn:lrkcsmh:beta}\n\\bett =\\frac{1}{\\lambda} (\\K_{\\hat{y}y}\\R_{y}\\K_{y\\hat{y}}+\\kappa\\K_{\\hat{y}\\hat{y}})^{-1}\\K_{\\hat{y}y}\\K_{x\\hat{x}}\\alpp.\n\\end{align}\n\n\nThe thresholding procedure of \\mbox{RKSMH} is the same as those of \\mbox{KSMH} and \\mbox{SMH}. The algorithm is summarized in Algorithm~\\ref{algorithm:lrkcmh}.\n\n\\begin{algorithm}[htb]\n\\caption{Algorithm of \\mbox{RKSMH}}\n\\label{algorithm:lrkcmh}\n\\begin{algorithmic}\n%\\SetKwInOut{Input}{Input}\\SetKwInOut{Output}{Output}\n\\STATE {\\bfseries Input:} \\\\\n$\\X$, $\\Y$ -- data matrices\n\\\\$\\mathcal{K}(\\cdot,\\cdot)$ -- kernel function\n\\\\ $M$ -- number of hash functions\n\\\\ $\\kappa,\\gamma$ -- regularization parameters\n\\STATE {\\bfseries Procedure:} \\\\\n\n  \\STATE Compute $\\K_{\\hat{x}x}, \\K_{\\hat{y}y}, \\K_{\\hat{x}\\hat{x}}, \\K_{\\hat{y}\\hat{y}}, \\R_{x},\\R_{y}$.\n   \\STATE Obtain $M$ eigenvectors corresponding to the $M$ largest eigenvalues of the generalized eigenvalue problem~(\\ref{eqn:lrkcsmh:alpha}) as $\\alpp$'s.\n   \\STATE Obtain the corresponding $\\bett$'s using Equation~(\\ref{eqn:lrkcsmh:beta}).\n   \\STATE Learn thresholds $ t_x $ and $ t_y $.\n  \\STATE  Obtain the hash codes of points $\\x^{*}$ and $\\y^{*}$ using Equations~(\\ref{eqn:kcsmh:hg1}), (\\ref{eqn:kcsmh:hg2}) \\& (\\ref{eqn:bit}).\n\\end{algorithmic}\n\\end{algorithm}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Beyond two modalities}\n\\label{smh:Ssmh:EXT:BEYOND}\n\nOur \\mbox{SMH} models can easily accommodate more than two modalities, using the corresponding extensions of \\mbox{CCA} and \\mbox{KCCA}~\\cite{hardoon2004nc}\\cite{blaschko2008ecml}.\n\nTaking \\mbox{SMH} for example, suppose we have $ K $ modalities and want to learn $ K $ projection vectors $ \\{\\w_1,\\cdots,\\w_K\\}$, we solve the following generalized eigenvalue problem:\n\\begin{align}\n\\begin{pmatrix}\n\\C_{11} & \\cdots &\\C_{1K} \\\\\n\\vdots & \\ddots &\\vdots \\\\\n\\C_{K1}&\\cdots &\\C_{KK} \\end{pmatrix}\\begin{pmatrix}\\w_1\\\\\\vdots\\\\\\w_K\\end{pmatrix} = \\lambda  \\begin{pmatrix}\n\\C_{11} & \\cdots &\\0 \\\\\n\\vdots & \\ddots &\\vdots \\\\\n\\0&\\cdots &\\C_{KK} \\end{pmatrix}\\begin{pmatrix}\n\\w_{1}\\\\\n\\vdots \\\\\n\\w_{K}\\end{pmatrix},\\nonumber\n\\end{align} \nwhere $ \\C_{ij} $ is the covariance matrix between modalities $ i $ and $ j $, and $  \\C_{ij} = \\C_{ji}^T  $.\n\nFor \\mbox{KSMH}, we select landmark points from each modality and index them with $ \\{\\hat{1},\\cdots,\\hat{K}\\} $. The corresponding eigenvalue problem, for projection vectors $ \\{\\alpha_1,\\cdots,\\alpha_K\\} $, is:\n\\begin{align}\\footnotesize\n\\begin{pmatrix}\n\\K_{\\hat{1}1}\\K_{1\\hat{1}} & \\cdots &\\K_{\\hat{1}1}\\K_{K\\hat{K}} \\\\\n\\vdots & \\ddots &\\vdots \\\\\n\\K_{\\hat{K}K}\\K_{1\\hat{1}}&\\cdots &\\K_{\\hat{K}K}\\K_{K\\hat{K}} \\end{pmatrix}\\begin{pmatrix}\\alpha_1\\\\\\vdots\\\\\\alpha_K\\end{pmatrix} =\n\\lambda  \\begin{pmatrix}\n\\K_{\\hat{1}1}\\K_{1\\hat{1}}+\\kappa\\K_{\\hat{1}\\hat{1}} & \\cdots &\\0 \\\\\n\\vdots & \\ddots &\\vdots \\\\\n\\0&\\cdots &\\K_{\\hat{K}K}\\K_{K\\hat{K}}+\\kappa\\K_{\\hat{K}\\hat{K}} \\end{pmatrix}\\begin{pmatrix}\n\\alpha_{1}\\\\\n\\vdots \\\\\n\\alpha_{K}\\end{pmatrix},\\nonumber\n\\end{align} \nwhere $ \\K_{\\hat{i}i} $ is the kernel matrix between the landmark points and the training data points and $ \\K_{\\hat{i}\\hat{i}} $ is the kernel matrix for the landmark points, for the $ i $th modality. The generalized eigenvalue problems for \\mbox{RKSMH} are similar, and we omit them here due to space limitations.\n\nWith the projection vectors learned, we can apply the same thresholding process to each modality and get the binary codes easily.\n\n%For multiple views, we should talk about it here. At least two ways.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\\section{Multimodal Binary Reconstructive Embedding}\n%\\label{smh:MBRE}\n%The \\mbox{SMH} model introduced in last subsection requires the data points in different modalities to be paired, which might not be the case in some applications. In this section, we extend a unimodal hashing method \\mbox{BRE} to multimodal settings to given a novel method called \\textit{multimodal binary reconstructive embedding} (\\mbox{MBRE}), the inputs of which is pairwise distance or relations.\n%\n%%+++++++++++++++++++++++++++++++++++++++++++++++++++++++\n%\\subsection{Model}\n%Let $M$ be the number of hash functions (\\aka code length), $N$ be the number of data points, and $Q$ be the number of landmark points. Given two kinds of data points $\\mathcal{X}$ and $\\mathcal{Y}$,\\footnote{Without loss of generality, here we assume there are two modalities and each modality has $N$ points.} similar to \\mbox{BRE}, we define hash functions \\wrt the $m$th bit for $\\x\\in\\mathcal{X}$ and $\\y\\in\\mathcal{Y}$, respectively, as follows,\n%\\begin{align}\n%h_{m}(\\x) = \\frac{1+\\sgn\\left(\\sum_{q=1}^{Q}W_{x}(m,q)\\kappa(\\x_q,\\x)\\right)}{2} \\ \\ \\mbox{or} \\ \\ g_{m}(\\x) = \\frac{1+\\sgn\\left(\\sum_{q=1}^{Q}W_{y}(m,q)\\kappa(\\y_q,\\y)\\right)}{2}\\nonumber,\n%\\end{align}\n%where $\\W_{x}$ and $\\W_{y}$ are two $M\\times Q$ projection matrices, $\\{\\x_q\\}_{q=1}^{Q}\\subset\\mathcal{X}$ and $\\{\\y_q\\}_{q=1}^{Q}\\subset\\mathcal{Y}$ are landmark points for $\\mathcal{X}$ and $\\mathcal{Y}$ respectively, and $\\kappa(\\cdot,\\cdot)$ is a kernel function. Note that defining hash functions this way is very common in kernel methods and brings us flexibility to work on a wide variety of data types. Therefore, given two points $\\x\\in\\mathcal{X}$ and $\\y\\in\\mathcal{Y}$, we denote their corresponding binary representations as $\\tilde{\\x}$ and $\\tilde{\\y}$ such that their $m$th bits can be evaluated by $\\tilde{x}(m) = h_{m}(\\x)$ and $\\tilde{y}(m) = g_{m}(\\y)$.\n%\n%Since in many real-world applications, it is much easier to obtain binary pairwise relationships rather than real-valued distance, here we simply define the \\textit{original} distance between two points $\\x_i,\\x_j$ as follows,\n%\\begin{align}\n%d(\\x_i,\\x_j) = \\left\\{ \\begin{array}{ll}\n%0 & \\textrm{if $\\x_i$ and $\\x_j$ belong to the same class};\\\\\n%1 & \\textrm{otherwise},\n%\\end{array} \\right. \\nonumber%\\\\\n%%d(\\y_k,\\y_l) = \\left\\{ \\begin{array}{ll}\n%%0 & \\textrm{if $\\y_k$ and $\\y_l$ are similar};\\\\\n%%1 & \\textrm{if $\\y_k$ and $\\y_l$ are dissimilar},\n%%\\end{array} \\right. \\nonumber\\\\\n%%%d(\\x_i,\\x_j) = \\frac{1}{2}\\|\\x_i-\\x_j\\|^{2}_2, &\\tilde{d}(\\x_i,\\x_j) = \\frac{1}{M}\\|\\tilde{\\x}_i-\\tilde{\\x}_j\\|^{2}_2,\\nonumber\\\\\n%%%d(\\y_k,\\y_l) = \\frac{1}{2}\\|\\y_k-\\y_l\\|^{2}_2, &\\tilde{d}(\\y_k,\\y_l) = \\frac{1}{M}\\|\\tilde{\\y}_k-\\tilde{\\y}_l\\|^{2}_2,\\nonumber\n%%d(\\x_i,\\y_k) = \\left\\{ \\begin{array}{ll}\n%%0 & \\textrm{if $\\x_i$ and $\\y_k$ are similar};\\\\\n%%1 & \\textrm{if $\\x_i$ and $\\y_k$ are dissimilar},\n%%\\end{array} \\right. \\nonumber\n%\\end{align}\n%$d(\\y_k,\\y_l)$ and $d(\\x_i,\\y_k)$ are defined similarly. Note that using binary values here to define distance is just a special case, and our model can accept other definitions of distance.\n%\n%We define the \\textit{reconstructive} distance between two points as follows,\n%\\begin{align}\n%\\tilde{d}(\\x_i,\\x_j) = \\frac{1}{M}\\|\\tilde{\\x}_i-\\tilde{\\x}_j\\|^{2}_2, \\ \\\n%\\tilde{d}(\\y_k,\\y_l) = \\frac{1}{M}\\|\\tilde{\\y}_k-\\tilde{\\y}_l\\|^{2}_2, \\ \\\n%\\tilde{d}(\\x_i,\\y_k) = \\frac{1}{M}\\|\\tilde{\\x}_i-\\tilde{\\y}_k\\|^{2}_2.\\nonumber\n%\\end{align}\n%\n%Intuitively speaking, we try to find $\\W_{x},\\W_{y}$ such that the reconstructive distance are close to the original distance. More specifically, the goal of \\mbox{MBRE} is to minimize the following objective,\n%\\begin{align}\n%\\mathcal{O}\\left(\\W_{x},\\W_{y}\\right)&=\\sum_{(\\x_i,\\x_j)\\in\\mathcal{N}_{x}}\\left(d(\\x_i,\\x_j)-\\tilde{d}(\\x_i,\\x_j)\\right)^{2}+\\sum_{(\\y_k,\\y_l)\\in\\mathcal{N}_{y}}\\left(d(\\y_k,\\y_l)-\\tilde{d}(\\y_k,\\y_l)\\right)^{2}\\nonumber\\\\\n%&+\\sum_{(\\x_i,\\y_k)\\in\\mathcal{N}_{xy}}\\left(d(\\x_i,\\y_k)-\\tilde{d}(\\x_i,\\y_k)\\right)^{2},\n%\\label{eqn:totalobj}\n%\\end{align}\n%where $\\mathcal{N}_{x}$ is a set of point pairs in $\\mathcal{X}$, $\\mathcal{N}_{y}$ is a set of point pairs in $\\mathcal{Y}$ and $\\mathcal{N}_{xy}$ is a set of pairs with one point in $\\mathcal{X}$ and the other point in $\\mathcal{Y}$. In our experiments, there are $k$ pairs for each point and so each set has size upper-bounded by $Nk$.\\footnote{The total number of pairs might be smaller than $Nk$, since there might be some duplicate pairs. Besides, different sets may have different $k$ values.}  We note that the objective function of \\mbox{BRE} is just the first term of that in Eqn.~(\\ref{eqn:totalobj}).\n%\n%\n%%######################################\n%\\subsection{Algorithm}\n%To solve the above optimization problem, we adapt the coordinate descent algorithm used in~\\cite{kulis2009nips} for our model. The major difference between the adapted algorithm and the original one is threefold: 1) we update all parameters sequentially but the original algorithm randomly updates only a small subset of them;\\footnote{Note that original algorithm is slow to converge because of random update.} 2) we use a warm-start approach to improve the convergence rate and obtain better performance; 3) our algorithm involves more updating terms.\n%\n%We first introduce Lemma~\\ref{lemma:updatex} as follows.\n%\\begin{mylem}\n%Let $\\bar{D}_{x}(i,j)=d(\\x_i,\\x_j)-\\tilde{d}(\\x_i,\\x_j),\\bar{D}_{xy}(i,k)=d(\\x_i,\\y_k)-\\tilde{d}(\\x_i,\\y_k)$. Consider updating one hash function of $\\mathcal{X}$ from $h_{o}$ to $h_{n}$, and let $\\h_{o}$ and $\\h_{n}$ be the $N\\times 1$ vectors obtained by applying the old and new hash functions to each data point in $\\mathcal{X}$. Furthermore, we denote the hash function of $\\mathcal{Y}$ with the same bit index as $g$ and the corresponding binary vector as $\\g$. Then the objective function of using $h_{n}$ instead of $h_{o}$ can be expressed as\n%\\begin{align}\n%\\mathcal{O} &= \\sum_{(\\x_i,\\x_j)\\in\\mathcal{N}_{x}}\\left(\\bar{D}_{x}(i,j)+\\frac{1}{M}(h_{o}(i)-h_{o}(j))^2-\\frac{1}{M}(h_{n}(i)-h_{n}(j))^2\\right)^2\\nonumber\\\\\n%&+ \\sum_{(\\x_i,\\y_k)\\in\\mathcal{N}_{xy}}\\left(\\bar{D}_{xy}(i,k)+\\frac{1-2g(k)}{M}(h_{o}(i)-h_{n}(i))\\right)^2+C,\n%\\end{align}\n%where $C$ is a constant independent of $h_{o}$ and $h_{n}$.\n%\\label{lemma:updatex}\n%\\end{mylem}\n%\\begin{myproof}\n%Let $\\tilde{\\D}_{x}^{o}$ and $\\tilde{\\D}_{x}^{n}$ be the matrices of reconstructive distance using $h_{o}$ and $h_{n}$ respectively, $\\H_{o}$ and $\\H_{n}$ be the $N\\times M$ matrices of old and new hash codes of $\\mathcal{X}$ respectively, and $\\G$ be the hash codes of $\\mathcal{Y}$. Moreover, we use $\\1_{t}$ to denote the $t$th standard basis vector and $\\1$ to denote a vector of all ones, and their dimensionalities will be clear in the context.\n%\n%We can express $\\tilde{\\D}_{x}^{o}$ as follows,\n%\\begin{align}\n%\\tilde{\\D}_{x}^{o} = \\frac{1}{M}\\left(\\Ell_{xo}\\1^{T}+\\1\\Ell^T_{o}-2\\H_{o}\\H_{o}^{T}\\right)\\nonumber,\n%\\end{align}\n%where $\\Ell_{xo}$ is the vector of squared norms of the rows of $\\H_{o}$. Accordingly, we can express $\\Ell_{xn}$ for $\\H_{n}$ as $\\Ell_{xn} = \\Ell_{xo} - \\h_{o}+\\h_{n}$, since $\\h_{o}$ and $\\h_{n}$ are binary vectors.\n%Moreover, we can easily obtain $\\H_{n} = \\H_{o} +(\\h_{n}-\\h_{o})\\1^{T}_{m}$, where $m$ is the index of the hash function being updated. Therefore,\n%\\begin{align}\n%\\tilde{\\D}_{x}^{n}\n%&= \\frac{1}{M}\\left(\\Ell_{xn}\\1^{T}+\\1\\Ell_{xn}^T-2\\H_{n}\\H_{n}^{T}\\right)\\nonumber\\\\\n%&= \\frac{1}{M}\\left((\\Ell_{xo} - \\h_{o}+\\h_{n})\\1^{T}+\\1(\\Ell_{xo} - \\h_{o}+\\h_{n})^{T}-2(\\H_{o} +(\\h_{n}-\\h_{o})\\1^{T}_{m})(\\H_{o} +(\\h_{n}-\\h_{o})\\1^{T}_{m})^{T}\\right)\\nonumber\\\\\n%&= \\tilde{\\D}_{x}^{o}-\\frac{1}{M}\\left((\\h_{o}\\1^{T}+\\1\\h_{o}^{T}-2\\h_{o}\\h_{o}^{T})-(\\h_{n}\\1^{T}+\\1\\h_{n}^{T}-2\\h_{n}\\h_{n}^{T})\\right).\\nonumber\n%\\end{align}\n%\n%Similarly, we have the following crossmodel reconstructive distance matrix,\n%\\begin{align}\n%\\tilde{\\D}_{xy}^{o} = \\frac{1}{M}\\left(\\Ell_{xo}\\1^{T}+\\1\\Ell_{y}^T-2\\H_{o}\\G^{T}\\right)\\nonumber,\n%\\end{align}\n%where $\\Ell_{y}$ is the vector of squared norms of the rows of $\\G$. Therefore,\n%\\begin{align}\n%\\tilde{\\D}_{xy}^{n}\n%&= \\frac{1}{M}\\left(\\Ell_{xn}\\1^{T}+\\1\\Ell_{y}^T-2\\H_{n}\\G^{T}\\right)\\nonumber\\\\\n%&= \\frac{1}{M}\\left((\\Ell_{xo} - \\h_{o}+\\h_{n})\\1^{T}+\\1\\Ell_{y}^{T}-2(\\H_{o} +(\\h_{n}-\\h_{o})\\1^{T}_{m})\\G^{T}\\right)\\nonumber\\\\\n%&= \\tilde{\\D}_{x}^{o}-\\frac{1}{M}\\left((\\h_{o}\\1^{T}-2\\h_{o}\\g^{T})-(\\h_{n}\\1^{T}-2\\h_{n}\\g^{T})\\right).\\nonumber\n%\\end{align}\n%\n%Thus we can write the objective function of using $h_{n}$ instead of $h_{o}$ as\n%\\begin{align}\n%\\mathcal{O} &= \\sum_{(\\x_i,\\x_j)\\in\\mathcal{N}_{x}}\\left(\\bar{D}_{x}(i,j)+\\tilde{D}_{x}^{o}(i,j)-\\tilde{D}_{x}^{n}(i,j)\\right)^2+\\sum_{(\\x_i,\\y_k)\\in\\mathcal{N}_{xy}}\\left(\\bar{D}_{xy}(i,k)+\\tilde{D}_{xy}^{o}(i,k)-\\tilde{D}_{xy}^{n}(i,k)\\right)^2\\nonumber\\\\\n%&=\\sum_{(\\x_i,\\x_j)\\in\\mathcal{N}_{x}}\\left(\\bar{D}_{x}(i,j)+\\frac{1}{M}(h_{o}(i)-h_{o}(j))^2-\\frac{1}{M}(h_{n}(i)-h_{n}(j))^2\\right)^2\\nonumber\\\\\n%&+\\sum_{(\\x_i,\\y_k)\\in\\mathcal{N}_{xy}}\\left(\\bar{D}_{xy}(i,k)+\\frac{1-2g(k)}{M}(h_{o}(i)-h_{n}(i))\\right)^2+C,\n%\\end{align}\n%where we have made use of $h_{o}(i)^2 = h_{o}(i)$ and $h_{n}(i)^2 = h_{n}(i)$ and grouped terms irrelevant to $h_{o},h_{n}$ into $C$. This completes the proof.\n%\\end{myproof}\n%\n%Now we move to the details of updating one element of $\\W_{x}$, e.g., $W_{x}(m,q_0)$, with all the other elements in $\\W_{x}$ fixed. Given a point $\\x_i$, the $m$th hash code can be obtained by computing\n%\\begin{align}\n%W_{x}(m,q_0)\\kappa(\\x_{q_0},\\x_i)+\\sum\\nolimits_{q\\neq q_0}W_{x}(m,q)\\kappa(\\x_{q},\\x_i).\n%\\label{eqn:threshold-1bit}\n%\\end{align}\n%Equating (\\ref{eqn:threshold-1bit}) to zero, we can easily obtain the incremental value for $W_{x}(m,q_0)$ that can change the current bit of $\\x_i$ as\n%\\begin{align}\n%    \\delta_{i} = \\left(\\sum\\nolimits_{q\\neq q_0}W_{x}(m,q)\\kappa(\\x_{q},\\x_{i})\\right)/\\kappa(\\x_{q_0},\\x_{i}) - W_{x}(m,q_0).\n%\\end{align}\n%\n%If $h_m(\\x_i)>0$, we should decrease $W_{x}(m,q_0)$ to flip the hash code, in another words, $\\delta_i<0$. On the contrary, if $h_m(\\x_i)<0$, we should increase $W_{x}(m,q_0)$ to flip the hash code, that is, $\\delta_i>0$. As a result, we first find all the $\\delta_{i}$'s for all $\\x_{i}$'s. Then we sort $\\{\\delta_i\\mid\\delta_i>0\\}$ in ascending order and $\\{\\delta_i\\mid\\delta_i<0\\}$ in descending order, and thus obtain two sets of intervals. It is easy to observe that, in a fixed interval, changing $W_{x}(m,q_0)$ will not affect the hash code of any point. However, if we go across intervals, the hash code of exactly one point will be changed. As a result, starting from the current value of $W_{x}(m,q_0)$, we first increase it by adding $\\delta_i+\\epsilon>0$ from the smallest one to the largest one to obtain a set of possible values of objective function~(\\ref{eqn:totalobj}). Note that $\\epsilon$ is a very small positive number ensuring that only the $i$th bit is flipped. We then decrease $W_{x}(m,q_0)$ by adding $\\delta_i-\\epsilon<0$ to the starting value from the largest one to the smallest one to obtain another set of possible objective values. In total, we obtain a set of $N$ possible objective values. After getting all these values, we update $W_x(m,q_{0})$ by adding $\\delta_i$ corresponding to the smallest objective $\\mathcal{O}_i$ if it is smaller than original objective $\\mathcal{O}$ before updating, or skip this iteration otherwise.\n%\n%The main idea of updating $W_{x}(m,q_0)$ is to find $\\delta_i$ leading to the smallest objective function value.  We can compute the values sequentially in an efficient way based on Lemma~\\ref{lemma:updateh}.\n%\\begin{mylem}\n%Given two hash vectors $\\h_{t}$ and $\\h_{t-1}$ for $\\mathcal{X}$ which are different in only one position, the objective w.r.t. $\\h_{t}$ can be computed from that w.r.t. $\\h_{t-1}$ in $O(k)$ time.\n%\\label{lemma:updateh}\n%\\end{mylem}\n%\\begin{myproof}\n%Let the index of the point in which $\\h_{t}$ and $\\h_{t-1}$ are different be $a$. The only terms that change in the objective are $(\\x_a,\\x_j)\\in\\mathcal{N}_{x},(\\x_i,\\x_a)\\in\\mathcal{N}_{x}$, and $(\\x_a,\\y_k)\\in\\mathcal{N}_{xy}$. Let $f_a = 1$ if $h_{t-1}(a)=0,h_{t}(a)=1$, and $f_a=-1$ otherwise. Therefore the relevant terms in the objective function as given in Lemma~\\ref{lemma:updatex} may be written as\n%\\begin{align}\n%\\mathcal{O}'&=\\sum_{(\\x_a,\\x_j)\\in\\mathcal{N}_{x}}\\left(\\bar{D}_{x}(a,j)-\\frac{f_a}{M}(1-2h_{t}(j))\\right)^2+\\sum_{(\\x_i,\\x_a)\\in\\mathcal{N}_{x}}\\left(\\bar{D}_{x}(i,a)-\\frac{f_a}{M}(1-2h_{t}(i))\\right)^2\\nonumber\\\\\n%&+\\sum_{(\\x_a,\\y_k)\\in\\mathcal{N}_{xy}}\\left(\\bar{D}_{xy}(a,k)-\\frac{f_a}{M}(1-2g(k))\\right)^2.\n%\\label{eqn:updateO-1bit}\\end{align}\n%\n%Since $\\x_{a}$ has $k$ nearest neighbors and lives in the neighborhood of $k$ points on average, it costs $O(k)$ time to update the objective.\n%\\end{myproof}\n%\n%We can update each element of $\\W_{y}$ similarly with the help of the following two lemmas. %Due to lack of space, we omit the proof here.\n%\n%\\begin{mylem}\n%Let $\\bar{D}_{y}(k,l)=d(\\y_k,\\y_l)-\\tilde{d}(\\y_k,\\y_l),\\bar{D}_{xy}(i,k)=d(\\x_i,\\y_k)-\\tilde{d}(\\x_i,\\y_k)$. Consider updating one hash function of $\\mathcal{Y}$ from $g_{o}$ to $g_{n}$, and let $\\g_{o}$ and $\\g_{n}$ be the $N\\times 1$ vectors obtained by applying the old and new hash functions to each data point in $\\mathcal{Y}$. We further denote the hash function of $\\mathcal{X}$ with the same index as $h$ and the corresponding binary vector of $\\mathcal{X}$ as $\\h$. Then the objective function of using $g_{n}$ instead of $g_{o}$ can be expressed as\n%\\begin{align}\n%\\mathcal{O} &= \\sum_{(\\y_k,\\y_l)\\in\\mathcal{N}_{y}}\\left(\\bar{D}_{y}(k,l)+\\frac{1}{M}(g_{o}(k)-g_{o}(l))^2-\\frac{1}{M}(g_{n}(k)-g_{n}(l))^2\\right)^2\\nonumber\\\\\n%&+ \\sum_{(\\x_i,\\y_k)\\in\\mathcal{N}_{xy}}\\left(\\bar{D}_{xy}(i,k)+\\frac{1-2h(i)}{M}(g_{o}(k)-g_{n}(k))\\right)^2+C',\n%\\end{align}\n%where $C'$ is a constant independent of $g_{o}$ and $g_{n}$.\n%\\label{lemma:updatey}\n%\\end{mylem}\n%\n%\\begin{mylem}\n%Given two hash vectors $\\g_{t}$ and $\\g_{t-1}$ for $\\mathcal{Y}$ which are different in only one position, the objective w.r.t. $\\g_{t}$ can be computed from that w.r.t. $\\g_{t-1}$ in $O(k)$ time.\n%\\label{lemma:updateg}\n%\\end{mylem}\n%\n%As a result, the general procedure of our algorithm can be summarized as follows. We first initialize model parameters $\\W_{x}, \\W_{y}$. Then we update each element of $\\W_{x}$ based on Lemma~\\ref{lemma:updatex}\\&\\ref{lemma:updateh}, and each element of $\\W_{y}$ based on Lemma~\\ref{lemma:updatey}\\&\\ref{lemma:updateg}. This updating procedure iterates until $\\W_{x}, \\W_{y}$ converge. We then use current values of $\\W_{x}, \\W_{y}$ as initialization and retrain the model to get better $\\W_{x}, \\W_{y}$. In our experiments, this warm-start approach is very effective, $\\W_{x}, \\W_{y}$ will converge very fast to a better local optimum. To update one element of $\\W_{x}$ or $\\W_{y}$, sorting $N$ incremental values $\\delta_i$'s needs $O(N\\log N)$ time, obtaining all objective function values needs $O(Nk)$ time and finding the smallest $\\mathcal{O}_i$'s needs $O(N)$ time. Putting everything together, the time complexity of updating one element is $O(N\\log N+Nk)$. As a result, one full iteration of updating $\\W_{x}$ or $\\W_{y}$ requires $O(MQN(\\log N+k))$ time.\n%\n%%\\begin{algorithm}\n%%%\\DontPrintSemicolon\n%%%\\SetKwData{Left}{left}\\SetKwData{This}{this}\\SetKwData{Up}{up}\n%%%\\SetKwFunction{Union}{Union}\\SetKwFunction{FindCompress}{FindCompress}\n%%\\SetKwInOut{Input}{Input}\\SetKwInOut{Output}{Output}\n%%\n%%\\Input{$\\mathcal{N}_{x}, \\mathcal{N}_{y}, \\mathcal{N}_{xy}$.}\n%%\\Output{$\\W_{x}, \\W_{y}$.}\n%%\\Begin{\n%%Initialize $\\W_{x}, \\W_{y}$.\n%%\\While{NOT Converge}{\n%%\\For{$m=1$ to $M$}{    \\For{$q=1$ to $Q$}{ Update $W_{x}(m,q)$.}    }\n%%\\For{$m=1$ to $M$}{    \\For{$q=1$ to $Q$}{ Update $W_{y}(m,q)$.}    }\n%%}}\n%%\\caption{General procedure of coordinate descent}\n%%\\label{algo:cmh}\n%%\\end{algorithm}\n%\n%Note that local convergence in a finite number of updates is guaranteed since each update will never increase the objective function value which is lower-bounded by zero. Therefore, the algorithm is  efficient and can scale well even for large high-dimensional data sets.\n%\n% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %\n%\\section{Multimodal Latent Binary Embeddings}\n%\\label{smh:MLBE}\n%\n%Up to now, we have presented two models, namely, \\mbox{SMH} and \\mbox{MBRE}. To evaluate the data correlation, \\mbox{SMH} requires paired or aligned input data which might not be easy to obtain. \\mbox{MBRE} eliminates this constraint by directly finding a discrete embedding, so that the Hamming distance in the embedded space maximally approximates the original distance. In this section, we introduce an alternative multimodal hashing model to improve \\mbox{SMH}, which is called \\textit{multimodal latent binary embeddings} (\\mbox{MLBE}), based on latent factor models. \\mbox{MLBE} relates hash codes and observations of similarity, i.e., intramodel similarity and intermodel similarity, in a probabilistic model, and the hash codes can be learned easily by \\mbox{MAP} estimation of the latent factors. %Among other things, \\mbox{MLBE} can be easily extended to determine the proper length of hash codes.\n%\n%% the intramodel and intermodel similarities are generated based on latent binary factors and weighting matrices. \n%\n%\\subsection{Model}\n%\n%In the following, we focus on the bimodel case but it is easy to extend \\mbox{MLBE} to support multiple modalities. Assume we have binary latent factors for each modality, for example, $ \\U \\in \\{+1,-1\\}^{N\\times K} $ for $ \\X  $ and $ \\V \\in \\{+1,-1\\}^{M\\times K} $ for $ \\Y  $. Correspondingly, we also have two weighting matrices, $\\W^{x} \\in \\mathbb{R}^{K\\times K}$ and $ \\W^{y}  \\in \\mathbb{R}^{K\\times K}$. The basic assumption of our model is that the observations of intramodel and intermodel similarities are determined by the latent factors and weighting matrices. The graphical representation of \\mbox{MLBE} is depicted in Figure~\\ref{fig:model}.\n%\n%\\begin{figure}[tb]\n%\\centering\n%\\epsfig{figure=fig/mlbe/graphmodel, width=0.4\\textwidth}\n%\\caption{Graphical representation of the model of multimodal latent binary embeddings. The shaded circles are observed variables and the empty ones are latent variables.}\n%\\label{fig:model}\n%\\end{figure}\n%\n%\n%Given $ \\U , \\V , \\W^{x} $ and $ \\W^{y} $, the two symmetric intramodel similarity matrices $ \\S^{x} \\in \\mathbb{R}^{N\\times N}$ for  $ \\X $ and $ \\S^{y} \\in \\mathbb{R}^{M\\times M}$ for $ \\Y $ are generated from the following distributions, respectively:\n%$$S^{x}_{ij} \\mid \\U, \\W^{x}  \\sim \\mathcal{N}(\\u_i^T\\W^{x}\\u_j,\\theta_x^2 ), \\ \\ \\forall i \\ge j, \\  i,j\\in\\{1,\\cdots,N\\}, $$\n%$$S^{y}_{ij} \\mid \\V, \\W^{y}  \\sim \\mathcal{N}(\\v_i^T\\W^{y}\\v_j,\\theta_y^2 ), \\ \\ \\forall i \\ge j, \\  i,j\\in\\{1,\\cdots,M\\}, $$\n%where $ \\u_i $ and $ \\u_j $ denote the $ i $th row and $ j $th row of $ \\U  $. Similarly, $ \\v_i $ and $ \\v_j $ denote the $ i $th row and $ j $th row of $ \\V  $.\n%\n%We also observe a intermodel similarity matrix $ \\S^{xy} \\in \\{1,0\\}^{N\\times M}$, where 1 and 0 stand for similar and dissimilar, respectively. For example, if an image and a text document are both for a historic event, we label them with 1. If they are irrelevant, we label them with 0. Note that it is quite common and easy to define intermodel similarity using binary values $ \\{1,0\\} $ in practice, but our model can also accommodate other values by simply changing the distribution. We further assume only a subset of the intermodel similarity values are observed and use an indicator matrix $ \\O\\in \\{0,1\\}^{N\\times M} $ to denote this, i.e., $ O_{ij}=1 $ if $ S_{ij}^{xy} $ is observed and $ O_{ij}=0 $ otherwise. Given $ \\U  $ and $ \\V  $, the observed elements in $ \\S^{xy} $ are generated by\n%$$S^{xy}_{ij} \\mid \\U, \\V  \\sim \\mbox{Bernoulli}(\\sigma(\\u_i^{T}\\v_j)),\\ \\ \\forall i,j, \\ O_{ij}=1,$$\n%where $ \\sigma(x) = 1/(1+\\exp(-x))$ is the logistic sigmoid function.\n%\n%Assume each element in $ \\U\\in\\{+1,-1\\}^{N\\times K}  $ is determined identically and independently the following way,\\footnote{Conventional the Bernoulli distribution is for $ \\{0,1\\} $ valued variables. Here, without loss of generality, we can map them to $ \\{-1,+1\\} $ by linear transformation.}\n%\\begin{align}\n%\\pi \\mid \\alpha_u,\\beta_u &\\sim \\mbox{Beta}(\\alpha_u,\\beta_u),\\nonumber\\\\\n%U_{ik} \\mid \\pi &\\sim \\mbox{Bernoulli}(\\pi),\\nonumber\n%\\end{align}\n%where $ \\alpha_u $ and $ \\beta_u $ are hyperparameters, we can integrate out $ \\pi $ to give the following prior on $ \\U $:\n%\\begin{align}\n%U_{ik} \\mid \\alpha_u,\\beta_u  \\sim \\mbox{Bernoulli}(\\frac{\\alpha_u}{\\alpha_u+\\beta_u}), \\ \\ \\forall i\\in\\{1,\\cdots,N\\}, \\ k\\in\\{1,\\cdots,K\\}.\\nonumber\n%\\end{align}\n%\n%Similarly, we define the prior on $ \\V \\in\\{+1,-1\\}^{M\\times K} $ as\n%\\begin{align}\n%V_{ik} \\mid \\alpha_v,\\beta_v  \\sim \\mbox{Bernoulli}(\\frac{\\alpha_v}{\\alpha_v+\\beta_v}), \\ \\ \n%\\forall i\\in\\{1,\\cdots,M\\}, \\ k\\in\\{1,\\cdots,K\\}.\\nonumber\n%\\end{align}\n%\n%%The prior terms for $ \\U  \\in \\{+1,-1\\}^{N\\times K}$ and $ \\V \\in \\{+1,-1\\}^{M\\times K} $ are from ~\\cite{griffiths2006nips}:\n%%$$\\Pr(\\U) = \\prod_{k=1}^K\\frac{\\frac{\\alpha}{K}\\Gamma(N_k+\\frac{\\alpha}{K})\\Gamma(N-N_k+1)}{\\Gamma(N+1+\\frac{\\alpha}{K})}$$\n%%and\n%%$$\\Pr(\\V) = \\prod_{k=1}^K\\frac{\\frac{\\beta}{K}\\Gamma(M_k+\\frac{\\beta}{K})\\Gamma(M-M_k+1)}{\\Gamma(M+1+\\frac{\\beta}{K})},$$\n%%where $ N_k = \\sum_{i=1}^{N}\\delta(U_{ik}=1) $ and $ M_k = \\sum_{i=1}^{M}\\delta(V_{ik}=1) $ are the number of $ 1 $'s in the $ k $th column of $ \\U  $ and $ \\V  $, respectively.\n%\n%For $ \\X  $, the entries of the symmetric weight matrix $ \\W^{x}\\in\\mathbb{R}^{K\\times K} $ are generated identically and independently by a standard Gaussian distribution:\n%$$\\W^{x}_{ij} \\mid \\phi_x^2  \\sim \\mathcal{N}(0,\\phi_x^2 ), \\ \\  \\forall i\\ge j, \\ i,j\\in\\{1,\\cdots,K\\}.$$\n%We put a similar prior on  $ \\W^{y}\\in\\mathbb{R}^{K\\times K} $ for $ \\Y  $:\n%$$\\W^{y}_{ij} \\mid \\phi_y^2  \\sim \\mathcal{N}(0,\\phi_y^2 ), \\ \\ \\forall i\\ge j, \\ i,j\\in\\{1,\\cdots,K\\}.$$\n%%We put simple matrix Gaussian prior on $ \\W_x $ and $ \\W_y $, which can be written as:\n%%$$\\Pr(\\w_{x}) = \\mathcal{N}(\\0,\\phi_x\\I ), \\w_{x} = \\W_x(:)$$\n%%$$\\Pr(\\w_y) = \\mathcal{N}(\\0,\\phi_y\\I ), \\w_y = \\W_y(:)$$\n%\n%\\subsection{Algorithm}\n%\n%Based on the observations, we can learn the parameters $ \\U $ and $ \\V $ to give the hash codes. But finding exact posterior distributions of $ \\U  $ and $ \\V  $ is intractable, as a result, we adopt an alternating algorithm to find an \\mbox{MAP} estimation of $ \\U , \\V ,\\W^x $ and $ \\W^y  $.\n%\n%We first update $ U_{ik} $ while fixing the others. To decide the \\mbox{MAP} estimation of $ U_{ik} $, we first define a loss function with respect to $ U_{ik}$ as in Definition~\\ref{def:lossu}:\n%\n%%  $ Let $ \\u_i $ be the $ i $th row of $ \\U  $, $\\w_{x} = \\W_x(:) $ and $ \\s^{x}_{i} = \\S_x(:,i) $, we denote $ \\A_i = \\mbox{kron}(\\u_i, \\U) $ and have $ \\Pr(\\s^{x}_{i}\\mid \\A,\\w_{x}) = \\mathcal{N}(\\A_i\\w_{x},\\theta_x\\I) $. The loss function of updating one element $ \\U_{ik}  $:\n%\n%\\begin{mydef}\n%\\begin{align}\n%\\mathcal{L}_{U_{ik}} &=\\log\\frac{\\alpha_u}{\\beta_u}-\\frac{1}{2\\theta_{x}^2}\\sum_{j\\neq i}^{N}\\left[-2 S^{x}_{ij} \\u_j^T\\W^x(\\u_{i}^{+} - \\u_{i}^{-}) - \\u_j^T\\W^x(\\u_{i}^{+}{\\u_{i}^{+}}^{T}-\\u_{i}^{-}{\\u_{i}^{-}}^{T})\\W^x\\u_j\\right]\\nonumber\\\\\n%&+\\sum_{j=1}^{M}O_{ij}\\left[S_{ij}^{xy}\\log \\frac{\\sigma_{ij}^{+}}{\\sigma_{ij}^{-}} + (1-S_{ij}^{xy})\\log \\frac{1-\\sigma_{ij}^{+}}{1-\\sigma_{ij}^{-}}\\right],\n%\\end{align}\n%where $ U_{-ik} $ denotes all the elements in $ \\U $ but $ U_{ik} $, $ \\s^{x}_i $ denotes the $ i $th row of $ \\S^{x} $, $ \\u^{+}_i $ is the $ i $th row of $ \\U  $ with $ U_{ik}=1 $ and $ \\u^{-}_i $ is the $ i $th row of $ \\U $ with $ U_{ik}=-1 $. We further define $ \\sigma^{+}_{ij} = \\sigma(\\v_j^T\\u_i^{+}) $ and $ \\sigma^{-}_{ij} = \\sigma(\\v_j^T\\u_i^{-}) $.\n%\\label{def:lossu}\\end{mydef}\n%\n%Then we have the following lemma:\n%\\begin{mylem}\n%The \\mbox{MAP} solution of $ U_{ik} $ is $ U_{ik}=1 $ if $ \\mathcal{L}_{U_{ik}}>0 $ and $ U_{ik}=-1 $ otherwise.\n%\\label{lemma:updateu}\\end{mylem}\n%\n%\\begin{myproof}\n%To get the \\mbox{MAP} estimation of $ U_{ik} $, we only need to compare the two posterior probabilities $ \\Pr(U_{ik}=1) $ and $ \\Pr(U_{ik}=-1) $ conditioned on the observations and all the other model parameters. Specifically, we compute the log ratio of the two probabilities which is larger than zero if $ \\Pr(U_{ik}=1) > \\Pr(U_{ik}=-1)  $ and smaller than zero otherwise. The log ratio can be evaluated as follows:\n%\\begin{align}\n% & \\log \\frac{\\Pr(U_{ik} = 1\\mid U_{-ik},\\V , \\W_x, \\S^{x}, \\S^{xy})}{\\Pr(U_{ik} = -1\\mid U_{-ik},\\V , \\W_x, \\S^{x}, \\S^{xy})}\\nonumber\\\\\n%=& \\log \\frac{\\Pr(U_{ik} = 1\\mid \\alpha,\\beta)}{\\Pr(U_{ik} = -1\\mid \\alpha,\\beta)}\n%+\\log \\frac{\\Pr(\\s^{x}_i\\mid U_{ik}=1, U_{-ik}, \\W^{x})}{\\Pr(\\s^{x}_i\\mid U_{ik}=-1, U_{-ik}, \\W^{x})}\\nonumber\\\\\n%+&\\log \\frac{\\Pr(\\S^{xy}\\mid U_{ik}=1, U_{-ik}, \\V)}{\\Pr(\\S^{xy}\\mid U_{ik}=-1, U_{-ik}, \\V)}\\nonumber\\\\\n%=&\\log\\frac{\\alpha_u}{\\beta_u}-\\frac{1}{2\\theta_{x}^2}\\sum_{j\\neq i}^{N}\\left[-2 S^{x}_{ij} \\u_j^T\\W^x(\\u_{i}^{+} - \\u_{i}^{-})\\right]\\nonumber\\\\\n%-&\\frac{1}{2\\theta_{x}^2}\\sum_{j\\neq i}^{N}\\left[\\u_j^T\\W^x(\\u_{i}^{+}{\\u_{i}^{+}}^{T}-\\u_{i}^{-}{\\u_{i}^{-}}^{T})\\W^x\\u_j\\right]\\nonumber\\\\\n%+&\\sum_{j=1}^{M}O_{ij}\\left[S_{ij}^{xy}\\log \\frac{\\sigma_{ij}^{+}}{\\sigma_{ij}^{-}} + (1-S_{ij}^{xy})\\log \\frac{1-\\sigma_{ij}^{+}}{1-\\sigma_{ij}^{-}}\\right],\n%%-\\frac{1}{\\theta_x}\\left[{\\s^{x}_i}^T (\\A^{-}_{i} -  \\A^{+}_{i} )\\w_{x}\\right]\\nonumber\\\\\n%%&-\\frac{1}{2\\theta_x}\\left[\\w_{x}^T({\\A^{+}_{i}}^{T}\\A^{+}_{i} - {\\A^{-}_{i}}^{T}\\A^{-}_{i})\\w_{x}\\right]\\nonumber\\\\\n%%&-\\frac{1}{\\mu}\\sum_{i,j}I_{ij}\\left[S^{xy}_{ij}(\\sigma^{-}_{ij}-\\sigma^{+}_{ij})+\\frac{1}{2}({\\sigma^{+}_{ij}}^2-{\\sigma^{-}_{ij}}^2)\\right],\n%\\label{eqn:lossu}\\end{align}\n%where $ U_{-ik} $ denotes all the elements in $ \\U $ but $ U_{ik} $, $ \\s^{x}_i $ denotes the $ i $th row of $ \\S^{x} $, $ \\u^{+}_i $ is the $ i $th row of $ \\U  $ with $ U_{ik}=1 $ and $ \\u^{-}_i $ is the $ i $th row of $ \\U $ with $ U_{ik}=-1 $. We further define $ \\sigma^{+}_{ij} = \\sigma(\\v_j^T\\u_i^{+}) $ and $ \\sigma^{-}_{ij} = \\sigma(\\v_j^T\\u_i^{-}) $.\n%\n%The log ratio computed in Eqn.~(\\ref{eqn:lossu}) gives exactly $ \\mathcal{L}_{U_{ik}} $, hence the proof is completed.\n%\\end{myproof}\n%\n%%The details can be found in Appendix.\n%\n%%We group all the terms irrelevant to $ U_{ik} $ in $ C $.\n%\n%%$ N_{-ik} = \\sum_{j\\neq i}\\delta(U_{jk}=1)$ is the number of $ +1 $ in $ k $th column and all rows but the $ i $th row and $ I_{ij}=1 $ if $ \\S^{xy}_{ij} $ is observed and  $ I_{ij}= 0 $ otherwise. We define $ \\A^{+}_{i} = \\mbox{kron}(\\u_i,\\U ) $ and $ \\sigma^{+}_{ij} = \\sigma(\\u_i^T\\v_j) $ with $ U_{ik}=1 $. We define $ \\A^{-}_{i} = \\mbox{kron}(\\u_i,\\U ) $ and $ \\sigma^{-}_{ij} = \\sigma(\\u_i^T\\v_j) $ with $ U_{ik}=-1 $.\n%\n%%\n%%$ (\\hat{\\u}_1-\\hat{\\u}_2)\\w_x\\S_x\\nonumber\\\\&+(\\hat{\\u}_1(\\W_x^T\\W_x))(\\hat{\\u}_1-\\hat{\\u}_2)\\nonumber\\\\& + (\\hat{\\u}_2(\\W_x^T\\W_x))(\\hat{\\u}_1-\\hat{\\u}_2)\\nonumber\\\\& +\\sum_{j}I_{ij}(S_{ij}-\\sigma(\\u_i^{T}\\v_j)q)^2 $\n%%We can easily evaluate loss function~(\\ref{eqn:loss_u}) and set\n%%\\begin{align}\n%%U_{ik} = \\left\\{ \\begin{array}{ll}\n%%+1 & \\mathcal{L}_{U_{ik}}>0\\\\\n%%-1 & \\mbox{otherwise}\n%%\\end{array} \\right.\n%%\\end{align}\n%\n%Similarly, we have Definition~\\ref{def:lossv} and Lemma~\\ref{lemma:updatev} for \\mbox{MAP} estimation of $ \\V $. %Due to space limitations, we omit the proof here.\n%\n%\\begin{mydef}\n%\\begin{align}\n%\\mathcal{L}_{V_{ik}} &=\\log\\frac{\\alpha_v}{\\beta_v}-\\frac{1}{2\\theta_{y}^2}\\sum_{j\\neq i}^{N}\\left[-2 S^{y}_{ij} \\v_j^T\\W^y(\\v_{i}^{+} - \\v_{i}^{-}) - \\v_j^T\\W^y(\\v_{i}^{+}{\\v_{i}^{+}}^{T}-\\v_{i}^{-}{\\v_{i}^{-}}^{T})\\W^y\\v_j\\right]\\nonumber\\\\\n%&+\\sum_{j=1}^{N}O_{ji}\\left[S_{ji}^{xy}\\log \\frac{\\sigma_{ji}^{+}}{\\sigma_{ji}^{-}} + (1-S_{ji}^{xy})\\log \\frac{1-\\sigma_{ji}^{+}}{1-\\sigma_{ji}^{-}}\\right],\n%\\end{align}\n%where $ V_{-ik} $ denotes all the elements in $ \\V $ but $ V_{ik} $, $ \\s^{y}_i $ denotes the $ i $th row of $ \\S^{y} $, $ \\v^{+}_i $ is the $ i $th row of $ \\V  $ with $ V_{ik}=1 $ and $ \\v^{-}_i $ is the $ i $th row of $ \\V $ with $ V_{ik}=-1 $. We further define $ \\sigma^{+}_{ji} = \\sigma(\\u_j^T\\v_i^{+}) $ and $ \\sigma^{-}_{ji} = \\sigma(\\u_j^T\\v_i^{-}) $.\n%\\label{def:lossv}\\end{mydef}\n%\n%\n%\\begin{mylem}\n%The \\mbox{MAP} solution of $ V_{ik} $ is $ V_{ik}=1 $ if $ \\mathcal{L}_{V_{ik}}>0 $ and $ V_{ik}=-1 $ otherwise.\n%\\label{lemma:updatev}\\end{mylem}\n%\n%When fixing $ \\U , \\V  $ and $ \\W^{y} $, we compute the \\mbox{MAP} estimation of $ \\W^{x} $ by maximizing the following loss function:\n%\\begin{align}\n%\\mathcal{L}_{\\W^{x}}&= \\log P(\\W^{x}) + \\log P(\\S^{x}_{h}\\mid \\U ,\\W^{x})\\nonumber\\\\\n%&=\\sum_{ i\\ge j}^{K}\\sum_{ j=1}^{K}-\\frac{{W^{x}_{ij}}^2}{2\\phi_x^2} + \\sum_{ i > j}^{N}\\sum_{ j=1}^{N}-\\frac{1}{2\\theta_x^2}(S^{x}_{ij}-\\u_i^T\\W^x\\u_j)^2\\nonumber\\\\\n%&=-\\frac{1}{4\\phi_x^2}\\w_{x}^T(\\I + \\mbox{diag}(\\m) )\\w_{x}\n%-\\frac{1}{2\\theta_x^2}\\left[(\\s^{x}_h-\\A_h\\w_x)^T(\\s^{x}_h-\\A_h\\w_x)\\right]\\nonumber\\\\\n%&= -\\frac{1}{2}\\w_{x}^T \\left(\\A_h^T\\A_h +\\frac{\\theta^2_x}{4\\phi^2_x}\\left(\\I + \\mbox{diag}(\\m) \\right) \\right)\\w_{x}\n% + \\w_{x}^T\\A^T_h \\s_h^x+C'\n%\\label{eqn:loss_wx}\\end{align}\n%where $ \\w_x  $ is a $ K^2 $-dimensional column vector taken column-wise from $ \\W^x $, $ \\m $ is a $ K^2 $-dimensional indicator vector in which the value should be 1 if the index corresponds to $ W^{x}_{ii},i=1,\\cdots,K $ and 0 otherwise.\n%Let $ \\S^{x}_{h} $ denote the left-lower half of $ \\S^{x} $ and its vector form be $ \\s^{x}_h $. We define $ \\A = \\U\\otimes \\U $ and $ \\A_h$ consists of the rows corresponding to $ S^x_{ij}, i>j $. We group all the terms irrelevant to $ \\W^{x} $ in $ C' $.\\footnote{Here we have used a property of Kronnecker multiplication: $ \\u^T \\W \\v = \\w^T(\\u\\otimes\\v)  $ where $ \\w $ is a column-wise vector of $ \\W $ if $ \\W $ is a symmetric matrix.}\n%\n%% $ \\s^x = \\S_x(:) $, we have $ \\Pr(\\s^x\\mid \\A,\\w_{x}) = \\mathcal{N}(\\A\\w_{x},\\theta_x\\I) $. The loss function of updating $ \\w_{x} $ is:\n%%\\begin{align}\n%%\\mathcal{L}_x = -\\frac{1}{2}\\w_{x} (\\A^T\\A +\\frac{\\theta_x}{\\phi_x}\\I )\\w_{x} + \\s^x\\A \\w_{x},\n%%\\end{align}\n%\\begin{mylem}\n%The \\mbox{MAP} estimation of $\\W^{x}$ can be evaluated by:\n%\\begin{align}\n%\\w_{x} =\\left(\\A_h^T\\A_h +\\frac{\\theta^2_x}{4\\phi^2_x}\\left(\\I + \\mbox{diag}(\\m) \\right)\\right)^{-1}\\A_h^T \\s^x. \\nonumber\n%\\end{align}\n%\\label{lemma:updatewx}\n%\\end{mylem}\n%\n%Note that Lemma~\\ref{lemma:updatewx} can be easily proved by setting the derivative of $ \\mathcal{L}_{\\W^{x}} $ with respect to $ \\w_{x} $ to zero.\\footnote{We can adopt gradient-based algorithms to find this global maximum, which may be much faster.} Similarly, we have Lemma~\\ref{lemma:updatewy} for $ \\W^{y} $.\n%\n%\\begin{mylem}\n%The \\mbox{MAP} estimation of $\\W^{y}$ can be evaluated by:\n%\\begin{align}\n%\\w_{y} =\\left(\\B_h^T\\B_h +\\frac{\\theta^2_y}{4\\phi^2_y}\\left(\\I + \\mbox{diag}(\\m) \\right)\\right)^{-1}\\B_h^T \\s^y,\\nonumber\n%\\end{align}\n%where $ \\w_y  $ is a $ k^2 $-dimensional column vector taken column-wise from $ \\W^y $, $ \\m $ is a $ k^2 $-dimensional indicator vector in which the value should be 1 if the index corresponds to $ W^{y}_{ii},i=1,\\cdots,K $ and 0 otherwise.\n%Let $ \\S^{y}_{h} $ denote the left-lower half of $ \\S^{y} $ and its vector form be $ \\s^{y}_h $. We define $ \\B = \\V\\otimes \\V $ and $ \\B_h$ consists of the rows corresponding to $ S^y_{ij}, i>j $.\n%\\label{lemma:updatewy}\n%\\end{mylem}\n%\n%%We can update $ \\W^{y} $ similarly.\\footnote{Updating $ \\W^{x} $ and $ \\W^{y} $ needs playing with a very large matrix  $ \\A_h$ which might not be handled in Matlab, so we use a small but sufficient reference set in $ \\X $ and $ \\Y  $ to learn $ \\W^{x} $ and $ \\W^{y} $ and fix them to learn $ \\U  $ and $ \\V $ for the whole database.}\n%\n%%Similarly, we have $ \\w_y =(\\B^T\\B +\\frac{\\theta_y}{\\phi_y}\\I )^{-1}\\B^T \\s_y $, where $ \\B = \\mbox{kron}(\\V, \\V) , \\w_y = \\W_y(:) $ and $ \\s^y = \\S_y(:) $.\n%\n%\n%%The algorithm should work as follows:\n%%1 use training data to get Wx, Wy and U, V.\n%%2 fix Wx, Wy and U, V for a reference set, we then paralelly update the U and V in the test set. Each update is conducted iteratively for the elements in U or V, should be converge very fast.\n%%3 use the code to do retrieval.\n%\n%We summarize the algorithm of \\mbox{MLBE} in Algorithm~\\ref{algorithm:mlbe}. In our experiments, we use the log likelihood to determine the convergence.\n%\n%\\begin{algorithm}[!t]\n%%\\DontPrintSemicolon\n%%\\SetKwData{Left}{left}\\SetKwData{This}{this}\\SetKwData{Up}{up}\n%%\\SetKwFunction{Union}{Union}\\SetKwFunction{FindCompress}{FindCompress}\n%\\SetKwInOut{Input}{Input}\\SetKwInOut{Output}{Output}\n%\\Input{$\\S_{x}$, $\\S_{y}$, $\\S_{xy}$ -- similarity matrices\n%\\\\ $\\O_{xy}$ -- similarity matrices\n%\\\\ $M$ -- number of hash functions\n%\\\\ $\\theta_x,\\theta_y, \\phi_x,\\phi_y, \\alpha_u,\\alpha_v, \\beta_u, \\beta_v$ -- regularization parameters}\n%\\Begin{\n%\\textit{Training phase}:\\\\\n%   Initialize $ \\U  $ and $ \\V  $ with $ \\{-1,+1\\}$ of equal probability.\n%   \\While{not converge}{\n%   Update each element of $ \\W_x $ sequentially using Lemma~\\ref{lemma:updatewx}.\n%   Update $ \\U  $ using Lemma~\\ref{lemma:updateu}.\n%   Update each element of $ \\W_y $ sequentially using Lemma~\\ref{lemma:updatewy}.\n%   Update $ \\V $ using Lemma~\\ref{lemma:updatev}.\n%   }\n%\\textit{Testing phase}:\\\\\n%   Obtain hash codes of points $\\x^{*}$ and $\\y^{*}$ using Lemma~\\ref{lemma:updateu} and Lemma~\\ref{lemma:updatev}, respectively.\n%}\n%\\caption{Algorithm of \\mbox{MLBE}}\n%\\label{algorithm:mlbe}\n%\\end{algorithm}\n%\n%%\\subsection{Complexity Analysis}\n%%-------------------------------------------------------------------------\n%\n%%\\section{Max margin multimodal hashing}\n%%\\label{smh:MMMH}\n%%\n%%In this section, we introduce a new model that utilize the idea of margin, which is equivalent to hinge loss. The key challenge is how to define margin in multimodal setting. And how to optimize. It will be the best if we can find some convex formulation. Nevertheless, we can use CCCP to achieve some global optimality. This should also be inspired from other embedding algorithms.\n%\n\\section{Experiments}\n\\label{smh:exps}\n\nWe conduct several experiments to compare \\mbox{SMH} and its extensions with some other related methods. Through the experiments, we want to answer the following questions for each method:\n\n\\begin{enumerate}\n\\item How does \\mbox{SMH} perform when compared with other state-of-the-art hashing models on crossmodal retrieval task?\n\\item How does \\mbox{SMH} perform when compared with other state-of-the-art hashing models on unimodal retrieval task?\n\\end{enumerate}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Data Sets}\n\\label{smh:exps:data}\n\nIn our experiments, we use two publicly available data sets that are, to the best of our knowledge, the only two up-to-date public data sets involving multiple modalities at large scale.\n\nThe first data set, named \\textit{Wiki}, is based on a set of Wikipedia featured articles provided by~\\cite{rasiwasia2010mm}.\\footnote{\\url{http://www.svcl.ucsd.edu/projects/crossmodal/}} It contains a total of 2,866 documents (image-text pairs), each of which consists of an image and a text article. Each document is annotated with a label chosen from ten semantic classes. The data set has been split into a training set of 2,173 documents and a test set of 693 documents. The image representation scheme is based on the popular \\textit{scale invariant feature transformation} (\\mbox{SIFT})~\\cite{lowe2004ijcv} with a codebook of 128 words.  Representation of a text article is based on its probability distribution over topics derived from a \\textit{latent Dirichlet allocation} (\\mbox{LDA}) model~\\cite{blei2003jmlr} with ten topics.\n\nThe second data set, named \\textit{\\mbox{Flickr}} thereafter, is a subset of the NUS-WIDE database\\footnote{\\url{http://lms.comp.nus.edu.sg/research/NUS-WIDE.htm}} which is based on images from \\mbox{Flickr.com}~\\cite{nus-wide-civr09}. We prune the original data set and keep only the points belonging to at least one of the ten largest classes. The data set contains a total of 186,577 image-text pairs, each of which belongs to at least one of ten possible labels (\\aka concepts). The data set has been split into a training set of 185,577 pairs and a test set of 1,000 pairs. The images are represented by a $500$-dimensional \\mbox{SIFT} representation. The text is simply represented by the number of occurrences of the 1,000 most frequently used tags according to the image.\n\nSome characteristics of the two data sets are summarized in Table~\\ref{table:data}.\n\n\\begin{table}[!t]\n% increase table row spacing, adjust to taste\n% \\renewcommand{\\arraystretch}{1.3}\n% if using array.sty, it might be a good idea to tweak the value of \\extrarowheight as needed to properly center the text within the cells\n\\caption{Characteristics of Data Sets}\\vspace{0.5cm}\n\\label{table:data}\n\\centering\n\\begin{tabular}{|c|c|c|c|c|}\n\\hline\nData set & $D_{x}$ &  $D_{y}$ &  \\# of points &\\# of classes\\\\\n\\hline\nWiki& 128& 10& 2,866 & 10\\\\\n\\hline\n\\mbox{Flickr}& 500& 1000& 186,577 &10\\\\\n\\hline\n\\end{tabular}\n\\end{table}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Experimental Settings}\n\\label{smh:exps:settings}\n\nTo mimic real multimedia retrieval systems, we consider two tasks in our experiments: crossmodel and uni-modal retrieval. In cross-modal retrieval, the query and the database belong to different modalities, for example, an image is used as a query and a set of text is used as a database. In uni-modal retrieval, the query and the database belong to the same modality. For each task, we first train the models on the training set, and then use documents in the test set as queries and the training set as database.\n\nWe use two evaluation measures in both cases, namely, \\textit{mean average precision} (\\mbox{MAP}) and precision at a fixed Hamming radius. \\mbox{MAP} is a measure widely used by the information retrieval community~\\cite{baeza1999book,rasiwasia2010mm}. Specifically, the \\mbox{MAP} for a set of queries is the mean of the \\textit{average precision} (\\mbox{AP}) scores for each query, with\n$$\\textrm{AP} = \\frac{1}{L}\\sum\\nolimits_{r=1}\\nolimits^{N}P(r)\\times\\delta(r),$$\nwhere $r$ is the rank position, $N$ is the number of retrieved documents, $\\delta(r)$ is a binary function that returns 1 if the document at rank position $r$ is relevant\\footnote{In the experiments, an image is relevant to a text if they share the same class label and vice versa.} to the query and 0 otherwise, $P(r)$ is the precision of relevance at position $r$, and $L$ is the total number of relevant documents in the retrieved set. \\mbox{MAP} is sometimes referred to geometrically as the area under the precision-recall curve for a set of queries~\\cite{turpin2006sigir}. Thus a larger value of \\mbox{MAP} indicates a better performance. To get the precision at Hamming radius $d$, we first retrieve all the documents which have Hamming distance at most $d$ to the query and then compute the precision of the retrieved documents. Similar to \\mbox{MAP}, larger values of precision indicate better performance. In all experiments, we set the rank position $r=100$ and the Hamming radius $d=2$.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Results} % of \\mbox{SMH}\n\\label{smh:exps:results_smh}\n\nIn the following experiments, we randomly select $P=500$  data points from the training set as landmarks for \\mbox{KSMH} and \\mbox{RKSMH} and repeat the process ten times. Hence for these two methods, we report the average results with the corresponding standard deviations. Moreover, linear kernel is used, Laplacians are defined based on labels and the parameters are set to $\\kappa = 10^{-4}$, $\\gamma = 0.1$ for the \\mbox{Wiki} data set and $\\gamma=100$ for the \\mbox{Flickr} data set.  Besides, to reduce computational cost on the \\mbox{Flickr} data set, we use a subset of 5,000 instances from the training set to train the models but the retrieval tasks are still conducted on the whole training set.\n\n%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Comparison for crossmodel retrieval}\n\\label{smh:exps:results:cross}\n\nWe first compare the four multimodal hashing methods, i.e., \\mbox{CMSSH}, \\mbox{SMH}, \\mbox{KSMH} and \\mbox{RKSMH}, for crossmodel retrieval. The results for different code lengths $M$ on the \\mbox{Wiki} data set are reported in Table~\\ref{table:comp-wiki-cross-it}~\\&~\\ref{table:comp-wiki-cross-ti}, and those on the \\mbox{Flickr} data set are reported in Table~\\ref{table:comp-flickr-cross-it}~\\&~\\ref{table:comp-flickr-cross-ti}.\n\n\\begin{table}[htb]\\small\n\\caption{Performance comparison for Image-Text retrieval on \\mbox{Wiki}}\\label{table:comp-wiki-cross-it}\\vspace{-0.5cm}\n\\begin{center}\n\\begin{tabular}{|c|c|c|c|c|}\n\\toprule[1pt]\\addlinespace[0pt]\n    \\multirow{2}{*}{Method}&  \\multirow{2}{*}{Measure}  &  \\multicolumn{3}{|c|}{Image query -- Text database}  \\\\\n\\cline{3-5}%\\addlinespace[0pt]\\midrule[1pt]\\addlinespace[0pt]\n&&$M=4$&$M=8$&$M=16$\\\\\n\\hline\n\\multirow{2}{*}{CMSSH}&{MAP}    &    $0.1660     $        &  $    0.1640    $ &$ 0.1751$  \\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}    &     \t$0.1150   $         &     $   0.1501  $         &        $  {\\bf0.3487} $       \\\\\n\\hline%\\addlinespace[0pt]\\midrule[0.5pt]\\addlinespace[0pt]\n\\multirow{2}{*}{SMH}&MAP        &     $0.1937 $         &     $  0.2290    $      &  $ 0.2140$ \\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}    &     \t$0.1252   $         &   $ {\\bf 0.1640}   $            &    $ 0.2200$         \\\\\n\\hline%\\addlinespace[0pt]\\midrule[0.5pt]\\addlinespace[0pt]\n\\multirow{2}{*}{KSMH}&MAP        &   $0.1909\\pm 0.0032$       &  ${\\bf0.2194\\pm0.0052}$         & $0.2177\\pm 0.0058$  \\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}    &  ${\\bf0.1253\\pm0.0008}$         & $0.1635\\pm 0.0045$              &  $0.2186\\pm0.0130$\\\\\n\\hline%\\addlinespace[0pt]\\midrule[0.5pt]\\addlinespace[0pt]\n\\multirow{2}{*}{RKSMH}&MAP        &     ${\\bf 0.1918\\pm0.0021}$         & $0.2189\\pm0.0036$          & ${\\bf0.2200\\pm0.0046}$  \\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}    &    \t$0.1219\\pm 0.0008        $          &    $0.1633\\pm0.0032$           &    $0.2172\\pm0.0084$         \\\\\n\\addlinespace[0pt]\\bottomrule[1pt]\n\\end{tabular}\n\\end{center}\n\\end{table}\n\n\\begin{table}[htb]\\small\n\\caption{Performance comparison for Text-Image retrieval on \\mbox{Wiki}}\\label{table:comp-wiki-cross-ti}\\vspace{-0.5cm}\n\\begin{center}\n\\begin{tabular}{|c|c|c|c|c|}\n\\toprule[1pt]\\addlinespace[0pt]\n    \\multirow{2}{*}{Method}&  \\multirow{2}{*}{Measure}  &  \\multicolumn{3}{|c|}{Text query -- Image database}\\\\\n\\cline{3-5}%\\addlinespace[0pt]\\midrule[1pt]\\addlinespace[0pt]\n&&$M=4$&$M=8$&$M=16$\\\\\n\\hline\n\\multirow{2}{*}{CMSSH}&{MAP}     &$  0.1928  $&$   0.1746 $& $     0.1950   $\\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}    & $0.1142$&$   0.1389    $&$    0.1320    $\\\\\n\\hline%\\addlinespace[0pt]\\midrule[0.5pt]\\addlinespace[0pt]\n\\multirow{2}{*}{SMH}&MAP        &${\\bf 0.2208}       $&$ {\\bf0.2784}  $&$ {\\bf0.3494} $\\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}    &$0.1258      $&$ {\\bf0.1800}   $&$ {\\bf0.3047} $\\\\\n\\hline%\\addlinespace[0pt]\\midrule[0.5pt]\\addlinespace[0pt]\n\\multirow{2}{*}{KSMH}&MAP        & $0.2207\\pm0.0039$& $ 0.2765\\pm 0.0052 $&$ 0.3108\\pm 0.0059 $\\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}    & ${\\bf 0.1264\\pm0.0013}$&$ 0.1782\\pm 0.0071 $&$ 0.2780\\pm 0.0118 $\\\\\n\\hline%\\addlinespace[0pt]\\midrule[0.5pt]\\addlinespace[0pt]\n\\multirow{2}{*}{RKSMH}&MAP & $0.2088\\pm0.0038$&$ 0.2559\\pm 0.0065 $&$ 0.3171\\pm 0.0075 $\\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}   &$0.1228        \\pm0.0008       $&$ 0.1740\\pm  0.0045 $&$ 0.2774\\pm 0.0106  $\\\\\n\\addlinespace[0pt]\\bottomrule[1pt]\n\\end{tabular}\n\\end{center}\n\\end{table}\n\n\\begin{table}[htb]\\small\n\\caption{Performance comparison for Image-Text retrieval on \\mbox{Flickr}}\\label{table:comp-flickr-cross-it}\\vspace{-0.5cm}\n\\begin{center}\n\\begin{tabular}{|c|c|c|c|c|}\n\\toprule[1pt]\\addlinespace[0pt]\n    \\multirow{2}{*}{Method}&  \\multirow{2}{*}{Measure}  &  \\multicolumn{3}{|c|}{Image query -- Text database}  \\\\\n\\cline{3-5}%\\addlinespace[0pt]\\midrule[1pt]\\addlinespace[0pt]\n&&$M=4$&$M=8$&$M=16$\\\\\n\\hline\n\\multirow{2}{*}{CMSSH}&{MAP}    &    $0.3723  $           &  $  0.3822  $ &$  0.4100$  \\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}    &     \t$0.3458 $         &     $   0.3503 $         &        $   0.4104$       \\\\\n\\hline%\\addlinespace[0pt]\\midrule[0.5pt]\\addlinespace[0pt]\n\\multirow{2}{*}{SMH}&MAP        &     $0.3463  $         &     $  0.3872  $      &  $  0.4159$ \\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}    &     \t$0.3451  $         &   $   0.4130 $            &    $  0.4100$         \\\\\n\\hline%\\addlinespace[0pt]\\midrule[0.5pt]\\addlinespace[0pt]\n\\multirow{2}{*}{KSMH}&MAP        &   ${\\bf0.4604 \\pm 0.0116}$       &  $   0.4747 \\pm  0.0136  $         & $   0.4718\\pm    0.0066$\\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}    &     \t${\\bf 0.3778  \\pm0.0052}  $         & $   0.4148  \\pm   0.0066  $              &  $ 0.4390\\pm  0.0111$ \\\\\n\\hline%\\addlinespace[0pt]\\midrule[0.5pt]\\addlinespace[0pt]\n\\multirow{2}{*}{RKSMH}&MAP        &     $0.4482 \\pm 0.0125  $         & $ {\\bf  0.4782   \\pm  0.0052}  $          & $ {\\bf 0.4865\\pm   0.0037}  $ \\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}    &    \t$0.3709  \\pm0.0038 $          &    $ {\\bf 0.4185   \\pm   0.0065}$           &    $ {\\bf 0.4690\\pm  0.0094} $\\\\\n\\addlinespace[0pt]\\bottomrule[1pt]\n\\end{tabular}\n\\end{center}\n\\end{table}\n\n\\begin{table}[htb]\\small\n\\caption{Performance comparison for Text-Image retrieval on \\mbox{Flickr}}\\label{table:comp-flickr-cross-ti}\\vspace{-0.5cm}\n\\begin{center}\n\\begin{tabular}{|c|c|c|c|c|}\n\\toprule[1pt]\\addlinespace[0pt]\n    \\multirow{2}{*}{Method}&  \\multirow{2}{*}{Measure}  &  \\multicolumn{3}{|c|}{Text query -- Image database}\\\\\n\\cline{3-5}%\\addlinespace[0pt]\\midrule[1pt]\\addlinespace[0pt]\n&&$M=4$&$M=8$&$M=16$\\\\\n\\hline\n\\multirow{2}{*}{CMSSH}&{MAP}      &${\\bf 0.4824}  $&$   {0.4829}  $& $    0.4712 $\\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}    & $0.3467 $&$   0.3616   $&$  {\\bf 0.5286 } $\\\\\n\\hline%\\addlinespace[0pt]\\midrule[0.5pt]\\addlinespace[0pt]\n\\multirow{2}{*}{SMH}&MAP &$0.3590  $&$   0.4056  $&$    0.4520 $\\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}     &$0.3447   $&$ {\\bf  0.4346 }  $&$   0.4460 $\\\\\n\\hline%\\addlinespace[0pt]\\midrule[0.5pt]\\addlinespace[0pt]\n\\multirow{2}{*}{KSMH}&MAP      & $0.4683   \\pm0.0146$&$    0.4849  \\pm     0.0119   $&$ 0.4860\\pm   0.0102 $\\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}   & $  {\\bf 0.3839   \\pm0.0054}  $&$   0.4260\\pm    0.0073     $&$   0.4537\\pm  0.0114 $\\\\\n\\hline%\\addlinespace[0pt]\\midrule[0.5pt]\\addlinespace[0pt]\n\\multirow{2}{*}{RKSMH}&MAP & $0.4610 \\pm0.0066 $&$   {\\bf 0.5013  \\pm   0.0081}    $&$   {\\bf 0.5098 \\pm   0.0050}$\\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}    &$0.3750   \\pm0.0057   $&$  0.4241   \\pm  0.0082    $&$  0.4751\\pm  0.0141  $\\\\\n\\addlinespace[0pt]\\bottomrule[1pt]\n\\end{tabular}\n\\end{center}\n\\end{table}\n\nFrom the tables, we can see that all three \\mbox{SMH} models outperform \\mbox{CMSSH} by a large margin on both data sets. Among our three models, \\mbox{RKSMH} performs the best on both data sets, indicating the effectiveness of \\textit{Laplacian} regularization. We also note that  \\mbox{KSMH} achieves performance similar to that of \\mbox{SMH} on the \\mbox{Wiki} data set and better performance than \\mbox{SMH} on the \\mbox{Flickr} data set, showing that the kernel extension is quite useful.\n\n%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Comparison for unimodel retrieval}\n\\label{smh:exps:results:uni}\n\nIn this section, we compare the four multimodal and two well-known unimodel hashing-based methods for unimodel retrieval.  It should be noted that multimodel hashing algorithms learn hash functions from both modalities whereas the unimodel hashing algorithms learn hash functions from only one modality. The results are summarized in Table~\\ref{table:comp-wiki-uni-ii}~\\&~\\ref{table:comp-wiki-uni-tt} for the \\mbox{Wiki} data set, and Table~\\ref{table:comp-flickr-uni-ii}~\\&~\\ref{table:comp-flickr-uni-tt} for the \\mbox{Flickr} data set.\n\n\\begin{table}[htb]\\small\n\\caption{Performance comparison for image retrieval on \\mbox{Wiki}}\\label{table:comp-wiki-uni-ii}\\vspace{-0.5cm}\n\\begin{center}\n\\begin{tabular}{|c|c|c|c|c|}\n\\toprule[1pt]\\addlinespace[0pt]\n    \\multirow{2}{*}{Method}&  \\multirow{2}{*}{Measure}  &  \\multicolumn{3}{|c|}{Image query -- Image database}  \\\\\n\\cline{3-5}%\\addlinespace[0pt]\\midrule[1pt]\\addlinespace[0pt]\n&&$M=4$&$M=8$&$M=16$\\\\\n\\hline\n\\multirow{2}{*}{SH}&{MAP}    & $0.1559$   &  $0.1545$&$ 0.1552 $ \\\\\n\\cline{2-5}%\n&{Precision}    &      $0.1084$         &        $0.1084$      &  $ 0.1083 $\\\\\n\\hline %\\addlinespace[0pt]\\midrule[0.8pt]\\addlinespace[0pt]\n\\multirow{2}{*}{CMSSH}&{MAP}    &    $0.1640  $           &  $    0.1683   $ &$ 0.1743$  \\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}    &     \t$0.1139  $         &     $    0.1171   $         &        $  0.1294 $       \\\\\n\\hline%\\addlinespace[0pt]\\midrule[0.5pt]\\addlinespace[0pt]\n\\multirow{2}{*}{SMH}&MAP        &     ${\\bf 0.1773}  $         &     $  {\\bf 0.1930} $      &  $  {\\bf 0.1903}$ \\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}    &     \t$ {\\bf 0.1178}  $         &   $ {\\bf 0.1352}  $            &    $  {\\bf 0.1536}$         \\\\\n\\hline%\\addlinespace[0pt]\\midrule[0.5pt]\\addlinespace[0pt]\n\\multirow{2}{*}{KSMH}&MAP        &   $0.1759        \\pm 0.0014    $       &  $0.1912\\pm 0.0031 $         & $0.1892\\pm   0.0019$ \\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}    &     \t$0.1173  \\pm0.0004  $         & $  0.1343 \\pm  0.0011  $              &  $   0.1533\\pm   0.0029$       \\\\\n\\hline%\\addlinespace[0pt]\\midrule[0.5pt]\\addlinespace[0pt]\n\\multirow{2}{*}{RKSMH}&MAP        &     $0.1747        \\pm0.0014       $         & $0.1848\\pm 0.0020$          & $0.1884\\pm0.0019$  \\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}    &    \t$0.1155        \\pm0.0006       $          &    $0.1324\\pm 0.0007$           &    $0.1512\\pm0.0022$         \\\\\n\\addlinespace[0pt]\\bottomrule[1pt]\n\\end{tabular}\n\\end{center}\n\\end{table}\n\n\\begin{table}[htb]\\small\n\\caption{Performance comparison for text retrieval on \\mbox{Wiki}}\\label{table:comp-wiki-uni-tt}\\vspace{-0.5cm}\n\\begin{center}\n\\begin{tabular}{|c|c|c|c|c|}\n\\toprule[1pt]\\addlinespace[0pt]\n    \\multirow{2}{*}{Method}&  \\multirow{2}{*}{Measure}  &  \\multicolumn{3}{|c|}{Text query -- Text database}\\\\\n\\cline{3-5}%\\addlinespace[0pt]\\midrule[1pt]\\addlinespace[0pt]\n&&$M=4$&$M=8$&$M=16$\\\\\n\\hline\n\\multirow{2}{*}{SH}&{MAP}  & ${\\bf 0.3068}$ & $0.3986$&$ 0.5590 $\\\\\n\\cline{2-5}%\n&{Precision}    &  $0.1084$           &$0.1086$&$ 0.1721 $\\\\\n\\hline %\\addlinespace[0pt]\\midrule[0.8pt]\\addlinespace[0pt]\n\\multirow{2}{*}{CMSSH}&{MAP}   &$0.3024   $&$    0.4737     $& $  0.5364 $\\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}    & $0.1739   $&$   0.2752      $&$   0.4179  $\\\\\n\\hline%\\addlinespace[0pt]\\midrule[0.5pt]\\addlinespace[0pt]\n\\multirow{2}{*}{SMH}&MAP      &$0.2850      $&$ 0.4461   $&$ 0.5563  $\\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}     &$0.1358      $&$ 0.2648   $&$ 0.5704 $\\\\\n\\hline%\\addlinespace[0pt]\\midrule[0.5pt]\\addlinespace[0pt]\n\\multirow{2}{*}{KSMH}&MAP        & $0.3066        \\pm0.0220    $&$ 0.4627\\pm  0.0173 $&$ 0.5590\\pm    0.0068 $\\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}   & $ {\\bf 0.1397   \\pm0.0041 } $&$  0.2742 \\pm    0.0226    $&$    0.5741\\pm 0.0217 $\\\\\n\\hline%\\addlinespace[0pt]\\midrule[0.5pt]\\addlinespace[0pt]\n\\multirow{2}{*}{RKSMH}&MAP       & $0.2891        \\pm0.0046       $&$ {\\bf 0.5078\\pm  0.0046} $&$ {\\bf 0.5697\\pm0.0041 } $\\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}    &$0.1328       \\pm0.0013      $&$ {\\bf 0.2786 \\pm  0.0144 } $&$ {\\bf 0.5927 \\pm 0.0143} $\\\\\n\\addlinespace[0pt]\\bottomrule[1pt]\n\\end{tabular}\n\\end{center}\n\\end{table}\n\n\n\\begin{table}[htb]\\small\n\\caption{Performance comparison for image retrieval on \\mbox{Flickr}}\\label{table:comp-flickr-uni-ii}\\vspace{-0.5cm}\n\\begin{center}\n\\begin{tabular}{|c|c|c|c|c|}\n\\toprule[1pt]\\addlinespace[0pt]\n    \\multirow{2}{*}{Method}&  \\multirow{2}{*}{Measure}  &  \\multicolumn{3}{|c|}{Image query -- Image database}  \\\\\n\\cline{3-5}%\\addlinespace[0pt]\\midrule[1pt]\\addlinespace[0pt]\n&&$M=4$&$M=8$&$M=16$\\\\\n\\hline\n\\multirow{2}{*}{SH}&{MAP}    &     $0.3743$          &  $0.3780$ &$0.3793  $\\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}    &       $0.3449$        &      $0.3449$       &$0.3449$ \\\\\n\\hline %\\addlinespace[0pt]\\midrule[0.8pt]\\addlinespace[0pt]\n\\multirow{2}{*}{CMSSH}&{MAP}    &    $0.4064  $           &  $   0.4262  $ &$ 0.4304$  \\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}    &     \t$0.3396   $         &     $ 0.3376  $         &        $  0.3424$       \\\\\n\\hline%\\addlinespace[0pt]\\midrule[0.5pt]\\addlinespace[0pt]\n\\multirow{2}{*}{SMH}&MAP        &     $0.3753 $         &     $   0.4326  $      &  $  0.4388$ \\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}    &     \t$0.3450 $         &   $   0.3786  $            &    $  0.4075$         \\\\\n\\hline%\\addlinespace[0pt]\\midrule[0.5pt]\\addlinespace[0pt]\n\\multirow{2}{*}{KSMH}&MAP        &   ${\\bf 0.4498   \\pm 0.0061 } $       &  $   0.4642 \\pm   0.0051  $         & $ 0.4606\\pm  0.0034$  \\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}    &     \t${\\bf 0.3746 \\pm0.0059 } $         & $ {\\bf 0.4095  \\pm   0.0103}   $              &  $  0.4342\\pm  0.0126$       \\\\\n\\hline%\\addlinespace[0pt]\\midrule[0.5pt]\\addlinespace[0pt]\n\\multirow{2}{*}{RKSMH}&MAP        &     $0.4390 \\pm0.0062 $         & $ {\\bf  0.4726  \\pm 0.0055}   $          & $ {\\bf  0.4783\\pm    0.0029}$  \\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}    &    \t$0.3668 \\pm0.0050 $          &    $  0.4020   \\pm   0.0070 $           &    $ {\\bf  0.4403\\pm   0.0082}$         \\\\\n\\addlinespace[0pt]\\bottomrule[1pt]\n\\end{tabular}\n\\end{center}\n\\end{table}\n\n\\begin{table}[htb]\\small\n\\caption{Performance comparison for text retrieval on \\mbox{Flickr}}\\label{table:comp-flickr-uni-tt}\\vspace{-0.5cm}\n\\begin{center}\n\\begin{tabular}{|c|c|c|c|c|}\n\\toprule[1pt]\\addlinespace[0pt]\n    \\multirow{2}{*}{Method}&  \\multirow{2}{*}{Measure} &  \\multicolumn{3}{|c|}{Text query -- Text database}\\\\\n\\cline{3-5}%\\addlinespace[0pt]\\midrule[1pt]\\addlinespace[0pt]\n&&$M=4$&$M=8$&$M=16$\\\\\n\\hline\n\\multirow{2}{*}{SH}&{MAP}    & $0.3753$ & $0.3756$&$ 0.3752 $\\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}    &      $0.3449$         &$0.3449$&$0.3449$\\\\\n\\hline %\\addlinespace[0pt]\\midrule[0.8pt]\\addlinespace[0pt]\n\\multirow{2}{*}{CMSSH}&{MAP}  &$0.4762 $&$   0.5197   $&$  {\\bf 0.5832 } $ \\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}  & $0.3824  $&$   0.3962   $&$   0.4112 $\\\\\n\\hline%\\addlinespace[0pt]\\midrule[0.5pt]\\addlinespace[0pt]\n\\multirow{2}{*}{SMH}&MAP &$0.3769 $&$    0.4650   $&$   0.5031 $\\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}    &$ 0.3449 $&$    0.3838   $&$   0.4356  $\\\\\n\\hline%\\addlinespace[0pt]\\midrule[0.5pt]\\addlinespace[0pt]\n\\multirow{2}{*}{KSMH}&MAP       & $ {\\bf 0.4866      \\pm0.0135}$&$ 0.5132  \\pm    0.0098    $&$ 0.5177\\pm   0.0095  $\\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}     & ${\\bf 0.3839   \\pm0.0062 } $&$    0.4342  \\pm   0.0121   $& $ 0.4760\\pm  0.0112  $\\\\\n\\hline%\\addlinespace[0pt]\\midrule[0.5pt]\\addlinespace[0pt]\n\\multirow{2}{*}{RKSMH}&MAP      & $0.4723  \\pm0.0153  $&$ {\\bf 0.5245  \\pm  0.0103 }     $&$   0.5441\\pm  0.0068  $\\\\\n\\cline{2-5}%\\addlinespace[0pt]\\cmidrule[0.5pt]{2-5}\\addlinespace[0pt]\n&{Precision}       &$0.3777  \\pm 0.0036 $&$  {\\bf 0.4394 \\pm   0.0073 }    $&$ {\\bf  0.5117\\pm  0.0127 }  $\\\\\n\\addlinespace[0pt]\\bottomrule[1pt]\n\\end{tabular}\n\\end{center}\n\\end{table}\n\nSimilar to the results of crossmodal retrieval, our models outperform \\mbox{CMSSH} on both data sets and the performance gap is larger on the \\mbox{Flickr} data set. As expected, \\mbox{RKSMH} achieves the best performance among our methods and \\mbox{KSMH} is better than \\mbox{SMH}. Note that our methods perform better than one state-of-the-art unimodal hashing methods, namely, \\textit{spectral hashing}, indicating that information from other modalities can help to learn good hash codes for unimodal retrieval. As a result, \\mbox{SMH}, especially \\mbox{RKSMH}, is also very useful for unimodal retrieval systems.\n\n% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %\n\\section{Conclusion}\n\\label{smh:conclusion}\n\nIn this chapter, we have proposed spectral multimodal hashing (\\mbox{SMH}) under the framework of multimodal hashing, the goal of which is to perform similarity search on data of multiple modalities. \\mbox{SMH} learns the hash codes through spectral analysis of the modality correlation. Experimental results show that our \\mbox{SMH} model outperforms the state-of-the-art methods. %However, \\mbox{SMH} has an apparent limitation, that is, it is only for the aligned data which may not be available in some applications. \n\nIn the future, we wish to relax the data alignment assumption of SMH and develop more general multimodal hashing methods. In addition, we would like to apply SMH to other applications such as multimodal medical image registration.%In the next chapter, we propose a new multimodal hashing model for graph data which is more general than aligned data.\n\n", "meta": {"hexsha": "bbda188b19e357871dfa11146bb894e1c7b35066", "size": 88607, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis_zhen/TexFile/4_smh.tex", "max_stars_repo_name": "yzhen-li/paper", "max_stars_repo_head_hexsha": "4043ea31f634669c46cc46318778e1a8317ca761", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thesis_zhen/TexFile/4_smh.tex", "max_issues_repo_name": "yzhen-li/paper", "max_issues_repo_head_hexsha": "4043ea31f634669c46cc46318778e1a8317ca761", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-05-19T06:22:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-19T07:15:40.000Z", "max_forks_repo_path": "thesis_zhen/TexFile/4_smh.tex", "max_forks_repo_name": "zhenyisx/paper", "max_forks_repo_head_hexsha": "4043ea31f634669c46cc46318778e1a8317ca761", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 82.3485130112, "max_line_length": 1465, "alphanum_fraction": 0.6583904206, "num_tokens": 32296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3334214526167139}}
{"text": "\\documentclass[../main.tex]{subfiles}\n\n\\begin{document}\n\n\\begin{abstract}\nThis paper presents ACROMUSE, a novel genetic algorithm (GA) which adapts crossover, mutation, and selection\nparameters. ACROMUSEs objective is to create and maintain a diverse population of highly-fit (healthy) individuals,\ncapable of adapting quickly to fitness landscape change and well-suited to the efficient optimization of multimodal\nfitness landscapes. A new methodology is introduced for determining standard population diversity (SPD) and an original\nmeasure of healthy population diversity (HPD) is proposed. The SPD measure is employed to adapt crossover and mutation,\nwhile selection pressure is controlled by adapting tournament size according to HPD. In addition to selection pressure\ncontrol, ACROMUSE tournament selection selects individuals according to healthy diversity contribution rather than\nfitness. This proposed selection mechanism simultaneously promotes diversity and fitness within the population. The\nperformance of ACROMUSE is evaluated using various multimodal benchmark functions. Statistically significant results\nare presented comparing ACROMUSEs fitness and diversity performance to that of several other GAs. By maintaining a\ndiverse population of healthy individuals, ACROMUSE responds to fitness landscape change by restoring better fitness\nscores faster than other GAs. Analysis of the adaptive operators illustrates that the key benefit of ACROMUSE is the\nsynergy of the operators working together to achieve an effective balance between exploration and exploitation.\n\\end{abstract}\n\n\\begin{mdframed}\n\\fullcite{6036171}\n\\end{mdframed}\n\nPremature population convergence about a local optimum is a common problem. It is usually caused by one of the\nfollowing reasons.\n\n\\begin{enumerate}\n\t\\item \\textbf{Incorrect application of selection pressure:} Whereby a ``super-performer'' in the population\n\tdominates the selection procedure and eliminates much of the population's diversity.\n\t\\item \\textbf{Too low mutation rate:} Diversity is lost trough selection and not recovered via mutation.\n\t\\item \\textbf{Loss of crossover efficacy:} As a population becomes more converged, recombination of similar\n\tindividuals causes similar offspring (inbreeding).\n\\end{enumerate}\n\nThis papers presents \\textbf{ACROMUSE} which adapts the crossover, mutation and selection parameters. The main goal is\nmaintaining a diverse population of healthy individuals. It employs two measures to of population diversity.\n\n\\begin{itemize}\n\t\\item \\textbf{Standard Population Diversity (SPD)} \\\\\n\tThis measure describes the population's solution space diversity. The SPD measure is used to control mutation and\n\tcrossover. Crossover employs SPD to divide the population into an \\textbf{exploration section} and an\n\t\\textbf{exploitation section}. The sizes of these sections are controlled by the SPD measure.\n\t\\item \\textbf{Healty Population Diversity (HPD)} \\\\\n\tThis measure describes a population’s solution space diversity from a fitness perspective, i.e., a measure of the\n\tdiversity of healthy individuals. HPD is used to regulate selection pressure. Tournament size is reduced when HPD\n\tis low permitting lower-fitness individuals to reproduce.\n\\end{itemize}\n\nMaintaining a diverse population is very important for GA search. Not only does high-genetic diversity increase the\npopulation's search coverage but it also endows the population with a degree of robustness in case of environmental\nchange.\n\n\\section{SPD \\& HPD}\n\n\\subsection{Standard Population Diversity (SPD)}\nThe SPD describes the level of variation in a population. Genetic diversity is a very important component of\nevolutionary exploration since a GA can only search the space offered to it by the genes present in the population.\n\nTraditional GA's can suffer from early convergence. Individuals converge to a relatively fit area trough repeated\nselection of similar individuals. This is of course undesirable when it's only a local optimum.\n\nHigh mutation rate can scatter individuals to introduce novel genetic information. ACROMUSE implements such an adaptive\nmutation operator. The trade-off is that high mutation rates are generally destructive from a fitness perspective.\n\n\\subsection{Calculating SPD}\n\nSPD is calculated by finding the position of the average individual within the population and summing the gene-wise\nEuclidean distances from this average point to the location of each individual. ACROMUSE’s population consists of $P$\nindividuals ($G_1$ to $G_P$) where each individual consist of $N$ genes: $G_i = (G_{i,1} \\mathellipsis G_{i,N})$.\n\n\\begin{equation}\nG_n^{\\text{avg}} = \\frac{1}{P} \\sum_{i=1}^P G_{i,n}\n\\end{equation}\n\nA simple summation for SPD is not used because is cannot be normalized, leading to the SPD measure varying immensely\nfor different problems and populations. Therefore, a gene-wise standard deviation is performed.\n\n\\begin{equation}\n\\text{SPD} = C_v(G^{\\text{avg}}) = \\frac{1}{N} \\sum_{j=1}^N \\left( \\frac{\\sigma (G^{\\text{avg}}_j)}{G^{\\text{avg}}_j}\n\\right)\n\\end{equation}\n\n\\subsection{Healthy Population Diversity (HPD)}\nWhat SPD lacks is that it does not account for the position of individuals in the fitness space. It is possible that\nthe populations appears diverged, but that most highly-fit individuals lie within a converged localized area. Healthy\nindividuals are population members that achieve good fitness scores. HPD is a a fitness-weighted measure of population\ndiversity. It differs from SPD in that each individual's contribution to diversity in the solution space is influenced\naccording to its fitness.\n\n\\subsection{Calculating HPD}\nIn contrast to SPD that exclusively considers the solution space, HPD merges both fitness and solution spaces by\nweighting each individual's distance contribution in the solution space according to its score in the fitness space.\n\nHPD is calculated by finding the position of the weighted average individual within the population and summing the\ngene-wise fitness-weighted distances from this weighted average point to the location of each individual.\n\n\\begin{equation}\n\\text{HPD} = C_V(G^{\\text{W.avg}}) = \\frac{1}{N} \\sum_{j=1}^N \\left( \\frac{\\sigma\n(G^{\\text{W.avg}}_j)}{G^{\\text{W.avg}}_j} \\right)\n\\end{equation}\n\nHere, $G^{\\text{W.avg}}$ is the weighted average individual, computed as the fitness-weighted gene-wise average across\nall individuals.\n\n\\section{Adaptive Operation Implementation}\n\nThe performance or a traditional GA is highly dependent on the choice of fixed parameters. In contrast, adaptive GA's\nparameters vary according to population statistics. Here, premature convergence is prevented by modifying the\ncrossover, mutation and selection operators according tot the population's diversity.\n\n\\subsection{Adaptive Crossover}\n\nCrossover generally converges the population because no new genetic information is  added. The technique of adaptively\nmutating individuals that do not undergo crossover divides the population into two sections:\n\n\\begin{enumerate}\n\t\\item Exploitation Section\n\t\\item Exploration Section\n\\end{enumerate}\n\nThe size of each section is determined by the SPD, with a larger exploration section for low SPD or and larger\nexploitation section for a high SPD. The crossover probability is given by $P_c$.\n\n\\begin{equation}\nP_c = \\bigg[ \\left( \\frac{\\text{SPD}}{\\text{SPD}_\\text{max}} \\cdot (K_2 - K_1) \\right) + K_1 \\bigg]\n\\end{equation}\n\n\\subsection{Adaptive Mutation}\nThe adaptive mutation rate $P_m$ is an average of two mechanisms: SPD controlled mutation ($P_m^{\\text{Diversity}}$)\nand parent fitness controlled mutation ($P_m^{\\text{Fitness}}$)\n\n\\begin{equation}\nP_m^{\\text{Diversity}} = \\frac{\\text{SPD}_\\text{max} - \\text{SPD}}{\\text{SPD}_\\text{max}} \\cdot K\n\\end{equation}\n\\begin{equation}\nP_m^{\\text{Fitness}} = \\left( \\frac{f_{\\text{max}} - f}{f_{\\text{max}} - f_{\\text{min}}} \\right) \\cdot K\n\\end{equation}\n\\begin{equation}\n\tP_m = \\frac{P_m^{\\text{Diversity}}  + P_m^{\\text{Fitness}}}{2}\n\\end{equation}\n\n\\subsection{Adaptive Selection}\n\n\\subsubsection{Limitations Adaptive Crossover and Mutation} Most mutations have a negative impact on fitness. This is\nbecause, for most problems, high-fitness areas are sparse in the fitness landscape. A nonadaptive selection operator\ncontinued to choose from the same converged cluster of highly fit individuals (exploitation segment of the population),\nneglecting the less-fit individuals scattered throughout the fitness landscape by the exploration segment.\n\n\\subsubsection{Rationale for Adaptive Selection} From a selection perspective, a diverged parent population does not\nautomatically result in diverged offspring.  A tournament size equal to the population size equates to elitism, while a\ntournament size of 1 equates to random selection. Therefore, decreasing tournament size in a converged population\nprovides outlying individuals with a chance of selection. The SPD measure is unfortunately not a good indicator, as\nselection pressure will increase in case of high SPD, but selection will return to a converged high fitness section due\nto low HPD.\n\n\\subsubsection{Proposed Adaptive Selection Operator} The HPD measure controls tournament size. When the population is\nconverged from a fitness-based perspective, low-fitness outliers are offered a greater chance of selection.\n\n\\begin{equation}\n\\text{Tsize} = \\left\\lceil \\frac{\\text{HPD}}{\\text{HPD}_\\text{max}} \\cdot \\text{Tsize}_\\text{max} \\right\\rceil\n\\end{equation}\n\n\\subsubsection{Traditional Tournament Selection}\n\nTournament selection involves selecting a number ($\\text{Tsize}$) of individuals randomly from the population, with the\nbest individual from this group being selected as a parent. The best individual is the one with the highest fitness.\n\n\\subsubsection{Adaptive Tournament Selection} Rather than selecting the individual with the highest fitness, the individual\nwith the largest healthy diversity contribution is selected. This ensures that selection recognizes both diversity\ncontribution and fitness in choosing the best individuals for reproduction.\n\n\\section{GA Review}\n\n\\begin{itemize}\n\t\\item \\textbf{Traditional Genetic Algorithm (TGA)} \\\\\n\tThe TGA does not employ adaptive operators. Default parameters are optimal in many cases but present a significant\n\trisk of premature convergence.\n\n\t\\item \\textbf{Fitness Sharing (FS)} \\\\\n\tIndividuals within a certain ``share-radius'' of each other have their fitness penalized according to a sharing\n\tfunction. This limits the number of individuals that can successfully occupy a niche and, therefore, encourages\n\texploration of other potential high-fitness areas.\n\n\t\\item \\textbf{Deterministic Crowding (DC)} \\\\\n\tDC is an elegant, elitist algorithm which insists that an offspring must be better than its most genotypically-\n\tsimilar parent in order to progress to the next generation.\n\n\t\\item \\textbf{CHC GA} \\\\\n\tIndividuals are randomly selected for crossover, therefore, giving every individual an equal chance of\n\treproduction. However, crossover is only allowed if individuals are sufficiently different genotypically. If no\n\tcrossover is possible at the current threshold, the threshold is decremented and\n\tcrossover is re-attempted.\n\n\t\\item \\textbf{Boltzmann Roulette Selection (BRS)} \\\\\n\tThis method begins search with a lowselection pressure and increases the pressure steadily according to a\n\tpredefined schedule. This approach affords greater exploration in the early stages of search, with increased\n\texploitation later.\n\\end{itemize}\n\n\\section{Conclusion}\nFor the multimodal functions employed, ACROMUSE outperforms all other investigated algorithms with regard to locating\nand recovering the best solution in the shortest time. For the multimodal functions employed, ACROMUSE outperforms all\nother investigated algorithms with regard to locating and recovering the best solution in the shortest time.\nMaintaining a diverse population is important for increasing population search coverage and for dealing with fitness\nlandscape change. Results demonstrate that through maintaining high HPD, ACROMUSE copes well with environmental change,\nrestoring better fitness scores faster than all other investigated algorithms.\n\n\\begin{itemize}\n\n\t\\item \\textbf{Traditional Genetic Algorithm (TGA)} \\\\\n\tTGA exhibits all the negative side effects associated with strong, nondynamic selection pressure and low- static\n\tmutation rates (i.e., loss of diversity/premature convergence at local optima).\n\n\t\\item \\textbf{Fitness Sharing (FS)} \\\\\n\tFS fails to maintain the same levels of SPD or HPD as ACROMUSE.\n\n\t\\item \\textbf{Deterministic Crowding (DC)}\n\tDC exhibits good fitness results, comparable to those obtained from FS, though DC diversity is lost much more\n\tsteadily than with FS or ACROMUSE, due to genetic drift inherent within the algorithm. In addition to this drift,\n\tDC’s inability to introduce novel diversity results in poor performance in the event of environmental change.\n\n\t\\item \\textbf{CHC GA} \\\\\n\tCHC with its population re-initialization mechanism performs competitively (fitness and diversity-wise) with the\n\tother niching algorithms, particularly in introducing novel diversity after fitness landscape change.\n\n\t\\item \\textbf{Boltzmann Roulette Selection (BRS)} \\\\\n\tBRS demonstrates good performance in escaping local optima in the initial stages of search but can still become\n\ttrapped at later generations, particularly after fitness landscape change. Indeed, BRS was not designed to maintain\n\tlong-term diversity.\n\n\\end{itemize}\n\n\n\\end{document}\n", "meta": {"hexsha": "0f5199393aabba1a50000f653153cc012e308d27", "size": 13539, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "subfiles/healthy_population_diversity.tex", "max_stars_repo_name": "JDevlieghere/Genetic-Algorithms", "max_stars_repo_head_hexsha": "cfdf4e890801b82be1301361b075c011b8c7768b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2015-01-16T21:26:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-10T16:25:22.000Z", "max_issues_repo_path": "subfiles/healthy_population_diversity.tex", "max_issues_repo_name": "JDevlieghere/Genetic-Algorithms", "max_issues_repo_head_hexsha": "cfdf4e890801b82be1301361b075c011b8c7768b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-01-20T12:10:33.000Z", "max_issues_repo_issues_event_max_datetime": "2015-01-20T13:03:09.000Z", "max_forks_repo_path": "subfiles/healthy_population_diversity.tex", "max_forks_repo_name": "JDevlieghere/Genetic-Algorithms", "max_forks_repo_head_hexsha": "cfdf4e890801b82be1301361b075c011b8c7768b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2016-08-11T13:19:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-20T00:41:31.000Z", "avg_line_length": 57.3686440678, "max_line_length": 123, "alphanum_fraction": 0.8022010488, "num_tokens": 3010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3334214440681949}}
{"text": "% Results\r\nThe results of the training process are presented in this chapter. We begin by first outlining the training network architecture and training process on simulated XANES in section \\ref{sec:nn-sim-data}. Then, we discuss the plan and current status on expanding the model to make solid predictions on experimental data.\r\n\r\n\\section{Training with Simulation Data} \\label{sec:nn-sim-data}\r\n\r\nThe 1000 simulated XANES spectra were first loaded into a Pandas dataframe \\cite{pandas-1} \\cite{pandas-2} of shape $ 1000\\times82 $. Each of the 82 columns represents a discrete energy value, and each row represents the absorption coefficient for a given spectrum at those energies. The dataset was split into training and testing groups according to an 80-20 random split, respectively. All absorption columns were then scaled via the standard scalar (\\ref{z-score}), and the training labels were scaled via a min-max scaler (\\ref{eqn:min-max-scaler}). First, the model was trained to predict four descriptors: the mean squared displacement (MSD), the mean bond length distance, the standard deviation of the bond length distributions, and the skew of the bond length distribution. Note that the standard deviation is equal to the square root of the MSD. This feature was only included preliminarily in order to better understand the correlation in the network's predictions. \r\n\r\n\\bgroup\r\n\\def\\arraystretch{1.5}%  1 is the default, change whatever you need\r\n\\begin{table}[h!]\r\n    \\centering\r\n    \\begin{tabular}{|l|l|l|}\r\n    \\hline\r\n    \\textbf{Layer  Type }   & \\textbf{ Output Shape}  & \\textbf{\\# of Parameters} \\\\ \\hline\r\n    Normalization  & (None, 82)    & 165                  \\\\ \\hline\r\n    Dense          & (None, 128)   & 10,624               \\\\ \\hline\r\n    Dense          & (None, 128)   & 16,512               \\\\ \\hline\r\n    Dense          & (None, 512)   & 25,088               \\\\ \\hline\r\n    Reshape        & (None, 8, 64) & 0                    \\\\ \\hline\r\n    1D-Convolution & (None, 6, 32) & 6,176                \\\\ \\hline\r\n    Dropout        & (None, 6, 32) & 0                    \\\\ \\hline\r\n    1D-Max-Pooling & (None, 3, 32) & 0                    \\\\ \\hline\r\n    Flatten        & (None, 96)    & 0                    \\\\ \\hline\r\n    Dense          & (None, 128)   & 12,416               \\\\ \\hline\r\n    Dense          & (None, 48)    & 6,192                \\\\ \\hline\r\n    Dense          & (None, 512)   & 25,088               \\\\ \\hline\r\n    Flatten        & (None, 512)   & 0                    \\\\ \\hline\r\n    Dense          & (None, 4)     & 513                  \\\\ \\hline\r\n    \\end{tabular}\r\n    \\caption[NN-Architecture Optimized for Simulations]{The model architecture for the network trained entirely on simulation data (which performed poorly on experimental data) relies primarily on affine (Dense) and convolutional layers. The model includes 108,966 total parameters, 108,801 of which are trainable.}\r\n    \\label{tb:nn-arch-sims}\r\n\\end{table}\r\n\\egroup\r\n\r\n\r\n\\begin{figure}\r\n    \\centering\r\n    \\includegraphics[width=\\linewidth]{Chapters/Figures/pa_train-test-fixed.png}\r\n    \\caption[Simulation Test Set Predictions]{One configuration of the trained neural network includes four output nodes: MSD, Sigma, Mean, and Kurtosis. Sigma is the square root of the MSD and was included during training to confirm the patterns recognized by the network. Each point in each subplot represents a FEFF simulated spectrum in the test set. For each spectrum, the y-axis represents the MSD value predicted by the NN, and the x-axis represents the true MSD (label) for that spectrum. Hence, points on the $ y=x $ red line are perfect predictions.}\r\n    \\label{fig:train-test-split-all4}\r\n\\end{figure}\r\n\r\n\\section{Experimental Data} \\label{ch:results}\r\n\r\nDue to the visible differences between simulation and experimental data discussed in chapter 2, training a neural network entirely on simulation data and then making predictions on experimental data is unlikely to provide quality results. Using the trained network from Table (\\ref{tb:nn-arch-sims}) that predicted the test set values in Figure \\ref{fig:train-test-split-all4}, we predicted the MSD values from two experimental spectra. On the unpublished IMASC data, the network predicted an MSD of $0.0003724~\\text{\\AA}^2$ instead of the EXAFS equation fitted value of ${\\sigma^2=0.0102(8)~\\text{\\AA}^2}$. This poor prediction suggests the network considers the experimental spectrum to look most similar to the lowest disorder FEFF spectra; the model is not generalizing to understand the disorder encoded in the spectral shape. In order to rectify this, we turn to data augmentation and include various forms of augmented experimental spectra in the training process. This approach is the topic of the following sections.\r\n\r\n\r\n\\begin{figure}\r\n    \\centering\r\n    \\includegraphics[width=\\linewidth]{Chapters/Figures/quality-of-interpolation-skinny.pdf}\r\n    \\caption[Experimental Data Interpolation]{The experimental data is measured as a function of different energy values than those on which the neural network is trained. Consequently, the experimental spectrum must be mapped onto the proper energy mesh via linear interpolation.}\r\n    \\label{fig:interpolation-skinny}\r\n\\end{figure}\r\n\r\n\\subsection{Data Augmentation}\r\nWhile there is ample data for training and predicting on exclusively simulation data, we only have two experimental spectra. In order to create more training and testing data for the neural network, two types of data augmentation were utilized: Gaussian noise inclusion and horizontal spectral shifting. While the motivation for utilizing data augmentation is to expand the size of the experimental training and testing set, the neural network must be trained to recognize the augmentation types prior to training or testing on the experimental data. As such, both the FEFF simulated dataset and experimental dataset are augmented.\r\n\r\nNoise is artificially injected into the spectra by randomly shifting each absorption coefficient vertically. The shifted value for each energy level is selected from a Gaussian distribution with standard deviation $ \\sigma=0.01 $. An exaggerated example of the injected noise is shown in Figure \\ref{fig:data-aug-gauss-noise}.\r\n\r\n\\begin{figure}[h!]\r\n    \\centering\r\n    \\includegraphics[width=.75\\linewidth]{Chapters/Figures/gaussian-noise-data-aug.pdf}\r\n    \\caption[Data Augmentation: Gaussian Noise]{Gaussian noise is added to the spectra to increase the variance of the training data. This helps the network to learn the low-level features of the spectra and ignore artifacts not caused by the structural disorder. For demonstration purposes, the scale of the noise in this figure has been increased beyond what was used in training.}\r\n    \\label{fig:data-aug-gauss-noise}\r\n\\end{figure}\r\n\r\nThe second form of data augmentation utilizes horizontal shifts. While this is common for signal processing and time series analysis, the inclusion here is more controversial. In XAFS, the edge location is dependent on the oxidation/reduction state of the species. Shifting the horizontal location is akin to shifting the species of the model; however, the neural network is not being tasked to determine the oxidation state of the sample. Instead, the model is merely tasked with predicting the mean squared displacement of the nanoparticle's bond lengths. The hypothesis is that the disorder information is encoded throughout the entire XANES spectrum, not from just a simple feature such as the edge placement.  \r\n\r\n\\begin{figure}[h!]\r\n    \\centering\r\n    \\includegraphics[width=.75\\linewidth]{Chapters/Figures/horz-shift-3way.pdf}\r\n    \\caption[Data Augmentation: Horizontal Shift]{In order to train the network to predict disorder from the overall shape of the spectra---as opposed to fixating on the edge location---we introduce horizontal-shift as a data augmentation technique.}\r\n    \\label{fig:data-aug-hor}\r\n\\end{figure}\r\n\r\n\\subsection{Transfer Learning}\r\nIn building the transfer learning model, we opted to begin with a new network architecture, which can be found in Table (\\ref{tab:meta-1}). We hypothesized that applying convolutional layers before any affine layers may lead to a more consistent prediction between simulation and experimental spectra.\r\n\r\n\\begin{figure}\r\n    \\centering\r\n    \\includegraphics[width=\\linewidth]{Chapters/Figures/transfer-learning-breakdown.pdf}\r\n    \\caption[Transfer Learning Process]{The allocation of training and testing data is summarized above. At each stage, the network architecture remains unchanged; however, some of the network's parameters are retrained on new data. The different sets of data are color-coded for readability. Note that the network is never trained on the original experimental data---it is only used for the final stage of testing.}\r\n    \\label{fig:transfer-learning-databreakdown}\r\n\\end{figure}\r\n\r\n\\bgroup\r\n\\def\\arraystretch{1.5}\r\n\\begin{table}[]\r\n    \\centering\r\n        \\begin{tabular}{|l|l|l|l|}\r\n        \\hline\r\n        \\multicolumn{1}{|c|}{\\textbf{Name}} & \\multicolumn{1}{c|}{\\textbf{Type}} & \\multicolumn{1}{c|}{\\textbf{\\# Parameters}} & \\multicolumn{1}{c|}{\\textbf{Output Shape}} \\\\ \\hline\r\n        normalization\\_input                & InputLayer                         & 0                                           &                                            \\\\ \\hline\r\n        normalization                       & Normalization                      & 165                                         & None, 82                                   \\\\ \\hline\r\n        reshape                             & Reshape                            & 0                                           & None, 82, 1                                \\\\ \\hline\r\n        conv1                               & Conv1D                             & 128                                         & None, 82, 32                               \\\\ \\hline\r\n        max\\_pooling1d                      & MaxPooling1D                       & 0                                           & None, 41, 32                               \\\\ \\hline\r\n        conv2                               & Conv1D                             & 3104                                        & None, 39, 32                               \\\\ \\hline\r\n        max\\_pooling1d\\_1                   & MaxPooling1D                       & 0                                           & None, 19, 32                               \\\\ \\hline\r\n        flatten                             & Flatten                            & 0                                           & None, 608                                  \\\\ \\hline\r\n        dense1                               & Dense                              & 58464                                       & None, 96                                   \\\\ \\hline\r\n        dout                                & DropOut                            & 0                                           & None, 96                                   \\\\ \\hline\r\n        dense2                              & Dense                              & 30264                                       & None, 312                                  \\\\ \\hline\r\n        output                              & Dense                              & 313                                         & None, 1                                    \\\\ \\hline\r\n    \\end{tabular}\r\n    \\caption{A new network architecture was constructed for the transfer learning process. The new network only has one output node, representing the MSD of the input spectrum.}\r\n    \\label{tab:meta-1}\r\n\\end{table}\r\n\\egroup\r\n\r\n\r\nOur approach for applying transfer learning involves two stages of fine-tuning. First, we primarily train the model on FEFF-simulated spectra, selecting an architecture and hyperparameters which are likely to be compatible with fine-tuning. We achieve this by weighting the validation set heavily (around $ 10\\% $) with augmented experimental spectra and choosing a model which predicts unseen data-augmented experimental spectra as well as it predicts unseen simulated FEFF spectra. The training loss curves and selection process can be found in Figure \\ref{fig:meta-1-sweep-loss}. One concern with this approach is that we are injecting biases into our model selection; however, we take this into account through the utilization of a third, unseen test set and the fact that the model does not update its parameters based on its validation set predictions. When training a model in machine learning, the parameters are continuously updated until a minimum is reached in the loss function. While the loss landscape will have a global minimum, it also contains local minima, some of which will be more agnostic to the differences in experimental spectra and be better candidates for transfer learning. In this first stage of learning, the intention is to teach the model to find broad predictive features from the simulation set while selecting a model at a local minimum that is likely to be a successful transfer-learning candidate. \r\n\r\n\r\n\\begin{figure}[h!]\r\n    \\centering\r\n    \\includegraphics[width=\\linewidth]{Chapters/Figures/10-sweep.png}\r\n    \\caption[Hyperparamater Sweep: Cost Curve]{The validation cost (mean squared error) for 10 out of the 50 hyperparameter combinations searched in this sweep are plotted above. Most hyperparameters result in a loss curve stabilizing around 0.08, which is significantly higher than the training cost (not shown) that stabilized around 0.01. A few of the validation loss curves, instead, stabilized around 0.01 (dulcet-sweep-41 and deep-sweep-40). Because the validation set is heavily weighted with augmented experimental spectra, these two spectra are likely to be good candidates for transfer learning onto experimental data.}\r\n    \\label{fig:meta-1-sweep-loss}\r\n\\end{figure}\r\n\r\n\\begin{figure}[h!]\r\n    \\centering\r\n    \\includegraphics[width=\\linewidth]{Chapters/Figures/new-hyperparameter-sweep-meta-1.png}\r\n    \\caption[Hyperpamater Sweep: Graphical Representation]{The hyperparameters are obtained through a ``sweep,'' where the entire training process (20 epochs) is repeated with different hyperparameters each time. The hyperparameter training process and figure generation was conducted with the aid of \\cite{wandb}. Training cost was measured with mean squared error.}\r\n    \\label{fig:meta-1-sweep-params}\r\n\\end{figure}\r\n\r\n\r\n\\begin{figure}[h!]\r\n    \\centering\r\n    \\includegraphics[width=\\linewidth]{Chapters/Figures/best-params-meta1.png}\r\n    \\label{fig:meta-1-best}\r\n    \\caption[Learning Curve for the best hyperparameters]{Both iterations of the training process were run with identical network architectures and hyperparameters; however, these two runs have significantly different validation losses. The discrepancy is due to the random weights initialization process. We mitigate this problem by setting global random seeds throughout the training process to select consistent pseudo-random values. The slight difference in initial parameters causes one iteration to become ``stuck'' in a different local minimum, which performed similarly with the training set but made substantially worse predictions on the validation set. The goal of the first stage of the transfer learning process is to identify hyperparameters that will lead to the best transfer learning candidates.}\r\n\\end{figure}\r\n\r\nThe next stage of transfer learning seeks to teach the model to ignore noise and focus on the broader shape of the spectrum. We achieve this by freezing the early stages of the model and retraining the later parameters on a new dataset comprised primarily entirely of data-augmented spectra. Often, models are trained with the augmented dataset in the initial stage, which helps act as a form of regularization. In the case of transfer learning, however, applying this regularization so early on in the process may lead to undesirable local minima for which transfer learning onto the experimental dataset would be impossible. By applying an initial stage of fine-tuning to a well-tuned base model, we increase the likelihood of a successful second fine-tuning stage.\r\n\r\nThe last stage of the fine-tuning process is to freeze even more layers and reduce the learning rate, then train the model using all of the data-augmented experimental spectra. If the process is successful, the model will have learned to predict the MSD and ignore horizontal and Gaussian noise in the spectra from the first stage. In this way, we have increased the number of possible training samples to use for the final fine-tuning stage from one to many, allowing us to withhold both of the un-altered experimental spectra from the training process and use them to evaluate the success of the transfer learning process. A visualization and specific breakdown of which data is allocated into each stage of the training process can be found in Figure \\ref{fig:transfer-learning-databreakdown}.\r\n\r\nAs of the completion of this thesis, the transfer learning process is still ongoing. The first stage of training (as depticted in Figure \\ref{fig:transfer-learning-databreakdown}) is complete, whereas stage two and stage three are the subject on ongoing work and discussed in Chapter 5.\r\n\r\n\r\n\r\n", "meta": {"hexsha": "530f6ef4fda1aa20fa5a704626d1f74ec95067a3", "size": 17270, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapters/Chapter4.tex", "max_stars_repo_name": "jthaller/BNL_Thesis", "max_stars_repo_head_hexsha": "1b748993f7ed76de12972f1bc75fedeebee8b7d5", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapters/Chapter4.tex", "max_issues_repo_name": "jthaller/BNL_Thesis", "max_issues_repo_head_hexsha": "1b748993f7ed76de12972f1bc75fedeebee8b7d5", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapters/Chapter4.tex", "max_forks_repo_name": "jthaller/BNL_Thesis", "max_forks_repo_head_hexsha": "1b748993f7ed76de12972f1bc75fedeebee8b7d5", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 119.1034482759, "max_line_length": 1436, "alphanum_fraction": 0.6828025478, "num_tokens": 3639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.33342144406819485}}
{"text": "% Template for EUSIPCO 2015 paper; to be used with:\n%          spconf.sty  - LaTeX style file, and\n%          IEEEbib.bst - IEEE bibliography style file.\n% --------------------------------------------------------------------------\n\\documentclass[a4paper]{article}\n\\usepackage{spconf,amsmath,amsfonts,amssymb,amsthm,graphicx}\n\\usepackage{color}\n\n% Example definitions.\n% --------------------\n\\newcommand{\\calA}{\\mathcal{A}}\n\\newcommand{\\calB}{\\mathcal{B}}\n\\newcommand{\\calD}{\\mathcal{D}}\n\\newcommand{\\calF}{\\mathcal{F}}\n\\newcommand{\\calL}{\\mathcal{L}}\n\\newcommand{\\calM}{\\mathcal{M}}\n\\newcommand{\\calP}{\\mathcal{P}}\n\\newcommand{\\calS}{\\mathcal{S}}\n\\newcommand{\\calT}{\\mathcal{T}}\n\\newcommand{\\calV}{\\mathcal{V}}\n\\newcommand{\\calW}{\\mathcal{W}}\n\\newcommand{\\calX}{\\mathcal{X}}\n\\newcommand{\\calY}{\\mathcal{Y}}\n\n\\newcommand{\\al}{\\alpha}\n\\newcommand{\\ga}{\\gamma}\n\\newcommand{\\De}{\\Delta}\n\\newcommand{\\ep}{\\epsilon}\n\\newcommand{\\tha}{\\theta}\n\\newcommand{\\ka}{\\kappa}\n\\newcommand{\\la}{\\lambda}\n\\newcommand{\\Om}{\\Omega}\n\\newcommand{\\rh}{\\rho}\n\\newcommand{\\Up}{\\Upsilon}\n\\newcommand{\\dUp}{\\partial\\Upsilon}\n\\newcommand{\\ze}{\\zeta}\n\n\\newcommand{\\C}{\\mathbb{C}}\n\\newcommand{\\E}{\\mathbf{ E}}\n\\newcommand{\\Ex}{\\mathbf{ E}}\n\\newcommand{\\I}{\\mathbb{I}}\n\\newcommand{\\Lp}{\\mathbb{L}_{p}}\n\\newcommand{\\Lt}{\\mathbb{L}_{2}}\n\\newcommand{\\N}{\\mathbb{N}}\n\\newcommand{\\Pb}{\\mathbf{ P}}\n\\newcommand{\\R}{\\mathbb{R}}\n\\newcommand{\\X}{\\mathbb{X}}\n\\newcommand{\\Z}{\\mathbb{Z}}\n\\newcommand{\\W}{{\\cal{W}}}\n\n\\newcommand{\\bfi}{\\mathbf{i}}\n\\newcommand{\\bfj}{\\mathbf{j}}\n\\newcommand{\\bfk}{\\mathbf{k}}\n\\newcommand{\\bfu}{\\mathbf{u}}\n\\newcommand{\\bfv}{\\mathbf{v}}\n\\newcommand{\\bfx}{\\mathbf{x}}\n\n\\newcommand{\\Mbar}{\\,\\overline{\\!M}}\n\\newcommand{\\mbar}{\\overline{m}}\n\\newcommand{\\Zbar}{\\,\\overline{\\!Z}}\n\n\n\n% Example definitions.\n% --------------------\n\\def\\x{{\\mathbf x}}\n\\def\\L{{\\cal L}}\n\n\n% Title.\n% ------\n\\title{Crossing-tree partition functions}\n%\n% Single address.\n% ---------------\n\\name{Author(s) Name(s)\\thanks{Thanks to XYZ agency for funding.}}\n\\address{Author Affiliation(s)}\n%\n% For example:\n% ------------\n%\\address{School\\\\\n%\tDepartment\\\\\n%\tAddress}\n%\n% Two addresses (uncomment and modify for two-address case).\n% ----------------------------------------------------------\n\\twoauthors\n  {Geoffrey Decrouez\\sthanks{Thanks to the Centre for Advanced Studies for funding.}}\n\t{National Research University\\\\\n\tHigher School of Economics\\\\\n\tMoscow, Russia}\n  {Pierre-Olivier Amblard}\n\t{GIPSAlab/CNRS UMR 5283\\\\\n\tUniversit\\'e de Grenoble\\\\\n\tGrenoble, France}\n%\n% Multiple author/addresses combination (use only in particular cases).\n% ---------------------------------------------------------------------\n%\\name{A. Author-one$^*$, B. Author-two$^*$$^\\dagger$, C. Author-three$^\\dagger$, D. Author-four$^\\ddagger$ %\n%\t\\thanks{General thanks/acknowledgment}%\n%\t\\thanks{$^*$ Thanks/acknowledgments for authors marked with *}%\n%\t\\thanks{$^\\dagger$ Thanks/acknowledgments for authors marked with $\\dagger$}%\n%\t\\thanks{$^\\ddagger$ Thanks/acknowledgments for authors marked with $\\ddagger$}%\n%}\n%\\address{%\n%    \\tabular{c}\n%\t\t$^*$ Institute ABC\\\\\n%\t\tGroup Group ABC\\\\\n%\t\tAddress ABC\n%\t\\endtabular\n%\t\\hskip 0.5in\n%    \\tabular{c}\n%\t\t$^\\dagger$ School DEF\\\\\n%\t\tDepartment DEF\\\\\n%\t\tAddress DEF\n%\t\\endtabular\n%\t\\hskip 0.5in\n%    \\tabular{c}\n%\t\t$^\\ddagger$ Company GHI\\\\\n%\t\tDepartment GHI\\\\\n%\t\tAddress GHI\n%\t\\endtabular\n%}\n%\n% The symbol order for multiple author combination is:\n%  $^*$, $^\\dagger$, $^\\ddagger$, $^\\mathsection$, $^\\mathparagraph$, $^\\|$,\n%  $^{**}$, $^{\\dagger\\dagger}$, $^{\\ddagger\\ddagger}$, ...\n%\n%\n% Alternative multiple author/addresses combination (use only in particular cases).\n% ---------------------------------------------------------------------------------\n%\\name{A. Author-one$^*$, B. Author-two$^*$$^\\dagger$, C. Author-three$^\\dagger$, D. Author-four$^\\ddagger$ %\n%\t\\thanks{General thanks/acknowledgment}%\n%\t\\thanks{$^*$ Thanks/acknowledgments for authors marked with *}%\n%\t\\thanks{$^\\dagger$ Thanks/acknowledgments for authors marked with $\\dagger$}%\n%\t\\thanks{$^\\ddagger$ Thanks/acknowledgments for authors marked with $\\ddagger$}%\n%}\n%\\address{%\n%\t$^*$ Institute ABC, Group Group ABC, Address ABC\\\\\n%\t$^\\dagger$ School DEF, Department DEF, Address DEF\\\\\n%\t$^\\ddagger$ Company GHI, Department GHI, Address GHI\\\\\n%}\n%\n% The symbol order for multiple author combination is:\n%  $^*$, $^\\dagger$, $^\\ddagger$, $^\\mathsection$, $^\\mathparagraph$, $^\\|$,\n%  $^{**}$, $^{\\dagger\\dagger}$, $^{\\ddagger\\ddagger}$, ...\n%\n\\begin{document}\n\n%\n\\maketitle\n%\n\\begin{abstract}\nA new multifractal formalism based on the crossing-tree for $H$-sssi processes was recently introduced \\cite{DecrAJ13, DecrA15}.\nThe crossing-tree performs an ad-hoc decomposition of a signal based on its fluctuations, and thus represents a natural tool for the multifractal analysis of time series. \nThe estimation of the Hausdorff spectrum happens in the context of a multifractal formalism, where the spectrum is obtained from a transform of a partition function.\nIn this contribution, we introduce a new crossing-tree partition function, which differs from the original one presented in \\cite{DecrA15}.\nWe show numerically that the new partition function improves the stability of the estimation in many cases, compared with the original crossing-tree partition function. \nEstimation is further compared with state-of-the-art techniques, including wavelet and wavelet leaders.  \n\\end{abstract}\n%\n\\begin{keywords}\n$H$-sssi processes, crossing tree, multifractal formalism, adaptative decomposition, wavelets\n\\end{keywords}\n%\n\\section{Introduction}\n\\label{sec:intro}\n\n\n{\\bf Motivations.} Fractal and multifractal signals often occur in so-called complex systems (systems with a huge number of degrees of freedom in nonlinear interaction) as different as turbulent fluids, stock markets or the internet. An important concept underlying these signals is scale invariance: the laws that underpin the construction of the processes are the same at all scales. This has naturally led to the use of multiscale tools to analyse such signals, among which the wavelet machinary is the best known, and provide today's state-of-the art techniques for fractal and multifractal signal analysis.  \n\nIn the wavelet paradigm, the notion of scale is introduced in the index set (time for signals, space for images). \nThe notion of scale can also be defined in the amplitude space of the signal. The crossing-tree decomposition then provides the corresponding multiscale decomposition: at  a given resolution, the amplitude set is cut into equal length intervals, the bound of which define the crossing levels. A crossing is defined as the path of the signal between two consecutive strictly different crossing levels. At a given resolution, the nodes of the tree contain the consecutive crossings. A multiscale representation is then provided by iterating the process on all crossings, by studying subcrossings at a finer resolution. To present the notation, we will formalize this later in this introduction. \nA main difference between wavelet decomposition and the crossing tree is the fact that the latter is an adaptive technique.\n\n The crossing tree was introduced to generalize the mid-point deplacement method to construct the standard Brownian motion. In \\cite{JoneS04} it was applied to self-similar processes, to test for self-similarity and stationary increments, and to obtain an asymptotically consistent estimator of the H\\\"older exponent. In \\cite{ArrJon06} the crossing tree was used to estimate a time-change of a self-similar process, and in \\cite{JonRol}, it was used to characterise and test if a process is a continuous local martingale. Later, it has been the basis to construct a class of monofractal and multifractal processes, see \\cite{DecrJ12, DecrHJ}. This lead us to invert the point of view and use the crossing tree as an analysis tool for fractal and multifractal signals. Indeed, the crossing tree is a very general concept  and can easily be computed on real data.\n\nIn \\cite{DecrAJ13,DecrA15} we showed how to use the crossing duration to estimate the H\\\"older exponent for several classes of monofractal signals. To do so we introduced a partition function using the crossing durations. A theoretical justification for it relies on  \\cite{DecrJ12, DecrHJ} where multifractal formalism is proved for the so-called multifractal embedded branching processes (MEBP, processes that are constructed {\\it via } the crossing tree). As many methods, the partition function suffers a lack of statistics for negative powers. {\\em The aim of the present paper is to illustrate\nhow an easy modification of the partition function allows better estimation for negative powers. }\n\nThe remaining of the paper is organized as follows. We continue this introduction by presenting the crossing tree decomposition and the class of signals we study. Section 2 will present the partition functions we use to estimate the H\\\"older exponents, whereas section 3 will present the practical set up as well as simulations. One aim is to compare the crossing tree approach with the state-of-the-art provided by wavelet and wavelet leaders. \n\n\\medskip\n\\noindent{\\bf The crossing tree.}\n%\\label{sec:xtree}\nWe consider a process $X: \\R^+\\rightarrow\\R$. Without loss of generality, we assume $X(0)=0$ almost surely (a.s.) and we further suppose it has continuous sample paths (a.s.).\nAt a resolution $m\\in \\Z$, the vertical axis is cut into levels of size $2^m$, and a crossing at level $m$ is defined as the path between two successive different crossing levels. The first crossing starts at $t=0$ and is defined as the path betwen $t=0$ and the first time the signal crosses either $2^m$ or $-2^m$. Each crossing is characterized by two parameters: its duration and its direction.\nThe level-$m$ crossing times $T_k^m$ are defined as \n\\[\nT_{k+1}^{m}= \\inf\\{t>T_{k}^{m}~|~X(t)\\in  2^{m}\\Z,~X(t)\\not = X(T_{k}^{m}) \\}\\,,\n\\]\nwhere  $T_0^m = 0$  and $2^{m}\\Z=\\{ x ~|~ x=2^m a \\textrm{ for } a\\in\\Z\\}$.\nThus, the $k$-th level-$m$ (equivalently scale $2^m$) crossing $C_k^m:= \\{ (t,X(t))\\mid T_{k-1}^m\\leqslant t < T_k^m\\}$ is the bit of sample path from $T_{k-1}^{m}$ to $T_{k}^{m}$.\nNow the crossing tree is created by iterating the previous construction.\n Each crossing of size $2^m$ is decomposed into a sequence of crossings of size $2^{m-1}$.\nThe nodes of the crossing tree are crossings and the offspring of any given crossing is the corresponding set of subcrossings at the level below.\nAn example of a crossing tree and the main notation  are given in Figure~1.\nThe crossing-tree can easily be computed for irregularly time-sampled signals, and as such the formalism developed later is adapted to this kind of data.\n\n\\begin{figure}[]\n\n\\begin{minipage}[b]{0.4\\linewidth}\n  \\centering\n  \\input descr-crossingtree.pdf_t\n % \\centerline{\\includegraphics[width=6.5cm]{descr-crossingtree.pdf}}\n%  \\vspace{2.0cm}\n%  \\centerline{(a) Result 1}\\medskip\n\\end{minipage}\n\n\\caption{Formation of the crossing tree from a sample path, and crossing tree notation. Variables are defined in the text.}\n\\label{fig:ct}\n%\n\\end{figure}\n\nTo code nodes in the tree we use\nthe address space $I = \\cup_{k=0}^\\infty \\N^k$, where $\\N^k$ is the set of words of $k$ integers and $\\N^0=\\emptyset$.\nFor the sake of simplicity, the root of the tree and  first crossing is supposed to go from $0$ to $\\pm 1$.\nIt is labelled $\\emptyset$ and its subcrossings (each of size $1/2$) are numbered from 1 to $Z_\\emptyset$.\nThe subcrossings of a crossing $\\bfi = i_1 i_2 \\cdots i_n\\in\\N^n$ are then labelled $\\bfi 1, \\ldots, \\bfi Z_\\bfi$, where $Z_\\bfi$ is the number of subcrossings of $\\bfi$ and $\\bfi j = i_1 i_2 \\cdots i_n j$. \nIt is easy to show that  $Z_\\bfi$ is an even integer larger or equal to 2.\nWe note as $N_n$ the size of generation $n$.\nThe second main parameter of a crossing $\\bfi$   is its type, either up or down, which we denote by $\\sigma_\\bfi$.\nThe other parameter $W_\\bfi$ is the duration of crossing $\\bfi$. The sample path is completely described by $\\{ (\\sigma_\\bfi, W_\\bfi) \\,:\\, \\bfi \\in I \\}$.\n\n\n\n\\medskip\n\n\\noindent{\\bf Some scale invariant processes.} $X(t)$ is said to be a self-similar process if there exists an $H\\in(0,\\,1)$ such that  $X(ct)=c^H X(t)$ holds for all $c>0$ (in the finite-dimensional distribution sense). \nIf in addition the process $X(t)$ has stationary increments, then $X(t)$ is said to be $H$-sssi.\n\nThe most-studied $H$-sssi processes are fractional Brownian motions (fBm), \nthe only self-similar Gaussian processes with stationary increments.\nTheir sample paths are continuous (a.s.) but non differentiable (a.s.). However, they have a degree of regularity \nand possess $H$ as  H\\\"older exponent almost everywhere. \nA nonGaussian generalization of fBm is provided by Hermite processes.\n\nLet ${\\cal B}(u)$ denote a Brownian motion.\nA Hermite process of order $k$ is defined as\n\\begin{align*}\n{\\cal H}^k_H(t) = \\int_{\\R^k}\\int_0^t \\left( \\prod_{j=1}^k (s-u_i)_+^{-(1/2 + (1-H)/k)}\\right)dsd{\\cal B}({\\bf u})\\,,%&\\\\\n%& \\hspace{-2.5cm}ds\\, d{\\cal B}(u_1)\\hdots d{\\cal B}(u_k)\\,,\n\\end{align*}\nwhere $d{\\cal B}({\\bf u})=d{\\cal B}(u_1)\\hdots d{\\cal B}(u_k)$,\nfor $k\\geq 1$, with $H\\in(1/2,\\,1)$, and $x_+=\\max(0,x)$.\nThe case $k=1$ corresponds to the case of an fBm.\n${\\cal H}^2_H(t)$ is usually referred to as the Rosenblatt process.\n\nThe Weierstrass function is defined as\n\\[\n{\\cal W}_H(t)= \\sum_{k\\in \\Z} \\lambda_0^{-k H} \\Big(\\cos(\\varphi_k)-\\cos(2\\pi \\lambda_0^k t +\\varphi_k) \\Big)\\,,\n\\]\nwhere $H$ stands for the H\\\"older exponent and $\\lambda_0$ is a fundamental harmonic. \nThe definition is made to impose ${\\cal W}_H(0)=0$. \nThe Weierstrass function exhibits discrete scale invariance (DSI), with ${\\cal W}_H(\\lambda_0 t)=\\lambda_0^H {\\cal W}_H(t)$, in distribution.\nWe consider here a stochastic version of this function, obtained by choosing the phases $\\{\\varphi_k\\}_{k\\in \\Z}$ as a sequence of i.i.d. variables uniformly distributed over $[0,~2\\pi]$. \n\n\n\n\n\\section{Partition functions}\n\\label{sec:majhead}\n\nThe estimation of the spectrum of singularities $D(h)$, defined as the Hausdorff dimension of the set of points with given H\\\"older regularity $h$, typically occurs in the context of the multifractal formalism.\nThe formalism relates the spectrum to a partition function $\\zeta(q)$ via the (Legendre) transform\n\\[\nD(h) = \\inf\\limits_{q\\in\\R} \\{ 1- \\zeta(q) + hq \\}\\,.\n\\]\nThis section reviews wavelet-based partition functions first, before introducing crossing-tree partition functions.\n\n\\subsection{Wavelet-based partition functions}\n\\label{ssec:wavform}\n\nWe first recall the wavelet decomposition of a signal $X(t)$.\nLet $\\psi$ be the mother wavelet.\nAny square integrable signal can be decomposed as\n\\[\nX(t)=\\sum_{n,k\\in\\Z} c_{n,k}\\psi(2^nt-k)\\,,\n\\] \nwhere $$c_{n,k}=2^n\\int X(t)\\psi(2^nt-k)dt\\,.$$ \nWe denote by $\\lambda_{n,k}=[k2^{-n}, (k+1)2^{-n})$ a dyadic cube at scale $n$, with $k\\in\\Z$.\nThe wavelet-based structure function of $X$ is defined from the $q$-th moment of the wavelet coefficients,\n$$S_{wc}(q,n) = 2^{-n} \\sum_k \\left| c_{n,k}  \\right|^q\\,,$$\nwhere the sum is taken over all dyadic cubes $\\lambda_{n,k}$ with non vanishing coefficients.\nThe wavelet partition function is then\n\\vspace{-.2cm}\n\\begin{equation}\\label{partition_wav}\n\\zeta_{wc}(q) = \\liminf_{n\\to+\\infty} \\left( \\dfrac{\\log S_{wc}(q,n)}{\\log 2^{-n}} \\right)\\,, \\quad q\\in\\R \\,,\n\\end{equation}\nwhich leads to the multifractal formalism \\cite{ParisiF85}\n\\begin{equation}\\label{spectrum_wav}\nD_X(h) = \\inf\\limits_{q\\in\\R} \\{ 1- \\zeta_{wc}(q) + hq \\}\\,.\n\\end{equation}\nThe wavelet-based partition function (\\ref{partition_wav}) is known to be unstable for negative exponents, corresponding to $q<0$. \nIndeed, wavelet coefficients can be arbitrary small, and a small error in their estimation can be multiplied when raised to a negative power.\n\nTo address this issue (amongst others), the wavelet leaders formalism was introduced \\cite{JaffLA06}.\nPut $3\\lambda_{n,k}= \\lambda_{n,k-1}\\cup \\lambda_{n,k}\\cup \\lambda_{n,k+1}$, which corresponds to the cube centered around $\\lambda_{n,k}$, three times wider. \nThe wavelet leaders $d_{n,k}$ of a bounded function $X(t)$ are defined as\n\\vspace{-.2cm}\n\\[\nd_{n,k} = \\sup\\limits_{\\{m,i\\,|\\, \\lambda_{m,i} \\subset 3\\lambda_{n,k}\\}}|c_{m,i}|\\,.\n\\]\nIt is then natural to introduce the wavelet leader structure function $$S_{wl}(q,n) = 2^{-n} \\sum_k \\left| d_{n,k}  \\right|^q\\,,$$ where the sum is taken over all non vanishing wavelet leader coefficients.\nThe scaling function is\n\\vspace{-.2cm}\n\\begin{equation}\\label{partition_wl}\n\\zeta_{wl}(q) = \\liminf_{n\\to+\\infty} \\left( \\dfrac{\\log S_{wl}(q,n)}{\\log 2^{-n}} \\right)\\,, \\quad q\\in\\R \\,,\n\\end{equation}\nwhich leads to the multifractal formalism\n\\begin{equation}\\label{spectrum_wl}\nD_X(h) = \\inf\\limits_{q\\in\\R} \\{ 1- \\zeta_{wl}(q) + hq \\}\\,.\n\\end{equation}\n\n\n\\subsection{Crossing-tree partition functions}\n\\label{ssec:ctform}\n\nA new formalism for the study of $H$-sssi processes was recently introduced \\cite{DecrAJ13, DecrA15}. \nThe formalism relates the spectrum of singularities to a partition function computed from multi resolution quantities obtained from the crossing-tree of a signal.\n\nGiven $t$, let $\\bfi \\in \\N^\\infty$ be such that for each $n$, the size $2^{-n}$ crossing that contains $t$ is $\\bfi|n$.\nThen, our analogue of the multiresolution quantity is the crossing duration $W_{\\bfi|n}$.\nWe say that the process $X(t)$ possesses scaling properties if time averages of the crossing durations follow a power law behaviour,\n\\begin{equation}\\label{structure_ct}\nS_{ct}(n,q) = \\frac{1}{N_n}\\sum\\limits_{\\bfi|n} |W_{\\bfi|n}|^q \\sim C_q' 2^{-n\\zeta_{ct}(q)}\\,,\n\\end{equation}\nas $n\\to \\infty$,\nwhere the sum is taken over all crossings of size $2^{-n}$.\nWe call $S_{ct}(n,q)$ the structure function and $\\zeta_{ct}$ the crossing tree partition function.\nThe partition function can be obtained from the structure function as a limit,  \n\\begin{equation}\\label{partition_ct}\n\\zeta_{ct}(q) = \\liminf_{n\\to \\infty}\\frac{\\log S_{ct}(n,q)}{-n \\log 2}\\,.\n\\end{equation}\n\nThe crossing-tree partition function (\\ref{partition_ct}) was first introduced to obtain a theoretical expression of the Hausdorff spectrum of a class of processes called Multifractal Embedded Branching Processes (MEBP), see \\cite{DecrJ12, DecrHJ}.\nAn MEBP process $X$ can be represented as the composition of a process $Y$ with constant modulus of continuity, and the inverse of an increasing process $\\calM$, so that it can be written as $X = Y \\circ \\calM^{-1}$.\nThe increasing process $\\calM$ is the integral of a multiplicative cascade defined on the boundary of the crossing tree of $Y$.\nThe multifractal analysis of $\\calM$ requires deducing the local H\\\"older exponent at every point of its support from a discretised version of it. To do so, the support of a multifractal measure is typical divided into dyadic cubes, and a structure function is defined from the empirical $q$-th moments of measures\nof cubes 3 times wider than the original partition, see e.g. Section 2 in \\cite{JaffLA06}. This methodology was adapted in \\cite{DecrHJ} to perform the multifractal analysis of $\\calM$. \nThe analysis performed there requires the introduction of a novel partition function constructed on a random grid adapted to the process. The new partition function is defined in terms of the $q$-th moment of the sum of 3 consecutive crossing durations (instead of 3 consecutive dyadic cubes), and constitutes the starting point of the present study.\n\nLet $\\bfi|n-$ and $\\bfi|n+$ denote respectively the left and right neighbours of $\\bfi|n$. The corresponding crossing durations are denoted $W_{\\bfi|n-}$ and $W_{\\bfi|n+}$. \nThe discussion above motivates the definition of a new crossing-tree structure function, \n\\begin{equation}\\label{structure_ct2}\n{\\cal S}_{ct}(n,q) = \\frac{1}{N_n}\\sum\\limits_{\\bfi|n} |W_{\\bfi|n-}+ W_{\\bfi|n}+W_{\\bfi|n+}|^q \\,,\n\\end{equation}\nand its associated partition function\n\\begin{equation}\\label{partition_ct2}\n\\eta_{ct}(q) = \\liminf_{n\\to \\infty}\\frac{\\log {\\cal S}_{ct}(n,q)}{-n \\log 2}\\,.\n\\end{equation}\nThe introduction of the right and left neighbours in the definition of ${\\cal S}_{ct}(n,q)$ takes cares of problems that may arise when the local H\\\"older exponent is discretised at time $t$, when $t$ is a crossing time, since $t$ corresponds in that case to one of the endpoints of the crossing durations.\n\nWavelet leaders were introduced to address the flaws of a multifractal analysis based directly on wavelet coefficients. In particular, wavelet leaders are known to estimate the spectrum of singularities with greater accuracy for $q<0$. They are defined from the supremum of wavelet coefficients over dyadic cubes 3 times larger than the original dyadic partition, which is the key to their success. \nWe thus expect that defining a structure function from of the $q$-th moments of statistics defined on 3 consecutive intervals will also improve the stability properties of the structure function for $q<0$, compared to the original $S_{ct}(n,q)$. \nThe numerical work presented in the next section supports this claim.\n\nHeuristic arguments presented in \\cite{DecrA15} lead to conjecture that for self-similar processes, the multifractal spectrum is related to the crossing-tree partition function via the transform\n\\begin{equation}\\label{ct_multifractal}\n\\zeta_{ct}(q) = \\inf_h\\{ (q+1)/h -D(h)/h \\}\\,.\n\\end{equation}\nFor monofractal processes with H\\\"older exponent $H$, one gets $\\zeta_{ct}(q)=q/H$. \nA similar reasoning yields $\\eta_{ct}(q)=q/H$ for this class of processes. \nThis conjecture, proved for the Brownian motion, remains open. \nThe numerical work presented in the next section supports this conjecture.\nThe expression of the crossing-tree partition functions for monofractal processes should be compared with wavelet-based techniques, where we directly get from (\\ref{spectrum_wav}) and (\\ref{spectrum_wl}) that $\\zeta_{wc}(q)=\\zeta_{wl}(q)=qH$.\nThe partition function is still linear in $q$, but the slope is inverted. \n\n\n\\section{Numerical work}\n\\label{ssec:numwork}\n\nFor each process defined in the introduction, we compare the performance of the two crossing-tree partition functions. \nEstimation based on wavelet coefficients is also presented.\nThe partition functions are estimated from an average of 1000 realizations of $2^{15}$ sample points each. \nThe wavelet partitions functions are estimated using Daubechies' wavelets with 3 vanishing moments, from scale $2^3$ to $2^{12}$ using Matlab routines from \\cite{WendtSPM2007, WendtICASSP2008}.\nThe crossing tree partition function is estimated from scale $2^2$ to $2^5$.\nThe  range of scales differs for wavelet methods and the crossing tree, since they are calculated differently: the scales chosen to analyse the crossing tree are computed from the spatial fluctuations of the signal.\n  \nWe focus our attention to the estimation of the negative moments, which is the main objective of the present contribution.\nFigure \\ref{fig:partition1} and \\ref{fig:partition2} display the estimation of $\\zeta_{ct}(q)$, $\\eta_{ct}(q)$ and $\\zeta_{wc}(q)$, $\\zeta_{wl}(q)$ for $q$ varying between -10 and 0.\nIt is clear from Figure \\ref{fig:partition2} that the partition function based on wavelet coefficients fails to work for negative $q$s, while the three other methods return stable results. \nIn particular, it can be seen from Figure \\ref{fig:partition1} that an estimation based on the crossing tree returns a good estimation for negative $q$s, and the estimation bias is further reduced when considering $\\eta_{ct}(q)$ instead of $\\zeta_{ct}(q)$.\nIn most cases, the bias almost vanishes, while wavelet leaders return a small bias in some cases.\nThe estimation was repeated for other values of $H> 0.5$, and the modified formalism systematically improves the estimation compared to the original crossing-tree partition function.\nEstimation for processes with $H< 0.5$ remains however challenging with the crossing tree, since the estimation of the crossing tree is all the more difficult as the process is rough (crossings are missed).\n\nFollowing the seminal work of Castaing \\cite{Cast93}, we considered in \\cite{DecrA15} a polynomial expansion of the partition function, and we defined an estimator of $H$ from the first coefficient in the expansion, estimated from the cumulant of the crossing durations. We repeated the same procedure for $\\eta_{ct}(q)$, and we found that the performances of the estimators based on $\\eta_{ct}(q)$ and $\\zeta_{ct}(q)$ are comparable in most cases.\n\n\\begin{figure}\n\n\\begin{minipage}[b]{.48\\linewidth}\n  \\centering\n  \\centerline{\\includegraphics[scale=.3]{max_fbm}}\n  \\vspace{.12cm}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[b]{0.48\\linewidth}\n  \\centering\n  \\centerline{\\includegraphics[scale=.3]{max_rosenblatt}}\n  \\vspace{.12cm}\n\\end{minipage}\n%\n\\begin{minipage}[b]{.48\\linewidth}\n  \\centering\n  \\centerline{\\includegraphics[scale=.3]{max_hermitte}}\n  \\vspace{-.12cm}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[b]{0.48\\linewidth}\n  \\centering\n  \\centerline{\\includegraphics[scale=.3]{max_weierstrass}}\n  \\vspace{-.12cm}\n\\end{minipage}\n%\n\\caption{Estimation of the partition function for $q$ varying between -10 and 0 using $\\zeta_{ct}(q)$ ($\\circ$) and $\\eta_{ct}(q)$ ($\\Box$). \nThe dashed line is the theoretical line $q/H$. \nFrom top to bottom, left to right, fractional Brownian motion, Hermite with $k=2$ and 3, and Weierstrass function, with $H=0.6$.}\n\\label{fig:partition1}\n\n\\end{figure}\n\n\n\n\\begin{figure}\n\n\\begin{minipage}[b]{.48\\linewidth}\n  \\centering\n  \\centerline{\\includegraphics[scale=.3]{leader_fbm}}\n  \\vspace{.12cm}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[b]{0.48\\linewidth}\n  \\centering\n  \\centerline{\\includegraphics[scale=.3]{leader_rosenblatt}}\n  \\vspace{.12cm}\n\\end{minipage}\n%\n\\begin{minipage}[b]{.48\\linewidth}\n  \\centering\n  \\centerline{\\includegraphics[scale=.3]{leader_hermite}}\n  \\vspace{-.12cm}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[b]{0.48\\linewidth}\n  \\centering\n  \\centerline{\\includegraphics[scale=.3]{leader_weierstrass}}\n  \\vspace{-.12cm}\n\\end{minipage}\n%\n\\caption{Estimation of the partition function using wavelet leaders ($\\circ$) and wavelet coefficients ($\\Box$).}\n\\label{fig:partition2}\n\n\\end{figure}\n\n\n\\section{Concluding remarks}\n\\label{ssec:numwork}\n\nThe present contribution extends earlier work on the crossing-tree, by introducing a novel crossing-tree partition function. \nWe showed numerically that a simple modification of the crossing-tree partition function presented in \\cite{DecrAJ13, DecrA15} allows a more stable estimation for negative powers.\n\nThis work further raises many challenges (both theoretically and numerically) and open conjectures.\nThe first step being formally proving that $\\eta_{ct}(q)=q/H$ for monofractal $H$-sssi processes, before proving (\\ref{ct_multifractal}) in all generality.\nEstimation for rougher processes ($H<0.5$) should also be further investigated, since the estimation of the crossing tree is deteriorated in this case. \nFinally, the crossing tree is defined so far only for one-dimensional processes. \nExtending its definition to two-dimensional processes might lead to a new tool to analyse images, and in particular to perform their multifractal analysis. \n\n\n% References should be produced using the bibtex program from suitable\n% BiBTeX files (here: strings, refs, manuals). The IEEEbib.bst bibliography\n% style file from IEEE produces unsorted bibliography list.\n% -------------------------------------------------------------------------\n\\bibliographystyle{IEEEbib}\n\\bibliography{strings,refs}\n\n\\end{document}\n", "meta": {"hexsha": "016c340ff49c2f82c265d4237e3d1ea5360f7bc8", "size": 27662, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/drafts/Eusipco_revision.tex", "max_stars_repo_name": "ivannz/crossing_paper2017", "max_stars_repo_head_hexsha": "a33c826b966d0238b96156ec19f462d2f9ed7906", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-25T21:37:23.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-25T21:37:23.000Z", "max_issues_repo_path": "paper/drafts/Eusipco_revision.tex", "max_issues_repo_name": "ivannz/crossing_paper2017", "max_issues_repo_head_hexsha": "a33c826b966d0238b96156ec19f462d2f9ed7906", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/drafts/Eusipco_revision.tex", "max_forks_repo_name": "ivannz/crossing_paper2017", "max_forks_repo_head_hexsha": "a33c826b966d0238b96156ec19f462d2f9ed7906", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 57.870292887, "max_line_length": 862, "alphanum_fraction": 0.7284361218, "num_tokens": 7903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.33342144406819485}}
{"text": "\\documentclass[12pt]{amsproc}\n\\usepackage[a4paper]{geometry}\n\\usepackage{float}\n\\usepackage{fouriernc}\n\\usepackage{verbatim}\n\n\\begin{comment}\n  Where to publish this ? JOSS is merely a software journal.\n  - CPC ?\n  - WIAS TR\n  - As part of documenter ?\n    After all, yes\n\n    Computing in Science \\& Engineering (CiSE)\n    \ncite:  https://www.researchgate.net/publication/223773028_A_frequency-domain_approach_to_dynamical_modeling_of_electrochemical_power_sources\nhttps://www.sciencedirect.com/science/article/abs/pii/S0013468697002387\nhttps://www.gamry.com/application-notes/EIS/basics-of-electrochemical-impedance-spectroscopy/\nhttps://iopscience.iop.org/article/10.1149/09401.0251ecst\n\n\n\\end{comment}\n\n\n\n\\title{Small signal analysis for nonlinear evolution equations\\\\ Draft.}\n\\author{J. Fuhrmann}\n\\newcommand{\\CV}{{\\mathcal{V}}}\n\\newcommand{\\VV}{\\mathbb{V}}\n\\newcommand{\\PP}{\\mathbb{P}}\n\\newcommand{\\TT}{\\mathbb{T}}\n\\newcommand{\\MM}{\\mathbb{M}}\n\\newcommand{\\RR}{\\mathbb{R}}\n\\newtheorem{example}{Example}\n\n\\newcommand{\\Exp}[1]{e^{#1}}\n\\begin{document}\n\\maketitle\n%\\begin{multicols}{2}\n\\section{Frequency response of an electrical network}\n  \nThe  current  dependency  on  voltage   of  basic  basic  elements  of\nelectrical networks  can be subsummed  using the notion  of impedance.\nLet $U(t)$  be a given  voltage difference  applied to as  device, and\n$I(t)$ be the resulting current.  For a periodic voltage perturbation,\nthe  frequency dependent  impedance  describes the  ratio between  the\namplitudes  of the  voltagee and  the current  response, respecitvely.\nAssuming a an applied  periodic voltage $U(t)=U_a\\Exp{i\\omega t}$ with\namplitude $U_a$ and frequency $\\omega$, we get\n\\begin{table}[H]\n  \\begin{center}\n\\renewcommand{\\arraystretch}{1.4}\n\\begin{tabular}{lllll}\nCircuit Element     & Law     & Standard form & Complex Form & Impedance\\\\ \nResistance  & Ohm     & $ I(t)=\\frac1R U(t)$                                & $I(t)=\\frac1R U(t)$       &  $Z(\\omega)=R$ \\\\\nCapacity    & Faraday & $ I(t)=C(t)\\frac{d}{dt}U(t)$                        & $I(t)=Ci\\omega U(t)$&          $Z(\\omega)=\\frac1{Ci\\omega}$\\\\\nInductivity & Henry   & $ I(t)=I_0+\\frac1L\\int\\limits_{t_0}^tU(\\tau) d\\tau$ & $I(t)=\\frac1{Li\\omega}$ U(t)&$Z(\\omega)=Li\\omega$ \\\\\n\\end{tabular}\n\\caption{\\label{tab:impedance} Impedance of three basic elements of electric circuits}\\hfill\n\\end{center}\n\\end{table}\n\nAny  network consisting  of  these  elements can  be  analyzed in  the\ncomplex domain  using Kirchoffs law  and regarding the impedance  as a\ncomplex resistance.\n\n\\section{Impedance spectroscopy in nonlinear evolution equations}\n\nUsually, the interpretations of impedance spectroscopy measurements of\nother  systems,  e.g. electrochemical  systems  is  performed using  a\nreplacement circuit consisting of  electrical network elements.  Being\nquite  successful  in many  cases,  this  interpretation basically  is\nlimited to compartment type models.\n\nHere,  we discuss an  approach of  applying impedance  spectroscopy to\nabstract evolution equations based on small signal analysis.\n\nFor a  given time  interval $\\TT=[0,T]$, a  Banach space  $\\CV$ called\n{\\em state space},  and a finite dimensional space  $\\PP$, called {\\em\nparameter  space},  regard  the  abstract doubly  nonlinear  evolution\nequation\n\\begin{equation}\\label{eq:abstrevol}\n \\frac{d S(v(t),\\lambda)}{dt} + D(v(t),\\lambda)=0\n\\end{equation}\n\nThe state of  the system is {\\em measured} by  some functional $M: \\CV\n\\rightarrow  \\MM$,   where  $\\MM$  is  the   finite  dimensional  {\\em\nmeasurement space}. We assume  $M(v)=M^{stdy}(v)+ d_t M^{tran}(v)$.\n\nAs an example, $\\CV$ may  be a finite dimensional space containing the\nsolution of some discretized system of partial differential equations.\n\n\nGiven   a  steady   state  $(v_0,   \\lambda_0)$  such   that  $D(v_0,\n\\lambda_0)=0$, measured  by $M_0=M(v_0)$, we  would like to  trace its\nresponse  to  a small,  periodic  perturbation $\\lambda(t)=  \\lambda_a\n\\Exp{i\\omega  t}   $.   Expressing   the measurement of this  response  as   $M(t)=  M_0+\nM_a(\\omega)  \\Exp{i\\omega  t}$,  we  yield the  impedance  $Z(\\omega)=\nM_a(\\omega)^{-1} \\lambda_a$.\n\n\n\nIn order to calculate the frequency response, we make the ansatz $v(t)=v_0+v_a\\Exp{i\\omega  t}$ for\nthe perturbation of the state variable and calculate the first order Taylor expansions\nof the terms $S,D$:\n\\begin{equation*}\n  \\begin{split}\n    S(v_0+v_a\\Exp{i\\omega  t},\\lambda_0+\\lambda_a\\Exp{i\\omega  t})\\approx&S(v_0,\\lambda_0)+ \n          S_v(v_0,\\lambda_0)v_a\\Exp{i\\omega  t}+\n          S_\\lambda(v_0,\\lambda_0)\\lambda_a\\Exp{i\\omega  t}\\\\\n    D(v_0+v_a\\Exp{i\\omega  t},\\lambda_0+\\lambda_a\\Exp{i\\omega  t})\\approx&D(v_0,\\lambda_0)+ \n          D_v(v_0,\\lambda_0)v_a\\Exp{i\\omega  t}+\n          D_\\lambda(v_0,\\lambda_0)\\lambda_a\\Exp{i\\omega  t}\n  \\end{split}\n\\end{equation*}\n\nPutting them into equation \\eqref{eq:abstrevol}  and using the steady state condition yields\n\\begin{equation*}\n  \\begin{split}\n    \\frac{d}{dt}\\left( \n      S_v(v_0,\\lambda_0)v_a\\Exp{i\\omega  t}+\n      S_\\lambda(v_0,\\lambda_0)\\lambda_a\\Exp{i\\omega  t}\\right)+ \n    D_v(v_0,\\lambda_0)v_a\\Exp{i\\omega  t}+\n    D_\\lambda(v_0,\\lambda_0)\\lambda_a\\Exp{i\\omega  t}&=0\\\\\n    i\\omega\\left( \n      S_v(v_0,\\lambda_0)v_a\\Exp{i\\omega  t}+\n      S_\\lambda(v_0,\\lambda_0)\\lambda_a\\Exp{i\\omega  t}\\right)+ \n    D_v(v_0,\\lambda_0)v_a\\Exp{i\\omega  t}+\n    D_\\lambda(v_0,\\lambda_0)\\lambda_a\\Exp{i\\omega  t}&=0\\\\\n    i\\omega\\left( \n      S_v(v_0,\\lambda_0)v_a+\n      S_\\lambda(v_0,\\lambda_0)\\lambda_a\\right)+ \n    D_v(v_0,\\lambda_0)v_a+\n    D_\\lambda(v_0,\\lambda_0)\\lambda_a&=0\n  \\end{split}\n\\end{equation*}\n\n\nFor the measurement, we have\n\\begin{align*}\n      M(v_0+v_a\\Exp{i\\omega  t})\\approx&M^{stdy}(v_0)+ \n    M^{stdy}_v(v_0)v_a\\Exp{i\\omega  t} +  i\\omega M^{tran}_v(v_0)v_a\\Exp{i\\omega  t}\n\\end{align*}\n\nAssuming $S_\\lambda=0$, $\\dim \\MM =\\dim \\PP=1$ we arrive at solving \n\\begin{equation}\\label{eq:impedsolve0}\n    i\\omega \n      S_v(v_0)v_a+\n    D_v(v_0,\\lambda_0)v_a+\n    \\lambda_a D_\\lambda(v_0,\\lambda_0)=0\n\\end{equation}\nfor given $\\omega$ for the  unknown $v_a$.\nThe corresponding measurement yields:\n\\begin{align*}\n  M_a(\\omega)= M^{stdy}_v(v_0)v_a + i\\omega M^{tran}_v(v_0)v_a \n\\end{align*}\n\nThe impedance then can be calculated as \n\\begin{equation*}\\label{eq:imped0}\n  Z(\\omega)= \\frac{\\lambda_a}{M_a(\\omega)}\n\\end{equation*}\n\nDividing \\eqref{eq:impedsolve0} by  $\\lambda_a$ (and thus rescaling $v_a$) gives the final expressions\n\\begin{equation}\\label{eq:impedsolve}\n    i\\omega \n      S_v(v_0)v_a+\n    D_v(v_0,\\lambda_0)v_a+\n    D_\\lambda(v_0,\\lambda_0)=0\n\\end{equation}\nand\n\\begin{equation}\\label{eq:imped}\n  Z(\\omega)= \\frac{1}{ M^{stdy}_v(v_0)v_a + i\\omega M^{tran}_v(v_0)v_a}.\n\\end{equation}\n\n\\subsection{Excited Dirichlet boundary condition}\nThis dicussion is based on the idea to implement Dirichlet boundary conditions using the\npenalty method and provides an easy way to handle deriviatives with respect to\nthe Dirichlet boundary value. We assume that our problem corresponds to a (discretized) PDE\nin a domain $\\Omega$ with boundary $\\Gamma=\\partial\\Omega$.\n\\begin{example}{Dirichlet Boundary Conditions}\\\\\n  Assum that $\\Gamma_0,\\Gamma_1\\subset \\Gamma$  are two disjunct parts of\n  the boundary.\n  For (discretized) differential operator $D_i$ defined\n  in $\\Omega$ assume that $D_i(v)=0$ is the discretization of the\n  homogeneous Neumann boundary value problem. Adding Robin boundary value terms\n  for $\\Gamma_0, \\Gamma_1$ with Robin coefficient $\\frac1\\epsilon$ and boundary values\n  0, resp. $\\lambda$ can be formally\n  written as\n  \\begin{align*}\n  D(v,\\lambda)= D_i(v)\n  +\\frac1\\epsilon\\delta_{\\Gamma_0}(v)\n  +\\frac1\\epsilon\\delta_{\\Gamma_1}(v-\\lambda),    \n  \\end{align*}\n  where $\\delta$ means delta functions with support at the corresponding boundary.\n  The limit $\\epsilon\\to 0$  corresponds to the Dirichlet boundary condition.\n  This covers the case of an\n  applied voltage difference  and an excitation at $\\Gamma_1$.\n  \n\n  Then  \n\\begin{equation*}\n  \\begin{split}\n    D_v(v,\\lambda)= D_{i,v}(v)+ \\frac1\\epsilon\\delta_{\\Gamma_0}+ \\frac1\\epsilon\\delta_{\\Gamma_1}\\\\\n    D_\\lambda(v,\\lambda)= -\\frac1\\epsilon\\delta_{\\Gamma_1}\\\\\n   \\end{split}\n\\end{equation*}\nTherefore  for the impedance calculation we have to solve \n\\begin{equation*}\n  i\\omega S_v v_a + D_{i,v} v_a +\\frac1\\epsilon\\delta_{\\Gamma_0}v_a +\\frac1\\epsilon\\delta_{\\Gamma_1}(v_a-1) =0\n\\end{equation*}\nwhich for $\\epsilon\\to 0$ corresponds to the Dirichlet problem  for the linearized equation \nwith boundary condition 0 on $\\Gamma_0$ and 1 on $\\Gamma_1$.\n\\end{example}\n\n\\subsection{Flux calculation via test function}\nFor a discussion, see e.g. [Gajewski, WIAS TR],  [Yoder, Gärtner], [Farrell et al, Handbook].\n\nAssume that $D_i(v,\\lambda) = \\nabla \\cdot J(v) + R(v)$. Let $T$ be be a test function\nsuch that $\\Delta T    +\\frac1\\epsilon\\delta_{\\Gamma_0}(T)\n+\\frac1\\epsilon\\delta_{\\Gamma_1}(T-1)=0$, which for $\\epsilon\\to 0$  corresponds to\na mixed boundary value problem with $T=0$ on $\\Gamma_0$, $T=1$ on $\\Gamma_1$ and $\\partial_n T=0$ on\n$\\partial\\Omega \\setminus  (\\Gamma_0 \\cup \\Gamma_1)$.\nThen the boundary flux integral as measurement can be calculated as\n\\begin{align*}\n  M(v)&=\\int_{\\Gamma_1} J(v,\\lambda)\\cdot n ds\n      =\\int_{\\Gamma_1} T J(v,\\lambda)\\cdot n ds\n      =\\int_{\\Gamma} T J(v,\\lambda)\\cdot n ds\\\\\n      &=\\int_{\\Omega} \\nabla\\cdot \\left(T J(v,\\lambda)\\right) d\\vec x\n      =\\int_\\Omega \\left(J(v) \\nabla T + T (\\nabla \\cdot J)\\right) d\\vec x\\\\\n      &=\\int_\\Omega \\left(J(v) \\nabla T + T (R(v,\\lambda) + d_t S(v))\\right) d\\vec x\n\\end{align*}\n\n\nAccordingly, $M^{stdy}(v)=\\int_\\Omega \\left(J(v) \\nabla T + T R(v)\\right) d\\vec x$ and\n  $M^{tran}(v) = \\int_{\\Omega} S(v) T d\\vec x$\nand\n$$M_a(\\omega)= \\int_\\Omega \\left(J_v(v_0)\\nabla v_a \\nabla T + T (R_v(v_0)v_a + i\\omega S_v(v_0)v_a)\\right) d\\vec x$$\n\nWith a finite volume discretizatiom, this representation has a discrete counterpart.\n\n\n\\subsection{Examples with analytical impedance expressions}\nThese examples can be taken for benchmarking numerical methods.\n\\begin{example}{Current Response}\n  We calculate the impedance of the current response at $L$ to voltage change in $0$ of the linear reaction  diffusion system in $(0,L)$  \n  \\begin{equation*}\n    \\begin{cases}\n      Cu_t - (Du_x)_x + Ru=&0\\\\\n      u(0,t)=&\\lambda\\\\\n      u(L,t)=&0\\\\\n    \\end{cases}\n  \\end{equation*}\n    As response functions we take the currents  $I_0=Du_x(0,t)$ and $I_L=-Du_x(L,t)$.\n    The corresponding impedance equation is\n    \\begin{equation*}\n      \\begin{cases}\n        Ci\\omega v - (Dv_x)_x +Rv =&0\\\\\n        v(0,t)=&1\\\\\n        v(L,t)=&0.\\\\\n      \\end{cases}\n    \\end{equation*}\nSetting $z=\\sqrt{i\\omega\\frac{C}{D}+\\frac{R}{D}}$, for the solution, we make the ansatz\n\\begin{equation*}\n  v=ae^{zx}+be^{-zx}\n\\end{equation*}\nwhich fulfills the differential equation.\nSetting $e^+=e^{zL},e^-=e^{-zL}$, from the boundary \nconditons we get the system\n\\begin{equation*}\n  \\begin{cases}\n    a+b&=1\\\\\n    ae^++be^-&=0\\\\\n  \\end{cases}\n\\end{equation*}\nwith the solutions $a=\\frac{e^-}{e^--e^+},b=\\frac{e^+}{e^+-e^-}$\nTherefore, we have\n\\begin{equation*}\n  Dv_x(0)=Dz(a-b)=Dz\\frac{e^-+e^+}{e^--e^+}\n\\end{equation*}\nand\n\\begin{equation*}\n  Dv_x(L)=Dz(ae^+-be^-)=Dz\\frac{e^-e^++e^+e^-}{e^--e^+}=\\frac{2Dz}{e^--e^+}\n\\end{equation*}\n\nAlternatively, we might be interested in e.g. $M(v)=\\int_\\Omega |\\nabla v|^2$\nas measurement. We have\n\\begin{align*}\n  \\nabla v&=a z e^{zx} - b z e^{-zx}\\\\\n  |\\nabla v|^2&=a z e^{2zx} -ab +  b z e^{-2zx}\\\\\n  \\int  |\\nabla v|^2 \\; dx &=  \\frac{1}{2z}aze^{2zx}  -\\frac{1}{2z}  b z e^{-2zx} - abx + C\\\\\n          &= \\frac{a}{2}e^{2zx}  -\\frac{b}{2}  b e^{-2zx} -abx +C\\\\\n  \\int_0^L  |\\nabla v|^2 \\; dx &=   \\frac{a}{2}e^{2zL}  -\\frac{b}{2}  e^{-2zL} -abL\n            -  \\frac{a}{2}  +\\frac{b}{2}\\\\\n  \\int_0^L  |\\nabla v|^2 \\; dx &=   \\frac{a}{2}(e^{2zL}-1)  -\\frac{b}{2} (e^{-2zL}-1) -abL\\\\\n                               &=    \\frac12\\frac{e^{-zL}}{e^{-zL}-e^{zL}}(e^{2zL}-1)  -\\frac12\\frac{e^{zL}}{e^{zL}-e^{-zL}} (e^{-2zL}-1) -abL\\\\\n          &=    \\frac12\\frac{e^{zL}-e^{-zL}}{e^{-zL}-e^{zL}}  -\\frac12\\frac{e^{-zL}-e^{zL}}{e^{zL}-e^{-zL}} -abL\\\\\n              &=-abL\\\\\n  &= \\frac{L}{e^{2zL} + e^{-2zL}-2}\n\\end{align*}\n\nBut ... the measurement is different: it has to be the derivative at $v_0$ applied to the solution:\n\\begin{align*}\n  2\\int_\\omega \\nabla v_0 \\nabla v_a \n\\end{align*}\nSteady state: $u(0)=1$, $u(L)=0$. Let $d=\\sqrt{\\frac{R}{D}}$.\nSet $u(x)=fe^{dx}+ ge^{-dx}$. \n\\begin{align*}\n  u'(x) &= fd e^{dx} -gde^{-dx}\\\\\n  u''(x) &= fd^2 e^{dx} +gd^2e^{-dx}=d^2 u(x)\\\\\n  u(0)=f+g\\\\\n  u(L)=fe^{dL}+ge^{dL}\n\\end{align*}\nSo for $d^+=e^{dL}$ and $d^-=e^{-dL}$ we get\n$f=\\frac{d^-}{d^--d^+}$ and $g=\\frac{d^+}{d^+-d^-}$ \n\nSo we have to calculate\n\\begin{align*}\n  \\nabla v_0 \\nabla v_a&=  (aze^{zx}-bze^{-zx})(fde^{dx}-gde^{-dx})\\\\\n                       &= azfde^{(z+d)x} -azgde^{(z-d)x}  - bzfde^{(d-z)x} + bzgde^{-(z+d)x}\\\\\n  \\int \\nabla v_0 \\nabla v_a &=   \\frac{azfd}{z+d}e^{(z+d)x} -\\frac{azgd}{z-d}e^{(z-d)x}  - \\frac{bzfd}{d-z}e^{(d-z)x} - \\frac{bzgd}{z+d}e^{-(z+d)x}\\\\\n  &=  zd\\left(\\frac{af}{z+d}e^{(z+d)x} -\\frac{ag}{z-d}e^{(z-d)x}  - \\frac{bf}{d-z}e^{(d-z)x} - \\frac{bg}{z+d}e^{-(z+d)x}\\right)\n\\end{align*}\n\n\\end{example}\n\n\n\\begin{example}{Voltage response}\nRegard the system\n  \\begin{equation*}\n    \\begin{cases}\n      Cu_t - (Du_x)_x + Ru=&0\\\\\n      u(0,t)=&\\lambda\\\\\n      (Du_x)(L,t)=&0\\\\\n    \\end{cases}\n  \\end{equation*}\n  and observe the values $u(L)$ and $Du_x(0)$.\nThe same ansatz as in the previous example leads to \n\\begin{equation*}\n  \\begin{cases}\n    a+b&=1\\\\\n    izae^+-izbe^-&=0\\\\\n  \\end{cases}\n\\end{equation*}\nwith the solutions $a=\\frac{e^-}{e^++e^-}$ and $b=\\frac{e^+}{e^++e^-}$\nTherefore,  $Du_x(0)=iDz\\frac{e^--e^+}{e^++e^-}$ and\n$u(L)=\\frac2{e^++e^-}$.\n\\end{example}\n\n\n\\section{Algorithmic implementation}\n\nAlgorithmically, we proceed as follows:\n\n\\begin{description}\n\\item[1] Given $\\lambda$, solve steady state equation $D(v,\\lambda)=0$\n\\item[2] Obtain Jacobi matrix for stationary problem\n\\item[3] Obtain Jacobi matrix of time derivative\n\\item[4] Obtain Derivative of measurement (both steady state and transient parts)\n\\item[5] Prepare system for impedance problem\n\\item[6] For $\\omega=\\omega_0\\dots\\omega_1$:\n  \\begin{description}\n  \\item[6.1] set up complex matrix\n  \\item[6.2] solve complex system, take old solution as initial value if this is done iteratively\n  \\item[6.3]calculate impedance functional\n  \\end{description}\n\\end{description}\n\n\\end{document}\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "2ca1d51a21303e99f0fab3f1d33d2c6a53cb9970", "size": 14514, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/src/impedance-derivation.tex", "max_stars_repo_name": "PatricioFarrell/VoronoiFVM.jl", "max_stars_repo_head_hexsha": "690943ff455c91f16d114ad52cc83f2e8fa84e58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 80, "max_stars_repo_stars_event_min_datetime": "2019-11-18T05:04:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T04:11:01.000Z", "max_issues_repo_path": "docs/src/impedance-derivation.tex", "max_issues_repo_name": "PatricioFarrell/VoronoiFVM.jl", "max_issues_repo_head_hexsha": "690943ff455c91f16d114ad52cc83f2e8fa84e58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28, "max_issues_repo_issues_event_min_datetime": "2019-11-19T18:12:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T15:39:14.000Z", "max_forks_repo_path": "docs/src/impedance-derivation.tex", "max_forks_repo_name": "PatricioFarrell/VoronoiFVM.jl", "max_forks_repo_head_hexsha": "690943ff455c91f16d114ad52cc83f2e8fa84e58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28, "max_forks_repo_forks_event_min_datetime": "2019-08-29T16:46:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T14:10:29.000Z", "avg_line_length": 38.2955145119, "max_line_length": 150, "alphanum_fraction": 0.6550916357, "num_tokens": 5295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.33342144406819485}}
{"text": "\\chapter{Timestamping}\n\\label{chpr:timestamping}\nPlacing a certain date on some data is surprisingly useful \\cite{Haber91howto, Bayer93improvingthe, Massias99designof, OTSannouncment}.\nAn inventor who had a patentable idea or a scientist who came to a relevant conclusion may want to create a verifiable proof that at a certain moment they discovered something. This can help them to protect their intellectual property, proving others their precedence over competing claims.\nIn a communication protocol having the possibility to attach a certain time to messages can improve the security of the transmission. However it is often difficult to come to an agreement on which is the correct time to use, so different security models yield to different practical schemes.\nWhen storing documents in a third party cloud server, it could behave maliciously, for instance modifying their contents. Placing a certain and tamper resistant date on a document will make harder for the server provider to corrupt that file: the attacker should also be able to falsify the certificate stating the date. \n\nOther practical applications of this technique are possible, however to have a complete understanding of the subject it is important to figure out which are its limits and which are the right choices to take to correctly put the concepts into practice. So we need to be a little more formal,\n\\begin{mydef}\n\tA timestamp is a proof that some data $d$ existed prior to time $t$.\n\\end{mydef}\nTo create such proof, $d$ has to cause an event that could not have been generated without the existence of $d$. Such event it is bound to time $t$ and can be observed by others, we call its record \\textit{time attestation}. So a proof consists in the data $d$, the set of \\textit{operations} that were applied to cause the event and the time attestation.\n\nProofs are useful if they are able to convince the verifiers. He must be able to check the correctness of the operations and must retain trustworthy the time attestation. Depending on the problem in exam one should properly choose which operations and attestations to use. \n\nLet's consider the case of a sent letter. The data $d$ is the content of the letter, $d$ caused the palpable letter: if $d$ were different the letter would be different. When the letter went through the post office a postmark with the date $t$ was stamped on the letter, the postmark is the time attestation. If the post officer is trustworthy, a verifier who examines the letter may be convinced that the content of the letter existed prior to the time stated in the postmark. However a good counterfeiter could change the content of the letter or falsify the postmark placing a false date, thus for some cases such proof would not be appropriate.\n\nIn the case of a digital document new problems arises: it is not necessary to be a good counterfeiter to falsify a document without leaving any kind of tamper evidence, thus new solutions must be adopted. A timestamp for the data $d$ should guarantee that if even only a single bit of $d$ is modified the timestamp proof becomes invalid. To solve this problem cryptography tools are used \\cite{Haber97securenames}. Digital data can also be shared easily and with little costs, this is among the features that enables the possibility to achieve distributed and decentralized consensus. Such an achievement would give user the chance to timestamp without any trust in a third party.\n\nResuming, at a certain moment $t_e$ some data $d$ exists, then at $t_c$ someone (or something) will have the necessity to prove the existence of $d$, so he implements the timestamp \\textit{creation procedure} that results in a proof stating that $d$ existed priort to time $t$. Consequently at time $t_v$ a challenger implements the \\textit{verification procedure} that ends in a binary result: true if he retains the proof correct, false otherwise. Naturally we have $t_e<t_c<t<t_v$.\n\nTo avoid common misunderstandings, it is important to clarify what a timestamp does not prove. The time $t$ is the first moment when $d$ went to existence, the creation procedure is not instantaneous and of course if the proof for $(d,t)$ is true then there exists a proof for $(d,t')$ which holds true for all $t'>t$. A timestamp is not necessarily linked to its creator and moreover it doesn't prove that who owns the timestamp (it can be owned by multiple entities) is the creator of the data $d$: it just proves that someone knew $d$. If an inventor comes up with a timestamp stating that he had a particularly smart idea prior to time $t$, it does not mean that he was the first one to have such idea, in fact he could have simply overheard the idea from a colleague and afterwards timestamped it. A timestamp does not prove that data $d' \\neq d$ does not exist. Imagine someone stating that he knew the result of the elections prior to the vote, he provides a timestamp and claims that it proves he predicted the correct outcome. However he could be an imposter: he may had timestamped several different results and once he saw how the vote count ended he will provide only the proof which make him look as a visionary.\nAlthough these limitations being able to timestamp is still useful. If stronger proofs are needed the used system must be endowed with other tools that actually provides what is asked. \n\nIn the following sections we analyse the two ingredients of timestamp proofs: operations and attestations.\n\n\\section{Commitment Operations}\n\nThe operations that compose a timestamp proof should be defined in a precise way, a verifier will check their correctness when evaluating the proof. An useful operation binds the data in a way that it is hard or impossible to modify the data after the creation of the timestamp. Being more general, such an operation commits the input to the output: the input cannot be changed without changing the output. The result of the operation is a commitment to the input, in the sense that it was caused by the input or, in other words, the input precede in time the output.\nFor instance in the case of a sent letter, the input is the content of the letter, the piece of paper that is sent is the output and physically writing the letter is the operation that commits the input to the output. We can say that a letter is a physical commitment to its content. If one wants to modify the content of the letter ex post it will change the letter itself. However, tamper evidence could be extremely hard to spot.\n\nDigital document are easier to tamper, but they could be defined in a more precise way, representing each document with bits. To take full advantage of this, we need a formal definition,\n\\begin{mydef}\n\tA function $C:X \\rightarrow Y$ is a commitment operation if given $x_1 \\in X$ it is not feasible to compute $x_2 \\in X$ s.t. $x_1 \\neq x_2, C(x_1)=C(x_2)$.\n\\end{mydef}\nThe property required is sometimes referred as second pre-image resistance. For practical purposes $X$, $Y$ can be thought as bit string spaces, their element can be seen as bit strings or another of their representations, for instance in hexadecimal digits or using a conventional encoding.\nThe simplest examples are the append and prepend operations:\n\n\\begin{myexample}\n\t\\textquotedblleft hello\\textquotedblright, \\textquotedblleft world\\textquotedblright $\\xrightarrow{\\text{append()}}$ \\textquotedblleft helloworld\\textquotedblright.\n\\end{myexample}\nIt is impossible to change the inputs without changing the output: the output contains the inputs themselves.\nIn the example the function is a binary operation, however, by fixing one input, it is possible to turn these commitment operations into unary operations:\n\\begin{myexample}\n\t\\textquotedblleft world\\textquotedblright $\\xrightarrow{\\text{prepend(\\textquotedblleft hello\\textquotedblright)}}$ \\textquotedblleft helloworld\\textquotedblright.\n\\end{myexample}\nAppend and prepend have two problems: they reveal everything about the inputs and the size of the output is always greater than the size of the inputs. \n\nHiding the input of a commitment is often useful. For instance Robert Hooke \\cite{Petroski96invention} in 1676 had formulated the spring law that will take his name. He wanted to prove that he knew that without revealing the law itself, so he published the latin anagram \\textquotedblleft ceiiinosssttuv\\textquotedblright. Later in 1678 he revealed the solution, \\textquotedblleft ut tensio, sic vis\\textquotedblright (\\textquotedblleft as the extension, so the force\\textquotedblright). However the anagram is not an optimal commitment operation: \\textquotedblleft ut vis, sic tensio\\textquotedblright is a solution too. For that time it was an acceptable solution, the verification procedure had minimal requirements and there was no real incentive in lying. Nowadays better solutions are available, hence using an anagram will make the verifier suspicious.\n\nTo address these problems cryptographic hash functions are used. Hash functions maps bit strings of arbitrary finite length into bit strings of fixed length \\cite{Damgard:1989:DPH:118209.118248}. \n\\begin{mydef}\n\t$h : \\{ 0, 1 \\} ^* \\rightarrow \\{ 0, 1 \\} ^n $ is a hash function if it is computable in polynomial time in the length of the input.\n\\end{mydef}\nWe will refer at the input of such functions as preimage, and the output as hash value. The codomain is strictly contained in the domain hence the presence of collisions (pairs of inputs with identical outputs) is unavoidable. \nTo give to these functions a practical use some of the following properties are required\n\\begin{mydef}\n\t\\label{hash-prop}\n\tLet $h$ be a hash function, the following properties may hold:\n\t\\begin{itemize}\n\t\t\\item preimage resistance: given $h(x)$ it is not feasible to compute $x$;\n\t\t\\item second-preimage resistance: given $x$ it is not feasible to compute $y$ s.t. $x \\neq y$, $h(x)=h(y)$;\n\t\t\\item collision resistance: it is not feasible to find $x, y$ s.t. $x \\neq y$, $h(x)=h(y)$.\n\t\\end{itemize}\n\\end{mydef}\n\nA preimage resistant hash function hides the inputs, this property is sometimes referred as one-wayness.\nA second-preimage resistant hash function is also a commitment operation, in addition it hides the input and create a fixed size fingerprint. A huge file can be mapped into a short bit string which is a commitment to it.\nCollision resistance, although is a nice to have, is not necessary for timestamping purposes: when a collision ($x \\neq y$ s.t $h(x)=h(y)$) is found, $x$ and $y$ are found at the same time \\cite{SHA1}.\n\nSuch properties depend on the dimension of the codomain, which is given by the parameter $n$, precisely $2^n$. If it is too low it will be easy to produce examples that invalidates the properties, if it is too high the hash function is not a good tool for reducing the size of the input. A good compromise has to be found, it should be based on the current state of the art of cryptanalysis and computer science. However what is considered acceptable during a period may not be accepted in a subsequent one, in fact if new techniques that break an hash function are discovered, then its use will be considered insecure.\nSeveral hashing functions has been proposed, we show a couple of examples:\n\\begin{myexample}\n\tSHA1 (Secure Hashing Algorithm) was designed by the National Security Agency (NSA), and released in 1995. It maps bit strings to a 160 bit space, it was considered preimage, second-preimage and collision resistant. In 2005 cryptanalysts discover a theoretical procedure to find collisions, later practical attacks were published \\cite{cryptoeprint:2017:190}, hence it was declared insecure. However only collision resistance was broken, thus it can still be used for timestamping purposes.\n\t\\begin{verbatim}\n\tSHA1(b'Hello World!\\n') = a0b65939670bc2c010f4d5d6a0b3e4e4590fb\n\t                          92b\n\tSHA1(b'Hello World\\n')  = 648a6a6ffffdaa0badb23b8baf90b6168dd16\n\t                          b3a\n\t\\end{verbatim}\n\\end{myexample}\n\n\\begin{myexample}\n\tSHA256 belongs to the family SHA2, the generation of hash functions following SHA1\\footnote{Currently, it is available SHA3, which contains, among others, KECCAK256.}. It outputs  strings 256 bit long and, at the moment, it is considered to satisfy all the properties in Definition \\ref{hash-prop}.\n\tSeveral systems are built upon this assumption. \n\tIn addition, as other hash functions, SHA256 could be modeled as a random oracle, a fixed input will provide always the same output, since hash functions are deterministic, but the outputs corresponding to new inputs will give results that are indistinguishable from a uniform distribution. \n\tNote how a little change in the input produces outputs very dissimilar in both hash functions, this feature helps to spot alterations in the inputs.\n\t\\begin{verbatim}\n\tSHA256(b'Hello World!\\n') = 03ba204e50d126e4674c005e04d82e84c21\n\t                            366780af1f43bd54a37816b6ab340\n\tSHA256(b'Hello World\\n')  = d2a84f4b8b650937ec8f73cd8be2c74add5\n\t                            a911ba64df27458ed8229da804a26\n\t\\end{verbatim}\n\tSince SHA256 is available, the use of SHA1 should be avoided unless there is a particular motivation. \n\\end{myexample}\n\nMore complex commitment operations are possible.\nBut they should be used only if there are some valid and shared motivations. Finding a badly motivated commitment operation in a proof will make verifiers suspicious.\n\nCombining the examples we saw it is possible to implement a data structure that is useful to embed several commitments into a single hash value, \nthis structure is called \\textit{Merkle tree} \\cite{DBLP:conf/sp/Merkle80}. Let $h$ be a second-preimage resistant hash function, start from $k$ data to timestamp $\\{d_i\\}_{i=1}^k$, called \\textit{leaves}, compute their hash values $\\{h(d_i)\\}_{i=1}^k=\\{h_i\\}_{i=1}^n$. The first step combines the couples of adjacent values (if there is one) by concatenating ($||$) the two values and computing the hash value of the concatenation: $h(h_i||h_{i+1})$ $\\forall i \\in [1,k]$ odd. The following steps proceed in an analogous manner, but starting from the results computed at the step before as described in Algorithm \\ref{alg:merkle-tree}. \n\n\\begin{algorithm}\n\t\\caption{Merkle tree construction}\n\t\\label{alg:merkle-tree}\n\t\\begin{algorithmic}[1]\n\t\t\\Procedure{merklestep}{$\\{h_i\\}_{i=1}^k$}\n\t\t\\State $S \\gets \\{\\}$\n\t\t\\For {$i\\gets 1,k$ s.t. $i\\equiv 1 (2)$}\n\t\t\\State $S \\gets S \\cup \\begin{cases} \n\t\th(h_i||h_{i+1}) & i \\neq k \\\\ \n\t\th(h_i) & i=k           \n\t\t\\end{cases}$\n\t\t\\EndFor\n\t\t\\State \\textbf{return} $S$\n\t\t\\EndProcedure\n\t\t\\Statex\n\t\t\\Procedure{merklelize}{$\\{d_i\\}_{i=1}^k$} \\Comment{from the leaves to the Merkle tip}\n\t\t\\State $S \\gets \\{\\}$\n\t\t\\For {$i\\gets 1, k$}\n\t\t\\State $S\\gets S \\cup h(d_i)$\\Comment{hash the leaves}\n\t\t\\EndFor\n\t\t\\State $k\\gets |S|$\n\t\t\\While {$k \\neq 1$}\n\t\t\\State $S \\gets$ \\Call{merklestep}{S} \\Comment{if necessary, store $S$}\n\t\t\\State $k\\gets |S|$\n\t\t\\EndWhile\n\t\t\\State \\textbf{return} $S$ \\Comment{Merkle tip}\n\t\t\\EndProcedure\n\t\\end{algorithmic}\n\\end{algorithm}\n\nAfter at most $\\lceil log(k) \\rceil$ steps the algorithm ends and one hash value is returned, it is called \\textit{Merkle tip} or \\textit{Merkle root}. \nThanks to reiteration of $h$ the tip is a commitment to all the leaves $\\{d_i\\}_{i=1}^k$, moreover to prove that a element $d_i$ is committed it is not necessary to know all tree, in fact it's enough to show the \\textit{Merkle path} starting from $d_i$ and ending in the tip. \nFor instance referring to Figure \\ref{fig:merkle-tree} the minimal requirement to show the commitment of $data3$ in $MT$ is the ordered sequence of operations to apply is:\n\\begin{verbatim}\nh, append(h4), h, prepend(A), h, append(E), h\n\\end{verbatim}\nMerkle trees can aggregate several commitments into one hash value, giving a scalability solution: the length of a single proof grows logarithmically with the number of leaves.\n\n\\begin{figure}\n\t\\begin{center}\n\t\t\\includegraphics[width=\\linewidth]{Images/merkle-tree.png}\n\t\t\\caption[Merkle tree example]{Merkle tree example. The Merkle root is a commitment to the leaves $\\{data_i\\}_{i=1}^5$.}\n\t\t\\label{fig:merkle-tree}\n\t\\end{center}\n\\end{figure}\n\n\\section{Time Attestations}\nAttestations are provided by a notary, which has the authority to state the time.\nNotaries are sometimes referred as timestamp servers, who ask for creating or verifying that a timestamp is referred as client.\nA time attestation binds some data $d$ to the time $t$, $d$ could be directly the data to timestamp or a commitment to them. \nTo properly design a timestamp scheme it is crucial to analyse which features an attestation should have and how to choose a notary that provides the desired security.\n\nAn attestation should be \\textit{tamper resistant} or, even better, \\textit{immutable}. Once created no one should be able to modify that, backdating the timestamp or changing the underlying data without making the attestation invalid.\n\nIn the case of a sent letter an important issue comes to the attention: the attestation (postmark) can be verified only if the letter is in our hands. This makes the task of a counterfeiter easier, few people will examine the postmark making the success of the attack more likely. A solution that mitigates this issue is \\textit{widely publishing} the attestation, for instance inserting it in a newspaper. The attacker has an harder task, in most cases, to guarantee himself good chances of success he needs to modify several, or even all, attestations leading to a higher cost. Considering an attestation on a newspaper, an attacker could counterfeit only the exact copy the verifier is going to check. To prevent such situation the verifier should check multiple sources and should not expose any information on where he is retrieving the copies used to examine. Attestations should be \\textit{easily accessible}, for instance a good solution is to publish them on the internet.\n\nWe call the service providing the attestations notary, it has the authority to state the time. To maintain such power it has to show itself as \\textit{trustworthy}: it should place the correct time in the attestations, it should not trick the clients modifying the timestamp ex post and he should not collude with the creator of the timestamp to trick a verifier. Moreover a notary should be \\textit{competent}: if it looses the information necessary to verify the timestamp, then its creator will be damaged.\n\nA good notary does not make distinctions among clients or data to timestamp, in other words it does \\textit{not censor}. An improvement would be if it is not aware of what it is timestamping, like the case of the commitments hiding their inputs, but even better if it is not aware of being used as a timestamp server, like the newspaper.\n\nIn the case of a sent letter, the notary is the post officer, he will place the postmark on the letter giving it a date. \nClients must trust such notary, which in theory can place a wrong date $t'$ instead of $t$, creating a false timestamp (if $t'<t$) or a deliberate weaker proof (if $t'>t$). Alternately he can decide not to timestamp a letter or modifying its content before timestamping. In addition the resulting timestamp is unique, thus if it gets damaged or lost the proof is gone forever.\n\nA notary willing to show himself as more trustworthy can make its possibly dishonest behaviour harder to implement. A possible solution is to link all the timestamps so that changing one would implies changing all the subsequent ones. A timestamp proof $TS_i$ for the data $d_i$ at the time $t_i$ ($t_{i-1}<t_i<t_{i+1}$) would have the following structure:\n\\begin{equation}\n\t\\label{singed-chain}\n\t\\begin{cases}\n\t\tTS_0 =(d_0,t_0, \\sigma_N((d_0,t_0))) & \n\t\t\\\\\n\t\tTS_i =(d_i,t_i,TS_{i-1}, \\sigma_N((d_i,t_i,TS_{i-1}))) & i = 1, ..., i_{max}\t\t\n\t\\end{cases}\n\\end{equation}\nwhere $\\sigma_N (x)$ is a commitment to the data $x$. Such commitment is created by the notary, who is (supposedly) the only one who is able to apply $\\sigma_N$. We call this function \\textit{signature}, it can be physical (as a postmark) or digital (with a public key cryptosystem). The signature $\\sigma_N$ is a commitment operation, so if $TS_{i}$ changes then $\\sigma_N((d_{i+1},t_{i+1},TS_i))$ changes, thus $TS_{i+1}$ changes resulting in $TS_j$ changing for all $j>i$. Starting from the \\textit{genesis timestamp} $TS_0$, the linked timestamps $\\{ TS_{i} \\}_{i=0}^{i_{max}}$ form a \\textit{chain}. A trusted notary which implement this scheme will be preferred by honest clients. Depending on each particular problem the designer of the system has to properly choose how to collect the timestamp requests, how to commit them into the chain, the time frequency, the signature procedure, how to publish the chain and how to distribute the timestamp proof to the clients.\n\nEven though linking the timestamps is a great improvement with respect to the previous schemes, having a trusted notary still involves some issues. The notary may loose what he needs for signing (e.g. stamp, private key); if an attacker can sign in the place of the notary, it will no longer be considered authoritative; if no one can sign the clients will be damaged. In addition the notary can create more than one chain starting from the same genesis timestamp, then he can use different chains for different clients. \nAnyhow nothing can guarantee that a trusted notary will behave honestly in the future, it can attack some clients in several ways and such bad behaviour can be hard to spot rapidly, a single client may realize that he has been tricked only when he needs the timestamp.\n\nTrusted attestations has security issues hence, in some situations, they could be considered not enough appropriate, yet for years an efficient solution that does not involve a trusted third party was considered barely impossible. \nIn 2008 Satoshi Nakamoto proposed \\cite{Nakamoto_bitcoin:a} which described a system to transfer value from one party to another without relying on the presence of a central authority. The system can be also used to timestamp arbitrary data without trusting any notary.", "meta": {"hexsha": "97436de44fbc22197d2bca68f1a1a2dba8d630ef", "size": 22092, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapters/Timestamping.tex", "max_stars_repo_name": "LeoComandini/Thesis", "max_stars_repo_head_hexsha": "d5754ae5c05f110e1fba115dc011f240878933f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2018-04-09T03:42:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-20T10:25:26.000Z", "max_issues_repo_path": "Chapters/Timestamping.tex", "max_issues_repo_name": "LeoComandini/Thesis", "max_issues_repo_head_hexsha": "d5754ae5c05f110e1fba115dc011f240878933f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapters/Timestamping.tex", "max_forks_repo_name": "LeoComandini/Thesis", "max_forks_repo_head_hexsha": "d5754ae5c05f110e1fba115dc011f240878933f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-04-06T17:48:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-19T09:36:36.000Z", "avg_line_length": 122.0552486188, "max_line_length": 1225, "alphanum_fraction": 0.7777023357, "num_tokens": 5361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3333221631901137}}
{"text": "\\lispy/ is statically typed. This means type safety (i.e.\\ that there are no discrepancies between expected types of values and actual types of values) is verified at compile time by analysing the source code. The language has  a small set of types and a limited (but simple) type system. The language has type inference for everything except function parameters, meaning it can determine the type of a value at compile time without relying on being explicitly told the type by the programmer.\n\n\\subsection{int and float}\nThere are both integer and rational numbers. The former are \\texttt{int}s and the latter are \\texttt{float}s (a fixed-point representation). The syntax for them is a bit laxer than it is in LISP 1.5 (see~\\nameref{sec:syntax}). However, octal number literals are unsupported. There are also \\texttt{float} constants for \\texttt{inf} (floating-point positive infinity) and \\texttt{nan} (``not a number'').\n\nThe behaviour of precision and overflow is implementation-defined. For the reference implementation, these types are implemented using Python's \\texttt{int} and \\texttt{float} types, so they are subject to the same limitations in \\lispy/ as they are in Python. That further depends on the Python interpreter used to run the compiled code.\n\n\\subsection{bool}\nThe \\texttt{bool} type is represented by the literal atoms \\texttt{true} and \\texttt{false}. This is a replacement for the \\texttt{T} and \\texttt{NIL} used by predicates in LISP 1.5. Having a single Boolean type makes it simple from a type checking perspective to implement predicates in \\lispy/.\n\n% TODO: mention that recursion is possible.\n\\subsection{func} \\label{subsec:func}\nA \\texttt{func} is a function as described in~\\nameref{subsec:simpleforms}. The fundamental way to create a function is with a special form know as a \\textit{lambda expression}. The resulting function is called a \\textit{lambda function}. The distinction from just \\textit{function} is that a lambda function is not bound to any name. Thus, to evaluate a lambda function, a composed form has to be used. In fact, the use of a lambda expression in place of a function name is what was being alluded to briefly in the description of~\\nameref{subsec:composedforms}. As with function names, the lambda expression is evaluated first in the form, and then the arguments are evaluated.\n\n\\begin{figure}[htp]\n    \\centering\n    \\begin{cminted}[autogobble=true, escapeinside=??]{lisp}\n        (?\\tikzmark{exp_start}?(lambda ?\\tikzmark{param_start}?((?\\tikzmark{atom_start}?x?\\tikzmark{atom_end}? int) (y ?\\tikzmark{type_start}?int?\\tikzmark{type_end}?))?\\tikzmark{param_end}? ?\\tikzmark{form_start}?(div x y)?\\tikzmark{form_end}?)?\\tikzmark{exp_end}? ?\\tikzmark{arg_start}?1 2?\\tikzmark{arg_end}?)\n    \\end{cminted}\n    \\begin{tikzpicture}[\n        remember picture,\n        overlay,\n        thick,\n        font=\\scriptsize,\n        every node/.style={pos=0.5, black}\n    ]\n        \\draw[decorate, decoration={calligraphic brace, mirror, raise=0.25em, amplitude=1pt}]\n            (pic cs:atom_start) -- (pic cs:atom_end)\n            node[below=0.5em]{atomic literal};\n\n        \\draw[decorate, decoration={calligraphic brace, mirror, raise=0.25em, amplitude=3pt}]\n            (pic cs:type_start) -- (pic cs:type_end)\n            node[below=0.5em]{type};\n\n        \\draw[decorate, decoration={calligraphic brace, mirror, raise=1.75em, amplitude=3pt}]\n            (pic cs:param_start) -- (pic cs:param_end)\n            node[below=2em]{parameters};\n\n        \\draw[decorate, decoration={calligraphic brace, mirror, raise=0.25em, amplitude=3pt}]\n            (pic cs:form_start) -- (pic cs:form_end)\n            node[below=0.5em]{body};\n\n        \\draw[decorate, decoration={calligraphic brace, mirror, raise=0.25em, amplitude=3pt}]\n            (pic cs:arg_start) -- (pic cs:arg_end)\n            node[below=0.5em]{arguments};\n\n        \\draw[decorate, decoration={calligraphic brace, mirror, raise=3.25em, amplitude=5pt}]\n            (pic cs:exp_start) -- (pic cs:exp_end)\n            node[below=3.5em]{lambda expression};\n    \\end{tikzpicture}\n    \\captionsetup[figure]{font=small, skip=5em}\n    \\captionof{figure}{A lambda function being evaluated.}\n\\end{figure}\n\nA function's evaluated value (the \\textit{return value}) is the result of evaluating the function body with the function variables, which are bound to some values (the \\textit{arguments}) prior to evaluation.\n\nFunction parameters are defined as pairs, of which there can be 0 or more. The first element of the pair is the name of the parameter. The second element is the type of that parameter. All parameters must be specified with their types; they are never type-inferred. Note that neither element of this pair is evaluated (this is possible because a lambda expression is a special form).\n\nUnlike parameters, the return value and arguments \\textit{will} be type inferred. In fact, there is no mechanism in the language for explicitly specifying the type of a return value or argument.\n\n\\subsubsection{First-class Functions}\nFunctions are \\textit{first-class citizens} in the language. This means that, like other values, a function can be passed as an argument to another function, can be returned from other functions, and can be assigned to variables. As a consequence, \\textit{higher-order functions} are supported, which are functions that takes a function as an argument and/or return a function.\n\n\\begin{figure}[htp]\n    \\centering\n    \\begin{cminted}[autogobble=true]{lisp}\n        (lambda ((f (func (int int) int))\n                 (i int))\n          (f 3 i)\n        )\n    \\end{cminted}\n    \\captionsetup[figure]{font=small}\n    \\captionof{figure}{A higher-order function that takes a function \\texttt{f} as an argument. \\texttt{f} has two \\texttt{int} parameters and an \\texttt{int} return value.}\n\\end{figure}\n\n\\paragraph{Special Forms}\nUnlike regular functions, special forms are not first-class citizens. However, this can be worked around by defining a lambda function which ``wraps'' the special form.\n\n\\begin{figure}[htp]\n    \\centering\n    \\begin{cminted}[autogobble=true]{lisp}\n        ((lambda ((f (func (int int) int))\n                 (i int))\n          (f 3 i))\n        (lambda ((a int) (b int)) (prod a b)) 2)\n    \\end{cminted}\n    \\captionsetup[figure]{font=small}\n    \\captionof{figure}{A lambda function wrapping a special form and being passed to another function. This is effectively doing $3 \\times 2 = 6$.}\n\\end{figure}\n\n\\subsubsection{Named Functions}\nLambda functions are not inherently bound to any variable. However, it can be quite useful to define a function so it can be re-used later. Since lambda functions are first-class citizens, it is valid to assign a lambda expression to a variable.\n\nOne way to do this has actually already been shown: rely on the binding mechanism of a lambda expression. A lambda can be bound to another lambda's parameters, and then the lambda will be accessible via a variable within the other lambda. However, this is tedious. A more convenient way to define functions with names is to use the \\texttt{let} special form. This will be discussed in~\\nameref{sec:bindingassign}.\n\n\\subsection{list}\nThe \\texttt{list} type stores a homogenous (i.e.\\ all of the same type) sequence of elements. Lists always have \\texttt{nil} as the final element.\n\nLists can be created with the special form \\texttt{cons}. For example, \\texttt{(cons 1 (2 (3 nil)))} creates the list \\texttt{(1 2 3)} (the presence of \\texttt{nil} is implicit). Notice that the second argument must be a list which holds elements that have the same type as the first argument. Alternatively, the special form \\texttt{list}, which takes an indefinite number of arguments, can create the same list: \\texttt{(list 1 2 3)}.\n\nThe first element of a list can be retrieved using the special form \\texttt{car}. For example, \\texttt{(car (list 1 2 3))} returns the value \\texttt{1}. Conversely, \\texttt{cdr} can be used to retrieve the remaining list: \\texttt{(cdr (list 1 2 3))} returns the value \\texttt{(2 3)}. Both \\texttt{car} and \\texttt{cdr} only accept one argument, which must be a \\texttt{list}.\n\n\\begin{figure}[htp]\n    \\centering\n    \\begin{cminted}[autogobble=true]{lisp}\n        (lambda ((n int) (l (list int)))\n          (prod n (car l)))\n    \\end{cminted}\n    \\captionsetup[figure]{font=small}\n    \\captionof{figure}{A lambda with a parameter that's a \\texttt{list} of \\texttt{int}s.}\n\\end{figure}\n\n\\subsubsection{nil}\nThe literal atom \\texttt{nil} represents an empty list. Thus, it also has a type of \\texttt{list}. In fact, an alternative way to represent \\texttt{nil} is \\texttt{()}. For \\texttt{nil}, \\texttt{car} and \\texttt{cdr} are unsupported -- attempting to do so will result in a runtime error.\n\n\\texttt{nil} is a built-in ``global'' variable that's accessible everywhere. However, it's special as far as variables go because it cannot be assigned a new value.\n", "meta": {"hexsha": "a86b905a6c7998ee65ed8947149fb7aee6da915c", "size": 8923, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/manual/types.tex", "max_stars_repo_name": "csun-comp430-s22/lispy", "max_stars_repo_head_hexsha": "03820211bd3c5a83e0de4b1ac26a864080e06aca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/manual/types.tex", "max_issues_repo_name": "csun-comp430-s22/lispy", "max_issues_repo_head_hexsha": "03820211bd3c5a83e0de4b1ac26a864080e06aca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-02-23T08:12:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T00:13:33.000Z", "max_forks_repo_path": "doc/manual/types.tex", "max_forks_repo_name": "csun-comp430-s22/lispy", "max_forks_repo_head_hexsha": "03820211bd3c5a83e0de4b1ac26a864080e06aca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 76.264957265, "max_line_length": 678, "alphanum_fraction": 0.7269976465, "num_tokens": 2346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3333221631901137}}
{"text": "\\documentclass[letterpaper,final,12pt,reqno]{amsart}\n\n\\usepackage[total={6.3in,9.2in},top=1.1in,left=1.1in]{geometry}\n\n\\usepackage{times,bm,bbm,empheq,fancyvrb,graphicx,amsthm,amssymb}\n\\usepackage[dvipsnames]{xcolor}\n\\usepackage{longtable}\n\\usepackage{booktabs}\n\n\\usepackage{tikz}\n\\usetikzlibrary{decorations.pathreplacing}\n\n\\usepackage[kw]{pseudo}\n\\pseudoset{left-margin=15mm,topsep=5mm,idfont=\\texttt}\n\n\\usepackage{float}\n\n% hyperref should be the last package we load\n\\usepackage[pdftex,\ncolorlinks=true,\nplainpages=false, % only if colorlinks=true\nlinkcolor=blue,   % ...\ncitecolor=Red,    % ...\nurlcolor=black    % ...\n]{hyperref}\n\n\\renewcommand{\\baselinestretch}{1.05}\n\n\\allowdisplaybreaks[1]  % allow display breaks in align environments, if they avoid major underfulls\n\n\\newtheoremstyle{cstyle}% name\n  {5pt}% space above\n  {5pt}% space below\n  {\\itshape}% body font\n  {}% indent amount\n  {\\itshape}% theorem head font\n  {.}% punctuation after theorem head\n  {.5em}% space after theorem head\n  {\\thmname{#1}\\thmnumber{ #2}\\thmnote{ (#3)}}% theorem head spec\n\\theoremstyle{cstyle}\n\n\\newtheorem{theorem}{Theorem}\n\\newtheorem{lemma}[theorem]{Lemma}\n\\newtheorem{assumptions}[theorem]{Assumptions}\n\n\\newtheoremstyle{cstyle*}% name\n  {5pt}% space above\n  {5pt}% space below\n  {\\itshape}% body font\n  {}% indent amount\n  {\\itshape}% theorem head font\n  {.}% punctuation after theorem head\n  {.5em}% space after theorem head\n  {\\thmname{#1}}% theorem head spec\n\\theoremstyle{cstyle*}\n\\newtheorem{assumptions*}{Assumptions}\n\n\\newtheoremstyle{dstyle}% name\n  {5pt}% space above\n  {5pt}% space below\n  {}%{\\itshape}% body font\n  {}% indent amount\n  {\\itshape}% theorem head font\n  {.}% punctuation after theorem head\n  {.5em}% space after theorem head\n  {\\thmname{#1}\\thmnumber{ #2}\\thmnote{ (#3)}}% theorem head spec\n\\theoremstyle{dstyle}\n\n\\newtheorem{definition}[theorem]{Definition}\n\\newtheorem{example}[theorem]{Example}\n\n% numbering\n\\numberwithin{equation}{section}\n\\numberwithin{figure}{section}\n\\numberwithin{table}{section}\n\\numberwithin{theorem}{section}\n\n\\newcommand{\\eps}{\\epsilon}\n\\newcommand{\\RR}{\\mathbb{R}}\n\n\\newcommand{\\grad}{\\nabla}\n\\newcommand{\\Div}{\\nabla\\cdot}\n\\newcommand{\\trace}{\\operatorname{tr}}\n\n\\newcommand{\\hbn}{\\hat{\\mathbf{n}}}\n\n\\newcommand{\\bb}{\\mathbf{b}}\n\\newcommand{\\be}{\\mathbf{e}}\n\\newcommand{\\bbf}{\\mathbf{f}}\n\\newcommand{\\bg}{\\mathbf{g}}\n\\newcommand{\\bn}{\\mathbf{n}}\n\\newcommand{\\br}{\\mathbf{r}}\n\\newcommand{\\bu}{\\mathbf{u}}\n\\newcommand{\\bv}{\\mathbf{v}}\n\\newcommand{\\bw}{\\mathbf{w}}\n\\newcommand{\\bx}{\\mathbf{x}}\n\\newcommand{\\bF}{\\mathbf{F}}\n\\newcommand{\\bV}{\\mathbf{V}}\n\\newcommand{\\bX}{\\mathbf{X}}\n\\newcommand{\\bxi}{\\bm{\\xi}}\n\\newcommand{\\bzero}{\\bm{0}}\n\n\\newcommand{\\cK}{\\mathcal{K}}\n\\newcommand{\\cV}{\\mathcal{V}}\n\n\\newcommand{\\rhoi}{\\rho_{\\text{i}}}\n\n\\newcommand{\\ip}[2]{\\left<#1,#2\\right>}\n\n\\newcommand{\\mR}{R^{\\bm{\\oplus}}}\n\\newcommand{\\iR}{R^{\\bullet}}\n\n\\newcommand{\\nn}{{\\text{n}}}\n\\newcommand{\\pp}{{\\text{p}}}\n\\newcommand{\\qq}{{\\text{q}}}\n\\newcommand{\\rr}{{\\text{r}}}\n\n\\newcommand{\\supp}{\\operatorname{supp}}\n\\newcommand{\\Span}{\\operatorname{span}}\n\n\n\\begin{document}\n\\title[On multilevel constraint decomposition methods]{On multilevel constraint decomposition methods \\\\ for nonlinear variational inequalities}\n\n\\author{Ed Bueler}\n\n\\date{\\today}\n\n\\begin{abstract} FIXME\n\\end{abstract}\n\n\\maketitle\n\n%\\tableofcontents\n\n\\thispagestyle{empty}\n%\\bigskip\n\n\\newfloat{pseudofloat}{t}{xyz}[section]\n\\floatname{pseudofloat}{Algorithm}\n\n\n\\section{Introduction} \\label{sec:intro}\n\nThe goal of this paper is to generalize the constraint decomposition (CD) method of X.-C.~Tai \\cite{Tai2003} to nonlinear VI problems to which it has not been previously applied.  The convergence of this method, for several types of decompositions, was proven by Tai for coercive variational inequality (VI) problems which arise from minimization of a convex functional over a convex set.  In its multilevel form the method has been shown to have optimal complexity for elliptic, linear obstacle problems \\cite[Subsection 5.4]{Tai2003}; see also \\cite[Theorem 4.6 and Algorithm 4.7]{GraeserKornhuber2009}.  We construct a new proof of convergence which removes the assumption that the problem arises from (constrained) optimization.  Furthermore we address its finite element (FE) implementation in nonlinear cases, and we demonstrate the resulting performance.\n\nThe algorithms and theory presented in \\cite{Tai2003} are extended in four particular directions:\n\\renewcommand{\\labelenumi}{\\emph{(\\roman{enumi})}}\n\\begin{enumerate}\n\\item We do not assume that the continuum VI problem arises from optimization of a scalar objective.  Nonetheless we can prove convergence in $H^1$ norm at the same rate as the original method converges in energy (Section \\ref{sec:convergence}); % HOPE\nexamples are explored in Sections \\ref{sec:vi} and \\ref{sec:results}.\n\n\\item We make the observation that, if implemented appropriately, multilevel ``up-smoothing'' is intrinsically more efficient than ``down-smoothing'' (Section \\ref{sec:multilevel}).  This observation seems to be new; compare the comments on V(1,0) and V(1,1) cycles in \\cite{GraeserKornhuber2009,Tai2003}.  A strong preference for up-smoothing is, apparently, special to multilevel CD methods and does not arise in corresponding unconstrained problems.\n\n\\item We make the multilevel CD algorithm more practical by addressing efficient storage of intermediate quantities.  In Section \\ref{sec:results} we show results from a full approximation storage (FAS; see \\cite{Brandt1977}) implementation for nonlinear operators, one which avoids global (Newton) linearization; compare \\cite{GraeserKornhuber2009}.\n\n\\item For problems of porous-media type the nonlinear operator $f$ is not coercive (Appendix A), so the convergence theory in \\emph{(i)} does not apply.  However, a full-cycle implementation of the multilevel CD method is demonstrated numerically.  By ``freezing' the solution-dependent coefficient, the operator is approximated by a coercive operator, nonlinear in general, for the duration of the V-cycle.  The resulting scheme is highly-effective for doubly-nonlinear diffusion operators (Section \\ref{sec:results}).\n\\end{enumerate}\n\nThe iterates from the CD method are always admissible, and thus the operator need only be defined for admissible states; Section \\ref{sec:results} includes a nontrivial example.  Admissible-iterate methods should permit direct solutions of certain VI problems, such as fluid-layer dynamics problems \\cite{Bueler2021conservation,JouvetBueler2012}, for which non-admissible methods, such as semi-smooth methods \\cite{BensonMunson2006}, require unnatural modifications of the operator formula.  The full-cycle scheme in \\emph{(iv)} above, which applies to non-coercive VIs, is also designed for these problems, which are characterized by the solution of an auxiliary PDE on a domain determined inside the VI residual evaluation.\n\nEspecially for the classical obstacle problem with a Laplacian operator, certain multilevel techniques are known to improve performance relative to the multilevel CD method \\cite{GraeserKornhuber2009}.  These improved methods either track the active set in the discretization or modify the nodal basis functions, and in this sense they are discrete algorithms.  By contrast the CD method applies at the level of the continuum problem (Sections \\ref{sec:cd} and \\ref{sec:convergence}), and thus it is a more fundamental method than the truncated monotone multigrid method \\cite{Kornhuber1994}, for example.  In any case, acceleration of our nonlinear multilevel CD method via active-set and/or basis-level manipulations represents a potential extension of the method here, though as a topic for future research.\n\n% A BRIDGE TOO FAR:  In one example at the end of this paper (Section \\ref{sec:resultsnonlocal}) we consider a nonlocal residual functional, that is, one which is not a partial differential operator.  Each evaluation of this functional requires the solution of a Stokes problem for a layer of fluid \\nocite{SayagWorster2013} on a substrate (which forms the obstacle), and thus the corresponding FE operator discretization is also not sparse.  In this case we cannot prove coercivity but we nonetheless succeed in demonstrating near-optimal complexity of the Section \\ref{sec:multilevel} multilevel CD algorithm in practice.\n\n\n\\section{Coercive variational inequalities} \\label{sec:vi}\n\nSuppose $\\cV$ is a real, reflexive Banach space with norm $\\|\\cdot\\|$ and topological dual space $\\cV'$.  Denote the dual pairing of $\\phi \\in \\cV'$ and $v\\in\\cV$ by $\\ip{\\phi}{v} = \\phi(v)$, and note that $\\|\\phi\\|_{\\cV'} = \\sup_{\\|v\\|=1} |\\ip{\\phi}{v}|$ defines a (Banach space) norm on $\\cV'$.\n\nLet $\\cK \\subset \\cV$ be a nonempty closed and convex subset, the \\emph{constraint set}; elements of $\\cK$ are said to be \\emph{admissible}.  For a continuous, but generally nonlinear, operator $f:\\cK \\to \\cV'$ and \\emph{source} $g\\in \\cV'$ we consider the following \\emph{variational inequality} (VI) for the (exact) solution $u^*\\in \\cK$, if it exists:\n\\begin{equation}\n\\ip{f(u^*)}{v-u^*} \\ge \\ip{g}{v-u^*} \\qquad \\text{for all } v\\in \\cK. \\label{eq:vi}\n\\end{equation}\nBecause $f$ is a (generally) nonlinear map, $g$ is not strictly needed when posing this VI, but its presence is helpful to the algorithms of Section \\ref{sec:multilevel}.  (Note that by redefining $f$ we may take $g=0$.)\n\nVI \\eqref{eq:vi} generalizes the nonlinear system of equations $f(u^*)=g$ from a vector space $\\cV$ to the constrained case (over $\\cK$).  Informally, if we conceptualize the dual pairing as an inner product then \\eqref{eq:vi} says that the angle between $f(u^*)-g$ and any arbitrary vector $v-u$ pointing from $u$ into $\\cK$ is at most $90^\\circ$.  That is, \\eqref{eq:vi} says that $f(u^*)-g$ may not be zero but it points directly into $\\cK$.  In particular, if $u^* \\in \\cK^\\circ$ (interior) then \\eqref{eq:vi} implies $f(u^*)=g$.  The following definitions are also standard \\cite{KinderlehrerStampacchia1980}.\n\n\\begin{definition} A map $f:\\cK \\to \\cV'$ is \\emph{monotone} if\n\\begin{equation}\n\\ip{f(u)-f(v)}{u-v} \\ge 0 \\qquad \\text{for all } u,v \\in \\cK, \\label{eq:monotone}\n\\end{equation}\n\\emph{strictly monotone} if equality in \\eqref{eq:monotone} implies $u=v$, and \\emph{coercive} if there exists $w \\in \\cK$ so that\n\\begin{equation}\n\\frac{\\ip{f(u)-f(w)}{u-w}}{\\|u-w\\|} \\to +\\infty \\qquad \\text{as } \\|u\\|\\to +\\infty. \\label{eq:coercive}\n\\end{equation}\nWe say VI \\eqref{eq:vi} is \\emph{monotone} if $f$ is monotone, and likewise for strictly monotone and coercive. \\end{definition}\n\nIt is well-known that if $f:\\cK \\to \\cV'$ is continuous, monotone, and coercive then VI \\eqref{eq:vi} has a solution \\cite[Corollary III.1.8]{KinderlehrerStampacchia1980}, and also that the solution $u^* \\in \\cK$ is unique when $f$ is strictly monotone.  As in the calculus of variations \\cite{Evans2010}, coercivity permits a compactness argument for unbounded sets $\\cK$; recall that the bounded, closed subsets of a reflexive Banach space are weakly compact.  The condition of continuity can be weakened to only apply on finite-dimensional subspaces \\cite{KinderlehrerStampacchia1980}, but the stronger condition will apply in our examples.\n\nThe coercive VIs solved in this paper satisfy a stronger inequality than \\eqref{eq:coercive}, and thus they are well-posed.\n\n\\begin{definition}  Let $p>1$.  The map $f:\\cK \\to \\cV'$ is \\emph{$p$-coercive} if there exists $\\kappa>0$ such that\n\\begin{equation}\n\\ip{f(u)-f(v)}{u-v} \\ge \\kappa \\|u-v\\|^p \\qquad \\text{for all } u,v \\in \\cK. \\label{eq:pcoercive}\n\\end{equation}\n\\end{definition}\n\nNote \\cite{Tai2003} uses ``coercive'' for $2$-coercive.  It is easy to see that if $f$ is $p$-coercive then it is monotone, strictly monotone, and coercive, and thus the following result holds.\n\n\\begin{theorem}  \\label{thm:viwellposed}  If $f:\\cK \\to \\cV'$ is continuous and $p$-coercive (for $p>1$) then there exists a unique $u\\in \\cK$ solving VI \\eqref{eq:vi}.\n\\end{theorem}\n\nWhen $f$ is monotone, VI \\eqref{eq:vi} generalizes the problem of minimizing a convex function over $\\cK$.  Suppose $F:\\cK \\to \\RR$ is lower semi-continuous and (G\\^ateau) differentiable with continuous derivative $F':\\cK \\to \\cV'$.  Then $F$ is convex if and only if $F'$ is monotone \\cite[Proposition I.5.5]{EkelandTemam1976}.  Furthermore, Proposition II.2.1 in \\cite{EkelandTemam1976} shows that if $F$ is convex then \\eqref{eq:vi} holds for $f=F'$ and $g=0$ if and only if\n\\begin{equation}\nu^* = \\operatorname{arg-min}_{v\\in\\cK} F(v). \\label{eq:minimization}\n\\end{equation}\nThe CD methods of Tai \\cite{Tai2003} address problem \\eqref{eq:minimization} under the hypothesis that $F'$ is coercive.\n\nFrom now on $\\Omega \\subset \\RR^d$ denotes a bounded, open set with smooth or piecewise-smooth (e.g.~polygonal) boundary.  Also, Sobolev spaces \\cite{Evans2010} are denoted by $W^{k,p}(\\Omega)$, for integer $k$ and $1\\le p \\le \\infty$, with $W^{k,2}$ denoted by $H^k$.\n\nThe following example includes the classical obstacle problem for the linear Laplacian \\cite{GraeserKornhuber2009} and the obstacle problem for the $p$-Laplacian \\cite{ChoeLewis1991}. \n\n\\begin{example}  \\label{ex:plaplacian}  Suppose $a\\in L^\\infty(\\Omega)$ such that $a(x)\\ge a_0$ a.e.~for some constant $a_0>0$, and $p\\ge 2$.  For $u,v \\in \\cV = W^{1,p}_0(\\Omega)$ define $f:\\cV \\to \\cV'$ by\n\\begin{equation}\n\\ip{f(u)}{v} = \\int_\\Omega a(x) |\\grad u|^{p-2} \\grad u \\cdot \\grad v\\,dx. \\label{eq:plaplacian}\n\\end{equation}\nNow, if $x,y\\in\\RR^d$ then $(|x|^{p-2} x - |y|^{p-2} y)\\cdot (x-y) \\ge 2^{2-p} |x-y|^p$ \\cite[see Appendix A and references therein]{Bueler2021conservation}.  Thus it follows from the Poincar\\'e inequality that\n    $$\\ip{f(u) - f(v)}{u-v} \\ge 2^{2-p} a_0 \\|\\grad u - \\grad v\\|_p^p \\ge 2^{2-p} a_0 C \\|u-v\\|^p$$\nfor some $C>0$, and thus $f$ is $p$-coercive.  (The map in \\eqref{eq:plaplacian} is coercive if $1<p<2$, but the proof is somewhat different \\cite[Theorem 4.4]{Bueler2021conservation}.  In Section \\ref{sec:results} we need only the $p\\ge 2$ case.)  For $g\\in\\cV'$ define\n    $$F(u) = \\int_\\Omega \\frac{a(x)}{p} |\\grad u|^p\\,dx - g(u).$$\nThen $F'(u) = f(u) - g$, $F$ is a convex functional (since $f$ is coercive), and, for any closed and convex $\\cK\\subset \\cV$, VI problem \\eqref{eq:vi} for is equivalent to optimization problem \\eqref{eq:minimization}.\n\\end{example}\n\nHowever, not all VI problems arise from optimization.  We give two such examples next, first a coercive and linear advection-diffusion problem, and then a nonlinear porous-medium-type problem.  Each of these examples is important in applications.  The first is preceded by a lemma.\n\n\\begin{lemma}  \\label{lem:advectionskew}  \\cite{Elmanetal2014}\\,  Suppose $\\bX :\\Omega \\to \\RR^d$ is a smooth and bounded vector field on $\\Omega$ with zero divergence ($\\Div \\bX=0$).  For $u,v \\in H^1(\\Omega)$ let $b(u,v) = \\int_\\Omega (\\bX \\cdot \\grad u) v\\,dx$.  Then $b(u,u) = \\frac{1}{2} \\int_{\\partial \\Omega} u^2 \\bX\\cdot \\bn\\,dx$ where $\\bn$ is the outward normal on $\\partial \\Omega$.\n\\end{lemma}\n\n\\begin{proof}\nIntegration by parts gives $b(u,v) = - b(v,u) + \\int_{\\partial \\Omega} uv \\bX\\cdot \\bn\\,dx$, so the result follows.\n\\end{proof}\n\n\\begin{example}  \\label{ex:advectiondiffusion}  Suppose $\\partial\\Omega$ is partitioned into Dirichlet and Neumann portions, i.e.~$\\partial\\Omega = \\partial_D\\Omega \\cup \\partial_N\\Omega$, with $\\partial_D\\Omega$ of positive measure.  Let $\\cV = H_0^1(\\Omega)$ be the space of functions with value zero on $\\partial_D\\Omega$.  (For simplicity we consider zero boundary data.)  Consider a smooth and bounded velocity field $\\bX$ on $\\Omega$ such that $\\Div \\bX=0$, but additionally assume that the flow is outward on the Neumann boundary, i.e.~$\\bX \\cdot \\bn \\ge 0$ at points of $\\partial_N\\Omega$.  For $u,v \\in \\cV = H_0^1(\\Omega)$ and $\\eps>0$ define\n\\begin{equation}\n\\ip{f(u)}{v} = \\int_\\Omega \\eps \\grad u \\cdot \\grad v - (\\bX \\cdot \\grad u) v\\,dx. \\label{eq:advectiondiffusion}\n\\end{equation}\nConsider VI \\eqref{eq:vi} for any closed and convex $\\cK \\subset \\cV$ and any $g\\in\\cV'$.  It is easy to see that $|\\ip{f(u)}{v}| \\le (\\eps + \\|\\bX\\|_\\infty) \\|u\\| \\|v\\|$, thus that $f:\\cK \\to \\cV'$ is continuous (and Lipschitz).  On the other hand, Lemma \\ref{lem:advectionskew} says that $s(u,v)$ is skew-symmetric up to a nonnegative term.  However, by the outward flow assumption and the Poincar\\'e inequality,\n\\begin{align*}\n\\ip{f(u)-f(v)}{u-v} &= \\eps \\int_\\Omega |\\grad u - \\grad v|^2\\,dx + b(u-v,u-v) \\\\\n                    &= \\eps \\int_\\Omega |\\grad u - \\grad v|^2\\,dx + \\frac{1}{2} \\int_{\\partial_N\\Omega} (u-v)^2 \\bX\\cdot\\bn \\ge \\eps C \\|u-v\\|^2.\n\\end{align*}\nThus $f$ is 2-coercive, and so VI problem \\eqref{eq:vi} is well-posed for any closed and convex $\\cK \\subset \\cV$ and $g\\in \\cV'$.\n\\end{example}\n\nIf $\\bX \\ne 0$ then VI \\eqref{eq:vi} for $f$ in \\eqref{eq:advectiondiffusion} is not a (constrained) minimization problem.  Indeed, the Jacobian of $f$, namely the bilinear form $J_f(u,v) = \\int_\\Omega \\eps \\grad u \\cdot \\grad v\\,dx - b(u,v)$, is not symmetric in that case.\\footnote{Assume $\\bX \\ne 0$ is continuous for simplicity.  For $u,v$ which are zero on $\\partial \\Omega$, $J_f(u,v) - J_f(v,u) = -2 b(u,v)$.  There exist $u,v$ so $b(u,v)$ is nonzero; construct $u,v$ locally near some point where $\\bX$ is nonzero.}  Thus $f$ in \\eqref{eq:advectiondiffusion} cannot be the Hessian of a scalar objective $F$.  References \\cite{Bueler2021conservation,ChangNakshatrala2017} consider such advection-diffusion VI problems over $\\cK = \\{v\\ge 0\\}$.\n\n\\begin{example}  \\label{ex:porous}  FIXME\n\\begin{equation}\n\\ip{f(u)}{v} = \\int_\\Omega \\phi(u) \\grad u \\cdot \\grad v\\,dx \\label{eq:porous}\n\\end{equation}\n\\end{example}\n\nNumerical solver performance for Examples \\ref{ex:plaplacian}, \\ref{ex:advectiondiffusion}, and \\ref{ex:porous} will be considered in Section \\ref{sec:results}.  Further examples of nonlinear VI problems appear in ice sheet models \\cite{Calvoetal2002,JouvetBueler2012} and other geophysical fluids \\cite{Bueler2021conservation}.\n\n\n\\section{Constraint decomposition, the basic algorithm} \\label{sec:cd}\n\nSuppose there are $m<\\infty$ closed subspaces $\\cV_i \\subset \\cV$ so that the sum\n\\begin{equation}\n\\cV = \\sum_{i=0}^{m-1} \\cV_i \\label{eq:subspacedecomp}\n\\end{equation}\nholds in the sense that if $w \\in \\cV$ then there exist $w_i \\in \\cV_i$ so that $w = \\sum_i w_i$; this is called a \\emph{subspace decomposition} \\cite{Xu1992}.  Suppose further that $\\cK_i \\subset \\cV_i$ are nonempty, closed, and convex subsets such that\n\\begin{equation}\n\\cK = \\sum_{i=0}^{m-1} \\cK_i. \\label{eq:constraintdecomp}\n\\end{equation}\nThe sum in \\eqref{eq:constraintdecomp} is required to hold in two senses: \\emph{(i)}~if $w \\in \\cK$ then there exist $w_i \\in \\cK_i$ so that $w = \\sum_i w_i$, and \\emph{(ii)}~if $z_i \\in \\cK_i$ for each $i$ then $\\sum_i z_i \\in \\cK$.\\footnote{Sense \\emph{(ii)} for \\eqref{eq:subspacedecomp} is automatic because the $\\cV_i$ are subspaces.}\n\nNote that neither decomposition \\eqref{eq:subspacedecomp} or \\eqref{eq:constraintdecomp} is required to be unique.  Also, $\\cK_i \\not\\subset \\cK$ in many applications; see the cartoon in Figure \\ref{fig:cartoon}.\n\nFinally, for each $\\cK_i$ we assume that there are bounded, (generally) nonlinear restriction operators $R_i : \\cK \\to \\cK_i$ such that if $v \\in \\cK$ then\n\\begin{equation}\nv = \\sum_{i=0}^{m-1} R_i v.  \\label{eq:constraintrestrictionsum}\n\\end{equation}\nA \\emph{constraint decomposition} (CD) of $\\cK$ is a choice of $\\cV_i,\\cK_i,R_i$ satisfying \\eqref{eq:subspacedecomp}--\\eqref{eq:constraintrestrictionsum} \\cite{Tai2003}.\n\n\\begin{figure}[ht]\n\\includegraphics[width=0.55\\textwidth]{genfigs/cartoon.pdf}\n\\caption{A constraint decomposition (CD) in a one-sided obstacle problem ($\\mathcal{K}=\\{v\\ge \\psi\\}$) might look like this if $\\mathcal{V}$ were 2-dimensional.}\n\\label{fig:cartoon}\n\\end{figure}\n\nIn Section \\ref{sec:multilevel} we will introduce discretizations and describe practical algorithms, but the fundamental CD concept applies even at the level of the continuum problem.  The following two examples illustrate this for obstacle problems \\cite{GraeserKornhuber2009}.  First we consider an overlapping domain decomposition.\n\n\\begin{example}  \\label{ex:domaindecomposition}  Consider a bounded domain $\\Omega \\subset \\RR^d$, let $\\cV = W_0^{k,p}(\\Omega)$ for $k\\ge 0$ and $p\\ge 1$, and suppose the obstacle $\\psi \\in W^{k,p}(\\Omega)$ satisfies $\\psi|_{\\partial \\Omega} \\le 0$.  Let $\\cK = \\{v \\ge \\psi\\} \\subset \\cV$.  Suppose further that $\\{\\phi_i\\}_{i=0}^{m-1}$ is a smooth partition of unity on $\\Omega$, satisfying $0 \\le \\phi_i\\le 1$ and $\\sum_i \\phi_i = 1$, and let $\\Omega_i$ be the support of $\\phi_i$.  Let $\\cV_i = \\{w \\in \\cV:w|_{\\Omega \\setminus \\Omega_i} =0 \\}$, $\\cK_i = \\{v \\in \\cV_i: v \\ge \\phi_i \\psi\\}$, and $R_i(v) = \\phi_i v$.  Then \\eqref{eq:subspacedecomp}, \\eqref{eq:constraintdecomp}, and \\eqref{eq:constraintrestrictionsum} all hold.\n\\end{example}\n\nOur second example is a disjoint frequency decomposition.  A multilevel FE CD, e.g.~the one proposed in Section \\ref{sec:multilevel}, approximates such a frequency decomposition.\n\n\\begin{example}  \\label{ex:frequencydecomposition}  For simplicity suppose $\\Omega = (0,a)^d \\subset \\RR^d$ is a cube, and let $\\cV = H_{\\text{per}}^k(\\Omega)$, $k\\ge 0$, be the periodic functions.  Suppose $\\psi \\in H_{\\text{per}}^k(\\Omega)$ and let $\\cK = \\{v \\ge \\psi\\} \\subset \\cV$.  Without using any detailed notation for Fourier representation, but noting that the frequencies are discrete, suppose $\\{\\cV_i\\}$ are $m<\\infty$ subspaces of $\\cV$ defined by an (nonoverlapping) partition by frequency, thus satisfying \\eqref{eq:subspacedecomp} as an orthogonal decomposition.  Suppose $P_i:\\cV \\to \\cV_i$ are the corresponding orthogonal projections, satisfying $I = \\sum_i P_i$.  Let $\\cK_i = \\{v \\ge P_i \\psi\\} \\subset \\cV_i$ and $R_i = P_i$.  Then \\eqref{eq:constraintdecomp} and \\eqref{eq:constraintrestrictionsum} also hold.\n\\end{example}\n\nNote that $\\cK_i \\not\\subset \\cK$ in most cases.  In Example \\ref{ex:domaindecomposition}, if $\\psi$ is positive over portions of $\\Omega$ where the decomposition into overlapping subdomains $\\Omega_i$ is nontrivial, then $\\cK_i \\not\\subset \\cK$, and similarly for Example \\ref{ex:frequencydecomposition}.  Instead, the important inclusion is $\\cK_i \\subset \\cV_i$.\n\nAlgorithm \\ref{alg:basiccd} below states the basic CD algorithm as an iteration which solves smaller VI problems over each set $\\cK_i$.  (By contrast, the algorithms in \\cite{Tai2003} solve optimization problems over each $\\cK_i$.)  The algorithm starts from a current iterate $u \\in \\cK$ and computes a new iterate $w\\in\\cK$, an improved approximation of the solution $u^* \\in \\cK$ of \\eqref{eq:vi}, using a damping parameter $0<\\alpha\\le 1$.  There are parallel (additive) and successive (multiplicative) versions of the algorithm, generalizing the Jacobi and Gauss-Seidel iterations \\cite{Greenbaum1997}, respectively.  For the parallel version the \\textbf{for} loop can be computed in any order.\n\n\\begin{pseudofloat}[H]\n\\begin{pseudo*}\n\\pr{cditeration}(u\\in\\cK)\\text{:} \\\\+\n    if \\pr{parallel}: \\\\+\n        for $i \\in \\{0,\\dots,m-1\\}$: \\\\+\n            $\\hat w_i\\in \\cK_i$: \\\\+\n                 $\\boxed{\\ip{f(u - R_i u + \\hat w_i)}{v_i-\\hat w_i} \\ge g(v_i-\\hat w_i)} \\quad \\forall v_i\\in \\cK_i$ \\\\---\n    else: \\\\+\n        for $i = 0,\\dots,m-1$: \\\\+\n            $\\hat w_i\\in \\cK_i$: \\\\+\n                $\\displaystyle \\boxed{\\ip{f\\Big(\\sum_{j<i} w_j + \\hat w_i + \\sum_{j>i} R_j u\\Big)}{v_i-\\hat w_i} \\ge g(v_i-\\hat w_i)} \\quad \\forall v_i\\in \\cK_i$ \\\\-\n            $w_i = (1-\\alpha) R_i u + \\alpha \\hat w_i\\in\\cK_i$ \\\\--\n    $\\hat w = \\sum_i \\hat w_i\\in\\cK$ \\\\\n    return $w=(1-\\alpha) u + \\alpha \\hat w\\in\\cK$\n\\end{pseudo*}\n\\caption{The basic constraint decomposition (CD) algorithm for VI problem \\eqref{eq:vi}.}\n\\label{alg:basiccd}\n\\end{pseudofloat}\n\nThe reader may confirm that, inside each boxed VI in Algorithm \\ref{alg:basiccd}, the argument of $f$ is an element of $\\cK$.  While the difference $v_i - \\hat w_i \\in \\cV_i$ appears, note that by \\eqref{eq:constraintdecomp} and \\eqref{eq:constraintrestrictionsum} one may write it as a difference of admissible vectors (i.e.~from $\\cK$), namely\n\\begin{align*}\n[u - R_i u + v_i] - [u - R_i u + \\hat w_i] &= v_i - \\hat w_i, \\label{eq:admissibledifference} \\\\\n\\left[\\sum_{j<i} w_j + v_i + \\sum_{j>i} R_j u\\right] - \\left[\\sum_{j<i} w_j + \\hat w_i + \\sum_{j>i} R_j u\\right] &= v_i - \\hat w_i,  \\notag\n\\end{align*}\nfor the two versions, respectively.\n\nIn other words, we solve VI \\eqref{eq:vi} over perturbations from the sets $\\cK_i$.  Define\n\\begin{equation}\ne_i = \\hat w_i - R_i u \\in \\cV_i \\label{eq:ithupdate}\n\\end{equation}\nas the $i$th update from a pass through either \\textbf{for} loop in Algorithm \\ref{alg:basiccd}.  Then $\\hat w = u + \\sum_{i} e_i$ and $w = u + \\alpha \\sum_i e_i$.  Easy identities $u - R_i u + \\hat w_i = u + e_i$ and $\\hat w = u^* + \\sum_i \\hat w_i - R_i u^*$ also hold.  We will use these identities in Section \\ref{sec:convergence}.\n\nThe convergence results in Section \\ref{sec:convergence} require substantial damping when applying the parallel algorithm, i.e.~$\\alpha \\le 1/m$, the same as in \\cite{Tai2003}, but the successive version can be shown to converge without damping ($\\alpha=1$).  In Section \\ref{sec:results} we demonstrate practical convergence for a larger range of $\\alpha$ than suggested by the theory.  % HOPE\n\nIn order for Algorithm \\ref{alg:basiccd} to have a practical and efficient FE implementation (Section \\ref{sec:multilevel}), we need additional notions when $f$ has any of the following properties: \\emph{(i)} $f$ is defined only on $\\cK$, or \\emph{(ii)} $f$ is nonlinear, or \\emph{(iii)} $f$ is non-local.  The issue of practical implementation for any such $f$ seems not to have been addressed in the CD literature, which is why we call Algorithm \\ref{alg:basiccd} the ``basic'' algorithm.  In particular  \\cite{GraeserKornhuber2009,Tai2003} only apply the CD method to the classical obstacle problem.  The following example explains the simplifications available in that easy case.\n\n\\begin{example}  \\label{ex:fnice} Suppose $f:\\cV \\to \\cV'$ is linear and defined on all of $\\cV$.  Furthermore suppose $f$ is local in the sense that a basis $\\{\\phi_i\\}$ of $\\cV_i$ exists, with each support small in $\\Omega$, such that $\\ip{f(\\phi_i)}{z}$ can be computed by an integral over the support of $\\phi_i$.  (When $\\cV$ is an FE space then this is the usual case for evaluating PDE weak forms over a basis of hat functions; see Section \\ref{sec:multilevel}.  Constrast integral operators where $\\ip{f(\\phi_i)}{z}$ requires an integral over $\\Omega$ even if the support of $\\phi_i$ is small.)  Considering only the parallel version of Algorithm \\ref{alg:basiccd} for simplicity, the boxed VI over $\\cK_i$ can be written as\n\\begin{equation}\n\\ip{f(e_i)}{v_i-\\hat w_i} \\ge \\tilde g(v_i-\\hat w_i) \\label{eq:linearlocalvi}\n\\end{equation}\nwhere $\\tilde g(z) = g(z) - \\ip{f(u)}{z}$.  Noting $e_i = \\hat w_i - R_i u \\in \\cV_i \\notin \\cK$, in general, VIs \\eqref{eq:linearlocalvi} will only make sense because $f$ is defined over $\\cV$.  Each problem \\eqref{eq:linearlocalvi} can be solved using a stored residual $\\ip{f(u)}{\\cdot}$ (already included into the source term).  The VI \\eqref{eq:vi} is then approximately solved in any incremental and efficient manner, by computations over the basis supports, during one application of \\pr{cditeration}.\n\\end{example}\n\nIn other words, when $f$ has all the nice properties proposed in Example \\ref{ex:fnice} then the decomposed VI problems can be computed from inexpensive data.  Note that the actual solution method for VI \\eqref{eq:linearlocalvi} is not the concern here; we are observing that the data of problem \\eqref{eq:linearlocalvi}, and the cost of residual evaluation, is small in practice.  A solver which would work for Example \\ref{ex:fnice} can thus have implementation efficiencies which are unavailable in general.\n\nAdditional ideas, like those in Section \\ref{sec:multilevel}, are needed for practical application of CD methods to more difficult problems.  In particular, we will extend the basic Algorithm \\ref{alg:basiccd} to nonlinear $f$ by applying the full approximation storage (FAS) idea of Brandt \\cite{Brandt1977}, in which case the decomposed problems only evaluate $f$ over (admissible) elements of $\\mathcal{K}$, and we propose restrictions which allow inexpensive approximations of the decomposed problems.  However, extending the algorithm to non-local residual functionals is a topic for future research.\n\n\n\\section{Convergence of the basic algorithm} \\label{sec:convergence}\n\nWe now seek a proof of the convergence of Algorithm \\ref{alg:basiccd}.  This will be possible if we restrict to $2$-coercive operators and make certain assumptions as in \\cite{Tai2003}.  First we define a new quantity related to VI problem \\eqref{eq:vi}.\n\n\\begin{definition} Suppose $f:\\cK \\to \\cV'$ and $g \\in \\cV'$.  For $u,v \\in \\cK$ let\n\\begin{equation}\n  E(v,u) = \\ip{f(v)}{v-u} - g(v-u).  \\label{eq:normlikedefn}\n\\end{equation}\n\\end{definition}\n\nIf $u^*$ solves \\eqref{eq:vi} then $E(v,u^*)$ is somewhat like an ``merit function,'' something used in the context of solving nonlinear equations \\cite{NocedalWright2006} to replace an objective (scalar) functional.  (Note that $E(v,u^*)$ is \\emph{not} a residual for \\eqref{eq:vi}.)  The next lemma, which follows directly from $p$-coercivity, shows $E(v,u^*)$ is bounded below.\n\n\\begin{lemma} \\label{lem:normlike}  Suppose $f:\\mathcal{K} \\to \\mathcal{V}'$ is $p$-coercive and $u^* \\in \\mathcal{K}$ solves \\eqref{eq:vi}.  For $v \\in \\mathcal{K}$,\n\\begin{equation}\n  E(v,u^*) \\ge \\kappa \\|v-u^*\\|^p.  \\label{eq:normlikebound}\n\\end{equation}\n\\end{lemma}\n\n\\begin{proof}\n\\begin{align*}\nE(v,u^*) &= \\ip{f(v)}{v-u^*} - \\ip{f(u^*)}{v-u^*} + \\ip{f(u^*)}{v-u^*} - g(v-u^*) \\\\\n   &\\ge \\kappa \\|v-u^*\\|^p + 0.  \\qedhere\n\\end{align*}\n\\end{proof}\n\nNext we make two assumptions which are essentially the same as (7) and (8) in \\cite{Tai2003}.\n\n\\begin{assumptions*}  There exists a constant $C_1>0$ so that\n\\begin{equation}\n\\left(\\sum_{i=0}^{m-1} \\|R_i u - R_i v\\|^2\\right)^{1/2} \\le C_1 \\|u-v\\| \\label{as:lipschitzrestrictions}\n\\end{equation}\nfor all $u,v\\in\\cK$.  Furthermore, there exists $C_2>0$ so that for all $v_i \\in \\cV_i$ and $y_j \\in \\cV_j$,\n\\begin{equation}\n\\sum_{i=0}^{m-1} \\sum_{j=0}^{m-1} \\left|\\ip{f(w_{ij} + v_i) - f(w_{ij})}{y_j}\\right| \\le C_2 \\left(\\sum_{i=0}^{m-1} \\|v_i\\|^2\\right)^{1/2} \\left(\\sum_{j=0}^{m-1} \\|y_j\\|^2\\right)^{1/2} \\label{as:lipschitzresidual}\n\\end{equation}\nfor all $w_{ij} \\in \\cK$ such that $w_{ij} + v_i \\in \\cK$ for all $i$ and $j$.\n\\end{assumptions*}\n\nThese inequalities might be described as ``totally Lipschitz'' requirements for the maps $R_i$ and $f$, respectively.  We make the following observations:\n\\begin{itemize}\n\\item Assumption \\eqref{as:lipschitzrestrictions} addresses only the CD, and not the map $f$.\n\\item It is sometimes the case that \\eqref{as:lipschitzresidual} addresses only a subspace decomposition property of $f$ (and not the CD itself).  For example, in the classical obstacle problem one may verify \\eqref{as:lipschitzresidual} over all $w_{ij} \\in \\cV$.\n\\item The unconstrained versions of \\eqref{as:lipschitzrestrictions} and \\eqref{as:lipschitzresidual} are (13), (14) in \\cite{TaiXu2002}, respectively.\n\\item If we assume $f$ itself is Lipschitz then the existence of $C_2$ is clear \\cite{TaiXu2002}.  However, our bound for the convergence rate for Algorithm \\ref{alg:basiccd} is improved when $C_1,C_2$ are made smaller.\n\\item Tai \\cite{Tai2003} gives values of the constants $C_1$ in \\eqref{as:lipschitzrestrictions} for obstacle problem constraint decompositions using $P_1$ FE spaces over shape-regular and quasi-uniform triangulations.  In particular, constants $C_1$ are known for overlapping domain decompositions (with or without an additional coarse mesh) and standard multilevel hierarchies.  Thus the cases we will demonstrate in Section \\ref{sec:results} are already covered.\n\\item The constants $C_1,C_2$ generally depend on $m$.  However, regarding the convergence proof below, \\cite{Tai2003} observes that if repeated application of Algorithm \\ref{alg:basiccd} generates a bounded sequence of iterates in $\\mathcal{K}$ then constants $C_1,C_2$ would be permitted to depend on $u,v,w_{ij},v_i,y_i$ as well.\n\\end{itemize}\n\nFrom the above definitions and assumptions we have the following estimate for the parallel version of Algorithm \\ref{alg:basiccd}.  Our proof follows \\cite{Tai2003}.\n\n\\begin{lemma} \\label{lem:core}  Suppose $f$ is $2$-coercive and $u^* \\in \\mathcal{K}$ solves \\eqref{eq:vi}.  Recall $E(v,u^*)$ is defined in \\eqref{eq:normlikedefn}.  Suppose $\\mathcal{V}_i$, $\\mathcal{K}_i$, $R_i$, and $f$ satisfy \\eqref{as:lipschitzrestrictions} and \\eqref{as:lipschitzresidual}.  Suppose $\\hat w$ is computed from $u$ by the parallel version of Algorithm \\ref{alg:basiccd}, and recall $e_i = \\hat w_i - R_i u$.  Then\n\\begin{equation}\n   E(\\hat w,u^*) \\le C_2 \\sum_{i=0}^{m-1} \\|e_i\\|^2 + \\kappa^{-1} C_1 C_2 \\left(\\sum_{i=0}^{m-1} \\|e_i\\|^2\\right)^{1/2} E(u,u^*)^{1/2}. \\label{eq:core}\n\\end{equation}\n\\end{lemma}\n\n\\begin{proof}  Recalling that $\\hat w = u^* + \\sum_i \\hat w_i - R_i u^*$, by the (parallel version) boxed VI in Algorithm \\ref{alg:basiccd} with $v_i = R_i u^*$ we get\n\\begin{align}\nE(\\hat w,u^*) &= \\sum_{i=0}^{m-1} \\ip{f(\\hat w)}{\\hat w_i - R_i u^*} - g(\\hat w_i - R_i u^*) \\label{eq:startcore} \\\\\n    &\\le \\sum_{i=0}^{m-1} \\ip{f(\\hat w)}{\\hat w_i - R_i u^*} + \\ip{f(u + e_i)}{R_i u^* - \\hat w_i} \\notag \\\\\n    &= \\sum_{i=0}^{m-1} \\ip{f(\\hat w) - f(u + e_i)}{\\hat w_i - R_i u^*}. \\notag\n\\end{align}\nFor $i\\in \\{0,1,\\dots,m-1\\}$ use wrapped indices to define elements $\\phi_{i,j}$:\n\\begin{align}\n\\phi_{i,0} &= u + e_i, \\label{eq:gridcore} \\\\\n\\phi_{i,1} &= u + e_i + e_{i+1}, \\notag \\\\\n  &\\vdots \\notag \\\\\n\\phi_{i,m-1} &= u + e_i + e_{i+1} + \\dots + e_{m-1} + e_0 + \\dots + e_{i-1}, \\notag\n\\end{align}\nand $\\phi_{i,j} \\in \\cK$ by \\eqref{eq:constraintdecomp} and \\eqref{eq:constraintrestrictionsum}.  Note that $\\phi_{i,m-1} = u + \\sum_i e_i = \\hat w$.  From \\eqref{eq:startcore}, apply a telescoping sum using the elements in \\eqref{eq:gridcore}:\n\\begin{align}\nE(\\hat w,u^*) &\\le \\sum_{i=0}^{m-1} \\sum_{j=1}^{m-1} \\ip{f(\\phi_{i,j}) - f(\\phi_{i,j-1})}{\\hat w_i - R_i u^*} \\label{eq:nextcore} \\\\\n  &\\le \\sum_{i=0}^{m-1} \\sum_{j=0}^{m-1} \\left|\\ip{f(\\phi_{i,j}) - f(\\phi_{i,j-1})}{\\hat w_i - R_i u^*}\\right|. \\notag\n\\end{align}\nBy an easy renumbering of the indices $i,j$ we may apply assumption \\eqref{as:lipschitzresidual}, then the triangle inequality, and then assumption \\eqref{as:lipschitzrestrictions}; we denote $\\left(\\sum_{i=0}^{m-1} \\|e_i\\|^2\\right)^{1/2}$ by $Z$:\n\\begin{align}\nE(\\hat w,u^*) &\\le C_2 Z \\left(\\sum_{i=0}^{m-1} \\|\\hat w_i - R_i u^*\\|^2\\right)^{1/2} = C_2 Z \\left(\\sum_{i=0}^{m-1} \\|\\hat w_i - R_i u + R_i u - R_i u^*\\|^2\\right)^{1/2} \\label{eq:nextnextcore} \\\\\n  &\\le C_2 Z \\left(Z + \\left(\\sum_{i=0}^{m-1} \\|R_i u - R_i u^*\\|^2\\right)^{1/2}\\right) \\le C_2 Z \\left(Z + C_1 \\|u-u^*\\|\\right). \\notag\n\\end{align}\nFinally apply \\eqref{eq:normlikebound} to give \\eqref{eq:core}.\n\\end{proof}\n\nFIXME NOW THE ENTIRE BATTLE IS TO GET A CONVEXITY RESULT $E(w,u) \\ge C \\sum_{j=0}^{m-1} \\|e_j\\|^2$ for some reasonable $C$\n\n\\section{Finite elements and multilevel constraint decomposition} \\label{sec:multilevel}\n\nIn practice we will solve VI \\eqref{eq:vi} over a finite-dimensional space $\\cV$ based on a choice of a mesh over $\\Omega$ and a finite element (FE) space.\n\nFIXME triangulation\n\n\\begin{example}  FIXME if $\\cV_i=\\Span\\{\\phi_i\\}$ for $\\phi_i\\in\\cV$ are 1d spaces and if $\\cK = \\{v \\ge \\psi\\} \\subset \\cV$ (obstacle problem), and if $R_i : \\cK \\to \\cK_i$ for obstacle problem; note $\\cK_i \\not\\subset \\cK$ when $\\psi>0$\n\\end{example}\n\nFIXME state essentially Algorithm 4.7 \\cite{GraeserKornhuber2009} but with $\\text{V}(\\nu_1,\\nu_2)$ cycles which works for linear; observe that up-smoothing is more efficient; state the FAS version which has $O(m)$ residual evaluation complexity on each level\n\n\n\\section{Results for local variational inequalities} \\label{sec:results}\n\nFIXME\n\n\n% A BRIDGE TOO FAR:  \\section{Results for a nonlocal variational inequality} \\label{sec:resultsnonlocal}\n\n\n\n\\small\n\\bibliography{mcd2}\n\\bibliographystyle{siam}\n\n\\normalsize\n\\appendix\n\n\\section{Porous-medium problems are never monotone}\n\nBased on the examples in Section \\ref{sec:vi}, the property of $p$-coercivity would seem to be a mild generalization of uniform ellipticity (including its quasi-linear meaning \\cite[Section 8.3]{Evans2010}).  Indeed, weak-form operators with certain lower-order terms (Example \\ref{ex:advectiondiffusion}) or degenerate quasi-linear type (Example \\ref{ex:plaplacian}) can be monotone and coercive.  However, even the weaker property of monotonicity is ``fragile'' in a pointwise sense, as explained next, while ellipticity is more robust.  In particular, we show that no nontrivial porous-medium type functional is monotone, nor $p$-coercive.  We have not found any such explanation in the literature, but the observation of non-monotonicity in \\cite{RocknerWang2008} is related.\n\nConsider the expression $(Ax - By)\\cdot (x-y)$ where $A,B \\in \\RR^{d\\times d}$ are symmetric matrices and $x,y\\in \\RR^d$.  This expression is the quadratic form for a certain symmetric block matrix.  In fact, regarding $x,y$ as column vectors, we observe that\n\\begin{equation}\n(Ax - By)\\cdot (x-y) = \\begin{bmatrix} x^\\top & y^\\top \\end{bmatrix} \\begin{bmatrix}\n                        A & -\\frac{1}{2}(A+B) \\\\\n                        -\\frac{1}{2}(A+B) & B \\end{bmatrix} \\begin{bmatrix} x \\\\ y \\end{bmatrix}. \\label{eq:blockmatrix}\n\\end{equation}\nLet $M_{A,B}$ denote the symmetric $2d \\times 2d$ matrix in \\eqref{eq:blockmatrix}.  Clearly the expression is only bounded below if $M_{A,B}$ is nonnegative definite.  Stated as the following Lemma, the important point here is that exact equality $A=B$ is required for nonnegativity of the expression; knowing $A$ is close to $B$ is not helpful.\n\n\\begin{lemma}  Suppose $A,B \\in \\RR^{d\\times d}$ are symmetric matrices which commute.  Then $(Ax - By)\\cdot (x-y)\\ge 0$ for all $x,y\\in \\RR^d$ if and only if $A=B$ is nonnegative definite. \\end{lemma}\n\n\\newcommand{\\sbvec}[2]{\\left[\\begin{smallmatrix} #1 \\\\ #2 \\end{smallmatrix}\\right]}\n\\newcommand{\\sbmat}[4]{\\left[\\begin{smallmatrix} #1 & #2 \\\\ #3 & #4 \\end{smallmatrix}\\right]}\n\n\\begin{proof}\nIf $A=B$ is nonnegative definite then nonnegativity of the expression follows immediately.  Conversely, since $A$ is symmetric there exists an orthogonal basis $\\{x_i\\}$ of eigenvectors, with $Ax_i = \\lambda_i x$.  By commutativity these are also eigenvectors of $B$, with $Bx_i = \\mu_i x_i$.  Let $\\big\\{\\sbvec{x_1}{x_1}$, $\\sbvec{x_1}{-x_1}$, $\\dots$, $\\sbvec{x_d}{x_d}$, $\\sbvec{x_d}{-x_d}\\big\\}$ be an ordered basis of $\\RR^{2d}$.  It is easy to confirm that in this basis $M_{A,B}$ is block diagonal with $2\\times 2$ diagonal blocks $\\sbmat{0}{-\\frac{1}{2}(\\lambda_i+\\mu_i)}{-\\frac{1}{2}(\\lambda_i+\\mu_i)}{\\lambda_i+\\mu_i}$.  Thus the eigenvalues of $M_{A,B}$ come in pairs $\\frac{1}{2}(\\lambda_i + \\mu_i) \\pm \\sqrt{\\frac{1}{2}(\\lambda_i^2 + \\mu_i^2)}$ for $i=1,\\dots,d$.  By the strict concavity of the square root, $\\sqrt{\\frac{1}{2}(\\lambda_i^2 + \\mu_i^2)} > \\frac{1}{2}(|\\lambda_i| + |\\mu_i|)$ if $\\lambda_i\\ne \\mu_i$.  Thus if any eigenvalues of $A$ differ from those of $B$, i.e.~$\\lambda_i\\ne \\mu_i$ for any $i$, then there exists a negative eigenvalue of $M_{A,B}$.\n\\end{proof}\n\nIt is not clear if the hypotheses of symmetry and commutativity can be removed.  However, when the matrices are scalar multiples of the identity then the Lemma asserts that $(ax-by)\\cdot(x-y) \\ge 0$ for all $x,y\\in\\RR^d$ if and only if $a=b\\ge 0$.  This scalar case suffices for the following result.\n\n\\begin{theorem}\nSuppose $\\phi:[0,\\infty) \\to (0,\\infty)$ is continuous.  For $\\Omega \\subset \\RR^d$ open and nonempty, $\\cV = H_0^1(\\Omega)$, and $g\\in \\cV'$, consider the following functional on $\\cK = \\{v\\ge 0\\} \\subset \\cV$:\n\\begin{equation}\n\\ip{f(u)}{v} = \\int_\\Omega \\phi(u) \\grad u\\cdot \\grad v\\,dx - g(v).  \\label{eq:porousagain}\n\\end{equation}\nIf $\\phi$ is not constant then $f$ is not monotone.\n\\end{theorem}\n\n\\begin{proof}\nSuppose $\\phi(\\alpha)\\ne \\phi(\\beta)$ for $\\alpha > 0$ and $\\beta \\ge 0$.  (That is, suppose $\\phi$ is not constant.)  For $x\\in\\Omega$, construct $u\\in \\cK$ smooth so that $u(x)=\\alpha$ and $\\xi = \\grad u(x) \\ne 0$.  Using the Lemma, choose $\\eta \\in \\RR^d$ so that $(\\phi(\\alpha) \\xi - \\phi(\\beta) \\eta) \\cdot (\\xi - \\eta) < 0$.  FIXME NOT SURE IF THIS IS GOING TO WORK\n\\end{proof}\n\nThe main idea is that even the slightest variation in the coefficient $\\phi(u)$ violates monotonicity.  A strong and tight ellipticity hypothesis, e.g.~the existence of $c_0>0$ and $\\eps>0$ so that $c_0 \\le \\phi(u) \\le (1+\\eps)c_0$, will not imply monotonicity.  Contrast the nontrivial coefficient dependence on $\\grad u$ in the $p$-coercive $p$-Laplacian Example \\ref{ex:plaplacian} (with $p>2)$.\n\nNo nontrivial functional \\eqref{eq:porousagain} is monotone, nor is it ever $p$-coercive for any $p>1$.\n\\end{document}\n\n", "meta": {"hexsha": "71fc094f5dca46747af7c44fb968646ed984a387", "size": 41380, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/mcd2.tex", "max_stars_repo_name": "bueler/mcd-extended", "max_stars_repo_head_hexsha": "c928ce705ffba4338c9c3e7ffb6e1140270b0545", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paper/mcd2.tex", "max_issues_repo_name": "bueler/mcd-extended", "max_issues_repo_head_hexsha": "c928ce705ffba4338c9c3e7ffb6e1140270b0545", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/mcd2.tex", "max_forks_repo_name": "bueler/mcd-extended", "max_forks_repo_head_hexsha": "c928ce705ffba4338c9c3e7ffb6e1140270b0545", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 83.2595573441, "max_line_length": 1078, "alphanum_fraction": 0.7109956501, "num_tokens": 13648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3333221631901137}}
{"text": "%\n% File acl2017.tex\n%\n%% Based on the style files for ACL-2015, with some improvements\n%%  taken from the NAACL-2016 style\n%% Based on the style files for ACL-2014, which were, in turn,\n%% based on ACL-2013, ACL-2012, ACL-2011, ACL-2010, ACL-IJCNLP-2009,\n%% EACL-2009, IJCNLP-2008...\n%% Based on the style files for EACL 2006 by \n%%e.agirre@ehu.es or Sergi.Balari@uab.es\n%% and that of ACL 08 by Joakim Nivre and Noah Smith\n\n\\documentclass[11pt,a4paper]{article}\n\\usepackage[hyperref]{acl2017}\n\\usepackage{times}\n\\usepackage{latexsym}\n\\usepackage{bm}\n\\usepackage{graphicx}\n\\usepackage{amsmath}\n\\DeclareMathOperator*{\\argmax}{argmax} % thin space, limits underneath in displays\n\\usepackage{url}\n\\usepackage[inline,shortlabels]{enumitem}\n\\usepackage{caption}% <-- added\n\n\\usepackage{tabularx,booktabs}\n\\newcolumntype{C}{>{\\centering\\arraybackslash\\hsize=.5\\hsize}X} % centered version of \"X\" type\n\\setlength{\\extrarowheight}{1pt}\n\n\n\\usepackage{adjustbox}\n\\usepackage{float}\n\n\n\n\\aclfinalcopy % Uncomment this line for the final submission\n%\\def\\aclpaperid{***} %  Enter the acl Paper ID here\n\n%\\setlength\\titlebox{5cm}\n% You can expand the titlebox if you need extra space\n% to show all the authors. Please do not make the titlebox\n% smaller than 5cm (the original size); we will check this\n% in the camera-ready version and ask you to change it back.\n\n\\newcommand\\BibTeX{B{\\sc ib}\\TeX}\n\n\\title{CS395T: Neural Networks for Sentiment Analysis Project Report}\n\n\\author{Zeyuan Hu \\\\\n  Computer Science Department \\\\\n  University of Texas at Austin \\\\\n  Austin, Texas \\\\\n  {\\tt iamzeyuanhu@utexas.edu} \\\\\n}\n\n\\date{}\n\n\\begin{document}\n\\maketitle\n\n\\begin{abstract}\nIn this project, I implement a Feedforward Neural Network based on\naveraged word vectors over the input sentence and a convolutional neural\nnetwork (CNN) to perform the sentiment analysis on the sentences from\nRotten Tomatoes introduced by Pang and Lee~\\shortcite{Pang:2005}.\n\\end{abstract}\n\n\\section{Collaborators}\nZhan Shi, Danlu Wang\n\n\\section{Introduction}\n\nSentiment analysis is an umbrella term for several closely-related tasks. One of them is to\nclassifiy the sentences as either negative or positive. Traditionally, Naive Bayes or SVM\nbag-of-words models are well-suited for those tasks. However, neural network approaches\nincluding convolutional networks \\cite{Kim14f} and feedforward networks \\cite{Iyyer2015} \ncan substitute those traditional models to achieve similar performance. In this project,\nI implement a feedford network and a convolutional neural networks for the sentiment analysis.\nIn addition, I explore various architectural and parameter options to \ntune the systems to gain good classification performance.\n\n\\section{Implementation Details}\n\n\\subsection{Feedforward Neural Networks}\n\nThe implementation of the feedforword neural network (FFNN) follows closely to\nthe architecture of the deep averaging network (DAN)\ndescribed by Iyyer et al.~\\shortcite{Iyyer2015}. In the paper, the authors\nbreak down the architecture into three simple steps: 1. take the average of\nword embeddings of words in a given sentence 2. pass the average into a \nFFNN with one or more hidden layers 3. perform classification\non the final output. I follow those three steps closely and my network contains\none hidden layer. Essentially, I calculate $P(\\boldsymbol{y}|\\boldsymbol{x})$ in the network.\n\\verb|one_best| contains the classifiction result of the sentences in the computataion graph \\verb|graph|.\nI implement batching and during each epoch, I shuffle\nthe training examples at the very beginning. For the optimizer, I experiment with both the Adam\nand the stochastic gradient descent (SGD). The parameter tuning and the impact of the optimizer\nto the performance will be disccued in details in the experiment section.\n\n\\subsection{CNN}\n\nThe implementation of CNN follows Zhang and Wallace~\\shortcite{Zhang15}'s empiricial study of\none-layer CNN hyperparameter setting on sentence classification. In my implementation, I use\none convolution layer with multiple filter widths and feature maps and then I use 1-max pooling\nsuggested in the paper. The code structure is divided into five steps: \n\\begin {enumerate*}[1) ]\n\\item construct embedding layer by looking up pre-trained word embeddings,\n\\item create convolution layer and implement 1-max pooling strategy, \n\\item combine all the pooled features,\n\\item add dropout, and \n\\item make final predictions.\n\\end {enumerate*} \nThe rest of work is to focus on the hyperparameter setting, which\nincludes filter region size(s) (i.e., \\verb|filter_sizes|), \nthe number of filters to use with each size (i.e., \\verb|num_filters|),\nthe activation function(s) (i.e., \\verb|activation_func|), and so on.\n\n\\section{Experiments}\n\nThe experiment is carried out in a similar way as Zhang and Wallace~\\shortcite{Zhang15}'s.\nFor each exploration task, I report the mean, minimum, and maximum average \naccuracy values observed over three replications. \n\n\\subsection{Feedforward Neural Networks}\n\nFor the FFNN, I explore the impact of the architecture and \nthe choice of the optimizer to the system performance. Without special note, the experiments\nis based on the hyperparameter setting in table 1.\n\n\\begin{table}\n\\captionsetup{size=footnotesize}\n\\caption{FFNN Configuration} \\label{tab:freq}\n%\\setlength\\tabcolsep{0pt} % let LaTeX compute intercolumn whitespace\n\\footnotesize\\centering\n%This table provides the frequencies.\n\n\\smallskip \n\\begin{tabular*}{\\columnwidth}{@{\\extracolsep{\\fill}}cc}\n\\toprule\n  Description  & Values  \\\\\n\\midrule\n batch size & 10      \\\\\n number of hidden layer & 1 \\\\\n number of hidden units & 150        \\\\\n number of epochs & 50        \\\\\n initial learning rate & 0.1        \\\\\n decay steps & 10 \\\\\n learning rate decay factor & 0.99 \\\\\n optimizer & SGD \\\\\n\\bottomrule\n\\end{tabular*}\n\\end{table}\n\n\\textbf{Optimizer:} I compare the performance between Adam and SGD, which is controlled by\nthe environment variable \\verb|OPT| in the code. One surprising finding is that whether \nsupplying \\verb|global_step| argument inside the function call \\verb|apply_gradients| \ncan have impact on the performance of the system . I use tensorflow version 1.3.0 and the result\nis shown in table 1.\n\n\\begin{table}[!htb]\n\\captionsetup{size=footnotesize}\n\\caption{Optimizer Performance with ``global\\_step\"} \\label{tab:freq}\n\\setlength\\tabcolsep{0pt} % let LaTeX compute intercolumn whitespace\n\\footnotesize\\centering\n%This table provides the frequencies.\n\n\\smallskip \n\\begin{tabular*}{\\columnwidth}{@{\\extracolsep{\\fill}}rccr}\n\\toprule\n  Optimizer  & Arg & Accuracy (training) & Accuracy (dev) \\\\\n\\midrule\n SGD & Yes   & 76.53 (76.44, 76.59)    & 74.83 (74.67, 75.05)      \\\\\n ADAM & Yes   & 77.58 (76.72, 78.23)    & \\textbf{74.98 (74.48, 75.33)}     \\\\\n SGD & No  & \\textbf{81.72 (81.15, 82.70)}     & 74.42 (74.20, 74.77)      \\\\\n ADAM & No   & 50.06 (50.06, 50.06)     & 49.06 (49.06, 49.06)      \\\\\n\\bottomrule\n\\end{tabular*}\n\\end{table}\n\nAs shown in the table, \\verb|global_step| does not have impact for SGD\nmeasured by the accuracy on the dev set. Adam has similar performance\nas SGD with \\verb|global_step|. However, without \\verb|global_step|,\nAdam performs poorly and SGD has significant increase in training set\naccuracy compared with \\verb|global_step| unset case.\n\n\\textbf{Architecture:} The architecture of FFNN is determined by the number of \nhidden layers. In this experiment, I explore the FFNN with zero and one\nhidden layers. The result is shown in table 3. \n\n\\begin{table}[!htb]\n\\captionsetup{size=footnotesize}\n\\caption{FFNN architecture} \\label{tab:freq}\n\\setlength\\tabcolsep{0pt} % let LaTeX compute intercolumn whitespace\n\\footnotesize\\centering\n%This table provides the frequencies.\n\n\\smallskip \n\\begin{tabular*}{\\columnwidth}{@{\\extracolsep{\\fill}}rcr}\n\\toprule\n  Hidden layers  &  Accuracy (training) & Accuracy (dev) \\\\\n\\midrule\n 0   &  71.73 (66.66, 77.40)   &  69.48 (65.76, 73.92)     \\\\\n 1    & \\textbf{81.72 (81.15, 82.70)}    & \\textbf{74.42 (74.20, 74.77)}     \\\\\n 2   & 51.22 (49.94, 52.05)     & 51.88 (50.38, 53.00)     \\\\\n\\bottomrule\n\\end{tabular*}\n\\end{table}\n\nAs shown in the table, there is a significant performance gain \nwhen we increase our hidden layer from zero to one. However, with\nthe given configuration, two layers architecture has notable performance\ndrop. This suggests that hyperparameter setting and architecture has\nto be carefully picked to achieve good performance.\n\n%\n%\\begin{table*}\n%\\caption{Impact of the parameters on the UAS score}\n%\\label{data-table}\n%\\begin{tabularx}{\\textwidth}{@{}l*{8}{C}c@{}}\n%\\toprule\n%Parser    & Optimizer & Learning Rate & Epoches & Sentences     & Batch Size     & UAS    \\\\    \n%\\midrule\n%Greedy    & SGD        & 0.2              & 10         & 5000          & 1         & 72.27  \\\\    \n%Greedy    & SGD        & 0.2            & 20      & 5000           & 1                & 74.67  \\\\   \n%Greedy    & SGD       & 0.2             & 30        & 5000          & 1               & 75.81  \\\\   \n%Greedy    & SGD       & 0.2              & 40         & 5000         & 1               & 75.74  \\\\   \n%\\addlinespace\n%Greedy    & SGD       & 0.2              & 30         & 6000          & 1              & 76.35  \\\\   \n%Greedy    & SGD       & 0.2              & 30      & 7000         & 1               & 76.43  \\\\  \n%Greedy    & SGD       & 0.2              & 30      & 39832          & 1                & \\textbf{78.60}  \\\\    \n%Global    & Adagrad(0.0001, 5) & 5    & 10      & 39832          & 20               & \\textbf{75.67}  \\\\ \n%\\bottomrule\n%\\end{tabularx}\n%\\end{table*} \n\n\\subsection{CNN}\n\nFor the CNN, I explore the impact of the hyperparameter setting to the system performance. \nWithout special note, the experiments is based on the configuration in table 4. Figure 1\nshows the performance of the CNN versus the number of epochs.\n\n\\begin{figure}[h]\n\\includegraphics[scale=0.5]{cnn-epoch.png}\n\\caption{Accuracy vs. number of epochs in dev set}\n\\end{figure}\n\n\\begin{table}\n\\captionsetup{size=footnotesize}\n\\caption{CNN Configuration}\n%\\setlength\\tabcolsep{0pt} % let LaTeX compute intercolumn whitespace\n\\footnotesize\\centering\n%This table provides the frequencies.\n\n\\smallskip \n\\begin{tabular*}{\\columnwidth}{@{\\extracolsep{\\fill}}cc}\n\\toprule\n  Description  & Values  \\\\\n\\midrule\ninput word vectors & GloVe-300      \\\\\nfilter region size & (3,4,5) \\\\\nfeature maps &    128    \\\\\nactivation functions & ReLU        \\\\\npooling & 1-max pooling        \\\\\ndropout rate & 0.5 \\\\\n$l2$ norm constant & 0 \\\\\noptimizer & Adam \\\\\nnumber of epochs & 20 \\\\\nbatch size & 64 \\\\\n\\bottomrule\n\\end{tabular*}\n\\end{table}\n\nIn the following experiments, I train the CNN for $5$ epochs. \n\\textbf{Filter region size(s):}\nIn this experiment, I examine whether the filter region sizes will have\nthe impact on the CNN performance. The choice of filter region sizes are \npicked based on Zhang and Wallace~\\shortcite{Zhang15}'s empirical study. \nThe result is shown in table 5. \n\n\\begin{table}[!htb]\n\\captionsetup{size=footnotesize}\n\\caption{Filter region sizes and CNN performance} \\label{tab:freq}\n\\setlength\\tabcolsep{0pt} % let LaTeX compute intercolumn whitespace\n\\footnotesize\\centering\n%This table provides the frequencies.\n\n\\smallskip \n\\begin{tabular*}{\\columnwidth}{@{\\extracolsep{\\fill}}cc}\n\\toprule\n  Filter region sizes  &   Accuracy (dev) \\\\\n\\midrule\n(3,4,5)    &  \\textbf{77.52 (77.39, 77.77)}     \\\\\n(7,7,7,7)  &  77.20 (76.92, 77.58)     \\\\\n(7)        &  76.92 (76.08, 77.39)     \\\\\n\\bottomrule\n\\end{tabular*}\n\\end{table}\n\nI try different region sizes and find out that the impact of the region sizes\nto the performance is not significant. Even we have one region size $7$, there\nis almost no performance drop.\n\n\\textbf{Feature maps:}\nZhang and Wallace~\\shortcite{Zhang15} suggests that the number of feature maps\nfor each filter region size is ranged between $100$ and $600$. This is quite large\nrange. I experiment with three feature maps with one value between $100$ and $200$,\none value between $200$ and $400$, and one value between $400$ and $600$. The result is\nshown in table 6.\n\n\\begin{table}[!htb]\n\\captionsetup{size=footnotesize}\n\\caption{Feature maps and CNN performance} \\label{tab:freq}\n\\setlength\\tabcolsep{0pt} % let LaTeX compute intercolumn whitespace\n\\footnotesize\\centering\n%This table provides the frequencies.\n\n\\smallskip \n\\begin{tabular*}{\\columnwidth}{@{\\extracolsep{\\fill}}cc}\n\\toprule\n  Feature maps  &   Accuracy (dev) \\\\\n\\midrule\n128    &  77.52 (77.39, 77.77)     \\\\\n300  &    \\textbf{77.86 (77.67, 78.05)} \\\\\n600    &  77.61 (76.83, 78.52)    \\\\\n\\bottomrule\n\\end{tabular*}\n\\end{table}\n\n\\textbf{Activation functions:}\nIn this experiment, I experiment with two activation functions: \\verb|tanh| and \\verb|relu|.\nThe result is summarized in the table 7.\n\n\\begin{table}[!htb]\n\\captionsetup{size=footnotesize}\n\\caption{Activation functions and CNN performance} \\label{tab:freq}\n\\setlength\\tabcolsep{0pt} % let LaTeX compute intercolumn whitespace\n\\footnotesize\\centering\n%This table provides the frequencies.\n\n\\smallskip \n\\begin{tabular*}{\\columnwidth}{@{\\extracolsep{\\fill}}cc}\n\\toprule\n  Activation function  &   Accuracy (dev) \\\\\n\\midrule\n \\verb|tanh|   &   77.49 (77.30, 77.77)     \\\\\n \\verb|relu|    &  \\textbf{77.52 (77.39, 77.77)}     \\\\\n\\bottomrule\n\\end{tabular*}\n\\end{table}\n\nAs shown in the table 7, the choice of the activation function does not have impact on the \nCNN performance.\n\n\\section{Conclusion and Future Work}\n\nIn this project, I implement a feedforward neural network and a CNN for sentiment analysis.\nI explore the impact of architecture choice and hyperparameter setting on the performance of \nthe neural networks to the task. In the future, I can carry out similar empirical study towards\nother NLP tasks with different type of neural networks (i.e., LSTM).\n\n\\bibliography{acl2017}\n\\bibliographystyle{acl_natbib}\n\n\\end{document}\n", "meta": {"hexsha": "e7bd488fd520b32170eee8ae9182c0e764a48e67", "size": 13887, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "2017/395T-greg/HW3/Tex/p3.tex", "max_stars_repo_name": "xxks-kkk/Code-for-blog", "max_stars_repo_head_hexsha": "3d5ae181f2b6c986f3dc1977d190847757d30834", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-10-04T08:20:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-11T23:43:59.000Z", "max_issues_repo_path": "2017/395T-greg/HW3/Tex/p3.tex", "max_issues_repo_name": "xxks-kkk/Code-for-blog", "max_issues_repo_head_hexsha": "3d5ae181f2b6c986f3dc1977d190847757d30834", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-10-22T20:10:50.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-22T20:10:50.000Z", "max_forks_repo_path": "2017/395T-greg/HW3/Tex/p3.tex", "max_forks_repo_name": "xxks-kkk/Code-for-blog", "max_forks_repo_head_hexsha": "3d5ae181f2b6c986f3dc1977d190847757d30834", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2017-12-26T09:02:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T05:17:27.000Z", "avg_line_length": 38.1510989011, "max_line_length": 112, "alphanum_fraction": 0.7145531792, "num_tokens": 3978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891163376236, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3333221550223483}}
{"text": "\\documentclass[a4paper,11pt,captions=tableheading,DIV=12]{scrartcl}\n\\pdfoutput=1\n\n% ----------------------------------------------------------- Packages\n\\usepackage{amsmath,amssymb,url,cite,slashed,cancel,booktabs,graphicx,listings,subcaption}\n\\usepackage[colorlinks=true,urlcolor=blue,citecolor=magenta]{hyperref}\n%%%UNUSED%%% \\usepackage{feynmp,enumerate,multirow,wrapfig}\n\\renewcommand\\citepunct{,\\penalty1000\\hskip.13emplus.1emminus.1em\\relax} % no line-break in \\cite\n\n% MATH NOTATION\n\\newcommand\\w[1]{_{\\mathrm{#1}}}\n\\newcommand\\vc[1]{{\\boldsymbol{#1}}}\n\\newcommand\\dd{\\mathrm{d}}\n\\newcommand\\ee{\\mathrm{e}}\n\\newcommand\\ii{\\mathrm{i}}\n\\newcommand\\pmat[1]{\\begin{pmatrix}#1\\end{pmatrix}}\n\\newcommand\\Order{\\mathop{\\mathcal{O}}}\n\\newcommand\\Br{\\mathop{\\mathrm{Br}}}\n\\newcommand{\\dn}[3]{\\frac{\\dd^#1 #2}{\\dd #3^#1}}\n\\newcommand{\\pdn}[3]{\\frac{\\partial^#1 #2}{\\partial #3^#1}}\n\\newcommand{\\pd}[2]{\\frac{\\partial #1}{\\partial #2}}\n\n\\newcommand\\unit[1]{\\,\\mathrm{#1}}\n\\newcommand\\eV{\\unit{eV}}\n\\newcommand\\keV{\\unit{keV}}\n\\newcommand\\MeV{\\unit{MeV}}\n\\newcommand\\GeV{\\unit{GeV}}\n\\newcommand\\TeV{\\unit{TeV}}\n\\newcommand\\fb{\\unit{fb}}\n\\newcommand\\pb{\\unit{pb}}\n\\newcommand\\iab{\\unit{ab^{-1}}}\n\\newcommand\\ifb{\\unit{fb^{-1}}}\n\\newcommand\\ipb{\\unit{pb^{-1}}}\n\\newcommand\\fm{\\unit{fm}}\n\n\\makeatletter\n\\def\\EE{\\@ifnextchar-{\\@@EE}{\\@EE}}\n\\def\\@EE#1{\\ifnum#1=1 \\times\\!10 \\else \\times\\!10^{#1}\\fi}\n\\def\\@@EE#1#2{\\times\\!10^{-#2}}\n\\makeatother\n\n\\newcommand{\\fracp}[3]{\\ifnum1=#3\\relax\\biggl(\\frac{#1}{#2}\\biggr)\\else\\biggl(\\frac{#1}{#2}\\biggr)^{#3}\\fi}\n\\newcommand{\\neut}[1][]{{\\tilde\\chi^0_{#1}}}\n\\newcommand{\\chrg}[1][]{{\\tilde\\chi^\\pm_{#1}}}\n\\newcommand{\\chrgP}[1][]{{\\tilde\\chi^+_{#1}}}\n\\newcommand{\\chrgM}[1][]{{\\tilde\\chi^-_{#1}}}\n\n\\lstset{columns=[l]fullflexible,basicstyle=\\small\\ttfamily,xleftmargin=2em,frame=L,keepspaces=true}\n\\bibliographystyle{utphys27mod}\n\n% ---------------------------------------------------- For Sho's Notes\n\\usepackage{scrlayer-scrpage,color,soul}\n\\usepackage[hhmmss]{datetime}\n\\newdateformat{mydate}{\\THEDAY\\;\\shortmonthname.\\;\\THEYEAR}\n\\addtokomafont{pagehead}{\\small\\normalfont}\n\\rohead*{\\texttt{[\\jobname~@~\\mydate\\today~\\currenttime]}}\n\n\\newcommand{\\TODO}[1]{\\begingroup\\color{red}\\textbf{$\\clubsuit$#1$\\clubsuit$}\\endgroup}\n\n\\title{SLHA convention compared against References}\n\\author{Sho Iwamoto}\n\\date{}\n\\newcommand{\\wL}{_{\\mathrm L}}\n\\newcommand{\\wR}{_{\\mathrm R}}\n\\newcommand{\\bU}{\\bar U}\n\\newcommand{\\bD}{\\bar D}\n\\newcommand{\\bE}{\\bar E}\n\\newcommand{\\tra}{^{\\mathrm T}}\n\\begin{document}\n\\maketitle\n%---------------------------------------------------------------------\n\\section{Comparison}\n\\subsection{Higgs potential}\n\n\\subsubsection{SLHA convention}\nThe SLHA~\\cite{SLHA} is based on Gunion--Haber's notation~\\cite{GH}:\n\\begin{align}\n\\begin{split}\n  W &\\supset-\\epsilon_{ab}\n \\mu H_1^aH_2^b\n \\\\&=-\\mu(H_1^1H_2^2-H_1^2H_2^1)\n \\\\&\\equiv \\mu(-H_1^0H_2^0+H_1^-H_2^+),\n\\end{split}\n \\tag{SLHA:3}\\\\\n\\begin{split}\n  V_2 &\\supset\n  m_{H_{1}}^{2}|H_1|^2\n + m_{H_{2}}^{2}|H_2|^2\n - (m_3^2\\epsilon_{ab}H_1^aH_2^b +\\text{h.c.}),\n\\\\\n&=\n  m_{H_{1}}^{2}|H_1|^2\n + m_{H_{2}}^{2}|H_2|^2\n+ \\left[m_3^2 (-H_1^0H_2^0+H_1^-H_2^+) +\\text{h.c.}\\right].\n\\end{split}\n \\tag{SLHA:7}\n\\end{align}\nwhere $\\epsilon_{12}=\\epsilon^{12}=+1$.\nThe parameter $m_A^2$, set by \\texttt{EXTPAR 24}, is then defined as\n\\begin{equation}\n m_A^2 = \\frac{2m_3^2}{\\sin2\\beta}.\n\\tag{SLHA:8}\n\\end{equation}\nThe Higgs vacuum expectation value is defined as\n\\begin{align}\n \\langle{H_i^0}\\rangle&=\\frac{v_i}{\\sqrt{2}};&\n m_Z^2 = \\frac14(g'^2+g^2)(v_1^2+v_2^2)=\\frac14(g'^2+g^2)v^2,\n\\end{align}\ni.e., $v\\simeq246\\GeV$ is given in the \\texttt{HMIX 3}.\n\n\\subsubsection{Comparison to GH convention}\nIn Gunion--Haber~\\cite{GH}, the definitions are as follows, with their errata applied:\n\\begin{align}\n W &\\supset -\\epsilon_{ab}\\mu H_1^aH_2^b,\\tag{GH:3.3--3.4}\n\\\\\nV\\w{soft}&\\supset m_1^2|H_1|^2 + m_2^2 |H_2|^2 - (m_{12}^2\\epsilon_{ab}H_1^a H_2^b+\\text{h.c.}),\n\\tag{GH:3.9}\n%\n\\end{align}\nwhere $\\bE\\equiv\\tilde R$ in their notation, with the same definition $\\epsilon_{12}=1$ (found below Eq.~(3.2)).\nSo, with the identification $(m_1^2,m_2^2,m_{12}^2)\\equiv(m_{H_1}^2,m_{H_2}^2,m_3^2)$, this is identical to SLHA convention.\nAlso we note the difference of the vacuum expectation values:\n\\begin{align}\n \\langle H_1\\rangle &= \\pmat{\\bar v_1\\\\0},&\n \\langle H_2\\rangle &= \\pmat{0\\\\\\bar v_2},\n\\tag{GH:3.7}\n\\end{align}\nwith $\\bar v_1>0$, $\\bar v_2>0$ (3.24), and $\\tan\\beta=\\bar v_2/\\bar v_1=v_2/v_1$ (2.8).\nHere we use bars to denote $v$s under this definition.\n\nWe can then use their results, which say\n\\begin{align}\n &m_{H_1}^2 = -|\\mu|^2 + 2\\lambda_1 \\bar v_2^2 - m_Z^2/2,\n\\tag{GH:3.21c}\n\\\\\n &m_{H_2}^2 = -|\\mu|^2 + 2\\lambda_1 \\bar v_1^2 - m_Z^2/2,\n\\tag{GH:3.21d}\n\\\\\n &m_{H_1}^2 + m_{H_2}^2 + 2|\\mu|^2 \n= m_{3}^2(\\tan\\beta+\\cot\\beta)\n= \\frac{2m_{3}^2}{\\sin2\\beta},\n\\tag{GH:3.22}\n\\end{align}\nand, noting that\n\\begin{align}\n m_Z^2&=(g^2+g'^2)\\bar v^2/2,&\n m_W^2&=g^2\\bar v^2/2,\n\\end{align}\nwhich are found below Eq.~(3.19),\n\\begin{equation}\n \\lambda_1\n= \\frac{g^2+g'^2}{4} + \\frac{m_3^2}{2\\bar v_1\\bar v_2}\n= \\frac{m_Z^2}{2(\\bar v_1^2+\\bar v_2^2)} + \\frac{m_3^2}{2\\bar v_1\\bar v_2};\n\\end{equation}\ncombining them, we have\n\\begin{align}\n m_{H_1}^2&=-|\\mu|^2-\\frac{m_Z^2}{2}\\cos2\\beta + m_3^2\\tan\\beta,\\\\\n m_{H_2}^2&=-|\\mu|^2+\\frac{m_Z^2}{2}\\cos2\\beta + m_3^2\\cot\\beta.\n\\end{align}\nAlso the Higgs parameters are given by\n\\begin{align}\n m_{H^\\pm}^2&=(4\\lambda_1-g'^2)\\bar v^2=m_W^2+m_A^2,\\tag{GH:3.16}\\\\\n m_{H_3^0}^2&=m_{H^\\pm}^2-m_W^2=m_A^2,\\tag{GH:3.17}\\\\\n m_{H_1^0,H_2^0}^2 &=\n \\frac12\\left[m_{H_3^0}^2+m_Z^2\\pm\\sqrt{\n (m_{H_3^0}^2+m_Z^2)^2-4m_Z^2 m_{H_3^0}^2\\cos^22\\beta\n}\\right],\\tag{GH:3.18}\\\\\n\\tan2\\alpha&=\\frac{m^2_{H_3^0}+m_Z^2}{m_{H_3^0}^2-m_Z^2}\\tan2\\beta\\tag{GH:3.19}.\n\\end{align}\n\n\\subsubsection{Comparison to SUSY Primer convention}\nWe here compare the SLHA/GH notation with Martin's SUSY primer~\\cite{Martin:1997ns}.\nThe potentials are given by\n\\begin{align}\n W\\w{MSSM}\n&\\supset\n \\mu H\\w u H\\w d \n\\equiv\n\\mu (H_2^+H_1^- - H_1^0H_2^0),\\tag{SP:6.1.1--3}\\\\\n%\n\\begin{split}\n-\\mathcal L\\w{soft}&\\supset\n  m_{H\\w d}^{2}|H\\w d|^2\n + m_{H\\w u}^{2}|H\\w u|^2\n + (b\\epsilon^{ab}H\\w u^aH\\w d^b +\\text{h.c.}),\n\\end{split}\\tag{SP:6.3.1}\n\\\\\n&\\bar v_u = \\langle{H\\w u^0}\\rangle,\\quad \\bar v_d = \\langle{H\\w d^0}\\rangle,\n\\tag{SP:8.1.5}\n%\n% (|\\mu|^2+{m^2_{H\\w u}})|H_u|^2\n%+(|\\mu|^2+{m^2_{H\\w d}})|H_d|^2\n%+\\left(b(H\\w u^+H\\w d^- - H\\w u^0 H\\w d^0)+\\text{c.c.}\\right),\\tag{SP:8.1.1}\n\\end{align}\nwhere $\\epsilon^{12}=+1$ (2.13).\nSo the parameters are identified by the replacement\n\\begin{align}\n\\mu&=\\mu,\\\\\nm_3^2&=b,\n\\\\\nm_{H_1}^2 &= m_{H\\w d}^2,\n\\\\\nm_{H_2}^2 &= m_{H\\w u}^2,\n\\end{align}\nwhere the LHS are the SLHA parameters and the RHS are those in SUSY primer.\nWith this identification, we can confirm that the above-shown formulae agree with SUSY Primer's equations (8.1.8)--(8.1.11) and (8.1.19)--(8.1.22).\n\n\n\n\\subsection{Interaction terms}\nHere, to simplify the notation, we omit the SU(2) indices with assuming\n\\begin{equation*}\n AB=-BA\\equiv A^1B^2-B^1A^2.\n\\end{equation*}\n\\subsubsection{SLHA convention}\nThe SLHA~\\cite{SLHA} convention for the interection terms are\n\\begin{align}\n W &=\n - H_2 QY_U\\bU\n + H_1 QY_D\\bD\n + H_1 LY_E\\bE,\n\\tag{SLHA:3}\\\\\n V_3 &=\n - H_2 \\tilde Q T_U \\tilde u^*\n + H_1 \\tilde Q T_D \\tilde d^*\n + H_1 \\tilde L T_E \\tilde e^*\n\\tag{SLHA:5}\\\\\n V_2 &=\n  \\tilde Q^*m_{Q}^{2} \\tilde Q\n + \\tilde L^*m_{L}^{2} \\tilde L\n + \\tilde u  m_{u}^{2} \\tilde u^*\n + \\tilde d  m_{d}^{2} \\tilde d^*\n + \\tilde e  m_{e}^{2} \\tilde e^*\n\\tag{SLHA:7}\\\\\n \\mathcal L_G &= \\frac{M_1}{2}\\tilde b\\tilde b+\\frac{M_2}{2}\\tilde w\\tilde w+\\frac{M_3}{2}\\tilde g\\tilde g + \\text{h.c.}\n\\tag{SLHA:9}\n\\end{align}\nThe neutralino and charginos are defined as\n\\begin{align}\n \\tilde\\psi^0&=(-\\ii\\tilde b,-\\ii\\tilde w^3,\\tilde h_1,\\tilde h_2)\\tra,\n&\n\\tilde\\psi^+&=(-\\ii\\tilde w^+,\\tilde h_2^+),\n&\n\\tilde\\psi^-&=(-\\ii\\tilde w^-,\\tilde h_1^-).\n\\tag{SLHA:10+13}\n\\end{align}\n\n\\subsubsection{Comparison to SUSY Primer convention}\nIn SUSY primer~\\cite{Martin:1997ns}, the interaction terms are defined by\n\\begin{align}\n W\\w{MSSM}\n&\\supset \\bar U y_u Q H\\w u - \\bar d y_d Q H\\w d - \\bar e y_e L H\\w d\n\\tag{SP:6.1.1}\\\\\n&=\n -H_2Q y_u\\tra \\bar U + H_1 Qy_d\\tra\\bar d  +H_1 Ly_e\\tra\\bar e\n\\notag\\\\\nV_3 &=\n \\tilde u^* a_u \\tilde Q H\\w u\n-\\tilde d^* a_d \\tilde Q H\\w d\n-\\tilde e^* a_e \\tilde L H\\w d\n\\notag\\\\\n&=\n-H_2 \\tilde Q a_u\\tra \\tilde u^*\n+H_1 \\tilde Q a_d\\tra \\tilde d^*\n+H_1 \\tilde L a_e\\tra \\tilde e^*\n\\notag\\\\\nV_2 &\\supset\n \\tilde Q^* m_Q^2 \\tilde Q\n+\\tilde L^* m_L^2 \\tilde L\n+\\tilde u^* m_u^2 \\tilde u\n+\\tilde d^* m_d^2 \\tilde d\n+\\tilde e^* m_e^2 \\tilde e\n\\notag\\\\\n&=\n \\tilde Q^* m_Q^2 \\tilde Q\n+\\tilde L^* m_L^2 \\tilde L\n+\\tilde u (m_u^2)\\tra \\tilde u^*\n+\\tilde d (m_d^2)\\tra \\tilde d^*\n+\\tilde e (m_e^2)\\tra \\tilde e^*\n\\notag\\\\\n\\mathcal L&\\supset\n-\\frac{M_1}{2}\\tilde b\\tilde b-\\frac{M_2}{2}\\tilde w\\tilde w-\\frac{M_3}{2}\\tilde g\\tilde g + \\text{h.c.},\\tag{SP:8.1.1}\n\\end{align}\nand the neutralinos and charginos are\n\\begin{align}\n \\tilde\\psi^0&=(\\tilde b,\\tilde w^3,\\tilde h_1,\\tilde h_2)\\tra,\n&\n\\tilde\\psi^+&=(\\tilde w^+,\\tilde h_2^+),\n&\n\\tilde\\psi^-&=(\\tilde w^-,\\tilde h_1^-).\n\\tag{SP:8.2.1+15}\n\\end{align}\nSo the notations can be matched with\n\\begin{align}\n Y_U, Y_D, Y_E &= y_u\\tra, y_d\\tra, y_e\\tra\\\\\n T_U, T_D, T_E &= a_u\\tra, a_d\\tra, y_e\\tra\\\\\n m_Q^2, m_L^2  &= m_Q^2, m_L^2\\\\\n m_u^2, m_d^2, m_e^2  &= (m_u^2)\\tra,(m_d^2)\\tra,(m_e^2)\\tra,\\\\\n M_1, M_2, M_3 &= M_1, M_2, M_3,\n\\end{align}\nwhere the LHS are the SLHA parameters and the RHS are those in SUSY primer.\n\n\n\\section{Reverting sfermion rotation}\nIn SLHA2 convention~\\cite{SLHA2}, the sfermion mass basis $\\tilde f_i$ and super-CKM/PMNS basis $\\tilde{\\vc f}$ are related as\n\\begin{equation}\n \\tilde f_i = R_{iA}\\tilde f_A,\n\\end{equation}\nwhere $R$ is the rotation matrix (e.g.~\\texttt{USQMIX}), capital (small) indices are used to denote super-CKM/PMNS (mass) eigenstates, and\nthe super-CKM/PMNS eigenstates are defined as, e.g.,\n\\begin{equation}\n \\tilde {\\vc u} = (\n\\tilde u\\w L, \\tilde c\\w L, \\tilde t\\w L,\n\\tilde u\\w R, \\tilde c\\w R, \\tilde t\\w R)\\tra.\n\\end{equation}\n\nIf the model has no flavor (and CP) violation and the left--right mixings in the first and second generation are negligible, we can convert the SLHA2 output to SLHA1 output.\nThe SLHA1 mixing matrix $R'$ is obtained as\n\\begin{equation}\nR' = \\begin{pmatrix}\n  R_{a3} & R_{a6}\\\\\n  R_{b3} & R_{b6}\n\\end{pmatrix}\n\\end{equation}\nwith all elements are non-zero and $a<b$, and thus $\\tilde f_a\\equiv\\tilde f^{\\text{3rd}}_1$\nand  $\\tilde f_b\\equiv\\tilde f^{\\text{3rd}}_2$.\nThe first and second generation fermions, $\\tilde f_A$, are identified with $\\tilde f_i$, where $|R_{iA}|>|R_{jA}|$ for all $j\\neq i$.\n\\bibliography{bibliography}\n\\end{document}\n", "meta": {"hexsha": "a5475d59e7e43f58384b5a71a5009e58e6d939e0", "size": 10736, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "misc/convention.tex", "max_stars_repo_name": "misho104/SimSUSY", "max_stars_repo_head_hexsha": "af879f234a82ec804c33cfb24d3939318a9e9541", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "misc/convention.tex", "max_issues_repo_name": "misho104/SimSUSY", "max_issues_repo_head_hexsha": "af879f234a82ec804c33cfb24d3939318a9e9541", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "misc/convention.tex", "max_forks_repo_name": "misho104/SimSUSY", "max_forks_repo_head_hexsha": "af879f234a82ec804c33cfb24d3939318a9e9541", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5333333333, "max_line_length": 173, "alphanum_fraction": 0.6418591654, "num_tokens": 4815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3333090998044544}}
{"text": "\\section{Other concepts} \\label{sec:other_NN_concepts}\nThis section will briefly describe some other concepts that are relevant to this document but not warrant a thorough explanation.\n\n\\subsection{Overfitting} \\label{sub:overfitting}\nOne fundamental principle, not only for neural networks but many other machine learning techniques, is the idea of generalization. An algorithm that learned by training on some given data should be able to produce good results not only on this seen data, but also on similar and never before seen data. In the case of supervising learning problems for example, all the data is already labeled, there is no need to create a complex algorithm that can find these labels since the answer is already know. When teaching machines to think, the goal is not to make them memorize all the inputs and outputs, it is instead to make them learn how to abstract the data, to capture the fundamental patterns, and to interpret the input in a high level (e.g. seeing shapes, and objects instead of just pixels).\n\nSince in the majority of cases the data available for training is only a fraction of the possible values expected for the problem, a machine learning algorithm must be able to use this relatively small amount of data to project how all the input space is distributed. This is as much a task for the algorithm as is for the dataset itself, the training data should contain enough samples to offer an accurate representation of how the input space is truly distributed. Ideally this data should be diverse enough to represent well the possible inputs (e.g. when training to differentiate between cats and dogs, the data should contain photos of both cats and dogs of multiple colors, in various angles, and with different poses) and it also should contain as much samples as possible\\footnote{\n    Although having too much representation for one region of the input space in relation with the others can introduce bias in the model. For example, \\cite{networkBias2018} found that some gender classification systems had a significant higher error rates for dark skinned women (as high as 30\\% higher than for white males) and that some facial analysis datasets underrepresented minorities in the samples. A similar problem happened to amazon, where an AI recruiting system was discriminating women for jobs since most of the resumes that it was trained on came from men \\cite{amazonBias2018}. One proposed approach to combat this problem is to train another network to learn how the data is distributed and sample more from underrepresented data \\cite{debiasingVAE2019}.\n}.\n\n\\begin{figure} [hbt]\n    \\centering\n    \\caption{Visual representation of a learning algorithm fit to noisy data}\n    \\includegraphics[width=0.8\\textwidth]{chapters/NeuralNets/figures/fitting.pdf}\n    \\fonte{From the author (2021)}\n    \\label{fig:fitting}\n\\end{figure}\nWhen the dataset is insufficient or the learning algorithm is not capable enough, the final model will only partially represent the data, but will not be able to capture all the details of the representation; this is called \\textit{Underfitting}, the model was not able to fully represent the structure of the problem. In the other hand, the algorithm can also go to the opposite extreme and learn the dataset too well, this means that it will pick up particularities of the training data that don't generalize to the whole input distribution; this is called \\textit{Overfitting} and it is facilitated by small datasets that don't represent much variety (noise in a sample has more influence in the signal to noise ratio of the whole dataset), or by networks that have too many degrees of freedom. \\autoref{fig:fitting} visually represents the different fits for a 1-dimensional case.\n\nOverfitting is however so common that it is almost natural to expect its appearance, it is one of the most prevalent problems in machine learning and there are many existing techniques to avoid it. The first step is to have a good quality dataset, data augmentation methods can be used to easily multiply the number of samples without much downsides. In the algorithmic side, next subsection will discuss regularization and how it can combat overfitting among other things.\n\n\\subsection{Regularization} \\label{sub:regularization}\nAccording to \\cite[p. 117]{deepLearningBook2016}: ``\\textit{Regularization is any modiﬁcation we make to a learning algorithm that is intended to reduce its generalization error but not its training error}''. This is a general definition that encompasses many different techniques for regularization, but for this document it will suffice to describe only dropout and the $\\ell_1$ and $\\ell_2$ norms.\n\n\\subsubsection{L1 and L2 norms}\nSince one of the reasons overfitting happens is because the models are given a large number of free parameters to adjust to the dataset (worth mentioning again the 175 billion parameters present in GPT-3 \\cite{gpt3_2020}), then a common way of reducing overfitting is to limit the choice of parameters by adding a penalization term $\\Omega(\\bm{\\theta})$ to the loss function as shown in \\autoref{eq:regularization_penalty} \\cite[p. 226]{deepLearningBook2016}.\n\\begin{equation} \\label{eq:regularization_penalty}\n    \\tilde{J}(\\bm{X}, \\bm{\\theta}) = J(\\bm{X}, \\bm{\\theta}) + \\lambda\\Omega(\\bm{\\theta})\n\\end{equation}\n\nThe \\gls{lambda} term is a positive hyperparameter that determines how much the penalty is relevant to the overall loss. For $\\ell_1$ and $\\ell_2$ norms, $\\Omega(\\bm{\\theta})$ will be the respective norm of the $\\bm{\\theta}$ parameters. The $\\ell_2$ norm is the standard distance in euclidean space, so for this norm the penalty term is given by \\autoref{eq:l2_norm}.\n\\begin{equation} \\label{eq:l2_norm}\n    \\ell_2(\\bm{\\theta}) = \\|\\bm{\\theta}\\|_2 = \\sqrt{\\theta_0^2 + \\theta_1^2 + \\dots + \\theta_n^2}\n\\end{equation}\n\nFor the $\\ell_1$ norm, the value calculated is what is called the Manhattan distance or taxicab distance \\cite[p. 102]{dataDrivenScience2019} and is calculated as shown is \\autoref{eq:l1_norm}\n\\begin{equation} \\label{eq:l1_norm}\n    \\ell_1(\\bm{\\theta}) = \\|\\bm{\\theta}\\|_1 =  |\\theta_0| + |\\theta_1| + \\dots + |\\theta_n|\n\\end{equation}\n\nBoth norms will penalize large parameter values and the modified loss function in \\autoref{eq:regularization_penalty} will make gradient descent favor solutions that use smaller parameters. The \\gls{lambda} hyperparameter then determines how much to favor these simpler solutions.\n\nA simple explanation on why smaller values would reduce overfitting can be given by considering the case of fitting a polynomial to some data. Consider the overfitting case seen before in \\autoref{fig:fitting}, fitting a polynomial to reduce the square error on that noisy data results in a reasonable good approximation around the data points, but the curve suddenly changes directions in the extremes because of the terms with the highest powers in the polynomial. To make the curve fit the noisy data, a least squares approach will usually produce very high coefficients to balance the higher powers, this reduces the error but will almost never produce the true behaviour behind the data. Penalizing high coefficients with regularization is a way to force the solution to assume simpler values.\n\nThis is in no way a rigorous argument for regularization, but it can be used to have an intuition. The goal of this section is just to introduce the concept, regularization is an active area of research and a lot of support for it is based on empirical evidence, there is no complete theory to explain how and why it works so well \\cite[chap. 3]{NN&DL2015}.\n\nOne last thing to mention is the fact that $\\ell_1$ norm promotes sparsity in the parameters, this means that this approach will usually find solutions where multiple parameters will equal zero, larger values of \\gls{lambda} will promote more sparse models.\n\n\\subsubsection{Dropout}\nSince the local minimum reached by a training process will depend on the starting values for the parameters, one common way to increase the accuracy of a model is create an ensemble of different networks trained in the same dataset but with different starting points and/or architectures \\cite[Chapter 6]{NN&DL2015}. The model output can then be a combination of the outputs of the ensemble, the combination could be majority voting, an average between outputs, or any other sensible function. This gives better results because it is not expected that randomly initialized networks would make the same mistakes in all situations \\cite[p. 253]{deepLearningBook2016}.\n\nDropout is a technique that can be interpreted as a way to approximate an exponentially large ensemble of networks while using a single network and without needing to train more models \\cite{dropout2012}. The idea behind it is that during training, when feedforwarding the input through the network, some units should have a probability $p$ of being dropped from the calculation, that is, their activations are set to zero.\n\nThe idea of removing units during calculation may sound counter-intuitive, but like the $\\ell$ norms it is a way of restricting the learning process so that the network can't build very complex connections. By removing random units in each iteration, the network must be able to learn to represent the data even if a great number of units are removed, it no longer can expect that a combination of units will be present when evaluating the result and so it cannot depend on complex inter-correlations between units \\cite{dropout2012}.\n\nBy dropping different units, dropout effectively trains the ensemble of all sub-networks of the base network. Typical dropout rates are 20\\% for the input layer and 50\\% for hidden layers \\cite[p. 255, 257]{deepLearningBook2016}.\n\n\\subsection{Optimizers} \\label{sub:optimizers}\nGradient descent has the theoretical basis for convergence, but it has big problems for use in practice. The first problem is that the whole training set must be averaged when calculating the loss $J(\\bm{\\theta})$, even for small datasets this is quite restrictive, for larger datasets containing hundreds of thousands or millions of samples this can make each iteration take an immense amount of time. This type of approach is commonly called Batch Gradient Descent.\n\nAnother problem is that, even if calculating the gradient was very fast, the simple parameter update (recall \\autoref{eq:gradient_descent}) can become very slow, specially later in training. The point in parameter space can reach a region in the loss surface where the curvature is minimal, making the gradients very small; the updates could also jump around a valley in the loss surface, never reaching the local minimum \\cite{momentumWorks2017}.\n\nFor calculating the gradients faster there is the approach called \\glsreset{SGD}\\gls{SGD}. There are several different methods for better traversing the loss surface, these are called optimizers. For the purposes of this document only the Momentum, RMSProp, and \\gls{Adam} optimizers will be briefly explained.\n\n\\subsubsection{Stochastic Gradient Descent}\nInstead of calculating the gradient $\\nabla_{\\bm{\\theta}} J$ for all inputs in the dataset, \\gls{SGD} instead approximates this value by calculating it for a single sample on the input. This makes the updates much faster, but will cause the updates to fluctuate heavily because of the gross approximation; this however can be beneficial since it can make the updates jump to potentially better local minima and it has been shown that, for small learning rates, \\gls{SGD} will also converge \\cite{optimizers2016}.\n\nAnother way to approximate the gradient is by calculating it only for a mini-batch of the dataset, that is, a subset of $m$ samples of the data. This is called Mini-batch Gradient Descent but is also more commonly referred to as \\gls{SGD} as well. Using mini-batches instead of a single sample gives more stable updates while still being very fast, the values for $m$ usually fall between $50$ and $256$ \\cite{optimizers2016}, but lower values are also common.\n\nAnother advantage of the stochastic approach is that the noise in the gradient approximation has an added regularization effect \\cite[p. 5]{practical_gradient_recomendations2012}.\n\n\\subsubsection{Momentum, RMSProp, and Adam}\n\\glsreset{Adam}\nThe simple parameter update (\\autoref{eq:gradient_descent}) for Gradient Descent has some problems that make it difficult to converge in practice. Some of the problems mentioned by \\textcite{optimizers2016} are: that it is hard to choose a good value for the learning rate; only using a single learning rate can be insufficient; the parameters can get stuck in difficult regions of the loss surface, especially saddle points.\n\nBetween the many different approaches to combat this, one of the most popular that is also recommended when training \\acp{GAN} \\cite[p. 20, 27]{nipsGAN2017} is the \\gls{Adam} optimizer. This optimizer is essentially a combination of Momentum and RMSProp, two other very popular optimizers.\n\nMomentum, as the name suggests, is a way to give some inertia to the gradient updates, accelerating in the consistent directions while dampening oscillations. This technique has a strong theoretical basis and can give a quadratic speedup on many functions \\cite{momentumWorks2017}. Momentum changes the parameter updates by adding a velocity term controlled by a new hyperparameter $\\beta$ as shown in the following equations.\n\\begin{gather} \\label{eq:momentum}\n    \\bm{m}_{i} = \\beta \\bm{m}_{i-1} + \\nabla_{\\bm{\\theta}} J(\\bm{\\theta}_{i-1}) \\\\\n    %\n    \\bm{\\theta}_{i} = \\bm{\\theta}_{i-1} - \\eta \\bm{m}_{i}\n\\end{gather}\n\nThe RMSProp algorithm also tries to reinforce movement to the most relevant directions, it does this by keeping a exponentially moving average $v$ of the gradient accumulation \\cite[303-304]{deepLearningBook2016}. It also introduces another $\\beta$ hyperparameter and changes the updates as follows.\n\\begin{gather}\n    \\bm{v}_{i} = \\beta \\bm{v}_{i-1} + (1 - \\beta)\\nabla_{\\bm{\\theta}} J(\\bm{\\theta}_{i-1})^2 \\\\\n    %\n    \\bm{\\theta}_{i} = \\bm{\\theta}_{i-1} - \\frac{\\eta}{\\sqrt{\\bm{v}_{i} + \\epsilon}} \\nabla_{\\bm{\\theta}} J(\\bm{\\theta}_{i-1})\n\\end{gather}\n\nRecall that although these equations are represented in vector form, all operation are performed element-wise. Finally for the \\gls{Adam} algorithm, it can be seen as a combination of the two previous algorithms. It introduces two new hyperparameters $\\beta_1$ and $\\beta_2$ and the parameter updates work as follows \\cite{adam2017}.\n\\begin{gather}\n    \\bm{m}_i = \\beta_1 \\bm{m}_{i-1} + (1 - \\beta_1) \\nabla_{\\bm{\\theta}} J(\\bm{\\theta}_{i-1}) \\\\[5pt]\n    \\bm{v}_i = \\beta_2 \\bm{v}_{i-1} + (1 - \\beta_2) \\nabla_{\\bm{\\theta}} J(\\bm{\\theta}_{i-1})^2 \\\\[5pt]\n    \\hat{\\bm{m}_i} = \\frac{\\bm{m}_i}{1 - \\beta_1^i} \\\\[5pt]\n    \\hat{\\bm{v}_i} = \\frac{\\bm{v}_i}{1 - \\beta_2^i} \\\\[5pt]\n    \\bm{\\theta}_i = \\bm{\\theta}_{i-1} - \\eta \\frac{\\hat{\\bm{m}_i}}{\\sqrt{\\hat{\\bm{v}_i} + \\epsilon}}\n\\end{gather}\n\n\\textcite{adam2017} mentions that good default values for the hyperparameters are $\\alpha = 0.001$, $\\beta_1 = 0.9$, $\\beta_2 = 0.999$ and $\\epsilon = 10^{-8}$. The Tensorflow library \\cite{tensorflow2015} follows this default, only changing $\\epsilon$ to a order of magnitude higher, that is, $\\epsilon = 10^{-7}$.\n\n\\subsection{Batch Normalization}\nOne important aspect in training neural networks is the distribution of the inputs for a layer. As mentioned in \\autoref{subsub:sigmoid} about sigmoid, \\textcite{efficientBackprop2012} showed that inputs that are not zero centered will have some bias effect on parameter updates, to avoid this the layer inputs should all be shifted to have a mean of zero; the authors also suggest to normalize all inputs in order to have the same covariance and, if possible, to have their values be uncorrelated. This should significantly speed up the learning process since the network will not have to adapt to a different distribution for every input.\n\nNormalizing inputs is then an easy and effective way for better learning, therefore being a very commonly used technique that will also be used for the experiments proposed in this document.\n\nHowever \\textcite{batchnorm2015} note that for any layer in the network, the normalization idea for its inputs also applies; that is, any hidden layer feeding its output to the next layer can be considered as an input layer for a sub-network consisting of all the subsequent layers. Therefore, the same advantages for normalized inputs would be beneficial by normalizing hidden layer outputs.\n\nLooking from the training perspective, each training iteration updates all parameters at the same time, but the gradient change in a layer gives the best change considering that all other layers remain constant \\cite[p.313-314]{deepLearningBook2016}. In reality, changing the parameters of the previous layers will affect the distribution of inputs for the current layer, this constant change to the inputs of a layer resulting from changes to previous layers is what \\textcite{batchnorm2015} call \\textit{internal covariate shift}.\n\nTo address these issues \\textcite{batchnorm2015} proposed a technique known as \\gls{BN}, this method can be applied to any hidden layer and it consists of normalizing the layer inputs by the mean and variance of all the inputs in the current mini-batch. So, for a mini-batch $\\mathcal{B}$ of size $m$ and inputs $(\\bm{x}_1, \\dots, \\bm{x}_m)$, the normalized inputs $\\hat{\\bm{x}}_i$ are calculated using the mean $\\bm{\\mu}_{\\mathcal{B}}$ and variance $\\bm{\\sigma}_{\\mathcal{B}}$ of the batch. Equations \\ref{eq:batch_mean}, \\ref{eq:batch_variance}, and \\ref{eq:batch_normalized_input} show how the mean, variance, and normalized inputs are calculated.\n\\begin{gather}\n    \\bm{\\mu}_{\\mathcal{B}} = \\frac{1}{m}\n    \\sum_{i=1}^{m}{\\bm{x}_i} \\label{eq:batch_mean} \\\\[5pt]\n    %\n    \\bm{\\sigma_}{\\mathcal{B}}^2 = \\frac{1}{m}\n    \\sum_{i=1}^{m}{ \\left( \\bm{x}_i - \\bm{\\mu}_{\\mathcal{B}} \\right)^2 } \\label{eq:batch_variance} \\\\[5pt]\n    %\n    \\hat{\\bm{x}}_i = \\frac{ \\bm{x}_i - \\bm{\\mu}_{\\mathcal{B}} }\n    { \\sqrt{\\bm{\\sigma}_{\\mathcal{B}}^2 + \\epsilon} } \\label{eq:batch_normalized_input}\n\\end{gather}\n\nNote that these operations are applied element-wise for each component of the vectors, and again $\\epsilon$ is used for numerical stability.\n\nThese operations result in the vectors $\\hat{\\bm{x}}_i$ having a mean of $0$ and variance of $1$ for each of their dimensions. However, by limiting the distribution to only these values also limits the representation power of the network \\cite{batchnorm2015}, so the last step is to scale each one of the normalized activations by two new learnable parameters, $\\gamma$ and $\\beta$, unique for each activation, to obtain the transformed input $\\bm{y}_i$ that can have any mean and variance. \\autoref{eq:batch_transformed_input} shows how to scale the dimension $k$ of the normalized input $i$.\n\\begin{equation} \\label{eq:batch_transformed_input}\n    y_i^{(k)} = \\gamma^{(k)} x_i^{(k)} + \\beta^{(k)}\n\\end{equation}\n\nThis method has proven to be very powerful, with the original paper being able to reach the same accuracy as the, at the time state of the art image classification model, in 14 times less training iterations \\cite{batchnorm2015}. The authors also cite a regularization effect of \\gls{BN} that can reduce the need for other techniques like dropout.\n\nWhen the authors originally proposed this method, they recommended applying the batch normalization operation directly to the weighted inputs of the network and only after apply the activation to the normalized values. However, since then \\textcite{CaffeNetBench2017} empirically showed that applying \\gls{BN} after the activation produces better results.\n\n\\subsection{Vanishing Gradients} \\label{sub:vanishing_gradients}\nRecall that for Equations \\ref{eq:delta_last_layer} and \\ref{eq:delta_hidden_layer} the $\\delta$ term used to calculate the gradients, was directly dependent on the derivative of the activation function with relation to the weighted inputs $f'(\\bm{z}^{(l)})$. Also note that the gradients are backpropagated through the network, which means that the $\\delta$ values in a hidden layer are calculated from the $\\delta$ in the next layer.\n\nConsider now the case for a sigmoid or \\gls{tanh} activation function which is applied to an weighted input far from zero, the activation in this case will be very close to the maximum or minimum value that the function can produce. When a unit outputs this kind of value it is said that it saturated, any slight deviation in the weighted input will barely have any difference in the activation value, in other words the derivative of the activation is close to zero.\n\nCombining the points made in the last paragraphs it is possible to recognize a problem, when a unit saturates its gradient will be very small since the derivative of the activation is close to zero. Even worse than that is the fact that this small gradient will be backpropagated through the network, reducing the gradients of all previous layers. When many units saturate, this effect can compound, making the gradients for deeper layers very small and greatly reducing the training speed; this is the problem known as the \\textit{Vanishing Gradients} problem.\n\nOne alternate case is when the gradients are high and compound to make the gradients in deeper layers become very high, making the steps too large and not converging to any local minima. This is called the \\textit{Exploding Gradients} problem.\n\nBoth situations are undesirable and are specially worrying when trying to train very deep neural networks. Ideally the gradients should all be close to $1$ to make training consistent, but for saturating activation functions like sigmoid, there will usually be vanishing gradients \\cite{NN&DL2015}. That is one of the main reasons to use non-saturating activation functions like \\gls{ReLU} in the hidden layers of the network. Other common ways to combat this problem is to carefully initialize the network parameters and use small learning rates \\cite{batchnorm2015}, these authors also suggest that \\gls{BN} can be used on saturating units since it can reduce the chance that the input of the units will fall to the saturating regions.\n", "meta": {"hexsha": "dba5d6647e271a85f95c27ca6920ef0a87ba7818", "size": 22294, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Overleaf/chapters/NeuralNets/others.tex", "max_stars_repo_name": "PatrickHoeckler/tcc_gan", "max_stars_repo_head_hexsha": "0fa63fff9c6a3bbee57af38683c492a8b120e24a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-04-20T22:17:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T06:19:44.000Z", "max_issues_repo_path": "Overleaf/chapters/NeuralNets/others.tex", "max_issues_repo_name": "PatrickHoeckler/tcc_gan", "max_issues_repo_head_hexsha": "0fa63fff9c6a3bbee57af38683c492a8b120e24a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Overleaf/chapters/NeuralNets/others.tex", "max_forks_repo_name": "PatrickHoeckler/tcc_gan", "max_forks_repo_head_hexsha": "0fa63fff9c6a3bbee57af38683c492a8b120e24a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 153.7517241379, "max_line_length": 884, "alphanum_fraction": 0.7814210101, "num_tokens": 5257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.33330909634122796}}
{"text": "% !TEX root = atlas_iros_16.tex\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{\\large Modeling and Identification}\n\\label{sec:advance}\n\nIn this section we shortly review the system modeling and enhanced impedance controller approach (\\ref{sec:advance_controller}), modifications to the momentum-based disturbance observer to include wrist wrench measurements (\\ref{sec:advance_observer}), compensation of modeling errors and collision handling (\\ref{sec:friction_comp_and_collDet}), and an identification scheme that iteratively estimates friction characteristics and rigid body parameters (\\ref{sec:advance_ident}).\n\n\\subsection{System Model and Joint Impedance Controller}\n\\label{sec:advance_controller}\nThis work focuses on the 7R type serial chain arms of the Boston Dynamics humanoid robot Atlas, see Fig.~\\ref{fig:StickCollisionPhoto}.\nThe arms employ a hybrid actuation concept where the first four joints (shz, shx, ely, elx) are hydraulic, and the wrist joints (wry, wrx, wry2) are driven by electromechanical gear drives.\nWe assume the standard fixed-base rigid joint arm model \n\\begin{equation}\n\\bm{M(\\bm{q})}\\ddot{\\bm{q}}+\\bm{C}(\\bm{q},\\dot{\\bm{q}})\\dot{\\bm{q}}+\\bm{g}(\\bm{q})=\\bm{\\tau}_\\mathrm{m}-\\bm{\\tau}_\\mathrm{f}+\\bm{\\tau}_\\mathrm{ext}\n\\label{eqn:invdyn}\n\\end{equation}\nwith generalized joint position $\\bm{q} \\in \\mathbb{R}^{n_\\mathrm{j}}$ ($n_\\mathrm{j}$ being the number of joints), positive definite and symmetric inertia matrix $\\bm{M}(\\bm{q})$, centrifugal and Coriolis matrix $\\bm{C}(\\bm{q}, \\dot{\\bm{q}})$, gravity torque vector $\\bm{g}(\\bm{q})$, actuator torques $\\bm{\\tau}_\\mathrm{m}$, friction torques $\\bm{\\tau}_\\mathrm{f}$ and external torques $\\bm{\\tau}_\\mathrm{ext}$. \nThe friction torque $\\bm{\\tau}_\\mathrm{f}$ is composed of the motor side friction $\\bm{\\tau}_{\\mathrm{f},\\theta}$ and the link side friction $\\bm{\\tau}_{\\mathrm{f},q}$.\nBoth hydraulic and electromechanic actuators are considered as ideal torque sources, generating a motor torque $\\bm{\\tau}_\\mathrm{m}$, allowing a separation of the actuator dynamics from the rigid body model.\n\nFor soft-robotics control of the system we chose the joint impedance control torque $\\bm{\\tau}_\\mathrm{d}$ to be\n\\begin{equation}\n\\begin{gathered}\n\\bm{\\tau}_\\mathrm{d}=\n\\bm{K}(\\bm{q}_\\mathrm{d}-\\bm{q})+\\bm{D}(\\dot{\\bm{q}}_\\mathrm{d}-\\dot{\\bm{q}})+\\hat{\\bm{g}}(\\bm{q}) % tau_I \n\\\\\n+\\hat{\\bm{C}}(\\bm{q},\\dot{\\bm{q}})\\dot{\\bm{q}} % tau_c\n+\\hat{\\bm{M}}(\\bm{q}_\\mathrm{d})\\ddot{\\bm{q}}_\\mathrm{d} % tau_ff\n+\\kappa_{\\mathrm{f}} \\hat{\\bm{\\tau}}_\\mathrm{f}(\\dot{\\bm{q}})\n-\\kappa_{\\varepsilon} \\hat{\\bm{\\tau}}_\\mathrm{\\varepsilon}(\\bm{q}, \\dot{\\bm{q}},\\bm{\\tau}_\\mathrm{m})\\;,\n\\label{eqn:controller}\n\\end{gathered}\n\\end{equation}\nwhere $\\bm{q}_\\mathrm{d}, \\dot{\\bm{q}}_\\mathrm{d}, \\ddot{\\bm{q}}_\\mathrm{d}$ are the desired position, velocity, and acceleration, respectively. The matrices $\\bm{K}=\\mathrm{diag}\\{k_i\\}$ and $\\bm{D}_\\xi=\\mathrm{diag}\\{d_{\\xi,i}\\}$ denote diagonal positive definite stiffness and modal damping and $\\bm{D}$ the resulting positive definite damping matrix.\n$\\hat{\\bm{g}}$ and $\\hat{\\bm{C}}$ are the gravity and centrifugal/Coriolis estimates.\nThe inertial feedforward term makes use of the estimated inertia matrix $\\hat{\\bm{M}}$ as a function of the desired position $\\bm{q}_\\mathrm{d}$.\nThe compensation terms $\\hat{\\bm{\\tau}}_\\mathrm{f}(\\dot{\\bm{q}})$ (viscous and Coulomb friction) and $\\hat{\\bm{\\tau}}_\\mathrm{\\varepsilon}(\\bm{q}, \\dot{\\bm{q}},\\bm{\\tau}_\\mathrm{m})$ (estimated disturbance from Sec.~\\ref{sec:advance_observer}) are activated via the scalars $\\kappa_{\\mathrm{f}}\\in \\{0,1\\}$ and $\\kappa_{\\varepsilon}\\in \\{0,1\\}$, respectively.\n\nCombining (\\ref{eqn:invdyn}) and (\\ref{eqn:controller}) leads to the closed-loop dynamics\n\\begin{equation}\n\\begin{gathered}\n\\bm{M(\\bm{q})}\\ddot{\\bm{q}}-\\hat{\\bm{M}}(\\bm{q}_\\mathrm{d})\\ddot{\\bm{q}}_\\mathrm{d}\n+\\bm{D}(\\dot{\\bm{q}}-\\dot{\\bm{q}}_\\mathrm{d})\n+\\bm{K}(\\bm{q}-\\bm{q}_\\mathrm{d})\n \\\\\n=\\bm{\\tau}_\\mathrm{ext}\n+ \\bm{\\delta}\n-\\kappa_{\\varepsilon} \\hat{\\bm{\\tau}}_\\mathrm{\\varepsilon},\n\\label{eqn:closedloop_general}\n\\end{gathered}\n\\end{equation}\nwhere $\\bm{\\delta}$ denotes lumped dynamics and friction modeling errors and errors caused by sensor drift, offsets and time delays. \nWe assume these effects to be additive. \n\n\\subsection{Disturbance Observer}\n\\label{sec:advance_observer}\n%\n\\begin{figure}\n\\centering\n\\input{./figures/MechErsatzBSB/rigid_flexible_joint_struktur.pdf_tex}\n\\caption{Relevant torques acting along the mechanical structure for the rigid joint model (a) with link inertia $\\bm{M}$ and the flexible joint model (b) with motor inertia $\\bm{B}$ and motor position $\\bm{\\theta}$.}\n\\label{fig:rigid_flexible_joint_structure}\n\\SkipBeforeText\n\\end{figure}\n%\nBefore introducing our observer design, let us shortly summarize the underlying problem of collision detection with typical hydraulic robots.\nFigure~\\ref{fig:rigid_flexible_joint_structure} emphasizes the friction torques that are relevant for rigid joint models in comparison to the flexible joint case.\nThe latter represents e.g. electromechanically actuated robots with elastic joints and torque sensing \\cite{Ott2008}. \nIn the former case, the total friction $\\bm{\\tau}_\\mathrm{f}$ and external torques $\\bm{\\tau}_\\mathrm{ext}$ act on a single body that represents both motor and link inertia and sum up to a total disturbance torque.\nThus, except under certain modeling assumptions they cannot be separated with standard proprioceptive sensing and according observer techniques. \nIn the latter case, motor and link-side dynamics are coupled via the joint stiffness $\\bm{K}_{\\mathrm{J}}$.\nTypically, this originates either from rather elastic gears such as Harmonic Drives in combination with joint torque sensors (rather high inherent stiffness $\\bm{K}_{\\mathrm{J}}$), or from deliberately placed spring elements as e.g. in the Series Elastic Actuation (SEA \\cite{PrattWil1995}) case (rather low inherent stiffness $\\bm{K}_{\\mathrm{J}}$).\nSince the link side friction $\\bm{\\tau}_{\\mathrm{f},q}$ is usually low (it is mainly caused by low friction link-side bearings), it may be neglected and the link-side observer essentially estimates the true external joint torques \\cite{Haddadin2014}.\nTherefore, it is possible to set up two observer schemes, one for the actuator side estimating $\\bm{\\tau}_{\\mathrm{f},\\theta}$ \\cite{LeTienAlbDeHir2008}, and one for the link side estimating $\\bm{\\tau}_\\mathrm{ext}$.\nNote that one can obviously set up an elastic joint model for the hydraulic case as well.\nHowever, this would only have a similar implication if an additional joint torque sensor for decoupling would be inserted after link friction.\n\nTo be able to distinguish between internal and external effects, we extend the momentum-based disturbance observer from \\cite{DeLucaMat2003,DeLucaMat2004,Haddadin2014} to include measurements of external wrenches $\\medmuskip=1.3mu\n\\thinmuskip=1.3mu\n\\thickmuskip=1.3mu\n\\bm{\\mathcal{F}}_\\mathrm{ext,EE}=\\begin{pmatrix}\\bm{f}_{\\mathrm{ext,EE}} & \\bm{m}_{\\mathrm{ext,EE}}\\end{pmatrix}^\\mathrm{T}$ that act on the end-effector, i.e. ``after'' the sensor \\cite{OttHenLee2013}.\nThe extended residual for end-effector contacts is then defined as\n%\n\\begin{equation}\n\\medmuskip=0.5mu\n\\thinmuskip=0.5mu\n\\thickmuskip=0.5mu\n\\hat{\\bm{\\tau}}_\\mathrm{\\varepsilon}=\\bm{K}_\\mathrm{o}\n\\left(\n\\hat{\\bm{M}}(\\bm{q})\\dot{\\bm{q}}\n-\\int\\limits_0^t\n [\\bm{\\tau}_\\mathrm{m}\n -\\bm{\\gamma}(\\bm{q},\\dot{\\bm{q}})\n +\\hat{\\bm{\\tau}}_\\mathrm{\\varepsilon}\n -\\bm{\\alpha}(\\bm{q},\\dot{\\bm{q}})\n ]\\mathrm{d}\\tilde{t} \n \\right),\n\\label{eqn:observer}\n\\end{equation}\n%\nwhere $\\bm{K}_\\mathrm{o}=\\mathrm{diag}\\{k_{\\mathrm{o},i}\\}>\\bm{0}$ is the observer gain matrix and\n\\begin{equation}\n\\medmuskip=0.05mu\n\\thinmuskip=0.05mu\n\\thickmuskip=0.05mu\n\\bm{\\gamma}(\\bm{q},\\dot{\\bm{q}}):=\n\\hat{\\bm{g}}(\\bm{q})\n+\\hat{\\bm{C}}(\\bm{q},\\dot{\\bm{q}})\\dot{\\bm{q}}\n-\\dot{\\hat{\\bm{M}}}(\\bm{q})\\dot{\\bm{q}}\n=\n\\hat{\\bm{g}}(\\bm{q})-\\hat{\\bm{C}}^\\mathrm{T}(\\bm{q},\\dot{\\bm{q}})\\dot{\\bm{q}}\\;.\n\\label{eqn:gamma}\n\\end{equation}\nEquality (\\ref{eqn:gamma}) follows directly from the skew-symmetry of $\\dot{\\hat{\\bm{M}}}(\\bm{q})-2\\hat{\\bm{C}}(\\bm{q},\\dot{\\bm{q}})$ \\cite{DeLucaAlbHadHir2006}. \nThe vector $\\bm{\\alpha}(\\bm{q},\\dot{\\bm{q}})$ is defined as \n\\begin{equation}\n\\begin{split}\n\\bm{\\alpha}(\\bm{q},\\dot{\\bm{q}}) :=& \n\\kappa_{\\mathrm{f}}\\hat{\\bm{\\tau}}_\\mathrm{f}(\\dot{\\bm{q}}) -\\kappa_{\\mathrm{ext}}\\bm{\\tau}_{\\mathrm{ext,EE}} \\\\\n=&\n\\kappa_{\\mathrm{f}}\\hat{\\bm{\\tau}}_\\mathrm{f}(\\dot{\\bm{q}})\n-\\kappa_{\\mathrm{ext}}\\bm{J}^{\\mathrm{T}}(\\bm{q}) \\bm{\\mathcal{F}}_\\mathrm{ext,EE} \\; .\n\\end{split}\n\\label{eqn:observer_settings}\n\\end{equation}\nThe contact wrench $\\bm{\\mathcal{F}}_\\mathrm{ext,EE}$ is typically measured with a load-compensated force/torque sensor in the robot wrist.\nThe resulting external joint torques $\\bm{\\tau}_{\\mathrm{ext,EE}}$ are obtained by the well known mapping via the end-effector Jacobian $\\bm{J}(\\bm{q})$. \nIts feedback is activated via $\\kappa_{\\mathrm{ext}} \\in \\{0,1\\}$. \nNote that the components of $\\bm{\\mathcal{F}}_\\mathrm{ext,EE}$ that are in the kernel of $\\bm{J}^{\\mathrm{T}}(\\bm{q})$ are absorbed by the structure of the robot and are not reflected in $\\bm{\\tau}_{\\mathrm{ext,EE}}$. \n\nTo distinguish directly measurable joint torques originating from external wrenches at the end-effector $\\bm{\\tau}_{\\mathrm{ext,EE}}$ from joint torques caused by external wrenches at the structure $\\bm{\\tau}_{\\mathrm{ext,links}}$ that cannot be measured by the wrist sensor, we define the total external torque vector $\\bm{\\tau}_{\\mathrm{ext}}$ to be\n\\begin{equation}\n\\bm{\\tau}_{\\mathrm{ext}} := \\bm{\\tau}_{\\mathrm{ext,EE}} + \\bm{\\tau}_{\\mathrm{ext,links}}.\n\\label{eqn:extjointtorqueseparata}\n\\end{equation}\nThe true disturbance joint torque ${\\bm{\\tau}}_\\mathrm{\\varepsilon}$ for rigid joint models consists of the joint torques from (\\ref{eqn:extjointtorqueseparata}) plus the error term $\\bm{\\delta}$ in (\\ref{eqn:closedloop_general}).\n%\nAs derived in \\cite{Haddadin2014} the observed disturbance torque, also for this extended form, converges element-wise with first order dynamics (presented in frequency domain)\n\\begin{equation}\n\\hat{\\tau}_{\\mathrm{\\varepsilon},i}=\n\\frac{k_{\\mathrm{o},i}}{s+k_{\\mathrm{o},i}}\n\\left(\\tau_{\\mathrm{ext,EE},i}(1-\\kappa_{\\mathrm{ext}})\n+ \\tau_{\\mathrm{ext,link},i}\n+ \\delta_{i}\n\\right)\n\\label{eqn:disttorqueconvergence}\n\\end{equation}\nwhere $1/k_{\\mathrm{o},i}$ is the time constant.\n%\n\\begin{figure}\n\\centering\n\\includegraphics{./figures/ObserverFlowChart/observer_scheme}\n\\caption{Flowchart of the proposed observer structure.}\n\\label{fig:observer_flowchart}\n\\SkipBeforeText\n\\end{figure}\n%\nFigure~\\ref{fig:observer_flowchart} depicts an overview of the overall observer structure.\n\nIn the next section, we outline how this extended disturbance observer is used to compensate for model errors and detect collisions simultaneously. \n\n\\subsection{Compensation of Model Errors and Collision Detection}\n\\label{sec:friction_comp_and_collDet}\n\nAssuming $\\bm{\\tau}_\\mathrm{ext}$ to have slower dynamics than the observer (sufficiently large observer gain $\\bm{K}_{\\mathrm{o}}$).\nOne can approximate the disturbance torque as\n\\mbox{$\\hat{\\bm{\\tau}}_\\mathrm{\\varepsilon}\\approx\n\\left(\\bm{\\tau}_\\mathrm{ext,EE}(1-\\kappa_{\\mathrm{ext}})\n+ \\bm{\\tau}_\\mathrm{ext,link}\n+ \\bm{\\delta}\n\\right)$}.\nTherefore, one obtains from equation (\\ref{eqn:closedloop_general})\n\\begin{equation}\n\\begin{split}\n\\bm{M(\\bm{q})}\\ddot{\\bm{q}}-\\hat{\\bm{M}}(\\bm{q}_\\mathrm{d})\\ddot{\\bm{q}}_\\mathrm{d}\n+\\bm{D}(\\dot{\\bm{q}}-\\dot{\\bm{q}}_\\mathrm{d})\n+\\bm{K}(\\bm{q}-\\bm{q}_\\mathrm{d})\\\\\n= \\bm{\\tau}_\\mathrm{ext}+\\bm{\\delta}\n-\\kappa_{\\varepsilon}\\left(\n  \\bm{\\tau}_\\mathrm{ext,EE}(1-\\kappa_{\\mathrm{ext}})\n+ \\bm{\\tau}_\\mathrm{ext,link}\n+ \\bm{\\delta}\n\\right)\\;.\n\\end{split}\n\\label{eqn:closed_loop_converged}\n\\end{equation}\nThe trajectory tracking performance can thus be improved significantly by using the disturbance compensation with $\\kappa_{\\varepsilon}=1$ in (\\ref{eqn:controller}) and $\\kappa_\\mathrm{ext}=0$ in (\\ref{eqn:observer_settings}), as this would eliminate model inaccuracies $\\bm{\\delta}$. \nThe obvious drawback would be the loss of compliance w.r.t. external torques, since equation (\\ref{eqn:closed_loop_converged}) becomes\n\\begin{equation}\n\\bm{M(\\bm{q})}\\ddot{\\bm{q}}-\\hat{\\bm{M}}(\\bm{q}_\\mathrm{d})\\ddot{\\bm{q}}_\\mathrm{d}\n+\\bm{D}(\\dot{\\bm{q}}-\\dot{\\bm{q}}_\\mathrm{d})\n+\\bm{K}(\\bm{q}-\\bm{q}_\\mathrm{d})\n= \\bm{0}.\n\\label{eqn:compLoss}\n\\end{equation}\nThus, the system no longer reacts to external forces in case of precise disturbance estimates. \nThis unwanted increase in stiffness could be avoided for interaction with the end-effector by exploiting wrist wrench sensing.\nSetting $\\kappa_{\\varepsilon}=1$ in (\\ref{eqn:controller}) and $\\kappa_{\\mathrm{ext}}=1$ in (\\ref{eqn:observer_settings}), the closed loop behavior (\\ref{eqn:closedloop_general}) becomes\n%\n\\begin{equation}\n\\medmuskip=3mu\n\\thinmuskip=3mu\n\\thickmuskip=3mu\n\\bm{M(\\bm{q})}\\ddot{\\bm{q}}-\\hat{\\bm{M}}(\\bm{q}_\\mathrm{d})\\ddot{\\bm{q}}_\\mathrm{d}\n+\\bm{D}(\\dot{\\bm{q}}-\\dot{\\bm{q}}_\\mathrm{d})\n+\\bm{K}(\\bm{q}-\\bm{q}_\\mathrm{d})=\n\\bm{\\tau}_\\mathrm{ext,EE}\\;.\n\\label{eqn:regainComp}\n\\end{equation}\nThis scheme has similarities to the one proposed in \\cite{Oh1999} and will be termed disturbance compensation (DC) with external forces compliance (EFC) from now on. A qualitative comparison for the different settings of $\\kappa_{\\varepsilon}$ and $\\kappa_\\mathrm{ext}$ is shown in the Table of Fig.~\\ref{fig:ReactionScheme}.\n%\n\nIn summary, it is possible to \n%\n\\begin{enumerate}\n\\item detect end-effector contacts with the inertia compensated wrench sensor,\n\\item detect contacts along the entire robot structure beyond a tolerance band with the extended observer,\n\\item render end-effector compliance while having stiff behavior for contacts along the robot structure.\n\\end{enumerate}\n\nThe missing compliance for link collisions can still be encountered by switching to compliance control as soon as a link collision is detected. \n\nUsing the above observer, we implemented a simple collision detection scheme that is based on a constant disturbance joint torque threshold ${\\bm{\\zeta}}$.\n%\n\\begin{equation}\n\\text{CollDet}=\n\\begin{cases}\n    1,& \\text{if } \\hat{\\bm{\\tau}}_{\\varepsilon} > {\\bm{\\zeta}} \\text{ (component wise)}\\\\\n    0,& \\text{otherwise}\n\\end{cases}\n\\label{eqn:CollDet}\n\\end{equation}\nFor (\\ref{eqn:CollDet}) to work properly, one has to solve the trade-off between robustness and convergence speed of the observer.\nThe first order observer dynamics in (\\ref{eqn:disttorqueconvergence}) with time constant $1/k_{\\mathrm{o},i}$ makes the collision detection robust against sensor noise and peaks, as long as $\\bm{K}_{\\mathrm{o}}$ is not chosen too large.\nHowever, large $\\bm{K}_{\\mathrm{o}}$ leads to faster convergence of $\\hat{\\bm{\\tau}}_\\mathrm{\\varepsilon}$ to $\\bm{\\tau}_\\mathrm{ext}$.\n\n\\begin{figure}\n\\centering\n\\includegraphics[scale=0.999]{./figures/ReactionScheme/reaction_scheme}\n\\SkipBeforePicture\n\\begin{center}\\footnotesize\n\\begin{tabular}{|l|c|c|c|}\n\\hline\nProperty & $\\kappa_{\\varepsilon}=0$ & $\\medmuskip=0mu\n\\thinmuskip=0mu \\thickmuskip=0mu \\kappa_{\\varepsilon}=1, \\kappa_{\\mathrm{ext}}=0$ & $\\medmuskip=0mu \\thinmuskip=0mu \\thickmuskip=0mu \\kappa_{\\varepsilon}=\\kappa_{\\mathrm{ext}}=1$ \\\\\n\\hline\nIncreased accuracy      & \\no & \\ok & \\ok \\\\\n\\hline\nEnd-effector compliance  & \\ok & \\no & \\ok \\\\\n\\hline\nLink compliance          & \\ok & \\no & \\no \\\\\n\\hline\nClosed-loop behavior & (\\ref{eqn:closedloop_general}) & (\\ref{eqn:compLoss}) & (\\ref{eqn:regainComp}) \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\SkipBeforePicture\n\\caption{Context sensitive control and reaction scheme and comparison between different setups of controller (\\ref{eqn:controller}).\nControl mode \\mbox{$\\kappa_\\mathrm{ext}=1$} is used for tasks which need end-effector compliance, \\mbox{$\\kappa_\\mathrm{ext}=0$} for tasks which do not. When a collision is detected, the controller switches into compliant mode ($\\kappa_\\varepsilon=0$).}\n\\label{fig:ReactionScheme}\n\\SkipBeforeText\n\\end{figure}\n\nFor collision reaction, in this work, we switch to gravity compensation mode \\cite{Haddadin2014}:\n\\begin{equation}\n\\bm{\\tau}_\\mathrm{d}=\n\\begin{cases}\n    \\hat{\\bm{g}}(\\bm{q}),& \\text{if CollDet}=1 \\\\\n    \\bm{\\tau}_\\mathrm{d} \\text{ from (\\ref{eqn:controller})},& \\text{otherwise}\\;.\n\\end{cases}\n\\label{eqn:CollReact}\n\\end{equation}\n%\nAnother possibility would be to implement the scheme depicted in Fig.~\\ref{fig:ReactionScheme}.\nIt uses the three control modes in the table in a context sensitive manner.\nFor example, for grasping objects end-effector compliance and high position accuracy is needed, therefore \\mbox{$\\kappa_\\varepsilon=1$} and \\mbox{$\\kappa_\\mathrm{ext}=1$} is used. For moving objects of unknown weight, end-effector compliance is not wanted and therefore \\mbox{$\\kappa_\\mathrm{ext}=1$} is used.\nFinally, if the collision threshold is exceeded, the robot switches into full compliant mode (\\mbox{$\\kappa_\\varepsilon=0$}) to avoid damage.\n\nNext, we outline our system identification and friction modeling approach.\n\n\n", "meta": {"hexsha": "71f8ece10a0f38fb67ca79dae1bfd9e74a9c8aaa", "size": 17175, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/sec_model.tex", "max_stars_repo_name": "wuyou33/robotics-paper_iros2016", "max_stars_repo_head_hexsha": "ad8811f17b19176bb1ac0194191ad1d0f12ba073", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-22T02:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T02:23:33.000Z", "max_issues_repo_path": "paper/sec_model.tex", "max_issues_repo_name": "wuyou33/robotics-paper_iros2016", "max_issues_repo_head_hexsha": "ad8811f17b19176bb1ac0194191ad1d0f12ba073", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/sec_model.tex", "max_forks_repo_name": "wuyou33/robotics-paper_iros2016", "max_forks_repo_head_hexsha": "ad8811f17b19176bb1ac0194191ad1d0f12ba073", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 60.9042553191, "max_line_length": 480, "alphanum_fraction": 0.7233770015, "num_tokens": 5360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.33328942688446933}}
{"text": "%#!platex DeepLearningTurbidite.tex\r\n\r\n\\section{notation}\r\nThe symbols L, M and T denote dimensions of length, mass and time respectively. The symbol [1] denotes that the value is dimensionless.\r\n\r\n\\begin{description}\r\n\\item[$C_T$] Total layer-averaged sediment concentration [$\\mathrm{1}$]\r\n\\item[$C_i$] Layer-averaged sediment concentration of the $i$th grain-size class [$\\mathrm{1}$]\r\n\\item[$C_f$] Bed friction coefficient [$\\mathrm{1}$]\r\n\\item[$e_{si}$] Sediment entrainment coefficient [$\\mathrm{1}$]\r\n\\item[$F_i$] Volumetric fraction of the $i$th grain-size class in the active layer [$\\mathrm{1}$]\r\n\\item[$L_a$] Thickness of the active layer [$\\mathrm{L}$]\r\n\\item[$R$] Submerged specific density of sediment particles ($=1 - \\rho_s / \\rho_f$) [$\\mathrm{1}$]\r\n\\item[$S$] Bed slope [1]\r\n\\item[$U$] Layer-averaged velocity of turbidity currents [$\\mathrm{LT^{-1}}$]\r\n \\item[$g$] Acceleration of gravity [$\\mathrm{LT^{-2}}$]\r\n \\item[$h$] Flow depth of turbidity current [$\\mathrm{L}$]\r\n \\item[$l_0$] Initial length of suspended sediment cloud [$\\mathrm{L}$] \r\n  \\item[$r_{0i}$] Ratio of near-bed sediment concentration of the $i$th grain-size class to layer-averaged concentration [$1$]\r\n \\item[$t$] Time [$\\mathrm{T}$]\r\n \\item[$w_{si}$] Settling velocity of sediment of the $i$th grain-size class [$\\mathrm{LT^{-1}}$]\r\n \\item[$x$] Bed-attached streamwise coordinate [$\\mathrm{L}$]\r\n \\item[$H_0$] Initial height of suspended sediment cloud [$\\mathrm{L}$] \r\n \\item[$J$] Number of model input parameters [1] \r\n \\item[$K$] Number of test datasets [1] \r\n \\item[$N$] Number of grain size classes [1] \r\n  \\item[$S_l$] Basin slope [1] \r\n \\item[$\\eta_T$] Thickness of the turbidite [$\\mathrm{L}$]\r\n \\item[$\\eta_i$] Volume per unit area of sediment of the $i$th grain-size class [$\\mathrm{L}$]\r\n \\item[$\\lambda_p$] Porosity of the turbidite [$\\mathrm{1}$]\r\n\\item[$\\rho_s$] Density of sediment particles [$\\mathrm{ML^{-3}}$]\r\n\\item[$\\rho_f$] Density of the water [$\\mathrm{ML^{-3}}$]\r\n\r\n\\end{description}\r\n\r\n", "meta": {"hexsha": "fa562726cf31c0cf9e2ff29aa39c53fdffc8faf2", "size": 2002, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/notation.tex", "max_stars_repo_name": "narusehajime/nninv1d", "max_stars_repo_head_hexsha": "697743346c7e24a8f06d676e2e9f3330aee93afe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tex/notation.tex", "max_issues_repo_name": "narusehajime/nninv1d", "max_issues_repo_head_hexsha": "697743346c7e24a8f06d676e2e9f3330aee93afe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/notation.tex", "max_forks_repo_name": "narusehajime/nninv1d", "max_forks_repo_head_hexsha": "697743346c7e24a8f06d676e2e9f3330aee93afe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.6111111111, "max_line_length": 136, "alphanum_fraction": 0.6768231768, "num_tokens": 621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926666143434, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.33318324344340533}}
{"text": "\\documentclass[a4paper]{article} %,twoside\n\\usepackage[english]{babel}\n%\\usepackage[final,ulem=normalem]{changes}\n\n%%\n%% Packages to be used.\n%%\n\\usepackage[utf8]{inputenc}\n\\usepackage{amsmath,amsfonts,amsthm,amssymb,amscd}\n\\usepackage{booktabs}\n\\usepackage{multirow}\n%\\usepackage{zibtitlepage}\n\\usepackage{alltt}\n\\usepackage{algorithm}\n\\usepackage{algorithmic}\n\\renewcommand{\\algorithmicrequire}{\\textbf{Input:}}\n\\renewcommand{\\algorithmicensure}{\\textbf{Output:}}\n\n%%\n%% PDF / DVI output\n%%\n\\usepackage{color}\n\\usepackage[pdftex]{graphicx}\n\\usepackage[pdftex]{thumbpdf}\n\\usepackage{epstopdf}\n\\graphicspath{{figures/}}\n\n\\usepackage{tikz}\n\\usetikzlibrary{arrows,calc,decorations.markings,intersections,positioning,shapes.arrows}\n\n\\usepackage{caption}\n\\usepackage{subcaption}\n\n\\usepackage{cite}\n\\usepackage[colorlinks=true]{hyperref}\n\n\\usepackage{url}\n\\usepackage{todonotes}\n\n\\usepackage{listings}\n\\lstset{language=Fortran,\n\tbasicstyle=\\small\\sffamily,\n\tcolumns=fullflexible,\n\tcaptionpos=b}\n\n\\lstdefinelanguage{tt}{\n\t\tbasicstyle=\\ttfamily}\n\t\n%Remove later, used only for getting todos in the margin\n%\\setlength{\\marginparwidth}{3cm}\n\n%%\n%% Special sets.\n%%\n\\newcommand{\\N}{\\mathbb{N}}\n\\newcommand{\\R}{\\mathbb{R}}\n\\newcommand{\\One}{\\boldsymbol{1}}\n\n\n%%\n%% Mathematical convenience.\n%%\n\\DeclareMathOperator{\\ld}{log_2}\n\\DeclareMathOperator{\\convex}{co}\n\\newcommand{\\half}{\\frac{1}{2}}\n\\newcommand{\\Ol}[1]{\\mathcal{O}(#1)}\n\\newcommand{\\dual}[1]{#1^\\star}\n\\newcommand{\\norm}[1]{\\left\\|#1\\right\\|}\n\\newcommand{\\const}{\\mathrm{const}\\,}\n\\renewcommand{\\d}{\\mathrm{d}}\n\n\\usepackage{pgfplots}\n\\usepackage{pgfplotstable}\n\\pgfplotsset{compat=newest}\n\\usepackage{booktabs}\n\n\\begin{document}\n\n\\title{Optimal Control of the Initial Condition for the KS Equation With LibPFASST}\n\\author{Sebastian Götschel}\n\\maketitle\n\n\\section{Problem setting}\n\n\nWe are considering the 1D Kuramoto-Sivashinsky equation\n\\begin{equation} \\label{eq:KS}\ny_t = -y y_x - y_{xx} - y_{xxxx}, \\quad x \\in \\Omega := [0,32\\pi]\n\\end{equation}\nwith periodic boundary conditions on some time interval $t \\in [0,T]$. Given some measured data (in the optimal control setting called \\emph{desired state}) $y_d(t,x)$, the aim is to identify an initial condition $y(0,x) = u(x)$ such that the solution $y(t,x;u)$ minimizes the deviation from the desired state. We will often refer to $u$ as the \\emph{control}. Put into formula, we want to minimize the \\emph{objective functional}\n\\begin{equation}\\label{eq:obj}\nJ(y,u) := \\frac{1}{2}\\int_{0}^{T} \\int_\\Omega (y-y_d)^2 \\mathrm{d}x\\ \\mathrm{d}t + R(u),\n\\end{equation}\nwhere $R$ is some generic regularization term, e.g., $R(u) = \\frac{\\lambda}{2} \\norm{u}^2$.\n\n\n\\paragraph{Gradient-based optimization.} For the gradient-based methods considered here, the optimization iteration proceeds as \n\\begin{align}\nu_{k+1} &= u_k + \\alpha_k d_k \\label{eq:update_u} \\\\\nd_{k+1} &= -\\nabla j(u_{k+1})+ \\beta_k d_k, \\label{eq:update_d}\n\\end{align}\nwhere $k$ is the iteration number, $\\nabla j(u_{k})$ the \\emph{reduced gradient}, and $\\alpha_k$ some step length for the control update. The parameter $\\beta_k$ is used to update the descent direction $d_k$ and determines the type of method (steepest descent for $\\beta_k = 0$, various choices for nonlinear conjugate gradient methods).\n\n\\paragraph{Computation of the reduced gradient.} Adjoint gradient computation consists of three steps:\n\\begin{enumerate}\n\t\\item Solve the PDE \\eqref{eq:KS} for a given control $u$\n\t\\item Solve the adjoint PDE \n\t\\begin{equation}\\label{eq:adjoint}\n\t\t-p_t = p p_x - p_{xx} - p_{xxxx} + (y-y_d), \\quad x \\in \\Omega := [0,32\\pi]\n\t\\end{equation}\n\twith periodic boundary boundary conditions and $p(T,x) = 0$.\n\t\\item Set $\\nabla j(u) =  p(0,x) + R'(u)$. \n\\end{enumerate}\nThe source term in eq.~\\ref{eq:adjoint} comes from differentiating the objective functional \\ref{eq:obj} with respect to the state $y$. If, instead of or in addition to, the difference $y-y_d$ in $[0,T] \\times \\Omega$ we track some desired final state $y_d^T(x)-y(T,x)$ the terminal condition in the adjoint gets modified to $p(T,x) =  y_d^T(x)-y(T,x)$ to account for this deviation.\n\nFor details on PDE-constrained optimization see, e.g., \\cite{HinzeEtAl2009,Troeltzsch2010}.\n\n\\section{Implementation}\n\n\nThis tutorial example consists of six source files\n\\begin{itemize}\n\t\\item \\lstinline+hooks.f90+ - output residuals during sweeps/PFASST iterations\n\t\\item \\lstinline+level.f90+ - interpolation/restriction of solutions\n\t\\item \\lstinline+main.f90+ - main program, contains main optimization loop\n\t\\item \\lstinline+pf_optimization_1d.f90+ - routines for evaluating objective, gradient, steps size selection\n\t\\item \\lstinline+probin.f90+ - define problem parameters\n\t\\item \\lstinline+sweeper.f90+ - defines problem equations and optimization quantities\n\\end{itemize}\nas well as\n\\begin{itemize}\n\t\\item \\lstinline+Makefile+\n\t\\item \\lstinline+imex.nml+ - specify input parameters for test runs\n\t\\item \\lstinline+plot.py+ - helper file to produce figures from npy output.\n\\end{itemize}\n\nIn the following we provide a walkthrough through the main parts of the implementation. For all details you will need to go through the actual source code, though.\n\n\\subsection{Encapsulation, sweeper, and controller for optimal control}\n\nThe LibPFASST library comes with a special data structure \\lstinline|pf_ndarray_oc_t| (file \\lstinline|pf_ndarray_oc_encap.f90|) to store solutions as well as a IMEX sweeper \\lstinline|pf_imexQ_oc_t| (file \\lstinline|pf_imexQ_oc_sweeper.f90|) capable of forward- and backward-in-time IMEX-SDC sweeps.\n\nAs the optimal control problem requires state and adjoint solution, PFASST's \\lstinline|pf_ndarray_t| is extended to contain two variables stored in \\lstinline|yflatarray| and \\lstinline|pflatarray|. It provides all the functionality of \\lstinline|pf_ndarray_t|, with the functions taking an optional \\lstinline|flag| argument specifying on which component to operate on (\\lstinline|flag==1| operates on \\lstinline|yflatarry|, \\lstinline|flag==2|  on \\lstinline|pflatarry|, and \\lstinline|flag==0| on both).\n\nSimilarly, the optimal control sweeper provides the same functionality as the standard IMEX sweeper \\lstinline|pf_imex_sweeper_t|, again with a \\lstinline|flag| argument for the function specifying the component and thus forward or backward sweeps (or both).\n\nFinally, for running PFASST routines like \\lstinline|pf_predictor_oc|, \\lstinline|pf_pfasst_block_oc| or \\lstinline|pf_vcycle_oc| are provided in \\lstinline|pf_parallel_oc.f90|. These routines are similar to the standard PFASST functions in \\lstinline|pf_parallel.f90|, but adapted to the optimal control setting (e.g., sweeping backwards on the adjoint).\n\nIn most cases, the user should not need to edit these library files to solve application problems.\n\n\\subsection{The optimization loop}\n\nBesides setting up PFASST and allocating data structures for various quantities used during the optimization, the main part of solving the optimal control problems happens in the optimization loop in \\lstinline|main.f90|, see Listing~\\ref{lst:optloop}.\n\n\\begin{lstlisting}[frame=tb,caption={Most important parts of the optimization loop from \\lstinline|main.f90|},label=lst:optloop]\ndo k=1,max_opt_iter\n\tif (k .eq. 1) then\n\t\tcall evaluate_objective(...)\n\t else\n\t\tobjective=objectiveNew ! from step size selection/linesearch\n\tend if\n\t\n\tcall mpi_allreduce(objective, globObj, 1, MPI_REAL8, MPI_SUM, pf%comm%comm, ierror)\n\tif (globObj < tol_obj) exit ! leave loop\n\n\tif (k .eq. 1) then   ! in later iterations, this is done in linesearch\n\t\tcall evaluate_gradient(...)\n\tend if\n\t\n\t ! compute gradient norms\n\tglobL2NormGradSq = sum(gradient**2)*Lx/dble(nvars(pf%nlevels))\n\tglobLinftyNormGrad = maxval(abs(gradient))\n\t\n\tif (sqrt(globL2NormGradSq) < tol_grad) exit\n\t\n\t! determine new search direction, here: steepest descent\n\tbeta = 0.0_pfdp\n\tsearchDir = -gradient + beta*prevSearchDir\n\t\n\t! line search for step size selection\n\tcall armijo_step()\n\t\n\tif (stepTooSmall) exit\nend do\n\\end{lstlisting}\n%\nAlgorithmic parameters like \\lstinline|max_opt_iter| or \\lstinline|tol_grad| are defined in \\lstinline|probin.f90| and can be set via command line parameters or an \\lstinline|*.nml| file. The main work happens in the functions \\lstinline|evaluate_objective| and \\lstinline|evaluate_gradient| from \\lstinline|pf_optimization_1d.f90|, where state and adjoint equations are solved, the objective functional gets evaluated and the gradient assembled. Only in the first optimization iteration these are called directly; in the following iterations they get called during linesearch (e.g., \\lstinline|armijo_step|).\n\nSolving the state equation by PFASST is done in \\lstinline|evaluate_objective|, and is shown in excerpts in Listing~\\ref{lst:evalobj}.\n\\begin{lstlisting}[frame=tb,caption={\\lstinline|evalute_objective| from \\lstinline|pf_optimization_1d.f90|},label=lst:evalobj]\nsubroutine evaluate_objective(...)\n\t! ...\n\t! set initial condition\n\tq1%yflatarray = ctrl\n\tcall pf%levels(pf%nlevels)%q0%copy(q1, 1) \n\tdo step = 1, nsteps ! this iterates over all steps this processor computes\n\t\tthisstep = (step-1)*pf%comm%nproc + pf%rank  \n\t\t! this is the 'true' time step we are computing \n\t\t! i.e., this processors time interval in this step\n\t\t! is [thisstep*dt, (thisstep+1)*dt]\n\t\t\n\t\t! use PFASST to solve on this block of time steps, i.e., every processors computes \n\t\t! their time step in parallel, exchanging data to transmit\n\t\t! initial conditions on the time intervals\n\t\tpf%state%pfblock = step    \n\t\tcall pf_pfasst_block_oc(pf, dt, step*pf%comm%nproc, .true., 1, step=thisstep)\n\t\t\n\t\t! evaluate objective functional for all quadrature nodes\n\t\tdo m = 1, nnodes\n\t\t\tcall objective_function(...)\n\t\tend do\n\t\t! integrate objective functional \n\t\tobjective = ...\n\t\t\n\t\t! copy/broadcase qend to q0 for next step\n\t\tif( step < nsteps ) then\n\t\t\tcall pf%levels(pf%nlevels)%qend%pack(...)   \n\t\t\tcall pf_broadcast(...)\n\t\t\tcall pf%levels(pf%nlevels)%q0%unpack(...)   \n\t\tend if\n\tend do\n\t\n\t! L2(Omega) control norm\n\tL2NormCtrlSq = sum(ctrl**2)*Lx/dble(nx)\n    objective = 0.5*objective + 0.5*alpha*L2NormCtrlSq\nend subroutine evaluate_objective\n\\end{lstlisting}\nThe main difference to the other Tutorial examples, where a single PDE is solved only once, is, that we cannot use the usual PFASST controller, but have assign blocks of time steps to processors by hand as well as record the solution values in order to solve the adjoint equation backward in time. There, the processors need to solve the specified time steps for which they have the state equation's solution, thus avoiding costly communication as well as memory issues, as every processor only has to store the values it actually needs.\n\nThe \\lstinline|evaluate_gradient| is similar, and consists of solving the adjoint and constructing the gradient. As the gradient requires the value of the adjoint at $t=0$, the first processor broadcasts this solution to the other processors, see Listing~\\ref{lst:evalgrad}. This broadcast could be left out when it is ensured that only the first processor updates the control (i.e., the initial condition); this modification is left as an exercise for the reader.\n\n\\begin{lstlisting}[frame=tb,caption={Excerpt of \\lstinline|evalute_gradient| from \\lstinline|pf_optimization_1d.f90|},label=lst:evalgrad]\nif(pf%rank == 0) then\n\t! gradient is adjoint at t0 (plus regularization term derivative = alpha*ctrl)\n\t! pack away on rank 0\n\tcall pf%levels(pf%nlevels)%q0%pack(pf%levels(pf%nlevels)%send, 2)\nend if\n! broadcast\ncall pf_broadcast(pf, pf%levels(pf%nlevels)%send, pf%levels(pf%nlevels)%mpibuflen, 0)\n! everybody sets gradient (actually this could be skipped, only rank 0 needs initial condition)\ngradient = pf%levels(pf%nlevels)%send\ngradient = gradient + alpha * ctrl\n\\end{lstlisting}\n\nWe do not discuss the line search functions \\lstinline|armijo_step| and \\lstinline|strong_wolfe_step| here. They are rather straightforward implementations of the standard Armijo- and strong Wolfe conditions (see your favorite textbook on nonlinear optimization, e.g., \\cite{NocedalWright2006}).\n\n\\subsection{Specifying the equations}\n\nDuring sweeps, the sweeper calls \\lstinline|feval| and \\lstinline|fcomp| routines, which are defined in \\lstinline|sweeper.f90|. Here the equations are specified. We use an IMEX approach, treating $-y_{xx}-y_{xxxx}$ implicitly.\n\n\\begin{lstlisting}[frame=tb,caption={Excerpt of \\lstinline|feval| from \\lstinline|sweeper.f90|},label=lst:feval]\nselect case (flags) ! are we solving for state or adjoint?\ncase(1) ! State\n\t!  Grab the arrays from the encap\n\tyvec => get_array1d_oc(y,1) ! ( ,1) means get state component\n\tfvec => get_array1d_oc(f,1)\n\n\t! explicit piece: -y y_x\n\ttmp = -0.5_pfdp*yvec*yvec\n\tcall fft%conv(tmp, this%ddx, fvec)\n\ncase(2) ! Adjoint\n\t!  Grab the arrays from the encap\n\tyvec => get_array1d_oc(y,1) ! state sol required for rhs (y-y_desired)\n\tfvec => get_array1d_oc(f,2)\n\tpvec => get_array1d_oc(y,2)\n\n\t! explicit piece: +y y_x\n\ttmp = 0.5_pfdp*pvec*pvec\n\tcall fft%conv(tmp, this%ddx, fvec)\n\n\t! source term from distributed tracking objective\n\tfvec = fvec + (yvec-this%ydesired(mystep, idx, :))\nend select\n\\end{lstlisting}\n\nListing \\ref{lst:feval} shows an excerpt of the \\lstinline|feval| function, specifying the explicit part of the equation. \\lstinline|flags| specifies which equation is to be solved, \\lstinline|flags==1| is the state equation, \\lstinline|flags==2| specifies the adjoint. In the latter, the source term from the distributed tracking type objective enters. The implicit piece is also evaluated using FFT, \\lstinline|call fft%conv(yvec,-this%lap-this%lap*this%lap,fvec)|; this does not differ between state and adjoint.\n\n\\begin{lstlisting}[frame=tb,caption={Excerpt of \\lstinline|fcomp| from \\lstinline|sweeper.f90|},label=lst:fcomp]\nif (piece == 2) then\n\t! Apply the inverse operator with the FFT convolution\n\tcall fft%conv(rhsvec,1.0_pfdp/(1.0_pfdp - dtq*(-this%lap*this%lap-this%lap)),yvec)\n\tfvec = (yvec - rhsvec) / dtq\nend if\n\\end{lstlisting}\n\nThe \\lstinline|fcomp| function in Listing \\ref{lst:fcomp} is similar to the other tutorial examples and has no modifications due to the optimization problem.\n\n\n\\subsection{Helper and convenience functions}\n\nIn \\lstinline|sweeper.f90| some helper functions specific to the optimization problem can be found. These are, e.g., \\lstinline|initialize_ocp| to allocate memory for the desired state, or \\lstinline|set_ydesired| to fill the variable with a desired state coming from measurements or artificially generated data. More importantly, functionality to evaluate the objective functional is provided (\\lstinline|objective_function(...)|), as well as functions to restrict the desired state (and the computed fine state solution) to coarser levels as required for solving the adjoint.\n\n\\section{Numerical example}\n\nHere we show two numerical results, without giving much detail. Please consider \\lstinline|imex.nml| for input parameters.\n\n\\subsection{Forward solve}\n\nWe use the example from \\cite{KassamTrefethen2005} and solve the KS equation for $x\\in[0,32\\pi]$ on the time interval $[0,60]$ using the initial condition $y(0,x) = \\cos(x/16)(1+\\sin(x/16))$. The solution using 600 time steps and two levels with 3/5 Lobatto nodes and 512/1024 spatial degrees of freedom is shown in Fig.~\\ref{fig:KS60}. \n\n\\begin{figure}\n\\includegraphics[scale=0.7]{figures/solKS_T60_nstep600_nx1024.png}\n\\caption{Solution of the KS equation}\n\\label{fig:KS60}\n\\end{figure}\n\n\\subsection{Identifying the initial condition}\n\nDue to the complicated dynamics, identifying the initial condition is demonstrated on the rather short time interval $[0,1]$, with 100 time steps. The other discretization parameters are as above. We start the optimization with an initial guess $u_0 = 0.75 u_\\text{exact}$. The target state is shown in Fig.~\\ref{fig:yd}. Fig.~\\ref{fig:optprogress} shows the progress of the steepest descent method, while Fig.~\\ref{fig:ctrl} shows the computed control (i.e., identified initial condition) as well as the difference of the identified and true initial condition.\n\n\\begin{figure}\n\t\\includegraphics[scale=0.7]{figures/solKS_T1_nstep100_nx1024_yd.png}\n\t\\caption{Target state (KS solution with correct initial condition).}\n\t\\label{fig:yd}\n\\end{figure}\n\n\\begin{figure}\n\t\\includegraphics[width=0.5\\textwidth]{figures/gradientKS_T1_nstep100_nx1024_u0_075uexact_progress.pdf}\n\t\\includegraphics[width=0.5\\textwidth]{figures/objKS_T1_nstep100_nx1024_u0_075uexact_progress.pdf}\n\t\\caption{Optimization progress. Left: norm reduced gradient. Right: Target mismatch.}\n\t\\label{fig:optprogress}\n\\end{figure}\n\n\n\\begin{figure}\n\t\\includegraphics[width=0.5\\textwidth]{figures/ctrlKS_T1_nstep100_nx1024_u0_075uexact_progress.png}\n\t\\includegraphics[width=0.5\\textwidth]{figures/ctrlKS_T1_nstep100_nx1024_u0_075uexact_diff_final.png}\n\t\\caption{Left: Initial and final control. Right: difference of final to exact control.}\n\t\t\\label{fig:ctrl}\n\\end{figure}\n\n\\bibliographystyle{plain}\n\\bibliography{references}\n\n\\end{document}\n", "meta": {"hexsha": "1758b8035e10fef7e0f3e9d8aa629a74ad0fe048", "size": 17002, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Tutorials/EX5_KS_control/doc/notes.tex", "max_stars_repo_name": "wavefunction91/LibPFASST", "max_stars_repo_head_hexsha": "8bf49000d4e613496e824bb98f368527044f7064", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-05-22T11:02:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T16:16:33.000Z", "max_issues_repo_path": "Tutorials/EX5_KS_control/doc/notes.tex", "max_issues_repo_name": "wavefunction91/LibPFASST", "max_issues_repo_head_hexsha": "8bf49000d4e613496e824bb98f368527044f7064", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-01-18T01:46:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-29T16:32:52.000Z", "max_forks_repo_path": "Tutorials/EX5_KS_control/doc/notes.tex", "max_forks_repo_name": "wavefunction91/LibPFASST", "max_forks_repo_head_hexsha": "8bf49000d4e613496e824bb98f368527044f7064", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-02-09T09:38:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-25T23:00:05.000Z", "avg_line_length": 50.4510385757, "max_line_length": 609, "alphanum_fraction": 0.7656746265, "num_tokens": 4865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.333183235354062}}
{"text": "\\section{Evolution of Trust}\n  \\subimport{thesis/definitions/}{turns.tex}\n  \\subimport{common/}{turnexample.tex}\n  We use $prev\\left(j\\right)$ and $next\\left(j\\right)$ to denote the previous and next turn respectively played by\n  $Player(j)$. A formal definition can be found in the Appendix.\n  \\subimport{common/definitions/}{damage.tex}\n  \\subimport{common/definitions/}{history.tex}\n  \\noindent Knowledge of the initial graph $\\mathcal{G}_0$, all players' initial capital and the history amount to full\n  comprehension of the evolution of the game. Building on the example of Fig.~\\ref{fig:utxo}, we can see the resulting graph\n  when $D$ plays\n  \\begin{equation}\n  \\label{turnexample}\n    Turn_1 = \\{Steal\\left(1, A\\right), Add\\left(4, C\\right), Add\\left(-1, B\\right)\\} \\enspace.\n  \\end{equation}\n  \\subimport{common/figures/}{turnexample.tikz}\n\n  \\noindent In the form presented here, Trust Is Risk is controlled by an environment that chooses a player, receives the turn\n  that this player wishes to play and, if this turn is valid, executes it. These steps are repeated indefinitely. We assume\n  players are chosen in a way that, after her turn, a player will eventually play again later.\n  \\subimport{thesis/algorithms/}{trustisriskgame.tex}\n\n  \\noindent \\texttt{strategy[}$A$\\texttt{]()} provides player $A$ with full knowledge of the game, except for the capitals of\n  other players. This assumption may not be realistic because out of band knowledge and traffic analysis methods can be used\n  to infer the capital of other players.\n\n  \\texttt{executeTurn()} checks the validity of \\texttt{Turn} and substitutes it with an empty turn if invalid.\n  Subsequently, it creates the new graph $\\mathcal{G}_j$ and updates the history accordingly. For the routine code,\n  see the Appendix.\n", "meta": {"hexsha": "66a9d9e1bb1a21b15f25b8116be0790494907516", "size": 1792, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/evolution.tex", "max_stars_repo_name": "dionyziz/DecentralizedTrust", "max_stars_repo_head_hexsha": "60f65bff00041e7e940491913bd4ca3f11bf22d9", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2017-03-15T14:33:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-01T14:07:45.000Z", "max_issues_repo_path": "thesis/evolution.tex", "max_issues_repo_name": "dionyziz/DecentralizedTrust", "max_issues_repo_head_hexsha": "60f65bff00041e7e940491913bd4ca3f11bf22d9", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2017-03-07T12:25:26.000Z", "max_issues_repo_issues_event_max_datetime": "2017-07-31T14:42:20.000Z", "max_forks_repo_path": "thesis/evolution.tex", "max_forks_repo_name": "dionyziz/DecentralizedTrust", "max_forks_repo_head_hexsha": "60f65bff00041e7e940491913bd4ca3f11bf22d9", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-03-07T10:49:58.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-28T06:32:33.000Z", "avg_line_length": 61.7931034483, "max_line_length": 126, "alphanum_fraction": 0.7544642857, "num_tokens": 475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.333183235354062}}
{"text": "%!TEX root = ../Thesis.tex\n\\chapter{Introduction}\\label{cha:introduction}\n%\nHere's a citation: \\cite{Wacker2016}. Two pictures are shown, Figures \\ref{fig:morten} and \\ref{fig:eps}. There's also a table: Table \\ref{tab:a-table}.\n\n\\section{A Section}\\label{sec:a-section}\n\n\\subsection{A Subsection}\\label{ssec:a-subsection}\n\n\\subsubsection{A Subsubsection}\\label{sssec:a-subsubsection}\n\n\\lipsum[2]\n\n\\begin{figure}[htbp]\n  \\centering\n  \\includegraphics[width=.3\\textwidth]{img/morten}\n  \\caption{Some dude}\n  \\label{fig:morten}\n\\end{figure}\n\n\\begin{figure}[htbp]\n  \\centering\n  \\includegraphics[width=.7\\textwidth]{img/time-constant}\n  \\caption{An eps image}\n  \\label{fig:eps}\n\\end{figure}\n\n\\begin{table}[htbp]\n  \\centering\n  \\caption{A table}\n  \\begin{tabular}{cc}\n    \\toprule\n    Something & Something else \\\\\n    \\midrule\n    A & a \\\\\n    B & b \\\\\n    \\bottomrule\n  \\end{tabular}\n  \\label{tab:a-table}\n\\end{table}\n\n\\begin{equation*}\n  \\begin{aligned}\n      & \\underset{\\*x, \\*u}{\\text{min}}\n      & & \\int_{t_k}^{t_{k+T}} ( \\*{e}(\\*{x})^{\\top} \\*{Q}_p \\*{e}(\\*{x}) +\n      \\dot{\\*{e}}(\\*{x})^{\\top} \\*{Q}_d \\dot{\\*{e}}(\\*{x}) +\n      \\ddot{\\*{q}}^{\\top} \\*{R}_{\\ddot{\\*{q}}} \\ddot{\\*{q}} +\n      \\*{u}^{\\top} \\*{R}_{\\*{u}} \\*{u} ) \\,dt\\\\\n      & \\text{s.t.}\n      & & \\dot{\\*x} = \\*f(\\*x,\\*u), \\\\\n      &&& \\bar{\\*x}_{lb} \\leq \\*x \\leq \\bar{\\*x}_{ub}, \\\\\n      &&& \\bar{\\*u}_{lb} \\leq \\*u \\leq \\bar{\\*u}_{ub}, \\\\\n      &&& \\bar{\\ddot{\\*q}}_{lb} \\leq \\ddot{\\*q} \\leq \\bar{\\ddot{\\*q}}_{ub}, \\\\\n      &&& \\*x(t_k) = \\*x_0. \\\\\n      \\end{aligned}\n\\end{equation*}\n\n\\begin{equation*}\n  f(x,u) = \\begin{bmatrix} \\dot{q} \\\\ M(q)^{-1} (\\tau - C(q, \\dot{q}) - G(q)) \\end{bmatrix}\n\\end{equation*}\n\n\\begin{equation*}\n  p(\\*y | \\*X, \\boldsymbol{\\theta}) = \\dots\n\\end{equation*}", "meta": {"hexsha": "4bb03fe2d95d8b8fa136df3e795760eb3b6e6c52", "size": 1766, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/1-introduction.tex", "max_stars_repo_name": "martiabr/ntnu-itk-thesis-template", "max_stars_repo_head_hexsha": "8eb0e2994de872af0f7a6e48042233bb84bf7fa9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tex/1-introduction.tex", "max_issues_repo_name": "martiabr/ntnu-itk-thesis-template", "max_issues_repo_head_hexsha": "8eb0e2994de872af0f7a6e48042233bb84bf7fa9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/1-introduction.tex", "max_forks_repo_name": "martiabr/ntnu-itk-thesis-template", "max_forks_repo_head_hexsha": "8eb0e2994de872af0f7a6e48042233bb84bf7fa9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.59375, "max_line_length": 152, "alphanum_fraction": 0.5509626274, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.333183235354062}}
{"text": "\n\\chapter{Motivation}\n\\label{cha:motivation}\nIn this chapter, we describe the motivations behind adding copatterns to\nIdris. We find that copatterns can be a means of recovering from an unfortunate\nloss of subject reduction. However, copatterns might not be the universal tool\nfor coinductive reasoning. Additionally, we motivate the addition of an\ninference system for guarded recursion.\n\n\\section{Recovering Subject Reduction}\n\\label{sec:recov-subj-reduct}\n%#########\n% Hvorfor mistes subject reduction ved dependent pattern matching på codata?\n% Mister Idris subject reduction?\n% Modeksempel (helst implementeret i Idris)\n% Hvordan afhjælper copatterns problemet?\n\n% Ny viden: Copatterns kan være et værktøj til at undgå at man mister subject reduction\n%#########\nSubject reduction is a property of a type system. Also called type preservation,\na type system has the property of subject reduction if evaluation of a\nwell-typed term does not cause its type to change\\,\\citep[Section~8.3.3]{Pierce:2002:TPL:509043}.\nIn some dependently typed programming languages with explicit coinductive types,\ne.g. Coq and Idris, values of such types are given as (potentially) infinite\ntrees of constructors. Accordingly, they can be analysed with (dependent)\npattern matching. However, this leads to a loss of subject reduction. The\nproblem was first identified by Gim\\'{e}nez\\,\\citep{Gimenez96uncalcul} for the\nCalculus of (Co)Inductive constructions, but was later (in 2008) shown by Oury\nto persist in both Coq and\nAgda\\,\\citep{OuryCounterexampleCoq,OuryCounterexampleAgda}.\n\nBy implementing Oury's counterexample\n(Figure~\\ref{fig:ourys_counterexample_idris}), we have found that the problem\narises in Idris as well. Oury's counterexample unfolds as follows: Given a\ncoinductive type \\texttt{A} with a single constructor \\texttt{A} $\\to$ \\texttt{A}, which we may call\n\\texttt{In}, and an inhabitant \\texttt{b} of \\texttt{A} (of which there exists only one,\nnamely the fixed point of \\texttt{In}), we can show that \\texttt{b} is definitionally\nequal to its own unfolding by exploiting dependent pattern matching. When\n\\texttt{b} is given as argument to \\texttt{forceEq} in\nFigure~\\ref{fig:ourys_counterexample_idris}, \\texttt{b} is reduced to \\texttt{In\n  (Delay (In (Delay a)))} by dependent pattern matching, such that \\texttt{forceEq b}\nreduces to \\texttt{Refl}. These reductions ensure that the implementation of\n\\texttt{p} is well-typed. The problem arises when we attempt to replace the\nright-hand side of \\texttt{p} with \\texttt{Refl}, which is the definition of\n\\texttt{forceEq b}. In this case, the Idris type checker rejects the program,\ncomplaining that \\texttt{b} cannot be unified with \\texttt{In b}. Thus, the\nevaluation of \\texttt{forceEq b} changes the type of \\texttt{Refl}, and subject\nreduction is lost.\n\n\\begin{figure}\n\\begin{lstlisting}[mathescape]\ncodata A : Type where\n  In : A $\\to$ A\n\nb : A\nb = In b\n\nforce : A $\\to$ A\nforce (In (Delay (In (Delay a)))) = In (Delay (In (Delay a)))\n\nforceEq : (x : A) $\\to$ x = force x\nforceEq (In (Delay (In (Delay a)))) = Refl\n\np : b = In (In b)\np = forceEq b\n\\end{lstlisting}\n  \\caption{Oury's counterexample implemented in Idris, leading to a loss of\n    subject reduction.}\n\\label{fig:ourys_counterexample_idris}\n\\end{figure}\n\nDependent pattern matching on coinductive data is problematic, but we cannot\nsimply disallow it, since we then lose the ability to write any interesting\nprograms involving coinductive data. This ability can be regained by introducing\ncopatterns. Instead of analysing coinductive data with dependent pattern\nmatching, we can choose to synthesize it using copatterns. In\nFigure~\\ref{fig:ourys_counterexample_copatterns}, we have translated Oury's\ncounterexample to an Idris implementation with copatterns, where we have\nrefrained from using dependent pattern matching. Using copatterns, we can still\ndefine both \\texttt{b} and \\texttt{force}, but we cannot provide an\nimplementation for \\texttt{p}, since the reduction behaviour from dependent\npattern matching is (virtually) unavailable. Hence, we have both regained\nexpressiveness and avoided this particular loss of subject reduction.\n\n\\begin{figure}[h]\n\\begin{lstlisting}[mathescape]\ncorecord A : Type where\n  out : A $\\to$ A\n\nb : A\n&out b = b\n\nforce : A $\\to$ A\n&out force a = out a\n&out &out force a = out (out a)\n\nforceEq : (x : A) $\\to$ x = force x\nforceEq a = $\\uwave{\\text{Refl}}$\n\np : b = out (out b)\np = $\\uwave{\\text{forceEq b}}$\n\\end{lstlisting}\n  \\caption{By using copatterns to synthesize coinductive data, we can both\n    implement functions on coinductive data and preserve subject\n    reduction. The underlined right-hand sides indicate type errors detected by\n    the Idris type checker.}\n\\label{fig:ourys_counterexample_copatterns}\n\\end{figure}\n\nIn Agda, pattern matching on coinductive data is currently\ndisallowed\\,\\citep{Danielsson09}, providing the user with copatterns instead. By\nimplementing copatterns in Idris, we provide a stepping stone in the same\ndirection. However, this solution may seem to avoid the problem, rather than\nsolving it. As pointed out by McBride\\,\\citep{McBride:2009}, the underlying\nproblem is that we can have intensional equalities between coinductive values\nwhich are merely bisimilar. To remedy the situation, he proposes that one could\nhave an observational propositional equality, which takes into account both\nfunctional extensionality and bisimilarity for coinductive values. Also,\nAltenkirch et al.\\,\\citep{Altenkirch:2007} proposes the adoption of an\nobservational type theory, which is essentially an intensional type theory where\none can have propsitional equalities up to observation, as opposed to\nconstruction. But until these ideas are incorporated into a practical system,\navoiding the problem seems superior to ignoring it.\n\n\n\\section{The Use Case for Copatterns}\n\\label{sec:motivation_copatterns}\n%############\n% Pattern matching on data with top-level product structure vs. copatterns\n% Mixed induction-coinduction, coinductive resumption monad\n% Coinduction (definition og operationel intuition) (måske bisimilarity)\n\n% Ny viden: Hvornår bør/kan jeg bruge copatterns?\n%############\n% Pattern matching has become a ubiquitous tool for analysing data in functional\n% programming languages. In combination with inductive data types, pattern\n% matching has evolved into such a widely applicable technique that many users may\n\n% be willing to disregard its drawbacks. Consider the following implementation of\n% a function which interleaves a filtered version of \\texttt{xs} with \\texttt{ys}:\n% \\begin{lstlisting}[mathescape]\n% interleaveFilter : (a $\\to$ Bool) $\\to$ Stream a $\\to$ Stream a $\\to$ Stream a\n% interleaveFilter p (x :: xs) (y :: ys) = \n% if p (head xs) then case xs of \n%                      xx :: xxs \n%    case (filter p xs) of\n%      px :: _ => (px :: y :: (interleaveFilter p xs ys)\n% \\end{lstlisting}\n% \\begin{lstlisting}[mathescape]\n% interleaveFilter : (a $\\to$ Bool) $\\to$ Stream a $\\to$ Stream a $\\to$ Stream a\n% head       (interleaveFilter p xs ys)  = head (filter p xs)\n% head (tail (interleaveFilter p xs ys)) = head ys\n% tail (tail (interleaveFilter p xs ys)) = \n%                                interleaveFilter p (tail xs) (tail ys)\n\n% mapNth : (a -> b) -> Nat -> Nat -> Stream a -> Stream b\n% mapNth f (S n') m s = case s of\n%                        x :: xs => x :: mapNth f n' xs\n% mapNth f Z m s = case s of\n%                   x :: xs => f x :: mapNth f m m xs\n\n% \\end{lstlisting}\n\n%\\subsection{Copatterns are Useful for Record Types}\n% Recursive types!\n\\label{sec:prod-vs.-copr}\nIf we must disallow pattern matching on coinductive data to preserve subject\nreduction, how much expressiveness can we recover by using copatterns? At\npresent, not as much as one might have hoped. Copatterns are well-suited for\nworking with data that has a top-level product structure. In the general sense\nof recursive types, this means that copatterns can be readily used for types\nwhich has a product-of-sums structure, i.e.\n${\\mu X.\\,A\\times B\\times\\cdots\\times X}$ or\n${\\nu X.\\,A\\times B\\times\\cdots\\times X}$, since a well-defined projection\nexists for each $A,\\,B,\\,\\cdots,\\,X$. In Idris, this amounts exactly to the\ntypes which can be defined as (co)inductive record types. Consider the\ndeterministic finite automaton defined in Figure~\\ref{fig:state_machine}, which\naccepts strings of binary numbers that contain an even number of zeros (a\ngraphical representation is given for reference in\nFigure~\\ref{fig:state_machine_graphical}). Inspired by\nJacobs\\,\\citep{JacobsCoalgebra}, we define a state as a type\n${\\mu S. (A\\,\\to\\,S)\\times Bool}$, where $A\\,\\to\\,S$ is the transition function\n(defined for each state) and $Bool$ indicates whether the state is a final\n(i.e. accepting) state. Consequently, we can define each state (\\texttt{SA} and\n\\texttt{SB} in Figure~\\ref{fig:state_machine}) quite elegantly using copatterns.\n\n\\begin{figure}[h]\n\\begin{lstlisting}[mathescape]\ndata Binary = Zero | One\n\nrecord State a where\n  transitions : a $\\to$ State a \n  isFinal     : Bool\n\nmutual  \n  SA : State Binary\n  &transitions SA = ts\n   where\n     ts : Binary $\\to$ State Binary\n     ts Zero = SB\n     ts One  = SA\n  &isFinal     SA = True \n  \n  SB : State Binary\n  &transitions SB = ts\n   where\n     ts : Binary $\\to$ State Binary\n     ts Zero = SA \n     ts One  = SB\n  &isFinal     SB = False\n\nisAccepted : List Binary $\\to$ Bool\nisAccepted = isAccepted$'$ SA\n  where\n   isAccepted$'$ : State Binary $\\to$ List Binary $\\to$ Bool\n   isAccepted$'$ s []        = isFinal s\n   isAccepted$'$ s (b :: bs) = isAccepted$'$ ((transitions s) b) bs\n\\end{lstlisting}\n  \\caption{A finite state machine implemented using copatterns, identifying\n    binary strings which contain an even amount of zeros.}\n\\label{fig:state_machine}\n\\end{figure}\n\n\\begin{figure}[h]\n\\centering\n\\includegraphics{figures/dfa}\n\\caption{A graphical representation of the automation defined in\n  Figure~\\ref{fig:state_machine}.}\n\\label{fig:state_machine_graphical}\n\\end{figure}\n\nUnfortunately, copatterns are not very well-suited for types that have a top-level\nsum-of-products structure, i.e. ${\\mu X.\\,A + B + \\cdots + X}$ and\n${\\nu X.\\,A + B + \\cdots + X}$, because values of such types can take on\ndifferent forms in different contexts. In other words, the observable behaviour\ndepends on a further analysis, and the projections must therefore make\nsuch an analysis possible. Consider the possibly infinite list encoded in\nFigure~\\ref{fig:colist}. Here, it is not possible to have a projection that\naccesses the first element of a \\texttt{CoList} directly, since it may be\nempty. Instead, we can access an unfolding of the list, which may give either\nanswer.\n\n\\begin{figure}[h]\n\\begin{lstlisting}[mathescape]\ncorecord CoList a where\n  unfold : Either (a, CoList a) ()\n\nmap : (a $\\to$ b) $\\to$ CoList a $\\to$ CoList b \n&unfold map f xs = case (unfold xs) of\n                      Left (x, xs) => Left (f x, map f xs)\n                      Right () => Right ()\n\\end{lstlisting}\n  \\caption{A possibly infinite list type and a \\texttt{map} function operating on it.}\n  \\label{fig:colist}\n\\end{figure}\n\nThe inherent uncertainty or ambiguity in types with sums-of-product structure\ncannot be elegantly handled with copatterns. We can try to eliminate the need\nfor further analysis by tagging all values with an indicator of its state, as\nshown with the modified CoList in Figure~\\ref{fig:dependent_colist}. However, as\nsoon as the value of the tag is given indirectly, e.g. by reference to other values,\nthe type checker may become unable to reduce the tag to a canonical form, thereby\ndefeating its purpose.\n\n\\begin{figure}[h]\n\\begin{lstlisting}[mathescape]\ncorecord CoList a where\n  isNil : Bool\n  elem  : if isNil then () else (a, CoList a)\n\nnil : CoList a\n&isNil nil = True\n&elem  nil = ()\n\ncons : a $\\to$ CoList a $\\to$ CoList a\n&isNil cons x xs = False\n&elem  cons x xs = (x, xs)\n\ntoggle : Nat $\\to$ Nat $\\to$ CoList Nat\n&isNil toggle n m = False\n&elem toggle n m = (n, (cons m (toggle m n)))\n\\end{lstlisting}\n\\caption{A version of CoList defined with a boolean tag indicating whether\n  additional elements of the list are available.}\n\\label{fig:dependent_colist}\n\\end{figure}\n\nSince many useful techniques involve coinductive types which do not have a\nstraightforward product-of-sums structure, e.g. coinductive\nresumptions\\,\\citep{Pirog2014273} and mixed\ninduction-coinduction\\,\\citep{Danielsson09mixinginduction}, \\texttt{co}patterns\nare therefore not necessarily a valuable tool for defining all kinds of\n\\texttt{co}inductive data. Instead, they provide elegant definitions when your data can be\nclearly defined by its external properties, rather than by its internal\nstructure. Hence, we find copatterns at this stage to be universally \\emph{applicable}, but not\nuniversally \\emph{useful}.\n\n\n\\section{Less Restrictive Productivity Checking} \n\\label{sec:less-restr-prod}\n% Hvorfor vil vi inferere guarded recursion?\n%###########\n% Dette afsnit har i princippet intet at gøre med copatterns!\n% Referer til baggrund om syntactic guardedness\n% Hvad kan guarded recursion som syntactic guardedness?\n% Hvorfor er guarded recursion frygteligt at skrive / ikke brugervenligt?\n% Bedre end syntactic guardedness + Bruger vil ikke skrive det => Inferer det\n\n\n% Ny viden: Hvorfor vil vi gerne inferere guarded recursion?\n%###########\nBecause the current productivity checker in Idris uses the syntactic\nguardedness principle to prove productivity, users writing programs on\ncoinductive types must place all recursive calls directly under a call to a\ncoinductive constructor. This limitation means that we cannot have simple\ndefinitions such as \\texttt{toggle} from Figure~\\ref{fig:dependent_colist}\nproven total by the compiler. Using the technique of guarded recursion presented\nin Section~\\ref{sec:guarded-recursion} we are able to prove that toggle is\ntotal, as shown in Figure~\\ref{fig:toggle_guarded_recursion}. The proof is quite\ninvolved, as it also requires us to define guarded recursive versions of\n\\texttt{cons} and \\texttt{CoList} on which the original definition of\n\\texttt{toggle} depends. The coinductive \\texttt{CoList} must be amended such\nthat the recursive reference in the \\texttt{elem} projection is not be\nimmediately available.\n\n\\begin{figure}[h]\n\\begin{lstlisting}[mathescape]\ncorecord $_g$CoList a where\n  isNil : Bool\n  elem  : if isNil then () else (a, $\\laterkappa$(CoList a))\n  constructor CoCons\n\ncons : $\\forall\\kappa.$ a $\\to$ $_g$CoList a $\\to$ $_g$CoList a\ncons = $\\Lambda\\kappa$. fix$^\\kappa$($\\lambda$rec.$\\lambda$x.$\\lambda$xs. CoCons$\\ $False (x, (Next xs)))\n\ntoggle$'$ : $\\laterkappa$(Nat $\\to$ Nat $\\to$ Stream) $\\to$ Nat $\\to$ Nat $\\to$ $_g$CoList Nat\ntoggle$'$ rec n m = CoCons False (n, (cons m ((rec $\\tensor$ m) $\\tensor$ n))) \n\ntoggle : $\\forall\\kappa.$ Nat $\\to$ Nat $\\to$ $_g$CoList Nat\ntoggle = $\\Lambda\\kappa.$ fix$^\\kappa$($\\lambda$rec.$\\lambda$n.$\\lambda$m. toggle$'$ rec n m)\n\\end{lstlisting}\n  \\caption{An implementation of \\texttt{toggle} from\n    Figure~\\ref{fig:dependent_colist} using guarded recursion, given in\n    Idris-like syntax.}\n\\label{fig:toggle_guarded_recursion}\n\\end{figure}\n\nAlthough guarded recursion widens the range of programs we can prove total as\ncompared to syntactic guardedness, requiring the user to write guarded recursive\nprograms is probably not feasible due to their complexity. Even disregarding\nthis complexity, building such programs quickly becomes an onerous\ntask. Consequently, we would like to have a system which can automatically build\nguarded recursive versions of at least some user-written programs, lifting the burden of\nbuilding productivity proofs by guarded recursion from the user and onto the\ncompiler. The structure and implementation of such a system will be the subject\nof Chapter~\\ref{cha:infer-guard-recurs}.\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: \"../copatterns-thesis\"\n%%% End:\n", "meta": {"hexsha": "f2cd70e7cd2cc9c80b4a682bd44fd03a6b92c10a", "size": 15975, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "sections/motivation.tex", "max_stars_repo_name": "sualitu/thesis", "max_stars_repo_head_hexsha": "22d2cb4f21dc7c2dab011da5bb560c003650a2bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sections/motivation.tex", "max_issues_repo_name": "sualitu/thesis", "max_issues_repo_head_hexsha": "22d2cb4f21dc7c2dab011da5bb560c003650a2bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sections/motivation.tex", "max_forks_repo_name": "sualitu/thesis", "max_forks_repo_head_hexsha": "22d2cb4f21dc7c2dab011da5bb560c003650a2bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.1298342541, "max_line_length": 105, "alphanum_fraction": 0.7447887324, "num_tokens": 4388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.333183235354062}}
{"text": "\n\\section{Feature Evaluation}\n\nSuccessful classification largely depends on the predictive value of the features. We, therefore, evaluate for the features whether they will be useful in the discrimination between the formal and informal classes. The evaluation requires the satellite image to be divided into the formal and informal classes. This division is represented using a ground truth, which is a mask covering the satellite image the location and shape of the slums. The mask is used to divide each block of pixels into the two classes: either formal or informal. Each block contains a vector of features, characterizing that particular block of pixels. All blocks of the same class will be grouped, allowing for the analysis of the distribution values of the two classes. If the distribution of the values of a particular feature varies substantially between the two classes, it should be a suitable candidate for classification.\n\nThe ground truth mask is constructed using a vector file containing the boundaries of informal areas. The boundary file is rasterized and applied on top of the satellite image, creating a mask of the location of the informal areas. Because the feature calculation is performed on blocks instead of pixels, we transform the pixel based mask into a block-based mask where every pixel represents a block of pixels in the original image. In the mask, the pixels with the value zero represent blocks in the image designated as formal while ones represent blocks of slums.\n\nWe visualize the predictive value of the features using a boxplot and a kernel density estimation plot. When a feature is distinctive, the distribution of the values in the two classes will be different, thus creating a visual difference in both plots. We attempted to use KL divergence as an objective measurement as an alternative for the visually inclined box plot and kernel density estimation. However, we were not able to extract reasonable KL divergence values from our data as for many outcomes would indicate a divergence of infinite value. We will therefore visually evaluate the differences between the formal and informal value distributions in the two types of plots.\n\nThe features will be calculated for all combinations of image sections, color bands, block sizes, and scales, resulting in large amounts of data of which only a selection is shown in the following sections. For HoG, LSR and RID the features are extracted from the three sections presented in Figure\n\\ref{fig:sections} for all three color bands. We analyze the impact of the block size and scale parameters by using the block sizes 20, 40, and 60 in combination with the scales 50, 100, and150. The individual\nimpact of each of the two parameters is evaluated using a comparison between the baseline and the increased parameter, for example, a comparison between the results obtained from a block size of 20 compared to a block size of 60, with all other parameters constant. The evaluation is on the assumption that all parameters are independent.\n\nBecause every combination of image section, block size and scale will have three different results due to the RGB color bands, we refrain from visualizing all bands and pick the first band, which is red. The results seem to vary slightly between the red, green, and blue band, although it is not significant. Furthermore, we will select the most expressive feature for each extraction method to reduce the complexity of the visualization.\n\n\\subsection{Histogram of Oriented Gradients}\n\n\\begin{figure}\n\t\\centering\n\t\\begin{tabular}{cc}\n\t\t\\subfloat{\\includegraphics[width=7cm]{images/HoG/inc_bk/section_1_boxplot_hog_BK20_SC100_F2}}&\n\t\t\\subfloat{\\includegraphics[width=7cm]{images/HoG/inc_bk/section_1_boxplot_hog_BK60_SC100_F2}}\\\\ \n\t\t\\subfloat{\\includegraphics[width=7cm]{images/HoG/inc_bk/section_1_kde_hog_BK20_SC100_F2}}&\n\t\t\\subfloat{\\includegraphics[width=7cm]{images/HoG/inc_bk/section_1_kde_hog_BK60_SC100_F2}}\n\t\\end{tabular}\n\t\\caption{The effect of increased block size on the HoG features. From left to\n\t\tright: a block size of 20 and 60 respectively.}\n\t\\label{hog_inc_bk}\n\\end{figure}\n\nFor the Histogram of Oriented Gradients, the third feature is selected for visualization in this section, which is the variance. Figure \\ref{hog_inc_bk} shows the effect of increased block size on the distribution of values in both classes. This example uses a constant scale of 100 pixels and a variable block size of 20 and 60 pixels. It seems that the block size, in this case, does not influence both distributions significantly. As a result, an increase in the size of a block within the tested range should have little to no influence on the predictive value of the feature.\n\n\\begin{figure}\n\t\\centering\n\t\\begin{tabular}{cc}\n\t\t\\subfloat{\\includegraphics[width=7cm]{images/HoG/inc_sc/section_1_boxplot_hog_BK20_SC50_F2}}&\n\t\t\\subfloat{\\includegraphics[width=7cm]{images/HoG/inc_sc/section_1_boxplot_hog_BK20_SC150_F2}}\\\\\n\t\t\\subfloat{\\includegraphics[width=7cm]{images/HoG/inc_sc/section_1_kde_hog_BK20_SC50_F2}}&\n\t\t\\subfloat{\\includegraphics[width=7cm]{images/HoG/inc_sc/section_1_kde_hog_BK20_SC150_F2}}\\\\\n\t\\end{tabular}\n\t\\caption{The effect of increased scale on the HoG features. From left to\n\t\tright: a scale of 50 and 150 respectively}\n\t\\label{hog_inc_sc}\n\\end{figure}\n\nFigure \\ref{hog_inc_sc} illustrates the effect of increased scale on a constant block size. It seems to indicate that an increased scale leads to increased separation of the two distribution, thus increasing the predictive value of the feature. Scales larger than 150 do not seem to improve the performance; in contrast, the performance seems to decrease with scales larger than 150. In the paper of Graesser \\textit{et al.} combined multiple scales to improve the detection of informal settlements. We will experiment with multiple scales and scale combinations in the results section.\n\n\\subsection{Line Support Region}\n\nThe Line Support Region feature visualized is the line mean entropy, which appeared to be the most expressive of the features. Furthermore, we showed the results from the first section because it produced the most distinct results from the three sections. The individual performances of the different sections will be evaluated in the results section. Similar to the analysis of HoG, the increase of the block size does not seem to influence the distribution of the two classes. The observed difference is as negligible as the comparison of the HoG in Figure \\ref{hog_inc_bk}\n\n\\begin{figure}\n\t\\centering\n\t\\begin{tabular}{cc}\n\t\t\\subfloat{\\includegraphics[width=7cm]{images/LSR/inc_sc/section_1_boxplot_lsr_BK20_SC50_F1}}&\n\t\t\\subfloat{\\includegraphics[width=7cm]{images/LSR/inc_sc/section_1_boxplot_lsr_BK20_SC150_F1}}\\\\\n\t\t\\subfloat{\\includegraphics[width=7cm]{images/LSR/inc_sc/section_1_kde_lsr_BK20_SC50_F1}}&\n\t\t\\subfloat{\\includegraphics[width=7cm]{images/LSR/inc_sc/section_1_kde_lsr_BK20_SC150_F1}}\n\t\\end{tabular}\n\t\\caption{The effect of increased scale on the second SLR feature. From left to\n\t\tright: a scale of 50 and 150 respectively.}\n\t\\label{lsr_inc_sc}\n\\end{figure}\n\nThe distributions for different scales of the LSR feature is visualized in Figure \\ref{lsr_inc_sc}. Similar to the features from the Histogram of Oriented Gradients, it appears that an increase in scale seems to increase the difference between the distributions of the formal and informal classes, even though this is not as clear in the other two sections, it seems to indicate that increased scale might improve performance\n\n\n\\subsection{Road Intersection Density}\n\n\\begin{figure}\n\t\\centering\n\t\\begin{tabular}{ccc}\n\t\t\\subfloat{\\includegraphics[height=3.8cm]{images/RID/1}}&\n\t\t\\subfloat{\\includegraphics[height=3.8cm]{images/RID/2}}&\n\t\t\\subfloat{\\includegraphics[height=3.8cm]{images/RID/3}}\\\\\n\t\t\\subfloat{\\includegraphics[height=3.8cm]{images/RID/4}}&\n\t\t\\subfloat{\\includegraphics[height=3.8cm]{images/RID/5}}&\n\t\t\\subfloat{\\includegraphics[height=3.8cm]{images/RID/6}}\\\\\n\t\\end{tabular}\n\t\\caption{The distribution of values for the Road Intersection Density feature. Top: Scale 150; Bottom: Scale 50}\n\t\\label{rid}\n\\end{figure}\n\n\nThe Road Intersection Density method generates a single feature produced by the Getis and Ord local G function. We have evaluated different block sizes and scales for RID although, in this case, the meaning of the scale and block size is slightly different than with HoG and LSR. In the calculation of the G function, we rasterize the locations of the intersection onto a grid, where the size of the blocks in the grid is the block size. The blocks in the grid contain a counter of the number of intersections that fell within that block. The G function is calculated over this grid where the scale is the neighborhood around a block, in the same manner as the HoG and LSR feature although the shape is a circle instead of a square.\n\nFigure \\ref{rid} shows the differences in distribution for the RID feature for scales 150 and 50. The low scale seems to create artifacts and does not have a distinctly different distribution. The higher scale, on the other hand, seems to have a difference, although not quite significant. Using RID together with the other two sections results in performance that is similar to the bottom right image in the figure. In the evaluation of RID, we have only used the parameters that worked well with the first section and applied this to the second and third section; this is likely cause for the low performance in the other sections. We would have to use three different sets of parameters to increase performance for the other two sections. It is clear that this approach does not seems scalable to large images where there is a significant variance in the types of roads.\n\n\\subsection{Conclusion}\n\nWith the right parameters, there is a clear distinction between the two classes for both the HoG and LSR features. RID, in contrast, does not seem to have a clear distinction, likely caused by a lack of specific parameters for section 2 and 3. For HoG and LSR, it seems that an increase in scale improves the distinctness of the two classes, although the increased scale is computationally expensive. On the three sections, the time to compute features at a high scale is measured in hours rather than minutes. Using features with high scales on large images is, therefore, discouraged. Besides, increasing the scale seems to give diminishing returns while taking significantly more time to compute. We use 150 as the maximum scale in the classification experiments to reduce the time needed to compute the features.\nFor HoG and LSR, the block size did not seem to improve or decrease performance. As a result, we would get the same performance with large block sizes as small block sizes using less computation. For now, the block size remains 20 pixels as the paper by Graesser \\textit{et al.} describes. We will test our hypothesis on the effect of block size and scale during the classification experiments in the results section.\n\n\n", "meta": {"hexsha": "0d31de61a5ff64bffcd1e98f27790c4afebd9af5", "size": 11011, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/evaluation.tex", "max_stars_repo_name": "DerkBarten/SlumDetection", "max_stars_repo_head_hexsha": "8ae38623454dc3467333f07571401073d9c40616", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thesis/evaluation.tex", "max_issues_repo_name": "DerkBarten/SlumDetection", "max_issues_repo_head_hexsha": "8ae38623454dc3467333f07571401073d9c40616", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis/evaluation.tex", "max_forks_repo_name": "DerkBarten/SlumDetection", "max_forks_repo_head_hexsha": "8ae38623454dc3467333f07571401073d9c40616", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 115.9052631579, "max_line_length": 907, "alphanum_fraction": 0.8061029879, "num_tokens": 2551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.33318323535406197}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\marginpar{Wednesday\\\\ 2020-12-2, \\\\ compiled \\\\ \\today}\n\nWe will consider another kind of baryogenesis mechanism, connected to the reheating phase. \n\nThe baryon asymmetry generated by the out-of-equilibrium decays of \\(X\\) particles is of the order of \n%\n\\begin{align}\nB \\approx \\frac{\\epsilon}{g_*}\n\\,,\n\\end{align}\n%\nwhere \\(g_* \\approx \\num{e2}\\) for the SM, or even \\(g_* \\approx \\num{e3}\\) BTSM.\n\nA possible approach is to identify the \\(X\\) particle as the inflaton \\(\\varphi \\). \n\nWe will use the usual notations: \\(n_X\\), \\(n_B\\), and \\(\\epsilon \\) for the amount of \\(CP\\) violation.\nThe Boltzmann equation reads \n%\n\\begin{align}\n\\dot{n}_X + 3H n_X = - \\Gamma _X n_X\n\\,,\n\\end{align}\n%\nwhich is equivalent to \n%\n\\begin{align}\n\\dot{\\rho}_\\varphi + 3 H \\rho _\\varphi = - \\Gamma _\\varphi \\rho _\\varphi \n\\,,\n\\end{align}\n%\nwith the identification \\(\\rho _\\varphi = m_X n_X\\), where \\(m_X\\) is the effective of the inflaton field before the start of oscillations. \n\nThe right-hand side should read \\(- \\Gamma _X (n_X - n_X^{\\text{eq}})\\), but we approximated it; the BE for baryon asymmetry on the other hand is \n%\n\\begin{align}\n\\dot{n}_B + 3 H n_B = +\\epsilon \\Gamma _X n_X\n\\,,\n\\end{align}\n%\nand we also need to write the Friedmann equation \n%\n\\begin{align}\nH^2 = \\frac{8 \\pi G}{3} \\qty(\\rho _\\varphi +\\rho _R)\n\\,.\n\\end{align}\n\nThe number density of \\(X\\) decays like \n%\n\\begin{align}\nn_X = n_{X, i} \\qty(\\frac{a_i}{a})^3 e^{-\\Gamma _\\varphi (t - t_i)}\n\\,,\n\\end{align}\n%\nwhere \\(t_i\\) is the ``oscillation time''. \n\nAs usual, we solve the BE for baryon asymmetry by writing the LHS as \n%\n\\begin{align}\n\\frac{1}{a^3} \\dv[]{}{t} (n_B a^3) \n\\,,\n\\end{align}\n%\ntherefore \n%\n\\begin{align}\nn_B a^3 = \\epsilon \\Gamma _X \\int_{t_i}^{t} n_{X, i} \\qty(\\frac{a_i}{a})^3 a^3e^{- \\Gamma _\\varphi (t - t_i)} \\dd{t}\n\\,.\n\\end{align}\n\nDoing the integral we get, \n%\n\\begin{align}\nn_B a^3 = \\epsilon n_{X, i} a_i^3 \\qty(1 - e^{- \\Gamma _\\varphi (t - t_i)})\n\\,.\n\\end{align}\n\nAt late times, we will get \n%\n\\begin{align}\nn_B a_f^3 = \\epsilon n_{X, i} a_i^3\n\\,.\n\\end{align}\n\nThis has a very simple physical meaning: the left-hand side counts the number of net (signed) baryons in a comoving volume, while the right-hand side is \\(\\epsilon \\) multiplied by the number of \\(X\\) particles in a comoving volume. \n\nThe final \\(B\\) is given by \n%\n\\begin{align}\nB_f = \\eval{\\frac{n_B}{s}}_{t_f} = \\frac{n_B a_f^3}{s a_f^3} = \\frac{\\epsilon n_{X, i} a_i^3}{S_f}\n\\,,\n\\end{align}\n%\nbut what is \\(S_f\\), the total entropy at a late time?\nThere are two ways to compute it: one is to solve the thermodynamic differential equations, and the alternative which we will adopt.\n\nWe write it as \n%\n\\begin{align}\nS_f =s_f a_f^3\n\\,,\n\\end{align}\n%\nand we know that in general for radiation domination \n%\n\\begin{align}\ns = \\frac{2 \\pi^2}{45} g_* T^3\n\\,,\n\\end{align}\n%\nand also \n%\n\\begin{align}\n\\rho _R = \\frac{\\pi^2}{30} g_* T^{4} \\implies T = g_*^{-1/4} \\rho _R^{1/4} \\qty(\\frac{30}{\\pi^2})^{1/4}\n\\,,\n\\end{align}\n%\ntherefore \n%\n\\begin{align}\nS = s a^3 = g_*^{1/4} \\rho _R^{3/4} a^3\n\\,.\n\\end{align}\n\nUsing this estimate, we can write \n%\n\\begin{align}\nB_f = \\frac{\\epsilon n_{X, i} a_i^3}{g_{*f}^{1/4} \\rho _{R, f}^{3/4} a_f^3}\n\\,.\n\\end{align}\n\nWe can build a hierarchy of timescales, and consider a time \\(t\\) such that: \\(t_i = t _{\\text{oscill}} < t \\leq t_\\varphi = \\Gamma _\\varphi^{-1}\\). \nIn this phase, \\(\\varphi \\) dominates.\nThen, with the assumption that there is complete conversion of the energy between \\(\\varphi \\) and radiation, we can write \n%\n\\begin{align}\n\\rho_{R, f}^{3/4} = \\rho _{X, i}^{3/4} \\qty(\\frac{a_i}{a_f})^{9/4}\n\\,,\n\\end{align}\n%\nso, since \\(a \\propto t^{2/3}\\) (matter domination):\n%\n\\begin{align}\nB_f &= \\frac{\\epsilon n_{X, i} a_i^{3/4}}{g_{*f}^{1/4} \\rho _{X, i}^{3/4} a_f^{3/4}}  \\\\\n&= \\frac{\\epsilon n_{X, i}}{g_*^{1/4} \\rho _{X, i}^{3/4}} t_i^{1/2} \\Gamma _\\varphi^{1/2}\n\\,,\n\\end{align}\n%\ntherefore in Friedmann's equation we have\n%\n\\begin{align}\nH_i^2 = \\frac{8 \\pi }{3} \\frac{\\rho_{X,i}}{m_P^2 } \\approx \\frac{1}{t_i^2}\n\\,,\n\\end{align}\n%\ntherefore \\(t_i \\approx m_P \\rho _{X, i}^{-1/2}\\).\nPlugging this in and using \\(\\rho _{X, i} = m_X n_{X, i}\\), we get \n%\n\\begin{align}\nB_f &\\approx \\frac{\\epsilon g_*^{-1/4} m_P^{1/2} \\Gamma _\\varphi^{1/2}}{m_X}  \\\\\n&\\approx \\epsilon \\frac{T_{RH}}{m_X}\n\\,,\n\\end{align}\n%\nwhere we recognize the approximate expression for the reheating temperature \\eqref{eq:reheating-temperature}.\n\nThis expression should be compared with \\(B_f = \\epsilon / g_*\\), the alternative. Which is larger?\nFor \\(k \\ll 1\\), the mass of the bosons violating baryon number must be quite large: \\(m_X \\gtrsim \\SI{e10}{GeV}\\). \nIn order for these to be relativistic, the temperature must then also be very large: \\(T \\gtrsim m_X \\sim \\SI{e10}{GeV}\\), which constrains the reheating temperature. \n\nIn this alternative scenario, with the inflaton violating baryon number conservation, we are allowed to violate this constraint. \n\nAre \\(B\\), \\(C\\) and \\(CP\\) violated in the SM? Yes, in some nonperturbative electroweak processes, but not enough. \n\n\\section{Dark matter production}\n\nWe will start with the ``freeze-out'' mechanism. \nFrom the latest Planck data, we know that at a \\SI{68}{\\percent} CL:\n%\n\\begin{align}\n\\Omega_{DM} h^2 &= \\num{.120(1)}   \\\\\nh &= \\num{.674(5)}\n\\,,\n\\end{align}\n%\ntherefore \\(\\Omega_{DM} \\approx \\SI{26.4}{\\percent}\\).\nDark Matter as measured here must be a non-relativistic pressureless fluid.\n\nConsider a massive particle \\(\\psi \\), with mass \\(m_\\psi \\). \nLet us define \n%\n\\begin{align}\ny = n_\\psi / s\n\\,.\n\\end{align}\n\nAs long as \\(\\Gamma _\\psi < H\\), the abundance of \\(\\psi \\) ``freezes out'' when \\(z = m_\\psi / T \\) reaches 1. \n\nThe Boltzmann equation for a process \\(\\psi \\overline{\\psi} \\leftrightarrow X \\overline{X}\\) where \\(X\\) is in equilibrium with the plasma reads \n%\n\\begin{align}\n\\dot{n}_\\psi + 3 H n_\\psi = - \\expval{\\sigma \\abs{v}} \\qty[n_\\psi^2 - (n_\\psi^{\\text{eq}})^2]\n\\,.\n\\end{align}\n\nThen, \n%\n\\begin{align}\n\\dot{y} = - \\expval{\\sigma \\abs{v}} s \\qty[y^2 - y^2 _{\\text{eq}}]\n\\,,\n\\end{align}\n%\ntherefore, because\n%\n\\begin{align}\n\\dv{z}{t} = zH\n\\,,\n\\end{align}\n%\nwe can express the same with derivatives with respect to \\(z\\), denoted with primes: \n%\n\\begin{align}\ny' &= - \\frac{\\expval{\\sigma \\abs{v}} s}{z H} \\qty[y^2 - y^2 _{\\text{eq}}]  \\\\\n&= - \\frac{z\\expval{\\sigma \\abs{v}} s}{H(z=1)} \\qty[y^2 - y^2 _{\\text{eq}}]\n\\,,\n\\end{align}\n%\nsince \\(z^2 H = H(z=1)\\), which corresponds to the moment at which \\(m_\\psi = T\\).\n\n\n%\n\\begin{align} \\label{eq:y-eq-freezeout}\ny _{\\text{eq}} = \\frac{n_\\psi^{\\text{eq}}}{s} = \\begin{cases}\n    \\num{.278} \\frac{g _{\\text{eff}}}{g_{*s}} & z \\ll 1  \\\\\n    \\num{.145} \\frac{g_\\psi }{g_{*s}} z^{3/2} e^{-z} & z \\gg 1\n\\,.\n\\end{cases}\n\\end{align}\n\nIn the \\(z \\gg 1\\) limit inverse processes are suppressed.\n\nThe effective number of degrees of freedom is given by \n%\n\\begin{align}\ng _{\\text{eff}} = \\begin{cases}\n    g_\\psi & \\text{boson} \\\\\n    \\frac{3}{4} g_\\psi & \\text{fermion} \n\\,.\n\\end{cases}\n\\end{align}\n\nWe can write the derivative of \\(y\\) with respect to \\(z\\) as \n%\n\\begin{align}\ny' &= - y^2 _{\\text{eq}} \\frac{\\expval{\\sigma \\abs{v}} s}{zH} \\qty[ \\qty(\\frac{y}{y _{\\text{eq}}})^2 - 1] \\\\\n\\frac{z}{y _{\\text{eq}}} y' &= - \\underbrace{n^\\psi  _{\\text{eq}} \\frac{\\expval{\\sigma \\abs{v}} s}{H}}_{\\Gamma_A / H} \\qty[ \\qty(\\frac{y}{y _{\\text{eq}}})^2 - 1] \n\\,.\n\\end{align}\n\nIf \\(\\Gamma _A / H <1\\), then the right-hand side becomes small, so the left-hand side (which is basically \\(\\Delta y / y\\) in a comoving volume) must also be small, meaning that \\(y\\) is roughly constant (frozen out): we have produced a relic abundance of \\(\\psi \\) particles.\n\n\\subsection{Hot Dark Matter relics}\n\nThese particles are called ``hot'' since they \\textbf{decouple while still being relativistic}. This is what we would expect for neutrinos, for example. \n\nThis particle decouples in the upper plateau of the curve \\(y(z)\\), so we expect little dependence for it on \\(z_f\\). \n\nHere we will have \n%\n\\begin{align}\ny_\\infty &= y(z \\to \\infty ) \\approx y _{\\text{eq}} (z_f)  \\\\\n&\\approx \\frac{\\zeta (3) g _{\\text{eff}}T_f^3 / \\pi^2}{(\\pi^2 / 45) g_{*s } (z_f) T_f^3} \\approx \\num{.278} \\frac{g _{\\text{eff}}}{g_{*s} (z_f)}\n\\marginnote{Used \\eqref{eq:y-eq-freezeout}.}\n\\,.\n\\end{align}\n\nNow, \n%\n\\begin{align}\n\\rho_{\\psi 0 } = m_\\psi n_{\\psi 0 } = m_\\psi y_\\infty s_0 \n\\,,\n\\end{align}\n%\nwhere \\(s_0 \\approx 1.8 g_{*s} (t_0 ) n_{\\gamma 0 }\\), where \\(n_{\\gamma 0} \\approx \\SI{422}{cm^{-3}}\\). \n\nAssuming that there is one relativistic neutrino species (this is conservative, we know there to be at least 2), we can write \n%\n\\begin{align}\ng_{*s} (t_0) \\approx \\num{2.63}\n\\,,\n\\end{align}\n%\ntherefore \\(s_0  \\approx \\num{2e3}\\). \nThis means that \n%\n\\begin{align}\n\\rho_{0, \\text{crit}} = \\SI{1.054e4}{eV cm^{-3}} h^2\n\\,,\n\\end{align}\n%\nand \n%\n\\begin{align}\n\\Omega_{0 \\psi } h^2 \\approx \\num{5.56e-2} \\times \\frac{m_\\psi }{\\SI{}{eV}} \\frac{g _{\\text{eff}}}{g_{*s} (z_f)}\n\\,.\n\\end{align}\n\nIn our case, \\(g _{\\text{eff}} = (3/4) \\times 2\\) since we have one neutrino species (with two polarizations), while \\(g_{*s}(z_f) = \\num{10.75}\\), accounting for three neutrinos, electrons, positrons and photons.\n\nFrom Planck data, including lensing of the CMB and BAO, we know that at a \\SI{95}{\\percent} CL: \n%\n\\begin{align}\n\\sum _{\\nu } m_\\nu < \\SI{.12}{eV}\n\\,.\n\\end{align}\n\nThey will surely be relativistic when they decouple at \\(T_f \\sim \\SI{}{MeV}\\). \nThis tells us that, if neutrinos are \\(\\psi \\), \n%\n\\begin{align}\n\\Omega_{0 \\nu  \\overline{\\nu}} h^2 = \\frac{\\qty(\\sum _{\\nu } m_\\nu  / \\SI{}{eV})}{128} \\lesssim \\num{e-3}\n\\,.\n\\end{align}\n\nThus, we learn that neutrinos cannot constitute the majority of DM. \nDespite this, they have a characteristic signature effect on structure formation. \n\nThe free-stream scale is given by \n%\n\\begin{align}\n\\lambda_{\\text{fs}}(t) = a(t) \\int_0^{t} \\frac{v_\\nu }{a(\\widetilde{t})} \\dd{\\widetilde{t}}\n\\,.\n\\end{align}\n\nBelow this scale (\\(\\lambda < \\lambda _{\\text{fs}}\\)), neutrinos move too fast and damp the power spectrum of matter. \n\n\\end{document}\n", "meta": {"hexsha": "f7d52d19d2ced9c6539a4c31cc470151822ea983", "size": 10097, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ap_third_semester/early_universe/dec02.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "ap_third_semester/early_universe/dec02.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ap_third_semester/early_universe/dec02.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 29.6970588235, "max_line_length": 277, "alphanum_fraction": 0.639100723, "num_tokens": 3762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.33318323535406197}}
{"text": "\\documentclass[conference]{IEEEtran}\r\n\\usepackage{amsmath}\r\n\\usepackage{verbatim}\r\n\\usepackage{datatool}\r\n\\usepackage{tikz}\r\n\\usetikzlibrary{arrows,shapes}\r\n\\usepackage{graphics}\r\n\r\n\\newcounter{Examplecount}\r\n\\setcounter{Examplecount}{0}\r\n\\newenvironment{example}\r\n{% This is the begin code\r\n    \\stepcounter{Examplecount} Example \\arabic{Examplecount} \r\n\\begin{it}\r\n    } \r\n    {% This is the end code\r\n\\end{it} \r\n}\r\n\r\n\\begin{document}\r\n\r\n\\title{A Hard Satisfiable Problem with 160 Variables}\r\n\r\n\r\n\\author{\\IEEEauthorblockN{Valentin Mayer-Eichberger}\r\n\\IEEEauthorblockA{NICTA and\\\\University of New South Wales\\\\\r\nValentin.Mayer-Eichberger@nicta.com.au}}\r\n\r\n% make the title area\r\n\\maketitle\r\n\r\n\r\n\\begin{abstract}\r\nIn trying to solve a hard graph colouring problem we ran into an interesting SAT formula. The encoding uses just 160\r\nvariables and defines a special case of a rectangle-free coloring of a 18x18 grid using four colors. Rectangle-free\r\nmeans that the corners of every rectangle in the grid cannot have all the same colour. Such structured satisfiable\r\nproblems pose a real challenge to SAT solvers. \r\n\\end{abstract}\r\n\\IEEEpeerreviewmaketitle\r\n\r\n\\section{Introduction}\r\n\r\nIn 2011 a blog post of\r\n\\begin{verbatim}\r\n    blog.computationalcomplexity.org \r\n\\end{verbatim} \r\nannounced a reward of $289$ \\$ for a solution to the problem of 4-colouring a $17\\times 17$ grid such that for each\r\nrectangle in the grid all its corners consist of at least two different colours. A solution to $16\\times 16$ was known\r\nto exist and all grids $19 \\times 19$ and larger were proven to not contain such a colouring.  In 2012 Steinbach and\r\nPosthoff presented a solution to $17\\times 17$ and $18\\times 18$ \\cite{Steinbach12} (every solution of larger grids\r\ngenerates solutions to smaller). We provide the SAT competition with an interesting encoding for this problem which is\r\nsimilar to the approach they used. It will be valuable for the community to see if any SAT solver is able to solve this\r\nhard problem within the time-out. Our own experiments show that CDCL solvers tend to spend several hours to find a\r\nsolution. By such a benchmark we might identify advantages of non-standard SAT solver techniques. \r\n\r\n\\section{Encoding}\r\n\r\nNaive encodings for this problem can solve grids up to $14\\times 14$  almost instantly and do not put a challenge to a SAT solver.\r\nWith some advancements and symmetry breaking one can also solve $15\\times 15$  and $16\\times 16$. However, no direct approach seems to tackle\r\nthe hard cases of $17\\times 17$ and $18\\times 18$. In this section we explain the tricks that made it possible. \r\n\r\nWe identify a special case that can be extended to a full solution. If such a solution would exist then the problem is\r\nsolved, but a negative result would not give much insight. Luckily, it turns out that the simplification does indeed\r\nlead to solutions. \r\n\r\nWe simplify the problem to find a two coloring. We denote the two colours as primary and secondary, and the secondary\r\ncolour represents the three other colours of the original problem. A solution to this problem can be extended to a\r\nsolution if\r\n\r\n\\begin{itemize}\r\n    \\item only the primary colour needs to be rectangle-free,\r\n    \\item $1/4$ of all positions are filled with the primary colour, \r\n    \\item rotating the solution by 90,180, and 270 degrees will not map a position containing a primay colour onto\r\nanother. \r\n\\end{itemize}\r\n\r\nWe can then take a solution of this problem and fill for each rotation the mapped positions of the primary colour with\r\none of the remaining one. Since there are no collisions and rectangle-free is preserved under rotation, we generate a\r\nfull solution. \r\n\r\n\r\n%\\begin{scriptsize}\r\n%\\begin{verbatim*}\r\n%bdaaadcbdbcddacbac\r\n%dddbdbccccbaacbbaa\r\n%aacbdabbcadcddcdab\r\n%babcddcaadbcbadccb\r\n%dbcdcbcaddabcdaaab\r\n%cdcabaddaddbbcabca\r\n%cdbbaaaacbcbaddcdd\r\n%bacadcbddcababbcdc\r\n%abdcccabcdadbabdda\r\n%cbbdcdbcbadcaaabdc\r\n%abaddcdcabbdabcacd\r\n%bbabbcdadaccccddba\r\n%cadcaddbbcbbcdcaba\r\n%dcccbadcbbcadabadb\r\n%daabcdadbccabbadcd\r\n%dcbabbabcaddcbdacc\r\n%ccddaccdaaaadbdbbb\r\n%acdacbbadbdabcccbd\r\n%\\end{verbatim*}\r\n%\\end{scriptsize}\r\n\r\nA natural choice would be to define for each  each position in the board a Boolean variable that is true if that\r\nposition contains the primary colour. We reduce the number of variables by using the restriction that each orbit wrt. to\r\nthe 90 degree rotations should have exactly one primary colour. This can be encoded in a logarithmic fashion such that\r\ntwo Boolean variables identify for each orbit in which of the four half section of the grid it exists. Furthermore, we\r\nbreak symmetries by forcing the upper left position to contain a primary colour. By these reductions we get a formula\r\nthat only uses 160 variables. \r\n\r\n\\section{Benchmark}\r\n\r\nThe set contains 4 encodings of the same problems. They have been generated by shuffling the variables, literals and\r\norder of clauses of the encoding described above.\r\n\r\n\\section*{Acknowledgement}\r\n\r\nNICTA is funded by the Australian Government as represented by the Department of Broadband, Communications and the\r\nDigital Economy and the Australian Research Council through the ICT Centre of Excellence program.\r\n\r\n\r\n\\bibliographystyle{IEEEtran}\r\n\\bibliography{p}\r\n\r\n\\end{document}\r\n", "meta": {"hexsha": "90af8b563275ff81210a170a608710d3f1daf900", "size": 5290, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ex/p.tex", "max_stars_repo_name": "vale1410/fourcoloring", "max_stars_repo_head_hexsha": "532c31d54a4435b9d24e9350041be913b1abb932", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ex/p.tex", "max_issues_repo_name": "vale1410/fourcoloring", "max_issues_repo_head_hexsha": "532c31d54a4435b9d24e9350041be913b1abb932", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ex/p.tex", "max_forks_repo_name": "vale1410/fourcoloring", "max_forks_repo_head_hexsha": "532c31d54a4435b9d24e9350041be913b1abb932", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.6535433071, "max_line_length": 142, "alphanum_fraction": 0.7782608696, "num_tokens": 1319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.33318323535406197}}
{"text": "\\hiddenappendixsection{Correctness Proof}\nIn this appendix, we reason about an \\SLCO model~$m = \\it{mn}\\ \\it{class^*}\\ \\it{obj^*}\\ \\it{chan^*}$ and a unidirectional, synchronous channel~$\\it{chan} = \\it{chn}()\\ \\textbf{sync from}\\ \\it{on_1}.\\it{pn_1}\\ \\textbf{to}\\ \\it{on_2}.\\it{pn_2}\\ \\in \\ \\it{chan^*}$.\nAs discussed in Chapter~\\ref{chap:reusable-correct-transformations}, transformation~\\TSim is considered to be correct if~$\\it{LTS}(m)$ and~$\\rho(\\it{LTS}(\\TSim(m, \\it{chn})))$ are branching bisimilar~\\cite{GlabWeijBisim96} for some appropriate label-renaming function~$\\rho$,\nwhere $\\it{LTS}(m)$ refers to the labeled transition system~(LTS) of model~$\\it{m}$ as defined by the operational semantics described in Appendix~\\ref{ap:sos-slco}.\nFirst, we discuss the label-renaming function~$\\rho$ that corresponds to transformation~\\TSim.\nSecond, we list the conditions for model~$\\it{m}$ that must hold to ensure that~$\\it{LTS}(m)$ and~$\\rho(\\it{LTS}(\\TSim(m, \\it{chn})))$ are branching bisimilar.\nFinally, we show that a branching bisimulation between~$\\it{LTS}(m)$ and~$\\rho(\\it{LTS}(\\TSim(m, \\it{chn})))$ exists by defining a relation~$R$ and showing that~$R$ is a branching bisimulation according to the definition given in Section~\\ref{subsec:reusable-correct-transformations:correctness_of_simple}.\n\n\\subsection{Label-Renaming Function}\nThe definition of transformation~\\TSim given in Appendix~\\ref{sec:transformations-slco:simple} defines that all transitions in model~$\\it{m}$ that send or receive signals over channel~$\\it{chan}$ are replaced by transitions that send or receive signals with a modified name.\nLet $\\it{Sgn} \\subseteq \\SignalNames$ be the set of all signal names that are passed over channel~$\\it{chan}$ in model~$\\it{m}$.\nWithout loss of generality, we assume that all other channels in model~$\\it{m}$ are used to pass signals with names not in~$\\it{Sgn}$.\nIf this is not the case, the signals passed over these other channels can be renamed.\nAfter applying transformation~\\TSim to model~$\\it{m}$, the set of names of signals that are passed over the modified channel~$\\it{chan'}$ is~$\\it{Sgn'} \\cup \\it{Sgn''}$, where~$\\it{Sgn'} = \\{``s\\_\" + \\it{sgn} \\mid \\it{sgn} \\in \\it{Sgn}\\}$ and~$\\it{Sgn''} = \\{``a\\_\" + \\it{sgn} \\mid \\it{sgn} \\in \\it{Sgn}\\}$.\nThe label-renaming function~$\\rho$ that corresponds to transformation~\\TSim is defined as follows, for every~$\\it{sgn'} \\equiv ``s\\_\" + \\it{sgn}$ and~$\\it{sgn''} \\equiv ``a\\_\" + \\it{sgn}$ such that~$\\it{sgn}\\in \\it{Sgn}$.\n%\n\\begin{itemize*}\n\\item $\\rho(\\textbf{send}~\\it{sgn'()}) = \\tau$\n\\item $\\rho(\\textbf{receive}~\\it{sgn'()}) = \\it{sgn()}$\n\\item $\\rho(\\textbf{send}~\\it{sgn''()}) = \\tau$\n\\item $\\rho(\\textbf{receive}~\\it{sgn''()}) = \\tau$\n\\end{itemize*}\n\n\\noindent\nRenaming~$\\rho$ is straightforwardly extended on LTSs.\nBy renaming the labels~$\\textbf{receive}~\\it{sgn'()}$ to $\\it{sgn()}$, for every~$\\it{sgn'} \\equiv ``s\\_\" + \\it{sgn}$ such that~$\\it{sgn}\\in \\it{Sgn}$, we indicate that these labels represent successful communication.\nThe other labels are renamed to $\\tau$ because they represent the implicit synchronization in the source model and should result in unobservable behavior of the target model.\n\n\\subsection{Applicability Conditions}\nTo ensure that~$\\it{LTS}(m)$ and~$\\rho(\\it{LTS}(\\TSim(m, \\it{chn})))$ are branching bisimilar, a number of conditions must hold for model~$\\it{m}$.\nAs mentioned above, the synchronous channel~$\\it{chan}$ connects two objects~$\\it{obj_1}$ and~$\\it{obj_2}$.\nEach object~$\\it{obj_i}$ is named~$\\it{on_i}$ and is an instance of class~$\\it{class_i}$ with name~$\\it{cn_i}$, for $i = 1,2$.\nWe require that the following conditions hold for~$\\it{m}$.\n\\begin{enumerate}\n\\item Channel~$\\it{chan}$ is unidirectional, as mentioned above.\n\\item At most one state machine~$\\it{sm_1}$ of object~$\\it{obj_1}$ sends signals over channel~$\\it{chan}$.\n\\item At most one state machine~$\\it{sm_2}$ of object~$\\it{obj_2}$ receives signals over channel~$\\it{chan}$.\n\\item Object~$\\it{obj_1}$ is the only instance of class~$\\it{class_1}$.\n\\item Object~$\\it{obj_2}$ is the only instance of class~$\\it{class_2}$.\n\\end{enumerate}\nA model can be adapted with the model transformations described in Section~\\ref{sec:slco:endogenous} if these conditions are not met.\nIf the first condition does not hold, transformation~\\Transformation{uni} can be applied to replace a bidirectional channel with two unidirectional channels.\nFurthermore, transformation~\\Transformation{ex} can be applied if the second or third condition is not met.\nIt ensures that each pair of state machines communicates over a channel that is used by these two state machines only.\nFinally, the transformation that clones classes can be applied if the last two conditions are not met.\n\nSince only the behavior of the instances of classes~$\\it{class_1}$ and~$\\it{class_2}$ are affected by transformation~\\TSim and objects~$\\it{obj_1}$ and~$\\it{obj_2}$ are the only instances of these classes, the behavior of all other objects is unchanged.\nFurthermore, because state machines~$\\it{sm_1}$ and~$\\it{sm_2}$ are the only state machines that communicate over channel~$\\it{chan}$, the behavior of all other state machines is also unchanged.\nFinally, because channel~$\\it{chan}$ is unidirectional, state machine~$\\it{sm_1}$ can only send signals over this channel, and state machine~$\\it{sm_2}$ can only receive signals over this channel.\n\n\\subsection{Bisimulation Relation}\nWe use~$\\it{cf} = \\langle m, \\sobjs, \\vglob, \\vloc, \\buf \\rangle$ to represent a configuration of~$\\it{LTS}(m)$ and~$\\it{cf'} = \\langle \\TSim(m), \\sobjs', \\vglob', \\vloc', \\buf' \\rangle$ to represent a configuration of~$\\rho(LTS(\\TSim(m, \\it{chn})))$.\nAccording to the definition of branching bisimilarity, $\\it{LTS}(m)$ and $\\rho(LTS(\\TSim(m, \\it{chn})))$ are branching bisimilar if their initial configurations are branching bisimilar.\nFor each configuration~$\\it{cf} = \\langle m, \\sobjs, \\vglob, \\vloc, \\buf \\rangle$, including the initial configuration, a counterpart~$\\it{cf'} = \\langle \\TSim(m), \\sobjs', \\vglob', \\vloc', \\buf' \\rangle$ exists such that~$\\sobjs = \\sobjs'$, $\\vglob = \\vglob'$, $\\vloc = \\vloc'$, $\\buf'(\\langle \\it{chn}, \\it{on_1}, \\it{on_2} \\rangle) = \\nil$, $\\buf'(\\langle \\it{chn}, \\it{on_2}, \\it{on_1} \\rangle) = \\nil$, and~$\\buf = \\buf'$ otherwise.\nTransformation~\\TSim does not modify the initial states and the variables of a model.\nIt does, however, replace a unidirectional, synchronous channel with a bidirectional, asynchronous channel.\nTherefore, according to the definitions concerning initialization provided in Section~\\ref{sec:sos-slco:initialization}, the initial configuration~$\\it{cf'_i}$ of $\\rho(LTS(\\TSim(m, \\it{chn})))$ is the counterpart of the initial configuration~$\\it{cf_i}$ of $\\it{LTS}(m)$ as discussed above.\nThus, if we prove that a branching bisimulation exists between each configuration~$\\it{cf}$ and its counterpart~$\\it{cf'}$, we prove that $\\it{LTS}(m)$ and $\\rho(LTS(\\TSim(m, \\it{chn})))$ are branching bisimilar.\n\nFor each~$\\it{sgn} \\in \\it{Sgn}$,\ntransformation~\\TSim modifies state machine~$\\it{sm_1}$ by replacing each transition\n%\n\\[\n\\it{trans^s_{sgn}} = \\it{tn}\\ \\textbf{from}\\ \\it{sn^s_1}\\ \\textbf{to}\\ \\it{sn^s_2}\\ \\textbf{send}\\ \\it{sgn}()\\ \\textbf{to}\\ \\it{pn}\n\\]\n%\nwith two transitions\n%\n\\begin{align*}\n& \\it{tn_1}\\ \\textbf{from}\\ \\it{sn^s_1}\\ \\textbf{to}\\ \\it{sn^s_{sgn}}\\ \\textbf{send}\\ \\it{sgn_1}()\\ \\textbf{to}\\ \\it{pn}\\ \\text{and}\\\\\n& \\it{tn_2}\\ \\textbf{from}\\ \\it{sn^s_{sgn}}\\ \\textbf{to}\\ \\it{sn^s_2}\\ \\textbf{receive}\\ \\it{sgn_2}()\\ \\textbf{from}\\ \\it{pn},\n\\end{align*}\n%\nwhere~$\\it{tn_1}$ and~$\\it{tn_2}$ are fresh transition names, $\\it{sn^s_{sgn}}$ is a fresh state name, $\\it{sgn_1} \\equiv ``s\\_\" + \\it{sgn}$, and~$\\it{sgn_2} \\equiv ``a\\_\" + \\it{sgn}$.\nSimilarly, for each~$\\it{sgn} \\in \\it{Sgn}$,\neach transition\n%\n\\[\n\\it{trans^r_{sgn}} = \\it{tn}\\ \\textbf{from}\\ \\it{sn^r_1}\\ \\textbf{to}\\ \\it{sn^r_2}\\ \\textbf{receive}\\ \\it{sgn}()\\ \\textbf{from}\\ \\it{pn}\n\\]\n%\nof state machine~$\\it{sm_2}$ is replaced with two transitions\n%\n\\[\n\\begin{array}{l}\n\\it{tn_1}\\ \\textbf{from}\\ \\it{sn^r_1}\\ \\textbf{to}\\ \\it{sn^r_{sgn}}\\ \\textbf{receive}\\ \\it{sgn_1}()\\ \\textbf{from}\\ \\it{pn}\\ \\text{and}\\\\\n\\it{tn_2}\\ \\textbf{from}\\ \\it{sn^r_{sgn}}\\ \\textbf{to}\\ \\it{sn^r_2}\\ \\textbf{send}\\ \\it{sgn_2}()\\ \\textbf{to}\\ \\it{pn},\n\\end{array}\n\\]\n%\nwhere~$\\it{tn_1}$ and~$\\it{tn_2}$ are fresh transition names, $\\it{sn^r_{sgn}}$ is a fresh state name, $\\it{sgn_1} \\equiv ``s\\_\" + \\it{sgn}$, and~$\\it{sgn_2} \\equiv ``a\\_\" + \\it{sgn}$.\n\nWe define a relation~$R$ between configurations as follows: $(\\it{cf}, \\it{cf'})\\in R$ if and only if $\\vglob = \\vglob'$, $\\vloc = \\vloc'$, and one of the following four conditions holds.\n%\n\\begin{enumerate}\n\\item\n  \\begin{enumerate}\n    \\item\n      $\\sobjs = \\sobjs'$,\n    \\item\n      $\\buf'(\\langle \\it{chn}, \\it{on_1}, \\it{on_2} \\rangle) = \\nil$,\n      $\\buf'(\\langle \\it{chn}, \\it{on_2}, \\it{on_1} \\rangle) = \\nil$,\n      and $\\buf' = \\buf$ otherwise;\n  \\end{enumerate}\n\n\\item\n  \\begin{enumerate}\n    \\item\n      $\\sobjs(\\it{on_1})(\\it{smn_1}) = \\it{sn^s_1}$,\n      $\\sobjs'(\\it{on_1})(\\it{smn_1}) = \\it{sn^s_{sgn}}$,\n      $\\sobjs = \\sobjs'$ otherwise,\n    \\item\n      $\\buf'(\\langle \\it{chn}, \\it{on_1}, \\it{on_2}\\rangle) = (\\it{sgn_1}, \\varepsilon)$,\n      $\\buf'(\\langle \\it{chn}, \\it{on_2}, \\it{on_1}\\rangle) = \\nil$,\n      and $\\buf' = \\buf$ otherwise,\n  \\end{enumerate}\n  if there is a transition~$\\it{trans^s_{sgn}}$ from state~$\\it{sn^s_1}$ and~$\\it{sgn_1} \\equiv ``s\\_\" + \\it{sgn}$;\n\n\\item\n  \\begin{enumerate}\n    \\item\n      $\\sobjs(\\it{on_1})(\\it{smn_1}) = \\it{sn^s_2}$,\n      $\\sobjs(\\it{on_2})(\\it{smn_2}) = \\it{sn^r_2}$,\n      $\\sobjs'(\\it{on_1})(\\it{smn_1}) = \\it{sn^s_{sgn}}$,\n      $\\sobjs'(\\it{on_2})(\\it{smn_2}) = \\it{sn^r_{sgn}}$,\n      $\\sobjs = \\sobjs'$ otherwise,\n    \\item\n      $\\buf'(\\langle \\it{chn}, \\it{on_1}, \\it{on_2}\\rangle) = \\nil$,\n      $\\buf'(\\langle \\it{chn}, \\it{on_2}, \\it{on_1}\\rangle) = \\nil$,\n      and $\\buf' = \\buf$ otherwise,\n  \\end{enumerate}\n  if there is a transition~$\\it{trans^s_{sgn}}$ to state~$\\it{sn^s_2}$ and a transition~$\\it{trans^r_{sgn}}$ to state~$\\it{sn^r_2}$;\n\n\\item\n  \\begin{enumerate}\n    \\item\n      $\\sobjs(\\it{on_1})(\\it{smn_1}) = \\it{sn^s_2}$,\n      $\\sobjs'(\\it{on_1})(\\it{smn_1}) = \\it{sn^s_{sgn}}$,\n      $\\sobjs = \\sobjs'$ otherwise,\n    \\item\n      $\\buf'(\\langle \\it{chn}, \\it{on_1}, \\it{on_2}\\rangle) = \\nil$,\n      $\\buf'(\\langle \\it{chn}, \\it{on_2}, \\it{on_1}\\rangle) = (\\it{sgn_2}, \\varepsilon)$,\n      and $\\buf' = \\buf$ otherwise,\n  \\end{enumerate}\n  if there is a transition~$\\it{trans^s_{sgn}}$ to state~$\\it{sn^s_2}$ and~$\\it{sgn_2} \\equiv ``a\\_\" + \\it{sgn}$.\n\\end{enumerate}\n%\nWe prove that $R$ is a branching bisimulation by distinguishing two cases.\nFirst, we consider the case in which $(\\it{cf_1}, \\it{cf_1'})\\in R$ and $\\it{cf_1} \\TextModelRelation{l} \\it{cf_2}$.\nWe distinguish four cases.\n\\begin{enumerate}\n\\item\nWe assume that $(\\it{cf_1}, \\it{cf_1'})\\in R$ according to the first condition stated above and distinguish between the cases~$l \\not \\equiv \\it{sgn}()$ and~$l \\equiv \\it{sgn}()$, for any~$\\it{sgn} \\in \\it{Sgn}$.\n\\begin{itemize}\n\\item\nIn the first case, the transition~$\\it{cf_1} \\TextModelRelation{l} \\it{cf_2}$ cannot be the result of synchronous communication between state machines~$\\it{sm_1}$ and~$\\it{sm_2}$.\nThus, the transition~$\\it{cf_1} \\TextModelRelation{l} \\it{cf_2}$ is the result of some of the transitions of these two state machines that are unaffected by the transformation or one or more transitions of some of the other state machines in the model, which are also unaffected by the transformation.\nBecause transition~$\\it{cf_1} \\TextModelRelation{l} \\it{cf_2}$ is the result of behavior that is unaffected by the transformation, a transition~$\\it{cf'_1} \\TextModelRelation{l} \\it{cf'_2}$ can also be made from configuration~$\\it{cf'_1}$, and~$(\\it{cf_2}, \\it{cf_2'})\\in R$ according to the first condition.\n\\item\nIn the second case, the transition~$\\it{cf_1} \\TextModelRelation{\\it{sgn}()} \\it{cf_2}$ is the result of synchronous communication between state machines~$\\it{sm_1}$ and~$\\it{sm_2}$.\nAccording to the SOS rule for synchronous communication, state machine~$\\it{sm_1}$ has to be in a state~$\\it{sn^s_1}$ with an outgoing transition~$\\it{trans^s_{sgn}}$, and state machine~$\\it{sm_2}$ has to be in a state~$\\it{sn^r_1}$ with an outgoing transition~$\\it{trans^r_{sgn}}$.\nAfter transformation, according to the SOS rules for asynchronous communication, state machine~$\\it{sm_1}$ can make a transition from such a state~$\\it{sn^s_1}$ to a state~$\\it{sn^s_{sgn}}$ and send a signal over channel~$\\it{chan'}$.\nThis results in a transition~$\\it{cf'_1} \\TextModelRelation{\\tau} \\it{cf'_2}$,\nwhere the label~$\\tau$ is the result of renaming the label~$\\textbf{send}\\ \\it{sgn_1}()$, and~$\\it{sgn_1} \\equiv ``s\\_\" + \\it{sgn}$.\nFurthermore, $(\\it{cf_1}, \\it{cf'_2})\\in R$ according to the second condition.\nNext, state machine~$\\it{sm_2}$ can make a transition to a state~$\\it{sn^r_{sgn}}$ and receive the signal sent by state machine~$\\it{sm_1}$.\nThis results in a transition~$\\it{cf'_2} \\TextModelRelation{\\it{sgn}()} \\it{cf'_3}$,\nwhere the label~$\\it{sgn}()$ is the result of renaming the label~$\\textbf{receive}\\ \\it{sgn_1}()$, and~$\\it{sgn_1} \\equiv ``s\\_\" + \\it{sgn}$.\nIn configuration~$\\it{cf'_3}$, state machine~$\\it{sm_1}$ is in state~$\\it{sn^s_{sgn}}$ and state machine~$\\it{sm_2}$ is in state~$\\it{sn^r_{sgn}}$.\nThus, $(\\it{cf_2}, \\it{cf_3'})\\in R$ according to the third condition.\n\\end{itemize}\n\n\\item\nWe assume that $(\\it{cf_1}, \\it{cf_1'})\\in R$ according to the second condition stated above and distinguish between the cases~$l \\not \\equiv \\it{sgn}()$ and~$l \\equiv \\it{sgn}()$, for any~$\\it{sgn} \\in \\it{Sgn}$.\n\\begin{itemize}\n\\item\nIn the first case, the transition~$\\it{cf_1} \\TextModelRelation{l} \\it{cf_2}$ cannot result from behavior of state machine~$\\it{sm_1}$, because this state machine can only send a signal over the synchronous channel~$\\it{chan}$ in a state~$\\it{sn^s_1}$ with an outgoing transition~$\\it{trans^s_{sgn}}$.\nThus, the transition~$\\it{cf_1} \\TextModelRelation{l} \\it{cf_2}$ must result from behavior of one or more other state machines.\nIf the transition is the result of behavior of state machine~$\\it{sm_2}$, then it must be the result of one of the transitions of this state machine that are unaffected by the transformation, because the affected transitions can only lead to synchronous communication.\nFurthermore, all other state machines are unaffected by the transformation.\nThus, the same behavior can be performed in the transformed model, leading to a transition~$\\it{cf'_1} \\TextModelRelation{l} \\it{cf'_2}$.\nFurthermore, since the values of~$\\sobjs(\\it{on_1})(\\it{smn_1})$ and~$\\sobjs'(\\it{on_1})(\\it{smn_1})$ remain the same, $(\\it{cf_2}, \\it{cf_2'})\\in R$.\n\\item\nIn the second case, according to the SOS rule for synchronous communication, state machine~$\\it{sm_2}$ has to be in a state~$\\it{sn^r_1}$ with an outgoing transition~$\\it{trans^r_{sgn}}$.\nAfter transformation, according to the SOS rules for asynchronous communication, state machine~$\\it{sm_2}$ is able to receive the signal in the buffer that corresponds to channel~$\\it{chan'}$.\nThis leads to a transition~$\\it{cf'_1} \\TextModelRelation{\\it{sgn}()} \\it{cf'_2}$,\nwhere the label~$\\it{sgn}()$ is the result of renaming the label~$\\textbf{receive}\\ \\it{sgn_1}()$, and~$\\it{sgn_1} \\equiv ``s\\_\" + \\it{sgn}$.\nIn configuration~$\\it{cf_2}$, state machine~$\\it{sm_1}$ is in state~$\\it{sn^s_2}$ and state machine~$\\it{sm_2}$ is in state~$\\it{sn^r_2}$.\nFurthermore, in configuration~$\\it{cf'_2}$, state machine~$\\it{sm_1}$ is in state~$\\it{sn^s_{sgn}}$ and state machine~$\\it{sm_2}$ is in state~$\\it{sn^r_{sgn}}$.\nThus, $(\\it{cf_2}, \\it{cf_2'})\\in R$ according to the third condition.\n\\end{itemize}\n\n\\item\nWe assume that $(\\it{cf_1}, \\it{cf_1'})\\in R$ according to the third condition stated above.\nIf transition~$\\it{cf_1} \\TextModelRelation{l} \\it{cf_2}$ is the result of behavior of state machines that are unaffected by the transformation, then $\\it{cf'_1} \\TextModelRelation{l} \\it{cf'_2}$ and~$(\\it{cf_2}, \\it{cf_2'})\\in R$.\nOtherwise, according to the SOS rules for asynchronous communication,\nstate machine~$\\it{sm_2}$ can make a transition from a state~$\\it{sn^r_{sgn}}$ to a state~$\\it{sn^r_2}$ and send a signal over channel~$\\it{chan'}$, resulting in a transition~$\\it{cf'_1} \\TextModelRelation{\\tau} \\it{cf'_2}$,\nwhere the label~$\\tau$ is the result of renaming the label~$\\textbf{send}\\ \\it{sgn_2}()$, and~$\\it{sgn_2} \\equiv ``a\\_\" + \\it{sgn}$.\nFurthermore, $(\\it{cf_1}, \\it{cf_2'})\\in R$ according to the fourth condition.\nNext, state machine~$\\it{sm_1}$ can make a transition from a state~$\\it{sn^s_{sgn}}$ to a state~$\\it{sn^s_2}$ and receive the signal sent over channel~$\\it{chan'}$, resulting in a transition~$\\it{cf'_2} \\TextModelRelation{\\tau} \\it{cf'_3}$,\nwhere the label~$\\tau$ is the result of renaming the label~$\\textbf{receive}\\ \\it{sgn_2}()$, and~$\\it{sgn_2} \\equiv ``a\\_\" + \\it{sgn}$.\nAccording to the first condition, $(\\it{cf_1}, \\it{cf_3'})\\in R$.\nFollowing the reasoning for the first case, each transition~$\\it{cf_1} \\TextModelRelation{l} \\it{cf_2}$ either corresponds to a transition~$\\it{cf_3'} \\TextModelRelation{l} \\it{cf_4'}$ with~$(\\it{cf_2}, \\it{cf_4'})\\in R$ or two transitions~$\\it{cf_3'} \\TextModelRelation{\\tau} \\it{cf_4'}$ and~$\\it{cf_4'} \\TextModelRelation{l} \\it{cf_5'}$ with~$(\\it{cf_1}, \\it{cf_4'}) \\in R$ and~$(\\it{cf_2}, \\it{cf_5'}) \\in R$.\n\n\\item\nWe assume that $(\\it{cf_1}, \\it{cf_1'})\\in R$ according to the fourth condition stated above.\nIf transition~$\\it{cf_1} \\TextModelRelation{l} \\it{cf_2}$ is the result of behavior of state machine~$\\it{sm_2}$ or state machines that are unaffected by the transformation, then $\\it{cf'_1} \\TextModelRelation{l} \\it{cf'_2}$ and~$(\\it{cf_2}, \\it{cf_2'})\\in R$.\nOtherwise, according to the SOS rules for asynchronous communication,\nstate machine~$\\it{sm_1}$ can make a transition from a state~$\\it{sn^s_{sgn}}$ to a state~$\\it{sn^s_2}$ and receive the signal sent over channel~$\\it{chan'}$, resulting in a transition~$\\it{cf'_1} \\TextModelRelation{\\tau} \\it{cf'_2}$,\nwhere the label~$\\tau$ is the result of renaming the label~$\\textbf{receive}\\ \\it{sgn_2}()$, and~$\\it{sgn_2} \\equiv ``a\\_\" + \\it{sgn}$.\nAccording to the first condition, $(\\it{cf_1}, \\it{cf_2'})\\in R$.\nFollowing a similar reasoning as in the case discussed above, transition~$\\it{cf_1} \\TextModelRelation{l} \\it{cf_2}$ can be mimicked from configuration~$\\it{cf'_2}$.\n\\end{enumerate}\n\n\\noindent\nSecond, we consider the case in which $(\\it{cf_1}, \\it{cf_1'})\\in R$ and $\\it{cf_1'} \\TextModelRelation{l} \\it{cf_2'}$.\nWe distinguish four cases.\n\\begin{enumerate}\n\\item\nWe assume that $(\\it{cf_1}, \\it{cf_1'})\\in R$ according to the first condition stated above.\nIf~$\\it{cf_1'} \\TextModelRelation{\\tau} \\it{cf_2'}$, then this transition must be the result of a transition of state machine~$\\it{sm_1}$ from a state~$\\it{sn^s_1}$ to a state~$\\it{sn^s_{sgn}}$, and the label~$\\tau$ must be the result of renaming the label~$\\textbf{send}\\ \\it{sgn_1}$, where~$\\it{sgn_1} \\equiv ``s\\_\" + \\it{sgn}$.\nIn that case, $(\\it{cf_1}, \\it{cf_2'})\\in R$ according to the second condition.\nOtherwise, the transition~$\\it{cf_1'} \\TextModelRelation{\\it{l}} \\it{cf_2'}$ is the result of behavior of state machine~$\\it{sm_2}$ or one of the state machines that are unaffected by the transformation.\nIn that case, the corresponding transition~$\\it{cf_1} \\TextModelRelation{l} \\it{cf_2}$ must also exist for the original model, and~$(\\it{cf_2}, \\it{cf_2'})\\in R$ holds according to the first condition.\n\n\\item\nWe assume that $(\\it{cf_1}, \\it{cf_1'})\\in R$ according to the second condition stated above.\nIf~$\\it{cf_1'} \\TextModelRelation{\\it{sgn}()} \\it{cf_2'}$, then this transition must be the result of a transition of state machine~$\\it{sm_2}$ from a state~$\\it{sn^r_1}$ to a state~$\\it{sn^r_{sgn}}$, and the label~$\\it{sgn}()$ must be the result of renaming the label~$\\textbf{receive}\\ \\it{sgn_1}$, where~$\\it{sgn_1} \\equiv ``s\\_\" + \\it{sgn}$.\nIn that case, $\\it{cf_1'} \\TextModelRelation{\\it{sgn}()} \\it{cf_2'}$ and~$(\\it{cf_2}, \\it{cf_2'})\\in R$ according to the third condition.\nIf this is not the case, then the transition~$\\it{cf_1'} \\TextModelRelation{\\it{l}} \\it{cf_2'}$ is the result of behavior of state machine~$\\it{sm_2}$ that is unaffected by the transformation or behavior of one of the state machines that are unaffected by the transformation.\nIn that case, the corresponding transition~$\\it{cf_1} \\TextModelRelation{l} \\it{cf_2}$ must also exist for the original model, and~$(\\it{cf_2}, \\it{cf_2'})\\in R$ holds according to the second condition.\n\n\\item\nWe assume that $(\\it{cf_1}, \\it{cf_1'})\\in R$ according to the third condition stated above.\nIf~$\\it{cf_1'} \\TextModelRelation{\\tau} \\it{cf_2'}$, then this transition must be the result of a transition of state machine~$\\it{sm_2}$ from a state~$\\it{sn^r_{sgn}}$ to a state~$\\it{sn^r_2}$, and the label~$\\tau$ must be the result of renaming the label~$\\textbf{send}\\ \\it{sgn_2}$, where~$\\it{sgn_2} \\equiv ``a\\_\" + \\it{sgn}$.\nIn that case, $(\\it{cf_1}, \\it{cf_2'})\\in R$ according to the fourth condition.\nOtherwise, the transition~$\\it{cf_1'} \\TextModelRelation{\\it{l}} \\it{cf_2'}$ is the result of behavior one of the state machines that are unaffected by the transformation.\nIn that case, the corresponding transition~$\\it{cf_1} \\TextModelRelation{l} \\it{cf_2}$ must also exist for the original model, and~$(\\it{cf_2}, \\it{cf_2'})\\in R$ holds according to the third condition.\n\n\\item\nWe assume that $(\\it{cf_1}, \\it{cf_1'})\\in R$ according to the fourth condition stated above.\nIf~$\\it{cf_1'} \\TextModelRelation{\\tau} \\it{cf_2'}$, then this transition must be the result of a transition of state machine~$\\it{sm_1}$ from a state~$\\it{sn^s_{sgn}}$ to a state~$\\it{sn^s_2}$, and the label~$\\tau$ must be the result of renaming the label~$\\textbf{receive}\\ \\it{sgn_2}$, where~$\\it{sgn_2} \\equiv ``a\\_\" + \\it{sgn}$.\nIn that case, $(\\it{cf_1}, \\it{cf_2'})\\in R$ according to the first condition.\nOtherwise, the transition~$\\it{cf_1'} \\TextModelRelation{\\it{l}} \\it{cf_2'}$ is the result of behavior of state machine~$\\it{sm_2}$ that is unaffected by the transformation or behavior of one of the state machines that are unaffected by the transformation.\nIn that case, the corresponding transition~$\\it{cf_1} \\TextModelRelation{l} \\it{cf_2}$ must also exist for the original model, and~$(\\it{cf_2}, \\it{cf_2'})\\in R$ holds according to the fourth condition.\n\n\\end{enumerate} ", "meta": {"hexsha": "06e07e8b2798c4231fb7fca6553c010a86de57bf", "size": 22650, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "proof/proof.tex", "max_stars_repo_name": "ljpengelen/latex-phd-thesis", "max_stars_repo_head_hexsha": "8cabcf160a6f06e12b5ced92bb5cec06983e5bb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-18T21:53:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-18T21:53:57.000Z", "max_issues_repo_path": "proof/proof.tex", "max_issues_repo_name": "ljpengelen/latex-phd-thesis", "max_issues_repo_head_hexsha": "8cabcf160a6f06e12b5ced92bb5cec06983e5bb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "proof/proof.tex", "max_forks_repo_name": "ljpengelen/latex-phd-thesis", "max_forks_repo_head_hexsha": "8cabcf160a6f06e12b5ced92bb5cec06983e5bb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 91.7004048583, "max_line_length": 437, "alphanum_fraction": 0.6897571744, "num_tokens": 7884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3330770175053749}}
{"text": "\\section{\\toolname}\\label{sec:liquidhaskell}\n\\begin{figure}[t!]\n\\centering\n\\captionsetup{justification=centering}\n\\noindent\\makebox[\\textwidth]{\\includegraphics[width=\\textwidth]{text/realworldhaskell/liquidHaskell}}\n\\caption{\\toolname Workflow.}\n\t\\label{fig:internals}\n\\end{figure}\n% \n% link for workflow\n% https://www.draw.io/#G0Bwp_mIorSVqJb2RENnNVWVlQTmc\n%\nWe start with a short description of the \\toolname workflow,\nsummarized in Figure~\\ref{fig:internals} and continue with an \nexample driven overview of how properties are specified\nand verified using the tool. \n\n% \\mypara{Usage} \n\\mypara{Source}\n\\toolname can be run from the command-line\\footnote{\\url{https://hackage.haskell.org/package/liquidhaskell}}\nor within a web-browser\\footnote{\\url{http://goto.ucsd.edu/liquid/haskell/demo/}}.\nIt takes as \\emph{input}:\n%\n(1)~a single Haskell \\emph{source} file with code and refinement\n    type specifications including refined datatype definitions, \n    measures (\\S~\\ref{sec:tool:measures}), predicate and type \n    aliases, and function signatures;\n%\n(2)~a set of directories containing \\emph{imported modules} \n    (including the \\verb+Prelude+) which may themselves \n    contain specifications for exported types and functions; and\n%\n(3)~a set of predicate fragments called \\emph{qualifiers},\n    which are used to infer refinement types. This set is \n    typically empty as the default set of qualifiers extracted \n    from the type specifications suffices for inference.\n\n\\mypara{Core}\n\\toolname uses GHC to reduce the source to the Core IL~\\cite{SulzmannCJD07}\nand, to facilitate source-level error reporting, creates a map from Core \nexpressions to locations in the Haskell source.\n\n\\mypara{Constraints}\nThen, it uses the abstract interpretation framework of Liquid Typing~\\cite{LiquidPLDI08}, \nmodified to ensure soundness under lazy evaluation~\\ref{chapter:refinedhaskell}\nand extended with Abstract~\\ref{chapter:abstractrefinements}\nand Bounded~\\ref{boundedrefinements} Refinement Types\nand Refinement Reflection~\\ref{refinementrflection},\nto generate logical constraints from the Core IL.\n     \n\\mypara{Solution}\nNext, it uses a fixpoint algorithm (from~\\citep{LiquidPLDI08})\ncombined with an SMT solver to solve the constraints, and hence \ninfers a valid refinement typing for the program. \n%\n\\toolname can use any solver that implements the SMT-LIB2\nstandard~\\cite{SMTLIB2}, including Z3~\\citep{z3}, CVC4~\\citep{CVC4}, and\nMathSat~\\citep{MathSat}.\n\n \n\\mypara{Types \\& Errors}\n% \\NV{satisfiability and validity refer to different things here, \n% which is confusing...}\nIf the set of constraints is satisfiable, then \\toolname outputs \n\\textsc{Safe}, meaning the program is verified.\nIf instead, the set of constraints is not satisfiable, then \\toolname\noutputs \\textsc{Unsafe}, and uses the invalid constraints to \nreport refinement type errors at the \\emph{source positions}\nthat created the invalid constraints, using the location \ninformation to map the invalid constraints to source positions.\n%\nIn either case, \\toolname produces as output a source map\ncontaining the \\emph{inferred} types for each program \nexpression, which, in our experience, is crucial for \ndebugging the code and the specifications.\n\n%\\mypara{Optional Typing}\n%\n\\toolname is best thought of as an \\emph{optional} type checker\nfor Haskell. By optional we mean that the refinements have \\emph{no} \ninfluence on the dynamic semantics, which makes it easy to apply \n\\toolname to \\emph{existing} libraries.\n%\nTo emphasize the optional nature of refinements and preserve \ncompatibility with existing compilers, all specifications \nappear within comments of the form \\verb|{-@ ... @-}|, \nwhich we omit below for brevity.\n\n\\subsection{Specifications}\n\nA refinement type is a Haskell type where each component\nof the type is decorated with a predicate from a (decidable)\nrefinement logic. We use the quantifier-free logic of equality, \nuninterpreted functions and linear arithmetic (QF-EUFLIA)~\\cite{Nelson81}. \nFor example,\n%\n\\begin{code}\n   {v:Int | 0 <= v && v < 100}\n\\end{code}\n%\ndescribes @Int@ values between @0@ and @100@.\n\n\\mypara{Type Aliases} For brevity and readability, it is often convenient \nto define abbreviations for particular refinement predicates and types.\nFor example, we can define an alias for the above predicate\n%\n\\begin{code}\n  predicate Btwn Lo N Hi = Lo <= N && N < Hi\n\\end{code}\n%\nand use it to define a \\emph{type alias}\n%\n\\begin{code}\n  type Rng Lo Hi = {v:Int | Btwn Lo v Hi} \n\\end{code}\n%\nWe can now describe the above integers as @(Rng 0 100)@.\n\n\\mypara{Contracts} \nTo describe the desired properties of a function, we need\nsimply refine the input and output types with predicates \nthat respectively capture suitable pre- and post-conditions. \nFor example,\n%\n\\begin{code}\n  range :: lo:Int -> hi:{Int | lo <= hi} -> [(Rng lo hi)]\n\\end{code}\n%\nstates that @range@ is a function that takes two @Int@s \nrespectively named @lo@ and @hi@ and returns a list of @Int@s \nbetween @lo@ and @hi@. There are three things worth\nnoting.\n%\nFirst, we have binders to name the function's \\emph{inputs} \n(\\eg @lo@ and @hi@) and can use the binders inside the \nfunction's \\emph{output}.\n%\nSecond, the refinement in the \\emph{input} type describes the \n\\emph{pre-condition} that the second parameter @hi@ cannot \nbe smaller than the first @lo@.\n%\nThird, the refinement in the \\emph{output} type describes the\n\\emph{post-condition} that all returned elements are between \nthe bounds of @lo@ and @hi@.\n\n\n\\subsection{Verification}\\label{sec:tool:verification}\n\nNext, consider the following implementation for @range@:\n%\n\\begin{code}\n  range lo hi \n    | lo <= hi  = lo : range (lo + 1) hi\n    | otherwise = []\n\\end{code}\n%\nWhen we run \\toolname on the above code, it reports an \nerror at the definition of @range@. This is unpleasant! \nOne way to debug the error is to determine what type has\nbeen \\emph{inferred} for @range@, \\eg by hovering the \nmouse over the identifier in the web interface. \nIn this case, we see that the output type is essentially:\n%\n\\begin{code}\n  [{v:Int | lo <= v && v <= hi}]\n\\end{code}\n%\nwhich indicates the problem. There is an \\emph{off-by-one} \nerror due to the problematic guard. If we replace the second @<=@ \nwith a @<@ and re-run the checker, the function is verified.\n\n\\mypara{Holes} It is often cumbersome to specify the Haskell\ntypes, as those can be gleaned from the regular type signatures \nor via GHC's inference. Thus, \\toolname allows the user to leave \nholes in the specifications. Suppose @rangeFind@ has type \n%\n\\begin{code}\n  (Int -> Bool) -> Int -> Int -> Maybe Int\n\\end{code}\n%\nwhere the second and third parameters define a range. \nWe can give @rangeFind@ a refined specification:\n%\n\\begin{code}\n  _ -> lo:_ -> hi:{Int | lo <= hi} -> Maybe (Rng lo hi)\n\\end{code}\n%\nwhere the @_@ is the unrefined Haskell type for the \ncorresponding position in the type.\n\n\\mypara{Inference} Next, consider the implementation\n%\n\\begin{code}\n  rangeFind f lo hi = find f $ range lo hi \n\\end{code}\n%$\nwhere @find@ from @Data.List@ has the (unrefined) type\n%\n\\begin{code}\n  find :: (a -> Bool) -> [a] -> Maybe a\n\\end{code}\n%\n\\toolname uses the abstract interpretation framework of \nLiquid Typing~\\cite{LiquidPLDI08} to infer that the type\nparameter @a@ of @find@ can be instantiated with @(Rng lo hi)@\nthereby enabling the automatic verification of @rangeFind@.\n\nInference is crucial for automatically synthesizing types\nfor polymorphic instantiation sites -- note there is another\ninstantiation required at the use of the apply operator \n@dollar@ --  and to relieve the programmer of the tedium of %$\nspecifying signatures for all functions. \n%\nOf course, for functions exported by the module,\nwe must write signatures to specify preconditions -- otherwise, \nthe system defaults to using the trivial (unrefined) Haskell \ntype as the signature \\ie, checks the implementation assuming \narbitrary inputs.\n\n\\subsection{Measures}\\label{sec:tool:measures}\nSo far, the specifications have been limited to comparisons and \narithmetic operations on primitive values. \nWe use \\emph{measure functions}, or just measures, to \nspecify \\emph{inductive properties} of algebraic data types. \n%\nFor example, we define a measure @len@ to write properties about the number\nof elements in a list.\n%\n\\begin{code}\n  measure len :: [a] -> Int\n  len []      = 0\n  len (x:xs)  = 1 + (len xs)\n\\end{code}\n%\nMeasure definitions are \\emph{not} arbitrary Haskell code but a very \nrestricted subset~\\ref{sec:measures}.\nEach measure has a single equation per constructor that defines the\nvalue of the measure for that constructor. The right-hand side of the \nequation is a term in the restricted refinement logic. Measures are \ninterpreted by generating refinement types for the corresponding \ndata constructors.\n%\nFor example, from the above, \\toolname derives the \nfollowing types for the list data constructors:\n%\n\\begin{code}\n  []  :: {v:[a]| len v = 0}\n  (:) :: _ -> xs:_ -> {v:[a]| len v = 1 + len xs}\n\\end{code}\n%\nHere, @len@ is an \\emph{uninterpreted function} in the refinement logic.\nWe can define multiple measures for a type; \\toolname simply conjoins\nthe individual refinements arising from each measure to obtain a single\nrefined signature for each data constructor.\n\n\\mypara{Using Measures}\nWe use measures to write specifications about algebraic types. \nFor example, we can specify and verify that: \n%\n\\begin{code}\n  append :: xs:[a] -> ys:[a] \n         -> {v:[a]| len v = len xs + len ys}\n\n  map    :: (a -> b) -> xs:[a] \n         -> {v:[b]| len v = len xs} \n\n  filter :: (a -> Bool) -> xs:[a] \n         -> {v:[a]| len v <= len xs}\n\\end{code}\n\n\\mypara{Propositions} \n%%In addition to allowing the specification of structural features like\n%%lengths, heights and so on, \nMeasures can be used to encode sophisticated \ninvariants about algebraic data types.\n%\nTo this end, the user can write a measure whose output has a special type \n@Prop@ denoting propositions in the refinement logic. For instance, we can\ndescribe a list that contains a @0@ as:\n%\n\\begin{code}\n  measure hasZero :: [Int] -> Prop\n  hasZero []      = false\n  hasZero (x:xs)  = x == 0 || hasZero xs\n\\end{code}\n%\nWe can then define lists containing a @0@ as:\n%\n\\begin{code}\n  type HasZero = {v : [Int] | hasZero v } \n\\end{code}\n%\nUsing the above, \\toolname will accept \n%\n\\begin{code}\n  xs0 :: HasZero \n  xs0 = [2,1,0,-1,-2]\n\\end{code}\n%\nbut will reject\n%\n\\begin{code}\n  xs' :: HasZero \n  xs' = [3,2,1]\n\\end{code}\n\n\n\n\\subsection{Refined Data Types}\n\nOften, we require that \\emph{every} instance of a type satisfies some invariants. \nFor example, consider a @CSV@ data type, that represents tables:\n%\n\\begin{code}\n  data CSV a = CSV { cols :: [String]\n                   , rows :: [[a]]    }\n\\end{code}\n%\n% With \\toolname we can enforce the invariant that for every @CSV@ table, \n% with a number of columns given by @dim@,\n% each row has @dim@ elements,\n% with the below refined data type definition\n%%With \\toolname we can enforce the invariant that every @CSV@ table \n%%has the number of columns given by @dim@, and that each row has \n%%@dim@ elements with a refined data type definition, such as:\nWith \\toolname we can enforce the invariant that every row in a @CSV@ table\nshould have the same number of columns as there are in the header\n%\n\\begin{code}\n  data CSV a = CSV { cols :: [String]  \n                   , rows :: [ListL a cols] }\n\\end{code}\n%\nusing the alias\n%\n\\begin{code}\n  type ListL a X = {v:[a]| len v = len X}\n\\end{code}\n%\nA refined data definition is \\emph{global} in that \\toolname \nwill reject any @CSV@-typed expression that does not respect \nthe refined definition. For example, both of the below \n%\n\\begin{code}\n  goodCSV = CSV [  \"Month\", \"Days\"] \n                [ [\"Jan\"  , \"31\"]\n                , [\"Feb   , \"28\"]\n                , [\"Mar\"  , \"31\"] ]\n\n  badCSV  = CSV [  \"Month\", \"Days\"] \n                [ [\"Jan\"  , \"31\"]\n                , [\"Feb   , \"28\"]\n                , [\"Mar\"        ] ]\n\\end{code}\n%\nare well-typed Haskell, but the latter is rejected by \\toolname.\n%\nLike measures, the global invariants are enforced by refining \nthe constructors' types. \n\n\\subsection{Refined Type Classes}\\label{sec:type-classes}\n\nNext, let us see how \\toolname allows verification of\nprograms that use ad-hoc polymorphism via type classes.\n%\nWhile the implementation of each typeclass instance is \ndifferent, there is often a common interface that \nall instances should satisfy.\n\n\\mypara{Class Measures}\nAs an example, consider the class definition\n%\n\\begin{code}\n  class Indexable f where\n    size :: f a -> Int\n    at   :: f a -> Int -> a\n\\end{code}\n%\nFor safe access, we might require that @at@'s second \nparameter is bounded by the @size@ of the container.\nTo this end, we define a \\emph{type-indexed} \nmeasure, using the @class measure@ keyword\n%\n\\begin{code}\n  class measure sz :: a -> Nat\n\\end{code}\n%\nNow, we can specify the safe-access precondition  \nindependent of the particular instances of @Indexable@:\n%\n\\begin{code}\n  class Indexable f where\n    size :: xs:_ -> {v:Nat | v = sz xs}\n    at   :: xs:_ -> {v:Nat | v < sz xs} -> a\n\\end{code}\n\n\\mypara{Instance Measures}\nFor each concrete type that instantiates a class, we require \na corresponding definition for the measure. \nFor example, to define lists as an instance of @Indexable@, \nwe require the definition of the @sz@ instance for lists:\n%\n\\begin{code}\n  instance measure sz :: [a] -> Nat\n    sz []     = 0\n    sz (x:xs) = 1 + (sz xs)\n\\end{code}\n%\nClass measures work just like regular measures in that the above \ndefinition is used to refine the types of the list data constructors.\nAfter defining the measure, we can define the type instance as:\n%\n\\begin{code}\n  instance Indexable [] where\n    size []        = 0\n    size (x:xs)    = 1 + size xs\n\n    (x:xs) `at` 0  = x\n    (x:xs) `at` i  = index xs (i-1)\n\\end{code}\n%\n\\toolname uses the definition of @sz@ for lists to check that @size@ \nand @at@ satisfy the refined class specifications. \n% NV the dictionary relevant this were removed\n% , and hence, that \n% the above creates a valid instance dictionary for @Indexable@.\n\n\\mypara{Client Verification}\nAt the clients of a type-class we use the refined \ntypes of class methods. Consider a client of @Indexable@s:\n%\n\\begin{code}\n  sum :: (Indexable f) => f Int -> Int\n  sum xs = go 0 \n    where\n      go i | i < size xs = xs `at` i + go (i+1)\n           | otherwise   = 0\n\\end{code}\n%\n\\toolname proves that each call to @at@ is safe, by using the refined\nclass specifications of @Indexable@. \nSpecifically, each call to @at@ is guarded by a check @i < size xs@\nand @i@ is  increasing \nfrom 0, so \\toolname proves that @xs `at` i@ will always be safe.\n\n\\begin{comment}\n\\subsection{Abstracting Refinements}\n\nSo far, all the specifications have used \\emph{concrete} refinements. Often it is\nuseful to be able to \\emph{abstract} the refinements that appear in a\nspecification. For example, consider a monomorphic variant of @max@\n%\n\\begin{code}\n  max     :: Int -> Int -> Int \n  max x y = if x > y then x else y\n\\end{code}\n%\nWe would like to give @max@ a specification that lets us verify:\n%\n\\begin{code}\n  xPos  :: {v: _ | v > 0}\n  xPos  = max 10 13\n\n  xNeg  :: {v: _ | v < 0}\n  xNeg  = max (-5) (-8)\n\n  xEven :: {v: _ | v mod 2 == 0} \n  xEven = max 4 (-6)\n\\end{code}\n%\nTo this end, \\toolname allows the user to \\emph{abstract refinements} over\ntypes~\\cite{vazou13}, for example by typing @max@ as:\n%\n\\begin{code}\n max :: forall <p :: Int -> Prop>. \n          Int<p> -> Int<p> -> Int<p>\n\\end{code}\n%\nThe above signature states that for any refinement @p@, if the two\ninputs of @max@ satisfy @p@ then so does the output. \\toolname uses\nLiquid Typing to automatically instantiate @p@ with suitable concrete\nrefinements, thereby checking @xPos@, @xNeg@, and @xEven@.\n\n\n\\mypara{Dependent Composition}\nAbstract refinements turn out to be a surprisingly expressive and \nuseful specification mechanism. For example, consider the function \ncomposition operator:\n%\n\\begin{code}\n  (.) :: (b -> c) -> (a -> b) -> a -> c\n  (.) f g x = f (g x)  \n\\end{code}\n%\nPreviously, it was not possible to check, \\eg that:\n%\n\\begin{code}\n  plus3 :: x:_ -> {v:_ | v = x + 3}\n  plus3 = (+ 1) . (+ 2)\n\\end{code}\n%\nas the above required tracking the dependency between @a@, @b@ and @c@,\nwhich is crucial for analyzing idiomatic Haskell.\nWith abstract refinements, we can give the @(.)@ operator the type:\n%\n\\begin{code}\n  (.) :: forall < p :: b -> c -> Prop\n                , q :: a -> b -> Prop>.\n           f:(x:b -> c<p x>) \n        -> g:(x:a -> b<q x>) \n        -> y:a \n        -> exists[z:b<q y>].c<p z>\n\\end{code}\n%\nwhich gets automatically instantiated at usage sites, allowing \\toolname\nto precisely track invariants through the use of the ubiquitous \nhigher-order operator.\n\n\\mypara{Dependent Pairs}\nSimilarly, we can abstract refinements over the definition of datatypes.\n% Similarly, we can abstract refinements over the definition of datatypes.\nFor example, we can express dependent pairs in \\toolname by refining the \ndefinition of tuples as:\n%\n\\begin{code}\n  data Pair a b <p :: a -> b -> Prop> \n    = Pair { fst :: a, snd :: b<p fst>}\n\\end{code}\n%\nThat is, the refinement @p@ relates the @snd@ element with the @fst@.\nNow we can define increasing and decreasing pairs\n%\n\\begin{code}\n  type IncP = Pair <{\\x y -> x < y}> Int Int\n  type DecP = Pair <{\\x y -> x > y}> Int Int\n\\end{code}\n%\nand then verify that:\n%\n\\begin{code}\n  up :: IncP\n  up = Pair 2 5\n  \n  dn :: DecP\n  dn = Pair 5 2\n\\end{code}\n%\nNow that we have a bird's eye view of the various specification mechanisms\nsupported by \\toolname, let us see how we can profitably apply them to\nstatically check a variety of correctness properties in real-world codes.\n\\end{comment}\n%%% Local Variables: \n%%% mode: latex\n%%% TeX-master: \"main\"\n%%% End: \n", "meta": {"hexsha": "d158280574a39a9c73ebee57f1a2e72c2bcdc017", "size": 17853, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "text/realworldhaskell/tool.tex", "max_stars_repo_name": "nikivazou/thesis", "max_stars_repo_head_hexsha": "a12f2e857a358e3cc08b657bb6b029ac2d500c3b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2016-12-02T00:46:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-20T07:04:01.000Z", "max_issues_repo_path": "text/realworldhaskell/tool.tex", "max_issues_repo_name": "nikivazou/thesis", "max_issues_repo_head_hexsha": "a12f2e857a358e3cc08b657bb6b029ac2d500c3b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "text/realworldhaskell/tool.tex", "max_forks_repo_name": "nikivazou/thesis", "max_forks_repo_head_hexsha": "a12f2e857a358e3cc08b657bb6b029ac2d500c3b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-12-02T00:46:51.000Z", "max_forks_repo_forks_event_max_datetime": "2016-12-02T00:46:51.000Z", "avg_line_length": 32.1097122302, "max_line_length": 108, "alphanum_fraction": 0.7044194253, "num_tokens": 4967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.33307701001008394}}
{"text": "%!TEX root = morusAC.tex\n\n%\\pagebreak[4]\n\n\\section{Discussion}\n\\label{sec/Discussion}\n\n%This is just a sketch for now...\n\nWe now discuss the impact of these attacks on the security of \\MORUS.\n\n\\subsubsection{Keystream correlation.}\n\nWe emphasize that the correlation we uncover between plaintext and ciphertext bits is\n\\emph{absolute}, in the sense that it does not depend on the encryption\nkey, or on the nonce.  This is the same situation as the keystream correlations\nin AEGIS~\\cite{sacryptMinaud14}.  As such, they can be leveraged to\nmount an attack in the broadcast setting, where the same message is\nencrypted multiple times with different IVs and potentially different\nkeys~\\cite{DBLP:conf/fse/MantinS01}.  In particular, the broadcast setting appears\nin practice in man-in-the-browser attacks against HTTPS connections\nfollowing the BEAST model~\\cite{duong2011here}.  In this scenario, an\nattacker uses Javascript code running in the victim's browser (by\ntricking the victim to visit a malicious website) to generate a large\nnumber of request to a secure website.  Because of details of the HTTP\nprotocol, each request includes an authentication token to identify the\nuser, and the attacker can target this token as a repeated plaintext.\nConcretely, correlations in the RC4 keystream have been exploited in this\nsetting, leading to the recovery of authentication cookies in\npractice~\\cite{DBLP:conf/uss/AlFardanBPPS13}.\n\n\\subsubsection{Data complexity.}\n\nThe design document of \\cipher{MORUS} imposes a limit of $2^{64}$\nencrypted blocks for a given key. However, since our attack is\nindependent of the encryption key, and hence immune to rekeying, this\nlimitation does not apply: all that matters for our attack is that the\nsame plaintext be encrypted enough times.\n\nWith the trail presented in this work, the data complexity is clearly\nout of reach in practice, since exploiting the correlation would require\n$2^{152}$ encrypted blocks for \\cipher{MORUS1280}, and $2^{146}$\nencrypted blocks for \\cipher{MORUS640}. The data complexity could be\nslightly lowered by leveraging multilinear cryptanalysis; indeed, the\ntrail holds for any bit shift, and if we assume independence, we could\nrun $w$ copies of the trail in parallel on the same encrypted blocks\n(recall that $w$ is the word size, and the trail is invariant by\nrotation by $w$ bits). This would save a factor $2^5$ on the data\ncomplexity for \\cipher{MORUS640}, and $2^6$ for \\cipher{MORUS1280}; but\nthe resulting complexity is still out of reach.\n\nHowever, \\cipher{MORUS1280} with a 256-bit key claims a security level\nof 256 bits for confidentiality, and an attack with complexity $2^{152}$\nviolates this claim, even if it is not practical.  \n\n\\subsubsection{Design considerations.}\nThe existence of this trail does hint at some weakness in the\ndesign of \\cipher{MORUS}. Indeed, a notable feature of the trail is that\nthe values of rotation constants are mostly irrelevant: a similar trail\nwould exist for most choices of the constants. That it is possible to\nbuild a trail that ignores rotation constants may be surprising. This\nwould have been prevented by adding a word-wise rotation to one of the\nstate registers at the input of the ciphertext equation.\n\n%%% Local Variables:\n%%% TeX-master: \"morusAC\"\n%%% End:\n", "meta": {"hexsha": "2f005184284defc1aed03a37d1258f3769f626ce", "size": 3284, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "morusAC_06_Discussion.tex", "max_stars_repo_name": "ildyria/MiniMorus", "max_stars_repo_head_hexsha": "168b27e059a46714bfe86af0cead20b4f6a51fcb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "morusAC_06_Discussion.tex", "max_issues_repo_name": "ildyria/MiniMorus", "max_issues_repo_head_hexsha": "168b27e059a46714bfe86af0cead20b4f6a51fcb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "morusAC_06_Discussion.tex", "max_forks_repo_name": "ildyria/MiniMorus", "max_forks_repo_head_hexsha": "168b27e059a46714bfe86af0cead20b4f6a51fcb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.2941176471, "max_line_length": 85, "alphanum_fraction": 0.7901948843, "num_tokens": 798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.33307701001008394}}
{"text": "\\section{Machine learning approach}\nML techniques in SHM were heavily utilised by researchers for damage detection~\\cite{Doebling1998, alvandi2006assessment, fan2011vibration, raghavan2008effects, su2009identification, Mitra2016}.\nMoreover, machine learning techniques attempt to map the patterns of the input data acquired by sensors to output targets for a damage estimation at different levels ~\\cite{rytter1993vibrational}.\nAccordingly, ML techniques demands high domain knowledge of the examiner to perform hand-crafted damage-sensitive feature extraction on the raw data acquired by sensors before being fed into a suitable ML model.\nGenerally, the process of damage-sensitive features extraction (hand-crafted) in the field of SHM emerged due to the enormous development in the physics-based SHM techniques such as modal strain energy (MSE)~\\cite{Kim}, modal curvature (MC)~\\cite{Wahab}, modal assurance criterion (MAC), and Coordinate (MAC)~\\cite{Allemang2003}, modal flexibility (MF)~\\cite{Jaishi}, damage locating vector (DLV)~\\cite{Bernal2002}, wavelet transform~\\cite{Staszewski,Kima} and probabilistic reconstruction algorithm (PRA)~\\cite{Hay2006} among others.\n\nIn this section, we are going to describe several feature extraction techniques and classification models used with machine learning utilised for structural damage detection.\nThese algorithms are suitable for scenarios where the sensitive damage features obtained from the structural responses are affected by the changes that occur due to the operational and environmental variability and the changes made by the damage.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Feature extraction techniques}\n\\subsubsection{Principal component analysis}\nPCA is a popular method used for damage identification in SHM.\nFurther, PCA shows a solid and efficient performance in feature extraction, and structural damage detection~\\cite{liu2014research, wang2014principal, nguyen2010fault}. \nBesides, PCA proves to be an effective tool to improve the training efficiency and enhance the classification accuracy for other ML algorithms, such as unsupervised learning methods~\\cite{liu2019rapid, datteo2017statistical, torres2014data}. \n\nPCA is dimensionality reduction technique utilised to reduce the dimensionality of large data (input space) into a lower dimension (feature space) through transforming a large set of variables into a smaller one with minimal loss information~\\cite{Jolliffe2002}.\nMoreover, PCA can be utilised for damage detection by eliminating noise and obtaining sensitive features of damage as eigenvectors.\nThe PCA technique is illustrated below.\nIn the beginning, a matrix \\(U(t)\\) is constructed as shown in Eqn. \\ref{U(t)}, which contains all registered data with time histories.\n\\begin{equation}\n\tU(t)=\n\t\\begin{bmatrix}\n\t\tu_1{(t1)}       & u_2{(t1)} & \\dots & u_M{(t1)} \\\\\n\t\tu_1{(t2)}       & u_2{(t2)} & \\dots & u_M{(t2)} \\\\\n\t\t\\vdots \t\t\t& \\vdots \t& \\ddots & \\vdots \\\\\n\t\tu_1{(t_N)}      & u_2{(t_N)} & \\dots & u_M{(t_N)}\n\t\\end{bmatrix}\\ ,\n\t\\label{U(t)}\n\\end{equation}\nwhere \\(t\\) corresponds to the time, \\(u_i\\ (i = 1, 2, ..., M)\\) represents to the response from the \\(i-th\\) sensor installed in the monitored structure, \\(M\\) represents the total number of sensors, \\(t_j\\ (j = 1, 2, ..., N)\\) represents the \\(j-th\\) time step of the data registering and \\(N\\) is the total time observations during monitoring.\nAdditionally, each column represents data registration of one sensor.\nThe next step is to normalise the time series of each sensor data registrations by subtracting the mean value shown in Eqn.~\\ref{mean value}:\n\\begin{equation}\n\t\\bar{u_i} = \\frac{1}{N}\\sum_{j=1}^{N}u_i(t_j)\\ ,\n\t\\label{mean value}\n\\end{equation}\nEquation~\\ref{normalised matrix} represents the normalised matrix.\n\\begin{equation}\n\tU'(t)=\n\t\\begin{bmatrix}\n\t\tu_1{(t1)}-\\bar{u_1}       & u_2{(t1)}-\\bar{u_2} & \\dots  & u_M{(t1)}-\\bar{u_M} \\\\\n\t\tu_1{(t2)}-\\bar{u_1}       & u_2{(t2)}-\\bar{u_2} & \\dots  & u_M{(t2)}-\\bar{u_M} \\\\\n\t\t\\vdots \t\t\t\t\t  & \\vdots \t  \t\t\t& \\ddots & \\vdots \\\\\n\t\tu_1{(t_N)}-\\bar{u_1}      & u_2{(t_N)}-\\bar{u_2}& \\dots  & u_M{(t_N)}-\\bar{u_M}\n\t\\end{bmatrix}\n\t\\label{normalised matrix}\n\\end{equation}\nAfter computing the normalised matrix, the covariance matrix is computed as shown in Eqn.~\\ref{covariance}:\n\\begin{equation}\n\tC = \\frac{1}{M}U'^TU' \\ ,\n\t\\label{covariance}\n\\end{equation}\nNext, the eigenvalue and the corresponding eigenvector of the covariance matrix are computed through solving the following equation~\\ref{eigvalue}:\n\\begin{equation}\n\t(C-\\lambda_iI)\\psi_i =0 \\ ,\n\t\\label{eigvalue}\n\\end{equation}\nwhere \\(I\\) represents the \\(M\\times M\\) identity matrix, \\(\\psi_i = [\\psi_{i,1},\\psi_{i,2}, \\hdots, \\psi_{i,j}]^T\\) in which \\(\\psi_{i,j}(j=1, 2, \\hdots, M)\\) is the element related to the \\(j-th\\) sensor.\nUsually, eigenvalues are sorted into decreasing order, particularly \\(\\lambda_1>\\lambda_2>\\hdots>\\lambda_M\\). \nThen, the first eigenvector \\(\\psi_1\\) corresponding to \\(\\lambda_1\\) holds the greatest variance and consequently holds the most important information for the original matrix U. \nThe first few principal components hold most of the variance, whereas the remaining less important components involve the measurement of noise.\nAccordingly, the first few eigenvectors are utilised as sensitive features for damage detection and localisation.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Mahalanobis squared distance}\nMSD is an effective multivariate distance measuring technique in which it measures the distance between a point and a distribution.\nTherefore, MSD is utilised with multivariate statistics outlier detection~\\cite{Worden2000}.\nAssuming \\(X\\) to be a training set with data acquired when the undamaged structure is under environmental and/or operational variations (EOVs) with multivariate mean vector \\(\\mu\\) and covariance matrix \\(\\Sigma\\)~\\cite{Farrar2013}.\nAccordingly, the damage index \\((DI_i)\\) between feature vectors from training set \\(X\\) and any new feature vector from the test matrix \\(Z\\) is calculated using Eqn.~\\ref{msd}.\n\\begin{equation}\n\tDI_i = (z_i-\\mu)\\Sigma^{-1}(z_i-\\mu)^T\n\t\\label{msd}\n\\end{equation}\nwhere \\(z_i\\) is a tested feature vector.\nThe performance of this technique mainly relies on acquiring all likely EOVs in the training set~\n\\cite{Farrar2013}.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Gaussian mixture models}\nGMM is a clustering method commonly used with unsupervised learning, in which it aims to find main clusters of points in a dataset that share some common characteristics or features.\nAdditionally, GMM has also been referred to as Expectation-Maximization (EM) clustering that is based on the optimization strategy.\n%%%%%%%%%%\nThe damage detection is performed based on multiple MSD-based algorithms, in which the covariance matrices and mean vectors are functions of the main components.\n%%%%%%%%%%\nA GMM is defined as a superposition of K Gaussian distributions as shown in Eqn. \\ref{gmm}.\n\n\\begin{equation}\n\tp(x) = \\sum_{k=1}^K P(k) \\mathcal{N}(x|\\mu_k,\\Sigma_k) \n\t\\label{gmm}\n\\end{equation}\nwhere \\(x\\) represents the training samples in the dataset, and \\(P(k)\\) corresponds to the mixture proportion (contribution weight) of the \\(k-\\)th distribution, in which the mixture proportion must satisfy \\(0\\leq P(x)\\leq 1\\).\nThe sum of all mixture proportion satisfies the following Eqn.~\\ref{mixture}\n\\begin{equation}\n\t\\sum_{k=1}^{K}P(x) =1 \n\t\\label{mixture}\n\\end{equation}  \n\\(\\mathcal{N}(x|\\mu_k,\\Sigma_k)\\) refers to the conditional probability of the instance \\(x\\) for the \\(k-\\)th Gaussian distribution \\(\\mathcal{N}(\\mu_k,\\Sigma_k)\\) presented in Eqn.~\\ref{conditional}, where \\(\\mu_k\\) and \\(\\Sigma_k\\) are the mean and the covariance of that Gaussian distribution respectively.\n\\begin{equation}\n\t\\mathcal{N}(x|\\mu_k,\\Sigma_k) = \\frac{\\exp(-\\frac{1}{2}(x-\\mu_k)^T\\Sigma_k^{-1}(x-\\mu_k))}{(2\\pi)^{\\frac{d}{2}\\sqrt{\\det(\\Sigma_k)}}}\n\t\\label{conditional}\t\t\n\\end{equation}\nThe complete GMM is parameterized by the mean vectors, covariance matrices and the mixture weights from all component densities \\(\\{\\mu_k,\\Sigma_k, P(x)\\}_{k=1,\\hdots,K}\\).\n\nThe parameters can be carried out from the training data using the classical maximum likelihood estimator (CMLE) based on the EM algorithm~\\cite{Dempster1977}.\nDamage can be detected through estimating \\(k\\) \\(DIs\\) for each data sample \\(x\\) as shown in Eqn. \\ref{DIs}\n\\begin{equation}\n\tDI_q(x) = (x-\\mu_k)\\Sigma_k^{-1}(x-\\mu_k)^T\n\t\\label{DIs}\n\\end{equation}\nwhere \\(\\mu_k\\) and \\(\\Sigma_k\\) refers to all observations from the \\(k\\) data component.\nFor each observation the DI is given by the smallest DI estimated on each component as in Eqn. \\ref{DI}\n\\begin{equation}\n\tDI(x) = \\min[DI_k(x)]\n\t\\label{DI}\n\\end{equation}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Classification models}\n\\subsubsection{Support vector machine}\nSupport vector machine (SVM) is a supervised ML model that is utilised as a classification and regression tool.  \nThe idea behind SVM is to find an optimal hyperplane (e.g separate line) in N-dimensional space (N is the number of features) that separates the classes, furthermore, the aim of the hyperplane is to maximize the margin between the points on either side hence so called \\enquote{decision line/boundary}.\nFurthermore, when we try to separate two classes of data points, we could have many possible hyperplanes, however, our goal is to find the hyperplane that has the maximum margin (maximum distance between data points of both classes). \nFigure~\\ref{fig:SVM} shows SVM hyperplanes in 2D feature space and 3D feature space.\n\\begin{figure}[!h]\n\t\\begin{subfigure}[b]{0.49\\textwidth}\t\t\n\t\t\\centering\n\t\t\\includegraphics[width=.8\\linewidth]{figures/2d_svm.png}\n\t\t\\caption{Hyperplane 2D feature space } \n\t\t\\label{fig:2dsvm}\n\t\\end{subfigure}\n\t\\hfill\n\t\\begin{subfigure}[b]{0.49\\textwidth}\n\t\t\\centering\n\t\t\\includegraphics[width=1.0\\linewidth]{figures/3d_svm.png}\n\t\t\\caption{Hyperplane 3D feature space} \n\t\t\\label{fig:3dsvm}\n\t\\end{subfigure}\t\n\t\\caption{SVM for 2D and 3D feature space.}\n\t\\label{fig:SVM}\n\\end{figure}\n\n\\subsubsection{K-Nearest Neighbor}\nK-Nearest Neighbor (KNN) is a supervised ML technique utilized to perform classification tasks.\nKNN does not have a specialized training phase.\nIt saves all the training data and uses the entire training set for classifying a new data point, which adds time complexity at the testing time.\nMoreover, KNN is a non-parametric learning algorithm, which means it does not have any assumptions regarding the input data, which is useful considering the real-world data does not obey the typical theoretical assumptions such as linear separability, uniform distribution among others.\n\nIn the KNN technique, at the first, the distance between the new data point and the whole other data points is calculated.\nFurthermore, any distance method can be applied e.g. Euclidean, Manhattan, etc.\nAccordingly, it picks the K-nearest points, where K is an integer number (number of neighbors) that can be chosen in such a way the model will be able to predict new unseen data accurately. \nThen, it assigns the new data point to the class to which the majority of the K data points belong.\nIn Fig.~\\ref{fig:datapoints} shows initial data points (training set) before classification, and Fig.~\\ref{fig:KNN_K_5} shows the result of applying KNN techniques on the data points (3 classes) assuming \\(K=6\\).\n\\begin{figure}[!h]\n\t\\begin{subfigure}[b]{0.49\\textwidth}\t\t\n\t\t\\centering\n\t\t\\includegraphics[width=1\\linewidth]{figures/KNN_datapoints.png}\n\t\t\\caption{Data points } \n\t\t\\label{fig:datapoints}\n\t\\end{subfigure}\n\t\\hfill\n\t\\begin{subfigure}[b]{0.49\\textwidth}\n\t\t\\centering\n\t\t\\includegraphics[width=1.0\\linewidth]{figures/KNN_K_6.png}\n\t\t\\caption{3-Classes with \\(K=6\\)} \n\t\t\\label{fig:KNN_K_5}\n\t\\end{subfigure}\t\n\t\\caption{KNN algorithm: data classification with \\(K=6\\) .}\n\t\\label{fig:KNN}\n\\end{figure}\n\n\\subsubsection{Decision tree}\nDecision trees are supervised ML that is used in applications for classification and regression. \nAdditionally, decision trees are considered the bases for many other ML techniques such as random forests, bagging and boosted decision trees.\nThe idea of a decision tree is to represent the whole data as a tree where each internal node represents a test on an attribute (a decision rule) and each branch represents an outcome of the test, and finally each leaf node (terminal node) holds the label of the class.\n\nDecision tree can be divided into two categories:\n\\begin{enumerate}\n\t\\item Categorical variable decision trees: which includes categorical target variables that are divided into categories. A category means that the decision falls into one of the categories and there is no in-between such as (Yes/No category).\n\t\\item Continuous variable decision trees: which has a continuous target variable that can be predicted based on available information (e.g. crack length).\n\\end{enumerate}\nFigure~\\ref{fig:Decision_tree} presents a typical decision tree.\nAny decision tree has a root node where data input is carried through.\nFurthermore, the root node is split into sets of decision rules that result either in a leaf node which is a non-splitting node, or into another decision rule, creating what so-called a branch or sub-tree.\nIn case there are decision rules that can be eliminated from the tree, a process called \\enquote{pruning} is applied to minimize the complexity of the algorithm.\n\\begin{figure}[!h]\n\t\\begin{center}\n\t\t\\includegraphics[width=1.0\\linewidth]{figures/decision_tree.png}\n\t\\end{center}\n\t\\caption{Decision tree.}\n\t\\label{fig:Decision_tree}\n\\end{figure} \n", "meta": {"hexsha": "4477691b468a6ea1f9a2caddded29a0444f96d2b", "size": 13686, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "reports/monograph/Ijjeh/ChapterTwo/Machine_learning_approach.tex", "max_stars_repo_name": "IFFM-PAS-MISD/aidd", "max_stars_repo_head_hexsha": "9fb0ad6d5e6d94531c34778a66127e5913a3830c", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-03T05:36:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T05:36:07.000Z", "max_issues_repo_path": "reports/monograph/Ijjeh/ChapterTwo/Machine_learning_approach.tex", "max_issues_repo_name": "IFFM-PAS-MISD/aidd", "max_issues_repo_head_hexsha": "9fb0ad6d5e6d94531c34778a66127e5913a3830c", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "reports/monograph/Ijjeh/ChapterTwo/Machine_learning_approach.tex", "max_forks_repo_name": "IFFM-PAS-MISD/aidd", "max_forks_repo_head_hexsha": "9fb0ad6d5e6d94531c34778a66127e5913a3830c", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 72.4126984127, "max_line_length": 534, "alphanum_fraction": 0.7496711968, "num_tokens": 3629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3330770100100839}}
{"text": "\\section{Introduction}\nCommunity detection is an important topic in graph mining. By learning node community labels on the graph, we are able to detect node hidden attributes as well as explore the closeness between nodes \\cite{fortunato2010community}. Conventional methods are mostly user-independent to detect communities solely relying on graph topological structure \\cite{fortunato2016community}, generate semi-supervised communities with node constraints \\cite{jin2019graph}, or select top-K sub graphs as user-centric communities \\cite{li2015influential}. These approaches are no longer enough to satisfy users with a pursuit of personalization, which makes involving user need into community detection to become an inevitable task.\n\nFirst, user-independent approaches solely consider graph topological structure without user need. Second, semi-supervised approaches detect communities restricted by pre-selected seed nodes. As different user needs refer to different seeds, each individual user requires a separate process to run the whole model completely to get personalized communities, which is inapplicable in real cases. Third, sub-graph selection approaches only generate communities from the partial graph instead of the whole one.  \n\nTo detect personalized communities on the whole graph, I propose a \\textbf{g}enetic \\textbf{P}ersonalized \\textbf{C}ommunity \\textbf{D}etection (gPCD) model with an offline and an online step. Specifically, in the offline step, I convert the user-independent graph community to a binary community tree which is encoded with binary code. Subsequently, a deep learning method is utilized to learn low-dimensional embedding representations for both user need and nodes on the binary community tree. In the online step, I propose a genetic tree-pruning approach on the tree to detect personalized communities by maximizing user need and minimizing user searching cost simultaneously. The whole genetic approach runs in an iterative manner to simulate an evolutionary process and generate a number of partition candidates which are regarded as ``chromosomes'' in each genetic generation. Through the selection, cross-over and mutation process, successive chromosomes are bred as better personalized community partitions to meet with user need.\n", "meta": {"hexsha": "228911a78117ebc747682c2a3009a3473351f9b0", "size": 2289, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapter3/chapter3.1.tex", "max_stars_repo_name": "RoyZhengGao/thesis", "max_stars_repo_head_hexsha": "b73b473d5b8a5d948080420edeb899c60d88c9e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapter3/chapter3.1.tex", "max_issues_repo_name": "RoyZhengGao/thesis", "max_issues_repo_head_hexsha": "b73b473d5b8a5d948080420edeb899c60d88c9e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter3/chapter3.1.tex", "max_forks_repo_name": "RoyZhengGao/thesis", "max_forks_repo_head_hexsha": "b73b473d5b8a5d948080420edeb899c60d88c9e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 327.0, "max_line_length": 1038, "alphanum_fraction": 0.8309305374, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.33300472587591906}}
{"text": "\\documentclass[]{article}\n\\usepackage[margin=1.0in]{geometry}\n\\usepackage{amssymb}\n\n%title material\n\\title{Astronomy 400B Homework \\#5}\n\\author{Please Show Your Work for Full Credit}\n\\date{Due April 30, 2015 by 9:35am}\n\n\n%include latex definitions\n\\input{astro400B_definitions.tex}\n\n%begin the document\n\\begin{document}\n\n%make the title, goes after document begins\n\\maketitle\n\n\\section{Sparke \\& Gallagher Problem 8.7}\n\nThe quantity $\\ave{\\Delta_k^2}^{1/2}$ gives the expected fractional deviation\n$|\\delta(\\vx)|$ from the mean density in an overdense of diffuse region of\nsize $1/k$.  Write $\\delta(\\vx)$ and $\\Phi(\\vx)$ as Fourier transforms and\nuse Poisson's equation\n\\begin{equation}\n\\nabla^2 \\Phi(\\vx) = 4\\pi G \\rho(\\vx)\n\\end{equation}\n\\noindent\nto show that these lumps and voids cause fluctuations $\\Delta\\Phi_k$ in the\ngravitational potential, where $k^2|\\Delta\\Phi_k|\\sim4\\pi G\\bar{\\rho}\\ave{\\Delta_k^2}^{1/2}$.\nShow that, when $P(k)\\propto k$, the {\\it Harrison-Zel'dovich} spectrum, $|\\Delta\\Phi_k|$ does\nnot depend on $k$: the potential is equally `rippled' on all spatial scales.\n\n\\section{Sparke \\& Gallagher Problem 8.9}\n\nBy substituting into the equation\n\\begin{equation}\n\\ddot{R}(t) = -\\frac{4\\pi G}{3} R(t)\\left[ \\rho(t) + \\frac{3p(t)}{c^2}\\right]\n\\end{equation}\n\\noindent\nshow that, when vacuum energy dominates the expansion, we have $R(t) \\propto \\exp(t\\sqrt{\\Lambda/3})$.\n\n\\section{Sparke \\& Gallagher Problem 8.11}\n\nBlackbody radiation and relativistic particles provide most of the\nenergy density at $t\\ll t_{eq}$. Show that the equation\n\\begin{equation}\nH^2(t) = H_0^2[\\Omega_r(1+z)^4 + \\Omega_m(1+z)^3 + (1 -\\Omega_{tot})(1+z)^2 + \\Omega_{\\Lambda}]\n\\end{equation}\n\\noindent\nthen implies that $H(t)=1/(2t)$. Early on, the leftmost term of the\nequation\n\\begin{equation}\n\\frac{kc^2}{R^2(t_0)} = H_0^2(1-\\Omega_{tot}) = a^2(t)\\left[H^2(t) - \\frac{8\\pi G}{3} \\rho(t)\\right]\n\\end{equation}\n\\noindent\nis tiny, so $H^2(t)\\approx8\\pi G\\rho(t)/3$: show that the temperature $T(t)$ is\ngiven by\n\\begin{equation}\nT = \\left(\\frac{3c^2}{32 \\pi G a_B t^2}\\right)^{1/4},\n\\end{equation}\nwhere $a_B = 7.56\\times 10^{-16}~\\mathrm{J}~\\mathrm{m}^{-3}~\\K^{-4}$ is the blackbody constant.\n\n\\section{Sparke \\& Gallagher Problem 8.13}\n\nShow that, when cool matter accounts for most of the energy density, and the universe\nis flat with $k=0$, we have\n\\begin{equation}\n\\dot{a}\\propto a^{-1/2},~\\mathrm{and}~a(t)\\propto t^{2/3}.\n\\end{equation}\n\\end{document}", "meta": {"hexsha": "9feb2c7f25a8451f360d4d2d162f287f819f9a75", "size": 2455, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "homework_5.tex", "max_stars_repo_name": "brantr/astro400B", "max_stars_repo_head_hexsha": "95cd675c23b9c44242f428516ed3e0fca54d3b4f", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-05-03T23:30:58.000Z", "max_stars_repo_stars_event_max_datetime": "2015-05-03T23:30:58.000Z", "max_issues_repo_path": "homework_5.tex", "max_issues_repo_name": "brantr/astro400B", "max_issues_repo_head_hexsha": "95cd675c23b9c44242f428516ed3e0fca54d3b4f", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homework_5.tex", "max_forks_repo_name": "brantr/astro400B", "max_forks_repo_head_hexsha": "95cd675c23b9c44242f428516ed3e0fca54d3b4f", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0972222222, "max_line_length": 102, "alphanum_fraction": 0.7018329939, "num_tokens": 873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.33300472587591906}}
{"text": "% declare document class and geometry\n\\documentclass[12pt]{article} % use larger type; default would be 10pt\n\\usepackage[margin=1in]{geometry} % handle page geometry\n\n\\input{../header.tex}\n\n\\title{Phys 220A -- Classical Mechanics -- Lec03}\n\\author{UCLA, Fall 2014}\n\\date{\\formatdate{09}{10}{2014}} % Activate to display a given date or no date (if empty),\n         % otherwise the current date is printed \n\n\\begin{document}\n\\setlength{\\unitlength}{1mm}\n\\maketitle\n\n\n\\section{Lagrangian formalism}\n\nThe Lagrangian formalism has some advantages over the Newtonian formulation:\n\\begin{itemize}\n\\item Looks the same in all coordinate systems\n\\item Conservation laws are manifestly evident\n\\item Constraints are simpler to deal with (normal forces, string tensions, etc.)\n\\item Lagrange equations can be derived from an action principle. This is great because all fundamental laws of physics can be formulated this way (general relativity, Maxwell theory, standard model). \n\\item Lagrangians and actions are the starting point for the path integral formulation of quantum mechanics.\n\\item Leads us to Hamiltonian formulation!\n\\end{itemize}\n\n\n\\subsection{Action principle}\n\nWhat is the action principle (or Hamilton's principle, the principle of least action)? Start with a system of generalized coordinates $q_i(t)$ and generalized velocities $\\dot{q}_i(t)$, $i = 1, \\dots N$. The Lagrangian is assumed to be a function $L(q_i, \\dot{q}_i, t)$. Then the action is defined as a functional\n\\begin{equation}\nS[q_i(t)] = \\int_{t_1}^{t_2} dt L(q_i, \\dot{q}_i, t)\n\\end{equation}\ntaking for its argument the path $q_i(t)$ with fixed boundary conditions $q_i(t) = q_i^\\text{initial}$ and $q_i(t_2)^\\text{final}$. (Recall that a functional $F[q(t)]$ maps a function to a real number.) \n\nThe action principle (the ``principle of least action'') says that the physical path is given by an extremum of the action:\n\\begin{equation}\n\\text{Euler-Lagrange:}\t\\qquad\t\\frac{\\delta S[q]}{\\delta q_i(t)} = 0, \\quad i = 1, \\dots, N. \n\\end{equation}\nWhat does this mean? Will need to familiarize ourselves with variational calculus and functional derivatives. \n\nFor simplicity let's consider a single coordinate $q(t)$ with initial and final points $q_1, q_2$. Then we have an action\n\\begin{equation}\nS[q(t)] = \\int dt L(q, \\dot q, t).\n\\end{equation}\nRecall the ordinary derivative is given by\n\\begin{equation}\n\\frac{df}{dx} = \\lim_{\\epsilon \\rightarrow 0} \\frac{f(x+\\epsilon) - f(x)}{\\epsilon} = \\lim_{\\epsilon \\rightarrow 0} \\frac{\\epsilon \\delta f + \\bigo(\\epsilon^2)}{\\epsilon} = \\delta f\n\\end{equation}\nWe consider an infinitesimal variation of $q(t)$,\n\\begin{equation}\n\\tilde{q}(t) = q(t) + \\delta q(t) = q(t) + \\epsilon h(t) + \\bigo(\\epsilon^2)\n\\end{equation}\nwhere $h(t)$ is an arbitrary function with $h(t_1) = h(t_2) = 0$ so that initial and final values of $q$ are fixed and the variation vanishes at the end points: $\\delta q(t_1) = \\delta q(t_2) = 0$. \n\nIn the variation of the action we only consider terms to order $\\epsilon$,\n\\begin{align}\n\\delta S &= S[q+\\delta q] - S[q] \\\\\n\t&= \\int_{t_1}^{t_2} L(q(t) + \\epsilon h(t), \\dot{q}(t) + \\epsilon \\dot{h}(t), t) - \\int_{t_1}^{t_2} dt L(q(t), \\dot{q}(t), t) \\\\\n\t&= \\epsilon \\int_{t_1}^{t_2} dt \\left\\{ \\frac{\\pd L}{\\pd q} h(t) + \\frac{\\pd L}{\\pd \\dot q} \\right\\} + \\bigo(\\epsilon^2),\n\\end{align}\nand integrating the second term by parts we find\n\\begin{equation}\n\\delta S = \\epsilon \\int_{t_1}^{t_2} \\left\\{ \\frac{\\pd L}{\\pd q} h - (\\frac{d}{dt} \\frac{\\pd L}{\\pd \\dot{q}}) h + \\frac{d}{dt} (\\frac{\\pd L}{\\pd \\dot{q}} h) \\right\\} + \\bigo(\\epsilon^2).\n\\end{equation}\nThe third term is a total derivative with vanishing boundary conditions so vanishes when integrated, so we're left with\n\\begin{equation}\n\\delta S = \\epsilon \\int_{t_1}^{t_2} dt \\left\\{ \\frac{\\pd L}{\\pd q} - \\frac{d}{dt} \\frac{\\pd L}{\\pd \\dot{q}} \\right\\} h(t) + \\bigo(\\epsilon^2).\n\\end{equation}\nThe action is an extremum if $\\delta S = 0$, it's still an integral but the function $h(t)$ is arbitrary. Thus we are left with the Euler-Lagrange equations,\n\\begin{equation}\n\\delta S = 0\t\\qquad \\iff \\qquad \\frac{\\pd L}{\\pd q} - \\frac{d}{dt} \\frac{\\pd L}{\\pd \\dot{q}} = 0.\n\\end{equation}\nNote that the extremum is not always a minimum of the action (as the name ``least action principle'' implies). For long trajectories we can find paths that are in fact saddle points of the action. However, it will in fact never be a maximum. This is because we can always take a longer path which increases the action. \n\nSome comments:\n\\begin{enumerate}\n\\item We can easily generalize to more than one coordinate. Taking variations $\\delta q_i = q_i + \\epsilon h_i(t)$ we have\n\\begin{equation}\n\\delta S = \\epsilon \\int dt \\sum_i \\left( \\frac{\\pd L}{\\pd q_i} - \\frac{d}{dt} \\frac{\\pd L}{\\pd \\dot{q}_i} \\right) h_i (t) + \\bigo(\\epsilon^2).\n\\end{equation}\nSince we can just set all $h_j = 0$ for $j \\neq i$ we just find the Euler-Lagrange equation applies for each variable,\n\\begin{equation}\n\\frac{\\pd L}{\\pd q_i} - \\frac{d}{dt} \\frac{\\pd L}{\\dot{q}_i} = 0, \\quad i = 1, \\dots, N.\n\\end{equation}\n\n\\item Newton's equation are of course reproduced for conservative forces by choosing $L = T - V$, so for a single particle $L = (1/2)m\\dot{x}^2 - V(x)$. Then the Euler-Lagrange equation just reproduces newton's equations\n\\begin{equation}\n-m\\ddot{x} - \\frac{\\pd V}{\\pd x} = 0,\n\\end{equation}\nwhich is 3 dimensions would is $m \\ddot{\\v{x}} = -\\v{\\nabla}V(\\v{x})$. Similarly for $N$ particles we would have $m_i \\ddot{\\v{x}}_i = -\\v{\\nabla}_i V(\\v{x})$. \n\n\\item One big advantage of the Euler-Lagrange equations is that they take the same form in any coordinate system. To show this, consider a change of coordinates $q_i \\rightarrow r_j$ which is a diffeomorphism, in other words a map\n\\begin{equation}\nr_j = r_j(q_1, \\dots, q_N, t), \\qquad j = 1, \\dots, N\n\\end{equation}\nwhich is differentiable and has a differentiable inverse. (For example, take $q_i$ to be cartesian coordinates $x, y, z$ and $r_j$ to be spherical coordinates $r, \\theta, \\phi$.) Then we have the Jacobian $J\\indices{_j^i} = \\frac{\\pd r_j}{\\pd q_i}$ which has full rank ($\\det J \\neq 0$). Note that the Lagrangian should of course be independent of coordinates if it is just the difference $T-V$ between kinetic and potential energy. We can write this as\n\\begin{equation}\nL'(r_j, \\dot{r}_j, t) = L(q_i(r_j, \\dot{r}_j), \\dot{q}_i(r_j, \\dot{r}_j), t),\n\\end{equation}\nthus we have \n\\begin{equation}\nS = \\int dt L(q_i, \\dot{q}_i, t) = \\int dt L'(r_j, \\dot{r}_j, t).\n\\end{equation}\nTherefore the condition that the variation $\\delta S$ vanishes is entirely geometric so the Euler-Lagrange equations must take the same form $r_j$ coordinates,\n\\begin{equation}\n\\frac{\\pd L'}{\\pd r_j} - \\frac{d}{dt} \\frac{\\pd L'}{\\pd \\dot{r}_j} = 0.\n\\end{equation}\n\nWe can check this on the level of the Euler-Lagrange equations themselves. Notice that we have by change of coordinates\n\\begin{equation}\n\\frac{\\pd L}{\\pd q_i} - \\frac{d}{dt} \\frac{\\pd L}{\\pd \\dot{q}_i} = \\sum_j \\frac{\\pd r_j}{\\pd q_i} ( \\frac{\\pd L'}{\\pd r_j} - \\frac{d}{dt} \\frac{\\pd L'}{\\pd \\dot{r}_j} ).\n\\end{equation}\nWriting the term on the right in parentheses as $v_j$ this is just a matrix equation $J\\indices{_i^j}v_j = 0$ which since $J$ has full rank implies that $v_j = 0$. \n\n[He works it out in coordinates a bit more but it's unnecessary given the linear algebraic treatment is enough.]\n\\end{enumerate}\n\nNow, depending on the coordinate the Euler-Lagrange equation might look simpler or more complicated. For example, for a free particle in 3D we have $L = T = (1/2)m \\dot{\\v{x}}^2$ with EL $\\implies \\ddot{x}_i = 0$. On the other hand, in spherical coordinates\n\\begin{equation}\nL = \\frac{1}{2} m (\\dot{r}^2 + r^2 \\dot{\\theta}^2 + r^2\\sin^2\\theta \\dot{\\phi}^2 )\n\\end{equation}\nand the EL equations give us \n\\begin{align}\n0 &= r \\dot{\\theta}^2 + r\\sin^2\\theta \\dot{\\phi}^2 \\\\\n0 &= \\frac{d}{dt} (r^2 \\sin^2\\theta \\dot{\\phi}^2) \\\\\n0 &= r^2 \\sin\\theta \\cos\\theta \\dot{\\phi}^2 - \\frac{d}{dt} (r^2 \\dot\\theta)\n\\end{align}\nwhich look much worse to work with. The challenge is to find coordinates which make $L$ as simple as possible!\n\nNote also that the derivation allowed for explicitly time dependent coordinate transformations. This implies that the EL equations also have the same form in non-inertial coordinate systems. Some examples:\n\\begin{enumerate}\n\\item \\textbf{Constant acceleration}\n\\begin{align}\nx &= x' \\\\\ny &= y' \\\\\nz &= z' + \\frac{1}{2} a t^2\n\\end{align}\nfor the free particles gives us\n\\begin{align}\nL &= \\frac{1}{2} m (\\dot{x}^2 + \\dot{y}^2 + \\dot{z}^2) \\\\\nL' &= \\frac{1}{2} m \\left[ \\dot{x}'^2 + \\dot{y}'^2 + (\\dot{z}' + at)^2 \\right] \\\\\n\t&= \\frac{1}{2} m (\\dot{x}'^2 + \\dot{y}'^2 + \\dot{z}'^2) + mat \\cdot \\dot{z}' + \\frac{1}{2} mat^2.\n\\end{align}\nThat last term does not depend on coordinates. Then EL equations give\n\\begin{equation}\n\\ddot{x} = 0, \\quad \\ddot{y} = 0, \\quad \\ddot{z} + ma = 0\n\\end{equation}\nwhich is the same as the equations for a constant gravitational field (this is the equivalence principle). \n\n\\item \\textbf{Rotating frame}\n\\begin{align}\nx &= x' \\cos \\omega t + y' \\sin \\omega t \\\\\ny &= y' \\cos \\omega t - x' \\sin \\omega t \\\\\nz &= z',\n\\end{align}\ngives us\n\\begin{align}\n\\dot{x} &= \\dot{x}' \\cos\\omega t - \\omega x' \\sin \\omega t + \\dot{y}' \\sin \\omega t + \\omega y' \\cos \\omega t \\\\\n\\dot{y} &= \\dot{y}' \\cos \\omega t - y' \\omega \\sin \\omega t - \\dot{x}' \\sin \\omega t - x' \\omega \\cos \\omega t \\\\\n\\dot{z} &= \\dot{z}'.\n\\end{align}\nThen our Lagrangian is given by\n\\begin{align}\nL &= \\frac{1}{2} m (\\dot{x}^2 + \\dot{y}^2 + \\dot{z}^2) \\\\\n\t&= \\frac{1}{2} m \\left[ (\\dot{x}' + \\omega y')^2 + (\\dot{y}' - \\omega x')^2 + \\dot{z}'^2 \\right] \\\\\n\t&= \\frac{1}{2} m (\\dot{\\v{x}}' - \\v{\\omega} \\times \\v{x}')^2\n\\end{align}\nwhere $\\v{\\omega} = (0, 0, \\omega)^\\top$. We find that the EL equations give us\n\\begin{equation}\n\\ddot{\\v{x}} - 2 \\v{\\omega} \\times \\dot{\\v{x}} + \\v{\\omega} \\times \\v{\\omega} \\times \\v{x} = 0\n\\end{equation}\nwhere we recognize the second term as the Coriolis force and the third term as the centrifugal force. We got this from:\n\\begin{align}\n\\frac{\\pd L}{\\pd \\v{x}} &= \\frac{\\pd}{\\pd \\v{x}} \\left( -m \\v{x} \\cdot (\\v{\\omega} \\times \\v{x}) + (m/2) (\\v{\\omega} \\times \\v{x})^2 \\right) \\\\\n\t&= -m \\dot{\\v{x}} \\times \\v{\\omega} - m (\\v{\\omega} \\times \\v{\\omega} \\times \\v{x})\n\\end{align}\nwhere the first term is obtained by:\n\\begin{align}\n\\frac{\\pd}{\\pd x_m} \\dot{\\v{x}} \\cdot (\\v{\\omega} \\times \\v{x}) &= \\dot{x}_i \\varepsilon_{ijk} \\omega_j \\delta_{km} \\\\\n\t&= \\dot{x}_i \\omega_j \\varepsilon_{ijm} \\\\\n\t&= \\dot{\\v{x}} \\times \\v{\\omega}.\n\\end{align}\n\n\\end{enumerate}\n\n\n\n\\section{A little more on variational calculus and functional derivatives}\n\nBefore, we had  the statement $\\delta S / \\delta q_i(t) = 0$ as the analog of $df / dx_i = 0$ for extrema. How is this equality defined? For the ordinary derivative we can write $df = f' dx$. For the functional derivative, we have\n\\begin{align}\n\\frac{\\pd S[q(t) + \\epsilon h(t)]}{\\pd \\epsilon} \\Big|_{\\epsilon = 0} &= \\epsilon \\int dt \\left( \\frac{\\pd L}{\\pd q} - \\frac{d}{dt} \\frac{\\pd L}{\\pd \\dot{q}} \\right) h(t) \\\\\n\t&= \\epsilon \\int dt \\frac{\\delta S}{\\delta q(t)} h(t)\n\\end{align}\nwhere $\\delta q(t) = \\epsilon h(t)$. Then we can write\n\\begin{equation}\n\\delta S = \\int dt \\frac{\\delta S}{\\delta q(t)} \\delta q(t).\n\\end{equation}\nNote the integral! This actually looks different than the ordinary derivative. \n\nMost rules for derivatives (product, chain, etc) apply with this definition of the functional derivative. Another quick way to define the functional derivative in general is:\n\\begin{equation}\n\\frac{\\delta S[q]}{\\delta q(t')} = \\lim_{\\epsilon \\rightarrow 0} \\frac{S[q(t) + \\epsilon \\delta(t-t')] - \\delta q(t)}{\\epsilon}.\n\\end{equation}\nFor $S = \\int dt L(q, \\dot q, t)$ this gives us\n\\begin{align}\n\\frac{\\delta S[q]}{\\delta q} &= \\lim_{\\epsilon \\rightarrow 0} \\frac{1}{\\epsilon} \\int dt \\left[ L(q(t) + \\epsilon \\delta(t-t'), \\dot{q}(t) + \\epsilon \\frac{d}{dt} \\delta(t-t'), t) - L(q(t), \\dot{q}(t), t) \\right] \\\\\n\t&= \\lim_{\\epsilon \\rightarrow 0} \\frac{1}{\\epsilon} \\int dt \\left[ \\cancel{L(q, \\dot q, t)} + \\epsilon \\frac{\\pd L}{\\pd q} \\delta(t-t') + \\epsilon \\frac{\\pd L}{\\pd \\dot{q}} \\frac{d}{dt} \\delta(t-t') - \\cancel{L(q, \\dot q, t)} + \\bigo(\\epsilon^2) \\right] \\\\\n\t&= \\int dt \\left[ \\frac{\\pd L}{\\pd q} - \\frac{d}{dt} \\frac{\\pd L}{\\pd \\dot{q}} \\right] \\delta(t-t') \\\\\n\t&= \\frac{\\pd L}{\\pd q} - \\frac{d}{dt} \\frac{\\pd L}{\\pd \\dot{q}}.\n\\end{align}\n\n\n\n\n\n\n\\end{document}\n", "meta": {"hexsha": "5a224b6987e229f93830be1eb19665228912c4b3", "size": 12474, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "classical/lec03.tex", "max_stars_repo_name": "paulinearriaga/phys-ucla", "max_stars_repo_head_hexsha": "48084dbbac2f8a4748c1fdaaf63a4cebaae16809", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "classical/lec03.tex", "max_issues_repo_name": "paulinearriaga/phys-ucla", "max_issues_repo_head_hexsha": "48084dbbac2f8a4748c1fdaaf63a4cebaae16809", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "classical/lec03.tex", "max_forks_repo_name": "paulinearriaga/phys-ucla", "max_forks_repo_head_hexsha": "48084dbbac2f8a4748c1fdaaf63a4cebaae16809", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.1891891892, "max_line_length": 453, "alphanum_fraction": 0.6654641655, "num_tokens": 4320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.333004725875919}}
{"text": "\\chapter{Introduction to Electricity}\n\nWhat happens when you turn on a flashlight? The battery in the\nflashlight acts as an electron pump. The electrons flow through the\nwires to the lightbulb (or LED). As the electrons pass through the\nlightbulb, they excite the molecules within, which gives off light and\nheat. (LEDs also give off light and heat, but they give off a lot less\nheat.) Then the electrons return to the battery to be pumped around\nagain.\n\nWhen electricity is flowing through a copper wire, the protons and\nneutrons of the copper stay put while the electrons jump between the\natoms on their way from the battery to the lightbulb and back again.\n\nIn some materials, like copper and iron, electrons are loosely bound\nto their nuclei, forming a sea of electrons, which allows enery to flow. These are good \\textit{electrical conductors}. In\nother materials, like glass and plastic, electrons don't leave their\nnuclei easily. Thus, they are terrible electrical conductors -- we call\nthem \\textit{electrical insulators}. For example, the plastic around a\nwire is electrical insulation.\n\n\\includegraphics[width=0.8\\textwidth]{Insulator_vs_Conductor.png}\n% KA: https://www.khanacademy.org/science/physics/electric-charge-electric-force-and-voltage/charge-electric-force/v/conductors-and-insulators\n\n\\section{Units}\n\nElectrons are very small, so to study them, scientists came up with a\nunit that represents \\textit{a lot} of electrons. 1 \\textit{coulomb}\nis about 6,241,509,074,460,762,608 electrons.  When 5 coulombs enter one end of the wire every second (and simultaneously 5 coulombs exit the other end), we say ``This wire is carrying 5 ampere of current.''\\index{coulombs}\n\n(Truthfully, we usually shorten ampere to just ``amp''.  This is\nsometimes a little awkward because we often shorten the word\n``amplifier'' to ``amp''. You should be able to tell which is which\nfrom the context.)\\index{amp or ampere}\n\nIf you look at the circuit breakers or fuses for your home's\nelectrical system, you'll see that each one is rated in amps.  For\nexample, maybe the circuit that supplies power to your kitchen has a 10\namp circuit breaker. If for some reason, more than 10 amps tries to\npass through that wire, the circuit breaker will turn off the whole\ncircuit.\n\nWhen it is on, your flashlight pushes about 1 amp of current\nthrough the lightbulb(When it is off, there is no current in the\nlightbulb).\n\n\\includegraphics[width=0.8\\textwidth]{Circuit_OnOff.png}\n\nThe lightbulb creates \\textit{Resistance} that the current pushes\nthrough.\\index{resistance} Think of it like plumbing: The current is the amount of water\npassing through a pipe. The resistence is something that tries to stop\nthe current -- like a ball of hair. The battery is what allows\n the current to push through the resistance; we call that\npressure \\textit{voltage}.\\index{voltage}\n\n\\section{Circuit Diagrams}\n\nHere is a circuit diagram of your flashlight:\n\n\\begin{circuitikz}\n\\draw (0,0) to[battery1,invert,l=$3V$] ++(0,3)\nto [switch,i=1A] ++(3,0)\nto [lamp=$1\\Omega$,bipoles/length=0.9cm] ++(0,-3) -- (0,0);\n\\end{circuitikz}\n\nThe lines are wires.  The symbols that we  will use:\n\n\\begin{tabular}{c c c c}\n  Battery & Switch & Lamp & Resistor \\\\\n\\begin{circuitikz}\n\\draw (0,0) to[battery1] (2,0); \n\\end{circuitikz}\n&\n\\begin{circuitikz}\n\\draw (0,0) to[lamp,bipoles/length=0.9cm,l=$3 \\Omega$] (2,0); \n\\end{circuitikz}\n&\n\\begin{circuitikz}\n\\draw (0,0) to[switch,/tikz/circuitikz/bipoles/length=1.0cm] (2,0); \n\\end{circuitikz}\n&\n\\begin{circuitikz}\n\\draw (0,0) to[R,  l=$3 \\Omega$] (2,0); \n\\end{circuitikz} \\\\\n\\end{tabular}\n\nThe battery pushes the electrons from one end and pulls them back in at the other, so the circuit must go around in a circle for current to flow. This is why the current stops flowing when the switch breaks the circuit.\n\nYou can think of a switch as having zero resistance when it is closed and infinite resistance when it is open.\n\n\nFor our purposes, a lamp is just a resistor that gives off light.\n% KA: https://www.khanacademy.org/science/high-school-physics/dc-circuits/electric-power-and-dc-circuits/a/circuit-introduction\n\n\\section{Ohm's Law}\n\nResistance is measured in \\textit{ohms}, and we use a Greek capital omega for that: $\\Omega$  \n\nVoltage is measured in\n\\textit{volts}.\\index{ohms}\\index{volts}\n\n\\begin{mdframed}[style=important, frametitle={Ohm's Law}]\\index{Ohm's law}\n  Whenever a voltage $V$ is pushing a current $I$ through a resistance of $I$, the following is true:\n\n  $$V = IR$$\n\n  where $V$ is in volts, $I$ is in amps, and $R$ is in ohms.\n\\end{mdframed}\n% KA: https://www.khanacademy.org/science/physics/circuits-topic/circuits-resistance/v/circuits-part-1\n\n\\section{Power and Watts}\n\n\\begin{mdframed}[style=important, frametitle={Joule's Law}]\\index{Joule's law}\n\n  When a current $I$ is passing through a resistance $R$, the power consumed is\n  \n  $$W = I^2 R$$\n\n  where $W$ is in watts, $I$ is in amps, and $R$ is in ohms.\n\\end{mdframed}\n\nOf course $V = IR$, so we can extend this to:\n\n$$W = I^2 R = I V = \\frac{V^2}{R}$$\n\nYour flashlight's batteries provides about 3 volts. How much\nbattery power is the flashlight using when it is on? The power (in\nwatts) produced by the battery is the product of the voltage (in\nvolts) and the current (in amps). So your flashlight giving off $3\nvolts \\times 1 amp = 3 watts$ of power. Some of that power is given\noff as light, some as heat.\\index{watts}\n\nA watt is 1 joule of energy per second. We say that a watt is a\nmeasure of \\textit{power}.\n\nWhen we talk about how much energy is stored in a battery, we use a\nunit like kilowatt-hour. A kilowatt-hour is equivalent to 3.6 million\njoules.\n\n\\section{Another great use of RMS}\n\nIn many electrical problems, the voltage fluctuates a lot.  For\nexample, the fluctuations in voltage makes the sound that comes out of an\naudio speaker.\n\nYou can use the root-mean-squared of the voltage to figure out the average power\nyour speaker is consuming.\n\nLets say that the RMS of the voltage you are sending to the speaker is $V_{rms}$\nand the resistance of the speaker is $R$ ohms, then the power consumed\nby the speaker is:\n\n$$P = \\frac{V_{rms}^2}{R}$$\n\nSimilarly, if you know the RMS of the current you are pushing through\nthe speaker is $I_{rms}$, then the power consumed by the speaker is:\n\n$$P = I_{rms} R$$\n\n\\section{Electricity Dangers}\n\nLarge amounts of electricity moving through your body can hurt or even kill\nyou. You must be careful around electricity.\n\nHowever, your body is not a very good conductor, so low-voltage\nsystems (like a flashlight) don't have enough voltage to move succnificant amounts of\ncurrent through your body.\n\nHowever, the  electricity in a power outlet has much more voltage. The voltage\nin these outlets is fluctuating between positive and negative, so we\ncall it \\textit{Alternating Current} or AC.\n% ADD: Introduce difference between AC and dc\n\n\\includegraphics[width=0.8\\textwidth]{AC_vs_DC.png}\n\nIn most countries, the RMS of the voltage between 110 and 240 V. (The\npeak voltage is always $\\sqrt{2}$ times the RMS value. In the US, for\nexample, people say ``Our outlets supply 120 V.'' They mean that the\nRMS of the voltage difference between the wire and the earth is 120V.\nThe peak voltage is almost 170V.)\n\nHow much current can a human handle? Not much. You can barely feel 1\nmA moving through your body, but at 16 mA, your muscles will clench\nand you won't be able to relax them -- many people die from\nelectrocution because they grab a wire which pushes enough current\nthrough their body to prevent them from letting go of the wire.  At 20\nmA, a human's respiratory muscles become paralyzed.\n\nThe fuse breaker in a house will often allow 20 A to flow through the\ncircuit before it shuts off the power: Always, always, always shut off\nthe power before touching any of the wiring in your house.\n\nWhile water is actually a mediocre conductor, it can still deliver enough current\nto kill you. If you see a wire in a puddle, you should not touch the\npuddle. Interestingly, because of the salt, sea water is more than\n100 times better at conducting electricity than the water you drink.\n% ADD: Sea of electrons makes a good conductor\n\n\\includegraphics[width=0.8\\textwidth]{Sea_Electrons.png}\n\nIf you hold a wire in each hand, how many Ohms of resistance will your\nbody have? Once it gets past your skin, you will look like a bag of\nsalt water to the electricity. After the skin, your body will have a\nresistance of about 300$\\Omega$. However, the skin is a pretty good\ninsulator. If you have dry, calloused hands, your skin may add a\n100,000$\\Omega$ to the resistance.\n\n% KA: https://www.khanacademy.org/science/in-in-class10th-physics/in-in-electricity/in-in-electric-power-and-heating-effect-of-current/v/electric-power-energy\n\n", "meta": {"hexsha": "096401d3021c033ffa83a90df2c9d6bd70872a65", "size": 8768, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Modules/MatterEnergy/dc1-en_US.tex", "max_stars_repo_name": "hillegass/sequence", "max_stars_repo_head_hexsha": "b7b4896d804c49cbc93fe86a0d2fce531afbcc1f", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-06-13T17:19:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T00:43:44.000Z", "max_issues_repo_path": "Modules/MatterEnergy/dc1-en_US.tex", "max_issues_repo_name": "hillegass/sequence", "max_issues_repo_head_hexsha": "b7b4896d804c49cbc93fe86a0d2fce531afbcc1f", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Modules/MatterEnergy/dc1-en_US.tex", "max_forks_repo_name": "hillegass/sequence", "max_forks_repo_head_hexsha": "b7b4896d804c49cbc93fe86a0d2fce531afbcc1f", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-05T00:43:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T00:43:58.000Z", "avg_line_length": 41.7523809524, "max_line_length": 223, "alphanum_fraction": 0.7601505474, "num_tokens": 2407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.3328239933253469}}
{"text": "\\documentclass[11pt]{article}\n\n\\usepackage[top=1in, bottom=1in, left=1in, right=1in]{geometry} \n\\usepackage{graphicx}\n\\usepackage{titling}\n\\usepackage{float}\n\\usepackage{bm}\n%\\usepackage[fleqn]{amsmath}\n\\usepackage{amssymb,amsmath}\n\\usepackage{listings}\n\\usepackage{color}\n\\usepackage{enumitem}\n\\usepackage{fancyvrb}\n\\usepackage{hyperref}\n\\usepackage{setspace}\n\\usepackage{tabularx}\n\\usepackage{diagbox}\n\\usepackage{pdfpages}\n\\geometry{letterpaper}\n\\linespread{1.1}% \\geometry{landscape} % rotated page geometry\n\n\\definecolor{codegreen}{rgb}{0,0.6,0}\n\\definecolor{codegray}{rgb}{0.5,0.5,0.5}\n\\definecolor{codepurple}{rgb}{0.58,0,0.82}\n\\definecolor{backcolour}{rgb}{0.95,0.95,0.92}\n\\definecolor{outcolor}{rgb}{0.545, 0.0, 0.0}\n\n\\lstdefinestyle{mystyle}{\n\tbackgroundcolor=\\color{backcolour},   \n\tcommentstyle=\\color{codegreen},\n\tkeywordstyle=\\color{magenta},\n\tnumberstyle=\\tiny\\color{codegray},\n\tstringstyle=\\color{codepurple},\n\tbasicstyle=\\footnotesize,\n\tbreakatwhitespace=false,         \n\tbreaklines=true,                 \n\tcaptionpos=b,                    \n\tkeepspaces=true,                 \n\tnumbers=left,                    \n\tnumbersep=5pt,                  \n\tshowspaces=false,                \n\tshowstringspaces=false,\n\tshowtabs=false,                  \n\ttabsize=2\n}\n\n\\lstset{style=mystyle}\n\n\\setlength{\\droptitle}{-5em}\n\\title{CE 264 Problem Set 5: Midterm Review}\n\\date{22 Mar. 2018} \n\\author{Kun Qian \\ \\ \\ \\ \\ \\ (3033030782)\\\\ Franklin Zhao \\ (3033030808)\\\\ Yichen Zhong \\  (3033030873)}\n\n\\begin{document}\n\t\n\t\\maketitle\n\t\\renewcommand\\theequation{\\arabic{equation}}\n\t\\renewcommand{\\figurename}{Fig.}\n\t\\renewcommand\\thesection{Problem \\arabic{section}}\n\t\\renewcommand\\thesubsection{(\\Alph{subsection})}\n\t\\renewcommand\\thesubsubsection{Question (\\alph{subsubsection}):}\n\t\\onehalfspacing\t\n\t\n\\section{}\n\\noindent The probability to move to North Berkeley is:\n\\begin{equation}\\label{finaleq}\nPr(NB)=\\frac{e^{V_{NB}}}{e^{V_{NB}}+e^{V_{SF}}+e^{V_{PO}}}\\ \\ \\text{(since only 3 choices available here)}\n\\end{equation}\n\\noindent For the choice-residential model, we have the utility function:\n\\begin{equation}\nU=\\beta_{Rent}\\times Rent+\\beta_{Price}\\times Price+\\beta_{Size}\\times Size+\\beta_d\\times DummyHouse+\\beta_{Log}\\times Logsum\n\\end{equation}\nwhere most values are listed in the problem, but we still need to compute the logsum from the commuter's choice model.\n\\begin{equation}\nLL=log(\\prod Pr_{i,j})\n\\end{equation}\nwhere $i\\in\\{1,2\\}$ represents an individual; $j\\in\\{1,2,3\\}$ represents a residence choice.\\\\\\\\\nFor a nested logit model:\n\\begin{align}\nPr(Driver)=Pr(Driver|Auto)\\times Pr(Auto)\\times...\\\\\nPr(Auto)=\\frac{e^{\\mu V_A}}{e^{\\mu V_A}+e^{\\mu V_N}+e^{\\mu V_T}}\\\\ Pr(Driver|Auto)=\\frac{e^{\\mu_AV_D}}{e^{\\mu_AV_D}+e^{\\mu_AV_P}}\\\\\nV_A=\\frac{1}{\\mu_A}log(e^{\\mu_AV_D}+e^{\\mu_AV_P})\\ \\ (\\text{Similar for }\\mu_{NM}\\text{ and } \\mu_T)\n\\end{align}\nwhere $\\mu_A=1.67$, $\\mu_{NM}=1.205$, and $\\mu_T=1.784$.\nFor each individual in each residential choice, the following utility equations are as follows:\n\\begin{equation}\nV_{Drive}=ASC_{Drive}+\\beta_{in-veichle}\\times T_{Time}+\\beta\\times Cost\n\\end{equation}\n\\begin{equation}\nV_{Passgr}=ASC_{ShareRide}+\\beta_{in-veichle}\\times T_{Time}+\\beta\\times Cost\n\\end{equation}\t\n\\begin{equation}\nV_{Walk}=ASC_{Walk}+\\beta_{Walking}\\times T_{Time}+\\beta\\times Cost\n\\end{equation}\t\t\n\\begin{equation}\nV_{Bike}=ASC_{Bike}+\\beta_{Bike}\\times T_{Time}+\\beta\\times Cost\n\\end{equation}\t\n\\begin{equation}\nV_{W-T}=ASC_{W-T}+\\beta_{in-veichle}\\times T_{Time}+\\beta_{Wait}\\times T_{Wait}+\\beta_{Transit}\\times T_{Transit}+\\beta\\times Cost\n\\end{equation}\t\t\n\\begin{equation}\nV_{A-T}=ASC_{D-T}+\\beta_{in-veichle}\\times T_{Time}+\\beta_{Wait}\\times T_{Wait}+\\beta_{Transit}\\times T_{Transit}+\\beta\\times Cost\n\\end{equation}\t\nThe upper level utilites are computed in Table 1.\n\\begin{center}\nTable 1: Upper level utilities\n\\end{center}\n\\begin{figure}[H]\n\\centering\n\\vspace{-0.6cm}    \n\\includegraphics[width=\\linewidth]{tb1.pdf}  \n\\end{figure}\nUsing these 12 computed upper level utilities, the following results can be derived:\n\\begin{align}\n\\tilde{V}_{MD,Auto}=log(e^{-1.562}+e^{-2.268})=-1.161\\\\\n\\tilde{V}_{MD,Non}=log(e^{-2.914}+e^{-0.595})=-0.411\\\\\n\\tilde{V}_{MD,Tran}=log(e^{0.271}+e^{-0.562})=0.632\\\\\n\\tilde{V}_{NB,Auto}=log(e^{-1.925}+e^{-0.300})=-0.121\\\\\n\\tilde{V}_{NB,Non}=log(e^{-0.595}+e^{-0.915})=-0.049\\\\\n\\tilde{V}_{NB,Tran}=log(e^{-1.306}+e^{0.309})=0.491\n\\end{align}\n\\newpage\n\\begin{align}\n\\tilde{V}_{PO,Auto}=log(e^{-1.427}+e^{-1.008})=-0.503\\\\\n\\tilde{V}_{PO,Non}=log(e^{-0.595}+e^{0.005})=0.443\\\\\n\\tilde{V}_{PO,Tran}=log(e^{-1.330}+e^{-1.316})=-0.630\n\\end{align}\nNow, let's compute the logsum for each residential choice:\n\\begin{align}\n\\tilde{V}_{MD}=log(e^{-1.161}+e^{-0.411}+e^{0.632})=2.858\\\\\n\\tilde{V}_{NB}=log(e^{-0.121}+e^{-0.049}+e^{0.491})=3.472\\\\\n\\tilde{V}_{PO}=log(e^{-0.503}+e^{0.443}+e^{-0.630})=2.695\n\\end{align}\nHence, the utility for each residential choice can be derived:\n\\begin{align}\nV_{MD}=-0.16\\times29-0.064\\times70+4.400\\times0.82-0.782\\times0+2.000\\times2.858=0.204\\\\\nV_{NB}=-0.16\\times28-0.064\\times60+4.400\\times1.16-0.782\\times1+2.00\\times3.472=2.946\\\\\nV_{PO}=-0.16\\times18-0.064\\times82+4.400\\times1.26-0.782\\times1+2.000\\times2.695=2.024\n\\end{align}\nPlug the above equations into Equation~(\\ref{finaleq}), and the final result is obtained:\n\\begin{equation}\nPr(NB)=\\frac{e^{2.946}}{e^{0.204}+e^{2.946}+e^{2.024}}=\\bf{0.684}\n\\end{equation}\n\\section{}\n\\subsection{}\n\\begin{align}\nPr(P|G=1)=\\frac{e^0}{e^{(0.3+1.8)}+e^1+e^0}=0.084\\\\\nPr(M|G=1)=\\frac{(0.3+1.8)}{e^{(0.3+1.8)}+e^1+e^0}=0.687\\\\\nPr(T|G=0)=\\frac{e^1}{e^{0.3}+e^1+e^0}=0.536\\\\\nPr(T|G=0)=\\frac{e^0.3}{e^{0.3}+e^1+e^0}=0.266\n\\end{align}\n\\begin{equation}\nLL=log(0.084^2\\times0.687^4\\times0.536^6\\times0.266^2)=-12.8\n\\end{equation}\nHence, the value of the log-likelihood function at MLE is \\textbf{-12.8}.\n\\subsection{}\n\\begin{equation}\n\\rho^2=1-\\frac{L(\\beta)}{L(0)}=1-\\frac{-12.8}{14\\times log(\\frac{1}{3})}=1-\\frac{-12.8}{-15.4}=\\bf{0.17}\n\\end{equation}\n\\subsection{}\n\\textbf{Yes,} since now if we check the table of estimated parameters, we noticed given\tthat $\\beta_{3T}=\\beta_{3P}=0$, the graduate students' choice will always be $M$, which in fact makes $\\beta_S$ not estimable. Hence, changing the availability like this would definitely affect the value of MLE.\n\\section{}\n\\subsection{}\n\\textbf{Yes.} Travel time is a variable across alternatives, so it can be included in all alternatives and four parameters can be estimable. In this example, the parameter values are partially constrained to be the same across motor and nonmotor alternatives.\n\\subsection{} \n\\textbf{No.} Because the distance between home and destination for each staff is fixed and does not vary across alternatives. To modify the specification, estimated alternative-specific distance parameters and one base alternative can be used to replace a single beta for all four alternatives.\n\\subsection{} \n\\textbf{No.} Because the average price per gallon is a fixed value for all respondents, which means it is perfectly correlated with the car constant. It can be modified to fuel cost per trip based on trip distances to estimate the parameter.\n\\subsection{} \n\\textbf{Yes.} Female = 1 – Male. This variable does not vary across alternatives and it is categorical with two categories. So, one utility and one category must be the base and gender can be included in at most 3 alternatives. \n\\subsection{} \n\\textbf{No,} at most 2 variables can be included in each utility. So, one of the income categories need to be set as a base and drop from utility.\n\\section{}\n\\subsection{}\nBecause \\textit{t-test}$=\\frac{\\hat{\\beta}-0}{\\bar{\\sigma}}$,\n\\begin{equation}\n\\bar\\sigma=\\frac{\\hat{\\beta}-0}{\\text{\\textit{t-test}}}=\\frac{0.8}{8.52}=0.094\n\\end{equation}\nThen we let $\\alpha$ walk-transit for Transit Nest to de a hypothesis test:\n\\begin{equation}\n\\begin{array}{rl}\nH_0:&\\alpha=1\\\\\nH_1:&\\alpha\\neq1\\\\\n\\text{\\textit{t-test}}=&\\frac{0.8-1}{0.094}=-2.128<-2.1\n\\end{array}\n\\end{equation}\nThus we \\textbf{reject} the null hypothesis, and the cross situation is preferred.\n\\subsection{}\t\nFor unrestricted model, we can estimate much more parameters than restricted models. Thus, the likelihood and $\\rho^2$ will increase, and we cannot confirm what happens to $\\rho^2$.\n\\end{document}", "meta": {"hexsha": "6f10e82e8b78ec3cdc8a8d162cea8b2e0292e8c2", "size": 8277, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "PS5/CE264PS5.tex", "max_stars_repo_name": "QinganZhao/Behavior-Modeling", "max_stars_repo_head_hexsha": "18298c00d0b6781705feb192f04d6497d6801039", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-01-08T02:54:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-08T02:54:01.000Z", "max_issues_repo_path": "PS5/CE264PS5.tex", "max_issues_repo_name": "QinganZhao/Behavior-Modeling", "max_issues_repo_head_hexsha": "18298c00d0b6781705feb192f04d6497d6801039", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PS5/CE264PS5.tex", "max_forks_repo_name": "QinganZhao/Behavior-Modeling", "max_forks_repo_head_hexsha": "18298c00d0b6781705feb192f04d6497d6801039", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.5631578947, "max_line_length": 299, "alphanum_fraction": 0.7035157666, "num_tokens": 2948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.33282398976083993}}
{"text": "%\\chapter{Modalities}\\label{chap:modalities}\n\n\\section{Modalities}\\label{sec:modal-refl-subun}\n\nIn this section we will introduce the following four notions of modality\nand prove that they are all equivalent:\n\\begin{enumerate}\n\\item Higher modalities\n\\item Uniquely eliminating modalities\n\\item $\\Sigma$-closed reflective subuniverses\n\\item Stable orthogonal factorization systems\n\\end{enumerate}\nAfter their equivalence has been established, we will call all of them simply \\emph{modalities}.\n\nThe first three definitions have the following data in common: by a \\define{modal operator} we mean a function $\\modal:\\UU\\to\\UU$, and by a \\define{modal unit} we mean a family of functions $\\modalunit^\\modal:\\prd*{A:\\UU}A\\to\\modal A$.\nGiven these data, we say a type $X$ \\define{is modal} if $\\modalunit[X]:X\\to\\modal X$ is an equivalence, and we write $\\UU_\\modal \\defeq \\sm{X:\\UU} \\ismodal(X)$ for the \\define{subuniverse of modal types}.\n\n\\begin{defn}\\label{defn:highermod}\nA \\define{higher modality} consists of a modal operator and modal unit together with\n\\begin{enumerate}\n\\item for every $A:\\UU$ and every dependent type $P:\\modal A\\to\\UU$, a\nfunction\n\\begin{equation*}\n\\mathsf{ind}_{\\modal A}:\\big(\\prd{a:A}\\modal(P(\\eta(a)))\\big)\\to\\prd{z:\\modal A}\\modal(P(z)).\n\\end{equation*}\n\\item An identification\n\\begin{equation*}\n\\mathsf{comp}_{\\modal A}(f,x):\\id{\\mathsf{ind}_{\\modal A}(f)(\\eta(x))}{f(x)}\n\\end{equation*}\nfor each $f:\\prd{x:A}\\modal(P(\\eta(x)))$.\n\\item For any $x,y:\\modal A$ the modal unit $\\modalunit[(\\id{x}{y})]:\\id{x}{y}\\to \\modal(\\id{x}{y})$ is an equivalence.\n\\end{enumerate}\n\\end{defn}\n\n\\begin{defn}\\label{defn:modunique}\nA \\define{uniquely eliminating modality} consists of\na modal operator and modal unit such that the function\n\\begin{equation*}\n\\lam{f} f\\circ\\modalunit[A] : (\\prd{x:\\modal A}\\modal(P(x)))\\to(\\prd{a:A}\\modal(P(\\modalunit[A](a))))\n\\end{equation*}\nis an equivalence for any $A$ and any $P:\\modal A\\to\\UU$.\n\\end{defn}\n\n\\begin{defn}\\label{defn:ssrs}\nA reflective subuniverse $L$ is said to be \\define{$\\Sigma$-closed} if $\\sm{x:X}P(x)$ is $L$-local for every family $P:X\\to \\UU_L$ of $L$-local types over an $L$-local type $X$.\n\\end{defn}\n\nNote that unlike \\cref{defn:highermod,defn:modunique}, in \\cref{defn:ssrs} the notion of ``modal type'' is part of the data.\nHowever, we will show in \\cref{thm:subuniv-modal} that $\\ismodal(A)$ if and only if $\\modalunit[A]$ is an equivalence.\n\n\\begin{defn}\\label{defn:sofs}\nAn \\define{orthogonal factorization system} consists of\npredicates $\\mathcal{L},\\mathcal{R}:\\prd*{A,B:\\UU} (A\\to B)\\to\\prop$ such that\n\\begin{enumerate}\n\\item $\\mathcal{L}$ and $\\mathcal{R}$ are closed under composition and contain all identities (i.e.\\ they are subcategories of the category of types that contain all the objects), and\n\\item the type $\\fact_{\\mathcal{L},\\mathcal{R}}(f)$ of factorizations\n\\begin{equation*}\n\\begin{tikzcd}\nA \\arrow[rr,\"f\"] \\arrow[dr,swap,\"f_{\\mathcal{L}}\"] & & B \\\\\n& \\im_{\\mathcal{L},\\mathcal{R}}(f) \\arrow[ur,swap,\"f_{\\mathcal{R}}\"]\n\\end{tikzcd}\n\\end{equation*}\nof $f$, with $f_{\\mathcal{L}}$ in $\\mathcal{L}$ and $f_{\\mathcal{R}}$ in $\\mathcal{R}$, is contractible.\n\\end{enumerate}\nMore precisely, the type $\\fact_{\\mathcal{L},\\mathcal{R}}(f)$ is defined to\nbe the type of\ntuples\n\\begin{equation*}\n(\\im_{\\mathcal{L},\\mathcal{R}}(f),(f_{\\mathcal{L}},p),(f_{\\mathcal{R}},q),h)\n\\end{equation*}\nconsisting of a type $\\im_{\\mathcal{L},\\mathcal{R}}(f)$, a function $f_{\\mathcal{L}}:A\\to \\im_{\\mathcal{L},\\mathcal{R}}(f)$ with\n$p:\\mathcal{L}(f_{\\mathcal{L}})$, a function $f_{\\mathcal{R}}:\\im_{\\mathcal{L},\\mathcal{R}}(f)\\to B$ with $q:\\mathcal{R}(f_{\\mathcal{R}})$, and an identification $h:\\id{f}{f_{\\mathcal{R}}\\circ f_{\\mathcal{L}}}$. The type $\\im_{\\mathcal{L},\\mathcal{R}}(f)$ is called\nthe \\define{$(\\mathcal{L},\\mathcal{R})$-image of $f$}.\n\nA type $X$ is said to be \\define{$(\\mathcal{L},\\mathcal{R})$-modal} if\nthe map $!:X\\to\\unit$ is in $\\mathcal{R}$ (and hence $!_\\mathcal{L}$\nis an equivalence).\n\nAn orthogonal factorization system is said to be \\define{stable} if the class\n$\\mathcal{L}$ is stable under pullbacks (By\n\\autoref{lem:ofs_rightstable}, $\\mathcal{R}$ is always stable under pullbacks).\n\\end{defn}\n\n\\begin{rmk}\n  By univalence, the fact that $\\mathcal{L}$ and $\\mathcal{R}$ contain all identities implies that they each contain all equivalences.\n  Conversely, if $f\\in \\mathcal{L}\\cap\\mathcal{R}$, then $(\\idfunc,f)$ and $(f,\\idfunc)$ are both $(\\mathcal{L},\\mathcal{R})$-factorizations of $f$, and hence equal; which implies that $f$ is an equivalence.\n  Thus, $\\mathcal{L}\\cap\\mathcal{R}$ consists exactly of the equivalences.\n\\end{rmk}\n\nWe now consider a few examples.\nSince we will eventually prove all the definitions to be equivalent, we can use any one of them to describe any particular example.\n\n\\begin{eg}\n  The prime example is the \\textbf{$n$-truncation modality} $\\truncf n$ as studied in~\\cite[Chapter 7]{hottbook}.\n  This can be given as a higher modality, using its induction principle and the fact that $\\trunc n A$ is an $n$-type and the identity types of an $n$-type are again $n$-types (indeed, $(n-1)$-types).\n  The corresponding stable orthogonal factorization system, consisting of $n$-connected and $n$-truncated maps, is also constructed in~\\cite[Chapter 7]{hottbook}; our construction in \\cref{thm:sofs_from_ssrs} will be a generalization of this.\n\\end{eg}\n\n\\begin{eg}\\label{eg:open}\n  Let $Q$ be a mere proposition.\n  The \\textbf{open modality} determined by $Q$ is defined by $\\open Q A = (Q\\to A)$, with unit $\\modalunit[A](x) = \\lam{\\nameless}x : A \\to (Q \\to A)$.\n  To show that this is a higher modality, suppose we have $P: (Q\\to A) \\to \\UU$ and $f:\\prd{a:A} Q \\to P(\\lam{\\nameless} a)$.\n  Then for any $z:Q\\to A$ and $q:Q$ we have $f(z(q),q) : P(\\lam{\\nameless} z(q))$.\n  And since $Q$ is a mere proposition, we have $z(q) = z(q')$ for any $q':Q$, hence $e(z,q) : (\\lam{\\nameless} z(q)) = z$ by function extensionality.\n  This gives\n  \\[ \\lam{z}{q} \\trans{e(z,q)}{(f(z(q),q))} : \\prd{z:Q\\to A} Q \\to P(z) \\]\n  For the computation rule, we have\n  \\begin{align*}\n    (\\lam{z}{q} \\trans{e(z,q)}{(f(z(q),q))})(\\lam{\\nameless} a) &= \\lam{q} \\trans{e(\\lam{\\nameless} a,q)}{(f(a,q))}\\\\\n    &= \\lam{q} f(a,q) = f(a)\n  \\end{align*}\n  by function extensionality, since $e(\\lam{\\nameless} a,q) = \\refl{}$.\n  Finally, if $x,y:Q\\to A$, then $(x=y) \\simeq \\prd{q:Q} x(q) = y(q)$, and the map\n  \\[ \\Big(\\prd{q:Q} x(q) = y(q)\\Big) \\to \\Big( Q \\to \\prd{q:Q} x(q) = y(q)\\Big) \\]\n  is (by currying) essentially precomposition with a product projection $Q\\times Q\\to Q$, and that is an equivalence since $Q$ is a mere proposition.\n\\end{eg}\n\n\\begin{eg}\\label{eg:closed}\n  Again, let $Q$ be a mere proposition.\n  The \\textbf{closed modality} determined by $Q$ is defined by $\\closed Q A = Q \\ast A$, the \\emph{join} of $Q$ and $A$ (the pushout of $Q$ and $A$ under $Q\\times A$).\n  We show that this is a $\\Sigma$-closed reflective subuniverse.\n  Define a type $B$ to be modal if $Q \\to \\iscontr(B)$, and note that it is indeed the case that $Q\\to\\iscontr(Q\\ast A)$, for any type $A$.\n  By the universal property of pushouts, a map $Q \\ast A \\to B$ consists of a map $f:A\\to B$ and a map $g:Q\\to B$ and for any $a:A$ and $q:Q$ an identification $p:f(a)=g(q)$.\n  But if $Q \\to \\iscontr(B)$, then $g$ and $p$ are uniquely determined, so this is just a map $A\\to B$.\n  Thus $(\\closed Q A \\to B) \\to (A\\to B)$ is an equivalence, so we have a reflective subuniverse.\n  It is $\\Sigma$-closed since the dependent sum of a contractible family of types over a contractible base is contractible.\n\\end{eg}\n\n\\begin{eg}\\label{eg:dneg}\n  The \\textbf{double negation modality} is defined by $A\\mapsto \\neg\\neg A$, i.e.\\ $(A\\to \\emptyt)\\to \\emptyt$, with $\\modalunit(a) = \\lam{g} g(a)$.\n  We show that this is a uniquely eliminating modality.\n  Since the map $\\lam{f}f\\circ \\modalunit[A]$ that must be an equivalence has mere propositions as domain and codomain, it suffices to give a map in the other direction.\n  Thus, let $P: \\neg\\neg A \\to \\UU$ and $f:\\prd{a:A} \\neg \\neg P(\\lam{g} g(a))$; given $z:\\neg\\neg A$ we must derive a contradiction from $g:\\neg P(z)$.\n  Since we are proving a contradiction, we can strip the double negation from $z$ and assume given an $a:A$.\n  And since $\\neg\\neg A$ is a mere proposition, we have $z = \\lam{g} g(a)$, so that we can transport $f(a)$ to get an element of $\\neg\\neg P(z)$, contradicting $g$.\n\\end{eg}\n\n\\begin{eg}\n  The \\textbf{trivial modality} is the identity function on $\\UU$.\n  It coincides with $\\open \\top$ and with $\\closed\\bot$.\n\n  Dually, the \\textbf{zero modality} sends all types to $\\unit$.\n  It is equivalently the $(-2)$-truncation, and coincides with $\\open\\bot$ and with $\\closed \\top$.\n\\end{eg}\n\n\n\\paragraph*{Summary.}\nIn each of \\autoref{defn:highermod,defn:modunique,defn:ssrs,defn:sofs}\nwe have defined what it means for a type to be modal. In each case, being\nmodal is a family of mere propositions indexed by the universe, i.e.~a subuniverse.\nWe will show in \\autoref{thm:subuniv-highermod,thm:subuniv-modunique,thm:subuniverse-rs,thm:subuniv-sofs} that each kind of structure is completely determined by this subuniverse.\n(\\autoref{thm:subuniverse-rs} is more general, not requiring $\\Sigma$-closedness.)\n\nIt follows that the type of all modalities of each\nkind is a subset of the set $\\UU\\to\\prop$ of all subuniverses, and in particular is a set.\nThis makes it easier to establish\nthe equivalences of the different kinds of modalities.\nIt suffices\nto show that any modality of one kind determines a modality of the next kind\nwith the same modal types, which we will do as follows:\n\\begin{center}\n\\begin{tikzcd}\n  & \\text{higher modality} \\ar[dr,bend left,\"\\text{\\autoref{thm:modunique_from_highermod}}\"] \\\\\n  \\parbox{3cm}{\\centering stable factorization system} \\ar[ur,bend left,\"\\text{\\autoref{thm:highermod_from_sofs}}\"] &&\n  \\parbox{3cm}{\\centering uniquely eliminating modality} \\ar[dl,bend left,\"\\text{\\autoref{thm:ssrs_from_modunique}}\"] \\\\\n  & \\parbox{3cm}{\\centering $\\Sigma$-closed reflective subuniverse} \\ar[ul,bend left,\"\\text{\\autoref{thm:sofs_from_ssrs}}\"]\n\\end{tikzcd}\n\\end{center}\nBefore \\autoref{thm:sofs_from_ssrs} we take the opportunity to develop a bit more theory of reflective subuniverses, including closure under identity types (\\autoref{lem:rs_idstable}) and dependent products\n(\\autoref{lem:modal-Pi}), along with several equivalent characterizations of $\\Sigma$-closedness (\\autoref{thm:ssrs-characterize}).\n\nOf these equivalences, the most surprising is that a stable factorization system is uniquely determined by its underlying reflective subuniverse of types.\nThis is false for stable factorization systems on arbitrary categories; the reason it holds here is that we are talking \\emph{in type theory} about factorization systems \\emph{on the category of types}.\nAn analogous fact is true in classical set-based mathematics for stable factorization systems on the category of sets (although in that case there are much fewer interesting examples).\nWe \\cite{RijkeShulmanSpitters} we also observe that when type theory is interpreted in a higher category, the data of a reflective subuniverse or modality has to be interpreted ``fiberwise'', giving a richer structure than a single reflective subcategory.\n\n\n\\subsection{Higher modalities}\n\\label{sec:higher-modalities}\n\nWe start by showing that a higher modality is determined by its modal types, and gives rise to a uniquely eliminating modality.\n\n\\begin{lem}\nIf $\\modal$ is a higher modality, then any type of the form $\\modal X$ is modal.\n\\end{lem}\n\n\\begin{proof}\n  We want to show that the modal unit $\\modalunit[\\modal X]:\\modal X\\to\\modal\\modal X$\nis an equivalence. By the induction principle and the computation rule for\nhigher modalities, we find a function $f:\\modal \\modal X\\to\\modal X$ with\nthe property that $f\\circ \\modalunit[\\modal X]\\htpy\\idfunc[\\modal X]$. We wish to\nshow that we also have $\\modalunit[\\modal X]\\circ f\\htpy\\idfunc$. Since identity\ntypes of types of the form $\\modal Y$ are declared to be modal, it is\nequivalent to find a term of type\n\\begin{equation*}\n\\prd{x:\\modal \\modal X}\\modal(\\modalunit[\\modal X](f(x))=x).\n\\end{equation*}\nNow we are in the position to use the induction principle of higher modalities\nagain, so it suffices to show that $\\modalunit(f(\\modalunit(x)))=\\modalunit(x)$\nfor any $x:\\modal X$. This follows from the fact that $f\\circ\\modalunit=\\idfunc$.\n\\end{proof}\n\n\\begin{thm}\\label{thm:subuniv-highermod}\nThe data of two higher modalities $\\modal$ and $\\modal'$\nare identical if and only if they have the same modal types.\n\\end{thm}\n\n\\begin{proof}\nAnother way of stating this, is that the function from the type of \\emph{all}\nmodalities on $\\UU$ to the type $\\UU\\to\\prop$ of predicates on $\\UU$, given\nby mapping a modality to the predicate $\\ismodal$, is an embedding. Thus, we\nneed to show that for any predicate $\\mathcal{M}:\\UU\\to\\prop$, we can find at\nmost one modality for which $\\mathcal{M}$ is the class of modal types. This\nfollows, once we demonstrate that,\n\\begin{quote}\nfor any $\\mathcal{M}:\\UU\\to\\prop$ closed under identity types,\nand for any type $X$, the type of tuples $(Y,p,\\pi,I,C)$ ---\nconsisting of a type $Y$ with $p$ witnessing that $Y$\nsatisfies $\\mathcal{M}$, a function $\\pi:X\\to Y$, a function\n\\begin{equation*}\nI_P:(\\prd{x:X} P(\\pi(x)))\\to(\\prd{y:Y} P(y))\n\\end{equation*}\nfor every $P:Y\\to\\UU_{\\mathcal{M}}$,\nwhich is a right inverse of precomposing with $\\pi$, as is witnessed by the\nterm $C$ --- is a mere proposition.\n\\end{quote}\n\nWe prove this statement in two parts. First, we show that the\ntype of pairs $(I,C)$, with $I$ and $C$ of the indicated types, is a mere\nproposition for any $(Y,p,\\pi)$. After that, we show that the type of triples\n$(Y,p,\\pi)$ is also a mere proposition. These two facts combined prove the\nstatement.\n\nConsider a type $Y$ satisfying $\\mathcal{M}$, and a function $\\pi:X\\to Y$, and\nlet $(I,C)$ and $(I',C')$ be two terms witnessing that $Y$ satisfies an induction\nprinciple with a computation rule. We want to show that $(I,C)=(I',C')$, and of\ncourse it suffices to show that $(I(s),C(s))=(I'(s),C(s))$ for any\n$P:Y\\to\\UU_{\\mathcal{M}}$ and $s:\\prd{x:X}P(\\pi(x))$.\n\nTo show that $I(s,y)=I'(s,y)$ for any $y:Y$, we use\nthe induction principle $(I,C)$. So it suffices to show that\n$I(s,\\pi(x))=I'(s,\\pi(x))$. Both of these terms are equal to $s(x)$. Thus,\nwe obtain a proof $J(s,y)$ that $I(s,y)=I'(s,y)$, with the property that\n$J(s,\\pi(x))=\\ct{C(s,x)}{\\inv{C'(s,x)}}$.\nNow we need to show that $\\trans{J(s)}{C(s)}=C'(s)$, which is equivalent\nto the property we just stated. This finishes the proof that the type of\nthe induction principle and computation rule is a mere proposition.\n\nIt remains to show that $(Y,\\pi)=(Y',\\pi')$, provided that $Y$ and $Y'$ are both\nin $\\mathcal{M}$, and that both sides satisfy\nthe induction principle and computation rule. It suffices to find an equivalence\n$f:Y\\to Y'$ such that $f\\circ \\pi=\\pi'$.\n\nFrom the induction principles of $Y$ resp. $Y'$, we obtain a function\n$f:Y\\to Y'$ with the property that $f\\circ \\pi=\\pi'$, and a function\n$f':Y'\\to Y$ with the property that $f'\\circ \\pi'=\\pi$.\nTo show that $f'\\circ f=\\idfunc$ we use the induction principle\nof $Y$. Since the type $f'(f(y))=y$ is in $\\mathcal{M}$, it suffices to show that\n$f'(f(\\pi(y)))=\\pi(y)$. This readily follows from the defining properties of $f$\nand $f'$. Similarly, we have $f\\circ f'=\\idfunc$.\n\\end{proof}\n\n\\begin{thm}\\label{thm:modunique_from_highermod}\nA higher modality is a uniquely eliminating modality, with the\nsame modal types.\n\\end{thm}\n\n\\begin{proof}\nLet $\\modal$ be a modality with modal units $\\modalunit[A]$. Our goal is to show\nthat the pre-composition map\n\\begin{equation*}\n\\lam{s}s\\circ\\modalunit[A]:(\\prd{x:\\modal A}\\modal(P(x)))\\to(\\prd{a:A}\\modal(P(\\modalunit[A](a))))\n\\end{equation*}\nis an equivalence for each $A:\\UU$ and $P:\\modal A\\to\\UU$.\nBy the given induction principle and computation rule, we obtain a\nright inverse $\\mathsf{ind}_{\\modal A}$ of $\\blank\\circ\\modalunit[A]$.\n\nTo show that it is a left inverse, consider $s:\\prd{x:\\modal A}\\modal(P(x))$.\nWe need to find a homotopy\n\\begin{equation*}\n\\prd{x:\\modal A}\\id{s(x)}{\\mathsf{ind}_{\\modal A}(s\\circ \\modalunit_A)(x)}.\n\\end{equation*}\nBy assumption we have that $P(x)$ is\nmodal for each $z:\\modal A$ and hence it follows that $\\id{s(x)}{\\mathsf{ind}_{\\modal A}(s\\circ \\modalunit_A)(x)}$\nis modal for each $x$. Hence it suffices to find a function of type\n\\begin{equation*}\n\\prd{a:A}\\id{s(\\modalunit_A(a))}{\\mathsf{ind}_{\\modal A}(s\\circ \\modalunit_A)(\\modalunit_A(a))}.\n\\end{equation*}\nThis follows straight from the computation rule of higher modalities.\n\\end{proof}\n\n\\subsection{Uniquely eliminating modalities}\n\\label{sec:uniq-elim}\n\nNext, we show that a uniquely eliminating modality is determined by its modal types, and gives rise to a $\\Sigma$-closed reflective subuniverse.\n\n\\begin{lem}\nGiven a uniquely eliminating modality, $\\modal X$ is modal for any type $X$.\n\\end{lem}\n\n\\begin{proof}\nUsing the elimination principle of $\\modal \\modal X$, we find a function\n$f:\\modal \\modal X\\to\\modal X$ and an identification $f\\circ\\modalunit[\\modal X]=\\idfunc[\\modal X]$.\nBy the uniqueness property, the type\n\\begin{equation*}\n\\sm{g:\\modal \\modal X\\to\\modal \\modal X} g\\circ\\modalunit[\\modal X]=\\modalunit[\\modal X]\n\\end{equation*}\nis contractible. Since both $\\idfunc[\\modal \\modal X]$ and $\\modalunit[\\modal X]\\circ f$\nare in this type (with suitable identifications), we find that $f$ is also the\nright inverse of $\\modalunit[\\modal X]$. This shows that $\\modalunit[\\modal X]$ is an\nequivalence, so $\\modal X$ is modal.\n\\end{proof}\n\n\\begin{thm}\\label{thm:subuniv-modunique}\nThe data of two uniquely eliminating modalities $\\modal$ and $\\modal'$ are equivalent if and only if both have the same modal types.\n\\end{thm}\n\n\\begin{proof}\nWe need to show that the type of uniquely eliminating modalities\nwith a given class $\\mathcal{M}:\\UU\\to\\prop$ of modal types\nis a mere proposition. Since the types of the form $\\modal X$ are modal,\nit suffices to show for any class $\\mathcal{M}\n:\\UU\\to\\prop$ and any type $X$, that\n\\begin{quote}\nthe type of tuples $(Y,p,\\pi,H)$ --- consisting of a type $Y$\nwith $p$ witnessing that $Y$ is in $\\mathcal{M}$, a function $\\pi:X\\to Y$, and\nfor each $P:Y\\to\\UU$ a term $H_P$ witnessing that the function\n\\begin{equation*}\n\\lam{s}s\\circ \\pi:(\\prd{y:Y}\\modal(P(y)))\\to(\\prd{x:X}\\modal(P(\\pi(x))))\n\\end{equation*}\nis an equivalence --- is a mere proposition.\n\\end{quote}\nLet $(Y,p,\\pi,H)$ and $(Y',p',\\pi',H')$ be such tuples. To show that they are\nequal, it suffices to show that $(Y,\\pi)=(Y',\\pi')$ because the other things\nin the list are terms of mere propositions. Furthermore, showing that\n$(Y,\\pi)=(Y',\\pi')$ is equivalent to finding an equivalence $f:\\eqv{Y}{Y'}$ with\nthe property that $f\\circ\\pi=\\pi'$. By $H$, there is such a function, and by\n$H'$ there is a function $f':Y'\\to Y$ such that $f'\\circ\\pi'=\\pi$. Now the\nuniqueness gives that $f'\\circ f$ is the only function from $Y$ to $Y$ such\nthat $f'\\circ f\\circ\\pi=\\pi$ and of course $\\idfunc[Y]$ is another such function.\nTherefore it follows that $f'\\circ f=\\idfunc$, and similarly it follows that\n$f\\circ f'=\\idfunc$.\n\\end{proof}\n\n\\begin{thm}\\label{thm:ssrs_from_modunique}\nAny uniquely eliminating modality determines a $\\Sigma$-closed reflective\nsubuniverse with the same modal types.\n\\end{thm}\n\n\\begin{proof}\nIt is immediate from the definition of uniquely eliminating modalities\nthat every map $f:A\\to B$ into a modal type $B$ has a homotopy unique extension to $\\modal A$\nalong the modal unit:\n\\begin{equation*}\n\\begin{tikzcd}\nA \\arrow[dr,\"f\"] \\arrow[d,swap,\"\\modalunit_A\"] \\\\ \\modal A \\arrow[r,densely dotted,swap,\"\\tilde f\"] & B\n\\end{tikzcd}\n\\end{equation*}\nSince the types of the form $\\modal X$ are modal, we obtain a reflective subuniverse.\nIt remains to verify  that the type $\\sm{x:\\modal X}\\modal(P(x))$ is modal for\nany type $X$ and $P:X\\to\\UU$. We have the function\n\\begin{equation*}\n\\varphi\\defeq\\lam{m}\\pairr{f(m),g(m)}:\\modal(\\sm{x:\\modal X}\\modal(P(x)))\\to\\sm{x:\\modal X}\\modal(P(x)),\n\\end{equation*}\nwhere\n\\begin{align*}\nf & \\defeq \\ind{\\modal}(\\lam{x}{u} x) & & : \\modal(\\sm{x:\\modal X}\\modal(P(x)))\\to \\modal X \\\\\ng & \\defeq \\ind{\\modal}(\\lam{x}{u} u) & & : \\prd{w:\\modal(\\sm{x:\\modal X}\\modal(P(x)))} \\modal(P(f(w)))\n\\end{align*}\nOur goal is to show that $\\varphi$ is an inverse to the modal unit.\n\nNote that\n\\begin{equation*}\n\\varphi(\\modalunit(x,y)) \\jdeq \\pairr{f(\\modalunit(x,y)),g(\\modalunit(x,y))} \\jdeq \\pairr{x,y},\n\\end{equation*}\nso we see immediately that $\\varphi$ is a left inverse of $\\modalunit$.\n\nTo show that $\\varphi$ is a right inverse of $\\modalunit$, note that the type\nof functions $h$ fitting in a commuting square of the form\n\\begin{equation*}\n\\begin{tikzcd}[column sep=-3em]\n\\modal(\\sm{x:\\modal X}\\modal(P(x))) \\arrow[rr,densely dotted,\"h\"] & & \\modal(\\sm{x:\\modal X}\\modal(P(x))) \\\\\n& \\sm{x:\\modal X}\\modal(P(x)) \\arrow[ul,\"\\modalunit\"] \\arrow[ur,swap,\"\\modalunit\"]\n\\end{tikzcd}\n\\end{equation*}\nis contractible, and it contains the identity function. Therefore, it suffices\nto show that $(\\modalunit\\circ\\varphi)\\circ\\modalunit=\\modalunit$, but this follows\nfrom the fact that $\\varphi$ is a left inverse of the modal unit.\n\\end{proof}\n\n\\subsection{\\texorpdfstring{$\\Sigma$}{Σ}-closed reflective subuniverses}\n\\label{sec:ssrs}\n\nNow we study reflective subuniverses in a bit more detail, and end by\nshowing that $\\Sigma$-closed ones give rise to stable factorization\nsystems. $\\Sigma$-closure is used in \\autoref{thm:sofs_from_ssrs} to\nshow that left maps and right maps are closed under composition.\n\n\n\n\\subsubsection{\\texorpdfstring{$\\Sigma$}{Σ}-closed reflective subuniverses}\n\\label{sec:sigma-closed}\n\n\\begin{defn}\\label{defn:connected}\nLet $\\mathcal{M}:\\UU\\to\\prop$ be a reflective subuniverse with modal\noperator $\\modal$. We say\nthat a type $X$ is \\define{$\\modal$-connected} if $\\modal X$ is contractible,\nand we say that a function $f:X\\to Y$ is \\define{$\\modal$-connected} if each\nof its fibers is. Similarly, we say that $f$ is \\define{modal} if each of its\nfibers is.\n\\end{defn}\n\nNote that a type $X$ is modal or $\\modal$-connected just when the map $X\\to\\unit$ is.\n\n\\begin{eg}\\label{eg:closed-connected}\n  Recall from \\cref{eg:open} that the open modality associated to a proposition $Q$ is defined by $\\open Q(A) \\defeq (Q\\to A)$.\n  We claim that $A$ is $\\open Q$-connected if and only if $Q \\to\\iscontr(A)$.\n  In other words, $(Q \\to\\iscontr(A))\\eqvsym \\iscontr(Q\\to A)$.\n  For on the one hand, if $Q\\to \\iscontr(A)$, then $Q\\to A$; while any two $f,g:Q\\to A$ can be shown equal by function extensionality, since if $Q$ then $A$ is contractible.\n  But on the other hand, if $\\iscontr(Q\\to A)$ and $Q$, then $\\eqv{(Q\\to A)}{A}$, hence $\\iscontr(A)$.\n\n  Note that $Q \\to\\iscontr(A)$ is also the defining condition for the $\\closed Q$-modal types from \\cref{eg:closed}.\n  That is, the $\\open Q$-connected types coincide with the $\\closed Q$-modal types.\n\\end{eg}\n\nThe following theorem combines Lemma 7.5.7 and Theorem 7.7.4 of \\cite{hottbook}.\n\n\\begin{thm}\\label{thm:ssrs-characterize}\nGiven a reflective universe with modal operator $\\modal$,\nthe following are equivalent:\n\\begin{enumerate}\n\\item It is $\\Sigma$-closed.\n\\item It is uniquely eliminating.\n\\item The modal units are $\\modal$-connected.\n\\end{enumerate}\n\\end{thm}\n\n\\begin{proof}\nSuppose first that $\\modal$ is $\\Sigma$-closed, let $X$ be a type and let\n$P:\\modal X\\to\\UU_\\modal$, i.e.\\ $P(x)$ is modal for each $x:\\modal X$.\nTo show that $\\modal$ is uniquely eliminating, we want\n\\begin{equation*}\n\\lam{s}s\\circ\\modalunit[X]:(\\prd{x:\\modal X}P(x))\\to(\\prd{x:X}P(\\modalunit(x)))\n\\end{equation*}\nto be an equivalence. Since the type $\\prd{a:A}B(a)$ is equivalent to the type\nof functions $f:A\\to\\sm{a:A}B(a)$ such that $\\proj1\\circ f=\\idfunc[A]$, we\nget the desired equivalence if the pre-composition map $\\lam{j}j\\circ\\modalunit$\ngives an equivalence from diagonal fillers of the square\n\\begin{equation*}\n\\begin{tikzcd}\nX \\arrow[r,densely dotted] \\arrow[d,swap,\"\\modalunit\"] & \\sm{x:\\modal X}P(x) \\arrow[d,\"\\proj1\"] \\\\\n\\modal X \\arrow[ur,densely dotted,\"j\"] \\arrow[r,equals] & \\modal X\n\\end{tikzcd}\n\\end{equation*}\nto the type of maps $X\\to\\sm{x:\\modal X}P(x)$ such that the indicated square\ncommutes.  But this is true by the universal property of $\\modalunit$, since $\\sm{x:\\modal X}P(x)$ is modal by $\\Sigma$-closedness.\n\nNow suppose that $\\modal$ is uniquely eliminating.\nTo show that the modal units are connected, we want a term of type\n\\begin{equation*}\n\\prd{x:\\modal X}\\iscontr(\\modal(\\fib{\\modalunit}{x})).\n\\end{equation*}\nUsing the dependent eliminators, it is easy to find a term\n$s:\\prd{x:\\modal X}\\modal(\\fib{\\modalunit}{x})$ with the property that\n$s\\circ\\modalunit(x)=\\modalunit(x,\\refl{\\modalunit(x)})$. Now we need to show\nthat\n\\begin{equation*}\n\\prd{x:\\modal X}{w:\\modal(\\fib{\\modalunit}{x})}w=s(x).\n\\end{equation*}\nSince the type $w=s(x)$ is modal, this is equivalent to\n\\begin{equation*}\n\\prd{x:\\modal X}{x':X}{p:\\modalunit(x')=x} \\modalunit(x',p)=s(x).\n\\end{equation*}\nMoreover, the type $\\sm{x:\\modal X}\\modalunit(x')=x$ is contractible, so this\nis equivalent to\n\\begin{equation*}\n\\prd{x':X} \\modalunit(x',\\refl{\\modalunit(x')})=s(\\modalunit(x')),\n\\end{equation*}\nof which we have a term by the defining property of $s$.\n\nFinally, suppose that all the modal units are $\\modal$-connected, let $X$ be modal and let $P:X\\to\\UU_\\modal$.\nTo show that $\\sm{x:X}P(x)$ is modal, we show that\n$\\modalunit:(\\sm{x:X}P(x))\\to\\modal(\\sm{x:X}P(x))$ is an equivalence.\nSince $X$ is modal, we can extend $\\proj 1$ along $\\modalunit$ as indicated\nin the diagram\n\\begin{equation*}\n\\begin{tikzcd}\n\\sm{x:X}P(x) \\arrow[d,\"\\modalunit\"] \\arrow[dr,\"\\proj 1\"] \\\\\n\\modal(\\sm{x:X}P(x)) \\arrow[r,densely dotted,swap,\"p\"] & X\n\\end{tikzcd}\n\\end{equation*}\nThe type of maps\n\\begin{equation*}\nf:\\modal(\\sm{x:X}P(x))\\to \\sm{x:X}P(x)\n\\end{equation*}\nsuch that $\\proj1\\circ f=p$ is equivalent to the type $\\prd{z:\\modal(\\sm{x:X}P(x))}P(p(z))$.\nUsing the assumption that $\\modalunit$ is connected, we calculate\n\\begin{align*}\n\\prd{z:\\modal(\\sm{x:X}P(x))}P(p(z))\n& \\eqvsym \\prd{z:\\modal(\\sm{x:X}P(x))} \\modal(\\fib{\\modalunit}{z})\\to P(p(z)) \\\\\n& \\eqvsym \\prd{z:\\modal(\\sm{x:X}P(x))} \\fib{\\modalunit}{z}\\to P(p(z)) \\\\\n& \\eqvsym \\prd{\\pairr{x,y}:\\sm{x:X}P(x)} P(x)\n\\end{align*}\nWe have the second projection $\\proj 2$ of the latter type. We obtain a term\n\\begin{equation*}\nq : \\prd{z:\\modal(\\sm{x:X}P(x))}P(p(z))\n\\end{equation*}\nsuch that $q(\\eta(x,y))=y$. Therefore, we get the map $\\pairr{p,q}:\\modal(\\sm{x:X}P(x))\\to \\sm{x:X}P(x)$ for which the diagram\n\\begin{equation*}\n\\begin{tikzcd}\n\\sm{x:X}P(x) \\arrow[dr,\"\\modalunit\"] \\arrow[ddr,bend right=15,swap,\"\\proj 1\"] \\arrow[rr,\"\\idfunc\"] & & \\sm{x:X}P(x) \\arrow[ddl,bend left=15,\"\\proj 1\"] \\\\\n& \\modal(\\sm{x:X}P(x)) \\arrow[d,swap,\"p\"] \\arrow[ur,densely dotted,\"\\pairr{p,q}\"] \\\\\n& X\n\\end{tikzcd}\n\\end{equation*}\ncommutes. In particular, $\\pairr{p,q}$ is a left inverse of the modal unit.\nTo see that it is also a right inverse, note that $\\modalunit\\circ\\pairr{p,q}\\circ\\modalunit=\\modalunit=\\idfunc\\circ\\modalunit$; thus $\\modalunit\\circ\\pairr{p,q}=\\idfunc$ follows by uniqueness.\nHence $\\sm{x:X}P(x)$ is modal.\n\\end{proof}\n\n\\begin{thm}\\label{thm:sofs_from_ssrs}\nA $\\Sigma$-closed reflective subuniverse determines a stable orthogonal factorization system with the same\nmodal types.\n\\end{thm}\n\n\\begin{proof}\nDefine $\\mathcal{L}$ to be the class of $\\modal$-connected\nmaps and $\\mathcal{R}$ to be the class of modal maps.\nWe first show that both $\\mathcal{L}$ and $\\mathcal{R}$ are closed under\ncomposition. Recall that for $f:X\\to Y$ and $g:Y\\to Z$, one has\n$\\fib{g\\circ f}{z}=\\sm{p:\\fib{g}{z}}\\fib{f}{\\proj1(p)}$.\nThus, by $\\Sigma$-closedness, if $f$ and $g$ are both in $\\mathcal{R}$ then so is $g\\circ f$, so $\\cR$ is closed under composition; while \\cref{thm:rsu-compose-cancel} implies that $\\cL$ is closed under composition.\nAnd since the fibers of an identity map are contractible, and contractible types are both modal and $\\modal$-connected, both $\\mathcal{L}$ and $\\mathcal{R}$ contain all identities.\n\n% Next, we need to show that $\\mathcal{L}(f)\\land\\mathcal{R}(f)\\leftrightarrow\n% \\isequiv(f)$. Since a function is an equivalence if and only if its fibers are\n% contractible, and since the contractible types are modal in any reflective\n% universe, it follows that $\\isequiv(f)\\to\\mathcal{L}(f)\\land\\mathcal{R}(f)$.\n% Now suppose that $f$ is in $\\mathcal{L}$ and in $\\mathcal{R}$. Then its fibers\n% are modal, and the modal operator applied to its fibers results in a contractible\n% type, so it is an equivalence.\n\nTo obtain a factorization system,\nit remains to show that the type of\n$(\\mathcal{L},\\mathcal{R})$-factorizations of any function $f$ is contractible.\nSince $\\pairr{X,f}=\\pairr{\\sm{y:Y}\\fib{f}{y},\\proj1}$, it is sufficient to\nshow that $\\fact_{\\mathcal{L},\\mathcal{R}}(\\proj1)$ is contractible for any\n$\\proj1:\\sm{y:Y}P(y)\\to Y$. But $\\proj1$ factors as\n\\begin{equation*}\n\\begin{tikzcd}\n\\sm{y:Y}P(y) \\arrow[r,\"p_\\mathcal{L}\"] & \\sm{y:Y}\\modal(P(y)) \\arrow[r,\"p_\\mathcal{R}\"] & Y\n\\end{tikzcd}\n\\end{equation*}\nwhere $p_\\mathcal{L}\\defeq\\total{\\modalunit[P(\\blank)]}$ and $p_\\mathcal{R}\\defeq\\proj1$.\nThe fibers of $p_\\mathcal{R}$ are $\\modal(P(\\blank))$, so it follows\nimmediately that $p_\\mathcal{R}$ is in $\\mathcal{R}$.\nMoreover, since\n$\\eqv{\\fib{\\total{\\modalunit}}{\\pairr{y,u}}}{\\fib{\\modalunit[P(y)]}{u}}$ and each $\\modalunit$ is $\\modal$-connected, it follows that $p_\\mathcal{L}$ is in\n$\\mathcal{L}$.\n\nNow consider any other factorization $(g,h,H)$ of $\\proj1$ into\nan $\\cL$-map $g:(\\sm{y:Y}P(y))\\to I$ followed by an $\\cR$-map $h:I\\to Y$. Since\n$I=\\sm{y:Y}\\fib{h}{y}$, we have a commuting square\n\\begin{equation*}\n\\begin{tikzcd}\n\\sm{y:Y}P(y) \\arrow[r,\"g\"] \\arrow[d,swap,\"{\\total{\\gamma}}\"]\n  & I \\arrow[d,\"h\"] \\\\\n\\sm{y:Y}\\fib{h}{y} \\arrow[ur,equals] \\arrow[r,swap,\"\\proj1\"] & Y\n\\end{tikzcd}\n\\end{equation*}\nin which $\\gamma(y,u)\\defeq \\pairr{g(y,u),H(y,u)}$.\nIt follows that $(g,h,H)=(\\total{\\gamma},\\proj1,\\nameless)$.\nThus suffices to show that there is a commuting triangle\n\\begin{equation*}\n\\begin{tikzcd}[column sep=0]\n& P(y) \\arrow[dl,swap,\"\\modalunit\"] \\arrow[dr,\"{\\gamma_y}\"] \\\\\n\\modal(P(y)) \\arrow[rr,equals] & & \\fib{h}{y}\n\\end{tikzcd}\n\\end{equation*}\nWe will do this using \\cref{lem:reflective_uniqueness}, by showing that $\\gamma_y$ has the same universal property as $\\modalunit[P(y)]$.\nThis follows from the following calculation:\n\\begin{align*}\n(\\fib{h}{y}\\to Z) & \\eqvsym ((\\sm{w:\\fib{h}{y}}\\modal(\\fib{g}{\\proj1(w)}))\\to Z) \\\\\n& \\eqvsym ((\\sm{w:\\fib{h}{y}}\\fib{g}{\\proj1(w)})\\to Z) \\\\\n& \\eqvsym (\\fib{h\\circ g}{y}\\to Z) \\\\\n& \\eqvsym (P(y)\\to Z).\n\\end{align*}\nwhich we can verify is given by precomposition with $\\gamma_y$.\n\nIt remains to show that our orthogonal factorization system is stable. Consider a pullback diagram\n\\begin{equation*}\n\\begin{tikzcd}\nA' \\arrow[d,swap,\"k\"] \\arrow[r,\"f\"] & A \\arrow[d,\"l\"] \\\\\nB' \\arrow[r,swap,\"g\"] & B\n\\end{tikzcd}\n\\end{equation*}\nin which $l$ is in $\\mathcal{L}$. By the pasting lemma for pullbacks, it\nfollows that $\\fib{k}{b}=\\fib{l}{g(b)}$ for each $b:B'$. Thus, it follows that\n$k$ is in $\\mathcal{L}$.\n\\end{proof}\n\n\n\\subsection{Stable orthogonal factorization systems}\n\nTo complete \\cref{sec:modal-refl-subun}, we will show that stable orthogonal factorization systems are also determined by their modal types, and give rise to higher modalities.\n\n\\subsubsection{Orthogonal factorization systems}\n\nIn classical category theory, orthogonal factorization systems are equivalently characterized by a unique lifting property.\nWe begin with the analogue of this in our context.\n\n\\begin{defn}\nLet $(\\mathcal{L},\\mathcal{R})$ be an orthogonal factorization system, and\nconsider a commutative square\n\\begin{equation*}\n\\begin{tikzcd}\nA \\arrow[r,\"f\"] \\arrow[d,swap,\"l\"] \\ar[dr,phantom,\"\\scriptstyle S\"] & X \\arrow[d,\"r\"] \\\\\nB \\arrow[r,swap,\"g\"] & Y\n\\end{tikzcd}\n\\end{equation*}\n(i.e.\\ paths $S : r\\circ f = g\\circ l$)\nfor which $l$ is in $\\mathcal{L}$ and $r$ is in $\\mathcal{R}$. We define\n$\\fillers S$ to be the type of \\define{diagonal fillers}\nof the above diagram, i.e.~the type of tuples $(j,H_f,H_g,K)$ consisting of\n$j:B\\to X$, $H_f:j\\circ l=f$ and $H_g:r\\circ j=g$ and an equality $K : r\\circ H_f = \\ct S{(H_g \\circ l)}$.\n\\end{defn}\n\n\\begin{lem}\\label{lem:diagonal_fillers}\nLet $(\\mathcal{L},\\mathcal{R})$ be an orthogonal factorization system, and\nconsider a commutative square\n\\begin{equation*}\n\\begin{tikzcd}\nA \\arrow[r,\"f\"] \\arrow[d,swap,\"l\"] \\ar[dr,phantom,\"\\scriptstyle S\"] & X \\arrow[d,\"r\"] \\\\\nB \\arrow[r,swap,\"g\"] & Y\n\\end{tikzcd}\n\\end{equation*}\nfor which $l$ is in $\\mathcal{L}$ and $r$ is in $\\mathcal{R}$. Then the type\n$\\fillers S$ of diagonal fillers is contractible.\n\\end{lem}\n\n\\begin{proof}\nBy the fact that every morphism factors uniquely as a left map followed by a\nright map, we may factorize $f$ and $g$ in $(\\mathcal{L},\\mathcal{R})$ as $H_f : f = f_\\cR \\circ f_\\cL$ and $H_g : g = g_\\cR \\circ g_\\cL$, obtaining the diagram\n\\begin{equation*}\n\\begin{tikzcd}\nA \\arrow[r,\"f_{\\mathcal{L}}\"] \\arrow[d,swap,\"l\"] & \\im(f) \\arrow[r,\"f_{\\mathcal{R}}\"] & X \\arrow[d,\"r\"] \\\\\nB \\arrow[r,swap,\"g_{\\mathcal{L}}\"] & \\im(g) \\arrow[r,swap,\"g_{\\mathcal{R}}\"] & Y\n\\end{tikzcd}\n\\end{equation*}\nNow both $(r\\circ f_{\\mathcal{R}})\\circ f_{\\mathcal{L}}$ and\n$g_{\\mathcal{R}}\\circ(g_{\\mathcal{L}}\\circ l)$ are factorizations\nof the same function $r\\circ f:A\\to Y$.\nSince $\\fact_{\\mathcal{L},\\mathcal{R}}(r\\circ f)$ is contractible, so is its identity type\n\\[ (\\im(f), f_\\cL, r\\circ f_\\cR, r\\circ H_f) = (\\im(g), g_\\cL \\circ l, g_\\cR, \\ct{S}{(H_g\\circ l)}). \\]\nThis identity type is equivalent to\n\\begin{multline*}\n\\sm{e:\\im(f) \\simeq \\im(g)}{H_\\cL : g_\\cL \\circ l = e\\circ f_\\cL}{H_\\cR : r\\circ f_\\cR = g_\\cR\\circ e}\\\\\n(\\ct{(r\\circ H_f)}{(H_\\cR \\circ f_\\cL)} = \\ct S{\\ct{(H_g \\circ l)}{(g_\\cR \\circ H_\\cL)}})\n\\end{multline*}\nNow since $\\fact_{\\cL,\\cR}(f)$ and $\\fact_{\\cL,\\cR}(g)$ are also contractible, we can sum over them to get that the following type is contractible:\n\\begin{multline*}\n  \\sm{\\im(f):\\UU}{f_\\cL : A \\to \\im(f)}{f_\\cR : \\im(f) \\to X}{H_f : f = f_\\cR \\circ f_\\cL}\\\\\n  \\sm{\\im(g):\\UU}{g_\\cL : B \\to \\im(g)}{g_\\cR : \\im(g) \\to Y}{H_g : g = g_\\cR \\circ g_\\cL}\\\\\n\\sm{e:\\im(f) \\simeq \\im(g)}{H_\\cL : g_\\cL \\circ l = e\\circ f_\\cL}{H_\\cR : r\\circ f_\\cR = g_\\cR\\circ e}\\\\\n(\\ct{(r\\circ H_f)}{(H_\\cR \\circ f_\\cL)} = \\ct S{\\ct{(H_g \\circ l)}{(g_\\cR \\circ H_\\cL)}})\n\\end{multline*}\n(omitting the hypotheses that $f_\\cL,g_\\cL\\in\\cL$ and $f_\\cR,g_\\cR\\in\\cR$).\nReassociating and removing the contractible type $\\sm{\\im(g):\\UU}(\\im(f) \\simeq \\im(g))$, and renaming $\\im(f)$ as simply $I$, this is equivalent to\n\\begin{multline*}\n  \\sm{I:\\UU}{f_\\cL : A \\to I}{f_\\cR : I \\to X}{H_f : f = f_\\cR \\circ f_\\cL}\\\\\n  \\sm{g_\\cL : B \\to I}{g_\\cR : I \\to Y}{H_g : g = g_\\cR \\circ g_\\cL}{H_\\cL : g_\\cL \\circ l = f_\\cL}{H_\\cR : r\\circ f_\\cR = g_\\cR}\\\\\n(\\ct{(r\\circ H_f)}{(H_\\cR \\circ f_\\cL)} = \\ct S{\\ct{(H_g \\circ l)}{(g_\\cR \\circ H_\\cL)}})\n\\end{multline*}\nRemoving the contractible $\\sm{f_\\cL : A \\to I} (g_\\cL \\circ l = f_\\cL)$ and $\\sm{g_\\cR : I \\to Y} (r\\circ f_\\cR = g_\\cR)$, this becomes\n\\begin{multline*}\n  \\sm{I:\\UU}{f_\\cR : I \\to X}{g_\\cL : B \\to I}{H_f : f = f_\\cR \\circ g_\\cL \\circ l}{H_g : g = r\\circ f_\\cR \\circ g_\\cL}\\\\\n(r\\circ H_f = \\ct S{(H_g \\circ l)})\n\\end{multline*}\nInserting a contractible $\\sm{j:B\\to X} (f_\\cR \\circ g_\\cL = j)$, and reassociating more, we get\n\\begin{multline*}\n  \\sm{j:B\\to X}{I:\\UU}{f_\\cR : I \\to X}{g_\\cL : B \\to I}{H_j:f_\\cR \\circ g_\\cL = j}\\\\\n  \\sm{H_f : f = f_\\cR \\circ g_\\cL \\circ l}{H_g : g = r\\circ f_\\cR \\circ g_\\cL}\n  (r\\circ H_f = \\ct S{(H_g \\circ l)})\n\\end{multline*}\nBut now $\\sm{I:\\UU}{f_\\cR : I \\to X}{g_\\cL : B \\to I}{H_j:f_\\cR \\circ g_\\cL = j}$ is just $\\fact_{\\cL,\\cR}(j)$, hence contractible.\nRemoving it, we get\n\\begin{equation*}\n  \\sm{j:B\\to X}{H_f : f = j \\circ l}{H_g : g = r\\circ j}(r\\circ H_f = \\ct S{(H_g \\circ l)})\n\\end{equation*}\nwhich is just $\\fillers S$.\nTherefore, this is also contractible.\n\\end{proof}\n\n\\begin{defn}\\label{defn:orthogonal}\nFor any class $\\mathcal{C}:\\prd*{A,B:\\UU}(A\\to B)\\to\\prop$ of maps, we define\n\\begin{enumerate}\n\\item $^{\\bot}\\mathcal{C}$ to be the class of maps with \\define{(unique) left lifting\nproperty} with respect to all maps in $\\mathcal{C}$: the mere proposition\n$^\\bot\\mathcal{C}(l)$ asserts that for every commutative square\n\\begin{equation*}\n\\begin{tikzcd}\nA \\arrow[r,\"f\"] \\arrow[d,swap,\"l\"] \\ar[dr,phantom,\"S\"] & X \\arrow[d,\"r\"] \\\\\nB \\arrow[r,swap,\"g\"] & Y\n\\end{tikzcd}\n\\end{equation*}\nwith $r$ in $\\mathcal{C}$, the type $\\fillers S$ of diagonal fillers is contractible.\n\\item $\\mathcal{C}^\\bot$ to be the class of maps with the dual \\define{(unique) right lifting\nproperty} with respect to all maps in $\\mathcal{C}$.\n\\end{enumerate}\n\\end{defn}\n\n\\begin{lem}\\label{lem:ofs_lifting}\nIn an orthogonal factorization system $(\\mathcal{L},\\mathcal{R})$, one has\n$\\mathcal{L}={^\\bot\\mathcal{R}}$ and $\\mathcal{L}^\\bot=\\mathcal{R}$.\n\\end{lem}\n\n\\begin{proof}\nWe first show that $\\mathcal{L}={^\\bot\\mathcal{R}}$, i.e.~we show that\n$\\mathcal{L}(f)\\leftrightarrow {^\\bot\\mathcal{R}}(f)$ for any map $f$. Note\nthat the implication $\\mathcal{L}(f)\\to {^\\bot\\mathcal{R}}(f)$ follows from\n\\autoref{lem:diagonal_fillers}.\n\nLet $f:A\\to B$ be a map in ${^\\bot\\mathcal{R}}$.\nWe wish to show that $\\mathcal{L}(f)$. Consider the factorization\n$(f_{\\mathcal{L}},f_{\\mathcal{R}})$ of $f$. Then the square\n\\begin{equation*}\n\\begin{tikzcd}\nA \\arrow[r,\"f_{\\mathcal{L}}\"] \\arrow[d,swap,\"f\"] & \\mathsf{im}_{\\mathcal{L},\\mathcal{R}}(f) \\arrow[d,\"f_{\\mathcal{R}}\"] \\\\\nB \\arrow[r,swap,\"\\idfunc\"] & B\n\\end{tikzcd}\n\\end{equation*}\ncommutes. Since $f$ has the left lifting property, the type of diagonal fillers\nof this square is contractible. Thus we have a section $j$ of $f_{\\mathcal{R}}$.\nThe map $j\\circ f_\\mathcal{R}$ is then a diagonal filler of the square\n\\begin{equation*}\n\\begin{tikzcd}\nA \\arrow[r,\"f_{\\mathcal{L}}\"] \\arrow[d,swap,\"f_{\\mathcal{L}}\"] & \\mathsf{im}_{\\mathcal{L},\\mathcal{R}}(f) \\arrow[d,\"f_{\\mathcal{R}}\"] \\\\\n\\mathsf{im}_{\\mathcal{L},\\mathcal{R}}(f) \\arrow[r,swap,\"f_{\\mathcal{R}}\"] & B\n\\end{tikzcd}\n\\end{equation*}\nOf course, the identity map $\\idfunc[\\mathsf{im}_{\\mathcal{L},\\mathcal{R}}(f)]$\nis also a diagonal filler for this square, so the fact that the type of\nsuch diagonal fillers is contractible implies that $j\\circ f_{\\mathcal{R}}=\\idfunc$.\nThus, $j$ and $f_\\cR$ are inverse equivalences, and so the pair $(B,f)$ is equal to the pair $(\\mathsf{im}_{\\mathcal{L},\\mathcal{R}}(f),f_\\cL)$.\nHence $f$, like $f_\\cL$, is in $\\cL$.\n\nSimilarly, \\autoref{lem:diagonal_fillers} also implies that $\\mathcal{R}(f)\\to \\mathcal{L}^\\bot(f)$\nfor any map $f$, while we can prove $\\mathcal{L}^\\bot(f)\\to\\mathcal{R}(f)$ analogously to ${^\\bot\\mathcal{R}}(f)\\to\\mathcal{L}(f)$.\n\\end{proof}\n\n\\begin{cor}\\label{lem:sofs_req}\nThe data of two orthogonal factorization systems $(\\mathcal{L},\\mathcal{R})$ and\n$(\\mathcal{L}',\\mathcal{R}')$ are identical if and only if\n$\\mathcal{R}=\\mathcal{R}'$.\n\\end{cor}\n\\begin{proof}\n  ``Only if'' is obvious.\n  Conversely, if $\\mathcal{R}=\\mathcal{R}'$, then by \\cref{lem:ofs_lifting} we have $\\cL = \\cL'$, and the remaining data of an orthogonal factorization system is a mere proposition.\n\\end{proof}\n\n\\begin{comment}\n\\begin{lem}[Unfinished]\nFor each $l:X\\to Y$ such that $\\mathcal{L}(l)$ and each type $Z$, the function\n\\begin{equation*}\n\\lam{g} g\\circ l: (\\sm{g:Y\\to Z}\\mathcal{R}(g))\\to(\\sm{f:X\\to Z}\\mathcal{R}(f))\n\\end{equation*}\nis a monomorphism. Also, for each $r:X\\to Y$ such that $\\mathcal{R}(r)$ and\neach type $Z$, the function\n\\begin{equation*}\n\\lam{f} r\\circ f : (\\sm{f:Z\\to X}\\mathcal{L}(f))\\to(\\sm{g:Z\\to Y}\\mathcal{L}(g))\n\\end{equation*}\nis a monomorphism.\n\\end{lem}\n\n\\begin{proof}\nWe prove the first statement. Suppose $g,g':Y\\to Z$ are two $\\mathcal{R}$-maps\nsuch that $H:g\\circ l=f$ and $H':g'\\circ l=f$. Then we obtain two  ...\n\\end{proof}\n\\end{comment}\n\n\\begin{comment}\n\\begin{thm}\nFrom every orthogonal factorization system we obtain a reflective subcategory with the same modal types.\n\\end{thm}\n\n\\begin{proof}\nWe define $P(A)$ to be the proposition that the unique map $A\\to\\unit$ is in\n$\\mathcal{R}$.\nFor any type $A$, there is a unique factorization\n\\begin{equation*}\n\\begin{tikzcd}\nA \\arrow[r,\"{\\modalunit[A]}\"] & \\modal A \\arrow[r] & \\unit\n\\end{tikzcd}\n\\end{equation*}\nof the unique map $A\\to\\unit$, where $\\modalunit[A]$ is in $\\mathcal{L}$. This\ndefines the operation $\\modal$ and the modal units.\n\nNow let $A:\\UU$ and $B:\\UU_P$, and consider $f:A\\to B$. We have to show that\nthe type of extensions of $f$ along $\\modalunit$ is contractible.\nIt is immediate that the type of such extensions is equivalent to the type\n$\\mathsf{fill}_{\\mathcal{L},\\mathcal{R}}(f,g)$ of diagonal fillers\nof the square\n\\begin{equation*}\n\\begin{tikzcd}\nA \\arrow[r,\"f\"] \\arrow[d,swap,\"{\\modalunit[A]}\"] & B \\arrow[d] \\\\\n\\modal A \\arrow[r,swap,\"g\"] & \\unit\n\\end{tikzcd}\n\\end{equation*}\nBy \\autoref{lem:diagonal_fillers}, the assumption that $P(B)$ holds and the fact that $\\modalunit[A]$ is\nin $\\mathcal{L}$, we know that this type of diagonal fillers is contractible.\n\\end{proof}\n\\end{comment}\n\n\\begin{lem}\\label{lem:ofs_rightstable}\nLet $(\\mathcal{L},\\mathcal{R})$ be an orthogonal factorization system. Then\nthe class $\\mathcal{R}$ is stable under pullbacks.\n\\end{lem}\n\n\\begin{proof}\nConsider a pullback diagram\n\\begin{equation*}\n\\begin{tikzcd}\nA \\arrow[d,swap,\"k\"] \\arrow[r,\"g\"] & X \\arrow[d,\"h\"] \\\\\nB \\arrow[r,swap,\"f\"] & Y\n\\end{tikzcd}\n\\end{equation*}\nwhere $h:X\\to Y$ is assumed to be in $\\mathcal{R}$, and let $k=k_{\\mathcal{R}}\\circ k_\\mathcal{L}$ be a factorization of $h$.\nThen the outer rectangle in the diagram\n\\begin{equation*}\n\\begin{tikzcd}\nA \\arrow[r,equals] \\arrow[d,swap,\"k_{\\mathcal{L}}\"] & A \\arrow[d,swap,\"k\"] \\arrow[r,\"g\"] & X \\arrow[d,\"h\"] \\\\\n\\im_{\\mathcal{L},\\mathcal{R}}(k) \\arrow[r,swap,\"k_{\\mathcal{R}}\"] & B \\arrow[r,swap,\"f\"] & Y\n\\end{tikzcd}\n\\end{equation*}\ncommutes, so by the universal property of pullbacks we obtain a unique map $j:\\im_{\\mathcal{L},\\mathcal{R}}(k)\\to A$ such that $j\\circ k_{\\mathcal{L}}=\\idfunc$ and $k\\circ j=k_{\\mathcal{R}}$.\nIt suffices to show that $k_{\\mathcal{L}}$ is an equivalence, and since we already have that $j\\circ k_{\\mathcal{L}}=\\idfunc$ we only need to show that $k_{\\mathcal{L}}\\circ j=\\idfunc$.\n\nWe do this using the contractibility of the type of diagonal fillers. Consider the square\n\\begin{equation*}\n\\begin{tikzcd}\nA \\arrow[r,\"k_{\\mathcal{L}}\"] \\arrow[d,swap,\"k_{\\mathcal{L}}\"] & \\im_{\\mathcal{L},\\mathcal{R}}(k) \\arrow[d,\"k_{\\mathcal{R}}\"] \\\\\n\\im_{\\mathcal{L},\\mathcal{R}}(k) \\arrow[r,swap,\"k_{\\mathcal{R}}\"] & B,\n\\end{tikzcd}\n\\end{equation*}\nfor which $\\idfunc:\\im_{\\mathcal{L},\\mathcal{R}}(k)\\to \\im_{\\mathcal{L},\\mathcal{R}}(k)$ (with the trivial homotopies) is a diagonal filler. However, we also have the homotopies $k_{\\mathcal{L}}\\circ j\\circ k_{\\mathcal{L}} \\htpy k_{\\mathcal{L}}$ and $k_{\\mathcal{R}}\\circ k_{\\mathcal{L}}\\circ j\\htpy k\\circ j\\htpy k_{\\mathcal{R}}$. This shows that we have a second diagonal filler, of which the underlying map is $k_{\\mathcal{L}}\\circ j$. Since the type of diagonal fillers is contractible, it follows that $k_{\\mathcal{L}}\\circ j=\\idfunc$, as desired.\n\\end{proof}\n\n\\subsubsection{Stable orthogonal factorization systems}\n\n\\begin{lem}\\label{lem:fill_compute}\nGiven $l,r,f,g$ and a homotopy $S : r \\circ f = g  \\circ l$, consider as $b:B$ varies all the diagrams of the form\n\\begin{equation*}\n\\begin{tikzcd}\n\\fib{l}{b} \\arrow[r,\"i_b\"] \\arrow[d,\"!\"'] & A \\arrow[d,swap,\"l\"] \\arrow[r,\"f\"] \\ar[dr,phantom,\"S\"] & X \\arrow[d,\"r\"] \\\\\n\\unit \\arrow[r,swap,\"b\"] & B \\arrow[r,swap,\"g\"] & Y\n\\end{tikzcd}\n\\end{equation*}\nand write $S_b : r \\circ (f \\circ i_b) = (g\\circ b) \\circ \\mathord !$ for the induced commutative square.\n(Note that the square on the left commutes judgmentally.)\nThen the map\n\\begin{equation*}\n\\fillers{S} \\to \\prd{b:B}\\fillers{S_b},\n\\end{equation*}\ndefined by precomposition with $b$, is an equivalence.\n\\end{lem}\n\n\\begin{proof}\nIt suffices to show that the map on total spaces\n\\begin{equation}\n  \\Big(\\sm{S:r\\circ f = g\\circ l} \\fillers{S}\\Big) \\to \\Big( \\sm{S:r\\circ f = g\\circ l} \\prd{b:B}\\fillers{S_b}\\Big)\\label{eq:fill-total}\n\\end{equation}\nis an equivalence.\nThe domain of~\\eqref{eq:fill-total} can be computed as\n\\begin{align*}\n  &\\hspace{-1cm}\\sm{S:r\\circ f = g\\circ l}{j:B\\to X}{H_f :j\\circ l=f}{H_g:r\\circ j=g} \\ct{(r\\circ H_f)}{(H_g\\circ l)^{-1}} = S\\\\\n  &\\eqvsym \\sm{j:B\\to X}(j\\circ l=f)\\times (r\\circ j=g)\n\\end{align*}\nby contracting a based path space.\nOn the other hand, note that\n\\begin{align*}\n  (r\\circ f = g\\circ l)\n  &\\eqvsym\n  \\prd{a:A} r(f(a)) = g(l(a))\\\\\n  &\\eqvsym\n  \\prd{a:A}{b:B}{l(a)=b} r(f(a)) = g(l(a))\\\\\n  &\\eqvsym\n  \\prd{b:B}{u:\\fib l b} r(f(i_b(a))) = g(l(i_b(a)))\\\\\n  &\\eqvsym\n  \\prd{b:B}{u:\\fib l b} r(f(i_b(a))) = g(b)\\\\\n  &\\eqvsym\n  \\prd{b:B} (r \\circ (f \\circ i_b) = (g\\circ b) \\circ \\mathord !)\n\\end{align*}\nThat is, to give $S$ is the same as to give each $S_b$.\nThus the codomain of~\\eqref{eq:fill-total} can be computed as\n\\begin{align*}\n  &\\hspace{-1cm}\\sm{S:r\\circ f = g\\circ l} \\prd{b:B}\\fillers{S_b}\\\\\n  &\\eqvsym \\sm{S:\\prd{b:B} (r \\circ (f \\circ i_b) = (g\\circ b) \\circ \\mathord !)} \\prd{b:B}\\fillers{S_b}\\\\\n  &\\eqvsym \\prd{b:B}\\sm{S_b:r \\circ (f \\circ i_b) = (g\\circ b) \\circ \\mathord !} \\fillers{S_b}\\\\\n  &\\eqvsym \\prd{b:B}\\sm{j_b:\\unit\\to X}(j_b=f\\circ i_b)\\times (r\\circ j_b=g(b))\n\\end{align*}\nusing the same argument as above for $S$.\nNow we can compute\n\\begin{align*}\n&\\hspace{-1cm}\\prd{b:B}\\sm{j_b:\\unit\\to X}(j_b=f\\circ i_b)\\times(r\\circ j_b=g\\circ b) \\\\\n& \\eqvsym\n\\prd{b:B}\\sm{j_b:X}(\\lam{x}j_b=f\\circ i_b)\\times(r(j_b)=g(b)) \\\\\n& \\eqvsym\n\\sm{j:B\\to X}\\prd{b:B}(\\lam{\\nameless}j(b)=f\\circ i_b)\\times(r(j(b))=g(b)) \\\\\n& \\eqvsym\n\\sm{j:B\\to X}(\\prd{b:B}\\lam{\\nameless}j(b)=f\\circ i_b)\\times(\\prd{b:B}r(j(b))=g(b)) \\\\\n& \\eqvsym\n\\sm{j:B\\to X}(\\prd{b:B}\\lam{\\nameless}j(b)=f\\circ i_b)\\times(r\\circ j=g) \\\\\n& \\eqvsym\n\\sm{j:B\\to X}(\\prd{b:B}\\prd{a:A}{p:l(a)=b}j(b)=f(a))\\times(r\\circ j=g) \\\\\n& \\eqvsym\n\\sm{j:B\\to X}(\\prd{a:A}j(l(a))=f(a))\\times(r\\circ j=g) \\\\\n& \\eqvsym\n\\sm{j:B\\to X}(j\\circ l=f)\\times(r\\circ j=g)\n\\end{align*}\nwhich is what we computed as the domain of~\\eqref{eq:fill-total} above.\n\\end{proof}\n\n\\begin{cor}\nIn any orthogonal factorization system\n$(\\mathcal{L},\\mathcal{R})$, if\n$l:A\\to B$ is a map such that $\\fib{l}{b} \\to \\unit$ is in $\\cL$ for each $b:B$, then also $l$ itself is in $\\cL$.\n\\end{cor}\n\\begin{proof}\n  By \\cref{lem:ofs_lifting}, $l$ is in $\\cL$ iff $\\fillers S$ is contractible for each $r\\in\\cR$ and $S$ as in \\cref{lem:fill_compute}, while similarly $\\fib{l}{b} \\to \\unit$ is in $\\cL$ iff $\\fillers {S_b}$ is contractible.\n  But the product of contractible types is contractible.\n\\end{proof}\n\n\\begin{cor}\\label{thm:detect-right-by-fibers}\n  In any stable orthogonal factorization system, if $l\\perp r$ for all maps $l\\in\\cL$ of the form $l:A\\to \\unit$, then $r\\in\\cR$.\n  In particular, for any modality $\\modal$, if $X\\to (A\\to X)$ is an equivalence for all $\\modal$-connected types $A$, then $X$ is modal.\n\\end{cor}\n\\begin{proof}\n  By \\cref{lem:fill_compute}, for any $l\\in\\cL$ and commutative square $S$ from $l$ to $r$, we have $\\fillers{S} \\eqvsym \\prd{b:B}\\fillers{S_b}$.\n  Since $(\\cL,\\cR)$ is stable, each map $\\mathord{!}_b:\\fib{l}{b}\\to \\unit$ is also in $\\cL$, so that $\\mathord{!}_b\\perp r$ by assumption.\n  Thus $\\fillers{S_b}$ is contractible for all $b$, hence so is $\\fillers{S}$.\n\n  For the second statement, the type $f:A\\to X$ is equivalent to the type of commutative squares\n  \\[\n  \\begin{tikzcd}\n    A \\ar[r,\"f\"] \\ar[d] & X \\ar[d] \\\\ \\unit\\ar[r] & \\unit\n  \\end{tikzcd}\n  \\]\n  and the type of fillers for such a square is equivalent to the type of $x:X$ such that $f(a) = x$ for all $a:A$, i.e.\\ the fiber of $X\\to (A\\to X)$ over $f$.\n  Thus, the assumption ensures that all such types of fillers are contractible, i.e.\\ $l\\perp r$ for all $\\modal$-connected maps of the form $l:A\\to \\unit$, so the first statement applies.\n\\end{proof}\n\n\\begin{lem}\\label{lem:sofs_rfib}\nLet $(\\mathcal{L},\\mathcal{R})$ be a stable orthogonal factorization system.\nThen a map $r:X\\to Y$ is in $\\mathcal{R}$ if and only if $\\fib{r}{y}$\nis $(\\mathcal{L},\\mathcal{R})$-modal for each $y:Y$.\n\\end{lem}\n\n\\begin{proof}\nThe class of right maps is stable under pullbacks by \\autoref{lem:ofs_rightstable},\nso it suffices to show that any map with modal fibers is in $\\mathcal{R}$.\n\nLet $r:X\\to Y$ be a map with modal fibers. Our goal is to show that\n$r$ is in $\\mathcal{R}$. By \\autoref{lem:ofs_lifting} it suffices to show that\n$r$ has the right lifting property with respect to the left maps.\nConsider a diagram of the form\n\\begin{equation*}\n\\begin{tikzcd}\nA \\arrow[d,swap,\"l\"] \\arrow[r,\"f\"] & X \\arrow[d,\"r\"] \\\\\nB \\arrow[r,swap,\"g\"] & Y\n\\end{tikzcd}\n\\end{equation*}\nin which $l$ is a map in $\\mathcal{L}$.\nWe wish to show that the type of diagonal fillers is contractible.\nBy \\autoref{lem:fill_compute}, the type of diagonal fillers of the above diagram\nis equivalent to the dependent product of the types of fillers of\n\\begin{equation*}\n\\begin{tikzcd}\n\\fib{l}{b} \\arrow[d] \\arrow[r,\"f\\circ i_b\"] & X \\arrow[d,\"r\"] \\\\\n\\unit \\arrow[r,swap,\"g(b)\"] & Y\n\\end{tikzcd}\n\\end{equation*}\nindexed by $b:B$. Thus, it suffices that the type of diagonal fillers for this\nsquare is contractible for each $b:B$. Since any filler factors uniquely through\nthe pullback $\\unit\\times_Y X$, which is $\\fib{r}{g(b)}$, the type of diagonal\nfillers of the above square is equivalent to the type of diagonal fillers of the\nsquare\n\\begin{equation*}\n\\begin{tikzcd}\n\\fib{l}{b} \\arrow[d] \\arrow[r,densely dotted] & \\fib{r}{g(b)} \\arrow[d] \\\\\n\\unit \\arrow[r,equals] & \\unit\n\\end{tikzcd}\n\\end{equation*}\nwhere the dotted map, is the unique map into the pullback $\\fib{r}{g(b)}$. In\nthis square, the left map is in $\\mathcal{L}$ because $\\mathcal{L}$ is assumed\nto be stable under pullbacks, and the right map is in $\\mathcal{R}$ by assumption,\nso the type of diagonal fillers is contractible.\n\\end{proof}\n\n\\begin{thm}\\label{thm:subuniv-sofs}\nAny two stable orthogonal factorization systems with the same modal types are\nequal.\n\\end{thm}\n\n\\begin{proof}\nBy \\autoref{lem:sofs_req} it follows that any orthogonal factorization system\nis completely determined by the class of right maps.\nBy \\autoref{lem:sofs_rfib} it follows that in a stable orthogonal factorization\nsystem, the class of right maps is completely determined by the modal types.\n\\end{proof}\n\n\\begin{thm}\\label{thm:highermod_from_sofs}\nAny stable orthogonal factorization system determines a higher modality with\nthe same modal types.\n\\end{thm}\n\n\\begin{proof}\nFor every type $X$ we have the $(\\cL,\\cR)$-factorization $X\\to\\modal X\\to\\unit$ of the\nunique map $X\\to\\unit$. This determines the modal unit\n$\\modalunit:X\\to\\modal X$ which is in $\\mathcal{L}$, and the\nunique map $\\modal X\\to\\unit$ is in $\\mathcal{R}$, i.e.\\ $\\modal X$ is $(\\cL,\\cR)$-modal.\n\nTo show the induction principle, let $P:\\modal X\\to\\UU$ and $f:\\prd{x:X} \\modal(P(\\eta(x)))$.\nThen we have a (judgmentally) commutative square\n\\begin{equation*}\n\\begin{tikzcd}\nX \\arrow[r,\"f\"] \\arrow[d,swap,\"\\modalunit\"] & \\sm{x:\\modal X}\\modal(P(x)) \\arrow[d,\"\\proj1\"] \\\\\n\\modal X \\arrow[r,equals] & \\modal X.\n\\end{tikzcd}\n\\end{equation*}\nNote that by \\autoref{lem:sofs_rfib},\nthe projection $\\proj1:(\\sm{x:\\modal X}\\modal(P(x)))\\to\\modal X$ is in $\\mathcal{R}$\nbecause its fibers are modal. Also, the modal unit\n$\\modalunit:X\\to\\modal X$ is in $\\mathcal{L}$.\nThus, by \\cref{defn:orthogonal}, the type of fillers of this square is contractible.\nSuch a filler consists of a function $s$ and homotopies filling the two triangles\n\\begin{equation*}\n\\begin{tikzcd}\nX \\arrow[r,\"f\"] \\arrow[d,swap,\"\\modalunit\"] & \\sm{x:\\modal X}\\modal(P(x)) \\arrow[d,\"\\proj1\"] \\\\\n\\modal X \\arrow[r,equals] \\arrow[ur,densely dotted] & \\modal X\n\\end{tikzcd}\n\\end{equation*}\nwhose composite is reflexivity, i.e.\\ the type\n\\begin{multline*}\n\\sm{s:\\modal X \\to \\sm{x:\\modal X}\\modal(P(x))}{H:\\prd{x:\\modal X} \\proj1(s(x))=x}{K:\\prd{x:X} s(\\modalunit(x))=f(x)}\\\\\n\\prd{x:X} \\proj1(K(x)) = H(\\modalunit(x)).\n\\end{multline*}\nIf we decompose $s$, $f$, and $K$ by their components, we get\n\\begin{multline*}\n\\sm{s_1:\\modal X \\to \\modal X}{s_2:\\prd{x:\\modal X} \\modal(P(s_1(x)))}{H:\\prd{x:\\modal X} s_1(x)=x}\\\\\n\\sm{K_1:\\prd{x:X} s_1(\\modalunit(x))=f_1(x)}{K_2 :\\prd{x:X} s_2(\\modalunit(x)) =_{K_1(x)} f_2(x)}\\\\\n\\prd{x:X} K_1(x) = H(\\modalunit(x)).\n\\end{multline*}\nNow we can contract $s_1$ and $H$, and also $K_1$ with the final unnamed homotopy, to get\n\\begin{equation*}\n\\sm{s_2:\\prd{x:\\modal X} \\modal(P(x))}  \\prd{x:X} s_2(\\modalunit(x)) =_{K_1(x)} f_2(x).\n\\end{equation*}\nBut this is just the type of extensions of $f$ along $\\modalunit$, i.e.\\ the fiber of precomposition by $\\modalunit$.\nThus, precomposition by $\\modalunit$ is an equivalence, so in fact that we have a uniquely eliminating modality.\nBy \\cref{lem:rs_idstable}, the identity types of $\\modal X$ are modal, so we have a higher modality as well.\n\\end{proof}\n\n\\section{Accessible reflective subuniverses}\\label{sec:accessible}\n\n\\begin{defn}\nGiven a family $f:\\prd{i:I}A_i\\to B_i$ of maps, a type $X$ is said to be \\define{$f$-local} if the precomposition map\n\\begin{equation*}\n\\precomp{f_i}:(B_i\\to X)\\to (A_i\\to X)\n\\end{equation*}\nis an equivalence, for each $i:I$. The family $f$ is said to be a \\define{presentation} of a reflective subuniverse $L$ if the subuniverses of $f$-local types and $L$-local types coincide. A reflective subuniverse is said to be \\define{accessible} if there exists a presentation for it. \n\\end{defn}\n\nIn \\cite{RijkeShulmanSpitters} it is shown that the subuniverse of $f$-local types is always a reflective subuniverse, provided that sufficiently many higher inductive types are available. However, it is not clear whether their construction is possible in our current setting, where the only higher inductive types that are assumed to exist are homotopy pushouts. In this section we will establish general properties of accessible reflective subuniverses. We will show in \\cref{chap:compact} that for any family $f$ of maps between \\emph{compact} types, the subuniverse of $f$-local types is indeed reflective. \n\n\\begin{rmk}\nNote that being accessible is structure; different families can present the same reflective subuniverse or modality.\nAs a trivial example, note that localizing at the empty\ntype, and localizing at the type family on $\\bool$ defined by\n$\\bfalse\\mapsto \\emptyt$ and $\\btrue\\mapsto \\unit$ both map all types to contractible types.\n\nHowever, we are usually only interested in properties of presentations insofar as they determine properties of subuniverses.\nFor instance, by \\cref{thm:acc-modal}, a reflective subuniverse is a modality exactly when it has a presentation in which each $C(a)=\\unit$.\n\\end{rmk}\n\n\\begin{eg}\\label{thm:trunc-acc}\nThe trivial modality $\\truncf{(-2)}$ is presented by $\\emptyt$, while the propositional truncation modality $\\truncf{(-1)}$ is presented by $\\bool$.  More generally, the\n$n$-truncation modality $\\truncf{n}$ is presented by the $(n+1)$-sphere $\\Sn^{n+1}$.\n\\end{eg}\n\n\\begin{eg}\\label{thm:open-acc}\nFor every mere proposition $P$, the open modality $\\open P (X) \\defeq (P\\to X)$ from \\cref{eg:open} is \npresented by the singleton type family $P$.\nTo see this, note that $\\modalunit[X] : X \\to (P\\to X)$ is the same as the map in the definition of locality, so that $X$ is modal for the open modality on $P$ if and only if it is $P$-local.\n(If $P$ is not a mere proposition, however, then $X\\mapsto (P\\to X)$ is not a modality, and in particular does not coincide with localization at $P$.)\n\\end{eg}\n\n\\begin{eg}\\label{thm:closed-acc}\n  The closed modality $\\closed P$ from \\cref{eg:closed} associated to a mere proposition $P$ is presented by the type family $\\lam{x} \\emptyt : P \\to \\UU$.\n  For by definition, $A$ is null for this family if and only if for any $p:P$ the map $A \\to (\\emptyt \\to A)$ is an equivalence.\n  But $\\emptyt \\to P$ is contractible, so this says that $P\\to\\iscontr(A)$, which was the definition of $\\closed P$-modal types from \\cref{eg:closed}.\n\\end{eg}\n\n\n\n\\begin{lem}\\label{lemma:characterizationsigmaflocal}\n    Let $f:\\prd{i:I}A_i\\to B_i$ be a family of maps. Denote the family consisting of the suspensions\n    of the functions by $\\susp{f} : \\prd{i:I} \\susp{A_i} \\to \\susp{B_i}$.\n    A type $X$ is $\\suspsym f$-local if and only if for every $x,y : X$, the type\n    $x =_X y$ is $f$-local.\n    In other words, $L_{\\susp{f}} = (L_{f})'$.\n\\end{lem}\n\n\\begin{proof}\n    By the induction principle for suspension and naturality, we obtain for each $i : I$ a commutative square\n\\[\n  \\begin{tikzcd}\n    (\\susp{B_i} \\to X) \\arrow[r,\"\\simeq\"] \\arrow[d] & \\left( \\sm{x,y:X} (B_i \\to x = y) \\right) \\arrow[d] \\\\\n    (\\susp{A_i} \\to X) \\arrow[r,\"\\simeq\"] & \\left( \\sm{x,y:X} (A_i \\to x = y) \\right)\n  \\end{tikzcd}\n\\]\nin which the horizontal maps are equivalences.\nSo $X$ is $\\suspsym f$-local if and only if the right vertical map is an equivalence\nfor every $i : I$, if and only if for each $x,y : X$, the type $x = y$ is $f_i$-local\nfor every $i : I$.\n\\end{proof}\n\nA general localization is only a reflective subuniverse, but there is a convenient sufficient condition for it to be a modality: if each $C(a)=\\unit$.\nA localization modality of this sort is called \\emph{nullification}.\n\n\\begin{thm}\\label{thm:nullification_modality}\n  If $F:\\prd{a:A} B(a) \\to C(a)$ is such that each $C(a)=\\unit$, then localization at $F$ is a modality, called \\define{nullification at $B$}.\n\\end{thm}\n\\begin{proof}\n  It suffices to show that for any $B:A\\to\\UU$, the $B$-null types are $\\Sigma$-closed.\n  Thus, let $X:\\UU$ and $Y:X\\to \\UU$ be such that $X$ and each $Y(x)$ are $B$-null.\n  Then\n  \\begin{align*}\n    (B\\to \\sm{x:X} Y(x))\n    &\\eqvsym \\sm{g:B\\to X} \\prd{b:B} Y(g(b)) \\\\\n    &\\eqvsym \\sm{x:X} B \\to Y(x) \\\\\n    &\\eqvsym \\sm{x:X} Y(x)\n  \\end{align*}\n  with the inverse equivalence being given by constant maps.\n  Thus, $\\sm{x:X} Y(x)$ is $B$-null.\n\\end{proof}\n\nOf course, it might happen that $\\localization{F}$ is a modality even if $F$ doesn't satisfy the condition of \\cref{thm:nullification_modality}.\nFor instance, if $B:A\\to \\UU$ has a section $s:\\prd{a:A} B(a)$, then localizing at the family $s' : \\prd{a:A} \\unit \\to B(a)$ is equivalent to nullifying at $B$, since in a section-retraction pair the section is an equivalence if and only if the retraction is.\nHowever, we can say the following.\n\n\\begin{lem}\\label{thm:acc-modal}\n  If $F:\\prd{a:A} B(a)\\to C(a)$ is such that $\\localization{F}$ is a modality, then there exists a family $E:D\\to \\UU$ such that $\\localization{F}$ coincides with nullification at $E$.\n\\end{lem}\n\\begin{proof}\n  Write $\\modal\\defeq\\localization{F}$ and $\\modalunit$ for its modal unit.\n  Define $D = \\sm{a:A} (\\modal (B(a)) + \\modal(C(a)))$, and $E:D\\to \\UU$ by\n  \\begin{align*}\n    E(a,\\inl(b)) &\\defeq \\fib{\\modalunit[B(a)]}{b}\\\\\n    E(a,\\inr(c)) &\\defeq \\fib{\\modalunit[C(a)]}{c}.\n  \\end{align*}\n  Then since $\\modalunit$ is $\\modal$-connected, each $E(d)$ is $\\modal$-connected, and hence every $F$-local type is $E$-null.\n\n  On the other hand, suppose $X$ is an $E$-null type.\n  Each $\\modalunit[B(a)]$ and $\\modalunit[C(a)]$ is $\\localization{E}$-connected, since their fibers are $\\localization{E}$-connected (by definition); thus $X$ is also $\\modalunit[B(a)]$-local and $\\modalunit[C(a)]$-local.\n  But we have the following commutative square:\n  \\[\n  \\begin{tikzcd}[column sep=large]\n    B(a) \\ar[r,\"{\\modalunit[B(a)]}\"] \\ar[d,\"F(a)\"'] & \\modal(B(a)) \\ar[d,\"{\\modal(F(a))}\"]\\\\\n    C(a) \\ar[r,\"{\\modalunit[C(a)]}\"'] & \\modal(C(a))\n  \\end{tikzcd}\n  \\]\n  and ${\\modal(F(a))}$ is an equivalence; thus $X$ is also $F(a)$-local.\n  So the $F$-local types coincide with the $E$-null types.\n\\end{proof}\n\nThis shows that the following definition of accessible modality is consistent with our terminology of accessible reflective subuniverse.\n\n\\begin{defn}\\label{defn:accessible}\nA modality $\\modal$ on $\\UU$ is said to be \\define{accessible} if it is the nullification at a family of types in $\\UU$, indexed by a type in $\\UU$.\nA \\define{presentation} of a modality $\\modal$ consists of a family of types $B: A\\to\\UU$, where $A:\\UU$, such that the subuniverse of modal types coincides with the subuniverse of $B$-null types.\n\\end{defn}\n\n\\begin{egs}\n  Our characterizations of the truncation and open and closed modalities in \\cref{thm:trunc-acc,thm:open-acc,thm:closed-acc} made no reference to the ambient universe.\n\\end{egs}\n\n\\begin{eg}\n  By contrast, the double-negation modality $\\neg\\neg$ \\emph{is} defined in a polymorphic way on all universes, but in general there seems no reason for it to be accessible on any of them.\n  However, if propositional resizing holds, then it is the nullification at $\\bool$ together with all propositions $P$ such that $\\neg\\neg P$ holds, and hence accessible.\n\n  Whether or not any inaccessible modalities remain after imposing propositional resizing may depend on large-cardinal principles.\n  It is shown in~\\cite{css:large-cardinal} that this is the case for the analogous question about reflective sub-$(\\infty,1)$-categories of the $(\\infty,1)$-category of $\\infty$-groupoids.\n\\end{eg}\n\n\\begin{rmk}\\label{rmk:extend-oops}\n  It is tempting to think that \\emph{any} reflective subuniverse $\\modal$ on $\\UU$ could be extended to an accessible one on $\\UU'$ by localizing at the family of \\emph{all} functions in $\\UU$ that are inverted by $\\modal$ (or nullifying at the family of all $\\modal$-connected types in $\\UU$, in the case of modalities), which is a $\\UU'$-small family though not a $\\UU$-small one.\n  This does produce an accessible reflective subuniverse $\\modal'$ of $\\UU'$ such that the $\\modal'$-modal types in $\\UU$ coincide with the $\\modal$-modal ones, but there seems no reason why the modal \\emph{operators} $\\modal'$ and $\\modal$ should agree on types in $\\UU$.\n\\end{rmk}\n\n\\endinput\n\\section{Left exact modalities}\\label{sec:left-exact-modal}\n\nWe have seen that the modal operator of any reflective subuniverse preserves products, but even for a modality it does not generally preserve pullbacks.\nIf it does, we call the modality ``left exact'' or just ``lex''.\n\n\\begin{thm}\\label{thm:lex-modalities}\n  For a modality $\\modal$, the following are equivalent.\n  \\begin{enumerate}\n  \\item If $A$ is $\\modal$-connected, then so is $(x=y)$ for any $x,y:A$.\\label{item:mu0}\n  \\item Whenever $A$ and $\\sm{x:A}B(x)$ are $\\modal$-connected, then so is $B(x)$ for all $x:A$.\\label{item:mu1}\n  \\item Any map between $\\modal$-connected types is $\\modal$-connected.\\label{item:mu1a}\n  \\item Any $\\modal$-modal function between $\\modal$-connected types is an equivalence.\\label{item:mu1b}\n  \\item If $f:A\\to B$ and $\\total g:(\\sm{x:A} P(x)) \\to (\\sm{y:B} Q(y))$ are $\\modal$-connected, then so is $g_a:P(a)\\to Q(fa)$ for each $a:A$.\\label{item:mu3b}\n  \\item If $S:k\\circ g = f\\circ h$ is a commutative square in which $f$ and $g$ are $\\modal$-connected, then for any $a$ the induced map $\\fib{h}{a} \\to \\fib{k}{fa}$ is $\\modal$-connected.\\label{item:mu3c}\n  \\item If $S:k\\circ g = f\\circ h$ is a commutative square in which $f$ and $g$ are $\\modal$-connected and $h$ and $k$ are $\\modal$-modal, then the square is a pullback.\\label{item:mu3d}\n  \\item For any $f:A\\to B$ and $b:B$, the evident map $\\fib{f}{b} \\to \\fib{\\modal f}{\\modalunit b}$ is $\\modal$-connected.\\label{item:mu3a}\n  \\item For any $A$ and $x,y:A$, the induced map $\\modal(x=y) \\to (\\modalunit[A](x) = \\modalunit[A](y))$ is an equivalence.\\label{item:mu6}\n  \\item The functor $\\modal$ preserves pullbacks.\\label{item:mu3}\n  \\item $\\modal$-connected maps satisfy the 2-out-of-3 property.\\label{item:mu4}\n  \\item If $\\modal f: \\modal A\\to \\modal B$ is an equivalence, then $f$ is $\\modal$-connected.\\label{item:mu5}\n  \\item For any $\\modal$-connected type $A$ and any $P:A\\to \\modaltype$, there is a $Q:\\modaltype$ such that $P(a)\\eqvsym Q$ for all $a:A$.\\label{item:mu2}\n  \\end{enumerate}\n  When they hold, we say that $\\modal$ is \\define{lex}.\n\\end{thm}\n\n\\begin{proof}\n  The equivalence~\\ref{item:mu1}$\\Leftrightarrow$\\ref{item:mu1a} is easy, using the definition of $\\modal$-connected maps and the fact that any function is equivalent to a fibration.\n  And~\\ref{item:mu0}$\\Rightarrow$\\ref{item:mu1a} since $\\fib f b \\jdeq \\sm{a:A} (f(a)=b)$ and $\\modal$-connected types are closed under $\\Sigma$ (since $\\modal$-connected maps are closed under composition, being the left class of a factorization system).\n\n  Condition~\\ref{item:mu1b} is a special case of~\\ref{item:mu1a}, since a function that is both modal and connected is an equivalence.\n  But assuming~\\ref{item:mu1b}, if $f:A\\to B$ is any function between $\\modal$-connected types, then in its $(\\cL,\\cR)$-factorization $A\\xrightarrow{e} I\\xrightarrow{m} B$ the type $I$ is also connected by right cancellation.\n  Thus~\\ref{item:mu1b} implies that $m$ is an equivalence; thus $f$, like $e$, is $\\modal$-connected, giving~\\ref{item:mu1a}.\n\n  Assuming~\\ref{item:mu1a}, the $3\\times 3$ lemma allows us to identify the fiber of $g_a$ over $q:Q(fa)$ with a fiber of the induced map $\\fib{\\total{g}}{(a,q)} \\to \\fib{f}{fa}$:\n  \\begin{equation}\n  \\begin{tikzcd}[column sep=large]\n  \\bullet \\arrow[r] \\arrow[d] \n    & P(a) \\arrow[r] \\arrow[d] \n    & Q(f(a)) \\arrow[d] \\\\\n  \\fib{\\total{g}}{(a,q)} \\arrow[r] \\arrow[d] \n    & \\sm{x:A}P(x) \\arrow[r,\"{\\total{g}}\"] \\arrow[d,swap,\"{\\proj1}\"] \n    & \\sm{y:B}Q(y) \\arrow[d,\"{\\proj1}\"] \\\\\n  \\fib{f}{f(a)} \\arrow[r] \n    & A \\arrow[r,swap,\"f\"] \n    & B\n  \\end{tikzcd}%\n  \\end{equation}\n  Since $f$ and $\\total g$ are $\\modal$-connected by assumption, their fibers are $\\modal$-connected, and hence by~\\ref{item:mu1a} so is this fiber; thus~\\ref{item:mu3b} holds.\n\n  Now assuming~\\ref{item:mu3b}, we can deduce~\\ref{item:mu3c} by replacing the maps $h$ and $k$ by equivalent dependent projections.\n  If in addition $h$ and $k$ are $\\modal$-modal, then $\\fib{h}{a} \\to \\fib{k}{fa}$ is a function between $\\modal$-modal types, hence itself $\\modal$-modal as well as $\\modal$-connected and thus an equivalence; thus~\\ref{item:mu3c}$\\Rightarrow$\\ref{item:mu3d}.\n  On the other hand, the special case of~\\ref{item:mu3d} in which $f$ and $g$ have codomain $\\unit$ reduces to~\\ref{item:mu1b}.\n\n  Applying~\\ref{item:mu3c} instead to the commutative square\n  \\begin{equation}\n  \\begin{tikzcd}\n  A \\arrow[r,\"{\\modalunit[A]}\"] \\arrow[d,swap,\"f\"] \n    & \\modal(A) \\arrow[d,\"\\modal(f)\"] \\\\\n  B \\arrow[r,swap,\"{\\modalunit[B]}\"]\n    & \\modal(B)\n  \\end{tikzcd}\n  \\end{equation}\n  for any $f:A\\to B$ yields~\\ref{item:mu3a}.\n  % \\begin{equation}\n  % \\vcenter{\\xymatrix{\n  %     \\bullet\\ar[r]\\ar[d] &\n  %     \\fib{f}{b}\\ar[r]\\ar[d] &\n  %     \\fib{\\modal f}{\\modalunit b}\\ar[d]\\\\\n  %     \\fib{\\modalunit[A]}{u}\\ar[r]\\ar[d] &\n  %     A\\ar[r]^{\\modalunit[A]}\\ar[d]_f &\n  %     \\modal A\\ar[d]^{\\modal f}\\\\\n  %     \\fib{\\modalunit[B]}{(\\modal f)(u)}\\ar[r] &\n  %     B\\ar[r]_{\\modalunit[B]} &\n  %     \\modal B\n  %     }}\n  % \\end{equation}\n  And as a special case of~\\ref{item:mu3a}, if $A\\defeq \\unit$ and $B$ is $\\modal$-connected, we find that $\\apfunc{\\modalunit}$ is $\\modal$-connected.\n  Since $\\modal$-connected maps are inverted by $\\modal$, this implies~\\ref{item:mu6}.\n  Conversely, if~\\ref{item:mu6} holds, if $A$ is $\\modal$-connected then $(\\modalunit(x)=\\modalunit(y))$ is contractible, hence $(x=y)$ is $\\modal$-connected, giving~\\ref{item:mu0}.\n  Thus~\\ref{item:mu0} through~\\ref{item:mu6} are equivalent.\n\n  Assuming these equivalent conditions, for a cospan $A\\xrightarrow{f}C \\xleftarrow{g} B$ the map of pullbacks\n  \\begin{equation}\n    \\sm{a:A}{b:B} (fa=gb) \\longrightarrow \\sm{x:\\modal A}{y:\\modal B} ((\\modal f)(x) = (\\modal g)(y))\\label{eq:pbpres}\n  \\end{equation}\n  is equivalent to the map on total spaces induced by $\\modalunit[A]:A\\to\\modal A$ and the fiberwise transformation\n  \\[ h : \\prd{a:A} \\left(\\fib{g}{fa} \\to \\fib{\\modal g}{(\\modal f)(\\modalunit a)}\\right). \\]\n  But since $(\\modal f)(\\modalunit a) = \\modalunit(fa)$, by~\\ref{item:mu3a} each $h_a$ is $\\modal$-connected.\n  Since $\\modalunit[A]$ is also $\\modal$-connected, by \\cref{lem:nconnected_postcomp_variation} so is~\\eqref{eq:pbpres}.\n  Hence the induced map\n  \\[ \\modal\\left(\\sm{a:A}{b:B} (fa=gb)\\right) \\longrightarrow \\sm{x:\\modal A}{y:\\modal B} ((\\modal f)(x) = (\\modal g)(y))\\]\n  (which exists since the codomain is $\\modal$-modal) is an equivalence, yielding~\\ref{item:mu3}.\n\n  On the other hand, if~\\ref{item:mu3}, then $\\modal$ preserves any pullback\n  \\begin{equation}\n  \\begin{tikzcd}\n  (x=y) \\arrow[r] \\arrow[d] \n    & \\unit \\arrow[d,\"x\"] \\\\\n  \\unit \\arrow[r,\"y\"'] \n    & A\n  \\end{tikzcd}\n  \\end{equation}\n  yielding~\\ref{item:mu6}.\n\n  For~\\ref{item:mu4}, two-thirds of the 2-out-of-3 property holds for any modality, so it remains to show that for $f:A\\to B$ and $g:B\\to C$, if $g\\circ f$ and $g$ are $\\modal$-connected, so is $f$.\n  However, the unstable octahedral axiom~(\\cite[ex4.4]{hottbook}) implies that for any $b:B$, the fiber $\\fib f b$ is equivalent to the fiber of the induced map $\\fib{g\\circ f}{gb} \\to \\fib{g}{gb}$.\n  These two types are $\\modal$-connected since $g\\circ f$ and $g$ are; thus~\\ref{item:mu1a}$\\Rightarrow$\\ref{item:mu4}.\n  Conversely,~\\ref{item:mu1a} is clearly a special case of~\\ref{item:mu4}.\n\n  Since $\\modalunit[A] : A\\to \\modal A$ is $\\modal$-connected, easily~\\ref{item:mu4}$\\Rightarrow$\\ref{item:mu5}.\n  On the other hand, if $g\\circ f$ and $g$ are $\\modal$-connected, then they are both inverted by $\\modal$, and hence so is $f$; thus~\\ref{item:mu5}$\\Rightarrow$\\ref{item:mu4}.\n\n  Next we assume~\\ref{item:mu4} and show \\ref{item:mu2}.\n  Suppose $A$ is $\\modal$-connected and $P:A\\to\\modaltype$, and define\n  \\[ Q \\defeq \\modal\\left(\\sm{a:A} P(a)\\right),\\]\n  and $g:\\prd{a:A} P(a) \\to Q$ by $g(a,u) \\defeq \\modalunit(a,u)$.\n  We will show $g$ to be a family of equivalences.\n\n  Since $P(a)$ and $Q$ are both $\\modal$-modal, for $g_a$ to be an equivalence, it suffices for it to be $\\modal$-connected.\n  We will prove this by showing that the induced map $\\total g:(\\sm{a:A} P(a)) \\to (\\sm{a:A} Q)$ is $\\modal$-connected.\n  By the assumed 2-out-of-3 property, for this it suffices to show that the other two maps in the following commutative triangle are $\\modal$-connected:\n  \\begin{equation}\n  \\begin{tikzcd}\n  \\sm{a:A} P(a) \\arrow[r,\"{\\total g}\"] \\arrow[dr,swap,\"{\\modalunit}\"]\n    & \\sm{a:A} Q \\mathrlap{\\,\\jdeq A\\times Q} \\arrow[d,\"\\proj2\"] \\\\\n  & Q\n  \\end{tikzcd}\n  \\end{equation}\n  But the right-hand vertical map is $\\modal$-connected since its fiber is the $\\modal$-connected type $A$,\n  and the diagonal map is $\\modal$-connected since it is simply $\\modalunit$.\n  This completes the proof of~\\ref{item:mu4}$\\Rightarrow$\\ref{item:mu2}.\n\n  Finally, we prove~\\ref{item:mu2}$\\Rightarrow$\\ref{item:mu0}.\n  Suppose $A$ is $\\modal$-connected and $x:A$.\n  Then $\\lam{y} \\modal(x=y) : A \\to \\modaltype$ so there is a $Q_x:\\modaltype$ such that $\\modal(x=y)\\eqvsym Q_x$ for all $y:A$.\n  It follows that transport in the type family $\\lam{y} \\modal(x=y)$ is constant, i.e.\\ if $p,q:y=z$ and $u:\\modal(x=y)$ then $\\trans p u = \\trans q u$.\n  Now for any $p:x=y$, we have $\\trans p {\\modalunit(\\refl x)} = \\modalunit(p)$; hence for any $p,q:x=y$ we have $\\modalunit(p)=\\modalunit(q)$.\n  By $\\mathsf{ind}^\\modal$, it follows that for any $u,v:\\modal(x=y)$ we have $u=v$, i.e.\\ $\\modal(x=y)$ is a mere proposition.\n  But $\\modal(x=x)$ is inhabited by $\\modalunit(\\refl x)$, hence $Q_x$ is also inhabited, and thus so is $\\modal(x=y)$ for all $y$; thus it is contractible.\n\\end{proof}\n\nNote that~\\ref{item:mu3a} and~\\ref{item:mu3} both imply that a lex modality preserves fibers: given $f:A\\to B$ and $b:B$, the map $\\modal(\\fib{f}{b}) \\to \\fib{\\modal f}{\\modalunit b}$ is an equivalence.\nIn fact, this property (and hence also~\\ref{item:mu3}) characterizes lex modalities even among reflective subuniverses.\n\n\\begin{thm}\\label{thm:rsu-lex}\n  If $\\modal$ is a reflective subuniverse such that for any $f:A\\to B$ and $b:B$, the map $\\modal(\\fib{f}{b}) \\to \\fib{\\modal f}{\\modalunit b}$ is an equivalence, then $\\modal$ is $\\Sigma$-closed (and hence a lex modality).\n\\end{thm}\n\\begin{proof}\n  Suppose $A$ and each $B(a)$ are $\\modal$-modal.\n  We have a commutative square\n  \\[\n  \\begin{tikzcd}\n    \\sm{a:A}B(a) \\ar[r,\"\\modalunit\"] \\ar[d,\"\\proj1\"'] &\n    \\modal(\\sm{a:A}B(a)) \\ar[d,\"\\modal \\proj1\"] \\\\\n    A \\ar[r,\"\\modalunit\"',\"\\sim\"] & \\modal A\n  \\end{tikzcd}\n  \\]\n  in which the bottom map is an equivalence.\n  Thus, to show that the top map is an equivalence it suffices to show that the induced map on each fiber $B(a) \\to \\fib{\\modal \\proj1}{\\modalunit a}$ is an equivalence.\n  But this map factors through the equivalence $B(a) \\eqvsym \\modal B(a)$ by the map $\\modal B(a) \\to \\fib{\\modal \\proj1}{\\modalunit a}$, which is an equivalence by assumption.\n\\end{proof}\n\nA particularly useful corollary of \\cref{thm:lex-modalities} is the following.\n\n\\begin{cor}\\label{modaln-truncated}\n  A lex modality preserves $n$-truncated maps for all $n$.\n\\end{cor}\n\\begin{proof}\n  We first argue by induction on $n$ that a lex modality $\\modal$ preserves $n$-types for all $n$.\n  The base case is \\cref{lem:modal-pres-prop}.\n  For the inductive step, suppose $\\modal$ is lex and preserves $n$-types, and $A$ is an $(n+1)$-type.\n  Then for $u,v:\\modal A$ the proposition that $u=v$ is an $n$-type is $\\modal$-modal, since it is constructed inductively using $\\Sigma$, $\\Pi$, and identity types.\n  Thus, we can prove it by $\\modal$-induction on $u,v$.\n  But for $x,y:A$ the type $\\modalunit(x)=\\modalunit(y)$ is equivalent to $\\modal(x=y)$ by \\cref{thm:lex-modalities}\\ref{item:mu6}, hence is an $n$-type by the inductive hypothesis.\n\n  Now if $f:A\\to B$ is $n$-truncated, to show that $\\modal f$ is $n$-truncated we must show that $\\fib{\\modal f}{y}$ is an $n$-type for all $y:\\modal B$.\n  Again, by $\\modal$-induction we can reduce to the case $y\\defeq \\modalunit(b)$ for some $b:B$, in which case \\cref{thm:lex-modalities}\\ref{item:mu3a} implies that $\\fib{\\modal f}{\\modalunit(b)} \\eqvsym \\modal(\\fib f b)$, which is an $n$-type since $f$ is $n$-truncated and $\\modal$ preserves $n$-types.\n\\end{proof}\n\nNot every modality satisfying \\cref{modaln-truncated} is lex.\nFor instance, the $m$-truncation modality preserves $n$-types for all $n$, but is not lex for $m\\ge -1$.\n(To see that it is not lex, consider an Eilenberg--MacLane space $K(G,m+1)$~\\cite{FinsterLicata}; this is $m$-connected, but its loop space is $K(G,m)$ which is not $m$-connected.\nAlternatively, we can use \\cref{thm:acc-lex} below together with the fact that the universe of $m$-types in the $m^{\\mathrm{th}}$ universe is not an $m$-type~\\cite{ks:u-not-ntype}.)\n\nWe do know at least one example of a lex modality.\n\n\\begin{eg}\n  For any mere proposition $P$, the open modality $\\open P \\defeq \\lam{X} (P\\to X)$ is lex.\n  This is easy to see since mapping out of $P$ is a right adjoint, hence preserves all limits, including pullbacks.\n\\end{eg}\n\nHowever, constructing lex modalities in general, such as by localization, is somewhat tricky.\nUnlike the characterization of modalities as $\\Sigma$-closed reflective subuniverses, which refers only to the \\emph{modal types} and hence was easy to prove in \\cref{thm:nullification_modality}, all the characterizations of lex-ness refer explicitly or implicitly to the \\emph{modal operator} $\\modal$, and not just by way of its ``mapping out'' universal property but saying something about its identity types.\nIn general, saying anything about the identity types of a higher inductive type (such as localization) requires some amount of univalence, and the present case is no exception (although we do not need a full ``encode-decode'' type argument).\n\n\\begin{thm}\\label{thm:acc-lex}\n  Let $\\modal$ be an accessible modality; the following are equivalent.\n  \\begin{enumerate}\n  \\item $\\modal$ is lex.\\label{item:al1}\n  \\item $\\modal$ has a presentation $B:A\\to \\UU$ such that for any $a:A$ and any $P:B(a)\\to \\modaltype$, there is a $Q:\\modaltype$ such that $P(b)\\eqvsym Q$ for all $b:B(a)$.\\label{item:al2}\n  \\item The universe $\\modaltype \\defeq \\{A:\\type | A \\text{ is $\\modal$-modal}\\}$ of modal types is $\\modal'$-modal, where $\\modal'$ is the canonical accessible extension of $\\modal$ to a universe $\\UU'$ containing $\\UU$, as in \\cref{thm:acc-extend}.\\label{item:al3}\n  \\end{enumerate}\n\\end{thm}\n\\begin{proof}\n  Assuming~\\ref{item:al1}, condition~\\ref{item:al2} holds for \\emph{any} presentation: it is just a special case of \\cref{thm:lex-modalities}\\ref{item:mu2}, since each $B(a)$ is $\\modal$-connected.\n\n  Now assume~\\ref{item:al2} for some presentation $B:A\\to\\UU$.\n  By definition of $\\modal'$, it suffices to show that $\\modaltype$ is $B(a)$-null for all $a:A$, i.e.\\ that the ``constant functions'' map\n  \\[ \\modaltype \\to (B(a) \\to \\modaltype) \\]\n  is an equivalence for all $a:A$.\n  The assumption~\\ref{item:al2} says that this map has a section, and hence in particular is surjective.\n  Thus, it suffices to show it is an embedding, i.e.\\ that for any $X,Y:\\modaltype$ the map\n  \\[ (X=Y) \\to ((\\lam{b} X)= (\\lam{b} Y)) \\]\n  is an equivalence.\n  But by univalence and function extensionality, this map is equivalent to\n  \\[ (X\\eqvsym Y) \\to (B(a) \\to (X\\eqvsym Y)), \\]\n  which is an equivalence by \\cref{connectedtotruncated} since $X\\eqvsym Y$ is $\\modal$-modal and $B(a)$ is $\\modal$-connected.\n\n  Finally, if we assume~\\ref{item:al3}, then for any $\\modal$-connected type $A:\\UU$ the map\n  \\[ \\modaltype \\to (A\\to\\modaltype) \\]\n  is an equivalence.\n  In particular, it has a section, proving \\cref{thm:lex-modalities}\\ref{item:mu2}.\n\\end{proof}\n\n\\begin{cor}\\label{thm:prop-loc-lex}\n  Let $B:A\\to\\prop$ be a family of mere propositions.\n  If the subuniverse of $B$-null types is a reflective subuniverse, then nullification at $B$ is a lex modality. Modalities of this form are called \\define{topological}\n\\end{cor}\n\\begin{proof}\n  We prove condition~\\ref{item:al2} of \\cref{thm:acc-lex}.\n  Given $P:B(a) \\to \\modaltype$, define $Q \\defeq \\prd{b:B(a)} P(b)$.\n  This lies in $\\modaltype$ since modal types are always closed under dependent function types.\n  And if we have any $b:B(a)$, then $B(a)$ is an inhabited proposition and hence contractible,\n  and a product over a contractible type is equivalent to any of the fibers.\n\\end{proof}\n\n\\begin{eg}\n  For any mere proposition $Q$, the closed modality $\\closed Q \\defeq \\lam{X} Q\\ast X$ is topological, since it is presented by the family $\\lam{x:P} \\emptyt$.\n  Thus, by \\cref{thm:prop-loc-lex}, it is lex.\n\\end{eg}\n\n\\section{Accessible reflective subuniverses}\\label{sec:accessible}\n\n\\begin{defn}\nGiven a family $f:\\prd{i:I}A_i\\to B_i$ of maps, a type $X$ is said to be \\define{$f$-local} if the precomposition map\n\\begin{equation*}\n\\precomp{f_i}:(B_i\\to X)\\to (A_i\\to X)\n\\end{equation*}\nis an equivalence, for each $i:I$. The family $f$ is said to be a \\define{presentation} of a reflective subuniverse $L$ if the subuniverses of $f$-local types and $L$-local types coincide. A reflective subuniverse is said to be \\define{accessible} if there exists a presentation for it. \n\\end{defn}\n\nIn \\cite{RijkeShulmanSpitters} it is shown that the subuniverse of $f$-local types is always a reflective subuniverse. However, it is not clear whether their construction is possible in our current setting, where the only higher inductive types that are assumed to exist are homotopy pushouts. In this section we will establish general properties of accessible reflective subuniverses. We will show in \\cref{chap:compact} that for any family $f$ of maps between \\emph{compact} types, the subuniverse of $f$ is indeed reflective. \n\n\\begin{rmk}\nNote that being accessible is structure; different families can present the same reflective subuniverse or modality.\nAs a trivial example, note that localizing at the empty\ntype, and localizing at the type family on $\\bool$ defined by\n$\\bfalse\\mapsto \\emptyt$ and $\\btrue\\mapsto \\unit$ both map all types to contractible types.\n\nHowever, we are usually only interested in properties of presentations insofar as they determine properties of subuniverses.\nFor instance, by \\cref{thm:acc-modal}, a reflective subuniverse is a modality exactly when it has a presentation in which each $C(a)=\\unit$.\nSimilarly, in \\cref{sec:lex-top-cotop} we will define a modality to be ``topological'' if it has a presentation in which each $C(a)=\\unit$ and each $B(a)$ is a mere proposition.\n\\end{rmk}\n\n\\begin{eg}\\label{thm:trunc-acc}\nThe trivial modality $\\truncf{(-2)}$ is presented by $\\emptyt$, while the propositional truncation modality $\\truncf{(-1)}$ is presented by $\\bool$.  More generally, the\n$n$-truncation modality $\\truncf{n}$ is presented by the $(n+1)$-sphere $\\Sn^{n+1}$.\n\\end{eg}\n\n\\begin{eg}\\label{thm:open-acc}\nFor every mere proposition $P$, the open modality $\\open P (X) \\defeq (P\\to X)$ from \\cref{eg:open} is \npresented by the singleton type family $P$.\nTo see this, note that $\\modalunit[X] : X \\to (P\\to X)$ is the same as the map in the definition of locality, so that $X$ is modal for the open modality on $P$ if and only if it is $P$-local.\n(If $P$ is not a mere proposition, however, then $X\\mapsto (P\\to X)$ is not a modality, and in particular does not coincide with localization at $P$.)\n\\end{eg}\n\n\\begin{eg}\\label{thm:closed-acc}\n  The closed modality $\\closed P$ from \\cref{eg:closed} associated to a mere proposition $P$ is presented by the type family $\\lam{x} \\emptyt : P \\to \\UU$.\n  For by definition, $A$ is null for this family if and only if for any $p:P$ the map $A \\to (\\emptyt \\to A)$ is an equivalence.\n  But $\\emptyt \\to P$ is contractible, so this says that $P\\to\\iscontr(A)$, which was the definition of $\\closed P$-modal types from \\cref{eg:closed}.\n\\end{eg}\n\n\n\n\\begin{lem}\\label{lemma:characterizationsigmaflocal}\n    Let $f:\\prd{i:I}A_i\\to B_i$ be a family of maps. Denote the family consisting of the suspensions\n    of the functions by $\\susp{f} : \\prd{i:I} \\susp{A_i} \\to \\susp{B_i}$.\n    A type $X$ is $\\suspsym f$-local if and only if for every $x,y : X$, the type\n    $x =_X y$ is $f$-local.\n    In other words, $L_{\\susp{f}} = (L_{f})'$.\n\\end{lem}\n\n\\begin{proof}\n    By the induction principle for suspension and naturality, we obtain for each $i : I$ a commutative square\n\\[\n  \\begin{tikzcd}\n    (\\susp{B_i} \\to X) \\arrow[r,\"\\simeq\"] \\arrow[d] & \\left( \\sm{x,y:X} (B_i \\to x = y) \\right) \\arrow[d] \\\\\n    (\\susp{A_i} \\to X) \\arrow[r,\"\\simeq\"] & \\left( \\sm{x,y:X} (A_i \\to x = y) \\right)\n  \\end{tikzcd}\n\\]\nin which the horizontal maps are equivalences.\nSo $X$ is $\\suspsym f$-local if and only if the right vertical map is an equivalence\nfor every $i : I$, if and only if for each $x,y : X$, the type $x = y$ is $f_i$-local\nfor every $i : I$.\n\\end{proof}\n", "meta": {"hexsha": "278dffce1a9bf8d23240c9cd94cc246a08caaea3", "size": 83008, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "modalities.tex", "max_stars_repo_name": "EgbertRijke/dissertation", "max_stars_repo_head_hexsha": "f2c087ba8983205d3dd336bbc194be5b7218c2c5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-07-06T10:37:12.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-06T10:37:12.000Z", "max_issues_repo_path": "modalities.tex", "max_issues_repo_name": "EgbertRijke/dissertation", "max_issues_repo_head_hexsha": "f2c087ba8983205d3dd336bbc194be5b7218c2c5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modalities.tex", "max_forks_repo_name": "EgbertRijke/dissertation", "max_forks_repo_head_hexsha": "f2c087ba8983205d3dd336bbc194be5b7218c2c5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.1548172757, "max_line_length": 611, "alphanum_fraction": 0.6855604279, "num_tokens": 28685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.33282398619633297}}
{"text": "\\documentclass[authoryear,preprint]{sigplanconf}\n\\usepackage{amsmath}\n\\usepackage{listings} \n\\usepackage{stmaryrd}\n\\usepackage{latexsym}\n\\usepackage{amssymb}\n\\usepackage{xcolor}\n\\usepackage{courier}\n\\usepackage{thmtools}\n\\usepackage{bbold}\n\n%%\n\n\\newcommand{\\geqz}{\\geq\\zerog}\n\\newcommand{\\leqz}{\\leq\\zerog}\n\\newcommand{\\zerog}{\\mathbb{0}}\n\\newcommand{\\oneg}{\\mathbb{1}}\n\\newcommand{\\twog}{\\mathbb{2}}\n\\newcommand{\\threeg}{\\mathbb{3}}\n\\newcommand{\\fourg}{\\mathbb{4}}\n\\newcommand{\\fiveg}{\\mathbb{5}}\n\\newcommand{\\bck}{\\triangleleft}\n\\newcommand{\\fwd}{\\triangleright}\n\n%%\n\n\\begin{document}\n\\special{papersize=8.5in,11in}\n\\setlength{\\pdfpageheight}{\\paperheight}\n\\setlength{\\pdfpagewidth}{\\paperwidth}\n\n\\newcommand{\\alt}{~|~}\n\\lstnewenvironment{code}{\\lstset{basicstyle={\\sffamily\\footnotesize}}}{}\n\n\\lstset{frame=none,\n         language=Haskell,\n         basicstyle=\\sffamily, \n         numberstyle=\\tiny,\n         numbersep=5pt,\n         tabsize=2,    \n         extendedchars=true,\n         breaklines=true,   \n         breakautoindent=true,\n         keywordstyle=\\color{black},\n         captionpos=b,\n         stringstyle=\\color{black}\\ttfamily,\n         showspaces=false,  \n         showtabs=false,    \n         framexleftmargin=2em,\n         framexbottommargin=1ex,\n         showstringspaces=false\n         basicstyle=\\sffamily,\n         columns=[l]flexible,\n         flexiblecolumns=true,\n         aboveskip=\\smallskipamount,\n         belowskip=\\smallskipamount,\n         lineskip=-1pt,\n         xleftmargin=1em,\n         escapeinside={/+}{+/},\n         keywords=[1]{Monad,Just,Nothing,type,data,right,left,id,where,do,\n                     if,then,else,let,in},\n         literate=\n           {+}{{$\\;+\\;$}}1 \n           {/}{{$/$}}1 \n           {*}{{$\\;*\\;$}}1\n           {=}{{$=\\ $}}1 \n           {/=}{{$\\not=$}}1\n           {[]}{$[\\;]$}2\n           {<}{{$<$}}1 \n           {>}{{$>$}}1 \n           {++}{{$+\\!\\!\\!+\\;$}}1 \n           {::}{{$:\\mkern -2.5mu:\\;$}}1\n           {&&}{{$\\&\\!\\!\\!\\&$}}2\n           {:=:}{{$:\\mkern -2mu=\\mkern -2mu:\\;$}}3\n           {:+:}{{$:\\mkern -5mu+\\mkern -5mu:\\;$}}3\n           {:-:}{{$:\\mkern -5mu-\\mkern -5mu:\\;$}}3\n           {:*:}{{$:\\mkern -5mu*\\mkern -5mu:\\;$}}3\n           {$}{{\\texttt{\\$}\\hspace{0.5em}}}1\n           {`}{$^\\backprime$}1\n           {==}{{$=\\!=\\;$}}2\n           {===}{{$\\equiv\\;$}}2\n           {->}{{$\\rightarrow\\;$}}2 \n           {>=}{{$\\geq$}}2 \n           {<=}{{$\\leq$}}2 \n           {>=0}{{$\\geq_\\zerog\\;$}}2 \n           {<=0}{{$\\leq_\\zerog\\;$}}2 \n           {==0}{{$=_\\zerog\\;$}}2 \n           {>0}{{$>_\\zerog\\;$}}2 \n           {<0}{{$<_\\zerog\\;$}}2 \n           {<-}{{$\\leftarrow$}}2\n           {=>}{{$\\Rightarrow\\;$}}2\n           {<<}{{$\\ll$}}2 \n           {>>}{{$\\gg\\;$}}2\n           {>>>}{{$\\ggg\\;$}}3 \n           {<<<}{{$\\lll\\;$}}3\n           {>>=}{{$\\gg\\mkern -2.5mu=\\;$}}3\n           {=<<}{{$=\\mkern -2.5mu\\ll\\;$}}3\n           {<|}{$\\lhd\\;$}2\n           {<||}{$\\unlhd\\;$}2\n           {\\ ||\\ }{$\\|$}1\n           {\\\\}{$\\lambda$}1\n           {:>}{{$\\rhd$}}2\n           {||>}{{$\\unrhd$}}2\n           {_}{{$\\_$}}1\n           {_B}{{$_b$}}2\n           {forall}{{$\\forall$}}1\n}\n\n\\lstset{postbreak=\\raisebox{0ex}[0ex][0ex]\n        {\\ensuremath{\\hookrightarrow}}}\n\\lstset{breaklines=true, breakatwhitespace=true}\n\\lstset{numbers=none, numbersep=5pt, stepnumber=2, numberstyle=\\scriptsize}\n\\lstset{rangeprefix=/*!\\ , rangesuffix=\\ !*\\/, includerangemarker=false}\n\n%% double-blind reviewing...\n\\title{Negative Types}\n\\authorinfo{}{}{}\n\\maketitle\n\n\\begin{abstract}\n\\ldots\n\\end{abstract}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Introduction}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{\\textsc{LET}: Operational Semantics}\n\nWe introduce a toy functional language. Separate the first-order from the\nhigher-order component.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{$\\Pi^{o}$: Operational and Denotational Semantics}\n\nPresent $\\Pi^{o}$ with an interpreter specifying the operational\nsemantics. This is $\\Pi$ with recursive types and a trace operator. (It might\nbe enough to have just one recursive type $\\mathbb{N}$.) We know\n\\emph{first-order} \\textsc{LET} can be translated to this language: we cannot\ntranslate higher-order functions. That requires compact closure but we live a\nplain symmetric bimonoidal category.\n\nFor a concrete model or denotational semantics that instantiates the\ncategorical framework, the minimum requirement is that every type maps to\nsome kind of space; a value $v : t$ maps to an element of that space; and a\ncombinator $c : t_1 \\leftrightarrow t_2$ maps to a function between the\nspaces denoting $t_1$ and $t_2$. The simplest model one can think of is to\nmap a type of size $n$ to a set of $n$ elements (including the infinite set\nof $\\omega$ elements; a value $v : t$ maps to an element in the set denoting\n$t$; a combinator maps to a permutation on that set. One could also build\nother models, e.g. vector spaces (infinite dimensional however) but that\nmodel is fine. Perhaps show the details of the model and the correspondence\nbetween operational and denotational semantics.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{$\\Pi^{o-}$: Operational Semantics}\n\nExtend $\\Pi^{o}$ with negative types and $\\eta$ and $\\epsilon$. Present the\noperational semantics that uses two interpreters forwards and backwards. Do\nwe have such a semantics that we like? \n\nThe categorical model is now supposed to be a ring category. This is\ncomplicated so we will work directly with a concrete model that gives us more\noperational intuition. We need to map every type to some space. If type $t$\nmaps to space $S$, we need to have an operation that maps that space to\nanother space that acts like ``negative'' $S$ so that we can satisfy for\nexample that $S-S=0$. Using the cardinality of the set like we did for\n$\\Pi^{o}$ does not directly work (footnote on papers that describe sets with\nnegative cardinality). Another idea is to generalize spaces to have two\ncomponents (a producer and a consumer; a left player and a right player) and\nto describe the space using the relative ``strength'' of the two\ncomponents. (This is the idea of the Int or G construction but that doesn't\ndirectly work if we have two monoidal structures and needs a complicated\ncompletion to ring categories.) A natural and beautiful theory is that of\nConway games which model two player games: left and right. In that setting we\ncan talk about games in which the left player has an $n$-move advantage\n(summarized by the number $n$) and games in which the right player has an\n$n$-move advantage (summarized by the number $-n$ which denotes that the left\nplayer has an $n$-move disadvantage). It is therefore possible to map a type\nof size $n$ where $n$ is an integer to the class Conway games where the left\nplayer has an $n$-move (dis-)advantage; the negative of a space $S$ is the\nspace in which all the games are flipped with left and right players\nexchanging positions; following common terminology, we call the target of the\ntype an \\emph{arena}; a value $v : t$ maps to a \\emph{strategy} for the left\nplayer in the arena for type $t$. Combinators transform strategies. Note that\nthe space corresponds to type $0$ is an arena with no possible moves.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Operational Semantics}\n\nGiven that our language is reversible, a backward evaluator is relatively\nstraightforward to implement: using the backward evaluator to calculate\n$c(v)$ is equivalent to $c^{\\dagger}(v)$ in the forward evaluator.\n\n\\begin{figure*}\n\\[\\begin{array}{rclr}\n[\\mathit{iso}, v, C, s]_{\\bck} &\\longmapsto& \n  \\langle \\mathit{iso}, v', C, s'\\rangle_{\\bck} \n  \\quad\\textrm{where}~\\mathit{iso}^{\\dagger}~s~v \\longmapsto (v', s') \\\\\n\\langle c_1, v, \\mathit{Fst}~C~c_2, s \\rangle_{\\bck} &\\longmapsto& \n  \\langle c_1 \\fatsemi c_2, v, C, s \\rangle_{\\bck} \\\\\n\\langle c_2, v, \\mathit{Snd}~c_1~C, s \\rangle_{\\bck} &\\longmapsto& \n  [c_1, v, \\mathit{Fst}~C~c_2, s]_{\\bck} \\\\\n[ c_1 \\fatsemi c_2, v, C, s ]_{\\bck} &\\longmapsto& \n  [c_2, v, \\mathit{Snd}~c_1~C, s]_{\\bck} \\\\\n\\langle c_1, v, \\mathit{LeftP}~C~c_2, s \\rangle_{\\bck} &\\longmapsto& \n  \\langle c_1 \\oplus c_2, \\mathit{left}~v, C \\rangle_{\\bck} \\\\\n[c_1 \\oplus c_2, v', C, s ]_{\\bck} &\\longmapsto& \n  [ c_1, v, \\mathit{LeftP}~C~c_2, s[v' \\approx left v] ]_{\\bck} \\\\\n\\langle c_2, v, \\mathit{RightP}~c_1~C, s\\rangle_{\\bck} &\\longmapsto& \n  \\langle c_1 \\oplus c_2, \\mathit{right}~v, C \\rangle_{\\bck} \\\\\n[c_1 \\oplus c_2, v', C,s ]_{\\bck} &\\longmapsto& \n  [ c_2, v, \\mathit{RightP}~c_1~C, s[v' \\approx right v] ]_{\\bck} \\\\\n\\langle c_1, v_1, \\mathit{LeftT}~C~c_2~v_2, s \\rangle_{\\bck} &\\longmapsto& \n  \\langle c_1 \\otimes c_2, (v_1, v_2), C, s \\rangle_{\\bck} \\\\\n\\langle c_2, v_2, \\mathit{RightT}~c_1~v_1~C, s \\rangle_{\\bck} &\\longmapsto& \n  [ c_1, v_1, \\mathit{LeftT}~C~c_2~v_2, s ]_{\\bck} \\\\\n[ c_1 \\otimes c_2, v, C, s ]_{\\bck} &\\longmapsto& \n  [ c_2, v_2, \\mathit{RightT}~c_1~v_1~C, S' ]_{\\bck} \n  \\quad\\textrm{where}~ s' = s[v \\approx (v_1, v_2)] \\\\\n\\\\\n\\\\\n\\langle \\epsilon, v, C, s \\rangle_{\\fwd} &\\longmapsto& \n  \\langle \\epsilon, \\mathit{left}~(-v'), C, s[v \\approx right v'] \\rangle_{\\bck} \\\\\n\\langle \\epsilon, v, C, s \\rangle_{\\fwd} &\\longmapsto& \n  \\langle \\epsilon, \\mathit{right}~v', C, s[v \\approx left (-v')] \\rangle_{\\bck} \\\\\n\\\\\n\\\\\n\\langle \\eta, v, C, s \\rangle_{\\bck} &\\longmapsto& \n  \\langle \\eta, \\mathit{left}~(-v'), C, s[v \\approx right v'] \\rangle_{\\fwd} \\\\\n\\langle \\eta, v, C, s \\rangle_{\\bck} &\\longmapsto& \n  \\langle \\eta, \\mathit{right}~v', C, s[v \\approx left (-v')] \\rangle_{\\fwd}\n\\end{array}\\]\n\\end{figure*}\n\nWe add the following rules to the reductions above. \n\\begin{enumerate}\n\\item The rules for $\\epsilon$ essentially transfer control from the forward\n  evaluator (whose states are tagged by $\\triangleright$) to the backward\n  evaluator (whose states are tagged by $\\triangleleft$). In other words,\n  after an $\\epsilon$ the direction of the world is reversed. The pattern\n  matching done by the unification ensures that a value on the right wire is\n  tagged to be negative and transferred to the left wire, and vice versa.\n  Note that there is no evaluation rule for $\\eta$ in the forward\n  evaluator. This corresponds to the fact that there is no value of type 0\n  and hence the forward evaluator can never execute an $\\eta$.\n\n\\item The rules for $eta$ are added to the backward evaluator. A program\n  executing backwards starts executing forwards after the execution of the\n  $\\eta$. Dual to the previous case, there is no rule for $\\epsilon$ in the\n  backward evaluator since the output type of $\\epsilon$ is 0.\n\\end{enumerate}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Conway Numbers: Arenas}\n\nA Conway number is a game consisting of left and right options where each\noption models a move to another game. There is another technical condition\ngiven below that constrains every left option to be ``less than'' every right\noption but that can be ignored for the moment. Players alternate taking\noptions and the player with no available options loses. In Haskell, ignoring\nthe additional technical condition, one might define the datatype of Conway\nnumbers as:\n\\begin{code}\ndata ConwayNumber = CN [ConwayNumber] [ConwayNumber]\n\\end{code}\nThe simplest Conway number is \\lstinline|CN [] []| with empty left and right\noptions. We call this number $\\zerog$: \n\\begin{code}\n/+ $\\zerog$ +/  = CN  [] []\n\\end{code}\nOnce we have defined $\\zerog$, we can also define the following:\n\\begin{code}\n/+ $\\oneg$ +/  = CN  [ /+ $\\zerog$ +/ ]  []\n/+ $\\twog$ +/  = CN  [ /+ $\\oneg$ +/ ]  []\n/+ $\\threeg$ +/  = CN  [ /+ $\\twog$ +/ ]  []\n\\end{code}\nand so on. Intuitively, the number $\\mathbb{n}$ represents a game in which\nthe left player has an $n$-move advantage over the right player. Dually, we\ncan define the following numbers where the left player has $n$-move\n\\emph{disadvantage} over the right player:\n\\begin{code}\n/+ -$\\oneg$ +/  = CN  [] [ /+ $\\zerog$ +/ ]\n/+ -$\\twog$ +/  = CN  [] [ /+ -$\\oneg$ +/ ]\n/+ -$\\threeg$ +/  = CN  [] [ /+ -$\\twog$ +/ ]\n\\end{code}\nMore generally, the \\emph{unary negation} of a number or its \\emph{dual} is\ndefined as follows:\n\\begin{code}\nneg :: ConwayNumber -> ConwayNumber\nneg (CN xls xrs) = \n  CN [ neg xr | xr <- xrs ] [ neg xl | xl <- xls ]\n\\end{code}\n\n\\smallskip\\noindent\\textbf{Comparing numbers.} There are three outcomes to\ngames represented by Conway numbers $\\mathbb{n}$:\n\\begin{itemize}\n\\item $\\mathbb{n} > \\zerog$ which indicates that the \\emph{left} player can\n  enforce a win, no matter who starts;\n\\item $\\mathbb{n} < \\zerog$ which indicates that the \\emph{right} player can\n  enforce a win, no matter who starts;\n\\item $\\mathbb{n} = \\zerog$ which indicates that the \\emph{second}\n  player can enforce a win, no matter who.\n\\end{itemize}\nFor example, we have $\\threeg > \\zerog$ because the right player would have\nno options (i.e., would lose) on the first or second turn depending on who\nstarts. Similarly, we have $-\\threeg < \\zerog$ because the left player would\nhave no options on on the first or second turn depending on who starts. For\n$\\zerog$, it is evident that the first player to take a turn must lose, i.e.,\nthat the second player wins. More interestingly, consider the game\n$\\textsf{CN}~[-\\oneg]~[\\oneg]$ which we claim is $= \\zerog$. Indeed, if the\nleft player starts, the only option is to move to the game $-\\oneg$ which the\nright player wins. If however the right player moves first, the only option\nis to move to the game $\\oneg$ which the left player wins. In both cases, the\nsecond player wins. To ensure that these three outcomes are the only possible\noutcomes, Conway numbers have an additional restriction: for every left\noption $x$ and right option $y$, we require that $x < y$. If that restriction\nis lifted we could construct games such that $\\textsf{CN}~[\\zerog]~[\\zerog]$\nfor which none of the relations $> \\zerog$, $< \\zerog$, or $= \\zerog$\nholds. Instead for this game, the first player always wins, which means that\nthe left player cannot enforce a win (in case the right player starts) and\nvice-versa.\n\nThe formal definitions of the comparison operators are:\n\\begin{code}\n>=0 (CN _ xrs)  = not $ or (map <=0 xrs)\n<=0 (CN xls _)  = not $ or (map >=0 xls) \n==0 x           = >=0 x && <=0 x\n<0 x            = <=0 x && not (>=0 x)\n>0 x            = >=0 x && not (<=0 x)\n\\end{code}\nOnly $\\geq_\\zerog$ and $\\leq_\\zerog$ are fundamental. The predicate\n$\\geq_\\zerog$ means that the left player can win as second player and\n$\\leq_\\zerog$ means that the right player can win as second player. If the\nleft player can win as second player, it means that the right player has no\ngood opening move, i.e., that there is no right option that is $\\leq_\\zerog$.\n\nConway numbers also come equipped with addition, subtraction, and\nmultiplication operations defined as follows.\n\n\\smallskip\\noindent\\textbf{Addition and subtraction.} Addition of two games\nintuitively gives each player the choice of selecting an option from either\ngame. Subtraction is simply the addition of the dual of a game. Formally:\n\\begin{code}\n(:+:) :: ConwayNumber -> ConwayNumber -> ConwayNumber\nx@(CN xls xrs) :+: y@(CN yls yrs) = \n  CN \n    ([ xl :+: y | xl <- xls ] `union`\n     [ x :+: yl | yl <- yls ])\n    ([ xr :+: y | xr <- xrs ] `union`\n     [ x :+: yr | yr <- yrs ])\n\n(:-:) :: ConwayNumber -> ConwayNumber -> ConwayNumber\nx :-: y = x :+: (neg y) \n\\end{code}\nIt is easy to check that $\\zerog$ is the unit of addition and that addition\nis commutative. Furthermore, adding two positive numbers like~$\\twog$\nand~$\\threeg$ gives $\\fiveg$ as desired, and similarly for two negative\nnumbers. When mixing positive and negative numbers, e.g., adding $\\threeg$\nand $-\\twog$, the result appears much more complicated:\n\\begin{code}\nCN [CN  [CN  [-/+ $\\twog$ +/] \n             [CN [-/+ $\\oneg$ +/] [/+ $\\oneg$ +/]]]\n        [CN  [CN [-/+ $\\oneg$ +/] [/+ $\\oneg$ +/]] \n             [/+ $\\twog$ +/]]] \n   [CN  [CN  [CN [-/+ $\\oneg$ +/] [/+ $\\oneg$ +/]] \n             [/+ $\\twog$ +/]] \n        [/+ $\\threeg$ +/]]\n\\end{code}\nWe will formalize the sense in which the game above is equivalent to the game\n$\\oneg$, but for now we can intuitively reason as follows. We have already\nseen that the game $\\textsf{CN}~[-\\oneg]~[\\oneg]$ is equivalent to $\\zerog$\nwhich simplifies the above to:\n\\begin{code}\nCN [CN  [CN  [-/+ $\\twog$ +/] [/+ $\\zerog$ +/]]\n        [CN  [/+ $\\zerog$ +/] [/+ $\\twog$ +/]]]\n   [CN  [CN  [/+ $\\zerog$ +/] [/+ $\\twog$ +/]]\n        [/+ $\\threeg$ +/]]\n\\end{code}\nNow consider the game $\\textsf{CN}~[\\zerog]~[\\twog]$. If the left player\nstarts, the game proceeds to $\\zerog$ and the right player loses. If the\nright player starts, the game proceeds to $\\twog$ which is an even stronger\nposition for the left player. In other words, the right option is useless and\nthe right player always loses: the game is equivalent to\n$\\textsf{CN}~[\\zerog]~[\\;]$, i.e., to~$\\oneg$. By a similar reasoning,\n$\\textsf{CN}~[-\\twog]~[\\zerog]$ simplifies to $-\\oneg$, and the whole\nexpression becomes:\n\\begin{code}\nCN [CN  [/+ -$\\oneg$ +/] [/+ $\\oneg$ +/]]\n   [CN  [/+ $\\oneg$ +/] [/+ $\\threeg$ +/]]\n\\end{code}\nThe left option is equivalent to $\\zerog$ and the right one is equivalent to\n$\\twog$, and the entire expression is equivalent to $\\oneg$.\n\n\\smallskip\\noindent\\textbf{Multiplication.} The most complicated operation on\nConway numbers is multiplication. It is defined as follows:\n\\begin{code}\n(:*:) :: ConwayNumber -> ConwayNumber -> ConwayNumber\nx@(CN xls xrs) :*: y@(CN yls yrs) = \n  CN \n    ([ (xl :*: y) :+: (x :*: yl) :-: (xl :*: yl)\n     | xl <- xls, yl <- yls] `union`\n     [ (xr :*: y) :+: (x :*: yr) :-: (xr :*: yr)\n     | xr <- xrs, yr <- yrs])\n    ([ (xl :*: y) :+: (x :*: yr) :-: (xl :*: yr)\n     | xl <- xls, yr <- yrs] `union`\n     [ (xr :*: y) :+: (x :*: yl) :-: (xr :*: yl)\n     | xr <- xrs, yl <- yls])\n\\end{code}\n\nConway numbers form a \\emph{ring} under the semantic notion of equality\n\\lstinline$:=:$ defined below:\n\\begin{code}\n(:=:) :: ConwayNumber -> ConwayNumber -> ConwayNumber\nx :=: y = ==0 (x :-: y)\n\\end{code}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{$\\Pi^{o-}$: Denotational Semantics} \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{$\\Pi^{o-}$: Correspondence} \n\nShow correspondence between operational and denotational semantics for\n$\\Pi^{o-}$.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Back to $\\textsc{LET}$}\n\nNow work out the full translation from \\textsc{LET} to $\\Pi^{o-}$.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Conclusion}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\bibliographystyle{abbrvnat}\n\\softraggedright\n\\bibliography{cites}\n\n\\end{document}\n\n", "meta": {"hexsha": "7717474636b65410735ced02d330297e91b4c211", "size": 18978, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "negatives.tex", "max_stars_repo_name": "JacquesCarette/pi-dual", "max_stars_repo_head_hexsha": "003835484facfde0b770bc2b3d781b42b76184c1", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2015-08-18T21:40:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T01:07:57.000Z", "max_issues_repo_path": "negatives.tex", "max_issues_repo_name": "JacquesCarette/pi-dual", "max_issues_repo_head_hexsha": "003835484facfde0b770bc2b3d781b42b76184c1", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-06-07T16:27:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-29T20:41:23.000Z", "max_forks_repo_path": "negatives.tex", "max_forks_repo_name": "JacquesCarette/pi-dual", "max_forks_repo_head_hexsha": "003835484facfde0b770bc2b3d781b42b76184c1", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-05-29T01:56:33.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-10T09:47:13.000Z", "avg_line_length": 42.9366515837, "max_line_length": 83, "alphanum_fraction": 0.6138686901, "num_tokens": 5885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.33282398619633297}}
{"text": "%!TEX root = ../../template.tex\n\n\n\\section{Methods and Findings}%\n\\label{sec:intro_methods}\n\nThe \\acrlong{RQ} were used to guide the conduction of this thesis' work.\nThis has led to a natural two side division: on the one hand, there was\nthe need to algorithmically define projections for tomographic\nreconstruction of a trace gas concentration field; on the other hand,\nphysical tests had to be conducted to ensure that the idealised\nprojections were feasible. These were the two hypothesis that had to be\nverified.\n\nThe first hypothesis was addressed by the construction of a software\nsimulation system based on several projection and backprojection matrix\noperators. This system is based on one of the main novelties involved in\nthis project: a high degree of geometric measurement freedom. This is\nachieved by assuming that our tomographic acquisition system is mounted\non a custom-built \\gls{UAV}, which carries specific spectroscopic\nequipment and is programmed using ArduCopter's SITL software\nsuite~\\cite{arducopter} for full autonomous operation. Spectral\nacquisition takes place using a set circular trajectory that implies the\nacquisition of a higher-than-usual projection number in comparison with\ntraditional DOAS-tomography operations. After simulating the spectral\nprojection information, according to a number of parameters that are\ninput at runtime, the system calculates their backprojection and\nassembles a simulated concentration map for the selected trace gases.\n\nThe second hypothesis is addressed by means of the physical acquisition\nof spectral data between two relatively close points in Almada,\nPortugal. By comparing spectral information retrieved by two different\nsets of equipment in said geographical points, we should be able to\nestablish that current day equipment is able to measure trace gas\nconcentrations in this kind of distances and that it is possible to make\nthese measurements through the difference of two passive \\gls{DOAS}\nmeasurements.\n", "meta": {"hexsha": "5411ea9c8c8c07e00d4859cca4f4c018ca5afa4d", "size": 1981, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapters/introduction/methods.tex", "max_stars_repo_name": "ruivalmeida/novathesis", "max_stars_repo_head_hexsha": "ba50f95c3e6e10f5ec3ff4c98cc8bb786246a6ef", "max_stars_repo_licenses": ["LPPL-1.3c"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapters/introduction/methods.tex", "max_issues_repo_name": "ruivalmeida/novathesis", "max_issues_repo_head_hexsha": "ba50f95c3e6e10f5ec3ff4c98cc8bb786246a6ef", "max_issues_repo_licenses": ["LPPL-1.3c"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapters/introduction/methods.tex", "max_forks_repo_name": "ruivalmeida/novathesis", "max_forks_repo_head_hexsha": "ba50f95c3e6e10f5ec3ff4c98cc8bb786246a6ef", "max_forks_repo_licenses": ["LPPL-1.3c"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.1315789474, "max_line_length": 72, "alphanum_fraction": 0.8243311459, "num_tokens": 412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.332823979067319}}
{"text": "\\chapter{CFG}\n\\section{Settings}\n{\\inblue\\tt .../jsaf/analysis/cfg/\\{package, CFG, CFGId\\}.scala}\\\\\n\\[\n\\begin{array}{rllll}\nP   & \\in & \\SF{Program} & = & \\powerset{\\fid \\times \\SF{ArgumentsName} \\times \\args \\times \\vars} \\times \\graph \\\\\nfid & \\in & \\fid & ::= & fid_{global} ~\\mid~ fid_1 ~\\mid \\cdots \\\\\n& & \\SF{VarKind} & ::= & \\SF{GlobalVar} ~\\mid~ \\SF{PureLocalVar} ~\\mid~ \\SF{CapturedVar} ~\\mid~ \\SF{CapturedCatchVar} \\\\\n& & \\args,\\vars & ::= & x^* \\\\\n& & \\SF{ArgumentsName} & = & \\SF{String} \\\\\nG, \\langle \\controlpoint,\\cfgnext,\\excnext,\\mathbb{A}\\rangle & \\in & \\graph & = & \\powerset{\\SF{Node}} \\times \\powerset{\\Edge} \\times \\powerset{\\Edge} \\times \\powerset{\\SF{Call}}\\\\\nn & \\in & \\SF{Node} & = & \\fid \\times \\SF{Label}\\\\\n& & \\Edge,\\SF{Call} & = & \\SF{Node} \\times \\SF{Node}\\\\\n& & \\SF{Label} & ::= & \\SF{ENTRY} \\mid \\SF{EXIT} \\mid \\SF{EXIT-EXC} \\mid c_1 \\mid \\cdots \\\\\n&&\\inblue{\\tt Label}&\\inblue = &\\inblue\n{\\tt LEntry}\\mid {\\tt LExit}\\mid {\\tt LExitExc}\\mid {\\tt LBlock(id: BlockId)}\n\\\\\n\\end{array}\n\\]\n  A call expression splits into a pair of call and after-call nodes in this flow graph, and there is no edge between the pair. In order to treat them as a call-site and a return-site of the call, the pair $(cp_{\\textit{call}},cp_{\\textit{after-call}})$ must be recorded in $\\mathbb{A}$ as an element.\n\\section{Helper Functions}\\label{sec:abs-helper}\n{\\inblue\\tt .../jsaf/analysis/cfg/CFG.scala}\n\n\\[\n\\begin{array}{lcl}\n  \\chf{getCmd}_{P} & : & \\SF{Node} \\rightarrow \\Command \\\\\n  \\chf{getArgVars}_{P} & : & \\fid \\rightarrow \\args \\\\\n  \\chf{getLocalVars}_{P} & : & \\fid \\rightarrow \\vars \\\\\n  \\chf{getCallFromAftercall}_{P} & : & \\SF{Node} \\rightarrow \\SF{Node} \\\\\n  \\chf{getAftercallFromCall}_{P} & : & \\SF{Node} \\rightarrow \\SF{Node} \\\\\n  \\chf{getExcSucc}_{P} & : & \\SF{Node} \\rightarrow \\SF{Node} \\\\\n  \\chf{getArgumentsName}_{P} & : & \\fid \\rightarrow \\SF{String} \\\\\n  \\chf{getReturnVar}_{P} & : & \\SF{Node} \\rightarrow \\SF{String} \\\\\n  \\chf{getVarKind}_{P} & : & \\SF{String} \\rightarrow \\SF{VarKind} \\\\\n  \\chf{isUserFunction}_{P} & : & \\SF{FunctionId} \\rightarrow \\SF{Boolean} \\\\\n\\end{array}\n\\]\n\n\\section{Syntax of $\\Command$}\n{\\inblue\\tt .../jsaf/analysis/cfg/\\{CFG, CFGInst, CFGExpr\\}.scala}\\\\\n\n\\[\n\\begin{array}{r@{~~}r@{~~}lll}\nc \\in \\Command & ::= & \\Entry & \\mbox{\\tt\\inblue Entry}& \\comment{entry node} \\\\\n& \\mid & \\Exit & \\mbox{\\tt\\inblue Exit}& \\comment{exit node} \\\\\n& \\mid & \\Exite & \\mbox{\\tt\\inblue ExitExc}& \\comment{exit node for exception} \\\\\n& \\mid & i^+ & \\mbox{\\tt\\inblue Block}& \\comment{basic block} \\\\\n\ni \\in \\Instruction & ::= & \n         x~\\verb+:=+~\\TT{alloc}\\verb+(+ e^{?} \\verb+)+\n & \\mbox{\\tt\\inblue CFGAlloc}\n\\\\\n\n% & \\mid & x~\\verb+:=+~\\TT{allocObject}\\verb+()+\n%  & \\mbox{\\tt\\inblue CFGAllocObject}\n% \\\\\n\n& \\mid & x~\\verb+:=+~\\TT{allocArray}\\verb+(+n\\verb+)+\n & \\mbox{\\tt\\inblue CFGAllocArray}\n\\\\\n\n& \\mid & x~\\verb+:=+~\\TT{allocArg}\\verb+(+n\\verb+)+\n & \\mbox{\\tt\\inblue CFGAllocArg}\n\\\\\n\n& \\mid & x ~\\verb+:=+~ e\n & \\mbox{\\tt\\inblue CFGExprStmt}\n\\\\\n\n& \\mid & x ~\\verb+:=+~ \\TT{delete}\\verb+(+e\\verb+)+\n & \\mbox{\\tt\\inblue CFGDelete}\n\\\\\n\n& \\mid & x ~\\verb+:=+~ \\TT{delete}\\verb+(+e_1,e_2\\verb+)+\n & \\mbox{\\tt\\inblue CFGDeleteProp}\n\\\\\n\n& \\mid & e\\verb+[+e\\verb+]+ ~\\verb+:=+~ e \n & \\mbox{\\tt\\inblue CFGStore}\n\\\\\n\n%& \\mid & \\inred \\verb+with(+e^*,x,x\\verb+)+~\\verb+:=+~e\n% \\\\\n\n& \\mid & x_1 ~\\verb+:=+~ \\TT{function} ~x_2^{?}\\verb+(+fid\\verb+)+\n & \\mbox{\\tt\\inblue CFGFunExpr}\n\\\\\n\n& \\mid & \\TT{construct}\\verb+(+e_1,e_2,e_3\\verb+)+\n & \\mbox{\\tt\\inblue CFGConstruct}\n\\\\\n\n& \\mid & \\TT{call}\\verb+(+e_1,e_2,e_3\\verb+)+\n & \\mbox{\\tt\\inblue CFGCall}\n\\\\\n\n& \\mid & \\TT{assert}\\verb+(+e\\inop e\\verb+)+ \n & \\mbox{\\tt\\inblue CFGAssert}\n\\\\\n\n& \\mid & \\TT{catch}\\verb+(+x\\verb+)+\n & \\mbox{\\tt\\inblue CFGCatch}\n\\\\\n\n& \\mid & \\TT{return}\\verb+(+e^{?}\\verb+)+ \n & \\mbox{\\tt\\inblue CFGReturn}\n\\\\\n\n& \\mid & \\TT{throw}\\verb+(+e\\verb+)+\n & \\mbox{\\tt\\inblue CFGThrow}\n\\\\\n\n& \\mid & x ~\\verb+:=+~\\ensuremath{\\diamond}x\\verb+(+x^{*}\\verb+)+\n & \\mbox{\\tt\\inblue CFGInternalCall}\n\\\\\n\n& \\mid & \\TT{noop}\n & \\mbox{\\tt\\inblue CFGNoOp}\n\\\\\n\ne \\in \\Expression & ::= & x\n & \\mbox{\\tt\\inblue CFGVarRef}\n\\\\\n\n& \\mid & e \\inop e \n & \\mbox{\\tt\\inblue CFGBin}\n\\\\\n\n& \\mid & \\preop e\n & \\mbox{\\tt\\inblue CFGUn}\n\\\\\n\n& \\mid & e\\verb+[+e\\verb+]+\n & \\mbox{\\tt\\inblue CFGLoad}\n\\\\\n\n% & \\mid & \\inred\\verb+with(+e^*,x,x\\verb+)+\\\\\n% v \\in \\Value & ::= \n% & \\mid & \\inred loc & \\inred \\comment{Location} \\\\\n& \\mid & n & \\mbox{\\tt\\inblue CFGNumber}\n&\\comment{Number, double}\\\\\n& \\mid & ``s\" \n & \\mbox{\\tt\\inblue CFGString}\n& \\comment{String}\\\\\n& \\mid & \\TT{true}, \\TT{false} \n & \\mbox{\\tt\\inblue CFGBool}\n& \\comment{Boolean}\\\\\n& \\mid & \\TT{null} \n & \\mbox{\\tt\\inblue CFGNull}\n\\\\\n& \\mid & \\TT{this}\n & \\mbox{\\tt\\inblue CFGThis}\n\\\\\n \\preop & ::= &\n\\multicolumn{3}{l}{\n \\TT{void} \\mid \\TT{typeof} \\mid \\TT{+} \\mid \\TT{-} \\mid \\TT{\\~} \\mid \\TT{!}} \\\\\n \\inop & ::= &\n\\multicolumn{3}{l}{\n \\TT{instanceof} \\mid \\TT{in} \\mid \\TT{|} \\mid \\TT{\\&}\n               \\mid \\TT{\\^} \\mid \\TT{<<} \\mid \\TT{>>} \\mid \\TT{>>>}\n\\mid \\TT{+} \\mid \\TT{-} \\mid \\TT{*} \\mid \\TT{/} \\mid \\TT{\\%} \\mid \\TT{==} \\mid \\TT{!=} \n\\mid \\TT{===}} \\\\\n&\\mid& \\TT{!==} \\mid \\TT{<} \\mid \\TT{>} \\mid \\TT{<=} \\mid \\TT{>=}\n\n\\end{array}\n\\]\n\n\\input{safe-ir2cfg}\n%\\newpage\n\n\\chapter{CFG Collecting Semantics}\n Assumptions and limitations are as follows:\n\\begin{itemize}\n\\item All the variables declared by `\\TT{var}' are included in the set $\\vars$.\n\\item Followings are not yet supported: regular expression, with, getter, setter, eval.\n\\item Runtime exception is omitted. \\TT{throw} is the only way to make an exception.\n\\item Semantics of operators are omitted.\n\\item Semantics for helper functions is not written using denotational semantics(they are not compositional).\n\\item Try-catch clause in a finally block can disturb a flow of a previous throwed value.\n\\end{itemize}\n\n\\section{Settings}\n\\[\n\\begin{array}{rlcl}\nx \\in & \\SF{Prop} & =  & \\SF{String} \\cup\n                       \\set{\n                         \\varprop{return},\\ \\varprop{exception},\\ \\varprop{exception\\_all},\\ \\varprop{this},\\\n                         \\varprop{up},\\ \\varprop{outer} \\\\\n                         \\varprop{proto},\\ \\varprop{scope},\\ \\varprop{class},\\\n                         \\varprop{function},\\ \\varprop{extensible},\\ \\varprop{construct}\n                       }\\\\\nl \\in & \\SF{Loc}  & ::= & %\\varloc{temp} ~\\mid~\n               \\varloc{Global}\n               ~\\mid~ \\varloc{ObjProto}\n               ~\\mid~ \\varloc{ArrayProto}\n               ~\\mid~ \\varloc{RefErrProto} \\\\\n&&             \\mid & \\varloc{RangeErrProto}\n               ~\\mid~ \\varloc{TypeErrProto}\\\\\n\n&     & \\mid  & l_1 ~\\mid~ \\cdots \\\\\ncp \\in & \\SF{ControlPoint} & = & \\SF{Node} \\\\\nH \\in & \\SF{Heap} & =  & \\SF{Loc} \\finto \\SF{Obj} \\\\\no \\in & \\SF{Obj}  & =  & \\SF{Prop} \\finto \\SF{PropValue} \\\\\nA \\in & \\SF{Env} & = & \\SF{Loc}\\listd \\\\\n(H,A), \\SF{stuck} \\in & \\SF{State} & = & \\SF{Heap} \\times \\SF{Env} \\\\\n      & \\SF{PropValue} & = & \\SF{ObjectValue} \\cup \\SF{Value} \\cup \\fid \\cup \\SF{Env} \\\\\n      &       &    & \\inblue \\textit{`$\\SF{Value}\\cup \\fid\\cup \\SF{Env}$' is for internal property.} \\\\\nv \\in & \\SF{Value} & = & \\SF{Loc} \\cup \\SF{PValue} \\\\\nov \\in& \\SF{ObjectValue} & = & \\set{\n                                   value: \\SF{Value}; \\\\\n                                   writable: \\SF{Bool}; \\\\\n                                   enumerable: \\SF{Bool}; \\\\\n                                   configurable: \\SF{Bool}; \\\\\n                                 } \\\\\npv\\in & \\SF{PValue}& = & \\SF{Number}\n                     \\cup \\SF{String}\n                     \\cup \\SF{Bool}\n                     \\cup \\set{\\SF{undefined},\\ \\SF{null}} \\\\\nn \\in & \\SF{Number} & ::= & \\SF{NaN} ~\\mid~ \\SF{Inf} ~\\mid~ -\\SF{Inf} ~\\mid~ 0 ~\\mid~ 1 ~\\mid~ -1 ~\\mid~ 2 ~\\mid~\\cdots\\\\\ns \\in & \\SF{String}\\\\\nb \\in & \\SF{Bool} \\\\\nexc \\in & \\SF{Exception} & ::= & \\exc{ReferenceError} ~\\mid~ \\exc{RangeError} ~\\mid~ \\exc{TypeError}\n\\end{array}\n\\]\n\n\\section{Helper Functions}\n\\[\n\\begin{array}{ll}\n& \\chf{PushStack}(l_o^*,l_n) = l_n::l_o^* \\\\\n& \\chf{TopStack}(l_n::l_o^*) = l_n \\\\\\\\\n& \\chf{Dom}(H) = \\set{l\\ |\\ l\\mapsto o \\in H} \\\\\n& \\chf{Dom}(o) = \\set{x\\ |\\ x\\mapsto v \\in o} \\\\\n\\\\\n& \\chf{IsArray}(H,l) = \\left\\{\n  \\begin{array}{l@{\\quad\\quad\\quad}l}\n    \\vtrue &\\ifc{H(l)(\\varprop{class}) =\n  ``Array\"}\\\\\n    \\vfalse &\\owc\\\\\n  \\end{array}\\right.\n\\\\\n& \\chf{IsObject}(H,l) = \\left\\{\n  \\begin{array}{l@{\\quad\\quad\\quad}l}\n    \\vtrue &\\ifc{H(l)(\\varprop{class}) =\n  ``Object\"\\lor H(l)(\\varprop{class}) = ``Function\"}\\\\\n    \\vfalse &\\owc\\\\\n  \\end{array}\\right.\n\\\\\\\\\n\\chf{IsArrayIndex} & : \\SF{Value} \\rightarrow \\SF{Bool} \\\\\n& \\chf{IsArrayIndex}(v)\n  = \n  \\left\\{\n    \\begin{array}{l@{\\quad\\quad}l}\n      \\vtrue & \\ifc{\\chf{toString}(\\chf{\\inred ToUint32}(\\chf{toString}(v))) = \\chf{toString}(v)\\\\\n        \\land\\ \\chf{\\inred ToUint32}(\\chf{toString}(v)) \\neq 2^{32}-1} \\\\\n      \\vfalse & \\owc\\\\\n    \\end{array}\n  \\right.\n\\\\\n\\\\\n\n\\chf{VarStore} & : \\SF{Heap} \\times \\SF{Env} \\times \\SF{Prop} \\times \\SF{Value}\n\\times \\SF{Bool} \\rightarrow \\SF{Heap} \\\\\n& \\chf{VarStore}(H,[\\varloc{Global}], x, v, b)\n  =  \\chf{PropStore}(H,\\varloc{Global},x,v) \\\\\n& \\quad\\ifc{x\\not\\in\\chf{Dom}(H(\\varloc{Global}))} \\\\\n& \\chf{VarStore}(H,l_{hd}::l_{tl}^{*},x,v,b)\n  =  H[l_{hd}\\mapsto H(l_{hd})[x\\mapsto \\set{H(l_{hd})(x) \\rwith value=v; writable=b}]]\\\\\n& \\quad\\ifc{x \\in \\chf{Dom}(H(l_{hd}))}\\\\\n& \\chf{VarStore}(H,l_{hd}::l_{tl}^{*},x,v,b)\n  =  \\chf{VarStore}(H,l_{tl}^{*},x,v,b)\\\\\n& \\quad\\ifc{x \\not\\in \\chf{Dom}(H(l_{hd}))}\\\\\\\\\n\n\\chf{VarStoreE} & : \\SF{Heap} \\times \\SF{Env} \\times \\SF{Prop} \\times \\SF{Value}\n\\times \\SF{Bool} \\rightarrow \\SF{Heap} \\\\\n& \\chf{VarStoreE}(H,A, t, v, b) = \\chf{VarStore}(H,A, t, v, b) \\\\\n& \\chf{VarStoreE}(H,A, x, v, b) = \\left\\{\n  \\begin{array}{ll}\n    \\chf{VarStore}(H,A, x, v, b) &\\ifc{\\chf{CanPutVar}(H,A,x)}\\\\\n    H & \\owc\n  \\end{array}\n\\right. \\\\\\\\\n\n\\chf{PropStore} & : \\SF{Heap} \\times \\SF{Loc} \\times \\SF{Prop} \\times \\SF{Value} \\rightarrow \\SF{Heap} \\\\\n& \\chf{PropStore}(H,l,x,v)\n  = H\\left[l\\mapsto H(l)\\left[x\\mapsto \\set{\n    value=v;\\\\\n   enumerable=\\vtrue;\\\\\n    configurable=\\vtrue;\\\\\n    writable=\\vtrue\n }\\right]\\right]\\\\\n& \\quad\\ifc{x\\not\\in \\chf{Dom}(H(l))} \\\\\n& \\chf{PropStore}(H,l,x,v)\n  = H\\left[l\\mapsto H(l)\\left[x\\mapsto \\set{H(l)(x)\\rwith value=v}\\right]\\right]\\\\\n& \\quad\\ifc{x\\in \\chf{Dom}(H(l))} \\\\\n\n\\\\\n\\chf{Delete} & : \\SF{Heap} \\times \\SF{Loc} \\times \\SF{Prop} \\rightarrow \\SF{Heap}\n\\times \\SF{Bool}\\\\\n& \\chf{Delete}(H,l,x)\n  =  (H,\\vtrue)\\\\\n& \\quad\\ifc{\\lnot\\chf{HasOwnProperty}(H,l,x)} \\\\\n& \\chf{Delete}(H,l,x)\n  =  (H,\\vfalse)\\\\\n& \\quad\\ifc{\\chf{HasOwnProperty}(H,l,x)\\land\n    H(l)(x).configurable = \\vfalse} \\\\\n& \\chf{Delete}(H,l,x)\n  =  (H[l\\mapsto H(l) - x],\\vtrue)\\\\\n& \\quad\\ifc{\\chf{HasOwnProperty}(H,l,x) \\land H(l)(x).configurable = \\vtrue} \\\\\\\\\n\n\\chf{Lookup} & : \\SF{Heap} \\times \\SF{Env} \\times \\SF{Prop} \\rightarrow \\SF{Value} \\cup \\SF{Exception}\\\\\n\n&\n\\begin{array}{ll}\n% Exception\n% & \\chf{Lookup}(H,[\\varloc{Global}],x)\n%   =  \\exc{ReferenceError} \\quad\\ifc{\\lnot\\chf{HasProperty}(H,\\varloc{Global},x)} \\\\\n\n  \\chf{Lookup}(H,[\\varloc{Global}],x)\n  =  \\exc{ReferenceError} & \\ifc{\\lnot\\chf{HasProperty}(H,\\varloc{Global},x)} \\\\\n  \\chf{Lookup}(H,[\\varloc{Global}],x)\n  =  \\chf{Proto}(H, \\varloc{Global}, x) & \\ifc{\\chf{HasProperty}(H,\\varloc{Global},x)}\\\\\n% & \\chf{Lookup}(H,l_{hd}::l_{tl}^{*},x)\n%   =  \\exc{RefError} \\quad\\ifc{H(l_{hd})(x).value = \\bot} \\\\\n  \\chf{Lookup}(H,l_{hd}::l_{tl}^{*},x)\n   =  H(l_{hd})(x).value & \\ifc{x\\in\\chf{Dom}(H(l_{hd}))} \\\\\n   \\chf{Lookup}(H,l_{hd}::l_{tl}^{*},x)\n   =  \\chf{Lookup}(H, l_{tl}^{*},x) & \\ifc{x\\not\\in\\chf{Dom}(H(l_{hd}))}\\\\\n\\end{array}\\\\\n\\\\\n\\end{array}\n\\]\n\\[\n\\begin{array}{ll}\n\\chf{TypeTag} & : \\SF{Heap} \\times \\SF{Value} \\rightarrow \\set{``number\", ``string\", ``boolean\", ``object\",\\\\ ``function\", ``null\", ``undefined\"}\\\\\n& \\chf{TypeTag}(H,v) = \\left\\{\n\\begin{array}{l@{\\quad\\quad}l}\n  ``number\" & \\ifc{v \\in \\SF{Number}} \\\\\n  ``boolean\" & \\ifc{v \\in \\SF{Boolean}} \\\\\n  ``string\" & \\ifc{v \\in \\SF{String}} \\\\\n  ``object\" & \\ifc{v \\in \\SF{Loc}\\land\\lnot\\chf{IsCallable}(H,v)} \\\\\n  ``function\" & \\ifc{v \\in \\SF{Loc}\\land\\chf{IsCallable}(H,v)} \\\\\n  ``object\" & \\ifc{v = \\SF{null}} \\\\\n  ``undefined\" & \\ifc{v = \\SF{undefined}} \\\\\n\\end{array}\n\\right. \\\\\n\\\\\n\n\\chf{CanPut} & : \\SF{Heap} \\times \\SF{Loc} \\times \\SF{Prop} \\rightarrow \\SF{Bool}\\\\\n&\n\\begin{array}{ll}\n  \\chf{CanPut}(H,l,x) = \\chf{CanPutHelp}(H,l,x,l) & \\\\\n\\end{array}\n\\\\\\\\\n\n\\chf{CanPutHelp} & : \\SF{Heap} \\times \\SF{Loc} \\times \\SF{Prop} \\times \\SF{Loc}\n\\rightarrow \\SF{Bool}\\\\\n&\n\\begin{array}{ll}\n  \\chf{CanPutHelp}(H,l_1,x,l_2) = \\chf{CanPutHelp}(H,H(l_1)(\\varprop{proto}).value,x,l_2) &\\\\\n   \\quad\\ifc{x\\not\\in\\chf{Dom}(H(l_1)) \\land H(l_1)(\\varprop{proto}).value\\ \\neq \\SF{null}}&\\\\\n  \\chf{CanPutHelp}(H,l_1,x,l_2) = H(l)(\\varprop{extensible}) &\\\\\n  \\quad\\ifc{x\\not\\in\\chf{Dom}(H(l_1)) \\land H(l_1)(\\varprop{proto}).value\\ = \\SF{null}}&\\\\\n  \\chf{CanPutHelp}(H,l_1,x,l_2) = H(l_1)(x).writable &\\\\\n  \\quad\\ifc{x\\in\\chf{Dom}(H(l_1))}&\\\\\n\\end{array}\n\\\\\\\\\n\n\\chf{CanPutVar} & : \\SF{Heap} \\times \\SF{Env} \\times \\SF{Prop} \\rightarrow \\SF{Bool}\\\\\n&\n\\begin{array}{ll}\n  \\chf{CanPutVar}(H,[\\varloc{Global}],x)\n  =  \\chf{CanPut}(H,\\varloc{Global},x) \\\\\n\\chf{CanPutVar}(H,l_{hd}::l^{*}_{tl},x)\n  =  H(l_{hd})(x).writable & \\ifc{x\\in\\chf{Dom}(H(l_{hd}))} \\\\\n\\chf{CanPutVar}(H,l_{hd}::l^{*}_{tl},x)\n  =  \\chf{CanPutVar}(H,l^{*}_{tl},x) & \\ifc{x\\not\\in\\chf{Dom}(H(l_{hd}))} \\\\\n\\end{array}\\\\\n\\\\\n\n\\chf{HasProperty} & : \\SF{Heap} \\times \\SF{Loc} \\times \\SF{Prop} \\rightarrow \\SF{Bool} \\\\\n& \\chf{HasProperty}(H,l,x) = \\vtrue \\\\\n& \\quad\\ifc{\\chf{HasOwnProperty}(H,l,x)} \\\\\n& \\chf{HasProperty}(H,l,x) = \\vfalse \\\\\n& \\quad\\ifc{\\lnot\\chf{HasOwnProperty}(H,l,x) \\land H(l_1)(\\varprop{proto}).value\\ = \\SF{null}}\\\\\n& \\chf{HasProperty}(H,l,x) = \\chf{HasProperty}(H,H(l)(\\varprop{proto}).value,x)\\\\\n& \\quad\\ifc{\\lnot\\chf{HasOwnProperty}(H,l,x) \\land H(l_1)(\\varprop{proto}).value\\ \\neq \\SF{null}} \\\\\n\\\\\n\\\\\n\n\\chf{HasOwnProperty} & : \\SF{Heap} \\times \\SF{Loc} \\times \\SF{Prop} \\rightarrow \\SF{Bool} \\\\\n&\n\\begin{array}{ll}\n  \\chf{HasOwnProperty}(H,l,x) = \\vfalse & \\ifc{x\\not\\in\\chf{Dom}(H(l))} \\\\\n  \\chf{HasOwnProperty}(H,l,x) = \\vtrue & \\ifc{x\\in\\chf{Dom}(H(l))} \\\\\n\\end{array}\\\\\n\\\\\n\\chf{LookupBase} & : \\SF{Heap} \\times \\SF{Env} \\times \\SF{Prop} \\rightarrow \\SF{Loc} \\\\\n&\n\\begin{array}{ll}\n\\chf{LookupBase}(H,[\\varloc{Global}],x)\n= \\chf{ProtoBase}(H, \\varloc{Global}, x) \\\\\n\\chf{LookupBase}(H,l_{hd}::l_{tl}^{*},x)\n= l_{hd} & \\ifc{x\\in\\chf{Dom}(H(l_{hd}))} \\\\\n\\chf{LookupBase}(H,l_{hd}::l_{tl}^{*},x)\n= \\chf{LookupBase}(H, l_{tl}^{*},x) & \\ifc{x\\not\\in\\chf{Dom}(H(l_{hd}))} \\\\\n\\end{array}\\\\\n\\\\\n\\end{array}\n\\]\n\\[\n\\begin{array}{ll}\n\\chf{ProtoBase} & : \\SF{Heap} \\times \\SF{Loc} \\times \\SF{Prop} \\rightarrow \\SF{Loc}\\\\\n& \n\\begin{array}{ll}\n  \\chf{ProtoBase}(H,l,x) = l &\\\\\n    \\quad\\ifc{x\\in\\chf{Dom}(H(l))}&\\\\\n  \\chf{ProtoBase}(H,l,x) = \\{ \\} &\\\\\n    \\quad\\ifc{x\\not\\in\\chf{Dom}(H(l)) \\land H(l)(\\varprop{proto}).value\\ = \\SF{null}}&\\\\\n  \\chf{ProtoBase}(H,l,x) =  \\chf{ProtoBase}(H,H(l)(\\varprop{proto}).value,x) &\\\\\n    \\quad\\ifc{x\\not\\in\\chf{Dom}(H(l)) \\land H(l)(\\varprop{proto}).value\\ \\neq \\SF{null}}&\\\\\n\\end{array}\\\\\n\\\\\n\\chf{Proto} & : \\SF{Heap} \\times \\SF{Loc} \\times \\SF{Prop} \\rightarrow \\SF{Value}\\\\\n& \n\\begin{array}{ll}\n  \\chf{Proto}(H,l,x) =  H(l)(x).value &\\\\\n    \\quad\\ifc{x\\in\\chf{Dom}(H(l))}&\\\\\n  \\chf{Proto}(H,l,x) =  \\chf{Proto}(H,H(l)(\\varprop{proto}).value,x) &\\\\\n    \\quad\\ifc{ x\\not\\in\\chf{Dom}(H(l)) \\land H(l)(\\varprop{proto}).value\\ \\neq \\SF{null}}\\\\\n  \\chf{Proto}(H,l,x) = \\SF{undefined} &\\\\\n    \\quad\\ifc{ x\\not\\in\\chf{Dom}(H(l)) \\land H(l)(\\varprop{proto}).value\\ = \\SF{null}}\\\\\n\\end{array}\\\\\n\\\\\n\\chf{NewObject} & : \\SF{Loc} \\rightarrow \\SF{Obj} \\\\\n& \\chf{NewObject}(l) = \\set{\\varprop{class}\\mapsto \"Object\",\\\\\n  \\varprop{proto}\\mapsto\n  \\set{\n    value=l;\\\\writable=\\vfalse;\\\\\n    enumerable=\\vfalse;\\\\configurable=\\vfalse\\\\\n    },\\\\\n  \\varprop{extensible}\\mapsto \\vtrue}\\\\\\\\\n\n\\chf{NewFunctionObject} & : \\fid \\times \\SF{Env} \\times \\SF{Loc} \\times \\SF{Number} \\rightarrow \\SF{Obj} \\\\\n& \\chf{NewFunctionObject}(fid,A,l,n) = \\set{\n    \\varprop{class}\\mapsto ``Function\",\\\\\n    \\varprop{function}\\mapsto fid,\\\\\n    \\varprop{construct}\\mapsto fid,\\\\\n    \\varprop{scope}\\mapsto A,\\\\\n    \\varprop{proto}\\mapsto\n    \\set{\n      value=\\varloc{FunctionProto};\\\\writable=\\vfalse;\\\\\n      enumerable=\\vfalse;\\\\configurable=\\vfalse\n    },\\\\\n    ``prototype\"\\mapsto \\set{\n        value:l;\\\\\n        writable:\\vtrue;\\\\\n        enumerable:\\vfalse;\\\\\n        configurable:\\vfalse\n      },\\\\\n    ``length\"\\mapsto \\set{\n        value:n;\\\\\n        writable:\\vfalse;\\\\\n        enumerable:\\vfalse;\\\\\n        configurable:\\vfalse\n      },\\\\\n    \\varprop{extensible}\\mapsto \\vtrue\n}\\\\\\\\\n\\chf{NewArrayObject} & : \\SF{Number} \\rightarrow \\SF{Obj} \\\\\n& \\chf{NewArrayObject}(n) = \\set{\n    \\varprop{class}\\mapsto ``Array\",\\\\\n    \\varprop{proto}\\mapsto \n    \\set{\n      value=\\varloc{ArrayProto};\\\\writable=\\vfalse;\\\\\n      enumerable=\\vfalse;\\\\configurable=\\vfalse\n    },\\\\\n   ``length\"\\mapsto \\set{\n       value:n;\\\\\n       writable:\\vtrue;\\\\\n       enumerable:\\vfalse;\\\\\n       configurable:\\vfalse\n     },\\\\\n    \\varprop{extensible}\\mapsto \\vtrue\n}\\\\\\\\\n\n\\end{array}\n\\]\n\\[\n\\begin{array}{ll}\n\n\\chf{NewArgObject} & : \\SF{Number} \\rightarrow \\SF{Obj} \\\\\n& \\chf{NewArgObject}(n) = \\set{\n    \\varprop{class}\\mapsto ``Arguments\",\\\\\n    \\varprop{proto}\\mapsto \n    \\set{\n      value=\\varloc{ObjProto};\\\\writable=\\vfalse;\\\\\n      enumerable=\\vfalse;\\\\configurable=\\vfalse\n    },\\\\\n   ``length\"\\mapsto \\set{\n       value:n;\\\\\n       writable:\\vtrue;\\\\\n       enumerable:\\vfalse;\\\\\n       configurable:\\vtrue\n     },\\\\\n    \\varprop{extensible}\\mapsto \\vtrue\n}\\\\\\\\\n\n\\chf{NewBoolean} & : \\SF{Bool} \\rightarrow \\SF{Obj} \\\\\n& \\chf{NewBoolean}(v) = \\set{\n    \\varprop{class}\\mapsto ``Boolean\",\\\\\n    \\varprop{proto}\\mapsto \n    \\set{\n      value=\\varloc{BoolProto};\\\\writable=\\vfalse;\\\\\n      enumerable=\\vfalse;\\\\configurable=\\vfalse\n    },\\\\\n    \\varprop{extensible}\\mapsto \\vtrue, \\\\\n    \\varprop{primitive}\\mapsto v\n}\\\\\\\\\n\n\\chf{NewNumber} & : \\SF{Number} \\rightarrow \\SF{Obj} \\\\\n& \\chf{NewNumber}(v) = \\set{\n    \\varprop{class}\\mapsto ``Number\",\\\\\n    \\varprop{proto}\\mapsto \n    \\set{\n      value=\\varloc{NumProto};\\\\writable=\\vfalse;\\\\\n      enumerable=\\vfalse;\\\\configurable=\\vfalse\n    },\\\\\n    \\varprop{extensible}\\mapsto \\vtrue, \\\\\n    \\varprop{primitive}\\mapsto v\n}\\\\\\\\\n\n\\chf{NewString} & : \\SF{String} \\rightarrow \\SF{Obj} \\\\\n& \\chf{NewString}(s) = o_1 \\cup o_2 \\\\\n& \\quad\\wherec{\n  v_{len} = length(s)\\\\\n  \\land\\ o_1 = \\set{\n    \\varprop{class}\\mapsto ``String\",\\\\\n    \\varprop{proto}\\mapsto \n    \\set{\n      value=\\varloc{StrProto};\\\\writable=\\vfalse;\\\\\n      enumerable=\\vfalse;\\\\configurable=\\vfalse\n    },\\\\\n    \\varprop{extensible}\\mapsto \\vtrue, \\\\\n    \\varprop{primitive}\\mapsto s, \\\\\n    ``length\"\\mapsto \\set{\n      value=v_{len};\\\\writable=\\vfalse;\\\\\n      enumerable=\\vfalse;\\\\configurable=\\vfalse\n    }\n  }\\\\\n  \\land\\ o_2 = \\set{\\left.``i\"\\mapsto \\set{\n      value = v_{char};\\\\writable=\\vfalse;\\\\\n      enumerable=\\vtrue;\\\\configurable=\\vfalse\n    } ~\\right|~ 0 \\leq i < v_{len}\\land\\ v_{char}=charAt(s,i)}\n}\\\\\\\\\n\n\\chf{IsCallable} & : \\SF{Heap} \\times \\SF{Loc} \\rightarrow \\SF{Bool} \\\\\n& \\chf{IsCallable}(H,l)\n  = \\left\\{\n    \\begin{array}{l@{\\quad\\quad\\quad}l}\n      \\vtrue &\\ifc{\\varprop{function}\\in\\chf{Dom}(H(l))}\\\\\n      \\vfalse &\\owc\n    \\end{array}\n    \\right.\\\\\\\\\n\\end{array}\n\\]\n\\[\n\\begin{array}{ll}\n\\chf{HasConstruct} & : \\SF{Heap} \\times \\SF{Loc} \\rightarrow \\SF{Bool} \\\\\n& \\chf{HasConstruct}(H,l)\n  = \\left\\{\n    \\begin{array}{l@{\\quad\\quad\\quad}l}\n      \\vtrue & \\ifc{\\varprop{construct}\\in\\chf{Dom}(H(l))}\\\\\n      \\vfalse &\\owc\n    \\end{array}\n    \\right.\\\\\\\\\n\n\\chf{newLocation} & : \\SF{Unit} \\rightarrow \\SF{Loc} \\\\\n& \\chf{newLocation}()\n  = l_{new}\\\\\n\\\\\n\\chf{toNumber} & : \\SF{PValue} \\rightarrow \\SF{Number} \\\\\n& \\chf{toNumber}(pv)\n  = \n  \\left\\{\n    \\begin{array}{l@{\\quad\\quad}l}\n      \\SF{NaN} & \\ifc{pv=\\SF{undefined}} \\\\\n      \\SF{0}   & \\ifc{pv=\\SF{null}\\lor pv=\\vfalse} \\\\\n      \\SF{1}   & \\ifc{pv=\\vtrue} \\\\\n      pv   & \\ifc{pv\\in\\SF{Number}} \\\\\n      \\inred \\chf{Str2Num}(pv)   & \\ifc{pv\\in\\SF{String}} \\\\\n    \\end{array}\n  \\right.\\\\\n\\\\\n\\chf{toString} & : \\SF{PValue} \\rightarrow \\SF{String} \\\\\n& \\chf{toString}(pv)\n  = \n  \\left\\{\n    \\begin{array}{l@{\\quad\\quad}l}\n      ``undefined\" & \\ifc{pv=\\SF{undefined}} \\\\\n      ``null\"      & \\ifc{pv=\\SF{null}} \\\\\n      ``pv\"        & \\ifc{pv\\in\\SF{Boolean}} \\\\\n      ``\\SF{$pv$}\" & \\ifc{pv\\in\\SF{Number}} \\\\\n      pv           & \\ifc{pv\\in\\SF{String}} \\\\\n    \\end{array}\n  \\right.\\\\\n\\\\\n\\chf{toBoolean} & : \\SF{Value} \\rightarrow \\SF{Bool} \\\\\n& \\chf{toBoolean}(v)\n  = \n  \\left\\{\n    \\begin{array}{l@{\\quad\\quad}l}\n      \\vfalse   & \\ifc{v=\\SF{undefined}} \\\\\n      \\vfalse   & \\ifc{v=\\SF{null}} \\\\\n      v         & \\ifc{v\\in\\SF{Boolean}} \\\\\n      \\vfalse   & \\ifc{v\\in\\SF{Number}\\land v\\in\\set{\\sf 0,NaN}} \\\\\n      \\vtrue    & \\ifc{v\\in\\SF{Number}\\land v\\not\\in\\set{\\sf 0,NaN}} \\\\\n      \\vfalse   & \\ifc{v\\in\\SF{String}\\land v=``\"} \\\\\n      \\vtrue    & \\ifc{v\\in\\SF{String}\\land v\\neq``\"} \\\\\n      \\vtrue    & \\ifc{v\\in\\SF{Loc}}\n    \\end{array}\n  \\right.\\\\\n\\\\\n\\chf{toPrimitive} & : \\SF{Value} \\rightarrow \\SF{PValue} \\\\\n& \\chf{toPrimitive}(v)\n  = \n  \\left\\{\n    \\begin{array}{l@{\\quad\\quad}l}\n      v & \\ifc{v\\not\\in\\SF{Loc}} \\\\\n      \\inred \\chf{Obj2Str}(v)   & \\ifc{v\\in\\SF{Loc}} \\\\\n    \\end{array}\n  \\right.\\\\\n\\\\\n\\chf{toObject} & : \\SF{Heap} \\times \\SF{Value} \\rightarrow \\SF{Heap} \\times \\SF{Value} \\cup \\SF{Exception}\\\\\n& \\chf{toObject}(H, l) = (H, l)\\\\\n& \\chf{toObject}(H, v) = (H, \\SF{TypeError}) \\quad\\ifc{v \\in \\set{\\SF{undefined}, \\SF{null}}}\\\\\n& \\chf{toObject}(H, v) = (H_1, l_{new}) \\\\\n& \\quad\\wherec{\n  o = \\left\\{\n    \\begin{array}{ll}\n      \\chf{NewString}(v) & \\ifc{v \\in \\SF{String}}\\\\\n      \\chf{NewNumber}(v) & \\ifc{v \\in \\SF{Number}}\\\\\n      \\chf{NewBoolean}(v) & \\ifc{v \\in \\SF{Bool}}\\\\\n    \\end{array}\n  \\right. \\\\\n  H_1 = H[l_{new}\\mapsto o] \\\\\n  l_{new} = \\chf{newLocation}()\n}\\\\\n\\\\\n\\end{array}\n\\]\n\\[\n\\begin{array}{ll}\n\\chf{getThis} & : \\SF{Value} \\rightarrow \\SF{Loc} \\\\\n& \\chf{getThis}(v)\n  = \n  \\left\\{\n    \\begin{array}{l@{\\quad\\quad}l}\n      \\varloc{Global} & \\ifc{v=\\SF{undefined}} \\\\\n      \\varloc{Global} & \\ifc{v=\\SF{null}} \\\\\n      \\varloc{Global} & \\ifc{v\\in\\SF{Loc} \\land \\lnot\\chf{IsObject}(v)} \\\\\n      v               & \\ifc{v\\in\\SF{Loc} \\land \\chf{IsObject}(v)}\\\\\n    \\end{array}\n  \\right.\\\\\n\\\\\n\\chf{inherit} & : \\SF{Heap} \\times \\SF{Loc} \\times \\SF{Loc} \\rightarrow \\SF{Value} \\\\\n& \\chf{inherit}(H,l_1,l_2) = \\left\\{\n  \\begin{array}{ll}\n    \\vtrue & \\ifc{l_1 = l_2} \\\\\n    \\vfalse & \\ifc{l_1 \\neq l_2 \\land H(l_1)(\\varprop{proto}).value\\ = \\SF{null}} \\\\\n    \\chf{inherit}(H,H(l_1)(\\varprop{proto}).value,l_2) & \\ifc{l_1 \\neq l_2 \\land H(l_1)(\\varprop{proto}).value\\ \\neq \\SF{null}} \\\\\n  \\end{array}\n  \\right.\\\\\n\\\\\n\\chf{iteratorInit} & : \\SF{Obj} \\times \\powerset{\\SF{Prop}} \\times \\SF{Number} \\rightarrow \\SF{Obj} \\\\\n& \\chf{iteratorInit}(o,P,n) = \n  \\left\\{\n  \\begin{array}{l}\n    \\{\\varprop{i}\\mapsto 0\\} \\\\\\quad\\ifc{P = \\emptyset} \\\\\n    \\chf{iteratorInit}(o,P-x,n+1)[n\\mapsto x] \\\\\\quad \\ifc{x\\in P} \\\\\n  \\end{array}\n  \\right.\\\\\n\\\\\n\\chf{collectProps} & : \\SF{Heap} \\times \\SF{Loc} \\rightarrow \\powerset{\\SF{Loc}} \\\\\n& \\chf{collectProps}(H,l) = \n  \\left\\{\n  \\begin{array}{ll}\n    \\chf{Dom}(H(l)) \\cup\\ \\chf{CollectProps}(H,H(l)(\\varprop{proto}).value)\n    & \\ifc{H(l)(\\varprop{proto}).value \\neq \\SF{null}} \\\\\n    \\{\\} & \\ifc{H(l)(\\varprop{proto}).value = \\SF{null}} \\\\\n  \\end{array}\n  \\right.\\\\\n\\\\\n\\end{array}\n\\]\n\\[\n\\begin{array}{ll}\n\\chf{isEnumerable} & : \\SF{Heap} \\times \\SF{Loc} \\times \\SF{Prop} \\rightarrow \\SF{Bool} \\\\\n& \\chf{isEnumerable}(H,l,x) =\n  \\left\\{\n    \\begin{array}{l}\n      H(l)(x).enumerable \\\\\n      \\quad\\ifc{x\\in\\chf{Dom}(H(l))} \\\\\n      \\chf{isEnumerable}(H,H(l)(\\varprop{proto}).value,x) \\\\\n      \\quad\\ifc{x\\notin\\chf{Dom}(H(l)) \\land H(l)(\\varprop{proto}).value \\neq \\SF{null}} \\\\\n      \\vfalse \\\\\n      \\quad\\ifc{x\\notin\\chf{Dom}(H(l)) \\land H(l)(\\varprop{proto}).value = \\SF{null}} \\\\\n    \\end{array}\n  \\right.\\\\\n\\\\\n\\chf{next} & : \\SF{Heap} \\times \\SF{Obj} \\times \\SF{Number} \\times \\SF{Loc} \\rightarrow \\SF{Number} \\\\\n& \\chf{next}(H,o_{iter},n,l) = \n  \\left\\{\n  \\begin{array}{ll}\n    n &\\ifc{n\\notin \\chf{Dom}(o_{iter})} \\\\\n    n &\\ifc{n\\in \\chf{Dom}(o_{iter})\n%      \\land\\ \\chf{HasProperty}(H,l,o_{iter}(n))\\\\\n      \\land\\ \\chf{isEnumerable}(H,l,o_{iter}(n))} \\\\\n    \\chf{next}(H,o_{iter},n+1,l) & \\owc\\\\\n  \\end{array}\n  \\right.\\\\\n\\\\\n\\chf{NewExceptionObject} & : \\SF{Exception} \\rightarrow \\SF{Obj} \\\\\n& \\chf{NewExceptionObject}(exc) = \\chf{NewObject}(l)\\\\\n& \\quad\\wherec{\n  l=\\left\\{\n    \\begin{array}{ll}\n      \\varloc{RefErrProto}&\\ifc{exc = \\exc{ReferenceError}} \\\\\n      \\varloc{RangeErrProto}&\\ifc{exc = \\exc{RangeError}} \\\\\n      \\varloc{TypeErrProto}&\\ifc{exc = \\exc{TypeError}} \\\\\n    \\end{array}\n  \\right.\n}\\\\\\\\\n\\chf{RaiseException} & : \\SF{Heap} \\times \\SF{Exception}\\cup\\SF{Value} \\rightarrow \\SF{Heap} \\\\\n& \\chf{RaiseException}(H,v) = H_1 \\\\\n& \\quad\\wherec{\n  H_1 = H[\\varloc{temp}\\mapsto H(\\varloc{temp})[\\varprop{exception}\\mapsto v]]\n}\\\\\n& \\chf{RaiseException}(H,exc) = H_2 \\\\\n& \\quad\\wherec{\n  l_e = \\chf{newLocation}() \\\\\n  H_1 = H[l_e\\mapsto\\chf{NewExceptionObject}(exc)] \\\\\n  H_2 = H_1[\\varloc{temp}\\mapsto H_1(\\varloc{temp})[\\varprop{exception}\\mapsto l_{e}]]\n}\n\\end{array}\n\\]\n% \\[\n% \\begin{array}{ll}\n% \\chf{@ToObject} & : \\SF{PValue} \\rightarrow \\SF{} \\\\\n% & \\chf{Prim2Str}(v)\n% \\end{array}\n% \\]\n\n\\newpage\n\\section{Semantics}\n\\[\n\\begin{array}{lcl}\n  \\N & \\in & \\SF{ControlPoint} \\rightarrow \\Command \\rightarrow \\powerset{\\SF{State}} \\rightarrow \\powerset{\\SF{State}} \\\\\n  \\I & \\in & \\SF{ControlPoint} \\rightarrow \\SF{Instruction} \\rightarrow \\SF{State} \\rightarrow \\SF{State} \\\\\n  \\V & \\in & \\SF{Expression} \\rightarrow \\SF{State} \\rightarrow \\SF{Value} \\cup \\SF{Exception}\\\\\n  \\B & \\in & \\SF{Expression} \\rightarrow \\SF{State} \\rightarrow \\SF{State} \\\\\n\\end{array}\n\\]\n\\[\n\\begin{array}{l} \n% \\Entry & \\comment{entry node}\\\\\\\\\n\\N _{cp}\\lbr {\\sf entry} \\rbr S = \n \\bigcup\\set{(H_1,A) \\mid (H,A)\\in S} \\\\\n \\quad\\wherec{\n   ({fid_{this}},\\SF{ENTRY}) = cp \\land l=\\chf{TopStack}(A)\\\\\n   \\land\\ x_{argvar}^{*} = \\chf{getArgVars}_P({fid_{this}})\\ \n   \\land\\ x_{localvar}^{*} = \\chf{getLocalVars}_P({fid_{this}}) \\\\\n   \\land\\ H_1=H\\left[l\\mapsto\n   H(l)\n     \\left[\n       \\begin{array}{l}\n         \\left(x_{argvar}\\mapsto\\set{value=\\SF{undefined};writable=\\vtrue;\\\\\n             enumerable=\\vfalse;configurable=\\vfalse}\\right)^{*}, \\\\\n         \\left(x_{localvar}\\mapsto\\set{value=\\SF{undefined};writable=\\vtrue;\\\\\n             enumerable=\\vtrue;configurable=\\vfalse}\\right)^{*} \\\\\n    \\end{array}\n     \\right]\n     \\right] \\\\\n   % \\land\\ H_2=H_1[l\\mapsto H_1(l)\\ (\\ []\\ )^{*}\\ ] \\\\\n   % \\land\\ H_3=H_2[l\\mapsto H_2(l)\\ (\\ []\\ )^{*}\\ ] \\\\\n}\\\\\\\\\n\n\\N _{cp}\\lbr \\SF{exit} \\rbr S = S \\\\\\\\\n\\N _{cp}\\lbr \\SF{exit-exc} \\rbr S = S \\\\\\\\\n% \\Exit & \\comment{exit node}\\\\\\\\\n% \\Exite & \\comment{exit node for exception}\\\\\\\\\n\n% i^+\n\\N _{cp}\\lbr i^+\\rbr S = \\bigcup\\set{(\\I _{cp} \\lbr i\\rbr(H,A))^{+} \\mid (H,A)\\in S}\\\\\\\\\n\n\\I _{cp}\\lbr i \\rbr (H,A) = (H,A)\n\\quad\\ifc{\\chf{HasProperty}(H,\\varloc{temp},\\varprop{exception}) \\lor (H,A)=\\SF{stuck}}\n\\\\\\\\\n\n% x~\\verb+:=+~\\TT{alloc}\\verb+(+ e \\verb+)+\n\\comment{\\inblue * if $e$ is None, $v$ is considered like a value which is not an element of $\\SF{Loc}$.}\\\\\n\\I  _{cp}\\lbr x\\TT{:=}\\TT{alloc}\\TT{(}e^{?}\\TT{)}\\rbr (H,A)\n = (H_2,A) \\quad\\ifc{v=\\V\\lbr e \\rbr(H,A)}\\\\\n\\quad \\wherec{\nl_{new} = \\chf{newLocation}()\\\\\nl_p = \\left\\{\n  \\begin{array}{ll}\n    v & \\ifc{v \\in \\SF{Loc}} \\\\\n    \\varloc{ObjProto} & \\owc\n  \\end{array}\n\\right.\\\\\nH_1 = H[l_{new}\\mapsto \\chf{NewObject}(l_p)] \\\\\nH_2 = \\chf{VarStoreE}(H_1,A,x,l_{new},\\vtrue)\n}\\\\\n% x~\\verb+:=+~\\TT{alloc}\\verb+(+ e \\verb+)+\n\\I  _{cp}\\lbr x\\TT{:=}\\TT{alloc}\\TT{(}e^{?}\\TT{)}\\rbr (H,A)\n = (H_1, A) \\quad\\ifc{exc=\\V\\lbr e \\rbr(H,A)}\\\\\n\\quad\\wherec{\n  H_1=\\chf{RaiseException}(H,exc)\n}\\\\\\\\\n\n% % x~\\verb+:=+~\\TT{alloc}\\verb+(+ e \\verb+)+\n% \\I  _{cp}\\lbr x\\TT{:=}\\TT{allocObject}\\TT{()}\\rbr (H,A)\n%  = (\\chf{VarStore}(H,A,x,l_{new},\\vtrue)[l_{new}\\mapsto \\chf{NewObject}(\\varloc{ObjProto})],A) \\\\\n% \\quad \\wherec{l_{new} = \\chf{newLocation}()\\land \\chf{CanPutVar}(H,A,x)}\n% \\\\\\\\\n         \n% x~\\verb+:=+~\\SF{allocArray}\\verb+(+n\\verb+)+\n\\I _{cp}\\lbr x\\TT{:=}\\TT{allocArray}\\TT{(n)} \\rbr(H,A)\n = (H_2,A) \\\\\n\\quad\\wherec{\n  l_{new} =\\chf{newLocation}()\\\\\n  n = \\V\\lbr \\TT{n} \\rbr(H,A)\\\\\n  H_1 = H[l_{new}\\mapsto \\chf{NewArrayObject}(n)] \\\\\n  H_2 = \\chf{VarStoreE}(H_1,A,x,l_{new},\\vtrue) \n}\n\\\\\\\\\n\n% x~\\verb+:=+~\\SF{allocArg}\\verb+(+n\\verb+)+\n\\I _{cp}\\lbr x\\TT{:=}\\TT{allocArg}\\TT{(n)} \\rbr(H,A)\n = (H_2,A) \\\\\n\\quad\\wherec{l_{new} =\\chf{newLocation}() \\\\\n  n = \\V\\lbr \\TT{n} \\rbr(H,A)\\\\\n  H_1 = H[l_{new}\\mapsto \\chf{NewArgObject}(n)]\\\\\n  H_2 = \\chf{VarStoreE}(H_1,A,x,l_{new},\\vtrue)\n}\n\\\\\\\\\n\n% x ~\\verb+:=+~ e \n\\I _{cp}\\lbr x\\TT{:=}e \\rbr(H,A)\n = (H_1,A)\\quad\\ifc{v=\\V\\lbr e\\rbr(H,A)}\\\\\n \\quad\\wherec{\n   H_1 = \\chf{VarStoreE}(H,A,x,v,\\vtrue)\n}\n\\\\\n\\I _{cp}\\lbr x\\TT{:=}e \\rbr(H,A)\n = (H_1,A)\\quad\\ifc{exc=\\V\\lbr e\\rbr(H,A)}\\\\\n\\quad\\wherec{\n  H_1=\\chf{RaiseException}(H,exc)\n}\\\\\\\\\n\n% x ~\\verb+:=+~ \\SF{delete}\\verb+(+e_1^(?),e_2\\verb+)+\n\\I _{cp}\\lbr x_1 \\TT{:=} \\TT{delete}\\TT{(}x_2\\TT{)} \\rbr(H,A)\n = (H_2,A) \\\\\n\\quad\\wherec{\n  l_{base}=\\chf{LookupBase}(H,A,x_2)\\\\\n  (H_1,b)=\\chf{Delete}(H,l_{base},x_2)\\\\\n  H_2=\\chf{VarStoreE}(H_1,A,x_1,b,\\vtrue)\n}\\\\\n\\I _{cp}\\lbr x \\TT{:=} \\TT{delete}\\TT{(}e\\TT{)} \\rbr(H,A)\n = (H_1,A) \\quad\\ifc{v=\\V\\lbr e\\rbr(H,A)}\\\\\n\\quad\\wherec{\n  H_1=\\chf{VarStoreE}(H,A,x,\\vtrue,\\vtrue)\n}\\\\\n\\I _{cp}\\lbr x \\TT{:=} \\TT{delete}\\TT{(}e\\TT{)} \\rbr(H,A)\n = (H_1,A) \\quad\\ifc{exc=\\V\\lbr e\\rbr(H,A)}\\\\\n\\quad\\wherec{\n  H_1 = \\chf{RaiseException}(H,exc)\n}\n\\\\\\\\\n\\I _{cp}\\lbr x \\TT{:=} \\TT{delete}\\TT{(}e_1,e_2\\TT{)} \\rbr(H,A)\n = (H_2,A) \\\\\n\\quad\\wherec{\n  l=\\V\\lbr e_1\\rbr(H,A)\\ \\land\\ s=\\V\\lbr e_2\\rbr(H,A)\\\\\n  (H_1,b)=\\chf{Delete}(H,l,s)\\\\\n  H_2=\\chf{VarStoreE}(H_1,A,x,b,\\vtrue)\n}\\\\\n\\\\\n\\end{array}\n\\]\n\\[\n\\begin{array}{ll}\n\n% e\\verb+[+e\\verb+]+ ~\\verb+:=+~ e \n\\I _{cp}\\lbr e_1\\TT{[}e_2\\TT{]}\\TT{=}e_3 \\rbr(H,A)\n = (H_1, A) \\quad\\ifc{exc=\\V\\lbr e_3\\rbr(H,A)}\\\\\n\\quad\\wherec{\n  H_1=\\chf{RaiseException}(H,exc)\n}\\\\\\\\\n\n% e\\verb+[+e\\verb+]+ ~\\verb+:=+~ e \n\\I _{cp}\\lbr e_1\\TT{[}e_2\\TT{]}\\TT{=}e_3 \\rbr(H,A)\n = (H_1,A)\\quad\\ifc{\\lnot \\SF{IsArray}(H,l)\\ \\land\\ \\chf{CanPut}(H,l,x)}\\\\\n\\quad\\wherec{\n  l=\\V\\lbr e_1\\rbr(H,A)\\\\\n  x=\\V\\lbr e_2\\rbr(H,A)\\\\\n  v=\\V\\lbr e_3\\rbr(H,A)\\\\\n  H_1=\\chf{PropStore}(H,l,x,v)\n}\\\\\n%\\inred \\ifc{l=\\V\\lbr e_2\\rbr(H,A)?}\\\\\n\\I _{cp}\\lbr e_1\\TT{[}e_2\\TT{]}\\TT{=}e_3 \\rbr(H,A)\n = (H_2, A)\\quad\\ifc{\\SF{IsArray}(H,l)\\ \\land\\ \\chf{CanPut}(H,l,v_{idx})\\ \\land\\ \\chf{IsArrayIndex}(v_{idx})}\\\\\n\\quad\\wherec{\n  l=\\V\\lbr e_1\\rbr(H,A)\\\\\n  v_{idx}=\\V\\lbr e_2\\rbr(H,A)\\\\\n  v=\\V\\lbr e_3\\rbr(H,A)\\\\\n  n_{oldLen}=\\chf{Proto}(H,l,``length\")\\\\\n  H_1=H[l\\mapsto H(l)[v_{idx}\\mapsto \\set{value=v;writable=\\vtrue;enumerable=\\vtrue;configurable=\\vtrue}]] \\\\\n  H_2= \\left\\{\n    \\begin{array}{ll}\n      H_1[l\\mapsto H_1(l)[``length\"\\mapsto H(l)(``length\")\\SF{ with } value=v_{idx}+1]] & \\ifc{n_{oldLen} \\leq v_{idx}}\\\\\n      H_1 & \\owc\\\\\n    \\end{array}\n  \\right.\n}\\\\\n\\\\\n\\I _{cp}\\lbr e_1\\TT{[}``length\"\\TT{]}\\TT{=}e_2 \\rbr(H,A)\n = (H_2,A) \\quad\\ifc{\\SF{IsArray}(H,l)\\ \\land\\ \\chf{CanPut}(H,l,``length\")\\ \\land\\ n_{newLen} \\geq 0\n}\\\\\n\\quad\\wherec{\n  l=\\V\\lbr e_1\\rbr(H,A)\\\\\n  n_{oldLen}=\\chf{Proto}(H,l,``length\") \\\\\n  n_{newLen}=\\chf{toNumber}(\\V\\lbr e_2\\rbr(H,A))\\\\\n  H_1=H[l\\mapsto H(l)[``length\"\\mapsto H(l)(``length\") \\SF{ with } value=n_{newLen}]]\\\\\n  H_2= \\left\\{\n    \\begin{array}{ll}\n      \\bigsqcup_{x=n_{oldLen}-1\\textrm{ to }n_{newLen}}\\chf{Delete}(H_1,l,x)\n      & \\ifc{n_{newLen} < n_{oldLen}} \\\\\n      H_1 & \\owc \\\\\n    \\end{array}\n  \\right.\n}\\\\\n\\I _{cp}\\lbr e_1\\TT{[}``length\"\\TT{]}\\TT{=}e_2 \\rbr(H,A)\n = (H_1, A) \\quad\\ifc{\\SF{IsArray}(H,l)\\\\\\land\\ \\left(n_{newLen} < 0 \\lor n_{newLen} \\in \\set{\\SF{NaN},\\SF{Inf}, -\\SF{Inf}}\\right )}\\\\\n\\quad\\wherec{\n  l=\\V\\lbr e_1\\rbr(H,A)\\\\\n  n_{newLen}=\\chf{toNumber}(\\V\\lbr e_2\\rbr(H,A))\\\\\n  H_1=\\chf{RaiseException}(H,\\exc{RangeError})\n}\\\\\n\\\\\n\\I _{cp}\\lbr e_1\\TT{[}e_2\\TT{]}\\TT{=}e_3 \\rbr(H,A)\n = (H,A)\\quad\\ifc{\\lnot\\chf{CanPut}(H,l,x)\\ \\land\\ v=\\V\\lbr e_3\\rbr(H,A)}\\\\\n\\quad\\wherec{\n  l=\\V\\lbr e_1\\rbr(H,A)\\\\\n  x=\\V\\lbr e_2\\rbr(H,A)\\\\\n}\\\\\n\\\\\n % & \\inred \\comment{$\\I e_1[e_2]\\TT{=}e_3 (H,A)\n %   = (H[l'\\mapsto H(l')[v_1\\mapsto v_2]],A)$\n %    where $\\SF{IsArray}(H,l') \\land l'=..., v_1=..., v_2=...$}\n\n% x_1 ~\\verb+:=+~ \\SF{function}~x_2\\verb+(+fid\\verb+)+\n\\I_{cp}\\lbr x_1\\TT{:=}\\TT{function}~x_2^{?}\\TT{(}fid\\TT{)}\\rbr(H,A)\n = \\left(H_1\n    \\left[\n       \\begin{array}{l}\n        l_{new1}\\mapsto\\chf{NewFunctionObject}(fid,A_1,l_{new2},n), \\\\\n         l_{new2}\\mapsto o_{new}\n         \\left[``constructor\"\\mapsto \n             \\set{\n                 value=l_{new1};\\\\\n                 writable=\\vtrue;\\\\\n                 enumerable=\\vfalse;\\\\\n                 configurable=\\vtrue\n            }\n             \\right]\n       \\end{array}\n     \\right],A_1\n   \\right) \\\\\n\\quad\\wherec{l=\\chf{TopStack}(A)\\ \\land\\ l_{new1}=\\chf{newLocation}() \\land l_{new2}=\\chf{newLocation}() \\land l_{new3}=\\chf{newLocation}() \\\\\n  H_1=\\chf{VarStoreE}(H,A,x_1,l_{new1},\\vtrue)\\\\\n  \\land\\ o_{new}=\\chf{NewObject}(\\varloc{ObjProto})\\\\\n  \\land\\ l_{new3}=\\set{x_2\\mapsto \\set{value=l_{new1};writable=\\vfalse;enumerable=\\vfalse;configurable=\\vfalse}}\\\\\n  \\land\\ A_1 = \\chf{PushStack}(A,l_{new3}) \\\\\n  \\land\\ n=|\\chf{getArgVars}_{P}(fid)|\n}\n\\\\\\\\\n\\end{array}\n\\]\n\\[\n\\begin{array}{ll}\n\n% \\SF{construct}\\verb+(+e_1,e_2,e_3\\verb+)+\n\\I _{cp}\\lbr \\TT{construct}\\TT{(}e_1,e_2,e_3\\TT{)} \\rbr(H,A)\n = \\left(H\\left[\n      \\begin{array}{l}\n       l_{arg}\\mapsto\n           H(l_{arg})\\left[\n             callee \\mapsto\n               \\set{\n                 value=l_{fun};\\\\\n                 writable=\\vtrue;\\\\\n                 enumerable=\\vfalse;\\\\\n                 configurable=\\vtrue}\n           \\right],\n       \\\\\n       l_{new}\\mapsto \\set{\n            arguments \\mapsto\n              \\set{\n                value=v_{arg};\\\\\n                writable=\\vtrue;\\\\\n                enumerable=\\vfalse;\\\\\n                configurable=\\vfalse},\\\\\n            \\varprop{this}\\mapsto value=l_{this},\\\\\n            \\varprop{up}\\mapsto A,\\\\\n            \\varprop{return}\\mapsto H(\\varloc{temp})(\\varprop{return}),\\\\\n          }\n      \\end{array}\n    \\right], A_1\\right) \\\\\n\\quad\\wherec{\n\n\\chf{HasConstruct}(H,\\V\\lbr e_1\\rbr(H,A)) \\land A_1=\\chf{PushStack}(\\V\\lbr\n  e_1\\TT{[}\\varprop{scope}\\TT{]}\\rbr(H,A),l_{new}) \\\\\n  \\land\\ l = \\V\\lbr e_1\\rbr(H,A) \\\\\n  \\land\\ arguments = \\chf{getArgumentsName}_{P}(fid_{callee}) \\\\\n  \\land\\ v_{arg} = \\V\\lbr e_3\\rbr(H,A) \\\\\n  \\land\\ l_{this} = \\chf{getThis}(\\V\\lbr e_2\\rbr(H,A)) \\\\\n  \\land\\ l_{new}=\\chf{newLocation}()\\ \\land fid_{callee}=\\V\\lbr e_1\\TT{[}\\varprop{construct}\\TT{]}\\rbr(H,A)\\\\\n  \\land\\ cp_{\\textit{after-call}} = \\chf{getAftercallFromCall}_P(cp) \\\\\n  \\land\\ {\\inblue \\cfgnext} :=\n  {\\inblue \\cfgnext}\\cup\\set{( cp,(fid_{callee},\\SF{ENTRY})),\n    ((fid_{callee},\\SF{EXIT}), cp_{\\textit{after-call}})}\\\\\n  \\land\\ {\\inblue \\excnext}:={\\inblue \\excnext}\n  \\cup\\set{((fid_{callee},\\SF{EXIT-EXC}), cp_{\\textit{after-call}})}\\\\\n  \\land\\ \\chf{BelongsTo}:=\\chf{BelongsTo}\\cup\\set{(l_{new},cp)}\n} \\\\\n\\\\\n\\I _{cp}\\lbr \\TT{construct}\\TT{(}e_1,e_2,e_3\\TT{)} \\rbr(H,A)\n = (H_1, A) \\quad\\ifc{\\lnot\\chf{HasConstruct}(H,v) \\lor\\ v\\not\\in\\SF{Loc}}\\\\\n\\quad\\wherec{\n  v=\\V\\lbr e_1\\rbr(H,A)\\\\\n  H_1=\\chf{RaiseException}(H,\\exc{TypeError})\n} \\\\\n\\I _{cp}\\lbr \\TT{construct}\\TT{(}e_1,e_2,e_3\\TT{)} \\rbr(H,A)\n = (H_1, A) \\quad\\ifc{exc=\\V\\lbr e_1\\rbr(H,A)}\\\\\n\\quad\\wherec{\n  H_1=\\chf{RaiseException}(H,exc)\n} \\\\\\\\\n\n% \\SF{call}\\verb+(+e_1,e_2,e_3\\verb+)+\n\\I _{cp}\\lbr \\TT{call}\\TT{(}e_1,e_2,e_3\\TT{)} \\rbr(H,A)\n = \\left(H\\left[\n      \\begin{array}{l}\n       l_{arg}\\mapsto\n            H(l_{arg})\\left[\n              callee \\mapsto\n                \\set{\n                  value=l_{fun};\\\\\n                  writable=\\vtrue;\\\\\n                  enumerable=\\vfalse;\\\\\n                  configurable=\\vtrue}\n            \\right], \n       \\\\\n       l_{new}\\mapsto \\set{\n            arguments \\mapsto\n              \\set{\n                value=l_{arg};\\\\\n                writable=\\vtrue;\\\\\n                enumerable=\\vfalse;\\\\\n                configurable=\\vfalse},\\\\\n            \\varprop{this}\\mapsto value=l_{this},\\\\\n            \\varprop{up}\\mapsto A,\\\\\n            \\varprop{return}\\mapsto H(\\varloc{temp})(\\varprop{return}),\\\\\n          }\n      \\end{array}\n    \\right], A_1\\right) \\\\\n\\quad\\wherec{\n  l_{fun} = \\V\\lbr e_1\\rbr(H,A) \\land\\ \\chf{IsCallable}(H,l_{fun}) \\land A_1=\\chf{PushStack}(\\V\\lbr\n  e_1\\TT{[}\\varprop{scope}\\TT{]}\\rbr(H,A),l_{new}) \\\\\n  \\land\\ arguments = \\chf{getArgumentsName}_{P}(fid_{callee}) \\\\\n  \\land\\ l_{arg} = \\V\\lbr e_3\\rbr(H,A) \\\\\n  \\land\\ l_{this} = \\chf{getThis}(\\V\\lbr e_2\\rbr(H,A)) \\\\\n  \\land\\ l_{new}=\\chf{newLocation}()\\ \\land fid_{callee}=\\V\\lbr e_1\\TT{[}\\varprop{function}\\TT{]}\\rbr(H,A)\\\\\n%  \\land\\ (cp,cp_{\\textit{after-call}})\\in\\mathbb{A}  \\\\\n  \\land\\ cp_{\\textit{after-call}} = \\chf{getAftercallFromCall}_P(cp) \\\\\n  \\land\\ {\\inblue \\cfgnext} :=\n  {\\inblue \\cfgnext}\\cup\\set{( cp,(fid_{callee},\\SF{ENTRY})),\n    ((fid_{callee},\\SF{EXIT}), cp_{\\textit{after-call}})}\\\\\n  \\land\\ {\\inblue \\excnext}:={\\inblue \\excnext}\n  \\cup\\set{((fid_{callee},\\SF{EXIT-EXC}), cp_{\\textit{after-call}})}\\\\\n  \\land\\ \\chf{BelongsTo}:=\\chf{BelongsTo}\\cup\\set{(l_{new},cp)}\n} \\\\\n\\\\\n\\I _{cp}\\lbr \\TT{call}\\TT{(}e_1,e_2,e_3\\TT{)} \\rbr(H,A)\n = (H_1, A) \\quad\\ifc{\\lnot\\chf{IsCallable}(H,v) \\lor\\ v\\not\\in\\SF{Loc}}\\\\\n\\quad\\wherec{\n  v=\\V\\lbr e_1\\rbr(H,A)\\\\\n  H_1=\\chf{RaiseException}(H,\\exc{TypeError})\n} \\\\\n\\I _{cp}\\lbr \\TT{call}\\TT{(}e_1,e_2,e_3\\TT{)} \\rbr(H,A)\n = (H_1, A) \\quad\\ifc{exc=\\V\\lbr e_1\\rbr(H,A)}\\\\\n\\quad\\wherec{\n  H_1=\\chf{RaiseException}(H,exc)\n} \\\\\\\\\n\\end{array}\n\\]\n\\[\n\\begin{array}{ll}\n% \\SF{after-call}\\verb+(+x\\verb+)+\n\\I _{cp}\\lbr \\TT{after-call}\\TT{(}x\\TT{)} \\rbr(H,A)\n = \\SF{stuck}\\quad\\ifc{\\lnot\\chf{BelongsTo}(l,cp_{call})}\\\\\n\\quad\\wherec{\n  l = \\chf{TopStack}(A)\\\\\n  cp_{call} = \\chf{getCallFromAfterCall}_P(cp) \n}\n\\\\\n\\I _{cp}\\lbr \\TT{after-call}\\TT{(}x\\TT{)} \\rbr(H,A)\n = (H_2,A_1)\\quad\\ifc{\\chf{BelongsTo}(l,cp_{call})}\\\\\n\\quad\\wherec{\n  l = \\chf{TopStack}(A)\\\\\n  cp_{call} = \\chf{getCallFromAfterCall}_P(cp) \\\\\n  A_1=H(l)(\\varprop{up})\\\\\n  H_1=\\chf{VarStoreE}(H,A_1,x,H(\\varloc{temp})(\\varprop{return}),\\vtrue)\\\\\n  H_2 = H_1[\\varloc{temp}\\mapsto H_1(\\varloc{temp})[\\varprop{return}\\mapsto H(l)(\\varprop{return})]] \\\\\n}\n\\\\\\\\\n\n% \\SF{assert}\\verb+(+e\\inop e\\verb+)+ \n\\I _{cp}\\lbr \\TT{assert}\\TT{(}e_1\\inop e_2\\TT{)} \\rbr(H,A)\n = \\B\\lbr e_1\\inop e_2\\rbr(H,A)\n\\\\\\\\\n\n% \\SF{catch}\\verb+(+x\\verb+)+\n\\I _{cp}\\lbr \\TT{catch}\\TT{(}x\\TT{)} \\rbr(H,A)\n = (H_2,A)\\\\\n\\quad\\wherec{\n  H_1 = \\chf{VarStore}(H,A,x,H(\\varloc{temp})(\\varprop{exception}),\\vtrue),\\\\\n  H_2 = \\chf{Delete}(H_1,\\varloc{temp},\\varprop{exception})\n} \\\\\n\\\\\n% \\SF{return}\\verb+(+e\\verb+)+ \n\\I _{cp}\\lbr \\TT{return}\\TT{(}e\\TT{)} \\rbr(H,A)\n = (H[\\varloc{temp}\\mapsto H(\\varloc{temp})[\\varprop{return}\\mapsto v]], A)\n\\quad\\ifc{\n  v=\\V\\lbr e\\rbr(H,A)\n}\\\\\n\\I _{cp}\\lbr \\TT{return}\\TT{(}e\\TT{)} \\rbr(H,A)\n = (H_1, A) \\quad\\ifc{exc = \\V\\lbr e\\rbr(H,A)}\\\\\n\\quad\\wherec{\n  H_1=\\chf{RaiseException}(H,exc)\n}\n\\\\\\\\\n\\I _{cp}\\lbr \\TT{return}\\TT{()} \\rbr(H,A)\n = (H[\\varloc{temp}\\mapsto H(\\varloc{temp})[\\varprop{return}\\mapsto \\SF{undefined}]], A)\n\\\\\\\\\n\n% \\SF{throw}\\verb+(+e\\verb+)+\n\\I _{cp}\\lbr \\TT{throw}\\TT{(}e\\TT{)} \\rbr(H,A)\n   = (H_2, A)\\\\\n\\quad\\wherec{\n  H_1=\\chf{RaiseException}(H,\\V\\lbr e\\rbr(H,A)), \\\\\n  \\land\\ H_2=H_1[\\varloc{temp}\\mapsto H_1(\\varloc{temp})[\\varprop{return}\\mapsto \\SF{undefined}]]\n}\\\\\n\\\\\n\n% Exception\n% \\I _{cp}\\lbr x \\TT{:=} \\chfi{toObject}\\TT{(}e\\TT{)} \\rbr(H,A)\n%  = (H[\\varloc{temp}\\mapsto H(\\varloc{temp})[\\varprop{exception}\\mapsto \\SF{TypeError}]], A) \\\\\n%  \\quad\\ifc{\\V\\lbr e\\rbr(H,A) = \\SF{undefined}\\lor \\V\\lbr e\\rbr(H,A) = \\SF{null}}\\\\\n\\I _{cp}\\lbr x \\TT{:=} \\chfi{toObject}\\TT{(}e\\TT{)} \\rbr(H,A)\n = (H_2,A)\\quad\\ifc{v = \\V\\lbr e\\rbr(H,A)\\ \\land\\ (H_1, l_{new}) = \\chf{toObject}(H, v)}\\\\\n \\quad\\wherec{\n   H_2=\\chf{VarStoreE}(H_1,A,x,l_{new},\\SF{true})\n}\\\\\n\\I _{cp}\\lbr x \\TT{:=} \\chfi{toObject}\\TT{(}e\\TT{)} \\rbr(H,A)\n = (H_1, A)\\quad\\ifc{v = \\V\\lbr e\\rbr(H,A)\\ \\land\\ (\\_, exc) = \\chf{toObject}(H, v)}\\\\\n \\quad\\wherec{\n   H_1=\\chf{RaiseException}(H,exc)\n}\\\\\n\\I _{cp}\\lbr x \\TT{:=} \\chfi{toObject}\\TT{(}e\\TT{)} \\rbr(H,A)\n = (H_1, A)\\quad\\ifc{exc = \\V\\lbr e\\rbr(H,A)}\\\\\n\\quad\\wherec{\n  H_1=\\chf{RaiseException}(H, exc)\n}\n\\\\\\\\\n\\I _{cp}\\lbr x \\TT{:=} \\chfi{isObject}\\TT{(}e\\TT{)} \\rbr(H,A)\n = (H_1,A)\\quad\\ifc{l = \\V\\lbr e\\rbr(H,A)}\\\\\n\\quad\\wherec{\n  H_1=\\chf{VarStoreE}(H,A,x,\\vtrue,\\SF{true})\n}\\\\\n\\I _{cp}\\lbr x \\TT{:=} \\chfi{isObject}\\TT{(}e\\TT{)} \\rbr(H,A)\n = (H_1,A)\\quad\\ifc{pv = \\V\\lbr e\\rbr(H,A)}\\\\\n\\quad\\wherec{\n  H_1 = \\chf{VarStoreE}(H,A,x,\\vfalse,\\SF{true})\n}\\\\\n\\I _{cp}\\lbr x \\TT{:=} \\chfi{isObject}\\TT{(}e\\TT{)} \\rbr(H,A)\n = (H_1, A)\\quad\\ifc{exc = \\V\\lbr e\\rbr(H,A)}\\\\\n\\quad\\wherec{\n  H_1=\\chf{RaiseException}(H,exc)\n}\n\\\\\\\\\n\\I _{cp}\\lbr x \\TT{:=} \\chfi{toString}\\TT{(}e\\TT{)} \\rbr(H,A)\n= (H_1, A)\\quad\\ifc{v = \\V\\lbr e\\rbr(H,A)}\n\\\\\\quad\\wherec{\n  pv=\\chf{toPrimitive}(v)\\\\\n  H_1=\\chf{VarStoreE}(H,A,x,\\chf{toString}(pv),\\vtrue)\\\\\n}\\\\\n\\I _{cp}\\lbr x \\TT{:=} \\chfi{toString}\\TT{(}e\\TT{)} \\rbr(H,A)\n = (H_1, A)\\quad\\ifc{exc = \\V\\lbr e\\rbr(H,A)}\\\\\n\\quad\\wherec{\n  H_1=\\chf{RaiseException}(H,exc)\n}\n\\\\\\\\\n\\end{array}\n\\]\n\\[\n\\begin{array}{ll}\n\n\\I _{cp}\\lbr x \\TT{:=} \\chfi{toNumber}\\TT{(}e\\TT{)} \\rbr(H,A)\n= (H_1, A)\\quad\\ifc{l = \\V\\lbr e\\rbr(H,A)}\n\\\\\\quad\\wherec{\n  pv=\\chf{toPrimitive}(l)\\\\\n  H_1=\\chf{VarStoreE}(H,A,x,\\chf{toNumber}(pv),\\vtrue)\n}\\\\\n\\I _{cp}\\lbr x \\TT{:=} \\chfi{toNumber}\\TT{(}e\\TT{)} \\rbr(H,A)\n= (H_1, A)\\quad\\ifc{pv = \\V\\lbr e\\rbr(H,A)}\n\\\\\\quad\\wherec{\n  H_1=\\chf{VarStoreE}(H,A,x,\\chf{toNumber}(pv),\\vtrue)\n}\\\\\n\\I _{cp}\\lbr x \\TT{:=} \\chfi{toNumber}\\TT{(}e\\TT{)} \\rbr(H,A)\n = (H_1, A)\\quad\\ifc{exc = \\V\\lbr e\\rbr(H,A)} \\\\\n\\quad\\wherec{\n  H_1=\\chf{RaiseException}(H,exc)\n}\n\\\\\\\\\n\n\\I _{cp}\\lbr x \\TT{:=} \\chfi{toBoolean}\\TT{(}e\\TT{)} \\rbr(H,A)\n= (H_1, A)\\quad\\ifc{v = \\V\\lbr e\\rbr(H,A)}\n\\\\\\quad\\wherec{\n  H_1=\\chf{VarStoreE}(H,A,x,\\chf{toBoolean}(v),\\vtrue)\n}\\\\\n\\I _{cp}\\lbr x \\TT{:=} \\chfi{toBoolean}\\TT{(}e\\TT{)} \\rbr(H,A)\n = (H_1, A)\\quad\\ifc{exc = \\V\\lbr e\\rbr(H,A)} \\\\\n\\quad\\wherec{\n  H_1=\\chf{RaiseException}(H,exc)\n}\n\\\\\\\\\n\n\\I _{cp}\\lbr x_1 \\TT{:=} \\chfi{getBase}\\TT{(}x_2\\TT{)} \\rbr(H,A)\n = (H_1,A) \\\\\n\\quad\\wherec{\n  l_{base}=\\chf{LookupBase}(H,A,x_2)\\\\\n  H_1=\\chf{VarStoreE}(H,A,x_1,l_{base},\\vtrue)\n}\n\\\\\\\\\n\n\\I _{cp}\\lbr x \\TT{:=} \\chfi{iteratorInit}\\TT{(}e\\TT{)} \\rbr(H,A)\n = (H_2,A) \\\\\n  \\quad\\wherec{\n  l = \\V\\lbr e\\rbr(H,A) \\\\\n  P = \\chf{collectProps}(H,l) \\\\\n  o_{new} = \\chf{iteratorInit}(H(l), P, 0) \\\\\n  l_{new} = \\chf{newLocation}() \\\\\n  H_1 = H[l_{new}\\mapsto o_{new}] \\\\\n  H_2 = \\chf{VarStoreE}(H_1,A,x,l_{new},\\vtrue)\n  }\n\\\\\\\\\n\n\\I _{cp}\\lbr x_1 \\TT{:=} \\chfi{iteratorHasNext}\\TT{(}e,x_2\\TT{)} \\rbr(H,A)\n = (H_1,A) \\\\\n\\quad\\wherec{\n  l_1 = \\V\\lbr x_2\\rbr (H,A)\\\\\n  l_2 = \\V\\lbr e\\rbr (H,A)\\\\\n  i=\\chf{next}(H,H(l_1),H(l_1)(\\varprop{i}),l_2) \\\\\n  b=\\left\\{\n    \\begin{array}{ll}\n      \\vtrue & \\ifc{i\\in \\chf{Dom}(H(l_1))} \\\\\n      \\vfalse & \\owc\n    \\end{array}\n  \\right.\\\\\n  H_1=\\chf{VarStoreE}(H,A,x_1,b,\\vtrue)\n}\n\\\\\\\\\n\\I _{cp}\\lbr x_1 \\TT{:=} \\chfi{iteratorNext}\\TT{(}e,x_2\\TT{)} \\rbr(H,A)\n = (H_2,A) \\\\\n \\quad\\wherec{\n  l_1 = \\V\\lbr x_2\\rbr (H,A)\\\\\n  l_2 = \\V\\lbr e\\rbr (H,A)\\\\\n  i=\\chf{next}(H,H(l_1),H(l_1)(\\varprop{i}),l_2) \\\\\n  v=H(l_1)(\\chf{toString}(i))) \\\\\n  H_1 = H[l_1\\mapsto H(l_1)[\\varprop{i}\\mapsto i+1]] \\\\\n  H_2=\\chf{VarStoreE}(H_1,A,x_1,v,\\vtrue)\n}\n\\\\\\\\\n\n% x\n\\V\\lbr x \\rbr(H,A) = \\chf{Lookup}(H,A,x)\\\\\n\\\\\n\n% e \\inop e \n\\V\\lbr e_1\\inop e_2 \\rbr(H,A)\n   = v_1\\inop v_2 \n\\quad\\ifc{\n  v_1 = \\V\\lbr e_1\\rbr(H,A)\\land\\ v_2 = \\V\\lbr e_2\\rbr(H,A)\n}\n\\\\\n\\V\\lbr e_1\\inop e_2 \\rbr(H,A)\n   = exc\n\\quad\\ifc{\n  exc = \\V\\lbr e_1\\rbr(H,A)\n}\n\\\\\n\\V\\lbr e_1\\inop e_2 \\rbr(H,A)\n   = exc\n\\quad\\ifc{\n  v=\\V\\lbr e_1\\rbr(H,A)\n  \\land\\ exc=\\V\\lbr e_2\\rbr(H,A)\n}\n\\\\\\\\\n\n% \\preop e\n\\V\\lbr\\preop e \\rbr(H,A)\n   = \\preop v\n\\quad\\ifc{\n  v = \\V\\lbr e\\rbr(H,A)\n}\n\\\\\n\\V\\lbr\\preop e \\rbr(H,A)\n  = exc\n\\quad\\ifc{\n  exc=\\V\\lbr e\\rbr(H,A)\n}\n\\\\\\\\\n\n% e\\verb+[+e\\verb+]+\n\\V\\lbr e_1\\TT{[}e_2\\TT{]} \\rbr(H,A)\n   = v \\quad \\wherec{l = \\V\\lbr e_1\\rbr(H,A)\\land s = \\V\\lbr e_2\\rbr(H,A)\\land v=\\chf{Proto}(H,l,s)}\n\\\\\\\\\n\n\\V\\lbr \\TT{n} \\rbr(H,A) = n\\\\\\\\\n\n\\V\\lbr ``\\TT{s}\" \\rbr(H,A) = s\\\\\\\\\n\\end{array}\n\\]\n\\[\n\\begin{array}{ll}\n\n\\V\\lbr \\TT{true} \\rbr(H,A) = \\vtrue\\\\\\\\\n\n\\V\\lbr \\TT{false} \\rbr(H,A) = \\vfalse\\\\\\\\\n\n\\V\\lbr\\TT{null}\\rbr (H,A) = \\SF{null}\\\\\\\\\n\n\\V\\lbr \\TT{this}\\rbr (H,A) = l_{this} \\quad\\wherec{l_{this} = H(l)(\\varprop{this})\\land l = \\chf{TopStack}(A)} \\\\\\\\\n\n\\V\\lbr e_1\\,\\TT{instanceof}\\,e_2 \\rbr (H,A) = \\chf{inherit}(H,H(l_1)(\\varprop{proto}),l_3) \\\\\n\\quad\\wherec{\n  \\chf{HasConstruct}(H,l_2) \\\\\n  \\land\\ l_1 = \\V\\lbr e_1 \\rbr (H,A)\n  \\land\\ l_2 = \\V\\lbr e_2 \\rbr (H,A) \\\\\n  \\land\\ l_3 = \\chf{Proto}(H,l_2,``prototype\")\n}\n\\\\\n\\V\\lbr e_1\\,\\TT{instanceof}\\,e_2 \\rbr (H,A) = \\vfalse \\\\\n\\quad\\wherec{\n  \\chf{HasConstruct}(H,l_2) \\\\\n  \\land\\ \\V\\lbr e_1 \\rbr (H,A)\\in\\SF{PValue}\n  \\land\\ l_2 = \\V\\lbr e_2 \\rbr (H,A) \\\\\n}\n\\\\\n\\V\\lbr e_1\\,\\TT{instanceof}\\,e_2 \\rbr (H,A)\n = \\exc{TypeError} \\\\\n\\quad\\wherec{\n  \\V\\lbr e_2\\rbr (H,A)\\in\\SF{PValue}\n  \\lor\\ \n  \\left(\\lnot\\chf{HasConstruct}(H,l_2) \\land l_2 = \\V\\lbr e_2 \\rbr (H,A)\\right)\n}\n\\\\\n\\V\\lbr e_1\\,\\TT{instanceof}\\,e_2 \\rbr (H,A)\n = \\exc{TypeError} \\\\\n\\quad\\wherec{\n  \\chf{HasConstruct}(H,l_2)\n  \\land\\ l_2 = \\V\\lbr e_2 \\rbr (H,A)\n  \\land\\ \\chf{Proto}(H,l_2,``prototype\")\\in\\SF{PValue}\n}\n\\\\\n\\V\\lbr e_1\\,\\TT{instanceof}\\,e_2 \\rbr (H,A)\n = exc\\\\\n\\quad\\wherec{\n  exc=\\V\\lbr e_1\\rbr(H,A) \\in \\SF{Exception}\n}\n\\\\\n\\V\\lbr e_1\\,\\TT{instanceof}\\,e_2 \\rbr (H,A)\n = exc\\\\\n\\quad\\wherec{\n  v=\\V\\lbr e_1\\rbr(H,A)\n  \\ \\land\\ exc=\\V\\lbr e_2\\rbr(H,A) \\in \\SF{Exception}\n}\n\\\\\\\\\n\\V\\lbr e_1\\,\\TT{in}\\,e_2 \\rbr (H,A)= \\chf{HasProperty}(H,l,x)\\\\\n\\quad\\wherec{\n  v = \\V\\lbr e_1\\rbr(H,A)\n  \\land\\ l = \\V\\lbr e_2\\rbr(H,A) \\\\\n  \\land\\ x = \\chf{toString}(\\chf{toPrimitive}(v))\n}\n\\\\\n\\V\\lbr e_1\\,\\TT{in}\\,e_2 \\rbr (H,A)\n = \\exc{TypeError} \\\\\n\\quad\\wherec{\n  \\V\\lbr e_1\\rbr(H,A) \\in \\SF{Value}\n  \\land\\ \\V\\lbr e_2\\rbr(H,A)\\in\\SF{PValue}\n}\n\\\\\n\\V\\lbr e_1\\,\\TT{in}\\,e_2 \\rbr (H,A)\n = \\V\\lbr e_1\\rbr(H,A) \\\\\n\\quad\\wherec{\n  \\V\\lbr e_1\\rbr(H,A)\\in\\SF{Exception}\n}\n\\\\\n\\V\\lbr e_1\\,\\TT{in}\\,e_2 \\rbr (H,A)\n = exc\\\\\n\\quad\\wherec{\n  v=\\V\\lbr e_1\\rbr(H,A)\n  \\ \\land\\ exc=\\V\\lbr e_2\\rbr(H,A)\n}\n\\\\\\\\\n\\V\\lbr \\TT{typeof}\\,e \\rbr (H,A) = \\chf{TypeTag}(H,v)\\quad\\ifc{v=\\V\\lbr e\\rbr(H,A)}\n\\\\\n\\V\\lbr \\TT{typeof}\\,e \\rbr (H,A)\n = exc\n\\quad\\ifc{\n  exc=\\V\\lbr e\\rbr(H,A)\n}\n\\\\\\\\\n\n\\B \\lbr e \\rbr(H,A)\n = S \\\\\n\\quad\\wherec{\n  \\V \\lbr e \\rbr(H, A) = v\\\\\n  S=\\left\\{\n    \\begin{array}{ll}\n      (H, A) & \\chf{toBoolean}(v) = \\vtrue \\\\\n      {\\sf stuck} & \\chf{toBoolean}(v) = \\vfalse \\\\\n    \\end{array}\n  \\right.\n}\n\\\\\n\\B \\lbr e \\rbr(H,A) \n = (H_1[\\#temp \\mapsto H_1(\\#temp)[@exception \\mapsto l_e]], A) \\\\\n\\quad\\wherec{\n   \\V \\lbr e \\rbr(H, A) = exc \\\\\n   l_e = \\chf{newLocation}() \\\\\n   H_1=H[l_e\\mapsto\\chf{NewExceptionObject}(exc)] \\\\\n}\n\\\\\\\\\n\\end{array}\n\\]\n\\[\n\\begin{array}{l@{~~}r@{~~}ll}\n\n \\preop & ::= & \\SF{void}\n% \\mid \\SF{typeof}\n \\mid \\TT{+} \\mid \\TT{-} \\mid \\TT{\\~} \\mid \\TT{!} \\\\\n \\inop & ::= &\n% \\SF{instanceof} \\mid \n% \\SF{in} \\mid \n \\TT{|} \\mid \\TT{\\&} \n               \\mid \\TT{\\^} \\mid \\TT{<<} \\mid \\TT{>>} \\mid \\TT{>>>} \\\\\n& & \\mid \\TT{+} \\mid \\TT{-} \\mid \\TT{*} \\mid \\TT{/} \\mid \\TT{\\%} \\mid \\TT{==} \\mid \\TT{!=} \n               \\mid \\TT{===} \\mid \\TT{!==} \\mid \\TT{<} \\mid \\TT{>} \\mid \\TT{<=} \\mid \\TT{>=} \\\\\n\n\\end{array}\n\\]\n\n We consider the collecting semantics of program $P$ that is characterized by an\n invariant $\\lbr P\\rbr \\in \\controlpoint \\rightarrow \\powerset{\\SF{State}}$,\n collecting a set of reachable states at each control point.\n The collecting semantics is defined by the least fixpoint of composition of \n semantic functions\n $F_{\\textit{control-flow}},F_{\\textit{exception-flow}}\\in (\\controlpoint\\rightarrow \\powerset{\\SF{State}})\\rightarrow (\\controlpoint\\rightarrow \\powerset{\\SF{State}}))$\n such that,\n\\[\n\\begin{array}{l@{~}l@{}}\n\\chf{ExcFlow}(S) & = \\set{(H,A)\\mid \\SF{stuck}\\neq(H,A)\\in S \\land \\chf{HasProperty}(H,\\varloc{temp},\\varprop{exception})} \\\\\n\\chf{NormalFlow}(S) & = \\set{(H,A)\\mid \\SF{stuck}\\neq(H,A)\\in S \\land \\lnot \\chf{HasProperty}(H,\\varloc{temp},\\varprop{exception})} \\\\\nf_{cp} & = \\N_{cp}(\\chf{getCmd}_P(cp)) \\\\\nF_{\\textit{control-flow}}(X)&=\\lambda cp\\in\\controlpoint. \\bigcup_{cp'\\cfgnext cp}f_{cp'}\\left(\\chf{NormalFlow}(X(cp'))\\right). \\\\\nF_{\\textit{exception-flow}}(X)&=\\lambda cp\\in\\controlpoint. \\bigcup_{cp'\\excnext cp}f_{cp'}\\left(\\chf{ExcFlow}(X(cp'))\\right). \\\\\nF & = F_{\\textit{control-flow}} \\circ F_{\\textit{exception-flow}}\n\\end{array}\n\\]\n\n\\newpage\n\\chapter{CFG Abstract Semantics}\n{\\inblue\\tt .../jsaf/analysis/typing/\\{package, Config\\}.scala}\\\\\n\nAssumptions and limitations are as follows:\n\\begin{itemize}\n  \\item When a value is updated, a part of $\\abs{PropValue}$ type value is directly used instead of $\\abs{PropValue}\\times\\abs{Absent}$. In this case, the $\\abs{Absent}$ value and the rest parts of $\\abs{PropValue}$ is considered as $\\bot$.\\\\ e.g.) $x\\mapsto \\langle\\hat{v},\\afalse,\\afalse\\,\\afalse\\rangle$ means $x\\mapsto \\langle\\langle\\langle\\hat{v},\\afalse,\\afalse\\,\\afalse\\rangle,\\bot_{Value},\\bot_{FunctionId}\\rangle,\\bot_{Absent}\\rangle$.\n\n%  \\item All the update operation for heap space is a weak update.\n  \\item Semantics for helper functions is not written using denotational semantics(they are not compositional).\n  \\item For appropriate type conversion, a subscript is used. In this case, all the implicit values can be\n    considered as $\\bot$.\n  \\item We maintain mutable inter-procedural edge set ($\\ipnext$) throughout semantics.\n\\end{itemize}\n\n\n\\newpage\n\\section{Settings}\n{\\inblue\\tt .../jsaf/analysis/typing/domain/\\{package, AbsDomain, DomainPrinter\\}.scala}\\footnote{\nAmong the $\\abs{IROP}$ operators, we handle only $==$, $!=$, $===$, and $!==$\nfor now as the $\\ahf{K}$ function describes in Section~\\ref{sec:abs-helper}.}\\\\\n\\[\n\\begin{array}{rlcl}\n% (\\hat{H}) \\in & \\abs{States} & = & \\aHeap \\\\\n\\acp \\in & \\aControlPoint & = & \\SF{Node} \\times \\abs{CallContext} \\\\\n\\hat{cc} \\in & \\abs{CallContext} &  & \\comment{\\inblue  Parameterized context-sensitivity. See Section~\\ref{sec:context-sensitivity}} \\\\ \n\\hat{S}, (\\hat{H},\\hat{C}) \\in & \\aState & = & \\aHeap \\times \\abs{Context}\\\\\n\\hat{H} \\in & \\aHeap & = & \\aLoc \\finto \\aObj \\\\\n\\hat{C} \\in & \\abs{Context} & = & {\\inred \\powerset{\\aLoc}} \\times {\\inred \\powerset{\\aLoc}} \\times \\powerset{\\abs{Address}} \\times \\powerset{\\abs{Address}} \\\\\n            &               &   & \\comment{\\inblue {\\inred variable environment,\\ this (moved to \\#PureLocal)},\\ may old,\\ must old} \\\\\n\\hat{l}_R,\\hat{l}_O,\\hat{l} \\in & \\aLoc &  = & \\abs{Address} \\times \\abs{RecencyTag}\\\\\n\\hat{a} \\in & \\abs{Address} & ::= & \\avarloc{Global} ~\\mid~ \n                           \\avarloc{StringProto} ~\\mid~ \n                           \\avarloc{BooleanProto} ~\\mid~ \n                           \\avarloc{FunctionProto} \\\\\n                    & & & ~\\mid~ \n                           \\avarloc{RefErr} ~\\mid~ \n                           \\avarloc{RangeErr} ~\\mid~ \n                           \\avarloc{TypeErr} ~\\mid~ \n                           \\avarloc{RefErrProto}  \\\\\n                    & & & ~\\mid~ \n                           \\avarloc{RangeErrProto} ~\\mid~ \n                           \\avarloc{ArrayProto} ~\\mid~ \n                           \\avarloc{TypeErrProto} \\\\\n                    & & & ~\\mid~ \n                           \\avarloc{ObjProto} ~\\mid~ \n                           \\avarloc{PureLocal} ~\\mid~ \n                           \\avarloc{GlobalCallsite} ~\\mid~ \n                           \\avarloc{Collapsed} \\\\\n                    & & & ~\\mid~\n                           \\hat{a}_1 ~\\mid~ \\cdots \\\\\n\t\t\t& \\abs{RecencyTag} & ::= & \\hat{Recent} \\mid \\hat{Old}\\\\\n\\hat{o} \\in & \\aObj & = & \\SF{Prop} \\finto \\abs{PropValue} \\times \\abs{Absent}\\\\\n\\hat{propv} \\in & \\abs{PropValue} & = & \\abs{ObjectValue} \\times \\aValue \\times \\powerset{\\fid} \\\\\n\\hat{ov}\\in & \\abs{ObjectValue} & = & \\aValue \\times \\abs{Bool} \\times \\abs{Bool} \\times \\abs{Bool} \\\\\n            &                   &   & {\\inblue value,\\ writable,\\ enumerable,\\ configurable} \\\\\n\\hat{v} \\in & \\aValue & = & \\abs{PValue} \\times \\powerset{\\aLoc} \\\\\n\\hat{pv}\\in & \\abs{PValue} & = & \\abs{Undef} \\times \\abs{Null} \\times \\abs{Bool} \\times \\abs{Number} \\times \\abs{String} \\\\\n\\hat{exc}\\in& \\abs{Exception} & ::= & \\hat{\\exc{Error}} ~\\mid~ \\hat{\\exc{EvalError}} ~\\mid~\n                                      \\hat{\\exc{RangeError}} ~\\mid~ \\hat{\\exc{ReferenceError}} ~\\mid~\n                                      \\hat{\\exc{SyntaxError}} ~\\mid~ \\hat{\\exc{TypeError}} ~\\mid~ \n                                      \\hat{\\exc{URIError}} \\\\\n            & \\abs{IPEdge} & = & \\aControlPoint \\times \\aControlPoint \\times \\abs{Context} \\times \\abs{Obj} \\\\\n\\ipnext \\in & \\powerset{\\abs{IPEdge}} & &\\\\\n\n\npe \\in & \\SF{PrunExpression} & = & \\{x, e_1[ e_2 ]\\}\\\\\nre \\in & \\SF{RelExpr} & = & \\SF{Expression} ~\\rel ~ \\SF{Expression} \\\\\n\\rel \\in & \\SF{IROP} & = & \\SF{IRRelOP} \\cup \\SF{IRObjOP} \\\\\n& \\SF{IRRelOP} & = &  == ~\\mid~ != ~\\mid~ === ~\\mid~ !== ~\\mid~ > ~\\mid~ >= ~\\mid~ < ~\\mid~ <= ~\\mid\\\\\n& \\SF{IRObjOP} & = & \\TT{in} ~\\mid~ \\TT{notIn} ~\\mid~ \\TT{instanceof} ~\\mid~ \\TT{notInstanceof}\\\\\n\n%\\rel \\in & \\abs{IROP} & ::= &  == ~\\mid~ != ~\\mid~ === ~\\mid~ !== ~\\mid~ > ~\\mid~ >= ~\\mid~ < ~\\mid~ <= ~\\mid~ \\TT{in} ~\\mid~ \\TT{instanceof} \\\\\n%\\$e \\in & \\$\\SF{Expression} &  = & \\{x, e_1[ e_2 ]\\}\\\\\n%\\hat{re} \\in & \\abs{Rel} & = & \\SF{Expression}\\ ~\\rel~ \\ \\SF{Expression} \\\\\n\n\n\\end{array}\n\\]\n\n\\[\n\\abs{Undef} =\n\\begin{matrix}\n  \\begin{tikzpicture}\n    \\node (top) at (0,0) {$\\aundef$};\n    \\node (down) at (0,-1.4) {$\\bot_{Undef}$};\n    \\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (top) -- (down);\n  \\end{tikzpicture}\n\\end{matrix}\n\\quad\n\\abs{Null} =\n\\begin{matrix}\n  \\begin{tikzpicture}\n    \\node (top) at (0,0) {$\\anull$};\n    \\node (down) at (0,-1.4) {$\\bot_{Null}$};\n    \\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (top) -- (down);\n  \\end{tikzpicture}\n\\end{matrix}\n\\quad\n\\abs{Bool} =\n\\begin{matrix}\n  \\begin{tikzpicture}\n    \\node (top) at (0,0) {$\\top_{Bool}$};\n    \\node (midleft) at (-0.7,-0.7) {$\\atrue$};\n    \\node (midright) at (0.7,-0.7) {$\\afalse$};\n    \\node (down) at (0,-1.4) {$\\bot_{Bool}$};\n    \\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (top) -- (midleft);\n    \\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (top) -- (midright);\n    \\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (midleft) -- (down);\n    \\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (midright) -- (down);\n  \\end{tikzpicture}\n\\end{matrix}\n\\quad\n\\abs{Absent} =\n\\begin{matrix}\n  \\begin{tikzpicture}\n    \\node (top) at (0,0) {$\\hat{\\SF{absent}}$};\n    \\node (down) at (0,-1.4) {$\\bot_{Absent}$};\n    \\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (top) -- (down);\n  \\end{tikzpicture}\n\\end{matrix}\n\\]\n\\[\n\\abs{Number} = \n\\begin{matrix} \n  \\begin{tikzpicture}\n    % First, locate each of the nodes and name them\n    \\node (top) at (0,0) {$\\top_{Number}$};\n    \\node (upperleft) at (-1.9,-0.7) {$\\hat{\\SF{Inf}}$};\n    \\node (uppercenter) at (0,-0.7) {$\\hat{\\SF{UInt}}$};\n    \\node (upperright) at (2.1,-0.7) {$\\hat{\\SF{NUInt}}$};\n    \\node (lower1) at (-3.0,-1.5) {$\\hat{\\SF{-inf}}$};\n    \\node (lower2) at (-2.2,-1.5) {$\\hat{\\SF{+inf}}$};\n    \\node (lower3) at (-1.2,-1.5) {$\\hat{\\SF{NaN}}$};\n    \\node (lower4) at (-0.4,-1.5) {$\\hat{0}$};\n    \\node (lower5) at (0,-1.5) {$\\hat{1}$};\n    \\node (lower6) at (0.4,-1.5) {...};\n    \\node (lower7) at (1.2,-1.5) {...};\n    \\node (lower8) at (1.8,-1.5) {$\\hat{-42}$};\n    \\node (lower9) at (2.4,-1.5) {$\\hat{1.2}$};\n    \\node (lower10) at (3,-1.5) {...};\n    \\node (down) at (0,-2.4) {$\\bot_{Number}$};\n    % Now draw the lines0\n    \\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (top) -- (upperleft);\n    \\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (top) -- (uppercenter);\n    \\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (top) -- (upperright);\n    \\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (top) -- (lower3);\n    \\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (upperleft) -- (lower1);\n    \\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (upperleft) -- (lower2);\n    \\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (uppercenter) -- (lower4);\n    \\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (uppercenter) -- (lower5);\n    \\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (uppercenter) -- (lower6);\n    \\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (upperright) -- (lower7);\n    \\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (upperright) -- (lower8);\n    \\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (upperright) -- (lower9);\n    \\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (upperright) -- (lower10);\n    \\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (lower1) -- (down);\n    \\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (lower2) -- (down);\n    \\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (lower3) -- (down);\n    \\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (lower4) -- (down);\n    \\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (lower5) -- (down);\n    \\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (lower6) -- (down);\n    \\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (lower7) -- (down);\n    \\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (lower8) -- (down);\n    \\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (lower9) -- (down);\n    \\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (lower10) -- (down);\n  \\end{tikzpicture}\n\\end{matrix}\n\\]\n\\[\n\\abs{String} = \n\t\\begin{matrix} \n\t\t\\begin{tikzpicture}\n\t    % First, locate each of the nodes and name them\n\t    \\node (top) at (0,0) {$\\top_{String}$};\n\t    \\node (upperleft) at (-1,-0.7) {$\\hat{\\SF{NumStr}}$};\n\t    \\node (upperright) at (1,-0.7) {$\\hat{\\SF{OtherStr}}$};\n\t    \\node (lower1) at (-2,-1.5) {$\\hat{``\\SF{NaN}\"}$};\n\t    \\node (lower2) at (-1.2,-1.5) {$\\hat{``1.1\"}$};\n\t    \\node (lower3) at (-0.4,-1.5) {...};\n\t    \\node (lower4) at (0.4,-1.5) {$\\hat{``foo\"}$};\n\t    \\node (lower5) at (1.5,-1.5) {$\\hat{``bar\"}$};\n\t   \t\\node (lower6) at (2.2,-1.5) {...};\n\t    \\node (down) at (0,-2.4) {$\\bot_{String}$};\n\t    % Now draw the lines0\n\t  \t\\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (top) -- (upperleft);\n\t  \t\\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (top) -- (upperright);\n\t  \t\\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (midleft) -- (lower1);\n\t  \t\\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (midleft) -- (lower2);\n\t  \t\\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (midleft) -- (lower3);\n\t  \t\\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (midright) -- (lower4);\n\t  \t\\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (midright) -- (lower5);\n\t  \t\\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (midright) -- (lower6);\n\t  \t\\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (lower1) -- (down);\n\t  \t\\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (lower2) -- (down);\n\t  \t\\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (lower3) -- (down);\n\t  \t\\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (lower4) -- (down);\n\t  \t\\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (lower5) -- (down);\n\t  \t\\draw [black, thick, shorten <= -1pt, shorten >=-1pt] (lower6) -- (down);\n\t\t\\end{tikzpicture}\n\t\\end{matrix}\n\\]\n\n% % States                         \n% \\[\n% \\powerset{\\SF{State}} \\galois{\\alpha_{state}}{\\gamma_{state}} \\abs{State}\n% \\]\n% \\[\n% \\begin{array}{lcl}\n% \\alpha_{state}(S) & = & (\\hat{H})\\\\\n% &&  \\wherec{\n%     \\hat{H} = \\alpha_{Heap}\\left(\\set{H \\mid (H,A)\\in S}\\right) \\\\\n% %    \\hat{AS} = \\bigcup\\set{\\alpha_{Env}(A) \\mid (H,A)\\in S} \\\\\n%   } \\\\\n% \\end{array}\n% \\]\n\n% % Heap\n% \\[\n% \\powerset{\\SF{Heap}} \\galois{\\alpha_{heap}}{\\gamma_{heap}} \\aHeap\n% \\]\n% \\[\n% \\begin{array}{lcl}\n% \\alpha_{heap}(HS) & = & \n% \\lambda \\hat{l}.\\alpha_{Obj}(\\{o~\\mid~ \\hat{l}=\\alpha_{Loc}(l) \\land l\\mapsto o\\in HS \\})\n% \\end{array}\n% \\]\n\n% % Env\n% \\[\n% \\SF{Env} \\galois{\\alpha_{env}}{\\gamma_{env}} \\abs{Env}\n% \\]\n\n% % Obj\n% \\[\n% \\powerset{\\SF{Obj}} \\galois{\\alpha_{Obj}}{\\gamma_{obj}} \\aObj\n% \\]\n\n% % PropValue\n% \\[\n% \\powerset{\\SF{PropValue}} \\galois{\\alpha_{PropValue}}{\\gamma_{PropValue}} \\abs{PropValue}\n% \\]\n\n% % ObjectValue\n% \\[\n% \\powerset{\\SF{ObjectValue}} \\galois{\\alpha_{ObjectValue}}{\\gamma_{ObjectValue}} \\abs{ObjectValue}\n% \\]\n\n% % Value\n% \\[\n% \\powerset{\\Value} \\galois{\\alpha_{Value}}{\\gamma_{Value}} \\aValue\n% \\]\n\n% % PValue\n% \\[\n% \\powerset{\\SF{PValue}} \\galois{\\alpha_{PValue}}{\\gamma_{PValue}} \\abs{PValue}\n% \\]\n\\newpage\n\\section{Domain Operators}\n\\[\n\\begin{array}{ll}\n\\textit{Heap Order} & : \\aHeap \\times \\aHeap \\rightarrow \\SF{Boolean} \\\\\n& \\hat{H}_1 \\sqsubseteq \\hat{H}_2 \\defi dom(\\hat{H}_1) \\subseteq dom(\\hat{H}_2) \n\t\\land \\forall \\hat{l} \\in dom(\\hat{H}_1): \\hat{H}_1(\\hat{l}) \\sqsubseteq \\hat{H}_2(\\hat{l})\\\\\n\\\\\n\n\\textit{Heap Join} & : \\aHeap \\times \\aHeap \\rightarrow \\aHeap \\\\\n& \\hat{H}_1 \\sqcup \\hat{H}_2  \\defi \\forall \\hat{l} \\in dom(\\hat{H}_1) \\cup dom(\\hat{H}_2): \n  \\left\\{\n    \\begin{array}{ll}\n      \\left[\\hat{l} \\mapsto \\hat{H}_1(\\hat{l}) \\sqcup \\hat{H}_2(\\hat{l})\\right] & \\ifc{\\hat{l} \\in dom(\\hat{H}_1)\\land \\hat{l} \\in dom(\\hat{H}_2)}\\\\\n      \\left[\\hat{l} \\mapsto \\hat{H}_2(\\hat{l}) \\right] & \\ifc{\\hat{l} \\not\\in dom(\\hat{H}_1)\\land \\hat{l} \\in dom(\\hat{H}_2)}\\\\\n      \\left[\\hat{l} \\mapsto \\hat{H}_1(\\hat{l}) \\right] & \\ifc{\\hat{l} \\in dom(\\hat{H}_1)\\land \\hat{l} \\not\\in dom(\\hat{H}_2)}\\\\\n    \\end{array}\n  \\right.\\\\\n\\\\\n\n\\textit{Heap Domain In} & : \\aHeap \\times \\aLoc \\rightarrow \\SF{Boolean} \\\\\n& \\hat{l} \\in dom(\\hat{H}) \\defi\n \\left\\{\n   \\begin{array}{ll}\n     \\SF{true}\n     & \\ifc{\\hat{l} \\in \\{ \\hat{l}'\\ |\\ (\\hat{l}', \\hat{o}) \\in \\hat{H}\\}} \\\\\n     \\SF{false}\n     & \\owc \\\\\n   \\end{array}\n \\right.\\\\\n\\\\\n\n& {\\inblue \\textit{Although $\\bot_{Obj}$ is returned for non-existent locations, heap is still partial function.}} \\\\\n\\textit{Heap Lookup} & : \\aHeap \\times \\aLoc \\rightarrow \\aObj \\\\\n& \\hat{H}(\\hat{l}) \\defi\n \\left\\{\n   \\begin{array}{ll}\n      \\hat{o} & \\ifc{(\\hat{l}, \\hat{o}) \\in \\hat{H}} \\\\\n      \\bot_{Obj} & \\owc\n   \\end{array}\n \\right.\\\\\n\\\\\n\n\\textit{Heap Update} & : \\aHeap \\times \\aLoc \\times \\aObj \\rightarrow \\aHeap \\\\\n& \\hat{H}[\\hat{l} \\mapsto \\hat{o}] \\defi\n \\left\\{\n   \\begin{array}{ll}\n      \\{( \\hat{l}, \\hat{o})\\} \\cup (\\hat{H}-\\hat{l})\n      & \\ifc{\\hat{l} = \\hat{l}_R \\land \\hat{o} \\neq \\bot_{Obj}} \\\\\n      \\bot_{Heap} \n      & \\ifc{\\hat{l} = \\hat{l}_R \\land \\hat{o} = \\bot_{Obj}} \\\\\n      \\{( \\hat{l}, \\hat{H}(\\hat{l}) \\sqcup \\hat{o})\\} \\cup (\\hat{H}-\\hat{l})\n      & \\ifc{\\hat{l} = \\hat{l}_O \\land \\hat{H}(\\hat{l}) \\sqcup \\hat{o} \\neq \\bot_{Obj}} \\\\\n      \\bot_{Heap} \n      & \\ifc{\\hat{l} = \\hat{l}_O \\land \\hat{H}(\\hat{l}) \\sqcup \\hat{o} = \\bot_{Obj}} \\\\\n   \\end{array}\n \\right.\\\\\n\\\\\\\\\n\n\n\\textit{Context Order} & : \\abs{Context} \\times \\abs{Context} \\rightarrow \\SF{Boolean} \\\\\n& \\hat{C}_1 \\sqsubseteq \\hat{C}_2 \\defi \n  \\begin{array}[t]{l}\n    \\hat{C}_1.3 \\subseteq \\hat{C}_2.3 ~~ \\land \\\\\n    \\hat{C}_1.4 \\supseteq \\hat{C}_2.4 \\quad\\quad\\comment{{\\inblue order is opposite for must old set}}\n  \\end{array} \\\\\n\\\\\n\n\\textit{Context Join} & : \\abs{Context} \\times \\abs{Context} \\rightarrow \\abs{Context} \\\\\n& \\hat{C}_1 \\sqcup \\hat{C}_2 \\defi \n  \\langle\n    {\\inred \\{ \\}, \\{ \\}},\\ \n    \\hat{C}_1.3 \\cup \\hat{C}_2.3,\\ \n    \\hat{C}_1.4 \\cap \\hat{C}_2.4\n  \\rangle \\\\\n\\\\\\\\\n\n\n\\textit{Obj Order} & : \\aObj \\times \\aObj \\rightarrow \\SF{Boolean} \\\\\n& \\hat{o}_1 \\sqsubseteq \\hat{o}_2 \\defi \\forall x \\in dom(\\hat{o}_1) \\cup dom(\\hat{o}_2): \\hat{o}_1(x) \\sqsubseteq \\hat{o}_2(x)\\\\\n\\\\\n\\textit{Obj Join} & : \\aObj \\times \\aObj \\rightarrow \\aObj \\\\\n& \\hat{o}_1 \\sqcup \\hat{o}_2  \\defi \\forall x \\in dom(\\hat{o}_1) \\cup dom(\\hat{o}_2): \\left[x \\mapsto \\hat{o}_1(x) \\sqcup \\hat{o}_2(x)\\right]\\\\\n\\\\\n\n\\textit{Obj Domain In} & : \\aObj \\times \\abs{String} \\rightarrow \\abs{Bool} \\\\\n& \\hat{s} \\dot{\\in} dom(\\hat{o}) \\defi\n     \\left\\{\n       \\begin{array}{ll}\n         x \\dot{\\in} dom(\\hat{o})\n         & \\ifc{\\hat{o} \\neq \\bot_{Obj} \\land \\hat{s} = \\hat{\\SF{NumStrSingle}}(x) }\\\\\n         x \\dot{\\in} dom(\\hat{o})\n         & \\ifc{\\hat{o} \\neq \\bot_{Obj} \\land \\hat{s} = \\hat{\\SF{OtherStrSingle}}(x) }\\\\\n         \\hat{b}_1\n         & \\ifc{\\hat{o} \\neq \\bot_{Obj} \\land \\hat{s} = \\hat{\\SF{NumStr}} }\\\\\n         \\hat{b}_2\n         & \\ifc{\\hat{o} \\neq \\bot_{Obj} \\land \\hat{s} = \\hat{\\SF{OtherStr}} }\\\\\n         \\hat{b}_3\n         & \\ifc{\\hat{o} \\neq \\bot_{Obj} \\land \\hat{s} = \\top_{String} }\\\\\n         \\bot_{Bool} \n         & \\ifc{\\hat{o} = \\bot_{Obj} \\lor \\hat{s} = \\bot_{String} }\\\\\n       \\end{array}\n     \\right.\\\\\n & \\quad\\wherec{\n   \\hat{b}_1 = \n     \\left\\{\n       \\begin{array}{ll}\n         \\top_{Bool} & \\ifc{\\hat{o}(\\emph{@default\\_number}).1.1.1 \\not\\sqsubseteq \\bot_{Value}}\\\\\n         \\top_{Bool} & \\ifc{\\hat{o}(\\emph{@default\\_number}).1.1.1 \\sqsubseteq \\bot_{Value}}\\\\\n                     & \\quad \\land\\ \\exists x \\in dom(\\hat{o}):x \\in \\SF{String} \\land \\hat{``x\"} \\sqsubseteq \\hat{\\SF{NumStr}}\\\\\n         \\afalse & \\owc\\\\\n       \\end{array}\n     \\right.\\\\\n   \\hat{b}_2 = \n     \\left\\{\n       \\begin{array}{ll}\n         \\top_{Bool} & \\ifc{\\hat{o}(\\emph{@default\\_other}).1.1.1 \\not\\sqsubseteq \\bot_{Value}}\\\\\n         \\top_{Bool} & \\ifc{\\hat{o}(\\emph{@default\\_other}).1.1.1 \\sqsubseteq \\bot_{Value}}\\\\\n                     & \\quad \\land\\ \\exists x \\in dom(\\hat{o}):x \\in \\SF{String} \\land \\hat{``x\"} \\sqsubseteq \\hat{\\SF{OtherStr}}\\\\\n         \\afalse & \\owc\\\\\n       \\end{array}\n     \\right.\\\\\n   \\hat{b}_3 = \n     \\left\\{\n       \\begin{array}{ll}\n         \\top_{Bool} \n         & \\ifc{\\hat{o}(\\emph{@default\\_number}).1.1.1 \\not\\sqsubseteq \\bot_{Value}\\vee \\hat{o}(\\emph{@default\\_other}).1.1.1 \\not\\sqsubseteq \\bot_{Value}}\\\\\n         \\top_{Bool} \n         & \\ifc{\\hat{o}(\\emph{@default\\_number}).1.1.1 \\sqsubseteq \\bot_{Value}\\land \\hat{o}(\\emph{@default\\_other}).1.1.1 \\sqsubseteq \\bot_{Value}}\\\\\n         & \\quad \\land\\ \\exists x \\in dom(\\hat{o}):x \\in \\SF{String}\\\\\n         \\afalse & \\owc\\\\\n       \\end{array}\n     \\right.\\\\ \n  }\\\\\n\\end{array}\n\\]\n\n\\[\n\\begin{array}{ll}\n\\textit{Obj Domain In} & : \\aObj \\times \\SF{Prop} \\rightarrow \\abs{Bool} \\\\\n& x \\dot{\\in} dom(\\hat{o}) \\defi\n  \\left\\{\n    \\begin{array}{ll}\n      \\hat{b} & \\ifc{\\hat{o} \\neq \\bot_{Obj}} \\\\\n      \\bot_{Bool} & \\ifc{\\hat{o} = \\bot_{Obj}}\n    \\end{array}\n  \\right. \\\\\n& \\quad\\wherec{\n  \\hat{b} = \n    \\left\\{\n      \\begin{array}{ll}\n        \\atrue\n        &\\ifc{\\hat{o}(x)\\not\\sqsubseteq\\bot \\land \\hat{\\SF{absent}}\\not\\sqsubseteq\\hat{o}(x).2}\\\\\n        \\top_{Bool}\n        &\\ifc{\\hat{o}(x)\\not\\sqsubseteq\\bot \\land \\hat{\\SF{absent}}\\sqsubseteq\\hat{o}(x).2}\\\\\n        \\top_{Bool}\n        &\\ifc{\\hat{o}(x)\\sqsubseteq\\bot \\land x\\in \\SF{String} \\land \\alpha(x) \\sqsubseteq \\hat{\\SF{NumStr}}}\\\\\n        & \\quad\\land \\hat{o}(\\emph{@default\\_number}).1.1.1 \\not\\sqsubseteq \\bot_{Value} \\\\\n        \\top_{Bool}\n        &\\ifc{\\hat{o}(x)\\sqsubseteq\\bot \\land x\\in \\SF{String} \\land \\alpha(x) \\sqsubseteq \\hat{\\SF{OtherStr}}}\\\\\n        & \\quad\\land \\hat{o}(\\emph{@default\\_other}).1.1.1 \\not\\sqsubseteq \\bot_{Value} \\\\\n        \\afalse\n        &\\ifc{\\hat{o}(x)\\sqsubseteq\\bot \\land x\\in \\SF{String} \\land \\alpha(x) \\sqsubseteq \\hat{\\SF{NumStr}}}\\\\\n        & \\quad\\land \\hat{o}(\\emph{@default\\_number}).1.1.1 \\sqsubseteq \\bot_{Value} \\\\\n        \\afalse\n        &\\ifc{\\hat{o}(x)\\sqsubseteq\\bot \\land x\\in \\SF{String} \\land \\alpha(x) \\sqsubseteq \\hat{\\SF{OtherStr}}}\\\\\n        & \\quad\\land \\hat{o}(\\emph{@default\\_other}).1.1.1 \\sqsubseteq \\bot_{Value} \\\\\n        \\afalse\n        &\\ifc{\\hat{o}(x)\\sqsubseteq\\bot \\land x\\not\\in \\SF{String}}\\\\\n        \\afalse&\\owc\\\\\n      \\end{array}\n    \\right.\n}\n\\\\\\\\\n\n\\textit{Obj Lookup} & : \\aObj \\times \\abs{String} \\rightarrow \\abs{PropValue} \\times \\abs{Absent}\\\\\n& \\hat{o}(\\hat{s}) \\defi\n     \\left\\{\n       \\begin{array}{ll}\n         \\hat{o}(x)\n         & \\ifc{\\hat{s} = \\hat{\\SF{NumStrSingle}}(x) }\\\\\n         \\hat{o}(x)\n         & \\ifc{\\hat{s} = \\hat{\\SF{OtherStrSingle}}(x) }\\\\\n         \\langle (\\bigsqcup_{x \\in P_1} \\hat{o}(x)).1 \\sqcup \\hat{o}(\\emph{@default\\_number}).1, \\top_{Absent}\\rangle\n         & \\ifc{\\hat{s} = \\hat{\\SF{NumStr}} }\\\\\n         \\langle (\\bigsqcup_{x \\in P_2} \\hat{o}(x)).1 \\sqcup \\hat{o}(\\emph{@default\\_other}).1, \\top_{Absent}\\rangle\n         & \\ifc{\\hat{s} = \\hat{\\SF{OtherStr}} }\\\\\n         \\left\\langle \n           \\begin{matrix}\n             (\\bigsqcup_{x \\in P_3} \\hat{o}(x)).1 \\sqcup \\hat{o}(\\emph{@default\\_number}).1 \\\\ \n             \\sqcup \\hat{o}(\\emph{@default\\_other}).1\n           \\end{matrix},\n         \\top_{Absent}\\right\\rangle\n         & \\ifc{\\hat{s} = \\top_{String} }\\\\\n         \\bot_{PropValue \\times Absent} \n         &\\ifc{\\hat{s} = \\bot_{String} }\\\\\n       \\end{array}\n     \\right.\\\\\n & \\quad\\wherec{\n   P_1 = \\{ x\\ |\\ x \\in dom(\\hat{o}) \\land x \\in \\SF{String} \\land \\hat{``x\"} \\sqsubseteq \\hat{\\SF{NumStr}}\\}\\\\\n   P_2 = \\{ x\\ |\\ x \\in dom(\\hat{o}) \\land x \\in \\SF{String} \\land \\hat{``x\"} \\sqsubseteq \\hat{\\SF{OtherStr}}\\}\\\\\n   P_3 = \\{ x\\ |\\ x \\in dom(\\hat{o}) \\land x \\in \\SF{String}\\}\\\\\n  }\\\\\n\\\\\\\\\n\\textit{Obj Lookup} & : \\aObj \\times \\SF{Prop} \\rightarrow \\abs{PropValue} \\times \\abs{Absent} \\\\\n& \\hat{o}(x) \\defi \n  \\left\\{\n    \\begin{array}{ll}\n      \\langle\\hat{propv}, \\hat{abs}\\rangle\n      & \\ifc{\\begin{array}{l}x \\rightarrow \\langle\\hat{propv}, \\hat{abs}\\rangle \\in \\hat{o}\\end{array}} \\\\\n      \\langle\\bot_{PropValue}, \\bot_{Absent}\\rangle\n      & \\ifc{\\begin{array}{l}x \\rightarrow \\langle\\hat{propv}, \\hat{abs}\\rangle \\not\\in \\hat{o} \\land x \\not\\in \\SF{String} \\end{array}}\\\\\n      \\langle\\hat{propv}_2, \\hat{abs}_2\\rangle\n      & \\ifc{ \\begin{array}{l}\n          x \\rightarrow \\langle\\hat{propv}_1, \\hat{abs}_1\\rangle \\not\\in \\hat{o} \\land x \\in \\SF{String}\\\\\n          \\land \\alpha(x) \\sqsubseteq \\hat{\\SF{NumStr}}\n          \\land \\emph{@default\\_number} \\rightarrow\n          \\langle\\hat{propv}_2, \\hat{abs}_2\\rangle \\in \\hat{o}\\end{array}}\\\\\n      \\langle\\hat{propv}_3, \\hat{abs}_3\\rangle\n      & \\ifc{ \\begin{array}{l}\n          x \\rightarrow \\langle\\hat{propv}_1, \\hat{abs}_1\\rangle \\not\\in \\hat{o} \\land x \\in \\SF{String}\\\\\n          \\land \\alpha(x) \\sqsubseteq \\hat{\\SF{OtherStr}}\n          \\land \\emph{@default\\_other} \\rightarrow\n          \\langle\\hat{propv}_3, \\hat{abs}_3\\rangle \\in \\hat{o}\\end{array}}\\\\\n    \\end{array}\n  \\right.\\\\\n\\\\\n\n\\end{array}\n\\]\n\n\\[\n\\begin{array}{ll}\n\\textit{Obj Update} & : \\aObj \\times \\abs{String} \\times \\abs{PropValue} \\rightarrow \\aObj \\\\\n& \\hat{o}[\\hat{s} \\mapsto \\hat{propv}] \\defi \n \\left\\{\n       \\begin{array}{ll}\n         \\hat{o}[x \\mapsto \\hat{propv}]\n         & \\ifc{\\hat{o} \\neq \\bot_{Obj} \\land \\hat{s} = \\hat{\\SF{NumStrSingle}}(x) }\\\\\n         \\hat{o}[x \\mapsto \\hat{propv}]\n         & \\ifc{\\hat{o} \\neq \\bot_{Obj} \\land \\hat{s} = \\hat{\\SF{OtherStrSingle}}(x) }\\\\\n         \\hat{o}\n         \\left[\n           \\begin{array}{l}\n           \\forall x \\in P_1 : x \\mapsto \\hat{o}(x) \\sqcup \\hat{propv},\\\\\n           \\emph{@default\\_number} \\mapsto \\hat{o}(\\emph{@default\\_number}) \\sqcup \\hat{propv}\\\\\n           \\end{array}\n         \\right]\n         & \\ifc{\\hat{o} \\neq \\bot_{Obj} \\land \\hat{s} = \\hat{\\SF{NumStr}} }\\\\\n         \\hat{o}\n         \\left[\n           \\begin{array}{l}\n           \\forall x \\in P_2 : x \\mapsto \\hat{o}(x) \\sqcup \\hat{propv},\\\\\n           \\emph{@default\\_other} \\mapsto \\hat{o}(\\emph{@default\\_other}) \\sqcup \\hat{propv}\\\\\n           \\end{array}\n         \\right]\n         & \\ifc{\\hat{o} \\neq \\bot_{Obj} \\land \\hat{s} = \\hat{\\SF{OtherStr}} }\\\\\n         \\hat{o}\n         \\left[\n           \\begin{array}{l}\n           \\forall x \\in P_3 : x \\mapsto \\hat{o}(x) \\sqcup \\hat{propv},\\\\\n           \\emph{@default\\_number} \\mapsto \\hat{o}(\\emph{@default\\_number}) \\sqcup \\hat{propv},\\\\\n           \\emph{@default\\_other} \\mapsto \\hat{o}(\\emph{@default\\_other}) \\sqcup \\hat{propv}\\\\\n           \\end{array}\n         \\right]\n         & \\ifc{\\hat{o} \\neq \\bot_{Obj} \\land \\hat{s} = \\top_{String} }\\\\\n         \\bot_{Obj}\n         & \\ifc{\\hat{o} = \\bot_{Obj} \\lor \\hat{s} = \\bot_{String} }\\\\\n       \\end{array}\n     \\right.\\\\\n& \\quad\\wherec{\n   P_1 = \\{ x\\ |\\ x \\in dom(\\hat{o}) \\land x \\in \\SF{String} \\land \\hat{``x\"} \\sqsubseteq \\hat{\\SF{NumStr}}\\}\\\\\n   P_2 = \\{ x\\ |\\ x \\in dom(\\hat{o}) \\land x \\in \\SF{String} \\land \\hat{``x\"} \\sqsubseteq \\hat{\\SF{OtherStr}}\\}\\\\\n   P_3 = \\{ x\\ |\\ x \\in dom(\\hat{o}) \\land x \\in \\SF{String}\\}\\\\\n  }\\\\\n\\\\\\\\\n\\textit{Obj Update} & : \\aObj \\times \\SF{Prop} \\times \\abs{PropValue} \\rightarrow \\aObj \\\\\n& \\hat{o}[x \\mapsto \\hat{propv}] \\defi \n  \\left\\{\n    \\begin{array}{ll}\n      \\{( x, \\langle \\hat{propv}, \\bot_{Absent} \\rangle)\\} \\cup (\\hat{o}\\setminus\\{(x,\\langle \\hat{propv}', \\hat{abs}' \\rangle)\\}) \n        & \\ifc{\\hat{o} \\neq \\bot_{Obj}} \\\\\n      \\bot_{Obj} & \\ifc{\\hat{o} = \\bot_{Obj}} \\\\\n    \\end{array}\n  \\right.\n\\\\\\\\\n\\textit{Obj Update} & : \\aObj \\times \\SF{Prop} \\times \\abs{PropValue} \\times \\abs{Absent} \\rightarrow \\aObj \\\\\n& \\hat{o}[x \\mapsto \\langle \\hat{propv}, \\hat{abs} \\rangle] \\defi \n  \\left\\{\n    \\begin{array}{ll}\n      \\{( x, \\langle \\hat{propv}, \\hat{abs} \\rangle)\\} \\cup (\\hat{o}\\setminus\\{(x,\\langle \\hat{propv}', \\hat{abs}' \\rangle)\\}) \n        & \\ifc{\\hat{o} \\neq \\bot_{Obj}} \\\\\n      \\bot_{Obj} & \\ifc{\\hat{o} = \\bot_{Obj}} \\\\\n    \\end{array}\n  \\right.\n%\\textit{Obj Update} & : \\aObj \\times \\SF{Prop} \\times \\abs{PropValue} \\times \\abs{Absent} \\rightarrow \\aObj \\\\\n%& \\hat{o}[x \\mapsto \\langle \\hat{propv}, \\hat{abs} \\rangle] \\defi \\{( x, \\langle \\hat{propv}, \\hat{abs} \\rangle)\\} \\cup (\\hat{o}\\setminus\\{(x,\\langle \\hat{propv}', \\hat{abs}' \\rangle)\\})\\\\\n\\\\\\\\\n\\textit{Obj Remove} & : \\aObj \\times \\abs{String} \\rightarrow \\aObj \\\\\n& \\hat{o}- \\hat{s} \\defi \n \\left\\{\n       \\begin{array}{ll}\n         \\hat{o} - x\n         & \\ifc{\\hat{o} \\neq \\bot_{Obj} \\land \\hat{s} = \\hat{\\SF{NumStrSingle}}(x) }\\\\\n         \\hat{o} - x\n         & \\ifc{\\hat{o} \\neq \\bot_{Obj} \\land \\hat{s} = \\hat{\\SF{OtherStrSingle}}(x) }\\\\\n          \\hat{o} \\sqcup \\bigsqcup_{x \\in P_1}\\ \\{ (y,\\langle \\hat{propv}, \\hat{abs}\\rangle)\\ |\\ (y,\\langle \\hat{propv}, \\hat{abs}\\rangle) \\in \\hat{o} \\land y \\neq x \\}\n         & \\ifc{\\hat{o} \\neq \\bot_{Obj} \\land \\hat{s} = \\hat{\\SF{NumStr}} }\\\\\n          \\hat{o} \\sqcup \\bigsqcup_{x \\in P_2}\\ \\{ (y,\\langle \\hat{propv}, \\hat{abs}\\rangle)\\ |\\ (y,\\langle \\hat{propv}, \\hat{abs}\\rangle) \\in \\hat{o} \\land y \\neq x \\}\n         & \\ifc{\\hat{o} \\neq \\bot_{Obj} \\land \\hat{s} = \\hat{\\SF{OtherStr}} }\\\\\n          \\hat{o} \\sqcup \\bigsqcup_{x \\in P_3}\\ \\{ (y,\\langle \\hat{propv}, \\hat{abs}\\rangle)\\ |\\ (y,\\langle \\hat{propv}, \\hat{abs}\\rangle) \\in \\hat{o} \\land y \\neq x \\}\n         & \\ifc{\\hat{o} \\neq \\bot_{Obj} \\land \\hat{s} = \\top_{String} }\\\\\n         \\bot_{Obj}\n         & \\ifc{\\hat{o} = \\bot_{Obj} \\lor \\hat{s} = \\bot_{String} }\\\\\n       \\end{array}\n     \\right.\\\\\n& \\quad\\wherec{\n   P_1 = \\{ x\\ |\\ x \\in dom(\\hat{o}) \\land x \\in \\SF{String} \\land \\atrue \\sqsubseteq \\hat{o}(x).1.1.4 \\land \\hat{``x\"} \\sqsubseteq \\hat{\\SF{NumStr}} \\}\\\\\n   P_2 = \\{ x\\ |\\ x \\in dom(\\hat{o}) \\land x \\in \\SF{String} \\land \\atrue \\sqsubseteq \\hat{o}(x).1.1.4 \\land \\hat{``x\"} \\sqsubseteq \\hat{\\SF{OtherStr}}\\}\\\\\n   P_3 = \\{ x\\ |\\ x \\in dom(\\hat{o}) \\land x \\in \\SF{String} \\land \\atrue \\sqsubseteq \\hat{o}(x).1.1.4\\}\\\\\n  }\\\\\n\\\\\\\\\n\\textit{Obj Remove} & : \\aObj \\times \\SF{Prop} \\rightarrow \\aObj \\\\\n& \\hat{o}- x \\defi \n  \\left\\{\n  \\begin{array}{ll}\n    \\{ (y,\\langle \\hat{propv}, \\hat{abs}\\rangle)\\ |\\ (y,\\langle \\hat{propv}, \\hat{abs}\\rangle) \\in \\hat{o} \\land y \\neq x \\} \n    & \\ifc{\\hat{o} \\neq \\bot_{Obj}} \\\\\n    \\bot_{Obj} & \\ifc{\\hat{o} = \\bot_{Obj}} \\\\\n  \\end{array}\n  \\right.\\\\\n\\\\\\\\\n%\\rel^t &: \\abs{IROP} \\rightarrow \\abs{IROP}\\\\\n\\rel^t &: \\SF{IRRelOP} \\rightarrow \\SF{IRRelOP}\\\\\n& \\rel^ t = \\left\\{\n  \\begin{array}{ll}\n    < & \\ifc{ \\rel ~=~ >}\\\\\n    <= & \\ifc{ \\rel ~=~ >=}\\\\\n    > & \\ifc{ \\rel ~=~ <}\\\\\n    >= & \\ifc{ \\rel ~=~ <=}\\\\\n    \\rel & \\owc \\\\\n  \\end{array}\n\\right.\\\\\n\\\\\\\\\n\\end{array}\n\\]\n\n\\newpage\n\\section{Helper Functions}\n{\\inblue\\tt .../jsaf/analysis/typing/Helper.scala}\n\n%%% CanPut %%%\n\\[\n\\begin{array}{ll}\n\\ahf{CanPut} & : \\aHeap \\times \\aLoc \\times \\abs{String} \\rightarrow \\abs{Bool}\\\\\n&\n\\begin{array}{ll}\n  \\ahf{CanPut}(\\hat{H},\\hat{l},\\hat{s}) = \\ahf{CanPutHelp}(\\hat{H},\\hat{l},\\hat{s},\\hat{l}) & \\\\\n\\end{array}\n\\\\\\\\\n\n%& {\\inblue \\textit{For all case of }\\hat{s}_n\\textit{ if the condition is false, the value of }\\hat{s}_n\\textit{ is }\\bot_{String}.} \\\\\n& {\\inblue \\textit{Cycle in prototype chain is detected at implementation level.}} \\\\\n\\ahf{CanPutHelp} &  : \\aHeap \\times \\aLoc \\times \\abs{String} \\times \\aLoc \\rightarrow \\abs{Bool}\\\\\n&  \\ahf{CanPutHelp}(\\hat{H},\\hat{l}_1,\\hat{s},\\hat{l}_2)  = \\hat{b}_1\\sqcup\\hat{b}_2\\\\\n&  \\quad\\wherec{\n    \\hat{b}_1 =\n    \\left\\{\n      \\begin{array}{ll}\n        \\hat{H}(\\hat{l}_1)(\\hat{s}).1.1.2\n        ~~{\\inblue \\textit{// writable attribute}}\n        & \\ifc{\\atrue\\sqsubseteq(\\hat{s} \\dot{\\in} dom(\\hat{H}(\\hat{l})))}\\\\\n        \\bot_{Bool} & \\owc\\\\\n      \\end{array}\n    \\right.\\\\\n    \\hat{L}_{proto}=\\hat{H}(\\hat{l}_1)(\\varprop{proto}).1.1.1.2\n~~{\\inblue \\textit{// $\\powerset{\\aLoc}$ type}}\\\\\n    \\hat{b}_2 =\n    \\left\\{\n      \\begin{array}{ll}\n        \\hat{b}_3 \\sqcup \\bigsqcup_{\\hat{l}_{proto}\\in\\hat{L}_{proto}}\\ahf{CanPutHelp}(\\hat{H},\\hat{l}_{proto},\\hat{s},\\hat{l}_2)& \\ifc{\\afalse\\sqsubseteq(\\hat{s} \\dot{\\in} dom(\\hat{H}(\\hat{l})))}\\\\\n        \\bot_{Bool} & \\owc\\\\\n      \\end{array}\n    \\right.\\\\\n    \\hat{b}_3 =\n    \\left\\{\n      \\begin{array}{ll}\n        \\hat{H}(\\hat{l}_2)(\\varprop{extensible}).1.2.1.3& \\ifc{\\hat{H}(\\hat{l}_1)(\\varprop{proto}).1.1.1.1.2 \\not\\sqsubseteq \\bot_{Null}}\\\\\n        \\bot_{Bool} & \\owc\\\\\n      \\end{array}\n    \\right.\\\\\n    }\\\\\n\\\\\n\n\\ahf{CanPutVar} & : \\aHeap \\times \\SF{Prop} \\rightarrow \\abs{Bool}\\\\\n&\n\\begin{array}{ll}\n\\ahf{CanPutVar}(\\hat{H},x)\n  =  \\hat{b}_1\\sqcup\\hat{b}_2\\\\\n  \\quad\\wherec{\n    \\hat{b}_1 =\n      \\left\\{\n        \\begin{array}{ll}\n          \\hat{H}(\\avarloc{Global}_R)(x).1.1.2 & \\ifc{\\atrue\\sqsubseteq(x \\dot{\\in} dom(\\hat{H}(\\avarloc{Global})))} \\\\\n          \\bot_{Bool} & \\owc \\\\\n        \\end{array}\n      \\right.\\\\\n    \\hat{b}_2 = \n      \\left\\{\n        \\begin{array}{ll}\n          \\ahf{CanPut}(\\hat{H},\\avarloc{Global}_R,\\hat{x}) & \\ifc{\\afalse\\sqsubseteq(x \\dot{\\in} dom(\\hat{H}(\\avarloc{Global})))} \\\\\n          \\bot_{Bool} & \\owc \\\\\n        \\end{array}\n      \\right.\\\\\n  }\n\\end{array}\\\\\n\\\\\n\n\\\\\n\n%%% CreateMutableBinding %%%\n\n\n& {\\inblue \\textit{Temporaries and pure local variables are always mutable in non-strict mode.}} \\\\\n& {\\inblue \\textit{In strict-mode, ``arguments\" is immutable AND pure local, which invalidates current approach.}} \\\\\n\\ahf{CreateMutableBinding} & : \\aHeap \\times \\SF{Prop} \\times \\SF{Value} \\rightarrow \\aHeap \\\\\n& \\ahf{CreateMutableBinding}(\\hat{H}, x, \\hat{v}) = \\hat{H}_1 \\quad\\ifc{\\chf{getVarKind}_P(x) = \\SF{PureLocalVar}} \\\\\n& \\quad\\wherec{\\hat{H}_1 = \\hat{H}[\\avarloc{PureLocal}_R \\mapsto \\hat{H}(\\avarloc{PureLocal}_R)\n    [x \\mapsto \\langle \\hat{v},\\bot_{Bool},\\bot_{Bool},\\afalse \\rangle]]} \\\\\n& \\ahf{CreateMutableBinding}(\\hat{H}, x, \\hat{v}) = \\hat{H}_1 \\quad\\ifc{\\chf{getVarKind}_P(x) = \\SF{CapturedVar}} \\\\\n& \\quad\\wherec{\\hat{H}_1 = \\bigsqcup_{\\hat{l}\\in\\hat{H}(\\avarloc{PureLocal}_R)(\\varprop{env}).1.2.2} \\hat{H}[\\hat{l} \\mapsto \\hat{H}(\\hat{l})\n    [x \\mapsto \\langle \\hat{v},\\atrue,\\bot_{Bool},\\afalse \\rangle]]} \\\\\n& \\ahf{CreateMutableBinding}(\\hat{H}, x, \\hat{v}) = \\hat{H}_1 \\quad\\ifc{\\chf{getVarKind}_P(x) = \\SF{CapturedCatchVar}} \\\\\n& \\quad\\wherec{\\hat{H}_1 = \\hat{H}[\\avarloc{Collapsed}_O \\mapsto \\hat{H}(\\avarloc{Collapsed}_O)\n    [x \\mapsto \\langle \\hat{v},\\bot_{Bool},\\bot_{Bool},\\afalse \\rangle]]} \\\\\n& \\ahf{CreateMutableBinding}(\\hat{H}, x, \\hat{v}) = \\hat{H}_1 \\quad\\ifc{\\chf{getVarKind}_P(x) = \\SF{GlobalVar}} \\\\\n& \\quad\\wherec{\\hat{H}_1 = \\hat{H}[\\avarloc{Global}_R \\mapsto \\hat{H}(\\avarloc{Global}_R)\n    [x \\mapsto \\langle \\hat{v},\\atrue,\\atrue,\\afalse \\rangle]]} \\\\\n\\\\\n\\end{array}\n\\]\n\\\\\n\n%%% Delete %%%\n\\[\n\\begin{array}{ll}\n\n& {\\inblue \\hat{H}(\\hat{l})(\\hat{s}).1.1.4\\textit{ means the configurable attribute of the property.}} \\\\\n\\ahf{Delete} & : \\aHeap \\times \\aLoc \\times \\abs{String} \\rightarrow \\aHeap\n\\times \\abs{Bool}\\\\\n& \\ahf{Delete}(\\hat{H},\\hat{l},\\hat{s})\n  = (\\hat{H}_1\\sqcup\\hat{H}_2,\\hat{b}_1\\sqcup\\hat{b}_2)\\\\\n&  \\quad\\wherec{\n%    (\\hat{H}_1,\\hat{b}_1) = \\left\\{\n%      \\begin{array}{ll}\n%        (\\hat{H},\\atrue)\n%        & \\ifc{\\afalse\\sqsubseteq\\ahf{HasOwnProperty}(\\hat{H},\\hat{l},x)} \\\\\n%        \\bot_{Heap\\times Bool} & \\owc \\\\\n%      \\end{array}\n%    \\right.\\\\\n    (\\hat{H}_1,\\hat{b}_1) = \\left\\{\n      \\begin{array}{ll}\n        (\\hat{H},\\afalse)\n        & \\ifc{\\atrue\\sqsubseteq\\ahf{HasOwnProperty}(\\hat{H},\\hat{l},\\hat{s})\n          \\land\\ \\afalse\\sqsubseteq\\hat{H}(\\hat{l})(\\hat{s}).1.1.4}\\\\\n        \\bot_{Heap\\times Bool} & \\owc \\\\\n      \\end{array}\n    \\right.\\\\\n%{\\inblue \\textit{If the value is deleted in update operation,}}\\\\\n%{\\inblue \\textit{the absent attribute of the value will be 'absent' instead of removing the value}}\\\\\n%{\\inblue \\textit{because of a weak update.}}\\\\\n    (\\hat{H}_2,\\hat{b}_2) = \\left\\{\n      \\begin{array}{ll}\n        (\\hat{H}[\\hat{l}\\mapsto \\hat{H}(\\hat{l}) - \\hat{s}],\\atrue)\n        & \\ifc{\n          \\begin{array}{l}\n            \\left(\n              \\begin{array}{l}\n              \\atrue \\sqsubseteq\\ahf{HasOwnProperty}(\\hat{H},\\hat{l},\\hat{s})\\\\\n              \\land \\atrue\\sqsubseteq\\hat{H}(\\hat{l})(\\hat{s}).1.1.4)\n              \\end{array}\n            \\right)\\\\\n            \\vee (\\afalse\\sqsubseteq\\ahf{HasOwnProperty}(\\hat{H},\\hat{l},\\hat{s}))\n          \\end{array}}\\\\\n        \\bot_{Heap\\times Bool} & \\owc \\\\\n      \\end{array}\n    \\right.\\\\\n  }\\\\\n\\\\\n\n\\ahf {DeleteAll} &: \\aHeap \\times \\aLoc \\times \\abs{String} \\rightarrow \\aHeap\\\\\n& \\ahf{DeleteAll} (\\hat{H}, \\hat{l}, \\hat{s}) = \\hat{H}_1\\\\\n& \\quad\\wherec{\n  \\hat{H}_2 = \\ahf{Delete}(\\hat{H}, \\hat{l}, \\hat{s}).1\\\\\n  \\hat{H}_1 = \\left\\{\n    \\begin{array}{ll}\n      \\ahf{DeleteAll}(\\hat{H}_2, \\hat{l}_1, \\hat{s}) & \\ifc{\\hat{H}(\\hat{l})(@proto).1.1.1.1.2 \\sqsubseteq \\bot_{Null} \\\\ \\land \\hat{H}(\\hat{l})(@proto).1.1.1.2 = \\{ \\hat{l}_1\\}}\\\\\n      \\hat{H}_2 & \\owc\n    \\end{array}\n  \\right.\n}\n\\\\\n\n\\\\\n\n%Exception\n\n\n\\ahf{RaiseException} & : \\aHeap \\times \\abs{Context} \\times \\powerset{\\abs{Exception}} \\rightarrow \\aHeap \\times \\abs{Context}\\\\\n & \\ahf{RaiseException}(\\hat{H},\\hat{C}, \\hat{es}) = (\\hat{H}_1, \\hat{C}_1) \\\\\n & \\quad\\wherec{\n   \\hat{v}_{old} = \\hat{H}(\\avarloc{PureLocal}_R)(\\varprop{exception\\_all}).1.2 \\\\\n   \\hat{v}_e = \\langle \\bot_{PValue},\\ \\bigsqcup_{\\hat{exc}\\in\\hat{es}}\\ahf{NewExceptionLoc}(\\hat{exc}) \\rangle \\\\\n   \\hat{H}_e = \\hat{H}\\left[\\avarloc{PureLocal}_R\\mapsto \\hat{H}(\\avarloc{PureLocal}_R)\n     \\left[\\begin{array}{l}\n         \\varprop{exception}\\mapsto \\hat{v}_e, \\\\\n         \\varprop{exception\\_all}\\mapsto \\hat{v}_e \\sqcup \\hat{v}_{old} \n     \\end{array}\\right]\\right]\\\\\n   (\\hat{H}_1, \\hat{C}_1) = \\left\\{\n     \\begin{array}{ll}\n       (\\hat{H}_e, \\hat{C})&\\quad\\ifc{\\hat{es} \\neq \\{\\}}\\\\\n       (\\bot_{Heap}, \\bot_{Context}) &\\quad\\owc\n     \\end{array}\n   \\right.\\\\\n}\\\\\n\\\\\n\n\\ahf{NewExceptionLoc} & : \\abs{Exception} \\rightarrow \\abs{Loc} \\\\\n & \\ahf{NewExceptionLoc}(\\hat{H},\\hat{exc}) =\n \\left\\{\n   \\begin{array}{ll}\n     \\avarloc{Err}_O & \\ifc{\\hat{exc} = \\hat{\\exc{Error}}} \\\\\n     \\avarloc{EvalErr}_O & \\ifc{\\hat{exc} = \\hat{\\exc{EvalError}}} \\\\\n     \\avarloc{RangeErr}_O & \\ifc{\\hat{exc} = \\hat{\\exc{RangeError}}} \\\\\n     \\avarloc{RefErr}_O & \\ifc{\\hat{exc} = \\hat{\\exc{ReferenceError}}} \\\\\n     \\avarloc{SyntaxErr}_O & \\ifc{\\hat{exc} = \\hat{\\exc{SyntaxError}}} \\\\\n     \\avarloc{TypeErr}_O & \\ifc{\\hat{exc} = \\hat{\\exc{TypeError}}} \\\\\n     \\avarloc{URIErr}_O & \\ifc{\\hat{exc} = \\hat{\\exc{URIError}}} \\\\\n   \\end{array}\n \\right.\\\\\n\\\\\n\\end{array}\n\\]\n\\\\\n\n%%% get %%%\n\\[\n\\begin{array}{ll}\n\n\\ahf{getRel} & : \\SF{RelExpr} \\rightarrow \\aState \\rightarrow \\powerset{\\SF{RelExpr}}\\\\\n%& \\ahf{getRel}(\\hat{re}, \\hat{S}) = \\hat{re}_1 \\sqcup \\hat{re}_2 \\sqcup \\hat{re}_3\\\\\n%& \\quad\\wherec{\n%  (\\hat{H}, \\hat{C}) = \\hat{S}\\\\\n%  e_1 \\rel e_2 = \\hat{re}\\\\\n%  b = \\ahf{validity}(\\aV \\lbr e_2 \\rbr (\\hat{H}, \\hat{C}).1) \\land b_1\\\\\n%  b_1 = \\left\\{\n%    \\begin{array}{ll}\n%      \\ahf{validity}(\\aV \\lbr e_3 \\rbr (\\hat{H}, \\hat{C}).1) \\land \\ahf{validity}(\\aV \\lbr e_4 \\rbr (\\hat{H}, \\hat{C}).1) & \\ifc { e_3 \\otimes e_4 = e_1}\\\\\n%      \\vfalse & \\owc\\\\\n%    \\end{array}\n%  \\right.\\\\\n%  \\hat{re}_1 = \\left\\{\n%    \\begin{array}{ll}\n%      \\{\\hat{re}\\} &  \\ifc{ e_1 \\in \\$\\sf{Expression}}\\\\\n%      \\{\\} & \\owc\n%    \\end{array}\n%   \\right.\\\\\n%  \\hat{re}_2 = \\left\\{\n%    \\begin{array}{ll}\n%      \\ahf{getRel}(e_3 \\rel ( e_2 - e_4 ), \\hat{S} ) \\sqcup \\ahf{getRel}(e_4 \\rel ( e_2 - e_3 ), \\hat{S} ) &  \\ifc{ e_3 + e_4 = e_1 \\land b}\\\\\n%      \\ahf{getRel}(e_3 \\rel ( e_2 + e_4 ), \\hat{S} ) \\sqcup \\ahf{getRel}(e_4 \\rel^t ( e_2 - e_3 ), \\hat{S} ) &  \\ifc{ e_3 - e_4 = e_1 \\land b}\\\\\n%      \\{\\} & \\owc\n%    \\end{array}\n%   \\right.\\\\\n%  \\hat{re}_3 = \\left\\{\n%    \\begin{array}{ll}\n%      \\ahf{getRel}((e_3 * n ) \\rel e_2, \\hat{S} ) &  \\ifc{ n * e_3 = e_1 \\land b}\\\\\n%      \\ahf{getRel}(e_3 \\rel ( e_2 / n), \\hat{S} ) &  \\ifc{ e_3 * n = e_1 \\land b \\land n > 0}\\\\\n%      \\ahf{getRel}(e_3 \\rel ( e_2 * n), \\hat{S} ) &  \\ifc{ e_3 / n = e_1 \\land b \\land n > 0}\\\\\n%      \\ahf{getRel}(e_3 \\rel^t ( e_2 / n), \\hat{S} ) &  \\ifc{ e_3 * n = e_1 \\land b \\land n < 0}\\\\\n%      \\ahf{getRel}(e_3 \\rel^t ( e_2 * n), \\hat{S} ) &  \\ifc{ e_3 / n = e_1 \\land b \\land n < 0}\\\\\n%      \\{\\} & \\owc\n%    \\end{array}\n%   \\right.\\\\\n%}\\\\\n& \\begin{array}{lll}\n  \\ahf{getRel}(pe \\rel e, \\hat{S}) &=& \\{pe \\rel e\\}\\\\\n  \\ahf{getRel}((e_1 + e_2) \\rel e_3, \\, \\hat{S})  &=& \\ahf{getRel} (e_1 \\rel (e_3 - e_2), \\hat{S}) \\cup \\ahf{getRel} (e_2 \\rel (e_3 - e_1), \\hat{S}) \\quad \\ifc{\\ahf{validity}_3(e_1, e_2, e_3, \\hat{S})}\\\\\n  \\ahf{getRel}((e_1 - e_2) \\rel e_3, \\hat{S})  &=& \\ahf{getRel} (e_1 \\rel (e_3 + e_2), \\hat{S}) \\cup \\ahf{getRel} (e_2 \\rel^t (e_1 - e_3), \\hat{S})\\quad \\ifc{\\ahf{validity}_3(e_1, e_2, e_3, \\hat{S})}\\\\\n  \\ahf{getRel} ((n * e_1) \\rel e_2, \\hat{S})  &=& \\ahf{getRel} ((e_1  * n) \\rel e_2, \\hat{S}) \\quad \\ifc{\\ahf{validity}_2(e_1, e_2, \\hat{S})}\\\\\n  \\ahf{getRel} ((e_1  * n) \\rel e_2, \\hat{S}) &=& \\ahf{getRel} (e_1 \\rel (e_2/n), \\hat{S}) \\quad \\ifc {n>0 \\land \\ahf{validity}_2(e_1, e_2, \\hat{S})}\\\\\n  \\ahf{getRel} ((e_1  * n) \\rel e_2, \\hat{S}) &=& \\ahf{getRel} (e_1 \\rel^t (e_2/n), \\hat{S}) \\quad \\ifc {n<0 \\land \\ahf{validity}_2(e_1, e_2, \\hat{S})}\\\\\n  \\ahf{getRel} ((e_1  / n) \\rel e_2, \\hat{S}) &=& \\ahf{getRel} (e_1 \\rel (e_2*n), \\hat{S}) \\quad \\ifc {n>0 \\land \\ahf{validity}_2(e_1, e_2, \\hat{S})}\\\\\n  \\ahf{getRel} ((e_1  / n) \\rel e_2, \\hat{S}) &=& \\ahf{getRel} (e_1 \\rel^t (e_2*n), \\hat{S}) \\quad \\ifc {n<0 \\land \\ahf{validity}_2(e_1, e_2, \\hat{S})}\\\\\n\\end{array}\\\\\n%& \\quad \\wherec{\n%  (\\hat{H}, \\hat{C}) = \\hat{S}\\\\\n%  (\\hat{v}_1, \\hat{es}_1) = \\hat{\\V}_{cp} \\lbr e_1 \\rbr (\\hat{H}, \\hat{C})\\\\\n%  (\\hat{v}_2, \\hat{es}_2) = \\hat{\\V}_{cp} \\lbr e_2 \\rbr (\\hat{H}, \\hat{C})\\\\\n%  (\\hat{v}_3, \\hat{es}_3) = \\hat{\\V}_{cp} \\lbr e_3 \\rbr (\\hat{H}, \\hat{C})\\\\\n%  \\vtrue = \\ahf{validity}(\\hat{v}_1)\\\\\n%  \\vtrue = \\ahf{validity}(\\hat{v}_2)\\\\\n%  \\vtrue = \\ahf{validity}(\\hat{v}_3)\\\\\n%}\\\\\n\n& \\begin{array}{lll}\n  \\ahf{getRel}(re) &=& \\O \\quad\\owc\n\\end{array}\n\\\\\\\\\n\n\\ahf{getThis} & : \\aHeap \\times \\aValue \\rightarrow \\powerset{\\aLoc} \\\\\n& \\ahf{getThis}(\\hat{H}, \\hat{v})\n  = \\hat{L}_1\\cup\\hat{L}_2\\cup\\hat{L}_3\\\\\n& \\quad\\wherec{\n  \\hat{L}_1 = \\left\\{\n    \\begin{array}{ll}\n      \\{\\avarloc{Global}_R\\} & \\ifc{\\aundef\\sqsubseteq\\hat{v}.1.1 \\vee \\anull\\sqsubseteq\\hat{v}.1.2} \\\\\n      \\{\\} & \\owc \\\\\n    \\end{array}\n    \\right.\\\\\n  \\hat{L}_2 = \\left\\{\n    \\begin{array}{ll}\n      \\{\\avarloc{Global}_R\\} & \\ifc{\\exists\\ \\hat{l} \\in \\hat{v}.2 : \\afalse \\sqsubseteq \\ahf{IsObject}(\\hat{h},\\hat{l})} \\\\\n      \\{\\} & \\owc \\\\\n    \\end{array}\n    \\right.\\\\\n  \\hat{L}_3 = \\{ \\hat{l} \\in \\hat{v}.2 ~|~ \\atrue \\sqsubseteq \\ahf{IsObject}(\\hat{h},\\hat{l}) \\} \\\\\n}\n\\\\\n\n\\\\\n\n%%% Has %%%\n\n\\ahf{HasConstruct} & : \\aHeap \\times \\aLoc \\rightarrow \\abs{Bool} \\\\\n& \\ahf{HasConstruct}(\\hat{H},\\hat{l})\n  = \\hat{b}_1\\sqcup\\hat{b}_2 \\\\\n& \\quad\\wherec{\n  \\hat{b}_1 = \n    \\left\\{\n      \\begin{array}{l@{\\quad\\quad\\quad}l}\n        \\atrue &\\ifc{\\atrue\\sqsubseteq(\\varprop{construct} \\dot{\\in} dom(\\hat{H}(\\hat{l})))}\\\\\n        \\bot_{Bool} &\\owc\n      \\end{array}\n    \\right.\\\\\n  \\hat{b}_2 = \n    \\left\\{\n      \\begin{array}{l@{\\quad\\quad\\quad}l}\n        \\afalse &\\ifc{\\afalse\\sqsubseteq(\\varprop{construct} \\dot{\\in} dom(\\hat{H}(\\hat{l})))}\\\\\n        \\bot_{Bool} &\\owc\n      \\end{array}\n    \\right.\\\\\n  }\n\\\\\\\\\n\n\\ahf{HasInstance} & : \\aHeap \\times \\aLoc \\rightarrow \\abs{Bool} \\\\\n& \\ahf{HasConstruct}(\\hat{H},\\hat{l})\n  = \\hat{b}_1\\sqcup\\hat{b}_2 \\\\\n& \\quad\\wherec{\n  \\hat{b}_1 = \n    \\left\\{\n      \\begin{array}{l@{\\quad\\quad\\quad}l}\n        \\atrue &\\ifc{\\atrue\\sqsubseteq(\\varprop{hasinstance} \\dot{\\in} dom(\\hat{H}(\\hat{l})))}\\\\\n        \\bot_{Bool} &\\owc\n      \\end{array}\n    \\right.\\\\\n  \\hat{b}_2 = \n    \\left\\{\n      \\begin{array}{l@{\\quad\\quad\\quad}l}\n        \\afalse &\\ifc{\\afalse\\sqsubseteq(\\varprop{hasinstance} \\dot{\\in} dom(\\hat{H}(\\hat{l})))}\\\\\n        \\bot_{Bool} &\\owc\n      \\end{array}\n    \\right.\\\\\n  }\n\\\\\\\\\n\n& {\\inblue \\textit{Cycle in prototype chain is detected at implementation level.}} \\\\\n\\ahf{HasProperty} & : \\aHeap \\times \\aLoc \\times \\abs{String} \\rightarrow \\abs{Bool} \\\\\n& \\ahf{HasProperty}(\\hat{H},\\hat{l},\\hat{s}) = \\hat{b}_1\\sqcup\\hat{b}_2 \\\\\n& \\wherec{\n  \\hat{b}_1 = \\left\\{\n    \\begin{array}{ll}\n      \\atrue & \\ifc{\\atrue\\sqsubseteq\\ahf{HasOwnProperty}(\\hat{H},\\hat{l},\\hat{s})} \\\\\n      \\bot_{Bool} & \\owc \\\\\n    \\end{array}\n    \\right.\\\\\n    \\hat{L}_{proto} = \\hat{H}(\\hat{l})(\\varprop{proto}).1.1.1.2 \\\\\n  \\hat{b}_2 = \\left\\{\n    \\begin{array}{ll}\n      \\hat{b}_3 \\sqcup \\bigsqcup_{\\hat{l}_{proto}\\in\\hat{L}_{proto}}\\ahf{HasProperty}(\\hat{H},\\hat{l}_{proto},\\hat{s})\n      & \\ifc{\\afalse\\sqsubseteq\\ahf{HasOwnProperty}(\\hat{H},\\hat{l},\\hat{s})} \\\\\n      \\bot_{Bool} & \\owc \\\\\n    \\end{array}\n    \\right.\\\\\n    \\hat{b}_3 =\n    \\left\\{\n      \\begin{array}{ll}\n        \\afalse & \\ifc{\\hat{H}(\\hat{l}_1)(\\varprop{proto}).1.1.1.1.2 \\not\\sqsubseteq \\bot_{Null}}\\\\\n        \\bot_{Bool} & \\owc\\\\\n      \\end{array}\n    \\right.\\\\\n  }\\\\\n\\\\\n\n\\ahf{HasOwnProperty} & : \\aHeap \\times \\aLoc \\times \\abs{String} \\rightarrow \\abs{Bool} \\\\\n&  \\ahf{HasOwnProperty}(\\hat{H},\\hat{l},\\hat{s}) = (\\hat{s} \\dot{\\in} dom(\\hat{h}(\\hat{l})))\\\\\n\\\\\n\\end{array}\n\\]\n\\\\\\\\\n\n%%% inherit %%%\n\\[\n\\begin{array}{ll}\n& {\\inblue \\textit{Cycle in prototype chain is detected at implementation level.}} \\\\\n\\ahf{inherit} & : \\aHeap \\times \\aLoc \\times \\aLoc \\rightarrow \\aValue \\\\\n& \\ahf{inherit}(\\hat{H},\\hat{l}_1,\\hat{l}_2)\n  = \\left\\{\n    \\begin{array}{ll}\n      \\atrue & \\ifc{\\hat{l}_1 \\hat{=} \\hat{l}_2} \\\\\n      \\hat{v}_1 \\sqcup \\bigsqcup_{\\hat{l}\\in \\hat{H}(\\hat{l}_1)(\\varprop{proto}).1.1.1.2} \\ahf{inherit}(\\hat{H},\\hat{l},\\hat{l}_2) & \\ifc{\\hat{l}_1 \\hat{\\neq} \\hat{l}_2} \\\\\n    \\end{array}\n  \\right.\\\\\n& \\quad\\wherec{\n  \\hat{v}_1 =\n    \\left\\{\n    \\begin{array}{ll}\n      \\afalse & \\ifc{\\hat{H}(\\hat{l}_1)(\\varprop{proto}).1.1.1.1.2 \\not\\sqsubseteq \\bot_{Null}}\\\\\n      \\bot_{Value} & \\owc\\\\\n    \\end{array}\n    \\right.\n  }\\\\\n\\\\\n\n\\ahf {inheritProto}_1 &:  \\aHeap \\times \\aLoc \\times \\aLoc \\times \\abs{Bool} \\rightarrow \\powerset{\\aLoc}\\\\\n& \\ahf {inheritProto}_1 (\\hat{H}, \\hat{l}_1, \\hat{l}_2, \\hat{b}) = \\hat{L}\\\\\n& \\quad \\wherec{\n  \\hat{L} = \\left\\{\n    \\begin{array}{ll}\n      \\{ \\hat{l}_1 \\} & \\ifc{ \\hat{b} \\sqsubseteq \\ahf{inherit}(\\hat{H}, \\hat{l}_1, \\hat{l}_2)}\\\\\n      \\{ \\} & \\owc\\\\\n    \\end{array}\n  \\right.\\\\\n}\n\\\\\\\\\n\n\\ahf {inheritProto}_2 &:  \\aHeap \\times \\aLoc \\times \\aLoc \\times \\abs{Bool} \\rightarrow \\powerset{\\aLoc}\\\\\n& \\ahf {inheritProto}_2 (\\hat{H}, \\hat{l}_1, \\hat{l}_2, \\hat{b}) = \\hat{L}\\\\\n& \\quad \\wherec{\n  \\hat{L} = \\left\\{\n    \\begin{array}{ll}\n      \\{ \\hat{l}_2 \\} & \\ifc{ \\hat{b} \\sqsubseteq \\ahf{inherit}(\\hat{H}, \\hat{l}_1, \\hat{l}_2)}\\\\\n      \\{ \\} & \\owc\\\\\n    \\end{array}\n  \\right.\\\\\n}\n\\\\\n\n\\\\\n\n%%% Is %%%\n\n\\ahf{IsArray} & : \\aHeap \\times \\aLoc \\rightarrow \\abs{Bool} \\\\\n& {\\inblue \\hat{H}(\\hat{l})(\\varprop{class}).1.2\\textit{ is the }\\abs{Value}} \\\\\n& \\ahf{IsArray}(\\hat{H},\\hat{l}) = \\hat{b}_1\\sqcup\\hat{b}_2\\\\\n& \\quad\\wherec{\n    \\hat{b}_1=\\left\\{\n      \\begin{array}{ll}\n        \\atrue &\\ifc{\\hat{``Array\"} \\sqsubseteq \\hat{H}(\\hat{l})(\\varprop{class}).1.2}\\\\\n        \\bot_{Bool} & \\owc \\\\\n      \\end{array}\n    \\right.\\\\\n    \\hat{b}_2 = \\left\\{\n      \\begin{array}{ll}\n        \\afalse & \\ifc{\\hat{``Array\"} \\neq \\hat{H}(\\hat{l})(\\varprop{class}).1.2}\\\\\n        \\bot_{Bool} & \\owc\\\\\n      \\end{array}\n    \\right.\\\\\n  }\\\\\n\\\\\n\n\\ahf{IsArrayIndex} & : \\abs{String} \\rightarrow \\abs{Bool} \\\\\n& \\ahf{IsArrayIndex}(\\hat{s}) = \\left\\{\n      \\begin{array}{ll}\n        \\top_{Bool} & \\ifc{\\hat{s} = \\top_{String}}\\\\\n        \\top_{Bool} & \\ifc{\\hat{s} = \\hat{\\SF{NumStr}}}\\\\\n        \\afalse     & \\ifc{\\hat{s} = \\hat{\\SF{OtherStr}}}\\\\\n        \\atrue      & \\ifc{\\hat{s} = \\hat{\\SF{NumStrSingle}}(s) \\land 0 \\leq \\SF{ToNumber}(s) < 2^{32}-1}\\\\\n        \\top_{Bool} & \\ifc{\\hat{s} = \\hat{\\SF{NumStrSingle}}(s) \\land (\\SF{ToNumber}(s) < 0 \\lor < 2^{32}-1 \\leq \\SF{ToNumber}(s))}\\\\\n        \\afalse     & \\ifc{\\hat{s} = \\hat{\\SF{OtherStrSingle}}}\\\\\n        \\bot_{Bool} & \\ifc{\\hat{s} = \\bot_{String}} \\\\\n      \\end{array}\n    \\right.\\\\\n\\\\\n\n\\ahf{IsCallable} & : \\aHeap \\times \\aLoc \\rightarrow \\abs{Bool} \\\\\n& \\ahf{IsCallable}(\\hat{H},\\hat{l})\n  = \\hat{b}_1\\sqcup\\hat{b}_2 \\\\\n& \\quad\\wherec{\n  \\hat{b}_1 = \n    \\left\\{\n      \\begin{array}{l@{\\quad\\quad\\quad}l}\n        \\atrue &\\ifc{\\atrue\\sqsubseteq(\\varprop{function} \\dot{\\in} dom(\\hat{H}(\\hat{l})))}\\\\\n        \\bot_{Bool} &\\owc\n      \\end{array}\n    \\right.\\\\\n  \\hat{b}_2 = \n    \\left\\{\n      \\begin{array}{l@{\\quad\\quad\\quad}l}\n        \\afalse &\\ifc{\\afalse\\sqsubseteq(\\varprop{function} \\dot{\\in} dom(\\hat{H}(\\hat{l})))}\\\\\n        \\bot_{Bool} &\\owc\n      \\end{array}\n    \\right.\\\\\n  }\\\\\n\\\\\n\n\\ahf{IsObject} & : \\aHeap \\times \\aLoc \\rightarrow \\abs{Bool} \\\\\n& \\ahf{IsObject}(\\hat{H},\\hat{l}) = \\varprop{class} ~ \\dot{\\in} ~ dom(\\hat{h}(\\hat{l})) \\\\\n\\\\\n\\end{array}\n\\]\n\\\\\\\\\n\n%%% K %%%\n\\[\n\\begin{array}{ll}\n\\ahf{K} & : \\SF{IRRelOP} \\rightarrow \\aValue \\rightarrow \\aValue \\times \\abs{Absent}\\\\\n& \\ahf{K}_{!==} \\hat{v}_1 = (\\top_{Value}, \\hat{\\SF{absent}})\\\\\n& \\ahf{K}_{===} \\hat{v}_1 = (\\hat{v}_1, \\hat{abs})\\\\\n& \\quad \\wherec{ \n  \\hat{abs} = \\left\\{\n    \\begin{array}{ll}\n      \\hat{\\SF{absent}} & \\ifc{ \\aundef \\sqsubseteq \\hat{v}_1.1.1}\\\\\n      \\bot_{Absent} & \\owc\\\\\n    \\end{array}\n  \\right.\\\\\n}\\\\\n& \\ahf{K}_{!=} \\hat{v}_1 = (\\top_{Value}, \\hat{\\SF{absent}})\\\\\n& \\ahf{K}_{==} \\hat{v}_1 = (\\langle \\langle \\hat{v}_1.1.1 \\sqcup \\hat{pv}_1,\\hat{v}_1.1.2 \\sqcup \\hat{pv}_2, \\hat{v}_1.1.3 \\sqcup \\hat{pv}_3, \\hat{v}_1.1.4 \\sqcup \\hat{pv}_4, \\top_{String} \\rangle, \\top_{\\aLoc}  \\rangle, \\hat{abs})\\\\ \n%\\end{array}\\\\\n& \\quad\\wherec{\n  \\hat{abs} = \\left\\{\n    \\begin{array}{ll}\n      \\hat{\\SF{absent}} & \\ifc{ \\aundef \\sqsubseteq \\hat{v}_1.1.1 \\lor \\anull \\sqsubseteq \\hat{v}_1.1.2}\\\\\n      \\bot_{Absent} & \\owc\\\\\n    \\end{array}\n  \\right.\\\\\n  n_1 = \\left\\{\n    \\begin{array}{ll}\n      \\hat{1} & \\ifc{ \\atrue \\sqsubseteq \\hat{v}_1.1.3}\\\\\n      \\bot_{Number} & \\owc\\\\\n    \\end{array}\n  \\right.\\\\\n  n_2 = \\left\\{\n    \\begin{array}{ll}\n      \\hat{0} & \\ifc{ \\afalse \\sqsubseteq \\hat{v}_1.1.3}\\\\\n      \\bot_{Number} & \\owc\\\\\n    \\end{array}\n  \\right.\\\\\n  n_3 = \\ahf{Str2Num} ((\\hat{v}_1.1.5)_{\\hat{PValue}})\\\\\n  n_4 = \\left\\{\n    \\begin{array}{ll}\n      \\bot_{Number} & \\ifc{ \\hat{v}_1.1.4 \\sqsubseteq \\hat{NaN}}\\\\\n      \\hat{v}_1.1.4 & \\owc\\\\\n    \\end{array}\n  \\right.\\\\\n%  \\hat{L}_{loc} = \\ahf{getLoc}(\\hat{H}, \\hat{v}.2)\\\\\n  \\hat{pv}_1 = \\left\\{\n    \\begin{array}{ll}\n      \\aundef & \\ifc {\\anull \\sqsubseteq \\hat{v}_1.1.2}\\\\\n      \\bot_{Undef} & \\owc\\\\\n    \\end{array}\n  \\right.\\\\\n  \\hat{pv}_2 = \\left\\{\n    \\begin{array}{ll}\n      \\anull & \\ifc {\\aundef \\sqsubseteq \\hat{v}_1.1.1}\\\\\n      \\bot_{Null} & \\owc\\\\\n    \\end{array}\n  \\right.\\\\\n  \\hat{pv}_3 = \\left\\{\n    \\begin{array}{ll}\n      \\top_{Bool} & \\ifc{ \\hat{\\sf{UINT}} \\sqsubseteq \\hat{v}_1.1.4 \\lor \\hat{v}_1.2 \\not= \\O }\\\\\n      \\atrue & \\ifc{ \\hat{v}_1.2 = \\O \\land (\\hat{1} \\sqsubseteq \\hat{v}_1.1.4 \\lor \\hat{1} \\sqsubseteq \\ahf{Str2Num}((\\hat{v}_1.1.5)_{\\hat{PValue}}))}\\\\\n      \\afalse & \\ifc{ \\hat{v}_1.2 = \\O \\land (\\hat{0} \\sqsubseteq \\hat{v}_1.1.4 \\lor \\hat{0} \\sqsubseteq \\ahf{Str2Num}((\\hat{v}_1.1.5)_{\\hat{PValue}}))}\\\\\n      \\bot_{Bool} & \\owc\\\\\n    \\end{array}\n  \\right.\\\\\n  \\hat{pv}_4 = \\left\\{\n    \\begin{array}{ll}\n      n_1 \\sqcup n_2 \\sqcup n_3 \\sqcup n_4  & \\ifc{ \\hat{v}_1.2 = \\O} \\\\\n      \\top_{Number} & \\owc\n    \\end{array}\n  \\right.\\\\\n}\\\\\n\\end{array}\n\\]\n\\\\\\\\\n\n%%% Lookup %%%\n\n\\[\n\\begin{array}{ll}\n\\ahf{Lookup} & : \\aHeap \\times \\SF{Prop} \\rightarrow \\aValue \\times \\powerset{\\abs{Exception}}\\\\\n& \\ahf{Lookup}(\\hat{H},x) = (\\hat{H}(\\avarloc{PureLocal}_R)(x).1.1.1, \\set{ }) \n      \\quad\\ifc{\\chf{getVarKind}_P(x) = \\SF{PureLocalVar}} \\\\\n& \\ahf{Lookup}(\\hat{H},x) = (\\bigsqcup_{\\hat{l}\\in\\hat{H}(\\avarloc{PureLocal})(\\varprop{env}).1.2.2} \\ahf{LookupL}(\\hat{H},\\hat{l},x), \\set{ })\n      \\quad\\ifc{\\chf{getVarKind}_P(x) = \\SF{CapturedVar}} \\\\\n& \\ahf{Lookup}(\\hat{H},x) = (\\hat{H}(\\avarloc{Collapsed}_O)(x).1.1.1, \\set{ }) \n      \\quad\\ifc{\\chf{getVarKind}_P(x) = \\SF{CapturedCatchVar}} \\\\\n& \\ahf{Lookup}(\\hat{H},x) = \\ahf{LookupG}(\\hat{H},x)\n      \\quad\\ifc{\\chf{getVarKind}_P(x) = \\SF{GlobalVar}} \\\\\n\\\\\n\n\\ahf{LookupG} & : \\aHeap \\times \\SF{Prop} \\rightarrow \\aValue \\times \\powerset{\\abs{Exception}}\\\\\n&\n  \\ahf{LookupG}(\\hat{H},x)\n   = (\\hat{v}_1\\sqcup\\hat{v}_2, \\hat{es})\\\\\n& \\quad\\wherec{\n  \\hat{v}_1 = \\left\\{\n    \\begin{array}{ll}\n      \\hat{H}(\\avarloc{Global}_R)(x).1.1.1\n      & \\ifc{\\atrue\\sqsubseteq(x \\dot{\\in} dom(\\hat{H}(\\avarloc{Global})))} \\\\\n      \\bot_{Value}\n      & \\owc \\\\\n    \\end{array}\\right. \\\\\n  (\\hat{v}_2, \\hat{es}) = \\left\\{\n    \\begin{array}{ll}\n      (\\hat{v}_3, \\hat{exc})\n      & \\ifc{\\afalse\\sqsubseteq(x \\dot{\\in} dom(\\hat{H}(\\avarloc{Global})))}\\\\\n      (\\bot_{Value}, \\{\\})\n      & \\owc \\\\\n    \\end{array}\\right. \\\\\n  \\hat{L}_{proto} = \\hat{H}(\\avarloc{Global}_R)(\\hat{\\varprop{proto}}).1.1.1.2\\\\\n  \\hat{v}_3 = \n    \\bigsqcup_{\\hat{l}_{proto}\\in\\hat{L}_{proto}}\n    \\left\\{\n    \\begin{array}{ll}\n      \\ahf{Proto}(\\hat{H}, \\hat{l}_{proto}, \\hat{x})\n      & \\ifc{\\atrue\\sqsubseteq\\ahf{HasProperty}(\\hat{H},\\hat{l}_{proto},x)}\\\\\n      \\bot_{Value}\n      & \\owc \\\\\n    \\end{array}\\right. \\\\\n  \\hat{exc} = \n    \\bigsqcup_{\\hat{l}_{proto}\\in\\hat{L}_{proto}}\n    \\left\\{\n    \\begin{array}{ll}\n      \\{\\hat{\\SF{ReferenceError}}\\}\n      & \\ifc{\\afalse\\sqsubseteq\\ahf{HasProperty}(\\hat{H},\\hat{l}_{proto},x)}\\\\\n      \\bot_{Exception}\n      & \\owc \\\\\n    \\end{array}\\right. \\\\\n}\n\\\\\\\\\n\n& {\\inblue \\textit{Cycle in scope chain is detected at implementation level.}} \\\\\n\\ahf{LookupL} & : \\aHeap \\times \\aLoc \\times \\SF{Prop} \\rightarrow \\aValue \\\\\n& \\ahf{LookupL}(\\hat{H}, \\hat{l}, x) = \\hat{v}_1 \\sqcup \\hat{v}_2 \\\\\n& \\quad\\wherec{\n    \\hat{v}_1 =\n      \\left\\{\n      \\begin{array}{ll}\n        \\hat{H}(\\hat{l})(x).1.1.1 & \\ifc{\\atrue \\sqsubseteq (x \\dot{\\in} dom(\\hat{H}(\\hat{l})))}\\\\\n        \\bot_{Value} & \\owc \\\\\n      \\end{array}\n      \\right.\\\\\n    \\hat{L}_{outer} = \\hat{H}(\\hat{l})(\\varprop{outer}).1.2.2 \\\\\n    \\hat{v}_2 =\n      \\left\\{\n      \\begin{array}{ll}\n        \\bigsqcup_{\\hat{l}_{outer}\\in\\hat{L}_{outer}}\\ahf{LookupL}(\\hat{H}, \\hat{l}_{outer}, x) \n          & \\ifc{\\afalse \\sqsubseteq(x \\dot{\\in} dom(\\hat{H}(\\hat{l})))} \\\\\n        \\bot_{Value} & \\owc \\\\\n      \\end{array}\n      \\right.\\\\\n  } \\\\\n\\\\\n\n\\ahf{LookupBase} & : \\aHeap \\times \\SF{Prop} \\rightarrow \\powerset{\\aLoc}\\\\\n& \\ahf{LookupBase}(\\hat{H},x) = \\{ \\avarloc{PureLocal}_R \\} \n    \\quad\\ifc{\\chf{getVarKind}_P(x) = \\SF{PureLocalVar}} \\\\\n& \\ahf{LookupBase}(\\hat{H},x) = \\bigcup_{\\hat{l}\\in\\hat{H}(\\avarloc{PureLocal}_R)(\\varprop{env}).1.2.2} \\ahf{LookupBaseL}(\\hat{H},\\hat{l},x)\n    \\quad\\ifc{\\chf{getVarKind}_P(x) = \\SF{CapturedVar}} \\\\\n& \\ahf{LookupBase}(\\hat{H},x) = \\{ \\avarloc{Collapsed}_O \\} \n    \\quad\\ifc{\\chf{getVarKind}_P(x) = \\SF{CapturedCatchVar}} \\\\\n& \\ahf{LookupBase}(\\hat{H},x) = \\ahf{LookupBaseG}(\\hat{H},x)\n    \\quad\\ifc{\\chf{getVarKind}_P(x) = \\SF{GlobalVar}} \\\\\n\\\\\n\n\\ahf{LookupBaseG} & : \\aHeap \\times \\SF{Prop} \\rightarrow \\powerset{\\aLoc}\\\\\n&\n  \\ahf{LookupBaseG}(\\hat{H},x)\n   = \\hat{L}_1\\cup\\hat{L}_2\\\\\n& \\quad\\wherec{\n  \\hat{L}_1 = \\left\\{\n    \\begin{array}{ll}\n      \\{\\avarloc{Global}_R\\}\n      & \\ifc{\\atrue\\sqsubseteq(x \\dot{\\in} dom(\\hat{H}(\\avarloc{Global}_R))} \\\\\n      \\{\\}\n      & \\owc \\\\\n    \\end{array}\\right. \\\\\n  \\hat{L}_2 = \\left\\{\n    \\begin{array}{ll}\n      \\hat{L}_3\n      & \\ifc{\\vfalse\\sqsubseteq(x \\dot{\\in} dom(\\hat{H}(\\avarloc{Global}_R))}\\\\\n      \\{\\}\n      & \\owc \\\\\n    \\end{array}\\right. \\\\\n  \\hat{L}_{proto} = \\hat{H}(\\avarloc{Global}_R)(\\varprop{proto}).1.1.1.2\\\\\n  \\hat{L}_3 = \n    \\bigsqcup_{\\hat{l}_{proto}\\in\\hat{L}_{proto}}\n    \\ahf{ProtoBase}(\\hat{H}, \\hat{l}_{proto}, \\hat{x})\\\\\n}\n\\\\\\\\\n\n& {\\inblue \\textit{Cycle in scope chain is detected at implementation level.}} \\\\\n\\ahf{LookupBaseL} & : \\aHeap \\times \\aLoc \\times \\SF{Prop} \\rightarrow \\powerset{\\aLoc} \\\\\n& \\ahf{LookupBaseL}(\\hat{H}, \\hat{l}, x) = \\hat{L}_1\\cup\\hat{L}_2 \\\\\n& \\quad\\wherec{\n    \\hat{L}_1 =\n      \\left\\{\n      \\begin{array}{ll}\n        \\{ \\hat{l} \\} & \\ifc{\\atrue \\sqsubseteq (x \\dot{\\in} dom(\\hat{H}(\\hat{l})))} \\\\\n        \\{ \\} & \\owc \\\\\n      \\end{array}\n      \\right.\\\\\n    \\hat{L}_{outer} = \\hat{H}(\\hat{l})(\\varprop{outer}).1.2.2 \\\\\n    \\hat{L}_2 =\n      \\left\\{\n      \\begin{array}{ll}\n        \\bigcup_{\\hat{l}_{outer}\\in\\hat{L}_{outer}}\\ahf{LookupBaseL}(\\hat{H}, \\hat{l}_{outer}, x)\n          & \\ifc{\\afalse \\sqsubseteq (x \\dot{\\in} dom(\\hat{H}(\\hat{l})))} \\\\\n        \\set{} & \\owc \\\\\n      \\end{array}\n      \\right.\\\\\n  } \\\\\n\\\\\n\\end{array}\n\\]\n\\\\\n\n%%% New %%%\n\\[\n\\begin{array}{ll}\n\n\\ahf{NewBoolean} & : \\abs{Value} \\rightarrow \\aObj \\\\\n& \\ahf{NewBoolean}(\\hat{v}) = \\set{\n    \\varprop{class}\\mapsto \\hat{``Boolean\"}_{Value},\\\\\n    \\varprop{proto}\\mapsto \n    \\langle\\langle\\bot_{PValue},\\{\\avarloc{BoolProto}_R\\}\\rangle,\\afalse,\\afalse,\\afalse\\rangle,\\\\\n    \\varprop{extensible}\\mapsto \\atrue_{Value}, \\\\\n    \\varprop{primitive}\\mapsto \\hat{v}\n}\\\\\\\\\n\n\\ahf{NewNumber} & : \\abs{Value} \\rightarrow \\aObj \\\\\n& \\ahf{NewNumber}(\\hat{v}) = \\set{\n    \\varprop{class}\\mapsto \\hat{``Number\"}_{Value},\\\\\n    \\varprop{proto}\\mapsto \n    \\langle\\langle\\bot_{PValue},\\{\\avarloc{NumProto}_R\\}\\rangle,\\afalse,\\afalse,\\afalse\\rangle,\\\\\n    \\varprop{extensible}\\mapsto \\atrue_{Value}, \\\\\n    \\varprop{primitive}\\mapsto \\hat{v}\n}\\\\\\\\\n\n\\ahf{NewString} & : \\abs{Value} \\rightarrow \\aObj \\\\\n& \\ahf{NewString}(\\hat{v}) = \\hat{o}_1 \\sqcup \\hat{o}_2 \\\\\n& \\quad\\wherec{\n  \\hat{s} = \\hat{v}.1.5\\ \\land\\ \\hat{v}_{len} = length(\\hat{s})\\\\\n  \\hat{o}_1 = \\set{\n    \\varprop{class}\\mapsto \\hat{``String\"}_{Value},\\\\\n    \\varprop{proto}\\mapsto \n    \\langle\\langle\\bot_{PValue},\\{\\avarloc{StrProto}_R\\}\\rangle,\\afalse,\\afalse,\\afalse\\rangle,\\\\\n    \\varprop{extensible}\\mapsto \\atrue_{Value}, \\\\\n    \\varprop{primitive}\\mapsto \\hat{v}, \\\\\n    ``length\"\\mapsto \\langle (\\hat{v}_{len})_{Value}, \\afalse, \\afalse, \\afalse\\rangle \\\\\n  } \\\\\n  \\hat{o}_2 = \\set{``i\"\\mapsto \\langle (\\hat{v}_{char})_{Value}, \\afalse, \\atrue, \\afalse\\rangle ~\\left|~\n      \\begin{array}{l}\n        0 \\leq i\\\\\n        \\land\\ \\exists l\\in\\gamma(\\hat{v}_{len}).i < l\\\\\n        \\land\\ \\hat{v}_{char} = charAt(\\hat{s},i)\n      \\end{array}\n    \\right.}\n}\\\\\n\n\\\\\n\n\\ahf{NewDeclEnvRecord} & : \\abs{Value} \\rightarrow \\aObj \\\\\n& \\comment{\\inblue outer is either location set or null value} \\\\\n& \\ahf{NewDeclEnvRecord}(\\hat{v}) = \\set{\n    \\varprop{outer} \\mapsto \\hat{v}\n}\\\\\\\\\n\n\\ahf{NewObject} & : \\aLoc \\rightarrow \\aObj \\\\\n& \\ahf{NewObject}(\\hat{l}) = \\set{\\varprop{class}\\mapsto \\hat{``Object\"}_{Value},\\\\\n  \\varprop{proto}\\mapsto\n   \\langle \\langle\\bot_{PValue},\\{\\hat{l}\\}\\rangle,\\afalse,\\afalse,\\afalse \\rangle,\\\\\n  \\varprop{extensible}\\mapsto \\atrue_{Value}\n  }\\\\\n\\\\\n\n\\ahf{NewArgObject} & : \\abs{Number} \\rightarrow \\aObj \\\\\n& \\ahf{NewArgObject}(\\hat{n}) = \\set{\n    \\varprop{class}\\mapsto \\hat{``Arguments\"}_{Value},\\\\\n    \\varprop{proto}\\mapsto \n    \\langle\\langle\\bot_{PValue},\\{\\avarloc{ObjProto}_R\\}\\rangle,\\afalse,\\afalse,\\afalse\\rangle,\\\\\n   ``length\"\\mapsto\n   \\langle\\hat{n}_{Value},\\atrue,\\afalse,\\atrue\\rangle,\\\\\n  \\varprop{extensible}\\mapsto \\atrue_{Value}\n}\\\\\\\\\n    \n\\ahf{NewArrayObject} & : \\abs{Number} \\rightarrow \\aObj \\\\\n& \\ahf{NewArrayObject}(\\hat{n}) = \\set{\n    \\varprop{class}\\mapsto \\hat{``Array\"}_{Value},\\\\\n    \\varprop{proto}\\mapsto \n    \\langle\\langle\\bot_{PValue},\\{\\avarloc{ArrayProto}_R\\}\\rangle,\\afalse,\\afalse,\\afalse\\rangle,\\\\\n   ``length\"\\mapsto\n   \\langle\\hat{n}_{Value},\\atrue,\\afalse,\\afalse\\rangle,\\\\\n  \\varprop{extensible}\\mapsto \\atrue_{Value}\n}\\\\\\\\\n\n\\ahf{NewFunctionObject} & : \\fid \\times \\abs{Value} \\times \\aLoc \\times \\abs{Number} \\rightarrow \\aObj \\\\\n& \\comment{\\inblue scope is either location set or null value} \\\\\n& \\ahf{NewFunctionObject}(fid,\\hat{v},\\hat{l},\\hat{n}) = \\set{\n  \\varprop{class}\\mapsto \\hat{``Function\"}_{Value},\\\\\n  \\varprop{proto}\\mapsto\n    \\langle\\langle\\bot_{PValue},\\{\\avarloc{FunctionProto}_R\\}\\rangle,\\afalse,\\afalse,\\afalse\\rangle,\\\\\n  \\varprop{extensible}\\mapsto \\atrue_{Value},\\\\\n  \\varprop{function}\\mapsto \\{fid\\},\\\\\n  \\varprop{construct}\\mapsto \\{fid\\},\\\\\n  \\varprop{hasinstance}\\mapsto \\top_{Null},\\\\\n  \\varprop{scope}\\mapsto \\hat{v},\\\\\n  ``prototype\"\\mapsto\n    \\langle\\langle\\bot_{PValue},\\{\\hat{l}\\}\\rangle,\\atrue,\\afalse,\\afalse\\rangle,\\\\\n  ``length\"\\mapsto\n    \\langle\\hat{n}_{Value},\\afalse,\\afalse,\\afalse\\rangle\n}\\\\\\\\\n\n\n\\ahf{NewPureLocal} & : \\abs{Value} \\times \\powerset{\\abs{Loc}} \\rightarrow \\aObj \\\\\n& \\comment{\\inblue env is either location set or null value} \\\\\n& \\ahf{NewPureLocal}(\\hat{v}_{env}, \\hat{L}_{this}) = \\set{\n    \\varprop{env} \\mapsto \\hat{v}_{env}, \\\\\n    \\varprop{this} \\mapsto \\hat{L}_{this}, \\\\\n    \\varprop{exception} \\mapsto \\bot_{PropValue}, \\\\\n    \\varprop{exception\\_all} \\mapsto \\bot_{PropValue}, \\\\\n    \\varprop{return} \\mapsto \\aundef_{Value} \n}\\\\\n\\end{array}\n\\]\n\\\\\n\n%%% Oldify %%%\n\\[\n\\begin{array}{ll}\n\n\\ahf{Oldify} & : \\aHeap \\times \\abs{Context} \\times \\abs{Address} \\rightarrow \\aHeap \\times \\abs{Context}\\\\\n & \\ahf{Oldify}(\\hat{H},\\hat{C}, \\hat{a}) =\n     \\left\\{\n       \\begin{array}{ll}\n         (\\hat{H}_1, \\hat{C}_1) & \\ifc{\\hat{C} \\neq \\bot_{Context}} \\\\\n         (\\bot_{Heap}, \\bot_{Context}) & \\ifc{\\hat{C} = \\bot_{Context}} \\\\\n       \\end{array}\n     \\right.\\\\\n & \\quad\\wherec{\n   \\hat{l}_R = (\\hat{a}, \\hat{Recent}) \\land\\ \\hat{l}_O = (\\hat{a}, \\hat{Old})\\\\\n   \\land\\ \\hat{H}_1 =\n     \\left\\{\n       \\begin{array}{ll}\n         (\\hat{H}[\\hat{l_O}\\mapsto \\hat{H}(\\hat{l_R})]-\\hat{l}_R)\\{\\hat{l}_O / \\hat{l}_R\\}\n         & \\ifc{\\hat{l_R}\\in dom(\\hat{H})} \\\\\n         \\hat{H}\\{\\hat{l}_O / \\hat{l}_R\\}\n         & \\ifc{\\hat{l_R}\\not\\in dom(\\hat{H})} \\\\\n       \\end{array}\n     \\right.\\\\\n   \\land\\ \\hat{C}_1 = \\langle {\\inred \\{ \\}, \\{ \\}}, \\hat{C}.3 \\cup \\{\\hat{a}\\}, \\hat{C}.4 \\cup \\{\\hat{a}\\} \\rangle\n}\\\\\\\\\n\n\n& {\\inblue \\textit{At function return, this method oldifies bypassed pure local object.}} \\\\\n\\ahf{FixOldify} & : \\abs{Context} \\times \\aObj \\times \\powerset{\\abs{Address}} \\times \\powerset{\\abs{Address}} \\rightarrow \\abs{Context} \\times \\aObj \\\\\n& \\ahf{FixOldify}(\\hat{C}_0, \\hat{o}_0, \\hat{A}_{may}, \\hat{A}_{must}) =\n    \\left\\{\n      \\begin{array}{ll}\n        (\\hat{C}_n, \\hat{o}_n) & \\ifc{\\hat{C} \\neq \\bot_{Context}} \\\\\n        (\\bot_{Context}, \\bot_{Obj}) & \\ifc{\\hat{C} = \\bot_{Context}} \\\\\n      \\end{array}\n    \\right.\\\\\n& \\quad\\wherec{\\hat{a}_1\\cdots\\hat{a}_n = \\hat{A}_{may} ~ \\land} \\\\\n& \\quad\\forall 1 \\leq i \\leq n.\\\\\n& \\quad\\quad \\begin{array}{l}\n    \\hat{l}_{R_i} = (\\hat{a}_i, \\hat{Recent}) \\land\\ \\hat{l}_{O_i} = (\\hat{a}_i, \\hat{Old})\\ \\land \\\\\n    \\hat{C}_i = \n    \\left\\{\\begin{array}{ll}\n      \\langle {\\inred \\{ \\}},\n              {\\inred \\{ \\}},\n              \\hat{C}_{i-1}.3 \\cup \\{\\hat{a}_i\\},\n              \\hat{C}_{i-1}.4 \\cup \\{\\hat{a}_i\\}\n      \\rangle & \\ifc{a_i \\in \\hat{A}_{must}} \\\\\n      \\langle {\\inred \\{ \\}},\n              {\\inred \\{ \\}},\n              \\hat{C}_{i-1}.3 \\cup \\{\\hat{a}_i\\},\n              \\hat{C}_{i-1}.4 \n      \\rangle & \\ifc{a_i \\not\\in \\hat{A}_{must}} \\\\\n    \\end{array}\\right. \\\\\n    \\hat{o}_i = \n    \\left\\{\\begin{array}{ll}\n      \\hat{o}_i = \\hat{o}_{i-1}\\{\\hat{l}_{O_i} / \\hat{l}_{R_i} \\} & \\ifc{a_i \\in \\hat{A}_{must}} \\\\\n      \\hat{o}_i = \\hat{o}_{i-1}\\{\\{\\hat{l}_{O_i}, \\hat{l}_{R_i}\\} / \\hat{l}_{R_i} \\} & \\ifc{a_i \\not\\in \\hat{A}_{must}}\n    \\end{array}\\right. \\\\\n  \\end{array}\n\\\\\n\\\\\n\n%%% Proto %%%\n& {\\inblue \\textit{Cycle in prototype chain is detected at implementation level.}} \\\\\n\\ahf{Proto} & : \\aHeap \\times \\aLoc \\times \\abs{String} \\rightarrow \\aValue\\\\\n  & \\ahf{Proto}(\\hat{H},\\hat{l},\\hat{s})\n    =\\hat{v}_1\\sqcup\\hat{v}_2\\\\\n  & \\quad\\wherec{\n     \\hat{v}_1 =\n        \\left\\{\n          \\begin{array}{ll}\n            \\hat{H}(\\hat{l})(\\hat{s}).1.1.1\n            & \\atrue\\sqsubseteq(\\hat{s} \\dot{\\in} dom(\\hat{H}(\\hat{l}))))\\\\\n            \\bot_{Value} & \\owc \\\\\n          \\end{array}\n        \\right.\\\\\n      \\hat{L}_{proto} = \\hat{H}(\\hat{l})(\\varprop{proto}).1.1.1.2\\\\\n      \\hat{v}_2 =\n        \\left\\{\n          \\begin{array}{ll}\n            \\hat{v}_3 \\sqcup \\bigsqcup_{\\hat{l}_{proto}\\in\\hat{L}_{proto}}\\ahf{Proto}(\\hat{H},\\hat{l}_{proto},\\hat{s})\n            & \\afalse\\sqsubseteq(\\hat{s} \\dot{\\in} dom(\\hat{H}(\\hat{l})))\\\\\n            \\bot_{Value} & \\owc \\\\\n          \\end{array}\n        \\right.\\\\\n    \\hat{v}_3 =\n      \\left\\{\n      \\begin{array}{ll}\n        \\aundef_{Value} & \\ifc{\\hat{H}(\\hat{l})(\\varprop{proto}).1.1.1.1.2 \\not\\sqsubseteq \\bot_{Null}}\\\\\n        \\bot_{Value} & \\owc\\\\\n      \\end{array}\n    \\right.\\\\\n    }\\\\\n\\\\\n\n& {\\inblue \\textit{Cycle in prototype chain is detected at implementation level.}} \\\\\n\\ahf{ProtoBase} & : \\aHeap \\times \\aLoc \\times \\abs{String} \\rightarrow \\powerset{\\aLoc}\\\\\n  & \\ahf{ProtoBase}(\\hat{H},\\hat{l},\\hat{s})\n    = \\hat{L}_1\\cup\\hat{L}_2\\\\\n  & \\quad\\wherec{\n      \\hat{l} \\in dom(\\hat{H})\\\\\n      \\land\\ \\hat{L}_1 =\n        \\left\\{\n          \\begin{array}{ll}\n            \\set{\\hat{l}} & \\atrue\\sqsubseteq(\\hat{s} \\dot{\\in} dom(\\hat{H}(\\hat{l}))\\\\\n            \\set{} & \\owc \\\\\n          \\end{array}\n        \\right.\\\\\n        \\land\\ \\hat{L}_{proto} = \\hat{H}(\\hat{l})(\\varprop{proto}).1.1.1.2\\\\\n      \\land\\ \\hat{L}_2 =\n        \\left\\{\n          \\begin{array}{ll}\n            \\bigsqcup_{\\hat{l}_{proto}\\in\\hat{L}_{proto}}\\ahf{ProtoBase}(\\hat{H},\\hat{l}_{proto},\\hat{s})\n            & \\afalse\\sqsubseteq(\\hat{s} \\dot{\\in} dom(\\hat{H}(\\hat{l}))\\\\\n            \\set{} & \\owc \\\\\n          \\end{array}\n        \\right.\\\\\n        \n      \\\\\n    }\\\\\n\\\\\n\\end{array}\n\\]\n\\\\\n\n%%% Prun %%%\n\\[\n\\begin{array}{ll}\n\n\\ahf {Pruning}_1 &: \\SF{PrunExpr} \\times \\aValue \\times \\SF{IRRelOP} \\times \\aValue \\times \\aState \\rightarrow \\aState\\\\\n& \\ahf{Pruning}_1(pe, \\hat{v}_1, \\rel, \\hat{v}_2, (\\hat{H}, \\hat{C})) = (\\hat{H}_1, \\hat{C}_1)\\\\\n& \\quad\\wherec {\n%  \\hat{abs} = \\hat{abs}_1 \\sqcap \\hat{H}(\\hat{l})(\\hat{s}).2\\\\\n%  \\hat{L} = \n%    \\left\\{\n%      \\begin{array}{ll}\n%        \\{ \\#\\hat{Global}_{R}, \\#\\hat{PureLocal}_{R} \\} & \\ifc{ \\$e = x}\\\\\n%        (\\hat{V}_{cp} \\lbr e_1 \\rbr (\\hat{H}, \\hat{C})).1.2 & \\ifc{ \\$e = e_1[e_2] }\\\\\n%      \\end{array}\n%    \\right.\\\\\n  (\\hat{v}, \\hat{abs}) = \\ahf{K}_\\rel (\\hat{v}_2)\\\\\n  \\hat{s} = \n    \\left\\{\n      \\begin{array}{ll}\n        ``\\hat{x}\" & \\ifc{ pe = x}\\\\\n        \\ahf{toString}(\\hat{pv}) &\n          \\ifc{ pe = e_1[e_2]}\\\\\n          & \\wherec{\\hat{pv} = \\ahf{toPrimitive}((\\aV \\lbr e_2 \\rbr (\\hat{H}, \\hat{C})).1) }\n      \\end{array}\n    \\right.\\\\\n  \\hat{L}_{base} = \\left\\{\n    \\begin{array}{ll}\n      \\ahf{LookupBase}(\\hat{H}, \\hat{C}.1, ``x\") & \\ifc{ pe = x }\\\\\n      \\bigsqcup_{\\hat{l} \\in (\\aV \\lbr e_1 \\rbr (\\hat{H}, \\hat{C})).1.2 } \\ahf{ProtoBase}(\\hat{H}, \\hat{l}, \\hat{s}) & \\ifc{ pe = e_1[e_2] }\\\\\n    \\end{array}\n  \\right.\\\\\n  \\hat{propv} = \\left\\{\n    \\begin{array}{ll}\n      \\langle \\langle \\hat{v} \\sqcap \\hat{v}_1, \\hat{ov}.2, \\hat{ov}.3, \\hat{ov}.4 \\rangle, \\bot_{Value}, \\bot_{FunctionId} \\rangle & \\ifc {\\ahf{size}(\\hat{L}_{base}) = 1}\\\\\n        &\\wherec{\n          \\hat{l} \\in \\hat{L}_{base}\\\\\n          \\hat{ov} = \\hat{H}(\\hat{l})(\\hat{s}).1.1\\\\\n          }\\\\\n      \\bot_{PropValue} & \\owc\\\\\n    \\end{array}\n  \\right.\\\\\n  (\\hat{H}_1, \\hat{C}_1) = \n    \\left\\{\n      \\begin{array}{ll}\n      (\\hat{H}[\\hat{l} \\mapsto \\hat{H} (\\hat{l})[ \\hat{s} \\mapsto \\langle \\hat{propv},  \\hat{abs} \\sqcap \\hat{H}(\\hat{l})(\\hat{s}).2 \\rangle]], \\hat{C}) &\n         \\ifc{\\ahf{size}(\\hat{L}_{base}) = 1\\land \\{x\\} = \\gamma(\\hat{s})}\\\\\n         & \\wherec{ \\hat{l} \\in \\hat{L}_{base} }\\\\\n        (\\bot_{Heap}, \\bot_{Context}) &\n          \\ifc{ \\ahf{size}(\\hat{L}_{base}) = 0} \\\\\n        (\\hat{H}, \\hat{C}) &\n          \\owc \\\\\n      \\end{array}\n    \\right.\n}\\\\\\\\\n\n\\ahf {Pruning}_2 &: \\SF{RelExpr} \\times \\aState \\rightarrow \\aState\\\\\n& \\ahf{Pruning}_2( re, (\\hat{H}, \\hat{C})) = (\\hat{H}_1, \\hat{C}_1)\\\\\n& \\quad\\wherec {\n  e_1 ~ \\rel ~ e_2 = re\\\\\n  \\hat{v}_1 = (\\aV \\lbr e_1 \\rbr (\\hat{H}, \\hat{C})).1\\\\\n  \\hat{v}_2 = (\\aV \\lbr e_2 \\rbr (\\hat{H}, \\hat{C})).1\\\\\n  \\hat{s} = \\ahf{toString}(\\ahf{toPrimitive}(\\hat{v}_1))\\\\\n\n  \\hat{L}_{base} = \\left\\{\n    \\begin{array}{ll}\n      \\bigsqcup_{\\hat{l} \\in \\hat{v}_2.2} \\ahf{ProtoBase}(\\hat{H}, \\hat{l}, \\hat{s})  & \\ifc{ \\rel = \\TT{in}}\\\\\n      \\hat{v}_2.2  & \\owc \\\\\n    \\end{array}\n  \\right.\\\\\n  (\\hat{H}_1, \\hat{C}_1) = \\left\\{\n    \\begin{array}{ll}\n      (\\hat{H}[\\hat{l} \\mapsto \\hat{H}(\\hat{l})[\\hat{s} \\mapsto (\\hat{H}(\\hat{l})(\\hat{s})).1]], \\hat{C}) & \\ifc{\\{\\hat{l} \\} = \\hat{L}_{base} \\land \\{x\\} = \\gamma (\\hat{s}) \\land \\rel = \\TT{in}}\\\\\n      (\\ahf{DeleteAll}(\\hat{H}, \\hat{l}, \\hat{s}), \\hat{C}) & \\ifc{ \\{\\hat{l} \\} = \\hat{L}_{base} \\land \\{x\\} = \\gamma (\\hat{s}) \\land \\rel = \\TT{notIn}}\\\\\n%      ((\\bigsqcap_{\\hat{l}_1 \\in \\hat{L}_{base}} \\ahf{Delete}(\\hat{H}, \\hat{l}_1, \\hat{s})), \\hat{C}) & \\ifc{ \\{\\hat{l} \\} = \\hat{v}_1.2 \\land \\{x\\} = \\gamma (\\hat{s}) \\land \\rel = \\TT{notIn}}\\\\\n      (\\ahf{PrunInstanceof}(\\hat{l}_1, \\hat{l}, \\atrue, \\hat{H}), \\hat{C}) & \\ifc{ \\{\\hat{l} \\} = \\hat{L}_{base}  \\land \\{\\hat{l}_1 \\} = \\hat{v}_1.2  \\\\ \\land \\rel = \\TT{instanceof}}\\\\\n      (\\ahf{PrunInstanceof}(\\hat{l}_1, \\hat{l}, \\afalse, \\hat{H}), \\hat{C}) & \\ifc{ \\{\\hat{l} \\} = \\hat{L}_{base} \\land \\{\\hat{l}_1 \\} = \\hat{v}_1.2 \\\\ \\land \\rel = \\TT{notInstanceof}}\\\\\n      (\\bot_{Heap}, \\bot_{Context}) & \\ifc{ \\ahf{size}(\\hat{L}_{base}) = 0}\\\\\n      (\\hat{H}, \\hat{C}) & \\owc\\\\\n    \\end{array}\n  \\right.\n}\\\\\\\\\n\n\\ahf {PrunInstanceof} &:  \\aLoc \\times \\aLoc \\times \\abs{Bool} \\times \\aHeap \\rightarrow \\aHeap\\\\\n& \\ahf {PrunInstanceof} (\\hat{l}_{obj}, \\hat{l}_{fun}, \\hat{b}, \\hat{H}) = \\hat{H}_1 \\sqcap \\hat{H}_2\\\\\n& \\quad\\wherec{\n  \\hat{L}_{prototype} = \\hat{H}(\\hat{l}_{fun})(``prototype\").1.1.1.2\\\\\n  \\hat{L}_{proto} = \\hat{H}(\\hat{l}_{obj})(@proto).1.1.1.2\\\\\n  \\hat{L}_1 = \n      \\bigsqcup_{\\hat{l}_1 \\in \\hat{L}_{proto}} \\bigsqcup_{\\hat{l}_2 \\in \\hat{L}_{prototype}} \\ahf{inheritProto}_2(\\hat{H}, \\hat{l}_1, \\hat{l}_2, \\hat{b})\\\\\n%  \\left\\{\n%    \\begin{array}{ll}\n%      \\bigsqcup_{\\hat{l}_2 \\in \\hat{L}_{prototype}} \\ahf{inheritProto}_2(\\hat{H}, \\hat{l}_1, \\hat{l}_2, \\hat{b}) & \\ifc{ \\hat{L}_{proto} = \\{ \\hat{l}_1 \\} }\\\\\n%      \\{\\} & \\owc\n%    \\end{array}\n%  \\right.\\\\\n  \\hat{L}_2 = \n      \\bigsqcup_{\\hat{l}_1 \\in \\hat{L}_{proto}} \\bigsqcup_{\\hat{l}_2 \\in \\hat{L}_{prototype}} \\ahf{inheritProto}_1(\\hat{H}, \\hat{l}_1, \\hat{l}_2, \\hat{b})\\\\\n%  \\left\\{\n%    \\begin{array}{ll}\n%      \\bigsqcup_{\\hat{l}_1 \\in \\hat{L}_{proto}} \\ahf{inheritProto}_1(\\hat{H}, \\hat{l}_1, \\hat{l}_2, \\hat{b}) & \\ifc{ \\hat{L}_{prototype} = \\{ \\hat{l}_2 \\} }\\\\\n%      \\{\\} & \\owc\n%    \\end{array}\n%  \\right.\\\\\n  \\hat{H}_1 = \n%  \\left\\{\n%    \\begin{array}{ll}\n      \\hat{H} \\left[ \\hat{l}_{obj} \\mapsto \\hat{H}(\\hat{l}_{obj}) \\left[ @proto \\mapsto \n        \\left\\langle \n        \\begin{array}{l}\n        \\langle \\bot_{PValue}, \\hat{L}_1 \\rangle,\\\\\n        \\afalse,\\\\\n        \\afalse,\\\\\n        \\afalse\\\\\n        \\end{array}\n        \\right\\rangle      \n      \\right]\\right]\\\\\n%         & \\ifc{\\ahf{size}(\\hat{L}_{prototype}) = 1}\\\\\n%      \\hat{H} & \\owc\n%    \\end{array}\n%  \\right.\\\\\n  \\hat{H}_2 = \n%  \\left\\{\n%    \\begin{array}{ll}\n      \\hat{H} \\left[ \\hat{l}_{fun} \\mapsto \\hat{H}(\\hat{l}_{fun}) \\left[ ``prototype\" \\mapsto \n        \\left\\langle \n        \\begin{array}{l}\n        \\langle \\bot_{PValue}, \\hat{L}_2 \\rangle,\\\\\n        \\afalse,\\\\\n        \\afalse,\\\\\n        \\afalse\\\\\n        \\end{array}\n        \\right\\rangle      \n      \\right]\\right]\\\\\n%         & \\ifc{\\ahf{size}(\\hat{L}_{proto}) = 1}\\\\\n%      \\hat{H} & \\owc\n%    \\end{array}\n%  \\right.\\\\\n%  \\hat{H}_3 = \\left\\{\n%    \\begin{array}{ll}\n%      \\bigsqcap_{\\hat{l}_2 \\in (\\hat{L}_{prototype} - \\hat{l}_1)} \\ahf{PrunProto}_2(\\hat{l}_1, \\hat{l}_2, \\hat{b}, \\hat{H}) & \\ifc{ \\hat{L}_{proto} = \\{ \\hat{l}_1 \\} }\\\\\n%      \\hat{H} & \\owc\\\\\n%    \\end{array}\n%  \\right.\\\\\n}\\\\\n\\\\\n\n%%% size %%%\n\n\\ahf{size} & : \\powerset{\\aLoc} \\rightarrow {\\sf Number}\\\\\n& \\begin{array}{llll}\n  \\ahf{size}(\\{\\}) & = & {\\sf 0}\\\\\n  \\ahf{size}( \\hat{L} ) & = & {\\sf 1} + \\ahf{size}(\\hat{L}_1) & \\wherec { \\hat{l} \\in \\hat{L}\\\\ \\hat{L}_1 = \\hat{L} - \\{\\hat{l}\\}}\\\\\n\\end{array}\\\\\n\n\\end{array}\n\\]\n\\\\\n\n%%% Store %%%\n\\[\n\\begin{array}{ll}\n\n\\ahf{VarStore} & : \\aHeap \\times \\SF{Prop} \\times \\aValue \\rightarrow \\aHeap\\\\\n& \\ahf{VarStore}(\\hat{H}, x, \\hat{v}) = \\hat{H}_1 \\quad\\ifc{\\chf{getVarKind}_P(x) = \\SF{PureLocalVar}} \\\\\n& \\quad\\wherec{\\hat{H}_1 = \\hat{H}[\\avarloc{PureLocal}_R \\mapsto \\hat{H}(\\avarloc{PureLocal}_R)\n    [x \\mapsto \\langle \\hat{v},\\bot_{Bool},\\bot_{Bool},\\afalse \\rangle]]} \\\\\n& \\ahf{VarStore}(\\hat{H}, x, \\hat{v}) = \\hat{H}_1 \\quad\\ifc{\\chf{getVarKind}_P(x) = \\SF{CapturedVar}} \\\\\n& \\quad\\wherec{\\hat{H}_1 = \\bigsqcup_{\\hat{l}\\in\\hat{H}(\\avarloc{PureLocal}_R)(\\varprop{env}).1.2.2} \\ahf{VarStoreL}(\\hat{H},\\hat{l},x,\\hat{v})} \\\\\n& \\ahf{VarStore}(\\hat{H}, x, \\hat{v}) = \\hat{H}_1 \\quad\\ifc{\\chf{getVarKind}_P(x) = \\SF{CapturedCatchVar}} \\\\\n& \\quad\\wherec{\\hat{H}_1 = \\hat{H}[\\avarloc{Collapsed}_O \\mapsto \\hat{H}(\\avarloc{Collapsed}_O)\n    [x \\mapsto \\langle \\hat{v},\\bot_{Bool},\\bot_{Bool},\\afalse \\rangle]]} \\\\\n& \\ahf{VarStore}(\\hat{H}, x, \\hat{v}) = \\hat{H}_1 \\sqcup \\hat{H}_2 \n    \\quad\\ifc{\\chf{getVarKind}_P(x) = \\SF{GlobalVar}} \\\\\n& \\quad\\wherec{\n  \\hat{H}_1 = \\left\\{\n    \\begin{array}{ll}\n      \\ahf{VarStoreG}(\\hat{H}, x, \\hat{v}) & \\quad\\ifc{\\atrue\\sqsubseteq\\ahf{CanPutVar}(\\hat{H}, x)} \\\\\n      \\bot_{Heap} & \\quad\\owc\n    \\end{array}\n  \\right. \\\\\n  \\land\\ \\hat{H}_2 = \\left\\{\n    \\begin{array}{ll}\n      \\hat{H} & \\quad\\ifc{\\afalse \\sqsubseteq \\ahf{CanPutVar}(\\hat{H}, x)} \\\\\n      \\bot_{Heap} & \\quad\\owc\n    \\end{array}\n  \\right. \\\\\n} \\\\\n\\\\\n\n\\ahf{VarStoreG} & : \\aHeap \\times \\SF{Prop} \\times \\aValue \\rightarrow \\aHeap \\\\\n& \\ahf{VarStoreG}(\\hat{H}, x, \\hat{v})\n  =\n  \\hat{H}_1 \\sqcup \\hat{H}_2 \\\\\n&\\wherec{\n  \\hat{l}_g = \\avarloc{Global}_R\\ \\land\\ \\hat{ov}_{old} = \\hat{H}(\\hat{l}_g)(x).1.1\\\\\n  \\hat{H}_1 =\n  \\left\\{\n    \\begin{array}{ll}\n      \\ahf{PropStore}(\\hat{H},\\hat{l}_g,\\hat{x},\\hat{v}) & \\ifc{\\afalse\\sqsubseteq(x \\dot{\\in} dom(\\hat{H}(\\hat{l}_g)))} \\\\\n      \\bot_{Heap} & \\owc \\\\\n    \\end{array}\n   \\right.\\\\ \n  \\hat{H}_2 =\n  \\left\\{\n    \\begin{array}{ll}\n      \\hat{H}[\\hat{l}_g\\mapsto \\hat{H}(\\hat{l}_g)[x \\mapsto\n        \\langle \\hat{v},\\hat{ov}_{old}.2,\\hat{ov}_{old}.3,\\hat{ov}_{old}.4\\rangle]]\n        & \\ifc{\n          \\atrue\\sqsubseteq (x \\dot{\\in} dom(\\hat{H}(\\hat{l}_g)))\\\\\n        } \\\\\n        \\bot_{Heap} & \\owc \\\\\n    \\end{array}\n  \\right. \\\\\n}\\\\\\\\\n\n& {\\inblue \\textit{Writable is false only for function name variables, which is always determined exactly.}} \\\\\n& {\\inblue \\textit{Cycle in scope chain is detected at implementation level.}} \\\\\n\\ahf{VarStoreL} & : \\aHeap \\times \\aLoc \\times \\SF{Prop} \\times \\aValue \\rightarrow \\aHeap\\\\\n& \\ahf{VarStoreL}(\\hat{H}, \\hat{l}, x, \\hat{v}) = \\hat{H}_1 \\sqcup \\hat{H}_2 \\\\\n& \\quad\\wherec{\n    \\hat{H}_1 = \n      \\left\\{\n      \\begin{array}{ll}\n        \\hat{H}\\left[\\hat{l}\\mapsto \\hat{H}(\\hat{l})\\left[x \\mapsto \\langle\\hat{v},\\atrue,\\bot_{Bool},\\afalse\\rangle\\right]\\right] \n          & \\ifc{\\atrue \\sqsubseteq (x \\dot{\\in} dom(\\hat{H}(\\hat{l}))) ~\\land~ \\hat{H}(\\hat{l})(x).1.1.2 = \\atrue} \\\\\n        \\hat{H} \n          & \\ifc{\\atrue \\sqsubseteq (x \\dot{\\in} dom(\\hat{H}(\\hat{l}))) ~\\land~ \\hat{H}(\\hat{l})(x).1.1.2 = \\afalse} \\\\\n        \\bot_{Heap} & \\owc \\\\\n      \\end{array}\n      \\right. \\\\\n    \\hat{L}_{outer} = \\hat{H}(\\hat{l})(\\varprop{outer}).1.2.2 \\\\\n    \\hat{H}_2 = \n      \\left\\{ \n      \\begin{array}{ll}\n        \\bigsqcup_{\\hat{l}_{outer}\\in\\hat{L}_{outer}}\\ahf{VarStoreL}(\\hat{H}, \\hat{l}_{outer}, x, \\hat{v})\n          & \\afalse \\sqsubseteq (x \\dot{\\in} dom(\\hat{H}(\\hat{l}))) \\\\\n        \\bot_{Heap} & \\owc \\\\\n      \\end{array}\n      \\right. \\\\\n  } \\\\\n\\\\\n\n%\\ahf{PropStore}_{Pre} & : \\aHeap \\times \\aLoc \\times \\abs{String} \\times \\aValue \\rightarrow \\aHeap \\\\\n%& \\ahf{PropStore}_{Pre}(\\hat{H},\\hat{l},\\hat{s},\\hat{v})\n%  = \\hat{H}_2\\\\\n%& \\quad\\wherec{\n%\\hat{H}_1 = \\left\\{\n%    \\begin{array}{ll}\n%      \\hat{H}\\left[\\hat{l}\\mapsto \\hat{H}(\\hat{l})\\left[\\hat{s}\\mapsto \\langle\\hat{v},\\atrue,\\atrue,\\atrue\\rangle\\right]\\right] & \\ifc{\\afalse\\sqsubseteq(\\hat{s} \\dot{\\in} dom(\\hat{H}(\\hat{l})))} \\\\\n%      \\hat{H} & \\owc \\\\\n%    \\end{array}\n%  \\right. \\\\\n%  \\hat{ov}_{old}=\\hat{H}_1(\\hat{l})(\\hat{s}).1.1\\\\\n%  \\hat{H}_2 = \\left\\{\n%    \\begin{array}{ll}\n%      \\hat{H}_1\\left[\\hat{l}\\mapsto \\hat{H}_1(\\hat{l})\\left[\\hat{s}\\mapsto\n%          \\langle \\hat{v},\\hat{ov}_{old}.2,\\hat{ov}_{old}.3,\\hat{ov}_{old}.4\\rangle\n% \\set{H(l)(x)\\rwith value=v}\n%        \\right]\\right] & \\ifc{\\atrue\\sqsubseteq (\\hat{s} \\dot{\\in} dom(\\hat{H}(\\hat{l})))}\\\\\n%      \\hat{H}_1 & \\owc \\\\\n%    \\end{array}\n%  \\right. \\\\\n%}\\\\\n%\\\\\n\n\\ahf{PropStore} & : \\aHeap \\times \\aLoc \\times \\abs{String} \\times \\aValue \\rightarrow \\aHeap \\\\\n& \\ahf{PropStore}(\\hat{H},\\hat{l},\\hat{s},\\hat{v})\n  = \\hat{H}_1\\sqcup\\hat{H}_2\\\\\n& \\quad\\wherec{\n\\hat{H}_1 = \\left\\{\n    \\begin{array}{ll}\n      \\hat{H}\\left[\\hat{l}\\mapsto \\hat{H}(\\hat{l})\\left[\\hat{s}\\mapsto \\langle\\hat{v},\\atrue,\\atrue,\\atrue\\rangle\\right]\\right] & \\ifc{\\afalse\\sqsubseteq(\\hat{s} \\dot{\\in} dom(\\hat{H}(\\hat{l})))} \\\\\n      \\bot_{Heap} & \\owc \\\\\n    \\end{array}\n  \\right. \\\\\n  \\hat{ov}_{old}=\\hat{H}(\\hat{l})(\\hat{s}).1.1\\\\\n  \\hat{H}_2 = \\left\\{\n    \\begin{array}{ll}\n      \\hat{H}\\left[\\hat{l}\\mapsto \\hat{H}(\\hat{l})\\left[\\hat{s}\\mapsto\n          \\langle \\hat{v},\\hat{ov}_{old}.2,\\hat{ov}_{old}.3,\\hat{ov}_{old}.4\\rangle\n% \\set{H(l)(x)\\rwith value=v}\n        \\right]\\right] & \\ifc{\\atrue\\sqsubseteq (\\hat{s} \\dot{\\in} dom(\\hat{H}(\\hat{l})))}\\\\\n      \\bot_{Heap} & \\owc \\\\\n    \\end{array}\n  \\right. \\\\\n}\\\\\n\\\\\n\n\\ahf{ReturnStore} & : \\aHeap \\times \\aValue \\rightarrow \\aHeap\\\\\n& \\ahf{ReturnStore}(\\hat{H}, \\hat{v}) = \\hat{H}[\\avarloc{PureLocal}_R \\mapsto \\hat{H}(\\avarloc{PureLocal}_R)[\\varprop{return} \\mapsto \\hat{v}]]\\\\\n\\\\\n\\end{array}\n\\]\n\\\\\n\n%%% to %%%\n\\[\n\\begin{array}{ll}\n% \\chf{newLocation} & : \\SF{Unit} \\rightarrow \\SF{Loc} \\\\\n% & \\chf{newLocation}()\n%   = l_{new}\\\\\n% \\\\\n\\ahf{toBoolean} & : \\aValue \\rightarrow \\abs{Bool} \\\\\n& \\ahf{toBoolean}(\\hat{v})\n  = \\langle\\langle \\bot,\\bot,\\displaystyle\\bigsqcup_{n=1\\cdots8}\\hat{b}_n,\\bot,\\bot\\rangle,\\{\\}\\rangle \\\\\n& \\wherec{\n  \\hat{b}_1 = \\afalse \\quad\\ifc{\\aundef\\sqsubseteq\\hat{v}.1.1}\\\\\n  \\hat{b}_2 = \\afalse \\quad\\ifc{\\anull\\sqsubseteq\\hat{v}.1.2}\\\\\n  \\hat{b}_3 = \\hat{v}.1.3 \\\\\n  \\hat{b}_4 = \\afalse \\quad\\ifc{\\hat{0}\\sqsubseteq\\hat{v}.1.4\\lor\\hat{\\SF{NaN}}\\sqsubseteq\\hat{v}.1.4} \\\\\n  \\hat{b}_5 = \\atrue \\quad\\ifc{\\hat{v}.1.4\\not\\sqsubseteq\\bot_{number}\\land\\hat{v}.1.4\\neq\\hat{0}\\land\\hat{v}.1.4\\neq\\hat{\\SF{NaN}}} \\\\\n  \\hat{b}_6 = \\afalse \\quad\\ifc{\\hat{``\"}\\sqsubseteq\\hat{v}.1.5} \\\\\n  \\hat{b}_7 = \\atrue \\quad\\ifc{\\hat{v}.1.5\\not\\sqsubseteq\\bot_{string}\\land\\hat{v}.1.5\\neq\\hat{``\"}}\\\\\n  \\hat{b}_8 = \\atrue \\quad\\ifc{\\hat{v}.2\\not\\sqsubseteq\\bot_{Loc}}\\\\\n}\\\\\\\\\n\n\\ahf{toNumber} & : \\abs{PValue} \\rightarrow \\abs{Number} \\\\\n& \\ahf{toNumber}(\\hat{pv})\n  = \\hat{n}_1\\sqcup\\hat{n}_2\\sqcup\\hat{n}_3\\sqcup\\hat{n}_4\\sqcup\\hat{n}_5 \\\\\n& \\quad\\wherec{\n  \\hat{n}_1 = \\hat{\\SF{NaN}}\\quad\\ifc{\\aundef_{Value}\\sqsubseteq\\hat{pv}}\\\\\n  \\hat{n}_2 = \\hat{0}\\quad\\ifc{\\anull\\sqsubseteq\\hat{pv}\\lor\\afalse\\sqsubseteq\\hat{pv}}\\\\\n  \\hat{n}_3 = \\hat{1}\\quad\\ifc{\\atrue\\sqsubseteq\\hat{pv}}\\\\\n  \\hat{n}_4 = \\hat{pv}.4\\\\\n  \\hat{n}_5 = {\\inred \\ahf{Str2Num}(\\hat{pv})}\\quad\\ifc{\\hat{pv}.5\\not\\sqsubseteq\\bot_{string}}\\\\\n}\\\\\\\\\n\n\\ahf{toString} & : \\abs{PValue} \\rightarrow \\abs{String} \\\\\n& \\ahf{toString}(\\hat{pv})\n  = \\hat{s}_1\\sqcup\\hat{s}_2\\sqcup\\hat{s}_3\\sqcup\\hat{s}_4\\sqcup\\hat{s}_5\\\\\n& \\quad\\wherec{\n  \\hat{s}_1 = \\hat{``undefined\"}\\quad\\ifc{\\hat{pv}.1\\not\\sqsubseteq\\bot_{Undefined}} \\\\\n  \\hat{s}_2 = \\hat{``null\"}\\quad\\ifc{\\hat{pv}.2\\not\\sqsubseteq\\bot_{Null}} \\\\\n  \\hat{s}_3 = \\hat{``pv.3\"}\\quad\\ifc{\\hat{pv}.3\\not\\sqsubseteq\\bot_{Bool}} \\\\\n  \\hat{s}_4 = \\hat{``pv.4\"}\\quad\\ifc{\\hat{pv}.4\\not\\sqsubseteq\\bot_{Number}} \\\\\n  \\hat{s}_5 = \\hat{pv}.5\\\\\n}\\\\\n\\\\\n\n\\ahf{toStringSet} & : \\abs{PValue} \\rightarrow \\powerset{\\abs{String}} \\\\\n& \\ahf{toStringSet}(\\hat{pv})\n  = \\hat{ss} ~ \\textit{with redundancies removed}\\\\\n& \\quad\\wherec{\n  \\hat{ss}_1 = \n    \\left\\{\\begin{array}{ll}\n      \\{ \\hat{``undefined\"} \\} & \\ifc{\\hat{pv}.1\\not\\sqsubseteq\\bot_{Undefined}} \\\\\n      \\{\\} & \\owc \\\\\n    \\end{array}\\right. \\\\\n  \\hat{ss}_2 = \n    \\left\\{\\begin{array}{ll}\n      \\{ \\hat{``null\"} \\} & \\ifc{\\hat{pv}.2\\not\\sqsubseteq\\bot_{Null}} \\\\\n      \\{\\} & \\owc \\\\\n    \\end{array}\\right. \\\\\n  \\hat{ss}_3 = \n    \\left\\{\\begin{array}{ll}\n      \\{ \\hat{``pv.3\"} \\} & \\ifc{\\hat{pv}.3\\not\\sqsubseteq\\bot_{Bool}} \\\\\n      \\{\\} & \\owc \\\\\n    \\end{array}\\right. \\\\\n  \\hat{ss}_4 = \n    \\left\\{\\begin{array}{ll}\n      \\{ \\hat{``pv.4\"} \\} & \\ifc{\\hat{pv}.4\\not\\sqsubseteq\\bot_{Number}} \\\\\n      \\{\\} & \\owc \\\\\n    \\end{array}\\right. \\\\\n  \\hat{ss}_5 = \n    \\left\\{\\begin{array}{ll}\n      \\{ \\hat{pv}.5 \\} & \\ifc{\\hat{pv}.5\\not\\sqsubseteq\\bot_{String}} \\\\\n      \\{\\} & \\owc \\\\\n    \\end{array}\\right. \\\\\n  \\hat{ss} = \\hat{ss}_1\\cup\\hat{ss}_2\\cup\\hat{ss}_3\\cup\\hat{ss}_4\\cup\\hat{ss}_5\n}\\\\\n\\\\\n\\end{array}\n\\]\n\n\\[\n\\begin{array}{ll}\n\n\\ahf{toObject} & : \\aHeap \\times \\abs{Context} \\times \\aValue \\times \\abs{Address} \\rightarrow \\aHeap \\times \\abs{Context} \\times \\aValue \\times \\powerset{\\abs{Exception}} \\\\\n& \\ahf{toObject}(\\hat{H}, \\hat{C}, \\hat{v}, \\hat{a})\n  = (\\langle\\bot_{PValue},\\hat{L}_3\\rangle,\\hat{H}_4,\\hat{C}_4,\\hat{es}) \\\\\n  & \\quad\\wherec{\n    \\hat{L} = \\hat{v}.2\\\\\n    \\hat{o}_1 =\n    \\left\\{\n      \\begin{array}{ll}\n        \\ahf{NewString}(\\hat{v}.1.5) & \\ifc{\\hat{v}.1.5\\not\\sqsubseteq\\bot_{string}} \\\\\n        \\bot_{Obj} & \\owc\\\\\n      \\end{array}\n    \\right.\\\\\n    \\hat{o}_2 =\n    \\left\\{\n      \\begin{array}{ll}\n        \\ahf{NewBoolean}(\\hat{v}.1.3) & \\ifc{\\hat{v}.1.3\\not\\sqsubseteq\\bot_{boolean}} \\\\\n        \\bot_{Obj} & \\owc\\\\\n      \\end{array}\n    \\right.\\\\\n    \\hat{o}_3 =\n    \\left\\{\n      \\begin{array}{ll}\n        \\ahf{NewNumber}(\\hat{v}.1.4) & \\ifc{\\hat{v}.1.4\\not\\sqsubseteq\\bot_{number}} \\\\\n        \\bot_{Obj} & \\owc\\\\\n      \\end{array}\n    \\right.\\\\\n    \\hat{es} = \n    \\left\\{\n      \\begin{array}{ll}\n        \\{\\hat{\\SF{TypeException}}\\} & \\ifc{\\hat{v}.1.1\\not\\sqsubseteq\\bot_{undef}\\lor \\hat{v}.1.2\\not\\sqsubseteq\\bot_{null}} \\\\\n        \\{\\} & \\owc\\\\\n      \\end{array}\n    \\right.\\\\\n    \\hat{o} = \\hat{o}_1 \\sqcup \\hat{o}_2 \\sqcup \\hat{o}_3 \\\\\n\n    \\inblue (\\hat{H}_1, \\hat{C}_1) = \\ahf{Oldify}(\\hat{H}, \\hat{C}, \\hat{a}_{new})\n    \\quad\\comment{{\\inblue // Recency Abstraction}}\\\\\n    \\inblue\\hat{l}_{R} = (\\hat{a}, \\hat{Recent})\n    \\quad\\comment{{\\inblue // Recency Abstraction}}\\\\\n\n    (\\hat{L}_1, \\hat{H}_2, \\hat{C}_2) = \\left\\{\n      \\begin{array}{ll}\n        (\\{\\hat{l}_R\\}, \\hat{H}_1[\\hat{l}_R\\mapsto \\hat{o}], \\hat{C}_1)& \\quad\\ifc{\\hat{o}\\not\\sqsubseteq \\bot_{Obj}} \\\\\n        (\\set{}, \\bot_{Heap}, \\bot_{Context})& \\owc\n      \\end{array}\n    \\right.\\\\\n    (\\hat{L}_2, \\hat{H}_3, \\hat{C}_3) = \\left\\{\n      \\begin{array}{ll}\n        (\\hat{L}, \\hat{H}, \\hat{C}& \\quad\\ifc{\\hat{L}\\not\\sqsubseteq \\set{}} \\\\\n        (\\set{}, \\bot_{Heap}, \\bot_{Context})& \\owc\n      \\end{array}\n    \\right.\\\\\n    \n    \\hat{L}_3 = \\hat{L}_1\\sqcup\\hat{L}_2 \\land\\ \\hat{H}_4 = \\hat{H}_2 \\sqcup \\hat{H}_3\\land\\ \\hat{C}_4 = \\hat{C}_2 \\sqcup \\hat{C}_3\\\\\n  }\\\\\\\\\n\n\\ahf{toPrimitive} & : \\aValue \\rightarrow \\abs{PValue} \\\\\n& \\ahf{toPrimitive}(\\hat{v})\n  = \\hat{v}.1 \\sqcup \\inred \\ahf{Obj2Str}(\\hat{v}.2) \\\\\n\\\\\n\n\n\n\n%%% TypeTag %%%\n\n& {\\inblue \\textit{For all case of }\\hat{s}_n\\textit{ if the condition is false, the value of }\\hat{s}_n\\textit{ is }\\bot_{String}.} \\\\\n\\ahf{TypeTag} & : \\aHeap \\times \\aValue \\rightarrow \\abs{String}\\\\\n& \\ahf{TypeTag}(\\hat{H},\\hat{v}) = \\hat{s}_1\\sqcup\\hat{s}_2\\sqcup\\hat{s}_3\\sqcup\\hat{s}_4\\sqcup\\hat{s}_5\\sqcup\\hat{s}_6\\sqcup\\hat{s}_7 \\\\\n& \\wherec{\n  \\begin{array}{ll}\n  \\hat{s}_1 = \\hat{``number\"} & \\ifc{\\hat{v}.1.4\\not\\sqsubseteq\\bot_{number}} \\\\\n  \\hat{s}_2 = \\hat{``boolean\"} & \\ifc{\\hat{v}.1.3\\not\\sqsubseteq\\bot_{boolean}} \\\\\n  \\hat{s}_3 = \\hat{``string\"} & \\ifc{\\hat{v}.1.5\\not\\sqsubseteq\\bot_{string}} \\\\\n  \\hat{s}_4 = \\hat{``object\"} & \\ifc{\\hat{v}.2\\not\\sqsubseteq\\bot_{Loc}\\land\\afalse\\sqsubseteq\\bigsqcup_{\\hat{l}\\in\\hat{v}.2}\\ahf{IsCallable}(\\hat{H},\\hat{l})} \\\\\n  \\hat{s}_5 = \\hat{``function\"} & \\ifc{\\hat{v}.2\\not\\sqsubseteq\\bot_{Loc}\\land\\atrue\\sqsubseteq\\bigsqcup_{\\hat{l}\\in\\hat{v}.2}\\ahf{IsCallable}(\\hat{H},\\hat{l})} \\\\\n  \\hat{s}_6 = \\hat{``object\"} & \\ifc{\\hat{v}.1.2\\not\\sqsubseteq\\bot_{null}} \\\\\n  \\hat{s}_7 = \\hat{``undefined\"} & \\ifc{\\hat{v}.1.1\\not\\sqsubseteq\\bot_{undef}} \\\\\n  \\end{array}\\\\\n  }\\\\\n\\\\\n\\\\\n%%% validity %%%\n\n\\ahf{validity}_1 & : \\sf{Expression} \\times \\aState \\rightarrow {\\sf Boolean}\\\\\n& \\ahf{validity}_1(e, (\\hat{H}, \\hat{C})) = b\\\\\n& \\quad\\wherec {\n  \\hat{v} = (\\aV \\lbr e \\rbr (\\hat{H}, \\hat{C})).1\\\\\n  b = \\left\\{\n    \\begin{array}{ll}\n      \\vtrue & \n        \\ifc{ \\hat{v}.1.1 \\sqsubseteq \\bot_{Undef} \\land \\hat{v}.1.2 \\sqsubseteq \\bot_{Null} \\land (\\hat{v}.1.4 \\sqsubseteq \\hat{\\sf UInt} \\lor \\hat{v}.1.4 \\sqsubseteq \\hat{\\sf NUInt})\\\\\n           \\land \\hat{v}.1.5 \\sqsubseteq \\bot_{String} \\land \\hat{v}.2 = \\{\\} }\\\\\n      \\vfalse & \\owc\n    \\end{array}\n  \\right.\n}\\\\\n\\\\\n\n\\ahf{validity}_2 & : \\sf{Expression} \\times \\sf{Expression} \\times \\aState \\rightarrow {\\sf Boolean}\\\\\n& \\ahf{validity}_2(e_1, e_2, (\\hat{H}, \\hat{S})) = \\ahf{validity}_1(e_1, \\hat{S}) \\land \\ahf{validity}_1(e_2, \\hat{S})\\\\\\\\\n\n\\ahf{validity}_3 & : \\sf{Expression} \\times \\sf{Expression} \\times \\sf{Expression} \\times \\aState \\rightarrow {\\sf Boolean}\\\\\n& \\ahf{validity}_3(e_1, e_2, e_3, (\\hat{H}, \\hat{S})) = \\ahf{validity}_1(e_1, \\hat{S}) \\land \\ahf{validity}_1(e_2, \\hat{S}) \\land \\ahf{validity}_1(e_3, \\hat{S})\\\\\n\\\\\\\\\n\n%%% X %%%\n\n\\ahf{X} & : \\SF{RelExpr} \\rightarrow \\aState \\rightarrow \\aState\\\\\n& \\ahf{X} \\lbr re \\rbr (\\hat{H}, \\hat{C}) = (\\hat{H}_1, \\hat{C}_1)\\\\\n& \\quad\\wherec{\n  e_1 ~ \\rel ~ e_2 = re\\\\\n  \\hat{v}_1 = (\\aV \\lbr e_1 \\rbr (\\hat{H}, \\hat{C})).1\\\\\n  \\hat{v}_2 = (\\aV \\lbr e_2 \\rbr (\\hat{H}, \\hat{C})).1\\\\\n  (\\hat{H}_1, \\hat{C}_1) = \n    \\left\\{ \n      \\begin{array}{ll}\n        \\ahf {Pruning}_1 (e_1, \\hat{v}_1, \\rel, \\hat{v}_2, (\\hat{H}, \\hat{C})) & \n          \\ifc{\\rel \\in \\SF{IRRelOP} \\land e_1 \\in \\SF{PrunExpression}}\\\\\n        \\ahf {Pruning}_2 ( re, (\\hat{H}, \\hat{C})) & \n          \\ifc{\\rel \\in \\SF{IRObjOP}}\\\\\n        (\\hat{H}, \\hat{C}) & \\owc\\\\\n      \\end{array}\n    \\right.\\\\\n}\\\\\n\n\n\\end{array}\n\\]\n\\\\\n\n% &  \\left\\{\n%     \\begin{array}{l@{\\quad\\quad}l}\n%       \\vfalse   & \\ifc{v=\\SF{undefined}} \\\\\n%       \\vfalse   & \\ifc{v=\\SF{null}} \\\\\n%       v         & \\ifc{v\\in\\SF{Boolean}} \\\\\n%       \\vfalse   & \\ifc{v\\in\\SF{Number}\\land v\\in\\set{\\sf 0,NaN}} \\\\\n%       \\vtrue    & \\ifc{v\\in\\SF{Number}\\land v\\not\\in\\set{\\sf 0,NaN}} \\\\\n%       \\vfalse   & \\ifc{v\\in\\SF{String}\\land v=``\"} \\\\\n%       \\vtrue    & \\ifc{v\\in\\SF{String}\\land v\\neq``\"} \\\\\n%       \\vtrue    & \\ifc{v\\in\\SF{Loc}}\n%     \\end{array}\n%   \\right.\\\\\n\n\n\n% \\inred\\ahf{iteratorInit} & : \\aObj \\times \\powerset{\\abs{Prop}} \\times\n% \\abs{Number} \\rightarrow \\aObj \\\\\n% & \\ahf{iteratorInit}(\\hat{o},\\hat{P},\\hat{n})\n%   = \n% \\\\\n% \\\\\n\n%\\[\n%\\begin{array}{ll}\n% \\ahf{NewExceptionObject} & : \\abs{Exception} \\rightarrow \\abs{Obj} \\\\\n% & \\ahf{NewExceptionObject}(\\hat{exc}) = \\hat{o}_1\\sqcup\\hat{o}_2\\sqcup\\hat{o}_3\\\\\n% & \\quad\\wherec{\n%   \\begin{array}{ll}\n%     \\hat{o}_1=\\ahf{NewObject}(\\avarloc{RefErrProto})&\\ifc{\\hat{\\SF{ReferenceError}}\\sqsubseteq \\hat{exc}} \\\\\n%     \\hat{o}_2=\\ahf{NewObject}(\\avarloc{RangeErrProto})&\\ifc{\\hat{\\SF{RangeError}}\\sqsubseteq \\hat{exc}} \\\\\n%     \\hat{o}_3=\\ahf{NewObject}(\\avarloc{TypeErrProto})&\\ifc{\\hat{\\SF{TypeError}}\\sqsubseteq \\hat{exc}} \\\\\n%   \\end{array}\n% }\n% \\\\\\\\\n% \\ahf{NewExceptionLoc} & : \\abs{Exception} \\rightarrow \\abs{Loc} \\\\\n% & \\chf{NewExceptionObject}(exc) =\\left\\{\n%     \\begin{array}{ll}\n%       \\varloc{RefErr}&\\ifc{\\hat{\\SF{ReferenceError}}\\sqsubseteq \\hat{exc}} \\\\\n%       \\varloc{RangeErr}&\\ifc{\\hat{\\SF{RangeError}}\\sqsubseteq \\hat{exc}} \\\\\n%       \\varloc{TypeErr}&\\ifc{\\hat{\\SF{TypeError}}\\sqsubseteq \\hat{exc}} \\\\\n%     \\end{array}\n%   \\right.\n% \\end{array}\n\n%\n%\\ahf{X} & : \\powerset{\\abs{RelExpr}} \\rightarrow \\aState \\times \\aState \\rightarrow \\aState \\times \\aState\\\\\n%& \\ahf{X} \\lbr relSet \\rbr \\left( (\\hat{H}, \\hat{C}), \\hat{S} \\right) = \\left( (\\hat{H}_1, \\hat{C}_1), \\hat{S}_1 \\right)\\\\\n%& \\quad\\wherec{\n%  (\\hat{H}_1, \\hat{C}_1) = \n%    \\left\\{ \n%      \\begin{array}{ll}\n%        \\left( \\bigsqcap_{\\hat{re} \\in relSet} \\ahf {Pruning}_1(\\$e_1,\\hat{v}_1, \\rel, \\hat{v}_2, (\\hat{H}, \\hat{C}))\\right) & \n%          \\ifc{ relSet \\not= \\O \\land \\rel \\in \\abs{IRRelOP}}\\\\\n%          & \\wherec{ \\$e_1 \\rel e_2 = \\hat{re}\\\\\n%              (\\hat{v}_1, \\hat{es}_1) = \\hat{\\V}_{cp} \\lbr \\$e_1 \\rbr (\\hat{H}, \\hat{C})\\\\\n%              (\\hat{v}_2, \\hat{es}_2) = \\hat{\\V}_{cp} \\lbr e_2 \\rbr (\\hat{H}, \\hat{C}) }\\\\\n%        \\left( (\\hat{H}, \\hat{C}), \\hat{S} \\right) & \\owc\\\\\n%      \\end{array}\n%    \\right.\\\\\n%  \\hat{S}_1 = \n%    \\hat{S} \\sqcup \\left( \\bigsqcup_{\\hat{re} \\in relSet} (\\ahf{RaiseException} (\\hat{H}, \\hat{C}, \\hat{es}_1) \\sqcup \\ahf{RaiseException} (\\hat{H}, \\hat{C}, \\hat{es}_2)) \\right)\\\\\n%      \\quad \\wherec{ \\$e_1 \\rel e_2 = \\hat{re} \\\\\n%         (\\hat{v}_1, \\hat{es}_1) = \\aV_{cp} \\lbr \\$e_1 \\rbr (\\hat{H}, \\hat{C})\\\\\n%         (\\hat{v}_2, \\hat{es}_2) = \\aV_{cp} \\lbr e_2 \\rbr (\\hat{H}, \\hat{C})}\\\\\n%}\\\\\n%\\\\\\\\\n\n%\\ahf {PrunProto} &:  \\aLoc \\times \\aLoc \\times \\abs{Bool} \\times \\aHeap \\rightarrow \\aHeap\\\\\n%& \\ahf {PrunProto} (\\hat{l}_1, \\hat{l}_2, \\hat{b}, \\hat{H}) = \\hat{H}_1\\\\\n%& \\quad \\wherec{\n%  \\hat{L}_{proto} = \\bigsqcup_{\\hat{l} \\in \\hat{H}(\\hat{l}_1)(@proto).1.1.1.2} \\ahf{inheritProto}_1(\\hat{H}, \\hat{l}, \\hat{l}_2, \\hat{b})\\\\\n%  \\hat{H}_2 = \\hat{H}[\\hat{l}_1 \\mapsto \\hat{H}(\\hat{l}_1)[@proto \\mapsto \\langle \\langle \\bot_{PValue}, \\hat{L}_{proto} \\rangle, \\afalse, \\afalse, \\afalse \\rangle]]\\\\\n%  \\hat{H}_1 = \\left\\{\n%    \\begin{array}{ll}\n%      \\bigsqcap_{\\hat{l} \\in (\\hat{L}_{proto} - \\hat{l}_2)} \\ahf{PrunProto}(\\hat{l}, \\hat{l}_2, \\hat{b}, \\hat{H}_2) & \\ifc{ \\hat{L}_{proto} \\not= \\O}\\\\\n%      \\hat{H} & \\owc\\\\\n%    \\end{array}        \n%  \\right.\\\\\n%}\n%\\\\\\\\\n%\\ahf {PrunProto}_2 &:  \\aLoc \\times \\aLoc \\times \\abs{Bool} \\times \\aHeap \\rightarrow \\aHeap\\\\\n%& \\ahf {PrunProto} (\\hat{l}_1, \\hat{l}_2, \\hat{b}, \\hat{H}) = \\hat{H}_1\\\\\n%& \\quad \\wherec{\n%  \\hat{L}_{proto} = \\bigsqcup_{\\hat{l} \\in \\hat{H}(\\hat{l}_2)(@proto).1.1.1.2} \\ahf{inheritProto}_2(\\hat{H}, \\hat{l}_1, \\hat{l}, \\hat{b})\\\\\n%  \\hat{H}_2 = \\hat{H}[\\hat{l}_2 \\mapsto \\hat{H}(\\hat{l}_2)[@proto \\mapsto \\langle \\langle \\bot_{PValue}, \\hat{L}_{proto} \\rangle, \\afalse, \\afalse, \\afalse \\rangle]]\\\\\n%  \\hat{H}_1 = \\left\\{\n%    \\begin{array}{ll}\n%      \\bigsqcap_{\\hat{l} \\in \\hat{L}_{proto}} \\ahf{PrunProto}(\\hat{l}_1, \\hat{l}, \\hat{b}, \\hat{H}_2) & \\ifc{ \\hat{L}_{proto} \\not= \\O}\\\\\n%      \\hat{H} & \\owc\\\\\n%    \\end{array}        \n%  \\right.\\\\\n%}\n\n%\n%\\ahf{GetPropLoc} & : \\aHeap \\times \\aLoc \\times \\abs{String} \\rightarrow \\powerset{\\aLoc}\\\\\n%& \\ahf{GetPropLoc} (\\hat{H}, \\hat{l}, \\hat{s}) = \\hat{L}_1 \\sqcup \\hat{L}_2\\\\\n%&  \\quad\\wherec{\n%    \\hat{L}_{proto} = \\hat{H}(\\hat{l})(@proto).1.1.1.2\\\\\n%    \\hat{L}_1 = \\left\\{\n%      \\begin{array}{ll}\n%        \\{\\hat{l}\\} & \n%        \\ifc{ \\atrue \\sqsubseteq \\ahf{HasOwnProperty}(\\hat{H}, \\hat{l}, \\hat{s}) }\\\\\n%        \\{\\} & \\owc\\\\\n%      \\end{array}\n%    \\right.\\\\\n%    \\hat{L}_2 = \\left\\{\n%      \\begin{array}{ll}\n%        \\bigsqcup_{\\hat{l}_{proto} \\in \\hat{L}_{proto}} \\ahf{GetPropLoc}(\\hat{H}, \\hat{l}_{proto}, \\hat{s}) & \n%        \\ifc{ \\afalse \\sqsubseteq \\ahf{HasOwnProperty}(\\hat{H}, \\hat{l}, \\hat{s}) }\\\\\n%        \\{\\} & \\owc\\\\\n%      \\end{array}\n%    \\right.\n%  }\n\n%\\\\\\\\\n%\\ahf{getLoc} & : \\aHeap \\times \\aLoc \\rightarrow \\powerset{\\aLoc}\\\\\n%& \\begin{array}{ll}\n%  \\ahf{getLoc}(\\hat{H}, \\hat{l}) = \\{\\hat{l}\\} \\cup (\\bigcup_{\\hat{l}_1 \\in \\hat{v}.2} \\ahf{getLoc}(\\hat{l}_1))\\\\\n%  \\quad\\wherec{\n%    \\hat{v} = \\hat{H}(\\hat{l})\\\\\n%  }\n%\\end{array}\\\\\n\n\n\n\\newpage\n\\section{Context-sensitivity}\\label{sec:context-sensitivity}\n{\\inblue\\tt .../jsaf/analysis/typing/CallContext.scala}\\\\\n\n% Context-insensitive\n\\subsection{Context-insensitive}\n\\[\n\\begin{array}{rcl}\n\\abs{CallContext} & = & \\abs{Address} \\\\\n\\abs{globalCallContext} & = & \\avarloc{GlobalCallsite} \\\\\n\\\\\n\n\\ahf{NewCallContext} & : & \\abs{CallContext} \\times \\SF{FunctionId} \\times \\abs{Loc} \\times \\powerset{\\abs{Loc}} \\rightarrow \\powerset{\\abs{CallContext} \\times \\abs{Obj}} \\\\\n& & \\comment{\\inblue caller context, callee function, callsite, this}  \\\\\n%& & \\ahf{NewCallContext}(\\hat{cc}, fid, \\hat{l}, \\hat{L}) = \\{ (\\hat{cc}, \\ahf{NewPureLocal}(\\{\\hat{l}\\}, \\hat{L})) \\} \\\\\n& & \\ahf{NewCallContext}(\\hat{cc}, fid, \\hat{l}, \\hat{L}) = \\\\\n& & \\quad\\quad \\left\\{\n       \\begin{array}{ll}\n         \\{ \\langle \\avarloc{GlobalCallsite}, ~ \\ahf{NewPureLocal}(\\{\\hat{l}\\}, \\hat{L}) \\rangle \\} & \\ifc{\\chf{isUserFunction}_P(fid)} \\\\\n         \\{ \\langle \\hat{l}.1, ~ \\ahf{NewPureLocal}(\\{\\hat{l}\\}, \\hat{L}) \\rangle \\} & \\owc \\\\\n       \\end{array}\n     \\right.\\\\\n\\end{array}\n\\]\n\n\n% 1-callsite sensitivity\n\\subsection{1-callsite sensitivity}\n\\[\n\\begin{array}{rcl}\n\\abs{CallContext} & = & \\abs{Address} \\times \\abs{Address} \\\\\n\\abs{globalCallContext} & = & (\\avarloc{GlobalCallsite}, \\avarloc{GlobalCallsite}) \\\\\n\\\\\n\n\\ahf{NewCallContext} & : & \\abs{CallContext} \\times \\SF{FunctionId} \\times \\abs{Loc} \\times \\powerset{\\abs{Loc}} \\rightarrow \\powerset{\\abs{CallContext} \\times \\abs{Obj}} \\\\\n& & \\comment{\\inblue caller context, callee function, callsite, this}  \\\\\n& & \\ahf{NewCallContext}(\\hat{cc}, fid, \\hat{l}, \\hat{L}) = \\\\\n& & \\quad\\quad \\left\\{\n       \\begin{array}{ll}\n         \\{ \\langle (\\hat{l}.1, \\avarloc{GlobalCallsite}), ~ \\ahf{NewPureLocal}(\\{\\hat{l}\\}, \\hat{L}) \\rangle \\} & \\ifc{\\chf{isUserFunction}_P(fid)} \\\\\n         \\{ \\langle (\\hat{cc}.1, \\hat{l}.1), ~ \\ahf{NewPureLocal}(\\{\\hat{l}\\}, \\hat{L}) \\rangle \\} & \\owc \\\\\n       \\end{array}\n     \\right.\\\\\n\\end{array}\n\\]\n\n\n% k-callsite sensitivity\n\\subsection{k-callsite sensitivity}\n\\[\n\\begin{array}{rcl}\n\\abs{CallContext} & = & \\abs{Address} \\listd \\\\\n\\abs{globalCallContext} & = & \\SF{nil} \\\\\n\\\\\n\n\\ahf{NewCallContext} & : & \\abs{CallContext} \\times \\SF{FunctionId} \\times \\abs{Loc} \\times \\powerset{\\abs{Loc}} \\rightarrow \\powerset{\\abs{CallContext} \\times \\abs{Obj}} \\\\\n& & \\comment{\\inblue caller context, callee function, callsite, this}  \\\\\n& & \\ahf{NewCallContext}(\\hat{cc}, fid, \\hat{l}, \\hat{L}) = \\\\\n& & \\quad\\quad \\left\\{\n       \\begin{array}{ll}\n         \\{ \\langle (\\hat{l}.1 :: \\hat{cc})|_{k}, ~ \\ahf{NewPureLocal}(\\{\\hat{l}\\}, \\hat{L}) \\rangle \\} & \\ifc{\\chf{isUserFunction}_P(fid)} \\\\\n         \\{ \\langle (\\hat{l}.1 :: \\hat{cc})|_{k+1}, ~ \\ahf{NewPureLocal}(\\{\\hat{l}\\}, \\hat{L}) \\rangle \\} & \\owc \\\\\n       \\end{array}\n     \\right.\\\\\n\\end{array}\n\\]\n\n\n% callsite-set sensitivity\n\\subsection{callsite-set sensitivity}\n\\[\n\\begin{array}{rcl}\n\\abs{CallContext} & = & \\powerset{\\abs{Address}} \\\\\n\\abs{globalCallContext} & = & \\set{ } \\\\\n\\\\\n\n\\ahf{NewCallContext} & : & \\abs{CallContext} \\times \\SF{FunctionId} \\times \\abs{Loc} \\times \\powerset{\\abs{Loc}} \\rightarrow \\powerset{\\abs{CallContext} \\times \\abs{Obj}} \\\\\n& & \\comment{\\inblue caller context, callee function, callsite, this}  \\\\\n& & \\ahf{NewCallContext}(\\hat{cc}, fid, \\hat{l}, \\hat{L}) = \\{ \\langle \\hat{cc} \\cup \\{ \\hat{l}.1 \\}, ~ \\ahf{NewPureLocal}(\\{\\hat{l}\\}, \\hat{L}) \\rangle \\} \\\\\n\\end{array}\n\\]\n\n\n% 1-object sensitivity\n\\subsection{1-object sensitivity}\n\n\\[\n\\begin{array}{rcl}\n\\abs{CallContext} & = & \\aLoc \\times \\abs{Address} \\\\\n\\abs{globalCallContext} & = & (\\avarloc{Global}_R, \\avarloc{GlobalCallsite}) \\\\\n\\\\\n\n\\ahf{NewCallContext} & : & \\abs{CallContext} \\times \\SF{FunctionId} \\times \\abs{Loc} \\times \\powerset{\\abs{Loc}} \\rightarrow \\powerset{\\abs{CallContext} \\times \\abs{Obj}} \\\\\n& & \\comment{\\inblue caller context, callee function, callsite, this}  \\\\\n%& & \\ahf{NewCallContext}(\\hat{cc}, fid, \\hat{l}, \\hat{L}) = \\bigcup_{\\hat{l}_{this} \\in \\hat{L}} \\{ (\\hat{l}_{this}, \\ahf{NewPureLocal}(\\{\\hat{l}\\}, \\{ \\hat{l}_{this} \\}) \\} \\\\\n& & \\ahf{NewCallContext}(\\hat{cc}, fid, \\hat{l}, \\hat{L}) = \\\\\n& & \\quad\\quad \\left\\{\n       \\begin{array}{ll}\n         \\bigcup_{\\hat{l}_{this} \\in \\hat{L}} \n         \\{ \\langle (\\hat{l}_{this}, \\avarloc{GlobalCallsite}), ~ \\ahf{NewPureLocal}(\\{\\hat{l}\\}, \\{ \\hat{l}_{this} \\} \\rangle \\} & \\ifc{\\chf{isUserFunction}_P(fid)} \\\\\n         \\{ \\langle (\\hat{cc}.1, \\hat{l}.1), ~ \\ahf{NewPureLocal}(\\{\\hat{l}\\}, \\hat{L}) \\rangle \\} & \\owc \\\\\n       \\end{array}\n     \\right.\\\\\n\\end{array}\n\\]\n\n\n% 1-object sensitivity (TAJS style)\n\\subsection{1-object sensitivity (TAJS style)}\n\n\\[\n\\begin{array}{rcl}\n\\abs{CallContext} & = & \\powerset{\\aLoc} \\times \\abs{Address} \\\\\n\\abs{globalCallContext} & = & (\\{ \\avarloc{Global}_R \\}, \\avarloc{GlobalCallsite}) \\\\\n\\\\\n\n\\ahf{NewCallContext} & : & \\abs{CallContext} \\times \\SF{FunctionId} \\times \\abs{Loc} \\times \\powerset{\\abs{Loc}} \\rightarrow \\powerset{\\abs{CallContext} \\times \\abs{Obj}} \\\\\n& & \\comment{\\inblue caller context, callee function, callsite, this}  \\\\\n%& & \\ahf{NewCallContext}(\\hat{cc}, fid, \\hat{l}, \\hat{L}) = \\bigcup_{\\hat{l}_{this} \\in \\hat{L}} \\{ (\\hat{l}_{this}, \\ahf{NewPureLocal}(\\{\\hat{l}\\}, \\{ \\hat{l}_{this} \\}) \\} \\\\\n& & \\ahf{NewCallContext}(\\hat{cc}, fid, \\hat{l}, \\hat{L}) = \\\\\n& & \\quad\\quad \\left\\{\n       \\begin{array}{ll}\n         \\{ \\langle (\\hat{L}, \\avarloc{GlobalCallsite}), ~ \\ahf{NewPureLocal}(\\{\\hat{l}\\}, \\hat{L}) \\rangle \\} & \\ifc{\\chf{isUserFunction}_P(fid)} \\\\\n         \\{ \\langle (\\hat{cc}.1, \\hat{l}.1), ~ \\ahf{NewPureLocal}(\\{\\hat{l}\\}, \\hat{L}) \\rangle \\} & \\owc \\\\\n       \\end{array}\n     \\right.\\\\\n\\end{array}\n\\]\n\n\n\\newpage\n\\section{Semantics}\n{\\inblue\\tt .../jsaf/analysis/typing/\\{Typing, Semantics, Operator, Worklist, Fixpoint\\}.scala}\\\\\n\\[\n\\begin{array}{lcl}\n  \\aE & \\in & \\abs{IPEdge} \\rightarrow \\aState \\rightarrow \\aState \\\\\n  \\aN & \\in & \\aControlPoint \\rightarrow \\Command \\rightarrow \\aState \\rightarrow \\aState \\times \\aState\\\\\n  \\aI & \\in & \\aControlPoint \\rightarrow \\SF{Instruction} \\rightarrow \\aState \\times \\aState \\rightarrow \\aState \\times \\aState\\\\\n  \\aV & \\in & \\SF{Expression} \\rightarrow \\aState \\rightarrow \\aValue \\times \\powerset{\\abs{Exception}} \\\\\n  \\aB & \\in & \\SF{Expression} \\rightarrow \\aState \\times \\aState \\rightarrow \\aState \\times \\aState\\\\\n\\end{array}\n\\]\n\\[\n\\begin{array}{l}\n% call inter-procedural edge (bottom heap)\n\\aE \\lbr \\acp \\cfgnext_{\\hat{C},\\hat{o}} ((fid,\\SF{ENTRY}),\\hat{cc}) \\rbr (\\bot_{Heap},\\hat{C}_1) = \\bot_{State}\n\\vspace{1mm}\\\\\n\n% call inter-procedural edge\n\\aE \\lbr \\acp \\cfgnext_{\\hat{C},\\hat{o}} ((fid,\\SF{ENTRY}),\\hat{cc}) \\rbr (\\hat{H}_1,\\hat{C}_1) = (\\hat{H}_3,\\hat{C}) \\\\\n  \\quad\\wherec{\n    \\hat{o}_{env} = \\ahf{NewDeclEnvRecord}(\\hat{o}(\\varprop{scope}).1.2) \\\\\n    \\land\\ \\hat{o}_2 = \\hat{o} - \\varprop{scope} \\\\\n    \\land\\ \\hat{H}_2 = \\hat{H}_1[\\avarloc{PureLocal}_R \\mapsto \\hat{o}_2] \\\\\n    \\land\\ \\hat{H}_3 = \\bigsqcup_{\\hat{l}_{env}\\in\\hat{o}_2(\\varprop{env}).1.2.2} \\hat{H}_2[\\hat{l}_{env} \\mapsto \\hat{o}_{env}]\n  }\n\\\\\\\\\n\n% normal return inter-procedural edge (bottom heap)\n\\aE \\lbr ((fid,\\SF{EXIT}),\\hat{cc}) \\cfgnext_{\\hat{C},\\hat{o}} \\acp \\rbr (\\bot_{Heap},\\hat{C}_1) = \\bot_{State} \n\\vspace{1mm}\\\\\n\n% normal return inter-procedural edge\n\\aE \\lbr ((fid,\\SF{EXIT}),\\hat{cc}) \\cfgnext_{\\hat{C},\\hat{o}} \\acp \\rbr (\\hat{H}_1,\\hat{C}_1) =\n  \\left\\{\n    \\begin{array}{ll}\n      (\\hat{H}_3, \\hat{C}_2) & \\ifc{\\hat{C}_2 \\neq \\bot_{Context}} \\\\\n      \\bot_{State} & \\ifc{\\hat{C}_2 = \\bot_{Context}} \\\\\n    \\end{array}\n  \\right.\\\\\n  \\quad\\wherec{\n    (\\hat{C}_2, \\hat{o}_1) = \\ahf{FixOldify}(\\hat{C}, \\hat{o}, \\hat{C}_1.3, \\hat{C}_1.4) \\\\ \n    \\land\\ \\hat{v} = \\hat{H}_1(\\avarloc{PureLocal})(\\varprop{return}).1.2 \\\\\n    \\land\\ \\hat{H}_2 = \\hat{H}_1[\\avarloc{PureLocal}_R \\mapsto \\hat{o}_1] \\\\\n    \\land\\ \\hat{H}_3 = \\ahf{VarStore}(\\hat{H}_2, \\chf{getReturnVar}_P(\\acp.1), \\hat{v})\n  }\n\\\\\\\\\n\n% exception return inter-procedural edge (bottom heap)\n\\aE \\lbr ((fid,\\SF{EXIT-EXC}),\\hat{cc}) \\cfgnext_{\\hat{C},\\hat{o}} \\acp \\rbr (\\bot_{Heap},\\hat{C}_1) = \\bot_{State}\n\\vspace{1mm}\\\\\n\n% exception return inter-procedural edge\n\\aE \\lbr ((fid,\\SF{EXIT-EXC}),\\hat{cc}) \\cfgnext_{\\hat{C},\\hat{o}} \\acp \\rbr (\\hat{H}_1,\\hat{C}_1) =\n  \\left\\{\n    \\begin{array}{ll}\n      (\\hat{H}_2, \\hat{C}_2) & \\ifc{\\hat{C}_2 \\neq \\bot_{Context}} \\\\\n      \\bot_{State} & \\ifc{\\hat{C}_2 = \\bot_{Context}} \\\\\n    \\end{array}\n  \\right.\\\\\n  \\quad\\wherec{\n    (\\hat{C}_2, \\hat{o}_1) = \\ahf{FixOldify}(\\hat{C}, \\hat{o}, \\hat{C}_1.3, \\hat{C}_1.4) \\\\ \n    \\land\\ \\hat{v} = \\hat{H}_1(\\avarloc{PureLocal})(\\varprop{exception}).1.2 \\\\\n    \\land\\ \\hat{v}_{old} = \\hat{o}_1(\\varprop{exception\\_all}).1.2 \\\\\n    \\land\\ \\hat{H}_2 = \\hat{H}_1\\left[\\avarloc{PureLocal}_R \\mapsto \\hat{o}_1\n      \\left[\\begin{array}{l}\n        \\varprop{exception} \\mapsto \\hat{v}, \\\\\n        \\varprop{exception\\_all} \\mapsto \\hat{v} \\sqcup \\hat{v}_{old}\n      \\end{array}\\right]\\right]\n  }\n\\\\\\\\\n\n\\end{array}\n\\]\n\\[\n\\begin{array}{l} \n% \\Entry & \\comment{entry node}\\\\\\\\\n\\aN_{\\acp}\\lbr c \\rbr (\\bot_{Heap},\\bot_{Context})\n = (\\bot_{State},\\bot_{State})\\\\\\\\\n\n\\aN _{\\acp}\\lbr {\\sf entry} \\rbr (\\hat{H}_0,\\hat{C}) =\n \\left((\\hat{H_m},\\hat{C}), \\bot_{State}\\right)\\\\\n \\quad\\wherec{\n   (({fid_{this}},\\SF{ENTRY}),\\hat{cc}) = \\acp \\\\\n   \\land\\ x_1 \\cdots x_n = \\chf{getArgVars}_P(fid_{this})\\ \n   \\land\\ x_{n+1} \\cdots x_m = \\chf{getLocalVars}_P(fid_{this}) \\\\\n   \\land\\ \\hat{L}_{arg} = \\hat{H}_0(\\avarloc{PureLocal}_R)(\\chf{getArgumentsName}(fid_{this})).1.1.1.2 \\\\\n   \\land\\ \\forall 1 \\leq i \\leq n.\\ \\hat{H_i}= \\ahf{CreateMutableBinding}(\\hat{H}_{i-1}, x_i, \n     \\bigsqcup_{\\hat{l}_{arg}\\in\\hat{L}_{arg}}\\ahf{Proto}(\\hat{H}_{i-1},\\hat{l}_{arg},\\hat{``i-1\"}) \\\\\n   \\land\\ \\forall n+1 \\leq j \\leq m.\\ \\hat{H_j}= \\ahf{CreateMutableBinding}(\\hat{H}_{j-1}, x_j, \\aundef_{Value})\n}\\\\\n\\\\\n\n\\aN_{\\acp}\\lbr \\SF{exit} \\rbr (\\hat{H},\\hat{C}) = \\left((\\hat{H},\\hat{C}),\\bot_{State}\\right) \\\\\n\\\\\n\\aN_{\\acp}\\lbr \\SF{exit-exc} \\rbr (\\hat{H},\\hat{C}) = \\left((\\hat{H},\\hat{C}),\\bot_{State}\\right) \\\\\n\\\\\n% \\Exit & \\comment{exit node}\\\\\\\\\n% \\Exite & \\comment{exit node for exception}\\\\\\\\\n\n% i^+\n\\aN_{\\acp}\\lbr i^+\\rbr (\\hat{H},\\hat{C}) =\n  \\left(\\aI _{\\acp} \\lbr i\\rbr\\left((\\hat{H},\\hat{C}),\\bot_{State}\\right)\\right)^{+} \\\\\\\\\n%  \\left(\\aI _{\\acp} \\lbr i\\rbr(\\hat{H},\\hat{C})(\\hat{S})\\right)^{+} \\\\\\\\\n\n% \\aI _{\\acp}\\lbr i \\rbr (\\hat{H},\\hat{A}) = (\\hat{H},\\hat{A})\n% \\quad\\ifc{\\chf{HasProperty}(H,\\varloc{temp},\\varprop{exception}) \\lor (H,A)=\\SF{stuck}}\n% \\\\\\\\\n\n% x~\\verb+:=+~\\TT{alloc}\\verb+(+ e \\verb+)+\n\\aI_{\\acp}\\lbr i \\rbr \\left((\\bot_{Heap},\\hat{C}),\\hat{S}\\right)\n = \\left((\\bot_{State},\\hat{S}\\right) \\\\\\\\\n\\aI_{\\acp}\\lbr x\\TT{:=}\\TT{alloc(}e^{?}\\TT{)}_{\\hat{a}_{new}}\\rbr \\left((\\hat{H},\\hat{C}),\\hat{S}\\right)\n = \\left((\\hat{H}_3,\\hat{C}_1),\\hat{S}_1\\right) \\\\\n\\quad\\wherec{\n  \\inblue\\hat{l}_{R} = (\\hat{a}_{new}, \\hat{Recent})\n  \\land\\ \\inblue (\\hat{H}_1, \\hat{C}_1) = \\ahf{Oldify}(\\hat{H}, \\hat{C}, \\hat{a}_{new})\n    \\quad\\comment{{\\inblue // Recency Abstraction}}\\\\\n  \\land\\ (\\hat{v},\\hat{es})=\\aV\\lbr e \\rbr(\\hat{H}_1,\\hat{C}_1) \\quad\\comment{\\inblue // if $e$ is None, $\\hat{v}$ is considered as an element of $PValue$.}\n\\\\\n  \\land\\ \\hat{L}_p=\\hat{v}.2 \n  \\land\\ \\hat{L}_v=\\left\\{\n    \\begin{array}{ll}\n      \\set{\\avarloc{ObjProto}_R} & \\ifc{\\hat{v}.1 \\not\\sqsubseteq \\bot_{PValue}}\\\\\n      \\set{} & \\owc\n    \\end{array}\\right.\\\\\n  \\land\\ \\hat{H}_2 = \\hat{H}_1[\\hat{l}_{R}\\mapsto \\bigsqcup_{\\hat{l}_p\\in\\hat{L}_p\\cup\\hat{L}_v}\\ahf{NewObject}(\\hat{l}_p)]\\\\\n  \\land\\ \\hat{H}_3 = \\ahf{VarStore}(\\hat{H}_2, x,\\langle\\bot_{PValue},\\{\\hat{l}_{R}\\}\\rangle) \\\\\n  \\land\\ \\hat{S}_1 = \\hat{S}\\sqcup\\ahf{RaiseException}(\\hat{H},\\hat{C}, \\hat{es})\n}\n\\\\\\\\\n         \n% x~\\verb+:=+~\\TT{alloc}\\verb+(+ e \\verb+)+\n% \\aI _{\\acp}\\lbr x\\TT{:=}\\TT{allocObject}\\TT{()}_{\\hat{l}_{new}}\\rbr (\\hat{H},\\hat{C})\n%  = (\\hat{H}_2,\\hat{C}) \\\\\n% \\quad \\wherec{\n%   \\atrue\\sqsubseteq\\ahf{CanPutVar}(\\hat{H},x) \\\\\n%   \\land\\ \\hat{H}_1 = \\ahf{VarStore}(\\hat{H},x,\\langle \\bot_{PValue},\\{l_{new}\\}\\rangle,\\atrue) \\\\\n%   \\land\\ \\hat{H}_2 = \\hat{H}_1[\\hat{l}_{new}\\mapsto \\ahf{NewObject}(\\avarloc{ObjProto})] \\\\\n% }\n% \\\\\\\\\n\n% x~\\verb+:=+~\\SF{allocArray}\\verb+(+n\\verb+)+\n\\aI_{\\acp}\\lbr x\\TT{:=}\\SF{allocArray}\\TT{(n)}_{\\hat{a}_{new}} \\rbr \\left((\\hat{H},\\hat{C}),\\hat{S}\\right)\n = \\left((\\hat{H}_3,\\hat{C}_1),\\hat{S}\\right) \\\\\n\\quad\\wherec{\n  \\inblue\\hat{l}_{R} = (\\hat{a}_{new}, \\hat{Recent})\n  \\land\\ \\inblue (\\hat{H}_1, \\hat{C}_1) = \\ahf{Oldify}(\\hat{H}, \\hat{C}, \\hat{a}_{new})\n    \\quad\\comment{{\\inblue // Recency Abstraction}}\\\\\n  \\land\\ \\hat{n} = (\\aV\\lbr \\TT{n}\\rbr(\\hat{H}_1,\\hat{C}_1)).1.1.4\\\\ \n  \\land\\ \\hat{H}_2 = \\hat{H}_1[\\hat{l}_{R}\\mapsto \\ahf{NewArrayObject}(\\hat{n})] \\\\\n  \\land\\ \\hat{H}_3 = \\ahf{VarStore}(\\hat{H}_2, x,\\langle\\bot_{PValue},\\{\\hat{l}_{R}\\}\\rangle) \\\\\n}\n\\\\\\\\\n\n% x~\\verb+:=+~\\SF{allocArg}\\verb+(+n\\verb+)+\n\\aI_{\\acp}\\lbr x\\TT{:=}\\SF{allocArg}\\TT{(n)}_{\\hat{a}_{new}} \\rbr \\left((\\hat{H},\\hat{C}),\\hat{S}\\right)\n = \\left((\\hat{H}_3,\\hat{C}_1),\\hat{S}\\right) \\\\\n\\quad\\wherec{\n  \\inblue\\hat{l}_{R} = (\\hat{a}_{new}, \\hat{Recent})\n  \\land\\ \\inblue (\\hat{H}_1, \\hat{C}_1) = \\ahf{Oldify}(\\hat{H}, \\hat{C}, \\hat{a}_{new})\n    \\quad\\comment{{\\inblue // Recency Abstraction}}\\\\\n  \\land \\hat{n} = (\\aV\\lbr \\TT{n}\\rbr(\\hat{H}_1,\\hat{C}_1)).1.1.4\\\\\n  \\land\\ \\hat{H}_2 = \\hat{H}_1[\\hat{l}_{R}\\mapsto \\ahf{NewArgObject}(\\hat{n})] \\\\\n  \\land\\ \\hat{H}_3 = \\ahf{VarStore}(\\hat{H}_2,x,\\langle\\bot_{PValue},\\{\\hat{l}_{R}\\}\\rangle) \\\\\n}\n\\\\\\\\\n\\end{array}\n\\]\n\\[\n\\begin{array}{ll}\n% x ~\\verb+:=+~ e \n\\aI_{\\acp}\\lbr x\\TT{:=}e \\rbr \\left((\\hat{H},\\hat{C}),\\hat{S}\\right)\n = \\left((\\hat{H}_1,\\hat{C}_1),\\hat{S}_1\\right)\\\\\n \\quad\\wherec{\n   (\\hat{v},\\hat{es}) = \\aV\\lbr e\\rbr(\\hat{H},\\hat{C})\\\\\n   \\land\\ (\\hat{H}_1, \\hat{C}_1) = \\left\\{\n     \\begin{array}{ll}\n       (\\ahf{VarStore}(\\hat{H},x,\\hat{v}), \\hat{C})\n        & \\quad\\ifc{\\hat{v}\\not\\sqsubseteq\\bot_{Value}} \\\\\n       (\\bot_{Heap}, \\bot_{Context}) & \\quad\\owc\n     \\end{array}\n   \\right.\\\\\n   \\land\\ \\hat{S}_1 = \\hat{S}\\sqcup\\ahf{RaiseException}(\\hat{H},\\hat{C}, \\hat{es})\n }\\\\\n\\\\\n\n% x ~\\verb+:=+~ \\SF{delete}\\verb+(+e_1^(?),e_2\\verb+)+\n\\aI_{\\acp}\\lbr x_1 \\TT{:=} \\SF{delete}\\TT{(}x_2\\TT{)} \\rbr \\left((\\hat{H},\\hat{C}),\\hat{S}\\right)\n = \\left((\\ahf{VarStore}(\\hat{H}_1,x_1,\\hat{b}_{Value}),\\hat{C}),\\hat{S}\\right) \\\\\n\\quad\\wherec{\n  \\hat{L}_{base}=\\ahf{LookupBase}(\\hat{H},x_2)\\\\\n  \\land\\ (\\hat{H}_1,\\hat{b})=\\bigsqcup_{\\hat{l}_{base}\\in\\hat{L}_{base}}\\ahf{Delete}(\\hat{H},\\hat{l}_{base},\\hat{x}_2)\\\\\n}\\\\\\\\\n\n\\aI _{\\acp}\\lbr x \\TT{:=} \\SF{delete}\\TT{(}e\\TT{)} \\rbr \\left((\\hat{H},\\hat{C}),\\hat{S}\\right)\n = \\left((\\hat{H}_1,\\hat{C}_1),\\hat{S}_1\\right) \\\\\n\\quad\\wherec{\n   (\\hat{v},\\hat{es}) = \\aV\\lbr e\\rbr(\\hat{H},\\hat{C})\\\\\n   \\land\\ (\\hat{H}_1, \\hat{C}_1) = \\left\\{\n     \\begin{array}{ll}\n       (\\ahf{VarStore}(\\hat{H},x,\\atrue_{Value}), \\hat{C}) & \\quad\\ifc{\\hat{v}\\not\\sqsubseteq\\bot_{Value}} \\\\\n       (\\bot_{Heap}, \\bot_{Context}) & \\quad\\owc\n     \\end{array}\n   \\right.\\\\\n   \\land\\ \\hat{S}_1 = \\hat{S}\\sqcup\\ahf{RaiseException}(\\hat{H},\\hat{C}, \\hat{es})\n}\\\\\n\\\\\n\n\\aI _{\\acp}\\lbr x \\TT{:=} \\SF{delete}\\TT{(}e_1,e_2\\TT{)} \\rbr \\left((\\hat{H},\\hat{C}),\\hat{S}\\right)\n = \\left((\\hat{H}_2,\\hat{C}_2),\\hat{S}_1\\right) \\\\\n\\quad\\wherec{\n  \\hat{L}=(\\aV\\lbr e_1\\rbr(\\hat{H},\\hat{C})).1.2\n  \\land\\ (\\hat{v}, \\hat{es}) = \\aV\\lbr e_2\\rbr(\\hat{H},\\hat{C}) \\\\\n  \\land\\ \\hat{ss} = \n    \\left\\{\\begin{array}{ll}\n      \\ahf{toStringSet}(\\ahf{toPrimivite}(\\hat{v})) & \\ifc{\\hat{v} \\not\\sqsubseteq \\bot_{Value}} \\\\\n      \\{\\} & \\owc \\\\\n    \\end{array}\\right. \\\\\n  \\land\\ (\\hat{H}_1,\\hat{b}) = \\bigsqcup_{\\hat{l}\\in\\hat{L}} \\bigsqcup_{\\hat{s} \\in \\hat{ss}} \\ahf{Delete}(\\hat{H},\\hat{l},\\hat{s}) \\\\\n  \\land\\ (\\hat{H}_2,\\hat{C}_2) =\n    \\left\\{\\begin{array}{ll}\n      (\\ahf{VarStore}(\\hat{H}_1,x,\\hat{b}_{Value}),\\hat{C}) & \\ifc{\\hat{H}_1 \\not\\sqsubseteq \\bot_{Heap}} \\\\\n      (\\bot_{Heap}, \\bot_{Context}) & \\owc \\\\\n    \\end{array}\\right. \\\\\n  \\land\\ \\hat{S}_1 = \\hat{S}\\sqcup\\ahf{RaiseException}(\\hat{H},\\hat{C}, \\hat{es}) \\\\\n}\\\\\n\\\\\n\n%\\aI _{\\acp}\\lbr x \\TT{:=} \\SF{delete}\\TT{(}e_1,e_2\\TT{)} \\rbr \\left((\\hat{H},\\hat{C}),\\hat{S}\\right)\n% = \\left((\\ahf{VarStore}(\\hat{H}_1,x,\\hat{b}_{Value}),\\hat{C}),\\hat{S}\\right) \\\\\n%\\quad\\wherec{\n%  \\hat{L}=(\\aV\\lbr e_1\\rbr(\\hat{H},\\hat{C})).1.2\n%  \\land\\ \\hat{s}=(\\aV\\lbr e_2\\rbr(\\hat{H},\\hat{C})).1.1.5\\\\\n%  \\land\\\n%  (\\hat{H}_1,\\hat{b})=\\bigsqcup_{\\hat{l}\\in\\hat{L}}\\ahf{Delete}(\\hat{H},\\hat{l},\\hat{s})\n%}\\\\\n%\\\\\n\n\\end{array}\n\\]\n\\[\n\\begin{array}{ll}\n\n% e\\verb+[+e\\verb+]+ ~\\verb+:=+~ e \n\\aI_{\\acp}\\lbr e_1\\TT{[}e_2\\TT{]}\\TT{=}e_3 \\rbr \\left((\\hat{H},\\hat{C}),\\hat{S}\\right)\n = \\left((\\hat{H}_1,\\hat{C}_1),\\hat{S}_1\\right) \\\\\n\\quad\\wherec{\n  \\hat{L} = (\\aV\\lbr e_1\\rbr(\\hat{H},\\hat{C})).1.2 \\land (\\hat{s},\\hat{es}_{s})=(\\aV\\lbr e_2\\rbr(\\hat{H},\\hat{C}))\n  \\land (\\hat{v},\\hat{es})=\\aV\\lbr e_3\\rbr(\\hat{H},\\hat{C}) \\\\\n  \\land\\ \\hat{v}_{newLen} = \\ahf{ToUInt32}(\\hat{v}) \\land \\hat{v}_{oldLen} = \\hat{H}(\\hat{l})(``length\").1.1.1.1.4\\\\\n  \\land\\ \\hat{L}_{\\emph{NArr}}=\\set{\\hat{l}~\\mid~\\hat{l}\\in\\hat{L}\n    \\land \\afalse\\sqsubseteq\\ahf{IsArray}(\\hat{H},\\hat{l})\n    \\land \\atrue\\sqsubseteq \\ahf{CanPut}(\\hat{H}, \\hat{l}, \\hat{s})} \\\\\n  \\land\\ \\hat{L}_{\\emph{Arr}}=\\set{\\hat{l}~\\mid~\\hat{l}\\in\\hat{L}\n    \\land \\atrue\\sqsubseteq\\ahf{IsArray}(\\hat{H},\\hat{l})\n    \\land \\atrue\\sqsubseteq \\ahf{CanPut}(\\hat{H}, \\hat{l}, \\hat{s})} \\\\\n  \n  \\land\\ \\hat{H}_{\\emph{CantPut}} = \\left\\{\\begin{array}{ll}\n      \\hat{H}\n      & \\ifc{\\exists \\hat{l} \\in \\hat{L}: \\afalse \\sqsubseteq \\ahf{CanPut}(\\hat{H}, \\hat{l}, \\hat{s})}\\\\\n      \\bot_{Heap} & \\owc \\\\\n    \\end{array}\\right.\\\\\n  \n  \\land\\ \\hat{H}_{\\emph{NArr}} =\n    \\bigsqcup_{\\hat{l}\\in\\hat{L}_{\\emph{NArr}}} \\ahf{PropStore}(\\hat{H}, \\hat{l}, \\hat{s}, \\hat{v})\\\\\n    \n  \\land\\ (\\hat{H}_{\\emph{Arr}}, \\hat{es}_{\\emph{Arr}}) = \\bigsqcup_{\\hat{l}\\in\\hat{L}_{\\emph{Arr}}}\n    (\\hat{H}_{\\emph{Arr}_{\\emph{length}}} \\sqcup \\hat{H}_{\\emph{Arr}_{\\emph{index}}} \\sqcup \\hat{H}_{\\emph{Arr}_{\\emph{other}}}, \\hat{es}_1)\\\\\n  \\land\\ (\\hat{H}_{\\emph{Arr}_{\\emph{length}}}, \\hat{es}_1) = \\left\\{\\begin{array}{ll}\n      (\\hat{H}_{\\emph{Arr}_{\\emph{length1}}}, \\hat{es}_{len})\n      & \\ifc{\\hat{``length\"} \\sqsubseteq \\hat{s} }\\\\\n      (\\bot_{Heap}, \\bot_{Exception}) & \\owc \\\\\n    \\end{array}\\right.\\\\\n  \\land\\ \\hat{H}_{\\emph{Arr}_{\\emph{length1}}} = \\left\\{\\begin{array}{ll}\n      \\hat{H}_{\\emph{Arr}_{\\emph{length2}}} \\sqcup \\hat{H}_{\\emph{Arr}_{\\emph{length3}}} \\sqcup \\hat{H}_{\\emph{Arr}_{\\emph{length4}}} \n      & \\ifc{\\atrue \\sqsubseteq (\\ahf{ToNumber}(\\hat{v}) \\hat{=} \\hat{v}_{newLen})}\\\\\n      \\bot_{Heap} & \\owc \\\\\n    \\end{array}\\right.\\\\\n  \\land\\ \\hat{H}_{\\emph{Arr}_{\\emph{length2}}} = \\left\\{\\begin{array}{ll}\n      \\ahf{PropStore}(\\hat{H}, \\hat{l}, \\hat{``length\"}, \\hat{v})\n      & \\ifc{\\atrue \\sqsubseteq (\\hat{v}_{oldLen} \\hat{\\leq} \\hat{v}_{newLen})\\land \\atrue \\sqsubseteq \\ahf{CanPut}(\\hat{H}, \\hat{l}, \\hat{``length\"})}\\\\\n      \\bot_{Heap} & \\owc \\\\\n    \\end{array}\\right.\\\\\n  \\land\\ \\hat{H}_{\\emph{Arr}_{\\emph{length3}}} = \\left\\{\\begin{array}{ll}\n      \\hat{H}\n      & \\ifc{\\afalse \\sqsubseteq \\ahf{CanPut}(\\hat{H}, \\hat{l}, \\hat{``length\"})}\\\\\n      \\bot_{Heap} & \\owc \\\\\n    \\end{array}\\right.\\\\\n  \\land\\ \\hat{H}_{\\emph{Arr}_{\\emph{length4}}} = \\left\\{ \\begin{array}{ll}\n      \\bigsqcup_{x=\\hat{v}_{oldLen}-1\\textrm{ to }\\hat{v}_{newLen}}\\ahf{Delete}(\\ahf{PropStore}(\\hat{H}, \\hat{l}, \\hat{``length\"}, \\hat{v}),\\hat{l},x)\\quad\\ifc{\\hat{v}_{newLen}\\hat{<}\\hat{v}_{oldLen}\\\\\\land\\ \\atrue \\sqsubseteq \\ahf{CanPut}(\\hat{H}, \\hat{l}, \\hat{``length\"}))}\\\\\n      \\ahf{PropStore}(\\hat{H}, \\hat{l}, \\hat{``length\"}, \\hat{v}) \\quad \\owc\n    \\end{array}\\right.\\\\\n  \\land\\ \\hat{es}_{len} = \\left\\{\\begin{array}{ll}\n      \\{\\hat{\\SF{RangeError}}\\}\n      & \\ifc{\\afalse \\sqsubseteq (\\ahf{ToNumber}(\\hat{v}) \\hat{=} \\ahf{ToUInt32}(\\hat{v}))}\\\\\n      \\bot_{Exception} & \\owc \\\\\n    \\end{array}\\right.\\\\\n    \n  \\land\\ \\hat{H}_{\\emph{Arr}_{\\emph{index}}} = \\left\\{\\begin{array}{ll}\n      \\hat{H}_{\\emph{Arr}_{\\emph{index1}}} \\sqcup \\hat{H}_{\\emph{Arr}_{\\emph{index2}}} \\sqcup \\hat{H}_{\\emph{Arr}_{\\emph{index3}}} \n      & \\ifc{\\atrue \\sqsubseteq \\ahf{IsArrayIndex}(\\hat{s})}\\\\\n      \\bot_{Heap} & \\owc \\\\\n    \\end{array}\\right.\\\\\n  \\land\\ \\hat{H}_{\\emph{Arr}_{\\emph{index1}}} = \\left\\{\\begin{array}{ll}\n      \\hat{H} \n      & \\ifc{\\atrue \\sqsubseteq (\\hat{v}_{oldLen} \\hat{\\leq} \\ahf{ToUInt32}(\\hat{s}))\\land \\afalse \\sqsubseteq \\ahf{CanPut}(\\hat{H}, \\hat{l}, \\hat{``length\"})}\\\\\n      \\bot_{Heap} & \\owc \\\\\n    \\end{array}\\right.\\\\\n  \\land\\ \\hat{H}_{\\emph{Arr}_{\\emph{index2}}} = \\left\\{\\begin{array}{ll}\n      \\ahf{PropStore}(\\hat{H}, \\hat{l}, \\hat{s}, \\hat{v})\n      & \\ifc{\\atrue \\sqsubseteq (\\ahf{ToUInt32}(\\hat{s}) \\hat{<} \\hat{v}_{oldLen})}\\\\\n      \\bot_{Heap} & \\owc \\\\\n    \\end{array}\\right.\\\\\n  \\land\\ \\hat{H}_{\\emph{Arr}_{\\emph{index3}}} = \\left\\{\\begin{array}{ll}\n      \\ahf{PropStore}(\\ahf{PropStore}(\\hat{H}, \\hat{l}, \\hat{s}, \\hat{v}), \\hat{l}, \\hat{``length\"}, \\ahf{ToUInt32}(\\hat{s} \\hat{+} \\hat{1}))\n      & \\ifc{\\atrue \\sqsubseteq (\\hat{v}_{oldLen} \\hat{\\leq} \\ahf{ToUInt32}(\\hat{s})) \\\\\n      \\land \\ \\atrue \\sqsubseteq \\ahf{CanPut}(\\hat{H}, \\hat{l}, \\hat{``length\"})}\\\\\n      \\bot_{Heap} & \\owc \\\\\n    \\end{array}\\right.\\\\\n\n       \n  \\land\\ \\hat{H}_{\\emph{Arr}_{\\emph{other}}} = \\left\\{\\begin{array}{ll}\n      \\ahf{PropStore}(\\hat{H}, \\hat{l}, \\hat{s}, \\hat{v}) \n      & \\ifc{\\hat{s} \\neq \\hat{``length\"} \\land \\afalse \\sqsubseteq \\ahf{IsArrayIndex}(\\hat{s})}\\\\\n      \\bot_{Heap} & \\owc \\\\\n    \\end{array}\\right.\\\\\n\n  \\land\\ (\\hat{H}_1, \\hat{C}_1) = (\\hat{H}_{\\emph{CantPut}} \\sqcup \\hat{H}_{\\emph{NArr}} \\sqcup \\hat{H}_{\\emph{Arr}}, \\hat{C})\\\\\n  \\land\\ \\hat{S}_1 = \\hat{S}\\sqcup\\ahf{RaiseException}(\\hat{H},\\hat{C}, \\hat{es}_{s}\\sqcup \\hat{es}\\sqcup \\hat{es}_{\\emph{Arr}})\n}\\\\\\\\\n\n\t\n%\\inred \\aI_{\\acp}\\lbr e_1\\TT{[}``length\"\\TT{]=}e_2\\rbr \\left((\\hat{H},\\hat{C}),\\hat{S}\\right)\n% = \\left((\\hat{H}_2,\\hat{C}),\\hat{S}\\right) \\\\\n%\\quad\\wherec{\n%  \\hat{L}=\\set{\\hat{l}~\\mid~\\hat{l}\\in(\\aV\\lbr e_1\\rbr(\\hat{H},\\hat{C})).2\n%    \\land \\afalse\\sqsubseteq\\SF{IsArray}(\\hat{H},\\hat{l})\n%    \\land \\atrue\\sqsubseteq\\ahf{CanPut}(\\hat{H},\\hat{l},\\hat{``length\"})\n%  } \\\\\n%  \\land\\ \\hat{v}_{newLen} = \\ahf{toNumber}(\\aV\\lbr e_2\\rbr(\\hat{H},\\hat{C}).1)\\\\ % if v_{newLen} is not equal to the result of ToUint32(V[e_2](H,C)), throw a RangeError exception.\n%    \\land\\ \\hat{H}_1 = \\bigsqcup_{\\hat{l}\\in\\hat{L}}\\hat{H}\\left[\\hat{l}\\mapsto\\hat{H}(\\hat{l})\\left[``length\"\\mapsto\\langle(\\hat{v}_{newLen})_{Value},\\hat{ov}.2,\\hat{ov}.3,\\hat{ov}.4\\rangle\\right]\\right]\\quad\\wherec{\\hat{ov}=\\hat{H}(\\hat{l})(``length\").1.1}\\\\\n%  \\land\\ \\hat{H}_2 = \\left\\{\n%    \\begin{array}{ll}\n%      \\bigsqcup_{\\hat{l}\\in\\hat{L}}\\bigsqcup_{x=\\hat{v}_{oldLen}-1\\textrm{ to }\\hat{v}_{newLen}}\\ahf{Delete}(\\hat{H}_1,\\hat{l},x)\\quad\\ifc{\\hat{v}_{newLen}\\hat{<}\\hat{v}_{oldLen}\\\\\\land\\ \\hat{v}_{oldLen}=\\ahf{Proto}(\\hat{H},\\hat{l}, \\hat{``length\"})}\\\\\n%      \\hat{H}_1\\quad\\owc\n%    \\end{array}\n%    \\right.\n%}\\\\\\\\\n%\n%\n%\n%\\inred \\aI_{\\acp}\\lbr e_1\\TT{[}e_2\\TT{]}\\TT{=}e_3 \\rbr \\left((\\hat{H},\\hat{C}),\\hat{S}\\right)\n% = \\left((\\hat{H}_2,\\hat{C}),\\hat{S}\\right) \\\\\n%\\quad\\wherec{\n%  \\hat{v}_{idx}=\\ahf{ArrayIndex}(\\aV\\lbr e_2\\rbr(\\hat{H},\\hat{C}).1) \\\\\n%  \\land\\ \\hat{T}=\\set{\\langle\\hat{l}, x\\rangle~\\mid~\\hat{l}\\in(\\aV\\lbr e_1\\rbr(\\hat{H},\\hat{C})).1.2\n%    \\land x\\in{\\inred \\gamma(\\hat{v}_{idx})}\\land \\atrue\\sqsubseteq\\SF{IsArray}(\\hat{H},\\hat{l})\n%    \\land \\atrue\\sqsubseteq\\ahf{CanPut}(\\hat{H},\\hat{l},\\hat{x})\n%%  } \\\\\n%  \\land\\ \\hat{v}=\\aV\\lbr e_3\\rbr(\\hat{H},\\hat{C}).1 \\\\\n%  \\land\\ \\hat{H}_1 = \\bigsqcup_{\\langle\\hat{l},x\\rangle\\in\\hat{T}}\\hat{H}\\left[\\hat{l}\\mapsto\\hat{H}(\\hat{l})\\left[x\\mapsto\\langle\\hat{v},\\atrue,\\atrue,\\atrue\\rangle\\right]\\right] \\\\\n%  \\land\\ \\hat{H}_2 = \\left\\{\n%    \\begin{array}{ll}\n%      \\bigsqcup_{\\langle\\hat{l},x\\rangle\\in\\hat{T}}\\hat{H}_1\\left[\\hat{l}\\mapsto\\hat{H}_1(\\hat{l})\\left[``length\"\\mapsto \\ahf{incr}(\\hat{H}(\\hat{l})(``length\"))\\right]\\right]\\\\ \\quad\\ifc{\\ahf{Proto}(\\hat{H},\\hat{l}, \\hat{``length\"})\\hat{\\le} \\alpha(x)_{Value}} \\\\\n%      \\hat{H}_1 \\quad\\owc\n%    \\end{array}\n%    \\right.\n%}\\\\\\\\\n\t\n\\end{array}\n\\]\n\\[\n\\begin{array}{ll}\n\n\n\n% \\inred\\aI_{\\acp}\\lbr e_1\\TT{[}e_2\\TT{]}\\TT{=}e_3 \\rbr(\\hat{H},\\hat{this})\n%  = (\\hat{H}_1) \\\\\n% \\quad\\wherec{\n%   \\land\\ \\hat{L}=(\\aV\\lbr e_1\\rbr(\\hat{H},\\hat{this})).2\n%   \\land\\ \\hat{s}=(\\aV\\lbr e_2\\rbr(\\hat{H},\\hat{this})).1.5\n%   \\land\\ \\hat{v}=\\aV\\lbr e_3\\rbr(\\hat{H},\\hat{this}) \\\\\n%   \\land\\ \\afalse\\sqsubseteq \\SF{IsArray}(\\hat{H},\\hat{l})\n%   \\land\\ \\hat{H}_1 = \\bigsqcup_{\\hat{l}\\in\\hat{L}}\\bigsqcup_{\\inred x\\in\\gamma(\\hat{s})}\\ahf{PropStore}(\\hat{H},\\hat{l},x,\\hat{v})\n% }\\\\\n\n% x_1 ~\\verb+:=+~ \\SF{function}\\verb+(+fid\\verb+)+\n\\aI_{\\acp}\\lbr x_1\\TT{:=}\\SF{function}\\TT{(}fid\\TT{)}_{\\hat{a}_{new1},\\hat{a}_{new2}}\\rbr \\left((\\hat{H},\\hat{C}),\\hat{S}\\right)\\\\\n = \\left(\\left(\\hat{H}_3\n    \\left[\n       \\begin{array}{l}\n         \\hat{l}_{R1}\\mapsto\\ahf{NewFunctionObject}(fid,\\hat{H}_3(\\avarloc{PureLocal}_R)(\\varprop{env}).1.2,\\hat{l}_{R2},\\hat{n}), \\\\\n         \\hat{l}_{R2}\\mapsto\\hat{o}_{new}\n         \\left[``constructor\"\\mapsto \n           \\langle\\langle\\bot_{PValue},\\{\\hat{l}_{R1}\\}\\rangle,\\atrue,\\afalse,\\atrue\\rangle\n         \\right]\n       \\end{array}\n     \\right]\n     ,\\hat{C}_2\n   \\right),\\hat{S}\\right) \\\\\n\\quad\\wherec{\n  \\hat{n}=\\alpha(\\mid\\chf{getArgVars}_{P}(fid)\\mid) \\\\\n  \\land\\ \\hat{o}_{new}=\\ahf{NewObject}(\\avarloc{ObjProto}_R)\\\\\n  \\land\\ {\\inblue \\hat{l}_{R1} = (\\hat{a}_{new1}, \\hat{Recent})}\n    \\land\\ {\\inblue (\\hat{H}_1,\\hat{C}_1) = \\ahf{Oldify}(\\hat{H}, \\hat{C}, \\hat{a}_{new1})} \n    \\quad\\comment{{\\inblue // Recency Abstraction}} \\\\\n  \\land\\ {\\inblue \\hat{l}_{R2} = (\\hat{a}_{new2}, \\hat{Recent})}\n    \\land\\ {\\inblue (\\hat{H}_2,\\hat{C}_2) = \\ahf{Oldify}(\\hat{H}_1, \\hat{C}_1, \\hat{a}_{new2})} \n    \\quad\\comment{{\\inblue // Recency Abstraction}} \\\\\n  \\land\\ \\hat{H}_3=\\ahf{VarStore}(\\hat{H}_2,x_1,\\langle\\bot_{PValue},\\{\\hat{l}_{R1}\\}\\rangle)\\\\\n}\n\\\\\\\\\n\n% x_1 ~\\verb+:=+~ \\SF{function}~x_2\\verb+(+fid\\verb+)+\n\\aI_{\\acp}\\lbr x_1\\TT{:=}\\SF{function}~x_2\\TT{(}fid\\TT{)}_{\\hat{a}_{new1},\\hat{a}_{new2},\\hat{a}_{new3}}\\rbr \\left((\\hat{H},\\hat{C}),\\hat{S}\\right)\\\\\n = \\left(\\left(\\hat{H}_5\n    \\left[\n       \\begin{array}{l}\n         \\hat{l}_{R1}\\mapsto\\ahf{NewFunctionObject}(fid,\\{\\hat{l}_{R3}\\}_{Value},\\hat{l}_{R2},\\hat{n}), \\\\\n         \\hat{l}_{R2}\\mapsto\\hat{o}_{new}\n         \\left[``constructor\"\\mapsto \n           \\langle\\langle\\bot_{PValue},\\{\\hat{l}_{R1}\\}\\rangle,\\atrue,\\afalse,\\atrue\\rangle\n         \\right]\n       \\end{array}\n     \\right]\n     ,\\hat{C}_3\n   \\right),\\hat{S}\\right) \\\\\n\\quad\\wherec{\n  \\hat{n}=\\alpha(\\mid\\chf{getArgVars}_{P}(fid)\\mid) \\\\\n  \\land\\ \\hat{o}_{new}=\\ahf{NewObject}(\\avarloc{ObjProto}_R)\\\\\n  \\land\\ {\\inblue \\hat{l}_{R1} = (\\hat{a}_{new1}, \\hat{Recent})}\n    \\land\\ {\\inblue (\\hat{H}_1,\\hat{C}_1) = \\ahf{Oldify}(\\hat{H}, \\hat{C}, \\hat{a}_{new1})} \n    \\quad\\comment{{\\inblue // Recency Abstraction}} \\\\\n  \\land\\ {\\inblue \\hat{l}_{R2} = (\\hat{a}_{new2}, \\hat{Recent})}\n    \\land\\ {\\inblue (\\hat{H}_2,\\hat{C}_2) = \\ahf{Oldify}(\\hat{H}_1, \\hat{C}_1, \\hat{a}_{new2})} \n    \\quad\\comment{{\\inblue // Recency Abstraction}} \\\\\n  \\land\\ {\\inblue \\hat{l}_{R3} = (\\hat{a}_{new3}, \\hat{Recent})}\n    \\land\\ {\\inblue (\\hat{H}_3,\\hat{C}_3) = \\ahf{Oldify}(\\hat{H}_2, \\hat{C}_2, \\hat{a}_{new3})} \n    \\quad\\comment{{\\inblue // Recency Abstraction}} \\\\\n  \\land\\ \\hat{o}_{env} = \\ahf{NewDeclEnvRecord}(\\hat{H}_3(\\avarloc{PureLocal}_R)(\\varprop{env}).1.2) \\\\\n  \\land\\ \\hat{H}_4=\\hat{H}_3[\\hat{l}_{R3} \\mapsto \\hat{o}_{env}\n    [x_2\\mapsto\\langle\\langle\\bot_{PValue},\\{\\hat{l}_{R1}\\}\\rangle,\\afalse,\\bot_{Bool},\\afalse\\rangle]]\\\\\n  \\land\\ \\hat{H}_5=\\ahf{VarStore}(\\hat{H}_4,x_1,\\langle\\bot_{PValue},\\{\\hat{l}_{R1}\\}\\rangle)\\\\\n}\n\\end{array}\n\\]\n\\[\n\\begin{array}{ll}\n% \\SF{construct}\\verb+(+e_1,e_2,e_3\\verb+)+\n\\aI_{\\acp}\\lbr \\SF{construct}\\TT{(}e_1,e_2,e_3\\TT{)}_{\\hat{a}_{new}} \\rbr \\left((\\hat{H},\\hat{C}),\\hat{S}\\right)\n = \\left(\n   (\\hat{H}_3,\\hat{C}_1),\\hat{S}_1\\right) \\\\\n\\quad\\wherec{\n  {\\inblue \\hat{l}_R = (\\hat{a}_{new}, \\hat{Recent})}\n    \\land\\ {\\inblue (\\hat{H}_1,\\hat{C}_1) = \\ahf{Oldify}(\\hat{H}, \\hat{C}, \\hat{a}_{new})} \n    \\quad\\comment{{\\inblue // Recency Abstraction}} \\\\\n  \\land\\ (\\hat{v}_1,\\hat{es}_1) = \\aV\\lbr e_1\\rbr(\\hat{H}_1,\\hat{C}_1)\n  \\land\\ \\hat{L}_f = \\set{ \\hat{l} ~|~ \\hat{l}\\in \\hat{v}_1.2 \\land \\atrue\\sqsubseteq\\ahf{HasConstruct}(\\hat{H}_1,\\hat{l})} \\\\\n  \\land\\ \\hat{L}_{this} = \\ahf{getThis}(\\hat{H}_1,\\aV\\lbr e_2\\rbr(\\hat{H}_1,\\hat{C}_1).1) \\\\\n  \\land\\ \\hat{v}_{arg} = \\aV\\lbr e_3\\rbr(\\hat{H}_1,\\hat{C}_1).1 \\\\\n  \\land\\ \\hat{o}_{old} = \\hat{H}_1(\\avarloc{PureLocal}_R) \\\\\n  \\land\\ \\hat{cc}_{caller} = \\acp.2 \\\\\n  \\land\\ n_{\\textit{after-call}} = \\chf{getAftercallFromCall}_P(\\acp.1) \\\\\n  \\land\\ \\acp_{\\textit{after-call}} = (n_{\\textit{after-call}}, \\hat{cc}_{caller}) \\\\\n  \\land\\ \\acp_{exc} = (\\chf{getExcSucc}_P(n_{\\textit{after-call}}), \\hat{cc}_{caller}) \\\\\n  \\land\\ {\\inblue \\ipnext} :=\n  {\\inblue \\ipnext}~ \\cup ~ \n   \\bigcup_{\\hat{l}_f\\in \\hat{L}_f} \n   \\bigcup_{fid \\in \\hat{H}_1(\\hat{l}_f)(\\varprop{construct}).1.3} \n   \\bigcup_{(\\hat{cc}_{new}, \\hat{o}_{new}) \\in \\ahf{NewCallContext}(\\hat{cc}_{caller}, fid, \\hat{l}_R, \\hat{L}_{this}) } \\\\\n   \\quad\\quad\\set{\n    \\acp\\ \\ipnext_{\\hat{C}_{new}, \\hat{o}_{new_2}} ((fid,\\SF{ENTRY}),\\hat{cc}_{new}) \\\\\n      \\quad\\wherec{\n        \\hat{C}_{new} = \\langle {\\inred \\{ \\}, \\{ \\}}, \\{ \\}, \\{ \\} \\rangle \\\\\n        \\hat{o}_{new_2} = \\hat{o}_{new} \n        \\left[\\begin{array}{l} \n          \\chf{getArgumentsName}(fid) ~\\mapsto~ \\langle\\hat{v}_{arg},\\atrue,\\afalse,\\afalse\\rangle, \\\\\n          \\varprop{scope} ~\\mapsto~ \\hat{H}_1(\\hat{l}_f)(\\varprop{scope}).1\n        \\end{array}\\right]}\\\\\n    ((fid,\\SF{EXIT}),\\hat{cc}_{new})\\ \\ipnext_{\\hat{C}_1, \\hat{o}_{old}}\\ \\acp_{\\textit{after-call}} , \\\\\n    ((fid,\\SF{EXIT-EXC}),\\hat{cc}_{new})\\ \\ipnext_{\\hat{C}_1, \\hat{o}_{old}}\\ \\acp_{exc}\n  }\\\\\n  \\land\\ \\hat{H}_2 = \\bigsqcup_{\\hat{l}\\in\\hat{v}_{arg}.2}\\hat{H}_1 \\left[\n        \\hat{l} \\mapsto \\hat{H}_1(\\hat{l}) \\left[\n            ``callee\" \\mapsto \\langle\\langle\\bot_{PValue},\\hat{L}_f\\rangle,\\atrue,\\afalse,\\atrue\\rangle\n          \\right]\n  \\right]\\\\\n  \\land\\ \\hat{es}_2 = \\{\\hat{\\exc{TypeError}}\\} \\quad\\ifc{\\exists \\hat{l}\\in\\hat{v}_1.2:\\afalse\\sqsubseteq\\ahf{HasConstruct}(\\hat{H}_1,\\hat{l})}\\\\\n  \\land\\ \\hat{es}_3 = \\{\\hat{\\exc{TypeError}}\\} \\quad\\ifc{\\hat{v}_1.1\\not\\sqsubseteq\\bot_{PValue}}\\\\\n  \\land\\ \\hat{es} = \\hat{es}_1\\sqcup\\hat{es}_2\\sqcup\\hat{es}_3\\\\\n  \\land\\ \\hat{S}_1 = \\hat{S}\\sqcup\\ahf{RaiseException}(\\hat{H}_1,\\hat{C}_1, \\hat{es})\\\\\n  \\land\\ \\hat{H}_3 = \\left\\{\n    \\begin{array}{ll}\n      \\hat{H}_2 & \\quad\\ifc{\\hat{L}_f \\not=\\set{}}\\\\\n      \\bot_{Heap} & \\quad\\owc\n    \\end{array}\n  \\right.\n}\\\\\n\\\\\n\n\n% \\SF{call}\\verb+(+e_1,e_2,e_3\\verb+)+\n\\aI_{\\acp}\\lbr \\SF{call}\\TT{(}e_1,e_2,e_3\\TT{)}_{\\hat{a}_{new}} \\rbr \\left((\\hat{H},\\hat{C}),\\hat{S}\\right)\n = \\left(\n   (\\hat{H}_3,\\hat{C}_1),\\hat{S}_1\\right) \\\\\n\\quad\\wherec{\n  {\\inblue \\hat{l}_R = (\\hat{a}_{new}, \\hat{Recent})}\n    \\land\\ {\\inblue (\\hat{H}_1,\\hat{C}_1) = \\ahf{Oldify}(\\hat{H}, \\hat{C}, \\hat{a}_{new})} \n    \\quad\\comment{{\\inblue // Recency Abstraction}} \\\\\n  \\land\\ (\\hat{v}_1,\\hat{es}_1) = \\aV\\lbr e_1\\rbr(\\hat{H}_1,\\hat{C}_1)\n  \\land\\ \\hat{L}_f = \\set{ \\hat{l} ~|~ \\hat{l}\\in \\hat{v}_1.2 \\land \\atrue\\sqsubseteq\\ahf{IsCallable}(\\hat{H}_1,\\hat{l})} \\\\\n  \\land\\ \\hat{L}_{this} = \\ahf{getThis}(\\hat{H}_1,\\aV\\lbr e_2\\rbr(\\hat{H}_1,\\hat{C}_1).1) \\\\\n  \\land\\ \\hat{v}_{arg} = \\aV\\lbr e_3\\rbr(\\hat{H}_1,\\hat{C}_1).1 \\\\\n  \\land\\ \\hat{o}_{old} = \\hat{H}_1(\\avarloc{PureLocal}_R) \\\\\n  \\land\\ \\hat{cc}_{caller} = \\acp.2 \\\\\n  \\land\\ n_{\\textit{after-call}} = \\chf{getAftercallFromCall}_P(\\acp.1) \\\\\n  \\land\\ \\acp_{\\textit{after-call}} = (n_{\\textit{after-call}}, \\hat{cc}_{caller}) \\\\\n  \\land\\ \\acp_{exc} = (\\chf{getExcSucc}_P(n_{\\textit{after-call}}), \\hat{cc}_{caller}) \\\\\n  \\land\\ {\\inblue \\ipnext} :=\n  {\\inblue \\ipnext}~ \\cup ~\n   \\bigcup_{\\hat{l}_f\\in \\hat{L}_f}\n   \\bigcup_{fid \\in \\hat{H}_1(\\hat{l}_f)(\\varprop{function}).1.3}\n   \\bigcup_{(\\hat{cc}_{new}, \\hat{o}_{new}) \\in \\ahf{NewCallContext}(\\hat{cc}_{caller}, fid, \\hat{l}_R, \\hat{L}_{this}) } \\\\\n   \\quad\\quad\\set{\n    \\acp\\ \\ipnext_{\\hat{C}_{new}, \\hat{o}_{new_2}} ((fid,\\SF{ENTRY}),\\hat{cc}_{new}) \\\\\n      \\quad\\wherec{\n        \\hat{C}_{new} = \\langle {\\inred \\{ \\}, \\{ \\}}, \\{ \\}, \\{ \\} \\rangle \\\\\n        \\hat{o}_{new_2} = \\hat{o}_{new} \n        \\left[\\begin{array}{l} \n          \\chf{getArgumentsName}(fid) ~\\mapsto~ \\langle\\hat{v}_{arg},\\atrue,\\afalse,\\afalse\\rangle, \\\\\n          \\varprop{scope} ~\\mapsto~ \\hat{H}_1(\\hat{l}_f)(\\varprop{scope}).1\n        \\end{array}\\right]}\\\\\n    ((fid,\\SF{EXIT}),\\hat{cc}_{new})\\ \\ipnext_{\\hat{C}_1, \\hat{o}_{old}}\\ \\acp_{\\textit{after-call}} , \\\\\n    ((fid,\\SF{EXIT-EXC}),\\hat{cc}_{new})\\ \\ipnext_{\\hat{C}_1, \\hat{o}_{old}}\\ \\acp_{exc}\n  }\\\\\n  \\land\\ \\hat{H}_2 = \\bigsqcup_{\\hat{l}\\in\\hat{v}_{arg}.2}\\hat{H}_1 \\left[\n        \\hat{l} \\mapsto \\hat{H}_1(\\hat{l}) \\left[\n            ``callee\" \\mapsto \\langle\\langle\\bot_{PValue},\\hat{L}_f\\rangle,\\atrue,\\afalse,\\atrue\\rangle\n          \\right]\n  \\right]\\\\\n  \\land\\ \\hat{es}_2 = \\{\\hat{\\exc{TypeError}}\\} \\quad\\ifc{\\exists \\hat{l}\\in\\hat{v}_1.2:\\afalse\\sqsubseteq\\ahf{IsCallable}(\\hat{H}_1,\\hat{l})}\\\\\n  \\land\\ \\hat{es}_3 = \\{\\hat{\\exc{TypeError}}\\} \\quad\\ifc{\\hat{v}_1.1\\not\\sqsubseteq\\bot_{PValue}}\\\\\n  \\land\\ \\hat{es} = \\hat{es}_1\\sqcup\\hat{es}_2\\sqcup\\hat{es}_3\\\\\n  \\land\\ \\hat{S}_1 = \\hat{S}\\sqcup\\ahf{RaiseException}(\\hat{H}_1,\\hat{C}_1, \\hat{es})\\\\\n  \\land\\ \\hat{H}_3 = \\left\\{\n    \\begin{array}{ll}\n      \\hat{H}_2 & \\quad\\ifc{\\hat{L}_f \\not=\\set{}}\\\\\n      \\bot_{Heap} & \\quad\\owc\n    \\end{array}\n  \\right.\n}\\\\\n\\\\\n\\end{array}\n\\]\n\\[\n\\begin{array}{ll}\n% \\SF{assert}\\verb+(+e\\inop e\\verb+)+ \n\\aI_{\\acp}\\lbr \\SF{assert}\\TT{(}e_1\\inop e_2\\TT{)} \\rbr \\left((\\hat{H},\\hat{C}),\\hat{S}\\right)\n = \\left(\\aB\\lbr e_1\\inop e_2\\rbr(\\hat{H},\\hat{C}),\\hat{S}\\right)\n\\\\\\\\\n\n% \\SF{catch}\\verb+(+x\\verb+)+\n\\aI_{\\acp}\\lbr \\SF{catch}\\TT{(}x\\TT{)} \\rbr \\left((\\hat{H},\\hat{C}),\\hat{S}\\right)\n = \\left((\\hat{H}_2,\\hat{C}),\\bot_{State}\\right)\\\\\n\\quad\\wherec{\n  \\hat{v}_{old} = \\hat{H}(\\avarloc{PureLocal}_R)(\\varprop{exception\\_all}).1.2 \\\\\n  \\land\\ \\hat{H}_1 = \\ahf{CreateMutableBinding}(\\hat{H},x,\\hat{H}(\\avarloc{PureLocal}_R)(\\varprop{exception}).1.2) \\\\\n  \\land\\ \\hat{H}_2 = \\hat{H}_1[\\avarloc{PureLocal}_R\\mapsto \\hat{H}_1(\\avarloc{PureLocal}_R)[\\varprop{exception}\\mapsto \\hat{v}_{old}]]\n} \\\\\n\\\\\n\n\n% \\SF{return}\\verb+(+e\\verb+)+ \n\\aI_{\\acp}\\lbr \\SF{return}\\TT{(}e\\TT{)} \\rbr \\left((\\hat{H},\\hat{C}),\\hat{S}\\right)\n = \\left((\\hat{H}_1, \\hat{C}_1),\\hat{S}_1\\right)\\\\\n\\quad\\wherec{\n  (\\hat{v},\\hat{es})=\\aV\\lbr e\\rbr(\\hat{H},\\hat{C})\\\\\n  \\land\\ (\\hat{H}_1, \\hat{C}_1) = \\left\\{\n     \\begin{array}{ll}\n       (\\hat{H}[\\avarloc{PureLocal}_R \\mapsto \\hat{H}(\\avarloc{PureLocal}_R)[\\varprop{return} \\mapsto \\hat{v}]], \\hat{C}))\n       & \\quad\\ifc{\\hat{v}\\not\\sqsubseteq\\bot_{Value}} \\\\\n       (\\bot_{Heap}, \\bot_{Context}) & \\quad\\owc\n     \\end{array}\n   \\right.\\\\\n  \\land\\ \\hat{S}_1 = \\hat{S}\\sqcup\\ahf{RaiseException}(\\hat{H},\\hat{C}, \\hat{es})\n}\n% = (\\hat{H}[\\avarloc{temp}\\mapsto \\hat{H}(\\avarloc{temp})[\\varprop{return}\\mapsto \\aV\\lbr e\\rbr(\\hat{H},\\hat{C})]],\\hat{C})\n\\\\\\\\\n\\aI_{\\acp}\\lbr \\SF{return}\\TT{()} \\rbr \\left((\\hat{H},\\hat{C}),\\hat{S}\\right)\n = \\left((\\hat{H}_1,\\hat{C}), \\hat{S}\\right) \\\\\n\\quad\\wherec{\n  \\hat{H}_1 = \\hat{H}[\\avarloc{PureLocal}_R \\mapsto \\hat{H}(\\avarloc{PureLocal}_R)[\\varprop{return} \\mapsto \\aundef_{Value}]]\n}\n% = (\\hat{H}[\\avarloc{temp}\\mapsto \\hat{H}(\\avarloc{temp})[\\varprop{return}\\mapsto \\aV\\lbr e\\rbr(\\hat{H},\\hat{C})]],\\hat{C})\n\\\\\\\\\n\n% \\SF{throw}\\verb+(+e\\verb+)+\n\\aI_{\\acp}\\lbr \\SF{throw}\\TT{(}e\\TT{)} \\rbr \\left((\\hat{H},\\hat{C}),\\hat{S}\\right)\n   = \\left(\\bot_{State},\\hat{S}_1\\right)\\\\\n\\quad\\wherec{\n  (\\hat{v},\\hat{es})=\\aV\\lbr e\\rbr(\\hat{H},\\hat{C})\\\\\n  \\land\\ \\hat{v}_{old} = \\hat{H}(\\avarloc{PureLocal}_R)(\\varprop{exception\\_all}).1.2 \\\\\n  \\land\\ \\hat{H}_1 = \\hat{H}\\left[\\avarloc{PureLocal}_R\\mapsto \\hat{H}(\\avarloc{PureLocal}_R)\n    \\left[\\begin{array}{l}\n      \\varprop{return}\\mapsto \\aundef_{Value}, \\\\\n      \\varprop{exception}\\mapsto \\hat{v}, \\\\\n      \\varprop{exception\\_all}\\mapsto \\hat{v} \\sqcup \\hat{v}_{old}\n    \\end{array}\\right]\\right] \\\\\n  \\land\\ (\\hat{H}_e, \\hat{C}_e) = \\ahf{RaiseException}(\\hat{H},\\hat{C}, \\hat{es})\n  \\land\\ \\hat{S}_1 = \\hat{S}\\sqcup(\\hat{H}_1\\sqcup\\hat{H}_e, \\hat{C}\\sqcup\\hat{C}_e)\n}\n\\\\\\\\\n\n% Exception\n% \\I _{\\acp}\\lbr x \\TT{:=} \\chfi{toObject}\\TT{(}e\\TT{)} \\rbr(H,A)\n%  = (H[\\varloc{temp}\\mapsto H(\\varloc{temp})[\\varprop{exception}\\mapsto \\SF{TypeError}]], A) \\\\\n%  \\quad\\ifc{\\V _{\\acp}\\lbr e\\rbr(H,A) = \\SF{undefined}\\lor \\V _{\\acp}\\lbr e\\rbr(H,A) = \\SF{null}}\\\\\n\\aI_{\\acp}\\lbr x \\TT{:=} \\ahfi{toObject}\\TT{(}e\\TT{)}_{a_{new}} \\rbr \\left((\\hat{H},\\hat{C}),\\hat{S}\\right)\n = \\left((\\hat{H}_3,\\hat{C}_3),\\hat{S}_1\\right)\\\\\n \\quad\\wherec{\n   (\\hat{v},\\hat{es}_1) = \\aV\\lbr e\\rbr(\\hat{H},\\hat{C}) \\\\\n   \\land\\ (\\hat{H}_1, \\hat{C}_1, \\hat{v}_1, \\hat{es}_2) = \\ahf{toObject}(\\hat{H}, \\hat{C}, \\hat{v}, \\hat{a}_{new}) \\\\\n   \\land\\ (\\hat{H}_2, \\hat{C}_2) = \\left\\{\n     \\begin{array}{ll}\n       (\\ahf{VarStore}(\\hat{H}_1,x,\\hat{v}_1), \\hat{C}_1) & \\quad\\ifc{\\hat{v}_1\\not\\sqsubseteq\\bot_{Value}} \\\\\n       (\\bot_{Heap}, \\bot_{Context}) & \\quad\\owc\n     \\end{array}\n   \\right.\\\\\n   \\land\\ (\\hat{H}_3, \\hat{C}_3, \\hat{es}_3) = \\left\\{\n     \\begin{array}{ll}\n       (\\hat{H}_2, \\hat{C}_2, \\hat{es}_1\\sqcup\\hat{es}_2) & \\quad\\ifc{\\hat{v}\\not\\sqsubseteq\\bot_{Value}} \\\\\n       (\\bot_{Heap}, \\bot_{Context}, \\hat{es}_1) & \\quad\\owc\n     \\end{array}\n   \\right.\\\\\n\n   \\land\\ \\hat{S}_1 = \\hat{S}\\sqcup\\ahf{RaiseException}(\\hat{H},\\hat{C}, \\hat{es}_3)\n }\n\\\\\n\\\\\n\\aI_{\\acp}\\lbr x \\TT{:=} \\ahfi{isObject}\\TT{(}e\\TT{)} \\rbr \\left((\\hat{H},\\hat{C}),\\hat{S}\\right)\n = \\left((\\hat{H}_1,\\hat{C}_1),\\hat{S}_1\\right)\\\\\n \\quad\\wherec{\n   (\\hat{v},\\hat{es})=\\aV\\lbr e\\rbr(\\hat{H},\\hat{C})\\\\\n   \\land\\ (\\hat{H}_1, \\hat{C}_1) = \\left\\{\n     \\begin{array}{ll}\n       (\\ahf{VarStore}(\\hat{H},x,\\hat{b}_{Value}), \\hat{C})\n       & \\quad\\ifc{\\hat{v}\\not\\sqsubseteq\\bot_{Value}} \\\\\n       (\\bot_{Heap}, \\bot_{Context}) & \\quad\\owc\n     \\end{array}\n   \\right.\\\\\n   \\land\\ \\hat{b}_1 = \\left\\{\n     \\begin{array}{ll}\n       \\atrue & \\ifc{\\hat{v}.2 \\not\\sqsubseteq \\bot_{Loc}} \\\\\n       \\bot_{Bool} & \\owc \\\\\n     \\end{array}\n   \\right. \n   \\land\\ \\hat{b}_2 = \\left\\{\n     \\begin{array}{ll}\n       \\afalse & \\ifc{\\hat{v}.1 \\not\\sqsubseteq \\bot_{PValue}} \\\\\n       \\bot_{Bool} & \\owc \\\\\n     \\end{array}\n   \\right. \\\\\n   \\land\\ \\hat{b} = \\hat{b}_1 \\sqcup \\hat{b}_2 \\\\\n   \\land\\ \\hat{S}_1 = \\hat{S}\\sqcup\\ahf{RaiseException}(\\hat{H},\\hat{C}, \\hat{es})\n }\n\\\\\n\\\\\n\n%\\aI_{\\acp}\\lbr x \\TT{:=} \\ahfi{toString}\\TT{(}e\\TT{)} \\rbr \\left((\\hat{H},\\hat{C}_1),\\hat{S}\\right)\n%= \\left((\\hat{H}_1,\\hat{C}_1),\\hat{S}_1\\right)\n%\\\\\\quad\\wherec{\n%  (\\hat{v},\\hat{es}) = \\aV\\lbr e\\rbr(\\hat{H},\\hat{C})\\\\\n%  \\land\\ (\\hat{H}_1, \\hat{C}_1) = \\left\\{\n%     \\begin{array}{ll}\n%       (\\ahf{VarStore}(\\hat{H},x,(\\ahf{toString}(\\hat{pv}))_{Value}), \\hat{C})\n%       & \\quad\\ifc{\\hat{v}\\not\\sqsubseteq\\bot_{Value}} \\\\\n%       (\\bot_{Heap}, \\bot_{Context}) & \\quad\\owc\n%     \\end{array}\\right.\\\\\n%  \\land\\ \\hat{pv}=\\ahf{toPrimitive}(\\hat{v})\\\\\n%  \\land\\ \\hat{S}_1 = \\hat{S}\\sqcup\\ahf{RaiseException}(\\hat{H},\\hat{C}, \\hat{es})\n%}\\\\\n%\\\\\n\\end{array}\n\\]\n\\[\n\\begin{array}{ll}\n\\aI_{\\acp}\\lbr x \\TT{:=} \\ahfi{toNumber}\\TT{(}e\\TT{)} \\rbr \\left((\\hat{H},\\hat{C}),\\hat{S}\\right)\n= \\left((\\hat{H}_1,\\hat{C}_1),\\hat{S}_1\\right)\n\\\\\\quad\\wherec{\n  (\\hat{v},\\hat{es}) = \\aV\\lbr e\\rbr(\\hat{H},\\hat{C})\\\\\n  \\land\\ (\\hat{H}_1, \\hat{C}_1) = \\left\\{\n     \\begin{array}{ll}\n       (\\ahf{VarStore}(\\hat{H},x,(\\ahf{toNumber}(\\hat{pv}))_{Value}), \\hat{C})\n       & \\quad\\ifc{\\hat{v}\\not\\sqsubseteq\\bot_{Value}} \\\\\n       (\\bot_{Heap}, \\bot_{Context}) & \\quad\\owc\n     \\end{array}\\right.\\\\\n  \\land\\ \\hat{pv}=\\ahf{toPrimitive}(\\hat{v})\\\\\n  \\land\\ \\hat{S}_1 = \\hat{S}\\sqcup\\ahf{RaiseException}(\\hat{H},\\hat{C}, \\hat{es})\n}\\\\\\\\\n\n\\aI_{\\acp}\\lbr x_1 \\TT{:=} \\ahfi{getBase}\\TT{(}x_2\\TT{)} \\rbr \\left((\\hat{H},\\hat{C}),\\hat{S}\\right)\n = \\left((\\ahf{VarStore}(\\hat{H},x_1,\\langle\\bot_{PValue},\\hat{L}_{base}\\rangle),\\hat{C}),\\hat{S}\\right) \\\\\n\\quad\\wherec{\n  \\hat{L}_{base}=\\ahf{LookupBase}(\\hat{H},x_2)\n}\n\\\\\\\\\n\n\\aI _{\\acp}\\lbr x \\TT{:=} \\ahfi{iteratorInit}\\TT{(}e\\TT{)} \\rbr \\left((\\hat{H},\\hat{C}),\\hat{S}\\right)\n = \\left((\\hat{H}, \\hat{C}),\\hat{S}\\right)\n% \\quad\\wherec{\n% }\n\\\\\\\\\n\n\\aI _{\\acp}\\lbr x \\TT{:=} \\ahfi{iteratorHasNext}\\TT{(}e_1,e_2\\TT{)} \\rbr \\left((\\hat{H},\\hat{C}),\\hat{S}\\right)\n = \\left((\\ahf{VarStore}(\\hat{H},x,(\\top_{Bool})_{Value}),\\hat{C}),\\hat{S}\\right) \n % \\quad\\wherec{\n %   \\atrue\\sqsubseteq\\ahf{CanPutVar}(\\hat{H},x_1)\\\\\n % }\n\\\\\\\\\n\n\\aI _{\\acp}\\lbr x \\TT{:=} \\ahfi{iteratorNext}\\TT{(}e_1,e_2\\TT{)} \\rbr \\left((\\hat{H},\\hat{C}),\\hat{S}\\right)\n = \\left((\\ahf{VarStore}(\\hat{H},x,(\\top_{String})_{Value}),\\hat{C}),\\hat{S}\\right)\n % \\quad\\wherec{\n %   \\atrue\\sqsubseteq\\ahf{CanPutVar}(\\hat{H},x_1)\\\\\n % }\n\\\\\\\\\n\n\\aI _{\\acp}\\lbr \\SF{noop} \\rbr \\left((\\hat{H},\\hat{C}),\\hat{S}\\right)\n = \\left((\\hat{H},\\hat{C}),\\hat{S}\\right)\n\\\\\\\\\n\n% x\n\\aV\\lbr x \\rbr(\\hat{H},\\hat{C}) = \\ahf{Lookup}(\\hat{H},x)\\\\\n\\\\\n\n\n% e \\inop e \n\\aV\\lbr e_1\\inop e_2 \\rbr(\\hat{H},\\hat{C})\n   = \\left(\\hat{v}, \\hat{es}\\right)\\\\\n\\quad\\wherec{\n  (\\hat{v}_1,\\hat{es}_1) = \\aV\\lbr e_1\\rbr(\\hat{H},\\hat{C})\n  \\land\\ (\\hat{v}_2,\\hat{es}_2) = \\aV\\lbr e_2\\rbr(\\hat{H},\\hat{C}) \\\\\n  \\land\\ (\\hat{v}, \\hat{es}) = \n  \\left\\{\\begin{array} {ll}\n    (\\bot_{Value},\\hat{es}_1) & \\ifc{\\hat{v}_1 \\sqsubseteq \\bot_{Value}} \\\\\n    (\\bot_{Value},\\hat{es}_1\\sqcup\\hat{es}_2) & \\ifc{\\hat{v}_1 \\not\\sqsubseteq \\bot_{Value} \n    \\land\\ \\hat{v}_2 \\sqsubseteq \\bot_{Value}} \\\\\n    \\left(\\hat{v}_1\\ainop \\hat{v}_2,\\hat{es}_1\\sqcup\\hat{es}_2\\right) & \\owc \\\\ \n    \\end{array}\\right. \\\\\n}\n\\\\\\\\\n\n% \\preop e\n\\aV\\lbr\\preop e \\rbr(\\hat{H},\\hat{C})\n   = \\left(\\apreop \\hat{v},\\hat{es}\\right)\n\\quad\\wherec{\n  (\\hat{v},\\hat{es}) = \\aV\\lbr e\\rbr(\\hat{H},\\hat{C})\n}\n\\\\\\\\\n\n% e\\verb+[+e\\verb+]+\n\\aV\\lbr e_1\\TT{[}e_2\\TT{]} \\rbr(\\hat{H},\\hat{C})\n   = \\left(\\hat{v}_1, \\hat{es}\\right)\\\\\n   \\quad\\wherec{\n     \\hat{L} = (\\aV\\lbr e_1\\rbr(\\hat{H},\\hat{C})).1.2\\\n     \\land\\ (\\hat{v}, \\hat{es}) = \\aV\\lbr e_2\\rbr(\\hat{H},\\hat{C}) \\\\\n     \\land\\ \\hat{ss} = \n       \\left\\{\\begin{array}{ll}\n         \\ahf{toStringSet}(\\ahf{toPrimivite}(\\hat{v})) & \\ifc{\\hat{v} \\not\\sqsubseteq \\bot_{Value}} \\\\\n         \\{\\} & \\owc \\\\\n       \\end{array}\\right. \\\\\n     \\land\\ \\hat{v}_1 = \\bigsqcup_{\\hat{l}\\in\\hat{L}} \\bigsqcup_{\\hat{s} \\in \\hat{ss}} \\ahf{Proto}(\\hat{H},\\hat{l},\\hat{s}) \\\\\n   }\n\\\\\\\\\n\n% e\\verb+[+e\\verb+]+\n%\\aV\\lbr e_1\\TT{[}e_2\\TT{]} \\rbr(\\hat{H},\\hat{C})\n%   = \\left(\\hat{v},\\bot_{Exception}\\right)\\\\\n%   \\quad\\wherec{\n%     \\hat{L} = (\\aV\\lbr e_1\\rbr(\\hat{H},\\hat{C})).1.2\\\n%     \\land\\ \\hat{s} = (\\aV\\lbr e_2\\rbr(\\hat{H},\\hat{C})).1.1.5\n%     \\land\\ \\hat{v}=\\bigsqcup_{\\hat{l}\\in\\hat{L}}\\ahf{Proto}(\\hat{H},\\hat{l},\\hat{s})\n%   }\n%\\\\\\\\\n\n\\aV\\lbr \\TT{n} \\rbr(\\hat{H},\\hat{C}) = \\left(\\hat{n}_{Value},\\bot_{Exception}\\right)\\\\\\\\\n\n\\aV\\lbr ``\\TT{s}\" \\rbr(\\hat{H},\\hat{C}) = \\left(\\hat{s}_{Value},\\bot_{Exception}\\right)\\\\\\\\\n\n\\aV\\lbr \\TT{true} \\rbr(\\hat{H},\\hat{C}) = \\left(\\atrue_{Value},\\bot_{Exception}\\right)\\\\\\\\\n\n\\aV\\lbr \\TT{false} \\rbr(\\hat{H},\\hat{C}) = \\left(\\afalse_{Value},\\bot_{Exception}\\right)\\\\\\\\\n\n\\aV\\lbr\\TT{null}\\rbr (\\hat{H},\\hat{C}) = \\left(\\anull_{Value},\\bot_{Exception}\\right)\\\\\\\\\n\n\\aV\\lbr \\TT{this}\\rbr (\\hat{H},\\hat{C}) = \\left(\\langle\\bot_{PValue},\\hat{H}(\\avarloc{PureLocal})(\\varprop{this}).1.2.2\\rangle,\\bot_{Exception}\\right)\n\\\\\\\\\n\\end{array}\n\\]\n\\[\n\\begin{array}{ll}\n\\aV\\lbr e_1\\,\\TT{instanceof}\\,e_2\\rbr (\\hat{H},\\hat{C})\n = \\left(\\hat{b}_{Value},\\hat{es}\\right)\\\\\n\\quad\\wherec{\n  (\\hat{v}_1,\\hat{es}_1) = \\aV\\lbr e_1\\rbr(\\hat{H},\\hat{C})\n  \\land\\ (\\hat{v}_2,\\hat{es}_2) = \\aV\\lbr e_2\\rbr(\\hat{H},\\hat{C})\\\\\n  \\land\\ \\hat{L}_1 = \\hat{v}_1.2\n  \\land\\ \\hat{L}_2 = \\hat{v}_2.2\\\\\n  \\land\\ \\hat{L}_3 = \\set{ \\hat{l} \\,\\mid\\ \\hat{l}\\in\\hat{L}_2\\land\\ \\atrue\\sqsubseteq\\ahf{HasInstance}(\\hat{H},\\hat{l}) } \\\\\n  \\land\\ \\hat{v}_{proto} = \\bigsqcup_{\\hat{l}\\in\\hat{L}_3} \\ahf{Proto}(\\hat{H},\\hat{l},\\hat{``prototype\"}) \\\\\n  \\land\\ \\hat{L}_4 = \\hat{v}_{proto}.2 \\\\\n  \\land\\ \\hat{L}_5 = \\set{ \\hat{l} \\,\\mid\\ \\hat{l}\\in\\hat{L}_2\\land\\ \\afalse\\sqsubseteq\\ahf{HasInstance}(\\hat{H},\\hat{l}) } \\\\\n  \\land\\ \\hat{b}_1 = \\bigsqcup_{\\hat{l_1}\\in\\hat{L}_1}\\bigsqcup_{\\hat{l_2}\\in\\hat{L}_4}\\ahf{inherit}(\\hat{H},\\hat{l}_1,\\hat{l}_2) \\\\\n  \\land\\ \\hat{b}_2 = \\left\\{\n    \\begin{array}{ll}\n      \\afalse & \\quad\\ifc{\\hat{v}_1.1\\not\\sqsubseteq \\bot_{PValue} \\land \\hat{L}_4\\not\\sqsubseteq \\{\\}} \\\\\n      \\bot_{Bool} & \\quad\\owc \\\\\n    \\end{array}\n  \\right.\\\\\n  \\land\\ \\hat{es}_3 = \\left\\{\n    \\begin{array}{ll}\n      \\{\\hat{\\exc{TypeError}}\\} & \\quad\\ifc{\\hat{v}_2.1\\not\\sqsubseteq \\bot_{PValue}\\lor \\hat{L}_5\\not\\sqsubseteq\\{\\}\\lor\\hat{v}_{proto}.1\\not\\sqsubseteq \\bot_{PValue}} \\\\\n      \\{\\} & \\quad\\owc \\\\\n    \\end{array}\n  \\right.\\\\\n  \\land\\ \\hat{b} = \\hat{b}_1 \\sqcup \\hat{b}_2 \\land\\ \\hat{es} = \\hat{es}_1 \\sqcup \\hat{es}_2 \\sqcup \\hat{es}_3\n}\n\\\\\\\\\n\n\\aV\\lbr e_1\\,\\TT{in}\\,e_2\\rbr (\\hat{H},\\hat{C}) = \\left(\\hat{b}_{Value},\\hat{es}\\right)\\\\\n\\quad\\wherec{\n  (\\hat{v}_1,\\hat{es}_1)=\\aV\\lbr e_1\\rbr(\\hat{H},\\hat{C})\n  \\land\\ (\\hat{v}_2,\\hat{es}_2)=\\aV\\lbr e_2\\rbr(\\hat{H},\\hat{C})\\\\\n  \\land\\ \\hat{s}=\\ahf{toString}(\\ahf{toPrimitive}(\\hat{v}_1)) \\\\\n  \\land\\ \\hat{b} = \\bigsqcup_{\\hat{l}\\in\\hat{v}_2.2}\\ahf{HasProperty}(\\hat{H},\\hat{l},\\hat{s})\\\\\n  \\land\\ \\hat{es}_3 = \\left\\{\n    \\begin{array}{ll}\n      \\{\\hat{\\exc{TypeError}}\\} & \\quad\\ifc{\\hat{v}_2.1\\not\\sqsubseteq \\bot_{PValue}} \\\\\n      \\{\\} & \\quad\\owc \\\\\n    \\end{array}\n  \\right.\\\\\n  \\land\\ \\hat{es} = \\hat{es}_1 \\sqcup \\hat{es}_2 \\sqcup \\hat{es}_3\n}\n\\\\\\\\\n\n\\aV\\lbr \\TT{typeof}\\,\\TT{x}\\rbr (\\hat{H},\\hat{C}) = \\left((\\hat{s}_1 \\sqcup \\hat{s}_2)_{Value}, \\set{}\\right)\\\\\n\\quad\\wherec{\n  (\\hat{v},\\hat{es}) = \\aV\\lbr e\\rbr(\\hat{H},\\hat{C}) \\\\\n  \\land\\ \\hat{s}_1 = \\ahf{TypeTag}(\\hat{H},\\hat{v}) \\\\\n  \\land\\ \\hat{s}_2 = \n  \\left\\{\\begin{array} {ll}\n    \\hat{``undefined\"} & \\ifc{\\hat{\\exc{ReferenceError}} \\in \\hat{es}} \\\\\n    \\bot_{String}      & \\owc \\\\\n    \\end{array}\\right. \\\\\n}\n\\\\\\\\\n\n\\aV\\lbr \\TT{typeof}\\,e\\rbr (\\hat{H},\\hat{C}) = \\left((\\ahf{TypeTag}(\\hat{H},\\hat{v}))_{Value},\\hat{es}\\right)\\\\\n\\quad\\wherec{\n  (\\hat{v},\\hat{es}) = \\aV\\lbr e\\rbr(\\hat{H},\\hat{C})\n}\n\\\\\\\\\n\n\\aB \\lbr e \\rbr \\left( (\\hat{H},\\hat{C}), \\hat{S} \\right) =  \\left( (\\hat{H}_1, \\hat{C}_1), \\hat{S}_1 \\right)\\\\\n\\quad\\wherec{\n  relSet = \\left\\{\n    \\begin{array}{ll}\n      \\ahf{getRel}(e_1 \\rel e_2, (\\hat{H}, \\hat{C}))\\cup \\ahf{getRel}(e_2 \\rel^t e_1, (\\hat{H}, \\hat{C})) & \\ifc{ e_1 \\rel e_2 = e \\land \\rel \\in \\SF{IRRelOP}}\\\\\n      \\{ e \\} & \\ifc{ e_1 \\rel e_2 = e \\land \\rel \\in \\SF{IRObjOP}}\\\\\n      \\O & \\owc\n    \\end{array}\n  \\right.\\\\\n  (\\hat{v}, \\hat{es}) = \\hat{\\V} \\lbr e \\rbr(\\hat{H},\\hat{C})\\\\\n  \\hat{S}_1 = \\hat{S} \\sqcup \\ahf{RaiseException}(\\hat{H}, \\hat{C}, \\hat{es})\\\\\n  (\\hat{H}_1, \\hat{C}_1) =\n    \\left\\{\n      \\begin{array}{ll}\n        \\bigsqcap_{re \\in relSet} \\ahf{X} \\lbr re \\rbr (\\hat{H},\\hat{C}) & \n          \\ifc{ relSet \\not= \\O \\land \\hat\\vtrue \\sqsubseteq \\ahf{toBoolean}(\\hat{v}).1.3}\\\\\n        (\\hat{H}, \\hat{C}) & \n          \\ifc{ relSet = \\O \\land \\hat\\vtrue \\sqsubseteq \\ahf{toBoolean}(\\hat{v}).1.3}\\\\\n         (\\bot_{Heap}, \\bot_{Context}) & \n          \\owc\n      \\end{array}\n    \\right.\\\\\n}\n\\\\\\\\\n\\end{array}\n\\]\n\\[\n\\begin{array}{l@{~~}r@{~~}ll}\n\n \\preop & ::= & \\SF{void} % \\mid \\SF{typeof}\n                \\mid \\TT{+} \\mid \\TT{-} \\mid \\TT{\\~} \\mid \\TT{!} \\\\\n \\inop & ::= & % \\SF{instanceof} \\mid \\SF{in} \\mid\n               \\TT{|} \\mid \\TT{\\&} \n               \\mid \\TT{\\^} \\mid \\TT{<<} \\mid \\TT{>>} \\mid \\TT{>>>} \\\\\n& & \\mid \\TT{+} \\mid \\TT{-} \\mid \\TT{*} \\mid \\TT{/} \\mid \\TT{\\%} \\mid \\TT{==} \\mid \\TT{!=} \n               \\mid \\TT{===} \\mid \\TT{!==} \\mid \\TT{<} \\mid \\TT{>} \\mid \\TT{<=} \\mid \\TT{>=} \\\\\n\n\\end{array}\n\\]\n", "meta": {"hexsha": "bd99363a842ad53fe33f9174063b62cb6d864735", "size": 184797, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/manual/safe-cfg.tex", "max_stars_repo_name": "daejunpark/jsaf", "max_stars_repo_head_hexsha": "d9c155f01330672a7b895d77782001c95b29e8a0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-10-07T21:28:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-11T12:09:30.000Z", "max_issues_repo_path": "doc/manual/safe-cfg.tex", "max_issues_repo_name": "daejunpark/jsaf", "max_issues_repo_head_hexsha": "d9c155f01330672a7b895d77782001c95b29e8a0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/manual/safe-cfg.tex", "max_forks_repo_name": "daejunpark/jsaf", "max_forks_repo_head_hexsha": "d9c155f01330672a7b895d77782001c95b29e8a0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-11T13:00:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-11T13:00:37.000Z", "avg_line_length": 39.4107485605, "max_line_length": 444, "alphanum_fraction": 0.5463779174, "num_tokens": 80468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.3327997044170587}}
{"text": "\\section{Analysis}\n\nThe type of analyses we are interested in are \\emph{intra-functional}, that is, we do not consider function calls. To root the design of the analysis infrastructure\nwe considered the four basic analyses in \\cite{spa} which were also covered during the second part of the course, these are \\emph{liveness}, \\emph{available expressions},\n\\emph{very busy expressions} and \\emph{reaching definitions}. \n\n\\newpar From a pure algorithmic point of view, these four analyses are striking similar: all of them operate on sets on a data structure that has a notion of successor and predecessor \nand both use set union, intersection and difference as operations; this suggest an analysis framework with parametric analyses instead of a framework with \\emph{hardcoded}\nones. This approach promotes code reuse, hides the details of the solver and underlying operations, e.g. set union, and it exposes an interface expressive enough to\nwrite \\emph{power set based} analyses.\n\n%\\subsection{Control Flow Graph}\n\n\\newpar The intermediate representation (of the program) upon which the analyses relay on is the Control Flow Graph with single-statement blocks (CFG). A \\emph{Control Flow Graph} with \\emph{single-statement blocks} is a digraph in which the control flow between non-control flow statements is modeled. This differ from a \\emph{pure} control flow graph in the block (node) definition; in a typical control flow graph a block is a maximal sequence of linear statements. (\\cite{cooper}).\n\n\\newpar CFG generation based on the parsed Abstract Syntax Tree (AST) has been implemented in Python, since existing AST-to-CFG parser libraries did not support generating single-statement blocks as required by this project. The CFG generation will generate a CFG with single-statement blocks given a generated TIP/C subset AST. \n\n\\newpar From each node in the CFG we require an interface to its successors (forward flow), predecessors (backward flow), left-hand side variable (if any), right-hand side expressions and type of statement.\nAn extra requirement for the CFG is the variables set, i.e. all the variables declared in the program and the expressions set.\n\nThe \\emph{working unit} of an analysis is a set of monotone functions, and each monotone function take as an argument a node in the CFG. \n\nTo guide the construction and interfacing of the Analysis Engine (AE), we wrote \\texttt{blue\\_print.py} that focus on the design and inner workings of the analysis engine (represented by the class \\texttt{Analysis}) while abstracting away all the implementation details about the components interfacing with it. \n\n\\newpar At the top level the AE requires a CFG and a non-empty list of monotone functions: \\texttt{analysis = Analysis(cfg, monotone\\_functions)}. To find the analysis' fix point to the given CFG, is just a matter of executing: \\texttt{analysis.fix\\_point()}. Also we designed the AE so the writing of monotone functions is as close as the mathematical formulation as possible.\n\n\\newpar To be able to find the fix point, the AE keeps a list of all user provided monotone functions (\\texttt{self.monotone\\_functions}) and a list \\texttt{self.\\_state} of size the number of nodes in the CFG. Each entry of the \\texttt{self.\\_state} list holds the current result of the monotone function that analysed the node. The signature of a monotone function looks like: \\texttt{def join\\_least\\_upper\\_bound (analysis, cfg\\_node)} in which \\texttt{analysis} is a reference to the AE and \\texttt{cfg\\_node} is a reference to the CFG node to be analysed. We send a reference to the AE to the monotone function so the user can have access the\n\\texttt{self.\\_state} variable; this is useful when a function requires information from other nodes.\nTo find the fix point the AE iterates over all blocks in the CFG, per each block, each monotone function is applied in the same order as they were provided by the user when the AE was constructed, a block is considered to be analysed when a monotone function returns a non \\texttt{None} value. Hence, a requirement is set to all monotone functions: if a monotone function does not apply to the given CFG node, then it must return \\texttt{None}. This approach can be improved by caching, per CFG node, the function that returned a non \\texttt{None} value.\n\n\\newpar The \\texttt{Analysis} class exposes two functions to the monotone functions: \\texttt{def least\\_upper\\_bound(self, left, right)} and \\\\\\texttt{def greatest\\_lower\\_bound(self, left, right)} corresponding to the lattice functions \\emph{least upper bound} and \\emph{greatest lower bound}, respectively.\n\nAs an example of a monotone function implementation, we show the JOIN function w.r.t. the least upper bound: \n\\begin{minted}{python}\ndef join_least_upper_bound(analysis, cfg_node):\n   club = frozenset()\n   for successor in cfg_node.successors:\n      club = analysis.least_upper_bound(club, analysis.state(successor))\n   return club\n\\end{minted}\n\n\\newpar To find the least fix-point, we iterate over the nodes of the CFG, applying the corresponding monotone function depending on the \\emph{type} of the node. A \\texttt{\\_state} variable keeps track of the latest monotone function result per CFG node. The least fix-point is found when the \\texttt{\\_state} variable does not change. The \\texttt{\\_state} variable is updated each time a monotone function is executed, as a consequence a small improvement on the time complexity might be achieved depending on the iteration order of the CFG nodes.\n\n\\subsection{Lattice based analyses}\nTo be able to handle general lattices and not only power set based analyses, certain changes must be made to the current implementation of \\texttt{Analysis}. First, a new constructor must be added it will take the CFG and monotone functions as parameters but also will take as an additional parameter a list of pairs \\texttt{lattice} that represent all the edges in the lattice. If $(x,y) \\in$ \\texttt{lattice} then $x < y$. From this list is possible to express the partial order completely as a matrix and use this matrix to calculate the least and greatest bounds. These changes are described in the \\hyperref[futurework]{Future Work} section. \n\n\n", "meta": {"hexsha": "0e61463531aa7856e548700d0453a88e1a817fff", "size": 6200, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/analysis/analysis.tex", "max_stars_repo_name": "andersfischernielsen/ASA-Analyzer", "max_stars_repo_head_hexsha": "349a48d66a5472df7c8e2e2a671d48405ecad087", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/analysis/analysis.tex", "max_issues_repo_name": "andersfischernielsen/ASA-Analyzer", "max_issues_repo_head_hexsha": "349a48d66a5472df7c8e2e2a671d48405ecad087", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/analysis/analysis.tex", "max_forks_repo_name": "andersfischernielsen/ASA-Analyzer", "max_forks_repo_head_hexsha": "349a48d66a5472df7c8e2e2a671d48405ecad087", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 129.1666666667, "max_line_length": 648, "alphanum_fraction": 0.7901612903, "num_tokens": 1409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3327867186228418}}
{"text": "\\documentclass[a4paper, 12pt]{article}\n\\usepackage{amsmath}\n%\\usepackage[utf16]{inputenc}\n\\usepackage{graphicx}\n\\usepackage[left=2.5cm, right=2.5cm, bottom=2.5cm, top=2.5cm]{geometry}\n\\usepackage{natbib}\n\\usepackage{microtype}\n\\usepackage{coloremoji}\n\n\\title{Measure --- or as the kids call it these days, addition}\n\\author{Brendon J. Brewer}\n\\date{}\n\n\\begin{document}\n\\maketitle\n\n% Need this after the abstract\n\\setlength{\\parindent}{0pt}\n\\setlength{\\parskip}{8pt}\n\nSee \\citet{knuth2016deeper}.\n\n\\section{Bigger and smaller}\nSome things are bigger than others.\n\n\\section{How long is a piece of string?}\n\nConsider a set, or collection, of objects, and suppose we can\nunambiguously rank or sort the objects. For example, maybe we\nhave twenty apples, each of which has been weighed precisely.\nWe could put the apples in order by mass, from lowest to highest (or\nthe other way around).\n\nMore formally, think of a set $\\mathcal{S} = \\{s_1, s_2, ..., s_n\\}$.\nIf we can take any two elements\n(call them $x$ and $y$) and say that either $x > y$ or $y > x$ (where\nwe get to define what ``greater than'' means for a particular application),\nthen $\\mathcal{S}$ is a {\\em totally ordered set}. The definition of\n$>$ that you use has to have the properties that $>$ usually does. For\nexample, if $x > y$ and $y > z$, then $x > z$. \nLater, there will be a concept called a {\\em chain} which is pretty much\nthe same as a partially ordered set.\nIf you are used to computer programming, then any\nlist/vector/array of items which can be unambiguously sorted\nis a totally ordered set.\n\nWe can draw this situation using points on a line\n(Figure~\\ref{fig:totally_ordered_set}).\nEach point\nrepresents an element of the set, and they are arranged from highest\nto lowest in terms of which elements are ``greater than'' other elements.\nThat is, if $x > y$ (element\n$x$ is ranked above element $y$), then $x$ is drawn above $y$ in the\ndiagram.\n\n\\begin{figure}[!ht]\n\\centering\n\\includegraphics[scale=0.6]{figures/totally_ordered_set.pdf}\n\\caption{A set with five elements, each represented by a black dot.\nWhen one dot is above another and they are connected with a line, it\nmeans the higher element is greater than (using whatever definition of $>$ we\nchoose) the lower one.\nThis is a simple example of a {\\em Hasse diagram}. More complex\nHasse diagrams will appear later.\\label{fig:totally_ordered_set}}\n\\end{figure}\n\n\n\\section{The sum rule}\n\n\\section{Measure in boolean lattices}\n\n\n\\begin{figure}[!ht]\n\\centering\n\\includegraphics[width=0.5\\textwidth]{figures/boolean_lattice.pdf}\n\\caption{\\label{fig:boolean_lattice}}\n\\end{figure}\n\n\nApples.\nOne bag of apples combined with another bag of apples.\nThe exact same situation. The numbers of apples add, as\ndo the masses. Two different sum rules apply to the same\nsituation!\n\n\n\\section{Infidelity and ``signed measure''}\n\n\\subsection{A fate worse than death}\n\nInfidelity allows for fates worse than death.\nAn absence of experience, denoted $\\bot$,\nhas measure zero, so you can add arbitrary amounts\nof non-existence to any experience without changing\nits quality. So, for example:\n\\begin{align}\nm(😃 \\vee \\bot)        &= m(😃)\\\\\nm(😀 \\vee 😪 \\vee \\bot) &= m(😀 \\vee 😪)\n\\end{align}\nand so on.\nIn other words, $\\bot$ is the {\\em identity element}\nof the set of potential experiences.\n\n\\bibliographystyle{chicago}\n\\bibliography{references}\n\n\\end{document}\n\n", "meta": {"hexsha": "23873e919ade73a5e85e491072c73ae1d9aa032e", "size": 3371, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/1_addition.tex", "max_stars_repo_name": "eggplantbren/KnuthForDummies", "max_stars_repo_head_hexsha": "40fb205c7ce2330d0cfea9d66e3ac2e11993de50", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-09-26T10:36:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-10T03:17:07.000Z", "max_issues_repo_path": "doc/1_addition.tex", "max_issues_repo_name": "eggplantbren/KnuthForDummies", "max_issues_repo_head_hexsha": "40fb205c7ce2330d0cfea9d66e3ac2e11993de50", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/1_addition.tex", "max_forks_repo_name": "eggplantbren/KnuthForDummies", "max_forks_repo_head_hexsha": "40fb205c7ce2330d0cfea9d66e3ac2e11993de50", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9266055046, "max_line_length": 77, "alphanum_fraction": 0.7439928805, "num_tokens": 955, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3327867186228418}}
{"text": "\\documentclass[11pt,oneside]{article}    %use\"amsart\"insteadof\"article\"forAMSLaTeXformat\n\\usepackage{geometry}        %Seegeometry.pdftolearnthelayoutoptions.Therearelots.\n\\geometry{letterpaper}        %...ora4paperora5paperor...\n%\\geometry{landscape}        %Activateforforrotatedpagegeometry\n%\\usepackage[parfill]{parskip}        %Activatetobeginparagraphswithanemptylineratherthananindent\n\\usepackage{graphicx}                %Usepdf,png,jpg,orepsßwithpdflatex;useepsinDVImode\n                                %TeXwillautomaticallyconverteps-->pdfinpdflatex        \n\\usepackage{amssymb}\n\\usepackage[colorlinks]{hyperref}\n\n%----macros begin---------------------------------------------------------------\n\\usepackage{color}\n\\usepackage{amsthm}\n\n\\def\\conv{\\mbox{\\textrm{conv}\\,}}\n\\def\\aff{\\mbox{\\textrm{aff}\\,}}\n\\def\\E{\\mathbb{E}}\n\\def\\R{\\mathbb{R}}\n\\def\\Z{\\mathbb{Z}}\n\\def\\tex{\\TeX}\n\\def\\latex{\\LaTeX}\n\\def\\v#1{{\\bf #1}}\n\\def\\p#1{{\\bf #1}}\n\\def\\T#1{{\\bf #1}}\n\n\\def\\vet#1{{\\left(\\begin{array}{cccccccccccccccccccc}#1\\end{array}\\right)}}\n\\def\\mat#1{{\\left(\\begin{array}{cccccccccccccccccccc}#1\\end{array}\\right)}}\n\n\\def\\lin{\\mbox{\\rm lin}\\,}\n\\def\\aff{\\mbox{\\rm aff}\\,}\n\\def\\pos{\\mbox{\\rm pos}\\,}\n\\def\\cone{\\mbox{\\rm cone}\\,}\n\\def\\conv{\\mbox{\\rm conv}\\,}\n\\newcommand{\\homog}[0]{\\mbox{\\rm homog}\\,}\n\\newcommand{\\relint}[0]{\\mbox{\\rm relint}\\,}\n\n%----macros end-----------------------------------------------------------------\n\n\\title{Hierarchical structures with LAR\n\\footnote{This document is part of the \\emph{Linear Algebraic Representation with CoChains} (LAR-CC) framework~\\cite{cclar-proj:2013:00}. \\today}\n}\n\\author{Alberto Paoluzzi}\n%\\date{}                            %Activatetodisplayagivendateornodate\n\n\\begin{document}\n\\maketitle\n\\nonstopmode\n\n\\tableofcontents\n\n\n\n%===============================================================================\n\\section{Affine transformations}\n%===============================================================================\n%-------------------------------------------------------------------------------\n\\subsection{Design decision}\n%-------------------------------------------------------------------------------\nFirst we state the general rules that will be satisfied by the matrices used in this module, mainly devoted to apply affine transformations to vertices of models in structure environments:\n\\begin{enumerate}\n\\item assume the scipy \\texttt{ndarray} as the type of vertices, stored in row-major order;\n\\item use the last coordinate as the homogeneous coordinate of vertices, but do not store it explicitly;\n\\item store explicitly the homogeneous coordinate of transformation matrices.\n\\item use labels '\\texttt{verts}' and '\\texttt{mat}' to distinguish between vertices and transformation matrices.\n\\item transformation matrices are dimension-independent, and their dimension is computed as the length of the parameter vector passed to the generating function.\n\\end{enumerate}\n\n\n%-------------------------------------------------------------------------------\n\\subsection{Affine mapping}\n%-------------------------------------------------------------------------------\n\n%-------------------------------------------------------------------------------\n@D Apply an affine transformation to a LAR model \n@{\"\"\" Apply an affine transformation to a LAR model  \"\"\"\nfrom scipy import array\n\ndef larApply(affineMatrix):\n    def larApply0(model):\n        if isinstance(model,Model):\n            V = scipy.dot(array([v+[1.0] for v in model.verts]), affineMatrix.T).tolist()\n            V = [v[:-1] for v in V]\n            CV = copy.copy(model.cells)\n            return Model((V,CV))\n        elif isinstance(model,tuple) or isinstance(model,list):\n            if len(model)==2: V,CV = model\n            elif len(model)==3: V,CV,FV = model\n            V = scipy.dot([list(v)+[1.0] for v in V], affineMatrix.T).tolist()\n            if len(model)==2: return [v[:-1] for v in V],CV\n            elif len(model)==3: return [v[:-1] for v in V],CV,FV\n    return larApply0\n@}\n%-------------------------------------------------------------------------------\n\n\n%-------------------------------------------------------------------------------\n\\subsection{Elementary matrices}\n%-------------------------------------------------------------------------------\nElementary matrices for affine transformation of vectors in any dimensional vector space are defined here. They include translation, scaling, rotation and shearing. \n\n\\paragraph{Translation}\n%-------------------------------------------------------------------------------\n@D Translation matrices\n@{def t(*args): \n    d = len(args)\n    mat = scipy.identity(d+1)\n    for k in range(d): \n        mat[k,d] = args[k]\n    return mat.view(Mat)\n@}\n%-------------------------------------------------------------------------------\n\\paragraph{Scaling}\n%-------------------------------------------------------------------------------\n@D Scaling matrices\n@{def s(*args): \n    d = len(args)\n    mat = scipy.identity(d+1)\n    for k in range(d): \n        mat[k,k] = args[k]\n    return mat.view(Mat)\n@}\n%-------------------------------------------------------------------------------\n\\paragraph{Rotation}\n%-------------------------------------------------------------------------------\n@D Rotation matrices\n@{def r(*args): \n    args = list(args)\n    n = len(args)\n    @< plane rotation (in 2D) @>\n    @< space rotation (in 3D) @>\n    return mat.view(Mat)\n@}\n%-------------------------------------------------------------------------------\n%-------------------------------------------------------------------------------\n@D plane rotation (in 2D)\n@{if n == 1: # rotation in 2D\n    angle = args[0]; cos = COS(angle); sin = SIN(angle)\n    mat = scipy.identity(3)\n    mat[0,0] = cos;    mat[0,1] = -sin;\n    mat[1,0] = sin;    mat[1,1] = cos;\n@}\n%-------------------------------------------------------------------------------\n%-------------------------------------------------------------------------------\n@D space rotation (in 3D)\n@{if n == 3: # rotation in 3D\n    mat = scipy.identity(4)\n    angle = VECTNORM(args); axis = UNITVECT(args)\n    cos = COS(angle); sin = SIN(angle)\n    @< elementary rotations (in 3D) @>\n    @< general rotations (in 3D) @>\n@}\n%-------------------------------------------------------------------------------\n%-------------------------------------------------------------------------------\n@D elementary rotations (in 3D)\n@{if axis[1]==axis[2]==0.0:    # rotation about x\n    mat[1,1] = cos;    mat[1,2] = -sin;\n    mat[2,1] = sin;    mat[2,2] = cos;\nelif axis[0]==axis[2]==0.0:    # rotation about y\n    mat[0,0] = cos;    mat[0,2] = sin;\n    mat[2,0] = -sin;    mat[2,2] = cos;\nelif axis[0]==axis[1]==0.0:    # rotation about z\n    mat[0,0] = cos;    mat[0,1] = -sin;\n    mat[1,0] = sin;    mat[1,1] = cos;\n@}\n%-------------------------------------------------------------------------------\n%-------------------------------------------------------------------------------\n@D general rotations (in 3D)\n@{else:        # general 3D rotation (Rodrigues' rotation formula)    \n    I = scipy.identity(3) ; u = axis\n    Ux = scipy.array([\n        [0,        -u[2],      u[1]],\n        [u[2],        0,     -u[0]],\n        [-u[1],     u[0],         0]])\n    UU = scipy.array([\n        [u[0]*u[0],    u[0]*u[1],    u[0]*u[2]],\n        [u[1]*u[0],    u[1]*u[1],    u[1]*u[2]],\n        [u[2]*u[0],    u[2]*u[1],    u[2]*u[2]]])\n    mat[:3,:3] = cos*I + sin*Ux + (1.0-cos)*UU\n@}\n\n\n%===============================================================================\n\\section{Structure types handling}\n%===============================================================================\n\nIn order to implement a structure as a list of models and transformations, we need to be able to distinguish between two different types of scipy arrays. The first type is the one of arrays of vertices, the second one is the matrix array used to represent the fine transformations.\n\n\\subsection{\\texttt{Mat} and \\texttt{Verts} classes}\n%-------------------------------------------------------------------------------\n@D types Mat and Verts\n@{\"\"\" class definitions for LAR \"\"\"\nimport scipy\nclass Mat(scipy.ndarray): pass\nclass Verts(scipy.ndarray): pass\n@}\n%-------------------------------------------------------------------------------\n\n\\subsection{\\texttt{Model} class}\n%-------------------------------------------------------------------------------\n@D Model class\n@{class Model:\n    \"\"\" A pair (geometry, topology) of the LAR package \"\"\"\n    def __init__(self,(verts,cells)):\n        self.n = len(verts[0])\n        # self.verts = scipy.array(verts).view(Verts)\n        self.verts = verts\n        self.cells = cells\n    def __getitem__(self,i):\n        return list((self.verts,self.cells))[i]\n@}\n%-------------------------------------------------------------------------------\n\n\\subsection{\\texttt{Struct} iterable class}\n%-------------------------------------------------------------------------------\n@D Struct class\n@{\"\"\" Struct iterable class \"\"\"\nclass Struct:\n    \"\"\" The assembly type of the LAR package \"\"\"\n    def __init__(self,data=None,name=None,category=None):\n        if data==None or data==[]:\n            self.body = []\n        else:\n            self.body = [item for item in data if item != None]\n            self.box = box(self) \n            self.dim = len(self.box[0])\n        if name != None: \n            self.name = str(name)\n        else:\n            self.name = str(id(self))\n        if category != None: \n            self.category = str(category)\n        else:\n            self.category = \"feature\"\n    def __name__(self):\n        return self.name\n    def __category__(self):\n        return self.category\n    def __iter__(self):\n        return iter(self.body)\n    def __len__(self):\n        return len(list(self.body))\n    def __getitem__(self,i):\n        return list(self.body)[i]\n    def __setitem__(self,i,value):\n        self.body[i] = value\n    def __print__(self): \n        return \"<Struct name: %s>\" % self.__name__()\n    def __repr__(self):\n        return \"<Struct name: %s>\" % self.__name__()\n        #return \"'Struct(%s,%s)'\" % (str(self.body),str(str(self.__name__())))\n    def set_name(self,name):\n        self.name = str(name)\n    def clone(self,i=0):\n        from copy import deepcopy\n        newObj = deepcopy(self)\n        if i != 0: newObj.name = self.name + \"_\" + str(i)\n        return newObj\n    def set_category(self,category):\n        self.category = str(category)\n    def larBoundary(self):\n        data = struct2lar(self)\n        if len(data) == 3:\n            V,FV,EV = data\n            #import pdb; pdb.set_trace()\n            return V,FV,EV\n        else:\n            return \"<Struct name: %s> boundary non computable\" % self.__name__()\n    def draw(self,color=WHITE,scaling=1,metric=ID):\n        vmin,vmax = self.box\n        delta = VECTDIFF([vmax,vmin])\n        point = CCOMB(self.box)\n        scalingFactor = scaling*delta[0]/20.\n        text = TEXTWITHATTRIBUTES (TEXTALIGNMENT='centre', TEXTANGLE=0,\n                    TEXTWIDTH=0.1*scalingFactor, \n                    TEXTHEIGHT=0.2*scalingFactor,\n                    TEXTSPACING=0.025*scalingFactor)\n        point = metric([point])[0]\n        return T([1,2,3])(point)(COLOR(color)(text(self.name)))\n@}\n%-------------------------------------------------------------------------------\n\n\n\\subsection{\\texttt{Struct} containment box}\n\n%-------------------------------------------------------------------------------\n@D Computation of the containment box of a Lar Struct or Model\n@{\"\"\" Computation of the containment box of a Lar Struct or Model \"\"\"\nimport copy\ndef box(model):\n    if isinstance(model,Mat): return []\n    elif isinstance(model,Struct):\n        dummyModel = copy.deepcopy(model)\n        dummyModel.body = [term if (not isinstance(term,Struct)) else [term.box,[[0,1]]]  for term in model.body]\n        listOfModels = evalStruct( dummyModel )\n        #dim = checkStruct(listOfModels)\n        theMin,theMax = box(listOfModels[0]) \n        for theModel in listOfModels[1:]:\n            modelMin, modelMax = box(theModel)\n            theMin = [val if val<theMin[k] else theMin[k] for k,val in enumerate(modelMin)]\n            theMax = [val if val>theMax[k] else theMax[k] for k,val in enumerate(modelMax)]\n        return [theMin,theMax]\n    elif isinstance(model,Model):\n        V = model.verts\n    elif (isinstance(model,tuple) or isinstance(model,list)) and (len(model)==2 or len(model)==3):\n        V = model[0]\n    coords = TRANS(V)\n    theMin = [min(coord) for coord in coords]\n    theMax = [max(coord) for coord in coords]\n    return [theMin,theMax]\n@}\n%-------------------------------------------------------------------------------\n\n\n%-------------------------------------------------------------------------------\n\\section{Structure to LAR conversion}\n%-------------------------------------------------------------------------------\n\n\\subsection{Remove duplicate faces}\n%-------------------------------------------------------------------------------\n@D Remove duplicate faces\n@{\"\"\" Remove duplicate faces  \"\"\"\nfrom collections import defaultdict\ndef removeDups (CW):\n    CW = list(set(AA(tuple)(CW)))\n    CWs = list(set(AA(tuple)  (AA(sorted)(CW))  ))\n    no_duplicates = defaultdict(list)\n    for f in CWs: no_duplicates[f] = []\n    for f in CW:\n        no_duplicates[tuple(sorted(f))] += [f]\n    CW = [f[0] for f in no_duplicates.values()]\n    return CW\n@}\n%-------------------------------------------------------------------------------\n\n\n\\subsection{Structure to pair (Vertices,Cells) conversion}\n%-------------------------------------------------------------------------------\n@D Structure to pair (Vertices,Cells) conversion\n@{\"\"\" Structure to pair (Vertices,Cells) conversion \"\"\"\n\ndef struct2lar(structure,metric=ID):\n    listOfModels = evalStruct(structure)\n    vertDict = dict()\n    index,defaultValue,CW,W,FW = -1,-1,[],[],[]\n        \n    for model in listOfModels:\n        if isinstance(model,Model):\n            V,FV = model.verts,model.cells\n        elif (isinstance(model,tuple) or isinstance(model,list)):\n            if len(model)==2: V,FV = model\n            elif len(model)==3: V,FV,EV = model\n        for k,incell in enumerate(FV):\n            outcell = []\n            for v in incell:\n                key = vcode(4)(V[v])\n                if vertDict.get(key,defaultValue) == defaultValue:\n                    index += 1\n                    vertDict[key] = index\n                    outcell += [index]\n                    W += [eval(key)]\n                else: \n                    outcell += [vertDict[key]]\n            CW += [outcell]\n        if len(model)==3:\n            for k,incell in enumerate(EV):\n                outcell = []\n                for v in incell:\n                    key = vcode(4)(V[v])\n                    if vertDict.get(key,defaultValue) == defaultValue:\n                        index += 1\n                        vertDict[key] = index\n                        outcell += [index]\n                        W += [eval(key)]\n                    else: \n                        outcell += [vertDict[key]]\n                FW += [outcell]\n            \n    if ((isinstance(model,tuple) or isinstance(model,list)) and len(model)==2) or (\n        (isinstance(model,Model) and model.n==2)): \n        if len(CW[0])==2: \n            CW = list(set(AA(tuple)(AA(sorted)(CW))))\n        else: CW = removeDups(CW)\n        return metric(W),CW\n    if ((isinstance(model,tuple) or isinstance(model,list)) and len(model)==3) or (\n        (isinstance(model,Model) and model.n==3)): \n        FW = list(set(AA(tuple)(AA(sorted)(FW))))\n        CW = removeDups(CW)\n        return metric(W),CW,FW\n@}\n%-------------------------------------------------------------------------------\n\n\n\n\\subsection{Model simplification}\n\n\\paragraph{Remove double instances of cells}\n\n%-------------------------------------------------------------------------------\n@O test/py/larstruct/test10.py\n@{\"\"\" Remove double instances of cells (and the unused vertices) \"\"\"\nfrom larlib import *\n\n@< Transform Struct object to LAR model pair @>\n@< Remove the double instances of cells @>\nVIEW(EXPLODE(1.2,1.2,1.2)(MKPOLS((W,FW))))\n\n@< Remove the unused vertices @>\n@}\n%-------------------------------------------------------------------------------\n\nThe actual removal of double cells (useful in several applications, and in particular in the extraction of boundary models from 3D medical images) is performed by first generating a dictionary of cells, using as key the tuple given by the cells themselves, and then removing those discovered having a double instance.\nThe algorithm is extremely simple, and its implementation, given below, is straightforward.\n\n%-------------------------------------------------------------------------------\n@D Remove the double instances of cells\n@{\"\"\" Remove the double instances of cells \"\"\"\ncellDict = defaultdict(list)\nfor k,cell in enumerate(FW):\n    cellDict[tuple(cell)] += [k]\nFW = [list(key) for key in cellDict.keys() if len(cellDict[key])==1]\n@}\n%-------------------------------------------------------------------------------\n\n%-------------------------------------------------------------------------------\n@D Remove the unused vertices\n@{\"\"\" Remove the unused vertices \"\"\"\nprint \"len(W) =\",len(W)\nV,FV = larRemoveVertices(W,FW)\nprint \"len(V) =\",len(V)\n@}\n%-------------------------------------------------------------------------------\n\n%-------------------------------------------------------------------------------\n@D Remove the unused vertices from a LAR model pair\n@{\"\"\" Remove the unused vertices \"\"\"\ndef larRemoveVertices(V,FV):\n    vertDict = dict()\n    index,defaultValue,FW,W = -1,-1,[],[]\n        \n    for k,incell in enumerate(FV):\n        outcell = []\n        for v in incell:\n            key = vcode(4)(V[v])\n            if vertDict.get(key,defaultValue) == defaultValue:\n                index += 1\n                vertDict[key] = index\n                outcell += [index]\n                W += [eval(key)]\n            else: \n                outcell += [vertDict[key]]\n        FW += [outcell]\n    return W,FW\n@}\n%-------------------------------------------------------------------------------\n\n\n\n\n\n\\subsection{Embedding or projecting LAR models}\n%-------------------------------------------------------------------------------\n\nIn order to apply 3D transformations to a two-dimensional LAR model, we must embed it in 3D space, by adding one more coordinate to its vertices. \n\n\\paragraph{Embedding or projecting a geometric model}\n\nThis task is performed by the function \\texttt{larEmbed} with parameter $k$, that inserts its $d$-dimensional geometric argument in the $x_{d+1}, \\ldots, x_{d+k}=0$ subspace of $\\E^{d+k}$.\nA projection transformation, that removes the last $k$ coordinate of vertices, without changing the object topology, is performed by the function \\texttt{larEmbed} with \\emph{negative} integer parameter.\n\n\n%-------------------------------------------------------------------------------\n@D Embedding and projecting a geometric model\n@{def larEmbed(k):\n    def larEmbed0(model):\n        if len(model)==2: V,CV = model\n        elif len(model)==3: V,CV,FV = model\n        if k>0:\n            V = [v+[0.]*k for v in V] \n        elif k<0:\n            V = [v[:-k] for v in V] \n        if len(model)==2: return V,CV\n        elif len(model)==3: return V,CV,FV\n    return larEmbed0\n\ndef larEmbed(k):\n    def larEmbed0(model):\n        if k>0:\n            model[0] = [v+[0.]*k for v in model[0]] \n        elif k<0:\n            model[0] = [v[:-k] for v in model[0]] \n        return model\n    return larEmbed0\n@}\n%-------------------------------------------------------------------------------\n\n%===============================================================================\n\\section{Hierarchical complexes}\n%===============================================================================\nHierarchical models of complex assemblies are generated by an aggregation\nof subassemblies, each one defined in a local coordinate system, and\nrelocated by affine transformations of coordinates.  This operation\nmay be repeated hierarchically, with some subassemblies defined by\naggregation of simpler parts, and so on, until one obtains a set of\nelementary components, which cannot be further decomposed.\n\nTwo main advantages can be found in a hierarchical modeling approach. Each elementary part and each assembly, at every hierarchical level, are defined independently from each other, using a local coordinate frame, suitably chosen to make its definition easier. Furthermore, only one copy of each component is stored in the memory, and may be instanced in different locations and orientations how many times it is needed.\n\n%-------------------------------------------------------------------------------\n\\subsection{Traversal of hierarchical structures}\n%-------------------------------------------------------------------------------\n\nOf course, the main algorithm with hierarchical structures is the \\emph{traversal} of the structure network, whose aim is to transform every encountered object from local to global coordinates, where the global coordinates are those of the network root (the only node with indegree zero).\n\nA structure network can be modelled using a directed acyclic multigraph, i.e.~a triple $(N,A,f)$\nmade by a set $N$ of nodes, a set $A$ of arcs, and a function $f:A \\to N^2$ from arcs to ordered pairs of nodes. Conversely that in standard oriented graphs, in this kind of structure more than one oriented arc is allowed between the same pair on nodes.\n\n\\begin{figure}[htbp] %  figure placement: here, top, bottom, or page\n   \\centering\n   \\includegraphics[width=0.8\\linewidth]{images/traversal} \n   \\caption{Traversal algorithm of an acyclic multigraph.}\n   \\label{fig:traversal}\n\\end{figure}\n\nA simple modification of a DFS (Depth First Search) visit of a graph can be used to traverse the structure network This algorithm is given in Figure~\\ref{fig:traversal} from~\\cite{Paoluzzi2003a}. \n\n\\subsubsection{Traversal of nested lists}\n\nThe representation chosen for structure networks with LAR is the serialised one, consisting in ordered sequences (lists) of either (a) LAR models, or (b) affine transformations, or (c) references to other structures, either directly nested within some given structure, or called by reference (name) from within the list.\n\nThe usual aim of a structure network traversal is, of course, to transform every component structure, usually defined in a local coordinate system, into the reference frame of the structure as a whole, normally corresponding with the reference system of the structure's root, called the \\emph{world coordinate} system.\n\n\\paragraph{The pattern of calls and returned values}\n\nIn order to better understand the behaviour of the traversal algorithm, where every transformation is applied to all the following models, --- but only if included in the same structure  (i.e.~list) --- it may be very useful to start with an \\emph{algorithm emulation}. In particular, the recursive script below discriminates between three different cases (number, string, or sequence), whereas the actual traversal must do with (a) Models, (b) Matrices, and (c) Structures, respectively.\n\n%-------------------------------------------------------------------------------\n@D Emulation of scene multigraph traversal\n@{\"\"\" Emulation of scene multigraph traversal \"\"\" \nfrom larlib import *\n\ndef __traverse(CTM, stack, o):\n    for i in range(len(o)):\n        if ISNUM(o[i]): print o[i], REVERSE(CTM)\n        elif ISSTRING(o[i]): \n            CTM.append(o[i])\n        elif ISSEQ(o[i]):\n            stack.append(o[i])                # push the stack\n            __traverse(CTM, stack, o[i])\n            CTM = CTM[:-len(stack)]         # pop the stack\n\ndef algorithm(data):\n    CTM,stack = [\"I\"],[]\n    __traverse(CTM, stack, data)  \n@}\n%-------------------------------------------------------------------------------\n\nSome use example of the above algorithm are provided below. The printout produced at run time is shown from the \\texttt{emulation of traversal algorithm} macro.\n%-------------------------------------------------------------------------------\n@D Examples of multigraph traversal\n@{data = [1,\"A\", 2, 3, \"B\", [4, \"C\", 5], [6,\"D\", \"E\", 7, 8], 9]  \nprint algorithm(data)\n>>> 1 ['I']\n    2 ['A', 'I']\n    3 ['A', 'I']\n    4 ['B', 'A', 'I']\n    5 ['C', 'B', 'A', 'I']\n    6 ['B', 'A', 'I']\n    7 ['E', 'D', 'B', 'A', 'I']\n    8 ['E', 'D', 'B', 'A', 'I']\n    9 ['B', 'A', 'I']\n\ndata = [1,\"A\", [2, 3, \"B\", 4, \"C\", 5, 6,\"D\"], \"E\", 7, 8, 9]  \nprint algorithm(data)\n>>> 1 ['I']\n    2 ['A', 'I']\n    3 ['A', 'I']\n    4 ['B', 'A', 'I']\n    5 ['C', 'B', 'A', 'I']\n    6 ['C', 'B', 'A', 'I']\n    7 ['E', 'A', 'I']\n    8 ['E', 'A', 'I']\n    9 ['E', 'A', 'I']\n@}\n%-------------------------------------------------------------------------------\n%-------------------------------------------------------------------------------\n@D Emulation of traversal algorithm\n@{dat = [2, 3, \"B\", 4, \"C\", 5, 6,\"D\"]\nprint algorithm(dat)\n>>> 2 ['I']\n    3 ['I']\n    4 ['B', 'I']\n    5 ['C', 'B', 'I']\n    6 ['C', 'B', 'I']\ndata = [1,\"A\", dat, \"E\", 7, 8, 9]\nprint algorithm(data)\n>>> 1 ['I']\n    2 ['A', 'I']\n    3 ['A', 'I']\n    4 ['B', 'A', 'I']\n    5 ['C', 'B', 'A', 'I']\n    6 ['C', 'B', 'A', 'I']\n    7 ['E', 'A', 'I']\n    8 ['E', 'A', 'I']\n    9 ['E', 'A', 'I']\n@}\n%-------------------------------------------------------------------------------\n\n\\paragraph{Traversal of a scene multigraph}\n\nThe previous traversal algorithm is here customised for scene multigraph, where the objects are LAR models, i.e.~pairs of vertices of type '\\texttt{Verts} and cells, and where the transformations are matrix transformations of type '\\texttt{Mat}'.\n\n\\paragraph{Check models for common dimension}\nThe input list of a call to \\texttt{larStruct} primitive is preliminary checked for uniform dimensionality of the enclosed LAR models and transformations. The common dimension \\texttt{dim} of models and matrices is returned by the function \\texttt{checkStruct}, within the class definition \\texttt{Struct} in the module \\texttt{lar2psm}. Otherwise, an exception is generated (TODO).\n\n%-------------------------------------------------------------------------------\n@D Check for dimension of a structure element (Verts or V)\n@{@< Flatten a list @>\ndef checkStruct(lst):\n    \"\"\" Return the common dimension of structure elements.\n\n        TODO: aggiungere test sulla dimensione minima delle celle (legata a quella di immersione)\n    \"\"\"\n    obj = lst[0]\n    if (isinstance(obj,tuple) or isinstance(obj,list)):\n        dim = len(obj[0][0])\n    elif isinstance(obj,Model): \n        dim = obj.n    \n    elif isinstance(obj,Mat): \n        dim = obj.shape[0]-1    \n    elif isinstance(obj,Struct): \n        dim = len(obj.box[0])    \n    return dim\n@}\n%-------------------------------------------------------------------------------\n\n\\paragraph{Flatten a list using Python generators}\nThe \\texttt{flatten} is a generator that yields the non-list values of its input in order. In the example, the generator is converted back to a list before printing. Modified from \\href{http://rosettacode.org/wiki/Flatten_a_list#Python}{\\emph{Rosetta code}} project. It is used here to flatten a structure in order to check for common dimensionality of elements.\n\n%-------------------------------------------------------------------------------\n@D Flatten a list\n@{\"\"\" Flatten a list using Python generators \"\"\"\ndef flatten(lst):\n    for x in lst:\n        if (isinstance(x,tuple) or isinstance(x,list)) and len(x)==2:\n            yield x\n        elif (isinstance(x,tuple) or isinstance(x,list)):\n            for x in flatten(x):\n                yield x\n        elif isinstance(x, Struct):\n            for x in flatten(x.body):\n                yield x\n        else:\n            yield x\n \n#  lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]\n#  print list(flatten(lst)) \n#  [1, 2, 3, 4, 5, 6, 7, 8]\n\n#  import itertools\n#  chain = itertools.chain.from_iterable([[1,2],[3],[5,89],[],[6]])\n#  print(list(chain))\n#  [1, 2, 3, 5, 89, 6]    ###  TODO: Bug coi dati sopra?\n@}\n%-------------------------------------------------------------------------------\n\n\\paragraph{Initialization and call of the algorithm}\n\nThe function \\texttt{evalStruct} is used to evaluate a structure network, i.e.~to return a \\texttt{scene}\nlist of objects of type \\texttt{Model}, all referenced in the world coordinate system. The input variable \\texttt{struct} must contain an object of class \\texttt{Struct}, i.e.~a reference to an unevaluated structure network. The variable \\texttt{dim}  contains the embedding dimension of the structure, i.e.~the number of coordinates of its vertices (normally either 2 or 3), the CTM (Current Transformation Matrix) is initialised to the (homogeneous) identity matrix, and  the \\texttt{scene} is returned by calling the \\texttt{traverse} algorithm.\n\n%-------------------------------------------------------------------------------\n@D Traversal of a scene multigraph\n@{\"\"\" Traversal of a scene multigraph \"\"\"\n@< Structure traversal algorithm @>\ndef evalStruct(struct):\n    dim = checkStruct(struct.body)\n    CTM, stack = scipy.identity(dim+1), []\n    scene = traversal(CTM, stack, struct, []) \n    return scene\n@}\n%-------------------------------------------------------------------------------\n\n\\paragraph{Structure traversal algorithm}\n\nThe \\texttt{traversal} algorithm decides between three different cases, depending on the type of the currently inspected object. If the object is a \\texttt{Model} instance, then applies to it the \\texttt{CTM} matrix; else if the object is a \\texttt{Mat} instance, then the \\texttt{CTM} matrix is updated by (right) product with it; else if the object is a \\texttt{Struct} instance, then the \\texttt{CTM} is pushed on the stack, initially empty, then the \\texttt{traversal} is called (recursion), and finally, at (each) return from recursion, the \\texttt{CTM} is recovered by popping the stack.\n\n%-------------------------------------------------------------------------------\n@D Structure traversal algorithm \n@{def traversal(CTM, stack, obj, scene=[]):\n    for i in range(len(obj)):\n        if isinstance(obj[i],Model): \n            scene += [larApply(CTM)(obj[i])]\n        elif (isinstance(obj[i],tuple) or isinstance(obj[i],list)) and (\n                len(obj[i])==2 or len(obj[i])==3):\n            scene += [larApply(CTM)(obj[i])]\n        elif isinstance(obj[i],Mat): \n            CTM = scipy.dot(CTM, obj[i])\n        elif isinstance(obj[i],Struct):\n            stack.append(CTM) \n            traversal(CTM, stack, obj[i], scene)\n            CTM = stack.pop()\n    return scene\n@}\n%-------------------------------------------------------------------------------\n\n\\paragraph{Structure embedding algorithm}\n%-------------------------------------------------------------------------------\n@D Embed a struct object\n@{\"\"\" embed a struct object \"\"\"\n@< Structure embedding algorithm  @>\n\ndef embedStruct(n):\n    def embedStruct0(struct,suffix=\"New\"):\n        if n==0: \n            return struct, len(struct.box[0])\n        cloned = Struct()\n        cloned.box = hstack((struct.box, [n*[0],n*[0]])).tolist()\n        cloned.name = str(id(cloned))  #struct.name+suffix\n        cloned.category = struct.category\n        cloned.dim = struct.dim + n\n        cloned = embedTraversal(cloned,struct,n,suffix) \n        return cloned\n    return embedStruct0\n@}\n%-------------------------------------------------------------------------------\n\n\\paragraph{Structure embedding algorithm}\n%-------------------------------------------------------------------------------\n@D Structure embedding algorithm \n@{\"\"\" Structure embedding algorithm \"\"\"\ndef embedTraversal(cloned, obj,n,suffix):\n    for i in range(len(obj)):\n        if isinstance(obj[i],Model): \n            cloned.body += [obj[i]]\n        elif (isinstance(obj[i],tuple) or isinstance(obj[i],list)) and (\n                len(obj[i])==2):\n            V,EV = obj[i]\n            V = [v+n*[0.0] for v in V]\n            cloned.body  += [(V,EV)]\n        elif (isinstance(obj[i],tuple) or isinstance(obj[i],list)) and (\n                len(obj[i])==3):\n            V,FV,EV = obj[i]\n            V = [v+n*[0.0] for v in V]\n            cloned.body  += [(V,FV,EV)]\n        elif isinstance(obj[i],Mat): \n            mat = obj[i]\n            d,d = mat.shape\n\n            newMat = scipy.identity(d+n*1)\n            for h in range(d-1): \n                for k in range(d-1): \n                    newMat[h,k] = mat[h,k]\n                newMat[h,d-1+n*1] = mat[h,d-1]\n            cloned.body  +=  [newMat.view(Mat)]\n\n        elif isinstance(obj[i],Struct):\n            newObj = Struct()\n            newObj.box = hstack((obj[i].box, [n*[0],n*[0]]))\n            newObj.name = obj[i].name+suffix\n            newObj.category = obj[i].category\n            cloned.body  += [embedTraversal(newObj, obj[i], n, suffix)]\n    return cloned\n@}\n%-------------------------------------------------------------------------------\n\n\n\n\n%===============================================================================\n\\section{Larstruct exporting}\n%===============================================================================\n\\label{sec:larstruct}\nHere we assemble top-down the \\texttt{lar2psm} module, by orderly listing the functional parts it is composed of. Of course, this one is the module version corresponding to the current state of the system, i.e.~to a very initial state. Other functions will be added when needed.\n%------------------------------------------------------------------\n@O larlib/larlib/larstruct.py\n@{\"\"\"Module with functions needed to interface LAR with pyplasm via Struct\"\"\"\nfrom larlib import *\n\n@< Symbolic utility to represent points as strings @>\n@< Translation matrices @>\n@< Scaling matrices @>\n@< Rotation matrices @>\n@< Embedding and projecting a geometric model @>\n@< Apply an affine transformation to a LAR model @>\n@< Check for dimension of a structure element (Verts or V) @>\n@< Remove duplicate faces @>\n@< Remove the unused vertices from a LAR model pair @>\n@< Traversal of a scene multigraph @>\n@< types Mat and Verts @>\n@< Model class @>\n@< Struct class @>\n@< Structure to pair (Vertices,Cells) conversion @>\n@< Embedding and projecting a geometric model @>\n@< Embed a struct object @>\n@< Computation of the containment box of a Lar Struct or Model @>\n@}\n%------------------------------------------------------------------\n\n%-------------------------------------------------------------------------------\n%===============================================================================\n\\section{Examples}\n%===============================================================================\n%-------------------------------------------------------------------------------\nSome examples of structures as combinations of LAR models and affine transformations are given in this section. \n\n\\paragraph{Global coordinates}\nWe start with a simple 2D example of a non-nested list of translated 2D object instances and rotation about the origin.\n\n%-------------------------------------------------------------------------------\n@O test/py/larstruct/test04.py\n@{\"\"\" Example of non-nested structure with translation and rotations \"\"\"\nfrom larlib import *\n\nsquare = larCuboids([1,1])\ntable = larApply( t(-.5,-.5) )(square)\nchair = larApply( s(.35,.35) )(table)\nchair1 = larApply( t(.75, 0) )(chair)\nchair2 = larApply( r(PI/2) )(chair1)\nchair3 = larApply( r(PI/2) )(chair2)\nchair4 = larApply( r(PI/2) )(chair3)\nVIEW(SKEL_1(STRUCT(MKPOLS(table)+MKPOLS(chair1)+\n                   MKPOLS(chair2)+MKPOLS(chair3)+MKPOLS(chair4))))\n@}\n%-------------------------------------------------------------------------------\n\n\\paragraph{Local coordinates}\nA different composition of transformations, from local to global coordinate frames, is used in the following example.\n\n%-------------------------------------------------------------------------------\n@O test/py/larstruct/test05.py\n@{\"\"\" Example of non-nested structure with translation and rotations \"\"\"\nfrom larlib import *\n\nsquare = larCuboids([1,1])\n#square = Model(square)\ntable = larApply( t(-.5,-.5) )(square)\nchair = larApply( s(.35,.35) )(table)\nchair = larApply( t(.75, 0) )(chair)\nstruct = Struct([table] + 4*[chair, r(PI/2)])\nscene = evalStruct(struct)\nVIEW(SKEL_1(STRUCT(CAT(AA(MKPOLS)(scene)))))\n@}\n%-------------------------------------------------------------------------------\n\n\\paragraph{Call of nested structures by reference}\nFinally, a similar 2D example is given, by nesting one (or more) structures via separate definition and call by reference from the interior. Of course, a cyclic set of calls must be avoided, since it would result in a \\emph{non acyclic} multigraph of the structure network.\n\n%-------------------------------------------------------------------------------\n@O test/py/larstruct/test06.py\n@{\"\"\" Example of nested structures with translation and rotations \"\"\"\nfrom larlib import *\n\nsquare = larCuboids([1,1])\n#square = Model(square)\ntable = larApply( t(-.5,-.5) )(square)\nchair = Struct([ t(.75, 0), s(.35,.35), table ])\nstruct = Struct( [t(2,1)] + [table] + 4*[r(PI/2), chair])\nstruct = Struct(10*[struct,t(0,2.5)])\nstruct = Struct(10*[struct,t(3,0)])\nscene = evalStruct(struct)\nVIEW(SKEL_1(STRUCT(CAT(AA(MKPOLS)(scene)))))\n@}\n%-------------------------------------------------------------------------------\n\n\n%-------------------------------------------------------------------------------\n@O test/py/larstruct/test08.py\n@{\"\"\" LAR model input and handling \"\"\"\nfrom larlib import *\n\n@< Input of LAR architectural plan @>\ndwelling = larApply(t(3,0))(Model((V,FV)))\nprint \"\\n dwelling =\",dwelling\nVIEW(EXPLODE(1.2,1.2,1)(MKPOLS((dwelling.verts,dwelling.cells))))\nVIEW(EXPLODE(1.2,1.2,1)(MKPOLS((dwelling.verts,EV))))\nplan = Struct([dwelling,s(-1,1),dwelling])\nVIEW(EXPLODE(1.2,1.2,1)(CAT(AA(MKPOLS)(evalStruct(plan)))))\n@}\n%-------------------------------------------------------------------------------\n\n\n\n%-------------------------------------------------------------------------------\n@D Input of LAR architectural plan\n@{\"\"\" Input of LAR architectural plan \"\"\"\nfrom larlib import *\n\nV = [[3,-3],\n[9,-3],[0,0],[3,0],[9,0],[15,0],\n[3,3],[6,3],[9,3],[15,3],[21,3], \n[0,9],[6,9],[15,9],[18,9],[0,13],\n[6,13],[9,13],[15,13],[18,10],[21,10], \n[18,13],[6,16],[9,16],[9,17],[15,17],\n[18,17],[-3,24],[6,24],[15,24],[-3,13]]\nFV = [\n[22,23,24,25,29,28], [15,16,22,28,27,30], [18,21,26,25], \n[13,14,19,21,18], [16,17,23,22], [11,12,16,15],\n[9,10,20,19,14,13], [2,3,6,7,12,11], [0,1,4,8,7,6,3],\n[4,5,9,13,18,17,16,12,7,8],[17,18,25,24,23]]\n\npolylines = lar2polylines((V,FV))\nlines = CAT([zip(polyline[:-1],polyline[1:]) for polyline in polylines])\t\nverts = dict(zip(AA(vcode(4))(V),range(len(V))))\nedges = [tuple(sorted([verts[vcode(4)(v1)], verts[vcode(4)(v2)]])) for v1,v2 in lines]\nEV = list(set(edges))\n@}\n%-------------------------------------------------------------------------------\n\n\n\n\\paragraph{Transformation of Struct object to LAR model pair}\n\nThe following test application first generates a grid $3\\times 3$ of LAR cubes, extracts\nits boundary cells as \\texttt{BV}, then produces a \\texttt{struct} object with 30 translated instances of it,\nand finally transforms the \\texttt{struct} object into a LAR pair \\texttt{W,FW}.\nLet us notice that due to the assembly process, some 2-cells in \\texttt{FW} are doubled.\n\n%-------------------------------------------------------------------------------\n@O test/py/larstruct/test09.py\n@{\"\"\" Transformation of Struct object to LAR model pair \"\"\"\nfrom larlib import *\n\n@< Transform Struct object to LAR model pair @>\n@}\n%-------------------------------------------------------------------------------\n\nThe actual generation of the structure and its transformation to a LAR model pair is actually performed in the following macro.\n\n%-------------------------------------------------------------------------------\n@D Transform Struct object to LAR model pair\n@{\"\"\" Generation of Struct object and transform to LAR model pair \"\"\"\ncubes = larCuboids([10,10,10],True)\nV = cubes[0]\nFV = cubes[1][-2]\nCV = cubes[1][-1]\nbcells = boundaryCells(CV,FV)\nBV = [FV[f] for f in bcells]\nVIEW(EXPLODE(1.2,1.2,1.2)(MKPOLS((V,BV))))\n\nblock = Model((V,BV))\nstruct = Struct(10*[block, t(10,0,0)])\nstruct = Struct(10*[struct, t(0,10,0)])\nstruct = Struct(3*[struct, t(0,0,10)])\nW,FW = struct2lar(struct)\n\nVIEW(EXPLODE(1.2,1.2,1.2)(MKPOLS((W,FW))))\n@}\n%-------------------------------------------------------------------------------\n\n\n\n%===============================================================================\n\\appendix\n%===============================================================================\n\\subsection{Importing a generic module}\nFirst we define a parametric macro to allow the importing of \\texttt{larcc} modules from the project repository \\texttt{lib/py/}. When the user needs to import some project's module, she may call this macro as done in Section~\\ref{sec:lar2psm}.\n%------------------------------------------------------------------\n@d Import the module\n@{import sys; sys.path.insert(0, 'lib/py/')\nimport @1\n@}\n%------------------------------------------------------------------\n\n\\paragraph{Importing a module} A function used to import a generic \\texttt{lacccc} module within the current environment is also useful.\n%------------------------------------------------------------------\n@d Function to import a generic module\n@{def importModule(moduleName):\n    @< Import the module @(moduleName@) @>\n@| importModule @}\n%------------------------------------------------------------------\n\n\n\n\\subsection{Numeric utilities}\n\nA small set of utility functions is used to transform a \\emph{point} representation, given as array of coordinates, into a string of fixed format to be used as point key into python dictionaries.\n\n%------------------------------------------------------------------\n@D Symbolic utility to represent points as strings\n@{\"\"\" TODO: use package Decimal (http://docs.python.org/2/library/decimal.html) \"\"\"\n#global PRECISION\n#PRECISION = 4.\n\ndef verySmall(number): return abs(number) < 10**-(PRECISION)\n\ndef prepKey (args): return \"[\"+\", \".join(args)+\"]\"\n\ndef fixedPrec(PRECISION):\n    def fixedPrec0(value):\n        out = round(value*10**(PRECISION))/10**(PRECISION)\n        if out == -0.0: out = 0.0\n        return str(out)\n    return fixedPrec0\n    \ndef vcode (PRECISION=4):\n    def vcode0 (vect):\n        \"\"\"\n        To generate a string representation of a number array.\n        Used to generate the vertex keys in PointSet dictionary, and other similar operations.\n        \"\"\"\n        return prepKey(AA(fixedPrec(PRECISION))(vect))\n    return vcode0\n@}\n%------------------------------------------------------------------\n\n\n\\bibliographystyle{amsalpha}\n\\bibliography{larstruct}\n\n\\end{document}\n", "meta": {"hexsha": "25a68116fd4126ffc3b9cabf5bf8f19d4bf97330", "size": 42967, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/tex/larstruct.tex", "max_stars_repo_name": "cvdlab/lar-cc", "max_stars_repo_head_hexsha": "7092965acf7c0c78a5fab4348cf2c2aa01c4b130", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-09-20T04:48:12.000Z", "max_stars_repo_stars_event_max_datetime": "2016-09-20T04:48:12.000Z", "max_issues_repo_path": "src/tex/larstruct.tex", "max_issues_repo_name": "Ahdhn/lar-cc", "max_issues_repo_head_hexsha": "7092965acf7c0c78a5fab4348cf2c2aa01c4b130", "max_issues_repo_licenses": ["MIT", "Unlicense"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-02-20T21:57:07.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-21T07:18:11.000Z", "max_forks_repo_path": "src/tex/larstruct.tex", "max_forks_repo_name": "Ahdhn/lar-cc", "max_forks_repo_head_hexsha": "7092965acf7c0c78a5fab4348cf2c2aa01c4b130", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2016-11-04T10:47:42.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-10T17:32:50.000Z", "avg_line_length": 42.4995054402, "max_line_length": 593, "alphanum_fraction": 0.5176530826, "num_tokens": 10095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.3327867186228418}}
{"text": "\\chapter{Background}\\label{sec:Background}\nRL is a process that requires both interactive parts as well as algorithms that improve interactions. The following section \\ref{reinforcement_learning} introduces the general concept of RL and its specifications. Afterwards, two popular learning algorithms for RL problems are presented: PPO and DQN.\n\n\\section{Reinforcement Learning}\\label{reinforcement_learning}\nSutton and Barto wrote in ``Reinforcement learning: An introduction'' \\cite{suba18} that RL is based on two components that interact with each other: an environment and an agent, see Figure \\ref{fig:rl_cycle}. Those interactions take part during a time period with discrete time steps $t\\in\\mathbb{N}_0$ until a goal is reached or the ending condition applies. This process is called an episode. Formally, the journey of the agent to find the goal is described as a Markov Decision Process (MDP) \\cite{suba18}. When multiple agents act in the same environment, the Markov decision process is called a stochastic game \\cite{buba10}.\n\n\\begin{figure}[hpbt]\n    \\centering\n    \\includegraphics[width=0.6\\textwidth]{pictures/RLInteractionSB}\\\\\n    \\caption[Reinforcement Learning Cycle]{The cycle of agent-environment interaction as\n        shown in ``Reinforcement learning: An introduction'' \\cite{suba18}}\\label{fig:rl_cycle}\n\\end{figure}\n\nOne environment state $S_t$ is part of a set $S$ containing all possible states. In most cases, the environment state describes what the agent can see. An agent often only has a small field of view, which turns a MDP into a partially observable MDP \\cite{suba18}. During each point in time $t$, the agent can interact with the environment by executing an action $A_t$, which changes the environment state. An example would be moving in the environment, which results in a new area that the agent can now see. In a multiagent environment, every agent chooses its action simultaneously and adds it into a joint action set, which is executed collectively during $t$ \\cite{buba10}.\n\nThe reward $R_t$ is an element of a set of possible rewards $R \\subset \\mathbb{R}$ \\cite{suba18}. Therefore, the reward can potentially be negative. Depending on the environment, that value can act as immediate feedback to the agents action. Other times, the reward is received as a result of a whole action sequence or the achievement of a certain state, for instance the goal or subgoals. The general concept of RL, as defined by Sutton and Barto \\cite{suba18}, is for agents to maximize rewards. Unlike machine learning approaches, the agent starts with no knowledge about good or bad actions and enhances the decision-making over time.\n\nSutton and Barto defines the agents' action selection with respect to the current state as a policy $\\pi$. They explain further that a policy could be as simple as a lookup table, mapping states to actions, or it could contain a complicated search process for the best decision. However, policies most of the time map action-state pairs to a selection probability, with all actions of a state adding up to 100\\%.\nDuring environment interactions, agents receive rewards which can be used to update the policy accordingly. As an example, the probability of policy $\\pi(a \\mid s)$ decreases when receiving a negative or low reward, reducing the chances of executing the same action in that specific state again.\n\nWhile rewards only rate the immediate situation, a value function, i.e. the state-value function $V^\\pi(s_t)$ for a policy $\\pi$, can be used to estimate the long-term value of a state $s$ \\cite{suba18}:\n\\begin{equation}\\label{eq:value_func}\n    v_\\pi(s) \\doteq \\mathbb{E}_\\pi \\left[ G_t \\mid S_t = s \\right] = \\mathbb{E}_\\pi \\left[ \\sum^{\\infty}_{k=0} \\gamma^k R_{t+k+1 \\mid S_t = s}  \\right]\n\\end{equation}\nThe result is the estimated discounted cumulative reward an agent could get following that state and choosing actions based on the current policy. The discount factor is defined by Sutton and Barto as $0 \\le \\gamma < 1$ and provides a constant that reduces the importance of future rewards. A high $\\gamma$ symbolizes a greater interest in rewards that are far away, whereas a discount of zero only takes the current reward into account. By setting $\\gamma$ smaller than one, it is ensured that the infinite sum results in a value. Generally, states that offer immediate high rewards could end in a low reward streak. In the opposite case, a low reward state could subsequently yield high rewards. Therefore, value functions are of great use to achieve the maximum reward.\n\nThe last part to note about RL is that it entails the problem of balancing exploration and exploitation \\cite{suba18}. On the one hand, an agent has to explore different options in order to learn and expand its knowledge. On the other hand, agents strive to maximize the reward, which can lead to greediness. An agent could start to exploit its knowledge too early, choosing actions of which it knows to result in positive rewards. However, if an agent does not explore enough, the best action sequence will stay hidden and the agents knowledge will not improve.\n\n\\section{Proximal Policy Optimization}\nIn 2017, Schulman et al. introduced the concept of PPO in the article ``Proximal Policy Optimization Algorithms'' \\cite{scwo17}. Policy optimization is the improvement of the action selection strategy $\\pi$ based on the current state $s_{t}$. This is achieved by rotating two steps \\cite{scwo17}: \\\\\n\\begin{enumerate}\n  \\item Sampling data from the policy and\n  \\item Optimizing the objective with that data through several epochs.\n\\end{enumerate}\n\nUsing those steps results in the agent gathering a small batch of experiences while choosing actions with a policy $\\pi$. Afterwards, this batch is used once to enhance the current policy. Then, the experiences are discarded and the agent uses the updated policy to gather a new batch. By repeating those two steps the agent can learn to choose better actions. PPO is applied to prevent drastic policy changes, which stabilizes the learning process.\n\nThe origin of PPO lies in a similar approach called Trust Region Policy Optimization (TRPO). TRPO also restricts policy updates by defining a trust region \\cite{scle15}. This is achieved by maximizing the following function \\cite{scwo17}:\n\\begin{equation}\\label{eq:TRPO}\n    \\underset{\\theta}{maximize}\\,\\hat{\\mathbb{E}}_{t} \\left[ \\frac{\\pi_{\\theta}(a_{t} \\mid s_{t})}{\\pi_{\\theta_{old}}(a_{t} \\mid s_{t})}\n        \\hat{A}_{t}-\\beta \\, KL[\\pi_{\\theta_{old}}(\\cdot \\mid s_{t}),\\pi_{\\theta}(\\cdot \\mid s_{t})] \\right]\n\\end{equation}\nThe expectation $\\hat{\\mathbb{E}}_{t}$ indicates, that an empirical average over a number $t$ of samples is used for estimation and the algorithm alternates between sampling and executing these calculations. The variable $\\hat{A}_{t}$ describes an estimator of the advantage function. This function was defined in the paper ``Trust Region Policy Optimization'' \\cite{scle15} with \\\\ $A_\\pi(s,a) = Q_\\pi(s,a)-V_\\pi(s)$. The first part calculates the state-action value, estimating the upcoming rewards for an agent, starting at state s and initially selecting action a. Afterwards, the action selection is based on the current policy $\\pi$. \n\nThe second part contains the state value function $V_\\pi(s)$, which works very similarly by starting at state s and using $\\pi$. However, the difference is that the agent always chooses actions according to the policy. The result of the advantage function $A_\\pi(s,a)$ shows whether a profit could be gained when deviating from the policy by specifically choosing action a.\n\nThe fraction $\\frac{\\pi_{\\theta}(a_{t} \\mid s_{t})}{\\pi_{\\theta_{old}}(a_{t} \\mid s_{t})}$ in the Minuend of function \\eqref{eq:TRPO} can be replaced by $r(\\theta)$\nand represents the probability ratio of an action in the current policy in comparison to the old policy \\cite{scwo17}. $\\theta$ represents a policy parameter. The result of $r(\\theta)$ is greater than one, if an action is very probable in the current policy. Otherwise, the outcome lies between zero and one. Schulman et al. \\cite{scwo17} further extract the first part of function \\eqref{eq:TRPO} as the surrogate objective:\n\\begin{equation}\\label{eq:TRPO_surrogate}\n    L^{CPI}(\\theta) = \\hat{\\mathbb{E}}_{t} \\left[ \\frac{\\pi_{\\theta}(a_{t} \\mid s_{t})}{\\pi_{\\theta_{old}}(a_{t} \\mid s_{t})} \\hat{A}_{t} \\right]\n    = \\hat{\\mathbb{E}}_{t} \\left[ r(\\theta)\\hat{A}_{t} \\right]\n\\end{equation}\nIf only this part of function \\eqref{eq:TRPO} is maximized on its own, it would result in large outcomes, which in turn leads to drastic policy updates. In order to stay in a trust region, as the name suggests, a penalty is subtracted from the surrogate function \\eqref{eq:TRPO_surrogate}. The penalty is the subtrahend of equation \\eqref{eq:TRPO} and contains the fixed coefficient $\\beta$. Regardless of the function details and outcome of $KL$, the coefficient $\\beta$ is hard to choose, since different problems require different penalty degrees \\cite{scwo17}. Even during a training process it could be necessary to adapt the coefficient, due to changes.\n\nTherefore, Schulman et al. introduced\n\\begin{equation}\\label{eq:PPO}\n    L^{CLIP}(\\theta) = \\hat{\\mathbb{E}}_{t} \\left[ \\min \\left( \\; r(\\theta)\\hat{A}_{t}, \\; clip(r(\\theta), 1-\\epsilon, 1+\\epsilon)\\hat{A}_{t} \\; \\right) \\right]\n\\end{equation}\nwhich is very similar to equation \\eqref{eq:TRPO} but does not require coefficients. The first $\\min$ entry contains $L^{CPI}$ \\eqref{eq:TRPO_surrogate}. The second part contains a $clip$ function, which narrows the space of policy mutation with the small hyperparameter $\\epsilon$. After applying the clip function, $r(\\theta)$ lies between $[1-\\epsilon,1+\\epsilon]$. Calculating the minimum of the clipped and unclipped probability ratio produces the lower bound of the unclipped $r(\\theta)$, preventing the policy to change drastically.\n\nFinally, the following equation is introduced\n\\begin{equation}\\label{eq:PPO_algo}\n    L_{t}^{CLIP+VF+S}(\\theta) = \\hat{\\mathbb{E}}_{t} \\left[ L_{t}^{CLIP}(\\theta) - c_{1}L_{t}^{VF}(\\theta) + c_{2}S[\\pi_{\\theta}](s_{t}) \\right]\n\\end{equation}\nwith $c_{1}$ and $c_{2}$ as coefficients. The authors point out that the loss function \\\\\n$L_{t}^{VF} = (V_{\\theta}(s_{t})-V_{t}^{targ})^2$ combines the policy surrogate and the value function error term and is necessary once a neural network shares parameters between policy and value function. An entropy bonus $S$ is added to ensure exploration.\n\nFurthermore, Schulman et al. point out that the policy is executed for $T$ time steps, with $T$ being a smaller value than the overall episode duration. Until now, the advantage function calculates values through an infinite loop, see the value function \\eqref{eq:value_func} for example. Hence, the advantage function needs to be adjusted as well. It is necessary that the future estimations do not exceed that time step limit. In this context, the following advantage function is used \\cite{scwo17}:\n\\begin{equation}\\label{eq:advantage_func}\n    \\hat{A_t} = \\delta_t+(\\gamma \\lambda)\\delta_{t+1}+ \\cdots + (\\gamma \\lambda)^{T-t+1}\\delta_{T-1}\n\\end{equation}\n\\begin{equation}\\label{eq:advantage_func_delta}\n    \\textrm{where} \\qquad \\delta_t = r_t + \\gamma V(s_{t+1}) - V(s_t)\n\\end{equation}\n\nSchulman et al. also showed an example of the PPO algorithm, cf. algorithm \\ref{algo:ppo_algo_code}. The example uses an actor-critic approach, which means that a critic is responsible to approximate the value function of the policy and the actor in turn improves the policy based on the approximation results of the critic \\cite{kots03}. $N$ detonates actors collecting data in T time steps in each iteration. Meanwhile, the critic computes the estimations of the advantage values. Afterwards, the policy is replaced with a new one, in which the function $L_{t}^{CLIP+VF+S}(\\theta)$ \\eqref{eq:PPO_algo} is optimized during K epochs. For the optimization process, a small random batch of the previous time steps is used.\n\n\\begin{algorithm}[H]\n    \\DontPrintSemicolon\n    \\For(){\\text{iteration=1,2,...}}{\n        \\For(){\\text{actor=1,2,...,$N$}}{\n            Run policy $\\pi_{\\theta_{old}}$ in environment for $T$ timesteps \\;\n            Compute advantage estimates $\\hat{A}_{1},...\\hat{A}_{T}$\n        }\n        Optimize surrogate $L$ wrt $\\theta$, with K epochs and minibatch size $M \\; \\leq \\; NT$ \\;\n        $\\theta_{old} \\leftarrow \\theta$\n    }\n    \\caption{PPO, Actor-Critic Style, as shown in ``Proximal Policy Optimization Algorithms'' \\cite{scwo17}}\\label{algo:ppo_algo_code}\n\\end{algorithm}\n\n\\section{Deep Q-Network}\\label{dqn}\nAnother learning approach that is often compared with PPO is the training algorithm of a deep Q-Network with Q-learning and experience replay. Instead of improving a policy, agents improve by maximizing a value function. Hence, this algorithm relies on the action value function, that is formally defined as follows \\cite{mnba16}:\n\\begin{equation}\\label{eq:qvalue}\n    Q^\\pi(s,a) = \\mathbb{E} \\left[ R_t \\mid s_t = s,a \\right]\n\\end{equation} \n$R_t$ represents the discounted cumulative reward $R_t=\\sum^{\\infty}_{k=0} \\gamma^k r_{t+k}$. The estimated outcome is calculated by starting at a state $s$, executing a specific action $a$ and reaching the next states by using a policy $\\pi$. Mnih et al. \\cite{mnka15} state, that the optimal action-value can be approximated with a deep convolutional neural network and the following function:\n\\begin{equation}\\label{eq:opt_qvalue}\n    Q^*(s,a) =  \\underset{\\pi} \\max \\mathbb{E}\\left[ r_{t} + \\gamma r_{t+1} + \\gamma^2 r_{t+2} + \\ldots | s_t = s, a_t = a, \\pi \\right]\n\\end{equation}\n\nThe difference between function \\eqref{eq:qvalue} and \\eqref{eq:opt_qvalue} is, that in the second one, a policy is chosen, which optimizes the outcome. Mnih et al. continue by stating, that in a scenario where the sequence $s'$ of all actions $a'$ are known, the optimal $Q^*(s',a')$ of the next state can be calculated. Then, this Bellman equation could be applied \\cite{mnba16}: \n\\begin{equation}\\label{eq:bel_qvalue}\n    Q^*(s,a) =  \\mathbb{E}_{s'} \\left[ r+ \\gamma \\underset{a'}\\max \\; Q^* (s', a') \\mid s,a \\right]\n\\end{equation}\nMany RL algorithms estimate this function through iterative updates, by calculating $Q_{i+1}(s,a) =  \\mathbb{E} \\left[ r+ \\gamma \\underset{a'}\\max \\; Q_i (s', a') \\mid s,a \\right]$, $Q_{i+2}$, \\dots \\cite{mnka13}. Eventually the optimal Q value is reached with $i\\rightarrow \\infty$. Those calculations proved to be very impractical, since they require a lot of computational work, which is why Mnih et al. introduced the Q-network at this point. As a result, the parameters of the Q function are extended with $\\theta$ as network weights ($Q(s,a;\\theta)$).\n\nHowever, the researchers argued that using a neural network in combination with the Q function proofed to be unstable. According to the authors, this is caused by correlating observations that are used to calculate the function. Additionally, small updates to the action value may lead to drastic changes of the policy. Such problems change the connection between Q values and their successive target values $r+\\gamma \\; \\underset{a'} \\max \\; Q(s',a')$. To overcome these issues, Mnih et al. introduced two new concepts: \n\\begin{enumerate}\n  \\item An experience replay that enables random sampling of observations and\n  \\item An iterative update process of the action values approaching the target values.\n\\end{enumerate}\nThe target values are only updated periodically in their implementation.\n\nIn algorithm \\ref{algo:dqn_algo_code}, a deep Q-learning approach with an experience replay is shown. The experience replay contains the acquired agent knowledge of each time step in form of a quadruple: (old state, action, reward, new state). The experience values are then stored into the replay memory $D$ across multiple episodes. The states are parameters of $\\Phi_{t}$ in the example, since they are preprocessed, to match the network input conditions.\n\nIn addition to the action value function $Q$, the target action-value $\\hat Q$ is initially defined with the same weights to enable iterative updates. In order to fill the memory, the agent first selects actions and acts in the environment. The action selection here is based on the $\\epsilon$-greedy policy, meaning that with a probability of $\\epsilon$ a random action is chosen \\cite{mnka15}. Otherwise, the best option according to the Q-value is selected.\n\n\\begin{algorithm}[H]\n    \\DontPrintSemicolon\n    Initialize replay memory $D$ to capacity $N$ \\;\n    Initialize action-value function $Q$ with random weights $\\theta$ \\;\n    Initialize target action-value function $\\hat{Q}$ with weights $\\theta^{-} = \\theta$ \\;\n    \\For(){\\text{episode=1,$M$}}{\n        Initialize sequence $s_1 = \\{x_1\\}$ and preprocessed sequence $\\phi_1 = \\phi(s_1)$ \\;\n        \\For(){\\text{$t$=1,T}}{\n            With probability $\\epsilon$ select a random action $a_t$ \\;\n            otherwise select $a_t = \\text{argmax}_a Q(\\phi(s_t), a; \\theta)$ \\;\n            Execute action $a_t$ in emulator and observe reward $r_t$ and image $x_{t+1}$ \\;\n            Set $s_{t+1} = s_{t}, a_{t}, x_{t+1}$ and preprocess $\\phi_{t+1}=\\phi(s_{t+1})$ \\;\n            Store transition ($\\phi_{t}, a_{t}, r_{t}, \\phi_{t+1}$) in $D$ \\;\n            Sample random minibatch of transitions ($\\phi_{j}, a_{j}, r_{j}, \\phi_{j+1}$) from $D$ \\;\n            Set $y_j = \\begin{cases}\n                r_j & \\text{if episode terminates at step j + 1}\\\\\n                r_j + \\gamma \\text{max}_{a'} \\hat{Q}(\\phi_{j+1}, a', \\theta^{-}) & \\text{otherwise}\n                \\end{cases}$  \\;\n            Perform a gradient descent step on $\\left( y_j - Q(\\phi, a_j ; \\theta) \\right) ^2$ with respect to the network parameters $\\theta$ \\;\n            Every $C$ steps reset $\\hat{Q} = Q$\n        }\n    }\n    \\caption{DQN with Experience Replay, as shown in ``Human-level control through deep reinforcement learning'' \\cite{mnka15}}\\label{algo:dqn_algo_code}\n\\end{algorithm}\n\nExecuting the selected action results in a memory entry in the form of the earlier described quadruple. Afterwards, a minibatch of the replay memory is randomly sampled to calculate the difference between the values. The action values with the current weights are subtracted from $y_i$. This variable calculates estimated Bellman equation by using the target action values with the old weights. The parameter $y_i$ contains just the reward value of the sample, if the sampled entry was the last step the episode of the entry. A gradient descent step is performed on the function, which means that the local minima of the function is searched by tweaking the parameter $\\theta$. \n\nFinally, every certain amount of steps C the target network is set to the current Q-Network. The suggested process offers several advantages \\cite{mnka15}: the replay memory leads to a smaller deviation or fluctuation in the parameters. The random samples of minibatches can be efficient, since an experience might be used multiple times to update the network weights. Furthermore, through the randomness in the samples, the correlation of steps is interrupted. This leads to a decrease of variance in between updates. Lastly, updating the target network periodically improves the stability of the learning process.", "meta": {"hexsha": "80de3594aad00076defac3016d79ec2770c2c580", "size": 19339, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Thesis/text/text/Background.tex", "max_stars_repo_name": "zarahz/MARL-and-Markets", "max_stars_repo_head_hexsha": "3591a160e098e7251b9e7c7b59c6d0ab08ba0779", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-12T09:17:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T09:17:32.000Z", "max_issues_repo_path": "Thesis/text/text/Background.tex", "max_issues_repo_name": "zarahz/MARL-and-Markets", "max_issues_repo_head_hexsha": "3591a160e098e7251b9e7c7b59c6d0ab08ba0779", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Thesis/text/text/Background.tex", "max_forks_repo_name": "zarahz/MARL-and-Markets", "max_forks_repo_head_hexsha": "3591a160e098e7251b9e7c7b59c6d0ab08ba0779", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 133.3724137931, "max_line_length": 772, "alphanum_fraction": 0.7460054812, "num_tokens": 4946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.332735728457863}}
{"text": "\\subsubsection{\\stid{3.12} Sub-project: hypre}\n\n\\paragraph{Overview}\nThe {\\sl hypre} software library \\cite{hypre:homepage,hypre_design_impl_2006} provides high performance preconditioners and solvers for the solution of large sparse linear systems on massively parallel computers, with particular focus on algebraic multigrid solvers. One of {\\sl hypre}’s unique features is the provision of a (semi)-structured interface, in addition to a traditional linear-algebra based interface. The semi-structured interface is appropriate for applications whose grids are mostly structured, but with some unstructured features. Examples include block-structured grids, composite grids in structured adaptive mesh refinement (AMR) applications, and overset grids. These interfaces give application users a more natural means for describing their linear systems, and provide access to methods such as structured multigrid solvers, which can take advantage of the additional information beyond just the matrix. Since current architecture trends are favoring regular compute patterns to achieve high performance, the ability to express structure has become much more important. The {\\sl hypre} library provides both unstructured and structured multigrid solvers, which have shown excellent scalability on a variety of high performance computers, e.g Blue Gene systems (unstructured solver BoomerAMG has scaled up to 1.25 million MPI cores with a total of 4.5 million hardware threads). It is used by many ECP application teams, including ExaAM, Subsurface, ExaWind, CEED, and more. It requires a C compiler and an MPI implementation, but it also runs in an OpenMP environment. It also has GPU capabilities.\n\n\\paragraph{Key  Challenges}\n\nWhile {\\sl hypre}'s solvers contain much parallelism, their main focus is the solution of sparse linear systems, leading to  very large demands on memory bandwidth. In addition, the use of multiple levels, while greatly aiding convergence of the solvers, leads to decreasing systems sizes, number of operations and parallel efficiencies on coarser levels. Particularly the unstructured algebraic multigrid solver BoomerAMG\\cite{HeYa2002}, which is {\\sl hypre}'s most often used preconditioner, suffers from increasing communication complexities on coarser levels. Coarse grid operators are generated by multiplying three matrices leading to increasing numbers of nonzeroes per row in the resulting matrices and with it increasing numbers of neighbor processes. While BoomerAMG's solve phase mainly consists of matrix vector products and smoothing operations, which are fairly straight forward to parallelize, even on a GPU, its setup phase is highly complex, including many branches, a lot of integer operations as well as some sequential passages. Previous interpolation strategies that lead to best convergence and performance on distributed memory machines were not suitable for implementation on GPUs or similar architectures requiring extreme parallelism and required new algorithmic approaches. Since {\\sl hypre} is a mature product with many solvers and interdependent features, any significant changes that affect the whole library, are tedious and require much testing to ensure that the library stays backward compatible and no features are broken.\n\n\\paragraph{Solution Strategy}\n\nSince computer architectures continue to change rapidly, it was important to come up with strategies that will facilitate future porting of the software. Therefore we developed and implemented a new memory model that addresses the use of different memory locations.\nSince the upcoming computer architectures are heterogeneous with accelerators, we focus on enabling {\\sl hypre} for GPUs. We have looked into various options, such as the use of CUDA, OpenMP 4.5, as well as RAJA and Kokkos. We limited the latter three options to the structured interface and solvers which are more natural candidates for such an approach due to their use of macros, called BoxLoops, for loops. We adopted a modular approach for the unstructured interface, which relies on the restructuring the solver components to use smaller kernels that are and/or will be implemented in CUDA for Nvidia GPUs. Since hip is similar to CUDA, porting to AMD GPUs has been fairly straight forward. We are now investigating the use of a vendor conversion tool from CUDA to SYCL to port structured and unstructured solvers to upcoming exascale computers with Intel GPUs.\n\n\\paragraph{Recent Progress}\n\nPreviously we had enabled the structured interface and solvers, SMG and PFMG\\cite{AsFa1996}, to completely run on GPUs, using CUDA, OpenMP4.5, RAJA and Kokkos, and have now also added hip to enable use on AMD GPUs.\nFor our unstructured AMG solver BoomerAMG, we had implemented suitable CUDA kernels for setup and solve phase, designed a new class of interpolation operators based on sparse matrix operations\\cite{LiSY2020}, implemented it on GPUs and ported aggressive coarsening to the GPU. Recently, we added Umpire support for memory pooling on GPUs, which can significantly improve performance. We have enabled hypre's specialized solvers, including linear and eigensolvers for Maxwell problems and solvers for H-div problems, to run on Nvidia GPUs. Figure \\ref{fig:AMS-PCG} shows some results for a Maxwell problem using finite elements of increasing order on 1 node of Lassen. We have ported many of the CUDA kernels and routines in the unstructured interface to hip to enable their use on AMD GPUs. We have also developed a new version of multipass interpolation based on matrix-matrix multiplications and implemented it in CUDA and hip. Multipass interpolation is a popular low-memory prolongation used with aggressive coarsening. Figure \\ref{fig:Spock-AMG} shows a comparison of CPU and GPU runtimes on 2 nodes of Spock for a 3D diffusion problem with a 27-point stencil on a $n \\times n \\times n$ grid using AMG-PCG with aggressive coarsening on the first level for increasing $n$.\n\n\\begin{figure}[bth]\n\\centering\n\t\\includegraphics[width=3.9in]{projects/2.3.3-MathLibs/2.3.3.12-SUNDIALS-hypre/AMS-PCG.png}\n\t%\\includegraphics[width=3in]{AMS-PCG.png}\n\t\\caption{\\label{fig:AMS-PCG} Solution of a simple 3D electromagnetic diffusion problem corresponding to the 2nd order definite Maxwell equation  $\\nabla \\times \\nabla \\times E + E = f$ using AMS-PCG on 1 node of Lassen (4 GPUs vs. 40 CPU cores) using finite elements of increasing order on a Fichera mesh.}\n\n\\end{figure}\n\n\\begin{figure}[bth]\n\\centering\n\t\\includegraphics[width=3in]{projects/2.3.3-MathLibs/2.3.3.12-SUNDIALS-hypre/spock-AMG-PCG.png}\n\t%\\includegraphics[width=3in]{spock-AMG-PCG.png}\n\t\\caption{\\label{fig:Spock-AMG} Total times (setup plus solve times) on 2 nodes of Spock using AMG-PCG with aggressive coarsening and multi-pass interpolation for a 3D diffusion problem with a 27-point stencil on a $n \\times n \\times n$ grid. The CPU runs were performed with 8 MPI tasks with 16 OpenMP threads per MPI task, the GPU runs were performed on 8 AMD GPUs.}\n\n\\end{figure}\n\n\\paragraph{Next Steps}\n\nWe will pursue the following tasks:\n\n\\begin{itemize}\n\\item We will continue to add new GPU capabilities to {\\sl hypre} and improve the performance of current capabilities. We will thoroughly investigate the performance on AMD GPUs and begin porting to Intel GPUs.\n\\item We will test and evaluate performance of important hypre solvers on AMD and Intel GPUs, improve their performance and port additional components if necessary.\n\\end{itemize}\nIn addition, we will work with ECP application teams who are using {\\sl hypre}, such as ExaWind, ExaAM, AMReX,  to achieve best performance by tuning the solvers for them and potentially implementing suitable algorithmic changes.\n", "meta": {"hexsha": "20a3efd7bbb74f8240f95373d3d4784369099854", "size": 7718, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "projects/2.3.3-MathLibs/2.3.3.12-SUNDIALS-hypre/2.3.3.12-hypre.tex", "max_stars_repo_name": "egboman/ECP-ST-CAR-PUBLIC", "max_stars_repo_head_hexsha": "6ac85f302f3f5b1fbf51191f99392a5502a164fa", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2018-11-30T02:07:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T16:46:54.000Z", "max_issues_repo_path": "projects/2.3.3-MathLibs/2.3.3.12-SUNDIALS-hypre/2.3.3.12-hypre.tex", "max_issues_repo_name": "egboman/ECP-ST-CAR-PUBLIC", "max_issues_repo_head_hexsha": "6ac85f302f3f5b1fbf51191f99392a5502a164fa", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 24, "max_issues_repo_issues_event_min_datetime": "2018-12-16T00:09:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T21:51:14.000Z", "max_forks_repo_path": "projects/2.3.3-MathLibs/2.3.3.12-SUNDIALS-hypre/2.3.3.12-hypre.tex", "max_forks_repo_name": "egboman/ECP-ST-CAR-PUBLIC", "max_forks_repo_head_hexsha": "6ac85f302f3f5b1fbf51191f99392a5502a164fa", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 104, "max_forks_repo_forks_event_min_datetime": "2018-11-20T23:14:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T19:13:59.000Z", "avg_line_length": 171.5111111111, "max_line_length": 1624, "alphanum_fraction": 0.8117387924, "num_tokens": 1722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.332735728457863}}
{"text": "%!TEX root = ../thesis.tex\n%*******************************************************************************\n%*********************************** Signal region optimisation *********\n%*******************************************************************************\n\n\n\\chapter{Signal region optimisation}\\label{ch:signal_region_optimisation}\n\n\\graphicspath{{chapter-optimisation/Figs/Vector/}{chapter-optimisation/Figs/}}\n\n\\glsreset{sr}\n\nIn order to discover the rare \\gls{susy} signals considered in the following, dedicated kinematic regions enriched in signal events, so-called \\glspl{sr}, are constructed.\nThey are optimised such as to be sensitive to a maximum number of signal models considered in this analysis.\nIn this chapter, the optimisation procedures leading to the final signal regions are introduced and discussed. \n\n\\section{Optimisation methods}\n\nAll optimisation methods used in the following require a figure of merit that is maximised in order to find configurations yielding optimal performance.\nWhile the multidimensional cut scan and the \\textit{N}--1 plots approach, introduced in \\cref{sec:n-dim-scan,sec:n-1-scan}, respectively, use the binomial discovery significance $Z_\\mathrm{B}$, the fit scan procedure, discussed in \\cref{sec:fit-scan}, aims to maximise the area of the expected exclusion contour.\n\n\\subsection{Multidimensional cut scan}\\label{sec:n-dim-scan}\n\n \\begin{figure}\n\t\\centering\n\t\\begin{subfigure}[b]{0.5\\linewidth}\n\t\t\\centering\\includegraphics[width=1.0\\textwidth]{N-1_cut_scan/roc_curve_thesis_plots}\n\t\t\\caption{\\label{fig:roc_curve}}\n\t\\end{subfigure}\\hfill\n\t\\begin{subfigure}[b]{0.5\\linewidth}\n\t\t\\centering\\includegraphics[width=1.0\\textwidth]{N-1_cut_scan/z_vs_effs_thesis_plots}\n\t\t\\caption{\\label{fig:z_vs_eff}}\n\t\\end{subfigure}\\hfill\n\n\t\\caption{Small $N$-dimensional cut scan using $10^4$ unique cut combinations, illustrating the approach of~\\subref{fig:roc_curve} generating a \\gls{roc} curve from the scanned cut combinations in order to \\subref{fig:z_vs_eff} reduce the number of candidates used in computationally expensive significance calculations. The cut combination candidates forming the \\gls{roc} curve (dark blue) also maximise the discovery significance. In \\subref{fig:z_vs_eff}, the significance $Z_\\mathrm{B}$ includes the \\gls{mc} statistical uncertainty on the expected background rate and a constant 30\\% systematic uncertainty.} \n\t\\label{fig:ahoi_examples}\n\\end{figure}\n\nThe first optimisation method used for designing the \\glspl{sr} is an $N$-dimensional cut\\footnote{In the following, the term \\textit{cut} refers to a simple upper or lower requirement on kinematic observables like \\eg requiring $\\mt>\\SI{100}{\\GeV}$.} scan using $M$ observables.\nFor each unique combination of requirements on the set of observables considered, the expected signal and background rate as well as the statistical uncertainty on the background rate is determined from the \\gls{mc} simulated events.\nAs this takes a considerable computational effort, it is crucial to restrict the amount of cut combinations to be tested. By comparing with distributions at preselection level, as for example those shown in \\cref{fig:norm_obs}, a set of discrete cuts can be defined for each observable.\nIn practice, a total number of \\mbox{$\\mathcal{O}(10^7$--$10^8)$} cut combinations can still be tested on a single machine with a reasonable turnaround time. \n\nAfter determining the expected event rates and statistical uncertainties, the different cut combinations are binned into a predefined number of signal efficiency bins.\nFor each bin, the background rejection is subsequently maximised, \\ie the cut combination with the highest background rejection is chosen as a candidate combination for the respective signal efficiency bin.\nThe assumption is that, for a fixed signal efficiency, the cut combination candidate maximising the background rejection also maximises the discovery significance $Z_\\mathrm{B}$.\nWith the significance definition used herein, this is in general a valid assumption, as the significance tends to monotonically increase with decreasing background rate, even while the statistical uncertainty on the background estimation increases due to tighter requirements and less available \\gls{mc} statistics (cf. \\cref{fig:ahoi_examples}).\nThis procedure effectively generates a \\gls{roc} curve, that can be used to perform more computationally intensive calculations, as \\eg calculating different variations of the discovery significance.\nThe approach is illustrated in a small scan using $10^4$ cut combinations in \\cref{fig:ahoi_examples}.\nThe cut combination candidates maximising the background rejection and thus lying on the \\gls{roc} curve in \\cref{fig:roc_curve} are the same candidates that maximise the discovery significance in \\cref{fig:z_vs_eff}.\n\nA common problem of $N$-dimensional scans is the concept of \\textit{over-tightening} the selections given the available \\gls{mc} statistics.\nSince the cross sections of the \\gls{susy} processes considered are many orders of magnitude smaller than those of the dominant \\gls{sm} processes, it is often necessary to apply tight requirements on the kinematic observables in order to achieve a significant signal-to-background separation.\nHowever, due to the finite amount of \\gls{mc} statistics available, many of the more extreme cut combinations select kinematic regions where not enough \\gls{mc} statistics are available for a reasonable estimation of the background rates.\nThus, by maximising the background rejection, it may occur that cut combinations are selected where the mere lack of \\gls{mc} statistics, needed to properly estimate the background rates, causes a high significance value.\nAs the significance values obtained for such configurations are obviously not trustworthy, they need to be avoided. \n\nIn the $N$-dimensional cut scan implementation used herein, the available \\gls{mc} datasets are split in two statistically independent, equally sized subsets. Although resulting in an additional dilution of the available \\gls{mc} statistics, this approach allows to generate two independent \\gls{roc} curves and  to compute two independent values for the discovery significance for each cut combination candidate. A large difference in either the \\gls{roc} curves or the significance values is an indication for statistical fluctuations as a result of over-tightened cuts. In addition, requirements on the minimum number of unweighted \\gls{mc} events for different background processes, as well as the maximum allowed statistical uncertainty on a given process, can be applied. In combination, these precautions offer a good handle against statistical fluctuations. In the following, the $N$-dimensional cut scan implementation provided by \\texttt{ahoi}~\\cite{ahoi} is used.\n\n\\subsection[\\textit{N}--1 plots]{$\\makemebold{N}$--1 plots}\\label{sec:n-1-scan}\n\nInstead of performing a brute-force scan of a large set of cut combinations, a more manual approach, using iterative one-dimensional scans can be employed. In so-called `\\textit{N}--1 plots', the kinematic distributions of the background components as well as representative signal processes are plotted in conjunction with the significance achieved by applying a cut on each value on the \\textit{x}-axis of the one-dimensional distribution plotted. All other selection requirements, except the one on the observable plotted, are applied. This method allows to investigate the impact of a single kinematic requirement on the overall significance value. By repeatedly executing this process for each observable considered, it is possible to iteratively approach a cut combination yielding results comparable to that of a brute-force cut scan. Especially when considering a sizeable set of observables, this manual approach, however, quickly becomes very cumbersome and inefficient, and risks missing optimal cut combinations that would have been found by a brute-force approach.\n\nFor this reason, the following optimisation uses an $N$-dimensional cut scan to cover the full space spanned by the observables and scan ranges considered, while \\textit{N}--1 plots are used to verify and fine-tune results obtained by the brute-force approach.\n\n\\subsection{Scans using asymptotic formulae}\\label{sec:fit-scan}\n\nThe last of the optimisation methods, used in the following, relies on scans over sets of simplified profile likelihood fit configurations in order to run a simplified version of the full statistical inference machinery on a large number of signal region candidates.\nWhile the preceding optimisation methods rely on the binomial significance computed in independent \\textit{cut-and-count} signal regions, the simplified fit scans statistically combine disjunct signal regions by building a single likelihood, and compute the \\textit{p}-values using the asymptotic formulae introduced in~\\cref{ch:statistics}.\nIn addition, the simplified fits use all available signal points instead of relying on a limited set of benchmark points, and can thus derive an estimate of the expected exclusion contour for a large number of signal region candidates.\nThe estimation of the background event rates in the signal regions is taken from \\gls{mc} simulation only and considers a constant systematic uncertainty of 30\\% on the estimated event rate, correlated over all signal region bins. Statistical uncertainties on the background estimate from limited \\gls{mc} statistics are also taken into account. \n\nAs building the likelihood and executing the statistical inference takes a considerable computational effort, this method benefits from the previous optimisation steps defining promising signal region candidates worth scanning over.\nIn order to keep the number of configurations to be tested at a manageable level, the signal region candidates obtained from the previous methods are only varied to a limited degree, assuming that they were already close to optimal to begin with.\n\n\\section[Optimisation for the $1\\ell$ search]{Optimisation for the $\\makemebold{1\\ell}$ search}\n%\\section[Optimisation for the $\\boldsymbol{1\\ell}$ search]{Optimisation for the $\\boldsymbol{1\\ell}$ search}\n\n\\begin{table}\n\t\\centering\n\t\\small\n\t\\setlength\\heavyrulewidth{0.2ex}\n\t\\caption{List of observables and cut ranges used in the $N$-dimensional cut scan. All cuts are optional and allowed not to be applied at all.}\n\t\\begin{tabular} {l c l}\n\t\t\\toprule\n\t\tObservable &  & Cut values \\\\ \n\t\t\\midrule\n\t\t$\\etmiss$ [GeV]& $>$ & $\\in \\{200,220,240,260,280,300,320,340\\}$ \\\\\n\t\t$\\etmiss$ significance $\\mathcal{S}$ & $>$ & $\\in \\{5,10,15\\}$ \\\\\n\t\t$\\mt$ [GeV]& $>$ & $\\in \\{100, 120, 140,160,180,200,220,240,260,280, 300\\}$ \\\\\n\t\t$\\mct$ [GeV]& $>$ & $\\in \\{100, 120, 140,160,180,200,220,240,260,280, 300\\}$ \\\\\n\t\t$\\mbb$ lower [GeV]& $>$ & $\\in \\{85,90,95,100,105,110,115\\}$ \\\\\n\t\t$\\mbb$ upper [GeV]& $<$ & $\\in \\{130,135,140,145,150\\}$ \\\\\n\t\t$p_\\textrm{T}^\\ell$ $[\\SI{}{\\GeV}]$& $>$ & $\\in \\{20, 40, 60, 80\\}$ \\\\\n\t\t$p_\\textrm{T}^\\mathrm{jet1}$ [GeV]& $>$ & $\\in \\{50, 100, 150\\}$ \\\\\n\t\t$p_\\textrm{T}^\\mathrm{jet2}$ [GeV]& $>$ & $\\in \\{50, 75, 100\\}$ \\\\\t\n\t\t$\\upDelta R_{jj}$ & $<$ & $\\in \\{0.8,1.0,1.2,2.0\\}$ \\\\\n\t\t$\\upDelta R_{b\\hspace{-0.06em}\\bar{b}}$ & $<$ & $\\in \\{0.8,1.0,1.2,2.0\\}$ \\\\\n\t\t$N_\\mathrm{jet}$ & $\\leq$ & $\\in \\{2,3,4\\}$ \\\\\t\t\t\n\t\t$\\upDelta\\phi (\\vetmiss,\\vptlep )$ [rad]& $>$ & $\\in \\{0.5,1.0,2.0,2.5\\}$ \\\\\n\t\t\\bottomrule\t\t\t\t\t\n\t\\end{tabular}\\vspace{2mm}\n\t\\label{tab:cut_scan}   \n\\end{table}\n\nThe optimisation of the signal regions for the \\onelepton search benefits from the experience of past analyses investigating the same simplified model in the same final state~\\cite{SUSY-2013-23,SUSY-2017-01}, but explores new observables and considers signal region configurations optimised for the integrated luminosity of the full Run~2 dataset. \n\n\\subsection{Starting from benchmark signal points}\n\nA total of six so-called \\textit{benchmark} signal points, each representative of a different part of the model parameter space, are chosen for the first step of the optimisation procedure involving $N$-dimensional cut scans and \\textit{N}--1 plots.\nApart from the variables introduced in~\\cref{sec:variables}, a set of additional, potentially discriminative observables are considered in the $N$-dimensional cut scan\\footnote{These variables will turn out not to be used for the final signal regions and are only introduced here for completeness of the optimisation procedure description. Representative kinematic distributions for all observables are shown as a reference in \\cref{fig:additional_presel_plots}.}:\n\\begin{itemize}\n\t\\item The transverse momenta of the two leading jets as well as of the lepton ($p_\\textrm{T}^\\mathrm{jet1}$, $p_\\textrm{T}^\\mathrm{jet2}$, $\\ptl$). Especially for signal models with high mass differences between the electroweakinos, the transverse momenta of the lepton and the jets tend to have higher values than in \\gls{sm} background processes.\n\t\\item The object-based $\\etmiss$ significance $\\mathcal{S}$~\\cite{met_significance:2294922}, an observable designed to quantify how genuine the reconstructed $\\etmiss$ in an event is. It is determined through a hypothesis test using a log-likelihood ratio that takes into account the resolution of all objects entering the computation of $\\etmiss$. As such, $\\mathcal{S}$ offers good discrimination against events with a sizeable fraction of fake $\\etmiss$ in the event originating, \\eg, from jet mismeasurements or the non-hermeticity of the detector. Events with a large share of fake $\\etmiss$ accumulate at low values of $\\mathcal{S}$, while events with mostly real $\\etmiss$ tend to have large values of $\\mathcal{S}$. \n\t\\item The distance between the two leading jets $\\upDelta R_{jj}$ as well as between the two \\textit{b}-jets $\\upDelta R_{b\\hspace{-0.06em}\\bar{b}}$. Especially in events with a large mass difference between the electroweakinos, the Higgs can receive a significant boost, such that the two \\textit{b}-jets from the Higgs decay tend to be close together in the laboratory frame (and are also the highest-$\\pt$ jets in an event), resulting in small values of both $\\upDelta R_{jj}$ and $\\upDelta R_{b\\hspace{-0.06em}\\bar{b}}$. In \\gls{sm} background processes, however, the two leading (\\textit{b}-)jets often do not originate from the same object and thus tend to be further apart.\n\t\\item The azimuthal distance between the lepton $\\pt$ and the missing transverse momentum, denoted by $\\upDelta \\phi (\\makemebold{p}_\\mathrm{T}^\\ell, \\makemebold{p}_\\mathrm{T}^\\mathrm{miss})$. This observable exploits the fact that the lepton and the $\\etmiss$ tend to have a more back-to-back configuration in signal events than in many \\gls{sm} processes where the lepton and the neutrino (the latter often responsible for a large part of the $\\etmiss$ in an event) often originate from the same $W$ boson decay.\n\\end{itemize}\n\n\\begin{figure}\n\t\\centering\n\t\\begin{subfigure}[b]{0.5\\linewidth}\n\t\t\\centering\\includegraphics[width=1.0\\textwidth]{N-1_cut_scan/z_vs_effs_300_150.pdf}\n\t\t\\caption{$m(\\charg$/$\\neutr), m(\\lsp) =  300, \\SI{150}{\\GeV}$}\n\t\\end{subfigure}\\hfill\n\t\\begin{subfigure}[b]{0.5\\linewidth}\n\t\t\\centering\\includegraphics[width=1.0\\textwidth]{N-1_cut_scan/z_vs_effs_800_250.pdf}\n\t\t\\caption{$m(\\charg$/$\\neutr), m(\\lsp) =  800, \\SI{250}{\\GeV}$}\n\t\\end{subfigure}\\hfill\n\n\t\\caption[N-dimensional cut scan results]{Results of the $N$-dimensional cut scan for two representative benchmark points. The binomial discovery significance $Z_\\mathrm{B}$ is plotted against the signal efficiency for different uncertainty configurations. Additionally, the expected \\gls{sm} background event rates are shown (grey), including their statistical uncertainties for one of the two statistically independent samples (grey shaded area). The solid and dashed lines represent the two statistically independent subsets that the \\gls{mc} samples are split into.}\n\t\\label{fig:results_z_vs_eff}\n\\end{figure}\n\nIn order to avoid selecting cut combination candidates with over-tightened selection criteria compared to the available \\gls{mc} statistics, constraints are applied on the relative statistical uncertainty on the background, and on the number of unweighted \\gls{mc} events passing the cut combination candidates.\nCut combinations are only considered if they result in less than 50\\% relative statistical uncertainty on the total background.\nIn addition, all cut combinations need to result in at least five unweighted \\gls{mc} events for each of the three major backgrounds, $\\ttbar$, single top and $\\wjets$.\n\nThe discrete selection possibilities for each of the observables are shown in \\cref{tab:cut_scan}.\nA preselection of a lepton and exactly two \\textit{b}-jets (and thus at least two jets overall in the event) is always applied. Requirements on the different observables in~\\cref{tab:cut_scan} are optional and do not need to be applied by the optimisation algorithm.\nThe results of the brute-force $N$-dimensional cut scans for each benchmark signal point can be visualised by plotting the expected discovery significance $Z_\\mathrm{B}$ against the signal efficiency.\n\\Cref{fig:results_z_vs_eff} shows the results of two such cut scans using two of the benchmark signal points.\nThe corresponding plots for the remaining benchmark points are shown in~\\cref{fig:results_z_vs_eff_rest}. In these figures, the binomial significance is calculated for different uncertainty configurations for each of the two statistically independent subsets.\nIn addition, the expected background rate is shown for each subset.\nA cut combination with high achieved significance can be chosen, while avoiding statistical fluctuations and over-tightening.\nThe cut combinations chosen for each benchmark point, after a round of \\textit{N}--1 plots, are shown in~\\cref{tab:cut_scan_results}. The \\textit{N}--1 plots, shown in~\\cref{fig:results_n1_800_0,fig:results_n1_800_150,fig:results_n1_800_250,fig:results_n1_600_300,fig:results_n1_400_200,fig:results_n1_300_150}, are used to validate and fine-tune the cut values obtained through the cut scan and allow to identify and remove cuts on observables that do not contribute significantly to the achieved $Z_\\mathrm{B}$ value.\nFrom the 12 observables initially considered, only six (excluding the \\textit{b}-jet multiplicity technically not part of the scan) are part of the optimised cut combination candidates.\nThe remaining observables turned out not to significantly improve the sensitivity and are therefore dropped in the following.\n\n\n\\begin{table}\n\t\\begin{center}\n\t\\small\n\t\t\t\\begin{tabular} {l c c c c c c c}\n\t\t\t\t\\toprule\n\t\t\t\tObservable &  $(300,150)$ & $(400,200)$ & $(600,300)$  & $(800,250)$ & $(800,150)$ & $(800,0)$ \\\\\n\t\t\t\t\\midrule\n\t\t\t\t$N_{b\\mathrm{-jet}}$ &  2 & 2 & 2 & 2 & 2 & 2 \\\\\n\t\t\t\t$N_\\mathrm{jet}$ & 2 & 2 & 2 -- 3 & 2 -- 3  & 2 -- 3 & 2 -- 3\\\\\n\t\t\t\t$\\mbb$  $[\\SI{}{\\GeV}]$& $[105-135]$ & $[100-140]$ & $[100-140]$ & $[95-145]$ & $[95-145]$ & $[95-145]$ \\\\\n\t\t\t\t$\\met$ $[\\SI{}{\\GeV}]$ & $>240$ & $>240$ & $>240$ & $>240$ & $>240$  & $>240$\\\\\n\t\t\t\t$m_\\mathrm{CT}$ $[\\SI{}{\\GeV}]$ &  $>200$ & $>240$ & $>260$ & $>260$ & $>260$   & $>280$ \\\\\n\t\t\t\t$m_\\mathrm{T}$ $[\\SI{}{\\GeV}]$ &  $>100$ & $>120$ & $>140$ & $>200$ & $>240$ & $>240$ \\\\\n\t\t\t\t$\\mlb$ $[\\SI{}{\\GeV}]$ &  -- & -- & $>150$ & $>120$ & $>120$ & $>120$ \\\\\n\t\t\t\t\\midrule\n\t\t\t\t$Z_\\mathrm{B}$ $[\\sigma]$ & \\multicolumn{1}{c}{0.8} & \\multicolumn{1}{c}{1.9} & \\multicolumn{1}{c}{2.1} & \\multicolumn{1}{c}{1.8} & \\multicolumn{1}{c}{2.2} & \\multicolumn{1}{c}{2.3} \\\\\n\t\t\t\t\\bottomrule\n\t\t\t\\end{tabular}\n\t\t\\caption{Optimal cut combination for each benchmark signal point obtained with a brute force cut scan and a round of \\textit{N}--1 plots. The parameters of the benchmark points are $m(\\charg$/$\\neutr)$ and $m(\\lsp)$, both given in $\\SI{}{\\GeV}$. The significance is computed for \\onethirtynineifb with the binomial discovery significance $Z_\\mathrm{B}$ and includes MC statistical uncertainty as well as a constant 30\\% systematic uncertainty. A dash `--' is used where no requirement on the respective observable is applied.}\n\t\t\\label{tab:cut_scan_results}\n\t\\end{center}\n\\end{table}\n\n\n\n\n\\subsection{Towards final signal regions}\\label{sec:towards_signal_regions}\n\nThe optimal cut combinations obtained for the benchmark signal points, shown in~\\cref{tab:cut_scan_results}, need to be consolidated into a final set of signal regions.\nFrom~\\cref{tab:cut_scan_results}, it can be concluded, that all benchmark points favour a common baseline selection including exactly two \\textit{b}-jets, possibly one additional light jet, a Higgs mass window requirement of roughly $\\mbb\\in [100,140]$~$\\SI{}{\\GeV}$, and $\\etmiss > \\SI{240}{\\GeV}$.\nThe remaining requirements on $\\mt$, $\\mct$ and $\\mlb$ are, however, not easily consolidated into a single signal region, as they vastly differ depending on the model parameter space and kinematic regime represented by each benchmark point.\n\nIt can already be seen from the normalised distributions in~\\cref{fig:norm_obs,fig:norm_obs_app}, that signal points from different kinematic regimes in the parameter space would in principle prefer different requirements on all three of these observables.\nDesigning a single signal region that achieves optimal sensitivity to the entire parameter space studied, is thus not possible.\nInstead, a more generalised configuration is chosen, defining multiple signal region bins orthogonal to each other through their requirements on $\\mt$ and $\\mct$.\nBeing mutually exclusive, such signal region bins can be statistically combined in a single likelihood and can be used in a simultaneous fit to data, effectively creating a two-dimensional shape-fit in these observables.\nSuch a shape-fit configuration allows to exploit the differences in shape between signal and background distributions, and is able to accommodate the varying shapes of signal points from different regions in the parameter space, making it an ideal statistical tool to cover a wide range of kinematic regimes.\n\nThe optimal number of bins as well as values of the individual bin edges in both distributions depends on the available \\gls{mc} statistics and is determined using the simplified fit scans introduced in~\\cref{sec:fit-scan}.\nThe \\gls{mc} statistical uncertainties, as well as a systematic uncertainty of 30\\%, correlated over all bins, are considered in each configuration.\nThe number of bins is varied in each direction ($\\mt$ and $\\mct$) between two and five using different bin edges, varied within ranges determined by the optimal cut values obtained for the benchmark points.\nAs configurations with more bins could, in some circumstances, potentially benefit from the additional \\gls{mc} statistics resulting from looser selection criteria on the remaining variables, the previously consolidated baseline selection is also allowed to vary to some extent.\nFinally, although not expected to yield better performance, configurations with multiple orthogonal signal region bins in $\\etmiss$ or $\\mbb$ are also included in the scan.\nA subset of the investigated candidates is illustrated in~\\cref{fig:fit_scan_optimisation}, showing the nominal expected exclusion limit at 95\\% without uncertainty bands.\nConfigurations with multiple, disjoint patches of excluded areas in the parameter space are discarded, as they typically result from high statistical fluctuations.\n\n\\begin{figure}\n\\floatbox[{\\capbeside\\thisfloatsetup{capbesideposition={right,center},capbesidewidth=0.35\\textwidth}}]{figure}[\\FBwidth]\n{\\caption{Expected exclusion contours obtained from a subset of the signal region candidates. The background estimate is directly taken from \\gls{mc} and includes \\gls{mc} statistical uncertainty as well as an uncorrelated scale uncertainty of 30\\%. For the sake of visibility, only the nominal contours are shown (without uncertainty bands). Configurations resulting in multiple, disjoint patches of excluded areas are rejected.}\\label{fig:fit_scan_optimisation}}\n{\\includegraphics[width=0.60\\textwidth]{HF/batch_compare}}\n\\end{figure}\n\nAs expected from~\\cref{tab:cut_scan_results}, the best performing configurations define multiple signal region bins in the $\\mt$ and $\\mct$ distributions, while keeping a constant baseline selection on the remaining observables.\n\\Cref{fig:plot_binnings} shows a comparison of the expected exclusion contour for exemplary two-dimensional shape-fit configurations, using signal regions binned in ($\\mt$, $\\etmiss$), ($\\mt$, $\\mbb$) or ($\\mt$, $\\mct$).\nThe setup using a two-dimensional shape-fit in $\\mt$ and $\\mct$ clearly maximises the expected excluded area.\n%In addition, this configuration also leads to optimal sensitivity within the expected limit, as is illustrated in~\\cref{fig:plot_binnings_cls}.\nFinally, applying a requirement on high values of $\\mlb$ in the highest $\\mt$ bins has been shown (cf.~\\cref{fig:plot_mlb1_cls}) to further increase sensitivity to signal models with high mass differences. \n\nIn~\\cref{fig:previous_analysis_comparison}, the fully optimised two-dimensional shape-fit configuration is compared with the signal regions of the previous iteration of the search~\\cite{SUSY-2017-01}, scaled up to the integrated luminosity of the full Run~2 dataset.\nIt can clearly be seen that a significant improvement in sensitivity is achieved through the introduction of the two-dimensional shape-fit strategy.\n\n \\begin{figure}\n\t\\centering\n\t\\begin{subfigure}[b]{0.5\\linewidth}\n\t\t\\centering\\includegraphics[width=1.0\\textwidth]{HF/plot_binnings}\n\t\t\\caption{\\label{fig:plot_binnings}}\n\t\\end{subfigure}\\hfill\n\t\\begin{subfigure}[b]{0.5\\linewidth}\n\t\t\\centering\\includegraphics[width=1.0\\textwidth]{HF/plot_2d_shapefit}\n\t\t\\caption{\\label{fig:previous_analysis_comparison}}\n\t\\end{subfigure}\\hfill\n\n\t\\caption{Comparison of different shape-fit configurations. Figure~\\subref{fig:plot_binnings} compares three different two-dimensional shape-fit configurations using $3\\times 3$ bins in ($\\mt$, $\\etmiss$), ($\\mt$, $\\mbb$) and ($\\mt$, $\\mct$). Figure~\\subref{fig:previous_analysis_comparison} compares the two-dimensional shape-fit in $\\mt$ and $\\mct$ to the signal regions of the previous analysis iteration signal regions scaled to \\onethirtynineifb. All exclusion limits shown are expected limits at 95\\% CL, using \\gls{mc} statistical and 30\\% systematic uncertainties.}\n\t\\label{fig:results_HF_scans}\n\\end{figure}\n\n\n\\section{Signal region definitions}\\label{sec:signal_region_definitions}\n\n\\begin{table}\n\t\\begin{center}\n\t\t\\begin{tabular} {l | c c c }\n\t\t\t\\toprule\n\t\t\t\t&  \\textbf{SR-LM} & \\textbf{SR-MM} & \\textbf{SR-HM} \\\\\n\t\t\t\\midrule\n\t\t\t$N_{\\mathrm{lepton}}$ & \\multicolumn{3}{c}{$=$ 1}\\\\\n\t\t\t$\\ptl$ [\\GeV] & \\multicolumn{3}{c}{ $>7(6)$ for $e$($\\mu$)} \\\\\n\t\t\t$N_\\mathrm{jet}$ & \\multicolumn{3}{c}{$=$ 2 or 3}\\\\\n\t\t\t$N_{b\\textrm{-jet}}$ &\\multicolumn{3}{c}{$=$ 2} \\\\\n\t\t\t$\\met$ $[\\SI{}{\\GeV}]$ & \\multicolumn{3}{c}{$>240$}\\\\\n\t\t\t$\\mbb$  $[\\SI{}{\\GeV}]$ & \\multicolumn{3}{c}{$\\in [100,140]$}\\\\\n\t\t\t$m(\\ell,b_1)$ $[\\SI{}{\\GeV}]$ & -- & -- & $>120$ \\\\\n\t\t\t\\midrule\n\t\t\t%                        \\mt $[\\SI{}{\\GeV}]\\mathrm{(excl.)}$&   $\\in [100,160]$ & $\\in [160,240]$ & $\\in [240,\\infty]$ \\\\\n\t\t\t$\\mt$ $[\\SI{}{\\GeV}]~\\mathrm{(excl.)}$&   $\\in [100,160]$ & $\\in [160,240]$ & $>240$ \\\\\n\t\t\t\n\t\t\t\n\t\t\t$\\mct$ $[\\SI{}{\\GeV}]~\\mathrm{(excl.)}$ &\\multicolumn{3}{c}{ $ \\{ \\in [180,230]$,\\,$\\in [230,280]$, $>280  \\}$}\\\\\n\t\t\t%                        &\\multicolumn{3}{c}{ $\\in [180,230]$}\\\\\n\t\t\t%                        \\mct $[\\SI{}{\\GeV}]\\mathrm{(excl.)}$ & \\multicolumn{3}{c}{ $\\in [230,280]$} \\\\   \n\t\t\t%                         & \\multicolumn{3}{c}{ $>280$}\\\\\n\t\t\t%                         & \\multicolumn{3}{c}{ $\\in [280,\\infty]$}\\\\\n\t\t\t\n\t\t\t\\midrule\n\t\t\t$\\mt$ $[\\SI{}{\\GeV}]~\\mathrm{(disc.)}$&   $>100$ & $>160$ & $>240$ \\\\\n\t\t\t$\\mct$ $[\\SI{}{\\GeV}]~\\mathrm{(disc.)}$ & \\multicolumn{3}{c}{ $>180$}\\\\\n\t\t\t\\bottomrule\n\t\t\\end{tabular}\n\t\t\\caption{Overview of the selection criteria for the signal regions. Exclusion \\glspl{sr} (`excl.') are defined for model-dependent limits, and discovery \\glspl{sr} (`disc.') are defined for model-independent upper limits. A dash `--' is used where no requirement on the respective observable is applied.} \n\t\t\\label{tab:SignalRegionDef}\n\t\\end{center}\n\\end{table}\n\nAn overview of the final signal region definitions is provided in~\\cref{tab:SignalRegionDef}.\nBased on the previously discussed results, three signal regions bins in $\\mt$ are defined, optimised for different regimes in the \\mbox{$\\charg$/$\\neutr$} and $\\lsp$ mass difference. According to the mass difference regime targeted, they are aptly called low (SR-LM), medium (SR-MM), and high (SR-HM) mass signal regions, respectively.\nWhile SR-LM targets the smallest values of $\\mt$, SR-MM and SR-HM target progressively increasing values of $\\mt$.\nAll three signal regions are further divided into three $\\mct$ bins each, resulting in a total of nine disjoint signal region bins. The signal region with the highest requirement on $\\mt$ (SR-HM) also requires $\\mlb>\\SI{120}{\\GeV}$, for the reason explained previously.\nAll three signal regions otherwise share a common set of requirements on the number of jets, $\\etmiss$ and $\\mbb$.\nAs shape-fits are by construction highly model-dependent\\footnote{The signal shapes need to be known in order to estimate the expected signal rates in multiple, disjoint signal region bins.}, these \\glspl{sr} will be used for deriving model-dependent limits in the case where no significant excess, compared to the expected \\gls{sm} background rate, is seen in data.\nFor this reason, the shape-fit regions will be referred to as \\textit{exclusion} regions in the following. A graphical representation of the nine exclusion signal region bins is shown in~\\cref{fig:sr_strategy}.\nThe kinematic distributions in SR-LM, SR-MM and SR-HM are shown as \\textit{N}--1 plots in \\cref{fig:Wh_reopt_second_round_n1_srlm,fig:Wh_reopt_second_round_n1_srmm,fig:Wh_reopt_second_round_n1_srhm}.\n\nFor evaluating a potential excess in data compared to the expected background rate, a second set of signal regions is derived from the optimised shape-fit setup.\nFor each of the three bins in the transverse mass (SR-LM, SR-MM, and SR-HM), the three $\\mct$ bins are summed up and the upper bound on $\\mt$ is removed (if present).\nThis results in three \\textit{cut-and-count} signal regions in which only the total number of events after the selection is relevant. Since no information about the shape of the distribution of signal events is used, these so-called \\textit{discovery} regions make minimal model assumptions, and can be used to constrain any \\gls{bsm} physics process for which the expected event rates in one or multiple discovery signal regions are known (cf.~\\cref{sec:model_independent_limits}).\nIn case no significant excess over the \\gls{sm} expectation is seen in data, the discovery \\glspl{sr} can be used to derive upper limits on the visible cross section of physics beyond the \\gls{sm}, \\ie the apparent cross section of \\gls{bsm} processes including the acceptance and efficiency of the signal region selections. \n\n% -------------------------------------------------------------------------------------------------------\n\\FloatBarrier\n\\newpage\n% -------------------------------------------------------------------------------------------------------\n\n%\\begin{figure}\n%\\floatbox[{\\capbeside\\thisfloatsetup{capbesideposition={right,center},capbesidewidth=0.5\\textwidth}}]{figure}[\\FBwidth]\n%{\\caption{Configuration of the exclusion signal regions. Nine signal region bins are defined on $\\mt$ and $\\mct$ within the Higgs mass window. All signal regions can be statistically combined using a single likelihood, effectively resulting in a two-dimensional shape-fit.}\\label{fig:sr_strategy}}\n%{\\includegraphics[width=0.45\\textwidth]{strategy_2}}\n%\\end{figure}\n\n\\begin{figure}\n\t\\centering\\includegraphics[width=0.6\\textwidth]{strategy_2}\n\t\\caption{Configuration of the exclusion signal regions. Nine signal region bins are defined in $\\mt$ and $\\mct$ within the Higgs mass window. All signal regions can be statistically combined using a single likelihood, effectively resulting in a two-dimensional shape-fit.}\\label{fig:sr_strategy}\n\\end{figure}\n\n\\begin{figure}\n\t\\centering\n\t\\begin{subfigure}[b]{0.45\\linewidth}\n\t\t\\centering\\includegraphics[width=\\textwidth]{n1_SRLM_mct_bins/met.pdf}\n\t\t\\vspace{-2em}\n\t\t\\caption{\\label{fig:Wh_reopt_second_round_n1_srlm_met}}\n\t\\end{subfigure}%\n\t\\begin{subfigure}[b]{0.45\\linewidth}\n\t\t\\centering\\includegraphics[width=\\textwidth]{n1_SRLM_mct_bins/mct.pdf}\n\t\t\\vspace{-2em}\n\t\t\\caption{\\label{fig:Wh_reopt_second_round_n1_srlm_mct}}\n\t\\end{subfigure}\n\t\\par\\medskip\n\t\\begin{subfigure}[b]{0.45\\linewidth}\n\t\t\\centering\\includegraphics[width=\\textwidth]{n1_SRLM_mct_bins/mt_both.pdf}\n\t\t\\vspace{-2em}\n\t\t\\caption{\\label{fig:Wh_reopt_second_round_n1_srlm_mt}}\n\t\\end{subfigure}%\n\t\\begin{subfigure}[b]{0.45\\linewidth}\n\t\t\\centering\\includegraphics[width=\\textwidth]{n1_SRLM_mct_bins/mbb_both.pdf}\n\t\t\\vspace{-2em}\n\t\t\\caption{\\label{fig:Wh_reopt_second_round_n1_srlm_mbb}}\n\t\\end{subfigure}\n%\t\\begin{subfigure}[b]{0.4\\linewidth}\n%\t\t\\centering\\includegraphics[width=\\textwidth]{n1_SRLM_mct_bins/mlb1.pdf}\n%\t\t\\caption{\\label{fig:Wh_reopt_second_round_n1_srlm_mlb1}}\n%\t\\end{subfigure}%\n\t\\par\\medskip\n\t\\begin{subfigure}[b]{0.45\\linewidth}\n\t\t\\centering\\includegraphics[width=\\textwidth]{n1_SRLM_mct_bins/nJet30.pdf}\n\t\t\\vspace{-2em}\n\t\t\\caption{\\label{fig:Wh_reopt_second_round_n1_srlm_njet}}\n\t\\end{subfigure}\n\t\\caption{\\textit{N}--1 plots for SR-LM, with representative signal points and all $\\mct$ bins included. The dashed area represents the \\gls{mc} statistical uncertainties on the background. In all figures except \\figname~\\subref{fig:Wh_reopt_second_round_n1_srlm_mct}, the significance in the lower pad is obtained by summing up all the events in the direction of the cut arrow and includes 30\\% systematic uncertainties as well as MC statistical uncertainties. In \\figname~\\subref{fig:Wh_reopt_second_round_n1_srlm_mct} the significance is only computed on a bin-by-bin basis, \\ie not summing up all events in the direction of the cut arrow.}\n\t\\label{fig:Wh_reopt_second_round_n1_srlm}\n\\end{figure}\n\n\\begin{figure}\n\t\\centering\n\t\\begin{subfigure}[b]{0.45\\linewidth}\n\t\t\\centering\\includegraphics[width=\\textwidth]{n1_SRMM_mct_bins/met.pdf}\n\t\t\\vspace{-2em}\n\t\t\\caption{\\label{fig:Wh_reopt_second_round_n1_srmm_met}}\n\t\\end{subfigure}%\n\t\\begin{subfigure}[b]{0.45\\linewidth}\n\t\t\\centering\\includegraphics[width=\\textwidth]{n1_SRMM_mct_bins/mct.pdf}\n\t\t\\vspace{-2em}\n\t\t\\caption{\\label{fig:Wh_reopt_second_round_n1_srmm_mct}}\n\t\\end{subfigure}\n\t\\par\\medskip\n\t\\begin{subfigure}[b]{0.45\\linewidth}\n\t\t\\centering\\includegraphics[width=\\textwidth]{n1_SRMM_mct_bins/mt_both.pdf}\n\t\t\\vspace{-2em}\n\t\t\\caption{\\label{fig:Wh_reopt_second_round_n1_srmm_mt}}\n\t\\end{subfigure}%\n\t\\begin{subfigure}[b]{0.45\\linewidth}\n\t\t\\centering\\includegraphics[width=\\textwidth]{n1_SRMM_mct_bins/mbb_both.pdf}\n\t\t\\vspace{-2em}\n\t\t\\caption{\\label{fig:Wh_reopt_second_round_n1_srmm_mbb}}\n\t\\end{subfigure}\n%\t\\begin{subfigure}[b]{0.4\\linewidth}\n%\t\t\\centering\\includegraphics[width=\\textwidth]{n1_SRMM_mct_bins/mlb1.pdf}\n%\t\t\\caption{\\label{fig:Wh_reopt_second_round_n1_srmm_mlb1}}\n%\t\\end{subfigure}%\n\t\\par\\medskip\n\t\\begin{subfigure}[b]{0.45\\linewidth}\n\t\t\\centering\\includegraphics[width=\\textwidth]{n1_SRMM_mct_bins/nJet30.pdf}\n\t\t\\vspace{-2em}\n\t\t\\caption{\\label{fig:Wh_reopt_second_round_n1_srmm_njet}}\n\t\\end{subfigure}\n\t\\caption{\\textit{N}--1 plots for SR-MM, with representative signal points and all $\\mct$ bins included. The dashed area represents the \\gls{mc} statistical uncertainties on the background. In all figures except \\figname~\\subref{fig:Wh_reopt_second_round_n1_srmm_mct}, the significance in the lower pad is obtained by summing up all the events in the direction of the cut arrow and includes 30\\% systematic uncertainties as well as MC statistical uncertainties. In \\figname~\\subref{fig:Wh_reopt_second_round_n1_srmm_mct} the significance is only computed on a bin-by-bin basis, \\ie not summing up all events in the direction of the cut arrow.}\n\t\\label{fig:Wh_reopt_second_round_n1_srmm}\n\\end{figure}\n\n\\begin{figure}\n\t\\centering\n\t\\begin{subfigure}[b]{0.45\\linewidth}\n\t\t\\centering\\includegraphics[width=\\textwidth]{n1_SRHM_mct_bins/met.pdf}\n\t\t\\vspace{-2em}\n\t\t\\caption{\\label{fig:Wh_reopt_second_round_n1_srhm_met}}\n\t\\end{subfigure}%\n\t\\begin{subfigure}[b]{0.45\\linewidth}\n\t\t\\centering\\includegraphics[width=\\textwidth]{n1_SRHM_mct_bins/mct.pdf}\n\t\t\\vspace{-2em}\n\t\t\\caption{\\label{fig:Wh_reopt_second_round_n1_srhm_mct}}\n\t\\end{subfigure}\n\t\\par\\medskip\n\t\\begin{subfigure}[b]{0.45\\linewidth}\n\t\t\\centering\\includegraphics[width=\\textwidth]{n1_SRHM_mct_bins/mt_both.pdf}\n\t\t\\vspace{-2em}\n\t\t\\caption{\\label{fig:Wh_reopt_second_round_n1_srhm_mt}}\n\t\\end{subfigure}%\n\t\\begin{subfigure}[b]{0.45\\linewidth}\n\t\t\\centering\\includegraphics[width=\\textwidth]{n1_SRHM_mct_bins/mbb_both.pdf}\n\t\t\\vspace{-2em}\n\t\t\\caption{\\label{fig:Wh_reopt_second_round_n1_srhm_mbb}}\n\t\\end{subfigure}\n\t\\par\\medskip\n\t\\begin{subfigure}[b]{0.45\\linewidth}\n\t\t\\centering\\includegraphics[width=\\textwidth]{n1_SRHM_mct_bins/mlb1.pdf}\n\t\t\\vspace{-2em}\n\t\t\\caption{\\label{fig:Wh_reopt_second_round_n1_srhm_mlb1}}\n\t\\end{subfigure}%\n\t\\begin{subfigure}[b]{0.45\\linewidth}\n\t\t\\centering\\includegraphics[width=\\textwidth]{n1_SRHM_mct_bins/nJet30.pdf}\n\t\t\\vspace{-2em}\n\t\t\\caption{\\label{fig:Wh_reopt_second_round_n1_srhm_njet}}\n\t\\end{subfigure}\n\t\\caption{\\textit{N}--1 plots for SR-HM, with representative signal points and all $\\mct$ bins included. The dashed area represents the \\gls{mc} statistical uncertainties on the background. In all figures except \\figname~\\subref{fig:Wh_reopt_second_round_n1_srhm_mct}, the significance in the lower pad is obtained by summing up all the events in the direction of the cut arrow and includes 30\\% systematic uncertainties as well as MC statistical uncertainties. In \\figname~\\subref{fig:Wh_reopt_second_round_n1_srhm_mct} the significance is only computed on a bin-by-bin basis, \\ie not summing up all events in the direction of the cut arrow.}\n\t\\label{fig:Wh_reopt_second_round_n1_srhm}\n\\end{figure}\n\n\n\n\n", "meta": {"hexsha": "f88d65f6afaad020c703906f902e863a1badef78", "size": 38134, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapter-optimisation/optimisation.tex", "max_stars_repo_name": "eschanet/phd-thesis", "max_stars_repo_head_hexsha": "607efdd3d48ec4def49ba41188c4453b04dd99d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapter-optimisation/optimisation.tex", "max_issues_repo_name": "eschanet/phd-thesis", "max_issues_repo_head_hexsha": "607efdd3d48ec4def49ba41188c4453b04dd99d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter-optimisation/optimisation.tex", "max_forks_repo_name": "eschanet/phd-thesis", "max_forks_repo_head_hexsha": "607efdd3d48ec4def49ba41188c4453b04dd99d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 93.4656862745, "max_line_length": 1077, "alphanum_fraction": 0.7542875125, "num_tokens": 10310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.3327357229393087}}
{"text": "% 270 words\n% Limit: 500 words\n\\section{Method}\n\n\\subsection{The data}\n\nWe crossmatched the \\mct\\ catalog of stellar rotation periods, measured from\n\\kepler\\ light curves, with the \\gaia\\ DR2 catalog.\nReddening and extinction from dust was calculated for each star using the\nBayestar dust map implemented in the dustmaps {\\it Python} package\n\\citep{green2018}.\nWe estimated effective temperatures from dereddened \\Gaia\\ \\gcolor\\ color,\nusing an 8th-order polynomial relation calibrated using .... stars\n\\racomment{ask Jason for details}.\n\\begin{equation}\n    \\mathrm{T_{eff}} = 8960 -4802C + 1931C^2 -2446C^3 + 2669C^4 - 1324C^5 +\n    301C^6 - 26C^7,\n% 8959.8112335205078, -4801.5566310882568, 1931.4756631851196,\n%           -2445.9980716705322, 2669.0248055458069, -1324.0671020746231,\n%           301.13205924630165, -25.923997443169355]\n\\end{equation}\nwhere C is \\gaia\\ \\gcolor.\n\n\\begin{figure}\n  \\caption{\nA \\gaia\\ color magnitude diagram showing the \\citet{mcquillan2014} sample with\n    extinction-corrected magnitudes, colored by rotation period.\nWe excluded photometric binaries and subgiants from our analysis by removing\nstars above the two dashed lines.\nThe rotation periods of binaries and subgiants do not follow a Skumanich-like\nbraking law.\nThe rotation period gradient across the main sequence is visible by eye in\n    this figure: young, rapidly rotating stars are located below the old,\n    slowly rotating stars.\n}\n  \\centering\n    \\includegraphics[width=1\\textwidth]{CMD_cuts}\n\\label{fig:CMD_cuts}\n\\end{figure}\nWe removed visual binaries and subgiants from the sample as the\nrotation-period evolution of these two types of stars is generally different\nto that of single stars which more usually follow a Skumanich-like spin-down\nlaw.\n% Tidal and magnetic interactions between the two components of a binary system\n% can influence the rotation periods of both stars, and the expanding envelopes\n% of subgiants drive rapid spin-down through conservation of angular momentum.\nWe removed visual binaries and subgiants from the sample by applying cuts to\nthe color-magnitude diagram (CMD), shown in figure \\ref{fig:CMD_cuts}.\nWe fit a 6th-order polynomial to the main sequence and raised it by 0.22 dex,\nto approximate the division between single stars and visual binaries.\nWe eliminated visual binaries by removing all stars above this line from the\nsample, and subgiants by removing stars brighter than 6th magnitude in \\gaia\\\nG-band.\n\nWe removed stars with negative parallaxes and parallax signal-to-noise ratios\nbelow 10 and a small number of stars fainter than 16th magnitude from the\nsample.\nWe used the {\\tt Pyia} \\citep{price-whelan_2018} and {\\tt astropy}\n\\citep{astropy2013, astropy2018} {\\it Python} packages to calculate stellar\nvelocities.\n{\\tt Pyia} has built-in functionality for calculating velocity samples from\nthe full \\gaia\\ uncertainty covariance matrix via Monte Carlo sampling.\nIt therefore not only incorporates uncertainties on the \\gaia\\ positions\nparallaxes and proper motions, it also accounts for the {\\it covariance}\nbetween these properties.\nFinally, we removed stars with absolute \\vb\\ uncertainties greater than 1\n\\kms\\ from the sample.\n\nGyrochronal ages were calculated using a polynomial gyrochronology relation\ncalibrated to Praesepe and the Sun \\citep{angus2019}.\nWe used dereddened \\gaia\\ \\gcolor\\ color to calculate these ages.\nFigure \\ref{fig:period_teff} shows the \\mct\\ rotation period sample, separated\ninto three groups: stars above the gap in blue (classified as stars older than\n1.1 Gyr), stars below the gap in orange (younger than 1.1 Gyr but older than\n0.5 Gyr), and stars that are likely to be synchronized binaries (younger than\n0.5 Gyr).\nWe used a gyrochronal isochrone (often called a gyrochrone) to separate these\ngroups of stars because the rotation period gap appears to fall on a\ngyrochrone of 1.1 Gyr, and because the lower envelope of rotation periods is\nalso shaped like a gyrochrone at 0.5 Gyr.\nThis is probably because there is not a significant number of stars younger\nthan 500 Myr in the \\kepler\\ field.\nStars with short rotation periods, that seem younger than 500 Myr according to\nthe \\citet{angus2019} gyrochronology relation are likely to be binaries.\nStars rotating more rapidly than 7 days were shown to be mostly synchronized\nbinaries \\citep{citation}.\nThis is also borne out in the results section of this paper.\nAlthough most rapid rotators are likely synchronized binaries (and therefore\nnot actually young -- just rotating rapidly because of tidal synchronization),\n{\\it some} of the rapid rotators probably {\\it are} young and this could be an\nextremely interesting group of stars from a scientific standpoint.\n\n\\begin{figure}\n  \\caption{\nThe rotation periods of stars in the \\citet{mcquillan2014} sample vs.\neffective temperature, with visual binaries and subgiants removed.\nBlue circle points are non-photometric binary dwarfs, cooler than 4800 k, with\na rotation period and \\gaia\\ color indicating they are older than 1.1 gyr.\norange squares are stars that with rotation periods that fall just below the\ngap: they have rotation-ages between 0.5 and 1.1 gyrs.\nGreen triangles are stars with rotation periods faster than the main envelope\nof stars.\nThese are probably binaries whose rotation periods are synchronized to their\norbits and have been spun-up via tidal interactions.\n}\n  \\centering\n    \\includegraphics[width=1\\textwidth]{period_teff}\n\\label{fig:period_teff}\n\\end{figure}\n", "meta": {"hexsha": "8eef11889d6f3c764a584cf46d65d07387aa7fa2", "size": 5477, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "method.tex", "max_stars_repo_name": "RuthAngus/period_gap", "max_stars_repo_head_hexsha": "cca9037cfd8aaba75822480d7f906c90021a0f51", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "method.tex", "max_issues_repo_name": "RuthAngus/period_gap", "max_issues_repo_head_hexsha": "cca9037cfd8aaba75822480d7f906c90021a0f51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "method.tex", "max_forks_repo_name": "RuthAngus/period_gap", "max_forks_repo_head_hexsha": "cca9037cfd8aaba75822480d7f906c90021a0f51", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.7909090909, "max_line_length": 79, "alphanum_fraction": 0.7918568559, "num_tokens": 1396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6654105587468141, "lm_q2_score": 0.5, "lm_q1q2_score": 0.33270527937340705}}
{"text": "%!TEX root = theory.tex\n% =========================================================================\n% -------------------------------------------------------------------------\n% Single and Multiphase Flow:\n% -------------------------------------------\n%\n%  This is a good place to outline key objectives of this section.\n%\n% -------------------------------------------------------------------------\n\n% bold symbols\n\\def\\bnabla{{\\boldsymbol{\\nabla}}}\n\\def\\bg{{\\boldsymbol{g}}}\n\\def\\bq{{\\boldsymbol{q}}}\n\\def\\bx{{\\boldsymbol{x}}}\n\\def\\bJ{{\\boldsymbol{J}}}\n\\def\\K{{\\mathbb K}}\n\n% abbreviations\n\\def\\Frac{\\displaystyle \\frac}\n\n% units\n\\def\\ucdot{{\\,\\cdot\\,}}\n\\def\\ukg{{\\rm kg}}\n\\def\\um{{\\rm m}}\n\\def\\us{{\\rm s}}\n\\def\\umol{{\\rm mol}}\n\\def\\upa{{\\rm Pa}}\n\n\\section{Isothermal Flow Processes}         \n\\label{sec:flow-processes}\n\n\\subsection{Overview}\n\nSubsurface flow simulations typically assume that Darcy's law is valid. \nAs this law gives a relationship between velocity and pressure,\nit essentially replaces the momentum equation. \nThere has been much research to support the validity of Darcy's\nLaw~\\citep{bear-1972}.\nMost references give the applicability of Darcy's Law to be \nfor laminar flows with Reynolds numbers less that 10 using the pore throat diameter for a soil.\nThere has been some effort to include inertial as well as turbulence effects that can occur near the wells.\n\nIt is also assumed that thermodynamic equilibrium (mechanical and thermal) exists for each grid block.  \nSub-grid scale features often play a prominent role in multi-fluid simulations. \nFaults and fractures will likely be fast paths for contaminant transport and can\neffectively be treated with multiple porosity models. \nSimilarly, rate-limited diffusion from clay inclusions can also be modeled with a\nmultiple porosity material.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\subsection{Fully Saturated Flow}\n\\label{sec:flow-single-phase}\n\nThe most basic flow model is a single-phase fully saturated flow in a porous medium.  \nNotwithstanding its simplicity, it has a wide application to\ndescribing subsurface processes.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Assumptions and Applicability}\n\nThere are many assumptions required for the strict validity of Darcy's Law, \nincluding \n\\begin{itemize}\n\\item\n  incompressibility and \n\\item\n  laminararity of the flow.\n\\end{itemize}\nWe also assume that \n\\begin{itemize}\n\\item\n  solid/rock is incompressible,\n\\item \n  fluid viscosity is constant,\n\\item\n  there are no fractures, only pores.\n\\end{itemize}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Process Model Equations}\n\nUnder the above assumptions fully saturated flow is governed by \n\\begin{subequations}\n\\label{eq:Darcy fully saturated}\n\\begin{align}\n  \\phi \\left(\\Frac{S_s}{g} + \\Frac{S_y}{L\\,g}\\right) \\frac{\\partial p_l}{\\partial t} \n  &=\n  -\\boldsymbol{\\nabla} \\cdot (\\rho_l \\boldsymbol{q}_l) + Q,\n  \\\\\n  \\bq_l &= -\\frac{\\K}{\\mu_l} \n  (\\bnabla p_l - \\rho_l \\bg),\n\\end{align}\n\\end{subequations}\nwhere the primary variable is the fluid presure $p_l$ [\\upa]. \nThe fluid velocity $\\bq_l$ [$\\um\\ucdot\\us^{-1}$] is the dependent variable.\nAll the other variables can be treated as material parameters\nthat sometimes may depend on pressure.\nThese include:\n$\\phi$ [-] is the porosity,\n$S_s$ [$\\um^{-1}$] and $S_y$ [-] are specific storage and yeild, respectively,\n$g$ [$\\um\\ucdot\\us^{-2}$] is the gravitational constant\nand $\\bg$ [$\\um\\ucdot\\us^{-2}$] is the gravitational vector,  \n$L$ [$\\um$] is a characteristic size of the yield layer, \n$\\K$ [$\\um^2$] is an absolute permeability tensor, and \n$Q$ [$\\ukg \\ucdot \\um^{-3} \\ucdot \\us^{-1}$] is source or sink term.\n \n\nIt is common to see the Darcy Law written in terms of hydraulic head $h$\nand the hydraulic conductivity tensor $\\K_h$:\n\\begin{subequations}  \\label{eq:HydraulicHead}\n\\begin{align}\n  \\bq_l &= -\\K_h \\bnabla h,\n  \\\\\n  h \\, &=  z + \\frac{p_l}{\\rho_l g},\n  \\\\\n  \\K_h &= \\K \\, \\frac{\\rho_l g}{\\mu_l}.\n\\end{align}\n\\end{subequations}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Boundary conditions}\n\n\nThree types of \\textit{boundary conditions} are supported by the model:\n\\begin{enumerate}\n\\item\n  prescribed pressure $p_l$ (or head), see \\eqref{eq:BC pressure Darcy FS};\n\\item\n  prescribed flux, i.e. normal component of the velocity $\\bq_l$, see \\eqref{eq:BC flux Darcy FS};\n\\item\n  semipervious boundary, see \\eqref{eq:BC semipervious Darcy FS}. \n\\end{enumerate}\n%\\citep[for reference see][]{bear-1979}.\n%These boundary conditions are described in Section~\\ref{sec:flow-boundary-conditions}.\n\n\\begin{figure}  [h]\n\\begin{center} \n\\includegraphics[scale=0.25]{figs/bc_flow.pdf}\n\\caption{Flow domain between two rivers \\citep[it was partially based on]{bear-1972}.}\n\\label{fig:bc_flow}\n\\end{center}\n\\end{figure}\n\n\\paragraph{Boundary of prescribed pressure or head.}\nThis involves the specification of a fixed pressure or hydrostatic head on boundary $\\Gamma_D$.\nFor instance, a boundary of this kind occurs whenever the flow domain is adjacent to a body of open water.\nSegments A-B and E-F in Fig.~\\ref{fig:bc_flow} are examples of a boundary of prescribed potential.\nThe pressure or head boundary conditions are given functions, e.g.\n\\begin{equation}\n\\label{eq:BC pressure Darcy FS}\n  p_l(\\bx,t) = p_{b}(\\bx,t), \\quad \\bx \\in \\Gamma_D. \n\\end{equation}\n\n\\paragraph{Boundary of prescribed flux.}\nThis involves the specification of the flux normal to the boundary $\\Gamma_N$\n(see segment C-D in Figure \\ref{fig:bc_flow}):\n\\begin{equation}\n\\label{eq:BC flux Darcy FS} \n  \\bq_l\\cdot \\bn = q_{b}(\\bx,t), \\quad \\bx \\in \\Gamma_N,\n\\end{equation}\nwhere $q_b$ [$\\um\\ucdot\\us^{-1}$] is the given boundary flux. \nFor infiltration at the top horizontal surface, it equals to the Darcy velocity\nand referred to as the infiltration velocity.\n\n\\paragraph{Semipervious boundary (or mixed boundary condition).}\nThis boundary condition is more complicated than the first two as it involves a case \nin which local conditions within the computational domain influence the flux in or \nout of the domain.\nThis type of boundary occurs when the porous medium domain is in contact with \na body of water continuum (or another porous medium domain, see for instance segments \nA-B and E-F in Fig.~\\ref{fig:bc_flow}), however, a relatively thin semipervious layer \nseparates the two domains:\n\\begin{equation}\n\\label{eq:BC semipervious Darcy FS}\n  \\bq_l \\cdot \\bn = I\\, \\left(p (\\bx,t) - p_{b}(\\bx,t) \\right), \\quad \\bx \\in \\Gamma_R.\n\\end{equation}\nwhere $I$ is an impedance and $p_{b}(\\bx,t)$ is the given external pressure.\n\n\n\n\\clearpage\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\subsection{Partially Saturated Flow}\n\\label{sec:richards-equation}\n\nThe Richards equation is often used to describe single phase flow under partially \nsaturated conditions (i.e., the pores are not occupied exclusively by a single phase).  \nAs such, it requires the introduction of a relative permeability and a capillary \npressure relations. % as discussed in Section~\\ref{sec:pc_s_relations}.\nThe Richards equation is well suited to very large numerical problems (millions of \ndegrees of freedom) because it requires only one independent variable per cell.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Assumptions and Applicability}\n\nThe Richards equation makes the fundamental assumption that \nwe are neglecting the movement of the gas phase.\nBecause of this assumption, using the Richards equation may limit the kinds of \ntransport analysis that can be done.\nIt should also be noted that the Richards equation is often highly nonlinear\ndue to strong dependence of the relative permeability of the liquid phase\non the liquid saturation.\nWe also assume that there are no fractures and the water flows through the pores only. \n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Process Model Equations} \n\\label{sec:richards-model-equations}\n\nThe Richards equation is derived from the conservation of\nliquid mass equation.\nIn the mixed formulation it is written\nfor the volumetirc water content $\\theta$ [$\\umol\\ucdot\\um^{-3}$] \nand the Darcy velocity $\\bq_l$ [$\\um\\ucdot\\us^{-1}$]:  \n\\begin{subequations}\\label{eq:Darcy}\n\\begin{align}\n  \\frac{\\partial \\theta(p_l)}{\\partial t} \n  &= \n  -\\bnabla \\cdot (\\eta_l \\bq_l) + Q,\n  \\\\\n  \\bq_l \n  &= \n  -\\frac{\\K k_{rl}}{\\mu_l} (\\bnabla p_l - \\rho_l \\bg),\n\\end{align}\n\\end{subequations}\nwhere \n$\\eta_l$ [$\\umol\\ucdot\\um^{-3}$] is the molar liquid density,\n$Q$ [$\\ukg \\ucdot \\um^{-3} \\ucdot \\us^{-1}$] is source or sink term,\n$\\K$ [$\\um^2$] is absolute permeability tensor,\n$\\mu_l$ [$\\upa\\ucdot\\us$ ] is liquid viscosity,\n$\\rho_l$ [$\\ukg\\ucdot\\um^{-3}$ ] is liquid density, and\n$k_{rl}$ [-] is relative permeability.\nThe total volumetric water content $\\theta$ is defined as\na product of porosity $\\phi$, molar liquid density $\\eta_l$ and liquid saturation $s_l$:\n$$\n  \\theta(p_l) = \\phi(p_l) \\eta_l\\, s_l(p_c).\n$$\nUsage of the molar liquid density $\\theta$\nallows us to easily extend the model to a non-isothermal case.\n\nJust like in the case of the fully saturated flow \\eqref{eq:Darcy fully saturated},\nthe primary dependent variable in \\eqref{eq:Darcy} is liquid pressure $p_l$.\nThe difference with \\eqref{eq:Darcy fully saturated}\nis in that the pressure enters the equations in a nonlinear form,\nthrough a dependence $\\theta_l(p_l)$ to be discussed in the following sections.\n\nIn general the porosity $\\phi$ is a functions of pressure $p_l$.\nThe relative permeability $k_{rl}$ is a function of saturation $s_l$,\nwhich in turns is a function of capillary pressure $p_c$. \nThe relation between pressures $p_l$ and $p_c$ will be discussed in the next section.\nTypical models of relative permeability are \nthe van Genuchten-Mualem relations \\eqref{eq:krl_vGM} and \nthe Brooks-Corey-Burdine relations \\eqref{eq:krl_BCB}.\nThe equation \\eqref{eq:Darcy} is continuous when transitioning from the saturated to the vadoze zones.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Capillary Pressure -- Saturation Relations}  \n\\label{sec:richards-pc_s_relations}\n\nRichards equation for unsaturated flow\n%, as well as more general multiphase flow models, \nrequires representations of the capillary pressure $p_c$ and the relative permeability $k_{rl}$.  \nThe capillary pressure is a fundamental dependent variable in the multi-phase flow model, and\nrelates the difference in pressure across an interface between two\nfluids to the tendency of a porous medium to pull in the wetting fluid\nand push out the non-wetting one.\nFor the partially saturated fluid flow model typically used to\ncharacterize air-water systems, \nthere is only a single capillary pressure:\n\\begin{equation} \\label{eq:GasLiquidCapillaryPressure}\n  p_c = p_g - p_l\n\\end{equation}\nwhere $p_g$ is the pressure of the air/gas. \n\nLet us define the effective liquid saturation $s_e$ as\n\\begin{equation}\n\\label{eq:SaturationDefinition}\ns_e \\eq \\frac{s_l^{} - s_l^r}{s_l^0 - s_l^r}, \n\\end{equation}\nwhere $s_l^0$ is the maximum and\n$s_l^r$ is the residual (i.e. minimum) liquid saturations. \nNotice that \\eqref{eq:SaturationDefinition} implies the effective saturation $s_e$\ntakes values in the range from zero to one.\n\nUsing these definitions, \ntwo widely used capillary pressure-saturation model relations are presented below, \nnamely the Brooks-Corey \\citep{brooks1964hydraulic} and van Genuchten \\citep{van1980closed} \nmodels.\n\n\n\\paragraph{Brooks-Corey model.}\nThe Brooks-Corey form of the saturation function \\citep{brooks1964hydraulic} is given by\n\\begin{equation}\n  \\label{eq:BC_s_pc_relation}\n  s_e \\eq \\left( \\alpha |p_c| \\right)^{-\\lambda}, \n\\end{equation}\nwhere the empirical parameters $\\lambda$ [-], and $\\alpha$ [$\\upa^{-1}$] \nare fit to experimental observations.\nThe inverse relation is written as\n\\begin{equation}\n  \\label{eq:BC_pc_s_relation}\n  p_c \\eq \\frac{1}{\\alpha} s_e^{-1/\\lambda}.\n\\end{equation}\n\n\\paragraph{Van Genuchten model.}\nIn the \\citet{van1980closed} model the effective liquid saturation is\ndescribed by the relation\n%\n\\begin{equation}  \n  \\label{eq:vG_s_pc_relation}\n  s_e \\eq \\left[1+\\left( \\alpha |p_c| \\right)^n \\right]^{-m}, \n\\end{equation}\n%\nwith inverse relation\n\\begin{equation}\n  \\label{eq:vG_pc_s_relation}\n  p_c \\eq \\frac{1}{\\alpha} \\left[ s_e^{-1/m} -1 \\right]^{1/n}.\n\\end{equation}\n%\nThe non-dimensional constants $n$ [-], $m$ [-] and dimensional $\\alpha$ [$\\upa^{-1}$] are\nempirical parameters.\n\n\nOne may notice that Van Genuchten model is an evolution of Brooks-Corey model as evident \nboth by the dates and the form of the equations.\nIn particular notice that if we take \n$\\lambda = mn$ and $(\\alpha p_c)^n \\gg 1$, \nthen the Brooks-Corey and van Genuchten saturation functions, \nEquations \\eqref{eq:BC_s_pc_relation} and \\eqref{eq:vG_s_pc_relation}, are equivalent.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Relative Permeability -- Saturation Relations}\n\\label{sec:richards-relative-permeability}\n\nGiven capillary pressure - saturation relations $p_c(s_l$, \nthe relative permeability relations needed by Richards equation can be defined.  \nTwo popular relative permeability - saturation relations used in air-water \nsystems are the \\citet{mualem1976new} and \\citet{burdine1953relative} models.\nThe relative permeability model proposed by \\citet{mualem1976new} has the form\n\\begin{equation} \\label{eq:Mualem}\n  k_{rl}(s_l) \n  = \n  s_e^{\\ell} \\, \n  \\frac{ \\left\\{ \\displaystyle\\int_0^{s_e} p_c(s)^{-1} ds \\right\\}^2 }\n  { \\left\\{ \\displaystyle\\int_0^{1} p_c(s)^{-1} ds \\right\\}^2 },\n\\end{equation}\nwhere the power $\\ell$ in $s_e^\\ell$ is a pore-connectivity parameter that varies \ndepending on the soil. \nAlthough, \\citet{mualem1976new} estimated an average value of\n$\\ell=1/2$, values of $\\ell$ ranged from -5 to +5 across soils. More recent studies\n[cf. \\citet{vanG_retc_1991}] have suggested that $\\ell=1/2$ may be\nappropriate for coarse-textured soils, but not for many medium- and\nfine-textured soils. Thus, $\\ell$ should be available as a fitting parameter.\n\nSimilarly, the older \\citet{burdine1953relative} model is given by\n\\begin{equation}\n\\label{eq:Burdine}\n  k_{rl}(s_l) = s_e^{\\ell} \\, \n    \\frac{ \\displaystyle\\int_0^{s_e} p_c(s)^{-2} ds }\n         { \\displaystyle\\int_0^{1} p_c(s)^{-2} ds },\n\\end{equation}\nwhere \\citet{burdine1953relative} assumed $\\ell=2$. However, as with\nthe Mualem model \\eqref{eq:Mualem}, $\\ell$, should be available as a\nfitting parameter.\n\n\n\\paragraph{Van Genuchten relative permeability.}\nTo obtain a closed-form solution for the relative permeability using\neither the Mualem or Burdine models (Eqns.\\eqref{eq:Mualem} and\n\\eqref{eq:Burdine}, respectively) combined with the van Genuchten\nsaturation function, the parameters $n$ and $m$ must be related by the\nexpressions\n\\begin{equation}\n\\label{eq:lambda} \nm = \\left\\{\n  \\begin{array}{ll}\n    1 - \\dfrac{1}{n}, & \\text{Mualem},\\\\[9pt]\n    1 - \\dfrac{2}{n}, & \\text{Burdine}.\n  \\end{array}\n\\right.\n\\end{equation}\nIn the more general case of independent values of $m$ and $n$ the\nrelative permeability involves the incomplete beta function \\citep{vangenuchten1985}. \nMore recently \\citep{douradoneto2011} presented a general model for Mualem and \nBurdine relative permeability functions for use with the van Genuchten saturation \nfunction in terms of hypergeometric functions.\n\n\nThe Burdine relative permeability function for the liquid phase derived\nfrom the van Genuchten saturation function is given by\n\\begin{equation}\n  k_{rl} \\eq s_e^{2} \\left\\{ 1 - \\left[ 1 - s_e^{1/m} \\right]^m \\right\\}.\n  \\label{eq:krl_vGB} \n\\end{equation}\n\nThe Mualem \nrelative permeability function has the form (note power 2):\n\\begin{equation}\n  k_{rl} \\eq s_e^{\\ell} \\left\\{ 1 - \\left[ 1 - s_e^{1/m} \\right]^m \\right\\}^2.\n  \\label{eq:krl_vGM} \n\\end{equation}\n\n\n\n\n\\paragraph{Brooks-Corey relative permeability.}\nCombined with the Brooks-Corey saturation function, the Mualem\nrelative permeability function is given by\n\\begin{equation} \\label{eq:krl_BCM}\n  k_{rl} = \\big(s_e\\big)^{\\ell+2+2/\\lambda} \n         = \\left(\\alpha |p_c|\\right)^{-((\\ell+2)\\lambda+2)}.\n\\end{equation}\nThe Burdine form originally considered by \\citet{brooks1964hydraulic}\nis given by\n\\begin{equation} \\label{eq:krl_BCB}\n  k_{rl} = \\left( s_e \\right)^{ \\ell+1+2/\\lambda}\n         = \\left( \\alpha |p_c| \\right)^{-((\\ell+1)\\lambda+2)}.\n\\end{equation}\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Boundary conditions}  \n%\nTo facilitate the discussion on boundary conditions, consider the case of \nflow described in Fig.~\\ref{fig:bc_flow}. \nAlthough the figure represents a two-dimensional flow field, the passage to three dimensions \nis straightforward and requires no further explanations. \n\nFour types of boundary conditions are supported by the model:\n\\begin{enumerate}\n\\item\n  prescribed pressure $p_l$ (or head), see \\eqref{eq:BC pressure Darcy PS};\n\\item\n  prescribed flux, i.e. normal component of the velocity $\\bq_l$, see \\eqref{eq:BC flux Darcy PS};\n\\item\n  semipervious boundary, see \\eqref{eq:BC semipervious Darcy PS}; %\\citep[for reference see][]{bear-1979};\n\\item\n  seepage face.\n\\end{enumerate}\n\n\n\n\\paragraph{Boundary of prescribed pressure or head.}\nThis involves the specification of a fixed pressure or hydrostatic head on boundary $\\Gamma_D$.\nFor instance, a boundary of this kind occurs whenever the flow domain is adjacent to a body of open water.\nSegments A-B and E-F in Fig.~\\ref{fig:bc_flow} are examples of a boundary of prescribed potential.\nThe pressure or head boundary conditions are given functions, e.g.\n\\begin{equation}\n\\label{eq:BC pressure Darcy PS}\n  p_l(\\bx,t) = p_{b}(\\bx,t), \\quad \\bx \\in \\Gamma_D. \n\\end{equation}\n\n\\paragraph{Boundary of prescribed flux.}\nThis involves the specification of the flux normal to the boundary $\\Gamma_N$\n(see segment C-D in Figure \\ref{fig:bc_flow}):\n\\begin{equation}\n\\label{eq:BC flux Darcy PS}\n  \\bq_l\\cdot \\bn = q_{b}(\\bx,t), \\quad \\bx \\in \\Gamma_N,\n\\end{equation}\nwhere $q_b$ [$\\um\\ucdot\\us^{-1}$] is the given boundary flux. \nFor infiltration at the top horizontal surface, it equals to the Darcy velocity\nand referred to as the infiltration velocity.\n\n\\paragraph{Semipervious boundary (or mixed boundary condition).}\nThis boundary condition is more complicated than the first two as it involves a case \nin which local conditions within the computational domain influence the flux in or \nout of the domain.\nThis type of boundary occurs when the porous medium domain is in contact with \na body of water continuum (or another porous medium domain, see for instance segments \nA-B and E-F in Fig.~\\ref{fig:bc_flow}), however, a relatively thin semipervious layer \nseparates the two domains:\n\\begin{equation}\n\\label{eq:BC semipervious Darcy PS}\n  \\bq_l \\cdot \\bn = I\\, \\left(p (\\bx,t) - p_{b}(\\bx,t) \\right), \\quad \\bx \\in \\Gamma_R.\n\\end{equation}\nwhere $I$ is an impedance and $p_{b}(\\bx,t)$ is the given external pressure.\n\n\\paragraph{Seepage face.}\nAs is shown in Fig.~\\ref{fig:bc_flow} (see segments B-C and D-E), seepage face (or surface) \nis always present when a phreatic surface ends at the down-stream external boundary of flow domain.\nIn this case the phreatic surface is tangent to the boundary of the porous medium at points C and D.\nAlong a seepage surface, water emerges from the flow domain, trickling downward to the adjacent body of water.\n\nA seepage surface is defined as the boundary \nwhere water leaves the ground surface and then continues to flow in a thin film along its surface.\nBeing exposed to the atmosphere, the pressure along the seepage face is equal to the atmospheric pressure \n(i.e. capillary pressure $p_{c}=0$). \n\nThe geometry of the seepage face is known (as it coincides with the boundary of the porous medium), \nexcept for its limit (points C and D in Figure \\ref{fig:bc_flow}) \nwhich is also lying on the (a priori) unknown phreatic surface.\nThe location of this point is, therefore, part of the required solution.\nIn unsteady flow, the location of the upper limit of the seepage face varies with time\nand could be simulated in two ways:\n\\begin{enumerate}\n\\item Using a dynamic boundary condition that switches from a prescribed pressure boundary condition\nto a prescribed flux boundary condition representing the recharge.\n\\item Combining boundary conditions in a hybrid one to represent the transition recharge/seepage \nsurface (e.g. see Fig.~\\ref{fig:seepage_bc}).\n\\end{enumerate}\n\n\\begin{figure}  [h]\n\\begin{center}\n\\includegraphics[scale=0.3]{figs/seepage_bc.pdf}\n\\caption{Seepage face.}\n\\label{fig:seepage_bc}\n\\end{center}\n\\end{figure}\n\nThe state of the first option depends on the pressure inside the computational domain.\nRegarding the second option, this hybrid boundary condition \\citep[based on][]{hamm2000} can be formulated as\n\\begin{equation} \\label{eq:fifth_bc_richard}\n\\begin{array} {lllll}\n  \\bq_l \\cdot \\bn & = & q_{b}(t) & \\qquad \\text{for} \\quad &  p < \\left( \\frac{3}{2} p' + p_{0} \\right), \\\\[0.5ex]\n  \\bq_l \\cdot \\bn & = & \\frac{\\left(  7-2f-f^{2}  \\right)}{8} q_{b}(t) \n                    & \\qquad \\text{for} \\quad &  \\left( \\frac32 p' + p_{0} \\right) \\leq p \\leq \\left( \\frac12 p' + p_{0} \\right), \\\\[1.0ex]\n  \\bq_l \\cdot \\bn & = & I (p - p_{0}) &  \\qquad \\text{for} \\quad & \\left( \\frac{1}{2} p' + p_{0} \\right) < p, \n\\end{array} \n\\end{equation}\nwhere $q_{b}(t)$ is the maximum recharge and $f(p,t)$ is a local variable between $-1$ and $1$ \ndefined as \n\\begin{equation}\n  f(p,t) = 2 \\frac{p'- (p(x_{b},y_{b},z_{b},t) - p_{0}) }{p'},\n\\end{equation}\nwhere $p_{0}$ is a reference pressure (in this particular example case, its value is equal to \nthe atmospheric pressure), and $p'$ is defined as \n\\begin{equation}\n  p' = I^{-1} q_{b}(t).\n\\end{equation}\n\n\n\n\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\\subsection{Thermal Richards Equation}\n%\\label{sec:thermal-richards-equation}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\\subsubsection{Process Model Equations} \n\n%\\begin{equation}\n%  \\frac{\\partial \\theta}{\\partial t} \n%  =\n%  - \\bnabla \\cdot (\\eta_l \\bq_l)\n%  - \\bnabla \\cdot (\\K_g \\bnabla \\big(\\frac{p_v}{p_g}\\big)) + Q,\n%  \\qquad\n%  \\bq_l = -\\frac{\\K k_r}{\\mu} (\\bnabla p - \\rho_l \\bg)\n%\\end{equation}\n\n\n\\clearpage\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Isothermal Richards Equation with Dual Porosity Model}\n\\label{sec:dual-porosity-richards-equation}\n\nDual porosity model is designed to model fluid flows\nwhen the solid contains both pores/matrix and fractures.\n\n\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Assumptions and Applicability} \n\n\nTypically flow in the fracture is much faster that that in the pores/matrix.\nTherefore, \ndual-porosity model assumes that water flow is restricted to the fractures.\nThe pores in the solid material (e.g. rock) \nrepresent immobile pockets that can exchange, retain and store water\nbut do not permit convective flow.\nThis leads to dual-porosity type flow and transport models that partition the liquid\nphase into mobile and immobile regions.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Process Model Equations} \n\nThe Richards equation in the mobile (fracture dominated) region is augmented by the water exchange\nterm $\\Sigma_w$: \n\\begin{subequations}\n\\begin{align}\n  \\frac{\\partial \\theta_f}{\\partial t} \n  &= \n  -\\bnabla \\cdot (\\eta_l \\bq_l) + Q_f - \\Sigma_w, \n  \\\\\n  \\bq_l \n  &= \n  -\\frac{\\K k_r}{\\mu} (\\bnabla p_l - \\rho_l \\bg),\n\\end{align}\n\\end{subequations}\nwhere $\\Sigma_w$ is the transfer rate of water from the matrix to the fracture, \nand $Q_f$ is source or sink term [$\\ukg \\ucdot \\um^{-3} \\ucdot \\us^{-1}$].\nThe equation for water balance in the matrix is\n$$\n  \\frac{\\partial \\theta_m}{\\partial t} \n  = Q_m + \\Sigma_w,\n$$\nwhere and $Q_m$ is source or sink term [$\\ukg \\ucdot \\um^{-3} \\ucdot \\us^{-1}$].\nThe volumetric water contents $\\theta_f$ and $\\theta_m$ are defined as\n$$\n  \\theta_f = \\phi_f\\, \\eta_l\\, s_{lf},\\qquad\n  \\theta_m = \\phi_m\\, \\eta_l\\, s_{lm},\n$$\nwhere saturations $s_{lf}$ and $s_{lm}$ may use different \ncapillary pressure-saturation models.\nThe rate of water transfer from the matrix to the fracture regions $\\Sigma_w$ \nis proportional to the difference in hydraulic heads:\n$$\n  \\Sigma_w = \\alpha_w (h_f - h_m),\n$$\nwhere $\\alpha_w$ is the mass transfer coefficient.\nSince hydraulic heads are needed for both regions, this equation requires\nestimating retention curves for both regions and therefore is nonlinear.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Boundary conditions}\n\\label{sec:flow-boundary-conditions}\n\n\nTo facilitate the discussion on boundary conditions, consider the case of \nflow described in Fig.~\\ref{fig:bc_flow}. \nAlthough the figure represents a two-dimensional flow field, the passage to three dimensions \nis straightforward and requires no further explanations. \n\nIn the dual porosity model one has to specify the boundary conditions for the fracture and the matrix (pores).\nDue to the assumption that the pores do not permit convective flow,\n\\paragraph{the boundary conditions for the matrix} are always zero flux conditions:\n\\begin{equation}\n\\label{eq:BC flux DP matrix}\n  \\bq_m\\cdot \\bn = 0, \\quad \\bx \\in \\Gamma.\n\\end{equation}\n\n\n\n\n\\paragraph{Boundary of prescribed pressure or head for fracture.}\nThis involves the specification of a fixed pressure or hydrostatic head on boundary $\\Gamma_D$.\nFor instance, a boundary of this kind occurs whenever the flow domain is adjacent to a body of open water.\nSegments A-B and E-F in Fig.~\\ref{fig:bc_flow} are examples of a boundary of prescribed potential.\nThe pressure or head boundary conditions are given functions, e.g.\n\\begin{align}\n\\label{eq:BC pressure DP}\n  p_f(\\bx,t) = p_{b}(\\bx,t), \\quad \\bx \\in \\Gamma_D. \n\\end{align}\n\n\\paragraph{Boundary of prescribed flux for fracture.}\nThis involves the specification of the flux normal to the boundary $\\Gamma_N$\n(see segment C-D in Figure \\ref{fig:bc_flow}):\n\\begin{equation}\n\\label{eq:BC flux DP}\n  \\bq_f\\cdot \\bn = q_{b}(\\bx,t), \\quad \\bx \\in \\Gamma_N,\n\\end{equation}\nwhere $q_b$ [$\\um\\ucdot\\us^{-1}$] is the given boundary flux. \nFor infiltration at the top horizontal surface, it equals to the Darcy velocity\nand referred to as the infiltration velocity.\n\n\\paragraph{Semipervious boundary (or mixed boundary condition).}\nThis boundary condition is more complicated than the first two as it involves a case \nin which local conditions within the computational domain influence the flux in or \nout of the domain.\nThis type of boundary occurs when the porous medium domain is in contact with \na body of water continuum (or another porous medium domain, see for instance segments \nA-B and E-F in Fig.~\\ref{fig:bc_flow}), however, a relatively thin semipervious layer \nseparates the two domains:\n\\begin{equation}\n\\label{eq:BC semipervious DP}\n  \\bq_f \\cdot \\bn = I\\, \\left(p (\\bx,t) - p_{b}(\\bx,t) \\right), \\quad \\bx \\in \\Gamma_R.\n\\end{equation}\nwhere $I$ is an impedance and $p_{b}(\\bx,t)$ is the given external pressure.\n\n\\paragraph{Seepage face.}\nAs is shown in Fig.~\\ref{fig:bc_flow} (see segments B-C and D-E), seepage face (or surface) \nis always present when a phreatic surface ends at the down-stream external boundary of flow domain.\nIn this case the phreatic surface is tangent to the boundary of the porous medium at points C and D.\nAlong a seepage surface, water emerges from the flow domain, trickling downward to the adjacent body of water.\n\nA seepage surface is defined as the boundary \nwhere water leaves the ground surface and then continues to flow in a thin film along its surface.\nBeing exposed to the atmosphere, the pressure along the seepage face is equal to the atmospheric pressure \n(i.e. capillary pressure $p_{c}=0$). \n\nThe geometry of the seepage face is known (as it coincides with the boundary of the porous medium), \nexcept for its limit (points C and D in Figure \\ref{fig:bc_flow}) \nwhich is also lying on the (a priori) unknown phreatic surface.\nThe location of this point is, therefore, part of the required solution.\nIn unsteady flow, the location of the upper limit of the seepage face varies with time\nand could be simulated in two ways:\n\\begin{enumerate}\n\\item Using a dynamic boundary condition that switches from a prescribed pressure boundary condition\nto a prescribed flux boundary condition representing the recharge.\n\\item Combining boundary conditions in a hybrid one to represent the transition recharge/seepage \nsurface (e.g. see Fig.~\\ref{fig:seepage_bc}).\n\\end{enumerate}\n\n\nThe state of the first option depends on the pressure inside the computational domain.\nRegarding the second option, this hybrid boundary condition \\citep[based on][]{hamm2000} can be formulated as\n\\begin{equation} \\label{eq:fifth_bc_richard DP}\n\\begin{array} {lllll}\n  \\bq_f \\cdot \\bn & = & q_{b}(t) & \\qquad \\text{for} \\quad &  p < \\left( \\frac{3}{2} p' + p_{0} \\right), \\\\[0.5ex]\n  \\bq_f \\cdot \\bn & = & \\frac{\\left(  7-2f-f^{2}  \\right)}{8} q_{b}(t) \n                    & \\qquad \\text{for} \\quad &  \\left( \\frac32 p' + p_{0} \\right) \\leq p \\leq \\left( \\frac12 p' + p_{0} \\right), \\\\[1.0ex]\n  \\bq_f \\cdot \\bn & = & I (p - p_{0}) &  \\qquad \\text{for} \\quad & \\left( \\frac{1}{2} p' + p_{0} \\right) < p, \n\\end{array} \n\\end{equation}\nwhere $q_{b}(t)$ is the maximum recharge and $f(p,t)$ is a local variable between $-1$ and $1$ \ndefined as \n\\begin{equation}\n  f(p,t) = 2 \\frac{p'- (p(x_{b},y_{b},z_{b},t) - p_{0}) }{p'},\n\\end{equation}\nwhere $p_{0}$ is a reference pressure (in this particular example case, its value is equal to \nthe atmospheric pressure), and $p'$ is defined as \n\\begin{equation}\n  p' = I^{-1} q_{b}(t).\n\\end{equation}\n\n\n\n\n\n\n\n% =========================================================================\n% -------------------------------------------------------------------------\n% Infiltration Processes:\n% -------------------------------------------\n%\n%  This is a good place to outline key objectives of this section.\n%\n% -------------------------------------------------------------------------\n\n\\begin{comment}\n\n\\subsection{Infiltration} \\label{sec:infiltration}\n%\n%~\\todo{This section is called Infiltration but really it \n%       describes the near-surface water balance and recharge. -Freshley}\n\n%\\subsubsection{Overview}\n%\nThe infiltration process models are components of the subsurface fluid migration. \nInfiltration can be an important driving force for contaminant transport, especially in the vadose zone.  \nEngineered subsurface barrier technology seeks to minimize the infiltration\ndriving force for contaminant migration.  \nThere are a number of approaches and models that can be applied to predict infiltration processes. \nThese range from simple storage routing models to the more mechanistic \nRichards equation-based \n\\todo[color=cyan]{GEH: Suggest that we remove ``Richards equation-based'' and simply say ``more mechanistic models'' \nas Richards equation does not account for heat transport.}\nmodels that simulate water flow and heat transport \nin response to meteorological forcing and plant water uptake. \nWithin the complex interaction of physical, hydrologic, and biotic processes \nthat control field-scale infiltration at the site of interest, \nthe ideal model should be capable of assessing the impact\nof infiltration on contaminant transport, \nas well as supporting barrier design and performance assessment.\n\nPredicting infiltration requires consideration of unsaturated flow processes, \nprecipitation, surface runoff, water storage,  \nlateral diversion along sloped layers, and, ultimately, deep percolation ~\\citep{ward_1997,ward_2005}. \n%(Ward and Gee 1997; Ward et al. 2005a). \nAll of these processes occur in response to forcing meteorology \nthat leads to temporal variability in air temperature, relative humidity, wind speed, and barometric\npressure and, in the most sophisticated implementations, \nrequire the solution of coupled equations for mass and energy transport.\n\nA minimum set of processes for modeling the water budget should include:  \n%\n\\begin{align}\nP + I = R_{over} + \\Delta W + D + GD,% + E + T,\n\\end{align}\nwhere \n$P$ is the precipitation, \n$I$ -- irrigation,\n$R_{over}$ -- overland flow (run-off and run-on),\n$D$ -- drainage out of the soil cover (diverted by reduced-permeability layer),\n$GD$ -- ground water recharge (deep percolation past a reduced-permeability layer), and\n$\\Delta W$ -- change in soil water storage.\n%$E$ = evaporation\\\\\n%$T$ = transpiration.\n\n\n\n\\noindent \nEvaporation is defined as the process by which liquid water is\ntransformed into a gaseous state and the subsequent transfer of this\nvapor to the atmosphere.  \nTranspiration is the loss of water from plants through their stomata to the atmosphere.  \nPlants compensate for transpiration losses by taking up water from the soil.\n\nAnother requirement is that the process models must include a full energy balance (nonisothermal) option for\nevapotranspiration processes.  \nWater that does not run off the surface must be available for evaporation from the soil or plant surfaces, \nor infiltration into the soil profile. \nSoil water content must depend on the interactions of precipitation, temperature, vegetation, and albedo changes that vary temporally\n(e.g., diurnally, seasonally, and episodically).  \nSpatially and temporally variable water storage and flux must be available for contaminant transport.\n\n\n\\subsubsection{Process Model Requirements}\n\n\\paragraph{Precipitation. } \nThe treatment of precipitation \n%~\\todo{Why this limitation? - Finsterle} \nmust include all natural sources of moisture that may reach the surface \nin the form of rain, snow, sleet, hail, dew, and fog, and must account for precipitation not available for infiltration. \nThis includes precipitation intercepted by the plant canopy, from which it is evaporated\nor transpired without ever contacting the soil; and sublimation, the direct conversion of water from the solid phase to the vapor phase.  \nThis should also account for the presence of a snow cover that can delay\ninfiltration, reduce evaporation rates, and in the event of rapid snowmelt, lead to surface runoff.\n\n%\\subsubsection{Deterministic}\n\n%\\subsubsection{Stochastic}\n\n\\paragraph{Non-Precipitation Surface Recharge (including leaks).} \nProcess models should account for surface recharge sources (e.g., irrigation water used\nduring construction as a dust control agent and post-construction to\nsupport the establishment of vegetation; water condensing on plant\nsurfaces and falling to the ground once the maximum storage depth in\nthe canopy is exceeded, pipe leaks).  \nThese sources must also be subject to evaporation from soil and plant surfaces with the remainder\nbecoming available for runoff or infiltration.\n\n\n\n\n\n% =========================================================================\n% -------------------------------------------------------------------------\n% Section 3 Data Requirements for Flow\n% -------------------------------------------\n%\n%  Phases, Components, and Variables\n%\n% -------------------------------------------------------------------------\n\n\\subsection{Data Requirements for Flow}\n\n\\subsubsection{Permeability and Porosity}\n\nThe most basic properties of the subsurface, which are required for\nall of the flow models, are permeability and porosity.  Often this\ndata can only be provided by sparsely located well logs and at a\nspatial scale much finer than the scale of the model. As a\nconsequence, techniques of upscaling are required to fill in the\nmissing data and extrapolate to larger scales.\n\nPermeability estimates are available for a large variety of soils and\nrocks. When conceptual (and numerical) models have cells that\nrepresent fractures or faults, field tests (pumping and/or tracer) are\nrequired to determine effective permeabilities. Porosity data is also\navailable for many rock and soil types.\n\n\\subsubsection{Relative Permeability and Capillary Pressure.}\n\nFor both the Richards equation and more general multiphase problems, the\nmodel requires representations of relative permeability and capillary\npressure.  For two-phase systems, relative permeability and capillary\npressure data are widely available for the more common forms such as\nvan Genuchten and Brooks Corey.\n\nWhen a NAPL phase is present and the likelihood of three phases is\nsignificant, much of the relative permeability data available from the\nsoil literature may have only limited applicability and experiments on\nat least core size sample will be necessary.\n\\citet{stone1973estimation} presented a method to estimate three-phase\nrelative permeability that is in common usage in the oil\nindustry. However, when fractures or faults are present, parameters of\nthe relative permeability and capillary pressure models are estimated\nwith field data.  Relative permeabilities often exhibit strong\nhysteretic behavior.  Land's method\n\\citep{land1968calculation,spiteri2006impact} is one approach for\nhandling hysteretic behavior that is relatively simple to implement\nand is commonly used in the oil industry.\n\n Some capillary pressure data is available in the database described\nby \\citet{schaap2001computer}. Capillary models derived using surface\ntension data of pure components \\citep{prausnitz1977properties} are\nused where experimental data is not available.\n\n\\subsubsection{Fluid Characterization}\n\nThe model equations must also be augmented with property data for the\nfluids.  In simple problems we require only estimates of density and\nviscosity for each of the flowing phases.  For more complex problems\nin which we are modeling a multicomponent system, additional data is\nrequired.\n\n\\end{comment}\n\n\n\\begin{comment}\n\\subsubsection{Boundary Conditions and Initial Conditions}\n\nBoundary and initial conditions can take several different forms\ndepending on the application. Dirichlet boundary conditions specify\nthe pressure, temperature, and saturation at the boundary. Neumann\nconditions specify the flux $\\bq$ at the boundary.  Initial conditions\nmay consist of specifying a constant pressure or variable pressure,\ntemperature, and saturation, for example in the form of hydrostatic\nconditions taking into account the change in fluid density.\n\nTypical boundary condition for Richard's equation consist of\ninfiltration (recharge) and constant or time varying pressure\nconditions. More sophisticated conditions such at unit gradient, free\ndrainage, and seepage face are also used.\n\n%\n%  Need to fix this with the BC section.\n% \n\n\\subsubsection{Boundary Conditions and Initial Conditions}\n%------------------------------------------------------------------------------\n%------------------------------------------------------------------------------\n%------------------------------------------------------------------------------\nBoundary conditions for flow are exhaustively detailed in Subsection \\ref{sec:bc_flow}. \nThey and initial conditions can take several different forms depending on the application. \nDirichlet boundary conditions specify the pressure, temperature, and saturation at the boundary. \nNeumann conditions specify the flux $\\bq$ at the boundary. \nInitial conditions may consist of specifying a constant pressure or variable pressure, temperature, and saturation, for example in the form of hydrostatic conditions taking into account the change in fluid density.\n%------------------------------------------------------------------------------\n\\\\\n%------------------------------------------------------------------------------\n% For Richards equations\n%------------------------------------------------------------------------------\nTypical boundary conditions for the Richards equation consist of infiltration (recharge) and constant or time varying pressure conditions, but also to impose a prescribed pressure (i.e. Dirichlet boundary condition) is a valid option. \nMore sophisticated conditions such at unit gradient, free drainage, and seepage face are also used.\n%More sophisticated conditions such at unit gradient and seepage face\n%are also used.  For the component (NAPL) fluids, specified mole\n%fractions and flowrates (sources/sinks) are usual boundary conditions.\n%------------------------------------------------------------------------------\n\\\\\n%------------------------------------------------------------------------------\n% For multiphase flow \n%------------------------------------------------------------------------------\nAs regards the multiphase approach, additional data for the boundary and in initial conditions could be required such as the mass fraction for the {\\textit{j}}th component in the phase $\\alpha$ ($Y_{j \\alpha}$, see equation \\eqref{eq:MultiphaseConservationEquation}).  \n\\end{comment}\n\n\n\n\n\n \n\n\n\n\n\n\n", "meta": {"hexsha": "0d39427dfca0493d836595e2de31ded6ba9dc2c3", "size": 41688, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/theory_guide/flow.tex", "max_stars_repo_name": "fmyuan/amanzi", "max_stars_repo_head_hexsha": "edb7b815ae6c22956c8519acb9d87b92a9915ed4", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": 37, "max_stars_repo_stars_event_min_datetime": "2017-04-26T16:27:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T07:38:57.000Z", "max_issues_repo_path": "doc/theory_guide/flow.tex", "max_issues_repo_name": "fmyuan/amanzi", "max_issues_repo_head_hexsha": "edb7b815ae6c22956c8519acb9d87b92a9915ed4", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": 494, "max_issues_repo_issues_event_min_datetime": "2016-09-14T02:31:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T18:57:05.000Z", "max_forks_repo_path": "doc/theory_guide/flow.tex", "max_forks_repo_name": "fmyuan/amanzi", "max_forks_repo_head_hexsha": "edb7b815ae6c22956c8519acb9d87b92a9915ed4", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": 43, "max_forks_repo_forks_event_min_datetime": "2016-09-26T17:58:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T02:29:59.000Z", "avg_line_length": 42.582226762, "max_line_length": 269, "alphanum_fraction": 0.6930771445, "num_tokens": 10544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.5, "lm_q1q2_score": 0.332705279373407}}
{"text": "\\thispagestyle{empty}\n\\chapter*{Abstract}\n\nMotion planning for legged robots is a challenging problem and remains an open area of research. Particular difficulties arise from effective underactuation, the mechanism complexity, as well as nonlinear and hybrid dynamics.\nA common approach is to decompose this problem into smaller sub-problems that are solved sequentially. Recent research indicates that using a local optimal control solver, namely Differential Dynamic Programming (DDP), produces more efficient motions, with lower forces and impacts.\n\nThis master's thesis contributes in this direction by applying, evaluating and extending DDP-based whole-body trajectory optimization, pursuing three objectives. \nFirst, we develop a method for constraining DDP-like solvers in order to generate inherently balanced motion plans. \nSecond, the proposed motion planning approach is evaluated for quasi-static and dynamic motions in a real-time physics simulation and in real-world experiments on the lightweight and biologically inspired RH5 humanoid robot.\nFinally, the limits of the approach and the system design are examined by solving highly-dynamic movements. \n\n\\vfill\n\\noindent\\textbf{Keywords:} Differential Dynamic Programming, Dynamic Bipedal Walking, Humanoid Robots, Motion Planning, Multi-Contact Optimal Control, Whole-Body Trajectory Optimization\n \n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "d79dd0140c3a73edbe8b3a765742a91163f1c18d", "size": 1375, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/_abstract.tex", "max_stars_repo_name": "julesser/ma-thesis", "max_stars_repo_head_hexsha": "29d00b315f5d502fd1378457be2f64cf74049ca0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-28T08:48:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T08:48:54.000Z", "max_issues_repo_path": "tex/_abstract.tex", "max_issues_repo_name": "julesser/ma-thesis", "max_issues_repo_head_hexsha": "29d00b315f5d502fd1378457be2f64cf74049ca0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-04-18T12:28:21.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-18T12:43:52.000Z", "max_forks_repo_path": "tex/_abstract.tex", "max_forks_repo_name": "julesser/ma-thesis", "max_forks_repo_head_hexsha": "29d00b315f5d502fd1378457be2f64cf74049ca0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-26T14:30:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-26T14:30:37.000Z", "avg_line_length": 52.8846153846, "max_line_length": 282, "alphanum_fraction": 0.824, "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.5, "lm_q1q2_score": 0.332705279373407}}
{"text": "\\chapter{QDPT vs DPT with increasing coupling modes}\n\n\\begin{figure}[h!]\n\\includegraphics[scale=0.9, center]{Chapter4/figs/qdpt_err}\n\\caption{(QDPT - DPT) deviation with differing number of neighbouring modes being allowed to couple. From top, $\\mode{0}{77}$ is made to couple with two, four, six, and eight closest $\\Delta l=2$ neighbours (by frequency) as listed in table \\ref{tab:mode_list}. The trend shows large deviations from DPT frequencies in modes placed at either extreme regardless of how many modes couple while QDPT-DPT departure in the inner modes stay the same. This hints at QDPT frequencies obtained for the extremal modes being artefacts of the calculation and hence being unreliable.}\n\\label{fig:DPT_err} \n\\end{figure}", "meta": {"hexsha": "203b91b9acb7c83ae4d4ecaa015643c8722e499e", "size": 738, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Appendix2/appendix2.tex", "max_stars_repo_name": "tuneerch/masters_thesis", "max_stars_repo_head_hexsha": "487646d71dc5f1f2bfbb8e29ee4878d14825c344", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Appendix2/appendix2.tex", "max_issues_repo_name": "tuneerch/masters_thesis", "max_issues_repo_head_hexsha": "487646d71dc5f1f2bfbb8e29ee4878d14825c344", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Appendix2/appendix2.tex", "max_forks_repo_name": "tuneerch/masters_thesis", "max_forks_repo_head_hexsha": "487646d71dc5f1f2bfbb8e29ee4878d14825c344", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 105.4285714286, "max_line_length": 571, "alphanum_fraction": 0.7859078591, "num_tokens": 188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6261241772283035, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3326030318396058}}
{"text": "\\chapter{Effect of measurement uncertainty}\n\\label{cha:error}\n% **************************** Define Graphics Path **************************\n\\ifpdf\n    \\graphicspath{{Chapter4/Figs/Raster/}{Chapter4/Figs/PDF/}{Chapter4/Figs/}}\n\\else\n    \\graphicspath{{Chapter4/Figs/Vector/}{Chapter4/Figs/}}\n\\fi\n\n% **************************** Chapter Abstract ******************************\n\\leftskip=1cm\n\\noindent\n\\emph{Observations are inevitably contaminated with measurement uncertainty, which is a predominant source of uncertainty in some cases. In reliability analysis, probabilistic models are typically fitted to measurements without considering this uncertainty. Hence, this chapter intends to explore the effect of this simplification on structural reliability and to provide recommendations on its treatment. Statistical and interval-based approaches are used to quantify and to propagate measurement uncertainty. They are critically compared by analyzing ground snow measurements, which are often affected by large measurement uncertainty. It is propagated through the mechanical model of a generic structure to investigate its effect on reliability. \n%Parametric studies facilitate to analyze the effect of key parameters, such as measurement uncertainty, coefficient of variation of ground snow load, and distribution type. The interval analysis is performed as a hybrid interval-probabilistic analysis. Measurements are represented as intervals and probabilistic model is then fitted to them. Thus, snow parameters and the reliability index are also interval variables; other random variables are described by standard probabilistic distributions. Implementation of the statistical approach is based on the frequentist paradigm where the contamination mechanism is expressed in terms of random variables. This approach allows decoupling measurement uncertainty from a variable of interest.\nThe results indicate that measurement uncertainty may lead to significant (order of magnitude) underestimation of failure probability and should be taken into account in reliability analysis. \n%If more information than interval endpoints is available, a statistical approach is recommended; otherwise the interval representation should be used.\nRanges of the key parameters are identified where measurement uncertainty should be considered. For practical applications, the lower interval bound and predictive reliability index are recommended as point estimates using interval and statistical analysis, respectively. The point estimates should be accompanied by uncertainty intervals, which convey valuable information about the credibility of results. \n%Although general recommendations are given, treatment of measurement uncertainty should be handled on a case-specific basis.\n}\n\n\\leftskip=0pt\\rightskip=0pt\n\n%****************************************************************************************\n%****************************************************************************************\n\\section{Problem statement and the state of the art}\n\nModels accounting for all uncertainties are of a considerable interest in structural reliability since these are the bases of design specifications, hence impacting the building and structure stocks of large regions. Snow is particularly important for light-weight structures for which it is typically the governing action. To our knowledge, the effect of snow measurement uncertainty on structural reliability has not yet been studied and other probabilistic models are treated similarly in civil engineering. For instance, neither the joint European research on snow actions \\citep{Sanpaolesi1998} or the JCSS Probabilistic Model Code \\citep{JCSS_basis} provides any information on the treatment of measurement uncertainty and its effect. Therefore, the aim of this chapter is to explore the effect of this simplification on structural reliability and to provide recommendations on its treatment.\n\nObservations are inevitably contaminated with measurement uncertainty (MU), which is a predominant source of uncertainty in some cases. Uncertainty is understood here as the lack of knowledge (epistemic) and natural variability (aleatory)\\footnote{This division is subjective as conditioned on the selected ``model universe''.}  not including known systematic error, which are assumed to be adjusted. In reliability analysis, probabilistic models are typically fitted to measurements without considering their uncertainty. This is the case for snow measurements where often only the snow depth is measured and the applied techniques makes the derived loads highly uncertain, for example, the uncertainty range can reach 50\\% of the measured depth\\footnote{Based on a personal correspondence with a meteorologist.}. \n\nThe World Meteorological Organization conducted a comprehensive comparative study on the then available solid precipitation measurement techniques and experimentally confirmed that measurements should be adjusted for wetting loss, evaporation loss, and wind induced undercatch \\citep{Goodison1998}. They found that the snow catch ratio of the four most widely used gauges ranges from 20\\% to 70\\% at 6 m/s wind speed. Even for automated systems, measurement error in solid precipitation can vary from 20\\% to 50\\% due to undercatch in windy conditions \\citep{Rasmussen2012}. Although these mainly contribute to systematic error they indicate uncertainties in snow measurements as these errors cannot be exactly corrected. For instance coefficient of determination ($R^2$) values vary from 0.40 to 0.80 for the fitted wind correction equations at certain sites; these are associated with about 10\\% standard error in catchment ratio. Additional uncertainty may be introduced if no site specific auxiliary data, e.g. wind speed measurements, are available \\citep{Goodison1998}. These issues are not limited to snow measurements but valid for all evidence based models -- that is for every model -- although their importance may vary.\n\n%****************************************************************************************\n%****************************************************************************************\n\\section{Solution strategy}\n%*****************************************************************************************\n\\subsection{Adopted approaches}\n\nWe assume that measurements are corrected for known systematic errors. Additionally, the following model is assumed to describe the connection between observed ($Y$) and real, true, physical ($X$) values, i.e. the variable of interest:\n\\begin{equation}\n\\label{eq:ro_link}\n\t\\mathrm{(true, real\\footnotemark)} X \\xrightarrow[]{h(X,E)} Y \\mathrm{(observed)}.\n\\end{equation}\n\\footnotetext{Herein we tacitly assume the existence of some objective reality independent of the observer.}\nThe $h(X, E)$ function represents the mathematical relationship between the true and observed random variables referred hereinafter as reality-observation link. $E$ covers the unknown processes contributing to measurement uncertainty. The recommended probabilistic models -- typically distributions -- in the literature are almost exclusively given for the true variable and not for the observed, potentially contaminated one. Possible reasons for this are that:\n\\begin{itemize}\n\t\\item The contamination is commonly site- and measuring technique-dependent, thus no general recommendations can be given for the distribution of $Y$.\n\t\\item The model type is often selected based on theoretical arguments considering the physical phenomena generating $X$, for example Normal distribution if $X$ is the result of summation; Lognormal if $X$ is the product of random variables; extreme value distribution if $X$ is related to extremes.\n\t\\item Structural reliability ultimately depends on $X$ and not on $Y$, although we are limited to access only $Y$.\n\\end{itemize}\n\nThe last point is especially important since structures are subjected to actions coming from $X$ and not from $Y$; the latter is affected by our ignorance or inability to make accurate measurements (epistemic uncertainty). In a broader sense this also applies for $X$, but for now we remain in the commonly accepted model universe of engineering and treat $X$ as a random variable. If the distribution type of $X$ is known or agreed, then the reality-observation link uniquely determines the distribution of $Y$. Hence, if any measurement uncertainty is present, its distribution type almost certainly differs from the distribution of $X$. This is prevalently neglected while fitting distributions in civil engineering -- $Y$ is assumed to be distributed as $X$. This simplification is acceptable in some practical cases. This method is termed hereinafter as Approach~1 while it is referred to as Approach~2 when the difference between distributions is appreciated:\n\\begin{description}\n\t\\item[Approach~1] Use the probabilistic model of true random variable ($X$) and treat the observations -- contaminated with measurement uncertainty -- ($\\mathbf{y}$) as the realizations of this model: $\\mathbf{y} \\sim X$.\n\t\\item[Approach~2] Differentiate between the distribution of true and observed random variables. Within this, the following two sub-approaches are considered:\n\t\\begin{description}\n\t\t\\item[Approach~2a] Representation of measurement uncertainty with intervals at the level of observations and propagating them to the derived parameters via interval analysis. As interval representation by nature contains no information about the reality-observation link, the decontamination of observations is not possible.\n\t\t\\item[Approach~2b] Representation of measurement uncertainty with a probability distribution. Use a mathematical model ($h(X, E)$) to describe the connection between measurement uncertainty ($E$), true phenomenon ($X$), and observed phenomenon ($Y$). Based on this model and on observations ($\\mathbf{y}$), infer the parameters of the true random variable ($X$). These issues are referred to as \\textit{measurement error problems} in the literature \\citep{Kondlo2010}.\n\t\\end{description}\n\\end{description}\n\n\\noindent Additional assumptions for all considered approaches:\n\\begin{itemize}\n\t\\item ${\\mathbf{y}} = \\left\\{ {{y_1},{y_2},...,{y_n}} \\right\\}$ and ${\\mathbf{x}} = \\left\\{ {{x_1},{x_2},...,{x_n}} \\right\\}$ each are independent, identically distributed realizations; $\\mathbf{y}$ is contaminated with measurement uncertainty.\n\t\\item The realizations of the true phenomenon ($\\mathbf{x}$) and measurement uncertainty ($\\boldsymbol{\\epsilon}$) are mutually independent.\n\t\\item The true phenomenon ($X$) follows arbitrary, but known distribution type.\n\t\\item Only for Approach~2b: the measurement uncertainty ($E$) follows arbitrary, but known distribution type, and the reality-observation link is also known.\n\\end{itemize}\n\n%Fig 1\n\n%****************************************************************************************\n%****************************************************************************************\n\\subsection{Uncertainty representation and propagation}\n\\label{sec:uncertainty_rep_prop}\n\n%*****************************************************************************************\n\\subsubsection{Interval analysis}\n\nInterval representation is one possible approach to quantify uncertainty in an observed variable: the width of the interval expresses our uncertainty (Figure \\ref{fig:obs_with_interval}). In this concept the true value is certainly within the interval but we know nothing about how likely it takes a particular value from that. In other words no probability distribution function is assumed over the interval, thus it expresses greater ignorance than probability distributions can \\citep{Huber2010}.\nThe basic objective of interval analysis is to propagate the interval uncertainty of input variables to the outputs. Its main challenge is to calculate the interval bounds without overestimating them. This typically occurs if floating point computations are simply replaced by intervals and caused by interval dependency \\citep{Moore2009}. Since the operators are typically not known explicitly and are non-monotonic, special algorithms are needed to obtain sufficiently narrow approximate interval bounds.\nInterval analysis is traditionally used to model floating point truncation error in numerical computations; however, it is also successfully applied to various civil engineering issues, for instance, reliability of structures \\citep{Qiu2008} and systems \\citep{Qiu2007}. \\citet{Rao2015} analyzed the effect of incorrect fitting on trusses and frames using mixed interval finite element formulation, using intervals to model fabrication errors. \\citet{Muhanna2015} demonstrated the feasibility of non-linear interval finite element analysis for beam-column structures. In their study geometric, material and load uncertainties are modeled with intervals.\nIn this study the general definition of interval variables is used and constrained numerical optimization is applied to find the interval endpoints. This is motivated by the readily available optimization algorithms, and its feasibility due to the analyzed simple, computationally cheap examples. For computationally demanding models more efficient algorithms are available \\citep{Zhang2010, Alibrandi2015, Muhanna2015}.\nIntervals in this study are defined by midpoint and radius ($\\epsilon_\\mathrm{r}$), the midpoint is taken as the observed value, $y_i$, see Figure \\ref{fig:obs_with_interval}. In this approach, the true value is assumed to be certainly within the interval given the modeling assumptions are valid.\n\\begin{figure}[htbp!] \n\t\\centering    \n\t\\includegraphics[]{obs_with_interval.pdf}\n\t\\includegraphics[]{MU_interval.pdf}\n\t\\caption{Interval representation of measurement uncertainty (black) on a sorted random sample (red). The sample is generated from $Q_1$ with properties given in Table \\ref{tab:prob_models_mu} and $CV_{Q_1} = 0.2$.}\n\t\\label{fig:obs_with_interval}\n\\end{figure}\n\n%*****************************************************************************************\n\\subsubsection{Statistical analysis}\nAn alternative approach to represent measurement uncertainty is statistical by means of probability distributions. The likelihood function depends on the reality-observation link (Eq.\\ref{eq:ro_link}). This connection is also uncertain, but for simplicity, known relationship is assumed here and a possible treatment of this uncertainty is discussed in Section \\ref{sec:discussion_mu}. Algebra of random variables can be used to obtain the likelihood function reflecting the distribution of involved random variables and the reality-observation link:\n\\begin{equation}\n\\label{eq:mu_like}\n\tL\\left( {{{\\boldsymbol{\\theta }}_X},{{\\boldsymbol{\\theta }}_E}|{\\mathbf{x}},{\\boldsymbol{\\epsilon }}} \\right) = \\prod\\limits_{i = 1}^n {p\\left( {h({x_i},{\\epsilon _i})|{{\\boldsymbol{\\theta }}_X},{{\\boldsymbol{\\theta }}_E}} \\right)}\n\\end{equation}\nwhere ${\\boldsymbol{\\theta }}_X$ and ${\\boldsymbol{\\theta }}_E$ are the parameters of true and measurement uncertainty random variables, respectively.\nIn Approach~1, this means no additional complication because the observations are assumed to be distributed as the true random variable since the reality-observation link is neglected. However, in Approach~2b the likelihood function should be constructed to remove the effect of measurement uncertainty ($E$) from the variable of interest ($X$).\nThe \\textit{measurement error problem} arises in many areas where only the contaminated values are attainable to the observer but the interest lays in the inference of true, uncontaminated values. Among others, these areas include astronomy, econometrics, biometrics, medical statistics, and image reconstruction \\citep{Stefanski2000, Koen2009, Meister2009}. A straightforward solution is to construct the likelihood function (Eq.\\ref{eq:mu_like}) and to infer the parameters of the variable of interest ($X$) by a selected method. To our knowledge this approach has not been applied in civil engineering yet.\nMaximum likelihood method is used herein to infer the parameters in the statistical formulation of the measurement uncertainty problem.\nAdditive and multiplicative reality-observation links are considered. For the additive relationship: $Y = X + E$, the density function of the sum of two independent, continuous random variables is obtained by convolution:\n\\begin{equation}\n\\label{eq:conv}\n\t{f_Y}\\left( y \\right) = \\left( {{f_X} * {f_E}} \\right)\\left( y \\right) = \\int\\limits_{ - \\infty }^\\infty  {{f_X}\\left( {y - x} \\right)}  \\cdot {f_E}\\left( x \\right) \\cdot {\\mathrm{d}}x.\n\\end{equation}\nHere, for convenience the $p(.)$ notation of density functions is replaced with one that identifies the function elsewhere than in the argument, $f_X(x) \\equiv p(x)$.\nThe integral can be efficiently solved by utilizing Fourier transformation since afterwards it reduces to a point-wise multiplication. Here, the fast-Fourier transformation is used to accomplish this task. For the multiplicative relationship: $Y = X \\cdot E$, the density function of the product of two independent, continuous random variables is obtained by computing the following integral:\n\\begin{equation}\n\\label{eq:prod}\n\t{f_Y}\\left( y \\right) = \\int\\limits_{ - \\infty }^\\infty  {{f_X}\\left( x \\right)}  \\cdot {f_E}\\left( {\\frac{y}{x}} \\right) \\cdot \\frac{1}{{\\left| x \\right|}} \\cdot {\\mathrm{d}}x.\n\\end{equation}\nThis can be efficiently solved by Mellin transformation but here the integral is directly calculated due to the small computational burden.\nSampling variability (parameter estimation uncertainty) is accounted for by using the predictive reliability index, $\\tilde \\beta$ \\citep{Kiureghian1989}:\n\\begin{equation}\n\\label{eq:predi_beta}\n\t \\tilde \\beta  = \\frac{{{{\\mathrm{mean}}_B}}}{{\\sqrt {1 + {{\\mathrm{std}}_B}^2} }} \\approx \\frac{{{\\mathrm{median}_B}}}{{\\sqrt {1 + {{\\left( {1.483 \\cdot {{\\mathrm{mad}}_B}} \\right)}^2}} }}\n\\end{equation}\nwhere $B$ is the posterior reliability index, std and mad are the standard deviation and median absolute deviation of $B$, respectively. The formulation with median and mad are used in this chapter, as that is more robust to outliers. Eq.\\ref{eq:predi_beta} is an approximation as it is valid only for Normal distributed $B$. Additionally, the statistics are estimated from repeated analyses, and no Bayesian formulation of the reliability problem is used, even though that was used to derive the formula. For this study it is deemed sufficiently accurate to indicate tendencies and to identify critical cases.\n\\begin{figure}[htbp!] \n\t\\centering    \n\t\\includegraphics[]{obs_with_prob_error.pdf}\n\t\\includegraphics[]{MU_prob_distr.pdf}\n\t\\caption{Illustration of probability distribution representation of measurement uncertainty (black) on a sorted random sample (red). The sample is generated from $Q_1$ with properties given in Table \\ref{tab:prob_models_mu} and $CV_{Q_1} = 0.2$.}\n\t\\label{fig:obs_with_prob_error}\n\\end{figure}\n\n%****************************************************************************************\n%****************************************************************************************\n\\section{Example: reliability of a generic structure}\n\n%*****************************************************************************************\n\\subsection{Model description}\nThe reliability of a simple structural member is analyzed using a generic limit state function:\n\\begin{equation}\n\t g(\\mathbf{X}) = R - \\left( {G + {Q_{50}}} \\right).\n\t %({\\mathbf{X}})\n\\end{equation}\n\nIt represents a structure subjected to permanent ($G$) and variable ($Q_{50}$) actions, where the subscript 50 indicates 50-year reference period (common design working life). The probabilistic model of involved random variables are based on the recommendations of \\citep{JCSS_basis} and summarized in Table \\ref{tab:prob_models_mu}. For simplicity only the variable action is assumed to be affected by measurement uncertainty; it could be easily extended to more variables. Coefficient of variations 0.2, 0.4 for $Q_1$ represent annual snow maxima of mountains, highlands, while 0.6 characterizes lowlands in the Carpathian Region. The Lognormal model for snow maxima is typically adopted in the USA \\citep{ASCE2010}, while the Gumbel model is widespread in Europe \\citep{Sanpaolesi1998, JCSS_load}. The Normal and Gumbel distributions are light-tailed while the Lognormal is heavy-tailed. The adopted distributions and parameter ranges cover also other variable actions such as wind and thermal actions, thus the results can be readily generalized.\n\nThe annual maxima are assumed to be independent:\n\\begin{equation}\n\\label{eq:gfun_mu}\n\t{F_{50}}\\left( q \\right) = {F_1}{\\left( q \\right)^{50}}\n\\end{equation}\nwhere $F(.)$ is the cumulative distribution function.\n\n\\begin{table}[htbp!]\n\\caption{Probabilistic models.}\n\\centering\n\\label{tab:prob_models_mu}\n\\small\n\t\\begin{threeparttable}\n    \\begin{tabular}{llll}\n    \\toprule\n    Variable name (symbol)  & Distribution & Mean & CV \\\\\n    \\midrule\n    \\rowcolor{lightgrey} Resistance ($R$)  & Lognormal & \\tnote{*} & 0.10  \\\\\n    Permanent action ($G$) & Normal &  8  & 0.10 \\\\\n    \\rowcolor{lightgrey} Variable action ($Q_1$)\\tnote{\\textdagger}  & Normal, Lognormal, Gumbel & 10 & $[0.20, 0.40, 0.60]$ \\\\\n    \\bottomrule\n    \\end{tabular}\n    \\begin{tablenotes}\n    \t\\item[*] set to reach $\\beta_\\mathrm{target} = 3.8$ for each combination of inputs.\n\t    \\item[\\textdagger] the specified parameters are used to generate 50-element sample and the parameters of the model used in reliability analysis are inferred from it.  \n   \t\\end{tablenotes}\n   \t\\end{threeparttable}\n\\end{table}\n\n\\subsection{Interval and reliability analysis}\n\\label{subsec:interval_reli}\nTo model the effect of measurement uncertainty, 50 random observations are generated from $Q_1$, these are treated as observed ($Y$) values as the reality-observation link by definition is unknown in interval representation (Figure \\ref{fig:int_alg}). Then intervals are centered at observations and various interval radiuses are considered. Using these interval variables, the distribution of $Q_1$ is fitted by the method of moments, which is a widely used approach in civil engineering \\citep{Sanpaolesi1998} and was proved to be robust e.g. for modeling hydrological extremes \\citep{Madsen1997}. The hybrid interval-probabilistic reliability problem is solved using optimization and first order reliability method (FORM). An outcome of the analysis is an interval reliability index.\n\nThe upper bound of it is irrelevant from safety point of view and the lower bound is recommended for practical applications \\citep{Qiu2007}. This is due to the special nature of intervals and how they represent uncertainty: the real value can be anything within the interval but one cannot assume that all points are equally likely (principle of indifference) at least because the consequence of specific values are not equal. Hence we chose the recommended, careful engineering approach and use the lower endpoint of the reliability index interval as representative value.\n\\begin{figure}[htbp!] \n\t\\centering    \n\t\\includegraphics[]{interval_analysis_algorithm_.pdf}\n\t\\caption{Algorithm of analyzing the effect of interval measurement uncertainty on reliability.}\n\t\\label{fig:int_alg}\n\\end{figure}\n\n\\subsubsection{Full and approximate propagation of interval uncertainty}\nAs measurement uncertainty is expressed at the level of individual observations its full propagation yields to two distinct 50-dimensional constrained optimization problems that can be computationally demanding if each iteration step involves fitting a distribution function and solving a reliability problem. The computational burden can be considerably lessened by a two-step approximate technique where first the distribution parameters are fitted to the interval observations. Then only the interval representation of distribution parameters are used in further reliability analysis. Thus, the optimization with reliability analysis is reduced to a two-dimensional search space. Moreover, our experience show that the optimum is at the bounds so as it can be found by considering only the possible permutations of the parameter bounds.\nThe accuracy of full and two-step approximate uncertainty propagations are compared using Gumbel distributed $Q_1$. The results in terms of reliability indices are presented in Figure \\ref{fig:beta_interval_full_approx}. The interval uncertainty is expressed as the ratio of interval radius and mean of annual maxima ($Q_1$). 0-10\\% range is covered and it is assumed that all observations are contaminated with the same radius. For each coefficient of variation the mean of the resistance is set to reach the 3.8 target reliability level. This is performed by considering no measurement uncertainty ($\\epsilon_\\mathrm{r} = 0$) and using the parameters given in Table \\ref{tab:prob_models_mu}, thus sampling variability has no effect. The calculated upper and lower reliability index endpoints are presented in the plots with solid and dashed lines for two-step and full propagations, respectively. Figure \\ref{fig:beta_interval_full_approx} shows also the reliability index obtained by Approach~1. This is illustrated with a dotted line and is not affected by the assumed measurement uncertainty interval.\n\\begin{figure}[htbp!] \n\t\\centering    \n\t\\includegraphics[]{beta_interval_full_approx.pdf}\n\t\\caption{Reliability index intervals as the function of normalized measurement uncertainty radius ($\\epsilon_\\mathrm{r}/\\mu_{Q_1}$) with full and approximate propagation of interval uncertainty.}\n\t\\label{fig:beta_interval_full_approx}\n\\end{figure}\n\nThe plots show that the approximate technique slightly overestimates the accurate (full) reliability intervals, the largest difference is observed for $CV_{Q_1} = 0.2$ with large measurement uncertainty. Since in general the overestimation of the approximate technique is small, it is used in all further analysis. The sensitivity factor of the 50-year reference period maxima ($\\alpha_{Q_{50}}$) is also displayed on the plots. It corresponds to a model without uncertainty in measurement and parameters. The decreasing interval range of $\\beta$ with increasing $CV_\\mathrm{Q1}$ is explained by the decreasing contribution of interval uncertainty to the full uncertainty of $Q_1$, i.e. aleatory uncertainty becomes dominating. Figure \\ref{fig:explain_decr_beta_int} illustrates this shrinkage of uncertainty interval by comparing the transformed cumulative distribution functions with different coefficient of variations. The plots correspond to 50 particular random realizations; the same pattern is observed for other sets of random realizations.\n\\begin{figure}[htbp!] \n\t\\centering    \n\t\\includegraphics[]{explain_decr_beta_int.pdf}\n\t\\caption{Illustration of the shrinkage of uncertainty interval with increasing coefficient of variation but constant measurement uncertainty interval.}\n\t\\label{fig:explain_decr_beta_int}\n\\end{figure}\n\n\\subsubsection{Effect on reliability index and required resistance}\nEq.\\ref{eq:gfun_mu} is solved for Normal, Lognormal and Gumbel distributed variable action ($Q_1$) using the two-step approximation technique. The results are summarized in Figure \\ref{fig:beta_interval_small_multiples}; they have the same rationale as is given for Figure \\ref{fig:beta_interval_full_approx}. The light gray lines show the opening reliability interval with increasing measurement uncertainty for 20 random samples, each with 50 realizations. These are indicative of the effect of sampling variability: in this case this is entirely parameter estimation uncertainty due to the finite sample size. The results show that sampling variability -- with 50 realizations, which is typical for maxima model of climatic actions -- has significant effect on reliability. It is dominating over measurement uncertainty for small interval radiuses and comparable for larger values. The thick black lines are the median of the 20 sample sets. The reliability index without considering measurement uncertainty can be seen at the common starting point of the lower and upper bound lines. The difference of this value and the lower bound is of interest here as it indicates the extent of the non-conservative neglect of measurement uncertainty. Based on our experience, the difference is deemed significant if it is larger than 0.5. This level is indicated by a dashed horizontal line while the significant range with a red half line. With the selected target reliability level, this corresponds to more than six-fold increase in failure probability.\n\\begin{figure}[htbp!] \n\t\\centering    \n\t\\includegraphics[]{beta_interval_small_multiples.pdf}\n\t\\caption{Reliability index intervals as the function of the normalized measurement uncertainty radius ($\\epsilon_\\mathrm{r}/\\mu_{Q_1}$). The gray lines represent 20 random samples, indicating sampling variability. The black lines are the median lower and upper interval endpoints of the reliability index. The red half line indicates the range where the lower endpoint of the reliability interval is significantly lower ($>0.5$) than the reliability calculated without measurement uncertainty ($\\epsilon_\\mathrm{r} = 0$).}\n\t\\label{fig:beta_interval_small_multiples}\n\\end{figure}\n\nThe results suggest that moderate $\\pm 4\\%$ measurement uncertainty can lead to significant reduction of reliability level for mountains and highlands represented by $CV_{Q_1} = 0.2-0.4$. For the largest considered value of $CV_{Q_1} = 0.6$, the Gumbel model does not reach the limiting value. This indicates that for lowlands even a quite large $\\pm 10\\%$ measurement uncertainty has no practically significant effect. The reliability interval ranges indicate that even a small $\\pm 2\\%$ measurement uncertainty can lead to an order of magnitude uncertainty in the failure probability, see for instance the Lognormal distribution with $CV_{Q_1} = 0.2$. For larger measurement uncertainties, the width of the reliability intervals can be larger than 2.0; the widths are quite considerable for large $CV_{Q_1} = 0.6$ models too.\nMeasurement uncertainty thus seems to have a marked effect on structural reliability. The practical question then arises: what are its implications on design and how it should be accounted for? To examine this, we calculated the mean resistance ($\\mu_R$) required to reach the target reliability with the lower bound of the reliability interval (Approach~2a). Then this value is compared to the $\\mu_R$ required to reach the target reliability without explicit consideration of measurement uncertainty (Approach~1). The ratios of the mean values (with interval MU/without explicit MU) are illustrated in Figure \\ref{fig:dspt_ratio_small_multiples}. These indicate how large adjustment might be needed in representative resistance values to meet target reliability in the presence of measurement uncertainty. The plots are structured and have the same rationale as Figure \\ref{fig:beta_interval_small_multiples}. Based on our expertise, the ratio is deemed practically significant if it is larger than 1.1. This level is indicated by a dashed horizontal line while the significant range with a red half line. The small effect of sampling variability for Normal distribution is likely due to the small sensitivity factor of $Q_{50}$. On the contrary, sampling variability is quite considerable for Lognormal distribution. The selected threshold is reached for all distributions. The Lognormal model shows opposite trend, this might be attributed to its heavy tail. For this distribution the 1.1 threshold is reached at about 4\\% normalized radius and the ratio can be over 1.4 for larger radiuses, which is a huge potential adjustment. The Gumbel distribution illustrates decreasing ratio with increasing coefficient of variation. For $CV_{Q_1} = 0.2$ (mountains), moderate $\\pm 4\\%$ measurement uncertainty can lead to significant $\\mu_R$ ratio. For lowlands ($CV_{Q_1} = 0.6$), the ratio is over the selected threshold only for excessive measurement uncertainty $\\pm 9\\%$, which suggests that measurement uncertainty can be neglected for large values of $CV_{Q_1}$.\n\\begin{figure}[htbp!] \n\t\\centering    \n\t\\includegraphics[]{dspt_ratio_small_multiples.pdf}\n\t\\caption{Mean resistance ($\\mu_R$) ratio for the variable action with and without measurement uncertainty as the function of the normalized measurement uncertainty radius ($\\epsilon_\\mathrm{r}/\\mu_{Q_1}$). The red half line indicates the significant range where the ratio is larger than 1.1.}\n\t\\label{fig:dspt_ratio_small_multiples}\n\\end{figure}\n\n\\subsection{Statistical and reliability analysis}\nThis section presents the statistical approach to quantify and propagate measurement uncertainty (Approach~2b). To model the effect of measurement uncertainty, 50 random observations are generated from $Q_1$ and treated as true ($X$) values. Then by using the assumed reality-observation link they are contaminated with measurement uncertainty. This is generated from a known, independent distribution ($E$). The algorithm is outlined in Figure \\ref{fig:stat_alg}. Additive and multiplicative reality-observation links are assumed and the measurement uncertainty is taken as normally distributed with zero mean (unbiased). After the contamination of data, the information about the parameters of the underlying generating models -- with the exception of the zero mean of measurement uncertainty -- is disregarded and the maximum likelihood method is applied to decouple true values from measurement uncertainty. Finally, the model of decontaminated observations is used in reliability analysis. The sampling variability is again indicated by 20 samples and taken into account in an approximate manner through the predictive reliability index (Eq.\\ref{eq:predi_beta}). The median and mean absolute deviation are calculated.\n\\begin{figure}[htbp!] \n\t\\centering    \n\t\\includegraphics[]{statistical_analysis_algorithm_.pdf}\n\t\\caption{Algorithm of analyzing the effect of measurement uncertainty on reliability using statistical technique.}\n\t\\label{fig:stat_alg}\n\\end{figure}\n\n\\subsubsection{Decontamination of observations}\nTo illustrate the technique and the effect of decontamination, random realizations are generated from Gumbel distribution -- with parameters given in Table \\ref{tab:prob_models_mu} -- and contaminated with measurement uncertainty (Figure \\ref{fig:Gumbel_additive_me_smallm}). First, additive reality-observation relationship is assumed and Approach~1 and Approach~2b are used to infer the model parameters. The maximum likelihood method is used to obtain point estimates and the delta method is applied to construct $90\\%$ confidence intervals to illustrate parameter estimation uncertainty \\citep{Coles2001}.\\mynote{ref to chapter 2!} The results for three cases of Gumbel distribution and two cases of measurement uncertainty with varying standard deviation are discussed only. The realizations and the fitted models are shown in Figure \\ref{fig:Gumbel_additive_me_smallm}. It comprises return value-return period plots transformed to Gumbel space where the Gumbel distribution appears as a straight line. Though the plots are corresponding to a particular set of realizations, they convey reliably the trends and expected differences: (\\textit{i}) Approach~1 typically overestimates the fractiles thus leading to lower reliability level and being conservative; (\\textit{ii}) the difference between models increases with increasing return period. Due to the small sample size, the difference is affected by large sampling variability.\nThe calculations are repeated with multiplicative measurement uncertainty (Figure \\ref{fig:Gumbel_prod_me_smallm}). The results correspond well with those obtained for the additive format. Furthermore, wider confidence intervals of Approach~2b compared with Approach~1 are observed. This is due to the larger model space where the same sample size allows less certain inference. This effect is less pronounced for the additive model.\nFor both models, Approach~1 is inherently biased since it is not using the correct likelihood function, while Approach~2b asymptotically converges to the true model. Thus, in the long run -- from theoretical point of view -- Approach~2b is better; however, Approach~1 seems to be generally conservative for the considered reality-observation links. This latter aspect is analyzed in more detail in the following section focusing on reliability index as a quantity of practical interest.\n\\begin{figure}[htbp!] \n\t\\centering    \n\t\\includegraphics[]{Gumbel_additive_me_smallm_50_rng23.pdf}\n\t\\caption{Gumbel distributions fitted to random realizations contaminated with additive measurement uncertainty using Approach~1 and Approach~2b. The point estimates (dashed lines) are accompanied by 90\\% confidence intervals (dotted lines).}\n\t\\label{fig:Gumbel_additive_me_smallm}\n\\end{figure}\n\\begin{figure}[htbp!] \n\t\\centering    \n\t\\includegraphics[]{Gumbel_prod_me_smallm_50_rng14.pdf}\n\t\\caption{Gumbel distributions fitted to random realizations contaminated with multiplicative measurement uncertainty using Approach~1 and Approach~2b. The point estimates (dashed lines) are accompanied by 90\\% confidence intervals (dotted lines).}\n\t\\label{fig:Gumbel_prod_me_smallm}\n\\end{figure}\n\n\\subsubsection{Effect on reliability index}\nThe effect of measurement uncertainty on reliability index is analyzed for the additive relationship considering Normal, Lognormal and Gumbel distributed true values and with coefficient of variation ranging from 0.2 to 0.6. The measurement uncertainty has Normal distribution with known zero mean and varying standard deviation. Consistently with the interval analysis in Section \\ref{subsec:interval_reli}, the mean value of the resistance is determined to reach the target reliability without measurement uncertainty and parameter estimation uncertainty. Then the algorithm presented in Figure \\ref{fig:stat_alg} is applied to generate contaminated observations, to decontaminate them, and to calculate the reliability index using the inferred parameters. The calculations are repeated for 20 samples with sample size of 50. The results in terms of reliability indices are shown in Figure \\ref{fig:Normal_lognormal_additive_me_beta_smallm} and in Figure \\ref{fig:Gumbel_additive_me_beta_smallm}. Grey and light blue solid lines are representing the 20 samples, and the corresponding thick solid and dashed lines are the median and predictive reliability indices, respectively. The difference between these latter two lines expresses the effect of parameter estimation uncertainty. For Normal distribution, this effect is small compared to Lognormal and Gumbel for which it is increasing with increasing standard deviation of measurement uncertainty. For Approach~2b it is typically larger than Approach~1 as the larger model space allows less certain inference with the same sample size. In case of Lognormal and Gumbel models, the ratio of the predictive and median failure probabilities can be as large as an order of magnitude or larger. Additionally, the plots show that the reliability index can considerably be overestimated when parameter estimation uncertainty is neglected. The salient large scatter of Approach~2b might be partially attributed to the unstable maximum likelihood estimators for small samples \\citep{Hosking1985, Martins2000}.\n\\begin{figure}[htbp!] \n\t\\centering    \n\t\\includegraphics[]{Normal_additive_me_beta_smallm_666_median.pdf}\n\t\\includegraphics[]{Lognormal_additive_me_beta_smallm_666_median.pdf}\n\t\\caption{Reliability indices as the function of the normalized standard deviation of measurement uncertainty ($\\sigma_{E}/\\mu_{Q_1}$). The thick solid lines are the median of the reliability indices while the thick dashed lines are the approximate predictive reliability indices.}\n\t\\label{fig:Normal_lognormal_additive_me_beta_smallm}\n\\end{figure}\n\nComparing Approach~1 with Approach~2b for Normal and Gumbel distributions, the former approach yields to systematically lower reliability indices. The opposite trend observed for Lognormal distribution might be attributed to its heavy-tail. For Normal distribution, Approach~1 seems to be overly conservative, the median is well below the target reliability level. \nFor all distributions, Approach~1 is reasonably conservative with the exception of Lognormal distribution and coefficient of variation of 0.6. However, even in this case the predictive reliability index corrects the overestimation. Though for Normal distribution it is too conservative, the currently prevalent Approach~1 appears to be safely applicable to measurement uncertainty problems in case of additive reality-observation relationship. Approach~2b is sound from theoretical point of view; however, its median overestimates reliability level, thus the predictive reliability index is to be used to avoid underestimation of failure probability. Its larger parameter estimation uncertainty can lead large reduction in reliability index for small sample sizes.\n\\begin{figure}[htbp!] \n\t\\centering    \n\t\\includegraphics[]{Gumbel_additive_me_beta_smallm_666_median.pdf}\n\t\\caption{Reliability indices as the function of the normalized standard deviation of measurement uncertainty ($\\sigma_{E}/\\mu_{Q_1}$). The thick solid lines are the median of the reliability indices while the thick dashed lines are the approximate predictive reliability indices.}\n\t\\label{fig:Gumbel_additive_me_beta_smallm}\n\\end{figure}\n\n%****************************************************************************************\n%****************************************************************************************\n\\section{Application example: Turbine hall of Paks Nuclear Power Plant}\n\\label{sec:turbine_mu}\n\nThe turbine hall of Paks Nuclear Power Plant is selected to demonstrate the effect of measurement uncertainty on a real life example. The structure is introduced in Annex~\\ref{sec:paks}, here only the essential details, which are required to interpret the results, are provided. The interval approach is used to represent measurement uncertainty and the two-step approximation is applied to propagate interval uncertainty. Annual ground snow maxima related to the location are contaminated with measurement uncertainty, the rest of random variables are represented by probability distributions. The results in terms of reliability indices and failure probabilities are given in Figure~\\ref{fig:interval_beta_turbine_hall}. One year reference period is used for all calculations of the frame.\n\n\\begin{figure}[htbp!] \n\t\\centering    \n\t\\includegraphics[]{interval_beta_turbine_hall.pdf}\n\t\\caption{Reliability index and failure probability intervals as the function of normalized measurement uncertainty radius ($\\epsilon_\\mathrm{r}/\\mu_{Q_1}$). Comparison of Approach~1 and Approach~2a for the turbine hall of Paks Nuclear Power Plant.}\n\t\\label{fig:interval_beta_turbine_hall}\n\\end{figure}\n\nThe widest reliability index interval is 0.2, which is obtained for the largest measurement uncertainty error radius. This small value is in agreement with the trend observed in the previous example (Figure~\\ref{fig:beta_interval_small_multiples}). It is attributed to the large coefficient of variation of annual ground snow load that is dominating over measurement uncertainty. In this example, neglect of measurement uncertainty leads to 70\\% underestimation of failure probability at worst; hence, the effect is negligible.\n\n%****************************************************************************************\n%****************************************************************************************\n\\section{Discussion}\n\\label{sec:discussion_mu}\nOne can distinguish two components of measurement uncertainty: the reality-observation link and the nature of the contamination $E$. The three approaches considered here differ in how they treat these two components. The present prevalent approach (Approach~1) neglects both components, thus entirely ignores the possibility that the real values are greater or smaller than the observed due to measurement uncertainty.\n\nThe interval approach (Approach~2a) expresses full ignorance in respect of reality-observation link and represents measurement uncertainty with intervals. Therefore, no decoupling of true values from measurement uncertainty is possible. Intervals should be used with caution because by definition values outside of the interval are impossible. This assumption is rarely met in civil engineering. Measurement uncertainty is often described on the basis of expert judgment and wide intervals are applied to almost surely capture real, unobserved values.\n\nThe statistical approach (Approach~2b) requires the knowledge of the reality-observation link and represents measurement uncertainty with distribution function. This is the only approach that can decontaminate the observations and can directly infer the variable of interest, true variable. This is important since structural reliability is dependent on the true variable. The statistical and interval analysis based approaches are conceptually different, thus they are only comparable on that level but not quantitatively. Their uncertainty representation is inherently distinct, thus there is no equivalency between interval and distribution based representations.\n\nAdditionally, it must be emphasized that another type of uncertainty – statistical uncertainty in parameter estimation and selection of distribution function – often needs to be taken into account in reliability analysis as it may be even more important as measurement uncertainty investigated here \\citep{RozsasIABSE2015, RozsasESREL2015}. Bayesian paradigm is a natural choice to incorporate this uncertainty, consequently that is recommended for practical applications. For example, in real-life situations, the reality-observation link cannot be established with certainty. Yet, this uncertainty can be captured by using multiple models and averaging them with respect their goodness of describing the data, this can be achieved for example by Bayesian model averaging \\citep{Hoeting1999}.\n\nAlthough this study is limited by the considered distribution types, reality-observation functions, and parameter range, it is believed to cover many practically relevant random variables. The presented approaches and algorithms can be easily used for other distribution types and measurement error structure. An additional limitation of this study is that measurement uncertainty is considered only for the dominant variable action. However, it is anticipated that for other random variables the effect is smaller due to their typically smaller sensitivity factor. Moreover, measurement uncertainty is much smaller for other than climatic actions such as resistance and permanent actions. Furthermore, the effect of sample size should be analyzed in later works. It is believed that the outcomes would be similar for sample sizes ranging from 20 to couple of hundreds, which cover the majority of cases in civil engineering. More data would allow more certain model identification.\n\n%\\section{Application example}\n\n\\section{Summary and conclusions}\nThe current practice in probabilistic engineering treats observed data contaminated with measurement uncertainty as realizations of the true distribution, thus neglecting the contamination mechanism. Statistical and interval-based analyses are thus conducted to investigate the effect of this simplification on structural reliability. Extensive parametric analyses -- based on 50 realizations, which is a typical length of records for climatic actions -- reveal that:\\\\\nIf interval representation of measurement uncertainty is used:\n\\begin{itemize}\n\t\\item Sampling variability (parameter estimation uncertainty) has significant effect on reliability: it is dominant over measurement uncertainty for small interval radiuses and comparable for large radiuses.\n\t\\item For mountains and highlands, moderate $\\pm 4\\%$ measurement uncertainty -- relative to value of an observed variable -- can lead to significant reduction of reliability level. For lowlands, even a large $\\pm 10\\%$ measurement uncertainty has no significant effect. An effect is deemed significant if it yields to greater than six fold increase in failure probability compared with Approach~1 (neglect of measurement uncertainty).\n\t\\item Reliability interval ranges indicate that a small $\\pm 2\\%$ measurement uncertainty can lead to reduction of 0.6 in reliability index. For larger measurement uncertainties, the width of the reliability intervals can be larger than 2.0.\n\t\\item The effect of measurement uncertainty is more pronounced for low variability random variables where its contribution to the total uncertainty increases.\n\t\\item Parameter ranges where Approach~1 often overestimates the reliability index are identified.\n\\end{itemize}\nIf statistical (distribution function) representation of measurement uncertainty is used:\n\\begin{itemize}\n\t\\item It is demonstrated that the statistical approach can be used to decontaminate the observations, thus to access the variable of interest.\n\t\\item The ratio of the predictive and median failure probabilities can be as large as an order of magnitude or larger ($\\sim30$ for Lognormal distribution).\n\t\\item If parameter estimation uncertainty is disregarded, the reliability index can be considerably overestimated.\n\t\\item For all considered distributions with additive measurement uncertainty, Approach~1 is reasonably conservative in most cases.\n\\end{itemize}\n\nPractical recommendations:\n\\begin{itemize}\n\t\\item Figure \\ref{fig:beta_interval_small_multiples} and Figure \\ref{fig:dspt_ratio_small_multiples} can be used to identify cases when Approach~1 significantly overestimates reliability index. In such cases and when no or very limited information on measurement uncertainty is available, then interval analysis could be used, considering the lower bound of the reliability interval.\n\t\\item If the reality-observation link is known then the statistical approach is recommended. For small and moderate sample sizes ($<100$), the predictive reliability index is recommended. For additive measurement uncertainty, Approach~1 is conservative.\n\t\\item For point estimates, such as median, the reliability index should be accompanied by uncertainty intervals to indicate the credibility of results.\n\t\\item For ground snow extremes at lowlands, Approach~1 provides a reasonable approximation, thus the effect of measurement uncertainty can be neglected. Otherwise more advanced analysis is recommended.\n\\end{itemize}\n\nAssessment of measurement uncertainty should be region- and case-specific accounting for measuring techniques, and applied correction equations, thus involvement of meteorologists, analysts or other experts is beneficial. Moreover, the selected approach to propagate measurement uncertainty should always be based on the particular issue in question, acknowledging ``the degree of precision to which the nature of the subject admits''.", "meta": {"hexsha": "da1466f8d574a582932441a06b1e512c70c38489", "size": 51161, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapter4/chapter4.tex", "max_stars_repo_name": "rozsasarpi/Snow-extremes-and-structural-reliability", "max_stars_repo_head_hexsha": "712f826564a71b934f167ecc81da4fd1b3368a77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter4/chapter4.tex", "max_issues_repo_name": "rozsasarpi/Snow-extremes-and-structural-reliability", "max_issues_repo_head_hexsha": "712f826564a71b934f167ecc81da4fd1b3368a77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter4/chapter4.tex", "max_forks_repo_name": "rozsasarpi/Snow-extremes-and-structural-reliability", "max_forks_repo_head_hexsha": "712f826564a71b934f167ecc81da4fd1b3368a77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 157.9043209877, "max_line_length": 2065, "alphanum_fraction": 0.786575712, "num_tokens": 10397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.33260302442763506}}
{"text": "\\chapter{Model's nomenclature}\n\\label{ap:nomen}\n\n\\textit{In this appendix we will report the nomenclature used in Chapter \\ref{ch::model} and in Appendix \\ref{ap:model} for model description.} \\\\\n\n~\\\\\n\n\\begin{longtable}{ r p{11cm} }\n  %\\hline\n  %\\multicolumn{1}{|c|}{\\textbf{Symbol}} & \\multicolumn{1}{c|}{\\textbf{Description}}                                    \\\\~\\\\\n  %\\hline\n  $\\left( x_w, y_w, z_w \\right)$        & Real coordinates of the point in the world reference system.                  \\\\~\\\\   \n  %\\hline\n  $\\left( x_f, y_f, z_f \\right)$        & Projection of the principal point on the laser plane reference system.        \\\\~\\\\ \n  %\\hline\n  $\\left( x_s, y_s, z_s \\right)$        & Point coordinates in the tilted image plane reference system.                 \\\\~\\\\ \n  %\\hline\n  $\\left( x_p, y_p, z_p \\right)$        & Points coordinates in the image plane parallel to the sensor plane.           \\\\~\\\\ \n  %\\hline\n  $\\left( x_p^d, y_p^d \\right)$         & Distorted points coordinates in the image plane parallel to the sensor plane. \\\\~\\\\ \n  %\\hline\n  $\\left( x_c, y_c \\right)$             & Discrete points coordinates in the sensor reference system                    \\\\~\\\\ \n  %\\hline\n  $\\phi$                                & Triangulation angle                                                           \\\\~\\\\ \n  %\\hline\n  $\\alpha$                              & Angle offset in $y$ direction, with respect to $\\phi$                         \\\\~\\\\ \n  %\\hline\n  $\\beta$                               & Angle offset in $x$ direction, with respect to the optical axis               \\\\~\\\\   \n  %\\hline\n  $\\rho$                                & Laser roll angle                                                              \\\\~\\\\ \n  %\\hline\n  $\\gamma$                              & Laser pitch angle                                                             \\\\~\\\\ \n  %\\hline\n  $\\upsilon$                            & Lens rotation in $y$ direction, due to Scheimpflug principle                  \\\\~\\\\ \n  %\\hline\n  $\\chi$                                & Lens rotation in $x$ direction, due to Scheimpflug principle                  \\\\~\\\\ \n  %\\hline\n  $Roll$                                & Rotation along $x$ axis                                                       \\\\~\\\\ \n  %\\hline\n  $Pitch$                               & Rotation along $y$ axis                                                       \\\\~\\\\ \n  %\\hline\n  $Yaw$                                 & Rotation along $z$ axis                                                       \\\\~\\\\ \n  %\\hline\n  \n  %\\caption{Model's nomenclature and descriptions}\n  %\\label{tab:ap-nomen}\n\\end{longtable}\n", "meta": {"hexsha": "67096bf69d8b55cf859c3d7d9e13e531fae98bfe", "size": 2669, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/thesis/src/appendexes/nomen.tex", "max_stars_repo_name": "extoxesses/LaserMat", "max_stars_repo_head_hexsha": "4e893cd56ecea8497918ecafb642b2fbf9a085a2", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-05-12T08:53:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T06:36:55.000Z", "max_issues_repo_path": "report/thesis/src/appendexes/nomen.tex", "max_issues_repo_name": "extoxesses/LaserMat", "max_issues_repo_head_hexsha": "4e893cd56ecea8497918ecafb642b2fbf9a085a2", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/thesis/src/appendexes/nomen.tex", "max_forks_repo_name": "extoxesses/LaserMat", "max_forks_repo_head_hexsha": "4e893cd56ecea8497918ecafb642b2fbf9a085a2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.6041666667, "max_line_length": 146, "alphanum_fraction": 0.4301236418, "num_tokens": 645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.3326030151340085}}
{"text": "\\chapter{Concept}\n\nIn this chapter the concept of transferring \\gls{AutoML} concepts to clustering will be described.\nFor this, it will first be explained how meta-learning and the hyperparameter optimization methods were used to optimize the parameters of a clustering algorithm.\nAfter this, the changes that had to made to the concept to also tackle the problem of algorithm selection  will be explained.\n\n\n\\section{Hyperparameter Optimization for Clustering}\n\n\\begin{itemize}\n    \\item First applied concepts on KMeans.\n    \\item Goal is to predict the number of clusters.\n    \\item For this, analyze which hyperparameter optimization methods are suitable.\n    \\item Also analyze which metrics are suitable for the different methods.\n    \\item So use internal/external metrics for the optimizers.\n    \\item Although external cannot be applied for new unseen datasets since they do not have class labels.\n    \\item But meta-learning can be used to warmstart optimizers.\n    \\item Warmstart means that the optimizers do not start with random models but with models that are suggestes by meta-learning model.\n    \\item For this, offline phase necessary.\n    \\item Assuming in the offline phase the number of clusters is known, it is also possible to use external metrics.\n    \\item Basic architecture shown in \\cref{fig:concept_arch}.\n    \\begin{figure}\n        \\centering\n        \\includegraphics[width=\\textwidth]{graphics/concept_architecture.png}\n        \\caption{General architecture of the concept divided in Online and Offline phase.}\n        \\label{fig:concept_arch}\n    \\end{figure}\n    \\item Offline phase: Train ``meta-model''\n    \\item Use optimizer to get configuration. Run KMeans on them and evaluate resulting according to metric.\n    \\item Then save result to Meta-DB.\n    \\item Also save the evaluation of the dataset together with the \\textit{meta-features}.\n    \\item Meta-DB builds the meta-model.\n    \\item For the meta-model a k-NN classifier with $k=1$ is used.\n    \\item If new dataset has to be clustered in online phase, then extract meta-features (same as in offline phase). \n    \\item Then find the ``nearest'' dataset.\n    This is basically where 1-NN is used to find the nearest dataset based on the $L1$ distance.\n    \\item Input is meta-features of the new dataset and these are used to build the 1-NN and find the nearest dataset.\n    \\item From the nearest dataset it is looked up for which configurations the lowest k deviation was measured in the offline phase.\n    \\item This configurations are then used to \\textit{warmstart} the optimizer, which means the optimizer first evaluates this configurations.\n    \n    \n    \n    \n\\end{itemize}\n \n \n\\section{Algorithm Selection for Clustering}\n\n\\begin{itemize}\n    \\item Basically same as for Hyperparameter Selection.\n    \\item Instead of only using parameters of that one algorithm, the optimizer gets one additional parameter.\n    \\item Additional parameter is name of algorithm.\n    \\item So the optimizer predicts the name of the algorithm and the hyperparameters like done in \\cite{ThorntonAuto-WEKA:Algorithms}.\n    \\item Limited to partitional clustering algorithms.\n    \\item Basically Bayes would also be applicable to other clustering algorithms, but for multi-arm bandit based methods the budget has to be defined somehow.\n    To get a meaningful metric result one needs labels for all data points after each iteration if the budget is the number of iterations or even for time budget.\n    This holds partitional clustering algorithms but not necessarily for other kinds of clustering algorithms.\n    \\item The architecture shown in \\cref{fig:concept_arch} changes in that way that the optimizer does not only gives the k value that should be executed next, but also the algorithm.\n    \\item New architecture can be seen in \\cref{fig:archAlgoSelection}.\n    \\begin{figure}\n        \\centering\n        \\includegraphics[width=\\textwidth]{main/concept_architecture_algo_selection.png}\n        \\caption{General architecture of the concept to also include the algorithm selection.}\n        \\label{fig:archAlgoSelection}\n    \\end{figure}\n    \n\\end{itemize}", "meta": {"hexsha": "03e2f801ebe7a23d07f38fcfd6011884aebe260c", "size": 4143, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "main/concept.tex", "max_stars_repo_name": "tschechlovdev/scientific-thesis-template", "max_stars_repo_head_hexsha": "e898fd0ed3cc15bee2202111a4f7b2b10ca4aa52", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main/concept.tex", "max_issues_repo_name": "tschechlovdev/scientific-thesis-template", "max_issues_repo_head_hexsha": "e898fd0ed3cc15bee2202111a4f7b2b10ca4aa52", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main/concept.tex", "max_forks_repo_name": "tschechlovdev/scientific-thesis-template", "max_forks_repo_head_hexsha": "e898fd0ed3cc15bee2202111a4f7b2b10ca4aa52", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 61.8358208955, "max_line_length": 184, "alphanum_fraction": 0.7603186097, "num_tokens": 891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.33256332010229367}}
{"text": "\\section{ General Framework for Group Deviation Detection\n}\n \\label{Sec:Framework}\nIn the last section, we clearly defined the problem of detecting group deviations in static and dynamic situations.   \n  This section elaborates  upon the general framework and underlying structure for GAD and GCD techniques. Discovering significant group deviations is related to three sub-problems. \n\\begin{enumerate}[1.]\n\\item {\\it Group Structures}:  The definition of groups and the relationship between data instances is important to understand. %  clustering algorithm aggregate data instances into group structures.\n\\item {\\it Statistical Properties}:  \nA variety of statistical properties may characterise group deviations. % For example, a user is able to examine statistical properties of interest such as proportions, location or dependence.\n If statistical properties  are  not adequately quantified then relevant group deviations cannot be identified.\n\\item  {\\it Model Design}: \n The design of GAD and GCD techniques include data inputs,   model assumptions, learning approaches and output information. \n\\end{enumerate}\n\n\n\\subsection{Group Structures}\nWe now highlight examples of different problems associated with group structures.   A group is a collection of two or more related data instances where Tan et al.  \\cite{Tan} state that a data instance is synonymous with terms such as  vector, sample, entity, observation, etc. %Many GAD techniques assume that features from members in a group are independent and identically distributed (iid) where\nMembers in a group can be related by  external information of known group labels such as in topic modelling where Xiong et al. \\cite{FGM} consider a document as a group of  words or a corpus as a group of documents. When group structures are not previously known, clustering algorithm aggregate data instances based on similarity criterion. \n For example, Xiong et al. \\cite{MGM} infer a spatial cluster of galaxies with distances closer than 1 megaparsecs while Wong et al. \\cite{wong-rule} examine a demographic group of patients  based on certain categorical features.  \n%   The interpretation of results relies on initial definition and construction of group structures. \n  \nWhen group structures are unknown a priori,  clustering algorithms are applied. Common procedures minimise the cumulative  distance  between  members in a group to a central reference point. %These algorithms such as $k$-means or  nearest neighbors\n Clustering algorithm  for numerical values  are discussed in Jain \\cite{jain2010} where a group of data instances contains members with similar features based on minimising distance metrics.   \nSteinbach \\cite{steinbach2004} discusses issues with distance-based clustering algorithms as data points become difficult to differentiate in higher dimensions.   More sophisticated techniques have been specifically developed for group  \n%In particular,\n group deviation detection   %techniques infer clusters based on different criterion \n such as:\n\\begin{enumerate}[-]\n\\item Chen et al.  \\cite{GLETS}  apply density-based spatial clustering based on Pearson's correlation and Euclidean distance between values of times series. \n%\\item Chen et al.  \\cite{Chen2014} examine Pearson's correlation and Euclidean distance between values of times series.  \n\\item    Yu et al. \\cite{GLAD} examine individual features as well as pairwise connection data.  %infer groups containing a mixture of social roles for social media applications. \n\\item Soleimani and   Miller \\cite{ATD} infer anomalous clusters of documents based on likelihood probabilities.\n\\item Dai et al. \\cite{ERACD} cluster based on the ranking of feature values. \n\\end{enumerate}\nTherefore there are many procedures for clustering data instances when group structures are previously unknown.\n\n\n\\begin{figure}[h]\n\\centering\n   \\begin{subfigure}{1\\linewidth} \\centering\n     \\includegraphics[width=6cm, height=4cm,trim=5cm 9.5cm 4.5cm 9cm]{FIGURES/ECGa}\n     \\caption{A collective anomaly (red dotted circle) in the ECG reading of a single patient.}\n   \\end{subfigure}\n   \\begin{subfigure}{1\\linewidth} \\centering\n     \\includegraphics[width=6cm,  height=4cm,trim=5cm 9.5cm 4.5cm 8.5cm]{FIGURES/ECG}\n     \\caption{A group anomaly (Patient 3) is observed when comparing several patients.} \n   \\end{subfigure}\n  % \\vspace{-1cm}\n\\caption{ In (a), a collective anomaly is a collection of related data instances that is anomalous with respect to time-dependent observations from  a single patient.   \nIn (b), a group anomaly is a specific example of a collective anomaly where  the entire dataset involves a group of observations from multiple patients. \n } \\label{Fig:ECG}\n\\end{figure}\n%\\vspace{1cm}\n\n\n \n \nIn our thesis, we do not use group anomaly and  collective anomaly interchangeably.  Chandola \\cite{Chandola} defines a collective anomaly  as \"a collection of related data instances that is anomalous with respect to the entire dataset.\" \nA group anomaly is specific example of a collective anomaly where  \nthe entire dataset involves multiple groups. % in the dataset. \nTo differentiate these terms, consider the electrocardiogram (ECG) example from Goldberger et al. \\cite{Goldberger}.  Figure \\ref{Fig:ECG} (a) highlights a collective anomaly (in the dotted red circle) that exhibits an irregular pattern as compared to the  entire dataset (time series of a single patient). For a GAD application,  Figure \\ref{Fig:ECG} (b) illustrates ECG readings from several patients  where  Patient 3 represents a group anomaly as the statistical properties are significantly different.  %however this is also a collective anomaly as the entire dataset can be considered as information from all of the patients.\n A realistic GCD case  would involve a group of patients with ECG readings similar to Figure \\ref{Fig:ECG} (a) where a large-scale phenomena affects all patients around $\\tau=10$. \n \n\n\n\\subsection{Statistical Properties}\n% SP - known vs unknown\n In some cases, a domain expert is interested in particular  statistical properties of groups. Statistical properties are measured and compared for group deviation detection. In terms of point-based and distributed-based group behaviours, point-based group deviations are characterised by a central location while distributed-based group deviations are characterised by statistical properties other than location such as scale, shape or dependence. In practice, group deviations are difficult to detect as a combination of statistical properties may  significantly differ. If a user is able to specify statistical properties of interest, group deviations are more easily detected and interpreted. \n\n Since there are also many ways to quantify statistical properties of groups, we describe common parametric and non-parametric measures for statistical properties in Table \\ref{Tab:Des} where non-parametric measurements are more robust to individual outliers. %Statistical properties in Table \\ref{Tab:Des}, capture group  behaviours  for continuous variables however other metrics are more suitable for discrete or categorical datasets. \n   Given prior knowledge of statistical properties that characterise group deviations for GAD or GCD applications, a suitable method for discriminating groups is easily constructed. However when the nature of significant group deviations in terms of statistical properties is unknown, more   specialised techniques are required.  \n \n \n\t\t\\begin{table}[h]\n%\\renewcommand{\\arraystretch}{1}\n\t\\tabcolsep=0.1cm\n\t\\begin{center}\n   \\scalebox{0.88}{\n\t\\begin{tabular}{lccc  }\n\t\\hline\\\\[-2mm]\n\t\t%\\multirow{ 2}{*}{} & & & \\\\[2mm]\n Statistical & %Function &\n\t Parametric Measures% in $\\boldsymbol \\alpha$ \n\t &  Non-parametric Measures %  in  $\\boldsymbol \\gamma$ \n\t \\\\[-1mm]  Property & & &\n\t \\\\[2mm] \\hline\\\\[-2mm]\n\t\t\\multirow{ 2}{*}{Location } & %\t\\multirow{ 2}{*}{$h_1$ }&\n\t  $ \\displaystyle\\bar{ {X}}_v=\\frac{1}{N} \\sum_{n=1}^N X_{nv}$ & $  \\displaystyle \\hat{q}_v({0.5})$  \\\\\n\t & \\hspace{5mm}(mean) & (median)  \\\\%[2mm]\n\t  %\n\t\\multirow{ 2}{*}{Scale} & %\\multirow{ 2}{*}{$h_2$} &\n\t $ \\hat\\sigma^2_v = \\displaystyle\t\\frac{1}{N-1}\\sum_{n=1}^{N} \\big(X_{nv}-\\bar {X}_v \\big)^2$  &  % \\displaystyle s^2 =\t\\(\\stackunder[1pt]{$ \\mbox{mediai}$}{\t\\scalebox{0.8}{$ 1\\le i\\le N$}} \\) $\\big (| X_n - q_{0.5}| \\big)$ \n\t$\\displaystyle \\hat{q}_v({0.75}) - \\hat{q}_v({0.25})$ \\\\ %[-1mm]\n\t & (variance) &(interquartile range)   \\\\[1mm]\n\t Skewness & % $h_3$ &\n\t$\\displaystyle\\frac{1}{N} \\sum_{n=1}^N \\frac{( X_{nv}-\\bar{X}_v)^3}{ \\hat\\sigma_v^3}  $  & \n\t$ \\displaystyle \\frac{\\hat{q}_v({0.9}) + \\hat{q}_v({0.1}) -2 \\hat{q}_v({0.5}) }{  \\hat{q}_v({0.9}) - \\hat{q}_v({0.1})  }$\\\\[4mm] %\\displaystyle  \\hat{\\mathcal{S}}=\n\t Kurtosis &  %$h_4$ &\n\t $\\displaystyle\\frac{1}{N} \\sum_{n=1}^N \\frac{( X_{nv}-\\bar{X}_v)^4}{ \\hat\\sigma_v^4}  $ &\n\t$ \\displaystyle\\frac{\\hat{q}_v({0.975}) -\\hat{q}_v({0.025}) }{\\hat{q}_v({0.75}) -\\hat{q}_v({0.25}) }  $ \\\\[4mm] %\\displaystyle \\hat{\\kappa} =\n\t \t\\multirow{ 2}{*}{Dependence} &  \t%\\multirow{ 2}{*}{$H$} &\n\t  $ \\; %\\hat \\rho =\n\t   \\displaystyle\\frac{ \\sum_{n} \\big(X_{n1}- \\bar X_{1} \\big) \\big(X_{n2} - \\bar X_{2}\\big) } {\\sqrt{ \\sum_n \\big(X_{n1}- \\bar X_{1} \\big) ^2 \\sum_n \\big(X_{n2} - \\bar X_{2}\\big)^2 }   } $ & \n\t\\;\\; $\\displaystyle   \\frac{ \\sum_{n} \\big(R_{n1} - \\bar R_{1} \\big) \\big(R_{n2} - \\bar R_{2}\\big) } { \\sqrt{ \\sum_n \\big(R_{n1} - \\bar R_{1} \\big) ^2 \\sum_n \\big(R_{n2} - \\bar R_{2}\\big)^2  }} $ \\\\\n\t & (Pearson's correlation ) & (Spearman's rank correlation \\cite{Spearman})\\\\[1mm] % \\hat{\\rho} = \n\t \\hline\\\\[-2mm]\n\t \\end{tabular}\n\t }\n\t\\end{center}\n\t\\caption{ Given a group ${\\bf G} =(X_{nv})  \\in \\mathbb{R}^{ N \\times V}$,  the $\\beta$-quantile  $\\hat{q}_v(\\beta)$ is estimated from  the empirical distribution of the $v$th column of random variables. Also\n$R_{\\cdot v}  \\in \\mathbb{R}^{ N }$  denotes ranked values  of $X_{\\cdot v}$ with average column rank $\\bar R_v$.  % Note Pearson's correlation captures a linear relationship between variables whereas Spearman's rank correlation \\cite{Spearman}  measures a monotonic (possibly non-linear) dependence.\nNon-parametric measures of skewness and kurtosis are respectively described in \nHinkley   \\cite{hinkley1975} \nand Moors \\cite{RobustK}.\n}\n \\label{Tab:Des}\n\\end{table}  \n \n% SP - characterise, measure \nIn most applications, statistical properties that characterises group deviations are usually known. Without prior information, it is difficult to differentiate a group deviation  as there may be a significant difference in a combination of statistical properties. %Also if an incorrect selection of statistical properties are analysed then significant group deviations cannot be identified. \n  Guevara et al. \\cite{SMDD} explore the GAD application and find that more complicated group behaviours are not adequately characterised by single quantities such as location estimates of group distributions. %Their study investigates examples of Gaussian mixtures where a group anomaly is generated from a different proportion of distributions.\n % Another issue occurs for high dimensional datasets as common measures of statistical properties in Table \\ref{Tab:Des} may not properly characterise the behaviour of groups.\n   Topic models are applied for GAD problems  where  statistical properties of  groups represent  proportions of inferred topic  variables.  % high number of dimensions where  models extract . \n  We  discuss topic models in more detail for  GAD applications in Chapter \\ref{sec:staticGAD}.   \n\n\n\n\\subsection{Model Design} \nAfter understanding problems associated with group structures and statistical properties of interest, a domain expert can construct suitable solutions for GAD and GCD problems. Firstly models are designed to be compatible for specific types of input data such as continuous or categorical variables. To appropriately identify group deviations, discriminative methods do not impose data assumptions  while generative models assume how data is generated.  Given availability of labeled group behaviours, models either apply  supervised or unsupervised learning. Another important aspect of model design is  interpreting outputs with scores or labels.  The model design of group deviation detection techniques requires a clear understanding. \n\n\\subsubsection{Input Data }\nCertain models are compatible for specific types of input data.   As specified by Equation (\\ref{Eqn:Domain}) in the problem definition, data types that are explored in GAD and GCD applications include  discrete, continuous or categorical features.\nData types also influence the appropriateness of statistical properties for characterising  groups behaviours. In particular, generative models are flexible in assuming a Gaussian distribution for continuous real-valued data whereas categorical features are modelled by categorical distributions.   \n Pairwise network connections are also a possible type of input data and are usually  incorporated for clustering when group structures are previously unknown.  Similarly, certain clustering algorithms are only compatible for specific data types. \n\n\n \n\\subsubsection{Assumptions}\n The assumptions of GAD and GCD techniques  are  discussed in terms of discriminative and generative models.  %where supervised or   unsupervised learning is applied depending on the availability of labeled data.  \nDiscriminative approaches are useful for directly classifying groups into regular and anomalous behaviours without knowledge of how data is generated.  %Due to the lack of regular and anomalous group labels, discriminative GAD techniques classify regular behaviour based on the predominant group pattern.  \n On the other hand, generative models assume specific probability density functions over   variables.  Hypothesis tests are a special type of generative model that further classify group deviations. %GAD and GCD  techniques  are classified as either  discriminative or generative models however hypothesis tests are also elaborated on.  \n% Common advantages and disadvantages of \nTable \\ref{Tab:DG} lists common advantages of  discriminative methods, generative models as well as hypothesis tests. % for  GAD and GCD  applications. \n\n\\begin{table}[H]\n\t\\tabcolsep=0.3cm\n\t\\renewcommand{\\arraystretch}{1.2}\n\t\\begin{center}\\scalebox{1}{\n\t\\begin{tabular}{lcccccccccccccccc  }\n\t\\hline\\\\[-6mm]\n Procedure & $\\mathcal{A}1$ & $\\mathcal{A}2$ & $\\mathcal{A}3$ & $\\mathcal{A}4$ & $\\mathcal{A}5$  \\\\[-1mm] \\hline \\\\[-8mm] \\hline\\\\[-6mm]\n  Discriminative Methods   & \\yeah & \\nope & \\yeah  & \\nope & \\nope \\\\\n  Generative Models   & \\nope & \\yeah & \\nope  & \\yeah & \\nope \\\\\n Hypothesis Tests  & \\yeah & \\yeah & \\nope  & \\yeah & \\yeah\\\\[3mm]\n\\hline \n\t \\end{tabular}\n\t}\n\t\\end{center}\n\t\\medskip\n\t\t\\caption{  Summary of advantages of   group deviation detection techniques in terms of \t discriminative methods, generative models and hypothesis tests. If a procedure has a particular advantage, a tick label is present whereas if a procedure lacks an advantage, a cross is displayed.  }\n\t%\\vspace{-5mm}\n \\label{Tab:DG}\n\\end{table}  \n\n\t\n\t\n\\begin{enumerate}[{$\\mathcal{A}$}1] \\setlength\\itemsep{5pt}\n\\item   {\\it Direct classification}:  discriminative models and hypothesis tests provide explicit boundaries between regular   behaviours and significant group deviations. \n \\item  {\\it Rich Interpretation}: Results from discriminative methods  are difficult to interpret due to the complex representation between group   variables. For explanatory purposes, \n  generative models offer a rich interpretation of  groups and inferred statistical properties.    The flexible structure of generative models is also useful for incorporating prior information.\n  \\item  {\\it  Minimal  Assumptions}: \n  Discriminative approaches assume that group behaviours can be differentiated based on certain optimisation criteria.   Generative models further impose distributional assumptions which are not  appropriate for all datasets. \n  \\item  {\\it Prevents Overfitting}: Discriminative methods are prone to overfitting model parameters especially on  training data with smaller sample sizes. \n Generally, generative models experience less overfitting  when the model assumptions are appropriate for given datasets.  \n   \\item  {\\it Statistical Significance}: In addition,  hypothesis tests determine whether the statistical properties of a group is significantly different. In many cases, generative models arbitrarily classify    significant group deviations based on highest anomalous scores. \n\\end{enumerate}\t\n\n\n\n\n\\subsubsection{Learning}\nSupervised learning requires previously labelled group behaviours while  \nunsupervised approaches learn the dominant pattern in the dataset. \nWhen surveying current state-of-the-art group deviation detection \n techniques, most discriminative  and generative models employ unsupervised learning.  \n Unsupervised learning is preferred as  ground truth labels of regular or irregular behaviours are not usually available. In a  comparison study conducted by Laskov et al. \\cite{laskov2005learning},  unsupervised methods achieve a higher accuracy than  supervised algorithms when learned behaviours from a training data do not account for unknown patterns in a test set.  Unsupervised methods are beneficial for  discovering novel group patterns. \n\n\\subsubsection{Output}\nThe output from group deviation detection techniques  is given by classification labels or  scores indicating significant group deviations.  \n Discriminative methods produce binary labels for regular or anomalous classes in GAD while GCD methods estimate times of significant change in a dynamic group over time.   Generative models  tend to compute scores that quantifies the degree that a  group is significantly different as compared to other groups in a dataset. Scores from generative models are often converted to a classification by a threshold chosen by a user however  this selection is subjective and equivocal.  Hypothesis tests are advantageous for obtaining classification labels based on the statistical significance of group deviations.  \n  \n\n  \n\n\n\n\n\\section{Challenges}\nWe now discuss challenges associated with group deviation detection. There are many issues that arise from inadequate group definitions in a dataset. Datasets involving group structures are more difficult to understand and analyse than many pointwise data problems with potential absence of group labels. Benchmark datasets are currently unavailable and thus comparison studies are difficult to conduct. Even though detecting group deviations may seem like a straightforward task, results require validation and careful interpretation. The challenges in  GAD and GCD applications  include:\n\n\\begin{enumerate}[\\textbullet]\n\\item {\\it  Defining Groups}:\n F\\~{a}rber et al. \\cite{ClusterEval}   highlight that known group labels may not represent natural clustering patterns in a dataset. \n However when group memberships are unknown a priori,   clustering method possibly lead to inadequate group representations. Group structures  may be improved by incorporating additional information such as known regular group behaviour or pairwise relationships between data instances. \n \\item {\\it Defining Group Deviations}: Group deviations can be defined based on the number of groups or the number of  data instances within groups. Usually when groups possess similar sizes, group deviations occur as a minority of group observations.    \n  % Consider  a single group that contains more observations than the total number of other groups. \n\\item {\\it Capturing Statistical Properties}: Group deviations may occur in a variety of statistical properties such as location, scale, shape, etc.    Borgatti et al. \\cite{GroupSocialMedia} explain that more complicated patterns exist when each member contributes to behaviour of a group. Thus an effective detection method has to adequately capture properties of groups in order to identify significant deviations.\n% \\item {\\it Evolving Patterns}: In many domains, the notion and definition of group deviations also changes over a period of time. Algorithms that can adapt to identifying evolving unknown group patterns  are preferable in many applications. \n\\item {\\it Not statistically significant}: Many methods classify or score group behaviours however they do not quantify statistical significance. In many cases, it is difficult to distinguish noisy group observations from a significant group deviation. \n\\item {\\it Absence of Group Labels}: When group memberships are unknown a priori, clustering  induces additional uncertainty in analysis and subsequent results. Halkidi et al. \\cite{ClusterValidity} explain that it is also difficult to evaluate the effectiveness of inferred clusters without sufficient ground truth labels. \n\\item {\\it Absence of Ground Truth Labels}: Like other anomaly detection applications, ground truth labels are usually unavailable. To investigate group deviations rather than a single  instance, requires more time and effort for obtaining  ground truth labels.  \n\\item {\\it Absence of Benchmark Datasets}: Since there is a lack of benchmark group datasets, many methods resort to anomaly injection. Anomaly injection involves contaminating a real-world dataset with significant deviations and subsequently comparing detected instances with  ground truth labels. This does not account for  anomalies that are naturally present in a dataset such that injected anomalies should possess higher deviations than naturally occurring anomalies. \n\\item {\\it Absence of Robust Comparison Studies}: Evaluative metrics that assess  group deviation detection datasets would be useful for a robust comparison study. For pointwise anomaly detection methods, Campos et al. \\cite{Campos2016} propose two measures for a dataset; difficulty of detecting different types of anomalies and diversity or agreement between scores computed from methods.  A similar evaluative process is recommended for group deviation datasets to provide a more robust comparison of state-of-the-art techniques. \n\\end{enumerate}\nThere is no single solution that overcomes all of these challenges in GAD and GCD research.  We further elaborate on related work for group deviation detection techniques in static and dynamic scenarios. \n\n\n\\section{Related Work}\nDue to continual research involving  anomaly detection and change detection,  there are additional problems and  techniques that are proposed after the publication of many papers. Extensive reviews on pointwise anomaly detection techniques are conducted by Hodge and  Austin \\cite{Hodge}  as well as Chandola et al. \\cite{Chandola}.   Since change detection is a general topic, many techniques are domain specific where  \nSingh \\cite{singh1989review} examines the application to remote sensor data while Reeves et al. \\cite{reeves2007review} explore change detection techniques for climate data. An overview of temporal outlier detection is provided by Gupta et al. \\cite{Gupta2013}. Many of these papers  briefly discuss  group applications however GAD and GCD are emerging areas of research where most state-of-the-art techniques have been more recently developed.  Yu et al. \\cite{SurveySocialMedia} and  Xiong \\cite{Collective}  provide descriptions of current state-of-the-art GAD methods.  % \n\n{  \nGAD is closely related to zero-shot learning (ZSL) where data instances are classified however their behaviour may not be seen in training. % different classes even when unseen instances in a test set   that are not present in the training set.\n%There is an overlap between GAD and zero-shot learning (ZSL) techniques however there are fundamental difference. \nSurveys on ZSL have been conducted by Xian et al. \\cite{ZSLsurvey} where ZSL assumes a subset of classes (groups) are known during training whereas GAD techniques are more general as none of regular  group behaviours (classes) may be available.\n%GAD is more general than ZSL as classes (groups) may not be available while ZSL assume classes are known during training.     \n %ZSL accounts for the simple case where training and test set are disjoint while classes in  training and test set may overlap for generalised ZSL. \n  Without known classes,  Kodirov et al. \\cite{unsupervisedZSL} propose an unsupervised ZSL technique that incorporates auxiliary textual information.   ZSL techniques are specfically formulated for certain domains such as image classification \\cite{ZSLanomaly} and network intrusion  \\cite{perez2016} however we focus on GAD techniques that are applicable for more general domains. \n\n\n\n%Group change detection  \nSimilarly the GCD problem has been  specifically formulated for many real-world applications. In video change detection, a video can be modelled as a group of color pixels or visual features where  significant deviations in video frames are detected over time. Lienhart \n\\cite{VideoSurvey} provides a survey of video transition (gradual change) detection techniques while a comparison study of performance for video-shot-change (abrupt  change) detection algorithms is conducted in Gargi et al. \\cite{gargi2000}. %Other methods such as  Yuan et al. \\cite{yuan2017anomaly} identify subtle changes in  traffic scenes while  %Yuan et  al.   \\cite{yuan2016hyperspectral} examine  reflectance spectrum data.\n%Rout et al. \\cite{rout2018}  detect changing  positions of dynamic objects in an underwater video.\n  In other applications, Sakaki et al. \\cite{sakaki2010} detect an earthquake event by monitoring a group of keywords on Twitter and  Xie et al. \\cite{xie2013} explore  sequential change-point detection in multiple sensor readings over time. % the average value of  sensor readings over time. % and also estimate the affected proportion  of sensors at a specific time step.  \nMany of these GCD techniques are only applicable in  specific domains and are not flexible for detecting changes in a variety of statistical properties.   \n}\n\n", "meta": {"hexsha": "fb018219d9c6e4e1db3606ecb08737eca41f673a", "size": 25963, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ARXIV_DAD_Survey/sections/MyModel.tex", "max_stars_repo_name": "raghavchalapathy/Deep-Learning-for-Anomaly-Detection-A-Survey", "max_stars_repo_head_hexsha": "aa775990a4b23306885979c4ef8e8cb3ed00441b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 107, "max_stars_repo_stars_event_min_datetime": "2019-01-11T12:06:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T12:03:57.000Z", "max_issues_repo_path": "ARXIV_DAD_Survey/sections/MyModel.tex", "max_issues_repo_name": "raghavchalapathy/Deep-Learning-for-Anomaly-Detection-A-Survey_Arxiv_WorkingDocument", "max_issues_repo_head_hexsha": "aa775990a4b23306885979c4ef8e8cb3ed00441b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ARXIV_DAD_Survey/sections/MyModel.tex", "max_forks_repo_name": "raghavchalapathy/Deep-Learning-for-Anomaly-Detection-A-Survey_Arxiv_WorkingDocument", "max_forks_repo_head_hexsha": "aa775990a4b23306885979c4ef8e8cb3ed00441b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2019-01-15T02:42:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-06T07:59:29.000Z", "avg_line_length": 108.1791666667, "max_line_length": 739, "alphanum_fraction": 0.7804953203, "num_tokens": 6009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.3325633201022936}}
{"text": "\\documentclass[a4paper,10pt]{article}\n\\usepackage{graphicx,xspace}\n\\usepackage[utf8]{inputenc}\n\\usepackage[left=2.5cm,top=3cm,bottom=3cm,right=2.5cm]{geometry}\n\\newcommand{\\R}{\\textsf{R}\\xspace}\n\n\\usepackage{/home/gavin/R/build/3.3-patched/share/texmf/tex/latex/Sweave}\n\n\\renewcommand{\\abstractname}{Summary}\n\n\\begin{document}\n\\title{Introduction to R for the Geoscience: Stratigraphic \\& Palaeo Data}\n\\author{Gavin Simpson}\n\\date{February , 2017}\n\n\\maketitle\n\n\\section{Rates of Change}\nIn this part of the practical you will compute some rate of change estimates\nfor a short core sequence from the Round Loch of Glenhead covering the last 140\nyears. There aren't any canned functions for computing rates of change in \\R so\nyou'll perform all the neccessary steps yourself --- don't worry, they aren't\ntoo onerous and you'll learn more about \\R coding as you go along. \n\nStart by loading the \\textsf{rioja} package and the dataset needed\n\\begin{Schunk}\n\\begin{Sinput}\n> library(\"rioja\")                        # install.packages(\"rioja\")\n> ## load data and extract\n> data(RLGH)\n> spp <- RLGH$spec\n> age <- RLGH$depth$Age\n\\end{Sinput}\n\\end{Schunk}\n\n\\subsection{Ordination-based rates of change}\nThe first method you'll use is the ordination based rate of change, for which\nwe need to smooth and interpolate the species data to a common time interval.\nThis can be done using the \\texttt{interp.dataset()} function\n\\begin{Schunk}\n\\begin{Sinput}\n> ## interpolate new dataset to every 5 years\n> ## using a smoothing splint\n> x.new <- seq(0, max(age), by=5)\n> sp.interp <- interp.dataset(y=spp, x=age, xout=x.new,\n+                             method = \"sspline\")\n> rownames(sp.interp) <- x.new\n\\end{Sinput}\n\\end{Schunk}\n\nNext you need to ordinate the data. Here we use DCA to follow the published version, but you could try other ordination techniques should you wish.\n\\begin{Schunk}\n\\begin{Sinput}\n> ## ordinate\n> library(\"vegan\")\n> ord <- decorana(sp.interp)\n> ord\n\\end{Sinput}\n\\begin{Soutput}\nCall:\ndecorana(veg = sp.interp) \n\nDetrended correspondence analysis with 26 segments.\nRescaling of axes with 4 iterations.\n\n                  DCA1    DCA2     DCA3     DCA4\nEigenvalues     0.1312 0.02112 0.007314 0.007082\nDecorana values 0.1316 0.01130 0.005090 0.003085\nAxis lengths    1.1056 0.53068 0.427959 0.374999\n\\end{Soutput}\n\\begin{Sinput}\n> ## plot of points showing ages\n> plot(ord, display = \"sites\", type = \"text\")\n\\end{Sinput}\n\\end{Schunk}\n\nHow many axes do you want to retain?\n\nFinally, to compute the rate of change we need to extract the axis scores we\nneed and compute the distance between observations in ordination space. This\nhas to be done by hand for the most part.\n\\begin{Schunk}\n\\begin{Sinput}\n> ## get scores\n> scrs <- scores(ord, display = \"sites\", choices = 1:2)\n> roc <- as.matrix(dist(scrs))\n> roc <- roc[row(roc) == col(roc) + 1] ## extract off-diagonal\n> roc\n\\end{Sinput}\n\\begin{Soutput}\n [1] 0.145791683 0.038388466 0.056476075 0.096765764 0.141675748 0.089316724\n [7] 0.148886370 0.065164981 0.123568620 0.180866597 0.135311608 0.072936429\n[13] 0.009012417 0.054150418 0.058022625 0.065137156 0.081900194 0.093647074\n[19] 0.102022525 0.106469426 0.102384652 0.095557955 0.078070381 0.054041243\n[25] 0.024817872 0.004879166 0.010482557 0.017234419\n\\end{Soutput}\n\\end{Schunk}\n\nPlot the rates of change for the core sequence\n\\begin{Schunk}\n\\begin{Sinput}\n> ## plot roc against age\n> plot(roc ~ head(x.new, -1), type = \"l\", ylab = \"Rate of Change\", xlab = \"Age\")\n> points(roc ~ head(x.new, -1), type = \"h\")\n\\end{Sinput}\n\\end{Schunk}\n\nIdentify the periods with greatest rates of change. You'll compare these with\nthose identified using the dissimilarity-based approach in the next section.\n\n\\subsection{Dissimilarity-based rates of change}\nNow you'll calculate rates of change for the same samples using the raw\ndissimilarity method. In this method the data don't need to be interpolate,\ninstead we work with the actual species data themselves. Start by computing\nthe squared chord distances between all samples and extract the off-diagonal\nelements (the pairwise dissimilarities)\n\\begin{Schunk}\n\\begin{Sinput}\n> roc2 <- as.matrix(paldist(spp/100, dist.method=\"sq.chord\"))\n> roc2 <- roc2[row(roc2) == col(roc2) + 1] ## extract off-diagonal\n\\end{Sinput}\n\\end{Schunk}\n\nNext scale these by the number of years between each sample. We can compute the\nsample intervals in years using the \\texttt{diff()} function\n\\begin{Schunk}\n\\begin{Sinput}\n> intervals <- diff(age)\n> roc2 <- roc2 / intervals\n\\end{Sinput}\n\\end{Schunk}\n\nPlot the rates of change for the core sequence\n\\begin{Schunk}\n\\begin{Sinput}\n> ## plot roc2 against age\n> plot(roc2 ~ head(age, -1), type = \"l\", ylab = \"Rate of Change\", xlab = \"Age\")\n> points(roc2 ~ head(age, -1), type = \"h\")\n\\end{Sinput}\n\\end{Schunk}\n\nIdentify the periods with greatest rates of change. How do these compare with\nthe rates extract using the ordination-based approach? Can you think why there\nmight be differences? Which method would you trust most? Why?\n\nTo aid you in your comparison, you can plot both rates of change on the same\ndevice\n\\begin{Schunk}\n\\begin{Sinput}\n> ## compare plots\n> layout(matrix(1:2, nrow = 2))\n> ## plot roc against new age\n> xlim <- range(age, x.new)\n> plot(roc ~ head(x.new, -1), type = \"l\", ylab = \"Rate of Change\", xlab = \"Age\",\n+      main = \"Ordination-based\", xlim = xlim)\n> points(roc ~ head(x.new, -1), type = \"h\")\n> ## plot roc2 against age\n> plot(roc2 ~ head(age, -1), type = \"l\", ylab = \"Rate of Change\", xlab = \"Age\",\n+      main = \"Dissimilarity-based\", xlim = xlim)\n> points(roc2 ~ head(age, -1), type = \"h\")\n> layout(1)\n\\end{Sinput}\n\\end{Schunk}\n\n\\section{Chronological clustering}\n\nNow we'll look at a coupld of chronological clustering methods that are available in \\R.\n\n\\subsection{CONISS}\n\nFirst we'll apply CONISS to the Abernethy Forest pollen record. We load the data set, convert the observations to proportions (from percentages) and apply a square root transformation. Ths means that when we compute the euclidean distances between samples using \\texttt{dist()} we are computing hellinger distances instead. Finally we use the \\texttt{chclust()} function to perform the CONISS clustering\n\n\\begin{Schunk}\n\\begin{Sinput}\n> library(\"analogue\")\n> data(abernethy)\n> aber <- abernethy[, seq_len(ncol(abernethy) - 2L)]\n> diss <- dist(tran(aber, method = \"pcent2prop\"))\n> clust <- chclust(diss)\n\\end{Sinput}\n\\end{Schunk}\n\nWe can plot the CONISS results and the variances ``explained'' by varying the number of zones.\n\n\\begin{Schunk}\n\\begin{Sinput}\n> layout(matrix(1:2, ncol = 2))\n> op <- par(mar = c(5,4,1,2) + 0.1)\n> plot(clust, labels = abernethy$Age, hang=-1, horiz=TRUE, x.rev = TRUE, cex = 0.5)\n> bstick(clust, 10)\n> par(op)\n> layout(1)\n\\end{Sinput}\n\\end{Schunk}\n\nUsing the screeplot method or Bennett's broken stick approach, suggest how many zones you would consider splitting the Abernethy Forest pollen record into?\n\n\\subsection{Binary splitting}\n\nUnfortunately, the \\textbf{mvpart} package that I used previously to do binary or recursive partitioning has been removed from CRAN as it contains problems that were never addressed by its author/maintainer. A new way of fitting almost the same model has become available in the \\textbf{partykit} package. Rather than use cross-validation and cost-complexity pruning to choose the number of binary splits, it uses conditional inference trees. I'm not exactly sure how to describe this, but it is essentially using statistical methods to decide if it should make a new split at all. This is in contrast to standard tree models where they are grown very large and we use cross validation to prune the branches back.\n\nIn this section we'll take a quick look at doing clustering via binary splitting using the \\textbf{partykit} package. First we load the package (you'll need to install it first) and then we remove some of the rare species (you should just do this casually --- I'm doing it here to make fitting the tree easier). We also need to clean up (remove spaces and hyphens) the taxon names so we can create the formula needed to fit the model\n\n\\begin{Schunk}\n\\begin{Sinput}\n> library(\"partykit\")                     # install.packages(\"partykit\")\n> aber2 <- chooseTaxa(aber, n.occ = 2, max.abun = 5)\n> names(aber2) <- gsub(\" \", \"\", names(aber2))\n> names(aber2) <- gsub(\"-\", \"\", names(aber2))\n\\end{Sinput}\n\\end{Schunk}\n\nNow we can create the formula which describes the conditional tree we want to fit. All the species we didn't remove will end up on the left hand side of the formula, and \\texttt{Age} will be the sole predictor. We add on the \\texttt{Age} variable to the reduced set of species so all the variables are in one object.\n\n\\begin{Schunk}\n\\begin{Sinput}\n> frm <- formula(paste0(paste(names(aber2), collapse = \" + \"), \" ~ Age\"))\n> aber2 <- cbind(aber2, Age = abernethy$Age)\n\\end{Sinput}\n\\end{Schunk}\n\nNow we can fit the conditional inference tree and plot the results\n\n\\begin{Schunk}\n\\begin{Sinput}\n> sptree <- ctree(frm, data = aber2, teststat = \"max\", minsplit = 2)\n> plot(sptree, terminal_panel = node_barplot, tp_args = list(rot = 45, just = c(\"right\")))\n\\end{Sinput}\n\\end{Schunk}\n\nThe leaves of the tree are illustrated by barplots showing the abundances of each species. These barplots give you some idea of the species composition in each zone, but the code isn't flexible enough yet to allow you to mke nicer plots or show taxon names clearly (or I haven't worked out how to do it!) Note that here we just used the raw percentage abundances to fit the tree, you might get a different tree if you transformed or standardised the species data.\n\nHow many zones are suggested by the tree? Do these zones match up with the ones CONISS identified?\n\n\\section{Principal Curves}\nIn this section of the practical you'll explore fitting a principal curve to\nthe Abernethy Forest pollen data set. The functions you need are available in\nthe \\textsf{analogue} package. Load it, and ignore the warnings for now.\n\\begin{Schunk}\n\\begin{Sinput}\n> library(\"analogue\")\n> data(abernethy)\n\\end{Sinput}\n\\end{Schunk}\n\nA simple summary of the data can be produced using the \\texttt{Stratiplot()}\nfunction\n\\begin{Schunk}\n\\begin{Sinput}\n> (plt <- Stratiplot(Age ~ . - Depth, data =\n+                    chooseTaxa(abernethy, max.abun = 15, n.occ = 10),\n+                    type = c(\"h\",\"g\",\"l\"), sort = \"wa\"))\n\\end{Sinput}\n\\end{Schunk}\n\nNext, remove two variables from the data set (the samples depths and ages) and\nthen proceed to fit a PCA and a CA, as well as the principal curve to the data\n\\begin{Schunk}\n\\begin{Sinput}\n> abernethy2 <- abernethy[, -(37:38)]\n> aber.pca <- rda(abernethy2)\n> aber.ca <- cca(abernethy2)\n> aber.pc2 <- prcurve(abernethy2, method = \"ca\", trace = TRUE, plotit = TRUE,\n+                     vary = TRUE, penalty = 1.4)\n\\end{Sinput}\n\\begin{Soutput}\n   Determining initial DFs for each variable...\n\n  |                                                                            \n  |                                                                      |   0%\n  |                                                                            \n  |==                                                                    |   3%\n  |                                                                            \n  |====                                                                  |   6%\n  |                                                                            \n  |======                                                                |   8%\n  |                                                                            \n  |========                                                              |  11%\n  |                                                                            \n  |==========                                                            |  14%\n  |                                                                            \n  |============                                                          |  17%\n  |                                                                            \n  |==============                                                        |  19%\n  |                                                                            \n  |================                                                      |  22%\n  |                                                                            \n  |==================                                                    |  25%\n  |                                                                            \n  |===================                                                   |  28%\n  |                                                                            \n  |=====================                                                 |  31%\n  |                                                                            \n  |=======================                                               |  33%\n  |                                                                            \n  |=========================                                             |  36%\n  |                                                                            \n  |===========================                                           |  39%\n  |                                                                            \n  |=============================                                         |  42%\n  |                                                                            \n  |===============================                                       |  44%\n  |                                                                            \n  |=================================                                     |  47%\n  |                                                                            \n  |===================================                                   |  50%\n  |                                                                            \n  |=====================================                                 |  53%\n  |                                                                            \n  |=======================================                               |  56%\n  |                                                                            \n  |=========================================                             |  58%\n  |                                                                            \n  |===========================================                           |  61%\n  |                                                                            \n  |=============================================                         |  64%\n  |                                                                            \n  |===============================================                       |  67%\n  |                                                                            \n  |=================================================                     |  69%\n  |                                                                            \n  |===================================================                   |  72%\n  |                                                                            \n  |====================================================                  |  75%\n  |                                                                            \n  |======================================================                |  78%\n  |                                                                            \n  |========================================================              |  81%\n  |                                                                            \n  |==========================================================            |  83%\n  |                                                                            \n  |============================================================          |  86%\n  |                                                                            \n  |==============================================================        |  89%\n  |                                                                            \n  |================================================================      |  92%\n  |                                                                            \n  |==================================================================    |  94%\n  |                                                                            \n  |====================================================================  |  97%\n  |                                                                            \n  |======================================================================| 100%\n\n\nFitting Principal Curve:\n\nInitial curve: d.sq: 103233.450\nIteration   1: d.sq: 4283.431\nIteration   2: d.sq: 4312.298\nIteration   3: d.sq: 4340.691\nIteration   4: d.sq: 4355.388\nIteration   5: d.sq: 4366.497\nIteration   6: d.sq: 4369.944\n\nPC Converged in 6 iterations.\n\\end{Soutput}\n\\end{Schunk}\nThe arguments to \\texttt{prcurve()} tell it to start from a CA solution, show\nit working by printing to the console and plotting the curve as it converges,\ntaxa are allowed differeing complexity smoothers and the penalty per degree of\nfreedom is increased by 40\\% to help avoid over-fitting.\n\nLook at the fitted object. How much of the variance in the dataset is explained\nby the principal curve?\n\\begin{Schunk}\n\\begin{Sinput}\n> aber.pc2\n\\end{Sinput}\n\\begin{Soutput}\n\tPrincipal Curve Fitting\n\nCall: prcurve(X = abernethy2, method = \"ca\", vary = TRUE, trace = TRUE,\nplotit = TRUE, penalty = 1.4)\n\nAlgorithm converged after 6 iterations\n\n           SumSq Proportion\nTotal     103234      1.000\nExplained  98864      0.958\nResidual    4370      0.042\n\nFitted curve uses 218.3391 degrees of freedom.\n\\end{Soutput}\n\\end{Schunk}\nCompare that with the variance explained by the PCA and CA\n\\begin{Schunk}\n\\begin{Sinput}\n> varExpl(aber.pca)\n\\end{Sinput}\n\\begin{Soutput}\n      PC1 \n0.4649883 \n\\end{Soutput}\n\\begin{Sinput}\n> varExpl(aber.ca)\n\\end{Sinput}\n\\begin{Soutput}\n      CA1 \n0.3098955 \n\\end{Soutput}\n\\end{Schunk}\nHow well has the principal curve done compared to the more traditional\ntechniques?\n\nPlot the principal curve\n\\begin{Schunk}\n\\begin{Sinput}\n> ## Plot the fitted curve\n> plot(aber.pc2)\n\\end{Sinput}\n\\end{Schunk}\nCan you see why the principal curve performs much better than the other two\nordination techniques?\n\nA longer chunk of code is required to draw rates of change and compare the\nvarious methods\n\\begin{Schunk}\n\\begin{Sinput}\n> Depth <- abernethy$Depth\n> Age <- abernethy$Age\n> layout(matrix(c(1,2,2), ncol = 3))\n> nseg <- nrow(abernethy2) - 1\n> RoC <- unclass(diff(gradientDist(aber.pc2))) / diff(Age)\n> plot(y = Age[-length(Age)],\n+      x = RoC * 1000, type = \"n\",\n+      ylim = rev(range(Age)),\n+      ylab = \"Age (Radiocarbon years BP)\",\n+      xlab  = expression(\"Rate of Change\" ~ (kyr^{-1})),\n+      main = \"a\", cex.main = 1.5)\n> segments(x0 = rep(0, nseg), y0 = Age[-length(Age)],\n+          x1 = RoC * 1000, y1 = Age[-length(Age)])\n> plot(gradientDist(aber.pc2), orderBy = Age,\n+      xlim = rev(range(Age)),\n+      type = \"o\", flipAxes = TRUE, xlab = \"Age (Radiocarbon years BP)\",\n+      main = \"b\",\n+      cex = 0.8, pch = 21, col = \"black\", bg = \"black\", cex.main = 1.5)\n> lines(gradientDist(aber.pca), orderBy = Age,\n+       lty = \"dashed\", flipAxes = TRUE, type = \"o\",\n+       cex = 0.8, pch = 22, col = \"black\", bg = \"black\")\n> lines(1 - gradientDist(aber.ca), orderBy = Age,\n+       lty = \"dotdash\", flipAxes = TRUE, type = \"o\",\n+       cex = 0.8, pch = 23, col = \"black\", bg = \"black\")\n> legend(\"topright\", bty = \"n\", pch = 21:23,\n+        legend = c(expression(PCurve), expression(PCA[1]), expression(CA[1])),\n+        lty = c(\"solid\",\"dashed\",\"dotdash\"),\n+        col = c(\"black\",\"black\",\"black\"),\n+        pt.bg = c(\"black\",\"black\",\"black\"), inset = 0.01, cex = 1.4,\n+        seg.len = 4)\n> layout(1)\n\\end{Sinput}\n\\end{Schunk}\n\nThe individual curves fitted to each taxon can be visualised, again with a long\nchunk of code. Here, only the most abundant taxa are shown\n\\begin{Schunk}\n\\begin{Sinput}\n> taxaWant <- chooseTaxa(aber, max.abun = 25, n.occ = 10, value = FALSE)\n> layout(matrix(seq_len(sum(taxaWant)), ncol = 3))\n> op <- par(mar = c(4,4,3,1) + 0.1)\n> plot(sppResponse(aber.pc2), which = taxaWant)\n> par(op)\n> layout(1)\n\\end{Sinput}\n\\end{Schunk}\n\nUsing the two plots, do you feel the principal curve has done a good job of\ndescribing floristic change in the Abernethy core?\n\\end{document}\n", "meta": {"hexsha": "d49541738912532227e4c49306758081e13b6d72", "size": 20634, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "04-thursday/04-stratigraphic-prac.tex", "max_stars_repo_name": "gavinsimpson/adelaide-2017", "max_stars_repo_head_hexsha": "93e5422b4960016a7b5e103b07baa0a1db28e842", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-04-20T02:38:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-13T21:20:33.000Z", "max_issues_repo_path": "04-thursday/04-stratigraphic-prac.tex", "max_issues_repo_name": "gavinsimpson/adelaide-2017", "max_issues_repo_head_hexsha": "93e5422b4960016a7b5e103b07baa0a1db28e842", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "04-thursday/04-stratigraphic-prac.tex", "max_forks_repo_name": "gavinsimpson/adelaide-2017", "max_forks_repo_head_hexsha": "93e5422b4960016a7b5e103b07baa0a1db28e842", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-01T10:17:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-01T10:17:37.000Z", "avg_line_length": 43.9957356077, "max_line_length": 713, "alphanum_fraction": 0.5088688572, "num_tokens": 4996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.6548947223065754, "lm_q1q2_score": 0.33256330984111393}}
{"text": "\\subsection{Experiment} \\label{experiment}\n\nThe proposed sliding window filter has several model parameters that need to be carefully tuned in order to achieve optimal performance. Depending on the application domain we need to select an appropriate window and step size, time series normalization, dissimilarity threshold, and filter criterion. In the following we describe all parameter settings that were assessed in our empirical study:\n\n\\begin{itemize}\n\n\\item\nThe \\textbf{window size} determines the number of most recent measurements contained in the examined time series subsequences. We tested four different sizes that were learned from the training gesture, including \\textbf{min}, \\textbf{max}, and \\textbf{avg} length as well as the \\textbf{mid}-point of the range. \\\\\n\n\\item\nThe \\textbf{step size} defines the gap between consecutive time series windows. As default setting we use one tenth of the window size. \\\\\n\n\\item\nFor online gesture recognition we employ the nearest neighbor classifier in combination with the DTW distance, where we evaluate 34 different Sakoe-Chiba \\textbf{band} sizes, ranging from 1 \\% to 100 \\%.\nPrior to pair-wise comparing sliding windows and training gestures, the corresponding time series should be normalized. We evaluate $\\eta$, $z$, and no \\textbf{normalization}. \\\\\n\n\\item\nThe dissimilarity \\textbf{threshold} defines the time series distance at which a sliding window and a training gesture are considered to belong to the same class. We determine the threshold for an individual class by measuring the distances between all samples of that particular class and all instances of other classes. In our empirical study we evaluate the threshold influence for: (i) one half of the minimum distance - \\textbf{HMinD}, (ii) one half of the average distance - \\textbf{HAvgD}, and (iii) one half of the midpoint distance - \\textbf{HMidD}. \\\\\n\n\\item\nThe \\textbf{filter criterion} is an essential part of our proposed approach. In our empirical study we evaluate the performance of the two filter criteria, namely the sample variance \\textbf{VAR} and the length normalized complexity estimate \\textbf{LNCE} of a time series. Both filters are tested with different factors that increase the size of the filter interval from 100 \\% to 300 \\%.\n\n\\end{itemize}\n\nFigure \\ref{fig:experiment} visualizes the online gesture recognition results for a sample time series stream processed by our proposed sliding window filter,\nafter selecting the above described model parameters with help of the recorded training gestures.\n\n\\begin{figure}\n    \\resizebox {\\textwidth} {!} {\n        \\begin{tikzpicture}\n            \\begin{axis}[\n                xmin=0,\n                xmax=2426,\n                ymin=-16,\n                ymax=16,\n                width=10*\\axisdefaultwidth,\n                height=\\axisdefaultheight,\n                xticklabels={,,},\n                yticklabels={,,}]\n                \\addplot[blue, mark=none, opacity=0.4] table[x=t, y=x] {../data/fig/experimentee_result2/exp1.dat};\n                \\addplot[red, mark=none, opacity=0.4] table[x=t, y=y] {../data/fig/experimentee_result2/exp1.dat};\n                \\addplot[green, mark=none, opacity=0.4] table[x=t, y=z] {../data/fig/experimentee_result2/exp1.dat};\n                \\addplot+[fill, opacity=0.5, red, mark=none] coordinates {(294, -16) (307, -16) (307, 16) (294, 16)} --cycle;\n                \\addplot+[fill, opacity=0.5, green, mark=none] coordinates {(307, -16) (357, -16) (357, 16) (307, 16)} --cycle;\n                \\addplot+[fill, opacity=0.5, red, mark=none] coordinates {(357, -16) (359, -16) (359, 16) (357, 16)} --cycle;\n                \\addplot+[fill, opacity=0.5, red, mark=none] coordinates {(497, -16) (508, -16) (508, 16) (497, 16)} --cycle;\n                \\addplot+[fill, opacity=0.5, green, mark=none] coordinates {(508, -16) (562, -16) (562, 16) (508, 16)} --cycle;\n                \\addplot+[fill, opacity=0.5, blue, mark=none] coordinates {(562, -16) (564, -16) (564, 16) (562, 16)} --cycle;\n                \\addplot+[fill, opacity=0.5, red, mark=none] coordinates {(712, -16) (722, -16) (722, 16) (712, 16)} --cycle;\n                \\addplot+[fill, opacity=0.5, green, mark=none] coordinates {(722, -16) (777, -16) (777, 16) (722, 16)} --cycle;\n                \\addplot+[fill, opacity=0.5, blue, mark=none] coordinates {(777, -16) (778, -16) (778, 16) (777, 16)} --cycle;\n                \\addplot+[fill, opacity=0.5, blue, mark=none] coordinates {(940, -16) (945, -16) (945, 16) (940, 16)} --cycle;\n                \\addplot+[fill, opacity=0.5, green, mark=none] coordinates {(945, -16) (1010, -16) (1010, 16) (945, 16)} --cycle;\n                \\addplot+[fill, opacity=0.5, blue, mark=none] coordinates {(1010, -16) (1023, -16) (1023, 16) (1010, 16)} --cycle;\n                \\addplot+[fill, opacity=0.5, red, mark=none] coordinates {(1310, -16) (1316, -16) (1316, 16) (1310, 16)} --cycle;\n                \\addplot+[fill, opacity=0.5, green, mark=none] coordinates {(1316, -16) (1367, -16) (1367, 16) (1316, 16)} --cycle;\n                \\addplot+[fill, opacity=0.5, red, mark=none] coordinates {(1367, -16) (1375, -16) (1375, 16) (1367, 16)} --cycle;\n                \\addplot+[fill, opacity=0.5, red, mark=none] coordinates {(1681, -16) (1689, -16) (1689, 16) (1681, 16)} --cycle;\n                \\addplot+[fill, opacity=0.5, green, mark=none] coordinates {(1689, -16) (1746, -16) (1746, 16) (1689, 16)} --cycle;\n                \\addplot+[fill, opacity=0.5, blue, mark=none] coordinates {(1746, -16) (1748, -16) (1748, 16) (1746, 16)} --cycle;\n                \\addplot+[fill, opacity=0.5, red, mark=none] coordinates {(2082, -16) (2090, -16) (2090, 16) (2082, 16)} --cycle;\n                \\addplot+[fill, opacity=0.5, green, mark=none] coordinates {(2090, -16) (2146, -16) (2146, 16) (2090, 16)} --cycle;\n                \\addplot+[fill, opacity=0.5, red, mark=none] coordinates {(2146, -16) (2147, -16) (2147, 16) (2146, 16)} --cycle;\n                \\addplot+[fill, opacity=0.5, blue, mark=none] coordinates {(2311, -16) (2388, -16) (2388, 16) (2311, 16)} --cycle;\n                \\addplot+[fill, opacity=0.5, red, mark=none] coordinates {(2297, -16) (2362, -16) (2362, 16) (2297, 16)} --cycle;\n            \\end{axis}\n        \\end{tikzpicture}\n    }\n    \\caption{Visualized results of online gesture recognition for a sample time series stream. We highlight true positives in green, false positives in red, false negatives in blue, and true negatives in transparent.\n    Although we see short false detection intervals before or after true positives, seven out of eight gestures were assigned to the correct class label.}\n    \\label{fig:experiment}\n\\end{figure}\n", "meta": {"hexsha": "ac86864cda7c6e12cbdc20c302ae032450dd6090", "size": 6700, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/evaluation/experiment.tex", "max_stars_repo_name": "GordonLesti/SlidingWindowFilter", "max_stars_repo_head_hexsha": "22c11f2912a5c523ae8ad85a849e2d0b123536ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-06-22T09:37:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-14T11:43:53.000Z", "max_issues_repo_path": "paper/evaluation/experiment.tex", "max_issues_repo_name": "GordonLesti/SlidingWindowFilter", "max_issues_repo_head_hexsha": "22c11f2912a5c523ae8ad85a849e2d0b123536ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/evaluation/experiment.tex", "max_forks_repo_name": "GordonLesti/SlidingWindowFilter", "max_forks_repo_head_hexsha": "22c11f2912a5c523ae8ad85a849e2d0b123536ec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-11T23:15:57.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-11T23:15:57.000Z", "avg_line_length": 91.7808219178, "max_line_length": 561, "alphanum_fraction": 0.6504477612, "num_tokens": 1977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.3322326474793146}}
{"text": "\\section{Comparison to other methods} \\label{sec:compare} \n\n\\begin{table}\n\\caption{Table of $\\theta_{\\rm inf}$ - $\\theta_{\\rm true}$ and uncertainties for different CIGALE setups  } \n\\begin{center} \n\\begin{tabular}{ccccc} \\toprule\nset & CIGALE A & CIGALE B & CIGALE C & CIGALE D \\\\\n$\\Delta M_{tot}$ & 0.07 & 0.09 & 0.27 & 0.05\\\\\n$M_{err}$ & 0.13 & 0.20 & 0.16 & 0.16\\\\\n$\\Delta$ Age & 1.78 & 1.59 & 1.97& 1.92\\\\\n$Age_{err}$ & 2.36 & 2.63 & 2.47 & 2.47\\\\\n$\\Delta$ Z & 0.0037 & 0.0026 & 0.0027 & 0.0027\\\\\n$Z_{err}$ & 0.0091 & 0.0085 & 0.0089 & 0.0089\\\\\n\\hline \n\\hline            \n\\end{tabular} \\label{tab:setups}\n\\end{center}\n\\end{table}\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=\\textwidth]{figs/mini_mocha_cigale.png} \n\\caption{The properties inferred from CIGALE photometry fit as a function of true properties. Configuration CIGALE A, B, C, and D on one plot.\n}\n\\label{fig:photo_cigaleALL}\n\\end{center}\n\\end{figure}\n\n", "meta": {"hexsha": "6a9c48c6df2b0859d37ba4224d77917b33d88127", "size": 930, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/paper/compare.tex", "max_stars_repo_name": "changhoonhahn/GQP_mock_challenge", "max_stars_repo_head_hexsha": "831d5423edd9955ee1bda8d41e44d30cd3c6bd4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-12-18T20:51:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T05:59:24.000Z", "max_issues_repo_path": "doc/paper/compare.tex", "max_issues_repo_name": "changhoonhahn/GQP_mock_challenge", "max_issues_repo_head_hexsha": "831d5423edd9955ee1bda8d41e44d30cd3c6bd4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44, "max_issues_repo_issues_event_min_datetime": "2020-02-20T06:02:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-13T20:00:50.000Z", "max_forks_repo_path": "doc/paper/compare.tex", "max_forks_repo_name": "changhoonhahn/GQP_mock_challenge", "max_forks_repo_head_hexsha": "831d5423edd9955ee1bda8d41e44d30cd3c6bd4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-10-04T22:25:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:05:03.000Z", "avg_line_length": 32.0689655172, "max_line_length": 142, "alphanum_fraction": 0.6537634409, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.607663184043154, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3322326462728403}}
{"text": "\\documentclass[a4paper,twocolumn]{article}\n\n\\usepackage[english]{babel}\n\\usepackage[utf8]{inputenc}\n\\usepackage{graphicx}\n\\usepackage{fullpage}\n\\usepackage{amssymb}\n\\usepackage{caption}\n\n\\newenvironment{Figure}\n  {\\par\\medskip\\noindent\\minipage{\\linewidth}}\n  {\\endminipage\\par\\medskip}\n\n\\title{Progressive Neural Networks $-$ summary}\n\\author{Matěj Nikl}\n\n\\begin{document}\n\\maketitle\n\\noindent\nProgressive Neural Networks (PNNs) are networks trying to address the task of using, transferring and not forgetting previously learned knowledge to learn yet another task, preferably with faster convergence. It retains a pool of trained models throughout training and learns connections to them to harvest potentially useful features while also learning new ones. What it means is that it has the ability to choose whether the previously learned knowledge is useful for the new task and thus to transfer it, or even to ignore it completely (by zeroing the lateral connections).\n\n    \\begin{figure}[!h]\n        \\centering\n        \\includegraphics[width=0.75\\columnwidth]{PNN.png}\n        \\caption{A three column progressive network}\n    \\end{figure}\n\n\\subsection*{Basic definition}\nA PNN starts with a single column $-$ a DNN with $L$ layers and hidden activations $h_i^{(1)} \\in \\mathbb{R}^{n_i}$, with $n_i$ the number of units at layer $i \\le L$, and parameters $\\Theta^{(1)}$ trained to convergence. When adding a second task, the parameters $\\Theta^{(1)}$ are ``frozen'' and a new column with parameters $\\Theta^{(2)}$ is instantiated (with random initialization), where layer $h_i^{(2)}$ receives input from both $h_{i-1}^{(2)}$ and $h_{i-1}^{(1)}$ via lateral connections. This generalizes to $K$ tasks as follows (biases omitted for clarity):\n\\[\n    h_i^{(k)} = f \\left( W_i^{(k)}h_{i-1}^{(k)} + \\sum_{j<k} U_i^{(k,j)} h_{i-1}^{(j)} \\right)\n\\]\nwhere $W_i^{(k)} \\in \\mathbb{R}^{n_i \\times n_{i-1}}$ is the weight matrix of layer $i$ of column $k$, $U_i^{(k,j)} \\in \\mathbb{R}^{n_i \\times n_{i-1}}$ are the lateral connections from layer $i-1$ of column $j$, to layer $i$ of column $k$ and $h_0$ is the network input. $f$ is a element-wise non-linearity, $f(x) = \\max (0, x)$ for all intermediate layers.\n\n\\paragraph{Adapters.} In practice, non-linear lateral connections called \\textit{adapters} are used. The serve both to improve initial conditioning and perform dimensionality reduction, so that the number of parameters stemming from the lateral connections is in the same order as $\\left| \\Theta^{(1)} \\right|$ as $k$ grows.\n\n\\subsection*{Principles of modularization}\nThe basic building block of PNNs is a \\textit{column}. A column is a neural network with lateral connections to all previously trained columns, each trying to solve just one task. That might encourage the thinking of a column as a potential module. However, it cannot be taken away and used on its own as a some kind of a standalone unit $-$ it always needs all of its previous columns with whom it was trained with to function properly, because it might be extremely dependent on features (knowledge) extracted from input by them. So, even though we might like to see it as a module, it definitely cannot be used that way.\n\n\n\\subsection*{Principles of growing}\nFor each new task a new column is allocated. The knowledge from all previously learned tasks has the potential to be transferred, while being protected against forgetting, because all previous columns have frozen weights. This way, the PNN can theoretically grow for as many tasks as needed (while potentially transferring the knowledge from all of the previously learned ones), however in practice, some other techniques like pruning and online compression must be used during training for the number of parameters to be reasonable.\n\n\n    \\begin{figure*}[ht]\n        \\centering\n        \\includegraphics[width=0.65\\textwidth]{2-column.png}\n        \\caption{A two column progressive network $-$ knowledge transfer}\n    \\end{figure*}\n\n    \\begin{figure*}[ht]\n        \\centering\n        \\includegraphics[width=0.9\\textwidth]{3-column.png}\n        \\caption{A three column progressive network $-$ knowledge transfer to the rightmost task}\n    \\end{figure*}\n\n    \\begin{figure*}[ht]\n        \\centering\n        \\includegraphics[width=\\textwidth]{perf.png}\n        \\captionsetup{singlelinecheck=off}\n        \\caption[trololo]{(a) Transfer matrix. Colors indicate transfer scores (clipped at 2). For progressive nets, the first column is trained on Pong, Noisy, or H-flip (table rows); the second column is trained on each of the other pong variants (table columns). (b) Example learning curves. \\\\\n        \\begin{itemize}\n            \\item \\textbf{Baseline 2} $-$ a single column, pretrained on a source task and fine-tuned on the target task (output layer only)\n            \\item \\textbf{Baseline 3} $-$ the same as baseline 2 but the whole model is fine-tuned\n            \\item \\textbf{Baseline 4} $-$ a 2 column progressive architecture, with previous columns initialized randomly and frozen\n        \\end{itemize}\n        }\n    \\end{figure*}\n\n\\end{document}\n", "meta": {"hexsha": "018fa58b0869676e48934c15cb3ed17fd7ac2fbb", "size": 5091, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "summary/1/PNN/PNN.tex", "max_stars_repo_name": "MatejNikl/incremental_learning", "max_stars_repo_head_hexsha": "57eb7d02c614d5baa5f1814b2347151cc0378b58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "summary/1/PNN/PNN.tex", "max_issues_repo_name": "MatejNikl/incremental_learning", "max_issues_repo_head_hexsha": "57eb7d02c614d5baa5f1814b2347151cc0378b58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "summary/1/PNN/PNN.tex", "max_forks_repo_name": "MatejNikl/incremental_learning", "max_forks_repo_head_hexsha": "57eb7d02c614d5baa5f1814b2347151cc0378b58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 71.7042253521, "max_line_length": 623, "alphanum_fraction": 0.7301119623, "num_tokens": 1309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.33223264627284027}}
{"text": "\\chapter{The third protocol - Computing and Comparing HD Homomorphically}\n\\label{chap:thirdProtocol}\n\n% **************************** Define Graphics Path **************************\n\\ifpdf\n\\graphicspath{{Chapter5/Figs/Raster/}{Chapter5/Figs/PDF/}{Chapter5/Figs/}}\n\\else\n\\graphicspath{{Chapter5/Figs/Vector/}{Chapter5/Figs/}}\n\\fi\n\n% **** main chapter\n\n\\section{Introduction}\n\\label{sub:introChap3}\nIn the previous chapter, we assumed that, given the Hamming Distance (HD) between the registered and queried\nbinary bitstring templates, it is infeasible for an attacker to infer or acquire any information\nabout the registered templates stored on the server. This assumption is plausible as long as the\ndistributions of the HD between registered and the queried templates is not in any way\ncorrelated to the templates themselves (analyzing these distributions is out of scope of the\nproject). However, in this chapter, we introduce our first attempt to hide this\ninformation from the server as well. Our results not only cause the protocol\nto work regardless of the aforementioned dependencies, it is also the first step we take to\nsecure the authentication protocol against an \\textit{active} server security model. Although the communication size of this variant might not\nbe suitable in practice for current network infrastructures, one can\nstill find some generic techniques used within it to be helpful while\napplying them to balance the computation time and the communication size of\nlattice-based cryptographic protocols. The contributions of this variant include:\n\\begin{itemize}\n\\item A technique to compare Hamming Distance (HD) homomorphically by computing\n  the Most Significant Bit (MSB) of a specific ciphertext.\n\\item A packing methods conversion technique to transform a ciphertext\n  encrypting a binary-encoded to a unary-encoded plaintext.\n\\item Some extensions of the Zero Knowledge Proof (ZKP) technique we used\n  in previous chapter to check the format of a message, in addition to the\n  information carried by the plaintext itself.\n\\item The combination of ZKP protocols to balance the communication size\n  trade-offs when used with lattice-based cryptosystems.\n\\end{itemize}\n\n\n\\section{Proposed Scheme}\nWe first propose a secure fingerprint authentication scheme that combines a\nSomewhat Homomorphic Encryption (SHE) with a Zero-Knowledge Proof (ZKP) to\nprovide privacy features with low FAR overhead. The scheme is secure under a\nhybrid model that assumes an active client and an honest but curious (HBC)\nserver. The server $\\server$ is considered to be HBC by assuming that it can be\naudited regularly. This scheme uses Hamming Distance (HD) as the main measure\nunit to determine the difference between two fingerprint templates. The detailed\ndescriptions of each protocol step are discussed in later sections of the\nchapter. Together with notations according to previous chapter, we use extra notations regarding encryptions as follows:\n\\begin{itemize}\n\\item $Enc^{(1)}(m)$: The BV encryption of $m$ as in previous chapter.\n\\item $Enc^{(2)}(m)$: The BV encryption of $x^{m}$: $Enc^{(2)}(m) = Enc^{(1)}(x^{m})$\n\\item $Enc^{(3)}(m)$: The LWE encryption of $m$ over $\\mathbb{Z}_{Q}$ defined in section \\ref{sec:LWESymmetric}.\n\\end{itemize}\n\n\\subsection{The protocol}\n\\label{sec:theProtocol}\n\\begin{description}\n\t\\item[Setup] The server and the user run the setup process as\n\tfollows:\n\t\\begin{itemize}\n\n\n\n\t\t% * <trung.dinh@monash.edu> 2016-10-21T13:17:43.354Z:\n\t\t%\n\t\t% replace BGV by GSW for now\n\t\t%\n\t\t% ^.\n\n\t\t\\item $\\mathcal{S}$ invokes $params_{BV} \\gets\n\t\tSGen_{BV}(1^\\lambda)$\n\t\t\\item We are currently using a BV cryptosystem\n\t\t(\\cite{brakerski2011fully}). We refer the reader to section\n\t\t\\ref{sec:BVScheme} for details of $params_{BV}$, the public\n\t\tkey $pk$, the private key $sk$, as well as the\n\t\toperations of the\n\t\tcryptosystem.\n\t\t\\item A user $\\mathcal{U}_k$ invokes $(pk_k,sk_k) \\gets\n\t\tUGen_{BGV}(params_{BGV})$ and makes $pk_k$ publicly\n\t\tavailable to $\\mathcal{S}$.\n\n\n\n\n\t\t\\iffalse\n\t\t\\item $\\mathcal{S}$ invokes $params_{GSW} \\gets\n\t\tSGen_{GSW}(1^\\lambda)$\n\t\t\\item We are currently using GSW cryptosystem\n\t\t(\\cite{gentry2013homomorphic}).\n\t\tWe refer the reader to section\n\t\t\\missref{} for details of $params_{GSW}$, the public\n\t\tkey $pk$, the private key $sk$, as well as the\n\t\thomomorphic operations of the\n\t\tcryptosystem.\n\t\t\\item A user $\\mathcal{U}_k$ invokes $(pk_k,sk_k) \\gets\n\t\tUGen_{GSW}(params_{GSW})$ and make $pp_k$ publicly\n\t\tavailable to $\\mathcal{S}$\n\t\t\\fi\n\n\n\t\\end{itemize}\n\t\\item[Enrolment] The enrolment process runs as follows.\n\t\\begin{itemize}\n\t\t\\item $\\mathcal{U}$ uses a specific sensor and algorithm to\n\t\textract his biometric template $X$. $\\mathcal{U}$\n\t\tencrypts $X$ with his public key $pk_k$ to get\n\t\t$T_k = Enc^{(1)}(X)$.\n\t\t\\item $\\mathcal{U}$ sends $(k,T_k)$ to $\\mathcal{S}$.\n\t\tNoted that $k$\n\t\tis used as an identity index for $\\mathcal{U}$.\n\t\t\\item $\\mathcal{S}$ stores a tuple $(k, T_k)$ as a\n\t\trecord.\n\t\\end{itemize}\n\t\\item[Authentication] The authentication process for a user\n\t$\\mathcal{U}_k$ is as follows.\n\t\\begin{enumerate}\n\t\t\\item $\\user_k$ extracts his query template $Y$. He\n\t\tencrypts $Y$ with his public key $pk_k$ to obtain\n\t\t$Q_k = Enc^{(1)}(Y)$.\\label{protocol:step1}\n              \\item $\\user_k$ sends $(k,Q_k)$ to $\\server$ and runs\n                $\\mathbf{ZKPValidEnc((Q_k,pk_k),(Y,sk_k))}$ to prove the\n                validity of $Y$.\\label{protocol:step2} was detailed in Chapter \\ref{chap:firstProtocol}.\n              \\item $\\server$ locates the record $(k,T_k)$ and computes \\ the\n                encrypted Hamming Distance $C_{HD} = Enc^{(1)}( HD)$ of $X$ and\n                $Y$, using the homomorphic operation discussed in Section \\ref{sec:firstProcBGV}.\n\t\t$$C_{HD} \\gets\n\t\t\\textbf{EvalDistance}(T_k,Q_k).$$\\label{protocol:step3}\n\t\t\\item $\\server$ masks the $C_{HD}$ by sampling $r\n\t\t\\randomsample \\mathcal{P}$\n\t\tand performs one homomorphic addition to get\n\t\t$C_{HD'} = Enc^{(1)}(HD + r) \\gets Enc^{(1)}(HD) + Enc^{(1)}(r)$.\n\t\tThe result ciphertext is sent to $\\user_k$.\\label{protocol:step4}\n\t\t\\item $\\user_k$ uses his private key $sk_k$ to decrypt $C_{HD'}$\n\t\tand sends\n\t\tthe re-encryption $C_{HD'_0} = Enc^{(1)}(HD',0,0,\\dots,0)$ back to $\\server$.\n\t\t$\\user_k$ also decomposes the plaintext result\n\t\t$HD' = HD+r$ into its binary representation:\n\t\t\\[\n\t\tHD' = b_0 + b_12^1 + \\dots + b_l2^{l-1}\n\t\t\\]\n\t\tand sends $C_i = Enc^{(1)}(b_i)$ to $\\server$\n\t\tfor $i = 0, \\dots, l-1$.\\label{protocol:step5}\n\n\t\t\\item $\\user_k$ and $\\server$ run the $\\mathbf{ZKPUnpack}(C_{HD},C_{HD_0'})$ and\n\t\t$\\mathbf{ZKPBinDecomp}(C_{HD_0'},C_i)$\n\t\tprotocols to convince the server that\n\t\t$\\user_k$ did follow the protocol transcript correctly. This is detailed\n\t\tin section\n\t\t\\ref{sec:ZKPReencrypt}.\n\t\t\\label{protocol:step6}\n\t\t\\item $\\server$ computes $C_{HD}'' = Enc^{(2)}(2^l + t - HD) \\gets\n\t\tEnc^{(2)}(2^l + t) - Enc^{(2)}(HD+r) + Enc^{(2)}(r)$, where\n\t\t$Enc^{(2)}(HD + r)$ is computed by $\\mathbf{ToUnary}(C_i)$. We note that\n\t\t$Enc^{(2)}$ is the ``unary'' mode of encryption with the message\n\t\tencoded in the exponent of the polynomial, which allows the\n\t\tMost significant bit (MSB)\n\t\textraction on the ciphertext (this is detailed section \\ref{sec:binToUna} \\label{protocol:step7}).\n\t\t\\item $\\server$ does $Enc^{(3)}(res) \\gets\n\t\t\\mathbf{MSBExtract}(C_{HD}'')$, this is the ciphertext\n\t\tof the authentication result, which is sent to $\\user_k$. This\n\t\tis described in section \\ref{sec:MSBExtract}.\n\t\t\\label{protocol:step8}\n\t\t\\item $\\user_k$ decrypts the result $res$ and sends it to $\\server$\n\t\t(it will be either \\textbf{Accepted} or \\textbf{Rejected} by $\\server$).\n\t\t$\\user_k$ also runs another proof $\\mathbf{ZKPCorrectDec}(res)$\n\t\tto convince $\\server$ that he\n\t\tdid follow the protocol honestly (Section \\ref{sec:ZKPReencrypt}).\\label{protocol:step9}\n\n\n\n\n\t\t%$\\server$ also computes\n\t\t%the encryption of the authentication result $Enc(\\Delta < \\tau)$\n\t\t%using another homomorphic operation $Enc(\\Delta \\stackrel{?}{<}\n\t\t%\\tau) \\gets \\textbf{EvalRes}(pk_k, \\tau, Enc(\\Delta))$.\n\t\t%\\item $\\server$ sends $Enc(\\Delta \\stackrel{?}{<} \\tau)$ to $\\user_k$.\n\t\t%$\\user_k$ uses his private key $sk_k$ to decrypt the plaintext $\n\t\t%res \\gets \\Delta\n\t\t%\\stackrel{?}{<} \\tau$.\n\n\n\n\t\t% * <trung.dinh@monash.edu> 2016-10-21T13:15:14.957Z:\n\t\t%\n\t\t% we agreed to do this later, for now, we change back to GSW instead of BGV. Later when we apply MCC we will consider bringing these garble circuit back.\n\t\t%\n\t\t% ^.\n\t\t%\\item $\\server$ masks the computed distance with a random\n\t\t%value $R$, using Homomorphic addition operation:\n\t\t%$Enc(\\Delta + R) \\gets EvalAdd(pk_k, Enc(\\Delta),\n\t\t%Enc(R))$.\n\t\t%\\item $\\server$ builds a garbled circuit $\\textbf{GC}$ to evaluate\n\t\t%the bit value of the comparison between a plaintext $\\Delta$\n\t\t%against a threshold\n\t\t%$\\tau$ privately $(\\Delta \\stackrel{?}{<} \\tau) \\gets\n\t\t%\\textbf{GC}(k_{\\Delta + R}, k_R)$. We note that\n\t\t%$k_{\\Delta + R}$ and $k_R$ are cryptographic keys input\n\t\t%to garble circuit protocol. We refer the reader to\n\t\t%section \\missref{} for details of garble circuit\n\t\t%protocols.\n\t\t%\\item $\\server$ sends $Enc(\\Delta + R)$ and $\\textbf{GC}$ to $\\user_k$, $\\user_k$\n\t\t%uses his private key $sk_k$ to decrypt $\\Delta+R$.\n\t\t%\\item $\\user_k$ derives $k_{\\Delta + R}$ to be use as the\n\t\t%first input to $\\textbf{GC}$ and $\\user_k$ runs Oblivious Transfer protocol\n\t\t%$\\textbf{OT}$ to obtain $k_R$ from $\\server$ privately.\n\t\t%$\\textbf{OT}$ is discussed in section\n\t\t%\\missref{}.\n\t\t%\\item $\\user_k$ evaluates $(\\Delta \\stackrel{?}{<} \\tau) \\gets\n\t\t%\\textbf{GC}(k_{\\Delta + R}, k_R)$ and sends the result\n\t\t%$res$ to $\\server$.\n\n\n\n\n\n\t\t%\\item $\\user_k$ convinces $\\server$ that he did follow the\n\t\t%protocol honestly using Zero Knowledge Proof protocol\n\t\t%$\\textbf{ZKP}$. This protocol is discussed in section\n\t\t%\\missref{}.\n\n\t\\end{enumerate}\n\tThe proposed scheme satisfies the security notions defined in Sect. \\ref{sec:syntaxModel}.\n\t\\begin{theorem}\n\t\t\\label{theo:server}\n\t\tUnder the IND-CPA security of a BV cryptosystem, and the zero-knowledge\n\t\tproperty of the Stern protocol, the proposed scheme satisfies an (Honest But Curious) Server Privacy's Security.\n\t\\end{theorem}\n\t\\begin{theorem}\n\t\t\\label{theo:client}\n\t\tUnder the IND-CPA security of a BV cryptosystem and the soundness\n\t\tproperty of the underlying Stern protocol, the proposed scheme satisfies Impersonation Security. Concretely, for $\\delta>0$, the protocol is $(q,c)$-secure against impersonation with $c \\leq c(\\delta) + 3 \\cdot c_1$, assuming the underlying non-private biometric protocol has impersonation probability $\\varepsilon_{bio}$ and the underlying Stern ZK protocols have knowledge errors $\\eps_{ZK1},\\ldots,\\eps_{ZK4}$ such that $q(\\varepsilon_{ZK1}+\\varepsilon_{ZK2} +\n\\varepsilon_{ZK3} + \\varepsilon_{ZK4}) + \\delta \\leq c_1 \\cdot \\varepsilon_{bio}$, $c(\\delta) = 2 e^{1+2\\delta}$, and the condition $\\sigma/r_0 \\geq 4 \\pi k n q$ holds, with $k = 1 + \\sqrt{1/\\pi \\ln(2nq/\\delta)}$ and $r_0$ being an upper bound on the size of the noise in $C_{HD}$.\n\t\\end{theorem}\n\n\\end{description}\n\n\\begin{figure}[htbp!] \n  \\centering \\procedure{THE THIRD PROTOCOL}{\n    \\textbf{Client} \\> \\> \\textbf{Server}\\pclb\n    \\pcintertext[dotted]{Enrolment}\\\\\n    \\text{Extract } \\mathbf{x} \\randomsample D_k \\> \\> \\\\\n    T_k = Enc^{(1)}(\\mathbf{x},\\pk) \\> \\sendmessageright*{(k, T_k)}\n    \\> \\text{Persist $(k,T_{k})$}\\pclb\n    \\pcintertext[dotted]{Authentication}\\\\\n    \\text{Extract } \\mathbf{y} \\randomsample D_k \\> \\> \\\\\n    Q_k = Enc^{(1)}(\\mathbf{y},\\pk) \\> \\sendmessageright*{(k, Q_k)}\n    \\> \\\\\n    \\> \\sendmessageright*{\\mathbf{ZKPValidEnc}} \\> C_{HD} \\gets \\mathbf{EvalDistance}(T_k, Q_k)\\\\\n    \\> \\sendmessageleft*{C_{HD'}} \\> C_{HD'} \\gets Enc^{(1)}(HD,e_0) + Enc^{(1)}(r,e_r)\\\\\n    HD' \\gets Dec(C_{HD'},\\sk) \\> \\> \\\\\n    C_{HD'_0} \\gets Enc^{(1)}(HD', 0, \\dots, 0) \\> \\sendmessageright*{C_{HD'_0}} \\> \\\\\n    HD' = b_0 + b_1 2 + \\dots + b_l 2^{l-1} \\> \\> \\\\\n    C_i \\gets Enc^{(1)}(b_i) \\> \\sendmessageright*{C_i} \\> \\\\\n    \\> \\sendmessageright*{\\mathbf{ZKPUnpack}(C_{HD}, C_{HD'_0})} \\> \\\\\n    \\> \\sendmessageright*{\\mathbf{ZKPBinDecomp}(C_{i}, C_{HD'_0})} \\> C''_{HD} \\gets Enc^{(2)}(2^t + \\tau - HD)\\\\\n    \\> \\sendmessageleft*{C_{res}} \\> C_{res} = Enc^{(3)}(res) \\gets \\mathbf{MSBExtract}(C''_{HD})\\\\\n    res = Dec(C_{res}) \\> \\sendmessageright*{\\mathbf{ZKPCorrectDec}(res)} \\>\n    }\n  \\caption{The Third Protocol}\n  \\label{fig:thirdProtocol}\n\\end{figure}\n\n\n\\section{The Homomorphic tools}\n\\subsection{Extracting the Most Significant Bit homomorphically}\n\\label{sec:MSBExtract}\nWe observe that \\(HD < \\tau \\iff MSB(2^{l} + \\tau - HD) = 1\\), where \\(l\\) is\nthe bit-length of \\(HD\\) and MSB denotes the Most Significant Bit. This is our\nattempt to compare Hamming Distance homomorphically, the idea is to let the\nserver compute homomorphically the ciphertext of \\(MSB(2^{l} + \\tau - HD)\\),\nthen having the client to decrypt it and to send back the authentication result\nwith a zero knowledge proof. This section discusses a variant of the technique\nfrom \\cite{ducas2015fhew} to efficiently compute the MSB of the plaintext $M$ given\n$Enc(M)$, we adapt this technique to work with BGV encryption rather than GSW encryption used in \\cite{ducas2015fhew}. The main idea comes from the way we encode the message $M$ in ``unary'' form before the\nencryption.\n\nGiven $M \\in \\mathbb{Z}_{2n}$, we observe that\n\\[\n  \\begin{cases}\n    MSB(M) = 0 \\iff M \\in [0, n)\\\\\n    MSB(M) = 1 \\iff M \\in [n, 2n)\n  \\end{cases}\n\\]\n\nAssume that we encrypt $M$ using the SHE scheme (section\n\\ref{sec:BVScheme}). With the message space $R_t$ and assuming that $2n < t < q$,\nwe can encode $M$ as a ring element $m \\in R_t$ as follows\n\\[\n  m(x) = 0x^0 + 0x^1 + \\dots + 1x^M + \\dots + 0x^{n-1}\n  \\ \\textnormal{if} \\ M \\in [0,n)\n\\]\nor, due to $x^n = -1$ in $R_q$, we can also encode M as\n\\[\n  m(x) = 0x^0 + 0x^1 + \\dots - 1x^M + \\dots + 0x^{n-1}\n  \\ \\textnormal{if} \\ M \\in [n,2n)\n\\]\nThe ciphertext $Enc^{(2)}(M)$ has this form\n$(\\mathbf{c} = \\mathbf{p_0}\\mathbf{u} + t\\mathbf{g} + \\mathbf{m}, \\mathbf{c'} =\n\\mathbf{p_1}\\mathbf{u} + t\\mathbf{f})$, where $(\\mathbf{p_0}, \\mathbf{p_1})$ is\nthe public key and\n$\\mathbf{u}, \\mathbf{f}, \\mathbf{g} \\randomsample \\chi_{\\alpha q}$.  We denote\n$ rot({\\textbf{c}}) \\in \\mathbb{Z}_q^{n\\times n}$ as being an anti-circulant\nsquare matrix, whose first column is $\\mathbf{c}$, the other columns being the\ncyclic rotations of $\\mathbf{c}$ with the cycled entries negated\n\\[\n  rot({\\mathbf{c}})=\n  \\begin{bmatrix}\n    c_0 & -c_{n-1} & -c_{n-2} & \\dots\\\\\n    c_1 & c_0 & -c_{n-1} & \\dots\\\\\n    \\dots & \\dots & \\dots & \\dots\\\\\n    c_{n-1} & c_{n-2} & c_{n-3} & \\dots\n  \\end{bmatrix}\n\\]\nIt's easy to see that $rot(\\mathbf{c}\\mathbf{u}) = rot(\\mathbf{c})\n\\vec{u}$. Let $rot(\\mathbf{c})[0]$ to be the first column of $rot(\\mathbf{c})$.\n\n\\begin{lemma}\\label{lemma:bitToBin}\n\tGiven $M \\in Z_{2n}$ and $(\\mathbf{c},\\mathbf{c'}) = Enc^{(2)}(M)$ as the first level ciphertext of $M$ from the BV scheme, let $\\vec{1} = \\{1,1,\\dots,1\\} \\in \\mathbb{Z}^n$. The transformed ciphertext $(l, l') \\leftarrow (\\vec{1}\n\trot({\\mathbf{c}})[0], \\vec{1}\n\trot({\\mathbf{c'}})) \\in (\\mathbb{Z}_Q\n\t, \\mathbb{Z}_Q^n)$ encrypts the MSB information of $M$ under $Enc^{(3)}$.\n\\end{lemma}\n\n\\begin{algorithm}\n  \\caption{Most Significant bit extraction}\\label{alg:MSBExtract}\n  \\hspace*{\\algorithmicindent} \\textbf{Input:} $\\mathbf{c} = Enc^{(2)}(M)$ \\\\\n  \\hspace*{\\algorithmicindent} \\textbf{Output: $EncLWE((-1)^{MSB(M)})$} \n  \\begin{algorithmic}[1]\n    \\Procedure{MSBExtract}{$\\mathbf{c}$} \n    \\State $allOne = \\{1,\\dots,1\\}$\n    \\State $rot_{c_0} \\gets rot(c_0)$\n    \\State $lwe_0 \\gets allOne \\cdot rot_{c_0}[0]$\n    \\State $rot_{c_1} \\gets rot(c_1)$\n    \\State $lwe_1 \\gets allOne \\cdot rot_{c_1}$\n    \\State \\textbf{return} $(lwe_0,lwe_1)$\n    \\EndProcedure\n  \\end{algorithmic}\n\\end{algorithm}\n\n\n\\begin{proof}\n\tThe following is the case:\\\\\n\t\\begin{align*}\n\t\\vec{1} \\cdot rot(\\mathbf{c})[0] \\in \\zzq &= \\vec{1}\\overrightarrow{\n\t\t\\mathbf{p_0}\\mathbf{u} + t\\mathbf{g} + \\mathbf{m}}\\\\\n\t&= \\vec{1}\\cdot\\overrightarrow{p_0u} +t\\vec{1}\\cdot\\vec{g} +\\vec{1}\\cdot\\vec{m}\\\\\n\t&= -\\vec{1}(rot(p_1s)\\vec{u} +t.rot(e)\\vec{u}) + t\\vec{1}\\cdot\\vec{g} + (-1)^{MSB(M)}\\\\\n\t&= -\\vec{1}rot(p_1)\\vec{u}\\vec{s} - t.rot(e)\\vec{u} + t\\vec{1}\\cdot\\vec{g} + (-1)^{MSB(M)}\\\\\n\t\\end{align*}\n\tProvided that $\\mathbf{c'} = \\mathbf{p_1}\\mathbf{u} + t\\mathbf{f}$, the decryption $\\langle(l,l'),(1,\\mathbf{s})\\rangle \\mod t$ is $\\pm1$.\n\tThis implies the MSB information of M as discussed. We use here the relation $\\vec{1}\\cdot \\vec{m} = (-1)^{MSB(M)}$ thanks to the ``unary'' encoding of M discussed previously.\n\\end{proof}\n\n\\subsection{Converting from binary-encoded to unary-encoded plaintext}\n\\label{sec:binToUna}\nThis section discusses a linear transformation to map a message $b \\in \\{0,1\\}$\nonto a message $x^{jb}$ for $j \\geq 1$. Let $T: cx + d = y$ be the linear transformation. We want $T$ to map $0 \\rightarrow x^{j0} $ and\n$1 \\rightarrow x^j$, or\n\\[\n  \\begin{cases}\n    c.0 + d = 1\\\\\n    c + d = x^j\n  \\end{cases}\n  \\Leftrightarrow\n  \\begin{cases}\n    c = x^j - 1\\\\\n    d = 1\n  \\end{cases}\n\\]\nDue to the homomorphism property of BV cryptosystems , we can apply\n$T$ in the ciphertext domain to obtain $Enc(x^{jb})$ given $Enc(b)$,\nfor $b \\in \\{0,1\\}$:\n\\begin{align}\n  \\label{eq:encBitConvert}\n  Enc^{(2)}(j.b) = Enc^{(1)}(x^{jb}) &= Enc^{(1)}(c)Enc(b) + Enc^{(1)}(d) \\nonumber \\\\\n              &= Enc^{(1)}(x^j - 1)Enc^{(1)}(b) + Enc^{(1)}(1)\n\\end{align}\nFrom the implementation point of view, this operation can be done faster\nby ensuring $\\mathbf{u}, \\mathbf{f}, \\mathbf{g} \\gets 0$ instead of sampling them from\n$\\chi$ during $Enc(x^j -1)$ and $Enc(1)$, which results in $Enc^{(1)}(x^j -1) = (x^j - 1, 0)$ and $Enc^{(1)}(1) = (1,0)$. These are still valid encryptions and will not affect the correctness of Eq. (\\ref{eq:encBitConvert}).\n\nThis submodule is used in our protocol at authentication step\n\\ref{protocol:step7}. Recall that the server needs to compute $Enc^{(2)}(HD')$,\nwhich is the encryption of $HD'$ in the ``unary'' mode of encoding (the message is\nencoded in the exponent instead of in the coefficient of the polynomial). Given the encryptions $Enc(b_{i})$ of the bits $b_{i}$ of $HD' = \\sum_{j = 0}^{l -1} b_{j}2^{j}$\n, the server can convert $Enc(b_{j})$ to $Enc(2^{i}b_{i})$\n$Enc(x^{jb})$ and perform\n\\[\n  Enc^{(2)}(HD') = Enc^{(1)}(x^{HD'}) = \\prod_{i=0}^{l-1}Enc^{(1)}(x^{b_i2^i})\n\\]\nNote that this operation involves $log(l)$ levels of homomorphic multiplication, where\n$l$ is the bit length of the Hamming Distance.\n\\begin{algorithm}\n  \\caption{Binary to Unary ciphertext}\\label{alg:ToUnary}\n    \\hspace*{\\algorithmicindent} \\textbf{Input:} $\\mathbf{c_{i}} = Enc(b_{i})$ \\\\\n  \\hspace*{\\algorithmicindent} \\textbf{Output:} $HD$\n  \\begin{algorithmic}[1]\n    \\Procedure{ToUnary}{$\\mathbf{c_i}$}\n    \\For{$i = 0, \\dots, l-1$}\n    \\State let $j = 2^{i}$\n    \\State let $\\mathbf{hd_i} \\gets (x^j - 1,0)\\times \\mathbf{c_i} + (1,0)$\n    \\EndFor\n    \\State let $\\mathbf{hd} \\gets \\mathbf{hd}_0 \\times \\mathbf{hd}_1 \\times \\dots\n    \\times \\mathbf{hd}_{l-1}$\n\n\n    \\State \\textbf{return} $\\mathbf{hd}$\n    \\EndProcedure\n  \\end{algorithmic}\n\\end{algorithm}\n\n\\section{The Zero Knowledge Tools}\n\\label{sec:zkptools}\n\\subsection{ZKPoPK of Regev Cryptosystem}\n\\label{sec:zkpRegev}\nIn this section, we first review an application of the \\cite{ling2013improved} technique to apply ZKPoPK on Regev Cryptosystems, then we elaborate on the variants to be used in the protocol.\nGiven parameters $q, m, n, t, \\chi$ of a typical LWE-based cryptosystem, we can describe a variant of Regev's system as follows:\n\\begin{description}\n\\item [Kengen.] A secret key $\\vec{s}$ can be chosen from $\\chi^n$. The public key is then generated as\n  $pk = (p_0, p_1) = (\\mathbf{A}, \\mathbf{A}\\vec{s} + t\\vec{e})$. Where $\\mathbf{A} \\randomsample \\mathbb{Z}_q^{m \\times n}$\n  and $\\vec{e} \\randomsample \\chi^n$\n\\item [Encrypt.] Given a message $M \\in \\mathbb{Z}_t$, the ciphertext $C$ is computed by first sampling a random\n  vector $\\vec{r} \\in \\chi^n$ and setting\n  $C = (c_0, c_1) = (p_0\\vec{r}, p_1\\vec{r} + M)$\n\\item [Decrypt.] Given a ciphertext $C = (c_0, c_1)$, the message $M$ can be recovered by computing $M = c_1 - c_0\\vec{s} \\mod t$\n\\end{description}\nIn \\cite{ling2013improved}, the ZKPoPK was attained by proving the encryption relation\n\\begin{align*}\n  R_{Regev}^{q,m,n,t,\\chi} = \\{ ((p_0,p_1),(c_0,c_1),\\vec{r}||M) \\in (\\mathbb{Z}_q^{m \\times n} \\times \\mathbb{Z}_q^{m})\n  \\times (\\mathbb{Z}_q^n \\times \\mathbb{Z}_q) \\times \\mathbb{Z}_q^{n+1} : \\\\\n  (c_0 = p_0\\vec{r}) \\land (c_1 = p_1\\vec{r} + M) \\}\n\\end{align*}\n\nLet $\\mathbf{A}' = \\begin{bmatrix}\n  p_1, 1\\\\\n  p_0, 0\n\\end{bmatrix}\n$, and $\\mathbf{y} = \\begin{bmatrix}\n  c_1\\\\c_0\n\\end{bmatrix}$ be public parameters in the proof and\nlet $\\mathbf{x} = \\begin{bmatrix}\n  \\vec{r}\\\\\n  M\n\\end{bmatrix}$ be the $Prover$'s witness. We observe that\n$\\mathbf{A'}\\mathbf{x}= \\mathbf{y} \\mod q$, that is, $\\mathbf{x}$ is a solution\nto the ISIS problem defined by $(\\mathbf{A'},\\mathbf{y})$ and that we can use\nthe \\textbf{SternExt} protocol to obtain an efficient\nZKPoPK. This works in a symmetric key setting, where the $Prover$ knows the\nrandom $\\vec{r}$ to use as his witness. In our context, the client does not know\nthat $\\vec{r}$ as encryption was set by the server. Following the decryption\nequation:\n\\begin{align*}\n  c_1 - c_0\\vec{s} &= p_1\\vec{r} + M - p_0\\vec{r}\\vec{s} \\\\\n                   &= \\mathbf{A}\\vec{s}\\vec{r} + t\\vec{e}\\vec{r} + M - \\mathbf{A}\\vec{r}\\vec{s}\\\\\n                   &= t\\tilde{e} + M,\n\\end{align*}\nwe can write out the decryption relation as\n\\begin{align}\n  \\label{eq:RegevPub}\n  R_{Regev,dec}^{q,m,n,t,\\chi} = \\{ ((p_0,p_1),(c_0,c_1),\\vec{s},\\vec{e},\\tilde{e}, M) \\in (\\mathbb{Z}_q^{m \\times n} \\times \\mathbb{Z}_q^{m})\n  \\times (\\mathbb{Z}_q^n \\times \\mathbb{Z}_q) \\times \\chi^n \\times \\chi^n \\times \\chi \\times \\zzq :\\\\ \\nonumber\n  (p_1 = p_0\\vec{s} + t\\vec{e}) \\land (c_1 = c_0\\vec{s} + t\\tilde{e} + M) \\}\n\\end{align}\nIn this situation, we can let $\\mathbf{A'} = \\begin{bmatrix}\n  c_0, t, 0 , 1 \\\\p_0, 0, t, 0\n\\end{bmatrix}\n$\nand $\\mathbf{y} = \\begin{bmatrix}\n  c_1\\\\p_1\n\\end{bmatrix}$\nbe the public parameters and let $\\mathbf{x} = \\begin{bmatrix}\n  \\vec{s}\\\\ \\tilde{e}\\\\ \\vec{e}\\\\ M\n\\end{bmatrix}\n$, further applying the \\textbf{SternExt} to obtain the ZKPoPK  . We note that the two separate rows of $\\mathbf{A'}$ prove the two\nseparate relations in (\\ref{eq:RegevPub}): The $Prover$ needs to prove that he knows a secret $\\vec{s}$ that can decrypt\n$(c_0,c_1)$; he also needs to prove that the secret key $\\vec{s}$ is also the one corresponding to the public key\n$(p_0, p_1)$.\n\n\n\\subsection{ZKPoPK of BV cryptosystem}\n\\label{sec:ZKPBV}\nIn this section, we discuss ZKPoPK for a ring variant of the Regev scheme discussed above, which is the BV system that we use in\nour application context (section \\ref{sec:BVScheme}). We will refer to this\nproof as $\\mathbf{ZKPValidEnc}$. Recall that our public key is a pair of ring elements $pk = (\\mathbf{p_0},\n\\mathbf{p_1})$, where $\\mathbf{p_0}, \\mathbf{p_1} \\in \\rrq$ and $\\mathbf{p_1}\\mathbf{s}+ t\\mathbf{e} = -\\mathbf{p_0} $. This\nis one of the relation that the client will need to prove later on. Next, given a ciphertext $c = (\\mathbf{c_0}, \\mathbf{c_1})$, the original\nplaintext $\\mathbf{m} \\in R_{t}$ can be recovered by $\\mathbf{m} = \\mathbf{c_0} + \\mathbf{c_1}\\mathbf{s} \\mod t$ (spelled out as $\\mathbf{c_1}\\mathbf{s} + \\mathbf{c_0} = \\mathbf{m} + t\\mathbf{e'}$, or $\\mathbf{c_1}\\mathbf{s} -t\\mathbf{e'} -\\mathbf{m} = -\\mathbf{c_0}$).\nIn summary, the relation required for the ZKPoPK is:\n\\begin{align}\n  \\label{eq:BVRel}\n  R_{BV}^{Q,n,t,\\chi} = \\{((\\mathbf{c_0}, \\mathbf{c_1}),(\\mathbf{p_0}, \\mathbf{p_1}), \\mathbf{s},\\mathbf{e'}, \\mathbf{e}, \\mathbf{m} \\in\n  (\\rrq \\times \\rrq) \\times (\\rrq \\times \\rrq)  \\times \\chi^n \\times \\chi^n \\times \\chi^n \\times R_t:\\\\ \\nonumber\n  (\\mathbf{p_1}\\mathbf{s} + t\\mathbf{e} = -\\mathbf{p_0} ) \\land (\\mathbf{c_1}\\mathbf{s} - t\\mathbf{e'} -\\mathbf{m} = -\\mathbf{c_0})\n  \\}\n\\end{align}\nWe can proceed in a way similar to what appears in section \\ref{sec:zkpRegev}, where we tried to derive the ISIS relation ($\\mathbf{A}\\mathbf{x} = \\mathbf{y} \\mod q$)\nfrom the above relation and obtain the ZKP accordingly.\nThe matrix $\\mathbf{A}$ should be derived from $\\mathbf{T}= \\begin{bmatrix}\n  \\mathbf{c_1}, -t, 0, -1\\\\ \\mathbf{p_1}, 0, t, 0\n\\end{bmatrix}$ in order to obtain (\\ref{eq:BVRel}). Note that with $\\mathbf{c_1},\\mathbf{p_1} \\in \\rrq$, we can construct $\\mathbf{A}$ by\nreplacing from $\\mathbf{T}$: $\\mathbf{c_1}$ and $\\mathbf{p_1}$ are replaced by $rot(\\mathbf{c_1})$ and $rot(\\mathbf{p_1})$, constants\nare replaced by the product of the themselves by the identity matrix $\\mathbf{I}$. Recall that $ rot({\\textbf{c}}) \\in\n\\mathbb{Z}_q^{n\\times n}$ is defined to be an anti-circulant\nsquare matrix, whose first\ncolumn is $\\mathbf{c}$, the other columns being the cyclic rotations of\n$\\mathbf{c}$ with the cycled entries negated\n\\[\n  rot({\\mathbf{c}})=\n  \\begin{bmatrix}\n    c_0 & -c_{n-1} & -c_{n-2} & \\dots\\\\\n    c_1 & c_0 & -c_{n-1} & \\dots\\\\\n    \\dots & \\dots & \\dots & \\dots\\\\\n    c_{n-1} & c_{n-2} & c_{n-3} & \\dots\n  \\end{bmatrix}\n\\]\nSo, the matrix $\\mathbf{A}$ is of the following form:\n\\begin{align}\n  \\label{matrix:ZKP}\n  \\begin{bmatrix}\n    \\SquareBox[draw=black, minimum size=35]{$rot(\\mathbf{c_1})$}\n    \\SquareBox[draw=black, minimum size=35]{$-t\\mathbf{I}$}\n    \\SquareBox[draw=black, minimum size=35]{$\\mathbf{0}$}\n    \\SquareBox[draw=black, minimum size=35]{$\\mathbf{-I}$}\\\\\n    \\SquareBox[draw=black, minimum size=35]{$rot(\\mathbf{p_1})$}\n    \\SquareBox[draw=black, minimum size=35]{$\\mathbf{0}$}\n    \\SquareBox[draw=black, minimum size=35]{$t\\mathbf{I}$}\n    \\SquareBox[draw=black, minimum size=35]{$\\mathbf{0}$}\n  \\end{bmatrix}\n\\end{align}\n\nBy constructing the matrix $\\mathbf{A}$ this way, we can let $\\mathbf{x} = \\begin{bmatrix}\n  \\mathbf{s}\\\\\\mathbf{e'}\\\\\\mathbf{e}\\\\\\mathbf{m}\n\\end{bmatrix}$,  $\\mathbf{y} = \\begin{bmatrix}\n  -\\mathbf{c_0}\\\\-\\mathbf{p_0}\n\\end{bmatrix}$ and come up with the original ISIS relation $\\mathbf{A}\\mathbf{x} = \\mathbf{y} \\mod Q$. Again,\nwe can use the \\textbf{SternExt} protocol (section \\ref{append:Stern}) to obtain the ZKPoPK with $\\mathbf{x}$ being\nthe $Prover$'s witness and $\\mathbf{A}, \\mathbf{y}$ being the public parameters (Algorithm \\ref{alg:ZKPBV}).\n\n\\begin{algorithm}\n  \\caption{ZKPoPK for BV}\\label{alg:ZKPBV}\n  \\begin{algorithmic}[1]\n    \\Procedure{ZKPBV}{$(\\mathbf{c}, pk),(\\mathbf{m, s, e, e'}))$}\n    \\State $rot_{c_1} \\gets rot(\\mathbf{c_1})$\n    \\State $rot_{p_1} \\gets rot(\\mathbf{pk_1})$\n    \\State let I be the $n \\times n$ identity matrix\n    \\State let Z be the $n \\times n $ zero matrix\n    \\State $\\mathbf{A} \\gets ((rot_{c_1},-tI, Z, -I),(rot_{p_1}, Z, tI,Z)) $\n    \\State $\\mathbf{x} \\gets (\\mathbf{s, e', e, m})$\n    \\State $\\mathbf{y} \\gets (\\mathbf{-c_0, -pk_0})$\n    \\State \\textbf{Return} $\\mathbf{SternExt(A,x,y)}$\n    \\EndProcedure\n  \\end{algorithmic}\n\\end{algorithm}\n\n\n\\subsection{ZKP of plaintext with zero coefficients}\nThis section extends the previous proof with several submodules. Firstly, we\nneed a proof to convince the server that our ciphertext encrypts the message of the form $\\mathbf{m(x)} =\n0 + m_1x^1 + m_2x^2 + \\dots + m_{n-1}x^{n-1}$. Next, we need another proof to convince about the knowledge of encryption of\n$\\mathbf{m(x)} = m_0 + 0x^1 + 0x^2 + \\dots + 0x^{n-1}$. We also use some other proofs for messages containing only 1s or 0s. In other words, we want the $Prover$ to convince the $Verifier$\nabout the format correctness of the plaintext, in addition to asserting  knowledge of the plaintext itself.\n\n\\begin{description}\n\\item[Proving $\\mathbf{m}=\\sum_{i = 0}^l(m_ix^i) \\land m_0 = 0$ \\textbf{(ZKPExt1)}.]\n  If and only if the $Prover$ P has the message $\\mathbf{m}$ in this format, he can compute:\n  \\begin{align*}\n    rot(\\mathbf{c_0})\\mathbf{s} -t\\mathbf{Ie'} - \\begin{bmatrix}\n      1\\\\\n      0\\\\\n      \\dots\\\\\n      0\n    \\end{bmatrix}\\mathbf{m_0} &= -\\mathbf{c_0}\\\\\n    \\iff rot(\\mathbf{c_0})\\mathbf{s} -t\\mathbf{Ie'} - \\begin{bmatrix}\n      m_0\\\\\n      0\\\\\n      \\dots\\\\\n      0\n    \\end{bmatrix} &= -\\mathbf{c_0}\n  \\end{align*}\n  In order to set up this proof, we can proceed similarly to what was proposed in section \\ref{sec:ZKPBV},\n  just a minor modification is needed in the matrix represented in (\\ref{matrix:ZKP}):\n  We completely remove all the last $(n-1)$ columns of the last $n$ columns during the construction of the matrix $\\mathbf{A}$ (the new $\\mathbf{A}$ will thus have dimension $n \\times (3n + 1)$ instead of\n  $n \\times 4n$). The specification is summarized in Algorithm (\\ref{alg:ZKPExt1}).\n\n  \\begin{algorithm}\n    \\caption{ZKP for zero constant coefficient}\\label{alg:ZKPExt1}\n    \\begin{algorithmic}[1]\n      \\Procedure{ZKPExt1}{$(\\mathbf{c}, pk),(\\mathbf{m, s, e, e'}))$}\n      \\State $rot_{c_1} \\gets rot(\\mathbf{c_1})$\n      \\State $rot_{p_1} \\gets rot(\\mathbf{pk_1})$\n      \\State let I be the $n \\times n$ identity matrix\n      \\State let I' be 1 column matrix with all 1s.\n      \\State let Z be the $n \\times n $ zero matrix\n      \\State let Z' be 1 column matrix with all 0s.\n      \\State $\\mathbf{A} \\gets ((rot_{c_1},-tI, Z, -I'),(rot_{p_1}, Z, tI,Z')) $\n      \\State $\\mathbf{x} \\gets (\\mathbf{s, e', e, m})$\n      \\State $\\mathbf{y} \\gets (\\mathbf{-c_0, -pk_0})$\n      \\State \\textbf{Return} $\\mathbf{SternExt(A,x,y)}$\n      \\EndProcedure\n    \\end{algorithmic}\n  \\end{algorithm}\n\n\\item[Proving $\\mathbf{m}=\\sum_{i = 0}^l(m_ix^i) \\land m_j = 0\\  for\\  j = 1,2\n  \\dots l-1$. \\textbf{(ZKPExt2)}] This proof can be engineered similarly to $\\mathbf{ZKPExt1}$, following\n  the same method. Except that in this one, instead of removing $(n-1)$ columns, we\n  remove only the first column of the last $n$ columns of $\\mathbf{A}$. The result\n  is the matrix $\\mathbf{A}$, with dimension $n \\times (4n-1)$. The specification is summarized in Algorithm (\\ref{alg:ZKPExt2}).\n  \\begin{algorithm}\n    \\caption{ZKP for only constant non-zero coefficient}\\label{alg:ZKPExt2}\n    \\begin{algorithmic}[1]\n      \\Procedure{ZKPExt2}{$(\\mathbf{c}, pk),(\\mathbf{m, s, e, e'}))$}\n      \\State $rot_{c_1} \\gets rot(\\mathbf{c_1})$\n      \\State $rot_{p_1} \\gets rot(\\mathbf{pk_1})$\n      \\State let I be the $n \\times n$ identity matrix\n      \\State let I' be I with the first column removed.\n      \\State let Z be the $n \\times n $ zero matrix\n      \\State let Z' be Z with the first column removed.\n      \\State $\\mathbf{A} \\gets ((rot_{c_1},-tI, Z, -I'),(rot_{p_1}, Z, tI,Z')) $\n      \\State $\\mathbf{x} \\gets (\\mathbf{s, e', e, m})$\n      \\State $\\mathbf{y} \\gets (\\mathbf{-c_0, -pk_0})$\n      \\State \\textbf{Return} $\\mathbf{SternExt(A,x,y)}$\n      \\EndProcedure\n    \\end{algorithmic}\n  \\end{algorithm}\n\n\n\\item[Proving $\\mathbf{m}=\\sum_{i = 0}^l(m_ix^i) \\land m_j = 0 \\lor m_j = 1\\  for \\  j = 0,1\n  \\dots l-1$ \\textbf{(ZKPExt3 and ZKPExt4)}. ] Following the previous extensions, proving that a message\n  contains only zero or one coefficients amounts to a trivial modification of the matrix $\\mathbf{A}$ and an according set up of the bound of\n  \\textbf{SternExt}.\n\\end{description}\n\n\\subsection{ZKP of re-encryption correctness}\n\\label{sec:ZKPReencrypt}\nThis section first discusses the module \\textbf{ZKPUnpack(c, c')}, which proves the\ncorrectness of the re-encryption of a single slot unpacked plaintext $\\mathbf{m'} = Dec(\\mathbf{c'})$ from the\ncoefficients-packed ciphertext $\\mathbf{m} = Dec(\\mathbf{c})$.\nWe then provide details about the $\\mathbf{ZKPBinDecomp(c,c_i)}$ module, aimed at proving the correctness of re-encryption of a binary-encoded plaintext as a unary-encoded one.\n\\begin{description}\n\\item [{ZKPUnpack(c,c',pk, s, e, e').}]The relation of the proof is:\n  % \\[\n  %   R_{\\mathbf{ZKPUnpack}} = \\{ \\mathbf{c, c'} \\in R_q \\times R_q :\n  %   \\mathbf{m} = Dec(\\mathbf{c}) \\land \\mathbf{m'} = Dec(\\mathbf{c'}) \\land m_0\n  %   = m_0' \\land (m_i' = 0 \\  \\forall i \\neq 0)\\}\n  % \\]\n  \\begin{align*}\n    R_{\\mathbf{ZKPUnpack}} &= \\{ \\mathbf{c, c'} \\in R_q \\times R_q , \\mathbf{pk} \\in R_{q}^{2}; (\\mathbf{s,e,e'}) \\in \\chi^{n} : \\\\\n    &\\mathbf{m} = Dec(\\mathbf{c}) \\land \\mathbf{m'} = Dec(\\mathbf{c'}) \\land m_0\n    = m_0' \\land (m_i' = 0 \\  \\forall i \\neq 0)\\}\n  \\end{align*}\n  Given $m_0 = m_0'$, we observe $\\mathbf{m(x) - m'(x)} = 0 + m''_1x + \\dots + m''_{n-1}x^{n-1}$. Therefore, $\\mathbf{ZKPUnpack}$\n  can be carried out as specified in Algorithm (\\ref{alg:ZKPUnpack})\n\n  \\begin{algorithm}\n    \\caption{ZKP of coefficients transform}\\label{alg:ZKPUnpack}\n    \\begin{algorithmic}[1]\n      \\Procedure{ZKPUnpack}{$\\mathbf{c, c', pk, s, e, e'}$}\n      \\State Let $b_1 \\gets \\mathbf{ZKPExt1((c-c',pk),(Dec(c-c'), s, e, e'))}$\n      \\State Let $b_2 \\gets \\mathbf{ZKPExt2((c',pk),(Dec(c'),s,e,e'))}$\n      \\State \\textbf{Return} $b_1 \\land b_2$\n      \\EndProcedure\n    \\end{algorithmic}\n  \\end{algorithm}\n\n\\item [$\\mathbf{ZKPBinDecomp(c,c_i).}$] The relation of the proof is:\n  \\begin{align*}\n    R_{\\mathbf{ZKPBinDec}} &= \\{ \\mathbf{c}, \\mathbf{c}_{i}|_{i=0}^{l-1} \\in R_q \\times R_q^l, \\mathbf{pk} \\in R_{q}^{2}; (\\mathbf{s,e,e'}) \\in \\chi^{n}:\\\\\n    &\\mathbf{m} = Dec(\\mathbf{c}) \\land \\mathbf{m_0} = \\sum_{i=0}^{l-1}b_i2^i\n    \\land \\mathbf{c_i} = Enc(b_i) \\land b_{i} \\in {0,1}\n    \\}\n  \\end{align*}\n  The specification of the proof is detailed in Algorithm\n  (\\ref{alg:ZKPBinDecomp}).\n\n  \\begin{algorithm}\n    \\caption{ZKP of encoding transform}\\label{alg:ZKPBinDecomp}\n    \\begin{algorithmic}[1]\n      \\Procedure{ZKPBinDecomp}{$\\mathbf{c, c_i}$}\n      \\State Let $\\mathbf{c'} \\gets \\sum_{i=0}^{l-1}\\mathbf{c_i}2^i$\n      \\State Let $\\mathbf{c''} \\gets c - c' $\n      \\State \\textbf{Return} $\\mathbf{ZKPExt1((c'',pk),(Dec(c''),s,e,e'))}$\n      \\EndProcedure\n    \\end{algorithmic}\n  \\end{algorithm}\n\\item [Applications in our protocol.] In authentication step \\ref{protocol:step5}, after receiving\n  the ciphertext $C_{HD'}$, which encrypts a plaintext\n  of the form $(HD', g_1, \\dots, g_{n-1})$, $\\user_k$ removes the noise terms $g_1, \\dots,\n  g_{n-1}$ and sends the re-encryption $C_{HD_0'} = Enc(HD', 0, 0, \\dots,\n  0)$ back to $\\server$. The client needs to prove that he performs this step correctly, this is done\n  by $\\mathbf{ZKPUnpack(C_{HD},C_{HD_0'}})$. In this step, the server also receives $\\mathbf{c_i} = Enc(b_i)$ to compute $Enc(x^{HD'})$, as discussed in section \\ref{sec:binToUna}. Before doing this operation, the client needs to convince the server\n  that the bits sent are actually the ones decomposed from $HD'$. This proof is done\n  by $\\mathbf{ZKPBinDecomp(C_{HD_0'},c_i)}$.\n\n  Besides, In authentication step \\ref{protocol:step1}, $\\user_k$ uses $\\mathbf{ZKPBV}$ to convince $\\server$ that he is\n  authenticating with a valid template $Y$. Moreover, in step \\ref{protocol:step9}, $\\user_k$ can use either $\\mathbf{ZKPExt3}$ or $\\mathbf{ZKPExt4}$ to\n  convince $\\server$ about the authentication result.\n\\end{description}\n\n\\section{Security Proofs}\n\\label{append:Proofs}\n\\subsection{Security Proof for Theorem~\\ref{theo:client}: Type I Impersonation attack}\nThe proof of theorem \\ref{theo:server} and \\ref{theo:client} can be provided\nusing a sequence of games between the challenger $\\challenger$ and the adversary\n$\\attacker$. We present a sequence of games as well as the relations among them to demonstrate the type I security model proof.\\\\\n% \\begin{figure}[htbp!] \n%   \\centering\n%   \\fbox{\n%    \\begin{gameproof}[nr=-1]\n%   \\gameprocedure[linenumbering, mode=text]{\n%     $D_{k} \\randomsample D_{bio}$\\\\\n%     $(\\sk, \\pk) \\gets KeyGen(params)$\\\\\n%     $\\mathbf{X}_{k} \\randomsample D_{k}$\\\\\n%     $\\enc{\\mathbf{X_{k}}} \\gets Enc(\\mathbf{X}_{k},\\pk)$\\\\\n%     For $i=1,\\dots,q$:\\\\\n%     $\\mathbf{Y}_{i} \\gets \\{0,1\\}^{n}$\\\\\n%     $\\enc{\\mathbf{Y}_{i}} \\gets Enc(\\mathbf{Y}_{i},\\pk)$\\\\\n%     $verifierView1 \\gets \\mathbf{ZKPoPK1}((\\sk,\\mathbf{Y}_{i});(\\pk,\\enc{\\mathbf{Y}_{i}}))$\\\\\n%     $\\enc{\\mathbf{HD}_{i}} = EvalDistance(\\enc{\\mathbf{X}_{k}},\\enc{\\mathbf{Y}_{i}})$\\\\\n%     $r_{i} \\randomsample \\mathbb{Z}_{HD}$,$\\enc{\\mathbf{HD'}_{i}} = Add(\\enc{\\mathbf{HD}_{i}},\\enc{r_{i}})$\\\\\n%     $HD'_{i} \\gets Dec(\\enc{\\mathbf{HD'}_{i}},\\sk)$\\\\\n%     $verifierView2 \\gets \\mathbf{ZKPoPK2}((\\sk,\\mathbf{HD'}_{i});(\\pk,\\enc{\\mathbf{HD'}_{i}}))$\\\\\n%     $HD_{i} \\gets HD'_{i} - r_{i}$\\\\\n%     $res_{i} \\gets compare(HD_{i}, \\tau)$\\\\\n%     $\\beta \\gets \\adv(verifierView1, verifierView2, \\enc{\\mathbf{X}_{k}}, \\enc{\\mathbf{Y}_{i}}, res_{i}, r_{i}, HD_{i},\n%     \\enc{\\mathbf{HD'}_{i}}, \\enc{\\mathbf{HD}_{i}})$ }\n% \\end{gameproof}\n%   }\n%   \\caption{Game 0 - Malicious Client game}\n%   \\label{fig:game0protocol3client}\n% \\end{figure}\n\\textit{Game 0} Game 0 is the original impersonation game for type I attack.\n\\begin{description}\n\t\\item [Setup.] $\\challenger$ initiates $D_k \\randomsample D_{bio}$ and $X_k\n\t\\randomsample D_k$. $\\challenger$ sets up $(sk_k, pk_k)$ and executes\n\t$Enrol(k, X_k)$ to get $(sk_k, T_k =(pk_k, C_k = Enc^{(1)}_{pk_k}(X_k)))$.\n\t$\\attacker$ submits the attack query type I and receives $sk_k$ from\n\t$\\challenger$.\n        \\begin{sloppypar}\n\t\\item [Query.] $\\attacker$ runs $q$ authentication sessions. In each session $j\n\t= 1, \\dots, q$,\n\t$\\attacker$ sends $(Q_k^{(j)} = Enc^{(1)}(Y^{(j)}))$. $\\attacker$ and\n\t$\\challenger$ runs $\\mathbf{ZKPValidEnc}(Q_k^{(j)},Y^{(j)})$. $\\challenger$ evaluates \n\t$C_{HD} = \\mathbf{EvalDistance}_{pk_k}(C_k, Q_k^{(j)})$, then computes\n\t$C_{HD'} = (-1)C_{HD} + Enc_{pk_k}^{(1)}(r_{HD'},e_{HD'})$ for $r_{HD'}\n\t\\randomsample \\mathcal{P}$ and $e_{HD'} \\randomsample \\chi_{HD}$. The\n\tresult ciphertext is sent to $\\attacker$, $\\attacker$ decrypts $C_{HD'}$\n\tand decomposes it into bits and further sends back the ciphertexts $C_0^{(j)}, \\dots,\n\tC_{l-1}^{(j)} (= Enc^{(1)}(b_i), i = 0,\\dots, l-1)$, as well as the\n\tre-encryption $C_{HD_0'}$. $\\attacker$ and $\\challenger$ engage\n\t$\\mathbf{ZKPUnpack}(C_{HD},C_{HD_0'})$ and $\\mathbf{ZKPBinDecomp}(C_{HD_0'},\n\tC_i^{(j)})$.\n\t$\\challenger$ evaluates $C_{HD}'' = Enc^{(2)}(2^l + t) +\n\t\\mathbf{ToUnary}(C_i^{(j)}) + Enc^{(2)}(-r) $ to get $Enc^{(2)}(2^l + t -\n\tHD)$. $\\challenger$ computes $Enc^{(3)}(res) \\gets\n\t\\mathbf{MSBExtract}(C_{HD}'')$ and sends the result to $\\attacker$. $\\attacker$\n\tdecrypts it and sends the authentication result bit back. $\\challenger$ and\n\t$\\attacker$ then fire $\\mathbf{ZKPCorrectDec}(res)$ to trigger the server's acceptance of the\n\tauthentication result. At the end, the server outputs \\textbf{Accept} if\n\tall the proofs pass and $res = \\mathbf{Accept}$.\n        \\end{sloppypar}\n\\end{description}\nNext, we discuss the games that follow, the plan being to proceed towards the final game where \neverything $\\attacker$ receives relating to $X_k$ can be simulated\nwithout any knowledge about $X_k$, except that $X_k$ is\nthe function $Verify(X_k, Y)$. Let $res_s = Verify(X_k, Y^{(j)})$ and $S_i$ be\nthe event in the game $i$ such that $res_s = Accept$.\\\\\n\\textit{Game 1}. In this game, we abort $\\mathbf{ZKPValidEnc}$ if $Q_k^{(j)}$\nis not a valid encryption of the query, but the $Prover$ manages to pass the\nproof. Let $(*)_1$ be this event.\n\\[\n(*_1)res_s = \\begin{cases}\n\\text{Reject if } \\mathbf{ZKPValidEnc} \\text{ fails}\\\\\n\\text{res else}\n\\end{cases}\n\\]\nLet $bad_0$ be the event in game 0 : $\\exists j \\leq q\\  s.t\\  (*_1)\\\n\\textnormal{is thus the case}$. We want to show that when we modify \\textit{game 0}, the\nprobability of a successful forgery $S_1$ in this \\textit{game 1} is not much\nlower than what it was. Due to the modification, we observe that\n$\nPr[S_1] \\geq Pr[S_0] - Pr[bad_0]\n$\n.For any $j$ in the $q$ authentication attempts, by the $\\varepsilon-soundness$ property of\n$\\mathbf{ZKPValidEnc}$ as a proof of membership in (*), we have $Pr[(*_1)\\\noccurring\\ for\\ some \\ j] \\leq \\varepsilon_{ZK1}$. So, the probability of $bad_0$\nwould be the union of these events, which is bounded by $Pr[bad_0] \\leq\nq\\varepsilon_{ZK1}$. In other words, the advantage of $\\attacker$ in \\textit{game\n\t1} is\n\\[\nPr[S_1] \\geq Pr[S_0] - Pr[bad_0] \\geq \\varepsilon_{imp} - q\\varepsilon_{ZK1}\n\\]\n\\\\\n\\textit{Game 2}. In this game, we abort $\\mathbf{ZKPUnpack}$ if, in one of the\n$j^{th}$ runs, the $Verifier$ accepts but the ciphertext does not satisfy the\nrelation. Let $bad_1$ be this event, by the same type of argument, we can\nderive $Pr[bad_1] \\leq q\\varepsilon_{ZK2}$ and therefore\n$$Pr[S_2] \\geq Pr[S_1]\n- Pr[bad_1] \\geq \\varepsilon_{imp} - q(\\varepsilon_{ZK1}+\\varepsilon_{ZK2})\n$$\n\\textit{Game 3 and Game 4}. Similarly, we abort $\\mathbf{ZKPBinDecomp}$ and\n$\\mathbf{ZKPCorrectDec}$ if, in any $j^{th}$ runs, the $Verifier$ accepts even\nwhen the correctness of the ZKP is not satisfied. We have\n$$Pr[S_3] \\geq  \\varepsilon_{imp} - q(\\varepsilon_{ZK1}+\\varepsilon_{ZK2}\n+\\varepsilon_{ZK3})\n$$ and\n$$Pr[S_4] \\geq  \\varepsilon_{imp} - q(\\varepsilon_{ZK1}+\\varepsilon_{ZK2} +\n\\varepsilon_{ZK3} + \\varepsilon_{ZK4})\n$$\nBy the end of \\textit{Game 4}, if in any authentication attempt $j$, there is\nno abort while running any of the 4 games, then, by the correctness property of ZKP, the\nserver output is equal to the output of $Verify(X_k, Y^{(j)})$. In other words,\nwe have shown what we could get by just querying the oracle $Verify()$. Next,\nwe want to simulate everything related to $X_k$ the attacker can see using\njust that oracle.\\\\\n\\textit{Game 5.} At the end of \\textit{Game 4}, $\\challenger$ possesses the bit\n$b = Verify(Y^{(i)},X_k)$. In this game, we can change $C_{res}^{(j)}$ from\n$\\mathbf{MSBExtract}(C_{HD}'') = Enc(b;e_{res})$ to\n$Enc(verify(Y^{(i)},X_k);e_{res})$, given that the challenger can use the\nsecret key to extract $e_{res}$. Despite this change,  \nthe same ciphertext is still accessible to $\\attacker$, so its probability of winning of \nis the same as in \\textit{Game 4}.\\\\\n\\textit{Game 6.} In this game, we change the way $\\challenger$ computes\n$C_{HD}''$: In the original game 0, $Enc(-r)$ was added to remove the mask. We now\nwant to remove this $r$ from being used anywhere in the game, so we replace\nthis with $Enc(0)$. This change does not affect $\\attacker$'s success\nprobability: $r$ only affects the plaintext inside $C_{HD}''$, since we do not\nuse this plaintext anymore (as it has been replaced in \\textit{Game 5}), so this change\ndoes not affect the information available to the attacker. Again, $Pr[S_6] = Pr[S_5] = Pr[S_4]$.\\\\\n\\textit{Game 7.} We modify the way $C_{HD}'$ is computed in this game. Instead\nof calculating $C_{HD}' \\gets (-1)C_{HD} + Enc(r;e_{HD'})$, the challenger chooses a\nrandom $HD' \\randomsample \\mathbb{Z}_t$ and encrypts it with the noise used\nbefore: $C_{HD}' \\gets Enc(HD'; -e_{HD} + e_{HD'})$. In this game, the\nplaintext has changed from being $r + HD$ to a uniform $HD' \\in \\mathbb{Z}_t$.\nSince $r$ is also uniform in $\\mathbb{Z}_t$, the attacker is confronted with a uniform\nplaintext in both cases. Therefore, $Pr[S_7] = Pr[S_6]$.\\\\\n\\textit{Game 8.} Finally, we set $C_{HD'} = Enc(HD', e_{HD'})$ for $e_{HD'}\n\\randomsample \\chi_{mask}$ instead of $-e_{HD} + e_{HD'}$. We replace the sum\nof the Gaussian noise with a random noise. In the previous chapter, we\nshowed that $Pr[S_8] \\geq \\frac{1}{c(\\delta)}(Pr[S_7]-q \\cdot \\delta)$, where $c(\\delta) = RD(-e_{HD} + e_{HD'},\ne_{HD}) \\leq 2 \\cdot e^{1+2\\delta}$ by Lemma~\\ref{le:Renyi} and by our assumption on the parameter's values. After we finish \\textit{Game 8}, we notice that all the messages available to the attacker can be simulated with only the verified bit $b =\nVerify(Y^{(i)}, X_k)$. We now have an attacker $A'$ against the biometric\nimpersonation with advantage:\n\\[\n\\varepsilon_{bio} = Adv(A') = Pr[S_8] \\geq \\frac{1}{c(\\delta)}(\\varepsilon_{imp} - q(\\varepsilon_{ZK1}+\\varepsilon_{ZK2} +\n\\varepsilon_{ZK3} + \\varepsilon_{ZK4}) + \\delta),\n\\]\nwhich gives the claimed bound $\\varepsilon_{imp} \\leq c(\\delta) \\cdot \\varepsilon_{bio} + q \\cdot (\\varepsilon_{ZK1}+\\varepsilon_{ZK2} +\n\\varepsilon_{ZK3} + \\varepsilon_{ZK4}) + \\delta \\leq (c(\\delta)+c_1) \\cdot \\varepsilon_{bio}$ if $q(\\varepsilon_{ZK1}+\\varepsilon_{ZK2} +\n\\varepsilon_{ZK3} + \\varepsilon_{ZK4}) + \\delta \\leq c_1 \\cdot \\varepsilon_{bio}$.\n\n\n\\subsection{Security Proof for Theorem~\\ref{theo:client}: Type II Impersonation attack}\n\\label{append:ProofsTypeII}\nThe proof of Theorem \\ref{theo:client} can be provided using a sequence of games between the challenger $\\challenger$ and the adversary $\\attacker$. We present\na sequence of games as well as the relations among them to demonstrate the type II security model proof. The idea is that in this type of attack, $sk_k$ is not used to compute the view of $\\attacker$. On the other hand, the soundness of the zero-knowledge proof of knowledge $\\mathbf{ZKPValidEnc}$ implies the existence of an efficient witness extractor algorithm, that can be used to extract the witness (i.e. the secret key $sk_k$) from a cheating prover succeeding with probability non-negligibly higher than the knowledge error of the zero-knowledge proof, thus contradicting the IND-CPA security of the BV encryption scheme. \\\\\\\\\n\\textit{Game 0}. Game 0 is the original impersonation game for a type II attack, i.e., the same as Game 0 in the proof of security against Type I attacks, except that $(T_k =(pk_k, C_k = Enc^{(1)}_{pk_k}(X_k)))$ is given by $\\challenger$ to $\\attacker$ at the beginning of the game, rather than $sk_k$.\nFor $j \\in \\{1,\\ldots,q\\}$, let $res^{j}$ denote the result of the $j$th authentication protocol run between $\\attacker$ and $\\challenger$, and $S_0$ be\nthe event in the game $0$ such that $res^{j} = Accept$ for some $j=1,\\ldots,q$. We have $\\Pr[S_0] = \\varepsilon_{imp,II}$ as the type II success probability of $\\attacker$. \\\\\\\\\n\\textit{Game 1}. From the definition of event $S_0$ in Game 0, it follows that there exists some $j^* \\in \\{1,\\ldots,q\\}$ such that $\\Pr[res^{j^*} = Accept] \\geq \\varepsilon_{imp,II}/q$. Furthermore, by an averaging argument, there must exist a set $G$ of $(D_k,X_k,pk_k)$ such that $\\Pr[(D_k,X_k,pk_k) \\in G] \\geq \\varepsilon_{imp,II}/(2 \\cdot q)$, and for each $(D'_k,X'_k,pk'_k) \\in G$, we have $\\Pr[res^{j^*} = Accept |(D_k,X_k,pk_k)=(D'_k,X'_k,pk'_k)] \\geq  \\varepsilon_{imp,II}/(2 \\cdot q)$. By $\\varepsilon_{ZK1}$-soundness of the zero-knowledge proof of knowledge $\\mathbf{ZKPValidEnc}$ \\cite{goldreich2009foundations}, there exists a witness extractor algorithm that runs in expected time $T'=O(\\mathrm{poly}(n \\log Q) \\cdot T / (\\varepsilon_{imp,II}/(2*q) - \\varepsilon_{ZK1}))$, where $T$ denotes the run-time of $\\attacker$ and outputs a witness containing $sk_k$ for ${ZKPValidEnc}$. Therefore, we obtain a (secret key recovery) attack algorithm against the IND-CPA security of the BV encryption scheme, with expected run-time $T'$ and advantage $\\varepsilon' \\geq \\varepsilon_{imp,II}/(2 \\cdot q)$. Hence,  if $\\varepsilon_{imp,II}/(2*q) - \\varepsilon_{ZK1} > \\varepsilon_{imp,II}/(4*q)$, or equivalently, if $\\varepsilon_{imp,II} > 4 \\cdot q \\varepsilon_{ZK1}$, we obtain a contradiction with the assumption the BV encryption scheme with parameters $Q,n,\\sigma$ is IND-CPA against attacks with expected time $O(\\mathrm{poly}(n \\log Q) \\cdot T / \\varepsilon_{ZK1})$ and advantage $\\geq \\varepsilon_{ZK1}$. It follows under the latter assumption that $\\varepsilon_{imp,II} \\leq 2q \\varepsilon_{ZK1} \\leq 4 c_1  \\cdot \\varepsilon_{bio}$, under the assumption that  $q(\\varepsilon_{ZK1}+\\varepsilon_{ZK2} +\n\\varepsilon_{ZK3} + \\varepsilon_{ZK4} + \\delta) \\leq c_1 \\cdot \\varepsilon_{bio}$.\n\n\n\\subsection{Security Proof for Theorem~\\ref{theo:server}: Privacy against Server}\n\\label{append:ProofsPrivacy}\nThe proof of Theorem \\ref{theo:client} can be done using a sequence of games between the challenger $\\challenger$ and the adversary $\\attacker$. We present a sequence of games. The idea is to proceed to remove $sk_k$ and $X_k$ from being used to compute the view of $\\attacker$, except for $Verify(X_k,Y_k^{j})$ queries, as in the ideal game, relying on the correctness of the protocol and the IND-CPA security of the BV encryption scheme. \\\\\\\\\n\\textit{Game 0}. Game 0 is the original real privacy game, in which $(T_k =(pk_k, C_k = Enc^{(1)}_{pk_k}(X_k)))$ is given by $\\challenger$ to $\\attacker$ at the beginning of the game. Then, for $j=1\\ldots,q$, the attacker sends $Y_k^{(j)} \\in \\{0,1\\}^n$ to $\\challenger$, and the latter simulates a run of the authentication protocol between an honest client with input $(k,Y_k^{(j)}, sk_k)$ and an honest server with input $(k,T_k)$, returning to $\\attacker$ the protocol view $V^{(j)}_S$ of the server. Finally, $\\attacker$ outputs a bit $\\beta$. In the following Game $i$, we let $S_i$ denote the event of $\\beta=1$.\\\\\\\\\n\\textit{Game 1}. We change the computation of the authentication result bit $res^{(j)}$ sent by client to server from the decryption of the ciphertext $\\textbf{MSBExtract}(C''_{HD}$ (its value in Game 0) to the result returned by $Verify(X_k, Y^{(j)})$. By correctness of the protocol, this does not change the value of $res^{(j)}$, so $\\Pr[S_1] = \\Pr[S_0]$. \\\\\\\\\n\\textit{Game 2}. We change the computation of the zero-knowledge protocol transcripts. Instead of computing those transcripts using the secret witnesses, we simulate them using the statistical zero-knowledge simulator algorithms for the zero-knowledge proofs. By the zero-knowledge property, this is a perfect simulation, yielding $\\Pr[S_2]= \\Pr[S_1]$.\\\\\\\\\n\\textit{Game 3}. We change the computation of the ciphertexts $C^{(j)}_i$ for $i=0,\\ldots,l-1$ and $Q^{(j)}_k$ for $j=1,\\ldots,q$ and $C_k$ to encrypt zero messages, instead of encrypting the secret-related messages as in the previous game. Since now $sk_k$ is not used anywhere in generating the view of $\\attacker$, it follows by a hybrid argument that $|\\Pr[S_3]-\\Pr[S_2]| ((l+1) \\cdot q + 1) \\cdot \\varepsilon_{BV}$, where $\\varepsilon_{BV}$ denotes the maximal advantage of an attacker against IND-CPA of BV scheme against attacks with run-time $T + \\mathrm{poly}(n, \\log Q)$, where $T$ is the run-time of $\\attacker$.\nIn this game, since the only information on $X_k$ comes via the $Verify(X_k,Y_k^{j})$ queries, the challenger together with $\\attacker$ constitute an efficient attacker against the ideal privacy game, which outputs 1 with probability different by at most $(l+1) \\cdot q + 1) \\cdot \\varepsilon_{BV}$ relatively to the probability of outputting 1 in the real privacy game, as required.\n\n\\section{Conclusion}\n\\label{sec:evaluation}\nWe quickly notice that the main bottle neck of this protocol is the\ncommunication size: 4 different Zero-Knowledge Proofs are needed for one\nauthentication. With the parameters set used previously\n($n=2048, q \\approxeq 2^{70}, t = 2048, \\sigma=8$), the communication size for\neach authentication ($\\approx 84MB$) will not satisfy the practical usage\nrequirement. However, the contributions of this chapter maybe of independent\ninterest, as building blocks for other secure computation protocols are based on the\nBV SWHE scheme:\n\\begin{itemize}\n\\item A ZKP technique to prove the correctness of re-encryption of a\n  binary-encoded plaintext (useful for efficient homomorphic\n  addition/multiplication arithmetic operations) as a unary-encoded plaintext\n  (useful for efficient homomorphic comparison operations).\n\\item Correctness of re-encryption of a coefficient-packed plaintext slot vector\n  into an unpacked single slot plaintext.\n\\end{itemize}\nIn the next chapter, we discuss different techniques used to remove this\ncommunication overhead: we replace the Stern-based ZKP technique, which requires\nmany rounds of proof for security by the Schnoor-based technique (requiring only 1 round). Other cryptographic tools including Garbled Circuit and Oblivious\nTransfer will be used in the HD comparison step to avoid supplementary proofs during\nauthentication.\n\n\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: \"../thesis\"\n%%% End:\n", "meta": {"hexsha": "e496d416a7937be1f89a56626d2ce057f1941a4e", "size": 51891, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapter6/chapter6.tex", "max_stars_repo_name": "rimrim/thesis", "max_stars_repo_head_hexsha": "91a197b74f4d33b674e4457e4bfce33c126614e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter6/chapter6.tex", "max_issues_repo_name": "rimrim/thesis", "max_issues_repo_head_hexsha": "91a197b74f4d33b674e4457e4bfce33c126614e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter6/chapter6.tex", "max_forks_repo_name": "rimrim/thesis", "max_forks_repo_head_hexsha": "91a197b74f4d33b674e4457e4bfce33c126614e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 57.4015486726, "max_line_length": 1717, "alphanum_fraction": 0.6748183693, "num_tokens": 18132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.3322326385035477}}
{"text": "\\documentclass[11pt]{beamer}\n\\input{definitions}\n\n\\begin{document}\n\t\\author{Myles Lee}\n\t\\title{Explaining Makespan Schedules}\n\t\\date{25\\textsuperscript{th} June 2019}\n\t\n\t\\begin{frame}[plain]\n\t\t\\maketitle\n\t\\end{frame}\n\t\n\t\\begin{frame}\n\t\t\\frametitle{Introduction}\n\t\t\\makebox[\\textwidth][c]{\n\t\t\t\\begin{tikzpicture}\n\t\t\t\t\\node (left) at (0, 0){\\includegraphics[scale=0.25]{figures/inefficient_makespan.png}};\n\t\t\t\t\\node (right) at (6, 0){\\includegraphics[scale=0.25]{figures/efficient_makespan.png}};\n\t\t\t\t\\draw[thick,->] (left) -- (right) node[midway, above] {optimise};\n\t\t\t\\end{tikzpicture}\n\t\t}\n\t\t\\begin{itemize}\n\t\t\t\\item Solvers and schedules are difficult to understand\n\t\t\t\\item Apply argumentation to makespan schedules to generate explanations\n\t\t\\end{itemize}\n\t\\end{frame}\n\n\t\\begin{frame}\n\t\t\\frametitle{Contributions}\n\t\t\\begin{columns}\n\t\t\t\\begin{column}{0.5\\textwidth}\n\t\t\t\t\\includegraphics[width=\\textwidth]{figures/tool_gui.png}\n\t\t\t\\end{column}\n\t\t\t\\begin{column}{0.5\\textwidth}\n\t\t\t\t\\resizebox{\\textwidth}{!}{\\input{theorem_textless}}\n\t\t\t\\end{column}\n\t\t\\end{columns}\n\n\t\t\\begin{columns}\n\t\t\t\\begin{column}{0.5\\textwidth}\n\t\t\t\t\\begin{itemize}\n\t\t\t\t\t\\item Interactive tool\n\t\t\t\t\t\\item Algorithms\n\t\t\t\t\\end{itemize}\n\t\t\t\\end{column}\n\t\t\t\\begin{column}{0.5\\textwidth}\n\t\t\t\t\\begin{itemize}\n\t\t\t\t\t\\item Theoretical extensions \n\t\t\t\t\t\\item Discussion\n\t\t\t\t\\end{itemize}\n\t\t\t\\end{column}\n\t\t\\end{columns}\t\t\t\n\t\\end{frame}\n\n\t\\begin{frame}\n\t\t\\frametitle{Demonstration}\n\t\t\\includegraphics[width=\\textwidth]{figures/tool_gui.png}\n\t\\end{frame}\n\n\t\\subsection{Interactive Tool and Algorithms}\n\n\t\\begin{frame}\n\t\t\\frametitle{Abstract Argumentation}\n\t\t\\begin{itemize}\n\t\t\t\\item An abstract argumentation framework is a directed graph $\\pair{Args}{\\rightsquigarrow}$.\n\t\t\t\\item Extension $E$ is a subset of $Args$.\n\t\t\\end{itemize}\n\t\t\n\t\t\\begin{definition}\n\t\t\t$E$ is conflict-free on $\\pair{Args}{\\rightsquigarrow}$ iff $\\forall a,b\\in E. a\\not\\rightsquigarrow b$.\n\t\t\\end{definition}\n\t\n\t\t\\begin{definition}\n\t\t\t$E$ is stable on $\\pair{Args}{\\rightsquigarrow}$ iff $E$ is conflict-free on $\\pair{Args}{\\rightsquigarrow}$ and $\\forall a\\in Args\\setminus E.\\exists e\\in E.e\\rightsquigarrow a$.\n\t\t\\end{definition}\n\t\\end{frame}\n\n\t\\begin{frame}[label=pipeline]\n\t\t\\frametitle{Pipeline}\n\t\t\\resizebox{\\textwidth}{!}{\\input{pipeline}}\n\t\\end{frame}\n\n\t\\begin{frame}\n\t\t\\frametitle{Feasibility Framework Construction}\n\t\t\t\t\n\t\t\\begin{columns}\n\t\t\t\\begin{column}{0.5\\textwidth}\n\t\t\t\t\\begin{center}\n\t\t\t\t\t$\\begin{bmatrix}\n\t\t\t\t\t\t1 & 0 & 1\\\\\n\t\t\t\t\t\t0 & 1 & 0\\\\\n\t\t\t\t\t\\end{bmatrix}$\n\t\t\t\t\t\\begin{equation*}\n\t\t\t\t\t\t\\forall j\\in\\mathcal{J}.\\sum_{i\\in\\mathcal{M}}x_{i,j}=1\n\t\t\t\t\t\\end{equation*}\n\t\t\t\t\\end{center}\n\t\t\t\\end{column}\n\t\t\t\\begin{column}{0.5\\textwidth}\n\t\t\t\t\\begin{center}\n\t\t\t\t\t\\begin{tikzpicture}\n\t\t\t\t\t\t\\node(a) at (0, 0){$\\pair{2}{\\mathtt{a}}$};\n\t\t\t\t\t\t\\node(b) at (1, 0){$\\pair{2}{\\mathtt{b}}$};\n\t\t\t\t\t\t\\node(c) at (2, 0){$\\pair{2}{\\mathtt{c}}$};\n\t\t\t\t\t\t\\node(d) at (0, 2){$\\pair{1}{\\mathtt{a}}$};\n\t\t\t\t\t\t\\node(e) at (1, 2){$\\pair{1}{\\mathtt{b}}$};\n\t\t\t\t\t\t\\node(f) at (2, 2){$\\pair{1}{\\mathtt{c}}$};\n\t\t\t\t\t\t\n\t\t\t\t\t\t\\draw[thick,<->](a) -- (d);\n\t\t\t\t\t\t\\draw[thick,<->](b) -- (e);\n\t\t\t\t\t\t\\draw[thick,<->](c) -- (f);\n\t\t\t\t\t\\end{tikzpicture}\n\t\t\t\t\t$Args_F=\\mathcal{M}\\times\\mathcal{J}$\\\\\n\t\t\t\t\t$\\pair{i}{j}\\rightsquigarrow_F\\pair{i'}{j'}$ iff $i\\neq i'\\land j=j'$\n\t\t\t\t\\end{center}\n\t\t\t\\end{column}\n\t\t\\end{columns}\n\t\\end{frame}\n\n\t\\begin{frame}\n\t\t\\frametitle{Framework Modelling}\n\t\t\n\t\t\\begin{definition}\n\t\t\tFramework $\\pair{Args}{\\rightsquigarrow}$ stability-models a property $P$ iff $\\forall E\\subseteq Args.E$ is stable on $\\pair{Args}{\\rightsquigarrow}\\Leftrightarrow P$\n\t\t\\end{definition}\n\t\n\t\t\\begin{tikzpicture}\n\t\t\t\\node(a) at (0, 0){$\\pair{2}{\\mathtt{a}}$};\n\t\t\t\\node(b) at (1, 0){$\\pair{2}{\\mathtt{b}}$};\n\t\t\t\\node(c) at (2, 0){$\\pair{2}{\\mathtt{c}}$};\n\t\t\t\\node(d) at (0, 2){$\\pair{1}{\\mathtt{a}}$};\n\t\t\t\\node(e) at (1, 2){$\\pair{1}{\\mathtt{b}}$};\n\t\t\t\\node(f) at (2, 2){$\\pair{1}{\\mathtt{c}}$};\n\t\t\t\n\t\t\t\\draw[thick,<->](a) -- (d);\n\t\t\t\\draw[thick,<->](b) -- (e);\n\t\t\t\\draw[thick,<->](c) -- (f);\n\t\t\t\n\t\t\t\\node at (-1.7, 0.5){$\\pair{Args_F}{\\rightsquigarrow_F}$};\n\t\t\t\\draw (-0.5, -0.5) rectangle (2.5, 2.5);\n\t\t\t\n\t\t\t\\node at (-5, 1.5){$P_F\\equiv\\forall j\\in\\mathcal{J}.\\sum_{i\\in\\mathcal{M}}x_{i,j}=1$};\n\t\t\\end{tikzpicture}\n\t\t\n\t\t\\begin{theorem}\n\t\t\t$\\pair{Args_F}{\\rightsquigarrow_F}$ \\textnormal{stability-models} $P_F$\n\t\t\\end{theorem}\n\t\\end{frame}\n\n\t\\begin{frame}\n\t\t\\frametitle{Algorithm Notation}\n\n\t\t\\begin{columns}\n\t\t\t\\begin{column}{0.5\\textwidth}\n\t\t\t\t\\begin{align*}\n\t\t\t\t\t\\mathbf{0}^{2\\times 2}&=\n\t\t\t\t\t\\begin{bmatrix}\n\t\t\t\t\t\t0&0\\\\\n\t\t\t\t\t\t0&0\\\\\n\t\t\t\t\t\\end{bmatrix}\n\t\t\t\t\\end{align*}\n\n\t\t\t\t\\begin{align*}\n\t\t\t\t\t\\begin{bmatrix}\n\t\t\t\t\t\t0&0\\\\\n\t\t\t\t\t\t1&1\\\\\n\t\t\t\t\t\\end{bmatrix}\n\t\t\t\t\t\\incircbin{\\land}\n\t\t\t\t\t\\begin{bmatrix}\n\t\t\t\t\t\t0&1\\\\\n\t\t\t\t\t\t0&1\\\\\n\t\t\t\t\t\\end{bmatrix}\n\t\t\t\t\t&=\n\t\t\t\t\t\\begin{bmatrix}\n\t\t\t\t\t\t0&0\\\\\n\t\t\t\t\t\t0&1\\\\\n\t\t\t\t\t\\end{bmatrix}\n\t\t\t\t\\end{align*}\n\t\t\t\\end{column}\n\t\t\t\\begin{column}{0.5\\textwidth}\t\t\n\t\t\t\t\\begin{align*}\n\t\t\t\t\t\\incircbin{\\neg}\n\t\t\t\t\t\\begin{bmatrix}\n\t\t\t\t\t\t1&0\\\\\n\t\t\t\t\t\t0&1\\\\\n\t\t\t\t\t\\end{bmatrix}&=\n\t\t\t\t\t\\begin{bmatrix}\n\t\t\t\t\t\t0&1\\\\\n\t\t\t\t\t\t1&0\\\\\n\t\t\t\t\t\\end{bmatrix}\n\t\t\t\t\\end{align*}\n\t\t\t\t\n\t\t\t\t\\begin{align*}\n\t\t\t\t\t\\begin{bmatrix}\n\t\t\t\t\t\t0&0\\\\\n\t\t\t\t\t\t1&1\\\\\n\t\t\t\t\t\\end{bmatrix}\n\t\t\t\t\t\\incircbin{\\lor}\n\t\t\t\t\t\\begin{bmatrix}\n\t\t\t\t\t\t0&1\\\\\n\t\t\t\t\t\t0&1\\\\\n\t\t\t\t\t\\end{bmatrix}\n\t\t\t\t\t&=\n\t\t\t\t\t\\begin{bmatrix}\n\t\t\t\t\t\t0&1\\\\\n\t\t\t\t\t\t1&1\\\\\n\t\t\t\t\t\\end{bmatrix}\n\t\t\t\t\\end{align*}\n\t\t\t\\end{column}\n\t\t\\end{columns}\t\t\n\t\\end{frame}\n\n\t\\begin{frame}\n\t\t\\frametitle{Construct-Feasibility Algorithm}\n\t\t\\begin{algorithm}[H]\n\t\t\t\\caption{}\n\t\t\t\\begin{algorithmic}[1]\n\t\t\t\t\\Function{Construct-Feasibility}{$m$, $n$}\n\t\t\t\t\\State $\\twoheadrightarrow_F$ $\\gets$ $\\mathbf{0}^{(m\\times n)^2}$\n\t\t\t\t\\For{$i_1,i_2\\in\\mathcal{M},j\\in\\mathcal{J}$}\n\t\t\t\t\\If{$i_1\\neq i_2$}\n\t\t\t\t\\State ${\\twoheadrightarrow_F}_{i_1,j,i_2,j}$ $\\gets$ 1\n\t\t\t\t\\EndIf\n\t\t\t\t\\EndFor\n\t\t\t\t\\State \\Return $\\twoheadrightarrow_F$\n\t\t\t\t\\EndFunction\n\t\t\t\\end{algorithmic}\n\t\t\\end{algorithm}\n\t\\end{frame}\n\n\t\\begin{frame}\n\t\t\\frametitle{Explain-Stability Algorithm}\n\t\t\\vspace{-0.3\\baselineskip}\n\t\t\\begin{algorithm}[H]\n\t\t\t\\caption{}\n\t\t\t\\begin{algorithmic}[1]\n\t\t\t\t\\Function{Explain-Stability}{$\\mathbf{x}$, $\\twoheadrightarrow$, $\\bar{\\mathbf{u}}$, $\\bar{\\mathbf{c}}$}\n\t\t\t\t\\State $\\mathbf{u}$ $\\gets\\incircbin{\\neg}$ $\\mathbf{x}$\n\t\t\t\t\\State $\\mathbf{c}$ $\\gets\\mathbf{0}^{(m\\times n)^2}$\n\t\t\t\t\\For{$i\\in\\mathcal{M},j\\in\\mathcal{J}$}\n\t\t\t\t\\If{$x_{i,j}=1$}\n\t\t\t\t\\State $\\mathbf{u}$ $\\gets$ $\\mathbf{u}$ $\\incircbin{\\land}$ $\\incircbin{\\neg}\\twoheadrightarrow_{i,j}$\n\t\t\t\t\\State $c_{i,j}$ $\\gets$ $\\mathbf{x}$ $\\incircbin{\\land}$ $\\twoheadrightarrow_{i,j}$ \n\t\t\t\t\\EndIf\n\t\t\t\t\\EndFor\t\t\t\n\t\t\t\t\\State $\\mathbf{u}$ $\\gets$ $\\mathbf{u}$ $\\incircbin{\\land}$ $\\incircbin{\\neg}$ $\\bar{\\mathbf{u}}$\n\t\t\t\t\\State $\\mathbf{c}$ $\\gets$ $\\mathbf{c}$ $\\incircbin{\\land}$ $\\incircbin{\\neg}$ $\\bar{\\mathbf{c}}$\n\t\t\t\t\\State \\Return $\\pair{\\mathbf{u}}{\\mathbf{c}}$\n\t\t\t\t\\EndFunction\n\t\t\t\\end{algorithmic}\n\t\t\\end{algorithm}\n\t\\end{frame}\n\n\t\\begin{frame}\n\t\t\\frametitle{Explain-Feasibility Algorithm}\n\t\t\\vspace{-0.8\\baselineskip}\n\t\t\\scalebox{0.64}{\\begin{minipage}{1.5625\\textwidth}\n\t\t\t\\begin{algorithm}[H]\n\t\t\t\t\\caption{}\n\t\t\t\t\\begin{algorithmic}[1]\n\t\t\t\t\t\\Function{Explain-Feasibility}{$\\mathbf{u}$, $\\mathbf{c}$}\n\t\t\t\t\t\t\\If{$m=0$}\n\t\t\t\t\t\t\t\\If{$n=0$}\n\t\t\t\t\t\t\t\t\\State \\emph{There are no jobs, so the schedule is trivially feasible.}\n\t\t\t\t\t\t\t\\Else\n\t\t\t\t\t\t\t\t\\State \\emph{There are no machines to allocate to jobs.}\n\t\t\t\t\t\t\t\\EndIf\n\t\t\t\t\t\t\\Else\n\t\t\t\t\t\t\t\\If{$\\mathbf{u}=\\mathbf{0}\\land\\mathbf{c}=\\mathbf{0}$}\n\t\t\t\t\t\t\t\\State \\emph{All jobs are allocated to exactly one machine.}\n\t\t\t\t\t\t\t\\Else\n\t\t\t\t\t\t\t\\For{$j\\in\\mathcal{J}$}\n\t\t\t\t\t\t\t\\If{$u_{:,j}=1$}\n\t\t\t\t\t\t\t\\State \\emph{Job $j$ is not allocated to any machine.}\n\t\t\t\t\t\t\t\\EndIf\n\t\t\t\t\t\t\t\\If{$c_{:,j,:,j}\\neq\\mathbf{0}$}\n\t\t\t\t\t\t\t\\State \\emph{Job $j$ is over-allocated to machines $\\{i\\ |\\ i\\in\\mathcal{M}, x_{i,j}=1\\}$.}\n\t\t\t\t\t\t\t\\EndIf\n\t\t\t\t\t\t\t\\EndFor\n\t\t\t\t\t\t\t\\EndIf\n\t\t\t\t\t\t\\EndIf\n\t\t\t\t\t\\EndFunction\n\t\t\t\t\t\\end{algorithmic}\n\t\t\t\\end{algorithm}\n\t\t\\end{minipage}}\n\t\\end{frame}\n\n\t\\againframe{pipeline}\n\n\t\\begin{frame}\n\t\t\\frametitle{Algorithms Overview}\n\t\t\\begin{center}\n\t\t\t\\resizebox{0.9\\textwidth}{!}{\\input{algorithms}}\t\t\n\t\t\\end{center}\n\t\\end{frame}\n\n\t\\begin{frame}\n\t\t\\frametitle{Generating Efficiency Explanations}\n\t\t\n\t\t\\begin{columns}\n\t\t\t\\begin{column}{0.5\\textwidth}\n\t\t\t\t\t\t\\begin{itemize}\n\t\t\t\t\t\\item Single and pair-wise exchange properties\n\t\t\t\t\t\\item Fixed decision awareness\n\t\t\t\t\t\\item Explanations are:\n\t\t\t\t\t\\begin{itemize}\n\t\t\t\t\t\t\\item superfluous\n\t\t\t\t\t\t\\item local\n\t\t\t\t\t\t\\item expensive\n\t\t\t\t\t\\end{itemize}\n\t\t\t\t\\end{itemize}\n\t\t\t\\end{column}\n\t\t\t\\begin{column}{0.5\\textwidth}\n\t\t\t\t\\includegraphics[width=\\textwidth]{figures/inefficient_makespan.png}\n\t\t\t\\end{column}\n\t\t\\end{columns}\n\t\\end{frame}\n\n\t\\begin{frame}\n\t\t\\frametitle{Generating Fixed Decisions Explanations}\n\t\t\\scalebox{0.8}{\\begin{minipage}{1.125\\textwidth}\n\t\t\t\\begin{algorithm}[H]\n\t\t\t\t\\caption{}\n\t\t\t\t\\begin{algorithmic}[1]\n\t\t\t\t\t\\Function{Explain-Satisfaction}{$D$, $\\mathbf{u}$, $\\mathbf{c}$}\n\t\t\t\t\t\t\\For{$j\\in\\mathcal{J}$}\n\t\t\t\t\t\t\t\\If{$\\exists i\\in\\mathcal{M}\\ \\pair{i}{j}\\not\\in D^-$}\n\t\t\t\t\t\t\t\t\\State\\emph{Job $j$ cannot be allocated to any machine.}\n\t\t\t\t\t\t\t\\EndIf\n\t\t\t\t\t\t\t\\If{$D^-$ and $D^+$ are not disjoint}\n\t\t\t\t\t\t\t\t\\State\\emph{Job $j$ has conflicting negative and positive fixed decisions.}\n\t\t\t\t\t\t\t\\EndIf\n\t\t\t\t\t\t\t\\If{$|\\{i\\in\\mathcal{M}\\ |\\ \\pair{i}{j}\\in D^+\\}|>1$}\n\t\t\t\t\t\t\t\t\\State\\emph{Job $j$ cannot be allocated to multiple machines.}\t\n\t\t\t\t\t\t\t\\EndIf\n\t\t\t\t\t\t\\EndFor\n\t\t\t\t\t\t\\State ...\n\t\t\t\t\t\\EndFunction\n\t\t\t\t\\end{algorithmic}\n\t\t\t\\end{algorithm}\t\t\n\t\t\\end{minipage}}\n\t\\end{frame}\n\n\t\\begin{frame}\n\t\t\\frametitle{Partial-Precomputation Optimisation}\n\t\t\\begin{itemize}\n\t\t\t\\item $\\twoheadrightarrow$ construction has $\\mathcal{O}(m^2n^2)$ memory usage.\n\t\t\t\\item Inline stability and framework construction algorithms\n\t\t\t\\item Operate on sub-graphs $\\twoheadrightarrow_{i,j}$\n\t\t\\end{itemize}\n\t\t\\vspace{\\baselineskip}\n\t\t\\begin{itemize}\n\t\t\t\\item Full-Precomputation complexity: $\\mathcal{O}(m^2n^2)$\n\t\t\t\\item Partial-Precomputation complexity: $\\mathcal{O}(mn^2)$\n\t\t\\end{itemize}\n\t\\end{frame}\t\n\t\\subsection{Theoretical Extensions}\n\n\t\\begin{frame}\n\t\t\\frametitle{Time-indexed Interval Scheduling}\n\t\t\\begin{columns}\n\t\t\t\\begin{column}{0.5\\textwidth}\n\t\t\t\t\\begin{center}\n\t\t\t\t\t\\includegraphics[width=\\textwidth]{figures/interval_schedule.png}\n\t\t\t\t\\end{center}\n\t\t\t\\end{column}\n\t\t\t\\begin{column}{0.5\\textwidth}\n\t\t\t\t\\begin{itemize}\n\t\t\t\t\t\\item Single-allocation of jobs\n\t\t\t\t\t\\item No overlapping jobs\t\n\t\t\t\t\t\\item Start and finish times\n\t\t\t\t\t\\item Fixed decisions\n\t\t\t\t\\end{itemize}\n\t\t\t\\end{column}\n\t\t\\end{columns}\n\t\\end{frame}\n\n\t\\begin{frame}\n\t\t\\frametitle{Theoretical Applications}\n\t\t\\begin{definition}\n\t\t\tProperty $P$ is stability-modellable iff $\\exists\\pair{Args}{\\rightsquigarrow}.\\pair{Args}{\\rightsquigarrow}$ stability models $P$.\n\t\t\\end{definition}\n\t\t\\begin{theorem}\n\t\t\t\\textnormal{Interval scheduling feasibility is stability-modellable.}\n\t\t\\end{theorem}\n\t\\end{frame}\n\n\t\\begin{frame}\n\t\t\\frametitle{Union of Modelling Frameworks Theorem}\n\t\t\\begin{center}\n\t\t\t\\resizebox{0.9\\textwidth}{!}{\\input{theorem}}\t\t\n\t\t\\end{center}\n\t\\end{frame}\n\n\t\\subsection{Evaluation}\n\n\t\\begin{frame}\n\t\t\\frametitle{Questionnaire}\n\t\t\\begin{columns}\n\t\t\t\\begin{column}{0.5\\textwidth}\n\t\t\t\t\\begin{center}\n\t\t\t\t\t\\fbox{\\includegraphics[scale=0.2,page=1]{../report/questionnaire.pdf}}\n\t\t\t\t\\end{center}\n\t\t\t\\end{column}\n\t\t\t\\begin{column}{0.5\\textwidth}\n\t\t\t\t\\begin{center}\n\t\t\t\t\t\\fbox{\\includegraphics[scale=0.2,page=2]{../report/questionnaire.pdf}}\n\t\t\t\t\\end{center}\n\t\t\t\\end{column}\n\t\t\\end{columns}\n\t\\end{frame}\n\n\t\\begin{frame}\n\t\t\\frametitle{Questionnaire Results}\n\t\t\\begin{center}\n\t\t\t\\includegraphics[width=0.8\\textwidth]{figures/questionnaire_results_summary.png}\n\t\t\\end{center}\n\t\\end{frame}\n\n\t\\begin{frame}\n\t\t\\frametitle{Profiling}\n\t\t\\begin{itemize}\n\t\t\t\\item $m=10$\n\t\t\\end{itemize}\n\t\t\\begin{columns}\n\t\t\t\\begin{column}{0.5\\textwidth}\n\t\t\t\t\\begin{center}\n\t\t\t\t\t\\includegraphics[width=\\textwidth]{figures/cpu_profile.png}\n\t\t\t\t\tCPU Performance\n\t\t\t\t\\end{center}\n\t\t\t\\end{column}\n\t\t\t\\begin{column}{0.5\\textwidth}\n\t\t\t\t\\begin{center}\n\t\t\t\t\t\\includegraphics[width=\\textwidth]{figures/memory_profile.png}\n\t\t\t\t\tMemory Performance\n\t\t\t\t\\end{center}\n\t\t\t\\end{column}\n\t\t\\end{columns}\n\t\\end{frame}\n\n\t\\subsection{Conclusion}\n\t\\begin{frame}\n\t\t\\frametitle{Limitations with Argumentation}\n\t\t\\begin{itemize}\n\t\t\t\\item Memory performance\n\t\t\t\\item Computational performance\n\t\t\t\\item Abstracted interface\n\t\t\t\\item Functional equivalence\n\t\t\t\\item Implementation complexity\n\t\t\\end{itemize}\n\t\\end{frame}\n\n\t\\begin{frame}\n\t\t\\frametitle{Practicability of Argumentation}\n\t\t\\resizebox{\\textwidth}{!}{\\begin{minipage}{\\textwidth}\n\t\t\t\t\\input{../report/problempath}\n\t\t\\end{minipage}}\n\t\\end{frame}\n\n\t\\begin{frame}\n\t\t\\frametitle{Summary}\n\t\t\\begin{center}\n\t\t\t\\begin{tikzpicture}\n\t\t\t\t\\node[draw,align=center](a) at (0, 0){Explaining makespan schedules using argumentation is\\\\practically\n\t\t\t\tpossible but not practically suitable.};\n\t\t\t\\end{tikzpicture}\n\t\t\\end{center}\n\t\\end{frame}\n\n\t\\begin{frame}\n\t\t\\frametitle{Resources}\n\t\t\\begin{center}\n\t\t\tThese slides, report and source code are accessible at \\url{github.com/mylestunglee/aes}.\n\t\t\\end{center}\n\\end{frame}\n\\end{document}", "meta": {"hexsha": "008ecbf0187fb53ed6cfb1d821149e288f5666cb", "size": 13130, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "presentation/main.tex", "max_stars_repo_name": "mylestunglee/aes", "max_stars_repo_head_hexsha": "7aa110c54e631fb8eeb94eedfcb2e63280eddcc7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-06-05T10:10:42.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-20T15:23:54.000Z", "max_issues_repo_path": "presentation/main.tex", "max_issues_repo_name": "mylestunglee/aes", "max_issues_repo_head_hexsha": "7aa110c54e631fb8eeb94eedfcb2e63280eddcc7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "presentation/main.tex", "max_forks_repo_name": "mylestunglee/aes", "max_forks_repo_head_hexsha": "7aa110c54e631fb8eeb94eedfcb2e63280eddcc7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-09-19T11:50:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-29T23:03:07.000Z", "avg_line_length": 27.6421052632, "max_line_length": 182, "alphanum_fraction": 0.6278750952, "num_tokens": 5031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.3322326385035477}}
{"text": "\\documentclass[11pt,a4paper]{article}\n\\usepackage[xetex]{hyperref}\n\\usepackage{mathtools,latexsym,amsfonts,amssymb,MnSymbol}\n\\usepackage{xcolor}\n\\usepackage{fancyhdr}\n\\usepackage{ccicons}\n\\hypersetup{colorlinks=true}\n\\pagestyle{fancy}\n\n\\fancyhf{}\n\\cfoot{\\thepage}\n\\rfoot{\\ccby}\n\\renewcommand{\\headrulewidth}{0.0pt}\n\\renewcommand{\\footrulewidth}{0.0pt}\n\n\\newcommand{\\key}[1]{\\textrm{\\textbf{#1}}}\n\\newcommand{\\nbkey}[1]{\\textrm{#1}}\n\\newcommand{\\record}[1]{\\{\\!\\!\\shortmid #1 \\shortmid\\!\\!\\}}\n\\newcommand{\\overld}[3]{\\largecircle^{#1}_{#2}{#3}}\n\\newcommand{\\irecrd}[2]{\\largesquare^{#1}{#2}}\n\\newcommand{\\tyvarsubst}[2]{#1\\ \\hspace{-0.2ex}:\\hspace{1pt}=\\ #2}\n\\newcommand{\\ovldrefine}[2]{#1\\ \\circ\\hspace{-0.3ex}=\\ #2}\n\\newcommand{\\irecextend}[2]{#1\\ \\smallsquare\\hspace{-0.3ex}=\\ #2}\n\\newcommand{\\lab}{\\nbkey{lab}}\n\\newcommand{\\rigdvar}[1]{\\ddot{#1}}\n\\newcommand{\\flexvar}[1]{\\tilde#1}\n\n\\newcommand{\\comment}[1]{\\textit{\\color{olive}#1}}\n\\newcommand{\\ifclause}[1]{\\textit{if}\\hspace{1.5ex}#1}\n\\newcommand{\\whereclause}[1]{\\textit{where}\\hspace{1.5ex}#1}\n\n\\newcommand{\\unify}[3]{#1\\,{\\color{brown}{\\simeq}}\\,#2 \\Rightarrow #3}\n\\newcommand{\\subst}[2]{[#1]\\,#2}\n\\newcommand{\\braced}[1]{\\{#1\\}}\n\n\\newcommand{\\compose}[2]{#1 \\circ #2}\n\n\\newcommand{\\tycon}{\\mathbb{C}}\n\\newcommand{\\tyfun}{\\zeta}\n\\newcommand{\\type}{\\tau}\n\\newcommand{\\qualtype}[2]{#1 \\triangleright #2}\n\\newcommand{\\scheme}{\\delta}\n\\newcommand{\\substitute}{\\rho}\n\\newcommand{\\equality}{\\epsilon}\n\\newcommand{\\eqyes}{\\equiv}\n\\newcommand{\\eqnot}{\\nequiv}\n\n\\newcommand{\\wildcard}{{\\color{gray}\\scriptstyle\\textbf{*}}}\n\\newcommand{\\vect}[1]{\\overline{#1}}\n\n\\begin{document}\n\n\\title {A pure specification of MLton - Part 1. types}\n\\author{Wu Jiasen $\\langle$\\href{mailto:wujiasen@yahoo.com}{wujiasen@yahoo.com}$\\rangle$}\n\\maketitle \n\\thispagestyle{fancy}\n\n\\section{Type in Standard ML}\n\\newcommand{\\q}     {\\textrm{'}}\n\\newcommand{\\Env}   {\\textrm{E}}\n\\newcommand{\\vdashT}{\\ \\vdash_{\\textrm{\\tiny T}}\\  }\n\\newcommand{\\inTE}  {\\ \\in^{\\textrm{\\tiny TE}}\\  }\n\\[\\begin{array}{lcll}\ntype & = & \\q a                                             & \\\\\n     & | & \\q\\q a                                           & \\\\\n     & | & tycon\\ \\vect{type}              \t            \t&\\comment{constructor}\\\\\n     & | & \\braced{\\vect{\\lab:type}}       \t\t        \t&\\comment{record type}\\\\\n\\end{array}\\]\n\n\\section{Type in Core-Lang}\n{\\renewcommand{\\arraystretch}{1.2}\\[\n\\begin{array}{lcll}\n\\type\n     & = & \\alpha                                           & \\\\\n     & | & \\tycon\\ \\vect\\type              \t            \t&\\comment{constructor}\\\\\n     & | & \\record{\\vect{\\lab:\\type}}       \t\t    \t\t&\\comment{record type}\\\\\n     & | & \\irecrd{\\alpha}{[\\vect{\\lab:\\type}]}         \t\t&\\comment{incomplete record type}\\\\\n     & | & \\overld{\\alpha}{\\type}{[\\vect\\scheme]}     \t\t&\\comment{overloading type}\\\\\n\\alpha \n     & = & \\rigdvar{\\alpha}^{\\equality}                     &\\comment{rigid type variable}\\\\\n     & | & \\flexvar{\\alpha}                                 &\\comment{flexible type variable}\\\\     \n\\\\\n\\qualtype{\\vect\\type_1}{\\type_2} & &                        &\\comment{qualified type} \\\\\n                            & &                             &\\comment{$\\vect\\type_1$ are types that must admit equality} \\\\\n\\\\     \n\\scheme \n     & = & \\forall \\vect{\\alpha}\\,.\\,\\qualtype{\\vect\\type_1}{\\type_2}\n                                                            &\\\\\n\\\\\n\\equality\n\t& = & \\eqyes\t& \\comment{admitting equality}     \\\\\n\t& | & \\eqnot\t& \\comment{not admitting equality} \\\\\n\\\\\n\\substitute\n     & = & \\tyvarsubst{\\alpha}{\\type}                   \t&\\comment{substitute a tyvar}\\\\\n     & | & \\irecextend{\\alpha}{[\\lab:\\type]}\t     \t    &\\comment{extend an incomplete record}\\\\\n     & | & \\ovldrefine{\\alpha}{[\\scheme]}               \t&\\comment{refine a overloading type}\\\\\n\n\\tyfun\n     & = & \\Lambda{\\vect{\\alpha}}\\,.\\,{\\qualtype{\\vect\\type_1}{\\type_2}} \n                                                            &\\comment{type function}\\\\\n\\end{array}\n\\]}\n\n\\section {computing equality of types}\n\\begin{minipage}{0.7\\textwidth}\n\\[\\begin{array}{lcl}\neq(\\rigdvar{\\alpha}^\\equality) \t\t\t\t\t\t&=& \\equality \\\\\neq(\\flexvar{\\alpha})                                &=& \\eqyes    \\\\\neq(\\tycon^\\equality\\ \\vect\\type) \t\t\t\t\t&=& \\equality + eq(\\vect\\type) \\\\\neq(\\record{\\vect{\\lab:\\type}})\t\t\t        \t&=& eq(\\vect\\type)    \\\\\neq(\\irecrd{\\alpha}{[\\vect{\\lab:\\type}]})\t    \t\t&=& eq(\\vect\\type)    \\\\\neq(\\overld{\\alpha}{\\type}{[\\vect\\scheme]})\t\t\t&=& \\eqnot                \\\\\neq(\\type_1\\ \\type_2\\ \\cdots\\ \\type_n)\t\t\t    &=& \\sum_i^n eq(\\type_i)  \\\\\n\\end{array}\\]\n\\end{minipage}\n\\begin{minipage}{0.3\\textwidth}\n\\[\\begin{array}{ccccccccl}\n\\eqyes &+& \\eqyes &=& \\eqyes \\\\\n\\eqnot &+& \\eqnot &=& \\eqnot \\\\\n\\eqyes &+& \\eqnot &=& \\eqnot &+& \\eqyes &=& \\eqnot \\\\\n\\\\ \\\\ \\\\ \\\\ \\\\\n\\end{array}\\]\n\\end{minipage}\n\n\\section {Substitution}\n\\newcommand{\\s}{\\vect{\\delta}}\n\\newcommand{\\ts}{\\vect{\\type}}\n\\vspace{-25pt}\n\\begin{flushright}\n\\framebox{ $\\subst{\\rho}{\\type} \\Rightarrow \\type'$ }\n\\end{flushright}\n{\\renewcommand{\\arraystretch}{1.2}\\[\n\\begin{array}{lcl}\n\\subst{\\tyvarsubst{\\alpha}{\\type_1}}{\\alpha} & \\Rightarrow & \\type_1\t \\\\\n\\subst{\\tyvarsubst{\\alpha}{\\type_1}}{\\tycon\\ \\ts} & \\Rightarrow & \\tycon\\ \\subst{\\tyvarsubst{\\alpha}{\\type_1}}{\\ts} \\\\\n\\subst{\\tyvarsubst{\\alpha}{\\type_1}}{\\record{flds}}   & \\Rightarrow & \\record{\\subst{\\tyvarsubst{\\alpha}{\\type_1}}{flds}}   \\\\\n\\subst{\\tyvarsubst{\\alpha}{\\type_1}}{\\overld{\\alpha}{\\type_2}{\\s_2}} & \\Rightarrow & \\type_1  \\\\\n\\subst{\\tyvarsubst{\\alpha}{\\type_1}}{\\overld{\\beta}{\\type_2}{\\s_2}} & \\Rightarrow & \n    \\overld{\\beta}{\\subst{\\tyvarsubst{\\alpha}{\\type_1}}{\\type_2}}{\\s_2}  \\\\    \n\\subst{\\tyvarsubst{\\alpha}{\\type_1}}{\\irecrd{\\alpha}{flds}} & \\Rightarrow & \\type_1  \\\\\n\\subst{\\tyvarsubst{\\alpha}{\\type_1}}{\\irecrd{\\beta}{flds}} & \\Rightarrow &  \n    \\irecrd{\\beta}{\\subst{\\tyvarsubst{\\alpha}{\\type_1}}{flds}} \\\\\n & & \\\\\n\\subst{\\ovldrefine{\\alpha}{\\s_1}}{\\alpha} & \\Rightarrow & \\perp\t \\\\\n\\subst{\\ovldrefine{\\alpha}{\\s_1}}{\\tycon\\ \\ts} & \\Rightarrow & \\tycon\\ \\subst{\\ovldrefine{\\alpha}{\\s_1}}{\\ts} \\\\\n\\subst{\\ovldrefine{\\alpha}{\\s_1}}{\\record{flds}}   & \\Rightarrow & \\record{\\subst{\\ovldrefine{\\alpha}{\\s_1}}{flds}}   \\\\\n\\subst{\\ovldrefine{\\alpha}{\\s_1}}{\\overld{\\alpha}{\\type}{\\s_2}} & \\Rightarrow & \\overld{\\alpha}{\\type}{\\s_1} \n    \\quad\\ifclause{\\s_1 \\subseteq \\s_2} \\\\\n\\subst{\\ovldrefine{\\alpha}{\\s_1}}{\\overld{\\beta}{\\type}{\\s_2}} & \\Rightarrow & \n    \\overld{\\beta}{\\subst{\\ovldrefine{\\alpha}{\\s_1}}{\\type}}{\\s_2} \\\\\n\\subst{\\ovldrefine{\\alpha}{\\s_1}}{\\irecrd{\\beta}{flds}} & \\Rightarrow & \n    \\irecrd{\\beta}{\\subst{\\ovldrefine{\\alpha}{\\s_1}}{flds_1}} \\\\ \n & & \\\\\n\\subst{\\irecextend{\\alpha}{flds_1}}{\\alpha}                 & \\Rightarrow & \\perp\t \\\\\n\\subst{\\irecextend{\\alpha}{flds_1}}{\\tycon\\ \\ts}        & \\Rightarrow & \\tycon\\ \\subst{\\irecextend{\\alpha}{flds_1}}{\\ts} \\\\\n\\subst{\\irecextend{\\alpha}{flds_1}}{\\record{flds_2}}        & \\Rightarrow & \\record{\\subst{\\irecextend{\\alpha}{flds_1}}{flds_2}}\\\\\n\\subst{\\irecextend{\\alpha}{flds_1}}{\\overld{\\beta}{\\type}{\\s}}   & \\Rightarrow & \\overld{\\beta}{\\subst{\\irecextend{\\alpha}{flds_1}}{\\type}}{\\s} \\\\\n\\subst{\\irecextend{\\alpha}{flds_1}}{\\irecrd{\\alpha}{flds_2}}& \\Rightarrow & \\irecrd{\\alpha}{flds_1}\\\\\n\\subst{\\irecextend{\\alpha}{flds_1}}{\\irecrd{\\beta}{flds_2}} & \\Rightarrow & \\irecrd{\\alpha}{\\subst{\\irecextend{\\alpha}{flds_1}}{flds_2}}\\\\\n & & \\\\\n\\subst{\\rho}{\\qualtype{\\vect\\type_1}{\\type_2}}              & \\Rightarrow & \\qualtype{\\subst{\\rho}{\\vect\\type_1}}{\\subst{\\rho}{\\type_2}} \\\\\n\\subst{\\rho}{\\type_1\\ \\type_2\\ \\cdots\\ \\type_n} \t\t\t& \\Rightarrow & \\subst{\\rho}\\type_1\\ \\subst{\\rho}\\type_2\\ \\cdots \\subst{\\rho}\\type_n \\\\\n\\end{array}\n\\]}\n\n\\section {Generalization and Instantiation}\n{\\renewcommand{\\arraystretch}{1.2}\\[\\begin{array}{lcll}\nfree(\\alpha)                  & = & \\braced{\\alpha}                 &       \\\\\nfree({\\tycon\\ \\ts})           & = & free(\\ts)                 \t\t&       \\\\\nfree(\\record{flds})           & = & free(flds)                      &       \\\\\nfree({\\overld{\\alpha}{\\type}{\\s}}) & = & \\braced{\\alpha} \\cup free(\\type)    & \\\\\nfree({\\irecrd{\\alpha}{flds}}) & = & \\braced{\\alpha} \\cup free(flds) &       \\\\\nfree(\\qualtype{\\vect\\type_1}{\\type_2})\n                              & = & free(\\vect\\type_1) \\cup free(\\type_2)&       \\\\\nfree(\\type_1\\ \\type_2\\ \\cdots\\ \\type_n)\n\t\t\t\t\t\t\t  & = & free(\\type_1) \\cup free(\\type_2) \\cdots \\cup free(\\type_n) & \\\\                           \n& & \\\\\ngen_{env}(\\qualtype{\\vect\\type_1}{\\type_2})\n                              & = & \\forall \\vect{\\alpha}. \\qualtype{\\vect\\type_1}{\\type_2}\n                                                                    & \\whereclause{\\vect{\\alpha} = free(\\qualtype{\\type_1}{\\type_2}) - free(env)} \\\\\ninst(\\forall \\vect{\\alpha}.\\qualtype{\\vect\\type_1}{\\type_2})\n                              & = &[\\rho]\\qualtype{\\vect\\type_1}{\\type_2}& \\whereclause{\\rho = \\braced{\\alpha_i \\mapsto \\flexvar{\\beta}_i \\ |\\ \\flexvar{\\beta}_i\\ \\textrm{is a fresh tyvar}}} \\\\\n\\end{array}\\]}\n\n\\section{Instance relationship}\n\\vspace{-25pt}\n\\begin{flushright}\n\\framebox{ $\\type \\prec \\scheme$}\n\\end{flushright}\n\\[\n\t\\cfrac{ \\unify{\\type}{inst(\\s)}{\\_}}{\\type \\prec \\s}\n\\]\n\n\\section{Unification}\n\\vspace{-25pt}\n\\begin{flushright}\n\\framebox{ $\\unify{\\type_1}{\\type_2}{\\rho}$}\n\\end{flushright}\n\n\\[\n\\begin{array}{ccc}\n \\multicolumn{3}{c}{\\unify{\\alpha}{\\alpha}{\\braced{}}} \\\\\n &                                                                                                          \\\\\n {\\unify{\\flexvar{\\alpha}}{\\type}{\\{\\tyvarsubst{\\flexvar\\alpha}{\\type}\\}}} & \\quad & \n {\\unify{\\type}{\\flexvar{\\alpha}}{\\{\\tyvarsubst{\\flexvar\\alpha}{\\type}\\}}}                                  \\\\\n &                                                                                                          \\\\\n {\\unify{\\rigdvar{\\alpha}}{\\type}{\\perp}} & \\quad & \n {\\unify{\\type}{\\rigdvar{\\alpha}}{\\perp}}                                                                   \\\\\n &                                                                                                          \\\\\n \\unify{\\tycon_1\\ \\ts}{\\record{flds}}{\\perp}     & \\quad & \\unify{\\record{flds}}{\\tycon_1\\ \\ts}{\\perp}      \\\\      \n &                                                                                                          \\\\\n \\unify{\\tycon_1\\ \\ts}{\\irecrd{\\alpha}{flds}}{\\perp} & \\quad & \\unify{\\irecrd{\\alpha}{flds}}{\\tycon_1\\ \\ts}{\\perp}  \\\\      \n &                                                                                                          \\\\\n \\cfrac\n  {\\unify{\\ts_1}{\\ts_2}{\\rho} \\quad \\tycon_1 = \\tycon_2}\n  {\\unify{\\tycon_1\\ \\ts_1}{\\tycon_2\\ \\ts_2}{\\rho}} & \\quad &\n \\cfrac\n  {\\tycon_1 \\ne \\tycon_2}\n  {\\unify{\\tycon_1\\ \\ts_1}{\\tycon_2\\ \\ts_2}{\\perp}}                                                         \\\\\n &                                                                                                          \\\\\n \\multicolumn{3}{c}{ \\cfrac\n  {\\unify{flds_1}{flds_2}{\\rho}}\n  {\\unify{\\record{flds_1}}{\\record{flds_2}}{\\rho}} }                                                        \\\\\n\\end{array}\n\\]\n\\[\n\\begin{array}{ccc}\n \\multicolumn{3}{c}{\\cfrac\n  {\\unify{\\alpha_1}{\\alpha_2}{\\rho_1} \\quad \\unify{\\subst{\\rho_1}{\\type_1}}{\\subst{\\rho_2}{\\type_2}}{\\rho_2} \\quad\n   \\exists \\s \\in \\s_1 \\cap \\s_2. (\\subst{\\rho_2}{\\type_1} \\prec \\s)}\n  {\\unify{\\overld{\\alpha}{\\type_1}{\\s_1}}{\\overld{\\alpha}{\\type_2}{\\s_2}}\n         {\\rho_2 \\circ \\{\\ovldrefine{\\subst{\\rho_1}{\\alpha_1}}{\\s_1 \\cap \\s_2}\\} \\circ \\rho_1}}}              \\\\\n & &                                                                                                        \\\\\n \\cfrac\n  {\\unify{\\type_1}{\\type_2}{\\rho} \\quad \\exists \\s \\in \\s_1. (\\subst{\\rho}{\\type_1} \\prec \\s)}\n  {\\unify{\\overld{\\alpha}{\\type_1}{\\s_1}}{\\type_2}{\\rho}} & \\quad &\n \\cfrac\n  {\\unify{\\type_1}{\\type_2}{\\rho} \\quad \\exists s \\in \\s_1. (\\subst{\\rho}{\\type_2} \\prec s)}\n  {\\unify{\\type_1}{\\overld{\\alpha_2}{\\type_2}{\\s_1}}{\\rho}}                                                          \\\\\n & &                                                                                                        \\\\\n \\multicolumn{3}{c}{\\cfrac\n  {\\unify{\\alpha_1}{\\alpha_2}{\\rho_1} \\quad\n   \\unify{\\subst{\\rho_1}{flds_1}}{\\subst{\\rho_1}{flds_2}}{\\rho_2} \\quad\n   flds_1 \\subseteq flds_2 \\vee flds_2 \\subseteq flds_1 }\n  {\\unify{\\irecrd{\\alpha_1}{flds_1}}{\\irecrd{\\alpha_2}{flds_2}}\n         {\\rho_2 \\circ \\{\\irecextend{\\subst{\\rho_1}{\\alpha_1}}{flds_1 \\cup flds_2}\\} \\circ \\rho_1}}}        \\\\\n & &                                                                                                        \\\\\n \\multicolumn{3}{c}{\\cfrac\n  {\\unify{flds_1}{flds_2}{\\rho} \\quad flds_1 \\subseteq flds_2}\n  {\\unify{\\irecrd{\\alpha_1}{flds_1}}{\\record{flds_2}}\n         {\\compose{\\braced{\\tyvarsubst{\\alpha_1}{[\\rho]flds_2}}}{\\rho}}}}                                   \\\\\n & &                                \\\\\n \\multicolumn{3}{c}{\\cfrac\n  {\\unify{flds_1}{flds_2}{\\rho} \\quad flds_1 \\subseteq flds_2}\n  {\\unify{\\record{flds_2}}{\\irecrd{\\alpha_1}{flds_1}}\n         {\\compose{\\braced{\\tyvarsubst{\\alpha_1}{[\\rho]flds_2}}}{\\rho}}}}                                   \\\\\n\\end{array}\n\\]\n\n\\section{Elaboration of types}\n\\vspace{-25pt}\n\\begin{flushright}\n\\framebox{ $ \\Env, type \\vdashT \\qualtype{\\vect\\type_1}{\\type_2}$ }\n\\end{flushright}\n\\[\n  \\Env, \\q a \\vdashT \\qualtype{}{\\rigdvar{\\alpha}^{\\eqnot}}\n\\]\n\\[\n  \\Env, \\q\\q a \\vdashT \\qualtype{\\braced{\\rigdvar{\\alpha}^{\\eqyes}}}{\\rigdvar{\\alpha}^{\\eqyes}}\n\\]\n\\[\n\\cfrac\n {tycon \\mapsto (k, \\tycon^\\equality,\\wildcard) \\inTE \\Env    \\qquad\n  \\Env,type_i\\vdash \\qualtype{p_i}{\\type_i}}\n {\\Env, tycon\\ \\vect{type}^{(k)} \\vdashT \\qualtype{(\\sum_{i} p_i)}{\\tycon^\\equality\\ \\vect{\\type}}}\n\\]\n\\[\n\\cfrac\n {tycon \\mapsto (k, \\zeta,\\wildcard) \\inTE \\Env    \\qquad\n  \\Env,type_i\\vdash \\qualtype{p_i}{\\type_i}}\n {\\Env, tycon\\ \\vect{type}^{(k)} \\vdashT \\qualtype{(\\sum_{i} p_i)}{\\zeta\\ \\vect{\\type}}}\n\\]\n\n\\[\n\\cfrac\n {\\Env,type_i\\vdash \\qualtype{p_i}{\\type_i}}\n {\\Env, \\braced{\\vect{\\lab:type}} \\vdashT \\qualtype{(\\sum_{i} p_i)}{\\record{\\vect{\\lab:\\type}}}}\n\\]\n\n\\end{document}\n", "meta": {"hexsha": "acd4ca0f21b75716ee5e4886ef915256d5aaf89c", "size": 14115, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "type.tex", "max_stars_repo_name": "pierric/sml-pure-spec", "max_stars_repo_head_hexsha": "cf48f75491f0c5f1490b96f84bbf8f12220aa63a", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "type.tex", "max_issues_repo_name": "pierric/sml-pure-spec", "max_issues_repo_head_hexsha": "cf48f75491f0c5f1490b96f84bbf8f12220aa63a", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "type.tex", "max_forks_repo_name": "pierric/sml-pure-spec", "max_forks_repo_head_hexsha": "cf48f75491f0c5f1490b96f84bbf8f12220aa63a", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.3390410959, "max_line_length": 192, "alphanum_fraction": 0.5187389302, "num_tokens": 4924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.3321752986351802}}
{"text": "\\documentclass[11pt]{article}\n\\usepackage{amsmath}\n\\usepackage{setspace}\n\\usepackage{pxfonts}\n%\\usepackage{graphicx}\n\\usepackage{geometry}\n\n\n\\geometry{letterpaper,left=.5in,right=.5in,top=0.5in,bottom=.75in,headsep=5pt,footskip=20pt}\n\n\\title{PSYC 51.09: Problem Set 5}\n%\\author{Jeremy R. Manning}\n\\date{}\n\n\\begin{document}\n\\maketitle\n\\vspace{-0.75in}\n\\section*{Introduction}\nThis problem set is intended to solidify the concepts you learned about in this week's lectures and readings.  Your responses will be worth 3\\% of your final grade.  You are encouraged to work together with your classmates in small groups, and/or to post and answer questions on the course’s Canvas site.  \\textbf{\\textit{However, you must clearly indicate who your collaborated with and submit your own (uniquely worded) responses.}}\n\nWe will go over the answers to this problem set in class on \\textbf{Monday, February 15, 2016 at 1:45 pm}.  You must upload your answers before then in order to receive credit.  No late submissions will be accepted.\n\n\\section*{Readings}\n\\begin{enumerate}\n\\item Read Chapter 5 of \\textit{Foundations of Human Memory} (if you\n  have not already done so).  What were your thoughts on the reading?\n  \\textbf{(Ungraded)}\n\n\\item Read Chapter 6 of \\textit{Foundations of Human Memory}.  What were your thoughts on the reading?\n  \\textbf{(Ungraded)}\n\\end{enumerate}\n\n\\section*{Graded questions}\n\nFor this problem set, your job is to create your own neural\n  network model of memory (a Hopfield network).  Below are two\n  memories, $\\mathbf{m}_1$ and $\\mathbf{m}_2$ that you will store in\n  your network.  Use the techniques we discussed in class (and in\n  the book), along with the provided equations, to answer the\n  following questions.  Show your work!\n\\[\n  \\mathbf{m}_1=\n  \\begin{pmatrix}\n    1\\\\\n    -1\\\\\n    -1\\\\\n    1\\\\\n    -1\\\\\n    -1\n  \\end{pmatrix}\\quad\n  \\mathbf{m}_2=\n  \\begin{pmatrix}\n    -1\\\\\n    -1\\\\\n    1\\\\\n    -1\\\\\n    -1\\\\\n    1\\\\\n  \\end{pmatrix}\\quad\n\\mathbf{x}_1=\n  \\begin{pmatrix}\n    -1\\\\\n    -1\\\\\n    0\\\\\n    0\\\\\n    0\\\\\n    0\\\\\n  \\end{pmatrix}\\quad\n\\mathbf{x}_2=\n  \\begin{pmatrix}\n    1\\\\\n    -1\\\\\n    0\\\\\n    0\\\\\n    0\\\\\n    0\\\\\n  \\end{pmatrix}\n\\]\nLearning rule:\n\\[\nW(i,j) = \\sum_{k = 1}^L a_k(i)a_k(j)\n\\]\nDynamic rule:\n\\[\na(i) = \\mathrm{sign}\\left(\\sum_{j=1}^N W(i,j)a(j)\\right)\n\\]\n\n\\begin{enumerate}\n\\item Create a weight matrix, using Hebbian learning, that contains\n  both $\\mathbf{m}_1$ and $\\mathbf{m}_2$ as stable memories.\n  \\textbf{(1.5 points)}\n\n\\item For each of the partial cues, $\\mathbf{x}_1$ and $\\mathbf{x}_2$,\n  the activity of the first two neurons is known.  Use\n  \\textbf{asynchronous updating} to calculate the activities of the\n  remaining four neurons (in whatever order you want).  Can the\n  network retrieve both memories?  Hint: update neurons 3, 4, 5, and 6\n  (in any order).  Then continue updating those 4 neurons until none of the\n  values change to show that the network has stabilized.\\textbf{(1.5 points)}\n\\end{enumerate}\n\n\\end{document}\n\n\n", "meta": {"hexsha": "c1c4106165aad1fc829b9423ec11ea5bb72587cc", "size": 3002, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "problem sets/previous years/problem set 5/ps5_2016.tex", "max_stars_repo_name": "dougs-repos/human-memory", "max_stars_repo_head_hexsha": "4d6e7aa8ad7213432e43fa4a9df0ebe32f407dea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-11T21:59:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-11T21:59:45.000Z", "max_issues_repo_path": "problem sets/previous years/problem set 5/ps5_2016.tex", "max_issues_repo_name": "AshBT/human-memory", "max_issues_repo_head_hexsha": "4d6e7aa8ad7213432e43fa4a9df0ebe32f407dea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problem sets/previous years/problem set 5/ps5_2016.tex", "max_forks_repo_name": "AshBT/human-memory", "max_forks_repo_head_hexsha": "4d6e7aa8ad7213432e43fa4a9df0ebe32f407dea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-26T11:48:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-26T11:48:41.000Z", "avg_line_length": 28.5904761905, "max_line_length": 434, "alphanum_fraction": 0.6935376416, "num_tokens": 958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.33217529511315275}}
{"text": "\\section{Parallel Partitioning and Subsampling of Meshes}\\label{sec:parallel_partitioning_and_sampling_of_the}\n\n% dedicated solver\n\nThe derivation of increasingly detailed models in the domain of biomechanics has to be complemented by engineering of efficient software that is used to solve these models. Using proper parallelization allows to increase the amount of computational load that is possible to handle. In turn, this allows to simulate more complex models with higher resolution and ultimately enables physiological and pathological insights on a new level.\n\nFor detailed multi-scale model solvers, parallelization is a complex task. \nThe paradigm has to be regarded  during the whole setup process of the system. Different descriptions for the same physical behavior have to be evaluated with respect to their solvability in parallel. For a given model, suitably parallelizable numerical solution schemes have to be selected. The implementation of individual solvers and their coupling have to take into account the parallel environment. \nDiscretization schemes enabling parallel domain decomposition are required. Their representation on compute hardware with distributed memory has to be taken into account as well as ensuring acceptable conditioning of large scale problems. To ensure fast runtimes, load balancing between compute nodes and parallel scalability are important.\n\nAll these fundamental considerations potentially depend on each other and require a comprehensive solution. \nThus, it is often difficult to port existing, isolated solver software that was designed for serial or moderately parallel execution to efficiently fit into a highly-parallel, multi-scale solution framework. To not (re-)create this kind of isolated solvers for individual model components, we focus on their parallel design from the ground up in the current and following sections.\n\nIn this section, we introduce algorithms for the generation of parallel partitioned meshes, which are fundamental ingredients to all our solvers. The parallel organization of the data and their indexing using various numbering schemes\nhas already been discussed in \\cref{sec:oragnization_of_parallel_partitioned_data} and \\cref{sec:numbering_schemes_for}, respectively. \nIn the following, we consider the parallel partitioning problem on a higher level and provide algorithms to construct the domain decomposition for various meshes in the multi-scale model discretization. Meshes with different mesh widths are obtained by subsampling a finely resolved initial mesh, which is the outcome of the algorithms described in \\cref{sec:generation_of_meshes_for_multiscale}, and, in practice, is given to a particular simulation program by the respective mesh input file.\n\n\\Cref{sec:algorithm_for_partitioning_and_sampling,sec:partitioning_requirements} set the scene and define our requirements for well-behaved parallelized meshes. \\Cref{sec:partitioning_alg1,sec:partitioning_alg2} give details on the implemented algorithms and \\cref{sec:partitioning_user_options} addresses the configuration for the user. \\Cref{sec:partitioning_results} concludes by comparing the resulting partitionings for different parameters.\n%The subsequent sections present the parallel solvers for various parts of the multi-scale model.\n\n\n%\\subsection{Algorithm for Partitioning and Sampling the 3D Mesh}\\label{sec:algorithm_for_partitioning_and_sampling}\n\\subsection{Specification of the Partitioning}\\label{sec:algorithm_for_partitioning_and_sampling}\n\nStructured meshes of the types \\code{RegularFixed}\\code{OfDimension<D>} or \\code{Structured}\\code{Deformable}\\code{OfDimension<D>} are partitioned for parallel execution by distributing the elements to all processes. As mentioned in \\cref{sec:oragnization_of_parallel_partitioned_data}, planar cuts in the space of the element indices separate the subdomains. For example, in computations on a structured 3D mesh with $N_x^\\text{el} \\times N_y^\\text{el} \\times N_z^\\text{el}$ global elements, the process with rank $r$ owns a subdomain with\n$N_x^{\\text{el,local,}r} \\times N_y^{\\text{el,local,}r} \\times N_z^{\\text{el,local,}r}$ local elements.\nThe sizes of the local subdomains depend on the specified total number of subdomains $n_i$ in each coordinate direction $i \\in \\{x,y,z\\}$.\nGiven $n_i$, the number of local elements in every subdomain along the coordinate axis $i$ can be set to either $N_i^{\\text{el,local}} = \\lfloor N^\\text{el}_i/n_i+1\\rfloor$ or $N_i^{\\text{el,local}} = \\lfloor N^\\text{el}_i/n_i \\rfloor$ to allow for good load balancing.\n\nA prerequisite to construct such a partitioning for $n_\\text{proc}$ processes is to fix the numbers of subdomains $n_x \\times n_y \\times n_z = n_\\text{proc}$. In OpenDiHu, the Python settings file can either specify the global numbers $N_i^\\text{el}$ of elements or separate local numbers $N_i^{\\text{el,local,}r}$ of elements for every rank $r$. This step involves setting the option \\code{inputMeshIsGlobal} to either \\code{True} or \\code{False} as explained in \\cref{sec:exemplary_usage_1}.\n\nSpecifying the global numbers of elements is often useful for toy problems, when the total element count is small and the actual partitioning is not important. In this case, PETSc is used to determine optimal subdomain sizes for all processes and, subsequently, constructing the partitioning. Because the partitioning is not yet known at the time of parsing of the Python settings, spatial information such as node positions or boundary conditions have to be specified on every rank for the whole domain.\n\nMost of the electrophysiology examples, however, use the specification of local numbers of elements. Thus, every rank only needs to specify the local data of its subdomain, such as node positions and boundary conditions. This is a prerequisite for good parallel weak scaling behavior, as the amount of data processing on each process stays constant when simultaneously increasing problem size and total process counts.\n\nIn the electrophysiology examples, the partitioning into $n_x \\times n_y \\times n_z$ subdomains can be specified by the command line parameter \\code{--n_subdomains n_x n_y n_z}, where \\code{n_x}, \\code{n_y} and \\code{n_z} are replaced by the actual numbers. Their product has to match the process count $n_\\text{proc}$ that is given to MPI to start the program.\nIf this option is not specified, the values are determined automatically by the following algorithm: For all partitions of the number $n_\\text{proc}$ into three integer factors, a performance value $p$ is computed as follows:\n%\n\\begin{align*}\n  p = (n_x-n_\\text{opt})^2 + (n_y-n_\\text{opt})^2 + (n_z-n_\\text{opt})^2.\n\\end{align*}\nThe optimal value is given by $n_\\text{opt} = n_\\text{proc}^{1/3}$, which, in general, is not an integer. The partitioning with the lowest value of $p$ is selected among all partitions, as it leads to nearly cuboid subdomains with the best volume-to-surface ratio. An advantage of this method is that it is independent of the mesh size.\n\n\\subsection{Requirements for Partitioning and Sampling of the 3D Mesh Based on 1D Fiber Meshes}\\label{sec:partitioning_requirements}\n%\\subsection{Requirements for Partitioning and Sampling of the 3D Mesh}\n\nNext, we specify desired properties of the parallel partitioned 3D meshes, which are used together with 1D muscle fiber meshes in the discretization of fiber based multi-scale models. Subsequently, we construct an algorithm to generate the accordingly partitioned 3D meshes in parallel by sampling a finer dataset based on 1D fiber meshes.\n\nSimulation scenarios with fiber based electrophysiology use a 3D muscle mesh and embedded 1D fiber meshes, which are generated from the same node positions as described in \\cref{sec:postprocessing_of_the_generated_streamlines}. The binary input file contains a structured grid of points, which can be either interpreted as 1D fibers by connecting the points in $z$-direction or as 3D mesh by additionally connection points in $x$ and $y$-directions.\n\nUsually, all points in such a file are used to define the 1D fiber meshes and the 3D mesh is constructed from only a subset of the available points. To obtain a 3D mesh with approximately equal mesh widths in all coordinate directions, the point data are sampled by constant strides in $x$, $y$ and $z$ direction.  The stride in fiber direction ($z$ direction) is typically chosen larger than the strides in transverse directions as the distance between the given points is smaller in this direction.\n\nIn the following, we discuss the sampling procedure that generates the partitioned 3D mesh from the fiber data in more detail.\nGiven a structured hexahedral fine 3D mesh, numbers of subdomains $n_i$ and sampling stride parameters \\code{sampling_stride_$i$} for the three coordinate directions $i\\in\\{x,y,z\\}$, we have to determine the nodes that should be part of each subdomain in the resulting coarser hexahedral 3D mesh. \n\nFor illustration, \\cref{fig:partitioning1} shows the initial fine mesh visualized by spheres that are arranged in fibers, that run from the shown cross-section to the back. The resulting sampled mesh is given by the white elements and uses a subset of the nodes in the fine mesh. The sampled mesh is partitioned into the colored subdomains. \nFurthermore, the coarse mesh consists of quadratic elements that are formed from two by two white standard elements, in the cross-section each. Hence, every subdomain contains an even number of the white elements in horizontal and vertical directions.\n\n% quadratic partitioning\n\\begin{figure}\n  \\centering%\n  \\includegraphics[width=\\textwidth]{images/implementation/partitioning7.png}%\n  \\caption{Partitioning and subsampling of a fiber mesh to twelve processes. The fiber data indicated by the spheres are sampled with a stride parameter of two to obtain the partitioned quadratic coarse mesh given by the white elements. The subdomains are indicated by different colors. The image shows a perspective view on the top 2D face of the 3D muscle mesh.}%\n  \\label{fig:partitioning1}%\n\\end{figure}%\n\nThe requirements for the sampling and partitioning algorithm are as follows: \n\\begin{enumerate}[label=(\\roman*)]\n\\item The resulting coarser 3D mesh should use every $k$th node, where $k$ is adjustable by the parameter \\code{sampling_stride_$i$} in the settings.\n\\item The number of nodes in every subdomain should be approximately equal to allow for a good load balancing in the computation.\n\\item There should be as little \\say{remainder elements} that have a different mesh width than the majority of the elements as possible.\n\\item If a quadratic shape functions are required, e.g., for solid mechanics models, the number of (standard) elements in every subdomain in every coordinate direction has to be even to allow for the generation of quadratic hexahedral elements.\n\\end{enumerate}\n\nClearly, not all requirements can be fulfilled exactly for all given input meshes. For combinations of given input mesh sizes and sampling strides that lead to an even number of sampled nodes, requirement (iv) cannot be fulfilled. \nExact fulfillment of requirement (ii), i.e., an equal number of nodes in every subdomain is also only possible for suited parameter choices. Therefore, we relax requirement (i) and also occasionally allow different step widths between the selected nodes on the fine grid. Having varying distances between the nodes leads to elements with different mesh widths, which is unfavorable in terms of the numerical conditioning of the problem. Therefore, the number of such elements should be as low as possible, which is also stated by requirement (iii).\n\nTo avoid differently sized elements as far as possible, we work with a granularity parameter. This parameter specifies the amount of nodes to summarize and treat as an indivisible unit. For example, a value of \\code{granularity_x=2} specifies that pairs of two neighboring points are in the same element. Then, subdomain boundaries and element boundaries can only occur at every second node.\n\n\\subsection{Algorithm for Partitioning and Sampling of the 3D Mesh Based on 1D Fiber Meshes}\\label{sec:partitioning_alg1}\n\nImportant steps in the algorithm for sampling the fine mesh and constructing the partitioning are, first, to determine the locations of the new subdomains in the original fine grid, second, to determine the number of sampled points in each subdomain and third, to determine which points from the fine grid will be sampled in every subdomain of the coarse grid. The steps have to be carried out independently for all three coordinate directions. Thus, it suffices to only consider the algorithm for the partitioning along one axis.\nIn the following, we present the algorithms of the first two steps for the $x$-axis. \n\nThe algorithm for the first step is given in \\cref{alg:n_fibers_in_subdomain}. Input to the function \\code{n_fibers_in_}\\code{subdomain_x} is a subdomain coordinate in the range $[0,n_x-1]$ that identifies the subdomain. The output to be computed is the number of grid points in the fine grid or, equivalently, the number of fibers that are contained in the subdomain. Calling this function for all subdomains defines the partitioning of the fine grid.\n\n% partitioning algorithm\n\\begin{figure}\n  \\centering%\n  \\includegraphics[width=\\textwidth]{images/implementation/partitioning_algorithm.pdf}%\n  \\caption{Visualization of the steps of the partitioning algorithms given by \\cref{alg:n_fibers_in_subdomain,alg:n_sampled_points_in_subdomain} that yield the partitioning shown in \\cref{fig:partitioning1}.}%\n  \\label{fig:partitioning_algorithm}%\n\\end{figure}%\n\n\\begin{algorithm}\n  \\begin{algorithmic}[1]%\n    \\Procedure{n\\_fibers\\_in\\_subdomain\\_x}{subdomain\\_coordinate\\_x}\n    \\Require Index of a subdomain in $x$-direction\n    \\Ensure Number of fibers that are contained in this subdomain\n    \\Statex\n    \\State   $\\alpha$ = $\\lfloor$ n\\_fibers\\_x / $n_x$ / granularity\\_x $\\rfloor$ * granularity\\_x   \\label{alg:3.2}\n    \\Statex\n    \\State a1 = $\\lfloor$(n\\_fibers\\_x - $n_x$ * $\\alpha$) / granularity\\_x $\\rfloor$ \\label{alg:3.3}  \\Comment{subdomains with $>\\alpha$ nodes}\n    \\State a2 = $n_x$ - a1                        \\label{alg:3.4}              \\Comment{subdomains with $\\alpha $ nodes}\n    \\Statex\n    \\If{subdomain\\_coordinate\\_x < a1} \\Comment{first a1 subdomains} \\label{alg:3.5}\n      \\State \\textbf{return} $\\alpha$ + granularity\\_x \\label{alg:3.6}\n    \\ElsIf{subdomain\\_coordinate\\_x < $n_x$ - 1}\\label{alg:3.7}\n      \\State \\textbf{return} $\\alpha$                        \\label{alg:3.8}\n    \\Else  \\Comment{last subdomain}  \\label{alg:3.9}\n      \\State \\textbf{return} $\\alpha$ + n\\_fibers\\_x \\% granularity\\_x  \\label{alg:3.10}\n    \\EndIf\n    \\EndProcedure\n  \\end{algorithmic}%\n  \\caption{Computation of subdomain sizes, needed for the construction of a parallel partitioning.}%\n  \\label{alg:n_fibers_in_subdomain}%\n\\end{algorithm}%\n\n\\Cref{fig:partitioning_algorithm} provides a visualization of the algorithmic steps, corresponding to the partitioning in vertical direction of the mesh shown in \\cref{fig:partitioning1}. \\Cref{fig:partitioning_algorithm} (a) shows a 1D mesh with \\code{n_fibers_x=23} nodes or fibers.\n% By comparing with \\cref{fig:partitioning1}, it can be seen that nodes and fibers are equivalent in this point of view.\nThe goal is to partition them to $n_x=3$ subdomains. According to requirement (ii), the nodes should be distributed equally to the subdomains. Dividing 23 nodes by 3 subdomains yields an average number of $7\\frac23$ nodes per subdomain, which is indicated by the orange color in \\cref{fig:partitioning_algorithm} (a). \n\nFor now, we neglect the granularity parameter and set \\code{granularity_x=1}. \nLine \\ref{alg:3.2} of the algorithm computes the rounded down value $\\alpha$ of the average number fraction. Every subdomain should obtain either $\\alpha$ or $(\\alpha+1)$ nodes. We specify that the first \\code{a1} subdomains obtain $(\\alpha+1)$ nodes and the remaining subdomains obtain $\\alpha$ nodes. \nThe amount of nodes that remain after we fill every subdomain with $\\alpha$ nodes is the difference between all nodes \\code{n_fibers_x} and  $n_x \\cdot \\alpha$. This difference is equal to \\code{a1} and the formula in line \\ref{alg:3.3} of the algorithm computes the value of \\code{a1} accordingly. The remainder number of subdomains \\code{a2} follows as given in line \\ref{alg:3.4}.\nThe visualization in \\cref{fig:partitioning_algorithm} (b) shows that, in the example, \\code{a1=2} subdomains obtain $\\alpha+1=8$ nodes and only the last subdomain, i.e., \\code{a2=1}, obtains $\\alpha=7$ nodes.\n\nThe rest of \\cref{alg:n_fibers_in_subdomain} checks whether the given subdomain coordinate \\code{subdomain}\\code{_coor}\\code{dinate_x} refers to a subdomain with $(\\alpha+1)$ or with $\\alpha$ nodes by comparing the coordinate with \\code{a1} in line \\ref{alg:3.5}. The first branch of the \\code{if} statement returns the high number of nodes $(\\alpha+1)$, the other branches return the low number $\\alpha$, as far as the granularity parameter is neglected.\n\nNext, we discuss the algorithm with a granularity value that is different from 1. \nAssuming a value of, e.g., \\code{granularity_x=2}, always two neighboring nodes are grouped and the algorithm acts on these groups instead of individual nodes. The visualization in \\cref{fig:partitioning_algorithm} (c) shows this grouping. Because the considered example has an odd total number of 23 nodes, only a single nodes remains for the last group.\n\nThe number of nodes per subdomains should now be a multiple of the granularity. This is ensured in line \\ref{alg:3.2} of \\cref{alg:n_fibers_in_subdomain} by dividing by the granularity, rounding down and multiplying again with the granularity. The subdomains obtain either \\code{$\\alpha$} or \\code{($\\alpha$ + granularity_x)} nodes. The computation of the number \\code{a1} of subdomains with the higher number of nodes in line \\ref{alg:3.3} requires a division by \\code{granularity_x} as every subdomain with the higher number takes \\code{granularity_x} extra nodes. The rounding down in line \\ref{alg:3.3} is needed to obtain an integer value even if the total number of nodes is not a multiple of the granularity.\n\nIn the example in \\cref{fig:partitioning_algorithm} (d), the subdomains obtain either $\\alpha=6$ or $\\alpha +$ \\code{granularity_x}$=8$ nodes. In fact, for the last subdomain, only seven nodes remain, as the total number of 23 nodes is not divisible by the granularity of two.\nIn the algorithm, this is accounted for by the last branch of the \\code{if-else} construct in line \\ref{alg:3.10}, where only the remaining nodes are added to the last subdomain.\n\n\\subsection{Algorithm for Sampling Points from a Fine Fiber Mesh}\\label{sec:partitioning_alg2}\n\nNext, we can sample points from the nodes that were assigned to each subdomain. The sampling process is parametrized by the value of \\code{sampling_stride_x}, which specifies the step width of the nodes from the fine mesh to select for the coarse mesh.\n\\Cref{alg:n_sampled_points_in_subdomain} lists the function that determines the number of sampled points in a given subdomain. Similar to \\cref{alg:n_fibers_in_subdomain}, the input is a 1D subdomain coordinate. The output is the number of sampled points in this subdomain.\n\n\\begin{algorithm}\n  \\begin{algorithmic}[1]%\n    \\Procedure{n\\_sampled\\_points\\_in\\_subdomain\\_x}{subdomain\\_coordinate\\_x}\n    \\Require Index of a subdomain in $x$-direction\n    \\Ensure Number of points in the subdomain for the coarse 3D mesh\n      \\Statex\n      \\State n = n\\_fibers\\_in\\_subdomain\\_x(subdomain\\_coordinate\\_x)  \\hypertarget{alg:4.2}\n    \\State \\textbf{if} subdomain\\_coordinate\\_x == $n_x$ - 1 \\textbf{then}      \\hypertarget{alg:4.3}                      \n      \\State \\hspace{0.8em} n -= 1                                                     \\hypertarget{alg:4.4}\n    \\Statex\n    \\If{linear 3D elements}                                                     \\hypertarget{alg:4.5}\n      \\State result = $\\lfloor$ n / sampling\\_stride\\_x $\\rfloor$               \\hypertarget{alg:4.6}\n    \\Else                                                       \\hypertarget{alg:4.7}\n      \\State result = $\\lfloor$ n / (sampling\\_stride\\_x * 2) $\\rfloor$ * 2              \\hypertarget{alg:4.8}\n    \\EndIf\n    \\Statex\n    \\If{subdomain\\_coordinate\\_x == $n_x$ - 1}              \\hypertarget{alg:4.9}\n      \\State result += 1              \\hypertarget{alg:4.10}\n    \\EndIf              \\hypertarget{alg:4.11}\n    \\State \\textbf{return} result\n    \\EndProcedure\n  \\end{algorithmic}%\n  \\caption{Algorithm for sampling the fine mesh to obtain the coarser 3D mesh}%\n  \\label{alg:n_sampled_points_in_subdomain}%\n\\end{algorithm}%\n\nFirst, line \\hyperlink{alg:4.2}{2} of \\cref{alg:n_sampled_points_in_subdomain} calls \\cref{alg:n_fibers_in_subdomain} to obtain the number of fine grid points in the subdomain. The number of elements \\code{n} is equal to the number of points for all except the last 1D subdomain, which has one element less. This can be seen, e.g., in \\cref{fig:partitioning1}, where the first process with rank 0 (dark brown at the upper left) does not own the nodes on its subdomain boundary, whereas the last process with rank 11 (light brown at the lower right) owns all nodes on its subdomain boundary.\nThus, lines \\hyperlink{alg:4.3}{3} and \\hyperlink{alg:4.4}{4} of \\cref{alg:n_sampled_points_in_subdomain} decrement the value of \\code{n} to yield the correct number of elements. \n\nThe corresponding visualization in \\cref{fig:partitioning_algorithm} (e) assumes \\code{granularity_x=2} and shows $n=8$ elements for both the first and the second subdomain and $n=6$ elements for the last subdomain. \n\nThe resulting number of sampled points is obtained from the number of elements by a division by the sampling stride parameter and rounding down in lines \\hyperlink{alg:4.5}{5} to \\hyperlink{alg:4.8}{8}. For the last subdomain, line \\hyperlink{alg:4.10}{10} increments the result by one to account for the additional node on the boundary.\n\nDepending on whether the sampled mesh should contain linear or quadratic elements, the number of elements obtained from the algorithm has no restriction, or it has to be even. This is checked in the \\code{if} statement in line \\hyperlink{alg:4.5}{5}. In case of quadratic elements, an even number of elements is enforced by the formula in line \\hyperlink{alg:4.8}{8}.\n\nIn the considered example, we require quadratic elements and set \\code{sampling_stride_x=2}. The visualization in \\cref{fig:partitioning_algorithm} (f) shows the number of elements as long bars, which equals the \\code{result} variable before line \\hyperlink{alg:4.9}{9} in the algorithm. The resulting number of nodes is given in \\cref{fig:partitioning_algorithm} (f) by the circles below.\n\nThe actual selection of the nodes from the fine grid according to the stride parameter and using the determined subdomains and their numbers of contained nodes is a straight-forward task and not part of the algorithms listed here. For quadratic elements in the last subdomain, the potentially different mesh widths are resolved by selecting the second-last node in the middle between the third-last and the last node. In \\cref{fig:partitioning_algorithm} (f), this case occurs in the last subdomain. The orange node is sampled at the middle between the two neighboring dark red nodes. This behavior can also be observed in the corresponding partitioning in \\cref{fig:partitioning1} for the elements given by white lines in the lowest row. These elements have a larger vertical mesh width of three sampled points than the other elements, which have a vertical mesh width of two sampled points.\n\n\\subsection{User Options for the Algorithms}\\label{sec:partitioning_user_options}\n\nBy adjusting the sampling stride and granularity parameters, it is possible to tune the outcome of the partitioning algorithms.\nThe trade-off between the two requirements given in \\cref{sec:partitioning_requirements} by the numbers (ii) and (iii), i.e., that each subdomain obtains the same number of nodes, and that the least possible number of remainder elements is generated, can also be managed in the settings by enforcing either of the two requirements.\n\nMoreover, we set the granularity parameters to the same value as the sampling parameters by default and additionally ensure  for quadratic finite elements that the granularities are a multiple of two. This setting typically yields partitionings with equally sized elements. However, the number of nodes per subdomain is not always optimal.\n\nTo allow users to enforce a partitioning, where every rank gets the exact same number of nodes, except for the last subdomains in each coordinate direction, which potentially gets one layer of nodes less, we provide the option \\code{distribute_nodes_equally}, which can be set in the variables files. If this option is set to \\code{True}, the granularity values are internally fixed to one for \\say{linear} meshes and to two for \\say{quadratic} meshes, i.e., discretizations with quadratic finite element ansatz functions.\n\n\\subsection{Results}\\label{sec:partitioning_results}\n\nThe different results for the \\code{distribute_nodes_equally} option are demonstrated in \\cref{fig:partitioning3_4,fig:partitioning56}. \\Cref{fig:partitioning3_4} shows the automatic partitioning, where a simulation of fiber based electrophysiology with a grid of $9 \\times 9$ fibers is executed with eight processes and the stride values \\code{sampling_stride_x} and \\code{sampling_stride_y} are set to two.\nBy default, a linear mesh of $4\\times 4$ elements in $x$ and $y$-directions is created with $2\\times 2 \\times 2=8$ subdomains, as shown in \\cref{fig:partitioning4}. Only the first four subdomains can be seen in the visualization, the other four are located behind and hidden in the background.\n\nThe distribution of the fibers to the two 1D subdomains along both $x$ and $y$ directions yields four fibers for the first and five fibers for the second 1D subdomain. Thus, the total 3D subdomains of the first four processes contain $16,20,20$ and 25 fibers.\n\n\\Cref{fig:partitioning3} shows the same scenario, except that the option \\code{distribute_nodes_equally} has been set. The resulting partitioning is different and the fiber distribution is reversed, five and four fibers are assigned to the two 1D subdomains in both $x$ and $y$ directions. As a result, we get $25,20,20$ and $16$ fibers for the first four 3D subdomains. Note that this is the best balanced partitioning of a structured mesh that is possible for $9 \\times 9$ fibers.\nThe subdomain sizes are the same as in \\cref{fig:partitioning4}, except for a different order. However, for larger examples using more processes, the respective partitioning with the \\code{distribute_nodes_equally} option is always optimal, whereas the balance rapidly degrades without this option.\n\nWhile, in this example, there is no difference between \\cref{fig:partitioning4}  and \\cref{fig:partitioning3} in terms of load balancing, the 3D mesh quality of the generated partitioning is worse for \\cref{fig:partitioning3}. As can be seen in \\cref{fig:partitioning3}, the first and the third subdomain have one layer of elements more in both $x$ and $y$ direction, and these elements have half the mesh width of the normal elements. Additionally, the second and fourth subdomain also contain elements of different mesh widths.\n\nSimilar effects can also be studied in the scenario of \\cref{fig:partitioning56}, where the same mesh is partitioned to four processes in $z$-direction. The number of nodes in $z$-direction is \\num{1481} and the sampling stride is chosen as \\code{sampling_stride_z=50}. \\Cref{fig:partitioning6,fig:partitioning5} show the resulting partitioning without and with the \\code{distribute_nodes_equally} option. Again, the second scenario shows \\say{remainder} elements with smaller mesh widths at the boundaries of every subdomain. The distribution of nodes is $400,350,350$ and $381$ nodes per subdomain in \\cref{fig:partitioning6} and $371,370,370$ and $370$ nodes per subdomain for the scenario in \\cref{fig:partitioning5}, where the \\code{distribute_nodes_equally} option has been set. The first case has the better 3D mesh quality, whereas only the second case yields the perfect load balancing.\n\nIn summary, it is possible to tweak the created partitioning by adjusting the sampling stride and deciding between mesh quality and perfect load balancing. For electrophysiology simulations, which impose high computational load because of the subcellular model, the load balancing aspect is more important and the option \\code{distribute_nodes_equally}  should be set to \\code{True}. In simulations with elasticity models, the quality of the 3D meshes is more important and the partitioning for the corresponding meshes should be parametrized with the  \\code{distribute_nodes_equally} option set to \\code{False}.\n\n% partitioning with and without distribute_nodes_equally\n\\begin{figure}%\n  \\centering%\n  \\begin{subfigure}[t]{0.48\\textwidth}%\n    \\centering%\n    \\includegraphics[width=\\textwidth]{images/implementation/partitioning4.png}\n    \\caption{Resulting sampled mesh with the option \\code{distribute_nodes_equally=False}.}%\n    \\label{fig:partitioning4}%\n  \\end{subfigure}\n  \\quad\n  \\begin{subfigure}[t]{0.48\\textwidth}%\n    \\centering%\n    \\includegraphics[width=\\textwidth]{images/implementation/partitioning3.png}\n    \\caption{Resulting sampled mesh with the option \\code{distribute_nodes_equally=True}.}%\n    \\label{fig:partitioning3}%\n  \\end{subfigure}\n  \\caption{Mesh partitions generated by the sampling algorithm with different settings. A fine mesh with 49 fibers is sampled with a stride parameter of two and partitioned to eight processes.}%\n  \\label{fig:partitioning3_4}%\n\\end{figure}%\n\n% partitioning with and without distribute_nodes_equally\n\\begin{figure}%\n  \\centering%\n  \\begin{subfigure}[t]{0.48\\textwidth}%\n    \\centering%\n    \\includegraphics[width=\\textwidth]{images/implementation/partitioning6.png}\n    \\caption{Resulting sampled mesh with option \\code{distribute_nodes_equally=False}. The mesh width is constant, but the partitioning is not perfectly balanced.}%\n    \\label{fig:partitioning6}%\n  \\end{subfigure}\n  \\quad\n  \\begin{subfigure}[t]{0.48\\textwidth}%\n    \\centering%\n    \\includegraphics[width=\\textwidth]{images/implementation/partitioning5.png}\n    \\caption{Resulting sampled mesh with option \\code{distribute_nodes_equally=True}. The partitioning is perfectly balanced, but the mesh width is not constant.}%\n    \\label{fig:partitioning5}%\n  \\end{subfigure}\n  \\caption{Sampling a mesh along the fiber direction. The original mesh has 1481 nodes and is sampled with a stride value of 50.}%\n  \\label{fig:partitioning56}%\n\\end{figure}%\n\n\n\\begin{reproduce_no_break}\n  The partitioning in \\cref{fig:partitioning1} is obtained by the following simulation:\n  \\begin{lstlisting}[columns=fullflexible,breaklines=true,postbreak=\\mbox{\\textcolor{gray}{$\\hookrightarrow$}\\space}]\n    cd $\\$$OPENDIHU_HOME/examples/electrophysiology/fibers/fibers_contraction/no_precice/build_release\n    mpirun -n 12 ./biceps_contraction ../settings_biceps_contraction.py partitioning_demo.py --n_subdomains 4 3 1\n  \\end{lstlisting}\n  The partitionings in \\cref{fig:partitioning3_4,fig:partitioning56} are created by the following simulations. For \\cref{fig:partitioning4,fig:partitioning6}, edit the variables file \\code{partitioning_demo.py} and set \\code{distribute_nodes_equally = False}. For \\cref{fig:partitioning3,fig:partitioning5}, set \\code{distribute_}\\code{nodes_equally = True}.\n  \\begin{lstlisting}[columns=fullflexible,breaklines=true,postbreak=\\mbox{\\textcolor{gray}{$\\hookrightarrow$}\\space}]\n    cd $\\$$OPENDIHU_HOME/examples/electrophysiology/fibers/fibers_emg/build_release\n    mpirun -n 8 ./fast_fibers_emg ../settings_fibers_emg.py partitioning_demo.py\n    mpirun -n 4 ./fast_fibers_emg ../settings_fibers_emg.py partitioning_demo.py --n_subdomains 1 1 4\n  \\end{lstlisting}\n\\end{reproduce_no_break}\n\n\n\\section{Parallel Solver for the Fiber Based Electrophysiology Model}\\label{sec:parallel_partitioning_for_fiber_based}\n\nAfter discussing the general partitioning and sampling of 3D and 1D meshes in the last section, we now focus on the concrete application for the fiber based electrophysiology model.\nWe describe our basic solver and algorithmic improvements that yield lower runtimes.\n\nThe fiber based electrophysiology model consists of the action potential propagation model given by the 1D monodomain equation \\cref{eq:monodomain} and a 0D subcellular model as described in \\cref{sec:subcelullar_model}. The 0D and 1D problems are solved on the 1D fiber meshes. They are coupled to the 3D bidomain problem given in \\cref{eq:bidomain1}, which computes the EMG values. In summary, the components (b2),(c) and (d) of the diagram in \\cref{fig:multi-scale-model} are involved in this computation.\n\\Cref{fig:solver_fibers_3} shows a simulation result of this model, where the 1D fibers and the surface of the 3D mesh can be seen.\n\n% fibers mesh\n\\begin{figure}\n  \\centering%\n  \\includegraphics[width=\\textwidth]{images/results/application/fibers_3.png}\n  \\caption{Simulation result of the fiber based electrophysiology model with 1369 muscle fibers and a 2D surface mesh on top of the muscle. The fibers are colored according to the transmembrane potential $V_m$, the surface is colored according to the EMG values given by the extracellular potential $\\phi_e$.}%\n  \\label{fig:solver_fibers_3}%\n\\end{figure}\n\nIn the following, \\cref{sec:parallel_partitioning_for_fiber_based_solver} begins with a description of the solver structure and the parallelization. Subsequently, performance improvements considering the parallel execution of the solver are discussed. \\Cref{sec:improved_parallel_solver_for_fiber_based} presents a variant, where a faster solver is employed for the 1D part of the computation. \\Cref{sec:adaptive_computation_for_fiber_based} shows how the computational load can be reduced by only computing activated parts of the muscle.\n\n\\subsection{Parallel Solver Structure}\\label{sec:parallel_partitioning_for_fiber_based_solver}\nFor better visualization, we consider the 2D setting of a mesh and embedded 1D fibers partitioned to $2\\times 2$ processes as shown in \\cref{fig:mesh_structure} by different colors. However, all discussions are also valid for the real 3D setting shown in the last section and for arbitrary partitionings to $n_x \\times n_y \\times n_z$ processes.\n\n% program structure and partitioning\n\\begin{figure}%\n  \\centering%\n  \\begin{subfigure}[t]{0.30\\textwidth}%\n    \\centering%\n    \\includegraphics[width=\\textwidth]{images/implementation/mesh_structure.pdf}\n    \\caption{Visualization of the 3D mesh with embedded 1D fibers, partitioned to four ranks.}%\n    \\label{fig:mesh_structure}%\n  \\end{subfigure}\n  \\qquad\n  \\begin{subfigure}[t]{0.45\\textwidth}%\n    \\centering%\n    \\includegraphics[width=0.9\\textwidth]{images/implementation/program_structure.pdf}\n    \\caption{Structure of the OpenDiHu example program to solve the fiber based electrophysiology model. The colors match the scheme introduced in the overview chart in \\cref{fig:multi-scale-model}.}%\n    \\label{fig:program_structure}%\n  \\end{subfigure}\n  \\\\[8mm]\n  \\begin{subfigure}[t]{0.48\\textwidth}%\n    \\centering%\n    \\includegraphics[height=8cm]{images/implementation/fiber_partitioning1.pdf}\n    \\caption{Instances of the outer \\code{MultipleInstances} class in \\cref{fig:program_structure}.}%\n    \\label{fig:fiber_partitioning1}%\n  \\end{subfigure}\n  \\,\n  \\begin{subfigure}[t]{0.48\\textwidth}%\n    \\centering%\n    \\includegraphics[height=7.5cm]{images/implementation/fiber_partitioning2.pdf}\n    \\caption{Instances of the inner \\break\\code{MultipleInstances} classes in \\cref{fig:program_structure}.}%\n    \\label{fig:fiber_partitioning2}%\n  \\end{subfigure}\n  \\caption{Visualizations for the discussion of the program structure and partitioning used for fiber based electrophysiology simulations. The circles and lines represent the 1D meshes, their coloring indicates the MPI rank.}%Etwas mehr Information, z.B. Kreise sind Datenpunkte, Linien deuten Fasern an, Farben die MPI-Ranks?? Nee, kein Platz!\n  \\label{fig:partitioning_program}%\n\\end{figure}%\n\n\\Cref{fig:program_structure} shows the program structure of the example that solves the fiber based electrophysiology model. The outer class is a \\code{Coupling} that alternates between computing the monodomain equation \\cref{eq:monodomain} on the 1D fibers and computing the static bidomain equation \\cref{eq:bidomain1} on the 3D domain. The second part, the bidomain solver, is given in \\cref{fig:program_structure} by the class \\code{StaticBidomainSolver}, which includes two \\code{FiniteElementMethod} classes. The first class solves the potential flow to obtain the fiber direction for the anisotropic conduction tensor, the second class is used to discretize the spatial derivatives in the bidomain equation.\n\nThe first part of the coupling scheme in \\cref{fig:program_structure} consists of a \\code{Multiple}\\code{Instances} class, which encloses the Strang operator splitting. The splitting has two child solvers for the subcellular model and the diffusion or conduction term. The first child consists of another \\code{MultipleInstances} class with a \\code{Heun} scheme and the \\code{CellmlAdapter}\\nolinebreak.\nThe second child of the Strang splitting also consists of a \\code{MultipleInstances} class and a combination of an \\code{ImplicitEuler} scheme (alternatively a \\code{CrankNicolson} scheme can be used) and a \\code{FiniteElementMethod}.\n\nA \\code{MultipleInstances} class can be used to apply a solver to more than one problem of the same kind. The class allows to specify a number of instances of its nested solver. Each instance can be given a subset of processes that will take part in the computation of the instance. Each process then iterates over all instances, for which it is part of the subset. Thus, the nested solver of a \\code{MultipleInstances} class is called in series for all instances that share a process/MPI rank, and it is called in parallel and independently for 1D model instances that have disjoint subsets of ranks.\n\nFurthermore, the class provides a common output writer, which collectively writes the data of all instances. This allows, e.g., to create a single output file in every timestep containing the data of all fibers. Especially for large scenarios, this is more practical than having as many output files as fibers.\n\nThe settings that have to be specified in the Python file for a \\code{MultipleInstances} class comprise the number of instances and a list with the according number of entries, which further configure the instances. Each list entry can be \\code{None} if the rank does not take part in the computation of the corresponding instance. \nOtherwise, the list entry consists of (i) a specification of all ranks that should collectively compute the corresponding instance and (ii) the settings of the corresponding nested solver. \n\nThe own MPI rank of a process is known in the Python settings file. This allows to specify different settings for different ranks in the same file. By omitting the configuration of irrelevant instances and setting their list entry to \\code{None}, the amount of data is reduced and parsing of the script is sped up, especially for large problem sizes.\n\nThe settings and corresponding subdomains of the \\code{MultipleInstances} classes that are indicated by (c) and (d) in \\cref{fig:program_structure} are shown in \\cref{fig:fiber_partitioning1,fig:fiber_partitioning2}, respectively.\nAs can be seen in \\cref{fig:fiber_partitioning1}, the outer \\code{MultipleInstances} class separates the subdomains that are not connected by any fibers, such that they can be computed in parallel and independently of each other. In the example of \\cref{fig:mesh_structure}, the subdomains of ranks 0 and 2 can be computed independently of the subdomains of ranks 1 and 3. \nAs a consequence, all processes specify that their \\code{MultipleInstances} class has two instances. \nAt rank 0, the list of instance settings contains the settings of the nested Strang solver with all information of rank 0's subdomain (in the first item) and the value \\code{None}, as rank 0 has no information about fibers outside its subdomain (in the second item). Ranks 1, 2 and 3 specify their subdomain accordingly, as shown in \\cref{fig:fiber_partitioning1}.\n\nDuring computation, ranks 0 and 2 as well as ranks 1 and 3 enter the \\code{Strang} solver class collectively with a shared MPI communicator.\nThe inner \\code{MultipleInstances} classes employ the 0D subcellular and the 1D electric conduction solver on multiple fibers. As shown in \\cref{fig:fiber_partitioning2}, ranks 0 and 2 specify four instances with the settings of the four shared fibers. At the same time and concurrently, ranks 1 and 3 specify five instances with settings for their five shared fibers. \n\nNote that the multiplicity of the 0D instances on a fiber is not achieved by another \\code{MultipleInstances} class, but the model is solved for all points on the mesh together, using parallelism on the lower, instruction-based level.\n\nThese different splits of the geometry allow to compute the electrophysiology model on the fibers in parallel. The partitioning of the domain has to be the same for the 3D mesh and the embedded fibers to allow value mapping from the fibers to the 3D mesh without communication. The fibers are oriented along the $z$-direction in the 3D setting. This explains, why the ranks for a particular fiber, e.g., $\\{0,2\\}$ or $\\{1,3\\}$ are not direct successors of each other but increasing with a stride equal to the number of subdomains in $x$ and $y$ directions, $n_x \\cdot n_y$.\n\n\\subsection{Improved Parallel Solver Scheme using the Thomas Algorithm}\\label{sec:improved_parallel_solver_for_fiber_based}\n% FastMonodomainSolver\n\nThe monodomain model, which is solved on each fiber, consists of a reaction-diffusion equation, which is solved using the Strang operator splitting.\nThe diffusion part uses an implicit timestepping scheme, which leads to a linear system of equations to be solved in every timestep.\nAs the finite element method with linear ansatz functions is used for spatial discretization, this linear system has a tridiagonal system matrix.\n\nIn the solver tree structure in \\cref{fig:program_structure}, this solution step occurs in the solvers under the second inner \\code{MultipleInstances} class.  As can be seen in \\cref{fig:fiber_partitioning2}, the dofs of each fiber that are part of this linear system are partitioned to multiple processes. Hence, this linear system is solved using a parallel conjugate-gradient solver of PETSc.\n\nHowever, there is the possibility to improve the performance by exploiting the tridiagonal matrix structure. The \\emph{Thomas algorithm} is the specialization of Gaussian elimination for this matrix type and is known to efficiently solve such a system in linear time complexity. More specifically, it only requires a first downwards sweep through the matrix entries for forward substitution and a second upwards sweep for back substitution to compute the solution. It is stable for diagonally dominant matrices and this condition is met for the governing system matrix.\n\nAs the Thomas algorithm is not parallel, we have to gather the matrix data on a single process in order to employ the algorithm. In OpenDiHu, the \\code{FastMonodomainSolver} class is tailored to the parallel solution of fiber based electrophysiology using the Thomas algorithm. \n\\Cref{fig:fast_monodomain_scheme} outlines the steps performed by the \\code{FastMonodomainSolver} class.\n\nDuring initialization, the \\code{FastMonodomainSolver} class initializes its nested solver tree as normal and the parallel partitioning of the fibers is carried out as described in \\cref{sec:parallel_partitioning_for_fiber_based}. This is visualized on the left in \\cref{fig:fast_monodomain_scheme} for four fibers and two ranks. At the beginning of the first timestep, the communication to gather complete fiber data on single processes is carried out. The fiber data are communicated, such that every fiber is completely accessible at a single processes. The assignment of the fibers to processes occurs in a round-robin fashion, i.e., the first fiber is sent to rank 0, the second to the next rank, etc. As a result, every process has approximately the same number of complete fibers. \nThis is shown in the middle image of \\cref{fig:fast_monodomain_scheme}, where the red colored rank has all values of the first and third fiber and the orange colored rank has all values of the second and fourth fiber.\n\nThe processes then each compute the full monodomain model consisting of the Strang splitting with the subcellular model on the nodes of each fiber and the diffusion part using the Thomas algorithm. \nThis is done in a separate serial implementation for the now locally owned fibers, i.e., not using the nested solvers. The solution is obtained for as many subsequent timesteps as were specified in the settings. When the end time of the enclosing coupling scheme is reached, the fiber data are communicated back to the original partitioned fibers, as shown on the right in \\cref{fig:fast_monodomain_scheme}.\nThen, the coupling scheme continues with the data mapping from the partitioned fibers to the 3D domain and with the \\code{StaticBidomainSolver}. Afterwards, the \\code{FastMonodomainSolver} is called again and performs its computation anew starting with the communication step.\n\n% fibers mesh\n\\begin{figure}\n  \\centering%\n  \\includegraphics[width=0.6\\textwidth]{images/implementation/fast_monodomain_scheme.pdf}\n  \\caption{Algorithmic steps of the \\code{FastMonodomainSolver} to efficiently solve the 0D/1D problems. After a timestep of the 3D solver (left), the partitioned fibers, visualized by different colors for the MPI ranks, are communicated using MPI, such that every fiber is accessible on a single MPI rank (middle). The 0D/1D solvers compute multiple subsequent timesteps until the next 3D coupling step. Then, the original partitioning is restored by a second communication step and the 3D solver can continue with the next timestep (right).}%\n  \\label{fig:fast_monodomain_scheme}%\n\\end{figure}\n\n\nIn the C++ file, the \\code{FastMonodomainSolver} class is inserted as a wrapper to the outer \\code{MultipleInstances} class that is indicated by (c) in the solver structure in \\cref{fig:mesh_structure}. In the Python settings, the class does not add an additional nesting level such that the same settings file can be used for programs with and without the \\code{FastMonodomainSolver} class and yields the same simulation results.\n\nIn summary, the efficient serial computation of the monodomain model in the \\code{Fast}\\code{MonodomainSolver} is wrapped by communication steps of  the partitioned fiber data. The frequency of this communication step is determined by the timestep width of the coupling scheme. \nThe scenario solves the bidomain equation to simulate EMG signals. A typical sampling frequency of EMG capture devices is $f=\\SI{2}{\\kilo\\hertz}$, which corresponds to a coupling timestep width of $\\dt_\\text{3D}=\\SI{0.5}{\\milli\\second}$. The timestep widths $\\dt_\\text{0D}$ of the subcellular model and $\\dt_\\text{1D}$ of the diffusion term have to be set at maximum to $\\SI{1e-3}{\\milli\\second}$, yielding \\num{500} timesteps of computations on the fiber between subsequent communication steps. As a result, the communication cost is negligible.\n\n\\subsection{Adaptive Computation of the Subcellular Model}\\label{sec:adaptive_computation_for_fiber_based}\n% adaptive solution of cells and whole fibers\n\nDuring simulations of the fiber based electrophysiology model, often only a small fraction of the given fibers is activated.\nThe reason is, that, in physiological conditions, the smaller MUs are activated first and the larger MUs only get activated when the full force of the muscle is required. As the majority of the fibers belongs to larger MUs, a high portion of fibers is less frequently activated, also depending on the scenario.\nBut even if the scenario specifies a tetanic stimulation of all MUs, the larger MUs have lower stimulation frequencies, which again leads to less action potentials on large MUs than on smaller MUs in the same time span.\n\nA naive solver of the monodomain models always computes all 1D electric conduction problems on the fiber meshes and all 0D subcellular models on the nodes of the fiber meshes, regardless of their activation state. In the following, we present a method in OpenDiHu that exploits the infrequent activation events on most of the fibers while obtaining the same solution as the naive solver.\n\nWe assume that the subcellular models are initialized in their equilibrium state, where the temporal derivative of the state vector $\\bfy$ vanishes, $∂\\bfy/∂t = 0$. The first algorithmic improvement is to only consider those fibers in the solver that have yet been stimulated. This improves the performance especially for \\say{ramp like} motor recruitment, where more and larger MUs are activated over time. However, after all MUs have been activated at least once, all fibers are computed again and no more performance improvement is obtained.\n\nThe second improvement is to only compute instances of the subcellular model at those points, where it is not in equilibrium. To determine, whether an instance of the subcellular model is in equilibrium, we compare the solution before and after one integration step by the Heun method. Only if the relative change of any component of the state vector $\\bfy$ is larger than \\num{1e-5}, we consider the model to be not in equilibrium.\n\nThis check requires to compute the solution of the subcellular model, the avoidance of which is subject of the improved scheme. Therefore, we use the property of the 1D diffusion problem discretized by linear finite elements that the value at one spatial point can only influence its two neighbors in a single timestep. This allows us to avoid checking the equilibrium condition at points that are surrounded by other points in equilibrium. This means that the subcellular model does not have to be solved at most points in equilibrium, which drastically reduces the runtime. The 1D electric conduction problem, however, has to be solved for the whole fiber mesh if at least one point it is not in equilibrium.\n\nIn our method, each subcellular point can be in one of the three states \\say{active}, \\say{inactive} and \\say{neighbor is active}.\nIf the subcellular model is not in equilibrium, the point is in the state \\say{active} and has to be solved in the next timestep. If the subcellular model is in equilibrium and does not have to be solved because the solution vector stays constant, the point is in the state \\say{inactive}. The state \\say{neighbor is active} occurs for a previously inactive point, of which at least one neighbor became active and, thus, the check if the point is still in equilibrium has to be performed and the subcellular model has to be solved in the next timestep. After each solution step, the state of a point changes according to the transitions given in \\cref{fig:state_chart}.\n\nAn active point stays active, if the solution has changed in the last numerical integration step. It transitions to inactive, if the solution did not change. The same applies to points in the state \\say{neighbor is active}, which also change to \\say{active} or \\say{inactive} after one timestep. \nAn inactive state cannot be activated by a check on the point itself, as this state implies that no computation and no subsequent equilibrium check are carried out. The only transition for a point $A$ from an inactive state occurs, when a neighbor point $B$ reaches the state \\say{active} (or for external stimulation). Then, point $A$ changes to \\say{neighbor is active}.\nFor propagating action potentials along a fiber that is in the \\say{inactive} state, this leads to a propagating front of points in the \\say{neighbor is active} state.\n\nInitially, all states are set to \\say{active}. If no stimulation occurs and the subcellular model is in equilibrium, they momentarily change to \\say{inactive}. Upon external stimulation, the stimulated points are automatically set to \\say{active} and their neighbors are set to \\say{neighbor is active} such that the effect of the stimulation can be considered in subcellular model computations.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=0.7\\textwidth]{images/implementation/state_chart.pdf}%\n  \\caption{Transition diagram for the adaptive computation of the subcellular model. The diagram shows the transition between local states of points on the fibers. Points in inactive state do not perform the computation of the 0D subcellular model.}\n  \\label{fig:state_chart}\n\\end{figure}\n\n\\Cref{fig:compute_state3} shows a simulation, where the effect of both improvements is visible. The Hodgkin-Huxley subcellular model has been solved on a set of 49 fibers. At the displayed time of $t=\\SI{28}{\\milli\\second}$, two MUs have been activated. The value of the membrane potential $V_m$ is visualized by the radius of the fibers. The active or inactive state of the improved scheme is indicated by the colors.\n\n% compute state\n\\begin{figure}%\n  \\centering%\n  \\includegraphics[width=\\textwidth]{images/implementation/compute_state3.png}%\n  \\caption{Simulation scenario that demonstrates the adaptive computation method of fibers and subcellular points. A simulation of the monodomain equation on a set of 49 fibers with the subcellular model of Hodgkin and Huxley is shown. The transmembrane potential is visualized by the fiber radius. The states of the points used in the algorithm are given by the different colors.}%\n  \\label{fig:compute_state3}%\n\\end{figure}%\n\nIt can be seen that several fibers have gray color which indicates that they have not yet been stimulated and, thus, are not part of the computation. The other fibers have been stimulated either by the first or the second MU. Action potentials at two different distances from the center corresponding to the two MUs can be identified by the bulbous shapes. The red parts of the fibers contain the active points, where the subcellular model is not in equilibrium. At the yellow regions, the subcellular models are in equilibrium, and no computational work is performed there. The yellow regions are at the outer ends of the fibers that were not yet reached by the action potentials as well as around the center for fibers of the first MU. This demonstrates the repolarisation effect, after which the model reaches its equilibrium state again. \n\nThe purple colored points are in the state \\say{neighbor is active} and can be found between active and inactive points. As the algorithm iterates over all points of a fiber from left to right, these purple points only occur at the left boundaries of active regions. At their right boundaries, the initial \\say{neighbor is active} points transition to \\say{active} or \\say{inactive} directly after the computation step within this iteration.\n\nInstead of individual nodes on the fiber mesh, our implementation treats SIMD vectors of four or eight such adjacent nodes (depending on the hardware capabilities) as one point in the algorithm.  If one of these nodal instances is not in equilibrium, the whole SIMD vector is considered not in equilibrium and transitions to the \\say{active} state. This coarser granularity of the model instances allows to solve the subcellular problem in chunks according to the SIMD lane width using SIMD instructions.\n\n\\begin{reproduce_no_break}\n  The scenario of \\cref{fig:compute_state3} can be run as follows:\n  \\begin{lstlisting}[columns=fullflexible,breaklines=true,postbreak=\\mbox{\\textcolor{gray}{$\\hookrightarrow$}\\space}]\n    cd $\\$$OPENDIHU_HOME/examples/electrophysiology/fibers/fibers_emg/build_release\n    mpirun -n 4 ./fast_fibers_emg ../settings_fibers_emg.py compute_state_demo.py\n  \\end{lstlisting}\n  Instead of four processors, you can use as many as you have to speed up the computation.\n\\end{reproduce_no_break}\n\\section{Parallel Solver for the Multidomain Electrophysiology Model}\\label{sec:parallel_solver_multidomain}\n\nAfter the details on the parallel partitioning and solvers for the fiber based electrophysiology model have been discussed in \\cref{sec:parallel_partitioning_and_sampling_of_the,sec:parallel_partitioning_for_fiber_based}, we now consider the multidomain based model of electrophysiology, which includes electric conduction in the body fat layer. The class for the implicit solver within the operator splitting is the \\code{MultidomainWithFatSolver} class, which has been introduced in \\cref{sec:exemplary_usage_2}.\n\nThe multidomain based electrophysiology model contains the two multidomain equations, \\cref{eq:multidomain1,eq:multidomain2}, which are solved on the 3D domain. The model leads to a large linear system of equations that is solved in every timestep, described in \\cref{sec:discretization_body_domain}. \n\\Cref{fig:solver_multidomain_mesh} visualizes the body fat and muscle domains, on which the multidomain model is solved. The coloring of the muscle domain also gives an example for the occupancy factor $f_r^k$, which specifies to which extend every point in the domain is occupied by a particular MU.\n\n% multidomain mesh\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=0.7\\textwidth]{images/implementation/multidomain_mesh.png}%\n  \\caption{Visualization of the domains for the multidomain electrophysiology model: The body fat domain is shown in blue, the muscle domain is colored according to the values of one occupancy factor $f_r^k$, which specifies the territory of a MU.}\n  \\label{fig:solver_multidomain_mesh}\n\\end{figure}\n\n\\subsection{Construction and Partitioning of the Mesh}\\label{sec:construction_and_partitioning_of_the_mesh}\n\nThe mesh used in this solver is a composite mesh of type \\code{Mesh::CompositeOfDimension<D>}, as introduced in \\cref{sec:composite_meshes}. \\Cref{fig:structured_grid_n_nodes} shows the layout, in particular how the mesh of the body fat domain $\\Omega_B$ is connected with the mesh of the muscle domain $\\Omega_M$. The muscle and body fat meshes have $N_x^\\text{el} \\times N_y^\\text{el} \\times N_z^\\text{el}$ and $(N_x^\\text{el}+ N_y^\\text{el}) \\times N_\\text{fat}^\\text{el} \\times N_z^\\text{el}$ elements, respectively. Only the muscle mesh has been generated from medical imaging data by the pipline given in \\cref{sec:generation_of_meshes_for_multiscale}. The fat mesh is created on top of the muscle mesh geometry and has to use the same number of elements as the muscle mesh along the muscle surface for compatibility in the composite mesh. Only the physical thickness of the adipose tissue layer and the corresponding number $N_\\text{fat}^\\text{el}$ of elements in radial direction have to be specified.  (The mesh generation step is implemented in the script \\code{create_fat_layer.py}.) \n\n% fat layer mesh and partitioning\n\\begin{figure}\n  \\centering%\n  \\def\\svgwidth{0.6\\textwidth}\n  \\input{images/implementation/structured_grid_n_nodes.pdf_tex}%\n  \\caption{Layout of the composite 3D mesh for the multidomain model with fat layer. The orange elements belong to the mesh of the muscle domain $\\Omega_M$, the yellow elements are added on top to represent the body fat domain $\\Omega_B$.}%\n  \\label{fig:structured_grid_n_nodes}%\n\\end{figure}%\n\n\\Cref{fig:multidomain_matrix_mesh} shows such as composite mesh.\nThe muscle mesh is based on a dataset of $13\\times 13$ fibers with \\num{1481} nodes per fiber. This fine mesh is sampled as described in \\cref{sec:algorithm_for_partitioning_and_sampling} with stride values of $3,3$ and $20$ in $x,y$ and $z$ directions and \\code{distribute_nodes}\\code{_equally=True}. As a result, we get $N_x^\\text{el} \\times N_y^\\text{el} \\times N_z^\\text{el} = 5 \\times 4 \\times 75$ elements.\nThe fat mesh consists of a $\\SI{1}{\\centi\\meter}$ adipose tissue layer with $N_\\text{fat}^\\text{el}=4$ elements. The muscle and fat meshes have \\num{2280} and \\num{3800} dofs.\n\n% comment about parallelization\nThe partitioning of the composite mesh into $n_x \\times n_y \\times n_z$ subdomains cannot be chosen arbitrarily. The reason is that both the muscle and the body fat mesh have to be partitioned into the same number of subdomains. \nIf, e.g., a partitioning of $n_x=n_y=2$ is chosen, the cube in \\cref{fig:structured_grid_n_nodes} gets divided by one horizontal planar cut and one vertical planar cut. This divides the orange muscle mesh into four subdomains as expected. The yellow body fat mesh, however, is only partitioned to three of the four processes as there are no yellow elements below the horizontal cut and left of the vertical cut.\n\nThus, a valid partitioning can only be created if either $n_x$ or $n_y$ is set to one. Because there is no restriction on $n_z$, the total mesh can still be partitioned in two dimensions to a product of subdomains, either as $1 \\times n_y \\times n_z$ or as $n_x \\times 1 \\times n_z$.\nThe example mesh in \\cref{fig:multidomain_matrix_mesh} is partitioned to $2 \\times 1 \\times 2$ subdomains as shown by the different colors.\n\n% scenario_name: matrix,  n_subdomains: 2 1 2,  n_ranks: 4,  end_time: 0.002\n% dt_0D:           1e-03    multidomain solver:         1000 it. of gmres (10000 it. of gmres), lumped mass matrix: False, initial guess: previous solution\n% dt_multidomain:  1e-03    multidomain preconditioner: euclid (euclid), symmetric precond.: True\n% dt_splitting:    1e-03    theta: 1.0, solver tolerances, abs: 1e-15, rel: 1e-15\n% fiber_file:              ../../../input/left_biceps_brachii_13x13fibers.bin\n% fat_mesh_file:           ../../../input/left_biceps_brachii_13x13fibers.bin_fat.bin\n% cellml_file:             ../../../input/hodgkin_huxley_1952.c\n% firing_times_file:       ../../../input/MU_firing_times_always.txt\n% ********************************************************************************\n% 4 ranks, partitioning: x2 x y1 x z2\n%   sampling 3D mesh with stride 3 x 3 x 20 \n%   distribute_nodes_equally: True\n%     linear 3D mesh    nodes global: 6 x 5 x 76 = 2280, local: 3 x 5 x 38 = 570\n%     linear 3D mesh elements global: 5 x 4 x 75 = 1500, local: 3 x 4 x 38 = 456\n%     fat mesh, n points total:    3800 (10 x 5 x 76), (per process: 3 x 5 x 38 = 570)\n% \n\\begin{figure}\n  \\centering%\n  \\includegraphics[width=\\textwidth]{images/implementation/multidomain_matrix_mesh.png}%\n  \\caption{Composite mesh of the multidomain example, partitioned into four parallel subdomains.}%\n  \\label{fig:multidomain_matrix_mesh}%\n\\end{figure}%\n\n\\subsection{Structure of the System Matrix}\\label{sec:structure_multidomain_system_matrix}\n\n\\begin{figure}\n  \\centering%\n  \\includegraphics[width=0.3\\textwidth]{images/implementation/solver_structure_multidomain.pdf}%\n  \\caption{Solver structure of the multidomain solver, consisting of the Strang operator splitting, which contains the two nested solvers for the subcellular model (Heun scheme with CellML adapter) and the solver for the diffusion part of the multidomain problem. The colors match the scheme introduced in the overview chart in \\cref{fig:multi-scale-model}.}%\n  \\label{fig:multidomain_matrix_mesh}%\n\\end{figure}%\n\n\\Cref{fig:multidomain_matrix_mesh} shows the solver structure of a simulation of the multidomain model. The Strang operator splitting couples the Heun scheme of the 0D subcellular model with the multidomain solver, which is given by the \\code{MultidomainWithFatSolver} class. The \\code{MultidomainWithFatSolver} class uses nested \\code{FiniteElementMethod} classes to describe the anisotropic electric conduction in the muscle domain and the isotropic electric conduction in the fat domain.\nThe system matrix for the system of equations is given in \\cref{eq:discretized_multidomain_body2} in \\cref{sec:discretization_body_domain}. \nThe solver calculates the matrix block entries using the stiffness and mass matrices computed by the nested \\code{FiniteElementMethod} classes, i.e., the unknowns are organized in blocks in the system matrix for each MU.\n\n\\Cref{fig:original_matrix} shows the location of non-zeros in the resulting sparse matrix for three MUs. The matrix blocks are indicated by boxes and correspond to the symbolic formulation given in \\cref{eq:discretized_multidomain_body2}. The first three blocks correspond to the electric conduction problems of the 3 MUs given by the second multidomain equations in \\cref{eq:multidomain2}, the fourth row and column of blocks corresponds to the first multidomain equation \\cref{eq:multidomain1}, and the last block corresponds to the electric conduction problem in the fat domain. It can be seen that the dimension of the last block is different, corresponding to the number of dofs in the fat mesh.\n\nIn this visualization, it may seem that most of the blocks only have three non-zero entries per row, however, the actual number is higher (the \\say{lines} consist of multiple diagonals of non-zero entries) with a maximum of 27 entries, as the finite element ansatz function of a node in the 3D mesh has overlapping support with the ansatz functions of other nodes in a $3\\times 3 \\times 3$ grid.\nThe actual non-zero structure per block is close to the example shown in \\cref{fig:sparsity_pattern}.\n\nThe colors in \\cref{fig:original_matrix} correspond to the four processes, as defined in the partitioned mesh in \\cref{fig:multidomain_matrix_mesh}. \nThe entries in every block are all partitioned in the same way to the four processes, as given by the partitioning of the nested \\code{FiniteElementMethod} classes. The data structure for this layout is the \\code{MATNEST} type of PETSc. \n\nHowever, to be able to apply the multitude of PETSc solvers to this linear system, the matrix has to be transferred to the canonical parallel matrix layout of PETSc, which groups all dofs of the subdomains together. As this conversion is not available in PETSc, it is done in OpenDiHu by reordering the dofs and, as a consequence, the matrix entries. The same permutation is applied to the rows and to the columns of the matrix. The result of this operation is shown in \\cref{fig:reordered_matrix}. It can be seen that the portions for each process are now consecutive matrix rows. The non-zero structure within each process resembles the global matrix structure of the original matrix.\n\n% multidomain uses two fem objects, parallel partitioning\n% reorder matrix entries\n% for 16 processes scenario\n\n\\begin{figure}%\n  \\centering%\n  \\begin{subfigure}[t]{0.49\\textwidth}%\n    \\centering%\n    \\includegraphics[width=\\textwidth]{images/implementation/original_matrix.png}\n    \\caption{Original matrix layout.}%\n    \\label{fig:original_matrix}%\n  \\end{subfigure}\n  \\,\n  \\begin{subfigure}[t]{0.49\\textwidth}%\n    \\centering%\n    \\includegraphics[width=\\textwidth]{images/implementation/reordered_matrix.png}\n    \\caption{Reordered matrix layout.}%\n    \\label{fig:reordered_matrix}%\n  \\end{subfigure}\n  \\caption{Nonzero structure of the system matrix of the multidomain problem for three MUs. The five blocks in every row and column in (a) correspond to the dofs of the three MUs, the extracellular potential in the muscle domain, and the body potential.}%\n  \\label{fig:original_reordered_matrix}%\n\\end{figure}%\n\n\\subsection{Properties of a Diagonal Block-Matrix for the Preconditioner}\\label{sec:multidomain_diagonal_matrix}\nWith the reordered matrix, the linear system can now be solved using almost any preconditioner and linear solver of the PETSc framework. \nFor the construction of the preconditioner $\\mathcal{P}$ with left preconditioning matrix $P=\\mathcal{P}(A)$, we can either use the system matrix $A$ or provide a different matrix $A'$. The preconditioned linear system $P^{-1}A$ should have a smaller condition number than $A$ and, thus, solving the preconditioned system iteratively should be significantly faster than the original $A$ system.\n\nTo compute the condition number of the system matrix $A$, we determine its spectrum. \\Cref{fig:eigenvalues} shows the real parts of all eigenvalues of $A$. The imaginary parts vanish for almost all eigenvalues. The matrix is singular with one zero-eigenvalue. This property corresponds to the fact that the membrane potential in the problem is abitrary with respect to a constant offset. The singular problem can be solved using appropriate iterative solvers.\n\n% eigenvalues, spectrum, condition number is bad -> preconditioning\nThe real parts of the eigenvalues are all negative, which is in line with the fact that the model consists of a combination of several diffusion problems. The progression in \\cref{fig:eigenvalues} shows a large difference between the largest and the smallest eigenvalues. The condition number of $A$ can be computed by $\\textrm{cond}(A) = |\\lambda_\\text{max}| / |\\lambda_\\text{min}| = 161.2576 / 0.0116 \\approx \\num{1.4e5}$. Thus, the problem is ill-conditioned and can benefit from for preconditioning. The condition number is also dependent on the spatial mesh resolution and increases for larger problem sizes.\n\n% PETSc tutorial on preconditioning: https://www.mcs.anl.gov/petsc/meetings/2016/slides/tutorial1.pdf\n\\begin{figure}\n  \\centering%\n  \\includegraphics[width=0.7\\textwidth]{images/implementation/eigenvalues.png}%\n  \\caption{Real parts of the eigenvalues sorted by magnitude and corresponding to the example in \\cref{fig:multidomain_matrix_mesh}. The non-zero eigenvalue with largest and smallest absolute values are $\\lambda_\\text{max} = \\num{-161.2576}$ and $\\lambda_\\text{min} = \\num{-0.0116}$.}%\n  \\label{fig:eigenvalues}%\n\\end{figure}%\n\n\n% the ten smallest eigenvalues of the matrix:\n%     0.0000\n%    -0.0116\n%    -0.0183\n%    -0.0193\n%    -0.0204\n%    -0.0211\n%    -0.0222\n%    -0.0229\n%    -0.0235\n%    -0.0239\n% \n% the highest eigenvalues:\n%  -161.2576\n%  -157.7988\n%  -153.7242\n%  -151.2197\n%  -149.2269\n%  -144.5006\n%  -143.2441\n%  -142.4697\n%  -139.5421\n%  -139.2625\n\nWe experiment with a preconditioning matrix that only uses the diagonal blocks of the system matrix in reordered matrix layout, as shown in \\cref{fig:reordered_matrix}. \n\\Cref{fig:reordered_diagonal_matrix} shows the non-zero structure of the resulting matrix and compares it with the non-zero structure of the diagonal blocks of the matrix in original ordering in \\cref{fig:original_diagonal_matrix}. \nAs all diagonal blocks are symmetric matrices on both orderings, the resulting block-diagonal matrices $A'$ are also symmetric in contrast to the original matrix $A$.\n\nFurthermore, it can be seen that the matrices in \\cref{fig:original_reordered_diagonal_matrix} are different. The reordered layout depends on the parallel partitioning and contains only matrix entries within one subdomain, i.e., decouples the problems for different subdomains. In contrast, the diagonal blocks of the original system matrix are independent of the partitioning and contain dependencies between dof in different subdomains.\nWe use the reordered diagonal matrix for the preconditioner, as this approach is compatible with the parallel matrix storage in PETSc and allows to use the preconditioners and solvers of PETSc.\nThe decoupled entries on every rank potentially allows for a faster computation in the application of the preconditioner.\n\n\\begin{figure}%\n  \\centering%\n  \\begin{subfigure}[t]{0.49\\textwidth}%\n    \\centering%\n    \\includegraphics[width=\\textwidth]{images/implementation/original_diagonal_matrix.png}\n    \\caption{Original matrix layout.}%\n    \\label{fig:original_diagonal_matrix}%\n  \\end{subfigure}\n  \\,\n  \\begin{subfigure}[t]{0.49\\textwidth}%\n    \\centering%\n    \\includegraphics[width=\\textwidth]{images/implementation/reordered_diagonal_matrix.png}\n    \\caption{Reordered matrix layout.}%\n    \\label{fig:reordered_diagonal_matrix}%\n  \\end{subfigure}\n  \\caption{Nonzero structure of the symmetric preconditioner matrix of the multidomain problem. The symmetric matrices are obtained from the full matrices in \\cref{fig:original_reordered_matrix} by removing all blocks outside the main diagonal.}%\n  \\label{fig:original_reordered_diagonal_matrix}%\n\\end{figure}%\n\n\\subsection{Mesh and Matrices for Higher Degrees of Parallelism}\nTo show the effect of a higher degree of parallelism on the matrix structure, we also partition the same mesh as in \\cref{fig:multidomain_matrix_mesh} to 16 processes. The resulting partitioning of the mesh is given in \\cref{fig:16_multidomain_matrix_mesh}.\n\\Cref{fig:16_original_reordered_diagonal_matrix} shows the non-zero structure of the system matrix and the diagonal matrices for the preconditioner. \\Cref{fig:16_original_matrix} contains the original matrix structure that is permuted to the structure in \\cref{fig:16_reordered_matrix}. \nThe symmetric matrices for the preconditioner are shown in \\cref{fig:16_original_diagonal_matrix,fig:16_reordered_diagonal_matrix}. \nA comparison with \\cref{fig:original_reordered_diagonal_matrix} shows that the width of the non-zero band decreases for higher parallelizations.\n\n\n\\begin{figure}\n  \\centering%\n  \\includegraphics[width=\\textwidth]{images/implementation/16_multidomain_matrix_mesh.png}%\n  \\caption{Partitioning of the mesh in the multidomain example into 16 subdomains.}%\n  \\label{fig:16_multidomain_matrix_mesh}%\n\\end{figure}%\n\n\\begin{figure}%\n  \\centering%\n  \\begin{subfigure}[t]{0.49\\textwidth}%\n    \\centering%\n    \\includegraphics[width=\\textwidth]{images/implementation/16_original_matrix.png}\n    \\caption{Full matrix in original matrix layout.}%\n    \\label{fig:16_original_matrix}%\n  \\end{subfigure}\n  \\,\n  \\begin{subfigure}[t]{0.49\\textwidth}%\n    \\centering%\n    \\includegraphics[width=\\textwidth]{images/implementation/16_reordered_matrix.png}\n    \\caption{Full matrix in reordered matrix layout.}%\n    \\label{fig:16_reordered_matrix}%\n  \\end{subfigure}\n  \\\\\n  \\begin{subfigure}[t]{0.49\\textwidth}%\n    \\centering%\n    \\includegraphics[width=\\textwidth]{images/implementation/16_original_diagonal_matrix.png}\n    \\caption{Block-diagonal submatrix in original matrix layout.}%\n    \\label{fig:16_original_diagonal_matrix}%\n  \\end{subfigure}\n  \\,\n  \\begin{subfigure}[t]{0.49\\textwidth}%\n    \\centering%\n    \\includegraphics[width=\\textwidth]{images/implementation/16_reordered_diagonal_matrix.png}\n    \\caption{Block-diagonal submatrix in reordered matrix layout.}%\n    \\label{fig:16_reordered_diagonal_matrix}%\n  \\end{subfigure}\n  \\caption{Nonzero structure of the full system matrices in (a) and (b) and the symmetric preconditioner matrices in (c) and (d) of the multidomain problem, partitioned into 16 subdomains. The comparison with \\cref{fig:original_reordered_matrix} reveals smaller relative diagonal band widths for the larger number of subdomains in this example.}%\n  \\label{fig:16_original_reordered_diagonal_matrix}%\n\\end{figure}%\n\n\\begin{reproduce_no_break}\n  The following commands run one timestep of the multidomain simulation with fat layer:\n  \\begin{lstlisting}[columns=fullflexible,breaklines=true,postbreak=\\mbox{\\textcolor{gray}{$\\hookrightarrow$}\\space}]\n    cd $\\$$OPENDIHU_HOME/examples/electrophysiology/multidomain/multidomain_with_fat/build_release\n    mpirun -n 4 ./multidomain_with_fat ../settings_multidomain_with_fat.py matrix.py\n    mpirun -n 16 ./multidomain_with_fat ../settings_multidomain_with_fat.py matrix.py\n  \\end{lstlisting}\n  To inspect the system matrix, define a directory where the matrix should be stored. This can be done by setting the parameter \\code{config[`Solvers`][`multidomainLinear}\\code{Solver`][`dumpFilename`]}, e.g., to \\code{`out/matrix/m`}. Then, the directory \\code{out/matrix} will contain MATLAB files with the system matrix. To create the plots, open MATLAB, load the system matrix from the  respective file and open the script \\code{display_matrix}\\code{_entries.m}. Adjust the name of the matrix variable in the first code block, the run the desired steps of the Live Script to produce various plots.\\\\\n  The saved file contains the system matrix already in the reordered layout shown in \\cref{fig:reordered_matrix,fig:16_reordered_matrix}. The MATLAB script reverses the permutation that was applied in OpenDiHu to generate the plots of \\cref{fig:original_matrix,fig:16_original_matrix}.\n\\end{reproduce_no_break}\n\n% scenario_name: matrix,  n_subdomains: 4 1 4,  n_ranks: 16,  end_time: 0.002\n% dt_0D:           1e-03    multidomain solver:         1000 it. of gmres (10000 it. of gmres), lumped mass matrix: False, initial guess: previous solution\n% dt_multidomain:  1e-03    multidomain preconditioner: euclid (euclid), symmetric precond.: True\n% dt_splitting:    1e-03    theta: 1.0, solver tolerances, abs: 1e-15, rel: 1e-15\n% fiber_file:              ../../../input/left_biceps_brachii_13x13fibers.bin\n% fat_mesh_file:           ../../../input/left_biceps_brachii_13x13fibers.bin_fat.bin\n% cellml_file:             ../../../input/hodgkin_huxley_1952.c\n% firing_times_file:       ../../../input/MU_firing_times_always.txt\n% ********************************************************************************\n% 16 ranks, partitioning: x4 x y1 x z4\n%   sampling 3D mesh with stride 3 x 3 x 20 \n%   distribute_nodes_equally: True\n%     linear 3D mesh    nodes global: 6 x 5 x 77 = 2310, local: 2 x 5 x 19 = 190\n%     linear 3D mesh elements global: 5 x 4 x 76 = 1520, local: 2 x 4 x 19 = 152\n%     fat mesh, n points total:    3850 (10 x 5 x 77), (per process: 2 x 5 x 19 = 190)\n% \n\n% details multidomain solver, reordering of matrix entries\n\n% solver structure of contraction\n%\\begin{figure}\n%  \\centering%\n%  \\includegraphics[width=0.5\\textwidth]{images/implementation/solver_structure_contraction.pdf}%\n%  \\caption{solver structure}%\n%  \\label{fig:prestrech1b}%\n%\\end{figure}%\n\n% ----\n\n\\section{Computation of CellML Models}\\label{sec:computation_cellml_models}\n\nIn the following, we consider the computation of models that are given in CellML description, such as the subcellular model in the multi-scale muscle model.\n\nThe subcellular model is a system of DAEs that is solved at every node of the meshes in the discretized muscle.\nFor the fiber based electrophysiology description, instances of the 0D subcellular model are computed on every node of every 1D fiber mesh. The 0D instances are coupled by the monodomain equation on every fiber. For the multidomain description, 0D model instances are solved at every node of the 3D muscle mesh for every compartment.\n\nThe subcellular model is provided as a CellML file and can be configured in the Python settings as described in \\cref{sec:usage_cellml}.\nThe class in OpenDiHu that computes CellML model instances for all nodes of a given mesh is the \\code{CellMLAdapter}. It computes the expression $G$ of the right-hand side of the ODE system, to obtain the vector of rates $\\partial \\bfy / \\partial t = G(\\bfy)$ and the expression $H$ for the algebraics $\\bfh=H(\\bfy)$. The new state vector $\\bfy$ is computed from the previous vector by a timestepping scheme, which uses the computed rates $\\partial \\bfy / \\partial t$ as right-hand side. In the solver tree, the timestepping solver class has to be the parent node of the \\code{CellMLAdapter}.\n\nCellML models can be obtained as C source files, which can be compiled to shared libraries, loaded and accessed by the solver program. This approach is used in both OpenCMISS and OpenDiHu.\nThe operation of computing multiple instances of a CellML model at once can be done more efficiently than in the naive way of repeatedly executing the model function, as done in OpenCMISS. To exploit the structure of computing multiple model instances together, dedicated C code has to be generated from the CellML model at runtime for a given number of model instances.\nIn the following, we describe our code generation functionality for this purpose.\n\n\\subsection{Data Flow for the Computation of CellML Models}\n\n\\begin{figure}%\n  \\centering%\n  \\includegraphics[width=0.7\\textwidth]{images/implementation/cellml_scheme.pdf}%\n  \\caption{Processing of the given CellML model prior to solution. The CellML description is converted to C code using OpenCOR. The parser loads the C source code file and determines the contained initial values. Additionally, it parses the compute instructions into an internal syntax tree. The code generator produces optimized C code that can solve as many instances of the model as needed on every process according to the global partitioning of the domain. The generated C code is compiled, linked to a shared library and accessed from the solver code.}\n  \\label{fig:cellml_scheme}%\n\\end{figure}%\n\n\\Cref{fig:cellml_scheme} shows the information flow for the CellML subsystem in OpenDiHu. On the left, a subcellular model is specified in CellML format in a file \\code{model.cellml}. OpenDiHu uses the command line interface of OpenCOR to generate corresponding C code in the file \\code{model.c}. The C code computes the functions $G(\\bfy)$ and $H(\\bfy)$ for the right-hand side and algebraics vector, respectively. A parser traverses the generated C source file and stores all instructions in an internal syntax tree data structure. The parser also determines the initial values for the state vector $\\bfy$ from the code that initializes the variables.\nNext, certain constants and algebraics in the compute instructions are replaced by parameter variables, as configured in the settings.\n\nThen, a code generator outputs new C code that is optimized for a given number of CellML instances according to the number of nodes in the processes' subdomain within the global domain decomposition. \nThis step is executed in parallel by different processes, but only once for every required number of model instances.\n\nFor example, if two fibers with 100 elements each are computed by $2 \\times 2$ processes, the 101 nodes on each fiber are equally distributed to two different processes. As a result, each MPI rank has to compute either 51 or 50 CellML instances. Thus, the code generators on two of the ranks produce source code files for 51 and 50 model instances, named \\code{model_vc_51.c} and \\code{model_vc_50.c} in \\cref{fig:cellml_scheme}, respectively. After generation, the source files are compiled and linked to a shared library, resulting in the shared object files \\code{model_vc_51.so} and \\code{model_vc_50.so} in \\cref{fig:cellml_scheme}.\n\nThe generation, compilation and linking steps are performed only by one process per source file.\nIf a source file or shared library with the required name already exists from a previous run, the respective code generation and compilation steps are omitted.\nIn the example, only two processes generate and compile the code. All four processes synchronize after all shared libraries have been generated, before proceeding to execute the computations.\n\nThe generated shared libraries contain machine-code to compute $G(\\bfy)$ and $H(\\bfy)$. They are loaded into the simulation program and executed by the \\code{CellmlAdapter} class with the corresponding values, as indicated in \\cref{fig:cellml_scheme}. Furthermore, the \\code{Cellml}\\code{Adapter} uses the previously inferred vector of initial values to initialize the state vector before the first timestep. Also, the \\code{FastMonodomainSolver} class presented in \\cref{sec:improved_parallel_solver_for_fiber_based}, which efficiently solves the monodomain equation, makes use of the code generator and the shared libraries to evaluate the operators G and H of the subcellular model.\n\n\\subsection{Optimizations in the Generated Code}\\label{sec:optimizations_in_the_generated}\n\nThe code generator can be configured to employ various types of optimizations in the generated code. These optimizations can be selected in the settings by the parameter \\code{`optimizationType`}.\n\nThe naive way to solve multiple CellML model instances leads to storing the state vectors\nin an Array-of-Struct (AoS) memory layout. The \\say{struct} containing all components of the state vector for a single CellML model is stored at consecutive locations in memory and multiple structs for all computed instances are lined up next to each other. \\Cref{fig:memory_layouts} shows the AoS layout in the top row for four model instances given by different colors. Each instance contains the three state variables $0,1$ and $2$. \n\n\\begin{figure}%\n  \\centering%\n  \\begin{subfigure}[t]{0.6\\textwidth}%\n    \\centering%\n    \\includegraphics[width=\\textwidth]{images/implementation/memory_layouts.pdf}\n    \\caption{Data in different memory layouts.}%\n    \\label{fig:memory_layouts}%\n  \\end{subfigure}\\\\[4mm]\n  \\begin{subfigure}[t]{0.7\\textwidth}%\n    \\centering%\n    \\includegraphics[width=\\textwidth]{images/implementation/memory_layouts1.pdf}%\n    \\caption{Schemes how to construct the memory layouts. On the left, the entries are organized in a 2D field according to the state index and instance index. On the right, the traversal schemes for the different layouts are shown.}%\n    \\label{fig:memory_layouts1}%\n  \\end{subfigure}\n  \\caption{Different memory layouts for the CellML model: Array-of-Struct (AoS), Struct-of-Array (SoA), Array-of-Vectorized-Struct (AoVS), and Struct-of-Vectorized-Array (SoVA). The entries for four instances of the CellML model are shown by different colors, where each contains the three state variables 0,1 and 2.}%\n  \\label{fig:memory_layouts_both}%\n\\end{figure}%\n\nThe transposed memory layout is Struct-of-Array (SoA), where the same state components for all model instances are close in memory. In the example in the second row of \\cref{fig:memory_layouts}, always four states of the same kind are stored contiguously. \n\\Cref{fig:memory_layouts1} shows the construction schemes for the memory layouts. Comparing the scheme for SoA with AoS, it can be seen that the traversal in the 2D field of values is now vertical instead horizontal.\n\nSuch a vertical layout is a prerequisite for employing single-instruction-multiple-data (SIMD) parallelism. SIMD instructions perform the same calculations on multiple components of SIMD vectors simultaneously. In the visualization of SoA in \\cref{fig:memory_layouts}, always four operands could be loaded simultaneously from memory to the vector registers in the CPU. Modern processors support the AVX2 instruction set with a SIMD lane width of $\\mathcal{W}_T=4$ double values or the AVX-512 instruction set with $\\mathcal{W}_T=8$ double values.\n\n\\begin{figure}\n\\centering\n  \\begin{subfigure}[t]{\\textwidth}%\n  \\centering%\n\\begin{framed}\n\\begin{lstlisting}[basicstyle=\\footnotesize\\ttfamily,commentstyle=\\color{gray},numbers=left]\n  ALGEBRAIC[1] = ( - 0.100000*(STATES[0]+50.0000))/(exp(- (STATES[0]+50.0000)/10.0\n  RATES[1] =  ALGEBRAIC[1]*(1.00000 - STATES[1]) -  ALGEBRAIC[5]*STATES[1];\n  ...\n\\end{lstlisting}\n\\end{framed}\n    \\caption{Original C code for one CellML model instance generated by OpenCOR.}%\n    \\label{fig:cellml_codes_original}%\n  \\end{subfigure}\\\\[4mm]\n  \\begin{subfigure}[t]{\\textwidth}%\n  \\centering%\n\\begin{framed}\n\\begin{lstlisting}[basicstyle=\\footnotesize\\ttfamily,commentstyle=\\color{gray},numbers=left]\n  #pragma omp for simd\n  for (int i = 0; i < 1481; i++)\n    algebraics[1481+i] = ( - 0.100000*(states[0+i]+50.0000))/(exp(- (states[0+i]+5\n    \n  #pragma omp for simd\n  for (int i = 0; i < 1481; i++)\n    rates[1481+i] =  algebraics[1481+i]*(1.00000 - states[1481+i]) -  algebraics[7\n  ...\n\\end{lstlisting}\n\\end{framed}\n    \\caption{Generated code for optimization type \\code{`simd`}.}%\n    \\label{fig:cellml_codes_simd}%\n  \\end{subfigure}\\\\[4mm]\n  \\begin{subfigure}[t]{\\textwidth}%\n  \\centering%\n\\begin{framed}\n\\begin{lstlisting}[basicstyle=\\footnotesize\\ttfamily,commentstyle=\\color{gray},numbers=left]\n  // fill input vectors of states and parameters\n  for (int stateNo = 0; stateNo < nStates; stateNo++)\n    for (int i = 0; i < nVcVectors; i++)  // Vc vector no\n      for (int k = 0; k < $\\mathcal{W}_T$; k++)  // entry no in Vc vector \n        statesVc[i*nStates + stateNo][k] = states[stateNo*nInstances + i*$\\mathcal{W}_T$+k]; $\\label{alg:st_aovs}$\n     // statesVc[stateNo*nVcVectors + i][k] = states[stateNo*nInstances + i*$\\textcolor{gray}{\\mathcal{W}_T}$+k]  $\\label{alg:st_sova}$\n\n  for (int i = 0; i < nVcVectors; i++)\n  {\n    algebraicsVc[i*nAlgebraics + 1] = ( - 0.100000*(statesVc[i*nStates + 0]+50.000 $\\label{alg:b_aovs}$\n  //algebraicsVc[371+i] = ( - 0.100000*(statesVc[0+i]+50.0000))/(exponential(- (st $\\label{alg:b_sova}$\n    ...\n  }\n\\end{lstlisting}\n\\end{framed}\n    \\caption{Generated code for optimization type \\code{`vc`}.}%\n    \\label{fig:cellml_codes_vc}%\n  \\end{subfigure}\\\\[4mm]\n  \\begin{subfigure}[t]{\\textwidth}%\n  \\centering%\n\\begin{framed}\n\\begin{lstlisting}[basicstyle=\\footnotesize\\ttfamily,commentstyle=\\color{gray},numbers=left]\n  #pragma omp parallel for\n  for (int i = 0; i < 1481; i++)\n  {\n    algebraics[1481+i] = ( - 0.100000*(states[0+i]+50.0000))/(exp(- (states[0+i]+5\n    rates[1481+i] =  algebraics[1481+i]*(1.00000 - states[1481+i]) -  algebraics[7\n    ...\n  }\n\\end{lstlisting}\n\\end{framed}\n    \\caption{Generated code for optimization type \\code{`openmp`}.}%\n    \\label{fig:cellml_codes_openmp}%\n  \\end{subfigure}\n\\caption{Output of the CellML code generator in OpenDiHu for 1481 model instances and different optimization types.  The model is the subcellular model of Hodgkin and Huxley, and the code shows only two formulas of this model. Furthermore, the lines are truncated.}%\n\\label{fig:cellml_codes}%\n\\end{figure}\n\n\\Cref{fig:cellml_codes} demonstrates the code generation and presents different approaches to efficiently evaluate the operators of a CellML model for multiple instances. \\Cref{fig:cellml_codes_original} shows the original code for a single model instance, which can be obtained from the CellML website or exported from a CellML model using OpenCOR. The listing shows the computation of the algebraic variable with index one and the rate with index one. The formulas typically use other states, algebraics and constant variables and consist of basic arithmetic such as additions, multiplications, potentiations to integer exponents and exponential functions. Some models such as the subcellular model of Shorten et al. \\cite{Shorten2007} also involve piecewise definitions that include \\say{inline if} branching operations.\n\nCalling the code in \\cref{fig:cellml_codes_original} for multiple model instances is associated with the AoS memory layout.\nAn improvement is the generated code with optimization type \\code{`simd`} in \\cref{fig:cellml_codes_simd}, which assumes the data to be organized in the SoA memory layout. The code is generated specifically to solved 1481 instances of the model. The array indexing for the \\code{algebraics} and \\code{rates} variables sums the constant offset according to the memory layout and the number of the model instance. For example, for the second algebraic (with former index 1), the offset is 1481 because so many memory locations are filled with values of the first algebraic (with former index 0).\n\nFurthermore, every formula is enclosed in a loop over all 1481 instances of the model. The loops have OpenMP pragmas that instruct the compiler to use SIMD instructions for the loop body, if possible. Because of the consecutive storage, $\\mathcal{W}_T$ loop iterations can be combined into a single computation using vector instructions. For the remainder iterations at the end of the loop, the compiler automatically adds different instructions with corresponding smaller SIMD vector lengths.\n\nThe approach of using OpenMP pragmas has the advantage that it is independent of the actual hardware capabilities and does not fix the SIMD vector size $\\mathcal{W}_T$. If vectorization is disabled at compile-time, sequential CPU code is generated and the same valid solution is computed. A disadvantage is that the performance of the generated code depends on the vectorization ability of the compiler and its detection that the variables have the proper memory layout. For some constructs such as exponential functions or branching instructions, no vectorization is employed and the particular loop falls back to serial code. Such behavior is observed when inspecting the vectorization reports, which are emitted by the compiler.\n\nThus, we implement another optimization type \\code{`vc`} in the code generator that guarantees usage of vector instructions for all formulas. We use the C++ library \\emph{Vc}, which provides a wrapper to hardware-specific vector instructions and abstracts the SIMD lane width \\cite{vc2012,Kretz2015}. Using the data types of this library also allows writing hardware independent code and to achieve performance portability, like with the \\code{`simd`} optimization type. \nAs \\emph{Vc} only supports vectorization up to the AVX2 instruction set, we also use the \\code{std::experimental::simd} specification, which is currently considered by the International Organization for Standardization (ISO) and the International Electrotechnical Commission (IEC) for inclusion in the C++ standard library \\cite{hoberock2016working}. Switching between these two libraries is transparent in the code and depends on whether the compiler supports C++17.\n\nSimilar to the \\code{`simd`} optimization type, the \\code{`vc`} optimization type also uses a memory layout where consecutive memory entries correspond to different instances of the model, and the traversal direction in \\cref{fig:memory_layouts1} is vertical for at least $\\mathcal{W}_T$ entries. \\Cref{fig:memory_layouts_both} shows two such memory layouts for a SIMD vector length of $\\mathcal{W}_T=2$: Array-of-Vectorized-Struct (AoVS) and Struct-of-Vectorized-Array (SoVA). Both are implemented in the code generator. \n\nThe SoVA memory layout is very similar to SoA, the only difference is, that, in SoVA, entries are always accessed in multiples of the SIMD vector length $\\mathcal{W}_T$. The advantage of SoVA is that the array indices are given by the sum of a constant offset with the loop index, whereas, with the AoVS layout, a multiplication is required for every access.\n\nAoVS resembles more the AoS layout. Its advantage over SoVA is that the complete state vector $\\bfy$ for any model instance is located more locally in memory. As the total computation iterates over model instances, the accessed memory is more coherent than for the same iteration scheme with the AoVS layout. This possibly leads to more cache hits, however, for set-associative caches, the effect is reduced. Due to the complexity of today's cache architectures, only measurements can decide which of the two memory layouts leads to a faster execution. Our measurements show that the SoVA layout leads to \\SI{2}{\\percent} shorter runtimes than the AoVS memory layout and, thus, is the preferred choice.\n\n% hodgkin huxley\n%   vc-sova 216.6 s\n%   vc-aovs 217.3 s\n\n% shorten\n%   vc-sova 6873.6 s\n%   vc-aovs 7000.3 s\n\n% other run:\n%                     subdomains        user  total comp.         0D         1D  bidomain  duration_init     write       mem    n\n% scenarioName nRanks                                                                                                            \n% vc           18      [3, 2, 3]  186.429444   183.516278  45.524128  95.482744  2.693811       3.053507  1.707781  0.224 GB   18\n% vc-aovs      18      [3, 2, 3]  178.800859   177.067879  44.365866  92.375215  2.323516       1.917626  1.673526  0.223 GB  198\n% vc-sova      18      [3, 2, 3]  180.776722   179.158511  45.464952  93.226485  2.329576       1.810070  1.685208  0.223 GB  180\n% ------------------------------------------------------------------------------------------------------------------------\n% \n\n\\Cref{fig:cellml_codes_vc} shows the resulting code using the AoVS memory layout. The commented lines \\ref{alg:st_sova} and \\ref{alg:b_sova} show the corresponding code for the SoVA memory layout.\nAt the beginning of the generated program code, the given data in the \\code{states} variable are copied to the \\code{statesVc} variable in the new memory layout. Nested loops over all states, over the SIMD vectors and over the scalar values within the SIMD vector are used for this operation. For comparison, lines \\ref{alg:st_aovs} and \\ref{alg:st_sova} show the corresponding indexing of the \\code{statesVc} variables for the AoVS and SoVA memory layouts, respectively.\n\nFor the evaluation of the model operators, we iterate over the number \\code{nVcVectors} of SIMD vectors instead of the number of model instances as for \\code{`simd`}. In the example with 1481 instances, we have \\code{nVcVectors=$\\lceil 1481/\\mathcal{W}_T \\rceil$=371} SIMD vectors for $\\mathcal{W}_T=4$. \nAccordingly, the offsets for indexing the variables in the SoVA layout are smaller, e.g., in line \\ref{alg:b_sova}, the offset for indexing the \\code{algebraicsVc} variables is 371 instead of 1481 for the non-vectorized variable in the previously considered \\code{`simd`} code. \nComparing the statements for AoVS and SoVA in lines \\ref{alg:b_aovs} and \\ref{alg:b_sova}, it can be seen that the AoVS memory layout involves an additional multiplication during the indexing of the array.\n\nIn case of branching instructions in the CellML formulas, the Vc library provides an implementation of the \\say{inline if} statement for SIMD vectors, which checks the condition, potentially executes both branches and merges the components from the active branches into the resulting SIMD vector.\n\nProfiling the execution of the \\code{`vc`} code for different subcellular models shows that about half of the runtime is spent in evaluating the exponential function. Therefore, we use the following approximation:\n\\begin{align}\\label{eq:apx-e-function}\n  \\textrm{exp}(x) \\approx \\textrm{exp}^\\ast(x) = \\left( 1 + \\dfrac{x}{n}\\right)^n.\n\\end{align}\nThe series converges to the exact value for $n\\to \\infty$. We choose $n=1024$ and are able to compute the approximate value by only one addition and 11 multiplications using the following formula:\n\\begin{align*}\n    \\textrm{exp}^\\ast(x) = \\left( 1 + \\dfrac{x}{1024}\\right)^{2^{10}} = \\left(\\cdots{{\\left({\\left(\\left( 1 + \\dfrac{x}{1024}\\right)^2\\right)}^2\\right)}^{\\scriptsize\\iddots}}\\right)^2.\n\\end{align*}\n%\nIn the subcellular models of Hodgkin and Huxley \\cite{Hodgkin1952} and Shorten et al. \\cite{Shorten2007}, the values for $x$ are bounded by $|x| < x_\\text{max} = 12$, and we get a relative error of the approximation of $|(\\textrm{exp}^\\ast - \\textrm{exp})(x_\\text{max}) / \\textrm{exp}(x_\\text{max})| < 0.07.$\nThis approximation can be enabled or disabled in the code generation.\n\nAnother optimization is implemented for exponentiation $a^b$. In the considered CellML models, only integer exponents $b\\in \\mathbb{Z}$ occur. We add a recursive implementation of the power function that requires a logarithmic number of multiplications. \n\nThe code generator with the \\code{`vc`} optimization type is also used by the \\code{FastMonodomain}\\code{Solver} class described in \\cref{sec:improved_parallel_solver_for_fiber_based}. The generated codes for the \\code{FastMonodomainSolver} class additionally contain the Heun scheme to solve the model, integrate code for the stimulation of muscle fibers and  export certain algebraic values that were declared as parameters in the settings.\n\nAnother possiblity to improve the performance besides instruction-level parallelism is thread-level parallelism. The \\code{`openmp`} optimization type generates code containing OpenMP pragmas that distribute the computations to multiple OpenMP threads with shared memory. \\Cref{fig:cellml_codes_openmp} shows the generated code for this optimization type. A loop iterates over all model instances and the variables are stored in SoA memory layout. The loop iterations are independent of each other as they correspond to different instances of the CellML model. OpenMP distributes the workload to a predefined number of threads that can be specified by environment variables.\n\n\\subsection{Code Generation for GPUs}\n\nBesides instruction-level and thread-level parallelism, which were discussed in the last section, accelerator hardware such as GPUs can be considered to reduce the runtime of solving a CellML model.\nOur code generator features the \\code{`gpu`} optimization type to generate code that is called on the CPU and then offloads the main computations to a GPU.\n\nWe use OpenMP 4.5 to instrument the generated code for device offloading. At the time of writing, only an experimental version of GCC 11 is fully capable of compiling this code. In our studies, the code is compiled for the \\emph{nvptx} target, which generates and compiles device-specific CUDA code using the NVIDIA parallel thread execution (PTX) instruction set architecture. We successfully run the computation on various NVIDIA GPUs, including a GeForce RTX 3080. However, the approach is device-agnostic and other accelerator hardware can also be used.\n\n\\Cref{fig:cellml_codes_gpu} shows an excerpt of the generated code. It resembles the code of the\\break\\code{`openmp`} optimization type, except that the OpenMP pragma in lines \\ref{alg:pragma_line} and \\ref{alg:pragma_line2} is different. The lines specify the variables to be mapped to and from the target device: The vectors of states and parameters as well as the current simulation time \\code{t} are sent to the GPU and, after computation, the rates and algebraics are transferred back to the CPU.\n\n\\begin{figure}\n\\centering\n\\begin{framed}\n\\begin{lstlisting}[basicstyle=\\footnotesize\\ttfamily,commentstyle=\\color{gray},numbers=left]\n  #pragma omp target parallel for \\ $\\label{alg:pragma_line}$\n                     map(to:states,t,parameters) map(from:rates,algebraics) $\\label{alg:pragma_line2}$\n  for (int i = 0; i < 1481; i++)\n  {\n    algebraics[1481+i] = ( - 0.100000*(states[0+i]+50.0000))/(exp(- (states[0+i]+5\n    rates[1481+i] =  algebraics[1481+i]*(1.00000 - states[1481+i]) -  algebraics[7\n    ...\n  }\n\\end{lstlisting}\n\\end{framed}\n\\caption{Generated code for optimization type \\code{`gpu`} corresponding to the scenario in \\cref{fig:cellml_codes}.}%\n\\label{fig:cellml_codes_gpu}%\n\\end{figure}\n\nUsing the \\code{CellmlAdapter}, it is, thus, possible to run any CellML model on the GPU. \nHowever, for the fiber based electrophysiology model uploading and downloading the data of all model instances between CPU to GPU in every timestep is clearly not the most efficient way to utilize the GPU. Therefore, we add efficient GPU integration with proper memory management to the \\code{FastMonodomainSolver} class, which is specialized to solve the monodomain equation for multiple fibers. The class allows computing multiple timesteps in series on the GPU between subsequent points of synchronization with the CPU. This synchronization is only required, e.g., for writing output files or coupling to a solid mechanics solver.\n\nThe generated GPU source code for the \\code{FastMonodomainSolver} contains the full algorithm for solving multiple timesteps of the electrophysiology model for multiple fibers with a given number of nodes each. The Strang splitting scheme is used, which solves the 0D subcellular part and the 1D electric conduction part in the scheme 0D-1D-0D.\nThe 0D part is solved by the Heun scheme. The 1D part is computed either with the implicit Euler method or the Crank-Nicolson method. The linear system of equations is solved using the linear complexity Thomas algorithm.\n\nThe parallelization on the GPU uses a fixed number of thread teams, where all threads in a team execute the same code.\nFor the 0D problem, the iterations of the two nested loops over fibers and model instances per fiber are distributed to all thread teams, such that the iterations are \\emph{workshared}. Thus, the 0D subcellular models are computed concurrently for all instances. Between the computations of the 0D and 1D parts, synchronization occurs as the data on all instances on a fiber are accessed in the solution of the 1D problem. The 1D computations are distributed on the fiber level, before the second 0D computation in the Strang splitting is again distributed on the model instance level.\nAnother synchronization occurs after each timestep of the whole Strang splitting.\n\nThe data transfer in both directions between CPU and GPU is reduced to a minimum. Initially, all required parameters and initial values have to be transferred to GPU memory. The initial state vector $\\bfy$ is only sent once to the GPU and all model instances of all fibers get initialized to these same values. Further data to be sent includes parameters that describe the stimulation times as presented in \\cref{sec:stimulation_times_callbacks}, locations of the neuromuscular junction and the distribution of fibers to motor units. Instead of the callback functions described in \\cref{sec:stimulation_times_callbacks}, the stimulation times can be altered by an input file. For details, we refer to the online documentation \\cite{opendihuWeb}.\n\nDuring computation, smaller amounts of data are transferred before and after each set of consecutive timesteps on the GPU. The data to be sent to the GPU before the computations consist of the CellML parameter values and the lengths of all elements in the 1D mesh, which change, if muscle contraction is computed on the CPU. The data to be transferred back to the CPU after the computations on the GPU consist of a subset of the state vector for every model instance. This subset contains only those components of $\\bfy$ that should be written to an output file on the CPU or are required for coupling to another solver. Thus, the majority of the data stay on the GPU.\n\n\n% ---\n\\section{Solid Mechanics Solver}\\label{sec:solid_mechanics_solver}\nNext, we discuss details on the solver of the solid mechanics models, which is needed for the muscle contraction part of the multi-scale model, described in \\cref{sec:model_muscle_contraction}.\n\n\n\\Cref{sec:solver_linear_model_elasticity} gives details on the solver for the linear solid mechanics model. \\Cref{sec:specification_of_nonlinear_ma} addresses the nonlinear model and describes how the material model is specified. \\Cref{sec:convergence_improvements_for_the_nonlinear_solver} presents the timestepping method for the dynamic problem and describes the implemented measures to improve the convergence.\n\n\\subsection{Solver for the Linear Model}\\label{sec:solver_linear_model_elasticity}\n% linear fem\nAs noted in \\cref{sec:summary_of_existing_solver_classes}, the \\code{QuasiStaticLinearElasticitySolver} class can be used to solve the linearized solid mechanics model described in \\cref{sec:material_linear_model} and discretized in \\cref{sec:linearized_mechanics_model}. \nWithin this solver class, the matrix equation \\cref{eq:linearized_helper4} is assembled and solved by an object of the \\code{FiniteElementMethod} class, which is the same class that is used to solve  Laplace problems.\n\nIf the solver is explicitly coupled with an electrophysiology model, we obtain a quasi-static formulation of muscle contraction. The activation parameter $\\bar{\\gamma}$ on the 3D mesh is transferred from the electrophysiology model to the elasticity model.\nThen, the linear system of equations of the elasticity model is solved using the new muscle activation values in the right-hand side. The system matrix stays constant in all timesteps. After the new displacements have been computed, the geometries of the 3D mesh and the embedded 1D fiber meshes are updated accordingly.\n\nIn this scenario, the active stress tensor $\\bfsigma^\\text{active}$ in \\cref{eq:linearized_helper6} is computed as the product of the activation parameter $\\bar{\\gamma}$ with a scalar maximum active stress parameter $\\sigma_\\text{max,active}$ and an anisotropy tensor $\\bfa$:\n\\begin{align}\\label{eq:solid_mechanics_solver_1}\n  \\bfsigma^\\text{active} = \\sigma_\\text{max,active} \\,\\bar{\\gamma}\\,\\bfa.\n\\end{align}\nThe tensor $\\bfa$ can be specified in the Python settings by a $3 \\times 3$ matrix and allows to specify the anisotropic active behavior of the muscle tissue. In this specification, the first unit vector $\\bfe_1=(1,0,0)^\\top$ designates the fiber direction, $\\bfe_2$ and $\\bfe_3$ specify the transverse direction. Prior to the computation in \\cref{eq:solid_mechanics_solver_1}, the basis of the given matrix is changed, such that $\\bfe_1$ in the old basis maps to the fiber direction in the new basis and the new basis is orthonormal. This change of basis is performed at every point in the muscle with the respective fiber direction. Thus, it is possible to specify transversely isotropic material behavior with contraction in fiber direction.\n\n\\subsection{Specification of Nonlinear Material Models}\\label{sec:specification_of_nonlinear_ma}\n% load steps, initalization in the dynamic case\n\nTo compute the nonlinear model, the \\code{HyperelasticitySolver} class is used for the static formulation of a passive material, the \\code{DynamicHyperelasticitySolver} class is used for the dynamic passive behavior, and the \\code{MuscleContractionSolver} is used for either the static or the dynamic model with active stress contribution.\n\nThese solver classes can be coupled to the electrophysiology model in the same way as described in \\cref{sec:solver_linear_model_elasticity}.\nSimilar to \\cref{sec:solver_linear_model_elasticity}, the \\code{MuscleContractionSolver} adds an active stress term to the formulation according to the formula in \\cref{eq:active_stress_term}. The force-length relation $f_\\ell(\\lambda_f)$ can either be added by the \\code{MuscleContractionSolver}  or specified in the CellML description as part of the subcellular model for the activation parameter $\\gamma$.\n\nTo specify the passive material behavior, the strain energy function $\\Psi$ has to be defined.\nThis definition has to be available at compile-time and is specified in the C++ code. \n\nFour different terms can be defined to describe the material model in different forms such as the coupled or decoupled representation. The four terms are introduced in \\cref{sec:material_modeling} and given in \\cref{eq:definition_psi} as follows:\n\\begin{align}\\label{eq:definition_psi1}\n  \\Psi = \\Psi_\\text{vol}(J) + \\Psi_\\text{iso}(\\bar{I}_1,\\bar{I}_2,\\bar{I}_4,\\bar{I}_5) + \\Psi_1(I_1,I_2,I_3) + \\Psi_2(\\bfC,\\bfa_0).\n\\end{align}\nFormulas for these terms can be specified using C++ expressions with a syntax specified by the \\emph{SEMT} library \\cite{semt,gutterman2004symbolic} (and also described in the online documentation of OpenDiHu \\cite{opendihuWeb}). Mathematical functions such as power and log functions are available, intermediate variables can be defined and reused, and constants for material parameters can be used, whose values can be specified in the Python settings.\n\nThe implementation uses the SEMT library to symbolically differentiate the given terms with respect to their function arguments. Thus, all values used in the Newton solver including the Jacobian matrix can be computed automatically. Using this technology, OpenDiHu provides the flexibility to add new material models at compile-time without the need for manual differentiation.\n\nAdditionally, three options, which alter the computation and efficiency, have to be set in the C++ description: The first option specifies, whether the material is considered incompressible. If this option is set to true, the solution approach with Lagrange multiplier $p$ is used, otherwise the unknowns only contain the displacements $\\bfu$ and possibly the velocities $\\bfv$. The second option specifies, if the active stress term $\\bfS^\\text{active}$ should be added to the material. This option is only relevant for the \\code{MuscleContractionSolver} class, disabling it allows computing passive tissue.\n\nThe third option determines, if the fiber direction $\\bfa_0$ appears in the description of the material model. Only if this option is enabled, the corresponding invariants $I_4$ and $I_5$ are available for the definition of the $\\Psi_\\text{iso}$ term in \\cref{eq:definition_psi1}. If disabled, all terms in the formulas in \\cref{sec:stress_and_elasticity} that involve $\\bfa_0$ are left out of the computation, which speeds up the computations in the solver.\n\n\\subsection{Convergence Improvements for the Nonlinear Solver}\\label{sec:convergence_improvements_for_the_nonlinear_solver}\n\nThe nonlinear equation is solved using the Scalable Nonlinear Equations Solvers (SNES) component of PETSc, which provides Newton-type and quasi-Newton methods for solving systems of nonlinear equations. The method to use and other parameters such as the line-search type can be configured in the Python settings file.\n\nFast convergence of a Newton-based nonlinear solver is facilitated with a good initial guess for the vector of unknowns. Therefore, we predict the solution functions $\\bfu$ and $\\bfv$ for the next timestep in a dynamic problem using the following computations:\n\\begin{align*}\n  \\bfu^{(i+1),\\text{predicted}} &= \\bfu^{(i)} + \\dt\\,\\bfv^{(i)}, & \n  \\bfa^{(i)} &= \\dfrac1{\\dt}(\\bfv^{(i)} - \\bfv^{(i-1)}), & \n  \\bfv^{(i+1),\\text{predicted}} &= \\bfv^{(i)} + \\dt\\,\\bfa^{(i)}.\n\\end{align*}\n%\nThe predicted displacements $\\bfu^{(i+1),\\text{predicted}}$ for the next timestep $(i+1)$ are estimated by a forward Euler scheme from the displacements $\\bfu^{(i)}$ and velocities $\\bfv^{(i)}$ of the current timestep $i$. The current acceleration $\\bfa^{(i)}$ is estimated by finite differences from the current and previous velocities, $\\bfv^{(i)}$ and $\\bfv^{(i-1)}$. The predicted velocities $\\bfv^{(i+1),\\text{predicted}}$ for the next timestep again use a forward Euler method with the estimated acceleration values $\\bfa^{(i)}$.\nUsing the initial guess $(\\bfu^{(i+1),\\text{predicted}},\\bfv^{(i+1),\\text{predicted}},p^{(i)})^\\top$, the solution vector $(\\bfu^{(i+1)},\\bfv^{(i+1)},p^{(i+1)})^\\top$  for the next timestep can be obtained by the nonlinear system solver.\n\nIndependently of the predictions of initial values from previous timesteps, the convergence of the nonlinear solver within a timestep can be  improved by employing load stepping. This approach involves solving $N>1$ sub problems with increasing load steps. In each step $i$, the problem is solved with the right-hand side $\\bff_i = \\alpha_i\\,\\bff$, scaled by the load factor $\\alpha_i \\in [0,1]$. The obtained solution in iteration $i$ is used as the initial guess for the subsequent load step $(i+1)$. Increasing values of $\\alpha_i$ are used until the final solution is found for $\\alpha_N=1$. Typical load factors are $(\\alpha_i)_{i=1,\\dots,N} = (b^{-(N-1)}, b^{-(N-2)}, \\dots, b^{0})$ for a basis $b>0$.\n\nThe list of load factors can be specified in the settings. If the nonlinear solver diverges or fails because an unphysical negative determinant $J$ of the deformation gradient occurs, the current load factor is automatically reduced and the solution processes is started again, using the last valid solution as initial guess. If the last successful solution was found for load factor $\\alpha_i$ and the current load factor $\\alpha_{i+1}$ fails, a new load factor $\\alpha^\\ast_{i+1} = (\\alpha_i + \\alpha_{i+1})/2$ is inserted in the list of load factors between $\\alpha_i$ and $\\alpha_{i+1}$ and the solution of the nonlinear problem with this new factor is attempted. \n\nIn case of a poorly conditioned problem, it can happen that no more solution can be found, regardless of how far the load factor gets decreased. If the difference between two load factors falls below a configurable threshold, the nonlinear solution process for the current timestep is aborted.\n\nPractical tests with the dynamic incompressible problem have shown that the convergence sometimes degrades only for a single timestep and returns to normal in the next timestep. Thus, we allow a single timestep $i$ to diverge and, in this case, continue with the next timestep $(i+1)$ using the (diverged) solution with the lowest residual norm from timestep $i$ to predict the initial guess for timestep $(i+1)$.\n\n", "meta": {"hexsha": "95ba603ce8e20751262d42f96d839b6c536d84c2", "size": 116139, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "document/07_implementation_1.tex", "max_stars_repo_name": "maierbn/phd_thesis_source", "max_stars_repo_head_hexsha": "babee64f01f15d93cb75140eb8c8424883b33c6c", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-05T19:00:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-05T19:00:04.000Z", "max_issues_repo_path": "document/07_implementation_1.tex", "max_issues_repo_name": "maierbn/phd_thesis_source", "max_issues_repo_head_hexsha": "babee64f01f15d93cb75140eb8c8424883b33c6c", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "document/07_implementation_1.tex", "max_forks_repo_name": "maierbn/phd_thesis_source", "max_forks_repo_head_hexsha": "babee64f01f15d93cb75140eb8c8424883b33c6c", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 115.2172619048, "max_line_length": 1095, "alphanum_fraction": 0.7815118091, "num_tokens": 28527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.33217528806909774}}
{"text": "\\chapter*{Abbreviations}\n\\label{abbrs}\n\\addToTOC{abbrs}\n\n\\begin{deflist}\n\\abbr{BPTT}{Backpropagation through time}{See \\cref{sec:RNN-optim}.}\n\\abbr{BPF}{Band-pass filter}{See \\cref{ch:BPF}.}\n\\abbr{BCI}{Brain-computer interface}{See \\cref{sec:BCI}.}\n\\abbr{CA1}{``Cornu Ammonis'', subregion 1}{Area in the hippocampus where voltages are recorded from (see \\cref{fig:brain-anatomy}).}\n\\abbr{CA3}{``Cornu Ammonis'', subregion 3}{Area in the hippocampus (see \\cref{fig:brain-anatomy}). CA3 sends many axons (called ``Schafer collaterals'') to CA1.}\n\\abbr{ch.}{Channel}{}\n\\abbr{CSD}{Current source density}{The rate at which the positive charge surplus of a small volume decreases, $-\\pdv*{\\rho}{t}$. By charge conservation, equal to the net rate $\\div{\\J}$ at which positive charges flow out of the small volume. See \\cref{sec:CSD}.}\n\\abbr{FIR}{Finite impulse response}{A linear filter whose output is a convolution of the input signal with some kernel.}\n\\abbr{GEVal}{Generalized eigenvalue}{See \\cref{sec:generalized-eigenproblem}.}\n\\abbr{GEVec}{Generalized eigenvector}{See \\cref{sec:generalized-eigenproblem}.}\n\\abbr{GRU}{Gated recurrent unit}{See \\cref{sec:GRU_eqs}.}\n\\abbr{IIR}{Infinite impulse response}{A filter whose output at each timestep is a linear combination of both input samples and previous output samples.}\n\\abbr{IQR}{Interquartile range}{A measure of the spread of a set of one-dimensional values, that is robust to outliers. Difference between the 75th and the 25th data percentile.}\n\\abbr{KDE}{Kernel density estimate}{}\n\\abbr{LFP}{Local field potential}{The extracellular electric potential (see \\cref{ch:LFP}).}\n\\abbr{LTP}{Long-term potentiation}{See \\cref{sec:synaptic-plasticity}.}\n\\abbr{RMS}{Root-mean-square}{$\\sqrt{\\ev{x_t^2}}$ for a signal $x_t$.}\n\\abbr{RNN}{Recurrent neural network}{See \\cref{ch:RNN}.}\n\\abbr{SNR}{Signal-to-noise ratio}{See \\cref{sec:LSM}.}\n\\abbr{SOTA}{State of the art}{The algorithm currently used for SWR detection, namely an online single channel band-pass filter.}\n\\abbr{STDP}{Spike-timing-dependent plasticity}{See \\cref{sec:synaptic-plasticity}.}\n\\abbr{SWR}{Sharp wave-ripple}{The pattern in the LFP that we want to detect in real-time. See \\cref{ch:SWR}.}\n\\abbr{VHC}{Ventral hippocampal commisure}{See \\cref{sec:disruption}.}\n% todo: sort alphabetically :)\n\\end{deflist}\n", "meta": {"hexsha": "e0e2591d31ab5754fae3b5cee8a1c34954fe99a0", "size": 2322, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "modules/Frontmatter/Abbreviations.tex", "max_stars_repo_name": "tfiers/master-thesis", "max_stars_repo_head_hexsha": "3e97128eeb18827b03da90817fe6f6985c84ad80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-23T01:39:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-23T01:39:24.000Z", "max_issues_repo_path": "modules/Frontmatter/Abbreviations.tex", "max_issues_repo_name": "tfiers/master-thesis", "max_issues_repo_head_hexsha": "3e97128eeb18827b03da90817fe6f6985c84ad80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46, "max_issues_repo_issues_event_min_datetime": "2018-09-18T16:38:12.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-10T22:37:35.000Z", "max_forks_repo_path": "modules/Frontmatter/Abbreviations.tex", "max_forks_repo_name": "tfiers/master-thesis", "max_forks_repo_head_hexsha": "3e97128eeb18827b03da90817fe6f6985c84ad80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 74.9032258065, "max_line_length": 262, "alphanum_fraction": 0.7523686477, "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.3320905695097365}}
{"text": " \\section{Mappings} \\label{sec:mappings}\nFran\\c{c}ois Faure\n\n\n\\newcommand{\\mass}{\\ensuremath{M}}             % matrice de masse\n\\newcommand{\\vol}{\\ensuremath{\\mathcal V}} % volume d'intersection\n\\newcommand{\\press}{\\ensuremath{\\rho}}\n\n% In section~\\ref{sec:pixelcontact}, we have shown how to efficiently compute repulsion forces between arbitrary polyhedra.\n% In this section, we present a general framework to map the contact forces to the degrees of freedom of arbitrary physical models.\n% We then demonstrate it on a variety of models.\n\n\\subsection{Motivation} \\label{sec:geometryLayers}\nDifferent geometrical models can be used to model objects in contact.\nWe organize them in a hierarchy of layers. An example is shown in figure~\\ref{fig:hierarchy}, where a rigid object hits a shape embedded in deformable cells.\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{mappings.png}\n \\caption{Mappings from the DOFs to a contact point. Top: two simulated objects in contact (red point). Bottom: hierarchy of geometrical layers. Positions and velocities are propagated top-down. The contact force $f_c$ is accumulated in the contact layers. Forces are then propagated bottom-up.\n%Each object has its own state vectors and mappings.\n}\n \\label{fig:hierarchy}\n\\end{figure}\n\n% bases de la dynamique\nThe state of a simulated system can be described by the values and time derivatives of its independent degrees of freedom (DOF) gathered in two vectors $x_0$ and $v_0$.\nThe dynamics equation (Newton's law) relates the second time derivative $a_0$ of the DOF to the forces $f_0$ acting on them: $f_0 = \\mass a_0$, where \\mass~ is a matrix modeling the mass of the system.\n%We call $f_0$ the \\textit{net force}.\n\n% attacher de la g�om�trie\nA geometrical model can be attached to the DOF for visualization or contact computation. \nIts DOF positions, velocities and associated forces are stored in vectors $x_1$, $v_1$ and $f_1$, respectively.\nThey are not independent variables, since the positions and velocities are bound to the independent DOF.\nWe say that the child geometrical model $1$ is mapped from the parent model $0$,\n using a kinematic operator which we call \\textit{mapping}:\n\\begin{eqnarray*} %\\label{eq:mapV}\nx_1 &=&\\JNL_1(x_0)\\\\ \nv_1 &=& J_1 v_0\n\\end{eqnarray*}\nTypical mappings include polygonal shapes attached to rigid bodies using local coordinates, or embedded in deformable cells using barycentric coordinates, as well as skin surrounding articulated bodies using vertex blending techniques.\nMatrix $J_1 = \\frac{\\partial x_1}{\\partial x_0}$ encodes the linear relation between the DOF velocities and the shape velocities. Due to linearity, the same relation holds on elementary displacements $dx$.\nIt also holds on accelerations, with an additional offset due to velocities when the position mapping \\JNL is nonlinear.\nIn most cases, operators \\JNL~ and \\J~ are the same, but in the case of rigid bodies, \\JNL~ is nonlinear with respect to $x_0$ and it can not be written as a matrix.\nFor surfaces embedded in deformable cells, matrix \\J~contains the barycentric coordinates. \nFor surfaces attached to rigid bodies, each row of the matrix encodes the usual relation $v = \\dot o + \\omega \\times (x-o)$ for each vertex. \nSimilarly, skins around articulated bodies involve, at each vertex, the weighted  contributions of the rigid bodies. \n\n\n% g�om�trie suppl�mentaire d�e aux contacts\nWhen shapes collide, additional geometry can be necessary to model the contact.\nFor instance, when an edge intersects another one, a contact force is applied to the intersection points.\nThese points are defined by their barycentric coordinates with respect to their edge vertices. \nOther relations can be used, depending on the kind of geometrical primitives in contact.\nThis additional geometry requires another geometrical layer connected to the shape by a mapping, as illustrated in figure~\\ref{fig:hierarchy}.\n% This layer is also connected to the shape using mappings:\n% \\begin{eqnarray*} %\\label{eq:mapV}\n% x_2 &=&\\JNL_2(x_1)\\\\ \n% v_2 &=&J_2 v_1 \n% \\end{eqnarray*}\nWe extend this approach to tree-like hierarchies of geometries, with the independent DOFs at the root. \nFor instance, the independent DOF may have two children, one for collision using a coarse mesh, and the other for rendering using a finer mesh. The synchronization between these siblings is automatically guaranteed by their attachment to their common ancestor, the DOF layer.\n\nPositions and velocities are propagated top-down in the hierarchy. Conversely,\nin order to take all the forces into account in the dynamics equation, the forces are propagated bottom-up, up to the independent DOFs, where Newton's law $f=ma$ is applied. \nGiven forces $f_c$ applied to a child model, the mapping computes and accumulates the equivalent forces $f_p$ applied to its parent. \nSince equivalent forces must have the same power, the following relation holds:\n$$\nv_{p}^T f_p = v_c^T f_c\n$$\nThe kinematic relation $v_{c} = J v_{p}$ allows us to rewrite the previous equation as\n$$\nv_{p}^T f_{p} = v_{p}^T J^T f_c\n$$\nSince this relation holds for any velocity $v_p$, the principle of virtual work allows us to simplify the previous equation to obtain:\n\\begin{equation} \\label{eq:mapF}\nf_{p} = J^T f_c\n\\end{equation}\n\n\\subsection{Mapping functions}\nAs seen in section~\\ref{sec:geometryLayers}, the mappings propagate positions, velocities, displacements and accelerations top-down, and they propagate forces bottom-up.\nThe top-down propagation methods are:\n\\begin{itemize}\n \\item \\texttt{apply (const MechanicalParams*, MultiVecCoordId outPos, ConstMultiVecCoordId inPos )} for positions,\n \\item \\texttt{applyJ(const MechanicalParams*, MultiVecDerivId outVel, ConstMultiVecDerivId inVel )} for velocities and small displacements,\n\\item \\texttt{computeAccFromMapping(const MechanicalParams*, MultiVecDerivId outAcc, ConstMultiVecDerivId inVel, ConstMultiVecDerivId inAcc )} for accelerations, taking into account velocity-dependent accelerations in nonlinear mappings.\n\\end{itemize}\nThe bottom-up propagation methods are:\n\\begin{itemize}\n \\item \\texttt{applyJT(const MechanicalParams*, MultiVecDerivId inForce, ConstMultiVecDerivId outForce )} for child forces or changes of child forces,\n\\item \\texttt{applyDJT(const MechanicalParams*, MultiVecDerivId parentForce, ConstMultiVecDerivId  childForce )} for changes of parent force due to a change of mapping with constant child force,\n\\item \\texttt{applyJT(const ConstraintParams*, MultiMatrixDerivId inConst, ConstMultiMatrixDerivId outConst )} for constraint Jacobians,\n\\end{itemize}\n\n\nThe name of the methods used to propagate velocities or small displacements top-down contain $J$, which denotes the kinematic matrix, while the names of the methods used to propagate forces or constraint Jacobians bottom-up contain $JT$, which denotes the transpose of the same.\nMethod \\texttt{applyJT(const MechanicalParams*, MultiVecDerivId inForce, ConstMultiVecDerivId outForce )} is used to accumulate forces from a child model to its parent. It performs a cumulative write (+=) since a model may have several children:\n\\begin{equation}\n \\label{eq.applyjt}\n f_{p} += J^T f_c\n\\end{equation}\n\nSome differential equation solvers need compute the change of force df, given a change of position dx.\nThe displacement dx, considered small, is propagated top-down using the linear operator \\texttt{applyJ(const MechanicalParams*, MultiVecDerivId outVel, ConstMultiVecDerivId inVel )}, then the force changes are accumulated bottom-up.\nDifferentiating eq.\\ref{eq.applyjt}, we get:\n\\begin{equation}\n \\label{eq.applydjt}\n \\delta f_{p} += J^T \\delta f_c + \\delta J^T f_c\n\\end{equation}\nOnce the change of child force $\\delta f_c$ is computed (see the section on force fields), method \\texttt{applyJT(const MechanicalParams*, MultiVecDerivId inForce, ConstMultiVecDerivId outForce )} is used to accumulate it in the parent, corresponding to the first term in the right of eq.\\ref{eq.applydjt}.\nMethod \\texttt{applyDJT(const MechanicalParams*, MultiVecDerivId parentForce, ConstMultiVecDerivId  childForce )} is used to accumulate the second term, which is due to the change of matrix J due to a displacement.\nIt is null in linear mappings, such as BarycentricMapping.\nThis method queries the last displacement propagated and the child force using the MechanicalParams.\n\n\nConstraints enforced using Lagrange multipliers are represented using linear equations.\nIf a linear constraint on the child DOFS in expressed as $L_c v_c = a$, where $L_c$ is the Jacobian of the constraint, then the equivalent constraint at the parent level is: $L_p v_p = a$, where $L_p = J^T L_c$.\nMethod applyJT(const ConstraintParams*, MultiMatrixDerivId inConst, ConstMultiMatrixDerivId outConst ) is used to compute $L_p$.\nSince the Jacobians are generally sparse, they are encoded in sparse matrices instead of the dense vectors used for forces.\n\n\n\n%This simple relation allows us to map forces bottom-up through the hierarchy. \n%The corresponding acceleration can then be computed in the DOF layer.\n\n% We emphasize the simplicity and the generality of equation~\\ref{eq:mapF}. \n% It makes no assumption about the constitutive laws of the simulated objects.\n% It allows us to connect arbitrary bodies using any geometry, provided that a kinematic operator linking the velocity of the geometry to the body DOFs is available.\n% %It is not limited to polygonal geometries.\n\n% It encompasses and generalizes \\cite{Sifakis07}'s hard bindings which were introduced for Finite Elements and empirically extended to rigid bodies.\n% It enables us to efficiently and straightforwardly connect or make collide a wide variety of bodies.\n\n% Let $x_n$, $y_n$, $f_n$ be, respectively, the positions, velocities and net forces in the geometrical model $n$, and $x_{n+1}$, $y_{n+1}$, $f_{n+1}$ the positions, velocities and net forces in model $n+1$ mapped from model $n$.\n% The mappings have the following propagation methods:\n% \\begin{itemize}\n%  \\item apply: propa\n% \\end{itemize}\n\n\n", "meta": {"hexsha": "33e4f7ec0e49c7efa4a1d09283f85aa6806b24e3", "size": 10041, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/mappings/concepts_body.tex", "max_stars_repo_name": "sofa-framework/issofa", "max_stars_repo_head_hexsha": "94855f488465bc3ed41223cbde987581dfca5389", "max_stars_repo_licenses": ["OML"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/mappings/concepts_body.tex", "max_issues_repo_name": "sofa-framework/issofa", "max_issues_repo_head_hexsha": "94855f488465bc3ed41223cbde987581dfca5389", "max_issues_repo_licenses": ["OML"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/mappings/concepts_body.tex", "max_forks_repo_name": "sofa-framework/issofa", "max_forks_repo_head_hexsha": "94855f488465bc3ed41223cbde987581dfca5389", "max_forks_repo_licenses": ["OML"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 71.2127659574, "max_line_length": 306, "alphanum_fraction": 0.7861766756, "num_tokens": 2486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044135, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.33209055648922714}}
{"text": "\\chapter{Introduction}\n% Tony: \"1, 2, 3 pages\"\n% What is the problem?\n% Why is it interesting?\n% How did you solve it?\n% How far did you get?\n\n% Includes motivation, objectives, and contributions (what you achieved)\n\\section{Motivation}\n\n%Understanding the human brain\nThe human brain is considered to be one of the most complex objects which have puzzled scientists and philosophers alike throughout the centuries. To gain an understanding of how this mysterious black box works, through experimentation and modelling, would be of great aid to the furthering of science and humanity alike. A part of this includes developing cures for a multitude of mental and brain-related disorders.\n\n%Artificial neural networks\nSeveral medical discoveries from the 20th century have enlightened our knowledge of the human brain. One consequence of this was the development of different mathematical models of artificial neural networks, inspired by the fields of biology and medicine.\n\n% modelling the Attachment Theory. Watch out between the distinction between Self-Attachment and Attachment Theory\nOur motivation is to use some of these neural networks to explore the mathematics of a developing theory called Self-Attachment. Part of Attachment theory, this strategy aims to help cure various mental problems that people currently facing. Recent research has shown that a mathematical methodology of analysing these disorders is starting to become feasible. \\cite{net_model_neuroses}\n\nThe subsequent chapters will introduce the Attachment Theory and the mathematical model. We have mainly focused on the technical side, and have described psychological analogies that place our technical results in context of the theory.\n\n\\section{Objectives}\n\n%Main Objectives\nOur main objective is to confirm the results of previous work done by Federico Mancinelli, who has been analysing the attachment theory using neural networks. He has performed several experiments regarding clusters of attractors, basin sizes, and Gaussian-distributed patterns. Furthermore, we have been aiming at extending his results by exploring the following concepts:\n\\begin{itemize}\n\\item Using the network for performing image recognition\n\\item Restricted Boltzmann machines\n\\item Super-attractors\n\\end{itemize}\n\n%Improvement of Federico's results\nIn addition to that, we were aiming to improve some of the methods that were used in his experiments. This includes the technique for sampling Gaussian-distributed patterns or for calculating basin sizes. Our final aims consisted of explaining some of the subsequent inconsistencies that have been found in his results.\n\n\\section{Our achievements}\n\nSince our project was related to exploring attractor-based neural networks, we have obtained interesting results about their attractors. These attractors are analogous to learned memories or experiences that an individual has learned.\n\n%This list is by no means exhaustive. Feel free to add any other aspects. This is what I(Raz) could recall a few days ago.\nOur main contributions are outlined below:\n\\begin{itemize}\n\\item Confirming Mancinelli's results by reimplementing them in a completely different environment (Haskell)\n\\item Proving that the Hopfield network is capable of performing image recognition, by learning image patterns and then recalling the closest image, when queried for an input. Furthermore, we have proven it's associative memory properties, by successfully recalling some of the learned images.\n\\item We found out that training patterns are not guaranteed to become fixed points in the Hopfield network. This is an aspect that was not mentioned in similar research papers, and we first thought the the patterns are always fixed points.\n\\item Extending the research to encompass the Boltzmann Machine, which provides a nice way of overcoming some limitations of the Hopfield Network. Amongst other features, it can prevent convergence to spurious patterns by using a stochastic update rule.\n\\item A thorough analysis of Super-Attractors, which represent patterns that have been used multiple times in the training process. They generally have greater basin sizes, and therefore patterns will have a greater chance of converging to them compared to normal attractors.\n\\end{itemize}\n", "meta": {"hexsha": "53c11b325226988fe18502aae57dab9ff54ca39b", "size": 4264, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/introduction.tex", "max_stars_repo_name": "imperialhopfield/hopfield", "max_stars_repo_head_hexsha": "d64e21b1c7b915755ae535685ffd7dfd25e3970f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2015-07-30T10:00:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-10T15:49:06.000Z", "max_issues_repo_path": "report/introduction.tex", "max_issues_repo_name": "imperialhopfield/hopfield", "max_issues_repo_head_hexsha": "d64e21b1c7b915755ae535685ffd7dfd25e3970f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/introduction.tex", "max_forks_repo_name": "imperialhopfield/hopfield", "max_forks_repo_head_hexsha": "d64e21b1c7b915755ae535685ffd7dfd25e3970f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-12-19T13:06:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-03T13:32:21.000Z", "avg_line_length": 88.8333333333, "max_line_length": 417, "alphanum_fraction": 0.8217636023, "num_tokens": 820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.542863297964157, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.33189683433829703}}
{"text": "\\subsection{SNOW with C2C Communication}\n\\label{app:algorithm-a}\nIn this section,  we show that SNOW is possible in the   \\emph{multiple-writers single-reader} \n(MWSR) setting %, and prove that any fair and well-formed execution  of $A$ satisfies  the SNOW properties.  \n%In practice, a system with a single reader may not be very useful but this algorithm serves a counter example \n%algorithm\nwhen client-to-client communication is allowed. In particular, we present an algorithm $A$, which has all SNOW properties in such setting.\n%Algorithm $A$ \n%shows that if client-to-client communication is allowed, it is possible to have algorithms  that satisfies all of the SNOW properties with two clients. \nWe consider a system that has $\\ell \\geq 1$ writers with ids $w_1, \nw_2 \\cdots w_{\\ell} \\in \\mathcal{W}$ \n%(we denote this set by $\\mathcal{W}$)\n, one reader $r$, and  $k \\geq 1$ servers with ids $s_1, s_2\\cdots s_k \\in \\mathcal{S}$. \n%(denote as $\\mathcal{S}$) that maintains the  objects $o_1, \\cdots, o_k$, respectively. \nClient-to-client communication is allowed. \n%Note that for a two-client system, when both  clients are of the same type, i.e., two writers or two readers, the SNOW properties are trivially satisfied.\n%\t\t\t\n% For any two tags $t_1, t_2 \\in \\mathcal{T}$ we say  $t_2 > t_1$ if $(i)$ $t_2.z > t_1.z$ or $(ii)$ $t_2.z = t_1.z$ and $t_2.w > t_1.w$. Therefore, the set $\\mathcal{T}$ is totally ordered set. We also assume that every client and servers has a unique id and the ids can be compared w.r.t. some lexicographic order.\n%\nThe pseudocode for algorithm $A$ is presented in Pseudocode~\\ref{fig:algo_a}. \n%We assume that each of the processes is run in a single-threaded manner.\n%, and therefore, each of the servers or the clients executes the algorithmic steps sequentially. \t\n%\nWe use keys to uniquely identify a \\wot{}.  A key $\\kappa \\in \\mathcal{K}$ is defined as a pair $(z, w)$, \nwhere $z \\in \\mathbb{N}$, and $w \\in \\mathcal{W}$ is the id of a writer. $\\mathcal{K}$ denotes the set of all possible keys. \nAlso, with each transaction we associate a tag $t \\in \\mathbb{N}$. % which will help us define an order among the transactions. \n\n%For version control of the  object values  we use tags.  A tag $t$ is defined as a pair $(z, w)$, where $z \\in \\mathbb{N}$ and $w \\in \\mathcal{W}$  is the id of a writer. We use $\\mathcal{T}$ to denote the set of all possible tags.\n\n\\textit{\\textbf{State variables:}} %The state variables in  writer, reader and  server processes are as follows. \n$(i)$ Each  \\emph{writer $w$} stores a counter $z$ corresponding to the\nnumber of \\wots{}  it  has  invoked so far, initially $0$.\n$(ii)$ The  \\emph{reader} $r$ has an \nordered list of elements, $List$, as $(\\kappa, (b_1, \\cdots, b_k))$,  where \n$\\kappa  \\in \\mathcal{K}$  and \n$(b_1, \\cdots b_k) \\in  \\{0, 1\\}^k$. Initially,  \n$List= [ ({\\kappa}^0, (1, \\cdots 1) ]$, where ${\\kappa}^0  \\equiv (0, w_0)$, \nand $w_0$ is any\nplace holder identifier for writer id. \n%$List$ can be thought of as an array, with $0$ as the starting index.\n$(iii)$ Each   \\emph{server} $s_i \\in \\mathcal{S}$  stores a set variable $Vals$ \nwith elements \nof key-value pairs $({\\kappa}, v_i) \\in \\mathcal{K} \\times \\mathcal{V}_i$. Initially,\n$Vals= \\{ ({\\kappa}^0, v_i^0)\\}$. \n%This ensures that each \\wot{} generates a unique key.\n%labeled with phase names, viz., {\\readGetTag}, {\\readValueTag}, {\\readCompleteTag} and {\\writeGetTag}. The server to server messages are labeled as {\\readDisperseTag}. Also, in some phases of {\\SODA},  the message-disperse primitives {\\mdmetaprim} and {\\mdvalueprim} are used  as services. \n\n\\textit{\\textbf{Writer steps:}} Any writer client, $w \\in \\mathcal{W}$, may invoke a \\wot{} $\\Writetr{ (o_{i_1}, v_{i_1}), (o_{i_2}, v_{i_2}), \\cdots, (o_{i_p}, v_{i_p}) }$, comprising a set of write operations,\n%for a \\wot{},\n%can be  invoked at any writer $w$, \nwhere  $I = \\{i_1, i_2, \\cdots, i_p\\}$ is some subset of $p$ indices of $[k]$. We define the set  $S_I\\triangleq \\{s_{i_1}, s_{i_2}, \\cdots, s_{i_p}\\}$.      \nThis procedure consists of two consecutive phases: {\\writeValue} and {\\informReader}.  In the {\\writeValue} phase,  $w$ creates a key ${\\kappa}$ as  $ {\\kappa}  \\equiv (z + 1, w)$; and also increments the local counter $z$ by one.   Then it sends $(${\\writeValueTag}$, ({\\kappa}, v_{i}))$ to each server $s_i$ in $S_I$, and awaits {\\ackTag}s  \nfrom each server  in $S_I$.  After receiving all {\\ackTag}s,    $w$ initiates the {\\informReader} phase during which  it sends \n(\\informReaderTag, $({\\kappa}, (b_{1}, \\cdots b_{k})$) to $r$, where for any $i \\in [k]$, $b_i$ is a boolean variable, such that $b_i=1$ if $s_i \\in S_I$, otherwise $b_i=0$. \nEssentially, such a $(k+1)$-tuple\nidentifies the set of objects that are updated during that \\wot{}, i.e., if $b_i=1$ then object \n$o_i$ was updated \nduring the execution of the  \\wot{}, otherwise $b_i=0$.  \nAfter $w$ receives    {\\ackTag} \n%tag $t_w$ \nfrom $r$ it completes the \\wot{}. \n\n\\textit{\\textbf{Reader steps:}}  \nWe use the same notations for $I$ and $S_I$ as above for the set of indices and corresponding servers, possibly \ndifferent across transactions.\nThe procedure  \\Readtr{$ o_{i_1},  o_{i_2}, \\cdots, o_{i_p}$}, \nfor any  \\rot{}, \nis  initiated at  reader  $r$, where   $o_{i_1},  o_{i_2}, \\cdots, o_{i_p}$  denotes the  subset  of  \nobjects $r$ \nintends to read. This procedure\nconsists of only one phase,  {\\readValue},  of communication \nbetween the reader and the servers in $S_I$.   Here $r$ sends  the message\n(\\readValueTag, ${\\kappa}_i$) to each server $s_i \\in S_I$, where \nthe ${\\kappa}_i$ is the key in  the tuple $({\\kappa}_{i}, (b_{1}, \\cdots, b_{k}))$  in  $List$ located at  index $j^*$ such that $b_i =1$ such that \n$i \\in I$. % where $I \\triangleq  \\{{i_1},  {i_2}, \\cdots, {i_p}\\}$.\nAfter\nreceiving the values $v_{i_1}$, $v_{i_2}, \\cdots v_{i_p}$ from all  servers in $\\mathcal{S_I}$,  where $S_I \\triangleq \\{s_{i_1},  s_{i_2}, \\cdots, s_{i_p}\\}$, the transaction completes by \nreturning $(v_{i_1}, \\cdots v_{i_p})$.\n\nOn receiving a message  \n(\\informReaderTag, $({\\kappa}, (b_{1}, \\cdots, b_{k})$) from any writer $w$,  $r$ appends  \n$({\\kappa}, (b_{1}, \\cdots, b_{k})$ to its  $List$,  and responds to $w$ with  \n{\\ackTag} and $t_w = |List|$, i.e., number of elements in $List$.\nThe order of the  elements in  $List$ corresponds to  the order  \nthe \\wots{}, the order of the incoming  {\\informReaderTag} updates,  as seen by the reader.\n\n\n\\textit{\\textbf{Server steps:}} The server responds to messages containing the tags \n{\\writeValueTag} and \\readValueTag.  The first procedure is used if a server $s_i$ receives a \nmessage  $(${\\writeValueTag}$, ({\\kappa}, v_{i}))$  from a writer $w$,  it  adds $({\\kappa}, v_i)$ to its set variable   $Vals$ and sends {\\ackTag} back to $w$.\nThe second procedure is used  if  $s_i$ receives a message, i.e., $(${\\readValueTag}$, {\\kappa}_{i})$, from $r$, then it responds with $v_i$ such that $({\\kappa}_{i}, v_i)$ is in its $Vals$.\n\n\\begin{algorithm}[!h]\n\t\\begin{algorithmic}[2]\n\t\t%\\vspace{-2em}\n\t\t\\begin{multicols}{2}{\\footnotesize\n\t\t\t\t%\\Statex  \n\t\t\t\t\\Statex {\\bf At writer $w$}\n\t\t\t\t\\Part{{\\it State Variables at $w$}}{ \t\n\t\t\t\t\t\\Statex $z \\in \\mathbb N$, initially   $0$\n\t\t\t\t}\\EndPart\n\t\t\t\t\\Statex\\Statex\n\t\t\t\t{\\bf  \\Writetr{$(o_{i_1}, v_{i_1}), \\cdots, (o_{o_p},  v_{i_p})$}}\n\t\t\t\t\\Part{ \\underline{\\writeValue}} {\n\t\t\t\t\t\\State ${\\kappa} \\leftarrow (z +1,  w)$\n\t\t\t\t\t\\State $z \\leftarrow z +1 $\n\t\t\t\t\t\\State $I\\triangleq \\{i_1, i_2, \\cdots, i_p \\}$\n\t\t\t\t\t%\\State $S_{I}\\triangleq \\{s_{i_1}, s_{i_2}, \\cdots, s_{i_p} \\}$\n\t\t\t\t\t\\For{$i \\in I$} \n\t\t\t\t\t\\State Send (\\writeValueTag, $({\\kappa}, v_{s_i})$) to  $s_i$\n\t\t\t\t\t\\EndFor \n\t\t\t\t\t\\State  Await {\\ackTag}  from  $s_i$ $\\forall$ $i \\in I$.\n\t\t\t\t}\\EndPart\n\t\t\t\t\\Statex\n\t\t\t\t\\Part{ \\underline{\\informReader}} {\n\t\t\t\t\t\\For{$i \\in [k]$} \n\t\t\t\t\t\\If{$i \\in I$}\n\t\t\t\t\t\\State $b_i \\leftarrow 1$\n\t\t\t\t\t\\Else\n\t\t\t\t\t\\State $b_i \\leftarrow 0$\n\t\t\t\t\t\\EndIf\n\t\t\t\t\t\\EndFor \n\t\t\t\t\t%      \\State $b_{i}\\triangleq$   $v_i$ if  $i \\in I$, otherwise $\\bot$\n\t\t\t\t\t\\State  Send  (\\informReaderTag,\n\t\t\t\t\t \\\\~~~~~~$({\\kappa}, (b_{1}, \\cdots, b_{k}))$) to   $r$\n\t\t\t\t\t\\State  Receive ({\\ackTag}, $t_w$) from  $r$\n\t\t\t\t}\\EndPart\n\t\t}\\end{multicols}\t\n\t\t\\vspace{-1.5em} \n\t\t\\\\\\hrulefill \t\n\t\t\\vspace{-1.5em}\n\t\t\\begin{multicols}{2}{\\footnotesize\t\n\t\t\t\t\\Statex {\\bf At reader $r$}\n\t\t\t\t\\Part{{\\it State Variables at $r$}}{ \t\n\t\t\t\t\t\\Statex $List$, a list  of elements in  $\\mathcal{K} \\times \\{ 0, 1 \\}^k $,\\\\ ~~~~~initially  $[({\\kappa}^0, 1, \\cdots 1)]$\n\t\t\t\t}\\EndPart\n\t\t\t\t\n\t\t\t\t\\Statex\n\t\t\t\t\\Statex  {\\bf \\Readtr{$ o_{i_1},  o_{i_2}, \\cdots, o_{i_p}$}}\t\n\t\t\t\t\\Part{{\\underline{{\\readValue}}}}{ \n\t\t\t\t\t% \\State $\\forall i, 1 \\leq i \\leq k$: $t_i^{max}  \\leftarrow \\max\\{ t: (i, t) \\in  Tags\\}$\n\t\t\t\t\t\\State $I\\triangleq \\{i_1, i_2, \\cdots, i_p \\}$\n\t\t\t\t\t%\\State $S_{I}\\triangleq \\{s_{i_1}, s_{i_2}, \\cdots, s_{i_p} \\}$\n\t\t\t\t\t\\For{$i \\in I$} \n\t\t\t\t\t\\State $j^* \\leftarrow \\max_{1 \\leq j \\leq |List|} \\{j:$\n\t\t\t\t\t\\\\~~~~~~~~~~~$List[j].b_i = 1\\}$\n\t\t\t\t\t\\State ${\\kappa}_i \\leftarrow List[j^*].{\\kappa}$\n\t\t\t\t\t\\State  Send (\\readValueTag, ${\\kappa}_i$) to $s_i$\n\t\t\t\t\t\\EndFor\n\t\t\t\t\t\\Statex \n\t\t\t\t\t\\State  Await responses  $v_{i}$ from  $s_i$ $\\forall$ $i\\in I$\n\t\t\t\t\t%\\Statex /* $t_r \\triangleq \\max_{1 \\leq j \\leq |List|} \\{ j : List[j].b_i = 1 \\wedge i \\in I\\}$ */\n\t\t\t\t\t\\State Return  $(v_{i_1}, v_{i_2}, \\cdots, v_{i_p})$\n\t\t\t\t}\\EndPart\n\t\t\t\t%\t\\Statex\n\t\t\t\t\\\\\\hrulefill\n\t\t\t\t\\Statex\n\t\t\t\t\\Statex {\\bf Response routines}\n\t\t\t\t\\Part{{\\underline{On recv  (\\informReaderTag,}\n\t\t\t\t\t\t\\\\\\underline{$({\\kappa}, (b_{1}, \\cdots b_{k}))$) from  $w$}}}{ \n\t\t\t\t\t\\Statex %// $\\bigoplus$ denotes append to list\n\t\t\t\t\t\\State $List  \\leftarrow List \\bigoplus~ ({\\kappa}, (b_{1}, \\cdots b_{k}))$ \n\t\t\t\t\t\\\\~~~/* $\\bigoplus$ for append */\n\t\t\t\t\t\\State $tag \\leftarrow |List|$ /* $| \\cdot |$ list size */\n\t\t\t\t\t\\State Send  ({\\ackTag}, $tag$) to  $w$\n\t\t\t\t}\\EndPart\n\t\t\t\t%\\Statex\n\t\t}\\end{multicols}\n\t\t\n\t\t\\vspace{-1.5em}\n\t\t\\\\\\hrulefill %\t\n\t\t\\vspace{-1.5em}\n\t\t\\begin{multicols}{2}{\\footnotesize\n\t\t\t\t\\Statex {\\bf At server $s_i$ for any $i \\in [k]$}\n\t\t\t\t\\Part{{\\it State Variables}}{ \n\t\t\t\t\t\n\t\t\t\t\\Statex $Vals\\subset \\mathcal{K} \\times \\mathcal{V}_i$, initially   $\\{(t^0_{key}, v_i^0)\\}$\n\t\t\t\t\t%\t\t\t\t\t\t\tpair with a tag and a coded element, initially $(t_0, c_0)$.\n\t\t\t\t\t%\\Statex $t_c$,  the committed tag, initially $t_0$\n\t\t\t\t}\\EndPart\n\t\t\t\t\\Statex\n\t\t\t\t\n\t\t\t\t\\Part {\\underline{On recv (\\writeValueTag, $({\\kappa}, v)$) \n\t\t\t\t\t\tfrom $w$}} {\n\t\t\t\t\t\\State $Vals \\gets   Vals \\cup \\{({\\kappa}, v)\\}$ \n\t\t\t\t\t\\State Send {\\ackTag} to $w$.\n\t\t\t\t}\\EndPart\n\t\t\t\t\\Statex\n\t\t\t\t\\Part{ \\underline{On recv (\\readValueTag, ${\\kappa}$) from  $r$ }} {\n\t\t\t\t\t\\State   Send $v$ s.t. $({\\kappa}, v) \\in Vals$  to $r$\n\t\t\t\t}\\EndPart\t\n\t\t}\\end{multicols}\n\t\\end{algorithmic}\t\n\t\\caption{Steps at writer $w$, reader $r$ and server $s_i$ in $A$.}\\label{fig:algo_a}\n\\end{algorithm}\t\n%\tBelow we show that algorithm $C$ satisfies the SNOW properties. For the property ``S'' we will lean on an equivalence condition result from atomicity (strong consistency). We reproduce the lemma below. \\blue{Note that this lemma for atomicity on read/write atomic register but we will have to adapt it to atomic transactions carefully. For now,  we will assume it and later we will prove it for atomic transactions. }\n$A$ respects the SNOW properties as stated below.\n% Due to space constraints, the proof of the theorem can be found in Appendix~\\ref{app:algorithm-a}. %, where \\wots{} are live. % and the proof is omitted, for now, since it is very straightforward. \n\n\n%Consider any failure-free execution of algorithm $A$. In the steps for the reader assume the quantity\n%$t_r \\triangleq \\max_{1 \\leq j \\leq |List|} \\{ j : List[j].b_i = 1 \\wedge i \\in I\\}$, which is presented as a comment in the pseudo-code for $A$.\n%We associate with any transaction $\\phi$ a tag\n%$tag(\\phi)$ such that if  $\\phi$ is a \\wot{}  $tag(\\phi)=t_w$, i.e., the value of $t_w$ before the completion of the operation, and $tag(\\phi)=t_r$ when $\\phi$ is a \\rot{}.\n\n\\begin{theorem} Any well-formed  and fair execution of $A$ \n\t%transaction processing in the MWSR setting, % \n%\twith for objects of type $\\mathcal{O}_T$, \n\t%consisting of  objects $o_1, o_2, \\cdots o_k$ maintained by the  servers $s_1, s_y, \\cdots, s_k$, respectively; and it\n\t\t guarantees all of the SNOW properties.\n\t\\end{theorem}\n\\remove{\t\n\n\t\\begin{proof} Below we show that $A$ satisfies the  SNOW properties. \n\t\n\t\\noindent{\\emph{\\underline{S property:}}} \n\tLet $\\beta$ be any fair execution  of  $A$ and \n suppose all clients in $\\beta$ behave in a well-formed\nmanner. Suppose $\\beta$ contains no incomplete transactions and let  $\\Pi$ be the set of transactions in $\\beta$.  We define an irreflexive partial ordering ($\\prec$) among the transactions in $\\Pi$ as follows:  if $\\phi$ and $\\pi$ are any two distinct transactions in $\\Pi$ then we say \n\t$\\phi \\prec \\pi$ if either $(i)$ $tag(\\phi) < tag(\\pi)$ or $(ii)$ $tag(\\phi) = tag(\\pi)$ and $\\phi$ is a {\\sc write} and $\\pi$ is a {\\sc read}. We will prove the $S$  (strict-serializability) property of $A$ by proving that the properties $P1$, $P2$, $P3$ and $P4$ of Lemma~\\ref{lem:equivalence} hold for $\\beta$. \n\t\n\t\\emph{P1:}   If $\\pi$ is a {\\sc read} then since all {\\sc read}s are invoked by a single reader $r$ and in a well-formed manner, \n\ttherefore, there cannot be an infinite number of {\\sc read}s such that they all \n\tprecede $\\pi$ (w.r.t $\\prec$).\n\t Now, suppose $\\pi$ is a {\\sc write}. Clearly, from an inspection of the algorithm, \n\t $tag(\\pi) \\in \\mathbb{N}$. From inspection of the algorithm, each {\\sc write} increases the size of \n\t $List$, and the value of the tags are  defined by the size of $List$. Therefore, there can be at \n\t most a finite number of {\\sc write}s such that can precede $\\pi$ (w.r.t. $\\prec$) in $\\beta$.\n\t  \n\t\\emph{P2:}  Suppose $\\phi$ and $ \\pi$ are any two transactions in $\\Pi$, such that, $\\pi$ begins after $\\phi$ completes. \n\tThen we show that we cannot have $\\pi \\prec \\phi$. Now, we consider four cases, depending on whether $\\phi$ and $\\pi$ are {\\sc read}s or {\\sc write}s.\t\n\t\\begin{enumerate}\n\t    \\item [$(a)$] $\\phi$ and $\\pi$ are {\\sc write}s invoked by writers $w_{\\phi}$ and $w_{\\pi}$, respectively. Since the size of $List$, in $r$,  grows monotonically with each {\\sc write}  hence  $w_{\\pi}$ receives the  tag at least as high as $tag(\\phi)$, so $\\pi\\not \\prec \\phi$.\n\t      %\n\t       \\item [$(b)$] $\\phi$ is a {\\sc write}, $\\pi$ is a {\\sc read} transactions invoked by writer $w_{\\phi}$ and $r$, respectively.  \n\t        Since the size of $List$, in $r$,  grows monotonically, and because  $w_{\\pi}$ invokes $\\pi$ after $\\phi$ completes hence  $tag(\\pi)$ is at least as high as $tag(\\phi)$, so $\\pi\\not \\prec \\phi$.\n\t      %\n\t        \\item[$(c)$] $\\phi$ and $\\pi$ are {\\sc read}s  invoked by reader $r$. \n\t           Since the size of $List$, in $r$,  grows monotonically,  hence  $w_{\\pi}$ invoked $\\pi$ after $\\phi$ completes hence $tag(\\pi)$ is at least as high as $tag(\\phi)$, so $\\pi\\not \\prec \\phi$.\n\t        %\n\t         \\item [$(d)$] $\\phi$ is a {\\sc read}, $\\pi$ is a {\\sc write}  invoked by reader $r$ and $w_{\\pi}$, respectively.\n\t         This case is simple because new values are added to $List$  only  by writers, and $tag(\\pi)$ \n\t         is larger than the tag of $\\phi$ and hence   $\\pi\\not \\prec \\phi$. \n\t\\end{enumerate}\n\t\n\t\\emph{P3:} This is clear by the fact that any {\\sc write} transaction always creates a unique tag and all tags are totally ordered since they all belong to $\\mathbb{N}$\n\t\n\t\\emph{P4:} Consider a {\\sc read} $\\rho$ as $READ(o_{i_1}, o_{i_2}, \\cdots, o_{i_q})$, in $\\beta$. \nLet the returned value from $\\rho$ be $\\mathbf{v} \\equiv $$(v_{i_1}, v_{i_2}, \\cdots, v_{i_q})$ such that \n$1 \\leq {i_1} <  {i_2} <  \\cdots <  {i_q} \\leq k$, where value  $v_{i_j}$ corresponds to $o_{i_j}$. \n\tSuppose $tag(\\rho) \\in \\mathbb{N}$ was created during some {\\sc write} transaction, say $\\phi$, i.e., $\\phi$ is the {\\sc write} that \n\tadded the elements in index $(tag(\\rho)-1)$ of $List$. Note that element in index $0$ contains the initial value.\n\t%because {\\sc read} transactions do not generate new tags as they do not add any new item to the $Vals$ of any server.\n\t Now we consider two cases:\n\t \n\t\\emph{Case $tag(\\rho) = 1$.} We  know that it corresponds the initial default value $v_i^0$ at each sub-object $o_i$, and this equates to $\\rho$ returning the default initial value for each sub-object.\n\t %\n\t% Therefore, $tag(\\rho) = tag(\\phi)$. \n\t \n\t \\emph{Case $tag(\\rho) > 1$.} Then we argue that there exists no {\\sc write} transaction, say $\\pi$, that updated object $o_{i_j}$,   in $\\beta$, such that,  $\\pi \\neq \\phi$ and $\\rho$ returns values written by $\\pi$ and $\\phi \\prec \\pi \\prec \\rho$. Suppose we assume the \tcontrary, which means $tag(\\phi) < tag(\\pi) < tag(\\rho)$. The latter implies $tag(\\phi)  = tag(\\pi)$ which is not possible because \n\tthis contradicts the fact that for any two distinct {\\sc write}s $tag(\\phi) \\neq tag(\\pi)$  in any execution of   $A$.\n\t\n\t\\noindent{\\emph{\\underline{N property:}}}  By inspection of algorithm $A$ for the  response steps  of the servers to the reader.\n\t\n\t\\noindent{\\emph{\\underline{O property:}}} By inspection of the  {\\readValue} phase: it consists of one round of communication between the reader and the servers, where the servers send only one version of the value of the object it maintains.\n\t\n\t\\noindent{\\emph{\\underline{W property:}}}  By inspection of the {\\sc write} transaction steps, and  and  that writers always get to complete the transactions they invoke.\n\t%Finally, the liveness property of {\\sc write} transactions can be realized by inspecting the steps of  algorithm $A$.\n\t\\end{proof}\n}\n", "meta": {"hexsha": "ab3f4ff43c02ad7097da15271dab4a8e1e0b5f3e", "size": 17692, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "appendix_algra.tex", "max_stars_repo_name": "kishori82/DISC2020-SNOW-Revisited", "max_stars_repo_head_hexsha": "65f35b83186e9a3c5d83ad0851c3730271ff42f1", "max_stars_repo_licenses": ["LPPL-1.3c"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "appendix_algra.tex", "max_issues_repo_name": "kishori82/DISC2020-SNOW-Revisited", "max_issues_repo_head_hexsha": "65f35b83186e9a3c5d83ad0851c3730271ff42f1", "max_issues_repo_licenses": ["LPPL-1.3c"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "appendix_algra.tex", "max_forks_repo_name": "kishori82/DISC2020-SNOW-Revisited", "max_forks_repo_head_hexsha": "65f35b83186e9a3c5d83ad0851c3730271ff42f1", "max_forks_repo_licenses": ["LPPL-1.3c"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 65.2841328413, "max_line_length": 419, "alphanum_fraction": 0.6431155324, "num_tokens": 6096, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3318968252949478}}
{"text": "\\documentclass[12pt]{article}\r\n\\textwidth 150mm\r\n\\textheight 230mm\r\n\\topmargin -24pt\r\n\\oddsidemargin 0.4cm\r\n\\evensidemargin 0.4cm\r\n\r\n\\usepackage{amsmath}\r\n\\usepackage{amssymb}\r\n\r\n\\newcommand{\\Gr}{Gr\\\"obner }\r\n\\newcommand{\\B}{\\mathbb{B\\,}}\r\n\\newcommand{\\F}{\\mathbb{F}}\r\n\r\n\\title{BIBASIS: A Package for Calculating Boolean Involutive Bases}\r\n\\date{}\r\n\\author{\r\n    Yuri A. Blinkov\\\\[0.2cm]\r\n    Saratov State University\\\\\r\n    Saratov, Russia\\\\\r\n    Email: BlinkovUA@info.sgu.ru\\\\[0.2cm]\r\n    and \\\\[0.2cm]\r\n    Mikhail V. Zinin\\\\[0.2cm]\r\n    Joint Institute for Nuclear Research\\\\\r\n    Dubna, Russia\\\\[0.2cm]\r\n    Email: mzinin@gmail.com}\r\n\r\n\\begin{document}\r\n\\maketitle\r\n\r\n\r\n\\section{Introduction}\r\n\r\nInvolutive polynomial bases are redundant \\Gr bases of special structure with some additional useful features in comparison \r\nwith reduced \\Gr bases~\\cite{GB'98} . Apart from numerous applications of involutive bases~\\cite{Seiler'10} the \r\ninvolutive algorithms~\\cite{Gerdt'05} provide an efficient method for computing reduced \\Gr bases. A reduced \\Gr basis \r\nis a well-determined subset of an involutive basis and can be easily extracted from the latter without any extra reductions. \r\nAll this takes place not only in rings of commutative polynomials but also in Boolean rings.\r\n\r\nBoolean \\Gr basis already have already revealed their value and usability in  practice. The first impressive demonstration\r\nof practicability of Boolean \\Gr bases was breaking the first HFE (Hidden Fields Equations) challenge in the public\r\nkey cryptography done in~\\cite{Faugere'03} by computing a Boolean \\Gr basis for the system of quadratic\r\npolynomials in 80 variables. Since that time the Boolean \\Gr bases application area has widen drastically and nowadays there \r\nis also a number of quite successful examples of using \\Gr bases for solving SAT problems.\r\n\r\nDuring our research we had developed~\\cite{ISSAC'08, PaCS'08, PCA'09} Boolean involutive algorithms based on Janet and Pommaret \r\ndivisions and applied them to computation of Boolean \\Gr bases. Our implementation of both divisions has experimentally \r\ndemonstrated computational superiority of the Pommaret division implementation. This package BIBASIS is the result\r\nof our thorough research in the field of Boolean \\Gr bases. BIBASIS implements the involutive algorithm based on Pommaret \r\ndivision in a multivariate Boolean ring.\r\n\r\nIn section 2 the Boolean ring and its peculiarities are shortly introduced. In section 3 we briefly argue  \r\nwhy the involutive algorithm and Pommaret division are good for Boolean ring while the Buhberger's algorithm is not.\r\nAnd finally in section 4 we give the full description of BIBASIS package capabilities and illustrate it by examples.\r\n\r\n\\section{Boolean Ring}\r\n\r\n{\\em Boolean ring} perfectly goes with its name, it is a ring of {\\em Boolean functions} of $n$ variables, i.e\r\nmappings from $\\{0,1\\}^n$ to $\\{0,1\\}^n$. Considering these variables are $\\mathbf{X}:=\\{x_1,\\ldots,x_n\\}$ and\r\n$\\F_2$ is the finite field of two elements $\\{0,1\\}$, Boolean ring can be regarded as the quotient ring\r\n$$\r\n\\B[\\mathbf{X}]:=\\F_2[\\mathbf{X}]\\,/<x_1^2+x_1,\\ldots,x_n^2+x_n>.\r\n$$\r\nMultiplication in $\\B[\\mathbf{X}]$ is {\\em idempotent} and addition is {\\em nilpotent}\r\n$$\r\n\\forall\\, b\\in \\B[\\mathbf{X}]\\ :\\ \\,b^2=b\\,,\\ b+b=0.\r\n$$\r\nElements in $\\B[\\mathbf{X}]$ are {\\em Boolean polynomials} and can be represented as finite sums\r\n$$\r\n\\sum_j \\prod_{x\\in\\, \\Omega_j \\subseteq\\, \\mathbf{X}} x\r\n$$\r\nof {\\em Boolean monomials}. Each monomial is a conjunction. If set $\\Omega$ is empty, then the corresponding\r\nmonomial is the unity Boolean function 1. The sum of zero monomials corresponds to zero polynomial, i.e. is\r\nzero Boolean function 0.\r\n\r\n\\section{Pommaret Involutive Algorithm}\r\n\r\nDetailed description of involutive algorithm can found in~\\cite{Gerdt'05}. Here we note that result of both\r\ninvolutive and Buhberger's algorithms depend on chosen monomial ordering. At that the ordering must be\r\nadmissible, i.e.\r\n$$\r\n\\ m \\neq 1 \\Longleftrightarrow m \\succ 1, \\quad \\ \\ m_1 \\succ m_2 \\Longleftrightarrow m_1 m \\succ m_2 m\r\n\\quad \\ \\ \\forall \\ m, m_1, m_2.\r\n$$\r\nBut as one can easily check the second condition of admissibility does not hold for any monomial ordering\r\nin Boolean ring:\r\n$$\r\nx_1\\succ x_2\\quad \\xrightarrow{\\ \\ *x_1\\ \\ }\\quad x_1*x_1\\succ x_2*x_2\\quad \\xrightarrow{\\ \\ \\ \\ \\ }\\quad x_1 \\prec x_1x_2\r\n$$\r\nThough $\\B[\\mathbf{X}]$ is a principal ideal ring, boolean singleton $\\{p\\}$ is not necessarily a \\Gr basis of\r\nideal $<p>$, for example:\r\n$$\r\nx_1,x_2\\in \\,<x_1x_2 + x_1 + x_2> \\subset \\B[x_1, x_2].\r\n$$\r\nThat the reason why one cannot apply the Buhberger's algorithm directly in a Boolean ring, using instead a ring\r\n$\\F_2[\\mathbf{X}]$ and {\\em the field binomials} $x_1^2+x_1,\\ldots,x_n^2+x_n$.\r\n\r\nThe involutive algorithm based on Janet division has the same disadvantage unlike the Pommaret division algorithm as shown \r\nin~\\cite{ISSAC'08}. The Pommaret division  algorithm can be applied directly in a Boolean ring and admits effective data \r\nstructures for monomial representation.\r\n\r\n\\section{BIBASIS Package}\r\n\r\nThe package BIBASIS implements the Pommaret division algorithm in a Boolean ring. The first step to using the package\r\nis to load it:\r\n\\begin{verbatim}\r\n    1: load_package bibasis;\r\n\\end{verbatim}\r\nThe current version of the BIBASIS user interface consists only of 2 functions:     \\texttt{bibasis} and\r\n\\texttt{bibasis\\_print\\_statistics}.\r\n\r\n\\vskip 1.0cm\r\n\r\n\\noindent The \\texttt{bibasis} is the function that performs all the computation and has the following syntax:\r\n\\begin{center}\r\n    \\texttt{bibasis(initial\\_polynomial\\_list, variables\\_list, monomial\\_ordering, reduce\\_to\\_groebner);}\r\n\\end{center}\r\nInput:\r\n\\begin{itemize}\r\n    \\item \\texttt{initial\\_polynomial\\_list} is the list of polynomials containing the known basis of initial\r\nBoolean ideal. All given polynomials are treated modulo 2. See Example 1.\r\n    \r\n    \\item \\texttt{variables\\_list} is the list of independent variables in decreasing order.\r\n    \r\n    \\item \\texttt{monomial\\_ordering} is a chosen monomial ordering and the supported ones are:\r\n        \\begin{itemize}\r\n            \\item[] \\texttt{lex} -- pure lexicographical ordering;\r\n            \\item[] \\texttt{deglex} -- degree lexicographic ordering;\r\n            \\item[] \\texttt{degrevlex} -- degree reverse lexicographic.\r\n        \\end{itemize}\r\n        See Examples 2---4 to check that \\Gr (as well as involutive) basis depends on monomial ordering.\r\n        \r\n    \\item \\texttt{reduce\\_to\\_groebner} is a Boolean value, if it is \\texttt{t} the output is the reduced\r\n        Boolean \\Gr basis, if \\texttt{nil}, then the reduced Boolean Pommaret basis. Examples 5,6 show distinctions between these two outputs.\r\n\\end{itemize}\r\nOutput:\r\n\\begin{itemize}\r\n \\item The list of polynomials which constitute the reduced Boolean \\Gr or Pommaret basis.\r\n\\end{itemize}\r\n\r\n\\vskip 1.0cm\r\n\r\n\\noindent The syntax of \\texttt{bibasis\\_print\\_statistics} is simple:\r\n\\begin{center}\r\n    \\texttt{bibasis\\_print\\_statistics();}\r\n\\end{center}\r\nThis function prints out a brief statistics for the last invocation of \\texttt{bibasis} function. See Example 7.\r\n\r\n\\section{Examples}\r\n\r\n\r\nExample 1:\r\n\\begin{verbatim}\r\n    1: load_package bibasis;\r\n    2: bibasis({x+2*y}, {x,y}, lex, t);\r\n    {x}\r\n\r\n\\end{verbatim}\r\n\r\n\\noindent Example 2:\r\n\\begin{verbatim}\r\n1: load_package bibasis;\r\n2: variables :={x0,x1,x2,x3,x4}$\r\n3: polynomials := {x0*x3+x1*x2,x2*x4+x0}$\r\n4: bibasis(polynomials, variables, lex, t);\r\n{x0 + x2*x4,x2*(x1 + x3*x4)}\r\n\r\n\\end{verbatim}\r\n\r\n\\noindent Example 3:\r\n\\begin{verbatim}\r\n1: load_package bibasis;\r\n2: variables :={x0,x1,x2,x3,x4}$\r\n3: polynomials := {x0*x3+x1*x2,x2*x4+x0}$\r\n4: bibasis(polynomials, variables, deglex, t);\r\n{x1*x2*(x3 + 1),\r\n x1*(x0 + x2),\r\n x0*(x2 + 1),\r\n x0*x3 + x1*x2,\r\n x0*(x4 + 1),\r\n x2*x4 + x0}\r\n\r\n\\end{verbatim}\r\n\r\n\\noindent Example 4:\r\n\\begin{verbatim}\r\n1: load_package bibasis;\r\n2: variables :={x0,x1,x2,x3,x4}$\r\n3: polynomials := {x0*x3+x1*x2,x2*x4+x0}$\r\n4: bibasis(polynomials, variables, degrevlex, t);\r\n{x0*(x1 + x3),\r\n x0*(x2 + 1),\r\n x1*x2 + x0*x3,\r\n x0*(x4 + 1),\r\n x2*x4 + x0}\r\n\r\n\\end{verbatim}\r\n\r\n\\newpage\r\n\r\n\\noindent Example 5:\r\n\\begin{verbatim}\r\n1: load_package bibasis;\r\n2: variables :={x,y,z}$\r\n3: polinomials := {x, z}$\r\n4: bibasis(polinomials, variables, degrevlex, t);\r\n{x,z}\r\n\r\n\\end{verbatim}\r\n\r\n\\noindent Example 6:\r\n\\begin{verbatim}\r\n1: load_package bibasis;\r\n2: variables :={x,y,z}$\r\n3: polinomials := {x, z}$\r\n4: bibasis(polinomials, variables, degrevlex, nil);\r\n{x,z,y*z}\r\n\r\n\\end{verbatim}\r\n\r\n\\noindent Example 7:\r\n\\begin{verbatim}\r\n1: load_package bibasis;\r\n2: variables :={u0,u1,u2,u3,u4,u5,u6,u7,u8,u9}$\r\n3: polinomials := {u0*u1+u1*u2+u1+u2*u3+u3*u4+u4*u5+u5*u6+u6*u7+u7*u8+u8*u9,\r\n3:                 u0*u2+u1+u1*u3+u2*u4+u2+u3*u5+u4*u6+u5*u7+u6*u8+u7*u9,\r\n3:                 u0*u3+u1*u2+u1*u4+u2*u5+u3*u6+u3+u4*u7+u5*u8+u6*u9,\r\n3:                 u0*u4+u1*u3+u1*u5+u2+u2*u6+u3*u7+u4*u8+u4+u5*u9,\r\n3:                 u0*u5+u1*u4+u1*u6+u2*u3+u2*u7+u3*u8+u4*u9+u5,\r\n3:                 u0*u6+u1*u5+u1*u7+u2*u4+u2*u8+u3+u3*u9+u6,\r\n3:                 u0*u7+u1*u6+u1*u8+u2*u5+u2*u9+u3*u4+u7,\r\n3:                 u0*u8+u1*u7+u1*u9+u2*u6+u3*u5+u4+u8,\r\n3:                 u0+u1+u2+u3+u4+u5+u6+u7+u8+u9+1}$\r\n4: bibasis(polinomials, variables, degrevlex, t);\r\n{u3*u6,\r\n u3*u7,\r\n u7*(u6 + 1),\r\n u3*u8,\r\n u6*u8 + u6 + u7,\r\n u7*u8,\r\n u3*(u9 + 1),\r\n u6*u9 + u7,\r\n u7*(u9 + 1),\r\n u8*u9 + u6 + u7 + u8,\r\n u0 + u3 + u6 + u9 + 1,\r\n u1 + u7,\r\n u2 + u7 + u8,\r\n u4 + u6 + u8,\r\n u5 + u6 + u7 + u8}\r\n5: bibasis_print_statistics();\r\n        Variables order = u0 > u1 > u2 > u3 > u4 > u5 > u6 > u7 > u8 > u9\r\nNormal forms calculated = 216\r\n  Non-zero normal forms = 85\r\n        Reductions made = 4488\r\nTime: 270 ms\r\nGC time: 0 ms\r\n\r\n\\end{verbatim}\r\n\r\n\r\n\\begin{thebibliography}{99}\r\n\r\n\\bibitem{GB'98} V.P.Gerdt and Yu.A.Blinkov. {\\em Involutive Bases of Polynomial Ideals}. \r\nMathematics and Computers in Simulation, 45, 519--542, 1998; {\\em Minimal Involutive Bases}, ibid. 543--560.\r\n \r\n\\bibitem{Seiler'10} W.M.Seiler. {\\em Involution: The Formal Theory of Differential Equations and its Applications \r\nin Computer Algebra}. Algorithms and Computation in Mathematics, 24, Springer, 2010.  arXiv:math.AC/0501111\r\n\r\n\\bibitem{Gerdt'05} Vladimir P. Gerdt. {\\em Involutive Algorithms for Computing \\Gr Bases}.\r\nComputational Commutative and Non-Commutative Algebraic Geometry. IOS Press, Amsterdam, 2005, pp.199--225.\r\n\r\n\\bibitem{Faugere'03}\r\nJ.-C.Faug\\`{e}re and A.Joux. Algebraic Cryptanalysis of Hidden Field Equations\r\n(HFE) Using \\Gr Bases. {\\em LNCS} 2729, Springer-Verlag, 2003, pp.44--60.\r\n\r\n\\bibitem{ISSAC'08}\r\nV.P.Gerdt and M.V.Zinin. A Pommaret Division Algorithm for Computing \\Gr Bases in Boolean Rings.\r\n{\\em Proceedings of ISSAC 2008}, ACM Press, 2008, pp.95--102.\r\n\r\n\\bibitem{PaCS'08}\r\nV.P.Gerdt and M.V.Zinin. Involutive Method for Computing \\Gr Bases over $F_2$.\r\n{\\em Programming and Computer Software}, Vol.34, No. 4, 2008, 191--203.\r\n\r\n\\bibitem{PCA'09}\r\nVladimir Gerdt, Mikhail Zinin and Yuri Blinkov. On computation of Boolean involutive bases,\r\nProceedings of International Conference Polynomial Computer Algebra 2009, pp. 17-24\r\n(International Euler Institute, April 7-12, 2009, St. Peterburg, Russia)\r\n\r\n\r\n\\end{thebibliography}\r\n\r\n\\end{document}\r\n\r\n", "meta": {"hexsha": "e826cdeb333911965b545bbaaa28b4313824c56f", "size": 11356, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "packages/bibasis/bibasis.tex", "max_stars_repo_name": "arthurcnorman/general", "max_stars_repo_head_hexsha": "5e8fef0cc7999fa8ab75d8fdf79ad5488047282b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "packages/bibasis/bibasis.tex", "max_issues_repo_name": "arthurcnorman/general", "max_issues_repo_head_hexsha": "5e8fef0cc7999fa8ab75d8fdf79ad5488047282b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "packages/bibasis/bibasis.tex", "max_forks_repo_name": "arthurcnorman/general", "max_forks_repo_head_hexsha": "5e8fef0cc7999fa8ab75d8fdf79ad5488047282b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6258503401, "max_line_length": 143, "alphanum_fraction": 0.6971644945, "num_tokens": 3682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.3318968252949478}}
{"text": "\n\\section{Metatheory}\n\nIn this section we present several properties that are formally verified.\nFor the declarative system, the typing subsumption and subtyping\ntransitivity lemmas are discussed in detail.\nThe algorithmic system is proven to be sound with respect\nto the declarative system via a transfer relation.\nA partial completeness theorem is shown under the rank-1 restriction.\nWe then briefly describe the challenges we face when proving termination.\nLastly, proof statistics of Abella are discussed.\n\n\\subsection{Declarative Properties}\\label{sec:meta:decl}\n\n\\paragraph{The Typing Subsumption Lemma.}\nAn important desired property for a type system is \\emph{checking subsumption},\nwhich says that any expression $e$ can\ncheck against $B$ if $e$ checks against $A$ and $A \\le B$.\nSince our bidirectional type system defines the checking mode, inference mode and\napplication inference mode mutually,\nwe formalize the generalized \\emph{typing subsumption}.\n\nFirst of all, we give the definition of worklist subtyping,\nwhich is used to further generalize the typing subsumption lemma.\nThis is necessary because rules like $\\mathtt{Decl{\\to}I}$\nwill push the argument type $A$ into the context,\nthus when checking against a super type of $A \\to B$, say $C \\to D$,\nwill cause the bind of $x$ in the context to a subtype of $A$ (since $C \\le A$).\n\n\\begin{definition}[Worklist Subtyping]\n    Worklist subtyping compares the type of variables bound in the worklist.\n    $\\Psi <: \\Psi'$ iff each binding in $\\Psi$ is converted to one with a super type.\n    \\begin{gather*}\n        \\inferrule*[right=$\\mathtt{<:nil}$]\n            {~}{\\cdot <: \\cdot}\n        \\qquad\n        \\inferrule*[right=$\\mathtt{<:ty}$]\n            {\\Psi <: \\Psi'}\n            {\\Psi, a <: \\Psi', a}\n        \\\\\n        \\inferrule*[right=$\\mathtt{<:of}$]\n            {\\Psi' \\vdash A \\le B \\\\ \\Psi <: \\Psi'}\n            {\\Psi, x:A <: \\Psi', x:B}\n        \\qquad\n        \\inferrule*[right=$\\mathtt{<:\\omega}$]\n            {\\Psi <: \\Psi'}\n            {\\Psi \\Vdash \\jg <: \\Psi' \\Vdash \\jg}\n    \\end{gather*}\n\\end{definition}\n\nA basic property of worklist subtyping is that they acts similarly when\ndealing with subtyping between well-formed types.\n\\begin{lemma}[Worklist Subtyping Equivalence]~\\\\\n    Given $\\Psi <: \\Psi'$, $\\Psi \\vdash A \\le B \\Longleftrightarrow \\Psi' \\vdash A \\le B$.\n\\end{lemma}\n\nFinally, we give the statement of typing subsumption lemma,\nwhich is generalized by the worklist subtyping relation.\n\n\\begin{lemma}[Typing Subsumption]\n    Given $\\Psi <: \\Psi'$,\n    \\begin{enumerate}[1)]\n        \\item If $\\Psi' \\vdash e \\Lto A$ and $\\Psi' \\vdash A \\le B$, then $\\Psi \\vdash e \\Lto B$;\n        \\item If $\\Psi' \\vdash e \\To A$, then $\\exists B$ s.t. $\\Psi' \\vdash B \\le A$ and $\\Psi \\vdash e \\To B$.\n        \\item If $\\Psi' \\vdash \\appInf{C}{e}{A}$ and $\\Psi' \\vdash D \\le C$, then\n            $\\exists B$ s.t. $\\Psi' \\vdash B \\le A$ and $\\Psi \\vdash \\appInf{D}{e}{B}$.\n    \\end{enumerate}\n\\end{lemma}\n\n\\begin{proof}\n    By induction on the following size measure (lexicographical order on a 3-tuple):\n    \\begin{itemize}\n        \\item Checking ($e \\Lto A$): $\\langle |e|, 1, |A|_\\forall + |B|_\\forall \\rangle$\n        \\item Inference ($e \\To A$): $\\langle |e|, 0, 0 \\rangle$\n        \\item Application inference ($\\appInf{A}{e}{C}$): $\\langle |e|, 2, |C|_\\forall + |D|_\\forall \\rangle$\n    \\end{itemize}\n    Most of the cases are straightforward.\n    When rule $\\mathtt{{\\le}\\forall L}$ is applied for the subtyping predicate\n    like $\\Psi' \\vdash A \\le B$,\n    a mono-type substitution is performed on $\\all A$,\n    resulting in $[\\tau/a]A$.\n    Since $\\tau$ is a mono-type, the result type reduces the number of $\\forall$'s,\n    and thus reduces the size measure.\n\\end{proof}\n\nInterestingly, the two new declarative rules\n$\\mathtt{Decl\\top}$ and $\\mathtt{Decl{\\bot}App}$ are\ndiscovered when we were trying to prove the property instead of\nbefore exploring the meta-theory.\nGiven the typing and subtyping judgments $\\Psi \\vdash e \\Lto A$ and $\\Psi \\vdash A \\le \\top$,\nwe should derive $\\Psi \\vdash e \\Lto \\top$ from the lemma,\ntherefore Rule $\\mathtt{Decl\\top}$ is required,\nsaying that any expression can be checked against the top type.\nNote that here we do not include the condition $e \\Lto A$,\nsince we may elaborate the term to the top term\nwhich no longer refers to the original term.\n\nSimilarly, the most general type $\\bot$,\nbeing able to convert to any type due to Rule $\\mathtt{{\\le}Bot}$,\ncan be converted to any function type,\nor simply the most general one $\\top \\to \\bot$,\nwhich accepts any input and returns the $\\bot$ type,\nresulting in the derivation $\\Psi \\vdash \\appInf{\\bot}{e}{\\bot}$.\nFrom the lemma we can also derive that by\n$\\Psi \\vdash \\appInf{C}{e}{A}$, $\\Psi \\vdash \\bot \\le C$ and $\\Psi \\vdash \\bot \\le A$.\n\nWith the addition of Rules $\\mathtt{Decl\\top}$ and $\\mathtt{Decl{\\bot}App}$,\nwe can prove the typing subsumption lemma.\nTo the best of the author's knowledge,\nthey are the minimal set of rules that make the lemma hold.\n\n\n\\paragraph{Transitivity of Subtyping}\n\nThe transitivity lemma for declarative subtyping is a commonly expected property.\nThe proof depends on the following subtyping derivation size relation and an auxiliary lemma.\n\n\\begin{definition}[Subtyping Derivation Size]\n    \\begin{gather*}\n        \\begin{aligned}\n            |1 \\le 1| &= 0\\\\\n            |a \\le a| &= 0\\\\\n            |A \\le \\top| &= 0\\\\\n            |\\bot \\le B| &= 0\\\\\n            |A_1 \\to A_2 \\le B_1 \\to B_2| &= |B_1 \\le A_1| + |A_2 \\le B_2| + 1\\\\\n            |\\all A \\le B| &= |[\\tau/a]A \\le B| + 1\\\\\n            |A \\le \\all B| &= |A \\le B| + 1\n        \\end{aligned}\n    \\end{gather*}\n\\end{definition}\n\n\\begin{lemma}[Monotype Subtyping Substitution]\n    If $\\Psi \\vdash \\tau$ and $\\Psi, a, \\Psi_R \\vdash A \\le B$, then\n    $\\Psi, [\\tau/a]\\Psi_R \\vdash [\\tau/a]A \\le [\\tau/a]B$.\n\\end{lemma}\n\n\\begin{proof}\n    A routine induction on the subtyping relation $\\Psi, a, \\Psi_R \\vdash A \\le B$\n    finishes the proof.\n\\end{proof}\n\n\\begin{corollary}[Monotype Subtyping Substitution for Type Variables]\n    \\label{cor:subtyping_subst_mono}\n    If $\\Psi \\vdash \\tau$ and $\\Psi, a \\vdash A \\le B$, then\n    $\\Psi \\vdash [\\tau/a]A \\le [\\tau/a]B$.\n\\end{corollary}\n\nThe above lemma and corollary reveal the fact\nthat a type variable occurred in the subtyping relation\nrepresents an \\emph{arbitrary} well-formed monotype.\nAnd it also explains the difference in treatment of polymorphic types between\nRules $\\mathtt{{\\le}{\\forall}L}$ and $\\mathtt{{\\le}{\\forall}R}$:\nRule $\\mathtt{{\\le}{\\forall}R}$ is in fact equivalent to:\n$$\n\\inferrule*[right=$\\mathtt{{\\le}{\\forall}R'}$]\n    {\\forall \\tau \\text{ s.t. } \\Psi \\vdash \\tau \\Longrightarrow \\Psi \\vdash A \\le [\\tau/b]B}\n    {\\Psi \\vdash A \\le \\all[b] B}\n$$\n\nFinally, with the size measure defined and required lemma proven,\nwe can obtain the transitivity lemma for declarative subtyping.\n\n\\begin{lemma}[Subtyping Transitivity]\n    If $\\Psi \\vdash A \\le B$ and $\\Psi \\vdash B \\le C$ then\n    $\\Psi \\vdash A \\le C$.\n\\end{lemma}\n\n\\begin{proof}\n    Induction on the lexicographical order defined by\n    $\\langle |B|_\\forall, |A \\le B| + |B \\le C| \\rangle$.\n    Most cases preserve the first element of the size measures $|B|_\\forall$,\n    and are relatively easy to prove.\n    The difficult case is when $B$ is a polymorphic type,\n    when the conditions are $\\Psi \\vdash A \\le \\all B$ and $\\Psi \\vdash \\all B \\le C$.\n    They are derived through rules $\\mathtt{{\\le}\\forall L}$ and\n    $\\mathtt{{\\le}\\forall R}$, respectively.\n    Therefore, we have $\\Psi, a \\vdash A \\le B$ and $\\Psi \\vdash [\\tau/a] B \\le C$.\n    To exploit the induction hypothesis, the contexts should be unified.\n    By Corollary~\\ref{cor:subtyping_subst_mono}, $\\Psi \\vdash A \\le [\\tau/a]B$.\n    Notice that the freshness condition is implicit for rule $\\mathtt{{\\le}\\forall L}$.\n    Clearly, $|[\\tau/a]B|_\\forall < |\\all B|_\\forall$, i.e. the first size measure decreases.\n    By induction hypothesis we get $\\Psi \\vdash A \\le C$ and finish this case.\n\\end{proof}\n\n\\subsection{Transfer}\n\n\\begin{figure}[t]\n    \\begin{gather*}\n    \\begin{aligned}\n    \\text{Declarative worklist}\\qquad&\\Om &::=&\\quad \\nil \\mid \\Om, a \\mid \\Om, x: A \\mid \\Om \\Vdash \\jg\n    \\end{aligned}\n    \\end{gather*}\n    \\hfill \\framebox{$\\Gm \\sto \\Om$} \\hfill $\\Gm$ instantiates to $\\Om$.\n    \\begin{gather*}\n    \\inferrule*[right=$\\mathtt{{\\sto}}\\Om$]\n    {~}\n    {\\Om \\sto \\Om}\n    \\quad\n    \\inferrule*[right=$\\mathtt{{\\sto}\\al}$]\n    {\\Om\\vdash\\tau \\\\ \\Om,[\\tau/\\al]\\Gm \\sto \\Om}\n    {\\Om,\\al,\\Gm \\sto \\Om}\n    \\end{gather*}\n    \\Description{Declarative Worklists and Instantiation}\n    \\caption{Declarative Worklists and Instantiation}\n    \\label{fig:top:trans}\n\\end{figure}\n\nFollow the approach of Section~\\ref{sec:metatheory},\nthe transfer relation and the declarative instantiation relation are defined\nin Figure~\\ref{fig:top:trans}.\n\nSimilarly, Lemmas~\\ref{lem:top:insert} and \\ref{lem:top:extract}\ngeneralizing Rule $\\mathtt{{\\sto}\\al}$ hold as well.\n\n\\begin{lemma}[Insert]\\label{lem:top:insert}\nIf $\\Gm_L, [\\tau/\\al]\\Gm_R \\sto \\Om$ and $\\Gm_L\\vdash \\tau$\n, then $\\Gm_L, \\al, \\Gm_R \\sto \\Om$.\n\\end{lemma}\n\\begin{lemma}[Extract]\\label{lem:top:extract}\nIf $\\Gm_L, \\al, \\Gm_R \\sto \\Om$\n, then there exists $\\tau$ s.t. $\\Gm_L\\vdash\\tau$ and $\\Gm_L, [\\tau/\\al]\\Gm_R \\sto \\Om$.\n\\end{lemma}\n\n\\begin{figure}[ht]\n\\hfill \\framebox{$\\|\\Om\\|$} \\hfill Judgment erasure.\n\\begin{gather*}\n\\begin{aligned}\n\\|\\nil\\| &= \\nil\\\\\n\\|\\Om,a\\| &= \\|\\Om\\|, a\\\\\n\\|\\Om,x:A\\| &= \\|\\Om\\|, x:A\\\\\n\\|\\Om\\Vdash\\jg\\| &= \\|\\Om\\|\n\\end{aligned}\n\\end{gather*}\n\n\\hfill \\framebox{$\\Om \\rto \\Om'$} \\hfill Declarative transfer.\n\\begin{gather*}\n\\begin{aligned}\n\\Om,a &\\rto \\Om \\\\  \\Om,x:A & \\rto \\Om\\\\\n\\Om\\Vdash A\\le B &\\rto \\Om &\\text{ when } \\|\\Om\\| \\vdash A\\le B\\\\\n\\Om\\Vdash e\\Lto A &\\rto \\Om & \\text{ when } \\|\\Om\\| \\vdash e\\Lto A\\\\\n\\Om\\Vdash e\\To_a \\jg &\\rto \\Om\\Vdash[A/a]\\jg & \\text{ when } \\|\\Om\\| \\vdash e\\To A\\\\\n\\Om\\Vdash \\appInfAlg{A}{e} &\\rto \\Om\\Vdash[C/a]\\jg & \\text{ when } \\|\\Om\\| \\vdash \\appInf{A}{e}{C}\\\\\n\\end{aligned}\n\\end{gather*}\n\\Description{Declarative Transfer}\n\\caption{Declarative Transfer}\n\\label{fig:top:decl:worklist}\n\\end{figure}\n\nFigure~\\ref{fig:top:decl:worklist} defines a relation $\\Om \\rto \\Om'$,\nchecking that every judgment entry in the worklist\nholds using a corresponding declarative judgment.\n\n\\subsection{Soundness}\n\nOur algorithm is sound with respect to the declarative system.\nFor any worklist $\\Gm$ that reduces successfully,\nthere is a valid instantiation $\\Om$ that transfers all judgments\nto the declarative system.\n\\begin{theorem}[Soundness]\nIf \\emph{wf }$\\Gm$ and $\\Gm \\redto \\nil$,\nthen there exists $\\Om$ s.t. $\\Gm \\sto \\Om$ and $\\Om \\redto \\nil$.\n\\end{theorem}\n\nSoundness is a basic desired property of a type inference algorithm,\nwhich ensures that the algorithm is always producing\nvalid declarative derivations when the judgments are accepted.\n\n\\subsection{Partial Completeness of Subtyping: Rank-1 Restriction}\n\nThe algorithm is incomplete due to the subtyping rules 14, 15, 20 and 21.\nHowever, subtyping is complete with respect to the declarative system in a rank-1 setting.\n\n\\paragraph{Declarative Rank-1 Restriction}\n\nRank-1 types are also named type schemes in the Hindley-Milner type system.\n$$\\begin{aligned}\n    \\text{Declarative Type Schemes}\\qquad&\\sigma &::=&\\quad \\all \\sigma \\mid \\tau\\\\\n\\end{aligned}$$\nIn other words, the universal quantifiers only appear in the top level\nof all polymorphic types.\n\nFor declarative subtyping, a judgment must be of form $\\sigma_1 \\le \\sigma_2$.\n\n\\subsection{Algorithmic Rank-1 Restriction (Partial Completeness)}\n\nThe algorithmic mono-types and type schemes are defined as following:\n$$\\begin{aligned}\n    \\text{Algorithmic Mono-types}\\qquad&\\tau_A &::=&\\quad\n        1 \\mid \\top \\mid \\bot \\mid a \\mid A\\to B \\mid \\al\\\\\n    \\text{Algorithmic Type Schemes}\\qquad&\\sigma_A &::=&\\quad \\all \\sigma_A \\mid \\tau_A\\\\\n\\end{aligned}$$\n\nStarting from the declarative judgment $\\sigma_1 \\le \\sigma_2$,\nthe algorithmic derivation might involve different other kinds of judgments.\nThe following derivation, as an example, shows how a rank-1 judgment derives.\n\n$$\\begin{aligned}\n           & \\cdot \\Vdash \\all a \\to a \\le \\all[b] (b \\to b) \\to (b \\to b)\\\\\n    \\rrule{8} & b \\Vdash \\all a \\to a \\le (b \\to b) \\to (b \\to b)\\\\\n    \\rrule{7} & b, \\al \\Vdash \\al \\to \\al \\le (b \\to b) \\to (b \\to b)\\\\\n    \\rrule{6} & b, \\al \\Vdash \\al \\le b \\to b \\Vdash b \\to b \\le \\al\\\\\n    \\rrule{} & \\cdots\n\\end{aligned}$$\n\nIn this derivation, we begin from a judgment of the form $\\sigma \\le \\sigma$.\nAfter Rule 8 is applied, the judgment becomes $\\sigma \\le \\tau$,\nsince the right-hand-side polymorphic type is reduced to a declarative mono-type.\nThen, Rule 7 introduces existential variables to the left-hand-side,\nresulting in a judgment like $\\tau_A \\le \\tau$,\nor $\\sigma_A \\le \\tau$ in a more general case.\nFinally, Rule 6 breaks a judgment between functions into two sub-judgments,\nwhich swaps the positions of the argument types\nand creates a judgment like $\\tau \\le \\tau_A$.\nNotice that $\\sigma_A$ is not possible to occur to the right\nbecause the function type may not contain any polymorphic types as its argument type.\n\nAfter a detailed analysis on the judgments derivations,\nwe found that the only possible judgments that a rank-1 declarative subtyping judgment\nmight step to belong to the following two categories:\n$$\\sigma_A \\le \\sigma \\quad\\text{or}\\quad \\tau \\le \\sigma_A$$\nAll the possible judgment types shown above fall into these categories.\nFor example, $\\tau_A \\le \\tau$ is a special form of $\\sigma_A \\le \\sigma$,\nand $\\tau \\le \\tau_A$ belongs to $\\tau \\le \\sigma_A$.\n\nAn interesting observation is that $\\al \\le \\bt$ does not belong to either category,\nneither does $\\al \\le A \\to B$ when $\\al \\in \\text{FV}(A \\to B)$.\nTherefore, in the rank-1 setting, both cases of incompleteness never occur,\nand our algorithm is complete.\n\n\\begin{theorem}[Completeness of Rank-1 Subtyping]\n    Given $\\Psi \\vdash \\sigma_1 \\le \\sigma_2$,\n    \\begin{itemize}\n        \\item If $\\Gm \\Vdash \\sigma_A \\le \\sigma \\sto \\Psi \\Vdash \\sigma_1 \\le \\sigma_2$\n            \\\\then $\\Gm \\Vdash \\sigma_A \\le \\sigma \\redto \\nil$;\n        \\item If $\\Gm \\Vdash \\tau \\le \\sigma_A \\sto \\Psi \\Vdash \\sigma_1 \\le \\sigma_2$\n            \\\\then $\\Gm \\Vdash \\tau \\le \\sigma_A \\redto \\nil$.\n    \\end{itemize}\n\\end{theorem}\n\n\\subsection{Termination}\n\nThe measure used in Chapter~\\ref{chap:ICFP} no longer works because subtyping judgments like\n$$\\al \\le \\bot \\to \\top$$\ncause $\\al$ to split into $\\al[1] \\to \\al[2]$, without solving any part of it,\nresulting in an increased number of existential variables\nand possibly increased complexity of the worklist through the size-increasing substitution\n$\\{\\al := \\al[1] \\to \\al[2]\\}$.\n\nWe have performed a large set of tests on generated subtyping judgments\nthat are consist of algorithmic monotypes,\nand all judgments terminated within a reasonable number of derivation depth.\nUnfortunately, we have not yet find any formal proof for the termination statement.\n\nIn some theoretical point of view, an algorithm should terminate on any valid input.\nHowever, there are programs that do not terminate,\nwhich we also consider them as an ``algorithm''.\nTherefore, we would still call our reduction procedure an algorithm,\nalthough the termination argument has not been formally proven.\n\n\n\\subsection{Formalization in the Abella Proof Assistant}\n\nWe have chosen the Abella (v2.0.7-dev\n\\footnote{We use a forked version \\url{https://github.com/JimmyZJX/abella} by only enhancing the Abella prover with a handy\n``applys'' tactic.}\n) proof assistant~\\citep{AbellaDesc} to develop our formalization.\nEquipped with HOAS, Abella eases the formalization and proof tasks a lot\ncompared with various libraries in Coq.\nAdditionally, our algorithm heavily uses eager substitutions,\nand Abella greatly simplifies relevant proofs thanks to its built-in\nsubstitution representation and higher-order unification algorithms.\n\nThe reader may find the source code of the proof at \\url{https://github.com/JimmyZJX/Dissertation/tree/main/src/Subtyping}.\n\n\\paragraph{Statistics of the Proof}\nThe proof script consists of 7,301 lines of Abella code with a total of\n48 definitions and 592 theorems.\nFigure~\\ref{table:top:proof_statistics} briefly summarizes the contents of each file.\nThe files are linearly dependent due to the limitations of Abella.\n\n\\begin{table}[t]\n    \\renewcommand{\\arraystretch}{1.2}\n    \\caption{Statistics for the proof scripts}\n    \\centering\\begin{tabular}{@{}lrrl@{}}\n    \\toprule\n        File(s) & LOC & \\#Thm & Description\\\\\n    \\midrule\n        olist.thm, nat.thm  &   311 & 57  & Basic data structures\\\\\n        typing.thm          &   273 & 7   & Declarative \\& algorithmic system, debug examples\\\\\n        decl.thm            &   241 & 33  & Basic declarative properties\\\\\n        order.thm           &   274 & 27  & The $|\\cdot|_\\forall$ measure; decl. subtyping strengthening\\\\\n        alg.thm             &   699 & 82  & Basic algorithmic properties\\\\\n        trans.thm           &   635 & 53  & \\makecell[l]{Worklist instantiation and declarative transfer;\\\\\n                                Lemmas~\\ref{lem:insert}, \\ref{lem:extract}}\\\\\n        declTyping.thm      & 1,087 & 76  & \\makecell[l]{Non-overlapping declarative system; \\\\\n                                Lemmas~\\ref{lem:inv_allR}, \\ref{lem:inv_chkAll},\n                                    \\ref{lem:inv_chkLam}, \\ref{lem:subsumption}}\\\\\n        soundness.thm       & 1,206 & 81  & Soundness theorem; aux. lemmas on transfer\\\\\n        dcl.thm             &   417 & 12  & Non-overlapping declarative worklist \\\\\n        scheme.thm          & 1,113 & 98  &\n                                Type scheme (rank-1 restriction)\\\\\n        completeness.thm    & 1,045 & 63  &\n                                Completeness theorem; aux. lemmas and relations\\\\\n    \\midrule\n        \\emph{Total}        & 7,301 & 592 & (48 definitions in total)\\\\\n    \\bottomrule\n    \\end{tabular}\n    \\label{table:top:proof_statistics}\n\\end{table}\n\n\n\n", "meta": {"hexsha": "1b6e4c531ce0718ffe233f9f53cd5fe2cb5cd92b", "size": 18129, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Sources/Top/Metatheory.tex", "max_stars_repo_name": "JimmyZJX/Dissertation", "max_stars_repo_head_hexsha": "823bfe90e4b5cc5b7d90c045670bdf4b087877cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sources/Top/Metatheory.tex", "max_issues_repo_name": "JimmyZJX/Dissertation", "max_issues_repo_head_hexsha": "823bfe90e4b5cc5b7d90c045670bdf4b087877cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sources/Top/Metatheory.tex", "max_forks_repo_name": "JimmyZJX/Dissertation", "max_forks_repo_head_hexsha": "823bfe90e4b5cc5b7d90c045670bdf4b087877cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.7898550725, "max_line_length": 123, "alphanum_fraction": 0.6744994208, "num_tokens": 5475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.33189682529494774}}
{"text": "\\documentclass[10pt]{article}\n\n\\usepackage{url}\n\\usepackage{proof}\n\\usepackage{fullpage}\n\n%% ODER: format ==         = \"\\mathrel{==}\"\n%% ODER: format /=         = \"\\neq \"\n\\makeatletter\n\n\\usepackage{amstext}\n\\usepackage{amssymb}\n\\usepackage{stmaryrd}\n\\DeclareFontFamily{OT1}{cmtex}{}\n\\DeclareFontShape{OT1}{cmtex}{m}{n}\n  {<5><6><7><8>cmtex8\n   <9>cmtex9\n   <10><10.95><12><14.4><17.28><20.74><24.88>cmtex10}{}\n\\DeclareFontShape{OT1}{cmtex}{m}{it}\n  {<-> ssub * cmtt/m/it}{}\n\\newcommand{\\texfamily}{\\fontfamily{cmtex}\\selectfont}\n\\DeclareFontShape{OT1}{cmtt}{bx}{n}\n  {<5><6><7><8>cmtt8\n   <9>cmbtt9\n   <10><10.95><12><14.4><17.28><20.74><24.88>cmbtt10}{}\n\\DeclareFontShape{OT1}{cmtex}{bx}{n}\n  {<-> ssub * cmtt/bx/n}{}\n\\newcommand{\\tex}[1]{\\text{\\texfamily#1}}\t% NEU\n\n\\newcommand{\\Sp}{\\hskip.33334em\\relax}\n\n\\newlength{\\lwidth}\\setlength{\\lwidth}{4.5cm}\n\\newlength{\\cwidth}\\setlength{\\cwidth}{8mm} % 3mm\n\n\\newcommand{\\Conid}[1]{\\mathit{#1}}\n\\newcommand{\\Varid}[1]{\\mathit{#1}}\n\\newcommand{\\anonymous}{\\kern0.06em \\vbox{\\hrule\\@width.5em}}\n\\newcommand{\\plus}{\\mathbin{+\\!\\!\\!+}}\n\\newcommand{\\bind}{\\mathbin{>\\!\\!\\!>\\mkern-6.7mu=}}\n\\newcommand{\\sequ}{\\mathbin{>\\!\\!\\!>}}\n\\renewcommand{\\leq}{\\leqslant}\n\\renewcommand{\\geq}{\\geqslant}\n\\newcommand{\\NB}{\\textbf{NB}}\n\\newcommand{\\Todo}[1]{$\\langle$\\textbf{To do:}~#1$\\rangle$}\n\n\\makeatother\n\\bibliographystyle{plain}\n\n\\parskip=\\medskipamount\n\\parindent=0pt\n\n\\newcommand{\\isa}{\\ensuremath{\\; {:}{:}{=} \\;}}\n\\newcommand{\\ora}{\\ensuremath{\\;\\mid\\;}}\n\\newcommand{\\IF}{\\ensuremath{\\mathtt{ if \\;}}}\n\\newcommand{\\THEN}{\\ensuremath{\\mathtt{\\; then \\;}}}\n\\newcommand{\\ELSE}{\\ensuremath{\\mathtt{\\; else \\;}}}\n\\newcommand{\\TRUE}{\\ensuremath{\\mathtt{ true \\;}}}\n\\newcommand{\\FALSE}{\\ensuremath{\\mathtt{\\; false \\;}}}\n\\newcommand{\\BOOL}{\\ensuremath{\\mathtt{\\; Bool \\;}}}\n\\newcommand{\\INT}{\\ensuremath{\\mathtt{\\; Int \\;}}}\n\\newcommand{\\PLUS}{\\ensuremath{\\mathtt{ plus \\;}}}\n\\newcommand{\\MINUS}{\\ensuremath{\\mathtt{ sub \\;}}}\n\n\\title{Monadic Typed Lambda Calculus Interpreter}\n\\author{Perry Alexander \\\\\n  ITTC - The University of Kansas \\\\\n  2335 Irving Hill Rd \\\\\n  Lawrence, KS 66045 \\\\\n  \\texttt{alex@ittc.ku.edu}}\n\n\\begin{document}\n\n\\maketitle\n\n\\section{Introduction}\n\nThe objective of this project is to write an interpreter for an\nextended simply typed lambda calculus ($\\lambda_\\rightarrow$) based on\ndefinitions from \\emph{Types and Programming Languages}~\\cite{Pie02a},\nChapter 8, Figure 8-1 and Chapter 9, Figure 9-1.  We will enhance the\nbasic language to include integers and integer sum and difference in\naddition to the basic operations.  The definition of the abstract\nsyntax provides the following forms for $\\lambda_\\rightarrow$ terms,\nvalues and types in:\n\n\\begin{eqnarray*}\n  t & \\isa & x \\ora v \\ora \\lambda x:T.t \\ora t\\; t \\ora \\PLUS t\\; t \\ora \\MINUS t\\;\n  t \\\\\n  v & \\isa & \\lambda x:T.t \\ora \\mathcal{I} \\ora \\mathtt{true} \\ora \\mathtt{false}\\\\\n  T & \\isa & \\BOOL \\ora \\INT \\ora T \\rightarrow T\n\\end{eqnarray*}\n\nThe definition for call-by-value evaluation provides the following\nevaluation rules that will define the evaluation function:\n\n\\[\\vcenter{\\infer[\\textsc{E-App1}]\n  {t_1 t_2 \\longrightarrow t_1^{'} t_2}\n  {t_1\\longrightarrow t_1^{'}}}\\]\n\n\\[\\vcenter{\\infer[\\textsc{E-App2}]\n  {t_1 t_2 \\longrightarrow t_1 t_2^{'}}\n  {t_2\\longrightarrow t_2^{'}}}\\]\n\n\\[\\vcenter{\\infer[\\textsc{E-AppAbs}]\n  {(\\lambda x:T.t_{12})v_2 \\longrightarrow [x\\rightarrow v_2]t_{12}}\n  {}}\\]\n\n\\[\\vcenter{\\infer[\\textsc{E-IfTrue}]\n  {t_2}\n  {\\IF \\TRUE \\THEN t_2 \\ELSE t_3}}\\]\n\n\\[\\vcenter{\\infer[\\textsc{E-IfFalse}]\n  {t_3}\n  {\\IF \\FALSE \\THEN t_2 \\ELSE t_3}}\\]\n\n\\[\\vcenter{\\infer[\\textsc{E-If}]\n  {\\IF t_1 \\THEN t_2 \\ELSE t_3 \\rightarrow \\IF t_1^{'} \\THEN t_2 \\ELSE t_3}\n  {t_1\\rightarrow t_1^{'}}}\n\\]\n\n\\[\\vcenter{\\infer[\\textsc{E-Plus1}]\n  {\\PLUS t_1^{'}\\; t_2^{'}}\n  {t_1\\rightarrow t_1^{'} & t_2\\rightarrow t_2^{'}}}\n\\]\n\n\\[\\vcenter{\\infer[\\textsc{E-Plus2}]\n  {\\mathcal{I}_1 + \\mathcal{I}_2}\n  {\\PLUS \\mathcal{I}_1\\; \\mathcal{I}_2}}\n\\]\n\n\\[\\vcenter{\\infer[\\textsc{E-Minus1}]\n  {\\MINUS t_1^{'}\\; t_2^{'}}\n  {t_1\\rightarrow t_1^{'} & t_2\\rightarrow t_2^{'}}}\n\\]\n\n\\[\\vcenter{\\infer[\\textsc{E-Minus2}]\n  {\\mathcal{I}_1 - \\mathcal{I}_2}\n  {\\MINUS \\mathcal{I}_1\\; \\mathcal{I}_2}}\n\\]\n\nwhere $\\mathcal{I}$ is any constant integer value.\n\nThe following typing rules that define the type inference function:\n\n\\[\\vcenter{\\infer[\\textsc{T-Var}]{\\Gamma\\vdash x:T}{x:T\\in\\Gamma}}\\]\n\n\\[\\vcenter{\\infer[\\textsc{T-Abs}]\n  {\\Gamma\\vdash\\lambda x:T_1.t_2 : T_1\\rightarrow T_2}\n  {\\Gamma,x:T_1\\vdash t_2 : T_2}}\n\\]\n\n\\[\\vcenter{\\infer[\\textsc{T-App}]\n  {\\Gamma\\vdash t_1\\; t_2 : T_{12}}\n  {\\Gamma\\vdash t_1 : T_{11}\\rightarrow T_{12} & \\Gamma\\vdash t_2:T_{11}}}\n\\]\n\n\\[\\vcenter{\\infer[\\textsc{T-If}]\n  {\\Gamma\\vdash \\IF t_1 \\THEN t_2 \\ELSE t_3 : T}\n  {\\Gamma\\vdash t_1 : \\BOOL & \\Gamma\\vdash t_2 : T & \\Gamma\\vdash t_3 : T}}\n\\]\n\n\\[\\vcenter{\\infer[\\textsc{T-True}]{\\TRUE:\\BOOL}{}}\\]\n\n\\[\\vcenter{\\infer[\\textsc{T-False}]{\\FALSE:\\BOOL}{}}\\]\n\n\\[\\vcenter{\\infer[\\textsc{T-Plus}]\n  {\\PLUS t_1\\; t_2 : \\INT}\n  {t_1 : \\INT & t_2 : \\INT}}\n\\]\n\n\\[\\vcenter{\\infer[\\textsc{T-Minus}]\n  {\\MINUS t_1\\; t_2 : \\INT}\n  {t_1 : \\INT & t_2 : \\INT}}\n\\]\n\nOur objective is to: (i) define a data structure for representing\n$\\lambda_\\rightarrow$ terms embodying the abstract syntax; (ii) a type\nderivation function for $\\lambda_\\rightarrow$ terms embodying the type\nrules; and (iii) an evaluation function for $\\lambda_\\rightarrow$\nterms embodying the evaluation rules.\n\n\\section{Abstract Syntax}\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{module}\\;\\Conid{TypedLambdaAST}}$\\\\\n${\\hskip2.00em\\relax\\mathbf{where}}$\\\\\n${}$\\\\\n${\\mathbf{import}\\;\\Conid{LangUtils}}$\n\\end{tabbing}\n\\subsection{Type Language}\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{data}\\;\\Conid{TyBase}\\;\\Varid{ty}\\mathrel{=}\\Conid{TyBool}\\mid \\Conid{TyInt}\\;\\mathbf{deriving}\\;(\\Conid{Eq},\\Conid{Show})}$\\\\\n${}$\\\\\n${\\mathbf{data}\\;\\Conid{TyAbs}\\;\\Varid{ty}\\mathrel{=}\\Varid{ty}\\mathbin{:->:}\\Varid{ty}\\;\\mathbf{deriving}\\;(\\Conid{Eq},\\Conid{Show})}$\\\\\n${}$\\\\\n${\\mathbf{type}\\;\\Conid{TyLangSum}\\mathrel{=}(\\Conid{Sum}\\;\\Conid{TyBase}\\;\\Conid{TyAbs})}$\\\\\n${}$\\\\\n${\\mathbf{type}\\;\\Conid{TyLang}\\mathrel{=}\\Conid{Rec}\\;\\Conid{TyLangSum}}$\\\\\n${}$\\\\\n${\\mathbf{instance}\\;\\Conid{Eq}\\;\\Conid{TyLang}\\;\\mathbf{where}}$\\\\\n${\\hskip2.00em\\relax\\Varid{x}\\equiv \\Varid{y}\\mathrel{=}(\\Varid{unS}\\;(\\Varid{out}\\;\\Varid{x}))\\equiv (\\Varid{unS}\\;(\\Varid{out}\\;\\Varid{y}))}$\n\\end{tabbing}\n\\subsection{Term Language}\n\nThe term language include Boolean values and integer values, addition\nand subtraction operators, if-then-else expressions, and lambda\nexpressions and lambda application.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{data}\\;\\Conid{TmBool}\\;\\Varid{te}\\mathrel{=}\\Conid{TmTrue}\\mid \\Conid{TmFalse}\\;\\mathbf{deriving}\\;(\\Conid{Eq},\\Conid{Show})}$\\\\\n${}$\\\\\n${\\mathbf{instance}\\;\\Conid{Functor}\\;\\Conid{TmBool}\\;\\mathbf{where}}$\\\\\n${\\hskip2.00em\\relax\\Varid{map}_{f}\\;\\Varid{f}\\;\\Conid{TmTrue}\\mathrel{=}\\Conid{TmTrue}}$\\\\\n${\\hskip2.00em\\relax\\Varid{map}_{f}\\;\\Varid{f}\\;\\Conid{TmFalse}\\mathrel{=}\\Conid{TmFalse}}$\\\\\n${}$\\\\\n${\\mathbf{data}\\;\\Conid{TmInt}\\;\\Varid{te}\\mathrel{=}\\Conid{TmConstInt}\\;\\Conid{Int}\\;\\mathbf{deriving}\\;(\\Conid{Eq},\\Conid{Show})}$\\\\\n${}$\\\\\n${\\mathbf{instance}\\;\\Conid{Functor}\\;\\Conid{TmInt}\\;\\mathbf{where}}$\\\\\n${\\hskip2.00em\\relax\\Varid{map}_{f}\\;\\Varid{f}\\;(\\Conid{TmConstInt}\\;\\Varid{x})\\mathrel{=}(\\Conid{TmConstInt}\\;\\Varid{x})}$\\\\\n${}$\\\\\n${\\mathbf{data}\\;\\Conid{TmOp}\\;\\Varid{te}\\mathrel{=}\\Conid{TmAdd}\\;\\Varid{te}\\;\\Varid{te}\\mid \\Conid{TmSub}\\;\\Varid{te}\\;\\Varid{te}\\;\\mathbf{deriving}\\;(\\Conid{Eq},\\Conid{Show})}$\\\\\n${}$\\\\\n${\\mathbf{instance}\\;\\Conid{Functor}\\;\\Conid{TmOp}\\;\\mathbf{where}}$\\\\\n${\\hskip2.00em\\relax\\Varid{map}_{f}\\;\\Varid{f}\\;(\\Conid{TmAdd}\\;\\Varid{x}\\;\\Varid{y})\\mathrel{=}(\\Conid{TmAdd}\\;(\\Varid{f}\\;\\Varid{x})\\;(\\Varid{f}\\;\\Varid{y}))}$\\\\\n${\\hskip2.00em\\relax\\Varid{map}_{f}\\;\\Varid{f}\\;(\\Conid{TmSub}\\;\\Varid{x}\\;\\Varid{y})\\mathrel{=}(\\Conid{TmSub}\\;(\\Varid{f}\\;\\Varid{x})\\;(\\Varid{f}\\;\\Varid{y}))}$\\\\\n${}$\\\\\n${\\mathbf{data}\\;\\Conid{TmIf}\\;\\Varid{te}\\mathrel{=}\\Conid{If}\\;\\Varid{te}\\;\\Varid{te}\\;\\Varid{te}\\;\\mathbf{deriving}\\;(\\Conid{Eq},\\Conid{Show})}$\\\\\n${}$\\\\\n${\\mathbf{instance}\\;\\Conid{Functor}\\;\\Conid{TmIf}\\;\\mathbf{where}}$\\\\\n${\\hskip2.00em\\relax\\Varid{map}_{f}\\;\\Varid{f}\\;(\\Conid{If}\\;\\Varid{c}\\;\\Varid{t}\\;\\Varid{e})\\mathrel{=}(\\Conid{If}\\;(\\Varid{f}\\;\\Varid{c})\\;(\\Varid{f}\\;\\Varid{t})\\;(\\Varid{f}\\;\\Varid{e}))}$\\\\\n${}$\\\\\n${\\mathbf{data}\\;\\Conid{TmVar}\\;\\Varid{t}\\mathrel{=}\\Conid{TmVar}\\;\\Conid{String}\\;\\mathbf{deriving}\\;(\\Conid{Show},\\Conid{Eq})}$\\\\\n${}$\\\\\n${\\mathbf{instance}\\;\\Conid{Functor}\\;\\Conid{TmVar}\\;\\mathbf{where}}$\\\\\n${\\hskip2.00em\\relax\\Varid{map}_{f}\\;\\Varid{f}\\;(\\Conid{TmVar}\\;\\Varid{x})\\mathrel{=}(\\Conid{TmVar}\\;\\Varid{x})}$\\\\\n${}$\\\\\n${\\mathbf{data}\\;\\Conid{TmFn}\\;\\Varid{t}\\mathrel{=}\\Conid{TmLambda}\\;\\Conid{String}\\;\\Conid{TyLang}\\;\\Varid{t}}$\\\\\n${\\phantom{\\mathbf{data}\\;\\Conid{TmFn}\\;\\Varid{t}\\mbox{}}\\mid \\Conid{TmApp}\\;\\Varid{t}\\;\\Varid{t}}$\\\\\n${\\phantom{\\mathbf{data}\\;\\Conid{TmFn}\\;\\Varid{t}\\mbox{}}\\phantom{\\mid \\mbox{}}\\mathbf{deriving}\\;(\\Conid{Eq})}$\\\\\n${}$\\\\\n${\\mathbf{instance}\\;\\Conid{Functor}\\;\\Conid{TmFn}\\;\\mathbf{where}}$\\\\\n${\\hskip2.00em\\relax\\Varid{map}_{f}\\;\\Varid{f}\\;(\\Conid{TmLambda}\\;\\Varid{s}\\;\\Varid{ty}\\;\\Varid{te})\\mathrel{=}(\\Conid{TmLambda}\\;\\Varid{s}\\;\\Varid{ty}\\;(\\Varid{f}\\;\\Varid{te}))}$\\\\\n${\\hskip2.00em\\relax\\Varid{map}_{f}\\;\\Varid{f}\\;(\\Conid{TmApp}\\;\\Varid{te1}\\;\\Varid{te2})\\mathrel{=}(\\Conid{TmApp}\\;(\\Varid{f}\\;\\Varid{te1})\\;(\\Varid{f}\\;\\Varid{te2}))}$\\\\\n${}$\\\\\n${\\mathbf{type}\\;\\Conid{TmLangSum}\\mathrel{=}(\\Conid{Sum}\\;\\Conid{TmBool}}$\\\\\n${\\phantom{\\mathbf{type}\\;\\Conid{TmLangSum}\\mathrel{=}(\\mbox{}}(\\Conid{Sum}\\;\\Conid{TmInt}}$\\\\\n${\\phantom{\\mathbf{type}\\;\\Conid{TmLangSum}\\mathrel{=}(\\mbox{}}\\phantom{(\\mbox{}}(\\Conid{Sum}\\;\\Conid{TmOp}}$\\\\\n${\\phantom{\\mathbf{type}\\;\\Conid{TmLangSum}\\mathrel{=}(\\mbox{}}\\phantom{(\\mbox{}}\\phantom{(\\mbox{}}(\\Conid{Sum}\\;\\Conid{TmIf}}$\\\\\n${\\phantom{\\mathbf{type}\\;\\Conid{TmLangSum}\\mathrel{=}(\\mbox{}}\\phantom{(\\mbox{}}\\phantom{(\\mbox{}}\\phantom{(\\mbox{}}(\\Conid{Sum}\\;\\Conid{TmVar}\\;\\Conid{TmFn})))))}$\\\\\n${}$\\\\\n${\\mathbf{type}\\;\\Conid{TmLang}\\mathrel{=}\\Conid{Rec}\\;\\Conid{TmLangSum}}$\\\\\n${}$\\\\\n${}$\\\\\n${\\Varid{toTmLang}\\mathbin{::}(\\Conid{Subsum}\\;\\Varid{f}\\;\\Conid{TmLangSum})\\Rightarrow \\Varid{f}\\;\\Conid{TmLang}\\to \\Conid{TmLang}}$\\\\\n${\\Varid{toTmLang}\\mathrel{=}\\Varid{toSum}}$\n\\end{tabbing}\n\\section{Environment}\n\nThis very simple module defines a standard environment parameterized\nover a stored type.  It is used to define both \\ensuremath{\\Varid{\\Gamma}} for the type\nchecking routine and the environment for the evaluation routine.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{module}\\;\\Conid{TypedLambdaEnv}\\;\\mathbf{where}}$\\\\\n${}$\\\\\n${\\mathbf{type}\\;\\Conid{Environment}\\;\\Varid{a}\\mathrel{=}[\\mskip1.5mu (\\Conid{String},\\Varid{a})\\mskip1.5mu]}$\\\\\n${}$\\\\\n${\\Varid{lookupEnv}\\mathbin{::}(\\Conid{Eq}\\;\\Varid{a})\\Rightarrow \\Conid{String}\\to (\\Conid{Environment}\\;\\Varid{a})\\to (\\Conid{Maybe}\\;\\Varid{a})}$\\\\\n${\\Varid{lookupEnv}\\;\\Varid{s}\\;\\Varid{e}\\mathrel{=}\\Varid{lookup}\\;\\Varid{s}\\;\\Varid{e}}$\n\\end{tabbing}\n\\section{Type Checking}\n\n\\subsection{Type Values}\n\nThese are the type values available in our language.  For the type\nlanguage, this will serve as the carrier set or value space for both\nthe type langauge and the term language under type checking.  \\ensuremath{\\Varid{\\phi}}\nfor the type language is defined over \\ensuremath{\\Varid{Ty}_{\\mathcal D}\\;\\Varid{a}} while \\ensuremath{\\Varid{\\phi}} for the term\nlanguage type checker is defined over \\ensuremath{\\Varid{T}_{n-1}\\;\\Varid{a}}.  In effect, \\ensuremath{\\Varid{\\phi}}\nevaluates the term language to a type value rather than a term value.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{module}\\;\\Conid{TypedLambdaTypesT}\\;\\mathbf{where}}$\\\\\n${\\hskip1.00em\\relax\\mathbf{import}\\;\\Conid{LangUtils}}$\\\\\n${\\hskip1.00em\\relax\\mathbf{import}\\;\\Conid{TypedLambdaAST}}$\\\\\n${\\hskip1.00em\\relax\\mathbf{import}\\;\\Conid{TypedLambdaEnv}}$\\\\\n${\\hskip1.00em\\relax\\mathbf{import}\\;\\Conid{Monad}}$\\\\\n${\\hskip1.00em\\relax\\mathbf{import}\\;\\Conid{\\Conid{Control}.\\Conid{Monad}.Error}}$\\\\\n${\\hskip1.00em\\relax\\mathbf{import}\\;\\Conid{\\Conid{Control}.\\Conid{Monad}.Reader}}$\n\\end{tabbing}\nNote that values are not interpreted, so no \\ensuremath{\\Conid{Algebra}} is needed.\nTechnically, we could make \\ensuremath{\\Varid{\\phi}\\mathrel{=}\\Varid{id}} for values, but it's not\nnecessary to think about this right now.\n\n\\subsubsection{Boolean and Integer Type Value}\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\hskip1.00em\\relax\\mathbf{data}\\;\\Conid{TyBaseVal}\\;\\Varid{ty}\\mathrel{=}\\Conid{TyBoolVal}\\mid \\Conid{TyIntVal}\\;\\mathbf{deriving}\\;(\\Conid{Eq},\\Conid{Show})}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\mathbf{instance}\\;\\Conid{Functor}\\;\\Conid{TyBaseVal}\\;\\mathbf{where}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{map}_{f}\\;\\Varid{f}\\;\\Conid{TyBoolVal}\\mathrel{=}\\Conid{TyBoolVal}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{map}_{f}\\;\\Varid{f}\\;\\Conid{TyIntVal}\\mathrel{=}\\Conid{TyIntVal}}$\n\\end{tabbing}\n\\subsubsection{Abstraction Type Value}\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\hskip1.00em\\relax\\mathbf{data}\\;\\Conid{TyAbsVal}\\;\\Varid{ty}\\mathrel{=}\\Conid{TyAbsVal}\\;\\Varid{ty}\\;\\Varid{ty}\\;\\mathbf{deriving}\\;(\\Conid{Eq},\\Conid{Show})}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\mathbf{instance}\\;\\Conid{Functor}\\;\\Conid{TyAbsVal}\\;\\mathbf{where}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{map}_{f}\\;\\Varid{f}\\;(\\Conid{TyAbsVal}\\;\\Varid{x}\\;\\Varid{y})\\mathrel{=}\\Conid{TyAbsVal}\\;(\\Varid{f}\\;\\Varid{x})\\;(\\Varid{f}\\;\\Varid{y})}$\n\\end{tabbing}\n\\subsubsection{Type Value}\n\nThe value space sum for types is the sum of the base values (integer\nand boolean) and the abstraction value and is called \\ensuremath{\\Conid{TyValSum}}.  The\nset of type values is the fixed point, \\ensuremath{\\Conid{TyVal}}.  \\ensuremath{\\Conid{TyVal}} is an\ninstance of \\ensuremath{\\Conid{Show}} and \\ensuremath{\\Conid{Eq}} to allow printing and comparing values.\n\\ensuremath{\\Varid{toTyVal}} injects elements from \\ensuremath{\\Conid{TyVal}} components into the value\nspace.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\hskip1.00em\\relax\\mathbf{type}\\;\\Conid{TyValSum}\\mathrel{=}(\\Conid{Sum}\\;\\Conid{TyBaseVal}\\;\\Conid{TyAbsVal})}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\mathbf{instance}\\;(\\Conid{Show}\\;(\\Varid{f}\\;\\Varid{a}),\\Conid{Show}\\;(\\Varid{g}\\;\\Varid{a}))\\Rightarrow \\Conid{Show}\\;(\\Conid{Sum}\\;\\Varid{f}\\;\\Varid{g}\\;\\Varid{a})\\;\\mathbf{where}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{show}\\;(\\Conid{S}\\;(\\Conid{\\Conid{Prelude}.Left}\\;\\Varid{x}))\\mathrel{=}(\\text{\\tt \\char34 (Left~\\char34}\\plus (\\Varid{show}\\;\\Varid{x})\\plus \\text{\\tt \\char34 )\\char34})}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{show}\\;(\\Conid{S}\\;(\\Conid{\\Conid{Prelude}.Right}\\;\\Varid{x}))\\mathrel{=}(\\text{\\tt \\char34 (Right~\\char34}\\plus (\\Varid{show}\\;\\Varid{x})\\plus \\text{\\tt \\char34 )\\char34})}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\mathbf{type}\\;\\Conid{TyVal}\\mathrel{=}\\Conid{Rec}\\;\\Conid{TyValSum}}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\mathbf{instance}\\;\\Conid{Show}\\;\\Conid{TyVal}\\;\\mathbf{where}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{show}\\;\\Varid{x}\\mathrel{=}\\Varid{show}\\;(\\Varid{out}\\;\\Varid{x})}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\mathbf{instance}\\;\\Conid{Eq}\\;\\Conid{TyVal}\\;\\mathbf{where}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{x}\\equiv \\Varid{y}\\mathrel{=}(\\Varid{unS}\\;(\\Varid{out}\\;\\Varid{x}))\\equiv (\\Varid{unS}\\;(\\Varid{out}\\;\\Varid{y}))}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\Varid{toTyVal}\\mathbin{::}(\\Conid{Subsum}\\;\\Varid{f}\\;\\Conid{TyValSum})\\Rightarrow \\Varid{f}\\;\\Conid{TyVal}\\to \\Conid{TyVal}}$\\\\\n${\\hskip1.00em\\relax\\Varid{toTyVal}\\mathrel{=}\\Varid{toSum}}$\n\\end{tabbing}\n\\subsection{The Reader Error Monad}\n\nThe monad used for handling the environment and error messages will be\nformed by composing a \\ensuremath{\\Conid{Reader}} with and \\ensuremath{\\Conid{ErrorMonad}}.  First we define\nthe error handling aspects, then embed the \\ensuremath{\\Conid{ErrorMonad}} in a \\ensuremath{\\Conid{Reader}}\nusing \\ensuremath{\\Conid{ReaderT}}.\n\nThe \\ensuremath{\\Conid{Either}} type constructor is already an instance of the\n\\ensuremath{\\Conid{MonadError}} class.  Thus, it is not necessary to define \\ensuremath{\\Varid{throwError}}\nand \\ensuremath{\\Varid{catchError}} explicitly for the type.  The definitions are\nincluded here for documentation, but are not loaded.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\hskip1.00em\\relax\\mathbf{instance}\\;\\Conid{MonadError}\\;(\\Conid{Either}\\;\\Varid{e})\\;\\mathbf{where}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{throwError}\\mathrel{=}\\Conid{Left}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{catchError}\\;(\\Conid{Left}\\;\\Varid{e})\\;\\Varid{handler}\\mathrel{=}\\Varid{handler}\\;\\Varid{e}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{catchError}\\;\\Varid{a}\\;\\anonymous \\mathrel{=}\\Varid{a}}$\n\\end{tabbing}\n\\ensuremath{\\Conid{TyError}} is a simple data type for storing errors. We could simply\nstore the error string rather than create a type.  However, \\ensuremath{\\Conid{TyError}}\nserves as a placeholder if we want to do fancier things later.\n\\ensuremath{\\Conid{TyError}} is also an instance of the standard \\ensuremath{\\Conid{Error}}.\n \n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\hskip1.00em\\relax\\mathbf{data}\\;\\Conid{TyError}\\mathrel{=}\\Conid{Err}\\;\\Conid{String}\\;\\mathbf{deriving}\\;(\\Conid{Show},\\Conid{Eq})}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\mathbf{instance}\\;\\Conid{Error}\\;\\Conid{TyError}\\;\\mathbf{where}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{noMsg}\\mathrel{=}\\Conid{Err}\\;\\text{\\tt \\char34 Type~Error\\char34}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{strMsg}\\;\\Varid{s}\\mathrel{=}\\Conid{Err}\\;\\Varid{s}}$\n\\end{tabbing}\n\\ensuremath{\\Varid{\\Gamma}} defines the data structure used for a binding list.  It is\nsimply a list of \\ensuremath{(\\Conid{String},\\Conid{TyVal})} pairs.  Adding a binding appends it\nto the front of a binding list and looking up a binding is handled in\nthe canonical fashion.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\hskip1.00em\\relax\\mathbf{type}\\;\\Varid{\\Gamma}\\mathrel{=}\\Conid{Environment}\\;\\Conid{TyVal}}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\Varid{addBinding}\\mathbin{::}\\Varid{\\Gamma}\\to (\\Conid{String},\\Conid{TyVal})\\to \\Varid{\\Gamma}}$\\\\\n${\\hskip1.00em\\relax\\Varid{addBinding}\\;\\Varid{g}\\;\\Varid{t}\\mathrel{=}(\\Varid{t}\\mathbin{:}\\Varid{g})}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\Varid{lookupGamma}\\mathbin{::}\\Conid{String}\\to \\Varid{\\Gamma}\\to \\Conid{Maybe}\\;\\Conid{TyVal}}$\\\\\n${\\hskip1.00em\\relax\\Varid{lookupGamma}\\mathrel{=}\\Varid{lookup}}$\n\\end{tabbing}\n\\ensuremath{\\Conid{TyMonad}} defines the actual monad used by the type checker.  The\nsignature of \\ensuremath{\\Conid{TyMonad}} is a bit odd.  It must be a type constructor\nand thus must have one argument.  \\ensuremath{\\Conid{ReaderT}} is applied to a \\ensuremath{\\Varid{\\Gamma}}\nand \\ensuremath{(\\Conid{Either}\\;\\Conid{TyError})} leaving the last argument to \\ensuremath{\\Conid{TyError}} as an\nargument to \\ensuremath{\\Conid{TyMonad}}.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\hskip1.00em\\relax\\mathbf{type}\\;\\Conid{TyMonad}\\mathrel{=}\\Conid{ReaderT}\\;\\Varid{\\Gamma}\\;(\\Conid{Either}\\;\\Conid{TyError})\\;\\Conid{TyVal}}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\mathbf{instance}\\;\\Conid{Subtype}\\;\\Conid{TyError}\\;(\\Conid{Either}\\;\\Conid{TyError}\\;\\Conid{TyVal})\\;\\mathbf{where}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\uparrow}\\;\\Varid{x}\\mathrel{=}(\\Conid{Left}\\;\\Varid{x})}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\downarrow}\\;(\\Conid{Left}\\;\\Varid{x})\\mathrel{=}\\Conid{Just}\\;\\Varid{x}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\downarrow}\\;(\\Conid{Right}\\;\\Varid{x})\\mathrel{=}\\Conid{Nothing}}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\mathbf{instance}\\;\\Conid{Subtype}\\;\\Conid{TyVal}\\;(\\Conid{Either}\\;\\Conid{TyError}\\;\\Conid{TyVal})\\;\\mathbf{where}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\uparrow}\\;\\Varid{x}\\mathrel{=}(\\Conid{Right}\\;\\Varid{x})}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\downarrow}\\;(\\Conid{Right}\\;\\Varid{x})\\mathrel{=}\\Conid{Just}\\;\\Varid{x}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\downarrow}\\;(\\Conid{Left}\\;\\Varid{x})\\mathrel{=}\\Conid{Nothing}}$\n\\end{tabbing}\n\\subsection{Type Language}\n\nThe type language defines the language for types over the type values.\nThe type language will be \\ensuremath{\\Varid{f}} and defined over the type value space\nserving as \\ensuremath{\\Varid{a}} in an algebra definition.\n\n\\subsubsection{Base Types}\n\nThe Base Types represent integer and boolean atomic types.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\hskip1.00em\\relax\\mathbf{instance}\\;\\Conid{Functor}\\;\\Conid{TyBase}\\;\\mathbf{where}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{map}_{f}\\;\\Varid{f}\\;\\Conid{TyBool}\\mathrel{=}\\Conid{TyBool}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{map}_{f}\\;\\Varid{f}\\;\\Conid{TyInt}\\mathrel{=}\\Conid{TyInt}}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\mathbf{instance}\\;\\Conid{Algebra}\\;\\Conid{TyBase}\\;\\Conid{TyMonad}\\;\\mathbf{where}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\phi}\\;\\Conid{TyBool}\\mathrel{=}\\Varid{return}\\mathbin{\\$}\\Varid{\\uparrow}\\mathbin{\\$}\\Varid{toTyVal}\\;\\Conid{TyBoolVal}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\phi}\\;\\Conid{TyInt}\\mathrel{=}\\Varid{return}\\mathbin{\\$}\\Varid{\\uparrow}\\mathbin{\\$}\\Varid{toTyVal}\\;\\Conid{TyIntVal}}$\n\\end{tabbing}\n\\subsubsection{Abstraction Type}\n\nTypically thought of as a function type, the abstraction type\nrepresents a mapping from a range type to a domain type.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\hskip1.00em\\relax\\mathbf{instance}\\;\\Conid{Functor}\\;\\Conid{TyAbs}\\;\\mathbf{where}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{map}_{f}\\;\\Varid{f}\\;(\\Varid{x}\\mathbin{:->:}\\Varid{y})\\mathrel{=}(\\Varid{f}\\;\\Varid{x})\\mathbin{:->:}(\\Varid{f}\\;\\Varid{y})}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\mathbf{instance}\\;\\Conid{Algebra}\\;\\Conid{TyAbs}\\;\\Conid{TyMonad}\\;\\mathbf{where}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\phi}\\;(\\Varid{x}\\mathbin{:->:}\\Varid{y})\\mathrel{=}\\mathbf{do}\\;\\{\\mskip1.5mu \\Varid{x'}\\leftarrow \\Varid{x}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Varid{x}\\mathbin{:->:}\\Varid{y})\\mathrel{=}\\mathbf{do}\\;\\mbox{}};\\Varid{y'}\\leftarrow \\Varid{y}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Varid{x}\\mathbin{:->:}\\Varid{y})\\mathrel{=}\\mathbf{do}\\;\\mbox{}};\\Varid{return}\\mathbin{\\$}\\Varid{\\uparrow}\\mathbin{\\$}\\Varid{toTyVal}\\;(\\Conid{TyAbsVal}\\;\\Varid{x'}\\;\\Varid{y'})}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Varid{x}\\mathbin{:->:}\\Varid{y})\\mathrel{=}\\mathbf{do}\\;\\mbox{}}\\mskip1.5mu\\}}$\n\\end{tabbing}\nDefine a utility function for converting a type term into the type\nlanguage.  The \\ensuremath{\\Varid{evalTy}} function is a separate function for evaluating\nelements of the type language.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\hskip1.00em\\relax\\Varid{toTyLang}\\mathbin{::}(\\Conid{Subsum}\\;\\Varid{f}\\;\\Conid{TyLangSum})\\Rightarrow \\Varid{f}\\;\\Conid{TyLang}\\to \\Conid{TyLang}}$\\\\\n${\\hskip1.00em\\relax\\Varid{toTyLang}\\mathrel{=}\\Varid{toSum}}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\Varid{evalTy}\\mathbin{::}\\Conid{TyLang}\\to \\Conid{TyMonad}}$\\\\\n${\\hskip1.00em\\relax\\Varid{evalTy}\\mathrel{=}\\Varid{cata}}$\n\\end{tabbing}\n\\subsection{Type Checking Functions}\n\nThe type checking functions are defined by defining an algebra from\n\\ensuremath{\\Conid{TmLang}} to \\ensuremath{\\Conid{TyMonad}}.  Thus, \\ensuremath{\\Conid{TyMonad}} is the carrier set for the\n\\ensuremath{\\Conid{TmLang}} algebra and \\ensuremath{\\Varid{\\phi}} defines the evaluation function.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\hskip1.00em\\relax\\mathbf{instance}\\;\\Conid{Algebra}\\;\\Conid{TmBool}\\;\\Conid{TyMonad}\\;\\mathbf{where}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\phi}\\;\\Conid{TmTrue}\\mathrel{=}\\Varid{return}\\mathbin{\\$}\\Varid{\\uparrow}\\mathbin{\\$}\\Varid{toTyVal}\\;\\Conid{TyBoolVal}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\phi}\\;\\Conid{TmFalse}\\mathrel{=}\\Varid{return}\\mathbin{\\$}\\Varid{\\uparrow}\\mathbin{\\$}\\Varid{toTyVal}\\;\\Conid{TyBoolVal}}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\mathbf{instance}\\;\\Conid{Algebra}\\;\\Conid{TmInt}\\;\\Conid{TyMonad}\\;\\mathbf{where}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\phi}\\;(\\Conid{TmConstInt}\\;\\Varid{x})\\mathrel{=}\\Varid{return}\\mathbin{\\$}\\Varid{\\uparrow}\\mathbin{\\$}\\Varid{toTyVal}\\;\\Conid{TyIntVal}}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\mathbf{instance}\\;\\Conid{Algebra}\\;\\Conid{TmOp}\\;\\Conid{TyMonad}\\;\\mathbf{where}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\phi}\\;(\\Conid{TmAdd}\\;\\Varid{x}\\;\\Varid{y})\\mathrel{=}\\mathbf{do}\\;\\{\\mskip1.5mu \\Varid{x'}\\leftarrow \\Varid{x}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{TmAdd}\\;\\Varid{x}\\;\\Varid{y})\\mathrel{=}\\mathbf{do}\\;\\mbox{}};\\Varid{y'}\\leftarrow \\Varid{y}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{TmAdd}\\;\\Varid{x}\\;\\Varid{y})\\mathrel{=}\\mathbf{do}\\;\\mbox{}};\\mathbf{if}\\;(\\Varid{x'}\\equiv (\\Varid{toTyVal}\\;\\Conid{TyIntVal})\\mathrel{\\wedge}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{TmAdd}\\;\\Varid{x}\\;\\Varid{y})\\mathrel{=}\\mathbf{do}\\;\\mbox{}}\\phantom{;\\mathbf{if}\\;(\\mbox{}}\\Varid{y'}\\equiv (\\Varid{toTyVal}\\;\\Conid{TyIntVal}))}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{TmAdd}\\;\\Varid{x}\\;\\Varid{y})\\mathrel{=}\\mathbf{do}\\;\\mbox{}}\\phantom{;\\mbox{}}\\mathbf{then}\\;\\Varid{return}\\mathbin{\\$}\\Varid{\\uparrow}\\mathbin{\\$}\\Varid{toTyVal}\\;\\Conid{TyIntVal}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{TmAdd}\\;\\Varid{x}\\;\\Varid{y})\\mathrel{=}\\mathbf{do}\\;\\mbox{}}\\phantom{;\\mbox{}}\\mathbf{else}\\;\\Varid{throwError}\\mathbin{\\$}\\Conid{Err}\\;\\text{\\tt \\char34 Argument~to~Add~not~Integer\\char34}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{TmAdd}\\;\\Varid{x}\\;\\Varid{y})\\mathrel{=}\\mathbf{do}\\;\\mbox{}}\\mskip1.5mu\\}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\phi}\\;(\\Conid{TmSub}\\;\\Varid{x}\\;\\Varid{y})\\mathrel{=}\\mathbf{do}\\;\\{\\mskip1.5mu \\Varid{x'}\\leftarrow \\Varid{x}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{TmSub}\\;\\Varid{x}\\;\\Varid{y})\\mathrel{=}\\mathbf{do}\\;\\mbox{}};\\Varid{y'}\\leftarrow \\Varid{y}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{TmSub}\\;\\Varid{x}\\;\\Varid{y})\\mathrel{=}\\mathbf{do}\\;\\mbox{}};\\mathbf{if}\\;(\\Varid{x'}\\equiv (\\Varid{toTyVal}\\;\\Conid{TyIntVal})\\mathrel{\\wedge}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{TmSub}\\;\\Varid{x}\\;\\Varid{y})\\mathrel{=}\\mathbf{do}\\;\\mbox{}}\\phantom{;\\mathbf{if}\\;(\\mbox{}}\\Varid{y'}\\equiv (\\Varid{toTyVal}\\;\\Conid{TyIntVal}))}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{TmSub}\\;\\Varid{x}\\;\\Varid{y})\\mathrel{=}\\mathbf{do}\\;\\mbox{}}\\phantom{;\\mbox{}}\\mathbf{then}\\;\\Varid{return}\\mathbin{\\$}\\Varid{\\uparrow}\\mathbin{\\$}\\Varid{toTyVal}\\;\\Conid{TyIntVal}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{TmSub}\\;\\Varid{x}\\;\\Varid{y})\\mathrel{=}\\mathbf{do}\\;\\mbox{}}\\phantom{;\\mbox{}}\\mathbf{else}\\;\\Varid{throwError}\\mathbin{\\$}\\Conid{Err}\\;\\text{\\tt \\char34 Argument~to~Sub~not~Integer\\char34}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{TmSub}\\;\\Varid{x}\\;\\Varid{y})\\mathrel{=}\\mathbf{do}\\;\\mbox{}}\\mskip1.5mu\\}}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\mathbf{instance}\\;\\Conid{Algebra}\\;\\Conid{TmIf}\\;\\Conid{TyMonad}\\;\\mathbf{where}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\phi}\\;(\\Conid{If}\\;\\Varid{c}\\;\\Varid{t}\\;\\Varid{e})\\mathrel{=}\\mathbf{do}\\;\\{\\mskip1.5mu \\Varid{c'}\\leftarrow \\Varid{c}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{If}\\;\\Varid{c}\\;\\Varid{t}\\;\\Varid{e})\\mathrel{=}\\mathbf{do}\\;\\mbox{}};\\Varid{t'}\\leftarrow \\Varid{t}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{If}\\;\\Varid{c}\\;\\Varid{t}\\;\\Varid{e})\\mathrel{=}\\mathbf{do}\\;\\mbox{}};\\Varid{e'}\\leftarrow \\Varid{e}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{If}\\;\\Varid{c}\\;\\Varid{t}\\;\\Varid{e})\\mathrel{=}\\mathbf{do}\\;\\mbox{}};\\mathbf{if}\\;(\\Varid{c'}\\equiv (\\Varid{toTyVal}\\;\\Conid{TyBoolVal})\\mathrel{\\wedge}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{If}\\;\\Varid{c}\\;\\Varid{t}\\;\\Varid{e})\\mathrel{=}\\mathbf{do}\\;\\mbox{}}\\phantom{;\\mathbf{if}\\;(\\mbox{}}\\Varid{t'}\\equiv \\Varid{e'})}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{If}\\;\\Varid{c}\\;\\Varid{t}\\;\\Varid{e})\\mathrel{=}\\mathbf{do}\\;\\mbox{}}\\phantom{;\\mbox{}}\\mathbf{then}\\;\\Varid{return}\\mathbin{\\$}\\Varid{\\uparrow}\\;\\Varid{t'}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{If}\\;\\Varid{c}\\;\\Varid{t}\\;\\Varid{e})\\mathrel{=}\\mathbf{do}\\;\\mbox{}}\\phantom{;\\mbox{}}\\mathbf{else}\\;\\Varid{throwError}\\mathbin{\\$}\\Conid{Err}\\;\\text{\\tt \\char34 Either~condition~is~not~boolean~or~then~and~else~are~not~of~same~type~in~If\\char34}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{If}\\;\\Varid{c}\\;\\Varid{t}\\;\\Varid{e})\\mathrel{=}\\mathbf{do}\\;\\mbox{}}\\mskip1.5mu\\}}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\mathbf{instance}\\;\\Conid{Algebra}\\;\\Conid{TmVar}\\;\\Conid{TyMonad}\\;\\mathbf{where}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\phi}\\;(\\Conid{TmVar}\\;\\Varid{s})\\mathrel{=}\\mathbf{do}\\;\\{\\mskip1.5mu \\Varid{val}\\leftarrow \\Varid{asks}\\;(\\Varid{lookupGamma}\\;\\Varid{s})}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{TmVar}\\;\\Varid{s})\\mathrel{=}\\mathbf{do}\\;\\mbox{}};\\mathbf{case}\\;\\Varid{val}\\;\\mathbf{of}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{TmVar}\\;\\Varid{s})\\mathrel{=}\\mathbf{do}\\;\\mbox{}}\\phantom{;\\mbox{}}\\Conid{Just}\\;\\Varid{x}\\to \\Varid{return}\\;\\Varid{x}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{TmVar}\\;\\Varid{s})\\mathrel{=}\\mathbf{do}\\;\\mbox{}}\\phantom{;\\mbox{}}\\Conid{Nothing}\\to \\Varid{throwError}\\mathbin{\\$}\\Conid{Err}\\;(\\text{\\tt \\char34 Variable~\\char34}\\plus (\\Varid{s}\\plus \\text{\\tt \\char34 ~not~found\\char34}))}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{TmVar}\\;\\Varid{s})\\mathrel{=}\\mathbf{do}\\;\\mbox{}}\\mskip1.5mu\\}}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\mathbf{instance}\\;\\Conid{Algebra}\\;\\Conid{TmFn}\\;\\Conid{TyMonad}\\;\\mathbf{where}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\phi}\\;(\\Conid{TmLambda}\\;\\Varid{s}\\;\\Varid{ty}\\;\\Varid{te})\\mathrel{=}\\mathbf{do}\\;\\{\\mskip1.5mu \\Varid{\\gamma}\\leftarrow \\Varid{ask}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{TmLambda}\\;\\Varid{s}\\;\\Varid{ty}\\;\\Varid{te})\\mathrel{=}\\mathbf{do}\\;\\mbox{}};\\Varid{ty'}\\leftarrow \\Varid{evalTy}\\;\\Varid{ty}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{TmLambda}\\;\\Varid{s}\\;\\Varid{ty}\\;\\Varid{te})\\mathrel{=}\\mathbf{do}\\;\\mbox{}};\\Varid{te'}\\leftarrow \\Varid{local}\\;(\\Varid{const}\\;(\\Varid{addBinding}\\;\\Varid{\\gamma}\\;(\\Varid{s},\\Varid{ty'})))\\;\\Varid{te}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{TmLambda}\\;\\Varid{s}\\;\\Varid{ty}\\;\\Varid{te})\\mathrel{=}\\mathbf{do}\\;\\mbox{}};\\Varid{return}\\mathbin{\\$}\\Varid{\\uparrow}\\mathbin{\\$}\\Varid{toTyVal}\\;(\\Conid{TyAbsVal}\\;\\Varid{ty'}\\;\\Varid{te'})}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{TmLambda}\\;\\Varid{s}\\;\\Varid{ty}\\;\\Varid{te})\\mathrel{=}\\mathbf{do}\\;\\mbox{}}\\mskip1.5mu\\}}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\phi}\\;(\\Conid{TmApp}\\;\\Varid{te1}\\;\\Varid{te2})\\mathrel{=}\\mathbf{do}\\;\\{\\mskip1.5mu \\Varid{te1'}\\leftarrow \\Varid{te1}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{TmApp}\\;\\Varid{te1}\\;\\Varid{te2})\\mathrel{=}\\mathbf{do}\\;\\mbox{}};\\Varid{te2'}\\leftarrow \\Varid{te2}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{TmApp}\\;\\Varid{te1}\\;\\Varid{te2})\\mathrel{=}\\mathbf{do}\\;\\mbox{}};\\Varid{checkLambda}\\;(\\Varid{out}\\;\\Varid{te1'})\\;\\Varid{te2'}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{TmApp}\\;\\Varid{te1}\\;\\Varid{te2})\\mathrel{=}\\mathbf{do}\\;\\mbox{}}\\mskip1.5mu\\}}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\Varid{checkLambda}\\;\\Varid{l}\\;\\Varid{te2}\\mathrel{=}\\mathbf{case}\\;(\\Varid{\\downarrow}_{S}\\;\\Varid{l})\\;\\mathbf{of}}$\\\\\n${\\hskip1.00em\\relax\\phantom{\\Varid{checkLambda}\\;\\Varid{l}\\;\\Varid{te2}\\mathrel{=}\\mbox{}}(\\Conid{Just}\\;(\\Conid{TyAbsVal}\\;\\Varid{tty}\\;\\Varid{tte}))\\to \\mathbf{if}\\;\\Varid{tty}\\equiv \\Varid{te2}}$\\\\\n${\\hskip1.00em\\relax\\phantom{\\Varid{checkLambda}\\;\\Varid{l}\\;\\Varid{te2}\\mathrel{=}\\mbox{}}\\hskip11.00em\\relax\\mathbf{then}\\;\\Varid{return}\\mathbin{\\$}\\Varid{\\uparrow}\\;\\Varid{tte}}$\\\\\n${\\hskip1.00em\\relax\\phantom{\\Varid{checkLambda}\\;\\Varid{l}\\;\\Varid{te2}\\mathrel{=}\\mbox{}}\\hskip11.00em\\relax\\mathbf{else}\\;\\Varid{throwError}\\mathbin{\\$}\\Conid{Err}\\;\\text{\\tt \\char34 Actual~parameter~type~does~not~match~formal~parameter~type\\char34}}$\\\\\n${\\hskip1.00em\\relax\\phantom{\\Varid{checkLambda}\\;\\Varid{l}\\;\\Varid{te2}\\mathrel{=}\\mbox{}}\\anonymous \\to \\Varid{throwError}\\mathbin{\\$}\\Conid{Err}\\;\\text{\\tt \\char34 First~argument~to~application~must~be~a~Lambda\\char34}}$\n\\end{tabbing}\nThe basic \\ensuremath{\\Varid{typeof}_{\\mathcal D}} function is a catamorphism over the \\ensuremath{\\Conid{TmLang}\\;\\Conid{TyMonad}}.  The signature is specified to explicitly identify types.\nThe \\ensuremath{\\Varid{runTypeof}} function is a utilty function that evaluates the\n\\ensuremath{\\Conid{Reader}} monad.  The initial environment is empty because there are no\npredefined symbols in our language.  \\ensuremath{\\Varid{runTypeof}} should be used to\nintegrate the type checker with other language elements.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\hskip1.00em\\relax\\Varid{typeof}_{\\mathcal D}\\mathbin{::}\\Conid{TmLang}\\to \\Conid{TyMonad}}$\\\\\n${\\hskip1.00em\\relax\\Varid{typeof}_{\\mathcal D}\\mathrel{=}\\Varid{cata}}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\Varid{runTypeof}\\;\\Varid{t}\\mathrel{=}(\\Varid{runReaderT}\\;(\\Varid{typeof}_{\\mathcal D}\\;\\Varid{t})\\;[\\mskip1.5mu \\mskip1.5mu])}$\n\\end{tabbing}\n\\section{Evaluation}\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\hskip1.00em\\relax\\mathbf{module}\\;\\Conid{TypedLambdaEval}\\;\\mathbf{where}}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\mathbf{import}\\;\\Conid{LangUtils}}$\\\\\n${\\hskip1.00em\\relax\\mathbf{import}\\;\\Conid{TypedLambdaEnv}}$\\\\\n${\\hskip1.00em\\relax\\mathbf{import}\\;\\Conid{TypedLambdaAST}}$\\\\\n${\\hskip1.00em\\relax\\mathbf{import}\\;\\Conid{\\Conid{Control}.\\Conid{Monad}.Reader}}$\\\\\n${\\hskip1.00em\\relax\\mathbf{import}\\;\\Conid{\\Conid{Control}.\\Conid{Monad}.Error}}$\n\\end{tabbing}  \n\\subsection{Value Representation}\n\nThere are three values associated with the Lambda language that all\ninterpretable functions must converge to - booleans, integers, and\nlambda values.  Together, these are specified in the \\ensuremath{\\Conid{TmVal}}\nconstructed type.  Note that this type is recursive, unlike the term\nlanguage and type language specifications.  The \\texttt{Haskell} types\nused to represent primitive values are defined to be subtypes of the\naggregate \\texttt{TmVal} type.  Thus, \\ensuremath{\\Varid{\\downarrow}} and \\ensuremath{\\Varid{\\uparrow}} are define\nbetween types.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\hskip1.00em\\relax\\mathbf{data}\\;\\Conid{TmVal}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\mathrel{=}\\Conid{TmBoolVal}\\;\\Conid{Bool}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\mid \\Conid{TmIntVal}\\;\\Conid{Int}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\mid \\Conid{LambdaVal}\\;(\\Conid{TmValEnv}\\to \\Conid{TmValEnv})}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\mathbf{instance}\\;\\Conid{Show}\\;\\Conid{TmVal}\\;\\mathbf{where}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{show}\\;(\\Conid{TmBoolVal}\\;\\Varid{x})\\mathrel{=}\\Varid{show}\\;\\Varid{x}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{show}\\;(\\Conid{TmIntVal}\\;\\Varid{x})\\mathrel{=}\\Varid{show}\\;\\Varid{x}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{show}\\;(\\Conid{LambdaVal}\\;\\Varid{x})\\mathrel{=}\\text{\\tt \\char34 <Lambda~Value>\\char34}}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\mathbf{instance}\\;\\Conid{Subtype}\\;\\Conid{Bool}\\;\\Conid{TmVal}\\;\\mathbf{where}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\uparrow}\\;\\Varid{x}\\mathrel{=}(\\Conid{TmBoolVal}\\;\\Varid{x})}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\downarrow}\\;(\\Conid{TmBoolVal}\\;\\Varid{x})\\mathrel{=}\\Conid{Just}\\;\\Varid{x}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\downarrow}\\;(\\Conid{TmIntVal}\\;\\anonymous )\\mathrel{=}\\Conid{Nothing}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\downarrow}\\;(\\Conid{LambdaVal}\\;\\anonymous )\\mathrel{=}\\Conid{Nothing}}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\mathbf{instance}\\;\\Conid{Subtype}\\;\\Conid{Int}\\;\\Conid{TmVal}\\;\\mathbf{where}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\uparrow}\\;\\Varid{x}\\mathrel{=}(\\Conid{TmIntVal}\\;\\Varid{x})}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\downarrow}\\;(\\Conid{TmBoolVal}\\;\\anonymous )\\mathrel{=}\\Conid{Nothing}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\downarrow}\\;(\\Conid{TmIntVal}\\;\\Varid{x})\\mathrel{=}\\Conid{Just}\\;\\Varid{x}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\downarrow}\\;(\\Conid{LambdaVal}\\;\\anonymous )\\mathrel{=}\\Conid{Nothing}}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\mathbf{instance}\\;\\Conid{Subtype}\\;(\\Conid{TmValEnv}\\to \\Conid{TmValEnv})\\;\\Conid{TmVal}\\;\\mathbf{where}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\uparrow}\\;\\Varid{x}\\mathrel{=}(\\Conid{LambdaVal}\\;\\Varid{x})}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\downarrow}\\;(\\Conid{TmBoolVal}\\;\\anonymous )\\mathrel{=}\\Conid{Nothing}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\downarrow}\\;(\\Conid{TmIntVal}\\;\\anonymous )\\mathrel{=}\\Conid{Nothing}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\downarrow}\\;(\\Conid{LambdaVal}\\;\\Varid{x})\\mathrel{=}\\Conid{Just}\\;\\Varid{x}}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\mathbf{type}\\;\\Conid{Env}\\mathrel{=}\\Conid{Environment}\\;\\Conid{TmVal}}$\n\\end{tabbing}\n\\subsection{The Evaluator Monad}\n\nThe monad used to support evaluation is a composition of the\n\\ensuremath{\\Conid{ErrorMonad}} and the \\ensuremath{\\Conid{Reader}} monad with the \\ensuremath{\\Conid{ErrorMondad}}\nencapsulated by the \\ensuremath{\\Conid{Reader}}.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\hskip1.00em\\relax\\mathbf{data}\\;\\Conid{TmError}\\mathrel{=}\\Conid{Err}\\;\\Conid{String}\\;\\mathbf{deriving}\\;(\\Conid{Show},\\Conid{Eq})}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\mathbf{instance}\\;\\Conid{Error}\\;\\Conid{TmError}\\;\\mathbf{where}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{noMsg}\\mathrel{=}\\Conid{Err}\\;\\text{\\tt \\char34 Type~Error\\char34}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{strMsg}\\;\\Varid{s}\\mathrel{=}\\Conid{Err}\\;\\Varid{s}}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\mathbf{type}\\;\\Conid{TmValEnv}\\mathrel{=}\\Conid{ReaderT}\\;\\Conid{Env}\\;(\\Conid{Either}\\;\\Conid{TmError})\\;\\Conid{TmVal}}$\n\\end{tabbing}\n\\subsection{Expressions as Algebras}\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\hskip1.00em\\relax\\mathbf{instance}\\;\\Conid{Algebra}\\;\\Conid{TmBool}\\;\\Conid{TmValEnv}\\;\\mathbf{where}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\phi}\\;\\Conid{TmTrue}\\mathrel{=}\\Varid{return}\\mathbin{\\$}\\Varid{\\uparrow}\\;\\Conid{True}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\phi}\\;\\Conid{TmFalse}\\mathrel{=}\\Varid{return}\\mathbin{\\$}\\Varid{\\uparrow}\\;\\Conid{False}}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\mathbf{instance}\\;\\Conid{Algebra}\\;\\Conid{TmInt}\\;\\Conid{TmValEnv}\\;\\mathbf{where}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\phi}\\;(\\Conid{TmConstInt}\\;\\Varid{x})\\mathrel{=}\\Varid{return}\\mathbin{\\$}\\Varid{\\uparrow}\\;\\Varid{x}}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\mathbf{instance}\\;\\Conid{Algebra}\\;\\Conid{TmOp}\\;\\Conid{TmValEnv}\\;\\mathbf{where}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\phi}\\;(\\Conid{TmAdd}\\;\\Varid{x}\\;\\Varid{y})\\mathrel{=}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;\\mbox{}}\\mathbf{do}\\;\\{\\mskip1.5mu \\Varid{x'}\\leftarrow \\Varid{x}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;\\mbox{}}\\phantom{\\mathbf{do}\\;\\mbox{}};\\Varid{y'}\\leftarrow \\Varid{y}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;\\mbox{}}\\phantom{\\mathbf{do}\\;\\mbox{}};\\mathbf{case}\\;(\\Varid{\\downarrow}\\;\\Varid{x'})\\;\\mathbf{of}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;\\mbox{}}\\phantom{\\mathbf{do}\\;\\mbox{}}\\phantom{;\\mbox{}}\\Conid{Just}\\;\\Varid{x''}\\to \\mathbf{case}\\;(\\Varid{\\downarrow}\\;\\Varid{y'})\\;\\mathbf{of}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;\\mbox{}}\\phantom{\\mathbf{do}\\;\\mbox{}}\\phantom{;\\mbox{}}\\phantom{\\Conid{Just}\\;\\Varid{x''}\\to \\mbox{}}\\Conid{Just}\\;\\Varid{y''}\\to \\Varid{return}\\mathbin{\\$}\\Varid{\\uparrow}\\;((\\Varid{x''}\\mathbin{::}\\Conid{Int})\\mathbin{+}(\\Varid{y''}\\mathbin{::}\\Conid{Int}))}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;\\mbox{}}\\phantom{\\mathbf{do}\\;\\mbox{}}\\phantom{;\\mbox{}}\\phantom{\\Conid{Just}\\;\\Varid{x''}\\to \\mbox{}}\\Conid{Nothing}\\to \\Varid{error}\\;((\\Varid{show}\\;\\Varid{y'})\\plus \\text{\\tt \\char34 ~not~an~integer\\char34})}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;\\mbox{}}\\phantom{\\mathbf{do}\\;\\mbox{}}\\phantom{;\\mbox{}}\\Conid{Nothing}\\to \\Varid{error}\\;((\\Varid{show}\\;\\Varid{x'})\\plus \\text{\\tt \\char34 ~not~an~integer\\char34})}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;\\mbox{}}\\phantom{\\mathbf{do}\\;\\mbox{}}\\mskip1.5mu\\}}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\phi}\\;(\\Conid{TmSub}\\;\\Varid{x}\\;\\Varid{y})\\mathrel{=}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;\\mbox{}}\\mathbf{do}\\;\\{\\mskip1.5mu \\Varid{x'}\\leftarrow \\Varid{x}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;\\mbox{}}\\phantom{\\mathbf{do}\\;\\mbox{}};\\Varid{y'}\\leftarrow \\Varid{y}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;\\mbox{}}\\phantom{\\mathbf{do}\\;\\mbox{}};\\mathbf{case}\\;(\\Varid{\\downarrow}\\;\\Varid{x'})\\;\\mathbf{of}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;\\mbox{}}\\phantom{\\mathbf{do}\\;\\mbox{}}\\phantom{;\\mbox{}}\\Conid{Just}\\;\\Varid{x''}\\to \\mathbf{case}\\;(\\Varid{\\downarrow}\\;\\Varid{y'})\\;\\mathbf{of}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;\\mbox{}}\\phantom{\\mathbf{do}\\;\\mbox{}}\\phantom{;\\mbox{}}\\hskip5.50em\\relax\\Conid{Just}\\;\\Varid{y''}\\to \\Varid{return}\\mathbin{\\$}\\Varid{\\uparrow}\\;((\\Varid{x''}\\mathbin{::}\\Conid{Int})\\mathbin{-}(\\Varid{y''}\\mathbin{::}\\Conid{Int}))}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;\\mbox{}}\\phantom{\\mathbf{do}\\;\\mbox{}}\\phantom{;\\mbox{}}\\hskip5.50em\\relax\\Conid{Nothing}\\to \\Varid{error}\\;((\\Varid{show}\\;\\Varid{y'})\\plus \\text{\\tt \\char34 ~not~an~integer\\char34})}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;\\mbox{}}\\phantom{\\mathbf{do}\\;\\mbox{}}\\phantom{;\\mbox{}}\\Conid{Nothing}\\to \\Varid{error}\\;((\\Varid{show}\\;\\Varid{x'})\\plus \\text{\\tt \\char34 ~not~an~integer\\char34})}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;\\mbox{}}\\phantom{\\mathbf{do}\\;\\mbox{}}\\mskip1.5mu\\}}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\mathbf{instance}\\;\\Conid{Algebra}\\;\\Conid{TmIf}\\;\\Conid{TmValEnv}\\;\\mathbf{where}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\phi}\\;(\\Conid{If}\\;\\Varid{b}\\;\\Varid{t}\\;\\Varid{e})\\mathrel{=}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;\\mbox{}}\\mathbf{do}\\;\\{\\mskip1.5mu \\Varid{b'}\\leftarrow \\Varid{b}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;\\mbox{}}\\phantom{\\mathbf{do}\\;\\mbox{}};\\mathbf{case}\\;(\\Varid{\\downarrow}\\;\\Varid{b'})\\;\\mathbf{of}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;\\mbox{}}\\phantom{\\mathbf{do}\\;\\mbox{}}\\phantom{;\\mbox{}}\\Conid{Just}\\;\\Varid{b''}\\to \\mathbf{if}\\;\\Varid{b''}\\;\\mathbf{then}\\;\\Varid{t}\\;\\mathbf{else}\\;\\Varid{e}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;\\mbox{}}\\phantom{\\mathbf{do}\\;\\mbox{}}\\phantom{;\\mbox{}}\\Conid{Nothing}\\to \\Varid{error}\\;((\\Varid{show}\\;\\Varid{b'})\\plus \\text{\\tt \\char34 ~is~not~boolean\\char34})}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;\\mbox{}}\\phantom{\\mathbf{do}\\;\\mbox{}}\\mskip1.5mu\\}}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\mathbf{instance}\\;\\Conid{Algebra}\\;\\Conid{TmVar}\\;\\Conid{TmValEnv}\\;\\mathbf{where}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\phi}\\;(\\Conid{TmVar}\\;\\Varid{v})\\mathrel{=}\\mathbf{do}\\;\\{\\mskip1.5mu \\Varid{val}\\leftarrow \\Varid{asks}\\;(\\Varid{lookup}\\;\\Varid{v})}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{TmVar}\\;\\Varid{v})\\mathrel{=}\\mathbf{do}\\;\\mbox{}};\\mathbf{case}\\;\\Varid{val}\\;\\mathbf{of}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{TmVar}\\;\\Varid{v})\\mathrel{=}\\mathbf{do}\\;\\mbox{}}\\phantom{;\\mbox{}}\\Conid{Just}\\;\\Varid{x}\\to \\Varid{return}\\;\\Varid{x}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{TmVar}\\;\\Varid{v})\\mathrel{=}\\mathbf{do}\\;\\mbox{}}\\phantom{;\\mbox{}}\\Conid{Nothing}\\to \\Varid{error}\\;(\\text{\\tt \\char34 Variable~\\char34}\\plus (\\Varid{v}\\plus \\text{\\tt \\char34 ~not~found\\char34}))}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;(\\Conid{TmVar}\\;\\Varid{v})\\mathrel{=}\\mathbf{do}\\;\\mbox{}}\\mskip1.5mu\\}}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\mathbf{instance}\\;\\Conid{Algebra}\\;\\Conid{TmFn}\\;\\Conid{TmValEnv}\\;\\mathbf{where}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\phi}\\;(\\Conid{TmLambda}\\;\\Varid{s}\\;\\Varid{ty}\\;\\Varid{te})\\mathrel{=}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;\\mbox{}}\\mathbf{do}\\;\\{\\mskip1.5mu \\Varid{env}\\leftarrow \\Varid{ask}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;\\mbox{}}\\phantom{\\mathbf{do}\\;\\mbox{}};\\Varid{return}\\mathbin{\\$}\\Varid{\\uparrow}\\mathbin{\\$}(\\lambda \\Varid{v}\\to \\mathbf{do}\\;\\{\\mskip1.5mu \\Varid{v'}\\leftarrow \\Varid{v}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;\\mbox{}}\\phantom{\\mathbf{do}\\;\\mbox{}}\\phantom{;\\Varid{return}\\mathbin{\\$}\\Varid{\\uparrow}\\mathbin{\\$}(\\lambda \\Varid{v}\\to \\mathbf{do}\\;\\mbox{}};\\Varid{local}\\;(\\Varid{const}\\;((\\Varid{s},\\Varid{v'})\\mathbin{:}\\Varid{env}))\\;\\Varid{te}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;\\mbox{}}\\phantom{\\mathbf{do}\\;\\mbox{}}\\phantom{;\\Varid{return}\\mathbin{\\$}\\Varid{\\uparrow}\\mathbin{\\$}(\\lambda \\Varid{v}\\to \\mathbf{do}\\;\\mbox{}}\\mskip1.5mu\\})}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;\\mbox{}}\\phantom{\\mathbf{do}\\;\\mbox{}}\\mskip1.5mu\\}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\Varid{\\phi}\\;(\\Conid{TmApp}\\;\\Varid{te1}\\;\\Varid{te2})\\mathrel{=}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;\\mbox{}}\\mathbf{do}\\;\\{\\mskip1.5mu \\Varid{te1'}\\leftarrow \\Varid{te1}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;\\mbox{}}\\phantom{\\mathbf{do}\\;\\mbox{}};\\mathbf{case}\\;(\\Varid{\\downarrow}\\;\\Varid{te1'})\\;\\mathbf{of}}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;\\mbox{}}\\phantom{\\mathbf{do}\\;\\mbox{}}\\phantom{;\\mbox{}}(\\Conid{Just}\\;(\\Conid{LambdaVal}\\;\\Varid{f}))\\to (\\Varid{f}\\;\\Varid{te2})}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;\\mbox{}}\\phantom{\\mathbf{do}\\;\\mbox{}}\\phantom{;\\mbox{}}\\Varid{a}\\to \\Varid{error}\\;((\\Varid{show}\\;\\Varid{a})\\plus \\text{\\tt \\char34 ~is~not~a~lambda~value\\char34})}$\\\\\n${\\hskip1.00em\\relax\\hskip2.00em\\relax\\phantom{\\Varid{\\phi}\\;\\mbox{}}\\phantom{\\mathbf{do}\\;\\mbox{}}\\mskip1.5mu\\}}$\n\\end{tabbing}\nThe \\ensuremath{\\Varid{eval}_{\\mathcal D}} function generates a monad from a term language element.\nThe monad is an \\ensuremath{\\Conid{ErrorMonad}} composed with a \\ensuremath{\\Conid{Reader}} monad, thus the\nresult of applying \\ensuremath{\\Varid{runReader}} is either a value or an error message.\n\\ensuremath{\\Varid{runEval}} applies \\ensuremath{\\Varid{runReaderT}} to the \\ensuremath{\\Conid{Reader}} monad resulting from\n\\ensuremath{\\Varid{eval}_{\\mathcal D}} on an environment parameter.  \\ensuremath{\\Varid{execute}} applies \\ensuremath{\\Varid{runEval}} with\nan empty environment.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\hskip1.00em\\relax\\Varid{eval}_{\\mathcal D}\\mathbin{::}\\Conid{TmLang}\\to \\Conid{TmValEnv}}$\\\\\n${\\hskip1.00em\\relax\\Varid{eval}_{\\mathcal D}\\mathrel{=}\\Varid{cata}}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\Varid{runEval}\\;\\Varid{t}\\;\\Varid{e}\\mathrel{=}(\\Varid{runReaderT}\\;(\\Varid{eval}_{\\mathcal D}\\;\\Varid{t})\\;\\Varid{e})}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\Varid{execute}\\;\\Varid{t}\\mathrel{=}\\Varid{runEval}\\;\\Varid{t}\\;[\\mskip1.5mu \\mskip1.5mu]}$\n\\end{tabbing}\n\\section{Interpretation}\n\nHere the type checker and the evaluator are put together to form an\ninterpreter.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\hskip1.00em\\relax\\mathbf{module}\\;\\Conid{TypedLambdaInterpreter}\\;\\mathbf{where}}$\\\\\n${}$\\\\\n${\\hskip1.00em\\relax\\mathbf{import}\\;\\Conid{LangUtils}}$\\\\\n${\\hskip1.00em\\relax\\mathbf{import}\\;\\Conid{TypedLambdaEnv}}$\\\\\n${\\hskip1.00em\\relax\\mathbf{import}\\;\\Conid{TypedLambdaAST}}$\\\\\n${\\hskip1.00em\\relax\\mathbf{import}\\;\\Conid{TypedLambdaEval}}$\\\\\n${\\hskip1.00em\\relax\\mathbf{import}\\;\\Conid{TypedLambdaTypesT}}$\n\\end{tabbing}\nThe \\ensuremath{\\Varid{interpret}} function is primarily a command line, testing\nfunction.  It accepts a term and generates an \\ensuremath{\\Conid{IO}} monad representing\neither the error message or value generated by the evaluator.  Most of\nthe work here is simply getting the output in a reasonably well\nformatted form.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\hskip1.00em\\relax\\Varid{interpret}\\mathbin{::}\\Conid{TmLang}\\to \\Conid{IO}\\;()}$\\\\\n${\\hskip1.00em\\relax\\Varid{interpret}\\;\\Varid{t}\\mathrel{=}\\mathbf{case}\\;(\\Varid{runTypeof}\\;\\Varid{t})\\;\\mathbf{of}}$\\\\\n${\\hskip1.00em\\relax\\phantom{\\Varid{interpret}\\;\\Varid{t}\\mathrel{=}\\mbox{}}(\\Conid{Left}\\;(\\Conid{\\Conid{TypedLambdaTypesT}.Err}\\;\\Varid{y}))\\to }$\\\\\n${\\hskip1.00em\\relax\\phantom{\\Varid{interpret}\\;\\Varid{t}\\mathrel{=}\\mbox{}}\\hskip2.00em\\relax\\mathbf{do}\\;\\{\\mskip1.5mu \\Varid{putStr}\\;\\text{\\tt \\char34 Type~Error:~\\char34}}$\\\\\n${\\hskip1.00em\\relax\\phantom{\\Varid{interpret}\\;\\Varid{t}\\mathrel{=}\\mbox{}}\\hskip2.00em\\relax\\phantom{\\mathbf{do}\\;\\mbox{}};\\Varid{putStr}\\;\\Varid{y};\\Varid{putStr}\\;\\text{\\tt \\char34 \\char92 n\\char34}}$\\\\\n${\\hskip1.00em\\relax\\phantom{\\Varid{interpret}\\;\\Varid{t}\\mathrel{=}\\mbox{}}\\hskip2.00em\\relax\\phantom{\\mathbf{do}\\;\\mbox{}}\\mskip1.5mu\\}}$\\\\\n${\\hskip1.00em\\relax\\phantom{\\Varid{interpret}\\;\\Varid{t}\\mathrel{=}\\mbox{}}(\\Conid{Right}\\;\\Varid{y})\\to \\mathbf{case}\\;(\\Varid{runEval}\\;\\Varid{t}\\;[\\mskip1.5mu \\mskip1.5mu])\\;\\mathbf{of}}$\\\\\n${\\hskip1.00em\\relax\\phantom{\\Varid{interpret}\\;\\Varid{t}\\mathrel{=}\\mbox{}}\\hskip6.00em\\relax(\\Conid{Left}\\;(\\Conid{\\Conid{TypedLambdaEval}.Err}\\;\\Varid{z}))\\to }$\\\\\n${\\hskip1.00em\\relax\\phantom{\\Varid{interpret}\\;\\Varid{t}\\mathrel{=}\\mbox{}}\\hskip6.00em\\relax\\hskip2.00em\\relax\\mathbf{do}\\;\\{\\mskip1.5mu \\Varid{putStr}\\;\\text{\\tt \\char34 Runtime~Error:~\\char34}}$\\\\\n${\\hskip1.00em\\relax\\phantom{\\Varid{interpret}\\;\\Varid{t}\\mathrel{=}\\mbox{}}\\hskip6.00em\\relax\\hskip2.00em\\relax\\phantom{\\mathbf{do}\\;\\mbox{}};\\Varid{putStr}\\;(\\Varid{show}\\;\\Varid{z})}$\\\\\n${\\hskip1.00em\\relax\\phantom{\\Varid{interpret}\\;\\Varid{t}\\mathrel{=}\\mbox{}}\\hskip6.00em\\relax\\hskip2.00em\\relax\\phantom{\\mathbf{do}\\;\\mbox{}};\\Varid{putStr}\\;\\text{\\tt \\char34 \\char92 n\\char34}}$\\\\\n${\\hskip1.00em\\relax\\phantom{\\Varid{interpret}\\;\\Varid{t}\\mathrel{=}\\mbox{}}\\hskip6.00em\\relax\\hskip2.00em\\relax\\phantom{\\mathbf{do}\\;\\mbox{}}\\mskip1.5mu\\}}$\\\\\n${\\hskip1.00em\\relax\\phantom{\\Varid{interpret}\\;\\Varid{t}\\mathrel{=}\\mbox{}}\\hskip6.00em\\relax(\\Conid{Right}\\;\\Varid{z})\\to }$\\\\\n${\\hskip1.00em\\relax\\phantom{\\Varid{interpret}\\;\\Varid{t}\\mathrel{=}\\mbox{}}\\hskip6.00em\\relax\\hskip2.00em\\relax\\mathbf{do}\\;\\{\\mskip1.5mu \\Varid{putStr}\\;\\text{\\tt \\char34 Value:~\\char34}}$\\\\\n${\\hskip1.00em\\relax\\phantom{\\Varid{interpret}\\;\\Varid{t}\\mathrel{=}\\mbox{}}\\hskip6.00em\\relax\\hskip2.00em\\relax\\phantom{\\mathbf{do}\\;\\mbox{}};\\Varid{putStr}\\;(\\Varid{show}\\;\\Varid{z})}$\\\\\n${\\hskip1.00em\\relax\\phantom{\\Varid{interpret}\\;\\Varid{t}\\mathrel{=}\\mbox{}}\\hskip6.00em\\relax\\hskip2.00em\\relax\\phantom{\\mathbf{do}\\;\\mbox{}};\\Varid{putStr}\\;\\text{\\tt \\char34 ::~\\char34}}$\\\\\n${\\hskip1.00em\\relax\\phantom{\\Varid{interpret}\\;\\Varid{t}\\mathrel{=}\\mbox{}}\\hskip6.00em\\relax\\hskip2.00em\\relax\\phantom{\\mathbf{do}\\;\\mbox{}};\\Varid{putStr}\\;(\\Varid{show}\\;\\Varid{y})}$\\\\\n${\\hskip1.00em\\relax\\phantom{\\Varid{interpret}\\;\\Varid{t}\\mathrel{=}\\mbox{}}\\hskip6.00em\\relax\\hskip2.00em\\relax\\phantom{\\mathbf{do}\\;\\mbox{}};\\Varid{putStr}\\;\\text{\\tt \\char34 \\char92 n\\char34}}$\\\\\n${\\hskip1.00em\\relax\\phantom{\\Varid{interpret}\\;\\Varid{t}\\mathrel{=}\\mbox{}}\\hskip6.00em\\relax\\hskip2.00em\\relax\\phantom{\\mathbf{do}\\;\\mbox{}}\\mskip1.5mu\\}}$\n\\end{tabbing}\n\\bibliography{prog-langs}\n\n\\end{document}", "meta": {"hexsha": "94c57ea538c2258ea7b9c0a83ba4a0a3bab20129", "size": 53464, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "TypedLambda/TypedLambdaMonad.tex", "max_stars_repo_name": "palexand/interpreters", "max_stars_repo_head_hexsha": "c5ff4e644fce1e97f1823321710dd082aa79aa72", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2015-02-05T13:24:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T18:39:05.000Z", "max_issues_repo_path": "TypedLambda/TypedLambdaMonad.tex", "max_issues_repo_name": "palexand/interpreters", "max_issues_repo_head_hexsha": "c5ff4e644fce1e97f1823321710dd082aa79aa72", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TypedLambda/TypedLambdaMonad.tex", "max_forks_repo_name": "palexand/interpreters", "max_forks_repo_head_hexsha": "c5ff4e644fce1e97f1823321710dd082aa79aa72", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-09T10:16:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-09T10:16:44.000Z", "avg_line_length": 72.7401360544, "max_line_length": 325, "alphanum_fraction": 0.6729387999, "num_tokens": 23176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.33189682529494774}}
{"text": "\\chapter{Summary and Conclusions}\\label{c:conclude}\n\nThe \\numbers\\ program is a shell program which reads and stores data\nfrom a finite element model described in the \\exo\\ database\nformat~\\cite{EXODUS}. Within this shell program are several utility\nroutines which calculate information about the finite element model.\nThe utilities currently implemented in \\numbers\\ allow the analyst to\ndetermine: \n\\begin{itemize}\n\\item the volume and coordinate limits of each of the materials in the model;\n\\item the mass properties of the model; \n\\item the minimum, maximum, and average element volumes for each material; \n\\item the volume and change in volume of a cavity; \n\\item the nodes or elements that are within a specified distance from a\nuser-defined point, line, or plane \n\\item an estimate of the explicit central-difference timestep for each \nmaterial; \n\\item the validity of contact surfaces or slidelines, that is, whether\ntwo surfaces overlap at any point; and\n\\item the distance between two surfaces.\n\\end{itemize}\n\nSince it is relatively easy to add a new utility to \\numbers, its\ncapabilities should increase in the future.  Utilities that may be added\nin the future include the calculation of element distortion parameters\nwhich would be useful for validating automatically generated finite\nelement discretizations, determination of the surface area of side sets,\nand additional verification of contact surfaces. Although \\numbers\\ does\nnot currently read any of the variables, except for the displacements,\nfrom an \\exo\\ file, the code is structured such that this capability\ncould be easily added if needed.  \n", "meta": {"hexsha": "812545dc156e548d4af73fa40f880d7a0132290e", "size": 1620, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "packages/seacas/doc-source/numbers/conclude.tex", "max_stars_repo_name": "jschueller/seacas", "max_stars_repo_head_hexsha": "14c34ae08b757cba43a3a03ec0f129c8a168a9d3", "max_stars_repo_licenses": ["Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "NetCDF", "BSL-1.0", "X11", "BSD-3-Clause"], "max_stars_count": 82, "max_stars_repo_stars_event_min_datetime": "2016-02-04T18:38:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T03:01:49.000Z", "max_issues_repo_path": "packages/seacas/doc-source/numbers/conclude.tex", "max_issues_repo_name": "jschueller/seacas", "max_issues_repo_head_hexsha": "14c34ae08b757cba43a3a03ec0f129c8a168a9d3", "max_issues_repo_licenses": ["Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "NetCDF", "BSL-1.0", "X11", "BSD-3-Clause"], "max_issues_count": 206, "max_issues_repo_issues_event_min_datetime": "2015-11-20T01:57:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:12:04.000Z", "max_forks_repo_path": "packages/seacas/doc-source/numbers/conclude.tex", "max_forks_repo_name": "jschueller/seacas", "max_forks_repo_head_hexsha": "14c34ae08b757cba43a3a03ec0f129c8a168a9d3", "max_forks_repo_licenses": ["Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "NetCDF", "BSL-1.0", "X11", "BSD-3-Clause"], "max_forks_count": 68, "max_forks_repo_forks_event_min_datetime": "2016-01-13T22:46:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T06:25:05.000Z", "avg_line_length": 50.625, "max_line_length": 77, "alphanum_fraction": 0.8049382716, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.33182736982495936}}
{"text": "\\chapter{Results}\\label{chap5}\nIn this section we present the preliminary results of the performance of the $\\tauh$ identification algorithm using $\\int\\mathcal{L} dt=139.2$ fb$^{-1}$ of data recorded between 2015 and 2018.\nThe correction factors are applied to simulation in order to match the efficiency observed in data. These correction factors are defined as the ratio between the efficiency measured in data and in simulation.\n\\begin{equation}\nC_{\\text{ID}}=\\frac{\\mathcal{E}_{\\text{MC}}}{\\mathcal{E}_{\\text{Data}}}.\n\\end{equation}\nFor this work, we present a preview of the value of the correction factors for \\textit{Tight} ID working point for $\\tauh$ candidates with $\\pt$ above 45 GeV. Since this report is about a work in progress and we have not studied yet the effect of the systematic uncertainties on our results, we will take another approach on estimating the correction factors.\n\n\\section{Systematic uncertainties}\nThe values for the systematic uncertainties used to report the value of the correction factors are presented in Table \\ref{Tab5}. These numbers have been provided by Terry Wyatt and Sam Dysch, based on their previous experience working on analysis that make use of $Z\\to\\tauh l$ events.\n\\begin{table}[htbp]\n\t\\centering\n\t\\begin{tabular}{cc}\n\t\t\\hline\n\t\t\\multicolumn{1}{|c|}{Source}        & \\multicolumn{1}{c|}{Sys. Uncertainty (\\%)} \\\\ \\hline\n\t\tElectron ID efficiency              & 0.8                                        \\\\\n\t\tMuon ID Efficiency                  & 0.2                                        \\\\\n\t\tElectron $\\pt$ scale and resolution & 0.4                                        \\\\\n\t\tMuon $\\pt$ scale and resolution     & 0.3                                        \\\\\n\t\tTau $\\pt$ scale                     & 1.9                                        \\\\\n\t\tElectron trigger efficiency         & 0.1                                        \\\\\n\t\tMuon trigger efficiency             & 0.4                                        \\\\ \n\t\tIntegrated luminosity               & 1.7                                        \\\\ \\hline\n\t\\end{tabular}\n\t\\caption{Systematic uncertainties used in this study.}\n\t\\label{Tab5}\n\\end{table}\n\\section{$\\mu\\tau$ Final state}\nWe define the simulation correction factor as\n\\begin{equation}\n\tC_{\\text{Tight-ID}}=\\frac{N_{\\text{MC}}}{N_{\\text{Data}}}.\n\\end{equation}\nWhere $N_{\\text{Data}}$ are the total number of events measured in data substracting all the contributions from fake $\\tauh$ estimated in the MC and  $N_{\\text{MC}}$ are the number of events in simulation that have a truth matched $\\tauh$. The number of events that gets selected after all the cuts and without the $\\pt(\\tauh)>45$ GeV requirement are shown in Table \\ref{Table6}.\n\\begin{table}[htbp]\n\t\\centering\n\t\\resizebox{\\columnwidth}{!}{%\n\t\\begin{tabular}{ccc}\n\t\t\\hline\n\t\t\\multicolumn{1}{c|}{Samples} & \\multicolumn{1}{c|}{Before $\\pt(\\tauh)$\\textgreater{}45 GeV cut} & After all cuts      \\\\ \\hline\n\t\tZ$\\to\\tau\\tau$               & 34224.49$\\pm$420.83(stat)$\\pm$581.81(lumi)$\\pm$675.88(sys)                                              & 11899.10$\\pm$182.66(stat)$\\pm$202.28(lumi)$\\pm$234.99(sys) \\\\\n\t\tZ+jets                       & 543.21$\\pm$11.06(stat)$\\pm$9.23(lumi)$\\pm$10.73(sys)                                                 & 98.92$\\pm$4.69(stat)$\\pm$1.68(lumi)$\\pm$1.95(sys)      \\\\\n\t\tW+jets                       & 586.70$\\pm$77.99(stat)$\\pm$9.97(lumi)$\\pm$11.59(sys)                                                 & 37.11$\\pm$18.75(stat)$\\pm$0.63(lumi)$\\pm$0.73(sys)     \\\\\n\t\tttbar                        & 339.94$\\pm$6.84(stat)$\\pm$5.78(lumi)$\\pm$6.70(sys)                                                  & 88.44$\\pm$3.42(stat)$\\pm$1.50(lumi)$\\pm$1.75(sys)      \\\\\n\t\tDiboson                      & 470.69$\\pm$4.72(stat)$\\pm$8.00(lumi)$\\pm$9.30(sys)                                                  & 187.07$\\pm$2.82(stat)$\\pm$3.18(lumi)$\\pm$3.69(sys)     \\\\\n\t\tSingle top                   & 63.03$\\pm$3.07(stat)$\\pm$1.07(lumi)$\\pm$1.24(sys)                                                   & 14.35$\\pm$1.50(stat)$\\pm$0.24(lumi)$\\pm$0.28(sys)      \\\\\n\t\tMJ                           & 2386.06$\\pm$143.76(stat)$\\pm$40.56(lumi)$\\pm$47.12(sys)                                               & 231.43$\\pm$75.25(stat)$\\pm$3.93(lumi)$\\pm$4.57(sys)    \\\\ \\hline\n\t\t\\multicolumn{1}{c|}{MC Total}   & \\multicolumn{1}{c|}{38634.12$\\pm$668.27(stat)$\\pm$656.78(lumi)$\\pm$762.96(sys)}                         & 12556.42$\\pm$289.09(stat)$\\pm$213.46(lumi)$\\pm$247.97(sys) \\\\ \\hline\n\t\t\\multicolumn{1}{c|}{Data}    & \\multicolumn{1}{c|}{39101$\\pm$198(stat)}                               & 12692$\\pm$112(stat)      \\\\ \\hline\n\t\\end{tabular}\n\t}\n\t\\caption{Number of selected events in data and each of the simulation samples in the $Z\\to\\tauh\\mu$. Statistical and systematic uncertainties are presented separately. Luminosity uncertainty is presented apart. Z+jets stands for the combination of $Z\\to ee$ and $Z\\to\\mu\\mu$ samples.}\n\t\\label{Table6}\n\\end{table}\nThe value obtained for $C_{\\text{Tight-ID}}$ in the final state that contains one muon and a $\\tauh$ candidate is\n\\begin{equation}\nC_{\\text{Tight-ID}}=0.989\\pm 0.012\\text{(stat)}\\pm 0.017\\text{(lumi)}\\pm 0.020\\text{(sys)}.\n\\end{equation}\nAll the distributions of the relevant cuts for selecting our signal events after applying all the other cuts are shown in Fig.\\ref{Fig17} (Appendix A).\n\\section{$e\\tau$ Final state}\nFor the final state that contains one electron and a $\\tauh$ candidate, the number of events that gets selected after all the cuts and without the $\\pt(\\tauh)>45$ GeV requirement are shown in Table \\ref{Table8}.\n\\begin{table}[htbp]\n\t\\centering\n\t\\resizebox{\\columnwidth}{!}{%\n\t\\begin{tabular}{ccc}\n\t\t\\hline\n\t\t\\multicolumn{1}{c|}{Samples} & \\multicolumn{1}{c|}{Before $\\pt(\\tauh)$\\textgreater{}45 GeV cut} & After all cuts     \\\\ \\hline\n\t\tZ$\\to\\tau\\tau$               & 25269.30$\\pm$362.92(stat)$\\pm$429.58(lumi)$\\pm$531.26(sys)                                              & 8787.97$\\pm$150.77(stat)$\\pm$149.39(lumi)$\\pm$184.76(sys) \\\\\n\t\tZ+jets                       & 682.15$\\pm$12.69(stat)$\\pm$11.60(lumi)$\\pm$14.34(sys)                                                 & 74.07$\\pm$4.23(stat)$\\pm$1.26(lumi)$\\pm$1.56(sys)     \\\\\n\t\tW+jets                       & 348.28$\\pm$56.10(stat)$\\pm$5.92(lumi)$\\pm$7.32(sys)                                                 & 8.08$\\pm$8.08(stat)$\\pm$0.14(lumi)$\\pm$0.17(sys)      \\\\\n\t\tttbar                        & 255.55$\\pm$6.05(stat)$\\pm$4.34(lumi)$\\pm$5.37(sys)                                                  & 56.63$\\pm$2.86(stat)$\\pm$0.96(lumi)$\\pm$1.19(sys)     \\\\\n\t\tDiboson                      & 384.25$\\pm$4.19(stat)$\\pm$6.53(lumi)$\\pm$8.08(sys)                                                  & 152.92$\\pm$2.58(stat)$\\pm$2.60(lumi)$\\pm$3.21(sys)    \\\\\n\t\tSingle top                   & 47.48$\\pm$2.71(stat)$\\pm$0.81(lumi)$\\pm$1.00(sys)                                                   & 11.29$\\pm$1.32(stat)$\\pm$0.19(lumi)$\\pm$0.24(sys)     \\\\\n\t\tMJ                           & 1530.54$\\pm$101.21(stat)$\\pm$26.02(lumi)$\\pm$32.18(sys)                                               & 229.34$\\pm$65.04(stat)$\\pm$3.90(lumi)$\\pm$4.82(sys)   \\\\ \\hline\n\t\t\\multicolumn{1}{c|}{Total}   & \\multicolumn{1}{c|}{28487.55$\\pm$545.87(stat)$\\pm$484.29(lumi)$\\pm$598.91(sys)}                         & 9320.31$\\pm$234.87(stat)$\\pm$158.44(lumi)$\\pm$195.95(sys) \\\\ \\hline\n\t\t\\multicolumn{1}{c|}{Data}    & \\multicolumn{1}{c|}{29723$\\pm$172(stat)}                               & 9559$\\pm$98(stat)        \\\\ \\hline\n\t\\end{tabular}\n\t}\n\t\\caption{Number of selected events in data and each of the simulation samples in the $Z\\to\\tauh e$. Statistical and systematic uncertainties are presented separately. Luminosity uncertainty is presented apart.}\n\t\\label{Table8}\n\\end{table}\nThe value obtained for $C_{\\text{Tight-ID}}$ is\n\\begin{equation}\nC_{\\text{Tight-ID}}=0.974\\pm 0.014\\text{(stat)}\\pm 0.017\\text{(lumi)}\\pm 0.020\\text{(sys)}.\n\\end{equation}\nAll the distributions of the relevant cuts for selecting our signal events after applying all the other cuts are shown in Fig.\\ref{Fig18} (Appendix A).\n\\section{Discussion}\nAs this study makes use of events highly boosted in the transverse plane the Z$(\\pt)$ modelling is very important. All the plots that have been shown in previous sections make use of the Sherpa generator for $Z\\to\\tauh l$ events. Some distributions related to the Z$(\\pt)$ are shown in Fig.\\ref{Fig19} for Sherpa. The complete set of plots showing the Z$(\\pt)$ distribution for both e-tau and mu-tau final states for the two different type of topologies are shown in Fig.\\ref{Fig21} and Fig.\\ref{Fig22}. In the first stages of our analysis we used Powheg+Pythia8 to simulate $Z\\to\\tauh l$ events. Fig.\\ref{Fig23} shows the Z$(\\pt)$ and $\\Delta\\phi(\\tauh,l)$ for the muon-tau final state for in-between events modelled by Powheg+Pythia8. As it can be seen the tendency in the MC is to underestimate the data for high-Z$(\\pt)$ values. These results have been previously reported in ATLAS studies \\cite{Aad:2019wmn}. Fig.\\ref{Fig20} shows the Z$(\\pt)$ modelling made by different generators. This has motivated us to use Sherpa to simulate our signal events.\n\\begin{figure}[htbp]\n\t\\centering\n\t\\subfloat[]{\\label{Fig19a}{\\includegraphics[width=0.50\\textwidth]{figures/Fig19a}}}\\hfill\n\t\\subfloat[]{\\label{Fig19b}{\\includegraphics[width=0.50\\textwidth]{figures/Fig19b}}}\n\t\\caption{Distribution of Z$(\\pt)$ for in-between events (a) and $\\Delta\\phi(\\tauh,l)$ (b) using Sherpa. All the other cuts have been applied apart from the one being plotted.}\n\t\\label{Fig19}\n\\end{figure}\n\\begin{figure}[htbp]\n\t\\centering\n\t\\subfloat[]{\\label{Fig23a}{\\includegraphics[width=0.50\\textwidth]{figures/Fig23a}}}\\hfill\n\t\\subfloat[]{\\label{Fig23b}{\\includegraphics[width=0.50\\textwidth]{figures/Fig23b}}}\n\t\\caption{Distribution of Z$(\\pt)$ for in-between events (a) and $\\Delta\\phi(\\tauh,l)$ (b) using Powheg+Pythia8. All the other cuts have been applied apart from the one being plotted.}\n\t\\label{Fig23}\n\\end{figure}\n\\begin{figure}[htbp]\n\t\\centering\n\t\\includegraphics[width=0.5\\textwidth]{figures/Fig20}\n\t\\caption{Comparison of the different modelling of the Z$(\\pt)$ in Drell-Yan events made by different MC generators. As it can be seen Sherpa does a better job describing the Z boson transverse momentum for higher $(\\pt)$ values than Powheg+Pythia8. However both generators underestimate the measured value in the high-Z$(\\pt)$ region. Taken from \\cite{Aad:2019wmn}.}\n\t\\label{Fig20}\n\\end{figure}\n\nAnother challenging task will be to control the MJ background contribution when we go to looser regions in tau-ID. As it can be seen in Fig.\\ref{Fig17c} and Fig.\\ref{Fig17d} the MJ background contribution starts to be more important for 1-prong and 3-prong taus for looser values of the RNN score. We have explored the possible correlation that could arise in actual $Z\\to\\tauh l$ events in variables like the ratio between the transverse momentum of the tau and the lepton or the ratio between the Z$(\\pt)$ and the leading jet. The distributions for this variables are shown in Fig.\\ref{Fig24a} and Fig.\\ref{Fig24b} respectively.\n\\begin{figure}[htbp]\n\t\\centering\n\t\\subfloat[]{\\label{Fig24a}{\\includegraphics[width=0.50\\textwidth]{figures/Fig24a}}}\\hfill\n\t\\subfloat[]{\\label{Fig24b}{\\includegraphics[width=0.50\\textwidth]{figures/Fig24b}}}\n\t\\caption{$r_{\\frac{\\pt(\\mu)}{\\pt(\\tau)}}$ (a) and $r_{\\frac{\\pt(j)}{\\pt(Z)}}$ distributions (b) do not seem to offer a big discriminating power against MJ background events. }\n\t\\label{Fig24}\n\\end{figure}\nThese variables though do not offer a discriminating power against the MJ background. ", "meta": {"hexsha": "3f478145a0af8d432ae54e9127803ad3dc2419d8", "size": 11673, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/5-Results.tex", "max_stars_repo_name": "diegobaronm/1st-Year-Report", "max_stars_repo_head_hexsha": "5089e6bb20e018637116c454ceb9016fa30e5b90", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/5-Results.tex", "max_issues_repo_name": "diegobaronm/1st-Year-Report", "max_issues_repo_head_hexsha": "5089e6bb20e018637116c454ceb9016fa30e5b90", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/5-Results.tex", "max_forks_repo_name": "diegobaronm/1st-Year-Report", "max_forks_repo_head_hexsha": "5089e6bb20e018637116c454ceb9016fa30e5b90", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 99.7692307692, "max_line_length": 1055, "alphanum_fraction": 0.6171506896, "num_tokens": 3592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3317806413173664}}
{"text": "\\section{\\DYNAMICO is}\n\n\\DYNAMICO \\footnotemark is a new dynamical core for LMD-Z, the atromspheric GCM part\nof IPSL-CM Earth System Model.\n%\n\\DYNAMICO is funded by the Indo-French Centre for the Promotion of\nAdvanced Research, by IPSL and by the G8 Research Councils Initiative on\nMultilateral Research Funding, project ICOMEX.\n\n\n\\footnotetext{\nThis section is based on the \\DYNAMICO Wiki page (\\url{http://forge.ipsl.fr/dynamico/wiki})\n}\n\n\n\nThe primary goal of \\DYNAMICO is to re-formulate in LMD-Z the horizontal\nadvection and dynamics on a icosahedral grid, while preserving or\nimproving their qualities with respect to accuracy, conservation laws\nand wave dispersion.\n%\nA broader goal is to revisit all fundamental features of the dynamical\ncore, especially the shallow-atmosphere/traditional approximation, the\nvertical coordinate and the coupling with physics.\n%\nAlso efficient implementation of present and future supercomputing\narchitectures is a key issue.\n\nThis manual describes the overview of \\DYNAMICO and each kernel program\nbriefly.\n%\nFor the details of \\DYNAMICO, see\n\\cite{gmd-8-3131-2015},\netc.\n\n\nKernel programs for \\DYNAMICO are taken from \\DYNAMICO ver 1.0, r339.\n%\nMain feature of \\DYNAMICO-1.0 are;\n\\begin{itemize}\n \\item hydrostatic, traditional shallow atmosphere,\n \\item icosahedral-hexagonal C-grid in horizontal, mass-based Lorentz\n       staggering in vertical,\n \\item Mimetic finite difference + slope-limited finite volume\n       transport, and\n \\item explicit Runge-Kutta time stepping.\n\\end{itemize}\n\n\n\n\\section{Governing equations}\n\nBasic scheme of \\DYNAMICO is the energy/voticity conserving schemes and\nthe curl (vector-invariant) form.\n%\nTo deliver governing equations, \\DYNAMICO adopts the Hamiltonian\nformulation of the equations of motion.\n%\nThis Hamiltonian theory has been extended for compressible hydrostatic\nflows and for non-Eulerian vertical coordinates \\citep{JAS-D-13-0339,MWR-D-14-00069}.\n%\nDerivation of governing equations is complicated, we skip it here. See\n\\cite{gmd-8-3131-2015} etc.\n\n\n\n\n\\section{Horizontal and vertical grid}\n\n\\DYNAMICO adopts the icosahedral-hexagonal C-grid in horizontal and\nmass-based Lorentz staggering grid in vertical.\n%\n\\autoref{f:ico_c_grid} shows horizontal and vertical grids.\n\nScalar variables, such as entropy $\\Theta$, are defined on the center of\nhexagonal control volume (circle points in the figure), velocities and fluxes,\nare defined on the edge (square points), and tracer are\ndefined on the vertex (triangle points).\n%\nSee \\cite{gmd-8-3131-2015} for details.\n\n\n\\begin{figure}\n \\centering\n \\includegraphics[scale=1]{figs/AIMES_DYNAMICO-08-0.png}\n \\caption{Icosahedral C-grid and Lorenz grid.}\\label{f:ico_c_grid}\n%http://www.lmd.polytechnique.fr/~dubos/Talks/2014DubosAGU.pdf\n\\end{figure}\n\n\n\n\\section{Parallelization}\n\nLike \\NICAM and \\DYNAMICO, icosahedral grids on entire globe can be\nseparated by 10 ``diamonds'', each are consist of neighboring two\ntriangles of an icosahedron.\n%\nEach diamonds can be divided in \\src{nsplit_i}$\\times$\\src{nsplit_j} areas,\nand one of divided area,\ncalled ``patch'' in \\DYNAMICO, is the basis of domain decomposition.\n%\n\\src{nsplit_i} and \\src{nsplit_j} are control parameter and read from\nconfiguration file on execution.\n%\nOne MPI process can handle \\src{ndomain} patches, which is decided by\nthe number of total patchs and the number of MPI processes.\n\n\n\n\\section{Data structure}\\label{s:data_structure}\n\nBasic data structure in \\DYNAMICO is a \\src{t_field}, as shown in\n\\autoref{l:t_field}.\n%\nOne instance of \\src{t_field} is to access one field within one patch.\n%\nOne MPI process may handle several patches, and one field may be usually\nan array of \\src{t_field}.\n%\nAllocation and halo-exchange routines are work on \\src{t_field(:)}\nvariables, and other high-level computational routines work on them, too.\n%\nSee the next section as an example.\n\n\\begin{LstF90}[%\ncaption={\\src{t_field} structure},%\nlabel={l:t_field}%\n]\n  TYPE t_field\n    CHARACTER(30)      :: name\n    REAL(rstd),POINTER :: rval2d(:)\n    REAL(rstd),POINTER :: rval3d(:,:)\n    REAL(rstd),POINTER :: rval4d(:,:,:)\n\n    INTEGER,POINTER :: ival2d(:)\n    INTEGER,POINTER :: ival3d(:,:)\n    INTEGER,POINTER :: ival4d(:,:,:)\n\n    LOGICAL,POINTER :: lval2d(:)\n    LOGICAL,POINTER :: lval3d(:,:)\n    LOGICAL,POINTER :: lval4d(:,:,:)\n\n    INTEGER :: ndim\n    INTEGER :: field_type\n    INTEGER :: data_type\n    INTEGER :: dim3\n    INTEGER :: dim4\n  END TYPE t_field\n\\end{LstF90}\n\nOne of members of \\src{t_field} are pointer to the array of\n\\src{REAL(rstd)}, \\src{INTEGER} or \\src{LOGICAL}, and whose dimension is\none, two or three.\n%\nIf the field is horizontal, such as surface pressure or sea surface\ntemperature, \\src{rval2d} is used.\n%\nNote that horizontal index $I$ and $J$ are merged to one dimension.\n\n\n\\autoref{f:aimes_dynamico-30-0} shows horizontal indexing in \\DYNAMICO.\n%\nAs shown in previous chapter, \\DYNAMICO adopts icosahedral grid, and\ncontrol volume is hexagonal as usual.\n%\nOne ``patch'' is rhomboid, and can be indexed as two-dimensional, each\nsize are \\src{iim} and \\src{jjm}, as shown in left figure of\n\\autoref{f:aimes_dynamico-30-0}.\n%\nThese can be re-written as usual orthogonal i-j plane, shown in the\nright figure of \\autoref{f:aimes_dynamico-30-0}.\n%\nThe \\src{n} point in the figure is surrounded by\nsix neighbouring cells, named \\src{right}, \\src{rup}, etc.\n%\nSo stencil calculation comes from finite difference in horizontal uses\nseven points, not five as in usual orthogonal grid.\n\n\\begin{figure}[htpb]\n\\centering\n\\includegraphics[scale=0.7]{figs/AIMES_DYNAMICO-30-0.png}\n\\caption{Horizontal indexing}\\label{f:aimes_dynamico-30-0}\n\\end{figure}\n\nThe number of the edge point is three times larger than that of the center point.\nAs shown in \\autoref{f:rel_center_edge}, each center point manages three edge points.\nThese points are named \\src{u_right}, \\src{u_lup}, and \\src{u_ldown}.\n\n\\begin{figure}[htpb]\n\\centering\n\\includegraphics[scale=0.5]{figs/AIMES_DYNAMICO-30-1.png}\n\\caption{Relationship of center points and edge points}\\label{f:rel_center_edge}\n\\end{figure}\n\nTo allocate one \\src{t_field} instance, subroutine \\src{allocate_field}\nis called.\n%\nBelow is the example of allocating orography named ``phis''.\n\n\\begin{LstF90}\n ! Time-independant orography\n    CALL allocate_field(f_phis,field_t,type_real,name='phis')\n\\end{LstF90}\n\n\n\n\\section{Code structure}\n\nGlobal program structure of \\DYNAMICO is as follows.\n\nIn the main program, after the various initialization, time step loop is\ncarried by a single subroutine \\src{timeloop}.\n%\n\\autoref{f:pad_timeloop} shows PAD (Problem Analysis\nDiagram)\\footnotemark of main processes in subroutine \\src{timeloop}.\n%\nAs seen in the top of this PAD,\n\n\\footnotetext{See \\autoref{s:pad} for reading PAD.}\n\n\\begin{figure}[htb]\n \\centering\n \\includegraphics[scale=.4]{figs/timeloop.pdf}\n \\caption{PAD of \\src{timeloop}}\\label{f:pad_timeloop}\n\\end{figure}\n\nMain time step loop is described in first \\src{it} loop, from step\n\\src{itau0} to \\src{itau0+italmax}.\n%\nFirst IF block in this loop is for halo exchange of several fields,\nusing subroutine \\src{send_message} and \\src{wait_message}.\n%\nIn the next \\src{stage} loop subroutine \\src{caldyn}, one of\n\\src{*_scheme} and \\src{advect_tracer} are called sequentially.\n%\nSubroutine \\src{caldyn} calculate dynamical terms such as potential\nvorticity, etc.\n%\nSubroutine \\src{*_scheme} is for time-advancing. For example,\n\\src{rk_scheme} uses Runge-Kutta scheme.\n%\nThis is a default scheme for this kernel package.\n%\nSubroutine \\src{advect_tracer} is to calculate advection of tracer\nquantities.\n%\nHere variable \\src{nb_stage} in the loop range is the number of\niteration necessary for each time-advancing scheme. For example,\n\\src{nb_stage=1} for Euler scheme, \\src{nb_stage=4} for Runge-Kutta scheme.\n%\nFinally, if time step \\src{it} is at \\src{itau_physics}'th step,\nsubroutine \\src{physics} is called to calculate physics part.\n\n\n\n\\autoref{l:definition_caldyn} is the definition part of subroutine\n\\src{caldyn}\\footnotemark,\nand \\autoref{f:pad_caldyn} is the PAD of it.\n%\n\\footnotetext{Here is the version in \\file{caldyn_gcm.f90}}\n%\nNote that all of current four kernel program in this package is taken\nfrom the subroutine called from this \\src{caldyn} (See \\autoref{s:kernelize}).\n%\nAs mentioned in \\autoref{s:data_structure}, all of fields used in this\nsubroutine is given as pointers of instance of \\src{t_field}.\n\n\\begin{LstF90}[%\ncaption={Definition part of \\src{caldyn}},%\nlabel={l:definition_caldyn}%\n]\n  SUBROUTINE caldyn(write_out,f_phis, f_ps, f_mass, f_theta_rhodz, f_u, f_q, &\n       f_hflux, f_wflux, f_dps, f_dmass, f_dtheta_rhodz, f_du)\n    USE icosa\n    USE disvert_mod, ONLY : caldyn_eta, eta_mass\n    USE vorticity_mod\n    USE kinetic_mod\n    USE theta2theta_rhodz_mod\n    USE wind_mod\n    USE mpipara\n    USE trace\n    USE omp_para\n    USE output_field_mod\n    USE checksum_mod\n    IMPLICIT NONE\n    LOGICAL,INTENT(IN)    :: write_out\n    TYPE(t_field),POINTER :: f_phis(:)\n    TYPE(t_field),POINTER :: f_ps(:)\n    TYPE(t_field),POINTER :: f_mass(:)\n    TYPE(t_field),POINTER :: f_theta_rhodz(:)\n    TYPE(t_field),POINTER :: f_u(:)\n    TYPE(t_field),POINTER :: f_q(:)\n    TYPE(t_field),POINTER :: f_hflux(:), f_wflux(:)\n    TYPE(t_field),POINTER :: f_dps(:)\n    TYPE(t_field),POINTER :: f_dmass(:)\n    TYPE(t_field),POINTER :: f_dtheta_rhodz(:)\n    TYPE(t_field),POINTER :: f_du(:)\n\n    REAL(rstd),POINTER :: ps(:), dps(:)\n    REAL(rstd),POINTER :: mass(:,:), theta_rhodz(:,:), dtheta_rhodz(:,:)\n    REAL(rstd),POINTER :: u(:,:), du(:,:), hflux(:,:), wflux(:,:)\n    REAL(rstd),POINTER :: qu(:,:)\n    REAL(rstd),POINTER :: qv(:,:)\n\n! temporary shared variable\n    REAL(rstd),POINTER  :: theta(:,:)\n    REAL(rstd),POINTER  :: pk(:,:)\n    REAL(rstd),POINTER  :: geopot(:,:)\n    REAL(rstd),POINTER  :: convm(:,:)\n    REAL(rstd),POINTER  :: wwuu(:,:)\n\n    INTEGER :: ind\n    LOGICAL,SAVE :: first=.TRUE.\n\\end{LstF90}\n\n\\begin{figure}[htb]\n\\centering\n\\includegraphics[scale=.4]{figs/caldyn.pdf}\n\\caption{PAD of \\src{caldyn}}\\label{f:pad_caldyn}%\n\\end{figure}\n\nIn \\autoref{f:pad_caldyn} there are some assignment from\n\\src{t_field} to real pointer, such as \\src{ps = f_ps(ind)}.\n%\nThis is defined as module procedure and generic subroutine\n\\src{get_val} and using interface assignment.\n%\nAll of them are defined in module \\src{field_mod} in \\file{field.f90}.\n\n", "meta": {"hexsha": "bea565ab2458a0008f56241f2404cec760b00be6", "size": 10388, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/DYNAMICO/src/20_intro_dynamico.tex", "max_stars_repo_name": "aimes-project/IcoAtmosBenchmark_v1", "max_stars_repo_head_hexsha": "44b8f12dcf0e50094a2d0f78a8794febda270007", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/DYNAMICO/src/20_intro_dynamico.tex", "max_issues_repo_name": "aimes-project/IcoAtmosBenchmark_v1", "max_issues_repo_head_hexsha": "44b8f12dcf0e50094a2d0f78a8794febda270007", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/DYNAMICO/src/20_intro_dynamico.tex", "max_forks_repo_name": "aimes-project/IcoAtmosBenchmark_v1", "max_forks_repo_head_hexsha": "44b8f12dcf0e50094a2d0f78a8794febda270007", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-04T04:07:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-04T04:07:38.000Z", "avg_line_length": 31.4787878788, "max_line_length": 91, "alphanum_fraction": 0.7404697728, "num_tokens": 3032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3317806413173664}}
{"text": "\\documentclass{article} % For LaTeX2e\n\\usepackage{iclr2017_conference,times}\n\\usepackage{hyperref}\n\\usepackage{url}\n\n\n\n\\usepackage{amsmath,graphicx}\n\\usepackage{algorithm}\n\\usepackage[noend]{algpseudocode}\n\n\\makeatletter\n\\def\\BState{\\State\\hskip-\\ALG@thistlm}\n\\makeatother\n\n\n%\\usepackage[cmex10]{amsmath}\n\\usepackage{amssymb}\n\\usepackage{amsthm}\n\\usepackage{geometry}\n\\usepackage{graphicx}\n\\usepackage{epstopdf}\n\\usepackage{hyperref}\n% \\usepackage[francais]{babel}\n\\usepackage[applemac]{inputenc}\n\\usepackage{color}\n\n%\\usepackage{graphicx}% Include figure files\n%\\usepackage{dcolumn}% Align table columns on decimal point\n%\\usepackage{bm}% bold math\n%\\usepackage{color}\n%\\usepackage[caption=false]{subfig} \n\n\\usepackage{listings}\n\n\\definecolor{dkgreen}{rgb}{0,0.6,0}\n\\definecolor{gray}{rgb}{0.5,0.5,0.5}\n\\definecolor{mauve}{rgb}{0.58,0,0.82}\n\n\\lstset{frame=tb,\n  language=python,\n  aboveskip=3mm,\n  belowskip=3mm,\n  showstringspaces=false,\n  columns=flexible,\n  basicstyle={\\small\\ttfamily},\n  numbers=none,\n  numberstyle=\\tiny\\color{gray},\n  keywordstyle=\\color{blue},\n  commentstyle=\\color{dkgreen},\n  stringstyle=\\color{mauve},\n  breaklines=true,\n  breakatwhitespace=true,\n  tabsize=3\n}\n\n\\newcommand {\\lb} {{\\langle}}\n\\newcommand {\\rb} {{\\rangle}}\n\\newcommand {\\R} {{\\mathbb{R}}}\n\\newcommand {\\X} {{\\tilde X}}\n\\newcommand {\\w} {{\\tilde w}}\n\\newcommand {\\hh} {{k}}\n\\newcommand {\\p} {{\\tilde p}}\n\\newcommand {\\RN} {{{\\mathbb{R}}^N}}\n\\newcommand {\\Z} {{\\mathbb{Z}}}\n\\newcommand {\\E} {{\\mathbb{E}}}\n\\newcommand {\\W} {{\\cal{W}}}\n\\newcommand {\\Fem} {F_{e}}\n\\newcommand {\\Forr} {F_{o}}\n\\newcommand{\\Exp}[1]{\\mathbb{E}\\left(#1 \\right)}\n\n\\usepackage{amsthm}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\n\n\\newcommand{\\figref}[1]{Fig. \\ref{#1}}\n\n\n\\newtheorem{theorem}{Theorem}[section]\n\\newtheorem{lemma}[theorem]{Lemma}\n\\newtheorem{proposition}[theorem]{Proposition}\n\\newtheorem{corollary}[theorem]{Corollary}\n\n\n\\title{Topology and Geometry of Deep Rectified Network Optimization Landscapes }\n\n\n\\author{C. Daniel Freeman \\thanks{ See our github page at PAGEGOHERE} \\\\\nDepartment of Physics\\\\\nUniversity of California at Berkeley\\\\\nBerkeley, CA 94720, USA \\\\\n\\texttt{daniel.freeman@berkeley.edu} \\\\\n\\And\nJoan Bruna \\\\\nCourant Institute of Mathematical Sciences \\\\\nNew York University \\\\\nNew York, NY 10011, USA \\\\\n\\texttt{bruna@cims.nyu.edu} \\\\\n}\n\n% The \\author macro works with any number of authors. There are two commands\n% used to separate the names and addresses of multiple authors: \\And and \\AND.\n%\n% Using \\And between authors leaves it to \\LaTeX{} to determine where to break\n% the lines. Using \\AND forces a linebreak at that point. So, if \\LaTeX{}\n% puts 3 of 4 authors names on the first line, and the last on the second\n% line, try using \\AND instead of \\And before the third author name.\n\n\\newcommand{\\fix}{\\marginpar{FIX}}\n\\newcommand{\\new}{\\marginpar{NEW}}\n\n%\\iclrfinalcopy % Uncomment for camera-ready version\n\n\\begin{document}\n\n\n\\maketitle\n\n\\begin{abstract}\nThe loss surface of deep neural networks has recently attracted interest \nin the optimization and machine learning communities as a prime example of \nhigh-dimensional non-convex problem. Some insights were recently gained using spin glass \nmodels, but at the expense of strongly simplifying the nonlinear nature of the model.\n\nIn this work, we do not make any such assumption and study conditions \non the data distribution and model architecture that prevent the existence \nof bad local minima. Our theoretical work quantifies and formalizes two \nimportant qualitative facts: (i) the landscape of deep linear networks is radically different \nfrom that of deep half-rectified ones, thus implying that mean-field approximations\nare unable to capture essential nonlinear behavior, and (ii) that the energy landscape \nin the non-linear case is fundamentally controlled by the interplay between the smoothness of the data distribution and model over-parametrization. \nThese results are in accordance with empirical practice and recent literature. \n%Together with \n%recent results that rigorously establish that no gradient descent can \n%get stuck on saddle points, we conclude that gradient descent converges\n%to a global optimum in deep rectified networks. \n\nThe conditioning of gradient descent is the next challenge we address. \nWe study this question by estimating the geometry of level sets, and we introduce\nan algorithm to estimate the regularity of such sets on large-scale networks. \nOur empirical results show that these level sets remain connected throughout \nall the learning phase, but they become exponentially more curvy \nas the energy level decays, in accordance to what is observed in practice with \nvery low curvature attractors.\n\\end{abstract}\n\n%\\tableofcontents\n\n%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%\n\\section{Introduction}\n\\label{sec:Intro}\n%%%%%%%%%%%%%%%%%%%%%%\n\n\\begin{itemize}\n\\item Context of the problem\n\\item Related work: Spin glass, recent results from Shamir. Gradient Descent converges to minimizers (Jordan Recht et al). \n\\item Topology of the level sets. Main result on connectedness of level sets.\n\\item Geometry of the level sets. Algorithm to estimate the geodesics along level sets. Measure of curvature of these sets. \n\\end{itemize}\n  \n\n\n\\section{Topology of Level Sets}\n\nLet $P$ be a probability measure on a product space $\\mathcal{X} \\times \\mathcal{Y}$, \nwhere we assume $\\mathcal{X}$ and $\\mathcal{Y}$ are Euclidean vector spaces for simplicity.\nLet $\\{ (x_i, y_i)\\}_i$ be an iid sample of size $L$ drawn from $P$ defining the training set.\nWe consider the classic empirical risk minimization of the form\n\\begin{equation}\n\\label{emp_risk_min}\n\\Fem(\\theta) = \\frac{1}{L} \\sum_{l=1}^L \\| \\Phi(x_i;\\theta) - y_i \\|^2~,\n\\end{equation}\nwhere $\\Phi(x ; \\theta)$ encapsulates the feature representation \nthat uses parameters $\\theta \\in \\R^S$. In a deep neural network, this parameter\ncontains the weights and biases used in all layers.\nFor convenience, in our analysis we will also use the oracle risk minimization:\n\\begin{equation}\n\\label{risk_min}\n\\Forr(\\theta) = \\E_{(X,Y) \\sim P} \\| \\Phi(X;\\theta) - Y \\|^2~,\n\\end{equation}\n\nWe define the level set of $F(\\theta)$ as \n\\begin{equation}\n\\Omega_F(\\lambda) = \\{ \\theta \\in \\R^S~;~F(\\theta) \\leq \\lambda \\}~. \n\\end{equation}\n\nThe first question we study is the structure of critical points of $\\Fem(\\theta)$ and $\\Forr(\\theta)$\nwhen $\\Phi$ is a multilayer neural network. In particular, we are interested to know whether\n$\\Fem$ has local minima which are not global minima. This question is answered by \nknowing whether $\\Omega_F(\\lambda)$ is connected at each energy level $\\lambda$:\n\n\\begin{proposition}\nIf $\\Omega_F(\\lambda)$ is connected for all $\\lambda$ then every local minima of $F(\\theta)$ is a global minima. \n\\end{proposition}\n{\\it Proof:} Suppose that $\\theta_1$ is a local minima and $\\theta_2$ is a global minima, \nbut $F(\\theta_1) > F(\\theta_2)$. If $\\lambda = F(\\theta_1)$, then clearly \n$\\theta_1$ and $\\theta_2$ both belong to $\\Omega_F(\\lambda)$. Suppose \nnow that $\\Omega_F(\\lambda)$ \nis connected. Then we could find a smooth (i.e. continuous and differentiable) path $\\gamma(t)$ \nwith $\\gamma(0) = \\theta_1$, $\\gamma(1)= \\theta_2$ and $F(\\gamma(t)) \\leq \\lambda = F(\\theta_1)$.\nIn particular, as $t \\to 0$, we have\n\\begin{eqnarray*}\nF(\\gamma(t)) &=& F(\\theta_1) + t \\langle \\nabla F(\\theta_1) , \\dot{\\gamma}(0) \\rangle + \\frac{t^2}{2} \\left(\\dot{\\gamma}(0)^T H F(\\theta_1) \\dot{\\gamma}(0) + \\langle \\nabla F(\\theta_1), \\ddot{\\gamma}(0) \\rangle \\right) + o(t^2) \\\\\n&=& F(\\theta_1) +   \\frac{t^2}{2}  \\dot{\\gamma}(0)^T H F(\\theta_1) \\dot{\\gamma}(0)  + o(t^2) ~,\n\\end{eqnarray*}\nwhich shows that $F(\\gamma(t)) \\leq F(\\theta_1)$ for all $t$ is incompatible with $H(\\theta_1) \\succeq 0$. $\\square$\n\n\n\\subsection{The Linear Case}\n\nA particularly simple but insightful case is \nwhen $F$ is a multilayer network defined by\n\\begin{equation}\n\\label{linearcase}\n\\Phi(x;\\theta) = W_K \\dots W_1 x~,~\\theta = (W_1, \\dots, W_K)~.\n\\end{equation}\nThis model defines a non-convex (and non-concave) loss $\\Fem(\\theta)$.\nIt has been shown in \\cite{ganguli} and \\cite{linearcase} (concurrently with our work) that in this case, \nevery local minima is a global minima.  \nFor completeness, we provide here an alternative proof of that result.\n\n%For that purpose, let $W_1, W_2, \\dots, W_K$ be weight matrices of sizes \n%$n_k \\times n_{k+1}$, $k < K$. Assume first that $n_j \\geq \\min(n_1, n_K)$ for $j=2 \\dots K-1$.\n%and let us define the following multilinear regression problem:\n%\\begin{equation}\n%\\label{multilinloss}\n%L_0(W_1, \\dots, W_K) = \\sum_i \\| W_K, \\dots W_1 x_i - y_i \\|^2~,\n%\\end{equation}\n%where $\\{ (x_i, y_i)\\,; x_i \\in \\mathbb{R}^{n_1}, y_i \\in \\mathbb{R}^{n_K} \\}_i$ is a given \n%training set. \n\nWe have the following result.\n\\begin{proposition}\n\\label{proplinear}\nLet $W_1, W_2, \\dots, W_K$ be weight matrices of sizes \n$n_k \\times n_{k+1}$, $k < K$, and let $\\Fem(\\theta)$, $\\Forr(\\theta)$ \ndenote the risk minimizations using $\\Phi$ as in (\\ref{linearcase}).\nAssume that $n_j \\geq \\min(n_1, n_K)$ for $j=2 \\dots K-1$ [TODO I think this is not necessary].\nThen $\\Omega_{\\Fem}(\\lambda)$ is connected for all $\\lambda$, as well as $\\Omega_{\\Forr}$, \nand therefore there are no poor local minima.  \n\\end{proposition}\n{\\it Proof:} We proceed by induction over the number of layers $K$. \nFor $K=1$, the loss $F(\\theta)$ is convex. Let  $\\theta_1$, $\\theta_2$ be two arbitrary points \nin a level set $\\Omega_\\lambda$. Thus $L(\\theta_1) \\leq \\lambda$ and $L(\\theta_2) \\leq \\lambda$. We have\n$$L( t \\theta_1 + (1-t) \\theta_2) \\leq t L(\\theta_1) + (1-t) L(\\theta_2) \\leq \\lambda~,$$\nand thus a linear path is sufficient in that case to connect $\\theta_1$ and $\\theta_2$.\n\nSuppose the result is true for $K-1$. Let $\\theta_1 = (W_1^1, \\dots, W^1_K)$ and \n $\\theta_2 = (W_1^2, \\dots, W^2_K)$ with $L(\\theta_1) \\leq \\lambda$, $L(\\theta_2) \\leq \\lambda$.\nFor each $W_1, \\dots, W_K$, we denote $\\tilde{W}_j = W_j$ for $j < K-1$ and\n$\\tilde{W}_{K-1} = W_K W_{K-1}$. By induction hypothesis, the \nloss expressed in terms of $\\tilde{\\theta} = (\\tilde{W}_1, \\dots, \\tilde{W}_{K-1})$ is connected \nbetween $\\tilde{\\theta}_1$ and $\\tilde{\\theta_2}$. Let $\\tilde{W}_{K-1}(t)$ the corresponding \npath projected in the last layer. We just need to produce a path in the variables $W_{K-1}(t)$, $W_K(t)$ \nsuch that (i) $W_{K-1}(0) = W_{K-1}^1$, $W_{K-1}(1) = W_{K-1}^2$, \n(ii) $W_{K}(0) = W_{K}^1$, $W_{K}(1) = W_{K}^2$, and \n(iii) $W_{K}(t) W_{K-1}(t) = \\tilde{W}_{K-1}(t)$ for $t \\in (0,1)$. \nWe construct it as follows. Let \n$$W_{K}(t) = t W_{K}^2 + (1-t) W_{K}^1 + t (1-t) V~,$$\n$$W_{K-1}(t) = W_{K}(t)^\\dagger \\tilde{W}_{K-1}(t)  ~,$$\nwhere $W_{K}(t)^\\dagger = ( W_{K}(t)^T W_{K}(t))^{-1} W_{K}(t)^T$ denotes the pseudoinverse \nand $V$ is a $n_{K-1} \\times n_{K}$ matrix drawn from a iid distribution. \nConditions (i) and (ii) are immediate from the definition, and condition (iii) results from the fact that \n$$W_{K}(t) W_{K}(t)^\\dagger  = {\\bf I}_{N_K}~,$$\nsince $W_K(t)$ has full rank for all $t \\in (0,1)$. \n$\\square$.\n\n\\subsection{Half-Rectified Nonlinear Case}\n\nWe now study the setting given by \n\\begin{equation}\n\\label{relucase}\n\\Phi(x;\\theta) = W_K \\rho W_{K-1} \\rho \\dots \\rho W_1 x~,~\\theta = (W_1, \\dots, W_K)~,\n\\end{equation}\nwhere $\\rho(z) = \\max(0 ,z)$. \nThe biases can be implemented by replacing the input vector $x$ \nwith $\\overline{x}=(x, 1)$ and by rebranding each parameter matrix as \n$$\\overline{W}_i = \\left( \n\\begin{array}{c|c}\nW_i & b_i \\\\\n\\hline \n0 & 1 \n\\end{array}\n\\right)~,$$\nwhere $b_i$ contains the biases for each layer.\t\nFor simplicity, we continue to use $W_i$ and $x$ in the following.\n\nOne may wonder whether the same phenomena of global connectedness also holds \nin the half-rectified case. A simple motivating counterexample shows that this is not the case in \ngeneral. Consider a simple setup with $X \\in \\R^2$ drawn from a mixture of two Gaussians $\\mathcal{N}_{-1}$ \nand $\\mathcal{N}_{1}$, and let $Y = (X-\\mu_Z) \\cdot Z $ , where $Z$ is the (hidden) mixture component taking $\\{1,-1\\}$ values.  Let \n$\\hat{Y} = \\Phi(X; \\{ W_1, W_2\\} )$ be a single-hidden layer ReLU network, with two hidden units, \nillustrated in Figure ??. \n%Since the model is homogeneous, one can think about $W_1$ as encoding two unitary vectors without loss of generality. \nLet $\\theta^A$ be a configuration that bisects the two mixture components, \nand let $\\theta^B$ the same configuration, but swapping the bisectrices. \nOne can verify that they can both achieve arbitrarily small risk by letting the covariance of the mixture components go to $0$. \nHowever, any path that connects $\\theta^A$ to $\\theta^B$ \nmust necessarily pass through a point in which $W_1$ has rank $1$, which leads to an estimator with risk at least $1/2$.  \n\nIn fact, it is easy to see that this counter-example can be extended to any generic half-recitifed architecture, if one is \nallowed to adversarially design a data distribution. For any given $\\Phi(X; \\theta)$ with arbitrary architecture and current parameters \n$\\theta = (W_i)$, let $\\mathcal{P}_\\theta=\\{ \\mathcal{A}_1, \\dots, \\mathcal{A}_S\\}$ be the underlying tesselation of the input space given by our current choice of parameters; that is, $\\Phi(X; \\theta)$ is piece-wise linear and $\\mathcal{P}_\\theta$ contains those pieces. Now let \n$X$ be any arbitrary distribution with density $p(x) > 0$ for all $x \\in \\R^n$, for example a Gaussian, and let %$Y ~|~ \\{X \\in \\mathcal{A}_s\\} = s$. \n%It is the indicator function corresponding to the tesselation $\\mathcal{P}$. \n$Y ~|~X = \\Phi(X ; \\theta)$~. Since $\\Phi$ is invariant under permutations $\\theta_\\sigma$ of its hidden layers, it is easy to see that one can find two parameter values $\\theta_A = \\theta$ and $\\theta_B = \\theta_\\sigma$ such that $\\Forr(\\theta_A) = \\Forr(\\theta_B) = 0$, but any continuous path $\\gamma(t)$ from $\\theta_A$ to $\\theta_B$ will have a different tesselation and therefore won't satisfy $\\Forr( \\gamma(t) ) = 0$. \n \nThis illustrates an intrinsic difficulty in the optimization landscape if one is after \\emph{universal} \nguarantees that do not depend upon the data distribution. This difficulty is non-existent in the linear case \nand not easy to exploit in mean-field approaches such as \\cite{choromaska}, but \nis easily detected as soon as one considers a non-linear model, and shows that in general \nwe should not expect to obtain connected level sets. However, \nconnectedness can be recovered if one is willing to accept a small increase \nof energy. Our main result shows that the amount by which the energy is \nallowed to increase is upper bounded by a quantity that trades-off model overparametrization \nand smoothness in the data distribution.\n\nFor that purpose, we start with a characterization of the oracle loss, and for simplicity let us assume \n$Y \\in \\R$. \nLet us first describe the case with a single hidden layer of size $m$, and let\n\\begin{equation}\n\\label{bla2}\ne(m) = \\min_{W_1 \\in \\R^{m \\times n}, W_2 \\in \\R^m} \\E\\{ | \\Phi(X; \\theta) - Y|^2 \\}~.\n\\end{equation}\nIt is a well known result by Hornik and Cybenko that a single hidden layer \nis a universal approximator under very mild assumptions, i.e. $\\lim_{m \\to \\infty} e(m) = 0$.\nThis result merely states that our statistical setup is consistent. A more interesting \nquestion is the rate at which $e(m)$ decays, which clearly depends \non the smoothness of the joint density $(X, Y) \\sim P$. \n\nOur main result considers now a non-asymptotic scenario given by some \nsize $M$ of the hidden layer. Given two parameter values $\\theta^A = (W_1^A, W_2^A) \\in \\mathcal{W}$ \nand $\\theta^B= (W_1^B, W_2^B)$ with $\\Forr(\\theta^{\\{A,B\\} } ) \\leq \\lambda$, \nwe show that there exists a continuous path \n$\\gamma: [0,1] \\to \\mathcal{W}$ connecting $\\theta^A$ and $\\theta^B$ \nsuch that its risk is uniformly bounded by $\\lambda + \\epsilon$, where $\\epsilon$ \ndecreases with model overparametrization and with the decay rate of $e(m)$.\n\\begin{theorem}\n\n\\end{theorem}\n\n\n\n\n%\\begin{theorem}\n%Let $W_1, W_2, \\dots, W_K$ be weight matrices of sizes \n%$n_k \\times n_{k+1}$, $k < K$, and let $\\Fem(\\theta)$, $\\Forr(\\theta)$ \n%denote the risk minimizations using $\\Phi$ as in (\\ref{relucase}).\n%Assume that $n_j \\geq \\min(n_1, n_K)$ for $j=2 \\dots K-1$ [TODO I think this is not necessary].\n%Then $\\Omega_{\\Forr}(\\lambda)$ is connected for all $\\lambda$. \n%\\end{theorem}\n%{\\it Proof:}\n%We will again prove the result by induction over the depth $K$. \n%Suppose first that $K=2$. The oracle risk is \n%$$\\Forr( W_1, W_2) = \\Exp{ \\| W_2 \\rho W_1 X - Y \\|^2}~.$$\n%If we denote $X_{W_1} = \\rho W_1 X$, let us verify that $\\Forr(W_1, W_2)$ \n%only depends upon the correlation operator of $X_{W_1}$ \n%and its cross-correlation to $Y$. Indeed, we have\n%\\begin{eqnarray*}\n%\\Exp{ \\| W_2 \\rho W_1 X - Y \\|^2} &=& \\Exp{ \\| W_2 X_{W_1} - Y \\|^2} \\\\\n%&=& W_2 \\Sigma_{W_1} W_2^T + \\Sigma_Y - 2  Tr\\left( W_2 \\Sigma_{W_1,Y} \\right)~,\n%\\end{eqnarray*}\n%where $\\Sigma_{W_1} = \\Exp{ X_{W_1} X_{W_1}^T}$ and $\\Sigma_{W_1,Y} = \\Exp{ X_{W_1} Y^T}$.\n%Let us see that when $\\rho(z)$ is the half-rectification the covariance structure \n%of $X_{W_1}$ can be easily related to the original distribution. Indeed, we have\n%the following\n%\\begin{lemma}\n%Let $Z = \\rho W X$ with $\\rho(z) = \\max(0,z)$. Then\n%\\begin{equation}\n%\\Sigma_Z = \\tilde{W}^T \\Sigma_X \\tilde{W} \n%\\end{equation}\n%\\end{lemma}\n%\n%$\\square$\n\n\n\n[ TODO  $\\Fem$ case]. \n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%\n\\section{Geometry of Level Sets}\n%\\section{Quantifying Nonconvexity}\n\\label{sec:QuanNoncon}\n\n\\subsection{The Greedy Algorithm}\n\\label{sec:GreedyAlg}\n%%%%%%%%%%%%%%%%%%%%%%\n\n For a pair of models with network parameters $\\theta_i$, $\\theta_j$, each with $F_e(\\theta)$ below a threshold $L_0$, we aim to efficienly generate paths in the space of weights where the empirical loss along the path remains below the threshold.  These paths are continuous curves belonging to $\\Omega_F(\\lambda)$--that is, the level sets of the loss function of interest.\n  \n We provide a greedy algorith, Dynamic String Sampling, which finds such a path below.\n\n\\begin{algorithm}\n\\caption{Greedy Dynamic String Sampling}\\label{euclid}\n\\begin{algorithmic}[1]\n\\State $\\text{$L_0$} \\gets \\text{Threshold below which path will be found}$\n\\State $\\text{$\\Phi_1$} \\gets \\text{randomly initialize } $$\\theta_1$$ \\text{, train } $$\\Phi (x_i\\;\\theta_1)$$ \\text{ to $L_0$}$\n\\State $\\text{$\\Phi_2$} \\gets \\text{randomly initialize } $$\\theta_2$$ \\text{, train } $$\\Phi (x_i\\;\\theta_2)$$ \\text{ to $L_0$}$\n\n\\State $\\text{BeadList} \\gets $$(\\Phi_1,\\Phi_2)$\n\\State $\\text{Depth} \\gets 0$ \n\n\\Procedure{FindConnection}{$\\Phi_1,\\Phi_2$}\n\\State $\\text{$t^*$} \\gets \\text{t such that } $$\\frac{d \\gamma(\\theta_1, \\theta_2, t)}{dt} \\bigg|_{t} = 0$$  \\text{ OR } $$t = 0.5$$ $\n\\State $\\text{$\\Phi_3$} \\gets \\text{train } $$\\Phi(x_i; t^*\\theta_1 + (1-t^*)\\theta_2)$$ \\text{ to $L_0$}$\n\\State $\\text{BeadList} \\gets \\text{insert}$$(\\Phi_3$$\\text{, after } $$\\Phi_1$$\\text{, BeadList)}$\n\\State $\\text{$MaxError_1$} \\gets \\text{$max_t$}$$(F_e(t\\theta_3 + (1-t)\\theta_1))$$ $\n\\State $\\text{$MaxError_2$} \\gets \\text{$max_t$}$$(F_e(t\\theta_2 + (1-t)\\theta_3))$$ $\n\\If {$\\text{$MaxError_1$} > \\text{$L_0$ }} \\text{ }\\Return \\text{ FindConnection}$$(\\Phi_1,\\Phi_3)$$ $\n\\EndIf\n\\If {$\\text{$MaxError_2$} > \\text{$L_0$ }} \\text{ }\\Return \\text{ FindConnection}$$(\\Phi_3,\\Phi_2)$$ $\n\\EndIf\n\\State $\\text{Depth} \\gets \\text{Depth$+1$}$ \n\\EndProcedure\n\\end{algorithmic}\n\\end{algorithm}\n \n  The algorithm recursively builds a string of models in the space of weights which continuously connect $\\theta_i$ to $\\theta_j$.  Models are added and trained until the pairwise linearly interpolated loss, i.e. $\\rm{max}_t F_e(t\\theta_i\\ +\\ (1-t)\\theta_j)$ for $t\\in(0,1)$, is below the threshold, $L_0$, for every pair of neighboring models on the string.  We provide a cartoon of the algorithm in \\figref{fig:AlgorithmFigure}.\n \n \\begin{figure}\n\\begin{center}\n\\scalebox{1}{\\includegraphics[width=1.0\\columnwidth]{AlgorithmFigure}}\n\\end{center}\n\\caption{A cartoon of the algorithm.  $a):$ The initial two models with approximately the same loss, $L_0$. $b):$ The interpolated loss curve, in red, and its global maximum, occuring at $t=t^*$. $c):$ The interpolated model $\\Theta(\\theta_i, \\theta_j, t^*)$ is added and labeled $\\theta_{i,j}$.  $d):$ Stochastic gradient descent is performed on the interpolated model until its loss is below $\\alpha L_0$. $e):$ New interpolated loss curves are calculated between the models, pairwise on a chain.  $f):$ As in step $c)$, a new model is inserted at the maxima of the interpolated loss curve between $\\theta_i$ and $\\theta_{i,j}$.  $g):$  As in step $d)$, gradient descent is performed until the model has low enough loss.}\n\\label{fig:AlgorithmFigure}\n\\end{figure}\n \n  \n  \\subsection{Failure Conditions and Practicalities}\n  \\label{sec:Fail}\n  \n  While the algorithm presented will faithfully certify two models are connected if the algorithm converges, it is worth emphasizing that the algorithm does not guarantee that two models are disconnected if the algorithm fails to converge.  In general, the problem of determining if two models are connected can be made arbitrarily difficult by choice of a particularly pathological geometry for the loss function, so we are constrained to heuristic arguments for determining when to stop running the algorithm.  Thankfully, in practice, loss function geometries for problems of interest are not intractably difficult to explore.  We comment more on diagnosing disconnections more carefully in section SYMMETRYDISCONNECT.\n  \n  Further, if the $\\rm{\\mathbf{MaxError}}$ exceeds $L_0$ for every new recursive branch as the algorithm progresses, the worst case runtime scales as $O(\\rm{exp}(\\rm{\\mathbf{Depth}}))$.  Empirically, we find that the number of new models added at each depth does grow, but eventually saturates, and falls for a wide variety of models and architectures, so that the typical runtime is closer to $O(\\rm{poly}(\\rm{\\mathbf{Depth}}))$---at least up until a critical value of $L_0$.  We comment more on this in section NUMERICALDISCUSSION.\n  \n  Finally, we find that training $\\Phi_3$ to $\\alpha L_0$ for $\\alpha < 1$ in line $8$ of the algorithm tends to aid convergence without noticeably impacting our numerics.\n \n\n \n %%%%%%%%%%%%%%%%%%%%%%\n\\section{Numerical Experiments}\n\\label{sec:NumExp}\n\nFor our numerical experiments, we aimed to extract qualitative features of both small, toy networks, as well as of larger workhorse networks suitable for use on real world tasks (e.g. MNIST).  At its core, the maximum interpolated error (i.e., \\eqref{eq:minmaxerror}) is a measure of problem nonconvexity---or, more precisely, of the nonconvexity of the loss surface of a given architecture on a particular learning problem.\n\n\n\\subsection{Polynomial Regression}\n\\label{sec:PolyFuncs}\n%%%%%%%%%%%%%%%%%%%%%%\n\n Polynomial function regression is a task for which small neural networks can achieve extremely high accuracy.  For our numerical experiments, we studied a 1-4-4-1 fully connected multilayer perceptron style architecture with RELU activation and RMSProp optimization.  For ease-of-analysis, we restricted the family of polynomials to be strictly contained in the interval $x\\in[0,1]$ and $f(x)\\in[0,1]$.\n \n Discussion of different Loss functions\n \n etc.\n\n\n%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Convolutional Neural Networks}\n\\label{sec:CNN}\n%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n%Exploitation\n\\begin{figure}\n\\label{figurelength}\n\\centering\n\\includegraphics[width=.4\\textwidth]{Plots/normlengthcubics}\n\\includegraphics[width=.4\\textwidth]{Plots/normlengthMNIST}\n\\caption{Normalized geodesic length as a function of the energy level for two different models. Left: a ``low-dimensional\" neural network \nattempting to fit a cubic polynomial. Right: a convolutional neural network on MNIST. Whereas the cubic fitting displays a heavily non-convex structure \nat mid-energy values, the MNIST example qualitatively behaves as a convex loss, in which geodesics approach straight lines.}\n\\end{figure}\n\n\n%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%\n\\section{Discussion}\n\\label{sec:Discussion}\n%%%%%%%%%%%%%%%%%%%%%%\n\\begin{itemize}\n\\item Future: Generalization Error Question. \n\n\\end{itemize}\n\n\n\\subsubsection*{Acknowledgments}\n\nUse unnumbered third level headings for the acknowledgments. All\nacknowledgments, including those to funding agencies, go at the end of the paper.\n\n\\appendix\n\n\\section{Constrained Dynamic String Sampling}\n  \\label{sec:ConstrainedAlg}\n  \n  While the algorithm presented in Sec. \\ref{sec:GreedyAlg} is fast for sufficiently smooth families of loss surfaces with few saddle points, here we present a slightly modified version which, while slower, provides more control over the convergence of the string.  Instead of training intermediate models via full SGD to a desired accuracy, intermediate models will be subject to a constraint that ensures they are ``close'' to the neighboring models on the string.  Specifically, intermediate models will be constrained to the unique hyperplane in weightspace equidistant from its two neighbors.  This is similar to a sort of ``$L_1$ regularization'' where the loss function for a given model on the string, $\\theta_i$, has an additional term $\\tilde{L}(\\theta) = L(\\theta)+\\zeta(\\|\\theta_{i-1} - \\theta_i\\|+\\|\\theta_{i+1} + \\theta_i\\|)$.  The strength of the $\\zeta$ regularization term controls the ``springy-ness'' of the weightstring. note: make this more precise, the hyperplane constraint is stronger than the $L_1$ constraint...$L_1$ only keeps the model in a ball close to the midpoint between the models.\n  \n  Because adapting DSS to use this constraint is straightforward, here we will describe an alternative ``breadth-first'' approach wherein models are trained in parallel until convergence.  This alternative approach has the advantage that it will indicate a disconnection between two models ``sooner'' insofar as it will be clear two models cannot be connected once the loss on either of the two initial models, $\\theta_1$ or $\\theta_2$, is less than $\\Gamma(\\theta_1, \\theta_2)$.  The precise geometry of the loss surface will dictate which approach to use in practice.\n  \n  Given two random models $\\sigma_i$ and $\\sigma_j$ where $|\\sigma_i - \\sigma_j| < \\kappa$, we aim to follow the evolution of the family of models connecting $\\sigma_i$ to $\\sigma_j$.  Intuitively, almost every continuous path in the space of random models connecting $\\sigma_i$ to $\\sigma_j$ has, on average, the same (high) loss.  For simplicity, we choose to initialize the string to the linear segment interpolating between these two models.  If this entire segment is evolved via gradient descent, the segment will either evolve into a string which is entirely contained in a basin of the loss surface, or some number of points will become fixed at a higher loss.  These fixed points are difficult to detect directly, but will be indirectly detected by the persistence of a large interpolated loss between two adjacent models on the string.\n  \n  The algorithm proceeds as follows:\n  \n  (0.) Initialize model string to have two models, $\\sigma_i$ and $\\sigma_j$.\n  \n  1. Begin training all models to the desired loss, keeping the instantaneous loss of all models being trained approximately constant..\n  \n  2. If the pairwise interpolated loss $\\gamma(\\sigma_n,\\sigma_{n+1})$ exceeds a tolerance $\\alpha_1$, insert a new model at the maximum of the interpolated loss between these two models.  For simplicity, this tolerance is chosen to be $(1 + \\alpha_1^*)$ times the instantaneous loss of all other models on the string.  \n  \n  3. Repeat steps (1) and (2) until all models (and interpolated errors) are below a threshold loss $L_0$, or until a chosen failure condition (see \\ref{sec:Fail}).\n\n\n\n\\bibliography{iclr2017_conference}\n\\bibliographystyle{iclr2017_conference}\n\n\\end{document}\n", "meta": {"hexsha": "fdf42f50e89cfc1e8540aa6e5a7c8a79b92e6f95", "size": 27939, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Writeup/iclr/iclr2017_conference.tex", "max_stars_repo_name": "danielfreeman11/convex-nets", "max_stars_repo_head_hexsha": "252a8230845fb2076221113ac8cabfade5152bfb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-08-09T00:48:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-03T09:04:59.000Z", "max_issues_repo_path": "Writeup/iclr/iclr2017_conference.tex", "max_issues_repo_name": "danielfreeman11/convex-nets", "max_issues_repo_head_hexsha": "252a8230845fb2076221113ac8cabfade5152bfb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Writeup/iclr/iclr2017_conference.tex", "max_forks_repo_name": "danielfreeman11/convex-nets", "max_forks_repo_head_hexsha": "252a8230845fb2076221113ac8cabfade5152bfb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.1159695817, "max_line_length": 1115, "alphanum_fraction": 0.7163463259, "num_tokens": 8311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.3317806413173664}}
{"text": "\\section{Setting the target domain} \\label{sec:domain}\n%=======================================================================\n\nIn this section, the number of grids, and the target domain and its relationship with the MPI process are explained.\nThe calculation domain is determined by the horizontal grid spacing and the number of grid points.\nThe parallelization is implemented by a 2D domain decomposition in the horizontal directions.\n\nFigure \\ref{fig:domain} shows an example of this relationship.\nThe total numbers of grids are specified by \\nmitem{IMAXG, JMAXG} in \\namelist{PARAM_ATMOS_GRID_CARTESC_INDEX}.\nThe entire domain is divided into \\nmitem{PRC_NUM_X} along the X direction and \\nmitem{PRC_NUM_Y} in the Y direction; the \\nmitem{PRC_NUM_X} and \\nmitem{PRC_NUM_Y} are specified in \\namelist{PARAM_PRC_CARTESC}.\nThe process number starts zero and is numbered in order from the bottom left to the top right (Arrow in Fig. \\ref{fig:domain}).\nEach sub-domain is managed by an MPI process, each of which takes charge of a grid block of \\nmitem{IMAX} $\\times$ \\nmitem{JMAX} $\\times$ \\nmitem{KMAX},\nwhere \\nmitem{KMAX} is the number of grids along the vertical direction specified in \\namelist{PARAM_ATMOS_GRID_CARTESC_INDEX}.\nCare is taken to ensure that \\nmitem{IMAX} and \\nmitem{JMAX} must be identical for all MPI processes.\nTherefore, \\nmitem{PRC_NUM_X} and \\nmitem{PRC_NUM_Y} must be a divisor of \\nmitem{IMAXG} and \\nmitem{JMAXG}, respectively.\n\nThe total number of grids along each horizontal direction and that in the entire domain are summarized as\n\\begin{eqnarray}\n  && \\nmitemeq{IMAXG} = \\nmitemeq{IMAX} \\times \\nmitemeq{PRC_NUM_X}\n  \\label{eq:xgridnum}\\\\\n  && \\nmitemeq{JMAXG} = \\nmitemeq{JMAX} \\times \\nmitemeq{PRC_NUM_Y}.\n  \\label{eq:ygridnum}\\\\\n&& \\verb|Total number of grids in the domain| \\nonumber\\\\\n&&\\quad = \\nmitemeq{IMAXG} \\times \\nmitemeq{JMAXG} \\times \\nmitemeq{KMAX}, \\nonumber\\\\\n&&\\quad = \\left(\\nmitemeq{IMAX} \\times \\nmitemeq{PRC_NUM_X}\\right)\n          \\times (\\nmitemeq{JMAX} \\times \\nmitemeq{PRC_NUM_Y})\n          \\times (\\nmitemeq{KMAX} ).\n\\end{eqnarray}\nWhen \\nmitem{IMAXG} and \\nmitem{JMAXG} are specified, \\nmitem{IMAX} and \\nmitem{JMAX} are internally calculated.\nAlternatively, user can specify \\nmitem{IMAX} and \\nmitem{JMAX} instead of \\nmitem{IMAXG} and \\nmitem{JMAXG}.\nIn this case, \\nmitem{IMAXG} and \\nmitem{JMAXG} are internally calculated by using Eqs. (\\ref{eq:xgridnum}) and (\\ref{eq:ygridnum}), respectively.\n\n\n\nThe size of the entire domain is determined as follows:\n\\begin{eqnarray}\n \\verb|Domain length in the X direction| &=& \\nmitemeq{IMAXG} \\times \\nmitemeq{DX}\\\\\n \\verb|Domain length in the Y direction| &=& \\nmitemeq{IMAXG} \\times \\nmitemeq{DY},\n\\end{eqnarray}\nwhere \\nmitem{DX, DY} is grid spacings specified in \\namelist{PARAM_ATMOS_GRID_CARTESC} as described in subsection \\ref{subsec:gridinterv}.\n\n\nIn order to perform a horizontal-vertical two-dimensional experiment, set both the \\nmitem{IMAXG} and \\nmitem{PRC_NUM_X} to 1.\nIn this case, the motion in the Y-Z section is calculated.\nThe value of \\texttt{DX} does not affect the simulation result.\n\nIn the next subsections, the number of grids, the grid interval, and the configuration of the MPI processes are described in more detail.\n\\textcolor{blue}{Note that it is necessary that these settings must be identical among the configuration files for \\texttt{scale-rm\\_pp},  \\texttt{scale-rm\\_init}, and \\texttt{scale-rm}}.\n\n\\begin{figure}[h]\n\\begin{center}\n  \\includegraphics[width=0.8\\hsize]{./../../figure/domain_decomposition.pdf}\\\\\n  \\caption{Relation between horizontal grid interval (\\texttt{DX}, \\texttt{DY}),\n   the number of grids (\\nmitem{IMAX}, \\nmitem{JMAX}) per MPI process,\n   the total number of grids (\\nmitem{IMAXG}, \\nmitem{JMAXG}) in the entire domain,\n   and the number of MPI processes (\\nmitem{PRC_NUM_X}, \\nmitem{PRC_NUM_Y}).\n   The blue part corresponds to a region managed by an MPI process.\n   The six digit number following ``pe'' indicates the process number.}\n  \\label{fig:domain}\n\\end{center}\n\\end{figure}\n\n%-----------------------------------------------------------------------\n\\subsection{Setting the number of horizontal and vertical grids} \\label{subsec:relation_dom_reso3}\n%-----------------------------------------------------------------------\n\nThe number of grids is specified in \\namelist{PARAM_ATMOS_GRID_CARTESC_INDEX} in the configuration files.\n\\editboxtwo{\n\\verb|&PARAM_ATMOS_GRID_CARTESC_INDEX| & \\\\\n\\verb| KMAX  = 97,|  & ; Number of vertical layers \\\\\n\\verb| IMAXG = 40,|  & ; Total number of grids along the {\\XDIR} \\\\\n\\verb| JMAXG = 25,|  & ; Total number of grids along the {\\YDIR} \\\\\n\\verb|/|\\\\\n}\n\n%-----------------------------------------------------------------------\n\\subsection{Setting grid intervals along the horizontal and vertical directions} \\label{subsec:gridinterv}\n%-----------------------------------------------------------------------\n\nExcluding the buffer region explained in Section \\ref{subsec:buffer}, the horizontal grid intervals are configured only equidistantly, whereas the vertical grid intervals are configured freely.\nWhen the grid intervals are configured uniformly along all directions, specify the grid intervals for the x, y, and z directions with \\nmitem{DX, DY, DZ} in \\namelist{PARAM_ATMOS_GRID_CARTESC}, respectively.\nThe unit is [m].\n\\editboxtwo{\n\\verb|&PARAM_ATMOS_GRID_CARTESC  | & \\\\\n\\verb| DX = 500.D0,| & ; Grid interval along the {\\XDIR} \\\\\n\\verb| DY = 500.D0,| & ; Grid interval along the {\\YDIR} \\\\\n\\verb| DZ = 500.D0,| & ; Grid interval along the vertical (Z) direction\\\\\n\\verb|/|\\\\\n}\n\nAn arbitrary non-uniform grid can be specify in the vertical direction.\nSince the model employs the C-grid system, the points of definition for the velocity vector and other scalars are staggered, deviating by a half grid.\nIn this document, the scalar location is called the center point and the half-grid-deviated location the face point.\nRefer to Figure \\ref{fig:scale_grid} for the details.\nThe face point of the vertical grids can be specified with \\nmitem{FZ(:)} in \\namelist{PARAM_ATMOS_GRID_CARTESC} as an array \\footnote{In this case, the same precision as used in the simulation is recommended to be specified. By default, the model is compiled as a double-precision floating point model.}.\nNote that the number of elements specified in \\nmitem{FZ(:)} should correspond to the number of vertical layers (\\nmitem{KMAX} in \\namelist{PARAM_ATMOS_GRID_CARTESC_INDEX}).\nThe following file for the ideal experiment is shown as an example:\n\\editboxtwo{\n\\verb|&PARAM_ATMOS_GRID_CARTESC|     & \\\\\n\\verb| DX = 500.D0,|   & Grid interval along the X direction (equidistant) [m]\\\\\n\\verb| DY = 500.D0,|   & Grid interval along the Y direction (equidistant) [m]\\\\\n\\verb| FZ(:) = |       & Location at face point along the Z direction [m] \\\\\n\\verb|     80.000000000000000D0      ,| & \\\\\n\\verb|     168.00000190734863D0      ,| & \\\\\n\\verb|     264.80000610351567D0      ,| & \\\\\n\\verb|           ........           | & \\\\\n\\verb|     14910.428862936289D0      ,| & \\\\\n\\verb|     15517.262523292475D0      ,| & \\\\\n\\verb|     16215.121232702089D0      ,| & \\\\\n\\verb|     17017.658748523147D0      ,| & \\\\\n\\verb|     17940.576891717363D0      ,| & \\\\\n\\verb|     19001.932756390710D0      ,| & \\\\\n\\verb|     20222.492000765058D0      ,| & \\\\\n\\verb| BUFFER_DZ = 5000.D0,|          & Refer to Section \\ref{subsec:buffer}\\\\\n\\verb| BUFFFACT  =   1.0D0,|          & Refer to Section \\ref{subsec:buffer}\\\\\n\\verb|/|\\\\\n}\n\n\\begin{figure}[tb]\n\\begin{center}\n  \\includegraphics[width=0.4\\hsize]{./../../figure/verticalface.pdf}\\\\\n  \\caption{The definition of the face point in \\scalerm. If \\nmitem{FZ} is given in \\namelist{PARAM_ATMOS_GRID_CARTESC}, the top height at the first layer is given for the value at $k=1$. Note that $k=1$ is not the ground surface height.}\n  \\label{fig:scale_grid}\n\\end{center}\n\\end{figure}\n\nThe above setting is processed at a topographical height of 0 m.\nThe location of the vertical grids at the non-zero topography is appropriately treated by the terrain-following coordinate.\n\nThe locations of the vertical grids are configured arbitrarily.\nHowever, an unusual configuration sometimes leads to numerical instability. To avoid it, the tool for the generation of vertical grids is supported as a FORTRAN program \\verb|make_vgrid.f90| in the directory\\\\ \\texttt{scale-\\version/scale-rm/util/makevgrid/} with several samples of the namelist. If needed, use them as references. The tool generates the values of \\nmitem{FZ(:)} directly. Copy and paste them in the configuration file.\n\n%-----------------------------------------------------------------------\n\\subsection{Setting the number of MPI processes} \\label{subsec:relation_dom_reso2}\n%-----------------------------------------------------------------------\n\nThe number of MPI processes is specified in \\namelist{PARAM_PRC_CARTESC} in the configuration file.\n\\editboxtwo{\n\\verb|&PARAM_PRC_CARTESC| & \\\\\n\\verb| PRC_NUM_X       = 2,| & ; number of divisions by MPI parallelization in the {\\XDIR} (zonal direction) \\\\\n\\verb| PRC_NUM_Y       = 1,| & ; number of divisions by MPI parallelization in the {\\YDIR} (meridional direction) \\\\\n\\verb|/|\\\\\n}\nIt should be noted that the number of MPI process must be a divisor of the total grid number \\nmitem{IMAXG} or \\nmitem{JMAXG} in the x- and y-directions, respectively.\nOtherwise, the program is terminated immediately with the following message:\n\\msgbox{\n  \\verb|number of IMAXG should be divisible by PRC_NUM_X| \\\\\n}\nor\n\\msgbox{\n  \\verb|number of JMAXG should be divisible by PRC_NUM_Y| \\\\\n}.\n\nThe total number of MPI processes is given by \\verb|PRC_NUM_X| $\\times$ \\verb|PRC_NUM_Y|.\nThe above example expresses a two-MPI parallel by dividing the domain into two sub-domains along the X direction, but not dividing along the Y direction. The total number of processes must be given as the number of MPI processes in the MPI command at submitting job.\nIf this condition is not satisfied,  the program is terminated immediately without calculation and the following message is output to the standard output.\n\\msgbox{\n\\verb|xxx total number of node does not match that requested. Check!| \\\\\n}\n\nSince the input and output files of \\scalerm are divided process by process according to the MPI, the total number of files is changed according to the number of MPI processes.\nFor example, the initial and boundary files made by two-MPI processes cannot be used for model execution by four-MPI processes.\nIf the number of MPI processes is changed, it is necessary\nto edit \\namelist{PARAM_PRC_CARTESC} in \\verb|pp.conf|, \\verb|init.conf|, and \\verb|run.conf|,\nand then conduct once again the processes of \\verb|pp| and \\verb|init|.\nAs another way, the postprocess \\sno is also available for redistribution (Please refer Sec.\\ref{sec:sno}).\n\n\n%-----------------------------------------------------------------------\n\\subsection{Setting sponge layer} \\label{subsec:raydamp}\n%-----------------------------------------------------------------------\n\n\\scalerm adopts height coordinate system in vertical. The uppermost boundary condition is a rigid lid, and the sound and gravity waves often reflect at the model top. To reduce worse effects of these reflecting waves, the damping layer named ``sponge layer'' is placed in the upper part of the model domain. In the sponge layer, a vertical velocity is dumped by Rayleigh friction. The relaxation time scale (= e-folding time) of damping is minimum at the model top and it increases with decreasing the height. Below the bottom boundary of sponge layer, the relaxation time scale is set to infinity.\nThere are two methods to set the thickness of the sponge layer in \\namelist{PARAM_ATMOS_DYN}.\n\n\\begin{enumerate}\n\\item specify number of layer of the sponge layer \\\\\n  The number of layer appointed in \\nmitem{ATMOS_DYN_wdamp_layer} is set as the sponge layer. The number is counted from the model top.\n\\item specify bottom boundary height [m] of the sponge layer \\\\\n  The layer that is higher than altitude appointed in \\nmitem{ATMOS_DYN_wdamp_height} is set as the sponge layer.\n\\end{enumerate}\n\nBoth parameters above are not set by default, and the sponge layer is not applied. If both are set, \\nmitem{ATMOS_DYN_wdamp_layer} is given priority.\n\nThe relaxation time at the uppermost boundary is specified by \\nmitem{ATMOS_DYN_wdamp_tau}. The unit is [second]. This parameter is not allowed to set the value smaller than \\nmitem{TIME_DT_ATMOS_DYN}. When \\nmitem{ATMOS_DYN_wdamp_tau} is not specified explicitly, the value ten times as large as \\\\\n\\nmitem{TIME_DT_ATMOS_DYN} is automatically set. Please refer to section \\ref{sec:timeintiv} for \\nmitem{TIME_DT_ATMOS_DYN}.\nThe example of concrete setting is shown in section \\ref{subsec:atmos_dyn_scheme}.\n\n%-----------------------------------------------------------------------\n\\subsection{Setting Buffer Region and Boundary Nudging Method} \\label{subsec:buffer}\n%-----------------------------------------------------------------------\n\nIn general, disagreement in values between input data as boundary condition and actual calculation output occurs at the lateral boundaries.\nThey generate several problems, such as nonphysical mode, in calculation.\nTo avoid these problems, the ``buffer region'' is placed in the domain.\n\nAs shown in Fig.\\ref{fig:buff_xz}, \\scalerm places the buffer region just inside the calculation domain.\nIn the buffer region, prognostic variables are updated to be close to the specified values of boundary data and/or the parent model data with a certain relaxation time.\nHereinafter, this relaxation is called nudging.\n\n\\subsubsection{Buffer Region}\n\n\nThe width of the buffer region is specified in \\namelist{PARAM_ATMOS_GRID_CARTESC} in the configuration file. Note again that the configuration in all procedures must be identical. There are two methods to configure the width of the buffer region.\n\n\\begin{enumerate}\n\\item specify number of grid of the buffer region with \\nmitem{BUFFER_NX, BUFFER_NY, BUFFER_NZ}\n\\item specify width [m] of the buffer region with \\nmitem{BUFFER_DX, BUFFER_DY, BUFFER_DZ}\n\\end{enumerate}\nBoth parameters above are not set by default, and no buffer regions are set. If both are set, \\nmitem{BUFFER_NX, BUFFER_NY, BUFFER_NZ} is given priority.\nThe buffer regions along the horizontal directions are placed at the four domain boundaries,\nwhereas those along the vertical direction are placed just at the top of the domain.\nNothing is affected in the bottom region.\nNote that the actual target region unaffected by the nudging (the region excluding the buffer regions) narrows compared to the calculation domain because the buffer region is placed on the inside of calculation domain.\n\nTwo examples are as below.\n%\n\\editboxtwo{\n\\verb|&PARAM_ATMOS_GRID_CARTESC| & \\\\\n \\verb|BUFFER_NX = 30, | & ; The number of grid for the buffer region along the \\XDIR \\\\\n \\verb|BUFFER_NY = 30, | & ; The number of grid for the buffer region along the \\YDIR \\\\\n \\verb|BUFFFACT  = 1.D0, | & ; Stretched factor for grid intervals in the buffer region \\\\\n\\verb|/|\\\\\n}\n\\editboxtwo{\n\\verb|&PARAM_ATMOS_GRID_CARTESC| & \\\\\n \\verb|BUFFER_DZ  = 5000.D0,   | & ; The width of the buffer region along the Z direction from the top of the model (a reference) [m]\\\\\n \\verb|BUFFER_DX  = 300000.D0, | & ; The width of the buffer region along the X (zonal) direction ( a reference ) [m]\\\\\n \\verb|BUFFER_DY  = 300000.D0, | & ; The width of the buffer region along the Y (meridional) direction ( a reference ) [m]\\\\\n \\verb|BUFFFACT_Z = 1.20D0,    | & ; Stretched factor for grid intervals along the Z direction\\\\\n \\verb|BUFFFACT_X = 1.05D0,    | & ; Stretched factor for grid intervals along the X (zonal) direction\\\\\n \\verb|BUFFFACT_Y = 1.05D0,    | & ; Stretched factor for grid intervals along the Y (meridional) direction\\\\\n \\verb|/|\\\\\n}\n\n\n\nThe setting procedure of buffer region for the X direction is described as follows.\nThe number of grids \\verb|ibuff| in the buffer region is equal to \\nmitemeq{BUFFER_NX}.\nIf \\nmitemeq{BUFFER_DX} is configured instead of \\nmitemeq{BUFFER_NX}, \\verb|ibuff| is automatically calculated as the minimum integer satisfying the following condition:\n%\n\\begin{eqnarray}\n   && \\sum_{n=1}^{\\verb|ibuff|} \\verb|BDX|(n) \\ge \\nmitemeq{BUFFER_DX}. \\nonumber\n\\end{eqnarray}\n%\nThus, it should be noted that the width of the buffer region $\\verb|BUFFER|_{\\verb|X|}$ ($= \\sum_{n=1}^{\\verb|ibuff|} \\verb|BDX|(n)$) does not always correspond to \\nmitem{BUFFER_DX}. At the end, the actual target region excluded by the buffer region is expressed as\n%\n\\begin{eqnarray}\n   && \\nmitemeq{DX} \\times ( \\nmitemeq{IMAXG} - 2 \\times \\verb|ibuff| ).\n\\end{eqnarray}\n%\nAlthough the situations along the Y and Z directions are similar to this, note that the actual target region along the Z direction is expressed as\n%\n\\begin{eqnarray}\n   && \\nmitemeq{DZ} \\times ( \\nmitemeq{KMAX} - \\verb|kbuff| ),\n\\end{eqnarray}\n%\nusing the number of grids \\verb|kbuff| in the upper buffer region.\n\n\\begin{figure}[t]\n\\begin{center}\n  \\includegraphics[width=0.8\\hsize]{./../../figure/buffer_xz.pdf}\\\\\n  \\caption{Location of the buffer region in the entire calculation domain: the shaded area indicates the buffer region. This figure shows the XZ cross-section. It is the same as the YZ cross-section.}\n  \\label{fig:buff_xz}\n\\end{center}\n\\end{figure}\n\nIn general, there is no clear criterion for setting the width and locating grids in the buffer region.\nThis depends on a problem to be solved.\nIn \\scalerm, the followings are recommended: the number of grids in the vertical buffer region at the top of the model is greater than 5, whereas that in the lateral boundaries is approximately 20$\\sim$40.\nDepending on the experiment, it may be necessary to increase the number of grids in the buffer region, to increase the buffer region itself by using the appropriate stretch factor, to tune relaxation time, and so on.\nThe relaxation time is explained below.\n\n\n\nThe grid intervals in the buffer region are the same as \\nmitem{DX, DY, DZ} in \\namelist{PARAM_ATMOS_GRID_CARTESC} by default.\nBut, it is possible for them to be stretched by setting \\nmitem{BUFFFACT} $>$ 1. This specification of \\nmitem{BUFFFACT} is applied in all directions if the grid intervals are uniformly specified. When the stretched factor is configured separately in every direction, specify \\nmitem{BUFFFACT_X, BUFFFACT_Y, BUFFFACT_Z}. Note that in case of the configuration of vertical levels by giving \\nmitem{FZ(:)} (refer to \\ref{subsec:gridinterv}), the above stretched settings have no effect along the vertical direction.\n\nThe grid interval \\verb|BDX| in the buffer region is determined as follows:\n\\begin{eqnarray}\n \\verb|BDX(|n\\verb|)| &=& \\verb|DX| \\times \\verb|BUFFFACT|^n, \\nonumber\n\\end{eqnarray}\nwhere $n$ denotes the index of grids in the buffer region, in the order directed from the inner to the outer region in the domain. The grid interval is the same as the inner domain at \\nmitem{BUFFFACT=1.0}, whereas it increases from the inner to the outer region by a factor of 1.2 at \\nmitem{BUFFFACT=1.2}.  Although any value of \\nmitem{BUFFFACT} can be configured, the value from 1.0 to 1.2 is recommended to avoid numerical instability.\n\nFinally, the width of the buffer region $\\verb|BUFFER|_{\\verb|X|}$ is as follows:\n\\begin{eqnarray}\n  \\verb|BUFFER|_{\\verb|X|} = \\nmitemeq{DX} \\times \\frac{ \\nmitemeq{BUFFFACT}^{\\texttt{\\detokenize{ibuff}}}-1}{ \\nmitemeq{BUFFFACT}-1 }\n\\end{eqnarray}\nEven if the same width of buffer region \\nmitem{BUFFER_DX} is specified, the number of grids in the buffer region decreases with increasing \\nmitem{BUFFFACT}.\nWhen given by \\nmitem{BUFFER_NX}, only the width of buffer region is changed.\n\n\n\n\\subsubsection{Nudging Methods in Buffer Region}\n\n\\namelist{PARAM_ATMOS_BOUNDARY} has parameters to configure the nudging in the buffer region.\nThe boundary data type is configurable by \\nmitem{ATMOS_BOUNDARY_TYPE} in \\namelist{PARAM_ATMOS_BOUNDARY} (Table \\ref{tab:nml_atmos_boundary_type}.)\n\n\\begin{table}[h]\n\\begin{center}\n\\caption{Choices of the boundary data type}\n\\label{tab:nml_atmos_boundary_type}\n\\begin{tabularx}{150mm}{lXX} \\hline\n  \\rowcolor[gray]{0.9} Value & Description of type \\\\ \\hline\n  \\verb|NONE|    & Do not nudge \\\\\n  \\verb|CONST|   & Nudge to a prescribed constant value \\\\\n  \\verb|INIT|    & Nudge to the initial value \\\\\n  \\verb|OFFLINE| & Nudge to value read from a file (temporally unchanged) \\\\\n  \\verb|REAL|    & Nudge to time-dependent value of the parent model or domain \\\\\n  \\hline\n\\end{tabularx}\n\\end{center}\n\\end{table}\n\n\nThe following is the parameters in \\namelist{PARAM_ATMOS_BOUNDARY}.\n\\editboxtwo{\n  \\verb|&PARAM_ATMOS_BOUNDARY | & \\\\\n  \\verb| ATMOS_BOUNDARY_TYPE = 'NONE',         | & ; The boundary data type. See Table \\ref{tab:nml_atmos_boundary_type}. \\\\\n  \\verb| ATMOS_BOUNDARY_IN_BASENAME = '',      | & ; File name of the boundary data for \\verb|OFFLINE| or \\verb|REAL| type \\\\\n  \\verb| ATMOS_BOUNDARY_IN_CHECK_COORDINATES | \\textbackslash \\\\\n  ~~\\verb|                   = .true.,| & ; Flag to check coordinate variables in the boundary data file. \\\\\n  \\verb| ATMOS_BOUNDARY_START_DATE | \\textbackslash \\\\\n  ~~\\verb|        = (/ -9999, 0, 0, 0, 0, 0 /),| & ; Start time of the boundary data. Only for \\verb|REAL| type. \\\\\n  \\verb| ATMOS_BOUNDARY_UPDATE_DT = 0.0D0,     | & ; Time interval of the boundary data. Only for \\verb|REAL| type. \\\\\n  \\\\ ({\\small\\slshape continued on next page})\n}\n\\editboxtwo{\n  ({\\small\\slshape continued from previous page}) \\\\ \\\\\n  \\verb| ATMOS_BOUNDARY_INTERP_TYPE | \\textbackslash \\\\\n  ~~\\verb|                  = 'lerp_initpoint',| & ; Temporal interpolation type. \\\\\n                                                 &  ~\\verb|same_parent|: use the latest step value (no interpolation), \\\\\n                                                 &  ~\\verb|nearest_neighbor|: use the value of the nearest time step, \\\\\n                                                 &  ~\\verb|lerp_initpoint|: linear interpolation between values at two time steps as the values are snapshot, \\\\\n                                                 &  ~\\verb|lerp_midpoint|: same as \\verb|lerp_initpoint| but the values are temporal average during the time step for boundary data. \\\\\n  \\verb| ATMOS_BOUNDARY_OUT_BASENAME = '',     | & ; File name to output the initial boundary data. \\\\\n  \\verb| ATMOS_BOUNDARY_OUT_TITLE | \\textbackslash \\\\\n  ~~\\verb|     = 'SCALE-RM BOUNDARY CONDITION',| & ; Title for the output file. \\\\\n  \\verb| ATMOS_BOUNDARY_OUT_DTYPE = 'DEFAULT', | & ; Data type (\\verb|REAL4| or \\verb|REAL8|) for the output. \\\\\n  \\verb| ATMOS_BOUNDARY_USE_DENS = .false.,    | & ; Switch of the nudging for the density. \\\\\n  \\verb| ATMOS_BOUNDARY_USE_VELZ = .false.,    | & ; Switch for the w. \\\\\n  \\verb| ATMOS_BOUNDARY_USE_VELX = .false.,    | & ; Switch for the u. \\\\\n  \\verb| ATMOS_BOUNDARY_USE_VELY = .false.,    | & ; Switch for the v. \\\\\n  \\verb| ATMOS_BOUNDARY_USE_PT = .false.,      | & ; Switch for the $\\theta$. \\\\\n  \\verb| ATMOS_BOUNDARY_USE_QV = .false.,      | & ; Switch for the vapor. \\\\\n  \\verb| ATMOS_BOUNDARY_USE_QHYD = .false.,    | & ; Switch for the hydrometeors. \\\\\n  \\verb| ATMOS_BOUNDARY_VALUE_VELZ = 0.0D0,    | & ; Value of the w. Only for \\verb|CONST| type. \\\\\n  \\verb| ATMOS_BOUNDARY_VALUE_VELX = 0.0D0,    | & ; Value of the u. Only for \\verb|CONST| type. \\\\\n  \\verb| ATMOS_BOUNDARY_VALUE_VELY = 0.0D0,    | & ; Value of the v. Only for \\verb|CONST| type. \\\\\n  \\verb| ATMOS_BOUNDARY_VALUE_PT = 300.0D0,    | & ; Value of the $\\theta$. Only for \\verb|CONST| type. \\\\\n  \\verb| ATMOS_BOUNDARY_VALUE_QTRC =   0.0D0,  | & ; Value of the vapor. Only for \\verb|CONST| type. \\\\\n  \\verb| ATMOS_BOUNDARY_ALPHAFACT_DENS = 1.0D0,| & ; Factor of the $1/\\tau$ for the density. \\\\\n  \\verb| ATMOS_BOUNDARY_ALPHAFACT_VELZ = 1.0D0,| & ; Factor for the w. \\\\\n  \\verb| ATMOS_BOUNDARY_ALPHAFACT_VELX = 1.0D0,| & ; Factor for the u. \\\\\n  \\verb| ATMOS_BOUNDARY_ALPHAFACT_VELZ = 1.0D0,| & ; Factor for the v. \\\\\n  \\verb| ATMOS_BOUNDARY_ALPHAFACT_PT = 1.0D0,  | & ; Factor for the $\\theta$. \\\\\n  \\verb| ATMOS_BOUNDARY_ALPHAFACT_QTRC = 1.0D0,| & ; Factor for the vapor. \\\\\n  \\verb| ATMOS_BOUNDARY_SMOOTHER_FACT = 0.2D0, | & ; Factor of the horizontal smoother against the pointwise difference. \\\\\n  \\verb| ATMOS_BOUNDARY_FRACZ = 1.0D0,         | & ; Fraction for the nudging region to the buffer region in the z-direction. \\\\\n  \\verb| ATMOS_BOUNDARY_FRACX = 1.0D0,         | & ; Fraction in the x-direction. \\\\\n  \\verb| ATMOS_BOUNDARY_FRACY = 1.0D0,         | & ; Fraction in the y-direction. \\\\\n  \\verb| ATMOS_BOUNDARY_TAUZ = DT * 10.0D0,    | & ; Time scale of the nudging at the top boundary (in second). \\\\\n  \\verb| ATMOS_BOUNDARY_TAUX = DT * 10.0D0,    | & ; Time scale at the western and eastern boundaries. \\\\\n  \\verb| ATMOS_BOUNDARY_TAUY = DT * 10.0D0,    | & ; Time scale at the southern and northern boundaries. \\\\\n  \\verb| ATMOS_BOUNDARY_LINEAR_V = .false.,    | & ; Profile type of the time scale in the z-direction. If \\verb|.true.|, it is a linear profile, otherwise a sinusoidal profile. \\\\\n  \\verb| ATMOS_BOUNDARY_LINEAR_H = .false.,    | & ; Profile type in the x- and y-direction. If \\verb|.true.|, it is a linear profile, otherwise a exponential profile. \\\\\n  \\verb| ATMOS_BOUNDARY_EXP_H = 2.0D0,         | & ; Factor of the exponent of the exponential profile. \\\\\n  \\verb| ATMOS_BOUNDARY_DENS_ADJUST = .false., | & ; Switch of the mass flux adjustment. \\\\\n  \\verb| ATMOS_BOUNDARY_DENS_ADJUST_TAU | \\textbackslash \\\\\n  ~~\\verb|     = -1.0D0,                       | & ; Time scale of the density nudging when the mass flux adjustment is enabled (in second). \\\\\n}\n\nThe tendency due to the nudging is written as\n\\begin{eqnarray}\n  \\left.\\frac{\\partial \\phi_{k,i,j}}{\\partial t}\\right|_\\mathrm{nudging}\n  & = & - \\alpha \\Delta\\phi_{k,i,j} \\\\ \\nonumber\n  && + \\alpha_s \\left( \\frac{\\Delta\\phi_{k,i-1,j} + \\Delta\\phi_{k,i+1,j} + \\Delta\\phi_{k,i,j-1} + \\Delta\\phi_{k,i,j+1}}{8} - \\frac{\\Delta\\phi_{k,i,j}}{2} \\right),\n\\label{eq:nudging}\n\\end{eqnarray}\nwhere $\\Delta\\phi$ is difference from the boundary data and $\\alpha_s = \\alpha \\times \\nmitemeq{ATMOS_BOUNDARY_SMOOTHER_FACT}$.\nThe $\\alpha$ is the maximum of those in the tree directions $\\alpha_x, \\alpha_y$ and $\\alpha_z$.\nThe $\\alpha$s depend on a length scale $e$ as\n\\begin{equation}\n  e = \\max\\left( 1 - \\frac{d}{\\texttt{BUFFER} \\times \\nmitemeq{ATMOS_BOUNDARY_FRAC}}, 0 \\right),\n\\end{equation}\nwhere $d$ is distance from the boundary.\nIf \\nmitem{ATMOS_BOUNDARY_LINEAR_V} = \\verb|.true.|,\n\\begin{equation}\n  \\alpha_z = e_z / \\tau_z,\n\\end{equation}\notherwise\n\\begin{equation}\n  \\alpha_z =  \\sin^2(\\pi e_z/2) / \\tau_z,\n\\end{equation}\nwhere $\\tau_z$ is \\nmitem{ATMOS_BOUNDARY_TAUZ}.\nFor the horizontal direction, if \\nmitem{ATMOS_BOUNDARY_LINEAR_H} = \\verb|.true.|,\n\\begin{equation}\n  \\alpha_x = e_x / \\tau_x,\n\\end{equation}\notherwise\n\\begin{equation}\n  \\alpha_x = e_x \\exp\\{ - (1-e_x) \\times \\nmitemeq{ATMOS_BOUNDARY_EXP_H} \\} / \\tau_x.\n\\end{equation}\n$\\alpha_y$ is derived by the same way as $\\alpha_x$.\n\nThe $\\tau$ is the relaxation time at the boundary ($d=0$) with which the difference between the simulated value and the boundary value becomes $1/e$.\nOn the other hand, two grid scale component of $\\Delta \\phi$ becomes $1/e$ with the time of $\\tau/\\nmitemeq{ATMOS_BOUNDARY_SMOOTHER_FACT}$ by the second term of the right-hand side of Eq. \\ref{eq:nudging}.\nThe default value of the $\\tau$ is ten times of \\nmitem{TIME_DT}.\nPlease refer to Section \\ref{sec:timeintiv} for \\nmitem{TIME_DT}.\n\n\nIf \\nmitem{ATMOS_BOUNDARY_TYPE} = ``\\verb|REAL|'' in \\namelist{PARAM_ATMOS_BOUNDARY},\nthe nudging at the top and lateral boundaries is applied for the horizontal velocities, potential temperature, density, and vapor,\nregardless of the settings of \\nmitem{ATMOS_BOUNDARY_USE_{VELX,VELY,PT,DESN,QV}}.\nThe nudging for the vertical velocity and hydrometeors is applied\nwhen \\nmitem{ATMOS_BOUNDARY_USE_VELZ}=\\verb|.true.| and \\nmitem{ATMOS_BOUNDARY_USE_QHYD}=\\verb|.true.|, respectively.\nIn the case of an online nesting simulation (See Section \\ref{subsec:nest_online}),\nthe same settings with the `` \\verb|REAL|'' boundary type is applied to the child domain,\nexcept that \\nmitem{ONLINE_USE_VELZ} and \\nmitem{ONLINE_BOUNDARY_USE_QHYD} in \\namelist{PARAM_COMM_CARTESC_NEST}\nare used instead of \\nmitem{ATMOS_BOUNDARY_USE_VELZ} and \\nmitem{ATMOS_BOUNDARY_USE_QHYD}, respectively.\n\n\nThe density nudging is effective to reduce the bias of total mass in the simulation. However, it also decreases the pressure gradient in the nudging region; the pressure gradient plays a role to transfer the information of boundary data into the inner domain especially in outflow region.\nAs a way to reduce the mass bias keeping the pressure gradient, the adjustment of the mass flux is available.\nBy using the adjustment of the mass flux, the density nudging could be weakened.\n%\nIf \\nmitem{ATMOS_BOUNDARY_DENS_ADJUSTMENT} = \\verb|.true.|,\nthe mass flux at the lateral boundaries is adjusted so that the difference in the total mass between the parent model and the simulation becomes small.\nFor example, if the total mass in the simulation is less than that in the parent model, the $\\rho u$ at the western boundary and the $\\rho v$ at the southern boundary are increased, and the $\\rho u$ at the eastern boundary and the $\\rho v$ at the northern boundary are decreased to enlarge the total mass convergence.\nThe mass flux adjustment is available only for the \\verb|REAL| boundary type and child domain of the online nesting.\nWhen the mass flux adjustment is enabled, the time scale of the density nudging is specified by \\nmitem{ATMOS_BOUNDARY_DENS_ADJUSTMENT_TAU}.\nIf the value is negative, the time scale is internally determined as $\\nmitemeq{ATMOS_BOUNDARY_UPDATE_DT} / 6.0$.\nTo weaken the density nudging, set the time scale larger than \\nmitem{ATMOS_BOUNDARY_TAUX} and \\nmitem{ATMOS_BOUNDARY_TAUY}.\nThe adjustment method in \\scalerm is constructed under the assumption that the total mass change due to convergence of the mass flux at the lateral boundaries is much larger than that due to the physical processes, such as precipitation and surface latent heat flux.\nThe validity of the assumption depends on target domain and situation.\n\nThere exists a similar dumping method at near the top boundary, i.e., Rayleigh dumping. See Section \\ref{subsec:raydamp}.\n\n%-----------------------------------------------------------------------\n\\subsection{Setting vertical grids for ocean, land, and urban models} \\label{subsec:gridolu}\n%-----------------------------------------------------------------------\n\nSettings for horizontal grids of ocean, land, and urban models are same as those for the atmospheric model.\nThe numbers of the grids are specified by \\nmitem{IMAXG, JMAXG} in \\namelist{PARAM_ATMOS_GRID_CARTESC_INDEX}.\nThe horizontal grid intervals are specified by \\nmitem{DX, DY} in \\namelist{PARAM_ATMOS_GRID_CARTESC}.\nOn the other hand, settings for vertical grids should be specified for each model separately.\n\nPlease see Sec. \\ref{sec:basic_usel_ocean}, Sec. \\ref{sec:basic_usel_land} and Sec. \\ref{sec:basic_usel_urban}\nfor vertical grid settings for ocean, land and urban models, respectively.\n", "meta": {"hexsha": "15af83b08a3ec52ea001f616e49990a871e0fc21", "size": 31247, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/users-guide/en/51_setting_domain.tex", "max_stars_repo_name": "slayoo/scale", "max_stars_repo_head_hexsha": "ca4b476ad55cb728b2009f0427ce3f7161ecfcf7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-06-14T11:12:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T05:29:55.000Z", "max_issues_repo_path": "doc/users-guide/en/51_setting_domain.tex", "max_issues_repo_name": "slayoo/scale", "max_issues_repo_head_hexsha": "ca4b476ad55cb728b2009f0427ce3f7161ecfcf7", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-07-29T03:38:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-30T05:08:47.000Z", "max_forks_repo_path": "doc/users-guide/en/51_setting_domain.tex", "max_forks_repo_name": "slayoo/scale", "max_forks_repo_head_hexsha": "ca4b476ad55cb728b2009f0427ce3f7161ecfcf7", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-10T10:39:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-28T22:20:41.000Z", "avg_line_length": 69.4377777778, "max_line_length": 598, "alphanum_fraction": 0.7143405767, "num_tokens": 8595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.679178686187839, "lm_q2_score": 0.48828339529583475, "lm_q1q2_score": 0.3316316749043623}}
{"text": "\\documentclass[12pt]{amsart}\n\\usepackage[margin=0.5in]{geometry} \n  % see geometry.pdf on how to lay out the page. There's lots.\n\\usepackage{bsymb}\n\\usepackage{calculational}\n\\usepackage{ulem}\n\\usepackage{hyperref}\n\\usepackage{unitb}\n\n\\newcommand{\\REQ}{\\text{REQ}}\n\n\\begin{document}\n\n\\section{Strategy}\n\n\\begin{itemize}\n  \\item \n\\end{itemize}\n\\section{Model m0 --- Requests and non-deterministic handling}\n  % \\input{lock-free-deque/machine_m0.tex}\n\\begin{machine}{m0}\n  \\with{sets}\n  \\newset{\\REQ} \n  \\newevent{add}{add}\n  \\newevent{handle}{handle}\n  \\[ \\variable{ req : \\set [\\REQ] } \\]\n  \\begin{description}\n    \\comment{req}{set of pending requests}\n  \\end{description}\n  \\[ \\param{add}{ r : \\REQ } \\]\n  \\[ \\param{handle}{ r : \\REQ } \\]\n  \\begin{align*}\n      \\initialization{m0:init0}{ req = \\emptyset } \\\\\n      \\evguard{add}{m0:guard}{ \\neg r \\in req } \\\\\n      \\evbcmeq{add}{m0:act0}{req}{ req \\bunion \\{ r \\} } \\\\\n      \\cschedule{handle}{m0:sch0}{ \\neg req = \\emptyset } \\\\\n      \\evguard{handle}{m0:grd0}{ r \\in req } \\\\\n      \\evbcmeq{handle}{m0:act0}{req}{ req \\setminus \\{ r \\} } \n  \\end{align*}\n\n\\noindent\n\\end{machine}\n\\section{Model m1 --- Version numbers and individual fairness}\n  % \\input{lock-free-deque/machine_m1.tex}\n\\begin{machine}{m1}\n    \\refines{m0}\n  \\[ \\variable{ ver : \\Int } \\]\n  \\begin{description}\n    \\comment{ver}{ serial number of the current data structure state }\n  \\end{description}\n  \\[ \\indices{handle}{ v : \\Int } \\]\n  \\promote{handle}{r}\n  \\removecoarse{handle}{m0:sch0}\n  \\removeguard{handle}{m0:grd0}\n  % \\removeact{handle}{m0:act0}\n  \\[\\witness{handle}{r}{r \\in req}\\]\n  \\[\\witness{handle}{v}{v = ver}\\]\n  \\begin{align}\n      \\initialization{m1:init0}{ ver = 0 } \\\\\n      \\cschedule{handle}{m1:sch0}{ r \\in req } \\\\\n      \\cschedule{handle}{m1:sch1}{ v = ver } \\\\\n      % \\evguard{handle}{m1:grd0}{ r = r0 } \\\\\n      \\evbcmeq{handle}{m1:act0}{ver}{ ver + 1 } \n  \\end{align}\n\\end{machine}\n\\section{Model m2 --- Specialized events}\n  % \\input{lock-free-deque/machine_m2}\n\\begin{machine}{m2}\n  \\refines{m1}\n  \\[ \\variable{pshL,pshR,popR,popL : \\set [\\REQ]} \\]\n  \\begin{description}\n    \\comment{pshL}{replaces $req$. Set of push\\_left requests }\n    \\comment{pshR}{replaces $req$. Set of push\\_right requests }\n    \\comment{popL}{replaces $req$. Set of pop\\_left requests }\n    \\comment{popR}{replaces $req$. Set of pop\\_right requests }\n  \\end{description}\n  \\begin{align}\n    \\initialization{m2:init0}{pshL = \\emptyset} \\\\\n    \\initialization{m2:init1}{popL = \\emptyset} \\\\\n    \\initialization{m2:init2}{pshR = \\emptyset} \\\\\n    \\initialization{m2:init3}{popR = \\emptyset} \n  \\end{align}\n  \\subsection{Specialize \\emph{handle}}\n  % \\begin{align*}\n    \\refiningevent{handle}{handle:popL}{handle\\_popL}\n    \\refiningevent{handle}{handle:popR}{handle\\_popR} \n    \\refiningevent{handle}{handle:pushL}{handle\\_pushL}\n    \\refiningevent{handle}{handle:pushR}{handle\\_pushR}\n  % \\end{align*}\n  \\splitevent{handle}{handle:popL,handle:popR,handle:pushR,handle:pushL}\n  \\begin{align}\n    \\invariant{m2:inv0}{ pshL \\bunion \n        pshR \\bunion \n        popL \\bunion \n        popR \n        = req } \\\\\n    \\invariant{m2:inv1}{ pshL \\binter pshR = \\emptyset } \\\\\n    \\invariant{m2:inv2}{ pshL \\binter popL = \\emptyset } \\\\\n    \\invariant{m2:inv3}{ pshL \\binter popR = \\emptyset } \\\\\n    \\invariant{m2:inv4}{ pshR \\binter popL = \\emptyset } \\\\\n    \\invariant{m2:inv5}{ pshR \\binter popR = \\emptyset } \\\\\n    \\invariant{m2:inv6}{ popL \\binter popR = \\emptyset } \\\\\n    \\cschedule{handle:pushL}{m2:sch0}{ r \\in pshL } \\\\\n    \\evbcmeq{handle:pushL}{m2:act0}{pshL}{pshL \\setminus \\{ r \\}} \\\\\n    \\cschedule{handle:pushR}{m2:sch0}{ r \\in pshR } \\\\\n    \\evbcmeq{handle:pushR}{m2:act0}{pshR}{pshR \\setminus \\{ r \\}} \\\\\n    \\cschedule{handle:popL}{m2:sch0}{ r \\in popL } \\\\\n    \\evbcmeq{handle:popL}{m2:act0}{popL}{popL \\setminus \\{ r \\}} \\\\\n    \\cschedule{handle:popR}{m2:sch0}{ r \\in popR } \\\\\n    \\evbcmeq{handle:popR}{m2:act0}{popR}{popR \\setminus \\{ r \\}} \n    % \\invariant{m2:inv1}{ popL \\subseteq req } \\\\\n    % \\invariant{m2:inv2}{ pshR \\subseteq req } \\\\\n    % \\invariant{m2:inv3}{ popR \\subseteq req } \n  \\end{align}\n  \\[ \\variable{ ppd : \\set [\\REQ] } \\]\n  \\begin{align}\n    \\initialization{m2:init4}{ ppd = \\emptyset } \\\\\n    \\evbcmeq{handle:popR}{m2:act1}{ppd}{ ppd \\bunion \\{r\\} } \\\\\n    \\evbcmeq{handle:popL}{m2:act1}{ppd}{ ppd \\bunion \\{r\\} }\n  \\end{align}\n  \\newevent{return}{return}\n  \\[ \\indices{return}{ r : \\REQ } \\]\n  \\begin{align}\n    \\cschedule{return}{m2:sch0}{ r \\in ppd } \\\\\n    \\evbcmeq{return}{m2:act0}{ppd}{ ppd \\setminus \\{ r \\} }\n  \\end{align}\n\\subsection{Specialize \\emph{add}}\n    \\refiningevent{add}{add:popL}{add\\_popL} \n    \\refiningevent{add}{add:popR}{add\\_popR}\n    \\refiningevent{add}{add:pushL}{add\\_pushL}\n    \\refiningevent{add}{add:pushR}{add\\_pushR}\n  \\splitevent{add}{add:popL,add:popR,add:pushR,add:pushL}\n  \\begin{align}\n    \\evbcmeq{add:popL}{m2:act0}{popL}{popL \\bunion \\{r\\}} \\\\\n    \\evbcmeq{add:pushL}{m2:act1}{pshL}{pshL \\bunion \\{r\\}} \\\\\n    \\evbcmeq{add:popR}{m2:act2}{popR}{popR \\bunion \\{r\\}} \\\\\n    \\evbcmeq{add:pushR}{m2:act3}{pshR}{pshR \\bunion \\{r\\}} \n  \\end{align}\n\\subsection{Data refinement}\n  \\removevar{req}\n  \\removeinit{m0:init0}\n  \\[\\initwitness{req}{req = \\emptyset}\\]\n  \\removeact{handle:popR}{m0:act0}\n  \\removeact{handle:pushR}{m0:act0}\n  \\removeact{handle:popL}{m0:act0}\n  \\removeact{handle:pushL}{m0:act0}\n  \\removecoarse{handle:popR}{m1:sch0}\n  \\removecoarse{handle:pushR}{m1:sch0}\n  \\removecoarse{handle:popL}{m1:sch0}\n  \\removecoarse{handle:pushL}{m1:sch0}\n  \\removeguard{add:popR}{m0:guard}\n  \\removeguard{add:pushR}{m0:guard}\n  \\removeguard{add:popL}{m0:guard}\n  \\removeguard{add:pushL}{m0:guard}\n  \\begin{align*}\n  \\evguard{add:popR}{m2:grd0}\n    { \\neg r \\in pshL \\bunion pshR \\bunion popL \\bunion popR } \\\\\n  \\evguard{add:pushR}{m2:grd0}\n    { \\neg r \\in pshL \\bunion pshR \\bunion popL \\bunion popR } \\\\\n  \\evguard{add:popL}{m2:grd0}\n    { \\neg r \\in pshL \\bunion pshR \\bunion popL \\bunion popR } \\\\\n  \\evguard{add:pushL}{m2:grd0}\n    { \\neg r \\in pshL \\bunion pshR \\bunion popL \\bunion popR } \n  \\end{align*}\n  \\removeact{add:popR}{m0:act0}\n  \\removeact{add:pushR}{m0:act0}\n  \\removeact{add:popL}{m0:act0}\n  \\removeact{add:pushL}{m0:act0}\n\\end{machine}\n  \\newcommand{\\OBJ}{\\text{OBJ}}\n\\section{Model m3 --- The Contents}\n  % \\input{lock-free-deque/machine_m3}\n\\begin{machine}{m3}\n  \\refines{m2}\n  \\with{functions}\n  \\with{intervals}\n\n  \\newset{\\OBJ}\n  \\[ \\variable{ p,q : \\Int } \\]\n  \\[ \\variable{ qe : \\Int \\pfun \\OBJ } \\]\n  \\begin{align}\n    \\invariant{m3:inv0}{ qe \\in \\intervalR{p}{q} \\tfun \\OBJ } \\\\\n    \\invariant{m3:inv1}{ p \\le q } \\\\\n    \\initialization{m3:init0}{ p = 0 \\land q = 0} \\\\\n    \\initialization{m3:init1}{ qe = \\emptyfun }\n  \\end{align}\n  \\subsection{Push}\n    \\[\\variable{insL : \\REQ \\pfun \\OBJ} \\]\n    \\[\\variable{insR : \\REQ \\pfun \\OBJ} \\]\n  \\begin{description}\n    \\comment{insL}{parameter for the \\emph{push left} operation} \n    \\comment{insR}{parameter for the \\emph{push right} operation} \n  \\end{description}\n  \\begin{align}\n    \\invariant{m3:inv2}{ insL \\in pshL \\tfun \\OBJ } \\\\\n    \\invariant{m3:inv3}{ insR \\in pshR \\tfun \\OBJ } \\\\\n    \\initialization{m3:init2}{ insL = \\emptyfun } \\\\\n    \\initialization{m3:init4}{ insR = \\emptyfun }\n  \\end{align}\n  \\begin{align}\n    \\evbcmeq{handle:pushL}{m3:act0}{p}{p - 1} \\\\\n    \\evbcmeq{handle:pushL}{m3:act1}{qe}{ qe \\2| (p \\0- 1 \\fun insL.r)} \\\\\n    \\evbcmeq{handle:pushR}{m3:act0}{q}{q + 1} \\\\\n    \\evbcmeq{handle:pushR}{m3:act1}{qe}{ qe \\2| (q \\fun insR.r)} \n  \\end{align}\n  \n  \\[ \\param{add:pushL}{ obj : \\OBJ } \\]\n\n  \\begin{align}\n    \\evbcmeq{add:pushL}{m3:act0}\n      {insL}{ insL \\1| r \\fun obj } \\\\\n    \\evbcmeq{handle:pushL}{m3:act2}\n      {insL}{ \\{ r \\} \\domsub insL }\n  \\end{align}\n\n  \\[ \\param{add:pushR}{ obj : \\OBJ } \\]\n  \n  \\begin{align}\n    \\evbcmeq{add:pushR}{m3:act0}\n      {insR}{ insR \\1| r \\fun obj } \\\\\n    \\evbcmeq{handle:pushR}{m3:act2}\n      {insR}{ \\{ r \\} \\domsub insR }\n  \\end{align}\n  \\[ \\variable{ res : \\REQ \\pfun \\OBJ } \\]\n  \\[ \\variable{ result : \\OBJ } \\]\n  \\[ \\variable{ emp : \\Bool } \\]\n  \\subsection{Pop}\n  \\begin{align}\n    \\initialization{m3:init3}{ res = \\emptyfun } \\\\\n    \\invariant{m3:inv4}{ res \\in ppd \\pfun \\OBJ } \\\\\n    \\evbcmeq{return}{m3:act0}{res}{ \\{r\\} \\domsub res} \\\\\n    \\evbcmsuch{return}{m3:act1}{result}{ r \\in \\dom.res \\implies result' = res.r } \\\\\n    \\evbcmeq{return}{m3:act2}{emp}{ (r \\in \\dom.res) } \n  \\end{align}\n  \\splitevent{handle:popL}{handle:popL:empty,handle:popL:non:empty}\n  \\splitevent{handle:popR}{handle:popR:empty,handle:popR:non:empty}\n  \\refiningevent{handle:popL}{handle:popL:empty}{handle\\_popL\\_empty}\n  \\refiningevent{handle:popL}{handle:popL:non:empty}{handle\\_popL\\_non\\_empty}\n  \\refiningevent{handle:popR}{handle:popR:empty}{handle\\_popR\\_empty}\n  \\refiningevent{handle:popR}{handle:popR:non:empty}{handle\\_popR\\_non\\_empty}\n  \\[ \\dummy{v : \\Int} \\]\n  \\replace{handle:popL}{m3:sch0}{m3:prog0}\n  \\begin{align*}\n    & \\progress{m3:prog0}{v = ver}{p = q \\lor p < q}\n    \\refine{m3:prog0}{implication}{}{}\n  \\end{align*}\n  \\begin{align}\n    \\cschedule{handle:popL:non:empty}{m3:sch0}{ p < q } \\\\\n    \\cschedule{handle:popL:empty}{m3:sch0}{ p = q } \\\\\n    \\evbcmeq{handle:popL:non:empty}{m3:act0}{res}{ res \\1| (r \\fun qe.p) } \\\\\n    \\evbcmeq{handle:popL:non:empty}{m3:act1}{p}{p+1} \\\\\n    \\evbcmeq{handle:popL:non:empty}{m3:act2}{qe}{ \\{p\\} \\domsub qe }\n  \\end{align}\n  \\replace{handle:popR}{m3:sch0}{m3:prog0}\n  \\begin{align}\n    \\cschedule{handle:popR:non:empty}{m3:sch0}{ p < q } \\\\\n    \\cschedule{handle:popR:empty}{m3:sch0}{ p = q } \\\\\n    \\evbcmeq{handle:popR:non:empty}{m3:act0}{res}{ res \\1| (r \\fun qe.(q\\0-1)) } \\\\\n    \\evbcmeq{handle:popR:non:empty}{m3:act1}{q}{q-1} \\\\\n    \\evbcmeq{handle:popR:non:empty}{m3:act2}{qe}{ \\{q-1\\} \\domsub qe }\n  \\end{align}\n\\end{machine}\n\\section{Model m4 --- Memory nodes}\n\\newcommand{\\Node}{\\text{Node}}\n  % \\input{lock-free-deque/machine_m4}\n\\begin{machine}{m4}\n  \\refines{m3}\n\\subsection{Data structure}\n  \\newset{\\Node}\n  \\[ \\variable{ rep : \\Int \\pfun \\Node } \\]\n  \\[ \\variable{ item : \\Node \\pfun \\OBJ } \\]\n  \\[ \\variable{ node : \\set [\\Node] } \\]\n  \\[ \\constant{ dummy : \\Node } \\]\n  \\begin{align}\n    \\invariant{m4:inv0}\n      { rep \\in \\intervalR{p}{q} \\tfun node } \\\\\n    \\invariant{m4:inv1}\n      { item \\in node \\tfun \\OBJ } \\\\\n    % \\invariant{m4:inv2}{ rep is injective }\n    \\invariant{m4:inv3}\n      { \\qforall{i}{\\betweenR{p}{i}{q}}{ qe.i = item.(rep.i) } } \\\\\n    \\initialization{m4:init0}{ rep  = \\emptyfun } \\\\\n    \\initialization{m4:init1}\n      { \\qexists{val}{}{ item \\1= dummy \\fun val } } \\\\\n    \\initialization{m4:init2}{ node = \\{ dummy \\} } \\\\\n    \\invariant{m4:inv9}\n      { dummy \\in node } \\\\\n    \\invariant{m4:inv10}\n      { \\neg dummy \\in \\ran.rep }\n  \\end{align}\n\\subsection{Pop}\n  \\begin{align}\n    \\evbcmeq{handle:popL:non:empty}{m4:act0}{rep}\n      { \\{ p \\} \\domsub rep } \\\\\n    \\evbcmeq{handle:popR:non:empty}{m4:act0}{rep}\n      { \\{ q-1 \\} \\domsub rep }\n  \\end{align}\n\\subsection{Push}\n  \\[ \\variable{ nL : \\REQ \\pfun \\Node } \\]\n  \\[ \\variable{ nR : \\REQ \\pfun \\Node } \\]\n  \\[ \\variable{ new : \\set [\\Node] } \\]\n\\paragraph{\\eqref{m4:inv0}}\n  \\begin{align}\n    \\invariant{m4:inv4}{ nL \\in pshL \\pfun node } \\\\\n    \\invariant{m4:inv5}{ nR \\in pshR \\pfun node } \\\\\n    \\initialization{m4:init3}{ nL = \\emptyfun } \\\\\n    \\initialization{m4:init4}{ nR = \\emptyfun } \\\\\n    \\evbcmeq{handle:pushL}{m4:act0}\n      {rep}{ rep \\2| (p\\0-1 \\fun nL.r) } \\\\\n    \\cschedule{handle:pushL}{m4:sch0}\n      { r \\in \\dom.nL } \\\\\n    \\evbcmeq{handle:pushR}{m4:act0}\n      {rep}{ rep \\2| (q \\fun nR.r) } \\\\\n    \\cschedule{handle:pushR}{m4:sch0}\n      { r \\in \\dom.nR } \n  \\end{align}\n  \\replace{handle:pushL}{m4:sch0}{m4:prog0}\n  \\replace{handle:pushR}{m4:sch0}{m4:prog1}\n  \\[ \\dummy{ r : \\REQ } \\]\n  \\begin{align}\n    \\progress{m4:prog0}{ r \\in pshL }{ r \\in \\dom.nL } \\\\\n    \\progress{m4:prog1}{ r \\in pshR }{ r \\in \\dom.nR }\n  \\end{align}\n\\paragraph{\\eqref{m4:inv3}}\n  \\begin{align}\n    \\invariant{m4:inv6}\n      { \\qforall{r}{ r \\in \\dom.nL }{item.(nL.r) = insL.r} }\\\\\n    \\evbcmeq{handle:pushL}{m4:act1}{nL}{ \\{ r \\} \\domsub nL }\n  \\end{align}  \n  \\begin{align}\n    \\invariant{m4:inv7}\n      { \\qforall{r}{ r \\in \\dom.nR }{item.(nR.r) = insR.r} }\\\\\n    \\evbcmeq{handle:pushR}{m4:act1}{nR}{ \\{ r \\} \\domsub nR }\n  \\end{align} \n\\subsection{ \\eqref{m4:inv10} } \n  \\begin{align}\n    \\invariant{m4:inv11}\n      { \\neg dummy \\in \\ran.nL } \\\\\n    \\invariant{m4:inv12}\n      { \\neg dummy \\in \\ran.nR }\n  \\end{align}\n\\subsection{New Progress Properties}\n  \\newevent{allocateL}{allocate\\_left}\n  \\begin{align*}\n    \\refine{m4:prog0}{ensure}{allocateL}{ \\index{r}{r' = r} }\n  \\end{align*}\n  \\[ \\indices{allocateL}{ r : \\REQ } \\]\n  \\[ \\param{allocateL}{ n : \\Node } \\]\n  \\begin{align}\n    \\evguard{allocateL}{m4:grd0}{ \\neg n \\in node } \\\\\n    \\assumption{m4:asm0}{ \\neg \\finite{\\Node} } \\\\\n    \\invariant{m4:inv8}{ \\finite{node} } \\\\\n    \\cschedule{allocateL}{m4:sch0}{ r \\in pshL } \\\\\n    \\evbcmeq{allocateL}{m4:act0}{nL}{nL \\1| (r \\fun n)} \\\\\n    \\evbcmeq{allocateL}{m4:act1}{item}{item \\1| (n \\fun insL.r)} \\\\\n    \\evbcmeq{allocateL}{m4:act2}{node}{ node \\bunion \\{n\\}}\n  \\end{align}\n  \\newevent{allocateR}{allocate\\_right}\n  \\begin{align*}\n    \\refine{m4:prog1}{ensure}{allocateR}{ \\index{r}{r' = r} }\n  \\end{align*}\n  \\[ \\indices{allocateR}{ r : \\REQ } \\]\n  \\[ \\param{allocateR}{ n : \\Node } \\]\n  \\begin{align}\n    \\evguard{allocateR}{m4:grd0}{ \\neg n \\in node } \\\\\n    \\cschedule{allocateR}{m4:sch0}{ r \\in pshR } \\\\\n    \\evbcmeq{allocateR}{m4:act0}{nR}{nR \\1| (r \\fun n)} \\\\\n    \\evbcmeq{allocateR}{m4:act1}{item}{item \\1| (n \\fun insR.r)} \\\\\n    \\evbcmeq{allocateR}{m4:act2}{node}{ node \\bunion \\{n\\}}\n  \\end{align}\n\n\\end{machine}\n\\begin{machine}{m5}\n  \\refines{m4}\n  \\[ \\variable{ left, right : \\Node \\pfun \\Node } \\]\n  \\[ \\variable{ LH, RH : \\Node } \\]\n  \\begin{align}\n    \\invariant{m5:inv0}{ left \\in node \\tfun node } \\\\\n    \\invariant{m5:inv1}{ right \\in node \\tfun node }  \\\\\n    \\invariant{m5:inv2}\n      { p < q \\1\\implies LH = rep.p \\land RH = rep.(q\\0-1) }  \\\\\n    \\invariant{m5:inv3}\n      { p = q \\1\\implies LH = dummy \\land RH = dummy }  \\\\\n    \\invariant{m5:inv4}{ left.dummy = dummy }  \\\\\n    \\invariant{m5:inv5}{ right.dummy = dummy }  \\\\\n    \\initialization{m5:init0}{ left \\1= (dummy \\fun dummy) } \\\\\n    \\initialization{m5:init1}{ right \\1= (dummy \\fun dummy) } \\\\\n    \\initialization{m5:init2}{ LH = dummy \\land RH = dummy }\n  \\end{align}\n\n%   \\begin{align}\n    \\invariant{m5:inv6}\n      { \\qforall{i}{\\betweenR{p}{i}{q\\0-1}}{ right.(rep.i) = rep.(i+1) } } \\\\\n    \\invariant{m5:inv7}\n      { \\qforall{i}{\\betweenR{p}{i}{q\\0-1}}{ left.(rep.(i+1)) = rep.i } } \n%   \\end{align}\n% \\subsection{Pop}\n%   \\begin{align}\n    \\invariant{m5:inv8}\n      { left.LH = dummy } \\\\\n    \\invariant{m5:inv9}\n      { right.RH = dummy } \\\\\n      \n%   \\end{align}\n\\subsection{Push}\n\\subsection{Allocate}\n\\end{machine}\n\\end{document}\n", "meta": {"hexsha": "07b2706fa11dd3b47f326177bbf3e99ad05554f1", "size": 14963, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Tests/lock-free deque/main13.tex", "max_stars_repo_name": "literate-unitb/literate-unitb", "max_stars_repo_head_hexsha": "0d843456dc103bb09babc5b12855435d2e10f534", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-07-27T11:05:56.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-20T14:53:33.000Z", "max_issues_repo_path": "Tests/lock-free deque/main13.tex", "max_issues_repo_name": "unitb/literate-unitb", "max_issues_repo_head_hexsha": "0d843456dc103bb09babc5b12855435d2e10f534", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32, "max_issues_repo_issues_event_min_datetime": "2017-06-25T03:53:02.000Z", "max_issues_repo_issues_event_max_datetime": "2017-06-25T04:28:38.000Z", "max_forks_repo_path": "Tests/lock-free deque/main13.tex", "max_forks_repo_name": "literate-unitb/literate-unitb", "max_forks_repo_head_hexsha": "0d843456dc103bb09babc5b12855435d2e10f534", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5843520782, "max_line_length": 85, "alphanum_fraction": 0.6053598877, "num_tokens": 6143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160666, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3315220333719305}}
{"text": "\\documentclass[11pt]{article}\n\n\\usepackage{graphicx}\n\\usepackage{courier}\n\\usepackage{underscore}\n\n\\title{Turing Machine Documentation}\n\\author{Adam Yedidia}\n\n\\begin{document}\n    \n\\maketitle\n\nThis document explains the structure of the Turing machines used in this project. It is intended for users who are curious about the algorithm. Note that this document also appears nearly verbatim in Section 8 (Compilation and Processing) at:  \\\\ \\\\\n\\texttt{parsimony/tex/busybeaver/busybeaver.pdf} \\\\\n\nThere are two ways to think about the layout of the tape symbols: with a $4$-symbol alphabet ($\\{\\texttt{\\_}, \\texttt{1}, \\texttt{H}, \\texttt{E}\\}$, blank symbol \\texttt{\\_}), and with a $2$-symbol alphabet ($\\{\\texttt{a}, \\texttt{b}\\}$, blank symbol \\texttt{a}). \\ The $2$-symbol alphabet version is the one that's ultimately used for the results in this paper, since we advertised a Turing machine that used only two symbols. \\ However, in nearly all parts of the Turing machine, the $2$-symbol version of the machine is a direct translation of the $4$-symbol version, according to the following mapping:\n\n\\begin{itemize}\n\\item $\\texttt{\\_} \\leftrightarrow \\texttt{aa}$\n\\item $\\texttt{1} \\leftrightarrow \\texttt{ab}$\n\\item $\\texttt{H} \\leftrightarrow \\texttt{ba}$\n\\item $\\texttt{E} \\leftrightarrow \\texttt{bb}$\n\\end{itemize}\n\nThe sections that follow sometimes refer to the \\texttt{ERROR} state. \\ Transitions to the \\texttt{ERROR} state should never be taken under any circumstances, and are useful for debugging purposes.\n\n\\section{Concept} \\label{sec:ontape}\n\nA directory of TMD functions is converted at compilation time to a string of bits to be written onto the tape, along with other states designed to interpret these bits. \\ The resulting Turing machine has three main components, or \\emph{submachines}:\n\n\\begin{enumerate}\n\\item The \\emph{initializer} sets up the basic structure of the variable registers and the function stack.\n\\item The \\emph{printer} writes down the binary string that corresponds to the compiled TMD code.\n\\item The \\emph{processor} interprets the compiled binary, modifying the variable registers and the function stack as necessary.\n\\end{enumerate}\n\nThe Turing machine's control flow proceeds from the initializer to the the printer to the interpreter. \\ In other words, initializer states point only to initializer states or to printer states, printer states point only to printer states or to interpreter states, and interpreter states point only to interpreter states or the \\texttt{HALT} state.\n\nThis division of labor, while seemingly straightforward, actually constitutes an important idea. \\ The problem of the compiler is to convert a higher-level representation---a machine with many tapes, a larger alphabet, and a function stack---to the lower-level representation of a machine with a single tape, a $2$-symbol alphabet and no function stack. \\ The immediately obvious solution, and the one taught in every computability theory class as a proof of the equivalence of different kinds of Turing machines, is to have every ``state'' in the higher-level machine compile down to many states in the lower-level machine. %See Figure~\\ref{fig:mttost} for a visual representation of what such a conversion might look like.\n\nWhile simple, this approach is suboptimal in terms of the number of states. \\ As is nearly always true when designing systems to be parsimonious, the clue that improvement is possible lies in the presence of repetition. \\ Each state transition in the higher-level machine is converted to a group of lower-level states with the same basic structure. \\ Why not instead explain how to perform this conversion exactly once, and then apply the conversion many times?\n\nThis idea is at the core of the division of labor described previously. We begin by writing a description of the higher-level machine onto the tape, and then ``run'' the higher-level machine by reading what is on the tape with a set of states that understands how to interpret the encoded higher-level machine. We refer to this idea as \\emph{on-tape processing}. The printer writes the TMD program onto the tape, and the processor executes it. As a result of using this scheme, we incur a constant \\emph{additive} overhead---we have to include the processor in our final Turing machine---but we avoid the constant \\emph{multiplicative} overhead required for the na\\\"ive scheme.\n\nThe subsections that follow describe each of the three submachines---the initializer, the printer, and the processor---in greater detail.\n\n\\section{The Initializer}\n\nThe initializer starts by writing a counter onto the tape which encodes how many registers there will be in the program. \\ Using the value in that counter, it creates each register, with demarcation patterns between registers, and unique identifiers for each register. \\ Each register's value begins with the pattern of non-blank symbols laid out in the \\texttt{initvar} file. \\ The initializer also creates the program counter, which starts at 0, and the function stack, which starts out with only a single function call to the top function in the \\texttt{functions} file.\n\nFigure~\\ref{fig:postinit} is a detailed diagram describing the tape's state when the initializer passes control to the printer.\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[scale=0.36]{figs/postinit.png}\n\\caption{The state of the Turing machine tape after the initializer completes. \\ The top bar is a high-level description of what each part of the Turing machine tape represents. \\ The middle bar is an encoding of the tape in the standard $4$-symbol alphabet; the bottom bar is simply the translation of that tape into the $2$-symbol alphabet. \\label{fig:postinit}}\n\\end{center}\n\\end{figure}\n\n\\section{The Printer} \\label{sec:introspect}\n\n\\subsection{Specification}\n\nThe printer writes down a long binary string which encodes the entirety of the TMD program onto the tape.\n\nFigure~\\ref{fig:postprog} shows the tape's state when the printer passes control to the processor.\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[scale=0.36]{figs/postprog.png}\n\\caption{The state of the Turing machine tape after the printer completes. \\ The top bar is a high-level description of the entire tape; unfortunately, at this point there are so many symbols on the tape that it is impossible to see everything at once. \\ For a detailed view of the first two-thirds of the tape (registers, program counter, and stack), see Figure~\\ref{fig:postinit}. \\ The bottom three bars show a zoomed-in view of the program binary. \\ From the top, the second bar gives a high-level description of what each part of the program binary means; the third bar gives the direct correspondence between $4$-symbol alphabet symbols on the tape and their meaning in TMD; the fourth and final bar gives the translation of the third bar into the $2$-symbol alphabet. \\label{fig:postprog}}\n\\end{center}\n\\end{figure}\n\n\\subsection{Introspection}\n\nWriting down a long binary string onto a Turing machine tape in a parsimonious fashion is not as straightforward as it might initially appear. \\ The first idea that comes to mind is simply to use one state per symbol, with each state pointing to the next, as shown in Figure~\\ref{fig:naiveprog}.\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[scale=0.25]{figs/naiveprog.png}\n\\caption{A na\\\"ive implementation of the printer. \\ In this example, the hypothetical program is ten bits long, and the printer uses ten states, one for each bit. \\ In the diagram, the blue symbol is the symbol that is read on a transition, the red letter indicates the direction the head moves, and the green symbol indicates the symbol that it written. \\ Note the lack of transitions on reading a \\texttt{b}; this is because in this implementation, the printer will only ever read the blank symbol, which is \\texttt{a}, since the head is always proceeding to untouched parts of the tape. \\ It therefore makes no difference what behavior the Turing machine adopts upon reading a \\texttt{b} in states 1-10 (and therefore \\texttt{b} transitions are presumed to lead to the \\texttt{ERROR} state) \\label{fig:naiveprog}}\n\\includegraphics[scale=0.25]{figs/introspectprog.png}\n\\caption{An introspective implementation of the printer. \\ In this example, the hypothetical program is $k=10$ bits long, and so the word size must be 2 (since $w=2$ is the largest $w$ such that $w2^w \\le 10$). \\ There are therefore $n_w = \\left \\lceil{\\frac{k}{w}}\\right \\rceil = 5$ data states, each encoding two bits. \\ The \\texttt{b} transitions carry the information about the encoding; note that each one only points to one of the last four data states. \\ The last four data states have in parentheses what word we mean to encode if we point to them. \\label{fig:introspectprog}}\n\\end{center}\n\\end{figure}\n\nOn closer examination, however, this approach is quite wasteful for all but the smallest binary files. \\ Every \\texttt{a} transition points to the next state in the sequence, and none of the \\texttt{b} transitions are used at all! \\ Indeed, the only information-bearing part of the state is the single bit contained in the choice of which symbol to write. \\ But in theory, far more information than that could be encoded in each state. \\ In a machine with $n$ states, each state could contain $2(\\log_2(n) + 1)$ bits of information, because each of its two transitions could point to any of the $n$ states, and write either an \\texttt{a} or a \\texttt{b} onto the tape. \\ Of course, this is only in theory; in practice, to extract the information contained in therefore Turing machine's states and translate it into bits on the tape is nontrivial.\n\nWe will use a scheme originally conceived by Ben-Amram and Petersen and refined further and suggested to us by Luke Schaeffer. \\ It does not achieve the optimal theoretical encoding described above, but is relatively simple to implement and understand, and is within a factor of $2$ of optimal for large binary strings. \\ Schaeffer named Turing machines that use this idea \\emph{introspective}.\n\nIntrospection works as follows. \\ If the binary string contains $k$ bits, then let $w$ be the \\emph{word size}. The word size $w$ takes the largest value it can such that $w2^w \\le k$. \\ We can split the binary string into $n_w = \\left \\lceil{\\frac{k}{w}}\\right \\rceil$ \\emph{words} of $w$ bits each (we can pad the last word with copies of the blank symbol). \\ In our scheme, each word in the bit-string is represented by a \\emph{data state}. \\ Each data state points to the state representing the next word in the sequence for its \\texttt{a} transition, but which state the \\texttt{b} transition points to encodes the next word. \\ Every \\texttt{b} transition points to one of the last $2^w$ data states, thereby encoding $w$ bits of information.\n\nOf course, the encoding is useless until we specify how to extract the encoded bit-string from the data states. \\ The extraction scheme works as follows. \\ To query the $i^\\textrm{th}$ data state for the bits it encodes, we run the data states on the string $\\texttt{a}^{i-1}\\texttt{b}\\texttt{a}^{\\infty}$ (a string of $i-1$ \\texttt{a}'s followed by a \\texttt{b} in the $i^\\textrm{th}$ position). \\ After running the data states on that string, what remains on the tape is the string $\\texttt{b}^{i-1}\\texttt{a}\\texttt{b}^r\\texttt{a}^{\\infty}$, assuming that the $i^\\textrm{th}$ data state pointed to the $r^\\textrm{th}$-to-last data state. \\ Thus, what we're left with is essentially a unary encoding of the ``value'' of the word in binary. \\ Thus, the job of the extractor is to set up a binary counter which removes one \\texttt{b} at a time and increments the counter appropriately. \\ Then, afterward, the extractor reverts the tape back to the form $\\texttt{a}^i\\texttt{b}\\texttt{a}^{\\infty}$, shifts all symbols on the tape over by $w$ bits, and repeats the process. \\ Finally, when the state beyond the last data state sees a \\texttt{b} on the tape, we know that the process has completed, and we can pass control to the processor. \\ Figure~\\ref{fig:introspectprog} shows the whole procedure.\n\nHow much have we gained by using introspection for encoding the program binary, instead of the na\\\"ive approach? \\ It depends on how large the program binary is. \\ Using introspection incurs an $O(\\log k)$ \\emph{additive} overhead, because we have to include the extractor in our machine. \\ (Our implementation of the extractor takes $10w + 17$ states. It's possible to build a constant-size extractor, but it's not worth it for our value of $w$) \\ In return, we save a \\emph{multiplicative} factor of $w$ (which scales with $\\log k$) on the number of data states needed.\n\nThis is plainly not worth it for the $10$-bit example binary shown in Figs.~\\ref{fig:naiveprog} and~\\ref{fig:introspectprog}. \\ For that binary, we require $69$ additional states for the extractor in order to save $5$ data states. \\ For real programs, however, it is worth it, as can be seen from the following table.\n\n\\begin{center}\n    \\begin{tabular}{||c c c c c c c||}\n    \\hline\n    Program & Binary Size & $w$ & $n_w$ & Extractor Size & States (Na\\\"ive) & States (Introspective) \\\\ [0.5ex]\n    \\hline\\hline\n    Example TMD & 116 & 4 & 29 & 57 & 116 & 86 \\\\\n    \\hline\n    Goldbach & 4,964 & 9 & 552 & 107 & 4,964 & 659 \\\\\n    \\hline\n    Riemann & 9,532 & 10 & 1,024 & 117 & 9,532 & 1,141 \\\\\n    \\hline\n    ZFC & 38,956 & 11 & 3,542 & 127 & 38,956 & 3,621 \\\\\n    \\hline\n    \\end{tabular}\n\\end{center}\n\nOne minor detail concerns the numbers presented for the Riemann program. \\ Ordinarily, with a binary of size 9,532, we would opt to split the program into 1,060 words of 9 bits each plus a 107-state extractor, since 9 is the greatest $w$ such that $w2^w <$ 9,532. \\ But because 9,532 is so close to the ``magic number'' 10,240, it's actually more parsimonious to pad the program with copies of the blank symbol until it's 10,240 bits long, and split it into 1,024 words of $10$ bits each plus a $117$-state extractor.\n\n\n\\section{The Processor}\n\nThe processor's job is to interpret the code written onto the tape and modify the variable registers and function stack accordingly. \\ The processor does this by the following sequence of steps:  \\\\ \\\\\nSTART:\n\\begin{enumerate}\n\\item Find the function call at the top of the stack. Mark the function $f$ in the code whose ID matches that of the top function call.\n\\item Read the current program counter. Mark the line of code $l$ in $f$ whose line number matches the program counter.\n\\item Read $l$. Depending on what type of command $l$ is, carry out one of the following three lists of tasks.\n\\end{enumerate}\n\n\\noindent IF $l$ IS AN EXPLICIT TAPE COMMAND:\n\\begin{enumerate}\n\\item Read the variable name off $l$. Index the variable name into the list of variables in the top function on the stack. This list of variables corresponds to the mapping between the function's local variables and the register names.\n\\item Match the indexed variable to its corresponding register $r$. Mark $r$. Read the symbol $s_r$ to the right of the head marker in that register.\n\\item Travel back to $l$, remembering the value of $s_r$ using states. Find and mark the reaction $x$ corresponding to the symbol. See what symbol $s_w$ should be written in response to reading $s_r$.\n\\item Travel back to $r$, remembering the value of $s_w$ using states. Replace $s_r$ with $s_w$.\n\\item Travel back to $x$. See which direction $d$ the head should move in response to reading $s_r$.\n\\item Travel back to $r$, remembering the value of $d$ using states. Move the head marker accordingly.\n\\item Travel back to $x$. See if a jump is specified. If a jump is specified, copy the jump address onto the program counter. Otherwise, increment the program counter by 1.\n\\item Go back to START.\n\\end{enumerate}\n\n\\noindent IF $l$ IS A FUNCTION CALL:\n\\begin{enumerate}\n\\item Write the function's name to the top of the stack.\n\\item For each variable in the function call, index the variable name into the list of variables in the top function on the stack. This list of variables corresponds to the mapping between the function's local variables and the register names. Push the corresponding register names in the order that they correspond to the variables in the function call.\n\\item Copy the current program counter to the return address of the newborn function call at the top of the stack.\n\\item Replace the current program counter with 0 (meaning ``read the first line of code'').\n\\item Go back to START.\n\\end{enumerate}\n\n\\noindent IF $l$ IS A RETURN STATEMENT:\n\\begin{enumerate}\n\\item Replace the current program counter with $f$'s return address.\n\\item Increment the program counter by 1.\n\\item Erase the call to $f$ from the top of the stack.\n\\item Check if the stack is now empty. If so, halt.\n\\item Go back to START.\n\\end{enumerate}\n\n\n\\end{document}", "meta": {"hexsha": "4743a7fa48ebae9dfc7d0cc79af54fc73c3894da", "size": 16851, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/docs/tm_doc.tex", "max_stars_repo_name": "ricsonc/parsimony", "max_stars_repo_head_hexsha": "37cbead5421f546b2f687c1a916fc50ad21f417d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tex/docs/tm_doc.tex", "max_issues_repo_name": "ricsonc/parsimony", "max_issues_repo_head_hexsha": "37cbead5421f546b2f687c1a916fc50ad21f417d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/docs/tm_doc.tex", "max_forks_repo_name": "ricsonc/parsimony", "max_forks_repo_head_hexsha": "37cbead5421f546b2f687c1a916fc50ad21f417d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 104.6645962733, "max_line_length": 1298, "alphanum_fraction": 0.7629220818, "num_tokens": 4215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.6150878555160666, "lm_q1q2_score": 0.3315220333719304}}
{"text": "\\documentclass[11pt]{report}\n\\renewcommand{\\baselinestretch}{1.1}\n\\usepackage[utf8]{inputenc}\n\\usepackage{amsmath,mathtools}\n\\usepackage{tcolorbox}\n\\usepackage{multirow}\n\\newcommand{\\mbf}[1]{\\mathbf{#1}}\n\\newcommand{\\tbf}[1]{\\textbf{#1}}\n\\newcommand{\\dsum}[3]{$\\sum^{#1}_{#2}{#3}$}\n\\newcommand{\\dint}[3]{\\int^{#1}_{#2}{#3}}\n\\newcommand{\\tit}[1]{\\textit{#1}}\n\\newcommand{\\fn}[1]{\\footnote{#1}}\n\\newcommand{\\de}[2]{\\frac{d{#1}}{d{#2}}}\n\\newcommand{\\ch}[2]{\\Gamma^{#1}_{#2}}\n\\newcommand{\\chris}{\\ch{\\mu}{\\alpha \\beta}=\\frac{1}{2}g^{\\mu \\lambda}(\\p_{\\alpha} g_{\\beta \\lambda}+\\p_\\beta g_{\\alpha \\lambda} - \\p_\\lambda g_{\\alpha \\beta})}\n\\newcommand{\\p}{\\partial}\n\\newcommand{\\pe}[2]{\\frac{\\partial{#1}}{\\partial{#2}}}\n\\newcommand{\\n}{\\nonumber}\n\\newcommand{\\cbox}{tcolorbox}\n\\newcommand{\\cc}[1]{\\left({#1}\\right)}\n\\newcommand{\\rr}[1]{\\left[{#1}\\right]}\n\\newcommand{\\vd}[1]{\\dot{\\vec{#1}}}\n\\newcommand{\\tx}[1]{\\text{#1}}\n\n\\begin{document}\n\\title{Cluster Mergers}\n\\author{Divesh Jain}\n\\maketitle\n\\tableofcontents\n\n\\chapter{Introduction}\nThe idea of this document is to basically cover all theoretical aspects of areas and bootstrapping related to Ruta's project. \n\\begin{itemize}\n\\item Understanding theory behind radiation\n\\item cover synchrotron and review papers eventually\n\\item How shocks lead to Cosmic Rays(finding a connection between radio and X-ray) - \\textbf{Read VanWeeren Review}\n\\item The type of mechanism involved in particle acceleration(Fermi I and Fermi II Order acceleration ) - \\textbf{Read Brunetti Review}\n\\end{itemize}\nOver many areas, one area I am thoroughly interested is in particle acceleration mechanism.\n\\chapter{Basics behind Radiation}\n\\section{Principles of Special Relativity}\nTo describe a physical process we require both spatial and temporal co-ordinates of the events, which can be put to a single entity of four numbers $x^i=(t,\\mbf{x})$. For the purpose of this article and following sections to come Latin indices \\tit{a,b,c..,i,j,k} run over 0 , 1, 2 and 3; where 1, 2, 3 denote space dimensions.The Greek indices would be used to represent just the spatial dimensions.\\\\\n\nIn the following discussion we pay special attention to a subset of coordinate systems, called \\textbf{inertial coordinate systems.} \\\\\n\\textbf{How do we create this inertial coordinate system?}\\\\\nThese coordinates systems, are defined by the property that a material particle, far removed from all external influences, will move with uniform velocities in such systems. verify this criterion. \\textbf{But, there is no fundamental reason why any one class of coordinate systems should be preferred over others except for mathematical convenience.}Just to make our lives simpler, we still postulate that such a set of coordinates exists where any frame moves with uniform velocity with respect to an inertial frame.\\\\\n\n\\textbf{Rules of the game}\nIt is experimentally found that these two statements are true:\n\\begin{itemize}\n\\item All laws of nature are identical in all frames of reference, that is, the equations expressing the laws of nature are invariant in form with respect to the coordinate transformation connecting two frames.\n\\item Interactions between material particles does not take instantaneously and there exists a maximum speed of propagation for information of interaction. We call it \\tit{c}.\n\\end{itemize}\n\nThe implication of the first point here is, that \\tbf{the maximum speed of information propagation is same in all inertial frames.}\n\n\n\nSection copied from paddy's book:\\\\\n\\textbf{To begin with, this result rules out any absolute nature for simultaneity; two events that appear to occur at the same time in one inertial frame will not, in general, appear to occur at the same time in another inertial frame.}\\\\\n\\textbf{Another important consequence requires first a mathematical construct. We define\n\\begin{equation}\nds^2=c^2dt^2 - dx^2 - dy^2 - dz^2\n\\end{equation}\nIf $ds=0$ in one frame then it implies that infinitesimally separated events $\\mbf{P\\text{ and } Q}$ with coordinates $x^i$ and $x^i+dx^i$ can be connected by a light signal. And because speed of light is same in all inertial frames, therefore $ds^\\prime=0$ is also true in other frame of references. }\n\\\\\n\\textbf{We want to find the value of this length element in different inertial frames, to do that}:\\\\\nAs a second step what we do is to treat $ds^2$ as a function of $(ds^\\prime)^2$ and we can expand $ds^2$ as a function of $(ds^\\prime)$ given as\n\\begin{eqnarray*}\nds^2=\\alpha + a ds^{\\prime^2}\\\\\n\\text{Now for $ds=0$, the distance element  $ds^\\prime=0$ } \\implies \\alpha=0\\\\\n\\end{eqnarray*}  \nWe propose, that $a$ be a function of relative velocity $V$ between frames. Further, homogeneity and isotropy would require that $a(\\mbf{V})$ be only a function of magnitude of $|\\mbf{V}|$.\n\\section{Basics Of Electromagnetic Radiation}\n\\subsection{External Fields Of Force}\n\n\\subsection{Introduction to radiation from an accelerated charge}\nThe Electric Field in case of a stationary charged particle or charge moving with constant velocity falls as $r^{-2}$. When the charged particle accelerates then, the charge picks up a part which falls as $r^{-1}$, called the \\textbf{radiation field}.\\\\\nA field which falls as $E \\propto r^{-1}$, has an energy flux $S \\propto E^2 \\propto r^{-2}$; we also know that the surface area of sphere increases as $r^2$. \\textbf{Therefore in case of an accelerating charge, same amount of energy will flow through spheres of different radii, and also allows radiation field to travel large distances.}\n\\\\\n\\subsubsection{Understanding Why accelerated charge radiate?}\n\\textbf{What is the $r$ dependence in Electric Field? }\\\\\nFrom an earlier equation $\\mbf{A}$ scales as the velocity $\\mbf{v}$ of the charge. Because $\\dot{\\mbf{A}}$ contributes to E, there will be one  term in $\\mbf{E}$ that is $\\propto \\; \\; \\mbf{a}$. This is, of course, in addition to the usual coulomb term that is independent of $\\mbf{a}$ and falls as $\\mbf{r}^{-2}$. As electric field is linear in charge $q$ as well,this term is linear in $q$. \\\\\n\nLet us consider this electric field in the instantaneous rest frame, then a general form \n\\begin{equation}\nE=C(\\theta)\\frac{qa}{c^nr^m}=C(\\theta) \\cc{\\frac{q}{r^2}}\\cc{\\frac{a}{c^nr^{m-2}}}\n\\end{equation}\nC is dimensionless which depends $\\theta$ between $\\mbf{r \\text{ and } a}$ and n and m need to be determined.(Because $v=0$ in the instantaneous rest  frame, the field cannot depend on the velocity). By dimensional analysis, it immediately follows that n=2 and m=1 . Hence\n\\begin{equation}\nE=C\\frac{qa}{c^2r}\n\\end{equation}\nHence we have a $r^{-1}$ dependence.\nFor C($\\theta$)\n\\section{Radiation by Moving Charges}\nBefore we start with the chapter, we accept the fact that \\textbf{accelerated charges emits electromagnetic radiation.}For, non relativistic motion the radiation is well described by Larmor's result.\\\\\nWe, first define Lienard-Wiechart Potentials and try to describe Fields for a Point Charge.\n\\subsection{Lienard-Wiechart Potentials for a point charge}\nIf there are no \\textbf{Incoming Fields}, then the 4-vector potential caused by a charged particle in motion is:\n\\begin{equation}\\label{Vpot}\nA^\\alpha(x)=\\frac{4 \\pi}{c}\\int d^4x^\\prime D_r(x-x^\\prime)J^\\alpha(x^\\prime)\n\\end{equation}\nwhere $D_r(x-x^\\prime)$ is the \\textbf{retarded Green Function} and 4-vector current is given as:\n\\begin{equation}\\label{Cden}\nJ^\\alpha(x^\\prime)=ec\\int d\\tau V^\\alpha(\\tau)\\delta^{(4)}\\rr{x^\\prime-r(\\tau)}\n\\end{equation}\n\\textbf{I think that the above equation gives 4 vector current density where $J^{\\alpha}(x^\\prime)$ defines the current density at point $(x^\\prime)$. This quantity depends on 4 velocity of moving charge($V^\\alpha(\\tau)$) at time $\\tau$ and $r^\\alpha$ is its position.}\\\\\n\nNow, we substitute \\eqref{Cden} and \\textbf{Retarded Green's Function} in \\eqref{Vpot}. After this we integrate it over a volume $d^4 x^\\prime$ which results in\n\n\\begin{eqnarray*}\nA^\\alpha(x)=\\frac{4 \\pi}{c}\\int d^4x^\\prime D_r(x-x^\\prime)ec\\int d\\tau V^\\alpha(\\tau)\\delta^{(4)}\\rr{x^\\prime-r(\\tau)}\\\\\nA^\\alpha(x)=e4 \\pi\\int d^4x^\\prime D_r(x-x^\\prime)\\int d\\tau V^\\alpha(\\tau)\\delta^{(4)}\\rr{x^\\prime-r(\\tau)}\n\\end{eqnarray*}\n\n\n\n\\begin{equation}\\label{Vpotf}\nA^\\alpha(x)=2e\\int d\\tau V^\\alpha(\\tau)\\theta\\rr{x_0-r_0(\\tau)}\\delta\\rr{x-r(\\tau)}^2\n\\end{equation}\n\nThe remaining integral over the charge's proper time gives a contribution only at $\\tau=\\tau_0$ where $\\tau_0$ is defined by the line cone condition:\n\\begin{equation}\\label{lc}\n\\rr{x-r(\\tau_0)}^2=0\n\\end{equation}\nNow, the light-cone reaches upto $r(\\tau_0)$, and \\textbf{the requirement of retardation condition is $x_0>r_0(\\tau_0)$}.\n\\begin{figure}[h!]\n\\includegraphics[width=0.7\\linewidth]{lienardpot.png}\n\\label{radlineard}\n\\end{figure}\nNow, focus on Fig. \\ref{radlineard}. \n\\begin{itemize}\n\\item Green Function is different from zero only on the backward lightcone of the observation point.\n\\item World line of the particle, $r(\\tau)$, intersects the light cone at only two observation point, one earlier and one later than $x_0$.\n\\item Consequently in the earlier part, $r^\\alpha(\\tau_0)$ is the only part of the path that contributes to the field at $x^\\alpha$.\n\\end{itemize}\nNow, we know that\n\\begin{equation}\\label{deltatau}\n\\delta[f(x)]=\\sum_i \\frac{\\delta(x-x_i)}{|\\cc{\\pe{f}{x}}_{(x=x_i)}|}\n\\end{equation}\n\\textbf{Note:} Here, it was assumed that the zeros of $f(x)$ at $(x=x_i)$ are all linear.\\\\\nand also we also need,\n\\begin{equation}\n\\frac{d}{d\\tau}\\rr{x-r(\\tau)}^2 =2\\rr{x-r(\\tau)}_\\beta \\cc{-\\frac{d r(\\tau)}{d\\tau}}^\\beta=-2\\rr{x-r(\\tau)}_\\beta V^\\beta(\\tau)\n\\end{equation}\nwhich is evaluated at point $\\tau=\\tau_0$\n\\textbf{So, can we say that the motion of charged particle $r(\\tau)$ is completely determined by the potential term?}\n\nIn our case, $\\rr{x-r(\\tau)}^2$ is function of $\\tau$. In our case, only earlier point contributes to the path, so we consider only $r^\\alpha(\\tau_0)$ as zeros for \\eqref{deltatau}.\\\\\nTherefore, we have,\n\\begin{equation}\\label{deltatau}\n\\delta([x-r(\\tau)]^2)= \\frac{\\delta(x-r(\\tau))}{|-2\\rr{x-r(\\tau)}_\\beta V^\\beta(\\tau)|_{\\tau=(\\tau_0)}}\n\\end{equation}\nNow, putting everything in \\eqref{Vpotf}:\n\\begin{eqnarray*}\nA^\\alpha(x)=2e\\int d\\tau V^\\alpha(\\tau)\\theta\\rr{x_0-r_0(\\tau)}\\delta\\rr{x-r(\\tau)}^2\\\\\n=2e\\int d\\tau V^\\alpha(\\tau)\\theta\\rr{x_0-r_0(\\tau)}\\frac{\\delta(x-r(\\tau))}{|-2\\rr{x-r(\\tau)}_\\beta V^\\beta(\\tau)|_{\\tau=(\\tau_0)}}\n\\end{eqnarray*}\n\\begin{equation}\n\\implies A^\\alpha(x)=\\frac{e V^\\alpha(\\tau)}{\\rr{x-r(\\tau)}_\\beta V^\\beta(\\tau)}|_{\\tau=(\\tau_0)}\\\\\n\\end{equation}\nor,\n\\begin{equation}\\label{liendardVpot}\n\\implies A^\\alpha(x)=\\frac{e V^\\alpha(\\tau)}{V . \\rr{x-r(\\tau)}}|_{\\tau=(\\tau_0)}\n\\end{equation}\nwhere, \\textbf{$\\tau_0$ is defined by \\eqref{lc} and Retardation requirement}. And \\textbf{\\eqref{liendardVpot} is called \\tit{Lienard-Wiechert potentials}}.\nWe can further work on it. Now, Let:\n\\begin{equation}\nx_0-r_0(\\tau_0) = \\mbf{|x_0-r_0(\\tau_0)|} \\equiv R\n\\end{equation}\nHence,\nwe can write:\n\\begin{eqnarray*}\n\\text{First we expand the individual 4 vector components of V.(x-r)}\\\\\nV.(x-r)=V_0\\rr{x_0-r_0(\\tau_0)}-\\mbf{V.\\rr{x-r(\\tau_0)}}\n=\\gamma cR-\\gamma\\mbf{v.n}R\\\\\n\\text{where, $\\mbf{n}$ is a unit vector in the direction of}\\\\\n\\text{$\\mbf{x-r(\\tau)}$ and $\\mbf{\\beta=v(\\tau)/c}$}\\\\\n\\implies \\gamma c R(1-\\mbf{\\beta .n})\n\\end{eqnarray*}\nFinally, we can wite the potential in the final form can be deomposed into components as\n\\begin{equation*}\n A^\\alpha(x)=\\frac{e V^\\alpha(\\tau)}{V . \\rr{x-r(\\tau)}}|_{\\tau=(\\tau_0)}\n\\end{equation*}\n\n\\section{Synchrotron Radiation: Basics}\nSynchrotron radiation is emitted by charges spiralling in a magnetic field moving at relativistic speeds.\\\\\n\\textbf{Why is it important?}\\\\\nSynchrotron has a broad frequency spectrum often corresponding to a million harmonics of the basic frequency of particle in motion.\\\\\n\n\nA charged particle in constant magnetic field moves in a circular trajectory in plane perpendicular to $\\mbf{B}$.\\\\\nThe angular velocity of such a particle with an energy E. If $v.\\mbf{B}=0$, then particle moves in a circular path of radius\n\\begin{equation}\nr_B=\\frac{v}{\\omega}=\\frac{mcv}{qB}\\gamma\n\\end{equation}\nBefore, we start with the business of Synchrotron. We first recapitulate the Synchrotron for non-relativistic electrons. \\\\\n\n\\begin{\\cbox}\nFor non relativistic electrons accelerated by magnetic fields are said to emit cyclotron radiation. The radiation is at frequency of gyration $\\omega=eB/m_ec$. \n\\end{\\cbox}\n\\textbf{For relativistic particles, this emission extends to higher frequencies and we call it Synchrotron Emission.}\n\n\\chapter{Continuum Radiation Processes}\n\\textbf{This Chapter is largely based on Klein Fetcher's book on galactic and intergalactic magnetic field, Chapter 2. The important point to note is, we will be doing the mathematical part behind radiation in our own time. This is a more applicative based study and less mathematical.}\\\\\n\\section{Introduction}\n\\textbf{Why is studying Sychrotron Radiation important?:}\\\\\nWe observe low frequency synchrotron radiation on galactic scales when relativistic electrons move in a magnetic field.\\\\ \nStudying synchrotron helps us to use it as a tool to trace magnetic fields in interstellar and intergalactic scales, by virtue of its \\textbf{radiation spectrum and polarisation properties}.\\\\\n\n\\textbf{What is the issue with observing this low frequency radiation?}\\\\\nThe main point of concern is at radio frequency we not only observe the synchrotron radiation, it is contaminated by free-free radiation coming from \\textbf{ionised HII regions} and \\textbf{ionised medium of milky way} galaxy and other galaxy.\\\\\n\nSo it becomes important for us to know both \\textbf{thermal(free-free)} and \\textbf{non thermal(synchrotron)} part of energy so that we can extract out the non thermal component.\\\\\n\\begin{\\cbox}\nFree-Free is called thermal radiation because it results from an ensemble of particles with a \\textbf{Maxwellian Energy Distribution}. On the other hand, energy distribution of synchrotron follows a power-law.\n\\end{\\cbox}\n\\begin{\\cbox}\nNote point: In order to produce measurable Synchrotron radiation vs measurable thermal radiation, the number of relativistic particles required is less lower than the thermal ones. \\textbf{Just because they are so energetic} \n\\end{\\cbox}\n\\section{Radiation of an Accelerated Electron}\n\\begin{figure}[th]\n\\includegraphics[scale=0.7]{singleprad.png}\\label{singleprad}\n\\caption{Geometry for a moving charged particle as seen from the point P}\n\\end{figure}\n\\textbf{What is the electric field for an accelerated electron?}\\\\\nSo we have an accelerated electron as Fig. \\ref{singleprad}. The velocity of the electron is $\\vec{v}$ and the acceleration is $\\vec{\\dot{v}}$, as seen by observer at some point P. \\textbf{Refer Chapter 14 Jackson} The electric field for such a particle is given as\n\\begin{equation}\n\\vec{E}=\\cc{\\frac{e}{c}}\\cdot \\frac{\\vec{n}\\times \\rr{\\cc{\\vec{n}-\\vec{\\beta}}\\times \\vec{\\dot{\\beta}}\\;}}{R\\cc{1-\\cos\\theta \\cdot \\beta}^3}\n\\end{equation}\n\\begin{itemize}\n\\item $\\vec{n}$ is unit vector pointing from the particle towards the observer.\n\\item $\\beta=\\frac{\\vec{v}}{c}$ and $\\vd{\\beta}=\\frac{\\vd{v}}{c}$\n\\end{itemize}\n\n\\textbf{What is the flux of radiation and the power radiated?}\\\\\nThe flux of radiation is given by \\textbf{Pontying Vector}\n\\begin{equation}\n\\vec{S}=\\frac{c}{4\\pi}\\cdot \\vec{E}\\times\\vec{B}=\\frac{c}{4\\pi}\\cdot |\\vec{E^2}|.\\vec{n}\n\\end{equation}\nThe \\textbf{power radiated into a unit solid angle per unit frequency and unit time} Units=[$Wstr^{-1}Hz^{-1}sec^{-1}$] is given by:\n\\begin{align}\n\\frac{dP(t)}{d\\Omega}&=&|\\vec{S}|\\cdot(1-\\beta \\cos \\theta)R^2\\\\\n&=&\\frac{e^2}{4 \\pi c}\\cdot \\frac{|\\vec{n}\\times\\rr{\\vec{n}-\\vec{\\beta}}\\times\\vd{\\beta}|^2}{(1-\\beta \\cdot \\cos \\theta)^5}\n\\end{align}\nR being the distance between observer at point P and the electron.\\\\\nThe above equation will be used in the following case and form:\n\\begin{itemize}\n\\item $\\beta<<1$ for  thermal radiation\n\\item $\\beta\\leq 1$ for non-thermal radiation\n\\end{itemize}\nIn order to find the power the above equation has to be modified over the $4\\pi$ solid angle of the sphere. \\textbf{Here, $\\theta=\\angle (\\vec{v},\\vec{n})$} and hence\n\\begin{equation*}\n\\cos \\theta = \\vec{n} \\cdot \\vec{\\beta}\n\\end{equation*}\n\\begin{\\cbox}\nWhen measuring flux densities of radio sources, we can calculate their radio power or luminosity once we can determine this distance using standard astronomical techniques.Hence R is not relevant in the derivations that we shall work out below. It is just a matter of conversion from flux density to power or monochromatic luminosity, or from flux to total power or luminosity. So, converting for instance flux density $S_\\nu$ to power $P_\\nu$ then reads\n\\begin{equation*}\nP_\\nu=4 \\pi R^2 S_\\nu\n\\end{equation*}\nAssuming the radio source emits isotropically.\n\\end{\\cbox}\n\\textbf{Skipping the section on free-free Radiation for now!}\n\\section{Synchrotron Radiation}\n\\textbf{Why is Synchrotron radiation important? }\\\\\nIt basically serves as a diagnostic tool to trace magnetic fields in the ISM and IGM. \\\\\n\\textbf{How are the electrons in IGM and ISM are relativistically energised?}\\\\\n\\begin{itemize}\n\\item Electrons are energised in ISM by the shock waves produced during supernovae explosions\\\\\n\\item and energised due to AGN activity, by galactic wakes\\fn{it is the hypersonic flow of intergalactic gas past a galaxy. \\textbf{not sure!!} } and by merging of galaxies for the case of IGM.\n\\end{itemize}\n\\textbf{A brief overview:}\n\\begin{itemize}\n\\item Relativistic electrons in magnetic field experience Lorentz force.\n\\item This force makes the particles move in helical motion.\n\\item This accelerated helical motion leads to synchrotron radiation.\n\\item This radiation has a characteristics frequency spectrum and is \\textbf{partially polarised.}\n\\end{itemize}\n\\begin{\\cbox}\n galaxies and AGN exhibit synchrotron radiation as soon as they come into existence, a mere few hundred million years after the Big Bang. In fact, the distribution of faint(hence distant)radio sources is characterised by near isotropy,in accord with the cosmological principle. The bulk of these sources are AGN, which may produce Doppler boosting, which renders them detectable out to cosmological distances. \n\\end{\\cbox}\nAnother important observable is Faraday Rotation is \\textbf{Faraday Rotation} - It allows us to estimate \\textbf{Magnetic field strength} and \\textbf{and their orientation} (towards and away from us) in the medium towards the radio source.\n\\subsection{Radiation from a single electron}\nSo as we already know power radiated from a single relativistic particle into a unit solid angle per unit frequency and per unit time is given by \\eqref{eq:rel1particle}\n\\begin{figure}[h!]\n\\includegraphics[height=4cm,width=9cm]{singleprad.png}\n\\caption{Geometry for a moving charged particle as seen from the point P}\n\\end{figure}\n\n\\begin{equation}\\label{eq:rel1particle}\n\\de{P}{\\Omega}=\\frac{e^2}{4 \\pi c} \\cdot \\frac{|\\vec{n}\\times \\rr{(\\vec{n}-\\vec{\\beta})\\times\\dot{\\vec{\\beta}}}|^2}{(1- \\vec{n}\\cdot \\vec{\\beta})^5}\n\\end{equation}\n\\begin{itemize}\n\\item $\\vec{n}$ is unit vector pointing from the particle towards the observer.\n\\item $\\beta=\\frac{\\vec{v}}{c}$ and $\\vd{\\beta}=\\frac{\\vd{v}}{c}$\n\\end{itemize}\nWhen dealing with relativistic particles, we study two cases of the direction of $\\vd{\\beta}$ and $\\beta$.\n\\begin{enumerate}\n\\item \\tbf{LINEAR ACCELERATOR or }($\\vd{\\beta} \\parallel \\beta$):\nThen we have the power radiated derived from \\eqref{eq:rel1particle} to be :\n\\begin{equation}\\label{eq:rel1particlelin}\n\\de{P}{\\Omega}=\\frac{e^2 \\dot{v^2}}{4 \\pi c} \\cdot \\frac{\\sin^2 \\theta}{(1- \\cos \\theta \\beta)^5}\n\\end{equation}\n\\tbf{It is to be noted that:the radiation pattern has a strong dependence on the angle \f and on the particle speed}. Refer to book to check out how $\\beta$ influences radiation pattern. \\tbf{\\tit{What do we mean when we say radiation pattern, what are we plotting?}}.\nThe reason for strong dependence of value of $\\beta$ on radiation pattern is because the maximum power radiated depends on $\\gamma$ i.e.\n\\begin{equation}\n\\de{P}{\\Omega}(\\theta_{max}) \\sim \\gamma^8\n\\end{equation}\nwhere,\n\\begin{equation}\n\\cos \\theta_{max}=\\frac{1}{3 \\beta}\\cc{\\sqrt{1+15 \\beta^2}-1}\n\\end{equation}\nThe above equations can be obtained by maximizing equation \\eqref{eq:rel1particlelin} with respect to $\\theta$ and then substituting  back in \\eqref{eq:rel1particlelin} and $\\theta_{max}=\\frac{1}{2\\gamma}$ i.e. is the maximum power is radiated when $\\theta$ is very small and photons are emitted in the direction of acceleration.\n\\begin{\\cbox}\nThe strong dependence on the Lorentz factor is called 'relativistic boosting' or 'beaming', meaning that a charged particle moving with relativistic speed emits essentially its whole radiation in the forward direction. \n\\end{\\cbox} \n\nThe total radiation of the relativistic particle is given by the integration:\n\\begin{eqnarray*}\nP(t)=\\int^{2\\pi} _{0} \\int^{\\pi} _{0} \\de{P}{\\Omega} d\\Omega \\\\\n\\implies P(t)=\\int^{2\\pi} _{0} \\int^{\\pi} _{0} \\frac{e^2 \\dot{v^2}}{4 \\pi c} \\cdot \\frac{\\sin^2 \\theta}{(1- \\cos \\theta \\beta)^5} \\sin^2 \\theta d\\theta d\\phi \\\\\n\\implies P(t)= \\frac{e^2 \\dot{v^2}}{2 c} \\int^{\\pi} _{0}  \\frac{\\sin^2 \\theta}{(1- \\cos \\theta \\beta)^5} \\sin^2 \\theta d\\theta \\\\\n\\implies P(t)=\\frac{2}{3}\\cdot \\frac{e^2 \\dot{v^2}}{c^3} \\cdot \\gamma^6\n\\end{eqnarray*}\n\n\\item \\tbf{Transverse or CYCLOTRON ACCELERATOR or SYNCHROTRON }($\\vd{\\beta} \\perp \\beta$): Check Figure \\ref{figtrac}. The geometry of and various angle required are given in right hand cartoon and the left hand cartoon refers to the same particle moving in interstellar magnetic field. \n\\begin{figure}[h!]\\label{figtrac}\n\\includegraphics[scale=1]{figtrac}\n\\caption{ Illustration of the various angles used in describing the transverse acceleration of a relativistic electron in a magnetic field}\n\\end{figure}\n\\end{enumerate}\n\\textbf{Define Pitch angle:}\\\\\nPitch angle is the motion of particle is inclined to the magnetic field vector. In Figure \\ref{figtrac} $\\chi$ is the \\textbf{pitch angle}.\\\\\n\n Now the, particle experiences \\textbf{Lorentz force} and $\\vec{\\beta} \\perp \\vd{\\beta}$ and \n\\begin{eqnarray}\n\\de{P}{\\Omega}=\\frac{e^2}{4 \\pi c} \\cdot \\frac{|\\vec{n}\\times \\rr{(\\vec{n}-\\vec{\\beta})\\times\\dot{\\vec{\\beta}}}|^2}{(1- \\vec{n}\\cdot \\vec{\\beta})^5}\n\\implies \\de{P}{\\Omega}=\\frac{e^2 \\dot{v^2}}{4 \\pi c^3} \\cdot \\frac{1-\\frac{\\sin^2 \\theta \\cos^2 \\phi }{\\gamma^2(1-\\beta \\cos \\theta)^2}}{(1-\\beta \\cos \\theta)^3}\n\\end{eqnarray}\n\\textbf{As in case of the linear accelerator, the relativistic motion causes a relativistic aberration of the radiation of the charged particle, i.e. a strong distortion of the radiation pattern. check Figure \\ref{figtracpa}}\n\\begin{figure}[h!]\\label{figtracpa}\n\\includegraphics[scale=1]{figtracpa.png}\n\\caption{Radiation pattern of the transversely accelerated electron ($\\beta$:0.8)}\n\\end{figure}\n\\textbf{Its main lobe can be shown to have a half-power width that is inversely proportional to the Lorentz factor 1=$1/\\gamma$ at half-maximum} or \n\\begin{equation}\n\\theta_{HP}\\approx 1/\\gamma =\\frac{m_0c^2}{E^2}\n\\end{equation}\nNote:The half-power width is the angular width of the radiation  pattern at which the power has dropped to half its maximum value.\\\\\n\\textbf{As in case of the transverse accelerator, the radiated power has a strong dependence on the Lorentz factor:\n\\begin{equation}\n\\de{P}{\\Omega} \\sim \\dot{v^2}\\gamma^6\n\\end{equation}\nand\n\\begin{equation}\nP(t)=\\int^{2 \\pi} _{0}\\int^{ \\pi} _{0} \\de{P}{\\Omega} d\\Omega \\sim \\dot{v^2}\\gamma^4\n\\end{equation}\n}\n\nNow, we try to calculate the Larmor Circle and at the end of it you would understand why we need it at all:\\\\\nNow, the equation of motion a charged particle in magnetic field is given by\n\\begin{equation}\nm\\vd{v}=m\\cdot (\\vec{v}\\times \\vec{\\omega_L})=\\frac{-e}{c}(\\vec{v}\\times \\vec{B})\n\\end{equation}\nLet us consider the pitch angle, $\\chi=90^circ$ i.e. the particle motion is perpendicular to the magnetic field.Hence,\n\\begin{eqnarray}\nm\\omega^2_Lr_L=m\\cdot \\frac{v^2}{r_L}=\\frac{e}{c} \\cdot vB\n\\implies m\\frac{v}{r_L}=\\frac{e}{c} B\\\\\n\\implies \\omega_L=\\frac{eB}{mc}\n\\end{eqnarray}\nNow for a relativistic particle we know, $m=\\gamma m_0$, since $E=mc^2=\\gamma m_0c^2$. Therefore,\n\\begin{equation}\n\\omega_L=\\frac{eB}{mc}\n\\end{equation}\nand the larmor radius for $v\\approx c$ is\n\\begin{equation}\nr_L=\\frac{v}{\\omega_L}=\\frac{m_0vc}{eB}\\cdot \\gamma\\approx \\frac{m_0c^2}{eB}\\cdot \\gamma =\\frac{E}{eB}\n\\end{equation}\nor in general,\n\\begin{\\cbox}\n\\begin{equation}\nr_L=\\frac{E}{eB}\\sin \\chi\n\\end{equation}\nWe realise that the Larmor radius does not depend on the mass of the particle, but just on its energy (and on the magnetic- field strength). \n\\end{\\cbox}\nNow, for a $\\gamma=1$ and a magnetic field of $B=10\\mu G$ we have a frequency of 28Hz. \n\\textbf{Now, the question may be asked that how can we observe such particles in radio regime? The answer to this question is in}\n\n\\begin{\\cbox}\n\\textbf{what we have found is the power emitted by the relativistic particle in the direction of observer, but we need to make a frame transition to observer's frame if we want to obtain power spectrum seen by the observer}\n\\end{\\cbox}\nTherefore, the way the observer observes the radiation from electron is is by calculating the time dependence of radiation as seen by the observer.\\\\\nNow, in order to calculate the radiation spectrum \\textbf{ we perform a Fourier analysis of the time-dependent radiation power of single particles,then 'fold in' their energy spectrum and then calculate the emissivity.} The frequency of the emitted pulses of the gyrating relativistic electrons \\textbf{ corresponds to the inverse of the time that the radiation pattern needs to sweep across the observer}.\nTherefore, we can visualize the radiation emitted by the particle as given in Fig. \\ref{figobsrad}\n\\begin{figure}\\label{figobsrad}\n\\includegraphics[scale=1]{figobsrad.png}\n\\end{figure}\n\\textbf{Now, how long does the pulse last in particle's frame of reference:}\\\\\nThe duration of the pulse in the particle's frame of reference is equal to:\n\\begin{equation}\n\\Delta t =\\frac{r_L\\theta_{HP}}{v}\\approx \\frac{r_L \\theta_{HP}}{c}\n\\end{equation}\nand since, $r_L \\approx \\frac{Ee}{B}$ and $\\theta_{HP}\\approx \\frac{1}{\\gamma}$, we find \n\\begin{equation}\n\\Delta t =\\frac{m_0 c}{e B}\n\\end{equation}\nOur next order of business would be transforming frames from particles to observer i.e. from t frame to $t^\\prime$.\\\\\nThe transformation is shown in Figure \\ref{figtrans}. What we need to account is the motion of particle when it emitted the pulse of duration $\\Delta t$. Therefore our transformation time is given as \n\n\\begin{figure}[h!]\\label{figtrans}\n\\includegraphics[width=\\linewidth]{figtrans.png}\n\\caption{geometry of the transformation from the particle's to the observer's reference frame}\n\\end{figure}\n\\begin{equation}\nt^\\prime=t+\\frac{|\\vec{r}-\\vec{r_L(t)}|}{c}\n\\end{equation}\nNow, the rate of change of time in one frame to another is given as follows:\n\\begin{eqnarray*}\nt^\\prime=t+\\frac{|\\vec{r}-\\vec{r_L(t)}|}{c}\\\\\n\\implies t^\\prime=t+\\frac{\\cc{\\cc{|\\vec{r}-\\vec{r_L(t)}|}^2}^{1/2}}{c}\\\\\n\\implies \\de{t^\\prime}{t}=1-\\frac{\\vec{r}-\\vec{r_L(t)}}{|\\vec{r}-\\vec{r_L(t)}|}\\cdot \\de{\\vec{r_L(t)}}{t}\\\\\n\\implies \\de{t^\\prime}{t}=1-\\frac{\\vec{n}\\cdot \\vec{v}}{c}=1-\\beta \\cdot \\cos \\theta_{HP}\\\\\n\\tx{I think $\\theta_{HP}$ is the average value of angle between $\\vec{n}$ and $\\vec{v}$}\\\\\n\\tx{and, for small angles}\\\\\n\\implies \\de{t^\\prime}{t}=1-\\beta \\cdot \\sqrt{1- \\theta^2_{HP}} \\\\\n\\implies \\de{t^\\prime}{t}=1-\\beta \\cdot \\sqrt{1- \\frac{1}{\\gamma^2}} \\\\\n\\implies \\de{t^\\prime}{t}=1-\\beta^2 =\\frac{1}{\\gamma^2} \\\\\n\\end{eqnarray*}\n\\begin{\\cbox}\n\\begin{equation}\n\\Delta t^\\prime =\\frac{\\Delta t }{\\gamma^2}\n\\end{equation}\n\n\\end{\\cbox}\nNow, Remember the argument of particle emitting at frequency 28Hz at $B=10\\mu G$, for $\\gamma=2000$, the frequency spectrum is shifted towards a $\\gamma^2$ higher range and that would be around $\\nu=700MHz$.\\\\\nNow we define \\tbf{a critical frequency} and the purpose of this being \\tbf{the particles produce a significant power at this frequency}. given as $\\omega_c =2 \\pi \\nu_c$. Even though $\\omega_c$ has different definitions, we will use one by Schwinger \n\\begin{equation}\n\\omega_c\\equiv \\frac{1}{\\frac{2}{3}\\Delta t^\\prime}\n\\end{equation}\nand substituting the value of $\\Delta t$ here we get\n\\begin{\\cbox}\n\\begin{equation}\n\\nu_c=\\frac{3}{4 \\pi}\\cdot \\frac{e B_{\\perp}}{m_0c}\\cdot \\gamma^2\n\\end{equation}\nHere, $B_{\\perp}=B \\cdot \\sin \\chi$. is the component of the magnetic field perpendicular to the line-of-sight.\n\\end{\\cbox}\n\\textbf{So far so good, we have considered the synchrotron emission from particles composed of only electrons. What about protons? Evidently, The cosmic-ray (CR) energy spectrum observed near earth exhibits $\\sim 100$ times more protons than electrons (at the same energy).}\\\\\nHere, we now check for the contribution of protons:\\\\\nSo, we know,\n\\begin{equation}\n\\nu_c=\\frac{3}{4 \\pi}\\cdot \\frac{e B_{\\perp}}{m_0c}\\cdot \\gamma^2\n\\end{equation}\nWe substitute $\\gamma= \\frac{E}{m_0c^2}$. \n\\textbf{This tells us a crucial fact, $\\nu_c$ depends on the mass of the radiating particle like $m^{-3}$}. And, we can find that\n\\begin{equation}\n\\cc{\\frac{m_p}{m_e}}^{-3}=1.6 \\cdot 10^{-10}\n\\end{equation}\nand hence the frequency for proton relative to electron would be around\n\\begin{equation}\n\\cc{\\frac{\\nu_{c,p}}{\\nu_{c,e^{-1}}}}=1.6 \\cdot 10^{-10}\n\\end{equation}\n\\textbf{Put differently, we can calculate how much more kinetic energy a proton must have in order to radiate at the same frequency as the electron.}\n\\begin{equation}\nE_p=\\cc{\\frac{m_p}{m_e}}^{3/2}\\cdot E_e =8\\cdot 10^4 E_e\n\\end{equation}\n\\textbf{Hence, even the ratio of number densities measured in the CR energy spectrum of $np/ne \\approx 100$ does not help. In fact, as we shall see later, \\tit{relativistic protons are much more long-lived, owing to their very low radiation losses. They may remain relativistic for more than a Hubble time, while electrons become non-relativistic within less than 100 Myr}}\\\\\nRemember the power of the time dependent radiated power into a unit solid angle per unit frequency and per unit time is\n\\begin{align}\n\\frac{dP(t)}{d\\Omega}&=&\\frac{e^2}{4 \\pi c}\\cdot \\frac{|\\vec{n}\\times\\rr{\\vec{n}-\\vec{\\beta}}\\times\\vd{\\beta}|^2}{(1-\\beta \\cdot \\cos \\theta)^5}\n\\end{align}\nFor, small angle $\\theta$ and large Lorentz factors $\\gamma$\\textbf{Note: I have not done this calculation yet.}\n\\begin{equation}\nfrac{dP(t)}{d\\Omega}=\\frac{2}{\\pi}\\;\\frac{e^2 \\dot{v}^2}{c^3} \\gamma^6\\cdot \\frac{1}{(1+\\gamma^2 \\theta^2)^3}\\cdot \\rr{1-\\frac{4 \\gamma^2 \\theta^2 \\cos^2 \\phi}{(1+\\gamma^2\\theta^2)^2}}\n\\end{equation}\nand, upon integration over solid angle it becomes\n\\begin{equation}\\label{eq:timeP}\nP(t)=\\int^{2 \\pi}_0 \\int^{\\pi}_0 \\de{P}{\\Omega}d\\Omega=\\frac{2}{3}\\frac{e^2\\dot{v}^2}{c^3}\\cdot\\gamma^4\n\\end{equation}\nNow, what we do is the \\tbf{Fourier analysis of time-dependent radiated power} for the small angle approximation [\\textbf{Done by schwinger}]:\n\\begin{equation}\nP(\\nu)=\\frac{\\sqrt{3}e^3}{m_0 c^2} \\cdot B_{\\perp} \\cdot F\\cc{\\frac{\\nu}{\\nu_c}}\n\\end{equation}\nwhere\n\\begin{equation}\\label{eq:freqP}\nF\\cc{\\frac{\\nu}{\\nu_c}}=\\frac{\\nu}{\\nu_c}\\cdot \\int^\\infty_{\\nu/\\nu_c} K_{5/3}(x)dx\n\\end{equation}\n\\textbf{The function $F\\cc{\\frac{\\nu}{\\nu_c}}$ is the Airy integral of the modified Bessel Function $K_{5/3}(x)$}. Th Wallis approximation renders us the following important result\n\\begin{\\cbox}\n\n\\begin{equation}\nF\\cc{\\frac{\\nu}{\\nu_c}}=1.78 \\cc{\\frac{\\nu}{\\nu_c}}^{0.3} \\cdot e^{-\\frac{\\nu}{\\nu_c}} \n\\end{equation}\n\\end{\\cbox}\nUsing \\eqref{eq:timeP} and \\eqref{eq:freqP} we can plot for various values of $\\gamma$ as given in Figure \\ref{figfour}\n\n\\begin{figure}\\label{figfour}\n\\includegraphics[scale=1]{figfour.png}\n\\caption{Sketch of the time dependence of the synchrotron pulses and their radiation spectra}\n\\end{figure}\n\n\\subsection{Synchrotron Radiation from Relativistic Electrons with an Energy Spectrum}\nNow, if we need to measure the radiation coming in from a bunch of particles we would need to know the energy spectrum of the bunch of charges. The CR shower on the atmosphere has been observed and identified to follow as power lay given as given as\n\\begin{equation}\nN(E)dE=A\\cdot E^{-g}dE\n\\end{equation}\nand plotted in Figure \\ref{figepower} which shows the measured energy spectrum near earth.\n\\begin{figure}\\label{figepower}\n\\includegraphics[scale=1]{figepower.png}\n\\end{figure}\n\\begin{itemize}\n\\item A is a constant. Representing the local number density of relativistic particles per energy interval.\n\\item g is the power law index , \\textbf{generally g=2.4}\n\\end{itemize}\nComing back to Figure \\ref{figepower}:\n\\begin{itemize}\n\\item ($\\leq 1GeV - 10's\\;\\;GeV$): Represents energies of particles emitting synchrotron\n\\item  measured spectrum is strongly modulated by the solar wind below a few GeV, which explains the deviation from the power-law there. Hence, nothing is known about the shape of the spectrum at the lowest CR energies. \n\\item  At the highest energies, there are changes in the spectrum called 'knee' (at $\\geq 10^{15}$ eV) and 'ankle' (at $\\geq 10^{18}$ eV).\n\\item  The particles with the highest recorded energies($\\geq 10^{20}$ eV, so-called ultra-high energy cosmic rays, or UHECR) are a real enigma, their origin being totally unknown.\n\n\\end{itemize}\nNow, the intensity of emission is given through the emissivity equation:\n\\begin{equation}\n4 \\pi \\epsilon_\\nu=\\int^{E_2}_{E_1}P(\\nu)\\cdot N(E)dE\n\\end{equation}\n\\textbf{Assuming that there is no background radiation, the radiation transport equation yields the intensity from the brightness and the source function}\n\\begin{equation}\nI_\\nu=S_\\nu(T)\\cdot (1-\\exp^{-\\tau_\\nu}) \\approx S_\\nu(T)\\cdot \\tau_\\nu\n\\end{equation}\nfor small values of $\\tau_\\nu$. we expect the medium to more or less transparent to the observed frequency but \\textbf{should the $\\tau_\\nu$ not be tending more toward infinity. then why do we assume that the $\\tau_\\nu$ is small?}.\\\\\nFrom Kirchoff's law we have \\textbf{Look into this too}\n\\begin{equation}\nS_\\nu(T)=\\frac{\\epsilon_\\nu}{\\chi_\\nu}\n\\end{equation}\nresult in\n\\begin{equation}\nI_\\nu=\\int^{s_0}_0\\epsilon_\\nu ds\n\\end{equation}\nand hence\n\\begin{equation}\nI_\\nu=\\frac{1}{4\\pi}\\int^{s_0}_0 \\int^{\\infty}_0 P(\\nu) N(E)dEds\n\\end{equation}\n\\textbf{check about above definition I am not so sure!!!!}\\\\\nThe units of brightness or intensity is given as $\\rr{erg\\;\\;s^{-1}\\;\\;cm^{-2}\\;\\;Hz^{-1}\\;\\;sr^{-1}}$.\\\\\n\\tbf{\\tit{ Let us assume for simplicity that neither the power $P(\\nu)$ nor does the energy spectrum depends on the location.}}\\\\\ni.e. $dP/ds=0$ and $dN/ds=0$.\\\\\nUsing the equations of Power in frequency domain and energy spectrum we have\n\\begin{equation}\nI_\\nu=\\frac{s_0}{4\\pi}\\cdot \\frac{\\sqrt{3}e^3}{m_0c^2}\\cdot B_{\\perp} A \\cdot \\int^{\\infty}_0 F\\cc{\\frac{\\nu}{\\nu_c}}E^{-g}dE\n\\end{equation}\n\\textbf{$s_0$ being the total path length}.\\\\\nWhen push in Waalis approximation\n\\begin{equation}\nI_\\nu=\\frac{s_0}{4\\pi}\\cdot \\frac{\\sqrt{3}e^3}{m_0c^2}\\cdot B_{\\perp} A \\cdot 1.78 \\cdot \\int^{\\infty}_0 \\cc{\\frac{\\nu}{\\nu_c}}^{0.3} \\dot e^{-\\nu/\\nu_c}E^{-g}dE\n\\end{equation}\nLet's do some assignments for abstraction:\n\\begin{eqnarray*}\nC\\equiv 1.78  \\frac{\\sqrt{3}e^3}{4 \\pi m_0c^2}=3.32 \\times 10^{-23}esu^3 erg^{-1}\\\\\n\\nu_c=\\frac{3}{4\\pi}\\cdot\\frac{eB_{\\perp}}{m_0^3c^5}\\cdot E^2\\equiv \\eta B_{\\perp} E^2\\\\\n\\eta=6.26 \\times 10^{18}s^4g^{-5/2}cm^{-7/2}\n\\end{eqnarray*}\nWe also make use of substitution\n\\begin{equation}\n\\sqrt{\\frac{\\nu_c}{\\nu}}\\equiv x =\\cc{\\frac{\\eta \\cdot \\beta}{\\nu}}^{1/2}\\cdot E\n\\end{equation}\ni.e.\n\\begin{equation}\ndE=\\cc{\\frac{\\nu}{\\eta B}}^{1/2}dx\n\\end{equation}\nTo be derived:\\\\\nThe expression for intensity is given as\n\\begin{equation}\nI_\\nu=s_0 C A \\eta^{\\frac{g-1}{2}}B_{\\perp}^{\\frac{g+1}{2}}\\nu^{\\frac{-g+1}{2}}\\int^\\infty_0 x^{-(g+0.6)}e^{-\\frac{1}{^2}}dx\n\\end{equation}\n\\begin{\\cbox}\nNot only for Milky way but even for external galaxies h=2.4\n\\end{\\cbox}\nTherefore with\n\\begin{equation}\n\\frac{1}{x^2}=u \\implies \\frac{-2}{x^3}dx=du\n\\end{equation}\nwe have\n\\begin{equation}\n\\int^\\infty_0x^{-3}\\cdot e^{-\\frac{1}{x^2}}dx=\\frac{1}{2}\\int^\\infty_0 e^{-u}du=\\frac{1}{2}\n\\end{equation}\nand using $g=2.4$ we finally have\n\\begin{\\cbox}\n\\begin{equation}\nI_\\nu=2.4 \\cdot 10^{-10}\\cc{\\frac{s_0}{cm}}\\cc{\\frac{A}{erg^{1.4}cm^{-3}}}\\cc{\\frac{B_\\perp}{G}}^{1.7}\\cc{\\frac{\\nu}{Hz}}^{-0.7}\n\\end{equation}\n\\end{\\cbox}\nwhich has the dimensions of $\\rr{erg\\;\\;s^{-1}\\;\\;cm^{-2}\\;\\;Hz^{-1}\\;\\;sr^{-1}}$.\\\\\nlet us look into some numbers first some number crunching, \\\\\nThe value of A $=8.2 \\times 10^{-17}erf^{1.4}cm^{-3}$ close to earth, this is true. But we take it constant over a line of sight of 10Kpc, then the magnetic field would expect synchrotron intensity as\n\\begin{equation}\nI_\\nu \\approx 10^{18} erg s^{-1} cm^{-2} Hx^{-1} sr^{-1}\n\\end{equation} \nat an observing frequency of $\\nu =1GHz$.\\\\\nIn general if\n\\begin{\\cbox}\nThe energy spectrum is given by:\n\\begin{equation}\nN(E)dE\\sim E^{-g}dE\n\\end{equation}\nthen we have\n\\begin{equation}\nI_\\nu \\sim B_{\\perp}^{1+\\alpha}\\cdot \\nu^{-\\alpha}\n\\end{equation}\nwhere $\\alpha$ is the spectral index . The spectral index related to the power law index  $g$ as \n\\begin{equation}\n\\alpha=\\frac{g-1}{2}\n\\end{equation}\nFor ISM, g=2.4 and $\\alpha=0.7$.\n\\end{\\cbox}\n\\textbf{ The synchrotron spectrum steepens in regions of lacking energy supply , while in the vicinity of star-forming regions in which stellar winds and supernovae cause turbulence and (re-)accelerate the particles. What is happening in computing I\nis that for each electron the radiation spectrum P($\\nu$) of the single particle is successively multiplied by the 'particles' number density for each energy. The integration over the whole energy range then yields the frequency spectrum. In the log-log plot this means that we have to add (logarithmically) the 'weighting functions', given by N(E). \\tit{If the energy spectrum has a cut-off at some energy $E_{max}$, the spectrum will fall off exponentially beyond the corresponding critical frequency}}.\n\\begin{equation}\n\\nu_c=\\frac{3}{4 \\pi}\\cdot \\frac{e. B_{\\perp}}{m_0c}\\cdot \\gamma^2_{max}\n\\end{equation}\nNow, we show an illustration for the cut off frequency and single electron spectrum plot in Figure. \\ref{figsyn}\n\\begin{figure}\\label{figsyn}\n\\includegraphics[scale=1]{figsyn.png}\n\\end{figure}\n\\chapter{Diffuse Radio Emission from Galaxy Clusters}\n\\textbf{This work is largely based on R.J.  Van Weeren's review paper with the same title}\n\\section{Abstract}\nWith increased detection of galaxy clusters there has been increased identification of the diffuse extended radio sources. \\textbf{Note point: These sources may not be individually linked to host cluster galaxies.}And the radio emission from these sources reveal the presence of \\textbf{cosmic rays and magnetic fields in the intra-cluster medium (ICM)}\\\\\n\\textbf{What comprises of this intra-cluster medium?}\\\\\n\\textbf{What are cosmic rays and why are they important at all?}\nThe diffuse cluster radio sources can be classified as:\n\\begin{itemize}\n\\item Radio Halos: They can be further classified as:\n\\begin{itemize}\n\\item Giant halos\n\\item Mini halosa\n\\item Ans possible intermediate sources\n\\end{itemize}\n\\textbf{Where do you find these halos and how does their brightness vary?}\\\\\n Halos are generally positioned at cluster center and their brightness approximately follows the distribution of the thermal ICM.\\\\\n \\textbf{How are halos formed at cluster center and why is the brightness following the distribution of the thermal ICM?}\\\\\n\\item Cluster Radio Shocks(Relics): These are generally found in Cluster's periphery.\\\\\n\\textbf{Again, here it becomes important to know how are the relics formed? what do we know about them?}\\\\\n\\textbf{\\textit{One very crucial property here is they are tracer for merger induced shock waves!!}}\n\\item Revived AGN fossil plasma sources:\\\\\n\\textbf{Among other sources, how do you identify Revived fossil plasma sources?}\\\\\nAns. \\begin{itemize}\n\\item They have steep radio spectra. I guess in the intensity vs frequency graph, it rises very fast.\n\\item They have irregular morphologies\n\\end{itemize}\n\\end{itemize}\n\\textbf{What will you study here?}\\\\\n\\begin{itemize}\n\\item We will have an overview of recent results regarding properties of this diffused sources.\n\\item We will discuss, the resulting implications for the underlying physical acceleration processes that operate in the ICM.\n\\item we will discuss, the role of relativistic fossil plasma and the properties of ICM shocks and magnetic fields.\n\\end{itemize}\n\\newpage\n\\section{Introduction}\nWhen we talk about scales in universe, galaxy clusters are \\textbf{largest virialized objects} objects in the universe. $M_{cluster}=\\sim 10^{15} M_\\odot$. They grow through the accumulation of smaller groups of galaxies and through major mergers with other massive clusters. Located between clusters, elongated filaments of galaxies, form even larger unbound structures, making up the cosmic web. These filaments span the regions between clusters. \n\n\n\\textbf{Galaxy clusters are located at the nodes of filaments, like spiders in the cosmic web.}\\\\\n\\textbf{What is ICM? What is its emission form like?}\\\\\nAns. Clusters may contain up to several thousands of galaxies. However, the galaxies comprise \\textbf{of only $1\\%$ of cluster's total mass}.\\\\\nMost of the baryonic mass is contained in \\textbf{hot $(10^7-10^8 \\;\\; K)$, ionized cluster medium(ICM)} held together by cluster's gravitational pull.\\\\\n\\begin{itemize}\n\\item \\textbf{The main emission mechanism is:} Thermal Bremstrahlung at X-ray wavelengths. \n\\item \\textbf{ The ICM makes up $\\sim 15\\%$ of a cluster’s mass budget. Most of the mass, $\\sim 80\\%$, is in the form of dark matter }.\n\\end{itemize}\nEarlier, remember we were talking about the filaments. Now these filaments are surrounded by \\textbf{Warm Hot Intergalatic Medium}. Let us compare the properties of ICM and WHIM\n\\begin{itemize}\n\\item Particle density: \n\\begin{itemize}\n\\item ICM: $\\sim 10^{-3} \\text{particle per } cm^{-3}$\n\\item WHIM: $\\sim 10^{-4} \\text{particle per } cm^{-3}$\n\\end{itemize} \nTherefore , WHIM is less dense than ICM.\n\\item Medium Temperature:\n\\begin{itemize}\n\\item ICM: $(10^7 -10^8 \\;\\ ; K)$\n\\item WHIM: $(10^5 -10^7 \\;\\ ; K)$\n\\end{itemize}\nWHIM is hence cooler then ICM.\n\\end{itemize}\n\\begin{\\cbox}\n\\textbf{So, fun fact: Half of Universe's baryons reside in WHIM}\n\\end{\\cbox}\n\\begin{\\cbox}\n\\textbf{Galaxy filaments are expected to be surrounded by accretion shocks, where the plasma is first shock heated!.}\\\\\n\\textbf{Why are the filaments expected to be surrounded by shocks?}\n\\textbf{Q. so if it is said plasma is shock heated, is accretion shock the reason, why ICM has hence higher temperature?}\n\\end{\\cbox}\n\\textit{studying the WHIM and associated shocks is difficult due to a lack of sensitive observational tools.}\\\\\n\\textbf{How are galaxy clusters formed and what are the consequences?}\\\\\nAns. They are formed by accretion from the WHIM and through a sequence of mergers of clusters and groups. These mergers are highly energetic events, releasing upto $\\sim 10^{64} \\; ergs\\; \\text{On a few giga year time scale}$. This energy is dissipated through low Mach number shocks and turbulence,  This strongly affects the physical properties of the different properties of clusters, for example the density distribution and velocity dispersion of galaxies, and the temperature, metallicity, and density distribution of \\\\\n The shocks and turbulence that are generated in the ICM might also amplify magnetic fields ($\\sim \\mu G$) and accelerate relativistic particles (Lorentz factor $\\gamma >>$  1000), resulting in megaparsec-scale synchrotron emission regions\\\\\n  The spectral index $\\alpha$ of the synchrotron emission is generally steep: $\\alpha \\leq 1$ with $S \\propto \\nu^\\alpha$, where $\\nu$ is the observed frequency and S is the measured flux density. The steep spectral index suggests that the synchrotron emission is relatively bright at low radio frequencies. \\\\\n \n\\textbf{Q. Is the above mentioned mechanism the only one to heat the ISM, is heating due accretion shock another reason to heat up ICM?}\\\\\nClusters can thus be divided into(in accordance with their dynamical state):\n\\begin{itemize}\n\\item Relaxed or undisturbed cluster\n\\item Merging or Dynamic cluster\n\\end{itemize}\nGalaxy clusters also host a number of AGN's that emit radio synchrotron emission also called radio galaxies. An important difference to note between radio galaxies that are located away from galaxy clusters or groups, is that \\textbf{ the jets of cluster radio galaxies often show signs of interaction with the ICM}.\\\\\n\\textbf{Q. Why is the above interaction of concern?}\\\\\nThese interactions of cluster radio galaxies result in morphologies that range from \\textit{wide-angle-tail(WAT), narrow-angle-tail(NAT)} and \\textit{head to tail} radio sources.\n\\section{Synchrotron Radiation}\n A standard assumption is that the ICM CR population can be described by a power law energy (E) distribution \n \\begin{equation}\n n(E)dE\\propto E^{-p}dE\n \\end{equation}\n \\textbf{Note:we had earlier introduced the quantity 'p' as 'g'.}\\\\\n \\textbf{The index of energy or momentum distribution is also related to the \\tit{radio spectral index as}}\n \\begin{equation}\n p=1-2\\alpha\n \\end{equation}\n where spectral index relates flux and frequency relationship\n \\begin{equation}\n F_\\nu \\propto \\nu^\\alpha\n \\end{equation}\n \\tbf{Let us now try to build a case why in situ production of CRe's or reacceleration of CRe's are a better bet , than a single point electron acceleration for explaining Mpc scale radio relics.}\\\\\n \\begin{itemize}\n \\item Diffuse cluster radio emission typically has \\tbf{a steep spectral index}, i.e., $\\alpha \\leq -1$. \n \\item The spectral shape is related to \\tbf{the physics of the acceleration mechanism} and \\tbf{the electron synchrotron and IC energy loss}.The more the losses , steeper the spectra as  for the same frequency  we observe a lower energy! hence as electron ages, the spectra becomes steeper.\n \\item  The characteristic lifetime ($t_{age}$) of the synchrotron emitting electrons ($\\gamma \\sim 10^4$; GeV energy) due to these energy losses is\n \\begin{equation}\n t_{age}[yr]\\approx 3.2 \\times 10^{10} \\frac{B^{1/2}}{B^2+B^2_{CMB}}\\rr{(1+z)\\nu}^{-1/2}\n \\end{equation}\n \\tit{1. Higher the magnetic field, higher the synchrotron losses and hence characteristic life time decreases, also photons originating from farther redshifts must have lower characteristic age, as it suffers decrease in observed frequency of photon.}\\\\\nHere $B$ is  the magnetic field strength, $z$ the source redshift,\\tbf{ $B_{CMB}$ is the equivalent magnetic field strength of the CMB ($B_{CMB} [\\mu Gauss] \\approx 3.25(1+z)^2)$}, and $\\nu$ is the observing frequency in MHz.\n\\item In clusters, we have $t_{age} \\approx10^8$ yrs. The typical diffusion length-scale in the ICM of a GeV electron, using the Bohm approximation, is of the order of 10 pc (e.g., Bagchi et al. 2002). \n\n\\item Plasma motions\\fn{What is plasma motions here?} can increase the distance over which GeV electrons travel, but this distance is still expected to remain well below a Mpc. \\textbf{This means that Mpc-scale diffuse radio sources cannot trace CR electrons that are accelerated at a single location in the ICM.}\n\n\\item  Therefore, for Mpc scale diffusion, \\textbf{particles need to be (re-)accelerated or produced in-situ (Jaffe 1977), this will help us provide important constraints on the possible acceleration/production mechanisms.}\n\\item  Due to the energy losses, the initial power-law spectrum steepens beyond a \\textbf{break frequency, whose position is related to the time since acceleration\\tit{ or energy of electrons}}.\n\\item The power-law spectrum is commonly refereed to \\tit{\\tbf{as the injection spectrum}},characterized by an \\tbf{\\tit{injection spectral index ($\\alpha_{inj}$)}}.\n \\end{itemize}\n \\textbf{Q. How would you describe energy losses of the electron ensemble?}\\\\\nAns. Various models that could describe energy losses are:\n \\begin{itemize}\n \\item For the \\tbf{JP (Jaffe-Perola) synchrotron spectrum} (Jaffe and Perola 1973), one assumes that there is a \\tbf{continuous isotropization} of the electron pitch angles (i.e., angle between the magnetic field and the electron velocity) on a timescale that is shorter than $t_{age}$. A JP spectrum describes a synchrotron spectrum from a \\tbf{single burst of acceleration} and then ageing.\n \n \\item  The \\tbf{KP (Kardashev Pacholczyk) model(Kardashev 1962;Pacholczyk 1970)} also represents such a spectrum, but \\tbf{without the isotropization} of the pitches angles. \n \\item  Since it is usually difficult to spatially isolate electrons that all have the same spectral age, there are also composite models. These models sum JP (or KP) spectra with different amounts of spectral ageing.\n \n \\item The \\tbf{CI (continuous injection)} composite model (Pacholczyk 1970) describes the integrated spectrum of a source with \\tbf{continuous particle injection}.\n \\item  For the \\tbf{KGJP/KGKP (Komissarov-Gubanov) model (Komissarov and Gubanov 1994)}, the particles are only injected for a \\tbf{finite amount of time} before the injection in the source stops\n \\end{itemize}\n \\section{Particle Acceleration Mechanism}\n Here we give a brief overview of physical mechanisms that accelerate particles in the ICM and produce Synchrotron emitting CR electrons:\n \\begin{itemize}\n \n \\item \\tbf{\\tit{First order Fermi acceleration(Fermi-I)}:}\n \\begin{enumerate}\n \\item This process of acceleration is called  diffusive shock acceleration (DSA)\\\\\n \\item  For DSA, particles are \\tbf{accelerated at a shock} with the acceleration taking place \\tbf{diffusively}. In this process, particles cross back and forward across the shock front as they \\tbf{scatter from magnetic inhomogeneities} in the shock down and upstream region. \n \\item At each crossing, particles gain additional energy, forming a \\tbf{power-law energy distribution} of CR.\n \\end{enumerate}\n \\item \\tbf{\\tit{Second order Fermi acceleration(Fermi-I)}:}\n \\begin{enumerate}\n \\item It is a stochastic process. \\tit{It means that the process has some random variable at play!}\n \\item In this process, particles scatter from magnetic inhomogeneities; for example from MHD turbulence.\n \\item  \\textbf{Particles can either gain or loose energy} when scattering. When the motions are random, the probability for a head-on collision, where energy is gained, is slightly larger.\\tit{I don't understand this point! Why should the probability for head on collision larger for random motions?} Because of its random nature, second order Fermi acceleration is an \\tbf{inefficient process}.\\tit{The take away point being, energy can either be gained or lost by Fermi II but is always gained by Fermi I }\n \\end{enumerate}\n \\item \\tit{\\tbf{Adiabatic Compression:}}\n \\begin{enumerate}\n \\item A shock wave can \\tbf{adiabatically compress} a bubble/lobe/cocoon of (old) relativistic radio plasma from an AGN.\n \n \\item Due to the compression, the \\tit{CR electrons in the cocoon} regain energy boosting the radio synchrotron emission (Ensslin and GopalKrishna 2001; Ensslin and Bruggen 2002).\\tit{It is important to note, that CR electrons are already present in such cases and shock compresses and the elctrons regain energy to emit synchrotron in this process}\n \\end{enumerate}\n\\item \\tit{\\tbf{Secondary Models:}}\n\\begin{enumerate}\n\\item This model proposes that that the CR electrons are produced as secondary particles(\\tbf{decay products}). In the hadronic model, collisions between relativistic protons and the thermal ions produce secondary CR electrons\n\\item  CR protons have a \\tbf{very long lifetime} compared to CR electrons, they will accumulate over the lifetime of a cluster once they are accelerated\n\\item Possible mechanisms to produce CR protons are first order Fermi acceleration at shocks, AGN activity, and galactic outflows (supernovae, winds).\n\\item \\tbf{Although alternative models have been proposed, i.e. secondary models, in which the synchrotron emitting electrons are continuously injected by inelastic collisions between cosmic ray protons and thermal protons (e.g. Dennison 1980; Enslin et al. 2011). The process of generation of secondary particles via proton-proton collisions is thought to play a minor role due to current upper limits in gamma ray observations (Ackermann et al. 2014. Ackermann et al. 2016, Brunetti et al. 2012, Brunetti et al. 2017, Zandanel $\\&$ Ando 2014) unless this mechanism is combined with turbulent re-acceleration.}\n\\end{enumerate}\n\n \\end{itemize}\n \\section{Classifying Diffuse Cluster Radio Sources}\nAccording VanWeeren's Classification of Diffuse cluster sources:\n\\begin{itemize}\n\\item Radio Halos\n\\item Radio Relics(Cluster Radio Shocks)\n\\item AGN fossil plasma sources, phoenices and GReET\n\\end{itemize}\n \\subsection{Radio Relics and fossil plasma sources}\n \\begin{itemize}\n \\item \\tbf{\\tit{Revived AGN fossil plasma sources, phoenices}}\n \\begin{itemize}\n \n\\item These are the sources which have been re-energized by the processes in the ICM unrelated to radio galaxy itself\n\\item Their precise origin and connection to cluster radio shocks and possibly also halos is still uncertain. \n\\item The main observational property that the sources have in common is the AGN origin of the plasma and their ultra-steep radio spectra due to their losses.\n\\item Fossil Radio plasma plays an important role in origin of both halos and cluster radio shocks.\n\\item It is predicted that fossil plasma is re-accelerated via first and second fermi processes\n\\item The phoenices have \\tbf{irregular filamentary morphologies}\n \\end{itemize}\n \\item  \\tbf{\\tit{GReET:}}Gently re-energized tails (GReET)are tails of radio galaxies that are somehow revived, showing unexpected spectral flattening, opposite from the general steepening trend caused by electron energy losses.\n \\item \\tbf{\\tit{Cluster Radio Shocks(Radio Relics):}}\n \\begin{itemize}\n \\item They are also called Radio Relics\n \\item These are  extended diffuse sources tracing particles that are (re-)accelerated at ICM shock waves\n \\item This shock classification is similar to that of large Radio Gischt (which  are large Mpc size sources that trace particles accelerated at shocks via Fermi I) but does not require DSA or Fermi I type acceleration. \\tit{However, based on our current understanding of these sources, we do anticipate that in most cases cluster radio shocks are associated with Fermi-I acceleration processes.}\n \\item It is \\tbf{not required} that cluster radio shocks are located in the cluster periphery, although for large cluster radio shocks that will typically be the case. \n \\item A large majority of these sources are expected to show a \\tbf{high degree of polarization}. \n \n \\item  Unlike radio halos, cluster radio shocks \\tbf{can be associated} to a specific cluster region where a shock wave is present, or where a shock wave recently passed.\n \\item for a number of sources the \\tbf{presence of a shock at their location has been confirmed by X-ray observations}.\n \\item  A drawback of the radio shock classification is that the detection of shocks in the ICM is observationally challenging\n \\end{itemize}\n \n \\end{itemize}\n \\section{Cluster Magnetic Field}\n \\section{Cluster Radio Shocks and Revived Fossil Plasma Sources}\n \\textbf{The distinction between radio shocks and fossil plasma sources is not always straightforward, since it requires the detection of shocks via SZ or Xray measurements and the availability of radio spectra.. Phoenices and other revived AGN fossil sources  }\n\n\\chapter{Radio Ghosts}\nThis is based on the paper titled \\tbf{Radio Ghosts} by T.A. Enslin.\\\\\n\n\\tbf{What is the role of Radio Ghosts?}\\\\\n\nWe investigate the possibility that patches of old radio plasma or radio ghosts of former radio galaxies to form a second distinct phase of intergalactic medium. \\\\\n\n\n Since patches of this plasma are largely invisible in the radio we use the term 'radio ghost' to characterize their nature.\\\\\n \n \\begin{\\cbox}\n  We discuss the role radio ghosts can have: They are able to store relativistic particles for cosmological times, but are also able to release them under the influence of very strong turbulence. \n  \\end{\\cbox}\n  \n  The role of adiabatic compression in radio ghosts is discussed in next chapter, here we discuss the role of release of relativistic proton population and how it can produce radio halos of some cluster of galaxies via hadronic reactions with the background gas leading to the production of secondary electrons and positrons.\\\\\n  \n  \\section{Introduction}\n  The active radio galaxies becomes rapidly invisible to radio telescope due to inverse compton and synchrotron energy  losses of the relativistic electrons. Afterwards it becomes an invisible but an important phase of the IGM. The amount of energy stored should be the same, as it is assumed that the power of active galactic nuclei is deposited into the radio plasma and into X-ray light output is comparable.\\\\\n  \n  \\section{Fate of Radio Ghosts and Consequence of different astrophysical phenomenas}\n  \n  The radio plasma and later radio ghosts will expand or contract until they reach pressure equilibrium with the surrounding medium.\\\\\n  \n  \\tbf{How is the internal pressure inside the ghosts is determined?}\\\\\n  \n   The pressure of the ghost is given by that of the confined relativistic particles and the magnetic fields, assumed to be in rough energy equipartition. Therefore magnetic fields should be typically of the strength of the thermal energy density of the environment.\\\\\n   \n\\tbf{Fate of ghosts due to astrophysical phenomena}\\\\\n\n\\tit{Effect of Subsonic Turbulence}\\\\\n   \n    Subsonic turbulence in this environment, which has an energy density below the thermal energy density, is therefore not strong enough to overcome the magnetic elastic forces of the radio ghost. \\\\\n    \n\\tit{Effect of Supersonic Turbulence}\\\\\n    \n    Sonic or super-sonic turbulence, which is e.g. expected in giant merger events of cluster of galaxies, can 'shred' the ghost into smaller pieces. The size of such pieces will be comparable to the \\tbf{eddy size of the turbulence}\\fn{What is Eddy size of a turbulence?}.\n    \n Q. What is eddy size of turbulence and why is it relevant?\\\\\n \n This means, since a typical turbulent spectrum has less energy density on smaller scales, that there is a length scale(eddy size) below which the turbulence is not able to overcome magnetic forces.\\\\\n \nQ. What happens when eddy size of turbulence is reached by the pieces of ghosts?\\\\\n \n  Turbulent erosion of radio ghosts should stop at this length-scale, leaving small-scale patches of still unmixed old radio plasma.\n\n\n\\section{Detection of Radio Ghosts}\n\nEven though poorly constrained the knowledge of  number density, sizes, and filling-factor of our hypothesized radio ghosts  would be required in order to estimate their influence on the properties of the IGM. \n\n\\subsection{Synchrotron Emission and Radio Ghosts detection}\nThe old population of relativistic electrons within the ghost is emitting low frequency radio emission. \n\n\\tbf{Finding the lorentz factor of electrons}\n\nAt a given frequency $\\nu$ synchrotron emission reveals mostly electrons with a Lorentz-factor of \n\\begin{equation}\n\\gamma(\\nu,B,z)=\\sqrt{2 \\pi m_e c \\nu (1+z)/3eB}\n\\end{equation}\nwhere,\n\\begin{itemize}\n\\item B is magnetic field\n\\item z being the redshift of emission region\n\\end{itemize}\n\n\\tbf{Q. What is the cooling time for electron with synchrotron and emission regions?}\\\\\n\n\\begin{equation}\nt_{cool}(\\gamma,B,z)=\\cc{\\frac{4 \\sigma_T}{3 m_ec}(e_B+e_{CMB})}^{-1}\n\\end{equation}\n\nwhere $e_B=\\frac{B^2}{8 \\pi}$ and $e_{CMB}=e_{CMB,0}(1+z)^4$ are the magnetic field and CMB energy density and $e_{CMB,0}$ depends on the present value. \\\\\n\nNow the max cooling time is obtained for $e_B=e_{CMB}/3$ for fixed $\\nu$ and z. So if any electron is visible at a frequency $\\nu$, it had to be accelerated before \n\\begin{equation}\nt_{cool,max}=0.7Gyr\\;\\;\\cc{\\nu/100\\;\\;MHz}^{-1/2}(1+z)^{-7/2}\n\\end{equation} \notherwise it cannot be seen.\\\\\n\n\\tbf{Thus, the low frequency radio observation cannot reveal ghosts which are older than about a Gyr, unless the electron population has been recently re-accelerated.}\n\n\\subsection{CMB Comptonization and detection}\n\\tbf{The relativistic electrons, if still present within ghosts, will scatter the CMB photons to higher energies. Since the infrared and the optical bands are overwhelmed by other sources, the chance of detection only exists above the UV range}.\\\\\n\n\nNow, for detection of electron at $10eV$, we would need a scattered photon with a $\\gamma\\approx 100$ as\n\\begin{equation}\n<e_{IC}>=\\frac{4}{3}\\gamma^2 2.7 kT_{CMB}\n\\end{equation}\nHence, now the idea to detect a 10 eV now requires investigation of the if  energetic electrons can maintain an energy of 50 MeV for cosmological times. \\\\\n\nAgain, we want to examine the most optimistic case in order to demonstrate the difficulties of detect\n\\tbf{Skipping for focus on some other areas}\\\\\n\n\\section{Possible Roles of Radio Ghosts}\n\\subsection{Storage sites of relativistic protons}\n\\tbf{Requirement of relativistic protons to explain gamma emissions from blazars}\\\\\n\nRadio ghosts consist of magnetic fields and low energy relativistic electrons. A long outstanding question is the extent to which radio plasma clouds contain relativistic protons. The detection of TeV $\\gamma$-rays from blazars support the presence of a significant proton component, since this emission is difficult to understand within pure leptonic jet models (Mannheim 1998). \\\\\n\n\\tbf{q. Why relativistic protons are expected in radio ghosts?}\\\\\n\nA relativistic proton population can therefore be expected within ghosts, since the escape of protons is suppressed due to the low cross field diffusion coefficient.\\\\\n\n\\tbf{Let us do a calculation, that gives is an idea whether our expectation that the proton will stay confined in the ghosts.}\\\\\n\nTo begin let us try to estimate  the escape time of a 10 GeV proton in a 10 $\\mu$G field, which could be typical for a ghost in a cluster environment.\n\nNow, The parallel and cross-field diffusion coefficient is given by:\n\\begin{eqnarray}\nk_\\parallel \\approx \\frac{1}{3}cr_g/\\delta_B(r_g)\\\\\nk_\\perp \\approx \\frac{1}{3}cr_g\\delta_B(r_g)\n\\end{eqnarray}\n Now these depend on the (relative) energy density in magnetic fluctuation\n\\begin{equation}\n\\delta_B(r_g)=\\delta B^2(r_g)/B^2\n\\end{equation} \non the scale of gyro radius $r_g=10^{-6}pc$ of the diffusing particle.\\\\\n\n The magnetic fields of the ghost are in rough equipartition with the surrounding thermal medium $e_B\\approx e_{th}$. And, \n The level of turbulence on the turbulence injection scale $l_{inj}$ = 10 kpc is assumed to be a small fraction of the thermal energy density. Upto this scale  the turbulence energy density integrate is \n \\begin{equation}\n e_{turb}(l_{inj})=0.01r_{th}\n \\end{equation}\n  Assuming a Kolmogoroff turbulence spectrum, one gets a turbulent energy density integrated up to the scale $r_g$ , of value\n  \\begin{equation}\n  e_{turb}(r_g)=e_{turb}(l_{inj})\\cc{l_{inj}/r_g}^{-2/3}\\approx 10^{-8.7} e_{th}\n  \\end{equation}\n  \n  Now as a result of the above, The turbulence-induced small-scale magnetic irregularities are therefore  $\\delta_B \\approx 10^{-8.7}$ . Which correspond to a cross field diffusion coefficient of $k_\\perp \\approx 10^{13.8} cm^2s^{-1}$. \\tbf{This is far too small to allow any macroscopic diffusion.}\\\\\n  \n  But this is not the end of the story, the high parallel diffusion coefficient of $k_\\parallel \\approx  10^{31.2} cm^2 s^{-1}$ allows the particle to travel rapidly along the magnetic field lines.  Now, if we allow neighbouring field lines to diverge exponentially, a small diffusive step of the particle perpendicular to the field can be strongly amplified by the rapid movement along the field.  This leads to the compound cross-field diffusion coefficient\n  \\begin{equation}\n  k_{comp}\\approx k_\\perp (1+\\Lambda^2/ln \\Lambda) \\approx 10^{25.6} cm^2 s^{-1}\n  \\end{equation}\n  where the quantity\n  \\begin{equation}\n  \\Lambda=\\frac{\\delta_B(l_B)}{\\sqrt{2}\\delta_B(r_g)}\\approx 10^{6.5}\n  \\end{equation}\n  is simplified here by assuming a single typical field correlation-length parallel and perpendicular to the field direction of $l_B \\approx 10Kpc$ . This is still too small to allow an efficient  escape of protons from the ghost, since a typical diffusion time-scale is \n  \\begin{equation}\n  \\tau_{diff}\\approx (10kpc)^2/(2k_{comp})\\approx 3 \\times 10^{11} yr\n  \\end{equation}\n  On this argument, it seems reasonable that relativistic particles are confined for cosmological times within ghosts\n  \n  \\subsection{Escape of Relativistic Protons}\n  \n\\chapter{Enslin-Gopalkrishna Paper}\n\\section{Abstract}\n\t\\tbf{Q. What are radio ghosts which turn out to be radio phoenices ?}\\\\\nAns.  the radio plasma in the lobes of radio galaxies remains mostly intact after release, forming the proposed radio fossils or ghosts\\\\\n\n \\tbf{Q. What happens when central engine of AGN turns off? The jet stops and the galaxy expands and diffuses?}\\\\\nAns. \\tit{ In such a case, the radio population will expand just like an isolated system of overpressured gas, till pressure equilibrium is maintained}. \\\\\n\n\\tbf{Q. Radio Phoenices a story of shocks and rebirth?}\\\\\nAns. \n\\begin{itemize}\n\\item When there is a nearby cataclysmic activity like \\tbf{cluster mergers or dynamic activity like accretion from cold filaments}, shock is driven into the self-evolving plasma population. \n\\item This  plasma, hence goes through a series of expansion and contraction phase, resulting in synchrotron, inverse compton and adiabatic losses or gains in energy. \n\\item It is speculative that this would explain the origin of cluster radio relics or halos or it may also happen that it turns out to be itself a new class of Ultra Steep Spectrum sources in itself , sometimes not related to any parent galaxy. The relics or halos are regions of diffuse radio emissions in cluster of galaxies. Without any parent galaxy seen nearby.\n\\item \\tbf{To summarize, if true, we have found ourselves tracers of shock waves associated with large scale structure formation.}\\\\\n\\end{itemize}\n\n\\tbf{Q. What do we mean by diffuse emission?}\\\\\nAns. Diffused emission is basically all emission which comes through non-collapsed sources.\n\n\n\\section{Introduction}\n\\begin{\\cbox}\n\\tbf{Check Biman Nath's paper on IGM and Radio Cocoons that gave the theory or detection of shutting down of central engine of galaxy. Check up as to how the matter in the galaxy evolves shortly after the AGN turns off would give us insight of initial conditions that go into evolution of plasma long after the AGN is off}\\\\\n\\end{\\cbox}\n\nRadio Plasma consists of :\n\\begin{itemize}\n\\item Thermal gas component/ \\tit{Gases and Dust?}\n\\item Relativistic electrons\n\\item Magnetic fields\n\\item Possibly relativistic protons(Check the chapter on radio ghosts)\n\\end{itemize}\n\\tit{If I can draw out energy losses vs time, I can predict after how much time components present in general galaxy cease to exist and when and how we zero in just 5 components for AGN off galaxy. \\tbf{May be the plasma is related to the components in the lobe of the galaxy}}.\\\\\n\n\\tbf{Q. What are we trying to do here?}\\\\\nAns. We try to explore the possibility of fossil galaxies as precursor candidate of Steep and Ultra Steep Spectrum Sources(USS)\\fn{Mention the value of $\\alpha$ for both}. We speculate that the radio ghosts  give rise to synchrotron emission when a shock by cosmological large scale structure formation passes through it.\\\\\n\n\\begin{\\cbox}\n\\textbf{ Cluster radio relics can not be simply relic radio galaxies, as their name suggests. The \\tit{spectral ages} of the electron population are usually \\tit{too short} to admit even the nearest galaxy to have been the parent radio galaxy, which has moved to its present location with a velocity typical for cluster galaxies.}\\fn{Find reference}\\\\\nThis means that these sources reactivated recently.\n\\end{\\cbox}\nSo, even though there are propositions that through Fermi I process of particle acceleration one can explain Relics. The arguments that make fossil galaxies to be a possibility for USS's are:\n\\begin{itemize}\n\\item \\textbf{Cluster radio relics are extremely rare, whereas shock waves should be very common within clusters of galaxies. The dual requirement of a shock wave and fossil radio plasma, for producing a cluster radio relic, would be an attractive explanation for the rareness of the relics. }\\\\\n\\tit{\\tbf{NP} :Check the idea as a cause of radio relic\n\\begin{itemize}\n\\item change in fast change in gravitational potential causing the same compression features\n\\item supernova explosion a cause for relics?\n\\item \\tbf{Ans. No, this proposition will lead to relics to be found out more rarer than they are.}\n\\end{itemize}}\n\n\\item \\textbf{ Fossil radio plasma with existing relativistic electron population and fairly strong magnetic field appears to have ideal properties to be brightened up during the shock's passage. }\n\\item  The cluster radio relic 1253+375 near the Coma cluster of galaxies appears to be fed with radio plasma by the nearby galaxy NGC 4789 (see Fig 1 and scenario C in Sec. 6).\n\\end{itemize}\n\\textbf{\\tit{But it is important to note that the particle re-energizing is not a result of shock acceleration of particles but the result of heating of electrons during adiabatic compression induced by the passage of shock in the surrounding medium. Why?}}\\\\\nBecause, if indeed the fossil radio plasma and not the normal IGM were to become radio luminous at a shock wave, the expected very high sound velocity of that relativistic plasma should forbid the shock in the ambient medium to penetrate into the radio plasma. Thus, shock acceleration is not expected to occur there. Instead, the fossil radio plasma would get adiabatically compressed, and the energy gain of the electrons is expected to be mainly due to adiabatic heating. \\tbf{Do the calculation of sound speed for relativistic plasma and compare it with speed of shocks! Give a basis on numbers. }\n\\section{Shock Acceleration of CRs}\nThe acceleration of CRs at shocks is customarily described according to the diffusive shock acceleration (DSA) theory.\\\\\n\n\\tbf{What is the effect of CRs being accelerated by the DSA?}\\\\\nIn effect diffusing particles are temporarily trapped in a converging flow across the shock if their scattering lengths across the shock are finite but much greater than the shock thickness.\\\\\n\nLet us have a volume of gas in which a shock is forming a sheet of motion, it can be at any height from the base of the volume. Now the particles which have higher scattering length than the thickness of the shock are transported upstream and in the process gets accelerated. Now two things can happen\n\\begin{itemize}\n\n\\item If the particle losses energy and cannot experience scattering then it will be pulled convectionally downstream\n\n\\item If the particle still has energy to scatter further with the shock velocity , it again crosses the shock and gets accelerated , this will happen repeatedly until the particle losses the energy and flows downstream\n\\end{itemize}\n\nReiterating the point.Particles escape eventually by convection downstream. Until they do, they gain energy each time they are reflected upstream across the shock, with a rate determined by the velocity change they encounter across the shock discontinuity and a competition between convection and diffusion on both sides of the shock. \\\\\n\n\\tbf{So what does the spectrum of these CRs look like and what can we say about their spectrum?}\\\\\nThe hardness (flatness) of the resulting spectrum reflects the balance between energy gain and escape rates. In other words, it depends on the energy gain in each shock crossing combined with the probability that particles remain trapped long enough to reach high energies.\\\\\n\nMathematically this balance can be conveniently described through the \\tbf{Diffusion Convection Equation}.  Let the average distribution function for CR $f(p,t)$ in a compressible flow for a pitch angle is given as \n\\begin{equation}\\label{diffuseeq}\n\\pe{f}{t}+(\\tbf{V}\\cdot \\nabla)f-\\nabla\\cdot \\rr{\\tbf{n}D(\\tbf{n}\\cdot \\nabla)f}=\\frac{1}{3}\\cc{\\nabla \\cdot \\tbf{V}}p\\pe{f}{p}\n\\end{equation}\nHere p is the modulus of the particle's momentum. \\tbf{f is the number of CRs per unit phase-space volume of $d^3pdV$}. \\tbf{V} is the velocity of the background medium . Here an important assumption to note is \\\\\n\n($c>>V>>V_A$, where $V_A$ is the alfven velocity)\\\\\n\n\\tbf{n} is the unit vector parallel to the local magnetic field and D is the \\tbf{particle spatial diffusion coefficient}\\\\\n\n\\tbf{Q. What are the other terms in \\eqref{diffuseeq}?}\\\\\n The 2nd and 3rd terms account for convection and diffusion, respectively, while the right hand side takes account of the adiabatic energy gains (losses) suffered by particles in a converging (expanding) flow.\n \n \\begin{\\cbox}\n It is important to note that the \\eqref{diffuseeq} ignores \n \\begin{itemize}\n \\item Non adiabatic losses\n \\item Momentum diffusion\n \\item effects such as CR energy transfer to wave amplification/dissipation \n \\end{itemize}\n \n \\end{\\cbox}\nWhen all the above condition to \\eqref{diffuseeq} is satisfied and if\n\\begin{itemize}\n\\item All particles are injected at low energies\n\\item \"see\" the same velocity change across the shock\n\\end{itemize}\nthen the steady state spectrum of test particle CRs at a plane power law in momentum is $f(p)=Kp^{-(\\delta_{inj}+2)}$, where the slope is\n\\begin{equation}\n\\delta_{inj}=2\\frac{M^2+1}{M^2-1}\n\\end{equation}\nwhere M is $V_{sh}/c_s$ is the Mach number of the shock.\\\\\n\n\\tbf{Q. How does Nature of shock influences the distribution function of CRs.}\\\\\n\nFor strong shock, $M\\rightarrow \\infty $ this slope causes $\\delta_{inj} \\rightarrow 2$ .\\\\\n\\tit{Thus, in the strong shock limit, the energy and pressure in the resulting CRs are broadly distributed towards the highest energies that are achieved}.\\\\\n\nOn the other hand, for weak shocks $M^2\\approx 1+\\epsilon$ with $\\epsilon<<1$, this tends to $\\delta_{inj}\\approx 2+4/\\epsilon>>2$. \\\\\n\\tit{In this case the fractional energy jump across the shock is small, so the energy in CRs accelerated from suprathermal values is concentrated in the lowest energy CRs. That is, the CRs gain relatively little energy before they escape downstream}. \\\\\n\n\\tbf{Bottom line is, for the same number of CRs and the same kinetic energy flux through the shock, $\\sim \\rho V^3_{sh}$, the energy input to locally injected CRs through DSA is much greater in strong shocks than in weak shocks}\\\\\n\n\\tbf{Q. How does these shock energetic CRs influence back on shocks?}\\\\\n\nAs a consequence of above theory, it is apparent that even a modest injection of particles at a strong shock can lead to a substantial fraction of the kinetic energy flux into strong, initially purely hydrodynamical shocks going into CRs. Those, in turn backreact on and modify the structure of the shocks themselves.\\\\\n\\tbf{ The main outcome of that development is the formation of a compressive precursor to the shock, leading to an increase in the total shock compression, upstream turbulence and magnetic field amplification, followed by an actual weakening of the fluid shock transition (the so-called 'sub-shock'). }\\\\\n\n\\tbf{Q. What is the implication of a highly CR modified shock}\\\\\nIn a highly CR-modified shock a large part of the DSA process at high CR energies actually takes place in the precursor when the spatial diffusion coefficient, D is an increasing function of particles momentum. Then, the subshock is responsible mostly for the acceleration process at low energies and injection of seed DSA particles. \\fn{What does injection of seed DSA particle mean?}\\\\\n\n\\tbf{What does the detailed outcome of non linear evolution in strong shocks depend on?}\\\\\n\nThe importance and detailed outcomes of nonlinear evolution in strong shocks depend on\n\\begin{itemize}\n\\item size of the CR population at the shock\n\\item hardness of the CR spectrum being accelerated at shocks \n\\item efficiency and the distribution of turbulent magnetic field amplification, upstream of the shock and geometry of the shock.\n\\end{itemize}\nThese physical details are important, since they regulate how much energy is extracted from the flow into the shock and, accordingly how much pressure will develop from these CRs and amplified magnetic field within the shock transition.\\\\\n\n\n\\tbf{Q. If the above happens in strong shocks, what about the weaker ones?}\\\\\n On the other hand, unless they include much larger total CR populations or interact with a pre-existing CR population with a hard spectrum, weak shocks are minimally affected by non linear effects,because of the steeper CR spectra generated in these shocks.\\\\\n \n\\tbf{A comparison of weak and strong shock in terms of evolution in time in \\ref{fig:dsacomparison} shows the time evolution of CRp spectra accelerated at simulated weak and stronger shocks. In the case of weak shocks the spectrum agrees with the prediction of test particle DSA theory, while the spectrum becomes concave and flatter than test particle DSA for stronger shocks,due to the non-linear back-reaction of CRp.}\\\\\n\n\\begin{figure}[h!]\\label{fig:dsacomparison}\n\\includegraphics[scale=1]{DSA.png}\n\\end{figure}\n \n\\section{Structure Formation Shock Waves}\nThe flows of the cosmological large-scale structure formation are predicted to produce frequently \\tbf{shock waves at the boundaries of clusters and filaments} of galaxies and \\tbf{during cluster merger}. \n\\begin{\\cbox}\n A radio polarization of $27\\%$ was detected from the radio relic (Giovannini et al., 1991), but not from the tails of NGC 4789 feeding the relic with radio plasma. This is a clear signature of the \\textbf{alignment of magnetic fields enhanced in the shock compression}. The polarization vectors are consistent with a shock wave oriented parallel to the main axis of the radio relic (Enslin et al., 1998). This helps with our case of shocks re-energising the fossil plasma.\n\\end{\\cbox}\n\\section{Fossil Radio Plasma}\n\\textbf{Section to be read later}\n\\section{The Formalism}\nLet 'p' be the dimensionless momentum of an ultra relativistic electrons defined as $p\\equiv \\frac{P}{m_e c}$. This momentum changes as a result of \n\\begin{itemize}\n\\item \\tbf{synchrotron losses} proportional to the magnetic energy density $u_B$\n\\item \\tbf{inverse Compton (IC)} losses proportional to the CMB field energy density $u_C$\n\\item \\tbf{adiabatic losses or gains} connected to the change of the volume V of the radio plasma\n\\end{itemize}\nThe temporal variation of momentum is  given by the relation\n\\begin{equation}\\label{eqp}\n-\\de{p}{t}=a_0(u_B+u_C)p^2 +\\frac{1}{3}\\frac{1}{V}\\de{V}{t}p\n\\end{equation}\nHere $a_0=\\frac{4}{3}\\sigma_T/(m_ec)$. The First term on right side represents sum of magnetic energy density and cosmic energy density while second term represents adiabatic energy loss or gained\\\\\n\n\\tbf{Q. Are there any other losses to consider of?}\\\\\n\\tit{We, do not consider bremsstrahlung and Coulomb losses because of very low particle density within Radio plasma}.\\fn{What are coulomb losses? is it some analogy to $I^2R$ loss.}\\\\\n\nSufficient pitch angle scattering is considered to keep the electron pitch angle distribution isotropic which is with regards to JP model. Electron pitch angle is basically the angle between velocity vector of electron and the magnetic field. \\\\\n\nThe compression ratio is defined as:\n\\begin{equation}\nC(t)=\\frac{V_0}{V(t)}\n\\end{equation}\nIf C is greater than 1, then gas is compressed with respect to its initial state.\\\\\n\nLet us try integrating \\eqref{eqp} by first allowing a change of variables form $p(t)\\rightarrow \\tilde{p}(t)=C(t)^{-1/3}p(t)$.\\\\\n\n\\tbf{*Do the integration later*}\n\n\\begin{eqnarray*}\n-C(t)^{-1/3} \\cdot \\de{p}{t}=C(t)^{-1/3} \\cdot a_0(u_B+u_C)p^2 +C(t)^{-1/3} \\cdot \\frac{1}{3}\\frac{1}{V}\\de{V}{t}p\\\\\n\\implies -\\cc{\\frac{V(t)}{V_0}}^{1/3} \\cdot \\de{p}{t}=\\cc{\\frac{V(t)}{V_0}}^{1/3} \\cdot a_0(u_B+u_C)p^2 + \\cc{\\frac{V(t)}{V_0}}^{1/3}\\cdot \\frac{1}{3}\\frac{1}{V}\\de{V}{t}p\\\\\n\\implies - \\cc{V(t)^{1/3}} \\cdot \\de{p}{t}=\\cc{V(t)}^{1/3} \\cdot a_0(u_B+u_C)p^2 +  \\frac{1}{3}\\frac{1}{V^{2/3}}\\de{V}{t}p\\\\\n\\end{eqnarray*}\n\nThe result being\n\\begin{equation}\\label{eqp2}\np(p_0,t)=\\frac{p_0}{C(t)^{-1/3}+\\frac{p_0}{p_\\star (t)}}\n\\end{equation}\n\\tit{Note that instantaneous momentum is dependent on two quantities, the compression rate which is determined by the environment of the radio cocoon and the $p_\\star$ which depends on the energy densities of losses from the cocoon.}\\\\\n\nand $p_\\star$ is defined as \\tbf{Characteristic Momentum}. This is basically the momentum only due to energy losses in Synchrotron and compton effect for rate of change of volume to be zero.\n\n\\begin{equation}\\label{eqpstar}\n\\frac{1}{p_\\star(t)}=a_0\\int^t _{t_0} dt^\\prime \\cc{u_B(t^\\prime)+u_C(t^\\prime)}\\cc{\\frac{C(t^\\prime)}{C(t)}}^{1/3}\n\\end{equation}\n\n\nNow, from \\eqref{eqp2} it is clear that for increase in energy density in fields and hence higher losses, the momentum would be governed by compression ration. Higher compression, higher momentum.\\\\\n\n\nNow suppose, the change in volume was approximated as,\\tit{power law in time}\n\\begin{equation}\nV(t)=V_0\\cc{\\frac{t}{t_0}}^{b}\\;\\;\\text{ or }\\;\\;C(t)=\\cc{\\frac{t}{t_0}}^{-b}\n\\end{equation}\n\\tbf{Q. What gives us the precedent of formalizing the variation of volume to a dominant single power of time and how wrong we can be if it is more of an expansion form?}\\\\\n\nTherefore as time passes for a positive value of 'b', the compression ratio of gas decreases, i.e. gas is expanding with respect to time. Now, this power law will help to provide an analytic solution to \\eqref{eqp} \\tbf{Find this analytic solution!!!!}\\\\\n\n\\begin{\\cbox}\nAs a further assumption, the photon energy density is considered to be constant, \\tit{as our theory is dominated by CMB background radiation, } it does not change with timescales considered here.\\\\\n\\end{\\cbox}\nFurther we assume, the magnetic field energy density scales as\n\\begin{equation}\nu_B(t)=u_{B,0}(V/V_0)^{-4/3}=u_{B,0}(t/t_0)^{-4b/3}\n\\end{equation}\n\\tbf{as one would expects for an isotropic expansion of the magnetized plasma-- Look into Ruta's thesis and Longair's High energy astrophysics eq. 11.8!!!}\\\\\n\n\nThe above assumptions help us to integrate \\eqref{eqpstar}. We will in addition to above assumptions also exclude the case of $b=3$ and $b=3/5$ (as they give logarithmic relations instead of power laws).[\\tbf{we are yet to derive all results and even see why values of b is refuted}].\\\\\n\nSo, we have the \\tbf{characteristic momentum of electron} defined as \n\\begin{equation}\np_\\star(t)=\\frac{C^{1/3}}{a_0t\\cc{\\frac{C^{5/3}-C^{1/b}}{1-5b/3} u_{B,0}+\\frac{C^{1/3}-C^{1/b}}{1-b/3} u_{C,0}}}\n\\end{equation}\n\\tit{We can see from the above equation why those values of b where refuted- the above expression of $p_\\star$ would blow up.}\\\\\n\n\n\\tbf{\\tit{Here, $C=C(t)$ for brevity}}. \\\\\n\nThe the synchrotron and Inverse Compton - cooling produces a sharp upper cut off in the electron distribution$f(p,t)$ at $p_\\star(t)$, \\tbf{even if the original distribution $f_0(p_0)$ at time $t_0$ extended to infinity. That would mean the at a time t once we go beyond $p_\\star$ the electron distribution would fall very sharp}.\\\\\n\nThe electron density per volume and momentum $f(p,t)dpdV$ for $p<p_\\star(t)$ \\fn{is it because, $p=p_\\star$ is the cut-off, and we expect approximately all of electrons to have a momentum less than the characteristic momentum?} is given by\n\\begin{equation}\\label{eqedis}\nf(p,t)=f_0(p_0(p,t))\\pe{p_0(p,t)}{p}C(t)\n\\end{equation}\nwhere \n\\begin{equation}\\label{eqpdis}\np_0(p,t)=\\frac{pC(t)^{-1/3}}{1-p/p_\\star(t)}\n\\end{equation}\nNow, if the original distribution was a power law\n\\begin{equation}\\label{eqe0dis}\nf_0(p_0)=\\tilde{f_0}p^{-\\alpha_e} _0\n\\end{equation}\nfor $p_{min0}<p_{0}<p_{max0}$\\fn{Here, we do not want to consider electrons which do not have enough momentum to emit significant synchrotron and hence we have set $p_{min0}$ }, the resulting spectrum is \n\\begin{equation}\\label{eqetdis}\nf(p,t)=\\tilde{f_0}C(t)^{\\frac{\\alpha_e +2}{3}} p^{-\\alpha_e}\\cc{1-p/p_\\star(t)}^{\\alpha_e-2}\n\\end{equation}\nfor $p_{min}(t)=p(p_{min0,t})<p<p_{max}(t)=p(p_{max0,t})$. In order to obtan \\eqref{eqetdis} we just need to substitute \\eqref{eqe0dis} and \\eqref{eqpdis} in \\eqref{eqedis} \\\\\n\n\\tit{\\tbf{N.P.:}existence of synchrotron cutoff means the that radiation pattern is not entirely synchrotron and hence  the cut off would represent the frequency after which the radiation pattern is no longer the same synchrotron of spectral index $\\alpha_e$ }\n\n\\tbf{We are interested in the situation where several phases of cooling characterized by different expansion or contraction rates and durations shaped the electron distribution as the time progressed. Note with require both rates of expansion and duration of phases to accomplish the task of formulation. Both are not the same.}\\\\\n\n We write $ p_1 = p(t_1)$ for the \\tbf{momentum of an electron originally at $p_0$ after phase 1}. The $p_1$ is characterized by\n\\begin{itemize}\n\\item the compression during this phase $C_{0 1} = C(t_1)$\n\\item and $p_{\\star 0 1} = p_\\star(t1)$\n\\end{itemize} \n   \\tbf{$p_2=p(t_2)$ for the momentum of the same electron after phase 2, characterized by $C_{1 2}=C(t_2)$ and $p_{\\star1 2}=p_\\star(t2)$, and so on.}\\\\\n It is straightforward to show that, the final electron momentum(\\tbf{momentum of same electron after n stages, calculated directly after n stages after stage 0}) $p_n$ after n such phases can still be written in the form\n \\begin{equation}\n p_n(p_0)=\\frac{p_0}{(C_{0n})^{-1/3}+p_0/p_{\\star 0n}}\n \\end{equation}\n where \n \\begin{equation}\n C_{0n}=\\Pi_{i=1} ^nC_{i-1i}=\\Pi^n _{i=1}\\frac{V_i-1}{V_i}=\\frac{V_0}{V_n}\n \\end{equation}\nwhich is basically the compression ratio of the final and initial configuration and maximal final momentum is given by\n\\begin{equation}\n\\frac{1}{p_{\\star 0n}}=\\sum^n _{i=1}\\frac{(C_{0i-1})^{1/3}}{p_{\\star i-1 i}}\n\\end{equation}\nThe effects of the individual cooling phases sum up weighted by $(C_{0 i}) ^{1/3}$ . Thus, \\textbf{whenever the radio plasma is most extended, cooling is inefficient}\\\\\nIt remains to provide the parameters describing the different phases.\\\\ \\tbf{Now, suppose we want to describe a phase i where the expansion or compression is described by $b_i$, and two of the following three quantities are given: $\\tau_i$, the time scale of expansion, $C_{i-1i}$, the compression ratio during the phase, and $\\Delta ti$, the duration of the phase. These quantities are related via }\n\\begin{equation}\\label{eqCi}\nC_{i-1i}=(1+\\Delta t_i/\\tau_i)^{-b_i}\n\\end{equation}\nWe get\n\\begin{equation}\\label{eqpdisi}\np_{\\star i-1i}=\\frac{C^{1/3}}{a_0t_i\\cc{\\frac{C^{5/3}-C^{1/b}}{1-5b/3} u_{B,i-1}+\\frac{C^{1/3}-C^{1/b}}{1-b/3} u_{C}}}\n\\end{equation}\nwhere, $C=C_{i-1,i}$ and $t_i=\\tau_i+\\Delta t_i$\\\\\nThe magnetic energy density at the beginning of the phase i is that of the end of the phase, phase $i-1$:\n\\begin{equation}\nu_{B,i-1}=u_{B,0}(C_{0,i-1})^{4/3}\n\\end{equation}\nThe resulting electron spectrum from an initial power law distribution is \n\\begin{equation}\nf_i(p)=\\tilde{f_0}C^{\\frac{\\alpha_e+2}{3}}_{0i} p^{-\\alpha_e}(1-p/p_{\\star,0i})^{\\alpha_e-2}\n\\end{equation}\nfor $p_{min\\;\\;i}(t)=p_i(p_{min0})<p<p_{max\\;\\;i}(t)=p_i(p_{max0})$ and $f_i(p)=0$ otherwise.\\\\\nThe synchrotron emission at a given frequency is \n\\begin{equation}\nL_{\\nu\\;\\;i}=c_3B_i V_i \\int^{p_{max\\;i}} _{p_{min \\; i}} dpf_i(p) \\tilde{F}(\\nu/\\nu_i(p))\n\\end{equation}\nwhere $c_3=\\sqrt{3}e^3/(4 \\pi m_e c^2)$ and the characteristic frequency $\\nu_i(p)=3eB_ip^2/(4 \\pi m_e c)$. The dimensionless spectral emissivity of a mono-energetic isotropic electron distribution in isotropically oriented magnetic fields $\\tilde{F}(x)$ can be approximated :\n\\begin{equation}\n\\tilde{F}(x)\\approx \\frac{2^{2/3}(\\pi/3)^{3/2}}{\\Gamma(11/6)}x^{1/3}\\exp\\cc{\\frac{-11}{8}x^{7/8}}\n\\end{equation}\nIn reality, after shock passage an originally isotropic ensemble of field lines gets partially aligned with the shock plane. This is also true for the unshocked radio plasma, since its morphology gets significantly flattened during compression (see phase 3 in Sec. 5). This would produce a radio polarization and a luminosity which depends on the viewing angle (Enslin et al., 1998). As long as we are only calculating the total luminosity of the radio cocoon/relic,this can be ignored. But, in case one wants to know the expected flux, one has to correct for the anisotropic emission pattern of the cluster radio relics. Fortunately, the degree of radio polarization can be used to determine the viewing angle with respect to the shock plane (Laing, 1980; Enslin et al., 1998).\\\\\nThe upper cutoff in the electron distribution at $p_{\\star \\;\\; 0 \\; \\;n}$ produces a cutoff in the synchrotron spectrum near $\\nu_{\\star n} = \\nu_c(p_{\\star 0n})$. But since $\\tilde{F}(x)$  has a broad maximum even a sharp cutoff in the electron spectrum gives a soft cutoff in the radio, with significant flux above $\\nu_{\\star n}$.\n\n\\section{The Model}\nThe radio plasma goes various stages of expansion and contraction between the release of the matter from radio galaxy and the reappearance as cluster radio relic:\n\\begin{itemize}\n\\item \\tbf{Phase 0: Injection}\n\\begin{itemize}\n\\item The radio galaxy is active and a large expanding volume is being filled with radio plasma.\n\\item assuming that there is no gas density gradient in the vicinity of the radio galaxy, The expansion of this cocoon is likely to be supersonic (with respect to the outer medium) and therefore $b_0 = 9/5$ \\tbf{(Kaiser and Alexander, 1997)}.\\tbf{How did we get the value of $b_0$}\n\\item the typical age of a radio source at the end of nuclear activity (Alexander and Leahy, 1987, for typical ages) is around $\\tau=0.15 Gyr$. We assume that the injection occurred with the same time constant.\n\\item by injection of fresh electrons, The particle population is kept close to a power-law distribution. In flux vs frequency plot, we assume a  spectral index of $\\alpha_e = 2.5$ and an upper cutoff at $p_{max0} = 10^5$. The momentum cut-off produces a radio cut-off above $42GHz(B/\\mu G)$.\\tit{The results are not very sensitive to the choice of this parameter.} \\tbf{ More realistic electron spectra at the end of phase 0 could be constructed by superimposing the spectra of the electron populations of different ages}, as in the models of Kaiser et al. (1997). \\tit{But, for the present purpose of demonstrating that \\tbf{the fossil radio plasma can be revived by compression}, our simplified treatment should be sufficiently illustrative. }\\tbf{Look into the sources to get all the parameters correct!!}\n\\end{itemize}\n\\item \\tbf{Phase 1:Expansion}\n\\begin{itemize}\n\\item Once the central engine of the radio galaxy became inactive, the radio cocoon might still be strongly over-pressured compared to its gaseous environment (Begelman and Cioffi, 1989). \\textbf{This is because of the internal pressure of plasma on the cocoon surface?}\\tit{ So does a surface actually exist which we call cocoon, that prevents diffusion of plasm into the surrounding medium?}\n\\item  If this is the case a Sedov-like expansion phase exists with $b_1 = 6/5$. \\tbf{The answer to my previous question lie in sedov like expansion phase}\n\\item Momentum conservation of the expanding shell around the cocoon forces the expansion rates at the end of phase 0 and beginning of phase 1 to be the same, leading to $\\tau_1 = \\frac{b_1}{b_0} \\tau_0 = \\frac{2}{3}\\tau_0$. \n\\item \\tbf{ The expansion will significantly deviate from $b_1 = 6/5$ at the moment when the \\tit{internal pressure drops to a value comparable to the environmental pressure}.}\n\\item We simplify this behaviour by assuming that \\tbf{the expansion is Sedov-like until pressure equilibrium} is reached. The \\tbf{radio cocoon probably becomes undetectable} during this phase, and therefore becomes a fossil radio cocoon or a so called \\tbf{radio ghost}.\n\\end{itemize}\n\\item \\tbf{Phase 2: Lurking.}\n\\begin{itemize}\n\\item In this phase the Pressure equilibrium with the environment is reached, and the volume of the radio plasma remains more or less constant. Therefore, in this stage, $C_{12}\\approx 1$ and $b\\approx 0$. Now, we consider this phase to last very long time and hence we consider $\\tau_2 \\rightarrow \\infty$ in \\eqref{eqpdisi} to get \n\\begin{equation}\\label{eqp12}\np_{\\star 12}=\\rr{a_0(u_{B2}+u_{C}\\Delta t_2)}^{-1}\n\\end{equation}\n\n\\item Due to the \\tbf{previous adiabatic energy losses} of the electrons, they reside at \\tbf{low energies during phase 2}.\\tit{Are adiabatic losses a part of sedov expansion phase?}.\n\\item Their radiation losses, which strongly depend on the particle energies, are therefore strongly diminished.  Additionally, the synchrotron losses are further reduced due to the weaker magnetic field during the expanded state of the radio cocoon.\n\\item The adiabatic losses are reversible, and will be reversed during the subsequent compression phase, whereas the radiative losses are irreversible. Since \\tbf{the latter are suppressed during this phase}, the radio ghost state can be called the \\tbf{energy saving mode of a radio cocoon.}\n\\end{itemize}\n\\item \\textbf{Phase 3: Flashing:} \n\\begin{itemize}\n\\item At this stage The fossil radio plasma gets dragged into a shock wave of cosmic large-scale structure formation, e.g. at the boundary of a cluster of galaxies or in a galaxy cluster merger event.\n\\item  While its thermal environment gets shocked, the radio plasma is not shocked due to the much higher internal sound speed.\n\\item The plasma is only compressed adiabatically because of the shocked external environment . \\tbf{The electron population and the magnetic field gain energy adiabatically}, leading to a \\tbf{steep enhancement of the synchrotron emissivity.}\n\\item The duration of this phase is given by\n\\begin{equation}\n\\Delta t_3= \\frac{V^{1/3}_2}{v_{shock2}}\\approx \\frac{0.1-1Mpc}{300-3000km/s}\\approx \\cc{30Myr-3Gyr}\n\\end{equation} \nwhere $v_{shock2}$ is the pre shock flow velocity in the shock frame.\n\\item This preshock flow velocity $v_{shock2}$ is related to pre shock sound speed as $c_{s2}=\\sqrt{\\gamma P_2/\\cc{n_e(m_p+m_e)/2}}$ via\n\\begin{equation}\nv^2 _{shock2}=\\frac{c^2_{s2}}{2 \\gamma}\\cc{\\gamma-1+(\\gamma-1)\\frac{P_3}{P_2}}\n\\end{equation}\n\\textbf{Check Landau and Lifshitz 1966} paper, here $\\gamma=\\frac{5}{3}$ is the adiabatic index of the thermal gas.\n\\item  The compression factor of the relativistic plasma is high, and can be calculated from the assumed pressure jump $P_3/P_2$ of the surrounding thermal gas, assuming pressure equilibrium before and after the shock passage:\n\\begin{equation}\nC_{23}=\\cc{P_3/P_2}^{3/4}\n\\end{equation}\n\\item Now we tru to get a rough picture of the compression process, this will also help us achieve the values of $b_3$ and $\\tau_3$\n\\begin{itemize}\n\\item The sound speed within the radio plasma should be much higher than even in the post-shock thermal environment, (it could be up to $c/\\sqrt{3}$, if the plasma is fully relativistic), so that an \\tbf{instantaneous response to environmental changes can be assumed.}\n\\item \\tbf{During the shock passage, the cocoon is exposed to the high thermal pressure of the post-shock gas on its down- and to the ram-pressure of the pre-shock gas on its up-stream side.}\n\\item   But, on the remaining surface the cocoon is only subject to the (much lower) up-stream gas pressure.\n\\item  The relativistic plasma will therefore start to expand orthogonal to the gas flow, producing a flattened pancake-like morphology. \n\\item In order be able to expel the ambient gas sideways \\tbf{why would the gas want to do that?} additional internal pressure  comparable to the ram pressure of the expelled material is needed. This pressure is produced by compression. \n\\item For that, The process of flattening stops when the ram pressure of the swept-up material at the expanding edges of the pancake is of the order of the ram pressure of the incoming flow \\textbf{What is the incoming flow here?}.\n\\item This implies that the ratio of the diameter to the thickness of the expanded cocoon is roughly 4 for a strong shock.\n\\end{itemize}\n\\end{itemize}\n  The compression is slow in the beginning, and rapid towards the end when the cocoon is significantly flattened. We mimic this by setting $b_3 = 2$ and a negative $\\tau_3$, according to \\eqref{eqCi}. We favour this over the more intuitive choice of a positive $\\tau_3$ and large negative $b_3$, since \\tbf{it describes the process of compression more realistically. }\n\\item \\tbf{Phase 4:Fading}\nIn this stage,The radio plasma is in pressure equilibrium with the post-shock medium, which should provide roughly a uniform environment: $b_4 = 0$. \\tbf{The radio emission of the relic now fades away due to the heavy radiation losses.}\n\n\\end{itemize}\n\\section{The Scenarios}\nHere we discuss three different plausible cases and try to illustrate the resulting plausible situations.\\\\\nThe following scenarios have been chosen:\n\\begin{enumerate}\n\\item \\tbf{Scenario A:} In this scenario, the relic is located at the \\tbf{center of a galaxy cluster}\n\\item \\tbf{Scenario B:} In this scenario, The location of the relic is near the cluster boundary, i.e., in the \\tbf{proximity of the accretion shock wave}.\n\\begin{\\cbox}\nIn the above scenarios A and B the duration of phase 2 was chosen to be so long that the shocked radio plasma could be barely observed as a weak ultra-steep spectrum source.\\\\\nAdditionally, In both the scenarios\\\\\nWe assume the initial cocoon (at the end of phase 0) to comtain the magnetic fields and the relativistic particles (electrons and protons)  with energies of $E_{B/e/p}=10^{60}erg$ each. \n\\end{\\cbox}\n\\item \\tbf{Scenario C:} In this scenario, the phase 2 is chosen shorter as it would henceforth result in moderately steepened spectrum of the cluster radio relic. In this scenario the relativistic energies are assumed to be $E_{B/e/p}=10^{58}erg$\n\\end{enumerate}\nIn all the above scenarios,\n\\begin{itemize}\n\\item the \\tbf{three components produce a \\tit{relativistic isotropic pressure of }}:\n\\begin{equation}\\label{eqisoP}\nP_{cocoon0}=\\frac{E_e+E_p+E_B}{3V_0}\n\\end{equation}\n \\item The spectral index of $\\alpha_e=2.5$ and a rather high cut off in the electron spectrum at $p_{max0}=10^5$.(\\tbf{This is claimed to have no physical influence on the conclusion.})\n \\item The lower cut off in electron spectrum is set at $p_{min0}=10$ in \\tbf{scenarios A and B} and $p_{min0}=100$ in \\tbf{Scenario C} .\\tbf{ The lower cutoffs only affect the normalizations of the radio fluxes, not the spectral shapes. }\n\\end{itemize}\nNow we look at scenarios individually:\n\\begin{itemize}\n\\item {Scenario A: The Cocoon at cluster center:}\nThe pre-cluster merger configuration at the location of radio galaxy are:\n\n\\begin{itemize}\n\\item Electron Density: $n_E: 0.3 \\cdot 10^{-3}cm^{-3}$\n\\item Temperature: $kT=3KeV$\n\\item Due to high environmental pressure , the internal pressure is assumed only twice of external pressure\n\\item The initial volume $V_0$ is obtained from \\eqref{eqisoP} \n\\end{itemize}\nNow the following assumptions and processes go in at various stages according accepted phenomenological logic:\n\\begin{itemize}\n\n \n\\item For the revived fossil cocoon to emit within observable frequency range, \\tbf{phase 2 cannot last longer than $\\Delta t_2=0.1Gyr$}.\\\\\n\n \\tbf{I want to be able to do these calculations at the end.}\n \n\\item We assume that the shock wave of a cluster merger event \\tbf{increases the internal pressure by $P_3/P_2 = 12$ during the phase 3}. This corresponds to a \\tbf{moderate shock with shock compression factor of 2.8}, whereas strong non-relativistic shocks can have a compression factor of 4. \\tbf{A moderate shock is expected, since both merging clusters are expected to have temperatures of several keV and therefore sound velocities comparable to the merger velocity.}\n\\begin{figure}[h!]\\label{figsceA}\n\\includegraphics[scale=0.7]{figsceA.png}\n\\caption{Radio spectrum of the radio cocoon in scenario A at the end of phases 0-4.}\n\\end{figure}\nCheck out Figure \\ref{figsceA}:\n\\begin{\\cbox}\nthe compression caused by the merger shock wave gives rise to a burst of low frequency emission, but practically no high frequency emission. This is due to the rapid decay of the upper end of the electron spectrum during phase 3, which essentially wipes out the adiabatic energy gains of these electrons. The source decays on a time-scale of a few tens of Myr, mostly due to the heavy synchrotron losses. If the radio cocoon is located in a more peripheral region of the cluster, where the density, the pressure and therefore the magnetic field strength inside the cocoon is much lower, these losses are also much milder. This lengthens the time scale over which the radiatively cooling synchrotron plasma can still be revived by the next passing shock, and thus rendered radio detectable. We, therefore, expect the radio relic phenomena to be found preferentially at larger cluster radii, and less often near the cluster center (although projection can help some relics to appear near the cluster core). The best environment to find cluster radio relics is, therefore, near the edges of the clusters. \n\\end{\\cbox}\n\\end{itemize}\n\\item \\tbf{Scenario B: The Cocoon at the Cluster Boundary}\nThe radio cocoon is assumed here to be born outside the cluster, in an environment of a dense galaxy filament, or a group of galaxies.\\\\\nThe pre-cluster merger configuration at the location of radio galaxy are(the parameters are much lower than the parameters when the cocoon was located at center of the cluster):\n\\begin{itemize}\n\\item Electron Density: $n_e=0.3 \\cdot 10^{-5}cm^{-3}$\n\\item Temperature:$kT=0.3KeV$\n\\item The freshly injected radio plasma might be overpressured by a factor of 100, leading to a short expansion phase(Phase 1). \\tbf{This is because the environmental pressure is not high}\n\\end{itemize} \nThe phenomological processes occurring during various stages\n\\begin{itemize}\n\\item After this, the electrons within the expanded Mpc sized cocoon suffer mostly the IC-losses, allowing revival of the radio plasma even $\\Delta t_2 = 1Gyr$ later .\\tit{The revival age for Scenario A cannot be pushed beyond $\\Delta t_2=0.1 Gyr$ for Scenario A}. The reason Scenario B has higher revival period is because of very low magnetic fields causing very low synchrotron losses.\n\\item  The revival can happen when the cocoon along with the ambient medium is crossed by the accretion shock of a cluster of galaxies in the Phase 3, which might entail a pressure jump as large as $P_3/P_2 = 100$, in order to heat the infalling cool gas to the cluster virial temperature of up to 10keV. \\tit{For scenario A this was the pressure ratios between phase 3 and phase 2 was 12}\n\\end{itemize} \n\\begin{figure}[h!]\\label{figsceB}\n\\includegraphics[scale=0.75]{figsceB.png}\n\\caption{Radio spectrum of the radio cocoon in scenario B at the end of phases 0-4.  The luminosity at the end of phase 2 is too small in order to be displayed in this figure.}\n\\end{figure}\nCheck out Figure \\ref{figsceB}\n\\begin{\\cbox}\nScenario B can explain the steep and bent radio spectrum of the cluster radio relic 0038-096 in Abell 85. An eye-fit to the radio spectrum (Fig. 5) shows that the maximal electron momentum in this case is $p_\\star = 10^4 (B/\\mu G)^{-1/2}$. The magnetic field strength of the cluster relic was estimated from the minimum energy argument to be $B \\approx 1\\mu G$ (Feretti and Giovannini, 1996) and from the detection of excess X-ray emission at the location of the relic, which implies a field strength of $B = 0.95 \\pm 0.10\\mu G$ (Bagchi et al., 1998) if this emission refers to the IC scattered cosmic microwave background photons, otherwise a higher field strength. Using $B = 1\\mu G$ and $p_\\star = 10^4$ and assuming a uniform environment without expansion and compression, an age of 0.2Gyr would result (Komissarov and Gubanov, 1994, and see Eq. \\eqref{eqp12}). But scenario B demonstrates that the radio plasma can be as old as 2Gyr. This resolves the problem of the apparent cooling time of the electrons being too short for any nearby galaxy to have ejected the plasma and then moved to its present location with a typical velocity of a cluster member. For the long duration of phase 2 the resulting spectrum is fairly steep in the observable radio range. But this need not to be the case for a scenario with a shorter fossil phase. \n\\end{\\cbox}\n\\item \\textbf{Scenario C: The Smoking Gun}\n In order to substantiate the last statement, we choose a set of parameters for scenario C which produces a cluster radio relic with relative flat, nearly unbent radio spectrum.\\\\\n The characteristics of the cocoon pre-cluster merger are\n \\begin{itemize}\n \\item electron density $n_e=0.3 \\times 10{-5}cm^{-3}$\\\\\n \\item $kT=0.6KeV$\n\\end{itemize}  \n The inflow of the plasma and the compression at the cluster accretion shock wave might have taken a few hundreds of Myr. We assume a pressure jump of only $P_3/P_2 = 40$ at the shock wave, not higher, in order to allow the temperature of the post-shock gas to stay below the average cluster temperature of 8.2KeV  As can be seen in Fig. \\ref{figsceC}, the radio spectrum below 1 GHz stays practically unbent for a couple of tens of Myr after the shock passage.\n\\begin{figure}[h!]\\label{figsceC}\n\\includegraphics[scale=1]{figsceC.png}\n\\caption{Radio spectrum of the radio cocoon in scenario C at the end of phases 0-4.  }\n\\end{figure}\n\\end{itemize}\n\\chapter{Cocoons Of Radio Galaxies}\n\\tbf{This section is taken up from Intergalactic Matter And Cocoons of Radio Galaxies by \\tit{Biman B. Nath}}. Refer \\tit{Begelman and Cioffi for more details,1989. Overpressured Cocoons in Extragalactic Radio sources}\\\\\n\\tbf{What are radio cocoons?}\\\\\nA cocoon is a natural by-product of the propagation of a supersonic jet through a denser ambient medium. Given a high-pressure jet, the slow lateral expansion of the cocoon guarantees that the average cocoon pressure will exceed the ambient pressure in the initial stages of the jet evolution. \n\n\\tbf{What keeps the cocoons expanding?}\nCocoons have been shown to remain overpressured with respect to the ambient medium for most of their lifetime of the source.\\\\\n\n\n It has long been evident that supersonic, low-density jets deposit most of their energy in the cocoon, which acts as a \"wastebasket\" (\\tit{Scheuer, P. A. G. 1974, MNRAS, 166, 513.\n}).\\\\\n\n\\tbf{Where does the idea of overpressure come into picture?}\\\\\nRecently, however, Begelman and Cioffi ( \\tit{Begelman, M. C., and Cioffi, D. F. 1989, ApJ, 345, L21}; hereafter BC) argued that the cocoons remain overpressured with respect to the ambient medium for a long time, and that for many sources, they have not yet reached a state of equilibrium. They then used this fact to address the problem of jet confinement by the ram pressure of the cocoon.\n\n\\tbf{So, what is the intutive picture we have of cocoons?}\\\\\n\\begin{\\cbox} \nThe picture that emerges from these studies is that of a overpressured, jet-nourished cocoon, whose length and width depend on the balance of the ram pressure of the ambient medium with, respectively, the jet's momentum flux and the cocoon pressure. \n\\end{\\cbox}\n\nHere we use, the value of hubble constant as $H=h_{50}\\;\\;km\\;\\;s^{-1}\\;\\;Mpc^{-1}$.\n\\section{Overpressured Cocoons}\n\\tbf{Why the jets produced cocoons must be light and hypersonic?}\\\\\n\nWe will not consider heavy jets to form cocoons as  Heavy jets behave like 'bullets' and do not form cocoons. And since the jet luminosity is proportional to$ M^3_h$ (M is the Mach number of the head of the jet with respect to the sound velocity of the ambient medium), high luminosity of the classical double jet implies hypersonic, if not supersonic, jets.\\\\\n\nNow, here we have assumed the $\\rho_j$ is smaller that of the ambient medium $\\rho_a$ i.e. $\\eta=\\rho_j/\\rho_a$. \\\\\n\n\\tbf{Mechanics of cocoons:}\\\\\n\nLet us assume that $L_j$ be the jet power which is constant in time for simplicity.\\\\\n\n\\tbf{Finding velocity of jet data:}\\\\\n\nThe velocity of the head of the jet $v_h$ is determined by the balance of the thrust of the jet($\\sim L_j/v_j$) spread over the cross sectional area $A_h$ of the bow shock at the end of the jet and the ram pressure of the ambient medium. This yields\n\\begin{equation}\nv_h \\sim \\cc{\\frac{L_j}{\\rho_a v^3_j A_h}}^{1/2}v_j\n\\end{equation}\nNotice that $A_h$ can be much larger than the cross-section of the jet itself. The cocoon pressure is given by dividing the total energy deposited by the jet inside the volume of the cocoon $V_c= \\epsilon_V (2\\pi r^2_c)l_h$ where $r_c$ is half width of the cocoon at the center , $l_h=\\int v_h dt$ is the length of the jet head and $\\epsilon_V$ is the volume factor depending on the shape of the cocoon. The value of $\\epsilon_V$ is\n\\begin{itemize}\n\\item 1 for cyclindrical cocoon\n\\item 1/3 for biconical\n\\end{itemize} \nOne thus obtains \n\\begin{equation}\np_C=\\frac{(\\gamma-1)L_jt}{V_c}\\approx \\rho_A\\cc{\\de{r_C}{t}}^2\n\\end{equation}\nHere the second equality comes from balancing the cocoon pressure with the ram pressure of the ambient medium. $\\gamma$ is the adiabatic index of the material in the cocoon. This readily yields upon integration an expression for the size of the cocoon as:\n\\begin{equation}\nr_c^2 \\approx \\cc{\\frac{6 (\\gamma -1)}{\\pi}}^{1/2} \\cc{\\frac{L_jv_jA_h}{\\rho_A}}^{1/2}\\cc{\\frac{\\epsilon_V}{1/3}}^{-1/2}t^{-1}\n\\end{equation}\nAnd the above two equations can be combined to give the cocoon pressure, as\n\\begin{equation}\np_c\\approx \\cc{\\frac{9(\\gamma-1)}{24\\pi}}^{1/2}\\cc{\\frac{L_j \\rho_a}{v_h}}\\cc{\\frac{\\epsilon_V}{1/3}}^{-1/2}t^{-1}\n\\end{equation}\nThe last equation  allows us to estimate the time $t_{eq}$ for the cocoon to reach pressure equilibrium with the ambient medium, after which the cocoon boundary expands at the sound speed of the ambient medium. For powerful radio galaxies, with length-scales of the order of Mpc, the ambient medium is the IGM. We can write the equilibrium time\nscale as,\n\\begin{eqnarray}\nt_{eq}\\approx\\frac{\\mu m_p}{kT_a}\\cc{\\frac{L_jv_jA_h}{\\rho_a}}^{1/4}\\cc{\\frac{9(\\gamma-1)}{24 \\pi}}^{1/2}\\cc{\\frac{\\epsilon_V}{1/3}}^{-1/2}\\\\\n\\sim 1.34 \\times 10^{10}(T_{a,6})^{-1}\\Omega^{-1/4}_{IGM}h^{1/2}_{50}L^{1/4}_{j,45}\\beta^{1/4}_j A^{1/4}_{h,30}\\cc{\\frac{\\epsilon_V}{1/3}}^{-1/2}yr\n\\end{eqnarray}\nHere,\n\\begin{itemize}\n\\item $\\mu \\sim 0.6$ is the molecular weight\\\\\n\\item $T_a=10^6 T_{a,6}K$ is the temperature of the IGM gas\n\\item k is the boltzman constant\n\\item $L_j$ is in the units of $10^{45}erg\\; s^{-1}$ \n\\item $A_h$ is in the units of $30kpc^2$\n\\end{itemize}\n\n\\chapter{Ruta Kale's Thesis}\n\\section{Introduction}\n\\section{Radio Relics}\nDiffuse radio sources with filamentary, elongated morphologies, not associated with any active galactic nucleus are termed as radio relics (e.g. Ferrari et al 2008). \\\\\n\\textbf{\\tit{may be they are not at all related to merger and they are just related to dead radio galaxies and the reason these dead galaxies get re-accelerated are the merger events}}\\\\\nThese can either be associated with galaxy clusters \\tbf{(cluster radio relics)} or can be remnants of radio galaxies \\tbf{(relic radio galaxies)}.\\\\\n\\textbf{\\tit{May be cluster radio relics and relic radio galaxies are not different and can be united to form a single group of relics, we can do this if we see similar attributes in structures or if we analyse the outcome of a particular relic radio galaxy being subjected to a shock and if the results are same as cluster radio relics we can have a united front}}.\\\\\n\\textbf{Properties of these relics:}\nSuch sources typically have steep synchrotron spectra ($\\alpha$ > 1) and high degree of polarization $(\\sim 10\\% - 40\\%)$ (Ferrari et al 2008 for a recent review). The linear sizes of the relics range from\n200 kpc to 2 Mpc. Relics are also low surface brightness ($\\sim mJy$ $arcmin^{-2}$ at 1.4 GHz) sources and occur in only $\\sim 6\\%$ of all clusters (Giovannini et al 1999). \\\\\n\\textbf{\\tit{it would be great if would be able to predict, which clusters should we observe relics (we, can give a methodology for the same!) and second think on the reason why we don't see relics more often}}\n\\subsection{Fossil/Relic Radio Galaxies}\nRadio galaxies produce jets which pump relativistic plasma into the surrounding medium. Back flows of the relativistic plasma are formed at the end of the jet and the non-thermal plasma(\\tbf{\\tit{just referring to non-Maxwellian distribution of particles}}) occupies regions surrounding the jets forming lobes.\\\\\n\\textbf{What happens to these lobes when the AGN switches off?}\n The overpressured lobes expand, even after the AGN switches off, until pressure equilibrium is attained and form structures like cocoons.\\\\\n\\tbf{\\tit{here, we are not questioning, whether to form such lobes in lifetime of AGN is feasible at all by the same mechanism? I mean does the current state of relic be related to expanded lobes numerically?}}\\\\ \n \n The PdV work done on the surrounding medium during expansion amounts to a loss in energy. \\tbf{\\tit{I would like to calculate if it is actually that feasible and timescales match!}}\\\\\n \n Such cocoons can remain detectable after the AGN stops to be active for only about 10-100 million years.\n\\tbf{\\tit{what are the various processes, by which this non thermal plasma,loose energy, a complete description of which will give us a handle on lifetime of such galaxies. It is just hard to relate if it is just synchrotron, then why do we have a number that has a factor of 10 i.e. there age may go from 10 to 100 mil.}} \\\\\n  These can be then seen as filamentary, elongated or double\nlobed radio sources with no obvious jets or cores. \\\\\n\\textbf{The short lifetimes can be the reason for a rarity of such sources. }For example, the relic in the cluster A85 (Slee\net al 2001) could be such a fossil (Fig. 1.7, left). Other examples of such relics are A133 (Fig. 1.6, right) (Slee et al 2001) and the relic in A4038 (Slee et al 2001; chapter 4).\\\\\n\\tit{There have been attempts to model the radio spectra of such sources to extract parameters such as the \\tbf{timescale over which the AGN was active, the time spent by the plasma in relic phase and the magnetic field (Komissarov $\\&$ Gubanov 1994; Slee et al 2001; Kaiser $\\&$ Cotter 2002).} } There are two basic approaches:\n\\begin{enumerate}\n\\item \\tbf{The JP models(Jaffe and Perola (1973)):}\\textbf{ In this approach the pitch angle of the electrons is assumed to isotropize much faster than the energy loss timescale}. Alfvén wave is a type of magneto hydrodynamic wave in which ions oscillate in response to a restoring force provided by an effective tension on the magnetic field lines. The scattering of electrons off the Alfen waves causes the isotropization. \\tbf{ The models which use the assumption of isotropization of pitch angles are regarded as JP models.}\n\\item \\tbf{The KP model:}\n\\end{enumerate}\n\n\\section{Chapter 2:}\n\\section{Summary}\nThe primary aim of the thesis was to understand\nthe origins of radio halos and relics in clusters of galaxies. \n\\subsection{Results}\n\\begin{itemize}\n\n\\item The multi-frequency (150, 350, and 1369 MHz) analysis of the radio halo and the relic in A2256 indicates that turbulent reacceleration during mergers may be the mechanism that generated the radio halo and the relic. \\textbf{\\textit{Refer Chapter 2: It would help you understand, how do we point out that a process or a result is indicative of turbulent re-acceleration}}.\\\\\nThe flat spectrum NW region of the relic ($\\sim$ 200 kpc region, showing polarization upto $45\\%$ at 1.4 GHz, CE06) could be the result of the current activity of a shock that passed through the cluster from SE to NW.\\textbf{\\tit{Shouldn't in order to conclude that a particular relic is a result of shock activity, should we say that the electrons age with time? What about the flat spectrum helps us know if a shock led to origin of particle acceleration}}\\\\\n The low frequency steepening of the spectra of the diffuse radio emission in A2256 (spectral index maps, Figs. 2.2 and 2.4) is interpreted as the result of superposition of spectra of relativistic electrons accelerated at two epochs. These two epochs are interpreted to be the two mergers that are proposed to have occurred based on X-ray and optical observations (Sun et al 2002; Berrington et al\n2003).\n\n\\item b\n\n\\item c\n\\item d\n\\item  The identification of ultra-steep spectrum ($\\alpha < - 1.8$) sources from the NVSS and the VLSS and their imaging at 330 MHz (VLA) and at 1.4 GHz (GMRT) led to the discovery of double lobed sources with no obvious presence of cores and jets (AGN).\\textbf{\\tit{What is NVSS and VLSS?}}\\\\\n These are interpreted to be dead radio galaxies.\\\\\n\\textbf{Can there be other possibilities, can it just be dust clouds and not exactly relics?}\\\\ \n  The model of lurking radio cocoons implies that most of these are sources which have been in the 'relic' phase (AGN off) for more time than the time scale for which the AGN was active. \\\\\\textbf{Why?}\\\\\nAssuming a mean redshift of 0.2 (4 of the 10 sources are at this redshift) for these sources, the present luminosities ($L_{1.4} \\sim 10^{24}W Hz^{-1}$) imply that their luminosities in active phase would have been 10 - 100 times of those of the brightest AGN s in the local universe.\\\\\n\\textbf{Do the same calculation, again!}\\\\\n\nWith the detection limits of the VLSS and the NVSS only the brightest among such dead radio sources could be detected. The luminosity function of the currently active AGN indicates that the number density of sources with power $L_{1.4} \\sim 10^{24} W Hz^{-1}$ is 100 times higher than with $L_{1.4} \\sim 10^{27} W Hz^{-1}$ (Sadler et al 2002) and more sensitive surveys will be able to detect these.\\\\\n\\textbf{I don't understand , this point!}\\\\\n\n These studies will\nlead to the understanding of the various stages of AGN evolution. (Chapter\n5; Dwarakanath, K. S. $\\&$ Kale, R. 2009, ApJL, 698, 163)\n\n\n\\end{itemize}\n\\chapter{List Of Sources}\nBelow I present the list of sources by unifying data from DB1-$www.galaxyclusters.com$ and DB2(Bold font)-$https://arxiv.org/pdf/1808.04057.pdf\n$\n\\begin{itemize}\n\\item The list is organized in ascending order of Redshift .\\\\\n\\item First column indicates designation of source.Second column represents Redshift as provided in DB1  and Third column represents Redshift from DB2.\n\\end{itemize}\n\n\\begin{center}\n\\begin{tabular}{|c|c|c|c|c|}\n\\hline \n\\tbf{Designation} & Redshift1(z) & Redshift2 & Frequency(MHz) & Surface Brightness(mJy)\\\\\n\\hline\n\\multirow{4}{*}{AS753} & 0.0130 & \\tbf{0.014} & 2378 & 100\\\\\n&&&330&8500\\\\\n&&&1398&460\\\\\n&&&843&1300\\\\\n\\hline\n\\multirow{7}{*}{A4038} & 0.0303 & \\tbf{0.02819}&843&170$\\pm$30\\\\\n&&&80&19000$\\pm$2700\\\\\n&&&160&4300$\\pm$500\\\\\n&&&327&1440$pm$150\\\\\n&&&1400&61$\\pm$3\\\\\n&&&408&910$\\pm$110\\\\\n&&&30&32000$\\pm$7000\\\\\n\\hline\n\\tbf{A2063}&&\\tbf{0.0349}\\\\\n\\hline\n\\tbf{A548b-NW} &&\\tbf{0.0424}\\\\\n\\hline\n\\tbf{A548b-N} &&\\tbf{0.0424}\\\\\n\\hline\n\\multirow{11}{*}{A85}& 0.0557 & \\tbf{0.0551}&843&200$\\pm$30\\\\\n&&&16&93000$\\pm$24000\\\\\n&&&80&34000$\\pm$3700\\\\\n&&&2700&10\\\\\n&&&300&2739\\\\\n&&&1400&43$\\pm$3\\\\\n&&&30&93000$\\pm$13000\\\\\n&&&408&1540$\\pm$250\\\\\n&&&1425&40$\\pm$2.3\\\\\n&&&160&8330$\\pm$700\\\\\n&&&327&3200$\\pm$320\\\\\n\\hline\n\\multirow{11}{*}{A133} & 0.0603&&4900&4$\\pm$0.3\\\\\n&&&2700&29$\\pm$16\\\\\n&&&1400&168$\\pm$6\\\\\n&&&843&530$\\pm$60\\\\\n&&&408&2620$\\pm$250\\\\\n&&&160&10900$\\pm$1200\\\\\n&&&80&35500$\\pm$4300\\\\\n&&&30&46000$\\pm$13000\\\\\n&&&330&3267.2$\\pm$7.7\\\\\n&&&1400&136.8$\\pm$0.2\\\\\n&&&327&2820$\\pm$280\\\\\n\\hline\n\\multirow{2}{*}{A725} & 0.0900&1400&6$\\pm$1\\\\\n&&&327&76$\\pm$9\\\\\n\\hline\n\\multirow{10}{*}{A13} & 0.0943 & \\tbf{0.0943}&160&2800$\\pm$600\\\\\n&&&1425&35.5$\\pm$1.7\\\\\n&&&80&6000$\\pm$1200\\\\\n&&&843&90$\\pm$10\\\\\n&&&160&2800$\\pm$600\\\\\n&&&1400&34$\\pm$0\\\\\n&&&408&490$\\pm$80\\\\\n&&&1400&31$\\pm$0\\\\\n&&&1400&30$\\pm$3\\\\\n&&&327&630$\\pm$60\\\\\n\\hline\n\\multirow{2}{*}{A2048} &0.0980& \\tbf{0.0972}&325&559$\\pm$61\\\\\n&&&1425&18.9$\\pm$4.3\\\\\n\\hline\n\\multirow{3}{*}{A2443} & 0.1080 & \\tbf{0.1080}&1425&6.5$\\pm$0.5\\\\\n&&&74&5310$\\pm$175\\\\\n&&&325&406$\\pm$69\\\\\n\\hline\n\\multirow{6}{*}{A1033} & 0.1220&&1341&53.9$\\pm$7.3\\\\\n&&&1465&45.8$\\pm$1.3\\\\\n&&&365&380$\\pm$0\\\\\n&&&1422&46.9$\\pm$7.6\\\\\n&&&1385&51.2$\\pm$1.5\\\\\n&&&608&220$\\pm$0\\\\\n\\hline\n\\tbf{A1664} & &\\tbf{0.1283}\\\\\n\\hline\n\\multirow{2}{*}{24P73} & 0.1500 & &1400&12$\\pm$3\\\\\n&&&325 &307$\\pm$33\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\tbf{Comments:}\n\\begin{itemize}\n\\item \\tit{The galaxy cluster database even if has classified the above as phoenix sources, There is a special mention of 'candidates' for few of the above sources in the surface brightness column, of which there is no description.}\\\\\n\\item \\tit{ The Redshift is measured from SDSS data. How do we have a discrepancy in redshift for some of the phoenix sources? How much important is redshift for us?}\n\\end{itemize}\n\\chapter{Coding Bootstrap}\nImportant point to note :\n\\begin{itemize}\n\\item Results depend on time scales ruthlessly.\n\\item The numerical calculations on infinities (in timescales of cooling) in calculation $p_{\\star\\; i-1\\;i}$ is handled by replacing the original expression with analytical expression in the same limit.\n\\item Rather than finding the energy density of inverse compton we use energy density of CMB at that redshift. (I forgot the redshift but it was through a google search and not in a review paper)\n\\item Something I am not sure still is how to find lower limit of momentum. and if it matters that the lower limit changes and how.\n\\item The only thing left is to identify , how to find magnetic field, volume of the source and time scales. Rest of the code is secured.\n\\item The $p_{max}i$ is determined to be maximal momentum in that stage given by $p_{\\star\\;0\\;i}$\n\\end{itemize}\n\\newpage\n\\section{29th June}\n\\tbf{Today's Target\n\\begin{itemize}\n\\item Target for today is collect data for Abel 1914 from Somyajit Mandal's Paper and if it changed from the data set provided by Ruta.\n\\item How to calculate magnetic fields, volume and redshift from observations.\n\\end{itemize}}\n\n\\subsection{Mandal's Paper}\nFrom Soumyajit's paper:\n\\begin{itemize}\n\\item The redshift he assumed is z=0.168 . Has high assymetric X ray distribution which is an indicator of merger. The other indicator of radio phoenix is ultra steep spectrum which is a result of synchtron and inverse compton cooling.\n\\item Furthermore, Botteon et al. (2018a) found surface brightness and temperature jumps in the ICM. \n\\item Is resolution of image dependent on the frequency we observe? if not how do we generate high resolution imaging in radio. What does $\\sigma_{rms}$ mean?\n\\item At the redshift of the Abell 1914 (z = 0.168). the luminosity distance is 808.5 Mpc and 1 arcsec corresponds to 2.873 kpc.\n\\item In this paper the following data was used:\n\\begin{itemize}\n\\item New Observation: LOFAR 150Hz and GMRT 610\n\\item Archival Observation: VLA 1.4 GHz and GMRT 325 MHz.\n\\end{itemize}\n\\item The measured flux density are as follows:\n\\begin{itemize}\n\\item \\tbf{150Hz:} 4.68$\\pm$0.46 Jy\n\\item \\tbf{325MHz:} 0.83$\\pm$0.08 Jy\n\\item \\tbf{610MHz:} 0.277 $\\pm$0.02 Jy\n\\item \\tbf{1.4GHz:} 34.8 $\\pm$ 2.0 mJy\n\\end{itemize}\n\\item The spectral index computed for $\\alpha_{150-1.4}=-2.17 \\pm 0.11$ for radio phoenix\n\\item They found that a second order polynomial was more appropriate as a fit than a traditional linear fit indicating curvature in spectral shape.\n\\item The phoenix candidate has a south west extension which may or may not be associated with a radio galaxy. It may just be a projection effect or the Radio phoenix is a radio bubble which was detached from the tail of the galaxy due to shock.\n\\item Botteon et al. (2018a) suggested that the merging scenario in Abell 1914 is similar to that observed in the bullet cluster (Markevitch et al. 2002) where a subcluster is moving from the E to the W direction, producing a cold front in the direction of the motion. On the eastern side of Abell 1914, they claimed the presence of a shock moving in the cluster outskirts, similar to the reverse shock found in the Bullet cluster (Shimwell et al. 2015). Deeper X-ray observations are needed to confirm this. But, the Xray observations are too shallow to confirm X-ray in the vicinity.\n\\end{itemize}\n\\section{6th July}\nBriefs of Revived Fossil Plasma Sources in Galaxy Clusters. by S. Mandal\n\\subsection{Revived Fossil Plasma Sources in Galaxy Clusters}\n\\tbf{When a pocket of fossil radio plasma is compressed, it boosts the visibility at sub-GHz frequencies, creating so-called radio phoenices. This compression can be the result of bulk motion and shocks in the ICM due to merger activity.}\\\\\nStudying them without boosting through compressing  these fossil electrons are barely visible even at radio frequencies well below a GHz due to  the typical steep radio spectrum due to synchrotron losses.\\\\\n\\begin{itemize}\n\\item When the galaxy cluster undergo mergers with other clusters. A huge amount of gravitational binding energy of the order of $\\sim 10^{64}$ ergs is released when galaxy clusters merge (e.g. Kravtsov $\\&$ Borgani 2012). \\tbf{where does this binding energy go? Go through the paper.}\n\\item The category of 'radio phoenices', as was defined by Kempner et al.(2004).\\\\\n\\item Sources have spatially non-uniform spectral indices suggests a different degree of mixing of the relativistic particles from the AGNs with the ICM and implies that several mechanisms are operating for the re-energisation of the plasma. \n\n\\subsection{Viral Parekh's 3017}\n\\begin{itemize}\n\\item  when two extremely large mass concentrations,such as two galaxy clusters,come relatively close to each other ($\\sim$ order of Mpc distance), the mass density of the filament/bridge between them is expected to be higher than the mean and might be detectable.Hence,binary galaxy clusters are the ideal locations to search for large-scale matter filaments and understand their role in structure formation. \n\n\\item Galaxy clusters grow in mass through certain processes:\n\\begin{itemize}\n\\item Merging with other cluster\n\\item accretion of matter\n\\end{itemize}\nThe first mechanism leads to \\tbf{X-ray substructures of hot gas due to heating and mixing of intra-cluster gas,}  and the later process proceeds via \\tbf{super sonic inflows near the virial radii of the clusters\\fn{This could be a good marker to decide if the fossil blob is in virial radii than the chances are to be re-accelerated.}}\n\\item  The central active galactic nucleus (AGN) plays an active role in creating cavities and bubbles. In an investigation of a large sample of such systems, it was revealed that a central radio source was present in every system,with the radio plasma(or radio lobes)often filling the cavities and bubbles.The X-ray cavities and bubbles are therefore interpreted as regions where the X-ray emitting gas has been displaced by radio plasma produced by energetic outflows from the AGN that injects significant power into the ICM. Hence the central AGN is thought to be a heating source providing feedback to compensate for the excessive cooling of the cluster core. \n\\item Spiral features are likely related to \"sloshing\"(meaning: a fluid moving irregularly) of the ICM in the core of the cluster(Blantonet al.2011).Simulations(Ascasibar $\\&$ Markevitch 2006; ZuHone et al. 2011)  have shown that the off centre collision of a cluster with a galaxy group, with mass ratios  1/2 to 1/10, accelerates both the dark matter and the cool gas of the cluster core, but the gas component is decelerated by ram pressure, resulting in separation between dark matter and baryons.  As the ram pressure weakens, the cool core gas falls back into the potential well, but overshoots it and begins to \"slosh\". This mechanism is efficient to move the cool gas from the center but it cannot stop or regulate the cluster cooling flow.\n\\begin{itemize}\n\\item  \\tbf{Is the text saying, that collision between two dark matter particles is not same as normal baryons.} Imagine  dark matter component as a shell surrounding the cluster, if the shell breaks, when the merger occurs, it may really not be affecting the overall structure but only at point of collision? So it may be possible that the velocity was just enough to kick out the dark matter at the line of action but not enough to perturb the dark matter of the whole system.\n\\item \\tbf{secondly, this mechanism sort of clears out the cooling outflow due to temperature difference?}.\n\\end{itemize}\n\\item \\tbf{Discussion}\n\\begin{itemize}\n\\item Estimate temperature for A3017 is $\\sim 5.8^{-0.57}_{+00.62}$ KeV. There is hot X-ray filament associated with A3017 and has a temperature of $\\sim 3.7^{-0.73}_{+1.22}$ KeV . The temperature of group sized systems is usually . 1 keV(Bahcall 1996;Rosati et al.2002), hence this X-ray emission is most probably related to the cluster ICM than to a group.\n\\item .From the optical data for A3017, it becomes clear that A3017 is an early stage merger because the positions of the brightest central galaxies are still associated with the X-ray peaks. In a late stage merger,the galaxies and ICM are often distributed differently.\n\\item There could be a weak shock present in the A3017, the presence of the weak shock in the filament could be responsible for the linear vertical radio structure visible in the radio map.\n\\item Akahori and Yoshikawa predict weak shocks of the Mach number $M \\sim 1.5-2.0$ at the bridge regions. These shocks are immediately formed at the contact interface of the two clusters when the clusters begin to collide, and they then propagate in a direction perpendicular to the merger axis outside of each cluster, forming outgoing merger shocks\n\\item However, in the present case, there is no strong evidence that the south X-ray cluster is at the same redshift as A3017,based on the galaxy density map analysis, so these two clusters do not form a binary cluster merger. We need further optical spectroscopic information to prove or disprove whether the X-ray bridge is connecting two binary cluster or is only associated with A3017 as hot X-ray tail.\n\\item Assuming the formula:\n\\begin{equation}\nt_{cool}=69\\cc{\\frac{n_e}{10^{-3}cm^{-3}}}^{-1}\\cc{\\frac{T}{10^8 K}}^{1/2} Gyr\n\\end{equation}\nThe cooling time came out to be A3017 1.4 Gyr.  There are substructures, two opposite cavities, and a spiral arm, visible in the core region and surrounding it.The cavities are filled with radio emission at 235 and 610 MHz, and they are very likely large empty bubbles evacuated by the AGN's radio lobes\n\\end{itemize}\n\\end{itemize}\n\\end{itemize}\n\n\\section{Data}\nThis is a record of the data I have and the data I have analysed\n\\begin{table}\n\\begin{tabular}{|c|c|c|c|c|c|}\n\\hline\nProposal ID & Observation & Type & Frequency & Pipeline & Saved\\\\\n\\hline\n$32\\_091$ &  9499(18jun) & GWB & 1450 MHz & &\\\\\n\\hline\n$32\\_091$ &  9757(17sep) & GSB & 306 MHz & &\\\\\n\\hline\n$32\\_091$ &  9757(17sep) & GWB & 306 MHz & &\\\\\n\\hline\n$32\\_091$ &  9762(18SEP) & GSB & 306 MHz & Analysed & $A3017\\_325gsb$\\\\\n\\hline\n$32\\_091$ &  9762(18SEP) & GWB & 500 MHz & Process & $A3017\\_325gwb$(change name)\\\\\n\\hline\n\\end{tabular}\n\\end{table}\n\n\\section{Data}\nSources in the table are near the clusters and in the filament region, which was not found in databases or was not classified . The sources present in the filament region is marked with [Fil]. And the sources which were available in the [2MASS] or [Gaia] is also presented.\n\\begin{table}\n\\begin{tabular}{|c|c|c|c|c|c|}\n\\hline\nSource & R.A. & Declination & 325 MHz & 500 MHz & 1450 MHz\\\\\n\\hline\n1 [2MaSS]& 2:26:38.948 & -42:00:13.33 & Yes\t& Yes\t&Yes\\\\\n\\hline\n2[Gaia DR2] & 2:26:24.257  & -42:02:53.65 &\t Yes& Yes\t&Yes\\\\\n\\hline\n3 & 2:26:18.262 & -42:04:17.74 & Yes\t& yes\t&Yes\\\\\n\\hline\n4 & 2:25:49.420 & -42:08:07.93 &\t Yes& Yes\t&\\\\\n\\hline\n5 [Fil] & 2:25:47.988 & -42:02:07.98 &\t Yes& Yes\t&Yes\\\\\n\\hline\n6 [Fil $\\&$ 2MASS source]& 2:25:39.017  & -42:00:47.8 &  Yes\t& Yes\t&\\\\\n\\hline\n7 [Fil]& 2:25:12.980  & -42:02:15.57 & Yes\t& Yes\t&\\\\\n\\hline\n8 & 2:25:49.785 & -42:04:28.87 & Yes\t& Yes\t&\\\\\n\\hline\n9 & 2:26:13.789 & -42:09:15 & Yes\t& Yes\t&\\\\\n\\hline\n\\end{tabular}\n\n\\end{table}\n\\section{Discussion with Devo}\n\\tbf{Q.  Why is it a good idea to split spw during calibration?}\\\\\n\nNow suppose we use n terms as 2 , we make a second order fit in frequency. If our source has a complex frequency structure it is difficult to put it in a model with just second order polynomial. So, one would require to find solutions for a set of channels or each channel in order to capture such complex frequency structure. \\\\\n\nIf the above is predicted for our source then it is perfectly okay to split spw,  given the condition that we have enough snr in the data. \\\\\n\n\n\\tbf{Q. When do you stop self calibration?}\\\\\n\nSo, our target is to achieve a high dynamic range. No matter how many phase cal or AP self cal loops we run, it does not matter if the Dynamic range for the image does not saturate.  When you start ap self after finishing phase only selfcal DR may decrease because your amplitudes are not calibrated well. But after few round it should increase. If you see it is continuously decreasing, then you may have picked up wrong emissions in your model. Here same thing is happening, after round 6 it is again increasing. And always check the DR, not the peak flux or rms separately\\\\\n\n\\tbf{Q. How do we decide solint of any calibration task?}\\\\\n\nThe solint is completely based on the fact that, the solution  required during  a calibration should be of time scale smaller than the effect for which calibration corrections are made so as to capture changes in the calibrator. If we say we need delay calibration at solint=60s, it means something is changing in the order of a minutes and we wish to capture that change. And only ionospheric delays can be captured in minutes.\n\n\\tbf{Q. \tHow do we decide the starting threshold?}\\\\\n\nOk, I get your point. Yes, if at that threshold any noise peak is picked up, then that will happen. But if no noise peak is picked up, then low threshold means you are making your model more accurately. So, my suggestion is always put the threshold based on rms of the dirty image. Suppose you have 0.1 mJy rms of dirty image, you can choose 10 sigma threshold of 1 mJy, then you should not pickup any noise. So, use at least 5-6 sigma of the rms of present round image\n\n\n\\chapter{Statistics}\n\\tbf{Q. What is the difference between RMS of a data set and the standard deviation of the data set?}\\\\\n\nAns. Standard deviation is the RMS error of the data set and for a set of equally propable $x_i$'s is represented by\n\\begin{equation}\n\\sigma=\\sqrt{\\frac{1}{N}\\sum_{i=1}^N(x_i-\\bar{x})^2}\n\\end{equation}\nwhere $\\bar{x}$ is the mean of  $x_i$'s.\\\\\n\nWhere as for the same data set rms is given by\n\\begin{equation}\nx_{rms}=\\sqrt{\\frac{1}{N}\\sum_{i=1}^N(x_i)^2}\n\\end{equation}\n\nSo basically, standard deviation is equal to rms of the data set when the mean is zero.\n\n\\end{document}\n", "meta": {"hexsha": "307b614cffe98d43ec39c270d04139da299a34de", "size": 135222, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Project_notes/notes.tex", "max_stars_repo_name": "diveshjain-phy/zombie_galaxies", "max_stars_repo_head_hexsha": "0b4db1767a1baac5e2af92c3f6cf89f83a0be4c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Project_notes/notes.tex", "max_issues_repo_name": "diveshjain-phy/zombie_galaxies", "max_issues_repo_head_hexsha": "0b4db1767a1baac5e2af92c3f6cf89f83a0be4c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Project_notes/notes.tex", "max_forks_repo_name": "diveshjain-phy/zombie_galaxies", "max_forks_repo_head_hexsha": "0b4db1767a1baac5e2af92c3f6cf89f83a0be4c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 74.2978021978, "max_line_length": 1340, "alphanum_fraction": 0.7532206298, "num_tokens": 38510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.33152203337193037}}
{"text": "\\documentclass[12pt]{article}\n\\usepackage{fontspec}\n\\usepackage{fullpage}\n\\usepackage{hyperref}\n\\hypersetup{bookmarks=true,colorlinks=true,linkcolor=red,citecolor=blue,filecolor=magenta,urlcolor=cyan}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{mathtools}\n\\usepackage{unicode-math}\n\\usepackage{tabu}\n\\usepackage{longtable}\n\\usepackage{booktabs}\n\\usepackage{caption}\n\\usepackage{enumitem}\n\\setmathfont{Latin Modern Math}\n\\newcommand{\\gt}{\\ensuremath >}\n\\newcommand{\\lt}{\\ensuremath <}\n\\global\\tabulinesep=1mm\n\\newlist{symbDescription}{description}{1}\n\\setlist[symbDescription]{noitemsep, topsep=0pt, parsep=0pt, partopsep=0pt}\n\\title{Software Requirements Specification for HGHC}\n\\author{W. Spencer Smith}\n\\begin{document}\n\\maketitle\n\\tableofcontents\n\\newpage\n\\section{Reference Material}\n\\label{Sec:RefMat}\nThis section records information for easy reference.\n\n\\subsection{Table of Units}\n\\label{Sec:ToU}\nThe unit system used throughout is SI (Système International d'Unités). In addition to the basic units, several derived units are also used. For each unit, \\hyperref[Table:ToU]{Tab: ToU} lists the symbol, a description and the SI name.\n\n\\begin{longtable}{l l l}\n\\toprule\n\\textbf{Symbol} & \\textbf{Description} & \\textbf{SI Name}\n\\\\\n\\midrule\n\\endhead\n${{}^{\\circ}\\text{C}}$ & temperature & centigrade\n\\\\\n${\\text{m}}$ & length & metre\n\\\\\n${\\text{W}}$ & power & watt\n\\\\\n\\bottomrule\n\\caption{Table of Units}\n\\label{Table:ToU}\n\\end{longtable}\n\\subsection{Table of Symbols}\n\\label{Sec:ToS}\nThe symbols used in this document are summarized in \\hyperref[Table:ToS]{Tab: ToS} along with their units. The choice of symbols was made to be consistent with the nuclear physics literature and with that used in the FP manual.\n\n\\begin{longtabu}{l X[l] l}\n\\toprule\n\\textbf{Symbol} & \\textbf{Description} & \\textbf{Units}\n\\\\\n\\midrule\n\\endhead\n${h_{\\text{b}}}$ & Initial coolant film conductance & --\n\\\\\n${h_{\\text{c}}}$ & Convective heat transfer coefficient between clad and coolant & $\\frac{\\text{W}}{\\text{m}^{2}{}^{\\circ}\\text{C}}$\n\\\\\n${h_{\\text{g}}}$ & Effective heat transfer coefficient between clad and fuel surface & $\\frac{\\text{W}}{\\text{m}^{2}{}^{\\circ}\\text{C}}$\n\\\\\n${h_{\\text{p}}}$ & Initial gap film conductance & --\n\\\\\n${k_{\\text{c}}}$ & Clad conductivity & --\n\\\\\n${τ_{\\text{c}}}$ & Clad thickness & --\n\\\\\n\\bottomrule\n\\caption{Table of Symbols}\n\\label{Table:ToS}\n\\end{longtabu}\n\\section{Specific System Description}\n\\label{Sec:SpecSystDesc}\nThis section first presents the problem description, which gives a high-level view of the problem to be solved. This is followed by the solution characteristics specification, which presents the assumptions, theories, and definitions that are used.\n\n\\subsection{Solution Characteristics Specification}\n\\label{Sec:SolCharSpec}\nThe instance models that govern HGHC are presented in \\hyperref[Sec:IMs]{Section: Instance Models}. The information to understand the meaning of the instance models and their derivation is also presented, so that the instance models can be verified.\n\n\\subsubsection{Data Definitions}\n\\label{Sec:DDs}\nThis section collects and defines all the data needed to build the instance models.\n\n\\vspace{\\baselineskip}\n\\noindent\n\\begin{minipage}{\\textwidth}\n\\begin{tabular}{>{\\raggedright}p{0.13\\textwidth}>{\\raggedright\\arraybackslash}p{0.82\\textwidth}}\n\\toprule \\textbf{Refname} & \\textbf{DD:htTransCladFuel}\n\\phantomsection \n\\label{DD:htTransCladFuel}\n\\\\ \\midrule \\\\\nLabel & Effective heat transfer coefficient between clad and fuel surface\n        \n\\\\ \\midrule \\\\\nSymbol & ${h_{\\text{g}}}$\n         \n\\\\ \\midrule \\\\\nUnits & $\\frac{\\text{W}}{\\text{m}^{2}{}^{\\circ}\\text{C}}$\n        \n\\\\ \\midrule \\\\\nEquation & \\begin{displaymath}\n           {h_{\\text{g}}}=\\frac{2 {k_{\\text{c}}} {h_{\\text{p}}}}{2 {k_{\\text{c}}}+{τ_{\\text{c}}} {h_{\\text{p}}}}\n           \\end{displaymath}\n\\\\ \\midrule \\\\\nDescription & \\begin{symbDescription}\n              \\item{${h_{\\text{g}}}$ is the effective heat transfer coefficient between clad and fuel surface ($\\frac{\\text{W}}{\\text{m}^{2}{}^{\\circ}\\text{C}}$)}\n              \\item{${k_{\\text{c}}}$ is the clad conductivity (Unitless)}\n              \\item{${h_{\\text{p}}}$ is the initial gap film conductance (Unitless)}\n              \\item{${τ_{\\text{c}}}$ is the clad thickness (Unitless)}\n              \\end{symbDescription}\n\\\\ \\bottomrule\n\\end{tabular}\n\\end{minipage}\n\\vspace{\\baselineskip}\n\\noindent\n\\begin{minipage}{\\textwidth}\n\\begin{tabular}{>{\\raggedright}p{0.13\\textwidth}>{\\raggedright\\arraybackslash}p{0.82\\textwidth}}\n\\toprule \\textbf{Refname} & \\textbf{DD:htTransCladCool}\n\\phantomsection \n\\label{DD:htTransCladCool}\n\\\\ \\midrule \\\\\nLabel & Convective heat transfer coefficient between clad and coolant\n        \n\\\\ \\midrule \\\\\nSymbol & ${h_{\\text{c}}}$\n         \n\\\\ \\midrule \\\\\nUnits & $\\frac{\\text{W}}{\\text{m}^{2}{}^{\\circ}\\text{C}}$\n        \n\\\\ \\midrule \\\\\nEquation & \\begin{displaymath}\n           {h_{\\text{c}}}=\\frac{2 {k_{\\text{c}}} {h_{\\text{b}}}}{2 {k_{\\text{c}}}+{τ_{\\text{c}}} {h_{\\text{b}}}}\n           \\end{displaymath}\n\\\\ \\midrule \\\\\nDescription & \\begin{symbDescription}\n              \\item{${h_{\\text{c}}}$ is the convective heat transfer coefficient between clad and coolant ($\\frac{\\text{W}}{\\text{m}^{2}{}^{\\circ}\\text{C}}$)}\n              \\item{${k_{\\text{c}}}$ is the clad conductivity (Unitless)}\n              \\item{${h_{\\text{b}}}$ is the initial coolant film conductance (Unitless)}\n              \\item{${τ_{\\text{c}}}$ is the clad thickness (Unitless)}\n              \\end{symbDescription}\n\\\\ \\bottomrule\n\\end{tabular}\n\\end{minipage}\n\\end{document}\n", "meta": {"hexsha": "ca029d7f75a0c60dac3e94a25dd4f56b8d4ed902", "size": 5585, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "code/stable/hghc/SRS/HGHC_SRS.tex", "max_stars_repo_name": "smiths/Drasil", "max_stars_repo_head_hexsha": "947be0411babe79ff198224d620b97642152710d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/stable/hghc/SRS/HGHC_SRS.tex", "max_issues_repo_name": "smiths/Drasil", "max_issues_repo_head_hexsha": "947be0411babe79ff198224d620b97642152710d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/stable/hghc/SRS/HGHC_SRS.tex", "max_forks_repo_name": "smiths/Drasil", "max_forks_repo_head_hexsha": "947be0411babe79ff198224d620b97642152710d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2333333333, "max_line_length": 249, "alphanum_fraction": 0.6893464637, "num_tokens": 1729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.33152203337193037}}
{"text": "\\documentclass[12pt, letterpaper, preprint, comicneue]{aastex63}\n%\\usepackage[default]{comicneue} % comic sans font for editing\n\\usepackage[T1]{fontenc}\n\\usepackage{fontawesome}\n\\usepackage{color}\n\\usepackage{amsmath}\n\\usepackage{natbib}\n\\usepackage{ctable}\n\\usepackage{bm}\n\\usepackage[normalem]{ulem} \n\\usepackage{xspace}\n\\usepackage{paralist}\n\n\n% typesetting shih\n\\linespread{1.08} % close to 10/13 spacing\n\\setlength{\\parindent}{1.08\\baselineskip} % Bringhurst\n\\setlength{\\parskip}{0ex}\n\\let\\oldbibliography\\thebibliography % killin' me.\n\\renewcommand{\\thebibliography}[1]{%\n  \\oldbibliography{#1}%\n  \\setlength{\\itemsep}{0pt}%\n  \\setlength{\\parsep}{0pt}%\n  \\setlength{\\parskip}{0pt}%\n  \\setlength{\\bibsep}{0ex}\n  \\raggedright\n}\n\\setlength{\\footnotesep}{0ex} % seriously?\n\n% citation alias\n\n% math shih\n\\newcommand{\\setof}[1]{\\left\\{{#1}\\right\\}}\n\\newcommand{\\given}{\\,|\\,}\n\\newcommand{\\lss}{{\\small{LSS}}\\xspace}\n\n\\newcommand{\\Om}{\\Omega_{\\rm m}} \n\\newcommand{\\Ob}{\\Omega_{\\rm b}} \n\\newcommand{\\OL}{\\Omega_\\Lambda}\n\\newcommand{\\smnu}{M_\\nu}\n\\newcommand{\\sig}{\\sigma_8} \n\\newcommand{\\mmin}{M_{\\rm min}}\n\\newcommand{\\BOk}{\\widehat{B}_0} \n\\newcommand{\\hmpc}{\\,h/\\mathrm{Mpc}}\n\\newcommand{\\bfi}[1]{\\textbf{\\textit{#1}}}\n\\newcommand{\\parti}[1]{\\frac{\\partial #1}{\\partial \\theta_i}}\n\\newcommand{\\partj}[1]{\\frac{\\partial #1}{\\partial \\theta_j}}\n\\newcommand{\\mpc}{{\\rm Mpc}}\n\\newcommand{\\eg}{\\emph{e.g.}}\n\\newcommand{\\ie}{\\emph{i.e.}}\n\n\\let\\oldAA\\AA\n\\renewcommand{\\AA}{\\text{\\normalfont\\oldAA}}\n% cmds for this paper \n\\newcommand{\\gr}{g{-}r}\n\\newcommand{\\fnuv}{FUV{-}NUV}\n\\newcommand{\\sfr}{{\\rm SFR}}\n\\newcommand{\\ssfr}{{\\rm SSFR}}\n\\newcommand{\\xobs}{\\bfi{x}_{\\rm obs}}\n\\newcommand{\\btheta}{\\boldsymbol{\\theta}}\n\\newcommand{\\bphi}{\\boldsymbol{\\phi}}\n\\newcommand{\\specialcell}[2][c]{%\n  \\begin{tabular}[#1]{@{}c@{}}#2\\end{tabular}}\n% text shih\n\\newcommand{\\foreign}[1]{\\textsl{#1}}\n\\newcommand{\\etal}{\\foreign{et~al.}}\n\\newcommand{\\opcit}{\\foreign{Op.~cit.}}\n\\newcommand{\\documentname}{\\textsl{Article}}\n\\newcommand{\\equationname}{equation}\n\\newcommand{\\bitem}{\\begin{itemize}}\n\\newcommand{\\eitem}{\\end{itemize}}\n\\newcommand{\\beq}{\\begin{equation}}\n\\newcommand{\\eeq}{\\end{equation}}\n\n\\newcommand{\\github}{\\href{https://github.com/changhoonhahn/SEDflow/}{\\faGithub}}\n\n\n\\newcommand{\\sedflow}{{\\sc SEDflow}}\n%% collaborating\n\\newcommand{\\todo}[1]{\\marginpar{\\color{red}TODO}{\\color{red}#1}}\n\\definecolor{orange}{rgb}{1,0.5,0}\n\\newcommand{\\chedit}[1]{{\\color{orange}#1}}\n\\newcommand{\\peter}[1]{{\\color{red}#1}}\n\n\\begin{document} \\sloppy\\sloppypar\\frenchspacing \n\n\\title{Accelerated Bayesian SED Modeling using Amortized Neural Posterior Estimation}\n\n\\newcounter{affilcounter}\n\\author[0000-0003-1197-0902]{ChangHoon Hahn}\n\\altaffiliation{changhoon.hahn@princeton.edu.com}\n\\affil{Department of Astrophysical Sciences, Princeton University, Princeton NJ 08544, USA} \n\n\\author[0000-0002-8873-5065]{Peter Melchior}\n\\affil{Department of Astrophysical Sciences, Princeton University, Princeton NJ 08544, USA} \n\\affil{Center for Statistics and Machine Learning, Princeton University, \nPrinceton, NJ 08544, USA}\n\n\\begin{abstract}\n    State-of-the-art spectral energy distribution (SED) analyses use a\n    Bayesian framework to infer the physical properties of galaxies from\n    observed photometry or spectra.\n    They require sampling from a high-dimensional space of SED model parameters\n    and take $>10-100$ CPU hours per galaxy, which renders them practically\n    infeasible for analyzing the {\\em billions} of galaxies that will be\n    observed by upcoming galaxy surveys (\\eg~DESI, PFS, Rubin, Webb, and Roman).\n    In this work, we present an alternative scalable approach to \n    rigorous Bayesian inference using Amortized Neural Posterior\n    Estimation (ANPE). \n    ANPE is a simulation-based inference method that employs neural networks\n    to estimate the posterior probability distribution over the full\n    range of observations.\n    Once trained, it requires no additional model evaluations to estimate the\n    posterior.  \n    We present, and publicly release, \\sedflow, an ANPE method to produce\n    posteriors of the recent \\cite{hahn2022} SED model from optical\n    photometry.\n    \\sedflow~takes \\emph{${\\sim}1$ second per galaxy} to obtain the posterior\n    distributions of 12 model parameters, all of which are in excellent\n    agreement with traditional Markov Chain Monte Carlo sampling results.\n    We also apply \\sedflow~to 33,884 galaxies in the NASA-Sloan Atlas and\n    publicly release their posteriors.\n    \\github\n\\end{abstract}\n\\keywords{galaxies: evolution -- galaxies: statistics}\n\n\\input{intro}\n\\input{sbi}\n\\pagebreak\n\\input{sedflow}\n\\input{obs}\n\\input{results}\n\\input{discuss}\n\\input{summary}\n\n\\section*{Acknowledgements}\nIt's a pleasure to thank \n    Adam Carnall, \n    Miles Cranmer, \n    Kartheik Iyer,\n    Andy Goulding,\n    Jenny E. Green,\n    Jiaxuan Li, \n    Uro{\\u s}~Seljak,\n    and \n    Michael A. Strauss\nfor valuable discussions and comments.\nThis work was supported by the AI Accelerator program of the Schmidt Futures Foundation.\n\n\\appendix\n\\input{fail}\n%\\bibliographystyle{mnras}\n\\bibliography{sedflow} \n\\end{document}\n", "meta": {"hexsha": "88937f24b8ce4e18d68cd86dd9a24ab14bb54ec5", "size": 5159, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/paper/main.tex", "max_stars_repo_name": "changhoonhahn/SEDflow", "max_stars_repo_head_hexsha": "4561ecfe3a38cc4c25df263d971a87e8a83f88ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2022-03-16T03:11:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T16:01:42.000Z", "max_issues_repo_path": "docs/paper/main.tex", "max_issues_repo_name": "changhoonhahn/SEDflow", "max_issues_repo_head_hexsha": "4561ecfe3a38cc4c25df263d971a87e8a83f88ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/paper/main.tex", "max_forks_repo_name": "changhoonhahn/SEDflow", "max_forks_repo_head_hexsha": "4561ecfe3a38cc4c25df263d971a87e8a83f88ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2838709677, "max_line_length": 92, "alphanum_fraction": 0.7305679395, "num_tokens": 1630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878414043814, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.3315220257659689}}
{"text": "\\subsection{The XGBoost Tuner}\n\nIn TVM framework, \\cite{Tianqi2018} proposed a configuration tuning method for operator-level optimization in which the search is guided by a performance prediction model trained with eXtreme Gradient Boosting (XGBoost). This XGBoost guided tuner (or XGBoost tuner) follows an iterative search process. In each iteration, a large number of configuration candidates are derived from configuration space by random walk. According to the predicted performance from a trained XGBoost model, the best candidates are selected and tested on hardware. The performance feedback from the hardware is collected and applied to further train the XGBoost model so as to improve its prediction accuracy.\n\nThe XGBoost tuner outperforms the other classic tuners including genetic algorithm search, random search, etc., for GEMM. Nevertheless, training the XGBoost model for a large configuration space would incur a high cost. In order to further improve the operator-level configuration tuning performance, we propose a new configuration search model which allows exploitation of relations between similar configurations, followed by two efficient tuning methods.\n\n\n\\subsection{Configuration Search Modeling}\n\nFor better analysis, we model the configuration tuning problem as a Markov Decision Process (MDP), where each configuration can be regarded as a unique state. We define the state as follows.\n\n\\begin{equation}\n    s = \\left[ s_m, s_k, s_n, J \\right],\n\\end{equation}\nwhere $s_m = \\left[ m_0, m_1, \\ldots, m_{d_m-1} \\right] \\in \\xi_m$, $s_k = \\left[ k_0, k_1, \\ldots, k_{d_k-1} \\right] \\in \\xi_k$, $s_n = \\left[ n_0, n_1, \\ldots, n_{d_n-1} \\right] \\in \\xi_n$, and $J$ is the binary number indicating whether the state is legitimate (e.g. the product of $m_i$'s must be $m$, the numbers must be integers, etc.).\n\nAs in the GEMM application, with similar configuration settings, i.e., the configuration parameters for each dimension of two states are equal or close, the performance of this two states may not exists large difference. Taking advantage of the relations among similar configurations, and considering the constraints of the matrices size in each configuration. We define the concept of action space as follows.\n\n\\begin{equation}\n    \\mathcal{A} = \\left[ \\begin{array}{l}\n         {s_x[i] = 2s_x[i] ~~\\text{and}~~ s_x[j]=s_x[j]/2 }, \\\\ \\\\\n         {\\text{where}~ \\forall x \\in \\{m,k,n\\}, \\forall i, j \\in [0, d_x)~\\text{and}~ i \\neq j }\n    \\end{array}\n     \\right].\n\\end{equation}\nAccordingly, we define a step function $step$, i.e.,\n\\begin{equation}\\label{fun:stepfun}\n    s'= step(s,a).\n\\end{equation}\nWith the input of any action $a \\in \\mathcal{A}$, the current state $s$ is transferred to state $s'$. We define $s$ and $s'$ are neighbor states. Based on the setting of action space, we guarantee the Euclidean distance between the neighbor state $s$ and $s'$ is the minimum value compared with the distance between the state $s$ and all the other states.\n\nMoreover, in order to better evaluate the performance of each action based on different states, if the agent takes action $a$ and goes from the state $s$ to the state $s'$, we define the rewards as follows\n\\begin{equation}\n    r(s,a) = \\frac{1}{T_{cost}(s'; m,k,n,d_m,d_k,d_n) }.\n\\end{equation}\n\nFollowing the above modeling, the agent is expected to determine its policy $\\boldsymbol{\\pi}$ so as to efficiently approach and discover the state $s^*$ with the lowest running time in hardware system. In the following subsections, we will analyze two different configuration tuning approaches guided by G-BFS and N-A2C reinforcement learning, followed by a discussion for their strengths with different scenarios.\n\n\n\n\\subsection{G-BFS Method}\n\n\\begin{figure*}\n\\centering\n\\includegraphics[scale=0.4]{4_Method/gbfs_pic.jpg}\n\\caption{G-BFS Method}\n\\label{fig:gbfs}\n\\end{figure*}\n\nThe G-BFS method is guided by Greedy Best-First-Search and follows the flowchart in Fig. \\ref{fig:gbfs}(a). We initialize an empty priority queue $\\mathcal{Q}$ (ordered by increasing cost), an empty list $S_v$ to record all visited configuration candidates, and a random or hand-crafted starting state $s_0$. We first test and enque the starting state $s_0$ and record its running time $T_{cost}(s_0)$ into the priority queue $Q$. Based on the configuration search model, for each iteration, we deque the top configuration candidate $s$ from the priority queue $Q$. We iterate through all actions $a\\in \\mathcal{A}$ and collect all corresponding neighbor states as\n\\begin{equation}\n    g(s) = [s'=step(s,a) ~~ \\forall a \\in \\mathcal{A}].\n\\end{equation}\nWe randomly select $\\rho$ ($\\rho \\in \\{1,2,\\ldots,len(g(s)) \\}$) configuration candidates from $g(s)$, and test them in hardware. For each state $s'$ sampled from $g(s)$, if state $s'$ is legitimate and has not been visited before, we enque state $s'$ and its tested running time $T_{cost}(s')$ into $Q$ and add state $s'$ in the visited list $S_v$. If its tested running time $T_{cost}(s')$ is smaller than the current minimum running time, we set state $s'$ as the optimal state visited and record its running time as $t_{cost}^{min}$. The iteration continues until the priority queue is empty or the computation time reaches the maximum time specified by the user. The current stored optimal state $s*$ and its running time $t_{cost}^{min}$ are returned as tuning results. The summary of the algorithm is shown in Algorithm \\ref{alg:gbfs}.\n\nIn Fig. \\ref{fig:gbfs}(b), we show the exploration situation in the middle of the tuning algorithm when $\\rho = len(g(s))$, where the red nodes denote the state currently stored in the priority queue and the grey nodes are all the visited states. In future iterations, the method will explore from the current most promising red nodes expands its visited state areas. In Fig. \\ref{fig:gbfs}(c), we take an example of 2-dimensional configuration search on the randomly generated rewards function. We discover that the proposed G-BFS method is able to correct itself from exploring wrong directions and efficiently expand its neighborhood to the optimal states. Moreover, when the value of $\\rho = len(g(s))$, given unlimited tuning time, the algorithm is guaranteed to visit all the configuration states.\n\n\\begin{algorithm}[htb]\n\\caption{G-BFS Method}\n\\label{alg:gbfs}\n\\vspace{.1cm}\n\\hrule\n    \\begin{algorithmic}[1]\n    \\vspace{.2cm}\n    \\STATE Initialization: $\\mathcal{Q}$=PriorityQueue(), $S_v$, $s_0$\n    \\STATE Q.push($(T_{cost}(s_0), s_0)$);\\\\\n    \\STATE Add $s_0$ in $S_v$;\\\\\n    \\WHILE{$Q\\neq \\O$ and $t<T^{max}$}\n        \\STATE $(T_{cost}(s), s)$ = Q.pop(); \\\\\n        \\STATE $\\mathcal{B}_{test}$ = Sample $\\rho$ randomly from $g(s)$; \\\\\n        \\FOR{$s'$ in sampled configuration candidates}\n            \\IF{$s'[-1]=True$ and $s' \\not\\in S_v$}\n                \\STATE Q.push($(T_{cost}(s'), s')$); \\\\\n                \\STATE Add $s'$ in $S_v$;\\\\\n                \\IF{$t_{cost}^{min} > T_{cost}(s')$}\n                    \\STATE $t_{cost}^{min} = T_{cost}(s')$; \\\\\n                    \\STATE $s^* = s'$;\n                \\ENDIF\n            \\ENDIF\n        \\ENDFOR\n    \\ENDWHILE\n    \\STATE Return: The optimal configuration $s^*$ with cost $t_{cost}^{min}$.\n    \\end{algorithmic}\n\\hrule\n\\end{algorithm}\n\n\n\n\n\n\n\\subsection{N-A2C Method}\n\n\n\n\n\n\n\\begin{algorithm}[htb]\n\\caption{N-A2C Method}\n\\label{alg:r_a2c}\n\\vspace{.01cm}\n\\hrule\n    \\begin{algorithmic}[1]\n    \\vspace{.2cm}\n    \\STATE Initialization: {$s_0$, $\\mathcal{M}$, $H_v$}\n    \\FOR{each episode}\n        \\WHILE{$len(\\mathcal{B}_{collect})< len(\\mathcal{B}_{test})$ }\n            \\STATE$s = s_0$; \\\\\n            \\FOR{each step until $T$ steps}\n                \\IF{$rand()<\\tau$}\n                    \\STATE $a$ follows $\\pi(s)$;\n                \\ELSE\n                    \\STATE $a$ is random selected from $\\mathcal{A}$;\n                \\ENDIF\n                \\STATE $s'=step(s,a)$; \\\\\n                \\IF {$s'$ not in $H_v$}\n                    \\STATE Add $s'$ in $\\mathcal{B}_{collect}$;\n                \\ENDIF\n                \\STATE $s = s'$;\n            \\ENDFOR\n        \\ENDWHILE\n        \\FOR{$s'$ in $\\mathcal{B}_{collect}$}   % Can be done in parallel computing\n            \\IF{$t_{cost}^{min} > T_{cost}(s')$}\n                \\STATE $t_{cost}^{min} = T_{cost}(s')$; \\\\\n                \\STATE $s^* = s'$; \\\\\n                \\STATE $s_0=s^*$; \\\\\n            \\ENDIF\n            \\STATE $H_v[s'] = T_{cost}(s')$; \\\\\n            \\STATE Store $(s, a, r(s,a), s')$ to $\\mathcal{M}$, where $\\forall s$, $\\forall a$ satisfying $step(s,a) = s'$; \\\\\n            \\STATE Train actor's and critic's neural networks with $\\mathcal{M}$;\n        \\ENDFOR\n    \\ENDFOR\n    \\STATE Return: The optimal configuration $s^*$ with cost $t_{cost}^{min}$.\n    \\end{algorithmic}\n    \\hrule\n\\end{algorithm}\n\nAs the G-BFS method explores only one step from the considered state for each iteration, its performance may be affected when the running time from similar states exhibits large random noise. In the N-A2C method, as shown in Fig. \\ref{fig:r_a2c}(a), for each episode, we let the exploration being generated in a $\\varsigma$-step neighborhood, and the direction of exploration is guided with A2C reinforcement learning method \\cite{bhatnagar2009natural}. The center of the exploration neighborhood is periodically updated with the optimal states ever visited.\n\n\nWe summarize the tuning method in Algorithm~\\ref{alg:r_a2c}. Initially, we set a random or experience-estimated starting state $s_0$, a fixed-size memory buffer $\\mathcal{M}$ to record the latest searching information and an empty hashtable $H_v$ recording all the visited states with their running time. For the A2C reinforcement learning model, both actor and critic firstly establish their neural networks with random weights, respectively. Following the configuration search model, for each episode, while the collected configuration candidates for testing is less than the predefined tested batch size, iteratively, from the same starting point, the agent explore $\\mathcal{T}$ continuous steps. For each step, with probability of $\\tau$, the agent take action $a$ guided by the policy $\\pi(s)$ from the actor's nerual network; With probability of $1-\\tau$, the agent choose a random action $a$ from current state. Based on the current state $s$ and action $a$, we get the next state $s'$ from (\\ref{fun:stepfun}). If the next state $s'$ has not been visited before, we add the state $s'$ in collected candidate batch $\\mathcal{B}_{collect}$.\n\n\n\n\nWhen the number of collected candidates $\\mathcal{B}_{collect}$ achieve the predefined test size, we let the system run the collected configuration candidates. Based on the corresponding running time, the stored hashmap $H_v$ and memory buffer $\\mathcal{M}$ is updated. Based on updated $\\mathcal{M}$, by randomly selecting history exploration data, the neural networks of A2C reinforcement learning is trained.\n\n\n\nGenerally, the proposed N-A2C method is able to efficiently search the optimal GEMM configuration with fixed exploration step in each episode. Nevertheless, in order to find the most important exploration neighborhood, the exploration step $\\mathcal{T}$ can have a soft start, which means starting with a large value and gradually reduce to a small number. Moreover, in order to fully explore the configuration space, after a long time exploration within the same starting points, the exploration step $\\mathcal{T}$ will gradually increase to further explore new configuration candidates.\n\nIn Fig. \\ref{fig:r_a2c}(b), we show a simple exploration map with the proposed N-A2C method. With more explorations, the exploration neighborhood changes with the update of optimal states ever visited. In Fig. \\ref{fig:r_a2c}(c), we take an example of 2-dimensional configuration on the randomly generated rewards function. Due to the large randomness in the example, we set the exploration step $\\mathcal{T}$ as 100 and the global optimal state can be efficiently discovered with the assistance of the A2C reinforcement learning algorithm.\n\n\\begin{figure*}\n\\centering\n\\includegraphics[scale=0.4]{4_Method/n_a2c_pic.jpg}\n\\caption{N-A2C Method}\n\\label{fig:r_a2c}\n\\end{figure*}\n\n\n\\subsection{Discussion}\nWe compare the G-BFS guided tuning method, N-A2C reinforcement learning method and the XGBoost guided tuning method in Table \\ref{tab:compare}.\n\n\\begin{table}[h!]\n    \\small\n    \\begin{center}\n        \\caption{Comparison of Configuration Search Methods}\n        \\label{tab:compare}\n        \\begin{tabular}{l|c|c|c}\n            Methods & XGBoost  & G-BFS & N-A2C \\\\\n            \\hline\n %           Explore neighbor conf. & No & Yes  & Yes  \\\\\n            Adapt to large space & No & Yes & Yes \\\\\n            Adapt to fluctuations & Weak & Weak & Strong \\\\\n %           Random Exploration & Exist & Depend & Exist \\\\\n            Lightweight & No & Yes & Yes \\\\\n            Hyper-parameters & Yes & only 1 & Yes \\\\\n            Trapped in Local Optima & No & No & No\n        \\end{tabular}\n    \\end{center}\n\\end{table}\n\nSince our proposed configuration search model is based on neighborhood information which is the ground for both our tuners, exploration by G-BFS and N-A2C methods are more confined in neighborhoods of current candidates and increasing the size of the configuration space does not have a large impact as it does on the XGBoost method, as the XGBoost method considers the overall configuration space.  Furthermore, when the performance feedback of neighboring configurations has large fluctuations, XGBoost and G-BFS may not be able to efficiently discover the global optimal solution, while the N-A2C method can explore multiple steps from the neighborhood, so as to locate the optimal configuration more efficiently. Moreover, random exploration exists within both XGBoost and N-A2C tuning methods, but in G-BFS, when the value of $\\rho = len(g(s))$, there will be no randomness during the configuration search. Compared with other configuration optimization methods, G-BFS is more lightweight and only requires the hyper-parameter setting of $\\rho$. Finally, all three methods are able to jump out of  local optima to get to global optimal solutions.\n\n", "meta": {"hexsha": "2a1cae0027c6e32c67c9655098c568c0e08cb54d", "size": 14196, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "4_Method/method.tex", "max_stars_repo_name": "markjunior/icml2019_gemm", "max_stars_repo_head_hexsha": "67cf41f02fba4f8d638e47ab6407a7579f757679", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "4_Method/method.tex", "max_issues_repo_name": "markjunior/icml2019_gemm", "max_issues_repo_head_hexsha": "67cf41f02fba4f8d638e47ab6407a7579f757679", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4_Method/method.tex", "max_forks_repo_name": "markjunior/icml2019_gemm", "max_forks_repo_head_hexsha": "67cf41f02fba4f8d638e47ab6407a7579f757679", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 75.9144385027, "max_line_length": 1151, "alphanum_fraction": 0.708086785, "num_tokens": 3597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982315512489, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.33148911158276784}}
{"text": "%!TEX root = ../gronskiy_phd_thesis.tex \n\\chapter[Approximation-Based Regularization for Robust Optimization]{Approximation-Based Regularization \\\\ for Robust Optimization}\n\\label{ch:gen_appch}\n\n\\hfill\n\\begin{minipage}[t]{.75\\textwidth}\n\\textit{``Truth is much too complicated to allow anything but approximations.''} \\\\\n  \\hrule\n  \\vspace{.2cm}\n  \\hfill\n  \\textsc{--- John von NEUMANN}, ``The Mathematician''\n\\end{minipage}\n\n\\section{Introduction}\n\n\\subsection{Motivation}\n\nWithin a given data set, not all information is useful~--- given measurement\nerror, some part of it explains noise, not the true functional dependencies.\nHence, there exists an inevitable limitation on the amount of information bits\none should use in order to avoid overfitting. However, another curse~---\nunderfitting~--- happens if for some reason the solver decides to play on the\nsafe side and uses less information than would be optimal. We refer to this\nphenomenon as the \\textit{informativeness vs. robustness trade-off}.\n\\index{Underfitting}\n\nIn the line of research started\nby~\\citet{conf/isit/Buhmann10,conf/mcpr2/Buhmann11}, an approach of utilizing\nself-calibrating\\footnote{Sometimes ``self-calibrating'' is replaced by\n``context-sensitive''.} optimization procedures is devised and advocated. In its\nessential part, this approach aims at maximizing (through a set of tools\ndiscussed below) the amount of useful information, thereby making \nsolutions both statistically robust \\textit{and} informative.\n\nThis approach features~\\citep[cf.][]{Busetto:PhD,jcss:2017}, among others, the following key\nproperties: \n\\begin{itemize}\n  \\item it does not require any knowledge on\n    probability distributions of input instances, particularly not whether the\n    noise is systematic or random;\n  \\item it allows to quantify the quality of the obtained solution w.r.t.~ \n    unseen data instances;\n  \\item moreover, it makes possible to rank different models.\n\\end{itemize}\n\nIn this chapter, we will provide justification of this approach, as well as\nintroduce some prototypic examples proving its usability. We will also discuss\npossible generalizations and adjustments of this approach, which will be\naddressed in the next chapters.\n\n\\subsection{Contributions and Outline of the Chapter}\n\\label{sec:asc_contribs}\n\nAs main contributions of this chapter, we\n\\begin{itemize}\n  \\item provide a justification and revisit the approach for robust optimization\n    called Approximation Set Coding;\\index{ASC|see{Approximation Set Coding}} \\index{Approximation Set Coding}\n  \\item introduce and evaluate the simplest, yet interpretable proof-of-concept\n    model which shows experimentally the superiority of the ASC-based approach\n    and refers to clear intuitions about the mechanism thereof;\n  \\item prove a theoretical result which suggests one step further in the direction\n    of eliminating the computational bottleneck of the ASC~--- computing the ASC\n    score;\n  \\item introduce a so-called Gibbs relaxation of the ASC approach, give \n    a rationale behind it and experimentally evaluate its performance.\n\\end{itemize}\n\nThe chapter is outlined as follows. First, a background and related work are\ngiven in Section~\\ref{sec:gen_appch_related_work}. We then provide technical\npreliminaries (setting and model assumptions) in\nSection~\\ref{sec:gen_appch_setting_and_model}. A comprehensive introduction into\nthe original approximation set-based approach is then given in\nSection~\\ref{sec:asc_original}. Section~\\ref{sec:similarity_approach_intro}\npresents an analogical approach to robust optimization. We then give a\nproof-of-concept experimental confirmation of the validity of approximation\nset-based methods in Section~\\ref{sec:proof_of_concept}. Further, we address one\nproblem which is very characteristic bottleneck for the most of applications of\napproximation set-based approaches and solve it in\nSection~\\ref{sec:analytic_solution}. We then explain how a relaxation of the\napproach (called Gibbs relaxation) works in Section~\\ref{sec:gibbs_relaxation_of_sim}\nand show experimental results for it. Finally, concluding remarks follow\nin~Section~\\ref{sec:gen_appch_conclusion}.\n\n\\myremark Section~\\ref{sec:similarity_approach_intro} is included into the\nthesis for the sake of ``self-containedness'', and presents an approach not due\nto the author of this thesis. For smooth integration into this thesis, we\nprovided necessary terminological and notational adaptation, but\nnevertheless, some small parts of the text of\nSection~\\ref{sec:similarity_approach_intro}, as well as\nSection~\\ref{sec:gen_appch_conclusion} may still be similar to that\nof~\\citet{Sramek:PhD}. Sections~\\ref{sec:proof_of_concept},~\\ref{sec:analytic_solution}\nand~\\ref{sec:gibbs_relaxation_of_sim} are a result of joint work hence their\ntextual presentation may be partially similar to that of~\\citet{jcss:2017}.\n\n\\section{Background and Related Work Overview}\n\\label{sec:gen_appch_related_work}\n\nWhen dealing with uncertain (noisy) inputs, the model designer always confronts\nwith two related questions:\n\\begin{itemize}\n  \\item For a given model, how to provide a well-generalizing regularization?\n  \\item For a predefined set of models, how to establish an ordering of them which\n  would reflect their generalization capability?\n\\end{itemize}\n\nWhile we introduce an approach which solves both tasks, in this chapter we will\nmainly concentrate on the first application of it, while the next chapter\n(Chapter~\\ref{ch:mst}) addresses the second one. For now, however, we summarize\nan overview of both tasks.\n\n\\subsection{Generalization and Stability in Learning}\n\\label{sec:generalization_stability_in_learning}\nWhen dealing with noisy inputs, a designer of an empirical risk minimization\n(ERM) algorithm is always confronting with how well the learned solution\ngeneralizes to the unknown test sets. In fact, the whole field of statistical\nlearning theory~\\citep{Vapnik71,Vapnik:1982} \\index{Statistical\nlearning theory} has been in its core posing this\nquestions since 70s of the last century. It focuses on the question: for a given\nalgorithm, can we derive bounds of its generalization error~\\citep{Bishop:2006}?\n\\index{ERM|see{Empirical Risk Minimization}} \n\\index{Empirical Risk Minimization} \n\nThe ways of bounding generalization error \\index{Generalization error} can be, in our view, split into\nthree\\footnote{These classes are very much interrelated. We brought such\nclassification for simplicity and don't pretend it to be the only division\npossible.} classes: to a more classical one belongs, e.g.~bounding\ngeneralization error via considering properties of \\textit{hypothesis space}\nsuch as VC-dimension~\\citep{Vapnik71,Vapnik:1982} or Rademacher\ncomplexity~\\citep{Shalev-Shwartz:2014}.\n\nAnother class of research directions encompasses approaches where one derives\nsuch bounds using the so-called (hypothesis, error or uniform)\nstability~\\citep{Devroye79,Bousquet:2002} property of the ERM algorithm, which,\nin essence, reflects how critical are the fluctuations of the input data for the\noutcome of an algorithm. As a side remark, we can note that from the technical\nstandpoint, the mentioned bounds utilized various concentration\ninequalities~\\citep{RaginskyS15}. \n\nLastly, stability \\index{Stability} (and thus generalization) properties have recently enjoyed\nresearch from the information theoretic prospective, considering a learning\nalgorithm as a channel from the input to output~\\citep{Russo15,Xu17} and\nrelating stability to the mutual information between the input and the output.\nTo the advantages of this third class of approaches belongs the fact, that the\nbounds provided by it, involve \\textit{both} the properties of the hypothesis\nspace and the learning algorithm (as opposed to the aforementioned methods). To\nthe same ``information theory-inspired'' class can we assign a recent work\nby~\\citet{Alabdulmohsin:2015} which relates generalization to a total variation\n\\index{Total variation information} information.\n\n\\myremark The approach via input-output mutual information comes very close to\nthe one introduced and advocated in this chapter. However, we should note that\nboth approaches stem from different definitions of the communication channel\nused to derive error bounds.\n\n\\myremark It should be noted here that all the above methods only provide ways \nto guarantee certain performance when the learning algorithm is fixed. They do\nnot answer the question how to regularize its solutions for a more robust\nperformance. In contrast, the approach presented and tested in this chapter does\nexactly this.\n\n\\subsection{Model Selection}\nBesides quantifying the quality of a given ERM solution (overview for which was\ngiven above), a modeler can ask another question: how to choose between two\npossible models, taking into account various properties such as e.g.~complexity?\nA long line research which addressed this question is presented by methods such\nas the Minimum Description Length (MDL) principle~\\citep{Rissanen:1978}, the\nAkaike Information Criterion (AIC), the Bayesian Information Criterion (BIC) or\nthe Generalized Information Criterion~\\citep[for an overview,\nsee][]{Konishi:2007}.\n\\index{Model validation}\n\\index{Model validation!MDL}\n\\index{Model validation!AIC}\n\\index{Model validation!BIC}\n\\index{AIC|see{Model validation}}\n\\index{BIC|see{Model validation}}\n\\index{MDL|see{Model validation}}\n\n\\subsection{Robust Optimization}\n\nBesides the approaches characteristic for statistical learning theory, there\nexists a methodological direction called \\textit{robust optimization}.\n\\index{Robust optimization}\n%\nBeing very close to the approaches above, robust optimization deals with models\nfor the uncertain input~--- however, contrary to the approaches traditional for\nstatistical learning theory, in the field of robust optimization, it is\nexplicitly discouraged to assume the knowledge of the input data distribution,\nalthough some information (for example, if the data comes form certain interval\ndomain or not) might be available.\n%\nFor a comprehensive overview of robust optimization approaches, we recommend a\nrecent survey by~\\citet{series/lncs/GoerigkS16}.\n\nThe closest point of contact between the robust optimization approaches and\napproaches of the above Section~\\ref{sec:generalization_stability_in_learning}\nis, in out view, \\textit{optimization for stable inputs} which makes an attempt\nto understand the connection between fluctuations of the input and the output,\ni.e. some sort of stability~\\citep{journals/cpc/BiluL12,%\nconf/sirocco/BiloGGPW09,journals/scheduling/GattoW11,conf/sofsem/MihalakSSW11}.\n\n\n\n% \\section{Related Work}\n% \\label{sec:gen_appch_related_work}\n% ­Noisy inputs received attention in a variety of ways. \\emph{Stochatic\n% programming}~\\cite{Schneider07,KallM05} utilizes random variables to model\n% uncertainty in the input data. When the random variables are used only in the\n% optimization method and not in modelling the problem, one commonly refers to\n% \\emph{stochastic optimization}. Stochastic methods often aim at minimizing or\n% maximizing the expected cost, and in general they assume all probability\n% distributions to be known exactly. However, this is quite a strong assumption\n% because as argued earlier, the patterns behind real-world noise might be complex\n% and not easily observable.\n\n% \\paragraph{Sensitivity analysis and stability}\n\n% \\emph{Robust optimization}~\\cite{BenTalEGN09} assumes that we are given a set of\n% so-called scenarios instead of a probability distribution over the possible\n% input instances. Each scenario corresponds to one particular realization of the\n% input. Strict robustness computes a solution that is feasible in every scenario,\n% and that minimizes the maximum cost over all scenarios. Instead of minimizing\n% the maximum absolute cost, min-max regret robustness~\\cite{journals/asa/Savage51}\n% minimizes the largest regret (i.e., the difference between the cost of the\n% chosen solution and the cost of the minimum in the given scenario) over all\n% scenarios. However, a worst case perspective in which an adversary will reveal\n% the worst possible instance, given the chosen solution, is far too pessimistic\n% for real-world applications. Therefore, various relaxations of the\n% aforementioned robust optimization approaches have been\n% proposed~\\cite{series/lncs/GoerigkS16}. For example, cardinality constrained\n% robustness~\\cite{journals/ior/BertsimasS04} allows a certain amount of problem\n% constraints to be violated, while light robustness~\\cite{journals/mmor/Schobel14}\n% allows to relax the constraints. The disadvantage of these approaches is that\n% they might compute solutions that are no longer feasible for the actual\n% scenario. To guarantee feasibility in all cases, recoverable robust\n% optimization~\\cite{series/lncs/LiebchenLMS09} goes one step further and allows\n% the proposed solution to be modified after the true instance (or parts of it)\n% have been revealed. For an overview on robust optimization approaches, we refer\n% to a recent survey by Goerigk and Sch\\\"obel~\\cite{series/lncs/GoerigkS16}.\n\n% \\emph{Optimization for stable inputs} attempts to understand when and how small\n% changes in the input data affect the solution~\\cite{journals/cpc/BiluL12,%\n% conf/sirocco/BiloGGPW09,journals/scheduling/GattoW11,conf/sofsem/MihalakSSW11}.\n% %\n% % \\emph{Info-gap decision theory} is peculiar in that it models uncertainty as an\n% % information gap rather than a probability~\\cite{BenHaim06}.\n% % \\tptodo{Elaborate or remove}\n% % %\n% Optimization for sample average~\\cite{KleywegtSH02} aims at solving optimization\n% problems preceded by averaging several inputs into one.\n\n\n\\section{Setting and Generative Model Assumptions}\n\\label{sec:gen_appch_setting_and_model}\n\n\\subsection{Optimization Problem}\n\\label{sec:optimization_problem_description}\n\nIn the setting we are going to analyze in this and the next chapters, the\nfollowing components are assumed to be defined: \n\n\\begin{itemize}\n  \\item A set $\\mathcal{X}$ of possible \\textit{data instances} $X$:\n  \\begin{equation}\n    \\mathcal{X} \\ni X,\n  \\end{equation}\n  \\nomenclature[A, 01]{$\\mathcal{X}$}{source of data instances}%\n  \\nomenclature[A, 01a]{$X \\in \\mathcal{X}$}{[random] data instance}%\n  on which no further assumptions (e.g. structure, finiteness, countability) are\n  imposed in the most general case (see below in\n  Section~\\ref{sec:data_generation_model} for possible specifications of such\n  assumptions).\n  \\index{Data instance}\n\n  \\item A set $\\mathcal{C}$ of possible \\textit{solutions}, or\n  \\textit{hypotheses} $c$:\n  \\begin{equation}\n    \\mathcal{C} \\ni c,\n  \\end{equation}\n  \\nomenclature[A, 01b]{$\\mathcal{C}$}{set of solutions}%\n  \\nomenclature[A, 01c]{$c \\in \\mathcal{C}$}{solution}% can add \\nomnorefeq\n  where again no further structural or finiteness assumptions are imposed.\n\n  \\item An \\textit{objective function} $R(c, X)$ representing the value of a\n  given solution solution $c$ for a data instance $X$:\n  \\begin{equation}\\label{eq:cost_function}\n    R(c, X) \\colon \\mathcal{C} \\times \\mathcal{X} \\to \\mathbb{R}.\n  \\end{equation}\n  \\nomenclature[A, 01d]{$R(c, X)$}{cost function}%\n  If not stated otherwise, we will assume a minimization (i.e. ``cost'', ``error''\n  or ``energy'') semantics of $R(c,X)$ and call it a \\textit{cost function}.\n\\end{itemize}\n\n\\begin{definition}\\label{def:optimization_problem_definition}\n  Provided that a \\textit{solution feasibility} assumption is fulfilled, i.e.~any\n  solution $c \\in \\mathcal{C}$ is \\textit{feasible} (i.e.~valid) for any data\n  instance $X \\in \\mathcal{X}$, then we can say that these three components define a\n  valid \\textit{optimization problem} denoted by a triplet $\\mathcal{P} =\n  (\\mathcal{X}, \\mathcal{C}, R)$.\n  \\nomenclature[A, 01e]{$\\mathcal{P} = (\\mathcal{X}, \\mathcal{C}, R)$}{optimization problem \\nomnorefeqpage\\hfill Def.~\\ref{def:optimization_problem_definition}}%\n  \\index{Optimization problem}\n\\end{definition}\n\nThe optimization goal consists in finding the\nset of those solutions which minimize the cost function:\n\\begin{equation}\n  \\mathcal{C}^\\bot(X) \\coloneqq \\arg \\min_{c \\in \\mathcal{C}} R(c, X).\n\\end{equation}\n\\nomenclature[A, 01f]{$\\mathcal{C}^\\bot(X)$}{set of empirical optimizers}%\nWith a bit of notation abuse we will also write\n\\begin{equation}\n  c^\\bot(X) \\coloneqq \\arg \\min_{c \\in \\mathcal{C}} R(c, X) \\in \\mathcal{C}^\\bot(X),\n\\end{equation}\n\\index{Global minimizer}\nmeaning a \\textit{one} (out of many possible) optimal solution (global\nminimizer). We will denote the optimal cost as:\n\\begin{equation}\n  R^\\bot(X) \\coloneqq  \\min_{c \\in \\mathcal{C}} R(c, X).\n\\end{equation}\n\\nomenclature[A, 01g]{$R^\\bot(X)$}{optimal cost}%\n\n\\subsection{Data Generation Model}\n\\label{sec:data_generation_model}\n\nDealing with \\textit{uncertainty} in optimization requires to define a data\ngeneration process.\n\nIn the following, we will simply assume that there is exists \\textit{true\n(ground, signal) data instance} $X^0$, from which the \\textit{noise-contaminated\ndata instances} are obtained independently, i.e.:\n\\begin{equation}\\label{eq:data_gen_model}\n  X', X'', X''', \\dots \\sim PG(X | X^0)\n\\end{equation}\nthrough a \\textit{problem generating} process $PG(\\cdot | X^0)$. \n\\nomenclature[A, 01h]{$PG(X \\mid X^0)$}{problem generator}%\n\\index{Problem generator}\nNote that the problem generating process is parametrized through the ground\ntruth $X^0$. Note also that the obtained data instances are independent,\nconditioned on the $X^0$:\n\\begin{equation}\\label{eq:pg_independence}\n  \\text{for any data instances $X', X'' \\sim PG(X | X^0)$:\\quad } X'\n  \\independent X'' | X^0.\n\\end{equation}  \n\\index{Data instance!Ground truth}\n\n\\myremark Although this notation might seem complex, it is actually very\nstraightforward. In most cases we consider, $X \\in \\mathcal{X}$ will be just a\nvector of random (generated by $PG(\\cdot)$) weights from which the costs $R(c,\nX)$ are constructed.\n\n\\section{Approximation Set-Based Approach}\n\\label{sec:asc_original}\n\n\\index{Approximation Set Coding}\nIn this section, we will introduce the notions related to Approximation Set\nCoding framework~--- a successful way of regularizing solutions to cost-driven\noptimization problems.\n\n\\subsection{Approximation Sets}\n\nWe introduce the notion of \\textit{approximation sets}, which are intended to\naddress the question: how to avoid the risk of overfitting in those frequent\ncases, when the solver is not aware of precise noise conditions $PG(\\cdot)$\nimposed on the dataset?\n\nConsider the following thought experiment: datasets $X', X'', \\ldots$ are drawn\naccording to the random data generation process $PG(\\cdot | X^0)$ as given in\nSection~\\ref{sec:data_generation_model}. As all the datasets stem from the same\n``ground'' dataset $X^0$ (in some sense, which we leave undefined  for the sake\nof keeping things simple for now), they contain both useful and irrelevant\ninformation. In other words: only \\textit{some} information the one obtains from\nthe dataset ``explains signal'' $X^0$ (e.g. has low condition entropy), while\nthe rest of the information ``explains noise''.\n\nUtilizing an optimization model defined by cost $R(\\cdot, \\cdot)$, as\nin~\\eqref{eq:cost_function} and thus obtaining optimal solutions $c^\\bot(X'),\nc^\\bot(X''), \\ldots$, we inevitably absorb both useful and irrelevant information\nand overfit, making solutions unstable w.r.t. each other. To regularize the\noptimization process, one might want to relax the optimal solution by including\nall the solutions located in the vicinity (in some topology we define in a\nsecond) of it. A natural way to define such topology is to utilize the level\nsurfaces of the cost function $R(\\cdot, \\cdot)$ itself! The method proposed\nby~\\citet{conf/isit/Buhmann10} suggests the following definition of the\napproximation set.\n\n\\begin{definition}[\\citet{conf/isit/Buhmann10}]\n\\label{def:approximation_set}\nFor a given real number $\\gamma \\ge 0$, an approximation set is defined as follows:\n\\begin{equation}\n  \\mathcal{C}_\\gamma (X, R) \\coloneqq \n  \\{c \\in \\mathcal{C} \\mid R(c, X) - R^\\bot(X) \\le \\gamma\\},\n\\end{equation}\n\\nomenclature[D, 01]{$\\mathcal{C}_\\gamma (X, R)$}{$\\gamma$-approximation set\\nomnorefeqpage\\hfill Def.~\\ref{def:approximation_set}}%\nand the solutions belonging to it will be called $\\gamma$-optimal. \n\\index{Solution, $\\gamma$-optimal}\nFor the sake\nof notation brevity, we will drop the parameter(s) $X$ and/or $R$ where it is\nclear from the context, which dataset and cost function are meant. \n\\index{Approximation set}\n\\end{definition}\n\n\\begin{figure}[th!]\n        \\centering\n        \\begin{subfigure}[b]{.48\\textwidth}\n            \\includegraphics[width=\\linewidth]{figures/ch_generic_approach/asc_coding_approximation_1}\n            \\caption{Large $\\gamma$: approximation sets are in a great agreement, but non-informative at all.\\\\}\n            \\label{fig:asc_illustration-0}\n        \\end{subfigure}\n        \\hfill\n        \\begin{subfigure}[b]{.48\\textwidth}\n            \\includegraphics[width=\\linewidth]{figures/ch_generic_approach/asc_coding_approximation_2}\n            \\caption{Decreasing $\\gamma$: approximation sets get distinguished, and more information is extracted.}\n            \\label{fig:asc_illustration-1}\n        \\end{subfigure}\n        \\\\[.5cm]\n        % \\begin{subfigure}[b]{.48\\textwidth}\n        %     \\includegraphics[width=\\linewidth]{figures/ch_generic_approach/asc_coding_approximation_3}\n        %     \\caption{Further decreasing $\\gamma$: approximation sets get distinguished, and more information is extracted.}\n        %     \\label{fig:asc_illustration-2}\n        % \\end{subfigure}\n        % \\hfill\n        \\begin{subfigure}[b]{.48\\textwidth}\n            \\includegraphics[width=\\linewidth]{figures/ch_generic_approach/asc_coding_approximation_4}\n            \\caption{Small $\\gamma$: almost all the information is extracted, but solutions are in poor agreement.}\n            \\label{fig:asc_illustration-3}\n        \\end{subfigure}\n        \\\\[.5cm]\n        \\caption{Intuitive illustration of informativeness vs. stability.\n          Approximation sets are parametrized by $\\gamma$. The data inputs $X'$,\n          $X''$ and $X'''$ come from the same generative source. Decreasing the\n          parameter $\\gamma$ leads to extracting more information from the given\n          data, but at the same time making solutions less stable.}\n        \\label{fig:asc_illustration}\n\\end{figure}\n\nProperties of the parameter $\\gamma$ are crucial for understanding its role.\nOn one hand, it is obvious that infinite $\\gamma$ yields the whole set of\nfeasible solutions:\n\\[\n    \\left.\\mathcal{C}_{\\gamma} \\right|_{\\gamma = \\infty} (X) \n      \\equiv \\mathcal{C}.\n\\]\nOn the other hand, it holds\n\\[\n    \\left.\\mathcal{C}_{\\gamma} \\right|_{\\gamma = 0} (X) \n      \\equiv \\mathcal{C}^\\bot(X) \n      \\equiv \\{c^\\bot(X)\\},\n\\]\ni.e. zero $\\gamma$ yields only optimal solutions. Selection of the parameter\n$\\gamma$ allows to trade-off stability of the solutions (extreme case: $\\gamma =\n\\infty$) and the their informativeness (extreme case: $\\gamma = 0$). This raises\na very important question: does there exist a way to choose this parameter?\n\n\\subsection{Communication and Learning Stability}\n\\label{sec:communication_learning_stability}\n\n\\begin{figure}[bh!]\n  \\centering\n  \\begin{subfigure}[b]{.48\\textwidth}\n      \\includegraphics[width=\\linewidth]{figures/ch_generic_approach/Boolean_Cube_8code}\n      \\caption{}\n      \\label{fig:boolen_cube_vectors_8}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[b]{.48\\textwidth}\n      \\includegraphics[width=\\linewidth]{figures/ch_generic_approach/Boolean_Cube_2code}\n      \\caption{}\n      \\label{fig:boolen_cube_vectors_2}\n  \\end{subfigure}\n  \\\\[.5cm]\n  \\caption{Placing codebook vectors of length $3$ on a Boolean cube. Case \\textbf{(a)}\n    is a ``mean'' option, when we use all the eight vertices as codebook vectors. \n    Case \\textbf{(b)} is a ``lean'' option, when we use some of vertices as \n    neighborhoods to the two codebook vectors $000$ and $111$ denoted as big $0$ and big $1$.}\n  \\label{fig:boolen_cube_vectors}\n\\end{figure}\n\n\\begin{figure}[th!]\n  \\centering\n  \\begin{subfigure}[b]{.85\\textwidth}\n      \\includegraphics[width=\\linewidth]{figures/ch_generic_approach/Boolean_Cube_8code_error}\n      \\caption{High rate ($R_{\\text{code}}=1$), but no way to correct the error\n      (red: sent and received codes).}\n      \\label{fig:boolen_cube_vectors_error_8}\n  \\end{subfigure}\n  \\\\[.5cm]\n  \\begin{subfigure}[b]{.85\\textwidth}\n      \\includegraphics[width=\\linewidth]{figures/ch_generic_approach/Boolean_Cube_2code_error}\n      \\caption{Lower rate ($R_{\\text{code}} = 1/3$), correcting one digit error\n      (red: sent and received codes).}\n      \\label{fig:boolen_cube_vectors_error_2}\n  \\end{subfigure}\n  \\\\[.5cm]\n  \\caption{Dealing with one digit error. Case \\textbf{(a)}\n    is high rate option with eight codebook vectors, leading to a low\n    error-correcting capacity (in fact, no error can be tolerated). Case\n    \\textbf{(b)} is lower rate option with two codebook vectors leading to a\n    higher error-correcting capacity (one digit error can be tolerated, two\n    digits not).}\n  \\label{fig:boolen_cube_vectors_error}\n\\end{figure}\n\nIn this section, we will be working under definitions of\nSection~\\ref{sec:background_coding}. The approximation set-based approach has clear\nanalogies in communication, featuring the idea of communication by means of data\nand solutions. To illustrate this relation, we first will refer to information\ntheory and coding. As established by~\\citet{shannon:1948, shannon:1963}, all the\nrates up to channel capacity are achievable with vanishing error.\n\n\\index{Shannon's Channel Coding Theorem}\n\\newtheorem*{shannon_thm}{Shannon's Channel Coding Theorem}\n\\begin{shannon_thm}[e.g. Theorem 7.7.1, \\citealp{Cover:2006}]\n  For a discrete memoryless channel, all rates below capacity $C$ are\n  achievable. Specifically, for every rate $R_{\\text{code}} < C$, there exists a sequence of\n  $(2^{nR_{\\text{code}}}, n)$ codes with maximum probability of error $\\lambda^{(n)} \\to 0$.\n  Conversely, any sequence of $(2^{nR_{\\text{code}}}, n)$ codes with $\\lambda^{(n)} \\to 0$\n  must have $R_{\\text{code}} \\le C$.\n\\end{shannon_thm}\n\nThis important theoretical statement has a non-constructive\nproof resting on the idea of random coding with code length $n$ going to\ninfinity, and thus it does not provide a practical way of building such codes of\nfinite length. It turns out, that an attempt to design a finite-sized code faces\nthe trade-off between its error-correcting capability and its rate. An example\nof this idea is the simplest Hamming code of length $3$ which we are going to\nbriefly illustrate due to its importance for the next steps.\n\\index{Trade-off!Error-correcting capability}\n\\index{Trade-off!Code rate}\n\\index{Hamming code}\n\n\nFigures~\\ref{fig:boolen_cube_vectors} and~\\ref{fig:boolen_cube_vectors_error} to\nsome extent explain this trade-off in the simplest possible setting, thus\npreparing the reader for introducing the communication channel by means of\ndatasets. Figure~\\ref{fig:boolen_cube_vectors} shows that one can vary the\ncodebook vector set by, for instance, expanding ``neighborhoods'' of two\nvertices $(000)$ and $(111)$ by including all the adjacent vectors, while\nFigure~\\ref{fig:boolen_cube_vectors_error} demonstrates that although the above\nprocess reduces the code rate from $R_{\\text{code}} = 1$ down to\n$R_{\\text{code}} = 1/3$, it increases its error-correcting capability so that\nthe code can now tolerate all the one-digit errors. One can also imagine an\nextreme (not shown in figures) case of high two-digit noise: it is easy to see\nthat under this condition, a reliable, stable communication is only possible\nwith \\textit{only one} codebook vector and the \\textit{zero rate}\n($R_{\\text{code}} = 0$). In other words, the code gets less informative, but\nmore robust. \n\\index{Code!Rate}\n\\index{Codebook!Vectors}\n\n\\begin{algorithm}[th!]\n\\caption{Establishing the Communication}\\label{alg:communication_establishing}\n\\KwData{\\\\\n  \\quad instance of the dataset $X' \\in \\mathcal{X}$, \\\\ \n  \\quad solution set $\\mathcal{C} = \\{c\\}$, \\\\ \n  \\quad cost function $R(c, X)$, \\\\ \n  \\quad set of transformations $\\mathbb{T} = \\{\\tau\\}$, where $\\tau \\colon \\mathcal{X} \\to \\mathcal{X}$\\\\ \n  \\quad parameter $\\gamma$}\n\\KwResult{established communication scheme}\n\n{Sender and Receiver agree on $R(c, X)$\\;}\n{Sender and Receiver agree on $X'$\\;}\n{Sender and Receiver agree on $\\mathbb{T}$\\;}\n{Sender and Receiver agree on $\\gamma$\\;}\n\\tcp{Then, a coverage by approximation sets is generated:}\n\\ForEach{$\\tau \\in \\mathbb{T}$}{\n  {both Sender and Receiver generate a transformed dataset $\\tau \\circ X'$\\;}\n  {both Sender and Receiver compute $\\gamma$-approximation set \n    $\\mathcal{C}_\\gamma(\\tau \\circ X')$\\;}\n}\n\\end{algorithm}\n\nAs well as in the coding scenario described above, the learning process can be\nviewed as a noisy communication, where the model is a \\textit{decoder} which tries\nto figure out the solution to \\textit{true (useful) signal} contained in the\nnoisy data. Thus, the following rough analogies can be pointed out:\n\\begin{itemize}\n  \\item The role of codebook vectors is played by solutions $c$ to the optimization\n    problem $R(c,X)$.\n  \\item The role of errors is played by the noise generating process $PG()$\n    (see.~\\eqref{eq:data_gen_model}), which injects uncertainty into data $X$.\n  \\item The role of ``neighborhoods'' of codebook vectors from\n    Figures~\\ref{fig:boolen_cube_vectors_2}\n    and~\\ref{fig:boolen_cube_vectors_error_2} is played by approximation\n    sets.\n\\end{itemize}\n\nWe are now going, following~\\cite{conf/isit/Buhmann10}, to introduce an\nartificial communication scenario~(Algorithms~\\ref{alg:communication_establishing},\n\\ref{alg:communication_transmission} and~\\ref{alg:communication_decoding}).\nWe advise the reader to compare the textual explanation with the pictorial one \nin Figure.~\\ref{fig:coding_scheme_cartoon}.\n\\index{Approximation Set Coding!Communication scenario}\n\\index{Communication scenario|see{Approximation Set Coding}}\n\n\\begin{algorithm}[bh!]\n\\caption{Encoding and Transmission}\\label{alg:communication_transmission}\n\\KwData{\\\\\n  \\quad instance of the dataset $X' \\in \\mathcal{X}$, \\\\ \n  \\quad instance $X'' \\in \\mathcal{X}$ not known to receiver, \\\\\n  \\quad solution set $\\mathcal{C} = \\{c\\}$, \\\\ \n  \\quad cost function $R(c, X)$, \\\\ \n  \\quad set of transformations $\\mathbb{T} = \\{\\tau\\}$, where $\\tau \\colon \\mathcal{X} \\to \\mathcal{X}$\\\\ \n  \\quad parameter $\\gamma$}\n  \n\\KwResult{a received message}\n{Sender picks a $\\tau_{\\text{send}} \\in \\mathbb{T}$ and sends it\\;}\n{Sender encodes it by generating \n  a transformed dataset $\\tau_{\\text{send}} \\circ X'$ and sends it\\;}\n{Sender sends $\\tau_{\\text{send}} \\circ X'$\\;}\n\\tcp{Channel noise comes in the next line:}\n{Channel introduces error by applying transformation $\\tau_{\\text{send}}$ to a $X''$\\;}\n{Receiver receives $\\tau_{\\text{send}} \\circ X''$ without knowing either $\\tau_{\\text{send}}$ or $X''$\\;}\n\\end{algorithm}\n\n\\paragraph{Encoding step (Algorithm~\\ref{alg:communication_establishing}\n\\index{Approximation Set Coding!Encoding and transmission}\nand~\\ref{alg:communication_transmission};\nFig.~\\ref{fig:coding_scheme_cartoon_1})} Very briefly, the Sender-Receiver\nanalogy consists in distinguishing individual solutions by means of the noisy\ndatasets: Sender sends a message (defined below) encoded by the first dataset,\nand Receiver receives this message, but perturbed by means of the second\ndataset. More precisely, assuming the generative process $PG$\n(see~\\eqref{eq:data_gen_model}), the transmitted ``messages'' are the\ntransformations $\\tau \\in \\mathbb{T}$ of the datasets, so\n\\begin{equation}\n  \\tau \\in \\mathbb{T}, \\quad \\tau \\colon \\mathcal{X} \\to \\mathcal{X}.\n\\end{equation}\n\\nomenclature[D, 01a]{$\\mathbb{T}$}{set of messages}%\n\\nomenclature[D, 01b]{$\\tau \\in \\mathbb{T}$}{message}%\nNow, both Sender and Receiver are agreeing on the dataset $X'$, which will\nplay the role of the encoding ``benchmark''. Sender then picks a\ntransformation $\\tau_{\\text{send}}$ and encodes the message by means of $X'$ via\napplying one to the other:\n\\begin{equation}\n  X_{\\text{send}} \\coloneqq \\tau_{\\text{send}} \\circ X',\n\\end{equation}\n\\nomenclature[D, 01c]{$X', X''$}{two instances (ASC scenario)}%\n\\nomenclature[D, 01da]{$\\tau_{\\text{send}}$}{message sent}%\nand sends it out. Remember that Receiver does not know $\\tau_{\\text{send}}$, but knows\n``codebook approximation sets'' $\\{\\tau \\circ X'\\}_{\\tau \\in \\mathbb{T}}$.\n\n\\paragraph{Hypothetic noise-free transmission}\nIf there were no noise, Receiver, having obtained $X_\\text{received} =\nX_{\\text{send}}$, and knowing both $\\mathbb{T}$ and $X'$, could just recover the\n$\\tau_{\\text{send}}$ by enumerating:\n\\begin{equation}\n\\label{eq:acs_brute_force_decoding}\n  \\hat \\tau \\coloneqq \\arg \\max_{\\tau \\in \\mathbb{T}} \\Ind\\{X_{\\text{received}} = \n    \\tau \\circ X' \\}.\n\\end{equation}\n\\nomenclature[D, 01db]{$\\hat \\tau$}{message decoded}%\n\n\\paragraph{Actual noisy transmission (Algorithm~\\ref{alg:communication_transmission}; \nFig.~\\ref{fig:coding_scheme_cartoon_2})} \nHowever, the noise is injected by replacing \n$X'$ by $X''$, which is a noisy version of the initial dataset:\n\\begin{equation}\n  X_{\\text{received}} \\coloneqq \\tau_{\\text{send}} \\circ X'',\n\\end{equation}\nwhich makes it impossible for Receiver to perfectly match obtained message to\nany of the ``benchmarked ones'' like in Eq.~\\eqref{eq:acs_brute_force_decoding}.\n\n\\parsec\n\\myremark It it important to realize, that there are two manifestations of noise\nin this scenario. One is the original source of noise generated by $PG(\\cdot)$ and resulting\nin replacing $X'$ by $X''$. The other is the transmission error caused by \ndifference between the sent and received messages.\n\n\\paragraph{Decoding (Algorithm~\\ref{alg:communication_decoding}; Fig.~\\ref{fig:coding_scheme_cartoon_3} and\n\\ref{fig:coding_scheme_cartoon_4})} \nJust the same\nas the Hamming channel performs decoding the received vector by finding\nthe closest codebook vector, our Receiver tries to find the closest codebook \ndataset out of all the possible datasets $\\{\\tau \\circ X'\\}_{\\tau \\in \\mathbb{T}}$.\nCloseness is measured as the size of the intersection of their approximation sets:\n\\begin{equation}\n  \\hat \\tau = \\arg \\max_{\\tau \\in \\mathbb{T}} \\,\\,\n  \\bigl| \n     \\mathcal{C}_\\gamma(\\tau \\circ X') \\cap \\mathcal{C}_\\gamma(\\tau_{\\text{send}} \\circ X'')\n  \\bigr|,\n\\end{equation}\nthus, approximation sets play the role of parity check regions here.\n\\index{Parity check}\n\n\\begin{algorithm}[t]\n\\caption{Decoding}\\label{alg:communication_decoding}\n\\KwData{\\\\\n  \\quad instance of the dataset $X' \\in \\mathcal{X}$, \\\\ \n  \\quad instance $X'' \\in \\mathcal{X}$ not known to receiver, \\\\\n  \\quad solution set $\\mathcal{C} = \\{c\\}$, \\\\ \n  \\quad cost function $R(c, X)$, \\\\ \n  \\quad set of transformations $\\mathbb{T} = \\{\\tau\\}$, where $\\tau \\colon \\mathcal{X} \\to \\mathcal{X}$\\\\ \n  \\quad parameter $\\gamma$}\n\\KwResult{Transformation $\\hat \\tau$ which is estimate for $\\tau_{\\text{send}}$}\n{Receiver computes a $\\gamma$-approximation set of the received dataset: \n$\\mathcal{C}_\\gamma(\\tau_{\\text{send}} \\circ X'')$\\;}\n{Receiver maximizes its overlap with known $\\gamma$-approximation sets: \n\\begin{equation}\\label{eq:asc_decoding_intersection}\n  \\hat \\tau = \\arg \\max_{\\tau \\in \\mathbb{T}} \\,\\,\n  \\bigl| \n     \\mathcal{C}_\\gamma(\\tau \\circ X') \\cap \\mathcal{C}_\\gamma(\\tau_{\\text{send}} \\circ X'')\n  \\bigr|\n\\end{equation}}\n\\index{Approximation Set Coding!Decoding}\n\\end{algorithm}\n\n\\index{Hamming code!Decoding}\n\\index{Hamming distance}\nIt is crucially important to realize that this decoding rule is very similar to\nthat of the Hamming code (and thus very natural), because in the Hamming coding,\nthe closeness is measured by \\textit{minimizing} the Hamming distance between\nthe received vector and the codebook vectors, which is the same as\n\\textit{maximizing} the intersection between them:\n\\begin{align}\n  \\hat{\\mathbf{x}} &= \n    \\arg \\min_{\\mathbf{x} \\in \\mathbb{B}^3} \\;\n      \\|\\textbf{x}_\\text{received} \\oplus \\textbf{x} \\| \\notag \\\\ \n    &= \\arg \\min_{\\mathbf{x} \\in \\mathbb{B}^3} \\; \\bigl( n - \n        \\|\\textbf{x}_\\text{received} \\cap \\textbf{x}\\| \\bigr) \\notag \\\\\n    &=  \\arg \\max_{\\mathbf{x} \\in \\mathbb{B}^3} \\;\n         \\|\\textbf{x}_\\text{received} \\cap \\textbf{x}\\|.\n\\end{align}\n\\nomenclature[A, 00]{$\\mathbb{B}^3$}{Boolean cube}%\n\\nomenclature[A, 00a]{$\\oplus$}{sum modulo $2$}%\n\n\\paragraph{Decoding error and its probability}\n\nWhen $\\hat \\tau \\ne \\tau_\\text{send}$, we say that a decoding error occurs.\nObviously, the noise in our channel\n(Algorithm~\\ref{alg:communication_transmission}), acting via $PG(\\cdot | X^0)$,\nis the reason for that. Transferring robust optimization problem into a robust\ndecoding problem, we now will answer, following~\\citet{conf/isit/Buhmann10}, a\nnatural question: how can we bound this probability?\n\nWe are interested in bounding the probability\n\\begin{equation}\n  \\Prob(\\hat \\tau \\ne \\tau_\\text{send} | \\tau_\\text{send}).\n\\end{equation}\n\n\\begin{figure}[th!]\n  \\centering\n  \\begin{subfigure}[b]{.48\\textwidth}\n      \\includegraphics[width=\\linewidth]{figures/ch_generic_approach/coding_scheme_1}\n      \\caption{}\n      \\label{fig:coding_scheme_cartoon_1}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[b]{.48\\textwidth}\n      \\includegraphics[width=\\linewidth]{figures/ch_generic_approach/coding_scheme_2}\n      \\caption{}\n      \\label{fig:coding_scheme_cartoon_2}\n  \\end{subfigure}\n  \\\\[.5cm]\n  \\begin{subfigure}[b]{.48\\textwidth}\n      \\includegraphics[width=\\linewidth]{figures/ch_generic_approach/coding_scheme_3}\n      \\caption{}\n      \\label{fig:coding_scheme_cartoon_3}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[b]{.48\\textwidth}\n      \\includegraphics[width=\\linewidth]{figures/ch_generic_approach/coding_scheme_4}\n      \\caption{}\n      \\label{fig:coding_scheme_cartoon_4}\n  \\end{subfigure}\n  \\\\[.5cm]\n  \\caption{Process of correct decoding by approximation sets in the solution\n    space: \\textbf{(a)} $X'$ is set and sender sends $\\tau_4$; \\textbf{(b)} due\n    to noise which replaces $X'$ by $X''$, all the minimizers move around (red\n    to blue) in the solution space; \\textbf{(c)} the received solution is\n    surrounded by its approximation set (blue) and overlaps are considered;\n    \\textbf{(d)} decoded solution (dark red) happens to be $\\tau_4$ which was initially\n    sent (correct decoding).}\n  \\label{fig:coding_scheme_cartoon}\n\\end{figure}\n\nBefore we proceed, we will denote the intersection in~\\eqref{eq:asc_decoding_intersection}\nas follows:\n\\begin{equation}\n  \\Delta \\mathcal{C}_\\gamma^\\tau \n    \\coloneqq \\mathcal{C}_\\gamma(\\tau \\circ X') \n      \\cap \\mathcal{C}_\\gamma(\\tau_{\\text{send}} \\circ X'').\n\\end{equation}\nDue to the union bound, it holds that \\index{Union bound}\n\\begin{equation}\n  \\Prob(\\hat \\tau \\ne \\tau_\\text{send} | \\tau_\\text{send}) \n    \\le \\sum_{\\tau \\in \\mathbb{T}} \\Prob \n      \\bigl(\n        |\\Delta \\mathcal{C}_\\gamma^\\tau| \\ge |\\Delta \\mathcal{C}_\\gamma^{\\tau_\\text{send}}| \\bigm| \\tau_\\text{send}\n      \\bigr),\n\\end{equation}\ni.e. for decoding error to occur, one has to encounter an approximation set\nwhich is yielded by a wrong transformation, but happens to be closer to the\nreceived approximation set (this is illustrated in\nFigure~\\ref{fig:coding_scheme_cartoon_7}). The last bound can be rewritten via\nthe indicator function:\n\\begin{equation}\n  \\Prob(\\hat \\tau \\ne \\tau_\\text{send} | \\tau_\\text{send}) \n    \\le \\sum_{\\tau \\in \\mathbb{T}} \\Expct_{PG}\n      \\bigl[\n        \\Ind\\{|\\Delta \\mathcal{C}_\\gamma^\\tau| \\ge |\\Delta \\mathcal{C}_\\gamma^{\\tau_\\text{send}}|\\} \\bigm| \\tau_\\text{send}\n      \\bigr],\n\\end{equation}\nwhere the expectation is taken w.r.t. the problem generation process $X', X''\n\\sim PG(\\cdot | X^0)$. We further utilize the monotonicity of $\\log$ function:\n\\begin{equation}\n  \\Ind\\{|\\Delta \\mathcal{C}_\\gamma^\\tau| \\ge |\\Delta \\mathcal{C}_\\gamma^{\\tau_\\text{send}}|\\} \n  = \\Ind\\{\\log |\\Delta \\mathcal{C}_\\gamma^\\tau| \\ge \\log |\\Delta \\mathcal{C}_\\gamma^{\\tau_\\text{send}}|\\} \n\\end{equation}\nand the fact that $\\Ind\\{x \\ge 0\\} \\le \\exp(x)$ to come to the following:\n\\begin{equation}\n  \\Expct_{PG}\n      \\Bigl(\n        \\Ind\\{|\\Delta \\mathcal{C}_\\gamma^\\tau| \\ge |\\Delta \\mathcal{C}_\\gamma^{\\tau_\\text{send}}|\\} \\Bigm| \\tau_\\text{send}\n      \\Bigr)\n      \\le\n      \\frac{|\\mathcal{C}_\\gamma(X')| \\;  |\\mathcal{C}_\\gamma(X'')|}%\n      {|\\mathbb{T}| \\; |\\Delta \\mathcal{C}_\\gamma^{\\tau_\\text{send}}|},\n\\end{equation}\nwhere the product in the nominator comes from the fact that, under our\ngeneration process, the data instances $X'$ and $X''$ are independent given\n$X^0$, see~\\eqref{eq:pg_independence}.\n\nIn the spirit of~\\citet{shannon:1948}, we use the random coding argument here: \nall the $\\tau$ are identically distributed and independent, hence the above can\nbe rewritten:\n\\begin{equation}\n  \\Prob(\\hat \\tau \\ne \\tau_\\text{send} | \\tau_\\text{send}) \\le (|\\mathbb{T}| - 1)\n    \\exp(- I_\\gamma(\\tau_\\text{send}, \\hat \\tau)),\n\\end{equation}\nwhere \n\\begin{equation}\n  I_\\gamma(\\tau_\\text{send}, \\hat \\tau) \\coloneqq  \\Expct \\log \n  \\Bigl(\n    \\frac{|\\mathbb{T}| \\; |\\Delta \\mathcal{C}_\\gamma^{\\tau_\\text{send}}|}%\n      {|\\mathcal{C}_\\gamma(X')| \\;  |\\mathcal{C}_\\gamma(X'')|}\n  \\Bigr).\n\\end{equation}\n\n\\paragraph{Optimizing approximation parameter $\\boldsymbol\\gamma$}\nAt this point, we can determine the optimal $\\gamma^*$ as follows: the optimal\napproximation threshold is chosen as\n\\begin{equation}\\label{eq:asc_best_gamma}\n  \\gamma^* = \\arg \\max_{\\gamma \\ge 0} I_\\gamma(\\tau_\\text{send}, \\hat \\tau).\n\\end{equation}\n\\nomenclature[D, 01]{$\\gamma^*$}{optimal $\\gamma$}%\n\n\\begin{figure}[th!]\n  \\centering\n  \\begin{subfigure}[b]{.48\\textwidth}\n      \\includegraphics[width=\\linewidth]{figures/ch_generic_approach/coding_scheme_5}\n      \\caption{}\n      \\label{fig:coding_scheme_cartoon_5}\n  \\end{subfigure}\n  \\\\[.5cm]\n  \\begin{subfigure}[b]{.48\\textwidth}\n      \\includegraphics[width=\\linewidth]{figures/ch_generic_approach/coding_scheme_6}\n      \\caption{}\n      \\label{fig:coding_scheme_cartoon_6}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[b]{.48\\textwidth}\n      \\includegraphics[width=\\linewidth]{figures/ch_generic_approach/coding_scheme_7}\n      \\caption{}\n      \\label{fig:coding_scheme_cartoon_7}\n  \\end{subfigure}\n  \\\\[.5cm]\n  \\caption{Decreased $\\gamma$ and increased code rate leads to incorrect\n    decoding: \\textbf{(a)} same setting (i.e. same noise) as in\n    Figure~\\ref{fig:coding_scheme_cartoon}, but added more codebook\n    vectors; \\textbf{(b)} due to noise which replaces $X'$ by $X''$, all the\n    minimizers move around (red to blue) in the solution space, \\textbf{(c)}\n    decoded solution (dark red) happens to be wrong (incorrect decoding).}\n  \\label{fig:coding_scheme_cartoon_incorrect}\n\\end{figure}\n\nIn practical applications and in the spirit of the Shannon's random coding\nargument, it is often assumed that that $\\tau_\\text{send} = \\mathrm{Id}$, i.e.\none computes\n\\begin{equation}\n  I_\\gamma(\\tau_\\text{send}, \\hat \\tau) \\coloneqq  \\Expct \\log \n  \\Bigl(\n    \\frac{|\\mathbb{T}| \\; |\\Delta \\mathcal{C}_\\gamma(X', X'')|}%\n      {|\\mathcal{C}_\\gamma(X')| \\; |\\mathcal{C}_\\gamma(X'')|}\n  \\Bigr),\n\\end{equation}\nwhere\n\\begin{equation}\n  \\Delta \\mathcal{C}_\\gamma \\coloneqq \\mathcal{C}_\\gamma(X') \n      \\cap \\mathcal{C}_\\gamma(X'').\n\\end{equation}\n\\nomenclature[D, 01]{$\\Delta \\mathcal{C}_\\gamma$}{intersection of approximation sets}%\nIn practice, one often replaces $|\\mathbb{T}|$ with the cardinality of the full\nsolution set~\\citep{morteza12}, reflecting a specific choice of possible\ntransformations\\footnote{Since the proof of error probability rests on the\nargument of random coding and the codebook messages are chosen randomly, all\nthe considerations remain valid.}:\n\\begin{equation}\\label{eq:asc_mutual_information_formula}\n  I_\\gamma(\\tau_\\text{send}, \\hat \\tau) \\coloneqq  \\Expct \\log \n  \\Bigl(\n    \\frac{|\\C| \\; |\\Delta \\mathcal{C}_\\gamma(X', X'')|}%\n      {|\\mathcal{C}_\\gamma(X')| \\; |\\mathcal{C}_\\gamma(X'')|}\n  \\Bigr),\n\\end{equation}\n\\nomenclature[D, 02a]{$I_\\gamma$}{ASC $\\gamma$-score}%\n\\begin{definition}\n\\label{def:asc_score}\n  We will call the above quantity ASC $\\gamma$-score. We will call its maximum\n  simply ASC score or Approximation Capacity (AC):\n  \\begin{equation}\n    C \\coloneqq \\max_\\gamma I_\\gamma.\n  \\end{equation}\n  \\nomenclature[D, 02ba]{$C$}{approximation capacity}%\n  \\index{ASC score}\n  \\index{Approximation capacity}\n\\end{definition}\n\n\\myremark It is interesting to note that the semantics of $I_\\gamma(\\tau_\\text{send}, \\hat\n\\tau)$ is surprisingly similar to that of mutual information\n(Definition~\\ref{def:inf_theory_mutual_information}). First, both are related to\nthe maximum rate of certain channel. Second,  both can be decomposed in quite a\nsimilar way: recall from~\\eqref{eq:background_mi_decomposition} that, for random\nvariables $X$ and $Y$,\n\\begin{equation*}\n  \\MI(X, Y) = H(X) + H(Y) - H(X, Y).\n\\end{equation*}\nIn a same way one may observe, that~\\eqref{eq:asc_mutual_information_formula}\ncan be very easily decomposed into three logarithms:\n\\begin{align}\n  I_\\gamma(\\tau_\\text{send}, \\hat \\tau) =  \\overbrace{- \\Expct \\log \n  \\Bigl(\n    \\frac{|\\mathcal{C}_\\gamma(X')|}{ |\\C| }\n  \\Bigr)}^{\\text{single entropy}}\n  %\n  &\\overbrace{- \\Expct \\log \n  \\Bigl(\n    \\frac{|\\mathcal{C}_\\gamma(X'')|}{|\\C|}\n  \\Bigr)}^{\\text{single entropy}} \\notag \\\\\n  %\n  &\\underbrace{+\\Expct \\log \n  \\Bigl(\n    \\frac{|\\Delta \\mathcal{C}_\\gamma(X', X'')|}{ |\\C| }\n  \\Bigr)}_{\\text{joint entropy}},\n\\end{align}\nwhere first two terms can be contemplated as single entropies of uniform\ndistributions over approximation sets, and the third term corresponds to\nthe joint entropy.\n\n\\myremark In practical applications, when there are only two data points $X'$, $X''$ and\nno information about $PG(\\cdot)$ is available, one can use an empirical version\nof~\\eqref{eq:asc_mutual_information_formula}\n\\begin{equation}\\label{eq:asc_mutual_information_formula_wo_expct}\n\\hat I_\\gamma(X', X'') \\coloneqq  \\log \n  \\Bigl(\n    \\frac{|\\C| \\; |\\Delta \\mathcal{C}_\\gamma(X', X'')|}%\n      {|\\mathcal{C}_\\gamma(X')| \\; |\\mathcal{C}_\\gamma(X'')|}\n  \\Bigr),\n\\end{equation}\n\\nomenclature[D, 02b]{$\\hat I_\\gamma$}{empirical ASC $\\gamma$-score}%\nas an estimator without the expectation sign. More on that will be given in\nChapter~\\ref{ch:mst} when describing the application.\n\n\\section{Another View: Similarity Approach}\n\\label{sec:similarity_approach_intro}\n\nIn this section, we briefly visit, with sufficient adaptation of\nnotation\\footnote{The two interpretations of the same idea have been\ndeveloped in parallel, hence there are two consistent systems of notation.},\nanother view on finding a robust approximation, which is called\n\\textit{similarity approach} and was introduced and developed, e.g.,\nin~\\citep{Sramek:PhD,Proeger:PhD,jcss:2017}. Yielding the same quantity as\nin~\\eqref{eq:asc_best_gamma}, this approach arose from a specific interpretation\nof the ASC~\\citep{conf/isit/Buhmann10}.\n\\index{Similarity approach}\n\nFor the sake of itegration into the thesis, in this section we use additive\napproximation set notation (i.e. the same as everywhere in this thesis),\nwhile~\\citet{Sramek:PhD} used a multiplicative one\\footnote{For the definiton of\nmultiplicative approximation sets, refer to e.g.~\\citep{Sramek:PhD} or\n\\citep{jcss:2017}.}. Assume there are two \\textit{data instances} $X'$ and\n$X''$, coming from the same source~$PG(\\cdot | X^0)$,\nsee~\\eqref{eq:data_gen_model}. \\citet{Sramek:PhD} identifies two cases:\n\n\\begin{itemize}\n  \\item If the generation process $PG$ is very noisy, resulting in two\n  non-similar instances $X'$ and $X''$ it is obvious that the intersection of\n  two approximation sets ${\\mathcal{C}_\\gamma}(X')\\cap\n  {\\mathcal{C}_\\gamma}(X'')$ will contain some solutions when $\\gamma$ is large\n  enough. \\citet{Sramek:PhD} calls such solutions \\emph{expected\n  due to $\\gamma$}. At this point, the reader can start building analogies to\n  the above by revisiting Figure~\\ref{fig:asc_illustration-0}, where large\n  approximation sets yield a lot of solutions in the intersection.\n\n  \\item On the other hand, if the two instances $X'$ and $X''$ are more similar,\n  which is the case for a low-noise $PG$, the intersection\n  ${\\mathcal{C}_\\gamma}(X')\\cap {\\mathcal{C}_\\gamma}(X'')$, taken at the same\n  $\\gamma$ value, will contain, in addition to the above-mentioned (expected due\n  to $\\gamma$) ones, some solutions due to the similarity of the instances.\n  \\citet{Sramek:PhD} calls them \\emph{unexpected}. In terms coined later~\\citep{jcss:2017} \n  it is called \\emph{expected due to similarity}.\n  \\index{Solutions!Expected due to similarity}\n\\end{itemize}\n\nThe point of introducing such cases consists in the following: these latter\nsolutions,~--- i.e. the ones expected due to similarity~--- are likely to be\ngood choices for possible test instance $X'''$ that comes from the same source.\n\nThe goal is thus shifted to finding the $\\gamma$ that maximizes the ratio of the\nnumber of solutions that are expected due to similarity over the size of the\nintersection (compare to the ASC approach~\\eqref{eq:asc_best_gamma}; the\ncomparison will be summarized in conclusion,\nSection~\\ref{sec:gen_appch_conclusion}). To fulfill the task, several\ndefinitions are required. Figure~\\ref{fig:intersection_types} illustrates these\ndefinitions.\n\n\\begin{definition}[Feasible approximation set] \\label{def:feasible_as}\n  A set of solutions $F\\subseteq\\mathcal{C}$ is called a\n  \\emph{feasible approximation set} if there exists some instance $\\tilde X$ and\n  some number $\\tilde \\gamma$ such that $F$ is the $\\tilde \\gamma$-approximation\n  set of $\\tilde X$.\n\\end{definition}\n\n\\begin{definition}[Expected intersection sizes due to $\\gamma$] \\label{def:intersection_due_to_gamma}\n  Given $\\gamma$ and the sizes $|{\\mathcal{C}_\\gamma}(X')| =: k(\\gamma)$ and\n  $|{\\mathcal{C}_\\gamma}(X'')| =: l(\\gamma)$, let\n  $es(\\gamma,k(\\gamma),l(\\gamma))$ denote the expected size of the intersection\n  of two feasible approximation sets $A$ and $B$ of sizes $k(\\gamma)$ and\n  $l(\\gamma)$, respectively.\n  \\nomenclature[D, 03a]{$es(\\gamma,k(\\gamma),l(\\gamma))$}{expected intersection\\nomnorefeqpage\\hfill Def.~\\ref{def:intersection_due_to_gamma}}%\n\\end{definition}\n  \n\\begin{definition}[Expected intersection due to similarity] \\label{def:intersection_due_to_sim}\n  Given $\\gamma$ and the sizes $|{\\mathcal{C}_\\gamma}(X')| =: k(\\gamma)$ and\n  $|{\\mathcal{C}_\\gamma}(X'')| =: l(\\gamma)$, if the intersection of\n  ${\\mathcal{C}_\\gamma}(X')$ and ${\\mathcal{C}_\\gamma}(X'')$ is larger than the\n  expected size $es(\\gamma,k(\\gamma),l(\\gamma))$, then it contains some\n  solutions that are expected due to similarity, and we will denote them\n  $sim(\\gamma)$.\n  \\nomenclature[D, 03b]{$sim(\\gamma)$}{size expected due to $\\gamma$\\nomnorefeqpage\\hfill Def.~\\ref{def:intersection_due_to_sim}}%\n\\end{definition}\n%\n%\n\\begin{figure}[t!]\n  \\centering\n  \\begin{subfigure}[b]{.55\\textwidth}\n      \\label{fig:approx_sets--example--1} \n      \\includegraphics[width=\\linewidth]{figures/ch_generic_approach/approx_sets--schematic--1}\n      \\caption{Placing a solution $c \\in \\C$}\n  \\end{subfigure}\n  \\\\[.5cm]\n  \\begin{subfigure}[b]{.55\\textwidth}\n      \\label{fig:approx_sets--example--3}\n      \\includegraphics[width=\\linewidth]{figures/ch_generic_approach/approx_sets--schematic--3}\n      \\caption{Intersection $\\mathcal{C}_{\\gamma}(X')\\cap \\mathcal{C}_{\\gamma}(X'')$}\n  \\end{subfigure}\n  \\\\[.5cm]\n  \\caption{\n    Approximation sets for the instances $X'$ and $X''$. By $c^\\bot(X)$ we\n    denote the solution whose cost is minimum in $X$. \\textbf{(a)}: We\n    place each solution $c \\in \\mathcal{C}$ at position\n    $(\\gamma',\\gamma'')$, where $\\gamma'=R(c, X') - R^\\bot(X')$ and\n    $\\gamma''=R(c, X'') - R^\\bot(X'')$. \\textbf{(b)}: Example of\n    intersection of approximation sets $\\mathcal{C}_{\\gamma}(X')\\cap\n    \\mathcal{C}_{\\gamma}(X'')$ (this view on approximation sets was \n    originally suggested by Tobias Pröger~\\citep[cf.][]{jcss:2017}, figure labels\n    adapted for additive notation).}\n  \\label{fig:approx_sets--schematic}\n\\end{figure}\n%\nThus we have \n\\begin{equation}\n  |{\\mathcal{C}_\\gamma}(X') \\cap {\\mathcal{C}_\\gamma}(X'')|=sim(\\gamma)+\n    es(\\gamma,k(\\gamma),l(\\gamma)),\n\\end{equation}\nand, to maximize the probability that the uniformly randomly\nchosen solution from the intersection is stable, we want to find the value $\\gamma$ that maximizes\n$\\frac{sim(\\gamma)}{sim(\\gamma)+es(\\gamma,k(\\gamma),l(\\gamma))}$. The following about \nmaximization objectives holds:\n\\begin{align}\n  \\arg \\max_{\\gamma>0} &\\;\\; \\frac{sim(\\gamma)}{sim(\\gamma)+es(\\gamma,k(\\gamma),l(\\gamma))}  \\notag \\\\\n    &\\qquad= \\arg \\max_{\\gamma > 0} \\; \\Bigl(\n        1 - \\frac{es(\\gamma,k(\\gamma),l(\\gamma))}{sim(\\gamma)+es(\\gamma,k(\\gamma),l(\\gamma))}\n      \\Bigr) \\notag \\\\\n    &\\qquad= \\arg \\min_{\\gamma > 0} \\;\\; \\frac{es(\\gamma,k(\\gamma),l(\\gamma))}{sim(\\gamma)+es(\\gamma,k(\\gamma),l(\\gamma))}\n      \\notag \\\\\n    &\\qquad= \\arg \\max_{\\gamma > 0} \\;\\; \\frac{sim(\\gamma)+es(\\gamma,k(\\gamma),l(\\gamma))}{es(\\gamma,k(\\gamma),l(\\gamma))},\n\\end{align}\nhence we can reformulate (for the sake of clarity) the objective of the similarity-based\napproach as maximizing the value\n\\begin{align}\n  \\label{eq:similarity}\n  S_\\gamma(X',X'')\n    \\coloneqq \\frac{|{\\mathcal{C}_\\gamma}(X') \\cap {\\mathcal{C}_\\gamma}(X'')|}{es(\\gamma,k(\\gamma),l(\\gamma))}\n    = \\frac{sim(\\gamma)+es(\\gamma,k(\\gamma),l(\\gamma))}{es(\\gamma,k(\\gamma),l(\\gamma))}.\n\\end{align}\n\n\n\\begin{figure}[t!]\n  \\centering\n  \\begin{subfigure}[b]{.49\\textwidth}\n      \\label{fig:intersection_due_to_gamma} \n      \\includegraphics[width=\\linewidth]{figures/ch_generic_approach/intersection_due_to_gamma}\n      \\caption{Two non-similar approximation sets.}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[b]{.49\\textwidth}\n      \\label{fig:intersection_due_to_sim}\n      \\includegraphics[width=\\linewidth]{figures/ch_generic_approach/intersection_due_to_sim}\n      \\caption{Two similar approximation sets}\n  \\end{subfigure}\n  \\\\[.5cm]\n  \\caption{Illustration of ideas contained in Definitions~\\ref{def:feasible_as},\n  \\ref{def:intersection_due_to_gamma} and \\ref{def:intersection_due_to_sim}: as\n  opposed to randomly chosen approximation sets \\textbf{(a)}, two related\n  (similar) approximation sets \\textbf{(b)} have a $sim(\\gamma)$ component of\n  the intersection, which we naturally seek to maximize.}\n  \\label{fig:intersection_types}\n\\end{figure}\n\n\\paragraph{Problem-based instance similarity}\nIn equation~\\eqref{eq:similarity}, the expected size of the intersection is\nw.r.t.\\  the problem specific probability distribution over all feasible\napproximation sets of size $|{\\mathcal{C}_\\gamma}(X')|$ and\n$|{\\mathcal{C}_\\gamma}(X'')|$, respectively. However, this distribution is hard\nto estimate, so,~\\citet{Sramek:PhD} introduced a problem-based based instance\nsimilarity, which approximates the denominator by a uniformly chosen pair of\napproximation sets.\n\\index{Similarity approach!Problem-based similarity}\n%\n\\begin{definition}[Problem-based instance similarity]\n  Let $X'$ and $X''$ be two input instances of a combinatorial optimization\n  problem $\\mathcal{P}$ with solution space $\\mathcal{C}$. For a given $\\gamma$,\n  let ${\\mathcal{C}_\\gamma}(X')$ and ${\\mathcal{C}_\\gamma}(X'')$ be $\\gamma$-approximation sets for $X'$\n  and $X''$. Further, let $\\mathcal{F}_k$ denote the set of all feasible\n  approximation sets of size $k$, i.e., the set of all such sets $F\\subseteq\n  \\mathcal{C}$ of size $k$ for which there exists an instance $I'$ and\n  a value $\\tilde \\gamma$ such that $F=\\mathcal{C}_{\\tilde \\gamma}(\\tilde X)$. Then, the expression\n  \\begin{equation}\n    \\label{eq:generic_similarity}\n    S_\\gamma(X',X'') = \\frac{|{\\mathcal{C}_\\gamma}(X')\\cap {\\mathcal{C}_\\gamma}(X'')|}\n      {\\mathop{\\mathbb{E}}_{A\\in \\mathcal{F}_{|{\\mathcal{C}_\\gamma}(X')|}, B\\in\n      \\mathcal{F}_{|{\\mathcal{C}_\\gamma}(X'')|}}{\\big[|A\\cap B|\\big]}}\n  \\end{equation}\n  \\nomenclature[D, 03c]{$S_\\gamma(X',X'')$}{instance $\\gamma$-similarity}%\n  \\nomenclature[D, 04]{$\\mathcal{F}_k$}{all feasible approximation sets}%\n  is the \\emph{similarity of $X'$ and $X''$ at value $\\gamma$} (with respect to\n  the optimization problem $\\mathcal{P}$), and the expression\n  \\begin{equation}\n    \\label{def:S}\n    S(X',X'') \\coloneqq \\max_\\gamma S_\\gamma(X',X'')\n  \\end{equation}\n  \\nomenclature[D, 03d]{$S(X',X'')$}{instance similarity}%\n  is the \\emph{similarity of $X'$ and $X''$} with respect to the optimization\n  problem $\\mathcal{P}$.\n\\end{definition}\n%\n\nThus, the similarity-based approach (in the following referred just as\n``similarity'' approach) works as follows. First, we compute the value $\\gamma$\nthat maximizes the similarity\n\\begin{align}\\label{eq:similarity_formula}\n  S_\\gamma(X',X'') = \\frac{|{\\mathcal{C}_\\gamma}(X')\\cap {\\mathcal{C}_\\gamma}(X'')|}\n    {\\mathop{\\mathbb{E}}_{A\\in \\mathcal{F}_{|{\\mathcal{C}_\\gamma}(X')|}, B\\in\n    \\mathcal{F}_{|{\\mathcal{C}_\\gamma}(X'')|}}{\\big[|A\\cap B|\\big]}},\n  \\tag{\\ref{eq:generic_similarity}}\n\\end{align}\nwhere the expectation is w.r.t.\\ the uniform probability distribution over the\nelements in $\\mathcal{F}_{|{\\mathcal{C}_\\gamma}(X')|}$ and $\\mathcal{F}_{|{\\mathcal{C}_\\gamma}(X'')|}$,\nrespectively. We then return a solution from ${\\mathcal{C}_\\gamma}(X')\\cap {\\mathcal{C}_\\gamma}(X'')$\nuniformly at random.\n\nHowever, there are two practical issues with the procedure shown above: a)~it is\nnot always clear how to directly optimize $\\gamma$ for the value\nof~\\eqref{eq:generic_similarity}; and b)~sampling from the intersection of the\ncorresponding $\\gamma$-approximation sets uniformly at random might be\ndifficult. Despite all that, the similarity approach can be always applied in the \ncases, where one can provide all the steps of Algorithm~\\ref{alg:similarity}.\n\n\\medskip\n\\begin{algorithm}[ht!]\n\\caption{Pipeline for Similarity Approach (Section~\\ref{sec:similarity_approach_intro})}\n\\label{alg:similarity}\n  {Determine the domains $\\mathcal{F}_k$ of feasible approximation sets of size\n  $k$.}\n\n  {Provide a mathematical analysis or an algorithm $ALG_\\mathbb{E}$ that\n  computes the expected size of the intersection of two approximation sets of\n  given sizes $k$ and $l$.}\n\n  {Provide an algorithm $ALG_\\cap$ that computes the size of the intersection\n  ${\\mathcal{C}_\\gamma}(X')\\cap {\\mathcal{C}_\\gamma}(X'')$, given $\\gamma$ and\n  two instances $X'$ and $X''$.}\n\n  {Find $\\gamma^*$ that maximizes the similarity $S_\\gamma(X',X'')$, using\n  $ALG_\\mathbb{E}$ and $ALG_\\cap$.}\n\n  {Provide an algorithm $ALG_\\text{rand}$ that picks a uniform random solution\n  from the intersection $\\C_{\\gamma^*}(X')\\cap \\C_{\\gamma^*}(X'')$.}\n\\end{algorithm}\n\\medskip\n\nIn order to fulfill these tasks, on can use several tools provided below. It is\nimportant to notice that these useful theorems close the\ngap between the ASC formulation~\\eqref{eq:asc_mutual_information_formula} and the\nsimilarity approach formulation~\\eqref{eq:similarity_formula}.\n\n\\begin{theorem}[\\citealp{Sramek:PhD}]\n  \\label{thm:simple}\n  Let $\\mathcal{P} = (\\mathcal{X}, \\mathcal{C}, R)$\n  (see~Section~\\ref{sec:optimization_problem_description}) be an optimization\n  problem with the property that for any subset $F$ of the set of all feasible\n  solutions $\\mathcal{C}$ there exists an instance $\\tilde X \\in \\mathcal{X}$\n  and a value $\\tilde \\gamma$ such that $\\mathcal{C}_{\\tilde \\gamma}(\\tilde\n  X)=F$. Then, the similarity of two instances $X', X''\\in\\mathcal{X}$ at value\n  $\\gamma$ is\n  \\begin{align}\n    \\label{eq:simple}\n    S_\\gamma(X',X'')=\\frac{|\\mathcal{C}||{\\mathcal{C}_\\gamma}(X') \\cap {\\mathcal{C}_\\gamma}(X'')|}\n      {|{\\mathcal{C}_\\gamma}(X')||{\\mathcal{C}_\\gamma}(X'')|}.\n  \\end{align}\n\\end{theorem}\n\nHowever, as \\citet{Sramek:PhD} notes, there exists an issue that not every subset\n$F\\subseteq\\mathcal{C}$ is a feasible approximation set, and there is still no general\nalgorithm of computing the expected size of the intersection. The following\nchain of theorems provides some approximation guarantees for the value of~\\eqref{eq:simple}.\n\n\\begin{theorem}[\\citealp{Sramek:PhD}]\n  \\label{thm:bound}\n  Let $\\mathcal{P} = (\\mathcal{X}, \\mathcal{C}, R)$ be an optimization problem. If\n  $|{\\mathcal{C}_\\gamma}(X')|=|{\\mathcal{C}_\\gamma}(X'')|$ for a given $\\gamma$, then\n  \\begin{align}\n    \\label{eq:bound}\n    S_\\gamma(X',X'') \\leq \\frac{|\\mathcal{C}||{\\mathcal{C}_\\gamma}(X')\\cap {\\mathcal{C}_\\gamma}(X'')|}\n      {|{\\mathcal{C}_\\gamma}(X')||{\\mathcal{C}_\\gamma}(X'')|}.\n  \\end{align}\n\\end{theorem}\n\n\\begin{theorem} [\\citealp{Sramek:PhD}]\n  \\label{thm:approx}\n  Let $A$ be a constant such that for each feasible solution $c$ of some\n  optimization problem $\\mathcal{P} = (\\mathcal{X}, \\mathcal{C}, R)$ it holds that \n  $|\\{F\\in \\mathcal{F}_k | c\\in F\\}| \\leq A k|\\mathcal{F}_k|/|\\mathcal{C}|$. Then,\n  \\begin{align}\n    S_\\gamma(X',X'')\\geq\\frac{|\\mathcal{C}||{\\mathcal{C}_\\gamma}(X')\\cap {\\mathcal{C}_\\gamma}(X'')|}\n      {A |{\\mathcal{C}_\\gamma}(X')||{\\mathcal{C}_\\gamma}(X'')|}.\n  \\end{align}\n\\end{theorem}\n\n\\begin{theorem} [\\citealp{Sramek:PhD}]\n  \\label{thm:worst_case}\n  Let $\\mathcal{P} = (\\mathcal{X}, \\mathcal{C}, R)$ be an optimization problem.\n  Then,\n  \\begin{align}\n    S_\\gamma(X',X'')\\geq\\frac{|{\\mathcal{C}_\\gamma}(X')\\cap {\\mathcal{C}_\\gamma}(X'')|}{|{\\mathcal{C}_\\gamma}(X')||{\\mathcal{C}_\\gamma}(X'')|}.\n  \\end{align}\n\\end{theorem}\n%\n\n\\myremark This shows that the step of deriving the appropriate specific formula or\nalgorithm to calculate the expected size of the intersection is a necessary\ncomponent of the approach, unless it is possible to show that for a concrete\nproblem the upper bound is sufficient. We will speculate more on that in the\nconclusion to this chapter (Section~\\ref{sec:gen_appch_conclusion}).\n\n\\section{Proof-of-Concept Prototypic Example}\n\\label{sec:proof_of_concept}\n\n\\index{Prototypic example!For ASC}\nPreviously, in Section~\\ref{sec:asc_original}, we introduced a method of\nsolution regularization by ASC, and later in\nSection~\\ref{sec:similarity_approach_intro} we gave a thorough overview of an\nanalogical approach called instance similarity. While they stem from completely\ndifferent roots, it can be easily seen that they both aim at choosing an optimal\napproximation set width $\\gamma$ in a same way. Specifically, we seek to\noptimize\n\\begin{equation}\\label{eq:similarity_maximization_objective}\n    \\gamma^* = \\arg \\max_{\\gamma >0} \\frac{|{\\mathcal{C}_\\gamma}(X') \\cap {\\mathcal{C}_\\gamma}(X'')|}\n      {|{\\mathcal{C}_\\gamma}(X')||{\\mathcal{C}_\\gamma}(X'')|}\n\\end{equation}\n\\myremark Note that this equation is\n\\textit{not} identical either to its ASC\nversion~\\eqref{eq:asc_mutual_information_formula} or similarity-based\nversion~\\eqref{eq:similarity_formula}, although yielding same optimization goal;\nwe will briefly revisit the technical differences, like presence of logarithm,\nlater in the conclusion.\n\nOne of the contributions of this thesis is to present an abstract\nproof-of-concept model for prototypical combinatorial optimization problems,\nwhich would allow to experimentally the advantages of the approximation set-based \napproaches. We will mostly experimentally investigate how the methods of\nSections~\\ref{sec:asc_original} and~\\ref{sec:similarity_approach_intro} perform\non this model.\n\n\\subsection{The Example Setting and Terminology}\nWe expect the approximation set-based methods to exceed the performance of other\noptimization methods when the set of solutions that have stable cost over all or\nmost instances is large enough not to be completely hidden in the noise.\n%\nTo highlight the potential of our approach, we consider an uncertain\nminimization problem $(\\mathcal{X}, \\mathcal{C}, R)$ in which the solution space\n$\\mathcal{C}$ is partitioned into two sets $\\sgood$ and $\\sbad$ of sizes $\\g$\nand $\\b$, respectively, which contain the \\good\\ and the \\bad\\ solutions,\nrespectively. Without loss of generality we assume that\n\\begin{align}\n  \\C &= \\{c_i\\}_{i=1}^n \\notag \\\\\n  \\sgood &= \\{c_1,\\ldots, c_{|\\g|}\\} \\notag \\\\\n  \\sbad &= \\{c_{|\\g|+1},\\ldots,c_{|\\g|+|\\b|}\\}.\n\\end{align}\n\\nomenclature[D, 04a]{$\\sgood$, $\\sbad$}{\\good\\ and \\bad\\ solutions}%\n%\nThe sets $\\sgood$ and $\\sbad$ represent solutions which are desirable and\nnon-desirable to be chosen, which reflects the fact that the approximation\nset-based approaches are designed to reliably tell them apart. We further assume\nthat $\\g \\ll \\b$, which corresponds to the fact that \\good\\ solutions should be hard\nto identify.\n\nOur proof-of-concept scenario abstracts from a concrete optimization problem. In\nother words, we do not address here the problem of specific optimization\nalgorithms. Hence we explicitly state that instead of generating inputs $X \\in\n\\mathcal{X}$, we rather directly generate costs of solutions $c \\in \\C$.\n%\nIn the terminology of Section~\\ref{sec:optimization_problem_description}, an\ninstance $X$ can be represented as a vector of random solution costs of length\n$n$:\n\\begin{equation}\\label{eq:generic_appch_cost_vector}\n  X \\coloneqq \\langle R_i \\rangle_{i=1}^{n},\n\\end{equation} \nand the cost function is simply\n\\begin{equation}\n  R(c_i, X) \\coloneqq R_i,\n\\end{equation} \ni.e.~the $i$-th entry stores the cost of the solution $c_i$ in $X$.\n\n\\subsection{Problem Generation}\n\\label{sec:gen_appch_pg}\n\nWe define the solution ``desirability'' by the intuition that costs of \\good\\\nsolutions have a small standard deviation and play the role of signal,\nwhile costs of \\bad\\ solutions have a higher mean and/or a higher standard\ndeviation and play the role of deceiving noise.\n\nWe assume the cost vector of an instance $X$ to be generated with the following\nrandom problem generating process $PG(\\cdot)$:\n\\begin{itemize}\n  \\item[1)] the first $\\g$ values are chosen at random according to some\n            (fixed) probability distribution $\\DG$, and\n  \\item[2)] the remaining $\\b$ values are chosen at random according to some\n            (fixed) probability distribution $\\DB$.\n\\end{itemize}\n\\nomenclature[D, 04b]{$\\DG$, $\\DB$}{cost distributions\\nomnorefeq}%\n\n\\begin{figure}[t!]\n  \\centering\n  \\begin{subfigure}[b]{.8\\textwidth}\n      \\includegraphics[width=\\linewidth]{figures/ch_generic_approach/stable_and_unstable_distr}\n  \\end{subfigure}\n  \\caption{Schematic example of \\good\\ and \\bad\\ cost distributions and noise\n  levels $N \\in \\mathcal{N}$ of \\bad\\ ones, as described in\n  Section~\\ref{sec:gen_appch_pg}.}\n  \\label{fig:stable_and_unstable_solutions}\n\\end{figure}\n\nNaturally it is safe to assume that both $\\DG$ and $\\DB$ have the property that\n\\good\\ solutions are superior to \\bad\\ ones\n(Figure~\\ref{fig:stable_and_unstable_solutions}), e.g., because they have a\nsmaller expected cost or a smaller variance, i.e. for any $R_\\text{\\good} \\sim\n\\DG$ and $\\R_\\text{\\bad} \\sim \\DB$, $\\Expct [R_\\text{\\good}] < \\Expct [R_\\text{\\bad}]$ \nand $\\Var [R_\\text{\\good}] < \\Var [R_\\text{\\bad}]$.\nWe further assume $\\DG$ and $\\DB$ are independent of the\ninstance and of the concrete solution (costs of \\good\\ solutions are always\nchosen from $\\DG$, costs of \\bad\\ solutions are always chosen from $\\DB$).\n\nWe model noise in a generic way by defining a set of noise levels $\\mathcal{N}$\n(the concrete definition depends on the type of the noise, see~\\citep{jcss:2017}). For a fixed noise\nlevel $N\\in\\mathcal{N}$, we randomly generate an instance as follows. \\Good\\\nsolutions are drawn from a distribution with fixed mean $\\mu_\\mathrm{\\G}$ and fixed\nstandard deviation $\\sigma_\\mathrm{\\G}$.\n\\Bad\\ solutions are drawn from a distribution with mean $\\mu_\\mathrm{\\B}(N)$ and standard\ndeviation $\\sigma_\\mathrm{\\B}(N)$. The distributions of the \\bad\\ solutions are\nchosen in a way such that for every two noise levels $N,N'\\in\\mathcal{N}$ with\n$N'>N$, we have $\\mu_\\mathrm{\\B}(N')<\\mu_\\mathrm{\\B}(N)$ or\n$\\sigma_\\mathrm{\\B}(N')>\\sigma_\\mathrm{\\B}(N)$.\n\\nomenclature[D, 04c]{$N \\in \\mathcal{N}$}{noise levels for experiment\\nomnorefeq}%\n\n\\myremark Such assumptions on noise levels are justified by the fact that noise\nwould naturally imply either a smaller expected cost, or a higher standard\ndeviation, or both~--- resulting in a more aggressive ``deceiving'' of the\nalgorithm. See Figure~\\ref{fig:stable_and_unstable_solutions} for schematic\nillustration of this intuition.\n\nDue to its enormous theoretical and practical relevance, we present here the\nresults for the Gaussian noise model (for more noise settings, see~\\citep{jcss:2017}).\n \\Good\\ solutions are drawn from a Gaussian\ndistribution with mean $\\mu_{\\G}=1$ and standard deviation $\\sigma_{\\G}=1$. We\ndefine the noise levels $\\mathcal{N}$ in such a way that for each noise level\n$N\\in\\mathcal{N}$, \\bad\\ solutions are drawn from a Gaussian distribution with\nmean $\\mu_{\\B}(N)=10$ and standard deviation $\\sigma_{\\B}(N)=N$: $\\DG = \\mathrm{Norm}(1, 1)$ and\n$\\DB(N) = \\mathrm{Norm}(10, N^2)$.\n\n\\subsection{The Goal and Success Metrics}\n\nNow, our goal is the following: given two instances $X'$ and $X''$ generated by\nthe random process $PG(\\cdot)$ described above, our algorithm $\\mathscr{A}$ has\nto compute a set of solutions $\\hat \\C_\\mathscr{A}$ of candidates for solutions in\n$\\sgood$, from which it then picks a solution\nuniformly at random. The only knowledge of an\nalgorithm consists of the two cost vectors of $X'$ and $X''$ defined\nin~\\eqref{eq:generic_appch_cost_vector}. The algorithm cannot exploit the fact\nthat there are two categories of solutions, and in particular it has no\nknowledge about $\\DG$ and $\\DB$.\n\nSince we assume that a solution from $\\hat{\\mathcal{C}}_{\\mathscr{A}}$ is\npicked uniformly at random, we define the \\emph{success probability} of $\\mathscr{A}$\nwith input $X'$ and $X''$ as\n\\begin{align}\n  \\label{eq:uncert:prob_succ}\n  P_{\\mathscr{A}}(X',X'')\n    = \\frac{|{\\mathcal{C}}_\\mathscr{A}\\cap\\sgood|}{|{\\mathcal{C}}_\\mathscr{A}|}\n      \\text{, for a solving algorithm } \\mathscr{A}.\n\\end{align}\n\\nomenclature[D, 04d]{$P_{\\mathscr{A}}(X',X'')$}{success metric for experiment}%\n\nWe want to investigate how the success probabilities of the similarity algorithm\nproposed in this chapter evolves with increasing noise, and benchmark it against\nsome other algorithms. In this thesis, we present only a Joint Minimizer algorithms\n(see next section), but for the results produced on a more complete list of benchmarks\nwe refer the reader to~\\citep{jcss:2017}.\n\n\\subsection{Experimental Results}\n\\label{sec:continuous_noise}\n\n\\paragraph{Benchmark: joint cost minimizing}\nWhen only two instances are given, the most efficient and straightforward idea\nto find a solution that is likely to be good for a test instance is to compute\na solution~$c$ that minimizes the average cost, or equivalently, the joint cost\n$R(c, X')+R(c, X'')$. We refer to this method as the \\textit{Joint Minimizer}\nmethod in the plots below.\n\\index{Joint cost minimizer}\n\\index{Joint minimizer|see{Joint cost minimizer}}\n\n\\paragraph{Results}\n\nFor each noise level $N\\in\\mathcal{N}$, we perform the following\nexperiment: we generate $\\R=1000$ instance pairs $(X',X'')_{k\\in\\{1,\\ldots,\n\\R\\}}$ with noise level $N$ according to the $PG(\\cdot)$ process described in\nSection~\\ref{sec:gen_appch_pg}, and for each of these instance pairs we compute\n$P_\\mathscr{A}(X',X'')$ for all algorithms $\\mathscr{A}$. After that we set\n\\begin{align}\n  \\hat P_\\mathscr{A}(N) &\\coloneqq \\frac{1}{\\R} \\sum_{k=1}^{\\R} P_\\mathscr{A}(X',X'')\n\\end{align}\nto estimate the average success probability of the proposed methods in\ndependency of the noise level $N$. Unless otherwise stated, $\\mathcal{C}$\ncontains $n=1000$ solutions.\n\nIn our experiments, $\\R=1000$ repetitions turned out to be enough to exhibit\nthe behaviors of the methods. Preliminary experiments with $10000$ repetitions\ngave similar results: the rankings of the methods were the same, only the curves in\nthe plots appeared to be smoother.\n\nFigure~\\ref{fig:gnm} shows that the experimental results for\nGaussian noise show a strong indication that the approximation set-based similarity\napproach is very competitive against the joint cost minimization.\n\\begin{figure}[t!]\n  \\centering\n  \\begin{subfigure}[b]{.49\\textwidth}\n      \\includegraphics[width=\\linewidth]{figures/ch_generic_approach/gnm_g50_b950}\n      \\caption{$5\\%$ of solutions are \\good.}\n      \\label{fig:gnm_5}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[b]{.49\\textwidth}\n      \\includegraphics[width=\\linewidth]{figures/ch_generic_approach/gnm_g100_b900}\n      \\caption{$10\\%$ of solutions are \\good.}\n      \\label{fig:gnm_10}\n  \\end{subfigure}\n  \\\\[.5cm]\n  \\begin{subfigure}[b]{.49\\textwidth}\n      \\includegraphics[width=\\linewidth]{figures/ch_generic_approach/gnm_g200_b800}\n      \\caption{$20\\%$ of solutions are \\good.}\n      \\label{fig:gnm_20}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[b]{.49\\textwidth}\n      \\includegraphics[width=\\linewidth]{figures/ch_generic_approach/gnm_g500_b500}\n      \\caption{$50\\%$ of solutions are \\good.}\n      \\label{fig:gnm_50}\n  \\end{subfigure}\n  \\\\[.5cm]\n  \\caption{Experimental results where $5\\%$ \\textbf{(a)}, $10\\%$ \\textbf{(b)},\n    $20\\%$ \\textbf{(c)} and $50\\%$ \\textbf{(d)} of the solutions are \\good.\n    Total number of solutions equals $1000$.}\n  \\label{fig:gnm}\n\\end{figure}\nNote that the latter is a straightforward way to compute solutions, when only two\ninputs are provided. \n\n\\section{Finding Optimal Approximations Analytically}\n\\label{sec:analytic_solution}\n\n\\subsection{Theoretical Results}\n\nOne of our main assumptions was that the noise generating process is unknown to\nthe predicting algorithm $\\mathscr{A}$. It was also previously noted that the\ncrucial step of the whole approximation set-based approach consists in deriving\nthe appropriate specific formula or algorithm to calculate the\nsimilarity~\\eqref{eq:simple}. As a first step towards a formal analysis of the\nmodel discussed in the previous section, in this section we thoroughly\ninvestigate how the similarity~\\eqref{eq:simple} behaves in expectation (where\nthe expectation is computed over all pairs of instances generated by the random\nprocess $PG(\\cdot)$), i.e., we analyze the function\n\\begin{equation}\n  \\label{eq:oracle_similarity}\n  S_\\gamma^{\\mathrm{EXP}}=\\mathbb{E}_{X',X''\\sim PG} \\,\n    S_\\gamma(X',X'').\n\\end{equation}\n\\index{Similarity approach!Calibration assumption}\n\\index{Calibration assumption|see{Similarity approach}}\nFor simplicity we introduce the \\emph{calibrating assumption} that the minimum\nsolutions of both instances $X'$ and $X''$ have the same cost $m$:\n\\begin{equation}\\label{eq:gen_appch_calibrating_assumption}\n  \\min_c R(c, X') \\approx \\min_c R(c, X'') \\approx m.\n\\end{equation} \nWithout this assumption our analysis would still be possible, but it would be\nmore technical. Notice that the assumption does not imply that the minimum\nsolutions themselves are the same: in general, it holds that\n\\begin{equation}\n   \\arg \\min_c R(c, X') \\ne \\arg \\min_c R(c, X''),\n\\end{equation} \ni.e. minimum costs are not necessarily attained on the same solution.\n\n\\index{Similarity approach!Theoretical estimator}\n\\begin{theorem}\n\\label{thm:oracle_similarity}\nLet $\\gamma>0$, $V = |\\mathcal{C}_\\gamma(X')\\cap \\mathcal{C}_\\gamma(X'')|$,\n$W = |\\mathcal{C}_\\gamma(X')|\\cdot |\\mathcal{C}_\\gamma(X'')|$, $m$ be the minimum cost of a\nsolution in both $X'$ and $X''$ (i.e., the calibrating assumption is\nsatisfied), and $\\FG$ and $\\FB$ denote the cumulative density functions of the\n\\good\\ and the \\bad\\ solutions, respectively, evaluated at $m+\\gamma$. Then, the\nexpected similarity~\\eqref{eq:oracle_similarity} can be approximated by the\nestimated similarity\n\\begin{align}\n  \\label{eq:esim}\n  S_\\gamma^{\\mathrm{EXP}} \\sim \\hat S_\\gamma \\coloneqq |\\mathcal{C}|\\left(\n    \\frac{\\Expct[V]}{\\Expct[W]} -\n    \\frac{\\Cov(V,W)}{\\Expct[W]^2} + \\frac{\\Var[W] \\cdot \\Expct[V]}{\\Expct[W]^3}\\right)\n\\end{align}\n\\nomenclature[D, 05]{$S_\\gamma^{\\mathrm{EXP}}$, $\\hat S_\\gamma$}{theoretical estimator of similarity}%\nwhere\n\\begin{align}\n  \\label{eq:esim:ev}\n  \\Expct[V] &= \\g\\FG^2 + \\b\\FB^2, \\\\\n  \\label{eq:esim:ew}\n  \\Expct[W] &= (\\g\\FG + \\b\\FB)^2, \\\\\n  \\label{eq:esim:cov}\n  \\Cov(V, W) &= \\g\\FG^2(1 - \\FG^2) + 2\\g(\\g-1) \\FG^3(1 - \\FG) \\notag \\\\\n    &\\quad + 2\\g\\b\\FG^2\\FB (1 - \\FG) + 2\\g\\b\\FG\\FB^2(1 - \\FB) \\notag \\\\\n    &\\quad + \\b\\FB^2(1 - \\FB^2) + 2\\b(\\b-1) \\FB^3(1 - \\FB), \\text{ and} \\\\\n  \\label{eq:esim:var}\n  \\Var[W] &= \\g^2\\FG^2(1- \\FG^2) + 2\\g^2(\\g-1)\\FG^3(1 - \\FG) \\notag\\\\\n    &\\quad + 2\\g\\b(\\b - 1) \\FG \\FB^2 (1 - \\FG) \\notag\\\\\n    &\\quad + 2\\g(\\g - 1)\\b \\FG^2 \\FB (1 - \\FB) \\notag\\\\\n    &\\quad + 2\\g\\b \\FG \\FB (1 - \\FG\\FB) \\notag\\\\\n    &\\quad + \\b^2 \\FB^2 (1 - \\FB^2) + 2\\b^2(\\b-1) \\FB^3 (1 - \\FB) \\notag\\\\\n    &\\quad + 4 \\g^2 \\b \\FG^2 \\FB (1 - \\FG) + 4\\g\\b^2 \\FG \\FB^2 (1 - \\FB).\n\\end{align}\n\\end{theorem}\n\n\\paragraph{Proof of Theorem~\\ref{thm:oracle_similarity}}\nTo make this proof more readable, we break it down into several\nsteps.\n\\begin{itemize}\n  \\item[1)] {\\em Preliminaries.}\n    Let $m=\\min_{c \\in \\mathcal{C}} R(c, X')=\\min_{c \\in \\mathcal{C}} R(c, X'')$. Let\n    $c_i$, $i\\in\\{1,\\ldots,\\g\\}$ denote the solutions in $\\sgood$ and\n    $\\bar c_i$, $i\\in\\{1,\\ldots,\\b\\}$ denote the solutions in $\\sbad$. We define\n    \\begin{align*}\n      A'_{i, \\gamma} &= \\mathbbm{1}\\{R(c_i,X') \\le m+\\gamma\\}, \\quad 1 \\le i \\le \\g \\\\\n      A''_{i, \\gamma} &= \\mathbbm{1}\\{R(c_i,X'') \\le m+\\gamma\\}, \\quad 1 \\le i \\le \\g \\\\\n      B'_{j, \\gamma} &= \\mathbbm{1}\\{R(\\bar c_j,X') \\le m+\\gamma\\}, \\quad 1 \\le j \\le \\b \\\\\n      B''_{j, \\gamma} &= \\mathbbm{1}\\{R(\\bar c_j,X'') \\le m+\\gamma\\}, \\quad 1 \\le j \\le \\b.\n    \\end{align*}\n    \\nomenclature[A, 00]{$\\mathbbm{1}\\{\\cdot\\}$}{indicator function\\nomnorefeqpage}%\n    Now the components of the similarity~\\eqref{eq:similarity} can be\n    expressed as\n    \\begin{align*}\n      |\\mathcal{C}_\\gamma(X')\\cap \\mathcal{C}_\\gamma(X'')|\n        &= \\sum_{i = 1}^{\\g} A'_{i,\\gamma} A''_{i,\\gamma} +\n          \\sum_{j = 1}^{\\b} B'_{j,\\gamma} B''_{j,\\gamma}, \\\\\n      |\\mathcal{C}_\\gamma(X')|\n        &= \\sum_{i = 1}^{\\g} A'_{i,\\gamma} + \\sum_{j = 1}^{\\b} B'_{j,\\gamma}, \\\\\n      |\\mathcal{C}_\\gamma(X'')|\n        &= \\sum_{i = 1}^{\\g} A''_{i,\\gamma} + \\sum_{j = 1}^{\\b} B''_{j,\\gamma}.\n    \\end{align*}\n    For the rest of this proof we will simplify the notation as follows:\n    1)~$\\gamma$~is omitted in the subscript because we can assume it to be\n    the same throughout all considerations, 2) the limits in the sums are\n    omitted; for \\good\\ solutions we\n    always sum up to $\\g$ and for \\bad\\ solutions to $\\b$, and 3) by $\\FG$ and\n    $\\FB$ we denote the cumulative density functions of \\good\\ and \\bad\\\n    distributions, respectively, evaluated at $m+\\gamma$:\n    \\begin{equation}\n      \\FG \\coloneqq \\FG(m + \\gamma), \\qquad \\FB \\coloneqq \\FB(m + \\gamma).\n    \\end{equation}\n    Observe that 1) $\\Expct[A'_i]=\\Expct[A''_i]=\\FG$ and $\\Expct[B'_j]=\\Expct[B''_j]\n    =\\FB$, 2) the random variables in $\\{A'_i\\}_i \\cup \\{A''_j\\}_j \\cup \\{B'_k\\}_k\n    \\cup \\{B''_\\ell\\}_\\ell$ are jointly independent, and 3) $(A'_i)^2=A'_i$,\n    $(A''_i)^2=A''_i$, $(B'_j)^2=Y_j$ and $(B''_j)^2=Y_j$ because these are\n    indicators. Also, remember that for jointly independent indicator random\n    variables $Z_1, Z_2, Z_3$ with $\\Expct[Z_i] = z_i$ we have\n    \\nomenclature[B, 00]{$\\Expct[\\cdot]$}{expected value\\nomnorefeqpage}%\n    \\nomenclature[B, 00]{$\\Var[\\cdot]$}{variance\\nomnorefeqpage}%\n    \\begin{align}\n      \\Cov(Z_1, Z_2)\n        &= z_1 z_2 (1 - z_1 z_2) \\label{eq:ag:covariance_general_2} \\\\\n      \\Cov(Z_1 Z_2, Z_1 Z_3 )\n        &= z_1 z_2 z_3 (1 - z_1) \\label{eq:ag:covariance_general_1}\n    \\end{align}\n  \\item[2)] {\\em Taylor expansion of the expected similarity.}\n    A second-order Taylor approximation of $\\Expct[V/W]$ gives\n    \\begin{align}\n      \\tag{\\ref{eq:esim}}\n      \\Expct\\biggl[\\frac{V}{W}\\biggl]\n        \\approx \\frac{\\Expct[V]}{\\Expct[W]} -\n        \\frac{\\Cov(V,W)}{\\Expct[W]^2} +\n        \\frac{\\Var[W] \\cdot \\Expct[V]}{\\Expct[W]^3}.\n    \\end{align}\n    Remember that $V$ denotes the size of the intersection while $W$ is the\n    product of the approximation set sizes. In the following, we will\n    analyze each term of~\\eqref{eq:esim} separately.\n  \\item[3)] {\\em Expected values of $V$ and $W$.}\n    \\begin{align*}\n      \\tag{\\ref{eq:esim:ev}}\n      \\Expct[V] = \\sum_i \\Expct[A'_i] \\cdot \\Expct[A''_i] +\n        \\sum_j \\Expct[B'_j] \\cdot \\Expct[B''_j] = \\g\\FG^2 + \\b\\FB^2.\n    \\end{align*}\n    Taking the independence of the random variables into account, for\n    $\\Expct[W]$ we obtain\n    \\begin{align*}\n      \\tag{\\ref{eq:esim:ew}}\n      \\Expct[W]\n        = \\Expct\\Bigl[\\sum_i A'_i + \\sum_j B'_j\\Bigr] \\cdot\n          \\Expct\\Bigl[\\sum_i A''_i + \\sum_j B''_j\\Bigr]\n        = ( \\g \\FG + \\b \\FB )^2.\n    \\end{align*}\n  \\item[4)] {\\em Analyzing the covariance of $V$ and $W$.}\n    Remember that\n    \\begin{align}\n      V &= \\sum_i A'_i A''_i + \\sum_i B'_i B''_i, \\\\\n      W &= \\sum_{j,k} A'_j A''_k + \\sum_{i,j} A'_j B''_k +\n        \\sum_{j,k} B'_j A''_k + \\sum_{j,k} B'_j B''_k,\n        \\label{eq:ag:w_representation}\n    \\end{align}\n    hence\n    \\begin{align}\n      \\Cov(V, W)\n        &= \\sum_{i,j,k} \\Cov( A'_i A''_i, A'_j A''_k ) + \\sum_{i,j,k} \\Cov( A'_i A''_i, A'_j B''_k ) \\notag \\\\\n        &+ \\sum_{i,j,k} \\Cov( A'_i A''_i, B'_j A''_k ) + \\sum_{i,j,k} \\Cov( A'_i A''_i, B'_j B''_k ) \\notag \\\\\n        &+ \\sum_{i,j,k} \\Cov( B'_i B''_i, A'_j A''_k ) + \\sum_{i,j,k} \\Cov( B'_i B''_i, A'_j B''_k ) \\notag \\\\\n        &+ \\sum_{i,j,k} \\Cov( B'_i B''_i, B'_j A''_k ) + \\sum_{i,j,k} \\Cov( B'_i B''_i, B'_j B''_k )\n    \\end{align}\n    We will now analyze each of the single terms.\n    \\begin{itemize}\n      \\item[$\\bullet$]\n        In the first term $\\sum \\Cov( A'_i A''_i, A'_j A''_k )$\n        only the summands with $j=i$ or $k=i$ are non-zero, hence we\n        obtain\n        \\begin{align}\n          \\sum_{i,j,k} &\\Cov( A'_i A''_i, A'_j A''_k )\n             = \\sum_i \\Cov( A'_i A''_i, A'_i A''_i) \\notag \\\\\n            &\\hspace{1cm}+ \\sum_{i \\ne j} \\Bigl[ \\Cov( A'_i A''_i, A'_i A''_j)\n            + \\Cov( A'_i A''_i, A'_j A''_i)\\Bigr] \\notag \\\\\n            &= \\sum_i \\Cov( A'_i A''_i, A'_i A''_i)\n            + 2 \\sum_{i \\ne j} \\Cov( A'_i A''_i, A'_i A''_j), \\notag\\\\\n            &= \\g \\FG^2(1 - \\FG^2)+2\\g(\\g-1) \\FG^3 (1 - \\FG),\n            \\label{eq:ag:comp_covariance_4}\n        \\end{align}\n        where the last equality holds due\n        to~\\eqref{eq:ag:covariance_general_2}\n        and~\\eqref{eq:ag:covariance_general_1}.\n      \\item[$\\bullet$]\n        The next two terms $\\sum \\Cov( A'_i A''_i, A'_j B''_k )$ and\n        $\\sum \\Cov( A'_i A''_i, B'_j A''_k )$ are equal to each other\n        (due to the symmetry of $A'$ and $A''$), so their sum resolves\n        to\n        \\begin{equation}\n          2 \\sum_{i,k} \\Cov( A'_i A''_i, A'_i B''_k )\n            \\stackrel{\\text{\\eqref{eq:ag:covariance_general_1}}}{=}\n            2 \\g \\b \\FG^2 \\FB ( 1 - \\FG). \\label{eq:ag:comp_covariance_2}\n        \\end{equation}\n      \\item[$\\bullet$]\n        The next two terms $\\sum \\Cov( A'_i A''_i, B'_j B''_k )$\n        and $\\sum \\Cov( B'_i B''_i, A'_j A''_k )$ are both zero\n        due to the independence of $A'_i A''_i$ and $B'_j B''_k$.\n      \\item[$\\bullet$]\n        The next two terms $\\sum \\Cov( B'_i B''_i, A'_j B''_k )$\n        and $\\sum \\Cov( B'_i B''_i, B'_j A''_k )$ can be computed in\n        exactly the same way as~\\eqref{eq:ag:comp_covariance_2} where\n        both $\\FG$ and $\\FB$ as well as $\\g$ and $\\b$ are interchanged.\n        Hence, their sum equals\n        \\begin{equation*}\n          2 \\sum_{i,k} \\Cov( B'_i B''_i, B'_i A''_k )\n            \\stackrel{\\text{\\eqref{eq:ag:covariance_general_1}}}{=}\n            2 \\g\\b \\FG \\FB^2 ( 1 - \\FB).\n        \\end{equation*}\n      \\item[$\\bullet$]\n        The last term $\\sum \\Cov( B'_i B''_i, B'_j B''_k )$ is computed\n        similar as~\\eqref{eq:ag:comp_covariance_4},\n        performing the above-mentioned replacements, hence\n        \\begin{align*}\n          \\sum_{i,j,k} &\\Cov( B'_i B''_i, B'_j B''_k )\n            = \\b \\FB^2(1 - \\FB^2) + 2\\b(\\b-1) \\FB^3 (1 - \\FB).\n        \\end{align*}\n    \\end{itemize}\n  \\item[5)] {\\em Analyzing the variance of $W$.}\n    Finally we compute $\\Var[W] = \\Cov(W, W)$. When $W$ is expressed\n    as~\\eqref{eq:ag:w_representation}, we obtain\n    \\begin{align*}\n      \\Cov(W, W)\n      &= \\sum_{i,j,k,\\ell} \\Cov(A'_i A''_j, A'_k A''_\\ell) + \\sum_{i,j,k,\\ell} \\Cov(A'_i B''_j, A'_k B''_\\ell) \\\\\n      &+\\sum_{i,j,k,\\ell} \\Cov(B'_i A''_j, B'_k A''_\\ell) + \\sum_{i,j,k,\\ell} \\Cov(B'_i B''_j, B'_k B''_\\ell) \\\\\n      &+ 2 \\sum_{i,j,k,\\ell} \\Cov(A'_i A''_j, A'_k B''_\\ell) + 2 \\sum_{i,j,k,\\ell} \\Cov(A'_i A''_j, B'_k A''_\\ell) \\\\\n      &+ 2 \\sum_{i, j, k, \\ell} \\Cov(A'_i A''_j, B'_k B''_\\ell) + 2 \\sum_{i,j,k,\\ell} \\Cov(A'_i B''_j, B'_k A''_\\ell) \\\\\n      &+ 2 \\sum_{i,j,k,\\ell} \\Cov(A'_i B''_j, B'_k B''_\\ell) + 2 \\sum_{i,j,k,\\ell} \\Cov( B'_i A''_j, B'_k B''_\\ell).\n    \\end{align*}\n    As before we analyze each of these terms separately.\n    \\begin{itemize}\n      \\item[$\\bullet$]\n        The first term $\\sum \\Cov(A'_i A''_j, A'_k A''_\\ell)$ can be\n        expressed as\n        \\begin{align*}\n          &\\sum_{i} \\Cov(A'_i A''_i, A'_i A''_i)\n            + 4 \\sum_{i\\ne j} \\Cov(A'_i A''_i, A'_i A''_j) \\\\\n          &+ 2\\hspace{-4mm}\\sum_{i \\ne j, i \\ne k, j \\ne k}\\hspace{-4mm} \\Cov( A'_i A''_j, A'_i A''_k)\n            + \\sum_{i \\ne j} \\Cov( A'_i A''_j, A'_i A''_j)\n        \\end{align*}\n        where\n        \\begin{align*}\n          \\sum_{i} \\Cov(A'_i A''_i, A'_i A''_i) &= \\g\\FG^2(1 - \\FG^2), \\\\\n          4 \\sum_{i\\ne j} \\Cov(A'_i A''_i, A'_i A''_j) &= 4\\g(\\g-1)\\FG^3(1-\\FG), \\\\\n          2\\hspace{-4mm}\\sum_{i \\ne j, i \\ne k, j \\ne k}\\hspace{-4mm}\n              \\Cov( A'_i A''_j, A'_i A''_k) &= 2\\g(\\g-1)(\\g-2) \\FG^3( 1- \\FG), \\\\\n          \\sum_{i \\ne j} \\Cov( A'_i A''_j, A'_i A''_j) &= \\g(\\g-1)\\FG^2 ( 1 - \\FG^2),\n        \\end{align*}\n        and therefore\n        \\begin{equation}\n          \\label{eq:ag:comp_covariance_6}\n          \\sum_{i,j,k,\\ell}\\hspace{-1mm} \\Cov(A'_i A''_j, A'_k A''_\\ell)\n            = \\g \\FG^2( 1- \\FG^2) + 2 \\g^2 (\\g-1) \\FG^3 ( 1- \\FG).\n        \\end{equation}\n      \\item[$\\bullet$]\n        The next two terms $\\sum \\Cov(A'_i B''_j, A'_k B''_\\ell)$ and\n        $\\sum \\Cov(B'_i A''_j, B'_k A''_\\ell)$ are equal due to the\n        symmetry in instances, hence their sum equals\n        \\begin{align*}\n          %&2 \\sum_{i, j, k, \\ell} \\Cov(A'_i B''_j, A'_k B''_\\ell) \\\\\n          &2 \\sum_{\\substack{i \\\\ j \\ne k}} \\Cov(A'_i B''_j, A'_i B''_k)\n            + 2 \\sum_{\\substack{i \\\\ j \\ne k}} \\Cov(A'_j B''_i, A'_k B''_i) \\\\\n          &\\quad + 2 \\sum_{i, j} \\Cov(A'_i B''_j, A'_i B''_j),\n        \\end{align*}\n        where the the terms are computed as\n        \\begin{align*}\n          2 \\sum_{\\substack{i \\\\ j \\ne k}} \\Cov(A'_i B''_j, A'_i B''_k)\n            &\\stackrel{\\text{\\eqref{eq:ag:covariance_general_1}}}{=}\n              2 \\g\\b(\\b-1) \\FG \\FB^2 (1 - \\FG), \\\\\n          2 \\sum_{\\substack{i \\\\ j \\ne k}} \\Cov(A'_j B''_i, A'_k B''_i)\n            &\\stackrel{\\text{\\eqref{eq:ag:covariance_general_1}}}{=}\n              2 \\g (\\g-1) \\b \\FG^2 \\FB (1 - \\FB), \\\\\n          2 \\sum_{i, j} \\Cov(A'_i B''_j, A'_i B''_j)\n            &\\stackrel{\\text{\\eqref{eq:ag:covariance_general_2}}}{=}\n              2\\g\\b \\FG \\FB ( 1 - \\FG \\FB).\n        \\end{align*}\n      \\item[$\\bullet$]\n        The next term $\\sum \\Cov(B'_i B''_j, B'_k B''_\\ell)$ is computed\n        analogically to~\\eqref{eq:ag:comp_covariance_6}\n        where \\good\\ and \\bad\\ solutions are interchanged, resulting in\n        \\begin{align*}\n          \\sum_{i,j,k,\\ell} &\\Cov(B'_i B''_j, B'_k B''_\\ell)\n            = \\b^2 \\FB^2 ( 1 - \\FB^2) + 2 \\b^2(\\b-1) \\FB^3 (1 - \\FB).\n        \\end{align*}\n      \\item[$\\bullet$]\n        The next terms $2\\sum \\Cov(A'_i A''_j, A'_k B''_\\ell)$ and\n        $2\\sum \\Cov(A'_i A''_j, B'_k A''_\\ell)$ are equal due to the\n        symmetry of the instances, hence their sum is\n        \\begin{align}\\label{eq:ag:comp_covariance_7}\n          4 \\sum_{i,j,k,\\ell} \\Cov(A'_i A''_j, A'_k B''_\\ell)\n            &= 4 \\sum_{i,j,k} \\Cov(A'_i A''_j, A'_i B''_k) \\notag \\\\\n            &\\stackrel{\\text{\\eqref{eq:ag:covariance_general_1}}}{=} 4 \\g^2 \\b \\FG^2 \\FB ( 1 - \\FG ).\n        \\end{align}\n      \\item[$\\bullet$]\n        The next terms $2\\sum \\Cov(A'_i A''_j, B'_k B''_\\ell)$ and\n        $2\\sum \\Cov(A'_i B''_j, B'_k A''_\\ell)$ are both equal to zero\n        due to the independence of $A'_i A''_j$ and $B'_k B''_\\ell$, and\n        of $A'_i B''_j$ and $A'_k A''_\\ell$.\n      \\item[$\\bullet$]\n        The last terms $2\\sum \\Cov(A'_i B''_j, B'_k B''_\\ell)$ and\n        $2\\sum \\Cov(B'_i A''_j, B'_k B''_\\ell)$ are equal due to the\n        symmetry the instances hence their sum can be computed\n        analogically to~\\eqref{eq:ag:comp_covariance_7} where \\good\\ and\n        \\bad\\ solutions are interchanged. Hence, we obtain\n        \\begin{equation*}\n          4 \\sum_{i,j,k,\\ell} \\Cov(B'_i A''_j, B'_k B''_\\ell)\n            = 4 \\g \\b^2 \\FG \\FB^2 ( 1 - \\FB).\n            \\qedhere\n        \\end{equation*}\n        \\nomenclature[B, 00]{$\\Cov(\\cdot, \\cdot)$}{covariance\\nomnorefeqpage}%\n    \\end{itemize}\n\n\\end{itemize}\n \nThe proof is thus finished.\n\\QEDA\n\n\\subsection{Experimental Results}\nWe now provide both positive and negative experimental results which highlight\nthe scope of applicability of such similarity estimation.  We performed an\nexperimental evaluation using Gaussian noise in a setting similar to the one in\nSections~\\ref{sec:gen_appch_pg}--\\ref{sec:continuous_noise}: parameters were set\nto $\\g=100$, $\\b=900$, $\\mu_{\\mathrm{\\G}}=1$, $\\sigma_{\\mathrm{\\G}}=1$, $\\mu_{\\mathrm{\\B}}=10$,\n$\\sigma_{\\mathrm{\\B}}\\in\\{0,0.1,\\ldots,10\\}$.\n% \nThe only adjustment on had to make was a slightly changed instance generator due\nto the calibrating assumption~\\eqref{eq:gen_appch_calibrating_assumption}: since\nthe minima of both instances have to be sufficiently close to each other, the\nproblem generation process disregarded each pair of instances for which the\nminima $m'$ and $m''$ differed by more than $\\varepsilon=10^{-4}$, and\nrepeatedly generated a new pair until $|m'-m''|\\le\n\\varepsilon$. \n\nFor each successful (i.e. not rejected due to calibrating assumption) instance\npair $(X',X'')$, we computed similarity~\\eqref{eq:simple} and\nestimated similarity~\\eqref{eq:esim}, where the latter was calibrated with\n$m=(m'+m'')/2$. We repeated the process $\\R=1000$ times and calculated the\naverage similarity\n\\begin{equation}\n  \\bar S_\\gamma=\\frac{1}{\\R}\\sum_{k=1}^\\R S_\\gamma(X',X''),\n\\end{equation}\nand compared it to the estimated similarity~\\eqref{eq:esim}. We note that we did\nnot compute the average estimated similarity over all instance pairs, but\ninstead calibrated Equation~\\eqref{eq:esim} directly using the average minimum\ncost of the instance pairs, i.e., using $m=\\frac{1}{\\R}\\sum_{k=1}^\\R\n(m'^k+m''^k)/2$ where $m'^k=\\min_{c \\in \\mathcal{C}} R(c, X'^k)$ and $m''$ is\ndefined respectively.\n\nFigure~\\ref{fig:realVsEstimatedSimilarities} shows the plots of $\\hat S_\\gamma$ and\n$\\bar S_\\gamma$ defined above for two noise levels: $\\sigma_{\\mathrm{\\B}}=1$ and for $\\sigma_{\\mathrm{\\B}}=5$.\n\\begin{figure}[ht!]\n  \\centering\n  \\begin{subfigure}[b]{.6\\textwidth}\n      \\includegraphics[width=\\linewidth]{figures/ch_generic_approach/realVsEstimatedSimilarities_sb1}\n      \\caption{}\n  \\end{subfigure}\n  \\\\[.5cm]\n  \\begin{subfigure}[b]{.6\\textwidth}\n      \\includegraphics[width=\\linewidth]{figures/ch_generic_approach/realVsEstimatedSimilarities_sb5}\n      \\caption{}\n  \\end{subfigure}\n  \\\\[.5cm]\n  \\caption{Average vs. estimated similarity for $\\sigma_{\\mathrm{\\B}}=1$ \\textbf{(a)}, and for\n    $\\sigma_{\\mathrm{\\B}}=5$ \\textbf{(b)}.}\n  \\label{fig:realVsEstimatedSimilarities}\n\\end{figure}\nWe see that the estimated similarity matches the average similarity relatively\nwell, especially for larger values of $\\gamma$. Although the discrepancy grows\nwith the noise (which is natural due to the Taylor expansion used in the proof),\nprobably the most important thing to note is that the positions of the $\\gamma^*$\ncomputed based on $\\hat S_\\gamma$ and $\\bar S_\\gamma$ remain the same.\n\n% \\agcomm{till here}\n\n% For $\\sigma_{\\mathrm{\\B}}=5$, the situation is more difficult to analyze. However,\n% Figure~\\ref{fig:realVsEstimatedSimilarities}b shows that the maximum of the\n% estimated similarity is larger than the estimated similarity at $\\gamma=0$, and\n% it also shows that the values $\\gamma$ where the average and the estimated\n% similarity, respectively, are maximized coincide well. Therefore the\n% aforementioned problem of an empty intersection does not occur.\n\n% As before we computed for both methods the\n% intersection $\\mathcal{C}_{\\gamma^*}(X')\\cap \\mathcal{C}_{\\gamma^*}(X'')$ and\n% evaluated the resulting success probability using the definition\n% in~\\eqref{eq:uncert:prob_succ}. \n% Figure~\\ref{fig:realVsEstimated} shows that for\n% high noise, \\tESIM\\ has a higher chance to pick a \\good\\ solution than \\tSIM\\\n% and \\tMR\\ which is not surprising because it has knowledge about the underlying\n% process.\n% \\begin{figure}[t!]\n%   \\centering\n%   \\begin{subfigure}[b]{.85\\textwidth}\n%       \\includegraphics[width=\\linewidth]{figures/ch_generic_approach/realVsEstimatedSuccessProbabilities}\n%   \\end{subfigure}\n%   \\\\[.5cm]\n%   \\begin{subfigure}[b]{.85\\textwidth}\n%       \\includegraphics[width=\\linewidth]{figures/ch_generic_approach/realVsEstimatedGamma}\n%   \\end{subfigure}\n%   \\\\[.5cm]\n%   \\caption{Comparison of the success rates of \\tMR\\ and \\tSIM\\ with the one of\n%     the estimated similarity (a), and a comparison of the values $\\gamma^*$\n%     that \\tMR, \\tSIM\\ and \\tESIM\\ compute.}\n%   \\label{fig:realVsEstimated}\n% \\end{figure}\n\n% The weak performance of the estimated similarity for small noise seems to be\n% more surprising. To understand why this happens, consider\n% Figure~\\ref{fig:realVsEstimated}b\\AGcomm{Fig ref broken} which shows the average value of $\\gamma^*$\n% that each method computes. Observe that for $\\sigma_{\\mathrm{\\B}}<2.5$, the average value of\n% $\\gamma^*$ that the estimated similarity computes is below the one that\n% \\tMR\\ computes, and since \\tMR\\ computes the\n% smallest $\\gamma$ for which the intersection of both $\\gamma$-approximation sets\n% is non-empty, the estimated similarity nearly always underestimates $\\gamma$. To\n% understand why this happens, we investigate the situation for $\\sigma_{\\mathrm{\\B}}=1$ (low\n% noise) and $\\sigma_{\\mathrm{\\B}}=5$ (moderate noise). For each of the $\\R=1000$ experiments,\n% we compared the values of $\\gamma^*$ that \\tSIM\\ computes with the\n% ones of the estimated similarity. Figure~\\ref{fig:realVsEstimatedPairs} shows\n% the distribution of the points $(\\gamma_\\SIM^*,\\gamma_\\ESIM^*)$ where a point is\n% red if \\tSIM\\ outperformed \\tESIM, and green\n% otherwise.\n% \\begin{figure}[t]\n%   \\centering\n%   \\begin{minipage}[t]{\\textwidth}\n%     \\small\n%     \\centering\n%     \\includegraphics[width=.9\\linewidth]{figures/ch_generic_approach/realVsEstimatedGamma_sb1}\n    \n%     (a)\n%   \\end{minipage}\\\\\n%   \\begin{minipage}[t]{\\textwidth}\n%     \\small\n%     \\centering\n%     \\includegraphics[width=.9\\linewidth]{figures/ch_generic_approach/realVsEstimatedGamma_sb5}\n    \n%     (b)\n%   \\end{minipage}\n%   \\caption{Each point corresponds to the outcome of one experiment, where the\n%     $x$-coordinate denotes the value $\\gamma^*$ computed by \\tSIM\\ and the\n%     $y$-coordinate denotes the value $\\gamma^*$ computed by \\tESIM. A point\n%     is red if \\tSIM\\ outperformed \\tESIM, and green otherwise. The\n%     experiments were performed for $\\sigma_{\\mathrm{\\B}}=1$ (a), and for $\\sigma_{\\mathrm{\\B}}=5$\n%     (b).}\n%   \\label{fig:realVsEstimatedPairs}\n% \\end{figure}\n% We see that for low noise, the estimated similarity nearly always\n% underestimates $\\gamma^*$. On the other hand, the choice of $\\gamma^*$ for\n% moderate noise is often better than the one by \\tSIM. Hence, it\n% seems that \\tSIM\\ is still too much influenced by the noise in the\n% instances.\n\nTo summarize, we considered the expected similarity of two instances from the\nsame generator, and we derived an estimation for it that only depends on the\nnumber of \\good\\ and \\bad\\ solutions, and on the respective cumulative density\nfunctions. Our experiments showed that our estimation approximates the expected\nsimilarity well when the noise is not too low. \n%\nOur experiments also showed that the $\\gamma^*$ that maximizes the estimated\nsimilarity does indeed help to identify \\good\\ solutions. In particular,\nchoosing a solution from the intersection of the corresponding\n$\\gamma^*$-approximation is a promising way of robust solving. One of the\npossible steps in this direction should be to analyze how many \\good\\ and how\nmany \\bad\\ solutions this intersection contains in expectation.\n\n\\section{Gibbs Relaxation of the Approximation Set-Based Approach}\n\\label{sec:gibbs_relaxation_of_sim}\n\n\\subsection{Approximation Sets with Gibbs Weights}\n\\label{sec:gibbs_relaxation_of_sim_weights}\n\n\\index{Approximation Set Coding!Gibbs relaxation}\n\\index{Gibbs relaxation|see{Approximation Set Coding}}\n\\nomenclature[D, 06]{$w^G_\\beta(c, X)$}{Gibbs weights\\nomnorefeq}%\n\\nomenclature[D, 06a]{$\\beta$}{inverse temperature\\nomnorefeq}%\n\\citet{conf/isit/Buhmann10}, in addition to the approximation set-based\napproach, introduced its Gibbs-relaxed version which we give in this section.\nThe idea (we adapt it for the sake of notation alignment with the material of\nthis chapter) is as follows: using the maximum entropy principle\n(Section~\\ref{sec:background_max_entropy}) by~\\citet{Jaynes82} from statistical\nphysics~\\citep[see also][]{book/MezardM09}, for a real number $\\beta \\ge 0$, an\ninstance~$X$ and a solution~$c$, the Gibbs weight \\index{Gibbs weights} of $c$\nis defined as $w^G_\\beta(c, X)\n\\coloneqq \\exp(-\\beta R(c, X))$. Now one computes a value $\\beta^*$ that\nmaximizes\n\\begin{align}\n  \\label{eq:gibbs_realaxation}\n  \\beta^* = \\arg \\max_{\\beta > 0}\n    \\log \\biggl(|\\C| \\frac{\\sum_{c\\in\\mathcal{C}}\\big(w^G_\\beta(c,X')\\cdot w^G_\\beta(c,X'')\n      \\big)}{\\big(\\sum_{c\\in\\mathcal{C}} w^G_\\beta(c,X')\\big)\\cdot\n      \\big(\\sum_{c\\in\\mathcal{C}} w^G_\\beta(c,X'')\\big)} \\biggr),\n\\end{align}\n\\nomenclature[D, 06c]{$\\beta^*$}{optimal inverse temperature}%\nor, since the optimization goal is the same (see remark\nafter~\\eqref{eq:similarity_maximization_objective}), maximizes the ratio\n\\begin{align}\n  \\label{eq:gibbs_similarity_maximization_objective}\n  \\beta^* = \\arg \\max_{\\beta > 0}\n    \\frac{\\sum_{c\\in\\mathcal{C}}\\big(w^G_\\beta(c,X')\\cdot w^G_\\beta(c,X'')\n      \\big)}{\\big(\\sum_{c\\in\\mathcal{C}} w^G_\\beta(c,X')\\big)\\cdot\n      \\big(\\sum_{c\\in\\mathcal{C}} w^G_\\beta(c,X'')\\big)},\n\\end{align}\nand then samples a solution $c$ from the whole solution space $\\mathcal{C}$ with\nprobability \n\\[\n  p_\\beta(c) = \\frac{w^G_{\\beta^*}(c,X')\\cdot w^G_{\\beta^*}(c,X'')}{\\sum_{c'\\in\n\\mathcal{C}} (w^G_{\\beta^*}(c',X')\\cdot w^G_{\\beta^*}(c',X''))}.\n\\]\nWe refer to this as the \\textit{Gibbs relaxation of approximation set-based\napproach}.\n\n\\subsection{Relation of Similarity and Gibbs Similarity}\n\nInterestingly, the classical approximation set-based\napproach~\\eqref{eq:similarity_maximization_objective} and its Gibbs\nrelaxation~\\eqref{eq:gibbs_similarity_maximization_objective} have a clear\nrelation: for a number $\\gamma\\ge 0$, an instance $X$ and a solution~$c$ we\ndefine a 0-1-weight $w^\\Ind_\\gamma(c, X)$ that is $1$ if and only if $R(c,\nX)\\le R(c^\\perp,X) +\n\\gamma$, and 0 otherwise. It is easy to see that\n\\begin{align}\n  \\label{eq:approximation_set_sum}\n  |{\\mathcal{C}_\\gamma}(X')| &= \\sum_{c\\in\\mathcal{C}} w^\\Ind_\\gamma(c, X')  \\notag \\\\\n  |{\\mathcal{C}_\\gamma}(X'')| &= \\sum_{c\\in\\mathcal{C}} w^\\Ind_\\gamma(c, X'') \\notag \\\\\n  |{\\mathcal{C}_\\gamma}(X')\\cap {\\mathcal{C}_\\gamma}(X'')| &= \\sum_{c\\in\\mathcal{C}}\n    \\big(w^\\Ind_\\gamma(c,X')\\cdot w^\\Ind_\\gamma(c,X'')\\big).\n\\end{align}\n\\nomenclature[D, 06c]{$w^\\Ind_\\gamma(c, X)$}{indicator weights}%\nWith these equalities it follows that the objective of maximizing\n$S_\\gamma(X',X'')$ in~\\eqref{eq:similarity_maximization_objective} corresponds\nto the one of~\\eqref{eq:gibbs_similarity_maximization_objective} in which the\n0-1-weights $w^{\\Ind}_\\gamma$ are substituted for the Gibbs weights $w^G_\\beta$.\n%\nMoreover, notice that $w^\\Ind_\\gamma(c,X')\\cdot w^\\Ind_\\gamma(c,X'')=1$ if\nand only $c\\in {\\mathcal{C}_\\gamma}(X')\\cap {\\mathcal{C}_\\gamma}(X'')$. Hence, sampling a solution from\n$\\mathcal{C}$ with a probability proportional to $w^\\Ind_{\\gamma^*}(c,X')\n\\cdot w^\\Ind_{\\gamma^*}(c,X'')$ corresponds to sampling a solution from\n$\\mathcal{C}_{\\gamma^*}(X')\\cap \\mathcal{C}_{\\gamma^*}(X'')$ uniformly at random.\n%\n\nSimilar to the parameter $\\gamma$ in Equation~\\eqref{eq:simple}, the parameter\n$\\beta$ (called ``inverse temperature'' in statistical physics\\footnote{Much\nmore on that will be given in Chapter~\\ref{ch:free_energy}.}) \n\\index{Inverse temperature} controls\nthe amount of solutions that are taken into account. For $\\beta=0$, all\nsolutions have the same weight 1 (corresponding to the case $\\gamma=\\infty$ in\nwhich the intersection contains every solution in $\\mathcal{C}$), while for\n$\\beta\\to \\infty$ the distribution concentrates on the solutions with the\nminimum joint cost. Hence, the parameter $\\beta$\nin~\\eqref{eq:gibbs_similarity_maximization_objective} is by its semantics an\n``inverse'' to the parameter~$\\gamma$ in~\\eqref{eq:simple}.\n\n\\subsection{Experimental Results}\n\\label{sec:gen_appch_gibbs_experiments}\n\n\\begin{figure}[t!]\n  \\centering\n  \\begin{subfigure}[b]{.49\\textwidth}\n      \\includegraphics[width=\\linewidth]{figures/ch_generic_approach/gnm_g50_b950_gibbs}\n      \\caption{$5\\%$ of solutions are \\good.}\n      \\label{fig:gnm_5_gibbs}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[b]{.49\\textwidth}\n      \\includegraphics[width=\\linewidth]{figures/ch_generic_approach/gnm_g100_b900_gibbs}\n      \\caption{$10\\%$ of solutions are \\good.}\n      \\label{fig:gnm_10_gibbs}\n  \\end{subfigure}\n  \\\\[.5cm]\n  \\caption{Gibbs relaxation shows almost the same performance. Experimental\n    results where $5\\%$ \\textbf{(a)} and $10\\%$ \\textbf{(b)}. Model and setting\n    are the same as in Section~\\ref{sec:proof_of_concept}.}\n  \\label{fig:gnm_gibbs}\n\\end{figure}\n\nSince the Gibbs relaxation chooses every solution $c \\in \\mathcal{C}$ with a probability\nproportional to $w^G_{\\beta^*}(c, X')\\cdot w^G_{\\beta^*}(c, X'')$, we define its\nsuccess probability as\n\\begin{equation}\n  P_\\mathscr{A}^G(X',X'')\n    \\coloneqq \\frac{\\sum_{c \\in \\sgood} w^G_{\\beta^*}(c, X')\\cdot w^G_{\\beta^*}(c, X'')}\n      {\\sum_{c \\in \\mathcal{C}} w^G_{\\beta^*}(c, X')\\cdot w^G_{\\beta^*}(c, X'')}\n\\end{equation}\nwhere $\\beta^*$ is the value $\\beta$ that\nmaximizes~(\\ref{eq:gibbs_similarity_maximization_objective}). Notice that the\nsums in the numerator and denominator are computed over different sets of\nsolutions. Notice that this formula is a full analogy\nof~\\eqref{eq:uncert:prob_succ}.\n\nFigure~\\ref{fig:gnm_gibbs} shows, under the same setting as in\nSection~\\ref{sec:proof_of_concept}, that the Gibbs relaxation provides yields\nalmost the same performance and thus can be considered as a viable variant\nof the approximation set-based approach. This idea will be massively exploited \nin Chapter~\\ref{ch:free_energy}.\n\n\\section{Discussion and Conclusion}\n\\label{sec:gen_appch_conclusion}\n\nIn this chapter, we introduced an approximation set-based approach to robust\noptimization and justified it via a so-called Approximation Set Coding which\nprovides an information-theoretic background. Below, we will elaborate on some\npoints which are, in our view, highlighting its most interesting and/or\ncontroversial properties.\n\n\\subsection*{Role of the logarithm}\n\nConsider the comparison between the empirical ASC score~\\eqref{eq:asc_mutual_information_formula}\n\\begin{equation*}\n  \\log \n    \\frac{|\\mathbb{\\C}| \\; |\\Delta \\mathcal{C}_\\gamma(X', X'')|}%\n      {|\\mathcal{C}_\\gamma(X')| \\; |\\mathcal{C}_\\gamma(X'')|}\n\\end{equation*}\nand the empirical similarity score~\\eqref{eq:simple}:\n\\begin{equation*}\n  \\frac{|\\mathcal{C}||{\\mathcal{C}_\\gamma}(X') \\cap {\\mathcal{C}_\\gamma}(X'')|}\n    {|{\\mathcal{C}_\\gamma}(X')||{\\mathcal{C}_\\gamma}(X'')|}.\n\\end{equation*}\nNote that there is a difference in putting the logarithm in front of the \nASC score. Although both have their maxima at the same $\\gamma$, this logarithm\nwill be of essential importance later in Chapter~\\ref{ch:free_energy} so\nit is instructive to explain this difference.\n\nThe numerator and the denominator of the score can be seen as the\nalternative and the null hypothesis, respectively, in statistical hypothesis\ntesting~--- the likelihood ratio test. One can view the usage of logarithm of\nthe likelihood ratio as a tool for ensuring asymptotic normality of estimators\nin the case of weak coupling. For the main objective of this chapter, using the\nlogarithm had no special implications, since we were interested in the $\\gamma^*$\nwhich maximized score, but not in the score itself.\n\nWe should also note that the coding argument which we brought when deriving ASC\nimplies that logarithm allows to quantify the informativeness/capacity using \\textit{bits}\n(or \\textit{nats}, depending on the type of the logarithm in use). This is \nturns the ASC score into the one which allows interpretable value~--- i.e. the one\nanswering ``how many bits of information can the model extract''.\n\\index{Nat (measure of information)}\n\n\\subsection*{Is the way of defining approximation unique?}\nAs one can see from the material of this chapter, the whole approximation\nset-based approach rests on \\textit{some notion} of closeness of the given\nsolution to the optimal one ($c^\\bot$). We quantified this notion in terms of\nparameters $\\gamma$ or (in case of Gibbs approximation) $\\beta$. But there\nexists a whole zoo of other possible parametrizations, for example,\nparametrizing by the step $t$ of a stepwise algorithm. However, we advocate the\npoint of view that such parametrization should yield a local topology around\neach solution according to the following informal procedure:\n\n\\begin{enumerate}\n  \\item define certain measure of local closeness of solutions around the optimal;\n\n  \\item make an assumption: each solution \\textit{is} the optimal solution for some\n  input;\n\n  \\item local approximation topologies induced by the above create a ``cover''\n  of the whole solution space; \n  \\index{Topology}\n  \\index{Local approximation topology}\n\n  \\item derive conditions under which such a covering by local topology is can be\n  turned into metric space (metrization theorems); \\index{Metrization theorems}\n\n  \\item the above allows to create a uniform (i.e. non-local) closeness relation.\n\\end{enumerate}\nThis high-level roadmap gives some insight into the final goal of such a journey:\nunderstand the structure of solution space in a problem-specific manner.\n\n\\subsection*{Are all solutions in the intersection created equal?}\nOur method expects all solutions in the best approximation set intersection to\nbe equally desirable (e.g., equally good for a third, unknown instance). In some\ncases, it might be useful to choose the solution based on some problem specific\ncriterion, e.g., choose the solution closest to the centroid of the intersection\nset.\n\n\\subsection*{Will more input lead to better results?}\nWe mostly studied the two instance scenario because this is the minimum number\nof instances necessary  to distinguish information from noise. Often, however,\nmore than two instances are available. The extension to multiple instances is\nnot immediately obvious.\n\nThere are several ways of addressing it: (a) first, one can break it into pairs\nand average. This is how the framework is intended to be used in practice; (b)\nsecond, one can derive a version of ASC for multiple agents. The latter approach\nsounds much more interesting from the research prospective, as it is not clear\nwhat would be the channel analogy in case of several agents (remember, in the\ntwo instance scenario, we considered one data point as a codebook benchmark, and\nthe other as error problem generator). On can as well go in the direction of a\nstraightforward generalization of the similarity\nformula~\\eqref{eq:asc_mutual_information_formula}. In the course of our\nresearch, some attempts have been made in that direction and they yielded\npromising results.\n\n\n\\subsection*{Can we find efficient algorithmic solutions?}\n\nThe remark after Theorems~\\ref{thm:simple}--\\ref{thm:worst_case} tells that one\nof the pitfalls of approximation set-based approach consists in computation of\nthe similarity score. While we used brute-force enumeration for our\nproof-of-concept experiments, it would be of a great importance to find either\n(a) analytical estimations for the similarity score or (b) efficient algorithms\nfor computing it.\n\nIn this chapter, we tackled case (a) and made an attempt to derive a very simple\nanalytical estimator, which uses the knowledge of the true distributions. This\nassumption, of course, renders it useless in real cases, but allows usage of\nplug-in estimators of the true distributions.\n\nOn a much higher level which uses less information about the true distributions,\nthe approach (a) will be tackled in Chapter~\\ref{ch:free_energy}.\n\nIn specific cases, such as application to combinatorial algorithms, the approach\n(b) can be used by utilizing combinatorial structure of the solutions. This will\nbe shown in Chapter~\\ref{ch:mst}.\n\n\\subsection*{Similarity as a computational goal-specific measure}\nAn interesting side-result that we did not focus on in this chapter is the\nexpressiveness of instance similarity $S_{\\gamma^*}$. In fact, it utilizes a\n\\textit{computational goal-induced} topology on the set of solutions. We bring\nhere a motivation which was best described in~\\citep{jcss:2017}.\n\\index{Topology}\n\\index{Computational goal-induced topology}\nFor example, consider the problem of computing a shortest path between two given\nvertices in a graph $G$. \n%\nHaving two instances $X'$ and $X''$ of this problem, one may attempt to measure\nthe similarity of these instances using certain structural information exposed to\nus~--- e.g.,~the correlation coefficient or the Euclidean distance between the\nvectors containing the edge weights.\n\\index{Euclidean distance}\n\nHowever, if the instances differ a lot only in some weights which are usually\nhigh and thus these edges that are never used in any nearly-shortest path, then\nthe similarity approach will correctly consider such examples as similar,\nwhereas for example the correlation coefficient will tell the opposite.\n%\nAt the same time, if the computational goal was a maximum matching of edges\nrather than the minimizing the weight cost, the similarity would regard the two\ninstances as significantly different.\n%\nThis example highlights the need for a measure of \\emph{similarity of instances\nwith respect to a computational goal}. This is performed by inducing a local topology\naround each solution, and this topology depends only on the computational goal\nand not on anything else.\n\n", "meta": {"hexsha": "5378690453ced3131532d5e5fabb19fb2c240cbd", "size": 111064, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/ch_generic_approach/ch_generic_approach.tex", "max_stars_repo_name": "agronskiy/phd-thesis", "max_stars_repo_head_hexsha": "182fcc5c09c8aa20df54cf536eb87766bfb6c353", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thesis/ch_generic_approach/ch_generic_approach.tex", "max_issues_repo_name": "agronskiy/phd-thesis", "max_issues_repo_head_hexsha": "182fcc5c09c8aa20df54cf536eb87766bfb6c353", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis/ch_generic_approach/ch_generic_approach.tex", "max_forks_repo_name": "agronskiy/phd-thesis", "max_forks_repo_head_hexsha": "182fcc5c09c8aa20df54cf536eb87766bfb6c353", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.6708407871, "max_line_length": 162, "alphanum_fraction": 0.7105452712, "num_tokens": 33663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.33148910462386283}}
{"text": "\\subsection{Stochastics}\n\nThe lack of a generally valid failure criterion in state-based PD makes an assessment of the initial idea to use a stochastic material distribution for the assessment of failure initiation difficult. However, stochastics may be used to achieve the same entropy in structured discretization as in unstructured base meshes and to individualize failure locations. The comparison of the original hex model with $dx=\\SI{0.4}{\\milli\\meter}$ and horizon $\\delta=\\SI{1.2}{\\milli\\meter}$ and three models with stochastic material distribution is shown in \\autoref{fig:Results:Hex:Stoch}. Ten different blocks are created with a deviation of the $\\SI{2}{\\percent}$ of the material bulk and shear modulus.\n\n\\pgfplotstableread[col sep=comma]{../../Material/Data/Numerics/Hex_0-4_1-2_Stoch.csv}{\\loadedtable}\n\n\\begin{figure}[htbp]\n  \\setlength{\\figheight}{7cm}\n  \\begin{subfigure}{0.55\\linewidth}\n    \\begin{minipage}[b][\\figheight]{\\linewidth}\n    \\centering\n%     \\includegraphics[width=\\linewidth,height=\\figheight]{example-image-a}\n    \\tikzexternalenable\n    \\tikzsetnextfilename{Hex_0-5_0-5625_Stoch}\n    \\begin{tikzpicture}\n      \\begin{axis}[\n        height=\\figheight+\\baselineskip,\n        width=\\linewidth,\n        axis lines=middle,\n        cycle list name=color list,%linestyles*,\n        cycle list shift=1,\n        xmin=0,\n        ymin=0,\n        title=\\empty,\n        xlabel={Displacement $[\\si{\\milli\\meter}]$},\n        ylabel={Force $[\\si{\\newton}]$},\n        x label style={at={(axis description cs:0.5,-0.075)},anchor=north},\n        y label style={at={(axis description cs:-0.105,0.5)},rotate=90,anchor=south},\n        legend pos=north west,\n        legend cell align={left},\n        legend style={font=\\footnotesize},\n      ]%   each nth point={2}\n        \\addplot+ [thick] table[x=DxNo, y=FxNo] {\\loadedtable};\n        \\addlegendentry{No stochastics}\n        \\addplot+ [] table[x=DxSto1, y=FxSto1] {\\loadedtable};\n        \\addlegendentry{Stochastic 1}\n        \\addplot+ [] table[x=DxSto2, y=FxSto2] {\\loadedtable};\n        \\addlegendentry{Stochastic 2}\n        \\addplot+ [] table[x=DxSto3, y=FxSto3] {\\loadedtable};\n        \\addlegendentry{Stochastic 3}\n      \\end{axis}\n    \\end{tikzpicture}\n    \\tikzexternaldisable\n    \\end{minipage}\n    \\caption{Force-displacement plot until failure}\n    \\label{fig:Results:Tet:Stoch:FD0-5_0-5625}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}{0.10\\linewidth}\n    \\begin{minipage}[b][\\figheight]{\\linewidth}\n    \\centering\n      %\\includegraphics[angle=90,width=\\linewidth,height=\\figheight,keepaspectratio]{../../Material/Figures/PD_Hex_Damage_0-4_1-2_3630_-z_ct.png}\n      \\includegraphics[angle=90,width=\\linewidth,height=\\figheight,keepaspectratio]{PD_Hex_Damage_0-4_1-2_3630_-z_ct}\n    \\end{minipage}\n    \\caption{No}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}{0.10\\linewidth}\n    \\begin{minipage}[b][\\figheight]{\\linewidth}\n      \\centering\n      %\\includegraphics[angle=90,width=\\linewidth,height=\\figheight,keepaspectratio]{../../Material/Figures/PD_Hex_Stoch_1_Damage_0-4_1-2_3475_-z_ct.png}\n      \\includegraphics[angle=90,width=\\linewidth,height=\\figheight,keepaspectratio]{PD_Hex_Stoch_1_Damage_0-4_1-2_3475_-z_ct}\n    \\end{minipage}\n    \\caption{1}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}{0.10\\linewidth}\n    \\begin{minipage}[b][\\figheight]{\\linewidth}\n      \\centering\n      %\\includegraphics[angle=90,width=\\linewidth,height=\\figheight,keepaspectratio]{../../Material/Figures/PD_Hex_Stoch_2_Damage_0-4_1-2_3540_-z_ct.png}\n      \\includegraphics[angle=90,width=\\linewidth,height=\\figheight,keepaspectratio]{PD_Hex_Stoch_2_Damage_0-4_1-2_3540_-z_ct}\n    \\end{minipage}\n    \\caption{2}\n  \\end{subfigure}\n  \\begin{subfigure}{0.10\\linewidth}\n    \\begin{minipage}[b][\\figheight]{\\linewidth}\n      \\centering\n      %\\includegraphics[angle=90,width=\\linewidth,height=\\figheight,keepaspectratio]{../../Material/Figures/PD_Hex_Stoch_3_Damage_0-4_1-2_3292_-z_ct.png}\n      \\includegraphics[angle=90,width=\\linewidth,height=\\figheight,keepaspectratio]{PD_Hex_Stoch_3_Damage_0-4_1-2_3292_-z_ct}\n    \\end{minipage}\n    \\caption{3}\n  \\end{subfigure}\n  \\caption{Failure for hex-mesh with $dx=\\SI{0.4}{\\milli\\meter}$ and stochastics}\n  \\label{fig:Results:Hex:Stoch}\n\\end{figure}\n\nIt can be seen that the overall stiffness and failure behavior does not change significantly. However, the stochastic material distribution makes it possible to spot several possible individual failure locations. One would expect a less slanted crack propagation. This can be achieved by using a finer discretization. However, a slightly angular failure path can also be observed in tests with a little different specimen geometry of the same material, see \\autoref{fig:Results:Exp:AngledCrackPath}. A contact-free displacement measurement using a video extensometer is used to avoid an influence on the crack path.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=0.5\\linewidth,keepaspectratio]{../../Material/Figures/KrauseD_Damage_LY564_statisch}\n  \\caption{Angled crack path in same material specimen with different geometry \\cite{KrauseD2016}}\n  \\label{fig:Results:Exp:AngledCrackPath}\n\\end{figure}\n\nThe same principal results are valid for tet meshes as shown in \\autoref{fig:Results:Tet:Stoch} with a modulus range of $\\SI{5}{\\percent}$ around the nominal value. It can be noted that the location of failure shifts slightly away from the geometric feature bordering the two separate volumes in this region. In one case failure occurs slightly earlier as a result of the stochastic material distribution. Overall, due to the higher mesh entropy, the effect of stochastic material distribution in tet meshes is smaller than in hex meshes.\n\n\\pgfplotstableread[col sep=comma]{../../Material/Data/Numerics/Tet_0-5_0-5625_Stoch.csv}{\\loadedtable}\n\n\\begin{figure}[htbp]\n  \\setlength{\\figheight}{7cm}\n  \\begin{subfigure}{0.55\\linewidth}\n    \\begin{minipage}[b][\\figheight]{\\linewidth}\n    \\centering\n%     \\includegraphics[width=\\linewidth,height=\\figheight]{example-image-a}\n    \\tikzexternalenable\n    \\tikzsetnextfilename{Tet_0-4_1-2_Stoch}\n    \\begin{tikzpicture}\n      \\begin{axis}[\n        height=\\figheight+\\baselineskip,\n        width=\\linewidth,\n        axis lines=middle,\n        cycle list name=color list,%linestyles*,\n        cycle list shift=1,\n        xmin=0,\n        ymin=0,\n        title=\\empty,\n        xlabel={Displacement $[\\si{\\milli\\meter}]$},\n        ylabel={Force $[\\si{\\newton}]$},\n        x label style={at={(axis description cs:0.5,-0.075)},anchor=north},\n        y label style={at={(axis description cs:-0.105,0.5)},rotate=90,anchor=south},\n        legend pos=north west,\n        legend cell align={left},\n        legend style={font=\\footnotesize},\n      ]%   each nth point={2}\n        \\addplot+ [thick] table[x=DxNo, y=FxNo] {\\loadedtable};\n        \\addlegendentry{No stochastics}\n        \\addplot+ [] table[x=DxSto1, y=FxSto1] {\\loadedtable};\n        \\addlegendentry{Stochastic 1}\n        \\addplot+ [] table[x=DxSto2, y=FxSto2] {\\loadedtable};\n        \\addlegendentry{Stochastic 2}\n        \\addplot+ [] table[x=DxSto3, y=FxSto3] {\\loadedtable};\n        \\addlegendentry{Stochastic 3}\n      \\end{axis}\n    \\end{tikzpicture}\n    \\tikzexternaldisable\n    \\end{minipage}\n    \\caption{Force-displacement plot until failure}\n    \\label{fig:Results:Tet:Stoch:FD0-4_1-2}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}{0.10\\linewidth}\n    \\begin{minipage}[b][\\figheight]{\\linewidth}\n    \\centering\n      %\\includegraphics[angle=90,width=\\linewidth,height=\\figheight,keepaspectratio]{../../Material/Figures/PD_Tet_Damage_0-5_0-5625_9600_-z_ct.png}\n      \\includegraphics[angle=90,width=\\linewidth,height=\\figheight,keepaspectratio]{PD_Tet_Damage_0-5_0-5625_9600_-z_ct}\n    \\end{minipage}\n    \\caption{No}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}{0.10\\linewidth}\n    \\begin{minipage}[b][\\figheight]{\\linewidth}\n      \\centering\n      %\\includegraphics[angle=90,width=\\linewidth,height=\\figheight,keepaspectratio]{../../Material/Figures/PD_Tet_Stoch_1_Damage_0-5_0-5625_5645_-z_ct.png}\n      \\includegraphics[angle=90,width=\\linewidth,height=\\figheight,keepaspectratio]{PD_Tet_Stoch_1_Damage_0-5_0-5625_5645_-z_ct}\n    \\end{minipage}\n    \\caption{1}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}{0.10\\linewidth}\n    \\begin{minipage}[b][\\figheight]{\\linewidth}\n      \\centering\n      %\\includegraphics[angle=90,width=\\linewidth,height=\\figheight,keepaspectratio]{../../Material/Figures/PD_Tet_Stoch_2_Damage_0-5_0-5625_3950_-z_ct.png}\n      \\includegraphics[angle=90,width=\\linewidth,height=\\figheight,keepaspectratio]{PD_Tet_Stoch_2_Damage_0-5_0-5625_3950_-z_ct}\n    \\end{minipage}\n    \\caption{2}\n  \\end{subfigure}\n  \\begin{subfigure}{0.10\\linewidth}\n    \\begin{minipage}[b][\\figheight]{\\linewidth}\n      \\centering\n      %\\includegraphics[angle=90,width=\\linewidth,height=\\figheight,keepaspectratio]{../../Material/Figures/PD_Tet_Stoch_3_Damage_0-5_0-5625_3950_-z_ct.png}\n      \\includegraphics[angle=90,width=\\linewidth,height=\\figheight,keepaspectratio]{PD_Tet_Stoch_3_Damage_0-5_0-5625_3950_-z_ct}\n    \\end{minipage}\n    \\caption{3}\n  \\end{subfigure}\n  \\caption{Failure for hex-mesh with $dx=\\SI{0.4}{\\milli\\meter}$ and stochastics}\n  \\label{fig:Results:Tet:Stoch}\n\\end{figure}", "meta": {"hexsha": "a88aeeba95ff3eb2d26fb13521cd8c928391bab4", "size": 9275, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Publications/2017_ECCOMAS/Texts/Paper/Sections/Results_Stochastics.tex", "max_stars_repo_name": "oldninja/PeriDoX", "max_stars_repo_head_hexsha": "f31bccc7b8ea60cd814d00732aebdbbe876a2ac7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Publications/2017_ECCOMAS/Texts/Paper/Sections/Results_Stochastics.tex", "max_issues_repo_name": "oldninja/PeriDoX", "max_issues_repo_head_hexsha": "f31bccc7b8ea60cd814d00732aebdbbe876a2ac7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Publications/2017_ECCOMAS/Texts/Paper/Sections/Results_Stochastics.tex", "max_forks_repo_name": "oldninja/PeriDoX", "max_forks_repo_head_hexsha": "f31bccc7b8ea60cd814d00732aebdbbe876a2ac7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.106741573, "max_line_length": 694, "alphanum_fraction": 0.7162264151, "num_tokens": 2885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.3312966214110021}}
{"text": "\\appendix\n\\section{Computation}\n\\label{s:appendix}\n\nIn this appendix we derive an expression for\nthe nonlocal resistance for finite contact resistance.\nWe first present the key definitions and critical boundary conditions.\nWe then derive the relation between the nonlocal resistance\nand the spin chemical potential at the far contact, $μ_s^N (L)$.\nFinally, we solve the diffusion equation inside the semiconductor to find $μ_s^N (L)$.\n\n\\subsection{Definitions}\n\nMany of the definitions and results in this section are taken from\n\\cite{ActaPhysicaSlovaca.57.4_5.565-907}.\nThe chemical potential and spin chemical potential are defined in terms\nof the spin-up and spin-down chemical potentials,\n\\begin{subequations}\n  \\label{eq:potentials}\n  \\begin{alignat}{2}\n    & μ   && = \\frac{1}{2} \\left( μ_↑ + μ_↓ \\right) , \\\\\n    & μ_s && = \\frac{1}{2} \\left( μ_↑ - μ_↓ \\right) .\n  \\end{alignat}\n\\end{subequations}\nThe material conductances and polarization are defined in terms\nof the spin-up and spin-down conductances,\n\\begin{subequations}\n  \\label{eq:conductances}\n  \\begin{alignat}{2}\n    & σ   && = σ_↑ + σ_↓ , \\\\\n    & σ_s && = σ_↑ - σ_↓ , \\\\\n    %\n    \\label{eq:material.polarization}\n    & P_σ && = \\frac{σ_s}{σ} .\n  \\end{alignat}\n\\end{subequations}\nThe gradient of the chemical potentials drives a current and spin current,\n\\begin{subequations}\n  \\label{eq:currents}\n  \\begin{alignat}{3}\n    & J_{↑↓} && = σ_{↑↓} ∇μ_{↑↓} , \\\\\n    %\n    \\label{eq:currents.current}\n    & J      && = J_↑ + J_↓ & = σ   ∇μ + σ_s ∇μ_s , \\\\\n    %\n    \\label{eq:currents.spincurrent}\n    & J_s    && = J_↑ - J_↓ & = σ_s ∇μ + σ   ∇μ_s .\n  \\end{alignat}\n\\end{subequations}\nTo indicate the material, any of the above can have a superscript\n$N$ (normal semiconductor) or $F$ (ferromagnet).\n\nThe contact conductances and polarization are defined in terms\nof the spin-up and spin-down contact conductances,\n\\begin{subequations}\n  \\label{eq:contact_conductances}\n  \\begin{alignat}{2}\n    & Σ   && = Σ_↑ + Σ_↓ , \\\\\n    & Σ_s && = Σ_↑ - Σ_↓ , \\\\\n    %\n    \\label{eq:contact.polarization}\n    & P_Σ && = \\frac{Σ_s}{Σ} .\n  \\end{alignat}\n\\end{subequations}\nThe mismatch of the chemical potentials across the contact\ndrives a current and spin current,\n\\begin{subequations}\n  \\label{eq:contact_currents}\n  \\begin{alignat}{2}\n    & J_{↑↓}^C && = Σ_{↑↓} \\left( μ^N_{↑↓} - μ^F_{↑↓} \\right)_c , \\\\\n    %\n    & J^C      && = J_↑^C + J_↓^C , \\\\\n    & J_s^C    && = J_↑^C - J_↓^C .\n  \\end{alignat}\n\\end{subequations}\nThe subscript $c$ will always denote the function evaluated at the contact.\n\nWe will use the term current to refer to $J$,\nwhen in fact this is a particle current density.\nFor constant $J$, the physical charge current $I$ will be related to $J$\nby a relation $I = - A J / e$ for some characteristic area $A$.\n\nTo reduce the number of subscripts and superscripts in the following,\nwe adopt the notation for the potentials\n\\begin{subequations}\n  \\begin{equation}\n    \\begin{aligned}\n    & \\begin{alignedat}{2}\n        & u && = μ^N_s , \\\\\n        & v && = μ^N   ,\n      \\end{alignedat}\n    & \\begin{alignedat}{2}\n        & φ && = μ^F_s , \\\\\n        & ψ && = μ^F   ,\n      \\end{alignedat}\n    \\end{aligned}\n  \\end{equation}\n  and currents\n  \\begin{equation}\n    \\begin{alignedat}{2}\n      & ȷ   && = J_s   , \\\\\n      & J_c && = J^C   , \\\\\n      & ȷ_c && = J_s^C .\n    \\end{alignedat}\n  \\end{equation}\n\\end{subequations}\n\nWe rewrite \\cref{eq:contact_currents} as\n\\begin{subequations}\n  \\label{eq:contact_currents.2}\n  \\begin{alignat}{3}\n    \\label{eq:contact_currents.2.current}\n    & J_c && = Σ   \\left( v_c - ψ_c \\right) && + Σ_s \\left( u_c - φ_c \\right) , \\\\\n    %\n    \\label{eq:contact_currents.2.spincurrent}\n    & ȷ_c && = Σ_s \\left( v_c - ψ_c \\right) && + Σ   \\left( u_c - φ_c \\right) ,\n  \\end{alignat}\n\\end{subequations}\nand \\cref{eq:conductances,eq:currents} as\n\\begin{equation}\n  \\label{eq:bdry_current}\n  ȷ = P_σ J + 4 \\frac{σ_↑ σ_↓}{σ} ∇μ_s .\n\\end{equation}\n\nUsing \\cref{eq:contact_conductances,eq:contact_currents.2},\n\\begin{equation}\n  \\label{eq:bdry_current_contact}\n  ȷ_c = P_Σ^i J_c + {R_C^i}^{-1} \\left( u_c - φ_c \\right) ,\n\\end{equation}\nwhere the contact resistance is\n\\begin{equation}\n  \\label{eq:contact.resistance}\n  R_C^i = \\frac{Σ^i}{4 Σ_↑^i Σ_↓^i} .\n\\end{equation}\nThe superscript $i$ allows for contacts with difference conductances.\n\n\\subsection{Boundary conditions}\n\nIn this sections, we derive the relations between the potentials and the currents\nThis corresponds to the needed boundary conditions.\n\n\\subsubsection{Semiconductor}\n\nFor the semiconductor, $σ^N_↑ = σ^N_↓ = σ^N / 2$, so $P_σ^N = 0$.\nEvaluating \\cref{eq:bdry_current} at the contact gives\n\\begin{equation}\n  \\label{eq:bdry_current.semiconductor}\n  ȷ^N_c = σ^N ( ∇u )_c .\n\\end{equation}\n\n\\subsubsection{Ferromagnet}\n\nFor the ferromagnet, one assumes $μ_s^F$ satisfies\nthe one dimensional diffusion equation.\nWe choose the $z'$ coordinate antiparallel to $z$ with origin at the contact.\nThe equation\n\\begin{equation}\n  \\label{eq:diffusion.ferromagnet}\n  φ'' \\left( z' \\right) - k_F^2 φ \\left( z' \\right) = 0 ,\n\\end{equation}\nwith the boundary condition\n$\\lim_{z' → - ∞} φ(z') = 0$\nhas solution\n\\begin{equation}\n  \\label{eq:diffusion.ferromagnet.solution}\n  φ(z') = φ_c e^{k_F z'} ,\n\\end{equation}\nwhere $φ_c = φ(0)$ is a yet undetermined constant.\nPutting this into \\cref{eq:bdry_current} and evaluating it at the contact gives\n\\begin{equation}\n  \\label{eq:bdry_current.ferromagnet}\n  ȷ^F_c = P_σ^F J^F_c + R_F^{-1} φ_c ,\n\\end{equation}\nwhere the ferromagnet resistance is\n\\begin{equation}\n  \\label{eq:ferromagnet.resistance}\n  R_F = \\frac{σ^F}{ 4 σ_↑^F σ_↓^F k_F } .\n\\end{equation}\nHere, $λ_F = 1 / k_F$ is the spin diffusion length in the ferromagnet.\n\n\\subsubsection{Continuity assumptions}\n\nAt the contact, the current and spin current are assumed continuous,\n\\begin{subequations}\n  \\label{eq:continuity.current}\n  \\begin{alignat}{3}\n    & J_c && = J^F_c && = J^N_c , \\\\\n    & ȷ_c && = ȷ^F_c && = ȷ^N_c .\n  \\end{alignat}\n\\end{subequations}\nUsing \\cref{eq:bdry_current.ferromagnet,eq:bdry_current_contact,eq:continuity.current}\nwe find the relation\n\\begin{subequations}\n  \\label{eq:bdry_solutions}\n  \\begin{equation}\n    \\label{eq:bdry_solutions.current}\n    \\left( P_σ^F R_F + P_Σ^i R_C^i \\right) J_c = \\left( R_F + R_C^i \\right) ȷ_c - u_c ,\n  \\end{equation}\n  and that $φ_c$ is determined by\n  \\begin{equation}\n    \\label{eq:bdry_solutions.potential}\n    R_F^{-1} φ_c = \\frac{ \\left( P_Σ^i - P_σ^F \\right) R_C^i ȷ_c + P_σ^F u_c}{P_σ^F R_F + P_Σ^i R_C^i} .\n  \\end{equation}\n\\end{subequations}\nIn the special case of zero current at the contact ($J_c = 0$),\n\\cref{eq:bdry_solutions} reduces to\n\\begin{subequations}\n  \\label{eq:bdry_solutions.zero}\n  \\begin{alignat}{2}\n    \\label{eq:bdry_solutions.zero.current}\n    & ȷ_c && = \\frac{1}{R_F + R_C^i} u_c   , \\\\\n    %\n    \\label{eq:bdry_solutions.zero.potential}\n    & φ_c && = \\frac{R_F}{R_F + R_C^i} u_c .\n  \\end{alignat}\n\\end{subequations}\n\n\\subsection{Nonlocal resistance}\n\\label{s:appendix:nonlocal_resistance}\n\nIn this section we derive the precise relation between $\\rNL$ and $μ_s^N (L)$.\nNote that we may write in general, for some $\\bar{μ}$,\n\\begin{equation}\n  μ = \\bar{μ} + P_σ μ_s ,\n\\end{equation}\nand, following\n\\cite{PhysRevB.67.052409},\ndefine the voltage due to the difference in the chemical potentials across the contacts by\n\\begin{equation}\n  V_c = \\left( \\bar{μ}_c^N - \\bar{μ}_c^F \\right) / e.\n\\end{equation}\n\nWe assume a fixed current $J_0 = \\abs{J_0} > 0$\nflows down through the contact at $x = 0$\nand to the left in the semiconductor for $x ≤ 0$,\nand no current flows for $x > 0$.\nThe experimentally measured quantity is the\nnonlocal resistance $\\rNL = V_L / I_0$,\nwhere $I_0 = - W L J_0 / e$ is the current through the contact at $x = 0$.\nIt is convenient to introduce the effective nonlocal resistance $\\rNLeff$\ndefined by\n\\begin{equation}\n  \\rNLeff = W L \\rNL = - e V_L / J_0 = \\frac{\\bar{μ}_c^F - \\bar{μ}_c^N}{J_0} .\n\\end{equation}\nTo determine $\\rNL$, we must express the difference\nof these chemical potentials in terms of $μ_s^N (L)$.\n\nSince there are two ferromagnetic contacts,\nwe have separate functions $ψ$ and $φ$ for each contact\nwhich we will denote by $ψ^0$, $φ^0$, and $ψ^L$, $φ^L$.\nFrom \\cref{eq:diffusion.ferromagnet.solution}, we have\n\\begin{subequations}\n  \\begin{align}\n    φ^0 \\left( z' \\right) & = φ_0 e^{k_F z'} , \\\\\n    φ^L \\left( z' \\right) & = φ_L e^{k_F z'} .\n  \\end{align}\n\\end{subequations}\n\nThe physical restriction on the current flow in the semiconductor\nis imposed by noting that since $σ_s^N = 0$,\n\\cref{eq:currents.current} gives $J^N = σ^N ∇v$, so we must have\n\\begin{equation}\n  v_x (x) =\n    \\begin{cases}\n      v_x (0) - \\left( J_0 / σ^N \\right) x & \\text{ for } x ≤ 0 , \\\\\n      v_x (0)                              & \\text{ for } x > 0 ,\n    \\end{cases}\n\\end{equation}\n$v_y (x) = v_y (0)$, and $v_z (x) = v_z (0)$.\n\nUsing \\cref{eq:currents.current},\nthe restriction on the current flow in each ferromagnet gives\n\\begin{subequations}\n  \\begin{align}\n    ∇ψ^0 & = \\left( J_0 / σ^F \\right) - P_σ^F ∇φ^0 , \\\\\n    ∇ψ^L & = - P_σ^F ∇φ^L .\n  \\end{align}\n\\end{subequations}\nIntegrating and enforcing\n$e V_c = v_x (0) - \\left( ψ_c - P_σ^F φ_c \\right)$,\n\\begin{subequations}\n  \\begin{align}\n    & \\begin{aligned}\n        ψ^0 \\left( z' \\right) & = - e V_0 + P_σ^F φ_0 \\left( 2 - e^{k_F z'} \\right) \\\\\n                              & \\qquad + v_x (0) + \\left( J_0 / σ^F \\right) z' ,\n      \\end{aligned} \\\\\n    & \\begin{aligned}\n        ψ^L \\left( z' \\right) & = - e V_L + P_σ^F φ_L \\left( 2 - e^{k_F z'} \\right) \\\\\n                              & \\qquad + v_x (0) .\n      \\end{aligned}\n  \\end{align}\n\\end{subequations}\n\nThere is no current at the contact at $x = 0$,\nthus \\cref{eq:contact_currents.2.current} gives\n\\begin{equation}\n  ψ_L - v_L = P_Σ^L \\left( u_L - φ_L \\right) ,\n\\end{equation}\nand with\n\\cref{eq:bdry_solutions.zero.potential},\nwe find\n\\begin{equation}\n  \\label{eq:rnl.full}\n  \\begin{aligned}\n    \\rNLeff & = \\left( ψ_L - v_L \\right) - P_σ^F φ_L \\\\\n            & = \\left[ P_Σ^L \\left( 1 - \\frac{R_F}{R_F + R_C^L} \\right) - \\frac{P_σ^F R_F}{R_F + R_C^L} \\right] \\frac{u_x (L)}{J_0} .\n  \\end{aligned}\n\\end{equation}\n\n\\subsection{Diffusion equation}\n\nIn this section we show how to solve for $μ_s^N (L)$.\nThis method is based on the one described in\n\\cite{PhysRevB.80.214427}.\nInside the semiconductor, $u$ satisfies the diffusion equation\n\\begin{equation}\n  \\label{eq:diffusion}\n  D ∇^2 u - \\frac{u}{τ} + ω × u = 0 .\n\\end{equation}\nHere, $D$ is the diffusion constant, $τ$ the spin lifetime,\nand $ω = \\left( g μ_B / ℏ \\right) B$ is proportional to the applied magnetic field\n(with $g$ the gyromagnetic ratio and $μ_B$ the Bohr magneton).\nThe spin diffusion length in the semiconductor is $λ = 1 / k = \\sqrt{D τ}$.\n\nThe function $u = u(x)$ only varies along $x$,\nand we introduce the notation\n\\begin{equation}\n  u_x (x) =\n    \\begin{cases}\n      u_{x-} (x) \\text{ for } x < 0     , \\\\\n      u_{x0} (x) \\text{ for } 0 ≤ x ≤ L , \\\\\n      u_{x+} (x) \\text{ for }     L < x ,\n    \\end{cases}\n\\end{equation}\nwith similar expressions for $u_y$ and $u_z$.\nThe most general solution to \\cref{eq:diffusion} decouples $u_z$ from $u_x$ and $u_y$.\nThe requirement $\\lim_{x → ± ∞} u(x) = 0$ yields\n\\begin{subequations}\n  \\begin{alignat}{3}\n    & u_{z±} (x) && {}={} && A^∓ e^{∓ k x}                     , \\\\\n    & u_{z0} (x) && {}={} && A_0^+ e^{k x} {}+{} A_0^- e^{-k x} ,\n  \\end{alignat}\n\\end{subequations}\nand\n\\begin{subequations}\n  \\begin{alignat}{6}\n    & u_{x±} (x) && =   && B^∓ e^{∓ κ x} && {}+{} &&   && C^∓ e^{∓ \\bar{κ} x} , \\\\\n    & u_{y±} (x) && = i && B^∓ e^{∓ κ x} && {}-{} && i && C^∓ e^{∓ \\bar{κ} x} ,\n  \\end{alignat}\n  \\begin{alignat}{12}\n    & u_{x0} (x) && =   && B_0^+ e^{κ x} && {}+{} &&   && B_0^- e^{- κ x} && {}+{} &&   && C_0^+ e^{ \\bar{κ} x } && {}+{} &&   && C_0^- e^{ - \\bar{κ} x } , \\\\\n    & u_{y0} (x) && = i && B_0^+ e^{κ x} && {}+{} && i && B_0^- e^{- κ x} && {}-{} && i && C_0^+ e^{ \\bar{κ} x } && {}-{} && i && C_0^- e^{ - \\bar{κ} x } ,\n  \\end{alignat}\n\\end{subequations}\nwhere $κ = k \\sqrt{1 + i ω τ}$.\nThe twelve constants $A$, $B$ and $C$ (with their various subscripts and superscripts) must be determined by imposing the appropriate boundary conditions.\n\nWe first require $u$ be continuous at $x = 0$ and $x = L$; this gives six equations.\nWe now require a boundary condition on $∇u$, but $∇u$ cannot be assumed continuous at the contact.\nWe make the assumption that the total spin current at the contact\nis the sum of the spin currents on either side, i.e.,\n\\begin{subequations}\n  \\label{eq:current.sum}\n  \\begin{alignat}{2}\n    & ȷ_0 && = σ^N \\left[ - u_-'(0) + u_0'(0) \\right] , \\\\\n    & ȷ_L && = σ^N \\left[ - u_0'(L) + u_+'(L) \\right] .\n  \\end{alignat}\n\\end{subequations}\nThe signs have been chosen to be consistent with the physical geometry.\nThe only nonzero component of the current at the contacts inside the semiconductor\nis the $x$ component at $x = 0$, so we use \\cref{eq:bdry_solutions.current}.\nFor all other components there is zero current at the contact, and we use\n\\cref{eq:bdry_solutions.zero.current}.\nTogether with \\cref{eq:current.sum}, this gives the other six equations,\n\\begin{subequations}\n  \\begin{alignat}{8}\n    & - & {} & u_{z-}'(0) & {}+{} & u_{z0}'(0) & {}+{} & η_0 u_z(0) && = 0 , \\\\\n    &   & {} & u_{z+}'(L) & {}-{} & u_{z0}'(L) & {}+{} & η_L u_z(L) && = 0 , \\\\\n    & - & {} & u_{x-}'(0) & {}+{} & u_{x0}'(0) & {}+{} & η_0 u_x(0) && = Δ , \\\\\n    &   & {} & u_{x+}'(L) & {}-{} & u_{x0}'(L) & {}+{} & η_L u_x(L) && = 0 , \\\\\n    & - & {} & u_{y-}'(0) & {}+{} & u_{y0}'(0) & {}+{} & η_0 u_y(0) && = 0 , \\\\\n    &   & {} & u_{y+}'(L) & {}-{} & u_{y0}'(L) & {}+{} & η_L u_y(L) && = 0 ,\n  \\end{alignat}\n\\end{subequations}\nwhere\n\\begin{subequations}\n  \\begin{alignat}{2}\n  & η_i^{-1} && = - σ^N \\left( R_F + R_C^i \\right) , \\\\\n  & Δ && = - (- J_0) \\left( P_σ^F R_F + P_Σ^0 R_C^0 \\right) η_0 .\n  \\end{alignat}\n\\end{subequations}\nWe define the $r$-parameter, $r_i = - η_i^{-1}$, introduced in \\cref{eq:r-parameter}.\n\nThese equations can be organized into a matrix equation and solved algebraically.\nA solution for $u_z$ corresponds to a condition of vanishing determinant,\n\\begin{equation}\n  e^{-2 L / λ} = \\left( 1 + \\frac{2 r_0}{λ} \\right) \\left( 1 + \\frac{2 r_L}{λ} \\right) ,\n\\end{equation}\nwhich can never be satisfied\n\\footnote{\n  Except at the nonphysical point $L / λ = r_i / λ = 0$.\n},\nthus $u_z = 0$ is the only allowed solution.\nThe other two components form an eight dimensional linear system.\nSolving this gives the remaining constants, and thus\n$u_x (L) = e^{- κ L} B^- + e^{- \\bar{κ} L} C^-$.\n\nFinally, by using $p_1 = - σ^N Δ / J_0$ along with \\cref{eq:rnl.full},\nwe can introduce $\\rSQ$ from \\cref{eq:square_resistance}\nand the polarizations\n\\begin{subequations}\n  \\label{eq:polarizations}\n  \\begin{align}\n    p_1 & = \\frac{P_σ^F R_F + P_Σ^L R_C^L}{R_F + R_C^L} , \\\\\n    p_2 / p_1 & = \\left. \\left( 1 - \\frac{P_σ^F R_F}{P_Σ^L R_C^L} \\right) \\middle/\n                  \\left(1 + \\frac{P_σ^F R_F}{P_Σ^L R_C^L} \\right) \\right. ,\n  \\end{align}\n\\end{subequations}\nto write\n\\begin{equation}\n  \\frac{\\rNLeff}{\\rSQ} = \\frac{p_1 p_2}{W / λ} \\left[ - \\frac{k u_x (L)}{Δ} \\right] .\n\\end{equation}\nThe factor in brackets is the function $f$ given in \\cref{eq:f}.\n", "meta": {"hexsha": "6356f3ed329ca0eb03c69c8e7bdf0ba0ce260e0c", "size": 15292, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/_appendix.tex", "max_stars_repo_name": "evansosenko/aps-spin-lifetime", "max_stars_repo_head_hexsha": "1f7a6188a0320c0bf8f5441cfcf20861ce259acb", "max_stars_repo_licenses": ["Ruby"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tex/_appendix.tex", "max_issues_repo_name": "evansosenko/aps-spin-lifetime", "max_issues_repo_head_hexsha": "1f7a6188a0320c0bf8f5441cfcf20861ce259acb", "max_issues_repo_licenses": ["Ruby"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/_appendix.tex", "max_forks_repo_name": "evansosenko/aps-spin-lifetime", "max_forks_repo_head_hexsha": "1f7a6188a0320c0bf8f5441cfcf20861ce259acb", "max_forks_repo_licenses": ["Ruby"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0660377358, "max_line_length": 158, "alphanum_fraction": 0.6220899817, "num_tokens": 5734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.33129662141100197}}
{"text": "\\documentclass[a4paper,11pt,final]{article}\n\\usepackage[american]{babel}\n\\usepackage[T1]{fontenc}\n\\usepackage{graphicx}\n\\usepackage[svgnames]{xcolor}\n\\usepackage{amsmath}\n\\usepackage[utf8]{inputenc}\n\\usepackage[pdfborder={0 0 0}]{hyperref}\n\\usepackage{mathptmx}\n\\hypersetup{\n    pdftitle={CamSim Physically-Based Rendering Model},\n    pdfauthor={Martin Lambers}\n} \n\n\\begin{document}\n\n\\section*{CamSim illumination model}\n\nThis describes the illumination model (direct and single-bounce indirect) used\nin CamSim.\n\nIt is based on this paper:\n  M. Lambers, S. Hoberg, A. Kolb:\n  Simulation of Time-of-Flight Sensors for Evaluation of Chip Layout Variants.\n  In IEEE Sensors Journal, 15(7), 2015, pages 4019-4026.\n\nThe extension for single-bounce indirect illumination is loosely based on this paper:\n  D. Bulczak, M. Lambers, A. Kolb:\n  Quantified, Interactive Simulation of AMCW ToF Camera Including Multipath\n  Effects.\n  In MDPI Sensors, 18(1), 2018, pages 1424-8220.\n\n\\section{Symbols}\n\n\\subsection{Radiometric}\n\n$Q$: Radiant energy $[J]$\\\\\n$P$: Radiant flux (``power'') $[W]$\\\\\n$I$: Radiant intensity $[W/\\mathrm{sr}]$\\\\\n$L$: Radiance (``radiant flux per unit solid angle per unit projected area'') $[W/\\mathrm{sr}/m^2]$\\\\\n$E$: Irradiance $[W/m^2]$\n\n\\subsection{Geometric}\n\n$L$: Light source position\\\\\n$C$: Camera center position\\\\\n$P$: Point on object surface seen by camera pixel\\\\\n$\\widehat{n_P}$: Surface normal at $P$\\\\\n$\\theta_{P\\rightarrow L}$: Angle between $\\widehat{n_P}$ and $\\widehat{L-P}$\\\\\n$Q$: Another point (on another surface) that may act as a virtual point light\\\\\n$\\widehat{n_Q}$: Surface normal at $Q$\\\\\n$\\theta_{Q\\rightarrow L}$: Angle between $\\widehat{n_Q}$ and $\\widehat{L-Q}$\n\n\\subsection{Other}\n\n$f_P(\\widehat{L-P}, \\widehat{n_P}, \\widehat{C-P})$: BRDF for $L\\rightarrow P\\rightarrow C$\\\\\n$f_Q(\\widehat{L-Q}, \\widehat{n_Q}, \\widehat{P-Q})$: BRDF for $L\\rightarrow Q\\rightarrow P$\\\\\n\n\n\\section{Direct Illumination}\n\n$I_{L\\rightarrow P} = \\frac{P_L}{4\\pi}$ (if $L$ is point light; there are alternatives)\\\\\n$L_{L\\rightarrow P} = \\frac{I_{L\\rightarrow P}}{d^2_{L\\rightarrow P}}$\\\\\n$L_{P\\rightarrow C} = f_P(\\widehat{L-P}, \\widehat{n_P}, \\widehat{C-P}) L_{L\\rightarrow P} \\cos(\\theta_{P\\rightarrow L})$\\\\\n$E_C = L_{P\\rightarrow C}$ ~~~(Note: no factor $\\cos(\\theta_{C\\rightarrow P})$ here)\\\\\n$P_C = E_C \\cdot \\mathrm{SensorPixelArea}$\\\\\n$Q_C = P_C \\cdot \\mathrm{SignalDutyCycle} \\cdot \\mathrm{ExposureTime}$\n\n\n\\section{Indirect Illumination via Virtual Point Lights}\n\nStart with the Rendering Equation:\\\\\n$\\displaystyle L_{P\\rightarrow C} = \\int_\\Omega f_P(\\omega_i, \\widehat{n_P}, \\widehat{C-P}) L_{i\\rightarrow P} \\cos(\\theta_i) d\\omega_i$\n\n\\noindent\nApproximate this by splitting into direct and indirect parts, and approximating\nthe indirect part with single-bounce RSM VPLs:\\\\\n$\\displaystyle L_{P\\rightarrow C} = f_P(\\widehat{L-P}, \\widehat{n_P}, \\widehat{C-P}) L_{L\\rightarrow P} \\cos(\\theta_{P\\rightarrow L})\n + \\frac{1}{|\\mathrm{RSM}|}\\sum_{Q\\in \\mathrm{RSM}} f_P(\\widehat{Q-P}, \\widehat{n_P}, \\widehat{C-P}) L_{Q\\rightarrow P} \\cos(\\theta_{P\\rightarrow Q})$\n\n\\noindent\nThe direct part is already computed in the direct step as $L_{P\\rightarrow C}$. Add the indirect part to it:\\\\\n$\\displaystyle L^*_{P\\rightarrow C} = L_{P\\rightarrow C}\n + \\frac{1}{|\\mathrm{RSM}|}\\sum_{Q\\in \\mathrm{RSM}} f_P(\\widehat{Q-P}, \\widehat{n_P}, \\widehat{C-P}) L_{Q\\rightarrow P} \\cos(\\theta_{P\\rightarrow Q})$\n\n\\noindent\nusing\n$L_{Q\\rightarrow P} = f_Q(\\widehat{L-Q}, \\widehat{n_Q}, \\widehat{P-Q}) L_{L\\rightarrow Q} \\cos(\\theta_{Q\\rightarrow L})$\\\\\nand\n$L_{L\\rightarrow Q} = \\frac{I_{L\\rightarrow Q}}{d^2_{L\\rightarrow Q}}, \\quad I_{L\\rightarrow Q} = \\frac{P_L}{4\\pi}$\n\n\n\\section{Values to Store in RSM}\n\n\\begin{itemize}\n\\item Parameters that allow BRDF sampling at $Q$, e.g. $k_d, k_s, s$ for modified Phong\n\\item Position of $Q$ (to perform shadow test and to compute $\\widehat{Q-P}$,\n$\\theta_{P\\rightarrow Q}$, $\\widehat{L-Q}$, $\\widehat{P-Q}$,$ \\theta_{Q\\rightarrow L}$)\n\\item $\\widehat{n_Q}$\n\\item $L_{L\\rightarrow Q}$\n\\end{itemize}\n\n%\\section{Notes}\n%\n%\\begin{itemize}\n%\\item Visibility tests:\n%    \\begin{itemize}\n%    \\item $P\\rightarrow C$: rasterization does this for us\n%    \\item $L\\rightarrow P$: per shadow map test\n%    \\item $L\\rightarrow Q$: rasterization of the RSM ensures that only lighted points are in the RSM; this visibility test is implicit\n%    \\item $Q\\rightarrow P$: not included in original RSM approach, BUT:\n%        \\begin{itemize}\n%        \\item Project $P$ into RSM of $Q$\n%        \\item Cast ray from $Q$ to $P$ and traverse it \\textbf{in Q's RSM space}\n%        \\item Find obstacles based on depth values\n%        \\end{itemize}\n%    \\end{itemize}\n%\\end{itemize}\n\n\\end{document}\n", "meta": {"hexsha": "acecbeb737fb0630e6218cfc3774a02bddb28e5e", "size": 4728, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/illumination.tex", "max_stars_repo_name": "Tetsu5902/camsim", "max_stars_repo_head_hexsha": "bcf995bb30e44792414ca2afd30a2869030b1f92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-02-19T14:03:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T08:26:01.000Z", "max_issues_repo_path": "doc/illumination.tex", "max_issues_repo_name": "Tetsu5902/camsim", "max_issues_repo_head_hexsha": "bcf995bb30e44792414ca2afd30a2869030b1f92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/illumination.tex", "max_forks_repo_name": "Tetsu5902/camsim", "max_forks_repo_head_hexsha": "bcf995bb30e44792414ca2afd30a2869030b1f92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-02-25T22:51:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-05T08:26:05.000Z", "avg_line_length": 39.0743801653, "max_line_length": 150, "alphanum_fraction": 0.6943739425, "num_tokens": 1575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.33129662141100197}}
{"text": "\\SecDef{intro}{Introduction}\n\nLightweight cryptography is a modern direction in the design of symmetric-key primitives. It aims to provide cryptographic security with constrained resources. Lightweight ciphers usually have a low security margin against unknown attacks and rely on the cryptanalysis done in the design phase.\n\nMy colleagues developed a framework for benchmarking lightweight ciphers, called FELICS~\\cite{Felics,Felics1,Felics2}. A large amount of implementations for 3 target platforms - AVR, MSP, ARM - was collected and benchmarked. The leading block ciphers were Chaskey~\\cite{Chaskey}, Simon and Speck~\\cite{Simon}, RECTANGLE~\\cite{RECTANGLE}, LEA\\cite{LEA}, HIGHT~\\cite{HIGHT}, AES~\\cite{AES}. Chaskey is an Even-Mansour block cipher and has a data-security trade-off; it does not have a security proof against linear/differential attacks. Simon and Speck were designed by the NSA and do not have a proof too. \n\nAs the top designs are ARX-based, i.e. they are composed from Addition, Rotation and XOR operations, we decided to design an ARX-based block cipher. However, the current \\emph{wide-trail strategy} for proving security against linear/differential cryptanalysis does not apply well to ARX-based block ciphers. For this reason, we developed a novel \\emph{long-trail strategy}. As a result, the block cipher \\sparx{} is the first ARX-based block cipher with provable security against single-trail linear and differential cryptanalysis.\n\nIn this chapter, I describe briefly the long-trail strategy.\nAfterward, I describe my contributions to the design. I developed an algorithm for efficient long-trail evaluation of a large class of SPN structures. We used this algorithm and the division property~\\cite{division} to evaluate a large class of potential linear layers. Interestingly, a Feistel-like linear layer turned out to provide an optimal balance between the linear/differential and integral attacks resistance, lightweightness of the primitive and simplicity. A few alternative linear layers seem to be a good choice as well.\n\n\\subsection{Outline}\nI describe briefly the long-trail strategy and my algorithms in \\SecRef{longtrail}. In \\SecRef{linear}, I describe the procedure that we used to choose an optimal linear layer for the cipher.\nI omit the specification of \\sparx{}, because it is not required for the contents of this chapter; it can be found in~\\cite{OurSPARX}.", "meta": {"hexsha": "4a75620ee395ed6014ae0be19b49ea96eefccea4", "size": 2409, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis-source/9deSPARX/1intro.tex", "max_stars_repo_name": "hellman/thesis", "max_stars_repo_head_hexsha": "6ba1c2b241e63c07cf76108481c1b67f21a50f12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2019-05-16T19:55:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-31T15:36:12.000Z", "max_issues_repo_path": "thesis-source/9deSPARX/1intro.tex", "max_issues_repo_name": "hellman/thesis", "max_issues_repo_head_hexsha": "6ba1c2b241e63c07cf76108481c1b67f21a50f12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-09T11:26:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-09T11:26:45.000Z", "max_forks_repo_path": "thesis-source/9deSPARX/1intro.tex", "max_forks_repo_name": "hellman/thesis", "max_forks_repo_head_hexsha": "6ba1c2b241e63c07cf76108481c1b67f21a50f12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-05T19:40:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-05T19:40:16.000Z", "avg_line_length": 172.0714285714, "max_line_length": 605, "alphanum_fraction": 0.8061436281, "num_tokens": 537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.33129662141100197}}
{"text": "\\documentclass[review]{elsarticle}\n\n\\usepackage{amsmath}\n\\usepackage{lineno,hyperref}\n\\modulolinenumbers[5]\n\\usepackage{caption}\n\\usepackage{subcaption}\n\\captionsetup{font=small}\n\\captionsetup[sub]{font=footnotesize}\n\\usepackage{nicefrac}\n\\usepackage{booktabs}\n\\usepackage[usenames]{xcolor}\n\\usepackage{units}\n\\usepackage[acronyms]{glossaries}\n\\usepackage[ruled,vlined]{algorithm2e}\n\n\\journal{Elsevier}\n\n%% `Elsevier LaTeX' style\n%\\bibliographystyle{elsarticle-num}\n\\bibliographystyle{elsarticle-num-names}\n\\makeatletter\n\\providecommand{\\doi}[1]{%\n  \\begingroup\n  \\let\\bibinfo\\@secondoftwo\n  \\urlstyle{rm}%\n  \\href{http://dx.doi.org/#1}{%\n    doi:\\discretionary{}{}{}%\n    \\nolinkurl{#1}%\n  }%\n  \\endgroup\n}\n\\makeatother\n\n%=================================================================================\n% Useful commands\n\\newcommand{\\ud}{\\,\\mathrm{d}}\n\\newcommand{\\pfrac}[2]{\\frac{\\partial#1}{\\partial#2}}\n\\newcommand{\\dpfrac}[2]{\\dfrac{\\partial#1}{\\partial#2}}\n\\newcommand{\\ufrac}[2]{\\frac{\\ud{}#1}{\\ud{}#2}}\n\\newcommand{\\dufrac}[2]{\\dfrac{\\ud{}#1}{\\ud{}#2}}\n\\newcommand{\\wt}[1]{\\widetilde{#1}}\n\\newcommand{\\ol}[1]{\\overline{#1}}\n\n%=================================================================================\n% Abbreviations\n\\newacronym{dns}{DNS}{direct numerical simulations}\n\\newacronym{les}{LES}{large eddy simulations}\n\\newacronym{pdf}{PDF}{probability density function}\n\\newacronym{pmf}{PMF}{probability mass function}\n\\newacronym{ml}{ML}{machine learning}\n\\newacronym{dnn}{DNN}{deep neural network}\n\\newacronym{dof}{DoFs}{degrees of freedom}\n\\newacronym{rmse}{RMSE}{root mean square error}\n\\newacronym{sgs}{SGS}{subgrid-scale}\n\\newacronym{wale}{WALE}{Wall Adapting Local Eddy-Viscosity}\n\\newacronym{sgd}{SGD}{stochastic gradient descent}\n\\makeglossaries\n\\glsdisablehyper\n\n\n%=================================================================================\n% Document\n\\begin{document}\n\n\\begin{frontmatter}\n\\title{A block-random algorithm for learning on distributed, heterogeneous data}\n\\author[ut]{Prakash Mohan}\n\\ead{prak@utexas.edu}\n\\author[nrel_hpacf]{Marc T. Henry de Frahan}\n\\ead{Marc.HenrydeFrahan@nrel.gov}\n\\author[nrel_cssog]{Ryan King}\n\\ead{Ryan.King@nrel.gov}\n\\author[nrel_hpacf]{Ray W. Grout}\n\\ead{Ray.Grout@nrel.gov}\n\\address[ut]{Institute for Computational Engineering and Sciences, The University of Texas at Austin, 201 E. 24th Street, POB 4.102, Austin, Texas 78712, USA}\n% \\address[nrel]{Computational Science Center, National Renewable Energy Laboratory, 15013 Denver W Pkwy, ESIF301, Golden, CO 80401, USA}\n\\address[nrel_hpacf]{High Performance Algorithms and Complex Fluids, Computational Science Center, National Renewable Energy Laboratory, 15013 Denver W Pkwy, ESIF301, Golden, CO 80401, USA}\n\\address[nrel_cssog]{Complex Systems Simulation and Optimization Group, Computational Science Center, National Renewable Energy Laboratory, 15013 Denver W Pkwy, ESIF301, Golden, CO 80401, USA}\n\n\n\\begin{abstract}\n\n  Most deep learning models are based on deep neural networks with\n  multiple layers between input and output. The parameters defining\n  these layers are initialized using random values and are ``learned''\n  from data, typically using stochastic gradient descent based\n  algorithms. These algorithms rely on data being randomly shuffled\n  before optimization. The randomization of the data prior to\n  processing in batches that is formally required for stochastic\n  gradient descent algorithm to effectively derive a useful deep\n  learning model is expected to be prohibitively expensive for in situ\n  model training because of the resulting data communications across\n  the processor nodes. We show that the \\gls{sgd} algorithm can still\n  make useful progress if the batches are defined on a per-processor\n  basis and processed in random order even though (i) the batches are\n  constructed from data samples from a single class or specific flow\n  region, and (ii) the overall data samples are heterogeneous. We\n  present block-random gradient descent, a new algorithm that works on\n  distributed, heterogeneous data without having to pre-shuffle. This\n  algorithm enables in situ learning for exascale simulations. The\n  performance of this algorithm is demonstrated on a set of benchmark\n  classification models and the construction of a subgrid scale\n  \\gls{les} model for turbulent channel flow using a data model\n  similar to that which will be encountered in exascale simulation.\n  \n\\end{abstract}\n\n\\begin{keyword}\n  stochastic gradient descent \\sep distributed \\sep block-random \\sep channel flow \n\\end{keyword}\n\n\\end{frontmatter}\n\n\\glsresetall\n\n\\section{Introduction}\\label{sec:intro}\n\nSimulating complex physics problems while resolving all the relevant\nlength scales is computationally expensive, requiring millions of core\nhours to compute a single realization. Combining \\gls{dns} with an\noptimization or design cycle is infeasible, creating a need for\nreduced-order models. Deep learning is an increasingly popular and\neffective modeling technique that use many data to train a neural\nnetwork for a variety of tasks~\\cite{Lecun2015, Schmidhuber2015,\n  Prieto2016, Goodfellow2016, Liu2017}. These tasks range from visual\nobject recognition and speech recognition to analyzing particle\naccelerator data and drug design. Recently, deep learning has been\nexplored as a tool for creating reduced-order closure models in\nturbulent fluid flows~\\cite{ling2016reynolds, duraisamy2015new,\n  duraisamy2019turbulence}.\n\nFor physics simulation, the advent of exascale computing will enable\nunprecedentedly high-fidelity simulations. The expectation is to\nderive reduced-order models for engineering and design applications\nfrom the many data generated by these simulations. Because it will be\nincreasingly difficult to save the large amounts of data generated\nduring the simulations for offline training, this will drive the need\nto change existing approaches for training deep learning\nmodels. Online or in situ training, where the model is trained during\nthe simulation to avoid data storage, has the potential to alleviate\nthis problem. A data parallel~\\cite{zinkevich2010parallelized}\nparadigm for deep learning is a practical approach for online\ntraining. In this setting, there are two distinct computational\nclusters: one for the physics computations and the other for deep\nlearning. Data will be transferred from the physics cluster to the\ndeep learning cluster as needed by the learning algorithms.\n\nMost deep learning models use artificial neural networks with multiple\nlayers to capture nonlinearities. The parameters defining these layers\nare ``learned'' from data, typically using algorithms that approximate\ngradient descent. With the increase in the amount of available data,\ndeterministic learning algorithms are often expensive and rarely used\nin practice.  \\Gls{sgd}~\\cite{bottou2010large, Goodfellow2016} and\nvariants using ``mini-batches'' are commonly used algorithms for practical\nlearning problems. The stochastic algorithms require the data to be\nrandomly shuffled~\\cite{bottou2010large, Goodfellow2016} for\noptimization; however, because fully shuffling the data will be\ninfeasible for exascale simulations because of the communication costs\nof moving the data between processor nodes, the data shuffling\nstrategy necessary for \\gls{sgd} will need to adapt to ensure the\nadequate representation of the vastly differing physical processes\noccurring in the simulation domain. Shuffling data extracted from a\nsingle computational node will not provide sufficient randomness\nbecause correlations tend to be spatially localized. The randomization\nof the data prior to processing in batches that is formally required\nfor \\gls{sgd} to make progress is expected to be prohibitively\nexpensive for in situ model training. We illustrate the memory\npatterns in Figure\\,\\ref{fig:access_patterns} for the simulation of a\npassively advected scalar using adaptive mesh refinement (setup\ndefined in the AMReX\ntutorial\\footnote{\\url{https://github.com/AMReX-Codes/amrex}}). The\nblocks of data are distributed among the different processors and are\nheterogeneous, with the mesh adaptivity refining areas of\ninterest. The memory access pattern for fully shuffling the data for\n\\gls{sgd} is shown in Figure\\,\\ref{fig:shuffled_access}. This type of\nmemory access is detrimental to the simulation performance because the\nmemory access is uncoalesced, disregards data locality, and requires\nmany global communications. A single global communication to transfer a large\ncontiguous chunk of data from one processor is more efficient than many\ncommunications transferring smaller chunks of data from multiple processors. We\nshow that the \\gls{sgd} algorithm can still make useful progress if the batches\nare defined on a per-processor basis and processed in random order even though\n(i) the batches are constructed from data samples from a single class or\nspecific flow region, and (ii) the overall data samples are heterogeneous. In\nthis work, we present a new block-random algorithm that works on distributed,\nheterogeneous data without having to pre-shuffle.\n\n\\begin{figure}[!tbp]%\n  \\centering%\n  \\begin{subfigure}[t]{0.32\\textwidth}%\n    \\includegraphics[width=\\textwidth]{./figs/singlevortex.png}%\n    \\caption{Advection of a passive scalar. Red: level 0; green: level 1; blue: level 2.}\\label{fig:singlevortex}%\n  \\end{subfigure}\\hfill%\n  \\begin{subfigure}[t]{0.32\\textwidth}%\n    \\includegraphics[width=\\textwidth]{./figs/proc_access.png}%\n    \\caption{Memory layout of the simulation data on the different processor ranks. Colors denote the processor ranks.}\\label{fig:proc_access}%\n  \\end{subfigure}\\hfill%\n  \\begin{subfigure}[t]{0.32\\textwidth}%\n    \\includegraphics[width=\\textwidth]{./figs/shuffled_access.png}%\n    \\caption{Fully shuffled memory access for training with \\gls{sgd}. Colors denote the different batches.}\\label{fig:shuffled_access}%\n  \\end{subfigure}%\n  \\caption{Illustration of memory access patterns for the simulation of a vortex using adaptive mesh refinement from the AMReX tutorial.}\\label{fig:access_patterns}%\n\\end{figure}%\n\nThis paper is organized as follows. In Section\\,\\ref{sec:methods}, we\npresent the problem formulation and describe the proposed methodology\nfor deep learning of distributed, heterogeneous data. In\nSection\\,\\ref{sec:results}, we detail the architecture of the deep\nconvolutional neural network used to perform the data recovery process\nfor fluid flows. In Section\\,\\ref{sec:benchmarks}, we evaluate our\nproposed method on the EMNIST data sets, a standard set of benchmark\nproblems commonly used in deep learning. In\nSection\\,\\ref{sec:channel}, we apply our methodology to a challenge\nproblem representative of those encountered for in situ deep learning\nin large scale simulations. We construct \\gls{sgs} stress models for\nlarge eddy simulations using our proposed methodology and compare it\nto standard approaches. Finally, we present conclusions and future work\nin Section\\,\\ref{sec:ccl}.\n\n\\section{Methods}\\label{sec:methods}\nGradient descent-based algorithms are typical optimization methods used for\ntraining \\glspl{dnn}.  Gradient descent is an algorithm to find the set of parameters\n$\\theta$ that minimize a cost function $J(\\theta)$. In the case of \\glspl{dnn}, the cost\nfunction is usually a normed distance between the predictions and data in a\ntraining set. The simplest form of gradient descent is:\n\\begin{equation}\n\\theta_{k+1} = \\theta_k - \\eta \\nabla_{\\theta_k} J(\\theta_k)\n\\label{eq:GD}\n\\end{equation}\nwhere $\\eta$ is the learning rate, $k$ denotes subsequent iterations\nof the gradient descent algorithm, and $J$ is computed on the entire\ntraining data set. For very large data sets, this algorithm is very\nslow because it computes the cost function on the entire data set for\na single update of the parameters. \\Gls{sgd}, in contrast, performs a\nparameter update for each sample in the training data set. \\gls{sgd}\nand \\gls{sgd} variants --- such as Adam~\\cite{kingma2014adam},\nRMSprop~\\cite{tieleman2012lecture} and\nAdagrad~\\cite{duchi2011adaptive} --- have proved to be effective ways\nof training \\glspl{dnn}. A common addition to \\gls{sgd} is to add\n``mini-batching'', where the training data are partitioned into\nbatches of size $n_b$. The batching procedure is used to provide\nsequences of approximations of the gradient of the cost function with\nrespect to the parameters by computing:\n\\begin{equation}\n  \\nabla_{\\theta_k} J(\\theta_k|x \\in b, y \\in b)\n\\end{equation}\nwhere $b$ is a batch of training data. Mini-batching provides a better\nestimate of $\\nabla_\\theta J(\\theta)$ by using several samples from\nthe training set instead of only one sample. As a result, the\nparameter updates tend to be less noisy. It is also computationally\nmore efficient by using vectorized computations and parallelism\nprovided by modern architectures. In practice, the shuffled training\ndata is divided into batches, the batches are then randomly shuffled\nbefore each pass through the training data, and each batch is used to\nprovide gradient approximations to update the neural network model\nparameters. It has been shown that the \\gls{sgd} gradient\napproximations converge to the true gradient in\nexpectation~\\cite{bottou2010large}.\n\nBeing stochastic, however, these algorithms require the data to be randomly\nshuffled to converge to a minimum of the cost function. Results from\nSection \\ref{sec:benchmarks} show how these algorithms fail to converge without\nshuffling when the batches have inherent bias.  As described in Section\n\\ref{sec:intro}, this shuffling operation is infeasible for online learning on\nexascale simulations. We propose a block-random algorithm for use in these\ncases where the data ordering needs to remain unchanged. The algorithm operates\nby swapping the order of shuffling and batching operations. This shuffling of\nbatches appears to be sufficient for learning the parameters even when the data\nare highly ordered, resulting in batches with high bias. Although individual\nbatches have high bias, this shuffling operation ensures that the same bias is\nnot seen by the optimizer consecutively, enabling it to still get to a local\nminima of the cost function. This behavior will be shown over a variety of\nbenchmark problems in Section \\ref{sec:results}. In a distributed data setting,\nthe shuffling of batches will be achieved by picking a random block of data and\ngetting a batch of size $n_b$ from it.\n\n\\begin{algorithm}[h]\n\\DontPrintSemicolon\n    \\textbf{Parameters:} learning rate $\\eta$, batch size $n_b$, number of epochs $n_e$\\;\n    \\KwIn{training data with N samples}\n    \\SetAlgoLined\n    \\While{$i \\leq n_e$}{\n        randomly shuffle data\\;\n        partition data into mini batches $B_k$ of size $n_b$\\;\n        \\While{$k \\leq \\nicefrac{N}{n_b}$}{\n          $\\theta_{k+1} = \\theta_k - \\eta \\nabla_{\\theta_k} J(\\theta_k|B_k)$\\;\n          $k = k +1$\\;\n        }\n        $i = i +1$\\;\n    }\n    \\caption{Stochastic gradient descent with mini-batching}\\label{algo:mini-batch}\n\\end{algorithm}\n\n\\begin{algorithm}[H]\n    \\DontPrintSemicolon\n    \\textbf{Parameters:} learning rate $\\eta$, batch size $n_b$, number of epochs $n_e$\\;\n    \\KwIn{training data with N samples}\n    \\SetAlgoLined\n    partition data into batches $B_k$ of size $n_b$\\;\n    \\While{$i \\leq n_e$}{\n        \\While{$k \\leq \\nicefrac{N}{n_b}$}{\n          $\\theta_{k+1} = \\theta_k - \\eta \\nabla_{\\theta_k} J(\\theta_k|B_k)$\\;\n          $k = k +1$\\;\n        }\n        $i = i +1$\\;\n    }\n    \\caption{Block-unshuffled gradient descent}\\label{algo:block-unshuffled}\n\\end{algorithm}\n\n\\begin{algorithm}[H]\n    \\DontPrintSemicolon\n    \\textbf{Parameters:} learning rate $\\eta$, batch size $n_b$, number of epochs $n_e$\\;\n    \\KwIn{training data with N samples}\n    \\SetAlgoLined\n    partition data into mini batches $B_k$ of size $n_b$\\;\n    \\While{$i \\leq n_e$}{\n        randomly shuffle ordering of batches $B_k$\\;\n        \\While{$k \\leq \\nicefrac{N}{n_b}$}{\n            $\\theta_{k+1} = \\theta_k - \\eta \\nabla_{\\theta_k} J(\\theta_k|B_k)$\\;\n            $k = k +1$\\;\n        }\n        $i = i +1$\\;\n    }\n    \\caption{Block-random gradient descent}\\label{algo:block-random}\n\\end{algorithm}\n\nThroughout this work, a batch denotes the data set that is used by the\n\\gls{sgd} algorithm to evaluate the model and perform the\nback-propagation of the neural network weights. A block, or a class\nfor the image classification benchmark problems, denotes a homogeneous\ndata set that is distributed among the multiple processors. An epoch\nconsists of training the model on the entire training data set.\n\nThe relative performance of the algorithms will be tested on a suite\nof data sets with the results shown in Section \\ref{sec:results}. Each\ndata set will be tested in three different scenarios: (i)\n\\textit{shuffled} --- fully shuffling all the data and then creating\nthe batches (Algorithm\\,\\ref{algo:mini-batch}); (ii)\n\\textit{block-unshuffled} --- arranging the data in blocks to\nemphasize bias and running it without shuffling\n(Algorithm\\,\\ref{algo:block-unshuffled}); (iii) \\textit{block-random}\n--- accessing the arranged blocks in a block-random fashion\n(Algorithm\\,\\ref{algo:block-random}). For the\n\\textit{block-unshuffled} and \\textit{block-random} cases, we pick the\nworst-case scenario for the bias. For instance, in the image\nclassification case, each block (and consequently each batch) will\ncontain only one class as shown in Table\\,\\ref{table:illustration}.\n\n\\begin{table}[!htb]\n    \\begin{subtable}{.3\\linewidth}\n      \\centering\n        \\begin{tabular}{ | c | c | c | c | c | }\n        \\hline\n            4 & 0 & 2 & \\ldots & 1 \\\\\n            3 & 2 & 9 & \\ldots & 6 \\\\\n            8 & 7 & 1 & \\ldots & 8 \\\\\n            9 & 8 & 4 & \\ldots & 5 \\\\\n            0 & 5 & 5 & \\ldots & 7 \\\\\n            6 & 1 & 3 & \\ldots & 2 \\\\\n            5 & 3 & 6 & \\ldots & 9 \\\\\n          \\vdots & \\vdots& \\vdots & \\ldots & \\vdots  \\\\\n            1 & 3 & 5 & \\ldots & 7 \\\\\n        \\hline\n        \\end{tabular}\n        \\caption{\\it shuffled}\n    \\end{subtable}%\n    \\begin{subtable}{.4\\linewidth}\n      \\centering\n        \\begin{tabular}{ | c | c | c | c | c | c | }\n        \\hline\n            0 & 0 & \\ldots & 1 & \\ldots & 9 \\\\\n            0 & 0 & \\ldots & 1 & \\ldots & 9 \\\\\n            0 & 0 & \\ldots & 1 & \\ldots & 9 \\\\\n            0 & 0 & \\ldots & 1 & \\ldots & 9 \\\\\n            0 & 0 & \\ldots & 1 & \\ldots & 9 \\\\\n            0 & 0 & \\ldots & 1 & \\ldots & 9 \\\\\n            0 & 0 & \\ldots & 1 & \\ldots & 9 \\\\\n            \\vdots & \\vdots& \\vdots & \\vdots &  \\vdots & \\vdots  \\\\\n            0 & 0 & \\ldots & 1 & \\ldots & 9 \\\\\n        \\hline\n        \\end{tabular}\n        \\caption{\\it block-unshuffled}\n    \\end{subtable}%\n    \\begin{subtable}{.4\\linewidth}\n      \\centering\n        \\begin{tabular}{ | c | c | c | c | c | }\n        \\hline\n            4 & 3 & 8 & 0 & \\ldots \\\\\n            4 & 3 & 8 & 0 & \\ldots \\\\\n            4 & 3 & 8 & 0 & \\ldots \\\\\n            4 & 3 & 8 & 0 & \\ldots \\\\\n            4 & 3 & 8 & 0 & \\ldots \\\\\n            4 & 3 & 8 & 0 & \\ldots \\\\\n            4 & 3 & 8 & 0 & \\ldots \\\\\n            \\vdots & \\vdots& \\vdots & \\vdots &  \\vdots \\\\\n            4 & 3 & 8 & 0 & \\ldots \\\\\n        \\hline\n        \\end{tabular}\n        \\caption{\\it block-random}\n    \\end{subtable}\n    \\caption{\n    Illustration of batches from the three scenarios for training on EMNIST digits\n    data set. Each column represents a single batch, in the order processed by the\n    algorithms. The \\textit{shuffled} case has no bias across the batches, but both\n    \\textit{block-unshuffled} and \\textit{block-random} just have one class in each\n    batch. The main difference between \\textit{block-unshuffled} and\n    \\textit{block-random} is that the consecutive batches are not from the same\n    class in the latter.}\n    \\label{table:illustration}\n\\end{table}\n\n\\section{Results}\\label{sec:results}\n\n\\subsection{Benchmark results on EMNIST data sets}\\label{sec:benchmarks}\n\nTo benchmark the different learning algorithms, we use the EMNIST data\nsets~\\cite{Cohen2017}. This is a commonly used data set of\n$28 \\times 28$ pixel images of handwritten character letters and\ndigits. We trained models using the different training algorithms\npresented in Section\\,\\ref{sec:methods} for the seven different data\nsets: ``fashion'', ``digits'', ``letters'', ``byclass'', ``balanced'',\nand ``mnist''.\n\n\n\\subsubsection{Neural network architecture}\nThe neural network architecture is two\nfully connected hidden layers each comprising 512 nodes, a rectified\nlinear unit activation function, and a dropout layer with a dropout\nrate of $0.2$. The final layer includes a softmax activation function\nfor the category probabilities:\n\\begin{align}\n  y = S(x) = \\frac{\\exp{(x)}}{\\sum^n_{i=1} \\exp{(x_i)}},\n\\end{align}\nwhere $x$ is the layer input vector of size $n$, and $y$ is the layer\noutput vector of size $n$, on the output layer to ensure that\n$\\sum^n_{i=1} y_i = 1$ and $y_i \\in [0,1]~\\forall i = 1, \\dots,\nn$. The loss function is the categorical cross-entropy loss, and the\n\\gls{sgd} algorithm for this work is the Adam\noptimizer~\\cite{Kingma2014}. The learning procedure occurred over 50\nepochs, where one epoch consists of training the model on the entire\ntraining data set. The deep learning framework was implemented through\nKeras~\\cite{Chollet2015} with the TensorFlow\nbackend~\\cite{tensorflow2015-whitepaper}.\n\n\\subsubsection{Assessments of learning algorithm performance}\n\nFigure\\,\\ref{fig:sum0} shows the model accuracy using the three\ndifferent learning strategies. The results indicate that the block-random\nalgorithm performs as well as the shuffled algorithm with little\ndifference in the model accuracy. The block-unshuffled case performs poorly\nfor all benchmark cases. Additionally, we investigated the effect of\nthe ratio $\\nicefrac{n_b}{n_c}$, where $n_b$ is the batch size, and\n$n_c$ is the number of samples in each class, i.e., a block of\nhomogeneous data, Figure\\,\\ref{fig:sum1}. The model accuracy for the\nblock-random algorithm decreases as a function of the ratio\n$\\nicefrac{n_b}{n_c}$. This is because as this ratio increases, the\n\\gls{sgd} algorithm operates on batches with little\nclass variation.\n\n\\begin{figure}[!tbp]%\n  \\centering%\n  \\begin{subfigure}[t]{0.48\\textwidth}%\n    \\includegraphics[page=2, width=\\textwidth]{./figs/benchmark_summary.pdf}%\n    \\caption{Model accuracy ($n_b=64$) for the three learning algorithms. Red: shuffled; green: sorted by class; blue: block-random.}\\label{fig:sum0}%\n  \\end{subfigure}\\hfill%\n  \\begin{subfigure}[t]{0.48\\textwidth}%\n    \\includegraphics[page=1, width=\\textwidth]{./figs/benchmark_summary.pdf}%\n    \\caption{Model accuracy of block-random algorithm as a function of $\\nicefrac{n_b}{n_c}$. Red squares: ``fashion''; green diamonds: ``digits''; blue circles: ``letters''; orange pentagon: ``byclass''; purple hexagon: ``balanced''; burgundy crosses: ``mnist''.}\\label{fig:sum1}%\n  \\end{subfigure}%\n  \\caption{Model accuracy, $\\alpha = \\nicefrac{\\text{number of correctly classified images}}{\\text{total number of images}}$, on validation data set for different benchmark cases.}\\label{fig:predictions}%\n\\end{figure}%\n\n\\subsection{Channel flow}\\label{sec:channel}\n\nTo evaluate the performance of the algorithm in an exascale-like setting, we\ndeveloped a \\gls{dnn} model for the ``closure problem'' for\n\\gls{les} in computational fluid dynamics. \\Gls{dns} of turbulent\nflows, in which all the physical length scales are resolved\nexplicitly, require large computational resources and are often\nunfeasible for engineering and design applications. \\Gls{les}\nalleviate the computational requirements by resolving the large-scale\nmotions and modeling the \\gls{sgs}, i.e., the length scales that\nare not resolved by the discretization grid. In computational fluid\ndynamics, \\gls{les} solve the filtered Navier-Stokes equations,\npresented here in their incompressible form:\n\\begin{align}\n  \\label{eq:fns}\n  \\pfrac{\\ol{u}_i}{t} + \\pfrac{}{x_j} \\left( \\ol{u}_i \\ol{u}_i \\right) &= \\pfrac{}{x_j} \\left( \\nu \\pfrac{\\ol{u}_i}{x_j} \\right) - \\frac{1}{\\rho} \\pfrac{\\ol{p}}{x_i} - \\pfrac{\\tau_{ij}}{x_j}\\\\\n  \\pfrac{\\ol{u}_i}{x_i} &= 0\n\\end{align}\nwhere $i$ and $j = 1,2,3$; $x_i$ is the coordinate; $u_i$ is the\nvelocity in the $x_i$ direction; $p$ is the pressure; $\\nu$ is the\nkinematic viscosity; $\\ol{\\cdot}$ is the filtering operation, defined\nfor an variable $\\phi$ as\n$\\ol{\\phi} = \\int_{\\mathcal{D}} \\phi(x) G(x,x') \\ud{} x'$, where\n$G(x,x')$ is a filter function and $\\mathcal{D}$ is the domain; and\n$\\tau_{ij}$ is the \\gls{sgs} stress defined as\n$\\tau_{ij} = \\ol{u_i u_j} - \\ol{u}_i\\ol{u}_j$. The \\gls{les} system of\nequations is unclosed because of the \\gls{sgs} stress term and\nrequires a model for the \\gls{sgs}. Extensive work has been done to\ndetermine appropriate models for the \\gls{sgs}\nstress~\\cite{Rogallo1984,Lesieur1996,Piomelli1999,Meneveau2000}. For\nexample, an early approach~\\cite{Smagorinsky1963} uses an eddy\nviscosity closure that relates resolved velocity gradients to the\n\\gls{sgs} stress according to:\n\\begin{align}\n  \\label{eq:smag}\n  \\tau_{ij} = -2 (C_s \\ol{\\Delta})^2 |\\ol{S}| \\ol{S}_{ij}\n\\end{align}\nwhere\n$\\ol{S}_{ij} = \\nicefrac{1}{2} \\left( \\pfrac{\\ol{u}_i}{x_j} +\n  \\pfrac{\\ol{u}_j}{x_i} \\right)$,\n$|\\ol{S}| = \\sqrt{2 \\ol{S}_{ij} \\ol{S}_{ij}}$, $\\ol{\\Delta}$ is the\nfilter length scale, and $C_s$ is a constant determined through the\n\\gls{dns} of turbulent flows. Though \\gls{sgs} models have received\nmuch attention, because they are often tuned to simple configurations,\nthe accuracy of these models continues to be problematic in a wide\nrange of flows. In this section, we will use deep learning to\nconstruct a \\gls{sgs} stress model for $\\tau_{12}$.\n\nWe emphasize that the objective of this work is not to derive the most\naccurate \\gls{sgs} model for turbulence, which has been a focus of\nrecent investigations using deep learning~\\cite{Ling2016, Maulik2017};\nrather, it is to illustrate how to use \\gls{dns} data from exascale-like\nsimulations to develop an accurate model in the context of\ndistributed, heterogeneous data. As such, we will use the \\gls{dns} of\nan incompressible channel flow at a friction Reynolds number ($Re_\\tau$) of 5186\nby \\citet{lee2015direct}. The simulations were performed using the code\nPoongBack~\\cite{lee2013petascale,lee2014experiences}, with 242 billion degrees\nof freedom (10240 in $x$, 1536 in $y$, and 7680 in $z$), and was run on 52488 cores,\nusing approximately 400 million core hours of computation. The incompressible\nchannel flow exhibits high inhomogeneity and anisotropy, as shown in\nFigure\\,\\ref{fig:dns_channel}, from the presence of the walls.  This makes it a\nchallenging test case for the block-random algorithm because there will be a high\nbias between data from each spatial block.\n\n\\begin{figure}[!tbp]%\n  \\centering%\n  \\reflectbox{\\includegraphics[width=0.5\\textwidth]{./figs/5200_u_XY_u_YZ_omega_z_XZ.pdf}}%\n  \\caption{Streamwise velocity and wall-shear stress (inset) in the turbulent channel flow \\gls{dns}. Figure generated by Dr.~Myoungkyu Lee, using data from~\\cite{lee2015direct}}%\n  \\label{fig:dns_channel}%\n\\end{figure}%\n\n\\subsubsection{Data generation process}\n\nTo get data for constructing a \\gls{sgs} model, first the nonlinear $u_i u_j$\nterms are computed from the \\gls{dns} velocity fields. A circular Fourier\ncutoff filter is then applied to the resulting fields, and $\\tau_{ij}$ is\ncomputed from the filtered fields.  The cutoff wavelength is chosen as\n$\\lambda^+\\approx1500$ in the wall-parallel directions using insights from\n\\citet{lee_moser_2019}. This results in a grid of dimensions $(200,1536,128)$ in $(x,y,z)$\nwith more than 39 million data points. The input model variables are the three\nfiltered velocities and nine filtered velocity gradients. The model is\ntherefore learning a pointwise functional form:\n\\begin{align}\n  \\label{eq:nn_function_model}\n  \\tau_{ij}|_k = f\\left( \\ol{u}_i|_k, \\left.\\pfrac{\\ol{u}_i}{x_j}\\right|_k \\right)\n\\end{align}\nwhere $k$ denotes a point in the domain. ,The resulting data are then\narranged into spatial blocks of size $(16,16,16)$ in $(x,y,z)$, with\neach block representing a computational node. In this setting, there\nwill be a total of 9600 nodes containing data, which mimics a\ndistributed large-scale computation.\n\n\\subsubsection{Neural network architecture}\n\nThe neural network architecture is a feed-forward, fully connected\n\\gls{dnn}. The hidden layers each comprise fully connected\nnodes. The first hidden layer contains a leaky rectified linear unit\nactivation function:\n\\begin{align}\n  \\label{eq:relu}\n  y = R(x) =\n  \\begin{cases}\n    x, & \\text{ if } x \\geq 0, \\\\\n    \\gamma x, & \\text{ otherwise, }\n  \\end{cases}\n\\end{align}\nwhere $x$ is the layer input vector, $y$ is the layer output vector,\nand $\\gamma=10^{-2}$ is a small slope. The other hidden layers contain\na hyperbolic tangent activation function. The final network layer does\nnot contain an activation function. The loss used to train the network\nis a mean squared error loss function. The specific \\gls{sgd} algorithm for this work is the Adam\noptimizer~\\cite{Kingma2014} because it presents many more advantages\nthan traditional \\gls{sgd} by maintaining a\nper-parameter learning rate, which is adapted during training based on\nexponential moving averages of the first and second moments of the\ngradients. The deep learning framework was implemented through\nKeras~\\cite{Chollet2015} with the TensorFlow\nbackend~\\cite{tensorflow2015-whitepaper}. To find a reasonably\naccurate model for this study, a sweep of the model's hyperparameters\nwas performed, exploring the following combinations: the initial\nlearning rate was varied from $10^{-2}$ to $10^{-5}$; the number of\nlayers, $L$, was varied from 2 to 16; and the number of nodes in\neach layer was varied from 8 to 512. The sweeps were performed on the\n1 million samples from the fully shuffled training data set. A\nneural network comprising an initial learning rate of $10^{-4}$,\nfour hidden layers, and 128 nodes in each layer (for a total of 68000\ntrainable parameters) led to a model that was accurate without\nnecessitating more than eight hours of training on an Intel Skylake\nworkstation. This set of model hyperparameters is used in all\nsubsequent results.\n\n\\subsubsection{Assessments of learning algorithm performance}\n\nIn this section, we present the results of the three different\nlearning algorithms presented in this work: (i) fully shuffling all\nthe data; (ii) using the data as they are in the high performance\ncomputing simulation (block-unshuffled), (iii) accessing the data in\nblock-random fashion, as discussed in Section\\,\\ref{sec:methods}. Model\nquantities are denoted by superscript $\\cdot^m$, and quantities\ncomputed with respect to the training and validation data sets are\nsubscripted with $t$ and $v$, respectively. The mean squared error is defined as\n$\\epsilon = \\frac{1}{|\\mathcal{D}|} \\sum_{i\\in \\mathcal{D}} (\\tau_{12}\n- \\tau_{12}^m)^2$, where $\\mathcal{D}$ denotes the data set, and\n$|\\cdot|$ is the cardinality of the set. The physics model used for\ncomparisons is the \\gls{wale} model~\\cite{Ducros1998}, a model\nspecifically designed for \\gls{les} of wall-bounded flows.\n\nThe training and validation mean squared error, $\\epsilon_t$ and\n$\\epsilon_v$, respectively, are shown in\nFigure\\,\\ref{fig:accuracies_batchsize} for the three different\nlearning algorithms as a function of the batch size, $n_b$. The\ntraining error for the shuffled case reaches a minimum at $n_b=256$\nand increases for higher $n_b$. The validation error, however, remains\nconstant and smaller than the other two algorithms. The training error\nfor the block-unshuffled algorithm is less than that for the block-random\nalgorithm, though the validation error is three times larger than the\nother algorithms. This indicates that the model is capturing the\nbatches of data toward the end of the training iteration but fails to\nadequately represent the full range of data. The training error\ndecreases as a function of batch size because it is able to get a more\nrepresentative data batch. This results, however, in an increasing\nvalidation error because it overfits the data available at the end of the\ntraining iteration. The block-random algorithms exhibits a validation\nerror that is approximately $10\\%$ higher than the shuffled algorithm,\nand it remains small as the batch size increases. For the remaining\nresults presented in this section, the batch size is fixed at 256.\n\n\\begin{figure}[!tbp]%\n  \\centering%\n  \\begin{subfigure}[t]{0.48\\textwidth}%\n    \\includegraphics[page=1, width=\\textwidth]{./figs/accuracies_batchsize.pdf}%\n    \\caption{Training error, $\\epsilon_t$.}%\n  \\end{subfigure}\\hfill%\n  \\begin{subfigure}[t]{0.48\\textwidth}%\n    \\includegraphics[page=2, width=\\textwidth]{./figs/accuracies_batchsize.pdf}%\n    \\caption{Validation error, $\\epsilon_v$.}%\n  \\end{subfigure}%\n  \\caption{Mean squared error for the three different learning algorithms as a function of the batch size. Red squares: shuffled; green diamonds: block-unshuffled; blue circles: block-random.}\\label{fig:accuracies_batchsize}%\n\\end{figure}%\n\nThe normalized \\gls{pdf} of the error and the conditional means of the\npredictions are shown in Figure\\,\\ref{fig:predictions}. The shuffled\nalgorithm exhibits a sharp \\gls{pdf} of the error and a conditional\nmeans of the predictions identical to the filtered \\gls{dns}\nthroughout the channel domain. The block-random algorithm has a\nsimilar error \\gls{pdf} but underpredicts the peak $\\tau_{12}$ by\napproximately $8\\%$. The block-unshuffled algorithm fails to capture the\nconditional means throughout the channel. The \\gls{wale} physics model\noverpredicts the peak $\\tau_{12}$ by a factor of two and predicts that\nthe peak occurs closer to the channel centerline. The \\gls{wale} error\n\\gls{pdf} has a higher variance than the shuffled and block-random\nalgorithms.\n\n\\begin{figure}[!tbp]%\n  \\centering%\n  \\begin{subfigure}[t]{0.48\\textwidth}%\n    \\includegraphics[page=4, width=\\textwidth]{./figs/predictions.pdf}%\n    \\caption{Probability density function of the error normalized by the standard deviation of $\\tau_{12}$.}%\n  \\end{subfigure}\\hfill%\n  \\begin{subfigure}[t]{0.48\\textwidth}%\n    \\includegraphics[page=17, width=\\textwidth]{./figs/predictions.pdf}%\n    \\caption{Conditional means as a function of wall distance, $y^+ = Re_\\tau y$.}%\n  \\end{subfigure}%\n  \\caption{Model accuracy on validation data set. Red squares and solid: shuffled; green diamonds and dashed: block-unshuffled; blue circles and dash-dotted: block-random; purple hexagons and solid: \\gls{wale} physics model; black solid: filtered \\gls{dns}}\\label{fig:predictions}%\n\\end{figure}%\n\nAs evidenced by these results, the key factor determining the\nperformance of the model is the order of the blocks used by the\n\\gls{sgd} algorithm to adjust the model\nparameters. To quantify the difference between the learning\nalgorithms, we use the Jensen-Shannon divergence~\\cite{Endres2003,\n  Osterreicher2003}, a measure of the similarity between two\n\\glspl{pdf}. It is a symmetric version of the Kullback-Leibler\ndivergence~\\cite{Kullback1987}, and it is defined as:\n\\begin{align}\n  \\label{eq:jsd}\n  J(Q,R) = \\frac{1}{2} \\left( D(Q , M) + D(R , M)\\right)\n\\end{align}\nwhere\n$D(Q,R) = \\sum_{i=1}^n R(i) \\ln{\\left( \\frac{R(i)}{Q(i)} \\right)}$;\n$M = \\nicefrac{1}{2} \\left( Q+R \\right)$; $Q$ and $R$ are \\glspl{pdf}\nof length $n$; and $0\\leq J(Q,R) \\leq \\ln{(2)}$. Low values indicate\nmore similarity between $Q$ and $R$. The Jensen-Shannon divergence has\nseveral advantages compared to the Kullback-Leibler divergence:\nsymmetry, i.e., $J(Q,R) = J(R,Q)$, bounded, and variable\nsupport. This metric is used to quantify the difference between the\ndifferent \\glspl{pdf}: the \\gls{pdf} of $\\tau_{12}$ in the validation\ndata set, $Y = P(\\tau_{12} \\in \\mathcal{D}_v)$, and the \\gls{pdf} of a\ngiven batch, $Y_b = P(\\tau_{12} \\in \\mathcal{D}_b)$, where\n$\\mathcal{D}_b$ is the set of data in batch $b$. We compare (i) how\nthe data in each batch are representative of the data in the entire\ndomain by computing $J(Y, Y_b)$ for all the batches in an epoch and\n(ii) how the data in each batch vary compared to the previous batch\nby computing $J(Y_{b-1}, Y_b)$.\n\nFigure\\,\\ref{fig:jsds} illustrates the different metrics for the three\ndifferent learning algorithms. For the fully shuffled case, each batch\nexhibits a \\gls{pdf} similar to that of the entire data set. The\ndifference between $Y$ and $Y_b$ for the block-random case is higher\nbut remains constant during the training epoch. For the block-unshuffled\ncase, there is a clear structure to $J(Y,Y_b)$ because of the\nheterogeneity of the data near the channel walls (beginning and ending\nof the training epoch). For all three algorithms, the difference\nbetween each subsequent batch is negligible. These results indicate\nthat ensuring that $J(Y,Y_b)$ remains less than 0.2 and constant\nthroughout the training epoch is a criteria for achieving high model\naccuracy.\n\n\\begin{figure}[!tbp]%\n  \\centering%\n  \\begin{subfigure}[t]{0.48\\textwidth}%\n    \\includegraphics[page=2, width=\\textwidth]{./figs/jsds.pdf}%\n    \\caption{Comparison between each batch and the entire data set.}%\n  \\end{subfigure}\\hfill%\n  \\begin{subfigure}[t]{0.48\\textwidth}%\n    \\includegraphics[page=5, width=\\textwidth]{./figs/jsds.pdf}%\n    \\caption{Comparison between subsequent batches.}%\n  \\end{subfigure}%\n  \\caption{Characterizing the differences between batches. Solid red: shuffled; dashed green: block-unshuffled; dash-dotted blue: block-random.}\\label{fig:jsds}%\n\\end{figure}%\n\n\\section{Conclusions}\\label{sec:ccl}\n\nEffectively training \\gls{dnn} models often assumes that the \\gls{sgd}\nalgorithm processes data in batches of data that have been randomized\nprior to model training. This is expected to be prohibitively\nexpensive for in situ model training from the perspective of\ncommunication between computing nodes, as illustrated in\nFigure\\,\\ref{fig:access_patterns}. We showed that the \\gls{sgd}\nalgorithm can still train an effective model if the batches are\nprocessed in random order even if the batches are each comprised of\nsimilar data. In this work, we demonstrated a block-random learning\nalgorithm for training \\glspl{dnn} in the context of distributed\nheterogeneous data for data parallelism learning, a situation that\nwill be increasingly common as the exascale era approaches and models\nare trained in situ. The block-random learning algorithm was tested on\nseveral different cases. For the benchmark EMNIST data sets, the\nblock-random algorithm achieves accuracy similar to the traditional\nfully shuffled learning algorithm. The performance decreases slightly\nas the ratio of the batch size to the number of classes increases. To\ndemonstrate the efficacy of the block-random algorithm for\nexascale-type simulations, we used a \\gls{dns} simulation of turbulent\nchannel flow to construct a \\gls{les} \\gls{sgs} model. The model\nconstructed using the block-random algorithm performed significantly\nbetter than the block-unshuffled learning model and is within $8\\%$ of\nthe fully shuffled model. Using the Jensen-Shannon divergence metric,\nwe analyzed the characteristics of the batches used by the \\gls{sgd}\nto inform a criteria for successfully constructing a \\gls{dnn} model\nfor distributed heterogeneous data.\n\nThis work --- including neural network models, analysis scripts,\nJupyter notebooks, and figures --- can be publicly accessed at the\nproject's GitHub\npage.\\footnote{\\url{https://github.com/NREL/block-random}} Traditional\nmachine learning algorithms were implemented through\nscikit-learn~\\cite{Pedregosa2011} and the deep learning algorithms\nthrough Keras~\\cite{Chollet2015} with the TensorFlow\nbackend~\\cite{tensorflow2015-whitepaper}.\n\n\\section*{Acknowledgments}\nThis work was authored in part by the National Renewable Energy Laboratory, operated by Alliance for Sustainable Energy, LLC, for the U.S. Department of Energy (DOE) under Contract No. DE-AC36-08GO28308. Funding provided by U.S. Department of Energy Office of Science and National Nuclear Security Administration. The views expressed in the article do not necessarily represent the views of the DOE or the U.S. Government. The U.S. Government retains and the publisher, by accepting the article for publication, acknowledges that the U.S. Government retains a nonexclusive, paid-up, irrevocable, worldwide license to publish or reproduce the published form of this work, or allow others to do so, for U.S. Government purposes.\n\nThis research was supported by the Exascale Computing Project (ECP), Project Number: 17-SC-20-SC, a collaborative effort of two DOE organizations -- the Office of Science and the National Nuclear Security Administration -- responsible for the planning and preparation of a capable exascale ecosystem -- including software, applications, hardware, advanced system engineering, and early testbed platforms -- to support the nation's exascale computing imperative.\n\n\\section*{References}\n\n\\bibliography{library}\n\n\\end{document}\n", "meta": {"hexsha": "f998ed9fbf90f8a08bad6aba76fb1294425f03ab", "size": 41075, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/paper.tex", "max_stars_repo_name": "NREL/block-random", "max_stars_repo_head_hexsha": "0d8938ea805f1fade727e5e5e20ffa71baec200f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-03-04T20:24:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-09T16:51:15.000Z", "max_issues_repo_path": "paper/paper.tex", "max_issues_repo_name": "NREL/batch-random", "max_issues_repo_head_hexsha": "0d8938ea805f1fade727e5e5e20ffa71baec200f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/paper.tex", "max_forks_repo_name": "NREL/batch-random", "max_forks_repo_head_hexsha": "0d8938ea805f1fade727e5e5e20ffa71baec200f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-03-05T17:44:17.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-20T01:51:34.000Z", "avg_line_length": 52.4584929757, "max_line_length": 726, "alphanum_fraction": 0.74678028, "num_tokens": 11056, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.3312966214110019}}
{"text": "%!TEX program = xelatex\n\\documentclass[a4paper,11pt]{article}\n\\usepackage{pos}\n% \\usepackage{ulem}\n\\usepackage{natbib}\n\\usepackage{cancel}\n\\usepackage{pgfplots}\n\\usepackage{wrapfig}\n\\usepackage{subcaption}\n\\usepackage{mathtools}\n\\pgfplotsset{compat=1.18}\n\n\\title{HMC with Normalizing Flows}\n%% \\ShortTitle{Short Title for header}\n\n% TODO: Add citations !!\n\n\\author*[a]{Sam Foreman}\n\\author[b, c]{Taku Izubuchi}\n\\author[d]{Luchang Jin}\n\\author[a]{Xiao-Yong Jin}\n\\author[a]{James C. Osborn}\n\\author[b]{Akio Tomiya}\n\n\\affiliation[a]{Argonne National Laboratory,\\\\\n  Lemont, IL 60439}\n\n\\affiliation[b]{RIKEN,\\\\\n 2-1 Hirosawa, Wako, Saitama, 351-0198, Japan}\n\n\\affiliation[c]{Brookhaven National Laboratory,\\\\\n Upton, NY 11973}\n\n\\affiliation[d]{Dept. of Physics, University of Connecticut,\\\\\n Storrs, CT 06269}\n\n\\emailAdd{foremans@anl.gov}\n\\emailAdd{izubuchi@bnl.gov}\n\\emailAdd{luchang.jin@uconn.edu}\n\\emailAdd{xjin@anl.gov}\n\\emailAdd{osborn@alcf.anl.gov}\n\n\\abstract{%\n    We propose using Normalizing Flows as a trainable kernel within the\n    molecular dynamics update of Hamiltonian Monte Carlo (HMC).\n    %\n    By learning (invertible) transformations that simplify our dynamics, we can\n    outperform traditional methods at generating independent configurations.\n    %\n    We show that, using a carefully constructed network architecture, our\n    approach can be easily scaled to large lattice volumes with minimal\n    retraining effort.\n    %\n    The source code for our implementation is publicly available online at\n    \\href{https://www.github.com/nftqcd/fthmc}{github.com/nftqcd/fthmc}.\n}\n\n\\FullConference{%\n The 38th International Symposium on Lattice Field Theory, LATTICE2021\n  26th-30th July, 2021\n  Zoom/Gather@Massachusetts Institute of Technology\n}\n\n\n%% \\tableofcontents\n\n\\begin{document}\n\\maketitle\n\\section{\\label{sec:intro}Introduction}\n\\subsection{%\n    \\label{subsec:gauge_theory}%\n    2D \\texorpdfstring{\\(U(1)\\)}{U(1)} Gauge Theory\n}\n%\n\\begin{wrapfigure}{r}{.33\\columnwidth}\n  \\includegraphics[width=0.33\\columnwidth]{assets/plaq.pdf}\n  \\caption{\\label{fig:plaq} Plaquette \\(x_{P}\\).}\n\\end{wrapfigure}\n%\nLet \\(U_{\\mu}(n) = e^{i x_{\\mu}(n)}\\in U(1)\\), with \\(x_{\\mu}(n)\\in [-\\pi,\n\\pi]\\) denote the \\emph{link variables}, where \\(x_{\\mu}(n)\\) is a link at the\nsite \\(n\\) oriented in the direction \\(\\hat{\\mu}\\).\n%\nOur goal is to generate an ensemble of configurations, distributed according to\n% %\n% For the 2D \\(U(1)\\) gauge theory on a square lattice with periodic boundary\n% conditions, we can write the target distribution \n% We can write our target distribution \\(p(x)\\) in terms of the Wilson action\n% \\(S(x)\\) as\n%\n\\begin{equation}\n    p(x)\\propto e^{-S(x)},\\quad S(x) \\equiv \\sum_{P} 1 - \\cos x_{P},\n\\end{equation}\n%\nwhere $S(x)$ is the Wilson action for the 2D \\(U(1)\\) gauge\ntheory\\footnote{Explicitly, on a square lattice with periodic boundary\nconditions.}, and \\(x_{P} = x_{\\mu}(n) + x_{\\nu}(n+\\hat{\\mu}) -\nx_{\\mu}(n+\\hat{\\nu}) - x_{\\nu}(n)\\) is the sum of the links around the\nelementary plaquette as shown in Figure~\\ref{fig:plaq}.\n%\nFor a given lattice configuration, we can define the topological charge as \\(Q\n= \\frac{1}{2\\pi}\\sum_{P}\\mathrm{arg}(x_{P}) \\in\\mathbb{Z}\\), where\n\\(\\mathrm{arg}(x_{P})\\in [-\\pi, \\pi]\\).\n% \\begin{equation}\n%     Q = \\frac{1}{2\\pi}\\sum_{P}\\mathrm{arg}(x_{P}),\\text{where}\\quad\n%     \\mathrm{arg}(x_{P})\\in[-\\pi,\\pi].\n% \\end{equation}\n%\n\nTraditional sampling techniques such as HMC are known to suffer from\n\\emph{critical slowing down}~\\cite{Schaefer:2010hu}, a phenomenon characterized\nby the freezing of the topological charge \\(Q\\) as we approach physical lattice\nspacings.\n%\nThis effect can be seen clearly in Figure~\\ref{subfig:q8},~\\ref{subfig:q16},\nwhere \\(Q\\) typically remains stuck for the duration of the HMC trajectories.\n%\nIn this work we describe a method for training a normalizing flow model that is\ncapable of sampling from different topological charge sectors, thereby reducing\nthe computational effort required to generate independent configurations.\n%\n% The most commonly used approach, Hamiltonian Monte Carlo (HMC), is\n% This can be seen in the samplers inability to mix between different\n% \\textcolor{blue}{We are interested in how this quantity evolves over a finite length Markov\n% chain, and in particular, we can define the tunneling rate, \\(\\delta Q\\) as}\n\n% \\marginpar{\\color{red}{Remove references to \\(\\delta Q\\)?}}\n% %\n% \\begin{equation}\n%     \\delta Q = \\sqrt{\\left(Q_{i+1} - Q_{i}\\right)^{2}}\n% \\end{equation}\n% %\n% \\textcolor{blue}{where the difference is between subsequent states in the chain.}\n% %\n% \\textcolor{blue}{This quantity is analogous to the lag-one autocorrelation in the\n% topological charge.}\n\\subsection{\\label{subsec:ft}Field Transformations}\n%\nFor a random variable \\(z\\) with a given distribution \\(z \\sim r(z)\\), and an\ninvertible function \\(x = f(z)\\) with \\(z = f^{-1}(x)\\), we can use the change\nof variables formula to write\n%\n\\begin{equation}\n    p(x) = r(z)\\left|\\det\\frac{\\partial z}{\\partial x}\\right| =\n    r(f^{-1}(x))\\left|\\det\\frac{\\partial f^{-1}}{\\partial x}\\right|\n\\end{equation}\n%\nwhere \\(r(z)\\) is the (simple) prior density, and our goal is to generate\nindependent samples from the (difficult) target distribution \\(p(x)\\).\n%\nThis can be done using \\emph{normalizing flows}~\\cite{rezende2015variational}\nto construct a model density \\(q(x)\\) that approximates the target\ndistribution, i.e. \\(q(\\cdot)\\simeq p(\\cdot)\\) for a suitably-chosen flow\n\\(f\\).\n\n\\begin{figure}[htpb]\n    \\centering\n    \\includegraphics[width=\\textwidth]{assets/flow_model.pdf}\n    % \\includegraphics[width=\\textwidth]{assets/flow_model.pdf}\n    \\caption{\\label{fig:flow_model} Using a flow to generate data \\(x'\\). Image\n    adapted from~\\cite{weng2018flow}}\n\\end{figure}\n%\nWe can construct a normalizing flow by composing multiple invertible functions\n\\(f_{i}\\) so that \\(x\\equiv \\left[f_{k}\\circ f_{k-1}\\circ \\cdots \\circ\nf_{2}\\circ f_{1}\\right](z)\\).\n%\nIn practice, the functions \\(f_{i}\\) are usually implemented as \\emph{coupling\nlayers}, which update an ``active'' subset of the variables, conditioned on the\ncomplimentary ``frozen'' variables~\\cite{Kanwar:2020xzo,Albergo:2021vyo}.\n%\n\\subsection{\\label{subsec:coupling_layers}Affine Coupling Layers}\nA particularly useful template function for constructing our normalizing flows\nis the affine coupling layer~\\cite{DinhSB16,rezende2015variational},\n%\n\\begin{align*}\n    f(x_{1}, x_{2}) &= \\left(e^{s(x_2)}x_{1} + t(x_{2}),\\, x_{2}\\right),\n        \\quad\\text{with}\\quad \\log J(x) = \\sum_{k}\\left[s(x_{2})\\right]_{k}\\\\\n    f^{-1}(x'_{1}, x'_{2}) &= \\left((x'_{1}-t(x'_{2}))e^{-s(x'_{2})},\\, x'_{2}\\right),\n        \\quad\\text{with}\\quad \\log J(x') = \\sum_{k}-\\left[s(x'_{2})\\right]_{k}\n\\end{align*}\n%\nwhere \\(s(x_{2})\\) and \\(t(x_{2})\\) are of the same dimensionality as \\(x_{1}\\)\nand the functions act element-wise on the inputs.\n\nIn order to effectively draw samples from the correct target distribution\n\\(p(\\cdot)\\), our goal is to minimize the error introduced by approximating\n\\(q(\\cdot)\\simeq p(\\cdot)\\).\n%\nTo do so, we use the (reverse) Kullback-Leibler (KL) divergence from\nEq.~\\ref{eq:kl_div}, which is minimized when \\(p=q\\).\n%\n\\begin{align}\n    \\label{eq:kl_div}\n    D_{\\mathrm{KL}}(q\\|p) \n    &\\equiv\\int dy q(y)\\left[\\log q(y) - \\log p(y)\\right]\\\\\n    &\\simeq \\frac{1}{N}\\sum_{i=1}^{N} \\left[\\log q(y_{i})-\\log p(y_{i})\\right],\n        \\,\\,\\text{where}\\,\\, y_{i}\\sim q\n\\end{align}\n%\n\\section{\\label{sec:trivializing_map}Trivializing Map}\n%\nUltimately, our goal is to evaluate expectation values of the form\n%\n\\begin{equation}\n    \\label{eq:exp_val}\n    \\langle \\mathcal{O} \\rangle = \\tfrac{1}{\\mathcal{Z}} \\int dx\\, \\mathcal{O} (x) e^{-S(x)}.\n\\end{equation}\n%\nUsing a normalizing flow, we can perform a change of variables \\(x = f(z)\\), so\nEq.~\\ref{eq:exp_val} becomes\n%\n\\begin{align}\n    \\langle \\mathcal{O} \\rangle \n    &= \\frac{1}{\\mathcal{Z}} \\int dz \\left|\\det \\left[ J(z) \\right]\\right|\n        \\mathcal{O} (f(z)) e^{-S(f(z))},\n        \\text{ where } J (z) = \\frac{\\partial f(z)}{\\partial z} \\\\\n    &= \\frac{1}{\\mathcal{Z}}\\int dz \\mathcal{O} (f(z)) e^{-S(f(z))\n        + \\log |\\det[J(z)]|}.\n\\end{align}\n%\nWe require the Jacobian matrix, \\(J(z)\\), to be:\n%\n\\begin{enumerate}\n    \\item Injective (1-to-1) between domains of integration\n    \\item Continuously differentiable (\\emph{or}, differentiable with\n        continuous inverse)\n\\end{enumerate}\n%\nThe function \\(f\\) is a \\emph{trivializing map}~\\cite{luscher2009} when\n\\(S(f(z)) - \\log\\left|\\det J(z)\\right| = \\text{const.}\\), and our expectation\nvalue simplifies to\n%\n\\begin{equation}\n    \\langle\\mathcal{O}\\rangle = \n    \\frac{1}{\\mathcal{Z}^{\\ast}}\\int dz\\, \\mathcal{O}(f(z)), \\text{ where }\n    \\frac{1}{\\mathcal{Z}^{\\ast}} \n    = \\frac{1}{\\mathcal{Z}}\\exp(-\\text{const.}).\n\\end{equation}\n%\n\\section{\\label{sec:hmc_nf}Field Transformation HMC: \\texttt{fthmc}}\n%\nWe can implement the trivializing map defined in\nSec.~\\ref{sec:trivializing_map} using a normalizing flow model.\n%\nFor conjugate momenta \\(\\pi\\), we can write the Hamiltonian as\n%\n\\begin{equation}\n    H(z, \\pi) = \\frac{1}{2}\\pi^{2} + S(f(z)) - \\log\\left|\\det J(f(z))\\right|,\n\\end{equation}\n%\nand the associated equations of motion as\n%\n\\begin{align}\n    \\dot{z} &= \\frac{\\partial H}{\\partial \\pi} = \\pi \\\\\n    \\dot{\\pi} &= -J(z) S'(f(z)) + \\mathrm{tr}\\left[ J^{-1}\\frac{d}{dz} J \\right].\n\\end{align}\n%\nIf we introduce a change of variables, \\(\\pi = J(z)\\rho = J(f^{-1}(x))\\rho\\)\nand \\(z = f^{-1}(x)\\), the determinant of the Jacobian matrix reduces to \\(1\\),\nand we obtain the modified Hamiltonian\n%\n\\begin{equation}\n    \\tilde{H}(x, \\rho) = \\frac{1}{2}\\rho^{\\dagger}\\rho + S(x) - \\log|\\det J|.\n\\end{equation}\n%\nAs shown in Figure~\\ref{fig:fthmc}, we can use a \\emph{field transformation},\n\\(f^{-1}: z \\rightarrow x\\) to perform HMC updates on the transformed variables\n\\(x\\), and \\(f: x \\rightarrow z\\) to recover the physical target distribution.\n%\n\\begin{figure}[htpb]\n    \\centering\n    \\includegraphics[width=\\textwidth]{assets/fthmc.pdf}\n    \\caption{\\label{fig:fthmc}Normalizing flow with inner HMC block.}\n\\end{figure}\n%\n\\subsection{\\label{subsec:hmc}Hamiltonian Monte Carlo (HMC)}\nWe describe the general procedure of the Hamiltonian Monte Carlo\nalgorithm~\\cite{Betancourt:2017}.\n\\begin{enumerate}\n    \\item Introduce \\(v \\sim \\mathcal{N} (0,\\mathbb{I}_{n}) \\in \\mathbb{R}^{n}\\)\n        and write the joint distribution as\n        \\begin{equation}\n            p(x, v) = p(x) p(v) \\propto e^{-S(x)} e^{-\\frac{1}{2} v^{T} v}\n        \\end{equation}\n    \\item Evolve the joint system \\((\\dot x, \\dot v)\\) according to\n        Hamilton's equations along \\(H=\\text{const.}\\) using the leapfrog\n        integrator:\n        \\begin{equation}\n            \\textbf{ (a.)  } \\tilde{v} \\leftarrow v - \\frac{\\varepsilon}{2}\\partial_{x}S(x)\\quad\n            \\textbf{ (b.)  } x' \\leftarrow x + \\varepsilon \\tilde{v}\\quad\n            \\textbf{ (c.)  } v' \\leftarrow \\tilde{v} - \\frac{\\varepsilon}{2}\\partial_{x} S(x')\n        \\end{equation}\n    \\item Accept or reject the proposal configuration using the\n        Metropolis-Hastings test,\n        \\begin{equation}\n            x_{i+1} = \\begin{cases}\n                x', \\text{ with probability } \n                    A(x'|x) \\equiv \\min\\left\\{1, \\frac{p(x')}{p(x)}%\n                    \\left|\\frac{\\partial x'}{\\partial x^{T}}\\right|\\right\\}\\\\\n                x, \\text{ with probability } 1 - A(x'|x)\n            \\end{cases}\n        \\end{equation}\n\\end{enumerate}\n%\n\\subsection{\\label{subsec:volume_scaling}Volume Scaling}\n%\nWe use gauge equivariant coupling layers that act on plaquettes as the\nbase layer for our network architecture.\n%\nAs in~\\cite{Albergo:2021vyo}, these layers are composed of inner coupling\nlayers which are implemented as stacks of convolutional layers.\n%\nOne advantage of using convolutional layers is that we can re-use the trained\nweights when scaling up to larger lattice volumes.\n%\nExplicitly, when scaling up the lattice volume we can initialize the weights\nof our new network with the previously trained values.\n%\nThis approach has the advantage of requiring minimal retraining effort while\nbeing able to efficiently generate models on large lattice volumes.\n%\n\\section{\\label{sec:results}Results}\n%\nFor traditional HMC, we see in Figure~\\ref{subfig:q8},\\ref{subfig:q16}\nthat \\(Q \\simeq 0\\) for across all trajectories for both \\(8\\times 8\\) and\n\\(16\\times 16\\) lattice volumes.\n%\nConversely, we see in Figure~\\ref{subfig:q8},\\ref{subfig:q16} that the trained\nmodels are able to sample from multiple values of \\(Q\\) for both the \\(8\\times\n8\\) and \\(16\\times16\\) volumes.\n%\n\nThe results in Figure~\\ref{subfig:loss} took \\(\\sim 4\\) hours to train using a\nsingle A100 Nvidia GPU.\n%\nThe performance of the trained sampler is limited by the acceptance rate of the\nproposed configurations, which in turn, is ultimately limited by the\ncomputational resources used to train the model.\n%\nBecause of this, we would expect a continued improvement in performance with\nadditional training.\n%\nFor this relatively simple proof of concept, we were able to\ndemonstrate the usefuleness of our approach without requiring prohibitively\nlarge upfront training costs.\n%\n\\begin{figure}[htpb]\n    \\centering\n    \\begin{subfigure}[b]{\\linewidth}\n        \\includegraphics[width=\\linewidth]{assets/histories_8x8_beta6.pdf}\n        \\caption{\\label{subfig:q8}The average plaquette \\(x_{P}\\) and\n            topological charge \\(Q\\) histories for the trained model and\n        HMC at \\(\\beta = 6\\) with \\(V = 8 \\times 8\\).}\n    \\end{subfigure}\n    \\hfill\n    \\begin{subfigure}[b]{\\linewidth}\n        \\includegraphics[width=\\linewidth]{assets/histories_16x16_beta6_xfr.pdf}\n        \\caption{\\label{subfig:q16}The same model from Figure~\\ref{subfig:q8}\n        used to generate configurations on \\(V = 16\\times16\\) lattice.}\n    \\end{subfigure}\n    \\caption{\\label{fig:histories}Comparison of lattice observables for both\n        HMC and the trained model at \\(V = 8\\times 8\\), and \\(V =\n    16\\times16\\).}\n\\end{figure}\n    % \\begin{subfigure}[b]{\\linewidth}\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=\\linewidth]{assets/ess_loss_dkl_train.pdf}\n    \\caption{\\label{subfig:loss}Loss and Effective Sample\n        Size~\\cite{2018arXiv180904129E} (ESS) vs train epoch at \\(\\beta = 6\\)\n    on \\(V = 8\\times 8\\) lattice.}\n\\end{figure}\n%\n\\section{\\label{sec:ack}Acknowledgments}\nThis research was supported by the Exascale Computing Project (17-SC-20-SC), a\ncollaborative effort of the U.S. Department of Energy Office of Science and the\nNational Nuclear Security Administration.\n%\nThis research was performed using resources of the Argonne Leadership Computing\nFacility (ALCF), which is a DOE Office of Science User Facility supported under\nContract DE\\_AC02--06CH11357. \n%\nThis work describes objective technical results and analysis.\n%\nAny subjective views or opinions that might be expressed in the work do not\nnecessarily represent the views of the U.S. DOE or the United States\nGovernment.\n%\nResults presented in this research were obtained using the Python\n\\citep{van1995python}, programming language and its many data science libraries\n\\cite{%\n    matplotlib,\n    harris2020array,\n    ipython4160251%\n}\n%\n% \\begin{thebibliography}{99}\n\\bibliographystyle{JHEP}\n\\bibliography{main}\n% \\bibitem{...}\n\n% \\end{thebibliography}\n\n\\end{document}\n", "meta": {"hexsha": "a4ee1b75000c3d386bb21c8cad621da8cd866aa5", "size": 15392, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "main.tex", "max_stars_repo_name": "nftqcd/fthmc-Lattice2021", "max_stars_repo_head_hexsha": "0bb337e7452656ee8961a0e2196162125d39c567", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.tex", "max_issues_repo_name": "nftqcd/fthmc-Lattice2021", "max_issues_repo_head_hexsha": "0bb337e7452656ee8961a0e2196162125d39c567", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.tex", "max_forks_repo_name": "nftqcd/fthmc-Lattice2021", "max_forks_repo_head_hexsha": "0bb337e7452656ee8961a0e2196162125d39c567", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9113300493, "max_line_length": 96, "alphanum_fraction": 0.6893840956, "num_tokens": 4773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.33129661306788}}
{"text": "%!TEX root = modelguide.tex\n\n\\chapter{Muscle Wrapping and Via Points}\n\\label{multipointSpringIntro:sec}\n\nArtiSynth provides support for multipoint springs and muscles, which\nare similar to axial springs and muscles (Sections\n\\ref{AxialSprings:sec} and \\ref{PointToPointMuscles:sec}), except that\nthey can contain multiple via points and also wrap around obstacles.\nThis allows the associated force directions to vary in response to\nobstacles and constraints in the model, which is particularly\nimportant in biomechanical models where point-to-point muscles need to\nwrap around anatomical structures such as bones.  A schematic\nillustration is shown in Figure \\ref{multiPointSpring:fig}, where a\nsingle spring connects points $\\p_0$ and $\\p_2$, while passing through\na single via point $\\p_1$ and wrapping around obstacles $W_1$ and\n$W_2$. Figure \\ref{multiSpringExamples:fig} shows two examples\ninvolving a rigid body with fixed via points and a spring wrapping\naround three rigid bodies.\n\n\\begin{figure}[ht]\n\\begin{center}\n \\includegraphics[width=4in]{images/multiPointSpring}\n\\end{center}\n\\caption{Schematic illustration of a multipoint spring passing through\na via point $\\p_1$ and wrapping around two obstacles $W_1$ and\n$W_2$. The points $A_1$, $B_1$ and $A_2$, $B_2$ denote the first and\nlast locations where $W_1$ and $W_2$ make contact with the spring.}\n\\label{multiPointSpring:fig}\n\\end{figure}\n\n\\begin{figure}[ht]\n\\begin{center}\n  \\begin{tabular}{cc}\n    \\iflatexml\n       \\includegraphics[width=3in]{images/multiSpringDemo}&\n       \\includegraphics[width=3in]{images/multiBodyWrap2}\n    \\else\n       \\includegraphics[width=2.5in]{images/multiSpringDemo}&\n       \\includegraphics[width=2.5in]{images/multiBodyWrap2}\n    \\fi\n  \\end{tabular}\n\\end{center}\n\\caption{Left: A multipoint spring with two via points rigidly fixed\nto a box-shaped rigid body. Right: A multipoint spring wrapped around\nthree obstacles.}\n\\label{multiSpringExamples:fig}\n\\end{figure}\n\nAs with axial springs and muscles, multipoint springs and muscles must\nhave two points to denote their beginning and end. In between, they can\nhave any number of {\\it via} points, which are fixed locations which\nthe spring must pass through in the specified order. Any ArtiSynth\n\\javaclass[\\mech]{Point} object may be specified\nas a via point, including particles and markers. The purpose of the\nvia point is generally to direct the spring along some particular\npath. In particular, the path directions before and after a via point\nwill generally be different, and forces acting on the via point will\nbe determined by the tension in the spring (or muscle) acting along\nthese two different directions.\n\n\\begin{figure}[ht]\n\\begin{center}\n \\includegraphics[width=2.5in]{images/multiPointViaPoint}\n\\end{center}\n\\caption{A multipoint spring with a single via point $\\p_1$, showing\nthe unit direction vectors $\\u_A$ and $\\u_B$ immediately before and\nafter.}\n\\label{multiPointViaPoint:fig}\n\\end{figure}\n\n\\begin{sideblock}\nConceptually, the spring or muscle ``slides'' through its via points,\nwhich act analogously to virtual three dimensional pulleys. In\nparticular, the proportional distance between via points does {\\it not}\nremain fixed.\n\\end{sideblock}\n\nThe tension $f$ within the spring or muscle is computed from its\nmaterial, using the relation $f(l,\\dot l, a)$ described in Sections\n\\ref{AxialSprings:sec} and \\ref{sec:mechii:musclematerials},\nwhere $l$ now denotes the {\\it entire} length of the spring\nas it passes through the via points and wraps around obstacles. The\ntotal force $\\f$ acting on each via point is then given by\n%\n\\begin{equation*}\n\\f = f \\cdot (\\u_B - \\u_A)\n\\end{equation*}\n%\nwhere $\\u_B$ and $\\u_A$ are unit vectors giving the spring's direction\nimmediately after and before the via point\n(Figure \\ref{multiPointViaPoint:fig}).\n\nMultipoint springs can also be made to wrap around one or more {\\it\nwrappable} objects. Unlike via points, wrappable objects can occur in\nany order along the spring and wrapping only occurs when the spring\nand the object actually collide. Any ArtiSynth object that implements\n\\javaclass[\\mech]{Wrappable} can be used as a wrapping object\n(currently, only \\javaclass[\\mech]{RigidBody} objects\nimplement {\\tt Wrappable}).\nThe forces acting on a wrappable are those\ngenerated by the forces $\\f_A$ and $\\f_B$ acting on the points\nA and B where the spring makes and leaves contact with the\nit (Figure \\ref{multiPointObstacle:fig}). These forces\nare given by\n%\n\\begin{equation*}\n\\f_A = - f \\u_A, \\quad \\f_B = f \\u_B,\n\\end{equation*}\n%\nwhere $\\u_B$ are $\\u_A$ are unit vectors giving the spring's direction\nimmediately before A and after B. Points A and B are collectively\nknown as the A/B points.\n\n\\begin{figure}[ht]\n\\begin{center}\n \\includegraphics[width=2.5in]{images/multiPointObstacle}\n\\end{center}\n\\caption{A multipoint spring wrapping around a single obstacle $W$,\nwith initial and final contact at points A and B, \nand associated unit direction vectors $\\u_A$ and $\\u_B$.}\n\\label{multiPointObstacle:fig}\n\\end{figure}\n\n\\section{Via Points}\n\\label{ViaPoints:sec}\n\nMultipoint springs and muscles are implemented by the classes\n\\javaclass[\\mech]{MultiPointSpring} and\n\\javaclass[\\mech]{MultiPointMuscle}, respectively.\nThe relationship between {MultiPointSpring} and \n{MultiPointMuscle} is the same as that between\n\\javaclass[\\mech]{AxialSpring} and \\javaclass[\\mech]{Muscle}:\nThe latter is a subclass of the former, and allows\nthe creation of active tension forces in response to\nits {\\sf excitation} property.\n\nAn application allocates one of these components, sets the appropriate\nmaterial properties for the tension forces, and then adds points and\nwrappable objects as desired.\n\nPoints can be added, queried, and removed using the methods\n%\n\\begin{lstlisting}[]\n   void addPoint (Point pnt)\n   Point getPoint (int idx)\n   int numPoints()\n   boolean removePoint (Point pnt)\n\\end{lstlisting}\n%\nAs with \\javaclass[\\mech]{AxialSpring}, there must\nbe at least two points anchoring the beginning and end of the\nspring. Any additional points will be {\\it via points}.\n\n\\begin{figure}[ht]\n\\begin{center}\n  \\begin{tabular}{cc}\n    \\iflatexml\n       \\includegraphics[width=3in]{images/cylinderWrapping}&\n       \\includegraphics[width=3in]{images/cylinderWrappingKnots}\n    \\else\n       \\includegraphics[width=2.5in]{images/cylinderWrapping}&\n       \\includegraphics[width=2.5in]{images/cylinderWrappingKnots}\n    \\fi\n  \\end{tabular}\n\\end{center}\n\\caption{A multipoint spring with two segments, separated by a blue\nvia point (top), with the rightmost segment set to be wrappable so\nthat it can wrap around a cylinder. The right image shows the\nwrappable segment's knots.}\n\\label{cylinderWrappingKnots:fig}\n\\end{figure}\n\nThe section of a multipoint spring between any two adjacent points is\nknown as a {\\it segment}. By default, each segment forms a straight\nline between the two points and does {\\it not} interact with any\nwrappable obstacles. To interact with wrappables, a segment needs to\nbe declared {\\it wrappable}, as described in\nSection \\ref{ObstacleWrapping:sec}.\n\nSpring construction is illustrated by the following code fragment:\n%\n\\begin{lstlisting}[]\n   MultiPoint spring = new MultiPointSpring();\n   spring.setMaterial (new LinearAxialMaterial (stiffness, damping));\n   spring.addPoint (p0); // start point\n   spring.addPoint (p1); // via point\n   spring.addPoint (p2); // via point\n   spring.addPoint (p3); // stop point\n\\end{lstlisting}\n%\nThis creates a new {\\tt MultiPointSpring} and sets its material to a\nsimple linear material with a specified stiffness and damping.  Four points\n{\\tt p0}, {\\tt p1}, {\\tt p2}, {\\tt p3} are then added, forming a start\npoint, two via points, and a stop point.\n\n\\subsection{Example: a muscle with via points}\n\\label{ViaPointMuscle:sec}\n\n\\begin{figure}[t]\n\\begin{center}\n\\iflatexml\n \\includegraphics[]{images/ViaPointMuscle}\n\\else\n \\includegraphics[width=3.75in]{images/ViaPointMuscle}\n\\fi\n\\end{center}\n\\caption{ViaPointMuscle model loaded into ArtiSynth.}\n\\label{ViaPointMuscle:fig}\n\\end{figure}\n\nA simple example of a muscle containing via points is given by \n{\\tt artisynth.demos.tutorial.ViaPointMuscle}.  It consists\nof a MultiPointMuscle passing through two via points attached to a\nblock. The code is given below:\n\\lstset{numbers=left}\n\\lstinputlisting{../../src/artisynth/demos/tutorial/ViaPointMuscle.java}\n\\lstset{numbers=none}\n\nLines 21-30 of the {\\tt build()} method create a {\\tt MechModel} and\nadd a simple rigid body block to it. Two non-dynamic points ({\\tt p0}\nand {\\tt p1}) are then created to act as muscle end points\n(lines 33-38), along with two markers ({\\tt via0} and {\\tt via1})\nwhich are attached to the block to act as via points\n(lines 41-44). The muscle itself is created by lines 42-53, with the\nend points and via points being added in order from start to end.\nThe muscle material is a \n\\javaclass[artisynth.core.materials]{SimpleAxialMuscle},\nwhich computes tension according to the simple linear formula \n(\\ref{SimpleAxialMuscle:eqn}) described in Section \n\\ref{sec:mechii:musclematerials}. Lines 56-57 set render\nproperties for the model, and line 59 creates a control panel\n(Section \\ref{ControlPanels:sec}) that allows the muscle {\\sf\nexcitation} property to be interactively controlled.\n\nTo run this example in ArtiSynth, select {\\sf All demos > tutorial >\nViaPointMuscle} from the {\\sf Models} menu. The model should load and\ninitially appear as in Figure \\ref{ViaPointMuscle:fig}.  Running the\nmodel will cause the block to fall and swing about under gravity,\nwhile changing the muscle's {\\sf excitation} in the control panel will\nvary its tension.\n\n\\section{Obstacle Wrapping}\n\\label{ObstacleWrapping:sec}\n\nAs mentioned in Section \\ref{ViaPoints:sec}, segments between pairs of\nvia points can be declared {\\it wrappable}, allowing them to interact\nwith wrappable obstacles. This can be done as via points are added\nto the spring, using the methods\n%\n\\begin{lstlisting}[]\n   void setSegmentWrappable (int numKnots)\n   void setSegmentWrappable (int numKnots, Point3d[] initialPoints)\n\\end{lstlisting}\n%\nThese make {\\it wrappable} the next segment to be created (i.e., the segment\nbetween the most recently added point and the next point to be added),\nwith {\\tt numKnots} specifying the number of {\\it knots} that should\nbe used to implement the wrapping. Knots are points that divide the\nwrappable segment into a piecewise linear curve, and are used to\ncheck for collisions with the wrapping surfaces\n(Figure \\ref{cylinderWrappingKnots:fig}).  The argument {\\tt\ninitialPoints} used by the second method is an optional argument\nwhich, if non-null, can be used to specify intermediate guide points\nto give the segment an initial path around around any obstacles (for\nmore details, see Section \\ref{wrappingInit:sec}).\n\nEach wrappable segment will be capable of colliding with any of the\nwrappable obstacles that are known to the spring.  Wrappables can be\nadded, queried and removed using the following methods:\n%\n\\begin{lstlisting}[]\n   void addWrappable (Wrappable wrappable)\n   Wrappable getWrappable (int idx)\n   int numWrappables()\n   boolean removeWrappable (Wrappable wrappable)\n\\end{lstlisting}\n%\nUnlike points, however, there is no implied ordering and wrappables\ncan be added in any order and at any time during the spring's\nconstruction.\n\nWrappable spring construction is illustrated by the following code\nfragment:\n%\n\\begin{lstlisting}[]\n   MultiPoint spring = new MultiPointSpring();\n   spring.setMaterial (new LinearAxialMaterial (stiffness, damping));\n   spring.addPoint (p0); // start point\n   spring.setSegmentWrappable (50);  // wrappable segment\n   spring.addPoint (p1); // via point\n   spring.addPoint (p2); // end point\n   spring.addWrappable (wrappable1);\n   spring.addWrappable (wrappable2);\n   spring.updateWrapSegments(); // ``shrink wrap'' spring to the obstacles\n\\end{lstlisting}\n%\nThis creates a new {\\tt MultiPointSpring} with a linear material and\nthree points {\\tt p0}, {\\tt p1}, and {\\tt p2}, forming a start point,\nvia point, and stop point.  The segment between {\\tt p0} and {\\tt p1}\nis set to be wrappable with 50 knot points. Two wrappable obstacles\nare added next, each of which will interact with the {\\tt p0}-{\\tt p1}\nsegment, but {\\it not} with the non-wrappable {\\tt p1}-{\\tt p2}\nsegment. Finally, {\\tt updateWrapSegments()} is called to do an\ninitial solve for the wrapping segments, so that they will be ``pulled\ntight'' around any obstacles before simulation begins.\n\nIt is also possible to make a segment wrappable {\\it after}\nspring construction, using the method\n%\n\\begin{lstlisting}[]\n   void setSegmentWrappable (int segIdx, int numKnots, Point3d[] initialPoints)\n\\end{lstlisting}\n%\nwhere {\\tt segIdx} identifies the segment between points ${\\tt segIdx}$\nand ${\\tt segIdx}+1$.\n\nHow many knots should be specified for a wrappable segment? Enough so\nthat the resulting piecewise-linear approximation to the wrapping\ncurve is sufficiently \"smooth\", and also enough to adequately detect\ncontact with the obstacles without passing through them. Values\nbetween 50 and 100 generally give good results. Obstacles that are\nsmall with respect to the segment length may necessitate more\nknots. Making the number of knots very large will slow down the\ncomputation (although the computational cost is only $O(n)$ with\nrespect to the number of knots).\n\nAt the time of this writing, ArtiSynth implements two types of\n\\javaclass[\\mech]{Wrappable} object, both of which are instances of\n\\javaclass[\\mech]{RigidBody}. The first are specialized {\\it analytic}\nsubclasses of {\\tt RigidBody}, listed in Table\n\\ref{analyticWrappables:tbl}, which define specific geometries and use\nanalytic methods for the collision handling with the knot points.  The\nuse of analytic methods allows for greater accuracy and\n(possibly) computational efficiency,\nand so because of this, these special geometry\nwrappables should be used whenever possible.\n\n\\begin{table}[h]\n\\centering\n\\begin{tabular}{ll}\n   \\hline\n   \\hline\n   Wrappable & Description \\\\\n   \\hline\n   \\javaclass[\\mech]{RigidCylinder} & \n              A cylinder with a specified height and radius\\\\\n   \\javaclass[\\mech]{RigidSphere} & \n              A sphere with a specified radius \\\\\n   \\javaclass[\\mech]{RigidEllipsoid} &  \n              An ellipsoid with specified semi-axis lengths\\\\\n   \\javaclass[\\mech]{RigidTorus} &  \n              A torus with specified inner and outer radii\\\\\n\\hline\n\\end{tabular}\n\\caption{Specialized analytic subclasses of {\\tt RigidBody}}\n\\label{analyticWrappables:tbl}\n\\end{table}\n\n\\begin{figure}[ht]\n\\begin{center}\n\\begin{tabular}{cc}\n\\iflatexml\n \\includegraphics[]{images/HumerusWrap}&\n \\includegraphics[]{images/HipWrap}\n\\else\n \\includegraphics[width=2.5in]{images/HumerusWrap}&\n \\includegraphics[width=2.5in]{images/HipWrap}\n\\fi\n\\end{tabular}\n\\end{center}\n\\caption{Muscle strands wrapped around general bone-shaped meshes: a\nhumerus (left), and a pelvis (right)}\n\\label{GeneralWrapping:fig}\n\\end{figure}\n\nThe second are general rigid bodies which are {\\it not} analytic\nsubclasses, and for which the wrapping surface is determined directly\nfrom the geometry of its collision mesh returned by\n\\javamethod[\\mech.RigidBody]{getCollisionMesh()}.  (Typically the\ncollision mesh corresponds to the surface mesh, but it is possible to\nspecify alternates; see Section \\ref{rigidBodyMultipleMeshes:sec}.)\nThis is useful in that it permits wrapping around {\\it arbitrary} mesh\ngeometries (Figure \\ref{GeneralWrapping:fig}), but in order for the\nwrapping to work well, these geometries should be smooth, without\nsharp edges or corners.  Wrapping around general meshes is implemented\nusing a quadratically interpolated signed-distance grid (Section\n\\ref{DistanceGrids:sec}), and the resolution of this grid also affects\nthe effective smoothness of the wrapping surface. More details on this\nare given in Section \\ref{GeneralSurfaceWrapping:sec}.\n\n\\subsection{Example: wrapping around a cylinder}\n\\label{CylinderWrapping:sec}\n\n\\begin{figure}[t]\n\\begin{center}\n\\iflatexml\n \\includegraphics[]{images/CylinderWrappingStart}\n\\else\n \\includegraphics[width=3.75in]{images/CylinderWrappingStart}\n\\fi\n\\end{center}\n\\caption{CylinderWrapping model loaded into ArtiSynth.}\n\\label{CylinderWrapping:fig}\n\\end{figure}\n\nA example showing multipoint spring wrapping is given by {\\tt\nartisynth.demos.tutorial.CylinderWrapping}.  It consists of a\n{\\tt MultiPointSpring} passing through a single via point, with both\nsegments on either side of the point made wrappable. Two analytic\nwrappables are used: a fixed {\\tt RigidCylinder}, and a moving {\\tt\nRigidEllipsoid} attached to the end of the spring. The code, excluding\ninclude directives, is given below: \n\n\\lstset{numbers=left} \n\\iflatexml\n%% Hack: latexml lstinputlisting doesn't handle firstline correctly\n\\lstset{firstnumber={-15}}\n\\lstinputlisting[firstline=1]{../../src/artisynth/demos/tutorial/CylinderWrapping.java}\n\\lstset{firstnumber={1}}\n\\else\n\\lstinputlisting[firstline=17]{../../src/artisynth/demos/tutorial/CylinderWrapping.java}\n\\fi\n\\lstset{numbers=none}\n\nLines 4-17 of the {\\tt build()} method create a {\\tt MechModel} with\ntwo fixed particles {\\tt via0} and {\\tt p1} to be used as via and stop\npoints. Next, two analytic wrappables are created: a {\\tt\nRigidCylinder} and a {\\tt RigidEllipsoid}, with the former fixed in\nplace and the latter connected to the start of the spring via the\nmarker {\\tt p0} (lines 20-37). Collisions are enabled between these\ntwo wrappables at line 40. The spring itself is created (lines 44-52),\nusing {\\tt setSegmentWrappable()} to make the segments ({\\tt p0}, {\\tt\nvia0}) and ({\\tt via0}, {\\tt p1}) wrappable with 50 knots each, and\n{\\tt addWrappable()} to make it aware of the two wrappables.  Finally,\nrender properties at set (lines 55-58), and a control panel (Section\n\\ref{ControlPanels:sec}) is added that allows the spring's {\\sf\ndrawKnots} and {\\sf drawABPoints} properties to be interactively set.\n\nTo run this example in ArtiSynth, select {\\sf All demos > tutorial >\nCylinderWrapping} from the {\\sf Models} menu. The model should load and\ninitially appear as in Figure \\ref{CylinderWrapping:fig}.  Running the\nmodel will cause the ellipsoid to fall and the spring to wrap around\nthe cylinder. Using the pull tool\n(Section ``Pull Manipulation'' in the\n\\artisynthManual{uiguide}{ArtiSynth User Interface Guide})\non the ellipsoid can cause additional motions and make it also collide\nwith the spring. Selecting {\\sf drawKnots} or {\\sf drawABPoints} in\nthe control panel will cause the spring to render its knots and/or A/B\npoints.\n\n\\section{General Surfaces and Distance Grids}\n\\label{GeneralSurfaceWrapping:sec}\n\nAs mentioned in Section \\ref{ObstacleWrapping:sec}, wrapping around\ngeneral mesh geometries is implemented using a quadratically\ninterpolated signed distance grid. By default, for a rigid body, this\ngrid is generated automatically from the body's collision mesh (as\nreturned by {\\tt getCollisionMesh()}; see Section\n\\ref{collisionMeshes:sec}).\n\nUsing a distance grid allows very efficient collision handling between\nthe body and the wrap segment knots. However, it also means that the\ntrue wrapping surface is not actually the collision mesh itself, but\ninstead the zero-valued isosurface associated with quadratic grid\ninterpolation.  Well-behaved wrapping behavior requires that this\nisosurface be smooth and free of sharp edges, so that knot motions\nremain relatively smooth as they move across it. Quadratic\ninterpolation helps with this, which is the reason for employing\nit. Otherwise, one should try to ensure that (a) the collision mesh\nfrom which the grid is generated is itself smooth and free of sharp\nedges, and (b) the grid has sufficient resolution to not introduce\ndiscretization artifacts.\n\nMuscle wrapping is often performed around structures such as bones,\nfor which the representing surface mesh is often insufficiently smooth\n(especially if segmented from medical image data).  In some cases, the\ndistance grid's quadratic interpolation may provide sufficient\nsmoothing on its own; to determine this, one should examine the\nquadratic isosurface as described below. In other cases, it may be\nnecessary to explicitly smooth the mesh itself, either externally or\nwithin ArtiSynth using the \\javaclass[\\mgeo]{LaplacianSmoother} class,\nwhich can apply iterations of either Laplacian or volume-preserving\nTaubin smoothing, via the method\n%\n\\begin{lstlisting}[]\n  LaplacianSmoother.smooth (mesh, numi, lam, mu);\n\\end{lstlisting}\n%\nHere {\\tt numi} is the number of iterations and {\\tt tau} and {\\tt mu}\nare the Taubin parameters. Setting ${\\tt lam} = 1$ and ${\\tt mu} = 0$\nresults in traditional Laplacian smoothing. If this causes the mesh to\nshrink more than desired, one can counter this by setting {\\tt tau}\nand {\\tt mu} to values used for Taubin smoothing, as described in\n\\cite{taubin1995curve}.\n\n\\begin{sideblock}\nIf the mesh is large (i.e., has many vertices), then smoothing it may\ntake noticable computational time. In such cases, it is generally best\nto simply save and reuse the smoothed mesh.\n\\end{sideblock}\n\nBy default, if a rigid body contains only one polygonal mesh, then its\nsurface and collision meshes (returned by\n\\javamethod[\\mech.RigidBody]{getSurfaceMesh()} and\n\\javamethod[\\mech.RigidBody]{getCollisionMesh()}, respectively) are\nthe same.  However, if it is necessary to significantly smooth or\nmodify the collision mesh, for wrapping or other purposes, it may be\ndesirable to use different meshes for the surface and collision. This\ncan be done by making the surface mesh non-collidable and adding an\nadditional mesh that {\\it is} collidable, as discussed in Section\n\\ref{rigidBodyMultipleMeshes:sec} as illustrated by the following code\nfragment:\n%\n\\begin{lstlisting}[]\n  PolygonalMesh surfaceMesh;\n  PolygonalMesh wrappingMesh;\n\n  // ... initialize surface and wrapping meshes ...\n\n  // create the body from the surface mesh\n  RigidBody body = RigidBody.createFromMesh (\n      \"body\", mesh, /*density=*/1000, /*scale=*/1.0);\n\n  // set the surface mesh to be non-collidable, and add the wrapping mesh as\n  // collidable but not having mass\n  body.getSurfaceMeshComp().setIsCollidable (false);\n  RigidMeshComp wcomp = body.addMesh (\n      wrappingMesh, /*hasMass=*/false, /*collidable=*/true);\n  RenderProps.setVisible (wcomp, false); // hide the wrapping mesh\n\\end{lstlisting}\n%\nHere, to ensure that the wrapping mesh does {\\it not} to contribute to\nthe body's inertia, its {\\sf hasMass} property is set to false.\n\nAlthough it is possible to specify a collision mesh that is separate\nfrom the surface mesh, there is currently no way to specify {\\it separate}\ncollision meshes for wrapping and collision handling.  If this is\ndesired for some reason, then one alternative is to create a separate\nbody for wrapping purposes, and then attach it to the main body, as\ndescribed in Section \\ref{AlternateWrappingSurfaces:sec}.\n\nTo verify that the distance grid's quadratic isosurface is\nsufficiently smooth for wrapping purposes, it is useful to visualize\nthe both distance grid and its isosurface directly, and if necessary\nadjust the resolution used to generate the grid. This can be\naccomplished using the body's\n\\javaclass[artisynth.core.mechmodels]{DistanceGridComp}, which is a\nsubcomponent named {\\tt distanceGrid} and which may be obtained using\nthe method\n%\n\\begin{lstlisting}\n   DistanceGridComp getDistanceGridComp()\n\\end{lstlisting}\n%\nA {\\tt DistanceGridComp} exports a number of properties that can be\nused to control the grid's visualization, resolution, and fit around\nthe collision mesh. These properties are described in detail in\nSection \\ref{DistanceGrids:sec}, and can be set either in code using\ntheir set/get accessors, or interactively using custom control panels\nor by selecting the grid component in the GUI and choosing {\\sf Edit\nproperties ...} from the right-click context menu.\n\n\\begin{sideblock}\nWhen rendering the mesh isosurface, it is usually desirable to also\ndisable rendering of the collision meshes within the rigid body.  For\nconvenience, this can be accomplished by setting the body's {\\sf\ngridSurfaceRendering} property to {\\tt true}, which will cause the\ngrid isosurface to be rendered {\\it instead} of the body's meshes.\nThe isosurface type will be that indicated by the grid component's\n{\\sf surfaceType} property (which should be {\\tt QUADRATIC} for the\nquadratic isosurface), and the rendering will occur independently of\nthe visibility settings for the meshes or the grid component.\n\\end{sideblock}\n\n\\subsection{Example: wrapping around a bone}\n\\label{TalusWrapping:sec}\n\n\\begin{figure}[t]\n\\begin{center}\n\\begin{tabular}{cc}\n\\iflatexml\n \\includegraphics[]{images/TalusWrapping}&\n \\includegraphics[]{images/TalusWrapping2}\n\\else\n \\includegraphics[width=3.2in]{images/TalusWrapping}&\n \\includegraphics[width=3.2in]{images/TalusWrapping2}\n\\fi\n\\end{tabular}\n\\end{center}\n\\caption{TalusWrapping model, with a dragger being used to move {\\tt\np0} (left), and the knots visible and grid visible with restricted\nrange (right).}\n\\label{TalusWrapping:fig}\n\\end{figure}\n\nAn example of wrapping around a general mesh is given by\n{\\tt artisynth.demos.tutorial.TalusWrapping}.  It consists\nof a MultiPointSpring anchored by two via points and wrapped around a\nrigid body representing a talus bone. The code, with include\ndirectives omitted, is given below: \n\\lstset{numbers=left}\n\\iflatexml\n%% Hack: latexml lstinputlisting doesn't handle firstline correctly\n\\lstset{firstnumber={-12}}\n\\lstinputlisting[firstline=1]{../../src/artisynth/demos/tutorial/TalusWrapping.java}\n\\lstset{firstnumber={1}}\n\\else\n\\lstinputlisting[firstline=14]{../../src/artisynth/demos/tutorial/TalusWrapping.java}\n\\fi\n\\lstset{numbers=none}\n\nThe mesh describing the talus bone is loaded from the file {\\tt\n\"data/TalusBone.obj\"} located beneath the model's source directory\n(lines 11-19), with the utility class\n\\javaclass[maspack.util]{PathFinder} used to determine the file path\n(Section \\ref{PathFinder:sec}).\nTo ensure better wrapping behavior, the mesh is smoothed\nusing Laplacian smoothing (line 21) before being used to create\nthe rigid body (lines 23-27). The spring and its anchor points {\\tt\np0} and {\\tt p1} are created between lines 30-49, with the talus added\nas a wrappable. The spring contains a single segment which is made\nwrappable using 100 knots, and initialized with an intermediate point\n(line 45) to ensure that it wraps around the bone in the correct way.\nIntermediate points are described in more detail in Section\n\\ref{wrappingInit:sec}.\n\nRender properties are set at lines 52-56; this includes turning off\nrendering for grid normals by zeroing the {\\sf lineWidth} render\nproperty for the grid component.\n\nFinally, lines 59-67 create a control panel (Section\n\\ref{ControlPanels:sec}) for interactively controlling a variety of\nproperties, including {\\sf gridSurfaceRendering} for the talus (to see\nthe grid isosurface instead of the bone mesh), {\\sf resolution}, {\\sf\nmaxResolution}, {\\sf renderGrid}, and {\\sf renderRanges} for the grid\ncomponent (to control its resolution and visibility), and {\\sf\ndrawKnots} and {\\sf wrapDamping} for the spring (to make knots visible\nand to adjust the wrap damping as described in Section\n\\ref{wrapTuning:sec}).\n\nTo run this example in ArtiSynth, select {\\sf All demos > tutorial >\nTalusWrapping} from the {\\sf Models} menu. Since all of the dynamic\ncomponents are fixed, running the model will not cause any initial\nmotion. However, while simulating, one can use the viewer's graphical\ndragger fixtures (see the section ``Transformer Tools'' in the\n\\artisynthManual{uiguide}{ArtiSynth User Interface Guide}) to move\n{\\tt p0} or {\\tt p1} and hence pull the spring across the bone surface\n(Figure \\ref{TalusWrapping:fig}, left). One can also interactively\nadjust the property settings in the control panel to view the grid,\nisosurface, and knots, and the adjust the grid's resolution.  Figure\n\\ref{TalusWrapping:fig}, right, shows the model with {\\sf renderGrid}\nand {\\sf drawKnots} set to {\\tt true} and {\\sf renderRanges} set to\n{\\tt \"10:12 * *\"}.\n\n\\section{Initializing the Wrap Path}\n\\label{wrappingInit:sec}\n\nBy default, when a multipoint spring or muscle is initialized (either\nat the start of the simulation or as a result of calling\n\\javamethod*[\\mech .MultiPointSpring]{updateWrapSegments()}), each\nwrappable segment is initialized to a straight line between its via\npoints. This path is then adjusted to avoid and wrap around obstacles,\nusing artificial linear forces as described in Section\n\\ref{wrapTuning:sec}. The result is a local shortest path that wraps\naround obstacles instead of penetrating them.  However, in some cases,\nthe initial path may not be the one desired; instead, one may want it\nto wrap around obstacles some other way. This can be achieved by\nspecifying additional intermediate points to initialize the segment as\na piecewise linear path which threads its way around obstacles in the\ndesired manner (Figure \\ref{wrapInitialization:fig}).  These are\nspecified using the optional {\\tt initialPnts} argument to the {\\tt\nsetSegmentWrappable()} methods.\n\n\\begin{figure}[ht]\n\\begin{center}\n \\includegraphics[width=6in]{images/wrapInitialization}\n\\end{center}\n\\caption{By default, the path for each wrappable segment is\ninitialized to a straight line between its via points (dotted line,\nleft), which is then adjusted to wrap around obstacles (solid line,\nmiddle). To cause the path to wrap around obstacles in a different\nway, it can instead be initialized using a piecewise-linear\npath defined by intermediate initial points (dotted line, right),\nwhich will then adjust to an alternate configuration.}\n\\label{wrapInitialization:fig}\n\\end{figure}\n\n\\begin{sideblock}\nWhen initial points are specified, it is recommended to finish\nconstruction of the spring or muscle with a call to\n\\javamethod[\\mech.MultiPointSpring]{updateWrapSegments()}.  This fits\nthe wrappable segments to their correct path around the obstacles,\nwhich can then be seen immediately when the model is first loaded. On\nthe other hand, by {\\it omitting} an initial call to {\\tt\nupdateWrapSegments()}, it is possible to see the initial path as\nspecified by the initial points. This may be useful to\nverify that they are in the correct locations.\n\\end{sideblock}\n\n\\begin{sideblock}\nIn some cases, initial points may also be necessary to help ensure\nthat the initial path does not penetrate obstacles. While obstacle\npenetration will normally be resolved by the artificial forces\ndescribed in Section \\ref{wrapTuning:sec}, this may not always work\ncorrectly if the starting path penetrates an obstacle too deeply.\n\\end{sideblock}\n\n\\subsection{Example: wrapping around a torus}\n\\label{TorusWrapping:sec}\n\n\\begin{figure}[ht]\n\\begin{center}\n\\iflatexml\n \\includegraphics[]{images/TorusWrapping}\n\\else\n \\includegraphics[width=3.75in]{images/TorusWrapping}\n\\fi\n\\end{center}\n\\caption{{\\tt TorusWrapping} model loaded into ArtiSynth.}\n\\label{TorusWrapping:fig}\n\\end{figure}\n\nAn example of using initial points is given by {\\tt\nartisynth.demos.tutorial.TorusWrapping}, in which a spring\nis wrapped completely around the inner section of a torus.\nThe primary code for\nthe build method is given below: \n\\lstset{numbers=left}\n\\iflatexml\n%% Hack: latexml lstinputlisting doesn't handle firstline correctly\n\\lstset{firstnumber={-20}}\n\\lstinputlisting[firstline=1,lastline=41]{../../src/artisynth/demos/tutorial/TorusWrapping.java}\n\\lstset{firstnumber={1}}\n\\else\n\\lstinputlisting[firstline=22,lastline=62]{../../src/artisynth/demos/tutorial/TorusWrapping.java}\n\\fi\n\\lstset{numbers=none}\n\nThe mech model is created in the usual way with frame and rotary\ndamping set to 1 and 10 (lines 4-5). The torus is created using the\nanalytic wrappable \\javaclass[\\mech]{RigidTorus} (lines 8-14). The\nspring start and end points {\\tt p0} and {\\tt p1} are created at lines\n(17-22), and the spring itself is created at lines (26-41), with six\ninitial points being specified to {\\tt setSegmentWrappable()} to wrap\nthe spring completely around the torus inner section.\n\nTo run this example in ArtiSynth, select {\\sf All demos > tutorial >\nTorusWrapping} from the {\\sf Models} menu. The torus will slide along\nthe wrapped spring until it reaches equilibrium.\n\n\\section{Alternate Wrapping Surfaces}\n\\label{AlternateWrappingSurfaces:sec}\n\nAlthough it common to use the general mesh geometry of a {\\tt\nRigidBody} as the wrapping surface, situations may arise where it is\ndesirable to {\\it not} do this. These may include:\n\n\\begin{itemize}\n\n\\item The general mesh geometry is not sufficiently smooth\nto form a good wrapping surface;\n\n\\item Wrapping around the default mesh geometry is not stable, in\nthat it is too easy for the wrap strand to ``slip off'';\n\n\\item Using one of the simpler analytic geometries\n(Table \\ref{analyticWrappables:tbl}) may result in a more efficient\ncomputation.\n\n\\end{itemize}\n\nThere are a couple of ways to handle this. One, discussed in Section\n\\ref{GeneralSurfaceWrapping:sec}, involves creating a collision mesh\nwhich is separate from the general mesh geometry. However, that same\ncollision mesh must then also be used for collision handling (Section\n\\ref{sec:mechii:collisions}). If that is undesirable, or if {\\it\nmultiple} wrapping surfaces are needed, then a different approach may\nbe used. This involves creating the desired wrappable as a separate\nobject and then {\\it attaching} it to the main {\\tt\nRigidBody}. Typically, this wrappable will be created with zero mass\n(or density), so that it does not alter the effective mass or inertia\nof the main body. The general procedure then becomes:\n\n\\begin{enumerate}\n\n\\item Create the main {\\tt RigidBody} with whatever desired geometry\nand inertia is needed;\n\n\\item Create the additional wrappable object(s), usually\nwith zero density/mass;\n\n\\item Attach the wrappables to the main body using\none of the {\\tt MechModel} {\\tt attachFrame()} methods described in\nSection \\ref{sec:mech:frameattachments}.\n\n\\end{enumerate}\n\n\\subsection{Example: wrapping for a finger joint}\n\\label{PhalanxWrapping:sec}\n\n\\begin{figure}[t]\n\\begin{center}\n\\iflatexml\n \\includegraphics[]{images/PhalanxWrapping}\n\\else\n \\includegraphics[width=3.75in]{images/PhalanxWrapping}\n\\fi\n\\end{center}\n\\caption{PhalanxWrapping model loaded into ArtiSynth.}\n\\label{PhalanxWrapping:fig}\n\\end{figure}\n\nAn example using an alternate wrapping surface is given by {\\tt\nartisynth.demos.tutorial.PhalanxWrapping}, which shows a \na muscle wrapping around a joint between two finger\nbones. Because the bones themselves are fairly narrow, using them as\nwrapping surfaces would likely lead to the muscle slipping\noff. Instead, a \\javaclass[\\mech]{RigidCylinder} is used for the\nwrapping and attached to one of the bones. The code, with include\ndirectives excluded, is given below: \\lstset{numbers=left} \\iflatexml\n%% Hack: latexml lstinputlisting doesn't handle firstline correctly\n\\lstset{firstnumber={-10}}\n\\lstinputlisting[firstline=1]{../../src/artisynth/demos/tutorial/PhalanxWrapping.java}\n\\lstset{firstnumber={1}}\n\\else\n\\lstinputlisting[firstline=12]{../../src/artisynth/demos/tutorial/PhalanxWrapping.java}\n\\fi\n\\lstset{numbers=none}\n\nThe method {\\tt createBody()} (lines 6-14) creates a rigid body from a\ngeometry mesh stored in a file in the directory ``{\\tt data}'' beneath\nthe source directory, using the utility class\n\\javaclass[maspack.util]{PathFinder} used to determine the file path\n(Section \\ref{PathFinder:sec}).\n\nWithin the {\\tt build()} method, a {\\tt MechModel} is created\ncontaining two rigid bodies representing the bones, {\\tt proximal} and\n{\\tt middle}, with {\\tt proximal} fixed and {\\tt middle} free to move\nwith a frame damping of 0.03 (lines 18-28). A cylindrical joint is\nthen added between the bones, along with markers describing the\nmuscle's origin and insertion points (lines 31-42).  A {\\tt\nRigidCylinder} is created to act as a wrapping obstacle and attached\nto the {\\tt middle} bone in the same location as the joint (lines\n46-50); since it is created with a density of 0 it has no mass and\nhence does not affect the bone's inertia. The muscle itself is created\nat lines 53-64, using a\n\\javaclass[artisynth.core.materials]{SimpleAxialMuscle} as a material\nand an extra initial point specified to\n{\\tt setSegmentWrappable()} to ensure that it wraps around\nthe cylinder in the correct way (Section\n\\ref{wrappingInit:sec}). Finally, render properties are set at lines\n67-69.\n\nTo run this example in ArtiSynth, select {\\sf All demos > tutorial >\nPhalanxWrapping} from the {\\sf Models} menu. The model should load and\ninitially appear as in Figure \\ref{PhalanxWrapping:fig}.  When running\nthe model, one can move the {\\tt middle} bone either\nby using the pull tool (Section ``Pull\nManipulation'' in the\n\\artisynthManual{uiguide}{ArtiSynth User Interface Guide}),\nor selecting the muscle in the GUI, invoking a property dialog by\nchoosing {\\sf Edit properties ...} from the right-click context menu,\nand adjusting the {\\sf excitation} property.\n\n\\section{Tuning the Wrapping Behavior}\n\\label{wrapTuning:sec}\n\nWrappable segments are implemented internally using artificial linear\nelastic forces to draw the knots together and keep them from\npenetrating obstacles. These artificial forces are invisible to the\nsimulation: the wrapping segment has no mass, and the knot forces are\nused to create what is essentially a first order physics that ``shrink\nwraps'' each segment around the obstacles at the beginning of each\nsimulation step, forming a shortest-distance geodesic curve from\nwhich the wrapping contact points A and B are calculated. This process\nis now described in more detail.\n\nAssume that a wrappable segment has $m$ knots, indexed by $k =\n1, \\ldots, m$, each located at a position $\\x_k$. Two types of\nartificial forces then act on each knot: a {\\it wrapping force}\nthat pulls it closer to other knots, and {\\it contact forces} that\npush it away from wrappable obstacles. The wrapping force is given by\n%\n\\begin{equation*}\n\\f_{w,k} = K_w (\\x_{k+1} - 2 \\x_k + \\x_{k-1})\n%\\label{knotForce:eqn}\n\\end{equation*}\n%\nwhere $K_w$ is the {\\it wrapping stiffness}. To determine the contact\nforces, we compute, for each wrappable, the knot's distance to the\nsurface $d_k$ and associated normal direction $\\n_k$, where $d_k < 0$\nimplies that the knot is inside. These quantities are determined\neither analytically (for analytic wrappables, Table\n\\ref{analyticWrappables:tbl}), or using a signed distance grid (for\ngeneral wrappables, Section \\ref{GeneralSurfaceWrapping:sec}).  The\ncontact forces are then given by\n%\n\\begin{equation*}\n\\f_{c,k} = \n\\begin{cases}\n-K_c \\, d_k \\, \\n_k & \\text{if} \\; d_k < 0 \\\\\n0 & \\text{otherwise},\n\\end{cases}\n%\\label{contactForce:eqn}\n\\end{equation*}\n%\nwhere $K_c$ is the {\\it contact stiffness}.\n\nThe total force $\\f_k$ acting on each knot is then given by\n%\n\\begin{equation*}\n\\f_k = \\f_{w,k} + \\sum_c \\f_{c,k}\n%\\label{XXX:eqn}\n\\end{equation*}\n%\nwhere the latter term is the sum of contact forces for all wrappables.\nIf we let $\\x$ and $\\f$ denote the aggregate position and force vectors\nfor all knots, then computing the wrap path involves finding the\nequilibrium position such that $\\f(\\x) = 0$. This is done at the\nbeginning of each simulation step, or whenever \\javamethod*[\\mech\n.MultiPointSpring]{updateWrapSegments()} is called, and\nis achieved iteratively using Newton's method.\nIf $\\x^j$ and $\\f(\\x^j)$ denote the positions and forces at iteration $j$, \nand\n%\n\\begin{equation*}\n\\K \\equiv \\frac{\\partial \\f}{\\partial \\x}\n\\end{equation*}\n%\ndenotes the local force derivative (or ``stiffness''), then the basic\nNewton update is given by\n%\n\\begin{equation*}\n\\x^{j+1} = \\x^j - \\K^{-1} \\f(\\x^j).\n\\label{NewtonSolve:eqn}\n\\end{equation*}\n%\nIn practice, to help deal with the nonlinearities associated with\ncontact, we use a damped Newton update,\n%\n\\begin{equation}\n\\x^{j+1} = \\x^j + \\alpha (D \\I - \\K)^{-1} \\f(\\x^j),\n\\label{DampedNewtonSolve:eqn}\n\\end{equation}\n%\nwhere $D$ is a constant {\\it wrap damping} parameter, and $\\alpha$ is\nan adaptively computed step size adjustment. The computation of\n(\\ref{DampedNewtonSolve:eqn}) can be performed quickly, in $O(m)$\ntime, since $\\K$ is a block-tridiagonal matrix, and the number of\niterations required is typically small (on the order of 10 or less),\nparticularly since the iterative procedure continues across simulation\nsteps and so $\\f(\\x)$ does not need to be brought to $0$ for any given\nstep. The maximum number of Newton iterations used for each\ntime step is $N_\\text{max}$.\n\n\\begin{sideblock}\nAgain, it is important to understand the artificial knot forces\n$\\f(\\x)$ described here are separate from the physical spring/muscle\ntension forces $f(l,\\dot l, a)$ discussed in Sections\n\\ref{AxialSprings:sec} and \\ref{sec:mechii:musclematerials}, and {\\it\nonly} facilitate the computation of each wrappable segment's path\naround obstacles.\n\\end{sideblock}\n\nThe default values for the wrapping parameters are $K_w = 1$, $K_c =\n10$, $D = 10$, and $N_\\text{max} = 10$, and these often give\nsatisfactory results without the need for modification.  However, in\nsome situations the default muscle wrapping may not perform adequately\nand it is necessary to adjust these parameters. Problems may include:\n\n\\begin{itemize}\n\n\\item The wrapping path does not settle down and tends to ``jump\naround''.  Solutions include increasing the damping parameter $D$ or\nthe maximum number of wrap iterations $N_i$. For general wrapping\nsurfaces (Section \\ref{GeneralSurfaceWrapping:sec}), one should also\nensure that the surface is sufficiently smooth.\n\n\\item A wrapping surface is too thin and so the wrapping\npath ``jumps through'' it. Solutions include increasing the damping\nparameter $D$, increasing the number of knots in the segment, or\ndecreasing the simulation step size. An alternative approach is to use\nan alternative wrapping surface\n(Section \\ref{AlternateWrappingSurfaces:sec}) that is thicker and\nbetter behaved.\n\n\\end{itemize}\n\nWrapping parameters are exported as properties of {\\tt\nMultiPointSpring} and {\\tt MultiPointMuscle}, and may be changed in\ncode (using their set/get accessors), or interactively,\neither by exposing them through a control panel,\nor by selecting the spring/muscle in the GUI and choosing {\\sf Edit\nproperties ...} from the right-click context menu.  Property values\ninclude:\n\n\\begin{description}\n\n\\item[wrapStiffness] Wrapping stiffness $K_w$ between knot points\n(default value 1). Since the wrapping behavior is determined by the\ndamping to stiffness {\\it ratio}, it is generally not necessary to\nchange this value.\n\n\\item[wrapDamping] Damping factor $D$ (default\nvalue 10). Increasing this value relative to $K_w$ results in wrap\npath motions that are smoother and less likely to penetrate obstacles,\nbut which are also less dynamically responsive. Applications generally\nwork with damping values between 10 and 100 (assuming $K_w = 1$).\n\n\\item[contactStiffness] Contact stiffness $K_c$ used to resolve obstacle\npenetration (default value 10). It is generally not necessary\nto change this value. Decreasing it will increase the distance that\nknots are permitted to penetrate obstacles, which {\\it may} result in\na slightly more stable contact behavior.\n\n\\item[maxWrapIterations] Maximum number of Newton iterations\n$N_\\text{max}$ per time step (default value 10). If the wrapping\nsimulation exhibits instability, particularly with regard to obstacle\ncontact, increasing the number of iterations (to say 100) may help.\n\n\\end{description}\n\nIn addition, {\\tt MultiPointSpring} and {\\tt MultiPointMuscle} also\nexport the following properties to control the rendering of knot and\nA/B points:\n\n\\begin{description}\n\n\\item[drawKnots] If true, renders the knot points in each wrappable segment.\nThis can be useful to visualize the knot density. Knots are rendered\nusing the style, size, and color given by the {\\sf pointStyle},\n{\\sf pointRadius}, {\\sf pointSize}, and {\\sf pointColor} values of the\nspring/muscle's render properties.\n\n\\item[drawABPoints] If true, renders the A/B points. These\nare the first and last points of contact that a wrap segment makes\nwith each wrappable, and correspond to the\npoints where the spring/muscle's tension acts on that wrappable\n(Section \\ref{multipointSpringIntro:sec} and\nFigure \\ref{multiPointObstacle:fig}).  A/B points are rendered using\nthe style and size given by the {\\sf pointStyle}, {\\sf pointRadius}\n($\\times 1.2$) and {\\sf pointSize} values of the spring/muscle's render\nproperties, and the color given by the {\\sf ABPointColor} property.\n\n\\end{description}\n", "meta": {"hexsha": "68c1508de8d74d09853c290b4c7556b91c31d31c", "size": 44623, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/modelguide/muscleWrapping.tex", "max_stars_repo_name": "aaltolab/artisynth_core", "max_stars_repo_head_hexsha": "ce01443e067f20a3f5874c05e9b97019ca7c7ca7", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/modelguide/muscleWrapping.tex", "max_issues_repo_name": "aaltolab/artisynth_core", "max_issues_repo_head_hexsha": "ce01443e067f20a3f5874c05e9b97019ca7c7ca7", "max_issues_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/modelguide/muscleWrapping.tex", "max_forks_repo_name": "aaltolab/artisynth_core", "max_forks_repo_head_hexsha": "ce01443e067f20a3f5874c05e9b97019ca7c7ca7", "max_forks_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.6198662846, "max_line_length": 97, "alphanum_fraction": 0.7756762208, "num_tokens": 11516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.331257107478906}}
{"text": "\\documentclass{article}\n\n\\usepackage{arxiv}\n\n\\usepackage[utf8]{inputenc} % allow utf-8 input\n\\usepackage[T1]{fontenc}    % use 8-bit T1 fonts\n\\usepackage{hyperref}       % hyperlinks\n\\usepackage{url}            % simple URL typesetting\n\\usepackage{booktabs}       % professional-quality tables\n\\usepackage{amsfonts}       % blackboard math symbols\n\\usepackage{nicefrac}       % compact symbols for 1/2, etc.\n\\usepackage{microtype}      % microtypography\n\\usepackage{lipsum}\t\t% Can be removed after putting your text content\n\\usepackage{amssymb,amsmath,amsthm}\n\\usepackage{listings}\n\\usepackage{graphicx}\n\\usepackage{subfig}\n\\usepackage{apacite}\n\\usepackage{algorithm}\n\\usepackage{algorithmicx}\n\\usepackage{algpseudocode}\n\\usepackage{kbordermatrix}% http://www.hss.caltech.edu/~kcb/TeX/kbordermatrix.sty\n\\usepackage{todonotes}\n\n\\newtheorem{theorem}{Theorem}\n\\DeclareMathOperator\\supp{supp}\n\n\\title{Sampling from the Bayesian poster of an agent-based model given partial observations}\n\n%\\date{September 9, 1985}\t% Here you can change the date presented in the paper title\n%\\date{} \t\t\t\t\t% Or removing it\n\n\\author{\n  Daniel Tang\\\\\n    Leeds Institute for Data Analytics, University of Leeds, UK\\thanks{This project has received funding from the European Research Council (ERC) under the European Union’s Horizon 2020 research and innovation programme (grant agreement No. 757455)}\\\\\n  \\texttt{D.Tang@leeds.ac.uk}\\\\\n  \\AND\n  Nick Malleson\\\\\n  School of Geography, University of Leeds, UK\\\\  \n  %% examples of more authors\n  %% \\AND\n  %% Coauthor \\\\\n  %% Affiliation \\\\\n  %% Address \\\\\n}\n\n\n\\begin{document}\n\\maketitle\n\n\\begin{abstract}\nThe discipline of data assimilation (DA), sometimes known as data fusion, addresses the problem of how to make use of noisy, imcomplete experimental observations to provide information about unobserved properties of a dynamical system. DA has developed rapidly in some areas of research, notably weather forecasting, but relatively little progress has been made in DA techniques applicable to agent based modelling. Agent Based Models (ABMs) consist of `agents' which often make discrete choices from a number of possible actions, meaning the space of model trajectories is not continuous and we cannot use techniques based on gradient ascent, such as 4D-VAR, that require the gradient of the posterior in this space. In addition, a set of observations will typically refute the vast majority of model trajectories, making it difficult to even identify trajectories that could have given rise to the observations, and so making it challenging to use algorithms that rely on perturbing the current solution such as non-gradient optimisation or most sampling algorithms.\n\nHere we present an algorithm that generates samples of the time evolution of an agent based model, given a set of noisy, incomplete experimental observations of the system. The algorithm approximates the set of possible trajectories as a linear program and uses an extension of the simplex algorithm to provide a proposal function for Markov-Chain-Monte-Carlo sampling.\n\nWe demonstrate the algorithm by performing data assimilation in an agent-based, spatial predator-prey model.\n\\end{abstract}\n\n% keywords can be removed\n\\keywords{Data assimilation, Bayesian inference, Agent based model, Integer linear programming, predator prey model}\n\n\\section{Introduction}\n\nAgent-based modelling (ABM) has become a popular tool for use in modelling systems that are driven by the behaviours and interactions of discrete, heterogeneous entities, such as human and animal systems.\nAlthough progress has been made towards the development and adaptation of techniques to conduct parameter optimisation~\\cite{thiele_facilitating_2014}, such methods are not able to dynamically optimise the model \\textit{state}. \nAgent-based models (ABMs) are typically optimised once, by repeatedly comparing their outputs under various parameter configurations to some real-world data, and then used to make predictions. \nHowever, in many circumstances, particularly when attempting to model complex systems, natural stochasticity causes the model to diverge from the real system, regardless of how well the parameters have been optimised.\nAlthough some studies have attempted to re-calibrate model parameters during runtime~\\cite{oloo_predicting_2018, oloo_adaptive_2017}, this does not prevent the model \\textit{state} from diverging.\nThe field of ABM has yet to develop methods that allow the model state to be updated dynamically in response to new data, which is a serious methodological drawback. \n\nThis paper presents a new method that will allow for \\textit{data assimilation} (DA) to be applied to ABMs in order to optimise the model state in response to new data that arise during runtime. The discipline of DA, sometimes known as data fusion, addresses the problem of how to make use of noisy, imcomplete experimental observations to provide information about the time evolution of unobserved properties of a dynamical system.\nIt is a technique that has developed rapidly in applications such as weather forecasting~\\cite{kalnay_atmospheric_2003} and the earth sciences more broadly~\\cite{reichle_data_2008}, but little progress has been made in developing techniques that are applicable when the dynamical system is an agent based model. DA methods typically rely on the differentiability of the model~\\cite{lewis_dynamic_2006}. As ABMs consist of `agents' that often make discrete choices from a number of possible actions, the the space of model trajectories is not continuous so techniques based on gradient ascent, such as 4D-VAR, that require the gradient of the posterior in this space, cannot be used. \nIn addition, a vast number of possible model trajectories will be refuted by the observations, making it challenging to use algorithms that rely on perturbing the current solution such as non-gradient optimisation or most sampling algorithms. For this reason, examples of data assimilation using well-known DA methods such as Particle Filters and variants of the Kalman Filter -- in applications such as crime~\\cite{lloyd_exploring_2016}, bus routes~\\cite{kieu_dealing_2020}, pedestrian dynamics~\\cite{wang_data_2015, ward_dynamic_2016, clay_realtime_2020, malleson_simulating_2020} and population movement~\\cite{lueck_who_2019} -- are necessarily limited to extremely small systems, quickly becoming intractable.\\todo{Reviewers may want a more comprehensive lit review}\n\nHere we present an algorithm that generates samples of the time evolution of an agent based model, given a set of noisy, incomplete experimental observations of the system. This allows for DA on an ABM by creating a posterior distribution within a reasonable amount of time. The algorithm approximates the set of possible trajectories as a linear program and uses an extension of the simplex algorithm to provide a proposal function for Markov-Chain-Monte-Carlo sampling. We demonstrate the algorithm by performing data assimilation in an agent-based, spatial predator-prey model.\n\n\\todo[inline]{NM: ``This paper has been structured as follows ... ''}\n\nOther work on sampling from discrete sets: Discrete hit-and-run (Baumert et.al. 2009) won't work because of the extreme sparsity of feasible points. Universal hashing (Meel et.al. 2016) doesn't seem to scale to the number of dimensions (100,000s) for this application. \n\n\\section{Formulation of the problem}\n%##########################################\n\nBroadly, this paper presents a new method that can be used to conduct data assimilation for agent-based models. The method provides a means of sampling possible ABM trajectories, confronting them with observations from the target system, and generating a posterior. This posterior provides the best estimate of the true system state. \n\n\\subsection{Agents, States and Actions}\n\nFormally, we define the problem as follows.\nSuppose we have a timestepping ABM where agents have a finite number of possible internal states and a finite number of ways of acting on their world. Given this, we can define an ABM as:\n\\begin{itemize}\n\t\\item An ordered list of agent actions $\\mathcal{A} =\\left< A_0 ... A_n \\right>$\n\t\n\t\\item An ordered list of agent states $\\mathcal{S} = \\left<S_0 ... S_m\\right>$\n\t\n\t\\item An \\textit{agent timestep}, $\\pi : \\mathbb{Z}\\times\\mathbb{Z}^{m+1}\\times\\mathbb{Z} \\to \\mathbb{R}$, which defines the probability that an agent will act in a particular way such that $\\pi(\\psi,\\Phi,a) $gives the probability that an agent in state $S_\\psi$, surrounded by agents, $\\Phi$, will perform action $A_a$ (where $\\Phi$ is a vector whose $i^{th}$ element is the number of agents in state $S_i$ at the start of the timestep).\n\t\n\t\\item An \\textit{action function}, $F: \\mathbb{Z} \\times \\mathbb{Z} \\to \\mathbb{Z}^{m+1}$, which defines the effect of an action on the world such that $F(\\psi, a)$ returns a vector, $\\Phi$, whose $i^{th}$ element gives the number of agents in state $S_i$ that result from an agent in state $S_\\psi$ performing act $A_a$ (including the final state of the acting agent).\n\\end{itemize}\n\n\\todo[inline]{Mention that the more traditional way of defining ABMs (e.g. using objects and step functions) can be easily mapped to this formulation}\n\nAs a simple illustration, consider a simple ``cat and mouse'' ABM, which consists of just two gridsquares, left and right, within which roam a cat and a mouse. Using the definitions above, the model can be formulated as follows: \n\n\\begin{description}\n\n\\item[Agent actions, $\\mathcal{A}$.] In any given timestep, agents can either move or stay still, so $\\mathcal{A} = \\left<\\textrm{move}, \\textrm{stay still}\\right> = \\left<0, 1\\right>$.\n\n\\item[Agent states, $\\mathcal{S}$.] The cat and mouse can exist on either of the two squares, so $\\mathcal{S} = \\left<\\textrm{left cat}, \\textrm{right cat}, \\textrm{left mouse}, \\textrm{right mouse} \\right> = \\left<0, 1, 2, 3 \\right>$. \n\n\\item[Agent timestep, $\\pi$.] As there are two possible actions ($\\mathcal{A}=\\left<0, 1\\right>$) then there are two variants to the agent timestep. With respect to the \\textit{move} action ($\\mathcal{A}=0$), a cat moves with probability $0.5$, irrespective of other agents, while a mouse will move if there are one or more cats on the same gridsquare, otherwise it will stay still:\n\\[\n\\begin{aligned}\n\\pi(\\psi, \\Phi, 0) &=   % MOVE equation\n\\begin{cases}\n0.5 & \\text{if } \\psi \\in \\left\\{0,1\\right\\}\\\\  % IF I'm a cat (0 and 1 are both cat) then prob move is 0.5%\n1 & \\text{ if } \\psi = 2, \\Phi_1 > 0 \\text{ or } \\psi=3, \\Phi_2 > 0\\\\ % mouse left & >0 cats in same square OR mouse right and >0 cats then move\n0 & \\text{ otherwise} %otherwise stay still\n\\end{cases}\n\\end{aligned}\n\\]\nWith respect to the \\textit{stay still} action  ($\\mathcal{A}=1$), the probability of the cat staying still remains at 0.5, where as the mouse remains still if there are no cats on the same grid square, otherwise it will move:\n\\[\n\\begin{aligned}\n\\pi(\\psi, \\Phi, 1) &= % STAY STILL equation\n\\begin{cases}\n0.5 & \\text{if } \\psi \\in \\left\\{0, 1\\right\\}\\\\  % IF I'm a cat (0 and 1 are both cat) then prob stay still is 0.5%\n1 & \\text{ if } \\psi = 2, \\Phi_1 = 0 \\text{ or } \\psi=3, \\Phi_2 = 0\\\\ % definitely stay still if mouse and no cats in same square\n0 & \\text{ otherwise}\n\\end{cases}\n\\end{aligned}\n\\]\n\n\\item[Action function, $F$.] Expresses the movement of the agents. For example, $F(\\psi=1, a=0)$ states that if there is an agent in state $\\psi=1$ (\\textit{right cat}) and it performs the action $a=0$ (\\textit{move)} then the result is one cat in state $\\psi=0$ (\\textit{left cat}):  $\\Phi=\\{1,0,0,0\\}$. The full range of possible inputs and outputs from the action function is:\n\\[\n\\begin{aligned}\nF(0, 0) &= \\{0,1,0,0\\}\\\\\nF(1, 0) &= \\{1,0,0,0\\}\\\\\nF(2, 0) &= \\{0,0,0,1\\}\\\\\nF(3, 0) &= \\{0,0,1,0\\}\\\\\nF(0, 1) &= \\{1,0,0,0\\}\\\\\nF(1, 1) &= \\{0,1,0,0\\}\\\\\nF(2, 1) &= \\{0,0,1,0\\}\\\\\nF(3, 1) &= \\{0,0,0,1\\}\\\\\n\\end{aligned}\n\\]\n\n\\end{description}\n\n\\subsection{Trajectories}\n\n\\begin{figure}\n\t\\centering\n\t\\resizebox{0.5\\textwidth}{!}{\n\t\t\\includegraphics[scale=0.5]{figs/catMouseSm}\n\t}\n\t\\caption{A simple cat and mouse model.\\label{fig:AB-MCMC-1}}\n\\end{figure}\n\n\nLet a model timestep consist of a matrix $E$ whose elements $e_{\\psi a}$ are the number of agents in state $\\psi$ that perform act $a$ in this timestep. For example, the timestep shown in Figure~\\ref{fig:AB-MCMC-1} for the cat and mouse example would be\n\\[\nE = \\kbordermatrix{\n\t& A_0 & A_1 \\\\\n\tS_0 & 0 & 0 \\\\\n\tS_1 & 1 & 0 \\\\\n\tS_2 & 0  & 1 \\\\\n\tS_3 & 0 & 0 \\\\\n}\n\\]\nwhere all elements are zero except those representing agent $S_1$ (\\textit{right cat}) performing action $A_0$ (\\textit{move}) and agent $S_2$ (\\textit{left mouse}) performing action $A_1$ (\\textit{stay still}).\n\nFinally, let a model trajectory, $T$, be an $(m\\times n\\times t)$ tensor consisting of $t$ model timesteps. We use the notation $T^t$ to denote the $t^{th}$ timestep matrix, $T^t_\\psi$ to denote the $\\psi^{th}$ row of the $t^{th}$ timestep matrix and $T^t_{\\psi a}$ to denote the $a^{th}$ element of the $\\psi^{th}$ row of the $t^{th}$ timestep. By convention, indices begin at 0. Note that this tensor will generally be very large for more realistic models, but also very sparse, so it can be dealt with computationally using a sparse representation.\n\nIt will occasionally be useful to refer to the set of all tensors of a given shape. For this we'll use $\\mathbb{R}$ adorned with the number of elements in each index position. For example, a trajectory representing $N$ timesteps of a model with $S$ agent states and $A$ actions must be a member of the set of tensors $\\mathbb{R}^N_{SA}$.\n\nA tensor must satisfy a number of constraints in order to be a valid trajectory of an ABM. Since the elements of a trajectory are counts of agents, they must be non-negative integers. We'll call this the \\textit{non-negative integer constraint} and define the set of all non-negative integer tensors\n\\begin{equation}\n\\mathcal{I}^N_{SA} = \\left\\{ T \\in \\mathbb{R^N_{SA}}: \\forall t,\\psi, a: T^t_{\\psi a} \\ge 0, T^t_{\\psi a} \\in \\mathbb{Z}\\right\\}\n\\label{nonNegativeInt}\n\\end{equation}\n\nThe \\textit{continuity constraint}\\footnote{The continuity constraint does not mean that agents cannot leave or enter the system, only that if they do then that change must be defined as part of an action.} requires that the number of agents in each state at the end of timestep $t-1$ must be the number of agents in each state at the beginning of timestep $t$. We define the set of continuous tensors:\n\\begin{equation}\n\\mathcal{C}^N_{SA}(F) = \\left\\{T\\in\\mathbb{R}^N_{SA}:  \\forall t \\in 1 ... N-1:\\forall \\phi: \\sum_{\\psi, a} F(\\psi, a)_\\phi T^{t-1}_{\\psi a} - \\sum_a T^t_{\\phi a} = 0\\right\\}\n\\label{continuous}\n\\end{equation}\n\nSo, the set of valid trajectories, $\\mathcal{T}^N_{SA}(F)$, is given by the set of tensors that satisfy \\eqref{nonNegativeInt} and \\eqref{continuous}.\n\\begin{equation}\n\\mathcal{T}^N_{SA}(F) = \\mathcal{I}^N_{SA} \\cap \\mathcal{C}^N_{SA}(F)\n\\label{SetOfTrajectories}\n\\end{equation}\n\n\n\\subsection{The posterior}\n\nIf we let $\\Psi^t$ be the vector whose $\\psi^{th}$ element is the number of agents in state $S_\\psi$ at the beginning of timestep $t$, then the prior probability of a trajectory is\n\\[\nP(T) =\n\\begin{cases}\nP\\left(\\Psi^0 = T^0 \\mathbf{1} \\right) \\prod_{\\psi, t} P\\left(T^t_{\\psi} \\mid \\Psi^t = T^t \\mathbf{1}\\right) & \\text{if } T \\in \\mathcal{T}^N_{SA}(F) \\\\\n0 & \\text{otherwise}\n\\end{cases}\n\\]\nwhere $P(\\Psi^0)$ is our prior belief about the model state at time $t=0$, and we use $\\mathbf{1}$ to denote a vector whose elements are all 1.\n\n\nThe probability that a single agent in a given state will perform an action, given the state of the other agents, $\\Psi^t$, is given by the agent timestep function, $\\pi(\\psi,\\Psi^t,a)$, so the joint probability that $\\Psi^t_\\psi$ agents will perform actions $T^t_{\\psi}$ in an environment of other agents $\\Psi^t$, is given by the multinomial distribution\n\\[\nP\\left(T^t_{\\psi} \\mid \\Psi^t \\right) = \\Psi^t_\\psi!\\prod_a \\frac{\\pi(\\psi,\\Psi^t,a)^{T^{t}_{\\psi a}}}{T^{t}_{\\psi a}!}.\n\\]\nSo the prior probability of a trajectory is\n\\[\nP(T) =\n\\begin{cases}\nP(\\Psi^0 = T^0\\mathbf{1})\n\\prod_{t, \\psi}\\left(T^t_{\\psi} \\cdot \\mathbf{1} \\right)!\n\\prod_a \\frac{\\pi(\\psi, T^{t}\\mathbf{1},a)^{T^{t}_{\\psi a}}}{T^{t}_{\\psi a}!} & \\text{if } T \\in \\mathcal{T}^N_{SA}(F) \\\\\n0 & \\text{otherwise}\\\\\n\\end{cases}\n\\]\n\nSuppose now we have a set of noisy, aggregate observations, $\\Omega$, that have a likelihood function $P(\\Omega|T)$. By Bayes' rule, we have\n\\[\nP(T|\\Omega) \\propto P\\left(\\Omega \\middle| T\\right)P(T)\n\\]\n\nWithout loss of generality, we take $\\Omega$ to consist of some number of observations that are independent of each other given the trajectory, so that the members $(\\omega,v)\\in \\Omega$ consist of a stochastic observation operator $\\omega$ and an observed value $v$ (which may be a vector). We write $P(\\omega(T)=v)$ to denote the probability of observation operator $\\omega$ making observation $v$ on trajectory $T$. So\n\\[\nP(\\Omega|T) = \\prod_{(\\omega,v) \\in \\Omega} P(\\omega(T)=v)\n\\]\n\nThe posterior can now be written as\n\\begin{equation}\nP(T|\\Omega) \\propto \n\\begin{cases}\nP(\\Psi^0 = T^0\\mathbf{1})\n\\prod_{(\\omega,v) \\in \\Omega} P\\left(\\omega(T)=v\\right)\n\\prod_{t, \\psi, a}\\left(T^t_{\\psi}\\cdot\\mathbf{1}\\right)!\n\\frac{\\pi(\\psi,T^t\\mathbf{1},a)^{T^{t}_{\\psi a}}}{T^t_{\\psi a}!} & \\text{if } T \\in \\mathcal{T}^N_{SA}(F) \\\\\n0 & \\text{otherwise}\\\\\n\\end{cases}\n\\label{posterior}\n\\end{equation}\n\nIn order to conduct data assimilation, we need to estimate the posterior, $P(T|\\Omega)$. To do this it is necessary to sample from this distribution. This is the problem that this paper attempts to solve.\nIn many practical applications, sampling is difficult because the posterior has zero probability for the vast majority of tensors (i.e. most tensors are not trajectories, contain an impossible action or are refuted by the observations). Even though we can generate trajectories that fit the prior by simply performing a forward execution of the model from an initial state drawn from the prior, if the observations refute the trajectory the probability falls to zero. \nWith even small numbers of observations, the probability of randomly choosing a trajectory that fits the observations becomes very small indeed. Therefore simple techniques such as rejection sampling, for example, are not practical. Techniques based on particle filtering may have more success but, for similar reasons, will likely soon reach a state containing a set of particles, none of which can be fit to the observations.\n\nIn this paper we'll show how the Metropolis-Hastings algorithm can be used to generate samples from \\eqref{posterior}. The challenge will be to create a proposal function which randomly generates a proposed next sample given the current one. For example, a common strategy with Metropolis-Hastings is to generate a new sample by perturbing one or more elements of the previous sample at random. However, if we do this with an ABM trajectory it's very unlikely that the perturbed tensor will be a trajectory that contains only possible actions and satisfies the observations. So, the proposed next sample would almost certainly be rejected and we'd probably end up stuck on the first sample until we grew old.\n\n\\section{Approximating the support of the posterior}\n%##########################################\n\nWe solve this problem by first approximating the support of the posterior, $\\supp(P(T^t_{\\psi a}|\\Omega))$ (i.e. the set of trajectories that have non-zero probability).\n\nFrom \\eqref{posterior}\n\\begin{equation}\n\\begin{aligned}\n\\supp (P( T |\\Omega)) = & \\mathcal{T}^N_{SA} \\cap \\\\ \n&\\supp(P(\\Psi^0 = T^0\\mathbf{1})) \\cap \\\\\n&\\bigcap_{(\\omega,v) \\in \\Omega}  \\supp\\left(P\\left(\\omega(T)=v\\right)\\right) \\cap \\\\\n&\\bigcap_{t, \\psi, a} \\left( \\supp\\left(\\pi(\\psi,T^t\\mathbf{1},a)\\right) \\cup \\left\\{T:T^t_{\\psi a} = 0\\right\\} \\right)\n\\end{aligned}\n\\label{support}\n\\end{equation}\ni.e. in order for $T$ to have non-zero posterior probability, it must be a trajectory of the ABM, it must have a start state that has non-zero prior probability, all the observation likelihoods must be non-zero and each element of $T$ must denote an agent action with non-zero probability.\n\n\n\\subsection{Convex $\\mathbb{Z}$-polyhedra and $\\mathbb{Z}$-distributions}\n%################################################################\n\\label{BPoly}\n\nLet a $\\mathbb{Z}$-polyhedron be a set of tensors with integer elements that can be described as a set of linear constraints on the elements: \n\\[\n\\mathcal{P^N_{SA}} = \\left\\{ T\\in\\mathbb{\\mathbb{Z}}^N_{SA} : L \\le \\sum_{t,\\psi,a} C^{\\psi a}_{t} T^t_{\\psi a} \\le U \\right\\}\n\\]\nwhere $L$,  $U$ and $C^{\\psi a}_t$ are vectors (this is similar to the $\\mathbb{Z}$-polyhedron described in \\cite{quinton1996manipulating}).\n\nFrom equation \\ref{SetOfTrajectories} we can see immediately that $\\mathcal{T}^N_{SA}$ is a  $\\mathbb{Z}$-polyhedron. The supports of the prior, $P(\\Psi^0)$, the observations, $P(\\omega(T)=v)$, and the agent actions, $\\pi(\\psi,T^t\\mathbf{1},a)$, can often be easily expressed as $\\mathbb{Z}$-polyhedra. If this is not the case, each of the probability distributions can be expressed as computer programs. Once in this form, abstract interpretation tools\\cite{cousot1977abstract} using the domain of convex polyhedra  \\cite{cousot1978automatic}\\cite{becchi2018efficient}\\cite{fukuda2020polyhedral} can be used to construct a convex polyhedron that contains the support (note that it's fine to overestimate the support, i.e. include points that aren't in the support, but not to exclude points that are in the support. Abstract interpretation tools\\cite{henry2012pagai}\\cite{GN2021} are perfectly suited to this purpose). In addition, if the number of agents is very much smaller than the number of agent states (which is often the case with agent based models) then we may be willing to make the assumption that at any timestep there is at most one agent performing a given action from a given start state (i.e. $\\forall \\psi, a, t: T^{\\psi a}_t \\in \\{0,1\\}$). Under this assumption, which we'll call the \\textit{Fermionic assumption} , the set of trajectories is a subset of the corners of the unit hypercube. Any such subset is a $\\mathbb{Z}$-polyhedron.\n\nUnder the assumption that all trajectories are Fermionic, we can rewrite \\eqref{support} in the form\n\\begin{equation}\n\\begin{aligned}\n\\supp(P( T |\\Omega)) \\subseteq \n& \\mathcal{T}^N_{SA} \\cap \\\\\n& \\mathcal{P}^N_{SA}(P(\\Psi^0 = T^0\\mathbf{1})) \\cap\\\\\n& \\bigcap_{(\\omega,v) \\in \\Omega}   \\mathcal{P}^N_{SA}\\left(P\\left(\\omega(T)=v\\right)\\right) \\cap \\\\\n& \\bigcap_{t,\\psi, a}\n\\left(\\mathcal{P}^N_{SA}\\left(\\pi(\\psi,T^t\\mathbf{1},a)\\right)\n\\cup\n\\left\\{T: T^t_{\\psi a} = 0\\right\\}\\right)\n\\\\\n\\end{aligned}\n\\label{polyhedralSupport}\n\\end{equation}\n\nThe intersection of two $\\mathcal{Z}$-polyhedra is easy to construct by just concatenating the constraints\n\\begin{multline}\n\\left\\{ T\\in\\mathbb{\\mathbb{Z}}^N_{SA} : L \\le \\sum_{t,\\psi,a} C^{\\psi a}_{t} T^t_{\\psi a} \\le U \\right\\}\n\\cap \\left\\{ T\\in\\mathbb{\\mathbb{Z}}^N_{SA} : L' \\le \\sum_{t,\\psi,a} D^{\\psi a}_{t} T^t_{\\psi a} \\le U' \\right\\} \\\\\n= \\left\\{ T\\in\\mathbb{\\mathbb{Z}}^N_{SA} : {L \\choose L'}  \\le \\sum_{t,\\psi,a} {C^{\\psi a}_t\\choose D^{\\psi a}_t} T^t_{\\psi a} \\le {U\\choose U'} \\right\\}\n\\end{multline}\nso the only difficulty is the union in the final term of \\eqref{polyhedralSupport}. To transform this into an intersection we introduce an auxiliary variable $I^t_{\\psi a}$ and use the identity\n\\begin{multline}\n\\left\\{ T\\in\\mathbb{Z}^N_{SA} : L \\le \\sum_{s,\\phi,b} C^{\\phi b}_{s} T^s_{\\phi b} \\le U \\right\\}\n\\cup\n\\left\\{T: T^t_{\\psi a} = 0\\right\\}\n=\\\\\n\\left\\{\nT\\in\\mathbb{Z}^N_{SA}, I^t_{\\psi a}\\in\\{0,1\\}:\\right.\\\\\n-\\infty \\le \\sum_{s,\\phi,b} C^{\\phi b}_{s} T^s_{\\phi b}\n+\n(\\overline{B}-U)I^{t}_{\\psi a}\n\\le \\overline{B},\\\\\n\\underline{B} \\le \\sum_{s,\\phi,b} C^{\\phi b}_{s} T^s_{\\phi b}\n+\n(\\underline{B}-L)I^{t}_{\\psi a} \\le \\infty,\\\\\n0 \\le mI^t_{\\psi a} - T^t_{\\psi a},\\\\\n\\left. I^t_{\\psi a} - T^t_{\\psi a} \\le 0\n\\right\\}\n\\label{implication}\n\\end{multline}\nwhere $m$ is the maximum value that any element of $T$ can take, the elements of $\\overline{B}\\in\\mathbb{R}_I$ are defined as\n\\[\n\\overline{B}_i = \\frac{m\\sum_{s,\\phi,b} \\left( C^{\\phi b}_{si} + \\left|C^{\\phi b}_{si}\\right|\\right)}{2}\n\\]\nand the elements of $\\underline{B}\\in\\mathbb{R}_I$ are defined as\n\\[\n\\underline{B}_i = \\frac{m\\sum_{s,\\phi,b} \\left(C^{\\phi b}_{si} - \\left|C^{\\phi b}_{si}\\right|\\right)}{2}\n\\]\n\nTo see why this identity holds, note first that the constraints on $I^t_{\\psi a}$ make it into an indicator variable that is 0 if $T^t_{\\psi a}=0$ or 1 otherwise. When $I^t_{\\psi a}=1$ the first set of constraints is equal to $\\sum_{s,\\phi,b} C^{\\phi b}_{s} T^s_{\\phi b} \\le U$ and the second is equal to $L \\le \\sum_{s,\\phi,b} C^{\\phi b}_{s} T^s_{\\phi b}$ so their intersection is $L \\le \\sum_{s,\\phi,b} C^{\\phi b}_{s} T^s_{\\phi b} \\le U$ as required, whereas when $I^t_{\\psi a}=0$ we have the constraints $\\underline{B} \\le \\sum_{s,\\phi,b} C^{\\phi b}_{s} T^s_{\\phi b} \\le \\overline{B}$. But $\\underline{B}$ and $\\overline{B}$ are lower and upper bounds on the value of $\\sum_{s,\\phi,b} C^{\\phi b}_{si} T^s_{\\phi b}$ so this is satisfied for all trajectories, as required.\n\nThere are two things worth noting here. Firstly if we make the Fermionic assumption then $I^t_{\\psi a} = T^t_{\\psi a}$ and the auxiliary indicator variable becomes unnecessary. Secondly, we must impose a finite value for $m$, the maximum value that elements of the trajectory can take. In practice, this is not a problem as we can give $m$ a value such that the probability of any trajectory of interest having any element larger than $m$ is vanishingly small.\n\nUsing this transformation the support of the posterior can be reduced to a $\\mathbb{Z}$-polyhedron\n\nThe idea of a $\\mathbb{Z}$-polyhedron as the support for a probability distribution naturally leads to the idea of a $\\mathbb{Z}$-distribution which is a discrete probability distribution defined over the members of a $\\mathbb{Z}$-polyhedron. From the above, it can be seen that the posterior distribution of an ABM trajectory is a $\\mathbb{Z}$-distribution.\n\nAs an illustration, consider a two-timestep trajectory of the cat and mouse model. Suppose we flip a fair coin to decide whether each agent state is occupied or empty at $t=0$ and that we observe a cat in the left grid-square at time $t=1$. Our aim is to construct a $\\mathbb{Z}$-polyhedron, $\\mathcal{P}^2_{4\\,2}(P(T|\\Omega))$, that describes the support of the posterior.\n\nWorking through \\eqref{polyhedralSupport} term by term, the $\\mathcal{T}^2_{4\\,2}$ term is just the continuity constraints in \\eqref{continuous}, which are already in linear form so we're done. The second term is the support of the prior. This constrains each agent state at $t=0$ to be at most 1, which can be expressed as\n\\[\n\\bigcap_\\psi \\left\\{T:T^0_{\\psi 0} + T^0_{\\psi 1} \\le 1\\right\\}\n\\]\n\nThe third term is the support of the observation. Since we observe a cat in the left grid-square at time $t=1$ we need to add the constraint\n\\[\nT^1_{0 0} + T^1_{0 1} = 1\n\\]\nThe final term guards against impossible actions. The only impossible actions are a mouse staying put when there is a cat on the same gridsquare or moving when there are no cats, which translates to the four cases\n\\begin{equation}\n\\begin{aligned}\n\\supp(\\pi(2,T^t\\mathbf{1},0)) &= \\left\\{ T: -T^t_{0 0} - T^t_{0 1} \\le -1 \\right\\}\\\\\n\\supp(\\pi(3,T^t\\mathbf{1},0)) &= \\left\\{ T: -T^t_{1 0} - T^t_{1 1} \\le -1 \\right\\}\\\\\n\\supp(\\pi(2,T^t\\mathbf{1},1)) &= \\left\\{ T: T^t_{0 0} + T^t_{0 1} \\le 0 \\right\\}\\\\\n\\supp(\\pi(3,T^t\\mathbf{1},1)) &= \\left\\{ T: T^t_{1 0} + T^t_{1 1} \\le 0 \\right\\}\n\\end{aligned}\n\\label{actionConstraints}\n\\end{equation}\nIf, for simplicity, we make the Fermionic assumption by adding the constraints\n\\[\n\\forall t,\\psi,a: T^t_{\\psi a} \\le 1\n\\]\nthen using the identity in \\eqref{implication} to take the union of each constraint in \\eqref{actionConstraints} with $\\left\\{T: T^t_{\\psi a} = 0\\right\\}$ gives the four constraints\n\\[\n\\begin{aligned}\n-T^t_{0 0} - T^t_{0 1} + T^t_{2 0} & \\le 0\\\\\n-T^t_{1 0} - T^t_{1 1} + T^t_{3 0} & \\le 0\\\\\nT^t_{0 0} + T^t_{0 1} + 2T^t_{2 1} & \\le 2 \\\\\nT^t_{1 0} + T^t_{1 1} + 2T^t_{3 1} & \\le 2\n\\end{aligned}\n\\]\nfor each timestep $t=0$ and $t=1$.\n\nTaken together, these constraints define a $\\mathcal{B}$-polyhedron that is the set of Fermionic trajectories for the cat and mouse ABM, and when combined with \\eqref{posterior} defines $P(T|\\Omega)$ as a $\\mathcal{B}-distribution$.\n\n\\section{Transforming between representations of a $\\mathbb{Z}$-polyhedron}\n%#####################################################\n\n\\todo[inline]{Brief explanation of why representing the $\\mathcal{B}$-polyhedron, and transforming between representations, is needed}\n\nNow that we can express the support of the posterior as a $\\mathcal{B}$-polyhedron in the form\n\\begin{equation}\n\\supp(P(T|\\Omega) \\subseteq \\left\\{T \\in \\mathbb{Z}^N_{SA}: L \\le \\sum_{t,\\psi,a} C^{\\psi a}_t T^t_{\\psi a} \\le U \\right\\}\n\\label{bPolySupport}\n\\end{equation}\nwe describe some different ways of representing the same $\\mathcal{B}$-polyhedron and methods of transforming from one representation to another. This will be useful in the development that follows.\n\n\\subsection{The standard form of a $\\mathbb{Z}$-polyhedron}\n\nSince there are many ways of representing a polyhedron, it will be useful to define a standard form when representing $\\mathbb{Z}$-polyhedra. We'll use the form\n\\begin{equation}\n\\mathcal{P}(Q,N,b,L,U) = \\left\\{X \\in \\mathbb{Z}^K: X = Q{X_B\\choose X_N}, X_B = b - NX_N, L \\le {X_B\\choose X_N} \\le U, X_B\\in\\mathbb{Z}^I, X_N \\in \\mathbb{Z}^J \\right\\}\n\\label{standardpolyhedron}\n\\end{equation}\nwhere $Q$ is a $K\\times (I+J)$ matrix that selects $J \\le K \\le I+J$ elements from $(X_B|X_N)^T$ (i.e. each column of $Q$ has at most one element equal to 1, each row has exactly one element equal to 1 and all other elements are 0). We'll call the elements of $X_B$ ``basic-variables'' and the elements of $X_N$ ``non-basic variables''\\footnote{The introduction of the requirement that $X_B \\in \\mathbb{Z}$ does not reduce expressivity as long as the elements of $N$ and $b$ can be expressed as rational numbers. In this case they can be converted to integers by multiplying each row by the product of the denominators on that row and dividing by the greatest common divisor. Once $N$ and $b$ are integer then $X_B$ is guaranteed to be integer for any $X_N\\in\\{0,1\\}^J$.}.\n\nEquation \\eqref{bPolySupport} can easily be expressed in the form \\eqref{standardpolyhedron} by ``flattening'' the trajectory, $T$, into a $J$-dimensional vector (without changing the values of the elements) using a tensor $R\\in\\mathbb{R}^{SA}_{NJ}$ where $J=NSA$ (i.e. for every $(t, \\psi, a)$ there is exactly one $j$ such that $R^{\\psi a}_{t j} = 1$ and for every $j$ there is exactly one $(t,\\psi,a)$ such that $R^{\\psi a}_{t j} = 1$ and all other elements are zero) so that\n\\[\nX_N = \\sum_{t,\\psi,a}R^{\\psi a}_t T^t_{\\psi a}\n\\]\nand letting $N$ be the $I\\times J$ matrix\n\\[\nN = \\sum_{t,\\psi,a} C^{\\psi a}_t R^{\\psi a}_t\n\\]\nand finally letting Q be the matrix such that $X_N = Q(X_B|X_N)$ and $b = \\mathbf{0}$. The constraint $X_B\\in\\mathbb{I}^I$ is satisfied since all the elements of $N$ are integers in our case.\n\n\\subsection{The pivot transformation}\n\nThe introduction of the matrix $Q$ in \\eqref{standardpolyhedron} allows us to transform the representation without changing the $\\mathbb{Z}$-polyhedron that is represented. We now describe the ``pivot transformation'' which will be a central operation in the sampling algorithm, and should look familiar to anyone acquainted with the simplex algorithm (see e.g. \\cite{vanderbei2015linear}).\n\nWe begin by expressing the linear constraint in the form\n\\[\n(I|N){X_B \\choose X_N} = b\n\\]\nwhere $I$ is the identity matrix.\n\nIf we let $S_{ij}$ be the permutation matrix such that\n\\[\n{X'_B\\choose X'_N} = S_{ij}{X_B\\choose X_N}\n\\]\nhas the effect of swapping the $i^{th}$ element of $X_B$ with the $j^{th}$ element of $X_N$ then we have\n\\[\n(I|N)S^{-1}_{ij}{X'_B \\choose X'_N} = b\n\\]\n(note that $S^{-1}_{ij} = S_{ij}$).\n\nIf we now pre-multiply this with the matrix \n\\[\nB_{ij}^{-1} =  \n\\begin{pmatrix}\n1 &  & -\\frac{N_{0j}}{N_{ij}} & & \\\\\n  & \\ddots & \\vdots & &\\\\\n & & \\frac{1}{N_{ij}} & &\\\\\n  & & \\vdots & \\ddots &\\\\\n  & & -\\frac{N_{nj}}{N_{ij}} & &1\\\\\n\\end{pmatrix}\n\\]\nit can be shown \\cite{maros2002computational} that\n\\begin{equation}\nB_{ij}^{-1}(I|N)S^{-1}_{ij} = (B_{ij}^{-1}|B_{ij}^{-1}N)S^{-1}_{ij} = (I|N')\n\\label{Ntransform}\n\\end{equation}\nand so\n\\begin{equation}\nB_{ij}^{-1}(I|N)S^{-1}_{ij}{X'_B \\choose X'_N} = B_{ij}^{-1}b  = (I|N'){X'_B \\choose X'_N} = b'\n\\end{equation}\nNow, if we choose an $i$ and $j$ such that $N_{ij} = \\pm 1$, then all elements of $B^{-1}_{ij}$ are integer and so all elements of $N'$ are also integer, as are the elements of $b'$. This ensures that if $X_N\\in\\mathbb{Z}^J$ then $X_B\\in\\mathbb{Z}^I$ and $X\\in\\mathbb{Z}^K$ as required.\n\nSo if we let\n\\[\nQ' = QS^{-1}_{ij}\n\\]\nwe can express the original $\\mathbb{Z}$-polyhedron in the equivalent form\n\\begin{equation}\n\\mathcal{P} = \\left\\{X\\in\\mathbb{Z}^K: X = Q'{X'_B\\choose X'_N}, X'_B = b'-N'X'_N, S_{ij}L \\le {X'_B \\choose X'_N} \\le S_{ij}U, X'_B \\in \\mathbb{Z}^I, X'_N \\in \\mathbb{Z}^J \\right\\}\n\\end{equation}\n\nIt is easy to see that this transformation defines an equivalence set so that, given a reference representation of a $\\mathbb{Z}$-polyhedron, $\\mathbb{Z}(Q,N,b,L,U)$, we can define the set of all equivalent ``pivot states'' $\\mathcal{S}(Q,N,b,L,U)$.\n\n\\subsection{Removal of fixed variables}\n\nIf we use the method described in section \\eqref{BPoly} to create a $\\mathbb{Z}$-polyhedron of the support then each continuity constraint (and possibly some of the observation constraints) will result in elements of $X_B$ that have fixed values (i.e. $L_i = U_i$). Removing these will reduce the dimensionality of the problem and so make valid solutions easier to find.\n\nSuppose the $i^{th}$ element of $X_B$ is fixed. If there exists some $j:N_{ij} = \\pm 1$ we can perform a pivot on $(i,j)$, to swap the fixed variable with the $j^{th}$ element of $X_N$ so that the fixed variable ends up in $X_N$. The fixed variable can be removed from $X_N$ by adding the $j^{th}$ column of $N$ times the variable's fixed value to b.\n\n\\section{Sampling from a $\\mathbb{Z}$-distribution}\n%#################################################\n\nArmed with the ability to express $P(T|\\Omega)$ as a $\\mathbb{Z}$-distribution and some tools to manipulate representations of $\\mathbb{Z}$-polyhedra, we can now go about defining a Markov process which will allow us to sample from a $\\mathbb{Z}$-distribution.\n\nTo do this we need to define\n\\begin{itemize}\n\\item a set of Markov states, $\\mathcal{M}$\n\n\\item a probability measure $P: \\mathcal{M} \\to \\mathbb{R}$ which gives the probability of each Markov state (this need not be normalised, though, as we'll only ever be interested in probability ratios)\n\n\\item a stochastic proposal function $f:\\mathcal{M} \\to \\mathcal{M}$ from which we can generate transitions to a new Markov state given the current Markov state\n\n\\item a mapping $E:\\mathcal{M} \\to \\mathbb{R}^T_{SA}$ which maps Markov states to trajectories so we can recover the sample.\n\\end{itemize}\n\nIn order to be useable in the Metropolis-Hastings algorithm, the proposal function, $f$, must have the following properties:\n\\begin{itemize}\n\t\\item For any two Markov states there should exist a set of transitions with non-zero probability which forms a path between those states.\n\t\n\t\\item For any transition from state $S_a \\to S_b$ with non-zero probability, the probability of the reverse transition from $S_b \\to S_a$ should also be non-zero. This allows us to attain detailed balance in the Metropolis Hastings algorithm. The average ratio of forward and backward probabilities times the ratio of start and end state probabilities should be close to 1 to ensure that a reasonable proportion of proposals are accepted.\n\t\n\t\\item Given a current Markov state, there should be computationally efficient ways of generating a proposal and calculating the ratio the probability of that transition and the reverse transition. \n\\end{itemize}\n\n\n\\subsection{The Markov states}\n%#############################################\n\nGiven a $\\mathbb{Z}$-polyhedron, we define a Markov state to be a pair $(X,S)$ where $X$ is a member of the $\\mathbb{Z}$-polyhedron and $S$ is a pivot state that defines a standard form representation of that polyhedron.\n\n\\subsection{The probability of a Markov state}\n\nNotice that for a given feasible solution, $X$, there are many Markov states, one for each possible pivot state. However, since the number of pivot states is the same for all feasible states we can assign to each feasible Markov state a probability $\\frac{P(X)}{N}$, where $P(X)$ is the probability of solution $X$ and $N$ is the number of valid pivot states. So, the probability of being in a Markov state associated with solution $X$ (summed over all pivot states) is $P(X)$. In the Metropolis-Hastings algorithm we only ever need to calculate probability ratios so, since $N$ is independent of $X$, we never need to calculate the value of $N$\\footnote{which is handy because it would be very difficult to calculate}.\n\n\\subsection{The transitions between Markov states}\n\n\\subsubsection{Bounds swaps}\nGiven the $X_N$ of a Markov state, a simple transition between Markov states is to swap the $i^{th}$ element of $X_N$ to it's other value while keeping the representation fixed. We'll call this a bound swap. If we're lucky the bound swap will not push $X_B$ outside its bounds and we'll have found another feasible Markov state. However, not all bound swaps are feasible in this way, and worse, there is no guarantee that given two feasible Markov states with the same representation there exists a sequence of feasible bound swaps that forms a path from one to the other.\n\n\\subsubsection{Pivot transitions}\nAnother simple transition between Markov states is to apply the pivot transition $S_{ij}$ to the representation for some valid $i$ and $j$. Since the variable that moves from $X_B$ to $X_N$ must end up having a value of either 0 or 1, we also specify which state this variable should end up in after the pivot. So, a pivot transition is fully defined by a triplet $(i,j,b)$.\n\n\\subsubsection{Infeasibility, infeasibility objective and potential energy}\n\nUnfortunately, if we only allow bound swaps and pivot transitions between feasible states there is no guarantee that there is a path between any two feasible states (note that we can't pivot on the non-binary basic variables or on elements of $N$ that don't have an absolute value of 1, so we can't guarantee that all vertices of the polyhedron are reachable and so can't rely on the proof that the polyhedron is connected).\n\nIn order to deal with this, we relax the bounds on the basic variables, $L \\le X_B \\le U$, and include Markov states where some elements of $X_B$ go outside their bounds. This ensures a path between any two feasible states (for example, by just performing bound swaps on the elements of $X_N$) without affecting the definition of bound swaps and pivot transitions.\n\nWith this modification the sampling algorithm will sometimes return infeasible samples which don't represent valid posterior ABM trajectories. However, if we just throw these away the remaining feasible samples will have the correct distribution. So, our aim will be to ensure that the infeasible/feasible sample ratio is small enough not to excessively slow down the sampling process while being large enough to ensure proper mixing in the Markov process.\n\n\\subsection{Choosing a transition}\n\nNow that we've defined the Markov states and the transitions between them, we next provide an algorithm to choose a proposal transition given the current Markov state. The algorithm should be able to draw a proposal from the transition-distribution and work out the ratio of probabilities of choosing a transition and its reverse transition.\n\nThe challenge here is to ensure that, during the sampling process, feasible states sometimes transition to infeasible states (in order to ensure good mixing) while ensuring that, once in an infeasible state, the sampling process quickly moves back into a (probably different) feasible state to create the next feasible sample.\n\nIn order to do this we take as our inspiration the algorithm described in \\cite{maros1986general}. This algorithm is intended to be used as a ``phase I'' of the simplex algorithm (see e.g. \\cite{vanderbei2015linear}) where the aim is just to find a feasible state as efficiently as possible rather than to create a Markov process. Here we present a Markov process that has a high probability of making the same transition as Maros' algorithm. Given this, we should expect the Markov process to quickly move into a feasible state.\n\n\\subsubsection{Choosing a non-basic variable: Infeasibility and potential energy}\n\nThe first step towards generating a proposal transition is to choose a non-basic variable to modify. To understand how this is done we'll first introduce a few concepts.\n\nGiven a Markov state, $\\mu$, let the infeasibility of the $i^{th}$ basic variable, $\\iota^\\mu_i$, be defined to be equal to 0 if the variable is within its bounds or equal to the distance to the nearest bound otherwise\n\\[\n\\iota^\\mu_i =\n\\begin{cases}\nL_i-X_{Bi} & \\text{if }X_{Bi}<L_i\\\\\nX_{Bi}-U_i & \\text{if }X_{Bi}>U_i\\\\\n0 & \\text{otherwise}\n\\end{cases}\n\\]\nand let the total infeasibility be the sum of infeasibilities of all basic variables\n\\[\n\\iota^\\mu = \\sum_i \\iota^\\mu_i\n\\]\nNote that the total infeasibility is piecewise linear, convex and all feasible points lie at the minimum. So, the problem is one of convex optimisation, complicated by the fact that we're only interested in integer feasible solutions. Given this,  a sensible strategy would be to somehow move down the gradient of $\\iota$ towards optimal values.\n\nThe gradient of $\\iota^\\mu$ at any point is given by\n\\[\n\\frac{d\\iota^\\mu}{dX_{Bi}} = \n\\begin{cases}\n-1 & \\text{if }X_{Bi}<L_i\\\\\n1 & \\text{if }X_{Bi}>U_i\\\\\n0 & \\text{otherwise}\n\\end{cases}\n\\]\n\nSince $X_B = b - NX_N$, the gradient of $\\iota^\\mu$ with respect to $X_N$, which we'll call $D^\\mu$, is given by\n\\[\nD^\\mu = \\frac{d\\iota^\\mu}{dX_N} = \\frac{d\\iota^\\mu}{dX_B}\\frac{dX_B}{dX_N} = - \\frac{d\\iota^\\mu}{dX_B}N\n\\]\n\nSince the total infeasibility is convex, if $D^\\mu_j$ is non zero we can tell which direction the $j^{th}$ non-basic variable, $X_{Nj}$, needs to be perturbed in order to potentially reduce infeasibility (or more precisely, which direction will definitely increase infeasibility). So, variables for which a bound-swap would move down the gradient $D^\\mu$ are good potential candidates for perturbation compared to those that don't.\n\nGiven this, we define the potential energy of the $j^{th}$ non-basic variable to be equal to 1 if a perturbation to $X_{Nj}$ is (potentially) able to move down the gradient, and 0 otherwise.\n\nIn order to encourage the selection of columns with positive potential, the $j^{th}$ non-basic variable is chosen with probability proportional to the exponential of its potential energy times some constant $k_c$\n\\begin{equation}\nP(j|\\mu) = \\frac{e^{k_cE^\\mu_j}}{\\sum_l e^{k_cE^\\mu_l}}\n\\label{columnChoice}\n\\end{equation}\n\n\\subsubsection{Choosing a column perturbation and pivot row}\n\nOnce a non-basic variable, $X_{Nj}$, is chosen for the transition, we can choose to perform a bound-swap on $X_{Nj}$ or perform a pivot transition on the $j^{th}$ column and any row that satisfies $|N_{ij}|=1$. If a pivot is chosen, the value of the new non-basic variable needs to be chosen to be either 0 or 1. An efficient algorithm to calculate the infeasibility resulting from each of these transitions is described in \\cite[Chapter~9]{maros2002computational}. For reasons that will become clear later, we also include the ``null transition'' which is a loop back to the same Markov state.\n\nLet $\\alpha^\\mu_j$ be the set of destination states reachable through transitions on $X_{Nj}$. In order to encourage transitions to lower infeasibility, while maintaining the possibility of reverse transitions to allow detailed balance, a transition, $\\mu\\to\\mu'$, is chosen with a probability proportional to the exponential of $-k_r\\iota^{\\mu'}$ for some constant $k_r$. i.e.\n\\begin{equation}\nP(\\mu'|j,\\mu) = \n\\frac{e^{-k_r\\iota^{\\mu'}}e^{k_cE^{\\mu'}_j} }\n\t{\\sum_{\\rho \\in \\alpha^\\mu_j}  e^{-k_r\\iota^\\rho}}\n\\label{pTransitionGivenJ}\n\\end{equation}\n\n\\subsubsection{Proposal function summary}\n\nGiven a transition from state $\\mu$ to state $\\mu' \\ne \\mu$ there is a unique non-basic variable $X_{Nj}$ that was involved in the transition \\footnote{if $N$ is unchanged then the transition was a bound swap on the only non-basic that has changed, if $N$ changes to $N'$ then it was a pivot transition on the only $j$ that satisfies equation \\eqref{Ntransform}} we'll use the notation $j^{\\mu\\to\\mu'}$ to denote the index of this variable.\n\nStarting from state $\\mu$, the probability of proposing a transition to $\\mu'$ is the probability that we choose the non-basic variable, $X_{Nj^{\\mu\\to\\mu'}}$ then choose the state $\\mu'$ from $\\alpha^\\mu_{j^{\\mu\\to\\mu'}}$, so from \\eqref{columnChoice} and \\eqref{pTransitionGivenJ}\n\\[\nP(\\mu \\rightarrow \\mu') \n= \nP(\\mu'|j^{\\mu\\to\\mu'},\\mu)P(j^{\\mu\\to\\mu'}|\\mu) \n=\n\\frac{e^{-k_r \\iota^{\\mu'}} e^{k_cE^{\\mu'}_{j^{\\mu'\\to\\mu}}}}\n\t{\\sum_{\\rho \\in \\alpha^\\mu_{j^{\\mu\\to\\mu'}}}e^{-k_r\\iota^\\rho}}\n\\frac{e^{k_c E^\\mu_{j^{\\mu\\to\\mu'}}}}\n\t{\\sum_l e^{k_c E^\\mu_l}}\n\\]\nSo, in the Metropolis-Hastings algorithm, the probability that a proposed transition, $\\mu\\to\\mu'$, is accepted is given by\n\\[\n\\frac{P(\\mu')P(\\mu'\\to\\mu)}{P(\\mu)P(\\mu\\to\\mu')} \n=\n\\frac{P(\\mu')}\n\t{P(\\mu)}\n\\frac{e^{-k_r \\iota^{\\mu}}e^{k_cE^{\\mu}_{j^{\\mu\\to\\mu'}}}}\n\t{\\sum_{\\rho \\in \\alpha^{\\mu'}_{j^{\\mu'\\to\\mu}}}e^{-k_r\\iota^\\rho}}\n\\frac{\\sum_{\\rho \\in \\alpha^{\\mu}_{j^{\\mu\\to\\mu'}}}e^{-k_r\\iota^\\rho}}\n\t{e^{-k_r \\iota^{\\mu'}}e^{k_cE^{\\mu'}_{j^{\\mu'\\to\\mu}}}}\n\\frac{e^{k_c E^{\\mu'}_{j^{\\mu'\\to\\mu}}}}\n\t{\\sum_l e^{k_c E^{\\mu'}_l}}\n\\frac{\\sum_l e^{k_c E^\\mu_l}}\n\t{e^{k_c E^\\mu_{j^{\\mu\\to\\mu'}}}}\n\\]\nHowever thanks to the fact that we included the null transition,  $\\alpha^{\\mu'}_{j^{\\mu\\to\\mu'}} = \\alpha^\\mu_{j^{\\mu'\\to\\mu}}$\\footnote{since $\\alpha^\\mu_{j^{\\mu\\to\\mu'}}$ describes the set of states that lie on the straight line that passes through $\\mu$ and $\\mu'$} the two sums over $\\alpha$ cancel, leaving\n\\begin{equation}\n\\frac{P(\\mu')P(\\mu'\\to\\mu)}\n\t{P(\\mu)P(\\mu\\to\\mu')} \n=\n\\frac{P(\\mu')}\n\t{P(\\mu)}\n\\frac{e^{-k_r \\iota^{\\mu}}}\n\t{e^{-k_r \\iota^{\\mu'}}}\n\\frac{\\sum_l e^{k_c E^\\mu_l}}\n\t{\\sum_l e^{k_c E^{\\mu'}_l}}\n\\label{acceptance1}\n\\end{equation}\n\nHowever, since infeasible states are thrown away in the final algorithm, we are free to assign them any probability we wish. This gives us some freedom to ensure that the algorithm spends an appropriate time in infeasible states and allows us to engineer an acceptance probability that is convenient to calculate. If we let\n\\begin{equation}\nP(\\mu) = P_e(T_\\mu|\\Omega)e^{-k_r \\iota^{\\mu}} \\frac{1}{n}  \\sum_l e^{k_c E^\\mu_l}\n\\label{penalty}\n\\end{equation}\nwhere $T_\\mu$ is the trajectory associated with Markov state $\\mu$ and $P_e(T_\\mu|\\Omega)$ is an ``extended posterior'', which for feasible states is just the posterior given by equation \\eqref{posterior}, while for infeasible states is calculated in the same way but the requirement that the trajectory belongs to $\\mathcal{T}^N_{SA}(F)$ is dropped and if any of the individual probabilities is zero it is replaced by its expectation over all trajectories (with some convenient prior over trajectories, we used a uniform distribution). Notice that for feasible states $P(\\mu) = P(T_\\mu|\\Omega)$ so if we apply this definition to all Markov states the feasible samples will be samples from the desired posterior.\n\nInserting \\eqref{penalty} into \\eqref{acceptance2} gives the final form for the acceptance\n\\begin{equation}\n\\frac{P(\\mu')P(\\mu'\\to\\mu)}{P(\\mu)P(\\mu\\to\\mu')} \n=\n\\frac{P_e(T_{\\mu'}|\\Omega)}{P_e(T_\\mu|\\Omega)}\n\\end{equation}\n\nNotice that states with lower infeasibility and lower potential energy have higher probability, so transitions that immediately reduce infeasibility are encouraged, but so are pivots that replace high potential energy variables with low potential variables. This has the consequence that if a high potential, non-basic variable is chosen but it can't immediately reduce infeasibility, it is more likely to be made basic where it is free to change its value in subsequent transitions. This helps the process find a basis where infeasibility-reducing transitions exist.\n\n\\subsubsection{Choosing temperature}\nThe exponential term $e^{\\frac{-E^\\mu}{T}}$ in equation \\eqref{penalty} is a Boltzmann distribution so $T$ can be thought of as a ``temperature'' and the sampling process will act as a thermodynamic system in equilibrium (with the posterior $P_e(T_\\mu|\\Omega)$ acting as an additional potential energy).  It has been shown that thermodynamic systems of this type are able to solve large integer optimisation problems \\cite{kirkpatrick1983optimization}. In our case, we don't need to change the temperature during the sampling process, but we do need to choose a value of $T$ initially. Higher temperatures will increase mixing in the Markov chain, but will also increase the proportion of time spent in infeasible states so we need to find a temperature that is high enough to ensure good mixing but low enough to ensure a reasonable proportion of samples are feasible.\n\n[TODO: Effective procedure for choosing $T$ and rationale. Choose start and target states at random and make linear probability with target state as maximum, then tune T to minimum samples to first hitting target. Repeat.\n Proportion of infeasible samples against proportion of feasible->infeasible samples. Average infeasible chain length proportion of infeasible samples/proportion of feasible->infeasible transitions.]\n \n If we first sample uniformly from the set of all states, we can get an idea of the number of states at each energy level...or, during burn-in we reduce temperature until we hit the desired proportion of (increase temp while feasible, reduce while infeasible, gradually reducing the size of the step).\n \n The ratio of $\\kappa_r$ and $\\kappa_c$: If $\\kappa_c$ is too low, we will tend to have long infeasible runs as high potential columns will not be pivoted-in, if it is too high, then many potential transitions into infeasibility will be rejected due to the increase in potential energy. If $\\kappa_r$ is to high (absolute value) then transitions into infeasibility will not be proposed often enough, if too low then potential transitions back into feasibility may be ignored even when available. The ratio is the ratio of the energy in an infeasible variable and a high-potential column....how important is reducing infeasibility against reducing potential energy?...\n\n\\section{Results}\n\n\\section{Further work}\n\\subsection{Abstract interpretation using convex polyhedra}\n\nIn many cases a $\\mathcal{B}$-polyhedron of the set of Fermionic trajectories in the support of the prior, observations and timestep of an agent can easily be constructed by hand in the form of a set of linear inequalities. In some cases, however, it may be less obvious how to construct this. In this case the linear inequalities can be constructed automatically from a computer program that calculates the function whose support we're trying to find.\n\n\n\n\n\nThe first two terms in equation \\eqref{support} consists of the supports of computer programs whose inputs are ABM trajectories and whose outputs are given, i.e. the set of trajectories that, when passed to a computer program, would produce a given output.\n\nCalculating the support of a computer program for a given output is, in full generality, NP-complete\\footnote{Consider, for example, a program that accepts an assignment of variables to truth values, and returns true if that assignment satisfies a Boolean formula. Deciding whether the support of this program, given that it returns true, is empty or not is equivalent to solving the Boolean satisfiability problem, which is known to be NP-complete\\cite{cook1971complexity}} but it is possible to use a technique known as \\textit{abstract interpretation}\\cite{cousot1977abstract} to efficiently calculate a superset of the support. So, given a computer program $\\rho$, we can calculate a set $\\mathcal{P}(\\rho, v)$ such that\n\\[\n\\supp(P(\\rho(.)=y)) \\subset \\mathcal{P}(\\rho, v)\n\\]\nTools to perform abstract interpretation already exist (e.g. PAGAI\\cite{henry2012pagai}) and are used widely in applications such as the verification of safety critical systems\\cite{blanchet2003static} and in practice $\\mathcal{P}(\\rho, v)$ is often reasonably tight (i.e. most members of $\\mathcal{P}(\\rho, v)$ are in $\\supp(P(\\rho(.)=y))$). For our application we choose to express $\\mathcal{P}(\\rho, v)$ in terms of a set of linear inequalities on $\\rho$'s inputs, this corresponds to the abstract domain of convex polyhedra\\cite{cousot1978automatic}\\cite{becchi2018efficient}. Calls to the random number generator can be dealt with in the abstract domain by generating a new variable, $r$, that satisfies $0 \\le r < 1$ for each call to \\texttt{Random()}. These can either be left in as ``auxiliary'' variables in the same way as slack variables, or removed as soon as the variable goes out of scope by finding the convex hull of the projection into a lower dimensional space (this can be done using the double description method\\cite{motzkin1953double}).\n\n\nConstraining our proposal function to members of the superset in equation \\eqref{linearSupport} instead of the true support won't affect the stationary distribution of the Markov Chain. If the proposal function happens to return a trajectory that isn't in $\\supp(P(\\rho(.)=y))$ then it will just be rejected. This is fine as long as we generate acceptable proposals at a reasonable rate.\n\n\\section{Conclusion}\n\n\\section{Notes}\n\n\n%\\bibliographystyle{unsrtnat}\n%\\bibliographystyle{apalike} \n\\bibliographystyle{apacite}\n\\bibliography{references}\n\n\\end{document}\n", "meta": {"hexsha": "966215f34d245cdab2972af7c7400d7567588aff", "size": 54347, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/ABMCMC.tex", "max_stars_repo_name": "nickmalleson/AgentBasedMCMC", "max_stars_repo_head_hexsha": "c31cc5e04e9da28373f402bd0bf61cd39e9183c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/ABMCMC.tex", "max_issues_repo_name": "nickmalleson/AgentBasedMCMC", "max_issues_repo_head_hexsha": "c31cc5e04e9da28373f402bd0bf61cd39e9183c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/ABMCMC.tex", "max_forks_repo_name": "nickmalleson/AgentBasedMCMC", "max_forks_repo_head_hexsha": "c31cc5e04e9da28373f402bd0bf61cd39e9183c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 79.1077147016, "max_line_length": 1455, "alphanum_fraction": 0.7322759306, "num_tokens": 15606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.33125709898587796}}
{"text": "\\documentclass[11pt]{article}\n\\usepackage{amsmath, amssymb}\n\\usepackage{geometry} % see geometry.pdf on how to lay out the page. There's lots.\n\\geometry{a4paper} % or letter or a5paper or ... etc\n\\usepackage{graphicx}\n% \\geometry{landscape} % rotated page geometry\n% See the ``Article customise'' template for come common customisations\n\\usepackage[style=phys,\ncitestyle=phys]{biblatex}\n\\addbibresource{van_vleck_memo_A.bib}\n\n\\usepackage{listings}\n\n\\title{Implementation of Van Vleck Correction for the MWA}\n\\author{Pyxie Star}\n% delete this line to display the current date\n\\renewcommand{\\Re}{\\operatorname{Re}}\n\\renewcommand{\\Im}{\\operatorname{Im}}\n%%% BEGIN DOCUMENT\n\\begin{document}\n\n\\maketitle\n% \\section{Introduction}\n\\paragraph{}Quantization in the MWA digital signal pathway introduces non-linear artifacts into the data. Formulae for correcting these artifacts with a Van Vleck correction were presented in \\cite{VV}. An implementation of the correction has been written into \\texttt{pyuvdata} as an option when reading raw MWA correlator output files. This memo describes MWA quantization, re-derives the correction formulae, and discusses the implementation.\n\\section{MWA Quantization}\n\\paragraph{}\nQuantization occurs in 3 stages of the MWA digital signal pathway, twice in the digital receivers and then in the correlator. It is this final quantization that the implemented Van Vleck correction addresses. All three quantization stages are described below in a summary of the digital signal pathway.\n\\paragraph{}\nThe analog signal from a tile is attenuated to $\\pm1$ Volt, and a bandpass is applied to limit the frequency range to 80-300 MHz. This signal then goes to a digital receiver, described in \\cite{rec}, where it is sampled at 655.36 MHz and quantized to 8-bit values. The quantized data is then cast from real to complex, and also channelized into 256 1.28 MHz 'coarse' channels, by a polyphase filter bank (PFB). The PFB has an 8 tap subfilter followed by a 512 point FFT, and functions as follows. A Kaiser windowing function is applied to 4096 data samples. The 4096 windowed samples are split into 8 'phases' of 512 samples each, which are summed to result in 512 inputs to the FFT. The FFT outputs 256 complex values each consisting of a 16-bit real and 16-bit imaginary pair. Since each frequency channel is complex, that is, carrying two sampled values, the sampling rate is halved to 327.68 MHz. The incoming data is then shifted by 512 samples and the PFB procedure applied to this next grouping. After the FFT, a gain is applied to the data, and the second quantization occurs, taking the 16-bit real, 16-bit imaginary pair to a 5-bit real, 5-bit imaginary pair. For each observing session, some subset of 24 coarse channels are chosen and sent to the correlator. \n\\paragraph{}\nThe MWA correlator has two stages: a PFB which channelizes the data, and a cross-multiply and accumulate module to perform the correlations. The correlator PFB  has 12-tap subfilter followed by a 128-point FFT, applying a Hanning window to the data stream. Outputs of this second PFB are quantized to 4-bit real, 4-bit imaginary pairs, and these integers are cast to floats for input into the cross-multiply. The correlator is described in greater detail in \\cite{corr}, and its PFB described in \\cite{pfb}.\n\\section{Van Vleck Correction}\n\\begin{figure}\n\\centering{}\n\\includegraphics[width=80mm]{quant.pdf}\n\\caption{The 4-bit quantization pattern of the MWA.\\label{quant}}\n\\end{figure}\n\\paragraph{}\nThe final 4-bit quantization in the correlator is assumed to have a dominant impact, and so is addressed by the Van Vleck correction.\nThat is, we effectively treat the values in the 4-bit quantization as being drawn from an analog zero-mean Gaussian distribution, ignoring the intermediate signal processing stages. Let $Z$ be the analog signal from an antenna and $\\hat Z$ the quantized signal. The quantization pattern $\\hat Z(Z)$ is shown in figure~\\ref{quant}; essentially, all $Z$ values within a certain range are placed into a certain quantization bin. After correlation, we no longer have access to $\\hat Z$, and so the Van Vleck correction instead treats the statistics of $\\hat Z$, assuming that we are in a regime in which we can approximate the auto and cross correlations as measuring variances and covariances as described in section 3. \n\\paragraph{}\nFirst, consider the relation between the variance of $\\hat Z$ and the variance of $Z$. Following \\cite{VV}, the variance $E[\\hat Z^2]$ is related to the probability of $Z$ falling into each of the quantization bins as follows\n\\begin{equation}\n\\begin{split}\nE[\\hat Z^2]=&0^2\\cdot P(-0.5<Z<0.5) +(-1)^2\\cdot P(-1.5<Z<-0.5)+1^2\\cdot P(0.5<Z<1.5)+\\cdot\\cdot\\cdot\\\\\n&+(-7)^2\\cdot P(Z<-6.5)+7^2\\cdot P(Z>6.5)\\\\\n=&0^2\\cdot P(-0.5<Z<0.5)+1^2\\cdot[P(-1.5<Z<1.5)-P(-0.5<Z<0.5)]+\\cdot\\cdot\\cdot\\\\\n&+7^2\\cdot[1-P(-6.5<Z<6.5)]\n\\end{split}\n\\end{equation}\nwhere we have taken advantage of the symmetry of the distribution of $Z$. With $Z$ drawn from a Gaussian distribution, the probability that $Z\\in[-a,a]$\n\\begin{equation}\nP(Z\\in[-a,a])=\\textrm{erf}\\left(\\frac{a}{\\sigma_Z\\sqrt{2}}\\right)\n\\end{equation}\nwhere $\\sigma_Z$ is the standard deviation of $Z$. Combining terms gives\n\\begin{align}\nE[\\hat Z^2]=&0^2\\cdot\\textrm{erf}\\left(\\frac{0.5}{\\sigma_Z\\sqrt{2}}\\right)+1^2\\cdot\\left[\\textrm{erf}\\left(\\frac{1.5}{\\sigma_Z\\sqrt{2}}\\right)-\\textrm{erf}\\left(\\frac{0.5}{\\sigma_Z\\sqrt{2}}\\right)\\right]+\\cdot\\cdot\\cdot+7^2\\cdot\\left[1-\\textrm{erf}\\left(\\frac{6.5}{\\sigma_Z\\sqrt{2}}\\right)\\right]\\nonumber\\\\\n=&(-1)\\textrm{erf}\\left(\\frac{0.5}{\\sigma_Z\\sqrt{2}}\\right)+(-3)\\textrm{erf}\\left(\\frac{1.5}{\\sigma_Z\\sqrt{2}}\\right)+\\cdot\\cdot\\cdot+(-13)\\textrm{erf}\\left(\\frac{6.5}{\\sigma_Z\\sqrt{2}}\\right)+7^2\\nonumber\\\\\n=&7^2-\\sum_{k=0}^6(2k+1)\\textrm{erf}\\left(\\frac{k+0.5}{\\sigma_Z\\sqrt{2}}\\right).\n\\end{align}\nThis result can be written in terms of the standard deviation of $\\hat Z$:\n\\begin{equation}\\label{autocorr}\n\\hat \\sigma_Z = \\left[7^2-\\sum_{k=0}^6(2k+1)\\textrm{erf}\\left(\\frac{k+0.5}{\\sigma_Z\\sqrt{2}}\\right)\\right]^{1/2}\n\\end{equation}\n\\paragraph{}\nNow consider the impact of quantization on the covariance and correlation between two quantized $\\hat Z_1$ and $\\hat Z_2$, where, since the distributions are zero-mean, the covariances\n\\begin{align}\n\\kappa &= E[Z_1Z_2],\\\\\n\\hat\\kappa &= E[\\hat Z_1\\hat Z_2];\n\\end{align}\nand the correlations\n\\begin{align}\n\\rho &= \\frac{\\kappa}{\\sigma_1\\sigma_2},\\\\\n\\hat\\rho&= \\frac{\\hat\\kappa}{\\hat\\sigma_1\\hat\\sigma_2}.\n\\end{align}\nAgain following \\cite{VV}, we use Prices's theorem, which, for two random variables $X$ and $Y$, states\n\\begin{equation}\n\\frac{ \\partial \\langle f(X, Y)\\rangle}{\\partial \\langle XY\\rangle}=\\Big\\langle\\frac{\\partial f}{\\partial X}\\frac{\\partial f}{\\partial Y}.\\Big\\rangle\n\\end{equation}\nwhere brackets indicate expectation values.\nUsing the function $f(Z_1, Z_2)=\\hat Z_1 \\hat Z_2$, we obtain\n\\begin{equation}\\label{price}\n\\frac{\\partial \\hat \\kappa}{\\partial \\kappa}=\\Big\\langle\\frac{\\partial \\hat Z_1}{\\partial Z_1}\\frac{\\partial \\hat Z_2}{\\partial Z_2}\\Big\\rangle\n\\end{equation}\nFor our quantization function, the derivative\n\\begin{equation}\n\\frac{\\partial \\hat Z}{\\partial Z} = \\delta(Z -(-6.5)) +\\delta(Z -(-5.5))+\\cdot\\cdot\\cdot+\\delta(Z-5.5)+\\delta(Z-6.5)\n\\end{equation}\nso\n\\begin{equation}\n\\frac{\\partial \\hat Z_1}{\\partial Z_1}\\frac{\\partial \\hat Z_2}{\\partial Z_2}=\\sum_{i=-7}^{6}\\sum_{j=-7}^{6}\\delta(Z_1-(i+0.5))\\delta(Z_2-(j+0.5))\n\\end{equation}\nTo find the expectation value, we integrate with the joint normal probability density function\n\\begin{equation}\n\\begin{split}\n\\Big\\langle\\frac{\\partial \\hat Z_1}{\\partial Z_1}\\frac{\\partial \\hat Z_2}{\\partial Z_2}\\Big\\rangle=\\sum_{i=-7}^{6}\\sum_{j=-7}^{6}\\int_{-\\infty}^\\infty\\int_{-\\infty}^\\infty &dZ_1dZ_2\\delta(Z_1-(i+0.5))\\delta(Z_2-(j+0.5))\\\\\n&\\frac{1}{2\\pi\\sigma_{1}\\sigma_{2}\\sqrt{1-\\rho^2}}\\exp\\Big[-\\frac{1}{2(1-\\rho^2)}\\Big(\\frac{Z_1^2}{\\sigma_1^2}+\\frac{Z_2^2}{\\sigma_2^2}-\\frac{2\\rho Z_1Z_2}{\\sigma_1\\sigma_2}\\Big)\\Big]\n\\end{split}\n\\end{equation}\nto get\n\\begin{equation}\n\\begin{split}\n\\Big\\langle\\frac{\\partial \\hat Z_1}{\\partial Z_1}\\frac{\\partial \\hat Z_2}{\\partial Z_2}\\Big\\rangle=\\sum_{i=-7}^{6}\\sum_{j=-7}^{6}\\frac{1}{2\\pi\\sigma_{1}\\sigma_{2}\\sqrt{1-\\rho^2}}\\exp&\\Big[-\\frac{1}{2(1-\\rho^2)}\\Big(\\frac{(i+0.5)^2}{\\sigma_1^2}+\\frac{(j+0.5)^2}{\\sigma_2^2}\\\\\n&-\\frac{2\\rho (i+0.5)(j+0.5)}{\\sigma_1\\sigma_2}\\Big)\\Big]\n\\end{split}\n\\end{equation}\nWriting $\\rho=\\kappa/\\sigma_1\\sigma_2$, equation \\ref{price} becomes\n\\begin{equation}\n\\label{crosscorr}\n\\begin{split}\n\\hat\\kappa=\\sum_{i=-7}^{6}\\sum_{j=-7}^{6}\\int_0^\\rho d{\\rho'}\\frac{1}{2\\pi\\sqrt{1-{\\rho'}^2}}\\exp&\\Big[-\\frac{1}{2(1-{\\rho'}^2)}\\Big(\\frac{(i+0.5)^2}{\\sigma_1^2}+\\frac{(j+0.5)^2}{\\sigma_2^2}\\\\\n&-\\frac{2{\\rho'} (i+0.5)(j+0.5)}{\\sigma_1\\sigma_2}\\Big)\\Big]\n\\end{split}\n\\end{equation}\n\\section{Implementation}\n\\paragraph{}Let the correlator inputs from antennas 1 and 2, with arbitrary polarization, be $\\hat Z_1$ and $\\hat Z_2$, where $\\hat Z$ is a sum of a sky signal and receiver noise: $\\hat Z=S+N$. $S$ and $N$ are both complex circular Gaussian random variables. That is, the real and imaginary parts are each Gaussian distributed with zero mean, and are uncorrelated with each other. Alternatively, we can think of this as there being no preferred phase in either the sky signal or in the receiver noise. We additionally assume that $\\hat Z$ itself is a complex circular Gaussian random variable, which might require assumptions about the lack of correlation between sky signal and instrument noise (see Appendix \\ref{ccrv}). \n\\paragraph{}In the limit of large time integration $t$, we can approximate the autocorrelation of $\\hat Z$ as the variance:\n\\begin{equation}\n\\frac{1}{t}\\sum_i^t \\hat Z_i \\hat Z_i^*\\rightarrow E[\\hat Z\\hat Z^*].\n\\end{equation}\nSince $Z$ is circular random, in this limit the autocorrelation is related to the variance of the real and imaginary parts of $Z$:\n\\begin{equation}\n\\frac{1}{t}\\sum_i^t \\hat Z_i \\hat Z_i^*=2E[\\Re(\\hat Z)^2]=2E[\\Im(\\hat Z)^2].\n\\end{equation}\nAlso in the limit of large $t$, the cross-correlation can be approximated as the covariance:\n\\begin{equation}\n\\frac{1}{t}\\sum_i^t \\hat Z_{1_i} \\hat Z_{2_i}^*\\rightarrow E[\\hat Z_1\\hat Z_2^*].\n\\end{equation}\nThe covariance can be expanded and simplified:\n\\begin{align}\nE[\\hat Z_1\\hat Z_2^*]=&E[\\Re(\\hat Z_1)\\Re(\\hat Z_2)]+E[\\Im(\\hat Z_1)\\Im(\\hat Z_2)]\\nonumber\\\\\n&+iE[\\Im(\\hat Z_1)\\Re(\\hat Z_2)] -iE[\\Re(\\hat Z_1)\\Im(\\hat Z_2)]\\nonumber\\\\\n=&2E[\\Re(\\hat Z_1)\\Re(\\hat Z_2)]+2iE[\\Im(\\hat Z_1)\\Re(\\hat Z_2)] \n\\end{align}\nwhere the following relations for circular complex random variables have been used, which may require the assumption that $\\hat Z_1=S+N_1$ and $\\hat Z_2=S+N_2$ are drawn from the same distribution.\n\\begin{align}\nE[\\Re(\\hat Z_1)\\Re(\\hat Z_2)]&=E[\\Im(\\hat Z_1)\\Im(\\hat Z_2)]\\\\\nE[\\Im(\\hat Z_1)\\Re(\\hat Z_2)]&=-E[\\Re(\\hat Z_1)\\Im(\\hat Z_2)]\n\\end{align}\n\\paragraph{}To correct a cross-correlation between antennas 1 and 2, the first step is to find $\\sigma_1$ and $\\sigma_2$. For antenna 1, the quantized standard deviation $\\hat \\sigma_1$ of the real and imaginary parts of $Z_1$ can effectively be found by taking the antenna's autocorrelation, dividing it by 2, and taking the square root. Equation \\ref{autocorr} can be used to find $\\sigma_1$ from $\\hat \\sigma_1$. This $\\sigma_1$, along with $\\sigma_2$ calculated in the same way, are then used in equation \\ref{crosscorr} to correct the real and imaginary parts of the cross correlation. The real and imaginary parts of the cross correlation are also divided by 2 before correcting.\n\\paragraph{}\nThe Van Vleck correction algorithm was implemented in \\texttt{pyuvdata}. To verify the algorithm, equations \\ref{autocorr} and \\ref{crosscorr} were plotted, as shown in figures~\\ref{corrplot} and \\ref{sig}. Comparison plots were then generated using the implementations of these functions in the code, verifying the functions' accuracy. Also, data corrected by the algorithm was taken back through equations \\ref{autocorr} and \\ref{crosscorr}, showing that the calculated quantized data matched the initial uncorreted input.\n\n\\begin{figure}\n\\centering{}\n\\includegraphics[width=80mm]{corrtestplot4.png}\n\\caption{The cross-correlation Van Vleck correction function (equation~\\ref{crosscorr}) plotted with $\\sigma_1=1.0, \\sigma_2=1.0$.\\label{corrplot}}\n\\end{figure}\n\n\\begin{figure}\n\\centering{}\n\\includegraphics[width=80mm]{sigmatestplot4.png}\n\\caption{The auto-correlation Van Vleck correction function (equation~\\ref{autocorr}).\\label{sig}}\n\\end{figure}\n\n\\paragraph{}The correction algorithm has a high computational cost associated with equation \\ref{crosscorr}, which has $14^2$ exponential terms in the summation. By combining redundant terms, this number can be reduced by a factor of 2. Evaluation of the integral using \\texttt{scipy.integrate.quad} requires ~750 computations of the summation. Using a \\texttt{scipy} root-finding function proved useful for finding the input of equation \\ref{autocorr} given some output. However, this same function is too costly when correcting the cross-correlations, even though only ~5 evaluations of equation \\ref{crosscorr} were required for the root-finding function to converge. An additional cost is memory usage, as running the root-finding function requires generation of a Jacobian matrix the size of which is dictated by the number of cross-correlations being corrected. This places a limit on the number of values which can be corrected simultaneously. \n\\paragraph{} \nThere are several possible solution for mitigating the cost of correcting the cross-correlations. One is to implement a \\texttt{scipy} integration function which allows for vectorized integral evaluation, though this has potential for loss in precision. Additionally, moving from a root-finding algorithm to a lookup table might be more computationally efficient. Both root-finding and a lookup table may ultimately require parallelization to be feasible. Another, perhaps more complicated but also potentially interesting, alternative is to exploit the role of the corrected auto-correlations in equation \\ref{crosscorr} and use the shapes of the correction on the autos to determine the shape of the correction on the respective cross-correlation. \n\\appendix\n\\section{Circular Complex Gaussian Random Variables}\\label{ccrv}\n\\paragraph{}A circular complex random variable $Z=\\Re(Z)+i\\Im(Z)$ is defined as having a distribution that is invariant under a random phase shift:\n\\begin{align}\nE[Z]&=E[e^{i\\phi}Z]=0,\\\\\nE[ZZ]&=E[e^{i\\phi}Ze^{i\\phi}Z],\\\\\nE[ZZ^*]&=E[e^{i\\phi}Ze^{-i\\phi}Z^*]].\n\\end{align}\nThe last of these conditions is trivial. The first and second are only satisfied if $E[Z]=E[ZZ]=0$. Thus\n\\begin{align}\nE[ZZ]&=0\\\\\n&=E[(\\Re(Z)+i\\Im(Z))(\\Re(Z)+i\\Im(Z))]\\\\\n&=E[\\Re(Z)^2]-E[\\Im(Z)^2]+iE[\\Re(Z)\\Im(Z)]+iE[\\Im(Z)\\Re(Z)]\n\\end{align}\nand\n\\begin{align}\nE[\\Re(Z)^2]&=E[\\Im(Z)^2],\\\\\nE[\\Re(Z)\\Im(Z)]&=-E[\\Im(Z)\\Re(Z)]=0\\label{CC1}.\n\\end{align}\nFor a complex random variable, the variance $\\sigma_Z^2=E[ZZ^*]=E[\\Re(Z)^2]+E[\\Im(Z)^2]$. So in the case of a circularly complex random variable\n\\begin{equation}\n\\sigma_Z^2=2E[\\Re(Z)^2]=2E[\\Im(Z)^2].\n\\end{equation}\nTwo circular complex random variables sampled from the same distribution have the following relations\n\\begin{align}\nE[\\Re(Z_1)\\Re(Z_2)]&=E[\\Im(Z_1)\\Im(Z_2)]\\\\\nE[\\Re(Z_1)\\Im(Z_2)]&=-E[\\Im(Z_1)\\Re(Z_2)]\\label{CC2}\n\\end{align}\nIf this relation does not hold for circular complex random variables sampled from different distributions, then some assumptions are required for the correlator input model.\n\\paragraph{}For example, consider the case of a correlator input $Z=S+N$, where $S$ and $N$ are both circular complex Gaussian random variables, that is, in addition to the conditions above, the real and imaginary parts of $S$ and $N$ are sampled from zero-mean Gaussian distributions. To treat $Z$ as circularly complex requires $E[\\Re(Z)\\Im(Z)]=0$. Thus\n\\begin{equation}\nE[\\Re(S)\\Im(S)]+E[\\Re(N)\\Im(N)]+E[\\Re(S)\\Im(N)]+E[\\Re(N)\\Im(S)]=0.\n\\end{equation}\nThe first two terms vanish according to \\eqref{CC1}. If \\eqref{CC2} applies to circular complex random variables sampled from different distributions, the last two terms vanish. If the relation does not apply, then it is required that $E[\\Re(S)\\Im(N)]=E[\\Re(N)\\Im(S)]=0$, that is, that the sky signal and receiver noise are uncorrelated. \n\\nocite{*}\n\\printbibliography\n%\\bibliographystyle{apsrmp4-2}\n\\end{document}", "meta": {"hexsha": "a0e2f7165e582cd02258df1793b00f46a8159921", "size": 16467, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "007_Van_Vleck_A/van_vleck_memo_A.tex", "max_stars_repo_name": "EoRImaging/Memos", "max_stars_repo_head_hexsha": "216dbda634c1686be25cda25bb258664067a3aad", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-05T08:38:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-05T08:38:01.000Z", "max_issues_repo_path": "007_Van_Vleck_A/van_vleck_memo_A.tex", "max_issues_repo_name": "EoRImaging/Memos", "max_issues_repo_head_hexsha": "216dbda634c1686be25cda25bb258664067a3aad", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-03-07T22:45:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-20T20:19:43.000Z", "max_forks_repo_path": "007_Van_Vleck_A/van_vleck_memo_A.tex", "max_forks_repo_name": "EoRImaging/Memos", "max_forks_repo_head_hexsha": "216dbda634c1686be25cda25bb258664067a3aad", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-03-07T01:12:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-07T01:12:56.000Z", "avg_line_length": 84.0153061224, "max_line_length": 1271, "alphanum_fraction": 0.7401469606, "num_tokens": 5163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3311781064336618}}
{"text": "\\documentclass{elsart}\n\n\\usepackage{amssymb}\n\n\\usepackage[all]{xy}\n\n\\newcommand{\\FuncProblem}[3][]\n{\n        \\begin{problem}#1 \n        \\end{problem}\n        \\begin{tabbing}\n        \\ \\ \\ \\ \\={\\bf Input:\\ \\=}#2\\\\\n        \\ \\ \\ \\ \\={\\bf Output:\\ \\=}#3 \\\\\n        \\end{tabbing}\n}\n\\newcommand{\\DecProblem}[3][]\n{\n        \\begin{problem}#1 \n        \\end{problem}\n        \\begin{tabbing}\n        \\ \\ \\ \\ \\={\\bf Input:\\ \\=}#2\\\\\n        \\ \\ \\ \\ \\={\\bf Question:\\ \\=}#3\\\\\n        \\end{tabbing}\n}\n\n\\newcommand {\\ket} [1] {\\ensuremath{\\vert}{#1}\\ensuremath{\\rangle}}\n\\newcommand {\\bra} [1] {\\ensuremath{\\langle}{#1}\\ensuremath{\\vert}}\n\\newcommand {\\braket} [2]\n{\\ensuremath{\\langle}{#1}\\ensuremath\\,{\\vert}\\,{#2}\\ensuremath{\\rangle}}\n\\newcommand {\\norm} [1] {\\ensuremath{\\Vert}\\,#1\\,\\ensuremath{\\Vert}}\n\\newcommand {\\abs} [1] {\\ensuremath{\\vert \\ }#1\\ensuremath{\\ \\vert}}\n\\newcommand {\\card} [1] {\\ensuremath{\\vert }#1\\ensuremath{\\vert}}\n\\newcommand{\\Prob}[1]{\\ensuremath{Prob[\\ }#1\\ensuremath{\\ ]}}\n\\newcommand {\\proof}{{\\bf Proof:\\newline \\indent}}\n\n\\newcommand{\\KW}[1]{{\\bf #1}}\n\n%\\input{complexityclass}\n%%\n%%      End of Header file\n%%\n\n\\newcommand{\\bproof}{\\noindent{\\it Proof}}\n\\newcommand{\\cproof}{\\noindent{\\it Proof of Claim}}\n\\newcommand{\\eproof}{\\hspace*{\\fill}$\\rule{2mm}{2mm}$~~~~~\\bigskip}\n\\newenvironment{psketch}{\\bproof~{\\it Sketch}. }{\\eproof}\n\\newenvironment{claimproof}{\\cproof. }{\\hspace*{\\fill}\\vspace{5mm}}\n\n\\newenvironment{remark}{\\begin{trivlist}%\n\\item[\\hskip\\labelsep{\\bf Remark.}]~}{\\end{trivlist}}\n\n\\newcommand{\\p}{\\mbox{\\rm P}}\n\\newcommand{\\UP}{\\mbox{\\rm UP}}\n\\newcommand{\\PP}{\\mbox{\\rm PP}}\n\\newcommand{\\PH}{\\mbox{\\rm PH}}\n\\newcommand{\\GapP}{\\mbox{\\rm GapP}}\n\\newcommand{\\NP}{\\mbox{\\rm NP}}\n\\newcommand{\\RP}{\\mbox{\\rm RP}}\n\\newcommand{\\FP}{\\mbox{\\rm FP}}\n\\newcommand{\\coNP}{\\mbox{\\rm co-NP}}\n\\newcommand{\\ParityP}{\\mbox{$\\oplus$\\rm P}}\n\\newcommand{\\ModkP}{\\mbox{\\rm Mod$_k$P}}\n\\newcommand{\\numP}{\\mbox{\\rm \\#P}}\n\\newcommand{\\LWPP}{\\mbox{\\rm LWPP}}\n\\newcommand{\\UPSV}{\\mbox{\\rm UPSV}}\n\\newcommand{\\SPP}{\\mbox{\\rm SPP}}\n\\newcommand{\\AM}{\\mbox{\\rm AM}}\n\\newcommand{\\coAM}{\\mbox{\\rm coAM}}\n\n\\newcommand{\\CeqP}{\\mbox{\\rm C$_=$P}} \n\\newcommand{\\gap}{\\mbox{\\it gap}}\n\\newcommand{\\acc}{\\mbox{\\it acc}}\n\\newcommand{\\rej}{\\mbox{\\it rej}}\n\n\\newcommand{\\BQP}{\\mbox{\\rm BQP}}\n\\newcommand{\\AWPP}{\\mbox{\\rm AWPP}}\n\n\\newcommand{\\Ints}{{\\mathbb{Z}}}\n\\newcommand{\\GA}{{\\rm{GA}}}\n\\newcommand{\\AUTO}{\\mbox{\\small\\rm AUTO}}\n\\newcommand{\\FINDGROUP}{\\mbox{\\small\\rm FIND{-}GROUP}}\n\\newcommand{\\HSP}{\\mbox{\\small\\rm HSP}}\n\\newcommand{\\GI}{{\\rm{GI}}}\n\\newcommand{\\CONJGP}{\\mbox{\\small\\rm CONJ{-}GROUP}}\n\\newcommand{\\NORM}{\\mbox{\\small\\rm NORM}}\n\\newcommand{\\TI}{{\\rm{TI}}}\n\\newcommand{\\MEMB}{{\\rm{MEMB}}}\n\n\\newcommand{\\SAT}{\\mbox{\\rm SAT}}\n\\newcommand{\\oneSAT}{\\ensuremath{\\rm 1SAT}}\n\n\\newcommand{\\TA}{{\\tt{TA}}}\n\\newcommand{\\V}[1]{{\\large \\ensuremath{\\mathcal{V}}}(#1)}\n\\newcommand{\\E}[1]{{\\large \\ensuremath{\\mathcal{E}}}(#1)}\n\\newcommand{\\Graph}[1]{\\ensuremath{\\mathcal{G}_{#1}}}\n\\newcommand{\\Tour}[1]{\\ensuremath{\\mathcal{T}_{#1}}}\n\\newcommand{\\Sym}[1]{{\\rm Sym(}#1{\\bf )}}\n\\newcommand{\\sym}[1]{\\ensuremath{\\bf S_#1}}\n\\newcommand {\\Aut}[1]{{\\rm Aut}({#1})}\n\\newcommand{\\lexleast}{{\\rm{lex{-}least}}}\n\\newcommand {\\iso}{\\ensuremath{\\cong} }\n\\newcommand {\\niso}{\\ensuremath{\\ncong} }\n\\renewcommand{\\th}[1]{\\ensuremath{#1^{th}}}\n\n\\renewcommand{\\angle}[1]{\\langle #1\\rangle}\n\n\\begin{document}\n\\begin{frontmatter}\n\\title{Graph Isomorphism is in SPP\\thanksref{focs}}\n\n\\thanks[focs]{A preliminary version of the results in this paper were\n  presented at the IEEE FOCS 2002 conference.}\n\n\\author{V. Arvind\\corauthref{cor}}\\and\n%\\collab{{V. Arvind\\corauthref{cor}} \\and Piyush P Kurur\\thanksref{now}}\n\\corauth[cor]{Corresponding author.}\n\\ead{arvind@imsc.res.in}\n\\author{Piyush P Kurur\\thanksref{now}}\n\\thanks[now]{Present Address: Department of Computer Science and Engineering,\nI.I.T, Kanpur, Kanpur 208016, India.}\n\\ead{ppk@imsc.res.in}\n\\address{Institute of Mathematical Sciences, Chennai 600113, India}\n\n\\date{}\n\n\\begin{abstract}\n  We show that Graph Isomorphism is in the complexity class SPP, and\n  hence it is in $\\ParityP$ (in fact, in $\\ModkP$ for each $k\\geq 2$).\n  These inclusions for Graph Isomorphism were not known prior to\n  membership in SPP. We derive this result as a corollary of a more\n  general result: we show that a {\\em generic problem} $\\FINDGROUP$\n  has an $\\FP^{\\SPP}$ algorithm. This general result has other\n  consequences: for example, it follows that the {\\em hidden subgroup\n    problem} for permutation groups, studied in the context of quantum\n  algorithms, has an $\\FP^{\\SPP}$ algorithm. Also, some other\n  algorithmic problems over permutation groups known to be at least as\n  hard as Graph Isomorphism (e.g.\\ coset intersection) are in $\\SPP$,\n  and thus in $\\ModkP$ for each $k\\geq 2$.\n\\end{abstract}\n\n\\begin{keyword}\nGraph Isomorphism, Counting Classes, SPP, Lowness.\n\\end{keyword}\n\n\\end{frontmatter}\n\n\\section{Introduction}\n\nThe Graph Isomorphism problem ---of testing if two graphs are\nisomorphic--- is a well-studied algorithmic problem in the class NP.\nFormally, the decision problem $\\GI$ (for Graph Isomorphism) is\ndefined as:\n\\begin{eqnarray*}\n\\GI=\\{\\angle{X_1,X_2}\\mid X_1\\mbox{ and }X_2\\mbox{ are isomorphic}\n\\mbox{ graphs}\\}. \n\\end{eqnarray*}\n\nIt is an outstanding open problem in computational complexity whether\nGraph Isomorphism has a polynomial-time algorithm. This problem has\nstimulated a great deal of research in algorithms and complexity over\nthe years. There is strong evidence that Graph Isomorphism is not\n$\\NP$-complete. In~\\cite{babai84trading} (also see\n\\cite{babai88arthur}) it was shown that Graph Nonisomorphism is in AM\nimplying that GI is in $\\NP\\cap\\coAM$. It follows that GI cannot be\nNP-complete unless the polynomial hierarchy collapses to\n$\\Sigma^p_2$~\\cite{boppana87does,schoning87graph}. Sch\\\"oning, who\nintroduced the notion of lowness in complexity theory, pointed out in\n\\cite{schoning87graph} that GI is {\\em low\\/} for $\\Sigma^p_2$.  I.e.\\\nGI is powerless as oracle for $\\Sigma^p_2$.\n\nSubsequently, it was shown in~\\cite{kobler92graph} that GI is also\n{\\em low\\/} for the counting complexity class PP (PP is the language\nclass corresponding to $\\numP$). This result is proven using the\nmachinery of $\\GapP$ functions introduced in the seminal paper by\nFenner, Fortnow, and Kurtz \\cite{fenner91gapdefinable} on\ngap-definable counting classes. The study of counting complexity\nclasses is an area of research in structural complexity theory\nmotivated by Valiant's class $\\numP$ (see e.g.\\\n\\cite{fenner91gapdefinable}). Intuitively, counting complexity classes\nare defined by suitable restrictions on the number of accepting and\nrejecting paths in nondeterministic Turing machines. In\n\\cite{fenner91gapdefinable} the languages classes $\\SPP$ and $\\LWPP$\nare introduced as generalizations of Valiant's class $\\UP$. It is\nshown in \\cite{fenner91gapdefinable} that\n$\\UP\\subseteq\\SPP\\subseteq\\LWPP$, and $\\LWPP$ is low for $\\PP$.\n\nAfter Shor's breakthrough quantum polynomial-time algorithms for\ninteger factoring and discrete log \\cite{shor97polynomialtime} a\nnatural question is whether Graph Isomorphism is in BQP (the class of\nproblems solvable in quantum polynomial time). The hidden subgroup\nproblem was formulated to generalize Shor's algorithmic technique. In\nparticular, Graph Isomorphism can be seen as an instance of the hidden\nsubgroup problem.\n\nHow does the class BQP relate to standard complexity classes defined\nusing classical Turing machines? Fortnow and Rogers\n\\cite{fortnow98complexity} show that BQP is contained in the counting\ncomplexity class AWPP (definitions follow). Thus, in a sense, we can\nalso think of BQP as a counting class.\n\n\\subsection{ Summary of new results}\n\nIn this paper, we show that Graph Isomorphism is in the class $\\SPP$.\nThis was left as an open question in \\cite{kobler92graph} (also see\n\\cite{fenner91gapdefinable}).  As a consequence it follows that $\\GI$\nis in and low for $\\ModkP$ for each $k\\geq 2$. Previously, only a\nspecial case of Graph Isomorphism, namely Tournament Isomorphism, was\nknown to be in $\\ParityP$.\\footnote{Tournament Isomorphism in\n$\\ParityP$ follows because any tournament has an odd number of\nautomorphisms. There are special cases of Graph Isomorphism, e.g.\\\nGraph Isomorphism for bounded-degree graphs or bounded genus graphs,\nthat have polynomial-time algorithms.}\n\nWhat we prove is a more general result: we show that a generic problem\n$\\FINDGROUP$ is in $\\FP^{\\SPP}$ as a consequence of which $\\GI$ and\nseveral other algorithmic problems on permutation groups that are not\nknown to have polynomial-time algorithms turn out to be in $\\SPP$. In\nparticular, as another corollary, we show that the hidden subgroup\nproblem (\\HSP) over permutation groups is in $\\FP^{\\SPP}$.  The hidden\nsubgroup problem is of interest in the area of quantum algorithms.\n\n\\subsubsection*{\\it Outline of the $\\FP^{\\SPP}$ algorithm}\n\nTo indicate how the proof of our main theorem will proceed, we give a\nbroad outline of the $\\FP^{\\SPP}$ algorithm for the specific problem\nof computing a generator set for the automorphism group $G=\\Aut X$ of\na graph $X$ on $n$ vertices (this problem is polynomial-time\nequivalent to GI). Since $G$ is a subgroup of $S_n$, it has the\nfollowing tower of subgroups\n\\[\n{\\bf 1}=G^{(n-1)}\\leq G^{(n-2)}\\leq\\ldots\\leq\nG^{(1)}\\leq G^{(0)}=G,\n\\]\nwhere $G^{(i)}$ is the subgroup of $G$ that fixes the points\n$1,2,\\ldots,i$.\n\nOur algorithm will compute a generator set for $G$ by computing the\ncoset representatives of $G^{(i)}$ in $G^{(i-1)}$ for each $i$.\nStarting with $G^{(n-1)}$, the algorithm will compute what is known as\na strong generator set for $G^{(i)}$ in decreasing order of $i$ until\nfinally it computes a strong generator set for $G^{(0)}=G$.\n\nIf $G$ were given by its generator set as input, then it is well-known\nthat a strong generator set for $G$ can be computed in polynomial\ntime.  These ideas were developed in\n\\cite{sims70computational,furst80polynomialtime} to design a\npolynomial-time membership test for permutation groups. These ideas\nplay an important role in the design of our algorithm. For our problem\nnotice that we do not have access to a generator set for $G=\\Aut X$.\nIndeed, a generator set for $\\Aut X$ is what the algorithm has to\ncompute. Our algorithm will use an NP oracle to access elements of $G$\nfrom different subgroups in the above tower. An important aspect that\nyields the $\\FP^{\\SPP}$ bound is that the queries made by the\nalgorithm to the NP oracle are carefully chosen. A key procedure we\nuse here is a polynomial-time algorithm for finding the\nlexicographically least element in a coset $Hg$ of a permutation group\n$H\\leq S_n$ and $g\\in S_n$.\n\nThe plan of the paper is as follows: in the next section we explain\nnotation and give preliminary definitions and results, particularly\nconcerning SPP and related counting complexity classes. In Sections 3\nand 4 we develop the ingredients leading to the proof of our main\nresult that there is an $\\FP^{\\SPP}$ algorithm for the $\\FINDGROUP$\nproblem, and derive as corollary that GI is in SPP. In Sections 5 and\n6 we give further applications of the main result.  Finally, we state\nsome open problems.\n\n\\section{Preliminaries}\n\nFollowing standard  notation, we use  $\\Sigma$ to denote  the alphabet\n$\\{0,1\\}$ and  $\\Sigma^*$ denotes the  set of all finite  strings over\n$\\Sigma$. The length  of a string $x\\in\\Sigma^*$ is  denoted by $|x|$.\nLet $\\mathbb{Z}$ denote the set of integers.\n\nAs usual, the class of languages computable in polynomial time is\ndenoted by P, and the class of polynomial-time computable functions is\ndenoted by FP. The class of languages computable in nondeterministic\npolynomial time is denoted by NP. Other basic notions from complexity\ntheory that we require in this paper can be found in standard\ntextbooks such as Balc\\'azar et al's\ntexts~\\cite{structcomp1,structcomp2}.  We now focus on definitions of\ncounting complexity classes, with particular emphasis on gap-definable\nclasses, and give a brief description of some of their properties\nrelevant to the present article. Details can be found in\n\\cite{fenner91gapdefinable,fenner93oracle,fortnow98complexity,Fe03}.\n\n\\subsection{\\bf SPP and other Counting Complexity Classes}\\label{defs}\n\nFenner, Fortnow and Kurtz defined gap-definable functions\n\\cite{fenner91gapdefinable} using which they examined several counting\ncomplexity classes like PP, $\\CeqP$, $\\ModkP$, and SPP.\n\n\\begin{defn}\\label{gapdefinable}\n  A function $f:\\Sigma^*\\rightarrow\\mathbb{Z}$ is said to be {\\em\n    gap-definable} if there is a nondeterministic polynomial time\n  Turing machine $M$ such that, for each $x\\in\\Sigma^*$, $f(x)$ is the\n  difference between the number of accepting paths and the number of\n  rejecting paths of $M$ on input $x$. More precisely, if $\\acc_M(x)$\n  denotes the number of accepting paths and $\\rej_M(x)$ the number of\n  rejecting paths of $M$ on input $x$, then \n\\[\nf(x)=\\acc_M(x)-\\rej_M(x).\n\\]\n\\end{defn}\n\nLet GapP denote the class of gap-definable functions\n\\cite{fenner91gapdefinable}. For each nondeterministic polynomial time\nTuring machine $M$ let $\\gap_M$ denote the GapP function defined by\nit.\n\nRecall that a language $L$ is in UP if there is a nondeterministic\npolynomial-time Turing machine $M$ accepting $L$ such that $M$ has at\nmost one accepting path on any input. The class UP was defined by\nValiant in \\cite{Val79} and it captures the complexity of 1-way\nfunctions.\n\nThe complexity class SPP introduced in \\cite{fenner91gapdefinable} is\nthe GapP analogue of UP. The class LWPP, also introduced in\n\\cite{fenner91gapdefinable}, contains SPP. We recall their\ndefinitions.\n\n\\begin{defn}\\mbox{}\\label{sppdef}\n\\begin{enumerate}\n\\item A language $L$ is in $\\SPP$ if there is a nondeterministic\n  polynomial-time Turing machine $M$ such that\n\\begin{eqnarray*}\nx\\in L & \\textrm{ implies } & \\gap_M(x)=1,\\\\\nx\\not\\in L & \\textrm{ implies } & \\gap_M(x)=0.\n\\end{eqnarray*}\n\\item A language $L$ is in $\\LWPP$ if there are a nondeterministic\n  polynomial-time Turing machine $M$ and an $\\FP$ function $g$ such\n  that\n\\begin{eqnarray*}\nx\\in L & \\textrm{ implies } & \\gap_M(x)=g(1^{|x|}),\\\\\nx\\not\\in L & \\textrm{ implies } & \\gap_M(x)=0.\n\\end{eqnarray*}\n\\end{enumerate}\nIn either case we say that $L$ is {\\em accepted} by the machine $M$.\n\\end{defn}\n\nWe note that $\\UP\\subseteq\\SPP\\subseteq \\LWPP$. The standard counting\ncomplexity classes PP and $\\ModkP$ can also be defined using\ngap-definable functions.\n\\begin{defn}{}{\\rm\\cite{fenner91gapdefinable}}\\label{pp-modkp-defs}\n\\begin{enumerate}\n\\item A language $L$ is in $\\PP$ if there is a nondeterministic\npolynomial-time Turing machine $M$ such that\n\\[\nx\\in L \\iff \\gap_M(x)>0.\n\\]\n\\item A language $L$ is in $\\ModkP$ (for $k\\geq 2$) if there is a\n  nondeterministic polynomial-time Turing machine $M$ such that\n\\[\nx\\in L \\iff \\gap_M(x)\\neq 0~(\\textrm{mod}~k).\n\\]\n\\end{enumerate}\n\\end{defn}\n\nIndeed, the above definitions are examples of a general notion of\ngap-definable complexity classes introduced and studied in\n\\cite{fenner91gapdefinable}. It is shown in\n\\cite{fenner91gapdefinable} that SPP is the minimal gap-definable\nclass in a certain sense.\n\nBy relativizing the nondeterministic polynomial-time Turing machines\nwe can define the relativized class $\\GapP^A$, for oracle\n$A\\in\\Sigma^*$. Thus, we can define the relativized complexity classes\n$\\SPP^A$, $\\PP^A$, and $\\ModkP^A$.\n\nThe notion of lowness was first introduced in complexity theory by\nSch\\\"oning in \\cite{Sch83}. We recall the definition.\n\n\\begin{defn}\nLet ${\\mathcal C}$ be a relativizable complexity class. We say that\na language $A\\in\\Sigma^*$ is {\\em low} for ${\\mathcal C}$ if\n${\\mathcal C}^A={\\mathcal C}$.\n\\end{defn}\n\nIn particular we are interested in languages that are low for the\nclass PP. We summarize as a theorem some properties of SPP from\n\\cite{fenner91gapdefinable} related to lowness.\n\n\\begin{thm}{}{\\rm\\cite{fenner91gapdefinable}}\\label{SPP-self-low}\n\\begin{enumerate}\n\\item Every language in $\\SPP$ (indeed, even in the larger class\n  $\\LWPP$) is low for $\\PP$. More precisely, $\\PP^{\\LWPP}=\\PP$.\n\\item $\\SPP\\subseteq\\ModkP$ for all $k\\geq 2$. Moreover,\n  $\\SPP^{\\SPP}=\\SPP$.\n\\end{enumerate}\n\\end{thm}\n\nWe note here that Graph Isomorphism was shown to be low for $\\PP$ in\n\\cite{kobler92graph} by proving that it is in $\\LWPP$. It is also\nshown in \\cite{kobler92graph} that $\\GA$ (testing if a given graph has\na nontrivial graph automorphism) is in $\\SPP$. It is known that $\\GA$\nis polynomial-time reducible to $\\GI$, but the converse is open.\n\nRecall that BPP denotes the class of languages with polynomial-time\nrandomized algorithms with error probability bounded by, say, $1/3$.\nThe class BPP is also known to be low for PP \\cite{kobler92turing}.\n\nThe complexity class AWPP was introduced in \\cite{fenner93oracle}.\nMore recently, Fenner~\\cite{Fe03} has shown a sort of gap\namplification property for AWPP which yields the following neat\ndefinition for this class.\n\\begin{defn}\n  A language $L$ is in the class $\\AWPP$ if there is a\n  nondeterministic polynomial-time Turing machine $M$ and a polynomial\n  $p$ such that for all $x\\in\\Sigma^*$\n\\begin{eqnarray*}\nx\\in L & \\textrm{ implies } & 2/3\\leq \\frac{\\gap_M(x)}{2^{p(|x|)}}\\leq 1,\\\\\nx\\not\\in L & \\textrm{ implies } & 0\\leq \\frac{\\gap_M(x)}{2^{p(|x|)}}\\leq 1/3.\n\\end{eqnarray*}\n\\end{defn}\nThe class AWPP generalizes both BPP and SPP, and it is shown in\n\\cite{fenner93oracle} that every language in $\\AWPP$ is low for PP.\n\nLet BQP denote the class of languages that have quantum\npolynomial-time algorithms with bounded error probability (say $1/3$).\nTo complete the picture relating these classes, Fortnow and Rogers in\n\\cite{fortnow98complexity} have shown that BQP is contained in AWPP\nand hence BQP is also low for PP.\n\nIt is interesting to note that $\\NP\\cap\\coNP$ is \\emph{not} known to\nbe low for PP. Here is a diagram that shows the containments between\nthe complexity classes discussed here.\n\n\\[\n\\xymatrix{\n  &\\textrm{AWPP}& \\\\\n  \\textrm{LWPP} \\ar@{-}[ur] & & \\ar@{-}[ul]\\textrm{BQP} \\\\\n  \\textrm{SPP} \\ar@{-}[u] & & \\ar@{-}[u] \\textrm{BPP} \\\\\n  \\textrm{UP}  \\ar@{-}[u]  & & \\ar@{-}[u] \\textrm{RP}\\\\\n  & \\ar@{-}[ur] \\textrm{P} \\ar@{-}[ul] & }.\n\\]\n\nAlthough no containment is known between BQP and SPP, it is\ninteresting to compare these classes in terms of natural problems they\ncontain. In the present paper we show that Graph Isomorphism and the\nhidden subgroup problem for permutation groups are in SPP. These\nproblems have resisted efficient deterministic or randomized\nalgorithms, but they are still considered as problems likely to have\npolynomial-time quantum algorithms. On the other hand, $\\FP^{\\SPP}$\ncontains Integer Factoring and Discrete Log that have polynomial-time\nquantum algorithms. In fact, these problems are even in $\\FP^{\\UP}$.\nAlso, as $\\p^{\\SPP}=\\SPP$, notice that the class $\\FP^{\\SPP}$ is\nessentially SPP: for $f\\in\\FP^{\\SPP}$ and input $x$, the bits of\n$f(x)$ can be computed in SPP. A similar closure property holds for\nBQP.\n\nAs mentioned before, $\\SPP$ is contained in and is low for the\ncomplexity classes $\\ModkP$, $\\CeqP$, and $\\PP$.  Also, $\\SPP$ has\nother nice properties (see \\cite{fenner91gapdefinable} for details).\nFor instance, \\SPP\\ is characterized exactly as the class of languages\nlow for $\\GapP$. In summary, \\SPP\\ can be seen as the $\\GapP$ analogue\nof $\\UP$ and is a robust complexity class. \n%In\\cite{fenner91gapdefinable} it is also shown that SPP is the {\\em\n%  smallest} reasonable gap-definable class.\n\nLet $M$ be a nondeterministic polynomial-time oracle Turing machine.\nSuppose $A$ is a language in $\\NP$ accepted by some NP machine $N$.\nWe say that $M^A$ makes {\\em UP-like queries} to the oracle $A$ if on\nall inputs $x$, $M^A(x)$ makes {\\em only} such queries $y$ for which\n$N(y)$ has {\\em at most} one accepting path.  Effectively, it is like\n$M$ having access to a UP oracle. We now state a useful variant of a\nresult from \\cite{kobler92graph,gi-book}.\n\n\\begin{thm}[\\cite{kobler92graph}]\\label{KST-theorem}\n  Let $M$ be a nondeterministic polynomial-time oracle machine with\n  oracle $A\\in\\NP$ such that $M^A$ makes UP-like queries to $A$ then\n  the function $h(x)=\\gap_{M^{A}}(x)$ is in $\\GapP$.\n\\end{thm} \n\n%Next, we recall an important property of the class SPP shown in\n%\\cite{fenner91gapdefinable}.\n%\n%\\begin{thm}[\\cite{fenner91gapdefinable}]\\label{SPP-self-low}\n%  If $L$ is in $\\SPP^A$ for some oracle $A\\in\\SPP$ then $L\\in\\SPP$.\n%  I.e.\\ $\\SPP^{\\SPP}=\\SPP$.\n%\\end{thm}\n\nThe following lemma, which is a straightforward consequence of\nTheorem~\\ref{KST-theorem} and of Theorem~\\ref{SPP-self-low}, is in a\nform useful for this paper.\n\n\\begin{lem}\\label{KST-cor}\\mbox{}\n\\begin{itemize}\n\\item Suppose $L$ is in $\\SPP^A$ accepted by the nondeterministic\n  polynomial-time oracle machine $M^A$ with oracle $A\\in\\NP$ (i.e.\\ \n  $x\\in L$ implies that $\\gap_{M^A}(x)=1$, and $x\\not\\in L$ implies\n  that $\\gap_{M^A}(x)=0$), such that the machine $M^A$ makes UP-like\n  queries to $A$, then $L$ is in $\\SPP$.\n\\item Suppose a function $f:\\Sigma^*\\rightarrow\\Sigma^*$ is in $\\FP^A$\n  (i.e.\\ $f$ is computed by a polynomial-time oracle transducer $M^A$)\n  where $A\\in\\NP$, such that the machine $M^A$ makes UP-like queries\n  to $A$, then $f$ is in $\\FP^{\\SPP}$.\n\\end{itemize}\n\\end{lem}\n\n\\subsection{Permutation group preliminaries}\n\nThe set of all permutations on the set $[n]=\\{1,2\\ldots,n\\}$ is a\ngroup under composition of permutations. This group is the\n\\emph{symmetric group of degree} $n$ and is denoted by $S_n$.  A {\\em\n  permutation group} on the set $[n]$ is a subgroup of $S_n$.\n\nWe use letters $g,h,\\ldots,\\sigma,\\tau ,\\pi,\\dots$ with subscripts and\nsuperscripts to denote elements of $S_n$ and $i,j$ and $k$ for the\nelements of the set $[n]$.  Subsets and subgroups of $S_n$ are denoted\nby capital letters $A$, $G$, $H$ etc. For two groups $G$ and $H$, we\nwrite $H\\leq G$ to denote that $H$ is a subgroup of $G$ (not\nnecessarily a proper subgroup).\n\nWe use the following standard notation in permutation group theory\n\\cite{wielandt64finite,luks93permutation}. For $g\\in S_n$ and\n$i\\in[n]$, we denote by $i^g$ the image of $i$ under permutation $g$.\nThe composition $g_1g_2$ of permutations $g_1, g_2\\in S_n$ is defined\n{\\em left to right}: i.e.\\ applying $g_1$ first and then $g_2$. More\nprecisely, $i^{g_1g_2}=(i^{g_1})^{g_2}$ for all $i\\in[n]$. For $A\n\\subseteq S_n$ and $i \\in [n]$ we denote the set $\\left\\{ i^g | g \\in\n  A \\right\\}$ by $i^A$. In particular, if $A\\leq S_n$ then $i^A$ is\nthe \\emph{orbit} of $i$ under the action of $A$ on $[n]$.\n\nIf $G\\leq S_n$ then for each $i\\in[n]$, we let $G^{(i)}$ denote the\nsubgroup $\\{g\\in G\\mid j^g=j$ for each $j\\in[i]\\}$. $G^{(i)}$ is\ncalled the {\\em pointwise stabilizer} of $[i]$ in $G$.\n\nThe identity permutation is denoted by $1$ (we use $1$ to denote the\nidentity of all groups) and the subgroup consisting of only $1$ is\ndenoted ${\\bf 1}$. The permutation group {\\em generated} by a subset\n$A$ of $S_n$ is the smallest subgroup of $S_n$ containing $A$ and is\ndenoted by $\\angle{A}$. \n\nFor the algorithmic problems considered in this paper, we assume that\na permutation $\\pi$ in $S_n$ is presented as the ordered sequence\n$(1^\\pi,2^\\pi,\\ldots,n^\\pi)$. Further, we assume that subgroups\nof $S_n$ are presented by generator sets. \n\nLet $G$ be a group and $H$ be a subgroup of $G$. For $\\varphi\\in G$\nthe subset $H\\varphi=\\{\\pi\\varphi:\\pi\\in H\\}$ of $G$ is a {\\em right\n  coset} of $H$ in $G$. Two right cosets of $H$ in $G$ are either\ndisjoint or identical. Thus, the right cosets of $H$ in $G$ form a\npartition of $G$. When $G$ is finite this partition is finite and can\nbe written as $G=H\\varphi_1\\cup H\\varphi_2 \\cup\\dots \\cup H\\varphi_k$.\nEach right coset of $H$ has cardinality equal to $|H|$ and the set\n$\\{\\varphi_1,\\varphi_2,\\dots,\\varphi_k\\}$ is a set of \\emph{distinct\n  coset representatives} of $H$ in $G$.\n\nAs developed by Sims~\\cite{sims70computational}, pointwise stabilizers\nare fundamental in the design of algorithms for permutation group\nproblems. The structure used is the chain of stabilizers subgroups in\n$G$ given by: ${\\bf 1}=G^{(n)}\\leq G^{(n-1)}\\leq \\dots \\leq\nG^{(1)}\\leq G^{(0)}=G.$ Let $C_i$ be a complete set of right coset\nrepresentatives of $G^{(i)}$ in $G^{(i-1)}, 1\\leq i\\leq n$. Then\n$\\bigcup_{i=1}^{n-1} C_i$ forms a generator set for $G$. Such a\ngenerator set is called a {\\it strong generator set} for\n$G$~\\cite{sims70computational,furst80polynomialtime}. Any $g\\in G$\nhas a unique factorization $g=g_1g_2\\dots g_n$, with $g_i\\in C_i$.\n\nWe now recall two basic algorithmic results concerning permutation\ngroups that are essential ingredients in the proof of our main result\nin Section~\\ref{mainsec}. These algorithms are originally due to Sims\n\\cite{sims70computational}, and the polynomial-time analysis is from\n\\cite{furst80polynomialtime}. Further details can be found in the\nsurvey article by Luks \\cite{luks93permutation} and the monograph by\nHoffman \\cite{hoffmann82group}.\n  \n\\begin{thm}\\label{perm-group-algos}%\\mbox{}\n Given as input the generator set $S$ for a permutation group $G\\leq\nS_n$, the following two basic algorithmic tasks can be implemented in\ntime polynomial in $n$\n\\begin{enumerate}{}\n\\item For each element $i\\in[n]$, its orbit $i^G=\\{i^g\\mid g\\in G\\}$,\n  can be computed in polynomial time.  Furthermore, for each $j$ in\n  the orbit $i^G$ we can compute in polynomial time an element $g\\in\n  G$ such that $i^g=j$.\n\\item The tower of subgroups ${\\bf 1}=G^{(n)}\\leq G^{(n-1)} \\leq\n  \\ldots \\leq G^{(1)}\\leq G$ can be computed in time polynomial in\n  $n$. (I.e.\\ the right coset representative sets $C_i$ for the groups\n  $G^{(i)}$ in $G^{(i-1)}, 1\\leq i\\leq n$ can be computed in\n  polynomial time giving a strong generator set for each $G^{(i)}$\n  including $G$).\n\\end{enumerate}\n\\end{thm}\n\n\\section{Computing the least element of a right coset}\\label{lextleast}\n\nWe define the lexicographic ordering $\\prec$ of permutations in $S_n$\ninduced by the natural order of $[n]$ as follows: For two permutations\n$\\pi\\neq \\tau\\in S_n$ we say that $\\pi\\prec \\tau$ if for some\n$i\\in[n]$ we have\n\\[\ni^\\pi<i^\\tau \\textrm{ and }~~\nj^\\pi=j^\\tau \\textrm{ for } 1\\leq j\\leq i-1.\n\\]\nClearly, this is a total order on $S_n$. Writing a permutation $\\pi$\nas the ordered sequence $(1^\\pi,2^\\pi,\\ldots,n^\\pi)$ this is clearly\nthe natural lexicographic ordering on these sequences with the\nsequence $(1,2,\\ldots,n)$ as the least element of $S_n$ and the\nsequence $(n,n-1,\\ldots,1)$ as the last element of $S_n$.\n   \nIn this section we describe a simple polynomial-time algorithm that\ntakes as input a permutation group $\\angle{A}=G \\leq S_n$ and a\npermutation $\\sigma\\in S_n$ and computes the lexicographically least\nelement of the right coset $G \\sigma$ of $G$ in $S_n$. This algorithm\nis a crucial ingredient in the proof of the main theorem in the next\nsection.\n\n\\begin{thm}\\label{lexleast}\n  There is a polynomial-time algorithm that takes as input a\n  permutation group $\\angle{A}=G \\leq S_n$ and a permutation\n  $\\sigma\\in S_n$ and computes the lexicographically least element of\n  the right coset $G \\sigma$.\n\\end{thm}\n\n\\begin{pf}\n\n We describe the algorithm and then argue its correctness.\n\n%\\caption{{\\bf Lexicographically least in a Right Coset}}\n\\begin{tabbing}\n\\quad \\=\\quad \\=\\quad                        \\kill\n{\\bf Input:} $G \\leq S_n$, $\\sigma \\in S_n$; \\\\\n{\\bf Output:} Lexicographically least element in $G \\sigma$ ; \\\\\nLet $G^{(n)}\\leq G^{(n-1)}\\leq\\ldots\\leq G^{(1)}\\leq G^{(0)}=G$ be the\ntower of subgroups of $G$\\\\ where, by Theorem~\\ref{perm-group-algos}, the\ngenerator set for each $G^{(i)}$ and the strong\\\\ generator set for $G$\ncan be computed in polynomial time;\\\\\n$\\pi_0 = \\sigma$;\\\\\n\\> \\KW{for} $i := 0$ \\KW{to} $n-1$\\\\\n\\> \\> find the element $y$ in $(i+1)^{G^{(i)}}$ such that\n                $y^{\\pi_i}$ is minimum;\\\\\n\\> \\> (* This can be done in polynomial time as the entire orbit \n$(i+1)^{G^{(i)}}$\\\\\n\\> \\>  of $i+1$ in $G^{(i)}$,  which is a set of size at most $n-i$, \ncan be computed in\\\\\n\\> \\>  polynomial time by applying Theorem~\\ref{perm-group-algos}, \nand finding  the minimum \\\\\n\\> \\> in the orbit takes linear time. *);\\\\\n\\> \\> Let $g_i \\in G^{(i)}$ be such that $(i+1)^{g_i} = y$;\\\\\n\\> \\> (* By Theorem~\\ref{perm-group-algos}, $g_i$ can be computed in\npolynomial time *);\\\\\n\\> \\>                $\\pi_{i+1} := g_i \\pi_i$;\\\\\n\\> \\KW{endfor};\\\\        \n\\KW{Output} $\\pi_n$;\\\\\n\\end{tabbing}\n\nSince $\\pi_0 = \\sigma$ and $G^{(n-1)} = \\{ 1 \\}$, it suffices to prove\nthe following claim in order to show that the algorithm computes the\nlexicographically least element of $G\\sigma$.\n\n\\begin{claim}\\label{claim1}\n  For all $0 \\leq i <n-1$ the lexicographically least element of\n  $G^{(i)}\\pi_i$ is in $G^{(i+1)} \\pi_{i+1}$.\n\\end{claim}\n\n\\begin{claimproof}\n  By definition, $\\pi_{i+1}=g_i\\pi_i$, where $g_i$ is in $G^{(i)}$\n  such that $g_i$ maps $i+1$ to $y\\in (i+1)^{G^{(i)}}$ and such that\n  $y^{\\pi_i}=x$ is the minimum element in $\\{z^{\\pi_i}\\mid z\\in\n  (i+1)^{G^{(i)}}\\}$.  Since $G^{(i)}$ fixes each element in the set\n  $[i]$ and since $g_i \\in G^{(i)}$, we can see that for every $1 \\leq\n  k \\leq i$ , for each $g \\in G^{(i)}$ and $h \\in G^{(i+1)}$, we have\n  $ k^{h \\pi_{i+1}} = k^{\\pi_{i+1}} = k^{g_i \\pi_i} = k^{\\pi_i} = k^{g\n    \\pi_i} $. In particular if $\\rho$ is the lex-least element of\n  $G^{(i)} \\pi_i$, every element in $G^{(i+1)} \\pi_{i+1}$ agrees with\n  $\\rho$ on the first $i$ elements.\n  \n  Furthermore, for each $g\\in G^{(i+1)}$ notice that $(i+1)^{g\n    \\pi_{i+1}} = (i+1)^{\\pi_{i+1}} = (i+1)^{g_i \\pi_i}=x$, where $x$\n    is defined above. It is clear that $G^{(i+1)}\\pi_{i+1}$ is\n    precisely the subset of $G^{(i)}\\pi_i$ each of whose elements maps\n    $i+1$ to $x$.  Together with the fact that $(i+1)^\\rho = x$ (by\n    the lex-least property of $\\rho$), we get the desired conclusion.\n\\end{claimproof}\n\nBy induction and the above claim it follows that the lex-least element\nof $G\\sigma=G^{(0)}\\pi_0$ is in $G^{(n)}\\pi_n=\\{\\pi_n\\}$. Thus,\n$\\pi_n$ is the desired lexicographically least element of $G\\sigma$. \\qed\n\\end{pf}\n\nThe polynomial-time algorithm of Theorem~\\ref{lexleast} can be\ngeneralised to compute the lexicographically least element of $\\tau G\n\\sigma$.\n\n\\begin{cor}\n  There is a polynomial-time algorithm that takes as input a\n  permutation group $\\angle{A}=G \\leq S_n$ and two permutations $\\tau,\n  \\sigma\\in S_n$, and computes the lexicographically least element of\n  $\\tau G \\sigma$. In particular, the lexicographically least element\n  of a left coset $\\tau G$ can also be computed in polynomial time.\n\\end{cor}\n\\begin{pf}\n  Notice that $\\tau G \\sigma=\\tau G\\tau^{-1}\\tau\\sigma$ and $\\tau\n  G\\tau^{-1}$ is a subgroup of $S_n$ with generating set $\\{\\tau\n  g\\tau^{-1}\\mid g\\in A\\}$. The result follows directly from\n  Theorem~\\ref{lexleast} applied to the group $\\tau G\\tau^{-1}$ and\n  the permutation $\\tau\\sigma$. \\qed\n\\end{pf}\n\n\\section{Graph Isomorphism in SPP}\\label{mainsec}\n\nWe are ready to prove the main theorem of the paper. Recall that the\nGraph Isomorphism problem is the following decision problem:\n$\\GI=\\{(X_1,X_2)\\mid X_1$ and $X_2$ are isomorphic$\\}$. A related\nproblem is $\\AUTO$ which is a functional problem: given a graph $X$ as\ninput the problem is to output a strong generator set for $\\Aut X$.\nIt is well-known from the result of Mathon \\cite{mathon79anote} (see\ne.g.  \\cite{gi-book}) that \\GI\\ and \\AUTO\\ are polynomial-time Turing\nequivalent.\n\nThus, in order to show that $\\GI\\in\\SPP$ it suffices to show that\n$\\AUTO\\in\\FP^{\\SPP}$. In other words, it suffices to show that there\nis a deterministic polynomial-time Turing machine $M$ with oracle\n$A\\in\\SPP$ that takes a graph $X$ as input and outputs a strong\ngenerator set for $\\Aut X$.\n\nWe observe here that the problem \\AUTO\\ itself is one among a class of\nproblems, each of which we will show is in $\\FP^{\\SPP}$ by giving such\nan algorithm for the following {\\em generic} problem $\\FINDGROUP$\nwhich we formally describe below:\n\nLet ${\\mathcal G}_n$ denote the set of all subgroups of $S_n$, for each\n$n$. Let ${\\mathcal G}$ denote the union $\\bigcup {\\mathcal G}_n$. The \n$\\FINDGROUP$ problem is defined by a function\n\\[\nf:\\Sigma^*\\times 0^*\\longrightarrow {\\mathcal G},\n\\]\nwhere to each pair $\\angle{x,0^n}$ in the domain, the image\n$f(\\angle{x,0^n})$ is a subgroup of $S_n$. When the function $f$ is\nfixed and $n$ is given, it is more convenient notation to denote\n$f(\\angle{x,0^n})$ by $G_x$.\n\nFurthermore, for each subgroup $f(\\angle{x,0^n})$ we assume that we\nhave an efficient membership test. More precisely, we assume that we\nhave access to a procedure $\\MEMB(x,g)$, that takes $x$ and $g\\in S_n$\nas input, and evaluates to {\\bf true} if and only if $g\\in G_x$\n\\emph{in time polynomial in $n$ and $|x|$}. The $\\FINDGROUP$ problem\nis to compute a strong generator set for $G_x$ given $\\angle{x,0^n}$\nas input.\n\nThe problem $\\FINDGROUP$ is generic in the sense that for different\nfunctions $f$ we get different problems. For instance, in the case of\n$\\AUTO$, for each $n$ vertex graph $X$, encoded as $x\\in\\Sigma^*$, we\ncan define $f(\\angle{X,0^n})=\\Aut X$ and for $m\\neq n$ we can define\n$f(\\angle{X,0^m})$ as the trivial subgroup ${\\bf 1}$ of $S_m$.  The\nfunction $\\MEMB(x,g)$ is polynomial-time computable as checking\nwhether $g\\in S_n$ is in $\\Aut X$ can be done in time polynomial in\n$n$.\n\n\\begin{remark}\n  An $\\FP^{\\SPP}$ algorithm for $\\FINDGROUP$ allows us to show at one\n  stroke that, apart from GI, several other permutation group problems\n  are in SPP. In particular, we show in the next section that the\n  hidden subgroup problem for permutation groups has an $\\FP^{\\SPP}$\n  algorithm.\n\\end{remark}\n\n\\begin{thm}\\label{maintheorem}\n  There is an $\\FP^{\\SPP}$ algorithm for the $\\FINDGROUP$ problem.\n\\end{thm}\n\n\\begin{pf} \n  Let $\\angle{x,0^n}$ be an input instance of $\\FINDGROUP$. The goal\n  is to compute a strong generator set for $G_x\\leq S_n$ using \\MEMB\\ \n  as subroutine. As we have fixed the input, we will sometimes drop\n  the subscript and write $G$ instead of the group $G_x$.\n  \n  Our goal is to design an $\\FP^{\\SPP}$ algorithm for finding the\n  coset representatives of $G^{(i)}$ in $G^{(i-1)}$ for each $i$ in the\n  tower of subgroups ${\\bf 1}=G^{(n-1)}\\leq G^{(n-2)}\\leq\\ldots\\leq\n  G^{(1)}\\leq G^{(0)}=G$. Starting with $G^{(n-1)}$, which is trivial, the\n  algorithm will build a strong generator set for $G^{(i)}$ in decreasing\n  order of $i$ until finally it computes a strong generator set for\n  $G^{(0)}=G$. Thus, it suffices to describe how the algorithm will\n  compute the coset representatives of $G^{(i)}$ in $G^{(i-1)}$ assuming\n  that a strong generator set for $G^{(i)}$ is already computed.\n\n  We first introduce a definition and notation. A \\emph{partial\n    permutation} on the set $[n]$ is an injective function $\\pi:\n  I\\longrightarrow [n]$, where the domain $I$ of $\\pi$ is a subset of\n  $[n]$. Thus, $\\pi$ is any function that can be extended to a\n  permutation in $S_n$. We say that a partial permutation $\\varphi$\n  \\emph{extends} $\\pi$ if the domain of $\\varphi$ contains $I$ and\n  $i^\\varphi=i^\\pi$ for all $i\\in I$. Let $\\pi:I\\longrightarrow [n]$\n  be a partial permutation and let $i\\in[n]\\setminus I$. We denote by\n  $\\pi[i\\mapsto j]$ the unique partial permutation that extends $\\pi$\n  to the domain $I \\cup\\{i\\}$ by mapping $i$ to $j$.\n\n  For a subgroup $H\\leq S_n$ and $g\\in S_n$ let $\\lexleast(Hg)$ denote\n  the lexicographically least permutation in the coset $Hg$. We next\n  define a language in NP to which our main algorithm will make\n  UP-like queries:\n\\begin{eqnarray*}\n  L & = & \\{\\angle{x,0^n,S,i,j,\\pi}\\mid S\\subseteq G^{(i)}_x, \n  \\pi\\textrm{ is a partial permutation that fixes}\\\\ \n  & & \\textrm{each of }1,\\ldots,i-1\\textrm{ and }i^\\pi = j,\\textrm{ and there is a } \n  g\\in G_x^{(i-1)}\\textrm{ such that } g\\\\\n  & &  \\textrm{ extends }\\pi \\textrm{ and } g=\\lexleast(\\angle{S}g)\\}.\n\\end{eqnarray*}\nPartial permutation $\\pi$ is part of instance\n$\\angle{x,0^n,S,i,j,\\pi}$, as we will use $L$ as an oracle to do a\nprefix search for the lexicographically least $g\\in G_x^{(i-1)}$ such\nthat $i^g=j$. We now describe an NP machine $N$ that accepts $L$.\n\\begin{tabbing}\n\\quad \\=\\quad \\=\\quad     \\kill\n{\\bf Description of Machine $N$ };\\\\\n\\KW{Input:} $\\angle{x,0^n,S,i,j,\\pi}$;\\\\\nVerify using MEMB that $S\\subseteq G_x^{(i)}$;\\\\\n\\> Guess $g \\in S_n$;\\\\\n\\> \\> \\KW{if} $g\\in G_x^{(i-1)}$ and $i^g=j$ and $g$ extends $\\pi$ and $g = \\lexleast(\\angle{S}g)$ \\\\\n\\> \\>        \\KW{then} ACCEPT\\\\\n\\>\\>        \\KW{else} REJECT;\\\\\n\\end{tabbing}\nClearly, $N$ is an NP machine that accepts $L$. The crucial point is\nthat if $i^g=j$ then for every element $h\\in\\angle{S}g$, $i^h=j$.\nAlso, using the algorithm in Theorem~\\ref{lexleast} the\nlexicographically least element of $\\angle{S}g$ can be computed in\npolynomial time.\n\n\\begin{claim}\\label{claim2}\n  If $\\angle{S}=G^{(i)}$ then the number of accepting paths of $N$ on\n  input $\\angle{x,0^n,S,i,j,\\pi}$ is either $0$ or $1$. In general, on\n  input $\\angle{x,0^n,S,i,j,\\pi}$, $N$ has either $0$ or\n  $\\frac{|G^{(i)}|}{|\\angle{S}|}$ accepting paths.\n\\end{claim}\n\n\\begin{claimproof} Suppose $\\angle{x,0^n,S,i,j,\\pi}\\in L$ and\n  $\\angle{S}=G^{(i)}$. Notice that if for some $g\\in G^{(i-1)}$ we\n  have $i^g=j$ (for $j>i$), then $\\angle{S}g$ consists of all elements\n  in $G^{(i-1)}$ that map $i$ to $j$. Thus the unique guess in $S_n$\n  made by $N$ that leads to acceptance is the lexicographically least\n  element of $\\angle{S}g$. On the other hand, if $\\angle{S}$ is a\n  proper subgroup of $G^{(i)}$ then $G^{(i)}g$ can be written as a\n  disjoint union of $|G^{(i)}|/|\\angle{S}|$ many right cosets of\n  $\\angle{S}$.  Thus, in general $N$ would have\n  $|G^{(i)}|/|\\angle{S}|$ many accepting paths if\n  $\\angle{x,0^n,S,i,j,\\pi}$ is in $L$.\n\\end{claimproof}\n\nWe are now ready to describe an $\\FP^L$ algorithm for $\\FINDGROUP$.\nThe algorithm is designed so it queries $L$ for a\n$\\angle{x,0^n,S,i,j,\\pi}$ {\\em only if} $\\angle{S}=G^{(i)}$, thereby\nensuring that it makes only UP-like queries to $L$. Finally, by\nLemma~\\ref{KST-cor} we can convert this algorithm to an $\\FP^{\\SPP}$\nalgorithm.\n  \n\\begin{tabbing}\n\\quad \\=\\quad \\=\\quad \\=\\quad \\=\\quad       \\kill\n(* $\\FP^L$ algorithm CONSTRUCT($\\angle{x,0^n}$  *);\\\\\n$C_i := \\emptyset$ for every $0 \\leq i \\leq n-2$;\\\\\n(* $C_i$ will finally be a complete set of coset representatives of \n         $G^{(i+1)}$ in $G^{(i)}$ *).\\\\\n$D_i := \\emptyset$ for every $0 \\leq i \\leq n-2$;\\\\\n$D_{n-1}=1$;\\\\\n(* $D_i$ will finally be a strong generator set for $G^{(i)}$\n        for each $i$. *)\\\\\n\\> \\KW{for} $i := n - 1$ \\KW{downto} $1$\\\\\n\\> \\>  (* $D_i$ is already computed at the beginning of the $\\th{i}$ iteration\\\\\n\\> \\>  and at the end of the $\\th{i}$ iteration we have $D_{i-1}$ *)\\\\\n\\> \\>   Let $\\pi:[i-1] \\rightarrow [n]$ be the partial permutation\\\\ \n\\> \\>   that fixes all elements from $1$ to $i-1$; \\\\\n\\> \\>  (* in case $i = 1$ this is the everywhere undefined partial \npermutation *)\\\\\n\\> \\> \\>  \\KW{for} $j := i+1$ \\KW{to} $n$\\\\\n\\> \\> \\>   $\\pi' := \\pi[i \\mapsto j]$;\\\\\n\\> \\> \\> (* $\\pi'$ extends $\\pi$ to $[i]$ by mapping $i$ to $j$ *)\\\\\n\\> \\> \\> \\KW{if} $\\angle{x,0^n,D_i,i,j,\\pi'} \\in L$ \\KW{then}\\\\\n\\> \\> \\> (* There is an element in $G^{(i-1)}$ that maps $i$ to $j$. We will find\\\\\n\\> \\> \\>   it by a prefix search that extends the partial permutation $\\pi'$ *)\\\\\n\\> \\> \\>  \\KW{for} $k := i+1$ \\KW{to} $n$\\\\\n\\> \\> \\> \\> find the element $\\ell$ not in the range of $\\pi'$ such that\\\\\n\\> \\> \\> \\> $\\angle{x,0^n,D_{i},i,j,\\pi'[ k \\mapsto \\ell]} \\in L$;\\\\\n\\> \\> \\> \\> $\\pi' := \\pi'[ k \\mapsto \\ell ]$;\\\\\n\\> \\> \\> \\> (* At this point $\\pi'$ will be a permutation in $S_n$ *)\\\\\n\\> \\> \\> \\KW{endfor}\\\\\n\\> \\> \\> $C_{i-1}:= C_{i-1} \\cup \\{\\pi'\\}$;\\\\\n\\> \\> \\> \\KW{endif}\\\\\n\\> \\>  \\KW{endfor}\\\\\n\\> \\> (* At this point $C_{i-1}$ is a complete set of coset\\\\\n\\> \\>  representatives of $G^{(i)}$ in $G^{(i-1)}$ *)\\\\\n\\>                 $D_{i-1} = D_i \\cup C_{i-1}$;\\\\\n\\KW{Output} {$D_0$}\n\\end{tabbing}\n        \nWe claim that a call to the $\\FP^L$ algorithm\nCONSTRUCT($\\angle{x,0^n}$) outputs a strong generator set $D_0$ for\nthe group $G=G_x$. We show this by induction. Initially, $D_{n-1}=1$\nclearly generates $G^{(n-1)}={\\bf 1}$. Suppose at the beginning of the\n$\\th{i}$ iteration it holds that $D_i$ is a strong generator set for\n$G^{(i)}$. It suffices to show that at the end of the $\\th{i}$\niteration $D_{i-1} = D_i \\cup C_{i-1}$ is a strong generator set for\n$G^{(i-1)}$.  For each $j: i+1\\leq j\\leq n$, the query\n$\\angle{x,0^n,D_i,i,j,\\pi'} \\in L$ checks if there is an element in\n$G^{(i-1)}$ that maps $i$ to $j$. The subsequent prefix search with\nqueries to $L$ computes the lexicographically least element in\n$G^{(i-1)}$ that maps $i$ to $j$.  Furthermore, by Claim~\\ref{claim2},\nas $D_i$ generates $G^{(i)}$, all queries made to $L$ are UP-like.\nThus, at the end of the $\\th{i}$ iteration $C_{i-1}$ is a complete set\nof coset representatives for $G^{(i)}$ in $G^{(i-1)}$ and hence\n$D_{i-1}$ is a strong generator set for $G^{(i-1)}$.  Thus at the end\n$D_0$ is a a strong generator set for $G$. Therefore, we have an\n$\\FP^L$ algorithm problem for $\\FINDGROUP$.\n\nFinally, since the $\\FP^L$ algorithm makes only UP-like queries to the\nNP oracle $L$, it follows from Lemma~\\ref{KST-cor} that $\\FINDGROUP$\nhas an $\\FP^{\\SPP}$ algorithm. \\qed\n\\end{pf}\n\n\\begin{remark}\n  Let UPSV denote the class of functions\n  $f:\\Sigma^*\\longrightarrow\\Sigma^*$ for which there is a\n  nondeterministic polynomial-time transducer $M$ that on each input\n  $x$ has a \\emph{unique} accepting path on which it outputs $f(x)$.\n  We note that using UPSV there is alternative description of our\n  $\\FP^{\\SPP}$ algorithm for $\\FINDGROUP$: we can first design an\n  $\\UPSV^{\\SPP}$ algorithm, where the prefix search that we do in\n  CONSTRUCT($\\angle{x,0^n}$) is replaced by directly guessing a\n  permutation in the right coset (consisting of elements that fix $1$\n  to $i-1$ and map $i$ to $j$) and rejecting along all paths on which\n  we do not guess the lexicographically least element of the coset.\n  Then, by a general prefix search argument we can see that\n  $\\FP^{\\SPP}$ and $\\UPSV^{\\SPP}$ are the same and hence conclude that\n  $\\FINDGROUP$ is in $\\FP^{\\SPP}$.\n\\end{remark}\n\nAs we already noted, $\\GI$ and $\\AUTO$ are polynomial-time equivalent\nand $\\AUTO$, being an instance of $\\FINDGROUP$ has an $\\FP^{\\SPP}$\nalgorithm by Theorem~\\ref{maintheorem}. Since $\\SPP^{\\SPP}=\\SPP$ and\n$\\SPP\\subseteq\\ModkP$ for each $k\\geq 2$, the next corollary is an\nimmediate consequence.\n\n\\begin{cor}\n  Graph Isomorphism is in $\\SPP$ and hence in $\\ModkP$ for every\n  $k\\geq 2$.\n\\end{cor}\n\n\\section{Hidden subgroup problem}\\label{hsp-section}\n\nWe recall the general definition of the hidden subgroup problem.\n\n\\begin{defn}\\label{hsp}\n  The {\\em hidden subgroup problem} \\HSP\\ has an input instance a\n  finite group $G$ (presented by a finite generator set) and we are\n  given (in the form of an oracle) a function $f$ from $G$ to some\n  finite set $X$ such that $f$ is constant and distinct on different\n  right cosets of a hidden subgroup $H$ of $G$. The problem is to\n  determine a generator set for $H$.\n\\end{defn}\n\nMany natural problems like Graph Isomorphism, Integer Factoring etc,\ncan be cast as a special case of \\HSP. An efficient quantum algorithm\nfor the general problem will result in efficient quantum algorithm for\nall these. Based on suitable generalizations of Shor's technique\n\\cite{shor97polynomialtime}, the above problem has efficient quantum\nalgorithms for the case when $G$ is an abelian group (see\ne.g.~\\cite{moscaphd} for an exposition).  However, the status of\n$\\HSP$ is open for general nonabelian groups, except for some special\ncases where it is settled (see, e.g.\\\n\\cite{hallgren00normal,ivanyos01efficient}). In particular, even when\nwe restrict attention to $G$ being the permutation group $S_n$, it is\nnot known if $\\HSP$ has quantum polynomial time algorithms except in\nspecial cases.\n\nIndependently, it is shown by Fortnow and Rogers \\cite{fortnow98complexity} \nthat the class BQP of languages that have polynomial-time quantum algorithms is\nclosely connected with language classes that are low for PP. In\nparticular, it is shown in \\cite{fortnow98complexity} that $\\BQP\\subseteq\\AWPP$\nwhere AWPP is a language class that generalizes both BPP and LWPP.\n\n\\begin{thm}{\\rm\\cite{fortnow98complexity}}\n$\\BQP\\subseteq\\AWPP$ and hence $\\BQP$ is low for $\\PP$.\n\\end{thm}\n\nIn this section we show as a corollary to Theorem~\\ref{maintheorem}\nthat there is an $\\FP^{\\SPP}$ algorithm for the $\\HSP$ problem over\npermutation groups.\n\n\\begin{thm}\n  There is an $\\FP^{\\SPP}$ algorithm for the $\\HSP$ problem over\n  permutation groups, and hence $\\HSP$ over permutation groups is low\n  for $\\PP$, $\\GapP$, $\\ParityP$, $\\CeqP$ etc.\n\\end{thm}\n\n\\begin{pf}\n  We are given (in the form of an oracle) a function $f$ from $S_n$ to\n  a finite set $X$ such that $f$ is constant and distinct on different\n  right cosets of a hidden subgroup $H$ of $S_n$. The $\\FP^{\\SPP}$\n  will first compute $f(1)$ with one query to $f$. Now, notice that\n  $f$ gives a membership test for the unknown subgroup $H$, because a\n  permutation $g\\in S_n$ is in $H$ if and only if $f(g)=f(1)$. Thus we\n  essentially have a membership test as required for the $\\FINDGROUP$\n  problem of Theorem~\\ref{maintheorem}. The result now follows by\n  invoking the algorithm described in the proof of\n  Theorem~\\ref{maintheorem}. Lowness for PP also follows as SPP is low\n  for PP. \\qed\n\\end{pf}\n\nUsing the $\\FP^{\\SPP}$ algorithm for the $\\FINDGROUP$ problem we can\nshow that other algorithmic problems on permutation groups \n\\cite{luks93permutation} which are not known to have polynomial-time algorithms\nare also in SPP. Among the different problems mentioned in\n\\cite{luks93permutation} we pick the following two examples as most other \nproblems are known to be polynomial time reducible to these.\n\nThe input instance to the $\\CONJGP$ problem consists of three\nsubgroups $\\angle{S}=G$, $\\angle{S_1}=H_1$, and $\\angle{S_2}=H_2$ of\n$S_n$, and the problem is to determine if there is a $g\\in G$ such\nthat $gH_1g^{-1}=H_2$ (i.e.\\ $H_1$ and $H_2$ are $G$-conjugate).\n\nA closely related problem $\\NORM$ has input instance two subgroups $G$\nand $H$ of $S_n$, and the problem is to determine a generator set for\nthe normalizer subgroup $N_G(H)=\\{g\\in G\\mid gHg^{-1}=H\\}$. Just as\n\\GI\\ and \\AUTO\\ are polynomial-time equivalent, it turns out that\n$\\CONJGP$ and $\\NORM$ are also polynomial-time equivalent\n\\cite{luks93permutation}.\n\n\\begin{thm}\n  The problem $\\NORM$ is in $\\FP^{\\SPP}$ and $\\CONJGP$ is in $\\SPP$.\n\\end{thm}\n\n\\begin{pf}\n  We show that $\\NORM$ is an instance of $\\FINDGROUP$. The theorem\n  will follow as a direct consequence of Theorem~\\ref{maintheorem}. It\n  suffices to observe that given subgroups $\\angle{S}=G$ and\n  $\\angle{T}=H$ of $S_n$, testing if $g\\in N_G(H)$ (i.e.\\\n  $gHg^{-1}=H$) can be carried out in polynomial time.  More\n  precisely, it is clear that $gHg^{-1}=H$ if and only if $gtg^{-1}\\in\n  H$ for every $t\\in T$, which can be checked in polynomial time by\n  Theorem~\\ref{perm-group-algos}. \\qed\n\\end{pf}\n\nAs already mentioned, a consequence of the above theorem is that\nseveral other decision problems in permutation groups (e.g.\\ coset\nintersection, double coset equality, set transporter) which are\npolynomial-time many-one reducible to $\\CONJGP$ are also in $\\SPP$.\n\n\\section{Parallel queries to NP}\n\nIn this section we discuss an application of our main theorem\nTheorem~\\ref{maintheorem} to a different problem concerning Graph\nIsomorphism.\n\nWe first recall the definitions of two important function classes.\nLet $\\FP^{\\NP}_{||}$ denote the class of functions computable in\npolynomial time with \\emph{parallel} queries to an NP oracle.\nLikewise, let $\\FP^{\\NP}[\\log]$ denote the class of functions\ncomputable in polynomial time with \\emph{logarithmically many}\nadaptive queries to an NP oracle. In contrast to the decision problem\nsetting where $\\p^{\\NP}_{||}=\\p^{\\NP}[\\log]$, it is believed to be\nunlikely that $\\FP^{\\NP}_{||}=\\FP^{\\NP}[\\log]$. Indeed, it is shown in\n\\cite{ESY84,S94,B95} that $\\FP^{\\NP}_{||}=\\FP^{\\NP}[\\log]$ implies\n$\\NP=\\RP$. It is useful to recall the proof of this result. Let $\\SAT$\ndenote the set of satisfiable Boolean formulas. The key idea in the\nproof is that given a boolean formula $F$ with a unique satisfying\nassignment, the satisfying assignment can be computed in\n$\\FP^{\\NP}_{||}$. Thus, if $\\FP^{\\NP}_{||}=\\FP^{\\NP}[\\log]$, we can\nfind a satisfying assignment of $F$ in polynomial time by enumerating\nthe polynomially many candidates (given by all possible answers to the\nlogarithmically many queries) and testing. Since SAT is randomly\nmany-one reducible to USAT (the set of boolean formulas with unique\nsatisfying assignment), the collapse result\n$\\FP^{\\NP}_{||}=\\FP^{\\NP}[\\log]$ implies $\\NP=\\RP$ follows.\n\nA question that has remained open is whether we can derive the\ncollapse $\\NP=\\p$ from the same assumption. The paper by Jenner and\nTor\\'an \\cite{JT95} contains a detailed investigation of this\nquestion. \n\nIn general, we could ask which problems in NP are in P as a\nconsequence of the assumption $\\FP^{\\NP}_{||}=\\FP^{\\NP}[\\log]$.\nConsider a language $L\\in\\NP$ defined by a set $A$ in $\\p$ and a\npolynomial bound $p$ as follows:\n\\[\nx\\in L \\iff \\exists y\\in \\Sigma^*~:~ |y|\\leq p(|x|) \\textrm{ and }\n\\angle{x,y}\\in A.\n\\]\nGiven an $x\\in L$ the problem of computing a witness $y\\in\\Sigma^*$\nsuch that $|y|\\leq p(|x|)$ and $\\angle{x,y}\\in A$ is the \\emph{search\n  problem} corresponding to $L$. Of course, the search problem depends\non the set $A$. Suppose $L$ has the property that this search problem\ncan be solved in $\\FP^{\\NP}_{||}$. Then, analogous to the discussion\nabove regarding SAT, it is easy to see that\n$\\FP^{\\NP}_{||}=\\FP^{\\NP}[\\log]$ implies that $L$ is in P. Using the\n$\\FP^{\\NP}[\\log]$ machine for the search problem, in polynomial time\nwe can simply enumerate the entire set of polynomially many candidate\nwitnesses and check if there is a $y$ among them such that\n$\\angle{x,y}\\in A$. Thus we have the following.\n\\begin{prop}\\label{prop-ga}\n  Suppose $L\\in\\NP$ has a corresponding search problem that can be\n  solved in $\\FP^{\\NP}_{||}$. Then $\\FP^{\\NP}_{||}=\\FP^{\\NP}[\\log]$\n  implies that $L$ is in $\\p$.\n\\end{prop}\nA natural example for such a language $L$ is the Graph Automorphism\nproblem GA as shown in \\cite{LT92}. Thus,\n$\\FP^{\\NP}_{||}=\\FP^{\\NP}[\\log]$ implies GA is in P \\cite{LT92}.\n\nFor Graph Isomorphism, however, it is open if the search problem can\nbe solved in $\\FP^{\\NP}_{||}$. Thus the above proposition is not\napplicable. Nevertheless, we will show that if\n$\\FP^{\\NP}_{||}=\\FP^{\\NP}[\\log]$ then $\\GI$ is in P as a consequence\nof Theorem~\\ref{maintheorem} and another general proposition similar\nto Proposition~\\ref{prop-ga}.\n\nWe recall the definition of promise problems.\n\n\\begin{defn}{\\rm\\cite{ESY84}}\nA promise problem is a pair of sets (Q,R). A set $L$ is\ncalled a solution of the promise problem (Q,R) if for\nall $x\\in Q$, $x\\in L \\Leftrightarrow x\\in R$.\n\\end{defn}\n \nA promise problem of particular interest is $(1\\SAT,\\SAT)$, where\n$\\oneSAT$ contains precisely those Boolean formulas which have at most\none satisfying assignment. Observe that any solution of the promise\nproblem $(\\oneSAT,\\SAT)$ has to agree with $\\SAT$ in the formulas\nhaving a unique satisfying assignment as well as in the unsatisfiable\nformulas. By the results of Selman \\cite{S94,ESY84} we know that\n$\\FP^{\\NP}_{||}=\\FP^{\\NP}[\\log]$ implies that every solution to the\npromise problem $(\\oneSAT,\\SAT)$ is in $\\p$. \n\n\\begin{prop}\\label{prop-gi}\n  Suppose $L\\in\\NP$ is accepted by a deterministic polynomial-time\n  oracle machine $M$ with access an $\\NP$ oracle $A$ such that $M$\n  makes \\emph{only} UP-like queries to $A$. Then\n  $\\FP^{\\NP}_{||}=\\FP^{\\NP}[\\log]$ implies that $L$ is in $\\p$.\n\\end{prop}\n\n\\begin{pf}\n  Recall that an oracle query $q$ to $A$ is UP-like if the NP machine\n  for $A$ has at most one accepting path on input $q$. Since all\n  oracle queries made by the machine $M$ to NP oracle $A$ are UP-like,\n  we can replace the oracle with any solution to the promise problem\n  $(\\oneSAT,\\SAT)$: let $f$ denote the standard parsimonious reduction\n  from $A$ to $\\SAT$. Then, each query $q$ to $A$ is transformed to a\n  SAT query $f(q)$ which will be correctly answered by any solution to\n  $(\\oneSAT,\\SAT)$. But the promise problem $(\\oneSAT,\\SAT)$ is in P\n  by the assumption $\\FP^{\\NP}_{||}=\\FP^{\\NP}[\\log]$. Thus, it follows\n  that $L$ is also in P. \\qed \n\\end{pf}\n\nWe can now easily derive our claimed result for Graph Isomorphism, and\nHSP for permutation groups.\n\n\\begin{thm}\n  $\\FP^{\\NP}_{||}=\\FP^{\\NP}[\\log]$ implies that the $\\FINDGROUP$\n  problem for permutation groups can be solved in polynomial time.\n  Hence, it follows that $\\FP^{\\NP}_{||}=\\FP^{\\NP}[\\log]$ implies\n  Graph Isomorphism is in $\\p$ and it implies that the hidden subgroup\n  problem for permutation groups is in $\\p$.\n\\end{thm}\n\n\\begin{pf}\n  As a consequence of Theorem~\\ref{maintheorem} it follows that\n  $\\FINDGROUP$ has a polynomial-time oracle algorithm that makes only\n  UP-like queries to an NP oracle $A$. Thus, by\n  Proposition~\\ref{prop-gi} it follows that\n  $\\FP^{\\NP}_{||}=\\FP^{\\NP}[\\log]$ implies $\\FINDGROUP$ can be solved\n  in polynomial time. Consequently, Graph Isomorphism and the hidden\n  subgroup problem for permutation groups are in $\\p$ under the\n  assumption $\\FP^{\\NP}_{||}=\\FP^{\\NP}[\\log]$. \\qed\n\\end{pf}\n\n\\section{Concluding remarks}\n\nIn this paper we have shown that Graph Isomorphism is in $\\SPP$. We\nhave also shown that several other problems on permutation groups are\nin $\\SPP$. All these results are byproducts of the $\\FP^{\\SPP}$\nalgorithm for the problem FIND-GROUP. We would like to know if better\nupper bounds can be shown for the complexity of special cases of graph\nisomorphism especially tournament isomorphism. Specifically, is\ntournament isomorphism in UP? It is known that the automorphisms of a\ntournaments forms a solvable group and has odd order. Can this\nadditional property be somehow exploited?\n\nA related problem is Graph Canonization. Let $f$ be a function from\nthe family of finite graphs, $\\mathcal{G}$, to itself. We say that $f$\nis a \\emph{canonization} if for every $X \\in \\mathcal{G}$, $f(X) \\cong\nX$ and for every $X_1,X_2 \\in \\mathcal{G}$, $f(X_1) = f(X_2)$ iff $X_1\n\\cong X_2$. There is an $O(n^{log n})$ algorithm for Tournament\nIsomorphism by giving a canonization procedure for tournaments\n\\cite{babai83canonical}. The complexity of Graph Canonization is\nintriguing. The only known upper bound for the problem is $\\FP^{\\NP}$.\nIt is known that Graph Isomorphism is polynomial-time reducible to\nGraph Canonization. Is the converse true, at least for tournaments? Is\nGraph Canonization for tournaments low for PP?\n\nIn order to study the complexity of group-theoretic problems in a\ngeneral setting, Babai and others in\n\\cite{babai85matrix,babai88arthur,babai92bounded}, have developed a\ntheory of black-box groups. The main results in\n\\cite{babai85matrix,babai88arthur,babai92bounded} were to put several\nnatural problems in $\\NP\\cap\\coAM$ or $\\AM\\cap\\coAM$. However, lowness\nfor $\\PP$ has been addressed only for the case of \\emph{solvable}\nblack-box groups in \\cite{arvind97solvable,vinodchandran97improved},\nwhere many of these problems are shown to be in $\\SPP$. It is\ninteresting to ask if our approach of showing membership in $\\SPP$ via\nfinding the lexicographically least element in a coset can be\ngeneralized to black-box groups. More precisely, what is the\ncomplexity of finding a\ncanonical element in the right coset of a black-box group?\\\\\n\n\\noindent{\\bf Acknowledgment.}~~We are grateful to the referees for\nuseful remarks and suggestions that have helped improve the\npresentation.\n\n\\bibliographystyle{plain}\n\\bibliography{bib}\n\\end{document}\n", "meta": {"hexsha": "4096db462dc83f5ee7bbaba6c02b000e700213d2", "size": 56006, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "contents/research/publication/Journal/2006-05-16-GI-is-in-SPP/paper.tex", "max_stars_repo_name": "piyush-kurur-pages/website", "max_stars_repo_head_hexsha": "246dfa730328b45b65840ebed3293e96c497aa86", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-04-16T09:55:17.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-16T09:55:17.000Z", "max_issues_repo_path": "contents/research/publication/Journal/2006-05-16-GI-is-in-SPP/paper.tex", "max_issues_repo_name": "piyush-kurur-pages/website", "max_issues_repo_head_hexsha": "246dfa730328b45b65840ebed3293e96c497aa86", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "contents/research/publication/Journal/2006-05-16-GI-is-in-SPP/paper.tex", "max_forks_repo_name": "piyush-kurur-pages/website", "max_forks_repo_head_hexsha": "246dfa730328b45b65840ebed3293e96c497aa86", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-10T22:18:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T22:18:56.000Z", "avg_line_length": 46.2859504132, "max_line_length": 101, "alphanum_fraction": 0.7002106917, "num_tokens": 18062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961016, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.33117809824366123}}
{"text": "\\subsubsection{Influence of Sliding Window Filter}\n\n\\begin{frame}{Influence of Sliding Window Filter}\n    \\begin{center}\n        \\resizebox {\\textwidth} {!} {\n            \\begin{tabular}{cc}\n                \\resizebox {!} {\\height} {\n                    \\begin{tikzpicture}\n                        \\begin{axis}[\n                            legend pos=north west,\n                            xmin=0.7,\n                            xmax=0.9,\n                            ymin=0.5,\n                            ymax=0.7,\n                            width=\\axisdefaultwidth,\n                            height=\\axisdefaultwidth,\n                            xlabel=$Precision_{\\mu}$,\n                            ylabel=$Recall_{\\mu}$,\n                            samples=100]\n                            \\addplot[blue, mark=o, only marks] table {../data/fig/sliding_window_filter_result/lnce.dat};\n                            \\addlegendentry{LNCE}\n                            \\addplot[red, mark=triangle, only marks] table {../data/fig/sliding_window_filter_result/var.dat};\n                            \\addlegendentry{VAR}\n                            \\addplot[black, mark=square, only marks] table {../data/fig/sliding_window_filter_result/nofilter.dat};\n                            \\addlegendentry{No Filter}\n                            \\addplot[gray, domain=0.31:1] {(0.6 * x) / (2 * x - 0.6)};\n                            \\addplot[gray, domain=0.36:1] {(0.7 * x) / (2 * x - 0.7)};\n                        \\end{axis}\n                    \\end{tikzpicture}\n                } &\n                \\resizebox {!} {\\height} {\n                    \\begin{tikzpicture}\n                        \\begin{axis}[\n                            xmin=0,\n                            xmax=1,\n                            ymin=0,\n                            ymax=1,\n                            width=\\axisdefaultwidth,\n                            height=\\axisdefaultwidth,\n                            xlabel=$Precision_{\\mu}$,\n                            ylabel=$Recall_{\\mu}$,\n                            samples=100]\n                            \\addplot[blue, mark=o, only marks] table {../data/fig/sliding_window_filter_result/lnce.dat};\n                            \\addplot[red, mark=triangle, only marks] table {../data/fig/sliding_window_filter_result/var.dat};\n                            \\addplot[black, mark=square, only marks] table {../data/fig/sliding_window_filter_result/nofilter.dat};\n                            \\addplot[gray, domain=0.051:1] {(0.1 * x) / (2 * x - 0.1)};\n                            \\addplot[gray, domain=0.11:1] {(0.2 * x) / (2 * x - 0.2)};\n                            \\addplot[gray, domain=0.16:1] {(0.3 * x) / (2 * x - 0.3)};\n                            \\addplot[gray, domain=0.21:1] {(0.4 * x) / (2 * x - 0.4)};\n                            \\addplot[gray, domain=0.26:1] {(0.5 * x) / (2 * x - 0.5)};\n                            \\addplot[gray, domain=0.31:1] {(0.6 * x) / (2 * x - 0.6)};\n                            \\addplot[gray, domain=0.36:1] {(0.7 * x) / (2 * x - 0.7)};\n                            \\addplot[gray, domain=0.41:1] {(0.8 * x) / (2 * x - 0.8)};\n                            \\addplot[gray, domain=0.46:1] {(0.9 * x) / (2 * x - 0.9)};\n                        \\end{axis}\n                    \\end{tikzpicture}\n                }\n            \\end{tabular}\n        }\n    \\end{center}\n\\end{frame}\n\n\\input{experiment/evaluation/influence_of_sliding_window_filter/influence_of_blur_factor.tex}\n", "meta": {"hexsha": "2ba07d783316f4bec1786c75c5ba36557edbc9ab", "size": 3504, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "presentation/experiment/evaluation/influence_of_sliding_window_filter.tex", "max_stars_repo_name": "GordonLesti/SlidingWindowFilter", "max_stars_repo_head_hexsha": "22c11f2912a5c523ae8ad85a849e2d0b123536ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-06-22T09:37:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-14T11:43:53.000Z", "max_issues_repo_path": "presentation/experiment/evaluation/influence_of_sliding_window_filter.tex", "max_issues_repo_name": "GordonLesti/SlidingWindowFilter", "max_issues_repo_head_hexsha": "22c11f2912a5c523ae8ad85a849e2d0b123536ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "presentation/experiment/evaluation/influence_of_sliding_window_filter.tex", "max_forks_repo_name": "GordonLesti/SlidingWindowFilter", "max_forks_repo_head_hexsha": "22c11f2912a5c523ae8ad85a849e2d0b123536ec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-11T23:15:57.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-11T23:15:57.000Z", "avg_line_length": 54.75, "max_line_length": 131, "alphanum_fraction": 0.4061073059, "num_tokens": 873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3311780982436612}}
{"text": "\\subsubsection{\\texorpdfstring{The 2\\textsuperscript{nd} Law of Thermodynamics}{The 2nd Law of Thermodynamics}}\nNow that we've gotten through all of that, we can finally talk about the second law of thermodynamics. It states that:\n\\begin{center}\n    \\textbf{The entropy of an isolated system cannot decrease, and will increase if possible.}\n\\end{center}\nOr, put another way, an isolated system will always progress towards a state of maximum entropy. Say you have an isolated system with a few closed systems inside of it. It just so happens that the maximum entropy of the entire isolated system is reached when all the closed systems inside of it are at the same temperature! (The exact reason of why this is the maximum entropy state will be revealed very soon!) This gives us a reason why heat flows from hot to cold, to maximize entropy.\n\\newline\\newline\nI'm going to backtrack a bit here to make a very important point. The proper definition of a reversible process is based on the second law of thermodynamics. A reversible process is one in which the entropy of the isolated system does not change. Since entropy is a function of state, running this process in reverse would also result in no entropy change. So, the second law of thermodynamics allows the process to run in both directions. If the process instead saw the entropy of the system increase, running it in reverse would see the entropy of the system decrease, which violates the second law of thermodynamics. The only truly isolated system is the entire universe\\footnote{Depending on who you ask, maybe not.}, so a process is reversible if and only if it does not change the entropy of the universe.\n\\newline\\newline\nUsing this idea of reversibility, we can see that no macroscopic process be truly reversible. For an isothermal process we can say $\\Delta S \\approx \\frac{Q}{T}$\\footnote{Ask the chemists!}, which clearly isn't zero unless nothing happens at all. Hence, it's not reversible in an isolated system.\n\\newline\\newline\nHowever, we still have some gaps in our understanding regarding entropy. For example, if right now I gave you the current state of a system, you couldn't calculate it's entropy! We've only characterized the \\textit{change} in entropy. That seems silly, so lets fix that.\n", "meta": {"hexsha": "e1a999c3a9869a9afdeae2d1e136e515bbc838e1", "size": 2274, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Entropy/secondlaw.tex", "max_stars_repo_name": "RioWeil/SCIE001-thermo-notes", "max_stars_repo_head_hexsha": "8578248f8f79f5704319dc6cd4ec679ce12b949c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Entropy/secondlaw.tex", "max_issues_repo_name": "RioWeil/SCIE001-thermo-notes", "max_issues_repo_head_hexsha": "8578248f8f79f5704319dc6cd4ec679ce12b949c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Entropy/secondlaw.tex", "max_forks_repo_name": "RioWeil/SCIE001-thermo-notes", "max_forks_repo_head_hexsha": "8578248f8f79f5704319dc6cd4ec679ce12b949c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-30T05:36:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-30T05:36:50.000Z", "avg_line_length": 174.9230769231, "max_line_length": 811, "alphanum_fraction": 0.7955145119, "num_tokens": 498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3311780982436612}}
{"text": "\\documentclass[a4paper]{article}\n\\usepackage[T2A]{fontenc}\n\\usepackage[utf8x]{inputenc}\n\\usepackage{ucs}\n\\usepackage[english]{babel}\n\\usepackage{tikz}\n\\begin{document}\n {\\center{\\huge \\bf Genetic Function Programming}}\n \\section{Type system}\n  GFP use static typing. List of types:\n  \\begin{list}{-}{}\n   \\item BOOL~--- Boolean type. In VM it presents as \\textit{NIL} for FALSE or other value for TRUE. \n   \\item INT~--- Integer type $-2^{16} \\ldots 2^{16}-1$. In VM it presents also as \\textit{INTEGER}.\n   \\item SYM-\\$~--- Symbol. Constant type and present own as value and type. In VM it presents as NIL because doesn't have value.\n   \\item (LIST~\\$1)~--- List type with elements of type \\$1. In VM it presents as LIST with elements of type \\$1 at each head.\n   \\item (PAIR~\\$1~\\$2)~--- Pair of two elements of type \\$1 and \\$2. In VM it presents as LIST with element of type \\$1 at head and type \\$2 at tail.\n   \\item (ANY~\\$1~\\$2)~--- This type can store value of type \\$1 or \\$2. In VM it present as LIST with BOOL at head fro choose type and value at tail.\n   \\item (FUNC~\\$1~\\$2)~--- Function type. $FUNC1 = \\$1 \\rightarrow \\$2$.\n  \\end{list}\n\n \\section{Functions}\n  \\begin{tabular}{|l|p{0.3\\linewidth}|p{0.4\\linewidth}|}\n   \\hline\n    Name & Type & Description \\\\\n   \\hline\n    IF & (FUNC BOOL (FUNC \\$1 (FUNC \\$1 \\$1))) & Return 2nd argument if 1st is TRUE or 3rd if 1st is FALSE. \\\\\n   \\hline\n    EQ & (FUNC \\$1 (FUNC \\$1 BOOL)) & Equal check. \\\\\n   \\hline\n    AND, OR & (FUNC BOOL (FUNC BOOL BOOL)) & Logical binary operations. \\\\\n   \\hline\n    NOT & (FUNC BOOL BOOL) & Logical NOT. \\\\\n   \\hline\n    +, -, * & (FUNC2 INT INT INT) & Ariphmetical operations. \\\\\n   \\hline\n    DIV, MOD & (FUNC2 INT INT (ANY~INT~SYM-DIV-BY-ZERO)) & Safe divergense and module. Return INTEGER if can be evalated or SYM-DIV-BY-ZERO instead. \\\\\n   \\hline\n    <, >, == & (FUNC2 INT INT BOOL) & Comparsion operations. \\\\\n   \\hline\n    MAKE-LIST & (LIST~\\$1) & Return empty list. \\\\\n   \\hline\n    PUSH & (FUNC2 (LIST~\\$1) \\$1 (LIST~\\$1)) & Insert value at start of list. \\\\\n   \\hline\n    HEAD & (FUNC1 (LIST~\\$1) (ANY~\\$1~SYM-EMPTY-LIST)) & Return head of list or SYM-EMPTY-LIST if it empty. \\\\\n   \\hline\n    TAIL & (FUNC1 (LIST~\\$1) (ANY~(LIST~\\$1)~SYM-EMPTY-LIST)) & Return tail of list or SYM-EMPTY-LIST if it empty. \\\\\n   \\hline\n    MAKE-PAIR & (FUNC2 \\$1 \\$2 (PAIR~\\$1~\\$2)) & Make pair from value. \\\\\n   \\hline\n    FIRST & (FUNC1 (PAIR~\\$1~\\$2) \\$1) & Return first element of pair. \\\\\n   \\hline\n    SECOND & (FUNC1 (PAIR~\\$1~\\$2) \\$2) & Return second element of pair. \\\\\n   \\hline\n    MAKE-ANY-FIRST & (FUNC1 \\$1 (ANY~\\$1~\\$2)) & Return ANY type from argument. \\\\\n   \\hline\n    MAKE-ANY-SECOND & (FUNC1 \\$2 (ANY~\\$1~\\$2)) & Return ANY type from argument. \\\\\n   \\hline\n    CHOOSE & (FUNC3 (ANY~\\$1~\\$2) (FUNC1~\\$1~\\$3) (FUNC1~\\$2~\\$3) \\$3) & Eval doings by current type of ANY. \\\\\n   \\hline\n    BIND2 & (FUNC2 (FUNC2~\\$1~\\$2~\\$3) \\$2 (FUNC1~\\$2~\\$3)) & Bind second argument of binary function (first argument can be binded with \\textit{((FUNC2~\\$1~\\$2~\\$3) \\$1) = (FUNC1~\\$2~\\$3)} form). \\\\\n   \\hline\n  \\end{tabular}\n\\end{document}\n", "meta": {"hexsha": "62e14930ad3ad125072459081d066d70891b0f52", "size": 3123, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/gfp.tex", "max_stars_repo_name": "o01eg/gfp", "max_stars_repo_head_hexsha": "49a5becba87ae14f36b3d42190006391d613e03f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-01-22T19:40:23.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-22T19:40:23.000Z", "max_issues_repo_path": "doc/gfp.tex", "max_issues_repo_name": "o01eg/gfp", "max_issues_repo_head_hexsha": "49a5becba87ae14f36b3d42190006391d613e03f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/gfp.tex", "max_forks_repo_name": "o01eg/gfp", "max_forks_repo_head_hexsha": "49a5becba87ae14f36b3d42190006391d613e03f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.796875, "max_line_length": 199, "alphanum_fraction": 0.6151136728, "num_tokens": 1088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.33117808967697426}}
{"text": "\\subsection{Multi instrument analysis}\n\\label{ssec:multi-instrument-analysis}\n\n\\begin{figure*}[t]\n\t\\sidecaption\n\t\\includegraphics[width=0.666\\textwidth]{figures/multi_instrument_analysis.pdf}\n\t\\caption{A multi-instrument analysis of the Crab Nebula}\n\t\\label{fig:multi_instrument_analysis}\n\\end{figure*}\n\n%% should we mention the joint-crab here or in the intro, where we talk about\n%% DL3, multi-instrument analysis and so forth...\n%% cite Laura's DL3 HAWC paper with the updated version of the joint-crab spectrum?\n\nIn this multi-instrument analysis example we showcase the capabilities of \\gammapy\nto perform a simultaneous likelihood fit incorporating data from different instruments\nand at different levels of reduction.\nWe estimate the spectrum of the Crab Nebula combining data from \\fermi, \\magic and \\hawc.\nMaps of \\fermi data are prepared selecting a region of $X^{\\circ}$ around the\nposition of the Crab Nebula applying the same selection criteria of the 3FHL\ncatalog (7 years of data with energy from $10\\,{\\rm GeV}$ to $2\\,{\\rm TeV}$, \\citealt{3FHL}).\n%% shall we explain exactly which type of Map is created?\nThe \\magic data are two observations of $20\\,{\\rm min}$ each, chosen from the\ndataset used to estimate the performance of the upgraded stereo system \\citep{magic_performance}\nand already included in \\cite{joint_crab}. The observations were taken at small\nzenith angles ($<30^{\\circ}$) in wobble mode \\citep{fomin_1994}, with the source\nsitting at an offset of $0.4^{\\circ}$ from the FoV center. Their energy range spans\n$80\\,{\\rm GeV} -- 20\\,{\\rm TeV}$. They are reduced to ON/OFF dataset before being fitted.\n\\hawc flux points data are estimated in \\cite{hawc_crab_2019} with $2.5\\,{\\rm years}$\nof data and span an energy range $300\\,{\\rm GeV} -- 300\\,{\\rm TeV}$, and directly read with \\gammapy.\n\n\\gammapy automatically generates a likelihood including three different types of\nterms. Two poissonian likelihoods: one for the \\fermi map and one for the ON/OFF\ncounts, and a $\\chi^2$ accounting for the flux points. For \\fermi, a\na three-dimensional forward folding of the sky model with the IRF is performed,\nin order to compute the predicted counts in each sky-coordinate and energy bin.\nFor \\magic, a one-dimensional forward folding of the spectral model with the IRF\nis performed to predict the counts in each estimated energy bin.\nA log parabola is fitted to the almost fived decades in energy $10\\,{\\rm GeV} -- 300\\,{\\rm TeV}$.\n%% is the LP formula specified elsewhere?\n\nThe result of the joint fit is displayed in Fig.~\\ref{fig:multi_instrument_analysis}.\nWe remark that the objective of this exercise is illustrative, we display the\nflexibility of \\gammapy in simultaneously fitting multi-isntrument data even at\ndifferent levels of reduction, we do not aim to provide a new measurement of the\nCrab Nebula spectrum.\n\n%% eventual part for physical modelling with naima\n", "meta": {"hexsha": "82ca556a03aea8ae200260f77f3b82703381ed71", "size": 2898, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/text/3-applications-subsections/multi-instrument-analysis.tex", "max_stars_repo_name": "bkhelifi/gammapy-v1.0-paper", "max_stars_repo_head_hexsha": "edb61c092ad90b523282be363150ed6013af0a43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/text/3-applications-subsections/multi-instrument-analysis.tex", "max_issues_repo_name": "bkhelifi/gammapy-v1.0-paper", "max_issues_repo_head_hexsha": "edb61c092ad90b523282be363150ed6013af0a43", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/text/3-applications-subsections/multi-instrument-analysis.tex", "max_forks_repo_name": "bkhelifi/gammapy-v1.0-paper", "max_forks_repo_head_hexsha": "edb61c092ad90b523282be363150ed6013af0a43", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.1428571429, "max_line_length": 101, "alphanum_fraction": 0.773636991, "num_tokens": 754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.33110844528482436}}
{"text": "\\documentclass[aps,twocolumn,twoside,secnumarabic,balancelastpage,amsmath,amssymb,nofootinbib,hyperref=pdftex]{revtex4}\n\n%\\usepackage{lgrind}        \n\\usepackage{chapterbib}    \n\\usepackage{color}         \n\\usepackage{graphics}      \n\\usepackage[pdftex]{graphicx}      \n\\usepackage{longtable}     \n\\usepackage{epsf}          \n\\usepackage{bm}           \n\\usepackage{verbatim}\n\\usepackage{gensymb}\n%\\usepackage{asymptote}     \n%\\usepackage{thumbpdf}\n%\\usepackage{xcolor}\n\\usepackage[colorlinks=true, urlcolor=green]{hyperref}  \n                                       \n\\usepackage{array,tabularx}\n \n\\addtolength\\topmargin{-.5\\topmargin} \n\n\\newenvironment{EqParameters}[1][]\n  {#1 \\begin{tabular}[t]{>{$}l<{$} @{${}={}$} l}}\n  {\\end{tabular}\\\\[\\belowdisplayskip]}\n\n\\begin{document}\n\\title{Ultraviolet and Visible Spectroscopy for Fluids}\n\\author         {Eduardo L. Bemelmans}\n\\email          {eduardo.bemelmans@student.pxl.be}\n\\homepage{https://github.com/PXL-Embedded-AI/repo/tree/master/Spectroscopy}\n\\date{\\today}\n\\affiliation{PXL University of applied sciences and arts, Department PXL-Digital: Electronics-ICT}\n\n\\begin{comment}\n    What effect do impurities have on the outcome ?\n    Calibration? => Supervision is required\n\\end{comment}\n\n\\begin{abstract}\n\n\n\n\\end{abstract}\n\n\\maketitle\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Introduction}\nUV and Vis spectroscopy allows determination of different organic compounds. In particular, fluids absorb light in the UV and visible range. The spectrum of every fluid, like any organic compound, is unique. Within the chemical process technology it is desired to be able to detect a difference in fluids. A UV-Vis spectroscopy measurement apparatus could provide a solution to automate the process of determining fluid deltas. Combined with an embedded AI system, predictions based on the deltas can be made. This document discusses the theory and implementation of UV-Vis spectroscopy for fluids.\n\n\\section{Theory}\n\\subsection{Principle}\n\nThe following equation is known as the grating equation\\cite{geqs}: %Eq.~\\ref{eq:gratingEquation1}\n\\begin{equation}\n   d(\\sin{\\alpha}+\\sin{\\beta})=m\\lambda \n   \\label{eq:gratingEquation1}\n\\end{equation}\nWhere:\n\\begin{EqParameters}\nd    &  spacing between the slits (the grating spacing) \\\\\n\\alpha &  the incident angle \\\\\n\\beta &  the diffraction angle \\\\\nm    &  the order of the spectrum \\\\\n\\lambda & the wavelength \\\\\n\\end{EqParameters}\n\nThe number of slits per unit of length $N$ is usually specified for diffraction gratings.\nSince\n\\begin{equation}\n   d = \\frac{1}{N}\n   \\label{eq:grSp1}\n\\end{equation}\n\nEq.~\\ref{eq:gratingEquation1} can be rewritten in terms of the number of slits or lines per unit length:\n\n\\begin{equation}\n   \\sin{\\alpha}+\\sin{\\beta}=Nm\\lambda \n   \\label{eq:gratingEquationwrN}\n\\end{equation}\n\nThe angle $\\alpha$ is the angle between the incident light and the normal of the grating, and $\\beta$ is the angle between the diffracted light and the normal of the grating. Notice the plus sign instead of minus in the equation. The incident angle is measured counter-clockwise from the grating normal and the diffraction angle is measured clockwise from the grating normal. This is a sign convention for transmission gratings. The equation governs the angular locations of the diffracted light of wavelength $\\lambda$. In our research project, transmission gratings are used to construct a simple test model as shown in Fig.~\\ref{fig:tr_gr}.\n\n\\begin{figure}[htb]\n\\includegraphics[width=5cm, height=8cm]{tr_gr_angles}\n\\caption{Diffraction by a plane transmission grating. Adapted from \\cite{Palmer2005}.\n\\label{fig:tr_gr}}\n\\end{figure}\n\n\\begin{comment}\nTo simplify the construction of the testmodel, the incident light beam must be parallel to the grating normal. Hence, defining $\\theta = \\beta_{-1}$, Eq.~\\ref{eq:gratingEquation1} reduces to:\n\n\\begin{equation}\n   d\\sin{\\theta}=m\\lambda \n   \\label{eq:gratingEquation2}\n\\end{equation}\n\\end{comment}\n\nThis implies that the the camera must be placed at a specific angle so that it can capture the spectrum of the first order ($m=1$). According to \\cite{mchr} (see: mountings), aligning elements can be used to refine the operation of the spectroscopy meter. Fig.~\\ref{fig:sp_m} shows the setup for a monochromator. The alignment elements used in this setup can also be applied to our spectrometer prototype. From the entrance slit (1), the light diverges to a collimating mirror (2). This mirror reforms the diverging incident light beam to a parallel light beam. The diffraction grating (3) is a reflective grating which reflects and disperses the light beam into different colors (and at an angle, governed by Eq.~\\ref{eq:gratingEquation1}). Since we want to capture the first order spectrum, a camera substitutes the camera mirror (4) in our project. In case a more advanced prototype is required, this setup must be considered. A video \\cite{spwo} shows the operation of this setup.\n\n\\begin{figure}[htb]\n\\includegraphics[width=7cm, height=5cm]{mountings.jpg}\n\\caption{Aligning elements for a monochromator. Adapted from \\cite{mchr}.\n\\label{fig:sp_m}}\n\\end{figure}\n\n\n\\subsection{Implementation}\nFluids can absorb light in the UV and the full (adjacent) visible spectral region. Therefore, the wavelength ranges from around 200 to 740nm. This is a complication as a source lamp which is bright, continuous, and stable across this range is required \\cite{lssp}. For the test model, a tungsten halogen lamp can be used. This lamp however, only covers the visible spectral region. The prototype should be armed with a more advanced source light system as shown in Fig.~\\ref{fig:sw-lssp}. According to \\cite{lssp}, the deuterium lamp is a continuous spectrum light source which is stable in the UV region.  \n\\begin{figure}[htb]\n\\includegraphics[width=6cm, height=5cm]{sw-lssp.jpg}\n\\caption{Switching light sources. Adapted from \\cite{lssp}.\n\\label{fig:sw-lssp}}\n\\end{figure}\n\nFig.~\\ref{fig:testmodel-sketch} shows the setup for the testmodel. It is essential that the camera captures the first order spectrum within its FOV. The case of the sensor must be constructed accordingly.\n\\begin{figure*}[htb]\n\\includegraphics[width=15cm, height=7cm]{Spectroscopy-testmodel.png}\n\\caption{Sketch setup test model.\n\\label{fig:testmodel-sketch}}\n\\end{figure*}\n\\section{Analysis and results}\nTo simplify the construction of the test model, the angle of incidence is zero. Table~\\ref{tab:table1} shows the diffraction angle with respect to the wavelength for the testmodel with a diffraction grating having 600 lines/mm. Table~\\ref{tab:table2} shows the same parameters, however the diffraction grating has 1000 lines/mm. Table~\\ref{tab:table3} again shows the same parameters but in this case, the angle of incidence is $-20\\degree$ and the diffraction grating has 600 lines/mm. All tables show the data for the first order spectrum. \n\nThe results for $\\beta$ from table~\\ref{tab:table1} indicate that the first order spectrum is spread over $\\approx19.50\\degree$, which is well within the FOV of the camera. Table~\\ref{tab:table2} and~\\ref{tab:table3} show that, when $N$ or $\\alpha$ is altered, the spectrum spreads over a wider angle. When $\\alpha=0$, and $N=1000$ the spectrum spreads over $\\approx36.20\\degree$, whereas if $\\alpha=-20\\degree$, and $N=600$, the spectrum spreads over $22.30\\degree$.\n\n\\begin{table}[htb]\n\\caption{\\label{tab:table1}Diffraction angle $\\beta$, where $\\alpha=0$\\degree, $m=1$, and $N=600$ lines per millimeter.}\n\\begin{ruledtabular}\n\\begin{tabular}{ccc}\n&$\\lambda$ (nm) &$\\beta$ (\\degree)\\\\\n\\hline\n%UV      & 200 & 6.89  \\\\\nViolet  & 380 & 13.89 \\\\\nBlue    & 435 & 15.13 \\\\\nCyan    & 500 & 17.46 \\\\\nGreen   & 520 & 18.18 \\\\\nYellow  & 565 & 19.82 \\\\\nOrange  & 590 & 20.73 \\\\\nRed     & 625 & 22.02 \\\\\n        & 740 & 26.36 \\\\\n\\end{tabular}\n\\end{ruledtabular}\n%\\footnotetext[1]{}\n\\end{table}\n\\begin{table}[htb]\n\\caption{\\label{tab:table2}Diffraction angle $\\beta$, where $\\alpha=0$\\degree, $m=1$, and $N=1000$ lines per millimeter.}\n\\begin{ruledtabular}\n\\begin{tabular}{ccc}\n&$\\lambda$ (nm) &$\\beta$ (\\degree)\\\\\n\\hline\n%UV      & 200 & 11.54 \\\\\nViolet  & 380 & 22.33 \\\\\nBlue    & 435 & 25.79 \\\\\nCyan    & 500 & 30 \\\\\nGreen   & 520 & 31.33 \\\\\nYellow  & 565 & 34.40 \\\\\nOrange  & 590 & 36.16 \\\\\nRed     & 625 & 38.68 \\\\\n        & 740 & 47.73 \\\\\n\\end{tabular}\n\\end{ruledtabular}\n%\\footnotetext[1]{}\n\\end{table}\n\\begin{table}[htb]\n\\caption{\\label{tab:table3}Diffraction angle $\\beta$, where $\\alpha=-20$\\degree, $m=1$, and $N=600$ lines per millimeter.}\n\\begin{ruledtabular}\n\\begin{tabular}{ccc}\n&$\\lambda$ (nm) &$\\beta$ (\\degree)\\\\\n\\hline\n%UV      & 200 & 27.52 \\\\\nViolet  & 380 & 34.75 \\\\\nBlue    & 435 & 37.09 \\\\\nCyan    & 500 & 39.94 \\\\\nGreen   & 520 & 40.85 \\\\\nYellow  & 565 & 42.92 \\\\\nOrange  & 590 & 44.11 \\\\\nRed     & 625 & 45.81 \\\\\n        & 740 & 51.82 \\\\\n\\end{tabular}\n\\end{ruledtabular}\n%\\footnotetext[1]{}\n\\end{table}\n\n%bibliograhy.\n\n\\bibliography{spectro-bib}\n\n\\end{document}\n", "meta": {"hexsha": "1f155291d6a343ffb5e9c226aacae6145ef3eedf", "size": 8992, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Spectroscopy/Theory/Spectroscopy/spectro-paper.tex", "max_stars_repo_name": "PXL-Embedded-AI/repo", "max_stars_repo_head_hexsha": "a444ead14146f923b6b858d8323df8e8bf976a0d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-01T06:34:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-01T06:34:52.000Z", "max_issues_repo_path": "Spectroscopy/Theory/Spectroscopy/spectro-paper.tex", "max_issues_repo_name": "PXL-Embedded-AI/repo", "max_issues_repo_head_hexsha": "a444ead14146f923b6b858d8323df8e8bf976a0d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2020-03-04T11:08:02.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-21T00:26:32.000Z", "max_forks_repo_path": "Spectroscopy/Theory/Spectroscopy/spectro-paper.tex", "max_forks_repo_name": "PXL-Embedded-AI/repo", "max_forks_repo_head_hexsha": "a444ead14146f923b6b858d8323df8e8bf976a0d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-09T09:06:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-09T09:06:16.000Z", "avg_line_length": 47.0785340314, "max_line_length": 984, "alphanum_fraction": 0.7227535587, "num_tokens": 2609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.33110843776122734}}
{"text": "\\documentclass[12pt,english]{article}\n\\usepackage{mathptmx}\n\\usepackage[utf8]{inputenc}\n\\usepackage{babel}\n\\usepackage{geometry}\n\\usepackage{color}\n\\usepackage[dvipsnames]{xcolor}\n\\definecolor{byublue}     {RGB}{0.  ,30. ,76. }\n\\definecolor{darkblue}    {RGB}{0.  ,0.  ,139.}\n\\definecolor{dukeblue}    {RGB}{0.  ,0.  ,156.}\n\\geometry{verbose,tmargin=1in,bmargin=1in,lmargin=1in,rmargin=1in}\n\\usepackage{amsmath}\n\\usepackage[authoryear]{natbib}\n\\usepackage{minted}\n\\usepackage{mathtools}\n\\definecolor{bg}{rgb}{0.95,0.95,0.95}\n\\usepackage[backref=page]{hyperref}                                              % Always add hyperref (almost) last\n\\hypersetup{unicode=true,bookmarksnumbered=true,bookmarksopen=true,bookmarksopenlevel=3,\n breaklinks=true,pdfborder={0 0 0},colorlinks,citecolor=darkblue,filecolor=darkblue,linkcolor=darkblue,urlcolor=darkblue,pagebackref=true}\n\\usepackage[all]{hypcap}                                            % Links point to top of image, builds on hyperref\n\\usepackage{breakurl}\n\n\\begin{document}\n\n\\title{Problem Set 5}\n\\author{ECON 6343: Econometrics III\\\\\nProf. Tyler Ransom\\\\\nUniversity of Oklahoma}\n\\date{Due: September 30, 9:00 AM}\n\n\\maketitle\nDirections: Answer all questions. Each student must turn in their own copy, but you may work in groups. Clearly label all answers. Show all of your code. Turn in jl-file(s), output files and writeup via GitHub. Your writeup may simply consist of comments in jl-file(s). If applicable, put the names of all group members at the top of your writeup or jl-file.\n\nYou may need to install and load the following package:\n\\begin{itemize}\n    \\item[~] \\texttt{DataFramesMeta}\n\\end{itemize}\n\nYou will also need to load the following previously installed packages:\n\\begin{itemize}\n    \\item[~] \\texttt{Optim} \n    \\item[~] \\texttt{HTTP} \n    \\item[~] \\texttt{GLM} \n    \\item[~] \\texttt{LinearAlgebra} \n    \\item[~] \\texttt{Random} \n    \\item[~] \\texttt{Statistics} \n    \\item[~] \\texttt{DataFrames} \n    \\item[~] \\texttt{CSV} \n\\end{itemize}\n\\pagebreak\nIn this problem set, we will explore a simplified version of the Rust (1987, \\textit{Econometrica}) bus engine replacement model. Let's start by reading in the data.\n\n\\begin{minted}[bgcolor=bg]{julia}\nusing DataFrames\nusing CSV\nusing HTTP\nurl = \"https://raw.githubusercontent.com/OU-PhD-Econometrics/fall-2021/\nmaster/ProblemSets/PS5-ddc/busdataBeta0.csv\"\ndf = CSV.read(HTTP.get(url).body, DataFrame)\n\\end{minted}\n\n\n\\subsubsection*{Static estimation}\n\n\\begin{enumerate}\n\\item Reshape the data into ``long'' panel format, calling your long dataset \\texttt{df\\_long}. I have included code on how to do this in the \\texttt{PS5starter.jl} file that accompanies this problem set.\n\n\\item The model we would like to estimate is Harold Zurcher's decision to run buses in his fleet. Zurcher's flow utility of running (i.e. not replacing) a bus is\n\\begin{align}\\label{eq:flowutil}\n    u_{1}\\left(x_{1t},b\\right) &= \\theta_0 + \\theta_1 x_{1t} + \\theta_2 b\n\\end{align}\nwhere $x_{1t}$ is the mileage on the bus's odometer (in 10,000s of miles) and $b$ is a dummy variable indicating whether the bus is branded (meaning its manufacturer is high-end). The choice set is $\\{0,1\\}$ where $0$ denotes replacing the engine.\n\nEstimate the $\\theta$ parameters assuming Zurcher is completely myopic. This amounts to estimating a simple binary logit model. (\\textbf{Note:} you may estimate this any way you wish. I would recommend using the \\texttt{GLM} package, but you may also use \\texttt{Optim} with your own log likelihood function.)\n\\end{enumerate}\n\n\n\\subsubsection*{Dynamic estimation}\n\nNow I will walk you through how to estimate the dynamic version of this model using backwards recursion. With discount factor $\\beta$, the differenced conditional value function for running the bus (relative to replacing it) is\n\\begin{align}\\label{eq:condv}\n    v_{1t}\\left(x_{t},b\\right)-v_{0t}\\left(x_{t},b\\right) &= \\theta_0 + \\theta_1 x_{1t} + \\theta_2 b + \\beta \\int V_{t+1}\\left(x_{t+1},b\\right) \\mathrm{d}F\\left(x_{t+1}\\vert x_{t}\\right)\n\\end{align}\nwhere $V_{t+1}$ is the value function and the integral is over transitions in the mileage states $x_{t}$.\n\nWe will approximate the integral with a summation, which means that we will specify a discrete mass function for $f\\left(x_{t+1}\\vert x_{t}\\right)$. This probability mass function depends on the current odometer reading ($x_{1t}$), whether the engine is newly replaced (i.e. $d_{t-1} = 0$), and on the value of another state variable $x_2$ which measures the usage intensity of the bus's route (i.e. high values of $x_2$ imply a low usage intensity and vice versa).  \n\nWe discretize the mileage transitions into 1,250-mile bins (i.e. 0.125 units of $x_{1t}$). We specify $x_2$ as a discrete uniform distribution ranging from 0.25 to 1.25 with 0.01 unit increments.\n\nFormally, we are discretely (but not discreetly!) approximating an exponential distribution: \n\\begin{align}\\label{eq:trans}\nf_{j}\\left(x_{1,t+1}\\vert x_{1,t},x_{2}\\right) &= \\begin{cases}\ne^{-x_2(x_{1,t+1}-x_{1t})}-e^{-x_2(x_{1,t+1}+0.125-x_{1t})} & \\textrm{  if  } j=1 \\textrm{  and  } x_{1,t+1}\\geq x_{1,t} \\\\\ne^{-x_2(x_{1,t+1})}-e^{-x_2(x_{1,t+1}+0.125)} & \\textrm{  if  } j=0 \\textrm{  and  } x_{1,t+1}\\geq 0 \\\\\n0 & \\textrm{ otherwise} \\end{cases}\n\\end{align}\nYou will not need to program \\eqref{eq:trans}; I will provide code for this part.\n\nUnder this formulation, \\eqref{eq:condv} can be written as\n\\begin{align}\\label{eq:condv2}\n\\begin{split}\n    v_{1t}\\left(x_{t},b\\right)-v_{0t}\\left(x_{t},b\\right) &= \\theta_0 + \\theta_1 x_{1t} + \\theta_2 b + \\\\\n    &\\phantom{\\text{===}}\\beta \\sum_{x_{1,t+1}} V_{t+1}\\left(x_{t+1},b\\right)\\left[f_{1}\\left(x_{1,t+1}\\vert x_{1,t},x_{2}\\right) - f_{0}\\left(x_{1,t+1}\\vert x_{1,t},x_{2}\\right)\\right]\n    \\end{split}\n\\end{align}\n\nFinally, we can simplify \\eqref{eq:condv2} since we know that $V_{t+1} = \\log\\left(\\sum_{k} \\exp\\left(v_{k,t+1}\\right)\\right)$ when we assume that unobserved utility is drawn from a T1EV distribution (as we do here):\n\n\\begin{align}\\label{eq:condv3}\n\\begin{split}\n    v_{1t}\\left(x_{t},b\\right)-v_{0t}\\left(x_{t},b\\right) &= \\theta_0 + \\theta_1 x_{1t} + \\theta_2 b + \\\\\n    &\\phantom{\\text{===}}\\beta \\sum_{x_{1,t+1}} \\log\\left\\{\\exp\\left(v_{0,t+1}\\left(x_{t+1},b\\right)\\right)+\\exp\\left(v_{1,t+1}\\left(x_{t+1},b\\right)\\right)\\right\\}\\times\\\\\n    &\\phantom{\\text{===}}\\left[f_{1}\\left(x_{1,t+1}\\vert x_{1,t},x_{2}\\right) - f_{0}\\left(x_{1,t+1}\\vert x_{1,t},x_{2}\\right)\\right]\n    \\end{split}\n\\end{align}\n\nEstimation of our dynamic model now requires two steps:\n\n\\paragraph{Solving the model} First, we need to solve the value functions for a given value of our parameters $\\theta$. The way we do this is by backwards recursion. We know that $V_{t+1} = 0$ in our final period (i.e. when $t=T$). Then we work backwards to obtain the future value at every possible state in our model. This will include many states that do not actually show up in our data.\n\n\\paragraph{Estimating the model} Second, once we've solved the value functions, we use maximum likelihood to estimate the parameters $\\theta$. The log likelihood function in this case is simply\n\\begin{align}\\label{eq:loglike}\n    \\ell &= \\sum_{i=1}^N\\sum_{j=0}^1\\sum_{t=1}^Td_{ijt}\\log P_{ijt}\n\\end{align}\nwhere\n\\begin{align}\\label{eq:ps}\n\\begin{split}\n    P_{i1t} &= \\frac{\\exp\\left( v_{1t}-v_{0t}\\right)}{1+\\exp\\left(v_{1t}-v_{0t}\\right)} \\\\\n    P_{i0t} &= 1-P_{i1t}\n\\end{split}\n\\end{align}\n\n\\begin{enumerate}\n\\setcounter{enumi}{2}\n\\item Now estimate the $\\theta$'s assuming that Zurcher discounts the future with discount factor $\\beta = 0.9$. I will walk you through specific steps for how to do this:\n    \\begin{enumerate}\n        \\item \\textbf{Read in the data} for the dynamic model. This can be found at the same URL as listed at the top of p. 2, but remove the \\texttt{\"Beta0\"} from the CSV filename.\n        \n        Rather than reshaping the data to ``long'' format as in question 1, we want to keep the data in ``wide'' format. Thus, columns \\texttt{:Y1} through \\text{:Y20} should be converted to an array labeled \\texttt{Y} which has dimension $1000 \\times 20$ where $N = 1000$ and $T = 20$. And similarly for columns starting with \\texttt{:Odo} and \\texttt{:Xst}. Variables \\texttt{:Xst*} and \\texttt{:Zst} keep track of which discrete bin of the $f_j$'s the given observation falls into.\n        \n        \\item \\textbf{Construct the state transition matrices}, which are the $f_j$'s in \\eqref{eq:trans}. To do so, simply run the following code:\n        \n        \\begin{minted}[bgcolor=bg]{julia}\nzval,zbin,xval,xbin,xtran = create_grids()\n        \\end{minted}\n        \n        \\texttt{zval} and \\texttt{xval} are the grids defined at the bottom of p. 2, which respectively correspond to the route usage and odometer reading. \\texttt{zbin} and \\texttt{xbin} are the number of bins in \\texttt{zval} and \\texttt{xval}, respectively. \\texttt{xtran} is a (\\texttt{zbin*xbin})$\\times$\\texttt{xbin} Markov transition matrix\\footnote{A Markov transition matrix is a matrix where each row sums to 1 and moving from e.g. column 1 to column 4 within a row gives the probability of moving from state 1 to state 4. Check out the Wikipedia page for more information} that gives the probability of falling into each $x_{1,t+1}$ bin given values of $x_{1,t}$ and $x_2$, according to the formula in \\eqref{eq:trans}.\n        \n        \\item \\textbf{Compute the future value terms} for all possible states of the model. \n        \\begin{itemize}\n            \\item First, initialize the future value array, which should be a 3-dimensional array of zeros. The size of the first dimension should be the total number of grid points (i.e. the number of rows of \\texttt{xtran}). The second dimension should be 2, which is the possible outcomes of \\texttt{:Branded}. The third dimension should be $T+1$.\n            \\item Now write four nested \\texttt{for} loops over each of the possible states:\n            \\begin{itemize}\n                \\item Loop backwards over \\texttt{t} from $T+1$ to 1\n                \\item Loop over the two possible brand states $\\{0,1\\}$\n                \\item Loop over the possible permanent route usage states (i.e. from 1 to \\texttt{zbin})\n                \\item Loop over the possible odometer states (i.e. from 1 to \\texttt{xbin})\n            \\end{itemize}\n            \\item Inside all of the for loops, make the following calculations\n            \\begin{itemize}\n                \\item Create an object that marks the row of the transition matrix that we need to be looking at (based on the loop values of the two gridded state variables). This will be \\texttt{x + (z-1)*xbin} (where \\texttt{x} indexes the mileage bin and \\texttt{z} indexes the route usage bin), given how the \\texttt{xtran} matrix was constructed in the \\texttt{create\\_grids()} function.\n                \\item Create the conditional value function for driving the bus ($v_{1t}$) based on the values of the state variables in the loop (not the values observed in the data). For example, for the mileage ($x_{1t}$), you should plug in \\texttt{xval[x]} rather than \\texttt{:Odo}.\n                \n                \\medskip\n                \n                The first component of $v_{1t}$ should be the flow utility, which is listed in \\eqref{eq:flowutil}.\n                \n                \\medskip\n                \n                The difficult part of $v_{1t}$ is the discrete summation over the state transitions. For this, you need to grab the appropriate row (and all columns) of the \\texttt{xtran} matrix, and then take the dot product of that with all possible $x_{1t}$ rows of the FV matrix for the given value of $x_{2}$.\n                \n                You should end up with something like\n                \\begin{minted}[bgcolor=bg]{julia}\nxtran[row,:]'*FV[(z-1)*xbin+1:z*xbin,b+1,t+1]\n                \\end{minted}\n                where \\texttt{b} indexes the branded dummy and \\texttt{t} indexes time periods.\\footnote{We need to index by \\texttt{b+1} because \\texttt{b} takes on values 0 or 1, but in Julia it is illegal to reference the 0th element of an array, so element 1 of the index corresponds to \\texttt{b=0} while element 2 of the index corresponds to \\texttt{b=1}.}\n                \\item Now create the conditional value function for replacing the engine ($v_{0t}$). For this, we repeat the same process as with $v_{1t}$ except the $\\theta$'s are normalized to be 0. The code for the expected future value is the same as for $v_{1t}$ with the exception that mileage resets to 0 after replacement, so instead of grabbing \\texttt{xtran[row,:]} we want \\texttt{xtran[1+(z-1)*xbin,:]}.\n                \\item Finally, update the future value array in period $t$ by storing $\\beta\\log\\left(\\exp\\left(v_{0t}\\right)+\\exp\\left(v_{1t}\\right)\\right)$ in the $t$th slice of the 3rd dimension of the array. This will be the new future value term for period $t-1$. Remember to set $\\beta=0.9$\n            \\end{itemize}\n        \\end{itemize}\n        \n        \\item \\textbf{Construct the log likelihood} using the future value terms from the previous step and only using the observed states in the data. This will entail a \\texttt{for} loop over buses and time periods.\n        \\begin{itemize}\n            \\item Initialize the log likelihood value to be 0. (We will iteratively add to it as we loop over observations in the data)\n            \\item Create a variable that indexes the state transition matrix rows for the case where the bus has been replaced. This will be the same \\texttt{1+(z-1)*xbin} as in the conditional value function $v_{0t}$ above. However, we need to plug in \\texttt{:Zst} from the data rather than a hypothetical value \\texttt{z}.\n            \\item Create a variable that indexes the state transition matrix rows for the case where the bus has not been replaced. This will be the same \\texttt{x + (z-1)*xbin} as in $v_{1t}$ above, except we substitute \\texttt{:Xst} and \\texttt{:Zst} for \\texttt{x} and \\texttt{z}.\n            \\item Now create the flow utility component of $v_{1t}-v_{0t}$ using the actual observed data on mileage and branding.\n            \\item Next, we need to add the appropriate discounted future value to round out our calculation of $v_{1t}-v_{0t}$. Here, we can difference the $f_j$'s as in \\eqref{eq:condv3}. You should get something like\n                \\begin{minted}[bgcolor=bg]{julia}\n(xtran[row1,:].-xtran[row0,:])'*FV[row0:row0+xbin-1,B[i]+1,t+1]\n                \\end{minted}\n            \\item Finally, create the choice probabilities for choosing each option as written in \\eqref{eq:ps} and then create the log likelihood according to the summation in \\eqref{eq:loglike}.\n        \\end{itemize}\n    \\item Wrap all of the code you wrote in (c) and (d) into a function and set up the function so that it can be passed to \\texttt{Optim}. For example, you will need to return the negative of the log likelihood and you will need to have the first argument be the $\\theta$ vector that we are trying to estimate\n    \\item On the same line as the function, prepend the function declaration with the macros so that your code says \\texttt{@views @inbounds function myfun()} rather than \\texttt{function myfun()}. This will give you more performant code. On my machine, it cut the computation time in half.\n    \\item Wrap all of your code in an empty function as you've done with other problem sets\n    \\item Try executing your script to estimate the likelihood function. This took about 4 minutes on my machine when I started from the estimates of the static model in Question 2.\n    \\item Pat yourself on the back and grab a beverage of your choice, because that was a lot of work!\n    \\end{enumerate}\n\n\n\n\n\\end{enumerate}\n\\end{document}\n", "meta": {"hexsha": "7cb57968f53ac368a08d990cebbecba121e2a8de", "size": 15731, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ProblemSets/PS5-ddc/PS5.tex", "max_stars_repo_name": "OU-PhD-Econometrics/fall-2021", "max_stars_repo_head_hexsha": "166049fb97512cc1b6bd5221f17d2d00b084a044", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-07-13T21:06:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T03:03:03.000Z", "max_issues_repo_path": "ProblemSets/PS5-ddc/PS5.tex", "max_issues_repo_name": "OU-PhD-Econometrics/fall-2021", "max_issues_repo_head_hexsha": "166049fb97512cc1b6bd5221f17d2d00b084a044", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-16T16:18:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-18T14:57:48.000Z", "max_forks_repo_path": "ProblemSets/PS5-ddc/PS5.tex", "max_forks_repo_name": "OU-PhD-Econometrics/fall-2021", "max_forks_repo_head_hexsha": "166049fb97512cc1b6bd5221f17d2d00b084a044", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2021-07-20T13:44:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T19:14:13.000Z", "avg_line_length": 76.3640776699, "max_line_length": 730, "alphanum_fraction": 0.6974763206, "num_tokens": 4644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.3311084377612273}}
{"text": "\\documentclass[a4paper]{article}\n\n\\input{temp}\n\n\\setcounter{section}{-1}\n\n\\begin{document}\n\n\\title{Quantum Computation}\n\n\\maketitle\n\n\\newpage\n\n\\tableofcontents\n\n\\newpage\n\n\\section{Introduction}\nasdasd\n\n\\newpage\n\nExercise classes: Sat 3 Nov 11am MR4, Sat 24 Nov 11am MR4, early next term (tba).\\\\\nThursday 8 November lecture is moved to Saturday 10 November 11am (still MR4).\n\n---Lecture 2---\n\n\\section{1}\n\nRecall that we have an oracle $U_f$ for $f:\\Z_M \\to \\Z_\\N$ periodic, with period $r$, $A=M/r$. We want to find $r$ in $O(poly(m))$ time where $m=\\log M$.\n\n\\subsection{The quantum algorithm}\nWork on state space $\\mathcal{H}_M \\otimes \\mathcal{N}$ with basis $\\{|i\\ket |k\\ket\\}_{i \\in \\Z_M, k \\in \\Z_N}$.\\\\\n$\\bullet$ Step 1. Make staet $\\frac{1}{\\sqrt{M}}\\sum_{i=0}^{M-1} |i\\ket|0\\ket$.\\\\\n$\\bullet$ Step 2. Apply $U_f$ to get $\\frac{1}{\\sqrt{M}} \\sum_{i=0}^{M-1} |i\\ket |f(i)\\ket$.\\\\\n$\\bullet$ Step 3. Measure the 2nd register to get a result $y$. By Born rule, the first register collapses to all those $i$'s (and only those) with $f(i)$ equal to the seen $y$, i.e. $i=x_0,x_0+r,...,x_0+(A-1)r$, where $0 \\leq x_0 < r$ in 1st period has $f(m)=y$.\\\\\nDiscard 2nd register to get $|per\\ket = \\frac{1}{\\sqrt{A}} \\sum_{j=0}^{A-1}|x_0+jr\\ket$.\\\\\nNote: each of the $r$ possible function values $y$ occurs with same probability $1/r$, so $0 \\leq x_0 < r$ has been chosen uniformly at random.\\\\\nIf we now measure $|per\\ket$, we'd get a value $x_0+jr$ for uniformly random $j$, i.e. random element $(x_0^{th})$ of a random period $(j^{th})$, i.e. random element of $\\Z_m$, so we could get no information about $r$.\\\\\n$\\bullet$ Step 4. Apply quantum Fourier transform mod $M$ (QFT) to  $|per\\ket$. Recall the definition of QFT: $QFT: |x\\ket \\to \\sum_{y=0}^{M-1} \\omega^{xy} |y\\ket$ for all $x \\in \\Z_M$ where $\\omega = e^{2\\pi i/M}$ is the $M$th root of unity. The existing result is that QFT mod $M$ can be implemented in $O(M^2)$ time.\\\\\nThen we get \n\\begin{equation*}\n    \\begin{aligned}\n    QFT |per\\ket &= \\frac{1}{\\sqrt{MA}} \\sum_{j=0}^{A-1} \\left(\\sum_{y=0}^{M-1} \\omega^{(x_0+jr)y}|y\\ket\\right)\\\\\n    &= \\frac{1}{\\sqrt{MA}} \\sum_{y=0}^{M-1} \\omega^{x_0y} \\left[\\sum_{j=0}^{A-1} \\omega^{jry}\\right] |y\\ket \\ (*)\n    \\end{aligned}\n\\end{equation*}\nwhere we group all the terms with the same $|y\\ket$ together. One good thing is that the sum inside the square bracket is a geometric series, with ratio $\\alpha = \\omega^{ry} = e^{2\\pi iry/M} = (e^{2\\pi i/A})^y$.\\\\\nHence term inside bracket $=A$ if $\\alpha=1$, i.e. $y=kA = k \\frac{M}{r}$, $k=0,1,...,(r-1)$, and equals $0$ otherwise when $\\alpha \\neq 1$. Now\\\\\n\\begin{equation*}\n    \\begin{aligned}\n        QFT |per\\ket = \\sqrt{\\frac{A}{M}} \\sum_{k=0}^{r-1} \\omega^{x_0 k \\frac{M}{r}} |k \\frac{M}{r}\\ket\n    \\end{aligned}\n\\end{equation*}\nThe random shift $x_0$ now appears only in phase, so measurement probabilities are now independent of $x_0$!\n\nMeasuring $QFT |per\\ket$ gives a value $c$, where $c = k_0 \\frac{M}{r}$ with $0 \\leq k_0 \\leq r-1$ chosen uniformly at random. Thus $\\frac{k_0}{r} = \\frac{c}{M}$, note that $c,M$ are known, $r$ is unknown (what we want), and $k_0$ is unknown but uniformly random.\n\nSo note that if we are lucky and get a $k_0$ that is coprime to $r$ then we could just simplify $\\frac{c}{M}$ to get $r$. Obviously we cannot be always lucky every time, but by theorem in number theory, the number of integers $<r$ coprime to $r$ grows as $O(r/\\log\\log r)$ for large $r$, so we know probability of $k_0$ coprime to $r$ is $O(\\frac{1}{\\log\\log r})$.\n\nThen by some probability calculation we know that $O(1/p)$ trials are enough to achieve $1-\\varepsilon$ probability of success.\n\nSo afer Step 4, cancel $c/M$ to the lowest terms $a/b$, giving $r$ as denominator $b$ (if $k_0$ is coprime to $r$). Check $b$ value by computing $f(0)$ and $f(b)$, since $b=r$ iff $f(0) = f(b)$.\n\nRepeating $K=O(\\log\\log r)$ times gives $r$ with any desired probability.\n\nFurther insights into utility of QFT here:\\\\\nWrite $R = \\{0,r,2r,...,(A-1)r\\} \\subseteq \\Z_M$. $|R\\ket = \\frac{1}{\\sqrt{A}} \\sum_{k=0}^{A-1} |kr\\ket$, and $|per\\ket = |x_0 + R\\ket = \\frac{1}{\\sqrt{A}} \\sum_{k=0}^{A-1} |x_0+br \\ket$ where $x_0$ is the random shift that caused problem previously.\\\\\nFor each $x_0 \\in \\Z_M$, consider mapping $k \\to k+x_0$ (shift by $x_0$) on $\\Z_M$, which is a 1-1 invertible map.\n\nSo linear map $U(x_0)$ on $\\mathcal{H}_M$ defined by $U(x_0): |k\\ket \\to |k+x_0\\ket$ is unitary, and $|x_0+R \\ket = U(x_0) |R\\ket$.\n\nSince $(\\Z_M,+)$ is abelian, $U(x_0)U(x_1) = U(x_0+x_1) =U(x_1)U(x_0)$ i.e. all $U(x_0)$'s commute as operators on $\\mathcal{H}_M$.\\\\\nSo we have orthonormal basis of common eigenvectors $|\\chi_k\\ket\\}_{k \\in \\Z_M}$, called \\emph{shift invariant states}.\n\n$U(x_0)|\\chi_k\\ket = \\omega(x_0,k)|\\chi_k\\ket$ for all $x_0,k \\in \\Z_M$ with $|\\omega(x_0,k)| = 1$. Now consider $|R\\ket$ written in $|\\chi\\ket$ basis,\\\\\n$|R\\ket = \\sum_{k=0}^{M-1} a_k | \\chi_k\\ket$ where $a_k$'s depending on $r$ (not $x_0$).\\\\\nThen $|per\\ket = U(x_0) |R\\ket = \\sum_{k=0}^{M-1}a_k \\omega(x_0,k) |\\chi_k\\ket$, and measurement in the $\\chi$-basis has $prob(k) = |a_k \\omega(x_0,k)|^2 = |a_k|^2$ which is independent of $x_0$, i.e. giving information about $r$!\n\n---Lecture 3---\n\n\n\nRecall last time we had $\\mathcal{H}_M$: shift operations $U(x_0) |y \\ket = |y+x_0\\ket$ for $x_0,y \\in \\Z_M$, which all permute, so have a common eigenbasis (shift invariant states) $\\{|\\chi_k\\ket \\}_{k \\in \\Z_M}$, $U(x_0) | x_k\\ket = \\omega(x_0,k) |\\chi_k\\ket$.\\\\\nMeasurement of $|x_0+R \\ket = \\frac{1}{\\sqrt{A}} \\sum_{l=0}^{A-1} |x_0 + l_r \\ket = U(x_0) |R\\ket$ in $|\\chi\\ket$ basis has output distribution independent of $x_0$, therefore gives information about $r$.\n\nIntroduce QFT as the unitary mapping that rotates $\\chi$-basis to standard basis, i.e. define $QFT|\\chi_k \\ket = |k\\ket$. So QFT followed by measurement implements $\\chi$-basis measurement.\n\nExplicit form of $|\\chi_k\\ket$ eigenspaces (!): consider\n\\begin{equation*}\n    \\begin{aligned}\n        |\\chi_k\\ket = \\frac{1}{\\sqrt{M}}\\sum_{l=0}^{M-1} e^{-2\\pi i kl/M}|l\\ket\n    \\end{aligned}\n\\end{equation*}\nThen\n\\begin{equation*}\n    \\begin{aligned}\n        U(x_0) |\\chi_k \\ket &= \\frac{1}{\\sqrt{M}} \\sum_{l=0}^{M-1} e^{-2\\pi i kl/M}|l+x_0\\ket \\\\\n        &= \\frac{1}{\\sqrt{M}} \\sum_{\\tilde{l}=0}^{M-1} e^{-2\\pi i k (\\tilde{l}-x_0)/M} | \\tilde{l} \\ket \\text { where } \\tilde{l} = l+x_0\\\\\n        &= e^{2\\pi i k x_0 / M} \\cdot |\\chi_k\\ket\n    \\end{aligned}\n\\end{equation*}\ni.e. these are the shift invariant staets, eigenvalues $\\omega(x_0,k) = e^{2\\pi i k x_0/M}$.\n\nMatrix of QFT: So\n\\begin{equation*}\n    \\begin{aligned}\n        [QFT^{-1}]_{lk} = \\frac{1}{\\sqrt{M}} e^{-2\\pi i lk/M}\n    \\end{aligned}\n\\end{equation*}\n(componets of $|\\chi_k \\ket = QFT^{-1} |k\\ket$ as $k^{th}$ column). So\n\\begin{equation*}\n    \\begin{aligned}\n        [QFT]_{kl} = \\frac{1}{\\sqrt{M}} e^{2\\pi i lk / M}\n    \\end{aligned}\n\\end{equation*}\nas expected.\n\n\\newpage\n\n\\section{The hidden subgroup problem (HSP)}\n\nLet $G$ be a finite group of size $|G|$. Given (oracle for) function $f:G \\to X$ ($X$ is some set), and promise that there is a subgroup $K < G$ such that $f$ is constant on (left) cosets of $K$ in $G$, and $f$ is distinct on distinct cosets.\\\\\nThe problem: determine the \\emph{hidden subgroup} $K$ (e.g. output a set of generators, or sample uniformly from $K$).\\\\\nWe want to solve in time $O(poly(\\log |G|))$ (an efficient algorithm) with any constant probability $1-\\varepsilon$.\n\nExamples of problems that can be cast(?) as HSPs:\\\\\n(i) periodicity: $f:\\Z_M \\to X$, periodic with period $r$. Let $G=(\\Z_m,+)$, the hidden subgroup is $K=\\{0,r,2r,...\\} < G$, cosets $x_0+K = \\{x_0,x_0+r,x_0+2r,...\\}$. The period $r$ is generator of $K$.\\\\\n(ii) discrete logarithm: for prime $p$, $\\Z_p^* = \\{1,2,...,p-1\\}$ with multiplication mod $p$. $g \\in \\Z_p^*$ is a generator (or primitive root mod $p$). If powers generate all of $\\Z_p^*$, $\\Z_p^* = \\{g^0 = 1,g^1,...,g^{p-2}\\}$, then also $g^{p-1} \\equiv 1 \\pmod p$ (easy number theory).\\\\\nFact: the generator always exists if $p$ is prime. So any $x \\in \\Z_p^*$ can be written $x = g^y$ for some $y \\in \\Z_{p-1}$, write $y=\\log_g x$ called the discrete log of $x$ to base $g$.\n\nDiscrete log problem: given a generator $g$ and $x \\in \\Z^*_p$, compute $y=\\log_g x$ (classically hard).\\\\\nTo express as HSP, consider $f:\\Z_{p-1} \\times \\Z_{p-1} \\to \\Z_p^*$: $f(a,b) = g^a x^{-b} \\ mod \\ p = g^{a-yb} \\ mod \\ p$.\\\\\nThen check: $f(a_1,b_1) = f(a_2,b_2)$ iff $(a_2,b_2) = (a_1,b_1)+\\lambda(y,1)$ where $\\lambda \\in \\Z_{p-1}$.\n\nSo if $G = \\Z_{p-1} \\times \\Z_{p-1}$, $K=\\{\\lambda(y,1):\\lambda \\in \\Z_{p-1}\\} < G$. Then $f$ is constant and distinct on the cosets of $K$ in $G$, and generator $(y,1)$ gives $y=\\log_g x$.\\\\\n\n(iii) graph problems ($G$ non-abelian now): consider undirected graph $A = \\{V,E\\}$, $|V| =n$, with at most one edge between any two vertices. Label vertices by $[n] = \\{1,2,...,n\\}$.\\\\\nIntroduce the permutation group $\\mathcal{P}_n$ of $[n]$. Define $Aut(A)$ to be the group of automorphisms of $A$, which is a subgroup of $\\mathcal{P}_n$, containing exactly the permutations $\\pi \\in \\mathcal{P}_n$ such that for all $i,j \\in [n]$, $(i,j) \\in E \\iff (\\pi(i),\\pi(j)) \\in E$, i.e. the labelled graph $\\pi(A)$ obtained by permuting labels of $A$ by $\\pi$ is the same \\emph{labelled} graph as $A$.\n\nAssociated HSP: Take $G = \\mathcal{P}_n$. Let $X$ be set of all labelled graphs on $n$ vertices. Given $A$, consider $f_A: \\mathcal{P}_n \\to X$ by $f_A(\\pi) = \\pi(A)$, $A$ with labels permuted by $\\pi$. The associated hiiden subroup is $Aut(A) = K$.\n\nApplication: if we can sample uniformly from this $K$, then we can solve graph isomorphism problem (GI): two labelled graphs $A,B$ are isomorphic if there is 1-1 map $\\pi:[n] \\to [n]$ such that for all $i,j \\in [n]$, $i,j$ is an edge in $A$ iff $\\pi(i),\\pi(j)$ is an edge in $B$, i.e. $A$ and $B$ are the same graph but just labelled differently.\n\n---Lecture 4---\n\nLet's come back to the graph isomorphism problem.\n\nProblem: given $A,B$, decide if $A \\cong B$ or not. This can be expressed as anon-abelian HSP (on example sheet), no known classical polynomial time algorithm. However it is in NP, but it is not believed to be NP-complete.\\\\\nRecent result (2017): a quasi-poly time classical algorithm (L.Babai).\n\nQuantum algorithm for finite \\emph{abelian} HSP:\\\\\nWrite group $(G,+)$ additively.\n\nConstruction of shift invariant states and FT for $G$:\\\\\nLet's introduce some representation theory for abelian group $G$. Consider mapping $\\chi:G \\to \\C^* = (\\C \\setminus \\{0\\}, \\cdot)$ satisfying $\\chi(g_1+g_2) = \\chi(g_1)\\chi(g_2)$, i.e. $\\chi$ is a group homomorphism. Such $\\chi$'s are called \\emph{irreducible} representations of $G$.\\\\\nWe have the following properties (without proof), which we'll call Theorem A later when we refer to it:\\\\\n(i) any value $\\chi(g)$ is a $|G|^{th}$ root of unity (so $\\chi$: $G \\to S^1$ = unit circle in $\\C$);\\\\\n(ii) (Schur's lemma, orthogonality): If $\\chi_i$ and $\\chi_j$ are representations, then $\\sum_{g \\in G} \\chi_i (g) \\bar{\\chi}_j(g) =\\delta_{ij}|G|$;\\\\\n(iii) there are always exactly $|G|$ different representations $\\chi$ (well, this is a special case of general representation theory).\n\nBy (iii), we can label $\\chi$'s as $\\chi_g$ for $g \\in G$. For example, $\\chi(g) = 1$ for all $g \\in G$ is always an irreducible representation (the trivial representation), labelled $\\chi_0$;\\\\\nThen by orthogonality (ii) for any $\\chi \\neq \\chi_0$ gives $\\sum_{g \\in G} \\chi(g) = 0$.\n\nShift invariant states: in space $\\mathcal{H}_{|G|}$ with basis $\\{|g\\ket\\}_{g \\in G}$, introduce \\emph{shift operators} $U(k)$ for $k \\in G$ defined by $U(k): |g\\ket \\to |g+k\\ket$. Clearly these all commute, so there is simultaneous eigenbasis:\\\\\nFor each $\\chi_k$, $k\\in G$, consider state $|\\chi_k \\ket = \\frac{1}{\\sqrt{|G|}} \\sum_{g \\in G} \\bar{\\chi}_k (g)|g\\ket$. Then theorem A(ii) implies these form orthonormal basis, and $U(g) |\\chi_k\\ket = \\chi_k(g)|\\chi_k\\ket$.\n\\begin{proof}\n    \\begin{equation*}\n        \\begin{aligned}\n            U(g)|\\chi_k\\ket &= \\frac{1}{\\sqrt{|G|}} \\sum_{h \\in G} \\bar {\\chi_k(h)} |h+g\\ket\\\\\n            &\\stackrel{h'=h+g}{=} \\frac{1}{\\sqrt{|G}} \\sum_{h' \\in G} \\bar{\\chi_k(h'-g)} |h' \\ket\n        \\end{aligned}\n    \\end{equation*}\n    This implies that \n    \\begin{equation*}\n        \\begin{aligned}\n            \\chi_k*-g) = (\\chi_k(g))^{-1} = \\bar{\\chi_k(g)},\\\\\n            \\bar{\\chi_k(h'-g)} = \\bar{\\chi_k(h')}\\bar{\\chi_k(-g)} = \\chi_k(h')\\chi_k(g)\n        \\end{aligned}\n    \\end{equation*}\n    So\n    \\begin{equation*}\n        \\begin{aligned}\n            U(g) | \\chi_k \\ket = \\frac{1}{\\sqrt{|G|}} = \\sum_{h' \\in G} \\chi_k(g) \\bar{\\chi}_k (h') | h' \\ket = \\chi_k (g) | \\chi_k \\ket\n        \\end{aligned}\n    \\end{equation*}\n\\end{proof}\n\nSo $|\\chi_k \\ket$'s are common eigenspaces, called \\emph{shift-invariant states}.\\\\\n    Introduce (define) Fourier transform QFT for group $G$ as the unitary that $QFT|\\chi_g\\ket = |g\\ket$ for all $g \\in G$.\\\\\n    In $|g\\ket-$basis matrices, $k^{th}$ column of $(QFT^{-1}) = $components of $|\\chi_k\\ket$, i.e. $\\frac{1}{\\sqrt{|G|}} \\bar{\\chi_k}(g) = [QFT^{-1}]_{gk}$.\\\\\n    So $[QFT]_{kg}^\\dagger = \\frac{1}{\\sqrt{|G|}}\\chi_k(g)$, and so $QFT|g\\ket = \\frac{1}{\\sqrt{|G|}} \\sum_{k \\in G} \\chi_k (g) |k\\ket$.\n\n\\begin{eg}\n    $G=\\Z_M$. Check $\\chi_a(b) = e^{2\\pi iab/M}$, $a,b \\in \\Z_M$ is a representation.\\\\\n    Similarly, for $G=\\Z_{M_1} \\times ... \\times \\Z_{M_r}$, $(a_1,...,a_r) = g_1, (b_1,...,b_r) = g_2$ where $g_1,g_2 \\in G$, $$\\chi_{g_1}(g_2) \\stackrel{def}{=} e^{2\\pi i \\left(\\frac{a_1b_1}{M_1} + ... + \\frac{a_rb_r}{M_r}\\right)}$$ is a representation of $G$. And we get $$QFT_G =QFT_{M_1} \\otimes ... \\otimes QFT_{M_r}$$ on $\\mathcal{H}_{|G|} = \\mathcal{H}_{M_1} \\otimes ... \\otimes \\mathcal{H}_{M_r}$.\\\\\n    This is exhaustive, since by classification theorem, every finite abelian group $G$ is isomorphic to a direct product of the form $G \\cong \\Z_{M_1} \\times ... \\times \\Z_{M_r}$. Furthermore, we can insist that $M_i$ are prime powers $p_i^{s_i}$, where $p_i$ are not necessarily distinct.\n\\end{eg}\n\nQuantum algorithm for finite abelian HSP:\\\\\nLet $f:G \\to X$, hidden subgroup $K<G$. We have cosets $K=0+K,g_2+K,...,g_m+K$, where $m=|G|/|K|$. State space as usual, with basis $\\{|g\\ket, |x\\ket \\}_{g \\in G, x \\in X}$.\\\\\n$\\bullet$ make the state $\\frac{1}{\\sqrt{|G|}} \\sum_{g \\in G} |g\\ket |0\\ket$;\\\\\n$\\bullet$ Apply oracle $U_f$, get $\\frac{1}{\\sqrt{|G|}} \\sum_{g \\in G} |g\\ket |f(g)\\ket$;\\\\\nmeasure second register to see a value $f(g_0)$.\\\\\nThen first register gives coset state (remember the function is constant on each coset). $|g_0+K \\ket = \\frac{1}{\\sqrt{|K|}} \\sum_{k \\in K} |g_0 + K \\ket = U(g_0) |K\\ket$.\\\\\nApply QFT and measure to obtain result $g \\in G$.\n\n---Lecture 5---\n\nLast time we disccused how to solve the abelian HSP problem. Now how does the output $g$ related to $K$?\\\\\n$\\bullet$ the output distribution of $g$ is independent of $g_0$, so same as that obtained from $QFT|K \\ket$ (i.e. $g_0 = 0$) since:\\\\\nwrite $|K \\ket $ in shift invariant basis $|\\chi_g \\ket$'s, $|K\\ket = \\sum_{g} a_g | \\chi_g \\ket$, then $|g_0+K \\ket = U(g_0) |K\\ket = \\sum a_g \\underbrace{\\chi_g(g_0) | \\chi_g \\ket}_{ = U(g_0) | \\chi_g \\ket}$; but $QFT|\\chi_g \\ket = |g\\ket$, so $Prob(g) = |a_g \\chi_g (g_0)|^2 = |a_g|^2$ as $\\chi_g(g_0)| = 1$.\n\nThus look at $QFT|K \\ket$. Recall $QFT|k \\ket = \\frac{1}{\\sqrt{|G|}} \\sum_{l \\in G} \\chi_l(k) |l\\ket$, so $QFT |K\\ket = \\frac{1}{\\sqrt{|G|}} \\frac{1}{\\sqrt{|K|}} \\sum_{l \\in G} \\left[\\sum_{k \\in K} \\chi_l(k) \\right] |l\\ket$.\\\\\nThe terms in $[...]$ involves irreducible representation $\\chi_l$ of $G$ restricted to subgroup $K < G$, which is an irreducible representation of $K$. Hence \n\\begin{equation*}\n    \\begin{aligned}\n        \\sum_{k \\in K} \\chi_l(k) = \\left\\{\n            \\begin{array}{ll}\n                |K| & \\chi_l \\text{ restricts to trivial irreducible representation on } K\\\\\n                0 & \\text{ otherwise}\n            \\end{array}\n        \\right.\n    \\end{aligned}\n\\end{equation*}\nand\n$$QFT|K\\ket = \\sqrt{\\frac{|K|}{|G|}} \\sum_{l \\in G \\text{ with }\\chi_l\\text{ reducing to trivial irreducible representation of }K} |l\\ket$$\nSo measurement gives a uniformly random choice of $l$ such that $\\chi_l(k) = 1$  for all $k \\in K$.\\\\\ne.g. If $K$ has generators $k_1,k_2,...,k_M$, $M=O(\\log |K|) = O(\\log |G|)$, then output has $\\chi_l(k_i) = 1$ for all $i$.\n\nIt can be shown that if $O(\\log|G|)$ such $l$'s are chosen uniformly at random, then with probability $>2/3$ they suffice to determine a generating set for $K$ via equations $\\chi_l(k) = 1$.\\\\\n(see example sheet 1 for particular examples).\n\n\\begin{eg}\n    If $G = \\Z_{M_1} \\times ... \\times \\Z_{M_q}$.\\\\\n    We had for $l=(l_1,...,l_q)$, $g \\in (b_1,...,b_q) \\in G$,\n    $$\\chi_l(g) = e^{2\\pi i (\\frac{l_1k_1}{M_1} + ... + \\frac{l_qb_q}{M_q})}$$\n    So for $k=(k_1,...,k_q)$, $\\chi_l(k) = 1$ becomes\n    $$\\frac{l_1k_1}{M_1} + ... + \\frac{l_qk_q}{M_q} \\equiv 0 \\pmod 1$$\n    (i.e. is an integer), a homogeneous linear equation on $K$, and $O(\\log |K|)$ is independent such that equations determine $K$ as null space.\n\\end{eg}\n\nSome remarks on HSP for non-abelian groups $G$ (write multiplicatively):\\\\\nAs before, can easily generate coset states \n$$ |g_0 K \\ket = \\frac{1}{\\sqrt{|K|}} \\sum_{k \\in K} |g_0 K\\ket$$\nwhere $g_0$'s are randomly chosen. But problems arise with QFT construction, because now there's no basis of shift-invariant states exists! (this is since $U(g_0)$'s don't commute anymore, so no common full eigenbasis).\n\nConstruction of non-abelian Fourier Transform (some more representation theory):\\\\\n$\\bullet$ $d$-dimensional representation of $G$ is a group homomorphism $\\chi: G \\to U(d)$ where $U(d)$ is the space of $d \\times d$ unitary matrices acting on $\\C^d$, by $\\chi(g_1 g_2) \\chi(g_1)\\chi(g_2)$. (see part II representation theory for the general form)\\\\\n$\\bullet$ $\\chi$ is irreducible representation if no subspace of $\\C^d$ is left invariant under $\\chi(g)$ for all $g \\in G$ (i.e. cannot simultaneously block diagonalise all $\\chi(g)$'s by a basis change).\\\\\n$\\bullet$ a complete set of irreducible representation: set $\\chi_1,...,\\chi_m$ such that any irreducible representation is unitarily equivalent to one of them (equivalence $\\chi \\to \\chi' = V\\chi V^T$).\n\n\\begin{thm} (non-abelian version of theorem A -- properties of representations)\\\\\n    If $d_1,...,d_m$ are dimensions of a complete set of irreducible representations $\\chi_1,...,\\chi_m$, then:\\\\\n    (i) $d_1^2+...+d_m^2 = |G|$;\\\\\n    (ii) Write $\\chi_i(g)_{jk}$ for the $(j,k)^{th}$ entry of matrix $\\chi_i(g)$, where $j,k = 1,...,d_i$. Then (Schur orthogonality):\n    $$\\sum_g \\chi_i(g)_{jk} \\bar{\\chi}_{i'}(g)_{j'k'} = |G| \\delta_{ii'} \\delta{jj'}\\delta{kk'}$$\n    Hence states\n    $$|\\chi_{i,jk} \\ket \\equiv \\frac{1}{\\sqrt{|G|}} \\sum_{g \\in G} \\bar{\\chi}_i(g)_{jk} |g\\ket$$\n    is an orthonomal basis.\n\\end{thm}\n\n$\\bullet$ QFT on $G$ \\emph{defined} to be the unitary that rotates $\\{|\\chi_{ijk}\\ket\\}$ basis into standard basis $\\{|g\\ket\\}$. However, $|\\chi_{ijk}\\ket$ are \\emph{not} shift invariant for all $U(g_0)$'s, and consequently measurement of coset state $|g_0 K\\ket$ in $|\\chi \\ket$-basis gives an output distribution \\emph{not} independent of $g_0$.\n\nHowever, \\emph{partial} shift invariance survives: Consider the incomplete measurement $M_{rep}$ on $|g_0 K\\ket$ that distinguishes only the irreducible representations (i.e. $i$ values) and not all $(i,j,k)$'s.\\\\\ni.e. with measurement outcome $i$ associated to $d_i^2$-dimensional orthogonal subspaces spanned by $\\{|\\chi_{(i),jk}\\ket\\}_{j,k = 1,...,d_i}$.\\\\\nThen $\\chi_i(g_1,g_2) = \\chi_i(g_1) \\chi_i(g_2)$ implies output distribution of $i$ values is independent of $g_0$, giving direct, albeit imcomplete, information about $K$.\\\\\nE.g. conjugate subgroups $K$ and $ = g_0 K g_0^{-1}$ for some $g_0 \\in G$ give \\emph{same} output distribution.\n\n---Lecture 6---\\\\\nNon-abelian HSP/FT remarks:\\\\\nFor efficient HSP algorithm, we also need QFT to be efficiently implementable, i.e. $poly(\\log|G|)$-time.\\\\\nThis is true for any abelian $G$ and some non-ablien $G$'s (such as $\\mathcal{P}_n$), but even in latter case there's no known efficient HSP algorithm.\n\nSome known result:\\\\\nfor normal subgroups, i.e. $gK= Kg$ for all $g \\in G$:\n\\begin{thm} (Hallgrer, Russell, Tashma, SIAM J.Comp 32 p916-934 (2003))\\\\\n    Suppose $G$ has efficient QFT. Then if hidden subgroup $K$ is normal, then there is an efficient HSP quantum algorithm.\\\\\n    (Construct coset state $|g_0 K\\ket$, perform $M_{rep}$ on it.)\\\\\n    Repeat $O(\\log|G|)$ times. Then $K$ normal implies outputs suffice to determine $K$.\n\\end{thm}\n\n\\begin{thm} (Ettinger, Hoyer, Knill)\\\\\n    For general non-abelian HSP, $M=O(poly(\\log|G|))$ random coset states $|g_1K\\ket$,...,$g_M K\\ket$ suffice to determine $K$ from $M$ coset states, but it's not efficient.\\\\\n    See example sheet for a proof -- construct a measurement procedure on $|g_1K\\ket \\otimes ... \\otimes g_MK\\ket$ to determine $K$, but it takes exponential time in $\\log|G|$.\n\\end{thm}\n\nThe phase estimation algorithm:\\\\\n$\\bullet$ a unifying principle for quantum algorithms, uses $QFT_{2^n}$ again.\\\\\n$\\bullet$ many applications, e.g. an alternative efficient factoring algorithm (A.Kitaev).\n\nGiven unitary operator $\\mathcal{U}$ and eigenstate $|v_\\phi \\ket \\cdot \\mathcal{U} | v_{\\phi}\\ket = e^{2\\pi i\\phi} | v_\\phi\\ket$, we want to estimate phase $\\phi$, where $0 \\leq \\phi < 1$ (to some precision, say to $n$ binary digits).\n\nWe'll need \\emph{controlled-$U^k$} for integers $k$, writte $C-U^k$, which satisfies $c-U^k |0\\ket |\\xi\\ket = |0\\ket |\\xi\\ket$, $C-U^k |1\\ket |\\xi\\ket = |1\\ket U^k|\\xi\\ket$, where $|\\xi\\ket$ in general has dimension $d$.\\\\\nNote $U^k |v_\\phi\\ket = e^{2\\pi ik\\phi} | v_\\phi\\ket$, $C-(U^k) = (C-U)^k$.\n\n\\begin{rem}\n    Given $U$ as a formula or (arant?) description, we can readily implement $C-U$, e.g. just control each gate of $U$'s circuit.\\\\\n    However, if $U$ is given as a \\emph{black box}, we need further info:\\\\\n    $\\bullet$ it suffices to have an eigenstate $|\\alpha\\ket$ with known eigenvalue $U|\\alpha\\ket = e^{i\\alpha} |\\alpha\\ket$:\\\\\n    We can consider\n\n    \\includegraphics[scale=0.5]{image/QC_01.png}\n    Where we get $CU|a\\ket |\\xi\\ket$ at the first two row and the third row $|\\alpha\\ket$ is always unchanged.\\\\\n    To see how it works, just check circuit action. (...)\n\\end{rem}\n\nWe'll actually want \\emph{generalised controlled-$U$} with $|x\\ket |\\xi\\ket \\to |x\\ket U^x |\\xi\\ket$, where $|x\\ket$ has $n$ qubits, i.e. $x \\in \\Z_{2^n}$.\\\\\nWe can make this thing from $C-(U^k)$ as follows:\n\n\\includegraphics[scale=0.5]{image/QC_02.png}\n\nWe get $|x\\ket U^x |\\xi\\ket$, where $x=x_{n-1}...x_1x_0$ binary, $U^x = U^{2^{x_{n-1}}} ... U^{2^{x_1}}U^{2^{x_0}}$.\\\\\nNote: if input $|\\xi\\ket = |v_\\phi\\ket$, then get $e^{2\\pi i \\phi x}|v_\\phi\\ket$.\n\nNow suppose over all $x=0,1,...,2^{n-1}$ and use $|\\xi\\ket = |v_\\phi\\ket$,\n\n\\includegraphics[scale=0.5]{image/QC_03.png}\n\nWhere the output is $\\frac{1}{\\sqrt{2^n}} \\sum_x e^{2\\pi i\\phi x} |x\\ket$, we call this state $|A\\ket$.\n\nFinally apply $QFT_{2^n}^{-1}$ to $|A\\ket$ and measure to see $y_0,...,y_{n-1}$ on lines $0,1,...,n-1$. Then output $0.y_0...y_{n-1} = \\frac{y_0}{2}+...+\\frac{y_{n-1}}{2^{n-1}}$, as the estimate of $\\phi$.\\\\\nThat's the phase estimation algorithm (for given $U$ and $V_\\phi\\ket$).\n\nSuppose $\\phi$ actually had only $n$ binary digits, i.e. $\\phi$ exactly equals $0.z_0z_1...z_{n-1}$ for some $z_k=0,1$ for all $k$.\n\nThen $\\phi = \\frac{z_0...z_{n-1}}{2^n} = \\frac{z}{2^n}$ where $z$ is $n$-bit integer in $\\Z_{2^n}$, and\n$$ |A\\ket = \\frac{1}{\\sqrt{2^n}} \\sum_x e^{2\\pi ixz/2^n} |x\\ket$$\n\\emph{is} $QFT_{2^n}$ of $|z\\ket$.\\\\\nSo $QFT^{-1} |A\\ket = |z\\ket$ and get $\\phi$ exactly, with certainty.\\\\\nIn this case the algorithm up to (not including) final measurements is a unitary operation, mapping $|0\\ket ... |0\\ket |v_\\phi \\ket \\to |z_0 \\ket ... |z_{n-1} \\ket |v_\\phi\\ket$.\n\n---Lecture 7---\nPhase Estimation (continued):\\\\\n\n$U$ is a $d \\times d$ unitary operation/matrix with eigenstate $U|v_\\phi \\ket = 2^{2\\pi i\\phi} | v_\\phi \\ket$, and we want to estimate $\\phi$.\\\\\n$U$ as a quantum physical operation is equivalent to $\\tilde{U} = e^{i \\alpha} U$ for any $\\alpha$ and $\\tilde{U}$ has $\\phi \\to \\phi+\\alpha/2\\pi$.\\\\\nSo if $U$ given as quantum physical operation alone, we cannot determine $\\phi$.\\\\\nBut controlled versions different: $C-U$ and $C-\\tilde{U}$ are different as physical operations (set $\\{e^{i\\alpha} C-U\\}_\\alpha \\neq \\{e^{i\\alpha} C-\\tilde{U}\\}_\\alpha$), and $C-U/\\tilde{U}$ \\emph{does} fix $\\phi$ associatied to choice of phase $\\alpha$.\\\\\nSo quantum phase estimation algorithm use $C-U$ ($C-U^{2^k}$) physical operations (not just $U$'s).\n\nWe had $\\underbrace{|0\\ket...|0\\ket}_{n} |v_\\phi\\ket \\stackrel[C-U's]{\\text{unitary}}{\\rightarrow} |A\\ket = \\frac{1}{\\sqrt{2^n}} \\sum_{x=0}^{2^n-1} e^{2\\pi i\\phi x} |x\\ket$ ($n$ qubits).\\\\\nApply $QFT^{-1}$ we get $QFT^{-1}|A\\ket$, measure to see $y_0,...,y_{n-1}$; output $\\phi = \\frac{(y_0y_1...y_{n-1})}{2^n}$, $0 \\leq y < 2^{n-1}$, where the numerator is a $n$-bit integer.\\\\\nIf $\\phi = \\frac{z}{2^n}$ for integer $0 \\leq z < 2^n$, i.e. $\\phi$ has exactly $n$ binary digits, then $|A\\ket = QFT|z\\ket$, so we get $z$ with certainty in the measurement.\n\nNow suppose $\\phi$ has \\emph{more} than $n$ bits, say $\\phi = 0.z_0z_1z_2...z_{n-1} | z_nz_{n+1}...$. Then we have:\n\n\\begin{thm} (PE)\n    If measurement in above algorithm give $y_0,...y_{n-1}$ (so output is $\\theta = 0.y_0...y_{n-1}$), then\\\\\n    (a) $\\P(\\theta$ is closet $n$ binary digit approximate to $\\phi) \\geq {4}{\\pi^2}$;\\\\\n    (b) $\\P(|\\theta-\\phi| \\geq \\varepsilon)$ is at most $P(\\frac{1}{2^n \\varepsilon})$ (we'll show it's at most $\\frac{1}{2^{n+1} \\varepsilon}$).\n\n    \\begin{rem}\n        In (a), we have probability $\\frac{4}{\\pi^2}$ that all $n$ lines of $n$-line QPE process are \\emph{good}.\\\\\n        But, if we want $\\phi$ accurate to $m$ bits with probability $1-\\eta$, then we use theorem (PE) (b) with $\\varepsilon = 1/2^m$. Then we'll use $n>m$ lines with\n        $$\\frac{1}{2^{n+1}} \\varepsilon = \\eta, \\varepsilon = \\frac{1}{2^m}$$\n        i.e. $n=m+\\log(1/\\eta)+1$. In words, number of lines needed is only number of bits wanted with good probability $1-\\eta$ plus a modest polynomial increase for exponetial reduction in $\\eta$.\n    \\end{rem}\n\n    \\begin{proof}\n        We have\n        \\begin{equation*}\n            \\begin{aligned}\n                QFT^{-1}|x\\ket = \\frac{1}{\\sqrt{2^n}} \\sum_{y=0}^{2^n-1} e^{-2\\pi i yx / 2^n} |y\\ket\n            \\end{aligned}\n        \\end{equation*}\n        So\n        \\begin{equation*}\n            \\begin{aligned}\n                QFT^{-1} |A\\ket =\\frac{1}{2^n} \\sum_y \\left[\\sum_x e^{2\\pi i(\\phi - y/2^n)x}\\right] |y\\ket\n            \\end{aligned}\n        \\end{equation*}\n        So for measurement,\n        \\begin{equation*}\n            \\begin{aligned}\n                \\P(\\text{see } n- \\text{ bit integer } y=y_0y_1...y_{n-1}) = \\frac{1}{2^{2n}} \\left|\\sum_{x=0}^{2^n-1} e^{2\\pi i \\underbrace{(\\phi-\\frac{y}{2^n})}_{:=\\delta(y)} x}\\right|^2\n            \\end{aligned}\n        \\end{equation*}\n        Note that this is a geometric series $e^{2\\pi i \\delta(y)}$, so \n        \\begin{equation*}\n            \\begin{aligned}\n                \\P(\\text{see } y) = \\frac{1}{2^{2n}} \\left|\\frac{1-e^{2^n 2\\pi i \\delta(y)}}{1-e^{2\\pi i\\delta(y)}} \\right|^2\n            \\end{aligned}\n        \\end{equation*}\n        Let's call this equation (P) (maybe for \\emph{phase}).\\\\\n        We want to bound/estimate this expression.\\\\\n        For (a): Let $y=a=a_0a_1...a_{n-1}$ give \\emph{closest} $n$-bit approximation to $\\phi$, i.e. $|\\phi-\\frac{a}{2^n}| \\leq \\frac{1}{2^{n+1}}$, i.e. $\\delta(a) \\leq \\frac{1}{2^{n+1}}$.\\\\\n        Now we bounds:\\\\\n        (i) $|1-e^{i\\alpha}| = |2\\sin \\frac{\\alpha}{2}| \\geq \\frac{2}{\\pi} |\\alpha|$ if $|\\alpha| < \\pi$;\\\\\n        (ii) $|1 - e^{2\\pi i \\beta}| \\leq 2\\pi \\beta$.\n\n        In equation (P), use (i) with $\\alpha =2^n \\cdot 2\\pi \\delta(a) \\leq 2^n 2\\pi \\frac{1}{2^{n+1}} \\leq \\pi$ to lower bound top line, and (ii) with $\\beta = \\delta(a)$ to upper bound bottom line, get\n        \\begin{equation*}\n            \\begin{aligned}\n                \\P(\\text{see } a) \\geq \\frac{1}{2^{2n}} \\left(\\frac{2^{n+1}\\delta(a)}{2\\pi \\delta(a)}\\right)^2 = \\frac{4}{\\pi^2}\n            \\end{aligned}\n        \\end{equation*}\n        For (b), we want to upper bound equaiton (P): for top line, $|1-e^{i\\alpha}| \\leq 2$ for any $\\alpha$; for bottom, use (i) get $|1-e^{2\\pi i\\delta(y)} | \\geq 4\\delta(y)$. So\n        \\begin{equation*}\n            \\begin{aligned}\n                \\P(y) \\leq \\frac{1}{2^{2n}} \\left(\\frac{2}{4\\delta(y)}\\right)^2 = \\frac{1}{2^{2n+2}} \\delta(y)^2\n            \\end{aligned}\n        \\end{equation*}\n        Now sum this for all $|\\delta(y)| > \\varepsilon$, $\\delta(y)$ values spaced by $1/2^n$'s. Let $\\delta_+$ be first $\\delta(y)$ (jumps?) with $\\delta(y) \\geq \\varepsilon$, $\\delta_-$ be that with $\\delta(y) \\leq -\\varepsilon$. So $|\\delta_+|,|\\delta_-| \\geq \\varepsilon$.\\\\\n        Then if $|\\delta(y)| \\geq \\varepsilon$, we have $\\delta(y) = \\delta_+ + \\frac{k}{2^n}$, $k=0,1,...$, or $=\\delta_- - \\frac{k}{2^n}$, $k=0,1,...$.\\\\\n        So $|\\delta(y)| \\geq \\varepsilon + \\frac{k}{2^n}$ with $k=0,1,2,...$ in each case.\\\\\n        So\n        \\begin{equation*}\n            \\begin{aligned}\n                \\P(|\\delta(y)| > \\varepsilon) &\\leq 2 \\sum_{k=0}^\\infty \\frac{1}{2^{2n+2}} \\frac{1}{(\\varepsilon+\\frac{k}{2^n})^2}\\\\\n                &\\leq \\frac{1}{2} \\int_0^\\infty \\frac{1}{(2^n \\varepsilon+k)^2} dk\\\\\n                &= \\int_{2^n \\varepsilon}^\\infty \\frac{dk}{k^2}\\\\\n                &= \\frac{1}{2^{n+1} \\varepsilon}\n            \\end{aligned}\n        \\end{equation*}\n    \\end{proof}\n\\end{thm}\n\nFurther remarks on QPE algorithm:\\\\\n(1) If $C-U^{2^k}$ is implemented as $(C-U)^{2^k}$, the QPE algorithm needs exponential time in $n$ as we have $1+2+...+2^{n-1} = 2^n-1$ $(C-U)$ gates.\\\\\nHowever, for some special $U$'s, $C-U^{2^k}$ can be implemented in $poly(k)$ time, so we get a poly time QPE algorithm.\\\\\nIt can be used to provide alternative facoring (order finding) algorithm (due to A. Kitaev) using PE.\n\n---Lecture 8---\n\nFirst exercise class: Saturday 3 Nov 11am MR4.\n\n(2) If instead of $|v_\\phi\\ket$, use general input state $|\\xi\\ket$:\n$$|\\xi \\ket = \\sum_j c_j | v_{\\phi_j}\\ket$$\n$$U|v_{\\phi_j} \\ket = e^{2\\pi i \\phi_j} | v_{\\phi_j} \\ket$$\nThen we get in QPE (before final measurement) a unitary process $U_{PE}$ with (lecturer had \\emph{that}) effect\n$$|0...0\\ket | \\xi\\ket \\xrightarrow{U_{PE}} \\sum_j c_j | \\phi_j\\ket |v_{\\phi_j}\\ket$$\nand final measurement will give a choice of $\\phi_j$'s (or approximation) chosen with probabilities $|c_j|^2$.\n\n\\begin{eg}\n    Implement $QFT_{\\mathcal{Q}}$ for $\\mathcal{Q}$ not a power of $2$, with a quantum curcuit of $1-$ and $2-$ qubit gates of circuit size $O(poly(\\log \\mathcal{Q}))$ (Kitaev's method).\n\\end{eg}\n\n\\begin{rem}\n    For $\\mathcal{Q}=2^m$, we have explicit known circuit of $O(m^2)$. $H$ and $C$-phase gate to implement $QFT_{2^m}$ exactly (cf part II QIC Notes).\n\\end{rem}\n\nFor $QFT_{\\mathcal{Q}}$: Introduce\n$$|\\eta_a \\ket = QFT_{\\mathcal{Q}} |a\\ket = \\frac{1}{\\sqrt{\\mathcal{Q}}} \\sum_{b=0}^{\\mathcal{Q}-1} \\omega^{ab} |b\\ket, a \\in \\Z_{\\mathcal{Q}}, \\omega = e^{2\\pi i/\\mathcal{Q}}$$\nIt suffices to make circuit hat does $|a \\ket \\to |\\eta_a\\ket$ (*).\\\\\nLet $2^{m-1} < \\mathcal{Q} < 2^m$, and set $M=2^m$, view $\\mathcal{H}_{\\mathcal{Q}}$ as subspace of $m$ qubits (spanned by $|a\\ket: 0 \\leq a < \\mathcal{Q}-1 < 2^m$).\\\\\nTo achieve (*), consider instead on $\\mathcal{H}_{\\mathcal{Q}} \\otimes \\mathcal{H}_{\\mathcal{Q}}$\n$$|a\\ket |0\\ket \\xrightarrow{(1)} |a\\ket |\\eta_a\\ket \\xrightarrow{(2)} |0\\ket |\\eta_a\\ket$$\n(1): get $\\eta_a\\ket$ from $|a\\ket$ while \\emph{remembering} $|a \\ket$;\\\\\n(2): \\emph{erase/forget} $|a\\ket$.\\\\\nFor (1), first do $|0\\ket \\to |\\xi\\ket = \\frac{1}{\\sqrt{\\mathcal{Q}}} \\sum_{b=0}^{\\mathcal{Q}-1} |b\\ket$ as follows:\\\\\non $m$ qubits $\\mathcal{H}^{\\otimes m}$ gives $\\frac{1}{\\sqrt{M}} \\sum_{x=0}^{2^m-1} |x\\ket$. Then consider the step function $f(x) = 0$ if $x<\\mathcal{Q}$ and 1 if $x \\geq \\mathcal{Q}$. It's classically efficiently computable, so can efficiently implement $U_f$ on $(m+1)$ qubits.\\\\\nSo applying $U_\\rho$ to $(H^{\\otimes m} |0\\ket) |0\\ket$ and measure output $(m+1^{st})$ qubit to get $|\\xi\\ket$ on first $n$ qubits if measurement result is 0.\\\\\nNote that $prob(0) > 1/2$ as $\\mathcal{Q} > 2^{m-1} = 2^m / 2$, so we can use multiple trials to give $|\\xi\\ket$.\\\\\nWe can do offline: failures/re-tries do not affect state to which we want to apply $QFT_{\\mathcal{Q}}$. So now we have $|\\tilde{\\xi} = |a\\ket \\left(\\frac{1}{\\sqrt{\\mathcal{Q}}} \\sum_{b=0}^{\\mathcal{Q}-1} |b\\ket\\right)$.\\\\\nNext consider $V |a\\ket |b\\ket = \\omega^{ab} |a\\ket |b\\ket$.\\\\\nThen $V|\\tilde{\\xi} \\ket = |a\\ket |\\eta_a\\ket$ as we want for (1).\n\nTo implement $V$, consider \n$$U:|b\\ket \\to \\omega^b |b\\ket$$\nIf $|b\\ket$ in $m$ qubits given by $|b_{m-1} \\ket ... |b_0\\ket$, i.e. $b = b_{m-1} ... b_0$ in binary, then $\\omega^b = \\omega^{b_{m-1} 2^{m-1}}...\\omega^{b_02^0}$. So $U$ is product of $1$-qubit phase gates\n$$P(\\omega^{2^{m-1}}) \\otimes ... \\otimes \\P(\\omega^{2^0})$$\nwhere $P(\\xi) = Diag(1,\\xi)$, $|\\xi|=1$ is a phase gate.\n\nSimilarly, for $C-U^{2^k}$ (starting with $U \\to U^{2^k}$ i.e. $\\omega^b \\to \\omega^{2^kb}$), and $V$ = \\emph{generalised $C-U$}: \n$$|a\\ket |b\\ket \\xrightarrow{V} |a\\ket U^a |b\\ket$$\nwhich is constructed as before, from $C-U^{2^k}$'s.\\\\\nSo now we have $|a\\ket |0\\ket \\xrightarrow{(1)} |a\\ket |\\eta_a\\ket$.\n\nFor (2), i.e. $|a\\ket |\\eta_a\\ket \\xrightarrow{(2)} |0\\ket |\\eta_a\\ket$, \\emph{if} we had $U$ with eigenstates $|\\eta_a\\ket$, eigenvalues $\\omega^a = e^{2\\pi i a/\\mathcal{Q}}$, then $U_{PE}$ would give\n$$|0\\ket |\\eta_a\\ket \\xrightarrow{U_{PE}} |a\\ket |\\eta_a\\ket$$\n(we are a bit loose on how information is presented -- writing eigenvalue output as $a$, and note we are assuming that PE works exactly)\\\\\nHence $U^{-1}_{PE}$ (\\emph{inverse gates taken in reverse order}) would give desired (2)!\n\nConsider $U:|x\\ket \\to |x-1\\ mod\\ \\mathcal{Q}\\ket$, and check that $U |\\eta_a\\ket = \\omega^a |\\eta_a\\ket$ as wanted.\\\\\nNow note $x \\to x-k\\ mod\\ \\mathcal{Q}$ for $k \\in \\Z_{\\mathcal{Q}}$ is classically computable in $poly(\\log\\mathcal{Q})$-time, thus we also have $U^k: |x\\ket \\to |x-k\\ mod\\ \\mathcal{Q}\\ket$, and PE algotirhm with $m=O(\\log(Q))$ lines.\\\\\nThen implementing (1) then (2) gives $poly(\\log\\mathcal{Q})$ sized circuit for $QFT_{\\mathcal{Q}}$.\n\nBut PE is not exact. However, using more qubit lines ($O(\\log 1/\\varepsilon)$ lines), we can achieve (by theorem PE(b))\n$$|0\\ket |\\eta_a \\ket \\xrightarrow{U_{PE}} (\\sqrt{1-\\varepsilon} |a\\ket + \\sqrt{\\varepsilon} |a^\\perp \\ket) |\\eta_a\\ket$$\n(where $a^\\perp$ is a state orthogonal to $|a\\ket$) for any (small) deserved $\\varepsilon$. Then\n$$||\\ |a\\ket - \\sqrt{1-\\varepsilon} |a\\ket + \\sqrt{\\varepsilon} | a^\\perp \\ket\\ || = O(\\sqrt{\\varepsilon})$$\nSo\n$$||\\ U_{PE}^{-1} |a\\ket |\\eta_a\\ket - |0\\ket |\\eta_a\\ket\\ || = O(\\sqrt{\\varepsilon})$$\n(as unitaries preserve lengths). So we can approximate $QFT_{\\mathcal{Q}}$ to any desired precision (omit details).\n\n\\newpage\n\n\\section{Amplitude Amplification}\nNote that this is a very good name -- a fifth order literation (both starting with \\emph{Ampli}).\\\\\nApothesis of technique in Grover's algorithm.\n\nSome background:\\\\\nWe'll make much use of \\emph{reflection operators}.\n\n---Lecture 9---\\\\\nA reminder that we don't have lecture next thursday.\n\nReflection operators:\\\\\n$\\bullet$ State $|\\alpha\\ket$ in $\\mathcal{H}_d$ $\\to$ 1-dimensional subspace $L_\\alpha$ and $(d-1)$-dimensional orthogonal complement $L_\\alpha^\\perp$\n$$I_{|\\alpha\\ket} \\stackrel{def}{=} I-2|\\alpha \\times \\alpha|$$\nhas $I_{|\\alpha\\ket} |\\alpha\\ket = -|\\alpha\\ket$, $I_{|\\alpha\\ket} |\\beta\\ket = |\\beta\\ket$ for any $|\\beta \\ket \\perp |\\alpha\\ket$.\\\\\nSo $I_{|\\alpha\\ket}$ is reflection in $(d-1)$-dimensional subspace $L_{\\alpha}^\\perp$.\n\nNote that for any unitary $U$, $U I_{|\\alpha\\ket} U^\\dagger = I_{U|\\alpha\\ket}$, since $U|\\alpha \\times \\alpha|Y^\\dagger = |\\xi \\times \\xi|$ ofr $\\xi = U|\\alpha\\ket$ (basically a change of basis).\n\n$\\bullet$ Take $k$-dimensional subspace $A \\subseteq \\mathcal{H}_d$, and any orthonormal basis $|a_1\\ket,...,|a_k\\ket$. Then $P_A = \\sum_{i=1}^k |a_i \\times a_i|$ is projection operator into $A$.\\\\\nDefine $I_A = I-2P_A$. Then we have $I_A |\\xi\\ket = |\\xi\\ket$ if $|\\xi\\ket \\in A^\\perp$, and $I_A|\\xi\\ket = -|\\xi\\ket$ if $|\\xi\\ket \\in A$.\\\\\nSo $I_A$ is reflection in $(d-k)$ dimensional mirror $A^\\perp$.\n\nRecap of Grover's algorithm (part II notes page 68-73):\\\\\n$\\bullet$ search for unique \\emph{good} item in unstructured database of $N=2^n$ items formalised as: (write $B_n$ to be the set of all $n$-bit strings, $N=2^n$):\nGiven oracle for $f:B_n \\to B$, promised that there is unique $x_0 \\in B_n$ with $f(x_0) = 1$, and we wish to find $x_0$.\\\\\nThis is closely related to class NP and Boolean satisfiability problem (see part II notes p 67-68).\\\\\nUsing one query to $(n+1)$-qubit $\\mathcal{U}_f$, we can implement reflection operator $I_{|x_0\\ket} : |x\\ket \\to |x\\ket$ if $x \\neq x_0$, and to $-|x\\ket$ if $x=x_0$.\\\\\n(viz. apply $\\mathcal{U}_f$ to $|x\\ket (\\frac{|0\\ket - |1\\ket}{\\sqrt{2}})$ and discard the last qubit.)\\\\\nThen consider \\emph{Grover iteration operator} on $n$ qubits:\\\\\n$$Q \\stackrel{def}{=} -H_n I_{|0...0\\ket} H_n I_{|x_0\\ket} = -I_{|\\psi_0\\ket} I_{|x_0\\ket}$$\nhere $H_n = H\\otimes H \\otimes ... \\otimes H = H_n^{\\dagger}$, and $|\\psi_0\\ket = H^n |0...0\\ket = \\frac{1}{\\sqrt{2^n}} \\sum_{x \\in B_n} |x\\ket$.\\\\\nSo one application of $Q$ uses 1 query to $\\mathcal{U}_f$.\n\n\\begin{thm} (Grover, 1996)\\\\\n    In 2-dimensional span of $|\\psi_0\\ket$ and (unknown) $|x_0\\ket$, the action of $Q$ is rotation by angle $2\\alpha$ where $\\sin\\alpha = \\frac{1}{\\sqrt{N}}$.\\\\\n\\end{thm}\n\nHence (Grover's algorithm) to find $x_0$ given $U_f$:\\\\\n1. Make $|\\psi_0\\ket$;\\\\\n2. Apply $Q$ $m$ times where $m = \\frac{\\arccos(\\frac{1}{\\sqrt{N}})}{2\\arctan(frac{1}{\\sqrt{N}})}$ to rotate $|\\psi_0\\ket$ very close to $|x_0\\ket$.\\\\\n3. Measure to see $x_0$ with high probability $\\sim 1-\\frac{1}{N}$.\n\nFor large $N$, $\\arccos(\\frac{1}{\\sqrt{N}}) \\approx \\pi/2$, $\\arcsin(\\frac{1}{\\sqrt{N}}) \\approx \\frac{1}{\\sqrt{N}}$ so $m = \\frac{\\pi}{4} \\sqrt{N}$ iterations/queries to $U_f$ suffice.\\\\\nClassically we need $O(N)$ queries to see $x_0$ with any \\emph{constant} probability (independent of $N$), so get \\emph{square-root} speed up quantumly.\n\nAmplitude Amplification:\\\\\nLet $G$ be any subspace (\\emph{good subspace}) of state space $\\mathcal{H}$, and $G^\\perp$ is orthogonal complement (\\emph{bad subspace}) $\\mathcal{J} = G \\oplus G^\\perp$.\\\\\nGiven any $|\\psi \\ket \\in \\mathcal{H}$, we have unique decompoisiton with \\emph{real positive} coefficients\n$$|\\psi\\ket = \\sin\\theta |g\\ket + \\cos\\theta |b\\ket$$\nwhere $|g\\ket \\in G$, $|b\\ket \\in G^\\perp$ normalised. Introduce reflections: flip $|\\psi\\ket $ and good vectors: $I_{|\\psi\\ket} = I-2|\\psi \\times \\psi|$, $I_G = I-2P_G$ (projection into $G$), so $\\sin\\theta = ||P_G |\\psi\\ket||$ is the length of good projection.\\\\\nIntroduce $Q \\stackrel{def}{=} -I_{|\\psi\\ket} I_G$.\n\n\\begin{thm} (Amplitude Amplification)\\\\\nIn the 2-dimensional subspace spanned by $|g\\ket$ and $|\\psi\\ket$ (or equivalently by orthonormal vectors $|g\\ket$ and $|b\\ket$), $Q$ is rotation by $2\\theta$ where $\\sin\\theta$ is the length of good projection of $|\\psi\\ket$.\n    \\begin{proof}\n        We have $I_G|g\\ket = -|g\\ket$, $I_G|b\\ket = |b\\ket$. So $Q|g\\ket = +I_{|\\psi\\ket} |g\\ket$, $Q|b\\ket = -I_{|\\psi\\ket} |b\\ket$.\\\\\n        Now \n        \\begin{equation*}\n            \\begin{aligned}\n                I_{|\\psi\\ket} &= I-2(\\sin\\theta|g\\ket + \\cos\\theta|b\\ket)(\\sin\\theta\\bra g| + \\cos\\theta\\bra b|)\\\\\n                &= I-2[\\sin^2\\theta |g\\times g| + \\sin\\theta\\cos\\theta |g\\times b| + \\sin\\theta\\cos\\theta|b \\times g| + \\cos^2\\theta |b\\times b|] |b\\ket\n            \\end{aligned}\n        \\end{equation*}\n        And direct calculation (using $\\bra g| b\\ket =0$, $\\bra g|g\\ket = \\bra b|b\\ket = 1$) gives \n        \\begin{equation*}\n            \\begin{aligned}\n                Q|b\\ket &= I_{|\\psi\\ket} |b\\ket\\\\\n                &=2\\sin\\theta\\cos\\theta |g\\ket - (1-2\\cos^2\\theta) |b\\ket\\\\\n                &= \\cos 2\\theta |b\\ket + \\sin 2\\theta|g\\ket\n            \\end{aligned}\n        \\end{equation*}\n        and $Q|g\\ket = +I_{|\\psi\\ket} |g\\ket = -\\sin 2\\theta |b\\ket + \\cos 2\\theta |g\\ket$.\\\\\n        So in $\\{|b\\ket,|g\\ket\\}$ basis, matrix of $Q$ is exactly the matrix of rotation by $2\\theta$.\n    \\end{proof}\n\\end{thm}\n\n---Lecture 10---\n\nLet's continue on Amplitude Amplification.\n\nLast time we showed that $Q=-I_{|\\psi\\ket} I_g$ is the rotation through $2\\theta$ in the plane of $|\\psi\\ket$ and $|g\\ket$, i.e. in $|b\\ket$ and $|g\\ket$ (orthonormal).\\\\\nSo $Q^n|\\psi\\ket = \\sin(2n+1)\\theta |g\\ket + \\cos(2n+1)\\theta |b\\ket$, and if we measure $Q^n |\\psi\\ket$ for good vs bad, we get $prob(good) = \\sin^2(2n+1)\\theta$.\\\\\nWe want to maximize this: it is maximised when $(2n+1)\\theta = \\pi/2$, i.e. $n=\\frac{\\pi^2}{4\\theta} - \\frac{1}{2}$.\n\n\\begin{eg}\n    \\emph{If} we had $\\theta =4/6$, then $n=\\frac{\\pi}{4\\theta} - \\frac{1}{2} = 1$ is an exact integer. So $Q^1$ rotates $|\\psi\\ket$ \\emph{exactly} onto $|g\\ket$, so we see good result with certainty!\n\\end{eg}\n\nGenerally, for given $\\theta$, $n$ is not an integer. So we use $n$ to be the nearest integer to $(\\frac{\\pi}{4\\theta} - \\frac{1}{2}) \\approx \\frac{\\pi}{4\\theta}$ (for small $\\theta$), which equals $O(\\frac{1}{\\theta} = O(\\frac{1}{\\sin\\theta}) = O(\\frac{1}{||good\\ proj\\ of\\ |\\psi||})$), and $Q^n|\\psi\\ket$ will be within angle $\\pm \\theta$ of $|g\\ket$, so probability of good result is at least $\\cos^2\\theta \\approx 1-O(\\theta^2)$.\n\nAll this can be implemented oif $I_{|\\psi\\ket}$ and $I_G$ can be implemented. See example sheet -- for $I_G$, suffices for $G$ to be spanned by computational basis states $|x\\ket$'s, and indicator function $f(x)=1$ for $x$ good and $0$ for $x$ bad efficiently computable.\\\\\nFor $I_{|\\psi\\ket}$, usally have $|\\psi\\ket =H_n|00...0\\ket$ ($H$ is the Hadamard gate). Then $I_{|\\psi\\ket}$ can be implemented in linear $O(n)$ time.\n\nNotes:\\\\\n(1) In AA process, relative amplitudes of good labels in $|g\\ket$ stay \\emph{same} as they were in $|\\psi\\ket = \\sin\\theta|g\\ket + \\cos\\theta |b\\ket$.\\\\\n(2) Final state is generally not exactly $|g\\ket$, but \\emph{if} $\\sin\\theta$ is \\emph{known}, then we can modify AA process to make it exact, i.e. giving $|g\\ket$ state exactly (see example sheet).\n\nApplications of AA:\\\\\n(1) \\emph{Grover Search} with one or \\emph{more} ($k$) good items in $N$:\\\\\n\\begin{equation*}\n    \\begin{aligned}\n        |\\psi\\ket &= |\\psi_0\\ket = \\frac{1}{\\sqrt{2^n}} \\sum_{x \\in B_n} |x\\ket\\\\\n        &= \\sqrt{\\frac{k}{N}} \\left(\\frac{1}{\\sqrt{k}} \\sum_{good\\ |g\\ket} |x\\ket\\right) + \\sqrt{\\frac{N-k}{N}} \\left(\\frac{1}{\\sqrt{N-k}} \\sum_{x\\ bad}|x\\ket\\right)\n    \\end{aligned}\n\\end{equation*}\n$G$ spanned by good $x$'s, $\\sin\\theta = \\frac{k}{n}$ so $Q$ is rotation through $2\\theta$, $\\theta=\\arcsin\\sqrt{k/N} \\approx \\sqrt{k/N}$, where $k\\ll N$; and we only need $O(\\sqrt{N/k})$ queries.\n\nNote: for $2$-bit case, $N=4$ with $k=1$ good item; we have $\\theta = \\arcsin(1/2) = \\pi/6$, so one application of $Q$ rotates $|\\psi_0\\ket$ exactly onto $|x_{good}\\ket$, i.e. a \\emph{single} query suffices to find a unique good item in four, \\emph{with certainty}!\n\n(2) Square-root sppedup of general quantum algorithms:\\\\\nLet $A$ be a quantum algorithm/circuit (sequence of unitary gates). on input, say $|0...0\\ket$. So final state is $A|0...0\\ket$.\\\\\nGood labels = desired computational outcomes\n$$A|0.000\\ket = \\alpha|a\\ket + \\beta|b\\ket, \\alpha=\\sin\\theta$$\nwhere $|a\\ket$ is normalised, genrally unequal superposition $\\sum_{good\\ x} c_x|x\\ket$.\\\\\nSo $Prob(\\text{success in 1 run}) = |\\alpha|^2$, so $O(\\frac{1}{|\\alpha|^2})$ repetitions of $A$ needed to succeed with any \\emph{constant} high probability $1-\\varepsilon$.\n\nInstead use AA: assumed we can check if answer is good or bad (e.g. factoring).\\\\\nSo we can then implement $I_G:|x\\ket \\to -|x\\ket$ if $x$ is good, and $\\to |x\\ket$ if $x$ is bad.\\\\\nConsider $|\\psi\\ket = A|0...0\\ket$ and $Q=-I_{A|0...0\\ket} I_G = -(AI_{|0...0\\ket} A^\\dagger) I_G$. All parts are implementable ($A$ is the algorithm, $A^\\dagger$ is inverse gate in reverse order, and $I_{|0...0\\ket}$ see example sheet).\\\\\nBy AA theorem, $Q$ is rotation through $2\\theta$, where $\\sin\\theta=|\\alpha|$. So after $n\\approx \\frac{\\pi}{4\\theta} = O(\\frac{1}{\\theta}) = O(\\frac{1}{\\sin\\theta}) = O(\\frac{1}{|\\alpha|})$ (for small $|\\alpha|$).\\\\\nRepetitions $A|0...0\\ket$ will be rotate very near to $|g\\ket$, and final measurement will succeed with high probability.\\\\\nEach application of $\\mathcal{Q}$ needs one $A$ and one $A^\\dagger$; $A^\\dagger$ is the \\emph{inverse gate in reverse order}, i.e. the time complexity is the same, i.e. $O(\\frac{1}{|\\alpha|})$ repetition of $Q$ gives square root time speed up over direct method.\n\nAlso, if success probability of $A$ (i.e. $|\\alpha|^2$) is known, then \\emph{improved} modification of the AA process that is \\emph{exact} can be applied; we convert probabilistic algorithm $A$ into \\emph{deterministic} one, giving a good outcome with certainty.\n\n\\newpage\n\n\\section{Quantum Counting}\n\nGiven $f:B_n \\to B$ a boolean function with an unknown number $k$ good $x$'s, we want ot \\emph{estimate} $k$ (rather than just find some good $x$).\n\nRecall that Grover operator $Q_G$ for $f$ is rotaion through $2\\theta$ in 2-dimensional space of $|\\psi_0 = \\frac{1}{\\sqrt{2^n}} \\sum_{x \\in B_n} |x\\ket$ and its good projection $|g\\ket = \\frac{1}{\\sqrt{k}} \\sum_{good\\ x} |x\\ket$, with $\\sin\\theta = \\sqrt{k/N} \\approx \\theta$ for $k \\ll N$.\n\n---Lecture 11---\n\n(Did I miss a lecture?)\n\n\\subsection{Hamiltonian Simulation}\n\n$k$-local Halmiltonians:\n\n$H$ on $n$ qubits is a $2^n \\times 2^n$ Hermitian matrix. We'll want to simulate $U=e^{-iHt}$ with a circuit of $poly(n,t)$ basic unitary gates, i.e. efficient simulation.\\\\\nNot all $H$'s can be efficently simulated, but some physically important classes can --\n\n\\begin{defi}\n    $H$ is $k$-local ($k$ is a fixed constant) on $n$ qubits if $H=\\sum_{j=1}^m H_j$ where each $H_j$ is a Hermitian matrix acting on at most $k$ qubits (not necessarily contiguous).\\\\\n    i.e. each $H_j = \\tilde{H}_j \\otimes I$ (on some $k$ qubits, and identity on rest of qubits).\n\n    So $m \\leq {n \\choose i} =O(n^k) = poly(n)$ terms in $H$.\n\\end{defi}\n\n\\begin{eg}\n    (1) $H=X \\otimes I \\otimes I - 5 Z \\otimes I \\otimes Y$ is $2$-local on 3 qubits.\\\\\n    (2) Write $M_{(j)}$ to denote operator $M$ acting on $j^{th}$ qubit (and $I$ on all others). Physically important spin-spin interactions:\\\\\n    Ising model on $n\\times n$ square lattice of qubits, $H=J \\sum_{i,j=1}^{n-1} Z_{(i,j)} Z_{(i,j+1)} + Z_{(i,j)}Z_{(i+1,j)}$, i.e. all nearest neighbours on square.\\\\\n    Heisenberg model on a line: $H=\\sum_{i=1}^{n-1} J_x X_{(i)} X_{(i+1)} + J_y Y_{(i)} Y_{(i+1)} + J_z Z_{(i)} Z_{(i+1)}$ (where $J,J_x,J_y,J_z$ are all real constants). This is very relevatn on chemistry (in studying covalence bonds?)\n\\end{eg}\n\nNote: in general, $e^{-i\\sum_{j} H_j t} \\neq \\prod_j (e^{-i H_j t})$ -- if the $H_j$'s don't commute.\n\nBut $e^{-iH_j t}$'s \\emph{are} local unitary gates (acting on $k$ qubits each), and we'll simulate $U(t_0) = e^{-i \\sum_j H_i t_0}$ in terms of these (for suitable $t$'s), and we'll have a $poly(n,t_0)$-sized circuit too.\n\nIf we want to use some standard universal gate set (to further express the above gates), then use: \\emph{Solovay-Kitaev theorem}: Let $U$ be a unitary operator on $k$ (const) qubits, and $S$ any universal set of quantum gates ($S$ is the set that have property that if we look at all circuit and all finite sets, then it's dense in all circuits?? Lecturer didn't write down).\\\\\nThen $U$ can be approximated to within $\\varepsilon$ using $O(\\log^c(1/\\varepsilon))$ gates from $S$ with $c < 4$ (it's actually exponential in $k$, but here we consider $k$ constant).\\\\\nSo all $S$-products of length $O(\\log^c(1/\\varepsilon))$ get within $\\varepsilon$ of any element of $U(k)$.\n\nWe'll also need a lemma about accumulation of errors (c.f. Example sheet).\\\\\nWe call this lemmma A: let $\\{u_i\\}, \\{v_i\\}$ be sets of $m$ unitary operators, with $||u_i - v_i|| < \\varepsilon$ for all $i=1,2,...,m$, then \n$$||u_m...u_1 - v_m...v_1|| \\leq m\\varepsilon$$\ni.e. errors accumulate linearly.\\\\\nProof is an easy exercise -- induction on $m$.\n\nWarm up: the (easy) commuting case.\n\\begin{prop} ($k$-local Hamiltonioans with commuting terms)\\\\\n    $H=\\sum_{j=1}^m H_j$ with $H_j$ commuting -- any local Hamiltonian with commuting terms.\\\\\n    Then for any $t$, $e^{-iHt}$ can be approximated to within $\\varepsilon$ by a circuit of $O(m\\ poly(\\log \\frac{m}{\\varepsilon}))$ gates from any given universal set.\\\\\n    Note, as $m=O(n^k)$ this is $poly(n,\\log\\frac{1}{\\varepsilon})$ too. Also, $\\log(\\frac{1}{\\varepsilon})$ is the number of digits of precision in the approximation.\n    \\begin{proof}\n        $H_j$'s commute implies that $e^{-i \\sum_j H_j t} = \\prod_{j=1}^m (e^{-i H_j t})$. Then SK theorem implies, for each $e^{-iH_j t}$ can be approximated to within $\\varepsilon/m$ within $O(poly(\\log\\frac{m}{\\varepsilon}))$ gates, so lemma $A$ then implies that the full product $\\prod_{j=1}^m$ is then approximated to within $m(\\varepsilon/m) = \\varepsilon$, with a total of $O(m\\ poly(\\log \\frac{m}{\\varepsilon}))$ gates (from the universal set).\n    \\end{proof}\n\\end{prop}\n\nNow let's look at the full non-commuting case: for any matrix $X$, write $X+O(\\varepsilon)$ for $X+E$ where $||E|| = O(\\varepsilon)$.\n\n\\begin{lemma} (B, Lie-Trotter product formula)\\\\\n    Let $A,B$ be matrices with $||A|| \\leq K$, $||B|| \\leq k$ and $k<1$ (small).\\\\\n    Then $e^{-iA} e^{-iB} = e^{-i(A+B)} + O(k^2)$.\n    \\begin{proof}\n        \\begin{equation*}\n            \\begin{aligned}\n                e^{-iA} &= I-iA + \\sum_{k=2}^\\infty \\frac{(-iA)^k}{k!}\\\\\n                &= I-iA + (iA)^2 \\sum_{k=0}^\\infty \\frac{(-iA)^k}{(k+2)!}\\\\\n                &= I-iA + O(k^2)\n            \\end{aligned}\n        \\end{equation*}\n        since $||(iA)^2|| < k^2$, and the remainder term is at most $1$. So\n        \\begin{equation*}\n            \\begin{aligned}\n                e^{-iA} e^{-iB} &= (I-iA + O(k^2)) (I-iB + O(k^2))\\\\\n                &= I-i(A+B) + O(k^2)\\\\\n                &= e^{-i(A+B)} + O(k^2)\n            \\end{aligned}\n        \\end{equation*}\n        by applying the inverse of above\n    \\end{proof}\n\\end{lemma}\nNow apply this repeatedly to accumulate sums of $H_1,...,H_m$ in exponent. Note thta if each $||H_i|| < k$, then $||H_1+...+H_l|| < lk$, we want this to be $<1$ for all $l\\leq m$.\\\\\nSo \\emph{for now}, we'll assume $||H_i|| < \\frac{1}{m}$ to have Lie-Trotter for all stages. Also take $t=1$ \\emph{for now}.\\\\\nThen consider\n\\begin{equation*}\n    \\begin{aligned}\n        e^{-iH_1} e^{-iH_2}...e^{-iH_m} &= \\left[e^{-i(H_1+H_2)}+O(k^2)\\right] e^{-iH^3} ... e^{-iH_m}\\\\\n        &= e^{-i(H_1+H_2)} e^{-iH_3} ... e^{-iH_m} + O(k^2)\\\\\n        &= ...\\\\\n        &= e^{-i(H_1+H_2+...+H_m)} +O(k^2)+O((2k)^2)+...+O(((m-1)k)^2)\\\\\n        &= e^{-i(H_1+H_2+...+H_m)} + O(m^3k^2)\\ (1)\n    \\end{aligned}\n\\end{equation*}\nwhere in the second equality we used that $||AU|| = ||A||$ for any unitary $U$, and note that the sum of squares up to $m$ is of order $m^3$.\n\n---Lecture 12---\n\nFor general finite $||H_j||$'s and $t$ values, $||H_j t|| < kt$ can be large, so interoduce $N$ (large-ish, fix later), and note \n$$\\frac{H_j t}{N} \\text{ has } \\tilde{K} = ||\\frac{H_j t}{N}|| < \\frac{kt}{N}\\ (*)$$\ncan be suitably small, i.e. divide $t$ into (small) $\\frac{1}{N}$ intervals,\n$$U=e^{i(H_1+...+H_m)t} = [e^{i(\\frac{H_1t}{N} + ... + \\frac{H_mt}{N})}]^N$$\nWe want final error for $U$ to be $<\\varepsilon$, so by lemma $A$, we want error for $[...]$ to be $<\\frac{\\varepsilon}{N}$.\\\\\nSo by (1) and (*), $Cm^3 \\tilde{k}^2 < \\frac{\\varepsilon}{N}$, i.e. $Cm^3 \\frac{K^2t^2}{N^2} < \\frac{\\varepsilon}{N}$, i.e. $N>\\frac{Cm^3K^2t^2}{\\varepsilon}$ (2).\\\\\nThen \n$$||e^{-iH_1t/N} e^{-iH_2t/N}...e^{-iH_mt/N} - e^{-i\\frac{(H_1+...+H_m)t}{N}}|| < \\frac{\\varepsilon}{N}$$\nso by lemma $A$ again,\n$$||(e^{-iH_1t/N}...e^{-iH_mt/N})^N - e^{-i(H_1+...+H_m)t}||< \\varepsilon$$\n(this is $Nm$ gates if form $e^{-iH_jt/N}$, and $N$ given by (2)). So circuit size is $O(\\frac{m^4(Kt)^2}{\\varepsilon})$.\\\\\nRecall for $n$ qubits and $k$-local Hamiltonians, $m=O(n^k)$, so circuit size is $O(n^{4k} \\frac{(Kt)^2}{\\varepsilon}) = O(n^{4k},t^2,\\frac{1}{\\varepsilon})$.\n\nWe have circuit $\\mathcal{C}$ of size $|\\mathcal{C}| = O(m^4 \\frac{(Kt)^2}{\\varepsilon})$ gates of form $e^{-i\\tilde{H}_j/N}$ approximate to $O(t)$.\\\\\nIf we want to use standard universal set, lemma A gives each of these gates needs to be approximate to $O(\\varepsilon/|\\mathcal{C}|)$ to maintain an overall $O(\\varepsilon)$ level approximation to $U$.\\\\\nSo by SK theorem, need $O(\\log^c(|\\mathcal{C}|/\\varepsilon))$ gates from the universal set for each, i.e. get (modest) multiplicative factor of $O(\\log^c \\frac{m^4(Kt)^2}{\\varepsilon^2})$ in $|\\mathcal{C}|$.\\\\\n\nFor fixed $n,\\varepsilon$, and variable $t$, the quantum process $e^{iHt}$ runs for time $t$; but our circuit simulation runs for time $O(t^2)$. By refining/improving Lie-Trotter formula, it can be shown that this can be improved to $O(t^{1+\\delta})$ for any $\\delta>0$ (See example sheet 2 for an example).\n\nHarrow-Hassidim-Lloyd (HHL) quantum algorithm for linear systems of equations:\\\\\nWe'll want to solve a linear system of equations $A \\mathbf{x} = \\mathbf{b}$, where $\\mathbf{b},\\mathbf{x} \\in \\C^N$, and dimension $N$ is potentially \\emph{very} large (we could set $N=2^n$, where $2^n$ is the least power of 2 that is greater than $N$).\\\\\nRather than outputting the full solution $\\mathbf{x}$ itself, which would take $O(N)$ time, we instead want to compute (suitable approximates to) the value of properties of the solution, such as quadratic expressions $\\mathbf{x}^T M \\mathbf{x}$ e.g. total weight of some subset of components.\n\nVery large lineary systems are important in applications: data mining/machine learning on data sets of increasingly large size to discover pattern properties in data; in science/engineering , we have numerical solutions of PDEs, where discretisation techniques (finite element methods) lead to linear systems far larger than original problem description.\n\nThe best known classical techniques take $poly(N)$ time to solve such problems.\n\nImportant parameters (for both classical and quantum algorithms):\\\\\n$\\bullet$ the system size $N$;\\\\\n$\\bullet$ the desired approximate tolerance $\\varepsilon$;\\\\\n$\\bullet$ the \\emph{condition number} $\\kappa$ of matrix $A$, defined as ratio of largest to smallest eigenvalue size $\\kappa = |\\frac{\\lambda_{max}}{\\lambda_{min}}|$;\\\\\nIt provides intrinsic scale of the linear transformation $A$, and is a measure of how close $A$ is to being non-invertible.\\\\\nIf renormalize $A$ to have $\\lambda_{max} = 1$, then $|\\lambda_{min}| = 1/\\kappa$, and numerical computation of $A^{-1}$ becomes less stable with increasing $\\kappa$, needing more significant digits and correspondingly longer runtime.\n\nPreliminary requirements for the HHL algorithm:\\\\\nAim: to compute $\\varepsilon$-approximate to properties of the solution of an $N$-dimensional system $A\\mathbf{x} = \\mathbf{b}$ in time $poly(\\log N) = poly(n)$. We'll take the property to be a quadratic expression $\\mu = \\mathbf{x}^T M \\mathbf{x}$.\n\nImmediate issue is how the defining ingredients viz $A$ and $\\mathbf{b}$ are actually given (as reading them componently would already have taken $O(poly(N))$ time). Thus we'll need a different presentation of the problem (cf below) that is still available in applications.\n\nThe $poly(\\log N)$ run time will be achieved by using only $O(\\log N)$ qubits and it will never be required to write down all of $A$ or $\\mathbf{b}$ or $\\mathbf{x}$ in the course of the algorithm (as that would be impossible given the complexity constraints).\n\n\n\n\n\n\n\n\n\n\n\\newpage\n\n\\section{Example Class 1}\n\n\\subsection{Question 1}\nBasic representation theory exercises.\\\\\nFor details see Part II Representation Theory.\n\n\\subsection{Question 2}\nLet $G=(\\Z_2^n, \\oplus)$ where $\\oplus$ is componentwise-addition. Subgroup $K$ generated by $a_1...a_k$, $K=\\{b_1a_1 \\oplus ... \\oplus b_ka_k:b_1,...,b_k \\in \\Z_2\\}$. Note that $K$ has size $2^k$ if $a_i$'s are LI, and so does any coset of $K$.\\\\\nThen $f(x) = f(x \\oplus a_i)$ for all $a_i$'s $\\equiv$ $f$ constant on cosets of $K$. $f$ is $2^k$-to-$1$: $a_k$'s all linearly independent and $f$ different on different cosets.\n\nShift invariant states: For $\\Z_2$ irreps are $\\chi_a(x) = (-1)^{ax)}$, $a,x \\in \\Z_2$ ($-1$ is the 2nd root of unity). So irreps on $(\\Z_2)^n$ are $\\chi_a(x) =(-1)^{a_1x_1} ... (-1)^{a_nx_n}$ where $a=a_1...a_n$, $x=x_1...x_n$ are in $\\Z_2^n$.\\\\\nWe also introduce a dot product $a \\cdot x = a_1x_1 \\oplus ... \\oplus a_n x_n \\in \\Z_2$ where $\\oplus$ here is $+$ modulo 2.\\\\\nSo shift invariant states\n$$|\\chi\\ket = \\frac{1}{\\sqrt{|G|}} \\sum_g \\overline{\\chi(g)} |g\\ket$$\nSo\n$$|\\chi_a\\ket = \\frac{1}{\\sqrt{2^n}} \\sum_{b \\in \\Z_2^n} (-1)^{a\\cdot b} |b\\ket$$\nin $n$ qubits. So\n$$(QFT)_{alr(?)} = \\frac{1}{\\sqrt{2^n}} (-1)^{a \\cdot b} = \\frac{1}{\\sqrt{2^n}} (-1)^{a_1b_1}...(-1)^{a_nb_n}$$\nso $QFT = H \\otimes H \\otimes ... \\otimes H$ where $H$ is the Hadamard gate.\\\\\nFor second part, it's just calculation:\\\\\nProbability that first string is LI is $1-2^{-m}$ (just exclude $0...0$);\\\\\nProbability that first 2 strings are LI given the first is is $1-2/2^m$ (i.e. as 1st string $x_1$ spans 2 strings, namely $0...0$ and $x_1$).\\\\\n...Probability that first $j$ strings are LI given the first $j-1$ are is $1-2^{j-1}/2^m$.\\\\\nSo by Bayes rule, probability that all of them are LI is $(1-1/2^m)...(1-2^{m-2}/2^m)(1-2^{m-1}/2^m)$. Use the hint given we get that is at least $\\frac{1}{2}(1-1/2) =1/4$.\n\nStanrdard HSP algorithm:\\\\\n1. query to $f$, get random coset state $|y \\oplus K \\ket = \\frac{1}{\\sqrt{2^n}} \\sum_{x \\in K} | y \\oplus x\\ket, y \\in \\Z_2^n$.\\\\\nApply $QFT=H^{\\otimes n}$ and measure; our theory assures that output is then uniformly random $c\\in(\\Z_2)^n$ s.t. irrep $\\chi_c$ of $G$ restricted to $K$ is \\emph{trivial irrep} of $K$, i.e .$\\chi_c(a) = 1$ for all $a \\in K$.\\\\\nSo $(-1)^{a \\cdot c} = 1$ for all $a \\in K$, i.e. $c \\cdot a = 0 \\pmod 2$ for all $a=K$, i.e. $c_1a_1\\oplus ... \\oplus c_na_n=0$ for $a=a_1...a_n$.\\\\\nWe know $K$ viewed as subspace of $(\\Z_2)^n$ ($n$ dimensional vector space over field $\\Z_2$) has dimension $k$. So $(n-k)$ LI $c_i$'s with $c_1 \\cdot a=0$ suffice to determine $K$ as null spaceof linear system of $(n-k)$ equations.\\\\\nSo run HSP algorithm $(n-k)$ times: by (b) we'll get $(n-k)$ LI $c's$ with probability at least 1/4, and we can solve for elements of $K$.\n\n\n\\end{document}\n", "meta": {"hexsha": "b09a8cb24b389b338220319f90aaddb466dca5e9", "size": 58993, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Notes/Quantum Computation.tex", "max_stars_repo_name": "raoxiaojia/raoxiaojia.github.io", "max_stars_repo_head_hexsha": "d20c23a64794b500f2e0356fd01017ee31830fa2", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-25T17:34:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-25T17:34:25.000Z", "max_issues_repo_path": "Notes/Quantum Computation.tex", "max_issues_repo_name": "raoxiaojia/raoxiaojia.github.io", "max_issues_repo_head_hexsha": "d20c23a64794b500f2e0356fd01017ee31830fa2", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Notes/Quantum Computation.tex", "max_forks_repo_name": "raoxiaojia/raoxiaojia.github.io", "max_forks_repo_head_hexsha": "d20c23a64794b500f2e0356fd01017ee31830fa2", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 73.9260651629, "max_line_length": 453, "alphanum_fraction": 0.62534538, "num_tokens": 22105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.3311084377612273}}
{"text": "\\documentclass[../psets.tex]{subfiles}\n\n\\pagestyle{main}\n\\renewcommand{\\leftmark}{Problem Set \\thesection}\n\\setcounter{section}{4}\n\n\\begin{document}\n\n\n\n\n\\section{Thermodynamics}\n\\begin{enumerate}[label={\\arabic*)}]\n    \\item \\marginnote{8/23:}\\textcite{bib:YoungFreedman}: Problem 36.21.\\par\n    An interference pattern is produced by light of wavelength $\\SI{580}{\\nano\\meter}$ from a distant source incident on two identical parallel slits separated by a distance (between centers) of $\\SI{0.530}{\\milli\\meter}$.\n    \\begin{enumerate}\n        \\item If the slits are very narrow, what would be the angular positions of the first-order and second-order, two-slit interference maxima?\n        \\item Let the slits have width $\\SI{0.320}{\\milli\\meter}$. In terms of the intensity $I_0$ at the center of the central maximum, what is the intensity at each of the angular positions in part (a)?\n    \\end{enumerate}\n    \\item \\textcite{bib:YoungFreedman}: Problem 36.44.\\par\n    \\textbf{Observing Jupiter.} You are asked to design a space telescope for Earth orbit. When Jupiter is $\\SI{5.93e8}{\\kilo\\meter}$ away (its closest approach to Earth), the telescope is to resolve, by Rayleigh's criterion, features on Jupiter that are $\\SI{250}{\\kilo\\meter}$ apart. What minimum-diameter mirror is required? Assume a wavelength of $\\SI{500}{\\nano\\meter}$.\n    \\item \\textcite{bib:YoungFreedman}: Problem 18.6.\\par\n    You have several identical balloons. You experimentally determine that a balloon will break if its volume exceeds $\\SI{0.900}{\\liter}$. The pressure of the gas inside the balloon equals air pressure ($\\SI{1.00}{\\atmosphere}$).\n    \\begin{enumerate}\n        \\item If the air inside the balloon is at a constant $\\SI{22.0}{\\celsius}$ and behaves as an ideal gas, what mass of air can you blow into one of the balloons before it bursts?\n        \\item Repeat part (a) if the gas is helium rather than air.\n    \\end{enumerate}\n    \\item \\textcite{bib:YoungFreedman}: Problem 18.21.\\par\n    Modern vacuum pumps make it easy to attain pressures of the order of $\\SI{e-13}{\\atmosphere}$ in the laboratory. Consider a volume of air and treat the air as an ideal gas.\n    \\begin{enumerate}\n        \\item At a pressure of $\\SI{9.00e-14}{\\atmosphere}$ and an ordinary temperature of $\\SI{300.0}{\\kelvin}$, how many molecules are present in a volume of $\\SI{1.00}{\\cubic\\centi\\meter}$?\n        \\item How many molecules would be present at the same temperature but at $\\SI{1.00}{\\atmosphere}$ instead?\n    \\end{enumerate}\n    \\item \\textcite{bib:YoungFreedman}: Problem 18.38.\\par\n    Perfectly rigid containers each hold $n$ moles of an ideal gas, one being hydrogen (\\ce{H2}) and the other being neon (\\ce{Ne}). If it takes $\\SI{300}{\\joule}$ of heat to increase the temperature of the hydrogen by $\\SI{2.50}{\\celsius}$, by how many degrees will the same amount of heat raise the temperature of the neon?\n    \\item \\textcite{bib:YoungFreedman}: Problem 19.10.\\par\n    Five moles of an ideal monatomic gas with an initial temperature of $\\SI{127}{\\celsius}$ expand and, in the process, absorb $\\SI{1500}{\\joule}$ of heat and do $\\SI{2100}{\\joule}$ of work. What is the final temperature of the gas?\n    \\item \\textcite{bib:YoungFreedman}: Problem 19.43.\\par\n    The following figure shows a $pV$-diagram for $\\SI{0.0040}{\\mole}$ of \\emph{ideal} \\ce{H2} gas. The temperature of the gas does not change during segment $bc$.\n    \\begin{center}\n        \\begin{tikzpicture}[\n            xscale=2.5,\n            pics/point/.style args={#1:#2}{code={\n                \\node [circle,fill,inner sep=1.5pt,label={#1:$#2$}] {};\n            }}\n        ]\n            \\footnotesize\n            \\draw (-0.2,0) -- (1,0) node[right,label={[xshift=-4pt]right:$(\\si{\\liter})$}]{$V$};\n            \\draw (0,-0.3) -- (0,2.5) node[above,label={[xshift=-4pt]right:$(\\si{\\atmosphere})$}]{$p$};\n            \\node [below left] {$O$};\n    \n            \\coordinate (a) at (0.2,0.5);\n            \\coordinate (b) at (0.2,2);\n            \\coordinate (c) at (0.8,0.5);\n    \n            \\draw [very thin,dashed] (a) -- (a |- 0,0) node[below]{$0.20$};\n            \\draw [very thin,dashed] (a) -- (a -| 0,0) node[left]{$0.50$};\n            \\draw [very thin,dashed] (b) -- (b -| 0,0) node[left]{$2.0$};\n    \n            \\draw [blx,very thick,line join={bevel},postaction={decorate},decoration={\n                markings,\n                mark=at position 0.15 with \\arrow{latex},\n                mark=at position 0.53 with \\arrow{latex},\n                mark=at position 0.9 with \\arrow{latex}\n            }] (a) -- plot[domain=0.2:0.8] (\\x,{0.4/\\x}) -- cycle;\n    \n            \\pic at (a) {point={[xshift=1pt,yshift=1pt]below left:a}};\n            \\pic at (b) {point=above:b};\n            \\pic at (c) {point={[xshift=-1pt,yshift=1pt]below right:c}};\n        \\end{tikzpicture}\n    \\end{center}\n    \\begin{enumerate}\n        \\item What volume does this gas occupy at point $c$?\n        \\item Find the temperature of the gas at points $a$, $b$, and $c$.\n        \\item How much heat went into or out of the gas during segments $ab$, $ca$, and $bc$? Indicate whether the heat has gone into or out of the gas.\n        \\item Find the change in the internal energy of this hydrogen during segments $ab$, $bc$, and $ca$. Indicate whether the internal energy increased or decreased during each segment.\n    \\end{enumerate}\n    \\item You hear the weather report on the radio. However, the announcer forgets to say what scale is being used: Celsius or Fahrenheit. If it doesn't matter, how cold is it outside?\n    \\item A pinhole camera can produce a surprisingly sharp image. The key is using a small hole so only a narrow bundle of rays is allowed through. However, if the pinhole is too small, then diffraction will limit the sharpness of the image. The optimum pinhole size is one that makes the fuzziness due to bundle size comparable to the fuzziness due to diffraction. Assume the distance from pinhole to screen is 1 foot, and the wavelength of the light is $\\SI{5500}{\\angstrom}$. What is the optimum size of the pinhole?\n\\end{enumerate}\n\n\n\n\n\\end{document}", "meta": {"hexsha": "dd81ff616d87747a8d6de0f05a1c29d4edc9d9d1", "size": 6108, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "PSets/PSet5/pset5.tex", "max_stars_repo_name": "shadypuck/PHYS13300Notes", "max_stars_repo_head_hexsha": "61c7dcb457b6ce79feba5d9a46e991c88cdcde68", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PSets/PSet5/pset5.tex", "max_issues_repo_name": "shadypuck/PHYS13300Notes", "max_issues_repo_head_hexsha": "61c7dcb457b6ce79feba5d9a46e991c88cdcde68", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PSets/PSet5/pset5.tex", "max_forks_repo_name": "shadypuck/PHYS13300Notes", "max_forks_repo_head_hexsha": "61c7dcb457b6ce79feba5d9a46e991c88cdcde68", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 71.8588235294, "max_line_length": 520, "alphanum_fraction": 0.6637197119, "num_tokens": 1768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.3311084377612273}}
{"text": "\\documentclass[10pt,a4paper]{article}\n\\usepackage{fullpage}\n\\usepackage{booktabs}\n\\usepackage{amsmath}\n\\usepackage{graphicx}\n\\usepackage{todonotes}\n\\usepackage{multirow,matlab-prettifier}\n\\usepackage[T1]{fontenc}\n\n\\hyphenpenalty=5000\n\\tolerance=1000\n\n\\newcommand{\\qmax}[0]{Q_{\\textrm{max}}}\n\\newcommand{\\nuab}[0]{$\\nu_{ab}$}\n\n\\newcommand{\\nuee}[0]{$\\nu_{ee}$}\n\\newcommand{\\nuei}[0]{$\\nu_{ei}$}\n\\newcommand{\\nues}[0]{$\\nu_{es}$}\n\\newcommand{\\nuse}[0]{$\\nu_{se}$}\n\\newcommand{\\nusr}[0]{$\\nu_{sr}$}\n\\newcommand{\\nusn}[0]{$\\nu_{sn}$}\n\\newcommand{\\nure}[0]{$\\nu_{re}$}\n\\newcommand{\\nurs}[0]{$\\nu_{rs}$}\n\n\\newcommand{\\gab}[0]{$G_{ab}$}\n\n\\newcommand{\\gabcd}[0]{$G_{abcd}$}\n\\newcommand{\\gese}[0]{$G_{ese}$}\n\\newcommand{\\gesre}[0]{$G_{esre}$}\n\\newcommand{\\gsrs}[0]{$G_{srs}$}\n\n\\newcommand{\\xyz}[0]{$XY\\!Z$}\n\n\\newcommand{\\gee}[0]{$G_{ee}$}\n\\newcommand{\\gei}[0]{$G_{ei}$}\n\\newcommand{\\ges}[0]{$G_{es}$}\n\\newcommand{\\gse}[0]{$G_{se}$}\n\\newcommand{\\gsr}[0]{$G_{sr}$}\n\\newcommand{\\gsn}[0]{$G_{sn}$}\n\\newcommand{\\gre}[0]{$G_{re}$}\n\\newcommand{\\grs}[0]{$G_{rs}$}\n\\newcommand{\\e}[1]{\\times 10^{#1}}\n\\newcommand{\\phia}[0]{$\\phi_a$}\n\\newcommand{\\phie}[0]{$\\phi_e$}\n\\newcommand{\\phii}[0]{$\\phi_i$}\n\\newcommand{\\phir}[0]{$\\phi_r$}\t\n\\newcommand{\\phis}[0]{$\\phi_s$}\n\\newcommand{\\phies}[0]{$\\phi_{es}$}\n\\newcommand{\\phirs}[0]{$\\phi_{rs}$}\n\\newcommand{\\phin}[0]{$\\phi_n$}\n\\newcommand{\\vsnl}[0]{$V^{(2)}_s(\\mathbf{k},\\omega)$}\n\n\\usepackage{setspace}\n\\onehalfspacing\n\n\\begin{document}\n\n\\section{MCMC Alternate Models}\n{\\bf Romesh Abeysuriya} \\today\n\\sffamily\n\nThis document outlines the different models available for the MCMC fitting. In terms of code, {\\tt template.m} is the abstract class that provides the standard interface for all model objects. \n\n\\begin{align}\n\\mathcal{F}(D_\\alpha) &= \\left(1 - \\frac{i\\omega}{\\alpha}\\right)\\left(1 - \\frac{i\\omega}{\\beta}\\right)\\\\[16pt]\n\\mathcal{F}(D_a) &= \\left( 1-\\frac{i\\omega}{\\gamma}\\right)^2 + k^2r^2\n\\end{align}\n\n\\subsection{Full model}\n\nImplemented in {\\tt full.m}. Includes EMG. \n\n\\begin{figure}[h!]\n\\begin{center}\n\\includegraphics[width=0.4\\textwidth]{full_model}\n\\caption{Full model schematic. A factor of $L$ is included for each connection marked with a red dot.}\n\\label{fig:full}\n\\end{center}\n\\end{figure}\n\nThis model implements the full EIRS system, in terms of the gains. Volume condution is incorporated with\n\n\\begin{align}\n\\mathbf{k} &= \\left( \\frac{2\\pi m}{L_x},\\frac{2\\pi n}{L_y} \\right),\\\\\nF(k) &= e^{-k^2/k_0^2}.\n\\end{align}\n\nThe power spectrum is given by\n\n\\begin{align}\n q^2r_e^2 &= \\left( 1-\\frac{i\\omega}{\\gamma_e} \\right)^2   - \\frac{1}{1-G_{ei}L} \\left\\lbrace LG_{ee} + \\frac{\\left[ L^2G_{ese}  + L^3 G_{erse}\\right]e^{i\\omega t_0}}{1 - L^2 G_{srs}}  \\right\\rbrace \\\\\nT &=  \\frac{L^2G_{esn}e^{i\\omega t_0 /2}}{(1 - L^2 G_{srs})(1-G_{ei}L)} \\frac{1}{k^2r_e^2 + q^2r_e^2}\\\\\n P(\\omega) &= \\sum_{m = -\\infty}^{\\infty}\\sum_{n = -\\infty}^{\\infty} \\Delta k_x \\Delta k_y |T(\\mathbf{k},\\omega)|^2||\\phi_n(\\mathbf{k},\\omega)|^2F(k)\\\\\nk^2 &=  \\left( \\frac{2\\pi m}{L_x} \\right)^2 + \\left( \\frac{2\\pi n}{L_y}\\right)^2 \n\\end{align}\n\nStability is identified by negative real part zero crossings of the dispersion relation\n\n\\begin{align}\n\\label{eqn:dispersion_relation}\n\\left( \\left[ \\left( 1-\\frac{i\\omega}{\\gamma_e} \\right)^2 + k^2r_e^2 \\right](1-G_{ei}L) - LG_{ee} \\right) (1 - L^2 G_{srs}) - (L^2G_{ese}  + L^3 G_{erse})e^{i\\omega t_0} &= 0\n\\end{align}\n\n\\begin{figure}[h!]\n\\begin{center}\n\\includegraphics[width=0.8\\textwidth]{example_full}\n\\caption{Example fit with full model.}\n\\label{fig:full}\n\\end{center}\n\\end{figure}\n\n\\begin{figure}[h!]\n\\begin{center}\n\\includegraphics[width=0.8\\textwidth]{example_full_k0}\n\\caption{Example fit with full model, with $k=0$ only.}\n\\label{fig:full}\n\\end{center}\n\\end{figure}\n\n\\clearpage\n\n\\subsection{Reduced model with L}\nImplemented in {\\tt reduced\\_l.m}. This is a new model, and bears the most (implementation) similarity to the full model. In this model, $L_{sr}$ is moved to the connection $rs$. Thus the $srs$ loop still gets two factors of $L$, but now $L_{ese} = L_{erse}$. This enables factorization of the $L$ terms in $Y$. However, separate parameters are still required for $G_{ee}$ and $G_{ei}$. \n\n\\begin{figure}[h!]\n\\begin{center}\n\\includegraphics[width=0.4\\textwidth]{reduced_l}\n\\caption{Full model schematic. A factor of $L$ is included for each connection marked with a red dot.}\n\\label{fig:full}\n\\end{center}\n\\end{figure}\n\nThe power spectrum is given by\n\n\\begin{align}\n q^2r_e^2 &=  \\left( 1-\\frac{i\\omega}{\\gamma_e} \\right)^2 - \\frac{LG_{ee}}{1-LG_{ei}} - \\frac{L^2(Y\\left( 1+Z'\\right)(1-G_{ei}))e^{i\\omega t_0}}{\\left( 1+Z' L^2 \\right)(1-LG_{ei})}\\\\\n T &=  \\frac{L^2G_{esn}e^{i\\omega t_0 /2}}{(1 - L^2 G_{srs})(1-G_{ei}L)} \\frac{1}{k^2r_e^2 + q^2r_e^2}\\\\\n P(\\omega) &= \\sum_{m = -\\infty}^{\\infty}\\sum_{n = -\\infty}^{\\infty} \\Delta k_x \\Delta k_y |T(\\mathbf{k},\\omega)|^2||\\phi_n(\\mathbf{k},\\omega)|^2F(k)\\\\\nk^2 &=  \\left( \\frac{2\\pi m}{L_x} \\right)^2 + \\left( \\frac{2\\pi n}{L_y}\\right)^2 \n\\end{align}\n\nStability is identified by negative real part zero crossings of the dispersion relation\n\n\\begin{align}\n\\label{eqn:dispersion_relation}\n\\left( \\left[ \\left( 1-\\frac{i\\omega}{\\gamma_e} \\right)^2 + k^2r_e^2 \\right](1-G_{ei}L) - LG_{ee} \\right) \\left( 1+Z' L^2 \\right) - L^2 Y\\left( 1+Z' \\right)\\left( 1-G_{ei} \\right) e^{i\\omega t_0} &= 0\n\\end{align}\n\n\\begin{figure}[h!]\n\\begin{center}\n\\includegraphics[width=0.8\\textwidth]{example_reduced_l}\n\\caption{Example fit with \\texttt{reduced\\_l}.}\n\\label{fig:full}\n\\end{center}\n\\end{figure}\n\n\\clearpage\n\n\\subsection{Reduced model}\nImplemented in {\\tt reduced.m}\n\nNormal reduced model including EMG. Equations are derived by substituting $L = 1$ into the full model except in $(1-G_{srs}L^2)$. \n\n\\begin{figure}[h!]\n\\begin{center}\n\\includegraphics[width=0.4\\textwidth]{reduced}\n\\caption{Reduced model schematic. A factor of $L$ is included for each connection marked with a red dot.}\n\\label{fig:full}\n\\end{center}\n\\end{figure}\n\nKey parameters are $X$, $Y$, $Z$. Stability is given using the dispersion relation\n\\begin{align}\n\t\\left[ \\left(1-\\frac{i\\omega}{\\gamma}\\right)^2 - X + k^2r_e^2 \\right] \\left( 1+Z' L^2 \\right) - Y\\left( 1+Z' \\right) e^{i\\omega t_0} &= 0, %JAMES DISPERSION RELATION\n\\end{align}\n\nwith $k=0$. The power spectrum is given by\n\n\\begin{align}\n\tq^2r_e^2 &= \\left( 1 - \\frac{i \\omega}{\\gamma}\\right)^2  - X - \\frac{Y(1+Z')}{1+Z'L^2}e^{i\\omega t_0},\\\\[14pt]\n\tP(\\omega) &= \\sum_{m = -\\infty}^{\\infty}\\sum_{n = -\\infty}^{\\infty} P_0 \\left| \\frac{1}{(1+Z'L^2)(k^2r_e^2+q^2r_e^2)}\\right|^2,\\\\[14pt]\n\tZ' &= Z \\frac{(\\alpha+\\beta)^2}{\\alpha\\beta},\n\\end{align}\n\n\\begin{figure}[h!]\n\\begin{center}\n\\includegraphics[width=0.8\\textwidth]{example_reduced}\n\\caption{Example fit with reduced model. }\n\\label{fig:full}\n\\end{center}\n\\end{figure}\n\n\\clearpage \n\n\\subsection{Reduced model with $L$ in prefactor}\nImplemented in {\\tt reduced\\_ln.m}. This model is the same as \\texttt{reduced} except that the factor of $L^2$ is preserved in the prefactor. The power spectrum is then given by:\n\\begin{align}\n\tP(\\omega) &= \\sum_{m = -\\infty}^{\\infty}\\sum_{n = -\\infty}^{\\infty} P_0 \\left| \\frac{L^2}{(1+Z'L^2)(k^2r_e^2+q^2r_e^2)}\\right|^2,\\\\[14pt]\n\\end{align}\n\n\\begin{figure}[h!]\n\\begin{center}\n\\includegraphics[width=0.8\\textwidth]{example_reduced_ln}\n\\caption{Example fit with reduced model.}\n\\label{fig:full}\n\\end{center}\n\\end{figure}\n\nThe primary effect of this modification is to greatly decrease the background power at high frequencies. The harmonic peaks at high frequencies are suppressed a little, but not quite enough. The rolloff at high frequency can be partially fixed with the EMG component but note that the power diverges even for the beta peak, when the EMG component should not have a significant effect.\n\n\\begin{figure}[h!]\n\\begin{center}\n\\includegraphics[width=0.8\\textwidth]{example_reduced_ln_emg_low}\n\\caption{Example of \\texttt{reduced\\_ln} with medium levels of EMG correction. The distribution shows larger values of $A_{EMG}$ may be favored. }\n\\label{fig:full}\n\\end{center}\n\\end{figure}\n\n\\begin{figure}[h!]\n\\begin{center}\n\\includegraphics[width=0.8\\textwidth]{example_reduced_ln_emg_high}\n\\caption{Example of \\texttt{reduced\\_ln} with high levels of EMG correction. The distribution shows an EMG peak, yet the spectrum is still a poor fit near 20\\,Hz. }\n\\label{fig:full}\n\\end{center}\n\\end{figure}\n\n\\clearpage\n\n\\subsection{Reduced model with $L$ in the $Y$ term}\nImplemented in {\\tt reduced\\_ly.m}. Includes EMG. Equations are derived by substituting $L = 1$ into the full model except in $(1-G_{srs}L^2)$. \n\n\\begin{figure}[h!]\n\\begin{center}\n\\includegraphics[width=0.4\\textwidth]{reduced_ly}\n\\caption{Reduced model schematic. A factor of $L$ is included for each connection marked with a red dot.}\n\\label{fig:full}\n\\end{center}\n\\end{figure}\n\nKey parameters are $X$, $Y$, $Z$. Stability is given using the dispersion relation\n\\begin{align}\n\t\\left[ \\left(1-\\frac{i\\omega}{\\gamma}\\right)^2 - X + k^2r_e^2 \\right] \\left( 1+Z' L^2 \\right) - L^2Y\\left( 1+Z' \\right) e^{i\\omega t_0} &= 0, %JAMES DISPERSION RELATION\n\\end{align}\n\nwith $k=0$. The power spectrum is given by\n\n\\begin{align}\n\tq^2r_e^2 &= \\left( 1 - \\frac{i \\omega}{\\gamma}\\right)^2  - X - \\frac{L^2Y(1+Z')}{1+Z'L^2}e^{i\\omega t_0},\\\\[14pt]\n\tP(\\omega) &= \\sum_{m = -\\infty}^{\\infty}\\sum_{n = -\\infty}^{\\infty} P_0 \\left| \\frac{L^2}{(1+Z'L^2)(k^2r_e^2+q^2r_e^2)}\\right|^2,\\\\[14pt]\n\tZ' &= Z \\frac{(\\alpha+\\beta)^2}{\\alpha\\beta},\n\\end{align}\n\n\\begin{figure}[h!]\n\\begin{center}\n\\includegraphics[width=0.8\\textwidth]{example_reduced_ly}\n\\caption{Example fit for \\texttt{reduced\\_ly}. Note that the stability criteria are now different so the tent surface corresponds to a different model.}\n\\label{fig:full}\n\\end{center}\n\\end{figure}\n\nThis model shows good suppression of features at high frequencies but the EMG component is unable to correct the rolloff at high frequencies.\n\n\n\\begin{figure}[h!]\n\\begin{center}\n\\includegraphics[width=0.8\\textwidth]{example_reduced_ly_emg_high}\n\\caption{Example of \\texttt{reduced\\_ly} with high levels of EMG correction. Again, the fit at very high frequencies is promoted in favour of discrepencies at lower frequencies.}\n\\label{fig:full}\n\\end{center}\n\\end{figure}\n\n\n\\clearpage\n\n\\subsection{Reduced LY with no $L$ prefactor}\nImplemented in {\\tt reduced\\_ly\\_no\\_n.m}. Includes EMG. The same as \\texttt{reduced\\_ly} except the $L^2$ is replaced by $1$, the same as in the reduced model i.e.\n\n\\begin{align}\n\tP(\\omega) &= \\sum_{m = -\\infty}^{\\infty}\\sum_{n = -\\infty}^{\\infty} P_0 \\left| \\frac{1}{(1+Z'L^2)(k^2r_e^2+q^2r_e^2)}\\right|^2,\\\\[14pt]\n\\end{align}\n\n\\begin{figure}[h!]\n\\begin{center}\n\\includegraphics[width=0.8\\textwidth]{example_reduced_ly_no_n}\n\\caption{Example fit \\texttt{reduced\\_ly\\_no\\_n}. No EMG component was included (multiplied by 0 internally)}\n\\label{fig:full}\n\\end{center}\n\\end{figure}\n\nThis idea didn't seem to work very well. \n\n\n\\clearpage\n\\section{Spatial variations}\nThis program uses a different approach to calculate the power spectrum based on matrix inversion. The model is the same as the full model up to this point: \n\n\\begin{align}\n\\phi_e \\left(D_{e}(1-G_{ei}L) - LG_{ee} - \\frac{\\left[ L^2G_{ese}  + L^3 G_{erse}\\right]e^{i\\omega t_0}}{1 - L^2 G_{srs}} \\right) &=  \\frac{L^2G_{esn}e^{i\\omega t_0 /2}\\phi_n}{1 - L^2 G_{srs}}\\\\\n\\label{spec_spatial}\n\\phi_e \\left(D_{e} - LG_{ee} - \\frac{\\left[ L^2G_{ese}  + L^3 G_{erse}\\right]e^{i\\omega t_0}}{(1-G_{ei}L)(1 - L^2 G_{srs})} \\right) &=  \\frac{L^2G_{esn}e^{i\\omega t_0 /2}\\phi_n}{(1-G_{ei}L)(1 - L^2 G_{srs})}\n\\end{align}\nwhere some of the parameters ($G_{ab}$, $t_0$, $L$, others) may depend on position. This equation is of the form\n\\begin{align}\nA(\\mathbf{r},\\omega) \\phi_e(\\mathbf{r},\\omega) = B(\\mathbf{r},\\omega) \\phi_n(\\mathbf{r},\\omega)\n\\end{align}\n\nTaking the Fourier transform of both sides results in a convolution\n\\begin{align}\nA(\\mathbf{k},\\omega) \\ast \\phi_e(\\mathbf{k},\\omega) = B(\\mathbf{k},\\omega) \\ast \\phi_n(\\mathbf{k},\\omega)\n\\end{align}\n\nNow, the critical step is that any discrete convolution can be written as an equivalent matrix multiplication. This is a nontrivial result. The convolution matrix consists of entries from the original matrix, but rearranged appropriately. The right side of the convolution is reshaped into a column vector, and then the left side of the convolution becomes a square matrix. Each row corresponds to one of the spatial modes. In 1D, the convolution matrix is a circulant matrix. In 2D, the matrix is block circulant. Obtaining the appropriate convolution matrix can be achieved by a very neat result that relates the convolution matrix to the DFT of the identity matrix. In 1D, the arrangement of the convolution matrix can be obtained with\n\n\\begin{lstlisting}[style=Matlab-editor,basicstyle=\\mlttfamily]\nQ = fft(eye(n_modes))\nLm = fft(1:n_modes)\nT = round(Q'*diag(Lm)*Q/numel(Lm))\n\\end{lstlisting}\n\nIn 2D, the convolution matrix can be obtained using the Kronecker product\n\\begin{lstlisting}[style=Matlab-editor,basicstyle=\\mlttfamily]\nQm = fft(eye(n_modes))\nQ = kron(Qm,Qm)\nLm = fft2(reshape(1:n_modes^2,[n_modes,n_modes]))\nT = round(Q'*diag(Lm(:))*Q/numel(Lm))\n\\end{lstlisting}\n\nThe output from these commands corresponds to the indexes of the original matrix being convolved. Thus the equivalence between convolution and matrix multiplication is established via a command like:\n\n\\begin{lstlisting}[style=Matlab-editor,basicstyle=\\mlttfamily]\nconv(A,phie)\nA(T)*phie(:)\n\\end{lstlisting}\n\nIt is most convenient in this case to keep the traditional ordering of the frequency components in the DFT - that is, prior to performing an fftshift. The first entry in the matrices thus corresponds to the zero frequency component, rather than the middle entry.\n\nFinally, the spatial operator in $A$ applies only to spatially uniform modes. Therefore, its' Fourier transform $k^2$ is added to the diagonal of the convolution matrix after it has been generated. It is omitted from $D_e$ when computing $A(\\mathbf{r},w)$. \\emph{Note that this is the reason why the form \\eqref{spec_spatial} is preferred - there is no multiplicative factor on $D_e$ which means that $k^2$ can just be directly added, remembering that the other terms can have more complex spatial and frequency dependence.}\n\nHaving obtained the convolution matrices $A_c$ and $B_c$, $\\phi_e$ can be obtained by matrix inversion\n\n\\begin{align}\n\\phi_e(\\mathbf{k},\\omega) = A_c^{-1}B_c\\phi_n(\\mathbf{k},\\omega)\n\\end{align}\n\nNoting that both $\\phi_e$ and $\\phi_n$ are arranged as column matrices. They can be reshaped into the original 2D matrices afterwards. \n\nThe spectrum $P(\\mathbf{k},\\omega)$ can be obtained directly from here. Obtaining $P(\\mathbf{r},\\omega)$ is somewhat more involved, because it requires averaging over the random phases of the white noise input. It can be obtained by assigning $M = A_c^{-1}B_c$. Then\n\n\\begin{align}\nP(\\mathbf{r},\\omega) = |\\phi_n(\\omega)^2| \\sum_{\\mu,\\nu} \\exp[i(\\mathbf{k}_\\mu - \\mathbf{k}_\\nu) \\cdot r] MM\\dag\n\\end{align}\n\nwhere $\\mu$ and $\\nu$ range over each of the spatial modes present in the calculation. This formula bears a resemblance to a DFT, but it is not identical. One advantage of this formulation is that it can be computed for an arbitrary set of positions. \n\n\n\\subsection{Spatial variations in  $t_0$ front-to-back}\nImplemented in {\\tt spatial\\_t0\\_2d.m}.\n\nThis calculation is essentially the same as the uniform full model, except that $t_0$ is allowed to vary with an amplitude up to $\\pm t_0$ along the $Y$-direction of the model. The spatial variation is limited to one spatial wavelength (i.e. one complete oscillation).\n\n\n\n\n\\end{document}", "meta": {"hexsha": "925f778c8dffa03421df6142932f4f62457f3f7f", "size": 15627, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "+bt/+model/documentation/models.tex", "max_stars_repo_name": "tmorshed/braintrak", "max_stars_repo_head_hexsha": "7773d7ddfaf14f79e0a47209321117478973318e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-10-30T19:07:37.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-29T05:53:23.000Z", "max_issues_repo_path": "+bt/+model/documentation/models.tex", "max_issues_repo_name": "tmorshed/braintrak", "max_issues_repo_head_hexsha": "7773d7ddfaf14f79e0a47209321117478973318e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-04-02T22:01:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-05T06:58:34.000Z", "max_forks_repo_path": "+bt/+model/documentation/models.tex", "max_forks_repo_name": "tmorshed/braintrak", "max_forks_repo_head_hexsha": "7773d7ddfaf14f79e0a47209321117478973318e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-10-12T14:17:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-14T15:09:43.000Z", "avg_line_length": 42.9313186813, "max_line_length": 738, "alphanum_fraction": 0.7048057849, "num_tokens": 5431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.3311084302376301}}
{"text": "\\documentclass{article}\r\n\r\n\\usepackage{blindtext}     \r\n\\usepackage{amsmath}\r\n\\usepackage{ragged2e}\r\n\r\n\\newcommand{\\ir}[1]{_{\\mathrm{#1}}}                     \r\n\r\n\r\n\\begin{document}\r\n\r\n\\section{Here it works!}\r\n\r\n\\emph{\\blindtext}\r\n\r\n\\begin{align}\r\nG(s) = \\frac{i(s)}{u(s)} = \\frac{ 1 }{R_{42} + s L_{1984} } \\:.\r\n\\end{align}\r\n\r\n\r\n\\section{Here everything gets screwed up!}\r\n\r\n\\begin{align}\r\nG(s) = \\frac{i(s)}{u(s)} = \\frac{ 1 }{R\\ir{Cu} + s L\\ir{eff}(s)} \\:.\r\n\\end{align}\r\n\r\n\\section{Here it doesn't work}\r\n\r\n\\emph{\\blindtext}\r\n\r\n\r\n\\end{document}\r\n", "meta": {"hexsha": "37195ddf07da0a930680fa5aa2b2d755b0ce7865", "size": 550, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "bugs/#2361-bug-in-lualatex-with-ragged2e-package-and-mathrm-fixed/2361.tex", "max_stars_repo_name": "MiKTeX/miktex-testing", "max_stars_repo_head_hexsha": "941ef3471275415fa864daba55aefa249e03e902", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bugs/#2361-bug-in-lualatex-with-ragged2e-package-and-mathrm-fixed/2361.tex", "max_issues_repo_name": "MiKTeX/miktex-testing", "max_issues_repo_head_hexsha": "941ef3471275415fa864daba55aefa249e03e902", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-12-06T14:21:44.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-06T15:17:47.000Z", "max_forks_repo_path": "bugs/#2361-bug-in-lualatex-with-ragged2e-package-and-mathrm-fixed/2361.tex", "max_forks_repo_name": "MiKTeX/miktex-testing", "max_forks_repo_head_hexsha": "941ef3471275415fa864daba55aefa249e03e902", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.6666666667, "max_line_length": 69, "alphanum_fraction": 0.5636363636, "num_tokens": 195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891307678321, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.331059630944739}}
{"text": "\\section{Mechanics}\n  We now trace $Alice$'s steps from joining the network to successfully completing a purchase. Suppose initially all her\n  coins, say $10\\bitcoin$, are under her exclusive control.\n\n  Two trustworthy friends, $Bob$ and $Charlie$, persuade her to try out Trust Is Risk. She installs the Trust Is Risk wallet\n  and migrates the $10\\bitcoin$ from her regular wallet, entrusting $2\\bitcoin$ to $Bob$ and $5\\bitcoin$ to $Charlie$. She now\n  exclusively controls $3\\bitcoin$. She is risking $7\\bitcoin$ to which she has full but not exclusive access in exchange for\n  being part of the network.\n\n  A few days later, she discovers an online shoes shop owned by $Dean$, also a member of Trust Is Risk. She finds a nice pair\n  of shoes that costs $1\\bitcoin$ and checks $Dean$'s trustworthiness through her new wallet. Suppose $Dean$ is deemed\n  trustworthy up to $5\\bitcoin$. Since $1\\bitcoin < 5\\bitcoin$, she confidently proceeds to purchase the shoes with her new\n  wallet.\n\n  She can then see in her wallet that her exclusive coins have remained $3\\bitcoin$, the coins entrusted to $Charlie$ have\n  been reduced to $4\\bitcoin$ and $Dean$ is entrusted $1\\bitcoin$, equal to the value of the shoes. Also, her purchase is\n  marked as pending. If she checks her trust towards $Dean$, it still is $5\\bitcoin$. Under the hood, her wallet redistributed\n  her entrusted coins in a way that ensures $Dean$ is directly entrusted with coins equal to the value of the purchased item\n  and that her reported trust towards him has remained invariant.\n\n  Eventually all goes well and the shoes reach $Alice$. $Dean$ chooses to redeem $Alice$'s entrusted coins, so her wallet\n  does not show any coins entrusted to $Dean$. Through her wallet, she marks the purchase as successful. This lets the system\n  replenish the reduced trust to $Bob$ and $Charlie$, setting the entrusted coins to $2\\bitcoin$ and $5\\bitcoin$ respectively\n  once again. $Alice$ now exclusively owns $2\\bitcoin$. Thus, she can now use a total of $9\\bitcoin$, which is expected,\n  since she had to pay $1\\bitcoin$ for the shoes.\n", "meta": {"hexsha": "eed5d0970e01cf9c3ebffe7b2650fd53cddbd183", "size": 2099, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "fc17/simplemechanics.tex", "max_stars_repo_name": "dionyziz/DecentralizedTrust", "max_stars_repo_head_hexsha": "60f65bff00041e7e940491913bd4ca3f11bf22d9", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2017-03-15T14:33:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-01T14:07:45.000Z", "max_issues_repo_path": "fc17/simplemechanics.tex", "max_issues_repo_name": "dionyziz/DecentralizedTrust", "max_issues_repo_head_hexsha": "60f65bff00041e7e940491913bd4ca3f11bf22d9", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2017-03-07T12:25:26.000Z", "max_issues_repo_issues_event_max_datetime": "2017-07-31T14:42:20.000Z", "max_forks_repo_path": "fc17/simplemechanics.tex", "max_forks_repo_name": "dionyziz/DecentralizedTrust", "max_forks_repo_head_hexsha": "60f65bff00041e7e940491913bd4ca3f11bf22d9", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-03-07T10:49:58.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-28T06:32:33.000Z", "avg_line_length": 80.7307692308, "max_line_length": 126, "alphanum_fraction": 0.7565507384, "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.33105963094473895}}
{"text": "\\ifnum\\pageno=1 \\input macros.tex \\pageno=200\\immediate\\openout\\inx=chap2.index\\makecontents\\draft{\\date (Rob)} \\fi\n%\\proofmodefalse\n\\def\\gsmooth{{s}}\n\\def\\vgsmooth{{\\vec s}}\n\\def\\symNN{N^S}\n\\def\\NN{N}\n\\def\\pepscat{1.1}\n\\def\\pepadd{1.2}\n\\def\\X{\\bf X}\n\\chapter  2 {Smoothing}\n\\medskip\n\\Section{What is a smoother?}\nA smoother is a tool for summarizing the dependence of a  response\nmeasurement $Y$ on one or more predictor measurements $X_1,\\ldots,\nX_p$.\nIt produces an estimate of this dependence that is less variable than $Y$\nitself; hence the name {\\sl smoother}.\nAn important property of a smoother is its {\\sl nonparametric} nature; that is,\nit doesn't assume a rigid\nform for the dependence.\nFor this reason, a smoother is\noften referred to as a\ntool for nonparametric regression.\nThe running mean (or moving average) is a simple example of a smoother, \nwhile a regression line is not thought of as a smoother because of its rigid\n parametric form. \n\\input spansizes.tex\n\\par\\figname{\\allsmooths}\nWe call the estimate produced by a smoother a {\\sl smooth}.\nThe most important example of smoothing involves a single predictor\nsetting, usually referred to as {\\sl scatterplot\nsmoothing}.\n\nSmoothers have two main uses.\nThe first use is for description.\nFor example, a scatterplot smoother can be used to enhance the \n visual appearance of the scatterplot of $Y$ vs $X$,\nto help our eyes  pick out the trend in the plot.\nFigure~\\pepscat\\ in Chapter~1 shows a plot\nof \\name{log(C-peptide)} versus \\name{age} for the diabetes data.\nIt seems that \\name{log(C-peptide)} has a strong dependence on \\name{age} and a scatterplot smoother\nwill be helpful in describing this relationship.\nFigure~\\allsmooths\\ shows a number of scatterplot smooths of these data; each  described in turn in this chapter.\nThe second use of a smoother is as an estimator of the dependence of $\\ev(Y)$ on\nthe predictors, and thus as a building block for the estimation of additive\nmodels, discussed in the remainder of the book.\n \n \nIn this chapter we give a brief overview of some useful smoothers.\nMost of our discussion concerns scatterplot smoothers; at the end of the \nchapter we give a brief description of multiple-predictor smoothers.\n \nThe  simplest smoother occurs in the case of a {\\sl categorical}\npredictor,\nfor example, \\name{sex} (male, female) or \\name{colour} (red, blue, green etc.)\nTo smooth $Y$ we can simply average the values of $Y$ in each category.\nThis  satisfies our requirements for a scatterplot smooth: it  captures the\n trend of $Y$ on $X$ and is  smoother than the $Y$-values themselves.\nWhile the reader might not normally think of this as {\\sl smoothing}, this simple\naveraging process is the conceptual basis for \nsmoothing in the most general setting, that of an ordered (noncategorical)\npredictor.\nThe problem here is often the lack of replicates at each \npredictor value.\nMost smoothers attempt to mimic category averaging through\n {\\sl local averaging}, that is,\naveraging the\n$Y$-values of observations having predictor  values close to a target\nvalue.\nThe averaging is done in {\\sl neighbourhoods} around the target value.\nThere are  two main  decisions to be made in scatterplot\nsmoothing:\\smallskip\n{\\parindent 20pt\n\\item{(i)}how to average the\nresponse values in each  neighbourhood, and\n\\item{(ii)} how big to take the neighbourhoods.\n\n}\\smallskip\n\\input allsmooths.tex\n\\par\nThe question of how to average within a neighbourhood is really the\nquestion of which {\\sl brand} of smoother to use, because  smoothers\ndiffer mainly  in their method  of averaging.\nIn this chapter  we describe a number of different smoothers and\ncompare them informally.\nFormal recommendations  on how to choose among smoothers are\ndifficult to make because \n few systematic  comparisons  have been made so far in the\nliterature.\n\nThe question of how big to make the neighbourhoods is discussed in\nthe next chapter.\nThe issue underlying this question is very important, however, so we briefly\ndiscuss it here.\nThe size of the neighbourhood is typically expressed in terms of an\nadjustable {\\sl smoothing parameter}.\nIntuitively, large neighbourhoods will produce an estimate with low\nvariance but potentially high bias, and conversely for small\nneighbourhoods (Fig.~\\spansizes).\nThus there is a {\\sl fundamental tradeoff between bias and variance},\ngoverned by the smoothing parameter.\nThis issue is exactly analogous to the question of how many predictors to put\nin a regression equation.\nIn the \nnext\n chapter  we discuss this important issue and the practical\nquestion of how to choose the smoothing parameter, based on the data,\nto  trade bias against variance in an optimal way.\n We also discuss some other important topics, such as\nlinear and nonlinear smoothers, the\nincorporation of  observation weights into --- and inference\nfor --- the\nfitted smooth.\n\nAll the smoothers we shall describe can easily be {\\em robustified} by replacing the averaging or least-squares operation by a more robust procedure.\nDetails can be found in Chapters~3 and  9.\n\n \nBibliographic notes  on smoothers are given at  the end\nof the next chapter.\n\n\\Sectionskip\n\\Section{Scatterplot smoothing: definition}\n\\Mark{SCATTERPLOT SMOOTHING}\nSuppose we have response measurements $\\vec y=(y_1,\\ldots,y_n)^T$ at design\npoints $\\vec x=(x_1,\\ldots,\n x_n)^T$.  We assume that each of $\\vec y$ and $\\vec x$ represent  \nmeasurements of variables $Y$ and $X$. \nIn most cases it is useful to think of\n$Y$, and sometimes $X$, as having been generated by some random mechanism, but this is not\nnecessary for the discussion here.\nIn particular we don't need to assume\n that the pairs $(x_i,y_i)$ are  a random sample from some joint distribution.\n For \nexample, the $X$-values might be preset dose levels of a drug. \n\n\n\nSince  $Y$ and $X$ are noncategorical we don't expect to find\nmany replicates at any given value of $X$. \nFor convenience we assume \nthat the data are sorted by $X$ \nand for the present discussion  that there are no tied $X$-values, so that\n$x_1 < \\cdots < x_n$.\nA trivial remedy when there are ties is to use weighted smoothers, which we \ndiscuss in  Chapter~3. \n\n \nWe  denote a scatterplot smooth of $\\vec y$ against $\\vec x$  by $\\gsmooth=\\smooth(\\vec y\\given \\vec x)$, where $\\gsmooth=\\gsmooth(x)$ is a function of $X$.\nUsually the recipe that defines $\\gsmooth(x_0)$, which is the function $\\smooth(\\vec y\\given \\vec x)$ evaluated at $x_0$, will be defined for all $x_0$, but at other times is defined only at $x_1,\\ldots,x_n$, the sample values of $X$.\nIn this latter case some kind of interpolation is necessary in order to \nobtain estimates at other $X$-values.\n\n\\Sectionskip\n\\Section{Parametric Regression}\nA regression line, estimated for example by least-squares,\n provides an estimate of the dependence of $\\ev(Y)$ on $X$.\nIt does so, however,\n by assuming a rigid form for this dependence,\nand thus it\n may or may not be appropriate for a given set of data.\nIf the dependence is linear or close to it, the regression line provides a\nconcise and useful summary.\nFor the data in Fig.~\\allsmooths, however,   the regression line is clearly inappropriate and  creates a misleading impression.\n\nIn a sense the regression line is an {\\sl infinitely smooth} function, and\nnot surprisingly many of the scatterplot smoothers that we \ndiscuss approach  the linear regression line as one extreme. \nThe other extreme\nis usually some function that interpolates the data.\n\n\nOther nonlocal parametric fits, such as polynomial regression estimates, share\nthe same pros and cons as the regression line.\nThey are useful\nif they are appropriate for the data at hand but potentially misleading otherwise.\nAlthough parametric fitting certainly isn't the solution to the scatterplot\nsmoothing problem,\nwe will still make use of it for\n comparative purposes and for  possible summaries of \nsmooths estimated by other methods. \nRegression splines are a less rigid \nform of parametric fitting which are closer in spirit to a smoother; we discuss them later in this chapter. \n\\Sectionskip\n\\Section{Bin smoothers}\nA bin smoother  mimics a categorical smoother by \npartitioning the predictor values into a number of disjoint and exhaustive regions,\nthen averaging the response in each region.\nFormally, we choose cutpoints \n$c_0 < \\cdots < c_K$\nwhere $c_0=-\\infinity$ and $c_K=\\infinity$,\n and define \n$$R_i=\\{j;c_i\\leq x_j < c_{i+1}\\};\\qquad i=1,\\ldots, K$$\nthe indices of\nthe data points in each region.\nThen $\\gsmooth=\\smooth(\\vec y\\given \\vec x)$ is given by  $\\gsmooth(x_0)=\\ave_{j\\in R_i} (y_j)$ if\n$x_0 \\in R_i$.\nTypically one chooses  five regions, for example, and picks the cutoff points \nso that \nthere is approximately an equal number of points in each region.\nThe bin smooth shown in Fig.~\\allsmooths\\ was constructed in this way and illustrates\nthe limitation of the method.\nThe estimate is not very smooth because it jumps at each cut point.\nUnless we have a prior reason to believe such  discontinuities exist, this \nestimate is not very appealing.\nOne way to make it more smooth is through the use of \noverlapping  regions, as we'll see in the next section.\n\\Sectionskip\n\\Section{Running-mean  and running-lines smoothers}\nAssume that our target value  $x_0$ equals one of the $x_j$s, say $x_i$.  If we had replicates at $x_i$,\nwe could simply  use the average of  the $Y$-values at $x_i$ as our estimate\n$\\gsmooth(x_i)$. \nNow\nwe are assuming that we don't have replicates, so instead we can average $Y$-values corresponding to $X$-values close to $x_i$. \nHow do we pick points that\nare {\\sl close} to $x_i$?\n A simple way is to choose $x_i$ itself, as well as the $k$ points  to the left  and $k$ points to the\nright of $x_i$ that are closest in $X$-value to $x_i$.\nThis is called a {\\sl symmetric nearest neighbourhood} and\nthe indices of these points \n will be denoted by\n$\\symNN(x_i)$.   Then we could define\nthe {\\sl running mean}\n$$\\gsmooth(x_i)=\\ave_{j\\in \n\\symNN(x_i)} (y_j).\\eqn{\\runm}$$\n  If it is not possible to take $k$ points to the left or right of\n$x_i$, we take as many as we can.\nA formal definition of a symmetric nearest neighbourhood is\n$$\\symNN(x_i)= \\{ \\max(i-k  ,1),\\ldots,i-1,i,i+1,\\ldots,\\min(i+ k\n,n)\\}.\\eqn{\\neigh}$$\n\nIt is not obvious how to define the  symmetric nearest neighbours at target points $x_0$ other  than the $x_i$ in the sample. \nWe could simply interpolate linearly \nbetween the fit of the two values of $X$ in the sample adjacent to $x_0$.\nAlternatively we could ignore symmetry and take the $r$ closest points to $x_0$, regardless\nof which side they are on; this is called a {\\sl nearest neighbourhood}.\nThis handles arbitrary $x_0$ in a simple and clean way.\nThe pros and cons of these two  types of neighbourhoods are discussed later.\n\\input rlsmooth.tex\n\\par\nThis simple smoother\nis\nalso called a {\\sl moving average}, and is popular for evenly-spaced time-series data.\nAlthough it is valuable for theoretical calculation because of its simplicity,\nin practice it does not work very well.  It tends to be  so wiggly that it hardly deserves the name {\\sl smoother.} \nApart from looking unpleasant, it tends to   flatten\nout  trends near the endpoints and hence can be severely biased.   \nFor example,  Fig.~\\allsmooths\\  shows a running mean smooth with $2k+1=11$ \nor 25\\% of the 43 observations.\n\n\nA simple generalization of the running mean alleviates the bias problem: we compute\na least-squares line instead of a mean in each neighbourhood. \nThe {\\sl running\nlines  smoother} is defined by\n$$\\gsmooth(x_0)=\\hat\\alpha(x_0) +\\hat\n\\beta(x_0) x_0\\eqn{\\runl}$$\n where $\\hat\\alpha(x_0)$ and $ \\hat \\beta(x_0) $ are the least-squares\nestimates for the data points in $\\symNN(x_0)$. \nFigure~\\rlsmooth\\ shows the local line computed in two different\nneighbourhoods, one in the interior, the other near the boundary.  As we\nwould expect, the fit in the interior is dominated largely by the mean and the slope\nplays a small role, whereas near the boundary the slope is important for\npicking up the trend in the asymmetric neighbourhood.\nA running-lines smooth with a neighbourhood size of $2k+1=13$ or 30\\% for the diabetes data, is shown in Fig.~\\allsmooths.\nIt seems to capture the trend in the data quite nicely\nbut is still somewhat jagged.\n\n\nThe parameter  $k$ controls the appearance of the running-lines smooth.\nLarge values of $k$  tend to produce smoother curves while small values \n tend to produce more jagged curves.\nIt is more convenient to  think not in terms of $k$ but instead in terms of\n$w=(2k+1)/n$, the proportion of points in each neighbourhood, called the {\\it\nspan}.\nWe  denote by $[\\symNN(x_i)]$ the number of points in $\\symNN(x_i)$.\n In the extreme case, if $w= 2$, so that each neighbourhood contains all of\nthe data (note that $w=1$ won't work because of endpoint effects), the running-lines smooth is the least-squares line.\nOn the other hand, if $w=1/n$, each neighbourhood consists only of one data point\nand hence the smoother interpolates the data.\nIn the next chapter  we  discuss the quantitative effects of varying the span and a\ndata-based criterion for choosing it.\n\n\nThe running-lines smoother can be computed in O(n) operations (Exercise~2.2),\nand there is a simple, effective method for span selection.\nThese can be important advantages when it is used as a building block in the\niterative  algorithms discussed  later in this book.\nOn the other hand, it tends to produce curves that are quite jagged so that\na second stage of smoothing might  be necessary. \n\n\n\nOne way to improve the appearance of the running-lines smooth  is through\nthe use of a {\\sl weighted} least-squares fit in each\nneighbourhood. \nThe running-lines smoother can produce jagged output because points in \na given neighbourhood are given equal (nonzero) weight while points\noutside of the neighbourhood are given zero weight.\nThus as the neighbourhoods move from left to right, there are discrete\nchanges in the weight given to the leftmost and rightmost points.\nWe can alleviate this problem by\ngiving the highest weight to $x_i$, and weights smoothly decreasing as\nwe move further away from $x_i$.\n^{Cleveland's (1979)} implementation of a locally-weighted running-lines smoother, {\\sl loess},   \nis popular and (essentially) works in this way.\nA full description of  locally-weighted running-line smoothers is given later in this Chapter; Fig.~\\allsmooths\\ shows one applied to the diabetes data.\nIt is  smoother than the unweighted running-lines smoother.\nThe cost of using smooth weights is a computational one, as the\nshortcuts  available for  the unweighted  running-lines\nsmoother (Exercise~2.2) do not work for locally\nweighted running-lines smoothers.\nHenceforth we will refer to the unweighted running-lines smoother\n simply as the running-lines smoother.\n\\Sectionskip\n\\Section{Kernel smoothers}\nA kernel smoother uses an explicitly defined set of local weights, defined by the {\\sl kernel}, to\nproduce the estimate at each target value.\nUsually a kernel smoother uses weights that decrease in a smooth fashion\nas one moves away from the target point.\n\\input kernelsm.tex\n\\par\nThe weight given to the $j$th point in producing the estimate at $x_0$\nis defined by\n$$S_{0j}={c_0\\over \\lambda}\nd\\left(\\big\\vert {{x_0-x_j}\\over{\\lambda}} \\big\\vert\\right)\\eqn{\\kernel}$$\nwhere $d(t)$ is an even function defined for $\\abs{t}>0$.\nThe parameter $\\lambda$ is the window width,\nand the constant \n$c_0$ is usually  chosen so that the weights  sum to unity, although\nthere are slight variations on this.\nA  natural candidate for $d$ is the standard Gaussian density: \nthis gives the so-called  { Gaussian kernel} smoother. \nOther popular kernels, with some theoretical justification (^{Eubank, 1988}),  are the Epanechnikov kernel\n$$d(t)=\\cases{ {3\\over 4} (1-t^2),&  for $\\abs{t}\\leq 1$;\\cr 0& otherwise\\cr}$$\nwhich minimizes (asymptotic) mean squared error, and the minimum\nvariance kernel \n$$d(t)=\\cases{ {3\\over 8} (3-5t^2),& for $\\abs{t}\\leq 1$;\\cr 0& otherwise\\cr}$$\nwhich minimizes the asymptotic variance of the estimate.\n  Note that the weight given to an observation is a\nfunction only of its {\\sl metric} distance from $x_0$, while the weights used by the nearest-neighbour    smoothers are typically a function of both {\\sl metric} and {\\sl rank} distance. \n\nKernel smoothers also exhibit biased endpoint behaviour. \nSpecial kernels have been developed  to overcome this bias; a simple approach is to use  kernel weights in a locally-weighted straight-line fit.\n\nA Gaussian-kernel smooth for the diabetes data is shown in \nFig.~\\allsmooths, where once again\nthe parameter $\\lambda$ was chosen so that the approximate  degrees of freedom  of the\nfitted smooth was five, the same as that of the other smooths in\nFig.~\\allsmooths.\n\n\\sectionskip\n\\section{Computational issues}\nOne can visualize the action of the kernel smooth as sliding the weight function along the $x$-axis in short steps, each time computing the weighted mean of $y$. \nThe smooth is thus similar to a convolution  between the kernel and an empirical step function defined on the data. \nThis is indeed the case, although the practical details obscure the resemblance. \nFor example, the kernel is usually truncated at the ends of the data, unless the data itself is periodic.\nTypically the kernel smooth is computed as \n$$\\gsmooth(x_0)={\\sum_{i=1}^n \nd({x_0-x_i \\over \\lambda})y_i\\over \\sum_{i=1}^n d({x_0-x_i \\over \\lambda})},\n\\eqn{\\NadWat}$$\nand so both the numerator and denominator are convolutions.\nIf the $x$-values are evenly spaced (and preferably a power of two in number), great savings can be made by using the FFT (fast Fourier transform) in performing the calculations.\nAlthough evenly spaced data are rarely the case in general regression contexts,   reasonable approximations can often reduce the data to a fine grid, where the FFT can be put to work. \nThe details are laid out in Exercise~2.9.\n\n\\Sectionskip\\Section{Running medians and enhancements}\nA somewhat different approach to smoothing is based  on   \nimprovements to the simple\nrunning mean smoother.\nFirst,\nthe running mean is replaced by a running median to make the  smoother\n   resistant to outliers in the data.\nThen the appearance of the estimate is enhanced by applying compound operations\nknown as   {\\em Hanning}, {em splitting} and {\\em twicing}, in various combinations.\nWe will not discuss these smoothers here because they are mainly\nuseful for evenly spaced data (sequences), especially time series, and they don't\ntypically provide an   adequate amount of  smoothing \nfor our purposes.\nThe interested reader can pursue the references given in the Bibliographic notes.\nWe focus on smoothers for unevenly spaced data (scatterplots), sometimes\ncalled {\\em regression smoothers}.\nIn our view,\nanother disadvantage of the enhanced running median smoothers is that they are\nhighly nonlinear functions of the response, and thus it is difficult to assess\nthe amount of fitting that they do.\nThis is an important consideration for the inferential stage of a data analysis.\nMany of the smoothers that we discuss are {\\em linear} (section~3.4.2), and this facilitates\nan approximate assessment of their {\\em degrees of freedom} (section~3.5).\n\nWe return to the time series setting for our discussion of   the Fourier analysis\nof smoothers in section~3.7, and a seasonal decomposition procedure in\nsection~8.5.\n\\input hatplot.tex\n\\Sectionskip\n\\Section{Equivalent kernels}\nThe smoothers described in this chapter are defined in quite different ways, with\nmore different ways to come. \nTheir {\\sl equivalent kernels} are one way to compare\nthem on common ground. \nAll the smoothers studied in this chapter  are {\\sl linear} in $Y$, which means that the fit at a point $x_0$ can be written as $\\gsmooth(x_0)=\\sum_{j=1}^n S_{0j}y_j$, and the $S_{0j}$ depend on all the $x_i$ and on the smoothing parameter $\\lambda$.\nThus the weight in the fit at $x_0$ which is associated with the point $x_j$ is $S_{0j}$, and this sequence of weights is known as the {\\em equivalent kernel} at $x_0$. \nA plot of $S_{0j}$ against $x_j$  shows which observations have an influence on the fit at $x_0$. \nLooking at Fig.~\\hatplot, we see that the running mean smoother has weights\neither zero or $1/m$, where $m$ is the number of observations in the neighbourhood.\nWe have used the same diabetes data as was used in Fig.~\\allsmooths.\n\nFor each smoother we have computed the equivalent kernel centered at two points: one near the boundary and one at the centre. \nThe weights at the boundary are larger and warn us that end effects may be a problem (as indeed they are). \n\nFor the  running-line smoother  the weights change linearly within the window (Exercise~2.3). \nFor both the running mean and line smoothers the weights drop off\nabruptly to zero outside the neighbourhood, and account for their jagged appearance.\nThe {\\em loess} smooth on the other hand has a strictly local neighbourhood yet the weights die down smoothly to zero.\n\nWe need to calibrate the smoothers so that they are doing approximately the same amount of smoothing, since the value of the smoothing parameter will clearly widen or narrow the equivalent kernels. \nWe do this using the {\\sl equivalent degrees of freedom}, which we describe in the next chapter. \nAll the smoothers in Fig.~\\hatplot\\ have been calibrated to do about five degrees of freedom worth of smoothing. \n\nIn the top panel we see the equivalent kernel for the  quartic polynomial fit. \nAs we might expect it spreads its influence everywhere. \n\nWe will return to Fig.~\\hatplot\\ as we encounter the remaining smoothers.\n\n\\Sectionskip\n\\Section {Regression splines}\nPolynomial regression has limited appeal due to the global nature of the \nfit, while in contrast the smoothers we have seen so far have an explicit local nature.\nRegression splines offer a compromise by representing the fit as a {\\sl piecewise}\npolynomial. \nThe regions that define the pieces are separated by a sequence\nof {\\sl knots} or breakpoints, $\\xi_1,\\ldots,\\xi_K$. \nIn addition, it is customary to enforce the piecewise polynomials to join smoothly at these knots. \nAlthough many different configurations are possible (the bin smoother was one), a popular choice  \nconsists of piecewise cubic polynomials constrained to be continuous and have continuous first and second derivatives at the knots. \nApparently our eyes are skilled at picking up second order and lower discontinuities, but not higher.\n\\input BS.tex\n\\par\nTo illustrate this point, Fig.~\\BS\\ shows four piecewise cubic fits to some simulated data, with 2\ninterior knots and different orders of continuity. \nApart from being smoother, the fit in panel (d) required fewer parameters (6 altogether) than  the others.\n\nBy allowing more knots, the family of curves becomes more flexible.\nFor any given set of knots, the smooth is computed by  multiple regression on an appropriate set of basis vectors. \nThese vectors are the basis functions representing the particular family of piecewise cubic polynomials evaluated at the observed values of the predictor $X$.\nThis approach is attractive because \nof its computational and statistical simplicity;  for example  standard\nparametric inferential  methods  can be used to test the importance \nof any of the parameters.\n\nA variant of polynomial splines are the natural splines; although they are defined for  all piecewise polynomials of odd degree, we  discuss the natural {\\sl cubic} splines. \nThese are cubic splines with the additional constraint that the function is linear beyond the boundary knots. \nTo enforce this condition we have to impose the two constraints in each of the boundary  regions: $f'''=f''=0$, which reduces the dimension of the space from $K+4$ to $K$ if there are $K$ knots. \nIn practice it is common to supply an additional knot at each extreme of the data, and impose the linearity beyond them. \nThen with $K$ interior knots (and two boundary knots), the dimension of the space of fits is $K+2$. \nNatural splines have less flexibility at the boundaries, but this tends to be a plus since the fitted values of regular regression splines have high variance near the boundary.\nFurthermore, for the same number of parameters, we get two more interior knots.  \n\n\\sectionskip\n\\section{Computational aspects} \nThe main difficulty when working with regression  splines is \n selecting the number and position of the knots. \nA very simple approach (referred to as cardinal splines) requires a single parameter, the {\\sl number} of interior knots. \nThe positions are then chosen uniformly over the range of the data. \nA slightly more adaptive version will place the knots at appropriate quantiles of the predictor variable; e.g., three interior knots would be placed at the three quartiles.\nMore adventurous schemes use data driven criteria to select the number and positions of the knots. \nThe main challenge is to come up with a sensible procedure, while avoiding a combinatorial nightmare. \nWe describe some specific proposals in Chapter~9.\n\n \nAnother computational aspect concerns the choice of basis functions for representing the splines (a vector space) for a given set of knots. \nSuppose these interior knots are denoted by $\\xi_1<\\cdots<\\xi_K$, and for notational simplicity we augment the set with two boundary knots $\\xi_0$ and $\\xi_{K+1}$. \nA simple choice of basis functions for piecewise-cubic splines, known as the truncated power series basis,  derives from the parametric expression for the smooth\n$$\\gsmooth(x)= \\beta_0+\\beta_1x+\\beta_2x^2+\\beta_3x^3+\\sum_{j=1}^K\\theta_j(x-\\xi_j)_+^3.\\eqn{\\tpseries}$$ where the $a_+$ denotes the positive part of $a$. \nEvidently (Exercise~2.4) \\tpseries\\ has the required properties:\\smallskip\n{\\parindent 20pt\n\\item{(i)} $\\gsmooth$ is cubic polynomial in any subinterval $[\\xi_j,\\xi_{j+1})$,\n\\item{(ii)} $\\gsmooth$ has two continuous derivatives, and\n\\item{(iii)} $\\gsmooth$ has a third derivative that is a step function with jumps at $\\xi_1,\\ldots,\\xi_K$.\n\n}\\smallskip\n\nWe can write \\tpseries\\  as a linear combination of $K+4$ basis functions $P_j(x)$: $P_1(x)=1$, $P_2(x)=x$,  and so on. \nEach of these  functions must  also satisfy the three conditions and  be linearly independent in order to qualify as a basis.\nEven without \\tpseries\\ it is clear that we require $K+4$ parameters to represent piecewise cubics; four for each of $(K+1)$ cubics, less three per interior knot due to the constraints.\nTo actually smooth some data pairs $\\{x_i,y_i\\}$, we would construct a regression matrix with $K+4$ columns, each column corresponding to a function $P_j$  evaluated at the $n$ values of $x$. \n\n\nAlthough \\tpseries\\ has algebraic appeal, it is not the recommended form for computing the regression spline. \nEven though a  particular cubic piece is designed to accommodate one interval, it is evaluated at all points to the right of its knot and the  numbers usually get large.\n\\input BSbasis.tex\n\\par\nThe $B$-spline basis functions provide a numerically superior alternative basis to the truncated power series.\nTheir main feature is that any given basis function $B_j(x)$ is nonzero over a span of at most five distinct knots. \nIn practice this means that their evaluation rarely gets out of hand, and the resulting regression matrix is banded.\n Of course the $B_j$ are themselves piecewise cubics, and we need $K+4$ of them if we want to span the space. \nTheir definition is rather simple (in terms of divided differences), but unhelpful for fully understanding their properties, so we omit it here and refer the reader to ^{de~Boor~(1978)}.\nFigure~\\BSbasis\\ shows the evaluated $B$-splines used to compute the fits in Fig.~\\BS(d).\n\nIn summary, regression splines are attractive because of their computational neatness, {\\sl when the knots are given}.\nStandard linear model estimation can be applied, which will be found to be very convenient in later chapters when we use regression splines in additive models.\n\nHowever the difficulty of choosing the number and position of the knots\ntends to be a drawback of this approach.\nWhen a small number of knots is used, the smoother can show some disturbing nonlocal behaviour. \nFigure~\\hatplot\\ shows the equivalent kernels for a natural cubic regression spline with three interior knots. \nThe right-hand kernel does not look much different from that for the quartic polynomial! With more knots this global influence would be dampened, but we often don't  have that many \\df\\ to spare.\n\nAnother problem with regression splines is that the smoothness of the \nestimate can not easily be  varied continuously as a function of a single  smoothing\nparameter; this is an attractive, if only approximate, property of most of the\nother smoothers that we discuss.  \n\n\\Sectionskip\n\\Section{Cubic smoothing splines}\nThis smoother is not constructed explicitly like those described so far, but instead emerges as the solution to an  optimization\nproblem.\n\n\nConsider the  following problem: among all functions \n$f(x)$ with absolutely continuous first derivatives and integrable second derivatives, find the one that minimizes\n$$\\sum_{i=1}^n\\{y_i-f(x_i)\\}^2 +\\lambda\\int_{-\\infty}^\\infty \\{f''(t)\\}^2 \\, dt\\eqn{\\qb}$$ where\n $\\lambda$ is a fixed constant.\nThis criterion satisfies the requirements for a scatterplot smoother that  we\nmentioned earlier. \nThe first term measures closeness to the data while the\nsecond term penalizes curvature in the function. \nNow it is one thing to state \na criterion like $\\qb$ and quite another to find the optimizing function.\n Remarkably, it can be shown that $\\qb$ has an explicit,  unique minimizer and\nthat minimizer is  a {\\sl natural cubic spline} with knots at the unique values of $x_i$\n(Exercise~2.6).\nAt face value it seems that the family is overparametrized, since there are  as many as $n-2$ interior knots. \nThis would result in $n+2$ parameters, although the  constraints on each end bring it down to $n$.  We'll see however that the coefficients are estimated in a constrained way as well, and this can bring the {\\sl effective} dimension down dramatically.\n\n\nA cubic \nsmoothing spline fitted to the diabetes data is shown in Fig.~\\allsmooths. \nIt looks\n much like the\nrunning-lines smooth\nbut is less jagged.\n\n\nThe parameter $\\lambda$ plays the same role as the span  in the running-lines smooth. \nLarge values of $\\lambda$  produce smoother curves while\nsmaller values  produce  more wiggly curves.  At the one extreme, as\n$\\lambda\\rightarrow \\infinity$, the penalty term dominates, forcing\n$f''(x)=0$, and thus the solution is the least-squares line. \nAt the other extreme, as $\\lambda\\rightarrow 0$, the penalty term becomes unimportant and the\nsolution tends to  an interpolating twice-differentiable function. \nWe discuss methods for choosing  $\\lambda$ in Chapter~3.\n \n\\sectionskip\n\\section{Computational aspects}\nUsing the fact that the solution to $\\qb$ is a natural cubic spline with $n-2$ interior knots, we can represent it in terms of a basis for this space of fits.\nFor computational convenience, we will use the unconstrained $B$-spline basis, and write \n $\\gsmooth(x)=\\sum_1^{n+2} \\gamma_i B_i(x)$, where $\\gamma_i$ are\ncoefficients and the $B_i$ are  the cubic $B$-spline basis functions. \nAs written here, $s$ lies in an $(n+2)$-dimensional space; however, the natural splines are a subspace.\nWe can now simply replace $f$ in \\qb\\ by $s$ and perform the integration.\nThen defining the $n\\times (n+2)$ matrix $ \\bB$ and $(n+2)\\times (n+2)$ matrix $\\fat{\\Omega}$ by\n$$\nB_{ij}=B_j(x_i)$$\nand \n$$\\fat{\\Omega}_{ij}=\\int_{-\\infty}^\\infty B_i''(x)B_j''(x) \\, dx,$$\nwe can rewrite the criterion $\\qb$ as\n$$(\\vec y-\\bB\\fat\\gamma)^T(\\vec y-\\bB\\fat\\gamma) +\\lambda\\fat \\gamma^T\\fat{\\Omega}\n\\fat \\gamma\\eqn{\\qd}$$\nAlthough at face value it seems that there are no boundary derivative constraints,  it turns out that the penalty term  automatically imposes them. \n\nSetting the derivative with respect to $\\gamma$ equal to zero gives \n$$(\\bB^T\\bB+\\lambda\\fat\\Omega)\\hatfat\\gamma=\\bB^T\\vec y\\eqn{\\eqq}$$\nSince the columns of $\\bB$ are the evaluated  $B$-splines, in order from left to right and evaluated at the {\\sl sorted} values of $X$, and the cubic $B$-splines have local support, $\\bB$ is lower 4-banded. \nConsequently  the matrix $\\vec M=(\\bB^T\\bB+\\lambda\\fat{\\Omega})$ is\n4-banded and hence its Cholesky decomposition $\\vec M=\\bL\\bL^T$ can be computed easily.  \nOne\nthen solves $\\bL\\bL^T\\hatfat\\gamma=\\bB^T\\vec y$ by back-substitution to give $\\hatfat\\gamma$\nand hence the solution  $\\hat\\gsmooth$ in O(n) operations. \n\n\nFor theoretical purposes, it is convenient to  rewrite  the solution\n vector $\\vgsmooth$ ($\\gsmooth$ evaluated at each of the $n$ values of $X$ in the sample)  in another form.\nLet $\\bN$ be an $n\\times n$ nonsingular {\\sl natural-spline} basis matrix for representing the solution (Exercise~2.5). \nDenote by $\\hatfat{\\beta}$  the transformed version of $\\hatfat\\gamma$ corresponding to the change in basis.  Then we can write  \n$$\\vgsmooth=\\bN\\hatfat{\\beta}=\\bN(\\bN^T\\bN+\\lambda\\fat{\\Omega})^{-1}\\bN^T\\vec y=\n(\\bI+\\lambda \\bK)^{-1}\\vec y\\eqn{\\qf}$$\nwhere $\\bK={\\bN^{-T}}\\fat{\\Omega} \\bN^{-1}$.\nIn terms of the candidate fitted vector $\\vec f$ and $\\bK$, the cubic smoothing spline $\\vgsmooth $ minimizes\n$$(\\vec y-\\vec f)^T(\\vec y-\\vec f) +\\lambda\\vec f^T\\bK\n\\vec f\\eqn{\\nqd}$$ over all vectors $\\vec f$.\nIt is appropriate to call the term $\\vec f^T\\bK\\vec f$ a roughness penalty, since it can be shown to be a quadratic form in second differences.\nThe cubic smoothing spline, because of the implicit way it is defined, doesn't appear\nto use {\\sl local averaging}.\nHowever, the equivalent-kernel weights  in Fig.~\\hatplot\\ show that it does possess local behaviour quite similar to kernels or locally-weighted lines. \nThe equivalent kernel is nowhere nonzero, but is close to zero far from the target point. \nOther examples of equivalent kernels are given in ^{Buja, Hastie and Tibshirani (1989)}, and\nan asymptotic form for the equivalent kernel of smoothing splines is derived by ^{Silverman (1984)}.\nOne might say, then,  that a cubic  smoothing spline is  approximately a {\\sl kernel} \nsmoother. \n\nThe smoothing parameter $\\lambda$ controls the shape of the kernel\nor weight function.\nAs one would expect,\nwhen $\\lambda$ is decreased\nthe weights tend to concentrate more around the target point, while as\n$\\lambda$ is increased, they spread out more. \nWe discuss the properties of smoothing splines in more detail in Chapters~5 and section~9.3.6.\n\n\\Sectionskip\n\\Section{Locally weighted running-line smoothers}\nHere we describe in more detail  the locally-weighted smoother of ^{Cleveland (1979)}, currently called {\\sl loess} in the S statistical-computing language. \nAlthough any polynomial can be fitted locally, we discuss local lines.\n\nA locally-weighted straight-line smooth $\\gsmooth(x_0)$ using $k$ nearest neighbours is computed in a number of steps:\\smallskip\n{\\parindent 20pt\n\\item{(i)} The $k$ nearest neighbours of $x_0$ are identified, denoted by\n$\\NN(x_0)$.\n\\item{(ii)}$\\Delta(x_0)=\\max_{N(x_0)}\\abs{x_0-x_i}$ is computed, the distance of the furthest near-neighbour from $x_0$.\n\\item{(iii)}Weights $w_i$ are assigned to each point in $\\NN(x_0)$, using the  {\\sl tri-cube} weight function:\n$$W\\biggl({\\abs{x_0-x_i}\\over {\\Delta(x_0)}}\\biggr)\n \\eqn{\\clev}$$\nwhere $$W(u)=(1-u^3)^3 \\quad\\for\\quad 0\\leq u <  1 \\eqn{\\tri}$$\nand zero otherwise.\n\\item{(iv)} $\\gsmooth(x_0)$ is the fitted value at $x_0$ from the weighted least-squares fit of $y$ to $x$ confined to $\\NN(x_0)$ using the weights computed in (iii).\n\n}\\smallskip\n\\input loessm.tex\n\\par\nFigure~\\loessm\\ depicts the situation, using the diabetes data once again. \nNotice that the kernel is truncated at one end due to the metric asymmetry of the neighbourhood.\n\nCleveland also discusses the use of a robust regression within each\nneighbourhood, to protect against outliers. \nThis effectively works by repeatedly smoothing the data, and at each iteration down-weighting points with large residuals. \nSee Chapters~3 and  9 for more details.\n\nA  locally-weighted running-line smooth\nis shown in Fig.~\\allsmooths. \nThe number of nearest-neighbours, usually expressed\nas a percentage or {\\sl span} of the data points, is the smoothing parameter. \nIn Figs~\\allsmooths\\ and \\loessm\\  a span of $21/43$ was used, chosen to make  \n the degrees of freedom approximately equal to that of the other smooths.\n\nIn principle, nearest neighbourhoods \nare preferable to \nsymmetric nearest neighbourhoods because in a  neighbourhood with \na fixed number of points, the average distance of the points to the target point\nis less in the nearest neighbourhood (unless the predictors are evenly spaced).\nIn general this  should result in less bias.\nWe use symmetric nearest neighbourhoods in a running-lines smoother, however,\nbecause of their superior performance at the left and right endpoints.\nA nearest neighbourhood at the endpoint contains the same number of data\npoints\nas a neighbourhood in the middle of the data,\n so that when a least-squares fit is applied there, too much\nweight is given to points far away from the target point.\nA symmetric nearest neighbourhood, on the other hand, contains only about\nhalf of the number of points as a full neighbourhood, and thus  \nautomatically reduces the weight given to far way points.\nNearest neighbourhoods work satisfactorily with {\\sl loess} at the endpoints, however,\nbecause the tri-cube function does the job of down-weighting far away points.\n\nThe locally-weighted smoothers are popular, since they enjoy the best of both worlds. \nThey share the ability of near-neighbour smoothers to adapt their bandwidth \nto the local density of the predictors, while they have the smoothness features\nof kernel smoothers.\n\nAlthough in principal it requires $O(n^2)$ operations to compute a locally-weighted smooth, the current implementations compute the fit over a grid of values of $x$, and use interpolation elsewhere.\n\n\\Sectionskip\n\n\\Section{Smoothers for multiple predictors}\nSo far we have talked about smoothers for a single predictor, that is,\nscatterplot smoothers.\nWhat if we have more than one predictor, say $X_1,\\ldots, X_p?$.\nThen our problem is one of fitting a $p$-dimensional surface to $Y$.\nThe multiple regression of $Y$ on $X_1,\\ldots, X_p$ provides a\nsimple, but very limited, estimate of the surface.\nOn the other hand,\nit is easy conceptually  to generalize the running mean,  locally-weighted \nrunning-lines, and kernel smoothers to this setting.\nThe first two smoothers require a definition of {\\sl nearest neighbours}\nof a point in $p$-space.\n{\\sl Nearest} is determined by a distance measure and for this \nthe most obvious choice is Euclidean distance.\nNote that the notion of symmetric nearest neighbours is no longer meaningful\nwhen $p > 1$.\nHaving defined a neighbourhood,\nthe generalization of the running mean estimates\n the surface at the target point by averaging the\nresponse values in the neighbourhood.\n\nThis\nhighlights an  important detail: what shape  neighbourhood do we use?  \nNearest-neighbourhoods defined in terms of Euclidean distance are typically\n spherical, but one could imagine more general \nneighbourhoods defined in terms of a covariance matrix $\\Sigma$ of the predictors.\n Such a metric  would consider  points lying on an ellipse centered at the target\npoint to be equidistant from the target.  \nThis generalization is not a purely\nacademic issue --- it may be important if the covariates are measured in different\nunits or are correlated.  In linear\nregression, the coefficients automatically scale each covariate\ncorrectly.  \nVarious strategies are used in practice, an obvious one being to standardize the individual variables prior to smoothing.\nThis might not always be the best choice, however.\nFor example, if the underlying surface changes more rapidly with one variable\nthan the other, one may wish to have the neighbourhoods thinner in the direction of the first variable. \nThis can be achieved by differential scaling of the variables. \n\\figname{\\bivar}\\par \nThe kernel  smoother is generalized in an analogous way\nto the running mean.\nGiven two $p$-vectors\n$\\vec  x^0$ and $\\vec  x^i$\nin predictor space, \nthe weight given to this $i$th point for the fit at  $\\vec  x^0$\nis $S_{0i}=(c_0/\\lambda)\nd({{\\norm{\\vec x^0-\\vec x^i}}/\\lambda})$\nwhere $d(t)$ is an inverse distance measure\nand $\\norm{\\cdot}$ is a norm, for example squared distance.\nThe constant $c_0$ is usually chosen to make the weights sum to unity, so that the smoother \nreproduces the constant function.\nThe multi-predictor Gaussian kernel uses \n$d(t)$ equal to the standard  Gaussian density.\nThe resulting weight function is depicted in Fig.~\\bivar.\n\\midinsert\n\\vbox{\n\\centerline{\\psfig{file=figures/bivar.p,width=3in}}\n\\figurecaption{\\bivar}{ The weight function for a bivariate Gaussian kernel smoother.\n}*\n}\n\\endinsert\nThe choice of norm  is important in this setting,  and  determines the  shape of\nthe  neighbourhoods in predictor space.\nOne might argue, for example, that the norm should incorporate \ncovariance information  by replacing the\nsquared error norm with  the ``Mahalanobis'' distance\n $$\\norm{\\vec x^0-\\vec x^i}=(\\vec x^0-\\vec x^i)^T\\Sigma^{-1}(\\vec x^0-\\vec x^i)$$\nwhere \n $\\Sigma$ is  the covariance matrix of the predictors.\n\n\nLocally-weighted lines generalize equally  easily to two or more dimensions.\nThe simplest generalization hardly needs any different wording than that used to describe the univariate situation. \nOnce a multivariate distance is defined,\nnearest-neighbourhoods and tri-cube weights get assigned in exactly the same way.\nOne computes a local plane rather than a line.\n\n \nThe  cubic  smoothing spline is more difficult to generalize to two or higher \ndimensions: the so-called {\\sl thin-plate spline} is one such\ngeneralization. \nIt derives from generalizing the second derivative penalty for smoothness to a  two dimensional Laplacian penalty of the form \n$$\\int\\int\\left\\{\\left({\\partial^2 f\\over \\partial x_1^2}\\right)^2 +  \\left({\\partial^2 f\\over \\partial x_1\\partial x_2}\\right)^2+\\left({\\partial^2 f\\over \\partial x_2^2}\\right)^2\\right\\}\\, dx_1dx_2.$$ \nThe computations are  $O(n^3)$ in number compared to the $O(n)$ for univariate splines.\nDetails are not given here; the interested reader can find references in the\nbibliographic notes at the end of Chapter~3.\n\nAnother generalization is known as multivariate {\\sl tensor product} splines. \nThese are also useful for generalizing univariate regression splines. \nThe basic idea is to construct two-dimensional basis functions by multiplying together one-dimensional basis functions in the respective predictors. \nWe discuss these in more detail for multivariate regression splines in Chapter~9. \nFor the smoothing version of tensor product splines, the effective basis set has dimension $n^2$ formed by the tensor product of the univariate bases. \nThe fit will be a damped regression onto this space of basis functions.\nSee the references at the end of Chapter~3 for  details. \n\nWe are not devoting much space to multi-predictor smoothers because we don't\nfeel that they are very useful for more than two or three predictors.\nIndeed, their many shortcomings (e.g.~difficulty of interpretation and computation)\nprovide an impetus for studying   additive models, the central\ntopic of this book.\nThese comments refer to the generic multivariate smoothers as described here. \nWe are not referring to some of the adaptive multivariate nonparametric regression methods, which might also be termed surface-smoothers, and which were designed to overcome some of these objectional aspects.  \nWe discuss some of the problems associated with multi-predictor smoothing in detail at the\nbeginning of Chapter~4.\nDespite these criticisms,  multi-predictor smoothers  (especially the bi-predictor) are useful\nin certain settings, as later examples  show. \n\n\\Sectionskip\n\\Section{Discussion and bibliography}\nIn this chapter we have described a number of scatterplot smoothers,\nincluding the running-mean and  running-lines smoothers, cubic regression and smoothing \nsplines, locally-weighted running-lines and kernel smoothers. \nWe have also touched on surface smoothers.\nOur discussion has focused on smoothers with which we have  some experience, and any imbalance in our introduction simply reflects this.\nIn addition, the emphasis in the book is not on smoothers {\\sl per~se}, but \non\nsmoothers as building blocks in the estimation of additive models.\n\n \n Some recent theoretical results suggest that for appropriately chosen\nsmoothing parameters,  there are not likely to be large differences between\nlocally-weighted running-lines, cubic smoothing-splines and kernel smoothers\n(^{Silverman, 1984}; ^{Muller, 1987}).\nIn order to assess the finite-sample operating characteristics of these \nand other smoothers, a comprehensive Monte Carlo study, akin to the \nPrinceton robustness study, would be very useful. \nA recent report by ^{Breiman}\nand Peters (1988) has this flavour.\n\nFor a detailed  bibliography, see the notes at the end of Chapter~3. \nHere we list some introductory references we have found useful.\n^^{Eubank, R.L.} Eubank (1988) covers most of the material in various levels of detail, especially smoothing splines. \n^^{Silverman, B.W.} Silverman's (1985) paper on smoothing splines not only gives an easy to read introduction but also touches on a variety of applications. \n^^{Cleveland, W. S.} Cleveland (1979) introduces the locally-weighted running-line smoother for univariate problems, and \n^^{Devlin, S.}^^{Grosse, E. H.} ^{Cleveland, Devlin and Grosse (1988)} describe the multivariate version.\n\n\\Sectionskip\n\\Section{Further results and exercises 2}\n\\Mark{EXERCISES \\ 2}%\n\\beginexercises%\n\\exercise For the diabetes data, compute one of each of the smooths described\nin this Chapter\nfor the variable \\name{base deficit}.\nCompare qualitatively the resulting estimates in terms of notable features\nand smoothness.\n\n\\exercise {\\sl Updating formula for running-line smooth.}\nSuppose we add a point $(x_{j+1},y_{j+1})$ to a neighbourhood\ncontaining $j$ points.\nIf the means, variance of $X$, and covariance of $X$ and $Y$  for the first $j$ points are \n$\\bar x_j$, $\\bar y_j$, $S^x_j$, and $S^{xy}_j$, show that\n$$\\bar x_{j+1}=(j\\bar x_j+x_{j+1})/(j+1)$$\n$$\\bar y_{j+1}=(j\\bar y_j+y_{j+1})/(j+1)$$\n$$(j+1)S^x_{j+1}=jS^x_j+{{j+1}\\over j}(x_{j+1}-\\bar x_{j+1})^2$$\n$$(j+1)S^{xy}_{j+1}=jS^{xy}_j+{{j+1}\\over j}(x_{j+1}-\\bar x_{j+1})(y_{j+1}-\n\\bar y_{j+1}).\\eqn{\\upd}$$\n\nWhat are the equivalent equations for deleting a point?\nTogether these\ncan be used to update the least-squares slope and intercept, and hence the entire fit can be computed in $O(n)$ operations.\n\n\\exercise Derive an expression for $S_{ij}$, the coefficient of $y_j$ in the\nexpression $\\gsmooth(x_i)=\\sum_{j=1}^n S_{ij}y_j$ for the running-line fit at $x_i$, \nusing $\\symNN(x_i)$ to denote the set of indices of the $k$ symmetric nearest-neighbours to $x_i$. \n\n\n\\exercise  Show that the truncated power series representation $$\\gsmooth(x)= \\beta_0+\\beta_1x+\\beta_2x^2+\\beta_3x^3+\\sum_{j=1}^k\\theta_j(x-\\xi_j)_+^3$$ satisfies the three conditions of a cubic spline given in the text.\n\n\\exercise {\\sl Basis for natural splines.} Suppose $B$ is an $n\\times (K+4)$ matrix containing the evaluations of the cubic  $B$-spline basis functions with $K$ interior knots evaluated at the $n$ values\nof $X$. \nLet $C$ be the $2\\times (K+4)$ matrix containing the second derivatives\nof the basis functions at the boundary points $x_1$ and $x_n$. \nShow how\nto derive $N$ from $B$, an $n\\times (K+2)$ basis matrix for the natural  cubic splines with the same interior knots and boundary knots at the extremes of the $X$.   \n\n\\exercise {\\sl Derivation of smoothing splines; ^{Reinsch (1967)}.} Consider the following optimization problem: minimize \n$$\\int_{-\\infty}^\\infty \\{f''(x)\\}^2 \\, dx\n\\quad \\hbox{subject to}\\quad \\sum_{i=1}^n \\{y_i-f(x_i)\\}^2 \\leq \\sigma\n\\eqn{\\sopt}$$\nover all twice differentiable\nfunctions $f(x)$.\nTo solve this problem, consider the Lagrangian functional\n$$F(f)=\\int_{-\\infty}^\\infty\\{f''(x)\\}^2 \\, dx + \\rho \\left[ \\sum_{i=1}^n \\{y_i-f(x_i)\\}^2-\\sigma+z^2\\right]\\eqn{\\lageq}$$\nwhere $z$ is an auxiliary variable.\n\\smallskip\n{\\parindent 20pt\n\\item{(i)} To find the minimum of $F(f)$, compute $d F\\{f+\\delta h(x)\\}\\delta$ where\n$h(x)$ is any twice differentiable function.\n(This is a standard technique in the calculus of variations).\nIntegrate by parts the resulting expression (twice) and conclude that the solution\nis a piecewise cubic polynomial with knots at the $x_i$.\nShow that the solution and its first two derivatives are continuous at the\nknots, but that the third derivative may be discontinuous there.\nShow also that the second derivative is zero outside of the range of the \n$x_i$.\n\n\\item{(ii)} Compute $d F(f)\\rho$ and $\\partial F(f)/\\partial \\sigma$ and conclude that either $\\hat \\rho=0$\nimplying that the least-squares line is a solution to $\\sopt$, or\n$\\hat\\rho\\neq 0$, in which case the solution is nonlinear.\n\n\\item{(iii)} Establish an equivalence between the $\\sopt$ and the penalized least-squares\nproblem $\\qb$ given in the text.\n}\n\n\\exercise Suppose each observation has associated with it a weight $w_i$.\n\\smallskip\n{\\parindent 20pt\n\\item{(i)} Derive the appropriate cubic smoothing spline using a weighted residual sum of squares.\n\\item{(ii)} Suppose there are ties in the $x$-values. \nSuggest a way to overcome this for smoothing splines.\n\n}\n\n\\exercise {\\sl Semi-parametric regression; ^^{Green, P.J.}^^{Jennison, C. }^^{Seheult, A.} Green, Jennison, and Seheult (1985).} Suppose we have a set of $n$ observations of $p$ predictors arranged in\nthe $n \\times p$ matrix  $\\bf X$, an additional covariate $\\vec z$, and a response vector $\\vec y$. \nWe wish to fit the model $y_i=\\vec x^i{\\fat\\beta} +f(z_i) +\\varepsilon_i$ by penalized least-squares.\nConstruct an  appropriate penalized residual sum of squares, and show that the minimizers must satisfy the following pair of {\\sl estimating} equations:\n$$\\eqalign{ {\\fat\\beta}&=(\\X^T\\X)^{-1}\\X^T(\\vec y-\\vec f)\\cr\nf &= \\smooth(\\vec y -\\X{\\fat\\beta}\\given \\vec z)\\cr}$$\nwhere $\\smooth$ is an appropriate smoothing-spline operator, and $\\vec f$ represents the function $f$ evaluated at the $n$ values  $z_i$.\n\\exercise {\\sl Efficient kernel smoothing; ^{Silverman (1982)}, ^{H\\\"ardle (1986)}}\nConsider the ^^{Nadaraya, E.A.}^^{Watson, G.S.}Nadaraya-Watson form of the kernel smooth given by equation \\NadWat:\n$$\\gsmooth(x_0)={\\sum_{i=1}^n\\rho({x_0-x_i \\over \\lambda})y_i\\over \\sum_{i=1}^n\\rho({x_0-x_i \\over \\lambda})}.$$\nWe wish to use the FFT to compute both the numerator and denominator. \nWith that end in mind we define a fine grid that covers the range of $X$.\nDescribe how you would approximate the data on the grid and use the FFT to perform the computations. \nPay particular attention to:\\smallskip\n{\\parindent 20pt\n\\item{(i)} what happens at the boundaries, and\n\\item{(ii)} a method for overcoming discontinuities due to the approximation.\n\n}\n\\exercise Extend the methods described in the previous exercise in order to compute a kernel-weighted running-line fit.\n\\exercise Suppose $\\bS$ is an $n\\times n$ smoother matrix for\nsmoothing against the $n$ unique predictor values $\\vec x=(x_1,\\ldots, x_n)^T$.\nThat is, if $s(x_i)=\\sum_{j=1}^n S_{ij}y_j$, then $\\bS$ has $ij$th entry $S_{ij}$.\nFor all of the\nsmoothers that we have described, $\\bS\\vec 1=\\vec 1$, and for most $\\bS\\vec\nx=\\vec x$.  For which is the second statement true, and what are the\nimplications of these two results?  For smoothing splines the symmetric\nstatements are also true:  $\\bS^T\\vec 1=\\vec 1$ and $\\bS^T\\vec x=\\vec\nx$, since $\\bS$ is symmetric in this case.  Is this true for any of the\nother smoothers?  What are the implications of these conditions?  How\nwould you modify $\\bS$ for the other smoothers in order that the first\nor both of these latter conditions are satisfied.  Try some examples\nand see what happens to the local support properties of the equivalent\nkernels.\n\\endexercises\n\\vfill\\supereject\n", "meta": {"hexsha": "dd4132fc7166e44011d85ee8e3d569e03d8aeef3", "size": 52168, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/index/chap2.tex", "max_stars_repo_name": "noelhunt/PadsPi", "max_stars_repo_head_hexsha": "636aeeb633ec1c6cf9fe629bb974096586921ed4", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/index/chap2.tex", "max_issues_repo_name": "noelhunt/PadsPi", "max_issues_repo_head_hexsha": "636aeeb633ec1c6cf9fe629bb974096586921ed4", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/index/chap2.tex", "max_forks_repo_name": "noelhunt/PadsPi", "max_forks_repo_head_hexsha": "636aeeb633ec1c6cf9fe629bb974096586921ed4", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.5813449024, "max_line_length": 251, "alphanum_fraction": 0.7656417727, "num_tokens": 13487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621764862150636, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3310596223053029}}
{"text": "\\section{Introduction}\n\\label{sec:intro}\n\\dan{TODO}\n%Introduce GCNN\nRecent researches in graph representation learning leverage\n\\textbf{Graph Convolution Neural Networks} (GCNNs) suggest a new direction on deep learning on graphs. Compared to traditional classification methods on graph like label propagation or matrix factorization, GCNN models provides user-friendly end-to-end solutions as well as state-of-art performance results. GCNN models layer-level interpretability\n\n\n%Introduce HIN and metapath.\nHomogeneous methods can be directly applied to heterogeneous graphs by neglecting different roles of nodes in the graph.\nHowever, previous successes of traditional algorithms such as metapath2vec \\cite{DongCS17} and ESim \\cite{ShangQLKHP16} suggest that models that consider heterogeneity of data may produce better results. Intuitively, deep learning models taking heterogeneity into account may produce decent results as well.\n\nCompared to the vast volume of GCNN researches published on homogeneous graphs, deep learnings on heterogeneous graphs have been less explored. \nSome methods convert heterogeneous graphs to homogeneous graphs by\n\\textbf{Topology Shrinking Sub-network} (TSSN) \\cite{WanOKH15}, \n\nso that methods designed for homogeneous graphs can be applied. \n%briefly describe TSSN\nGiven an HIN $G$ = ($V$, $E$), the TSSN of a certain object type $T_i$ derived from a meta-path $\\Phi$ is a graph whose nodes consist of only objects of type $T_i$ and whose edges connect objects that are related by instances of $\\Phi$.\nHAN is a state-of-art GCNN model proposed along this line of research.\n  \n  \n%What information does HAN fail to capture in their model?\nHAN considers hierarchical attention mechanism on heterogeneous graphs, yet fails to address differences of intermediate nodes during the shrinking pre-process of graph structure. \n\nHowever methods relying on TSSNs did not fully capture of heterogeneous graphs.\n\\dan{TODO:problem yet to solve}\n\n\\comment{\n\\begin{figure}\n    \\centering\n        \\includegraphics[width = 1.09\\linewidth]{flow_graph3.pdf}\n        \\caption{The key steps of (a) basic spectral clustering; (b) with local scaling and PI; (c) ROSC}\n        \\label{figure:flow_graph}\n\\end{figure}\n}\n\nIn this paper, we propose a novel semi-supervised classification algorithm on \\textbf{H}eterogeneous \\textbf{I}nformation \\textbf{N}etworks via \\textbf{G}raph \\textbf{C}onvolution \\textbf{N}ets, named HINGCN. Apart from hierarchical aggregation of node features, our model takes into account neglected edge information in TSSN methods as well.  by fine-tuning on pre-trained edge features\n\n\nOur main contributions are:\n\n\\noindent$\\bullet$\nTo compensate loss of information in shrinking homogeneous graph, we proposed a novel pre-process of edge feature. We also propose a novel fine-tuning mechanism for edge features, with limited computation power.\n\n\\noindent$\\bullet$\nWe propose an \n\n\\noindent$\\bullet$\nWe conduct extensive experiments %using synthetic and real datasets \nto evaluate the performance of HINGCN\nagainst $9$ other classification methods. \nOur results show that HINGCN performs very well against the competitors. \nIn particular, it is very robust in that it consistently performs well over all the datasets tested. \nAlso, it outperforms others by wide margins for datasets that are highly multi-scale. \n\nThe rest of the paper is organized as follows.\n%In Section~\\ref{sec:preliminary} we give more details of spectral clustering and briefly \n%describe the power iteration method.\nSection~\\ref{sec:related} mentions related works on heterogeneous graph neural networks, graph embedding and described several semi-supervised classification algorithms.\nSection~\\ref{sec:algorithm} presents the HINGCN algorithm.\nSection~\\ref{sec:exp} describes the experiments and presents experimental results.\nFinally, Section~\\ref{sec:conclusion} concludes the paper.\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "078e1bc45a101c80efd163bfda1d7cf5b8ab342e", "size": 3913, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/HINGCN/tex/introduction.tex", "max_stars_repo_name": "dingdanhao110/HINGCN", "max_stars_repo_head_hexsha": "281b73c03bd3b00e35bce4c5e1c27076233555e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paper/HINGCN/tex/introduction.tex", "max_issues_repo_name": "dingdanhao110/HINGCN", "max_issues_repo_head_hexsha": "281b73c03bd3b00e35bce4c5e1c27076233555e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/HINGCN/tex/introduction.tex", "max_forks_repo_name": "dingdanhao110/HINGCN", "max_forks_repo_head_hexsha": "281b73c03bd3b00e35bce4c5e1c27076233555e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.4868421053, "max_line_length": 388, "alphanum_fraction": 0.7991311015, "num_tokens": 877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3310596223053028}}
{"text": "\\documentclass[11pt,paper=a4]{article}\n\n%\\documentclass[12pt,preprint]{aastex}\n\n\n\\usepackage{amsmath}\n\\usepackage{natbib}\n\\usepackage{graphicx}\n\\usepackage[usenames,dvipsnames]{color}\n\\usepackage[absolute,overlay]{textpos}\n\\usepackage{color}\n\\usepackage{multirow}\n\n\\usepackage{hyperref}\n\\hypersetup{\n        colorlinks = true,\n        linkcolor = blue,\n        anchorcolor = red,\n        citecolor = blue,\n        filecolor = red,\n        urlcolor = red\n} \n\n\\newcommand{\\eht}{\\overline}    \n\\newcommand{\\fht}{\\widetilde}        \n\\newcommand{\\dr}{\\frac{\\partial}{\\partial r}}\n\\newcommand{\\dt}{\\frac{\\partial}{\\partial t}}\n\\newcommand{\\dth}{\\frac{\\partial}{\\partial \\theta}}\n\\newcommand{\\dph}{\\frac{\\partial}{\\partial \\phi}}\n\n\\def\\ef#1{#1'}\n\\def\\ff#1{#1''}\n\\def\\fhtc#1{\\left\\{#1\\right\\}}\n\\def\\erho{\\eht{\\rho}}\n\n% From Maxime's paper\n\n\n\\newcommand{\\vdag}{(v)^\\dagger}\n\\newcommand{\\Teff}{T_\\mathrm{eff}}\n\\newcommand{\\Rsun}{R_\\odot}\n\\newcommand{\\dV}{\\mathrm{d}V}\n%\\newcommand\\av[1]{\\overline{<#1>}}\n%\\newcommand\\av[1]{<\\overline{#1}>}\n\n\n%\\newcommand\\av[1]{\\overline{\\langle{#1}\\rangle}}\n\\def\\av#1{\\overline{#1}}\n%\\newcommand\\fav[1]{\\widetilde{\\langle #1 \\rangle}}\n\\def\\fav#1{\\widetilde{#1}}\n\\newcommand\\br[1]{\\langle #1\\rangle}\n\\newcommand\\hpartial[1]{\\hat{\\partial} #1}\n\n\n\n\n\n%----------  Own Macros  --------------------------------------\n\\def\\etal{{\\it et al. }}\n\\def\\ie{{\\it i.e. }}\n\\def\\eg{{\\it e.g. }}\n\\def\\ms{\\, {M_{\\odot}}}\n\n\\def\\la{\\hbox{\\raise.5ex\\hbox{$<$} \n    \\kern-1.1em\\lower.5ex\\hbox{$\\sim$}}} \n\\def\\ga{\\hbox{\\raise.5ex\\hbox{$>$} \n    \\kern-1.1em\\lower.5ex\\hbox{$\\sim$}}} \n\\def\\msun{$M_\\odot$} \n\n\\newcommand{\\SubItem}[1]{\n    {\\setlength\\itemindent{15pt} \\item[-] #1}\n}\n\n\n\n\\newcommand{\\mean}[1]{\\ensuremath{\\overline{#1}}}\n\\newcommand{\\dgr}{\\mbox{$^\\circ$}}           % degrees \n\\newcommand{\\Msun}{\\mbox{M$_\\odot$\\,}}         % M_sun \n\\newcommand{\\Lsun}{\\mbox{$L_\\odot$}}         % L_sun \n\\newcommand{\\dTdp}{\\mbox{$\\nabla$}}          % Temp.grad. \n\\newcommand{\\dTdpad}{\\mbox{$\\dTdp_{ad}$}}    % ad. Temp.grad. \n\\newcommand{\\Tmax}{\\mbox{$T_{max}$}}         % T_max \n\\newcommand{\\Tmaxq}{\\mbox{$\\overline T_{max}$}} % T_max quer \n\\newcommand{\\RTmax}{\\mbox{$R_{max}$}}        % RT_max \n\\newcommand{\\sTmax}{\\mbox{$\\sigma_T$}}       % sigma T_max \n\\newcommand{\\DTmax}{\\mbox{$\\Delta_T$}}       % Delta T_max \n\\newcommand{\\vexp}{\\mbox{$v_{exp}^{(a)}$}}   % vexp \n\\newcommand{\\vprop}{\\mbox{$v_{prop}^{(i)}$}} % vprop \n\\newcommand{\\Drinv}{\\mbox{$d_{inv}$}}        % Drinv \n\\newcommand{\\DRinv}{\\mbox{$\\Delta R_{inv}$}} % DRinv \n\\newcommand{\\aP}{${}^\\star$}                 % prime \n\\newcommand{\\ad}{\\mbox{d}}                   % d \n\\newcommand{\\gsim}{\\gtrsim}                  % greater sim \n\\newcommand{\\cm}{\\mbox{\\ cm}}                % units \n\\newcommand{\\g}{\\mbox{\\ g}}                  % units \n\\newcommand{\\s}{\\mbox{\\ s}}                  % units \n\\newcommand{\\K}{\\mbox{\\ K}}                  % units \n\\newcommand{\\erg}{\\mbox{\\ erg }}              % units \n\\newcommand{\\cms}{\\mbox{\\ cm s${}^{-1}$}}    % units \n\\newcommand{\\cmss}{\\mbox{\\ cm s${}^{-2}$}}    % units \n\\newcommand{\\Ks}{\\mbox{\\ K s${}^{-1}$}}    % un\n\\newcommand{\\Kcm}{\\mbox{\\ K cm${}^{-1}$}}    % un\n\\newcommand{\\mes}{\\mbox{\\ m s${}^{-1}$}}    % units \n\\newcommand{\\ergK}{\\mbox{\\ erg K${}^{-1}$}}    % units \n\\newcommand{\\gcm}{\\mbox{\\ g cm${}^{-3}$}}    % units \n\\newcommand{\\gcms}{\\mbox{$\\g\\cm^{-1}\\s^{-1}$}}    % units \n\\newcommand{\\ergcms}{\\mbox{$\\erg\\cm^{-3}\\s^{-1}$}}  % units \n\\newcommand{\\erggs}{\\mbox{$\\erg\\g^{-1}\\s^{-1}$}}  % units \n\\newcommand{\\ergs}{\\mbox{$\\erg\\s^{-1}$}}  % units\n\\newcommand{\\ergcmsK}{\\mbox{$\\erg\\K^{-1}\\cm^{-1}\\s^{-1}$}}   % units \n\\newcommand{\\dyncm}{\\mbox{\\ dyn$\\cm^{-2}$}}  % units \n\\newcommand{\\radcm}{\\mbox{\\ rad$^2 \\cm^{-2}$\\,}}  % units \n\\newcommand{\\radss}{\\mbox{\\ rad$^2 \\s^{-2}$\\,}}  % units \n\\newcommand{\\vrad}{\\mbox{v$_{r}$}} \n\\newcommand{\\sv}{\\langle\\sigma v\\rangle}\n\\newcommand{\\cer}{\\color{red}}\n\\def\\eSGS{\\eta_{SGS}} \n\n \n%  input: Math. f\"ur Hydroformeln \n\\newcommand{\\dz}{\\partial_t} \n%\\newcommand{\\dr}{\\partial_r} \n%\\newcommand{\\dt}{\\partial_\\theta} \n\\newcommand{\\df}{\\partial_\\phi} % \\dp macht in LaTeX Schwierigkeiten \n\\newcommand{\\ddz}{\\frac{\\partial}{\\dz}} \n\\newcommand{\\ddr}{\\frac{\\partial}{\\dr}} \n\\newcommand{\\ddt}{\\frac{\\partial}{\\dt}} \n\\newcommand{\\ddf}{\\frac{\\partial}{\\df}} \n%\\newcommand{\\vr}{v_r} \n\\newcommand{\\vt}{v_\\theta} \n\\newcommand{\\vp}{v_\\phi} \n\\newcommand{\\st}{{\\,\\sin\\!\\theta}} \n\\newcommand{\\ct}{{\\,\\cos\\!\\theta}} \n\\newcommand{\\stq}{{\\,\\sin^2\\!\\theta}} \n\\newcommand{\\rez}[1]{\\frac{1}{#1}} \n\\newcommand{\\rezr}{\\rez{r}} \n\\newcommand{\\rezrs}{\\rez{r\\st}} \n\\newcommand\\bba{\\,\\,\\Bigl[\\,\\,} \n\\newcommand\\bbz{\\,\\,\\Bigr]\\,\\,} \n\\newcommand{\\mbf}[1]{\\mbox{\\boldmath$#1$}} % bold in mmode \n\n\\DeclareMathAlphabet{\\mathpzc}{OT1}{pzc}{m}{it}\n\n\\def\\todo#1{{\\color{red}[#1]}}\n\n\\usepackage{titling}\n\\newcommand{\\subtitle}[1]{%\n  \\posttitle{%\n    \\par\\end{center}\n    \\begin{center}\\large#1\\end{center}\n    \\vskip0.5em}%\n}\n\n%\\title{... title ...}\n\\title{Towards Complex Understanding of Turbulent Convection in Stellar Interiors Using ransX Analysis Framework}\n\\subtitle{Proposal For Post-Doctoctoral Research Position}\n\n\\author{Dr. Miroslav Moc\\'ak}\n\n\\begin{document}\n\n\\maketitle\n\\bibliographystyle{plainnat}\n\n\\section{Introduction}\n\nContemporary ground- and space-based telescopes provide us precise stellar data leading to challenging questions and forcing us to reconsider our basic assumptions regarding turbulent convection and mixing in stars. Properties of supernova explosions studied by HST or Keck can not be linked to their progenitors conclusively \\citep{Smartt2009}. Such progenitors are known to have a structure interleaved by turbulent convection shells \\citep{HirschiMeynet2004}. VLT is observing massive stars with unexplained chemical peculiarities, where rotational mixing was considered to be enough to explain observations \\citep{Evans2008}. Kepler spacecraft finds unexplained pulsations of $\\delta$ Scuti and $\\gamma$ Doradus stars \\citep{UytterhoevenArxiv2011}, which depend heavily on properties of sub-surface stellar convection \\citep{GuzikKaye2000}. Explanation of observed element abundances in AGB stars requires physically motivated but still inconclusive tuning for mixing between turbulent envelope convection and underlying hydrogen-free core \\citep{Herwig2005}.\n\nTurbulence is during stellar evolution one of the most fundamental processes and before taking into account binarity, magnetism or rotation of a star to explain observations, we should understand stellar turbulence well first. It is arguably the greatest weakness in the modern theory of stellar evolution, which is mostly derived from one-dimensional calculations approximating dynamic turbulent processes by simplified theories \\citep{KipWeigert1990,CoxGiuli2008}. In reality, turbulent flows are multidimensional and driven by non-linear terms of the hydrodynamic Navier-Stokes equations. \n\n\\section{Aims}\n\nI will analyze three-dimensional (3D) hydrodynamic simulations of stellar convection within the context of Reynolds-Averaged Navier Stokes (RANS) approach pursued by \\citet{Besnard1992,Livescu2009,Schwarzkopf2011}. It is a unique way of learning about turbulence based on budget analysis of hydrodynamic equations averaged in space and time, by which complexity of every term is reduced to a one-dimensional mean field.\n\nUsing this methodology, we derived RANS evolution equations for transport/flux/variance of mass, momenta, kinetic/internal/total energy, temperature, enthalpy, pressure and composition densities (no magnetic fields, no rotation) \\citep{Mocak2014} and implemented them to analysis framework, that we call rans(eXtreme) or ransX\\footnote{ransX is free for download and test on \\href{https://github.com/mmicromegas/ransX}{https://github.com/mmicromegas/ransX}} for short. It should be noted here, that it is only one of many possible sets of equations relevant to closure problems in turbulence and there are many other formulations, which then need to approximate different terms \\citep{Canuto1992,Canuto1993,CanutoHoward2001,Hanjalic2002,Alfonsi2009,Garaud2010,Canuto2011a,BiferaleMantovani2011}. \n\nRANS approach introduces into the averaged equations many correlations of various thermodynamic fluctuations which are essentially new unknown variables. Hence, to solve them, we need either to design appropriate closures or derive and close evolution equations for them. Either of the tasks is difficult, because stellar turbulence is anisotropic, compressible and embedded in highly stratified environment where external forces like gravity and mean background flow play an important role. But we hope that this approach could in the future allow us to study stellar evolution using solution of the mean fields hydrodynamic equations, move away from canonical form of stellar structure equations and most importantly allow for a comprehensive synergy between engineering turbulence modeling and stellar astrophysics. \n\nMy aims encompass the following targets (their content partially overlap with each other and the estimated time of completion is stated in brackets):\n\n\\begin{itemize}  \n\\item publish our RANS mean-field equations implemented within ransX framework \\citep{Mocak2014}\\footnote{More up-to-date equation content of the ransX framework can be found here \\href{https://github.com/mmicromegas/ransX/blob/master/DOCS/ransXtheoryGuide.pdf}{https://github.com/mmicromegas/ransX/blob/master/DOCS/ransXtheoryGuide.pdf}} in high-impact referred journal and validate them with new high-resolution 3D hydrodynamic simulations (2+ year)\n\\item help to implement the ransX framework to all hydrodynamic codes capable of simulating stellar core and envelope convection (e.g. MUSIC \\citep{VialletBaraffe2011}, PROMETHEUS \\citep{Fryxell1991,Mueller1991})  or stellar atmospheres in 3D and make it an analysis standard (3+ years)\n\\end{itemize}\n\n%The new hydrodynamic stellar structure equations for stellar turbulence are listed below as equations (1),(2),(3),(4),(5),(6). They appear to work well (Fig.\\ref{hsse:eq_simp}) but the first four equations still lack a theory that explains them and the last equation (5) requires a proper model for transport of composition density ($\\nabla_r f_\\alpha$) commonly treated in stars as difussion.\n\n%\\begin{align}\n%\\partial_r \\eht{m} = & \\ -\\eht{\\rho} \\ \\eht{m} \\ \\eht{g}_r / \\Gamma_1 \\eht{P} + 4 \\pi r^2 \\eht{\\rho} &  \\\\\n%\\partial_r \\eht{P} = & \\ -\\eht{\\rho} \\ \\eht{g}_r \\\\\n%\\partial_r \\fht{L} = & \\ -4 \\pi r^2 \\eht{\\rho} \\ \\eht{g}_r / \\Gamma_1 + \\widetilde{\\epsilon}_{t} \\partial_r 4 \\pi r^2 \\eht{\\rho} \\fht{u}_r  \\\\\n%\\partial_r \\eht{T} = & -(\\Gamma_3 -1) \\ \\eht{\\rho} \\ \\eht{T} \\ \\eht{g}_r / \\Gamma_1 \\eht{P} \\\\\n%\\partial_t \\fht{X}_i = & \\ \\fht{\\dot{X}}_i^{nuc} - (1/\\eht{\\rho})\\nabla_r f_i - \\fht{u}_r \\partial_r \\fht{X}_i \\\\\n%\\fht{u}_r = & \\ \\dot{\\overline{M}} / 4 \\pi r^2 \\overline{\\rho}\n%\\end{align}\n\n\n%\\begin{figure}[!h]\n%\\centerline{\n%  \\includegraphics[width=6.3cm]{oblrez_hsse_continuity_eq_alternative_simplified.eps}\n%  \\includegraphics[width=6.3cm]{oblrez_hsse_momentum_x_eq_alternative_simplified.eps}}\n\n%\\centerline{\n%  \\includegraphics[width=6.3cm]{oblrez_hsse_temperature_eq_alternative_simplified.eps}\n%  \\includegraphics[width=6.3cm]{oblrez_hsse_luminosity_eq_alternative_simplified.eps}}\n\n%\\centerline{\n%  \\includegraphics[width=6.3cm]{oblrez_hsse_mean_Xtransport_ne20.eps}}\n  \n%\\caption{Hydrodynamic stellar structure equations without MLT validated by 3D low-resolution oxygen burning convective shell simulation. Initial model is described more in detail in \\citet{Mocak2018}.}\n%\\label{hsse:eq_simp}  \n%\\end{figure}\n\nPartial results from our mean-field RANS analysis related mostly to turbulent kinetic energy and transport of some chemical elements based on oxygen burning shell in massive stars have been already published e.g. \\citet{MeakinArnett2007,ArnettMeakin2009,Meakin2010,VialletMeakin2013,Mocak2018}.\n\nIn order to cover wider range of conditions present in stars like Schwarzschild and Ledoux stable/unstable regions, electron degeneracy and multiplicity of convection zones, I also plan to extend our library of ransX mean fields calculated during 3D high-resolution hydrodynamic simulations of: \n\n\\begin{itemize}\n\\item single convection zone during core helium flash in low-mass stars with Ledoux unstable region at its bottom \\citep{Mocak2008,Mocak2009,Mocak2011} (1+ year)\n\\item dual convection zone during core helium flash in metallicity free stars \\citep{Mocak2010} (1+ year)\n\\item single convection zone resulting from core carbon flash in intermediate stars with Ledoux unstable region at its bottom \\citep{Mocak2011} (1+ years)\n\\item O-Ne-C burning stellar interior in massive pre-supernova progenitor with multiple interacting convection zones \\citep{Meakin2006} (3+ years)\n%\\item thermal pulse (model from Marcello)  \n\\end{itemize} \n\nThe setups are already prepared in our MPI parallelized multi-species compressible fluid dynamics code PROMPI \\citep{MeakinArnett2007}. Anticipated problems encompass computational time required to perform high-resolution 3D simulations, that may require 100k CPU hours for a single convective turnover timescale. In order to get statistically robust mean-fields from our framework, we need to simulate at least three such timescales per model after initial transient behaviour.\n\nBesides general understading of the time-dependency, non-local and compressibility effects of turbulent convection in stars, these simulations will also serve as test beds for turbulence models inspired by work of \\citet{rogers1989,lazeroms2013} and \\citet{biferale2011}.\n\n\\section{Summary}\n\n\\begin{itemize}\n\\item publish comprehensive description and validation of the ransX framework in referred journal\n\\item extend our library of 3D hydrodynamic simulations with core helium flash, core carbon flash, dual core flash and O-Ne-C burning shell simulations (setups already prepared in our hydrodynamic code PROMPI)\n\\item develop turbulence models suitable for 1D stellar evolution calculations inspired by engineering turbulence literature with focus on turbulent composition flux, which in reactive flow controls nuclear reaction rates\n\\item make ransX a standard analysis tool in as many hydrodynamic codes as possible\n\\end{itemize}\n  \n\\section{Intended Collaboration and Topic}\n\n\\begin{itemize}\n\\item Simon Campbell (Monash Centre for Astrophysics, Australia)\n\\begin{itemize}\n\\item 3D simulations of dual core flashes and nucleosynthesis in low-mass stars    \n\\end{itemize}  \n\\item Casey Meakin (Karagozian and Case, Inc., Glendale, California)\n\\begin{itemize}\n\\item turbulence modelling, ransX development, hydrodynamic stellar structure equations\n\\end{itemize}  \n\\item Dave Arnett (Steward Observatory, University of Arizona)\n\\begin{itemize}\n\\item turbulence modelling, hydrodynamic stellar structure equations\n\\end{itemize}   \n\\item Cyril Georgy (Geneva Observatory, University of Geneva, Switzerland)\n\\begin{itemize}\n\\item ransX development, hydrodynamic stellar structure equations\n\\end{itemize}    \n\\item Ewald Mueller (Max-Planck-Institut f\\\"ur Astrophysik, Germany)\n\\begin{itemize}\n\\item search for origin of gravitational wave signals during 3D hydrodynamic simulations of core-collapse supernovas using ransX framework \n\\end{itemize} \n\\end{itemize}\n  \n%\\section{Definitions}\n\n%\\begin{align}                                                      \n%  & \\rho \\ \\ \\mbox{density}                                           & & g_r  \\ \\ \\mbox{radial gravitational acceleration} \\nonumber \\\\\n%  & m = \\rho V = \\rho \\frac{4}{3} \\pi r^3\\ \\ \\mbox{mass}              & & M = \\int \\rho(r) dV \\ \\ \\mbox{integrated mass} \\nonumber \\\\  \n%& T \\ \\ \\mbox{temperature}                                          & & X_i \\ \\ \\mbox{mass fraction)} \\nonumber \\\\\n%& P \\ \\ \\mbox{pressure}                                             & & \\epsilon_t \\ \\ \\ \\mbox{specific total energy} \\nonumber \\\\ \n%& u_r, u_\\theta, u_\\phi \\ \\ \\mbox{velocity components}                 & & f_i = \\eht{\\rho}\\fht{X''_i u''_i} \\ \\ \\mbox{composition flux}  \\nonumber \\\\\n%& {\\bf u} = u (u_r, u_\\theta, u_\\phi) \\ \\ \\mbox{velocity}               & &  d = \\nabla \\cdot {\\bf u} \\ \\ \\mbox{dilatation}    \\nonumber \\\\              \n%& \\Gamma_1 = (d \\ ln \\ P/ d \\ ln \\ \\rho)|_s                     & & \\Gamma_2 / (\\Gamma_2 -1) =  (d \\ ln \\ P/ d \\ ln \\ T)|_s \\nonumber \\\\ \n%& \\Gamma_3 -1 =  (d \\ ln \\ T/ d \\ ln \\ \\rho)|_s                             & &  \\nonumber \n%\\end{align}\n\n%add here also horizontal and statistical operator definitions, definition of X'' and u''r and the operators\n\n\n\\bibliography{referenc}\n\n\\end{document}\n\n\n", "meta": {"hexsha": "913a66c5baf1092dc7fd714f1cdbc61f04e59457", "size": 16638, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "DOCS/RANDOM/TEX/ransXproposal2019.tex", "max_stars_repo_name": "mmicromegas/ransX", "max_stars_repo_head_hexsha": "2faaa786e00cfd14dce0e18f0793cd0252428d2a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-04-22T11:43:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-16T00:28:15.000Z", "max_issues_repo_path": "DOCS/RANDOM/TEX/ransXproposal2019.tex", "max_issues_repo_name": "mmicromegas/ransX", "max_issues_repo_head_hexsha": "2faaa786e00cfd14dce0e18f0793cd0252428d2a", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 34, "max_issues_repo_issues_event_min_datetime": "2019-07-01T09:11:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T13:35:43.000Z", "max_forks_repo_path": "DOCS/RANDOM/TEX/ransXproposal2019.tex", "max_forks_repo_name": "mmicromegas/ransX", "max_forks_repo_head_hexsha": "2faaa786e00cfd14dce0e18f0793cd0252428d2a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-16T00:28:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-16T00:28:17.000Z", "avg_line_length": 58.3789473684, "max_line_length": 1063, "alphanum_fraction": 0.7084986176, "num_tokens": 4955, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3309510876326517}}
{"text": "% Document type and various settings\n\\documentclass[utf8]{frontiersSCNS}\n\n% Link colors\n\\RequirePackage[pdftex, bookmarks, colorlinks, breaklinks]{hyperref}\n\\definecolor{darkblue}{rgb}{0,0,.4}\n\\hypersetup{\n    linkcolor=darkblue,\n    citecolor=darkblue,\n    filecolor=black,\n    urlcolor=black\n}\n\n\\usepackage{url, lineno, microtype, subcaption, siunitx}\n\\usepackage[onehalfspacing]{setspace}\n\\def\\keyFont{\\fontsize{8}{11}\\helveticabold}\n\\linenumbers\n\n% Setup rendering of SI units\n\\sisetup{math-rm=\\rmfont, detect-all}\n\n% Citation commands\n\\renewcommand{\\cite}[1]{~\\citep{#1}}\n\\newcommand{\\textcite}[1]{\\citet{#1}}\n\n% Code listings\n\\usepackage{listings}\n\\usepackage{inconsolata}\n\\definecolor{codebackground}{rgb}{0.9,0.9,0.9}\n\\definecolor{comment}{rgb}{0.25,0.25,0.25}\n\\lstset{\n    basicstyle=\\ttfamily\\scriptsize,\n    keepspaces=true,\n    columns=fullflexible,\n    upquote=true,\n    language=Python,\n    belowskip=0pt,\n    commentstyle=\\color{comment}\n}\n\\newcommand{\\code}[1]{\\lstinline{#1}}\n\n% Some convenience commands when writing equations with lots of matrices\n\\newcommand{\\bm}[1]{\\mathbf{#1}}\n\\newcommand{\\mat}[1]{\\bm{#1}}\n\\renewcommand{\\vec}[1]{\\bm{#1}}\n\\newcommand{\\tmat}[1]{$\\bm{#1}$}\n\\newcommand{\\tvec}[1]{$\\bm{#1}$}\n\\newcommand{\\emat}[1]{\\hat{\\bm{#1}}}\n\\newcommand{\\evec}[1]{\\hat{\\bm{#1}}}\n\\newcommand{\\temat}[1]{$\\hat{\\bm{#1}}$}\n\\newcommand{\\tevec}[1]{{$\\hat{\\bm{#1}}$}}\n\\newcommand{\\trans}{^\\intercal}\n\\newcommand{\\ctrans}{^{\\intercal*}}\n\\newcommand{\\explainmat}[3]{$\\mat{#1} \\in \\mathbb{R}^{#2 \\times #3}$}\n\\newcommand{\\explaincmat}[3]{$\\mat{#1} \\in \\mathbb{C}^{#2 \\times #3}$}\n\\newcommand{\\explainvec}[2]{$\\vec{#1} \\in \\mathbb{R}^{#2}$}\n\\newcommand{\\explaincvec}[2]{$\\vec{#1} \\in \\mathbb{C}^{#2}$}\n\n% Author list\n\\def\\firstAuthorLast{van Vliet {et~al.}} %use et al only if is more than 1 author\n\\def\\Authors{Marijn van Vliet\\,$^{1,*}$, Mia Liljeström\\,$^{1,2}$, Susanna Aro\\,$^{1}$, Riitta Salmelin\\,$^{1}$ and Jan Kujala\\,$^{1}$}\n\\def\\Address{$^{1}$ Department of Neuroscience and Biomedical Engineering, Aalto University, Espoo, Finland\\\\\n             $^{2}$ NatMEG, Department of Clinical Neuroscience, Karolinska Institutet, Stockholm, Sweden}\n\\def\\corrAuthor{Marijn van Vliet}\n\\def\\corrEmail{marijn.vanvliet@aalto.fi}\n\\def\\extra{marijn.vanvliet@aalto.fi}\n\n% Begin actual document\n\\begin{document}\n\\onecolumn\n\\firstpage{1}\n\n\\title[Connectivity and power analysis using DICS]{Analysis of functional connectivity and oscillatory power using DICS: from raw MEG data to group-level statistics in Python} \n\n\\author[\\firstAuthorLast]{\\Authors}\n\\address{}\n\\correspondance{}\n\\extraAuth{}\n\n\\maketitle\n\n% The actual manuscript goes here\n\\begin{abstract}\n\n% Maximum number of words: 350\n% Current number of words: 277\n\nCommunication between brain regions is thought to be facilitated by the synchronization of oscillatory activity.\nHence, large-scale functional networks within the brain may be estimated by measuring synchronicity between regions. Neurophysiological recordings, such as magnetoencephalography (MEG) and electroencephalography (EEG), provide a direct measure of oscillatory neural activity with millisecond temporal resolution.\nIn this paper, we describe a full data analysis pipeline for functional connectivity analysis based on dynamic imaging of coherent sources (DICS) of MEG data.\nDICS is a beamforming technique in the frequency-domain that enables the study of the cortical sources of oscillatory activity and synchronization between brain regions.\nAll the analysis steps, starting from the raw MEG data up to publication-ready group-level statistics and visualization, are discussed in depth, including methodological considerations, rules of thumb and tradeoffs.\nWe start by computing cross-spectral density (CSD) matrices using a wavelet approach in several frequency bands (alpha, theta, beta, gamma).\nWe then provide a way to create comparable source spaces across subjects and discuss the cortical mapping of spectral power.\nFor connectivity analysis, we present a canonical computation of coherence that facilitates a stable estimation of all-to-all connectivity.\nFinally, we use group-level statistics to limit the network to cortical regions for which significant differences between experimental conditions are detected and produce vertex- and parcel-level visualizations of the different brain networks.\nCode examples using the MNE-Python package are provided at each step, guiding the reader through a complete analysis of the freely available openfMRI ds000117 ``familiar vs.\\ unfamiliar vs.\\ scrambled faces'' dataset.\nThe goal is to educate both novice and experienced data analysts with the ``tricks of the trade'' necessary to successfully perform this type of analysis on their own data.\n\n% We may include up to 8 keywords\n\\tiny\n\\keyFont{\\section{Keywords:} DICS, MEG, coherence, brain rhythms, workflow, tutorial}\n\n\\end{abstract}\n\n\n\\section{Introduction}\\label{introduction}\n\nIn this paper, we demonstrate the application of dynamic imaging of coherent sources (DICS), a spatial filtering technique for magneto/electro-encephalography (MEG/EEG) data originally proposed by \\textcite{Gross2001}.\nSpatial filters, or beamformers, are constructed to pass the activity originating at a specific location, while suppressing activity from other locations using a weighted sum of the sensor signals\\cite{VanVeen1997}.\nDICS is a linearly constrained minimum variance beamformer in the frequency domain, which can be used to calculate oscillatory power at any given location in the brain and coherence between any two given locations\\cite{Gross2001, Kujala2008}.\nThis enables us to create cortical ``power maps'' and to perform functional connectivity analysis.\n\nInteracting large-scale functional networks in the brain are thought to support cognition and behavior.\nDynamic changes in connectivity are of increasing interest, as recent results have shown that functional connectivity between brain regions changes in a time-resolved and task-dependent manner\\cite{Liljestrom2015a, Betti2013, Gonzalez-Castillo2017, Liljestrom2018} and hence provides information that is complementary to the analysis of evoked responses\\cite{Laaksonen2012b, Salmelin2006}.\nMagnetoencephalography (MEG) recordings provide a direct measure of neural activity with excellent time resolution.\nMEG enables non-invasive estimation of connectivity between brain regions with a cortex-wide spatial coverage that cannot be attained with, for example, intracranial recordings.\n\nThere are different ways to define and quantify functional connectivity\\cite{Schoffelen2009a}.\nIn general, two regions are assumed to interact when certain aspects of the recorded brain activity over these regions are consistent.\nIn this paper, we focus on coherence, which quantifies the cortico-cortical synchrony of oscillatory activity, as a connectivity measure\\cite{Gross2001}.\nOscillatory activity in neuronal populations is a principal feature of brain activation and synchronization, or coherence, of such oscillating activity across brain regions is thought to promote efficient communication within large-scale neural networks\\cite{Bressler2001, Fries2005}.\nCoherence is thus a neurophysiologically well motivated measure of functional connectivity.\nPrevious studies have suggested that oscillatory activity/interaction within specific frequency bands may have different functional roles\\cite{Buffalo2011, Donner2011, Hipp2012, Liljestrom2015a}.\nUsing coherence as a measure of connectivity enables a direct mapping of connectivity at different frequencies, without the need to estimate time series at the level of cortical sources\\cite{Kujala2008}.\n\nRecently, we developed a pipeline for estimating all-to-all functional connectivity\\cite{Liljestrom2015a, Saarinen2015} for MEG network analysis, which utilizes the DICS spatial filter combined with a wavelet approach to achieve a high temporal resolution\\cite{Laaksonen2012a}.\nWith this approach, we have demonstrated that a transient reorganization of the large-scale functional networks that support language takes place before onset of speech\\cite{Liljestrom2015a, Liljestrom2015b}.\n\nFor the current paper, we have made a new implementation of our pipeline and integrated it with the MNE-python package\\cite{mne}.\nWe will demonstrate it using the freely available MEG dataset collected by \\textcite{Wakeman2015}, for which we have chosen to compare changes in oscillatory activity and functional connectivity between processing faces and scrambled images, as described in \\autoref{dataset}.\nWe will go over all the steps of the analysis and provide examples of how to implement them using MNE-Python.\n\nThe preprocessing of the MEG data is briefly outlined in \\autoref{preprocessing}. \nIn the DICS beamformer, a cross-spectral density (CSD) matrix is used to represent the measured oscillatory activity and their dependencies.\nIn \\autoref{csd}, we describe estimation of the CSD matrices, the mathematical formulation, and its implementation using the python code.\nFor group-level comparisons it is important to obtain comparable source-points and connections across subjects.\nFor this purpose, we have chosen to create a surface-based cortical grid in a template brain and transform the source locations to each individual subject.\nIn \\autoref{forward}, we outline how this is implemented.\n\nWhile the current pipeline was primarily developed for the purpose of all-to-all connectivity analysis, it can also be used for estimation of oscillatory activity, (i.e., ``power mapping''), which we discuss in \\autoref{power}.\nIn \\autoref{connectivity}, we introduce a ``canonical'' computation of coherence between brain regions, which facilitates the stable estimation of all-to-all connectivity\\cite{Saarinen2015}.\nIn this approach, the source orientation configuration for each cortico-cortical connection is determined by identifying the orientation combination that maximizes coherence between the two sources.\n\nNeurophysiological recordings are inherently sensitive to spatial blurring of the signal due to field spread, thus complicating the estimation of functional connectivity between brain regions\\cite{Schoffelen2009a}.\nHence, we focus on connections that span long distances (\\SI{>4}{\\centi\\meter}).\nTo further suppress effects related to field spread, the current approach is based on identifying statistically significant differences in functional connectivity between power-matched experimental conditions, rather than absolute coherence values.\nThis analysis step is described in \\autoref{statistics}.\n\nImportantly, this approach identifies changes in connectivity between brain regions that can be linked to the specific task manipulation, rather than the entire underlying network.\nFor visualization of the identified networks, we use a combination of a cortical-level degree map which shows the total number of connections for each source point, and a circular connectogram that summarizes the number of connections between brain regions at a cortical parcellation level.\nThis is presented in \\autoref{visualization}.\n\nFinally, we discuss benefits and limitations of the present approach in \\autoref{discussion}, and present several methodological considerations related to functional connectivity analysis with MEG.\n\n\n\\subsection{Example dataset}\\label{dataset}\n% We should describe this data a little bit, so that the reader should not have to read Wakeman2015 in order to understand our paper.\nThroughout this paper, we will demonstrate the application of our pipeline to an example dataset. \nFor this purpose, we use the data collected by \\textcite{Wakeman2015}.\nThis subsection will provide a brief description of the characteristics of the data that are most salient to the present paper.\nFor further details on the dataset, see \\textcite{Wakeman2015}.\n\nThe dataset consists of simultaneous MEG and EEG recordings, collected from 19 participants who were viewing images of either faces or scrambled versions of the face stimuli.\nThe original study excluded data from 3 participants due to the presence of artifacts in the data\\cite{Wakeman2015}; we also excluded those data from our analysis.\nThe data was recorded by an Elekta Neuromag Vectorview 306 system that has 204 planar gradiometers.\nOnly the gradiometer MEG data was used in our example.\n\nThe stimuli consisted of 300 greyscale photographs, half from famous people (known to the participants) and half from people unknown to participants, and 150 images of scrambled versions of either famous or unknown faces.\nEach stimulus was presented twice, for a total of $2 \\times (300 + 150) = 900$ trials, with the second repetition occurring either immediately after the first, or with an interval of 5--15 intervening stimuli.\nIn our example analysis, we focus on the distinction between faces versus scrambled images, regardless of whether the faces were known or unknown to the participant.\n\nEach trial began with the presentation of a fixation cross for a random duration of \\SIrange{400}{600}{\\milli\\second}, followed by presentation of the stimulus for a random duration of \\SIrange{800}{1000}{\\milli\\second}, after which a white circle was presented for \\SI{1700}{\\milli\\second}.\nThe task for the participants was to press one of two buttons depending on whether they judged the image to be ``more'' or ``less'' symmetric than average.\n\n% \\subsection{Mathematical notation}\\label{notation}\n% \n% At some points, our analysis pipeline deviates from \\textcite{Gross2001} to address certain practical issues.\n% In these cases, we report the mathematics that underlie the computation that the code examples perform.\n% The following conventions are used for denoting matrices, vectors and scalars:\n% \n% \\setlength\\tabcolsep{2.5pt}\n% \\begin{tabular}{r p{15.5cm}}\n% Matrices & are denoted as bold, upper case letters, typeset in roman: $\\mat{M}$.\\\\\n% Vectors & are denoted as bold, lower case letters, typeset in roman: $\\mat{v}$. In case the vector is a row of a matrix, we denote this as $\\vec{M}(i)$, meaning row $i$ of matrix $\\mat{M}$. All vectors in this paper are row vectors.\\\\\n% Scalars & are denoted as lower case italic letters: $s$. In case the scalar is a single element of a matrix, we denote this as $M(i, j)$, meaning the element at row $i$ and column $j$ of matrix $\\mat{M}$. In case the scalar is a single element of a vector, we denote this as $v(i)$, meaning element $i$ of vector $\\vec{v}$.\n% \\end{tabular}\n% \n% Approximations of matrices, vectors and scalars are annotated with a hat: $\\widehat{\\mat{M}}$.\n\n\\subsection{Data and code availability}\\label{data}\n\nThe multi-subject, multi-modal human neuroimaging dataset\\cite{Wakeman2015} that we use in this study can be found at: \\url{https://openfmri.org/dataset/ds000117}.\n\nThe code repository related to this project is at: \\url{https://github.com/wmvanvliet/conpy}.\nThis currently includes the ConPy project code (in the \\code{conpy/} folder), the analysis scripts to process the \\textcite{Wakeman2015} dataset (in the \\code{scripts/} folder), the scripts to produce the figures in this paper (also in the \\code{scripts/} folder), the code examples included in this paper (in the \\code{paper/code_snippets/} folder), and the \\LaTeX\\ code to produce the final pdf (in the \\code{paper/} folder).\nFurther instructions on how to run the pipeline are provided in the \\code{README.md} file.\n\n\n\\section{Preprocessing}\\label{preprocessing}\n\nDICS based power analysis and functional connectivity can be investigated for multiple kinds of experimental designs, ranging from ones consisting of isolated events\\cite{Laaksonen2008} to ones with continuous naturalistic stimulation\\cite{Saarinen2015, Alexandrou2017}.\nThe present analysis pipeline focuses on data representing neural processes related to external stimuli or events whose timing can be determined exactly. \nFor this type of analysis, an important preprocessing step is to cut up the continuous MEG recording into fragments of data surrounding the onset of such events.\nThese fragments are referred to as ``epochs''.\n\nThe process of going from raw data to epochs is not specific to DICS analysis, but are the first steps shared by many analysis pipelines.\nA sister paper, \\textcite{Jas2017}, discusses the many parameters and trade-offs involved in these important preprocessing steps and provides code examples, using the same dataset as in this paper.\nTherefore, to keep the topic of the current paper focused on estimating cortical power and connectivity analysis, and to avoid duplication of effort, we refer the reader to \\textcite{Jas2017} for a detailed description of the preprocessing steps, which we will only summarize below.\n\nConstruction of the source space and forward model (see \\autoref{forward}) depends on a 3D model of the subject's head that is created from a structural magnetic resonance imaging (MRI) scan, which is done in our analysis pipeline using the FreeSurfer\\cite{freesurfer} package.\n\nThe MEG data is processed with the \\code{maxfilter} program, developed by Electa and also implemented in MNE-Python, to eliminate noise sources that originate outside the MEG helmet.\nFurthermore, the program uses the head coils that are attached to the participant's head to track the head position during the recording, and projects the data such that the influence of head movements is minimized.\n\nTo remove the signals produced by the head coils, the MEG signal must be low-pass filtered to at least below \\SI{150}{\\hertz}.\nAdditionally, the signal should be high-pass filtered above at least \\SI{1}{\\hertz} when performing independent component analysis (ICA).\n\nTo reduce the contamination of the MEG signal by artifacts caused by eye blinks and heart beats, ICA components are estimated on the continuous data.\nHowever, no actual data decomposition is performed yet.\nNext, an automated detection algorithm is applied to detect the onset of blinks and heart beats, and segments of data surrounding each onset are created and averaged, yielding an\n``average blink'' segment and average ``heart beat'' segment.\nThe average blink and average heart beat segments are then decomposed along the ICA components and the correlation between the electro-oculography (EOG) and electro-cardiography (ECG) sensors and each signal component is computed.\nThe ICA components for which the corresponding signal components correlate strongly with the EOG or ECG signal are flagged as ``bad'' and will be removed in the next step.\n\nThe continuous data is cut up into segments in a short time window relative to the onset of the presentation of each stimulus.\nThese segments are referred to as ``epochs''.\nThe data of each epoch is decomposed along the ICA components that were computed in the previous step, the components flagged as ``bad'' are dropped, and the signal is recomposed.\nFinally, epochs where the signal amplitude of one or more channels exceeds a predefined threshold, signifying the presence of an artifact (for example such as those caused by movements and biting) that contaminates the data segment beyond repair, are removed.\n\n\n\\subsection{Application to the example dataset}\n\nFor our analysis of the \\textcite{Wakeman2015} dataset, we mostly follow the preprocessing pipeline of \\textcite{Jas2017}, which implementation can be found at \\url{https://github.com/mne-tools/mne-biomag-group-demo}.\nHowever, there are some key differences between our pipeline and the one used by \\textcite{Jas2017}:\n\\begin{enumerate}\n    \\item Since our pipeline operates on MEG data, we restrict our preprocessing pipeline to only use the gradiometer and magnetometer channels, whereas \\textcite{Jas2017} also include EEG data.\n    \\item Since we are analyzing oscillatory activity rather than evoked potentials, we high-pass filter the data above \\SI{1}{\\hertz}, whereas \\textcite{Jas2017} perform no high-pass filtering other than the one performed by the recording hardware.\n    \\item We do not make use of the \\code{autoreject} package for dynamically determining thresholds when rejecting epochs which have a too large signal amplitude, but rather use a fixed, more lenient, threshold. This is because since our analysis of oscillatory activity is less sensitive to isolated signal spikes than the analysis of evoked potentials performed in \\textcite{Jas2017}.\n\\end{enumerate}\n\nThe preprocessing pipeline is implemented in the following scripts:\n\n\\begin{tabular}{lp{13cm}}\n    Script & Function \\\\\n    \\hline\n    \\verb#00_fetch_data.py# & downloads the openfmri ds117 dataset and extracts it \\\\\n    \\verb#01_anatomy.py# & runs the FreeSurfer \\verb#recon-all# program on the anatomical MRI data and uses the FLASH images to create surface meshes \\\\\n    \\verb#02_filter.py# & performs band-pass filtering between \\SIrange{1}{40}{\\hertz} on the MEG data \\\\\n    \\verb#03_ica.py# & uses ICA to decompose the MEG signal into independent components. Finds at most two ICA components that correlate with heart beats ($\\rho >$ 0.05), at most two components that correlate with eye blinks ($\\rho >$ 0.1), and flags these components for removal. \\\\\n    \\verb#04_epochs.py# & cuts the continuous MEG data into epochs from \\SIrange{-0.2}{2.9}{\\second} relative to the onset of the stimuli. Removes ICA components that were flagged in the previous step. Removes epochs where the signal amplitude of one or more gradiometer channels exceed \\SI{3e-10}{\\tesla/\\centi\\meter} or one or more magnetometer channels exceed \\SI{4e-12}{\\tesla}.\n\\end{tabular}\n\nFrom this point on, the analysis pipeline becomes specific to DICS analysis and will be described in more detail.\n\n\n\\section{Estimating cross-spectral density (CSD) matrices}\\label{csd}\n\nEstimating the cortical origins of oscillatory activity (we refer to this as ``power mapping'') and estimating connectivity between cortical sources (we refer to this as ``connectivity analysis'') both start with the computation of one or more cross-spectral density (CSD) matrices.\nThe CSD is the covariance between the two signals, in our case the activity recorded at two sensors, in the frequency domain.\nA CSD matrix defines the CSD between all sensor-pairs and is similar in nature to a covariance matrix.\n\nCommonly, both the analysis of oscillatory power and connectivity are conducted in multiple frequency bands, time windows, and/or experimental conditions.\nFor each of these, a separate CSD matrix needs to be computed.\n\nBecause we wish to compute CSD matrices for specific frequency bands and time windows, we choose to transform the signal to the time-frequency domain using a wavelet transform.\nWe follow the method outlined in \\textcite{TallonBaudry1997}, which offers a better tradeoff between time and frequency resolution than a standard Fourier transform.\n\n\\subsection{Mathematical formulation}\n\nFor each frequency $f$ (in Hertz) we want to include in the analysis, we construct the corresponding Morlet wavelet $\\vec{m}(f)$, which has a Gaussian shape both in the temporal and frequency domain.\nThe standard deviation of this Gaussian shape in the time domain, $\\sigma_\\text{t}$, is an important parameter that determines the tradeoff between temporal and frequency resolution of the resulting time-frequency decomposition.\nA common tactic is to use a large $\\sigma_\\text{t}$ at low frequencies, increasing the frequency resolution at the cost of temporal resolution, and use increasingly smaller values at higher frequencies, trading frequency resolution for temporal resolution.\nA convenient way to achieve this is to define $n_\\text{o}$ as the number of oscillations the Morlet wavelet completes. Then,\n\\begin{align}\\label{eq:oscillations}\n    \\sigma_\\text{t} &= \\frac{n_\\text{o}}{2 \\pi f}.\n\\end{align}\nA Morlet wavelet of the desired length can then be constructed as follows:\n\\begin{align}\\label{eq:wavelet}\n    \\vec{t} &= [-5\\sigma_\\text{t}, -5\\sigma_\\text{t} + 1/f_\\text{s}, \\ldots, 5\\sigma_\\text{t}], \\\\\n    \\vec{m}(f) &= (\\sigma_\\text{t} \\sqrt{\\pi})^{-1/2} \\exp(-\\frac{\\vec{t}^2}{2 \\sigma_\\text{t}^2}) \\exp(2 i \\pi f \\vec{t}),\n\\end{align}\nwhere $\\vec{t}$ are the time points at which the Morlet function is evaluated and $f_\\text{s}$ is the sampling frequency of the MEG signal.\nThe transformation to the time-frequency domain is performed by convolution of the Morlet wavelet for each frequency with the MEG signal:\n\\begin{align}\\label{eq:energy}\n    \\vec{e}_1(f) &= \\vec{m}(f) * \\vec{x}_1, \\\\\n    \\vec{e}_2(f) &= \\vec{m}(f) * \\vec{x}_2,\n\\end{align}\nwhere ($*$) denotes linear convolution.\nThe resulting vectors $\\vec{e}_1(f)$ and $\\vec{e}_2(f)$ contain the complex time courses of the signals $\\vec{x}_1$ and $\\vec{x}_2$ filtered at frequency $f$.\nFinally, we compute the CSD between the signals by taking the dot product of $\\vec{e}_1(f)$ and the complex conjugate of $\\vec{e}_2(f)$ for all the frequencies and time points we wish to include in the analysis and by averaging the result:\n\\begin{equation}\\label{eq:csd}\n    c(\\vec{x}_1, \\vec{x}_2) = \\frac{1}{N_\\text{f}} \\frac{1}{N_\\text{t}} \\sum_{f} \\sum_{t}{e_1(f)(t) \\cdot {e_2(f)(t)}^*},\n\\end{equation}\nwhere $N_\\text{f}$ is the number of frequencies, $N_\\text{t}$ the number of time points, ($\\cdot$) denotes the dot product between two vectors, the superscript ($^*$) the complex conjugate operation and $e(f)(t)$ the signal at frequency $f$ and time $t$. \nSince the frequency domain is described using complex numbers, $c$ will be a complex number as well when the computations are done for distinct signals $\\vec{x}_1$ and $\\vec{x}_2$.\n\nTo compute the full CSD matrix, \\autoref{eq:csd} is repeated for each pair of channels.\nEach element $C(i, j)$ of the resulting CSD matrix \\explaincmat{C}{N_\\text{s}}{N_\\text{s}} holds the CSD between sensors $i$ and $j$.\nThe matrix is Hermitian, so $C(i, j)$ and $C(j, i)$ are complex conjugates of each other, and the diagonal elements hold the mean power-spectral density (PSD) for each sensor.\nThe CSD matrices are computed for each epoch separately and then averaged to produce a single CSD matrix per experimental condition.\n\n\\subsection{Code example}\n\nThe following code example will compute the CSD matrix over the time range from \\SIrange{0}{0.4}{\\second} relative to the stimulus onset, for two frequency ranges:\n\\lstinputlisting{code_snippets/csd.py}\n\nAs discrete wavelet transforms are used in the CSD computation, the frequencies are specified as a list, rather than a range.\nThese frequencies should evenly span the desired frequency range.\nTheir suitable spacing depends on the frequency resolution of the wavelets.\n\nThe \\code{n_cycles} parameters of the \\code{csd_epochs} function controls $n_\\text{o}$, thus controlling the tradeoff between frequency and time resolution of the wavelet transform.\nIt can either be set to a fixed value (as in the example), which means the wavelets get shorter as the frequency increases (increasing the temporal resolution and decreasing the frequency resolution).\nAlternatively, one may specify a list of values, one for each frequency, to have precise control over the time/frequency resolution tradeoff.\n\nThe \\code{decim} parameter of the \\code{csd_epochs} function controls the spacing of the time points $t$ that are used in \\autoref{eq:csd}, enabling more efficient computation of the CSD matrix.\nThe time resolution of the signals following the wavelet transform (\\autoref{eq:energy}) is generally much lower than the sampling rate of the original signals.\nIn these cases we can safely pick every n\\textsuperscript{th} time point without losing information.\n\nThe wavelet convolution method assumes that the data across time has an approximate mean of zero. In our pipeline, we choose to remove the signal offset for each epoch. Another good option is to first apply a highpass filter to the data, in which case further detrending is not necessary.\n\n\\subsection{Application to the example dataset}\n\nFor our analysis of the \\textcite{Wakeman2015} dataset, we computed CSD matrices for the following frequency bands (following \\textcite{Liljestrom2015a}):\n\n\\begin{tabular}{ll}\n    Frequency range & Band name \\\\\n    \\toprule\n    \\SIrange{3}{7}{\\hertz} & theta \\\\\n    \\SIrange{7}{13}{\\hertz} & alpha \\\\\n    \\SIrange{13}{17}{\\hertz} & low beta \\\\\n    \\SIrange{17}{25}{\\hertz} & high beta 1 \\\\\n    \\SIrange{25}{31}{\\hertz} & high beta 2 \\\\\n    \\SIrange{31}{40}{\\hertz} & low gamma\n\\end{tabular}\n\nWe choose to use a fixed $n_\\text{o}=7$, and the width of our chosen frequency bands reflect the resulting time/frequency resolution tradeoff.\nThere is no golden standard for which frequency bands to use and you may have to adapt the frequency ranges to fit your dataset and research question.\nFor example, frequencies higher than \\SI{40}{\\hertz} may be of interest as well.\n\nThe CSD matrices were computed for both the time window from \\SIrange{0}{0.4}{\\second}, and during the ``baseline'' period from \\SIrange{-0.2}{0}{\\second}, relative to the onset of the stimulus.\nWe will later compare the cortical sources of oscillatory activity before and after the presentation of a stimulus.\nThis analysis step is implemented in script \\code{05_csd.py} and an example of the resulting CSD matrices is presented in \\autoref{fig:csd}.\n\n\\begin{figure}[b]\n\\centering\n\\includegraphics[width=12cm]{figures/csd.pdf}\n    \\caption{CSD matrices computed for different frequency bands. The CSD matrices were computed across all the epochs where a face stimulus was presented to subject 2, in the time window from \\SIrange{0}{0.4}{\\second} relative to the presentation of the stimulus. Each row and column corresponds to one of the 204 gradiometers. Note that each row has a separate color scale.}%\n\\label{fig:csd}\n\\end{figure}\n\n\n\\section{Source space and forward model}\\label{forward}\n\nThe DICS beamformer will, given a CSD matrix and forward modeling of neural currents, estimate the power of the oscillatory activity originating from one specific point on the cortex.\nDICS uses a spatial filter to determine the activity at the given point on the cortex while suppressing contributions from all other sources.\nBy creating a grid of regularly spaced points along the cortex and computing spatial filters for each point, a complete picture of brain-wide activity emerges.\nThis grid is referred to as the ``source space'' (\\autoref{fig:forward}, left).\nThe DICS power estimates are also used during connectivity analysis, where the source space is used for defining the start and end point of possible connections.\n\nTo create the source space, we first need a 3D-model of the subject's brain.\nHere, we obtain it by performing a structural MRI scan on the subject and processing the data with FreeSurfer\\cite{freesurfer}.\nThe details are explained in \\textcite{Jas2017} and the implementation can be found in the script \\code{01-run_anatomy.ipy} accompanying that paper.\nThe FreeSurfer analysis results in several 3D meshes, corresponding to different brain tissues, of which the white matter surface serves as the basis for our source space.\n\nFor group-level analysis, it is important that connections between the points within source spaces can be compared across subjects.\nThis is feasible if the same connections exist for each subject, which, in turn, means that the same source points must be defined for each subject.\nTo facilitate this, we first define the source space on the ``fsaverage'' brain: a template brain model, provided by FreeSurfer, constructed by averaging the MRI scans of 40 subjects\\cite{Fischl1999}.\nThe resulting source space is then morphed to each individual subject, transforming the source points to corresponding locations on the cortex\\cite{Fischl1999}.\nNote that the morphed source space will generally be only approximately evenly spaced.\nFor creating power maps, we advice to create evenly spaced source spaces for each individual subject and morph the estimated power map to the average brain, as explained in \\textcite{Jas2017}.\n\nIn our analysis pipeline, we compute all-to-all connectivity between the source points.\nTo keep the number of connections manageable, only a limited number of source points can be used.\nPartly, this is facilitated by placing the sources at slightly larger spatial intervals than is common in studies focusing on cortical activity.\nIn addition, we place sources only in areas that can be reliably measured using MEG, rather than in ``deep sources'' that do not generate signals that would be readily detectable with MEG sensors.\n\nWe start out with a regularly spaced grid of 5124 points covering the entire surface of the cortex, yielding an average distance of \\SI{~2.6}{\\milli\\meter} between neighbouring points.\nTo limit the number of source points, all points that are further than \\SI{7}{\\centi\\meter} from the nearest MEG sensor are discarded.\nFor this dataset, a cutoff distance of \\SI{7}{\\centi\\meter} provides a good tradeoff between the number of source points and coverage across the cortex, but this value may need to be adjusted for other datasets.\nClose visual inspection of the result is required, see \\autoref{fig:forward} (left).\nTo ensure that the same source points are defined for each subject, the distance from source points to the closest sensor is determined in one subject, and the resulting set of points is then used for all subjects.\nSince the distance from the source points to the sensors is dependent on the position of the subject's head in the MEG helmet, it is important to ensure that the initial distance computations are done for a subject whose head was in an approximately average position across subjects with respect to the helmet.\n\nThe resulting restricted source spaces are only used during connectivity analysis.\nFor computing power maps, the number of source points is less of an issue and therefore we always use the full source space.\n\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=0.5\\textwidth]{figures/forward1.png}%\n    \\includegraphics[width=0.5\\textwidth]{figures/forward2.png}%\n    \\caption{The source space and forward model used in connectivity analysis.\n    \\textbf{Left:} The white matter surface, as reconstructed by FreeSurfer.\n    The source space is defined as a grid of points along this surface, shown in yellow.\n    All points further than \\SI{7}{\\centi\\meter} from the closest MEG sensor (shown as blue squares in the background) have been discarded.\n    \\textbf{Right:} The forward model defines two dipoles at each source point.\n    The orientation of the dipoles is tangential to a sphere with its origin at the center of the brain.}\\label{fig:forward}\n\\end{figure}\n\nGiven the source space, we construct a forward model that models how the magnetic field, produced by a current at each source point, travels through the various tissues of the brain and head, resulting in activity recorded at the MEG sensors.\nFor this computation, we employ a boundary element method (BEM) model\\cite{Hamalainen1993} that uses the FreeSurfer meshes of the brain tissues, assuming homogeneous conductivity within each mesh.\nFor MEG datasets, we only include the inner skull meshes, resulting in a single-layer BEM model.\n% As electric currents are affected more by the various tissues in the head, we also include the outer skull and skin surfaces for EEG and combined MEG-EEG datasets, resulting in a three-layer BEM model.\n\nThe neural currents at the source points are modeled as equivalent current dipoles (ECDs) that represent the dominant component of the local current as a vector that has both a magnitude and a direction.\nThe forward model represents the ECD at each source point using three separate dipoles, arranged in three orthogonal orientations, representing the magnitude of the current in the x-, y-, and z-directions.\nWe will refer to these orthogonal dipoles, which are merely mathematical constructs, simply as ``dipoles'', while we will refer to the source dipole that is formed by combining the three orthogonal dipoles, as ``the ECD''.\n\nDuring the connectivity computation, we reduce the number of dipoles for computational efficiency reasons (\\autoref{canonical}) and use only two orthogonal dipoles instead of three; specifically, we use two orthogonal dipoles that are tangential to a spherical approximation of the head shape (\\autoref{fig:forward}, right) and that generate stronger magnetic fields than radial sources\\cite{Hamalainen1993}.\nFor computing power maps, we prefer to use three orthogonal dipoles at each source point.\n\n\\subsection{Code example}\\label{forward_example}\nThe following code example will construct a forward model for a single subject, suitable for connectivity analysis, following all the steps outlined above:\n\\lstinputlisting{code_snippets/forward.py}\n\nFor group-level analyses, it is important to note that MNE-Python stores the source points as vertex indices of the original FreeSurfer mesh and that these indices are always stored in sequential order.\nThus, when we morph the source space defined on the ``fsaverage'' brain to an individual subject, the ordering of the source points is not preserved.\nFor example, the first source point of subject 1 can correspond to the fourth source point of subject 2.\nTo account for this, we always store vertex indices in the order defined in the ``fsaverage'' source space.\nTo re-order the individual-level source-points correctly, we first determine the changes in the ordering of the vertices using the \\code{conpy.utils.get_morph_src_mapping} function and modify the vertex indices accordingly.\nThis process is implemented in script \\code{07_forward.py}.\n\n\\subsection{Application to the example dataset}\n\nIn the example dataset, the source space was first defined on the ``fsaverage'' brain and then morphed to each subject.\nFor each subject, three orthogonal dipoles were placed at each source point and the white matter and skull FreeSurfer meshes were used to compute the forward model. \nThe construction of the source spaces for the ``fsaverage'' brain is implemented in script \\code{06_fsaverage_src.py} and the morphing of the source space to the brains of the individual subjects and subsequent computation of the forward models are implemented in script \\code{07_forward.py}.\n\nWhile power mapping was done using all the source points, connectivity analysis used a restricted source space where all source points further than \\SI{7}{\\centi\\meter} from the closest MEG gradiometer were discarded.\nThis distance measurement was performed on the first subject and then used for all other subjects.\nThis process is implemented in script \\code{08_select_vertices.py}.\nIn connectivity analysis, the forward models that define three dipoles at each source point were transformed into ``tangential'' models that define two dipoles at each point.\nThis step is implemented in script \\code{10_connectivity.py}.\n\n\\section{Power mapping}\\label{power}\n\nThe DICS beamformer can be used to estimate the cortical sources of oscillatory activity within a given frequency band.\nAs explained in \\autoref{forward}, a grid of source points is defined along the cortex.\nAt each source point, three current dipoles are defined that are arranged to have orthogonal orientations.\nA whole-brain estimate of the oscillatory power is produced by computing, for each dipole, a spatial filter that passes activity that can be attributed to the dipole, while reducing activity originating from other sources\\cite{VanVeen1997}.\n\nOther than the various parameters involved in computing the CSD matrix and the forward model, the ``regularization'' parameter is an important parameter governing the creation of the spatial filters.\nIn practice, the regularization parameter represents a tradeoff between the amount of detail in the power maps and their sensitivity to noise.\nIf the amount of regularization is too small, it may result in the estimates being driven by noise factors, yielding sub-optimal results. If too much regularization is used, relevant details may be obscured and the power map will be dominated by the strongest sources.\nTypical values are in the range 0.01--0.1, scaled by the mean singular values of the CSD matrix.\n\nThe resulting cortical power maps define, at each source point, the power in all orientations.\nTypically, for each source point, only the power corresponding to the orientation that maximizes the power is reported.\n\n\\subsection{Mathematical formulation}\n\nThe regularization parameter $\\alpha$ arises from the need to compute the inverse of the CSD matrix.\nSince this matrix is often rank deficient, its inverse cannot be directly computed, but a pseudo-inverse needs to be approximated.\nThis estimation is more stable when a small value is added to the diagonal (diagonal loading):\n\\begin{align}\\label{eq:inverse}\n    \\lambda &= \\alpha \\, \\frac{\\text{trace}(\\mat{C})}{N_s}, \\\\\n    \\widehat{\\mat{C}}^{-1} &= {(\\mat{C} + \\lambda \\mat{I})}^{-1}.\n\\end{align}\nWe use the Moore--Penrose pseudoinverse to compute ${(\\mat{C} + \\lambda \\mat{I})}^{-1}$.\n\nInitially, the power maps will be biased towards superficial sources, since they have a larger effect on the MEG sensors.\nTo counter this, the leadfields can be normalized before computing the spatial filters:\n\n\\begin{equation}\\label{eq:leadfield}\n    \\widehat{\\vec{L}}(r) = \\frac{\\vec{L}(r)}{|\\vec{L}(r)|},\n\\end{equation}\nwhere $\\vec{L}(r)$ is a row vector containing the leadfield connecting dipole $r$ to each sensor, $|\\cdot|$ denotes the norm of the vector and $\\widehat{\\vec{L}}$ is the normalized leadfield.\n\n% We use this equation at multiple points, define it as a command\n\\newcommand{\\filter}[2]{\n    \\mat{A}(#1) \\, \\mat{C} \\, \\mat{A}{(#2)}\\ctrans\n}\n\nThe DICS beamformer is a linearly constrained minimum variance (LCMV) beamformer, computed using and applied to a (time-)frequency transformation of the original signals.\nWe deviate slightly from \\textcite{Gross2001} by computing the filter for each dipole separately:\n\\begin{equation}\\label{eq:filter}\n    \\vec{A}(r) = \\frac{\\widehat{\\vec{L}}{(r)}\\trans \\, \\widehat{\\mat{C}}^{-1}}{\\widehat{\\vec{L}}{(r)}\\trans \\, \\widehat{\\mat{C}}^{-1} \\, \\widehat{\\vec{L}}(r)}, \\\\\n\\end{equation}\nwhere $\\vec{A}(r)$ is a vector of weights that constitutes a linear spatial filter that attempts to isolate the signal power for the dipole from the rest of the signal.\nIn our approach, we treat dipoles with different orientations as separate sources, even if their locations are the same, and consequently compute the beamformer filter for each dipole individually.\nIn this case, $\\hat{\\vec{L}}(r)\\trans \\, \\hat{\\mat{C}}^{-1} \\, \\hat{\\vec{L}}(r)$ reduces to a scalar value, which avoids having to compute the inverse of another rank deficient matrix.\nWe obtain an estimate of the power at a source point by multiplying the filters for all dipoles defined at the location with the CSD matrix:\n\\begin{equation}\\label{eq:power}\n    \\mat{P}(\\vec{r}) = \\filter{\\vec{r}}{\\vec{r}},\n\\end{equation}\nwhere $\\mat{A}(\\vec{r})$ is a matrix whose rows contain the filters for all dipoles $\\vec{r}$ defined at the source point and $\\mat{P}(\\vec{r})$ is the resulting power estimate.\nThe power estimate contains, along the diagonal, the square of the power at each dipole, and the off-diagonal elements contain the cross-power estimates between dipoles.\n\nCommon methods of summarizing $\\mat{P}(\\vec{r})$ are:\n\\begin{enumerate}\n    \\item choosing the direction that maximizes the power, i.e.\\ the first singular value of $\\mat{P}(\\vec{r})$\n    \\item the sum of the squared power for each dipole, i.e.\\ $\\text{trace}(\\mat{P}(\\vec{r}))$\n    \\item the squared power in the direction that is orthogonal to the surface of the cortex.\n\\end{enumerate}\n\n\\subsection{Code example}\n\nIn the following example, we compute the cortical power maps for oscillatory activity in the range from \\SIrange{7}{13}{\\hertz} for the epochs corresponding to trials where a face stimulus was presented:\n\\lstinputlisting{code_snippets/power.py}\nThe regularization parameter \\code{reg} is set here to 0.05, which is generally a good tradeoff between the level of spatial detail and sensitivity to noise.\nIt is good practice to experiment with different values to see how the power maps behave: if the power estimates change substantially for small increments of the \\code{reg} parameter, it may be set too low.\nThe \\code{pick_ori} parameter selects the method with which to summarize the power at each source point.\nIn this case, for each source point, the power is computed along the direction which maximizes the power.\n\nWhen comparing the power maps from different subjects, the \\code{stc} objects can be morphed to the ``fsaverage'' brain with the \\code{stc.morph(to_subject)} method.\nThe morphed \\code{stc} objects can then be straightforwardly averaged and analyzed using the statistical functions in the same manner as for other types of source estimates\\cite{Jas2017}.\n\n\\subsection{Application to the example dataset}\n\nThe scripts \\code{09_power.py} and \\code{11_grand_average_power.py} implement the full analysis on the example dataset.\nScript \\code{figure_power.py} produces \\autoref{fig:power}.\n\n\\begin{figure}\n\\includegraphics[width=\\textwidth]{figures/power.pdf}\n\\caption{DICS grand average power maps. Cortical activity is visualized on an ``inflated'' version of the cortex, so as not to hide activity within the sulci. \\textbf{Top:} Estimation of cortical origins of oscillatory activity in the alpha band. In this case, the inflated view makes it seem there are three sources of alpha power, but in reality, these sources are adjacent on the original white matter surface. \\textbf{Bottom:} Contrasts between faces and scrambled images for all frequency bands. Warm colors indicate sources with more activity for faces than scrambled images and cold colors indicate sources with less.}\n\\label{fig:power}\n\\end{figure}\n\nIt is common for the power maps to be dominated by alpha and/or beta activity, as is the case for our example dataset as well (\\autoref{fig:power}, top row).\nThe alpha rhythm is typically generated in the parieto-occipital cortex.\nThe beamformer localizes the alpha activity over the entire \\SIrange{0}{0.4}{\\second} time window as a single, somewhat deep source\\cite{Ciulla1999}.\n\nMore interesting effects are revealed by contrasting two experimental conditions.\nIn the case of the example dataset, these are the presentation of faces versus scrambled images.\nFurthermore, we are interested in the changes in oscillatory power caused by the presentation of the stimuli, relative to the baseline period.\nAccordingly, our final power maps are computed as ``(faces$-$scrambled pictures)$/$baseline'' (\\autoref{fig:power}, bottom row).\n\n% The following is subject to change as we play with the parameters\nThe experimental paradigm used in the example dataset was designed to produce strong evoked potentials (EPs).\nAlthough DICS aims to capture oscillatory activity, the power maps are dominated by the EPs, especially in the lower frequency bands.\nIn our case, all frequency bands highlight the primary visual cortex, where there is a strong EP following shortly after the presentation of a visual stimulus.\nThe upper frequency bands only shows some very slight increases in activity, which is why we chose to perform the connectivity analysis for the low gamma band, since large differences in power between conditions will severely bias an all-to-all connectivity estimate.\n\nFor better interpretation of these results, one can proceed with statistical analysis of the power maps in a similar fashion as done with source estimates of evoked data, as detailed in \\textcite{Jas2017}.\n\n\n\\section{Connectivity analysis}\\label{connectivity}\n\nIn addition to analysis of oscillatory power, DICS is commonly used to investigate connectivity between cortical areas.\nThe DICS beamformer is well suited for estimating cortical connectivity, as coherence between brain regions can be determined based on the sensor-level CSD matrices, without the need to first estimate the time courses for the regions of interest, as required for most other connectivity metrics.\nThe coherence metric quantifies the level of synchronicity between the oscillatory activity of different areas, on a scale from 0 (no synchronization) to 1 (perfectly synchronized).\nCoherence is thought to be indicative of inter-areal communication\\cite{Fries2005}.\n\nIdeally, one would compute coherence between all source points in the source space.\nHowever, in practice, this is currently computationally intractable, so several thresholds will be applied to prune the number of connections.\nIn \\autoref{forward}, the first threshold was applied, namely that deep sources were eliminated from the source space.\nThis has the effect of only considering source locations where the MEG signals are the most reliable.\nThe second threshold we apply is a distance criterion.\nDue to the inherent field spread of the MEG signal\\cite{Hamalainen1993}, source points that are close together will always exhibit strong coherence.\nWhile this effect is alleviated by considering a contrast between two conditions, long-range connections\\cite{Salmelin2006} can be estimated more reliably than short-range ones.\nFor this reason, all connections between source points which are closer than a distance threshold (e.g., \\SI{\\leq 4}{\\centi\\meter}) are removed from further analysis.\nThe distance threshold is a parameter that needs to be chosen with care and in consideration with the research question of the study.\nWhen interpreting the result, one should always remember that there may be additional short-range connections present, but hidden from view due to the distance threshold.\n\nIn order to perform group-level analysis, coherence must be computed for the same connections in each subject.\nTherefore, the distance threshold based pruning is first applied to the connectivity pairs in a single subject, and the selection is subsequently carried over to the other subjects.\nIn \\autoref{statistics}, connections are further pruned based on a contrast between the experimental conditions.\n\n\\subsection{Canonical computation of coherence}\\label{canonical}\n\nThe connectivity computation is complicated somewhat by the fact that, generally, the forward model defines currents with both a magnitude and an orientation, represented through the use of multiple dipoles at each source point.\nFor example, our connectivity pipeline employs a ``tangential'' forward model that defines two orthogonal dipoles tangential to a sphere (see \\autoref{forward}).\nAs mentioned in the section on power mapping (\\autoref{power}), there are several ways to summarize the information at each source point.\nOne way would be to only use the orientation that maximizes source power\\cite{Gross2001}.\nHowever, simulations that were performed as part of the study by \\textcite{Saarinen2015} have shown that this strategy tends to produce spurious increases in coherence between unsynchronized sources.\nA better strategy may be to use, for each connection, orientations that maximize the coherence between the two source points.\nThis involves going through all the possible orientation combinations for the two source points, and choosing the orientation pair that maximizes the coherence.\nWe refer to this strategy as ``canonical computation of coherence'' and it is the default strategy implemented in the ConPy package.\n\n\\subsection{Mathematical formulation}\n\nGiven a CSD matrix $\\mat{C}$, it is straightforward to compute coherence between sensors (and later between cortical regions).\nThe coherence $m$ between sensors $i$ and $j$ is:\n\\begin{equation}\n    m(i, j) = \\frac{\\left|C(i, j)\\right|^2}{C(i, i) \\, C(j, j)}.\n\\end{equation}\n\nTo compute coherence between source points, the CSD matrix is first run through the DICS beamformer to obtain power estimates at each source point.\nIn our canonical coherence pipeline, we deviate from \\textcite{Gross2001} and replace the CSD matrix $\\mat{C}$ in \\autoref{eq:power} by the regularized version $\\widehat{\\mat{C}}$.\nThis results in an approximation of the power that is much faster to compute, as the equation simplifies to:\n\\begin{align}\n    \\widehat{P}(r) &= \\vec{A}(r) \\, \\widehat{\\mat{C}} \\, \\vec{A}{(r)}\\ctrans =\n        {\\left[\\widehat{\\vec{L}}{(r)}\\trans \\, \\widehat{\\mat{C}}^{-1} \\, \\widehat{\\vec{L}}(r)\\right]}^{-1},\n\\end{align}\nwhere $\\widehat{P}(r)$ is an approximation of the power estimate for dipole $r$.\nSimilarly, the cross-power between two dipoles ($r_1$, $r_2$) is approximated by ${[\\widehat{\\vec{L}}{(r_1)}\\trans \\, \\widehat{\\mat{C}}^{-1} \\, \\widehat{\\vec{L}}(r_2)]}^{-1}$.\n\nIn the canonical computation of coherence, coherence is estimated by optimizing the orientation of the ECDs at both source points for each connection.\nHere, we employ a tangential forward model, which defines two orthogonal dipoles at each source point to encode information about the leadfield in different orientations.\nUsing the tangential source orientation plane, we denote the leadfield for an ECD with orientation $\\theta$ as:\n\\begin{equation}\n    \\widehat{\\vec{L}}(\\vec{r}, \\theta) = \\sin(\\theta) \\, \\widehat{\\vec{L}}(r_1) + \\cos(\\theta) \\, \\widehat{\\vec{L}}(r_2),\n\\end{equation}\nwhere $r_1$ and $r_2$ are the two dipoles defined at the source point and $\\vec{r} = [r_1, r_2]$.\n\nCanonical coherence between two source points $M(\\vec{r}_1, \\vec{r}_2)$ is computed as follows:\n\\begin{equation}\\label{eq:coherence}\n    M(\\vec{r}_1, \\vec{r}_2) = \\max_{\\theta_1, \\, \\theta_2} \\,\n                              \\frac{|\\widehat{\\vec{L}}{(\\vec{r}_1, \\theta_1)}\\trans \\, \\widehat{\\mat{C}}^{-1} \\, \\widehat{\\vec{L}}(\\vec{r}_2, \\theta_2)|^2}\n                                   {[\\widehat{\\vec{L}}{(\\vec{r}_1, \\theta_1)}\\trans \\, \\widehat{\\mat{C}}^{-1} \\, \\widehat{\\vec{L}}(\\vec{r}_1, \\theta_1)] \\,\n                                    [\\widehat{\\vec{L}}{(\\vec{r}_2, \\theta_2)}\\trans \\, \\widehat{\\mat{C}}^{-1} \\, \\widehat{\\vec{L}}(\\vec{r}_2, \\theta_2)]\n                                   },\n\\end{equation}\nwhere $\\vec{r}_1$ are the two dipoles defined at the first source point and $\\vec{r}_2$ are the dipoles defined at the second source point, and $\\theta_1$ is the orientation of the ECD at the first source point and $\\theta_2$ the orientation of the ECD at the second source point.\n\nThe computation $\\max_{\\theta_1, \\theta_2}$ is conducted by performing a search over all possible ECD orientation combinations and using the maximum coherence value encountered during the search. In practice, ca. 50 different orientations are evaluated at both locations, spanning the tangential orientation plane at discrete intervals.\n\n\\subsection{Code example}\n\nIn the following example, we compute connectivity between all combinations of source pairs that are at least \\SI{4}{\\centi\\meter} apart.\nFor each connection, we compute the coherence between ECDs that are oriented in such a manner that the coherence between them is maximized (canonical computation of coherence).\nTo reduce the search space for the optimal orientation, we convert the forward model from one with three dipoles at each source point, to a tangential model with two (\\autoref{fig:forward}, right), which limits the orientations to the tangential plane:\n\\lstinputlisting{code_snippets/connectivity.py}\n\nWhen performing group-level analysis, it is important that connectivity is evaluated between the same pairs of source points in the same order across subjects.\nHowever, as we saw in \\autoref{forward_example}, by default, the ordering of the source points differs between subjects.\nTherefore, before comparing coherence values across subjects, the connectivity estimates need to be transformed to define the source points in the same order, e.g., the order of the ``fsaverage'' brain, with the \\code{con.to_original_src} method.\n\n\\subsection{Application to the example dataset}\n\nFor the example dataset, connectivity was estimated for the low gamma frequency band (\\SIrange{31}{40}{\\hertz}) in each subject.\nThe connectivity pairs were computed for the first subject and then carried over to the other subjects.\nThis computation is implemented in script \\code{08_select_vertices.py}.\nThe connectivity computations are implemented in script \\code{10_connectivity.py}.\nThe visualization of the connectivity results is performed after computing group-level statistics.\n\n\n\\section{Group-level statistics}\\label{statistics}\n\nOur analysis pipeline is designed for studying changes in cortico-cortical connectivity between different experimental conditions (as opposed to resting state analysis which studies the naturally occurring network while the subject is ``at rest'' in the scanner\\cite{Rosazza2011}).\nThus, instead of attempting to map the entire network, we focus on the parts of the network where connectivity changes between experimental conditions.\nThis means that the experimental design plays a vital role in our analysis pipeline, as experimental conditions must be designed so that contrasting them will reveal the sub-network of interest and are power-matched to minimize the effects of field spread.\n\nAll-to-all connectivity results can give an overwhelming amount of information that can be difficult to interpret.\nOne way to manage the complexity is to compute connectivity between parcels, rather than source points.\nHowever, in this paper we will demonstrate an alternative approach that focuses on pruning connections until a manageable number remains.\nThe procedure is an adaptation of the non-parametric cluster-permutation test by \\textcite{Maris2007}, where the difference is in the way the data is clustered.\n\nStarting from the initial all-to-all connectivity estimate, we prune connections that do not show a reliable difference between the experimental conditions.\nTo this end, we perform a paired $t$-test for each connection, comparing the coherence values for all subjects between the conditions.\nAll connections with an associated absolute $t$-value below a given threshold are pruned, while the surviving connections are grouped into ``bundles''.\nA ``bundle'' means in this context a group of connections whose start and end points are in close proximity to each other.\nBundles can be found by constructing a six-dimensional space, where each connection is assigned a position based on the Cartesian (xyz) coordinates of its starting and end points, and performing a hierarchical clustering in this space.\nThis clustering procedure is performed separately on connections with positive vs.\\ negative $t$-values, to assure that a bundle only contains connections that have an experimental effect in the same direction.\nEach bundle is assigned a ``bundle-$t$-value'' by summing the absolute $t$-values of the connections inside the bundle.\n\nTo determine which bundles show a significant effect, we repeat the above procedure many times with randomly permuted data to model the distribution of bundle-$t$-values we may expect from random data.\nRandom data was produced by flipping the condition labels for a random number of subjects, choosing a new random set of subjects for each permutation.\nImportantly, for each random permutation, only the maximum bundle-$t$-value is appended to the list of randomly observed $t$-values.\nThis is an effective way to manage type-I errors\\cite{Maris2007}.\nAny bundle with a bundle-$t$-value that is higher than at least \\SI{95}{\\percent} of the randomly obtained bundle-$t$-values, is deemed significant ($p \\leq 0.05$).\n\nThis procedure has two important parameters: the initial $t$-value threshold (\\code{cluster_threshold}) for pruning connections and the maximum distance between connections to be considered part of the same bundle (\\code{max_spread}).\nBoth parameters have an effect on the size of the bundles and hence the sensitivity of the test.\nSince the bundle-$t$-values are the sum of the $t$-values of the individual connections, large bundles will usually have a large bundle-$t$-value, making them more likely to survive the statistical threshold.\nHowever, the cluster-permutation test only tells whether a bundle as a whole is significant, not which connections inside a bundle drive this significance.\nThis means that a bundle that was flagged as significant could contain many connections that show little difference between experimental conditions, as long as it also contains connections that do show a salient difference.\n\nIn practice, we advise choosing \\code{cluster_threshold} such that a manageable number of connections remain (up to a few thousand) and \\code{max_spread} such that a reasonable number of connections (tens to hundreds) are assigned to each bundle.\nWhen choosing these parameters, it may help to visualize the selected connections (see \\autoref{visualization}) before performing the permutation test.\n\n\\subsection{Code example}\n\nThe following example reads in the connectivity objects for all subjects and all conditions and prunes the connections using the statistical thresholds outlined above.\n\n\\lstinputlisting{code_snippets/pruning.py}\n\n\\subsection{Application to the example dataset}\n\nIn the connectivity analysis of the example data, we focus on a selection of connections that show the most reliable difference between the experimental conditions.\nThe pruning of the all-to-all connectivity results is implemented in script \\code{12_connectivity_stats.py}. \n\nIn our analysis of the example dataset, we applied an initial $t$-value threshold of 5 to the connections, retaining 1028 out of the total of 4781057 connections.\nDuring the clustering step, connections with start and end points within \\SI{1}{\\centi\\meter} were grouped, resulting in 162 bundles.\nThe above thresholds were chosen such that there remained a manageable subset of the full all-to-all connectivity network, which shows the most robust differences between the processing of faces versus scrambled images.\nThe permutation test revealed two bundles that show a significant difference in coherence between the processing of faces versus scrambled images ($p < 0.05$), containing a total of 270 connections.\n\n\n\\section{Visualization}\\label{visualization}\n\nDepending on the statistical threshold, there may be hundreds or thousands of connections that survive the pruning step.\nIn order to visualize this many connections, we use a combination of a circular connectogram that summarizes connectivity between parcels (i.e., predefined cortical regions based on a brain atlas), and a ``degree map'' that shows, for each source point, the total number of connections from and to the point.\nIn this framework, we may use the circular connectogram to assess global connectivity patterns between parcels and use the degree map to see which specific parts of the cortex contain the start and end points of the connections.\n\nTo create a connectivity object that defines connectivity between parcels, rather than source points, we use brain atlases, such as the ones provided by the FreeSurfer package.\nThese atlases provide a list of parcels (also referred to as ``labels'') and a list of vertices of the cortical mesh belonging to each parcel.\nUsing this information, we can determine which source points belong to which parcel and make a parcel-wise summary.\n\nIn our pipeline, we choose to summarize the connection between two parcels by counting the total number of connections between them that survived the statistical thresholding (i.e., the degree).\nThe summary can then be visualized using a circular connectogram.\nIn general, large parcels that contain many source points will have more connections and thus a larger degree.\nTherefore, if the intention is for the circular connectogram to represent the overall connectivity between parcels, this ``degree bias'' could lead to misinterpretation of the result and it may be appropriate to remove this bias.\nThis can be done by dividing the sum by the total number of possible connections from and to the parcel.\n\nThe cortical degree map is created by counting the number of connections that survived the statistical threshold from and to each source point.\nThis degree map suffers from a similar bias as the circular connectogram, so it may be appropriate to divide the initial summary of each source point by the total number of possible connections from and to the point to remove this bias.\n\n\\subsection{Code example}\n\nThe following example will parcellate a connection object according to the ``aparc'' brain atlas\\cite{Fischl2004}, create a circular connectogram and a cortical degree map:\n\\lstinputlisting{code_snippets/visualization.py}\n\nThe above example results in a very basic circular connectogram.\nFor optimal clarity, some care needs to be put into the order and organization of the parcels along the circle.\nFor example, it may be useful to dedicate the left half of the circle to parcels in the left hemisphere and the right half to the right hemisphere.\nScript \\code{figure_connectivity.py} contains a more elaborate example of a circular connectogram.\n\n\\subsection{Application to the example dataset}\n\nThe visualization of the pruned all-to-all connectivity of the example dataset is implemented in script \\code{figure_connectivity.py} and presented in \\autoref{fig:connectivity}.\n\n\\begin{figure}\n    \\includegraphics[width=\\textwidth]{figures/connectivity.pdf}\n    \\caption{The subnetwork of the all-to-all connectivity network that shows the most robust changes across the experimental conditions. \\textbf{Left:} degree map showing, for each source point, the percentage of connections, out of all possible connections, that survived the statistical threshold and clustering operations. \\textbf{Right:} circular connectogram showing the number of connections between each parcel. Parcels were defined using the ``aparc'' anatomical brain atlas, provided by FreeSurfer.}\\label{fig:connectivity}\n\\end{figure}\n\nThe intended interpretation of \\autoref{fig:connectivity} is to first, using the degree map, identify the main areas where connectivity changes between faces versus scrambled images and then see which parcels overlap with these areas.\nThen, using the circular connectogram (\\autoref{fig:connectivity}, right), we can determine which connections between these areas are influenced by the experimental manipulation.\n\nIn our example dataset, the pruning of the all-to-all connectivity network resulted in a subnetwork that highlights a bundle of connections from the right middle temporal gyrus to the left superior frontal cortex and a bundle from the left motor cortex to the left oribitofrontal cortex (\\autoref{fig:connectivity}, top-left).\nSince the obtained connectome is so sparse, we opted not to compensate for the degree bias in the degree map and circular connectogram and simply report the number of connections.\n\nThe start and end points of the connection bundles do not always line up well with the parcels that are defined by the ``aparc'' brain atlas, which makes it less obvious in the circular connectogram that we are looking at two bundles of connections.\nHowever, when the circular connectogram is interpreted alongside the degree map, the two bundles become clear.\n\n\n\\section{Discussion}\\label{discussion}\n\nThe presented analysis pipeline facilitates mapping of cortico-cortical coherence, specifically its modulation between experimental conditions, in an all-to-all manner based on whole-head MEG data.\nThe original estimation of coupling is conducted at the level of a detailed grid of source points covering the entire cortex, but statistical testing and visualization of the results can be conducted both at this level and at the level of a coarser cortical parcels.\nIn addition to the estimation of connectivity, the pipeline provides source estimates of oscillatory activity (``power mapping'') at the same spatial scales as used in the coherence analysis.\nThe analysis pipeline consists of several steps that involve choices regarding how connectivity can be estimated, some of which are general considerations that are relevant also for other pipelines than the one presented here.\nIn this section, we discuss the effects and possible developments regarding some of these choices for the most critical analysis steps.\n\n\\subsection{Estimation of the cross spectral density matrix}\n\nIn the present manuscript, we considered cortico-cortical connectivity for event-related experimental paradigms where the cross spectral density matrix, which represents the mutual dependencies of neural signals at the sensor-level, needs to be estimated in a time-resolved manner.\nThis type of analysis is useful as it allows the use of event-related paradigms where experimental manipulation is generally more straightforward than in continuous and more naturalistic experiments.\nMoreover, the approach readily allows limiting the analysis to an artefact-free time window of the experiment (e.g., in speech production).\nThe original DICS was developed for continuous data\\cite{Gross2001} where the CSD estimation is based on Fourier transformations.\nIn the present analysis, as well as in previous work using event-related DICS\\cite{Kujala2012, Kujala2014, Liljestrom2015a}, wavelet-based analysis was used to obtain the time-frequency CSD\\@.\nIn the time-frequency domain, wavelets provide an optimal compromise between time and frequency resolution.\nHowever, the time-resolved estimation could equally well be conducted using short-term Fourier transformation, especially if appropriate windowing functions are used.\nMore importantly, while the present analysis focused on the event-related estimation of cortico-cortical coupling, the pipeline can directly be applied also to continuous data by replacing the CSD estimation step with Fourier transformation based computations, as was done in \\textcite{Gross2001}.\n\n\\subsection{Definition of the source space}\n\nIn general, reliable evaluation of cortico-cortical connectivity requires a group-level description of neural interactions.\nThis, in turn, necessitates the estimation of the neural connectivity patterns in the same locations across subjects.\nThis can be achieved both at the level of detailed grids of source points and cortical parcellations.\nParcellations have been used more commonly for all-to-all type connectivity estimation\\cite{Palva2010, Saarinen2015, Schoffelen2017} as they reduce the computational load of the estimation and the amount of statistical testing.\nThe present analysis pipeline facilitates both using a grid of source points and parcel-level estimation.  An effective group-level estimation of connectivity between source points is achieved by generating a grid of points along the cortex of a reference brain (e.g. FreeSurfer's ``fsaverage'' brain) and transforming this grid to each individual's anatomy.\nAs a consequence, the same connections are estimated in every subject, allowing direct estimation of the group-level statistics.\nA parcel-level description can then also by readily obtained as it is sufficient to assign each point-level connection to a parcel-pair in the common brain instead of doing the assignments separately in each subject.\nFor the parcel-level estimation it would be almost equally straightforward to use individually defined grids of source points.\nHowever, when one aims to evaluate more detailed spatial aspects of connectivity, the chosen approach eliminates the need for massive interpolation operations that would be required if individual-level grids of source points were used.\n\n\\subsection{Choice of the interaction metric}\n\nHere, we chose to apply a DICS based estimation of cortical connectivity that allows a direct mapping of the mutual dependencies of the sensor-level signals to a cortical space without the need for estimation of cortical-level time-series of activity.\nAs the present connectivity estimation is dependent on the use of a CSD matrix, coherence is the only interaction metric that can be estimated straightforwardly in this manner.\nNotably, similar approaches that map the sensor level interaction patterns to the source level without the time-series estimation step have also been developed for metrics such as partial directed coherence\\cite{Michalareas2013} or imaginary coherence\\cite{Drakesmith2013}.\n\nSince interactions due to field spread exhibit zero phase lag, using an interaction measure that is sensitive only to non-zero phase lag, such as imaginary coherence\\cite{Nolte2004, Drakesmith2013}, may reduce the detection of spurious interactions.\nHowever, there is good indication that not all zero-phase-lag connections are spurious\\cite{Gollo2014}, so methods focusing solely on imaginary coherence should be used with care.\n\nAs theoretical models of neural interactions propose that neuronal coherence mechanistically subserves neuronal communication\\cite{Fries2005}, the choice of coherence as an interaction metric factor does not necessarily represent a limitation of the approach.\nHowever, if the goal is to use some other metric to quantify neural interactions the analysis pipeline would need to be adjusted.\nWithin the framework of transforming sensor-level dependency patterns to the source level, it would be possible to utilize, e.g., weighted phase-lag index\\cite{Vinck2011} by transforming single-trial (as opposed to average) CSD matrices to the source level.\nMost metrics would, however, require that one would first estimate cortical-level time-series of activity.\nThis would be readily possible by using the DICS spatial filter for weighing the sensor-level time-series.\nWithin this framework, however, the use of a detailed grid of source points would no longer be computationally tractable and it would be better to construct parcel-level time-series before the metric-dependent quantification of neural interactions.\n\n\\subsection{Considerations regarding field spread and source orientations}\n\nIn the presented analysis we focused on estimating connectivity in an all-to-all manner without the need for a priori seed regions or constraining of the analysis to connections between preselected brain areas.\nThe field spread based confounding factors in connectivity estimation are particularly critical for this type of analysis\\cite{Schoffelen2009a} where it is difficult, e.g., to visually evaluate whether the observed changes in patterns of neural interactions truly represent modulation of coupling as opposed to modulation of field spread between experimental conditions.\nTo minimize the effects of field spread, we focused only on long range (\\SI{\\geq4}{\\centi\\meter}) connections and examined coherence modulations for conditions for which the amount of neural activity/oscillatory power are closely matched.\nHowever, the exact degree of matching that is required for contrasting canonical coherence, or any other type of coherence estimates, remains an open question.\n\nMost of the neural signals detected by MEG and EEG originate from sources that are approximately orthogonal to the surface of the cortex\\cite{Hamalainen1993}.\nSo, one may restrict the source space by defining only ECDs that point in the orthogonal direction, by for example leveraging the surface normals of the 3D-mesh produced by FreeSurfer\\cite{Dale1993}.\nHowever, in practice, each source grid-point represents the signal for a patch of cortical surface which, due to the folding of the cortex, includes locations with different surface normals.\nEspecially when using a large spacing between grid-points, as we do in our pipeline, the source within each patch that drives the activity at the grid-point does not necessarily have the same orientation as the average surface normal of the patch as a whole.\nThis is why it is recommended to allow for some flexibility regarding dipole orientation whenever possible\\cite{Lin2006}.\nWhether this is possible in practice depends on the computational costs of performing the source estimates for multiple orientations and whether the SNR is good enough to produce a reliable estimate of the optimal orientation.\n\nIn the current pipeline we exclusively used a canonical estimation of coherence\\cite{Saarinen2015, Liljestrom2015a, Liljestrom2015b} where, for each connection, the orientations of the source ECDs at both sides of the connection are selected such that they maximize coherence.\nTo make this computationally feasible, we restrict the number of possible orientations by leveraging the fact that MEG is less sensitive to ``radial'' sources, due to the properties of the magnetic field\\cite{Hamalainen1993}.\nBy choosing a tangential source space (see \\autoref{fig:forward}, right), coherence values are only computed for those ECD orientations that yield the largest signal on the MEG sensors.\nThis canonical estimation of coherence yields a maximally stable estimate of coherence and it is well suited for investigating modulation of coherence between experimental conditions.\nThe estimates are, however, relatively smooth.\nFor estimating absolute coherence values for short-range connections, especially when the expected coherence values are small, other criteria for defining the source orientations could be more appropriate.\n\nFor the connectivity analysis, we chose to design separate sets of DICS beamformer filters for each condition, instead of designing one set of filters to apply to both conditions.\nAccordingly, the estimation of coherence and optimization of the source orientations was also performed separately for each condition.\nThis approach allows for subtle differences in optimal source orientations between the conditions and avoids biasing the solution towards the condition with better SNR\\@.\nIf the goal were to ensure that field spread effects are be maximally cancelled out by contrasting two conditions, it would be beneficial to conduct the orientation optimization and weight estimation using a joint CSD across the conditions.\nThe optimal choice between the alternatives depends on the research question and properties of the data.\n\n\\subsection{Statistical testing and visualization}\n\nIn the final stage of connectivity analysis one also needs to consider both what type of statistical testing and what spatial scales are optimal.\nAs stated above, the present analysis pipeline has been designed for examining coherence modulations between experimental conditions.\nMoreover, to minimize confounding effects resulting from substantial power differences between conditions, the pipeline is aimed at contrasting different tasks as opposed to contrasting a single task to resting baseline levels of neural interaction.\nIt is also possible to contrast a single task to a task-average\\cite{Saarinen2015} to highlight how the connectivity changes in a specific task with respect to multiple different tasks.\nNotably, the analysis pipeline does not provide a full connectome, that is, a complete description of the underlying networks.\nInstead, it yields a snapshot of a specific part of the network where cortico-cortical coupling has changed from one experimental condition to another.\nBy introducing a battery of control conditions and comparisons between different conditions, the pipeline would thus allow the identification of different subnetworks that are critical for different aspects of neural processing in performing the tasks.\n\nThe present analysis pipeline enables the evaluation of the above aspects both at the level of detailed grids of source points and coarser parcellations.\nAn effective visualization combines a connectogram that shows the connectivity at the parcel level, with a visualization of the grid-level connectivity on the cortex.\nThis makes it possible to evaluate whether the patterns of neural connectivity evaluated at the grid-level are faithfully represented also at the level of a parcellated cortex.\nThis, in turn, allows the fine tuning of the parcellation schemes, which are generally based on anatomical division, to better suit MEG data.\n\n\n\\section{Conclusion}\n\nWe have presented an analysis pipeline that facilitates the cortical mapping of oscillatory activity and estimation of all-to-all type cortico-cortical coherence.\nCombined with \\textcite{Jas2017}, all the necessary steps of the analysis of a real experiment are described: starting from the processing of raw MEG data to the statistical group analysis of the networks and visualization of the results using connectograms, as one would use in a publication.\nWe have developed a new python package called ConPy, which integrates with MNE-python\\cite{mne} to offer a clean interface to all required software routines to reproduce the analysis.\nIt is our hope that our example analysis will serve as a strong foundation for others who seek to implement their own DICS analysis pipelines.\n\n\n\\section*{Conflict of Interest Statement}\n\nThe authors declare that the research was conducted in the absence of any commercial or financial relationships that could be construed as a potential conflict of interest.\n\n\n\\section*{Author Contributions}\n\nMvV, ML, RS, JK: writing of the manuscript.\nML, RS, JK: conceptualization of the DICS analysis pipeline. \nMvV, SA: software implementation of the analysis pipeline.\nMvV: analysis of the example dataset.\n\n\n\\section*{Funding}\n\nThis work was supported by the Academy of Finland (grant 310988), the Sigrid Juselius Foundation, Maud Kuistila Memorial Foundation and the Swedish Cultural Foundation in Finland.\n\n\n\\section*{Acknowledgments}\n\nWe would like to thank Britta Westner, Sarang S. Dalal, Eric Larson and Alexandre Gramfort for their help with reviewing the code.\n\n\n\\bibliographystyle{frontiersinSCNS_ENG_HUMS}\n\\bibliography{conpy}\n\n\\end{document}\n", "meta": {"hexsha": "94dfc75ea0e49d194b97e38d586529d3f7635dce", "size": 81479, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/conpy.tex", "max_stars_repo_name": "jundurraga/conpy", "max_stars_repo_head_hexsha": "e0836ea9206f988234e5d1fda3f2eeb86598203f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2018-08-22T14:51:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T22:41:23.000Z", "max_issues_repo_path": "paper/conpy.tex", "max_issues_repo_name": "jundurraga/conpy", "max_issues_repo_head_hexsha": "e0836ea9206f988234e5d1fda3f2eeb86598203f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-08-21T07:10:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-31T19:27:15.000Z", "max_forks_repo_path": "paper/conpy.tex", "max_forks_repo_name": "jundurraga/conpy", "max_forks_repo_head_hexsha": "e0836ea9206f988234e5d1fda3f2eeb86598203f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2018-11-11T21:53:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-17T03:11:56.000Z", "avg_line_length": 95.632629108, "max_line_length": 625, "alphanum_fraction": 0.7956283214, "num_tokens": 17977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.3309510876326516}}
{"text": "\\chapter[Proof handling]{Proof handling\\index{Proof editing}\n\\label{Proof-handling}}\n\nIn \\Coq's proof editing mode all top-level commands documented in \nChapter~\\ref{Vernacular-commands} remain available\nand the user has access to specialized commands dealing with proof\ndevelopment pragmas documented in this section. He can also use some\nother specialized commands called {\\em tactics}.  They are the very\ntools allowing the user to deal with logical reasoning. They are\ndocumented in Chapter~\\ref{Tactics}.\\\\ \nWhen switching in editing proof mode, the prompt\n\\index{Prompt} \n{\\tt Coq <} is changed into {\\tt {\\ident} <} where {\\ident} is the\ndeclared name of the theorem currently edited.\n\nAt each stage of a proof development, one has a list of goals to\nprove. Initially, the list consists only in the theorem itself. After\nhaving applied some tactics, the list of goals contains the subgoals\ngenerated by the tactics.\n\nTo each subgoal is associated  a number of\nhypotheses called the {\\em \\index*{local context}} of the goal.\nInitially, the local context contains the local variables and\nhypotheses of the current section (see Section~\\ref{Variable}) and the\nlocal variables and hypotheses of the theorem statement.  It is\nenriched by the use of certain tactics (see e.g. {\\tt intro} in\nSection~\\ref{intro}).\n\nWhen a proof is completed, the message {\\tt Proof completed} is\ndisplayed. One can then register this proof as a defined constant in the\nenvironment. Because there exists a correspondence between proofs and\nterms of $\\lambda$-calculus, known as the {\\em Curry-Howard\nisomorphism} \\cite{How80,Bar91,Gir89,Hue89}, \\Coq~ stores proofs as\nterms of {\\sc Cic}. Those terms are called {\\em proof\n  terms}\\index{Proof term}.\n\n\\ErrMsg When one attempts to use a proof editing command out of the\nproof editing mode, \\Coq~ raises the error message : \\errindex{No focused\n  proof}.\n\n\\section{Switching on/off the proof editing mode}\n\nThe proof editing mode is entered by asserting a statement, which\ntypically is the assertion of a theorem:\n\n\\begin{quote}\n{\\tt Theorem {\\ident} \\zeroone{\\binders} : {\\form}.\\comindex{Theorem}\n\\label{Theorem}}\n\\end{quote}\n\nThe list of assertion commands is given in\nSection~\\ref{Assertions}. The command {\\tt Goal} can also be used.\n\n\\subsection[Goal {\\form}.]{\\tt Goal {\\form}.\\comindex{Goal}\\label{Goal}}\n\nThis is intended for quick assertion of statements, without knowing in\nadvance which name to give to the assertion, typically for quick\ntesting of the provability of a statement. If the proof of the\nstatement is eventually completed and validated, the statement is then\nbound to the name {\\tt Unnamed\\_thm} (or a variant of this name not\nalready used for another statement).\n\n\\subsection[\\tt Qed.]{\\tt Qed.\\comindex{Qed}\\label{Qed}}\nThis command is available in interactive editing proof mode when the\nproof is completed.  Then {\\tt Qed} extracts a proof term from the\nproof script, switches back to {\\Coq} top-level and attaches the\nextracted proof term to the declared name of the original goal. This\nname is added to the environment as an {\\tt Opaque} constant.\n\n\\begin{ErrMsgs}\n\\item \\errindex{Attempt to save an incomplete proof}\n%\\item \\ident\\ \\errindex{already exists}\\\\ \n%  The implicit name is already defined. You have then to provide\n%  explicitly a new name (see variant 3 below).\n\\item Sometimes an error occurs when building the proof term,\nbecause tactics do not enforce completely the term construction\nconstraints.\n\nThe user should also be aware of the fact that since the proof term is\ncompletely rechecked at this point, one may have to wait a while when\nthe proof is large. In some exceptional cases one may even incur a\nmemory overflow.\n\\end{ErrMsgs}\n\n\\begin{Variants}\n\n\\item {\\tt Defined.}\n\\comindex{Defined} \n\\label{Defined} \n\n  Defines the proved term as a transparent constant.\n\n\\item {\\tt Save.}\n\\comindex{Save}\n\n  This is a deprecated equivalent to {\\tt Qed}.\n\n\\item {\\tt Save {\\ident}.}\n  \n  Forces the name of the original goal to be {\\ident}.  This command\n  (and the following ones) can only be used if the original goal has\n  been opened using the {\\tt Goal} command.\n\n\\item {\\tt Save Theorem {\\ident}.} \\\\\n {\\tt Save Lemma {\\ident}.} \\\\\n {\\tt Save Remark {\\ident}.}\\\\\n {\\tt Save Fact {\\ident}.}\n {\\tt Save Corollary {\\ident}.}\n {\\tt Save Proposition {\\ident}.}\n\n  Are equivalent to {\\tt Save {\\ident}.} \n\\end{Variants}\n\n\\subsection[\\tt Admitted.]{\\tt Admitted.\\comindex{Admitted}\\label{Admitted}}\nThis command is available in interactive editing proof mode to give up\nthe current proof and declare the initial goal as an axiom.\n\n\\subsection[\\tt Proof {\\term}.]{\\tt Proof {\\term}.\\comindex{Proof}\n\\label{BeginProof}}\nThis command applies in proof editing mode. It is equivalent to {\\tt\n  exact {\\term}; Save.} That is, you have to give the full proof in\none gulp, as a proof term (see Section~\\ref{exact}).\n\n\\variant {\\tt Proof.}\n  \n  Is a noop which is useful to delimit the sequence of tactic commands\n  which start a proof, after a {\\tt Theorem} command.  It is a good\n  practice to use {\\tt Proof.} as an opening parenthesis, closed in\n  the script with a closing {\\tt Qed.}\n\n\\SeeAlso {\\tt Proof with {\\tac}.} in Section~\\ref{ProofWith}.\n\n\\subsection[{\\tt Proof using} {\\ident$_1$} {\\ldots} {\\ident$_n$}{\\tt .}]\n{{\\tt Proof using} {\\ident$_1$} {\\ldots} {\\ident$_n$}{\\tt .}\n\\comindex{Proof using} \\label{ProofUsing}}\n\nThis command applies in proof editing mode. \nIt declares the set of section variables (see~\\ref{Variable}) \nused by the proof. At {\\tt Qed} time, the system will assert that \nthe set of section variables actually used in the proof is a subset of\nthe declared one.\n\nThe set of declared variables is closed under type dependency.\nFor example if {\\tt T} is variable and {\\tt a} is a variable of\ntype {\\tt T}, the commands {\\tt Proof using a} and\n{\\tt Proof using T a} are actually equivalent.\n\n\\variant {\\tt Proof using} {\\ident$_1$} {\\ldots} {\\ident$_n$} {\\tt with} {\\tac}{\\tt .} \nin Section~\\ref{ProofWith}.\n\n\\variant {\\tt Proof using All.} \n\n  Use all section variables.\n\n\\variant {\\tt Proof using Type.} \n\\variant {\\tt Proof using.} \n  \n  Use only section variables occurring in the statement.\n\n\\variant {\\tt Proof using Type*.} \n  \n  The {\\tt *} operator computes the forward transitive closure.\n  E.g. if the variable {\\tt H} has type {\\tt p < 5} then {\\tt H} is\n  in {\\tt p*} since {\\tt p} occurs in the type of {\\tt H}.\n  {\\tt Type* } is the forward transitive closure of the entire set of\n  section variables occurring in the statement.\n\n\\variant {\\tt Proof using -( \\ident$_1$} {\\ldots} {\\tt \\ident$_n$  ).}\n  \n  Use all section variables except {\\ident$_1$} {\\ldots} {\\ident$_n$}.\n\n\\variant {\\tt Proof using \\nterm{collection}$_1$ + \\nterm{collection}$_2$ .}\n\n\\variant {\\tt Proof using \\nterm{collection}$_1$ - \\nterm{collection}$_2$ .}\n\n\\variant {\\tt Proof using \\nterm{collection} - ( \\ident$_1$} {\\ldots} {\\tt \\ident$_n$ ).}\n\n\\variant {\\tt Proof using \\nterm{collection} * .}\n\n  Use section variables being, respectively, in the set union, set difference,\n  set complement, set forward transitive closure.\n  See Section~\\ref{Collection} to know how to form a named\n  collection.\n  The {\\tt *} operator binds stronger than {\\tt +} and {\\tt -}.\n\n\\subsubsection{{\\tt Proof using} options}\n\\optindex{Default Proof Using}\n\\optindex{Suggest Proof Using}\n\\optindex{Proof Using Clear Unused}\n\nThe following options modify the behavior of {\\tt Proof using}.\n\n\\variant {\\tt Set Default Proof Using \"expression\".} \n\n  Use {\\tt expression} as the default {\\tt Proof using} value.\n  E.g. {\\tt Set Default Proof Using \"a b\".} will complete all {\\tt Proof }\n  commands not followed by a {\\tt using} part with {\\tt using a b}.\n\n\\variant {\\tt Set Suggest Proof Using.}\n\n  When {\\tt Qed} is performed, suggest a {\\tt using} annotation if\n  the user did not provide one.\n\n\\variant{\\tt Unset Proof Using Clear Unused.}\n\n  When {\\tt Proof using a} all section variables but for {\\tt a} and\n  the variables used in the type of {\\tt a} are cleared.\n  This option can be used to turn off this behavior.\n\n\\subsubsection[\\tt Collection]{Name a set of section hypotheses for {\\tt Proof using}}\n\\comindex{Collection}\\label{Collection}\n\nThe command {\\tt Collection} can be used to name a set of section hypotheses,\nwith the purpose of making {\\tt Proof using} annotations more compact.\n\n\\variant {\\tt Collection Some := x y z.}\n\n  Define the collection named \"Some\" containing {\\tt x y} and {\\tt z} \n\n\\variant {\\tt Collection Fewer := Some - x.} \n  \n  Define the collection named \"Fewer\" containing only {\\tt x y} \n\n\\variant {\\tt Collection Many := Fewer + Some.} \n\\variant {\\tt Collection Many := Fewer - Some.} \n  \n  Define the collection named \"Many\" containing the set union or set difference\n  of \"Fewer\" and \"Some\".\n\n\\variant {\\tt Collection Many := Fewer - (x y).}\n\n  Define the collection named \"Many\" containing the set difference\n  of \"Fewer\" and the unnamed collection {\\tt x y}.\n\n\\subsection[\\tt Abort.]{\\tt Abort.\\comindex{Abort}}\n\nThis command cancels the current proof development, switching back to\nthe previous proof development, or to the \\Coq\\ toplevel if no other\nproof was edited.\n\n\\begin{ErrMsgs}\n\\item \\errindex{No focused proof (No proof-editing in progress)}\n\\end{ErrMsgs}\n\n\\begin{Variants}\n\n\\item {\\tt Abort {\\ident}.}\n\n  Aborts the editing of the proof named {\\ident}.\n\n\\item {\\tt Abort All.}\n\n  Aborts all current goals, switching back to the \\Coq\\ toplevel.\n\n\\end{Variants}\n\n%%%%\n\\subsection[\\tt Existential {\\num} := {\\term}.]{\\tt Existential  {\\num} := {\\term}.\\comindex{Existential}\n\\label{Existential}}\n\nThis command instantiates an existential variable. {\\tt \\num}\nis an index in the list of uninstantiated existential variables\ndisplayed by {\\tt Show Existentials} (described in Section~\\ref{Show}).\n\nThis command is intended to be used to instantiate existential\nvariables when the proof is completed but some uninstantiated\nexistential variables remain. To instantiate existential variables\nduring proof edition, you should use the tactic {\\tt instantiate}.\n\n\\SeeAlso {\\tt instantiate (\\num:= \\term).} in Section~\\ref{instantiate}.\n\\SeeAlso {\\tt Grab Existential Variables.} below.\n\n\\subsection[\\tt Grab Existential Variables.]{\\tt Grab Existential Variables.\\comindex{Grab Existential Variables}\n\\label{GrabEvars}}\n\nThis command can be run when a proof has no more goal to be solved but has remaining\nuninstantiated existential variables. It takes every uninstantiated existential variable\nand turns it into a goal.\n\n%%%%%%%%\n\\section{Navigation in the proof tree}\n%%%%%%%%\n\n\\subsection[\\tt Undo.]{\\tt Undo.\\comindex{Undo}}\n\nThis command cancels the effect of the last command.  Thus, it\nbacktracks one step.\n\n\\begin{Variants}\n\n\\item {\\tt Undo {\\num}.}\n\n  Repeats {\\tt Undo} {\\num} times.\n\n\\end{Variants}\n\n\\subsection[\\tt Restart.]{\\tt Restart.\\comindex{Restart}}\nThis command restores the proof editing process to the original goal.\n\n\\begin{ErrMsgs}\n\\item \\errindex{No focused proof to restart}\n\\end{ErrMsgs}\n\n\\subsection[\\tt Focus.]{\\tt Focus.\\comindex{Focus}}\nThis focuses the attention on the first subgoal to prove and the printing\nof the other subgoals is suspended until the focused subgoal is\nsolved or unfocused. This is useful when there are many current\nsubgoals which clutter your screen.\n\n\\begin{Variant}\n\\item {\\tt Focus {\\num}.}\\\\ \nThis focuses the attention on the $\\num^{th}$ subgoal to prove.\n\n\\end{Variant}\n\n\\subsection[\\tt Unfocus.]{\\tt Unfocus.\\comindex{Unfocus}}\nThis command restores to focus the goal that were suspended by the\nlast {\\tt Focus} command.\n\n\\subsection[\\tt Unfocused.]{\\tt Unfocused.\\comindex{Unfocused}}\nSucceeds in the proof is fully unfocused, fails is there are some\ngoals out of focus.\n\n\\subsection[\\tt \\{ \\textrm{and} \\}]{\\tt \\{ \\textrm{and} \\}\\comindex{\\{}\\comindex{\\}}}\nThe command {\\tt \\{} (without a terminating period) focuses on the\nfirst goal, much like {\\tt Focus.} does, however, the subproof can\nonly be unfocused when it has been fully solved (\\emph{i.e.} when\nthere is no focused goal left). Unfocusing is then handled by {\\tt \\}}\n(again, without a terminating period). See also example in next section.\n\nNote that when a focused goal is proved a message is displayed\ntogether with a suggestion about the right bullet or {\\tt \\}} to\nunfocus it or focus the next one.\n\n\\begin{ErrMsgs}\n\\item \\errindex{This proof is focused, but cannot be unfocused\n    this way} You are trying to use {\\tt \\}} but the current subproof\n  has not been fully solved.\n\\item see also error message about bullets below.\n\\end{ErrMsgs}\n\n\\subsection[Bullets]{Bullets\\comindex{+ (command)}\n  \\comindex{- (command)}\\comindex{* (command)}\\index{Bullets}}\nAlternatively to {\\tt \\{} and {\\tt \\}}, proofs can be structured with\nbullets. The use of a bullet $b$ for the first time focuses on the\nfirst goal $g$, the same bullet cannot be used again until the proof\nof $g$ is completed, then it is mandatory to focus the next goal with $b$. The\nconsequence is that $g$ and all goals present when $g$ was focused are\nfocused with the same bullet $b$. See the example below.\n\nDifferent bullets can be used to nest levels. The scope of bullet does\nnot go beyond enclosing {\\tt \\{} and {\\tt \\}}, so bullets can be\nreused as further nesting levels provided they are delimited by these.\nAvailable bullets are {\\tt -}, {\\tt +}, {\\tt *}, {\\tt --}, {\\tt ++}, {\\tt **},\n{\\tt ---}, {\\tt +++}, {\\tt ***}, ... (without a\nterminating period).\n\nNote again that when a focused goal is proved a message is displayed\ntogether with a suggestion about the right bullet or {\\tt \\}} to\nunfocus it or focus the next one.\n\nRemark: In {\\ProofGeneral} (Emacs interface to {\\Coq}), you must use\nbullets with the priority ordering shown above to have a correct\nindentation. For example {\\tt -} must be the outer bullet and {\\tt **}\nthe inner one in the example below.\n\nThe following example script illustrates all these features:\n\\begin{coq_example*}\nGoal (((True/\\True)/\\True)/\\True)/\\True.\nProof.\n  split.\n  - split.\n    + split.\n      ** { split.\n          - trivial.\n          - trivial.\n        }\n      ** trivial.\n    + trivial.\n  - assert True.\n    { trivial. }\n    assumption.\n\\end{coq_example*}\n\n\n\\begin{ErrMsgs}\n\\item \\errindex{Wrong bullet {\\abullet}1 : Current bullet\n    {\\abullet}2 is not finished.}\n\n  Before using bullet {\\abullet}1 again, you should first finish\n  proving the current focused goal. Note that {\\abullet}1 and\n  {\\abullet}2 may be the same.\n\n\\item \\errindex{Wrong bullet {\\abullet}1 : Bullet {\\abullet}2\n    is mandatory here.} You must put {\\abullet}2 to focus next goal.\n  No other bullet is allowed here.\n\n\n\\item \\errindex{No such goal. Focus next goal with bullet\n    {\\abullet}.}\n\n  You tried to applied a tactic but no goal where under focus. Using\n  {\\abullet} is mandatory here.\n\n\\item \\errindex{No such goal. Try unfocusing with {\"{\\tt \\}}\"}.} You\n  just finished a goal focused by {\\tt \\{}, you must unfocus it with \"{\\tt \\}}\".\n\n\\end{ErrMsgs}\n\n\n\\section{Requesting information}\n\n\\subsection[\\tt Show.]{\\tt Show.\\comindex{Show}\\label{Show}}\nThis command displays the current goals.\n\n\\begin{Variants}\n\\item {\\tt Show {\\num}.}\\\\ \n  Displays only the {\\num}-th subgoal.\\\\ \n\\begin{ErrMsgs}\n\\item \\errindex{No such goal}\n\\item \\errindex{No focused proof}\n\\end{ErrMsgs}\n\n\\item {\\tt Show Script.}\\comindex{Show Script}\\\\\n  Displays the whole list of tactics applied from the beginning\n  of the current proof. \n  This tactics script may contain some holes (subgoals not yet proved).\n  They are printed under the form \\verb!<Your Tactic Text here>!.\n\n%% \\item {\\tt Show Tree.}\\comindex{Show Tree}\\\\\n%% This command can be seen as a more structured way of\n%% displaying the state of the proof than that \n%% provided by {\\tt Show Script}. Instead of just giving\n%% the list of tactics that have been applied, it \n%% shows the derivation tree constructed by then. \n%% Each node of the tree contains the conclusion\n%% of the corresponding sub-derivation (i.e. a\n%% goal with its corresponding local context) and \n%% the tactic that has generated all the \n%% sub-derivations. The leaves of this tree are\n%% the goals which still remain to be proved.\n\n%\\item {\\tt Show Node}\\comindex{Show Node}\\\\\n%        Not yet documented\n\n\\item {\\tt Show Proof.}\\comindex{Show Proof}\\\\\nIt displays the proof term generated by the \ntactics that have been applied. \nIf the proof is not completed, this term contain holes,\nwhich correspond to the sub-terms which are still to be \nconstructed. These holes appear as a question mark indexed \nby an integer, and applied to the list of variables in \nthe context, since it may depend on them. \nThe types obtained by abstracting away the context from the\ntype of each hole-placer are also printed.\n\n\\item {\\tt Show Conjectures.}\\comindex{Show Conjectures}\\\\\nIt prints the list of the names of all the theorems that \nare currently being proved.\nAs it is possible to start proving a previous lemma during\nthe proof of a theorem, this list may contain several \nnames. \n\n\\item{\\tt Show Intro.}\\comindex{Show Intro}\\\\\nIf the current goal begins by at least one product, this command\nprints the name of the first product, as it would be generated by \nan anonymous {\\tt Intro}. The aim of this command is to ease the\nwriting of more robust scripts. For example, with an appropriate \n{\\ProofGeneral} macro, it is possible to transform any anonymous {\\tt\n  Intro} into a qualified one such as {\\tt Intro y13}.\nIn the case of a non-product goal, it prints nothing. \n\n\\item{\\tt Show Intros.}\\comindex{Show Intros}\\\\\nThis command is similar to the previous one, it simulates the naming \nprocess of an {\\tt Intros}.\n\n\\item{\\tt Show Existentials.\\label{ShowExistentials}}\\comindex{Show Existentials}\n\\\\ It displays\nthe set of all uninstantiated existential variables in the current proof tree, \nalong with the type and the context of each variable.\n\n\\item{\\tt Show Universes.\\label{ShowUniverses}}\\comindex{Show Universes}\n\\\\ It displays the set of all universe constraints and its\nnormalized form at the current stage of the proof, useful for\ndebugging universe inconsistencies.\n\n\\end{Variants}\n\n\n\\subsection[\\tt Guarded.]{\\tt Guarded.\\comindex{Guarded}\\label{Guarded}}\n\nSome tactics (e.g. refine \\ref{refine}) allow to build proofs using\nfixpoint or co-fixpoint constructions. Due to the incremental nature\nof interactive proof construction, the check of the termination (or\nguardedness) of the recursive calls in the fixpoint or cofixpoint\nconstructions is postponed to the time of the completion of the proof.\n\nThe command \\verb!Guarded! allows checking if the guard condition for\nfixpoint and cofixpoint is violated at some time of the construction\nof the proof without having to wait the completion of the proof.\"\n\n\n\\section{Controlling the effect of proof editing commands}\n\n\\subsection[\\tt Set Hyps Limit {\\num}.]{\\tt Set Hyps Limit {\\num}.\\optindex{Hyps Limit}}\nThis command sets the maximum number of hypotheses displayed in\ngoals after the application of a tactic. \nAll the hypotheses remains usable in the proof development.\n\n\n\\subsection[\\tt Unset Hyps Limit.]{\\tt Unset Hyps Limit.\\optindex{Hyps Limit}}\nThis command goes back to the default mode which is to print all\navailable hypotheses.\n\n\n\\subsection[\\tt Set Automatic Introduction.]{\\tt Set Automatic Introduction.\\optindex{Automatic Introduction}\\label{Set Automatic Introduction}}\n\nThe option {\\tt Automatic Introduction} controls the way binders are\nhandled in assertion commands such as {\\tt Theorem {\\ident}\n  \\zeroone{\\binders} : {\\form}}. When the option is set, which is the\ndefault, {\\binders} are automatically put in the local context of the\ngoal to prove.\n\nThe option can be unset by issuing {\\tt Unset Automatic Introduction}.\nWhen the option is unset, {\\binders} are discharged on the statement\nto be proved and a tactic such as {\\tt intro} (see\nSection~\\ref{intro}) has to be used to move the assumptions to the\nlocal context.\n\n\\section{Controlling memory usage\\comindex{Optimize Proof}\\comindex{Optimize Heap}}\n\nWhen experiencing high memory usage the following commands can be\nused to force Coq to optimize some of its internal data structures.\n\n\\subsection[\\tt Optimize Proof.]{\\tt Optimize Proof.}\n\nThis command forces Coq to shrink the data structure used to represent\nthe ongoing proof.\n\n\\subsection[\\tt Optimize Heap.]{\\tt Optimize Heap.}\n\nThis command forces the OCaml runtime to perform a heap compaction.\nThis is in general an expensive operation.  See:\n  \\url{http://caml.inria.fr/pub/docs/manual-ocaml/libref/Gc.html#VALcompact}\n\n\n%%% Local Variables: \n%%% mode: latex\n%%% TeX-master: \"Reference-Manual\"\n%%% End: \n", "meta": {"hexsha": "481afa8f87c6e649824da03b27077bb33f432bc0", "size": 20660, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "presentations/coq-workshop-2014-coq/doc/refman/RefMan-pro.tex", "max_stars_repo_name": "JasonGross/test-broken-tar", "max_stars_repo_head_hexsha": "6b52b8532879df53386b0f5413485888a1aa886a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "presentations/coq-workshop-2014-coq/doc/refman/RefMan-pro.tex", "max_issues_repo_name": "JasonGross/test-broken-tar", "max_issues_repo_head_hexsha": "6b52b8532879df53386b0f5413485888a1aa886a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "presentations/coq-workshop-2014-coq/doc/refman/RefMan-pro.tex", "max_forks_repo_name": "JasonGross/test-broken-tar", "max_forks_repo_head_hexsha": "6b52b8532879df53386b0f5413485888a1aa886a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4954627949, "max_line_length": 144, "alphanum_fraction": 0.7363504356, "num_tokens": 5284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.3309510804726407}}
{"text": "\\documentclass[11pt]{article}\r\n\\usepackage{cite}\r\n\\usepackage{a4}\r\n\r\n\\usepackage[utf8]{inputenc}\r\n\\usepackage[english]{babel}\r\n\\usepackage{amsmath,amssymb,amsthm}\r\n\r\n\\usepackage{url}\r\n\\usepackage{pgf}\r\n\\usepackage{tikz}\r\n\\usepackage{pictures}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% layout commands\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\newtheorem{thm}{Theorem}[section]\r\n\\newtheoremstyle{break}% name\r\n  {9pt}%      Space above, empty = `usual value'\r\n  {9pt}%      Space below\r\n  {\\itshape}% Body font\r\n  {}%         Indent amount (empty = no indent, \\parindent = para indent)\r\n  {\\bfseries}% Thm head font\r\n  {.}%        Punctuation after thm head\r\n  {.5em}% Space after thm head: \\newline = linebreak\r\n  {}%         Thm head spec\r\n\\theoremstyle{break}\r\n\\newtheorem{lem}[thm]{Lemma}\r\n\r\n\\newcommand{\\prog}[3]{\\langle #1, #2, #3\\rangle}\r\n\\newcommand{\\slp}[1]{\\mathbb{#1}}\r\n\\newcommand{\\slpterm}[3]{\\slp{#1}_{#2} = #3}\r\n\\newcommand{\\slpnonterm}[4]{\\slp{#1}_{#2} = \\slp{#1}_{#3} \\cdot \\slp{#1}_{#4}}\r\n\\newcommand{\\substr}[2]{[#1\\dots#2]}\r\n\\newcommand{\\subslp}[3]{\\slp{#1}[#2\\dots#3]}\r\n\r\n\\newcommand{\\probleminput}[1]{\\noindent \\textsc{Input:} #1}\r\n\\newcommand{\\problemoutput}[1]{\\noindent \\textsc{Output:} #1}\r\n\\newcommand{\\problem}[3]{\\smallskip\r\n            \\noindent {\\sc Problem:} \\textbf{#1} \\newline\r\n            \\noindent {\\sc Input:} #2 \\newline\r\n            \\noindent {\\sc Output:} #3\r\n\\smallskip}\r\n\\renewcommand{\\proof}{{\\bf Proof:}}\r\n\\newcommand{\\example}[1]{{\\bf Example} (#1)}\r\n\r\n\\renewcommand{\\emptyset}{\r\n    \\font\\msbm = msbm10 at 12pt\r\n    \\mbox{\\msbm \\char 63}\r\n}\r\n\r\n\\begin{document}\r\n\r\n\\title{Computing All Squares in Compressed Texts}\r\n\\author{Lesha Khvorost\\\\\r\nUral Federal University\\\\\r\njaamal@mail.ru}\r\n\\date{}\r\n\\maketitle\r\n\r\n\\begin{abstract}\r\nWe consider the problem of computing all squares in a string represented by a straight-line program (SLP). An instance of the problem is an\r\nSLP $\\slp{S}$ that derives some string $S$ and we seek a solution in the form of a table that contains information about all squares in $S$\r\nin a compressed form. We present an algorithm that solves the problem in $O(|\\slp{S}|^4\\log^2{|S|})$ time and requires $O(|\\slp{S}|^2)$\r\nspace, where $|\\slp{S}|$ (respectively $|S|$) stands for the size of the SLP $\\slp{S}$ (respectively the length of the string $S$).\r\n\\end{abstract}\r\n\r\n\\section{Introduction}\r\n\r\nVarious compressed representations of strings are known: straight-line programs (SLPs) \\cite{14,15,16,18},\r\ncollage-systems \\cite{12}, string representations using antidictionaries \\cite{13}, etc. Nowadays text compression\r\nbased on context-free grammars such as SLPs attracts much attention. The reason for this is not only that grammars\r\nprovide well-structured compression but also that the SLP-based compression is in a sense polynomially equivalent\r\nto the compression achieved by the Lempel-Ziv algorithm that is widely used in practice. It means that, given a\r\nstring $S$, there is a polynomial relation between the size of an SLP that derives $S$ and the size of the\r\ndictionary stored by the Lempel-Ziv algorithm \\cite{18}.\r\n\r\nWhile compressed representations save storage space, there is a price to pay: some classical problems on strings become computationally\r\nhard when one deals with compressed data and measures algorithms' speed in terms of the size of compressed representations. As examples we\r\nmention here the problems \\textbf{Hamming distance} \\cite{15} and \\textbf{Literal shuffle} \\cite{4}. On the other hand, there exist\r\nproblems that admit algorithms working rather well on compressed representations: \\textbf{Pattern matching} \\cite{15,10}, \\textbf{Longest\r\ncommon substring} \\cite{16}, \\textbf{Computing all palindromes} \\cite{16}. This dichotomy gives rise to the following research direction:\r\nto classify important string problems by their behavior with respect to compressed data.\r\n\r\n\\textbf{Computing All Squares} (\\textbf{CAS}) is a natural problem on strings some of whose variants are of importance for molecular\r\nbiology. (We just mention in passing a typical biological application \\cite{19} in which repeats in mouse genome were employed to trace the\r\nmigration of mouse subspecies through Eurasia.) Up to recently it is was not known whether or not \\textbf{CAS} admits an algorithm\r\npolynomial in the size of a compressed representation of a given string.\\footnote{A polynomial algorithm that solves \\textbf{CAS} for\r\nstrings represented by Lempel-Ziv encodings was announced in~\\cite{8}. This representation is slightly more general than that by SLPs.\r\nHowever, to the best of our knowledge, no details of the algorithm have ever been published.} The question is rather non-trivial because,\r\nin general, a string can have exponentially many squares with respect to the size of its compressed representation. For example, the string\r\n$a^n$ has $\\Theta(n^2)$ squares, while it is easy to build an SLP of size $O(\\log n)$ that derives $a^n$. Thus, if we look for a polynomial\r\nalgorithm for \\textbf{CAS}, we have to develop a suitable data structure to store information about squares in a compressed form. Also, the\r\nfact that the number of squares may be quite large implies that a polynomial algorithm cannot search for squares consecutively by moving\r\nfrom one square to the ``next'' one. Squares should be somehow grouped in relatively large families that are to be discovered at once. The\r\naim of the present paper is to demonstrate that these difficulties can be overcome for the case where strings are represented via SLPs.\r\n\r\nThe paper is structured as follows. Section~2 gathers some preliminaries concerning strings and SLPs. Section~3 collects brief descriptions\r\nand complexity analysis of some basic operations over SLPs that are frequently used in the paper. In Section~4 we present a polynomial\r\nalgorithm for \\textbf{CAS}. In Section~5 we discuss our results and their relation to other recent work in the area~\\cite{balancedsf,sf}.\r\n\r\nThe main result of the paper has been announced in \\cite{RuFiDim}. It relies on an earlier algorithm by the author \\cite{pure} which was\r\ndeveloped to find all \\emph{pure} squares (squares of primitive words) in a text derived from a given SLP.\r\n\r\n\r\n\\section{Preliminaries}\r\n\r\nWe consider strings of characters from a fixed finite alphabet $\\Sigma$. The \\emph{length} of a string $S$ is the number of its characters\r\nand is denoted by $|S|$. The \\emph{concatenation} of strings $S_1$ and $S_2$ is denoted by $S_1 \\cdot S_2$ or simply by $S_1S_2$. A\r\n\\emph{position} in a string $S$ is a point between two consecutive characters. We number positions from left to right by $1,2,\\dots,|S|-1$.\r\nIt is convenient to consider also the position 0 preceding the string and the position $|S|$ following it. For an integer $i$ with $0 \\le i\r\n\\le |S|$ we denote by $S[i]$ the character between the positions $i$ and $i+1$ of $S$. For example, $S[0]$ is the first character of $S$. A\r\n\\emph{substring} of $S$ starting at a position $\\ell$  and ending at a position $r$ where $0\\leq \\ell < r \\leq |S|$ is denoted by $S[\\ell\r\n\\dots r]$ (in other words, $S[\\ell \\dots r] = S[\\ell]\\cdot S[\\ell+1]\\cdot\\mbox{\\dots}\\cdot S[r-1]$). We say that a substring $S[\\ell \\dots\r\nr]$ \\emph{touches} a position $t$ if $\\ell \\leq t \\leq r$.\r\n\r\nA string is called a \\emph{square} if it can be obtained by concatenating two copies of some string called the \\emph{root} of the square. A\r\nsquare $xx$ is called \\emph{pure} if $x$ occurs exactly two times in $xx$. If $p$ is a positive integer, a string $S$ is called\r\n\\emph{$p$-periodic} if for every position $i$ with $0\\le i<|S-p|$, the equality $S[i] = S[i + p]$ holds. The integer $p$ is then referred\r\nto as a \\emph{period} of $S$. By the classic Fine--Wilf theorem~\\cite{20}, each period $p$ of a string $S$ such that $p\\le|S|/2$ is a\r\nmultiple of the least period of $S$. A $p$-periodic substring of a string $S$ is said to be \\emph{maximal} if it is not contained in any\r\nlonger $p$-periodic substring of $S$.\r\n\r\nA \\emph{straight-line program} (SLP) $\\slp{S}$ is a sequence of \\emph{rules}, that is assignments of the form:\r\n\\begin{equation}\r\n\\label{eq:SLP} \\slp{S}_0 := expr_0,\\ \\slp{S}_1 := expr_1, \\dots, \\slp{S}_n := expr_n,\r\n\\end{equation}\r\nwhere each $expr_i$ is either a letter from $\\Sigma$ (in this case the rule $\\slp{S}_i := expr_i$ is said to be \\emph{terminal}) or an\r\nexpression of the form $\\slp{S}_\\ell\\cdot \\slp{S}_r$ with $0\\le \\ell, r < i$ (in this case the rule $\\slp{S}_i := expr_i$ is called\r\n\\emph{nonterminal}). Thus, an SLP is a context-free grammar in Chomsky normal form. Every SLP $\\slp{S}$ derives exactly one string\r\n$S\\in\\Sigma^+$ and we refer to $S$ as the \\emph{text} derived from $\\slp{S}$.\r\n\r\nFor an illustration, consider the following SLP $\\slp{F}_6$ that derives the 6-th Fibonacci word $F_6=abaababaabaab$:\r\n\\begin{gather*}\r\n\\slp{F}_0 := a,\\ \\slp{F}_1 := b,\\ \\slp{F}_2 := \\slp{F}_1\\cdot \\slp{F}_2,\\ \\slp{F}_3 := \\slp{F}_3\\cdot \\slp{F}_1,\\\\\r\n\\slp{F}_4 := \\slp{F}_4\\cdot \\slp{F}_3,\\ \\slp{F}_5 := \\slp{F}_5\\cdot \\slp{F}_4,\\ \\slp{F}_6 := \\slp{F}_6\\cdot \\slp{F}_5.\r\n\\end{gather*}\r\nThe parse tree of the derivation is shown in Figure~\\ref{fibonacci_word_slp}. In this example, the SLP derives a text of length 13 and\r\ncontains 7 rules. In the general case, the $n$-th Fibonacci word can be derived from the following SLP with $n + 1$ rules:\r\n$$\\slp{F}_0:= b,\\ \\slp{F}_1:= a,\\ \\slp{F}_2:= \\slp{F}_1\\cdot\\slp{F}_0,\\ \\slp{F}_3:= \\slp{F}_2\\cdot\\slp{F}_1,\\ \\dots,\\\r\n\\slp{F}_n:= \\slp{F}_{n-1}\\cdot\\slp{F}_{n-2}.$$ Since the length of the $n$-th Fibonacci word is equal to the $(n + 1)$-th Fibonacci number,\r\ni.e. the nearest integer to $\\frac{\\varphi^{n+1}}{\\sqrt{5}}$, where $\\varphi=\\frac{1+\\sqrt{5}}2$ is the golden ratio, we see that the rule\r\nnumber of an SLP may be exponentially smaller than the length of the text derived from the SLP.\r\n\r\n\\begin{figure}[htb]\r\n    \\begin{center}\r\n        \\begin{picture}(100,175)(120,10)\r\n            \\fibonacciwordslp\r\n        \\end{picture}\r\n    \\end{center}\r\n    \\caption{The parse tree of the derivation of the text $abaababaabaab$ from $\\slp{F}_6$}\r\n    \\label{fibonacci_word_slp}\r\n\\end{figure}\r\n\r\nWe adopt the following conventions in the paper: every SLP is denoted by a capital blackboard bold letter, for example, $\\slp{S}$. The\r\nleft-hand sides of the rules of this SLP are denoted by the same letter with indices, for example, $\\slp{S}_0,\\slp{S}_1,\\dots$. If an SLP\r\n$\\slp{S}$ is fixed, its rules are uniquely determined by their left-hand sides and, for brevity, we allow ourselves to refer to\r\n$\\slp{S}_0,\\slp{S}_1,\\dots$ as rules. For each $i$, the rule $\\slp{S}_i$ can be also thought of as an SLP, namely, as the SLP\r\n$$\\slp{S}_0 := expr_0,\\ \\slp{S}_1 := expr_1, \\dots, \\slp{S}_i := expr_i,$$\r\nso that one can speak of the text derived from a rule. We denote this text by the same indexed capital letter but in the standard font; for\r\nexample, the text that is derived from $\\slp{S}_i$ is denoted by $S_i$.\r\n\r\nThe \\emph{cut position} of a nonterminal rule $\\slp{S}_i := \\slp{S}_\\ell\\cdot \\slp{S}_r$ is the position $|S_\\ell|$ in the text $S_i$. For\r\ninstance, the cut position of $\\slp{F}_4$ in Figure~\\ref{fibonacci_word_slp} is equal to~3. For every terminal rule, we define its cut\r\nposition to be equal to~0.\r\n\r\nThe \\emph{size} of an SLP $\\slp{S}$ is the number of its rules and is denoted by $|\\slp{S}|$. The \\emph{concatenation} of SLPs $\\slp{S}$\r\nand $\\slp{S}'$ is any SLP that derives the text $S\\cdot S'$. We denote the concatenation by $\\slp{S} \\cdot \\slp{S}'$ but we would like to\r\nemphasize that, unlike string concatenation, SLP concatenation is not a rigidly defined operation as there are various ways to construct an\r\nSLP that derives $S\\cdot S'$ starting from given SLPs $\\slp{S}$ and $\\slp{S}'$. A rather straightforward way to concatenate $\\slp{S}$ and\r\n$\\slp{S}'$ is as follows. Let $\\slp{S}$ be the SLP~\\eqref{eq:SLP} and let $\\slp{S}'$ be the SLP\r\n$$\\slp{S}'_0 := expr'_0,\\ \\slp{S}'_1 := expr'_1, \\dots, \\slp{S}'_{n'} := expr'_{n'}.$$\r\nWe set $m=n+n'+1$ and consider the SLP $\\slp{T}$ defined as\r\n$$\\slp{T}_0 := expr''_0,\\ \\slp{T}_1 := expr''_1, \\dots, \\slp{T}_{m} := expr''_{m},\\ \\slp{T}_{m+1}:=\\slp{T}_n\\cdot\\slp{T}_m,$$\r\nwhere for each $i=0,\\dots,n$,\r\n$$expr''_i=\\begin{cases} expr_i &\\text{if $expr_i$ is a letter from $\\Sigma$},\\\\\r\n\\slp{T}_\\ell\\cdot \\slp{T}_r &\\text{if }  expr_i=\\slp{S}_\\ell\\cdot \\slp{S}_r,\r\n\\end{cases}$$\r\nand for each $j=n+1,\\dots,m$,\r\n$$expr''_j=\\begin{cases} expr'_{j-n-1} &\\text{if $expr'_{j-n-1}$ is a letter from $\\Sigma$},\\\\\r\n\\slp{T}_\\ell\\cdot \\slp{T}_r &\\text{if }  expr'_{j-n-1}=\\slp{S}'_\\ell\\cdot \\slp{S}'_r.\r\n\\end{cases}$$\r\nWith this straightforward construction, the size of the concatenation of $\\slp{S}$ and $\\slp{S}'$ is $|\\slp{S}|+|\\slp{S}'|+1$. Of course,\r\nin some special cases one can concatenate CSPs in a much more economic way. For instance, the concatenation $\\slp{S}\\cdot\\slp{S}$ can be\r\nobtained by adding just one extra rule: if $\\slp{S}$ is the SLP~\\eqref{eq:SLP}, then this new rule is $\\slp{S}_{n+1}:=\\slp{S}_n\\cdot\r\n\\slp{S}_n$. More generally, the concatenation $\\underbrace{\\slp{S}\\cdot \\slp{S}\\cdot\\ldots\\cdot\\slp{S}}_{k\\text{ times}}$ (that we will\r\ndenote by $\\slp{S}^k$) can be constructed by adding $\\lceil\\log k\\rceil$ additional rules.\r\n\r\n\\section{Basic operations}\r\n\r\nManipulating with SLPs is based on certain ``elementary'' operations. In this section we list the algorithms for basic operations that we\r\nfrequently use in the present paper and discuss the space and time complexity of these algorithms. Except the pattern matching algorithm\r\nthat is taken from~\\cite{15}, the algorithms are folklore and it is hard to provide adequate references for them. Therefore, for the\r\nreader's convenience, we present them here in some detail even though we provide no formal correctness proofs.\r\n\r\nFirst we make a general observation: given an SLP $\\slp{S}$, it is easy to calculate the number $|S|$. Indeed, we can convert the rules of\r\n$\\slp{S}$ into a system of numerical equalities substituting each terminal rule $\\slp{S}_i:=a$, where $a\\in\\Sigma$, by the equality\r\n$|S_i|=1$ and each nonterminal rule $\\slp{S}_i:=\\slp{S}_\\ell\\cdot \\slp{S}_r$, where $\\ell,r<i$, by the equality $|S_i|=|S_\\ell|+|S_r|$.\r\nClearly, the resulting system of equalities constitutes a recursion that allows one to calculate $|S|$ (and $|S_i|$ for each $i$) via\r\n$O(|\\slp{S}|)$ additions. Therefore, in the algorithms below, we may and will assume that $|S|$ is known whenever $\\slp{S}$ is given. The\r\nargument also implies the inequality $\\log|S|\\le|\\slp{S}|$ which will be used without reference in several complexity considerations below.\r\n\r\n\\subsection{Subgrammar cutting}\r\n\r\nAn operation that is most frequently invoked in this paper is the one that constructs an SLP presentation for a substring of a text\r\npresented by a given SLP. We call this operation \\emph{subgrammar cutting} even though we should emphasize that in general an SLP for a\r\nsubstring need not be a subgrammar (in any common sense of the word) of the initial SLP.\r\n\r\nHere is a formal description of the subgrammar cutting problem:\r\n\r\n\\problem{SubCut}{an SLP $\\slp{S}$, integers $\\ell$ and $r$ such that $0 \\leq \\ell < r \\leq |S|$;}{an SLP that derives the text\r\n$S\\substr{\\ell}{r}$.}\r\n\r\nWe denote the output of \\textbf{SubCut} by $\\slp{S}\\substr{\\ell}{r}$. Our algorithm for \\textbf{SubCut} consists of three phases. In the\r\nfirst phase we try to locate the least node of the parse tree of the text $S$ with the property that the text $S\\substr{\\ell'}{r'}$ derived\r\nfrom the rule labelling the node contains the substring $S\\substr{\\ell}{r}$, that is, $\\ell'\\le\\ell$ and $r\\le r'$. The algorithm uses\r\nthree variables: a symbol $\\slp{C}$ for the current node label and integers $\\ell$ and $r$.\r\n\r\n\\smallskip\r\n\r\n\\noindent {\\sc Descent:} The algorithm starts from the root of the parse tree of $S$ and we initialize $\\slp{C}$ with the last rule of\r\n$\\slp{S}$ and the variables $\\ell$ and $r$ with the input values of \\textbf{SubCut}. If $\\slp{C}$ is a terminal rule then the algorithm\r\nstops and returns $\\slp{C}$ for $\\slp{S}\\substr{\\ell}{r}$. Otherwise the current node is labelled a nonterminal rule $\\slp{C}:= \\slp{L}\r\n\\cdot \\slp{R}$. If $r \\le |L|$, then the algorithm descends to node labelled by $\\slp{L}$; this means that we update $\\slp{C}$ with\r\n$\\slp{L}$ and keep the values of $\\ell$ and $r$. If $\\ell\\ge|L|$, then the algorithm descends to node labelled by $\\slp{R}$; this means\r\nthat we update $\\slp{C}$ with $\\slp{R}$ and set $\\ell := \\ell - |L|$, $r := r - |L|$. If $\\ell < |L| < r$, the desired node has been found,\r\nand the algorithm passes the current values $\\slp{C}$, $\\ell$, and $r$ to the next phase.\r\n\r\n\\smallskip\r\n\r\nIn the second phase, we work with the nonterminal rule $\\slp{C}:= \\slp{L} \\cdot \\slp{R}$ such that $\\ell < |L| < r$ and aim to decompose\r\nthe rules $\\slp{L}$ and $\\slp{R}$ into smaller ``pieces'' whose concatenations are SLPs that derive the substrings $S\\substr{\\ell}{|L|}$\r\nand respectively $S\\substr{|L|}{r}$. We present the decomposition algorithm for $\\slp{L}$ only since $\\slp{R}$ can be handled in a\r\nsymmetric way. The algorithm operates with a symbol $\\slp{CL}$ for the current node label and uses a stack for storing factors of the\r\ndecomposition.\r\n\r\n\\smallskip\r\n\r\n\\noindent {\\sc Left Decomposition:} We initialize $\\slp{CL}$ with $\\slp{L}$. If $\\slp{CL}$ is a terminal rule then the algorithm adds\r\n$\\slp{CL}$ to the result stack and stops. Otherwise $\\slp{CL}:= \\slp{LL} \\cdot \\slp{LR}$ is a nonterminal rule. If $\\ell > |LL|$, then the\r\nalgorithm descends to the node labelled by $\\slp{LR}$, that is, updates $\\slp{CL}$ with $\\slp{LR}$. The stack remains unchanged. If $\\ell =\r\n|LL|$ then the algorithm adds $\\slp{LR}$ to the stack and stops. If $\\ell < |LL|$, then the algorithm adds $\\slp{LR}$ to the stack and\r\ndescends to the node labelled by $\\slp{LL}$, that is, updates $\\slp{CL}$ with $\\slp{LL}$. When the algorithm stops, we have a nonempty\r\nstack of rules that is passed to the final phase.\r\n\r\n\\smallskip\r\n\r\n\\noindent {\\sc Concatenation:} We concatenate the SLPs from the stack produced by the \\textsc{Left Decomposition} in the top-to-bottom\r\norder (that is, the top element of the stack becomes the leftmost factor and so on). The concatenation produces an SLP\r\n$\\slp{S}\\substr{\\ell}{|L|}$ that derives $S\\substr{\\ell}{|L|}$. Dually, we concatenate the SLPs from the stack produced by the\r\n\\textsc{Right Decomposition} in the bottom-to-top order (the top element of the stack becomes the rightmost factor and so on). This\r\nproduces an SLP $\\slp{S}\\substr{|L|}{r}$ that derives $S\\substr{|L|}{r}$. Finally, we concatenate $\\slp{S}\\substr{\\ell}{|L|}$ with\r\n$\\slp{S}\\substr{|L|}{r}$ to produce the desired SLP $\\slp{S}\\substr{\\ell}{r}$.\r\n\r\n\\smallskip\r\n\r\n\\noindent \\textsc{Complexity:} The descent phase uses $O(|\\slp{S}|)$ time because the number of its steps does not exceed the length of the\r\nlongest path between the root of the parse tree of $S$ and some leaf of this tree. By the same reason, the decomposition phases spend\r\n$O(|\\slp{S}|)$ time and $O(|\\slp{S}|)$ space for stacks. The concatenation phase uses $O(|\\slp{S}|)$ time and $O(|\\slp{S}|)$ space to\r\nconcatenate the content of the stacks. Altogether the above algorithm solves \\textbf{SubCut} in $O(|\\slp{S}|)$ time and $O(|\\slp{S}|)$\r\nspace.\r\n\r\n\r\n\r\n\\subsection{Pattern matching}\r\n\\label{subsec:pm}\r\n\r\n Suppose that we are given two SLPs $\\slp{S}$ and $\\slp{T}$ and we want to find all occurrences of the text $S$ derived from\r\n$\\slp{S}$ as a substring of the text $T$ derived from $\\slp{T}$. (Clearly, we may and will assume that  $|S|\\le|T|$.) A difficulty here is\r\nthat in general the number of occurrences of $S$ in $T$ may be exponential as a function of $|\\slp{T}|$. Thus, any polynomial algorithm for\r\npattern matching with SLPs as input should store information about the occurrences in a suitable compressed form. It turns out that a\r\nsuitable way to encode the occurrences of $S$ in $T$ is by arithmetic progressions. More precisely, it can be shown that the start\r\npositions of all occurrences of $S$ in $T$ can be grouped into $O(|\\slp{T}|)$ arithmetic progressions. Each such arithmetic progression is\r\ncompletely characterized by 3 numbers: the first start position $s$, the difference $d$, and the length $n$, and we will denote the\r\nprogression by the triple $\\prog{s}{d}{n}$. For example, a progression denoted $\\prog{3}{2}{4}$ indicates that $T$ contains 4 occurrences\r\nof $S$ that start from the positions 3, 5, 7, and 9.\r\n\r\nHere is a formal description of the pattern matching problem:\r\n\r\n\\problem{PM}{SLPs $\\slp{S}$ and $\\slp{T}$ such that $|S| \\leq |T|$;}{$O(|\\slp{T}|)$ arithmetic progressions that describe the start\r\npositions of all occurrences of $S$ in $T$ if $S$ occurs in $T$ as a substring; the empty set otherwise.}\r\n\r\nFor an illustration, consider \\textbf{PM} for the Fibonacci SLPs $\\slp{F}_2$ and $\\slp{F}_6$. Then one of the possible outputs consists of\r\nthe two progressions $\\prog{0}{3}{2}$ and $\\prog{5}{3}{3}$.\r\n\r\nWe need the following result from~\\cite{15}:\r\n\\begin{thm}\r\nThere exists an algorithm that solves \\textbf{PM} using $O(|\\slp{T}|^2|\\slp{S}|)$ time and $O(|\\slp{T}||\\slp{S}|)$ space.\r\n\\end{thm}\r\n\r\nIn order to bound the number of arithmetic progressions in terms of the ratio $|T|/|S|$, the following consequence of the Fine--Wilf\r\ntheorem is useful. We say that a string $S$ \\emph{occurs at a position} $t$ in $T$ if $S=T[t\\dots t+|S|]$, that is, $t$ is the start\r\nposition of an occurrence of $S$ in $T$.\r\n\r\n\\begin{lem}[\\!\\!{\\mdseries\\cite{2}, Lemma~4.8}]\r\n\\label{lem:blocks} Let $p_1 < p_2 < \\dots < p_k$ be a sequence of positions of a text $T$ such that a string $S$ occurs at each of these\r\npositions but at no other position preceding $p_k$. If $p_k-p_1\\le\\frac{|S|}{2}$, then the $p_i$'s form an arithmetic progression with the\r\ndifference $p=p_2-p_1$ and the string $S$ is $p$-periodic with $p$ being its least period.\r\n\\end{lem}\r\n\r\nLemma~\\ref{lem:blocks} implies that if we divide $T$ into $2\\lceil\\frac{|T|}{|S|}\\rceil$ consecutive substrings of length\r\n$\\le\\lfloor\\frac{|S|}{2}\\rfloor$ and for each such substring consider start positions of occurrences of $S$ in $T$ the substring touches,\r\nthen these positions can be grouped into a single arithmetic progression. Therefore all start positions of occurrences of $S$ in $T$ can be\r\ndescribed by at most $2\\lceil\\frac{|T|}{|S|}\\rceil$ arithmetic progressions.\r\n\r\n\\subsection{Substring extending}\r\n\r\nMany algorithms detecting squares in a string $S$ start with detecting a pair of equal substrings in $S$. In order to check if such a pair\r\nindeed corresponds to a square is $S$, we should be able to recognize whether or not the substrings forming the pair can be extended to\r\nequal substrings which are adjacent in $S$. This leads to the following problem.\r\n\r\n\\problem{SubsExt}{an SLP $\\slp{S}$, integers $\\ell_1, r_1, \\ell_2$, $r_2$ with $0 \\le \\ell_1 < r_1 \\le|S|$, $0 \\le \\ell_2 < r_2 \\le|S|$\r\nsuch that $S\\substr{\\ell_1}{r_1} = S\\substr{\\ell_2}{r_2}$;}{integers $\\ell_{ex}$ and $r_{ex}$ such that $\\ell_{ex}$ is the length of the\r\nlongest common suffix of the substrings $S\\substr{0}{\\ell_1}$ and $S\\substr{0}{\\ell_2}$ and $r_{ex}$ is the length of the longest common\r\nprefix of the substrings of $S\\substr{r_1}{|S|}$ and $S\\substr{r_2}{|S|}$.}\r\n\r\nWe describe an algorithm that finds $r_{ex}$; clearly, $\\ell_{ex}$ can be found in a symmetric way. The algorithm uses two integer\r\nvariables: $r_{ex}$ and $s$.\r\n\r\n\\smallskip\r\n\r\n\\noindent \\textsc{Initialization:} We set $r_{ex}:=0$ and $s:=\\min \\{|S|-r_1,|S|-r_2\\}$.\r\n\r\n\\smallskip\r\n\r\n\\noindent \\textsc{Main loop:} If $s=0$, we stop and return the current value of $r_{ex}$. While $s>0$, we repeat the following. Using\r\n\\textbf{SubCut}, we construct the SLPs $\\subslp{S}{r_1+ r_{ex}}{r_1 + r_{ex} + s}$ and $\\subslp{S}{r_2+r_{ex}}{r_2 + r_{ex} + s}$ and\r\ninvoke \\textbf{PM} with these SLPs as input. If the output is not empty, then one of the substrings $S\\substr{r_1+ r_{ex}}{r_1 + r_{ex}+s}$\r\nand $S\\substr{r_2+ r_{ex}}{r_2 + r_{ex}+s}$ occurs as in the other one. This means that the two substrings are equal because they are of\r\nthe same length $s$. In this case we update the variables by setting $r_{ex}: = r_{ex} + s$ and $s: = \\min \\{|S| - r_1-r_{ex}, |S| -\r\nr_2-r_{ex},\\lceil \\frac{s}{2} \\rceil\\}$. Otherwise we keep the value of $r_{ex}$ and set $s:=s-\\lceil \\frac{s}{2} \\rceil$.\r\n\r\n\\smallskip\r\n\r\n\\noindent \\textsc{Complexity:} Since the value of $s$ does not exceed $|S|$ at the initialization phase and is at least halved at each\r\nrepetition of the main loop, there are $O(\\log |S|)$ steps. At each step the algorithm invokes \\textbf{SubCut} twice and \\textbf{PM} once.\r\nTotally it needs $O(|\\slp{S}|^3)$ time and $O(|\\slp{S}|^2)$ space for each step. Altogether the presented algorithm solves \\textbf{SubsExt}\r\nusing $O(|\\slp{S}|^3 \\log|S|)$ time and $O(|\\slp{S}|^2)$ space.\r\n\r\n\\smallskip\r\n\r\nUsing \\textbf{SubsExt} we can easily solve the following problem:\r\n\r\n\\problem{Period termination}{an SLP $\\slp{S}$, a positive integer $p$, integers $\\ell,r$ with $0 \\le \\ell < r \\le |S|$ such that\r\n$S\\substr{\\ell}{r}$ is a $p$-periodic substring;}{integers $t_L, t_R$ such that $0\\le t_L\\le\\ell$, $r\\le t_R\\le |S|$ and\r\n$S\\substr{t_L}{t_R}$ is a maximal $p$-periodic substring.}\r\n\r\nWe proceed as follows. First, using \\textbf{SubCut}, we construct an SLP $\\slp{P}$ that derives $S\\substr{\\ell}{\\ell + p}$. Then we let $k$\r\nbe the least odd integer such that $p^k > |S|$; clearly, $k$ is of order $O(\\log|S|)$. In $O(\\log k)$ time we construct an SLP $\\slp{P}^k$\r\nthat derives the string $S\\substr{\\ell}{\\ell+p}^k$. Finally, let $\\slp{T}=\\slp{S} \\cdot \\slp{P}^k$, $\\ell_1 = \\ell$, $r_1 = r$, $\\ell_2 =\r\n|S| + p\\frac{k-1}{2}$, $r_2 = |S| + p\\frac{k-1}{2} + (r - \\ell)$. The condition that $S\\substr{\\ell}{r}$ is $p$-periodic then ensures that\r\nthe substrings $T\\substr{\\ell_1}{r_1}=S\\substr{\\ell}{r}$ and $T\\substr{\\ell_2}{r_2}$ are equal. Thus, we can apply our algorithm for\r\n\\textbf{SubsExt} to the SLP $\\slp{T}$ with the parameters $\\ell_1,r_1,\\ell_2,r_2$. If $\\ell_{ex}$ and $r_{ex}$ are the output integers for\r\n\\textbf{SubsExt}, we get $t_L=\\ell-\\ell_{ex}$ and $t_R=r+r_{ex}$.\r\n\r\n\\smallskip\r\n\r\n\\noindent \\textsc{Complexity:} The algorithm invokes \\textbf{SubCut} once. Next it spends $\\log k$, that is $O(\\log\\log|S|)$ time to\r\nconstruct the SLP $\\slp{P}^k$. Finally, it invokes \\textbf{SubsExt} once. Altogether this algorithm solves \\textbf{Period termination}\r\nusing $O(|\\slp{S}|^3 \\log|S|)$ time and $O(|\\slp{S}|^2)$ space.\r\n\r\n\\section{The algorithm}\r\n\r\n\\subsection{Basic strategy}\r\n\r\nOur algorithm closely follows the logic of~\\cite{2} where an efficient solution to the problem of finding all squares in a (non-compressed)\r\nstring has been proposed. (Below we reproduce the key lemmas from~\\cite{2} for the reader's convenience.) Our contribution is, roughly\r\nspeaking, twofold. First, we show that the approach from~\\cite{2} can be implemented on a SLP representing a string in time polynomial of\r\nthe size of the SLP. Second, we provide a compressed representation for the set of all squares contained in the string. This compressed\r\nrepresentation is based on grouping the squares according to two integer parameters $i$ and $j$ that are defined as follows.\r\n\r\nLet $\\slp{S}$ be an SLP. Suppose that $xx$ is a square that occurs in the text $S$. It is easy to see there is a unique rule $\\slp{S}_j$\r\nsuch that the square $xx$ occurs in the text $S_j$ and $xx$ touches the cut position of $\\slp{S}_j$. This defines the parameter $j$ whose\r\nrange is therefore the set $\\{0,1,2, \\dots, |\\slp{S}|-1\\}$. The parameter $i$ is defined as the only integer such that\r\n$2^{i-1}\\le|x|<2^{i}$. The range of this parameter is the set $\\{1,2, \\dots, \\lfloor\\log|S|\\rfloor\\}$.\r\n\r\nWe introduce a rectangular $\\lfloor\\log|S|\\rfloor\\times |\\slp{S}|$-table $T(\\slp{S})$ and store a compressed representation of the group of\r\nsquares $xx$ that satisfy $2^{i-1}\\le |x|<2^i$, occur in $S_j$ and touch the cut position of $\\slp{S}_j$ in the cell $T(i,j)$ in the $i$-th\r\nrow and the $j$-th column of this table. Of course, for some $i$ and $j$, squares with the above properties may not exist; in this case we\r\nwrite $\\varnothing$ in the cell $T(i,j)$. Now we are in a position to precisely describe the form of \\textbf{Computing All Squares}\r\n(\\textbf{CAS}) solved by our algorithm.\r\n\r\n\\problem{CAS}{an SLP $\\slp{S}$;}{a $\\lfloor\\log|S|\\rfloor\\times |\\slp{S}|$-table $T(\\slp{S})$ such that for each $i$ and $j$, the cell\r\n$T(i,j)$ of $T(\\slp{S})$ contains either a compressed representation of all squares $xx$ that satisfy $2^{i-1}\\le|x|<2^i$, occur in $S_j$\r\nand touch the cut position of $\\slp{S}_j$ or $\\varnothing$ if no square with the above properties exists.}\r\n\r\nWe have not yet specified what kind of compressed representations is used for non-empty families of squares in cells of $T(\\slp{S})$. In\r\nfact, we use compressed representations of three different forms and the choice of the form depends on several conditions. We will\r\nformulate these conditions and describe the corresponding representations in the course of the explanation of our algorithm.\r\n\r\nThe fact that the output data are structured in a table form may suggest that a sort of dynamic programming is employed to fill out the\r\ncells of $T(\\slp{S})$, that is, the content of $T(i,j)$ is somehow determined by the contents of the cells $T(i',j')$ where $i'<i$ and/or\r\n$j'<j$. It is not the case, and our algorithms fills out each cell of $T(\\slp{S})$ independently of the contents of other cells. On the one\r\nhand, this can be seen as a disadvantage as quite similar calculations are to be repeated many times; on the other hand, this opens\r\nprospects for efficient parallelization.\r\n\r\n\\subsection{Local search tactic}\r\n\r\nNow we assume that an index $j$ and a positive integer $i$ are fixed and explain how we search for squares $xx$ to be represented in the\r\ncell $T(i,j)$. We may additionally assume that $i>1$. Indeed, if $i=1$, then the inequalities $2^{i-1}\\le|x|<2^i$ imply that $|x|=1$, that\r\nis, $x$ is a letter from $\\Sigma$. To locate squares of the form $aa$ where $a\\in\\Sigma$ in $S_j$, we can just invoke \\textbf{PM} for the\r\nSLP $\\slp{S}_j$ and the SLP $\\slp{A}_0:=a,\\ \\slp{A}_1:=\\slp{A}_0\\cdot\\slp{A}_0$, for each $a$. We then store the output of \\textbf{PM}\r\n(that is, $O(|\\slp{S}_j|)$ arithmetic progressions or $\\varnothing$) in the cell $T(i,j)$.\r\n\r\nThus, let $i>1$. If the length $|S_j|$ of text $S_j$ is less than $2^i$, no square $xx$ such that $2^{i-1}\\le|x|<2^i$ cannot occur in $S_j$\r\nand we put $\\varnothing$ the cell $T(i,j)$. Therefore we assume that $|S_j|\\ge 2^i$. Let $\\gamma$ be the cut position of $\\slp{S}_j$.\r\nConsider the $2^{i+1}$-neighborhood of $\\gamma$ in $S_j$, that is, the substring $S_j\\substr{\\gamma-2^{i+1}}{\\gamma+2^{i+1}}$. (Of course,\r\nit may happen that $\\gamma-2^{i+1}<0$ or $\\gamma+2^{i+1}>|S_j|$; in such a case, the borders of the neighborhood are correspondingly\r\nadjusted.) We divide the neighborhood into blocks of length $d=2^{i-2}$ starting from $\\gamma$ in both directions. In the ``regular'' case\r\nwhen the neighborhood has length $2^{i+2}=16d$, it gets divided into 16 blocks of equal length which we enumerate from left to right and\r\ndenote by $B_1,\\dots,B_{16}$. In particular, the blocks that touch $\\gamma$ are $B_8$ (on the left) and $B_9$ (on the right). In the\r\ngeneral case, the neighborhood may be shorter so that we may get less than 16 blocks and/or the leftmost and the rightmost blocks may have\r\nlength less than $d$. To simplify notation, we still consider 16 blocks $B_1,\\dots,B_{16}$ but allow some blocks to be empty and the\r\nextreme non-empty blocks to be of length less than $d$.\r\n\r\nConsider now a square $xx$ with $2^{i-1}\\le|x|<2^i$ that occurs in $S_j$ and touches $\\gamma$. Then for some position $c$ (referred to as\r\nthe \\emph{center} of $xx$), we can write $xx=S_j\\substr{c-|x|}{c+|x|}$ and $c-|x|\\le\\gamma\\le c+|x|$. Combining the latter inequalities\r\nwith the inequality $|x|<2^i$, we obtain\r\n$$\\gamma-4d=\\gamma-2^{i}<\\gamma-|x|\\le c\\le\\gamma+|x|<\\gamma+2^{i}=\\gamma+4d.$$\r\nThis means that if a block touches the center $c$ of $xx$, the block is one of the 8 central blocks $B_{4}, B_{5}, \\dots, B_{12}$. At most\r\ntwo blocks touch $c$; let $B_k$, where $k\\in\\{4,5,\\dots,12\\}$, be the leftmost of these blocks. We can write this block as\r\n$B_k=S_j[\\ell\\dots r]$ for some $\\ell$ and $r$ with $r-\\ell=d$. (It is easy to express $\\ell$ and $r$ via $\\gamma$, $k$, and $i$ but we do\r\nnot need to explicitly write down the corresponding expressions.) Then $\\ell<c\\le r$ and the block $B_{k-1}=S_j[\\ell-d\\dots\\ell]$ occurs as\r\na substring in $x=S_j\\substr{c-|x|}{c}$ since\r\n$$c-|x|\\le c-2^{i-1}\\le r-2^{i-1}=\\ell+d-2d=\\ell-d.$$\r\nThe string $x$ repeats in $S_j$ as $x=S_j\\substr{c}{c+|x|}$ whence a copy of the block $B_{k-1}$ should also occur as a substring in\r\n$S_j\\substr{c}{c+|x|}$; more precisely, $B_{k-1}$ is equal to the substring $S_j[\\ell-d+|x|\\dots\\ell+|x|]$ because the latter substring is\r\njust the right translate  by $|x|$ positions of the substring $S_j[\\ell-d\\dots\\ell]$. Observe that the inequalities $2^{i-1}\\le|x|<2^i$\r\nimply that\r\n$$\\ell-d+|x|\\ge\\ell-d+2d=\\ell+d=r\\ \\text{ and }\\ \\ell+|x|<\\ell+2^i=\\ell+4=r+3d.$$\r\nThis means that the start position of the substring $S_j[\\ell-d+|x|\\dots\\ell+|x|]$ occurs to the right of or coincides with the start\r\nposition of the block $B_{k+1}=S_j[r\\dots r+d]$ while the end position of $S_j[\\ell-d+|x|\\dots\\ell+|x|]$ occurs to the left of the end\r\nposition the block $B_{k+3}=S_j[r+2d\\dots r+3d]$. We conclude that a copy of the block $B_{k-1}$ should occur in the concatenation\r\n$B_{k+1}\\cdot B_{k+2}\\cdot B_{k+3}$, see Figure~\\ref{localsearch}.\r\n\\begin{figure}[htb]\r\n    \\begin{center}\r\n        \\begin{picture}(30,35)(120,10)\r\n            \\LocalSearch\r\n        \\end{picture}\r\n    \\end{center}\r\n    \\caption{A copy of $B_{k-1}$ in $B_{k+1}\\cdot B_{k+2}\\cdot B_{k+3}$}\r\n    \\label{localsearch}\r\n\\end{figure}\r\nLet us register this conclusion in the following statement.\r\n\r\n\\begin{lem}\r\n\\label{lem:search} Suppose that for $i>1$ and $j$, a square $xx$ with $2^{i-1}\\le|x|<2^i$ occurs in the text $S_j$ and touches the cut\r\nposition $\\gamma$ of the rule $\\slp{S}_j$. If the $2^{i+1}$-neighborhood of $\\gamma$ in $S_j$ is divided into blocks $B_1,\\dots,B_{16}$ as\r\ndescribed above, then there exists $k\\in\\{4,5,\\dots,12\\}$ such that the block $B_{k-1}$ occurs as a substring in the concatenation\r\n$B_{k+1}\\cdot B_{k+2}\\cdot B_{k+3}$.\r\n\\end{lem}\r\n\r\nIt is Lemma~\\ref{lem:search} that underlies the tactic of our algorithm. We proceed as follows. For each $k\\in\\{4,5,\\dots,12\\}$, we invoke\r\n\\textbf{SubCut} to extract from the SLP $\\slp{S}_j$ an SLP $\\slp{B}$ that derives the block $B_{k-1}$ and an SLP $\\slp{C}$ that derives the\r\nconcatenation $B_{k+1}\\cdot B_{k+2}\\cdot B_{k+3}$. Then we run \\textbf{PM} on the SLPs $\\slp{B}$ and $\\slp{C}$. If \\textbf{PM} returns the\r\nempty set, Lemma~\\ref{lem:search} ensures that no square $xx$ satisfying its conditions and having the center within the block $B_k$ may\r\nexist. Then we update the value of $k$ and proceed with the next block in the role of $B_{k-1}$. Otherwise \\textbf{PM} returns a bunch of\r\narithmetic progressions that describe the start positions of all occurrences of $B_{k-1}$ in $B_{k+1}\\cdot B_{k+2}\\cdot B_{k+3}$. Observe\r\nthat since the length of $B_{k+1}\\cdot B_{k+2}\\cdot B_{k+3}$ does not exceed $3|B_{k-1}|$, Lemma~\\ref{lem:blocks} implies that the start\r\npositions can be grouped into at most six progressions (see the argument at the end of Subsection~\\ref{subsec:pm}). Now for each of these\r\nprogressions, we check (using \\textbf{Period termination}) whether or not the block $B_{k-1}$ and its occurrences in $B_{k+1}\\cdot\r\nB_{k+2}\\cdot B_{k+3}$ corresponding to the chosen progression can be extended to a square.\r\n\r\n\\subsection{Checking square-freeness}\r\n\r\n\\noindent \\textsc{Algorithm:} For every block $B_{k-1}$ the algorithm invokes \\textbf{SubCut} two times with parameters\r\n$B_{k-1}$ and $B_{k+1}\\cdot B_{k+2} \\cdot B_{k+3}$. Next the algorithm invokes \\textbf{PM} with parameters $\\slp{B}_{k-1}$. From\r\nLemma~\\ref{lem:blocks} it follows that the occurrences can be represented using at most six arithmetic\r\nprogressions. So the algorithm compress the occurrences into six arithmetic progressions. Next it verifies whether on\r\nnot the block $B_{k-1}$ and a progression $\\prog{a}{p}{t}$ of its occurrences form any square. Let us consider the\r\nfollowing cases:\r\n\r\n\\begin{itemize}\r\n\\item If $t = 0$ then there are no squares of expected length that touch $\\gamma$ and fully contain $B_{k-1}$. The\r\nalgorithm moves to the next block;\r\n\r\n\\item If $t = 1$ then the algorithm obtains $\\ell_{ex}$, $r_{ex}$ using \\textbf{SubsExt} for $B_{k-1}$ and $S_j[a\\dots\r\na + 2^{i-2}]$. If $\\ell_{ex} + r_{ex} > a - (k-1)\\cdot 2^{i-2}$ then there exists at least one square and the algorithm\r\nreturns $\\bf{false}$. Otherwise there are no squares of expected length that touch $\\gamma$ and fully contain\r\n$B_{k-1}$. The algorithm moves to the next block;\r\n\r\n\\item If $t \\geq 2$ there exists at least one square. The algorithm returns $\\bf{false}$.\r\n\\end{itemize}\r\n\r\n\\noindent \\textsc{Complexity:} For each of the eight central blocks the algorithm invokes \\textbf{SubCut} two times,\r\n\\textbf{PM} at once and \\textbf{SubsExt} at most six times. So the main step required $O(|\\slp{S}|^3 \\cdot \\log |S|)$ time\r\nand $O(|\\slp{S}|^2)$ space. The algorithm contains at most $|\\slp{S}| \\cdot \\log |S|$ steps. Altogether we get the following theorem:\r\n\r\n\\begin{thm}\r\nThere is an algorithm that solves square-freeness problem using $O(|\\slp{S}|^4\\cdot \\log^2{|S|})$ time and\r\n$O(|\\slp{S}|^2)$ space.\r\n\\end{thm}\r\n\r\n\\subsection{Computing all squares algorithm} In this section we present an algorithm that fills out a table $T(\\slp{S})$. Remind the main problem:\r\n\r\n\\problem{Computing all squares}{an SLP $\\slp{S}$ that derives a text $S$;}{a table $T(\\slp{S}$).}\r\n\r\n\\noindent \\textsc{Algorithm:} It remains to recognize all squares between a block $B_k$ and the\r\narithmetic progression $\\prog{a}{p}{t}$ of its occurrences. Since $t$ can be exponentially large relative to\r\n$|\\slp{S}|$ there is no polynomial algorithm that can consecutively check every occurrence of $B_k$.\r\n\r\nLet $\\alpha_L, \\alpha_R$ be output of a call of \\textbf{Period termination} with the following parameters: $\\slp{S}_j, p,\r\n(k-1)\\cdot2^{i-2}, k\\cdot 2^{i-2} -1$. $\\alpha_L, \\alpha_R$ called \\emph{defined} if they satisfies the\r\nfollowing inequalities: $(2k-1)\\cdot2^{i-2} - (a + p\\cdot t) \\leq \\alpha_L$, $\\alpha_R < a + 2^{i-2}$.\r\nOtherwise they are called \\emph{undefined}. Since $2^{i} - 1$ is the greatest length of a root, start\r\npositions of squares can not be further right than $(2k-1)\\cdot2^{i-2} - (a + p\\cdot t)$. In other words it does\r\nnot matter where the $p$-periodicity terminates outside. Analogously let $\\gamma_L, \\gamma_R$ be output of a call of\r\n\\textbf{Period termination} with the following parameters: $\\slp{S}_j, p, a, a + p\\cdot t$. $\\gamma_L, \\gamma_R$  called\r\n\\emph{defined} if they satisfies the following inequalities: $(k-1)2^{i-2} \\leq \\gamma_L$ and $\\gamma_R < 2(a + p\\cdot\r\nt) - (k-1)2^{i-2}$. Otherwise they are called \\emph{undefined}.\r\n\r\nThe following lemmas present useful relations between $\\alpha_L, \\alpha_R, \\gamma_L$ and $\\gamma_R$.\r\n\r\n\\begin{lem}[{\\rm\\cite{2}}]\r\nIf one of $\\alpha_R$ or $\\gamma_L$ is defined, then the other one is defined, and $\\alpha_R - \\gamma_L \\leq p$.\r\n\\end{lem}\r\n\r\n\\begin{lem}[{\\rm\\cite{2}}]\r\nIf both $\\alpha_R$ and $\\gamma_L$ are undefined, then none of the squares possible containing $B_k$ are pure\r\nsquares.\r\n\\end{lem}\r\n\r\nThere are two main cases:\r\n\r\n\\noindent \\textbf{Case 1: both {\\boldmath $\\alpha_R$} and {\\boldmath $\\gamma_L$} are defined.} Let us consider\r\npossible relative positions of $\\alpha_R$ and $\\gamma_L$:\r\n\\begin{itemize}\r\n\\item If $\\alpha_R \\geq \\gamma_L$ then centers of squares may be located at $[k \\cdot 2^{i-2}, \\gamma_L]$, $(\\gamma_L, \\alpha_R]$,\r\n$(\\alpha_R, (k+1)\\cdot2^{i-2})$.\r\n\r\n\\item If $\\alpha_R < \\gamma_L$ then centers of squares may be located at $[k \\cdot 2^{i-2}, \\alpha_R]$, $(\\alpha_R, \\gamma_L]$,\r\n$(\\gamma_L, (k+1)\\cdot2^{i-2})$;\r\n\\end{itemize}\r\n\r\n\\begin{lem}[{\\rm\\cite{2}}]\r\nIf both $\\alpha_R, \\gamma_L$ are defined then:\r\n\r\n\\begin{enumerate}\r\n\\item Squares that are contain $B_k$ and centered at positions $h$, such that $h \\leq \\gamma_L$, may exist only if\r\n$\\alpha_L$ is defined. These squares constitute a family of squares that corresponds to the difference\r\n$|x| = a + t'\\cdot p - (k-1)2^{i-2}$, provided that there exists some $t' \\in \\{0\\dots t\\}$ such that\r\n$\\gamma_L - \\alpha_L = a + t'\\cdot p - (k-1)2^{i-2}$.\r\n\\item Squares that are contain $B_k$ and centered at positions $h$, such that $\\alpha_R < h$, may exist only if\r\n$\\gamma_R$ is defined. These squares constitute a family of squares that corresponds to the difference\r\n$|x| = a + t''\\cdot p - (k-1)2^{i-2}$, provided that there exists some $t'' \\in \\{0\\dots t\\}$ such that\r\n$\\gamma_L - \\alpha_L = a + t''\\cdot p - (k-1)2^{i-2}$.\r\n\\end{enumerate}\r\nNotice that if $\\alpha_R < \\gamma_L$, then squares whose center $h$ satisfies $\\alpha_R < h \\leq\\gamma_L$ may\r\nexist only if both $\\alpha_L$ and $\\gamma_R$ are defined and $\\gamma_R - \\alpha_R = \\gamma_L - \\alpha_L$.\r\n\\label{lem:simple_squares}\r\n\\end{lem}\r\n\r\nUsing Lemma~\\ref{lem:simple_squares} the algorithm finds simple families of squares and stores them in the following compressed way:\r\n$\\{|x|, c_l, c_r\\}$ where $|x|$ is length of the root, $c_l$ is the center of the leftmost square, $c_r$\r\nis the center of the rightmost square. \r\n\r\nIn the case $\\alpha_R < \\gamma_L$ the algorithm additionally calls \\textbf{SubsExt} to guarantee that every family consists of squares. \r\nLet $\\ell_{ex}, r_{ex}$ be output of a call \\textbf{SubsExt} with the following parameters: \r\n$\\slp{S}_j, \\alpha_L, \\alpha_R, \\gamma_L, \\gamma_R$. If $\\alpha_R + r_{ex} < \\gamma_L - \\ell_{ex}$ then there are no families of squares. \r\nOtherwise the algorithm intersects sets of centers obtained using Lemma~\\ref{lem:simple_squares} with $[\\gamma_L - \\ell_{ex}, \\alpha_R + r_{ex}]$.\r\n\r\nIf $\\alpha_R \\leq \\gamma_L$ then the algorithm may find at most three simple families of\r\nsquares: $\\{\\gamma_L - \\alpha_L, \\max \\{k \\cdot 2^{i-2}, \\gamma_L - \\ell_{ex}\\}, \\alpha_R\\}, \\{\\gamma_R - \\alpha_R, \r\n\\min \\{\\alpha_R + 1, \\gamma_L - \\ell_{ex}\\}, \\max \\{\\gamma_L, \\alpha_R + r_{ex}\\}\\},\r\n\\{\\gamma_R - \\alpha_R,  \\gamma_L + 1, \\min\\{a, \\alpha_R + r_{ex}, (k+1) \\cdot 2^{i-2} - 1\\}\\}$. Otherwise there are no simple families of squares. \r\nConsider the following case $\\alpha_R > \\gamma_L$, $|x| = \\gamma_L - \\alpha_L$. For an arbitrary but fixed $c \\leq \\gamma_L$ we have \r\n$S\\substr{\\alpha_L + 1}{\\alpha_R -1}$ should be equal to $S\\substr{\\gamma_L + 1}{c + \\gamma_L - \\alpha_L -1}$. But \r\n$S\\substr{\\alpha_L + 1}{\\alpha_R -1}$ is $p$-periodic substring and $S\\substr{\\gamma_L + 1}{c + \\gamma_L - \\alpha_L -1}$ is not $p$-periodic\r\nsubstring since it contains $\\alpha_R$ position. Notice that every simple family of squares is unique and can not be obtained at another \r\nsteps of the algorithm.\r\n\r\nFor example, let $S_j$ be equal to $c^4 \\cdot (ab)^5 \\cdot c^4 \\cdot (ab)^5 \\cdot c^4$ and the algorithm processes $B_7 = cc$. It finds all \r\noccurrences of $B_6 = ab$ in $B_8 \\cdot B_9 \\cdot B_{10} = ccabab$ that form the single arithmetic progression $\\prog{a}{p}{t} = \\prog{18}{2}{2}$. \r\nNext the algorithm calculates $\\alpha_L = 4, \\alpha_R = 14, \\gamma_L = 18$ and $\\gamma_R = 28$. Since $\\gamma_R < \\gamma_L$ it calculates \r\n$\\ell_{ex} = 4$ and $r_{ex} = 4$. Since the algorithm looks for squares that centered at $B_7$ it finds the single family of squares: $\\{12, 14, 15\\}$.\r\nIn other words it finds two squares of length 12 $c^2 \\cdot (ab)^5 \\cdot c^2 \\cdot c^2 \\cdot (ab)^5 \\cdot c^2$ and \r\n$c \\cdot (ab)^5 \\cdot c^3 \\cdot c \\cdot (ab)^5 \\cdot c^3$ that centered at positions 14 and 15 correspondingly.\r\n\r\n\\begin{lem}[{\\rm\\cite{2}}]\r\nIf $\\alpha_R, \\gamma_L$ are defined and $\\gamma_L < \\alpha_R$, then there might be a family of squares\r\nassociated with each of the differences $|x| = a + p\\cdot t' - (k-1)\\cdot 2^{i-2}$ where $t' \\in \\{0\\dots t\\}$,\r\nwith centers at positions $h$, such that $\\gamma_L < h \\leq \\alpha_R$. The squares in each such family are all\r\npure squares, and they are centered at positions $h$, such that $\\max(\\alpha_L + |x|, \\gamma_L) < h \\leq\r\n\\min(\\alpha_R, \\gamma_R-|x|)$. Notice that such a family is not empty only if $|x| < \\min(\\alpha_R-\\alpha_L,\r\n\\gamma_R-\\gamma_L)$.\r\n\\label{lem:dynamic_pure_squares}\r\n\\end{lem}\r\n\r\nUsing Lemma~\\ref{lem:dynamic_pure_squares} the algorithm finds at most one dynamic family of pure squares and stores\r\nit in the following compressed way: $\\{k, \\prog{a}{p}{t}, \\alpha_L, \\alpha_R, \\gamma_L, \\gamma_R\\}$. Notice that every \r\ndynamic family of pure squares is unique and can not be obtained at another steps of the algorithm.\r\n\r\nFor example, let $S_j$ be equal to $c^{12} \\cdot (abba)^4 \\cdot (bbaa)^3 \\cdot bba \\cdot c^{21}$ and the algorithm processes $B_7 = abba$.\r\nIt finds all occurrences of $B_6 = abba$ in $B_8 \\cdot B_9 \\cdot B_{10} = (bbaa)^3$ that form the single arithmetic progression $\\prog{a}{p}{t} = \\prog{30}{4}{3}$. \r\nNext the algorithm calculates $\\alpha_L = 12, \\alpha_R = 28, \\gamma_L = 27$ and $\\gamma_R = 43$. It finds the dynamic family of pure squares \r\n$\\{6, \\prog{30}{4}{3}, 12, 28, 27, 43\\}$ that represents single pure squares centered at position 27: $(abba)^3 abb \\cdot (abba)^3 abb$ of length 30.\r\nNotice that the pure square $(abba)^2 \\cdot abb \\cdot (abba)^2 \\cdot abb$ of length 22 centered at position 27 was rejected since in this case \r\nwe are looking for squares with $16 \\leq |x| \\leq 31$. \r\n\r\n\\noindent \\textbf{Case 2: both {\\boldmath $\\alpha_R$} and {\\boldmath $\\gamma_L$} are undefined.} So\r\n$S\\substr{\\alpha_L}{\\gamma_R}$ is $p$-periodic string and it contains squares with float centers and float lengths of\r\nroots. The algorithm gather all squares into the single dynamic family of squares that stored in the following compressed way: $\\{k, p, \\alpha_L, \\gamma_R\\}$.\r\nNotice that every dynamic family of squares is not unique and may contains squares of unexpected length. Hence the algorithm may obtain a similar family\r\nat another step and we should cleanup the $T(\\slp{S})$ table after the algorithm fills it out.\r\n\r\n\\noindent \\textsc{Complexity:} Let us estimate the upper bound of the main step of the algorithm. For each of the\r\neight central blocks the algorithm calculates at most six arithmetic progressions that describes all occurrences of the block.\r\nSo the algorithm invokes \\textbf{SubCut} at most 16 times and \\textbf{PM} at most 8 times. For each central block and each arithmetic progression\r\nthe algorithm calculates $\\alpha_L, \\alpha_R, \\gamma_L$ and $\\gamma_R$ positions and at most one time extends $S\\substr{\\alpha_L}{\\alpha_R}$ \r\nand $S\\substr{\\gamma_L}{\\gamma_R}$. So the algorithm invokes \\textbf{Period termination} and \\textbf{SubsExt} at most 64 times. \r\nAfter that it extracts families of squares and add them to $T(\\slp{S})$ using constant time.\r\nIf $T(\\slp{S})$ contains an adding family in a current cell (or in a current column for dynamic families of squares) then the algorithm skips the family.\r\nTotally the main step required $O(|\\slp{S}|^3 \\cdot \\log |S|)$ time and $O(|\\slp{S}|^2)$ space. The algorithm has $|\\slp{S}| \\cdot \\log |S|$ steps.\r\nAltogether we get the following theorem:\r\n\r\n\\begin{thm}\r\nThere is an algorithm that solves Computing all squares problem using $O(|\\slp{S}|^4 \\cdot \\log^2{|S|})$ time and\r\n$O(|\\slp{S}| \\cdot \\max(|\\slp{S}|, \\log{|S|}))$ space.\r\n\\end{thm}\r\n\r\n\\subsection{Squares table performance capabilities}\r\n\r\nRemind that a $T(\\slp{S})$ table is a rectangular table that stores at most constant number of families of squares in each cell. There are four types of \r\nfamilies of squares:\r\n\r\n\\begin{itemize}\r\n  \\item An empty family that stored as $\\emptyset$;\r\n  \\item A simple family of squares that stored as $\\{|x|, c_\\ell, c_r \\}$;\r\n  \\item A dynamic family of pure squares that stored as $\\{k, \\prog{a}{p}{t}, \\alpha_L, \\alpha_R, \\gamma_L, \\gamma_R\\}$;\r\n  \\item A dynamic family of squares that stored as $\\{k, p, \\alpha_L, \\gamma_R\\}$;\r\n\\end{itemize}\r\n\r\nThe structure of both types of dynamic families is nontrivial. This fact restricts a number of problems that are solvable by usage of $T(\\slp{S})$. \r\nIn the same time there are common properties supported by all dynamic families: \\emph{total} (total number of squares that contains in the family), \r\n\\emph{reduction by length of root} (for a fixed value of $|x|$ reduce a dynamic family to an array of simple families), \\emph{reduction\r\nby position} (for a fixed position $\\ell$ of $S$ returns range of roots of squares that start from $\\ell$ and contain\r\nin the family). Using this properties it is easy to solve the following problems:\r\n\r\n\\begin{itemize}\r\n  \\item to find information about all squares of fixed length;\r\n  \\item to compute total number of squares that are contained in $S$;\r\n  \\item to find information about all squares that starts from a fixed position~$i$;\r\n  \\item to find a maximal by length square that occurs in $S$;\r\n  \\item to check whether on not a text $S$ is square-free;\r\n\\end{itemize}\r\n\r\nIn the same time it is hard to solve the following problems:\r\n\r\n\\begin{itemize}\r\n  \\item for a given SLPs $\\slp{S}$ and $\\slp{P}$ such that $\\slp{P}$ derives a square $xx$ whether or not $xx$ occurs in\r\n  the text $S$ (it is easy to run the pattern matching algorithm than use information from $T(\\slp{S})$);\r\n  \\item for a given $\\slp{S}$ that derives a text $S$ to construct an SLP that derives all squares that occur in $S$\r\n  (we belief that this problem is NP-hard);\r\n\\end{itemize}\r\n\r\nThe last two problems shows us that $T(\\slp{S})$ accumulates quantitative information about squares rather than information\r\nappropriate for searching for some fixed squares. It is common restrictions of an algorithms over SLPs that gather some\r\ninformation about all objects of the specified type. We have the similar situation with \\textbf{Computing all\r\npalindromes} problem~\\cite{16}.\r\n\r\nIt remains to show how to implement the interface of a dynamic family for both types of families. Consider an implementation of\r\nthe interface for a dynamic family of pure squares.\r\n\r\n\\begin{itemize}\r\n  \\item \\emph{total} Since $\\alpha_R - \\gamma_L < p$ there is at most one $t_{c} \\in \\{0 \\dots t\\}$ such that $\\alpha_L\r\n  + |x_c| > \\gamma_L$ or/and $\\alpha_R \\geq \\gamma_R-|x_c|$ where $|x_c| = a + p\\cdot t_c - (k-1)\\cdot 2^{i-2}$. If\r\n  there is no such $t_c$ then the implementation returns $t \\cdot (\\alpha_R - \\gamma_L)$. Otherwise it computes value of\r\n  $|x_c|$ that corresponds to $t_c$ and returns $(t_c - 1) \\cdot (\\alpha_R - \\gamma_L) + (\\min(\\alpha_R, \\gamma_R-|x_c|)\r\n  - \\max(\\alpha_L + |x|, \\gamma_L))$. If the length of a root is equal to $a + p\\cdot (t_c + 1) - (k-1)\\cdot\r\n  2^{i-2}$ then the family contains no squares.\r\n  \\item \\emph{reduction by length of root} For a fixed length of a root $|x|$ the implementation returns the following family:\r\n  $\\{|x|, p, \\max(\\alpha_L + |x|, \\gamma_L)$, $\\min(\\alpha_R, \\gamma_R-|x_c|)\\}$.\r\n  \\item \\emph{reduction by position} Since $\\alpha_R - \\gamma_L < p$ there is at most one square that belong to the\r\n  family and starts from $\\ell$. The implementation returns \\emptyset or the length of the root of the square.\r\n\\end{itemize}\r\n\r\nConsider an implementation of the interface for a dynamic family of squares. Let $\\{k, p, \\alpha_L, \\gamma_R\\}$ be a a dynamic\r\nfamily of squares. For a particular position $c$ we can represent $S\\substr{\\alpha_L}{\\alpha_R}$ as $S\\substr{x}{c+p} \\cdot\r\nS\\substr{c}{c+p}^d \\cdot S\\substr{c}{y}$. What kind of squares from the family centered at $c$? There are the following squares:\r\n$S\\substr{c}{c+p}^4, S\\substr{c}{c+p}^6 \\dots, S\\substr{c}{c+p}^{2 \\cdot \\lfloor \\frac{d}{2}\\rfloor}$. Also there are squares that are\r\ngenerated by a set of overlaps of $S\\substr{c}{c+p}$. For example, if $S\\substr{c}{c+p} = aba$ then the set of overlaps is equal to $\\{a,\r\naba\\}$ and it generates the following squares: $\\{aa, abaaba\\}$. Notice that all squares generated by overlaps of $S\\substr{c}{c+p}$ are\r\npure squares and out of our interest at this moment. Suppose that there is another square $xx$ that centered at $c$. Hence it has the\r\nfollowing structure: $u \\cdot S\\substr{c}{c+p}^{t_\\ell} \\cdot S\\substr{c}{c+p}^{t_r} \\cdot v$, where $u$ and $v$ are suffix/prefix of\r\n$S\\substr{c}{c+p}$ correspondingly and $c = |u| + t_\\ell \\cdot p$. Obviously $|x|$ is the period of $u \\cdot S\\substr{c}{c+p}^{t_\\ell}\r\n\\cdot S\\substr{c}{c+p}^{t_r} \\cdot v$. Since $p$ is minimal period by Fine-Wilf's theorem \\cite{20}  we get that $LCD(|x|, p) = p$.  If\r\n$|u| + |v| \\neq p$ then we get the contradiction since $p | |x|$. If $|u| + |v| = p, |u| \\neq |v|$ then $xx$ is not centered at $c$.\r\nOtherwise we get the contradiction with the condition that $p$ is minimal.\r\n\r\nNow we know all about structure of squares from the family that are centered at a particular position. But we get the following problem:\r\nhow to aggregate information about squares since the family may contains exponentially many positions? The intuition behind this problem is simple:\r\nthere are constant number of restrictions: the borders $\\alpha_L, \\gamma_R$ and the cut position $\\gamma$, this restrictions generates a constant\r\nnumber of segments with predictable growth of squares (a particular number of segments depends on relative position of $\\alpha_L, \\gamma_R, \\gamma$).\r\nFor each segment we can calculate the required property.\r\n\r\nLet us show how to compute the count property. The positions $\\alpha_L, \\gamma_R$ affect on maximal valid length of square and position $\\gamma$\r\naffects on minimal valid length of square. The main idea is to calculate all squares in the family excluding condition of touching $\\gamma$ and\r\ncalculate all squares than does not touch $\\gamma$.\r\n\r\nThe leftmost square centered at position $\\alpha_L + 2p$ and its length equals to $p^4$. Analogously the rightmost square centered at position\r\n$\\gamma_R - 2p$ and its length equals to $p^4$. There is a single square of length $p^4$ centered at each position from $\\alpha_L + 2p, \\dots, \\alpha_L + 3p - 1$.\r\nSymmetrically is a single square of length $p^4$ centered at each position from $\\gamma_R - 2p, \\dots, \\gamma_R - 3p + 1$. There are two squares of\r\nlength $p^4$ and $p^6$ centered at each position from $\\alpha_L + 3p, \\dots, \\alpha_L + 4p - 1$. Symmetrically are two squares of length $p^4$ and $p^6$\r\ncentered at each position from $\\gamma_R - 3p, \\dots, \\gamma_R - 4p + 1$ and so on. Totally there are $\\lfloor \\frac{\\gamma_R - \\alpha_L}{2p} \\rfloor - 2$\r\nsuch steps and there are $2p \\cdot \\sum_{i=1}^{\\lfloor \\frac{\\gamma_R - \\alpha_L}{2p} \\rfloor - 2} i$ squares centered at presented positions.\r\nAlso there is a top step that contains $\\gamma_R - \\alpha_L - \\lfloor \\frac{\\gamma_R -\\alpha_L}{p}\\rfloor \\cdot p$ positions with\r\n$\\lfloor \\frac{\\gamma_R -\\alpha_L}{2p}\\rfloor - 1$ squares centered at each position. So we count all squares in the family excluding condition of touching $\\gamma$.\r\n\r\nAll squares from the family centered at positions $\\gamma - 2p, \\dots, \\gamma + 2p$ touch $\\gamma$. At each position from $\\gamma - 2p - 1, \\dots, \\gamma - 3p$\r\nand $\\gamma + 2p + 1, \\dots, \\gamma + 3p$ there is a single square of length $p^4$ that does not touches $\\gamma$. At each position from\r\n$\\gamma - 3p - 1, \\dots, \\gamma - 4p$ and $\\gamma + 3p + 1, \\dots, \\gamma + 4p$ there are two squares of length $p^4$ and $p^6$ that\r\ndoes not touch $\\gamma$ and so on. Totally we have the following sum: $p \\cdot \\sum_{i=1}^{\\lfloor \\frac{\\gamma - \\alpha_L}{p} - 4 \\rfloor} i +\r\n(\\gamma - \\alpha_L - \\lfloor \\frac{\\gamma - \\alpha_L}{p} \\rfloor p )(\\lfloor \\frac{\\gamma - \\alpha_L}{p} \\rfloor - 3) +\r\np \\sum_{i = 1}^{\\lfloor \\frac{\\gamma_R - \\gamma}{p} - 4 \\rfloor} i + (\\gamma_R - \\gamma - \\lfloor \\frac{\\gamma_R - \\gamma}{p} \\rfloor p )\r\n(\\lfloor \\frac{\\gamma_R - \\gamma}{p} \\rfloor - 3)$.\r\n\r\nBut there may exist positions greater than $\\alpha_L + 2p$ and less than $\\gamma_R - 2p$ such that\r\nthere are no squares that belongs to the family and touches $\\gamma$. Let $s_{\\ell}$ be the rightmost position less than $\\gamma$ and\r\n$s_r$ be the leftmost position greater than $\\gamma$. Formally $s_\\ell = \\alpha_L + \\lceil \\frac{\\gamma - \\alpha_L}{2} \\rceil$ and\r\n$s_r = \\gamma + \\lceil \\frac{\\gamma_R - \\gamma}{2} \\rceil$. Finally we should reduce our sums by positions $s_\\ell$ and $s_r$.\r\n\r\nFor example, let $\\slp{S}$ be an SLP that derives $(aba)^{15}ab$ and $\\gamma = 16$. By the formulas above we get $s_\\ell = 0 + \\lceil \\frac{16 - 0}{2} \\rceil = 8$\r\nand $s_r = 16 + \\lceil \\frac{47 -16}{2} \\rceil = 32$.\r\n\r\nLet us compute all squares that occur at $S$ and centered at $s_\\ell, \\dots, s_r$. $S$ has the following distributions of squares:\r\nthe first two $p$-blocks from the left and from the right located at positions $0, \\dots, 5$ and $42, \\dots, 47$ correspondingly contains no searching squares.\r\nNext $S$ has the ``stable'' grows of squares during the following $\\lfloor \\frac{\\gamma_R -\\alpha_L}{2p}\\rfloor - 2 = \\lfloor \\frac{47 - 0}{6}\\rfloor - 2 = 5$\r\n$p$-blocks from position $6$. Next $S$ has the top block of length $\\gamma_R - \\alpha_L - \\lfloor \\frac{\\gamma_R -\\alpha_L}{2p}\\rfloor \\cdot 2p + 1 =\r\n47 - \\lfloor \\frac{47 - 0}{3}\\rfloor \\cdot 3 = 47 - 42 = 5$ from position $6 + 5 \\cdot 3 = 21$ with $6$ squares at each position. Next $S$ has the ``stable''\r\nfalls of squares during the following 5 $p$-blocks from position $21 + 6 = 27$. To localize squares in $[s_\\ell, s_r]$ we find $p$-blocks that contains\r\n$s_\\ell$ and $s_r$. $s_\\ell$ is contained at $\\lfloor \\frac{s_\\ell}{p} \\rfloor + 1 = 3$ $p$-block from the left. $s_r$ is contained at\r\n$\\lfloor \\frac{\\gamma_R - s_r}{p} \\rfloor + 1 = 6$ $p$-block from the right. So we get the following sum:\r\n$\\sum_+ = 1 + 3 \\cdot \\sum_{i = 2}^5 + 5 \\cdot 6 + 3 \\cdot \\sum_{i=4}^5 = 91$. In other words there are 91 squares that occur at $S$\r\nand centered at positions $8, \\dots, 32$.\r\n\r\nLet us compute all squares that occur at $S$, centered at $s_\\ell, \\dots, s_r$ and does not touch $\\gamma$. The first squares that does not touch $\\gamma$\r\nappears at positions $\\gamma - 2p - 1 = 8$ and $\\gamma + 2p + 1 = 23$. There are 2 squares of length $p^4$ that centered at $9, \\dots, 8$ and does not touch $\\gamma$.\r\nThere are $3 \\cdot \\sum_{i=1}^3 i = 18$ squares that centered at $23, \\dots 32$ and does not touch $\\gamma$. There are $\\sum_- = 19$ squares that centered\r\nat $s_\\ell, \\dots, s_r$ and does not touch $\\gamma$.\r\n\r\nFinally there are $\\sum = \\sum_+ - \\sum_- = 91 - 19 = 82$ squares in $S$ that touch $\\gamma$.\r\n\r\nThe implementation of the remain properties are similar to the implementation of the \\emph{total} property.\r\n\r\n\\section{Conclusion}\r\n\r\nWe have presented an algorithm that for a given SLP $\\slp{S}$ deriving a text $S$ fills out a table containing\r\ninformation about all squares that occur in $S$ in time $O(|\\slp{S}|^4\\cdot \\log^2{|S|})$ using\r\n$O(|\\slp{S}|\\cdot \\max\\{ |\\slp{S}|, \\log{|S|}\\})$ space. We would like to emphasize some features of the\r\nalgorithm:\r\n\r\n\\begin{itemize}\r\n\\item This algorithm is divided into independent steps in contrast to classical algorithms in this area which\r\nconsecutively accumulate information about required objects. As a result it can be parallelized.\r\n\r\n\\item This algorithm presents a new technique for SLPs processing.\r\n\r\n\\item The algorithm is quite difficult for practical implementation. It is not excluded that constants hidden in the\r\n\"O\" notation are actually very big.\r\n\r\n\\item The present upper bound for the time complexity is rather high and is not matched by any lower bound. The question\r\nwhether the upper bound can be lowered to say, cubic in $|\\mathbb{S}|$ remains open.\r\n\\end{itemize}\r\n\r\nThere is an open problem: is there any better way to compress dynamic families of squares?\r\n\r\n\\bibliography{cas_problem}{}\r\n\\bibliographystyle{plain}\r\n\r\n%TODO: appendix with illustrative examples\r\n\r\n\\end{document}\r\n", "meta": {"hexsha": "9e75679937f2bc808fac078282e029dc42bca7c3", "size": 60383, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "texfiles/Khvorost/cas_problem/cas_problem.tex", "max_stars_repo_name": "jaamal/overclocking", "max_stars_repo_head_hexsha": "b40db5a72710c691ca558e22626c5c382fd3677a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "texfiles/Khvorost/cas_problem/cas_problem.tex", "max_issues_repo_name": "jaamal/overclocking", "max_issues_repo_head_hexsha": "b40db5a72710c691ca558e22626c5c382fd3677a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-04-11T12:58:50.000Z", "max_issues_repo_issues_event_max_datetime": "2015-04-12T10:54:35.000Z", "max_forks_repo_path": "texfiles/Khvorost/cas_problem/cas_problem.tex", "max_forks_repo_name": "jaamal/overclocking", "max_forks_repo_head_hexsha": "b40db5a72710c691ca558e22626c5c382fd3677a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 78.1151358344, "max_line_length": 167, "alphanum_fraction": 0.6968683239, "num_tokens": 19041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.3309510768926352}}
{"text": "\\documentclass{beamer}\n\\usepackage[utf8]{inputenc}\n\\usetheme{Madrid}\n\\usepackage{amssymb}\n\\usepackage{pifont}\n\\usepackage{xcolor}\n\\usepackage{bigints}\n\\usepackage{mathrsfs}\n\\definecolor{mblue}{rgb}{0.18,0.21,0.67}\n\\definecolor{dgreen}{rgb}{0.,0.6,0.}\n\\newcommand{\\cmark}{{\\color{dgreen}\\ding{52}}}%\n\\newcommand{\\xmark}{{\\color{red}\\ding{55}}}%\n\\newcommand{\\bmark}{{\\color{orange}$\\sim$}}%\n\\newcommand{\\arrow}{{{\\color{mblue}\\ding{220}}}}\n\\newcommand{\\mbold}[1]{\\textbf{\\color{mblue}#1}}\n%\\usepackage{marvosym}\n\\usepackage{soul}\n\n\\usepackage{multicol}\n\n\\usepackage{amsmath}\n\\usepackage{cancel}\n\\DeclareMathOperator*{\\argmax}{argmax}\n\\DeclareMathOperator*{\\argmin}{argmin}\n\n% bibliography\n\\usepackage[backend=bibtex, style=authoryear-comp]{biblatex}\n\\usepackage{filecontents}\n%\\newcommand{\\customcite}[1]{\\citeauthor{#1}, \\citetitle{#1}, \\citeyear{#1}}\n\\newcommand{\\customcite}[1]{\\citeauthor{#1} (\\citeyear{#1})}\n\n\\bibliography{refs}\n\n\\beamertemplatenavigationsymbolsempty\n%for backup slides\n\\newcommand{\\backupbegin}{\n   \\newcounter{finalframe}\n   \\setcounter{finalframe}{\\value{framenumber}}\n}\n\\newcommand{\\backupend}{\n   \\setcounter{framenumber}{\\value{finalframe}}\n}\n\n\n\\AtBeginSection[\n  {\\frame<beamer>{\\frametitle{Outline}   \n    \\tableofcontents[currentsection,currentsection]}}%\n]%\n{\n  \\frame<beamer>{ \n    \\frametitle{Outline}   \n    \\tableofcontents[currentsection,currentsection]}\n}\n\n\n\\title[NumKin 2019]{Exponential methods for solving hyperbolic problems with application to kinetic equations}\n%\\subtitle{Optimisation de WENO pour Vlasov-Poisson}\n\\author[J. Massot]{N. Crouseilles \\inst{1,2} \\and L. Einkemmer \\inst{3} \\and \\underline{J. Massot} \\inst{2,1}}\n\\institute[IRMAR]{\\inst{1} Inria Rennes -- Bretagne Atlantique \\and \\inst{2} IRMAR, Université de Rennes \\and \\inst{3} University of Innsbruck}\n\\date{December 10, 2019}\n\n% \\defbeamertemplate*{title page}{customized}[1][]\n% {\n%   \\vfill\n%   {\\usebeamerfont{title}\\inserttitle}\\par\n%   {\\usebeamerfont{subtitle}\\usebeamercolor[bg]{subtitle}\\insertsubtitle}\\par\n%   \\bigskip\n%   \\vfill\n%   \\hfill\\usebeamerfont{author}\\insertauthor\\par\\par\n%   \\hfill\\textcolor{black}{Encadré par~: Anaïs Crestetto\\\\\\hfill et Nicolas Crouseilles}\\par\n%   \\vfill\n%   \\hfill\\usebeamerfont{date}\\insertdate\n% }\n\n\\begin{document}\n\n\\begin{frame}[plain]\n  \\titlepage\n\\end{frame}\n\n\\begin{frame}{Outline}\n  \\tableofcontents\n\\end{frame}\n\n\\section{Motivation for Vlasov-Poisson equations}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\begin{frame}{Vlasov-Poisson equations 1D$\\times$1D}\n  Our model: a non-linear transport in $(x,v)\\in\\Omega\\times\\mathbb{R}$ of an electron density distribution $f=f(t,x,v)$:\n  $$\n    \\begin{cases}\n      \\partial_t f + v\\partial_x f + E\\partial_v f = 0 \\\\\n      \\partial_x E = \\int_{\\mathbb{R}} f\\,\\mathrm{d}v - 1\n    \\end{cases}\n  $$\n\n  \\textbf{\\color{mblue} Motivation:}\n  \\begin{itemize}\n    \\item We want high order methods in $(x,v)$\n    \\item We want high order methods in time $t$:\n      \\begin{itemize}\n        \\item Splitting methods: could have a lot of steps\n        \\item Runge-Kutta methods: stability constraints (CFL condition)\n          \\begin{itemize}\n            \\item The most restrictive CFL condition is associated with the linear part ($\\partial_tf + v\\partial_x f=0$)\n          \\end{itemize}\n      \\end{itemize}\n    \\end{itemize}\n    \\arrow We want to propose a compromise: exponential integrators.\n\\end{frame}\n%-------%\n\\begin{frame}{Vlasov-Poisson equations 1D$\\times$1D}\n  Fourier transform in $x$ direction of Vlasov, amenable to exponential integrators:\n  $$\n    \\partial_t\\hat{f} + ikv\\hat{f} + \\widehat{E\\partial_v f} = 0\n  $$\n  \n  Vlasov is of the form:\n  $$\n    \\dot{u} = iau + F(u)\n  $$\n  Variation of constant: $\\partial_t(e^{-iat}u) = e^{-iat}F(u)$. No more CFL in $x$ of the form $\\Delta t\\leq \\sigma\\frac{\\Delta x}{v_\\text{max}}$ with $[-v_\\text{max},v_\\text{max}]\\equiv\\mathbb{R}$.\n\n  Time integration:\n  $$\n    u(t_n+\\Delta t) = \\exp(ia\\Delta t)u(t_n) + \\int_0^{\\Delta t}\\exp(ia(\\Delta t-s))F(u(t_n+s))\\,\\mathrm{d}s\n  $$\n  with $\\Delta t>0$, $t_n = n\\Delta t$ with $n\\in\\mathbb{N}$\n\n  Linear part is exact! \\cmark\n\\end{frame}\n%-------%\n\\begin{frame}{Idea of exponential integrators}\n  \\textbf{\\color{mblue} 2 classes of methods:}\n  \\begin{description}\n    \\item[\\textbf{exponential Runge-Kutta:}] solve exactly what we can, and interpolate the rest. For example first order exponential Euler method:\n      $$\n        u(t_n+\\Delta t) \\approx u^{n+1} = e^{-ia\\Delta t}u^n + \\Delta t\\varphi_1(ia\\Delta t)F(u^n)\n      $$\n      where $\\varphi_1(z) = \\dfrac{e^z - 1}{z}$\n      \\begin{thebibliography}{9}\n        \\setbeamertemplate{bibliography item}[article]\n        \\bibitem{a} \\customcite{Hochbruck:2010}\n      \\end{thebibliography}\n    \\item[\\textbf{Lawson:}] Change of variable: $v(t)=e^{-iat}u(t)$, we solve with a RK method: $\\dot{v} = \\tilde{F}(t,v) = e^{-iat}F(e^{iat}v(t))$\n\n      For example, Lawson Euler method:\n      $$\n        v(t_n+\\Delta t)\\approx v^{n+1} = v^n + \\Delta t e^{-iat_n}F(e^{iat_n}v^n)\n      $$\n      or as an expression of $u$:\n      $$\n        u^{n+1} = e^{-ia\\Delta t}u^n + \\Delta te^{ia\\Delta t}F(u^n)\n      $$\n      \\begin{thebibliography}{9}\n        \\setbeamertemplate{bibliography item}[article]\n        \\bibitem{a} \\customcite{Isherwood:2018}\n      \\end{thebibliography}\n  \\end{description}\n\\end{frame}\n\n\\section{Linear analysis}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}{Reminder of stability tools}\n  \\only<1>{\n    If we want to study stability of:\n    $$\n      \\partial_t u + \\partial_x u = 0\n    $$\n    with centered scheme (CD2) $(\\partial_xu)_j \\approx \\frac{1}{2\\Delta x}(u_{j+1}-u_{j-1})$. After a Fourier transform (\\emph{von Neumann analysis}):\n    $$\n      \\dot{u} + i\\frac{\\sin(k\\Delta x)}{\\Delta x}u = 0\n    $$\n    Explicit Euler method in time: we have to stretch \\mbold{eigenvalues} (or \\mbold{Fourier symbol}) of CD2 into explicit Euler \\mbold{stability domain}.\n  } \\only<2>{\n    \\begin{figure}\\centering\n      \\includegraphics[height=0.8\\textheight]{img/cfl_example.png}\n    \\end{figure}\n  }\n\\end{frame}\n%-------%\n\\begin{frame}{From linear Vlasov equation to toy model}\n  Linear Vlasov equation:\n  $$\n    \\partial_t f + a\\partial_x f + b\\partial_v f = 0\n  $$\n  Fourier transform in $x$, CD2 in $v$ plus a Fourier transform in $v$, formally:\n  $$\n    \\frac{\\mathrm{d}f}{\\mathrm{d}t} + iak f + b\\frac{i\\sin(\\varphi)}{\\Delta v}f = 0\n  $$\n  \\mbold{Toy model:}\n  $$\n    \\dot{u} + iau + \\lambda u = 0\n  $$\n  with $a\\in\\mathbb{R}$, $\\lambda\\in\\mathbb{C}$ (diffusive scheme for example).\n\n  $\\lambda$ is the Fourier symbol (or eigenvalues) of FD method to approximate $\\partial_vf$.\n\\end{frame}\n%-------%\n\\begin{frame}{Phase discretization}\n  In $v$ direction we use a FD method:\n  \\begin{itemize}\n    \\item CD2 (centered difference of order 2): $(\\partial_v f)(v_j)\\approx \\dfrac{f_{j+1}-f_{j-1}}{2\\Delta v}$\n    \\item WENO5 (weighted essentially non-oscillatory of order 5):\n      \\begin{itemize}\n        \\item WENO5: non linear scheme: \\st{Von Neumann analysis}\n        \\item LW5 (linearized WENO5): linear scheme (this is Lagrange interpolation of order 5)\n      \\end{itemize}\n      $$\n        (\\partial_vf)(v_j)\\approx\\frac{1}{\\Delta v}\\left(-\\frac{1}{30}f_{j-3} + \\frac{1}{4}f_{j-2} - f_{j-1} + \\frac{1}{3}f_j + \\frac{1}{2}f_{j+1} - \\frac{1}{20}f_{j+2}\\right)\n      $$\n\n\\begin{thebibliography}{9}\n  \\setbeamertemplate{bibliography item}[article]\n  \\bibitem{Wang:2007} \\customcite{Wang:2007}\n  \\bibitem{Motamed:2010} \\customcite{Motamed:2010}\n\\end{thebibliography}\n\n  \\end{itemize}\n\\end{frame}\n%-------%\n\\begin{frame}{Fourier symbols}\n  \\begin{figure}\\centering\n    \\includegraphics[height=0.8\\textheight]{img/weno.png}\n  \\end{figure}\n\\end{frame}\n\n\\subsection{Lawson methods}\n%------------------------------------------------------------------------------\n\\begin{frame}{Lawson methods stability domain}\n  For our toy model:\n  $$\n    \\dot{u} = iau + \\lambda(u)\n  $$\n  Change of variable: $v(t) = e^{-iat}u(t)$\n  $$\n    \\dot{v} = e^{-iat}\\lambda e^{iat}v\n  $$\n  Apply a Runge-Kutta method to compute stability function of Lawson method:\n  $$\n    v^{n+1} = \\underbrace{p(\\lambda\\Delta t)}_{\\text{stability function of RK}}v^n\n  $$\n  \\emph{i.e.}:\n  $$\n    u^{n+1} = \\overbrace{p(\\lambda\\Delta t)e^{-ia\\Delta t}}^{\\text{stability function of Lawson}}u^n\n  $$\n  Stability domain: $\\mathcal{D}=\\left\\{z\\in\\mathbb{C},|p(z)|\\leq 1\\right\\}$ of Lawson method is \\textbf{the same} as the underlying Runge-Kutta method \\textbf{because} $ia\\in i\\mathbb{R}$\n\\end{frame}\n%-------%\n\\begin{frame}{Considered $Lawson(RK(s,p))$ methods}\n  \\begin{figure}\\centering\n    \\includegraphics[height=0.8\\textheight]{img/rk_sd.png}\n  \\end{figure}\n\\end{frame}\n%-------%\n\\begin{frame}{Lawson methods -- CD2}\n  For stability between a Lawson method and CD2, we solve:\n  $$\n    |p(iy)| = 1,\\quad y\\in\\mathbb{R}\n  $$\n  \\begin{table}\n    \\centering\n    \\begin{tabular}{|c|c|c|c|}\n      \\hline\n      Methods & Lawson($RK(3,2) \\; best$) & Lawson($RK(3,3)$) & Lawson($RK(4,4)$) \\\\\n      \\hline\n      $y_{\\max}$ & $2$ & $\\sqrt{3}$ & $2\\sqrt{2}$\\\\\n      \\hline  \n    \\end{tabular}\n    \\caption{CFL number for some Lawson schemes}\n  \\end{table}\n\\begin{thebibliography}{9}\n  \\setbeamertemplate{bibliography item}[article]\n  \\bibitem{} \\customcite{Baldauf:2008}\n\\end{thebibliography}\n\\end{frame}\n%-------%\n\\begin{frame}{Lawson methods -- LW5}\n  \\begin{columns}\n    \\begin{column}{0.5\\textwidth}\n      \\includegraphics[width=\\textwidth]{img/cfl_scheme}\n    \\end{column}\n    \\begin{column}{0.5\\textwidth}\n      \\includegraphics[width=\\textwidth]{img/cfl_rk44_weno.png}\n    \\end{column}\n  \\end{columns}\n\\end{frame}\n%-------%\n\\begin{frame}{Lawson methods -- LW5: CFL estimates}\n  \\begin{table}\n    \\centering\n    \\begin{tabular}{|c|c|c|c|}\n      \\hline\n      Methods & Lawson($RK(3,2) \\; best$) & Lawson($RK(3,3)$) & Lawson($RK(4,4)$) \\\\\n      \\hline\n      $\\sigma $ & $1.344$ & $1.433$   & $1.73$   \\\\\n      \\hline  \n    \\end{tabular}\n    \\caption{CFL number for some Lawson schemes.}\n  \\end{table}\n\\begin{thebibliography}{9}\n  \\setbeamertemplate{bibliography item}[article]\n  \\bibitem{} \\customcite{Motamed:2010}\n  \\bibitem{} \\customcite{Lunet:2017}\n\\end{thebibliography}\n\\end{frame}\n\n\\subsection{Exponential Runge-Kutta methods}\n%------------------------------------------------------------------------------\n\n\\begin{frame}{Exponential Runge-Kutta methods}\n  $$\n    \\dot{u} = iau + F(u)\n  $$\n  Example on ExpRK(2,2):\n  $$\n    \\begin{aligned}\n      u^{(1)} &= e^{-ia\\Delta t}u^n - \\Delta t\\varphi_1 F(u^n) \\\\\n      u^{n+1} &= e^{-ia\\Delta t}u^n - \\Delta t\\left[ (\\varphi_1-\\varphi_2)F(u^n) + \\varphi_2F(u^{(1)}) \\right] \n    \\end{aligned}\n  $$\n  % $$\n  %   \\begin{aligned}\n  %     u^{(1)} &= u^n(1+ia\\varphi_{1,2}) + ia\\Delta t\\varphi_{1,2}F(u^n) \\\\\n  %     u^{n+1} &= u^n(1+ia\\Delta t\\varphi_1) + \\frac{\\Delta t}{2}\\varphi_1F(u^n)+\\frac{\\Delta t}{2}\\varphi_1F(u^{(1)})\n  %   \\end{aligned}\n  % $$\n\n  Stability function becomes:\n  $$\n    p_{\\text{ExpRK(2,2)}}(z) = \\frac{1}{2}\\varphi_1\\varphi_{1,2}z^2 + (\\varphi_1+i\\frac{\\varphi_1\\varphi_{1,2}}{2}a)z + 1 + i\\varphi_1a\n  $$\n\n  Stability domain depends of $a\\Delta t$\\dots \\xmark\n\\end{frame}\n%-------%\n\\begin{frame}{}\n  \\only<1>{\n    \\begin{figure}\\centering\n      \\includegraphics[height=0.7\\textheight]{img/expRK22_sd.png}\n      \\caption{Stability domain of ExpRK(2,2) for $a\\Delta t\\in\\{1.1, 3.4\\}$}\n    \\end{figure}\n  }\n  \\only<2>{\n    \\begin{figure}\\centering\n      \\includegraphics[height=0.7\\textheight]{img/CM_sd.png}\n      \\caption{Stability domain of Cox-Matthews for $a\\Delta t\\in\\{1.1, 3.4\\}$}\n    \\end{figure}\n  }\n  \\only<3>{\n    \\begin{figure}\\centering\n      \\includegraphics[height=0.7\\textheight]{img/K_sd.png}\n      \\caption{Stability domain of Krogstad for $a\\Delta t\\in\\{1.1, 3.4\\}$}\n    \\end{figure}\n  }\n  \\only<4>{\n    \\begin{figure}\\centering\n      \\includegraphics[height=0.7\\textheight]{img/HO_sd.png}\n      \\caption{Stability domain of Hochbruck--Ostermann for $a\\Delta t\\in\\{1.1, 3.4\\}$}\n    \\end{figure}\n  }\n\\end{frame}\n%-------%\n\\begin{frame}{Stability domain informations}\n  Fourier symbol must fit in the stability domain of ExpRK method \\textbf{for all} values of $a\\Delta t\\in\\mathbb{R}$.\n  \\begin{description}\n    \\item[\\xmark] Impossible with WENO5 (LW5 Fourier symbol) \\begin{description}\\item[$\\rightarrow$] Numerical test: unstable in very short time\\end{description}\n    \\item[\\cmark] Singleton $\\{0\\}$ is alway in stability domain of ExpRK method for each values of $a\\Delta t$\n      \\begin{description}\n        \\item[$\\rightarrow$] We can try to stabilize CD2\n        \\item[\\xmark] SPOILER: CFL is equal to zero\n      \\end{description}\n  \\end{description}\n\\end{frame}\n%-------%\n\\begin{frame}{ExpRK -- CD2}\n  \\only<1>{\n    \\begin{figure}\\centering\n      \\includegraphics[width=0.5\\textwidth]{img/ymax_CM_example1.png}\n    \\end{figure}\n  }\n  \\only<2>{\n    \\begin{figure}\\centering\n      \\includegraphics[width=0.5\\textwidth]{img/ymax_CM_example2.png}\n    \\end{figure}\n  }\n  $y^{exp}_\\text{max} = \\min(y_+,|y_-|)$ the largest value to stretch $i[-1,1]$ into the stability domain at $a\\Delta t$\n\\end{frame}\n%-------%\n\\begin{frame}{ExpRK -- CD2: CFL number}\n  \\begin{figure}\\centering\n    \\includegraphics[width=\\textwidth]{img/ymax_CM.png}\n  \\end{figure}\n  CFL $y_\\text{max} = \\min_{a\\Delta t}y^{exp}_\\text{max}$ is still 0\\dots\n\\end{frame}\n%-------%\n\\begin{frame}{ExpRK -- CD2: Relaxed CFL condition}\n  \\only<1>{\n    $$\\mathcal{D}_\\varepsilon = \\left\\{z\\in\\mathbb{C},|p(z)|\\leq1+\\varepsilon\\right\\}$$\n    \\begin{columns}\n      \\begin{column}{0.5\\textwidth}\\centering\n        \\includegraphics[height=0.6\\textheight]{img/CM_sd_ymax_e0p00.png}\n        Cox-Matthews stability domain, relaxation $\\varepsilon = 0$\n      \\end{column}\n      \\begin{column}{0.5\\textwidth}\\centering\n        \\includegraphics[height=0.6\\textheight]{img/CM_sd_ymax_e0p01.png}\n        Cox-Matthews stability domain, relaxation $\\varepsilon = 10^{-2}$\n      \\end{column}\n    \\end{columns}\n  }\\only<2>{\n    \\begin{figure}\\centering\n      \\includegraphics[width=\\textwidth]{img/ymax_CM_relax.png}\n    \\end{figure}\n    Relaxed CFL $y_\\text{max}(\\varepsilon=10^{-2}) \\approx 0.450 \\neq 0$ ! (but unstable in theory)\n  }\n\\end{frame}\n%-------%\n\\begin{frame}{ExpRK -- CD2: Relaxed CFL estimates}\n  \\begin{table}\n    \\centering\n    \\begin{tabular}{|c|c|c|c|c|}\n      \\hline\n      Methods                                & ExpRK22 & Krogstad & Cox--Matthews & Hochbruck \\\\\n                                             &         &          &               & --Ostermann \\\\\n      \\hline\n      $y_{\\max} (\\varepsilon=10^{-3})$ & $0.300$ & $0.100$  & $0.150$      & $0.250$ \\\\\n      \\hline\n      $y_{\\max} (\\varepsilon=10^{-2})$ & $0.551$ & $0.200$  & $0.450$      & $0.501$ \\\\\n      \\hline  \n      $y_{\\max} (\\varepsilon=10^{-1})$ & $1.001$ & $0.601$  & $1.351$      & $1.702$ \\\\\n      \\hline  \n    \\end{tabular}\n    \\caption{CFL number, assuming the relaxed stability constraint, for some exponential integrators.}\n    It's unstable in theory, in practice, number of iterations is finished, so amplification is controlled.\n  \\end{table}\n\\end{frame}\n\n\\section{Numerical simulation: Vlasov-Poisson equations}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\begin{frame}{Vlasov-Poisson equations}\n  $$\n    \\begin{cases}\n      \\partial_tf + v\\partial_xf + E\\partial_vf = 0 \\\\\n      \\partial_xE = \\int_{\\mathbb{R}} f\\,\\mathrm{d}v - 1\n    \\end{cases}\n  $$\n\n  \\mbold{Numerical tools:}\n  \\begin{itemize}\n    \\item FFT in $x$ direction\n    \\item CD2 or WENO5 in $v$ direction\n    \\item $Lawson(RK(s,p))$ or ExpRK method in time $t$\n  \\end{itemize}\n\n  \\mbold{CFL:} $\\Delta t_n \\leq \\dfrac{C\\Delta v}{||E^n||_{\\infty}} \\leq \\dfrac{C\\Delta v}{\\max_n||E^n||_{\\infty}}$ where $C = y_\\text{max}$ or $\\sigma$ from the linear theory.\n\n  \\ \n\n  We can choose: $\\Delta t = \\min\\left( 0.1 , \\dfrac{C\\Delta v}{\\max_n||E^n||_{\\infty}} \\right)$\n\\end{frame}\n%-------%\n\\begin{frame}{Landau damping}\n  $$\n    f(t=0,x,v) = f_0(x,v) = \\frac{1}{\\sqrt{2\\pi}}e^{-\\frac{v^2}{2}}(1+0.001\\cos(0.5x))\n  $$\n  $x\\in[0,4\\pi]$, $v\\in[-8,8]$, $N_x = 81$, $N_v=128$\n\n  \\ \n\n  Because of damping:\n  $$\n    \\max_n||E^n||_{\\infty} = ||E^0||_\\infty\n  $$\n  So, we choose $\\Delta t = 0.1$ (with $\\Delta t = 100$ it is still stable!)\n\\end{frame}\n%-------%\n\\begin{frame}{Landau damping: numerical results}\n  \\only<1>{\n    \\begin{figure}\n      \\centering\n      \\resizebox{!}{.7\\paperheight}{\\input{img/hn}}\n      \\caption{Landau damping test: time history of the CFL condition (semi-log scale).}\n      \\label{ld}\n    \\end{figure}\n  }\\only<2>{\n    \\begin{figure}\n      \\centering\n      \\resizebox{!}{.7\\paperheight}{\\input{img/Emax}}\n      \\caption{Landau damping test: time history of $\\|E(t)\\|_{L^2}$ (semi-log scale) obtained with Lawson($RK(4, 4)$) and WENO5 \n      with $\\Delta t=1/8$ and $\\Delta t=1$.}\n      \\label{ld}\n    \\end{figure}\n  }\n\\end{frame}\n%-------%\n\\begin{frame}{Bump on Tail (BoT)}\n  $$\n    f(t=0,x,v) = \\left[\\frac{0.9}{\\sqrt{2\\pi}}e^{-\\frac{v^2}{2}} + \\frac{0.2}{\\sqrt{2\\pi}}e^{-2(v-4.5)^2} \\right](1+0.001\\cos(0.5x))\n  $$\n\n  $x\\in[0,20\\pi]$, $v\\in[-8,8]$, $N_x = 135$, $N_v=256$\n\n  Numerical estimation of $\\max_n||E^n||_\\infty\\approx 0.6$, we choose $\\Delta t = \\frac{C\\Delta v}{0.6}$\n\\end{frame}\n%-------%\n\\begin{frame}{BoT: numerical results}\n  \\only<1>{\n    \\begin{figure}\n    \\centering\n        \\includegraphics[width=\\textwidth]{img/vp_cfl.png}\n        \\caption{Distribution function at time $t=40$ as a function of $x$ and $v$ for Lawson($RK(4, 4)$) + WENO5 (left), Lawson($RK(4, 4)$) + centered scheme (center), Hochbruck--Ostermann + centered scheme (right).}  \n    \\label{space}      \n    \\end{figure}\n  } \\only<2> {\n    \\begin{columns}\n      \\begin{column}{0.5\\textwidth}\n        \\begin{figure}\n          \\includegraphics[width=0.9\\textwidth]{img/ee_weno_rk44.png}\n          \\caption{Illustration of the accuracy of the CFL estimate obtained from the linear theory. History of electric energy with Lawson($RK(4,4)$) + WENO5}\n        \\end{figure}\n        \\vfill\n        \\ \n      \\end{column}\n      \\begin{column}{0.5\\textwidth}\n        \\begin{figure}\n          \\includegraphics[width=0.9\\textwidth]{img/bot_cfl_weno_rk44.png}\n          \\caption{History of CFL condition for Lawson($RK(4,4)$) + WENO5 case}\n        \\end{figure}\n        \\vfill\n        \\ \n      \\end{column}\n    \\end{columns}\n  } \\only<3> {\n    \\begin{figure}\n      \\includegraphics[width=0.9\\textwidth]{img/H.png}\n    \\end{figure}\n  }\n\\end{frame}\n%-------%\n\\begin{frame}{Adaptive time step size}\n  \\centerline{\\mbold{$\\max_n||E^n||_\\infty$ is not accessible in practice.}}\n\n  \\ \n\n  To capture correctly the phenomena involved in the bump on tail test, we take the following time step size:\n  $$\n    \\Delta t_n = \\min\\left(0.1,\\frac{C\\Delta v}{||E^n||_\\infty}\\right)\n  $$\n  with $C=y_\\text{max}$ or $\\sigma$ from the linear theory.\n\n  \\arrow Good estimate in practice for Lawson methods.\n\\end{frame}\n%-------%\n\\begin{frame}{More Lawson methods}\n  \\only<1>{\n    We are interested in the numerical cost $\\dfrac{\\Delta t}{s}$ of RK($s$,$n$). To compare each time integrator, we compute total energy in Vlasov-Poisson system:\n    $$\n      H(t) = \\int_{\\Omega}\\int_{\\mathbb{R}} v^2f\\,\\mathrm{d}x\\mathrm{d}v + \\int_{\\Omega}E^2\\,\\mathrm{d}x\n    $$\n    which is preserved in time. We propose to select the best method by considering:\n    $$\n      h_{s,n}:\\frac{\\Delta t}{s}\\mapsto \\left|\\left| \\frac{H(t)-H(0)}{H(0)} \\right|\\right|_{\\infty}\n    $$\n  } \\only<2> {\n    \\begin{figure}\\centering\n      \\includegraphics[height=0.8\\textheight]{img/oHdt.png}\n    \\end{figure}\n  }\n\\end{frame}\n\n\n\n\\section{Numerical simulation: drift-kinetic equations}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\begin{frame}{Drift-Kinetic equations}\n  $f = f(t,r,\\theta,z,v)$\n  $$\n    \\begin{cases}\n      \\underbrace{\\vphantom{\\frac{}{}}\\partial_tf + v\\partial_zf}_{\\text{linear part}} \\underbrace{- \\frac{\\partial_\\theta\\phi}{r}\\partial_rf + \\frac{\\partial_r\\phi}{r}\\partial_\\theta f - \\partial_z\\phi\\partial_vf}_{\\text{non linear part}} = 0\\\\\n      -\\left[ \\partial_r^2\\phi + \\left(\\frac{1}{r}+\\frac{\\partial_rn_0(r)}{n_0(r)}\\right)\\partial_r\\phi + \\frac{1}{r^2}\\partial_\\theta^2\\phi \\right]+\\frac{1}{T_e(r)}(\\phi-\\langle\\phi\\rangle) = \\frac{1}{n_0(r)}\\int_{\\mathbb{R}}f\\,\\mathrm{d}v-1\n    \\end{cases}\n  $$\n  $(r,\\theta,z,v)\\in[0.1,14.5]\\times[0,2\\pi]\\times[0,L]\\times\\mathbb{R}$\n\n  After a Fourier transform in $z$, formally, the equation is still of the form of:\n  $$\n    \\partial_t f + ikvf + F(f) = 0\n  $$\n  Compatible with all previous time integrators.\n\n  This is more complicated to use linear stability analysis, we use an other adaptive time step method.\n\\end{frame}\n%-------%\n\\begin{frame}{Adaptive time step size (error estimate)}\n  For adaptive time step size with any time integrator $\\varphi$:\n  $$\n    f^{n+1} = \\varphi_{\\Delta t_n}(f^n)\\qquad;\\qquad \\tilde{f}^{n+1}=\\varphi_{\\Delta t_n/2}\\circ\\varphi_{\\Delta t_n/2}(f^n)\n  $$\n  Richardson extrapolated numerical solution of the method of order $p$:\n  $$\n    f^{n+1}_R = \\frac{2^{p+1}\\tilde{f}^{n+1}-f^{n+1}}{2^{p+1}+1}\n  $$\n  estimate of the local error:\n  $$\n    e_{n+1} = || f^{n+1}_R - f^{n+1} ||_{L^\\infty} + \\mathcal{O}(\\Delta t_n^{p+2})\n  $$\n  If $e_{n+1}>\\text{tol}$: we reject the step and start again from time $t_n$. Else we determine the new time step size:\n  $$\n    \\Delta t_{new} = s\\Delta t_n\\left(\\frac{\\text{tol}}{e_{n+1}}\\right)^{1/(p+1)}\n  $$\n  $s=0.8$ is safety factor.\n\\end{frame}\n%-------%\n% \\begin{frame}{Ion temperature gradient instability}\n%    $$f(t=0,r,\\theta,z,v) = f_{\\text{eq}}(r,v)\\left[1+\\epsilon\\exp\\left(-\\frac{(r-r_p)^2}{\\delta r}\\right)\\cos\\left(\\frac{2\\pi n}{L}z+m\\theta\\right) \\right],$$\n%     where the equilibrium (depends on space) distribution is given by:\n%     $$\n%       f_{\\text{eq}}(r,v) = \\frac{n_0(r)\\exp\\left(-\\frac{v^2}{2T_i(r)}\\right)}{(2\\pi T_i(r))^{1/2}}\n%     $$\n% \\end{frame}\n%-------%\n\\begin{frame}{Ion temperature gradient instability: numerical results}\n    \\begin{figure}\\centering\n      \\includegraphics[height=0.85\\textheight]{img/{driftkinetic-tol1.00e-02-64x64x64x128-pert0}.pdf}\n    \\end{figure}\n\\end{frame}\n\n\\section{Conclusion}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\begin{frame}{Conclusion}\n  \\mbold{Summary}\n  \\begin{itemize}\n    \\item Better understanding on stability of Lawson or ExpRK methods in transport equations\n    \\item Python script with \\texttt{sympy} to compute estimates of CFL of Lawson -- CD2, Lawson -- WENO (5 or 3) or ExpRK -- CD2 (with relaxing CFL)\n    \\item An adaptive time step size which works with any time integrators\n  \\end{itemize}\n\n  \\mbold{Future works}\n  \\begin{itemize}\n    \\item We can improve method with an embedded Runge-Kutta method (Dormand-Prince method, used in \\texttt{ode45} of Matlab)\n    \\item Compare performance between exponential integrators and splitting methods (same stages/step, same order?)\n    \\item Use semi-Lagrangian method to remove dependency on periodic space (Fourier transform)\n  \\end{itemize}\n\\end{frame}\n\n\\section{Future works}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\begin{frame}{VPHL}\n  $$\n    \\begin{cases}\n      \\partial_tf + v\\partial_xf + E\\partial_vf = 0 \\\\\n      \\partial_xE = \\int_\\mathbb{R} f\\,\\mathrm{d}v - 1\n    \\end{cases}\n  $$\n  We linearized around an equilibrium and we suppose:\n  $$\n    f(t=0,x,v) = \\underbrace{f_c(v)}_{(1-\\alpha)\\delta_0(v)} + \\underbrace{f_h(x,v)}_{\\mathcal{M}_{[\\alpha/2,u,1]}+\\mathcal{M}_{[\\alpha/2,-u,1]}}\n  $$\n  and add Ampère equation to obtain:\n  $$\n    \\begin{cases}\n      \\partial_t u_c = E \\\\\n      \\partial_t E = -\\rho_cu_c - \\int vf_h\\,\\mathrm{d}v \\\\\n      \\partial_t \\hat{f}_h = -ikv\\hat{f}_h - \\widehat{E\\partial_v f_h}\n    \\end{cases}\n  $$\n\\end{frame}\n%-------%\n\\begin{frame}{Schemes}\n  3 possibilities to built a scheme:\n  \\begin{itemize}\n    \\item Full-kinetic model with $f_0(x,v) = \\mathcal{M}_{[(1-\\alpha),0,T_c]}+\\mathcal{M}_{[\\alpha/2,u,1]}+\\mathcal{M}_{[\\alpha/2,-u,1]}$ with $T_c \\ll 1$.\n    \\item Hybrid version with splitting method.\n    \\item Hybrid version with Lawson method.\n  \\end{itemize}\n\\end{frame}\n%-------%\n\\begin{frame}{Hybrid splitting}\n  \\begin{description}\n    \\item[$\\varphi_{\\Delta t}^{[a]}$:] $$\n      \\begin{cases}\n        \\partial_t f_h + v\\partial_x f_h = 0 \\\\\n        \\partial_t u_c = 0 \\\\\n        \\partial_t E = -\\int vf_h\\,\\mathrm{d}v\n      \\end{cases}\n    $$\n    \\item[$\\varphi_{\\Delta t}^{[b]}$:] $$\n      \\begin{cases}\n        \\partial_t f_h + E\\partial_v f_h = 0 \\\\\n        \\partial_t u_c = E \\\\\n        \\partial_t E = 0\n      \\end{cases}\n    $$\n    \\item[$\\varphi_{\\Delta t}^{[c]}$:] $$\n      \\begin{cases}\n        \\partial_t f_h = 0 \\\\\n        \\partial_t u_c = 0 \\\\\n        \\partial_t E = -\\rho_cu_c\n      \\end{cases}\n    $$\n  \\end{description}\n  $$\n    U^{n+1} = \\varphi^{[a]}_{\\Delta t} \\circ \\varphi^{[b]}_{\\Delta t} \\circ \\varphi^{[c]}_{\\Delta t} (U^n)\n  $$\n\\end{frame}\n%-------%\n\\begin{frame}{Hybrid Lawson}\n  $$\n    \\partial_t U = AU + N(U)\n  $$\n  with:\n  $$\n    U = \\begin{pmatrix}u_c \\\\ E \\\\ \\hat{f}_h\\end{pmatrix}\n    \\quad\n    A = \\begin{pmatrix}0 & 1 & 0 \\\\ -\\rho_c & 0 & 0 \\\\ 0 & 0 & -ikv \\end{pmatrix}\n    \\quad\n    N(U) = \\begin{pmatrix}0 \\\\ -\\int vf_h\\,\\mathrm{d}v \\\\ -\\widehat{E\\partial_vf_h} \\end{pmatrix}\n  $$\n\\end{frame}\n%-------%\n\\begin{frame}{Numerical result}\n  \\begin{figure}\\centering\n    \\includegraphics[height=0.8\\textheight]{img/electric_energy.pdf}\n  \\end{figure}\n\\end{frame}\n%-------%\n\\begin{frame}{Conclusion of future works}\n  \\begin{itemize}\n    \\item A Python script to compute slope of dispersion relation of \\emph{any} input distribution.\n    \\item Kinetic, and hybrid simulation converge.\n    \\item Two hybrid simulations to compare (it's the future works to do!)\n  \\end{itemize}\n\\end{frame}\n\n\n\\begin{frame}[t]\n  \\vfill\n  {\\usebeamerfont{title} Thank you for your attention}\n  \\vfill\n  \\hfill {\\footnotesize For more questions, I will be at the sauna}\n\\end{frame}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\appendix\n\\backupbegin\n\n\\begin{frame}[plain]\n  \\vspace{0.65\\textwidth}\n  \\hfill\\footnotesize{Backup}\n\\end{frame}\n%-------%\n\\begin{frame}{WENO5 method}\n  \\only<1>{\n    \\textbf{W}eighted \\textbf{E}ssentially \\textbf{N}on-\\textbf{O}scillatory method of order 5: 3 estimates on 3 different stencils weighted with nonlinear weights.\n\n    \\begin{center}\n      \\includegraphics[width=0.5\\textwidth]{img/stencils.png}\n    \\end{center}\n\n    3 steps: \\begin{enumerate}\\item Indicator of smoothness \\item Weights \\item Flux \\end{enumerate}\n  }\n  \\only<2>{\n    \\mbold{Indicator of smoothness $\\beta^\\pm_i$}\n\n    To approximate $\\partial_xf(u)$:\n\n    Split $f$ as:\n    $$\n      f(u) = f^+(u) + f^-(u)\\quad,\\quad \\frac{df^+}{du}\\geq 0\\ \\text{et}\\ \\frac{df^-}{du}\\leq 0\n    $$\n\n    Indicators of smoothness:\n    $$\n      \\beta_i^\\pm  \\gets (f^\\pm_{[\\![j-2,j+3]\\!]})\\ ,\\ i=0,1,2\n    $$\n    Approximations of derivatives of order 1 and 2 on 3 stencils.\n  }\n  \\only<3>{\n    $$\n      \\begin{aligned}\n        \\beta_0^+ &= \\frac{13}{12}\\left( f^+_{j-2} - 2f^+_{j-1} + f^+_{j}   \\right)^2\\!\\!\\!\\!\\!\\!&+& \\frac{1}{4}\\left(  f^+_{j-2} - 4f^+_{j-1} + 3f^+_{j}   \\right)^2 \\\\\n        \\beta_1^+ &= \\frac{13}{12}\\left( f^+_{j-1} - 2f^+_{j}   + f^+_{j+1} \\right)^2\\!\\!\\!\\!\\!\\!&+& \\frac{1}{4}\\left(  f^+_{j-1}              -  f^+_{j+1} \\right)^2 \\\\\n        \\beta_2^+ &= \\frac{13}{12}\\left( f^+_{j}   - 2f^+_{j+1} + f^+_{j+2} \\right)^2\\!\\!\\!\\!\\!\\!&+& \\frac{1}{4}\\left( 3f^+_{j}   - 4f^+_{j+1} +  f^+_{j+2} \\right)^2\\\\\n        & & & \\\\\n        \\beta_0^- &= \\frac{13}{12}\\left( f^-_{j+1} - 2f^-_{j+2} + f^-_{j+3} \\right)^2\\!\\!\\!\\!\\!\\!&+& \\frac{1}{4}\\left( 3f^-_{j+1} - 4f^-_{j+2} +  f^-_{j+3} \\right)^2 \\\\\n        \\beta_1^- &= \\frac{13}{12}\\left( f^-_{j}   - 2f^-_{j+1} + f^-_{j+2} \\right)^2\\!\\!\\!\\!\\!\\!&+& \\frac{1}{4}\\left(  f^-_{j}                -  f^-_{j+2} \\right)^2 \\\\\n        \\beta_2^- &= \\frac{13}{12}\\left( f^-_{j-1} - 2f^-_{j}   + f^-_{j+1} \\right)^2\\!\\!\\!\\!\\!\\!&+& \\frac{1}{4}\\left(  f^-_{j-1} - 4f^-_{j}   + 3f^-_{j+1} \\right)^2\n      \\end{aligned}\n   $$\n  }\n  \\only<4>{\n    \\mbold{Weights $w^\\pm_i$}\n\n    Unnormalized weights:\n    $$\n      \\alpha_i^\\pm \\gets \\frac{\\gamma_i}{(\\epsilon+\\beta_i^\\pm)^2}\\ ,\\  \\gamma_i \\in\\mathbb{R}^*_+\\,: \\sum_k\\gamma_k = 1\n    $$\n    where $\\gamma_0 = \\frac{1}{10}, \\gamma_1=\\frac{6}{10}, \\gamma_2=\\frac{3}{10}$. Parameter $\\epsilon = 10^{-6}$\n\n    Linearized weights (LW5): $\\alpha_i^\\pm = \\gamma_i + \\mathcal{O}(\\Delta x^2)$\n\n    Normalized weights:\n    $$\n        w_i^\\pm \\gets \\frac{\\alpha_i^\\pm}{\\sum_k\\alpha_k^\\pm}\n    $$\n  }\n  \\only<5>{\n    \\mbold{Flux $f^\\pm_{i+\\frac{1}{2}}$}\n\n    $$\n      \\begin{aligned}\n        f_{j+\\frac{1}{2}}^+ \\gets w_0^+ \\left( \\frac{2}{6}f^+_{j-2} - \\frac{7}{6}f^+_{j-1} + \\frac{11}{6}f^+_{j}\\right)\n                                + w_1^+ \\left(-\\frac{1}{6}f^+_{j-1} + \\frac{5}{6}f^+_{j}   +  \\frac{2}{6}f^+_{j+1}\\right) \\\\\n                                + w_2^+ \\left( \\frac{2}{6}f^+_{j}   + \\frac{5}{6}f^+_{j+1} -  \\frac{1}{6}f^+_{j+2}\\right)\n      \\end{aligned}\n    $$\n\n    $$\n      \\begin{aligned}\n        f_{j+\\frac{1}{2}}^- \\gets w_2^- \\left(-\\frac{1}{6}f^-_{j-1} + \\frac{5}{6}f^-_{j}   + \\frac{2}{6}f^-_{j+1}\\right)\n                                + w_1^- \\left( \\frac{2}{6}f^-_{j}   + \\frac{5}{6}f^-_{j+1} - \\frac{1}{6}f^-_{j+2}\\right) \\\\\n                                + w_0^- \\left(\\frac{11}{6}f^-_{j+1} - \\frac{7}{6}f^-_{j+2} + \\frac{2}{6}f^-_{j+3}\\right)\n      \\end{aligned}\n    $$\n\n    $$\n    \\boxed{\n      (\\partial_x f(u))_j \\approx \\frac{1}{\\Delta x}\\left[(f_{j+\\frac{1}{2}}^+ - f_{j-\\frac{1}{2}}^+) + (f_{j+\\frac{1}{2}}^- - f_{j-\\frac{1}{2}}^-)\\right]\n      }\n    $$\n  }\n\\end{frame}\n%-------%\n\n\\backupend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\end{document}\n", "meta": {"hexsha": "23ca65fc6962d84d163bf57c574284c6e01f2a82", "size": 29960, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "communication/19-12-10_mingus/mingus.tex", "max_stars_repo_name": "kivvix/draft", "max_stars_repo_head_hexsha": "33b605be27e556df061f856be8e84e5b3f49a219", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-01-03T22:31:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-29T06:12:07.000Z", "max_issues_repo_path": "communication/19-12-10_mingus/mingus.tex", "max_issues_repo_name": "kivvix/draft", "max_issues_repo_head_hexsha": "33b605be27e556df061f856be8e84e5b3f49a219", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "communication/19-12-10_mingus/mingus.tex", "max_forks_repo_name": "kivvix/draft", "max_forks_repo_head_hexsha": "33b605be27e556df061f856be8e84e5b3f49a219", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-11-20T12:36:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-29T06:17:16.000Z", "avg_line_length": 35.5397390273, "max_line_length": 245, "alphanum_fraction": 0.5906875834, "num_tokens": 10886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.6370307806984445, "lm_q1q2_score": 0.33095107331262974}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\documentclass[12pt,a4paper]{paper}\n\\usepackage[latin1]{inputenc}\n\\usepackage{amsmath}\n\\usepackage{amsfonts}\n\\usepackage{amssymb}\n\\usepackage{amsthm}\n\\usepackage{epsfig,graphics,graphicx}\n\\usepackage{color}\n\\usepackage{mathtools}\n%\\usepackage{here}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\newcommand{\\acc}[2]{ \\{ #1 \\}_{#2} }\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\begin{document}\n\\begin{center}\n  {\\bf \\Large Simple application of the PoPe method\\\\ Work in progress... \\vspace{2.pt}\\\\}\n  {T. Cartier-Michaud, ...} \\\\\n  {October 2017}\\\\\n\\end{center}\n\n\\tableofcontents\n\n%*********************************\n%*** PoPe method in a nutshell ***\n%*********************************\n%\\baselineskip = 16.pt\n\\section[PoPe method in a nutshell]{PoPe method in a nutshell : decomposition onto a relevant basis plus an error}\nThe Projection on Proper element (PoPe \\textbf{cite}) method is a method allowing to recover the equations that have generated a set of data. In terms of verification, using output of any simulations to verify a code is fundamentaly different from the Method of Manufcatured Solutions (MMS \\textbf{cite}) where the code is verified with respect to an ``artificial'' solution as it is difficult to obtain a target analytical solution representative of typical simulations. Often the analytical solution chosen is smooth in space an time with respect to the discretisation, it is based on simplified geomertries or boundary conditions and it might not used every operators of the model : this verification is partial.\nUsing PoPe onto a set of data produced by a code, if one searches for the full set of equations implemented in the code considered, one does code verification, if one searches for a reduced set of equations compare to the set used in the first place by the code, one does model reduction.\nPoPe can also be understand a procedure of a posteriori error checking a posteriori. In this thesis, it has been used as a post treatment developped independently of the code as a Matlab/Octave library.\n\n\\section[Practial implementation of PoPe method]{Practial implementation of PoPe method}\n%\nTo explain the method, we use the following density equation eq.(\\ref{eq:dtN}) as an example :\n%\n\\begin{eqnarray}\n  \\label{eq:dtN}\n  \\partial_t N =\n  \\vec{\\nabla} (D_N \\vec{\\nabla}_\\perp N)\n-  \\vec{\\nabla} ( N u^{ion}_\\parallel \\vec{b}) \n-  \\vec{\\nabla} ( N \\vec{u}_{E \\times B})\n-  \\vec{\\nabla} ( N \\vec{u}^{ion}_{\\nabla B})\n+  S_N\n\\end{eqnarray}\n%\nEquation we immedialtely rewritte in a more compact form, using ``$th$'' subscript for ``theoretical'', $\\acc{O^i}{th}$ the five operators of eq.(\\ref{eq:dtN}) for $i\\in[1,5]$ associated to five theoretical weights $w^i_{th}$, also using Einstein's convention on indices :\n%\n\\begin{eqnarray}\n  \\acc{\\partial_t N}{th} &=& w^i_{th} \\acc{O^i}{th} \\label{eq:dtN_th}\\\\\n  w_{th} &=& [+1,-1,-1,-1,+1] \\label{eq:w_th}\n\\end{eqnarray}\n\nWhat we can easily do is :\n\\begin{enumerate}\n  %\n\\item Measurements of $\\acc{\\partial_t N}{ef}$, the effective (``$ef$'' subscript) time derivative computed with finite differences from outputs of a given code. In the present case, finite differences of order four compare to the order one time integration scheme in TOKAM3X.\n  \\begin{eqnarray}\n    \\acc{\\partial_t N}{ef}(t) &=& \\sum_{j=-2}^2 c(j) N(t+j\\Delta t) + \\mathcal{O}(\\Delta t^4)\\\\\n    c(-2:2) &=& [+1,-8,0,+8,-1]/(12\\Delta t)\n  \\end{eqnarray}\n  %  \n\\item Computations of each operator in eq.(\\ref{eq:dtN}), labeled $\\acc{O}{ol}^i$ for $i \\in [1,5]$, using higly accurate off-line (``$ol$'' subscript) post-treatments. TOKAM3X using second order method in space, the offline estimation uses method of order $2$ to $8$.\n  \\begin{eqnarray}\n    \\acc{O^i}{ol} &\\simeq& \\acc{O^i}{th} \\label{eq:olvsth}\\\\\n    ||\\acc{O^i}{th}- \\acc{O^i}{ol}|| &\\ll&  ||\\acc{O^i}{th}- \\acc{O^i}{ef}|| \\label{eq:tholef}\n  \\end{eqnarray}\n  %\n\\item Linear projections of $\\acc{\\partial_t N}{ef}$ onto $\\acc{O}{ol}^i$ and thus recover effective weights $w^i_{ef}$ and an effective residual $\\epsilon_{ef}$ lineary independent of $\\acc{O}{ol}^i$.\n  \\begin{equation}\n    \\acc{\\partial_t N}{ef} = w^i_{ef} \\acc{O}{ol}^i + \\epsilon_{ef}\n  \\end{equation}\n  %\n  This projection is simply done by solving the following linear systems eq.(\\ref{eq:leastmeansquare}) based on the least mean square approach. The residual is then recovered by explicitly computing eq.(\\ref{eq:epsef}).\n\\begin{eqnarray}\n  A^t A ~ w_{ef} &=& A^t \\acc{\\partial_t N}{ef} \\label{eq:leastmeansquare}\\\\\n  \\acc{\\partial_t N}{ef} - A ~ w_{ef} &=& \\epsilon_{ef} \\label{eq:epsef}\\\\\n  A(p,i) &=& \\acc{O(p)^i}{ol}\n\\end{eqnarray}\nThe matrix $A$ is of size $P \\times I$. Each column of the matrix $A$ is the evaluation of the $i^{th}$ operator from the set of $I$ operators present in the tested equation. Those evalations are perfomed for $P$ points labeled by the indice $p$. $P$ is define by the discretisation used to solve the equation with the code we want to verify in the first place. Usually $P\\gg I$ which justifies the mean least square approach to obtain the best estimation of $w_{ef}$. For TOKAM3X, typically, we have $P = N_{r} \\times N_{\\theta} \\times N_{\\phi} \\times N_t \\gg 10^6$ for a unique simulation. Nevertheless, to introduce a time dependence in $w_{ef}$, we usually use $N_t$ sets of $  N_{r} \\times N_{\\theta} \\times N_{\\phi} \\ge 10^4$ points.\n%\n\\end{enumerate}\n%\nThis leads to the interpretation of the effective time derivative of a given code ($\\acc{\\partial_t N}{ef}$) as a sum of weighted (by $w^i_{ef}$) operators ($\\acc{O}{ol}^i$) plus a residual ($\\epsilon_{ef}$) which has no linear dependency toward the operators of the equations. Ideally, $w_{ef} = w_{th}$ and $\\epsilon_{ef} = 0$.\n%\nThis decompostion is relevant as weights such as $w^i_{ef}$ define the nature of the equation so they control the behavior of the system (theoretically and numerically).\nA simple error such as the used of a diffusion coeffient two times higher than the one theoretically wanted would immediately be seen with $w^1_{ef} = 2 w^i_{th}$.\nThe control of weights would be absolute if $\\acc{O^i}{ef}$, operators effectively implemeted in the code, were ``exact''. As we discretise solutions over a finite number of degree of freedom, each having a finite accuracy, operators $\\acc{O^i}{ef}$ usually differ from theoertical expression of operators $\\acc{O^i}{th}$. The theoretical expression of operators being not accessible usually, we do not compare $\\acc{O^i}{ef}$ to $\\acc{O^i}{th}$ but rather to $\\acc{O^i}{ol}$, a set of operators computed off-line using a greater accuray than for $\\acc{O^i}{ef}$, so $\\acc{O^i}{ol}$ evaluations are closer to $\\acc{O^i}{th}$ than $\\acc{O^i}{ef}$ are close to $\\acc{O^i}{th}$ as define eq.(\\ref{eq:tholef}). This point is important to be able to associate the residual $\\epsilon_{ef}$ to an error in the code and not an error in the verification process. This off-line greater accuracy is easily obtained as for off-line computations we don't have to take care of any stability with respect to time integration.\nAlso, verification is usually performed on about $1\\%$ of the data generated by a code. For example $1$ time step out of $100$ over time is sufficient as generally the time step is define to insure small variations of the solution between consecutive iterations. Verifying each time step is still possible but it would conduct to verify many systems very close to each other.\nFinally recommandation concerns the localisation in space and time of the data used for the verification process. One equation is seen as a law that has to be verified anywhere and at any time with respect to the state of the system at those exact location and time. Thus, we have to carefully handle variables used to recompute the equation in order to be sure not to mix a variable $a$ evaluated at $(x,t)$ with a variable $b$ evaluated at $(x+\\Delta x, t+\\Delta t)$, unless the analytical system cleary states it is the way to do it, that the equation contains a time delay and an action over a distance.\n%\n%**************\n%*** how to ***\n%**************\n\\section{Aim of this pacakge : a test bed for PoPe}\n%\nThis package aims to offer a test case of the PoPe method in order to quickly learn how to use PoPe and to test new ideas. It is written in Matlab/Octave on a simple advection - diffusion problem using two parameters $(c,D)$ and an optional source $S$ :\n\\begin{eqnarray}\n  \\partial_t f = c \\partial_x f + D \\partial_x^2 f + S\n\\end{eqnarray}\n\n\\subsection{How to use this pacakge}\n\nJust run ``scan\\_void''...\n\n\\subsection{Open issues}\n\n%\n%**************\n%*** Results ***\n%**************\n\\section{Analysis of PoPe's results}\nAs a preminilary study, we can introduce a more general definition of the effective residual $\\epsilon_{ef}$ which, using $\\acc{O^i}{ol}=\\acc{O^i}{th}$ for simplification, is the total residual $\\epsilon$ defined as :\n%\n\\begin{eqnarray}\n  \\acc{\\partial_t N}{ef} - \\acc{\\partial_t N}{th} &=& \\epsilon \\label{eq:eps_total_def}\\\\\n  &=& ( w^i_{ef} - w^i_{th} ) \\acc{O}{ol}^i + \\epsilon_{ef} \\label{eq:eps_total_construction}\n\\end{eqnarray}\n%\nThis total residual contains a part linearly dependent on the operators as seen eq.(\\ref{eq:eps_total_construction}). It allows to clearly identify $\\delta^i=w^i_{ef} - w^i_{th}$ the error on weights of the equations. Nevertheless, using only eq.(\\ref{eq:eps_total_def}) we do not need to solve any linear system to obtain $\\epsilon$.\\\\\n\nIn this section, first we estimated the quality of a simulation studying $\\epsilon$ which contains the entire information on the discrepency between the theoretical evolutoin of the systeme the effective evolution. Then a statistical study of $w_{ef}$ and $\\epsilon_{ef}$ is performed in order to give a more physical interpretation of the results...\n% not dealing with boundaries\n\n\\begin{thebibliography}{100}\n%\\bibitem{Lesur_PRL_12} M. Lesur, P.H. Diamond submitted to Phys. Rev. Lett. (2012).\n\n\\end{thebibliography}\n\n\\end{document}\n\n%%% Local IspellDict: american  \n", "meta": {"hexsha": "1a394884606dd76fdc052dfc62b828cbf5fd1487", "size": 10019, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "README.tex", "max_stars_repo_name": "frozar/PoPe", "max_stars_repo_head_hexsha": "e2a9cbc1fc132e94a7dc5e369a463ddfb7c2f021", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "README.tex", "max_issues_repo_name": "frozar/PoPe", "max_issues_repo_head_hexsha": "e2a9cbc1fc132e94a7dc5e369a463ddfb7c2f021", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "README.tex", "max_forks_repo_name": "frozar/PoPe", "max_forks_repo_head_hexsha": "e2a9cbc1fc132e94a7dc5e369a463ddfb7c2f021", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 74.7686567164, "max_line_length": 1010, "alphanum_fraction": 0.7104501447, "num_tokens": 2869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.3309136791421204}}
{"text": "%\n% modified at Dec. 14th, 2009\n%\n%\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\chapter{Numerical Quadrature Method}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Introduction}\n Commonly to say, the exchange-correlation integrals we\nare dealing with in the KS-DFT equation adopt such form:\n\\begin{equation}\\label{}\n    I = \\int F(\\rho, \\bigtriangledown \\rho, \\cdots) d \\tau\n\\end{equation}\nSince the functional has so complicated expression, that no\nanalytical methods can be used to calculate its integrals. Hence the\nnumerical quadrature method is indispensable. The general idea of\nnumerical quadrature method is to transform the difficult integrals\ninto a summation process as approximation:\n\\begin{equation}\\label{}\n    \\int^{a}_{b}y(x)dx = \\sum^{n}_{i=1}A_{i}y(x_{i})\n\\end{equation}\nHere the $x_{i}$ is the grid point where the summation is taking;\nand $A_{i}$ is its integral coefficient.\n\nAccording to the above thoughts, the $I = \\int F(\\rho,\n\\bigtriangledown \\rho, \\cdots) d \\tau$ can be approximated as:\n\\begin{equation}\\label{NQMeq:1}\n\\int F(\\rho, \\bigtriangledown \\rho, \\cdots) d \\tau =\n\\sum^{n}_{i=1}A_{i}F(\\rho_{i}, \\bigtriangledown \\rho _{i}, \\cdots)\n\\end{equation}\nFor the functional F is heavily depends on the density change, so\nthe integral process can be well expected that two rules has to be\nfollowed:\n\\begin{itemize}\n  \\item Near the nuclear the $\\rho$ has cusp, so the integral has\n  cusp near the nuclear\n  \\item as the $r \\rightarrow \\infty$, $\\rho \\rightarrow 0$, so \n$I \\rightarrow 0$\n\\end{itemize}\nFor the reason of the first item, it's not appropriate to directly\nuse the grid over the whole three dimensional space. As a good\napproximation method, Becke\\cite{Becke} suggested an alternative way\nto calculate such integrals. The general main idea will be discussed\nin the following content, actually this idea has been taken in\nalmost all of the quantum chemistry softwares (such as \\cite{g03,\nQCHEM,turbomole}). As for conveniences, we will use the general\nfunction of $F(r)$ for discussion, and take functional of\n$f[\\rho]=\\rho ^{\\frac{3}{4}}$ as an example to illustrate the whole\nprocess.\n\nFor the common integral process, we have:\n\\begin{equation}\\label{}\n    \\int \\rho^{\\frac{3}{4}}(r) d \\tau \\approx \\sum_{i=1}^{n}\nA_{i} \\rho^{\\frac{3}{4}}(r_{i})\n\\end{equation}\nHere the $n$ denotes the number of grids, and $r_{i}$  stands for\nthe grid.\n\nSince the $\\rho$ has cusp near the nuclear, so a very natural idea\nis to divide the multicentric integral into single center\nintegration over nucleus, and then sum up them together:\n\\begin{eqnarray}\n% \\nonumber to remove numbering (before each equation)\n  I &=& \\sum_{n} I_{n} \\nonumber \\\\\n    &=& \\sum_{n} \\int F_{n}(r) d \\tau\n\\end{eqnarray}\nHere the $\\int F_{n}(r) d \\tau$ denotes the single center\nintegration over nuclear. After this step, then we can use numerical\nquadrature method to calculate each single center integral, then\nfinish the whole process. The most important question in this\nprocess is: How to associate the $F_{n}(r)$ with the general\nexpression of functional of $F(r)$? In other words, how to judge\nwhether a single grid belongs to this atom? As for answering this\nquestion, Becke suggested weight function method. In this method, he\nexpress the $F_{n}(r)$ as:\n\\begin{equation}\\label{}\nF_{n}(r) = w_{n}(r)F(r)\n\\end{equation}\nFor the grid belongs to the atom n, it has $w_{n}(r) \\approx 1$; and\nfor the grid not belongs to the atom n, $w_{n}(r) \\approx 0$. For\nall the atoms related to this grid, we have:\n\\begin{equation}\\label{}\n\\sum_{A}w_{A}(r) = 1\n\\end{equation}\nThis process corresponds to divide the grid expression of\n$A_{i}F(r_{i})$ in the (\\ref{NQMeq:1}) into some pieces, each has\nform of $w_{n}(r_{i})A_{i}F(r_{i})$, and if we add all the pieces\ntogether, that is $\\sum^{atoms}_{n}w_{n}(r_{i})A_{i}F(r_{i}) =\nA_{i}F(r_{i}) $, we still get the summation in the (\\ref{NQMeq:1}).\n\nRelative weight function which has the form of $w_{n}(r)$,\nhas value unity in the vicinity of its own nucleus, but vanishes in\na continuous and well behaved manner near any other nucleus. In a\nsense, the system is divided into some fuzzy, overlapping cells,\neach cell contains a nuclear, and on that nuclear the numerical\nquadrature method is taken on to calculating the single center\nintegrals; the relative weight function is used to make sure that\nthe grid in the calculation is belonged to the specific atom. \n\nNow let's use some example of $\\rho^{\\frac{3}{4}}$ to show the above\nwords, we have:\n\\begin{equation}\n\\label{NQM_general_eq}\n\\begin{split}\n \\rho^{\\frac{3}{4}}(r_{i}) &= \\sum^{atoms}_{n} w_{n}(r_{i})\n\\rho^{\\frac{3}{4}}(r_{i}) \\Rightarrow  \\\\\nI &= \\int \\rho^{\\frac{3}{4}}(r) d^{3}r \\\\\n  &= \\sum^{grids}_{g} A_{g}\\rho^{\\frac{3}{4}}(r_{g}) \\\\\n  &= \\sum^{grids}_{g} A_{g} \\sum^{atoms}_{n}\nw_{n}(r_{g})\\rho^{\\frac{3}{4}}(r_{g}) \\\\\n  &= \\sum^{grids}_{g}\\sum^{atoms}_{n}A_{g} \nw_{n}(r_{g})\\rho^{\\frac{3}{4}}(r_{g}) \\\\\n\\end{split}\n\\end{equation}\nThis is just the general method for us to evaluate the numerical\nquadrature for the arbitrary functional. \n\n\n%In term of this process, we will discuss it from five aspect:\n%\\begin{itemize}\n%  \\item scheme to produce relative weight function\n%  \\item radical integration\n%  \\item numerical quadrature method to calculate the single center\n%  integral\n%  \\item symmetry handling\n%  \\item linear scaling scheme\n%\\end{itemize}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Scheme to produce relative weight function}\\label{weight_function_dft} \n\nThe first systematic approach to introduce the relative weight\nfunction is from Becke\\cite{Becke}. where is this method we will know\nhow to generate the concrete $w_{n}$ for evaluating the quadrature. \n\nthe scheme used by Becke involves the two-center coordinate\nsystem known as confocal elliptical coordinates $(\\lambda, \\mu,\n\\phi)$. The coordinate $\\phi$ denotes the angle about the\ninternuclear axis, and coordinate $\\lambda$ and $\\mu$ are defined\nby:\n\\begin{equation}\\label{}\n \\lambda = \\frac{r_{1}+ r_{2}}{R_{12}} \\quad\n\\mu = \\frac{r_{1} - r_{2}}{R_{12}}\n\\end{equation}\nWhere $r_{1}, r_{2}, R_{12}$ denote distance to nuclear 1, distance\nto nuclear 2, and internuclear separation, respectively. Their range\nis indicated below:\n\\begin{eqnarray}\n% \\nonumber to remove numbering (before each equation)\n   & & 0 \\leq \\phi \\leq 2\\pi \\nonumber \\\\\n   & & 1 \\leq \\lambda <\\infty \\nonumber \\\\\n   & & -1 \\leq \\mu \\leq +1\n\\end{eqnarray}\nObviously the surface of $\\mu=0$ is bisecting the internuclear axis,\nso it works as sign for separating two atoms. So simply the weight\nfunction can be:\n\\begin{equation}\\label{NQMeq:2}\ns(\\mu_{ij})=\\begin{cases}\n1, & -1 \\leq \\mu_{ij} \\leq 0 \\\\\n0, & 0 \\leq \\mu_{ij} \\leq +1\n\\end{cases}\n\\end{equation}\nHence if we use this expression, conceptually for some grid it only\nbelongs to only one atom so that we have the $w_{n} = 1$ for some\natom $n$. Hence the summation over the atoms will disappeared.\n\nHowever, this expression is too simple so that it cause instability\nin the numerical quadrature. Further Becke suggest to use some\n\"smooth\" function to replace the expression of (\\ref{NQMeq:2}), which\nshould obey some boundary conditions:\n\\begin{eqnarray}\\label{NQMeq:5}\n% \\nonumber to remove numbering (before each equation)\n  s(-1) &=& 0 \\nonumber \\\\\n  s(+1) &=& 0 \\nonumber \\\\\n  \\frac{ds}{d \\mu}(-1) &=& \\frac{ds}{d \\mu}(+1) = 0\n\\end{eqnarray}\nUnder this condition, he finally construct some polynomials\nexpression which satisfy the condition above. It's worthy to note\nthat this polynomial should vary as fast as possible so that it can\navoid the cusp near the nuclear; so the final expression is:\n\\begin{eqnarray}\\label{NQMeq:3}\n% \\nonumber to remove numbering (before each equation)\n  s(\\mu_{ij}) &=& \\frac{1}{2} \\bigg[1- p \n\\Big\\{p \\big[ p(\\mu_{ij}) \\big] \\Big\\} \\bigg] \\nonumber \\\\\n  p(\\mu_{ij}) &=& \\frac{3}{2}\\mu_{ij} - \\frac{1}{2}\\mu^{3}_{ij}\n\\end{eqnarray}\nIt yields a 27 degree analytical polynomial expression. Here the\n$\\mu_{ij}$ is just the expression of $\\dfrac{r_{i} - r_{j}}{R_{ij}}$. \n\nSo finally we have weight function defined as:\n\\begin{eqnarray}\\label{NQM_generation_eq}\n% \\nonumber to remove numbering (before each equation)\n  P_{i}(r) &=&  \\prod_{j \\neq i}s(\\mu_{ij}) \\nonumber \\\\\n  w_{n}(r) &=& P_{n}(r)/\\sum_{m} P_{m}(r)\n\\end{eqnarray}\nHere i, j ,n, m all denote to the specific atoms.\n\nMurray et al.\\cite{MHL}, Gill et al.\\cite{PJM},Treutler et\nal.\\cite{OR}, etc. all use this technic to decide the relative\nweight function; however, Stratman et al.\\cite{EGM} further polished\nup the expression above, for speeding up the calculation efficiency.\n\nStratman et al. use another step function which functions similar to\nthe (\\ref{NQMeq:3}), who has degree of 7, which is much lower than\n(\\ref{NQMeq:3}):\n\\begin{equation}\\label{NQMeq:4}\nz(\\mu_{ij}:a) = \\frac{1}{16} \\Big[ 35(\\frac{\\mu_{ij}}{a}) - 35 (\n\\frac{\\mu_{ij}}{a})^{3} + 21(\\frac{\\mu_{ij}}{a})^{5}\n-5(\\frac{\\mu_{ij}}{a})^{7} \\Big]\n\\end{equation}\nHere they set $a$ equals to 0.64. By introducing the $z(\\mu_{ij}:a)$\nback into the (\\ref{NQM_generation_eq}), we can get the weight for\nsome specific $r$.\n\nIn their paper\\cite{EGM}, they presented another advantage brought\nby introducing this new polynomial expression, which is \"screen\nweights\". That means, in such scheme the weight which associated\nwith a certain of grid can be efficiently determined that whether it\nequals to 1 or not, by the condition below:\n\\begin{equation}\\label{}\n\\text{If} \\quad r_{ig} < \\frac{1}{2}(1-a)R_{in} \\Rightarrow\nw_{i}(r_{g}) = 1\n\\end{equation}\nWhere $r_{ig}$ is the distance from the grid point $g$ to its parent\natom $i$, $R_{in}$ is the distance to the nearest atomic neighbor of\n$i$, and $a$ is the constant defined above. Since a significant\namount of grid has weight equals to 1, so this step avoids a lot of\ncalculation time, but still be able to achieve same accuracy\nprecision\\cite{EGM}.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Linear scaling of the computation}\n%\n%\n%\n%\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Batch of the grid points}\n%\n%\n%\n%\nIn modern quantum chemistry packages, we usually employ the Gaussian\ntype of atomic orbitals. However, GTO has a fast decaying nature that\nfor a certain grid point, only a few of basis functions (GTOs) are\nmaking contribution to it and the others can be safely neglected\nwithout affecting the accuracy. Based on this idea, we can introduce\nthe ``batch'' concept.\n\nWhat does the batch mean? For an arbitrary grid point, we can\ndetermine that what kind of GTOs ( or shells, which is a group of\nGTOs who sharing the same center and angular parts) are making\ncontribution to this point. Such group of GTOs are called ``batch''.\nOn the other hand, we can also define that for a certain kind of\nshell (or GTOs), what kind of grids it making contribution to. That's\ntwo different types of definition, but should lead to the same\nresult. \n\nNow let's go to see how to put it into computation details. First, we\nhave to define the ``size'' of every shell (it's represented by\n$\\lambda$). That means, for a fixed shell, who is certering in\n$\\bm{R_{a}}$ and it's radical part is $\\psi_{a}$; it's size is\ndefined as $|\\psi_{a}| < \\epsilon$. then for some grid point of\n$\\bm{r_{g}}$, we use the formula below to determine that whether a\nshell contributing to the grid point or not:\n\\begin{equation}\n \\label{linear_scale_numerical_quadrature_eq:1}\nif \\quad |\\bm{r_{g}} - \\bm{R_{a}}| \\leq \\lambda_{a}, then \\quad\n\\psi_{a} \\in S_{g}\n\\end{equation}\nFinally, all the shells in this batch have the non-zero weight, and\nall the others shells (GTOs) has the zero weight. Then the weight\ncalculation also becomes easier.  \n\n\n\\begin{comment}\n\\subsection{Batch of the grid points}\nSince in the grid methods, such as Gauss-Lebedev grid; requires the\ninterval should be within in $-1 \\leq x \\leq +1$, but the radical\ninterval in the single center integral is to be $0 \\leq r \\leq\n\\infty$, so it's necessary to strike up a mapping between them.\nMoreover, this transformation may bring some delicate effects to the\nnumerical integration process; which had been carefully discussed by\nTreutler\\cite{OR}. We will carefully consider it as we encounter\nthis problem.\n\\end{comment}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{The single center integral}\n%\n%\n%\nTraditionally we have choices list below to achieve this process(here\nonly some of them are listed):\n\\begin{description}\n  \\item[Gauss-Lebedev grid]: This method is adopted by many popular\n  programs.\n  \\item[Lobatto grid]: used in turbomole.\n  \\item[Euler-Maclaurin grid]: used in DGAUSS and discribled by\n  Murray et al.\\cite{MHL}.\n\\end{description}\n\nThe numerical quadrature methods related to the single center, are\nvery stable and the difference of result between methods of grid is\nlittle. However, the Lebedev grid method is widely used for its high\nefficiency.\n\nGenerally, the grid methods can be described in the following form:\n\\begin{equation}\\label{}\nI_{n} = \\int\\int\\int F_{n}(r,\\theta,\\phi)r^{2}\\sin\\theta dr\nd\\theta d \\phi \\approx \\sum^{N_{r}}_{i=1} A^{r}_{i}\n\\sum^{N_{\\Omega}}_{j=1}A^{\\Omega}_{j} F(r_{i}, \\theta_{j}, \\phi_{j})\n\\end{equation}\nHere in this expression the $A^{r}_{i}$(related to the radical\nquadrature) and $A^{\\Omega}_{j}$(related to the angle quadrature)\nare constant parameters, actually they are the coefficients; and\nfunction of F has certain formation as expanding the integral into\nsummation.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Question With Radical Integration}\nSince in the grid methods, such as Gauss-Lebedev grid; requires the\ninterval should be within in $-1 \\leq x \\leq +1$, but the radical\ninterval in the single center integral is to be $0 \\leq r \\leq\n\\infty$, so it's necessary to strike up a mapping between them.\nMoreover, this transformation may bring some delicate effects to the\nnumerical integration process; which had been carefully discussed by\nTreutler\\cite{OR}. We will carefully consider it as we encounter\nthis problem.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\subsection{Symmetry Handling}\nThe grid based methods has some limitation with the symmetry\nhandling, which was first pointed out by Gill et al. \\cite{PGPOPLE}.\nThis is induced by the transformation from the the angle portion of\ncoordinate to the cartesian coordinate, which is closely related to\nthe grid scheme.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Linear Scaling Scheme}\nSo far, the most plentiful discussions about to speeding up the\nnumerical quadrature methods is coming from Stratmann et\nal.\\cite{EGM}; which is the default choice taken by Gaussian\nincorporation\\cite{g03}. On the other hand, Q-CHEM\\cite{QCHEM}\ncompany also published some articles related to the same\nissue\\cite{IncDFT}. In Stratmann's paper, they presented several\ntechnics to speed up the calculation time, and they claimed that\nthey finally had achieving linear scaling in the calculations. These\ntechnics are not complicated, just as using some new weight function\nto replace the old and inefficient ones; the screen weight methods\netc.; which have been mentioned in the above content. Here in the\nfirst manuscript we do not carefully examine these technics, it will\nbe carefully discussed as we step into the concrete program writing.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%%% Local Variables: \n%%% mode: latex\n%%% TeX-master: \"../../main\"\n%%% End: \n", "meta": {"hexsha": "4ec2a8aedf6ae4be50a29b5b8356a672fa4b15df", "size": 15693, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "algorithm/technic/NumericalQuadrature.tex", "max_stars_repo_name": "murfreesboro/fenglai-note", "max_stars_repo_head_hexsha": "7bdf943f681e54948cd68775a31e4c93a53a13f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-16T07:23:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T07:23:48.000Z", "max_issues_repo_path": "algorithm/technic/NumericalQuadrature.tex", "max_issues_repo_name": "murfreesboro/fenglai-note", "max_issues_repo_head_hexsha": "7bdf943f681e54948cd68775a31e4c93a53a13f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "algorithm/technic/NumericalQuadrature.tex", "max_forks_repo_name": "murfreesboro/fenglai-note", "max_forks_repo_head_hexsha": "7bdf943f681e54948cd68775a31e4c93a53a13f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.185483871, "max_line_length": 83, "alphanum_fraction": 0.6994201236, "num_tokens": 4443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.3309017694292729}}
{"text": "%% Faire un historique des formulations faites.\n%% Formuler le problème à notre sauce et identifier les cas évoqués en intro en particularisant les modules tangents etc. a ce moment, parler des trajets de chargement et des types d'ondes\n\n\\section*{Introduction}\nIt has been shown throughout this manuscript that hyperbolic problems in solid mechanics are solved in a different manner depending on the numerical method employed. \nIn particular, irreversible deformations which are usually numerically computed based on well-known constitutive integrators, may greatly differ from one scheme to another even for one-dimensional problems.\nHowever, the accurate assessment of residual stresses and strains are of major importance for many industrial applications such as high-speed metal forming, crash-proof design or the study of the impact of earthquakes on structures.\nThe simulations performed in chapter \\ref{chap:chap4} emphasized the improvements enabled by the knowledge of the characteristic structure of the solutions of conservation laws, especially for elastoplastic solids.\n%Nevertheless, the introduction of the exact solution by means of approximate Riemann solvers is so far only possible for problems in one space dimension in elastic-plastic solids.\nNevertheless, the use of an elastic-plastic approximate Riemann solver is so far only possible for problems in one space dimension.\n\nThe purpose of this chapter is to identify typical behavior of the solutions of two-dimensional elastoplasticity problems under small strains.\n%It is believed that the knowledge one can get about these solutions will allow, through the better understanding of their mathematical features, the building of approximate numerical solutions embedding the sufficient amount of information in order to mimic as well as possible the analytical behavior.\nIt is believed that the knowledge of these solutions will allow, through the better understanding of their mathematical features, the building of approximate numerical solutions embedding a sufficient amount of information in order to mimic the analytical behavior.\nThis will be possible at a low computational cost provided that some key-properties of the exact solutions are clearly identified. \n\nThis chapter is organized as follows.\nA brief historical review of the solution of dynamic problems in two-dimensional elastic-plastic solids is made in section \\ref{sec:review}.\n%A brief historical review of the solution of plastic waves in two-dimension space is made in section \\ref{sec:review}.\nThen, the equations of plasticity are recalled in section \\ref{sec:charac_plast} so that the characteristic analysis, followed by the application of the method of characteristics, can be carried out.\nIn section \\ref{sec:stress_paths}, attention is paid to the evolution of stress components inside simple waves that might propagate by means of a mathematical study of the ODEs satisfied within these waves.\nSince the developments rapidly become cumbersome, the analysis is supplemented with numerical results in section \\ref{sec:stress_paths_num}.\n%Attention is next paid in section \\ref{sec:stress_paths} to the evolution of stress components through simple waves possibly arising in the solution. \nAt last, some identified trends are discussed at the end of the chapter in order to use them for building a dedicated Riemann solver. \n\n\\section{Historical review}\n\\label{sec:review}\n\\input{chapter5/review}\n\n\n%\\section{Key points of the chapter}\n%% Ne pas considérer les chocs plastiques mais uniquement les ondes simples\n%As a result, it is assumed that no stiffening occurs in the material in such a way that the concave hardening laws considered only yields simple waves and no shock waves.\n%In what follows, attention is paid to the simple wave solutions arising in the characteristic structure of hyperbolic problems in two-dimensional elastic-plastic solids.\n\n\\section{Elastic-plastic wave structure in two space dimensions}\n\\paragraph*{Key points of the chapter:} The simple wave structure in two-dimensional solids is studied by writing the governing equations of plane strain and plane stress problems in \\textbf{a unique generic framework}.\n%For that purposes, the governing equations of dynamics in elastoplastic media are written in such a way that plane strain and plane stress problems are included in a unique generic framework.\nThus, the works carried out on simple waves mentioned above, formulated in terms of elastoplastic softnesses, appear \\textbf{as particular cases of the present investigation}.\nAs a result, we shall refer to those existing solutions in order to confirm our development as much as possible.\n\n\\label{sec:charac_plast}\n\\input{chapter5/characteristic_analysis}\n\n\\section{Loading paths through simple waves}\n\\label{sec:stress_paths}\n\\input{chapter5/loading_paths}\n\n\n\\section{Numerical integration of stress paths}\n\\label{sec:stress_paths_num}\n\\input{chapter5/numerical_results}\n\n% \\section{Towards a two-dimensional elastoplastic Riemann solver}\n% \\label{sec:ep_Riemman_solver}\n% \\input{chapter5/riemann_solver}\n\n\n\\section{Conclusion}\n\n\\subsection{Summary of the chapter}\n\nIn this chapter, the characteristic structure of the solution of hyperbolic problems in elastic-plastic solids in two space dimensions has been highlighted.\nIt is known since the 50s that plastic flow in two-dimensional solids yields two families of waves whose speeds depend on the stress state, the slow and fast waves.\n%As a result, shock and simple waves may occur in an elastoplastic medium even for linear hardening material.\nIn addition, these plastic waves may have an impact on all stress components in contrast to elastic discontinuities, hence the name of combined-stress waves.\nDuring the 60s, attention has been paid to simple waves in particular two-dimensional problems thus providing, among others, solutions of Picard problems in an elastic-plastic medium undergoing step loadings \\cite{Clifton,Ting68,Ting73}. % Idem pour ting ? c'est dit dans l'intro ? voir ce qui est fait dans le 73\nThe singular nature of such problems lies in the fact that the characteristic structure of the solution depends on the external loading undergone.\nIndeed, it has been shown \\cite{Clifton} that boundary conditions can lead to plastic flow involving one fast, one slow, or both simple waves.\nTherefore, it is crucial to be able to identify typical stress paths followed in each simple wave in order to link the initial data to a given stress state, and subsequently to determine the occurring wave pattern.\n\n%Besides these works, investigations on plastic shocks have been carried out.\n%The existence of such solutions is due to the state law for the hydrostatic pressure which dominates deviatoric effects.\n\n\n$\\newline$\n%% Lin et Ballman\nBased on these works, an iterative Riemann solver \\cite{Lin_et_Ballman}, whose procedure has been recalled in section \\ref{sec:stress_paths_num}, has been developed for the numerical solution of the thin-walled tube problem. \nThis solver relies on the ability to connect a stationary state to initial data by a characteristic wave pattern.\n% L'idée ici c'est de généraliser cette approche pour tous les problèmes 2D\nFollowing this approach, identifying characteristic wave patterns for general elastoplastic problems in two space dimensions should allow to enrich the numerical solution with the knowledge of physics.\nFor that purpose, the characteristic analysis of two-dimensional problems in elastic-plastic materials with linear isotropic hardening under plane strain and plane stress, in projection in an arbitrary direction of space, has been carried out in section \\ref{sec:charac_plast}.\nFast and slow waves are also involved in the solution so that applying the method of characteristic through the simple waves provides a system of ODEs.\nIntegration of this system leads to integral curves in terms of velocity and stress components that are followed inside the combined-stress waves.\n%Integration of this system leads to combined stress paths that are followed between initial and final stress states on the one hand, and to the integral curves in terms of velocity components involving integral along those loading paths on the other hand.\nSpecializing the ODEs to one direction of a Cartesian grid, it has been shown in section \\ref{sec:stress_paths} that the loading paths satisfied through slow and fast waves are perpendicular in the stress space for both plane strain and plane stress.\nMoreover, it has been established that the stress paths exhibit particular behavior in the space $(\\sigma_{11},\\sigma_{22},\\sigma_{12})$, that is $d\\sigma_{11}=0$, $d\\sigma_{12}=0$ or $d\\sigma_{22}=0$, for special values of the components of the acoustic tensor.\nThese situations are achieved for different stress states depending on whether the problem involves plane stresses of plane strains as shown in section \\ref{sec:stress_paths}.\n\n$\\newline$\nThe complexity of the ODEs derived in section \\ref{sec:charac_plast} prevents identifying all the singularities which may occur along the loading paths.\nHence, the mathematical analysis has been supplemented with numerical results consisting of the integration of stress paths from arbitrary initial stress values lying on the initial yield surface, for the particular direction $\\vect{e}_1$.\n\n%% Thin-walled tube\nFirst, in section \\ref{sec:num_thin-walled} the loading paths resulting from the integration of the ODEs derived in section \\ref{sec:charac_plast} have been compared to those of Clifton \\cite{Clifton}.\nThe two different formulations, respectively based on elastoplastic stiffnesses and softnesses, show  good agreement.\n\n%% Cont. planes\nSecond, the evolution of stress components across fast and slow waves under plane stress has been looked at in section \\ref{sec:num_plane_stress}.\nIt appears that though the loading paths are rather complex in stress space through a fast wave, the stress evolution in the deviatoric plane is restricted to the initial yield surface until one direction of pure shear is reached.\nA singularity then occurs so that the numerical integration cannot be pursued.\nOn the other hand, the loading paths resulting from the integration of ODEs satisfied inside a slow wave exhibit complex shapes along which $\\sigma_{11}$ varies much less than the other stress components.\n\n%% Def. planes\nThird, the plane strain case has been considered in section \\ref{sec:num_plane_strain}.\nOnce again, the integral curves inside a fast wave show complex shapes in stress space, and an evolution restricted to the initial yield surface in the deviatoric plane.\nIn that case, however, the paths may follow a direction of pure tension/compression in the latter plane so that the plastic flow is radial for high values of the hardening modulus. \nIn contrast, the paths inside slow waves first rotate on the yield surface and then lead to a stress state of pure shear in the deviatoric plane.\n\n\\subsection{Towards a two-dimensional elastoplastic Riemann solver}\nThe physical structures emphasized in this chapter enable a better understanding of the propagation of waves in two-dimensional elastoplastic media, although further investigations are required.\nOn the other hand, the loading paths followed in fast and slow simple waves can be used in order to improve the numerical simulation of these problems.\n\n%% Lin et Ballman\nOne possibility is to generalize the approach proposed by Lin and Ballman \\cite{Lin_et_Ballman} based on the clues provided above.\nThe idea would be to successively assume stationary states of the Riemann problem in terms of stress $\\sigma_{11}$, $\\sigma_{12}$ and $\\sigma_{22}$ in order to build stress paths starting from the initial data.\nNamely, considering the direction $\\vect{e}_1$, the loading paths followed through a slow wave can be integrated backward starting from the guessed state.\nThen, different situations may occur:\n\\begin{itemize}\n\\item[(1-a)] the curve thus obtained crosses the initial yield surface at a point where $\\sigma_{22}$ satisfies the initial data.\n  In that case, the elastic discontinuities led to that stress state so that the characteristic structure corresponds to that depicted in figure \\ref{fig:charac}\\subref{subfig:charac1}.\n\\item[(1-b)] if on the other hand the point reached on the initial yield does not satisfy the initial stress $\\sigma_{22}$, a fast wave is added in order to browse the initial yield surface until the initial data is recovered.\n  This situation is depicted in figure \\ref{fig:charac}\\subref{subfig:charac2}.\n\\item[(2-a)] the curve resulting from the reverse integration across a slow wave intersects the plane $\\sigma_{12}=0$.\n  Then, assuming that the paths of slow waves are symmetric with respect to that plane, a fast wave is added in order to reach the initial yield surface at the initial value of $\\sigma_{22}$.\n  Indeed, the fast waves have been shown to yield horizontal paths in the ($\\sigma_{11},\\sigma_{12}$) plane, in such a way that only that type of wave enables the achievement of the initial elastic domain.\n  This also corresponds to figure \\ref{fig:charac}\\subref{subfig:charac2}.\n\\item[(2-b)] if at last, the guessed state is such that $\\sigma_{12}=0$, a fast wave allows reaching the initial yield surface as depicted in figure \\ref{fig:charac}\\subref{subfig:charac3}.\n\\end{itemize}\n\n\\begin{figure}[h!]\n  \\centering\n  \\subcaptionbox{One slow wave \\label{subfig:charac1}}{\\input{chapter5/pgfFigures/charac_structuresSl}} \\qquad \n  \\subcaptionbox{Both simple waves \\label{subfig:charac2}}{\\input{chapter5/pgfFigures/charac_structuresSlFa}} \\qquad \n  \\subcaptionbox{One fast wave \\label{subfig:charac3}}{\\input{chapter5/pgfFigures/charac_structuresFa}}\n  \\caption{Characteristic structures possibly occurring in two-dimensional elastic-plastic solids.}\n  \\label{fig:charac}\n\\end{figure}\nNotice however that the above elementary loading paths are based on strong assumptions about the symmetry of the loading paths that have not been shown so far.\nAs a result, additional work must be performed in order to develop this approach and to introduce it in numerical methods.\nMoreover, the hardening of the material may modify the behavior of the loading paths and have not been considered yet.\nAt last, the generalization of the approach followed in this chapter to more complex hardening models (kinematic, nonlinear etc.) and other yield surfaces would be very interesting for the understanding of the physics. \n%On the other hand, generalize the approach followed in this chapter to more complex hardening models (kinematic, nonlinear etc.) and other yield surfaces would be very interesting for the understanding of the physics.\n\n\n%%% Local Variables:\n%%% mode: latex\n%%% ispell-local-dictionary: \"american\"\n%%% TeX-master: \"../mainManuscript\"\n%%% End:\n", "meta": {"hexsha": "49f7093acc2f03405e2b5833a025a5613514e1e1", "size": 14835, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "manuscript/chapter5/mainChapter5.tex", "max_stars_repo_name": "adRenaud/research", "max_stars_repo_head_hexsha": "2f0062a1800d7a17577bbfc2393b084253d567f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-18T14:52:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-18T14:52:03.000Z", "max_issues_repo_path": "manuscript/chapter5/mainChapter5.tex", "max_issues_repo_name": "adRenaud/research", "max_issues_repo_head_hexsha": "2f0062a1800d7a17577bbfc2393b084253d567f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-01-07T13:11:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-07T13:11:11.000Z", "max_forks_repo_path": "manuscript/chapter5/mainChapter5.tex", "max_forks_repo_name": "adRenaud/research", "max_forks_repo_head_hexsha": "2f0062a1800d7a17577bbfc2393b084253d567f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 98.2450331126, "max_line_length": 313, "alphanum_fraction": 0.8094371419, "num_tokens": 3119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.33090176139532157}}
{"text": "\\documentclass[10pt,a4paper]{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage[english]{babel}\n\\usepackage{amsmath}\n\\usepackage{amsfonts}\n\\usepackage{amssymb}\n\\usepackage{graphicx}\n%\\usepackage{hyperref}\n\\usepackage[affil-it]{authblk}\n\\usepackage[left=2cm,right=2cm,top=2cm,bottom=2cm]{geometry}\n\n\n\\title{Semi-Lagrangian Exponential Integrator}\n\\author{P. S. Peixoto\\thanks{pedrosp@ime.usp.br}\\hspace{0.3cm} et al.}\n\\affil{College of Engineering, Mathematics and Physical Sciences - University of Exeter \\\\ Instituto de Matem\\'atica e Estat\\'\\i stica - Universidade de S\\~ao Paulo\n}\n\n\n\\begin{document}\n\\maketitle\n\n\\section{Introduction}\n\nPurpose: show a possible method to solve the nonlinear SWE with a semi-Lagrangian exponential integrator.\n\n\\section{Shallow Water Equations}\nConsider the shallow water equations for a planar domain written as\n\n\\begin{eqnarray}\nu_{t}+uu_{x}+vu_{y} &=&  fv -g\\eta_x,\\\\\nv_{t}+uv_{x}+vv_{y} &=& -fu- g\\eta_y, \\\\\n\\eta_{t}+u\\eta_{x}+v\\eta_{y}&=&-\\bar{\\eta}( u_x +v_y) -\\eta (u_{x}+ v_{y}), \n\\end{eqnarray}\nwhere the total fluid depth $h$ was decomposed into $h=\\eta+\\bar{\\eta}$, where $\\bar{\\eta}$ is a constant mean fluid depth and $\\eta$ is the perturbation. The velocities are given by $\\vec{v}=(u,v)$ and the gravity $g$ is assumed constant. The Coriolis parameter $f$ is a function of $y$. \n\nLet the variables to be in a Lagrangian reference frame, $\\vec{v}=\\vec{v}(t,\\vec{r}(t))$ and $\\eta=\\eta(t,\\vec{r}(t))$, where $\\vec{r}(t)=(x(t), y(t))$. Then we have for $\\eta$ (and analogously for $u$ and $v$) that the total derivative is given as\n\\begin{equation}\n\\frac{d\\eta}{dt}=\\frac{\\partial \\eta}{\\partial t}+\\nabla \\eta \\cdot \\vec{v} =  \n\\frac{\\partial \\eta}{\\partial t} + u \\frac{\\partial \\eta}{\\partial x}+v\\frac{\\partial \\eta}{\\partial y},\n\\end{equation}\nwhere we have used that $\\vec{r}^{\\,\\prime}(t)=(x'(t), y'(t))=\\vec{v}$. \nConsidering the total derivatives given along flow trajectories, we will call $\\gamma$ the parametrized trajectory curves in $(t, x, y)$ space, \n\\begin{equation}\n\\gamma(s)=(s, x(s), y(s)).\n\\end{equation}\n%For the line integrals we will require\n%\\begin{equation}\n%\\gamma'(s)=(1, x'(s), y'(s))=(1, u(s), v(s)),\n%\\end{equation}\n%where we used that the velocities may be obtained from the derivatives of the position with time, $u(s)=x'(s)$ and $v(s)=y'(s)$. We also have that\n%\\begin{equation}\n%\\|\\gamma'(s)\\|=\\sqrt{1 + u^2(s)+ v^2(s)}.\n%\\end{equation}\n%Thus, the integral along a trajectory between two time steps will have the property that\n%\\begin{equation}\n%\\int_{t_n}^{t_{n+1}} d\\gamma =\\int_{t_n}^{t_{n+1}}\\|\\gamma'(s)\\| ds= \\int_{t_n}^{t_{n+1}}\\sqrt{1 + u^2(s)+ v^2(s)} \\, ds .\n%\\end{equation}\nSo the total derivative can be written as\n\\begin{equation}\n\\frac{d}{dt}= \\gamma'(t) \\cdot \\left(\\frac{\\partial }{\\partial t}, \\frac{\\partial }{\\partial x},\\frac{\\partial }{\\partial y} \\right),\n\\end{equation}\nwith\n\\begin{equation}\n\\gamma'(s)=(1, x'(s), y'(s))=(1, u(s), v(s)).\n\\end{equation}\n\n\nAlso, we may express the linear wave operator as a matrix operator given by\n\\begin{equation}\nL=\n\\left(\\begin{array}{ccc}\n  0 & f & -g\\partial_{x}\\\\\n -f & 0 & -g\\partial_{y}\\\\\n -\\bar{\\eta} \\partial_{x}& -\\bar{\\eta} \\partial_{x} & 0  \n\\end{array}\\right).\n\\end{equation}\n\n\n This allows the shallow water equations to be written as\n \\begin{equation}\n\\frac{dU}{dt}=LU+N(U), \n \\end{equation}\n where \n \\begin{equation}\n U=\\left(\\begin{array}{c}\n  u\\\\\n v\\\\\n \\eta  \n\\end{array}\\right),\n \\end{equation}\n \n \\begin{equation}\n N(U)=\\left(\\begin{array}{c}\n  0\\\\\n 0\\\\\n -\\eta \\nabla\\cdot \\vec{v}  \n\\end{array}\\right).\n \\end{equation} \n\n\n\\section{General semi-Lagrangian formulation}\n\nFor a review and details about semi-Lagrangian methods, please see \\cite{Staniforth1991} and \\cite{Durran2010}. \n\n\\subsection{Trajectory calculations}\n\nTo calculate the trajectories one needs to solve the following ODE problem for $\\vec{r}(t)=(x(t), y(t))$,\n\\begin{equation}\n\\frac{d \\vec{r}(t)}{dt} = \\vec{v}(t, \\vec{r}(t)),\n\\end{equation}\nwith \n\\begin{equation}\n\\vec{r}(t_0) = (x(t_0), y(t_0)).\n\\end{equation}\n\nThis can be done through many of existing techniques (see \\cite{Staniforth1991} and \\cite{Durran2010}).  We will discuss two possibilities in this section.\n\n\\subsubsection*{Basic 2-time-level}\n\nA simple approach uses fixed point iterations using the method of \\cite{Robert1981}, but following a two-time level method as in \\cite{McDonald1987}. Integrating from time $t_n$ to time $t_{n+1}$ we have that\n\\begin{equation}\n\\vec{r}(t_{n+1})-\\vec{r}(t_{n}) = \\int_{t_n}^{t_{n+1}}\\vec{v}(t, \\vec{r}(t))dt.\n\\end{equation}\nNumerically we can calculate departure points $\\vec{r}_d=\\vec{r}(t_{n})$ using the arrival grid points $\\vec{r}_a=\\vec{r}(t_{n+1})$ and the trajectory midpoint $\\vec{r}_m=\\vec{r}(t_{n+1/2})$ as\n\\begin{equation}\n\\vec{r}_a-\\vec{r}_d = \\vec{v}(t_{n+1/2}, \\vec{r}_m) \\Delta t,\n\\end{equation}\nand\n\\begin{equation}\n\\vec{r}_a-\\vec{r}_m = \\vec{v}(t_{n+1/2}, \\vec{r}_m) \\frac{\\Delta t}{2},\n\\end{equation}\nand solving iteratively the equation for the midpoints with\n\\begin{equation}\n\\vec{r}^{\\,k+1}_m = \\vec{r}_a-\\vec{v}(t_{n+1/2}, \\vec{r}^{\\,k}_m) \\frac{\\Delta t}{2},\n\\end{equation}\nwith $\\vec{r}^{\\,0}_m=\\vec{r}_a$. Two or three iterations are usually enough to obtain a good estimate for the midpoint. The departure point can then be estimated by \n\\begin{equation}\n\\vec{r}_d=\\vec{r}_m - \\vec{v}(t_{n+1/2}, \\vec{r}_m) \\frac{\\Delta t}{2}=2\\vec{r}_m-\\vec{r}_a.\n\\end{equation}\nExtrapolation methods are required to obtain the velocity at the trajectory midpoints, this may be obtained as\n\\begin{equation}\n\\vec{v}(t_{n+1/2}, \\vec{r}^{\\,k}_m)=\\left(\\frac{3}{2}\\vec{v}(t_{n})-\\frac{1}{2}\\vec{v}(t_{n-1}) \\right)_m,\n\\label{eq:extrap_simp}\n\\end{equation}\nwhere the sub-index $_m$ indicates that once the extrapolation is done, it is then interpolated to the trajectory midpoints $\\vec{r}^{\\,k}_m$.\n\n%It is common that only the arrival and departure point informations are used, to reduce the amount of interpolations, so the interpolation to midpoints is substituted by averages of the values at the arrival and departure points, to yield,\n%\\begin{equation}\n%\\vec{v}(t_{n+1/2}, \\vec{r}^{\\,k}_m)=\\frac{1}{2}\\left( \\frac{3}{2}\\vec{v}(t_{n})-\\frac{1}{2}\\vec{v}(t_{n-1})\\right)  + \\frac{1}{2}\\left( \\frac{3}%{2}\\vec{v}(t_{n})-\\frac{1}{2}\\vec{v}(t_{n-1}) \\right)_*.\n%\\end{equation}\n\n\\subsubsection*{Stable Extrapolation Two-Time-Level Scheme}\n\\label{sec:stable}\nThe extrapolation scheme shown above tends to be unstable for large time steps for the nonlinear shallow water equations \\cite{Durran2010}. An alternative is the Stable Extrapolation Two-Time-Level Scheme (SETTLS) of \\cite{Hortal2002}, used in the ECMWF global model IFS.\n\nThis approach uses as extrapolation method along the trajectories, for any given function $\\phi$,\n\\begin{equation}\n\\phi(t_{n+1/2}, \\vec{r}_m)=\\frac{1}{2}\\left(2\\phi(t_{n}, \\vec{r}_d)-\\phi(t_{n-1}, \\vec{r}_d) + \\phi(t_{n}, \\vec{r}_a)\\right).\n\\end{equation}\nSo the velocity at the midpoints may be approximated as\n\\begin{equation}\n\\vec{v}(t_{n+1/2}, \\vec{r}^{}_m)=\\frac{1}{2} \\left(2\\vec{v}(t_{n}, \\vec{r}_d)-\\vec{v}(t_{n-1}, \\vec{r}_d) + \\vec{v}(t_{n}, \\vec{r}_a) \\right).\n\\end{equation}\n\nThe departure point can be obtained through an iterative procedure as before with, \n\\begin{equation}\n\\vec{r}^{\\,k+1}_d = \\vec{r}_a- \\frac{\\Delta t}{2} \\left(2\\vec{v}(t_{n}, \\vec{r}_d^{\\,k})-\\vec{v}(t_{n-1}, \\vec{r}_d^{\\,k}) + \\vec{v}(t_{n}, \\vec{r}_a) \\right),\n\\end{equation}\nwith first guess given using $\\vec{r}^{\\,0}_d=\\vec{r}_a$.\n\n%\\begin{equation}\n%\\vec{r}^{1}_d = \\vec{r}_a- \\frac{\\Delta t}{2} \\left(3\\vec{v}(t_{n}, \\vec{r}_a)-\\vec{v}(t_{n-1}, \\vec{r}_a)  \\right),\n%\\end{equation}\nThe fields to be calculated at the departure points, such as $\\vec{v}(t_{n}, \\vec{r}_d^{\\,k})$, will be done first calculating $\\vec{v}(t_{n})$ at the usual grid points, and then this will be interpolated to the departure points $\\vec{r}_d^{\\,k}$. We will denote this interpolation to departure points with a $*$, to give the following formulas\n\\begin{equation}\n\\vec{r}^{\\,k+1}_d = \\vec{r}_a- \\frac{\\Delta t}{2} \\vec{v}(t_{n} ) - \\frac{\\Delta t}{2} \\left(2\\vec{v}(t_{n})-\\vec{v}(t_{n-1})\\right)_*  .\n\\end{equation}\n\nA second order interpolation for the velocity is usually enough to ensure an overall second order accurate semi-Lagrangian method \\cite{Peixoto2014}.\n\n\n\\subsection{Integrating factor}\n\nLet $I$ be defined as the solution to the problem \n\\begin{equation}\n\\frac{dI}{dt}=-IL,\n \\end{equation}\n subject to\n\\begin{equation}\nI(t_n)=\\text{Id},\n \\end{equation}\n where $\\text{Id}$ is the identity matrix.\n \n \nConsidering the integral as being element-wise in $L$, it is easily verified that the problem has solutions of the form\n\\begin{equation}\nI=e^{-\\int_{t_n}^t L(\\gamma(s))\\, ds},\n\\end{equation} \nwhere $\\gamma(s)$ is the trajectory curve  parametrization related to $d/dt$. This $I$ will be denoted as the integrating factor.\n\n%since\n%\\begin{equation}\n%\\frac{d }{dt} \\int_{t_n}^{t} L_{ij}(\\gamma(s))ds =\n%L_{ij}(\\gamma(t)),\n%\\end{equation}\n%for $L_{ij}$, $i,j=1,2,3$ elements of $L$, \n\n%where the primitive is considered along trajectories ($\\gamma$) and are such that\n%\\begin{equation}\n%\\frac{D }{Dt}\\left(\\int L d\\gamma \\right)=L.\n%\\end{equation} \n\n%\n%Since $L=L(t,x(t), y(t))=L(\\gamma(t))$, considering the integral as being element-wise in $L$, we have for an element $L_{ij}$, $i,j=1,2,3$,\n%\\begin{equation}\n%\\frac{d }{dt} \\int_{t_0}^{t} L_{ij}(\\gamma(s))ds =\n%L_{ij}(\\gamma(t)),\n%\\end{equation}\n%and thus,  \n%\\begin{eqnarray}\n%\\frac{dI}{dt}&=&\\frac{d}{dt} \\left(e^{-\\int_{t_0}^t L(s, x(s), y(s))\\, ds} \\right) \\\\\n%& =& -e^{-\\int_{t_0}^t L(s, x(s), y(s))\\, ds} \\frac{d}{dt} \\left(\\int_{t_0}^t L(s, x(s), y(s))\\, ds \\right) \\\\\n%&=& -e^{-\\int_{t_0}^t L(s, x(s), y(s))\\, ds} L(t, x(t), y(t))\\\\\n%&=&-IL.\n%\\end{eqnarray}\n\nWe will also need the inverse of the integrating factor, which we will call $J$,  defined as\n\\begin{equation}\nJ=e^{\\int_{t_n}^t L(\\gamma(s))\\, ds},\n\\end{equation} \nfor which one readily sees that $IJ$ is the identity matrix.\n\n\\subsection{Semi-Lagrangian method}\nUsing the above defined integrating factor $I$, we may write the shallow water equations as\n\\begin{equation}\nI\\frac{dU}{dt}=ILU+IN(U), \n\\end{equation}\nwhich, using the definition of the integrating factor and the properties of the derivative, can be transformed to \n\\begin{equation}\nI\\frac{dU}{dt}=-\\frac{dI}{dt}U+IN(U), \n\\end{equation}\n\\begin{equation}\n\\frac{d(IU)}{dt}=I N(U).\n\\end{equation}\n\nTo derive the semi-Lagrangian formulation we assume that the solution is known at grid points at a time step $t_n$ and wish to calculate the solution at time $t_{n+1}$. Integrating the above equation along trajectories gives us \n\\begin{equation}\n(IU)^{n+1}-(IU)^{n}_{*}=\\int_{t_n}^{t_{n+1}} I(t, \\vec{r}(t))\\, N(U(t, \\vec{r}(t)))\\, dt,\n\\end{equation}\nwhere $*$ indicates that this value should be at trajectories departure points and the integral is along trajectories. The integrating factor $I$ is the identity at the departure points, so the resulting method for calculation of the new values at grid points can be calculated as\n\\begin{equation}\nU^{n+1}=J^{n+1}(  U)^{n}_{*}+J^{n+1}\\int_{t_n}^{t_{n+1}} \\, I(t, \\vec{r}(t))\\, N(U(t, \\vec{r}(t)))\\,dt .\n\\end{equation}\nWe see that this is very similar to the usual exponential integrator equation in Eulerian forms.\n\nTo solve this equation, the trajectories and departure points may be calculated with any of the several existing flavours. We will discuss possible approximation for the right hand side of the equation in what follows.\n\n\\section{Non-divergent flow case}\n\nHere we will analyse the case when the flow is non-divergent, therefore, $N(U)=0$, and we need to solve only\n\n\\begin{equation}\n\\frac{dU}{dt}=L U,\n\\label{eq:swe}\n\\end{equation}\nwhere all the non-linearities are in the material derivative.\n\n\n\\subsection{On a f-plane} \n\nConsider the shallow water equations given for a bi-periodic plane with $f$ constant. In this case $L$ is constant along the trajectories, so\n\\begin{equation}\nU^{n+1}=J^{n+1}U^{n}_{*},\n\\end{equation}\nwith\n\\begin{equation}\n J^{n+1}=e^{L\\Delta t}\n\\end{equation}\nand the method may be written as\n\\begin{equation}\nU^{n+1}=e^{L\\Delta t}(U)^{n}_{*}.\n\\end{equation}\n\nAlthough $e^{L\\Delta t}$ has constant coefficients, it includes differential operator and cannot be exchanged with the interpolation operator $*$, since the departure points locations are defined through nonlinear trajectories. \n\n\\subsection{On a variable $f$ scenario}\n\nWe will now allow the Coriolis parameter $f$ to vary in the $y$ direction, for example as in the $\\beta$-plane approximation $f=f_0+\\beta y$ or, on the spherical case, $f=2\\Omega \\sin \\theta$, where $\\theta$ is the latitude, and $\\Omega$ is the rotation rate of the Earth. In this case, $L$ is no longer constant along trajectories and the integrating factor needs to be approximated. \n\n\\subsubsection{$f$ constant along trajectories}\n\nConsidering that the trajectories spam a small region in space for which the variation of $f$ is small, we may approximate the integrating factor considering the Coriolis parameter given for the trajectory midpoint. That is\n\\begin{equation}\nJ^{n+1}=e^{\\int_{t_n}^{t_{n+1}}L(\\gamma(t))dt}  \\approx e^{L(\\gamma(t_{n+1/2})) \\int_{t_n}^{t_{n+1}}dt} = e^{L^{1/2}\\Delta t},\n\\end{equation}\n where $L^{1/2}$ is the linear operator calculated at the trajectory midpoint $\\vec{r}_m$. The resulting method is similar to the $f$-plane case,\n\\begin{equation}\nU^{n+1}=(e^{L^{1/2}\\Delta t} U)^{n}_{*}.\n\\end{equation}\n \nThe problem with this approach is that the exponential integrator will depend on the trajectory points, which can make it impractical with REXI, since these the midpoints are not necessarily grid points. \n\nIf we consider a constant approximation of $L$ along trajectories, with reference values given for the time $t_n$, then \n\\begin{equation}\nJ^{n+1}=e^{\\int_{t_n}^{t_{n+1}}L(\\gamma(t))dt} \\approx e^{L(\\gamma(t_n))\\int_{t_n}^{t_{n+1}}dt} = e^{L \\Delta t},\n\\end{equation}\nthen\n\\begin{equation}\nU^{n+1}=e^{L \\Delta t}( U)^{n}_{*}.\n\\end{equation}\nwhere $e^{L \\Delta t} U$ is the usual exponential integrator but considering the variations of $f$ given for the time $t_n$. \n\nThe consequences of the latter approximation is that the Rossby waves might not be well represented if the time-step is too large.\n\n\n\n\n\n\n\\section{Full nonlinear case}\n\nConsidering the above method, where $L$ is constant along trajectories, then we may write the the method for the full non linear case as \n\\begin{equation}\nU^{n+1}=e^{L \\Delta t}( U)^{n}_{*}+e^{L\\Delta t}\\int_{t_n}^{t_{n+1}} \\, I(t, \\vec{r}(t))\\, N(U(t, \\vec{r}(t)))\\,dt.\n\\end{equation}\n\n\\subsection{Standard Exponential Integrator Scheme}\nThis can be worked out in several ways (like Cox and Mathews). A simple way is to consider a forward Euler method for the nonlinear part, as \n\\begin{eqnarray*}\ne^{L\\Delta t}\\int_{t_n}^{t_{n+1}} \\, I(t, \\vec{r}(t))\\, N(U(t, \\vec{r}(t)))\\,dt &\\approx & \ne^{L\\Delta t} \\left( \\int_{t_n}^{t_{n+1}}  I(t, \\vec{r}(t))\\,dt \\right) N(U(t_n))_*\\\\\n&= & \ne^{L\\Delta t} \\left( \\int_{t_n}^{t_{n+1}} \\frac{d I(t, \\vec{r}(t))}{dt}L^{-1}\\,dt \\right) N(U(t_n))_*\\\\\n&\\approx & \ne^{L\\Delta t} \\left(  I(t_{n+1}, \\vec{r}(t_{n+1}))- I(t_{n}, \\vec{r}(t_{n})) \\right) L^{-1} N(U(t_n))_*\\\\\n&= & \ne^{L\\Delta t} \\left( e^{-L\\Delta t} - \\text{Id} \\right) L^{-1} N(U(t_n))_*\\\\\n&= & \n \\left(   \\text{Id} - e^{L\\Delta t}\\right) L^{-1} N(U(t_n))_*\\\\\n&\\approx & \n \\left(\\left(   \\text{Id} - e^{L\\Delta t}\\right) L^{-1} N(U(t_n))\\right)_*,\n\\end{eqnarray*}\nwhere we use that the $I$ is constant along trajectories (but might not be constant in the domain), resulting in \n\\begin{equation}\nU^{n+1}=(e^{L \\Delta t} U)^{n}_{*}+\\left(\\left(   \\text{Id} - e^{L\\Delta t}\\right) L^{-1} N(U)\\right)^{n}_*.\n\\end{equation}\nwhich can be calculated as\n\\begin{equation}\nU^{n+1}=\\left(e^{L \\Delta t} U+\\left(   \\text{Id} - e^{L\\Delta t}\\right) L^{-1} N(U)\\right)^{n}_*.\n\\end{equation}\n\nThe problem with using standard exponential integrator approaches, such as Cox and Mathews, is that they rely on the having $L^{-1}$, which, in the case of SWE, is not well defined in general, since the kernel is non trivial (it has all the geostrophic modes).\n\n\n\\subsection{Alternative scheme}\n\nIn semi-Lagrangian methods, it is common that the nonlinear terms are discretized as averages of the departure and arrival trajectory points given for the intermediate time $t_{n+1/2}$.\n\n% This is equivalent to using the trapezoidal rule for the integral of the nonlinear part as\n%\\begin{equation}\n%\\int_{t_n}^{t_{n+1}} \\, I(t, \\vec{r}(t))\\, N(U(t, \\vec{r}(t)))\\,dt \\approx \\frac{\\Delta t}{2} \\left[ I(t_{n+1}, \\vec{r}_a)\\, N(U(t_{n+1}, \\vec{r}_a)+I(t_{n-1}, \\vec{r}_d)\\, N(U(t_{n-1}, \\vec{r}_d))\\right]\n%\\end{equation}\n\nThis leads to the following approach,\n\\begin{equation}\nU^{n+1}=e^{L \\Delta t}(U)^{n}_{*}+\\frac{\\Delta t}{2}e^{L\\Delta t}\\left[ I(t_{n+1/2}, \\vec{r}_a)\\, N(U(t_{n+1/2}, \\vec{r}_a)+I(t_{n+1/2}, \\vec{r}_d)\\, N(U(t_{n+1/2}, \\vec{r}_d))\\right],\n\\end{equation}\nwhich, using the assumption of constant $L$ along trajectories,\n\\begin{equation}\n I(t_{n+1/2}, \\vec{r}(t))=e^{-L\\Delta t/2},\n\\end{equation} \nmay be simplified.\n\n% to\n%\\begin{equation}\n%U^{n+1}=e^{L \\Delta t}(U)^{n}_{*}+\\frac{\\Delta t}{2}e^{L\\Delta t/2}\\left[ N(U(t_{n+1/2}, \\vec{r}_a)+ N(U(t_{n+1/2}, \\vec{r}_d))\\right],\n%\\end{equation}\n%or\n%\\begin{equation}\n%U^{n+1}=\\left(e^{L \\Delta t} U^n +\\frac{\\Delta t}{2}e^{L\\Delta t/2}N(U)^{n+1/2}\\right)_{*}+\\frac{\\Delta t}{2}e^{L\\Delta t/2} N(U)^{n+1/2}.\n%\\end{equation}\n%\n%Since $N(U)$ is required at an intermediate time-step, this needs to be extrapolated from previous values of $N(U)$ given in time steps $n$ and $n-1$. Using the same extrapolation as in equation \\eqref{eq:extrap_simp}, the resulting method is\n%\\begin{equation}\n%U^{n+1}=\\left[e^{L \\Delta t} U^n +\\frac{\\Delta t}{2}e^{L\\Delta t/2}\\left(\\frac{3}{2}N(U^n)-\\frac{1}{2}N(U^{n-1})\\right)\\right]_{*}+\\frac{\\Delta t}{2}e^{L\\Delta t/2} \\left(\\frac{3}{2}N(U^n)-\\frac{1}{2}N(U^{n-1})\\right).\n%\\end{equation}\n\n\\subsection{Stable scheme}\n\n\nAs discussed in section \\ref{sec:stable}, using standard extrapolation schemes may lead to an unstable scheme. An option is to use the SETTLS approach, which would give\n\\begin{equation}\nU^{n+1}=e^{L \\Delta t}  U^{n}_{*}+\\Delta t \\, e^{L\\Delta t}\\left[  \\tilde{N}(U(t_{n+1/2}, \\vec{r}_m)\\right],\n\\end{equation}\nwhere \n\\begin{equation}\n \\tilde{N}(U(t_{n+1/2}, \\vec{r}_m)) = \n\\frac{1}{2}\\left[2 I(t_{n}) N(U(t_{n})- I(t_{n-1}) N(U(t_{n-1})) \\right]_*+ I(t_{n}) N(U(t_{n}),\n\\end{equation}\nwhere\n\\begin{equation}\n I(t_{n-1})=e^{L\\Delta t},\n\\end{equation} \n and\n\\begin{equation}\n I(t_{n})=\\text{Id}.\n\\end{equation} \nTherefore,\n\\begin{equation}\n \\tilde{N}(U(t_{n+1/2}, \\vec{r}_m)) = \n\\frac{1}{2}\\left[2 N(U(t_{n})- e^{L\\Delta t} N(U(t_{n-1})) \\right]_*+  N(U(t_{n}).\n\\end{equation}\n\nThe resulting method is \n\\begin{equation}\nU^{n+1}=e^{L \\Delta t} U_*^n+\\frac{\\Delta t}{2}\\,e^{L\\Delta t}\\left[ 2 N^n- e^{L\\Delta t}N^{n-1}\\right]_*+\\frac{\\Delta t}{2}N^n,\n\\end{equation}\nwhere\n\\begin{equation}\nN^n=N(U(t_n)).\n\\end{equation}\n\nTo save on calculations, one may calculate\n\\begin{equation}\nV^n= e^{L\\Delta t}N^n, \n\\end{equation}\n\\begin{equation}\nW^n= U^n+ \\Delta t \\,N^n- \\frac{\\Delta t}{2} V^{n-1}\n\\end{equation}\n\n\nand then\n\\begin{equation}\nU^{n+1}=e^{L \\Delta t} W^n_* + \\frac{\\Delta t}{2}N^n,\n\\end{equation}\ntherefore at each time step only 2 applications of exponential integrators are requires: (i) for $V^{n-1}$ and for $W^n_*$.\n\n\nFor the interpolation to departure points, a third order interpolation method is recommended to ensure overall second order accuracy of the semi-Lagrangian scheme \\cite{Peixoto2014}.\n%\n%\\subsection{Calculations of $e^{L\\Delta t}N(U)$ }\n%\n%Since $N(U)=(0,0,\\psi)$, it might be possible to simplify the calculation of $e^{L\\Delta t}N(U)$ in REXI.\n\n\\section{Lagrangian treatment of Coriolis term}\n\nThe treatment of variable Coriolis term is complicated with the above approach for 2 reasons: First, it needs to be approximated along the trajectories, which could affect the Rossby waves, second, the exponential integrator has to deal with non constant coefficient solvers, which can be far more complicated and expensive.\n\nFor these reasons, here we will briefly describe the possibility of treating the Coriolis term in a Lagrangian fashion.\n\n\\subsection{Planar case}\nWe may write the momentum equations as\n\n\\begin{eqnarray}\n\\frac{du}{dt}&=&  f(y)v -g\\eta_x,\\\\\n\\frac{dv}{dt} &=& -f(y)u- g\\eta_y, \n\\end{eqnarray}\nor in vector notation,\n\\begin{equation}\n\\frac{d\\vec{u}}{dt}+f(y)\\vec{k}\\times\\vec{u}=-\\nabla \\eta, \n\\end{equation}\nwhere $\\vec{u}=(u,v)$, and $\\vec{k}=(0,0,1)$ is a vector normal to the plane. Now notice that \n\\begin{equation}\n\\frac{d \\vec{r}}{dt} = \\vec{v},\n\\end{equation}\nso we have that\n\\begin{equation}\n\\frac{d\\vec{u}}{dt}+f(y)\\vec{k}\\times\\frac{d \\vec{r}}{dt}=-\\nabla \\eta, \n\\end{equation}\n\nIf $f(y)=f$ constant (f-plane approximation), then\n\\begin{equation}\n\\frac{d\\left( \\vec{u} + f\\vec{k}\\times \\vec{r}\\right)}{dt}=-\\nabla \\eta, \n\\label{eq:lag_coriolis_plan}\n\\end{equation}\nwhich means that the Coriolis term can be solved together with the lagrangian advected quantity. \n\nIf $f$ is to be assumed dependent on $y$, then the above equation \\eqref{eq:lag_coriolis_plan} only makes sense considering the assumption that $f(y)$ is constant along trajectories. \n\n\\subsection{Spherical case}\n\nAlthough it is not possible to consider the variable $f$ case lagrangianly on a plane, this is different for the sphere. It is described in \\cite{Temperton1997} how it is possible to treat the Coriolis term in a lagrangian way even in the variable $f$ condition. As a consequence, the exponential computational (REXI) would treat only the gravity waves, but not the Rossby ones.\n\nWe will briefly describe this case here (soon).\n\n\\section{Numerical results}\n\n\n\\subsection{Non-divergent flows}\n\nGeostrophically balanced solution of the nonlinear equations.\n\n\\begin{eqnarray}\nh&=&\\cos\\left( 2 \\pi (x/L_x+y/L_y)\\right)+ \\bar{\\eta}\\\\\nu&=&\\frac{2 g \\pi}{f_0 L_y} \\sin\\left( 2 \\pi (x/L_x+y/L_y)\\right)\\\\\nv&=&-\\frac{2 \\pi g}{f_0 L_x} \\sin\\left( 2 \\pi (x/L_x+y/L_y)\\right)\n\\end{eqnarray}\n\nThis test has trajectories given as straight lines, but these are not coinciding with the grid. Therefore, the departure point calculation is expected to be very accurate, and the errors associated with the semi-lagrangian are mainly related to interpolation errors of the field at the departure points. \n\nSince the flow is non-divergent, the non advective nonlinear term (divergence term of continuity equation) is assumed to be zero.\n\n\\begin{figure}\n\\centering\n\\includegraphics[scale=0.4]{geobalance_rotated_h.pdf} \\includegraphics[scale=0.4]{geobalance_rotated_hscale.pdf} \\hspace{1cm}\\includegraphics[scale=0.4]{geobalance_rotated_uv.pdf} \n\\caption{Height and velocity fields for steady state rotated non-divergent flow}\n\\end{figure}\n\n\\subsection{Non-divergent Forced flow }\n\\begin{eqnarray}\nh&=&\\cos(2 \\pi x/L_x)\\sin(2\\pi y /L_y) + \\bar{\\eta}\\\\\nu&=&-\\frac{2 g \\pi}{f_0 L_y} \\cos(2\\pi x/L_x) \\cos(2\\pi y /L_y)\\\\\nv&=& -\\frac{2 \\pi g}{f_0 L_x} \\sin(2\\pi x/L_x) \\sin(2\\pi y/L_y)\\\\\n\\end{eqnarray}\nwith forcings\n\\begin{eqnarray}\nf_h&=&0\\\\\nf_u&=&-\\frac{\\pi}{L_x}\\left(\\frac{2 \\pi g}{f_0 L_y}\\right)^2 \\sin(4\\pi x/L_x)\\\\\nf_v&=& \\frac{\\pi}{L_y}\\left(\\frac{2 \\pi g}{f_0 L_x}\\right)^2 \\sin(4\\pi y/L_y)\\\\\n\\end{eqnarray}\n\n\\subsection{Divergent flows}\n\n\n\\section{Concluding remarks}\n\n\n\n\n\n\\appendix\n\n\n\n\\bibliographystyle{alpha}\n\\bibliography{bibliography}\n% \n%where $U=(h, u, v)$ is the vector of unknowns containing the the velocity $\\vec{v}=(u,v)$ and the fluid height perturbation ($h$), $L$ is the linear shallow water operator given by\n%where $H_0$ is the mean water depth (assumed constant),  and the $D/Dt$ is the material (total) derivative given by\n%\\begin{equation}\n%\\frac{D}{Dt}=\\frac{\\partial }{\\partial t}+\\vec{v}\\cdot \\nabla.\n%\\end{equation} \n%  \n%We will consider $U$ in its moving/Lagrangian framework, that is, $U(\\vec{p}(t),t)$ depends on a position $\\vec{p}(t)=(x(t),y(t))$ which varies with time.\n%\n%%Let $I$ be the an indefinite primitive of the linear exponential along an arbitrary trajectory,\n%%\\begin{equation}\n%%I=\\oint e^{sL}L \\, ds,\n%%\\end{equation} \n%%such that \n%%\\begin{equation}\n%%\\frac{D I}{Dt}=e^{tL}L.\n%%\\end{equation}\n%\n%If $L$ is independent of space, therefore constant along the trajectory (for example on a f-plane), then\n%\\begin{equation}\n%\\frac{De^{-tL}}{Dt}=-e^{tL} L ,\n%\\end{equation}\n%which can be used to reduce \\eqref{eq:swe} by multiplying it by $e^{-tL}$, \n%\\begin{equation}\n%e^{-tL}\\frac{DU}{Dt}=e^{-tL} L U,\n%\\end{equation}\n%which can be written as\n%\\begin{equation}\n%e^{-tL}\\frac{DU}{Dt}=-\\frac{De^{-tL}}{Dt} U,\n%\\end{equation}\n%and therefore\n%\\begin{equation}\n%\\frac{D (e^{-tL}U)}{Dt}=0,\n%\\end{equation}\n%\n%Now integrating between times $t_n$ and $t_n{n+1}$ along an arbitrary trajectory gives\n%\\begin{equation}\n%(e^{-t_{n+1}L}U)^{n+1}=(e^{-t_nL}U)^{n}_{*},\n%\\end{equation}\n%where the star ($*$) indicates that the value is given for the departure point of the trajectory. Since in the f-plane the exponential is invariant along trajectories, we may write it as\n%\\begin{equation}\n%U^{n+1}=e^{t_{n+1}L}(e^{-t_nL}U)^{n}_{*},\n%\\end{equation}\n%\\begin{equation}\n%U^{n+1}=(e^{\\tau L}U)^{n}_{*},\n%\\end{equation}\n%where $\\tau=t_{n+1}-t_n$.\n%\n%\\section{Numerical implementation}\n%Given a state $U^n$ at time $t_n$, the first step is to propagate the exponential integrator, \n%\\begin{equation}\n%U_L^{n}=e^{\\tau L}U^n.\n%\\end{equation}\n%\n%Now for all grid points, the back-trajectory should be estimated to obtain their respective departure points. Any two time level trajectory calculation can be used here (usually 3 iterations of the nonlinear equation . \n%\n%\n%his can be multiplied by $e^{-t_nL}$\n\n\\end{document}\n", "meta": {"hexsha": "563619d3018f0b3d29bb40fa38162e4b5b13e62a", "size": 25783, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/rexi/swe_rexi_plane_semi_lagrangian/slrexi.tex", "max_stars_repo_name": "valentinaschueller/sweet", "max_stars_repo_head_hexsha": "27e99c7a110c99deeadee70688c186d82b39ac90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2017-11-20T08:12:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-11T15:32:36.000Z", "max_issues_repo_path": "doc/rexi/swe_rexi_plane_semi_lagrangian/slrexi.tex", "max_issues_repo_name": "valentinaschueller/sweet", "max_issues_repo_head_hexsha": "27e99c7a110c99deeadee70688c186d82b39ac90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-02-02T21:46:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T11:10:27.000Z", "max_forks_repo_path": "doc/rexi/swe_rexi_plane_semi_lagrangian/slrexi.tex", "max_forks_repo_name": "valentinaschueller/sweet", "max_forks_repo_head_hexsha": "27e99c7a110c99deeadee70688c186d82b39ac90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2016-03-01T18:33:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T22:20:31.000Z", "avg_line_length": 43.1876046901, "max_line_length": 385, "alphanum_fraction": 0.6830857542, "num_tokens": 9112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.33090176139532157}}
{"text": "\\documentclass[a4paper]{article}\n\n\\usepackage{amsmath, amssymb}\n\\usepackage{booktabs}\n\\usepackage{siunitx}\n\\usepackage{pgfplots, pgfplotstable}\n\n\\def\\mean#1{\\left< #1 \\right>}\n\\sisetup{\n    round-mode=places,\n    round-precision=1\n}\n\n\\title{Investigating the Effect of String Tension on Fundamental Frequency}\n\\date{18 March 2015}\n\\author{Tarik Onalan}\n\n\\begin{document}\n    \\maketitle\n    \\section{Introduction}\n        \\subsection{Purpose}\n            Understand how string tension affects the fundamental frequency of the\n            string.\n        \\subsection{Hypothesis}\n            As tension increases, the fundamental frequency of the string will also\n            increase.\n        \\subsection{Variables}\n            \\textbf{Independent Variable}\n            \\begin{itemize}\n                \\item Tension [\\si\\N]\n            \\end{itemize}\n            \\textbf{Dependent Variable}\n            \\begin{itemize}\n                \\item Fundamental frequency [\\si\\hertz]\n            \\end{itemize}\n            \\textbf{Controlled Variables}\n            \\begin{itemize}\n                \\item String length [\\SI{0.50}{\\m}]\n                \\item String mass [\\SI{0.085}{\\kg}]\n                \\item Type of string\n            \\end{itemize}\n    \\section{Materials}\n        \\begin{itemize}\n            \\item 1 $\\cdot$ \\SI{0.50}{\\m} string\n            \\item 1 $\\cdot$ pitch sensor\n            \\item 1 $\\cdot$ spring scale\n        \\end{itemize}\n    \\section{Procedure}\n        \\begin{enumerate}\n            \\item Turn on pitch sensor\n            \\item Tighten string to \\SI{0}{\\N}\n            \\item ``Pluck'' string\n            \\item Record frequency\n            \\item Repeat steps 2-4 with \\SI{5}{\\N}, \\SI{10}{\\N}, and \\SI{15}{\\N}\n            \\item Repeat steps 2-5 as necessary for data collection\n        \\end{enumerate}\n    \\section{Data}\n        \\begin{center}\n            Table 1: Raw Data:\n            \\pgfplotstabletypeset[\n                multicolumn names,\n                col sep=comma,\n                display columns/0/.style={\n                    column name=Tension,\n                    column type={S},string type},\n                display columns/1/.style={\n                    column name=Trial 1,\n                    column type={S},string type},\n                display columns/2/.style={\n                    column name=Trial 2,\n                    column type={S},string type},\n                display columns/3/.style={\n                    column name=Trial 3,\n                    column type={S}, string type},\n                display columns/4/.style={\n                    column name=Average,\n                    column type={S}, string type},\n                columns/t/.append style={\n                    postproc cell content/.append style={\n                        /pgfplots/table/@cell content/.add={}{$\\pm0.1$}\n                    }\n                },\n                columns/1/.append style={\n                    postproc cell content/.append style={\n                        /pgfplots/table/@cell content/.add={}{$\\pm0.1$}\n                    }\n                },\n                columns/2/.append style={\n                    postproc cell content/.append style={\n                        /pgfplots/table/@cell content/.add={}{$\\pm0.1$}\n                    }\n                },\n                columns/3/.append style={\n                    postproc cell content/.append style={\n                        /pgfplots/table/@cell content/.add={}{$\\pm0.1$}\n                    }\n                },\n                columns/avg/.append style={\n                    postproc cell content/.append style={\n                        /pgfplots/table/@cell content/.add={}{$\\pm0.1$}\n                    }\n                },\n                every head row/.style={\n                    before row={\\toprule},\n                    after row={\n                         & \\si\\s & \\si\\s & \\si\\s & \\si\\s\\\\\n                        \\midrule}\n                },\n                every last row/.style={after row=\\bottomrule}\n            ]{foobar.csv}\n        \\end{center}\n        \\begin{tikzpicture}\n            \\begin{axis}[\n                scale=1.75,\n                title={Fundamental Frequency Relative to String Tension},\n                xlabel={Tension [\\si\\N]},\n                ylabel={Fundamental Frequency [\\si\\hertz]},\n                legend pos=south east\n            ]\n                \\addplot[\n                    color=blue,\n                    only marks\n                ] plot [\n                    error bars/.cd,\n                        x dir=both,\n                        y dir=both,\n                        x explicit,\n                        y explicit,\n                        x fixed=0.1,\n                        y fixed=0.1\n                ] table [\n                    x=t,\n                    y=avg,\n                    col sep=comma\n                ]{foobar.csv};\n                \\addplot[\n                    color=red,\n                    mark=none,\n                    very thick,\n                    domain=0:15\n                ]{1.97318355*sqrt(1.50045554*x)};\n                \\addlegendentry{Average}\n                \\addlegendentry{$1.97\\sqrt{1.50x}$}\n            \\end{axis}\n        \\end{tikzpicture}\n    \\section{Calculations}\n        \\subsection{Average}\n            \\begin{equation}\n                \\mean{\\si\\hertz(\\si\\N)}\n            \\end{equation}\n            \\begin{equation}\n                \\frac{\\displaystyle\\sum_i{\\si\\hertz(\\si\\N)}}{i}\n            \\end{equation}\n            \\begin{equation}\n                \\frac{\\si\\hertz(\\si\\N_1)+\\si\\hertz(\\si\\N_2)+...+\\si\\hertz(\\si\\N_{i-1})+\\si\\hertz(\\si\\N_i)}{i}\n            \\end{equation}\n        \\subsection{Error and Minimization}\n            \\begin{center}\n                Error was calculated using sum squared error, which is defined as follows:\n                \\begin{equation}\n                    E=\\displaystyle\\sum_{i=1}^n{(y_i-f(x_i))^2}\n                \\end{equation}\n                A program carried out the minimization of the above function, which entails\n                tracing the derivative of the function with respect to a given parameter\n                $k \\in \\{a, b, c, d, ...\\}$ to the local minima of the function\n                \\begin{equation}\n                    E'=\\frac{\\partial}{\\partial k}(\\displaystyle\\sum_{i=1}^n{(y_i-f(x_i))^2})\n                \\end{equation}\n            \\end{center}\n        \\subsection{Line of Best Fit}\n            \\begin{center}\n                When choosing a model for my data, I had to keep in mind the basic\n                features.  I knew that the tension and fundamental frequency were related\n                by the function\n                \\begin{equation}\n                    ?(x)=\\frac{\\sqrt{\\frac{T}{m/L}}}{2L}\n                \\end{equation}\n                where $T$ is tension, $m$ is mass, and $L$ is length. Because of this,\n                I assumed my data would also follow a square-root function.\n                \\\\\n                I constructed my function like so:\n                \\begin{equation}\n                    f(x)=a\\sqrt{bx+c}+d\n                \\end{equation}\n                As a control, I also constructed a linear function:\n                \\begin{equation}\n                    g(x)=a(bx+c)+d\n                \\end{equation}\n                As I had predicted, the square-root function yielded much less error\n                when modeling the data, which is why I chose it as my model. The errors\n                for the square-root and linear functions are shown below:\n                \\\\\n                \\bf{Error}\n                \\\\\n                \\begin{tabular}{|c|c|}\n                    \\hline\n                    $f(x)$ & $g(x)$\n                    \\\\\\hline\n                    $\\num[round-precision=5]{0.00471860747464}$ & $\\num[round-precision=5]{3.94833443333}$\n                \\end{tabular}\n            \\end{center}\n    \\section{Conclusion}\n        My hypothesis, that the fundamental frequency of the string would increase as the\n        tension of the string increased, was correct. The graph of the data shows\n        a marked upward trend. When there was \\SI{0.0}{\\N} of force on the string, the\n        fundamental frequency was \\SI{0.0}{\\hertz}. However, when the tension was increased\n        to \\SI{15.0}{\\N}, the fundamental frequency increased to \\SI{9.3}{\\hertz}. Also,\n        given that the data very closely matches the square-root used to model it, and\n        the square root function is a monotonically increasing function, it would be\n        safe to assume that the relationship shown by the data, that the fundamental\n        frequency increases as string tension increases, is true.\n        \\\\\n        A difficulty I experienced with this lab was keeping the spring scale still\n        while conducting a trial. While I did have it attached to an immobile object,\n        the scale was prone to slippage, and would occasionally slacken the string.\n        This is slightly shown in the data, where there are dips in the fundamental\n        frequency (see \\SI{5}{\\N} trial 2, \\SI{10}{\\N} trial 1, \\SI{15}{\\N} trial 2).\n        However, these errors are not large enough to nullify my conclusion.\n        \\\\\n        In the future, I would like to be able to conduct more trials, so any errors\n        like the one described above could be ``averaged away'', per se. While the\n        errors in my data were not particularly large, it would have been better to\n        conduct more trials to see exactly where the fundamental frequency was.\n\\end{document}\n", "meta": {"hexsha": "9c93d89b79b2f2ff906ede56f1ca305c66b8b223", "size": 9558, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "2014-2015/Physics/Waves/Wave_Lab.tex", "max_stars_repo_name": "QuantumPhi/school", "max_stars_repo_head_hexsha": "a1bec6b1ed4ea843cb291babf7b7b9925e370749", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2014-2015/Physics/Waves/Wave_Lab.tex", "max_issues_repo_name": "QuantumPhi/school", "max_issues_repo_head_hexsha": "a1bec6b1ed4ea843cb291babf7b7b9925e370749", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2015-04-10T07:28:17.000Z", "max_issues_repo_issues_event_max_datetime": "2015-04-10T07:30:10.000Z", "max_forks_repo_path": "2014-2015/Physics/Waves/Wave_Lab.tex", "max_forks_repo_name": "QuantumPhi/school", "max_forks_repo_head_hexsha": "a1bec6b1ed4ea843cb291babf7b7b9925e370749", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.48, "max_line_length": 109, "alphanum_fraction": 0.5012554928, "num_tokens": 2192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.33090176139532157}}
{"text": "\\chapter{Development Plan}\n\\label{ch:developmentplan}\n\n\\begin{wrapfigure}{r}{0.3\\textwidth}\n  \\vspace{-40pt}\n  \\begin{center}\n    \\includegraphics[width=0.25\\textwidth]{graph/phoalgorithm}\n  \\end{center}\n  \\caption{Toolkit Outline}\n  \\vspace{-90pt}\n\\end{wrapfigure}\n\nThis provides a general outline of the Photometry Toolkit and how I\ncurrently envision it working.\n\n\\section{Algorithm Outline}\n\n\\begin{enumerate}\n\\item Stereo Processing\n\\item Initialize Photometry\n  \\begin{itemize}\n    \\item \\textbf{Initialize DEMs and Blend} \\hfill \\\\\n      This should be done with the already provided The DEM variance found is optional written here.\n      \\texttt{image2plate} and \\texttt{platereduce}.\n    \\item \\textbf{Ingest DRGs} \\hfill \\\\\n      This involves thresholding the DRG for shadows and then solves\n      for a grassfire weighting. The weighting and the masking are the\n      same thing and should be stored inside the alpha channel for\n      quick access. The masks used is optional written.\n    \\item \\textbf{Seed Reflectance Images} \\hfill \\\\\n      Load up camera models, and use SPICE to determine Sun's\n      location.\n    \\item \\textbf{Seed Exposure Time} \\hfill \\\\\n      Somehow uses ratio of reflectance returns from previous step.\n    \\item \\textbf{Seed Albedo Image} \\hfill \\\\\n      Use this equation:\n      \\[\n      A_{ij}=\\sum_{k}\\frac{I^{k}_{ij}}{R^{k}_{ij}T^{k}}\n      \\]\n  \\end{itemize}\n\\item Iterate Solution\n  \\begin{itemize}\n    \\item \\textbf{Re-estimate Exposure} \\hfill \\\\\n      \\[\n      \\hat{T^{k}} = T^{k}+\\frac{\\sum_{ij}(I^{k}_{ij}-T^{k}A_{ij}R^{k}_{ij})A_{ij}R^{k}_{ij}S^{k}_{ij}}{\\sum_{ij}(A_{ij}R^{k}_{ij}S^k_{ij})^{2}}\n      \\]\n    \\item \\textbf{Re-estimate Albedo} \\hfill \\\\\n      \\[\n      \\hat{A_{ij}} = A_{ij}+\\frac{\\sum_{k}(I^k_{ij}-T^kA_{ij}R^k_{ij})T^kR^k_{ij}S^{k}_{ij}}{\\sum_{k}(T^kR^k_{ij}S^k_{ij})^2}\n      \\]\n    \\item \\textbf{Re-estimate DEM} \\hfill \\\\\n      \\emph{MAGIC!}\n    \\item \\textbf{Re-calculate Reflectance} \\hfill \\\\\n      Refer back to the cameras.\n    \\item \\textbf{Calculate Error} \\hfill \\\\\n      Error is used to determine if we're improving.\n      \\[\n      \\epsilon=\\sum_{k}\\sum_{ij}((I^k_{ij}-A_{ij}T^kR^k_{ij})S^k_{ij})^2\n      \\]\n  \\end{itemize}\n\\end{enumerate}\n\n\\section{Content of Files}\n\nThese files represent the results and working files from one session\nof the Photometry Toolkit. One project is inside a directory\nmasquerading as file with extension \\texttt{.ptk}. Here is a list of\nthe possible contents contents. These files are only created one need.\n\n\\begin{itemize}\n  \\item \\textbf{photometrytk.dat} \\hfill \\\\\n    This is a binary file written with google protobuf. This contains\n    all the meta information about a PhoTK project. It is also what is\n    served and modified as a service. The reason for this extra\n    complexity is that multiple processes on multiple machines will be\n    trying to access this file.\n  \\item \\textbf{photometrytk.bak} \\hfill \\\\\n    Back up file of \\texttt{photometrytk.dat} that is written\n    periodically in the case of a fault. Users can rename this file to\n    \\texttt{photometrytk.dat} if they think the original file is\n    corrupt.\n  \\item \\textbf{Albedo.plate} \\hfill \\\\\n    Is a PixelGrayA<uint8> platefile. This contains the final result of\n    a mosaic.\n  \\item \\textbf{DEM.plate} \\hfill \\\\1\n    Is a PixelGrayA<int16> platefile. This contains the input DEM\n    platefile. \\emph{There is currently not a complete idea about how this\n    is to be made or used by PhoTK.}\n  \\item \\textbf{DEMVariance.plate} \\hfill \\\\\n    Is a PixelGrayA<int16> platefile. \\emph{This is still in design.}\n  \\item \\textbf{DRG.plate} \\hfill \\\\\n    Is a PixelGrayA<uint8> platefile. It contains the input images.\n  \\item \\textbf{Reflectance.plate} \\hfill \\\\\n    Is a PixelGrayA<uint8> platefile. \\emph{This is still in design.}\n  \\item \\textbf{Error.plate} \\hfill \\\\\n    Is a PixelGrayA<uint8> platefile. \\emph{This is still in design.}\n\\end{itemize}\n\nThe platefiles Albedo, DEM, and DEMVariance are very similar and\noperate like normal plates do. These files are global image mosaics\nwhere the highest transaction ID represents the current working\nversion.\n\n%% DEMVariance and Mask are both helpful plate files that are\n%% used for reporting; but they're not used again after the\n%% initialization step.\n\nThe platefiles DRG, Reflectance, and Error are a little more\ntricky. They represent multiple K Cameras and their history. Their\ntransaction IDs involve a little math so that $ID_{transaction} =\n100*k+i$. Where $k$ is the camera number and $i$ is the iteration\nnumber. We provide only enough room for a hundred transactions.\n\n%% There's also one other file, the \\emph{PhoFile} which contains most of\n%% the project information. If your familiar with the original Photometry\n%% module, this is the model params and the global params stitched\n%% together. I imagine this this file will probably use\n%% proto-buffers. Here's an outline of the contents.\n\n%% \\begin{itemize}\n%%   \\item PhoFile \\hfill \\\\\n%%     \\begin{description}\n%%       \\item[Project Message] \\hfill \\\\\n%%         This contains Datum along with various information transaction\n%%         IDs.\n%%       \\item[Repeated Camera Message] \\hfill \\\\\n%%         This contains the exposure time along with the Vector3 for the\n%%         Sun Position and the Spacecraft Position.\n%%     \\end{description}\n%% \\end{itemize}\n\n\\section{Executables}\n\n%% \\begin{wrapfigure}{r}{0.5\\textwidth}\n%%    \\begin{center}\n%%      \\includegraphics[width=0.5\\textwidth]{graph/exec_init}\n%%    \\end{center}\n%%    \\caption{Initialization Executables}\n%% \\end{wrapfigure}\n\nEverything inside the Photometry Toolkit will hopefully fit\ninside 2 python scripts, \\texttt{phoinit.py} and\n\\texttt{phosolve.py}. As expected, \\texttt{phoinit.py} creates all the\nfiles to start with. \\texttt{phosolve.py} performs all the\niterations. In the end when the user wants the results, they must\nperform \\texttt{snapshot} or \\texttt{plate2tile} to get the results.\n\nAt this time of writing, only \\texttt{phosolve.py} has been\nwritten. Everything is still largely manual and requires some thought\nby the user. The rest of this section outlines how to do some tasks\nthat will hopefully add up to a full PhotometryTK session.\n\n\\subsection{Creating a mosaicked DEM}\n\nThis step is not currently used, but I thought it was worth noting as\nthere are a few tricks. Mosaicking images in platefiles,is currently\ndone with a utility called \\texttt{platereduce}. It is good for\ncalculating weighted averages or weighted variances. Calculating\nvariances is mostly just useful for calculating DEM precision. If you\nare master of \\texttt{snapshot}, you'll find that using\n\\texttt{platereduce} to be very similar.\n\nI assume you have a working \\texttt{index\\_server} setup. The first\nsteps are to apply \\texttt{grassfirealpha} to all input images. This\ncreates an alpha channel with feathered weights. The weights are\nhighest value in the center of the image and lowest value near the\nedge. After that we'll enter all the alpha'd images into a single\nplatefile. I'm using \\texttt{xargs} to make this step multiprocess so\nI can utilize my entire machine. The \\texttt{-P} option is the number\nof simultaneous processes to have running. Scale that setting to the\nappropriate value for your machine.\n\n\\begin{verbatim}\n  > echo *DEM.tif | xargs -n1 -P15 grassfirealpha\n  > echo *grass.tif | xargs -n1 -P15 image2plate -o pf:///index/DEM_blend.plate \\\n    --file tif -m equi\n\\end{verbatim}\n\nNotice on \\texttt{image2plate} that I set the output platefile to a\nTIF. This is important as the default option of PNG will shave bits on\nalpha'd values. I'm also using the 'equi' output option for an\nequirectangular projection. The default is to use a TOAST projection.\n\nWe are now ready to run \\texttt{platereduce}. The options\n\\texttt{begin\\_transaction} and \\texttt{end\\_transaction} specify the\nrange of transaction IDs to read as input. The \\texttt{transaction-id}\noption specify the output transaction ID to use.\n\nReducing plate can be a very slow task, because of this we'll be doing\nit in parallel with multiple commands. This requires us to tell the\n\\texttt{index\\_server} by hand when we are starting a transaction and\nending one. Notice how this is done if the following example.\n\n\\begin{verbatim}\n  > platereduce pf:///index/DEM_blend.plate -t 2000 --start \"Averaging DEMs\"\n  > for i in {0 .. $(NUM_LEVELS)}; do platereduce --end_t 1999 -t 2000\n       pf:///index/DEM_blend.plate -f WeightedAvg & done\n  > platereduce pf:///index/DEM_blend.plate -t 2000 --finish\n\\end{verbatim}\n\nAt this point the averaged DEM should be in transaction ID 2000 and it\naveraged all transaction IDs between 0 and 1999.\n\n\\subsection{Creating a PhotometryTK project}\n\nCreating a project is done with the command \\texttt{phoinitfile}. With\nthis command you set what reflectance type you are solving for. You\nalso specify which map projection to use for the project file. Current\noptions are TOAST, Plate Equirectangular, and Polar. You also specify\nthe number iterations to use for solving for the solution\nhere. \\emph{The number of iterations is not changeable after this\n  step.}\n\n\\begin{verbatim}\n  > phoinitfile usgspolar -m polar --max 100\n\\end{verbatim}\n\nAt this point we are ready to start serving the project out. This is\naccomplished with the utility called \\texttt{ptk\\_server}. The PTK\nserver is both the platefile index server and PhoTK project file\nserver. \\emph{You will not be able to run another instance reliably of\n  \\texttt{index\\_server} at the same time as \\texttt{ptk\\_server}.} It\nis possible that you might have an exchange name\ncollision. \\emph{Currently, PhoTK does not support the use of ZMQ\n  urls.}\n\n\\begin{verbatim}\n  > ptk_server usgspolar.ptk --url pf:///polar\n\\end{verbatim}\n\nThe PTK server only serves one project at a time, therefor the first\nargument is the input project file \\emph{(that is secretly a\n  directory)}. The second argument specify the URL prefix we will be\nusing for this project. A later points we will be needing our\nproject's URL. It is the combination of the URL prefix and then the\nproject file's name. For this example it is: \\texttt{pf:///polar/usgspolar.ptk}\n\nAt this point we are ready to start inserting our input images into\nthe project. This is done with \\texttt{phodrg2plate}. This is a clone\nof \\texttt{image2plate} but it gets most of its settings from the\nserved project file. Here's an example of me inserting files.\n\n\\begin{verbatim}\n  > echo *.tif | xargs -n1 -P15 phodrg2plate pf:///polar/usgspolar.ptk\n\\end{verbatim}\n\nIf you look inside the project file, you'll see that the platefile\n\\texttt{DRG.plate} has been created.\n\n\\subsection{Solving a PhotometryTK project}\n\n%%\\begin{wrapfigure}{r}{0.4\\textwidth}\n  \\begin{center}\n    \\includegraphics[width=0.4\\textwidth]{graph/exec_solve}\n  \\end{center}\n%%\\caption{Iteration Executables}\n%%\\end{wrapfigure}\n\nRunning the actually iterations of solving is pretty easy since it is\ncurrently hidden away in a python script. The file script\n\\texttt{phosolve.py} does all the steps of re-estimating exposure and\nupdating albedo. In the future, calculating reflectance and\nshape-from-shading will be inserted as optional steps in this file.\n\n\\begin{verbatim}\n  > phosolve.py --threads 15 --level 9 --iter 100 pf:///polar/usgspolar.ptk\n\\end{verbatim}\n\nThe level option is just what level of the image pyramid we wish to\nperform our calculations. The lower the number \\emph{(the higher up\n  the pyramid)} will increase the speed at which things are\nprocessed. However there is more likely a chance of error. I usually\nrun my sessions at about two thirds down the pyramid.\n\nAfter this step is completed you will find that \\texttt{Albedo.plate}\nhas been created in your project file. Viewing it can be\ntricky. \\emph{(In my example, the Albedo's url will be\n  pf:///polar\\_index/Albedo.plate.)} However you will find that only\none level of the pyramid has actually be populated. That makes it\ndifficult to locate that solution. Things are easier for the viewer if\nyou mipmap the solution up the pyramid.\n\n\\begin{verbatim}\n  > pmipmap --level 9 --threads 15 pf:///polar_index/Albedo.plate\n\\end{verbatim}\n\nViewing should now be much easier in VWV.\n\n\\begin{verbatim}\n  > vwv pf:///polar_index/Albedo.plate\n\\end{verbatim}\n\n\\subsection{Using ZMQ instead}\n\nThe above examples are using RabbitMQ for the message passing. I've\nsince become a fan of using ZeroMQ as it doesn't require a server to\nbe started. Remember that RabbitMQ has an erlang executable running in\nthe background that occasionally crashes after a length of time.\n\nSo here's the above examples rewritten to show how to use ZMQ, however\nnot everything works at this point in time.\n\n\\begin{verbatim}\n  > phoinitfile secret_base -m polar --max 100\n  > ptk_server secret_base.ptk --url zmq://*.5566\n\nIn new terminal:\n  > parallel -j -2 phodrg2plate zmq://localhost:5566/secret_base.ptk ::: *.tif\n  > phoitalbedo zmq://localhost:5566/secret_base.ptk -l 10\n\\end{verbatim}\n\nUnforunately, \\texttt{vwv} across ZMQ doesn't seem to be working at all. For\nthe time being I just kill the \\texttt{ptk\\_server} and run \\texttt{vwv} on the\nplatefile directly.\n\n\\subsection{Running once at high resolution and extracting result}\n\nMeh.\n\n%% \\subsection{An example run of PhotometryTK}\n\n%% Eventually the the python scripts should negate the need for\n%% this. Here are the actual executables called and the settings to\n%% use. Delete this section some time in the future.\n\n%% \\begin{verbatim}\n%%   > sudo $(START UP AMQP COMMAND)\n%%   > (in a different terminal) index_server $(PROJECT DIR)\n%%   > cd $(DEM_DIR)\n%%   > ls *DEM.tif | xargs -n 1 -P 10 grassfirealpha --nodata -10000\n%%   > ls *grass.tif | xargs -n 1 -P 10 image2plate -o\n%%       pf://index/DEM_blend.plate --file tif -m equi\n%%   > for i in {0..$(NUM LEVELS)}; do platereduce --end_t 1999 -t 2000\n%%       pf://index/DEM_blend.plate -l $i & done\n%%   > plate2plate -o pf://index/DEM.plate -i pf://index/DEM_blend.plate\n%%       --filter identity --bottom 10 --skim\n%%   > (in other terminal, kill index_server)\n%%   > rm -rf DEM_blend.plate\n%%   > (in other terminal, restart index_server)\n%%   > phoinitfile debug_apollo\n%%   > // Below can be ran in parallel\n%%   > echo *.tif | xargs -n1 echo |\n%%       xargs -n1 -P10 phodrg2plate pf://ptk/project.ptk\n%%   > echo {0..9} | xargs -n1 echo |\n%%       xargs -n1 -P10 -I{} phoitalbedo -j {} -n 10 pf://ptk/project.ptk\n%%   > mipmap pf://index/Albedo.plate\n%% \\end{verbatim}\n", "meta": {"hexsha": "90786385ef953b348263a5e370e488bef882797b", "size": 14512, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/photometry/developmentplan.tex", "max_stars_repo_name": "nasa/StereoPipeline", "max_stars_repo_head_hexsha": "8b9c0bcab258c41d10cb2973d97722765072a7bf", "max_stars_repo_licenses": ["NASA-1.3"], "max_stars_count": 29, "max_stars_repo_stars_event_min_datetime": "2015-05-06T01:28:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T22:55:29.000Z", "max_issues_repo_path": "docs/photometry/developmentplan.tex", "max_issues_repo_name": "imagineagents/StereoPipeline", "max_issues_repo_head_hexsha": "8b9c0bcab258c41d10cb2973d97722765072a7bf", "max_issues_repo_licenses": ["NASA-1.3"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/photometry/developmentplan.tex", "max_forks_repo_name": "imagineagents/StereoPipeline", "max_forks_repo_head_hexsha": "8b9c0bcab258c41d10cb2973d97722765072a7bf", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2015-01-15T04:20:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-10T01:31:17.000Z", "avg_line_length": 41.7011494253, "max_line_length": 143, "alphanum_fraction": 0.7322216097, "num_tokens": 4086, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.3308515959732461}}
{"text": "\\documentclass[12pt]{article}\n\\usepackage{fullpage,enumitem,amsmath,amssymb,graphicx,amsthm}\n\n\\begin{document}\n\n\\begin{center}\n{\\Large CS221 Fall 2017 Homework [Foundations]}\n\n\\begin{tabular}{rl}\nName: & yf-yang\n\\end{tabular}\n\\end{center}\n\nBy turning in this assignment, I agree by the Stanford honor code and declare\nthat all of this is my own work.\n\n\\section*{Problem 1}\n\n\\begin{enumerate}[label=(\\alph*)]\n  \\item \n    Let $\\theta^{\\ast} = \\underset{\\theta}{arg\\,min} f(\\theta)$, then\n    \\begin{equation}\\frac{\\partial f(\\theta^{\\ast})}{\\partial \\theta^{\\ast}} = \\sum_{i=1}^{n}{w_i(\\theta^{\\ast} - x_i)} = 0\\end{equation}\n    \\begin{equation}\\theta^{\\ast}\\sum_{i=1}^{n}{w_i} = \\sum_{i=1}^{n}{w_i x_i}\\end{equation}\n    \\begin{equation}\\theta^{\\ast} = \\frac{\\sum_{i=1}^{n}{w_i x_i}}{\\sum_{i=1}^{n}{w_i}}\\end{equation}\n    Without loss of generality, we can assume $\\sum_{i=1}^{n}{w_i}=1$, then\n    \\begin{equation}\\theta^{\\ast} = \\mathop{\\mathbb{E}_{\\mathbf{w}}}[\\mathbf{x}]\\end{equation}\n    In order to prove $\\theta^{\\ast}$ is a global minimum, we need to show\n    \\begin{equation}\\frac{\\partial^2 f(\\theta^{\\ast})}{\\partial {\\theta^{\\ast}}^2} = \\sum_{i=1}^{n}{w_i}\\end{equation}\n    Note that Eqn(5) is strictly positive if all $w_i$ are positive, so $\\theta^{\\ast}$ should be a global minimum, while when some $w_i$ is negative, $sum_{i=1}^{n}{w_i}$ may be negative, then the global minimum doesn't hold. \\qed\n    \n  \\item \n    \\begin{equation} f(\\mathbf{x})=\\sum_{i=1}^{d}{\\max_{s\\in \\{-1,1\\}}{s x_i}} = \\sum_{i=1}^{d}{{\\lvert}x_i{\\rvert}} \\end{equation}\n    \\begin{equation} g(\\mathbf{x})=\\max_{s\\in \\{-1,1\\}}{\\sum_{i=1}^{d}{s x_i}} = \\max_{s\\in \\{-1,1\\}}{s \\sum_{i=1}^{d}{x_i}} = {\\lvert}\\sum_{i=1}^{d}{x_i}{\\rvert} \\end{equation}\n    According to Triangular Inequality, we can conclude that $f(\\mathbf{x}) > g(\\mathbf{x})$ \\qed\n\n  \\item\n    Let $\\mathbf{X_i} =$ (number of points you roll the i-th time), $\\mathbf{N} =$ (number of rolls), then\n    \\begin{align*} \\mathop{\\mathbb{E}}[\\sum_{i=1}^{\\mathbf{N}}{\\mathbf{X_i}}] &= \\sum_{n=0}^{\\infty}f_{\\mathbf{N}}(n+1)\\mathop{\\mathbb{E}}[\\mathbf{X}|n+1] \\\\\n    &= \\sum_{n=0}^{\\infty}\\frac{1}{6}(\\frac{5}{6})^n\\frac{b-a}{5}n \\\\\n    &= \\frac{b-a}{30}\\sum_{n=0}^{\\infty}n(\\frac{5}{6})^n \\\\\n    &= b-a\\end{align*}  \\qed\n\n  \\item\n    Let $M(p) = \\log{L(p)}$, then\n    \\begin{equation}M(p) = 4\\log{p}+3\\log{(1-p)}\\end{equation}\n    At $M(p)$'s maximum, which is also $L(p)$'s maximum we have\n    \\begin{equation}\\frac{\\partial{M(p)}}{\\partial p}=\\frac{4}{p}-\\frac{3}{1-p}=0\\end{equation}\n    \\begin{equation}p = \\frac{4}{7}\\end{equation}\n    Intuitively, in order to get 4 Heads in 7 flips with max probability(on average $\\frac{4}{7}$ Head in one flip), we should let the probability of Heads in one flip, which is the Expectation of Heads in one flip be exactly $\\frac{4}{7}$(because $L(p)$ is a continuous function and Expectation of Heads in one flip should be where the probability is the maximum. \\qed\n    \n  \\item \n    \\begin{equation}\\frac{\\partial f}{\\partial w_k} = \\sum_{i=1}^{n}\\sum_{j=1}^{n}2(a_{ik}-b_{jk})(\\mathbf{a_i^\\top w-b_j^\\top w})+2\\lambda w_k\\end{equation}\n    \\begin{equation}\\frac{\\partial f}{\\partial \\mathbf w} = 2(\\sum_{i=1}^{n}\\sum_{j=1}^{n}(\\mathbf{a_i^\\top w-b_j^\\top w})(\\mathbf{a_{i}-b_{j}})+\\lambda\\mathbf w)\\end{equation} \\qed\n\\end{enumerate}\n\n\\section*{Problem 2}\n\n\\begin{enumerate}[label=(\\alph*)]\n  \\item \n    Start from 1-dimensional case with only one line segment to be placed, then the number of cases is\n    \\begin{equation}\\sum_{i=1}^n n=\\frac{n(n+1)}{2}\\end{equation}\n    With 6 independent parts and two independent axis, the total number should be\n    \\begin{equation}((\\frac{n(n+1)}{2})^6)^2=\\frac{n(n+1)}{2})^{12}\\end{equation}\n    And\n    \\begin{equation}\\lim_{n\\to\\infty}\\frac{n(n+1)}{2})^{12}=O(n^{24})\\end{equation}\\qed\n    \n  \\item \n    See prob2-2.py for the code.\n    The complexity is $O(n^2)$.\\qed\n    \n  \\item\n    \\begin{equation} f(n) = \n    \\begin{cases} \n      1, n = 0, 1 \\\\\n      \\sum_{i=0}^{n-1}{f(i)}, n \\ge 2\n   \\end{cases}\n   \\end{equation}\n   Then, we can prove $f(n)$ has a more direct form: \n   \\begin{equation}f(n) = 2^{n-1}, n \\in \\mathbb{N^+}\\end{equation}\n   We can prove that by induction: \\\\\n   \\textbf{Base Case}: Obviously, we have $f(1) = 2^0 = 1$ \\\\\n   \\textbf{Inductive Step}: \n   \\begin{equation}f(n) = \\sum_{i=1}^{n-1}2^{i-1}+f(0)=2^{n-1}-1+1=2^{n-1}\\end{equation}\\qed\n   \n \\item \n    \\begin{align}\\sum_{i=1}^{n}\\sum_{j=1}^{n}{(\\mathbf{a_i^\\top w-b_j^\\top w})}^2 + \\lambda \\left\\lVert\\mathbf{w}\\right\\rVert_2^2 &= \\sum_{i=1}^{n}\\sum_{j=1}^{n}{(\\mathbf{w^\\top a_i a_i^\\top w-w^\\top a_i b_j^\\top w + w^\\top b_j b_j^\\top w})} + \\lambda \\left\\lVert\\mathbf{w}\\right\\rVert_2^2\\\\\n    &= \\mathbf{w^\\top} (\\sum_{i=1}^{n}\\sum_{j=1}^{n}{(\\mathbf{a_i a_i^\\top-a_i b_j^\\top+b_j b_j})}) \\mathbf{w}+ \\lambda \\left\\lVert\\mathbf{w}\\right\\rVert_2^2\\end{align}\n    See prob2-4.py for the code. \\qed\n    \n\\end{enumerate}\n\n\\end{document}", "meta": {"hexsha": "1c68c5c9c5509bf31d80800417c4cb0e953240ae", "size": 4950, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "foundations/homework.tex", "max_stars_repo_name": "yf-yang/cs221", "max_stars_repo_head_hexsha": "9d6dd2fdb20ea1f656b3cc91364c9410998caf4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-05-18T09:02:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T04:09:55.000Z", "max_issues_repo_path": "foundations/homework.tex", "max_issues_repo_name": "yf-yang/cs221", "max_issues_repo_head_hexsha": "9d6dd2fdb20ea1f656b3cc91364c9410998caf4f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "foundations/homework.tex", "max_forks_repo_name": "yf-yang/cs221", "max_forks_repo_head_hexsha": "9d6dd2fdb20ea1f656b3cc91364c9410998caf4f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-11-01T11:42:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-26T16:25:57.000Z", "avg_line_length": 53.8043478261, "max_line_length": 369, "alphanum_fraction": 0.6193939394, "num_tokens": 2004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.3307657315701976}}
{"text": "\\input{frontmatter.tex}\n\\begin{document}\n\\input{4955_heading.tex}\n\n\\vspace{2em}\n\nThis document details a proposal for the combinational and learning AI that will play a major role in the game Sasq-watch, developed by Cryptid Games.\n\n\\section{High Level Overview}\n\nThe AI will be made up of three components, detailed below. Each of these components is a stripped down model of certain AI principles, namely a neural network, a genetic combination algorithm, and a recurrent neural network.\n\n\\begin{enumerate}\n    \\item A state machine with transfer weights in the graph determined by a vector given to the state machine at the start of the game\n    \\item A combination algorithm which takes the personal weight vectors of each player and joins them into one weight vector for propogation into the state machine. This combinational algorithm will also be used to combine each player's weight vector with the modified game vector created after the learning phase.\n    \\item A \"learning phase\" algorithm that, after being successfully defeated, goes back through the weight vector and modifies weights to direct the AI in a different direction, preventing the same attack from being successfully executed in the same way again.\n\\end{enumerate}\n\nThe aim with these components is to simulate, at the high level, the same processes that make recurrent nerual networks highly efficient at learning when presented with vast sums of training data and plenty of computation time are being stripped down and manually guided so that they can be applied to a hand-crafted game experience.\n\n\\section{State Machine}\n\nThe state machine sits in a place halfway between a state machine and a neural network. Figure \\ref{fig:state1} is an example of a very small machine that will be used for discussion purposes. \n\n\\begin{figure}\n\\begin{tikzpicture}[scale=0.2]\n\\tikzstyle{every node}+=[inner sep=0pt]\n\\draw [black] (12.6,-16.8) circle (3);\n\\draw (12.6,-16.8) node {$A$};\n\\draw [black] (34.8,-6.5) circle (3);\n\\draw (34.8,-6.5) node {$B_1$};\n\\draw [black] (34.8,-24.5) circle (3);\n\\draw (34.8,-24.5) node {$B_2$};\n\\draw [black] (15.32,-15.54) -- (32.08,-7.76);\n\\fill [black] (32.08,-7.76) -- (31.14,-7.65) -- (31.56,-8.55);\n\\draw (28.03,-12.18) node [below] {$\\vec{v_i}$};\n\\draw [black] (15.43,-17.78) -- (31.97,-23.52);\n\\fill [black] (31.97,-23.52) -- (31.37,-22.78) -- (31.05,-23.73);\n\\draw (17.86,-21.36) node [below] {$\\vec{v_{i+1}}$};\n\\end{tikzpicture}\n\\caption{An example state machine for discussion}\n\\label{fig:state1}\n\\end{figure}\n\nState $A$ represents a specific behavior of the cryptid, while states $B_1$ and $B_2$ are two behaviors that can occur from state $A$. $\\vec{v_i}$ refers to the $i$th value in $\\vec{v}$. State A is made up of two components: a cryptid action function and a transfer decision function. The cryptid action function describes the behavior that the cryptid will perform (i.e. forrage, travel, sleep, etc.). This is the main function of how the state machine interacts with the game, which allows us to leverage pre-existing knowledge and resources for Unity to simply create the AI using a state machine. The second component, the transfer decision function could work in one of two ways.\n\nThe first way it could work is very similar to the way a neural network moves through its weights. The decision function outputs a number $n$ such that $n \\in [-1, 1]$. $\\vec{v_i}$ could remain normal while $\\vec{v_{i+1}}$ is negated. Then, the state transfers anytime the transfer function evaluates to a value above $\\vec{v_i}$ or below $\\vec{v_{i+1}}$. This design could also work by assigning ranges to each edge of the state machine's graph with a specific range dedicated for the \"remain in this state\" decision. I believe this would be the worse of the two options because it limits the number of possible states we can transfer to, and it requires incredibly complex transfer functions.\n\nThe second way it could work is by having the transfer function provide a binary conclusion of transfer or stay. Then, when it decides on a transfer, the weights of all outgoing edges serve as the ratios for transfers. For example, the transfer from state $A$ would transfer to state $B_1$ with probability $P(\\vec{v_i})$ and would transfer to state $B_2$ with probability $P(\\vec{v_{i+1}})$. This allows for non-deterministic actions from the cryptid, and the computation of state transfers will be far less significant.\n\n\\section{Vector Combination Algorithm}\n\nThe vector combination algorithm fulfills several roles in the game. First, it allows four players joining the game to combine their individual cryptid decision vectors in a non-deterministic way, and it allows for the group decision vector to be combined with individual player vector after the game, letting the game affect future games. The combination algorithm is going to be similar to the genetic combination algorithms present in genetic learning alrogithms. The table below demonstrates this phenomenon.\n\n\\begin{tabular}{ccccc}\n$\\vec{v_0}$ & & $\\vec{u_0}$ & & $\\vec{v_0}$ \\\\\n$\\vec{v_1}$ & & $\\vec{u_1}$ & $\\Longrightarrow$ & $\\vec{u_1}$ \\\\\n$\\vec{v_2}$ & & $\\vec{u_2}$ & & $\\vec{u_2}$ \\\\\n\\vdots & & & & \\\\\n$\\vec{v_n}$ & & $\\vec{u_n}$ & & $\\vec{v_n}$ \\\\\n\\end{tabular}\n\nThe first element in each vector will be a simple count of the number of games a vector has \"played\" in. In this way, the combination algorithm can weight the cross pollination of \"genes\" based upon how \"experienced\" that vector is. The combination of the first two values could, for example, take the form of the equation:\n\n\\begin{equation}\n    \\frac{{\\log_{10}(\\vec{v_0})}\\vec{v_1} + {\\log_{10}(\\vec{u_0})}\\vec{u_1}}{\\log_{10}(\\vec{v_0}) + \\log_{10}(\\vec{u_0})} = \\vec{game_1}\n\\end{equation}\n\nThen, after the games conclusion, to update a player's weight vector, the same calculation can be performed with $\\vec{game}$ taking the place of $\\vec{v}$ in the equation above and the weight ratios being the ratio between total games played by all players and total games played by this player. \n\n\\section{Learning Algorithm}\n\nThe learning algorithm takes advantage of the fact that a state machine is really just a graph. As the game runs, every state transition pushes the state onto a stack. Then, when the game is finished, we can assume that the last few transitions led to the game loss. Therefore, we step back through the states and adjust the weights that allow arriving in those states. Then, we can perform a simple graph traversal to see if it becomes more difficult to arrive at that state through a given transition. If it does, then we consider it a successful change and continue to \"prune\" the next element on the stack by performing the same action. This can be repeated for a variable depth, allowing us to modify the amount of the game that is modified each time. A possible solution is that the depth is inversely related to how many games have been played.\n\n\\end{document}", "meta": {"hexsha": "47351893b3b35101d899d8e0475ac05306c60d12", "size": 6934, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "undergrad/cosc4955/aiprop/main.tex", "max_stars_repo_name": "andey-robins/school", "max_stars_repo_head_hexsha": "a3bf98dd2fdcbdea9eeecc524a7c31125e82fd77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "undergrad/cosc4955/aiprop/main.tex", "max_issues_repo_name": "andey-robins/school", "max_issues_repo_head_hexsha": "a3bf98dd2fdcbdea9eeecc524a7c31125e82fd77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "undergrad/cosc4955/aiprop/main.tex", "max_forks_repo_name": "andey-robins/school", "max_forks_repo_head_hexsha": "a3bf98dd2fdcbdea9eeecc524a7c31125e82fd77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 92.4533333333, "max_line_length": 851, "alphanum_fraction": 0.7526680127, "num_tokens": 1774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3307657212597985}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\section{Symmetries and conservation laws}\n\n\\marginpar{Tuesday\\\\ 2020-3-17, \\\\ compiled \\\\ \\today}\n\nOur aim is to describe the fundamental constituents of matter with a Quantum Field Theory. \nThe method used to derive the equations of motion is a variational principle: we will find a Lagrangian density for various particles, and then apply the variational principle to find their equations of motion. \n\nA guiding principle on the description of these fundamental particles is based on using their symmetries. \nWe have Nöether's theorem in Quantum Field Theory: from these symmetries we are able to find conserved quantities. \n\nThese symmetries are described with groups, since we can compose their application; the theory describing groups is very rich. \nFor this lecture we will base ourselves on Peskin's chapter 2 \\cite[]{peskinConceptsElementaryParticle2019}.\n\nA group \\(G\\) is a set of elements endowed with an operation. The set of elements can be either discrete or continuous. Examples of discrete transformations are the parity transformation \\(P\\): \\(P \\vec{x} = -\\vec{x}\\) and the time swap \\(T\\): \\(T x^{\\mu } = (-x^{0}, \\vec{x})\\). Continuous symmetries, on the other hand, are parametrized by one or more continuous-valued parameters. \n\nWe distinguish: \n\\begin{enumerate}\n  \\item \\textbf{spacetime} symmetries: groups which transform our coordinate system for spacetime, such as Lorentz and Poincaré transformations;\n  \\item \\textbf{internal} symmetries: groups which transform a certain field, or a certain property of our quantum system.\n\\end{enumerate}\n\nFor our set to be a group, we need to be able to define an operation --- we will usually call it multiplication --- between the elements of the group, such that if \\(a, b \\in G\\) then \\(ab \\in G\\). Also, we must have \n\\begin{enumerate}\n  \\item associativity: \\((ab)c = a(bc)\\);\n  \\item existence of the identity \\(\\mathbb{1}\\), such that \\(\\mathbb{1} a = a \\mathbb{1} = a\\);\n  \\item existence of inverses: there exists \\(a^{-1}\\) such that \\(a a^{-1} = a^{-1} a = \\mathbb{1}\\). \n\\end{enumerate}\n\nWhat is of interest to us is the association of the group with a transformation which is a symmetry: this is called a \\emph{representation}, which associates to each \\(g \\in G\\) a unitary operator \\(U_g\\) acting on the quantum states. We ask that this representation should preserve the group structure, that is to say, \\(U_{gh} = U_g U_h\\) and \\(U_{g^{-1}} = U_{g}^{-1}\\).\n\nWe call a transformation a symmetry if, after performing the transformation, the dynamics of the system do not change. \n\nFor a quantum mechanical system, we are interested in the observables: these are described by operators, whose eigenvalues are the observations we make, and which in the Heisenberg picture evolve like \n%\n\\begin{align}\n- i \\hbar \\dv{}{t} O(t) = [H, O(t)]\n\\,;\n\\end{align}\n%\nif an operator commutes with the Hamiltonian, \\([H,O]=0\\), then the operator's expectation value on any state is constant --- which is to say, the operator is constant. \n\nIf we perform a transformation in the form \n%\n\\begin{align}\n\\ket{\\psi } \\rightarrow \\ket{\\psi'} = U \\ket{\\psi }\n\\,,\n\\end{align}\n%\nthen the operators will change by \n%\n\\begin{align}\nO \\rightarrow O^{\\prime } = U ^\\dag O U \n\\,.\n\\end{align}\n\nNote that whether we have \\(U ^\\dag O U\\) or \\(U O U ^\\dag\\) does not matter, since we ask observables \\(O\\) to be Hermitian, so \\(O = O ^\\dag\\). \n\nWe know that these transformations must always be unitary, because the conservation of probability implies that we must have \\(\\braket{\\psi }{\\psi } = \\const\\): so, \n%\n\\begin{align}\nU ^\\dag U = \\mathbb{1}\n\\,.\n\\end{align}\n\nThis can be also stated as \\(U ^\\dag = U^{-1}\\). \n\nSo, the function associating a unitary operator \\(U\\) to an element \\(g\\) of the group is called its \\emph{unitary representation}. \n\nA transformation \\(G\\) is a symmetry if \\(\\forall a \\in G\\) we have \n%\n\\begin{align}\n[U(a), H]  =0\n\\,,\n\\end{align}\n%\nthat is, the unitary representation of the group element always commutes with the Hamiltonian.\n\nIf we have a state \\(\\ket{\\psi }\\) with energy \\(H \\ket{\\psi } = E \\ket{\\psi }\\), then the transformation commuting with the Hamiltonian means that \\(\\ket{\\psi'} = U \\ket{\\psi }\\) has the same energy: \n%\n\\begin{align}\nH (U \\ket{\\psi }) = HU \\ket{\\psi } \\overset{[H, U] = 0}{=} UH \\ket{\\psi } =\n U E \\ket{\\psi } = E \\qty(u \\ket{\\psi })\n\\,,\n\\end{align}\n%\nso the eigenvalue of \\(U \\ket{\\psi }\\) is the same as that of \\(\\ket{\\psi }\\).\n\nNow, we can move to an example, taken from Peskin \\cite[eq.\\ 2.38 onward]{peskinConceptsElementaryParticle2019}. \nConsider the discrete group \\(\\mathbb{Z}_{2}\\), which only has the elements \\(1\\) and \\(-1\\), with the same multiplication rules as those we would have if these elements were integers. \nSo, the group is closed with respect to multiplication.\nIt can be easily checked that this is indeed a group based on our definition. \n\nIn order for this to be of interest to us, we can consider a quantum mechanical system and find a unitary representation acting on its Hilbert space. \n\nLet us suppose we have a QM system with a basis made of two states \\(\\ket{\\pi^{+}}\\) and \\(\\ket{\\pi^{-}}\\). Let us define the \\emph{charge conjugation} operator \\(C\\), by: \n%\n\\begin{align}\nC \\ket{\\pi^{+}} = \\ket{\\pi^{-}} \n\\qquad \\text{and} \\qquad\nC \\ket{\\pi^{-}} = \\ket{\\pi^{+}} \n\\,.\n\\end{align}\n\nSo, we can find a unitary representation of \\(\\mathbb{Z}_{2}\\) in this system: we need to define \\(U(1)\\) and \\(U(-1)\\). We define \n%\n\\begin{subequations}\n\\begin{align}\nU(1) = \\mathbb{1} =\\left[\\begin{array}{cc}\n1 & 0 \\\\ \n0 & 1\n\\end{array}\\right] \n\\qquad \\text{and} \\qquad\nU(-1) = \\sigma_{x} = \\left[\\begin{array}{cc}\n0 & 1 \\\\ \n1 & 0\n\\end{array}\\right]\n\\,,\n\\end{align}\n\\end{subequations}\n%\nwhere the matrices are to be interpreted as acting on vectors expressed to the basis \\(\\qty{\\ket{\\pi_{+}}, \\ket{\\pi_{-}}}\\).\n\nSo, we can say that our unitary representation looks like \n%\n\\begin{align}\n\\mathbb{Z}_{2} \\rightarrow \\qty{\\mathbb{1}, C}\n\\,.\n\\end{align}\n\nNow, if \\([C, H] =0\\) (and \\(\\mathbb{1}\\) commutes with \\(H\\), which is always the case) then we say that ``\\(H\\) has the symmetry \\(\\mathbb{Z}_{2}\\)'': this implies that the energies of the two \\(\\pi_{\\pm}\\) particles are equal.\n\nThe interesting question to determine will be whether this is actually the case for our given group. \n\nGroups can be subdivided into abelian and non-abelian ones.\nA group is abelian if for every \\(a, b\\) in \\(G\\) we have \\(ab = ba\\), or equivalently, \\([a, b] =0\\). \nIt is not if this is not the case, that is, there exist \\(a, b\\) such that \\(ab \\neq ba\\).\n\nThe condition on the elements directly translates to a condition on the matrices of the unitary representation. \nIf we have commuting matrices, we can simultaneously diagonalize them: for example, in the case of \\(\\mathbb{Z}_{2}\\) we can go to a basis in which \n%\n\\begin{subequations}\n\\begin{align}\nC = \\left[\\begin{array}{cc}\n1 & 0 \\\\ \n0 & -1\n\\end{array}\\right]\n\\,,\n\\end{align}\n\\end{subequations}\n%\nspecifically the states on which this matrix will act will need to be \n%\n\\begin{align}\n\\ket{\\pi_{1}} = \\frac{\\ket{\\pi^{+}} + \\ket{\\pi^{-}}}{\\sqrt{2}} \n\\qquad \\text{and} \\qquad\n\\ket{\\pi_{2}} = \\frac{\\ket{\\pi^{+}} - \\ket{\\pi^{-}}}{\\sqrt{2}}\n\\,,\n\\end{align}\n%\nsince then \\(C \\ket{\\pi_1 } = \\ket{\\pi_1 }\\) (we write \\(C = +1\\)) and \\(C \\ket{\\pi_{2}} = - \\ket{\\pi_2 }\\) (we write \\(C = -1\\)). \nWe will often use this notation, confusing operator and eigenvalue.\n\nIn the case of nonabelian groups it is not in general possible to diagonalize all the matrices; we can however do a change of basis and write the matrices as a block matrix with the smallest possible blocks:\n%\n\\begin{subequations}\n\\begin{align}\nU_{R} = \\left[\\begin{array}{ccc}\nU_1  & 0 & 0 \\\\ \n0 & U_2  & 0 \\\\ \n0 & 0 & \\dots\n\\end{array}\\right] \n\\,,\n\\end{align}\n\\end{subequations}\n%\nwhere the matrices \\(U_i\\) are called the \\textbf{irreducible unitary representations of \\(G\\)}.\nThe dimension of the matrices \\(U_i\\) tells us the dimension of these irreducible unitary representations.\n\n\\todo[inline]{Add more details on irreps --- maybe not here? They can be found in professor Rigolin's intro to groups.}\n\nDo note that some elements of a nonabelian group can commute: for example, in the rotation group we have \n%\n\\begin{align}\n[J^{i}, J^{j}] = \\epsilon^{ijk} J_{k}\n\\,,\n\\end{align}\n%\nso if we take \\(i = j\\), that is, we consider rotations along the same axis, they will commute since then the Kronecker symbol is equal to zero. \n\n\\subsection{Continuous transformations: space translations}\n\nAn element of the group can be written as \n%\n\\begin{align}\nU(a) = e^{ - i a P }\n\\,,\n\\end{align}\n%\nwhere the operator \\(P\\), whose eigenvalue is the momentum, is called the generator of the transformation. \n\nIf we consider a plane wave we can clearly see how this action works: if we start from\n%\n\\begin{align}\n\\braket{x}{p} = e^{i p x}\n\\,,\n\\end{align}\n%\nwe can apply the operator \\(U(a)\\) to \\(\\ket{p}\\), which will yield \\(e^{-ipa}\\) (since eigenvectors of an operator are also eigenvectors of its exponential): so we find\n%\n\\begin{align}\n\\bra{x} U(a) \\ket{p} = e^{i p (x-a)}\n\\,,\n\\end{align}\n%\nwhich means that by acting with this operator we have effectively performed a translation with displacement \\(a\\). \n\nIf our system is invariant under translations, then Nöether's theorem tells us that the momentum is conserved. \n\nIn order to be a physical observable \\(P\\) needs to be Hermitian: \\(P = P ^\\dag\\). \n\nSo, the adjoint of the transformation \\(U(a)\\) is \n%\n\\begin{align}\nU ^\\dag (a) =\n\\sum _{n} \\qty(\\frac{(-iaP)^{n}}{n!}) ^\\dag\n= \\sum _{n} \\frac{(iaP ^\\dag)^{n}}{n!}\n=\ne^{i a P ^\\dag} = e^{iaP} = U^{-1}(a)\n\\,,\n\\end{align}\n%\nwhich confirms the fact that the transformation is unitary. \n\nLet us suppose that the momentum operator \\(P\\) commutes with the Hamiltonian: \\([P,H] = 0\\). Then, \n%\n\\begin{align}\n[U(a), H] = 0 \n\\,,\n\\end{align}\n%\nthat is, the Hamiltonian is translation-invariant. \n\nAll this is to say that a constant of motion \\(O\\) corresponds to an operator \\(O\\) which commutes with the Hamiltonian. \nThis is formalized by Nöther's theorem, which establishes the equivalence between symmetries and conservation laws:\n%\n\\begin{align}\n[O, H] = 0 \n\\iff \n[U_O, H] = 0\n\\,.\n\\end{align}\n\nAs an example, take the group \\(G\\) of 3D rotations. \nThey depend on a continuous parameter \\(\\vec{\\alpha}\\), just like translations depended on the parameter \\(a\\). \n\nThe rotation is written as \n%\n\\begin{align}\nU(\\vec{\\alpha}) = e^{-i \\vec{\\alpha} \\cdot \\vec{J}}\n\\,,\n\\end{align}\n%\nwhere the components of the angular momentum have the following commutation relations: \n%\n\\begin{align}\n[J^{i}, J^{j}] = i \\epsilon^{ijk} J^{k}\n\\,.\n\\end{align}\n\nWe will be able to compose the representations of rotations: \n%\n\\begin{align}\nU(\\vec{\\beta}) U(\\vec{\\alpha}) = U(\\vec{\\gamma})\n\\,.\n\\end{align}\n\nThis space of 3D rotations is called SO(3), since every rotation corresponds to a 3x3 matrix which is a rotation matrix --- it is orthogonal and has determinant 1.\n\nNow, we seek \\textbf{representations} of these rotations: so, we choose the dimension \\(d\\) of a quantum-mechanical vector and describe how it changes upon the action of the unitary matrices found by exponentiating certain \\(d\\)-dimensional generators \\(J^{i}\\), which must have the algebra discussed above. \n\nIf we look for 1D representations of the generators \\(J^{i}\\) the only option we find is \\(J^{i} = 0\\), which means that we are not actually performing a rotation. This is because scalars commute with each other.\nWhich states transform this way? These are scalar states, with spin 0. \n\nFor 2D representations, we have \n%\n\\begin{align}\nJ^{i} =\\frac{1}{2} \\sigma^{i} \n\\,,\n\\end{align}\n%\nwhere the \\(\\sigma^{i}\\) are the Pauli matrices.\n\nWe can also find 3D representations, which look like \n%\n\\begin{subequations}\n\\begin{align}\nJ^{1}= \\left[\\begin{array}{ccc}\n0 & 0 & 0 \\\\ \n0 & 0 & -i \\\\ \n0 & i & 0\n\\end{array}\\right] \n\\qquad \nJ^{2}= \\left[\\begin{array}{ccc}\n0 & 0 & i \\\\ \n0 & 0 & 0 \\\\ \n-i & 0 & 0\n\\end{array}\\right] \n\\qquad \nJ^{1}= \\left[\\begin{array}{ccc}\n0 & -i & 0 \\\\ \ni & 0 & 0 \\\\ \n0 & 0 & 0\n\\end{array}\\right] \n\\,\n\\end{align}\n\\end{subequations}\n%\nand represent a spin 1 particle. In general, spin \\(s\\) corresponds to a \\(2s+1\\)-dimensional representation.\n\nA rotation in 2D, represented by an element of SO(2), corresponds to a phase shift, so we can say that it is equivalent to an element of U(1).\nThis then allows us to see that SO(2) is abelian. \n\nIn general, we write for a unitary \\(n \\times n\\) representation\n%\n\\begin{align}\nU(n) \\rightarrow e^{-i \\alpha^{n} t^{a}}\n\\,,\n\\end{align}\n%\nwhere the generators \\(t^{a}\\) are Hermitian matrices corresponding to Hermitian operators. \nIn particular, conventionally we say that one of these is the identity: \\(t^{0} = \\mathbb{1}\\) (which must always be included in the group, lest we lose closure).\n\nSo, we omit it and say that we have \\(n^2-1\\) generators for the SU\\((n)\\) group.\nWe shall see that each of these generators corresponds to a particle, and for the weak interaction we will have \\(2^2-1 = 3\\) particles, while for the strong one we will have \\(3^2-1=8\\). \n\nIn general, if \\(t^{a}\\) are the generators of an abstract Lie group, we can describe the algebra of the group by \n%\n\\begin{align}\n\\qty[t^{a}, t^{b}] = i f^{abc} t^{c}\n\\,,\n\\end{align}\n%\nso, the commutator is decomposed into a linear combination of the generators, whose coefficients \\(f^{abc}\\) are called the \\textbf{structure constants} of the group.\n\n\\end{document}", "meta": {"hexsha": "cdc981b6a5b955dae50d3b21525222880faff834", "size": 13538, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ap_second_semester/astroparticle_physics/mar17.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "ap_second_semester/astroparticle_physics/mar17.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ap_second_semester/astroparticle_physics/mar17.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 38.9022988506, "max_line_length": 384, "alphanum_fraction": 0.6901314818, "num_tokens": 4053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.3307657212597984}}
{"text": "\\section{Link Path Loss}\\label{sec:reachi-experiments}\nIn this section, we present the method for simulating link \\gls{pathloss} from \\cite{paper:linkmodel}, as well\nas why the model does not work for our needs. For our simulations, we want to simulate the performance of\nnodes in a \\gls{manet}. The performance is, however, heavily dependent on network conditions and the\ncapabilities of the technology~\\cite[p.~10]{paper:linkmodel}. The author of \\cite{paper:linkmodel} presents\nmethods for evaluating the performance of a wireless network and proceeds to introduce methods for simulating\n\\gls{pathloss} on a multi-link model, based on real-world performance measurements. \\medbreak\n\nThe author of \\cite{paper:linkmodel} describes the \\gls{pathloss} of a link to be the sum of two parts: A\ndeterministic distance-dependent part, that describes the mean signal attenuation at any given link distance,\nand a stochastic shadow fading part, which is the \\gls{pathloss} caused by terrain, buildings, vegetation and\ncars. With this \\gls{pathloss}, it is possible to simulate the \\gls{rssi} on a given link, by subtracting the\n\\gls{pathloss} from the transmission power of the simulated radio.\n%\n\\begin{eq}\\label{eq:ld}\n    \\mathit{pl}_d(l) = 55 \\log_{10}(d(l)) - 18.8\n\\end{eq}\n\nThe distance-dependent \\gls{pathloss} is computed using the $\\mathit{pl}_d(l)$ function shown in\n\\autoref{eq:ld}~\\cite[p.~25]{paper:linkmodel}, where the function $d(l)$ denotes the distance of a link in\nmeters. Computing the shadow fading \\gls{pathloss}, on the other hand, is not as trivial. The shadow fading\npart of the \\gls{pathloss} is based on the correlation between angles of link pairs sharing a common nodes,\nand bears a significant practical limitation in the sense that the shadow fading part depends on a Cholesky\nfactorisation with a computational complexity of $O(N^6)$~\\cite[p.~31]{paper:linkmodel}, where $N$ is the\ntotal number of nodes in the network. \\medbreak\n\nThrough personal communication with the author of \\cite{paper:linkmodel}, we received access to logs from\nfield experiments for the Reachi project. These field experiments were conducted in different locations with\nan early prototype of the Reachi device. The logs contain \\gls{gps} coordinates, as well as \\gls{rssi}\ninformation for detected neighbours of each node. Examining these logs have shown discrepancies between the\n\\gls{pathloss} model from \\cite{paper:linkmodel} and the measured \\gls{rssi}.\n\\autoref{plot:reachi-experiments:measurements-vs-ld} plots samples drawn from the $\\mathit{pl}_d(l)$ function\nand measurements from a log containing field measurements from an experiment in Marikina, in the Phillippines.\nSince the log contained a total of 17761 links, the measurements are summarised based on the distance of the\nlink, and each link was sorted into distance buckets with 20-meter intervals. The average \\gls{rssi} for all\nlinks in a bucket is plotted in \\autoref{plot:reachi-experiments:measurements-vs-ld}. The plot shows that the\n\\gls{rssi} computed with the distance-dependent \\gls{pathloss} does not fit with the measured \\gls{rssi}.\n\\medbreak\n\nAs mentioned earlier, the shadow fading \\gls{pathloss} is based on the correlation between angles of link\npairs that share a common node. An assumption for this is that link pairs with a high correlation, where the\nangle between them is low, will have close to the same shadow fading~\\cite{paper:linkmodel}. However, this\ndoes not seem to be the case. \\autoref{plot:reachi-experiments:avg-rssi-angle-phili-rude} shows a plot where we\ncompare the Marikina log from earlier, with another field experiment log from Rude Skov. For both logs, pairs\nof links sharing a common node were sorted, based on the angle between them, into buckets of 5 \\degree\nintervals, and we computed the average \\gls{rssi} for these buckets, after removing the distance-dependent\n\\gls{pathloss}. This means that only the shadow fading part of the \\gls{pathloss} is included in the\n\\gls{rssi} plotted in \\autoref{plot:reachi-experiments:avg-rssi-angle-phili-rude}. Under the assumption that\nhighly correlated link pairs should result in less shadow fading \\gls{pathloss}, the traces on\n\\autoref{plot:reachi-experiments:avg-rssi-angle-phili-rude} should increase gradually as the angle increases.\nThis is not the case. \\medbreak\n\nBecause of this, and the fact that computing the shadow fading path loss is not feasible for a very large\nnumber of nodes, we instead propose our model for approximating the shadow fading \\gls{pathloss}.\n\n%As mentioned above, the angle based approach relies on the assumption that link pairs with a high correlation,\n%i.e. low angle between them, will have close to the same shadow fading. We have however not been able to\n%produce reliable proof that the assumption is correct. To produce proof, the Marikina and Rude skov log was\n%used. \n\n%For both logs, link pairs were created and sorted based on their angle into separate bucekts of\n%5$\\degree$ intervals. The average \\gls{rssi} for each bucket was then computed. Before computing the average\n%\\gls{rssi}, the distance dependent part $l_d$ was removed from the links \\gls{rssi} measurement, to isolate\n%the stochastic part. The resulting data can be seen plotted on\n%\\autoref{plot:reachi-experiments:avg-rssi-angle-phili-rude}. Under the previous assumption that a high\n%correlation gives smaller stochastic path loss, then the traces on\n%\\autoref{plot:reachi-experiments:avg-rssi-angle-phili-rude} should increase gradually as the angle increases.\n%Clearly the measurements does increase as the angle increase, but the increaes are not steady but rather vary\n%greatly. Too greatly to say that with certainty that the assumption holds on the received logs.\n\n\\begin{figure}[H]\n    \\centering\n    \\begin{tikzpicture}\n        \\begin{axis}[\n                height=10.5cm, width=0.95\\textwidth,\n                ylabel={RSSI},\n                xlabel={Distance in meters},\n                axis lines*=left,\n                xmin=0, xmax=750,\n                enlargelimits=false,\n                ymin=-120, ymax=-20,\n                xtick={0, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750},\n                ymajorgrids=true,\n                xmajorgrids=true,\n                grid style=dashed,\n                restrict y to domain=-120:-20,\n                samples=600\n            ]\n\n            \\addplot[very thick, solid, cyan, mark=*] coordinates {(20, -28.32345013477089) (40, -44.85830258302583) (60, -52.77323717948718) (80, -60.21201657458563) (100, -66.47435897435898) (120, -69.68905472636816) (140, -71.5976496922216) (160, -73.7866473149492) (180, -75.53428571428572) (200, -76.89289392378991) (220, -77.88135593220339) (240, -77.8035019455253) (260, -77.36784140969164) (280, -77.14030612244898) (300, -77.75299760191847) (320, -79.71686746987952) (340, -79.15481171548117) (360, -79.90728476821192) (380, -81.30909090909091) (400, -81.79746835443038) (420, -81.52272727272727) (440, -79.2) (460, -79.42105263157895) (480, -79.4375) (500, -79.0) (520, -77.91666666666667) (540, -83.0) (560, -81.27272727272727) (580, -83.57142857142857) (600, -86.0) (620, -83.4) (640, -86.5) (660, -81.42857142857143) (680, -79.0) (700, -82.71428571428571) (740, -77.0)};\n            \\addlegendentry{Marikina field measurements};\n\n            \\addplot[domain=0:740, very thick, solid, red] {26 - ld(x)};\n            \\addlegendentry{Computed \\gls{rssi}};\n        \\end{axis}\n    \\end{tikzpicture}\n    \\caption{Average RSSI pr. distance bucket.}\\label{plot:reachi-experiments:measurements-vs-ld}\n\\end{figure}\n\n\\begin{figure}[H]\n    \\centering\n    \\begin{tikzpicture}\n        \\begin{axis}[\n                height=10.5cm, width=0.95\\textwidth,\n                ylabel={Average RSSI - $\\mathit{pl}_d(l)$},\n                xlabel={Angle buckets},\n                axis lines*=left,\n                xmin=0, xmax=180,\n                xtick={0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160,170,180},\n                enlargelimits=false,\n                ymin=0, ymax=90,\n                ymajorgrids=true,\n                xmajorgrids=true,\n                grid style=dashed\n            ]\n\n            \\addplot[thick, solid, cyan, mark=*] coordinates {(5,7.581215097994852)(10,9.763581254686114)(15,11.59234807189617)(20,11.084399582147876)(25,9.411670936293284)(30,13.486232393853125)(35,19.91110051641767)(40,12.453590557884946)(45,14.70313120243339)(50,15.804939314638208)(55,16.87697870999425)(60,15.320902904198922)(65,18.673392004683087)(70,18.48508963612783)(75,21.147550183881993)(80,8.302184073487094)(85,10.641508684206432)(90,12.343183048128944)(95,14.396643466792797)(100,12.27504884861337)(105,17.994872329043496)(110,13.156645245862158)(115,11.595967499573286)(120,14.245146945189493)(125,14.528392002600814)(130,15.96981736460891)(135,13.70427190114752)(140,17.692009757218077)(145,17.79486440192431)(150,20.947579654378668)(155,25.611175147469265)(160,20.819124899373364)(165,12.495568407794714)(170,17.784042978338544)(175,9.646875797269503)(180,10.597197732034614)};\n            \\addlegendentry{Marikina};\n\n\n            \\addplot[thick, solid, red, mark=triangle*] coordinates {(5,8.968175725354994)(10,7.741408675352775)(15,9.042742837449076)(20,8.108954051047618)(25,11.273321343260399)(30,11.67692967914715)(35,13.401460743255232)(40,8.053793318539391)(45,14.17474549040368)(50,22.68855220716477)(55,15.026896145186285)(60,17.5755161176863)(65,85.01233086400362)(70,59.69038212814202)(75,62.41948703096457)(80,44.72712810089782)(85,20.029080610052482)(90,29.737954905927445)(95,43.39235466255519)(100,64.720015835849)(105,13.965589072181558)(110,61.334883149884675)(115,36.30455538419785)(120,33.32223486902817)(125,26.172354285886417)(130,45.62355888699502)(135,55.8474401182669)(140,47.511612928722954)(145,49.70429537245245)(150,50.649080550831435)(155,52.34402139529124)(160,51.45218633523966)(165,51.805898996936115)(170,52.39131328924595)(175,48.78102582759046)(180,51.91529108595685)};\n            \\addlegendentry{Rude Skov};\n        \\end{axis}\n    \\end{tikzpicture}\n    \\caption{Average \\gls{rssi} per angle bucket without distance dependent \\gls{pathloss}.}\n    \\label{plot:reachi-experiments:avg-rssi-angle-phili-rude}\n\\end{figure}", "meta": {"hexsha": "b0c323116d2d315fed7e13bfc957794c5ecc801b", "size": 10269, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "reports/p10/sections/02-radiophysics/03-pathloss.tex", "max_stars_repo_name": "Joklost/masters", "max_stars_repo_head_hexsha": "66bccba28a32ee47b7b874122de41c87f253349e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "reports/p10/sections/02-radiophysics/03-pathloss.tex", "max_issues_repo_name": "Joklost/masters", "max_issues_repo_head_hexsha": "66bccba28a32ee47b7b874122de41c87f253349e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "reports/p10/sections/02-radiophysics/03-pathloss.tex", "max_forks_repo_name": "Joklost/masters", "max_forks_repo_head_hexsha": "66bccba28a32ee47b7b874122de41c87f253349e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 80.8582677165, "max_line_length": 894, "alphanum_fraction": 0.7352225144, "num_tokens": 3149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.5078118642792043, "lm_q1q2_score": 0.33076572125979836}}
{"text": "\\section{Adversarial Example Landscape}\n\\transitionFrame{Adversarial Example Landscape}\n\n\\begin{frame}{Investigating the ``Inner Maximization''}\n  \\onslide<+->{%\n    \\begin{equation}\n      \\min_{\\params} \\rho(\\params) \\text{, where } \\rho(\\params) = \\mathbb{E}_{(\\X,\\y) \\sim \\distr} \\sbrack{\\red{\\max_{\\delta \\in \\sPerturb} \\loss (\\X + \\perturb, \\y ; \\params)}}\n    \\end{equation}\n  }\n\n  \\begin{itemize}[<+->]\n    \\setlength{\\itemsep}{20pt}\n    \\item Preceding theoretical analysis of \\textbf{\\red{inner maximization}} described PGD's usefulness to provide guarantees regarding first-order adversaries\n    \\item \\textbf{Goal of this Section}: Demonstrate \\textit{empirically} that the theoretical analysis holds even in environments that are theoretically \\textit{intractable}\n      \\begin{itemize}[<+->]\n        \\setlength{\\itemsep}{8pt}\n        \\item \\textbf{Recall}: Inner maximization is highly \\textit{non-concave} and not continuously-differentiable\n        \\item \\textbf{Question}: Why are we interested in concavity and not convexity?\n      \\end{itemize}\n  \\end{itemize}\n\\end{frame}\n\n\n\\begin{frame}{Experimental Setup}\n  \\onslide<+->{Setup applies for all experiments in this section}\n  \\begin{itemize}[<+->]\n    \\setlength{\\itemsep}{10pt}\n    \\item \\textbf{Datasets}: MNIST \\& CIFAR10\n\n    \\item \\textbf{Procedure}: Select example,~$\\X$, u.a.r.\\ from the dataset, then for each random restart:\n      \\begin{enumerate}[<+->]\n        \\setlength\\itemsep{6pt}\n        \\item Select initial perturbation,~${\\perturb \\in \\sPerturb}$, u.a.r.\n        \\item Perform PGD on perturbed example, ${\\X + \\perturb}$\n      \\end{enumerate}\n\n    \\item \\textbf{\\# Random Restarts}: Varies by experiment\n\n    \\item \\textbf{Loss Function}: Cross-entropy\n      \\onslide<+->{\n        \\begin{equation}\\label{eq:CrossEntropy}\n          \\loss(y,\\hat{y}) = \\sum_{c \\in \\mathcal{C}} -y_c \\log \\left( \\hat{y}_{c} \\right)\n        \\end{equation}\n      }\n  \\end{itemize}\n\\end{frame}\n\n\n\\begin{frame}{Experiment~\\#1: $\\Delta\\loss$ vs.\\ \\#Iterations}\n  \\onslide<+->{\\textbf{Goal}: Study change in adversarial loss for each iteration of PGD}\n  \\begin{itemize}[<+->]\n    \\item \\textbf{\\# Random Restarts}: 20\n  \\end{itemize}\n\n  \\begin{columns}\n    \\begin{column}{0.23\\textwidth}\n      \\begin{center}\n        \\onslide<+->{\\includegraphics[scale=0.32]{loss_v_iter/mnist_standard.pdf}}\n      \\end{center}\n    \\end{column}\n    \\begin{column}{0.2\\textwidth}\n      \\begin{center}\n        \\onslide<+->{\\includegraphics[scale=0.32]{loss_v_iter/mnist_adv.pdf}}\n      \\end{center}\n    \\end{column}\n    \\begin{column}{0.21\\textwidth}\n      \\begin{center}\n        \\onslide<+->{\\includegraphics[scale=0.32]{loss_v_iter/cifar_standard.pdf}}\n      \\end{center}\n    \\end{column}\n    \\begin{column}{0.22\\textwidth}\n      % \\vspace{-9pt}\n      \\begin{center}\n        \\onslide<+->{\\includegraphics[scale=0.32]{loss_v_iter/cifar_adv.pdf}}\n      \\end{center}\n    \\end{column}\n  \\end{columns}\n  \\vfill\n  \\onslide<+->{\\green{\\textbf{Takeaways}}}\n  \\begin{itemize}[<+->]\n    \\item Adversarial training significantly reduces loss on adversarial examples.\n    \\item Loss values are \\textbf{\\blue{well-concentrated}}\n      \\begin{itemize}\n        \\item Echoes \\textit{folklore belief} that neural network training possible since many local minima with similar loss values\n      \\end{itemize}\n  \\end{itemize}\n\\end{frame}\n\n\n\\begin{frame}{Experiment~\\#2: Absence of Outliers}\n  \\onslide<+->{\\textbf{Goal}: Verify security guarantee across many examples \\& random restarts}\n  \\begin{itemize}[<+->]\n    \\item \\textbf{\\# Examples} ($x$): 5\n    \\item \\textbf{\\# Random Restarts}: 100K\n  \\end{itemize}\n\n  \\vspace{-15pt}\n  \\begin{columns}\n    \\begin{column}{0.7\\textwidth}\n      \\begin{center}\n        \\onslide<4->{\\includegraphics[scale=0.19]{loss_hist/mnist}}\n\n        \\onslide<6->{\\includegraphics[scale=0.19]{loss_hist/cifar}}\n      \\end{center}\n    \\end{column}\n    \\begin{column}{0.25\\textwidth}\n      \\vspace{20pt}\n      \\onslide<5->{\n        \\begin{itemize}\n          \\setlength{\\itemsep}{20pt}\n          \\item \\textbf{\\blue{Blue}}: Standard training\n          \\item \\textbf{\\red{Red}}: Adversarial training\n        \\end{itemize}\n      }\n    \\end{column}\n  \\end{columns}\n\n  \\vfill\n  \\onslide<7->{\\green{\\textbf{Takeaway}}: No outliers (i.e., high loss adversarial examples) \\& concentrated losses}\n\\end{frame}\n\n\n\\begin{frame}{Experiment~\\#3: ``Mode Collapse''}\n  \\onslide<+->{\\textbf{\\blue{Mode Collapse}}: Common problem in GANs where the generated outputs have limited diversity.}\n  \\vfill\n  \\onslide<+->{\\textbf{Goal}: Demonstrate that the generated adversarial examples are noticeably distinct:}\n  \\begin{itemize}[<+->]\n    \\item \\textbf{\\# Random Restarts}: 10,000\n    \\item \\textbf{Metric}: Inter-adversarial example (Euclidean) distance\n  \\end{itemize}\n  \\vfill\n  \\onslide<+->{\\textbf{\\green{Result}}: Inter-maxima distance is distributed close to the expected distance between \\textit{two random points} in the $\\ell_{\\infty}$\\-/ball and cosine similarity between points is close to 90\\textsuperscript{$\\circ$}.}\n  \\begin{itemize}[<+->]\n    % \\item Empirically demonstrates no adversarial example ``mode collapse''\n    \\item Recall the ``curse of dimensionality'' so take with a grain of salt\n  \\end{itemize}\n  \\vfill\n  \\onslide<+->{\\textbf{\\green{Takeaway}}: No evidence of mode collapse}\n\\end{frame}\n", "meta": {"hexsha": "4fe58e8a23f7873ea1fa6d1f5b29facb94b6467a", "size": 5353, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/adv_example_experiments.tex", "max_stars_repo_name": "ZaydH/towards_adversarial_robustness", "max_stars_repo_head_hexsha": "c03c7948a7b8a8efefb7f7aa1d420b05c1eaee2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/adv_example_experiments.tex", "max_issues_repo_name": "ZaydH/towards_adversarial_robustness", "max_issues_repo_head_hexsha": "c03c7948a7b8a8efefb7f7aa1d420b05c1eaee2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/adv_example_experiments.tex", "max_forks_repo_name": "ZaydH/towards_adversarial_robustness", "max_forks_repo_head_hexsha": "c03c7948a7b8a8efefb7f7aa1d420b05c1eaee2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2357142857, "max_line_length": 251, "alphanum_fraction": 0.6620586587, "num_tokens": 1669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.33070456392715747}}
{"text": "\\chapter{Formal Concept Analysis}\n\\label{cha:form-conc-analys}\n\nIn this section we shall introduce almost all notions from the area of formal concept\nanalysis that are relevant for this work.  One of the main aspects of formal concept\nanalysis we are interested in are the methods it provides to extract \\emph{implicational\n  dependencies} from data.  To this end, we shall discuss in detail the notions of\n\\emph{implications} in formal contexts, \\emph{bases} of valid implications of formal\ncontexts, and the computation of the \\emph{canonical base} as a particular example of a\nminimal base.  This will be done in Sections~\\ref{sec:implications-sets}\nand~\\ref{sec:bases-implications}.  We shall also discuss related topics like \\emph{Galois\n  connections} and \\emph{closure operators} (Section~\\ref{sec:galois-connections}) and\n\\emph{attribute exploration} (Section~\\ref{sec:attr-expl}).  Before we can do so, however,\nwe have to introduce some of the fundamental notions of formal concept analysis such as\n\\emph{formal contexts} and \\emph{contextual derivation}.  This will be done in\nSection~\\ref{sec:form-cont-cont}.\n\nThe introduction to formal concept analysis as given in this chapter is mainly based\non~\\cite{fca-book}.  Note that this introduction is specifically tailored towards the\npurpose of the whole work.  As such, the following exposition is not complete in the sense\nthat it discusses all the mathematical foundations of formal concept analysis.  In\nparticular, we may omit proofs or details of certain argumentations if they are not\nrelevant for our work.  In case more details are needed, we provide pointers to the\nliterature where those details can be found.\n\n\\section{Formal Contexts and Concept Lattices}\n\\label{sec:form-cont-cont}\n\nWe introduce the basic notions of formal concept analysis in this section.  Most\nimportantly, we shall discuss how formal concept analysis allows us to represent\ncomplete lattices in terms of \\emph{formal concept lattices} using the notion of\n\\emph{formal contexts}.\n\nLet us briefly repeat the basic notions of order theory which are relevant for our further\nconsiderations.  Let $P$ be a set and let ${\\le} \\subseteq P \\times P$ be a binary\nrelation on $P$.  Then the pair $(P, \\le)$ is called a \\emph{(partially) ordered set} if\n$\\le$ is reflexive, transitive and antisymmetric.  Such structures can be visualized in\nterms of \\emph{order diagrams} (often called \\emph{Hasse diagrams}) if they are finite\n(and not too large).  For this we call two elements $x, y \\in P$ with $x < y$\n\\emph{directly neighbored} in $(P, \\le)$ if and only if there does not exist an element $z\n\\in P$ such that $x < z < y$.  Then to visualize $(P, \\le)$ we mark for every element $x\n\\in P$ a node $v_x$ on the plane such that whenever $x < y$ it is true that the ordinate\n(the second coordinate) of $v_x$ is strictly smaller then the one of $v_y$.  Then, we draw\nfor every two elements $x, y$ with $x < y$ which are directly neighbored in $(P, \\le)$ an\nundirected line from $v_x$ to $v_y$.\n\nObserve that this construction is not unique, and there are many different possibilities\n(good and bad) to visualize ordered sets in this way.  Also note that the naming $v_x$ of\nvertices for elements $x$ is arbitrary and can be chosen as it suits.\n\n\\begin{Example}\n  \\label{expl:1}\n  Let us consider the set $\\set{1, 2, 3}$ with the usual order $\\le$ on natural numbers.\n  Then a line diagram of this ordered set is\n  \\begin{center}\n    \\begin{tikzpicture}[every node/.style = {draw, circle, inner sep = 1pt}]\n      \\node (A) {$3$};\n      \\node[below of=A] (B) {$2$};\n      \\node[below of=B] (C) {$1$};\n      \\draw (A) -- (B);\n      \\draw (B) -- (C);\n    \\end{tikzpicture}\n  \\end{center}\n  We can readily read of this diagram that $1 < 2$ and $2 < 3$, because there are lines\n  connecting the corresponding vertices.  But we can also see that $1 < 3$ because there\n  is an \\emph{ascending path} from $1$ to $3$.\n\\end{Example}\n\nMore generally, in a line diagram of an ordered set $(P, \\le)$, two elements $x, y \\in P$\nsatisfy $x \\le y$ if and only if there is an ascending path from $x$ to $y$ in the line\ndiagram (where also paths of length 0 are allowed).\n\n\\begin{Example}\n  \\label{expl:2}\n  Let $P = \\set{ 1, 2, 3 }$ and consider the ordered set $(\\subsets{\\set{1,2,3}},\n  \\subseteq)$, where $\\subsets{\\set{1,2,3}}$ denotes the set of all subsets of\n  $\\set{1,2,3}$.  This set can be visualized as a line diagram as follows:\n  \\begin{center}\n    \\begin{tikzpicture}[every node/.style = {draw, circle, inner sep = 1pt}]\n      \\node (0) at (0,0)  {\\tiny 000};\n      \\node (1) at (-1,1) {\\tiny 100};\n      \\node (2) at (0, 1) {\\tiny 010};\n      \\node (3) at (1, 1) {\\tiny 001};\n      \\node (4) at (-1,2) {\\tiny 110};\n      \\node (5) at (0,2)  {\\tiny 101};\n      \\node (6) at (1,2)  {\\tiny 011};\n      \\node (7) at (0,3)  {\\tiny 111};\n      \\draw{\n        (0) -- (1)\n        (0) -- (2)\n        (0) -- (3)\n        (1) -- (4)\n        (1) -- (5)\n        (2) -- (4)\n        (2) -- (6)\n        (3) -- (5)\n        (3) -- (6)\n        (4) -- (7)\n        (5) -- (7)\n        (6) -- (7)\n      };\n    \\end{tikzpicture}\n  \\end{center}\n  Here we denote subsets of $\\set{1,2,3}$ by sequences of 0 and 1, meaning that the first\n  position is 1 if and only if the number 1 is an element of the corresponding subset, and\n  so on.  Then 101 corresponds to the set $\\set{1,3}$.\n\\end{Example}\n\nAn element $x \\in P$ is said to be the \\emph{smallest element} of $(P, \\le)$ if and only\nif $x \\le y$ is true for all $y \\in P$.  Likewise, $x$ is the \\emph{greatest element} of\n$(P, \\le)$ if and only if $y \\le x$ is true for all $y \\in P$.  Note that neither smallest\nnor greatest elements have to exist in $P$.  However, if these elements exist, they are\nunique.\n\nLet $Q \\subseteq P$.  An element $x \\in Q$ is said to be the \\emph{smallest element} in\n$Q$ (with respect to $(P, \\le)$) if and only if $x \\le y$ is true for all $y \\in Q$;\n\\emph{greatest elements} in $Q$ are defined likewise.  Again, neither smallest nor\ngreatest elements in $Q$ have to exist.\n\nLet $x \\in P$.  The \\emph{order-ideal} ${\\downarrow}x$ and the \\emph{order-filter}\n${\\uparrow} x$ of $x$ in $(P, \\le)$ are defined as\n\\begin{align*}\n  {\\downarrow} x &:= \\set{ y \\in P \\mid y \\le x },\\\\\n  {\\uparrow} x &:= \\set{ y \\in P \\mid x \\le y }.\n\\end{align*}\nIn other words, ${\\downarrow} x$ contains all elements which are \\emph{below} $x$ in $(P,\n\\le)$, and ${\\uparrow} x$ contains all elements which are \\emph{above} $x$ in $(P, \\le)$.\n\nLet again $Q \\subseteq P$.  Then the sets $Q^{*}$ and $Q_{*}$ defined as\n\\begin{align*}\n  Q^{*} &:= \\bigcap_{q \\in Q} {\\uparrow} q,\\\\\n  Q_{*} &:= \\bigcap_{q \\in Q} {\\downarrow} q\n\\end{align*}\nare called the set of \\emph{upper bounds} and \\emph{lower bounds} of $Q$ in $(P, \\le)$,\nrespectively, where we employ the convention that $\\bigcap \\emptyset = P$.  If $Q^{*}$ has\na smallest element (a \\emph{least upper bound}) in $(P, \\le)$, it is called the\n\\emph{supremum} of $Q$ in $(P, \\le)$ and is denoted by $\\sup Q$.  Likewise, if $Q_{*}$ has\na greatest element (a \\emph{greatest lower bound}) in $(P, \\le)$, then it is called the\n\\emph{infimum} of $Q$ in $(P, \\le)$ and is denoted by $\\inf Q$.\n\nNote again that neither infimum nor supremum have to exist in $(P, \\le)$.\n\n\\begin{Example}\n  \\label{expl:3}\n  Let $P = \\set{ a, b, c }$ and let $\\le$ be given by the smallest order relation that\n  satisfies $a < b$ and $a < c$.  Then $\\inf\\set{b,c}$ exists in $(P, \\le)$ and is equal\n  to $a$.  However, $\\sup\\set{b, c}$ does not exist in $(P, \\le)$, as ${\\uparrow} b \\cap\n  {\\uparrow} c = \\emptyset$.\n\\end{Example}\n\n\\noindent%\nStructures in which supremum and infimum always exist for \\emph{finite} sets $Q$ are\ncalled \\emph{lattices}.  If the sets $Q$ can be chosen arbitrary, then we call such a\nstructure a \\emph{complete lattice}.\n\n\\begin{Definition}[Lattice]\n  \\label{def:lattice}\n  Let $\\alg L = (L, \\le)$ be an ordered set.  Then $\\alg L$ is called a \\emph{lattice} if\n  and only if for each non-empty finite $Q \\subseteq L$ there exist both $\\sup Q$ and\n  $\\inf Q$ in $\\alg L$.  If for all $Q \\subseteq L$ there exist both $\\sup Q$ and $\\inf Q$\n  in $\\alg L$, then $\\alg L$ is called a \\emph{complete lattice}.\n\\end{Definition}\n\n\\noindent%\nFrom time to time we may also use another notation for $\\inf$ and $\\sup$: if $Q$ is\nfinite, then $Q = \\set{ q_1, \\dots, q_n }$ and we may write\n\\begin{align*}\n  q_1 \\wedge \\dots \\wedge q_n &\\quad\\text{instead of}\\quad \\inf Q,\\\\\n  q_1 \\vee \\dots \\vee q_n &\\quad\\text{instead of}\\quad \\sup Q.\n\\end{align*}\nIt is also common to write $\\bigwedge Q$ instead of $\\inf Q$, and $\\bigvee Q$ instead of\n$\\sup Q$.\n\nNote that every finite lattice is also a complete lattice.  Moreover, every complete\nlattice has a smallest and greatest element, given by $\\sup\\emptyset$ and $\\inf\\emptyset$,\nrespectively.  Furthermore, every ordered set $(P, \\le)$ in which the supremum exists for\neach $Q \\subseteq P$ is already a complete lattice, as the infimum is then given by\n\\begin{equation*}\n  \\inf Q = \\sup\\set{ x \\in P \\mid \\forall y \\in Q \\holds x \\le y }.\n\\end{equation*}\nThe same is of course true if supremum and infimum are exchanged.\n\nThe ordered sets from Examples~\\ref{expl:1} and~\\ref{expl:2} are lattices, but not the one\nfrom~\\ref{expl:3}.  More generally, if $P$ is a set, then $(\\subsets{P}, \\subseteq)$ is\nalways a complete lattice.\n\nThe study of lattices as mathematical structures has received much interest over the last\ndecades, and thus constitutes a major branch of order\ntheory~\\cite{Gratzer,books/math/Davey02,books/math/Birkhoff67}.  Additionally, (complete)\nlattices also allow for a quite natural interpretation as a hierarchy of\n\\emph{generalizations} and \\emph{specializations}: an element $x$ is below an element $y$\nif and only if $x$ is more \\emph{special} than $y$, or alternatively, if $y$ is more\n\\emph{general} than $x$.  Then for a set $Q$ of elements its supremum $\\sup Q$ can be\nthought of as a \\emph{most-specific generalization} of all elements in $Q$, and $\\inf Q$\ncan be seen likewise as the \\emph{most general specialization} of all elements in $Q$.\n\nFormal concept analysis now provides an approach to understand complete lattice in terms\nof this interpretation, by representing these lattices in terms of \\emph{objects} and\ntheir \\emph{attributes}.  For this, we need to introduce the notion of a \\emph{formal\n  context}.\n\n\\begin{Definition}[Formal Context]\n  \\label{def:formal-context}\n  A \\emph{formal context} $\\con K$ is constituted of three sets $G, M, I$, where $I\n  \\subseteq G \\times M$.  Formally, a formal contexts $\\con K$ is a triple $\\con K = (G,\n  M, I)$ where $G, M$ are sets and $I \\subseteq G \\times M$.  We shall call $G$ the set of\n  \\emph{objects} of $\\con K$, $M$ the set of \\emph{attributes} of $\\con K$ and $I$ the\n  \\emph{incidence} of $\\con K$.  Two formal contexts are equal if and only if their sets\n  of objects, attributes and their incidences are equal, respectively.\n\\end{Definition}\n\nFormal contexts can be thought of as simple data structures which record, for a given set\nof objects $G$ and a given set of attributes $M$, for each object $g \\in G$ the set of\nattributes from $M$ that $g$ has.  More precisely, we shall say that in a formal context\n$\\con K$ an object $g \\in G$ \\emph{has} an attribute $m$ if and only if $(g, m) \\in I$.\n\n\\begin{Example}\n  \\label{expl:star-trek}\n  Let us consider a small toy example $\\con K_{\\mathsf{TNG}}$ to illustrate the definition\n  of a formal context.  As sets of objects we choose some fictional characters from\n  \\emph{Star Trek: The Next Generation}, namely\n  \\begin{equation*}\n    G := \\set{ \\mathsf{Picard}, \\mathsf{Worf}, \\mathsf{Data}, \\mathsf{BorgQueen} }.\n  \\end{equation*}\n  As sets of attributes we choose\n  \\begin{equation*}\n    M := \\set{ \\mathsf{Human}, \\mathsf{Honorable}, \\mathsf{Artificial}, \\mathsf{Star\n        Fleet} }.\n  \\end{equation*}\n  To illustrate the incidence relation of our example formal context we make use of a\n  \\emph{cross table}, \\ie we depict $\\con K_{\\mathsf{TNG}}$ as a table where the rows are\n  labeled with objects and the columns are labeled with attributes.  Then in every cell we\n  write a cross if and only if the object labeling the corresponding row has the attribute\n  labeling the corresponding column.\n  \\begin{equation*}\n    \\def\\x{\\times}\n    \\begin{array}{r|*{4}{c}}\n      \\toprule\n      \\con K_{\\mathsf{TNG}} & \\mathsf{Human} & \\mathsf{Honorable} & \\mathsf{Artificial} & \\mathsf{Star Fleet} \\\\\n      \\midrule\n      \\mathsf{Picard} & \\x & \\x & & \\x \\\\\n      \\mathsf{Worf} & & \\x & & \\x \\\\\n      \\mathsf{Data} & & \\x & \\x & \\x \\\\\n      \\mathsf{BorgQueen} & & & \\x & \\\\\n      \\bottomrule\n    \\end{array}\n  \\end{equation*}\n  Then, for example, \\textsf{BorgQueen} has the attribute \\textsf{Artificial}, but not\n  \\textsf{Honorable}.\n\\end{Example}\n\nTo now expose the connection between formal contexts on the one hand and complete lattices\non the other we shall introduce the \\emph{derivation operators} in formal contexts.\n\n\\begin{Definition}[Contextual Derivation]\n  \\label{def:contextual-derivation}\n  Let $\\con K = (G, M, I)$ be a formal context and let $A \\subseteq G$ be a set of\n  objects.  Then the set of \\emph{common attributes} $A'$ of $A$ is defined to be\n  \\begin{equation*}\n    A' := \\set{ m \\in M \\mid \\forall g \\in G \\holds (g, m) \\in I }.\n  \\end{equation*}\n  Likewise, for a set $B \\subseteq M$ of attributes we define the set $B'$ of \\emph{shared\n    objects} as\n  \\begin{equation*}\n    B' := \\set{ g \\in G \\mid \\forall m \\in M \\holds (g, m) \\in I }.\n  \\end{equation*}\n  The functions $A \\mapsto A'$ and $B \\mapsto B'$ are called the \\emph{derivation\n    operators} of $\\con K$, and the sets $A'$ and $B'$ are called the \\emph{derivations}\n  of $A$ and $B$ in $\\con K$, respectively.\n\\end{Definition}\n\nFor $(A')'$ we may also simply write $A''$.\n\nNote that both derivation operators are denoted by $(\\cdot)'$, which usually does not lead\nto confusion, as it is most often clear from the context whether we deal with a set of\nobjects or a set of attributes from which we want to compute its derivation.  If it\nnevertheless happens that a single name for the derivation operator leads to confusion,\nthen we shall locally introduce separate names for both of them.\n\nWhat occurs more often, for example in Chapters~\\ref{cha:expl-conf}\nand~\\ref{cha:model-expl-conf}, is the derivation of sets in \\emph{different formal\n  contexts}.  For example we may have given two formal contexts $\\con K_1 = (G_1, M_1,\nI_1)$ and $\\con K_2 = (G_2, M_2, I_2)$ and a set $A \\subseteq M_1 \\cap M_2$.  When writing\n$A'$, it is not clear in which context we do the derivation.  To remedy this, we shall add\na subscript to the set $A$ to make clear of which context we consider it as a set of\nattributes: $A_{\\con K_1}$ denotes the set $A$ considered as a set of attributes in $\\con\nK_1$, and likewise $A_{\\con K_2}$.  While this notation is not useful as it stands, it\nbecomes handy if we consider derivations of $A$: $(A_{\\con K_1})'$ denotes the derivation\nof $A$ in the formal context $\\con K_1$, while $(A_{\\con K_2})'$ does the same for the\nformal context $\\con K_2$.  Of course, we can drop the parentheses if that does not lead\nto ambiguity, and write $A_{\\con K_1}'$ and $A_{\\con K_2}'$ instead.  Of course, the same\ncan be done for sets of objects.  In particular, instead of writing $(A_{\\con K_1}')_{\\con\n  K_1}'$ we shall often only write $A_{\\con K_1}''$.\n\n\\begin{Example}\n  \\label{expl:4}\n  Consider our Star Trek example context from~\\ref{expl:star-trek} and let $A :=\n  \\set{\\mathsf{Human}}$.  Then $A' = \\set{ \\mathsf{Picard} }$, $A'' = \\set{\n    \\mathsf{Human}, \\mathsf{Honorable}, \\mathsf{Star Fleet} }$, and $A''' = \\set{\n    \\mathsf{Picard} } = A'$.\n\\end{Example}\n\nThe case that $A''' = A'$ is true in the previous example is not a coincidence, but an\ninstance of a more general result: the derivation operators of a formal context form a\n\\emph{Galois connection} between the ordered sets $(\\subsets{G}, \\subseteq)$ and\n$(\\subsets{M}, \\subseteq)$.\n\n\\begin{Lemma}\n  \\label{lem:derivation-is-galois-connection}\n  Let $\\con K = (G, M, I)$ be a formal context and let $A \\subseteq M$ and $B \\subseteq\n  G$.  Then it is true that\n  \\begin{equation}\n    \\label{eq:1}\n    A \\subseteq B' \\iff B \\subseteq A'.\n  \\end{equation}\n  From this the following properties of the derivation operators of\\/ $\\con K$ can be\n  derived: let $A, A_1, A_2 \\subseteq M$ and $B, B_1, B_2 \\subseteq G$.  Then\n  \\begin{enumerate}[i. ]\n  \\item $A_1 \\subseteq A_2 \\implies A_2' \\subseteq A_1'$,\n  \\item $B_1 \\subseteq B_2 \\implies B_2' \\subseteq B_1'$,\n  \\item $A \\subseteq A''$,\n  \\item $B \\subseteq B''$,\n  \\item $A' = A'''$,\n  \\item $B' = B'''$.\n  \\end{enumerate}\n\\end{Lemma}\n%\nIn the proof of the lemma we shall only show Equation~\\eqref{eq:1}, as the remaining\nclaims then are an immediate consequence of the more general result\nLemma~\\ref{lem:properties-of-galois-connections} on Galois connections.\n%\n\\begin{Proof}[\\thref{lem:derivation-is-galois-connection}]\n  We can easily compute that\n  \\begin{align*}\n    A \\subseteq B'\n    & \\iff \\forall m \\in A \\holds m \\in B' \\\\\n    & \\iff \\forall m \\in A \\;\\forall g \\in B \\holds (g,m) \\in I \\\\\n    & \\iff \\forall g \\in B \\;\\forall m \\in A \\holds (g,m) \\in I \\\\\n    & \\iff \\forall g \\in B \\holds g \\in A' \\\\\n    & \\iff B \\subseteq A'\n  \\end{align*}\n  which shows the claim.\n\\end{Proof}\n\nAnother useful property of the derivation operators is\n\\begin{equation*}\n  A' = \\bigcap_{a \\in A} \\set{a}'\n\\end{equation*}\nfor $A \\subseteq M$.  This can easily be generalized into the following statement.\n\n\\begin{Lemma}\n  \\label{lem:piecewise-derivation}\n  Let $\\con K = (G, M, I)$ be a formal context, let $A \\subseteq M$ and let $(B_j \\mid j\n  \\in J)$ be a family of sets $B_j \\subseteq M$ such that\n  \\begin{equation*}\n    A = \\bigcup_{j \\in J} B_j.\n  \\end{equation*}\n  Then\n  \\begin{equation}\n    \\label{eq:2}\n    A' = \\bigcap \\set{ B_j' \\mid j \\in J }.\n  \\end{equation}\n  In particular, for every $\\mathcal{A} \\subseteq \\subsets{M}$ it is true that\n  \\begin{equation}\n    \\label{eq:3}\n    \\bigcap_{A \\in \\mathcal{A}} A' = \\bigl(\\bigcup_{A \\in \\mathcal{A}} A\\bigr)'.\n  \\end{equation}\n\\end{Lemma}\n%\nOf course, the same is true if $A$ and all $B_j$ are sets of objects instead of sets of\nattributes.\n%\n\\begin{Proof}[\\thref{lem:piecewise-derivation}]\n  Since $B_j \\subseteq A$ for all $j \\in J$, we can infer from\n  \\thref{lem:derivation-is-galois-connection} that $A' \\subseteq B_j'$.  It therefore\n  suffices to show that $A' \\supseteq \\bigcap \\set{ B_j' \\mid j \\in J }$.\n\n  To this end, let $g \\in \\bigcap \\set{ B_j' \\mid j \\in J }$.  Then $g \\in B_j'$ for each\n  $j \\in J$, and therefore $\\set{g}' \\supseteq B_j$, again for all $j \\in J$.  Since $A =\n  \\bigcup_{j \\in J} B_j$, we obtain from this that $\\set{g}' \\supseteq A$, and thus $g \\in\n  A'$, as required.\n\\end{Proof}\n\nWe have claimed earlier that there exists a close connection between complete lattices on\nthe one hand and formal contexts on the other.  Having introduced the derivation\noperators, we are now able to expose this connection.  To this end, we shall introduce the\nnotion of \\emph{formal concepts} of a formal context.\n\n\\begin{Definition}[Formal Concept]\n  \\label{def:formal-concept}\n  Let $\\con K = (G, M, I)$ be a formal context.  Then a \\emph{formal concept} of $\\con K$\n  is a pair $(A, B)$ such that $A \\subseteq G, B \\subseteq M$, and $A' = B, B' = A$ holds.\n  The first entry of a formal concept is called its \\emph{extent}, and the second one\n  called its \\emph{intent}.  The set of all formal concepts of $\\con K$ is denoted by\n  $\\BV(\\con K)$.\n\\end{Definition}\n\nNote that for each $B \\subseteq M$, the pair $(B', B'')$ is a formal concept of $\\con K$.\nMoreover, a set $B \\subseteq M$ is an intent of $\\con K$ if and only if $B = B''$: if $B =\nB''$, then $(B', B)$ is a formal concept of $\\con K$, and if $(A, B)$ is a formal concept\nof $\\con K$, then $B'' = A' = B$.  The same is of course true for $A \\subseteq G$: $A$ is\nan extent of $\\con K$ if and only if $A = A''$.\n\nFormal concepts have a strong philosophical motivation, as they are an attempt to\nformalize the rather vague notion of a \\emph{concept}.  This formalization is based on the\nperception that every formal concept is uniquely determined by the objects which are\ninstances of it, its \\emph{extension}, as well as by a characterization in terms of\nattributes, its \\emph{intension}.  We shall, however, not pursue this philosophical\nmotivation any further here, as it is not immediately relevant for our work.\nSee~\\cite{fca-book} for further discussion and references.\n\n\\begin{Example}\n  \\label{expl:5}\n  Two formal concepts of $\\con K_{\\mathsf{TNG}}$ from Example~\\ref{expl:star-trek} are\n  \\begin{gather*}\n    (\\set{\\mathsf{Picard}}, \\set{\\mathsf{Human}, \\mathsf{Honorable},\n      \\mathsf{StarFleet}}),\\\\\n    (\\set{\\mathsf{Picard}, \\mathsf{Worf}, \\mathsf{Data}}, \\set{\\mathsf{Honorable},\n      \\mathsf{StarFleet}}).\n  \\end{gather*}\n  The first formal concept could be said to represent the concept of an \\emph{honorable\n    human}, which in $\\con K_{\\mathsf{TNG}}$ has \\textsf{Picard} as its only instance.\n  The second formal concept describes everything \\emph{honorable}, having as extension\n  \\textsf{Picard}, \\textsf{Worf} and \\textsf{Data}.\n\\end{Example}\n\nFormal concepts can be ordered by \\emph{generality}: a formal concept $(A_1, B_1)$ is\n\\emph{more general} than another formal concept $(A_2, B_2)$ if it covers more objects,\n\\ie if\n\\begin{equation*}\n  A_1 \\subseteq A_2.\n\\end{equation*}\n\n\\begin{Definition}[Concept Lattice]\n  \\label{def:concept-lattice}\n  Let $\\con K = (G, M, I)$ be a formal context.  We define the relation $\\le$ on $\\BV(\\con\n  K)$ by\n  \\begin{equation*}\n    (A_1, B_1) \\leq (A_2, B_2) \\diff A_1 \\subseteq A_2.\n  \\end{equation*}\n  The structure $\\alg{\\BV}(\\con K) := (\\BV(\\con K), \\leq)$ is called the \\emph{concept\n    lattice} of $\\con K$.\n\\end{Definition}\n\nBy \\thref{lem:derivation-is-galois-connection} we can observe that\n\\begin{equation*}\n  (A_1, B_1) \\leq (A_2, B_2) \\iff B_2 \\subseteq B_1,\n\\end{equation*}\nas $B_1 = A_1'$ and $B_2 = A_2'$.  Furthermore, it is rather easy to see that the relation\n$\\leq$ from \\thref{def:concept-lattice} is an order relation on $\\BV(\\con K)$.  However,\neven more is true, namely that $\\alg{\\BV}(\\con K)$ is indeed a complete lattice.\n\n\\begin{Theorem}\n  \\label{thm:concept-lattices-are-complete-lattices}\n  Let $\\con K$ be a formal context.  Then $\\alg{\\BV}(\\con K)$ is a complete lattice, and\n  for formal concepts $((A_j, B_j) \\mid j \\in J)$ of $\\con K$ we have\n  \\begin{align*}\n    \\sup \\set{ (A_j, B_j) \\mid j \\in J } = \\Bigl( \\bigl( \\bigcap_{j \\in J} B_j \\bigr)' ,\n    \\bigcap_{j \\in J} B_j \\Bigr), \\\\\n    \\inf \\set{ (A_j, B_j) \\mid j \\in J } = \\Bigl( \\bigcap_{j \\in J} A_j, \\bigl( \\bigcap_{j\n      \\in J} A_j \\bigr)' \\Bigr).\n  \\end{align*}\n\\end{Theorem}\n\nOn the other hand, every complete lattice can be represented as a concept lattice of a\nsuitably chosen formal context.  To formalize this correctly, we shall introduce the\nnotion of an \\emph{order isomorphism} between two ordered sets.\n\n\\begin{Definition}[Order Isomorphism]\n  \\label{def:order-isomorphism}\n  Let $\\alg P = (P, \\leq_1)$ and $\\alg Q = (Q, \\leq_2)$ be two ordered sets.  A bijective\n  mapping $\\phi \\colon P \\to Q$ is called an \\emph{order isomorphism} if and only if\n  $\\phi$ is \\emph{order-preserving} and \\emph{order-reflecting}, \\ie it is true for all\n  $a, b \\in P$ that\n  \\begin{equation*}\n    a \\leq_1 b \\iff \\phi(a) \\leq_2 \\phi(b).\n  \\end{equation*}\n\\end{Definition}\n\nThe statement now is that every complete lattice is \\emph{order-isomorphic} to some\nconcept lattice.\n\n\\begin{Theorem}\n  \\label{thm:complete-lattices-are-concept-lattices}\n  Let $\\alg V = (V, \\leq_V)$ be a complete lattice.  Then the mapping $\\phi \\colon V \\to\n  \\BV(\\con K)$ defined by\n  \\begin{equation*}\n    \\phi(v) := (\\set{ w \\in V \\mid w \\leq_V v}, \\set{ w \\in V \\mid v \\leq_V w })\n  \\end{equation*}\n  is an order isomorphism between $\\alg V$ and $\\alg{\\BV}(V, V, \\leq_V)$.\n\\end{Theorem}\n\nBoth \\thref{thm:concept-lattices-are-complete-lattices} and\n\\thref{thm:complete-lattices-are-concept-lattices} are actually part of the Basic Theorem\nof formal concept analysis~\\cite[Theorem 3]{fca-book}.  We shall not give a proof of it\nhere, as it is not within the scope of this work.\n\n\\begin{Example}\n  \\label{expl:star-trek-concept-lattice}\n  Let us consider the formal context $\\con K_{\\mathsf{TNG}}$ of\n  Example~\\ref{expl:star-trek} again, and let us draw the concept lattice of $\\con\n  K_{\\mathsf{TNG}}$ in form of a line diagram.  There are six formal concepts of $\\con\n  K_{\\mathsf{TNG}}$, and they can be depicted as shown in\n  Figure~\\ref{fig:star-trek-concept-lattice}.\n\n  \\begin{figure}[tp]\n    \\centering\n    \\begin{tikzpicture}[scale=2, every node/.style = { draw, circle }]\n      \\node (1) at (0,0) {};\n      \\node (2) at (-1,1) {};\n      \\node (3) at (1,1) {};\n      \\node (4) at (0,2) {};\n      \\node (5) at (2,2) {};\n      \\node (6) at (1,3) {};\n      \\draw {\n        (1) -- (2)\n        (1) -- (3)\n        (2) -- (4)\n        (3) -- (4)\n        (3) -- (5)\n        (4) -- (6)\n        (5) -- (6)\n      };\n      \\begin{scope}[every node/.style = { draw=none, inner sep=1pt, fill=white },\n         node distance = 0.2cm and 0.2cm]\n        \\node[above=of 2] {\\small\\textsf{Human}};\n        \\node[below=of 2] {\\small\\textsf{Picard}};\n        \\node[below=of 3] {\\small\\textsf{Data}};\n        \\node[below=of 4] {\\small\\textsf{Worf}};\n        \\node[above=of 4] {\\small\\textsf{StarFleet}, \\textsf{Honorable}};\n        \\node[below=of 5] {\\small\\textsf{BorgQueen}};\n        \\node[above=of 5] {\\small\\textsf{Artificial}};\n      \\end{scope}\n    \\end{tikzpicture}\n    \\caption{Drawing of the concept lattice of $\\con K_{\\mathsf{TNG}}$}\n    \\label{fig:star-trek-concept-lattice}\n  \\end{figure}\n\n  The line diagram of Figure~\\ref{fig:star-trek-concept-lattice} uses an abridged\n  annotation which is common for concept lattices: instead of annotating every node in the\n  diagram with the formal concept it represents (which would yield an unreadable diagram),\n  we only write every object $g$ of $\\con K_{\\mathsf{TNG}}$ below the \\emph{smallest}\n  formal concept that has $g$ in its extent.  This formal concept always exists by\n  \\thref{thm:concept-lattices-are-complete-lattices}.  Then, by the definition of the\n  order on formal concepts, every formal concept which can be reached from the one labeled\n  with $g$ by an \\emph{ascending} path in the line diagram has $g$ in its extent, and all\n  other formal concepts do not.  For example, the formal concept labeled with\n  \\textsf{Picard} has this object in its extent, as well as the two formal concepts above\n  it.  No other formal concept has \\textsf{Picard} in its extent.\n\n  Likewise, we write every attribute $m$ of $\\con K_{\\mathsf{TNG}}$ only at the\n  \\emph{largest} formal concept that has this attribute in its intent.  Then every formal\n  concept that can be reached from the one labeled with $m$ by a \\emph{descending} path in\n  the line diagram has $m$ in its intent, and all the others do not.  Therefore, the node\n  labeled with \\textsf{Artificial} has this attribute in its intent, as has the formal\n  concept labeled with \\textsf{Data} and the bottom concept.  No other formal concept has\n  \\textsf{Artificial} in its intent.\n\\end{Example}\n\n\\section{Galois Connections and Closure Operators}\n\\label{sec:galois-connections}\n\nFor the proof of \\thref{lem:derivation-is-galois-connection} we invoked some general\narguments from the theory of Galois connections between ordered sets.  The notion of a\nGalois connection is fundamental for order theory, and is closely connected to other\nimportant concepts such as closure operators.  As both Galois connections and closure\noperators play an important role in this work, we shall review their general theory in\nthis section, to the extent needed in this work.\n\n\\begin{Definition}[Galois Connection]\n  \\label{def:galois-connection}\n  Let $\\alg P = (P, \\leq_P), \\alg Q = (Q, \\leq_Q)$ be two ordered sets, and let $\\phi\n  \\colon P \\to Q$ and $\\psi \\colon Q \\to P$ be two mappings.  Then the tuple $(\\alg P,\n  \\alg Q, \\phi, \\psi)$ is called a \\emph{Galois connection} between $\\alg P$ and $\\alg Q$\n  if and only if\n  \\begin{equation}\n    \\label{eq:4}\n    x \\leq_P \\psi(y) \\iff y \\leq_Q \\phi(x)\n  \\end{equation}\n  is true for all $x \\in P$, $y \\in Q$.\n\\end{Definition}\n\nNote that this form of a Galois connection is sometimes called an \\emph{antitone} Galois\nconnection, as the position of the elements $x$ and $y$ is reversed.  There is the\ncorresponding notion of an \\emph{isotone} Galois connection, where Equation~\\eqref{eq:4}\nis replaced by\n\\begin{equation}\n  \\label{eq:5}\n  x \\leq_P \\psi(y) \\iff \\phi(x) \\leq_Q y.\n\\end{equation}\nOf course, both notions are closely related: if we denote with $\\alg Q^d = (Q,\n\\leq_Q^{-1})$ the \\emph{dual} of the ordered set $\\alg Q$, then $(\\alg P, \\alg Q, \\phi,\n\\psi)$ is an antitone Galois connection if and only if $(\\alg P, \\alg Q^d, \\phi, \\psi)$ is\nan isotone Galois connection.\n\n\\begin{Example}\n  Two examples of Galois connections are the following.\n  \\begin{enumerate}[i. ]\n  \\item If $\\phi$ is an order isomorphism from $\\alg P = (P, \\leq_P)$ to $\\alg Q = (Q,\n    \\leq_Q)$, then $(\\alg P, \\alg Q, \\phi, \\phi^{-1})$ is an isotone Galois connection,\n    because\n    \\begin{align*}\n      x \\leq_P \\phi^{-1}(y)\n      &\\iff \\phi(x) \\leq_Q \\phi(\\phi^{-1}(y))\\\\\n      &\\iff \\phi(x) \\leq_Q y\n    \\end{align*}\n    is true for all $x \\in P$ and $y \\in Q$.\n\n    On the other hand, if $\\phi \\colon P \\to Q$ is a bijective mapping such that $(\\alg P,\n    \\alg Q, \\phi, \\phi^{-1})$ is an isotone Galois connection, then clearly $\\phi$ is an\n    order isomorphism by \\thref{lem:properties-of-galois-connections}.  In this sense,\n    Galois connections are a generalization of order isomorphisms.\n  \\item If $\\con K = (G, M, I)$ is a formal context, then the derivation operators\n    $(\\cdot)' \\colon \\subsets{G} \\to \\subsets{M}$ and $(\\cdot)' \\colon \\subsets{M} \\to\n    \\subsets{G}$ form an antitone Galois connection by\n    \\thref{lem:derivation-is-galois-connection}.\n  \\end{enumerate}\n\\end{Example}\n\nIndeed, the converse of the last example is also true to some extent, \\ie every antitone\nGalois connection between powerset lattices $(\\subsets{G}, \\subseteq), (\\subsets{M},\n\\subseteq)$ can be represented by a formal context $\\con K$, such that the derivation\noperators of $\\con K$ are just the mappings from the Galois connections.  However, we\nshall not go into details here, as this is not relevant for the purpose of our work.\nSee~\\cite{fca-book} for more details.\n\nInstead, we shall review some useful properties of antitone Galois connections.\n\n\\begin{Lemma}\n  \\label{lem:properties-of-galois-connections}\n  Let $(\\alg P, \\alg Q, \\phi, \\psi)$ be an antitone Galois connection between the ordered\n  sets $\\alg P = (P, {\\leq_P})$ and $\\alg Q = (Q, \\leq_Q)$.  Then the following statements\n  hold for all $a_1, a_2 \\in P$ and $b_1, b_2 \\in Q$:\n  \\begin{enumerate}[i. ]\n  \\item\\label{item:1} $a_1 \\leq_P a_2 \\implies \\phi(a_2) \\leq_Q \\phi(a_1)$,\n  \\item\\label{item:2} $b_1 \\leq_Q b_2 \\implies \\psi(b_2) \\leq_P \\psi(b_1)$,\n  \\item\\label{item:3} $a_1 \\leq_P \\psi(\\phi(a_1))$,\n  \\item\\label{item:4} $b_1 \\leq_Q \\phi(\\psi(b_1))$,\n  \\item\\label{item:5} $\\phi(a_1) = \\phi(\\psi(\\phi(a_1)))$,\n  \\item\\label{item:6} $\\psi(b_1) = \\psi(\\phi(\\psi(b_1)))$.\n  \\end{enumerate}\n\\end{Lemma}\n\\begin{Proof}\n  We only show statements~(\\ref{item:1}), (\\ref{item:3}) and~(\\ref{item:5}), as the others\n  follow from similar arguments.\n\n  We immediately obtain the truth of~(\\ref{item:3}), since from $\\phi(a_1) \\leq_Q\n  \\phi(a_1)$ we can infer $a_1 \\leq_P \\psi(\\phi(a_1))$ by \\Cref{eq:4} of a Galois\n  connection.\n\n  Then for~(\\ref{item:1}) we assume $a_1 \\leq_P a_2$ and obtain from~(\\ref{item:3}) that\n  then $a_1 \\leq_P \\psi(\\phi(a_2))$.  Using again the definition of a Galois connection we\n  obtain that $\\phi(a_2) \\leq_Q \\phi(a_1)$.\n\n  Finally, for~(\\ref{item:5}) we already know that $\\phi(\\psi(\\phi(a_1))) \\leq_Q\n  \\phi(a_1)$ is true.  On the other hand, $\\psi(\\phi(a_1)) \\leq_P \\psi(\\phi(a_1))$, so by\n  the definition of a Galois connection, we obtain $\\phi(a_1) \\leq_Q\n  \\phi(\\psi(\\phi(a_1)))$.  Since $\\leq_Q$ is antisymmetric, equality follows.\n\\end{Proof}\n\nGalois connections are closely related to the notion of \\emph{closure operators}.\n\n\\begin{Definition}[Closure Operator]\n  \\label{def:closure-operator}\n  Let $\\alg P = (P, \\leq_P)$ be an ordered set, and let $c \\colon P \\to P$ be a mapping.\n  Then $c$ is called a \\emph{closure operator} on $\\alg P$ if and only if\n  \\begin{enumerate}[i. ]\n  \\item $a \\leq_P c(a)$ for all $a \\in P$ ($c$ is \\emph{extensive}),\n  \\item $a \\leq_P b \\implies c(a) \\leq_P c(b)$ for all $a, b \\in P$ ($c$ is\n    \\emph{monotone}), and\n  \\item $c(a) = c(c(a))$ for all $a \\in P$ ($c$ is \\emph{idempotent}).\n  \\end{enumerate}\n  The element $c(a)$ for $a \\in P$ is called the \\emph{closure} of $a$ under $c$.  An\n  element $a \\in P$ is called \\emph{closed} under $c$ if and only if $a = c(a)$.\n\\end{Definition}\n\nClosure operators arise naturally in many situations, and we shall encounter them in the\nnext section when we introduce implications.  Moreover, closure operators and Galois\nconnections always appear together: If $(\\alg P, \\alg Q, \\phi, \\psi)$ is a Galois\nconnection, then the mapping $\\psi \\circ \\phi$ is a closure operator on $\\alg P$, and the\nmapping $\\phi \\circ \\psi$ is a closure operator on $\\alg Q$.  This is true because we know\nthat $\\psi \\circ \\phi$ is extensive\n(\\ref{lem:properties-of-galois-connections},~\\ref{item:3}), monotone\n(\\ref{lem:properties-of-galois-connections},~\\ref{item:1} and~\\ref{item:2}) and idempotent\n(\\ref{lem:properties-of-galois-connections},~\\ref{item:5}), \\ie a closure operator.\nShowing that $\\phi \\circ \\psi$ is a closure operator as well can be done similarly.\n\nConversely, if $c$ is a closure operator on the ordered set $\\alg P$, then there always\nexists a Galois connection $(\\alg P, \\alg Q, \\phi, \\psi)$ such that $c = \\psi \\circ \\phi$.\nSee~\\cite{fca-book} for more details on this.\n\nThere are two interesting properties of closure operators which are also relevant for our\npurpose.  The first observation is that if $c$ is a closure operator on the ordered set\n$\\alg P$ then the infimum $c(x) \\wedge c(y)$ is again closed under $c$ for all $x, y \\in\nP$.  This is because on the one hand we have\n\\begin{align*}\n  c(c(x) \\wedge c(y)) &\\leq_P c(c(x)) = c(x),\\\\\n  c(c(x) \\wedge c(y)) &\\leq_P c(c(y)) = c(y),\n\\end{align*}\nby monotonicity and idempotency of $c$.  Therefore $c(c(x) \\wedge c(y)) \\leq_P c(x) \\wedge\nc(y)$.  On the other hand, $c(x) \\wedge c(y) \\leq_P c(c(x) \\wedge c(y))$ because $c$ is\nextensive, and thus\n\\begin{equation}\n  \\label{eq:13}\n  c(c(x) \\wedge c(y)) = c(x) \\wedge c(y),\n\\end{equation}\n\\ie $c(x) \\wedge c(y)$ is closed.  It is also not hard to see that this argumentation can\nbe lifted to arbitrary infima, \\ie for all $Q \\subseteq P$, the element\n\\begin{equation*}\n  \\bigwedge_{x \\in Q} c(x)\n\\end{equation*}\nis closed under $c$.  In other words, the closed sets of $c$ always form a complete\nsublattice of $\\alg P$.  In particular, for all $x \\in P$ there always exists a smallest\nelement $z \\in P$ above $x$ which is closed under $c$, namely\n\\begin{equation*}\n  z = \\bigwedge_{y \\in P, x \\leq_P c(y)} c(y) = c(x).\n\\end{equation*}\n\n\\section{Implications}\n\\label{sec:implications-sets}\n\nLet us recall \\Cref{expl:star-trek}, were we had considered the formal context $\\con\nK_{\\mathsf{TNG}}$ with\n\\begin{equation*}\n  \\def\\x{\\times}\n  \\begin{array}{r|*{4}{c}}\n    \\toprule\n    \\con K_{\\mathsf{TNG}} & \\mathsf{Human} & \\mathsf{Honorable} & \\mathsf{Artificial} & \\mathsf{StarFleet} \\\\\n    \\midrule\n    \\mathsf{Picard} & \\x & \\x & & \\x \\\\\n    \\mathsf{Worf} & & \\x & & \\x \\\\\n    \\mathsf{Data} & & \\x & \\x & \\x \\\\\n    \\mathsf{BorgQueen} & & & \\x & \\\\\n    \\bottomrule\n  \\end{array}\n\\end{equation*}\nIn this formal context we see that whenever an object has the attribute\n\\textsf{StarFleet}, it also has the attribute \\textsf{Honorable}.  This expresses a\ncertain dependency between these two attributes, in the sense that \\textsf{StarFleet}\n\\emph{implies} \\textsf{Honorable} in the formal context $\\con K_{\\mathsf{TNG}}$.  Knowing\nsuch \\emph{implicational dependencies} between attributes in a formal context can be very\nhelpful, for example for reducing databases by transferring them into suitable normal\nforms or, as in our case, for learning knowledge from data.\n\nWe will model such implicational dependencies by means of \\emph{implications} on sets,\nwhich will be \\emph{valid} in a formal context.\n\n\\begin{Definition}[Implications, Validity in Formal Contexts]\n  Let $M$ be a set.  Then an implication $A \\to B$ on $M$ is constituted of two sets $A, B\n  \\subseteq M$, where $A$ is called the \\emph{premise} of $A \\to B$, and $B$ is called the\n  \\emph{conclusion} of $A \\to B$.  The set of all implications on $M$ is denoted by\n  $\\Imp(M)$.\n\n  Let $\\con K = (G, M, I)$ be a formal context.  An implication $(A \\to B) \\in \\Imp(M)$ is\n  said to be \\emph{valid} in $\\con K$ (or: \\emph{holds} in $\\con K$) if and only if $A'\n  \\subseteq B'$.  We shall write $\\con K \\models (A \\to B)$ in this case, and $\\con K\n  \\models \\mathcal{L}$, where $\\mathcal{L} \\subseteq \\Imp(M)$ is a set of valid\n  implications of $\\con K$.  The set of all valid implications of $\\con K$ is called the\n  \\emph{(implicational) theory} of $\\con K$, and is denoted by $\\Th(\\con K)$.\n\\end{Definition}\n\nNote that the condition $A' \\subseteq B'$ on the validity of an implication $A \\to B$ in\n$\\con K$ can be characterized as saying that every object which has all attributes from\n$A$ has all attributes from $B$.  This coincides with our initial example.\n\nMoreover, the condition $A' \\subseteq B'$ can equally be rephrased as\n\\begin{equation}\n  \\label{eq:6}\n  B \\subseteq A'',\n\\end{equation}\n\\ie all elements of the conclusion of $A \\to B$ are in the closure of the premise with\nrespect to the closure operator $(\\cdot)''$.  This little observation can be helpful for\nproofs.\n\n\\begin{Example}\n  \\label{expl:6}\n  As already mentioned, the implication $\\set{ \\mathsf{StarFleet} } \\to \\set{\n    \\mathsf{Honorable} }$ holds in $\\con K_{\\mathsf{TNG}}$.  On the other hand, the\n  implication $\\set{ \\mathsf{Artificial} } \\to \\set{ \\mathsf{Human} }$ is not valid in\n  $\\con K_{\\mathsf{TNG}}$.\n\\end{Example}\n\nImplications introduce a flavor of logic into formal concept analysis (indeed,\nimplications can be seen as a notational variant of definite Horn formulas of the\npropositional variables $M$).  As such, we can talk about \\emph{entailment} between\nimplications in a very natural sense.\n\n\\begin{Example}\n  \\label{expl:7}\n  In $\\con K_{\\mathsf{TNG}}$ the implications\n  \\begin{align*}\n    \\set{ \\mathsf{Human} } &\\to \\set{ \\mathsf{Honorable} } \\\\\n    \\set{ \\mathsf{Honorable} } &\\to \\set{ \\mathsf{StarFleet} } \\\\\n    \\set{ \\mathsf{Human} } &\\to \\set{ \\mathsf{StarFleet} }\n  \\end{align*}\n  are all valid.  However, we can intuitively see that the implication $\\set{\n    \\mathsf{Human} } \\to \\set{ \\mathsf{StarFleet} }$ is entailed by the other two: by the\n  first implication, every object that has \\textsf{Human} as attribute has also\n  \\textsf{Honorable} as attribute.  By the second implication, every object that has\n  \\textsf{Honorable} as attribute also has \\textsf{StarFleet} as attribute.  Therefore,\n  every object that has \\textsf{Human} as attribute also has \\textsf{StarFleet} as\n  attribute.\n\\end{Example}\n\nWe shall put this more formally in the following definition.\n\n\\begin{Definition}[Entailment between Implications]\n  \\label{def:entailment-between-implications}\n  Let $M$ be a set and let $\\mathcal{L} \\subseteq \\Imp(M)$.  Then an implication $(A \\to\n  B) \\in \\Imp(M)$ is \\emph{entailed by} $\\mathcal{L}$, written $\\mathcal{L} \\models (A \\to\n  B)$, if and only if for all formal contexts $\\con K$ with attribute set $M$ it is true that\n  \\begin{equation*}\n    \\con K \\models \\mathcal{L} \\implies \\con K \\models (A \\to B).\n  \\end{equation*}\n  We shall denote with $\\Cn_M(\\mathcal{L})$ the set of all implications on $M$ which\n  follow from $\\mathcal{L}$.  We may drop the subscript $M$, and may only write\n  $\\Cn(\\mathcal{L})$, if it is clear from the context.\n\n  If $\\mathcal{K} \\subseteq \\Imp(M)$, then we say that $\\mathcal{L}$ and $\\mathcal{K}$ are\n  \\emph{equivalent} if and only if $\\Cn_M(\\mathcal{L}) = \\Cn_M(\\mathcal{K})$.\n\\end{Definition}\n\nThe mapping $\\Cn_M \\colon \\subsets{\\Imp(M)} \\to \\subsets{\\Imp(M)}$ is a first example of a\nclosure operator which arises due to implications.  However, there is also another closure\noperator induced by a set $\\mathcal{L}$ of implications, which lets us easily decide\nwhether an implication $A \\to B$ follows from $\\mathcal{L}$ or not.\n\n\\begin{Definition}[Induced Closure Operator]\n  \\label{def:induced-closure-operator}\n  Let $M$ be a set and let $\\mathcal{L} \\subseteq \\Imp(M)$.  Define for $X \\subseteq M$\n  \\begin{align*}\n    \\mathcal{L}^1(X) &:= X \\cup \\bigcup \\set{ B \\mid (A \\to B) \\in \\mathcal{L}, A\n      \\subseteq X }, \\\\\n    \\mathcal{L}^{i + 1} &:= \\mathcal{L}^1(\\mathcal{L}^i(X)) \\quad (i \\in \\NN_{> 0}).\n  \\end{align*}\n  Then the \\emph{induced closure operator} of $\\mathcal{L}$ is defined by the mapping $X\n  \\mapsto \\mathcal{L}(X)$, where\n  \\begin{equation*}\n    \\mathcal{L}(X) := \\bigcup_{i \\in \\NN_{>0}}\\mathcal{L}^i(X).\n  \\end{equation*}\n  If no confusion is possible, we shall denote the closure operator induced by\n  $\\mathcal{L}$ again with $\\mathcal{L}$, \\ie we shall identify the set of implications\n  and its induced closure operator.\n\\end{Definition}\n\nIt is easy to see that the induced closure operator is indeed a closure operator on\n$(\\subsets{M}, \\subseteq)$.  Furthermore, the induced closure operator yields a\ncharacterization of entailment between implications.  For this we first consider some\ntechnical results.\n\n\\begin{Proposition}\n  \\label{prop:sound-implications-do-not-yield-more-then-doubleprime}\n  Let $\\con K = (G, M, I)$ be a formal context and let $\\mathcal{L} \\subseteq \\Th(\\con K)$\n  a set of valid implications of $\\con K$.  Then\n  \\begin{equation*}\n    \\mathcal{L}(A) \\subseteq A''.\n  \\end{equation*}\n\\end{Proposition}\n\\begin{Proof}\n  By \\thref{lem:derivation-is-galois-connection}, it suffices to show that $A' \\subseteq\n  \\mathcal{L}(A)'$.  Let $g \\in A'$.  If then $(X \\to Y) \\in \\mathcal{L}$ is such that $X\n  \\subseteq A$, then\n  \\begin{equation*}\n    g \\in A' \\subseteq X' \\subseteq Y',\n  \\end{equation*}\n  since $X \\to Y$ holds in $\\con K$.  Therefore,\n  \\begin{equation*}\n    g \\in A' \\cap \\bigcap \\set{ Y' \\mid (X \\to Y) \\in \\mathcal{L}, X \\subseteq A }.\n  \\end{equation*}\n  However,\n  \\begin{align*}\n    & \\phantom{{}={}} A' \\cap \\bigcap \\set{ Y' \\mid (X \\to Y) \\in \\mathcal{L}, X \\subseteq A} \\\\\n    & = (A \\cup \\bigcup \\set{ Y \\mid (X \\to Y) \\in \\mathcal{L}, X \\subseteq A })'\\\\\n    & = (\\mathcal{L}^1(A))'\n  \\end{align*}\n  by \\thref{lem:piecewise-derivation}, and thus $g \\in (\\mathcal{L}^1(A))'$.  Iterating\n  this argumentation yields $g \\in (\\mathcal{L}^i(A))'$ for all $i \\in \\NN_{>0}$, and\n  therefore\n  \\begin{equation*}\n    g \\in \\bigcap_{i \\in \\NN_{>0}} (\\mathcal{L}^i(A))' = \\bigl( \\bigcup_{i \\in \\NN_{>0}}\n    \\mathcal{L}^i(A) \\bigr)' = (\\mathcal{L}(A))'\n  \\end{equation*}\n  as required.\n\\end{Proof}\n\n\\begin{Proposition}\n  \\label{prop:context-model-for-implications}\n  Let $\\mathcal{L} \\subseteq \\Imp(M)$ for some set $M$.  Then the formal context\n  \\begin{equation*}\n    \\con K_{\\mathcal{L}} := ( \\set{ \\mathcal{L}(A) \\mid A \\subseteq M }, M, \\ni )\n  \\end{equation*}\n  satisfies $X'' = \\mathcal{L}(X)$ for all $X \\subseteq M$.\n\\end{Proposition}\n\nNote that this proposition has the interesting consequence that $\\Th(\\con K_{\\mathcal{L}})\n= \\Cn_M(\\mathcal{L})$.  In other words, every set $\\mathcal{L}$ of implications which is\nclosed under $\\Cn_M$ can be represented as a theory of a suitable chosen formal context,\nnamely $\\con K_{\\mathcal{L}}$.\n\n\\begin{Proof}\n  It is easy to see that $\\mathcal{K}_{\\mathcal{L}} \\models \\mathcal{L}$: if $(X \\to Y)\n  \\in \\mathcal{L}$ and $g \\in X'$, then $\\set{g}' \\supseteq X$.  However, every set\n  $\\set{g}'$ is of the form $\\mathcal{L}(A)$ for some $A \\subseteq M$.  Therefore, we have\n  $\\mathcal{L}(A) \\supseteq X$.  Applying $\\mathcal{L}$ on both sides yields\n  $\\mathcal{L}(A) \\supseteq \\mathcal{L}(X)$.  Since $(X \\to Y) \\in \\mathcal{L}$, $Y\n  \\subseteq \\mathcal{L}(X)$ and therefore $\\set{g}' \\supseteq \\mathcal{L}(X) \\supseteq Y$,\n  so $g \\in Y'$ as required.\n\n  For the other direction $\\mathcal{L}(X) \\supseteq X''$ we first show $(\\mathcal{L}(X))''\n  = \\mathcal{L}(X)$.  Then $X \\subseteq \\mathcal{L}(X)$ implies\n  \\begin{equation*}\n    X'' \\subseteq (\\mathcal{L}(X))'' = \\mathcal{L}(X).\n  \\end{equation*}\n\n  We compute\n  \\begin{equation*}\n    (\\mathcal{L}(X))' = \\set{ \\mathcal{L}(A) \\mid A \\subseteq M, \\mathcal{L}(A) \\supseteq\n      \\mathcal{L}(X) },\n  \\end{equation*}\n  and obtain in particular that $\\mathcal{L}(X) \\in (\\mathcal{L}(X))'$.  On the other\n  hand, for a subset $\\mathcal{A}$ of objects of $\\con K_{\\mathcal{L}}$ we have\n  \\begin{equation*}\n    \\mathcal{A}' = \\bigcap_{A \\in \\mathcal{A}} A,\n  \\end{equation*}\n  since the incidence relation of $\\con K_{\\mathcal{L}}$ is just $\\ni$.  Therefore,\n  \\begin{align*}\n    (\\mathcal{L}(X))'' &= \\set{ \\mathcal{L}(A) \\mid A \\subseteq M, \\mathcal{L}(A)\n      \\supseteq \\mathcal{L}(X) }' \\\\\n    &= \\bigcap \\set{ \\mathcal{L}(A) \\mid A \\subseteq M, \\mathcal{L}(A) \\supseteq\n      \\mathcal{L}(X) } \\\\\n    &= \\mathcal{L}(X),\n  \\end{align*}\n  as required.\n\\end{Proof}\n\nBased on these two technical results we can now rephrase entailment between implications\nin terms of induced closure operators.\n\n\\begin{Lemma}\n  \\label{lem:characterization-of-entailment-in-terms-of-induced-closure-operators}\n  Let $M$ be a set and let $\\mathcal{L} \\subseteq \\Imp(M)$.  Then for $(A \\to B) \\in\n  \\mathcal{L}$ it is true that\n  \\begin{equation}\n    \\label{eq:7}\n    \\mathcal{L} \\models (A \\to B) \\iff B \\subseteq \\mathcal{L}(A).\n  \\end{equation}\n\\end{Lemma}\n\\begin{Proof}\n  Suppose that $\\mathcal{L} \\models (A \\to B)$.  For the formal context $\\con\n  K_{\\mathcal{L}}$ from \\thref{prop:context-model-for-implications} we have\n  \\begin{equation*}\n    \\mathcal{L}(X) = X''\n  \\end{equation*}\n  for all $X \\subseteq M$.  Since $\\con K_{\\mathcal{L}} \\models (A \\to B)$, $A' \\subseteq\n  B'$ is true in $\\con K_{\\mathcal{L}}$.  But then\n  \\begin{equation*}\n    B \\subseteq A'' = \\mathcal{L}(A)\n  \\end{equation*}\n  as required.\n\n  Conversely, let $B \\subseteq \\mathcal{L}(A)$, and let $\\con K$ be a formal context such\n  that $\\con K \\models \\mathcal{L}$.  Then $\\mathcal{L}(A) \\subseteq A''$ by\n  \\thref{prop:sound-implications-do-not-yield-more-then-doubleprime}, and therefore $B\n  \\subseteq \\mathcal{L}(A) \\subseteq A''$.  But then $A' \\subseteq B'$, \\ie $A \\to B$\n  holds in $\\con K$.  Since $\\con K$ was chosen arbitrarily, it follows that $\\mathcal{L}\n  \\models (A \\to B)$.  \n\\end{Proof}\n\nThe computation of $\\mathcal{L}(A)$ for sets $A \\subseteq M$ can be done naively with time\nquadratic in $\\abs{\\mathcal{L}}$, assuming the size of the underlying set $M$ is fixed.\nHowever, one can improve this by using the \\enquote{LinClosure} algorithm from the theory\nof relational databases~\\cite{DBLP:books/cs/Maier83}, which achieves the same goal with\ntime linear in $\\abs{\\mathcal{L}}$.  Finally, one can also exploit the tight connection to\nHorn-formulas as mentioned above, and use the algorithm by Dowling and Gallier to decide\nsatisfiability of Horn formulas in linear time~\\cite{DBLP:journals/jlp/DowlingG84}.\n\n\\section{Bases of Implications}\n\\label{sec:bases-implications}\n\nWhen studying the valid implications of a formal context, it may be helpful not to\nconsider the whole set, but a smaller still equivalent set of implications.  The advantage\nof this approach is that this smaller set may be much easier to handle, especially from a\ncomputational point of view.  We therefore introduce in this section the notion of a\n\\emph{base} of a set of implications, and introduce a well known minimal base of all valid\nimplications of a formal context, the \\emph{canonical base}.\n\n\\begin{Definition}[Sound and Complete Sets of Implications, Bases]\n  \\label{def:sound-complete-base}\n  Let $\\mathcal{L} \\subseteq \\Imp(M)$ be a set of implications on a set $M$.  A set\n  $\\mathcal{K} \\subseteq \\Imp(M)$ of implications on $M$ is called \\emph{sound} for\n  $\\mathcal{L}$ if $\\Cn_M(\\mathcal{K}) \\subseteq \\Cn_M(\\mathcal{L})$.  The set\n  $\\mathcal{K}$ is called \\emph{complete} for $\\mathcal{L}$ if $\\Cn_M(\\mathcal{K})\n  \\supseteq \\Cn_M(\\mathcal{L})$.  Finally, the set $\\mathcal{K}$ is called a \\emph{base}\n  of $\\mathcal{L}$ if $\\mathcal{K}$ is sound and complete for $\\mathcal{L}$, \\ie if\n  \\begin{equation}\n    \\label{eq:8}\n    \\Cn_M(\\mathcal{K}) = \\Cn_M(\\mathcal{L}).\n  \\end{equation}\n  If $\\mathcal{L} = \\Th(\\con K)$, then a set $\\mathcal{K}$ which is sound or complete for\n  $\\mathcal{L}$ is also called sound or complete for $\\con K$, respectively.  Moreover, we\n  shall call bases of $\\mathcal{L}$ also bases of $\\con{K}$.\n\n  A base $\\mathcal{K}$ of $\\mathcal{L}$ is called \\emph{irredundant} if no proper subset\n  of $\\mathcal{K}$ is a base of $\\mathcal{L}$.  $\\mathcal{K}$ is called \\emph{minimal}, if\n  there does not exist a base of $\\mathcal{L}$ of smaller cardinality.\n\\end{Definition}\n\nNote that any base of a set $\\mathcal{L}$ is also a base of $\\Cn_M(\\mathcal{L})$, and vice\nversa.\n\nA simple example of a base of a formal context $\\con K = (G, M, I)$ is the set\n\\begin{equation}\n  \\label{eq:10}\n  \\mathcal{K} = \\set{ A \\to A'' \\mid A \\subseteq M, A \\neq A'' }.\n\\end{equation}\nObviously, this set contains only valid implications of $\\con K$.  Furthermore, if $A \\to\nB$ holds in $\\con K$, then $B \\subseteq A''$, and by\n\\thref{lem:characterization-of-entailment-in-terms-of-induced-closure-operators}, $A \\to\nB$ follows from $\\set{ A \\to A'' }$, and thus from $\\mathcal{K}$.  From this we can also\ninfer that\\footnote{This notation $\\Th(\\con K)(A)$ may be a bit misleading.  What is meant\n  here is that the induced closure operator of the set $\\Th(\\con K)$ of implications is\n  applied to $A$, so this expression could also be written as $(\\Th(\\con K))(A)$.}\n\\begin{equation*}\n  \\Th(\\con K)(A) = A''\n\\end{equation*}\nfor all $A \\subseteq M$, because\n\\begin{equation*}\n  \\Th(\\con K)(A) = \\mathcal{K}(A) = A''.\n\\end{equation*}\nTo see the latter equality we first observe that $\\mathcal{K}(A) \\supseteq A''$, because\n$(A \\to A'') \\in \\mathcal{K}$.  On the other hand, $A''$ is closed under $\\mathcal{K}$ and\nis a superset of $A$, thus $\\mathcal{K}(A) \\subseteq A''$, and so equality holds.\n\nChecking soundness of a set of implications $\\mathcal{L} \\subseteq \\Imp(M)$ for a formal\ncontext $\\con K$ is rather trivial, but checking completeness of $\\mathcal{L}$ for $\\con\nK$ is not so easy (indeed, it is coNP-complete~\\cite[Theorem\n12]{DBLP:journals/jair/Khardon95}).  There is a simple characterization, however, if\n$\\mathcal{L}$ is complete for a formal context, which is at least helpful for proofs.\n\n\\begin{Lemma}\n  \\label{lem:characterization-of-completeness}\n  Let $\\con K = (G, M, I)$ be a formal context and let $\\mathcal{L} \\subseteq \\Imp(M)$.\n  Then $\\mathcal{L}$ is complete for $\\con K$ if and only if\n  \\begin{equation}\n    \\label{eq:9}\n    \\forall U \\subseteq M \\holds \\mathcal{L}(U) = U \\implies U = U''.\n  \\end{equation}\n\\end{Lemma}\n\\begin{Proof}\n  Assume that $\\mathcal{L}$ is complete for $\\con K$ and suppose by that there exists $U\n  \\subseteq M$ such that $U \\neq U''$.  Then the implication $U \\to U''$ is valid in $\\con\n  K$, and since $\\mathcal{L}$ is complete for $\\con K$ we obtain that\n  \\begin{equation*}\n    \\mathcal{L} \\models (U \\to U'').\n  \\end{equation*}\n  But then $U'' \\subseteq \\mathcal{L}(U)$, and thus $U \\subsetneq \\mathcal{L}(U)$, and in\n  particular $U \\neq \\mathcal{L}(U)$ as required.\n\n  Now suppose that~\\eqref{eq:9} holds, and let $U \\subseteq M$.  Since $\\mathcal{L}(U)$ is\n  closed under $\\mathcal{L}$, \\ie $\\mathcal{L}(\\mathcal{L}(U)) = \\mathcal{L}(U)$, we\n  obtain from~\\eqref{eq:9} that\n  \\begin{equation*}\n    \\mathcal{L}(U) = (\\mathcal{L}(U))''\n  \\end{equation*}\n  for each $U \\subseteq M$.  But then $U'' \\subseteq (\\mathcal{L}(U))'' = \\mathcal{L}(U)$,\n  and therefore $\\mathcal{L} \\models (U \\to U'')$ by\n  \\thref{lem:characterization-of-entailment-in-terms-of-induced-closure-operators}.\n  Therefore, $\\mathcal{L}$ is complete for $\\con K$.\n\\end{Proof}\n\nThe base from~\\eqref{eq:10} is not very practical, as it will almost always have\nexponentially many elements in the size of the set $|M|$ of attribute of $\\con K$.\nProcessing such a base may be computationally infeasible, and it is therefore desirable to\nhave a smaller base.  Indeed, it is possible to explicitly describe even a \\emph{minimal}\nbase of every formal context $\\con K$ (or for every set of implications), namely its\n\\emph{canonical base}~\\cite{fca:DuquenneGuigues:1986,DBLP:books/cs/Maier83} (also called\n\\emph{Duquenne-Guiges base} or \\emph{stem base}).\n\nTo introduce this base, we first need to discuss the notion of \\emph{pseudo-intents}.\nNote that we only introduce the canonical base for bases of formal contexts.  However,\nthis can be done without loss of generality, as a base of a set $\\mathcal{L}$ of\nimplications is always also a base of its closure $\\Cn_M(\\mathcal{L})$, and such sets can\nbe represented as theories of formal contexts by virtue of\n\\thref{prop:context-model-for-implications}.\n\nThe variant of pseudo-intents as introduced here is due to~\\cite{stumme96attribute}.\n\n\\begin{Definition}[Pseudo-Intents]\n  \\label{def:pseudo-intents}\n  Let $M$ be a set, $\\con K$ a formal context with attribute set $M$ and let $\\mathcal{S}$\n  be a set of implications on $M$.  Then a set $P \\subseteq M$ is called an\n  \\emph{$\\mathcal{S}$-pseudo-intent} of $\\con K$ if and only if\n  \\begin{enumerate}[i. ]\n  \\item $P \\neq P''$,\n  \\item $P = \\mathcal{S}(P)$, and\n  \\item for each $\\mathcal{S}$-pseudo-intent $Q$ of $\\con K$ satisfying $Q \\subsetneq P$,\n    it is true that $Q'' \\subseteq P$.\n  \\end{enumerate}\n  If $\\mathcal{S} = \\emptyset$, then an $\\mathcal{S}$-pseudo-intent is just called a\n  \\emph{pseudo-intent}.\n\\end{Definition}\n\nAs it is given, the definition of $\\mathcal{S}$-pseudo-intents is quite inaccessible, and\nthe motivation for it may only become apparent while working with them.  However, the role\nof the set $\\mathcal{S}$ can already be motivated now: this set will be used as\n\\emph{background knowledge} when computing the canonical base.  Let us make this more\nprecise, and recall that we have defined the notion of a base $\\mathcal{K}$ of a set of\nimplications $\\mathcal{L}$ to just mean that $\\Cn_M(\\mathcal{K}) = \\Cn_M(\\mathcal{L})$.\nThe motivation for this was that we want bases of the set $\\mathcal{L}$ to be a different,\npotentially smaller but logically equivalent representation of $\\mathcal{L}$.  However,\nwithin this scenario, we can assume that we already \\enquote{know} a certain set $\\mathcal{S}\n\\subseteq \\mathcal{L}$ of implications, and we only want to find a base that somehow\nrepresents the \\enquote{difference} between $\\mathcal{L}$ and $\\mathcal{S}$.\n\n\\begin{Definition}[Bases with Implicational Background Knowledge]\n  \\label{def:bases-with-background-knowledge}\n  Let $\\mathcal{L}$ and $\\mathcal{S}$ be sets of implications on a set $M$ such that\n  $\\mathcal{S} \\subseteq \\Cn_M(\\mathcal{L})$.  A \\emph{base} of $\\mathcal{L}$ \\emph{with\n    background knowledge} $\\mathcal{S}$ is a set $\\mathcal{K}$ of implications on $M$ such that\n  \\begin{equation*}\n    \\Cn_M(\\mathcal{K} \\cup \\mathcal{S}) = \\Cn_M(\\mathcal{L}).\n  \\end{equation*}\n  The notions of \\emph{irredundancy} and \\emph{minimality} of bases with background\n  knowledge are defined analogously to \\thref{def:sound-complete-base}: $\\mathcal{K}$ is\n  an \\emph{irredundant} base of $\\mathcal{L}$ with background knowledge $\\mathcal{S}$ if\n  and only if no proper subset of $\\mathcal{K}$ is a base of $\\mathcal{L}$ with background\n  knowledge $\\mathcal{S}$.  $\\mathcal{K}$ is a \\emph{minimal} base of $\\mathcal{L}$ with\n  background knowledge $\\mathcal{S}$ if and only if $\\mathcal{K}$ has minimal cardinality\n  among all bases of $\\mathcal{L}$ with background knowledge $\\mathcal{S}$.\n\\end{Definition}\n\nThe canonical base, which we shall introduce shortly, can be defined such that it also\nallows for background knowledge.  This background knowledge then will play the role of the\nset $\\mathcal{S}$ in the definition of an $\\mathcal{S}$-pseudo-intent.  Moreover, it can\nbe shown that the canonical base is a minimal base with the given background knowledge.\n\n\\begin{Definition}[Canonical Base]\n  \\label{def:canonical-base}\n  Let $\\con K = (G, M, I)$ be a formal context and let $\\mathcal{S} \\subseteq \\Imp(M)$.\n  Then the \\emph{canonical base} $\\Can(\\con K, \\mathcal{S})$ of $\\con K$ \\emph{with\n    background knowledge} $\\mathcal{S}$ is defined as\n  \\begin{equation*}\n    \\Can(\\con K, \\mathcal{S}) := \\set{ P \\to P'' \\mid P \\text{ is an } \\mathcal{S}\n      \\text{-pseudo-intent of } \\con K }.\n  \\end{equation*}\n  If $\\mathcal{S} = \\emptyset$, then we just write $\\Can(\\con K)$ for $\\Can(\\con K,\n  \\mathcal{S})$.\n\\end{Definition}\n\nThe classical result about the canonical base can now be stated as follows.\n\n\\begin{Theorem}\n  \\label{thm:canonical-base-with-valid-background-knowledge}\n  Let $\\con K$ be a finite formal context and let $\\mathcal{S} \\subseteq \\Th(\\con K)$.\n  Then $\\Can(\\con K, \\mathcal{S})$ is a minimal base of $\\con K$ with background knowledge\n  $\\mathcal{S}$.\n\\end{Theorem}\n\nThis formulation assumes that the background knowledge $\\mathcal{S}$ is sound for $\\con\nK$.  However, this is not only not necessary, but we shall also later encounter situations\nwhere our background knowledge is not valid, but where the corresponding canonical base\nhas still a meaningful application.  We therefore slightly generalize\n\\thref{thm:canonical-base-with-valid-background-knowledge} to yield the following theorem.\n\n\\begin{Theorem}\n  \\label{thm:canonical-base-with-arbitrary-background-knowledge}\n  Let $\\con K = (G, M, I)$ be a formal context and let $\\mathcal{S} \\subseteq \\Imp(M)$.\n  Then $\\Can(\\con K, \\mathcal{S})$ is a set of valid implications of $\\con K$ such that\n  $\\Can(\\con K, \\mathcal{S}) \\cup \\mathcal{S}$ is complete for $\\con K$.  Moreover,\n  $\\Can(\\con K, \\mathcal{S})$ has minimal cardinality among all sets of valid implications\n  satisfying this property.\n\\end{Theorem}\n\nThe proof about the minimal cardinality of $\\Can(\\con K, \\mathcal{S})$ is a\nstraight-forward adaption of the proof of~\\cite[Theorem 3.8]{Diss-Felix}.\n\n\\begin{Proof}\n  We need to show the following three statements:\n  \\begin{enumerate}[i. ]\n  \\item\\label{item:7} $\\Can(\\con K, \\mathcal{S})$ is sound for $\\con K$;\n  \\item\\label{item:8} $\\Can(\\con K, \\mathcal{S}) \\cup \\mathcal{S}$ is complete for $\\con\n    K$ and\n  \\item\\label{item:9} $\\Can(\\con K, \\mathcal{S})$ has minimal cardinality among all sets\n    $\\mathcal{P} \\subseteq \\Th(\\con K)$ of implications such that $\\mathcal{P} \\cup\n    \\mathcal{S}$ is complete for $\\con K$.\n  \\end{enumerate}\n\n  For~\\ref{item:7} we just note that $\\Can(\\con K, \\mathcal{S})$ only consists of\n  implications which are of the form $P \\to P''$, which are of course valid in $\\con K$.\n\n  For the completeness as claimed in~\\ref{item:8} we shall make use of\n  \\thref{lem:characterization-of-completeness} by showing that every closed set of\n  $\\Can(\\con K, \\mathcal{S}) \\cup \\mathcal{S}$ is already an intent of $\\con K$.  For\n  readability, let us set $\\mathcal{L} := \\Can(\\con K, \\mathcal{S}) \\cup \\mathcal{S}$.\n\n  So let $U \\subseteq M$ be such that $\\mathcal{L}(U) = U$.  If then $V \\subsetneq U$ is\n  an $\\mathcal{S}$-pseudo-intent of $\\con K$, then $V'' \\subseteq U$, since $(V \\to V'')\n  \\in \\mathcal{L}$.  Furthermore, $\\mathcal{S}(U) = U$ because $\\mathcal{S} \\subseteq\n  \\mathcal{L}$.  Hence, if we assume by contradiction that $U \\neq U''$, then $U$ would be\n  an $\\mathcal{S}$-pseudo-intent of $\\con K$, \\ie $(U \\to U'') \\in \\Can(\\con K,\n  \\mathcal{S}) \\subseteq \\mathcal{L}$.  But then $U'' \\subseteq \\mathcal{L}(U) = U$, \\ie\n  $U = U''$ contradicting $U \\neq U''$.  Therefore, $U = U''$ and since $U$ was chosen\n  arbitrarily, $\\mathcal{L}$ is complete by \\thref{lem:characterization-of-completeness}.\n\n  For the last claim~\\ref{item:9} let $\\mathcal{P}$ be another set of valid implications\n  of $\\con K$ such that $\\mathcal{P} \\cup \\mathcal{S}$ is complete for $\\con K$.  Without\n  loss of generality we may assume that $\\mathcal{P}$ only contains implications of the\n  form $U \\to U''$ for suitable $U \\subseteq M$.\n\n  To prove~\\ref{item:9} we shall now show that for each $\\mathcal{S}$-pseudo-intent $P$ of\n  $\\con K$ there exists a set $U_P \\subseteq M$ such that $(U_P \\to U_P'') \\in\n  \\mathcal{P}$, and that in addition the mapping $P \\to U_P$ is injective.  From this it\n  immediately follows that $\\abs{\\mathcal{P}} \\ge \\abs{ \\Can(\\con K, \\mathcal{S}) }$.\n\n  So let $P$ be an $\\mathcal{S}$-pseudo-intent of $\\con K$.  Then $P \\neq P''$.  As\n  $\\mathcal{P} \\cup \\mathcal{S}$ is complete for $\\con K$ and $\\mathcal{S}(P) = P$, there\n  exists an implication $(X \\to X'') \\in \\mathcal{P}$ such that $X \\subseteq P$ and $X''\n  \\not\\subseteq P$.  Set $U_P := X$.\n\n  To see that the resulting map $P \\to U_P$ is indeed injective, let $P$ and $Q$ be two\n  $\\mathcal{S}$-pseudo-intents of $\\con K$, and assume that $U_P = U_Q =: U$.  Then $U\n  \\subseteq P$ and $U \\subseteq Q$ by definition of $U_P$ and $U_Q$.  Hence $U \\subseteq P\n  \\cap Q$, and therefore $U'' \\subseteq (P \\cap Q)''$.\n\n  Then the fact that $U'' = U_P'' \\not\\subseteq P$ and $U'' \\subseteq (P \\cap Q)''$ implies\n  that $(P \\cap Q)'' \\not\\subseteq P$.  Therefore, $(P \\cap Q)'' \\not\\subseteq P \\cap Q$,\n  and in particular\n  \\begin{equation}\n    \\label{eq:11}\n    (P \\cap Q)'' \\neq P \\cap Q.\n  \\end{equation}\n\n  Recall that $\\mathcal{S}(P) = P$ and $\\mathcal{S}(Q) = Q$.  This implies that\n  $\\mathcal{S}(P \\cap Q) = P \\cap Q$, since the intersection of closed sets is again\n  closed.  But then, by Equation~\\eqref{eq:11} and the fact that $\\Can(\\con K,\n  \\mathcal{S}) \\cup \\mathcal{S}$ is complete for $\\con K$, there must exist an implication\n  $(R \\to R'') \\in \\Can(\\con K, \\mathcal{S})$ such that\n  \\begin{equation*}\n    R \\subseteq P \\cap Q \\quad\\text{and}\\quad R'' \\not\\subseteq P \\cap Q.\n  \\end{equation*}\n  Without loss of generality we assume that $R'' \\not\\subseteq Q$.  But then $R \\subseteq\n  Q$ is an $\\mathcal{S}$-pseudo-intent of $\\con K$, so if $R \\subsetneq Q$, it must be\n  that $R'' \\subseteq Q$, which is not the case.  Therefore, $R = Q$.  Since $R \\subseteq\n  P \\cap Q$, we obtain $Q \\subseteq P \\cap Q$, \\ie $Q = P \\cap Q$ and therefore\n  \\begin{equation}\n    \\label{eq:12}\n    Q \\subseteq P\n  \\end{equation}\n\n  Since $(P \\cap Q)'' \\not\\subseteq P$, Equation~\\eqref{eq:12} implies that $Q''\n  \\not\\subseteq P$.  Since $Q \\subseteq P$, the $\\mathcal{S}$-pseudo-intents $Q$ and $P$\n  cannot be different, so we obtain $P = Q$.\n\n  Therefore, the mapping $P \\mapsto U_P$ is injective and we have proven~\\ref{item:9}.\n\\end{Proof}\n\n\\thref{thm:canonical-base-with-valid-background-knowledge} is now an immediate consequence\nof \\thref{thm:canonical-base-with-arbitrary-background-knowledge}.\n\nThe minimality properties of the canonical base makes it particularly interesting for\npractical applications.  Indeed, besides these minimality properties discussed above, the\ncanonical base also allows for a comparably simple computation.  On the other hand, the\nminimality of the canonical base does not save us from exponentially big bases.\n\n\\begin{Example}\n  \\label{expl:canonical-base-can-be-exponential}\n  The following example is taken from~\\cite{DBLP:journals/jucs/Kuznetsov04}.  Let $n \\in\n  \\NN$ and let us consider the formal context $\\con K_n$ as shown in\n  Figure~\\ref{fig:expl-for-exponentially-many-pseudo-intents}.  The object set $G = G_1\n  \\cup G_2$ of $\\con K$ is defined as\n  \\begin{align*}\n    G_1 &= \\set{ g_1, \\dots, g_n } \\\\\n    G_2 &= \\set{ \\bar g_1, \\dots, \\bar g_{2n} },\n  \\end{align*}\n  where all $g_i, \\bar g_i$ are distinct, and the attribute set $M = M_1 \\cup M_2 \\cup\n  \\set{ \\bar m_{0} }$ is given by\n  \\begin{align*}\n    M_1 &= \\set{ m_1, \\dots, m_n }, \\\\\n    M_2 &= \\set{ \\bar m_1, \\dots, \\bar m_n },\n  \\end{align*}\n  where again all $m_i, \\bar m_i$ are distinct.\n\n  \\begin{figure}[tp]\n    \\centering\n    \\begin{math}\n      \\begin{array}{c | c | c | c}\n        \\toprule\n        \\con K_n & m_0 & m_1 \\dots m_n & \\bar m_1, \\dots \\bar m_n \\\\\n        \\midrule\n        g_1 & & & \\\\\n        \\vdots & & I_1 & I_2 \\\\\n        g_n & & & \\\\\n        \\midrule\n        \\bar g_1   & \\times & \\multicolumn{2}{c}{} \\\\\n        \\vdots     & \\times & \\multicolumn{2}{c}{I_3} \\\\\n        \\bar g_{2n} & \\times & \\multicolumn{2}{c}{} \\\\\n        \\bottomrule\n      \\end{array}\n    \\end{math}\n    \\caption{A Formal Context with Exponentially Many Pseudo-Intents}\n    \\label{fig:expl-for-exponentially-many-pseudo-intents}\n  \\end{figure}\n\n  The relations $I_1, I_2, I_3$ are essentially $\\neq$, more precisely\n  \\begin{align*}\n    (g_i, m_j) \\in I_1           &\\diff i \\neq j\\\\\n    (g_i, \\bar m_j) \\in I_2      &\\diff i \\neq j\\\\\n    (\\bar g_i, m_j) \\in I_3      &\\diff i \\neq j\\\\\n    (\\bar g_i, \\bar m_j) \\in I_3 &\\diff i \\neq j + n\n  \\end{align*}\n\n  Then the claim is that the number of pseudo-intents of $\\con K_n$ is at least $2^n$.  To\n  see this we first observe that the set $\\set{ m_1, \\dots, m_n }$ is a pseudo-intent of\n  $\\con K_n$.  This is because if\n  \\begin{equation*}\n    B = \\set{ m_{j_1}, \\dots, m_{j_k} } \\subseteq \\set{ m_1, \\dots, m_n },\n  \\end{equation*}\n  then\n  \\begin{equation*}\n    B' = (G_1 \\setminus \\set{ g_{j_1}, \\dots, g_{j_k} }) \\cup (G_2 \\setminus \\set{ \\bar\n      g_{j_1}, \\dots, \\bar g_{j_k} })\n  \\end{equation*}\n  and then $B = B''$.  On the other hand, the set $\\set{ m_1, \\dots, m_n }$ is not closed, since\n  \\begin{equation*}\n    \\set{ m_1, \\dots, m_n }'' = \\set{ \\bar g_{n+1}, \\dots, \\bar g_{2n} }' = \\set{ m_0,\n      m_1, \\dots, m_n }.\n  \\end{equation*}\n  Therefore, as all subsets of $\\set{ m_1, \\dots, m_n }$ are closed and the set itself is\n  not, it is a pseudo-intent of $\\con K_n$ by definition.\n\n  Now, if we replace an attribute $m_i$ with $\\bar m_i$, the resulting set $\\set{ m_1,\n    \\dots, m_{i-1}, \\bar m_i, m_{i+1}, \\dots, m_n }$ is still a pseudo-intent of $\\con\n  K_n$, using a similar argument: the set $\\set{ m_1, \\dots, \\bar m_i, \\dots, m_n }$ is\n  not closed, since\n  \\begin{equation*}\n    \\set{ m_1, \\dots, \\bar m_i, \\dots, m_n }'' = \\set{ m_0, m_1, \\dots, \\bar m_i, \\dots,\n      m_n },\n  \\end{equation*}\n  and every subset $C \\subseteq \\set{ m_1, \\dots, \\bar m_i, \\dots, m_n }$ is closed, by\n  the same arguments as we used for $B$.\n\n  Therefore, $\\con K_n$ has at least $2^n$ pseudo-intents and thus\n  \\begin{equation*}\n    \\abs{ \\Can(\\con K_n) } \\ge 2^n.\n  \\end{equation*}\n\\end{Example}\n\nIn spite of this rather disappointing result it may still pay off in practical\napplications to compute the canonical base, as its size may still be considerably smaller\nthen the size of the base from~\\eqref{eq:10}.  In the following, we shall discuss a\nstandard algorithm that computes the canonical base of a formal context.\n\nThe first, rather technical definition we need to consider is the one of the \\emph{lectic\n  order} on the powerset $\\subsets{M}$ of a linearly ordered set $(M, \\leq_M)$, \\ie an\nordered set $(M, \\leq_M)$ where for any two elements $x, y \\in M$ it is true that $x\n\\leq_M y$ or $y \\leq_M x$.\n\n\\begin{Definition}[Lectic Order]\n  \\label{def:lectic-order}\n  Let $(M, \\leq_M)$ be a linearly ordered set, and let $i \\in M$.  Then for two sets $A, B\n  \\subseteq M$, $A$ is called \\emph{lectically smaller} than $B$ \\emph{at position $i$},\n  written $A \\prec_i B$, if\n  \\begin{equation*}\n    A \\prec_i B \\diff i = \\min\\nolimits_{\\leq_M}(A \\symdiff B) \\text{ and } i \\in B,\n  \\end{equation*}\n  where\n  \\begin{equation*}\n    A \\symdiff B := (A \\setminus B) \\cup (B \\setminus A)\n  \\end{equation*}\n  is the symmetric difference of $A$ and $B$.\n\n  Then the \\emph{lectic order} on $\\subsets{M}$ induced by $\\leq_M$ is the relation\n  $\\preceq$ defined as\n  \\begin{equation*}\n    A \\preceq B \\diff A = B \\text{ or } A \\prec_i B \\text{ for some } i \\in M.\n  \\end{equation*}\n\\end{Definition}\n\nThe fact that $A \\prec_i B$ can be understood as the statement that the smallest element\n(with respect to $\\leq_M$) in which $A$ and $B$ differ belongs to $B$.\n\n\\begin{Example}\n  Let $M = \\set{ 0, 1, 2 }$ and let $\\leq_M$ be given by $2 \\leq_M 1 \\leq_M 0$.  Then\n  \\begin{equation*}\n    \\set{0} \\prec_i \\set{1}.\n  \\end{equation*}\n  Moreover, all subsets of $M$ are ordered by $\\preceq$ as follows\n  \\begin{equation*}\n    \\emptyset \\preceq \\set{0} \\preceq \\set{1} \\preceq \\set{0, 1} \\preceq \\set{2} \\preceq\n    \\set{0, 2} \\preceq \\set{0, 1, 2}.\n  \\end{equation*}\n  If we encode a subset of $M$ as a binary number like we did in Example~\\ref{expl:2}, so\n  for example $\\set{0, 2}$ would be $101$ and $\\set{0}$ would be $001$, then the above\n  lectic order can also be written as\n  \\begin{equation*}\n    000 \\preceq 001 \\preceq 010 \\preceq 011 \\preceq 100 \\preceq 101 \\preceq 111\n  \\end{equation*}\n  which resembles the usual linear order on binary numbers.\n\\end{Example}\n\nIt is not hard to see (but technical to prove) that every lectic order is indeed a linear\norder on $\\subsets{M}$, \\ie the ordered set $(\\subsets{M}, \\preceq)$ is a linearly ordered\nset.  Moreover the lectic order \\emph{extends} the usual subset-order on $\\subsets{M}$, in\nthe sense that for all $A, B \\subseteq M$ it is true that\n\\begin{equation*}\n  A \\subseteq B \\implies A \\preceq B,\n\\end{equation*}\nirrespective of the linear order $\\leq_M$ used to define $\\preceq$.\n\nLet now $c$ be a closure operator on the linearly ordered set $(M, \\leq_M)$.  In the\nfollowing we shall introduce the Next-Closure\nalgorithm~\\cite{fca-book,DBLP:conf/icfca/Ganter10} that allows us to compute all closed\nsets of $c$ ordered by the lectic order on $\\subsets{M}$ induced by $\\leq_M$.  Moreover,\nthis algorithm has the advantage of usually being much faster than just applying the\nclosure operator $c$ to all subsets of $M$ and collecting the results.\n\nHowever, before we shall discuss the algorithm, let us first introduce an abbreviation.\nFor a set $A \\subseteq M$ and an element $i \\in M$, let us write\n\\begin{equation*}\n  A \\oplus_c i := c(\\set{ a \\in A \\mid a \\leq_M i } \\cup \\set{i}).\n\\end{equation*}\nThen the following theorem holds, which is~\\cite[Theorem 5]{fca-book}.\n\n\\begin{Theorem}\n  \\label{thm:next-closure}\n  Let $(M, \\leq_M)$ be a linearly ordered set, and let $\\preceq$ be the lectic order on\n  $\\subsets{M}$ induced by $\\leq_M$.  Furthermore, let $c$ be a closure operator on $(M,\n  \\leq_M)$ and let $A \\subseteq M$.  Then, if there exists a set $B$ such that $A \\precneq\n  B$ and $B$ is closed under $c$, then\n  \\begin{equation*}\n    \\min\\nolimits_{\\preceq}\\set{ A \\precneq B \\mid B = c(B) } = A \\oplus_c i,\n  \\end{equation*}\n  where $i$ is $\\leq_M$-maximal among all elements $j \\in M$ satisfying $A \\prec_j A\n  \\oplus_c j$, \\ie\n  \\begin{equation*}\n    i = \\max\\nolimits_{\\leq_M} \\set{ j \\in M \\mid A \\prec_j A \\oplus_c j }.\n  \\end{equation*}\n\\end{Theorem}\n\nThe proof of this theorem is rather technical, and we shall not repeat it here.\n\nThe main advantage of this theorem is now that it immediately gives rise to an effective\nalgorithm to compute the lectically next closed set after a given one.\nAlgorithm~\\ref{alg:next-closure} shows an example implementation, which returns\n\\lstinline{nil} if no lectically next closed set exists.\n\n\\addfunctionname{next-closure}\n\n\\begin{figure}[tp]\n  \\begin{Algorithm}[Next-Closure]~\n    \\label{alg:next-closure}\n\\begin{lstlisting}\ndefine next-closure($M$, $\\leq_M$, $A$, $c$)\n  $C$ := $\\set{ i \\in M \\mid A \\prec_i A \\oplus_c i }$\n  if $C$ = $\\emptyset$\n    return nil\n  else\n    return $A \\oplus_c \\max\\nolimits_{\\leq_M}(C)$\n  end\nend  \n\\end{lstlisting}\n  \\end{Algorithm}\n\\end{figure}\n\nThe Next-Closure algorithm can in particular be used to compute all intents (and thus all\nformal concepts) of a formal context, because intents are just those subsets of the\nattribute sets which are closed under $(\\cdot)''$.  The following example illustrates\nthis.\n\n\\begin{Example}\n  \\label{expl:9}\n  Let us again consider our Star Trek context $\\con K_{\\mathsf{TNG}}$.  Clearly,\n  $\\emptyset = \\emptyset''$ is true in that context.  For computing more intents using\n  Next-Closure, let us order the attributes of this context as follows\n  \\begin{equation*}\n    \\mathsf{Human} < \\mathsf{Honorable} < \\mathsf{Artificial} < \\mathsf{StarFleet}.\n  \\end{equation*}\n  We now want to compute the lectically next closed set of $(\\cdot)''$ after $\\emptyset$,\n  \\ie the next intent of $\\con K_{\\mathsf{TNG}}$ after $\\emptyset$.  For this, we compute\n  \\begin{equation*}\n    \\emptyset \\oplus_{(\\cdot)''} \\mathsf{StarFleet} = \\set{\\mathsf{StarFleet}}'' = \\set{\n      \\mathsf{Honorable}, \\mathsf{StarFleet} },\n  \\end{equation*}\n  but it is not true that\n  \\begin{equation*}\n    \\emptyset \\prec_{\\mathsf{StarFleet}} \\set{ \\mathsf{Honorable}, \\mathsf{StarFleet} }.\n  \\end{equation*}\n  So we continue with \\textsf{Artificial} and obtain\n  \\begin{equation*}\n    \\emptyset \\oplus_{(\\cdot)''} \\mathsf{Artificial} = \\set{ \\mathsf{Artificial} }'' = \\mathsf{Artificial}\n  \\end{equation*}\n  and indeed $\\emptyset \\prec_{\\mathsf{Artificial}} \\set{ \\mathsf{Artificial} }$, so this\n  set is the lectically next intent of $\\con K$ after $\\emptyset$.  The corresponding\n  formal concept is\n  \\begin{equation*}\n    (\\set{ \\mathsf{Artificial} }', \\set{ \\mathsf{Artificial} }) = (\\set{ \\mathsf{Data},\n      \\mathsf{BorgQueen} }, \\set{ \\mathsf{Artificial} }).\n  \\end{equation*}\n  Continuing this process, we can successively compute all intents of $\\con\n  K_{\\mathsf{TNG}}$ this way, and thus also all formal concepts of $\\con K_{\\mathsf{TNG}}$\n  as shown in Example~\\ref{expl:star-trek-concept-lattice}.\n\\end{Example}\n\n\\addfunctionname{next-closed-non-intent, first-closed-non-intent, canonical-base}\n\nBased on the Next-Closure algorithm we can now discuss an algorithm that allows us to\ncompute the canonical base of a formal context $\\con K$ with arbitrary background\nknowledge. Algorithm~\\ref{alg:canonical-base} gives an implementation of such an\nalgorithm.  We shall discuss the details of this algorithm when proving its correctness.\nNote that Algorithm~\\ref{alg:canonical-base} also contains the two auxiliary functions\n\\lstinline{next-closed-non-intent} and \\lstinline{first-closed-non-intent}, which are\ndiscussed below.\n\n\\begin{figure}[tp]\n  \\begin{Algorithm}[Computing the Canonical Base with Background Knowledge]\n    \\label{alg:canonical-base}\n    \\hspace*{0cm}\n\\begin{lstlisting}\n  define next-closed-non-intent ($\\con K = (G, M, I), \\leq_M, A, c$)\n    ;; compute the lectically next non-intent of $\\con K$ after $A$ that is closed under $c$\n    $P$ := next-closure($M$, $\\leq_M$, $A$, $c$)\n    if $P$ = nil then\n      return nil\n    else if $P \\neq P''$ then\n      return $P$\n    else\n      return next-closed-non-intent($\\con K$, $\\leq_M$, $P$, $c$)\n    end\n  end\n\n  define first-closed-non-intent($\\con K = (G, M, I)$, $\\leq_M$, $c$)\n    ;; compute the lectically first non-intent of $\\con K$ that is closed under $c$\n    if $\\emptyset \\neq \\emptyset''$ and $c(\\emptyset) = \\emptyset$ then\n      return $\\emptyset$\n    else\n      return next-closed-non-intent($\\con K$, $\\leq_M$, $\\emptyset$, $c$)\n    end\n  end\n\n  define canonical-base($\\con{K} = (G, M, I)$, $\\leq_M$, $\\mathcal{S} \\subseteq \\Imp(M)$)\n    ;; compute the canonical base of $\\con K$ with background knowledge $\\mathcal{S}$\n    ;; in the lectic order induced by $\\leq_M$.\n\n    $i$ := 0,\n    $P_i$ := first-closed-non-intent($\\con{K}$, $\\leq_M$, $\\mathcal{S}$),\n    $\\mathcal{L}_i$ := $\\emptyset$\n\n    while $P_i \\neq$ nil do\n      $\\mathcal{L}_{i + 1}$ := $\\mathcal{L}_i \\cup \\set{P_i \\to P_i''}$,\n      $P_{i + 1}$ := next-closed-non-intent($\\con{K}$, $\\leq_M$, $P_i$, $\\mathcal{L}_{i +\n1} \\cup \\mathcal{S}$),\n      $i$ := $i + 1$\n    end\n\n    return $\\mathcal{L}_i$\n  end\n\\end{lstlisting}\n  \\end{Algorithm}\n\\end{figure}\n\nThe correctness of \\lstinline{canonical-base} can now be stated as follows.\n\n\\begin{Theorem}\n  \\label{thm:canonical-base-computation}\n  Let $\\con K = (G, M, I)$ be a finite formal context, \\ie both $\\abs G$ and $\\abs M$ are\n  finite.  Furthermore, let $\\mathcal{K} \\subseteq \\Imp(M)$ and let $\\leq_M$ be a linear\n  order on $M$.  Then the call to \\lstinline{canonical-base} terminates and it is then\n  true that\n  \\begin{equation*}\n    \\Can(\\con K, \\mathcal{K}) = \\text{\\lstinline{canonical-base}}(\\con K, \\leq_M, \\mathcal{K}).\n  \\end{equation*}\n\\end{Theorem}\n\nBefore we are proving this theorem, we first consider the auxiliary functions also shown\nin Algorithm~\\ref{alg:canonical-base}, and show that they yield what their names suggest.\n\n\\begin{Proposition}\n  \\label{prop:auxiliary-functions-canonical-base}\n  Let $\\con K = (G, M, I)$ be a finite formal context, $\\leq_M$ a linear order on $M$ and\n  $c$ a closure operator on $(M, \\leq_M)$.  Denote with $\\preceq$ the lectic order on\n  $\\subsets{M}$ induced by $\\leq_M$.\n  \\begin{enumerate}[i. ]\n  \\item Let $A \\subseteq M$ and define $S :=\n    \\text{\\lstinline{next-closed-non-intent}}(\\con K, \\leq_M, A, c)$.  Then\n    \\begin{equation*}\n      S = \\min\\nolimits_{\\preceq} \\set{ B \\subseteq M \\mid A \\precneq B, B = c(B), B \\neq\n        B''}\n    \\end{equation*}\n    if this minimum exists, and $S = \\text{\\lstinline{nil}}$ otherwise.\n  \\item Define $T := \\text{\\lstinline{first-closed-non-intent}}(\\con K, \\leq_M, c)$.  Then\n    \\begin{equation*}\n      T = \\min\\nolimits_{\\preceq}\\set{ B \\subseteq M \\mid B = c(B), B \\neq B'' }\n    \\end{equation*}\n    if this minimum exists, and $T = \\text{\\lstinline{nil}}$ otherwise.\n  \\end{enumerate}\n\\end{Proposition}\n\\begin{Proof}\n  For the first statement observe that the algorithm considers in lectic order all sets $C\n  \\subseteq M$ where $A \\precneq C$ that are closed under $c$.  Now, if a lectically\n  smallest set $C \\subseteq M$ with $A \\precneq C$ exists such that $C \\neq C''$, then it\n  is finally found by the algorithm and returned as the resulting value.\n\n  On the other hand, if no such set exists, then the variable $P$ in the algorithm will\n  eventually obtain the value $M$, and the subsequent iteration will return\n  \\lstinline{nil}, since\n  \\begin{equation*}\n    \\text{\\lstinline{next-closure}}(M, {\\leq_M}, M, c) = \\text{\\lstinline{nil}}.\n  \\end{equation*}\n\n  For the second statement let us first assume that $\\emptyset \\neq \\emptyset''$ and\n  $c(\\emptyset) = \\emptyset$.  Then clearly\n  \\begin{equation*}\n    \\min\\nolimits_{\\preceq}\\set{ B \\subseteq M \\mid B = c(B), B \\neq B'' } = \\emptyset =\n    \\text{\\lstinline{first-closed-non-intent}}(\\con K, \\leq_M, c).\n  \\end{equation*}\n  If $\\emptyset = \\emptyset''$ or $c(\\emptyset) \\neq \\emptyset''$, then\n  \\begin{equation*}\n    \\emptyset \\precneq \\min\\nolimits_{\\preceq}\\set{ B \\subseteq M \\mid B = c(B), B \\neq\n      B'' }.\n  \\end{equation*}\n  Hence\n  \\begin{align*}\n    \\min\\nolimits_{\\preceq}\\set{ B \\subseteq M \\mid B = c(B), B \\neq B'' }\n    &= \\min\\nolimits_{\\preceq}\\set{ B \\subseteq M, \\emptyset \\precneq B, B = c(B), B \\neq\n      B''}\\\\\n    &= \\text{\\texttt{next-closed-non-intent}}(\\con K, \\leq_M, \\emptyset, c)\\\\\n    &= \\text{\\texttt{first-closed-non-intent}}(\\con K, \\leq_M, c)\n  \\end{align*}\n  as required.\n\\end{Proof}\n\nWe shall now prove~\\ref{thm:canonical-base-computation}.  Note that the proof itself is\nwell-known, but we shall give it here nevertheless for the sake of completeness, and to\nconvey some intuition why the implementation of \\lstinline{canonical-base} indeed computes\nthe canonical base.\n\nThe main line of argumentation of the proof is as follows: using induction, we shall prove\nthat in a call of \\lstinline{canonical-base($\\con K, \\leq_M, \\mathcal S$)} for each $i$\nthe following is true: if there exists an $\\mathcal{S}$-pseudo-intent that is not within\nthe list $P_0, \\dots, P_{i-1}$, then $P_i \\neq \\text{\\lstinline{nil}}$ and $P_0, \\dots,\nP_i$ are the lectically first $\\mathcal{S}$-pseudo-intents of $\\con K$.  Thus, if the\nalgorithm finishes in iteration $n$, say, then $\\mathcal{L}_n = \\Can(\\con K,\n\\mathcal{S})$, which is the value returned by the function.\n\n\\begin{Proof}[\\thref{thm:canonical-base-computation}]\n  As before, denote with $\\preceq$ the lectic order on $\\subsets{M}$ induced by $\\leq_M$.\n  As already mentioned, we shall prove by induction over the number $i$ of iterations that\n  if $\\con K$ has more than $i$ $\\mathcal{S}$-pseudo-intents, that then $P_i \\neq\n  \\text{\\lstinline{nil}}$ and the sets\n  \\begin{equation*}\n    P_0, \\dots, P_i\n  \\end{equation*}\n  are the first $i+1$ $\\mathcal{S}$-pseudo-intents of $\\con K$ with respect to $\\preceq$.\n\n  Let $i = 0$ and suppose that $\\con K$ has $\\mathcal{S}$-pseudo-intents.  If $\\bar P_0$\n  is then the lectically first $\\mathcal{S}$-pseudo-intent of $\\con K$, it is true that\n  $\\bar P_0$ is closed under $\\mathcal{S}$ but not an intent of $\\con K$.  Therefore, $P_0\n  \\preceq \\bar P_0$.\n\n  On the other hand, $P_0$ is already an $\\mathcal{S}$-pseudo-intent of $\\con K$, because\n  $P_0 \\neq P_0'', \\mathcal{S}(P_0) = P_0$ and if $Q \\subsetneq P_0$ such that\n  $\\mathcal{S}(Q) = Q$, then $Q = Q''$ already holds, \\ie there are no\n  $\\mathcal{S}$-pseudo-intents strictly contained in $P_0$.  Thus, $\\bar P_0 \\preceq P_0$\n  and therefore $P_0 = \\bar P_0$, \\ie $P_0$ is the lectically first\n  $\\mathcal{S}$-pseudo-intent of $\\con K$.  In particular, $P_0 \\neq\n  \\text{\\lstinline{nil}}$.\n\n  Now suppose $i > 0$ and suppose that $\\con K$ has more than $i$\n  $\\mathcal{S}$-pseudo-intents.  By induction hypothesis, the list\n  \\begin{equation*}\n    P_0, \\dots, P_{i-1}\n  \\end{equation*}\n  consists of the lectically first $i$ $\\mathcal{S}$-pseudo-intents.  Let $P$ be the\n  lectically next $\\mathcal{S}$-pseudo-intent after $P_{i-1}$.  Then $P$ is closed under\n  $\\mathcal{S}$ and not an intent of $\\con K$.  In particular, $P_i \\preceq P$, and $P_i\n  \\neq \\text{\\lstinline{nil}}$.\n\n  Furthermore, $P_i$ is an $\\mathcal{S}$-pseudo-intent of $\\con K$.  To see this we first\n  observe that $\\mathcal{S}(P_i) = P_i$ and $P_i \\neq P_i''$, so it suffices to show that\n  for each $\\mathcal{S}$-pseudo-intent $Q \\subsetneq P_i$ it is true that $Q'' \\subseteq\n  P_i$.  To this end let $Q \\subsetneq P_i$ be an $\\mathcal{S}$-pseudo-intent of $\\con K$.\n  Then $Q \\precneq P_i \\preceq P$, and by definition of $P$, it is true that $Q = P_j$ for\n  some $j \\in \\set{0, \\dots, i - 1}$.  Therefore, $(Q \\to Q'') \\in \\mathcal{L}_i$.  Since\n  $\\mathcal{L}_i(P_i) = P_i$ and $Q \\subseteq P_i$, it must therefore be true that $Q''\n  \\subseteq P_i$.\n\n  We have thus shown that $P_i$ is the lectically next $\\mathcal{S}$-pseudo-intent after\n  $P_{i-1}$.  Therefore,\n  \\begin{equation*}\n    P_0, \\dots, P_{i+1}\n  \\end{equation*}\n  are the lectically first $i+2$ $\\mathcal{S}$-pseudo-intents of $\\con K$ and the claim is\n  shown.\n\n  From the above claim we can now infer the validity of the theorem.  First of all we\n  observe that $\\con K$ can only have finitely many $\\mathcal{S}$-pseudo-intents, since\n  $\\con K$ itself is finite.  Therefore, if $\\con K$ has $n$ such\n  $\\mathcal{S}$-pseudo-intents, then these must be $P_0, \\dots, P_{n-1}$ and $P_n =\n  \\text{\\lstinline{nil}}$.  But then\n  \\begin{equation*}\n    \\mathcal{L}_n = \\set{ P_j \\to P_j'' \\mid j = 0, \\dots, n - 1} = \\Can(\\con K, \\mathcal{S}).\n  \\end{equation*}\n  Since $P_n$ is \\lstinline{nil}, the value $\\mathcal{L}_n$ is returned from\n  \\lstinline{canonical-base} and thus the claim is shown.\n\\end{Proof}\n\nWe have to note, however, that the computation as shown in\nAlgorithm~\\ref{alg:canonical-base} may still take time exponential in the size of the\ninput context $\\con K$ to compute the next $\\mathcal{S}$-pseudo-intent.  This is mainly\nbecause while computing all $\\mathcal{S}$-pseudo-intents of $\\con K$, we also compute all\nintents of $\\con K$ as well.  It is rather easy to see that the number of intents of a\nformal context can be exponential in the number of its pseudo-intents, and therefore our\nimplementation may need an exponential delay between the computation of two successive\npseudo-intents.\n\nIndeed, it is not known if this exponential delay can be avoided altogether.  There is a\ndifferent approach of computing the canonical base~\\cite{DBLP:journals/amai/ObiedkovD07},\nwhich however also computes all intents of $\\con K$ during the run.  There are also some\ncomplexity results with respect to computing the canonical base: enumerating\npseudo-intents in lectic order is coNP-hard~\\cite{DBLP:conf/icfca/Distel10}, so an\nalgorithm that computes the canonical base in some sort of lectic order cannot avoid\nexponential delays, unless P = NP.  See also~\\cite{DBLP:conf/icdm/BorchmannD11} for a\npractical scenario where, in a certain sense, this phenomenon can be observed.  Finally,\nwe note that already recognizing pseudo-intents of a formal context is\ncoNP-hard~\\cite{DBLP:journals/dam/BabinK13}.\n\nOn the other hand, it is possible in polynomial time to decide if a base of a formal\ncontext is indeed the canonical base.  For this, one can use a minimization procedure as\ndiscussed in~\\cite{DBLP:conf/icfca/Rudolph07}, which transforms every base into its\ncorresponding canonical base.  The result of this minimization agrees with the original\nbase if and only if the original base is its corresponding canonical base.  As this\nreduction can be done in quadratic time in the size of the original base, this yields a\npolynomial time method to test if a base is the canonical base.\n\nAll in all, it is not clear yet whether computing the canonical base is difficult or not,\nand it remains an open research problem.\n\n\\section{Attribute Exploration}\n\\label{sec:attr-expl}\n\nWhile we have considered valid implications of our example context $\\con K_{\\mathsf{TNG}}$\nwe have encountered the implication\n\\begin{equation*}\n  \\set{ \\mathsf{Human} } \\to \\set{ \\mathsf{Honorable} }.\n\\end{equation*}\nWhile neither exact definitions for \\enquote{human} nor for \\enquote{honorable} are given,\nthis implication is rather doubtful (even in the context of Star Trek).  But still, this\nimplication is a valid implication of $\\con K_{\\mathsf{TNG}}$.  On the other hand, one\ncould discuss that this context is not \\enquote{complete} in the sense that it lacks\nrelevant counterexamples, and certainly one would find such a counterexample for the above\nimplication in the Star Trek series.\n\nTo remedy this incompleteness of $\\con K_{\\mathsf{TNG}}$ one could go and add all\ncharacters which have ever occurred in Star Trek \\emph{The Next Generation} to $\\con\nK_{\\mathsf{TNG}}$.  While this is doable, it is certainly not practical, especially since\nit may not be necessary to include \\emph{all} characters into $\\con K_{\\mathsf{TNG}}$ to\ninvalidate certain implications.\n\nThe illustrated problem may very well occur in practical situations, where one is\ninterested in the valid implications of a certain \\emph{domain} which is represented by a\ncollection of \\emph{individuals} (Star Trek characters in the above example) with certain\n\\emph{attributes} (those listed in $\\con K_{\\mathsf{TNG}}$).  This collection of\nindividuals cannot be listed completely, or at least it is not feasible to do so.\nHowever, one can search for single individuals with certain properties.\n\nLet us make this more clear: we assume that our domain is representable by a formal\ncontext, which we shall call the \\emph{background context} $\\con K_{\\mathsf{back}} =\n(G_{\\mathsf{back}}, M, I_{\\mathsf{back}})$.  The objects of this formal context are the\nindividuals of our domain of interest.  The attributes in the background context are the\nattributes of the individuals we are \\emph{interested in}, in the sense that we want to\nfind implications between those attributes which are valid in the domain. Finally, the\nincidence of the background context encodes if an individual has a certain attribute in\nour domain or not.\n\nThe task is now to find the implicational theory of the background context.  Although we\ncannot access this context completely, we certainly need a way to access this data.  For\nthis, we shall make the following assumption: we are given an \\emph{expert} which can\n\\emph{answer questions} of the following type:\n\\begin{quote}\n  Does the implication $A \\to B$ hold in the background context?\n\\end{quote}\nThe expert may then either agree to this questions, or, if not, she\\footnote{We assume\n  experts to be female unless known otherwise.} has to provide a counterexample, \\ie a new\nobject $g$ such that $g \\in A'$ but $g \\notin B'$.  Note that this is much more realistic\nthan enumerating all objects of the background context, as we only have to find one object\nthat invalidates the given implication, if it does not hold in the background context.\n\nWithin the setting just described, the \\emph{attribute exploration} algorithm from formal\nconcept analysis can help~\\cite{fca-book,DBLP:conf/icfca/Ganter10}.  For this algorithm we\nassume that we have given a \\emph{working context} $\\con K = (G, M, I)$ which is a\nsubcontext of $\\con K_{\\mathsf{back}}$, \\ie $G \\subseteq G_{\\mathsf{back}}$ and $I =\nI_{\\mathsf{back}} \\cap G \\times M$.\\footnote{Actually, the names of the objects are not\n  relevant here.  Indeed, it is sufficient if we can \\emph{rename} the objects of $\\con K$\n  in a reversible manner such that these conditions hold.}  Moreover, we also assume that\nwe have given a set $\\mathcal{S} \\subseteq \\Imp(M)$ of \\emph{known implications} which are\nvalid in $\\con K_{\\mathsf{back}}$.\n\nThe task now, namely to compute a base of $\\con K_{\\mathsf{back}}$ with background\nknowledge $\\mathcal{S}$, is achieved by the attribute exploration algorithm as follows:\nthe algorithm successively computes implications $(A \\to B) \\in \\Imp(M)$ such that\n\\begin{enumerate}[i. ]\n\\item $A \\to B$ is valid in $\\con K$, and\n\\item $A \\to B$ is not entailed by $\\mathcal{S}$.\n\\end{enumerate}\nIntuitively, those implications are \\emph{undecided}: they are not invalidated by the\nobjects in $\\con K$, \\ie by the objects we already know from our domain of interest.  On\nthe other hand, $A \\to B$ also cannot be inferred from the implications we already know,\n\\ie from $\\mathcal{S}$.\n\nTherefore, we have to ask the expert about the implication $A \\to B$.  If she decides to\naccept this implication, $A \\to B$ is added to our set of known implications.  If she\ndecides to reject the implication, and to provide a counterexample for it, we add it to\nthe formal context.  Then, a new implication $A \\to B$ is computed which is valid in the\nworking context but does not follow from the known implications.\n\nThis algorithm proceeds until no more implications $A \\to B$ can be computed.  If this is\nthe case, then all valid implications in the working context already follow from the known\nimplications.  But this means that the known implications are a base of the background\ncontext with background knowledge $\\mathcal{S}$: if $X \\to Y$ is a valid implication in\nthe background context, then $X \\to Y$ is also valid in the working context, and thus it\nis entailed by the known implications.\n\nOf course, the description of attribute exploration as given above lacks a crucial detail,\nnamely how to compute the implications $A \\to B$.  Indeed, it turns out that this can be\ndone in a way very similar to how we compute the canonical base of formal context.  We\nshall not discuss this in detail here, as we are going to look into attribute exploration\nin much more detail in Sections~\\ref{cha:expl-conf} and~\\ref{cha:model-expl-conf}.\nInstead, we just show an example implementation of attribute exploration in\nAlgorithm~\\ref{alg:attribute-exploration}.  There we use the notation $\\con K + (g,g')$ to\ndenote the formal context which arises from $\\con K = (G, M, I)$ by adding the object $g$\nwith attributes $g'$, assuming that $g \\notin G$.  In other words,\n\\begin{equation*}\n  \\con K + (g,g') := (G \\cup \\set{g}, M, I \\cup \\set{ (g, m) \\mid m \\in g' }).\n\\end{equation*}\n\n\\begin{figure}[tp]\n  \\begin{Algorithm}[Attribute Exploration with Background Knowledge]\n    \\label{alg:attribute-exploration}\n    \\hspace*{0cm}\n\\begin{lstlisting}\n  define explore-attributes($\\con{K} = (G, M, I)$, $\\leq_M$, $\\mathcal{S} \\subseteq \\Imp(M)$)\n    ;; conducts attribute exploration with working context $\\con K$ and\n    ;; background knowledge $\\mathcal{S}$.\n\n    $i$ := 0,\n    $\\con K_i$ := $\\con K$\n    $P_i$ := first-closed-non-intent($\\con{K}_i$, $\\leq_M$, $\\mathcal{S}$),\n    $\\mathcal{L}_i$ := $\\emptyset$\n\n    while $P_i \\neq$ nil do\n\n      if $\\text{expert confirms } P_i \\to P_i''$ then\n        $\\mathcal{L}_{i + 1}$ := $\\mathcal{L}_i \\cup \\set{P_i \\to P_i''}$\n        $\\con K_{i+1}$ := $\\con K_i$\n      else\n        $\\mathcal{L}_{i+1}$ := $\\mathcal{L}_i$\n        $\\con K_{i+1}$ := $\\con K_{i} + (g, g')$ ;; $g$ counterexample provided by the expert\n      end\n\n      if $P_i \\neq P_i''$ then ;; derivation in $\\con K_{i+1}$\n        $P_{i+1}$ := $P_i$\n      else\n        $P_{i + 1}$ := next-closed-non-intent($\\con{K}_{i+1}$, $\\leq_M$, $P_i$, $\\mathcal{L}_{i + 1} \\cup \\mathcal{S})$\n      end\n      $i$ := $i + 1$\n\n    end\n\n    return $\\mathcal{L}_i$\n  end\n\\end{lstlisting}\n  \\end{Algorithm}\n\\end{figure}\n\nNote that attribute exploration makes use of the Next-Closure algorithm, so we have to\nprovide a linear order $\\leq_M$ on the attribute set $M$ for a call to\n\\lstinline{explore-attributes}.\n\nThe correctness of the attribute exploration algorithm is stated in the following theorem.\nHowever, this theorem states even more, namely a certain kind of \\emph{optimality}: the\nresulting set of implications is not only any base of the background context, but indeed\nthe canonical base of the background context with background knowledge $\\mathcal{S}$.\nThus, the number of implications \\emph{confirmed} by the expert is as small as possible.\n\n\\begin{Theorem}\n  \\label{thm:attribute-exploration}\n  Let $\\con K = (G, M, I)$ be a formal context, $\\leq_M$ a linear order on $M$, and let\n  $\\mathcal{S} \\subseteq \\Imp(M)$ be such that the expert confirms all implications in\n  $\\mathcal{S}$.  Then \\lstinline{explore-attributes} called with arguments $\\con K$,\n  $\\leq_M$ and $\\mathcal{S}$ terminates in a finite number of steps.  If $\\con\n  K_{\\mathsf{back}}$ denotes the background context of the exploration, then\n  \\begin{equation*}\n    \\text{\\lstinline{canonical-base}}(\\con K, \\leq_M, \\mathcal{S}) = \\Can(\\con\n    K_{\\mathsf{back}}, \\mathcal{S}).\n  \\end{equation*}\n\\end{Theorem}\n\nWe shall not prove this theorem here, but instead refer the reader to standard literature\nfor a proof~\\cite{fca-book,Diss-Felix,stumme96attribute,DBLP:journals/tcs/Ganter99}.\nMoreover, we shall discuss in Section~\\ref{cha:expl-conf} generalizations of this result,\nand their proofs then also apply to this theorem.\n\nNote that \\lstinline{explore-attributes} is a generalization of\n\\lstinline{canonical-base}, and as such inherits all disadvantageous properties of it.  In\nparticular, because enumerating pseudo-intents in lectic order cannot be done in\npolynomial time unless P = NP, it may happen that the time between two questions to the\nexpert may grow exponentially.\n\n%%% Local Variables: \n%%% mode: latex\n%%% TeX-master: \"../main\"\n%%% End: \n\n%  LocalWords:  sep Picard Worf StarFleet doubleprime tp quadratically LinClosure Dowling\n%  LocalWords:  Gallier Hentig Guiges\n", "meta": {"hexsha": "531f6ac4c0a1ec4cb16e22d5b82f9cbf84a98777", "size": 95719, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/formal-concept-analysis.tex", "max_stars_repo_name": "exot/thesis", "max_stars_repo_head_hexsha": "5cda9bc3011e0c5697b8a5aede9525d0001058ca", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/formal-concept-analysis.tex", "max_issues_repo_name": "exot/thesis", "max_issues_repo_head_hexsha": "5cda9bc3011e0c5697b8a5aede9525d0001058ca", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/formal-concept-analysis.tex", "max_forks_repo_name": "exot/thesis", "max_forks_repo_head_hexsha": "5cda9bc3011e0c5697b8a5aede9525d0001058ca", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.9577244259, "max_line_length": 119, "alphanum_fraction": 0.6818604457, "num_tokens": 31253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.33065623871920036}}
{"text": "% \n\n\n\\documentclass[twoside]{article}\n\\setlength{\\oddsidemargin}{0.25 in}\n\\setlength{\\evensidemargin}{-0.25 in}\n\\setlength{\\topmargin}{-0.6 in}\n\\setlength{\\textwidth}{6.5 in}\n\\setlength{\\textheight}{8.5 in}\n\\setlength{\\headsep}{0.75 in}\n\\setlength{\\parindent}{0 in}\n\\setlength{\\parskip}{0.1 in}\n\n%\n% ADD PACKAGES here:\n%\n\n\\usepackage{amsmath,amsfonts,graphicx,mathdots}\n\n\n\\newcounter{lecnum}\n\\renewcommand{\\thepage}{\\thelecnum-\\arabic{page}}\n\\renewcommand{\\thesection}{\\thelecnum.\\arabic{section}}\n\\renewcommand{\\theequation}{\\thelecnum.\\arabic{equation}}\n\\renewcommand{\\thefigure}{\\thelecnum.\\arabic{figure}}\n\\renewcommand{\\thetable}{\\thelecnum.\\arabic{table}}\n\n%\n% The following macro is used to generate the header.\n%\n\\newcommand{\\lecture}[4]{\n   \\pagestyle{myheadings}\n   \\thispagestyle{plain}\n   \\newpage\n   \\setcounter{lecnum}{#1}\n   \\setcounter{page}{1}\n   \\noindent\n   \\begin{center}\n   \\framebox{\n      \\vbox{\\vspace{2mm}\n    \\hbox to 6.28in { {\\bf EE402 - Discrete Time Systems\n\t\\hfill Spring 2018} }\n       \\vspace{4mm}\n       \\hbox to 6.28in { {\\Large \\hfill Lecture #1 \\hfill} }\n       \\vspace{2mm}\n       \\hbox to 6.28in { {\\it Lecturer: #2 \\hfill } }\n      \\vspace{2mm}}\n   }\n   \\end{center}\n   \\markboth{Lecture #1}{Lecture #1}\n\n   \\vspace*{4mm}\n}\n\n\\renewcommand{\\cite}[1]{[#1]}\n\\def\\beginrefs{\\begin{list}%\n        {[\\arabic{equation}]}{\\usecounter{equation}\n         \\setlength{\\leftmargin}{2.0truecm}\\setlength{\\labelsep}{0.4truecm}%\n         \\setlength{\\labelwidth}{1.6truecm}}}\n\\def\\endrefs{\\end{list}}\n\\def\\bibentry#1{\\item[\\hbox{[#1]}]}\n\n\n\\newcommand{\\fig}[3]{\n\t\t\t\\vspace{#2}\n\t\t\t\\begin{center}\n\t\t\tFigure \\thelecnum.#1:~#3\n\t\t\t\\end{center}\n\t}\n\n% Use these for theorems, lemmas, proofs, etc.\n\\newtheorem{theorem}{Theorem}[lecnum]\n\\newtheorem{lemma}[theorem]{Lemma}\n\\newtheorem{proposition}[theorem]{Proposition}\n\\newtheorem{claim}[theorem]{Claim}\n\\newtheorem{corollary}[theorem]{Corollary}\n\\newtheorem{definition}[theorem]{Definition}\n\\newenvironment{proof}{{\\bf Proof:}}{\\hfill\\rule{2mm}{2mm}}\n\n% **** IF YOU WANT TO DEFINE ADDITIONAL MACROS FOR YOURSELF, PUT THEM HERE:\n\n\\begin{document}\n\n% Lecture Details\n\\lecture{17}{Asst. Prof. M. Mert Ankarali}\n\n\\par\n\n\\section*{Discrete-time Luenberger Observer}\n\nIn general the state, $x[k]$ of a system\nis not accessible and \\textit{observers, estimators, filters})\nhave to be used to extract this information.\nThe output, $y[k]$, represents the measurements\nwhich is a function of $x[k]$ and $u[k]$.\n%\n\\begin{align*}\n  x[k+1] &= G x[k] + H u[k]\n  \\\\\n  y[k] &= C x[k] + D u[k]\n\\end{align*}\n%\nA Luenberger observers is built using a ``simulated'' model of the \nsystem and the errors caused by the mismatched initial conditions \n$x_0 \\neq \\hat{x}_0$ (or other types of perturbations)\nare reduced by introducing output error feedback.\n\nLet's assume that the states of the simulated system\nis $\\hat{x}[k]$, then the state space equation of this\nsynthetic system takes the form\n%\n\\begin{align*}\n  \\hat{x}[k+1] &= \\hat{G} x[k] + \\hat{H} u[k]\n  \\\\\n  \\hat{y}[k] &= \\hat{C} x[k] + \\hat{D} u[k]\n\\end{align*}\n%\nNote that since $u[k]$ is the input that is controlled\nit is assumed to be known. If $x[0] = \\hat{x}[0]$ and\nwhen there is no model mismatch or uncertainty in the system\nthen we expect that $x[k] = \\hat{x}[k]$ and $y[k] = \\hat{y}[k]$ \nfor all $k$. When $x[0] = \\hat{x}[0]$, then we observe a \ndifference between the measured and predicted output\n$y[k] \\neq \\hat{y}[k]$. The core idea in Luenberger observers\nis feeding the error in the output prediction \n$y[k] - \\hat{y}[k]$ to the system via a linear feedback gain.\n%\n\\begin{align*}\n  \\hat{x}[k+1] &= G \\hat{x}[k] + H u[k] + L \\left( y[k] - \\hat{y}[k] \\right) \n  \\\\\n  \\hat{y}[k] &= C x[k] + D u[k]\n\\end{align*}\n%\nIn order to understand how a Luenberger observer works and\not choose a proper observer gain $L$, we define an error signal\n$e[k] = x[k] - \\hat{x}[k]$. The dynamics w.r.t $e[k]$ can be derived\nas\n%\n\\begin{align*}\n  e[k+1] &= x[k+1] - \\hat{x}[k+1]\n        \\\\\n     &= \\left( G x[k] + H u[k] \\right)\n  - \\left( G \\hat{x}[k] + H u[k] + L \\left( y[k] - \\hat{y}[k] \\right)\n       \\right)\n\\\\\n   e[k+1] &= \\left( G - L C \\right) e[k]\n\\end{align*}\n%\nwhere $e[0] = x[0] - \\hat{x}[0]$ denotes the error in the initial\ncondition. \n\nIf the matrix $\\left( G - L C \\right)$ is stable then the errors\ninitial condition will diminish eventually. Moreover, in order\nto have a good observer/estimator performance the observer\nconvergence should be sufficiently fast. \n\n\\section*{Observer Gain \\& Pole Placement}\n\nSimilar to the state-feedback gain design,\nthe fundamental principle of ``pole-placement'' Observer design is that\nwe first define a desired closed-loop eigenvalue set and \ncompute associated desired characteristic polynomial. \n%\n\\begin{align*}\n \\mathcal{E}^* &= \\lbrace \\lambda_1^* , \\ \\cdots, \\  \\lambda_n^*\n                 \\rbrace\n  \\\\\n  p^*(z) &= \\left( z - \\lambda_1^* \\right) \\cdots \\left( z - \\lambda_n^*\n         \\right)                         \n  \\\\\n  &= z^n + a_1^* z^{n-1} + \\cdots + a_{n-1}^* z + a_n^*\n\\end{align*}\n%\nThe necessary and sufficient condition on arbitrary observer pole-placement\nis that the system should be fully Observable. Then we tune $L$ such\nthat \n%\n\\begin{align*}\n  \\mathrm{det} \\left( z I - ( G - L C ) \\right) = p^*(z)\n\\end{align*}\n%\n\\subsection*{Direct Design of Observer Gain}\n\nIf $n$ is small, the most efficient method could be the direct\ndesign. \n\n\\textbf{Example:} Consider the following DT system\n%\n\\begin{align*}\n x[k+1] &= \\left[ \\begin{array}{cc} 1 & 0 \\\\ 0 & 2 \\end{array} \\right] x[k]\n    + \\left[ \\begin{array}{c} 1 \\\\ 1 \\end{array} \\right] u[k]\n\\\\\n y[k] &= \\left[ \\begin{array}{cc} 1 & -1 \\end{array} \\right] u[k]\n\\end{align*}\n% \nDesign an observer such that estimater poles are located at \n$\\lambda_{1,2} = 0$ (Dead-beat Observer)\n\n\\textbf{Solution:} Desired characteristic equation can be computed as\n%\n\\begin{align*}\n  p^*(z) = z^2\n\\end{align*}\n%\nLet $L = \\left[ \\begin{array}{c} l_2 \\\\ l_1 \\end{array} \\right]$, then\nthe characteristic equation of $(G - L C)$ can be computed as\n%\n\\begin{align*}\n  \\mathrm{det} \\left( z I - ( G - L C ) \\right) &= \n  \\mathrm{det} \\left(\n  \\left[ \\begin{array}{cc} z - 1 + l_2 & -l_2 \\\\ l_1 & z - 2 - l_1 \\end{array} \\right]\n  \\right)\n\\\\\n&= z^2 + z (l_2 - l_1 - 3) + (l_1 - 2 l_2 + 2)\n\\end{align*}\n%\nIf we match the equations\n%\n\\begin{align*}\n  l_2 - l_1 &= 3\n\\\\\n  -l_1 + 2 l_2 &= 2\n\\\\\n l_2 &= -1\n\\\\\n l_1 &= -4\n\\end{align*}\n%\nThus $L = \\left[ \\begin{array}{c} -1 \\\\ -4 \\end{array} \\right]$\n\n\\subsection*{Design of Observer Gain Using Reachable Canonical\nForm}\n\nLet's assume that the state-space representation is in observable \ncanonical form \n%\n\\begin{align*}\nG &= \\left[ \\begin{array}{ccccc} 0 & 0 & \\cdots & 0 & -a_{n} \n              \\\\ 1 & 0 & \\cdots & 0 & -a_{n-1} \n\\\\ \\vdots & \\vdots & \\vdots & \\vdots & \\vdots\n\\\\ 0 & 0 & \\cdots & 0 & -a_2\n    \\\\ 0 & 0 & \\cdots & 1 & -a_1 \\end{array} \\right]\n\\quad , \\quad \nH = \\left[ \\begin{array}{c} (b_n - b_0 a_n)  \\\\ (b_{n-1} - b_0\n             a_{n-1}) \\\\ \\vdots \\\\ (b_2 - b_0 a_2) \\\\   (b_1 - b_0\n             a_1) \n\\end{array} \\right]\n\\\\ C &= \\left[ \\begin{array}{ccccc} 0 & 0 & \\cdots &  0 & 1 \\end{array} \\right]\n\\quad , \\quad\nD = b_0\n\\end{align*}\n%\nLet $L = \\left[ \\begin{array}{c} l_n \\\\ \\vdots \\\\ l_1 \\end{array} \\right]$, then\n$( G - L C )$ takes the form\n%\n\\begin{align*}\n\\left( G - L C \\right) &= \\left[ \\begin{array}{ccccc} 0 & 0 & \\cdots & 0 & -a_{n} \n              \\\\ 1 & 0 & \\cdots & 0 & -a_{n-1} \n\\\\ \\vdots & \\vdots & \\vdots & \\vdots & \\vdots\n\\\\ 0 & 0 & \\cdots & 0 & -a_2\n    \\\\ 0 & 0 & \\cdots & 1 & -a_1 \\end{array} \\right]\n- \\left[ \\begin{array}{c} l_n \\\\ \\vdots \\\\ l_1 \\end{array} \\right]\n\\left[ \\begin{array}{ccccc} 0 & 0 & \\cdots &  0 & 1 \\end{array}\n                                                  \\right]\n\\\\\n&= \n\\left[ \\begin{array}{ccccc} 0 & 0 & \\cdots & 0 & -(a_{n} + l_n)\n              \\\\ 1 & 0 & \\cdots & 0 & - (a_{n-1} + l_{n-1})\n\\\\ \\vdots & \\vdots & \\vdots & \\vdots & \\vdots\n\\\\ 0 & 0 & \\cdots & 0 & - (a_2 + l_n)\n    \\\\ 0 & 0 & \\cdots & 1 & - (a_1 + l_n) \\end{array} \\right]\n\\end{align*}\n%\nThe characterstic equation of $G - LC$ is simply given as\n%\n\\begin{align*}\n  p(z) = z^n + ( a_1 - l_1 ) z^{n-1} + \\cdots + ( a_{n-1} - l_{n-1} )\n  z + ( a_{n} - l_{n} )\n\\end{align*}\n%\nLet's assume that desired $p^*(z)$ is equal to\n%\n\\begin{align*}\n  p(z) = z^n + a_1^* z^{n-1} + \\cdots + a_{n-1}^* \n  z + a_{n}^*\n\\end{align*}\n%\nThen, the observer gain $L$ is computed as\n%\n\\begin{align*}\nL^* = \\left[ \\begin{array}{c} a_n^* - a_n \\\\ \\vdots \\\\ a_1^* - a_1 \\end{array} \\right]\n\\end{align*}\n\nIf the system is not in Observable canonical form, we can find a\ntransformation that outputs the Observable canonical form\nrepresentation\n%\nThe Observability matrix of a state-space representation is given as\n%\n\\begin{align*}\n O = \\left[ \\begin{array}{c} C \\\\ C G \\\\ \\vdots \\\\ C G^{-1} \\end{array} \\right]\n\\end{align*}\n%\nLet's define a transformation matrix $Q$ as follows:\n%\n\\begin{align*}\n  Q &= \\left( W O \\right)^{-1} \\quad , \\quad x[k] = Q \\bar{x}[k]\n\\\\\n \\bar{x}[k+1] &= \\left[ Q^{-1} G Q \\right] \\bar{x}[k] + Q^{-1} H u[k]\n\\\\ \n  y[k] &= C Q \\bar{x}[k] + D u[k]\n\\end{align*}\n%\nwhere\n%\n\\begin{align*}\n  W = \\left[ \\begin{array}{ccccc} a_{n-1} & a_{n-2} & \\cdots & a_1 & 1\n               \\\\ \na_{n-2} & a_{n-3} & \\cdots & 1 & 0\n\\\\ \\vdots & \\vdots & \\iddots & & \\vdots\n\\\\ a_1 & 1 &  & & \n    \\\\ 1 & 0 & \\cdots &  & 0 \\end{array} \\right] \n\\end{align*}\n%\nThen it is given that\n%\n\\begin{align*}\n  \\bar{G} = Q^{-1} G Q  &=  \\left[ \\begin{array}{ccccc} 0 & 0 & \\cdots & 0 & -a_{n} \n              \\\\ 1 & 0 & \\cdots & 0 & -a_{n-1} \n\\\\ \\vdots & \\vdots & \\vdots & \\vdots & \\vdots\n\\\\ 0 & 0 & \\cdots & 0 & -a_2\n    \\\\ 0 & 0 & \\cdots & 1 & -a_1 \\end{array} \\right]\n\\\\\n  \\bar{C}  = C Q & = \\left[ \\begin{array}{ccccc} 0 & 0 & \\cdots & 0\n    & 1 \\end{array} \\right]\n\\end{align*}\n%\nLet's compute $\\bar{C} Q^{-1}$\n%\n\\begin{align*}\n\\bar{C} Q^{-1} &= \\bar{C} W O \n\\\\\n&= \\left[ \\begin{array}{ccccc} 0 & 0 & \\cdots & 0\n    & 1 \\end{array} \\right]\n \\left[ \\begin{array}{ccccc} a_{n-1} & a_{n-2} & \\cdots & a_1 & 1\n               \\\\ \na_{n-2} & a_{n-3} & \\cdots & 1 & 0\n\\\\ \\vdots & \\vdots & \\iddots & & \\vdots\n\\\\ a_1 & 1 &  & & \n    \\\\ 1 & 0 & \\cdots &  & 0 \\end{array} \\right] O^T \n  \\\\\n&= \\left[ \\begin{array}{ccccc} 1 & 0 & \\cdots & 0 & 0 \\end{array}\n                                                    \\right]\n\\left[ \\begin{array}{cccc} C & C G & \\cdots & C G^{-1} \\end{array}\n                                                    \\right]\n\\\\\n&= C\n\\end{align*}\n%\nA similar approach (but longer) can be used to show \nthat $Q^{-1} G Q = \\bar{G}$. \n\nWe know how to design a\nobserver gain $\\bar{L}$ for the Observable\ncanonical form. Given $\\bar{L}$, Observer gain \nw.r.t. original state-space representation is \ncomputed as \n%\n\\begin{align*}\n L = Q \\bar{L}\n\\end{align*}\n\n\\textbf{Example 2:} Consider the following DT system\n%\n\\begin{align*}\n x[k+1] &= \\left[ \\begin{array}{cc} 1 & 0 \\\\ 0 & 2 \\end{array} \\right] x[k]\n    + \\left[ \\begin{array}{c} 1 \\\\ 1 \\end{array} \\right] u[k]\n\\\\\n y[k] &= \\left[ \\begin{array}{cc} 1 & -1 \\end{array} \\right] u[k]\n\\end{align*}\n% \nDesign an observer using the Observable canonical form \nsuch that estimater poles are located at $\\lambda_{1,2} = 0$ (Dead-beat Observer)\n\n\\textbf{Solution:} Characteristic equation of $G$ can be derived as\n%\n\\begin{align*}\n \\mathrm{det} \\left(  \\left[ \\begin{array}{cc} z-1 & 0 \\\\ 0 &\n                                                              z-2 \\end{array} \\right]  \\right)\n = z^2 - 3 z + 2\n\\end{align*}\n%\nObservability matrix can be computed as\n%\n\\begin{align*}\n O = \\left[ \\begin{array}{cc} 1 & -1 \\\\ 1 &\n                                                              -2 \\end{array} \\right]\n\\end{align*}\n%\nThe matrix $W$ can be computed as\n%\n\\begin{align*}\n  W =  \\left[ \\begin{array}{cc} -3 & 1 \\\\ 1 & 0 \\end{array} \\right]\n\\end{align*}\n%\nTransformation matrix $Q$ can be computed as\n%\n\\begin{align*}\n  Q &= \\left( W O^T \\right)^{-1}\n\\\\\n&= \\left( \n\\left[ \\begin{array}{cc} -3 & 1 \\\\ 1 & 0 \\end{array} \\right] \n\\left[ \\begin{array}{cc} 1 & -1 \\\\ 1 & -2 \\end{array} \\right]\n\\right)^{-1}\n= \\left( \n\\left[ \\begin{array}{cc} -2 & 1 \\\\ 1 & -1 \\end{array} \\right] \n\\right)^{-1}\n=\n\\left[ \\begin{array}{cc} -1 & -1 \\\\ -1 & -2 \\end{array} \\right] \n\\end{align*}\n%\n%\nGiven that desired characteristic polynomial is $p^*(z) = z^2$,\n$\\bar{L}$ of observable canonical from can be computed as\n%\n\\begin{align*}\n  \\bar{L} &= \\left[ \\begin{array}{c} - a_2 \\\\ -\n                                                       a_1 \\end{array}\n                                                       \\right]\n\\\\\n&= \\left[ \\begin{array}{c} -2 \\\\ 3 \\end{array}\n                                                       \\right]\n\\end{align*}\n%\nFinally Observer Gain $L$ can be computed as\n%\n%\n\\begin{align*}\n L &= Q \\bar{L} = \n \\left[ \\begin{array}{c} -1 \\\\ -4 \\end{array} \\right]\n\\end{align*}\n% \nNot surprisingly the result is same with the one found in\nfirst example.\n\n\\section*{Closed-Loop Observer \\& State-Feedback}\n\nIn the state-feedback control policy the input is ideally defined\nby the following law\n%\n\\begin{align*}\n u[k] = - K x[k]\n\\end{align*}\n%\nHowever, as mentioned in Observer lecture, in general we don't have\ndirect access to the all states of the system. In this case, we learnt\nhow to design an Observer/Estimator of the states. In this respect,\nit is natural to assume that in a closed-loop system, the control\npolicy that define the input should depend on the estimated states\n%\n\\begin{align*}\n u[k] = - K \\hat{x}[k]\n\\end{align*}\n%\nHowever the important question how this coupling affect the\nclosed-loop behavior, and even deeper question can be even \nuse such a policy. The advantage of LTI systems is that \nstate-feedback gain, and observer gain can be seperatelly\ndesigned and we guarntee a stable closed-loop performance. \nIn this section, we will analyze the coupled system\n%\nEquations of motion for the closed-loop observer \\& state-feedback\nbased control system is given below\n%\n\\begin{align*}\n   x[k+1] &= G x[k] + H u[k]\n  \\\\ \n   y[k] &= C x[k] + D u[k]\n  \\\\\n  \\hat{x}[k+1] &= G \\hat{x}[k] + H u[k] + L \\left( y[k] - \\hat{y}[k] \\right) \n  \\\\\n  \\hat{y}[k] &= C \\hat{x}[k] + D u[k]\n  \\\\\n   u[k] &= -K \\hat{x}[k]\n\\end{align*}\n%\nIf we eliminate $u[k]$ and $\\hat{y}[k]$ we obtain following \ndynamical representation\n%\n\\begin{align*}\n   x[k+1] &= G x[k] - H K \\hat{x}[k] \n  \\\\\n  \\hat{x}[k+1] &= G \\hat{x}[k] - H K \\hat{x}[k] + L C \\left( x[k] -\n                 \\hat{x}[k] \\right) \n  \\\\ \n   y[k] &= C x[k] - D K \\hat{x}[k] \n\\end{align*}\n%\nNow let's replace $\\hat{x}[k]$ with $e[k] = x[k] - \\hat{x}[k]$\n%\n\\begin{align*}\n   x[k+1] &= ( G - H K ) x[k] + H K e[k]\n  \\\\\n  e[k+1] &= ( G - LC ) e[k]\n  \\\\ \n   y[k] &= (C - D K) x[k] + D K e[k]\n\\end{align*}\n%\nNow let's defina a state for the whole system, \n$z[k] = \\left[ \\begin{array}{c} x[k] \\\\ e[k] \\end{array} \\right]$\nthen the state-space representation is given by\n%\n\\begin{align*}\n  z[k+1] = \\left[ \\begin{array}{cc} (G - H K) & H K\\\\ 0_{n \\times n}\n                                              & (G - LC) \\end{array}\n                                                \\right] z[k]\n\\\\\n y[k] = \\left[ \\begin{array}{cc} (C - DK) & D K \\end{array}\n                                                \\right] z[k]\n\\end{align*}\n%\nThe system matrix is in block diagonal form and the eigenvalues\nof this new system matrix is find by taking the union of eigenvalues\nof $(G - H K)$ and eigenvalues of $(G - L C)$. Thus a seperate\npole-placement can be performed for the state-feedback controller\nand the observer. \n\n% **** This ENDS THE EXAMPLES. DON'T DELETE THE FOLLOWING LINE:\n\\end{document}\n%\n", "meta": {"hexsha": "6ef4b8c6c37388a1003ef2d3758447de30843494", "size": 15627, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "METU-EE402/Lecture 17/EE402_Lecture_17.tex", "max_stars_repo_name": "sahinalper/Lecture-Notes", "max_stars_repo_head_hexsha": "1221614d34658593f8858de320e8be80fbb8e4c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-10-03T15:31:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-03T15:31:15.000Z", "max_issues_repo_path": "METU-EE402/Lecture 17/EE402_Lecture_17.tex", "max_issues_repo_name": "asudeeaydin/Lecture-Notes", "max_issues_repo_head_hexsha": "1876e743aed367c160cbc5376f5d1e5a34b8b8fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "METU-EE402/Lecture 17/EE402_Lecture_17.tex", "max_forks_repo_name": "asudeeaydin/Lecture-Notes", "max_forks_repo_head_hexsha": "1876e743aed367c160cbc5376f5d1e5a34b8b8fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4293785311, "max_line_length": 94, "alphanum_fraction": 0.5807896589, "num_tokens": 5750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.6224593241981982, "lm_q1q2_score": 0.3306562367972056}}
{"text": "\\section{Geometry}\\label{sec:geometry}\n\nGeometry is the multi-millennium evolution of attempts to measure parts of the earth. Ironically, it may be the main historical justification for the gradual axiomatization of mathematics. Completely abstract results about shapes date at least as early as in Ancient Greece. The important distinction between ancient geometry and modern geometry is the introduction of coordinates in the 17th century.\n\nAn axiomatic approach for a theory of plane and, solid figures was developed by Euclid in the third century BC. Later, Hilbert, Tarski and others independently proposed axioms that fit the requirements of modern logic systems. This is known today as \\term{synthetic Euclidean geometry} and is mostly of theoretical interest because modern tools are easier to work with.\n\nDescartes' idea of coordinates connects problems of algebra and geometry in such a way that most of today's mathematics seamlessly switches between algebraic and geometric interpretations of the same problem. The study of classical Greek geometry in terms of coordinates is known as \\term{analytic geometry}.\n", "meta": {"hexsha": "21f9a82544b27aa2790818c330c0f98d733b6593", "size": 1123, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/geometry.tex", "max_stars_repo_name": "v--/anthology", "max_stars_repo_head_hexsha": "89a91b5182f187bc1aa37a2054762dd0078a7b56", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/geometry.tex", "max_issues_repo_name": "v--/anthology", "max_issues_repo_head_hexsha": "89a91b5182f187bc1aa37a2054762dd0078a7b56", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/geometry.tex", "max_forks_repo_name": "v--/anthology", "max_forks_repo_head_hexsha": "89a91b5182f187bc1aa37a2054762dd0078a7b56", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 140.375, "max_line_length": 401, "alphanum_fraction": 0.8263579697, "num_tokens": 216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.3306562312783846}}
{"text": "\\documentclass[a4paper]{article}\n\\setlength{\\oddsidemargin}{-0.7cm}\n\\setlength{\\topmargin}{-1.5cm}\n\\setlength{\\textwidth}{16.5cm}\n\\setlength{\\textheight}{24cm}\n\n\\usepackage{amsmath}\n\\usepackage{graphics}\n\n\\newcommand{\\ex}[1]{E[ #1 ]}\n\\newcommand{\\xb}{\\bar{\\bf x}}\n\\newcommand{\\sgm}{\\sigma^2({\\bf x})}\n\\newcommand{\\ess}{{\\cal S}({\\bf x})}\n\n\\title{Unbiased Estimator for Fourth Moments}\n\\author{Synge Todo \\\\\n  {\\it Department of Physics, University of Tokyo, Tokyo 113-0033, Japan}}\n\n\\begin{document}\n\\maketitle\n\n\\section{Hybrids}\nBefore considering unbiased estimator for the fourth moments, we introduce more hybrids moments in addition to Online Appendix~M of Ref.~\\cite{Klements2009}.\n\\begin{align}\n  \\begin{split}\n    \\ex{x_1 x_2 \\xb^2} =& \\frac{1}{n^2} \\ex{x_1 x_2 (\\sum_{i=1}^n x_i)^2} \\\\\n    =& \\frac{1}{n^2} \\ex{x_1 x_2 (x_1^2 + x_2^2 + \\sum_{i=3}^n x_i^2 + 2 x_1 x_2 + 2 x_1 (\\sum_{i=3}^n x_i) + 2 x_2 (\\sum_{i=3}^n x_i) + \\sum_{i=3}^n\\sum_{j=i+1}^n x_i x_j)} \\\\\n    =& \\frac{2}{n^2} \\ex{x_1^3 x_2} + \\frac{n-2}{n^2} \\ex{x_1 x_2 x_3^2} + \\frac{2}{n^2} \\ex{x_1^2 x_2^2} + \\frac{4(n-2)}{n^2} \\ex{x_1^2 x_2 x_3} \\\\ &+ \\frac{(n-2)(n-3)}{n^2} \\ex{x_1 x_2 x_3 x_4} \\\\\n    =& \\frac{2}{n^2} (\\ess + 3 \\sgm \\mu + \\mu^3) \\mu + \\frac{5(n-2)}{n^2} (\\sgm + \\mu^2) \\mu^2 + \\frac{2}{n^2} (\\sgm^2+\\mu^2)^2 \\\\ &+ \\frac{(n-2)(n-3)}{n^2} \\mu^4 \\\\\n    =& \\frac{2}{n^2} \\ess \\mu + \\frac{5}{n} \\sgm \\mu^2 + \\frac{2}{n^2} \\sigma^4 + \\mu^4\n  \\end{split} \\\\\n  \\begin{split}\n    \\ex{x_1^2 x_2 \\xb} =& \\frac{1}{n} \\ex{x_1^2 x_2 (\\sum_{i=1}^n x_i)} \\\\\n    =& \\frac{1}{n} \\ex{x_1^3 x_2 + x_1^2 x_2^2 + (n-2) x_1^2 x_2 x_3} \\\\\n    =& \\frac{1}{n} (\\ess + 3 \\sgm \\mu + \\mu^3) \\mu + \\frac{1}{n} (\\sgm + \\mu^2)^2 + \\frac{n-2}{n} (\\sgm + \\mu^2) \\mu^2 \\\\\n    =& \\frac{1}{n} \\ess \\mu + \\frac{(n+3)}{n} \\sgm \\mu^2 + \\frac{1}{n} \\sigma^4 + \\mu^4.\n  \\end{split}\n\\end{align}\n\n\\section{Square of variance, $\\sigma_{\\xb}^4({\\bf x})$}\n\nExpression for square of variance, $\\sigma_{\\xb}^4({\\bf x})$, given on p.~9 in Online Appendix~M of Ref.~\\cite{Klements2009} is not correct.  The correct expression is\n\\begin{align}\n  \\begin{split}\n    \\sigma_{\\xb}^4({\\bf x}) =& \\ex{(x_i-\\xb)^2(x_j-\\xb)^2} \\\\\n    =& \\ex{\\frac{1}{n}\\sum(x_i-\\xb)^2\\cdot\\frac{1}{n}\\sum(x_j-\\xb)^2} \\\\\n    =& \\frac{1}{n^2} \\ex{\\sum_i \\sum_j (x_i-\\xb)^2(x_j-\\xb)^2} \\\\\n    =& \\frac{1}{n^2} \\ex{\\sum_i (x_i-\\xb)^4} + \\frac{1}{n^2} \\ex{\\sum_i \\sum_{j\\ne i} (x_i-\\xb)^2(x_j-\\xb)^2} \\\\\n    =& \\frac{1}{n} \\ex{(x_1-\\xb)^4} + \\frac{n-1}{n} \\ex{(x_1-\\xb)^2(x_2-\\xb)^2} \\\\\n    =& \\frac{1}{n} \\ex{(x_1-\\xb)^4} + \\frac{n-1}{n} \\ex{x_1^2 x_2^2 - 4 x_1^2 x_2 \\xb + 2x_1^2 \\xb^2 + 4 x_1 x_2 \\xb^2 - 4 x_1 \\xb^3 + \\xb^4} \\\\\n    =& \\frac{1}{n} {\\cal K_{\\xb}(\\bf x)}\n    + \\frac{n-1}{n} (\\sgm + \\mu^2)^2 \\\\\n    &- \\frac{4(n-1)}{n} \\Big[ \\frac{1}{n} \\ess \\mu + \\frac{(n+3)}{n} \\sgm \\mu^2 + \\frac{1}{n} \\sigma^4 + \\mu^4 \\Big] \\\\\n    &+ \\frac{2(n-1)}{n} \\Big[ \\frac{1}{n^2} {\\cal K}({\\bf x}) + \\frac{2(n+1)}{n^2} \\ess \\mu + \\frac{n+5}{n} \\sgm \\mu^2 + \\frac{n-1}{n^2} \\sigma^4 + \\mu^4 \\Big] \\\\\n    &+ \\frac{4(n-1)}{n} \\Big[ \\frac{2}{n^2} \\ess \\mu + \\frac{5}{n} \\sgm \\mu^2 + \\frac{2}{n^2} \\sigma^4 + \\mu^4\\Big] \\\\\n    &- \\frac{4(n-1)}{n} \\Big[ \\frac{1}{n^3} {\\cal K}({\\bf x}) + \\frac{4}{n^2} \\ess \\mu + \\frac{6}{n} \\sgm \\mu^2 + \\frac{3(n-1)}{n^3} \\sigma^4 + \\mu^4 \\Big] \\\\\n    &+ \\frac{n-1}{n} \\Big[ \\frac{1}{n^3} {\\cal K}({\\bf x}) + \\frac{4}{n^2} \\ess \\mu + \\frac{6}{n} \\sgm \\mu^2 + \\frac{3(n-1)}{n^3} \\sigma^4 + \\mu^4 \\Big] \\\\\n    =& \\frac{1}{n} {\\cal K_{\\xb}(\\bf x)} + \\frac{(n-1)(2n-3)}{n^4} {\\cal K}({\\bf x})\n    + \\frac{(n-1)(n^3-2n^2-3n+9)}{n^4} \\sigma^4({\\bf x}) \\\\\n    =& \\frac{n-1}{n^3} \\Big[ (n-1) {\\cal K}({\\bf x}) + (n^2-2n+3) \\sigma^4({\\bf x}) \\Big].\n  \\end{split}\n  \\label{eqn:square_of_variance}\n\\end{align}\nIn the last line in Eq.~(\\ref{eqn:square_of_variance}), we use the expression for the fourth sample central moment:\n\\begin{align}\n  \\begin{split}\n    {\\cal K_{\\xb}(\\bf x)} = \\ex{(x_i-\\xb)^4} = \\frac{n-1}{n^3} \\Big[ (n^2-3n+3) {\\cal K}({\\bf x}) + (6n-9)\\sigma^4({\\bf x}) \\Big],\n  \\end{split}\n  \\label{eqn:fourth_sample_central_moment}\n\\end{align}\nwhich is given on p.~8 in Online Appendix~M of Ref.~\\cite{Klements2009}.\n\n\\section{Unbiased estimator for $\\sigma^4({\\bf x})$, ${\\cal K}({\\bf x})$, and fourth cumulant}\n\nBy solving Eqs.~(\\ref{eqn:square_of_variance}) and (\\ref{eqn:fourth_sample_central_moment}), we obtain the unbiased estimators for the square of the variance, the fourth central moment, and the fourth cumulant as\n\\begin{align}\n  \\begin{split}\n    \\sigma^4({\\bf x}) = \\frac{n}{(n-1)(n-2)(n-3)} \\Big[ (n^2-3n+3) \\sigma_{\\xb}^4({\\bf x}) - (n-1) {\\cal K_{\\xb}(\\bf x)} \\Big]\n  \\end{split} \\\\\n  \\begin{split}\n    {\\cal K}({\\bf x}) = \\frac{n}{(n-1)(n-2)(n-3)} \\Big[ (n^2-2n+3) {\\cal K_{\\xb}(\\bf x)} - (6n-9) \\sigma_{\\xb}^4({\\bf x}) \\Big]\n  \\end{split} \\\\\n  \\begin{split}\n    \\kappa_4({\\bf x}) = {\\cal K}({\\bf x}) - 3 \\sigma^4({\\bf x})\n    = \\frac{n^2}{(n-1)(n-2)(n-3)} \\Big[ (n+1) {\\cal K_{\\xb}(\\bf x)} - 3(n-1) \\sigma_{\\xb}^4({\\bf x}) \\Big],\n  \\end{split}\n\\end{align}\nrespectively.\n\n\\section{Numerical tests}\n\nWe test numerically the above expressions for the Bernoulli distribution ${\\cal B}(p=3/4)$ and the normal distribution ${\\cal N}(\\mu=2,\\sigma=3/2)$. We evaluate Eqs.~(1)--(7) for the sample size $n=4,8,16,32,\\cdots,1024$. For each sample size, we take the average over 65536 sample sets and estimate the error bar. The results are shown in Figs.~1--7.\n\n\\bibliographystyle{naturemag}\n\\bibliography{fourth-moment}\n\n\\clearpage\n\n\\begin{figure}\n  \\begin{center}\n    \\resizebox{0.47\\textwidth}{!}{\\includegraphics{plot-eq1-b.pdf}}\n    \\resizebox{0.47\\textwidth}{!}{\\includegraphics{plot-eq1-n.pdf}}\n  \\end{center}\n  \\caption{Sample-size dependence of $\\ex{x_1 x_2 \\xb^2}$ for the Bernoulli distribution ${\\cal B}(p=3/4)$ (left) and the normal distribution ${\\cal N}(\\mu=2,\\sigma=3/2)$ (right). The green squares denotes the numerical results and the purple line denotes Eq.~(1) calculated by using the exact moments.}\n\\end{figure}\n\n\\begin{figure}\n  \\begin{center}\n    \\resizebox{0.47\\textwidth}{!}{\\includegraphics{plot-eq2-b.pdf}}\n    \\resizebox{0.47\\textwidth}{!}{\\includegraphics{plot-eq2-n.pdf}}\n  \\end{center}\n  \\caption{Sample-size dependence of $\\ex{x_1^2 x_2 \\xb}$ for the Bernoulli distribution ${\\cal B}(p=3/4)$ (left) and the normal distribution ${\\cal N}(\\mu=2,\\sigma=3/2)$ (right). The green squares denotes the numerical results and the purple line denotes Eq.~(2) calculated by using the exact moments.}\n\\end{figure}\n\n\\begin{figure}\n  \\begin{center}\n    \\resizebox{0.47\\textwidth}{!}{\\includegraphics{plot-eq3-b.pdf}}\n    \\resizebox{0.47\\textwidth}{!}{\\includegraphics{plot-eq3-n.pdf}}\n  \\end{center}\n  \\caption{Sample-size dependence of $\\sigma_{\\xb}^4({\\bf x})$ for the Bernoulli distribution ${\\cal B}(p=3/4)$ (left) and the normal distribution ${\\cal N}(\\mu=2,\\sigma=3/2)$ (right). The green squares denotes the numerical results and the purple line denotes Eq.~(3) calculated by using the exact moments.}\n\\end{figure}\n\n\\begin{figure}\n  \\begin{center}\n    \\resizebox{0.47\\textwidth}{!}{\\includegraphics{plot-eq4-b.pdf}}\n    \\resizebox{0.47\\textwidth}{!}{\\includegraphics{plot-eq4-n.pdf}}\n  \\end{center}\n  \\caption{Sample-size dependence of ${\\cal K_{\\xb}(\\bf x)}$ for the Bernoulli distribution ${\\cal B}(p=3/4)$ (left) and the normal distribution ${\\cal N}(\\mu=2,\\sigma=3/2)$ (right). The green squares denotes the numerical results and the purple line denotes Eq.~(4) calculated by using the exact moments.}\n\\end{figure}\n\n\\begin{figure}\n  \\begin{center}\n    \\resizebox{0.47\\textwidth}{!}{\\includegraphics{plot-eq5-b.pdf}}\n    \\resizebox{0.47\\textwidth}{!}{\\includegraphics{plot-eq5-n.pdf}}\n  \\end{center}\n  \\caption{Results for the square of the variance, $\\sigma^4({\\bf x})$, by using the unbiased estimator~(5) for the Bernoulli distribution ${\\cal B}(p=3/4)$ (left) and the normal distribution ${\\cal N}(\\mu=2,\\sigma=3/2)$ (right). The green squares denotes the numerical results and the purple line denotes the exact value.}\n\\end{figure}\n\n\\begin{figure}\n  \\begin{center}\n    \\resizebox{0.47\\textwidth}{!}{\\includegraphics{plot-eq6-b.pdf}}\n    \\resizebox{0.47\\textwidth}{!}{\\includegraphics{plot-eq6-n.pdf}}\n  \\end{center}\n  \\caption{Results for the fourth central moment, ${\\cal K}({\\bf x})$, by using the unbiased estimator~(6) for the Bernoulli distribution ${\\cal B}(p=3/4)$ (left) and the normal distribution ${\\cal N}(\\mu=2,\\sigma=3/2)$ (right). The green squares denotes the numerical results and the purple line denotes the exact value.}\n\\end{figure}\n\n\\begin{figure}\n  \\begin{center}\n    \\resizebox{0.47\\textwidth}{!}{\\includegraphics{plot-eq7-b.pdf}}\n    \\resizebox{0.47\\textwidth}{!}{\\includegraphics{plot-eq7-n.pdf}}\n  \\end{center}\n  \\caption{Results for the fourth cumulant, $\\kappa_4({\\bf x})$, by using the unbiased estimator~(6) for the Bernoulli distribution ${\\cal B}(p=3/4)$ (left) and the normal distribution ${\\cal N}(\\mu=2,\\sigma=3/2)$ (right). The green squares denotes the numerical results and the purple line denotes the exact value.}\n\\end{figure}\n\n\\end{document}\n", "meta": {"hexsha": "385bb3e3e239aff942ba1f4b8933e3a1f7f32f06", "size": 9061, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/stat/fourth-moment.tex", "max_stars_repo_name": "FIshikawa/standards", "max_stars_repo_head_hexsha": "d146e99a53504c07226d6ef6b38255ea31c58f5c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-06T13:04:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-06T13:04:43.000Z", "max_issues_repo_path": "doc/stat/fourth-moment.tex", "max_issues_repo_name": "FIshikawa/standards", "max_issues_repo_head_hexsha": "d146e99a53504c07226d6ef6b38255ea31c58f5c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-01-23T01:03:51.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-23T01:03:51.000Z", "max_forks_repo_path": "doc/stat/fourth-moment.tex", "max_forks_repo_name": "FIshikawa/standards", "max_forks_repo_head_hexsha": "d146e99a53504c07226d6ef6b38255ea31c58f5c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-06-10T08:37:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-02T10:55:39.000Z", "avg_line_length": 58.0833333333, "max_line_length": 351, "alphanum_fraction": 0.6171504249, "num_tokens": 3749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.33062512299989755}}
{"text": "\\label{ch:3}\nIn this section, we discuss different learning-based approaches that have been explored in recent years. To keep the discussion relevant to the contribution of the thesis, the discussion is focused on bodies work that fall under the banner of reinforcement learning (RL) or inverse reinforcement learning (IRL) based methods. Both RL and IRL have been widely researched in the field of socially-aware navigation. While these methods differ at their core, the problem definition for both the cases is mostly similar but with a key difference. For both RL and IRL setting, the problem at hand is expressed in the form of a Markov decision process (MDP). We define the problem below.\n\\subsection*{Problem definition:}\nA Markov decision process is a discrete-time stochastic control process and can be represented as a 5 tuple\n($\\mathcal{S}$,$\\mathcal{A}$,T,$\\gamma$, $\\mathcal{R}$), where,\n\\begin{itemize}\n    \\item $\\mathcal{S}$ is the set of all possible states.\n    \\item $\\mathcal{A}$ is the set of all possible actions.\n    \\item T is the transition dynamics.\n    \\item $\\gamma$ is the discount factor.\n    \\item $\\mathcal{R}$ is the set of rewards.\n\\end{itemize}  \nIn reinforcement learning problems, the goal is to find a policy $\\pi$: a function that maps a state to an action that maximizes the expected reward obtained.\\\\\nIn contrast, in inverse reinforcement learning problems, there is no reward function. Instead, a set of expert demonstrations is provided. This can be denoted by, D = \\{$\\tau_1$, $\\tau_2$, ... \\}. The goal is to generate a reward function $\\mathcal{R}$, which best explains the expert behavior and a policy that maximizes the reward function.\n\n\n\\section{RL based approaches}\n With their remarkable success in the field of video games and a suite of tasks of similar anatomy, RL has been one of the go-to tools in the field of social navigation in recent years. \\\\\nChen et al. \\cite{chen_socially_2017} address this problem by focusing on what not to do, rather than what to do. They introduce a reward function crafted to induce social norms in the behavior of the agent. The reward function primarily focuses on three different aspects of interaction: overtaking, passing, and crossing as shown in \\autoref{fig:chen_socially_crossing}\n \\begin{figure}[!htbp]\n     \\centering\n    \\includegraphics[width=.6\\linewidth]{figures/chapter2_rl_based_approach}\n    \\caption{Symmetric pairwise collision avoidance in a time efficient manner by the red agent in the three interaction scenarios. The interactions in the top and bottom row are often referred as left and right-handed rules respectively.}\n    \\label{fig:chen_socially_crossing}\n \\end{figure}\n%\\thcomment{In their paper they write : \"This work notes that social norms are one of the many\n%\tways to resolve a symmetrical collision avoidance scenario,\n%\tas illustrated in... \"}\nThey claim that symmetry is one of the driving factors that incorporate social behavior. The reward function they define is given by \\autoref{eq:chen_socially_2017_reward_function}.\n\\begin{align}\n\\label{eq:chen_socially_2017_reward_function}\n\\begin{split}\nR_{norm}(s^{jn}, a) &=  q_nI(s^{jn} \\in S_{norm})\\\\\ns.t. \\qquad S_{norm}&=  S_{pass} \\cup S_{ovtk} \\cup S_{cross}\\\\\nS_{pass} &= \\{s^{jn} | d_g > 3, 1 < \\tilde{p_x} < 4,\n\t\t\t  -2 < \\tilde{p_y} < 0, |\\tilde{\\phi} - \\psi| > 3\\pi/4 \\} \\\\\nS_{ovtk} &= \\{s^{jn} | d_g > 3, 0 < \\tilde{p_x} < 3, |v| > |\\tilde{v}|\n\t\t\t  0 < \\tilde{p_y} < 1, |\\tilde{\\phi} - \\psi| < \\pi/4 \\} \\\\\nS_{cross} &= \\{s^{jn} | d_g > 3, \\tilde{d_a} < 2,  \\tilde{\\phi_{rot}} > 0,\n\t\t\t  -3\\pi/4 < \\tilde{\\phi} - \\psi < -\\pi/4  \\}\n\\end{split}\n\\end{align}\\\\\nwhere, $I$ is an indicator function. $S_{pass}$, $S_{ovtk}$, and $S_{cross}$ are the set of states that fall under the category of passing, overtaking and crossing respectively, $s^{jn}$ is the joint state of the agent and its neighbor, $a$ is the action, $q_{n}$ is a scalar penalty, $d_{g}$ is the distance of the goal from the agent, $d_{a}$ is the distance to the neighboring agent, $\\tilde{\\phi}$ is the neighboring agent's orientation, $\\phi$ is the agent's orientation, $\\tilde{\\phi_{rot}}$ is the relative rotation angle between the two agents and $\\tilde{p_x}$ and $\\tilde{p_y}$ are the $x$ and $y$ coordinates of the neighboring agent in the target agent's reference frame. The reward function in \\autoref{eq:chen_socially_2017_reward_function} biases the agent towards adhering to the right-hand rules.\n\\\\\n\nA more recent work by the same authors, \"Collision avoidance in pedestrian-rich environments with deep reinforcement learning\" \\cite{everett_collision_2019}, %\\thcomment{Yes, it is the title of their paper.}\naddress drawbacks of their previous work: the inability to tackle a variable number of agents in the environment. They introduce a long short-term memory (LSTM) \\cite{hochreiterLongShortTermMemory1997} network architecture as shown in \\autoref{fig:everett_lstm_network} that takes as input the information from the nearby pedestrians in a sequence which eliminates the need for specifying a limit on the number of nearby-agents the method can handle.\n\\begin{figure}[!htbp]\n\t\\centering\n\t\\includegraphics[width=0.6\\linewidth]{figures/everett}\n\t\\caption{LSTM based network architecture to account for a variable number of nearby agents.}\n\t\\label{fig:everett_lstm_network}\n\\end{figure}\n For this work, they select a relatively simple sparse reward function that focuses on collision avoidance and maintaining distance from others as shown in \\autoref{eq:everett_reward_function}\\\\\n\\begin{align}\n\\label{eq:everett_reward_function}\nR(S^{jn}, \\mathbf{u}) = \n\\begin{cases}\n\t 1 & \\text{if \\quad $p=p_g$} \\\\\n\t -0.1+d_{min}/2 & \\text{if \\quad 0 < $d_{min}$ < 0.2} \\\\\n\t -0.25 & \\text{if \\quad $d_{min}$ < 0}\\\\\n\t 0 & \\text{otherwise}, \n\\end{cases}\n\\end{align}\nwhere $\\mathbf{u}$ is the action, and $s^{jn}$ is the joint state representing all the agents in the world, $p$ and $p_{g}$ are the position of the agent and the goal respectively, and $d_{min}$ is the distance to the nearest neighboring agent.\n%\\textbf{Conclusion}\\\\\n\\subsection*{Conclusion}\n\nReward function is the most succinct definition of the task at hand \\cite{abbeel_apprenticeshiplearning_2004}, making it a vital component that determines the final performance of a RL method. We can see similarities between RL methods and other classical approaches. RL method still involve reward engineering, which can get pretty complex even when considering a handful of simple interactions. The reward function by Everett et al. \\cite{everett_collision_2019} focuses solely on collision avoidance, and Chen et al. \\cite{chen_socially_2017} incorporate an element of naturalness to the mix using symmetry. But it takes into account a very limited number of scenarios: just 3 possible interaction scenarios, which is a small subset of the very many implicit intentions and explicit decisions a human takes while navigating.\n \nReinforcement learning, as a class of methods, has been widely successful in solving various complex control tasks including, but not limited to, video games making it one of the more preferred choices to tackle the problem of social navigation. \\par\nUsing RL in this particular setting however necessitates the formulation of a reward function that can correctly capture the `social and cultural' characteristics. As noted earlier, coming up with such a set of rules can be difficult and daunting as `social norms' are not always explicit and can vary widely across different societies and even based on a given situation.\\\\\n\n\\section{IRL based approaches}\n%\\textbf{Learning approaches meet probabilistic road map style path planner.}\nInverse reinforcement learning bypasses the step of engineering the reward function, instead, it aims at recovering the underlying reward function using expert demonstrations, making it an attractive alternative to RL based methods. IRL has been extensively explored to address the problem of social navigation. \\\\\nVasquez et al. \\cite{vasquez_inverse_2014}, present a comprehensive study on the effect of different feature representations and IRL methods on the performance of an agent in the task of social navigation. They examine two IRL methods: max-margin IRL and max-entropy IRL. Max-margin IRL aims at finding a set of weight parameters that maximizes the margin between the feature expectation of the expert demonstrations and that of the trained policy. The goal of max-entropy IRL is to find a set of weight parameters that maximizes the likelihood of the expert demonstrations, where the probability of occurrence of a given roll-out is proportional to the exponential of the reward obtained by it. \\\\\nFor the feature representations, they create a pool of measurements garnered from the state of the agent itself and the state of the other entities in the environment and combine these measurements to create 3 feature representations. \\\\\nThey test these on a Robot Operating System or, in short, ROS-based pedestrian simulator on 3 scenarios: airport gate, crossing hallway, and intersection. Expert demonstrations for these scenarios are obtained through tele-operation. They find that the performance across the two learning methods are similar. The feature representation, on the other hand, plays a major role in the final performance of the agent hence they come to the conclusion that spending time on modeling the feature representations or working to come up with learning methods that aid in the simplification of building the feature representations might be the way to go.\n\\\\\n\\par\nKim and Pineau \\cite{kim_socially_2016}, present a way to automate the navigation of a wheelchair in a social setting. Their navigation framework comprises of $3$ components, the feature extractor, the IRL module, and the path planner.\\\\\n%\\textbf{Feature extractor}\nThe features are generated from the readings of an RGB-d sensor (3D point cloud) mounted on the robot. The area around the agent is divided into 3D blocks or cells and the features are calculated for each of these spatial cells. \nThe authors calculate $4$ features namely,\ncrowd density, speed, velocity, and distance to the goal.\nWhile the calculation of the crowd density and the distance to the goal is straight forward, the calculation of the speed and velocity from 3D point clouds are more involved and the authors use an RGB-d optical flow method based on Farneback RGB optical flow \\cite{farneback_optical_flow}. \nThe result is a $12$-dimensional binary feature vector for each grid cell.\n%\\textbf{IRL module}\nThe authors use maximum-a-posteriori Bayesian inverse reinforcement learning (MAP-BIRL) \\cite{choi_MAP-BIRL_2011} to calculate the cost function for socially acceptable navigation. The cost of a state is given by\n\\begin{align}\nC(s,a) &=w \\cdot \\phi(s,a)\n\\end{align}\nwhere, $\\phi(s,a)$ is the feature representation of the state $s$ and $w$ is the weight vector learned from MAP-BIRL. \nThe weight vector is obtained by obtaining the maximum-a-posteriori (MAP) inference of the following expression:\n\\begin{align}\nL(w) = \\sum^M_{m=1} \\sum^{H}_{h=1}log[\\frac{\\exp \\mathcal{Q}^{*}_m(s^m_h, a^m_h)}{\\sum_{a\\in A} \\exp(\\mathcal{Q}_m^*(s_h^m,a))}]\n\\end{align}\nwhere, $M$ is the number of trajectories in the expert demonstration, $H$ is the number of states in each trajectory, $s_{h}^{m}$ and  $a_{h}^{m}$ is the state observed and action taken at time step $h^{th}$ of trajectory $m^{th}$ respectively, and $\\mathcal{Q}^{*}_m(s^m_h, a^m_h)$ is the cumulative discounted future reward associated with that state-action pair.\\\\ \nFor path planning, the authors maintain a hierarchical path planner consisting of 3 parts: a global planner, a local planner, and a collision detector.\nThe global planner chalks out a global path from the starting position of the robot to the goal state. The entire path is broken down into multiple sub-goals and the responsibility of moving from one sub-goal to the next falls on the local planner. During the run, the planner maintains a collision detector based on handcrafted rules.\nThe authors test their method on different scenarios including one that involves the robot operating in a crowded corridor.\\\\\n\nFahad et. al. \\cite{fahad_learning_2018}, present a navigation framework to train agents from demonstrations using maximum entropy deep IRL where the objective is to maximize the likelihood of the states visited by the expert.\nThis is achieved by dividing each demonstration, or trajectory, in this case, into a sum of the individual states encountered by the expert. and minimizing the difference in the state visitation frequency (SVF) of the agent and the expert.\\\\\nThe authors present a feature representation consisting of 4 parts:\n\\begin{enumerate}\n    \\item Social Affinity Map(SAM): This captures the motion of the pedestrians in the vicinity of the agent. The area near the agent is divided into two concentric circles. The region inside the inner circle is then divided into 4 parts, and the region between the inner and outer circle is divided into 6 parts as shown in \\autoref{fig:SAM_local_bins}\n    Information from each of these 10 areas (or bins) is then expressed using a 6-dimensional vector that captures the average velocity of the pedestrians in a given bin. \n    \\begin{figure}\n    \t\\centering\n    \t\\includegraphics[width=0.5\\linewidth]{figures/SAM_local_bins.png}\n    \t\\caption{Division of the area around the agent into spatial bins as done in the SAM features. The arrow marks the direction of heading of the agent.}\n    \t\\label{fig:SAM_local_bins}\n    \\end{figure}\n    \\item Density feature: Helps provide an idea of how dense the vicinity of the agent is. It is calculated by adding up the number of pedestrians present in the spatial bins (calculated above). Once calculated they are discretized based on some predefined threshold.\n    \\item Distance feature: Captures the distance between the agent's current location and the goal.\n    \\item Default Cost feature: Introduced to balance the rest of the other features. This has been proposed by various other works in the past.\n    \n\\end{enumerate}\nThe authors train and test their procedure using data collected in the ATC business center in Osaka, Japan.\nFrom these experiments, they show that the method is not only capable of producing a general navigator to negotiate the crowd, but also an agent that show traits of pedestrian behaviors like collision-avoidance and following the leader.\n\n\n\\subsection*{Conclusion}\nBoth Vasequez et al. \\cite{vasquez_inverse_2014} and Fahad et al. \\cite{fahad_learning_2018} assume availability of the transition dynamics of the environment which is difficult to obtain in a real-world environment. They also test their models on fairly restrictive scenarios. Vasquez et al. test on 3 specific interaction scenarios: an airport gate, a crossing hallway and an intersection, and, Fahad et al. select a section of a corridor inside a mall. While it represents data taken from actual pedestrians instead of simulation, they lack the richness of human interaction that comes from an open space that puts minimal restriction on the flow of the crowd. Kim et al. \\cite{kim_socially_2016} take a different approach and use a layered control architecture, each responsible for a specific part of the navigation. It is unclear as to how much the different control modules interfere in each other's decision and how this affects the overall performance of the method. For example, in an overcrowded environment if the collision detector module keeps over ridding control from the the local planner, then what percentage of the resulting trajectory will be the output of the collision-avoidance module compared to that of the IRL planner.\n\\par\nGiven the nature of the task, IRL based methods seem to be a promising avenue to explore. But the problem of social navigation is far from solved and many issues still need addressing. IRL methods are highly dependent on the design of the feature representation used in the algorithm, and a lot of time and effort are needed towards optimizing a set of features that would perform well. Moreover, for most of the existing work, not a lot has been discussed about the generalization of the agent. Most of the experiments are either conducted in a relatively simple environment, like a narrow hallway, or address some specific aspect of crowd navigation like negotiating intersections.\n%\\begin{comment}\n%\\textbf{Collection of expert trajectory might be expensive}\n%\\textbf{The generalization of the method is not that great for now}\n%\\textbf{The dependence of IRL on feature engineering: IRL methods are highly dependent on the design of the feature representation used in the algorithm, and a lot of time and effort are needed towards optimizing a set of features that would perform well.}\n%\n%The primary advantage of IRL over the other methods discussed, both model-based and data-driven methods, is that there is no need to specify a handcrafted reward function built to induce certain kinds of behavior within the agent. Most of the current work in this domain primarily focuses on capturing the expert's behavior, thus encapsulating the 'naturalness' in the movements during navigation.\n%Disadvantages:\n%Comment of IRL and feature engineering. \n%Getting expert demonstrations are more expensive compared to RL.\n%Hard to generalize. \n%\\end{comment}", "meta": {"hexsha": "b600db77c0703b96b7a6fcc46f731ad54aaf3e46", "size": 17401, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "LaTeX-Thesis-Template/base/chapter/chapter3.tex", "max_stars_repo_name": "ranok92/my_masters_thesis", "max_stars_repo_head_hexsha": "5a66e039b5702ff8045bd3f635572ada1d4482ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-17T08:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-17T08:30:52.000Z", "max_issues_repo_path": "LaTeX-Thesis-Template/base/chapter/chapter3.tex", "max_issues_repo_name": "ranok92/my_masters_thesis", "max_issues_repo_head_hexsha": "5a66e039b5702ff8045bd3f635572ada1d4482ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LaTeX-Thesis-Template/base/chapter/chapter3.tex", "max_forks_repo_name": "ranok92/my_masters_thesis", "max_forks_repo_head_hexsha": "5a66e039b5702ff8045bd3f635572ada1d4482ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 125.1870503597, "max_line_length": 1245, "alphanum_fraction": 0.7806447905, "num_tokens": 4069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.3305260048633077}}
{"text": "\\subsection{Principle of LIGO}\n\nWhen the gravitational wave reach us, without a doubt, they are only very weak perturbations on our local flat space. Be that as it may, they will provide information about the strong-field regions where they began. it will additionally permit us to decide the wave properties of the gravitational radiation—for ex-sufficient, their spread speed and polarization states \\cite{barish1999ligo}. The essential construction of LIGO's interferometers differs a little from the interferometer that Michelson planned more than 125 years prior, however for certain additional highlights. The visible pattern occurring where the coherent waves intersect is simply an \"interference\" pattern.\\cite{collaboration2015advanced}\n\n\\subsubsection{Interference Pattern}\n\nIn  nature,  the  peaks  and  troughs  of  one  wave cannot absolutely  meet  the  peaks or  troughs  of  another  wave. Regardless  of  how in-sync they are once they merge, the peak of the wave coming out from the interference always equals the sum of the heights of the merging waves on every point wherever they are physically interacting. What  dictates how  well-aligned  the  beams are once  they  merge  is  the path length  they travel before merging. So the core principle of LIGO is interference of light. When the path difference between two light wave is equal to integral multiple of wavelength, then constructive interference occurs where the resultant light will have maximum brightness. And if the path difference is equal to half-integral multiple of wavelength, then destructive interference occurs and resultant light will have minimum brightness. \\\\\n\nIf the beams travel precisely the same distance, their light waves will be absolutely aligned such that they lead to total destructive interference (LIGO is designed to get total destructive interference if no gravitational waves are detected).  But if the lasers don’t travel identical distances, their light waves are not any longer in synchronize as they merge, which implies no light, a bit light, or a light as bright because the original laser beam reaches the photodetector.  And if the arms are changing length over time, a flicker appears as the beams suffer a variety of interference. This time difference is manifested within the interference pattern once the two laser beams superimpose on the path to the photodetector, which can quantify stage movements to ten-billionths of an interference fringe.\\cite{barish1999ligo}\\\\\n\n\\begin{figure}[htpb]\n    \\centering\n    \\includegraphics[scale=0.585]{images.tex/interference.jpg}\n    \\caption{Interference. Source :- \\href{https://www.tulane.edu/~sanelson/eens211/interference_of_light.htm}{Interference Phenomena by Prof. Stephen A. Nelson}}\n\\end{figure}\n\n\\subsubsection{Differential mode of vibration}\n\nThe gravitational waves result in the space to stretch in a direction, at the same time,  compress in a direction perpendicular to it. In LIGO, this results in one arm getting longer whereas the opposite gets shorter, then the other way around, back and forth as long because the wave is passing.  The technical term for this motion is “Differential Arm” motion, or differential displacement, since the arms are at the same time are differing in lengths in opposing ways in which, or deferentially. So because the lengths of the arms differ, thus too will the total path traveled by every laser beam.\n\n\\begin{figure}[h]\n    \\centering\n    \\includegraphics[scale=0.52]{images.tex/Interferometer.jpg}\n    \\caption{Michelson interferometer.\\; Source :- \\href{https://www.sciencenews.org/article/trio-wins-physics-nobel-prize-gravitational-wave-detection}{Sciencenews.org}}\n\\end{figure}\n\nSo because the lengths of the arms change, so too does the space traveled by each beam . A beam travelling in the shorter arm will return to the beam splitter before the beam which is ravelling in the extended arm, then things switches because the arms oscillate between being longer and shorter. Arriving at different times, then the LASER does not meet nicely when recombined at the beam splitter. Instead, they shift in and out of alignment or \"phase\" as they merge. Unlike optical or radio telescopes, LIGO doesn't see electromagnetic waves. It doesn't need to because gravitational waves aren't a part of the spectrum. In fact, electromagnetic wave is so unimportant to LIGO that its detector components are completely isolated and sheltered from the surface world.\n\n\\pagebreak\n", "meta": {"hexsha": "5dc3f76211a1f787fb9e285a358c63026b62b939", "size": 4485, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "gw-physics-and-ligo/8 LIGO.tex/8.1 Princple.tex", "max_stars_repo_name": "Ashwin185/review-papers-2021", "max_stars_repo_head_hexsha": "c24553d1422160d8f537c04c4c11717478d504a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gw-physics-and-ligo/8 LIGO.tex/8.1 Princple.tex", "max_issues_repo_name": "Ashwin185/review-papers-2021", "max_issues_repo_head_hexsha": "c24553d1422160d8f537c04c4c11717478d504a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gw-physics-and-ligo/8 LIGO.tex/8.1 Princple.tex", "max_forks_repo_name": "Ashwin185/review-papers-2021", "max_forks_repo_head_hexsha": "c24553d1422160d8f537c04c4c11717478d504a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 149.5, "max_line_length": 870, "alphanum_fraction": 0.8040133779, "num_tokens": 960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073802837477, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.33046814016906223}}
{"text": "\\documentclass{Rinton-P9x6}\n%\\usepackage{showlabels}\n\\usepackage{graphics}\n%\\usepackage{fullpage}\n\\usepackage{amssymb}\n\\usepackage{amsfonts}\n\\usepackage{amsmath}\n\\usepackage[mathscr]{eucal}\n\n\\newtheorem{theorem}{Theorem}[section]\n\\newtheorem{lemma}[theorem]{Lemma}\n\\newtheorem{conjecture}[theorem]{Conjecture}\n\\newtheorem{fact}[theorem]{Fact}\n\\newtheorem{corollary}[theorem]{Corollary}\n\\newtheorem{claim}[theorem]{Claim}\n\\newtheorem{proposition}[theorem]{Proposition}\n\\newtheorem{observation}[theorem]{Observation}\n\\newtheorem{definition}[theorem]{Definition}\n\\newtheorem{problem}[theorem]{Problem}\n\\newtheorem{remark}[theorem]{Remark}\n\\newcommand{\\newblock}[1]{\\begingroup #1\\endgroup}\n\\newcommand{\\color}[2][]{}\n\\newcommand{\\floor}[1]{\\ensuremath{\\left\\lfloor{#1}\\right\\rfloor}}\n\\newcommand {\\ket} [1] {\\ensuremath \\left\\vert#1\\ensuremath \\right\\rangle}\n\\newcommand {\\bra} [1] {\\ensuremath \\left\\langle#1\\ensuremath \\right\\vert}\n\\newcommand {\\braket} [2]\n{\\ensuremath \\left\\langle#1\\ensuremath\\,{\\vert}\\,{#2}\\ensuremath \\right\\rangle}\n\\newcommand {\\norm} [1] {\\ensuremath \\left\\Vert\\,#1\\,\\ensuremath\\right\\Vert}\n\\newcommand {\\abs} [1] {\\ensuremath\\left\\vert \\ #1\\ensuremath\\ \\right\\vert}\n\\newcommand {\\card} [1] {\\ensuremath{\\vert }#1\\ensuremath{\\vert}}\n\\newcommand{\\Prob}[1]{\\ensuremath{Prob[\\ }#1\\ensuremath{\\ ]}}\n\\newcommand {\\proof}{{\\bf Proof:\\newline \\indent}}\n\\newcommand{\\F}{\\ensuremath{\\mathbb{F}}}\n\\newcommand{\\GF}[2][]{{\\ensuremath{\\mathbb{F}_{#2}^{#1}}}}\n\\newcommand{\\BAD}{\\ensuremath{\\rm BAD}}\n%\\newcommand{\\dim}{\\ensuremath{\\rm dim}}\n\\newcommand{\\GL}[2][2]{\\ensuremath{GL_{#2}(\\mathbb{F}_{#1})}}\n\\newcommand{\\GLnq}{\\GL[q]{m}}\n\n\\newcommand{\\fc}[1]{\\begin{center}\\epsfig{file=#1}\\end{center}}\n\n\\newcommand{\\bproof}{\\noindent{\\it Proof}}\n\\newcommand{\\cproof}{\\noindent{\\it Proof of Claim}}\n\\newcommand{\\eproof}{\\hspace*{\\fill}$\\rule{2mm}{2mm}$~~~~~\\bigskip}\n\\renewenvironment{proof}{\\bproof. }{\\eproof}\n\\newenvironment{psketch}{\\bproof~{\\it Sketch}. }{\\eproof}\n\\newenvironment{claimproof}{\\cproof. }{\\hspace*{\\fill}\\vspace{5mm}}\n\n\\newcommand{\\Tr}{\\mbox{\\it Tr}}\n\n\\newcommand{\\Ints}{{\\mathbb{Z}}}\n\n\\renewcommand{\\bold}[1]{{\\bf #1}}\n\n\\renewcommand{\\a}{{\\bf a}}\n\\renewcommand{\\b}{{\\bf b}}\n\\renewcommand{\\c}{{\\bf c}}\n\\renewcommand{\\d}{{\\bf d}}\n\\newcommand{\\e}{{\\bf e}}\n\\newcommand{\\x}{{\\bf x}}\n\\renewcommand{\\v}{{\\bf v}}\n\\renewcommand{\\u}{{\\bf u}}\n\\newcommand{\\y}{{\\bf y}}\n\\renewcommand{\\r}{{\\bf r}}\n\\newcommand{\\om}{{\\omega}}\n\\newcommand{\\w}{\\tilde{\\omega}}\n\\newcommand{\\bw}{\\ensuremath{\\mbox{\\boldmath $\\omega$}}}\n\\newcommand{\\balpha}{\\ensuremath{\\mbox{\\boldmath $\\alpha$}}}\n\\newcommand{\\bbeta}{\\ensuremath{\\mbox{\\boldmath $\\beta$}}}\n\\newcommand{\\bchi}{\\ensuremath{\\mbox{\\boldmath $\\chi$}}}\n\\newcommand{\\sbalpha}{\\ensuremath{\\mbox{\\scriptsize\\boldmath $\\alpha$}}}\n\\newcommand{\\sbbeta}{\\ensuremath{\\mbox{\\scriptsize\\boldmath $\\beta$}}}\n\\newcommand{\\sbchi}{\\ensuremath{\\mbox{\\scriptsize\\boldmath $\\chi$}}}\n\n\\newcommand{\\brac}[2]{{\\ensuremath{[[{#1}]]_{{#2}}}}}\n\n\\newcommand{\\wt}{{\\it wt}}\n\\newcommand{\\TA}{{\\tt{TA}}}\n\\newcommand{\\Hi}{{\\ensuremath{\\mathcal{H}}}}\n\\newcommand{\\A}{{\\ensuremath{\\mathcal{A}}}}\n\\newcommand{\\B}{{\\ensuremath{\\mathcal{B}}}}\n\\newcommand{\\C}{{\\ensuremath{\\mathcal{C}}}}\n\\newcommand{\\complex}{{\\ensuremath{\\mathbb{C}}}}\n\\newcommand{\\V}{{\\ensuremath{\\mathcal{V}}}}\n\\renewcommand{\\S}{{\\ensuremath{\\mathcal{S}}}}\n\\newcommand{\\cS}{{\\ensuremath{\\overline{\\mathcal{S}}}}}\n\\newcommand{\\Hin}{{\\ensuremath{\\mathcal{H}^{\\otimes^n}}}}\n\\newcommand{\\HinA}{{\\ensuremath{{L^2(A)}^{\\otimes^n}}}}\n\\newcommand{\\E}{{\\ensuremath{\\mathcal{E}}}}\n\\newcommand{\\D}{{\\ensuremath{\\mathcal{D}}}}\n\\newcommand{\\Graph}[1]{\\ensuremath{\\mathcal{G}_{#1}}}\n\\newcommand{\\Tour}[1]{\\ensuremath{\\mathcal{T}_{#1}}}\n\\newcommand{\\Sym}[1]{{\\rm Sym(}#1{\\bf )}}\n\\newcommand{\\sym}[1]{\\ensuremath{\\bf S_#1}}\n\\newcommand {\\Aut}[1]{{\\rm Aut}({#1})}\n\\newcommand{\\lexleast}{{\\rm{lex{-}least}}}\n\\newcommand {\\iso}{\\ensuremath{\\cong} }\n\\newcommand {\\niso}{\\ensuremath{\\ncong} }\n\\renewcommand{\\th}[1]{\\ensuremath{#1^{th}}}\n\n\\renewcommand{\\angle}[1]{\\langle #1\\rangle}\n\\newcommand{\\biangle}[1]{\\langle\\langle #1\\rangle\\rangle}\n\n\\title{{\\bf Non-Stabilizer Quantum Codes from Abelian Subgroups of the\n    Error Group}}\n\n\n\\author{\nV.~Arvind, Piyush P Kurur, and K.~R.~Parthasarathy\n}\n\\address{\n        Institute of Mathematical Sciences, C.I.T Campus\\\\ \n        Chennai 600113, India\\\\\n        email: {\\tt\\{arvind,krp,ppk\\}@imsc.res.in}\n}\n\n\\begin{document}\n\n\\maketitle\n\n\\abstracts{This paper is motivated by the computer-generated nonadditive code\n  described in Rains et al\\cite{rains97nonadditive}. We describe a theory of\n  non-stabilizer codes of which the nonadditive code of Rains et al is\n  an example. Furthermore, we give a general strategy of constructing\n  good nonstabilizer codes from good stabilizer codes and give some\n  explicit constructions and asymptotically good nonstabilizer codes.\n  Like in the case of stabilizer codes, we can design fairly efficient\n  encoding and decoding procedures.}\n\n\\section{Introduction}\n\nLet $A$ be a finite abelian group with operation denoted by $+$ and\nnull element denoted by 0. We identify $A$ with the alphabet of\nsymbols transmitted on a classical communication channel. Consider the\n$n$-fold cartesian product $A^n$ of copies of $A$. Elements of $A^n$\nare called \\emph{words} of \\emph{length} $n$. A commonly used group is\n$\\{0,1\\}$ with addition modulo 2.  Let $\\hat{A}$ denote the character\ngroup of $A$, the multiplicative group of all homomorphisms {from} $A$\ninto the multiplicative group of complex numbers of modulus unity. For\n$\\a=(a_1,a_2,\\ldots,a_n)^T\\in A^n$ we define its \\emph{weight} $w(\\bold{a})$\nto be $\\#\\{i\\mid a_i\\neq 0\\}$.  We say that a subgroup $\\C_n$ of $A^n$\nis a \\emph{$t$-error correcting group code} if for every non-zero\nelement $\\bold{x}=(x_1,x_2,\\ldots,x_n)^T$ in $\\C_n$, $w(\\bold{x})\\geq\n2t+1$.  In other words, if messages transmitted through a noisy\nchannel are encoded into words {from} $\\C_n$ and during transmission\nof a word errors at the output occur in at most $t$ positions, then\nthe message can be decoded without any error. There is a vast\nliterature on the construction of $t$-error correcting group codes and\nthe reader may find an introduction to this subject and pointers to\nliterature in standard texts\\cite{sloan,vLin}.\n\nA broad class of quantum error correcting codes known as stabilizer\ncodes was introduced by Gottesman\\cite{gottes} and Calderbank et\nal\\cite{cald-shor} (also see\nreferences\\cite{kl2,rains97nonadditive,rains}). Rains et\nal\\cite{rains97nonadditive} obtained the first example of a\nnon-stabilizer quantum code of distance 2. Subsequently, an entire\nfamily of non-stabilizer codes of distance 2 was constructed by\nRains\\cite{rains97}. Later, Roychowdhury and Vatan\\cite{vwani98qcqc}\nshowed that there are non-stabilizer codes with different minimum\ndistances and also proved an asymptotic result about the existence of\n$t$-error correcting non-stabilizer codes of good rate. \n\nIn this paper we develop a theory of \\emph{nonstabilizer} codes based\non the Weyl commutation relations. The nonadditive code of Rains et\nal\\cite{rains97nonadditive} is an instance of our theory and we derive\nit directly from the theory. Furthermore, we outline a general\nstrategy of constructing good nonstabilizer codes from good stabilizer\ncodes and give some explicit constructions and asymptotically good\nnonstabilizer codes. For a rich family of nonstabilizer codes, we\npresent elegant and efficient encoding circuits. We also present a\nsimple effective decoding procedure for these nonstabilizer codes.\n\nFirst we introduce some definitions. We choose and fix an\n$M$-dimensional complex Hilbert space $\\Hi$ and consider the unit\nvectors of $\\Hi$ as pure states of a finite level quantum system. If\n$A$ is a finite abelian group with $M$ elements and $\\{e_x\\mid x\\in\nA\\}$ is an orthonormal basis of $\\Hi$ indexed by elements of $A$ we\nexpress it in the Dirac notation as $\\ket{x}=e_x$.  If\n$\\bold{x}=(x_1,x_2,\\ldots,x_n)^T\\in A^n$ is a word of length $n$, we\nwrite\n\\[\n\\ket{\\x}=\\ket{x_1x_2\\ldots x_n}=e_{x_1}\\otimes e_{x_2}\\otimes\\ldots\\otimes e_{x_n}\n\\]\nwhere the right-hand side is a product vector in the $n$-fold tensor\nproduct $\\Hi^{\\otimes^n}$ of $n$ copies of $\\Hi$. Thus, with the\nchosen orthonormal basis, every word $\\x$ in $A^n$ is translated into\na basis state $\\ket{\\x}$ of $\\Hi^{\\otimes^n}$.\n\nA \\emph{quantum code} is a subspace $\\C_n$ of $\\Hi^{\\otimes^n}$. Note\nthat a pure state in $\\Hi^{\\otimes^n}$ described by a unit vector\n$\\ket{\\psi}$ in $\\Hi^{\\otimes^n}$ has density matrix\n$\\ket{\\psi}\\bra{\\psi}$. A density matrix $\\rho$ in $\\Hi^{\\otimes^n}$\nis a non-negative operator of unit trace. In quantum probability, a\nprojection operator $E$ in $\\Hi^{\\otimes^n}$ is interpreted as an\nevent concerning the quantum system and a density matrix $\\rho$ as a\nstate of the quantum system. The probability of the event $E$ in the\nstate $\\rho$ is given by $\\Tr\\rho E$. Messages to be transmitted\nthrough a quantum channel are encoded into pure states in\n$\\Hi^{\\otimes^n}$. When a pure state $\\ket{\\psi}$, or equivalently, a\ndensity matrix $\\ket{\\psi}\\bra{\\psi}$ is transmitted the channel\noutput is hypothesized to be a state of the form\n\\begin{eqnarray}\n\\rho=\\sum_{i}L_i\\ket{\\psi}\\bra{\\psi}L_i^{\\dagger}\\label{eq-1}\n\\end{eqnarray}\nwhere the operators $\\{L_i\\}$ belong to a linear subspace $\\A$ of the\nalgebra of all operators on $\\Hi^{\\otimes^n}$. The operators $\\{L_i\\}$\nmay depend on $\\rho$, but in order to ensure that $\\rho$ is a density\nmatrix it is assumed that $\\bra{\\psi}\\sum_i\nL^{\\dagger}_iL_i\\ket{\\psi}=1$. By the spectral theorem $\\rho$ can\nbe expressed as\n\\[\n\\rho = \\sum_{j}p_j\\ket{\\psi_j}\\bra{\\psi_j}\n\\]\n% $L_i^{\\dagger}$ denotes\n%the adjoint of $L_i$ and $\\sum_i L^{\\dagger}_iL_i=I$. The last\n%condition ensures that the operator $\\rho$ in (\\ref{eq-1}) has unit\n%trace for every unit vector $\\ket{\\psi}$. Thus $\\rho$ is a density\n%matrix and by the spectral theorem can be expressed as\n%\\[\n%\\rho=\\sum_{j}p_j\\ket{\\varphi_j}\\bra{\\varphi}\n%\\]\nwhere $\\psi_j$ is an orthonormal set in $\\Hi^{\\otimes^n}$ and\n$\\{p_j\\}$ is a probability distribution with $p_j>0$ for each $j$.  In\nother words, the output state $\\rho$ is not necessarily pure even\nthough the input state is pure.  The operators $L_i$ are called\n\\emph{error operators} and the linear space $\\A$ {from} which they\ncome is called the \\emph{error space}.\n\nLet $P$ be the projection operator corresponding to a quantum code\n$\\C_n$. The subspace $\\D(P)$ of \\emph{error operators detected} by $P$\nis defined as\n\\[\n\\D(P)=\\{L\\in\\B(\\Hin)\\mid PLP=c.P\\mbox{ for some }c\\in\\complex\\}.\n\\]\n\nIt is evident that there is a complex-valued functional\n$\\phi:\\D(P)\\rightarrow\\complex$ so that we can write $PLP=\\phi(L)P$\nfor all $L\\in\\D(P)$.\n\nA finite family $\\{M_j\\}\\subseteq\\B(\\Hin)$ constitutes a set\nof \\emph{decoding operators} for the code $\\C_n$ and error space $\\A$\nif the following conditions are satisfied.\n\\begin{itemize}\n\\item[(a)] $\\sum_j M^{\\dagger}_jM_j=I$.\n\\item[(b)] For any pure state $\\ket{\\psi} \\in \\C_n$ if the output state\n  $\\rho$ corresponding to $\\ket{\\psi}$ is given by \n$\\rho = \\sum_{i=1}^m L_i\\ket{\\psi}\\bra{\\psi}L_i^\\dagger$, $L_i \\in \\A$ then \n  \\[\n  \\sum_j M_j\\rho M^{\\dagger}_j=\n  \\sum_{i,j}M_jL_i\\ket{\\psi}\\bra{\\psi}L_i^{\\dagger}M_j^{\\dagger}\n  =\\ket{\\psi}\\bra{\\psi}.\n  \\]\n\\end{itemize}\n\nIn this case we say that $\\C_n$ is an \\emph{$\\A$-error correcting\nquantum code}. \n\nWe have the following fundamental theorem of Knill and\nLaflamme\\cite{KL} which characterizes the errors that a quantum code\ncan correct.  It essentially states that errors coming from a family\n$\\A$ of operators can be corrected for a quantum code with projection\n$P$ if and only if\n\\[\n\\{L_1^{\\dag}L_2\\mid L_1, L_2,\\in\\A\\}\\subseteq\\D(P).\n\\]\n\n\\begin{theorem}\\label{kl-theorem}\n  Let $\\A$ be a family of operators in $\\Hin$ and let $\\C_n\\subset\n  \\Hin$ be a quantum code with an orthonormal basis\n  $\\psi_1,\\psi_2,\\ldots,\\psi_d$. Let $P$ be the projection\n  corresponding to the code $\\C_n$. Then $\\C_n$ is an $\\A$-error\n  correcting quantum code if and only if\n\\[\n\\mathcal{A}^\\dag \\mathcal{A} = \\{L_1^{\\dag}L_2\\mid L_1, L_2\\in\\A\\}\\subseteq\\D(P).\n\\]\n\\end{theorem}\n\n\\begin{remark}\n  The proof of the above theorem is constructive and yields the\n  decoding operators in terms of $\\A$ and the basis\n  $\\psi_1,\\ldots,\\psi_d$ of $\\C_n$.\n\\end{remark}\n\nNow we specialize the choice of $\\A$. Consider all unitary operators\nin $\\Hin$ of the form $U=U_1\\otimes U_2\\otimes\\ldots\\otimes U_n$ where\neach $U_i$ is a unitary operator on $\\Hi$ and all but $t$ of the\n$U_i$'s are equal to $I$. Such a $U$ when operating on\n$\\psi=\\psi_1\\otimes\\ldots\\otimes \\psi_n\\in\\Hin$ produces $U\\ket{\\psi}$\nwhich is an $n$-fold tensor product that differs {from} $\\psi$ in at\nmost $t$ places. Denote by $\\A_t$ the linear span of all such unitary\noperators $U$. A quantum code $\\C_n$ is called a \\emph{$t$-error\n  correcting quantum code} if $\\C_n$ is an $\\A_t$-correcting quantum\ncode. \n\n\\section{Quantum Codes and Projections in a Group Algebra}\\label{defs}\n\nLet $(A,+)$ be a finite abelian group of $M$ elements with null\nelement 0. By the fundamental theorem of finite abelian groups, $A$ is\nisomorphic to $\\bigoplus_{i=1}^k\\Ints_{n_i}$ via the isomorphism\n$\\tau$. For every $m$, let $\\om_m=e^{2\\pi i/m}$. Define the\n\\emph{canonical bicharacter} of the group $A$ as the following\ncomplex-valued function on $A\\times A$.\n\\[\n\\biangle{a,b}=\\prod_{j=1}^k \\om_{n_j}^{x_jy_j},\\mbox{ where }\\\\\n\\tau(a)=(x_1,\\ldots,x_k)\\mbox{ and }\\tau(b)=(y_1,\\ldots,y_k).\n\\]\n\nNotice that for all $a,b,c\\in A$ we have\n$\\biangle{a,b}=\\biangle{b,a}$,\n$\\biangle{a+b,c}=\\biangle{a,c}\\biangle{b,c}$, and $\\biangle{a,b}=1$\nfor all $b\\in A$ if and only if $a=0$. Denote by $\\hat{A}$ the\ncharacter group of $A$. For each fixed $a\\in A$, the bicharacter\n$\\biangle{a,b}$, as a function of $b$, is a distinct element $\\chi_a$\nof $\\hat{A}$ and the correspondence $a\\mapsto \\chi_a$ is a group\nisomorphism between $A$ and the multiplicative character group\n$\\hat{A}$.\n\nDenote by $\\Hi$ the $M$-dimensional Hilbert space $L^2(A)$ of all\ncomplex-valued functions on $A$, spanned by $\\{\\ket{x}\\}_{x\\in A}$\n(where the vector $\\ket{x}$ denotes the indicator function $1_x$ of\nthe singleton $\\{x\\}$).  Define the unitary operators $U_{a}$ and\n$V_{a}$ on $\\Hi$ for every $a\\in A$ by\n\\[\nU_a\\ket{x}=\\ket{x+a},\\hspace{2cm} V_{a}\\ket{x}=\\biangle{a,x}\\ket{x}\n\\]\nwhere $x\\in A$. Then we have\n\n\\[\nU_aU_b=U_{a+b}~~~~V_aV_b=V_{a+b},\\mbox{ and }\\\\\n\\biangle{a,b}U_aV_b=V_bU_a\\mbox{~~}\\forall\\mbox{~~} a, b\\in A.\n\\]\n\nThese are the Weyl commutation relations between the unitary operators\n$U_{a}$ and $V_{a}$ on $\\Hi$. The family of operators $\\{U_aV_b\\mid a,\nb\\in A\\}$ is irreducible. \n\nThe canonical bicharacter on $A$ gives rise to the following\nbicharacter on $A^n$.  For two elements $\\a=(a_1,\\ldots,a_n)$ and\n$\\b=(b_1,\\ldots,b_n)$ in $A^n$, $\\biangle{\\a,\\b}$ is defined as\n\\[\n\\biangle{\\a,\\b}=\\prod_{i=1}^n\\biangle{a_i,b_i}.\n\\]\n\nPut $U_{\\a}=U_{a_1}\\otimes\\ldots\\otimes U_{a_n}$ and\n$V_{\\b}=V_{b_1}\\otimes\\ldots\\otimes V_{b_n}$. Then $\\{U_{\\a}V_{\\b}\\mid\n\\a, \\b\\in A^n\\}$ is again an irreducible family of unitary operators\nsuch that $U_{\\a}U_{\\b}=U_{\\a+\\b}$ and $V_{\\a}V_{\\b}=V_{\\a+\\b}$, and\nthey satisfy the Weyl commutation relations\n\n\\[\n\\biangle{\\a,\\b}U_{\\a}V_{\\b}=V_{\\b}U_{\\a}\\mbox{~~}\\forall\\mbox{~~}\n\\a, \\b\\in A^n.\n\\]\n\nIn the Hilbert space $\\B(\\Hin)$ of all linear operators on $\\Hin$ with\nthe scalar product $\\braket{X}{Y}=\\Tr X^{\\dagger}Y$ the set\n$\\{M^{-n/2}U_{\\a}V_{\\b}\\mid \\a, \\b\\in A^n\\}$ is an orthonormal basis.\nIn particular\n\n\\[\n\\Tr~U_{\\a}V_{\\b}=\n\\left\\{\n\\begin{array}{cc}\n    0&\\textrm{if } (\\a,\\b) \\neq (0,0), \\\\\n    M^n&\\textrm{otherwise,}\n\\end{array}\n\\right.\n\\]\n\nThe weight $\\wt(\\a,\\b)$ of a pair $(\\a,\\b)\\in A^n\\times A^n$ is\ndefined to be $\\#\\{i\\mid 1\\leq i\\leq n, (a_i,b_i)\\neq (0,0)\\}$, where\n$\\a=(a_1,a_2,\\ldots,a_n)$ and $\\b=(b_1,\\ldots,b_n)$. The\nirreducibility of $\\{U_{\\a}V_{\\b}\\mid \\a, \\b\\in A^n\\}$ implies that\n$\\{U_{\\a}V_{\\b}\\mid \\a, \\b\\in A^n, \\wt(\\a,\\b)\\leq t\\}$ spans $\\A_t$.\nAs a result, the Knill-Laflamme theorem for $\\A_t$-correcting quantum\ncodes takes the following form which is easy to derive from\nTheorem~\\ref{kl-theorem}.\n\n\\begin{theorem}\\label{kl-2}\n  $\\C_n\\subset L^2(A)^{\\otimes^n}$ is a $t$-error correcting quantum\n  code if and only if \n\\[\n\\{U_{\\a}V_{\\b}\\mid \\a, \\b\\in A^n, \\wt(\\a,\\b)\\leq 2t\\}\\subseteq\\D(P),\n\\]\nwhere $P$ is the projection corresponding to $\\C_n$.\n\\end{theorem}\n\nLet $N$ be the least positive integer such that $Na = 0$ for all $a\n\\in A$. Let $\\om=e^{2\\pi i/N}$, We define the error group $\\E$ as\nfollows.\n\n\\begin{definition}\n  The \\emph{error group} $\\E$ is defined as\n\n\\[ \n\\E = \\{\\om^iU_{\\a}V_{\\b}\\mid 0\\leq i\\leq N-1,\\a, \\b \\in A^n\\},\n\\]\nwith the group operation defined by\n\n\\[ \n\\om^iU_{\\a}V_{\\b}\\om^jU_{\\c}V_{\\d}=\\om^{i+j}\\biangle{\\b,\\c}U_{\\a+\\c}V_{\\b+\\d}.\n\\]\n\n\\end{definition}\n\nLet $\\S \\leq \\E$ be a subgroup of the error group. In the theory of\nstabilizer codes we are interested in subspaces of\n$L^2(A)^{\\otimes^n}$ that are left invariant under the action of $\\S$.\nIt turns out that the invariant subspace is nontrivial if and only if\n$\\S$ is abelian with the property that $\\omega^i I \\not \\in \\S$ for\nall $1 \\leq i \\leq N -1$.\n\n\\begin{definition}\\label{gottes}\n  An abelian subgroup $\\S$ of $\\E$ is said to be a \\emph{Gottesman\n    subgroup} of $\\E$ if $\\omega^i I \\not \\in \\S$ for all $1 \\leq i\n  \\leq N -1$. The \\emph{closure} of a Gottesman subgroup $\\S$ is the\n  abelian subgroup $\\cS$ of $\\E$ defined as\n\\[\n\\cS=\\{\\om^i g\\mid g\\in\\S,\\ 0\\leq i \\leq N -1\\}.\n\\]\n\\end{definition}\n\n\\begin{remark}\n  For any Gottesman subgroup $\\S$ of the error group $\\E$ the element\n  $\\omega^i U_{\\a} V_{\\b}\\in\\S$ for at most one $i: 0\\leq i\\leq N-1$.\n\\end{remark}\n\nLet $\\mathbb{C}[\\S]$ be the group algebra of formal sums $\\sum_{s \\in\n  \\S} T_s s$, $T_s \\in \\mathbb{C}$ where the sum and product\n(convolution) are defined as follows\n\n\\[\nT+T'=\\sum_{s \\in \\E} (T_s+T'_s) s,\n\\]\n\n\\[\nT'*T''=T,\\mbox{\\rm where }T_s=\\sum_{g\\in\\E} T'_g T''_{g^{-1}s}.\n\\]\n\nSince any Gottesman subgroup $\\S$ is a set of linearly independent\nelements of $\\B(\\Hin)$, the identity map is a natural injective linear\nembedding from $\\mathbb{C}[\\S]$ into $\\B(\\Hin)$. In other words,\n$\\mathbb{C}[\\S]$ is a subalgebra of $\\B(\\Hin)$ under operator addition\nand operator multiplication, where the convolution operation ``$*$''\nin $\\mathbb{C}[\\S]$ coincides with operator multiplication.\n\nEvery subspace (i.e.\\ quantum code) in $\\Hin$ is defined by its\ncorresponding projection operator in $\\B(\\Hin)$. In this paper we are\ninterested in the projection operators in $\\mathbb{C}[\\S]$ for a\nGottesman subgroup $\\S$ of $\\E$. In the following easy proposition we\ncharacterize the elements in $\\mathbb{C}[\\S]$ which are projection\noperators in $\\Hin$. Then our goal will be to seek for projections\nwhose range is a good $t$-error correcting quantum code.\n\n\\begin{proposition}\n  The element $T\\in\\mathbb{C}[\\S]$ is a projection operator on $\\Hin$ if and\n  only if $\\overline{T_s}=T_{s^{-1}}$ and $T*T=T$.\n\\end{proposition}\n\nWe use the Fourier transform over $\\mathbb{C}[\\S]$ and the above proposition to\ndescribe projection operators in $\\mathbb{C}[\\S]$. We recall the Fourier\ntransform and some of its properties.\n\nLet $\\S$ be an abelian group and let $\\hat{\\S}$ denote the character\ngroup of $\\S$. For each $s\\in \\S$ we can associate the element\n$\\sum\\alpha_g g$ in the algebra $\\mathbb{C}[\\S]$ where, $\\alpha_s = 1$ and\n$\\alpha_g=0$ for $g\\neq s\\in\\S$. Similarly, to $\\chi\\in\\hat{S}$ we\nassociate the element $\\sum\\chi(g)g$ of $\\mathbb{C}[\\S]$. Fix an isomorphism\n$s \\mapsto \\chi_s$ between the groups $\\S$ and $\\hat{\\S}$. The Fourier\ntransform over $\\mathbb{C}[\\S]$ is now defined as follows.\n\n\\begin{definition}[Fourier Transform]\n  The linear transformation that maps $s \\in \\mathbb{C}[\\S]$ to $\\chi_s \\in\n  \\mathbb{C}[\\S]$ is called the \\emph{Fourier transform} over $\\mathbb{C}[\\S]$. The\n  Fourier transform $\\hat{T}$ of $T$ in $\\mathbb{C}[\\S]$ is given by the\n  formula\n  \\[ \\hat{T}_u = \\sum_{s \\in \\S} \\chi_u(s) T_s.\\]\n\\end{definition}\n\nThe \\emph{inverse Fourier transform} is given by the following\nformula:\n\n\\[\nT_s= \\frac{1}{\\#\\S} \\sum_{u \\in \\S} \\overline{\\chi}_u(s) \\hat{T}_u .\n\\]\n\nLet $TT'$ denote the component-wise product of $T, T'\\in\\mathbb{C}[\\S]$. I.e.\n\n\\[\nTT' =\\sum_{s\\in\\S}T_sT'_s s.\n\\]\n\nWe now recall some useful properties of the Fourier transform.\n\n\\begin{eqnarray}\n\\nonumber\n  \\widehat{{T_1*T_2}} &=& \\hat{T_1}\\hat{T_2},~~~~~~ T_1, T_2\\in\\mathbb{C}[\\S]. \\\\\n\\nonumber\n  \\widehat{g T} &=& \\chi_g \\hat{T},~~~~~~ g\\in\\S,~~~ T\\in\\mathbb{C}[\\S].\n\\end{eqnarray}\n\nWe can characterize projection operators in $\\mathbb{C}[\\S]$ using the\nFourier transform.\n\n\\begin{theorem}\\label{nstab-code}\n  An element $T \\in \\mathbb{C}[\\S]$ is a projection (and hence a code) iff\n  $\\hat{T} = 1_B = \\sum_{g \\in B} g$ for some subset $B$ of $\\S$.\n\\end{theorem}\n\n\\begin{proof}\n  $T$ is a projection iff $T*T = T$ and $T^\\dagger = T$. On taking\n  Fourier transforms on both sides of the equation $T*T = T$ we get\n\\[\n\\hat{T} \\hat{T} = \\hat{T}.\n\\]\n\nThis implies $\\hat{T}_s^2=\\hat{T}_s$ for every $s\\in\\S$. Thus,\n$\\hat{T}_s\\in\\{0,1\\}$ for every $s\\in\\S$ which gives the desired result.\n\nConversely, note that if $\\hat{T} = 1_B$ then by inverse Fourier\ntransform we get\n\n\\[\nT = \\frac{1}{\\#\\S}\\sum_{s \\in \\S} \\sum_{u \\in B} \\overline{\\chi_u}(s) s.\n\\] \n\n{From} the above equation it is clear that the condition $T^\\dagger = T$\nis automatically satisfied.\n\\end{proof}\n\n{From} Theorem~\\ref{nstab-code} it is clear that the code defined by a\nprojection $T$ in $\\mathbb{C}[\\S]$ is completely specified by the subset $B$\nof $\\S$. We will call $B$ the {\\em Fourier description} of the quantum\ncode and denote the corresponding projection by $P(B)$. \n\nNext, we give a formula for the dimension of a quantum code defined by\na projection $T$ in $\\mathbb{C}[\\S]$.\n\n\\begin{lemma}{\\label{dimlemma}}\n  Let $\\C_n\\subseteq\\Hin$ be a quantum code defined by a projection\n  $T$ in $\\mathbb{C}[\\S]$ with Fourier description $B \\subseteq \\S$. Then\n  $\\C_n\\neq 0$ if and only if $\\om^iI\\not\\in\\S$ for $i: 1\\leq i\\leq\n  N-1$ (i.e. $\\S$ is a Gottesman subgroup), and if $\\C_n\\neq 0$ the\n  dimension of the code $\\C_n$ is given by\n\\[ \n\\dim(\\C_n) =\\frac{\\#A^n \\#B}{\\#\\S}.\n\\]\n\\end{lemma}\n\n\\begin{proof}\n  If $B$ is the Fourier description of the code then the projection\n  corresponding to the code is given by \\[ P =\\frac{1}{\\#\\S} \\sum_{s\n    \\in \\S} \\sum_{u \\in B} \\overline{\\chi_u}(s) s. \\] The dimension is\n  given by $\\Tr(P)$.  Observe that $\\Tr(U_{\\a}V_{\\b}) = 0$ if\n  $U_{\\a}V_{\\b}\\neq I$, and $\\Tr(\\om^iI)=\\om^i\\#A^n$, for\n  $\\om^iI\\in\\S$. Now, since $\\om$ is a nontrivial root of unity,\n  $\\sum_{\\om^iI\\in\\S} \\om^i \\# A =0 $ if $\\om^iI\\in\\S$ for some $i$\n  such that $1\\leq i\\leq N-1$. Thus, we have $\\Tr(P)=0$ if\n  $\\om^iI\\in\\S$ for some $i:~1\\leq i\\leq N-1$, and otherwise\n  $\\Tr(P)=\\frac{\\#B}{\\#\\S}\\#A^n$. This proves the lemma.\n\\end{proof}\n\n\\begin{proposition}\n  Let $g = \\omega^i U_{\\a} V_\\b$ and $h = \\omega^j U_\\c V_\\d$ be\n  elements in the error group $\\E$. Then\n\n  \\[\n  ghg^{-1}h^{-1} = \\gamma(g,h) I\n  \\]\n  where $\\gamma(g,h) = \\biangle{b,c} \\overline{\\biangle{a,d}}$. In particular\n  we have \n\n  \\[\n  \\gamma(g_1g_2,h) = \\gamma(g_1,h)\\gamma(g_2,h)\n  \\]\n\n  \\[\n  \\gamma(g,h_1 h_2) = \\gamma(g,h_1) \\gamma(g,h_2)\n  \\]\n  and\n  \\[\n  \\gamma(g,h) = \\overline{\\gamma(h,g)}\n  \\]\n\\end{proposition}\n\\begin{proof} \n  Straightforward from the Weyl commutation relations.\n\\end{proof}\n\\begin{remark}\\label{gammagremark}\n  When $h \\in \\E$ is fixed and $s$ varies in $\\S$ the map $s \\mapsto\n  \\gamma(s,h)$ is a character of $\\S$ which we will denote by\n  $\\gamma_h$.\n\\end{remark}\n\nLet $\\C_n\\subseteq\\Hin$ be a code with Fourier description $B$. In the\nnext theorem we derive a condition on $B$ such that $\\C_n$ is a\n$t$-error correcting quantum code. We introduce a convenient notation:\nFor $g=\\om^iU_{\\a}V_{\\b}$ in the error group $\\E$, let $\\wt(g)$ denote\nthe number $\\wt(\\a,\\b)$.\n\n\\begin{theorem}{\\label{distdtheorem}}\n  A quantum code $\\C_n\\subseteq\\Hin$ with Fourier description $B$ is\n  $t$-error correcting iff the following two conditions hold.\n  \n\\begin{enumerate}\n  \n\\item \nFor each $g \\in \\S$ such that $\\wt(g)\\leq 2t$\n\\[\n\\chi_g( u_1^{-1} u_2) = 1 \\textrm{ for all } u_1,u_2 \\in B. \n\\]\n(i.e. every $u \\in B$ is in the same coset of the kernel of $\\chi_g$.)\n\n\\item \nFor each $g \\in \\E \\setminus \\S$ such that $\\wt(g)\\leq 2t$, and for \nevery $u \\in B^{-1} B$ we have\n\\[\n\\sum_{s \\in \\S} \\gamma_g(s)\\chi_u(s) = 0.\n\\]\n(i.e.\\ the character $\\gamma_g$ is different from $\\chi_{u^{-1}}$ for every\n$u\\in B^{-1} B$.)\n\n\\end{enumerate}\n\\end{theorem}\n\n\\begin{proof}\n  \n  Let $\\C_n$ be a $t$-error correcting code and let $T = \\sum_{s\\in\\S}\n  T_s s$ be the corresponding projection. Recall that if $B$ is the\n  Fourier description for the code then\n\\[\nT_s = \\frac{1}{\\# \\S} \\sum_{u \\in B} \\overline{\\chi}_u(s).\n\\]\n  \nBy Theorem~\\ref{kl-theorem}, $\\C_n$ is $t$-error correcting if and\nonly if there is a scalar-valued function $\\phi$ such that for every\n$g\\in\\E$ with $\\wt(g)\\leq 2t$\n\\[\nTgT = \\phi(g) T.\n\\]\n\nThis is equivalent to the following condition.\n\n\\begin{eqnarray}\\label{eq-3}\n\\left( \\sum_{s_1 \\in \\S} T_{s_1} s_1 \\right) g \n\\left( \\sum_{s_2 \\in \\S} T_{s_2} s_2 \\right) = \\phi(g)\\sum_{s\\in\\S}T_s s.\n\\end{eqnarray}\n\n{{\\em Case 1}~~ $g \\in \\S$ :}\n\nIn this case Equation~\\ref{eq-3} yields $gT*T =\\phi(g)T$. Taking Fourier\ntransform on both sides we get \n\n\\[ \\chi_g \\hat{T} \\hat{T} = \\phi(g)\\hat{T}.\\] \n\nSince $\\hat{T} = 1_B$, we have $\\chi_g(u) = \\phi(g)$ for all $u \\in\nB$.  Thus, $\\chi_g$ is constant on $B$ for every $g \\in \\S$ such that\n$\\wt(g)\\leq 2t$. This is true precisely when $B$ is contained in some\ncoset of the kernel of $\\chi_g$.\n\n{{\\em Case 2}~~ $g\\not\\in\\S$ :}\n\nIn this case the Knill-Laflamme condition takes the following form\n\n\\[\n\\sum_{s\\in\\S}\n\\sum_{s_1s_2 = s} T_{s_1}T_{s_2} \\gamma(s_1,g) g s_1 s_2 = \\phi(g)\n\\sum_{s \\in \\S} T_s s.\n\\]\n\nSince the operators on the two sides of the above equation have\ndisjoint support, each side of the equation vanishes. Consequently,\n$\\phi(g) = 0$ and for all $s \\in \\S$\n\\[\n\\sum_{s_1s_2 =s} T_{s_1} T_{s_2} \\gamma(s_1,g) = 0.\n\\] \n\nThis yields\n\n\\[\n\\sum_{s_1s_2 =s} \\left(\\sum_{u_1 \\in B}\\overline{\\chi}_{u_1}(s_1)\n\\right) \\left(\\sum_{u_2 \\in B}{\\overline{\\chi}_{u_2}}(s_2)\\right)\n\\gamma(s_1,g) = 0.\n\\]\n\nOn simplification we get\n\\[\n\\sum_{u_1,u_2 \\in B} \\sum_{s_1 s_2 = s } \\gamma_g(s_1)\n\\overline{\\chi}_{u_1}(s_1) \\overline{\\chi}_{u_2}(s_2) = 0,\n\\]\nwhich gives \n\n\\begin{equation}\\label{eqn1}\n\\sum_{u_1,u_2 \\in B} \\overline{\\chi}_{u_2}(s) \\sum_{s_1 \\in \\S}\n(\\gamma_g\\chi_{u_2} \\overline{\\chi}_{u_1})(s_1) = 0.\n\\end{equation}\n \nNote that the inner summation in equation~\\ref{eqn1} is summing up of\na character of $\\S$, namely, $\\gamma_g \\chi_{u_1^{-1}} \\chi_{u_2}$,\nover the whole group $\\S$. Therefore, the inner summation yields\neither $0$ or $\\# \\S$. Hence, the necessary and sufficient condition\nfor equation~\\ref{eqn1} to hold is\n\\[\n\\sum_{s \\in \\S}\\gamma_g(s)\\chi_u(s) = 0~~~~~\\forall u \\in B^{-1}B.\n\\]\n\n\\end{proof}\n\n\\begin{remark}\n  If the Fourier description of a code, $B$, is a subgroup of $\\S$\n  then the code is actually a stabilizer code with stabilizer group\n  $B^\\perp$, where $B^\\perp$ is the annihilator of $B$ in $\\S$ defined\n  by\n  \\[\n  B^\\perp = \\{ a \\in \\S : \\forall b \\in B\\ \\biangle{a,b} = 0 \\}.\n  \\]\n  In particular if we set $B=\\{I\\}$, where $I$ is the identity\n  element, the code $\\C_n$ with Fourier description $B$ is the\n  stabilizer quantum code:\n  \\[\n  \\C_n = \\{\\ket{\\psi}\\mid s\\ket{\\psi}=\\ket{\\psi} \\forall s\\in\\S\\}.\n  \\]\n  Thus the stabilizer codes of\\cite{gottes} are a subclass of the class\n  of codes defined in this paper.\n\\end{remark}\n\nAt this point we recall some useful facts from the theory of\nstabilizer codes (see\\cite{AP02} for details).\n\nLet $\\S$ be a Gottesman subgroup of $\\E$\n\\[\n\\C(\\S)=\\{\\ket{\\psi}\\in\\HinA\\mid U\\ket{\\psi}=\\ket{\\psi}\\mbox{~~}\\forall\\mbox{~~} U\\in \\S\\}.\n\\]\n\nLet $Z(\\S)$ denote the centralizer of $\\S$ in $\\E$, that is,\n\n\\[\nZ(\\S) = \\{U\\in\\E\\mid UU'=U'U \\mbox{~~}\\forall\\mbox{~~} U'\\in \\S\\}.\n\\]\n\nFor Gottesman subgroup $\\S$ let the closure be $\\overline{\\S}$ (see\nDefinition~\\ref{gottes}).\n\n\\begin{theorem}\\label{kl-3}\n  Let $\\S$ be a Gottesman subgroup of the error group $\\E$ and let\n  $\\cS$ be its closure. Then $\\C(\\S)$ is a $t$-error correcting\n  quantum code if $\\wt(\\a,\\b)>2t$ for each $\\om^iU_{\\a}V_{\\b}\\in\n  Z(\\S)\\setminus\\cS$.\n\\end{theorem}\n\nThe above theorem is a generalization of a basic result of Calderbank et al \n\\cite[Theorem 1]{cald-shor}, where it is stated for the special case $A=\\F_4$.\n\nWe introduce a useful notation for describing quantum stabilizer\ncodes. Let $\\S$ be a Gottesman subgroup of $\\E$ with centralizer\n$Z(\\S)$. The \\emph{minimum distance} $d(\\S)$ is defined to be the\nminimum of\n\\[\n\\{\\wt(\\a,\\b)\\mid \\om^iU_{\\a}V_{\\b}\\in Z(\\S)\\setminus\\cS\\}.\n\\]\n\nWhen $A$ is the additive abelian group of the finite field $\\F_q$ we\ndefine an $\\brac{n,k,d}{q}$ quantum stabilizer code to be a\n$q^k$-dimensional subspace $\\C(\\S)$ of $L^2(\\F_q)^{\\otimes^n}$, where\n$\\S$ is a Gottesman subgroup of $\\E$ with $d(\\S)\\geq d$ and cardinality\n$q^{n-k}$.\n\nBy Theorem~\\ref{kl-3} it follows that an $\\brac{n,k,d}{q}$ quantum\nstabilizer code is a $\\floor{(d-1)/2}$-error correcting quantum code.\n\n\\section{Nonstabilizer codes over finite fields}\\label{finitefieldsection}\n\nWe focus our attention to the case when the abelian group $A$ is the\nfield $ \\GF{q}$. Recall that the additive group $\\GF[n]{q}$ is a\nvector space over $\\mathbb{F}_q$. If $\\omega$ is a nontrivial\ncharacter then the characters of the additive group $\\GF[n]{q}$\nconstitute the set $\\{ \\omega_{\\bf a} | {\\bf a} \\in \\GF[n]{q} \\}$\nwhere $\\omega_{\\bf a}({\\bf b}) = \\omega( {\\bf a} . {\\bf b})$, $\\a . \\b\n= \\sum a_i b_i$.\n\nThe set of operators $\\{ \\omega_p^i U_{\\bf a} V_{\\bf b} | {\\bf a},{\\bf\n  b} \\in \\GF[n]{q}\\textrm{, } 0 \\leq i \\leq p-1 \\}$, $\\omega_p$ is a\n$p^{th}$ root of unity, where $p$ is the characteristic of the field\n$\\GF{q}$, forms an irreducible representation of associated error\ngroup.  It is shown in\\cite{AP02} that any Gottesman subgroup $\\S$ is\nof the following form\n\n\\begin{eqnarray*}\\label{eq-lm}\n\\{ \\omega(\\rho({\\a}))U_{L{\\a}}V_{M{\\a}}\\mid {\\bf a}\\in\\GF[r]{q}\\},\n\\end{eqnarray*}\nwhere $L$ and $M$ are $n \\times r$ matrices over $\\GF{q}$ such that $L^{T}M$ is\nsymmetric and $\\rho(.)$ satisfies the condition that\n\\[\n\\rho({\\v_1} + {\\v_2}) - \\rho({\\v_1}) - \\rho({\\v_2}) = {\\v_2}^{T}L^{T} M{\\v_1}.\n\\]\n\nOur goal in this section is to seek for nonstabilizer codes with the\nhelp of Theorem~\\ref{distdtheorem}.\n\n\\begin{definition}\n  A Gottesman subgroup $\\S$ of the error group $\\E$ is said to be\n  \\emph{$d$-pure} if $\\wt(g)\\geq d$ for every $g \\in Z(\\S)$ that is\n  not a scalar multiple of the identity operator.\n\\end{definition}\n\nBy the theory of stabilizer codes, it follows that the stabilizer code\n$\\C(\\S)=\\{\\psi\\in\\HinA\\mid U\\psi=\\psi\\mbox{~~}\\forall\\mbox{~~} U\\in\n\\S\\}$ corresponding to a $d$-pure Gottesman subgroup $\\S$, is a\n$\\floor{(d-1)/2}$-error correcting quantum code.\n\nMore precisely, our aim is to start with the stabilizer code $\\C(\\S)$\nof distance $d$, and use Theorem~\\ref{distdtheorem} to construct\nnonstabilizer codes of the same distance but larger dimension.\n\nObserve that if $\\S$ is a $2t$-pure Gottesman subgroup of $\\E$, the\nfirst condition in Theorem~\\ref{distdtheorem} is vacuously true. Thus,\nwe only need to ensure that the second condition in\nTheorem~\\ref{distdtheorem} is satisfied.  For a $d$-pure Gottesman\ncode we define the \\emph{forbidden set} as follows\n\n\\begin{definition}\n  Let $\\S$ be a $d$-pure Gottesman subgroup of the error group $\\E$.\n  We define the \\emph{$d$-forbidden subset} of $\\S$, denoted by\n  $\\mathcal{F}_d(\\S)$, to be the subset\n  \\[ \n  \\mathcal{F}_d(\\S) = \\left\\{ u \\in \\S : u\\neq I,\\hbox{ and }\\exists g \\in \\E \\setminus \\S\\  wt(g) < d \n  \\textrm{  and }\\sum_{s \\in S}(\\gamma_g \\chi_u)(s) = \\# \\S \\right\\}.\n  \\]\n\\end{definition}\n\nWe have the following theorem that is an easy consequence of\nTheorem~\\ref{distdtheorem}.\n\n\\begin{theorem}\\label{puredistdtheorem}\nLet $\\S$ be a $d$-pure Gottesman subgroup of the error group $\\E$. Then \n$B \\subseteq \\S$ is the Fourier description of a distance $d$ code if and only if\n$B^{-1}B \\cap \\mathcal{F}_d(\\S)$ is empty.\n\\end{theorem}\n \nLet $s_{\\a}$ denote $\\omega_p(\\rho(a)) U_{L\\a} V_{M\\a}\\in\\S$. Observe\nthat $\\tau: s_{\\a}\\mapsto \\a$ is a group isomorphism from $\\S$ to\n$\\GF[r]{q}$, and $\\chi_{s_{\\a}}\\mapsto \\om_{\\a}$ is an isomorphism\nfrom $\\widehat{\\S}$ to $\\widehat{\\GF[r]{q}}$.\n    \nLet $g =\\om^i U_\\x V_\\y\\not\\in\\S$ with $\\wt(g)\\leq 2t$. By applying\nthe Weyl commutation relations we get $\\gamma_g(s_{\\a})=\n\\omega(\\a^{T}M^T \\x - \\a^{T}L^{T}\\y) = \\omega_\\a( M^T \\x - L^T \\y)$.\nWe have the following theorem.\n\n\\begin{theorem}\\label{forbiddensettheorem}\n  Let $\\S = \\{ \\omega(\\rho(\\a)) U_{L\\a} V_{M\\a} : a \\in \\GF[r]{q} \\}$\n  be a $d$-pure Gottesman subgroup of the error group $\\E$ over\n  $\\GF[n]{q}$. Then the $d$-forbidden subset of $\\S$ is given by\n  \\[\n  \\mathcal{F}_d(\\S) = \\{ s_{\\bf u}: \\exists \\x,\\y \\in \\GF[n]{q}\\ wt(\\x,\\y) < d\n  \\textrm{ and } {\\bf u} = L^T \\y - M^T \\x \\}.\n  \\]\n\\end{theorem}\n\\begin{proof}\n  \\[\n  \\sum_{s \\in \\S} \\gamma_g(s) \\chi_u(s) = \\sum_{\\a \\in \\GF[r]{q}}\n  \\omega_a({\\bf u } + M^T \\x - L^T \\y)\n  \\]\n  Note that the right hand side of the equation is the sum over all\n  characters of $\\GF[r]{q}$ and hence is nonzero iff $ {\\bf u} + M^T \\x\n  - L^T \\y= 0$. Hence\n  \\[\n  \\mathcal{F}_d(\\S) = \\{ s_{\\bf u}: \\exists \\x,\\y \\in \\GF[n]{q}\\ wt(\\x,\\y) < d\n  \\textrm{ and } {\\bf u} =L^T\\y -  M^T \\x  \\}\n  \\]\n\\end{proof}\n\n\\begin{remark}\\label{forbiddensetremark}\n  In the above setting we will call the set \n  \n  \\[\n  F_d(\\S) = \\{\\u: \\u\\neq 0, \\exists \\x,\\y \\in \\GF[n]{q}\\ wt(\\x,\\y) < d\n  \\textrm{ and } {\\bf u} = L^T \\y - M^T \\x \\}\n  \\] \n  the forbidden set. Note that $\\mathcal{F}_d(\\S) = \\{ s_{\\bf u} : {\n    \\bf u } \\in F_d(\\S)\\}$.\n\\end{remark}\n\n\\section{Bounds on the dimension of codes}\n\nWe now give upper and lower bounds on the dimension of nonstabilizer\ncodes built from pure Gottesman subgroups of $\\E$. Let the encoding\nspace be $\\HinA$, and $N(n,q,d)$ denote the number $\\sum_{i=0}^{d}\n{\\left( \\begin{array}{c} n \\\\ i \\end{array} \\right)} (q^2 -1)^i$. \nWe have the following upper bound on the dimension of the code.\n\n\\begin{theorem}\n  Let $\\C_n\\subseteq\\HinA$ be a $d$-error correcting quantum code such\n  that its corresponding projection $P$ has support in a $2d+1$-pure\n  Gottesman subgroup $\\S$ of the error group $\\E$. Let $B$ be the \n  Fourier description of $\\C_n$. Then the dimension of the code $\\C_n$\n  satisfies the inequality \n\\[ \n\\dim(\\C_n) \\leq \\frac{\\#A^n}{N\\left(n,\\#A,d\\right)}. \n\\]\n\\end{theorem}\n\n\\begin{proof}\n  Since $\\S$ is $2d+1$-pure, $\\{g\\in\\E\\mid \\wt(g)\\leq 2d\\}\\subseteq\n  \\E\\setminus\\S$. By Theorem~\\ref{distdtheorem} we have:\n\n\\[ \nPgP = 0\n\\] \nfor all $g\\in\\E$ such that $\\wt(g)\\leq 2d$. Let $P_g$ denote the\nprojection $g^{-1}Pg$. The range of $P_g$ has dimension $\\dim(\\C_n)$\nfor every $g\\in\\E$. Furthermore, for all $g_1, g_2\\in\\E$ such that\n$\\wt(g_1)\\leq d$ and $\\wt(g_2)\\leq d$, we have \n\n\\[ \nP_{g_1} P_{g_2} = g_1^{-1} P g_1 g_2^{-1} P g_2 = 0,\n\\] \nsince $\\wt(g_1 g_2)\\leq 2d$ implies $P g_1 g_2 P = 0$. Thus,\n$\\{P_g\\mid g\\in\\E, \\wt(g)\\leq d\\}$ is a collection of mutually\northogonal projections in $\\HinA$. Furthermore, the range of each\n$P_g$ is $\\dim(\\C_n)$. Since there are $N(n,\\#A,d)$ elements $g$ in\n$\\E$ with $\\wt(g)\\leq d$, it follows by adding dimensions that\n\n\\[\nN\\left(n,\\#A,d\\right)~\\dim(\\C_n) \\leq \\dim{\\HinA} = \\#A^n.\n\\] \n\\end{proof}\n\nWe now obtain a lower bound for the dimension of codes satisfying\nthe conditions of Theorem~\\ref{forbiddensettheorem}.\n\n\\begin{theorem}\\label{lowerbound}\n  Let $A=\\F^n_q$, and $\\S=\\{ \\omega(\\rho(\\a)) U_{L \\a} V_{M \\a} | \\a\n  \\in \\GF[r]{q}\\}$ be a $2d+1$-pure Gottesman subgroup of the error\n  group $\\E$ for the encoding space $\\HinA$. Then there is a $d$-error\n  correcting code $\\C_n$ such that its corresponding projection has\n  support in $\\S$ and\n\\[\n\\dim(C_n)\\geq \\frac{q^n}{N(n,q,2d)}.\n\\]\n\\end{theorem}\n\n\\begin{proof}\n  For the $2d+1$-pure Gottesman subgroup $\\S=\\{ \\omega(\\rho(\\a)) U_{L\n    \\a} V_{M \\a} | \\a \\in \\GF[r]{q}\\}$, let $X$ be the corresponding\n  forbidden set. By Theorem~\\ref{forbiddensettheorem}, $X$ is the\n  image of the set $\\{ (\\x,\\y) | \\x,\\y\\in \\GF[n]{q}, wt(\\x,\\y) \\leq\n  2d\\}$ under the map $(\\x,\\y) \\mapsto L^T \\y - M^T \\x$. There are $N(n,q,2d)$ pairs\n  $(\\x,\\y)$, such that $\\x,\\y \\in \\GF[n]{q}$ and $\\wt(\\x,\\y)\\leq 2d$.\n  It follow that $\\#X\\leq N(n,q,2d)$. We prove the existence of the code $\\C_n$\n  by constructing its Fourier description $B\\subseteq \\S$ using the\n  following ``greedy'' procedure to pick elements from $\\S$:\n\n  \\begin{enumerate}\n  \\item initially, let $B$ be the empty set and let $T = A$.\n  \\item Pick any $\\u \\in T$ and include in $B$.\n  \\item Remove from $T$ all elements $\\v$ such that difference $\\u\n   -\\v$ is in $X$, where $\\u$ is the element picked in the previous\n    step.\n  \\item If $T$ is empty, stop. Otherwise, return to Step 2.\n  \\end{enumerate}\n  \n  Consider the Fourier description $B$ constructed at the end of the\n  above procedure. Note that the procedure will eliminate at most\n  $\\#X$ elements from $T$ every time we include a new element in $B$.\n  Thus, the number of elements picked into $B$ will be at least\n  $\\floor{\\frac{\\#A}{\\#X}}\\geq \\frac{\\#A}{N(n,q,2d)}$. Applying\n  Lemma~\\ref{dimlemma} yields the desired lower bound on $\\dim(C_n)$.\n\\end{proof}\n\nWe can now easily argue about the existence of asymptotically good\nnonstabilizer codes. The following theorem is a paraphrase of a result\nwe proved in\\cite{AP02} about the existence of $d$-pure maximal\nGottesman subgroups of the error group $\\E$ for large $d$, for encoding\nspace $\\HinA$ for large $n$ ($A=\\F_2$).\n\nWe first need the following technical definition.\n\n\\begin{definition}\\label{good}\n  An $n\\times n$ matrix $R$ over $\\F_2$ is said to be\n  $\\alpha$-\\emph{good} if the following conditions are true.\n\\begin{enumerate}\n\\item[(i)] The sum of every $\\floor{\\alpha n}$ columns of $R$ has weight at\n  least $\\alpha n$.\n\\item[(ii)] The sum of every $\\floor{\\alpha n}$ rows of $R$ has weight at\n  least $\\alpha n$.\n\\item[(iii)] The sum of every $\\floor{\\alpha n}$ columns of $R$ has weight at\n  most $(1-\\alpha)n$.\n\\item[(iv)] The sum of every $\\floor{\\alpha n}$ rows of $R$ has weight at\n  most $(1-\\alpha)n$.\n\\end{enumerate}\n\\end{definition}\n\nIt is shown in\\cite{AP02} that there is a constant $\\alpha>0$ and a\ncorresponding positive integer $n_{\\alpha}$ such that, for a randomly chosen R\n\n\\[\n\\Pr[R\\mbox{ is $\\alpha$-good }]>0.\n\\]\n \n\\begin{theorem}\\label{exists}\n  For $0<\\alpha<1$, suppose $R$ is an $n\\times n$ $\\alpha$-good matrix\n  over $\\F_2$.  Let $L$ be the following $2n\\times 2n$ symmetric\n  matrix over $\\F_2$:\n\\[\n\\left( \\begin{array}{cc}\n       0 & R \\\\\n       R^T & 0 \n       \\end{array}   \n\\right)\n\\]\nIf we write $L=D+D^T$, where $D$ is the upper triangular matrix with\nzeros on the principal diagonal, then $\\S=\\{\\w(\\a^TD\\a)U_{\\a}V_{L\\a\n  -\\b}\\mid \\a\\in C, \\b\\in C^{\\perp}\\}$, is an $\\floor{\\alpha n}$-pure\nmaximal Gottesman subgroup $\\S$ of the error group $\\E$.\n\\end{theorem}\n\nNow, applying Theorem~\\ref{lowerbound} we immediately get the following\nfamily of asymptotically good nonstabilizer codes.\n\n\\begin{corollary}\\label{asymp-good}\n  For $0<\\alpha<1$, suppose $R$ is an $n\\times n$ $\\alpha$-good matrix\n  over $\\F_2$ and $\\S$ is the $\\floor{\\alpha n}$-pure maximal Gottesman\n  subgroup $\\S$ of the error group $\\E$ (defined in the above\n  theorem).  Then there is an $\\floor{(\\alpha n-1)/2}$-error correcting\n  quantum code of dimension $\\frac{2^n}{N(n,2,\\floor{\\alpha n})}$,\n  whose projection has support in $\\S$.\n\\end{corollary}\n\n\\section{Explicit construction of non-stabilizer codes}\\label{explicit}\n\nWe now give an explicit construction of a family of distance $2$ code.\nRecall that any abelian group of the error group is of the form\n\\[\n\\S = \\{ \\omega(\\rho(\\a)) U_{L\\a}V_{M\\a} : \\a \\in \\GF[r]{q} \\}\n\\]\nwhere $L$ and $M$ are $r \\times n$ matrices over \\GF{q} such that $L^T\nM$ is symmetric and $\\rho$ satisfies the condition\n\\[\n\\rho(\\a_1 + \\a_2 ) - \\rho(\\a_1) - \\rho(\\a_2) = \\a_1^T L^T M \\a_2.\n\\] \n\nGiven an odd integer $n = 2m + 1$, we give the explicit construction\nof a $((n,1+n(q-1),2))_q$ code. Note that if $q =2$ and $n=5$ we get a\n$((5,6,2))_2$ code. In\\cite{rains97nonadditive} a $((5,6,2))_2$ code\nis given which is generated by a computer search. They have also shown\nthat for distance 2 this is the best possible code. We also show that\nthere is a code of dimension greater than $\\left\\lceil\n  \\frac{q^n}{n(q^2-1)} \\right\\rceil$.\n\nLet ${\\bf x} \\in \\GF[n]{q}$ is all zeros except at positions $m+1$ and\n$m+2$ where it is $1$. Define the matrices $S$ and $L$ as follows\n\n\\[\nS = \\left( \\begin{array}{c}\n                    {\\bf x}^T\\\\\n                    \\sigma{\\bf x}^T\\\\\n                    \\vdots\\\\\n                    \\sigma^i{\\bf x}^T\\\\\n                    \\vdots\\\\\n                    \\sigma^{n-1}{\\bf x}^T\n                  \\end{array}\n                \\right)\\  L =\n                \\left( \n                 \\begin{array}{c|c}\n                    &  0\\\\\n                    I_{n-1}   & \\vdots \\\\\n                    & 0 \\\\\n                    \\hline\n                    -1 \\ldots -1     & 0 \n                  \\end{array}\n                \\right).\n\\] \nwhere $\\sigma$ is the cyclic shift on $n$ elements and $I_{n-1}$ is\nthe $n-1 \\times n-1$ identity matrix. Let $J$ be the $n\\times n $\nmatrix, all of whose entries are $1 \\in \\GF{q}$ and let $M = SL + J$.\nNote that $JL = 0$ and hence $M^TL = L^T S L$ is symmetric. As a\nresult the pair $L$, $M$ gives rise to a Gottesman subgroup\n\\[\n\\S = \\{ \\omega(\\rho(a)) U_{L\\a} V_{M\\a} : \\a \\in \\GF[n]{q} \\}.\n\\]\n\nLet $\\e_i, 0 \\leq i \\leq n - 1$ be the standard basis for $\\GF[n]{q}$.\n$\\e_i$ is the vector with a $1$ in the $i^{th}$ position and $\\e_0$ is\nthe vector with a $1$ at the $n^{th}$ position. Let $\\underline{1} =\n(1,1,\\ldots,1)$ then we have the following observation.\n\n\\begin{observation}\n  \\[\n  S \\e_j  = \\e_{j + m} + \\e_{j + m + 1}\\ ( \\textrm{ index addition mod n} ).\n  \\]\n\n  \\[\n  L^T \\e_j = \\left\\{\n    \\begin{array}{cc}\n      \\e_0 - \\underline{1} & \\textrm{if }j = 0,\\\\\n      \\e_j & \\textrm{otherwise.}\\\\\n    \\end{array}\n  \\right.\n\\]\n\n\n\\[\nM^T \\e_j = \\left\\{\n  \\begin{array}{cc}\n    \\e_{j+m} + \\e_{j+m+1} + \\underline{1} & \\textrm{if } j+m \\not \\equiv 0 \\textrm{ and } \n    j+m+1 \\not \\equiv  0\\ (\\textrm{mod n}),\\\\\n    \\e_{0} + \\e_1  & j+m \\equiv 0\\ (\\textrm{mod n}),\\\\\n    \\e_0 + \\e_{n-1} & j+m+1 \\equiv 0\\ (\\textrm{mod n}).\n    \\end{array}\n    \\right.\n\\]\n\\end{observation}\n\nNote that for $L$ and $M$ defined as above $\\S$ will be a maximal\nabelian subgroup (because its cardinality is $q^n$) and is $2$-pure.\nFurthermore, the 2-forbidden set is given by\n\\[\nF_2 = \\{ L^T \\y - M^T \\x : wt(\\x,\\y) = 1 \\} = \\{ a M^T \\e_j + b L^T\n\\e_j : (a,b) \\ne (0,0);\\ a,b \\in \\GF{q} 1 \\leq j \\leq n \\}.\n\\]\n    \nWe can now derive the following asymptotic result.\n\n\\begin{theorem}\n  Let $n = 2m +1$ be an odd integer. There exists a\n  $((n,\\left\\lceil\\frac{q^n}{n(q^2 -1)}\\right\\rceil,2))_q$ quantum code.\n\\end{theorem}\n\n\\begin{proof}\n  Let the matrices $S$, $L$, and $M$ be as defined in the above\n  observation and $F_2$ be the corresponding 2-forbidden set. Then\n  $\\#F_2 = n (q^2 - 1)$. Now, applying a greedy algorithm similar to\n  the one in the proof of Theorem~\\ref{lowerbound} we can construct a\n  $((n,\\left\\lceil\\frac{q^n}{n(q^2-1)}\\right\\rceil,2))_q$ quantum\n  code.\n\\end{proof}\n\nConsider the subset $B$ of $\\S$ defined as\n\\[\nB = \\left\\{ \\underline{0} \\right\\} \\cup \\left\\{ \\alpha \\e_0 : \\alpha \\in \\GF[*]{q} \\right\\} \\cup\n\\left\\{ \\e_0 + \\alpha\\left( \\sum_{i=1}^{n-1} \\e_i\\right) - \\e_j : \\alpha \\in\n  \\GF[*]{q};\\ j = 1,2,\\dots n-1 \\right\\}.\n\\]\nNotice that $\\# B = 1 + n(q-1)$. \n\n\\begin{theorem}\n  The set $B$ as defined above is the Fourier description of a $((n,1 + n(q-1), 2))_q$ code.\n\\end{theorem}\n\n\\begin{proof}\n  Let $D = (B - B ) \\setminus \\{ \\underline{0} \\}$.  Since $F_2$ does\n  not contain the zero vector it is sufficient to prove that $F_2 \\cap\n  D$ is empty. Let $\\u_i = \\left(\\sum_{j=1}^{n-1} \\e_j\\right) - \\e_i, 1 \\leq i \\leq\n  n-1$.  Now $D = A_1 \\cup A_2 \\cup A_3 \\cup A_4$ where\n  \\[\n  \\begin{array}{ccl}\n    A_1 &=& \\{ \\alpha \\e_0 , \\alpha \\ne 0 \\} \\\\\n    A_2 &=& \\{ \\e_0 + \\alpha \\u_i : \\alpha \\ne 0 \\} \\\\\n    A_3 &=& \\{ \\alpha \\e_0 + \\beta \\u_i : \\beta \\ne 0;\\ \\alpha \\ne -1 ;\\ 1\\leq i \\leq n - 1 \\}\\\\\n    A_4 &=& \\{ \\alpha \\u_i + \\beta \\u_j: \\alpha,\\beta \\ne 0;\\ 1 \\leq i,j \\leq n - 1;\\\n     \\alpha \\ne \\beta \\textrm{ or } i \\ne j\\}\n  \\end{array}\n  \\]\n  where $\\alpha,\\beta \\in \\GF{q}$. The elements of the forbidden set\n  $F_2$ are given by\n  \\[\n  \\begin{array}{ccl}\n    R_1 &=& \\{ a (\\e_m + \\e_{m+1}) + b \\e_0 + (a-b)\\underline{1} : (a,b) \\ne (0,0) \\}\\\\\n    R_2 &=& \\{ a ( \\e_0 + \\e_1 ) + b \\e_{m+1} : (a,b) \\ne (0,0) \\}\\\\\n    R_3 &=& \\{ a (\\e_0 + \\e_{n-1} ) + b \\e_m : (a,b) \\neq (0,0) \\}\\\\\n    R_4 &=& \\{ a (\\e_{j+m} + \\e_{j+m+1}) + b \\e_j + a \\underline{1} : (a,b) \\ne (0,0);\\\n                                                                    j \\ne 0, j\\ne m, j \\ne m+1 \\}\n  \\end{array}\n  \\]\n  \n  Now it can be verified that $A_i \\cap R_j$ is empty for every $1\n  \\leq i,j \\leq 4$. It follows that $D\\cap B=\\emptyset$.\n\\end{proof}\n\n\\section{Examples of 1-error correcting nonstabilizer codes}\n\nIn this section we give explicit constructions of a $((33,155,3))$\ncode and a $((15,8,3))$ code. The codes we construct will be over the\nfield $\\GF{2}$.\n\nLet $n=2m+1$ be any odd integer.  Let ${\\bf x }$ be the vector in\n$\\GF[n]{2}$ with zeros at all positions except $m+1$ and $m+2$. As in\nthe previous section, let\n\\[\nS = \\left( \\begin{array}{c}\n                    {\\bf x}\\\\\n                    \\sigma{\\bf x}\\\\\n                    \\vdots\\\\\n                    \\sigma^i{\\bf x}\\\\\n                    \\vdots\\\\\n                    \\sigma^{n-1}{\\bf x}\n                  \\end{array}\n                \\right)\\  L =\n                \\left( \n                 \\begin{array}{c|c}\n                    &  0\\\\\n                    I_{n-1}   & \\vdots \\\\\n                    & 0 \\\\\n                    \\hline\n                    1 \\ldots 1     & 0 \n                  \\end{array}\n                \\right),\n\\] \n\nwhere $\\sigma$ is the cyclic shift. Let $J$ be the $n \\times n$ matrix\nall of whose entries are 1's.  Recall that the generalized Laflamme\ncode is the stabilizer code associated with the stabilizer group given\nby\n\\[\n\\S = \\{ U_{L\\a} V_{M \\a } : \\a \\in \\GF[n]{2} \\},\n\\]\nwhere $M = S L + J$. The corresponding 2-forbidden set is given by \n\\[\nF_2 = \\{ a M^T e_i + b L^T e_i : a,b \\in \\GF{2} \\}.\n\\]\n\nLet $F_d + F_2=\\{\\u\\mid \\u=\\u_1+\\u_2,\\hbox{\\textrm such that }\n\\u_1\\in F_d, \\u_2,\\in F_2\\}$.\n\nIt can be easily verified that $F_{d + 1} = \\{\\u\\mid \\u\\in F_d + F_2,\n\\u\\neq 0\\}$. Now, let $W_d = \\{ wt(\\a) : \\a \\in F_d \\}$. It can be\neasily checked that $W_2 = \\{1,2,3,n-3,n-2,n-1\\}$ and $W_3 = \\{ 1,2,\n3, 4, 5, 6, n-6,n-5,n- 4, n-3 , n-2 , n-1 \\}$.\n\nIf $B$ is a subset of $\\GF[n]{2}$ such that for $u \\in B - B$ we have\n$wt(u) \\not \\in W_3$ then $B$ is the Fourier description of a 1-error\ncorrecting quantum code. A natural approach to finding large Fourier\ndescriptions $B$ is to solve the following combinatorial problem.\n\n\\begin{problem}\\label{prob1}\nConstruct a family of subsets $\\mathfrak{F}$ of\n$\\{1,2,\\ldots,n\\}$ such that for all $S_1,S_2 \\in \\mathfrak{F}$, $S_1\n\\ne S_2$ we have\n\\[ \n\\# (S_1 \\setminus S_2) + \\# (S_2\\setminus S_1) \\not\\in W_3. \n\\]\n\\end{problem}\n\nGiven such a collection of subsets $\\mathfrak{F}$, it is clear that\nthe set $B$ defined as\n\\begin{eqnarray}\\label{B-sets}\n B =\\left\\{ \\sum_{i \\in S} e_i : S \\in \\mathfrak{F}\\right\\}\n\\end{eqnarray}\nwill yield the Fourier description of a 1-error correcting quantum\ncode by Theorem~\\ref{distdtheorem}. For, the condition on the family\nof subsets $\\mathfrak{F}$ will ensure that the weight of any element\nin $B - B$ does not lie in the set $\\{\n1,2,3,4,5,6,n-6,n-5,n-4,n-3,n-2,n-1\\}$ and hence $(B - B)\\cap\nF_2=\\emptyset$.\n\nAs our first example we describe a $((15,8,3))$ code. For $n=15$ it\nsuffices to construct a family of $8$ subsets $\\mathfrak{F}$ such that\nfor any two distinct subsets $S_1,S_2\\in\\mathfrak{F}$ we have $\\# (S_1\n\\setminus S_2) + \\# (S_2\\setminus S_1)\\in\\{7,8\\}$. Then, $B$ defined\nby Equation~\\ref{B-sets} will be the Fourier description of a\n$((15,8,3))$ code. The eight subsets of $\\{1,2,\\ldots,15\\}$ that we\npick are as follows:\n\n\\begin{enumerate}\n\\item[] $S_1 = \\{1,2,3,4,13\\}$,  $S_2 = \\{5,6,7,8,13\\}$,  \n$S_3 = \\{9,10,11,12,13\\}$,\n\\item[] $S_4 = \\{1,2,5,6,9,10\\}$, $S_5 = \\{1,2,7,8,11,12\\}$, $S_6 =\n\\{3,4,7,8,9,10\\}$,\n\\item[] $S_7 = \\{3,4,5,6,11,12\\}$,  $S_8 = \\{14,15\\}$.\n\\end{enumerate}\n\nIn order to construct such nonstabilizer codes for general $n$ we need\nto construct explicit set families $\\mathfrak{F}$ as a solution to\nProblem~\\ref{prob1}. To this end we describe a general method and use\nit to construct a $((33,155,3))$ code. More precisely, we will seek a\nspecial solution of Problem~\\ref{prob1} in which all the sets in\n$\\mathfrak{F}$ are of the same cardinality.\n\n%\\begin{problem} Construct a family of subsets $\\mathfrak{F}$ of\n%$\\{1,2,\\ldots,n\\}$ such that the following conditions hold\n%\\begin{enumerate}\n%\\item For all $S \\in \\mathfrak{F}$, $\\# S = k$.\n%\\item For all $S_1,S_2 \\in \\mathfrak{F}$, $S_1 \\ne S_2$ we have\n%  \\[ k - \\frac{(n -7)}{2} \\leq \\# S_1 \\cap S_2 \\leq k - \\frac{7}{2}. \\]\n%\\end{enumerate}\n%\\end{problem}\n\nLet $n = 33$. In our construction we will consider only subsets of\n$\\{1,2,\\ldots,32\\}$. Notice that, $\\GF[5]{2}$ and $\\{1,2,\\ldots,32\\}$\nare sets of the same size and can be identified using any 1-1\ncorrespondence. Thus, our goal is essentially to find a family of\nsubsets of $\\GF[5]{2}$ that yields a solution to Problem~\\ref{prob1}.\n\nConsider the vector space $\\GF[5]{2}$. Let $\\mathfrak{F}$ be the\nfamily of all 3 dimensional subspaces of $\\GF[5]{2}$. Since any $S \\in\n\\mathfrak{F}$ is a vector space over $\\GF{2}$ of dimension three, we\nhave $\\# S = 2^3 = 8$.  Moreover any two distinct subspaces can have\nat most 4 vectors in common. Hence for every pair of distinct sets $\nS_1,S_2 \\in \\mathfrak{F}$ we have $\\# S_1 \\cap S_2 \\leq 4$.\nConsequently, for distinct sets $ S_1,S_2 \\in \\mathfrak{F}$ we have\n\\[\n8\\leq \\# (S_1 \\setminus S_2) + \\# (S_2\\setminus S_1) \\leq 14.\n\\]\n\nThus, for distinct sets $ S_1,S_2 \\in \\mathfrak{F}$ $\\# (S_1 \\setminus\nS_2) + \\# (S_2\\setminus S_1)\\not\\in W_2$ and hence the corresponding\nFourier description $B$ gives rise to a 1-error correcting code. \n\nNow, to find the size of the set $B$ which is the dimension of the\ncode we have to find the size of $\\mathfrak{F}$. The following general\ntheorem gives the exact size.\n\n\\begin{theorem} \\label{gntheorem}\n  Consider the vector space $\\GF[m]{q}$. The number of subspaces of dimension\n$r$ is\n\\[\n\\frac{(q^m - 1)(q^{m-1} -1 ) \\ldots (q -1) } { (q^r -1)(q^{r-1} -1 )\n  \\ldots (q-1) ( q^{m-r} -1 ) (q^{m-r-1} -1 ) \\ldots (q -1 ) }\n\\]\n\\end{theorem}\n\\begin{proof}\n  Let $\\e_1,\\e_2,\\ldots,\\e_m$ be the standard basis for $\\GF[m]{q}$.\n  Let $\\mathfrak{T}$ be the family of all $r$ dimensional subspaces of\n  $\\GF[m]{q}$.  We want to find $\\# \\mathfrak{T}$. Let $R$ be the\n  subspace of $\\GF[m]{q}$ spanned by the vectors\n  $\\e_1,\\e_2,\\ldots,\\e_r$. Consider the group $G = \\GLnq$. $G$ acts on\n  $\\mathfrak{T}$ transitively and hence the orbit of $R$ under the $G$\n  action is the whole of $\\mathfrak{T}$. Hence the number of elements in\n  $\\mathfrak{T}$ is given by\n  \\[\n  \\# \\mathfrak{T} = \\frac{\\# G}{\\# G_R}\n  \\]\n  where $G_R$ is the subgroup of $G$ that leaves $R$ invariant.\n  \n  Any element of $G_R$ is of the form \n  \\[\n  \\left(\n    \\begin{array}{c|c}\n      A&*\\\\\n      \\hline\n      0 & B\n    \\end{array}\n  \\right)\n  \\]\n  where $A$ and $B$ are $r \\times r $ and $(m-r) \\times (m-r)$ nonsingular matrices respectively and\n  $*$ is any $r \\times ( m -r) $ matrix. If $g(m) = \\# \\GLnq$ then we have \n  \\[\n  \\# G_R = g(r) g(m-r) q^{(m-r)r}.\n  \\]\n  So the problem reduces to finding $g(m)$. Let $A$ be any matrix in\n  $\\GLnq$. The first column of $A$ can be any one of the nonzero\n  vectors is $\\GF[m]{q}$. There are $q^m -1$ nonzero vectors.  Having\n  fixed the first column $\\a_1$, we have $q^m - q$ choices for the\n  second column $\\a_2$. Similarly there are $q^m -q^2$ choices for the\n  third column and so on. Therefore the number of elements in $\\GLnq$\n  is given by\n\\[\ng(m) = \\prod_{i=0}^{m-1} (q^m - q^i).\n\\]\n\nTherefore the size of $\\mathfrak{T}$ is given by\n\\begin{eqnarray}\n  \\nonumber\n  \\# \\mathfrak{T} &=& \\frac{g(m)}{g(r)g(m-r) q^{(m-r)r}}\\\\\n    \\nonumber\n    &=& \\frac{(q^m - 1)(q^{m-1} -1 ) \\ldots (q -1) }\n            { (q^r -1)(q^{r-1} -1 ) \\ldots (q-1) ( q^{m-r} -1 ) (q^{m-r-1} -1 )\n              \\ldots (q -1 ) }  \n\\end{eqnarray}\n\\end{proof}\n\n{From} Theorem~\\ref{gntheorem} we have \n\\[\n\\# \\mathfrak{F} = 155\n\\] and hence the set $B$ defined as\n\\[\nB = \\left\\{ \\sum_{i \\in S} e_i : S \\in \\mathfrak{F} \\right\\}\n\\] gives a $((33,155,3))$ code.\n\n\\begin{remark}\nWe can actually obtain a $((31,155,3))$ code as follows: construct the\nsame family of 3-dimensional subspaces of $\\GF[5]{2}$ which are 155 in\nnumber. Now, drop the extra coordinate, which will still result in 155\ndistinct subsets such that the symmetric difference of any pair of\nthese has weight in the range 7 to 14. Thus, we have a $((31,155,3))$\nnonstabilizer code. Notice that we can easily extend this puncturing \nargument to other nonstabilizer codes.\n\\end{remark}\n\n\\section{Encoding circuits for a class of nonstabilizer codes}\n\nIn this section we discuss the encoding algorithm for the class of\nnon-stabilizer codes defined in Section~\\ref{explicit} and the\nasymptotically good codes of Corollary~\\ref{asymp-good}. Recall that\ngiven a Gottesman subgroup $\\S$, the code $\\C(\\S)$ can be specified by\ngiving its Fourier description $B\\subseteq\\S$. We fix our encoding\nspace to be $L^2(\\GF[n]{q})$.  Let \\mbox{$C = \\{ \\a | \\sum_i a_i = 0\n  \\}$} and $C^\\perp$ the set $\\{ \\b | \\b^T \\a = 0 \\textrm{ for all }\n\\a \\in C\\}$.  We restrict attention to maximal Gottesman subgroups of\nthe form\n\n\\[\n\\S = \\{s_{a,b} = \\omega( \\a^T D \\a ) U_\\a V_{L\\a + \\b} | \\a \\in C, \\b\n\\in C^\\perp \\},\n\\] \nwhere $D$ is an upper triangular matrix and $L = D+D^T$. Consider a\ncode $\\C_n$ with Fourier description $B \\subseteq \\S$. Recall that the\ndimension of the code is $\\#B$. Due to the isomorphism $\\S \\cong C\n\\times C^\\perp \\hookrightarrow \\GF[n]{q} \\times \\GF[n]{q}$ we have the\ncharacter group of $\\S$ as\n\n\\[\n \\chi_{s_{\\c,\\d}}(s_{\\a,\\b}) = \\chi_{\\c,\\d}(\\a,\\b) = \\omega(\\a^T\\d +\n\\b^T \\c).\n\\]\n\nFor $u \\in \\S$ define $\\S_u$ to be the abelian group $\\{ \\chi_u(s) s |\ns \\in \\S\\}$. It is easy to see that the Gottesman subgroup $\\S_u$ is\nalso maximal. In this notation we have $\\S_1 = \\S$. Let\n$\\mathcal{C}_{\\S_u}$ denote the stabilizer (one dimensional) code\ncorresponding to the Gottesman subgroup $\\S_u$.  Let\n$\\{\\ket{\\varphi_u}\\}$ denote a (singleton) orthonormal basis for\n$\\mathcal{C}_{\\S_u}$ for each $u\\in\\S$.\n\n\\begin{theorem}\\label{onbasis}\n  The vectors $\\ket{\\varphi_u}, u \\in B$ form an orthonormal basis\n  for the code with Fourier description $B$.\n\\end{theorem}\n\n\\begin{proof}\n  The projection operators for the code with Fourier description $B$\n  is given by \n\n\\[\nP = \\frac{1}{\\#S} \\sum_{u \\in B} \\sum_{s \\in \\S} \\chi_u(s) s = \\sum_{u\n  \\in B} P_u\n\\] \n\nwhere $P_u = \\frac{1}{\\#\\S} \\sum_{s \\in \\S} \\chi_u(s) s$. Note that\n$P_u$ is the projection operator corresponding to the\nstabilizer code $\\mathcal{C}_{\\S_u}$. To prove that $\\{\\ket{\\varphi_u}\n| u \\in B\\}$ forms an orthonormal basis for the code given by $B$ it\nsuffices to show that\n  \n\\[\n  P_u P_v = \n\\left\\{\n\\begin{array}{cc}\n    0&\\textrm{if } u \\neq v, \\\\\n    P_u&\\textrm{otherwise,}\n\\end{array}\n\\right.\n\\]\n  \nwhich is an immediate consequence of the following:\n  \n\\[\n  P_u P_v = P_{\\chi_u * \\chi_v} = \\left\\{\\begin{array}{cc}\n      0&\\textrm{if } u \\neq v,\\\\\n      P_u&\\textrm{otherwise.}\n    \\end{array}\n  \\right. \n\\]\n\nIt follows that $\\{\\ket{\\varphi_u}\\mid u \\in B\\}$ is an orthonormal\nbasis for $\\C_n$.\n\\end{proof}\n\nFor $s_{\\a,\\b} \\in \\S$ instead of writing $\\S_{s_{\\a\\b}}$ we will\nwrite $\\S_{\\a,\\b}$. Similarly $\\ket{\\varphi_{\\a,\\b}}$ will be used to\ndenote $\\ket{\\varphi_{s_{\\a,\\b}}}$. It is easy to see that\n\n\\[\n\\ket{\\varphi_{\\c,\\d}} = \\sqrt{\\frac{1}{\\# C}}\\sum_{{\\bf x} \\in C}\n\\omega(({\\bf x} +\\d)^T D ({\\bf x} + \\d) ) \\overline{\\omega}({\\bf x}^T\nc) \\ket{{\\bf x} + d} .\n\\]\n\nSince the code has dimension $\\# B$, we will assume that the encoding\nmessage space is a Hilbert space of dimension $\\# B$ with basis \nindexed by elements of $B$ i.e. $\\{ \\ket{\\c,\\d} | s_{\\c,\\d} \\in B\\}$.\nTo summarize, we have the following observation.\n\n\\begin{proposition}\n  For a code with Fourier description $B$ the encoding procedure\n  is given by linear map with the following property $\\ket{\\c,\\d}\n  \\mapsto \\ket{\\varphi_{\\c,\\d}}$ for all $s_{\\c,\\d} \\in B$.\n\\end{proposition}\n\n%\\subsection{Encoding circuit for codes}\n\nIn the rest of this section we define the basic quantum gates using\nwhich we construct the encoding circuit for the code described above.\nWe will also outline the encoding algorithm. It is to be noted that\nfor a fixed $q$, these basic quantum gates over $L^2(\\GF{q})$ can be\nimplemented easily over any universal set of quantum gates.\n\n\\begin{tabular}{|l|l|}\n\\hline\n&\\\\\nGate & Definition\\\\\n\\hline\n&\\\\\nInvertor & $\\mathcal{I} \\ket{a} = \\ket{-a}, \\ a \\in \\GF{q}$\\\\\n\\hfill{}\n&\\\\\nControl-$U$ & $C\\textrm{-}U \\ket{a}\\ket{b} = \\ket{a}\\ket{ a + b},\n \\ \\ a,b \\in \\GF{q}$\\\\\n&\\\\\nControl-$V$ & $C\\textrm{-}V\\ket{a}\\ket{b} = \\omega(ab) \\ket{a} \n\\ket{b}, \\ \\ a,b \\in \\GF{q}$\\\\\n&\\\\\nControl-Control-$U$ & $CC\\textrm{-}U \\ket{a,b,c} = \\ket{a,b,c + ab},\n \\ \\ a,b,c \\in \\GF{q}$\\\\\n&\\\\\nControl-Control-$V$ & $CC$-$V \\ket{a,b,c} = \\omega( c + a b) \\ket{a,b,c},\n \\ \\ a,b,c \\in \\GF{q}$\\\\\n&\\\\\nFourier Transform & $F \\ket{a} = \\frac{1}{\\sqrt{q}} \n\\sum_{x \\in \\GF{q}} \\omega(ax) \\ket{x}, \\ \\ a\\in\\GF{q}$\\\\\n&\\\\\n\\hline\n\\end{tabular}\n\n\\vspace{5mm}\n\nNext, for any gate $C$-$f$ of two arguments $a,b \\in \\GF{q}$ defined\nas\n\\[\nC\\textrm{-}f \\ket{a}\\ket{b} = \\ket{a}\\ket{f(a,b)},\n\\]    \nwe extend it to an operator $C\\textrm{-}f_n$ with two arguments $\\a,\\b\n\\in \\GF[n]{q}$ as follows (see Figure~\\ref{figCfn})\n\\[\nC\\textrm{-}f_n \\ket{\\a}\\ket{\\b} = C\\textrm{-}f_n \\ket{a_1a_2\\ldots a_n}\n\\ket{b_1b_2\\ldots b_n} = \\ket{\\a} \\ket{f(a_1,b_1) , f(a_2,b_2), \\ldots\n,f(a_n,b_n)}.\n\\]\n\nIn a similar fashion we extend the gate $CC\\textrm{-}f$ with three\narguments $a,b,c \\in \\GF{q}$ to $CC$-$f_n$ defined on $\\a,\\b,\\c \\in\n\\GF[n]{q}$. In the circuits we draw a $C$-$f_n$ gate with thick wires\nto indicate that it takes a tuple from $\\GF[n]{q}$.\n\nGiven the message $\\c,\\d$, we can describe the main steps of the\nencoding algorithm as follows.\n\n\\begin{enumerate}\n\\item Initialize $\\ket{R} := \\ket{0^n}$\n\\item Apply $C$ on $R$ so that\n  \n\\[\n  \\ket{R} = \\sqrt{\\frac{1}{q^{n-1}}}\\sum_{\\x \\in C}\\ket{\\x}.\n\\]\n  \n\\item Apply $C$-$V_n$ on $\\ket{\\bf c}\\ket{R}$ so that\n    \n\\[\n\\ket{\\bf c}\\ket{R} \\mapsto \\ket{\\bf c} \\otimes (\\frac{1}{\\sqrt{q^{n-1}}}\n\\sum_{\\x \\in C} \\omega({\\bf c}^T \\x ) \\ket{\\x}).\n\\]\n  \n\\item Apply $C$-$U_n$ on $\\ket{\\d}\\ket{R}$\n    \n\\[\n\\ket{\\d}\\ket{R} \\mapsto \\ket{\\d} \\otimes ( \\frac{1}{\\sqrt{q^{n-1}}}\n    \\sum_{\\x \\in C}\\omega{\\c^T \\x}\\ket{\\x + \\d}.\n\\]\n  \n\\item Apply the circuit in Figure~\\ref{figmatvect} on\n    $\\ket{R}\\ket{D}\\ket{0^n}$ \n\\[\n\\ket{R}\\ket{D}\\ket{0^n} \\mapsto \\frac{1}{\\sqrt{q^{n-1}}}\\sum_{\\x \\in\n  C} \\omega(\\c^T \\x) \\ket{\\x+\\d,D(\\x+\\d)}\\ket{D}.\n\\]\n  \n\\item Apply $C$-$V_n$ on\n    $\\ket{R_1}=\\frac{1}{\\sqrt{q^{n-1}}}\\sum_{\\x \\in C} \\omega(\\c^T \\x)\n    \\ket{\\x+\\d,D(\\x+\\d)}$ to get\n    \n\\[\n\\ket{R_1} \\mapsto \\frac{1}{\\sqrt{q^{n-1}}}\\sum_{\\x \\in C}\n\\omega((\\x+\\d)^TD(\\x+\\d) + \\c^T \\x) \\ket{\\x+\\d,D(\\x+\\d)}.\n\\]\n\\end{enumerate}\n\nThe complete encoding circuit along with the building blocks is given\nin Figures \\ref{figbasicgates}, \\ref{figCfn}, \\ref{figdotproduct},\n\\ref{figmatvect}, \\ref{figuniformC}, and \\ref{figencode}.\n\n\\section{Decoding for a class of nonstabilizer codes}\n\nLet $\\C\\subseteq\\Hin$ be a $t$-error correcting quantum code\nsatisfying the conditions of Theorem~\\ref{distdtheorem}, with Fourier\ndescription $B$, and such that its projection $P$ has support in the\nGottesman subgroup $\\S$ of the error group $\\E$. The two conditions that\n$\\C$ satisfies are:\n\n\\begin{enumerate}\n  \n\\item \nFor each $g \\in \\S$ such that $\\wt(g)\\leq 2t$\n\\[\n\\chi_g( u_1^{-1} u_2) = 1 \\textrm{ for all } u_1,u_2 \\in B. \n\\]\n\n\\item \nFor each $g \\in \\E \\setminus \\S$ such that $\\wt(g)\\leq 2t$, and for \n$s\\in S$ we have\n\\[\n\\sum_{u_1,u_2 \\in B} \\chi_{u_2}(s) \\sum_{s_1 }\\gamma(g,s_1)\n\\chi_{s_1} (u_1^{-1} u_2 ) = 0,\n\\]\nwhere $\\gamma(g,s)$ is the scalar such that $\\gamma(g,s) s g = gs$.\n\\end{enumerate}\n\nFor $u \\in \\S$ let $\\S_u$ be the Gottesman group $\\{ \\chi_u(s) s | s \\in\n\\S\\}$. \n\nThe projection operator for the code $\\C_n$\n\n\\[\nP = \\frac{1}{\\#\\S} \\sum_{u \\in B} \\sum_{s \\in \\S} \\chi_u(s) s = \\sum_{u\n  \\in B} P_u,\n\\] \n\nwhere $P_u = \\frac{1}{\\#\\S} \\sum_{s \\in \\S} \\chi_u(s) s$. Note that\n$P_u$ is the projection operator corresponding to the stabilizer code\n$\\C_u$ with $\\S_u$ as stabilizer group for each $u\\in B$. As argued in\nTheorem~\\ref{onbasis}, $P_uP_v=0$ for distinct elements $u,v\\in B$. Let\n$D_u$ denote an orthonormal basis for $\\C_u$, $u\\in B$. Then\n$D=\\bigcup_{u\\in B} D_u$ is an orthonormal basis for $\\C$.\n\nIt suffices to describe the decoding procedure for the encoded message\nas a basis element from $D$ and error $g\\in\\E$ such that $\\wt(g)\\leq\nt$. With out loss of generality let $\\ket{\\psi}\\in D_u$ for some\n$u\\in B$ be the encoded message, and let $g\\in\\E$ of weight at most\n$t$ be the error operator.  The decoding procedure takes\n$g\\ket{\\psi}=\\ket{\\psi'}$ as input and outputs $\\ket{\\psi}$. Let\n$\\{s_1,s_2,\\ldots,s_k\\}$ be an independent generator set for $\\S$.\nNotice that for $1\\leq i\\leq k$\n\n\\[\ns_ig\\ket{\\psi}=\\overline{\\gamma(s_i,g)}\\chi_u(s_i)g\\ket{\\psi}.\n\\]\n\nThus, $g\\ket{\\psi}$ is an eigen vector for operator $s_i$ with eigen\nvalue $\\overline{\\gamma(s_i,g)}\\chi_u(s_i)$.\n\nThe decoding procedure will carry out the following steps. It uses as\nsubroutine the phase estimation algorithm of Kitaev\\cite{NC99}.\n\n\\begin{enumerate}\n\\item Let $\\ket{\\psi'}$ be the received state.\n  \n\\item Apply $s_i$ successively, for each $1\\leq i\\leq k$, and when\n  $s_i$ is applied run Kitaev's phase estimation algorithm to compute\n  the eigen value $\\alpha_i=\\overline{\\gamma(s_i,g)}\\chi_u(s_i)$. Let\n  $\\ket{\\rho}$ be the resulting state.\n  \n\\item If $g=I$ and some $u\\in B$ constitute a solution to the system\n  of $k$ group equations (using a classical algorithm that searches\n  through $B$):\n\\[\n\\alpha_i=\\overline{\\gamma(s_i,g)}\\chi_u(s_i), 1\\leq i\\leq k,\n\\]\n\nthen apply $s_i^{-1}$ for each $1\\leq i\\leq k$ to the state\n$\\ket{\\rho}$ and output that as the decoded state.\n\n\\item If $g=I$ does not give a solution to the $k$ equations, find\n  (using a classical algorithm that searches through $B$) a $g\\neq\n  I\\in\\E$ and the corresponding unique $u\\in B$ which are a solution\n  to the $k$ equations.  Apply $g^{-1}$ to the current state. Then\n  apply $s_i^{-1}$ for each $1\\leq i\\leq k$, and output that as the\n  decoded state.\n\\end{enumerate}\n\nWe now argue the correctness of the procedure. Firstly, notice that if\nthe error operator is $g\\in\\S$ such that $\\wt(g)\\leq t$, then by\nassumption $\\chi_g(u_2) = \\chi_g(u_1)$  for all $u_1,u_2 \\in\nB$. Denote this scalar by $\\lambda$. Notice that for any state\n$\\ket{\\varphi}\\in\\C$, $g\\ket{\\varphi}=\\lambda\\ket{\\varphi}$. Which\nmeans that $g$ introduces only an overall phase. We establish the\nfollowing claim from which the correctness of the procedure follows.\n\n\\begin{claim}\\label{decodeproof}\n\\begin{enumerate}\n\\item If $g=I$ and $u\\in B$ is a solution to the $k$ group equations\n  given above, then $u\\in B$ is the unique solution, and there is no\n  $g\\not\\in\\S$ which is a solution to the equations.\n\\item If $g=I$ is not part of a solution to the $k$ equations, then\n  there is a unique $u\\in B$ and some $g\\not\\in\\S$ that form a\n  solution such that $\\wt(g)\\leq t$.\n\\end{enumerate}\n\\end{claim}\n\n\\begin{claimproof}\n  For the first part, assume that $g=I$ and $u\\in B$ is a solution to\n  the $k$ group equations, and some $g\\not\\in\\S$ and $u'\\in B$ is\n  another solution. Then we have\n  $\\gamma(g,s_i)\\chi_u(s_i)\\overline{\\chi_{u'}(s_i)}=1, 1\\leq i\\leq k$.\n  Since $s_1,s_2,\\ldots,s_k$ generate $\\S$, it implies\n  $\\gamma(g,s)\\chi_u(s)\\overline{\\chi_{u'}(s)}=1$ for all $s\\in\\S$. It\n  is easy to see that this contradicts the second condition of\n  Theorem~\\ref{distdtheorem} for the element $g\\not\\in\\S$ of\n  $\\wt(g)\\leq t$.\n\nFor the second part, notice that any solution $g$ of $\\wt(g)\\leq t$ to\nthe equations is not in $\\S$. For, if $g'\\in\\S$ and $u\\in B$ are a\nsolution then so is $g=I$ and $u\\in B$, because $\\gamma(g',s)=1$ for\nall $s\\in\\S$. Assume to the contrary that there are two distinct\nsolutions $g_1\\not\\in\\S$ and $u\\in B$ and $g_2\\not\\in\\S$ and $u'\\in\nB$, where $\\wt(g_1)\\leq t$ and $\\wt(g_2)\\leq t$. Then, as before, the\n$k$ equations will yield\n\n\\[\n\\gamma(g_1,s)\\chi_u(s)=\\gamma(g_2,s)\\chi_{u'}(s), ~~~~\\forall s\\in\\S.\n\\]\n\nBy rearranging terms we get $\\gamma(g_1^{-1}g_2,s)\\chi_s(u'u^{-1})=1$\nfor all $s\\in\\S$. \n\nNow, if $g_1^{-1}g_2\\not\\in\\S$, then this again contradicts the second\ncondition of Theorem~\\ref{distdtheorem} for the element\n$g_1^{-1}g_2\\not\\in\\S$ of $\\wt(g_1^{-1}g_2)\\leq 2t$.\n\nNext, suppose that $g_1^{-1}g_2\\in\\S$. Then we get $\\chi_s(u'u^{-1})=1$\nfor all $s\\in\\S$ implying that $u=u'$. Thus $u$ is unique. Notice that\nby the first condition of Theorem~\\ref{distdtheorem}, since\n$\\wt(g_1^{-1}g_2)\\leq 2t$, the effect of applying the error\n$g_1^{-1}g_2$ to a state in $\\C$ only introduces an overall phase. Thus,\ndecoding with either $g_1^{-1}$ or $g_2^{-1}$ will coincide upto an\noverall phase. This completes the proof of the claim and correctness\nof the decoding procedure. \n\\end{claimproof}\n\nTo analyze the efficiency of the decoding procedure, we recall from\nNielsen and Chuang\\cite{NC99} that the phase estimation quantum\ncircuit is efficient (polynomial size in $n$). However, solving the\n$k$ group equations involves exhaustive enumeration. This takes time\n$O(n^{O(d)}.  \\# B)$, which is also the dominant term in the entire\ntime bound.\n\n%\\bibliographystyle{plain}\n\\bibliography{./NonStab}\n\n\\newpage\n\nSee Figure~\\ref{figbasicgates} for the basic gates. From these gates\nwe can construct a circuit that computes for any $\\a,\\b \\in \\GF[n]{q}$\nthe dot product $\\sum_i a_i b_i$ (see Figure~\\ref{figdotproduct}). The\nsecond circuit in Figure~\\ref{figdotproduct} is a symbolic\nrepresentation of the circuit (note the thick lines). Using this inner\nproduct circuit we can also define the circuit that takes a $n\\times\nn$ matrix $D$ and a vector $\\a\\in \\GF[n]{q}$ and computes the vector\n$D\\a$ (see Figure~\\ref{figmatvect} note the thick lines and the cut).\n\nWe also need a circuit which will take the vector $\\ket{0^n}$ and\ngenerate the uniform superposition $\\frac{1}{\\sqrt{q^{n-1}}} \\sum_{\\x\n  \\in C} \\ket{\\x}$. This circuit is given in Figure~\\ref{figuniformC}.\n\nSee Figure~\\ref{figencode} for a complete circuit. The other figures\nare the building blocks. Note that the extra$\\ket{D(\\x+\\d)}$ can be\nremoved by inverting it and then applying the circuit in\nfig~\\ref{figmatvect} on $\\ket{\\x+\\d,D(\\x+\\d)}\\ket{D}$.\\\\\n\n\\vspace{1cm}\n\n\\begin{figure}[h]\n  \\input{figs/basicgates.pstex_t}\n  \\caption{Basic Gates}\n  \\label{figbasicgates}\n\\end{figure}\n\n\\begin{figure}[h]\n  \\input{figs/Cfn.pstex_t}\n  \\caption{Circuit computing $C\\textrm{-}f_n$ from $C\\textrm{-}f$}\n  \\label{figCfn}\n\\end{figure}\n\n\n\\begin{figure}[h]\n  \\input{figs/dotproduct.pstex_t}\n  \\caption{Circuit computing the dot product $\\a^T\\b$}\n  \\label{figdotproduct}\n\\end{figure}\n\n\\begin{figure}[h]\n  \\input{figs/matvect.pstex_t}  \n  \\caption{Circuit to compute $D\\x$}\n  \\label{figmatvect}\n\\end{figure}\n\n\\begin{figure}[h]\n  \\input{figs/uniformC.pstex_t}\n  \\caption{Circuit generating $\\sqrt{\\frac{1}{q^{n-1}}} \\sum_{x \\in C} \\ket{x}$}\n  \\label{figuniformC}\n\\end{figure}\n\n\\begin{figure}[h]\n  \\input{figs/encode.pstex_t}\n  \\caption{Complete encoding circuit}\n  \\label{figencode}\n\\end{figure}\n\n\\end{document}\n\n\n", "meta": {"hexsha": "8cb41fef88f262eec91228ec8728815c14a4a108", "size": 68381, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "contents/research/publication/Journal/2004-01-01-Nonstabilizer-codes/NonStab.tex", "max_stars_repo_name": "piyush-kurur-pages/website", "max_stars_repo_head_hexsha": "246dfa730328b45b65840ebed3293e96c497aa86", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-04-16T09:55:17.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-16T09:55:17.000Z", "max_issues_repo_path": "contents/research/publication/Journal/2004-01-01-Nonstabilizer-codes/NonStab.tex", "max_issues_repo_name": "piyush-kurur-pages/website", "max_issues_repo_head_hexsha": "246dfa730328b45b65840ebed3293e96c497aa86", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "contents/research/publication/Journal/2004-01-01-Nonstabilizer-codes/NonStab.tex", "max_forks_repo_name": "piyush-kurur-pages/website", "max_forks_repo_head_hexsha": "246dfa730328b45b65840ebed3293e96c497aa86", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-10T22:18:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T22:18:56.000Z", "avg_line_length": 37.7586968526, "max_line_length": 103, "alphanum_fraction": 0.6460712771, "num_tokens": 25311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.33046813919244383}}
{"text": "\\chapter{Variational Inference for GW Parameter Estimation}\\label{ch:chap_5}\n\nWe note to the reader that this text is a modified version of the \npaper under review here~\\cite{1909.06296}. \n\nSo far, we have introduced fundamental \nconcepts from \\ac{GW} astronomy and \\ac{ML}. We have also provided \na broad survey of how \\ac{ML} is being applied across a variety of \ndomains within \\ac{GW} astronomy. In the previous chapter (Ch.~\\ref{ch:chap_4})\nwe showed one \nof the first implementations of deep learning for \\ac{GW} signal \ndetection and how our approach was able to match the sensitivies \nof standard methods, opening the door for a variety of follow-up \nstudies listed in Ch.~\\ref{ch:chap_3}. We now move on to the more \nchallenging task of applying \\ac{ML} methods towards \\ac{GW} Bayesian \nparameter estimation. We show for the first time that a form of \n\\ac{ML}, variational inference, may be used to produce Bayesian posteriors \nof \\ac{GW} source parameter values given \\ac{GW} time series data in \na fraction of the time taken by more traditional samplers.\n\n\\section{Introduction}\n\n%\n% background\n%\n\\ac{GW} detection is now commonplace~\\cite{PhysRevX.6.041015,PhysRevLett.119.161101} and as \nthe sensitivity of the global network of \\ac{GW} detectors \nimproves, we will observe $\\mathcal{O}(100)$s of transient \n\\ac{GW} events per year~\\cite{2018LRR....21....3A,1304.0670,1811.12907}. The current \nmethods used to estimate their source parameters employ \noptimally sensitive~\\cite{2009CQGra..26o5017S} but computationally \ncostly Bayesian inference approaches~\\cite{1409.7215} where typical \nanalyses have taken between 6 hours and 38 days~\\cite{gracedb_O3} to run. We \ndetermined these values by \ncompiling tables (Tab.~\\ref{tab:o3_events_runtime_1} \nand Tab.~\\ref{tab:o3_events_runtime_2}) containing of all \ndetected events during the O3 observing \nrun using the GraceDB database. We provide in the tables the length of \ntime to complete parameter estimation analyses using the lalinference \npipeline~\\cite{1409.7215}, as well as the predicted source \nclass using the \\texttt{p-astro}~\\footnote{See  \n\\url{https://pypi.org/project/p-astro/}.} computing package.\n~\\chris{Maybe even make a plot of run time vs total inferred mass and runtime vs SNR.}.\n\n%\n% O3 detected events table 1\n%\n\\begin{sidewaystable}\n\\centering\n\\caption[O3 events table containing information on detected event \nparameter estimation runtimes from April 8, 2019 - September 10, \n2019]{O3 events \ntable containing information on detected event parameter estimation \nruntimes and classification \nprobability (according to GraceDB) from April 8, 2019 - September 10, \n2019. The amount of \ntime for a run to produce \nfinal parameter estimation results is given by the difference between the \nevent time and the first reported parameter estimation results from \nlalinference. We do not show here any detection events flagged \nby GraceDB that were later retracted. Columns with a ``-'' are values \nwhich were either not reported by GraceDB, or could not be found.}\n\\resizebox{21cm}{!}{\n\\begin{tabular}{l*{6}{c}r}~\\label{tab:o3_events_runtime_1}\n\\\\\n\\hline\nEvent Name & Classification & Event Time & First LAL Results & Results Delay \\\\\n\\hline\n\\hline\nS190408an & BBH ($>99\\%$) & April 8, 2019 18:18:02 UTC & 2019-04-14 05:37:36 UTC & 5 d, 11 hrs, 19 min, 34 s \\\\\n\\hline\nS190412m & BBH ($>99\\%$) & April 12, 2019 05:30:44 UTC & - & - \\\\\n\\hline \nS190421ar & BBH ($97\\%$), & April 21, 2019 21:38:56 UTC & \nMay 3, 2019 08:18:56 UTC & 11 d, 10 hrs, 40 mins, 0 s \\\\\n& Terrestrial ($3\\%$) & & & \\\\\n\\hline \nS190425z & BNS ($>99\\%$) & April 25, 2019 08:18:05 UTC & \nApr 26, 2019 11:02:22 UTC & 1 d, 2 hrs, 44 mins, 17 s \\\\\n\\hline \nS190426c & BNS ($49\\%$), MassGap ($24\\%$), & \nApril 26, 2019 15:21:55 UTC & Apr 28, 2019 17:11:32 UTC & \n2 d, 1 hr, 49 min, 37 s \\\\ \n& Terrestrial ($14\\%$), NSBH ($13\\%$) & & & \\\\ \n\\hline \nS190503bf & BBH ($96\\%$), MassGap ($3\\%$) & May 3, 2019 18:54:04 UTC & \nJun 11, 2019 08:18:41 UTC & 38 d, 13 hrs, 24 min, 37 s \\\\\n\\hline \nS190510g & Terrestrial ($58\\%$), BNS ($42\\%$) & May 10, 2019 02:59:39 UTC & \nJun 3, 2019 16:19:23 UTC & 24 d, 13 hrs, 19 min, 44 s \\\\\n\\hline \nS190512at & BBH ($99\\%$), Terrestrial ($1\\%$) & May 12, 2019 18:07:14 UTC \n& May 17, 2019 15:27:36 UTC & 4 d, 21 hrs, 20 min, 22 s \\\\\n\\hline\nS190513bm & BBH ($94\\%$), MassGap ($5\\%$) & May 13, 2019 20:54:28 UTC & \nMay 16, 2019 14:43:37 UTC & 2 d, 17 hrs, 49 min, 9 s \\\\\n\\hline\nS190517h & BBH ($98\\%$), MassGap ($2\\%$) & May 17, 2019 05:51:01 UTC & \nMay 21, 2019 15:22:31 UTC & 4 d, 9 hrs, 31 min, 30 s \\\\\n\\hline \nS190519bj & BBH ($96\\%$), Terrestrial ($4\\%$) & May 19, 2019 15:35:44 UTC \n& May 22, 2019 10:05:27 UTC & 2 d, 18 hrs, 29 min, 43 s \\\\\n\\hline \nS190521g & BBH ($97\\%$), Terrestrial ($3\\%$) & May 21, 2019 03:02:29 UTC\n& May 21, 2019 09:11:04 UTC & 0 d, 6 hrs, 8 min, 35 s \\\\\n\\hline \nS190521r & BBH ($>99\\%$) & May 21, 2019 07:43:59 UTC & \nMay 24, 2019 21:22:47 UTC & 3 d, 13 hrs, 38 min, 48 s \\\\ \n\\hline \nS190602aq & BBH ($99\\%$) & June 2, 2019 17:59:27 UTC & \nJun 7, 2019 14:21:51 UTC & 4 d, 20 hrs, 22 min, 24 s \\\\\n\\hline\nS190630ag & BBH ($94\\%$), MassGap ($5\\%$) & June 30, 2019 18:52:05 UTC \n& Jul 1, 2019 18:09:39 UTC & 0 d, 23 hrs, 17 min, 34 s \\\\\n\\hline\nS190701ah & BBH ($93\\%$), Terrestrial ($7\\%$) & \nJuly 1, 2019 20:33:06 UTC & Jul 3, 2019 02:08:14 UTC & 1 d, 5 hrs, \n35 min, 8 s \\\\ \n\\hline\nS190706ai & BBH ($99\\%$), Terrestrial ($1\\%$) & \nJuly 6, 2019 22:26:41 UTC & Jul 8, 2019 05:17:16 UTC & 1 d, 6 hrs, 50 min, \n35 s \\\\\n\\hline\nS190707q & BBH ($>99\\%$) & July 7, 2019 09:33:26 UTC & \nJul 9, 2019 17:48:32 UTC & 2 d, 8 hrs, 15 min, 6 s \\\\\n\\hline\nS190718y & Terrestrial ($98\\%$), BNS ($2\\%$) & July 18, 2019 14:35:12 UTC \n& - & - \\\\\n\\hline\nS190720a & BBH ($99\\%$), Terrestrial ($1\\%$) & July 20, 2019 00:08:36 UTC & \nJul 21, 2019 13:54:03 UTC & 1 d, 13 hrs, 45 min, 27 s \\\\\n\\hline\nS190727h & BBH ($92\\%$), Terrestrial ($5\\%$), & July 27, 2019 06:03:33 UTC\n& Jul 31, 2019 20:08:10 UTC & 4 d, 14 hrs, 4 min, 37 s \\\\\n& MassGap ($3\\%$) & & & \\\\\n\\hline\nS190728q & BBH ($95\\%$), MassGap ($5\\%$) & July 28, 2019 06:45:10 UTC & \nJul 30, 2019 10:32:36 UTC & 2 d, 3 hrs, 47 min, 26 s \\\\\n\\hline\nS190814bv & NSBH ($>99\\%$) & Aug. 14, 2019 21:10:39 UTC & \nAug 15, 2019 09:02:34 UTC & 11 hrs, 51 min and 55 s \\\\\n\\hline\nS190828j & BBH ($>99\\%$) & Aug. 28, 2019 06:34:05 UTC & \nAug 30, 2019 07:58:27 UTC & 2 d, 1 hr, 24 min and 22 s \\\\\n\\hline\nS190828l & BBH ($>99\\%$) & Aug. 28, 2019 06:55:09 UTC & \nAug 29, 2019 15:43:57 UTC & 1 d, 8 hrs, 48 min and 48 s \\\\\n\\hline\nS190901ap & BNS ($86\\%$), Terrestrial ($14\\%$) & \nSept. 1, 2019 23:31:01 UTC & Sep 2, 2019 11:21:59 UTC & \n11 hrs, 50 min, 58 s \\\\\n\\hline\nS190910d & NSBH ($98\\%$), Terrestrial ($2\\%$) & Sept. 10, 2019 01:26:19 UTC & \nSep 10, 2019 22:33:57 UTC & 21 hrs, 7 min, 38 s \\\\\n\\end{tabular} \n}\n\\end{sidewaystable}\n\n%\n% O3 detected events table 2\n%\n\\begin{sidewaystable}\n\\centering\n\\caption[O3 events table containing information on detected event \nparameter estimation runtimes from September 10, 2019 - March 16, 2020.]{\nO3 events table containing information on detected event parameter \nestimation runtimes and classification \nprobability (according to GraceDB) from September 10, 2019 - \nMarch 16, 2020. \nThe amount of time for a run to produce \nfinal parameter estimation results is given by the difference between the \nevent time and the first reported parameter estimation results from \nlalinference. We do not show here any detection events flagged \nby GraceDB that were later retracted. Columns with a ``-'' are values \nwhich were either not reported by GraceDB, or could not be found.}\n\\resizebox{21cm}{!}{\n\\begin{tabular}{l*{6}{c}r}~\\label{tab:o3_events_runtime_2}\n\\\\\n\\hline\nEvent Name & Classification & Event Time & First LAL Results & Results Delay \\\\\n\\hline\n\\hline\nS190910h & BNS ($61\\%$), Terrestrial ($39\\%$) & \nSept. 10, 2019 08:29:58 UTC & Sep 11, 2019 17:11:34 UTC & \n1 d, 8 hrs, 41 min, 36 s \\\\\n\\hline\nS190915ak & BBH ($99\\%$) & Sept. 15, 2019 23:57:02 UTC & 2019-09-17 13:42:31 UTC \n& 1 d, 13 hrs, 45 min, 29 s \\\\\n\\hline\nS190923y & NSBH ($68\\%$), Terrestrial ($32\\%$) & \nSept. 23, 2019 12:55:59 UTC & - & - \\\\\n\\hline\nS190924h & MassGap ($>99\\%$) & Sept. 24, 2019 02:18:46 UTC & \n2019-09-27 19:17:41 UTC & 3 d, 16 hrs, 58 min, 55 s \\\\\n\\hline\nS190930s & MassGap ($95\\%$), Terrestrial ($5\\%$) & \nSept. 30, 2019 13:35:41 UTC & 2019-10-04 19:25:05 UTC & \n4 d, 5 hrs 49 min, 24 s \\\\\n\\hline\nS190930t & NSBH ($74\\%$), Terrestrial ($26\\%$) & \nSept. 30, 2019 14:34:07 UTC & - & - \\\\\n\\hline\nS191105e & BBH ($95\\%$), Terrestrial ($5\\%$) & \nNov. 5, 2019 14:35:21 UTC & 2019-11-12 12:51:56 UTC & \n6 d, 22 hrs, 16 min, 35 s \\\\\n\\hline\nS191109d & BBH ($>99\\%$) & Nov. 9, 2019 01:07:17 UTC & \n2019-11-10 14:31:40 UTC & 1 d, 13 hrs, 24 min, 23 s \\\\\n\\hline\nS191129u & BBH ($>99\\%$) & Nov. 29, 2019 13:54:17 UTC & \n2019-12-05 13:54:17 UTC & 6 d, 13 min, 48 s \\\\\n\\hline\nS191204r & BBH ($>99\\%$) & Dec. 4, 2019 17:15:26 UTC & - & - \\\\\n\\hline\nS191205ah & NSBH ($93\\%$), Terrestrial ($7\\%$) & \nDec. 5, 2019 21:52:08 UTC & - & - \\\\\n\\hline\nS191213g & BNS ($77\\%$), Terrestrial ($23\\%$) & \nDec. 13, 2019 04:34:08 UTC & - & - \\\\\n\\hline\nS191215w & BBH ($>99\\%$) & \nDec. 15, 2019 22:30:52 UTC & 2019-12-20 09:18:36 UTC & 4 d, \n10 hrs, 47 min, 44 s \\\\\n\\hline\nS191216ap & BBH ($99\\%$) & Dec. 16, 2019 21:33:38 UTC & - & - \\\\\n\\hline\nS191222n & BBH ($>99\\%$) & Dec. 22, 2019 03:35:37 UTC & 2019-12-22 22:06:36 UTC \n& 18 hrs, 30 min, 59 s \\\\\n\\hline\nS200105ae & Terrestrial ($97\\%$), NSBH ($3\\%$) & Jan. 5, 2020 16:24:26 UTC\n& 2020-01-09 16:56:28 UTC & 4 d, 32 min, 2 s \\\\\n\\hline\nS200112r & BBH ($>99\\%$) & Jan. 12, 2020 15:58:38 UTC & 2020-01-14 15:54:35 UTC \n& 1 d, 23 hrs, 55 min, 57 s \\\\\n\\hline\nS200114f & - & Jan. 14, 2020 02:08:18 UTC & - & - \\\\\n\\hline\nS200115j & MassGap ($>99\\%$) & Jan. 15, 2020 04:23:09 UTC & \n2020-01-20 04:51:25 UTC & 5 d, 28 min, 16 s \\\\\n\\hline \nS200128d & BBH ($97\\%$), Terrestrial ($3\\%$) & Jan. 28, 2020 02:20:11 UTC \n& 2020-01-30 09:35:52 UTC & 2 d, 7 hrs, 15 min, 41 s \\\\ \n\\hline \nS200129m & BBH ($>99\\%$) & Jan. 29, 2020 06:54:58 UTC & \n2020-02-03 00:08:54 UTC & 4 d, 17 hrs, 13 min, 56 s \\\\\n\\hline\nS200208q & BBH ($99\\%$) & Feb. 8, 2020 13:01:17 UTC & 2020-02-10 21:01:12 UTC \n& 2 d, 7 hrs, 59 min, 55 s \\\\\n\\hline\nS200213t & BNS ($63\\%$), Terrestrial ($37\\%$) & Feb. 13, 2020 04:10:40 UTC \n& - & - \\\\\n\\hline\nS200219ac & BBH ($96\\%$), Terrestrial ($4\\%$) & Feb. 19, 2020 09:44:15 UTC \n& - & - \\\\\n\\hline\nS200224ca & BBH ($>99\\%$) & Feb. 24, 2020 22:22:34 UTC & \n2020-02-26 13:49:38 UTC &  1 d, 15 hrs, 27 min, 4 s \\\\ \n\\hline\nS200225q & BBH ($96\\%$), Terrestrial ($4\\%$) & Feb. 25, 2020 06:04:21 UTC \n& 2020-02-26 07:42:24 UTC & 1 d, 1 hrs, 38 min, 3 s \\\\\n\\hline\nS200302c & BBH ($89\\%$), Terrestrial ($11\\%$) & March 2, 2020 01:58:11 UTC \n& 2020-03-02 19:06:13 UTC & 17 hrs, 8 min, 2 s \\\\\n\\hline\nS200311bg & BBH ($>99\\%$) & March 11, 2020 11:58:53 UTC & \n2020-03-13 04:55:55 UTC & 1 d, 16 hrs, 57 min, 2 s \\\\\n\\hline\nS200316bj & MassGap ($>99\\%$) & March 16, 2020 21:57:56 UTC & \n2020-03-21 02:46:41 UTC & 4 d, 4 hrs, 48 min, 45 s \\\\\n\\hline\n\\end{tabular}    \n}\n\\end{sidewaystable}\n\n%\n% rationale\n%\nFor \\ac{BNS} and \\ac{NSBH} systems prompt counterpart \\ac{EM} signatures are expected on timescales of 1~s -- 1~minute and the current fastest method for alerting \\ac{EM} follow-up observers~\\cite{2016PhRvD..93b4013S}, can provide estimates in $\\mathcal{O}(1)$ minute, on a limited range of key source parameters~\\chris{You could rephrase to refer to O3 results only and use the gracedb website to verify these low latency times - also include them in the table.}. \n%\n% results\n%\nHere we show that a \\ac{CVAE}~\\cite{1904.06264,1812.04405} pre-trained \non \\ac{BBH} signals can return Bayesian posterior probability estimates. \nThe training procedure need only be performed once for a given \nprior parameter space and detector network configuration and the \nresulting trained machine can then generate samples describing the \nposterior distribution $\\sim 6$ orders of magnitude faster \nthan existing techniques.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% INTRODUCTION\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% introduction - this section has to expand upon what has mentioned in the\n% abstract background (which was only ~50 words). It needs to cover the state of\n% the gravitational wave field and the number of detections expected in the next\n% ~5 years. It should briefly discuss the issue of low latency EM follow up. It\n% needs to cover Bayesian inference (not in too much detail) and the signal model\n% we are interested in here (again, not too much detail but enough for the\n% average Nature reader). It then needs to introduce machine learning and focus\n% mainly on how our scheme works. We also need to include a statement about how\n% the training data priors affect the result (are they really the priors?)\n%\n% Intro to the detection era with the LVC\n%\nWith the overwhelmingly successful observation runs of O1, O2 and now \nO3 complete, \\ac{LIGO} and Virgo have produced a large catalogue of \n\\ac{GW} data covering both \\ac{BBH} and \\ac{BNS} signals~\\cite{2010.14527}. \nOver the next five years we expect the number of detections to \nincrease to be upwards of $\\sim180$ \\ac{BNS} and $\\sim400$ \n\\ac{BBH} events per year~\\cite{1304.0670,1811.12907,2018LRR....21....3A}. \nThis large influx in the number of detections will put an \nincreased amount of pressure on the current computationally \ncostly \\ac{GW} inference methods used for parameter estimation.  \n\n%\n% From GW detection, to parameter estimation\n%\n\nThe problem of detecting \\acp{GW}s has largely been solved through the \nuse of template based matched-filtering, a process recently \nreplicated using machine learning\ntechniques\n~\\cite{GEORGE201864,PhysRevLett.120.141103,\nGebKilParHarSch,2021arXiv210403961Y}. Once a \\ac{GW} has been \nidentified through this process, Bayesian inference, known \nto be the optimal approach~\\cite{2009CQGra..26o5017S}, is used to \nextract information about the source parameters of the detected \\ac{GW} signal.\n\n%\n% Set up parameter estimation problem\n%\nIn the standard Bayesian \\ac{GW} inference approach (See \nSec.~\\ref{sec:bayesian_inference} of \nCh.~\\ref{ch:chap_1}), we assume a \nsignal and noise model and both may have unknown parameters that we \nare either interested in inferring or prefer to marginalise away. Each \nparameter is given a prior astrophysically motivated probability \ndistribution and in the \\ac{GW} case, we\ntypically assume a Gaussian additive noise model (in reality, the d\nata is not truly Gaussian). Given a noisy \\ac{GW} waveform, \nwe would like to find an optimal procedure for inferring \nsome set of the unknown \\ac{GW} parameters. Such a procedure \nshould be able to give us an accurate estimate of the parameters \nof our observed signal, whilst accounting for the uncertainty \narising from the noise in the data.\n\n%\n% Describe Bayes Theorem\n%\nAccording to Bayes' Theorem, a posterior probability distribution on a set of parameters, conditional on the measured data, can be represented as\n%\n\\begin{align}\\label{eq:bayes_theorem} \np(x|y) &\\propto p(y|x) p(x), \n\\end{align}\n%\nwhere $x$ are the parameters, $y$ is the observed data, \n$p(x|y)$ is the posterior, $p(y|x)$ is \nthe likelihood, and $p(x)$ is the prior on the parameters. The \nconstant of proportionality, which we omit here, is $p(y)$, the \nprobability of our data, known as the Bayesian evidence or the \nmarginal likelihood. We typically ignore $p(y)$ since it is a constant \nand for parameter estimation purposes we are only interested in the \nshape of the posterior (See Sec.~\\ref{sec:bayesian_inference} of \nCh.~\\ref{ch:chap_1} for further details).\n\n%\n% brief statement on the sampling algorithms\n%\nDue to the size, dimensionality and volume of the parameter \nspace typically encountered in \\ac{GW} parameter estimation and the \nvolume of data analysed, we must stochastically sample the \nparameter space in order to estimate the posterior. Sampling is \ndone using a variety of techniques including Nested\nSampling~\\cite{skilling2006,cpnest,dynesty} and Markov chain \nMonte Carlo methods~\\cite{emcee,ptemcee}. The primary software \ntools used by the \\ac{LIGO} parameter estimation analysis \nare \\texttt{LALInference} and\n\\texttt{Bilby}~\\cite{1409.7215,1811.02042}, which offer \nmultiple sampling methods.  \n  \n%\n% Intro to machine learning section\n%\nMachine learning has featured prominently in many areas of \n\\ac{GW} research over the last few years. These techniques have \nshown to be particularly promising in signal\ndetection~\\cite{GEORGE201864,PhysRevLett.120.141103,GebKilParHarSch},\nglitch classification~\\cite{0264-9381-34-6-064003}, earthquake\nprediction~\\cite{Coughlin_2017}, and to augment existing \nBayesian sampling methods~\\cite{10.1111/j.1365-2966.2011.20288.x}.\nWe also highlight recent developments in \\ac{GW} parameter \nestimation (independent to this work) where one- and two-dimensional \nmarginalised Bayesian posteriors are produced rapidly using \nneural networks~\\cite{2019arXiv190905966C}, and where \nnormalised flows in conjunction with \\acp{CVAE} can reproduce \nBayesian posteriors for a single \\ac{GW} detector\ncase~\\cite{PhysRevD.102.104057,2008.03312}. These methods, \nincluding the one presented in this paper, are known as \n``likelihood-free'' approaches in which there is no requirement for \nexplicit likelihood evaluation~\\cite{Cranmer201912789}, only \nthe need to sample from the likelihood. Nor is it the case that \npre-computed posterior distributions are required in the training procedure.\n\n%\n% Introduce CVAEs\n%\nRecently, a type of neural network known as \\ac{CVAE} was shown to \nperform exceptionally well when applied towards computational \nimaging inference~\\cite{1904.06264,NIPS2015_5775}, text to \nimage inference~\\cite{1512.00570}, high-resolution synthetic \nimage generation~\\cite{1612.00005}, \nend-to-end text-to-speech synthesis~\\cite{2021arXiv210606103K}, and the fitting of incomplete \nheterogeneous data~\\cite{1807.03653}. \\acp{CVAE}, as part of the variational \nfamily of inference techniques are ideally suited to the \nproblem of function approximation and have the potential to \nbe significantly faster than existing\napproaches. It is therefore this type of \\ac{ML} \nnetwork that we apply in the \\ac{GW} case to accurately \napproximate the Bayesian posterior\n$p(x|y)$, where $x$ represents the physical parameters that govern the \\ac{GW} signal, \nand are the quantities we are interested in inferring. The data $y$ represents the \nnoisy measurement containing the \\ac{GW} signal and obtained from a network of \\ac{GW} detectors. \n\n%\n% Brief introduction to loss functions used in the neural networks\n%\nThe construction of a \\ac{CVAE} begins with the definition \nof a quantity to be minimised (referred to as a cost, or loss function). In \nour case we take the expectation over the cross entropy\n%\n\\begin{align}\\label{eq:cross_ent} \nH(p,r) &= - \\left \\langle \\int dx\\, p(x|y) \\log r_{\\theta}(x|y) \\right \\rangle \n\\end{align}\n%\nbetween the true posterior $p(x|y)$ and \n$r_{\\theta}(x|y)$, the parametric distribution that \nwe will use neural networks to model and which we aim to be equal to \nthe true posterior. The expectation value is taken over different realisations of signal \nand noise, $y$. The parametric model is\nconstructed from a combination of 2 (encoder and decoder) neural networks $r_{\\theta_1}(z|y)$ and $r_{\\theta_2}(x|y,z)$ where\n%\n\\begin{align}\\label{eq:latent_model}\nr_{\\theta}(x|y) = \\int dz\\,r_{\\theta_1}(z|y)r_{\\theta_2}(x|y,z).\n\\end{align}\n%\nIn this case the $\\theta$ subscripts represent sets of trainable neural network parameters and \nthe variable $z$ represents locations within a \\emph{latent space}. This latter object is \ntypically a lower dimensional space within which an encoder can represent the input \ndata, and via marginalisation \nover $z$ allows the construction of a rich family of possible probability densities of $x$.\n\nStarting from Eq.~\\ref{eq:cross_ent} it is possible to derive a computable bound for \nthe cross-entropy that is reliant on the $r_{\\theta_1}$ and $r_{\\theta_2}$ \nnetworks and a third ``recognition'' encoder\nnetwork $q_{\\phi}(z|x,y)$ governed by the trainable parameter-set $\\phi$. \nThe details of the derivation are described in the cost function derivation section \n(Sec.~\\ref{sec:vit_cost_derivation}) and in~\\cite{1904.06264} but equate to an \noptimisation of the \\ac{ELBO}. The final form of the cross-entropy \ncost function is given by the bound\n%\n\\begin{align}\\label{eq:cost3} H \\lesssim\n\\frac{1}{N}\\sum_{n=1}^{N_{\\text{b}}}\\Big[\\overbrace{-\\log\nr_{\\theta_{2}}(x_{n}|z_{n},y_{n})}^{L}\n+\\overbrace{\\text{KL}\\left[q_{\\phi}(z|x_{n},y_{n})||r_{\\theta_{1}}(z|y_{n})\\right]}^{\\text{KL}}\\Big],\n\\end{align}\n%\nwhich is also represented graphically in Fig.~\\ref{fig:network_config}. The cost \nfunction is composed of 2 terms, the ``reconstruction'' cost $L$ which is a \nmeasure of how well the decoder network $r_{\\theta_2}$ predicts the true signal \nparameters $x$, and the \\ac{KL}-divergence cost that measures the similarity \nbetween the latent space distributions modelled by the $r_{\\theta_1}$ and $q_{\\phi}$ \nencoder networks. In practice, for each iteration of the training procedure, the \nintegrations over $x,y$ and $z$ are approximated by a sum over a\nbatch of $N_{\\text{b}}$ draws from the user defined prior $p(x)$, \nthe known likelihood $p(y|x)$, and the recognition function \n$q_{\\phi}(z|,x,y)$. Details of the training procedure are given in \nSec.~\\ref{sec:training_procedure}.  \n\n%\n% brief mention of differences to a standard CVAE\n%\nThe implementation of the \\ac{CVAE} that we employ in this chapter has \na number of specific \nfeatures that were included in order to tailor the analysis to \\ac{GW} signals. \nThe details of these enhancements are described in the network design \n(Sec.~\\ref{sec:network_design}), training procedure\n(Sec.~\\ref{sec:training_procedure}), data augmentation\n(Sec.~\\ref{sec:vit_data_aug}), and phase/polarisation angle reparameterisation \n(Sec.~\\ref{sec:phipsi_repar}) \nsections but in summary, the \nprimary modifications are as follows, 1) Physically appropriate output decoder \ndistributions are used for each output parameter: \nvon Mises-Fisher distribution on the \nsky location parameters, von Mises distributions on all parameters \nwith cyclic prior bounds,  \nand truncated Gaussians for\nparameters with defined prior bounds. 2) Each of the functions \n$r_{\\theta_1},r_{\\theta_2}$, and $q_{\\phi}$ are modelled using deep \nconvolutional neural networks with multi-detector timeseries represented as \nindependent input channels. 3) The $r_{\\theta_1}$ encoder models an $M=32$ \ncomponent Gaussian mixture model within the $n_{z}=15$ \ndimensional latent space in \norder to capture the corresponding typical multi-modal\nnature of \\ac{GW} posterior\ndistributions. 4.) All cyclic parameters are represented as points \nin an abstract 2D plane. In the next section, we will now \nderive the cost function used \nto train the entire \\ac{CVAE} outlined above.\n\n\n\\begin{figure}\n    \\begin{center}\n    \\includegraphics[width=0.75\\columnwidth]{figures/network_setup.png}\n    \\caption{\\label{fig:network_config} \n     The configuration of the \\ac{CVAE} neural network. During training (left-hand side), a training set of noisy \\ac{GW} signals ($y$) and their corresponding true parameters ($x$) are given as input to encoder network $q_{\\phi}$, while only $y$ is given to encoder network $r_{\\theta_1}$. The \\ac{KL}-divergence (Eq.~\\ref{eq:kl}) is computed between the encoder output latent space representations ($\\mu_q$ and $\\mu_r$) forming one component of the total cost function. Samples ($z_q$) from the $q_{\\phi}$ latent space representation are generated and passed to the decoder network $r_{\\theta_2}$ together with the original input data $y$. The output of the decoder ($\\mu_x$) describes a distribution in the physical parameter space and the cost component $L$ is computed by evaluating that distribution at the location of the original input $x$. When performed in batches this scheme allows the computation of the total cost function Eq.~\\ref{eq:cost3}. After having trained the network and therefore having minimised the cross-entropy $H$, the testing stage (right-hand side) is performed using only the $r_{\\theta_1}$ encoder and the $r_{\\theta_2}$ decoder to produce samples ($x_{\\text{samp}}$). These samples are drawn from the distribution $r_{\\theta}(x|y)$ (Eq.~\\ref{eq:latent_model}) and accurately model the true posterior $p(x|y)$.}\n    \\end{center}\n\\end{figure}\n\n\n%% Here is the endmatter stuff: Supplementary Info, etc.\n%% Use \\item's to separate, default label is \"Acknowledgements\"\n%\n% What is an autoencoder?\n%\n\\section{VItamin Cost Function Derivation}\\label{sec:vit_cost_derivation}\n%\nA \\ac{CVAE} is a form of variational autoencoder that is conditioned on an observation, \nwhere in our case the observation is a one-dimensional \\ac{GW} timeseries \nsignal $y$, over a multi-detector network. The autoencoders from which variational \nautoencoders are derived are typically used for problems involving image reconstruction \nand/or dimensionality reduction. They perform a regression task whereby the \nautoencoder attempts to predict its own given input (model the identity function) through a \n``bottleneck layer'' --- a limited and therefore distilled representation of the input \nparameter space. An autoencoder is composed of two neural networks, an encoder and \na decoder~\\cite{gallinari1987memoires}. The encoder network takes as input a vector, where the \nnumber of dimensions is a fixed number predefined by the user. The encoder converts the \ninput vector into a (typically) lower dimensional space, referred to as the \n{\\it{latent space}}. A representation of the data in the latent space is passed to \nthe decoder network which generates a reconstruction of the original input data to \nthe encoder network. Through training, the two sub-networks learn how to efficiently \nrepresent a dataset within a lower dimensional latent space which will take on the most \nimportant properties of the input training data. In this way, the data can be compressed with \nlittle loss of fidelity. Additionally, the decoder simultaneously learns to decode the \nlatent space representation and reconstruct that data back to its original form (the input data).\n\n%\n% What is a variational autoencoder?\n%\nThe primary difference between a variational autoencoder~\\cite{1812.04405} and an \nautoencoder concerns the method by which locations within the latent space are produced. \nIn our variant of the variational autoencoder, the output of the encoder is interpreted \nas a set of parameters governing statistical\ndistributions in the latent space. In proceeding to the decoder network, samples \nfrom the latent space ($z$) are randomly drawn from these distributions and fed \ninto the decoder, therefore adding an element of variation into the process. A particular \ninput can then have a range of possible outputs. Any trainable network architectures \ncan be used in both the decoder and the encoder networks and within \n\\texttt{VItamin} we use deep convolutional neural networks in all cases.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Remind the reader about the point of the cost function \n%\nWe will now derive the cost function and the corresponding network structure and \nwe begin with the statement defining the aim of the analysis. We wish to obtain a \nfunction that reproduces the posterior distribution (the probability of our \nphysical parameters $x$ given some measured data $y$). The cross-entropy between \n2 distributions is defined in Eq.~\\ref{eq:cross_ent} where we have made the \ndistributions explicitly conditional on $y$ (our measurement). In this case \n$p(x|y)$ is the target distribution (the true posterior) and $r_{\\theta}(x|y)$ is the \nparametric distribution that we will use neural networks \nto construct. The variable $\\theta$ represents the trainable neural network parameters. \n\n%\n% Marginalise over different data realisations \n%\nThe cross-entropy is minimised when $p(x|y)=r_{\\theta}(x|y)$ and so by minimising\n%\n\\begin{align}\\label{eq:cost1}\nH &= -\\text{E}_{p(y)}\\left[\\int dx\\,p(x|y) \\log r_{\\theta}(x|y)\\right],\n\\end{align}\n% \nwhere $\\text{E}_{p(y)}[\\cdot]$ indicates the expectation value over the \ndistribution of measurements $y$, we therefore make the parametric distribution as \nsimilar as possible to the target for all possible measurements $y$.\n\n%\n% Use Bayes theorem to simplify\n%\nConverting the expectation value into an integral over $y$ weighted by $p(y)$ we get \n%\n\\begin{equation}\n    H = -\\int dy\\,p(y) \\int dx\\,p(x|y) \\log r_{\\theta}(x|y).\n\\end{equation}\n%\nWe then apply Bayes' theorem to obtain\n\\begin{equation}\n    H = -\\int dy\\,p(y) \\int dx\\, \\frac{p(y|x)p(x)}{p(y)} \\log r_{\\theta}(x|y)\n\\end{equation}\n%\nwhere $p(x)$ is the prior distribution on the physical parameters $x$, and $p(y|x)$ is the likelihood of $x$ (the probability of measuring the data $y$ given the parameters $x$).\nCancelling out the $p(y)$ terms we arrive at\n%\n\\begin{align}\\label{eq:cost1}\nH &= -\\int dx\\,p(x)\\int dy\\,p(y|x)\\log r_{\\theta}(x|y).\n\\end{align}\n%\n\n%\n% basic general description of the r1 and r2 network inputs and outputs\n%\nThe \\ac{CVAE} network outlined in Fig.~\\ref{fig:network_config} makes use of a conditional \nlatent variable model and our parametric model is constructed from the product of 2 \nseparate distributions marginalised over the latent space as defined in Eq.~\\ref{eq:latent_model}. \nWe have used $\\theta_{1}$ and $\\theta_{2}$ to indicate that the 2 separate networks \nmodelling these distributions will be trained on these parameter sets respectively. \nThe encoder $r_{\\theta_1}(z|y)$ takes as input the data $y$ and outputs parameters \nthat describe a probability distribution within the latent space. The decoder \n$r_{\\theta_2}(x|z,y)$ takes as input a single location $z$ within the latent space \ntogether with the data $y$ and outputs sets of parameters describing a probability \ndistribution in the physical parameter space.\n%\n% Explicitly describe mathematical form of 3 NN models\n%\nThe explicit mathematical form $r_{\\theta_2}(x|z,y)$ take is that of \nmultiple multivariate Gaussian distributions whose moments, $\\mu_{\\mathrm{r}_2}$, are \npredicted by the parametric model given latent space samples $z$ and input data $y$.  \n$r_{\\theta_1}(z|y)$ takes the form of a Gaussian mixture \nmodel with a whose moments and mixture component weights (collectively labeled as \n$\\mu_{\\mathrm{r}_2}$) are also inferred by the parametric \nmodel given only observed data $y$.\n\n%\n% explain why we don't just stop here\n%\nOne could be forgiven for thinking that by setting up networks that \nsimply aim to \nminimise $H$ over the $\\theta_{1}$ and $\\theta_{2}$ would be \nenough to solve this \nproblem. However, as shown in~\\cite{NIPS2015_5775}, this \nis an intractable problem and a \nnetwork cannot be trained directly to do this. Instead, we have \nto also train an additional network to approximate the theoretical \njoint probability distribution $r_{\\theta}(z|x,y)$, which is essentially \nalready defined by the existing $r_{\\theta}(x|y)$, $r_{\\theta_1}(z|y)$ \nand $r_{\\theta_2}(x|z,y)$ joint distributions. We call the \nneural network which approximates the theoretical distribution,\n $r_{\\theta}(z|x,y)$, the recognition \nfunction , $q_{\\phi}(z|x,y)$, which is governed by the \ntrainable network parameters, $\\phi$, that will be used to derive an \\ac{ELBO}. \nFurthermore, $q_{\\phi}(z|x,y)$ takes the form of \nmultiple multivariate Gaussian distributions \nwhose moments, $\\mu_{\\mathrm{q}}$, are predicted by the parametric model given \nparameters $x$ and observed data $y$. It will become more clear in the \nderivation below that both defining and approximating this extra joint \nprobability distribution is necessary because it allows us to define \na computable form for $\\log r_{\\theta}(x|y)$. \n\n%\n% define the ELBO\n%\n%We can derive an \\ac{ELBO} by first recognising that decoder \n%$r_{\\theta_2}(x|z,y)$ may be written as the following expression \n%using Bayes theorem and \n%Using Bayes theorem we can \nWe first define the \\ac{KL}-divergence between the recognition \nfunction and the distribution $r_{\\theta}(z|x,y)$ as\n\n%~\\chris{for the paper this was fine but for the thesis I think you need to explain things a bit more. The reader will be confused as to where both of these distributions come from. they will also think that $r_{\\theta}(z|x,y)$ is one of the other, already defined, $r$ distributions. The idea is that you can write down (using Bayes theorem) how you can make $r_{\\theta}(z|x,y)$ from $r_1$ and $r_2$ - we can go through this in our meeting. So this new $r$ distribution is essentially already defined by the existing $r$ distributions. We are trying to make a new network $q$ to replicate the behaviour of this strange new $r$ distribution (that depends only on $r_1$ and $r_2$). That's the point of trying to minimise the KL between them.} \n%\n\\begin{align}\\label{eq:kl}\n\\text{KL}\\left[q_{\\phi}(z|x,y)||r_{\\theta}(z|x,y)\\right] =\n\\int dz\\,q_{\\phi}(z|x,y)\n\\log\\left(\\frac{q_{\\phi}(z|x,y)}{r_{\\theta}(z|x,y)}\\right).%\\nonumber\n\\end{align}\n%   \nThis is done because we want to minimise the difference between the \ntrue theoretical joint distribution $r_{\\theta}(z|x,y)$ and \nthe approximate version, $q_{\\phi}(z|x,y)$.\nUsing Bayes theorem we can write $r_{\\theta}(z|x,y)$ as \n%\n\\begin{equation}\n    r_{\\theta}(z|x,y) = \\frac{r_{\\theta_2}(x|z,y) r_{\\theta_1}(z|y)}{r_{\\theta}(x|y)}.\\nonumber\n\\end{equation}\n%\nPlugging this into Eq.~\\ref{eq:kl} we get\n%\n\\begin{equation}\n    \\text{KL}\\left[q_{\\phi}(z|x,y)||r_{\\theta}(z|x,y)\\right] =\n    \\int dz\\,q_{\\phi}(z|x,y)\n    \\log\\left(\\frac{q_{\\phi}(z|x,y) r_{\\theta}(x|y)}{r_{\\theta_2}(x|z,y) r_{\\theta_1}(z|y)}\\right).\\nonumber\n\\end{equation}\n%\nUsing the logarithm multiplication rule we arrive at\n%\n\\begin{align}\n    \\text{KL}\\left[q_{\\phi}(z|x,y)||r_{\\theta}(z|x,y)\\right] =\n    &\\int dz\\,q_{\\phi}(z|x,y)\n    \\log\\left(\\frac{q_{\\phi}(z|x,y)}{r_{\\theta_2}(x|z,y) r_{\\theta_1}(z|y)}\\right) + \\nonumber \\\\ \n    &\\int dz\\,q_{\\phi}(z|x,y) \\log r_{\\theta}(x|y). \\nonumber\n\\end{align}\n%\nRealising then that the $\\log r_{\\theta}(x|y)$ may be taken out of the integral since it is \nnot a function of $z$ and that the integral of a probability distribution, $q_{\\phi}(z|x,y)$ in \nthis case, is simply equivalent to 1 we can write\n%\n\\begin{align}\n    \\text{KL}\\left[q_{\\phi}(z|x,y)||r_{\\theta}(z|x,y)\\right] =\n    &\\int dz\\,q_{\\phi}(z|x,y)\n    \\log\\left(\\frac{q_{\\phi}(z|x,y)}{r_{\\theta_2}(x|z,y) r_{\\theta_1}(z|y)}\\right) + \\nonumber \\\\ \n    &\\log r_{\\theta}(x|y). \\nonumber\n\\end{align}\n%\nMoving $\\log r_{\\theta}(x|y)$ to the left-hand side of the equation and moving \nthe \\ac{KL} term to the right-hand side we get \n%\n\\begin{align}\\label{eq:elbo0}\n    \\log r_{\\theta}(x|y) = &\\text{KL}\\left[q_{\\phi}(z|x,y)||r_{\\theta}(z|x,y)\\right] + \\nonumber \\\\\n    &\\int dz\\,q_{\\phi}(z|x,y)\n    \\log\\left(\\frac{q_{\\phi}(z|x,y)}{r_{\\theta_2}(x|z,y) r_{\\theta_1}(z|y)}\\right), \n\\end{align}\n%\nwhere we realise that the right-hand integral term is simply a \\ac{KL}-divergence which \nwe define as the \\ac{ELBO} given by\n%\n\\begin{align}\\label{eq:elbo2}\n\\text{ELBO} &= \\int dz\\,\nq_{\\phi}(z|x,y)\\log\\left(\\frac{r_{\\theta_{2}}(x|y,z)r_{\\theta_{1}}(z|y)}{q_{\\phi}(z|x,y)}\\right).\n\\end{align}\n%\nIt is so-named since the \\ac{KL}-divergence has a minimum of zero and cannot be negative. Plugging \nEq.~\\ref{eq:elbo2} into Eq.~\\ref{eq:elbo0} we arrive at\n%\n\\begin{align}\\label{eq:elbo1}\n\\log r_{\\theta}(x|y) &= \\text{ELBO} + \\text{KL}\\left[q_{\\phi}(z|x,y)||r_{\\theta}(z|x,y)\\right].\n\\end{align}\n%\nwhere we now have $\\log r_{\\theta}(x|y)$ which we need for Eq.~\\ref{eq:cost1}. \nIf we were to find a $q_{\\phi}(z|x,y)$ function (optimised on $\\phi$) that minimised the \\ac{KL}-divergence defined in Eq.~\\ref{eq:kl} then we can state that\n%\n\\begin{align}\\label{eq:r_theta_ineq1}\n\\log r_{\\theta}(x|y) &\\geq \\text{ELBO}.\n\\end{align}\n%\n~\\chris{FYI, we could actually test this by using r1 and r2 to compute $r_{\\theta}(z|x,y)$ and compare it to the $q$ distribution - just a thought. It's this stage that people use to criticise the CVAE approach because we \"approach\" the true posterior, but if Eq 5.7 is zero then the log posterior *IS* the ELBO exactly.} \nSubstituting Eq.~\\ref{eq:elbo2} into Eq.~\\ref{eq:r_theta_ineq1} we get \n%\n\\begin{equation}\n    \\log r_{\\theta}(x|y) &\\geq \\int dz\\,\nq_{\\phi}(z|x,y)\\log\\left(\\frac{r_{\\theta_{2}}(x|y,z)r_{\\theta_{1}}(z|y)}{q_{\\phi}(z|x,y)}\\right).\n\\end{equation}\n%\nUsing logarithm division property we find \n%\n\\begin{equation}\n    \\log r_{\\theta}(x|y) &\\geq \\int dz\\,\nq_{\\phi}(z|x,y) \\left[ \\log (r_{\\theta_{2}}(x|y,z)r_{\\theta_{1}}(z|y)) - \n\\log q_{\\phi}(z|x,y) \\right].\\nonumber\n\\end{equation}\n%\nDistributing $q_{\\phi}(z|x,y)$ to the $\\log$ terms and using the \nlogarithm multiplicative property it can be shown that \n\\begin{align}\n    \\log r_{\\theta}(x|y) \\geq &\\int dz\\, q_{\\phi}(z|x,y) \\log r_{\\theta_{2}}(x|y,z) + \n    \\int dz\\, q_{\\phi}(z|x,y) \\log r_{\\theta_{1}}(z|y) \\nonumber \\\\\n    &- \\int dz\\, q_{\\phi}(z|x,y) \\log q_{\\phi}(z|x,y). \n\\end{align}\n%\nMaking the realisation that $\\int dz\\, q_{\\phi}(z|x,y) r_{\\theta_{2}}(x|y,z)$ \nis simply an expecation value and pulling out $q_{\\phi}(z|x,y)$ from the other \ntwo integrals we get\n%\n\\begin{equation}\n    \\log r_{\\theta}(x|y) &\\geq \\text{E}_{q_{\\phi}(z|x,y)}\\left[\\log\nr_{\\theta_{2}}(x|z,y)\\right] + \n    \\int dz q_{\\phi}(z|x,y) (\\log r_{\\theta_{1}}(z|y) - \\log q_{\\phi}(z|x,y)).\\nonumber\n\\end{equation}\n%\nand using the logarithm division property we get\n%\n\\begin{equation}\n    \\log r_{\\theta}(x|y) &\\geq \\text{E}_{q_{\\phi}(z|x,y)}\\left[\\log\nr_{\\theta_{2}}(x|z,y)\\right] + \n     \\left \\int dz q_{\\phi}(z|x,y) \\frac{\\log r_{\\theta_{1}}(z|y)}{\\log q_{\\phi}(z|x,y)}\\right.\\nonumber\n\\end{equation}\n%\nFinally, we make the realisation that the integral term is the negative \n\\ac{KL}-divergence of $q_{\\phi}(z|x,y)$ and $r_{\\theta_{1}}(z|y)$ and find that \n%\n\\begin{align}\\label{eq:logr}\n\\log r_{\\theta}(x|y) \\geq  &\\text{E}_{q_{\\phi}(z|x,y)}\\left[\\log\nr_{\\theta_{2}}(x|z,y)\\right] \\nonumber\\\\\n&-\\text{KL}\\left[q_{\\phi}(z|x,y)||r_{\\theta_{1}}(z|y)\\right].\n\\end{align}\n%\nWe can now substitute this inequality into our cost function as defined by Eq.~\\ref{eq:cost1} to obtain\n%\n\\begin{align}\\label{eq:cost2}\nH \\leq  -\\int dx\\, p(x)&\\int dy \\,p(y|x)\n\\Big[\\text{E}_{q_{\\phi}(z|x,y)}\\left[\\log r_{\\theta_{2}}(x|z,y)\\right]\n\\nonumber\\\\\n&-\\text{KL}\\left[q_{\\phi}(z|x,y)||r_{\\theta_{1}}(z|y)\\right]\\Big],  \n\\end{align}\n%\nwhich can in practice be approximated as a stochastic integral over draws of $x$ from the prior, $y$ from the likelihood function $p(y|x)$, and from the recognition function, giving us Eq.~\\ref{eq:cost3}, the actual function evaluated within the training procedure. In standard sampling algorithms it is required that the likelihood is calculated explicitly during the exploration of the parameter space and hence an analytic noise and signal model must be assumed. For a \\ac{CVAE} implementation we are required only to sample from the likelihood distribution, i.e., generate simulated noisy measurements given a set of signal parameters. This gives us the option of avoiding the assumption of detector noise Gaussianity in the future by training the \\ac{CVAE} using \"real\" non-Gaussian detector noise.\nIn the next section, we will discuss in detail the \\ac{CVAE} network \narchetecture, as well as specific design choices meant to tailor the \nmodel to our \\ac{GW}-specific problem domain.\n\n%\n% loss plot\n%\n\\begin{figure}\n    \\includegraphics[width=\\columnwidth]{inv_losses_log.png}\n\\caption{\\label{fig:loss_log} The cost as a function of training epoch. \nWe show the total cost function (green) together with its component parts: \nthe \\ac{KL}-divergence component (orange) and the reconstruction \ncomponent (blue) which are simply summed to obtain the total. \nThe dark curves correspond to the cost computed per epoch, \ndefined as the network seeing $2\\times10^{4}$ data samples, \nof training data and the lighter curves\nrepresent the cost when computed on independent validation data. \nThe close agreement between training and validation cost values \nindicates that the network is not overfitting to the training data. \nThe change in behavior of the cost between $10^2$ and $3\\times10^2$ \nepochs is a consequence of gradually introducing the \\ac{KL} \ncost term contribution via an annealing process, described in \nSec.~\\ref{sec:training_procedure}.} \n\\end{figure}\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{VItamin Network Design}\\label{sec:network_design}\n%\n% Describe the specific network hyper-parameters\n%\n\n%\n% Describe the specific network architecture design\n%\nThe \\ac{CVAE} network outlined in Fig.~\\ref{fig:network_config} is \nconstructed from the 3 separate neural networks modelling the encoder and \ndecoder distributions $r_{\\theta_1}$ and $r_{\\theta_2}$ as well as \nthe recognition function $q_{\\phi}$. Each of these components is a \ndeep convolutional network consisting of a series of \none-dimensional convolutional layers followed by a series of \nfully-connected layers. The details of each network structure are \ngiven in Table~\\ref{Tab:network_design} where we indicate the \nactivations used. We arrived at this network design through a combination \nof trial and error and Bayesian optimisation using Gaussian\nProcesses~\\cite{Siria2020.06.11.144253} (using the \\texttt{scikit-optimize}\ntoolkit~\\cite{scikit-learn}). After much testing, it turns out that \nour network chosen through trial and error was superior in performance \nto that of the Bayesian optimisation algorithm. \n\n%\n% I feel the need, the need to clearly define our CVAE networks\n%\n\\begin{table*}\n\\resizebox{14cm}{!}{\n\\begin{minipage}{\\linewidth}\n\\centering\n\\caption{The \\texttt{VItamin} network hyper-parameters. Dashed lines ``---'' indicate that \nconvolutional layers are shared between all 3 networks. \\hunter{could \nstate total number of network hyperparameters.} }\n\\begin{tabular}[t]{l|ccc}\n\\toprule\n\\backslashbox{Layer}{Network} & $r_{\\theta_1}(z|y)$ & $r_{\\theta_2}(x|y,z)$ & $q_{\\phi}(z|x,y)$ \\\\\n\\hline\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\multirow{2}{*}{Input $y$} & \\multirow{2}{*}{[1024,3]\\footnote{The shape of the\ndata [one-dimensional dataset length, No. channels].}} &\n\\multirow{2}{*}{[1024,3]} & \\multirow{2}{*}{[1024,3]} \\\\\n& & & \\\\\n\\hline\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\multirow{2}{*}{Layer 1} & conv(64,3,96)\\footnote{one-dimensional\nconvolutional filter with arguments (filter size, No. channels, No. filters).} & --- & --- \\\\\n& L2Reg(0.001)\\footnote{L2 regularization funciton applied to the kernel weights \nmatrix.} & --- & --- \\\\\n& act\\footnote{The activation function used.}=LeakyReLU & --- & --- \\\\\n\\hline\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\multirow{3}{*}{Layer 2} & conv(32,96,96) & --- &\n--- \\\\\n& stride(4)\\footnote{Striding layer with arguments (stride\nlength).} & --- & --- \\\\\n& L2Reg(0.001) & --- & --- \\\\\n& act=LeakyReLU & --- & --- \\\\\n\\hline\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\multirow{2}{*}{Layer 3} & conv(32,96,96) & --- &\n--- \\\\\n& L2Reg(0.001) & --- & --- \\\\\n& act=LeakyReLU & --- & --- \\\\\n\\hline\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\multirow{2}{*}{Layer 4} & conv(16,96,96) & --- &\n--- \\\\\n& stride(2) & --- & --- \\\\\n& L2Reg(0.001) & --- & --- \\\\\n& act=LeakyReLU & --- & --- \\\\\n\\hline\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\multirow{2}{*}{Layer 5} & conv(16,96,96) & --- &\n--- \\\\\n& L2Reg(0.001) & --- & --- \\\\\n& act=LeakyReLU & --- & --- \\\\\n\\hline\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\multirow{2}{*}{Layer 6} & conv(16,96,96) & --- &\n--- \\\\\n& stride(2) & --- & --- \\\\\n& L2Reg(0.001) & --- & --- \\\\\n& act=LeakyReLU & --- & --- \\\\\n\\hline\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\multirow{2}{*}{Input $z,x$} & \\multirow{2}{*}{flatten\\footnote{Take the multi-channel output of the previous layer and\nreshape it into a one-dimensional vector.}$\\rightarrow$[6144]} &\nflatten$\\rightarrow$[6144] & flatten$\\rightarrow$[6144] \\\\\n& & append\\footnote{Append the argument to the current dataset.}($z$)$\\rightarrow$[6159] & append($x$)$\\rightarrow$[6159] \\\\\n\\hline\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\multirow{3}{*}{Layer 7} & \n\\multirow{3}{*}{\n\\begin{tabular}[t]{c}\nFC(6159,4096)\\footnote{Fully\nconnected layer with arguments (input size, output size).}\\\\\nact=LeakyReLU \\\\\n\\end{tabular}\n} & \n\\multirow{3}{*}{\n\\begin{tabular}[t]{c}\nFC(6159,4096) \\\\\nact=LeakyReLU \\\\\n\\end{tabular}\n} &\n\\multirow{3}{*}{\n\\begin{tabular}[t]{c}\nFC(6159,4096) \\\\\nact=LeakyReLU \\\\\n\\end{tabular}\n} \\\\\n& & & \\\\\n& & & \\\\\n\\hline\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\multirow{3}{*}{Layer 8} & \n\\multirow{3}{*}{\n\\begin{tabular}[t]{c}\nFC(4096,2048)\\\\\nact=LeakyReLU \\\\\n\\end{tabular}\n} & \n\\multirow{3}{*}{\n\\begin{tabular}[t]{c}\nFC(4096,2048) \\\\\nact=LeakyReLU \\\\\n\\end{tabular}\n} &\n\\multirow{3}{*}{\n\\begin{tabular}[t]{c}\nFC(4096,2048) \\\\\nact=LeakyReLU \\\\\n\\end{tabular}\n} \\\\\n& & & \\\\\n& & & \\\\\n\\hline\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\multirow{3}{*}{Layer 9} & \n\\multirow{3}{*}{\n\\begin{tabular}[t]{c}\nFC(2048,1024)\\\\\nact=LeakyReLU \\\\\n\\end{tabular}\n} & \n\\multirow{3}{*}{\n\\begin{tabular}[t]{c}\nFC(2048,1024)\\\\\nact=LeakyReLU \\\\\n\\end{tabular}\n} &\n\\multirow{3}{*}{\n\\begin{tabular}[t]{c}\nFC(2048,1024) \\\\\nact=LeakyReLU \\\\\n\\end{tabular}\n} \\\\\n& & & \\\\\n& & & \\\\\n\\hline\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\multirow{4}{*}{Layer 10} & \n\\multirow{4}{*}{\n\\begin{tabular}[t]{c}\nFC(1024,960) \\\\\nact=None \\\\\noutput=$\\mu_{r_1}$ \\\\\n$\\rightarrow$[15,32,2]\\footnote{The $r_{\\theta_1}$ output has size\n[latent space dimension, No. modes, No. parameters defining each\ncomponent per dimension].} \\\\\n\\end{tabular}\n} & \\multirow{4}{*}{\n\\begin{tabular}[t]{c}\nFC(1024,30) \\\\\nact=(Sigmoid,-ReLU)\\footnote{Different activations are used for different\nparameters. For the scaled parameter means we use\nsigmoids and for log-variances we use negative ReLU functions.} \\\\\noutput=$\\mu_{r_2}$ \\\\\n$\\rightarrow$[19,2]\\footnote{The $r_{\\theta_2}$ output has size [physical space dimension+additional cyclic dimensions, No. parameters defining\nthe distribution per dimension].  The addtional cyclic dimensions account for the 2 parameters \neach cyclic parameter is represented by in the abstract 2D plane.} \\\\\n\\end{tabular}\n} &\n\\multirow{4}{*}{\n\\begin{tabular}[t]{c}\nFC(1024,30) \\\\\nact=None \\\\\noutput=$\\mu_{q}$ \\\\\n$\\rightarrow$[15,2]\\footnote{The $q_{\\phi}$ output has size [latent space\ndimension, No. parameters defining the distribution per dimension].} \\\\\n\\end{tabular}\n} \\\\\n& & & \\\\\n& & & \\\\\n& & & \\\\\n\\botrule\n\\end{tabular}\n%\\end{tabularx}\n\\label{Tab:network_design}\n\\end{minipage}\n}\n\\end{table*}  \n\n%\n% describe the r1 network\n%\nThe $r_{\\theta_1}$ network takes the input timeseries data $y$ in the \nform of multi-channel 1-dimensional vectors where channels represent \ndifferent \\ac{GW} detectors. After passing through a series \nof 1-dimensional convolutional and fully connected layers, the \noutput then defines the parameters of a $n_z$-dimensional \n(diagonal covariance matrices) Gaussian mixture model in the latent space. \nWe label these parameters as $\\mu_{r_1}$ containing $n_z\\times M$ means \nand log-covariances, where $M=32$ mixture component weights \nand $n_z = 15$. The motivation for using this mixture model \nrepresentation comes from the multi-modal nature of \\ac{GW} \nposterior distributions. The encoder network can use this \nflexibility to represent the $y$ timeseries data as belonging to \nmultiple possible latent space regions.   \n\n%\n% describe the q network\n% \nThe recognition function network $q_{\\phi}$ is very similar to \nthe $r_{\\theta_1}$ network with only 2 differences. The network \ntakes as input the $y$ timeseries and the true signal parameters \n$x$, however, only the $y$ data is passed through the \n1-dimensional convolutional layers. Only after the final convolutional \nlayer where the output is flattened is the $x$ data appended. It is \nthen this compound timeseries data ``feature-space'' and true signal \nparameters that are processed using the remaining fully-connected layers. \nThe second difference is that the output of the network defines \na \\emph{single-modal} (diagonal) $n_z$-dimensional Gaussian. We label \nthese parameters as $\\mu_{q}$ containing $n_z=15$ means and \nlog-covariances. The rationale behind this choice is that since \nthe $q_{\\phi}$ distribution is conditional on the true signal parameters, \nthere should be no ambiguity as to which mode in the latent \nspace that a particular timeseries belongs to.      \n\n%\n% describe the r2 network (bespoke output distributions)\n%\nThe decoder network $r_{\\theta_2}$ is identical in structure to the \n$q_{\\phi}$ network but with a difference in the form of their \noutputs and inputs. The $r_{\\theta_2}$ network takes as input both \nlatent space samples $z$ and timeseries $y$. The $r_{\\theta_2}$ output \nrepresents the parameters ($\\mu_{r_2}$) that govern an \n$n_x$-dimensional distribution in the physical parameter space \nwhere we have carefully chosen appropriate distributions for each \nof the physical parameters. For the  \nluminosity distance, the binary \ninclination, the time of coalescence, and spin \nparameters $a_1,a_2,\\Theta_1,\\Theta_2$ we have adopted truncated \nGaussian distributions where the truncation occurs at the predefined \nprior boundaries of the respective parameter space dimensions. For the \ncomponent masses we had initially adopted conditional truncated Gaussians where \nthe conditional aspect was to ensure that \n$m_{1}\\geq m_{2}$\\footnote{We note that \nthis additional complication of requiring conditional \ndecoder output distributions could have been avoided if a \ndifferent mass parameterisation were chosen, e.g., total mass and \nsymmetric mass ratio.}, but found that training duration increased significantly \nbecause of this choice. We also found that the network typically learned\nthis conditional boundary based on the training data alone anyways, so have now \ninstead opted for using truncated Gaussian distributions alone for \n$m_1$ and $m_2$. \nIndependent von Mises distributions are applied to \nphase, polarisation angle and spin parameters $\\phi_{12},\\phi_{jl}$ in \norder to capture the periodic nature of these parameters. We \nmodel all cyclic parameters as locations in an abstract 2D plane (Sec.~\\ref{sec:vit_data_aug}) \nand apply an additional reprameterisation on $\\phi_0$ and $\\psi$\n(Sec.~\\ref{sec:phipsi_repar}). Finally, we \nuse the von Mises-Fisher distribution to model the right ascension \nand declination (sky) parameters.\n% Additional details to note ... \n\n~\\chris{You have to opportunity to explain this all in more detail here, e.g., how the mode weights are all in log-space and un-normalised, how the FVM requires 3 input parameters (x,y,z on the unit sphere). You could even define the mathematical equations describing each of the output distributions.}    \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Training Procedure}\\label{sec:training_procedure}\n%\n% Introduce the training process\n%\nOur cost function is composed of 3 probability distributions \nmodelled by neural networks with well defined inputs and outputs \nwhere the mapping of those inputs to outputs is governed by the parameter sets\n$\\theta_{1},\\theta_{2}$ and $\\phi$. These parameters are the \nweights and biases of 3 neural networks acting as (variational) \nencoder, decoder, and encoder respectively, as well as the trainable \nparameters of the optimiser. To train such a network one must \nconnect the inputs and outputs appropriately to compute the cost \nfunction $H$ (Eq.~\\ref{eq:cost3}) and back-propagate cost \nfunction derivatives to update the network parameters. \n\n%\n% Go through the training step by step\n%\nTraining is performed via a series of steps illustrated schematically in Fig.~\\ref{fig:network_config}. A batch of data composed of pairs of timeseries $y$ and their corresponding true \\ac{GW} signal parameters $x$ are passed as input and the following steps are applied to each element of the batch.\n%\n\\begin{enumerate}\n%\n\\item The encoder $q_{\\phi}$ takes both the timeseries $y$ and the true parameters $x$ defining the \\ac{GW} signal. It then encodes these instances into parameters $\\mu_{q}$ defining an uncorrelated (diagonal covariance matrix) $n_z$-dimensional Gaussian distribution in the latent space. \n%\n\\item The encoder $r_{\\theta_1}$ is given only the timeseries data $y$ and encodes it into a set of variables $\\mu_{r_1}$ defining a multi-component multivariate Gaussian mixture distribution in the latent space.\n%\n\\item We then draw a sample from the distribution described by $\\mu_{q}$ giving us a location $z_{q}$ within the latent space.\n%\n\\item This sample, along with its corresponding $y$ data, are then passed as input to the decoder $r_{\\theta_2}$. This decoder outputs $\\mu_{\\theta_2}$ comprising a set of parameters that define a distribution in the physical $x$ space. \n %\n\\item The first term of the loss function, the reconstruction loss (defined as $L$ in Eq.~\\ref{eq:cost3}), is then computed by evaluating the probability density defined by $\\mu_{\\theta_2}$ at the true $x$ training value (the average is then taken over the batch of input data). \n%\n\\item The second loss component, the \\ac{KL}-divergence between the distributions $q_{\\phi}(z|x,y)$ and $r_{\\theta_1}(z|y)$ (described by the parameter sets $\\mu_{q}$ and $\\mu_{r_1}$), is given as \n%\n\\begin{align}\\label{eq:klgauss}\n\\text{KL}\\left[ q_{\\phi}(z|x_{n},y_{n})||r_{\\theta_{1}}(z|y_{n})\\right] \n= q_{\\phi}(z|x_n,y_n) \\log\\left(\\frac{q_{\\phi}(z|x_n,y_n)}{r_{\\theta_1}(z|y_n)}\\right) \\nonumber\n%\\right|_{z\\sim\n%q_{\\phi}(z|x_n,y_n)}\\nonumber\n\\end{align}\n%\nwhere $z_q$ is the sample drawn from $q_{\\phi}(z|x_n,y_n)$ in the first \ntraining stage. We use this single-sample Monte-Carlo integration \napproximation since the \\ac{KL}-divergence between a single-component \nand a multi-component multivariate Gaussian distribution has no analytic \nsolution (the average is then taken over the batch of input \ndata, hence the index $n$). \n%\n\\item The 2 loss components are then summed according to \nEq.~\\ref{eq:cost3} and all trainable network parameters \n(defined by $\\theta_1,\\theta_2,\\phi$) are updated based on \nthe derivative of the cost function with respect to these parameters.\n%\n\\end{enumerate}\n\n%\n% the ramp\n%\nA problematic aspect of training relates to the behaviour of the \nnetwork during the initial stages of training. The network has a \nstrong tendency to become trapped in local minima resulting in a \ndecreasing cost component $L$ (the reconstruction cost) but a \nnon-evolving \\ac{KL}-divergence term that remains close to zero. To \navoid this state we apply an annealing process in which the \\ac{KL}-\ndivergence term is initially ignored but its contribution is then \nincreased logarithmically from 0 to 1 between the epoch \nindices $10^2$--$3\\times10^2$. This allows the $q_{\\phi}$ encoder to \nlearn the latent space representation of the data via the reconstruction \ncost before being required to simultaneously try to best match its \ndistribution to that modelled by the $r_{\\theta_1}$ encoder. In \nparallel with the gradual introduction of the \\ac{KL} cost term, we \nalso find that the stability of training is negatively affected by the\ncomplexity of our tailored output decoder likelihood functions. To \nresolve this we apply the same annealing procedure over the same epoch \nrange in transitioning between unbound Gaussian likelihoods on all \nphysical parameters to the tailored likelihoods, where the boundaries \nof the Gaussian likelihoods are brought in from $-10$ to $0$ on the \nlower bound and $11$ to $1$ on the upper bound.\n\n%\n% Some practical aspects of the training\n%\nAs is standard practice in \\ac{ML} applications, the cost is \ncomputed over a batch of training samples and repeated for a \npre-defined number of epochs. An epoch traditionally is \ndefined as the point at which \nthe network has been trained on a number of samples equivalent to the \nsize of the entire training set. However, in this study we define an epoch \nas the network having been trained on a number of samples equivalent to \n$2\\times10^4$. For our purposes, we found that $\\sim 3 \\times 10^4$ \ntraining epochs, a batch size of $1500$ training samples and a learning \nrate of $10^{-4}$ was sufficient. We used a total of $10^7$ training \nsamples in order to adequately cover the \\ac{BBH} parameter space. \nWe additionally ensure that an (effectively) infinite number of \nnoise realizations are employed by making\nsure that every time a training sample is used it is given a unique \nnoise realisation despite only having a finite number of \nwaveforms. Every epoch we also randomly shuffle the phase, time of coalescence \nand distance parameters for all training samples loaded in disk. See\nSec.~\\ref{sec:vit_data_aug} for further details on \ndata augmentation techniques used in this chapter. \n\n%\n% completion of training and hardware\n%\nCompletion of training is determined by comparing output posteriors on \ntest samples with those of \\texttt{Bilby} iteratively during \ntraining. This comparison is done using standard figures of merit such as \nthe \\ac{PP}-plot \\ac{JS}-divergence (see Figs.~\\ref{fig:pp_plot} \nand \\ref{fig:kl_results}). We also assess training completion based on \nwhether the evolution of the cost function and its component parts\n(Fig.~\\ref{fig:loss_log}) have converged~\\chris{this is a fuzzy issue based on my smoothed loss curves which indicate that we are far from converged. This links to the study that you are doing on the theoretical lower limit on the cost based on the dynesty likelihoods and evidence values which you can link to here.}. We use a single Nvidia Tesla V100 \\acp{GPU} with $16/32$ Gb of RAM although consumer grade ``gaming\" \\ac{GPU} cards are equally fast for this application. \nWe also state that the onboard RAM memory of the machine/cluster itself \nhas implications for the batch size and consequently the speed and \noptimal learning rate to use.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Testing Procedure}\n%\n% Introduce the testing procedure\n%\nAfter training has completed and we wish to use the network for inference \nwe follow the procedure described in the right hand panel \nof Fig.~\\ref{fig:network_config}. Given a new $y$ data sample \n(not taken from the training set) we simply input this into the trained \nencoder $r_{\\theta_1}$ from which we obtain a single value of \n$\\mu_{r_1}$ describing a distribution (conditional on the data $y$) \nin the latent space. We then repeat the following steps:\n\n%\n% Go through the testing step by step\n%\n\\begin{enumerate}\n%\n\\item We randomly draw a latent space sample $z_{r_1}$ \nfrom the latent space distribution defined by $\\mu_{r_1}$.\n%\n\\item The $z_{r_1}$ sample and the corresponding original $y$ \ndata are fed as input to our pre-trained decoder network \n$r_{\\theta_2}$. The decoder network returns a set of \nparameters $\\mu_{r_2}$ which describe a multivariate \ndistribution in the physical parameter space.\n%\n\\item We then draw a random $x$ realisation from that distribution.\n%\n\\end{enumerate}\n%\n\n%\n% Final testing thoughts\n%\nA comprehensive representation in the form of samples drawn from the \nentire joint posterior distribution can then be obtained by \nsimply repeating this procedure and hence sampling from our \nlatent model $r_{\\theta}(x|y)$ (see Eq.~\\ref{eq:latent_model}).\nWe also note that some physical parameters are in-fact reparameterised in the \nneural network model (i.e. all cyclic parameters, $\\phi_0$, $\\psi$, and  \n$\\alpha$) and must then be converted back to their original \nparameterisation immediately \nfollowing step 3 above. See Sec.~\\ref{sec:vit_data_aug} for further details \nregarding how this is done.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Primary VItamin Results}\n%\nWe present results on $250$ multi-detector \\ac{GW} test \n\\ac{BBH} waveforms in simulated advanced detector \nnoise~\\cite{aligo_noisecurves} from the LIGO Hanford, \nLivingston and Virgo detectors. We compare between\nvariants of the existing Bayesian approaches and our \n\\ac{CVAE} implementation which we call \\texttt{VItamin}. \nPosteriors produced by the \\texttt{Bilby} inference \nlibrary~\\cite{1811.02042} are used as a benchmark in order to \nassess the efficiency and quality of our machine learning approach \nwith the existing methods for posterior sampling.\n\n%\n% describe the Bilby analysis \n%\nFor the benchmark analysis we assume that 14 parameters are\nunknown: the component masses\n$m_1,m_2$, the luminosity distance $d_{\\text{L}}$, the sky position\n$\\alpha,\\delta$, the binary inclination $\\Theta_{jn}$, the \\ac{GW} polarisation\nangle ${\\psi}$, the time of coalescence $t_{0}$, and the spin parameters $a_1,a_2,\n\\Theta_1,\\Theta_2,\\phi_{12},\\phi_{jl}$.  We do not include phase $\\phi_0$ in our \nresults \nbecause we apply phase marginalisation to all Bayesian samplers since \nthis \nimproves overall stability and runtime~\\cite{1811.02042}. For each parameter we use a uniform prior \nwith the exception of the declination, inclination, and tilt angle \nparameters for \nwhich we use priors uniform in $\\cos\\delta$, $\\sin\\Theta_{jn}$, $\\sin\\Theta_1$, \nand $\\sin\\Theta_2$ respectively. We also use a conditional mass prior, \nsuch that $m_2$ is constrained to be $m_2 < m_1$. The corresponding \nprior ranges are defined in Table~\\ref{tab:prior_ranges} and \nresult in a training set \\ac{SNR} distribution that has a median value of \n$\\text{SNR}\\approx 9$ and ranging between 0 and \n85 (see Fig.~\\ref{fig:VItamin_TrainingSet_SNR_Dist}). We use a \nsampling frequency of $1024$~Hz, a timeseries duration of 1~s, and \nthe waveform model used is \\texttt{IMRPhenomPv2}~\\cite{1809.10113} with \na minimum cutoff frequency of $20$Hz. For each input test \nwaveform we run the benchmark analysis using multiple \nsampling algorithms (\\texttt{ptemcee},\\texttt{Dynesty},\\texttt{emcee},\n\\texttt{CPnest}) available within \\texttt{Bilby}. For each run and \nsampler we extract $\\mathcal{O}(8000)$ samples from the posterior on the \n14 physical parameters.\n\n%\n% discussion on sampler settings\n%\nWith regards to the parameters choices in Table~\\ref{Tab:sampler_params}, \nafter having discussed with experts in the Bayesian sampler community, \nit is evident that Bayesian samplers are certainly not guaranteed \nto converge to the same results. Full convergence in many cases may \nrequire much fine tuning over many iterations for each individual run. \nAlthough we do not fine tune Bayesian benchmark samplers for each \nsampler and each individual test case, we do use settings which \nhave been recommended to us by \\texttt{bilby} developers and outside experts \nfor each respective Bayesian sampler. Both the \\texttt{Dynesty} and \n\\texttt{CPNest} \nsamplers have a tolerance threshold (change in the log evidence \nfrom one proposal to the next) which guarantees a certain level of \nconvergence. We use the recommended tolerance level of 0.1 for \nboth nested samplers. For the \\ac{MCMC} samplers, \\texttt{emcee} \nperforms poorly, \nbut is known to have difficulties with convergence within the \ncommunity. There are a handful of \\texttt{ptemcee} test cases \n(~5 of the 250) which show some minor indication of incomplete \nconvergence, but after careful review we have determined that a \nlengthier burn-in period does not significantly improve the \nresulting posteriors.\n\n%\n% I feel the need, the need for clearly outlining the bilby parameter choices\n%\n\\begin{table*}\n\\centering\n\\caption[Benchmark sampler configuration parameters.]{Benchmark sampler configuration parameters. Values were chosen based on a combination of their recommended default parameters~\\cite{1811.02042} and private communication with the \\texttt{Bilby} development team.}\n\\begin{minipage}{\\linewidth}\n\\begin{tabular}[t]{lc}\n\\toprule\nsampler & parameters \\\\\n\\hline\n\\texttt{Dynesty}~\\cite{dynesty} & $\\begin{array}{c} \\text{live-points} =1000,\\, \\text{dlogz} =0.1,\\, \\text{nact} =50,\\,  \\text{npool} =8,\\, \\\\ \\text{bound} = \\text{None},\\, \\text{sample} = \\text{uniform} \\end{array}$\\\\\n\\hline \n%\\texttt{ptemcee}~\\cite{ptemcee} & $\\begin{array}{c}\\text{walkers}=200\\,\n%\\text{temperatures}=20\\,\n%\\\\ \\text{nsamples}=10000\\, \\text{threads}=10\\end{array}$ \\\\\n\\texttt{ptemcee}~\\cite{ptemcee} & $\\begin{array}{c}\\text{walkers}=200,\\, \n\\text{temperatures}=20,\\, \\text{burn}\\_\\text{in}\\_\\text{nact}=50,\\, \\\\ \\text{thin}\\_\\text{by}\\_\\text{nact}=0.5,\\, \n\\text{nsamples}=10000,\\, \\text{threads}=10,\\, \\\\ \\text{autocorr}\\_\\text{tol}=50,\\, \n\\text{autocorr}\\_\\text{c} \\text{safety}=1,\\, \\text{autocorr}\\_\\text{tau}=1,\\, \\\\ \n\\text{gradient}\\_\\text{tau}=0.1,\\, \n\\text{gradient}\\_\\text{mean}\\_\\text{log}\\_\\text{posterior}=0.1,\\, \\\\ \\text{Q}\\_\\text{tol}=1.01,\\, \n\\text{min}\\_\\text{tau}=1,\\, \\text{threads}=1,\\, \\end{array}$ \\\\\n\\hline\n\\texttt{CPNest}~\\cite{cpnest} & $\\begin{array}{c} \\text{live-points} =2048,\\, \\text{maxmcmc} =1000, \\, \\text{nthreads} = 1,\\, \\\\\n\\text{seed} = 1994,\\, \\text{dlogz} =0.1 \\end{array}$ \\\\\n\\hline\n\\texttt{emcee}~\\cite{emcee} & $\\begin{array}{c} \\text{nwalkers} =250,\\, \\text{nsteps} =14000,\\, \\text{nburn}=4000,\\, \\text{a} = 1.4,\\, \\\\\n\\text{burn}\\_\\text{in}\\_\\text{fraction}=0.25,\\, \\text{burn}\\_\\text{in}\\_\\text{act}\\_=3 \\end{array}$ \\\\\n\\botrule\n\\end{tabular}\n\\label{Tab:sampler_params}\n\\end{minipage}\n\\end{table*}\n\n%\n% Priors\n%\n\\begin{table}\n\\centering\n\\caption{The prior boundaries used on the \\ac{BBH} signal parameters for the benchmark and the \\ac{CVAE} analyses. We note that the polarisation angle and phase are represented in the 2D plane through a reprameterisation given in (Sec. ~\\ref{sec:phipsi_repar}).}\n\\begin{minipage}{\\linewidth}\n\\begin{center}\n\\begin{tabular}[t]{lccccc}\n\\toprule\nParameter name & symbol & min & max & units & prior function \\\\\n\\hline\nmass 1 & $m_1$ & 35 & 80 & solar masses & Uniform \\\\\nmass 2 & $m_2$\\footnote{Additionally $m_2$ is constrained such that\n$m_{2}<m_{1}$.} & 35 & 80 & solar masses & Uniform \\\\\nluminosity distance & $d_{\\text{L}}$ & 1 & 3 & Gpc & Uniform \\\\\ntime of coalescence & $t_{0}$ & 0.65 & 0.85 & s & Uniform \\\\\nphase at coalescence & $\\phi_{0}$ & 0 & $2\\pi$ & radians & Uniform~\\footnote{Phase \nhas a periodic boundary condition.} \\\\\nright ascension & $\\alpha$ & 0 & $2\\pi$ & radians & Uniform~\\footnote{Right ascension \nhas a periodic boundary condition.} \\\\\ndeclination & $\\delta$ & $-\\pi/2$ & $\\pi/2$ & radians & Cosine \\\\\ninclination & $\\iota$ & 0 & $\\pi$ & radians & Sine \\\\\npolarisation & $\\psi$ & 0 & $\\pi$ & radians & Uniform~\\footnote{Polarisation \nhas a periodic boundary condition.} \\\\\nspin magnitude 1 & $a_1$ & 0 & 0.8 & - & Uniform \\\\\nspin magnitude 2 & $a_2$ & 0 & 0.8 & - & Uniform \\\\\ntilt angle 1 & $\\Theta_1$ & 0 & $\\pi$ & radians & Sine \\\\\ntilt angle 2 & $\\Theta_2$ & 0 & $\\pi$ & radians & Sine \\\\\nazimuthal angle & $\\phi_{12}$ & 0 & $2\\pi$ & radians & Uniform~\\footnote{Azimuthal angle  \nhas a periodic boundary condition.} \\\\\nazimuthal position & $\\phi_{jl}$ & 0 & $2\\pi$ & radians & Uniform~\\footnote{Azimuthal position  \nhas a periodic boundary condition.} \\\\\n\\hline\n%spins & - & \\multicolumn{2}{c}{0} & - \\\\\nepoch & \\multicolumn{3}{c}{1126259642} & GPS time & - \\\\\ndetector network & \\multicolumn{3}{c}{LIGO H1,L1, \\& Virgo V1} & - & - \\\\\n\\botrule\n\\end{tabular}\n\\end{center}\n\\label{tab:prior_ranges}\n\\end{minipage}\n\\end{table}\n\n\\begin{figure}\n    \\includegraphics{figures/TrainingSetSNR_distribution.png}\n    \\caption[VItamin signal-to-noise ratio training, validation and testing set distributions.]{\\label{fig:VItamin_TrainingSet_SNR_Dist} We show here a histogram of the optimal network \\ac{SNR} values of the \\texttt{VItamin} training, validation and testing sets. The mode for all \n    plotted distributions occurs at an \\ac{SNR} value of $\\sim8$ which drops off quickly to zero on the left-hand side. There is a tail on the right-hand side which drops off more gradually up to a maximum \\ac{SNR} value of $\\sim 85$ \n    for the training set, $\\sim 70$ for the validation set and $\\sim 57$ \n    for the testing set. The peak location and general distribution of the \\ac{SNR} values is heavily dependent on both the chosen source parameter \n    priors (Tab.~\\ref{tab:prior_ranges}) and the \\ac{PSD}.}\n\\end{figure}\n\n%\n% the VItamin process\n%\nThe \\texttt{VItamin} training process uses as input \n$10^{7}$ whitened waveforms corresponding to parameters drawn \nfrom the same priors as assumed for the benchmark analysis. The \nwaveforms are also of identical duration, sampling frequency, and \nuse the same waveform model as in the benchmark analysis. \nThe signals are whitened\\footnote{The whitening is used \nprimarily to scale the input to a magnitude range more suitable to \nneural networks. The \\emph{true} \\ac{PSD} does not have to be used for \nwhitening, but training data and test data must be contain \nsignals that have been whitened by the same \\ac{PSD}.} using the same \nadvanced detector \\acp{PSD}~\\cite{aligo_noisecurves} as assumed \nin the benchmark analysis. When each whitened waveform is \nplaced within a training batch it is given a unique detector \nGaussian noise realisation (after signal whitening this is simply \nzero mean, unit variance Gaussian noise). See Sec.~\\ref{sec:vit_data_aug} \nfor further data augmentation details. The \\texttt{VItamin} posterior \nresults are produced by passing each of our $250$ whitened noisy \ntesting set of \\ac{GW} waveforms as input into the testing path of \nthe pre-trained \\ac{CVAE} (Fig.~\\ref{fig:network_config}). For each \ninput waveform we sample until we have generated $8000$ posterior samples \non 15 physical parameters \n$x=(m_1,m_2,d_{\\text{L}},t_{0},\\Theta_{jn},a_1,a_2,\\Theta_1,\n\\Theta_2,\\psi, \\phi_0, \\phi_{12},\\phi_{jl},\\alpha,\\delta)$. We also note\nthat parameters (such as $\\phi_0$) can (if desired) be \nmarginalised out within the \\ac{CVAE} procedure itself, rather than \nafter training by choosing only to output a subset of the \nsource parameter space in the final layer of the decoder network. When \nperforming comparisons between the \\texttt{VItamin} approach and other \nbilby samplers, we only compare using 14 parameters (i.e. excluding \n$\\phi_0$) since we apply phase marginalisation to the bilby samplers when \ngenerating benchmark Bayesian test case posteriors. \n\n%\n% Corner plot results\n%\n\\begin{figure*}\n    \\includegraphics[width=\\textwidth]{corner_testcase0.png}\n    \\caption[Corner plot showing 1 and 2-dimensional\n    marginalised posterior distributions on the \\ac{GW} parameters for \n    one example test dataset.]{\\label{fig:corner_plot} Corner plot showing \n    1 and 2-dimensional marginalised posterior distributions on the \n    \\ac{GW} parameters for one example test dataset. Red contours \n    represent the two-dimensional joint posteriors obtained from \n    \\texttt{VItamin} and blue and green contours are the corresponding \n    posteriors output from our benchmark analyses \n    (using the \\texttt{Dynesty} and \\texttt{ptemcee} samplers \n    within \\texttt{Bilby}). In each case, the contour boundaries enclose \n    $68,90$ and $95\\%$ probability. 1 dimensional histograms of the \n    posterior distribution for each parameter from both methods are \n    plotted along the diagonal. Orange vertical and horizontal lines \n    denote the true parameter values of the simulated \n    signal. Vertical \n    dashed lines in the 1 dimensional plots are representative of the $5\\%$ and \n    $95\\%$ symmetric confidence bounds of the 3 sampler 1 dimensional posteriors.\n    At the top right of the figure we include a Mollweide projection of \n    the sky location posteriors from all three analyses. All results \n    presented in this chapter correspond to a three-detector configuration \n    but for clarity we only plot the H1 whitened noisy timeseries $y$ and \n    the noise-free whitened signal (in blue and cyan respectively) to the \n    right of the figure. The test signal was simulated with an \n    optimal multi-detector signal-to-noise ratio of 14.3.~\\chris{Try to make better use of the space - maybe increase the sky plot size and the timeseries plot. Th timeseries plot sould hav ethe legend removed and there is an argumnet for *all* fonts to be made larger for easier reading.}} \n\\end{figure*}\n\n%\n% discuss the corner plot results\n%\nWe can immediately illustrate the accuracy of our machine learning predictions\nby directly plotting 2- and 1-dimensional marginalised posteriors generated\nusing the output samples from our \\texttt{VItamin} and \\texttt{Bilby}\napproaches superimposed on each other. We show this for one example test\ndataset in Fig.~\\ref{fig:corner_plot} where strong agreement between the\n\\texttt{Bilby} sampler \\texttt{Dynesty} in blue,  and the\n\\ac{CVAE} (red) is clear. It is also evident that whilst we refer to the\n\\texttt{Bilby} sampler results as benchmark cases, different existing samplers\ndo not perfectly agree with each other (i.e. \\texttt{ptemcee} in green) despite using \nexpert recommended sampler settings shown in Tab.~\\ref{Tab:sampler_params}.  \nFor each of our 250 test cases we see\nreasonable levels of agreement between pairs of benchmark samplers \\emph{and}\nbetween any benchmark sampler and our \\ac{CVAE} results. \n\n%\n% mention the p-p plot and KL distribution results\n%\nFigures~\\ref{fig:pp_plot} and \\ref{fig:kl_results}\nshow the results of multiple statistical \ntests (the \\ac{PP} plot test and \\ac{JS}-divergence tests) \nperformed on the entire test dataset and between all samplers \n(\\texttt{Dynesty}, \\texttt{ptemcee}, \\texttt{CPNest}, \\texttt{emcee}, \nand \\texttt{VItamin}). In\nboth tests the quality of the \\texttt{VItamin} results are\n reasonably consistent with the\nbenchmark samplers\n. \n% pp plot\nA standard test used within the \\ac{GW} parameter estimation community \nis the production of so-called \\ac{PP} plots which we show for our \nanalysis and the benchmark comparisons in Fig.~\\ref{fig:pp_plot}. The plot \nis constructed by computing a cumulative probability for each \n1-dimensional marginalised test posterior evaluated at the true simulation parameter value (the fraction of posterior samples $\\leq$ the simulation value). We then plot the cumulative distribution of these values~\\cite{1409.7215}. Curves consistent with the black dashed diagonal line indicate that the 1-dimensional Bayesian probability distributions are consistent with the frequentist interpretation - that the truth will lie within an interval containing $X\\%$ of the posterior probability with a frequency of $X\\%$ of the time. It is clear to see that results obtained using \\texttt{VItamin} show deviations from the diagonal that are entirely consistent with those observed in all benchmark samplers. The $p$-value has also been calculated for each sampler and each parameter under the null-hypothesis that they are consistent with the diagonal. These results show that for at least 1 parameter, emcee shows inconsistency with the modal at the 0.4\\% level. \\texttt{Dynesty} has a worst case that is consistent only at the 0.7\\% level.  All other samplers (including \\texttt{VItamin}) show consistency at $>0.4\\%$ in the worst case.\nWhat these \\ac{PP} plot results show is that the posteriors produced \nby \\texttt{VItamin}, whilst perhaps not optimal, are still trustworthy and are unbiased \nin their estimation.~\\hunter{Is this enough of an explanation for the pp plot meaning?}\n~\\chris{Also, at some point, state what a pp plot actually means - why the Bayesian-Frequentist comparison is important.} \n~\\chris{use the final p-values output from the code to back this up. \nImportant results shouldn't only appear in figure captions. You actually \ngive the best and worst p-values for each sampler but bilby should \nalso output the overall p-value combining all parameters for a \ngiven sampler. It would be worth quoting those numbers}\n\n%\n% P-P plot\n%\n\\begin{figure}\n    \\includegraphics[width=\\columnwidth]{latest_pp_plot.png}\n    \\caption[One-dimensional \\ac{PP} plots for each parameter and for each benchmark sampler and \\texttt{VItamin}.]{\\label{fig:pp_plot}~\\chris{You might consider using 4 panels in the thesis to better separate the curves from the different samplers. It might then warrant adding the grey error regions?} One-dimensional \\ac{PP} plots for each parameter and for each benchmark sampler and \\texttt{VItamin}. The curves were constructed using the 250 test datasets and the dashed black diagonal line indicates the ideal result. The best and worst-case $p$-values~\\chris{in your description of the p-p plot earlier on you use p-value to describe the area to the left of the true value for each parameter and each test data sample. In this case the p-value is a different thing. It might be confusing.} associated with each sampling method are (0.918,  0.047 \\texttt{VItamin}), (0.912, 0.007 \\texttt{Dynesty}), (0.931,0.007 \\texttt{ptemcee}), \n    (0.706,0.007 \\texttt{CPNest}), (0.667,0.004 \\texttt{emcee} ).~\\chris{Compute the overall p-value for each sampler - in addition to the best and worst.}. \n}\n\\end{figure}\n%\n\n%\n% Discuss Dynesty plot\n%\nThe \\ac{JS}-divergence is generally used as measure of the similarity \nbetween distributions defined as \n%\n\\begin{equation}\\label{eq:JS_div}\n    \\mathrm{JS}(\\mathrm{P}||\\mathrm{Q}) = \\frac{1}{2} \\mathrm{KL}(\\mathrm{P}||\\mathrm{M}) + \n    \\frac{1}{2} \\mathrm{KL}(\\mathrm{Q}||\\mathrm{M}) \n\\end{equation}\n%\nwhere $\\mathrm{M} = 1/2(\\mathrm{P} + \\mathrm{Q})$, $\\mathrm{KL}$ is the \\ac{KL}-divergence \nas defined in Eq.~\\ref{eq:kl}, and ($\\mathrm{P},\\mathrm{Q}$) are \ntwo distributions we would like to measure the similarity between. In Fig.~\\ref{fig:JS_indi_par_dynesty} \nwe use this quantity to compare the output posterior estimates between \nsamplers for the same input test data. To do this we run each independent \nsampler (including \\texttt{VItamin}) on the same test data to produce \nsamples from the corresponding posterior. We then compute the \n1-dimensional \\ac{JS}-divergence between the output single \nparameter distributions from each sampler with every \nother sampler~\\cite{4839047}. For distributions that are \nidentical, the \\ac{JS}-divergence \\emph{should} equal zero but since we \nare representing our posterior distributions using finite numbers of \nsamples, identical distributions result in finite \\ac{JS}-divergence \nvalues~\\cite{2021MNRAS.tmp.2039A}. \nIn Fig. \\ref{fig:JS_indi_par_dynesty}, it can be seen that \\texttt{Dynesty}  \nvs. \\texttt{VItamin} JS values closely match results from \n\\texttt{Dynesty} vs. \\texttt{Ptemcee} for nearly all parameters, with \nthe exception of $\\phi_{jl}$, and \n$\\phi_{12}$. \\texttt{VItamin} predictions have slightly \nhigher \\ac{JS} values across all source parameters except for the \nspin parameters. \\texttt{Dynesty} vs. CPNest seems to generally \nhave similar JS values to \\texttt{Dynesty} vs. \\texttt{Ptemcee} with \nthe exception of having broader credible intervals on $t_0$, \n$\\theta_{jn}$, $\\phi_{jl}$, $\\alpha$ and $\\delta$. We also note in the  \n1-dimensional case that while \\ac{JS}-divergence values are reliable, they do not directly \ntest the multi-dimensional correlations between source parameters. \n\n%\n% All other 1D JS divergence plots discussion\n%\n\\hunter{I moved the additional JS divergence plots from the section \nbelow, to this smaller additional paragraph here.}\nWe also provide additional \\ac{JS}-divergence figures of merit on \n1-dimensional source parameter posteriors in\nFigs.~\\ref{fig:JS_indi_par_cpnest}, \\ref{fig:JS_indi_par_emcee},\nand~\\ref{fig:JS_indi_par_ptemcee}, where in each we highlight the comparison \nresults of one Bayesian sample (i.e. Fig.~\\ref{fig:JS_indi_par_cpnest} \nhighlights \\texttt{CPNest}). In all 3 figures it can be seen that \n\\texttt{VItamin} is generally consistent with the Bayesian sampler \nhighlighted. In particular, we point out that \\texttt{VItamin} \nappears to most closely agree with \\texttt{CPNest}, as shown in \nthe maroon colored bars of Fig.~\\ref{fig:JS_indi_par_cpnest}. Across all \n3 figures there is generally more strong agreement between samplers \non the spin parameters, and the least amount of agreement on the sky location \nparameters. \\texttt{VItamin} also consistently performs most poorly \nwith respect to each sampler on the polarsiation angle. What is also \ninteresting to note is the level of disagreement of other Bayesian samplers \nwith themselves across all 3 figures. This disagreement is especially \nprominent with regards \nto source parameters $t_0$, $\\theta_{jn}$, $\\phi_{jl}$, $\\alpha$, and $\\delta$.\n\\texttt{emcee} vs. all other methods generally has higher \\ac{JS}-divergence \nvalues than all other comparison results. This is expected given the difficulty \nof obtaining \\texttt{emcee} convergence.\nFinally, we note that although \\texttt{emcee} results are \nfairly poor in comparison with other \napproaches, they are a useful benchmark for indicating underperformance.\n\n%\n% 14D JS divergence results\n%\nIn Fig.~\\ref{fig:kl_results} we show the distributions of 14 \ndimensional \\ac{JS}-divergences \nfor the 250 test \\ac{GW} samples. In each panel we plot the \ndistribution of \\ac{JS}-divergences \nobtained when comparing one of the 4 benchmark samplers \nwith all other benchmark samplers \n(excluding \\texttt{VItamin}). We also plot the \ndistribution of \\ac{JS}-divergences obtained \nwhen comparing the same sampler with \\texttt{VItamin} \nalone. In all 4 cases the \\texttt{VItamin} \nresults show distributions completely consistent with the \ndeviations observed between \nbenchmark samplers. It is evident from the plot \nthat \\texttt{Dynesty}, \\texttt{CPNest}, \nand \\texttt{ptemcee} comparison results between themselves reach \n\\ac{JS} values far lower than any comparison result with \\texttt{VItamin}. \nOn the flip side, they also have tails at high \\ac{JS} values \nin their distributions which are consistent with \nthose of \\texttt{VItamin} comparison results. We see in all 4 subplots \nof Fig.~\\ref{fig:kl_results} (and most clearly in the lower right subplot) \nthat \\texttt{emcee} continues to have the highest \\ac{JS} values of \nall comparison results.\nWe also state here that the 14-dimensional \n\\ac{JS}-divergence distributions were estimated using an \napproximation technique\n~\\footnote{\\url{(https://pypi.org/project/universal-divergence/})} \nand a finite number of samples such that there was a \nfundamental noise of $\\sim +/- 0.15$ on the output values - \nhence even samples from 2 different sampler runs on the same \ntest data would have \\ac{JS}-divergence scatter of this \nmagnitude around 0. ~\\chris{\nYou might also want to \nmake a verison of this plot with non-logged y-axis - it will likely highlight the main problems \nthat we have in convincing people.}\n\n\\begin{figure*}\n    \\includegraphics[width=\\textwidth]{hist-JS.png}\n    \\caption[Distributions of the JS-divergence \n    values across 14 parameters between posteriors produced by different\n    samplers.]{\\label{fig:kl_results} Distributions of \\ac{JS}-divergence \n    values between posteriors produced by different samplers. In each \n    panel we show the distribution of \\ac{JS}-divergences computed \n    between a single benchmark sampler and every other benchmark sampler \n    over all 250 \\ac{GW} test cases (grey histogram outlines). \n    Also plotted in each \n    panel are the corresponding \\ac{JS}-divergence distributions \n    between the single benchmark sampler and the \\texttt{VItamin} \n    outputs (colored histogram outlines).}\n\n\\end{figure*}\n\n\n\\begin{figure}\n    \\includegraphics[width=\\columnwidth]{figures/JS_IndiPar_dynesty.png}\n    \\caption[JS divergences of individual source parameters for \\texttt{Dynesty} against all other approaches.]{\\label{fig:JS_indi_par_dynesty} We show JS divergence values for all 250 test samples as a function of test sample source parameter for \\texttt{Dynesty} against every other sampling approach. Each sampler method vs. another sampler method are denoted as different colors. The lower and upper end of boxes represent the 25th and 75th percentile credible regions respectively. The lower and upper end of the whiskers represent the 5th and 95th percentile credible regions. The orange lines are representative of the median JS values for each pair of compared samplers.}\n\\end{figure}\n\n%\n% discuss the speed of the analysis\n%\nThe dominating computational cost of running \\texttt{VItamin} lies \nin the training time, which can take $\\mathcal{O}(7)$ days~\\chris{There is the opportunity to include a simple study of the benchmark evolution as a function of both total loss and wall-clock time. You already have the plots for this.} \nto complete. Completion is determined by comparing posteriors \nproduced by the machine learning model and those of \n\\texttt{Bilby} iteratively during training~\\chris{well, kind of. If we got perfect overlap then yes we would stop at that point. However, as we now know, the loss is still evolving even at 50K epochs. A really nice thing to add would be the true ultimate H value that we can theoretically achieve computed using the dynesty evidence and the sample likelihoods and priors}. We \nadditionally assess whether the cost curves (Fig.~\\ref{fig:loss_log}) \nhave converged, such that \ntheir slope is near-zero~\\chris{true, but see previous comment}.\n\nWe stress that once trained, there is no need to retrain the network \nunless the user wishes to use different priors $p(x)$ or assume \ndifferent noise characteristics. The speed at which posterior \nsamples are generated for all samplers used, including \\texttt{VItamin}, \nis shown in Table~\\ref{Tab:speed}. Run-time for the benchmark samplers is \ndefined as the time to complete their analyses when configured using \nthe parameter choices defined in Table~\\ref{Tab:sampler_params}. \nFor \\texttt{VItamin}, the run-time is defined as the total time to \nproduce $8000$ samples. To be clear, this does not include \nthe $\\mathcal{7}$ days required to train the network. For our test \ncase of \\ac{BBH} signals \\texttt{VItamin} produces samples from the \nposterior at a rate which is $\\sim 6$ orders of magnitude faster than \nour benchmark analysis using current inference techniques, \nrepresenting a dramatic speed-up in performance.\n\n%\\chris{One more thing to add, especially if the other KL, AD, and PP plots\n%aren't convincing, is a plot displaying 1D confidence bounds compared between\n%bilby and VItamin. Imagine a plot with the x-axis as distance and the y-axis\n%steps through test data with increasing true distance. for each test data you\n%plot 2 error bars horizontally (one for bilby and one for VItamin) spanning the\n%range of 90\\% confidence. You would hopefully get nearly identical pairs of\n%errorbars stacked vertically. Technically you could do this for all parameters\n%(and you should) but we might only put one of the plots in the paper (if at\n%all).}\n\n%\n% I feel the need, the need for speed, table\n% \n\\begin{table}\n%\\centering\n\\caption[Durations required to produced samples from \n different posterior approaches.]{Durations required to produce \n samples from each of the different posterior sampling approaches.}\n\\begin{minipage}{\\linewidth}\n\\begin{center}\n\\begin{tabular}[t]{lcccc} \n\\toprule\n\\multirow{2}{*}{sampler} & \\multicolumn{3}{c}{run time (s)} & \\multirow{2}{*}{ratio\n$\\displaystyle\\frac{\\tau_{\\text{VItamin}}}{\\tau_{X}}$} \\\\\n& min & max & median & \\\\\n\\hline\n\\texttt{Dynesty}\\footnote{The benchmark samplers all produced\n$\\mathcal{O}(8000)$ samples dependent on the default sampling parameters\nused.}~\\cite{dynesty} & 21564 & 261268 & 45607\n\\footnote{We note that there are a growing number of specialised\ntechniques~\\cite{2016PhRvD..94d4031S,2019PhRvD..99h4026W,2019PhRvD.100d3030T,PhysRevD.92.023002} designed to speed up traditional sampling algorithms that could be used to reduce the runtimes quoted here by $\\mathcal{O}(1-2)$ orders of magnitude.}\n%\\footnote{The reader may note that benchmark sampler run times are a few orders\n%of magnitude lower than what is typical of a complete \\ac{BBH} analysis\n%($\\mathcal{O}(10^{4} -10^{5})$ seconds). This is primarily due our use of a\n%reduced parameter space, low sampling rate and choice of sampler\n%hyperparameters.} \n& $2.2\\times 10^{-6}$ \\\\\n\\texttt{emcee}~\\cite{emcee} & 16712 & 39930 & 19821 & $5.1\\times 10^{-6}$ \\\\\n\\texttt{ptemcee}~\\cite{ptemcee} & 2392 & 501632 & 41151.0 & $2.4\\times 10^{-6}$ \\\\\n\\texttt{CPNest}~\\cite{cpnest} & 10309 & 437008 & 83807 & $1.2\\times 10^{-6}$ \\\\\n\\texttt{VItamin}\\footnote{For the \\texttt{VItamin} sampler $8000$ samples are\nproduced as representative of a typical posterior. The run time is independent\nof the signal content in the data and is therefore constant for all test cases.} & \\multicolumn{3}{c}{\\bm{$1\\times10^{-1}$}} & 1 \\\\\n\\botrule\n\\end{tabular}\n\\end{center}\n\\label{Tab:speed}\n\\end{minipage}\n\\end{table}\n\n%\n% word count ~960 - approx 9.6 words per line\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%\\subsection{Additional Jensen--Shannon Divergence Plots Computed on Individual Source Parameters}\n\n%\n% Individual source parameter JS divergences\n%\n\n%We provide additional \\ac{JS}-divergence figures of merit in \n%Figs.~\\ref{fig:JS_indi_par_cpnest}, \\ref{fig:JS_indi_par_emcee},\n%and~\\ref{fig:JS_indi_par_ptemcee} where we plot the \\ac{JS}-divergence \n%values for each \\ac{GW} source parameter across all \n%Bayesian sampler approaches.\n%\n% Discuss CPNest plot\n%\n\n%In Fig. \\ref{fig:JS_indi_par_cpnest}, \\texttt{CPNest} is highlighted against \n%all other sampler approaches (including \\texttt{VItamin}). It can be seen \n%that both \\texttt{CPnest} vs. \\texttt{Dynesty} and \\texttt{CPnest} vs. \n%\\texttt{Ptemcee} are in strong agreement with each other (although with broad \n%credibility regions on $t_0$, $\\theta_{jn}$, $\\alpha$, $\\delta$). \\texttt{CPNest} \n%vs. \\texttt{VItamin} is also in strong agreement with \\texttt{CPnest} vs. \\texttt{Dynesty} and \\texttt{CPnest} vs. \\texttt{Ptemcee}, but it does show some \n%disagreement on $m_1$, $m_2$ and $\\psi$. \\texttt{CPNest} vs. \\texttt{Emcee} is \n%generally in disagreement with all other approaches.\n\n\\begin{figure}\n    \\includegraphics[width=\\columnwidth]{figures/JS_IndiPar_cpnest.png}\n    \\caption[JS divergences of individual source parameters for \\texttt{CPNest} against all other approaches.]{\\label{fig:JS_indi_par_cpnest} We show JS divergence values for all 250 test samples as a function of test sample source parameter for \\texttt{CPnest} against every other sampling approach. Each sampler method vs. another sampler method are denoted as different colors. The lower and upper end of boxes represent the 25th and 75th percentile credible regions respectively. The lower and upper end of the whiskers represent the 5th and 95th percentile credible regions. The orange lines are representative of the median JS values for each pair of compared samplers.}\n\\end{figure}\n\n%\n% Discuss Emcee JS indi par plot\n%\n\n%Fig. \\ref{fig:JS_indi_par_emcee} highlights the \\texttt{Emcee} sampler \n%vs. all other approaches including \\texttt{VItamin}. In Fig. \n%\\ref{fig:JS_indi_par_emcee} it can be seen that \\texttt{Emcee} has equal \n%overlap against all other sampler approaches. Given the high JS values \n%of \\texttt{Emcee} vs. all other approaches, this indicates that \\texttt{Emcee} \n%has found difficulty converging on many of the test sample cases. This is \n%expected given that it is well known that \\texttt{Emcee} generally difficult \n%to tune for proper convergence.\n\n\\begin{figure}\n    \\includegraphics[width=\\columnwidth]{figures/JS_IndiPar_emcee.png}\n    \\caption[JS divergences of individual source parameters for \\texttt{Emcee} against all other approaches.]{\\label{fig:JS_indi_par_emcee} We show JS divergence values for all 250 test samples as a function of test sample source parameter for \\texttt{emcee} against every other sampling approach. Each sampler method vs. another sampler method are denoted as different colors. The lower and upper end of boxes represent the 25th and 75th percentile credible regions respectively. The lower and upper end of the whiskers represent the 5th and 95th percentile credible regions. The orange lines are representative of the median JS values for each pair of compared samplers. We see here that \\texttt{VItamin} performs to within a degree of accuracy which is consistent with other Bayesian samplers when looking at predictions on an individual source parameter basis.}\n\\end{figure}\n\n%\n% Discuss Ptemcee JS indi par plot\n%\n\n%Fig. \\ref{fig:JS_indi_par_ptemcee} highlights \\texttt{Ptemcee} vs. all \n%other sampler approaches. In Fig. \\ref{fig:JS_indi_par_ptemcee} we see \n%that \\texttt{Ptemcee} vs. \\texttt{Dynesty} and \\texttt{Ptemcee} vs. \n%\\texttt{CPNest} closely match each other with the exception of slight \n%disagreement on $t_0$, $\\theta_{jn}$ and $\\phi_{jl}$ (with broader credibility %regions on \\texttt{Ptemcee} \n%vs. \\texttt{CPNest}). \\texttt{Ptemcee} vs. \\texttt{VItamin} in dark green \n%also closely matches the \\texttt{Ptemcee} vs. \\texttt{Dynesty} and %\\texttt{Ptemcee} vs. \\texttt{CPNest} results with slightl higher JS values \n%accross all source parameter values other than the spin parameters. \n%\\texttt{Emcee} is in strong misalignment with all other approaches.\n\n\\begin{figure}\n    \\includegraphics[width=\\columnwidth]{figures/JS_IndiPar_ptemcee.png}\n    \\caption[JS divergences of individual source parameters for \\texttt{Ptemcee} against all other approaches.]{\\label{fig:JS_indi_par_ptemcee} We show JS divergence values for all 250 test samples as a function of test sample source parameter for \\texttt{Ptemcee} against every other sampling approach. Each sampler method vs. another sampler method are denoted as different colors. The lower and upper end of boxes represent the 25th and 75th percentile credible regions respectively. The lower and upper end of the whiskers represent the 5th and 95th percentile credible regions. The orange lines are representative of the median JS values for each pair of compared samplers. We see here that \\texttt{VItamin} performs to within a degree of accuracy which is consistent with other Bayesian samplers when looking at predictions on an individual source parameter basis.}\n\\end{figure}\n\n%It is evident in Fig's \\ref{fig:JS_indi_par_cpnest}, %\\ref{fig:JS_indi_par_emcee}, \\ref{fig:JS_indi_par_ptemcee} that JS values for %individual source \n%parameters of \\texttt{VItamin} against all other sampler is generally \n%consistent with all other samplers against themselves. This is an important \n%point because it indicates that our \\ac{ML} approach is able \n%to produce Bayesian posteriors to within an accuracy which is at a similar \n%level of other Bayesian samplers, using the same individual source \n%parameter figure of merit used for other comparison studies in the Bayesian \n%\\ac{GW} parameter estimation literature %\\cite{1811.02042,2008.03312,PhysRevD.102.104057}. What is also \n%interesting to note is the level of disagreement of other Bayesian samplers \n%with themselves. This disagreement is especially prominent with regards \n%to source parameters $t_0$, $\\theta_{jn}$, $\\phi_{jl}$, $\\alpha$, and $\\delta$.\n%Although \\texttt{Emcee} results are fairly poor in comparison with other \n%approaches, they are a useful benchmark for indicating underperformance. \n\n\n\\section{Additional Supplemental \\texttt{VItamin} Results and Analysis}\n\nIn the following sections we will discuss additional analysis which supplement the \nmain \nresults of this chapter including: \ntraining \nset \\ac{SNR} distribution and it's  relationship to the \nperformance of \\texttt{VItamin}, as well as the structure and behavior \nof the \\ac{CVAE} latent space and it's relationship with \nthe predicted posterior distributions. \n\n\\subsection{Jensen-Shannon Divergence as a Function of Signal-to-Noise Ratio}\n\nOver the course of the work carried out in this chapter there was \nsome verbal discussion~\\chris{I think you should rephrase how you \nwant to introduce this section} on the possibility that high \\ac{SNR} \nsignals could be a limiting factor with regards to the performance of the \nneural network model. It was originally hypothesized that \ndue to the low number of high \\ac{SNR} signals in our training set \n(as seen in Fig.~\\ref{fig:VItamin_TrainingSet_SNR_Dist}), that the \nnetwork would perform worse on high \\ac{SNR} signals. This \nhypothesis is supported by the well known understanding in \\ac{ML} \nliterature that less available data in specific regions of the \nparameter space can cause a neural network model to underfit to those \nregions \\cite{Goodfellow-et-al-2016}. In Fig.~\\ref{fig:JS_vs_SNR_dynesty}\nthe \\ac{JS}-divergence for individual test sample cases \nof \\texttt{VItamin} vs. \\texttt{Dynesty} as a function of \\ac{SNR}. \nEach plus sign is representative of individual test cases and \ndifferent colors correspond to each interferometer. \n\n\\begin{figure}\n    \\includegraphics[width=\\columnwidth]{figures/JS_vs_SNR.png}\n    \\caption[14-dimensional JS-divergences of \\texttt{Dynesty} vs. \\texttt{VItamin} as a function of individual detector optimal SNR.]{\\label{fig:JS_vs_SNR_dynesty} We show here 14-dimensional \n    \\ac{JS}-divergence values of \\texttt{Dynesty} vs. \\texttt{VItamin} as a function of optimal\n    \\ac{SNR} (Ch.~\\ref{ch:chap_1}, Sec.~\\ref{sec:matched_filtering}). Different colours are representative of each of the 3 detectors (H1, L1, V1) used in the analysis. Each triangle symbol represents a different test \\ac{GW} case. As can \n    be seen, there does not appear to be a strong positive correlation with \\ac{SNR}.}\n\\end{figure}\n\nWe see in Fig. \\ref{fig:JS_vs_SNR_dynesty} that there is little to no \npositive correlation between \\ac{SNR} and the 14-dimensional \\ac{JS}-\ndivergence; instead, it appears that there is a slight negative \ncorrelation.\n\nThis plot shows that there would be marginal benefit gained from augmenting \nthe training set to more strongly emphasise high \\ac{SNR} \nsignals, and that the neural network may in fact struggle the most \nwith low \\ac{SNR} events. Given that the highest \\ac{JS}-divergence values \nappears to be loosely correlated with low \\ac{SNR} values, one might assume \nthat this could partially be solved by oversampling our training set \nin the low \\ac{SNR} regime. This is not necessarily practical given that \nthe prior would then need to be changed and thus the output posterior \nwould then need to be resampled to compensate. \\hunter{Not sure what to say \nafter this.} Even if there were a positive correlation it is unlikely that simply including more high \\ac{SNR} signals would be beneficial to the statistical results of the network model as a whole because there are fewer test signals at high \\ac{SNR} anyways due to the priors used.~\\chris{OK, I think that you need to make these arguments clearer - high SNR was a worry (but why?) - we tested it and it's actually low SNR that does worse - can we fix it by oversampling at low SNR? - well not easily because the prior is the prior - if we change that then we would have to resample the output to compensate - which we actually already do with distance.}\n\n%\n% How does vitamin perform with respect to SNR spread? \n%\nOne other interesting relationship to analyse is that between the 14-dimensional \n\\ac{JS}-divergence and the optimal \\ac{SNR} spread across all 3 detectors for a \ngiven \\ac{GW} test signal. The \\ac{SNR} spread is calculated by taking the difference \nbetween the maximum and minimum optimal \\ac{SNR} values for each test sample. We plot \nthe \\ac{JS}-divergence as a function of \\ac{SNR} spread in Fig.~\\ref{fig:14D_JS_SNR-spread} in order \nto gauge whether our neural network model performs worse when 1 or more detectors \nsees the test signal at a lower \\ac{SNR} than the other detectors. We see \nin Fig.~\\ref{fig:14D_JS_SNR-spread} that there appears to be no positive correlation \nand possibly a very weak negative correlation between the two quantities. This could \nindicate that our model has some difficulties with signals which have an equal amount \nof optimal \\ac{SNR} across all detectors.\n\n\\begin{figure}\n    \\centering\n    \\includegraphics{figures/JS_vs_SNR-spread.png}\n    \\caption[14-dimensional JS-divergences of \\texttt{Dynesty} vs. \\texttt{VItamin} as a function of individual detector optimal SNR spread.]{\\label{fig:JS_vs_SNR_dynesty} We show here 14-dimensional \n    \\ac{JS}-divergence values of \\texttt{Dynesty} vs. \\texttt{VItamin} as a function of optimal\n    \\ac{SNR} (Ch.~\\ref{ch:chap_1}, Sec.~\\ref{sec:matched_filtering}) spread. Each triangle symbol represents a different test \\ac{GW} case.}\n    \\label{fig:14D_JS_SNR-spread}\n\\end{figure}\n\n\n~\\chris{I also think that you should make a plot of JS divergences for the 1D cases and see if any particular parameter performs better or worse as a function of SNR. You have all the data - it's just a question of carefully choosing how to plot it and writing about it.}\n\n\\chris{Also, with the 14D JS values (and even the 1D) you should also look at the total network SNR AND look at the JS as a function of the spread in SNR - do we do worse when 1 detector doesn't see the signal?}\n\n\\subsection{VItamin Latent Space Analysis}\n%\n% Subsection intro\n%\nIn this section we will introduce diagnostic plots we have used in order to gauge the behaviour of our neural network model with respect to the latent space.\n%\n% Discuss the corner plot for test case 184.\n%\nFor context, we will first examine a test case at a median network \n\\ac{SNR} value of \\hunter{value}. As seen in Fig.~\\ref{fig:comp_post_0}, this \nmedian \\ac{SNR} event exhibits complex multi-modal behavior on multiple \nparameters including: the polarisation angle, time of coalescence, right \nascencsion and declination. We will discuss in the following paragraphs the \nlatent space structure associated with this test sample.\n\n%\n% Test set sample 0 corner plot\n%\n\\begin{figure}\n    \\includegraphics[width=\\columnwidth]{figures/comp_posterior_pub_plot_event_241.png}\n    \\caption[Posterior predictions from \\texttt{VItamin}, \\texttt{Dynesty} and \\texttt{Ptemcee} for the median SNR test sample case in the \\texttt{VItamin} paper training set.]{\\label{fig:comp_post_0} Corner plot showing 2 and 1-dimensional marginalised posterior distributions for the median \\ac{SNR} test dataset sample. Filled (red) contours represent the posteriors obtained from the \\ac{CVAE} approach and solid (blue) contours are the posteriors output from our baseline analysis (\\texttt{Bilby} using the \\texttt{Dynesty} sampler). In each case, the contour boundaries enclose $68,90$ and $95\\%$ probability. One dimensional marginalised posteriors for each parameter from both methods are plotted along the diagonal. Blue and red vertical lines represent the $5$---$95\\%$ symmetric confidence bounds for \\texttt{Bilby} and variational inference respectively. Orange crosses and vertical orange lines denote the true parameter values of the simulated signal. The original whitened noisy timeseries $y$ and the noise-free signal are plotted in blue and cyan respectively in the upper right hand panel. The test signal was simulated with network optimal signal-to-noise ratio of $10.89$.}\n\\end{figure}\n\n%\n% Discuss the latent space corner plots\n%\n\nThere is no hard and fast rule for determining the number of latent \nspace dimensions to use when deciding on the architecture for a \\ac{CVAE}. \nThat being said, our primary logical motivation for choosing a latent \nspace size of 15 is directly related to the total number of source \nparameters we are trying to get the neural network model to learn. \nWe want to ensure that the information in each source parameter dimension \ncan be encoded in a latent space which is of sufficient size to do so. \nAs can be seen in Fig.~\\ref{fig:latent_corner_0}, there are \nsome indications that this hypothesis may indeed be holding true. \n\n%\n% Test sample 0 latent space samples corner plot\n%\n\\begin{figure}\n    \\includegraphics[width=\\columnwidth]{figures/latent_pub_plot_event_241.png}\n    \\caption[Latent space samples corner plot for a test sample in the \\texttt{VItamin} paper training set.]{\\label{fig:latent_corner_0} We show in this figure latent space samples from all latent space dimensions of both the $q$ encoder network (blue) and the $r_1$ encoder network (red). Each point is representative of the predicted mean values for each latent space dimension (15). Each dimension on the horizontal and vertical axis represents a different latent space dimension. 1-dimensional histograms of latent space samples for each dimension are plotted along the diagonal. Contours represent the $68, 90, 95\\%$ credibility intervals.}\n\\end{figure}\n\nIn Fig.~\\ref{fig:latent_corner_0} we plot latent space samples drawn from \nlatent space predictions made by both the $q$ (blue) and $r_1$ (red) \nencoder networks after training. The probability distributions modeled by \nthe encoder networks are multivariate Gaussians, whose means and \nstandard deviations \nare infered by the encoders. If a dimension of the latent space is \nbeing used, we would expect that the corresponding 1-dimensional\nmarginalised posteriior for that latent space dimension along the diagonal \nof the corner plot to show some level of disagreement between the \npredictions from both encoder networks. The reasoning behind this \nstatement is that the $q$ network is given a different level of \ninformation with respect to the $r_1$ network. Specifically, the \n$q$ network is given not only the \\ac{GW} timeseries, but also the true \nvalues of the source parameters themselves, whereas the $r_1$ network \nis given the \\ac{GW} time series by itself. If a latent space dimension \nis not being used it means that there is no additional amount of \ninformation that can be gleamed from that dimension, so both encoder \nnetworks will simply return their default, mean zero unit variate \nGaussian distributions, which contribute nothing to the loss function. \nIf nothing is being contributed to the loss function, then nothing is \nbeing learned from that latent space dimension. We can say that there is a \nnull contribution to the loss function because the \\ac{KL} divergence \nbetween two Gaussian distributions is known to be zero. Since the \n\\ac{KL} component of the loss is zero for this dimension, weights will \nnot be updated during the backpropagation process which encourage this \ndimension to be used.~\\chris{OK, but lacking in mathematical rigour. We need to go through the maths in our next meeting. Each of your statements is basically correct but should be interspersed with equations supporting these statements.} \n\n%\n% Latent dimension corner description\n%\nFrom Fig.~\\ref{fig:latent_corner_0} we see that 5 of the 15 latent \nspace dimensions are not being used for this test case, where the  \n5 not being used from left to right on the horizontal axis are \ndimensions $z_3$,$z_4$,$z_8$,$z_{10}$, and $z_{15}$. It also appears that the $r_1$ encoder \nnetwork (red) is in-fact choosing to produce latent space samples \nwhich are representative of multi-modal distributions on some dimensions ($z_2$,$z_{14}$). \nThis should not be \nsurprising given that the $r_1$ encoder network's final output \nlatent space distributions are generated using a Gaussian Mixture \nmodel, where the motivation for using the Gaussian mixture model \nwas to encourage the $r_1$ network to encode different modes from the posterior \ndirectly in the latent space. It is also evident from the 2D posterior panels (i.e. $z_1$ vs. $z_{4}$)\nthat the mixture model in the $r_1$ encoder network is allowing for far more \nexpressive non-Gaussian shaped uni-modal distributions.\n\\hunter{Could add something about how phi and psi are unimodal, which is \nwhy only 2 dimensions have mulit-modes.}\n\n%\n% mode weight plot descriptions\n%\nWe see show in Fig.~\\ref{fig:latent_weight_0} predicted \nweights from the $r_1$ encoder network for the median \\ac{SNR} \ntest sample. It can be seen that the $r_1$ encoder network has assigned \na measurable amount of likelihood to 16 out of the 32 available latent space \nmodes, with all other \nmodes having essentially zero weight. The fact that there are \nseveral modes which \nare not assigned any weight at all may \nindicate that the Gaussian mixture model in the $r_1$ encoder network could \nhave a higher level of capacity than what is be needed.~\\chris{I would also recommend expanding this discussion of the weights to address the ensemble behaviour as well. Maybe you cold plot all other 249 weight distributions in the background with some transparency. You could then talk about the fact that some modes are never used by any test case indicating that we have enough modes. The plot can be quite messy but if the single test case you are interested in is plotted clearly in bold then it should be fine.}. \n\n%\n% mode corner plot posterior description\n%\nThe effect that the integrated \nGaussian mixture model in the $r_1$ network has on final posterior \nsamples, is perhaps most clearly illustrated in\nFig.~\\ref{fig:mode_corner_0}. \nHere, we sample from the 4 most likely latent space modes predicted by \nthe $r_1$ encoder (colored from highest to lowest likelihood as blue, \norange, green and red), where ``most likely'' is quantified through \nthe Gaussian mixture model weights. Posteriors for each mode are \nproduced by using latent samples from each mode and passing them \nthrough the $r_2$ decoder network. What we are left with are \nposteriors which represent the degree to which individual \nmodes in the \\texttt{VItamin} latent space contribute to the \nfinal posterior product. We note that the weight associated with \nprobability of drawing a sample from each mode is not included in \nFig.~\\ref{fig:mode_corner_0}.~\\chris{The only issue is the weight \nwhich isn't being applied in the plot. I think you should try to apply it.}. \nWe see in Fig.~\\ref{fig:mode_corner_0}, that the 2 most likely modes \n(blue, orange) agree strongly with each other across most \ndimensions ($\\Theta_{jn}$ and $\\phi_{jl}$ being possible \nexceptions), while the least likely 2 (green,red) also strong \ndisagreement on some parameters ($t_0$, $\\psi$, $\\alpha$, $\\delta$). \nOne might point out that the $r_1$ network has \nnot chosen to represent each mode in the posterior on $\\psi$ using \ndistinct modes in the latent space. We note that this is in-fact not \nsurprising given that we apply a reparameterisation to the \n$\\psi$ and $\\phi_0$ parameters (Sec.~\\ref{sec:phipsi_repar}) such that \nthe number of modes the network actually ``sees'' is effectively reduced.\n\n%~\\chris{OK, we have a number of issues here - even in this case the mixture modal is identifying 2 components of the sky posterior. These are not truly separate modes because they overlap but you can just see from Fig 5.13 (the physical posterior plot) that the sky posterior is a slightly odd shape. The network has tasked 2 latent space modes to try to model this. If you then look at the 2D posteriors you can see some evidence that each mode has slightly different properties in other parameters - e.g. the blue mode prefers smaller distances compared to the yellow mode. As mentioned before it would also be good to actually weight the different coloured posteriors in the mode plot.} \n\n%However, because the only mulitmodal \n%components of the posterior in this test case are in the \n%polarisation angle, it's likely we do not see multimodal behaviour \n%in the latent space because of the phase-polarisation reparametersation \n%outlined in Sec.~\\ref{sec:phipsi_repar}. The phase-polarisation \n%reparameterisation turns those 2 modes into 1 mode.\n\n%\n% Test sample 0 weights histogram\n%\n\\begin{figure}\n    \\includegraphics[width=\\columnwidth]{figures/latent_weight_pub_plot_event_241.png}\n    \\caption[Latent space weight plot for the median SNR test sample in \n    the \\texttt{VItamin} paper training set.]{\\label{fig:latent_weight_0} \n    Plotted are the predicted weight values from the $r_1$ encoder \n    network for a given posterior sample of the median \\ac{SNR} test \n    case as a function of latent space mode dimension number. Each \n    value is normalised such that the sum of the weights is 1, where 1 \n    is representative of the network model assigning a high \n    likelihood of sampling from that particular mode. \n    \\hunter{x axis should be mode number, not z dimension.}~\\chris{As mentioned in the text, I recommend also plotting (with transparency) the other 249 test case weights. Keep the primary curves bold and clear to see but then you can also discuss the distribution of weights over the test cases.}}\n\\end{figure}\n\n%\n% Test sample 0 mode posteriors\n%\n\\begin{figure}\n    \\includegraphics[width=\\columnwidth]{figures/modes_posterior_epoch_pub_plot_event_241.png}\n    \\caption[Modal posterior corner plot for the 1st~\\chris{change the test sample} test sample in the \\texttt{VItamin} paper training set.]{\\label{fig:mode_corner_0} Shown are posterior samples drawn from the 4 most likely latent space modes predicted by the $r_1$ encoder network. Colors denote each mode from highest to lowest mean mode weight as blue, orange, green and red respectively~\\chris{you need to either state the actual weights of each mode OR even better, normalise each posterior by its weight.}. The weight associated with each mode is not accounted for in the plot. Each dimension on the $x$ and $y$ axis represents 15 source parameter posteriors predicted. 1-dimensional marginalised posteriors of posterior samples for each source parameter are plotted along the diagonal. Contours represent the $68, 90, 95\\%$ credibility intervals. The orange vertical and and cross hairs represent the true source parameter values.~\\chris{ make the sky plot (for each of the modes).}}\n\\end{figure}\n\nWhat the results from Fig.~\\ref{fig:mode_corner_0} may imply \nis that the multi-modality clearly seen \nin the final posteriors of Fig.~\\ref{fig:comp_post_0} is being encoded across \nseveral modes in the latent space produced by $r_1$ encoder network. This \ncould indicate that the $r_1$ encoder network\nis partially determining what level of likelihood to assign to each \nmode in the posterior space. More work could be done in future \nstudies to more rigorously quantify this.\n\n%\n% Test sample 184 log weights histogram\n%\n%\\begin{figure}\n%    \\includegraphics[width=\\columnwidth]{figures/latent_logweight_pub_plot_event_184.png}\n%    \\caption[Latent space log weight plot for the 184th test sample in the \\texttt{VItamin} paper training set.]{\\label{fig:log_weight_184} Plotted are the predicted log'd weight values for the zeroth posterior sample of the 184th test sample as a function of mode latent space dimension number. Mode weights are predicted for each posterior sample by the $r_1$ encoder network.}\n%\\end{figure}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Dynesty vs. Dynesty Jensen--Shannon Divergence}\\label{dyn_v_dyn_JS}\n\nHere we provide some discussion regarding the lower limit of \\ac{JS} values \nwe might expect from \\texttt{VItamin}. We approximate a rough \nlimit by comparing two \nindependent \\texttt{Dynesty} runs on all $250$ test sample cases \nfor both the full 14-dimensional \\ac{JS}-divergence and the 1-dimensional \n\\ac{JS}-divergence.\n\n%\n% Discuss dynesty vs. dynesty on the full 14D case\n%\nIn Fig.~\\ref{fig:dyn_vs_dyn_ful14D_JS}, we compute the \\ac{JS}-divergence \nbetween two independent runs of \\texttt{Dynesty} for \neach of the 250 test cases across all 14 dimensions. The mean \n\\ac{JS} value across all test cases is $0.05$ with tails extending to a \nlower bound of $\\sim 10^{-3}$~\\chris{if this is for the 14-D case \nthen I'm sceptical of the lower bound here - I know that the\nuniversal divergence code gives negative numbers sometimes. You need to show and discuss the limitations and settings that you used to get these numbers.} and \nan upper bound of $\\sim 10^0$. Given that the \\texttt{Dynesty} sampler \nis known within the \\ac{GW} parameter estimation community to be one of the most\ntrusted and reviewed samplers~\\cite{2010.14527}. Given that \\texttt{Dynesty} \nis generally consistent between runs of the same data, we would expect \nthat two independent runs of the \\texttt{Dynesty} sampler should \nprovide us with a reliable lower limit on the best expected \n\\ac{JS} values we could hope to achieve. Given the range of \n\\ac{JS} values seen in Fig.~\\ref{fig:dyn_vs_dyn_ful14D_JS} and \ncomparing those values to those of Fig.~\\ref{fig:kl_results}, we see \nthat \\texttt{VItamin} results plotted against other sampler results do \ngenerally seem to have larger \\ac{JS} values than the mean of \n$0.05$ seen in Fig. \\ref{fig:dyn_vs_dyn_ful14D_JS}. This is to be \nexpected though because the \\ac{JS} values shown \nin  Fig.~\\ref{fig:dyn_vs_dyn_ful14D_JS} \nindicate a lower bound on the level of disagreement we \nexpect \\texttt{VItamin} to achieve between other \nsampler approaches. Furthermore, we see that the lowest \\ac{JS} value tails\nover all comparison results of \nFig.~\\ref{fig:kl_results} are consistent with the tails \nof Fig.~\\ref{fig:dyn_vs_dyn_ful14D_JS}. \n~\\chris{the plot you refer to here is rather dull. Why not also plot the equivalent distributions for the other samplers (including vitamin) as well?}\n\n%\n% Dynesty vs. Dynesty Full JS\n%\n\n\\begin{figure}\n    \\includegraphics[width=\\columnwidth]{figures/dynesty-dynesty_fullJS.png}\n    \\caption[\\texttt{Dynesty} vs. \\texttt{Dynesty} 14-dimensional \\ac{JS} divergence probability distribution plot.]{\\label{fig:dyn_vs_dyn_ful14D_JS} A probability distribution of \\ac{JS}-divergence values for \\texttt{Dynesty} vs. another independent run of \\texttt{Dynesty} using 14-dimensional \n    posteriors on the same test data. The mean \\ac{JS} divergence has a value of $0.05$~\\chris{indicate this on the plot visually}. We note that since since the \\ac{JS}-statistic is calculated using the \\texttt{universal-divergence}~\\cite{4839047} code-base, that there are some negative values which are not shown here.~\\chris{this should also be mentioned and explained in the main text. Also, as mentioned before, to make this more interesting you could also plot the same curves for the other samplers here too. Finally, can you sort out the fonts so that this is the same as the other plots and add (nats) to the x-axis label.}}\n\\end{figure}\n\n%\n% Dynesty vs. Dynesty 1D JS\n%\nIn Fig.~\\ref{fig:dyn_vs_dyn_indi_JS} we plot the \\ac{JS}-divergence \nbetween independent \\texttt{Dynesty} runs for using \n1-dimensional marginalised source parameter posterior results. Instead of \nusing the \\texttt{universal-divergence} code, we\ncalculate the \\ac{JS}-divergence using the analytic expression \ndefined in Eq.~\\ref{eq:JS_div} on the 1-dimensional marginalised posteriors \nbetween the two \\texttt{Dynesty} runs.~\\hunter{not sure if it's worth it \nto repeat the uncertainties here.} In the figure, different colors \nrepresent different source parameter \\ac{JS} distributions over all \n250 test cases. We see \nthat \\ac{JS}-diverence values across all source parameter distributions \nrange from $\\sim1 \\times 10^{-4} - 10^{-1}$. \nThe mean 1-dimensional \\ac{JS} value across all source parameter distributions\nis \napproximately $\\sim 10^{-3}$. This value indicates a lower limit \non the \\ac{JS}-divergence values we would expect to see with respect to \ncomparison results using 1-dimensional marginalised posteriors. \n\\hunter{Is this more coherent now?}\n\n\\begin{figure}\n    \\includegraphics[width=\\columnwidth]{figures/dynesty-dynesty_indiJS.png}\n    \\caption[Dynesty vs. Dynesty full 1-D JS divergence histogram plot.]{\\label{fig:dyn_vs_dyn_indi_JS} Shown are histograms of 1-dimensional JS divergence values for \\texttt{Dynesty} vs. another independent run of \\texttt{Dynesty}. Different colors represent JS values with respect to individual source parameter posterior \\texttt{Dynesty} predictions. Mean JS values for each source parameter are given as: $m_1 \\sim 0.00139$, $m_2 \\sim 0.00143$, $d_l \\sim 0.00142$, $t_0 \\sim 0.00358$, $\\theta_{jn} \\sim 0.00192$, $\\psi \\sim 0.00134$, $a_1 \\sim 0.00101$, $a_2 \\sim 0.00088$, $\\Theta_1 \\sim 0.00143$, $\\Theta_2 \\sim 0.00123$, $\\phi_{12} \\sim 0.00080$, $\\phi_{jl} \\sim 0.00136$, $\\alpha \\sim 0.00538$, $\\delta \\sim 0.00401$. JS values are calculated using the \\texttt{scipy} JS divergence code-base.~\\chris{I like what you're trying to do here but I think this would be far better displayed using box plots - you are currently struggling to represent the means using the caption which is not very sensible. With box plots you can still show the distribution but also then see how different parameters behave. I think this would be very useful and warrant discussion since I might expect some parameters to potentially have larger fundamental JS-calculation errors than others.}}\n\\end{figure}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Data Augmentation and Normalisation}\\label{sec:vit_data_aug}\n\nAs discussed previously in in Ch.~\\ref{ch:chap_2}, it is \noftentimes advantageous to augment the training set during training \nof a neural network. This is done to decrease the complexity of \nthe search space, as well as to provide a greater variety of \nsignals to the network such that it is better able to generalise \nto new signals when testing the model. \n\n%\n% Normalisation\n%\nThe first and most simple augmentation method we employ is that of\nnormalisation. \nWe normalise each source parameter value for all training samples such that \nthey lie between the values of zero and one (i.e. on the unit-hypercube). We also normalise the \nall timeseries in the training set using a normalisation factor such that all  \ntimeseries values also lie on the \nrange from zero to one. We note that this timeseries normalisation factor \nmust also then be applied during testing when using a pre-trained neural network. \nBoth of these normalisations are performed in order to reduce the search \nspace complexity. \n\n%\n% hour angle sky conversion stuff\n%\nWe also convert the right ascension source parameter values to \nthe hour angle parameter space. This is done because due to the \ndefinition of right ascension whereby different \\ac{GPS} times \nwill correspond~\\hunter{Need to ask Chris why hour angle conversion is \ndone again.}\n\n%\n% 2D cyclic parameter representation\n%\nIn order to make it easier for the network to predict cyclic parameter \nvalues which lie on the wrapped edges of the cylcic parameter space, we \nreparameterise all cylcic parameter values to be on the abstract \n2D plane. This conversion is done by enforcing the decoder network to \nproduce 2 means and 1 standard deviation characterising multivariate \nGaussians for each cyclic parameter (as \nopposed to the 1 mean for all other source parameters). The angle \nis then computed between the 2 predicted cyclic parameter means \nthrough the inverse tangent function. The inverse tangent converts the \n2-dimensional representation back to the original \nparameter space for all cyclic parameters. \n\n~\\chris{This all fits in nicely with the augmentation stuff- don't forget the hour angle sky conversion too.} Another augmentation technique that we apply \nis to \nallow the network to see multiple noise realizations of the same \nsignal multiple times. This is done by first enforcing that the network \nbe run over a subset of the entire training set, $2\\times10^4$ unique training \nsample waveforms, $4$ times. The cost function of the network \nis calculated by drawing a \nrandom batch of signals from the current training subset of $2\\times10^4$\nsignals, whereby each signal in the batch  \nis assigned a new white Gaussian \nnoise realisation. This means that we effectively train over an infinite \nnumber of Gaussian noise realisations.\nAfter the network has seen $2\\times10^4$ training signals $4$ times we then \nload in a new subset of $2\\times10^4$ training signals. By giving the network \nmultiple noise realisations for the same signals, we are hopefully \nencouraging the network to generalise to new noise realisations \nduring testing.\n\n%\n% t0, phi, distance augmentation\n%\nEvery time we give the network a new chunk of $2\\times10^4$ signals, \nwe also randomize the phase, time of arrival and distance of the \nnew loaded in training samples. We note that the new chunk of signals \nis read in already having existing values which have beend drawn from \nthe prior. This process is to relabel the source parameter values with \nnew draws from the prior and to also modify the noise-free timeseries \nof the training samples accordingly.\n%\n% Distance augmentation\n%\nFor distance, we first choose values uniformly at random from 0 to 1 for \neach distance training sample parameter. These values are then \nconverted to units of Mpc by \n%\n\\begin{equation}\\label{eq:dist_rescale}\n    d_{\\textrm{new}} = d_{\\textrm{min}} + d_{\\textrm{uni}} (d_{\\textrm{max}} - d_{\\textrm{min}}),\n\\end{equation}\n%\nwhere $d_{\\textrm{uni}}$ is a uniform set of numbers between 0 and 1, \n$d_{\\textrm{max}}$ represents the maximum allowed distance according to \nthe prior and $d_{\\textrm{min}}$ is the minimum allowed distance \naccording to the prior. We sample $d_{\\mathrm{uni}}$ from a unfiform \ndistribution simply because that is the prior we use for the \nluminosity distance. We then determine the scale factor by which \nthe distance has changed from its old value for each training \nsample by dividing the old distance by the new distance value.\n%\n\\begin{equation}\n    s = \\frac{d_{\\textrm{old}}}{d_{\\textrm{new}}}\n\\end{equation}\n%\nwhere $d_{\\textrm{old}}$ is the original distance value for the sample and $d_{\\textrm{new}}$ is the new value. In summary, all we're doing here is drawing \na new distance from the prior, and then computing a ratio between the old \nand new distance.\n\n%\n% Phase augmentation\n%\nIn order to get the phase augmentation correction term we do a similar \nprocess as the distance augmentation above. We begin by drawing \na new phase value from the prior with bounds that are defined by the \nphase prior. A phase correction term is then calculated\n%\n\\begin{equation}\n    \\Phi_{\\phi_0}^{\\textrm{corr}} = -\\exp\\left(i(\\phi_0^{\\text{new}} - \\phi_0^{\\text{old}})\\right),\n\\end{equation}\n%\nwhere $\\Phi_{\\phi_0}^{\\textrm{corr}}$ is the phase correction factor we \nwill use to randomize the phase, $\\phi_0^{\\textrm{new}}$ is the new \nrandomized phase value and $\\phi_0^{\\textrm{old}}$ is the \noriginal training sample phase value.\n\n%\n% time correction\n%\n\nThe time of coalescence correction term is then computed \nagain by first randomly drawing a new time of coalescence from the \nprior. We then find the difference between the new and old \ntimes and convert to the frequency domain given by the expression \n%\n\\begin{equation}\n    \\Phi_{t_0}^{\\textrm{corr}} = -\\exp\\left(i\\,2\\pi\\,\\vec{f_t}(t_0^{\\text{new}} - t_0^{\\text{old}})\\right)\n\\end{equation}\n%\n\\hunter{May want Chris to check this.}\nwhere $t_0^{\\textrm{new}}$ is the new time of coalescence, \n$t_0^{\\textrm{old}}$ is the old time of coalescence, \n$\\vec{f_t}$ is a frequency vector with values from 0 to the nyquist \nfrequency, and $\\Phi_{t_0}^{\\textrm{corr}}$ is the time of coalescence \ncorrection factor.\nFinally, given all the correction \nfactors for time of coalescence $\\Phi_{t_0}^{\\textrm{corr}}$, distance $s$ and \nphase at coalescence $\\Phi_{\\phi_0}^{\\textrm{corr}}$ have been calculated, \nwe need only simply multiply the phase correction term and the \ntime correction term by the real \\ac{FFT}~\\cite{Cooley1965AnAF} \nof the training sample \ntimeseries, $y$, where we note the time correction term is \nfrquency dependent and the phase correction term is a constant. \nThe application of all the correction terms may be \nexpressed as\n%\n\\begin{equation}\n    y_{\\phi \\textrm{corr}} = \\mathcal{F}(y)\\, \\phi_{\\textrm{corr}}\\, t_{\\textrm{corr}},\n\\end{equation}\n%\nwhere $\\mathcal{F}$ is the \\ac{FFT}. %defined as \n%\n%\\begin{equation}\n%    \\mathcal{F}(y) = \\sum_{n=0}^{N-1} y(n) \\exp\\left(\\frac{-i 2\\pi k n}{N} %\\right),\n%\\end{equation}\n%\n%where N is the total size of the time series, $k$ is \nWe note here that the time correction term effectively ``slides'' the signal \nin time, such that the end of the signal can be slid past the end of \nthe timeseries and end up at the start of the timeseries, and vice versa. \nThis is obviously unphysical, but we emphasise that our signals are \nconstructed so that they do not have significant amplitude at the \nboundaries of our timeseries. Additionally, the time of coalesence \nwindow defined by the prior is relatively narrow, hence we expect \nno unphysical signal wrapping.\n\n%\n% Get back to time domain\n%\nTo apply the distance term we  \ncompute the inverse real \\ac{FFT}~\\cite{Cooley1965AnAF}, $\\mathcal{F}^{-1}$, \nof $y_{\\phi \\textrm{corr}}$ and \nmultiply by the distance correction scale factor\n%\n\\begin{equation}\n    y_{\\phi \\textrm{corr}} = \\mathcal{F}^{-1}(y_{\\phi \\textrm{corr}})\\, d_{\\textrm{corr}}. \n\\end{equation}\n%\nAdding these randomized elements to the existing training workflow may   \nhelp to ensure that the neural network model does not \noverfit the training set. We also note that these augmentations \nwere a computationally cheap and simple \nmethod for expanding the effective training set size.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Phase and Psi Reparameterisation }\\label{sec:phipsi_repar}\n\nOne of the biggest issues we have faced while training the neural network has \nbeen dealing with the complex \nmulti-modal nature of the phase ($\\phi$) and psi ($\\psi$) parameters. \nAlong with the addition of the Gaussian mixture model component of the network \nmentioned previously, we have also implemented a reparameterization of both phase and \npolarisation angle in order to simplify the search space for the neural \nnetwork partly inspired by the work of Jones in~\\cite{10.1093/mnras/stv1584}.\n\n% why we are allowed to do this.\nWe are allowed to make the following reparameterisation due to the degeneracies \nin $\\psi$ and $\\phi_0$ of the signal model we use, where degeracy refers to different \n$\\psi,\\phi_0$ combinations which give rise to the same \\ac{GW} waveform. We note that \nif the signal contains higher order modes, these degeneracies are broken and thus \nthis reparameterisation would not be applicable in that case.~\\hunter{Is this \nenough of an intro to say why we're allowed to do this?}\nIn order to go from $\\psi$ and $\\phi$ to a new representation $\\psi^{'}$ and $X$, \nwe first take the remainder of the ratio \n$\\phi_0+\\psi$ and $\\pi$ which then becomes a new parameter denoted as $X$ given by\n%\n\\begin{equation}\n    X = (\\psi + \\phi_0) \\textrm{ mod } \\pi,\n\\end{equation}\n%\nwhere ``mod'' is the modulus. We also take the remainder \nof the ratio $\\psi$ and $\\pi/2$ given as\n%\n\\begin{equation}\n    \\psi^{'} = \\psi \\textrm{ mod } \\frac{\\pi}{2}.\n\\end{equation}\n%\nIn order to get back to the original $\\psi, \\phi_0$ representation, we \nchoose a set of two random integers with equal probability between zero and \n$2\\pi$ (denoted as $D_1$), as well as a \nset of two random integers with equal probability between $0$ and $\\pi/2$ (denoted as $D_2$) \nfor each $\\psi$ value and ensure both $\\psi^{'}$ and \n$X$ are in radians.\n~\\chris{D1 and D2 basically define which of the 4 tessellation that we use. I would discuss the tessellation figure before explaining the reverse process.} We then subtract off $\\psi^{'}$ from $X$, add both random radian integers and take the modulus  of the whole expression with respect to $2\\pi$ in order to get back $\\phi_0$. \n%\n\\begin{equation}\n    \\phi = ((X - \\psi^{'}) + D_{1} + D_{2}) \\textrm{ mod } 2\\pi     \n\\end{equation}\n%\nTo get back to $\\psi$ we add set \n$D_2$ and take the modulus with respect to $\\pi$\n%\n\\begin{equation}\n    \\psi = (\\psi^{'} + D_2) \\textrm{ mod } \\pi.\n\\end{equation}\n%\nThis essentially tessellates the $X-\\psi$ and $\\psi$ parameters across four quadrants of the parameter space while maintaining the same number of samples and general distribution shape.~\\chris{I find this explanation of how to get back to psi and phi very confusing - best to make more use of the figure with a clear description of what you're plotting and discuss it earlier on.}\n\nThe reparameterisation process is visually illustrated in Fig.~\\ref{fig:Xpsi}. It can be clearly seen that the 2-dimensional representation \n$X, \\psi^{'}$ in both the upper \nleft and lower right subplots, is vastly simpler than the original 2D $\\phi_0, \\psi$ representation. \nThe transformation is also able to maintain the property of being \nreversible~\\chris{well, not really. What does fully mean here? The process we have does not guarantee that being transformed forward then back would put you in the same place. Forwards maps you to the single master tessellation shape but backwards equally randomly places you in one of the 4 other tesselations. So not entirely reversible.}. \nAlthough, we do note that if one considers \\ac{GW} template waveforms with higher \norder modes this degeneracy is broken and the above reparameterization would not be necessary~\\cite{10.1093/mnras/stv1584}.\n\n~\\chris{One thing we don't address is the mystery as to why the CVAE didn't model the degeneracy itself. We needn't bring this up and simply argue that the reparameterisation is natural for our problem and simply avoids us having to deal with multimodal structures in the psi-phase space. You allude to this issue in your last sentence where you say that for higher modes this reparameterisation wouldn't be necessary. However, it's more like it wouldn't be valid. Whether or not the CVAE would then work without it is an unknown. }\n\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=16cm,height=20cm,keepaspectratio]{figures/Xpsi.png}\n    \\caption[An illustration of the $\\psi$ and $\\phi$ reparameterisation.]{\n    An illustration of the $\\psi$ and $\\phi$ reparameterisation. Upper left \n    plot: a random set of samples drawn from randomly chosen \n    multi-component (mixture) Gaussians for both $\\psi$ and $\\phi$\n    ~\\chris{the top left plot is representative of a single master \n    tessellation in the psi' and X space}. Red crosses denote each \n    Gaussian's mean and $X$ represents a reparameterization of \n    $\\psi$ and $\\phi$. Upper right: Same plot as the upper \n    left, \n    but with $\\psi$ subtracted off from the reparameterisation in \n    order to form a trapezoidal-like shape for tessellation purposes. \n    Lower left: We then apply a tessellation of the samples in the \n    upper right figure in order to convert the reparameterisation back \n    to the original units of $\\psi$ and $\\phi$. Lower right: We can \n    get back to the reparameterised version by applying our \n    reparameterisation trick again without any change to the original \n    in the upper left.~\\chris{We need to discuss exactly what these plots represent and how they were constructed. Assuming that the \"trick\" is valid then we generate in the psi', X space first (top right). We convert this to the psi,phi space in the top right. We tessellate the top right plot (using your D1 and D2 randomisation) to make lower left plot showing that the distribution on the full physical psi,phi space is just copies of the top right. The lower right plot is the lower left plot converted directly into psi', X and we can see that it is identical to the original top left plot.}}\n    \\label{fig:Xpsi}\n\\end{figure}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% CONCLUSIONS\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% conclusions - now draw conclusions about the quality of the comparison\n% results. Highlight the current limitations but also highlight the importance of\n% this for the GW field (multi-detector is easy, additional parameters are easy,\n% longer datasets may be a challenge regarding GPU memory?, we don't have to\n% assume a noise model if we inject training data into real noise, we do rely on\n% well defined signal models, EM-follow up in very low latency, can we use\n% transfer learning if we want to retrain, ...) End with broader statements about\n% inference in other fields and how this is applicable across the sciences.\n%\n% recap and main result\n%\n\\section{Summary}\n\nIn this chapter we have demonstrated that we are able to reproduce, to a high degree \nof accuracy, Bayesian posterior probability distributions generated through \\ac{ML}. \nThis is accomplished using a \\ac{CVAE} trained on simulated \\ac{GW} signals and does not \nrequire the input of precomputed posterior estimates. We have demonstrated that our \nneural network model, which\nwhen trained, can produce complete and accurate posterior estimates in a fraction of a second, achieves the same quality of results as the trusted benchmark analyses used within the \\ac{LVK}.\n\n%\n% CBC implications and why this is a game-changer - speed for EM followup\n%\nThe significance of our results is most evident in the orders of magnitude increase in \nspeed over existing algorithms. We have demonstrated the approach using \\ac{BBH} \nsignals but with additional work to increase sample rate and signal duration, the method \ncan also be extended for application to signals from \\ac{BNS} mergers (e.g.,\nGW170817~\\cite{PhysRevLett.119.161101}, and GW190425~\\cite{2020ApJ...892L...3A}) and\n\\ac{NSBH}~\\cite{Abbott_2021} systems where improved low-latency alerts will be especially \npertinent. By using our approach, parameter estimation speed will no longer be limiting\nfactor\\footnote{A complete low-latency pipeline includes a number of steps. The \nprocess of \\ac{GW} data acquisition is followed by the transfer of data. There is then the \ncorresponding candidate event identification, parameter estimation analysis, and the \nsubsequent communication of results to the \\ac{EM} astronomy community after which there \nare physical aspects such as slewing observing instruments to the correct pointing.} \nin observing the prompt \\ac{EM} emission expected on shorter time scales than \nis achievable with existing \\ac{LVK} analysis tools such as Bayestar~\\cite{2016PhRvD..93b4013S}.\n\n%\n% CBC implications and why this is a game-changer - faster, modular\n%\nThe predicted number of future detections of \\ac{BNS} mergers \n($\\sim 180$~\\cite{2018LRR....21....3A}) will severely strain the \\ac{GW} community's \ncurrent computational resources using existing Bayesian methods\n(Tab.~\\ref{tab:o3_events_runtime_1},Tab.~\\ref{tab:o3_events_runtime_2}). We \nanticipate that future iterations of our approach will provide full-parameter \nestimation on all classes of \\ac{CBC} signals in $\\mathcal{O}(1)$~s on single \\acp{GPU}. Our \ntrained network is also modular, and can be shared and used easily by any user to produce \nresults. The specific analysis described in this chapter assumes a uniform \nprior on the signal parameters. However, this is a choice and the network can be \ntrained with any prior the user demands, or users can cheaply resample accordingly \nfrom the output of the network trained on the uniform prior. We also note that \nour method will be invaluable for population studies since populations may now be generated and analysed in a fully-Bayesian manner on a vastly reduced time scale. \n\n%\n% future work, current limitations and prospects\n%\nFor \\ac{BBH} signals, \\ac{GW} data is usually sampled at $1$---$4$ kHz dependent upon \nthe mass of binary. We have chosen to use the noticeably low sampling rate of 1024Hz \nin order to decrease the computational time required to develop our approach and the \ncomputational burden of computing our 250 benchmark analyses for each of \n4 benchmark samplers.  We have found that increasing the sampling frequency of our \ninput comes at the cost of a small increase in training time and a similar \nincrease on the \\ac{GPU} memory requirement. We note that with the exception of \nrequiring 1-dimensional convolutional layers and an increase in the amount of \ntraining data to efficiently deal with a multi-detector analysis, the network \ncomplexity has not increased with the dimensionality of the physical parameter \nspace nor with the sampling rate of the input data. Given this, it is possible  \nthat extending the parameter space to lower masses may not be problematic.\n\n%\n% Non Gaussian noise and the final statement\n%\nIn reality, \\ac{GW} detectors are affected by non-Gaussian noise artefacts and \ntime-dependent variation in the detector noise \\ac{PSD}. Existing methods \nincorporate a parameterised \\ac{PSD} estimation into their inference~\\cite{2015PhRvD..91h4034L}. \nTo account for these and to exploit the ``likelihood-free'' nature of the \n\\ac{CVAE} approach, we could re-train our network at regular intervals using samples \nof real detector noise (preferably recent examples to best reflect the state of the detectors). \nIn this case we could also apply transfer learning to speed up each \ntraining instance based on the previously trained network state.  Alternatively, \nsince the \\ac{PSD} is an estimated quantity, we could \nmarginalise over its uncertainty by providing training data whitened by \nsamples drawn from a distribution of possible \\acp{PSD}. Furthermore, one could also \nprovide the \\ac{PSD} estimates from a distribution of \\acp{PSD} as an additional conditional \ninput to the \\ac{CVAE}. Our work can naturally be extended to include the full range \nof \\ac{CBC} signal types but also to any and all other parameterised \\ac{GW} \nsignals and to analyses of \\ac{GW} data beyond that of ground based \nexperiments. Given the abundant benefits of this method, we hope that a \nvariant of this of approach will form the basis for future \\ac{GW} parameter estimation.\n\n~\\chris{general note about the organisation of the chapter. It's not clear to me whether you should split the chapter into 2 parts (the paper and extra things). Also within the extra-things section, things are not flowing in a coherent way. Some things are sections, others are subsections, some things appear later on when they should probably go earlier. Have a look at the section headings and try to structure it better.}\n", "meta": {"hexsha": "5a537b58c4a191af33fe00bde776adaa6843787c", "size": 142851, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "vitamin.tex", "max_stars_repo_name": "hagabbar/The-Thesis", "max_stars_repo_head_hexsha": "1d8ac7a7b51daedf5c3ef849872991963e5fae9f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vitamin.tex", "max_issues_repo_name": "hagabbar/The-Thesis", "max_issues_repo_head_hexsha": "1d8ac7a7b51daedf5c3ef849872991963e5fae9f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vitamin.tex", "max_forks_repo_name": "hagabbar/The-Thesis", "max_forks_repo_head_hexsha": "1d8ac7a7b51daedf5c3ef849872991963e5fae9f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.1761297798, "max_line_length": 1344, "alphanum_fraction": 0.7377617238, "num_tokens": 39831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.33046813131717984}}
{"text": "\\subsubsection{\\stid{3.13} CLOVER Sub-project heFFTe}\\label{subsubsect:fftecp}\n\n\n\\paragraph{Overview}\n\nThe {\\it Highly Efficient FFTs for Exascale} ({\\bf heFFTe}) project provides sustainable \nhigh-performance multidimensional Fast Fourier Transforms (FFTs) for Exascale \nplatforms~\\cite{thasd19,heffte-iccs20}.\nHeFFTe leverages established but {\\it ad hoc} \nsoftware tools that have traditionally been part of application \ncodes, but not extracted as independent, supported libraries. \n%\nThe main objective of the heFFTe project is to:\n%\\begin{itemize}\n%\\item\n1)~ \n      Collect existing FFT capabilities from ECP \n      application teams;\n%\\item \n2)~\n      Assess gaps, extend, and make available various FFT\n      capabilities as a sustainable math library;\n%\\item \n3)~      \n      Explore opportunities to build multidimensional FFTs\n      while leveraging on-node concurrency from \n      batched FFT formulations;\n%\\item\n4)~\n      Focus on capabilities for Exascale platforms.\n%\\end{itemize}\n\nFFTs are used in many applications including molecular dynamics, \nspectrum estimation, fast convolution and correlation, signal \nmodulation and many wireless multimedia applications. The \ndistributed 3D FFT is one of the most important routines used \nin molecular dynamics (MD) computations, and its performance can \naffect MD scalability. The performance of the first \nprinciples calculations strongly depends on the performance of the \nFFT solver that performs many FFTs of size $\\approx 10^7$ points in \na calculation that we call batched FFT. Moreover, Poisson PDE-type \nequations arising from many engineering areas, such as plasma\nsimulation and density fields, need to solve FFTs of size larger than $10^9$. \n%\nMore than a dozen ECP applications use FFT in their codes.\nECP applications that require FFT-based solvers suffer from the lack of \nfast and scalable 3D FFT routines for distributed-heterogeneous parallel \nsystems as the ones projected for the upcoming exascale computing systems. \nTo address these needs, heFFTe functionalities are first delivered \nto CoPA projects using LAMMPS (molecular dynamics) and HACC (Hardware Accelerated\nCosmology Code).\n\nThe heFFTe software stack is illustrated in the left-hand side of Figure~\\ref{fig:fft-ecp-pipeline}, \nwhile the main components of the heFFTe framework are illustrated in the right-hand side of\nFigure~\\ref{fig:fft-ecp-pipeline}. \n% The first and last step address the need \n% for a flexible FFT API to take application-specific input and output (bricks/pencils), \n% including arbitrary initial decompositions. \n% Currently, heFFTe provides efficient\n% GPU support for all communication primitives and features in FFTMPI and SWFFT.\n \n\\begin{figure}[htb]\n    \\centering\n    \\includegraphics[width=0.42\\textwidth]{projects/2.3.3-MathLibs/2.3.3.13-CLOVER/heffte}~~\n    \\raisebox{.4\\height}{\\includegraphics[width=0.56\\textwidth]{projects/2.3.3-MathLibs/2.3.3.13-CLOVER/ffttransormations}}\n    \\caption{\\label{fig:fft-ecp-pipeline}\n    {\\bf Left}: the heFFTe software stack. {\\bf Right}: 3D FFT computational pipeline in heFFTe with:~\n      1) Flexible API for application-specific input and output,\n         including bricks/pencils/etc.;~\n      2) Efficient packing/unpacking and MPI communication\n         routines;~\n      3) Efficient 1D/2D/3D FFTs on the node.}\n\\end{figure}\n\n\\paragraph{Key  Challenges}\n\\begin{enumerate}\n\\item\n\\textbf{Communication costs:}\n%Today's machines have very complex memory hierarchies and thus data movement, \n%data layout translation, and communication should be the main focus of any \n%distributed FFT library that aims to improve the performance of any ECP \n%application that relies on FFT. \nCommunication costs are main bottleneck \non current systems; this includes low node bandwidth (relative to \nhigh compute capabilities) and sub-optimal accelerator-aware MPI \ncommunications that can lead to some stong scalability issues~\\cite{heffte-pact21}.\n\n\\item\n\\textbf{Application specifics:}\nECP applications that require FFT-based solvers suffer from the lack of fast \nand scalable FFTs for distributed-heterogeneous parallel systems \nas the ones projected for the upcoming exascale computing systems. Also, ECP \napplications need different application-specific versions of FFTs,\nand dictate parallelism and data distributions (where is the data, how is \ndistributed, what is the parallelism, etc.). This requires application\nknowledge and API designs with a suitable modular high-performance \nimplementation that is flexible and easy to use and integrate in ECP applications.\n\n\\item\n\\textbf{Performance portability:}\nPerformance portability across different architectures is always a challenge.\nThis is further exacerbated due to the many application and \nhardware-specific FFT versions needed.\n\\end{enumerate}\n\n\\paragraph{Solution Strategy}\n\n\\begin{enumerate}\n\\item\n\\textbf{Communications and GPU optimizations:}\nFFTs are communication bound and a main focus in heFFTe is on algorithmic\ndesign to minimize communication and efficient GPU \nimplementations~\\cite{sc19,eurompi19,heffte-pact21,hpec21}.\nOther strategies include the use of mixed-precision calculations~\\cite{Haidar2018,tcfft18}\nand data compression for reduced communications (including lossy, e.g., using ZFP \ncompression)~\\cite{Anztetal2020}.\n\\item\n\\textbf{Evolving design:}\nheFFTe is designed to support the fftMPI and SWFFT functionalities,\nwhich are already integrated in ECP applications. Thus, heFFTe benefits\ndirectly these applications and provides integrated solutions. \nMore functionalities and application-specific optimizations will be added \nthrough heFFTe backends to support various ECP applications. \n\\item\n\\textbf{Autotuning:}\nPerformance portability will be addressed through use of standards (like 1D FFTs \nfrom vendors), portable linear algebra (LA) using MAGMA~\\cite{Tomov_2010_pcsa}, \nand parameterized versions that will be tuned across architectures. We have extensive \nexpertise and well proven track record in the development and use of autotuning techniques \nfor important LA kernels~\\cite{Nath2010,Kurzak2012gemmfermi}. \n\\end{enumerate}\n\n\\paragraph{Recent Progress}\nThe heFFTe team completed two main milestones involving software releases adding \nnumerous stability, performance, and scalability enhancements, as well as new \nfunctionalities~\\cite{heffte-pact21}. \nHeFFTe 2.1 was released in April 2021, and heFFTe 2.2 was released in October \n2021. HeFFTe 2.1 added support for multidimensional FFTs and optimizations for real data.\nThis included the development of R2C and C2R FFTs and their integration in heFFTe and \nspecific optimizations in ECP applications. Support and optimizations was extended for AMD \nGPUs, dependence on MAGMA was added, as well as spack installation, and integration of heFFTe in xSDK.\nHeFFTe was also integrated in CoPA projects and ExaAM/Meumapps with new application-specific \noptimizations, tuning, and added Intel GPU support. \nHeFFTe 2.2 concentrated on adding support and optimization of the HIP and Intel GPU backends to \nheFFTe. HeFFTe's functional and performance portability on these architectures and\nmulticore CPUs was established~\\cite{hpec21}, as well as ease of integration in the ECP applications \nusing heFFTe. \nMultidimensional FFTs for \nfast discrete convolution, cosine (DCT), and sine (DST) transforms were also added with support \nfor Nvidia, AMD, \nand Intel GPUs. HeFFTe has demonstrate very good strong scalability and performance that is \nclose to 90\\% of the roofline peak on the newly added in heFFTe v2.2 R2C, C2R, convolution,\nDCS and DST transformations~\\cite{heffte-pact21,heffte-iccs20} (see Figure~\\ref{fig:fft-ecp-progress}). \nAn FFT benchmark for a number of FFT libraries, including a design study and evaluation of FFT \ncodes used in the ECP applications, was also developed~\\cite{fftbenchmark}.\n\n\\begin{figure}[htb]\n   \\centering\n%   \\includegraphics[width=0.55\\textwidth]{projects/2.3.3-MathLibs/2.3.3.13-CLOVER/heFFTeAcceleration}~~~\n   \\includegraphics[width=0.32\\textwidth]{projects/2.3.3-MathLibs/2.3.3.13-CLOVER/heFFTeStrongScalability}\n   \\includegraphics[width=0.65\\textwidth]{projects/2.3.3-MathLibs/2.3.3.13-CLOVER/heffte_conv_dst}\n    \\caption{\\label{fig:fft-ecp-progress}\n    %{\\bf Left}: heFFTe acceleration of $1024^3$ FFT on 4 Summit nodes.\n    %            Note: nodal computations are accelerated $43\\times$. \n    {\\bf Left}: heFFTe strong scalability on $1024^3$ \n                FFT on up to 256 nodes ($\\times 6$ V100 GPUs;\n                double complex arithmetic; starting and ending with bricks; \n                performance assumes $5 N^3 log_2 N^3$ flops).\n    {\\bf Middle}: Convolution of $512^3$ multidimensional arrays in double complex arithmetic.\n    {\\bf Right}: Performance of the Discrete Sine Transformation (DST) in heFFTe 2.2.\n    }\n\\end{figure}\n\n\n\\paragraph{Next Steps}\nNext steps of work are adding multidimensional batched FFTs and optimizations.\nThis will include support for AMD, Nvidia, and Intel GPUs.\nFurther integration and use will be added to CoPA applications and the ExaAM project.\nAutotuning framework that hides backend selection and other parameters from users\nwill be added, as well as improved GPU-aware MPI Alltoallv routines, mixed-precision, \nand approximate FFTs. Existing FFT libraries will be evaluated through the FFT \nbenchmark~\\cite{fftbenchmark}.\n\n\n\n", "meta": {"hexsha": "3982556a1d527a5c4bc356acaf799ff330f3b0ad", "size": 9373, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "projects/2.3.3-MathLibs/2.3.3.13-CLOVER/2.3.3.13-FFT-ECP.tex", "max_stars_repo_name": "PHHargrove/ECP-ST-CAR-PUBLIC", "max_stars_repo_head_hexsha": "6a42725738658c73ed14d61ca5c0bbe330441dbc", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "projects/2.3.3-MathLibs/2.3.3.13-CLOVER/2.3.3.13-FFT-ECP.tex", "max_issues_repo_name": "PHHargrove/ECP-ST-CAR-PUBLIC", "max_issues_repo_head_hexsha": "6a42725738658c73ed14d61ca5c0bbe330441dbc", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-12T19:39:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-12T19:39:54.000Z", "max_forks_repo_path": "projects/2.3.3-MathLibs/2.3.3.13-CLOVER/2.3.3.13-FFT-ECP.tex", "max_forks_repo_name": "PHHargrove/ECP-ST-CAR-PUBLIC", "max_forks_repo_head_hexsha": "6a42725738658c73ed14d61ca5c0bbe330441dbc", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-10-15T23:45:24.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-15T23:45:24.000Z", "avg_line_length": 50.3924731183, "max_line_length": 123, "alphanum_fraction": 0.7853408727, "num_tokens": 2328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.33046813131717984}}
{"text": "\\documentclass{article}\n\\usepackage{amsmath}\n\\usepackage{ulem}\n\\usepackage{asciimth}\n\n\\def\\startTrace{\\message{Starting trace...$}%\n    \\tracingmacros=2\\tracingassigns=2\\tracingcommands=2%\n}\n\\def\\endTrace{\\message{Ending trace...$}\\tracingmacros=0\\tracingassigns=0\\tracingcommands=0}\n\n\\def\\textbs{\\char92\\relax} % backslash\n\n% OK, note this doesn't really test spaces well.\n\\begingroup\n\\catcode32=13%\n\\gdef\\changeSpaces{%\n\\catcode32=13%\n\\catcode126=12\n\\let =\\ %\n}\n\\endgroup\n%HACK\n\\def\\changeSpacesBack{\\catcode32=10\\catcode126=13}\n\n\\def\\testRow{\\hline\\changeSpaces\\testRowA}\n\\def\\testRowA#1{%\n    \\changeSpacesBack\n    \\exampleRow{\\sanitizeVerbose#1\\end}{`#1`}%\n}\n\n\\def\\exampleRow#1#2{%\n    {\\tt\\char18#1\\char18}%\n    %& #2\\tabularnewline%\n    & \\mathcell{#2}\\tabularnewline\n}\n\n% This is a little bit of a hack, but it was the easiest way I could\n% figure out to get the math looking pretty inside of a table cell.\n\\def\\mathcell#1{{\n    \\fboxrule=0pt\n    \\fbox{$\\displaystyle #1$}%\n    }%\n}\n\n% We can't just set the catcodes of ^ and _ because we want them as letters\n% in the \\tt but as super/subscripts in the `...`.\n\\def\\sanitizeVerbose{\\futurelet\\nextTok\\sanitizeVerboseA}\n\\def\\sanitizeVerboseA{%\n    \\ifx\\nextTok\\bgroup\\let\\next=\\sanitizeGroupAndRepeat\n    \\else\\let\\next=\\sanitizeVerboseB\n    \\fi\\next\n}\n\\def\\sanitizeGroupAndRepeat#1{%\n    \\{\\sanitizeVerbose#1\\end\\}\\sanitizeVerbose\n}\n\\def\\sanitizeVerboseB#1{%\n    \\ifx#1\\end\\let\\next=\\relax\n    \\else\\ifx#1^\\def\\next{\\char94\\sanitizeVerbose}%\n    \\else\\ifx#1_\\def\\next{\\char95\\sanitizeVerbose}%\n    % If it's a macro, unpack the name.\n    \\else\\ifcat\\noexpand#1\\def\\def\\next{\\string#1\\sanitizeVerbose}%\n    \\else\\def\\next{#1\\sanitizeVerbose}%\n    \\fi\\fi\\fi\\fi\n    \\next\n}\n\n\\def\\rawExampleRow{\\hline\\changeSpaces\\readFirstPart}\n\\def\\readFirstPart#1{\\changeSpacesBack\\exampleRow{#1}}\n\n\\newenvironment{examples}[1]\n    {\\renewcommand{\\arraystretch}{1.5}\n    \\renewcommand{\\tabcolsep}{0.2cm}\n    \\noindent\\begin{tabular}{|p{6cm}|p{4cm}|}\n        \\multicolumn{2}{c}{\\textbf{#1}}\\\\}\n    {\\hline\\end{tabular}}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\title{The {\\tt asciimth} package}\n\\author{Judah Jacobson}\n\\begin{document}\n\\maketitle\n\n\\section{Introduction}\nThe {\\tt asciimth} package provides a more readable way to typeset\nmathematics in \\LaTeX{}.  \nWe provide a few environments to replace those provided by \\LaTeX{} and {\\tt amsmath}:\n\\begin{itemize}\n\\item The {\\tt asciimth} and {\\tt asciimth*} environments act like {\\tt equation} and {\\tt\nequation*}, except that the math inside uses the asciimth syntax.\n\\item The {\\tt alignA} and {\\tt alignA*} environments act like {\\tt align} and {\\tt align*}:\nformatting is done by \\verb|&| and \\verb|\\\\|, but the math inside is written using {\\tt\nasciimth}'s syntax.\n\\end{itemize}\nFor example, we can use the following code to typeset a formula for the root of a cubic polynomial (via Wikipedia):\n\\begin{verbatim}\nWhen `x^3+a x^2+b x+c`, one of the roots is\n\\begin{asciimth*}\n-1/3( a +root3( (m + sqrt(m^2-4k^3) ) / 2 )\n        +root3( (m - sqrt(m^2-4k^3) ) / 2 ))\n\\end{asciimth*}\nwhere:\n\\begin{alignA*}\nm &= 2a^3-9a,\\\\\nk &= a^2-3b.\n\\end{alignA*}\n\\end{verbatim}\n\nIt renders as:\n\nWhen `x^3+a x^2+b x+c`, one of the roots is\n\\begin{asciimth*}\n-1/3( a +root3( (m + sqrt(m^2-4k^3) ) / 2 )\n        +root3( (m - sqrt(m^2-4k^3) ) / 2 ))\n\\end{asciimth*}\nwhere:\n\\begin{alignA*}\nm &= 2a^3-9a,\\\\\nk &= a^2-3b.\n\\end{alignA*}\n\n\nAdditionally, \nany text surrounded by\nleft-quotes (\\char18\\ldots\\char18) will be parsed by the {\\tt asciimth}\nengine.  For example, typing {\\tt\\char18 (x-1)\\char94(2x)/(4-3)\\char18} in\nthe middle of a paragraph produces `(x-1)^(2x)/(4-3)`.  \n\nThat notation can be mixed with standard \\TeX{} math commands by\ninserting a left-quoted expression in the middle of an existing expression or\nequation.  For example, \\verb|$\\frac{1}{2}-`3/4`$| is typeset as \n$\\frac{1}{2}-`3/4`$.  It can also be embedded into display math\n(\\verb|$$| or \\verb|\\[|) or a math environment such as {\\tt multiline} or\n\\texttt{align}.\n\nFor compatibility with the common use of left-quotes, the empty expression \n{\\tt\\char18\\char18} is typeset as the begin-quotes symbol (``).  \nHowever, if you really need them, we provide the macros {\\tt \\textbs makeQuoteOther}\nand {\\tt\\textbs makeQuoteActive} which turn that special behavior off and on, respectively.\n\n\nThis document displays a range of example equations as typeset by {\\tt\nasciimth}.  It serves both as documentation and as a comprehensive\ntest of the package.\n\n\\begin{section}{Tables}\n\n\\begin{examples}{Simple commands}\n\\testRow{9+alpha}\n\\testRow{gamma>2 implies gamma*gamma>4}\n\\testRow{x ge 0 implies x x ge 0}\n\\testRow{t}\n\\testRow{1-a}\n\\testRow{1 234}\n\\testRow{a b - a\\,b}\n\\testRow{ (9)}\n\\testRow{9+(4-(alpha))}\n\\testRow{(-)}\n\\testRow{[2,3)}\n\\testRow{\"Im\"(f) \" such that \" f>0}\n\\rawExampleRow{ }{` `}\n\\rawExampleRow{}{``}\n\\end{examples}\n\n\\begin{examples}{Fractions and parentheses}\n\\testRow{9/2}\n\\testRow{(1//2]/(7//4)}\n\\testRow{(9)/(7) + ((8))/(((15)))}\n\\testRow{ 24/3 + ((alpha+2)/2 * 5)/7}\n\\testRow{2/3/3}\n\\testRow{-5/zeta}\n\\testRow{z/((q*(2/beta to gamma)))}\n\\testRow{([2/3])/7}\n\\testRow{Phi = 1+1/(1+1/(1+cdots))}\n\\testRow{left< 2/3 right|}\n\\testRow{(7 middle| 2/3 right.}\n\\end{examples}\n\n\\begin{examples}{Fonts}\n\\testRow{hat(a) + tilde(b) + bar(c) + widehat(a b c)}\n\\testRow{cal(T) [bf(x)] in bb(R)^n}\n\\end{examples}\n\n\n\\begin{examples}{Exponents and subscripts}\n\\testRow{5^14}\n\\testRow{5_14}\n\\testRow{(9^-74)}\n\\testRow{ 125^-74}\n\\testRow{1/125^74}\n\\testRow{(1/125)^74}\n\\testRow{alpha^(2+3)/5}\n\\testRow{x^n y_1^-t alpha^-(beta-z)}\n\\testRow{(q r s)_(123)^-[456/z]}\n\\testRow{a_1^2}\n\\testRow{(x)_-i + q^r_(s)}\n\\testRow{(a+b)_(k_1)^(x+2)}\n\\testRow{sum_(n=1)^infty 1/n^2}\n\\testRow{int_pi^infty 1/(sin x)^2\\,d x}\n\\testRow{lim_substack(x to 0\\\\ y to 1) x^2(y-1)^2} \n\\end{examples}\n\n\\begin{examples}{Square roots}\n\\testRow{sqrt 2}\n\\testRow{sqrt(2+4/5)}\n\\testRow{2/sqrt(3alpha)}\n\\testRow{sqrt sqrt 3}\n\\testRow{(2+3)/sqrt sqrt sqrt 3}\n\\testRow{root n (x^2+1)}\n\\testRow{(-b pm sqrt(b^2-4a c))/(2a)}\n\\testRow{sqrt x^3}\n\\end{examples}\n\n\\begin{examples}{Symbols}\n\\testRow{a_1...a_n}\n\\testRow{a_1,...,a_n}\n\\testRow{f:bb(R)^2->bb(R)}\n\\testRow{>= <= => != -= ~ ~= ~~ ~-}\n\\end{examples}\n\n\\begin{examples}{Matrices}\n\\testRow{matrix[y]}\n\\testRow{matrix(a,1,c)}\n\\testRow{matrix(3a;b^2;c-5d)}\n\\testRow{matrix[2, sqrt(x^3), x^3/(7-x); (d),e,f]}\n\\testRow{matrix[x;y; z right.}\n\\testRow{matrix[A_(1,1), ... ,A_(1,n); vdots,ddots,vdots; A_(m,1), ... ,A_(m,n)]}\n\\end{examples}\n\n\\begin{examples}{Embedded LaTeX environments}\n\\rawExampleRow\n{x/env\\{pmatrix\\}(2 \\& 3 \\textbs\\textbs 4 \\& 5)}\n{`x / env{pmatrix}(2&3\\\\4&5)`}\n\\rawExampleRow\n{env\\{cases\\}(sqrt(x) \\& \" if \" x >= 0\\textbs\\textbs \"undefined\" \\& \" otherwise.\")}\n{`env{cases}(sqrt(x) & \" if \" x >= 0\\\\ 0 & \" otherwise.\")`}\n\\end{examples}\n\n\\par\n\\par\nThe {\\tt raw} command lets you embed raw TeX commands inside of an asciimth environment.\nUnlike for other commands, curly braces must be used for {\\tt raw}.\n\nAs a shortcut, you can also type \\texttt{label\\{equationName\\}} inside of an {\\tt asciimth} or {\\tt alignA} environment.  It will have the same effect as typing\\\\ {\\tt raw\\{\\char92label\\{equationName\\}\\}}\n\n\\begin{examples}{Braces and raw commands}\n\\testRow{2^(3+y) + raw{\\frac{5}{6x}}}\n\\testRow{2^raw{\\frac78}}\n\\rawExampleRow\n{\\relax2 + raw\\{\\textbs{}begin\\{pmatrix\\}2\\textbs\\textbs3\n\\textbs{}end\\{pmatrix\\}\\}}\n{`2 / raw{\\begin{pmatrix}2\\\\3\\end{pmatrix}}`}\n\\testRow{t*{2+alpha}^2}\n\\testRow{t*{(2+alpha)}^2}\n\\testRow{ {2+x}/{gamma^2beta}}\n\\testRow{ \\{2/(x+y)\\}^3}\n\\end{examples}\n\n\n\n\\end{section}\n\n\\begin{section}{Layout tests}\n\nThese examples cover a few issues which are caused by the fact that we always\nuse {\\tt\\string\\left} and {\\tt\\string\\right} delimiters:\n\\begin{itemize}\n\\item Using {\\tt\\string\\left(\\ldots\\string\\right)} causes different\nspacing than\n{\\tt(\\ldots)}.  That issue has been resolved.\n\\item The parentheses around the inner `sum` in the last example\nare too large; they unnecessarily grow\nto cover the subscript `j`.\n\\end{itemize}\n\n\\begin{examples}{Parenthesis tests}\n\\testRow{f(x)+g(x/y)}\n\\testRow{(x+y)(x-y)}\n\\testRow{f(x^2)+f(2^(2/y))}\n\\testRow{(x^2)^2}\n\\testRow{sum(x_i)+sum(x/y).}\n\\testRow{sum_i(sum_j(2*x))}\n\\end{examples}\n\n\\end{section}\n\n\n\\end{document}\n", "meta": {"hexsha": "570df0c3a79cf9d1cf954daf746c5ac0118f1b21", "size": 8263, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "examples.tex", "max_stars_repo_name": "judah/asciimath-tex", "max_stars_repo_head_hexsha": "b5001bd82554c5d73458ac675c47b687190aed37", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2015-05-17T18:30:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-08T01:09:41.000Z", "max_issues_repo_path": "examples.tex", "max_issues_repo_name": "judah/asciimath-tex", "max_issues_repo_head_hexsha": "b5001bd82554c5d73458ac675c47b687190aed37", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-02-19T16:20:01.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-19T16:20:01.000Z", "max_forks_repo_path": "examples.tex", "max_forks_repo_name": "judah/asciimath-tex", "max_forks_repo_head_hexsha": "b5001bd82554c5d73458ac675c47b687190aed37", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-03-02T07:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-29T18:21:03.000Z", "avg_line_length": 28.5916955017, "max_line_length": 204, "alphanum_fraction": 0.6744523781, "num_tokens": 3064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.33032460548169035}}
{"text": "\\documentclass[10pt,a4paper]{article}\n\\usepackage{todonotes}\n\\usepackage{amsmath}\n\\usepackage{booktabs}                    % Support for better table layout\n\\usepackage{tabularx}\n\n\\title{Formal description of the generated ILP}\n\n\\begin{document}\n\n\\section{Problem description}\n\nGiven the following:\n\n\\begin{itemize}\n\t\\item A set of properties $P = P_{software} \\cup P_{hardware}$\n\t\\item A set of software components $C$\n\t\\item For each software component $c \\in C$\n\t\\begin{itemize}\n\t\t\\item a set of provided properties $P(c) \\subseteq P_{software}$\n\t\t\\item a set of implementations $I(c)$\n\t\\end{itemize}\n\t\\item For each implementation $i \\in I(c)$ of component $c$\n\t\\begin{itemize}\n\t\t\\item a set of required software components $Req(i) \\subseteq C \\setminus i$\n\t\t\\item a set of modes $M(i)$\n\t\\end{itemize}\n\t\\item A set of resources (containers) $R$\n\t\\item For each resource $r \\in R$\n\t\\begin{itemize}\n\t\t\\item a set of provided properties $P(r) \\subseteq P_{hardware}$\n\t\\end{itemize}\n\\end{itemize}\n\nThe total number of modes is therefore\n\\begin{equation}\n\t\\sum_{c}^{C} \\sum_{i}^{I(c)} |M(i)|\n\\end{equation}\n\nGiven a mode $m$ of implementation $i$ and component $c$, there is a contract restricting the deployment of $m$, containing any number of the following items\n\n\\begin{itemize}\n\t\\item Constraints $CS(c_{req},m) = (p, \\circ, val)$ for a required software component $c_{req} \\in Req(i)$\n\t\\begin{equation}\n\tp \\circ val, \\text{where } p \\in P(c_{req}), \\circ \\in \\{<, \\leq, >, \\geq \\}\n\t\\end{equation}\n\t\\item Constraints $CR(m) = (p, \\circ, val)$ for a resource\n\t\\begin{equation}\n\tp \\circ val, \\text{where } p \\in P_{hardware}, \\circ \\in \\{<, \\leq, >, \\geq \\}\n\t\\end{equation}\n\t\\item Provisions $Prov_m = (p, \\circ, val)$\n\t\\begin{equation}\n\tp \\overset{!}{\\circ} val, \\text{where } p \\in P(c), \\circ \\in \\{<, \\leq, >, \\geq, = \\}\n\t\\end{equation}\n\\end{itemize}\n\nFor each element $E$ of a contract, there are functions to ``access'' their sub-elements:\n\\begin{equation}\n\tE = (p, \\circ, val) \\Leftrightarrow p(E) = p, sense(E) = \\circ, val(E) = val\n\\end{equation}\n\nThe optimization problem is to find a mapping from one mode of each software component\\footnote{which is needed to serve the request} to one resource such that all constraints of the contracts hold.\n\n\\section{ILP description}\n\nThere are two kinds of used variables, $x_{m,r}$ and $y_{i}$, in the ILP. To describe the constraints, some auxiliary functions are needed:\n\\begin{itemize}\n\t\\item $x_{m,r}$ \\dots Deployment of mode $m$ on resource $r$ (binary variable)\n\t\\item $y_{i}$ \\dots Deployment of implementation $i$ (binary variable)\n\t\\item $reqModes(p)$ \\dots Every mode having a constraint on the property~$p$\n\t\\item $reqModes(p,c) = reqModes(p) \\cap \\left( \\bigcup\\limits_i^{I(c)} M(i) \\right)$ \\dots Every mode of component~$c$ having a constraint on the property $p$\n\t\\item $Req(c)$ \\dots Every component required by implementations of component $c$\n\t\\item\n\t$\n\tval(p,x) \\in\n\t\\begin{cases}\n\tP_{Software} \\times M & \\text{value of property }p\\text{ required in mode }x \\\\\n\tP_{Hardware} \\times R & \\text{value of property }p\\text{ provided by resource }x \\\\\n\t\\end{cases}\n\t$\n\t\\item $req_{all}(c) = \\bigcup_i^{I(c)} Req(i) $\n\t\\item $req_{map}(c) = \\bigcup_c^{req_{all}(c)} \\langle c, I^{-1}(c)  \\rangle $\n\\end{itemize}\n\n\\subsection{The constraints}\n\nImplementation $i$ is deployed $\\Leftrightarrow y_i \\equiv 1$, also ensures, that only one mode is deployed per component\n\\begin{equation}\n\t\\forall c \\in C, \\forall i \\in I(c): y_i = \\sum_{r}^{R} \\sum_{m}^{M(i)} x_{m,r} \\label{eq:impl-shortcut}\n\\end{equation}\nDeploy required components:\n\\begin{equation}\n\t\\forall c \\in C, \\langle c_{req}, I' \\rangle = req_{map}(c):\n\t\\sum_{i_{req}}^{I(c_{req})} y_{i_{req}} \\geq \\sum_{i}^{I'} y_i\n\t\\label{eq:req-comp}\n\\end{equation}\nSoftware property requirement clauses:\n\\begin{multline}\n\t\\forall c \\in C, \\forall p \\in P_{software}: \\\\\n\t\\sum_{r_1}^{R} \\sum_{c_{req}}^{Req(c)} \\sum_{i_{req}}^{I(c_{req})} \\sum_m^{M(i_{req})} x_{m_{req},r_1} * val (p, m_{req}) \\label{eq:sw-req} \\circ \\sum_{r_2}^{R} \\sum_{m}^{reqModes(p,c)} x_{m,r_2}\n\\end{multline}\nHardware property requirement clauses:\n\\begin{equation}\n\t\\forall r \\in R, \\forall p \\in P(r): \\sum_{m}^{reqModes(p)} x_{m,r} * val(p,m) \\circ val(p,r) \\label{eq:hw-req}\n\\end{equation}\n\nThe constraint sense $\\circ$ in equations \\eqref{eq:sw-req} and \\eqref{eq:hw-req} are connected to the contract constraints and are read from there. Actually one constraint is created for each unique pair of property and constraint sense. However, putting that into a formula would unnecessarily complicate it.\n\n\\subsection{The objective function}\n\nLet $p_{goal} \\in P$ be the property to optimize for.\n\n\\begin{equation}\n\tobjective = \\sum_{r}^{R} \\sum_{m}^{reqModes(p_{goal})} x_{m,r} * val(p_{goal},m)\n\\end{equation}\n\n\\section{Metrics for the generated ILP}\n\nNumber of variables $n$:\n\\begin{equation}\nn = |R| * \\sum_{c}^{C} \\sum_{i}^{I(c)} 1 + |M(i)|\n\\end{equation}\n%\nNumber of constraints $m$ (at most one required component, some hardware- and $S$~software clauses per mode on average):\n\\begin{equation}\nm = |C| + %\nS * \\sum_{c}^{C} \\sum_{i}^{I(c)} 1 + |M(i)| + %\n\\sum_r^{R} * P(r)\n\\end{equation}\n\n\\subsection{Sample values}\n\nAssuming $S = 2$ and $\\overline{P(r)} = 2$.\n\n\\begin{table}[th]\n\t\\aboverulesep0.0mm\n\t\\belowrulesep0.5mm\n\t\\centering\n%\t\\scriptsize\n\t\\newcolumntype{R}{>{\\raggedleft\\arraybackslash}X}\n\t\\begin{tabularx}{.9\\linewidth}{ r R R R | R R }\n\t\t$|C|$ & $\\overline{|I|}$ & $\\overline{|M|}$ & $|R|$ & $n$ & $m$ \\\\\n\t\t\\midrule\n\t\t10           & 10           & 2           & 100           &  20000 &  810 \\\\\n\t\t\\textbf{100} & 10           & 2           & 100           & 200000 & 6300 \\\\\n\t\t10           & \\textbf{100} & 2           & 100           & 200000 & 6210 \\\\\n\t\t10           & 10           & \\textbf{20} & 100           & 200000 & 4410 \\\\\n\t\t10           & 10           & 2           & \\textbf{1000} & 200000 & 2610 \\\\[1mm]\n\t\\end{tabularx}\n\t\\caption{Number of variables $n$ and constraints $m$ for some example values}\n\t\\label{tab:saved-energy}\n\\end{table}\n\n\\end{document}\n", "meta": {"hexsha": "957d0b1750b01fe19894229ca130932216ec4939", "size": 6066, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/ilp-gen.tex", "max_stars_repo_name": "rene-schoene/racr-mquat", "max_stars_repo_head_hexsha": "5f985816cadd556d7636a74bea0a5d5b1d95f9ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/ilp-gen.tex", "max_issues_repo_name": "rene-schoene/racr-mquat", "max_issues_repo_head_hexsha": "5f985816cadd556d7636a74bea0a5d5b1d95f9ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/ilp-gen.tex", "max_forks_repo_name": "rene-schoene/racr-mquat", "max_forks_repo_head_hexsha": "5f985816cadd556d7636a74bea0a5d5b1d95f9ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.135483871, "max_line_length": 310, "alphanum_fraction": 0.6534784042, "num_tokens": 2091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3303246054816903}}
{"text": "\\section{Introduction}\n\\label{sec:intro}\n\nOne fundamental task in \\emph{Bayesian networks} (BNs) \\cite{pear88} is inference.\nGiven that some variables have been observed, the task is to compute posterior probabilities of other variables.\n\\cite{koll09} introduce readers to exact inference in discrete BNs with the \\emph{Variable Elimination} (VE) \\cite{zhan94} algorithm.\nThe VE algorithm uses its own terminology such as elimination orderings to modify the \\emph{conditional probability tables} (CPTs) of the BN to answer queries.\n\nAnother fundamental task in BNs is modeling, by which we mean testing which conditional independence relations hold in a given BN.\nMore specifically, we want to know whether two sets $X$ and $Z$ of variables are conditionally independent given a third set $Y$ of variables.\n\\cite{pearl86,pear88} introduced the \\emph{directed separation} (d-separation) algorithm for this task.\nd-Separation uses its own specialized terminology such as closed convergent valves in the \\emph{directed acyclic graph} (DAG) to determine whether or not an independent holds.\n\nIn this paper, we aim to establish computation that is common to both inference and modeling.\nWe organize the common computation as an algorithm, called \\emph{Simple Propagation} (SP).\nSP takes the factorization of the BN CPTs and two sets $X$ and $Y$ of variables in the BN.\nSP modifies the factorization by removing all variables relevant to $X$ and $Y$.\nThe output of SP can now be used for both inference and modeling.\nSurprisingly, one salient feature of SP is that it performs the bulk of the work leaving only a few steps to be executed for inference and for modeling.\nAnother advantage of SP is that it brings unified terminology.\nThereby, the work here provides a deeper understanding of BNs.\n\n\nThis paper is organized as follows.\nIn Section \\ref{sec:back}, background is given.\nUnifying inference and modeling is done in Section \\ref{sec:new}\nSection \\ref{sec:adv} draws advantages of the new method.\nConclusions are shown in Section \\ref{sec:conc}.", "meta": {"hexsha": "3e4f4b1e02ee0d4bf9a00b74c13b419aa0c45040", "size": 2047, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "B - The Platform/Paper/sections/introduction.tex", "max_stars_repo_name": "andreeds/cs807-research-tasks", "max_stars_repo_head_hexsha": "6e05e548cfc76302af36cdb81096822b19c84c99", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "B - The Platform/Paper/sections/introduction.tex", "max_issues_repo_name": "andreeds/cs807-research-tasks", "max_issues_repo_head_hexsha": "6e05e548cfc76302af36cdb81096822b19c84c99", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "B - The Platform/Paper/sections/introduction.tex", "max_forks_repo_name": "andreeds/cs807-research-tasks", "max_forks_repo_head_hexsha": "6e05e548cfc76302af36cdb81096822b19c84c99", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 73.1071428571, "max_line_length": 175, "alphanum_fraction": 0.7953102101, "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199008363969, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.3303246030202661}}
{"text": "As explained in previous sections, the Ginan repository consist on two main components. The \\textit{precise orbit deterination} (POD) component estimates precise satellite position and orbital parameters, while the \\textit{parameter estimation algorithm} (PEA) monitor systematic biases asociated with GNSS signals. The Ginan software follows uses the \\textit{precise point positioning}(PPP) philosophy for processing of GNSS signals. PPP was originally developed as a GNSS based positioning method for calculating location of autonomous receivers with high levels of accuracy and precision. PPP aims to calculate the end user position by rigorously modelling and/or estimating error sources in GNSS measurements. \nThe systematic of errors in GNSS signals can be summarised as: \n\\begin{itemize}\n\t\\item Satellite state estimation errors: position, clock offset, hardware biases, antenna effects\n\t\\item Receiver state estimation errors: position, clock offset, hardware biases, antenna effects\n\t\\item Atmospheric effects: ionospheric propagation delay, tropospheric propagation delay\n\t\\item Other (modellable) enviromental effects: Relativistic corrections, phase windup\n\\end{itemize}\n\nThe various components of the Ginan software package are designed to model or estimate these errors as parameters. A diagram illustrating of the way the Ginan components interact to estimate these parameters can be found in figure \\ref{fig:PEAnPOD}. In the example illustrated by the figure:\n\\begin{enumerate}\n\t\\item  The POD in orbit fitting mode is used to calculate an a-priori position and the linearization partials of orbit parameters  \n\t\\item  The PEA, in network mode, estimate orbital parameters from orbit partials\n\t\\item  The POD, use the orbital parameters to estimate and predict precise satellite positions\n\t\\item  The PEA, in network mode, is used to estimate wide-area parameters: satellite clock offsets, satellite hardware bias and atmospheric delays \n\t\\item  The PEA, in end-user mode, is used to callculate local parameters like receiver position, receiver clock offset and local atmospheric delays \n\\end{enumerate}\n\nOther parameters, such as antenna, phase windup and relativistic effects are calculated from predefined models.\n\nA description of each components and its use is presented below.\\\\\n\n\\chapter{Using the POD Module}\nGINAN applications use YAML format to define configuration files. After installing the dependencies and compiling building the POD application, the POD processing can be started by typing the command.\n\\begin{lstlisting}\n$ ./pod -y <path_to_config_file>\n\\end{lstlisting}\nDetails on the configuration parameters included in YAML files can be found in chapter \\ref{ch:pod_yaml_configuration}. Configuration files corresponding to the examples in this section can be found in the \\textit{ginan/examples} directory.\\\\\n\nThe POD module has two main modes of operation, the orbit fitting mode and the orbit integration/prediction mode. In orbit fitting mode, precise orbit parameters are calculated from, potentially inaccurate, satellite position pseudo-observations. In orbit integration mode, precise satellite positions are estimated/predicted from precise orbit parameters.\\\\\n\n\\section{Using the POD for orbit fitting}\nThe orbit fitting mode can be selected by setting the \\textit{ pod\\_mode\\_fit} to true and \\textit{ic\\_input\\_format : sp3} to true. In this mode, the POD will take satellite position pseudo-measurments from a SP3 formatted file and estimate the orbit state of each satellite contained in the SP3 file. The SP3 file containing a priory satellite position needs to be specified as the \\textit{pseudobs\\_orbit\\_filename} parameter.\nThe orbit state in POD is represented by a set of parameters consisting of \n\\begin{itemize}\n\t\\item Satellite position (in ITRF or TCRF) at the first epoch in the SP3 file\n\t\\item Satellite velocity (in ITRF or TCRF) at the first epoch in the SP3 file\n\t\\item Up to 9 parameters describing the Solar Radiation Pressure over the fitting time\n\\end{itemize}\nThese initial conditions, and the models described in chapter \\ref{ch:observation_modelling} will allow for the precise determination of satellite positions over the fitting arch (set by the \\textit{orbit\\_arc\\_determination} parameter).\\\\\n\nThe main outputs from this mode of operation are the a-posteriori satellite position in SP3 format, and the orbit partials of satellite positions with respect to the initial conditions. \nThe ouput SP3 file which can be found on \\textit{output\\_directory/gagWWWWD.sp3} where \\textit{WWWW} is the GPS week and /textit{D} is the GPS day of the first epoc on the SP3 files.\nThe orbit partials are written in Ginan's proprietary Initial Conditions File (ICF) format, and can be found in  \\textit{output\\_directory/gagWWWWD\\_orbit\\_partials.out}.\nConfiguration files, \\textit{ex21\\_pod\\_fit\\_gps} and \\textit{ex21\\_pod\\_fit\\_gnss},  for this mode of operation are included in Ginans \\textit{examples} folder.\\\\\n\n\\section{using the POD for orbit integration/prediction}\nThe orbit fitting mode can be selected by setting the \\textit{ pod\\_mode\\_ic\\_int} to true and \\textit{ic\\_input\\_format : icf} to true. \n In this mode, the POD will take the initial conditions contained in the ICF formatted files and propagaes the satellite positions forward over the time period specified by the sum of \\textit{orbit\\_arc\\_determination} and \\textit{orbit\\_arc\\_prediction} parameters. \n It also propagates the satellite position backwards by a number of hours specified by the \\textit{orbit\\_arc\\_backwards} parameter.\n The ICF file containing the satellites initial condition and radiation pressure parametes needs to be specified as the \\textit{ic\\_input\\_format : ic\\_filename} parameter.\\\\\n\nIt is to note that the orbit fitting mode will also use the orbit integration operation after estimating the initial conditions from pseudo-observations. \nAlthough the  mode \\textit{ pod\\_mode\\_fit} will only integrated for a number of hours specified  by \\textit{orbit\\_arc\\_determination}.\nSelecting the \\textit{pod\\_mode\\_predict} will propagate the initial conditions a number of hours specified by the sum of \\textit{orbit\\_arc\\_determination} and \\textit{orbit\\_arc\\_prediction}\nThe integrated/predicted satellite position will be output to a SP3 formatted file located in \\textit{output\\_directory/gagWWWWD.sp3}.\\\\\n\nThe configuration file to perform orbit integration/prediction from SP3 files is \\textit{ex23\\_pod\\_prd\\_gps}.  \nThe configuration file to perform orbit integration/prediction from ICF files is \\textit{ex24\\_pod\\_ic\\_gps}. Both located in Ginans \\textit{examples} folder.\\\\\n\n", "meta": {"hexsha": "452b0296d3ca9b60f9db6802d2eabea2e3015028", "size": 6648, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/manual/Using_the_POD_module.tex", "max_stars_repo_name": "RodrigoNaves/ginan-bitbucket-update-tests", "max_stars_repo_head_hexsha": "4bd5cc0a9dd0e94b1c2d8b35385e128404009b0c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 73, "max_stars_repo_stars_event_min_datetime": "2021-07-08T23:35:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:17:58.000Z", "max_issues_repo_path": "docs/manual/Using_the_POD_module.tex", "max_issues_repo_name": "RodrigoNaves/ginan-bitbucket-update-tests", "max_issues_repo_head_hexsha": "4bd5cc0a9dd0e94b1c2d8b35385e128404009b0c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-09-27T14:27:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T23:50:02.000Z", "max_forks_repo_path": "docs/manual/Using_the_POD_module.tex", "max_forks_repo_name": "RodrigoNaves/ginan-bitbucket-update-tests", "max_forks_repo_head_hexsha": "4bd5cc0a9dd0e94b1c2d8b35385e128404009b0c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 39, "max_forks_repo_forks_event_min_datetime": "2021-07-12T05:42:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:15:34.000Z", "avg_line_length": 108.9836065574, "max_line_length": 714, "alphanum_fraction": 0.8094163658, "num_tokens": 1507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635841117624, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3303245984062125}}
{"text": "\\documentclass[12pt, letterpaper]{article}\n\\include{eu}\n\\pagestyle{plain}\n\\begin{document}\n\\section*{\\textsl{Einstein's Universe} Final Exam}\n\\setcounter{problem}{1}\n\n\\begin{problem}\n  (From Problem Set 1)\n  What, approximately, is the cargo volume of an armored truck?\n\\end{problem}\n\n\\begin{problem}\n  (From Problem Set 1)\n  What is the mass of one mole of water?\n\\end{problem}\n\n\\begin{problem}\n  (From Term Exam 1)\n  Classical mechanics, or Newtonian mechanics, is only valid in certain\ncircumstances. When do the laws of classical mechanics, like $\\vec{F} =\nm\\,\\vec{a}$ for example, become wrong or break down? There are many answers\nto this problem; I will take anything correct.\n\\end{problem}\n\n\\begin{problem}\n  (From Term Exam 1)\n  Which of the following physical quantities are vectors?\n\\\\\n\\textsl{(a)}~energy,\n\\textsl{(b)}~mass,\n\\textsl{(c)}~force,\n\\textsl{(d)}~momentum,\n\\textsl{(e)}~acceleration.\n\\end{problem}\n\n\\begin{problem}\n  (From Problem Set 2)\n  What is the mass $M$ you found for a piano string?\n\\end{problem}\n\n\\begin{problem}\n  (From Problem Set 2)\n  What, approximately, is the volume of an ice molecule?\n\\end{problem}\n\n\\begin{problem}\n  (From Term Exam 2)\n  This wave on a string is moving to the left. The string is moving only\nup and down. State, for each of the three points A, B, and C, which way those\nbits of string are moving.\\\\\n\\includegraphics{wavepulse.png}\n\\end{problem}\n\n\\begin{problem}\n  (From Term Exam 2)\n  A $50\\,\\g$ mass will have roughly what weight? Give your answer in force units.\n\\end{problem}\n\n\\begin{problem}\n  (From Problem Set 3)\n  What is the Lorentz factor $\\gamma$ for something moving relative\n  to you at speed $v = 0.99\\,c$?\n\\end{problem}\n\n\\begin{problem}\n  (From Problem Set 3)\n  What is the distance from us to the Galactic Center?\n\\end{problem}\n\n\\begin{problem}\n  (From Term Exam 3)\n  Give the lengths of the three sides of the triangle that you drew for the\n  moving-light-clock problem (Problem Set 3, problem 3).\n\\end{problem}\n\n\\begin{problem}\n  (From Term Exam 3)\n  Muons live for a couple of milliseconds. Naively, therefore, they can't travel more than few hundred meters,\neven traveling near the speed of light. And yet, they often are observed to travel many kilometers.\nHow is this possible?\n\\end{problem}\n\n\\begin{problem}\n  (From Problem Set 4)\n  Which produces more energy per unit mass?\n  Burning fossil fuels,\n  nuclear fission with uranium fuel, or\n  nuclear fusion with hydrogen fuel?\n\\end{problem}\n\n\\begin{problem}\n  (From Problem Set 4)\n  An elevator in New York City is accelerating downwards\n  at acceleration $g$ (the gravitational acceleration).\n  What is the magnitude of the normal force on a box of mass $M$ inside this elevator?\n\\end{problem}\n\n\\begin{problem}\n  (From Term Exam 4)\n  In normal space, the straight line (or geodesic) is the path of \\emph{shortest\ntotal distance} between two points. In spacetime, the geodesic is the path\nof what?\n\\end{problem}\n\n\\begin{problem}\n  (From Term Exam 4)\n  If you are in a rocket that is moving in the $x$-direction with\nrespect to the Earth at $0.75\\,c$ and, inside the rocket, you are\nmoving at $0.75\\,c$ in the $x$ direction with respect to the rocket,\nhow fast are you moving with respect to the Earth? No need to\ncalculate. All I want to know is: Are you moving closer to $0.75\\,c$,\n$0.95\\,c$, or $1.5\\,c$?\n\\end{problem}\n\n\\begin{problem}\n  (From Problem Set 5)\n  What, roughly, is the insolation on the surface of Pluto?\n\\end{problem}\n\n\\begin{problem}\n  (From Problem Set 5)\n  What is the recession speed (relative to us) of a galaxy that has a Doppler\n  factor of 10?\n\\end{problem}\n\n\\begin{problem}\n  (From Term Exam 5)\n  If a galaxy is moving away at 5 percent of the speed of light, the K\nline (which is at a rest-frame or natural wavelength of around $\\lambda =\n3900$\\,\\AA), will be shifted to the red. What, roughly, will be the change\n$\\Delta\\lambda$ in the wavelength of the line?\n\\end{problem}\n\n\\begin{problem}\n  (From Term Exam 5)\n  What was the policy introduced at the University in Berlin in 1933 that caused Einstein's job to be terminated?\n\\end{problem}\n\n\\begin{problem}\n  (From Problem Set 6)\n  What is the mass of the black hole at the center of the Milky Way?\n\\end{problem}\n\n\\begin{problem}\n  (From Problem Set 6)\n  How much energy was radiated away in gravitational radiation in event GW150914?\n  You can give your answer in energy units, or mass units (since, after all, there\n  is mass--energy equivalence).\n\\end{problem}\n\n\\begin{problem}\n  State one thing that you learned in this class\n  that you expect to remember for many years.\n\\end{problem}\n\n\\begin{problem}\n  Einstein brought two changes to physics: relativity (special and general) and\n  quantization of energy and mass. Which do you think is more important, and why?\n\\end{problem}\n\n\\end{document}\n", "meta": {"hexsha": "3c5f04795a095b2db4b987e0ed932f55c3aabb3e", "size": 4806, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/final.tex", "max_stars_repo_name": "davidwhogg/EinsteinsUniverse", "max_stars_repo_head_hexsha": "91babed322a5985a45ec827c030564cacbd49354", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tex/final.tex", "max_issues_repo_name": "davidwhogg/EinsteinsUniverse", "max_issues_repo_head_hexsha": "91babed322a5985a45ec827c030564cacbd49354", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-08-24T19:50:27.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-30T01:39:39.000Z", "max_forks_repo_path": "tex/final.tex", "max_forks_repo_name": "davidwhogg/EinsteinsUniverse", "max_forks_repo_head_hexsha": "91babed322a5985a45ec827c030564cacbd49354", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4846625767, "max_line_length": 113, "alphanum_fraction": 0.7322097378, "num_tokens": 1349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.3303245984062125}}
{"text": "\\chapter{dataReset}\n\n\\section{Introduction}\n\nA linearized process may have parameters that are initialized, changed and used, and subsequently ignored until they are used again.\nIn the interval from the last change or use of a parameter to its subsequent reuse, a parameter could have different values.\nThese values contribute to the size of the state space of the process \\emph{without} adding any new behavior!\n\nIt may be advantageous to detect from which moment the value of a parameter is no longer used and set it to a default value instead.\nThis is called `resetting'.\nAnalysis of an LPE can yield information on when parameters can be safely reset.\n\n\\section{Algorithm}\n\nThe algorithm is based on earlier work \\cite{van2009state}.\n\nAs a preparative step, several determinations are made about each parameter $p$ of the LPE per summand $s$:\n\\begin{itemize}\n\n\\item Is the value of $p$ potentially altered by $s$?\nIf so, $p$ is marked as `changed'.\n\n\\item Does $p$ occur in the guard of $s$?\nIf so, $p$ is marked as `directly used'.\n\n\\item Is $p$ marked as `directly used' in $s$?\nOr does $p$ occur in the assignment by $s$ to a parameter that is marked as `changed'?\nIn either case, $p$ is marked as `used'.\n\n\\item Must the value of $p$ have a specific (unique) value $v$ in order for $s$ to be enabled?\nIf so, $p$ is marked as `having a source' for $s$, with the source being $v$.\n\n\\item Does the value of $p$ have a specific (unique) value $v$ immediately after $s$ has been applied?\nIf so, $p$ is marked as `having a destination' for $s$, with the source being $v$.\n\n\\item Does $p$ have both a source and a destination for $s$?\nThen $p$ is called a \\emph{ruling parameter}.\n\n\\end{itemize}\n\n\\subsection{Control flow graphs}\n\nA parameter of the LPE is a \\emph{control flow parameter} of the LPE if for all summands it is either a ruling parameter or not marked as `changed' (or both).\nA parameter that is not a control flow parameter is defined as a \\emph{data parameter}.\n\n\\vspace{1mm}\n\nFor each control flow parameter $f$ of the LPE, a control flow graph is constructed.\nThere is a state in the control flow graph for each source and destination of $f$ (across all summands).\nTwo states $s_1$ and $s_2$ are connected by an edge $(s_1, i, s_2)$ if there is a summand $i$ where the source of $f$ is represented by one of the states and where the destination of $f$ is represented by the other state.\nThe direction of such an edge is from source state to destination state.\n\n\\subsection{Belongs-to function}\n\nNext, we define the \\emph{belongs-to} function.\nThe belongs-to function maps each data parameter $d$ to some set of control flow parameters $b(d)$ as follows\n\n\\begin{align*}\nb(d) = F \\cap \\bigcap\\limits_{s \\in S}^{} \\text{ruling}(s)\n\\end{align*}\n\nwhere\n\n\\begin{itemize}\n\\item $F$ is the set of all control flow parameters;\n\\item $S$ is the set of all summands in which $d$ is marked as `changed' or `used';\n\\item $\\text{ruling}(s)$ is the set of all parameters that rule summand $s$.\n\\end{itemize}\n\n\\clearpage\n\\subsection{Relevance relation}\n\nThe relevance relation $R$ bundles the information that has been gathered so far.\nThe relation $R$ relates a data parameter $d$, a control flow parameter $f$, and a value $v$ if $d$ may be used after a state in which $f$ has value $v$.\nThis is denoted $R(d, f, v)$.\nIntuitively, this is a situation in which $d$ should \\emph{not} be reset.\n\nThe computation of $R$ is a fixpoint algorithm: modifications are applied iteratively until $R$ no longer changes.\nThe initial value of $R$ is set to\n\n\\begin{align*}\nR_0 = \\bigcup\\limits_{\\substack{i \\in S \\\\ d_k \\in \\text{directlyUsed}(i)}}^{} \\;\\{\\; (d_k, d_j, \\text{source}(i, d_j)) \\;|\\; d_j \\in b(d_k) \\;\\}\n\\end{align*}\n\nwhere\n\n\\begin{itemize}\n\\item $S$ is the set of all summands;\n\\item $\\text{directlyUsed}(i)$ is a function that gives the set of all parameters marked as `directly used' in a summand $i$;\n\\item $\\text{source}(i, f)$ is a function that gives the source value of a control flow parameter $f$ for a summand $i$.\n\\end{itemize}\n\nEach iteration can be split into two steps.\nThe first step checks for control flow graphs in which a data parameter $d$ has already been marked as `relevant' whether this implies that $d$ is also relevant in preceding states (of the same control flow graph).\nIf so, the appropriate triples are added to $R$:\n\n\\begin{align*}\nR_{n}{'} = R_{n-1} \\cup \\bigcup\\limits_{\\substack{i \\in S}}^{} \\;\\left\\{\\; (d_k, d_j, s) \\;\\middle|\\; \\substack{(d_l, d_j, t) \\in R_{n-1} \\\\ d_j \\in b(d_k) \\\\ d_k \\in \\text{vars}(v_i(d_l)) \\\\ (s, i, t) \\in E_{d_j}} \\;\\right\\}\n\\end{align*}\n\nwhere\n\n\\begin{itemize}\n\\item $E_{f}$ is the set of edges that are part of the control flow graph of control flow parameter $f$.\n\\end{itemize}\n\nThe second step is similar, but data parameters that are found to be relevant are added as triples to $R$ in relation to \\emph{another} control flow parameter:\n\n\\begin{align*}\nR_{n} = R_{n}{'} \\cup \\bigcup\\limits_{\\substack{i \\in S}}^{} \\;\\left\\{\\; (d_k, d_j, \\text{source}(i, d_j)) \\;\\middle|\\; \\substack{(d_l, d_p, t) \\in R_{n}{'} \\\\ d_j \\in b(d_k),\\; d_j \\notin b(d_l) \\\\ d_k \\in \\text{vars}(v_i(d_l)) \\\\ (r, i, t) \\in E_{d_p}} \\;\\right\\}\n\\end{align*}\n\n\\clearpage\n\\subsection{Summand modification}\n\nFinally, each summand of an LPE can be modified by making use of the belongs-to function $b$ and the relevance relation $R$.\nIntuitively, we check whether the value of a parameter is `relevant' after a specific summand $i$ has been applied.\nIf so, the parameter should not be reset.\nOtherwise, the parameter can be reset, for example to its initialization value:\n\n\\begin{align*}\nv_{i}{'}(d_k) = \\begin{cases}\nv_{i}(d_k) & \\text{if } \\bigwedge\\limits_{\\substack{d_j \\in \\text{ruling}(i) \\\\ d_j \\in b(d_k)}}^{} R(d_k, d_j, \\text{dest}(i, d_j)) \\\\\nv_{0}(d_k) & \\text{otherwise}\n\\end{cases}\n\\end{align*}\n\nwhere\n\n\\begin{itemize}\n\\item $\\text{ruling}(s)$ is the set of all parameters that rule summand $s$;\n\\item $\\text{source}(i, f)$ is a function that gives the destination value of a control flow parameter $f$ for a summand $i$.\n\\end{itemize}\n\n", "meta": {"hexsha": "f82dbf8d3ce039260f7ed6814e0343d1b944d8f0", "size": 6098, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "_tex/lpeopsDoc/dataReset.tex", "max_stars_repo_name": "Sercammus/TxsLpeOps", "max_stars_repo_head_hexsha": "3354f2762cf195e571f4c05040ec500165969359", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_tex/lpeopsDoc/dataReset.tex", "max_issues_repo_name": "Sercammus/TxsLpeOps", "max_issues_repo_head_hexsha": "3354f2762cf195e571f4c05040ec500165969359", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_tex/lpeopsDoc/dataReset.tex", "max_forks_repo_name": "Sercammus/TxsLpeOps", "max_forks_repo_head_hexsha": "3354f2762cf195e571f4c05040ec500165969359", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.1703703704, "max_line_length": 265, "alphanum_fraction": 0.7128566743, "num_tokens": 1835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318479832805, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3301925824910315}}
{"text": "\\section{Background and Preliminaries}\n\\label{sec:bg}\n\nThis section introduces our running example, necessary background of ML system internals, as well as common types of redundancy.\n\n\\subsection{Running Example}\n\nExample~\\ref{ex:1} shows a user-level example ML pipeline---written in SystemDS' DML scripting language with R-like syntax \\cite{BoehmADGIKLPR20}---which we use as a running example throughout this paper.\n\n\\begin{example} [GridSearch LM] \\label{ex:1} We read a feature matrix \\mat{X} and labels \\mat{y}, and extract 10 random subsets of 15 features. For each feature set, we tune the linear regression (lm) hyper-parameters regularization, intercept, and tolerance via grid search and print the loss.\n\\begin{lstlisting}\n 1: X = read('data/X.csv'); # 1M x 100\n 2: y = read('data/y.csv'); # 1M x 1\n 3: for( i in 1:10) {\n 4:   s = sample(15, ncol(X));\n 5:   [loss, B] = gridSearch('lm', 'l2norm',\n        list(X[,s],y), list('reg','icpt','tol'),...);\n 6:   print(\"Feature set [\"+toString(s)+\"]: \"+loss);\n 7: }\n\\end{lstlisting}\nHigh-level primitives like \\texttt{gridSearch} and \\texttt{lm} are themselves script-based built-in functions and imported accordingly. Below functions show their key characteristics in simplified form:\n\\begin{lstlisting}\n01: gridSearch = function(...) return(...) {\n02:   HP = ... # materialize hyper-parameter tuples\n03:   parfor( i in 1:nrow(HP) ) { # parallel for\n04:     largs = ... # setup list hyper-parameters\n05:     rB[i,] = t(eval(train, largs));\n06:     rL[i,] = eval(score, list(X,y,t(rB[i,])));\n07: } }\n08: lm = function(...) return(...) { \n09:   if (ncol(X) <= 1024)  # select closed-form\n10:     B = lmDS(X, y, icpt, reg, verbose);\n11:   else                  # select iterative\n12:     B = lmCG(X, y, icpt, reg, tol, maxi, verbose);\n13: } \n14: lmDS = function(...) return(...) {\n15:   if (icpt > 0) {\n16:     X = cbind(X, matrix(1,nrow(X),1));\n17:     if (icpt == 2)\n18:       X = scaleAndShift(X); # mu=0,sd=1\n19:   } ...\n20:   A = t(X) %*% X + diag(matrix(reg,ncol(X),1);\n21:   b = t(X) %*% y;\n22:   beta = solve(A, b);\n23: } \n24: lmCG = function(...) return(...) {\n25:   if (icpt > 0) {\n26:     X = cbind(X, matrix(1,nrow(X),1));\n27:     if (icpt == 2)\n28:       X = scaleAndShift(X); # mu=0,sd=1\n29:   } ...\n30:   while (i<maxi & norm_r2>norm_r2_tgt) {\n31:     q = t(X) %*% (X %*% ssX_p); ...\n32:     p = -r + (norm_r2 / old_norm_r2) * p;\n33: } }\n\\end{lstlisting}\nThe \\texttt{gridSearch} function enumerates and materializes all hyper-parameter combinations $\\mat{HP}$ of the passed parameters and value ranges, and invokes training (\\texttt{lm}) and scoring (\\texttt{l2norm}) functions to find the best model and loss. The \\texttt{lm} function in turn dispatches---based on the number of features---either to a closed-form method with $\\mathcal{O}(m\\cdot n^2 + n^3)$ complexity (\\texttt{lmDS}); or an iterative conjugate-gradient method with $\\mathcal{O}(m \\cdot n)$ per iteration (\\texttt{lmCG}), which performs better for many features as it requires $\\leq n$ iterations until convergence.\n\\vspace{-0.1cm}\n\\end{example}\n\n\\subsection{ML Systems Background}\n\\label{sec:mlsys}\n\nThere is a variety of existing ML systems. Relevant for understanding this paper, are especially the underlying techniques for program and DAG compilation, and operator scheduling~\\cite{2019Boehm}. Here, we focus primarily on lazy evaluation and program compilation.\n\n\\textbf{Program/DAG Compilation:} We distinguish three types of compilation in contemporary ML systems: (1) interpretation or eager execution, (2) lazy expression or DAG compilation, and (3) program compilation. First, interpretation as used in R, PyTorch \\cite{PaszkeGMLBCKLGA19}, or Python libraries like NumPy \\cite{WaltCV11} or Scikit-learn \\cite{PedregosaVGMTGBPWDVPCBPD11} execute operations as-is and the host language (e.g., Python) handles the scoping of variables. Second, systems like TensorFlow \\cite{AbadiBCCDDDGIIK16}, OptiML \\cite{SujeethLBRCWAOO11}, and Mahout Samsara \\cite{MahoutSamsara} performing lazy expression evaluation that lazily collects a DAG of operations, which is optimized and executed on demand. Some of these systems---like TensorFlow or OptiML---additionally provide control flow primitives, integrated in the data flow graph. Here, the host language still interprets the control flow, and thus, unrolls operations into a larger DAG. However, recent work like AutoGraph \\cite{abs-1810-08061} automatically compiles TensorFlow control flow primitives. Only bound output variables leave the scope of expression evaluation. Third, program compilation in systems like Julia \\cite{BezansonEKS17}, SystemML \\cite{BoehmDEEMPRRSST16}, SystemDS~\\cite{BoehmADGIKLPR20}, and Cumulon \\cite{HuangB013} compiles a script into a hierarchy of program blocks, where every last-level block contains DAGs of operations. Accordingly, control flow and variable scoping is handled by the ML system itself. Despite the large optimization scope of lazy expression evaluation and program compilation, unnecessary redundancy cannot be fully eliminated via code motion and common subexpression elimination (CSE) because the conditional control flow is often unknown.\n\n\\begin{figure}[!t]\n\t\\centering\n\t\\includegraphics[scale=0.32]{figures/background}\n\t\\vspace{-0.25cm}\n\t\\caption{\\label{fig:background}Operator Scheduling and Runtime Plans.}\n\\end{figure}\n\n\\textbf{Operator Scheduling:} Given a DAG of operations of an expression or program block, operator scheduling then determines an execution order of the individual operations, subject to the explicit data dependencies (i.e., edges) of the data flow graph. The two predominant approaches are sequential and parallel instruction streams. First, a sequential instruction stream linearizes the DAG---in depth- or breadth-first order---into a sequence of instructions that is executed one-at-a-time. For example, Figure~\\ref{fig:background} shows a plan of runtime instructions in SystemDS for lines 21-23 of Example 1. A symbol table holds references to live variables and their metadata. Instructions are executed sequentially, read their inputs from a variable map (a.k.a. symbol table), and put their outputs back. Such a serial execution model---as used in PyTorch \\cite{PaszkeGMLBCKLGA19} and SystemML \\cite{BoehmDEEMPRRSST16,BoehmBERRSTT14}---is simple and allows bounding the memory requirements. Second, parallel instruction streams---as used in TensorFlow \\cite{AbadiBCCDDDGIIK16}---leverage inter-operator parallelism: when all inputs of an operation are available, this operation is enqueued for parallel execution. This  execution model offers a high degree of parallelism (for many small operations) but makes memory requirements less predictable. \n\n\\subsection{Sources of Redundancy} \n\\label{sec:redundancy}\n\nWe can now return to our running example and discuss common sources of fine-grained redundancy.\n\n\\begin{example} [GridSearch LM Redundancy] \nThe user script from Example~\\ref{ex:1} with a $1\\text{M} \\times 100$ feature matrix $\\mat{X}$ and three hyper-parameters (\\texttt{reg}, \\texttt{icpt}, \\texttt{tol} with 6, 3, and 5 values) exhibits multiple sources of redundancy. \n%\nFirst, since $\\mat{X}$ has 100 features, all calls to \\texttt{lm} are dispatched to \\texttt{lmDS} and thus, one of the hyper-parameters (\\texttt{tol}) is irrelevant and we train five times more models than necessary. \n%\nSecond, evaluating different $\\lambda$ parameters (\\texttt{reg}) for \\texttt{lmDS} exhibits fine-grained operational redundancy. The core operations $\\mat{X}^{\\top}\\mat{X}$ and $\\mat{X}^{\\top}\\mat{y}$ are independent of \\texttt{reg} and thus, should be executed only once for different $\\lambda$. \n%\nThird, both \\texttt{lmDS} and \\texttt{lmCG} have the same pre-processing block, and for 2/3 of \\texttt{icpt} values, we perform the same \\texttt{cbind} operation, which is expensive because it creates an intermediate larger than $\\mat{X}$.\n%\nFourth, appending a column of ones does not require re-executing $\\mat{X}^{\\top}\\mat{X}$ and $\\mat{X}^{\\top}\\mat{y}$. Instead we can reuse these intermediates and augment them with $\\text{colSums}(\\mat{X})$, $\\text{sum}(\\mat{y})$ and $\\text{nrow}(\\mat{X})$. Similarly, the random feature sets will exhibit overlapping features whose results can be reused.\n%\n%Overall, eliminating all redundancy allows us to reduce the number of floating point operations from XXX to XXX.\n\\end{example} \n\n\\textbf{Types of Redundancy:} Existing work performs reuse for coarse-grained sub-tasks in ML pipelines \\cite{SparksVKFR17, ZhangKR14, VartakTMZ18, XinMMLSP18, ShangZBKECBUK19, DerakhshanMARM20}. Generalizing upon the previous example, we further extend this to common types of \\emph{fine-grained} redundancy:\n\\begin{itemize}\n\\item \\emph{Full Function or Block Redundancy:} At all levels of the program hierarchy, there is potential for full reuse of the outputs of program blocks. This reuse is a form of function memoization \\cite{CrankshawWZFGS17}, which requires deterministic operations. %on the taken control path\n\\item \\emph{Full Operation Redundancy:} Last-level operations can be reused for equivalent inputs, given that all non-determinism (e.g., a system-generated seed) is exposed from these operations and cast to a basic input as well.\n\\item \\emph{Partial Operation Redundancy:} Operation inputs with overlapping rows or columns further allow reuse by extraction from---or augmentation of---previously computed results.\n\\end{itemize}\nTogether, these different types of redundancy motivate a design with (1) fine-grained lineage tracing, (2) multi-level, lineage-based reuse, and (3) exploitation of both full and partial reuse.\n\n\\textbf{Applicability in ML Systems:} Fine-grained lineage tracing and reuse is applicable in ML systems with eager execution, lazy  evaluation, and program compilation. In contrast, multi-level tracing, deduplication, and reuse require access to control structures and thus, are limited to systems with program compilation scope.\n", "meta": {"hexsha": "ef383e5d92dbee4c782ad3ff59ffc818af6655b1", "size": 9985, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "sigmod2021-LIMA-p32/paper/Background.tex", "max_stars_repo_name": "damslab/reproducibility", "max_stars_repo_head_hexsha": "f7804b2513859f7e6f14fa7842d81003d0758bf8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-12-10T17:20:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T14:38:40.000Z", "max_issues_repo_path": "sigmod2021-LIMA-p32/paper/Background.tex", "max_issues_repo_name": "damslab/reproducibility", "max_issues_repo_head_hexsha": "f7804b2513859f7e6f14fa7842d81003d0758bf8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sigmod2021-LIMA-p32/paper/Background.tex", "max_forks_repo_name": "damslab/reproducibility", "max_forks_repo_head_hexsha": "f7804b2513859f7e6f14fa7842d81003d0758bf8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 95.0952380952, "max_line_length": 1774, "alphanum_fraction": 0.750225338, "num_tokens": 2668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3301925746960095}}
{"text": "% This is LLNCS.DOC the documentation file of\n% the LaTeX2e class from Springer-Verlag\n% for Lbecture Notes in Computer Science, version 2.4\n\\documentclass{article} % For LaTeX2e\n\\usepackage{nips15submit_e,times}\n\\usepackage{hyperref}\n\\usepackage{url}\n\\usepackage[dvips]{graphicx}\n\\usepackage{xcolor}\n%\\usepackage{url}\n\\usepackage{colortbl}\n\\usepackage{multirow}\n\\usepackage{stmaryrd}\n\n%\\usepackage{amssymb}\n%\\newtheorem{definition}{Definition} % [section]\n%\\newtheorem{example}{Example} % [section]\n\\newcommand{\\pivot}[1]{\\mathbin{\\, {#1} \\,}}\n\\newcommand{\\Pivot}[1]{\\mathbin{\\; {#1} \\;}}\n\\newcommand{\\Var}[0]{\\mbox{\\texttt{Var}}}\n\\newcommand{\\tuple}[1]{\\(\\langle #1\\rangle\\)}\n\\def\\withmath#1{\\relax\\ifmmode#1\\else{$ #1 $}\\fi}\n\\def\\defeq{\\withmath{\\stackrel{d}{=}}}\n\\let\\from=\\leftarrow\n\n\\newcommand{\\keywords}[1]{\\par\\addvspace\\baselineskip\n\\noindent\\keywordname\\enspace\\ignorespaces#1}\n\\input{commands.tex}\n\n\\begin{document}\n%\\bibliographystyle{acmtrans}\n\n\\long\\def\\comment#1{}\n\\def\\mtimes{}\n\\def\\LL#1{\\llbracket #1 \\rrbracket}\n\\title{Notes on differentiable logic \\\\\n{\\small Logic through vector calculus} \\\\\n{\\small *** DRAFT v0.06 ***}}\n\n\\author{Vijay Saraswat \\\\\nIBM T.J. Watson Research Center\\\\\n1101 Kitchawan Road\\\\\nYorktown Heights, NY 10598 \\\\\n\\texttt{vijay@saraswat.org} \\\\\n\\And\nRadha Jagadeesan \\\\\nDe Paul University \\\\\n243 S. Wabash Avenue \\\\\nChicago, IL 60604 \\\\\n\\texttt{rjagadeesan@cs.depaul.edu}\n}\n\n\\newcommand{\\fix}{\\marginpar{FIX}}\n\\newcommand{\\new}{\\marginpar{NEW}}\n\n\\nipsfinalcopy % Uncomment for camera-ready version\n\n\\maketitle\n\n\\begin{abstract}\nFirst-order logic has crisp notions of individuation and predication: individuals are taken  to be fully formed objects from some underlying set $U$ which typically has no internal structure, and $k$-ary predicates are taken to be $k$-ary maps from $U$ to $B=\\{0,1\\}$ that specify whether a particular tuple is in the relation or not. \n\nRecent years have seen some remarkable successes in the application of machine learning techniques to a variety of applications in speech, vision and natural language understanding. Typically, these successes are based on the use of continuous (non-convex) optimization techniques (such as gradient descent). The need to account for logical structure has led to the development of several {\\em ad hoc} techniques based on embedding individuals into $n$-dimensional vectors (``distributional representations'', \\cite{unified-arch-nlp,mikolov-word-vec,baroni2014don}), and treating predicates as tensors \\cite{coecke-2010,grefenstette-2013,socher-ntn-2013,bishan-iclr15,rocktaschel-2015,order-embedding-kiros,TransIE}, without a proper understanding of how these techniques relate to logic. \n\n%% TODO: 1-Lipschitz vs continuous.\nIn these notes we give an account of a precise embedding of first-order logic (over finitary structures) into vector spaces over $\\Re$, via the ``Fourier expansion'' of Boolean functions as multilinear polynomials. This immediately permits a continuous embedding of predicates into $[0,1]^n \\rightarrow [0,1]$ that enables techniques such as gradient descent to be used directly on such formulas.\n\n%\\keywords{machine learning, concurrent constraint programming}\n\\end{abstract}\n\n\\def\\Or{\\vee}\n\\def\\And{\\wedge}\n\\def\\Arrow{\\rightarrow}\n\\def\\Xor{\\;\\mbox{xor}\\;}\n\\def\\Ind{\\;\\mbox{Ind}}\n\n\\section{Introduction}\nThe {\\em supervised machine learning} approach is applicable in settings where the programmer is concerned with specifying a function that must work accurately even in the presence of significant amounts of noise in the input. For instance, suppose the programmer must write code that labels an arbitrary input image with a tag (``dog with hat'') that best characterizes the image. The space of variations in the input is generally so vast and potentially so ill-understood mathematically that it may simply not be possible for the user to programmatically specify all the logic for the function.\n\nInstead we desire an approach whereby (portions of the) logic may be {\\em learnt} by automatic techniques, given a (potentially very) large collection of observations (input/output pairs) of the given function. \n\nConcretely, we may describe the problem as follows. Instead of providing a fully realized, executable function $f$, the programmer specifies a space $\\cal F$ of possible functions, obtained by varying the parameters $\\theta$ of some parametric function $f_{\\theta}$.  Also available is the set of {\\em observations} $(\\bar{x}_i, \\bar{y}_i)$ (for $i\\in I$) specifying pairs of input values with their associated output values, and a {\\em loss function} $L$ which can take two values $\\bar{y},\\bar{y}'$ and return a real value  $L(\\bar{y},\\bar{y}')$ which measures how far one value is from the other. The machine learning problem is now to determine a specific value $\\hat{\\theta}$ for the parameters which minimizes $$\\Sigma_{i \\in I} L(f_\\theta(\\bar{x}_i), \\bar{y}_i)$$\n\nMany algorithmic techniques are available, under various conditions, to address this problem. For instance, in situations where $f_{\\theta}$ represents a differentiable function of its parameters $\\theta$, one may use stochastic gradient descent to find a minima. Under other conditions, the Expectation Maximization algorithm may be used.\n\nA very powerful instance of this general picture is obtained with (feed forward) {\\em deep neural networks} (see, e.g., \\cite{deep-learning-nature-2015}).  In this setting, the parametric function $f_{\\theta}$ is given by $k$ layers of compute elements (called ``neurons''), an element in layer $i$ connected to some (possibly all) elements in the preceding layer. Each neuron is associated with a set of weights $W$ (its parameters) used to linearly sum its inputs. (There is also usually a bias value.) Some non-linear (but piece-wise differentiable) thresholding function (e.g. sigmoid, $\\lambda t.\\,(1/(1+e^{-t}))$) is used to determine the output of this element. One can think of the entire network as specified by a $k$-nested functional term, involving summations and pointwise applications of the thresholding function. It has been shown that any arbitrary non-linear (real-valued) function can be approximated arbitrarily closely with sufficiently many parameters, and sufficient training input. \n\nWhat has made the machine learning problem of great interest in recent years is the availability of large amounts of labeled training data, and vast amounts of (CPU, GPU) computation that can be brought to bear to train the given function. A better understanding of how training algorithms such as asynchronous stochastic gradient networks  \\cite{distbelief} can be made to work for deep networks has brought about a startling increase in accuracy in many applications, and a significant increase in the range of applications amenable to these techniques.\n\n\\subsection{Differentiable programming languages}\nA significant drawback of deep neural networks is their {\\em   opacity}. In general, it is not possible to give a meaningful answer to the question of {\\em why} the learnt program does what it does. At hand is simply the value of the (potentially billions of) parameters, poor material from which to construct causally coherent explanations accessible to a human observer.\n\n\nWe are interested in developing the foundations of a powerful framework for machine learning and reasoning which gives the programmer flexibility in expressing significant amount of prior knowledge in the struture of the space $\\cal F$. We wish to use the full power of a general-purpose programming framework, allied with machine learning. Conceptually, the programmer may write programs in a high-level language while leaving ``holes'' (also called {\\em   sketches}, \\cite{solar-lezama:asplos06}) to be filled in by an appropriate automated assistant, such as a supervised machine learning algorithm, or a constraint solver. For instance, a program may leave the definition of a procedure {\\em q?} unspecified, merely leaving in place an invocation of the procedure on particular arguments (e.g.{} {\\em q?(X,3,true)}). The task of the solver is to determine the definition of the procedure so that the overall program exhibits the desired observations (approximately).   \n\nWhile considerable progress has been made in the last decade on the use of constraint solvers for sketching (see, e.g., \\cite{armando}), the use of machine learning for sketching is an unexplored area. In particular, it calls for developing a ``differentiable'' programming language in which programs are embedded in a continuous space, may have user-specified parameters, and are end-to-end differentiable with respect to these parameters.  \n\nOf particular interest to us are programming languages based on logic -- such as definite clause logic programming \\cite{Kowalski76} and concurrent constraint programming \\cite{CCP}, including probabilistic versions thereof \\cite{muggleton:srl07,Gupta97b,cussens}. Such frameworks carry dual advantages -- they permit the direct expression of knowledge about the real world (via first-order formalizations), and they offer the full power of programming languages for algorithmic tasks. \n\nThe focus of this note is to establish the foundations for a continuous embedding of logic. Future version of this note / subsequent papers will develop machine learning applications and implementations. \n\n\\subsection{Related work}\n\n%% Also describe recent general end-to-end differentiable approaches. Neural Turing Machines.\n\n%% Work on open IE and matrix completion as a way of learning new predicates.\n\n%% Work by Bishan Yang, and Rajarshi Das and others on doing inference in knowledge graph through neural network techniques.\n\n%% Work on Neural Theorem Proving\n\n%% Work by Grefenstette and Cock on using tensors for first order formulas.\n\\section{Basic Idea}\nWe develop a continuous embedding for first-order logic, building on the ideas of \\cite{boolean-function}. Let us quickly sketch the construction.\n\nLet $B=\\{0,1\\}$, $I=[0,1]$, $U=B^n$ (the space of $n$-vectors over $B$) and $V=I^n$. The universe of individuals is taken to be $U$, predicates are thought of as {\\em multilinear polynomials} from $U^k$ to $B$, and logical functions are taken as maps from $U^k$ to $U$. The polynomial representation (also called the {\\em Fourier expansion}) provides the basis for an embedding of  predicates into the space of continuous functions $V^k \\rightarrow I$ and an embedding of logical functions into continuous functions $V\\rightarrow V$.   \n\nNote that the set of all Boolean functions in $n$ variables forms a vector space over $\\Re$. The elementary monomials $\\Pi_{i\\in A} x_i$ (with $A \\subseteq \\{1,\\ldots, n\\}$) form a basis. (The identity $x\\mtimes x=x$ can be used to reduce all monomials to this form.) \n\nWe now proceed step by step. \n\\subsection{Propositional logic}\\label{section:prop-logic}\nLet the underlying base domain be $B$, with $0$ interpreted as false and $1$ as true. Define $\\bar{a}$ as $1-a$. Define:\n\n\\begin{align*}\n  \\LL{\\neg a} &= \\bar{\\LL{a}}\\\\\n  \\LL{a \\And b} &= \\LL{a}\\mtimes \\LL{b}\n\\end{align*}\n\nThe definition of the other logical operators follows:\n\\begin{align*}\n  \\LL{a\\Or b} &= \\overline{\\bar{a}\\bar{b}} = a+b(1-a)=a(1-b)+b \\\\\n  \\LL{a \\Arrow b} &= \\overline{\\LL{a}\\mtimes\\bar{\\LL{b}}}\\\\\n  \\LL{a \\Xor b} &= \\LL{a} + \\LL{b} - 2\\mtimes\\LL{a}\\mtimes\\LL{b}=(\\LL{a}-\\LL{b})^2\\\\\n  \\LL{(a = b)} &=\\LL{a}\\mtimes \\LL{b} + \\bar{\\LL{a}}\\bar{\\LL{b}} =\\overline{(\\LL{a}-\\LL{b})^2}\n\\end{align*}\n\n% TODO: Look into using max for Or and min for And. How is the completion of these different\n% from the definitions above? \n \nThe indicator function $\\Ind_a(x)$ which for $a,x \\in B$ returns\n$1$ if $a$ equals $x$ and $0$ otherwise, is just $\\_=\\_$.\n\n\\subsection{Representing first-order logic}\n\n\\subsubsection{Representing the domain of discourse}\nFor now we shall consider only finite domains (the finiteness assumption of the underlying domain is standard practice in machine learning).\n\nWe shall now make an assumption fundamental to this vector space approach to logic: individuals can be associated with vectors over \\(B^n\\). That is, we assume that the space of individuals carries ``internal'' structure: an individual is, intrinsically, a linear combination of \\(n\\) unit vectors in some space, and the predicates of interest to us respect this linear structure. Note that the ``classical'' domain of discourse for logic -- consisting of a set of \\(n\\) individuals with no ``internal'' connection to each other -- can be accommodated in the current setting by considering a space with \\(n\\) dimensions, and associating each individual with a unit vector along a given dimension. Thus the individuals are ``linearly independent'' of each other (orthogonal). This use of ``one-hot'' representations comes at a price -- $n$ bits are used to represent a set of size \\(n\\), rather than a set of size \\(2^n\\). %\\footnote{Of course, a ``sparse'' representation of the vector could be used, each vector being represented by the index of the unique element that is \\(1\\) -- this is a representation of size \\(\\log_2(n)\\).} \n\nThe justification for such an assumption  comes from the ``associational'' theories of Robert Firth (``you shall know the meaning of words by the company they keep''), \\cite{firth-57}. In natural language processing, such a ``vector representation'' of words (including words such as {\\sc London} and {\\sc Paris}) has met with some success.  Various mechanisms have been devised (e.g.{} \\cite{word-to-vec}) using associational techniques to associate dense vectors with objects. Determining the dimensionality of this vector space now becomes a critical task in this approach to knowledge representation. Empirically, \\(n=300\\) and \\(n=600\\) have been used; likely these numbers are low for general knowledge representation tasks. \n\nNote that the linear representation automatically comes with a ``built-in'' similarity relation $\\sim$ (the cosine distance between the vectors).\n\n%We shall assume an external mechanism has been used to identify the individuals in the domain of interest to us (e.g.{} the characters in some novel), based on empirically available data. Further, this may have been done using ``distributional'' techniques, so that the individuals are in fact represented as (dense) vectors in some high dimensional space $U$ \\cite{word-to-vec}. This linear representation automatically comes with a ``built-in'' similarity relation $\\sim$ (the cosine distance between the vectors). The value of $n$ will depend on the amount of data available and the number of individuals; $n=300$ and $n=600$ have been used to create vectors for words in various corpora. Determining the right value of \\(n\\) is a critical task in this approach to knowledge representation.\n\n\nWe can extend the technique of indicator functions discussed above to $n$-vectors. By $\\Ind_a(x)$ (for $a,x$ $n$-vectors over \\(B\\)) we will mean \\(\\Pi_{i   \\in 1\\ldots n} \\Ind_{a_i}(x_i)\\).  Therefore, any function \\(f:B^n \\rightarrow \\Re\\) can be represented as a multilinear polynomial (its ``Fourier expansion'') \\cite{boolean-function}: \n\\begin{equation}\\label{eqn:fourier-expansion}\n\\LL{f} \\defeq \\Sigma_{a \\in \\{0,1\\}^n} f(a)\\Ind_{a}(x)\n\\end{equation}\n\n\nAlternatively, we can use a different basis, the monomials \\cite{PB-optimization}. Every\nfunction $f:\\{0,1\\}^n \\rightarrow \\Re$ can be uniquely represented as a multilinear polynomial: \n$$ c_0 + \\Sigma_{k \\in 1\\ldots m} (c_k\\; \\Pi_{i \\in A_k} x_i)$$\n\\noindent for real coefficients $c_0, c_1, \\ldots c_m$ and non-empty subsets $A_1, \\ldots, A_m$ of $N = \\{1, \\ldots, n\\}$. \n\n\\begin{example}\nLet us work out $\\mbox{and2}: \\{0,1\\}^2 \\rightarrow \\Re$ (a unary function that returns 1 iff both components are 1):\n\n\\begin{align*}\n\\LL{and2(x)}  &= 1\\mtimes \\Ind_{(1,1)}(x) + 0\\mtimes\\Ind_{(1,0)}(x) + 0\\mtimes\\Ind_{(0,1)}(x) + 0\\mtimes\\Ind_{(0,0)}(x)\\\\\n&= \\Ind_{(1,1)}(x) \\\\\n&= (1 \\mtimes x_1+0\\mtimes(1-x_1))\\mtimes(1 \\mtimes x_2+0\\mtimes(1-x_2))\\\\\n  &=x_1\\mtimes x_2 \n\\end{align*}\n\\end{example}\n\n\\subsubsection{Representing first-order predicates}\nWe can use the technique of indicator functions to represent a $k$-ary predicate $p$ as a multilinear polynomial over \\(kn\\) variables. \n\\begin{equation}\n\\LL{p(x_1,\\ldots, x_k)} \\defeq \\Sigma_{a_1,\\ldots,a_k \\in U} p(a_1, \\ldots, a_k) \\mtimes \\Pi_{i \\in 1\\ldots k} \\Ind_{a_i}(x_i)  \n\\end{equation}\n\n%% TODO: Somewhere we need to introduce the point that p is represented by n^k numbers only.\n%% We have to find a way to use the linear expansion here to reduce the size of these formulas\n%%\n\nImportantly, the above representation is linear in \\(p(a_1, \\ldots, a_k)\\). If the extension of the predicate is only partially known, each value for which it is not known can be replaced by a variable without affecting multilinearity. In this sense, the representation supports a form of ``higher-orderedness'' as well.\n\nNote that this technique can be used to represent the equality predicate: Here $p(a,b)=1$ if $a=b$, and $0$ otherwise.\n\nA $k$-ary function $f:U^k \\rightarrow U$ is represented by $n$ polynomials, one for each dimension.\n\nThe Boolean operations are defined as in Section~\\ref{section:prop-logic}. Since the domain is finite, existential quantification is represented by a finite disjunction:\n\\begin{equation}\n  \\LL{\\exists X \\, \\phi}\\defeq \\LL{\\bigvee_{a \\in U} \\phi[a/X]}\n\\end{equation}\n\\noindent Universal quantification is represented by a finite conjunction:\n\\begin{equation}\n  \\LL{\\forall X \\, \\phi} \\defeq \\LL{\\bigwedge_{a \\in U} \\phi[a/X]}\n\\end{equation}\n\nThus, any first-order formula (with equality) in a logical vocabulary \\({\\cal L}\\) can be represented as multilinear polynomial over \\(B\\). Importantly, formulas with free variables are representable as well.\n\n\\begin{example}\n  We can represent the formula \\(\\forall X, Y. P(X,Y) \\leftarrow \\exists Z. r(X,Z) \\wedge P(Z, Y) \\) (for \\(r\\) a binary predicate whose extension is known and \\(P\\) a binary predicate whose extension is not known) as follows. We introduce \\(|U|^2\\) variables \\(P_{a,b}\\) for \\(a,b\\in U\\):\n  \\[\n  \\begin{array}{lll}\n    \\LL{P(Z,Y)} &=& \\Sigma_{a,b \\in U} P_{a,b} \\mtimes \\LL{Z=a}\\mtimes \\LL{Y=B}\\\\\n    \\LL{r(X,Z)} &=& \\Sigma_{a,b \\in U} r(a,b) \\mtimes \\LL{X=a}\\mtimes \\LL{Z=B}\\\\    \n    \\LL{\\exists Z\\ r(X,Z)\\wedge P(Z,Y)} &=& \n  \\end{array}\n  \\]\n\\end{example}\n\n\n\\subsection{Tensor representation}\nA multilinear function $U^k \\rightarrow \\Re$ can be represented directly as a (covariant) tensor $T_k(U)$ \\cite[Chapter 8]{lee-book-2000}. The tensor maps a tuple \\tuple{u_1,\\ldots, u_k} to $1$ if the tuple is in the relation and to $0$ otherwise. Function application is implemented through tensor contraction. Note that in practice such a tensor is implemented extensionally merely as a \\(k\\)-dimensional array with \\(n\\) elements in each dimension (thus requiring \\(n^k\\) numbers). \n\nFor more details, please see Appendix~\\ref{sec:tensor} where a relatively self-contained background is provided for tensors, and examples worked out. \n\n\\subsection{Continuous embedding}\nWe now take the all important step of passing to the continuous version of the above representation. \nThe continuous representation of a first-order formula $p$, $p^c$ is given by the above polynomial, with\nvariables ranging over $[0,1]$. It is easy to see that the result will also be in $[0,1]$. (The result is the weighted sum of $p(a_1, \\ldots, \n  a_k)$, with the weight supplied by the distance between $(x_1,\n  \\ldots, x_k)$ and $(a_1, \\ldots, a_k)$ using $\\Ind_{a_i}(x_i)$. The\n  weights sum to $1$, as can be shown by an inductive argument,\n  leveraging the fact that $\\Ind_{0}(x) + \\Ind_{1}(x)=(1x+0(1-x))+(0x+1(1-x))=1$.)\n\nSimilarly for $f^c$. \n\nThe intuition is that $[0,1]^n$ represents a continuous smearing of the space $\\{0,1\\}^n$ of ``ideal'' individuals. The polynomial representation of a relation faithfully represents the behavior of the original (discrete) relation on the ideal points, and represents the behavior on intermediate (``smeared'') points as a linear combination of the behavior on ideal points.\n% TODO: Should be able to formulate using probabilities and expectations.\n\nThe rules for differentiation of these polynomials wrt a variable are standard. \n\n\\begin{example}\nAssume the underlying domain is expressible as 2-dimensional vectors. Let {\\em bill} be represented by \\((1, 0)\\), {\\em hilary} by \\((0,1)\\), and the extension of the predicate {\\em love/2} be given by\n\\begin{lstlisting}\nlove(bill,hillary).\nlove(hilary,bill).\nlove(hilary,hilary).\n\\end{lstlisting}\nThe representation of {\\em love(x,y)} is:\n\\begin{align*}\n&\\Ind_{(1,0)}(x)\\Ind_{(0,1)}(y) + \\Ind_{(0,1)}(x)\\Ind_{(1,0)}(y) + \\Ind_{(0,1)}(x)\\Ind_{(0,1)}(y)  \\\\\n&= x_1\\bar{x_2}\\bar{y_1}y_2 + \\bar{x_1}x_2y_1\\bar{y_2} + \\bar{x_1}x_2\\bar{y_1}y_2\n\\end{align*}\nFor \\(((1,0),(0,1))\\) the polynomial evaluates to \\(1\\); for \\(((1,0),(1,0))\\) it evaluates to \\(0\\). \n\nFor someone \\((0.9,0.2)\\) more like {\\em bill} than {\\em hilary}, the degree to which they love\n{\\em bill} is given by: \n\\(((0.9)(0.8)(0)(0) + (0.1)(0.2)(1)(1) + (0.1)(0.2)(0)(0)=0.02\\).\n%$((0.9)(0.8)(1)(1) + (0.1)(0.2)(0)(0) + (0.1)(0.2)(1)(1)=(0.72)+(0.02)=0.74$.\n\nFor someone (\\((0.5,0.5)\\)) with characteristics of both {\\em bill} and {\\em hilary} we get the degree to which they love {\\em hilary}  is given by\n%$(0.5)(0.5)(0.5)(0.5)+(0.5)(0.5)(0.5)(0.5)+(0.5)(0.5)(0.5)(0.5)=0.1875$.\n\\((0.5)(0.5)(1)(1)+(0.5)(0.5)(0)(0)+(0.5)(0.5)(1)(1)=0.5$, and the degree to which they love {\\em bill} is given by $(0.5)(0.5)(0)(0) + (0.5)(0.5)(1)(1) + (0.5)(0.5)(0)(0)=0.25\\).\n\n\\end{example}\n\n\\subsection{Expressiveness}\n% TODO: motivate and write up more extensively.\n% Define 1-Lipschitz. Motivate why they are interesting in this context.\nWe note that by adding max and step functions we can represent any $1$-Lipschitz function in the following sense.\n%This monomials as discussed above, together with max and step functions\n\nConsider the metric \\(d(X,Y) = max \\{\\lvert x_i - y_i \\rvert \\mid i\\in 1\\ldots n \\}\\) over \\(I^n\\). For a \nrational number \\(r\\) s.t. \\(0 \\leq r \\leq 1\\) and \\(Q\\) a vector of rational numbers, let \\(step_{r,Q}:I^n \\rightarrow \\Re\\) be defined as \\(max(0, r-d(X,Q))\\). This is the ``step'' function that is \\(r\\) at \\(X\\), then drops off to zero at the maximum possible rate. \n\n\\begin{definition}\n  Let \\(\\cal F\\) be the functions generated thus: any multilinear function is in \\(\\cal F\\); if \\(f,g \\in {\\cal F}\\), then so is \\(max(f,g)\\); \\(step_{r,Q} \\in {\\cal F}\\) for rational \\(r \\in I\\) s.t. \\(0 \\leq r \\leq 1\\) and vector \\(Q\\) of rationals.\n\\end{definition}\n\n\\begin{theorem}\n  For any \\(1\\)-Lipschitz function \\(g:I^n \\rightarrow \\Re\\) and \\(\\epsilon\\) there exists an \\(f \\in {\\cal F}\\) s.t. for all \\(X\\), \\(\\lvert g(X)-f(X) \\rvert \\lt \\epsilon\\).\n\\end{theorem}\nIn proof, consider the set \\(\\{ step_{r,Q} \\alt f(Q) \\ge r \\}\\). Closing this set under finite \\(max\\) yields a increasing sequence of functions that converges uniformly to \\(f\\).\n\n(Note: this proof does not depend on monomials.)\n\n\\section{Applications to Machine Learning}\n\n\nWe outline some directions that open up as a result of our approach.\n\n\\subsection{Learning arbitrary definite clauses}\nThe representation of formulas as polynomials makes it possible to use symbolic approaches to answer some logical questions. Here we discuss the {\\em rule extraction} task of \\cite[Algorithm 1]{bishan-iclr15}.\n\nThe basic approach in the paper is as follows. Entities are represented by $n$-vectors (as we discuss). A binary relation $p$ is represented as a matrix $\\LL{p}$, with a predication $p(x,y)$ evaluated as $\\LL{x}^t \\LL{p}\\LL{y}$.\\footnote{\\cite{bishan-iclr15} also discusses a form where predicates are represented as vectors; however this does not yield good results.} Their approach learns {\\em closed path} definite clauses; these are clauses of the form:\n$$ p_1(X_1, X_2), p_2(X_2,X_3), \\ldots, p_n(X_n, X_{n+1}) \\rightarrow p(X_1, X_{n+1})$$\nHere $p_i$ are known binary relations (trained matrices are available for them); this set is closed under inversion, since the inverse of a relation can be obtain by matrix operations. The basic idea is to find ``high probability paths'' in the knowledge graph (entities are types of nodes, predicates are binary edges), and compute the matrix representing the relation between the starting vertex $a$ and the final vertex $b$ by composing the matrices of the relations along the path. This is then compared with the existing relation labeling the edge $(a,b)$ using the $L_2$ norm; the rule is accepted if the norm is below a certain threshold. An example of a learned rule is:\n\\begin{lstlisting}\n nationality(A,C) :- bornInCity(A,B), cityOfCountry(B,C).\n\\end{lstlisting}\n\nThe main drawback of \\cite{bishan-iclr15} is that they have an {\\em ad hoc} rule for conjunction which permits them to only represent conjunctions of ``adjacent'' relations via matrix multiply. They do not have general compositional rules which permit the computation of conjunction of arbitrary formulas. For instance their technique cannot be used to learn clauses such as: \n\\begin{lstlisting}\n dualCitizen(A, C, C1) :- \n   bornIn(A,B), cityOfCountry(B, C1), C != C1, \n   residentOfCountry(C), \n   naturalizedInCountry(C).\n\\end{lstlisting}\nWith the techniques of this paper we can proceed as follows. The key point is that formulas are polynomials that can be manipulated algebraically. Assume we have identified a first-order formula $\\phi(\\bar{X})$ as the candidate for the body of a clause with head (an atomic formula) $\\psi(\\bar{Y})$. Typically $\\bar{Y}\\subseteq \\bar{X}$, consider for the moment that $\\bar{X}=\\bar{Y}$ (for the more general case we will need an order-reducing tensor operation, corresponding to projection or existential quantification). We need to determine whether the clause $\\phi(\\bar{X})\\rightarrow \\psi(\\bar{Y})$ is the case. Operating symbolically on the corresponding polynomials, we need to determine whether $1-\\phi(1-\\psi) \\approx 1$, i.e.{} $\\phi \\approx \\phi\\psi$. This can be done by tensor operations. \n\nIn essence, we can use the theory presented in this paper to address the problem of rule learning in a more general way.\n\n\\subsection{CCP programs with sketches}\n\n\\section{Work to do}\n\nHow does one deal with infinite domains?\n\n{\\em How does one deal with infinite domains? Does one need to? Do the\nusual machine learning algorithms make sense over infinite domains?\nThe representations are all in terms of finite vectors/ matrices /\ntensors, and individuals are represented with $n$-vectors, so in any\ncase we are basically considering only an equivalence class of the\ndomain with $2^n$ classes.}\n\n{\\em Track down whether there is any work in psuodo-Boolean\n  optimization related to optimization in the presence of first-order\n  constraints.\n}\n\n{\\em Are there general techniques from polynomial theory to help us do\n  logic, e.g. using Grobner basis, as in \\cite{Brickenstein:2009:PFG:1550968.1551286}.}\n\n{\\em Go back to the work on constrained clustering, adding these kinds\nof representations of first-order constraints. But first have to find\na tractable way of dealing with quantifiers. Look to hyper-doctrinal paper as a general \nway to introduce quantifiers.}\n\n{\\em Applications in constraint programming?}\n\n\\paragraph{Acknowledgements.} Luc de Raedt, Angelika Kimmig, Tom Mitchell, William Cohen, Bishan Yang, Michael Witbrock, Piero Molino, \\ldots\n\n\\bibliographystyle{alpha}\n\\bibliography{master}\n\n\\appendix\n\\newpage\n\n\\section{Clausal form and logic programming}\n\\subsubsection{Clausal representation}\nThe general representation of a clause with literals $a_i,b_j$ is:\n\\begin{equation}\n\\LL{a_1,\\ldots, a_m \\Arrow b_1, \\ldots, b_n} = 1-(\\Pi_{i \\in 1\\ldots m} \\LL{a_i}) \\mtimes (\\Pi_{j\\in 1\\ldots n} \\bar{b}_j)\n\\end{equation}\n\\noindent (Think: $a_1,\\ldots, a_m \\Arrow b_1, \\ldots, b_n$ is the same as $\\neg ((a_1 \\wedge \\ldots a_m)\n\\wedge (\\neg b_1) \\wedge \\ldots \\wedge (\\neg b_n))$.)\n\nDefinite clauses, negative clauses, unit clauses, and empty clauses are the special cases with \n$n=1$, $n=0$, $(m=0,n=1)$ and $(m=0,n=0)$: \n  \\begin{align*}\n    \\LL{a_1,\\ldots, a_m \\Arrow b} &= 1-{(\\Pi_{i \\in 1\\ldots m} a_i) \\mtimes \\bar{b}}\\\\\n    \\LL{a_1,\\ldots, a_m \\Arrow } &= 1-{\\Pi_{i \\in 1\\ldots m} a_i}\\\\\n    \\LL{ \\Arrow b} &= b\\\\\n    \\LL{ \\Arrow } &= 1 - 1 = 0\n  \\end{align*}\n\nNow we can see how unit resolution works.  Given $a=1$, unit resolution reduces $1-a\\mtimes\\phi$ to $1-\\phi$; given $a=0$, $1- (1-a)\\mtimes \\phi$ reduces to $1-\\phi$. \n\nMore generally, one can think of definite clause programming thus. We are given a theory $\\Sigma=\\{(1-\\phi_1),\\ldots, (1-\\phi_n)\\}$, where each formula $1-\\phi_i$ represents a definite clause.  \nLet us say that a {\\em valuation} is a function from the set of variables to $\\{0,1\\}$. A {\\em solution} of $\\Sigma$ assigns $1$ to each formula $1-\\phi_i$ in $\\Sigma$, i.e.{} assigns zero to each $\\phi_i$. \n\nNow we are given a query $q=a_1 \\And \\ldots \\And a_k$ and asked to establish $\\Sigma \\vdash q$. That is, every solution for $\\Sigma$ must assign $1$ to each $a_j, j\\in 1\\ldots k$. Backward chaining consists of finding some clause $b_1,\\ldots, b_m\\Arrow a_j$, for some $j\\in 1\\ldots k$ and replacing the query $q$ with $a_1\\And \\ldots \\And a_{j-1} \\And b_1 \\And \\ldots b_m \\And \\ldots \\And a_k$. (Note that $m$ could be zero, thus decreasing the size of the resulting query.) This process is repeated until the size of the final query is $0$.\n\nWhy is this sound? Because every solution $v$ that assigns $0$ to $b_1\\mtimes \\ldots \\mtimes b_j\\mtimes (1-a_j)$ and $1$ to \n$a_1\\mtimes \\ldots \\mtimes a_{j_1}\\mtimes b_1 \\mtimes \\ldots \\mtimes b_m \\mtimes a_{j+1}\\mtimes \\ldots \\mtimes a_k$ can only do so by \nassigning $1$ to $b_1, \\ldots, b_m$ {\\em and} $1$ to $a_j$, and $1$ to $a_1,\\ldots, a_{j-1},a_{j+1},\\ldots a_k$. Therefore it assigns $1$ to $a_1 \\mtimes \\ldots \\mtimes a_k$. \n\n\\paragraph{Posiform.}\n%% TODO: Have not introduced pseudo-Boolean yet. Why is this important to say. What does ``many ways'' mean?\nLet $\\bar{x}$ stand for $(1-x)$. Every pseudo-Boolean function can also be represented in many ways through ``clausal decompositions'', called {\\em posiforms}:\n\\begin{equation}\n  f(x_1,\\ldots, x_n)=b_0 + \\Sigma_{k \\in 1\\ldots m} b_k (\\Pi_{i\\in A_k} x_i \\Pi_{j\\in B_k}(\\bar{x_j}))\n\\end{equation}\n\\noindent where $b_k\\geq 0$ for $k \\in 1\\ldots m$. \n\n\\input{appendix-tensor-3}\n\\end{document}\n", "meta": {"hexsha": "29f5626117ceab8fb702cbf409ee1524acdee391", "size": 30436, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "notes.tex", "max_stars_repo_name": "saraswat/logic-nn", "max_stars_repo_head_hexsha": "79af16ead7d86e4eca0b3cfc88d1c3379485088f", "max_stars_repo_licenses": ["CECILL-B"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2016-05-13T15:55:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-11T12:28:48.000Z", "max_issues_repo_path": "notes.tex", "max_issues_repo_name": "saraswat/logic-nn", "max_issues_repo_head_hexsha": "79af16ead7d86e4eca0b3cfc88d1c3379485088f", "max_issues_repo_licenses": ["CECILL-B"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notes.tex", "max_forks_repo_name": "saraswat/logic-nn", "max_forks_repo_head_hexsha": "79af16ead7d86e4eca0b3cfc88d1c3379485088f", "max_forks_repo_licenses": ["CECILL-B"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 79.0545454545, "max_line_length": 1132, "alphanum_fraction": 0.7341963464, "num_tokens": 8590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.330192565775358}}
{"text": "\\documentclass[12pt]{article}\n\\usepackage{amssymb}\n\\usepackage{amsmath}\n\\usepackage{url}\n\\usepackage{xspace}\n\\usepackage[margin=2.5cm]{geometry}\n\\usepackage{tikz}\n\\usepackage{pgfplots} \n\\usepackage{listings}\n\\usepackage{color}\n\\usepackage{textcomp}\n\\usepackage[colorlinks]{hyperref}\n\\newcommand{\\real}{\\mathbb{R}}\n\\newcommand{\\vv}{\\operatorname{vec}}\n\\newcommand{\\diag}{\\operatorname{diag}}\n\\newcommand{\\vlnn}{\\textsc{MatConvNet}\\xspace}\n\\newcommand{\\cpp}{C{}\\texttt{++}~}\n\n\\newcommand{\\bx}{\\mathbf{x}}\n\\newcommand{\\by}{\\mathbf{y}}\n\\newcommand{\\bz}{\\mathbf{z}}\n\\newcommand{\\bff}{\\mathbf{f}}\n\\newcommand{\\bw}{\\mathbf{w}}\n\\newcommand{\\bs}{\\mathbf{s}}\n\\newcommand{\\bfe}{\\mathbf{e}}\n\\newcommand{\\bone}{\\mathbf{1}}\n\\newcommand{\\argmin}{\\operatornamewithlimits{argmin}}\n\n\\tikzstyle{block} = [draw, rectangle, minimum height=3em, minimum width=3em] \\tikzstyle{data} = []\n\\tikzstyle{pinstyle} = [pin edge={to-,thin,black}]\n\n% Taken inspiration from http://www.tjansson.dk/2008/11/using-lstlisting-to-include-code-in-latex/\n\\definecolor{listinggray}{gray}{0.9}\n\\definecolor{lbcolor}{rgb}{0.8,0.8,0.8}\n\\lstset{\n\t%backgroundcolor=\\color{lbcolor},\n\ttabsize=4,\n\trulecolor=,\n\tlanguage=matlab,\n\tbasicstyle=\\footnotesize,\n\tupquote=true,\n\tcolumns=fixed,\n\taboveskip={1.2\\baselineskip},\n\tbelowskip={1.2\\baselineskip},\n\tshowstringspaces=false,\n\textendedchars=true,\n\tbreaklines=false,\n\tprebreak = \\raisebox{0ex}[0ex][0ex]{\\ensuremath{\\hookleftarrow}},\n\t%frame=single,\n\tshowtabs=false,\n\tshowspaces=false,\n\tshowstringspaces=false,\n\tidentifierstyle=\\ttfamily,\n\tkeywordstyle=\\color[rgb]{0,0,1},\n\tcommentstyle=\\itshape\\color[rgb]{0.133,0.545,0.133},\n\tstringstyle=\\color[rgb]{0.627,0.126,0.941},\n}\n\n% ------------------------------------------------------------------\n\\begin{document}\n\\title{MatConvNet \\\\\n\\Large\nConvolutional Neural Networks for MATLAB}\n\\author{\nAndrea Vedaldi\n\\and\nKarel Lenc}\n\\date{}\n\\maketitle{}\n%\\vspace{-3em}\n\n\\begin{abstract}\n\\vlnn is an implementation of Convolutional Neural Networks (CNNs) for MATLAB. The toolbox is designed with an emphasis on simplicity and flexibility. It exposes the building blocks of CNNs as easy-to-use MATLAB functions, providing routines for computing linear convolutions with filter banks, feature pooling, and many more. In this manner, \\vlnn allows fast prototyping of new CNN architectures; at the same time, it supports efficient computation on CPU and GPU allowing to train complex models on large datasets such as ImageNet ILSVRC. This document provides an overview of CNNs and how they are implemented in \\vlnn and gives the technical details of each computational block in the toolbox.\n\\end{abstract}\n\n\\newpage\n\\tableofcontents{}\n% ------------------------------------------------------------------\n\n% ------------------------------------------------------------------\n\\section{Introduction}\\label{s:intro}\n% ------------------------------------------------------------------\n\n\\vlnn is a simple MATLAB toolbox implementing Convolutional Neural Networks (CNN) for computer vision applications. This documents starts with a short overview of CNNs and how they are implemented in \\vlnn. Section~\\ref{s:blocks} lists all the computational building blocks implemented in \\vlnn that can be combined to create CNNs and gives the technical details of each one. Finally, Section~\\ref{s:wrappers} discusses more abstract CNN wrappers and example code and models.\n\nA \\emph{Convolutional Neural Network} (CNN) can be viewed as a function $f$ mapping data $\\bx$, for example an image, on an output vector $\\by$. The function $f$ is a composition of a sequence (or a directed acyclic graph) of simpler functions $f_1,\\dots,f_L$, also called \\emph{computational blocks} in this document. Furthermore, these blocks are \\emph{convolutional}, in the sense that they map an input image of feature map to an output feature map by applying a translation-invariant and local operator, e.g. a linear filter. The \\vlnn toolbox contains implementation for the most commonly used computational blocks (described in Section~\\ref{s:blocks}) which can be used either directly, or through simple wrappers. Thanks to the modular structure, it is a simple task to create and combine new blocks with the existing ones. %New blocks are also easy to create and combine with the existing ones.\n\nBlocks in the CNN usually contain parameters $\\bw_1,\\dots,\\bw_L$. These are \\emph{discriminatively learned from example data} such that the resulting function $f$ realizes an useful mapping. A typical example is image classification; in this case the output of the CNN is a vector $\\by=f(\\bx)\\in\\real^C$ containing the confidence that $\\bx$ belong to any of $C$ possible classes. Given training data $(\\bx^{(i)},\\by^{(i)})$ (where $\\by^{(i)}$ is the indicator vector of the class of $\\bx^{(i)}$), the parameters are learned by solving\n\\begin{equation}\\label{e:objective}\n \\argmin_{\\bw_1,\\dots\\bw_n}\n \\frac{1}{n}\\sum_{i=1}^n\n \\ell\\left(\n f(\\bx^{(i)};\\bw_1,\\dots,\\bw_L),\n \\by^{(i)}\n \\right)\n\\end{equation}\nwhere $\\ell$ is a suitable \\emph{loss function} (e.g. the hinge or log loss).\n\nThe optimization problem~\\eqref{e:objective} is usually non-convex and very large as complex CNN architectures need to be trained from hundred-thousands or even millions of examples. Therefore efficiency is a paramount. Optimization often uses a variant of \\emph{stochastic gradient descent}. The algorithm is, conceptually, very simple: at each iteration a training point is selected at random, the derivative of the loss term for that training sample is computed resulting in a gradient vector, and parameters are incrementally updated by moving towards the local minima in the direction of the gradient. The key operation here is to compute the derivative of the objective function, which is obtained by an application of the chain rule known as \\emph{back-propagation}. \\vlnn can evaluate the derivatives of all the computational blocks. It also contains several examples of training small and large models using these capabilities and a default solver, although it is easy to write customized solvers on top of the library.\n\nWhile CNNs are relatively efficient to compute, training requires iterating many times through vast data collections. Therefore the computation speed is very important in practice. Larger models, in particular, may require the use of GPU to be trained in a reasonable time. \\vlnn has integrated GPU support based on NVIDIA CUDA and MATLAB built-in CUDA capabilities.\n\n% ------------------------------------------------------------------\n\\subsection{\\vlnn on a glance}\\label{s:vlnn}\n% ------------------------------------------------------------------\n\n\\vlnn has a simple design philosophy. Rather than wrapping CNNs around complex layers of software, it exposes simple functions to compute CNN building blocks, such as linear convolution and ReLU operators. These building blocks are easy to combine into a complete CNNs and can be used to implement sophisticated learning algorithms. While several real-world examples of small and large CNN architectures and training routines are provided, it is always possible to go back to the basics and build your own, using the efficiency of MATLAB in prototyping. Often no C coding is required at all to try a new architectures. As such, \\vlnn is an ideal playground for research in computer vision and CNNs.\n\n\\vlnn contains the following elements:\n\\begin{itemize}\n\\item \\emph{CNN computational blocks.} A set of optimized routines computing fundamental building blocks of a CNN. For example, a convolution block is implemented by \\linebreak \\verb!y=vl_nnconv(x,f,b)! where \\verb!x! is an image, \\verb!f! a filter bank, and \\verb!b! a vector of biases (Section~\\ref{s:convolution}). The derivatives are computed as\n\\verb![dzdx,dzdf,dzdb] = vl_nnconv(x,f,b,dzdy)! where \\verb!dzdy! is the derivative of the CNN output w.r.t \\verb!y!~(Section~\\ref{s:convolution}). Section~\\ref{s:blocks} describes all the blocks in detail.\n\\item \\emph{CNN wrappers.} \\vlnn provides a simple wrapper, suitably invoked by \\verb!vl_simplenn!, that implements a CNN with a linear topology (a chain of blocks). This is good enough to run most of current state-of-the-art models for image classification. You are invited to look at the implementation of this function, as it is a great starting point to understand how to implement more complex CNNs.\n\\item \\emph{Example applications.} \\vlnn provides several example of learning CNNs with stochastic gradient descent and CPU or GPU, on MNIST, CIFAR10, and ImageNet data.\n\\item \\emph{Pre-trained models.} \\vlnn provides several state-of-the-art pre-trained CNN models that can be used off-the-shelf, either to classify images or to produce image encodings in the spirit of Caffe or DeCAF.\n\\end{itemize}\n\n% ------------------------------------------------------------------\n\\subsection{The structure and evaluation of CNNs}\\label{s:forward}\n% ------------------------------------------------------------------\n\nCNNs are obtained by connecting one or more \\emph{computational blocks}. Each block $\\by = f(\\bx,\\bw)$ takes an image $\\bx$ and a set of parameters $\\bw$ as input and produces a new image $\\by$ as output. An image is a real 4D array; the first two dimensions index spatial coordinates (image rows and columns respectively), the third dimension feature channels (there can be any number), and the last dimension image instances. A computational block $f$ is therefore represented as follows:\n\\begin{center}\n\\begin{tikzpicture}[auto, node distance=2cm]\n\\node (x) [data] {$\\bx$};\n\\node (f) [block,right of=x]{$f$};\n\\node (y) [data, right of=f] {$\\by$};\n\\node (w) [data, below of=f] {$\\bw$};\n\\draw [->] (x.east) -- (f.west) {};\n\\draw [->] (f.east) -- (y.west) {};\n\\draw [->] (w.north) -- (f.south) {};\n\\end{tikzpicture}\n\\end{center}\nFormally, $\\bx$ is a 4D tensor stacking $N$ 3D images\n\\[\n   \\bx \\in \\real^{H \\times W \\times D \\times N}\n\\]\nwhere $H$ and $W$ are the height and width of the images, $D$ its depth, and $N$ the number of images. In what follows, all operations are applied identically to each image in the stack $\\bx$; hence for simplicity we will drop the last dimension in the discussion (equivalent to assuming $N=1$), but the ability to operate on image batches is very important for efficiency.\n\nIn general, a CNN can be obtained by connecting blocks in a directed acyclic graph (DAG). In the simplest case, this graph reduces to a sequence of computational blocks $(f_1,f_2,\\dots,f_L)$. Let $\\bx_1,\\bx_2,\\dots,\\bx_L$ be the output of each layer in the network, and let $\\bx_0$ denote the network input. Each output $\\bx_l$ depends on the previous output $\\bx_{l-1}$ through a function $f_l$ with parameter $\\bw_l$ as $\\bx_l = f_l(\\bx_{l-1};\\bw_l)$; schematically:\n\\begin{center}\n\\begin{tikzpicture}[auto, node distance=2cm]\n\\node (x0)  [data] {$\\bx_0$};\n\\node (f1) [block,right of=x0]{$f_1$};\n\\node (f2) [block,right of=f1,node distance=3cm]{$f_2$};\n\\node (dots) [right of=f2]{...};\n\\node (fL) [block,right of=dots]{$f_L$};\n\\node (xL)  [data, right of=fL] {$\\bx_L$};\n\\node (w1) [data, below of=f1] {$\\bw_1$};\n\\node (w2) [data, below of=f2] {$\\bw_2$};\n\\node (wL) [data, below of=fL] {$\\bw_L$};\n\\draw [->] (x0.east) -- (f1.west) {};\n\\draw [->] (f1.east) -- node {$\\bx_2$} (f2.west);\n\\draw [->] (f2.east) -- node {$\\bx_3$} (dots.west) {};\n\\draw [->] (dots.east) -- node {$\\bx_{L-1}$} (fL.west) {};\n\\draw [->] (fL.east) -- (xL.west) {};\n\\draw [->] (w1.north) -- (f1.south) {};\n\\draw [->] (w2.north) -- (f2.south) {};\n\\draw [->] (wL.north) -- (fL.south) {};\n\\end{tikzpicture}\n\\end{center}\nGiven an input $\\bx_0$, evaluating the network is a simple matter of evaluating all the intermediate stages in order to compute an overall function $\\bx_L = f(\\bx_0;\\bw_1,\\dots,\\bw_L)$. \n\n% ------------------------------------------------------------------\n\\subsection{CNN derivatives}\\label{s:backward}\n% ------------------------------------------------------------------\n\nIn training a CNN, we are often interested in taking the derivative of a loss $\\ell : f(\\bx,\\bw) \\mapsto \\real$ with respect to the parameters. This effectively amounts to extending the network with a \\emph{scalar block} at the end:\n\\begin{center}\n\\begin{tikzpicture}[auto, node distance=2cm]\n\\node (x0)  [data] {$\\bx_0$};\n\\node (f1) [block,right of=x0]{$f_1$};\n\\node (f2) [block,right of=f1,node distance=3cm]{$f_2$};\n\\node (dots) [right of=f2]{...};\n\\node (fL) [block,right of=dots]{$f_L$};\n\\node (loss) [block,right of=fL,node distance=3cm]{$\\ell$};\n\\node (w1) [data, below of=f1] {$\\bw_1$};\n\\node (w2) [data, below of=f2] {$\\bw_2$};\n\\node (wL) [data, below of=fL] {$\\bw_L$};\n\\node (z) [data, right of=loss] {$z\\in\\real$};\n\\draw [->] (x0.east) -- (f1.west) {};\n\\draw [->] (f1.east) -- node {$\\bx_2$} (f2.west);\n\\draw [->] (f2.east) -- node {$\\bx_3$} (dots.west) {};\n\\draw [->] (dots.east) -- node {$\\bx_{L-1}$} (fL.west) {};\n\\draw [->] (fL.east) -- node {$\\bx_L$} (loss.west);\n\\draw [->] (loss.east) -- (z) {};\n\\draw [->] (w1.north) -- (f1.south) {};\n\\draw [->] (w2.north) -- (f2.south) {};\n\\draw [->] (wL.north) -- (fL.south) {};\n\\end{tikzpicture}\n\\end{center}\nThe derivative of $\\ell \\circ f$ with respect to the parameters can be computed but starting from the end of the chain (or DAG) and working backwards using the chain rule, a process also known as back-propagation. For example the derivative w.r.t. $\\bw_l$ is:\n\\begin{equation}\\label{e:chain-rule}\n \\frac{dz}{d(\\vv\\bw_l)^\\top}\n =\n \\frac{dz}{d(\\vv\\bx_{L})^\\top}\n \\frac{d\\vv\\bx_{L}}{d(\\vv\\bx_{L-1})^\\top}\n \\dots\n \\frac{d\\vv\\bx_{l+1}}{d(\\vv\\bx_{l})^\\top}\n \\frac{d\\vv\\bx_{l}}{d(\\vv\\bw_{l})^\\top}.\n\\end{equation}\nNote that the derivatives are implicitly evaluated at the working point determined by the input $\\bx_0$ during the evaluation of the network in the forward pass. The $\\vv$ symbol is the vectorization operator, which simply reshape its tensor argument to a column vector. This notation for the derivatives is taken from~\\cite{kinghorn96integrals} and is used throughout this document.\n\nComputing~\\eqref{e:chain-rule} requires computing the derivative of each block $\\bx_l = f_l(\\bx_{l-1},\\bw_l)$ with respect to its parameters $\\bw_l$ and input $\\bx_{l-1}$. Let us know focus on computing the derivatives for one computational block. We can look at the network as follows:\n\\[\n    \\underbrace{\n    \\ell \\circ f_{L}(\\cdot,\\bw_L)\n     \\circ f_{L-1}(\\cdot,\\bw_{L-1})\n     \\dots\n     \\circ f_{l+1}(\\cdot,\\bw_{l+1})\n     }_{\\displaystyle z(\\cdot)}\n     \\circ f_{l}(\\bx_l,\\bw_{l})\n     \\circ \\dots\n\\]\nwhere $\\circ$ denotes the composition of function. For simplicity, lump together the factors from $f_l+1$ to the loss $\\ell$ into a single scalar function $z(\\cdot)$ and drop the subscript $l$ from the first block. Hence, the problem is to compute the derivative of $(z \\circ f)(\\bx,\\bw) \\in \\real$ with respect to the data $\\bx$ and the parameters $\\bw$. Graphically:\n\\begin{center}\n\\begin{tikzpicture}[auto, node distance=2cm]\n\\node (x) [data] {$\\bx$};\n\\node (f) [block,right of=x ] {$f$};\n\\node (bz)[block,right of=f ] {$z(\\cdot)$};\n\\node (z) [data, right of=bz] {$z$};\n\\node (w) [data, below of=f ] {$\\bw$};\n\\draw [->] (x.east) -- (f.west) {};\n\\draw [->] (f.east) -- node {$\\by$}  (bz.west) {};\n\\draw [->] (w.north) -- (f.south) {};\n\\draw [->] (bz.east) -- (z.west) {};\n\\end{tikzpicture}\n\\end{center}\nThe derivative of $z \\circ f$ with respect to $\\bx$ and $\\bw$ are given by:\n\\[\n\\frac{dz}{d(\\vv \\bx)^\\top}\n=\n\\frac{dz}{d(\\vv \\by)^\\top}\n\\frac{d\\vv f}{d(\\vv \\bx)^\\top},\n\\quad\n\\frac{dz}{d(\\vv \\bw)^\\top}\n=\n\\frac{dz}{d(\\vv \\by)^\\top}\n\\frac{d\\vv f}{d(\\vv \\bw)^\\top},\n\\]\nWe note two facts. The first one is that, since $z$ is a scalar function, the derivatives have a number of elements equal to the number of parameters. So in particular $dz/d\\vv \\bx^\\top$ can be reshaped into an array $dz/d\\bx$ with the same shape of $\\bx$, and the same applies to the derivatives $dz/d\\by$ and $dz/d\\bw$. Beyond the notational convenience, this means that storage for the derivatives is not larger than the storage required for the model parameters and forward evaluation.\n\nThe second fact is that computing $dz/d\\bx$ and $dz/d\\bw$ require the derivative $dz/d\\by$. The latter can be obtained by applying this calculation recursively to the next block in the chain.\n\n% ------------------------------------------------------------------\n\\subsection{CNN modularity}\\label{s:modularity}\n% ------------------------------------------------------------------\n\nSections~\\ref{s:forward} and~\\ref{s:backward} suggests a modular programming interface for the implementation of CNN modules. Abstractly, we need two functionalities:\n\\begin{itemize}\n\\item {\\bf Forward messages:} Evaluation of the output $\\by=f(\\bx,\\bw)$ given input data $\\bx$ and parameters $\\bw$ (forward message).\n\\item {\\bf Backward messages:} Evaluation of the CNN derivative $dz/d\\bx$ and $dz/d\\bw$ with respect to the block input data $\\bx$ and parameters $\\bw$ given the block input data $\\bx$ and paramters $\\bw$ as well as the CNN derivative $dx/d\\by$ with respect to the block output data $\\by$.\n\\end{itemize}\n\n\n\n% ------------------------------------------------------------------\n\\section{Computational blocks}\\label{s:blocks}\n% ------------------------------------------------------------------\n\nThis section describes the individual computational block supported by the \\vlnn. The interface of a CNN computational block follows Section~\\ref{s:modularity}. The block can be evaluated as a MATLAB function \\verb!y = vl_nn<block>(x,w)! that takes as input arrays \\verb!x! and \\verb!w! representing the input data and parameters of the block and returns an array \\verb!y! as output. \\verb!x! and \\verb!y! are 4D real arrays packing $N$ maps or images, as discussed above, whereas \\verb!\\bw! may have an arbitrary shape.\n\nIn order to compute the block derivatives, the same function can take a third optional argument \\verb!dzdy! representing the derivative of the output of the network with respect to $\\by$ and returns the corresponding derivatives \\verb![dzdx,dzdw] = vl_nn<block>(x,w,dzdy)!. \\verb!dzdx!, \\verb!dzdy! and \\verb!dzdw! are array with the same dimension of \\verb!x!, \\verb!y! and \\verb!w! respectively, as discussed in Section~\\ref{s:backward}.\n\nA function syntax may differ slightly depending on the specifics of a block. For example, a function can take additional optional arguments, specified as a property-value list; it can take no parameters (e.g. a rectified linear unit), in which case \\verb!w! is omitted; it can take multiple inputs and parameters, in which there may be more than one \\verb!x!, \\verb!w!, \\verb!dzdx!, \\verb!dzdy! or \\verb!dzdw!. See the MATLAB inline help of each function for details on the syntax.\\footnote{In some cases it may be convenient to wrap these functions to obtain completely uniform and abstract interfaces to all block types. Writing such wrappers, if they are needed, is easy. The core functions, however, focus on providing a straightforward and obvious interface to each block.}\n\nThe rest of the section describes the blocks implemented in \\vlnn. The purpose is to describe the blocks analytically; refer to MATLAB inline help for further details on the API.\n\n% ------------------------------------------------------------------\n\\subsection{Convolution}\\label{s:convolution}\n% ------------------------------------------------------------------\n\nThe convolutional block is implemented by the function \\verb!vl_nnconv!. \\verb!y=vl_nnconv(x,f,b)! computes the convolution of the input map $\\bx$ with a bank of $K$ multi-dimensional filters $\\bff$ and biases $b$. Here\n\\[\n \\bx\\in\\real^{H \\times W \\times D}, \\quad\n \\bff\\in\\real^{H' \\times W' \\times D \\times K}, \\quad\n \\by\\in\\real^{H'' \\times W'' \\times K}, \\quad\n \\quad\n W'' = W - W' + 1,\n \\quad\n H'' = H - H' + 1,\n\\]\nFormally, the output  is given by\n\\[\ny_{i''j''k}\n=\nb_k\n+\n\\sum_{i'=1}^{H'}\n\\sum_{j'=1}^{W'}\n\\sum_{d=1}^D\nf_{i'j'd} \\times x_{i''+i',j''+j',d,k}.\n\\]\nThe call \\verb!vl_nnconv(x,f,[])! does not use the biases. Note that the function works with arbitrarily sized inputs and filters (as opposed to, for example, square images).\n\n\\paragraph{Output size, padding, and sampling stride.} The convolution operator can be adapted to account for image padding and subsampling. Suppose that the input image or map $\\bx$ has width $W$ and that the filter $\\bff$ has width $W' \\leq W$. Then there are \n\\[\n  W'' = W - W' + 1\n\\]\npossible translations of the filters in the horizontal direction such that the filter is entirely contained in the input $\\bx$. Hence, by default the filtered signal $\\by$ has width $W''$. However, \\verb!vl_nnconv! accepts a padding parameters $[P_t,P_b,P_l,P_r]$ whose effect is to virtually pad with zeros the signal $\\bx$ in the top, bottom, left, and right  spatial directions respectively. In this case, the output signal has width\n\\[\n  W'' = W + (P_l + P_r) - W' + 1.\n\\]\n\\verb!vl_nnconv! also accepts a stride parameter $(\\delta_w,\\delta_h)$ to subsample the output. In this case, if $j$ is the column index of the output signal $\\by$, its maximum value is given by:\n\\[\n(j-1)\\delta_w + W' \\leq W + (P_l+P_r).\n\\]\nHence the width of $\\by$ is given by\n\\[\nW'' = \\lfloor\n\\frac{W + P_l+P_r - W'}{\\delta_w}\n\\rfloor + 1\n\\]\nsamples. Similar relations apply to the signal heights $H,H'$ and $H''$.\n\n\\paragraph{Fully connected layers.} In other libraries, a \\emph{fully connected blocks or layers} are blocks where each output dimension linearly depends on all the input dimensions. \\vlnn does not distinguishes between fully connected layers and convolutional blocks. Instead, the former is a special case of the latter obtained when the output map $\\by$ has dimensions $W''=H''=1$. Internally, \\verb!vl_nnconv! handle this case more efficiently if possible.\n\n\\paragraph{Filter groups.} For additional flexibility, \\verb!vl_nnconv! allows to group input feature channels and apply to them different filter groups. To to do so, specify as input a bank  of $K$ filters $\\bff\\in\\real^{H'\\times W'\\times D'\\times K}$ such that $D'$ divides the number of input dimensions $D$. These are treated as $g=D/D'$ filter groups; the first group is applied to dimensions $d=1,\\dots,D'$ of the input $\\bx$; the second group to dimensions $d=D'+1,\\dots,2D'$ and so on. Note that the ouptut is still an array $\\by\\in\\real^{H''\\times W''\\times K}$.\n\nAn application of grouping is implementing the Krizhevsky and Hinton network~\\cite{krizhevsky12imagenet}, which uses two such streams. Another application is sum pooling; in the latter case, one can specify $D$ groups of $D'=1$ dimensional filters identical filters of value 1 (however, this is considerably slower than calling the dedicated pooling function as given in Section~\\ref{s:pooling}).\n\n\\paragraph{Matrix notation and derivations.} It is often convenient to express the convolution operation in matrix form. To this end, let $\\phi(\\bx)$ the {\\tt im2row} operator, extracting all $W' \\times H'$ patches from the map $\\bx$ and storing them as rows of a $(H''W'') \\times (H'W'D)$ matrix. Formally, this operator is given by:\n\\[\n   [\\phi(\\bx)]_{pq} \\underset{(i,j,d)=t(p,q)}{=} x_{ijd}\n\\]\nwhere the index mapping $(i,j,d) = t(p,q)$ is\n\\[\n i = i''+i'-1, \\quad\n j = j''+j'-1, \\quad\n p = i'' + H'' (j''-1), \\quad\n q = i' + H'(j'-1) + H'W' (d-1).\n\\]\nIt is also useful to define the ``transposed'' operator {\\tt row2im}:\n\\[\n   [\\phi^*(M)]_{ijd}\n   =\n   \\sum_{(p,q) \\in t^{-1}(i,j,d)}\n   M_{pq}.\n\\]\nNote that $\\phi$ and $\\phi^*$ are linear operators. Both can be expressed by a matrix $H\\in\\real^{(H''W''H'W'D) \\times(HWD)}$ such that\n\\[\n  \\vv(\\phi(\\bx)) = H \\vv(\\bx), \\qquad \n  \\vv(\\phi^*(M)) = H^\\top \\vv(M).\n\\]\nHence we obtain the following expression for the vectorized output (see~\\cite{kinghorn96integrals}):\n\\[\n \\vv\\by = \n \\vv\\left(\\phi(\\bx) F\\right)\n =\n \\begin{cases}\n (I \\otimes \\phi(\\bx)) \\vv F, & \\text{or, equivalently,} \\\\\n (F^\\top \\otimes I) \\vv \\phi(\\bx),\n \\end{cases}\n\\]\nwhere $F\\in\\mathbb{R}^{(H'W'D)\\times K}$ is the matrix obtained by reshaping the array $\\bff$ and $I$ is an identity matrix of suitable dimensions. This allows obtaining the following formulas for the derivatives:\n\\[\n\\frac{dz}{d(\\vv F)^\\top}\n=\n\\frac{dz}{d(\\vv\\by)^\\top}\n(I \\otimes \\phi(\\bx))\n= \\vv\\left[ \n\\phi(\\bx)^\\top \n\\frac{dz}{dY}\n\\right]^\\top\n\\]\nwhere $Y\\in\\real^{(H''W'')\\times K}$ is the matrix obtained by reshaping the array $\\by$. Likewise:\n\\[\n\\frac{dz}{d(\\vv \\bx)^\\top}\n=\n\\frac{dz}{d(\\vv\\by)^\\top}\n(F^\\top \\otimes I)\n\\frac{d\\vv \\phi(\\bx)}{d(\\vv \\bx)^\\top}\n=\n\\vv\\left[ \n\\frac{dz}{dY}\nF^\\top\n\\right]^\\top\nH\n\\]\nIn summary, after reshaping these terms we obtain the formulas:\n\\[\n\\boxed{\n\\vv\\by = \n \\vv\\left(\\phi(\\bx) F\\right),\n\\qquad\n\\frac{dz}{dF}\n=\n\\phi(\\bx)^\\top\\frac{d z}{d Y},\n\\qquad\n\\frac{d z}{d X}\n=\n\\phi^*\\left(\n\\frac{d z}{d Y}F^\\top\n\\right)\n}\n\\]\nwhere $X\\in\\real^{(H'W')\\times D}$ is the matrix obtained by reshaping $\\bx$. Notably, these expressions are used to implement the convolutional operator; while this may seem inefficient, it is instead a fast approach when the number of filters is large and it allows leveraging fast BLAS and GPU BLAS implementations.\n\n% ------------------------------------------------------------------\n\\subsection{Pooling}\\label{s:pooling}\n% ------------------------------------------------------------------\n\n\\verb!vl_nnpool! implements max and sum pooling. The \\emph{max pooling} operator computes the maximum response of each feature channel in a $H' \\times W'$ patch\n\\[\ny_{i''j''d} = \\max_{1\\leq i' \\leq H', 1 \\leq j' \\leq W'} x_{i''+i',j''+j',d}.\n\\]\nresulting in an output of size $\\by\\in\\real^{H''\\times W'' \\times D}$, similar to the convolution operator of Sectino~\\ref{s:convolution}. Sum-pooling computes the average of the values instead:\n\\[\ny_{i''j''d} = \\frac{1}{W'H'}\n\\sum_{1\\leq i' \\leq H', 1 \\leq j' \\leq W'} x_{i''+i',j''+j',d}.\n\\]\n\n\\paragraph{Padding and stride.} Similar to the convolution operator of Sect.~\\ref{s:convolution}, \\verb!vl_nnpool! supports padding the input; however, the effect is different from padding in the convolutional block as pooling regions straddling the image boundaries are cropped. For max pooling, this is equivalent to extending the input data with $-\\infty$; for sum pooling, this is similar to padding with zeros, but the normalization factor at the boundaries is smaller to account for the smaller integration area.\n\n\\paragraph{Matrix notation.} Since max pooling simply select for each output element an input element, the relation can be expressed in matrix form as\n$\n    \\vv\\by = S(\\bx) \\vv \\bx\n$\nfor a suitable selector matrix $S(\\bx)\\in\\{0,1\\}^{(H''W''D) \\times (HWD)}$. The derivatives can the be written as:\n$\n\\frac{d z}{d (\\vv \\bx)^\\top}\n=\n\\frac{d z}{d (\\vv \\by)^\\top}\nS(\\bx),\n$\nfor all but a null set of points, where the operator is not differentiable (this usually does not pose problems in optimization by stochastic gradient). For max-pooling, similar relations exists with two differences: $S$ does not depend on the input $\\bx$ and it is not binary, in order to account for the normalization factors. In summary, we have the expressions:\n\\begin{equation}\\label{e:max-mat}\n\\boxed{\n\\vv\\by = S(\\bx) \\vv \\bx,\n\\qquad\n\\frac{d z}{d \\vv \\bx}\n=\nS(\\bx)^\\top\n\\frac{d z}{d \\vv \\by}.\n}\n\\end{equation}\n\n% ------------------------------------------------------------------\n\\subsection{ReLU}\\label{s:relu}\n% ------------------------------------------------------------------\n\n\\verb!vl_nnrelu! computes the \\emph{Rectified Linear Unit} (ReLU):\n\\[\n y_{ijd} = \\max\\{0, x_{ijd}\\}.\n\\]\n\n\\paragraph{Matrix notation.} With matrix notation, we can express the ReLU as\n\\[\n\\boxed{\n\\vv\\by = \\diag\\bs \\vv \\bx,\n\\qquad\n\\frac{d z}{d \\vv \\bx}\n=\n\\diag\\bs\n\\frac{d z}{d \\vv \\by}\n}\n\\]\nwhere $\\bs = [\\vv \\bx > 0] \\in\\{0,1\\}^{HWD}$ is an indicator vector.\n\n% ------------------------------------------------------------------\n\\subsection{Normalization}\\label{s:normalization}\n% ------------------------------------------------------------------\n\n\\verb!vl_nnnormalize! implements a cross-channel normalization operator. Normalization applied independently at each spatial location and groups of channels to get:\n\\[\n y_{ijk} = x_{ijk} \\left( \\kappa + \\alpha \\sum_{t\\in G(k)} x_{ijt}^2 \\right)^{-\\beta},\n\\]\nwhere, for each output channel $k$, $G(k) \\subset \\{1, 2, \\dots, D\\}$ is a corresponding subset of input channels. Note that input $\\bx$ and output $\\by$ have the same dimensions. Note also that the operator is applied across feature channels in a convolutional manner at all spatial locations.\n\n\\paragraph{Implementation details.} The derivative is easily computed as:\n\\[\n\\frac{dz}{d x_{ijd}}\n=\n\\frac{dz}{d y_{ijd}}\nL(i,j,d|\\bx)^{-\\beta}\n-2\\alpha\\beta x_{ijd}\n\\sum_{k:d\\in G(k)}\n\\frac{dz}{d y_{ijk}}\nL(i,j,k|\\bx)^{-\\beta-1} x_{ijk} \n\\]\nwhere\n\\[\n L(i,j,k|\\bx) = \\kappa + \\alpha \\sum_{t\\in G(k)} x_{ijt}^2.\n\\]\n\n% ------------------------------------------------------------------\n\\subsection{Softmax}\\label{s:softmax}\n% ------------------------------------------------------------------\n\n\\verb!vl_softmax! computes the softmax operator:\n\\[\n y_{ijk} = \\frac{e^{x_{ijk}}}{\\sum_{t=1}^D e^{x_{ijt}}}.\n\\]\nNote that the operator is applied across feature channels and in a convolutional manner at all spatial locations.\n\n\\paragraph{Implementation details.} Care must be taken in evaluating the exponential in order to avoid underflow or overflow. The simplest way to do so is to divide from numerator and denominator by the maximum value:\n\\[\n y_{ijk} = \\frac{e^{x_{ijk} - \\max_d x_{ijd}}}{\\sum_{t=1}^D e^{x_{ijt}- \\max_d x_{ijd}}}.\n\\]\nThe derivative is given by:\n\\[\n\\frac{dz}{d x_{ijd}}\n=\n\\sum_{k}\n\\frac{dz}{d y_{ijk}}\n\\left(\ne^{x_{ijd}} L(\\bx)^{-1} \\delta_{\\{k=d\\}}\n-\ne^{x_{ijd}}\ne^{x_{ijk}} L(\\bx)^{-2}\n\\right),\n\\quad\nL(\\bx) = \\sum_{t=1}^D e^{x_{ijt}}.\n\\]\nSimplifying:\n\\[\n\\frac{dz}{d x_{ijd}}\n=\ny_{ijd} \n\\left(\n\\frac{dz}{d y_{ijd}}\n-\n\\sum_{k=1}^K\n\\frac{dz}{d y_{ijk}} y_{ijk}.\n\\right).\n\\]\nIn matrix for:\n\\[\n  \\frac{dz}{dX} = Y \\odot \\left(\\frac{dz}{dY} \n  - \\left(\\frac{dz}{dY} \\odot Y\\right) \\bone\\bone^\\top\\right)\n\\]\nwhere $X,Y\\in\\real^{HW\\times D}$ are the matrices obtained by reshaping the arrays\n$\\bx$ and $\\by$. Note that the numerical implementation of this expression is straightforward once the output $Y$ has been computed with the caveats above.\n\n% ------------------------------------------------------------------\n\\subsection{Log-loss}\\label{s:loss}\n% ------------------------------------------------------------------\n\n\\verb!vl_logloss! computes the \\emph{logarithmic loss}\n\\[\n y = \\ell(\\bx,c) = - \\sum_{ij} \\log x_{ijc}\n\\]\nwhere $c \\in \\{1,2,\\dots,D\\}$ is the ground-truth class. Note that the operator is applied across input channels in a convolutional manner, summing the loss computed at each spatial location into a single scalar. \n\n\\paragraph{Implementation details.} The derivative is\n\\[\n\\frac{dz}{dx_{ijd}} = - \\frac{dz}{dy} \\frac{1}{x_{ijc}} \\delta_{\\{d = c\\}}.\n\\]\n\n% ------------------------------------------------------------------\n\\subsection{Softmax log-loss}\\label{s:sfloss}\n% ------------------------------------------------------------------\n\n\\verb!vl_softmaxloss! combines the softmax layer and the log-loss into one step for improved numerical stability. It computes\n\\[\ny = - \\sum_{ij} \\left(\nx_{ijc} - \\log \\sum_{d=1}^D e^{x_{ijd}}\n\\right)\n\\]\nwhere $c$ is the ground-truth class.\n\n\\paragraph{Implementation details.} The derivative is given by\n\\[\n\\frac{dz}{dx_{ijd}} \n= - \\frac{dz}{dy} \\left(\\delta_{d=c} - y_{ijc}\\right)\n\\]\nwhere $y_{ijc}$ is the output of the softmax layer. In matrix form:\n\\[\n\\frac{dz}{dX} \n= - \\frac{dz}{dy} \\left(\\bone^\\top \\bfe_c - Y\\right)\n\\]\nwhere $X,Y\\in\\real^{HW\\times D}$ are the matrices obtained by reshaping the arrays\n$\\bx$ and $\\by$ and $\\bfe_c$ is the indicator vector of class $c$.\n\n% ------------------------------------------------------------------\n\\section{Network wrappers and examples}\\label{s:wrappers}\n% ------------------------------------------------------------------\n\nIt is easy enough to combine the computational blocks of Sect.~\\ref{s:blocks} in any network DAG by writing a corresponding MATLAB script. Nevertheless, \\vlnn provides a simple wrapper for the common case of a linear chain. This is implemented by the \\verb!vl_simplenn! and \\verb!vl_simplenn_move! functions.\n\n\\verb!vl_simplenn! takes as input a structure \\verb!net! representing the CNN as well as input \\verb!x! and potentially output derivatives \\verb!dzdy!, depending on the mode of operation. Please refer to the inline help of the \\verb!vl_simplenn! function for details on the input and output formats. In fact, the implementation of \\verb!vl_simplenn! is a good example of how the basic neural net building block can be used together and can serve as a basis for more complex implementations.\n\n% ------------------------------------------------------------------\n\\subsection{Pre-trained models}\n% ------------------------------------------------------------------\n\n\\verb!vl_simplenn! is easy to use with pre-trained models (see the homepage to download some). For example, the following code downloads a model pre-trained on the ImageNet data and applies it to one of MATLAB stock images:\n\\begin{lstlisting}[language=Matlab]\n% setup MatConvNet in MATLAB\nrun matlab/vl_setupnn\n\n% download a pre-trained CNN from the web\nurlwrite(...\n  'http://www.vlfeat.org/sandbox-matconvnet/models/imagenet-vgg-f.mat', ...\n  'imagenet-vgg-f.mat') ;\nnet = load('imagenet-vgg-f.mat') ;\n\n% obtain and preprocess an image\nim = imread('peppers.png') ;\nim_ = single(im) ; % note: 255 range\nim_ = imresize(im_, net.normalization.imageSize(1:2)) ;\nim_ = im_ - net.normalization.averageImage ;\n\\end{lstlisting}\nNote that the image should be preprocessed before running the network. While preprocessing specifics depend on the model, the pre-trained model contain a \\verb!net.normalization! field that describes the type of preprocessing that is expected. Note in particular that this network takes images of a fixed size as input and requires removing the mean; also, image intensities are normalized in the range [0,255].\n\nThe next step is running the CNN. This will return a \\verb!res! structure with the output of the network layers:\n\\begin{lstlisting}[language=Matlab]\n% run the CNN\nres = vl_simplenn(net, im_) ;\n\\end{lstlisting}\n\nThe output of the last layer can be used to classify the image. The class names are contained in the \\verb!net! structure for convenience:\n\\begin{lstlisting}[language=Matlab]\n% show the classification result\nscores = squeeze(gather(res(end).x)) ;\n[bestScore, best] = max(scores) ;\nfigure(1) ; clf ; imagesc(im) ;\ntitle(sprintf('%s (%d), score %.3f',...\nnet.classes.description{best}, best, bestScore)) ;\n\\end{lstlisting}\n\nNote that several extensions are possible. First, images can be cropped rather than rescaled. Second, multiple crops can be fed to the network and results averaged, usually for improved results. Third, the output of the network can be used as generic features for image encoding.\n\n% ------------------------------------------------------------------\n\\subsection{Learning models}\n% ------------------------------------------------------------------\n\nAs \\vlnn can compute derivatives of the CNN using back-propagation, it is simple to implement learning algorithms with it. A basic implementation of stochastic gradient descent is therefore straightforward. Example code is provided in \\verb!examples/cnn_train!. This code is flexible enough to allow training on NMINST, CIFAR, ImageNet, and probably many other datasets. Corresponding examples are provided in the \\verb!examples/! directory.\n\n% ------------------------------------------------------------------\n\\subsection{Running large scale experiments}\n% ------------------------------------------------------------------\n\nFor large scale experiments, such as learning a network for ImageNet, a NVIDIA GPU (at least 6GB of memory) and adequate CPU and disk speeds are highly recommended. For example, to train on ImageNet, we suggest the following:\n\\begin{itemize}\n\\item Download the ImageNet data~\\url{http://www.image-net.org/challenges/LSVRC}. Install it somewhere and link to it from \\verb!data/imagenet12!\n\\item Consider preprocessing the data to convert all images to have an height 256 pixels. This can be done with the supplied \\verb!utils/preprocess-imagenet.sh! script. In this manner, training will not have to resize the images every time. Do not forget to point the training code to the pre-processed data.\n\\item Consider copying the dataset in to a RAM disk (provided that you have enough memory!) for faster access. Do not forget to point the training code to this copy.\n\\item Compile \\vlnn with GPU support. See the homepage for instructions.\n\\item Compile also the \\verb!vl_imreadjpeg! function. Currently, reading JPEG images from disk is a bottleneck and this function can partially alleviate this problem (in the future it should remove the bottleneck almost entirely). See the homepage for instructions.\n\\end{itemize}\n\nOnce your setup is ready, you should be able to run \\verb!examples/cnn_imagenet! (edit the file and change any flag as needed to enable GPU support and image pre-fetching on multiple threads).\n\nIf all goes well, you should expect to be able to train with 200-300 images/sec.\n\n% ------------------------------------------------------------------\n\\section{About \\vlnn}\n% ------------------------------------------------------------------\n\n\\vlnn main features are:\n\\begin{itemize}\n\\item \\emph{Flexibility.} Neural network layers are implemented in a straightforward manner, often directly in MATLAB code, so that they are easy to modify, extend, or integrate with new ones.\n\\item \\emph{Power.} The implementation can run the latest models such as Krizhevsky~\\textit{et al.}~\\cite{krizhevsky12imagenet}, including the DeCAF and Caffe variants, and variants from the Oxford Visual Geometry Group. Pre-learned features for different tasks can be easily downloaded.\n\\item \\emph{Efficiency.} The implementation is quite efficient, supporting both CPU and GPU computation (in the latest versions of MALTAB).\n\\item \\emph{Self contained.} The implementation is fully self-contained, requiring only MATLAB and a compatible C/C++ compiler to work (GPU code requires the freely-available CUDA DevKit). Several fully-functional image classification examples are included.\\end{itemize}\n\n\\paragraph{Relation to other CNN implementations.} There are many other open-source CNN implementations. \\vlnn borrows its convolution algorithms from Caffe (and is in fact capable of running most of Caffe's models). Caffe is a \\cpp framework using a custom CNN definition language based on Google Protocol Buffers. Both \\vlnn and Caffe are predated by Cuda-Convnet~\\cite{krizhevsky12imagenet}, a \\cpp-based project that allows defining a CNN architectures using configuration files. While Caffe and Cuda-Convnet can be somewhat faster than \\vlnn, the latter exposes individual CNN building blocks as MATLAB functions, as well as integrating with the native MATLAB GPU support, which makes it very convenient for fast prototyping. The DeepLearningToolbox~\\cite{deepltbx12} is a MATLAB toolbox implementing, among others, CNNs, but it does not seem to have been tested on large scale problems. While \\vlnn specialises on CNNs and computer vision applications, there are several general-purpose machine learning frameworks which include CNN support, but none of them interfaces natively with MATLAB. For example, the Torch7 toolbox~\\cite{collobert2011torch7} uses Lua and Theano~\\cite{bergstra2010} uses Python.\n\n% ------------------------------------------------------------------\n\\subsection{Acknowledgments}\\label{s:ack}\n% ------------------------------------------------------------------\n\nThe implementation of several CNN computations in this library are inspired by the Caffe library~\\cite{jia13caffe} (however, Caffe is \\emph{not} a dependency). Several of the example networks have been trained by Karen Simonyan as part of~\\cite{chatfield14return}.\n\nWe kindly thank NVIDIA for suppling GPUs used in the creation of this software.\n\n% ------------------------------------------------------------------\n\\bibliographystyle{plain}\n\\bibliography{references}\n\\end{document}\n% ------------------------------------------------------------------\n\n\n\n", "meta": {"hexsha": "d8f47652c361c3a9a0eb0b1bfb8dcb4cbbd60e85", "size": 40311, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "external/matconvnet/doc/matconvnet-manual.tex", "max_stars_repo_name": "chemanqiang/ALRVT", "max_stars_repo_head_hexsha": "522446d6917a3e0deb6da0fb9c7306667454a811", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2016-10-26T02:46:05.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-31T12:21:30.000Z", "max_issues_repo_path": "TrackerMCCT/matconvnet/doc/matconvnet-manual.tex", "max_issues_repo_name": "JHvisionchen/MCCT-matlab", "max_issues_repo_head_hexsha": "6eb2dc5bd675b32f016cbbf698accd28ee5708a4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TrackerMCCT/matconvnet/doc/matconvnet-manual.tex", "max_forks_repo_name": "JHvisionchen/MCCT-matlab", "max_forks_repo_head_hexsha": "6eb2dc5bd675b32f016cbbf698accd28ee5708a4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-12-15T09:35:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-08T02:07:19.000Z", "avg_line_length": 59.6316568047, "max_line_length": 1209, "alphanum_fraction": 0.674704175, "num_tokens": 10967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.5273165233795672, "lm_q1q2_score": 0.3301656316975745}}
{"text": "\n\n    \\filetitle{!log\\_variables}{List of log-linearised variables}{modellang/logvariables}\n\n\t\\paragraph{Syntax}\\label{syntax}\n\n\\begin{verbatim}\n!log_variables\n    VariableName, VariableName, \n    VariableName, ...\n\\end{verbatim}\n\n\\paragraph{Syntax with inverted list}\\label{syntax-with-inverted-list}\n\n\\begin{verbatim}\n!log_variables\n    !all_but\n    VariableName, VariableName, \n    VariableName, ...\n\\end{verbatim}\n\n\\paragraph{Syntax with regular\nexpression(s)}\\label{syntax-with-regular-expressions}\n\n\\begin{verbatim}\n!log_variables\n    VariableName, VariableName, \n    VariableName, ...\n    <REGEXP>, <REGEXP>, ...\n\\end{verbatim}\n\n\\paragraph{Description}\\label{description}\n\nList all log-variables under this headings. Only measurement or\ntransition variables can be declared as log-variables.\n\nIn non-linear models, all variables are linearised around the steady\nstate or a balanced-growth path. If you wish to log-linearise some of\nthem instead, put them on a \\texttt{!log\\_variables} list. You can also\nuse the \\texttt{!all\\_but} keyword to indicate an inverse list: all\nvariables will be log-linearised except those listed.\n\nTo create the list of log-variables, you can also use regular\nexpressions, each enlosed in a pair of angle brackets,\n\\texttt{\\textless{}} and \\texttt{\\textgreater{}}. All measurement and\ntransition variables whose names match one of the regular expressions\nwill be declared as log-variables. See also help on regular expressions\nin the Matlab documentation.\n\n\\paragraph{Example}\\label{example}\n\nThe following block of code will cause the variables \\texttt{Y},\n\\texttt{C}, \\texttt{I}, and \\texttt{K} to be declared as log-variables,\nand hence log-linearised in the model solution, while \\texttt{r} and\n\\texttt{pie} will be linearised:\n\n\\begin{verbatim}\n!transition_variables\n    Y, C, I, K, r, pie\n\n!log_variables\n    Y, C, I, K\n\\end{verbatim}\n\nYou can do the same job by writing\n\n\\begin{verbatim}\n!transition_variables\n    Y, C, I, K, r, pie\n\n!log_variables\n    !all_but\n    r, pie\n\\end{verbatim}\n\n\\paragraph{Example}\\label{example-1}\n\nWe again achieve the same result as above, but now using a regular\nexpression.\n\n\\begin{verbatim}\n!transition_variables\n    Y, C, I, K, r, pie\n\n!log_variables\n    <[A-Z]\\w*>\n\\end{verbatim}\n\nThe regular expression \\texttt{{[}A-Z{]}\\textbackslash{}w*} selects all\nvariables whose names start with an upper-case letter. Hence, again the\nvariables \\texttt{Y}, \\texttt{C}, \\texttt{I}, and \\texttt{K} will be\ndeclared as log-variables.\n\n\n", "meta": {"hexsha": "c5150eeff24e8f03f3a58dd3915d90282bcbf08f", "size": 2501, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "-help/modellang/logvariables.tex", "max_stars_repo_name": "OGResearch/IRIS-Toolbox-For-Octave", "max_stars_repo_head_hexsha": "682ea1960229dc701e446137623b120688953cef", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-12-06T13:38:38.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-06T13:38:38.000Z", "max_issues_repo_path": "-help/modellang/logvariables.tex", "max_issues_repo_name": "OGResearch/IRIS-Toolbox-For-Octave", "max_issues_repo_head_hexsha": "682ea1960229dc701e446137623b120688953cef", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-03-28T08:13:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-02T10:40:25.000Z", "max_forks_repo_path": "-help/modellang/logvariables.tex", "max_forks_repo_name": "OGResearch/IRIS-Toolbox-For-Octave", "max_forks_repo_head_hexsha": "682ea1960229dc701e446137623b120688953cef", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-17T07:06:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T07:06:39.000Z", "avg_line_length": 26.3263157895, "max_line_length": 89, "alphanum_fraction": 0.7461015594, "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6548947357776796, "lm_q1q2_score": 0.33000549840538457}}
{"text": "\\documentclass[landscape,twocolumn,letterpaper,9pt,reqno]{article}\n\n\\usepackage{lscape,fancyhdr}\n\n\\usepackage{hyperref}\n\n\\pagestyle{fancy}\n\n\\usepackage{amsmath,epsfig,subfigure,amsthm,amsfonts,epsf,psfrag,rotating,setspace,bm}\n\n\\usepackage{verbatim,color} % Allow text colors}\n\n\\setlength{\\oddsidemargin}{-0.4in}\t\t% default=0in\n\\setlength\\evensidemargin{-0.4in}\n\n\\setlength{\\textwidth}{9.8in}\t\t% default=9in\n\n\\setlength{\\columnsep}{0.5in}\t\t% default=10pt\n\n\\setlength{\\columnseprule}{0pt}\t\t% default=0pt (no line)\n\n\n\\setlength{\\textheight}{7.0in}\t\t% default=5.15in\n\n\\setlength{\\topmargin}{-0.75in}\t\t% default=0.20in\n\n\\setlength{\\headsep}{0.25in}\t\t% default=0.35in\n\n\\setlength{\\parskip}{1.2ex}\n\n\\setlength{\\parindent}{0mm}\n\n\\lhead{Course EPIB607: Regression 1 - Q\\&A}\n\\rhead{jh,sb \\ \\ \\ v. 2018.11.08}\n\n\\begin{document}\n\n\\section{When to use the log formula instead of the regression formula?}\n\n$\\log$ is primarily used when you're interested in the ratio of two parameters. For example, $$\\theta = \\frac{\\mu_{south}}{\\mu_{north}}.$$ Taking the $\\log$ of both sides, we get $$\\log(\\theta) = \\log(\\mu_{south}) - \\log(\\mu_{north}).$$ This form is much easier to deal with because we can ''trick'' any regression function to run this model. \n\n\\section{Are there differences in regression approaches for $\\mu$, $\\pi$ and $\\lambda$ or is it just a difference in the scales?}\n\nYes. We can use the linear model for $\\mu$. However, because both $\\pi$ and $\\lambda$ have a restricted domain ($\\pi$ must be between 0 and 1, $\\lambda$ must be greater than 0), care must be taken as to not obtain nonsensical values. In general we use logistic regression for $\\pi$ and poisson regression for $\\lambda$. These involve transformations of the original parameter so that the domain ranges from $-\\infty$ to $+\\infty$. \n\t\n\\section{Please explain how to assign the baseline with north and south}\t\n\nThe baseline is arbitrary. Usually the category of interest is chosen as the ``non-reference'' category. \n\n\\section{Not clear why we are doing both a t-test and a regression analysis to test for mean difference? In this case a t test seems to be the appropriate test, are we just applying it to regression to think about it conceptually?}\n\nThe two-sample t-test is a special case of regression when the only determinant of the parameter is the group. Regression is a much more general approach that allows you to include more determinants (i.e. confounders). The t-test can only handle a single determinant, which is often rarely the case in observational health research. \n\n\\section{Why is a t-test used to conduct inference for regression, but a z-test for the CI?}\n\nt procedures are technically correct, but often we have a large enough sample to assume we have a good estimate of $\\sigma$, so that we can use the z procedure. \n\n\n\\section{Was what we were doing today the same as least squares regression? If not, how was it different?}\n\nToday was about writing regression equations with parameters. We cheated by assuming the truth was known. Least-squares is a method to estimate the parameters with data. \n\n\\section{Is the lm function in R just for difference? How do we adapt it for ratios?}\n\n\\texttt{lm} is just for the difference. We must use the \\texttt{glm} function and specify the argument \\texttt{family=gaussian(link=log)} to adapt it for ratios. \n\t\n\\end{document}", "meta": {"hexsha": "27dc89e1bf92f333ccfe1584c149fbeb2d154358", "size": 3357, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "QNA/EPIB607_Regression1_QNA.tex", "max_stars_repo_name": "ly129/EPIB607", "max_stars_repo_head_hexsha": "ac2f917bc064f8028a875766af847114cd306396", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "QNA/EPIB607_Regression1_QNA.tex", "max_issues_repo_name": "ly129/EPIB607", "max_issues_repo_head_hexsha": "ac2f917bc064f8028a875766af847114cd306396", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QNA/EPIB607_Regression1_QNA.tex", "max_forks_repo_name": "ly129/EPIB607", "max_forks_repo_head_hexsha": "ac2f917bc064f8028a875766af847114cd306396", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-25T21:19:06.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-25T21:19:06.000Z", "avg_line_length": 50.1044776119, "max_line_length": 431, "alphanum_fraction": 0.7521596664, "num_tokens": 918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6548947223065754, "lm_q1q2_score": 0.330005491617212}}
{"text": "\\documentclass[envcountsame]{cls/cccg15}\n\\usepackage{graphicx}\n\n\\usepackage{amssymb,amsmath}\n\\usepackage[mathscr]{euscript}\n\n\\usepackage{caption,subcaption}\n\\usepackage{booktabs,multirow}\n\n\\usepackage{algorithm}\n\\usepackage[noend]{algorithmic}\n\\usepackage{tikz}\n\\usetikzlibrary{arrows}\n\n\\usepackage{cleveref}\n\n\n%------------------------ Paper Notations -----------------------------\n\n\\newcommand{\\rc}{r}\n\\newcommand{\\cp}{c_p}\n\\newcommand{\\dz}{(d + 1)(z + 1)}\n\\newcommand{\\Buffer}{\\ensuremath{\\text{Buffer}}}\n\n\\renewcommand{\\O}{\\ensuremath{{O}}} \n\\DeclareMathOperator*{\\argmin}{arg\\,min}\n\\newcommand{\\nd}{\\nobreakdash-}\n\n\n%----------------------- Page Style -----------------------------------------\n\n\\renewcommand{\\arraystretch}{1.3}\n\n%----------------------- Environments --------------------------\n\n\\newtheorem{problem}{Problem}\n\\newtheorem{definition}{Definition}\n\\newtheorem{claim}{Claim}\n\n\n%------------------------ Cleveref Labels -----------------------------\n\n\\Crefname{table}{Table}{Tables}\n\\Crefname{obs}{Observation}{Observations}\n\\Crefname{cor}{Corollary}{Corollaries}\n\\Crefname{algorithm}{Algorithm}{Algorithms}\n\\Crefname{lemma}{Lemma}{Lemmas}\n\n\n%------------------------ Algorithm -----------------------------\n\n\\newcommand{\\textproc}{\\textsc}\n\\newcommand{\\Call}[2]{\\textsc{#1}(#2)}\n\\renewcommand{\\algorithmicforall}{{\\bf for each}}\n\\renewcommand{\\algorithmiccomment}[1]{\\quad $\\vartriangleright$ #1}\n\n%-------------------------- Notations ------------------------------------\n\n\\newcommand{\\IN}{\\ensuremath{\\mathbb{N}}} \n\\newcommand{\\IZ}{\\ensuremath{\\mathbb{Z}}} \n\\newcommand{\\IQ}{\\ensuremath{\\mathbb{Q}}} \n\\newcommand{\\IR}{\\ensuremath{\\mathbb{R}}} \n\\newcommand{\\IC}{\\ensuremath{\\mathbb{C}}} \n\n\n\\newcommand{\\set}[1]{\\left\\{ #1 \\right\\}}\n\\newcommand{\\seq}[1]{\\left< #1 \\right>}\n\\newcommand{\\ceil}[1]{\\left\\lceil{#1}\\right\\rceil}\n\\newcommand{\\floor}[1]{\\left\\lfloor{#1}\\right\\rfloor}\n\\newcommand{\\card}[1]{\\left|{#1}\\right|}\n\\newcommand{\\len}[1]{\\|{#1}\\|}\n\\newcommand{\\radius}[1]{\\frac{2}{\\alpha} \\len{c_1 #1}}\n\\newcommand{\\setcomp}[1]{\\overline{#1}}\n\\newcommand{\\provided}{\\,|\\,}\n\n\\newcommand{\\poly}{\\mathop{\\mathrm{poly}}}\n\\newcommand{\\polylog}{\\mathop{\\mathrm{\\scriptsize polylog}}}\n\\newcommand{\\lcm}{\\mathop{\\mathrm{lcm}}}\n\n\\newcommand{\\lee}{\\leqslant}\n\\newcommand{\\gee}{\\geqslant}\n\\renewcommand{\\leq}{\\lee}\n\\renewcommand{\\le}{\\lee}\n\\renewcommand{\\geq}{\\gee}\n\\renewcommand{\\ge}{\\gee}\n\\newcommand{\\lei}{\\prec}\n\n\\newcommand{\\OPT}{\\ensuremath{\\mathop{\\mathrm{OPT}}}}\n\\newcommand{\\APX}{\\ensuremath{\\text{\\sc APX}}}\n\\newcommand{\\opt}{\\ensuremath{\\mbox{\\tt opt}}}\n\\newcommand{\\apx}{\\ensuremath{\\mbox{\\tt apx}}}\n\n\\newcommand{\\eps}{\\varepsilon}\n\\newcommand{\\bslash}{\\!\\setminus\\!}\n\\newcommand{\\bigOmega}{{\\rm\\Omega}}\n\\newcommand{\\etal}{{\\em et~al.\\/}}\n\\newcommand{\\REM}[1]{}\n\\newcommand{\\qed}{}\n\\newcommand{\\backspace}{\\vspace{-3em}\\\\}\n\n\n\\newcommand{\\linprog}[6]{\n  \\begin{alignat}{2}\n    \\text{#1}  \\quad & #2\\\\\n    \\text{s.t.}  \\quad & #3 & \\qquad #4 \\notag\\\\\n                     & #5 & \\qquad #6 \\notag\n  \\end{alignat}}\n  \n\\newcommand*\\samethanks[1][\\value{footnote}]{\\footnotemark[#1]}\n\n\n%----------------------- Title -----------------------------------------\n\n\\title{A Streaming Algorithm for 2-Center with Outliers in High Dimensions}\n\n\\author{Behnam~Hatami\\thanks{Department of Computer Engineering, \n\tSharif University of Technology, Tehran, Iran.\n\t{\\tt bhatami@ce.sharif.edu}}\n\t\\and \n\tHamid~Zarrabi-Zadeh\\thanks{Department of Computer Engineering, \n\tSharif University of Technology, Tehran, Iran.\n\t{\\tt zarrabi@sharif.edu}}\n}\n\n\n%------------------------------ Text -------------------------------------\n\n\\begin{document}\n\n\\maketitle\n\\pagestyle{plain}\n\n% ---------------------- Abstract --------------------------------------\n\n\\begin{abstract}\nWe study the 2-center problem with outliers in high-dimensional data streams. \nGiven a stream of points in arbitrary $d$ dimensions, the goal is to find two congruent balls \nof minimum radius covering all but $z$ points. \nWe provide a $(1.8+\\eps)$-approximation streaming algorithm for the problem, \nimproving upon the previous $(4 + \\eps)$-approximation algorithm available for the problem.\nThe space complexity and update time of our algorithm is $\\poly(d, z, {1 \\over \\eps})$,\nindependent of the size of the stream.\n\\end{abstract}\n\n% ---------------------- Introduction ---------------------------------\n\n\\section{Introduction}\nThe $k$-center problem---covering a set of points \nusing $k$ congruent balls of minimum radius---is a fundamental problem,\narising in many applications \nsuch as data mining, machine learning, statistics, and image processing.\nIn real-world applications, where input data is often noisy, \nit is very important to consider outliers, \nas even a small number of outliers can greatly affect the quality of the solution.\nThe $k$-center problem is particularly very sensitive to outliers,\nand even a constant number of outliers can increase the radius of the $k$-center unboundedly.\nTherefore, it is natural to consider the following generalization of\nthe the $k$-center problem: % which we call \\emph{$k$-center with $z$ outliers}:\ngiven a set $P$ of $n$ points in arbitrary $d$ dimensions\nand a bound $z$ on the number of outliers,\nfind $k$ congruent balls of minimum radius \nto cover at least $n - z$ points of $P$.\nSee \\Cref{fig:definition} for an example.\n%for $z$ being the number of outliers.\n%One of $k$-center problem variants is $k$-center with $z$-outlier which finds $k$ congruent balls with minimum radius covering all but $z$ points of a point set. \n\nIn this paper, we focus on the \\emph{data stream} model of computation\nwhere only a single pass over input is allowed,\nand we have only a limited amount of working space available.\n%which is typically sublinear in the input size.\nThis model is in particular useful for processing large data sets,\nas it does not require the entire data set to be stored in memory.\n\n%In this model, input data arrives as a sequence over time, \n%%only one pass over the input data is allowed, \n%and we have only a limited amount of working space available, \n%which is typically sublinear in the input size.\n%and thus, we cannot keep the entire data set in memory.\n%This makes designing streaming algorithms very challenging,\n%%as we can have only one pass over the input data, \n%%and must decide on the fly which data to keep in our limited working space,\n%as we cannot keep the entire data set in memory,\n%and must be still able to produce a solution comparable to \n%that of an offline algorithm that has unlimited access to the whole data set.\n\nThe Euclidean $k$-center problem has been extensively studied in the literature.\n%There is a considerable amount of work on the geometric $k$-center problem.\nIf $k$ is part of the input,\nthe problem in known to be NP-hard in two and more dimensions~\\cite{fowler1981optimal},\nand is even hard to approximate to within a factor better than $1.82$, \nunless P$\\,=\\,$NP~\\cite{feder1988optimal}.\nFactor-2 approximation algorithms are available for the problem \nin any dimension~\\cite{gonzalez1985clustering,feder1988optimal}.\n%The $k$-center problem without outliers (i.e., $z=0$) in general (Euclidean) space can not be approximated with a smaller factor than $2$ ($1.822$), unless $\\mathbf{P}=\\mathbf{NP}$~\\cite{bern1996approximation}.\n%Gonzalez~\\cite{gonzalez1985clustering} showed a $2$-approximation algorithm for general case of the problem.\nFor small $k$ and $d$, %there are more efficient algorithms.\nbetter solutions are available.\nThe 1-center problem in fixed dimensions is known to be LP-type \nand can be solved in $O(n)$ time~\\cite{chazelle1996linear}.\nFor 2-center in the plane, the current best algorithm\nruns in $\\O(n \\log^2 n \\log^2 \\log n)$ time~\\cite{chan1999more}.\n\n\nFor $k$-center with outliers, Charikar~\\etal~\\cite{charikar2001algorithms} \ngave the first algorithm with an approximation factor of $3$, \nwhich works in any dimension.\n%which is improvable to 3, if all candidate center points can be enumerated.\n%depending on whether the candidate center points can be enumerated or not, respectively.\nBetter results are known for small $k$ in the plane.\nThe 1-center problem with $z$ outliers in the plane can be solved \nin $\\O(n \\log n + z^{3} n^{\\eps})$ time, for any $\\eps > 0$, \nusing Matou{\\v{s}}ek's framework~\\cite{matouvsek1995geometric}.\nAgarwal~\\cite{agarwal2008efficient} gave a randomized \n$\\O(n z^{7} \\log^3 z)$-time algorithm for 2-center with $z$ outliers in the plane.\n\n\\begin{figure}[t]\n\t\\centering\n\t\\includegraphics[width=13em]{figs/definition}\n\t\\caption{An example of $2$-center with 6 outliers.}\n\t\\label{fig:definition}\n\t\\vspace{-.5em}\n\\end{figure}\n\nIn the streaming model, McCutchen~\\etal~\\cite{mccutchen2008streaming} \nand Guha~\\cite{guha2009tight} presented algorithms to maintain $(2+\\eps)$-approximation \nto the $k$-center problem in %in any metric space using \n$\\O(\\frac{kd}{\\eps} \\log \\frac{1}{\\eps})$ space.\nFor $k=1$, %better algorithms are known. % in high dimensions.\n%a $1.5$-approximation in high dimensions was presented by Zarrabi-Zadeh and Chan~\\cite{zarrabi2006simple}.\na factor-$((1+\\sqrt{3})/{2})$ approximation \nwas presented by Agarwal and Sharathkumar~\\cite{agarwal2010streaming} \nin high dimensions, using $O(d)$ space. \nThe approximation factor was later improved \n%to $(1+\\sqrt{3})/{2}$ by Agarwal and Sharathkumar~\\cite{agarwal2010streaming} \nto $1.22$ by Chan and Pathak~\\cite{chan2014streaming}.\n%If the dimension is fixed, a $(1 + \\eps)$-approximation\n%can be maintained in $\\O({k}/{\\eps^{((d-1)/2)}})$ space \n%using the notion of core-sets~\\cite{zarrabi2008core}., \n%Ahn~\\etal~\\cite{ahn2014computing} gave a $(2+\\eps)$-approximation algorithm using $\\O(\\frac{d}{\\eps})$ space and update time, which was improved for Euclidean spaces by \nFor $k=2$, Kim and Ahn~\\cite{kim2014improved} \nhave recently obtained a $(1.8+\\eps)$-approximation  \nusing $\\O(\\frac{d}{\\eps})$ space and update time.\n\nFor $k$-center with $z$ outliers in the streaming model, \nMcCutchen~\\etal~\\cite{mccutchen2008streaming} \n%(using the idea in Charikar~\\etal~\\cite{charikar2001algorithms} as subroutine) \ngave a $(4+\\eps)$-approximation \n%(or $(3+\\eps)$-approximation, if all center points can be enumerated) \nalgorithm using $\\O(\\frac{zk}{\\eps})$ space.\nWhen dimension is fixed, a $(1 + \\eps)$-approximation to 1-center with outliers\ncan be maintained in $\\O({z}/{\\eps^{((d-1)/2)}})$ space \nusing the notion of robust $\\eps$-kernels~\\cite{agarwal2007space, zarrabi2011almost}.\nFor 1-center with outliers in high dimensions, \nZarrabi-Zadeh and Mukhopadhyay~\\cite{zarrabi2009streaming} \ngave a $(\\sqrt{2}\\alpha)$-approximation, \nwhere $\\alpha$ is the approximation factor of the underlying algorithm for maintaining 1-center. \nCombined with the $1.22$-approximation algorithm of Chan and Pathak~\\cite{chan2014streaming},\nit yields an approximation factor of $(\\sqrt{2} \\times 1.22) < 1.73$ \nusing $O(d^3z)$ space and $\\poly(d,z)$ update time.\n%In fixed dimensions, there is a streaming $\\O(\\frac{z}{\\eps^{\\O(d)}})$-space algorithm~\\cite{agarwal2007space, zarrabi2011almost}.\n\n\n\\begin{table}[t]\n\\centering\n\\begin{tabular}{|c|c|c|}\n\\hline\n\\multirow{2}{*}{\\begin{tabular}[c]{@{}c@{}} \\ \\  Problem \\ \\ \\end{tabular}} & \\multicolumn{2}{c|}{Approximation Factor} \\\\ \\cline{2-3} \n & Without Outliers & With Outliers \\\\ \\hline \\hline\n1-Center & 1.22~\\cite{chan2014streaming} & 1.73~\\cite{zarrabi2009streaming} \\\\ \\hline\n2-Center & $1.8 + \\eps$~\\cite{kim2014improved} & \\textbf{$1.8 + \\eps$} [Here]  \\\\ \\hline\n$k$-Center & $2 + \\eps$~\\cite{guha2009tight,mccutchen2008streaming} & $4 + \\eps$~\\cite{mccutchen2008streaming}  \\\\ \\hline\n\\end{tabular}\n\\caption {Summary of the streaming algorithms \nfor $k$-center with and without outliers in high dimensions.}\n\\label{table:summary}\n\\end{table}\n\n\\paragraph{Our result}\nIn this paper, we study the 2-center problem with outliers in high dimensions.\nWe present a streaming algorithm for the problem that achieves\nan approximation factor of $1.8 + \\eps$, for any $\\eps > 1$,\n%using $O(d^3z/\\eps)$ space.\nusing $\\poly(d, z, {1 \\over \\eps})$ space and update time.\nThis improves the current streaming algorithm available for the problem\nwhich has an approximation factor of $4+\\eps$.\n%Our work not only improves the best previous algorithm available for the case of 2-center,\n%but is also counterintuitive in the sense that its \nThe approximation factor of our algorithm matches\nthat of the best streaming algorithm for the 2-center problem without outliers.\nThis is somewhat surprising, considering that \nthe current best approximation factors for streaming $k$-center with and without outliers \ndiffer by a multiplicative factor of $\\sqrt{2}$ for $k=1$,\nand by a factor of 2  for general~$k$. %the 1-center problem.\nSee \\Cref{table:summary} for a comparison.\n\nTo obtain our result, we have used a combination of several ideas\nincluding parallelization, far/close ball separation, centerpoint theorem,\nand keeping a lower/upper bound on the radius and distance of the optimal balls.\nWe have also utilized ideas used in~\\cite{kim2014improved} \nfor the 2-center problem with no outliers.\n%However, our algorithm is much detailed and uses many new ingredients.\nHowever, our problem is much harder here, % handling outliers makes the problem much harder,\nas we not only need to find balls of minimum radius, \nbut we also need to decide which subset of points to cluster.\nThis is in particular more challenging in the streaming model,\nwhere we only have a single pass over the input, and we must decide on the fly\nwhich point is an outlier, \nand which one can be safely ignored as a non-outlier point,\n%using only a limited amount of storage.\nto comply with the working space restriction enforced by the model.\n\n\n\\REM{\nThe rest of this paper is organized as follows.\nIn Section~\\ref{sec:1-center}, we give a simple $2$-approximation algorithm for \nthe 1-center problem with outliers that uses $\\O(z^2 + zd)$ space.\nIn the next section, we show a $(1.8 + \\eps)$-approximation\nstreaming algorithm for 2-center with $z$ outliers in high dimensions. \n}\n\n\n% ---------------------------- Preliminaries -------------------------------\n\n\\section{Preliminaries}\n\\label{sec:pre}\nLet $B(c,r)$ denote a ball of radius $r$ centered at $c$. \nWe use $r(B)$ to denote the radius of a ball $B$. % and $c(B)$, respectively.\nFor two points $p$ and $q$, %by $pq$ the straight line segment between $p$ and $q$,\nthe distance between $p$ and $q$ is denoted by $\\len{pq}$.\nGiven two balls $B(c,r)$ and $B'(c',r')$, \nwe define \n$\\delta(B, B') = \\max \\set{0, \\len{cc'}-r-r'}$\nto be the \\emph{distance} between $B$ and $B'$.\nTwo balls $B_1$ and $B_2$ %with radius $r$ \nare said to be \\emph{$\\alpha$-separated}, \n%if $\\delta(B_1, B_2) \\geq \\alpha r$.\nif $\\delta(B_1, B_2) \\geq \\alpha \\cdot \\max \\set{r(B_1), r(B_2)}$.\n\n\nGiven an $n$-point set $P$ in $d$-dimensions,\na point $c \\in \\IR^d$ is called a \\emph{centerpoint} of $P$,\nif any halfspace containing $c$ contains at least $\\ceil{{n}/({d + 1})}$ points of $P$. \n%In other words, any halfspace (or convex set) that avoids a centerpoint can contain at most $\\floor{\\frac{dn}{d + 1}}$ points of $P$. \nIt is well-known that any finite set of points in $d$-dimensional space \nhas a centerpoint~\\cite{danzer1963helly}. \nThe following observation is a corollary of this fact.\n%~\\cite{edelsbrunner1987algorithms}.\n\n\\begin{obs}\n\\label{obs:omitting-centerpoint}\n\tGiven a set $P$ of $k(d+1)$ points in $d$-dimensional space, \n\tthe centerpoint of $P$ has the property that \n\tany convex object not covering the centerpoint, \n\tleaves at least $k$ points of $P$ uncovered.\n\\end{obs}\n\nGiven  a point set $P$,\nthe \\emph{$k$-furthest point from} $p \\in P$\nis a point whose distance to $p$ is the $k$-th largest among all points in $P$.\n%is the $k$-th point in $P$ when points are sorted\n%in their decreasing distance from~$p$.\nWe assume the standard word-RAM model of computation. \nEach coordinate value takes a unit of space.\nThus, a $d$-dimensional point takes $\\O(d)$ space,\nand basic operations on the points take $\\O(d)$ time.\n\n\n%-------------------------- 1-center ---------------------------------\n\n\\section{A Simple Algorithm for 1-Center with Outliers}\n\\label{sec:1-center}\n\nTo warm up, we present a simple $2$-approximation streaming algorithm\nfor the 1-center problem with outliers.\nIt utilized a parallelization technique that \nwill be used extensively in the rest of the paper.\nThe pseudocode is provided in \\Cref{alg:1-center}.\nThe algorithm receives as input a stream of points, $P$,\nand the number of outliers, $z$.\nIt assumes that the first point $p_1$ of the stream is non-outlier.\nWe will show later how to remove this assumption.\nThe algorithm returns a ball $B$ covering all but at most $z$ points of $P$.\n%\n\n%\\begin{algorithm}\n%\\caption{\\sc 1-Center$(P, z)$} \n%\\algsetup{indent=1.5em}\n%\\label{alg:1-center}\n%\\begin{algorithmic}[1]\n%\n%\t%\\STATE Let $p_i$ denote the elements of $P$, for $i \\in \\set{1, \\dots, n}$.\n%\t\\STATE let $p_1, \\ldots, p_n$ be the points of $P$\n%\t\\FOR{$i = 1, \\dots, z+1$}\n%\t\t%\\STATE move $p_i$ to the front of $P$ %is a non-outlier point in optimal solution.\n%\t\t\\STATE $B_i \\gets$ \\Call{1-Center-Special}{$P, z,p_i$}\n%\t\\ENDFOR\n%\t%\\STATE $i^* \\gets \\argmin_{i=1}^{z+1} r_i$\n%\t\\RETURN smallest ball among $\\set{B_1, \\ldots, B_{z+1}}$\n%\n%\\end{algorithmic}\n%\\end{algorithm}\n\n\\begin{algorithm}\n\\caption{\\sc 1-Center$(P, z)$} \n\\algsetup{indent=1.5em}\n\\label{alg:1-center}\n\\begin{algorithmic}[1]\n\t%\\STATE {$\\triangleright$ $c$ is a non-outlier point in the optimal solution}\n\t\\STATE $c \\gets$ the first point in $P$\n\t\\STATE $B \\gets B(c, 0)$\n\t\\STATE $Q \\gets \\emptyset$\n\t\\FORALL {$p$ in $P$}\n\t\t\\IF {$p \\notin B$}\n\t\t\t\\STATE insert $p$ into $Q$\n\t\t\t\\IF {$|Q| = z + 1$}\n\t\t\t\t\\STATE $q$ $\\gets$ closest point to $c$ in $Q$\n\t\t\t\t\\STATE remove $q$ from $Q$\n\t\t\t\t\\STATE $B \\gets B(c, \\len{cq})$\n\t\t\t\\ENDIF\n\t\t\\ENDIF\n\t\\ENDFOR\n\t\\RETURN {B}\n\\end{algorithmic}\n\\end{algorithm}\n\n%The function \\textproc{1-Center-Special} in \\Cref{alg:1-center-special}, \n%takes as input a point $c$ which is guaranteed to be a non-outlier point in the optimal solution. \n%To overcome the lack of knowledge about such a point, \n%function \\textproc{1-Center} in \\Cref{alg:1-center}\n%tries each of the first $z+1$ points of the stream as a candidate for a non-outlier point and \n%generates a ball for each, using function \\textproc{1-Center-Special}. \n%It returns the ball with the minimum radius. \n%Note that, in the streaming model, %due to space limitations inherent to streaming data model, \n%the body of the for loop in function \\textproc{1-Center} runs in parallel.\n%To run function \\textproc{1-Center} in the data stream model,\n%we run the body of the for loop in $z+1$ parallel streaming instances.\n\n\\begin{theorem} \\label{thm:1-center}\n\tAlgorithm~\\ref{alg:1-center} computes a $2$-approximation to\n\tthe 1-center problem with $z$ outliers,\n\tassuming that the first point of the stream is not outlier. \n\\end{theorem}\n\n\n\\begin{proof}\nLet $B^*(c^*, r^*)$ be the optimal solution,\nand $c$ be a non-outlier point in the optimal solution.\nSince $c$ is covered by $B^*$,\nfor all points $p \\in B^*$, we have\n$\\len{cp} \\le \\len{cc^*} + \\len{c^*p} \\le 2r^*$.\nAmong the $z+1$ points furthest from $c$,\nthere is at least one point $q$ which is not outlier, % in the optimal solution,\nand therefore, is contained in $B^*$\n(see \\Cref{fig:1center}). \nThus, $\\len{cq} \\le 2r^*$,\nand hence, the ball $B(c, \\len{cq})$ returned by Algorithm~\\ref{alg:1-center} \nis a 2-approximation. \n\\end{proof}\n\n\n\\begin{figure}[t]\n\t\\centering\n\t\\includegraphics[width=10em]{figs/one-center}\n\t\\caption{Proof of \\Cref{thm:1-center}}\n\t\\label{fig:1center}\n\\end{figure}\n\n\n\\noindent\nAlgorithm~\\ref{alg:1-center} \nassumes that the first point of the stream is not outlier.\nTo remove this assumption,\nwe run $z+1$ instances of \\Cref{alg:1-center} in parallel,\neach of which is given as input one of the first $z + 1$ points of the stream,\nfollowed by the rest of the points.\nClearly, there exists a point among the first $z+1$ points of $P$\nwhich is not an outlier in the optimal solution.\nTherefore, the smallest ball among the $z+1$ balls computed in parallel\nis always within factor~2 of the optimal solution. % by \\Cref{thm:1-center-special}.\nSince the space complexity of Algorithm~\\ref{alg:1-center} for one instance is $\\O(zd)$, \nand its update time is $\\O (zd \\log z)$, % and the query time is $\\O (z)$.\nwe get the following result.\n\n\\begin{theorem} \\label{thm:1-center-stream}\n\tGiven a stream of points in $d$ dimensions,\n\twe can maintain a 2-approximation to the 1-center with $z$ outliers\n\tin $\\O(z^2d)$ space and $\\O (z^2d\\log z)$ update time.\n\\end{theorem}\n\n%function \\textproc{1-Center} in \\Cref{alg:1-center}\n%tries each of the first $z+1$ points of the stream as a candidate for a non-outlier point and \n%generates a ball for each, using function \\textproc{1-Center-Special}. \n%It returns the ball with the minimum radius. \n%Note that, in the streaming model, %due to space limitations inherent to streaming data model, \n%the body of the for loop in function \\textproc{1-Center} runs in parallel.\n%To run function \\textproc{1-Center} in the data stream model,\n%we run the body of the for loop in $z+1$ parallel streaming instances.\n%\n%The space complexity of Algorithm~\\ref{alg:1center} is $\\O(z^2 + zd)$, the update time is $\\O (z \\log z + zd)$ and the query time is $\\O (z)$.\n%If a non-outlier point $p$ is known then the space, update time and query time complexities of Algorithm~\\ref{alg:1center} can be reduced by a factor of $z$.\n\n\n\n%-------------------------- 2-center ---------------------------------\n\n\n\n\\section{The 2-Center Problem with Outliers}\n\\label{sec:2-center}\n\nIn this section, we provide a $(1.8 + \\eps)$-approximation algorithm\nfor the 2-center problem with outliers.\nIn all algorithms presented in this section,\nwe assume that the first point of the stream, $p_1$, is non-outlier. \nThis assumption can be easily removed by considering $z + 1$ parallel instances of the algorithm, \nsimilar to what we did in \\Cref{sec:1-center}.\n\nLet $B_1^*$ and $B_2^*$ be the balls\nin an optimal solution to the 2-center problem with $z$ outliers on a point set $P$.\nWe denote by $r^*$ the optimal radius,\nand by $\\delta^*$ the distance between $B_1^*$ and $B_2^*$.\nTo prove our main result, we distinguish between two cases.\nIn \\Cref{subsec:bigger}, we address the case where $\\delta^* > \\alpha r^*$, \nfor some constant $\\alpha$ to be fixed later.\n(It will turn out that $\\alpha = 16$ is a proper choice.)\nWe then present in \\Cref{subsec:smaller} \nour algorithm for the case of $\\delta^* \\leq \\alpha r^*$.\n\n%We inspect the case where $\\delta^* \\ge \\alpha r^*$ in Subsection~\\ref{subsec:bigger}.\n%give a description of our algorithm for a given $r > 0$ for the case where $\\delta^* < \\alpha r^*$ and $1.2r^* \\le r < (1.2 + 2\\eps/3)r^*$, which returns a $(1.8 + \\eps)$-approximate solution. We explain how to find such an $r$ and present a full description of our algorithm for the case where $\\delta^* < \\alpha r^*$ in Subsection~\\ref{subsec:findr}. \n\n\n\n\n% -------------------------------- First Case -----------------------------------\n\n\\subsection{The Case $\\delta^* > \\alpha r^*$}\n\\label{subsec:bigger}\n\nIn this section, we present a $1.8$-approximation algorithm for the case \nwhere optimal balls are separated by a distance greater than $\\alpha r^*$.\nWe start by two useful observations.\n%The value of $\\alpha$ will be fixed later in this section.  \n\n\\begin{obs}\n\\label{obs:c+4}\n\tLet $B_1$ and $B_2$ be two congruent balls of radius $r$,\n\twith distance $\\delta > \\alpha r$.\n\t%If $p$ and $q$ are two points in $B_1$ and $B_2$, respectively,\n\tFor any two points $p \\in B_1$ and $q \\in B_2$,\n\twe have $1 \\le \\frac{\\len{pq}}{\\delta} <  \\frac{\\alpha + 4}{\\alpha}$.\n\\end{obs}\n\n\\begin{proof}\nThe distance between $p$ and $q$ is at most $\\delta + 4r$.\n%(see \\Cref{fig:c+4}).\nHence, $\\frac{\\len{pq}}{\\delta} \\leq 1 + {4r \\over \\delta} < 1 + \\frac{4}{\\alpha}$.\n\\end{proof}\n\n\\REM{\n\\begin{figure}[th]\n\t\\centering\n\t\\includegraphics[width=20em]{figs/c_plus_4}\n\t\\vspace{-1em}\n\t\\caption{Illustrating Observation~\\ref{obs:c+4}}\n\t\\label{fig:c+4}\n\\end{figure}\n}\n\n\\begin{obs}\n\\label{obs:intersection}\n\tLet $B_1$ and $B_2$ be two disjoint balls of distance $\\delta$,\n\tand let $B$ be an arbitrary ball of radius less than $\\frac{\\delta}{2}$. \n\tThen $B$ intersects at most one of $B_1$ and $B_2$.\n\\end{obs}\n\n\\noindent \n%Before presenting our algorithm,\nWe next prove some properties regarding \nthe optimal balls, $B_1^*$ and $B_2^*$.\n\n\\begin{lemma}\n\\label{lem:c-sep}\n\tLet $B_1^*$ and $B_2^*$ be $\\alpha$-separated, with $\\alpha > 4$.\n\tIf $p$ is a point in $B_1^*$,\n\tand $S$ is a $(z+1)$-subset of $P$ furthest from~$p$,\n\tthen $S \\cap B_2^*$ is non-empty.\n\\end{lemma}\n\n\\begin{proof}\nSuppose by way of contradiction that $S \\cap B_2^*$ is empty. \nSince $\\card{S} = z + 1$, there is at least one point in $S$\nwhich is not outlier, and hence, it is in $B_1^*$.\nLet $q$ be a point in $S \\cap B_1^*$ furthest from~$p$. \nConsider the ball $B(p, \\len{pq})$. \n%It is clear that $B$ covers $P \\setminus S$. \nFor any point $s \\in P \\setminus S$, \nwe have $\\len{ps} \\leq \\len{pq}$,\nbecause $s \\not\\in S$ and $q \\in S$. \nTherefore, $B$ covers $P \\setminus S$.\nSince $p, q \\in B_1^*$, $\\len{pq}$ is at most $2r^*$. \nThus, by Observation~\\ref{obs:intersection}, $B_2^* \\cap B = \\emptyset$. \nTherefore, $B_2^* \\cap P = \\emptyset$, and hence,\n $B_2^*$ is empty, which contradicts the optimality of the solution.\n\\end{proof}\n\n\\begin{lemma}\n\\label{lem:(z+1)-furthest}\n\tLet $p$ be a point in $B_1^{*}$,\n\tand $q$ be the $(z+1)$-furthest point from $p$. \n\tThen, $\\delta^* > \\frac{\\alpha}{\\alpha+4}\\len{pq}$.\n\\end{lemma}\n\n\\begin{proof}\nBy Lemma~\\ref{lem:c-sep}, there exists a point $q' \\in B_2^*$ \nsuch that $\\len{pq'} \\ge \\len{pq}$. \nThus, by Observation~\\ref{obs:c+4}, \n%$\\frac{\\alpha}{\\alpha+4} \\len{pp_2} \\le \\delta^*$. \n${\\len{pq} \\over \\delta^*} \\le {\\len{pq'} \\over \\delta^*} < \\frac{\\alpha+4}{\\alpha}$.\n\\end{proof}\n\n\\begin{lemma}\n\\label{lem:2r}\n\tIf $p \\in B_1^*(c_1, r^*)$ and $q \\in B_2^*(c_2, r^*)$,\n\tthen $B_1^* \\subset B(p, 2r^*)$ and $B_2^* \\subset B(q, 2r^*)$,\n\tand hence, at most $z$ points of $P$ lie outside $B(p, 2r^*) \\cup B(q, 2r^*)$.\n\\end{lemma}\n\n\\begin{proof}\n\tFor an arbitrary point $p' \\in B_1^*$, $\\len{pp'} \\leq \\len{pc_1} + \\len{p'c_1} \\leq 2r^*$,\n\tand as a result, $B_1^* \\subset B(p, 2r^*)$.\n\tSimilarly, we have $B_2^* \\subset B(q, 2r^*)$. \n\tConsidering that at most $z$ points of $P$ are outlier, the proof is complete.\n\\end{proof}\n\n\\begin{lemma}\n\\label{lem:center-point}\n\tLet $S$ be a subset of $P$ of size at least $\\dz$,\n\tenclosed by a ball $B$ of radius less than $\\delta^* / 2$.\n\tThen the centerpoint $c_p$ of $S$ lies inside either $B_1^{*}$ or $B_2^{*}$.\n\\end{lemma}\n\n\\begin{proof}\n\tNot all points in $S$ can be outlier, because $\\dz > z$.\n\tThus, by Observation~\\ref{obs:intersection},\n\t$B$ intersects exactly one of $B_1^*$ and $B_2^*$.\n\tAssume, w.l.o.g., that $B$ intersect $B_1^*$. \n\tNow, by Observation \\ref{obs:omitting-centerpoint}, \n\tif $c_p$ is not in $B_1^*$, \n\tthen $z+1$ points of $S$ remain uncovered by $B_1^*$,\n\tcontradicting the fact that there at most $z$ outliers.\t\n\\end{proof}\n\n\\paragraph{The Algorithm}\nWe now describe our algorithm for handling the case  $\\delta^* > \\alpha r^*$.\nAt any time, our algorithm maintains a partition of $P$ into three disjoint subsets\n$B_1$, $B_2$, and Buffer.\nThe first point $p_1$ is assumed, w.l.o.g, to be in $B_1^*$. \n(We have already assumed that $p_1$ is not outlier.)\nThe algorithm tries to partition points in such a way that \nat the end,\n$B_1$ contains the whole $B_1^*$, and $B_2$ contains the whole $B_2^*$,\nwith possibly some outliers being contained in $B_1$ and $B_2$.\n%Buffer has always size at most $z$.\nThe algorithm sets $c_1 = p_1$ as the fixed center of $B_1$,\nand picks $c_2$ among the points processed so far as a candidate \nfor being the center of $B_2$.\nMoreover, the algorithm maintains two values $\\delta$ and $r$,\nwhere at any time, $\\delta$ is a lower bound of $\\delta^*$, \nand $r$ is an upper bound of $2r^*$ (under a certain condition). %(if $c_p \\in B_2^*$).\n\nOur algorithm is presented in \\Cref{alg:case-1}.\nFor each input point $p \\in P$, the algorithm first tries \nto add $p$ to either $B_1$ or $B_2$,\nusing functions \\textproc{AddToB$_1$} and \\textproc{AddToB$_2$}, respectively.\n%presented in Algorithms~\\ref{alg:addB1} and~\\ref{alg:addB2}.\nIf none of them fits, the point is added to Buffer.\nThe function \\textproc{AddToB$_1$} adds a point $p$ to $B_1$\nonly if it is within distance $\\delta$ of the center $c_1$.\nSimilarly, \\textproc{AddToB$_2$} adds a point $p$ to $B_2$\nonly if it is within $\\rc$-radius of $c_2$. \nThe two functions also update the values of $\\delta$ and $\\rc$ whenever necessary,\nto maintain the invariants to be defined in Lemma~\\ref{lem:invariants}.\n\n\n\\begin{algorithm}[t]\n\\caption{\\sc 2-Center-Separated$(P)$} \n\\algsetup{indent=1.5em}\n\\label{alg:case-1}\n\\begin{algorithmic}[1]\n\\STATE $c_1 \\gets p_1$, $\\rc  \\gets 0$, $\\delta \\gets 0$\n\\FORALL{$p \\in P$}\n\t\\IF {\\NOT (\\Call{AddToB$_1$}{$p$} \\OR \\Call{AddToB$_2$}{$p$})}\n\t\t\\STATE add $p$ to Buffer\n\t\t\\WHILE{$\\card{\\mbox{Buffer}} > z$} \\label{step:buffer-overflow}\n\t\t\t\\IF{$\\card{B_2} \\ge \\dz$}\n\t\t\t\t\\STATE $B_1 \\gets B_1 \\cup B_2$, $B_2 \\gets \\emptyset$\n\t\t\t\\ELSIF{$c_2$ is set}\n\t\t\t\t\\STATE $B_1 \\gets B_1 \\cup \\set{c_2}$ %, $B_u \\gets B_u \\cup \\set{c_2}$\n\t\t\t\t%\\STATE remove $c_2$ from $B_2$\n\t\t\t\\ENDIF\n\t\t\t\\STATE $T \\gets \\mbox{Buffer} \\cup B_2 \\setminus \\set{c_2}$\n\t\t\t\\STATE $B_2 \\gets \\emptyset$ \n%\t\t\t\\IF{first iteration of while}\n%\t\t\t\t\\FOR{$p \\in T$}\n%\t\t\t\t\t\\IF{\\Call{AddToB$_1$}{$p$}}\n%\t\t\t\t\t\t\\STATE remove $p$ from $T$\n%\t\t\t\t\t\\ENDIF\n%\t\t\t\t\\ENDFOR\n%\t\t\t\\ENDIF\n\t\t\t\\STATE $c_2 \\gets$ (z+1)-furthest point from $c_1$ in $T$ \n\t\t\t\\STATE $\\rc  \\gets \\radius{c_2}$\n\t\t\t\\FOR{$p \\in T$}\n\t\t\t\t\\STATE \\Call{AddToB$_2$}{$p$}\n\t\t\t\\ENDFOR\t\t\t\t\n\t\t\t\\STATE $\\mbox{Buffer} \\gets T \\setminus B_2$\n\t\t\\ENDWHILE\n\t\\ENDIF\n\\ENDFOR\n\\end{algorithmic}\n\\end{algorithm}\n\n\n\\begin{algorithm}[ht]\n\\caption{\\sc AddToB$_1(p)$} \n\\algsetup{indent=1.5em}\n\\label{alg:addB1}\n\\begin{algorithmic}[1]\n\n\t%\\STATE $q \\gets c_1$\n\t\\IF {at least $z + 1$ points have been processed}\n\t\t\\STATE $q \\gets$  $(z+1)$-furthest point from $c_1$\n\t\\ELSE\n\t\t\\STATE $q \\gets c_1$\n\t\\ENDIF\n\t\\STATE $\\delta \\gets \\frac{\\alpha}{\\alpha+4} \\len{c_1q}$\n\t\\IF {$p \\in B(c_1, \\delta)$}\n\t\t\\STATE $B_1 = B_1 \\cup \\set{p}$ %, B_u = B_u \\cup \\set{p}$\n\t\t\\RETURN{true}\n\t\\ENDIF\n\t\\RETURN{false}\n\n\\end{algorithmic}\n\\end{algorithm}\n\n\\begin{algorithm}[ht]\n\\caption{\\sc AddToB$_2(p)$} \n\\algsetup{indent=1.5em}\n\\label{alg:addB2}\n\\begin{algorithmic}[1]\n%\\FUNCTION{AddToB$_2$}{p}\n\t\\IF{$c_2$ is set \\AND $p \\in B(c_2, \\rc )$}\n\t\t\\STATE $B_2 \\gets B_2 \\cup \\set{p}$ %, B_u \\gets B_u \\cup \\set{p}$\n\t\t\\IF{$|B_2| = \\dz$}\n\t\t\t%\\STATE $\\cp  \\gets$  centerpoint of $B_2$\n\t\t\t\\STATE $\\rc  \\gets  (2 + \\frac{2}{\\alpha}) \\times \\rc$\n\t\t\t\\FOR{$p$ in Buffer}\n\t\t\t\t\\IF{$p \\in B(c_2, \\rc )$}\n\t\t\t\t\t\\STATE $B_2 \\gets B_2 \\cup \\set{p}$ %, B_u \\gets B_u \\cup \\set{p}$\n\t\t\t\t\t\\STATE remove $p$ from Buffer\n\t\t\t\t\\ENDIF\n\t\t\t\\ENDFOR\n\t\t\\ENDIF\n\t\t\\RETURN{true}\n\t\\ENDIF\n\t\\RETURN{false}\n%\\ENDFUNCTION\n\\end{algorithmic}\n\\end{algorithm}\n\nWhenever the buffer overflows (in line~\\ref{step:buffer-overflow} of \\Cref{alg:case-1}),\n%the assumption about $\\cp \\in B_2^*$ is contradicted.\n%At some point during the execution of Algorithm~\\ref{alg:case-1}, the assumption about $\\cp \\in B_2^*$ might be contradicted when the buffer overflows. We can then conclude that\n% $\\cp \\notin B_2^*$.\nthe algorithm takes one of the following actions\ndepending on the size of $B_2$. \nIf $|B_2| \\ge \\dz$, then the points of $B_2$ are moved to $B_1$, and $B_2$ is reset.\nOtherwise, the old $c_2$ (if already set) is moved to $B_1$,\nand another point from $T = B_2 \\cup \\Buffer \\setminus \\set{c_2}$ is picked as $c_2$.\nThe while loop iterates at most $O(dz)$ times,\nbecause after the first iteration, we are sure \nthat $T$ has at most $\\dz + z$ points, from which \none point (i.e., $c_2$) is removed at each subsequent iteration.\n\n\n%\\paragraph{Analysis}\nFor the sake of analysis, we maintain a ``central point'', \ndenoted by $\\cp$, %not necessarily in $P$,\n%which we call a \\emph{central point}.\nwhich is defined as follows:\nif $\\card{B_2} < \\dz$, then $\\cp = c_2$, otherwise,\n$\\cp$ is the centerpoint of the first $\\dz$ points currently in~$B_2$.\n\n\\begin{lemma}\n\\label{lem:invariants}\n\tThe following invariants are maintained during the execution of the algorithm:\n\n\\begin{enumerate}\n\\item [(a)] $\\delta < \\delta^*$ %$\\delta$ is a lower bound of $\\delta^*$\n\\item [(b)] $r \\leq \\delta/2$\n%\\begin{enumerate}\n%\t\\item[1.] $r \\leq \\delta/2$\n%\t\\item[2.] $B(c_p, \\radius{c_p}) \\subseteq B_2(c_2, r)$\n%\\end{enumerate}\n\\item [(c)] $B_1 \\cap B_2^* = \\emptyset$\n\\item [(d)]  if $\\cp \\in B_2^*$, then \n\t\\begin{enumerate}\n\t\t\\item [1.] $2r^* \\le r$\n\t\t\\item [2.] $B_2 \\cap B_1^* = \\emptyset$\n\t\t\\item [3.] all points in $\\Buffer$ are outlier\n\t\\end{enumerate}\n\n\\end{enumerate}\n\\end{lemma}\n\n\\begin{proof} \n%The proof consists of four parts and each part use previous parts:\nInvariant (a): \nAt the beginning, $\\delta = 0$, which clearly satisfies the invariant.\nAfter $z+1$ points of the stream is processed, \nfunction \\textproc{AddToB$_1$} starts updating $\\delta$\nto $\\frac{\\alpha}{\\alpha+4}\\len{c_1q}$,\nwhere $q$ is the $(z+1)$-furthest point from $c_1$ in the current stream.\nNow, since $c_1 \\in B_1^*$, Lemma~\\ref{lem:(z+1)-furthest}\nimplies that $\\delta < \\delta^*$.\n%Note that if less than $z+1$ points have been processed so far,\n%then $\\delta = 0$, and hence, the invariant holds.\n\nInvariant (b): \nWhen $c_2$ is set by Algorithm~\\ref{alg:case-1}, \nit is the $(z+1)$-furthest point from $c_1$ in a set $T \\subseteq P$,\nand $\\rc$ is set to $\\frac{2}{\\alpha}\\len{c_1c_2}$.\nLet $q$ be the $(z+1)$-furthest point from $c_1$ in the stream at that moment.\nThen $\\len{c_1c_2} \\leq \\len{c_1q}$.\nAssuming $\\alpha \\ge 16$, we have \n$\\radius{c_2} \\leq \\frac{1}{6}\\frac{\\alpha \\len{c_1 q}}{(\\alpha + 4)} \\leq \\delta / 6$, \nand hence,  \n$$\n\tr \\leq (2 + \\frac{2}{\\alpha})\\radius{c_2} \\leq 3 \\times \\radius{c_2}  \\leq \\delta /2,\n$$\nwhich means that the invariant holds, \neven after increasing $r$ by function \\textproc{AddToB$_2$}.\n\nInvariant (c): The proof is provided in \\Cref{app:inv-c}. \n% due to space constraints.\n\n\\REM{\nInvariant (c): \nWe first claim that if $c_2$ is set, then\n$B(c_p, \\radius{c_p}) \\subseteq B_2(c_2, r)$.\nIf $|B_2| < \\dz$, then $c_p = c_2$ and $r = \\radius{c_2}$, \nand hence, $B_2 = B(c_p, \\radius{c_p})$. \nWhen the size of $B_2$ reaches $\\dz$, \nthe central point $\\cp$ moves to the centerpoint of $B_2$,\nand $\\rc$ is increased by a factor of $(2 + \\frac{2}{\\alpha})$. \nBecause the centerpoint of $B_2$ locates in $B_2$, then $c_p \\in B(c_2, \\radius{c_2})$.\nThus, if $|B_2| \\ge \\dz$ then $\\len{c_2 c_p} \\leq \\radius{c_2}$, and hence\n$$\n\t\\radius{c_p} \\leq \\frac{2 (\\len{c_1 c_2} + \\len{c_2 c_p})}{\\alpha} \\leq \\radius{c_2}(1 + \\frac{2}{\\alpha}).\n$$ \nTherefore, $B(c_p, \\radius{c_p}) \\subseteq B_2(c_2, \\radius{c_2}(2 + \\frac{2}{\\alpha}))$.\n\nA point $p$ can be added to $B_1$ in two cases. % by \\Cref{alg:case-1}. \nThe first case is in function \\textproc{AddToB$_1$}, \nwhere the point is added to $B_1$ only if it is within distance $\\delta$ of the center $c_1$,  \n%when $\\len{pc_1} \\leq \\delta$, \nwhich by invariant (a), \nguaranties $\\len{pc_1} < \\delta^*$. Therefore, $p \\not \\in B_2^*$ in this case.\n\nThe second case is in \\Cref{alg:case-1}, when the buffer overflows and $B_2$ is non-empty.\nThe algorithm takes one of the following actions depending on the size of $B_2$.\nIf $|B_2| < \\dz $, then $c_2 = c_p$. \\Cref{alg:case-1} add $c_2$ to $B_1$.\nBy contradiction assume that $c_p \\in B_2^*$, \nthen by invariants (b) and (d1), \n$2r^* \\leq r \\leq \\delta/2 < \\delta^*/2$. \nTherefore, by Lemma \\ref{lem:2r}, there must be at most $z$ points outside $B_1 \\cup B_2$,\nwhich contradicts the overflow of the buffer. \nIf $|B_2| \\geq \\dz$, then $c_p$ is the centerpoint of the first $\\dz$ points currently in $B_2$. \nIn this case, we add all points of $B_2$ to $B_1$. \nBy invariant (b), $r \\leq \\delta/2 < \\delta^*/2$. \nTherefore, By Lemma \\ref{lem:center-point}, $c_p \\in B_1^*$ or $c_p \\in B_2^*$. \nSuppose by way of contradiction that $c_p \\in B_2^*$. \nIn this case, by invariant (d1) and the claim we proved first,\n$B_2$ covers $B(c_p, \\radius{c_p})$ and $2r^* \\leq r$. \nTherefore, Similar to the previous part, it contradicts the overflow of the buffer. \n}\n\nInvariant (d1): \nBy Observation \\ref{obs:c+4}, if $c_1 \\in B_1^*$ and $c_p \\in B_2^*$,\nthen $1 \\leq \\frac{\\len{c_1 c_p}}{\\delta^*} \\leq \\frac{\\len{c_1 c_p}}{\\alpha r^*}$,\nand as a result, $2r^* \\leq \\radius{c_p}$. \nIf $|B_2| < \\dz$, then $c_p = c_2$, and by \\Cref{alg:case-1}, \n$r = \\radius{c_2}$, and therefore, $2r^* \\leq r$.\nIf $|B_2| \\ge \\dz$, then similar to invariant (b), \n$$\n\t2r^* \\leq \\radius{c_p} \\leq (1 + \\frac{2}{\\alpha})\\radius{c_2} \n\t\\leq (2 + \\frac{2}{\\alpha})\\radius{c_2} = r.\n$$\n\nInvariant (d2): By invariant (d1), if $c_p \\in B_2^*$ then $2r^* \\leq r \\leq \\delta /2$ and $c_p \\in B_2$. \nNow, by invariant (a) and Observation~\\ref{obs:intersection}, \n$B_2$ intersect only $B_2^*$, and hence, $B_2 \\cap B_1^* = \\emptyset$.\n\nInvariant (d3): By invariants (c) and (d1), $2r^* \\leq r \\leq \\delta/2 < \\delta^* /2$. \nTherefore, by Lemma \\ref{lem:2r}, all points outside $B_1 \\cup B_2$ are outlier.\n\\end{proof}\n\n%\\paragraph{Streaming Model}\n\n\\REM{\nSuppose that our data structure for maintaining $B_1$, $B_2$ and $B_u$ uses $S(n,z,d)$ space, $T(n,z,d)$ update and $Q(n,z,d)$ query time. Note that by $Q_{o}(zd,z,d)$ we mean the query time for the offline 1-center problem with $z$ outlier in $d$ dimensions. The best known algorithm for 1-center without outliers is $1.22$-approximation by~\\cite{chan2014streaming, agarwal2010streaming}. The buffering framework introduced in~\\cite{zarrabi2009streaming} with $\\O(dz^3 + (\\frac{d}{\\eps^3})\\log(\\frac{1}{\\eps}))$ space complexity, can be used with this algorithm as subroutine to achieve a $(1.22\\sqrt{2})$-approximation ($1.22\\sqrt{2} < 1.8$) for 1-center problem with outliers.\n\n\\begin{theorem}\n\\label{thm:2nd-cmplx}\nSpace complexity of Algorithm~\\ref{alg:case-1} is $\\O(dz+S(n,z,d))$. It takes $\\O^*(dzT(n,z,d))$ time for update. Query time in Algorithm~\\ref{alg:query} is $\\O(zQ(n,z,d) + dz(dz+zQ_o(zd,z,d)))$ and it returns two centers that guarantee a $(1.8 + \\eps)$-approximation for 2-center problem with outliers.\n\\end{theorem}\n\n\\begin{proof}\nThe space complexity for this algorithm is derived from the space used by $B_1$, $B_2$, $B_u$ and the Buffer which is obviously $\\O(dz+S(n,z,d))$. The while loop runs at most once for each point, so amortized time is $\\O(zdT(n,z,d))$. The candidates in the Algorithm~\\ref{alg:query} are at most $zd$ points  so the query time will easily follows.\n\\end{proof}\n}\n\n\\begin{theorem}\n\\label{thm:far-cmplx}\n\tIf $\\delta^* > \\alpha r^*$, a $1.8$-approximation to the 2-center problem with $z$ outliers \n\tcan be maintained in $O(d^3z^2)$ space and $\\poly(d,z)$ update/query time.\n\\end{theorem}\n\n\\begin{proof}\nOur algorithm for answering queries is provided in ~\\Cref{sec:query}.\nIt uses the current partition $B_1$, $B_2$, and Buffer, to compute\nan optimal solution to 2-center with $z$ outliers.\nIn the streaming model, we cannot afford keeping all the points of $B_1$ and $B_2$. \n%To implement our algorithm in the streaming model,\nTherefore, we maintain the sets $B_1$ and $B_2$ \nin a data structure that supports adding points,\nand gives a $\\beta$-approximation to 1-center with $k$ outliers, for $k=0,\\dots,z$.\nMoreover, we maintain a set $B_u = B_1 \\cup B_2$ in a similar data structure.\nNote that these data structures do not need to maintain all the points. \nThey only need to have a buffer of size $\\dz$ to keep the most recently added points.\n\nTo maintain $B_1$, $B_2$, and $B_u$, we \nuse the streaming algorithm of~\\cite{zarrabi2009streaming,chan2014streaming},\n%To maintain an approximation to 1-center with $z$ outliers,\n%we use the streaming algorithm of~\\cite{zarrabi2009streaming}\n%which combined with the %current best streaming algorithm for 1-center~\\cite{chan2014streaming},\n%result of~\\cite{chan2014streaming},\nwhich provides an approximation factor of $1.22 \\times \\sqrt{2} <1.8$.\n%The algorithm of~\\cite{zarrabi2009streaming}\nThe algorithm uses $O(d^3z)$ space and has $\\poly(d,z)$ update time.\n%which implies the same bounds for \\Cref{alg:case-1}.\nSince we need to run $z + 1$ instances of \\Cref{alg:case-1} in parallel, \nthe space and update time are multiplied by a factor of~$z$.\n\\end{proof}\n\n\n% -------------------------------- Second Case -----------------------------------\n\n\\subsection{The Case $\\delta^* \\leq \\alpha r^*$}\n\\label{subsec:smaller}\n\n%Our algorithm for solving the problem in this case is based on two main ingredients.\nOur idea in this section is to carefully adopt\nthe algorithm of Kim and Ahn~\\cite{kim2014improved},\noriginally designed for maintaining an approximate 2-center.\nTo avoid duplication, we just sketch the main steps of their algorithm,\n%without entering the details, \nand explain our modifications to it. \nKim and Ahn's algorithm, which we refer to as the KA algorithm,\nhas 9 different states, shown in~\\Cref{fig:dag}.\nDepending on the points arrived so far, the algorithm is in one of the states.\n%In each step one or many of the states can be valid and their algorithm considers all of them in parallel. \nIn each state, the algorithm keeps at most two balls as a candidate solution. \nA transition between the states occurs whenever a point not covered by any of the two balls arrive. \n\nThe algorithm starts at node 1, and proceed through the transition graph as points arrive.\nIn some states, there is more than one state to follow,\nand the algorithm has no prior information which one is the correct choice.\nHowever, there are only three different paths to follow in the transition graph. \n%which is a DAG,\n%consisting of only three different transition paths.  \n%(paths from node 1 to node E) \nHence, we can easily run three instances of the algorithm in parallel,\neach of which follows one of the paths deterministically, \nto make sure that at any time, at least one of the instances is in a correct state.\n\n\\begin{figure}\n\\centering\n\\begin{tikzpicture}\n  [scale=.75,auto=left,every node/.style={circle,fill=blue!15}]\n \\tikzset{edge/.style = {->,> = latex'}}\n  \\node (1) at (1,2.5) {1};\n  \\node (2a) at (3,4)  {2a};\n  \\node (2b) at (5,4)  {2b};\n  \\node (2c) at (7,4)  {2c};\n  \\node (3a) at (3,1)  {3a};\n  \\node (3b) at (5,2)  {3b};\n  \\node (3c) at (7,2)  {3c};\n  \\node (3d) at (5,0)  {3d};\n  \\node (3e) at (7,0)  {3e};\n  %\\node (E) at (9, 2) {E};\n\n  \\foreach \\from/\\to in {1/2a,1/3a,2a/2b,2b/2c,3a/3b,3a/3b,3a/3d,3b/3c,3d/3e} %,2c/E,3c/E,3e/E\n    \\draw[edge] (\\from) to (\\to);\n\n\\end{tikzpicture}\n\\caption{State diagram of the KA algorithm.\nLabels are taken from \\cite{kim2014improved}.}\n\\label{fig:dag}\n\\end{figure}\n\n\\newcommand{\\state}{\\text{state}}\n\\newcommand{\\level}{{j}}\n\\newcommand{\\counter}{\\text{counter}}\n\\newcommand{\\Insert}{\\textsc{insert}}\n\\newcommand{\\CA}{\\text{KA}}\n\n\\begin{algorithm}[t]\n\\caption{\\sc 2-Center-Close$(P, z, r)$} \n\\algsetup{indent=1.5em}\n\\label{alg:smallc}\n\\begin{algorithmic}[1]\n\t\\STATE solutions $\\gets \\set{}$\n\t\\FORALL {$(n_1, n_2, n_3, n_4)$ such that $\\sum n_i=z$}\n\t\t%\\FORALL {path $\\pi$ in the transition graph}\n\t\t\\FORALL {$\\pi \\in \\set{1, 2, 3}$}\n\t\t\t\\STATE $\\counter_i \\gets 0$, for $i = 1, \\ldots, 4$ % $1 \\le i \\le 4$\n\t\t\t\\STATE $B_1 \\gets B(p_1, r)$, $B_2 \\gets \\emptyset$\n\t\t\t\\STATE $\\level \\gets 1$ \\COMMENT{$\\level$ represents current level}\n\t\t\t\\FORALL {$p \\in P$}\n\t\t\t\t\\IF {$p \\not\\in B_1 \\cup B_2$}\n\t\t\t\t\t\\STATE $\\counter_\\level \\gets \\counter_\\level + 1$\n\t\t\t\t\t\\IF {$\\counter_\\level > n_\\level$}\n\t\t\t\t\t\t\\STATE $\\level \\gets \\level+1$\n\t\t\t\t\t\t\\STATE $(B_1, B_2) \\gets \\CA.\\Insert(p, \\pi)$\n\t\t\t\t\t\\ENDIF\n\t\t\t\t\\ENDIF\n\t\t\t\\ENDFOR\n\t\t\t\\IF {$\\level \\le 4$}\n\t\t\t\t\\STATE add $\\max \\set{r(B_1), r(B_2)}$ to solutions\n\t\t\t\t%\\STATE add $(B_1, B_2)$ to solutions\n\t\t\t\\ENDIF\n\t\t\\ENDFOR\n\t\\ENDFOR\n\t\\RETURN $\\min\\set{\\text{solutions}}$\n\\end{algorithmic}\n\\end{algorithm}\n\nOur modification is on the transition part.\nPoints that are covered by the current solution can be safely ignored, \nas they do not cause any change in the current solution, and hence, they cause no transition.\nOnly those points that lie outside the current solution are candidates for being outliers.\nSince the number of outliers in each state is unknown,\nwe try all possible choices. \nThe observation here is that the transition graph is a DAG of depth four.\nIf $n_i$ ($1 \\le i \\le 4$) represents the number of outliers in depth $i$, \nthen it suffices to consider all tuples $(n_1,\\dots, n_4)$ such that $\\sum_{i=1}^{4} n_i=z$,\nIt is easy to verify that there are $O(z^3)$ such tuples.\n\nThe pseudocode of our algorithm is presented in \\Cref{alg:smallc}.\nFor each possible choices of $n_1$ to $n_4$, \nand each of the three paths in the transition graph, numbered from 1 to 3,\nthe algorithm keeps a candidate solution $(B_1, B_2)$ to the 2-center of non-outlier points,\na parameter $\\level$ representing the current level in the transition graph,\nand four counters to keep track of number of outliers seen so far at each level.\n\nThe algorithm starts with $B_1 = B(p_1, r)$ and $B_2 = \\emptyset$,\nwhich corresponds to Case 1 of the KA algorithm.\nFor each new point $p$, we first check if it is contained in the current solution.\nIf so, then we are done.\nOtherwise, if the number of outliers seen in the current level has not yet reached $n_\\level$, \nwe consider $p$ as an outlier and proceed.\n%If our quota for consuming outliers in this level is finished, \nOtherwise, we go to the next level, and update the current candidate solution, \n$(B_1, B_2)$, using the KA algorithm.\nWe give the transition path $\\pi$ along with the point $p$ to the KA algorithm\nto help it deterministically decide which state to choose as the next one.\n\nAfter all points in $P$ are processed, if we are in one of the four states in the current path,\nthen the obtained solution is added to the feasible solutions.\nOtherwise, the solution is not feasible, and is abandoned as in the KA algorithm.\nFinally, we return the best solution among all computed feasible solutions. \nKim and Ahn~\\cite{kim2014improved} proved that in all feasible solutions\ncomputed this way,\nthe larger ball among $B_1$ and $B_2$ has radius at most $3/2r$,\nprovided $\\delta^* \\le \\alpha r^*$.\n(Their proof is stated for $\\alpha = 2$, \nbut can be extended to any $\\alpha \\ge 2$.)\nAssuming that we have a good estimate $r$ satisfying\n$1.2r^* \\le r < (1.2 + 2\\eps/3)r^*$,\nwe get the following.\n\n\\begin{theorem} \\label{thm:close}\n\tFor $1.2r^* \\le r < (1.2 + {2 \\over 3}\\eps)r^*$ and $\\delta^* \\le \\alpha r^*$,\n\t\\Cref{alg:smallc} computes a $(1.8+\\eps)$-approximation to \n\tthe 2-center with $z$ outliers \n\tin $\\O (dz^3)$ space and $\\O (dz^3)$ update time,\n\tassuming that the first point of the stream is not outlier. \n\\end{theorem}\n\n\\REM{\n\\begin{proof}\nSince our algorithm considers all possible input cases of streaming points, there is at least one feasible solution. Since every feasible solution has its larger radius at most $3r/2$, the final solution has larger radius at most $3r/2 \\le (1.8 + \\eps)r^*$.\nFor space complexity, our algorithm maintains at most two balls in each case, and therefore it uses $\\O(dz^3)$ space. Whenever the next point is inserted, the algorithm updates the solution for each subcase in $\\O (d)$ time. Therefore, the algorithm spends $\\O (dz^3)$ update time for each point of $P$. Answering a query consists of choosing the minimum radius among all the candidate solutions, which amounts to $\\O (dz^3)$ time.\n\\end{proof}\n}\n\n% ---------------------------\n\n\\noindent\nAs shown in \\Cref{sec:estimate}, a desired estimate for $r$ can be\nobtained by running $O(1/\\eps)$ instances of \\Cref{alg:smallc} in parallel.\nAdding another level of parallelization to remove the assumption of $p_1$\nbeing a non-outlier, we get the following.\n\n\\begin{theorem}\n\\label{thm:close-cmplx}\n\tIf $\\delta^* \\leq \\alpha r^*$, a $(1.8 + \\eps)$-approximation to the 2-center problem with $z$ outliers \n\tcan be maintained in $\\O(\\frac{dz^4}{\\eps})$ space \n\tand $\\O(\\frac{dz^4}{\\eps})$ update/query time.\n\\end{theorem}\n\n%\\subsection{Final Result}\n\n\\noindent\nTheorems~\\ref{thm:far-cmplx} and~\\ref{thm:close-cmplx}\ntogether yield the following main result of the paper.\n\n\\begin{theorem} \\label{thm:1-center-stream}\n\tGiven a stream of points in $d$ dimensions,\n\twe can maintain a $(1.8 + \\eps)$-approximation to \n\tthe 2-center problem with $z$ outliers using \n\t$\\O(dz^2 (d^2 + z^2/\\eps))$ space and \n\t$\\poly(d, z, {1 \\over \\eps})$ update/query time.\n\\end{theorem}\n\n\n%\\begin{theorem}\n%Our algorithm uses $\\O(zS(n, z, d) + \\frac{dz^4}{\\eps})$ space and has time complexity $\\O^*(dz^2T(n,z,d) + \\frac{dz^5}{\\eps})$ and $\\O(z^2Q(n,z,d) + dz^2(dz+zQ_o(zd,z,d)) + \\frac{dz^4}{\\eps})$ for update and query operations, respectively. It returns a $(1.8 + \\eps)$-approximate solution for 2-center problem with outliers in any dimension.\n%\\end{theorem}\n%\n%\\noindent \n%Using the algorithm of~\\cite{zarrabi2009streaming}, \n%the space complexity of our algorithm is $\\O(\\frac{dz^4}{\\eps} + \\frac{dz}{\\eps^3})$.\n\n%---------------------------- Conclusions ---------------------\n\n\\section{Conclusions}\n\\label{sec:conc}\n\nIn this paper, we presented a $(1.8 + \\eps)$-approximation streaming algorithm for 2-center problem with outliers in Euclidean space.\nIt improves the previous $(4+\\eps)$-approximation algorithm available for the problem \ndue to McCutchen and Khuller~\\cite{mccutchen2008streaming}. \nFinding better approximation factor or space complexity\nis an interesting problem that remains open.\nIt is also interesting to see if the ideas in this paper \ncan be extended to the $k$-center problem with outliers in the data stream model,\n%for any $k$, or \neven for small values of $k \\ge 3$.\n\n\\paragraph{Acknowledgement}\nThe authors would like to thank Kiana Ehsani and Sahand Mozaffari \nfor their thoughtful discussions, and for their very helpful comments.\n%and for their help to improve the quality of this paper.\n\n\n%--------------- BIBS --------------------\n\n{\n\\small\n\\baselineskip=.85\\baselineskip\n\\bibliographystyle{abbrv}\n\\bibliography{bibs/abbrv,bibs/ref}\n}\n\n%\\end{document}\n\n%---------------------------- Appendix ------------------------\n\\newpage\n\n\\appendix \n\n%---------------------------- Answering Queries ------------------------\n\n\n\\section{Answering Queries}\n\\label{sec:query}\n\n%Using \\Cref{alg:case-1},\nIn the following, we show how the information maintained \nby \\Cref{alg:case-1} can be used to answer queries of this kind:\nfind two $\\alpha$-separated congruent balls of minimum radius\nto cover all but at most $z$ points of the stream processed so far.\n\nOur query algorithm is presented in \\Cref{alg:query}.\nThe idea behind the algorithm is as follows.\nBy our initial assumption about $p_1$ and  by invariants (c) and (d), \nif $c_p \\in B_2^*$, then we know that $B_1$ completely contains $B_1^*$,\nand $B_2$ completely contains $B_2^*$.\n%because $B_1 \\cap B_2^* = \\emptyset$ . \nHowever, it might be the case that our assumption about $c_p$ \nwas incorrect, and therefore, $B_1$ (resp., $B_2$) \nmay not completely contain $B_1^*$ (resp., $B_2^*$). \nTo overcome this issue, we try all possible candidates for $c_2$\n(which in turn, determines $c_p$),\nand compute, for each resulting partition of $P$ into \n$B_1$, $B_2$, and Buffer, the best solution for 2-center with $z$ outliers\nusing the \\textproc{MinCover} function presented in \\Cref{alg:compute-min}.\n\n\\begin{algorithm}\n\\caption{\\sc Query} \n\\algsetup{indent=1.2em}\n\\label{alg:query}\n\\begin{algorithmic}[1]\n\t%\\STATE solutions $\\gets \\set{\\Call{MinCover}{B_1, B_2, \\Buffer}}$\n\t\\STATE solutions $\\gets \\set{}$\n\t\n\t\\STATE candidates $\\gets B_2 \\cup \\Buffer$\n\t\\IF {$\\card{B_2} \\ge \\dz$}\n\t\t\\STATE candidates $\\gets \\set{c_2} \\cup \\Buffer $\n\t\t\\STATE $B_1 \\gets B_1 \\cup B_2$\n\t\\ENDIF\n\n\t\\STATE $\\delta_0 = \\delta$\n\t\\FOR{$c \\in$ candidates}\n\t\t\\STATE $\\rc  \\gets \\frac{2}{\\alpha} \\len{c_1 c}$\n\t\t\\STATE $B'_1 \\gets B_1$, $\\delta \\gets \\max \\{ \\delta_0, r \\}$\n\t\t\\STATE $B'_2 \\gets \\emptyset$, $\\Buffer' \\gets \\emptyset$ \n\t\t\\FOR{$p \\in$ candidates}\n\t\t\t\\IF {\\NOT (\\Call{AddToB$'_1$}{$p$} \\OR \\Call{AddToB$'_2$}{$p$})}\n\t\t\t\t\\STATE add $p$ to $\\Buffer'$\n\t\t\t\\ENDIF\n\t\t\\ENDFOR\n\t\t\\STATE add \\Call{MinCover}{$B'_1$, $B'_2$, $\\Buffer'$} to solutions\n\t\\ENDFOR\n\t\\RETURN $\\min\\set{\\text{solutions}}$\n%\\EndFunction\n\\end{algorithmic}\n\\end{algorithm}\n\n\\begin{algorithm}\n\\caption{\\sc MinCover($B_1, B_2, \\text{\\rm Buffer}$)} \n\\algsetup{indent=1.5em}\n\\label{alg:compute-min}\n\\begin{algorithmic}[1]\n%\\Function{MinCover}{$B_1$, $B_2$, Buffer}\n\t\\STATE solutions $\\gets \\set{}$\n\t\\FOR{$k \\gets 0, \\dots,(z - \\card{\\mbox{Buffer}})$}\n\t\t\\STATE $r_1 \\gets \\Call{1-Center}{B_1, k}$\n\t\t\\STATE $r_2 \\gets \\Call{1-Center}{B_2, z - \\card{\\mbox{Buffer}} - k}$\n\t\t\\STATE add $\\max \\set{r_1, r_2}$ to solutions\n\t\\ENDFOR\n\t\\RETURN $\\min\\set{\\text{solutions}}$\n%\\EndFunction\n\\end{algorithmic}\n\\end{algorithm}\n\n\n%Now, we show that the query algorithm correctly considers all possible candidates for $c_2$.\nLet $C$ denote the set of candidates for $c_2$.\nBy invariant~(c), we know that $B_1 \\cap B_2^* = \\emptyset$. \nTherefore, there exists a point in $(B_2 \\cup \\Buffer) \\cap B_2^*$,\nand hence, $C$ is $(B_2 \\cup \\Buffer) \\cap B_2^*$ in general.\n%We now use the following lemma.\n%In this general case, our candidates $C$ for $c_2$ is set $(B_2 \\cup \\Buffer) \\cap B_2^*$.\nHowever, when $|B_2| \\geq \\dz$, \nwe will show in the following lemma that $(\\{c_2\\} \\cup \\Buffer) \\cap B_2^* \\neq \\emptyset$. \nTherefore, if $|B_2| \\ge \\dz$, \nwe only need to consider $\\{c_2\\} \\cup \\Buffer$ as candidates for $C$.\n%our candidates for $C$ are only $\\{c_2\\} \\cup \\Buffer$. \n\n\n\n\\begin{lemma}\n\\label{lem:B2dz}\n\tAt any time, \n\tif $|B_2| \\ge \\dz$ and $\\cp \\not\\in B_2^*$,\n\tthen $B_2 \\cap B_2^* = \\emptyset$.\n\\end{lemma}\n\n\\begin{proof}\n\tBy invariants (a) and (b), we know that $r \\leq \\delta/2 < \\delta^*/2$. \n\tBy Lemma~\\ref{lem:center-point}, $c_p \\in B_1^* \\cap B_2^*$. \n\tSince $c_p \\not \\in B_2^*$, we have $c_p \\in B_1^*$. \n\tOn the other hand, by Observation~\\ref{obs:intersection}, \n\t$B_2$ intersect at most one of $B_1^*$ and $B_2^*$. \n\tTherefore, $B_2 \\cap B_2^* = \\emptyset$.\n\\end{proof}\n\n\\noindent\nOur query algorithm works as follows. \nFor each candidate point $c \\in C$, \\Cref{alg:query} \nconstructs $B'_1(c_1, \\max \\{\\delta, \\radius{c} \\})$ and $B'_2(c, \\radius{c})$. \nIf the candidate $c$ equals the current $c_2$, then we have $B_1 = B'_1$. \nSince $\\radius{c_2} \\leq r \\leq \\delta/2$ by invariant (b), and $B'_2 \\subset B_2$,\nwe do not need to construct any new set. \nFor $c \\neq c_2$, we know that $B_1 \\subset B'_1$, and hence,\nwe only need to see which points in $\\Buffer \\cap B_2$ are inside $B'_1$.\nWhen $|B_2| \\geq \\dz$ and $c \\neq c_2$, then it means that $c_p \\not \\in B_2^*$. \nTherefore, by Lemma \\ref{lem:B2dz}, $B_2$ can be added to $B'_1$ without violating invariant (c). \nSo in this case, we just need to see which points of $\\Buffer$ must be added to $B'_1$. \n\\Cref{alg:query} uses functions \\textproc{AddToB$'_1$} and \\textproc{AddToB$'_2$} \nfor adding a point to $B'_1$ and $B'_2$ respectively. \nThese functions are the same as \\textproc{AddToB$_1$} and \\textproc{AddToB$_2$},\nwith the only exception that they add points to $B'_i$ instead of $B_i$, for $i = 1, 2$.\n\nSince \\Cref{alg:query} considers all valid candidates for $c$, \nat least for one $c^* \\in C$, we have $c^* \\in B_2^*$. \nWe denote the corresponding $B'_1$ and $B'_2$ by $B''_1$ and $B''_2$. \nSince by Observation \\ref{obs:c+4},\n$1 \\leq \\frac{\\len{c_1 c^*}}{\\alpha^*} < \\frac{\\len {c_1 c^*}}{\\alpha r^*}$, \nwe have $2r^* \\leq \\radius{c^*}$, and hence\nby Lemma~\\ref{lem:2r}, $B^*_1 \\subset B''_1$ and $B^*_2 \\subset B''_2$.\nOn the other hand, since the distance of the new points added to $B''_1$ \n%compare to $B_1$ \nis less than $\\len{c_1 p} \\leq \\max \\{\\delta, \\radius{c^*} \\}$, \nwe have by invariant~(c) that  $B''_1 \\cap B_2^* = \\emptyset$.\nAs a result, $B''_1$ (resp., $B''_2$) completely covers $B_1^*$  (resp., $B_2^*$), \nand the points in $\\Buffer$ are all outliers.\nThe only unknown part is that \\Cref{alg:query} does not know how many outliers are in $B''_1$ and $B''_2$.\nTherefore, \\Cref{alg:compute-min} tries all possible cases and choose the one with the minimum radius.\n\n\n% --------------------------- Estimating r ----------------------\n\n\n\n\\section{Estimating $r$}\n\\label{sec:estimate}\n\nIn this section, we show how to obtain a value $r$,\nsuch that $1.2r^* \\le r < (1.2 + 2\\eps/3)r^*$.\nThe following lemma provides the main ingredient.\n\n\\begin{lemma}\n\\label{lem:2-approx}\n\tGiven a point set $P$ in $\\IR^d$,\n\tan optimal solution to the 1-center problem with $z$ outliers on $P$\n\tgives a $(2 + {\\alpha \\over 2})$-approximation for\n\tthe 2-center with $z$ outliers on $P$,\n\tprovided that $\\delta^* \\le \\alpha r^*$.\n\\end{lemma}\n\n\n\\begin{proof}\nLet $r_1^*$ and $r^*$ be the optimal radii for\nthe 1-center and 2-center problems with $z$ outliers on $P$, respectively.\nIt is clear that $r^* \\le r_1^*$,\nbecause any feasible solution $B^*$ for 1-center with $z$ outliers\nyields a feasible solution $(B^*, B^*)$ for 2-center with $z$ outliers.\n%Let $B^*$ be an optimal solution for the 1-center problem with $z$ outliers. \n%Then, $(B^*, B^*)$ is a feasible solution for the 2-center problem with $z$ outliers. \n%Hence, $r_2^* \\le r_1^*$.\nNow, suppose that $B_1^*(c_1^*, r^*)$ and $B_2^*(c_2^*, r^*)$\nare the balls in an optimal solution for the 2-center problem with $z$ outliers.\nLet $c$ be the midpoint of the segment connecting \n$c_1^*$ to $c_2^*$ (see Figure~\\ref{fig:2lt1}).\nClearly, $B\\left(c, \\frac{\\delta}{2} + 2r^*\\right)$ covers both $B_1^*$ and $B_2^*$. \nTherefore, it is a feasible solution for the 1-center problem with $z$ outliers.\nHence, $ r_1^* \\le \\left(2 + \\frac{\\alpha}{2}\\right) r^*$.\n\\end{proof}\n\n\\begin{figure}[t]\n\t\\centering\n\t\\includegraphics[width=19em]{figs/2lt1}\n\t\\caption{Proof of Lemma~\\ref{lem:2-approx}}\n\t\\label{fig:2lt1}\n\\end{figure}\n\n\\noindent \nThe following is a direct corollary of Lemma~\\ref{lem:2-approx} and \\Cref{thm:1-center}.\n\n\\begin{cor} \\label{cor:4-approx}\n\tIf $\\delta^* \\le \\alpha r^*$, \n\t\\Cref{alg:1-center} computes a $(4 + \\alpha)$-approximation to $r^*$. \n\\end{cor}\n\n\n%\\begin{obs}\n%\\label{obs:2apr}\n%Let $r_1$ and $k_0$ be two positive real numbers. Define $k=k_0 2^i$ to be the smallest real number satisfying the inequality $k \\ge r_1$, where $i$ is a non-negative integer. Clearly, $k$ is a $2$-approximation for $r_1$.\n%\\end{obs}\n\n%We maintains $m=\\ceil{{1.2 (3 \\alpha+12)}/{\\eps}}$ candidate lengths.\n%For each candidate length $r$, we run an instance of Algorithm~\\ref{alg:smallc}. \n\nWe use \\Cref{alg:1-center} to find an estimate for $r$. \nLet $r_i$ be the radius calculated by \\Cref{alg:1-center} after receiving\nthe $i$-th point, $p_i$.\nClearly, the sequence of $r_i$'s is increasing.\n%We use a doubling strategy, similar o what is used in~\\cite{zarrabi2008core}.\nLet $k$ be an integer such that $2^{k-1} \\le r_i \\le 2^{k}$, and set $\\ell_i = 2^{k}$.\n(If $r_i = 0$, we set $\\ell_i = 0$.)\n%Let $l_1=r_1$ and $l_i=2^j l_1$, where $l_i$ is the smallest number satisfying $l_i \\ge r_i$. \nObviously, $\\ell_i \\le 2 r_i$,\nand hence, by Corollary~\\ref{cor:4-approx}, \n$\\ell_i$ is a $(8 + 2\\alpha)$-approximation to $r^*$.\n\nWe divide the interval $(0, 1.2 \\ell_i]$ \ninto $m=\\ceil{{1.2 (3 \\alpha+12)}/{\\eps}}$ equal segments,\n% (Figure~\\ref{fig:findr}), then \neach of length $t_i = 1.2 \\ell_i / m$.\nClearly,  $t_i \\le (2\\eps/3) r^*$.\nTherefore, in the set\n$R_i = \\set{j \\times t_i \\provided j = 1, \\dots, m}$,\nthere is at least one value $r$ for which the  \ninequality $1.2 r^* \\le r \\le (1.2 + \\frac{2\\eps}{3})r^*$ holds.\n\n%\\begin{figure}[h]\n%\t\\centering\n%\t\\includegraphics[width=21em]{figs/findr}\n%\t\\caption{Subdivision of the interval $(0, 1.2 \\ell_i]$}\n%\t\\label{fig:findr}\n%\\end{figure}\n\n%When the first non-zero radius is observed, $l_1$ is set. \nWe run $m$ instances of Algorithm~\\ref{alg:smallc} for each value $r \\in R_i$ in parallel. \n%for all the previous points, which have been stored in a buffer. It is not hard to see that the space complexity for storing these points is $\\O(z)$. \nWhenever a new point $p_i$ is added, \nif $\\ell_i=\\ell_{i-1}$, then $R_i = R_{i-1}$,\nand the new point is inserted to all parallel instances. %corresponding to candidates in $L_i$. \n%Otherwise, Algorithm~\\ref{alg:smallc} should be executed for all of the candidates in $L_i$, with all the points. But this is not achievable due to space limitations. \nIf $\\ell_i > \\ell_{i-1}$, then the set $R_i$ has two types of values.\nThose values in $R_i$ which are less than $1.2\\ell_i$ are also present in $L_{i-1}$,\nbecause $t_i / t_{i-1}$ is a positive power of 2.\nFor these values, we continue executing the corresponding instance.\nIf a value $r \\in R_i$ is not present in $R_{i-1}$, \nthen we have $r \\ge 1.2 \\ell_{i - 1} \\ge \\ell_{i-1}$.\n%To overcome this problem, note that if the candidate $x_j=j \\times t_i \\in L_i$ is also in $L_{i-1}$, there is no need to start Algorithm~\\ref{alg:smallc} over and the current execution will be continued. If $x_j \\notin L_{i-1}$, then it is certain that $x_j \\ge l_{i - 1}$ (Observe that $l_i=ul_{i-1}$, for some $u\\in \\mathbb{N}$). \nSince those points not lying in the candidate solution \nare saved in the buffer of Algorithm~\\ref{alg:1-center} (which has size at most $z$), \nall non-outlier points of this algorithm lie in the candidate balls of Algorithm~\\ref{alg:smallc} which has center $p_1$ and radius at most $l_{i-1}$. \nThese outliers have been stored in a buffer. \nSince Algorithm~\\ref{alg:smallc} maintains two balls with radius at least $r$, \none of which (say $B_1$) is centered at $p_1$, \nthen all non-outlier points of Algorithm~\\ref{alg:1-center} are in $B_1$,\nand hence, they do not make any transition in the states of Algorithm~\\ref{alg:smallc}.\nTherefore, for any new value $r$, \nit suffices to execute Algorithm~\\ref{alg:smallc} with only the \noutlier points in the buffer of Algorithm~\\ref{alg:1-center}.\n%Overall, we get the following result.\n\n%\\begin{theorem}\n%\\label{thm:1st-cmplx}\n%Algorithm~\\ref{alg:smallc} uses $\\O(\\frac{dz^3}{\\eps})$ space, and takes $\\O(\\frac{dz^4}{\\eps})$ and $\\O(\\frac{dz^3}{\\eps})$ time for update and query, respectively.\n%\\end{theorem}\n\n\n% --------------------------- Invariant (c) ----------------------\n\n\n\n\\section{Proof of Invariant (c)}\n\\label{app:inv-c}\n\nHere, we provide a proof for Invariant (c).\n%We first prove the following technical claim.\nThe following technical claim will be used in our proof.\n\n\\begin{claim}\n\t\\label{claim:c}\n\tIf $c_2$ is set, then\n\t$B(c_p, \\radius{c_p}) \\subseteq B_2(c_2, r)$.\n\\end{claim}\n\n\\begin{proof}\nIf $|B_2| < \\dz$, then $c_p = c_2$ and $r = \\radius{c_2}$, \nand hence, $B_2 = B(c_p, \\radius{c_p})$. \nWhen the size of $B_2$ reaches $\\dz$, \nthe central point $\\cp$ moves to the centerpoint of $B_2$,\nand $\\rc$ is increased by a factor of $(2 + \\frac{2}{\\alpha})$. \nBecause the centerpoint of $B_2$ lies in $B_2$, then $c_p \\in B(c_2, \\radius{c_2})$.\nThus, if $|B_2| \\ge \\dz$ then $\\len{c_2 c_p} \\leq \\radius{c_2}$, and therefore,\n$$\n\t\\radius{c_p} \\leq \\frac{2 (\\len{c_1 c_2} + \\len{c_2 c_p})}{\\alpha} \\leq \\radius{c_2}(1 + \\frac{2}{\\alpha}).\n$$ \nHence, $B(c_p, \\radius{c_p}) \\subseteq B_2(c_2, \\radius{c_2}(2 + \\frac{2}{\\alpha}))$.\n\\end{proof}\n\n\\noindent\nNow, we prove Invariant (c),\nwhich states $B_1 \\cap B_2^* = \\emptyset$.\n\n\\begin{proof}\nA point $p$ can be added to $B_1$ in two cases. % by \\Cref{alg:case-1}. \nThe first case is in function \\textproc{AddToB$_1$}, \nwhere the point is added to $B_1$ only if it is within distance $\\delta$ of the center $c_1$,  \n%when $\\len{pc_1} \\leq \\delta$, \nwhich by invariant (a), \nguaranties $\\len{pc_1} < \\delta^*$. \nTherefore, $p \\not \\in B_2^*$ in this case.\n\nThe second case is in \\Cref{alg:case-1}, when the buffer overflows and $B_2$ is non-empty.\nThe algorithm takes one of the following actions depending on the size of $B_2$.\nIf $|B_2| < \\dz $, then $c_2 = c_p$.\nAlgorithm~\\ref{alg:case-1} adds $c_2$ to $B_1$.\nSuppose by way of contradiction that $c_p \\in B_2^*$.\nThen, by invariants (b) and (d1), \n$2r^* \\leq r \\leq \\delta/2 < \\delta^*/2$. \nTherefore, by Lemma \\ref{lem:2r}, there must be at most $z$ points outside $B_1 \\cup B_2$,\nwhich contradicts the overflow of the buffer. \nIf $|B_2| \\geq \\dz$, then $c_p$ is the centerpoint of the first $\\dz$ points currently in $B_2$. \nIn this case, we add all points of $B_2$ to $B_1$. \nBy invariant (b), $r \\leq \\delta/2 < \\delta^*/2$. \nTherefore, By Lemma \\ref{lem:center-point}, $c_p \\in B_1^*$ or $c_p \\in B_2^*$. \nSuppose by way of contradiction that $c_p \\in B_2^*$. \nIn this case, by invariant (d1) and Claim~\\ref{claim:c}, % that we proved first,\n$B_2$ covers $B(c_p, \\radius{c_p})$ and $2r^* \\leq r$. \nTherefore, Similar to the previous part, it contradicts the overflow of the buffer. \n\\end{proof}\n\n\\end{document}\n", "meta": {"hexsha": "59996342ea6705b9b085397dd1ac5fb799c6de08", "size": 65039, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "outlier.tex", "max_stars_repo_name": "behnamhatami/CCCG2015", "max_stars_repo_head_hexsha": "892ae9545105994da14c7bc689418f572df0ca94", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "outlier.tex", "max_issues_repo_name": "behnamhatami/CCCG2015", "max_issues_repo_head_hexsha": "892ae9545105994da14c7bc689418f572df0ca94", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "outlier.tex", "max_forks_repo_name": "behnamhatami/CCCG2015", "max_forks_repo_head_hexsha": "892ae9545105994da14c7bc689418f572df0ca94", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9867812293, "max_line_length": 679, "alphanum_fraction": 0.6801150079, "num_tokens": 21755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725053, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.32987802343849526}}
{"text": "\\documentclass[12pt, answers]{exam}\n%\\documentclass[12pt]{exam}\n\\RequirePackage{amssymb, amsfonts, amsmath, latexsym, verbatim, xspace, setspace}\n\\RequirePackage{tikz, pgflibraryplotmarks}\n\\usepackage[margin=1in]{geometry}\n\\usepackage{enumerate, paralist}\n\\parindent 0ex\n\n\\onehalfspacing\n\n\\usepackage{amsthm}\n\\usepackage{epsfig}\n\\usepackage{times}\n\\renewcommand{\\ttdefault}{cmtt}\n\\usepackage{graphicx} % for graphics files\n\n% The float package HAS to load before hyperref\n\\usepackage{float} % for psuedocode formatting\n\n% from Denovo Methods Manual\n\\usepackage{mathrsfs}\n\\usepackage[mathcal]{euscript}\n\\usepackage{color}\n\\usepackage{array}\n\n\\usepackage[pdftex]{hyperref}\n\\usepackage[parfill]{parskip}\n\n% math syntax\n\\newcommand{\\nth}{n\\ensuremath{^{\\text{th}}} }\n\\newcommand{\\ve}[1]{\\ensuremath{\\mathbf{#1}}}\n\\newcommand{\\Macro}{\\ensuremath{\\Sigma}}\n\n%---------------------------------------------------------------------------\n\\begin{document}\n\\begin{center}\n{\\bf NE 155, Class 3, S21 \\\\\nTypes of Equations in the Engineering Fields \\\\ January 26, 2021}\n\\end{center}\n\n\\setlength{\\unitlength}{1in}\n\\begin{picture}(6,.1) \n\\put(0,0) {\\line(1,0){6.25}}         \n\\end{picture}\n\n\\noindent \\textbf{Introduction}\n\nIn science and engineering in general, and nuclear engineering and reactor analysis in specific, we encounter a wide range of mathematical physics equations. In today's lecture we will introduce some of them.\n%\n\\begin{itemize}\n\\item Ordinary differential equations (ODEs)\n\\item Partial differential equations (PDEs)\n  \\begin{itemize}\n  \\item Elliptic PDEs\n  \\item Parabolic PDEs\n  \\item Hyperbolic PDEs\n  \\end{itemize}\n\\item Integro-differential equations\n\\item Integral equations\n\\end{itemize}\n\n%------------------------------------------------------------------------------\n\\section{ODEs}\nThe most general form of an \\nth order linear ordinary differential eqn.\\ is\n%\n\\ifprintanswers\n\\begin{equation}\na_{n}(x)y^{(n)}(x) + a_{n-1}(x)y^{(n-1)}(x) + \\cdots + a_{2}(x)y^{(2)}(x) + a_{1}(x)y'(x) + a_0(x)y(x) = f(x) \\nonumber\n\\end{equation}\n\\else\n \\\\ \\\\ \n \\hspace*{8em}\\textit{Equation here}\\\\\n\\fi\n%\n\\noindent where\n\\begin{itemize}\n\\item $a_n$ are coefficients\n\\item $y^{(n)}$ is the \\nth derivative of $y$.\n\\end{itemize}\n\nBoundary conditions:\n\\begin{enumerate}\n\\item Initial Value Problem (\\textbf{IVP}): if $y$ and its derivatives are given at one end of the domain/interval (e.g.\\ time zero if there's time or spatial starting point if there's only space, etc.)\n\\item Boundary Value Problem (\\textbf{BVP}): if $y$ and/or its derivatives are given at \\underline{each} end of the interval\n\\end{enumerate}\n\n\\vspace*{1em}\n\\textbf{Linear 1st order ODE's}\n\n\\underline{Reminders}\n\\begin{itemize}\n\\item 1st order means that $n=1$. The  coefficients $a_1$ and $a_0$ may depend on $y$ or $y'$.\n\\item Linear means each coefficient only depends on $x$ (i.e., not on $y$ or derivatives of $y$).\n\\end{itemize}\n\n%-------------------------------------------------------------\n\\underline{Linear 1st order ODE Example}:\n\\ifprintanswers\n\\begin{equation}\n\\frac{dy}{dx} + 3y(x) = \\sin(x) \\qquad x \\in [0, 1] \\nonumber\n\\end{equation}\n\\else\n \\\\ \\\\ \n \\hspace*{8em}\\textit{Equation here}\n\\fi\n%\n%\n\\begin{itemize}\n\\item IVP if boundary conditions are $y$(0) = 1; $y$'(0) = 2\n\\item BVP if boundary conditions are $y$(0)=-1, $y$(1) = 3 \n\\end{itemize}\n%\nIn this case the general solution is obtained through the use of an integrating factor.\n\n\\vspace*{1em}\n\\noindent \\underline{Linear 1st order ODE Example}:\n\nPoint Kinetics analysis of a nuclear reactor is an IVP, linear, 1st order ODE.\n%\n\\ifprintanswers\n\\begin{align}\n\\frac{dn(t)}{dt} &= \\frac{\\rho(t) - \\beta}{l^*}n(t) + \\sum_{i=1}^{N} \\lambda_i C_i(t) \\nonumber \\\\\n%\n\\frac{dC_i(t)}{dt} &= \\frac{\\beta_i}{l^*}n(t) - \\lambda_i C_i(t) \\qquad i=1,\\dots,N \\nonumber\n\\end{align}\n\\else\n \\\\ \\\\ \n \\hspace*{8em}\\textit{Equations here}\\\\ \\\\\n\\fi\n%\nWhere (we'll talk  more about what these terms mean later)\n%\n\\begin{itemize}\n\\item $n$ = \\# neutrons / s\n\\item $\\beta$ = fraction of delayed neutrons\n\\item $\\lambda_i$ = effective decay constant of the $i$th precursor\n\\item $C_i(t)$ = delayed neutron concentration of the $i$th precursor\n\\item $l^*$ = mean neutron lifetime\n\\item $\\rho = \\frac{k-1}{k}$ = reactivity\n\\end{itemize}\n%\nBCs: $n(0) = n_0$ and $C_i(0) = C_{i,0}$ for $i=1,\\dots,N$.\n\n%-------------------------------------------------------------\n\\vspace*{1em}\n\\noindent \\underline{Linear 1st order ODE Example}:\n\nThe number of atoms in a sample during radioactive decay (assuming decay only here) is described by the Bateman equation, which is a linear, 1st order ODE that is in an IVP:\n%\n\\ifprintanswers\n\\begin{align}\n\\frac{dN_1(t)}{dt} &= -\\lambda_1 N_1(t) \\nonumber \\\\\n\\frac{dN_i(t)}{dt} &= -\\lambda_i N_i(t) + \\lambda_{i-1}N_{i-1}(t) \\qquad 1 < i < I \\nonumber\\\\\n\\frac{dN_I(t)}{dt} &= \\lambda_{I-1} N_{I-1}(t) \\nonumber \\\\\n\\text{BC: }& N_i(t=0) = N_{i,0}\\nonumber\n\\end{align}\n\\else\n \\\\ \\\\ \n \\hspace*{8em}\\textit{Equations here}\\\\ \\\\\n\\fi\n%\nnote: isotope $i$ decays into $i+1$. This can be adapted for decay branches, and becomes more complicated if we have neutrons that transmute isotopes. \n\n%-------------------------------------------------------------\n\\vspace*{1em}\n\\underline{2nd order ODE Example}:\n\n\\ifprintanswers\n\\begin{align}\n-\\frac{d}{dx}p(x) \\frac{d}{dx}\\phi(x) &+ q(x)\\phi(x) = S(x) \\nonumber \\\\\n\\text{defined for }& \\alpha \\le x \\le \\beta \\nonumber \\\\\n\\text{BC: }& a\\frac{d\\phi}{dx} + \\gamma \\phi = \\sigma \\qquad \\text{at } x=\\alpha \\text{ and } x = \\beta \\text{ (BVP)}\\nonumber\n\\end{align}\n\\else\n \\hspace*{8em}\\textit{Equations here}\\\\\n\\fi\n%\nThis has\n\\begin{itemize}\n\\item \\textbf{Neumann} BCs if $\\gamma = 0$ (specifies the values that the \\textit{derivative} of a solution is to take on the boundary of the domain)\n\\item \\textbf{Dirichlet} BCs: if $a=0$ (specifies the values that a \\textit{solution} is to take on the boundary of the domain)\n\\item \\textbf{Mixed} BCs if [$\\gamma \\ne 0$ and $a = 0$ at $x = \\alpha$] and [$a \\ne 0$ and $\\gamma = 0$ at $x = \\beta$] (the solution is required to satisfy a Dirichlet or a Neumann boundary condition in a mutually exclusive way on disjoint parts of the boundary)\n\\item If $S(x)$ is nonzero at least somewhere over the physical range, a unique solution exists.\n\\end{itemize}\n\n%-------------------------------------------------------\n\\vspace*{1 em} \\underline{Reminder: eigenpairs}\n\nWe can formulate systems of equations as matrix-vector systems that look like \\ve{A}$\\vec{x} = \\lambda \\vec{x}$. \n\\begin{itemize}\n\\item An eigenvector is a non-zero vector $\\vec{x}$ that, when multiplied by the matrix \\ve{A}, yields a constant multiple of $\\vec{x}$. \n\\ifprintanswers\n\\item The constant multiple, $\\lambda$, is the eigenvalue corresponding to the eigenvector.\n\\else\n \\item \\textit{Text here}\n\\fi\n\\item There can be (and usually are) more than one eigenvalue, and more than one eigenvector. \n%\\item Several eigenvectors can have the same eigenvalue\n\\item Sometime the equation can be reformulated as as $\\vec{y}\\ve{A} = \\alpha \\vec{y}$ (the left eigenvector). In nuclear, we're used to seeing the right eigenvector formulation.\n\\end{itemize}\n\n\n%-------------------------------------------------------------\n\\vspace*{1em}\n\\underline{2nd order ODE Example}:\n\nThe homogeneous equation %[If  $\\phi(x)$  is a solution, so is  $c \\phi(x)$, where $c$ is an arbitrary (non-zero) constant. Note that in order for this condition to hold, each term in a linear differential equation of the dependent variable $y$ must contain $y$ or any derivative of $y$; a constant term breaks homogeneity]:\n%\n\\begin{align}\n-\\frac{d}{dx}p(x) \\frac{d}{dx}\\phi(x) &+ q(x)\\phi(x) = \\lambda f(x) \\phi(x) \\nonumber \\\\\n\\text{where }p(x) > 0, \\:f(x) \\geq 0,\\: &\\lambda = \\text{ eigenvalue;}\\nonumber \\\\\n\\frac{d\\phi}{dx} + \\gamma_L \\phi &= \\Macro \\qquad \\text{at }x=\\alpha \\qquad \\gamma_L \\geq 0  \\nonumber \\\\\n\\frac{d\\phi}{dx} + \\gamma_R \\phi &= \\Macro \\qquad \\text{at }x=\\beta \\qquad \\gamma_R \\geq 0\\nonumber \n\\end{align}\n%\nis known as the \\underline{Sturm-Liouville} eigenvalue problem. (If $\\gamma_L = \\gamma_R = 0$, the BCs become $\\phi(\\alpha) = \\phi(\\beta) = 0$.)\n\nThe solution has an infinite number of eigenfunctions, $\\phi_i(x)$ with corresponding \\textbf{REAL} and \\textbf{DISTINCT} eigenvalues, $\\lambda_i$. \n\n\\ifprintanswers\nIf we number them in sequence: $\\lambda_0 < \\lambda_1 < \\lambda_2 < \\dots < \\lambda_{\\infty}$, then $\\lambda_0$ is the lowest eigenvalue and $\\phi_0(x)$ is the fundamental eigenmode. \n\nIf $q(x) \\geq 0$, then all $\\lambda_i$ are positive.\n\\else\n \\vspace*{1em} \\hspace*{8em} \\textit{Text here} \n\\fi\n\n%-------------------------------------------------------------\n\\vspace*{1em}\n\\underline{2nd order ODE Example}:\n\n1-D, 1-group, time-independent neutron diffusion equation:\n%\n\\begin{align}\n-\\frac{d}{dx}D(x)\\frac{d}{dx}\\phi(x) + \\Macro_a(x)\\phi(x) &= S(x) \\qquad \\text{Fixed Source} \\nonumber \\\\\n-\\frac{d}{dx}D(x)\\frac{d}{dx}\\phi(x) + \\Macro_a(x)\\phi(x) &= \\frac{1}{k} \\nu \\Macro_f(x) \\phi(x)\\qquad \\text{Fission / Eigenvalue} \\nonumber\n\\end{align}\n%\nBCs: (BVP) vacuum, $\\phi(\\pm a) = 0$\n\n\n\\textbf{Aside:} Recall\n%\n\\begin{align}\n\\text{gradient is } \\nabla T &= \\vec{i}\\frac{\\partial T}{\\partial x} + \\vec{j}\\frac{\\partial T}{\\partial y} + \\vec{k}\\frac{\\partial T}{\\partial z} \\nonumber \\\\\n%\n\\text{divergence is } \\nabla \\cdot \\vec{v} &= \\frac{\\partial v_x}{\\partial x} + \\frac{\\partial v_y}{\\partial y} + \\frac{\\partial v_z}{\\partial z} \\nonumber\n\\end{align}\n\n%-------------------------------------------------------------\n\\section{PDEs}\n\nA partial differential equation is an equation containing an unknown function of two or more variables and its derivatives with respect to those variables. \n\nIf the PDE is linear in $u$ and all derivatives of $u$, then we say that the PDE is linear.\n%\n\\ifprintanswers\n\\begin{equation}\nA\\frac{\\partial^2 u}{\\partial x^2} + B\\frac{\\partial^2 u}{\\partial x \\partial  y} + C\\frac{\\partial^2 u}{\\partial y^2} + D\\frac{\\partial u}{\\partial x} + E\\frac{\\partial u}{\\partial y} + Fu(x,y) = G \\nonumber\n\\end{equation}\n\\else\n \\\\ \\\\ \\hspace*{8em}\\textit{Equation here}\\\\ \\\\\n\\fi\n%\nThis equation is a 2nd order PDE in two variables. It is linear if $A$ through $G$ do not depend on $u$ (they may depend on $x$ and/or $y$). \n%If $A^2 + B^2 + C^2 > 0$ over a region of the $xy$ plane, the PDE is second-order in that region (analogous to the eqn.\\ for a conic section: $Ax^2 + Bxy + Cy^2 + \\cdots = 0$. \n\n%-------------------------------------------------------------\n%-------------------------------------------------------------\n\\vspace*{1em}\n\\underline{Classification of PDEs}:%http://en.wikipedia.org/wiki/Partial_differential_equation#Classification\n\nJust as one classifies conic sections and quadratic forms into parabolic, hyperbolic, and elliptic based on the discriminant $B^2 - 4AC$, the same can be done for a second-order PDE at a given point. \n\n[To think about classification, think about replacing $\\partial x$ by $x$ and  $\\partial y$ by $y$ (formally this is done via Fourier transform). This converts the PDE into a polynomial of the same degree.]\n\n\\textit{Note:} these classifications only apply to second order PDEs. \n\n\\noindent The reason we care about this in the context of the Transport Equation:\n\\ifprintanswers\n\\begin{itemize}\n\\item In a void, the transport equation is like a \\textit{hyperbolic} wave equation. \n\\item For highly-scattering regions where $\\Macro_{s}$ is close to $\\Macro$, the equation becomes \\textit{elliptic} for the steady-state case. \n\\item If the scattering is forward-peaked then the equation is \\textit{parabolic}.\n\\end{itemize}\n\\else\n \\\\ \\\\  \\hspace*{8em} \\textit{Text here} \n\\fi\n\nLet's look at the classifications:\n%-------------------------------------------------------------\n\\begin{itemize}\n\\item \\textbf{Elliptic} if $B^2 - 4 AC < 0$. %Solutions of elliptic PDEs are as smooth as the coefficients allow within the interior of the region where the equation and solutions are defined. For example, solutions of Laplace's equation are analytic within the domain where they are defined, but solutions may assume boundary values that are not smooth. The motion of a fluid at subsonic speeds can be approximated with elliptic PDEs, and the Euler–Tricomi equation is elliptic where $x < 0$. \n\nSome famous elliptic PDEs:\n\\begin{align*}\n\\nabla^2 u &= 0 \\qquad \\text{Laplace's eqn.} \\nonumber \\\\\n\\nabla^2 u &= f(x) \\qquad \\text{Poisson's eqn.} \\nonumber \\\\\n-\\frac{\\partial}{\\partial x}D(x,y)\\frac{\\partial}{\\partial x}\\phi(x,y) &- \\frac{\\partial}{\\partial y}D(x,y)\\frac{\\partial}{\\partial y}\\phi(x,y) + \\bigl(\\Macro_a(x,y) - \\frac{1}{k} \\nu \\Macro_f(x,y)\\bigr) \\phi(x,y) = 0\\nonumber\n\\end{align*}\nFor each of these there's no $B$ term, so $-4AC < 0$ (in the diffusion equation case since $D(x,y)$ is positive).\n\nOne property of constant coefficient elliptic equations is that their solutions can be studied using the Fourier transform. %http://mathworld.wolfram.com/EllipticPartialDifferentialEquation.html\n\n %------------------------------------------------------------- \n\\item \\textbf{Parabolic} if $B^2 - 4 AC = 0$, e.g.\n\\ifprintanswers\n\\begin{align}\n\\frac{\\partial u}{\\partial t} &= k \\frac{\\partial^2 u}{\\partial x^2} \\qquad \\text{ 1-D heat eqn.} \\nonumber \\\\\n\\frac{1}{v}\\frac{\\partial \\phi(x,t)}{\\partial t} &= \\frac{\\partial}{\\partial x}D(x,t)\\frac{\\partial}{\\partial x}\\phi(x,t) + \\bigl(\\nu \\Macro_f(x,t)\\ - \\Macro_a(x,t)\\bigr) \\phi(x,t) + S(x,t)\\nonumber\n\\end{align}\n\\else\n \\\\ \\\\ \\hspace*{8em}\\textit{Equations here}\\\\ \\\\\n\\fi\nThere aren't $B$ or $C$ terms, so $-4AC = 0$\n\nEquations that are parabolic at every point can be transformed into a form analogous to the heat equation by a change of independent variables. Solutions smooth out as the transformed time variable increases.\n\\end{itemize}\n\nA perturbation of the initial (or boundary) data of an \\textit{elliptic or parabolic} equation is felt at once by essentially all points in the domain. \n\n%-------------------------------------------------------------\n\\begin{itemize}\n\\item \\textbf{Hyperbolic} if $B^2 - 4 AC > 0$, e.g.\n\\begin{align*}\n\\frac{\\partial^2 u}{\\partial t^2} &- c^2\\frac{\\partial^2 u}{\\partial x^2} = 0 \\qquad \\text{ 1-D wave eqn.} \\nonumber\n\\end{align*}\nThere's no $B$ term, and the $C$ term is negative so $-4AC > 0$\n  \\begin{itemize}\n  \\item if $u$ and its first $t$ derivative are arbitrarily specified with initial data on the initial line $t= 0$ (with sufficient smoothness properties), then there exists a solution for all of $t$.\n  \\item The solutions of hyperbolic equations are ``wave-like.\" If a disturbance is made in the initial data of a hyperbolic differential equation, then not every point of space feels the disturbance at once.\n  \\item Relative to a fixed time coordinate, disturbances have a finite propagation speed. They travel along the characteristics of the equation.\n  \\end{itemize}\n \n%The Euler–Tricomi equation has parabolic type on the line where $x = 0$.\n\\end{itemize}\n\n%-------------------------------------------------------------\n\\vspace*{1 em}  \\underline{higher order PDE classification}\\\\\nIf there are $n$ independent variables $x_1, x_2 , \\dots, x_n$, a general linear partial differential equation of second order has the form\n%\n\\begin{equation}\nLu = \\sum_{i=1}^n \\sum_{j=1}^n a_{i,j} \\frac{\\partial^2 u}{\\partial x_i x_j} + \\text{ Lower Order Terms } = 0 \\nonumber\n\\end{equation}\n%\nThe classification depends upon the signature of the eigenvalues of the coefficient matrix $a_{i,j}$.\n\\begin{enumerate}\n\\item \\underline{Elliptic}: The eigenvalues are all positive or all negative.\n\\item \\underline{Parabolic}: The eigenvalues are all positive or all negative, save one that is zero.\n\\item \\underline{Hyperbolic}: There is only one negative eigenvalue and all the rest are positive, or there is only one positive eigenvalue and all the rest are negative.\n\\item \\underline{Ultrahyperbolic}: There is more than one positive eigenvalue and more than one negative eigenvalue, and there are no zero eigenvalues. There is only limited theory for ultrahyperbolic equations (Courant and Hilbert, 1962).\n\\end{enumerate}\n\n%%-------------------------------------------------------------\n%\\vspace*{1em}\n%\\noindent \\underline{Elliptic example}:\n%\n%\\noindent Poisson's equation (stationary heat conduction with a volumetric source):\n%%\n%\\begin{equation}\n%\\nabla \\cdot (k \\nabla T) + q''' = 0 \\nonumber\n%\\end{equation}\n%% \n%where\n%\\begin{itemize}\n%\\item $T$ is temperature\n%\\item $k$ is thermal conductivity\n%\\item $q'''$ is volumetric heat generation rate\n%\\end{itemize}\n%%\n%There's no $B$ term, so $-4AC < 0$ since $k$ is positive.\n%\n%%\\begin{itemize}\n%\\item Dirichlet BCs if $f(a,b) =$ constant\n%\\item Neumann BCs if \n%\\begin{equation}\n%\\vec{n} \\cdot \\nabla f = n_x \\frac{\\partial f} {\\partial x} + n_y \\frac{\\partial f} {\\partial y}  +n_z \\frac{\\partial f} {\\partial z} \\nonumber\n%\\end{equation}\n%\\end{itemize}\n%\n%%-------------------------------------------------------------\n%\\vspace*{1em}\n%\\noindent \\underline{Parabolic Examples}:\n%\n%Transient heat conduction in a slab:\n%%\n%\\begin{equation}\n%\\frac{\\partial T(x,t)}{\\partial t} = \\frac{\\partial}{\\partial x} \\frac{k}{\\rho c} \\frac{\\partial}{\\partial x} T(x,t) + q'''(x,t) \\nonumber\n%\\end{equation}\n%%\n%where $\\rho$ = mass density and $c$ = specific heat capacity\n%\n%\\noindent There aren't $B$ or $C$ terms, so $-4AC = 0$\n%\n%\n%\\vspace*{2em}\n%(2) Time-dependent, 1-group neutron diffusion equation\n%%\n%\\begin{equation}\n%\\frac{1}{v} \\frac{\\partial \\phi(x,t)}{\\partial t} = \\frac{\\partial}{\\partial x} D \\frac{\\partial}{\\partial x} \\phi(x,t) + (\\nu \\Macro_f - \\Macro_a) \\phi(x,t) + S(x,t) \\nonumber\n%\\end{equation}\n%%\n%There aren't $B$ or $C$ terms, so $-4AC = 0$\n%\n%%-------------------------------------------------------------\n%\\vspace*{1em}\n%\\noindent \\underline{Hyperbolic Example}:\n%\n%(1) The wave equation\n%%\n%\\begin{equation}\n%\\frac{\\partial^2 f}{\\partial t^2} - c \\frac{\\partial^2 f}{\\partial x^2} = 0\n%\\end{equation}\n%%\n%where $f(x,t)$ is the displacement and $c$ is the speed of wave propagation.\n%\n%\\noindent There's no $B$ term, and $C$ is negative so $-4AC > 0$\n%\n%%\\noindent \\textbf{1st order Hyperbolic equations}\n%\n%For a system of the form\n%%\n%\\begin{equation}\n%\\frac{\\partial u}{\\partial t} + A \\frac{\\partial u}{\\partial x} + B u = F(t,x)\n%\\end{equation}\n%%\n%is hyperbolic if the matrix $A$ is diagonalizable with real eigenvalues.\n%\n%Diagonalizable means there is a nonsingular matrix $P$ such that\n%%\n% \\begin{align}\n%    PA^{-1}P &=    &=    \\begin{pmatrix}\n%      a_{1} & 0 & 0 & \\cdots & 0 \\\\\n%      0 & a_{2} & 0 & \\cdots & 0 \\\\\n%      0 & 0 & a_{3} & \\cdots & 0 \\\\\n%      \\vdots & \\vdots & \\vdots & \\ddots   & \\vdots \\\\\n%      0 & 0 & 0 & \\cdots & a_{d} \\\\\n%    \\end{pmatrix} \\nonumber  & = \\lambda\n%    %\n%\\end{align} \n%http://www.siam.org/books/textbooks/OT88sample.pdf\n%\n%%\\vspace*{2em}\n%(2) 1-D, unsteady flow of compressible fluids (in a uniform conduit)\n%%\n%\\begin{equation}\n%\\frac{\\partial \\rho}{\\partial t} + \\gamma \\frac{\\partial \\rho}{\\partial x} + \\rho \\frac{\\partial v}{\\partial x} = 0\n%\\end{equation}\n%\n%where $\\rho$ is the fluid density and $v$ is the fluid velocity.\n\n%\\vspace*{2em}\n%(2) The equation of motion under the influence of gravity \n\n\n\n\n\\end{document}", "meta": {"hexsha": "cd735bc265e650a7f8849060037d3783ab063f14", "size": 19217, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "03-eqns/3-eqns.tex", "max_stars_repo_name": "rachelslaybaugh/NE155", "max_stars_repo_head_hexsha": "5a08229eb11eebdd60e5ec1b4c0d41a541e7d82f", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2015-08-22T05:28:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T02:00:39.000Z", "max_issues_repo_path": "03-eqns/3-eqns.tex", "max_issues_repo_name": "rachelslaybaugh/NE155", "max_issues_repo_head_hexsha": "5a08229eb11eebdd60e5ec1b4c0d41a541e7d82f", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2015-04-01T00:18:04.000Z", "max_issues_repo_issues_event_max_datetime": "2016-10-31T20:14:58.000Z", "max_forks_repo_path": "03-eqns/3-eqns.tex", "max_forks_repo_name": "rachelslaybaugh/NE155", "max_forks_repo_head_hexsha": "5a08229eb11eebdd60e5ec1b4c0d41a541e7d82f", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-01-21T20:12:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-20T08:01:10.000Z", "avg_line_length": 41.9585152838, "max_line_length": 494, "alphanum_fraction": 0.6546287142, "num_tokens": 6031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.3296606911471149}}
{"text": "\\chapter{System F}\n\n% 2.1 Syntax\n% A simple, powerful calculus\n% mention here how powerful the language is, yada yada...\n% 2.1.1 Types\n% 2.1.2 Terms\n% 2.1.3 Values\n% 2.1.4 Contexts\n% 2.1.5 Evaluation\n\n% 2.2 Typing, a relation\n% 2.2.1 T-Var\n% 2.2.2 T-Abs \n% 2.2.3 T-TApp\n% 2.2.4 ......\n\n% 2.3 Properties of \n\n% Worth discussing why System F came about. Same as with Girard's qualms with System T, I retreat to System F for its expressivity and lack of improving expressivity.\n\\begin{singlespace}\n\\setlength{\\epigraphwidth}{0.6\\textwidth}\n\\epigraph{\\textit{So we are led to endless improvement, in order to be able to consider, besides the booleans, the integers, lists, trees, etc. Of course, all this is done to the detriment of conceptual simplicity and modularity.}}{\\textsc{Jean-Yves Girard \\\\  Proofs and Types (1989)}}\n\\end{singlespace}\n\n\\section{System T, then F}\nIn the Dialectica interpretation, Kurt G{\\\"o}del constructs System T. With it, he proves the consistency of Heyting arithmetic: a logical framework for reasoning about natural numbers \\cite{avigad1998godel}. That is, the axioms for Heyting arithmetic do not lead to contradictions about natural numbers. \n\nDespite success, logicians like Girard expressed misgivings about System T. In order to reason over natural numbers, System T explicitly introduces machinery for reasoning over things like booleans and pairs. Because they aren't inherently representable in System T, you end up with the endless improvements Girard mentions in the epigraph. To do something new in System T, you add something new. What results is a language which quickly loses \"conceptual simplicity and modularity.\"\n\nTo amend these misgivings, Girard constructs System F \\cite{girard1989proofs}. It's powerful enough to represent all machinery for the Dialectica interpretation, whilst preserving conceptual simplicity and modularity.\n\nSimilar misgivings about languages which learn programs led my retreat to System F. To learn something new, you add something new. Very quickly, these languages get complex. The key contribution of this work shows that not only does System F provide all machinery for the Dialectica interpretation, but also for learning from examples. To do something new in System F, I add nothing new.\n\nThe remainder of the chapter presents System F, with notation near identical to its presentation in \\cite{pierce2002types}. My presentation is terse, in order to provide intuitions for readers unfamiliar with lambda calculi. These intuitions ground the work developed hereafter. For comprehensive coverage, I defer to \\cite{pierce2002types}.\\\\\n\n\\begin{figure}[h]\n\\centering\n\\setlength{\\tabcolsep}{12pt}\n\\begin{tabular}{l  r}\n\\specialrule{.1em}{0em}{.2em}\n\n\\specialrule{.1em}{0em}{1em}\n    \\Large \\textsc{Syntax} & \\\\\n    & \\\\\n    \\begin{math}\n    \\setlength{\\jot}{-2pt}\n    \\begin{aligned}\n    e ::= \\;& && \\hspace*{.25in} \\textsc{terms:}\\\\\n        & x && \\hspace*{.25in} \\textit{variable}\\\\\n        & e_1e_2 && \\hspace*{.25in} \\textit{application}\\\\\n        & \\lam x {:} \\tau.e && \\hspace*{.25in} \\textit{abstraction}\\\\\n        & e\\lceil\\tau\\rceil && \\hspace*{.25in} \\textit{type application}\\\\    \n        & \\Lambda\\alpha.e && \\hspace*{.25in} \\textit{type abstraction}\\\\\n    \\\\\n    v ::= \\;& && \\hspace*{.25in} \\textsc{values:} \\\\\n        & \\lam x {:}\\tau.e && \\hspace*{.25in} \\textit{abstraction}\\\\\n        & \\Lambda\\alpha.e && \\hspace*{.25in} \\textit{type abstraction}\\\\\n    \\end{aligned}\n    \\end{math} & \n    \\begin{math}\n    \\setlength{\\jot}{-2pt}\n    \\begin{aligned}\n    \\tau ::= \\;& && \\hspace*{.25in} \\textsc{types:}\\\\\n        & \\tau_1 \\to \\tau_2 && \\hspace*{.25in} \\textit{function type}\\\\\n        & \\forall\\alpha.\\tau && \\hspace*{.25in} \\textit{polymorphic type}\\\\\n        & \\alpha && \\hspace*{.25in} \\textit{type variable}\\\\\n    \\\\\n    \\Gamma ::= \\;& && \\hspace*{.25in} \\textsc{contexts:}\\\\\n        & \\cdot && \\hspace*{.25in} \\textit{empty}\\\\\n        & x{:}\\tau,\\Gamma && \\hspace*{.25in} \\textit{variable}\\\\\n        & \\alpha,\\Gamma && \\hspace*{.25in} \\textit{type variable}\n    \\end{aligned}\n    \\end{math}\\\\\n    &\\\\\n\\specialrule{.1em}{1em}{0em}\n\\end{tabular}\n\\caption{Syntax in System F}\n    \\label{fig:syntax}\n\\end{figure}\t\n\n\\section{Syntax}\n\nA convenience of System F is its minimal syntax. It's only marginally more  complex than the simplest typed languages. Figure \\ref{fig:syntax} presents its grammar in Backus-Naur form \\cite{pierce2002types}. Beyond aesthetics, the minimalism is a mathematical convenience. Proofs about System F's behavior need only worry about a handful of language constructs. \n\nTo ease presentation, we use encodings for natural numbers from the start. These encodings are standard, and are shown in \\cite{girard1989proofs}.\n\n\\subsection{Types}\n\nTypes describe the behavior of programs.\n\n\\begin{enumerate}[label=\\alph*)]\n\\item $nat$ is the type for natural numbers. A program of this type is a natural number.\n\\item $nat \\!\\to\\!nat$ is the function type from $nat$ to $nat$. A program of this type has an input of type $nat$ and an output of type $nat$.\n\\item $nat \\!\\to\\!nat\\!\\to\\!nat$ is the function type from $nat$ and $nat$ to $nat$. A program of this type has two inputs of type $nat$ and an output of type $nat$.\n\\item $\\forall\\alpha.\\alpha\\!\\to\\!\\alpha\\!\\to\\!\\alpha$ is the polymorphic function type from $\\alpha$ and $\\alpha$ to $\\alpha$. A program of this type has two inputs of the same type and an output of that type. Polymorphic abstraction, denoted by $\\forall\\alpha$, lets the function work for any type represented by $\\alpha$. \n\\item $\\forall\\alpha.\\alpha\\!\\to\\!\\alpha\\!\\to\\!nat$ is the polymorphic function type from $\\alpha$ and $\\alpha$ to $nat$. A program of this type has two inputs of the same type and an output which is always type $nat$. \n\\end{enumerate}\n\n\\subsection{Terms}\n\nTerms are programs.\n\n\\begin{enumerate}[label=\\alph*)]\n\\item $\\lam x{:}nat.x$ is a program which takes a natural number $x$ as input, and returns it. The variable which comes after $\\lam$ in a term denotes the input. What comes after is the term's body, where its input is used for computation.\n\\item $(\\lam x{:}nat.x)1$ applies the previous program to $1$. \n\n\\item $\\Lambda\\alpha.\\lam x{:}\\alpha.x$ is a program which takes an $x$ of any type, and returns it. It's a polymorphic, or generic, version of the first program.\n\\item $(\\Lambda\\alpha.\\lam x{:}\\alpha.x)\\lceil nat\\rceil$ applies the previous program to type $nat$. \n\n\\item $\\lam f{:}nat\\!\\to\\!nat.\\lam x{:}nat.fx$ is a program which takes a function $f$ of type $nat\\!\\to\\!nat$ and a natural number $x$ as input. It returns the application of $f$ to $x$.  \n\\end{enumerate}\n\n\n\n\\subsection{Values}\n\nValues are programs which have finished computing.\n\\begin{enumerate}[label=\\alph*)]\n\\item $(\\lam x{:}nat.x)1$ is not a value. The program is an application, which can't be a value. Applications means there's computing left to do, namely the application of the program to its argument.  \n\\item $(\\lam x{:}nat)$ is a value. The program is applied to no arguments. There's no computing left to do.\n\\item $1$ is a value. \n\\end{enumerate}\n\n\\subsection{Contexts}\n\nContexts carry type information about variables. \n\\begin{enumerate}[label=\\alph*)]\n\\item $x{:}nat, y{:}nat$ is a valid context. It says $x$ and $y$ have type $nat$.  \n\\item $\\alpha$ is a valid context. It says $\\alpha$ is a type variable.\n\\item $\\cdot$ is a valid context. It says nothing. At times, when other information is present in the context, we omit $\\cdot$---which technically, is always present in the context.\n\\end{enumerate}\n\n\n\n\\section{Evaluating, a relation}\n\nSystem F's syntax tells us what programs look like. But doesn't say anything about how they run, how they compute. Suppose I have the program $(\\lam x{:}nat.x)1$. It applies a program which returns its input to the number $1$. It should return $1$. But how exactly? We want a relation which gives us the following behavior.\n$$(\\lam x{:}nat.x)1 \\to_\\beta x[1/x] \\to_\\beta 1$$\nFirst, $1$ is bound to the input $x$ of $\\lam x{:}nat.x$. Then $1$ substitutes $x$, resulting in $1$. The notation $x[1/x]$ denotes $1$ replacing $x$ in the program $x$. A relation of this behavior is defined in Figure \\ref{fig:evaluating}.\n\n\\begin{figure}[h]\n\\centering\n\\setlength{\\tabcolsep}{12pt}\n\\begin{tabular}{l r  l r}\n\\specialrule{.1em}{0em}{.2em}\n\\specialrule{.1em}{0em}{1em}\n    \\Large \\textsc{Evaluating} & \n    &  & \\fbox{ $e \\to_\\beta e'$}\\\\\n    & & \\\\\n    \\multicolumn{2}{c}{\n    \\def\\extraVskip{4pt}\n    \\def\\labelSpacing{4pt}\n    \\def\\defaultHypSeparation{\\hskip .05in}\n        \\AxiomC{$e_1 \\to_\\beta e_1'$}\n            \\RightLabel{\\textsc{(E-App1)}}\n        \\UnaryInfC{$e_1e_2 \\to_\\beta e_1'e_2$}\n        \\DisplayProof\n    } &\n    \\multicolumn{2}{c}{\n    \\def\\extraVskip{4pt}\n    \\def\\labelSpacing{4pt}\n    \\def\\defaultHypSeparation{\\hskip .05in}\n        \\AxiomC{$e \\to_\\beta e'$}\n            \\RightLabel{\\textsc{(E-TApp)}}\n        \\UnaryInfC{$e\\lceil\\tau\\rceil \\to_\\beta e'\\lceil\\tau\\rceil$}\n        \\DisplayProof\n    }\n    \\\\\n    & &\\\\\n    \\multicolumn{2}{c}{\n    \\def\\extraVskip{4pt}\n    \\def\\labelSpacing{4pt}\n    \\def\\defaultHypSeparation{\\hskip .05in}\n        \\AxiomC{$e_2 \\to_\\beta e_2'$}\n            \\RightLabel{\\textsc{(E-App2)}}\n        \\UnaryInfC{$e_1e_2 \\to_\\beta e_1e_2'$}\n        \\DisplayProof\n    } &\n    \\multicolumn{2}{c}{\n    \\def\\extraVskip{4pt}\n    \\def\\labelSpacing{4pt}\n    \\def\\defaultHypSeparation{\\hskip .05in}\n        \\AxiomC{$(\\Lambda\\alpha.\\lam x{:}\\alpha.e)\\lceil\\tau\\rceil \\to_\\beta (\\lam x{:}\\alpha.e)[\\tau/\\alpha]\\,\\,$\\textsc{(E-TSub)}}\n        \\DisplayProof\n    }\n    \\\\\n    & &\\\\\n    \\multicolumn{2}{c}{\n    \\def\\extraVskip{4pt}\n    \\def\\labelSpacing{4pt}\n    \\def\\defaultHypSeparation{\\hskip .05in}\n        \\AxiomC{$(\\lam x{:}\\tau.e)v \\to_\\beta e[v/x]\\,\\,$\\textsc{(E-Sub)}}\n        \\DisplayProof\n    } \\\\\n    & \\\\\n\\specialrule{.1em}{1em}{0em}\n\\end{tabular}\n\\caption{Evaluating in System F}\n    \\label{fig:evaluating}\n\\end{figure}\n\n\\textsc{(E-App1)} says that if a program $e_1$ evaluates to $e_1'$, then $e_1e_2$ evaluates to $e_1'e_2$. For example:\n\\begin{prooftree}\n\\def\\extraVskip{4pt}\n\\def\\labelSpacing{4pt}\n\t\\AxiomC{$(\\lam x{:}nat\\!\\to\\!nat.x)(\\lam y{:}nat.y) \\to_\\beta (\\lam y{:}nat.y)$}\n\t\\RightLabel{\\textsc{(E-App1)}}\n\t\\UnaryInfC{$((\\lam x{:}nat\\!\\to\\!nat.x)(\\lam y{:}nat.y))1 \\to_\\beta (\\lam y{:}nat.y)1$}\n\\end{prooftree}\n\n\\textsc{(E-App2)} says that if a program $e_2$ evaluates to $e_2'$, then $e_1e_2$ evaluates to $e_1e_2'$. For example:\n\\begin{prooftree}\n\\def\\extraVskip{4pt}\n\\def\\labelSpacing{4pt}\n\t\\AxiomC{$(\\lam x{:}nat.x)1 \\to_\\beta 1$}\n\t\\RightLabel{\\textsc{(E-App2)}}\n\t\\UnaryInfC{$(\\lam x{:}nat.x)((\\lam x{:}nat.x)1) \\to_\\beta (\\lam x{:}nat.x)1$}\n\\end{prooftree}\n\n\\textsc{(E-Sub)} says that if a program $\\lam x{:}\\tau.e$ is applied to value $v$, then replace all instances of $x$ in $e$ with $v$. For example: \\vspace*{-1.2em}\n\\begin{prooftree}\n\\def\\extraVskip{4pt}\n\\def\\labelSpacing{4pt}\n\t\\AxiomC{$(\\lam x{:}nat.x)1 \\to_\\beta x[1/x]\\,\\,$\\textsc{(E-Sub)}}\n\\end{prooftree}\n\n\\textsc{(E-TApp)} says that if a program $e$ evaluates to $e'$, then $e\\lceil\\tau\\rceil$ evaluates to $e'\\lceil\\tau\\rceil$. For example:\n\\begin{prooftree}\n\\def\\extraVskip{4pt}\n\\def\\labelSpacing{4pt}\n\t\\AxiomC{$\\Lambda\\alpha.(\\lam x{:}\\alpha\\!\\to\\!\\alpha.x)(\\lam x{:}\\alpha.x) \\to_\\beta \\Lambda\\alpha.\\lam x{:}\\alpha.x$}\n\t\\RightLabel{\\textsc{(E-TApp)}}\n\t\\UnaryInfC{$(\\Lambda\\alpha.(\\lam x{:}\\alpha\\!\\to\\!\\alpha.x)(\\lam x{:}\\alpha.x))\\lceil nat\\rceil \\to_\\beta (\\Lambda\\alpha.\\lam x{:}\\alpha.x)\\lceil nat\\rceil$}\n\\end{prooftree}\n\n\\textsc{(E-TSub)} says that if a program $\\Lambda\\alpha.\\lam x{:}\\alpha.e$ is applied to type $\\tau$, then replace all instances of $\\alpha$ in $\\lam x{:}\\alpha.e$ with $\\tau$. For example: \\vspace*{-1.2em}\n\\begin{prooftree}\n\\def\\extraVskip{4pt}\n\\def\\labelSpacing{4pt}\n\t\\AxiomC{$(\\Lambda\\alpha.\\lam x{:}\\alpha.x)\\lceil nat\\rceil \\to_\\beta (\\lam x{:}\\alpha.x)[nat/\\alpha]\\,\\,$\\textsc{(E-TSub)}}\n\\end{prooftree}\n\nThe evaluating relation comes in many forms. Here, we use what's referred to as a call-by-value evaluation strategy \\cite{plotkin1975call}. More exist, and each impact how programs evaluate in System F, e.g. call-by-name and call-by-need \\cite{plotkin1975call, ariola1997call}. These alternatives aren't discussed, but we do consider the reflexive, symmetric, transitive closure of the defined evaluating relation, $=_\\beta$. It denotes program equality. Because this evaluating relation has the normalization property, deciding program equality is decidable. In upcoming chapters, we'll see how program equality is used to learn from examples.\n\n\n\\section{Typing, a relation}\n\nWith syntax, we saw what programs look like. With evaluation, we saw how programs execute. So then why do we need typing? Without typing, we can write the following program in System F. The grammar in Figure \\ref{fig:syntax} permits it. \\vspace*{-1.0em}\n\\begin{singlespace}\n$$(\\lam x{:}nat.x)(\\lam y{:}nat.y)$$ \n\\end{singlespace}\nBut this program is nonsense. The left-hand side of the application is a program which returns its argument $x$, which must be of type $nat$. The right-hand side is the same program. If we were to naively evaluate this program, it would substitute $\\lam x{:}nat.x$ for the argument $x$ on the left-hand side. Yet the argument wouldn't be of type $nat$. $\\lam x{:}nat.x$ is the function type $nat\\!\\to\\!nat$. The types don't align for evaluation, to do computation.\n\nTo actually do something, the left-hand side needs an argument of the correct type. \\vspace*{-1.0em}\n\\begin{singlespace}\n$$(\\lam x{:}nat\\!\\to\\!nat.x)(\\lam y{:}nat.y)$$\n\\end{singlespace}\nThis is why we need typing. It lets us build programs which make sense, for which types align to do computation. Like evaluation, we define typing as a relation.\\\\\n\\begin{figure}[h]\n\\centering\n\\setlength{\\tabcolsep}{12pt}\n\\begin{tabular}{l r  l r}\n\\specialrule{.1em}{0em}{.2em}\n\\specialrule{.1em}{0em}{1em}\n    \\Large \\textsc{Typing} & \n    &  & \\framebox{$\\Gamma \\vdash e : \\tau$}\\\\\n    & & \\\\\n    \\multicolumn{2}{c}{\n    \\def\\extraVskip{4pt}\n    \\def\\labelSpacing{4pt}\n    \\def\\defaultHypSeparation{\\hskip .05in}\n        \\AxiomC{$x:\\tau \\in \\Gamma$}\n            \\RightLabel{\\textsc{(T-Var)}}\n        \\UnaryInfC{$\\Gamma \\vdash x : \\tau$}\n        \\DisplayProof\n    } &\n    \\multicolumn{2}{c}{\n    \\def\\extraVskip{4pt}\n    \\def\\labelSpacing{4pt}\n    \\def\\defaultHypSeparation{\\hskip .05in}\n        \\AxiomC{$\\Gamma,\\alpha \\vdash e : \\tau$}\n            \\RightLabel{\\textsc{(T-TAbs)}}\n        \\UnaryInfC{$\\Gamma \\vdash \\Lambda \\alpha.e:\\forall\\alpha.\\tau$}\n        \\DisplayProof\n    }\n    \\\\\n    & &\\\\\n    \\multicolumn{2}{c}{\n    \\def\\extraVskip{4pt}\n    \\def\\labelSpacing{4pt}\n    \\def\\defaultHypSeparation{\\hskip .05in}\n        \\AxiomC{$\\Gamma,x{:}\\tau_1 \\vdash e_2 : \\tau_2$}\n            \\RightLabel{\\textsc{(T-Abs)}}\n        \\UnaryInfC{$\\Gamma \\vdash \\lam x{:}\\tau_1.e_2:\\tau_1 \\to \\tau_2$}\n        \\DisplayProof\n    } &\n    \\multicolumn{2}{c}{\n    \\def\\extraVskip{4pt}\n    \\def\\labelSpacing{4pt}\n    \\def\\defaultHypSeparation{\\hskip .05in}\n        \\AxiomC{$\\Gamma \\vdash e : \\forall\\alpha.\\tau_1$}\n            \\RightLabel{\\textsc{(T-TApp)}}\n        \\UnaryInfC{$\\Gamma \\vdash e\\lceil\\tau_2\\rceil : [\\tau_2/\\alpha]\\tau_1$}\n        \\DisplayProof\n    }\n    \\\\\n    & &\\\\\n    \\multicolumn{2}{c}{\n    \\def\\extraVskip{4pt}\n    \\def\\labelSpacing{4pt}\n    \\def\\defaultHypSeparation{\\hskip .05in}\n        \\AxiomC{$\\Gamma \\vdash e_1 : \\tau_1 \\to \\tau_2$}\n        \\AxiomC{$\\Gamma \\vdash e_2 : \\tau_1$}\n            \\RightLabel{\\textsc{(T-App)}}\n        \\BinaryInfC{$\\Gamma \\vdash e_1e_2 : \\tau_2$}\n        \\DisplayProof\n    } \\\\\n    & \\\\\n\\specialrule{.1em}{1em}{0em}\n\\end{tabular}\n\\caption{Typing in System F}\n    \\label{fig:typing}\n\\end{figure}\n\n\\textsc{(T-Var)} says that if $x$ is bound to type $\\tau$ in the context $\\Gamma$, then the program $x$ is of type $\\tau$. \n\\begin{prooftree}\n\\def\\extraVskip{4pt}\n\\def\\labelSpacing{4pt}\n\t\\AxiomC{$x {:} nat \\in x {:} nat$}\n\t\\RightLabel{\\textsc{(T-Var)}}\n\t\\UnaryInfC{$x{:}nat \\vdash x : nat$}\n\\end{prooftree}\n\n\\textsc{(T-Abs)} says that if $x$ is bound to type $\\tau_1$ in the context $\\Gamma$ and that a program $e_2$ is of type $\\tau_2$, then the program $\\lam x{:}\\tau_1.e_2$ is of type $\\tau_1 \\!\\to\\! \\tau_2$ and $x$ is removed from the context. \n\\begin{prooftree}\n\\def\\extraVskip{4pt}\n\\def\\labelSpacing{4pt}\n\t\\AxiomC{$\\Gamma,x{:}nat \\vdash \\lam y{:}nat.y : nat \\!\\to\\! nat$}\n\t\\RightLabel{\\textsc{(T-Abs)}}\n\t\\UnaryInfC{$\\Gamma \\vdash \\lam x{:}nat.\\lam y{:}nat.y : nat \\!\\to\\! nat \\!\\to \\!nat$}\n\\end{prooftree}\n\n\\textsc{(T-App)} says that if a program $e_1$ is of type $\\tau_1 \\!\\to\\! \\tau_2$ and a program $e_2$ is of type $\\tau_1$, then  $e_1e_2$ is of type $\\tau_2$.\n\\begin{prooftree}\n\\def\\extraVskip{4pt}\n\\def\\labelSpacing{4pt}\n\t\\AxiomC{$\\Gamma \\vdash \\lam x{:}nat.x : nat \\!\\to\\! nat$}\n\t\\AxiomC{$\\Gamma \\vdash 1 : nat$}\n\t\\RightLabel{\\textsc{(T-App)}}\n\t\\BinaryInfC{$\\Gamma \\vdash (\\lam x{:}nat.x)1 : nat$}\n\\end{prooftree}\n\n\\textsc{(T-TAbs)} says that if $\\alpha$ is in the context, and a program $e$ is of type $\\tau$, then the program $\\Lambda\\alpha.e$ is of type $\\forall\\alpha.\\tau$ and $\\alpha$ is removed from the context.\n\\begin{prooftree}\n\\def\\extraVskip{4pt}\n\\def\\labelSpacing{4pt}\n\t\\AxiomC{$\\Gamma,\\alpha \\vdash \\lam x{:}nat.x : \\alpha \\!\\to\\! \\alpha$}\n\t\\RightLabel{\\textsc{(T-TAbs)}}\n\t\\UnaryInfC{$\\Gamma \\vdash \\Lambda\\alpha.\\lam x{:}\\alpha.x : \\forall\\alpha.\\alpha \\!\\to\\! \\alpha$}\n\\end{prooftree}\n\n\\textsc{(T-TApp)} says that if a program $e$ is of type $\\forall\\alpha.\\tau_1$, then  the program $e\\lceil\\tau_2\\rceil$ is of type $[\\tau_2/\\alpha]\\tau_1$.\n\\begin{prooftree}\n\\def\\extraVskip{4pt}\n\\def\\labelSpacing{4pt}\n\t\\AxiomC{$\\Gamma \\vdash \\Lambda\\alpha.\\lam x{:}\\alpha.x : \\forall\\alpha.\\alpha\\!\\to\\!\\alpha$}\n\t\\RightLabel{\\textsc{(T-Abs)}}\n\t\\UnaryInfC{$\\Gamma \\vdash (\\Lambda\\alpha.\\lam x{:}\\alpha.x)\\lceil nat\\rceil : nat\\!\\to\\!nat$}\n\\end{prooftree}\n\nAs with evaluating, there are many ways to construct typing relations on System F. Each offers their own take on what constitutes a well-typed program in System F, e.g. System F extended with subtyping \\cite{cardelli1991extension}. The behavior of the typing relation is especially important for learning, as learning will depend on key properties of the typing relation: namely progress and preservation.\n\n\\section{Metatheory}\nWell-typed terms can be thought of as theorems constructed through the typing relation, whose proof are sound proof trees. Hence, statements about these theorems, or the typing relation in general, are metatheoretic statements. I briefly review key metatheoretic properties of System F essential for learning. Proofs ommitted, but easily found in \\cite{girard1989proofs}.\n\\subsection{Programs don't get stuck}\n\\begin{theorem}[\\textsc{Progress in Typing}]\nIf $e$ is a closed, well-typed program, then either $e$ is a value or else there is some program $e'$ such that $e \\to_\\beta e'$.\n\\label{progress-typing}\n\\end{theorem}\n\nPrograms shouldn't get stuck in the middle of computation. We want well-typed programs to always have something to do, even if they don't ever stop. Progress ensures this. And with preservation, it lets us prove typing is sound, that we can prove all true theorems implied by the typing relation.\n\\subsection{Programs don't change types}\n\\begin{theorem}[\\textsc{Preservation in Typing}]\nIf $\\,\\Gamma \\vdash e : \\tau$ and $e \\to_\\beta e'$, then $\\Gamma \\vdash e' : \\tau$.\n\\label{preservation-typing}\n\\end{theorem}\n\nPrograms shouldn't suddenly switch types in the middle of computation. Remember, the point of the type is to let us know kind of computation to expect from a program. If the type switches during computation, we're losing that information. With progress, preservation lets us prove typing is sound. By extension, they are essential to prove learning sound.\n\n\\subsection{Programs always halt}\n\\begin{theorem}[\\textsc{Normalization in Evaluation}]\nWell-typed programs in System F always evaluate to a value, to a normal form.\n\\label{normalization-evaluation}\n\\end{theorem}\n\nProgress doesn't guarantee programs ever stop computing. They could get stuck in infinite loops. Under certain type systems it's impossible to guarantee programs ever stop, e.g. recursive types \\cite{pierce2002types}. But in System F we know all programs halt, or stop. For learning from examples, introduced in subsequent chapters, this property is essential. With normalization, program equivalence becomes decidable---a key part of the learning procedure. \n\n% Evaluation\n% --Church-Rosser\n% --Strongly Normalizing\n% Typing\n% --Progress\n% --Preservation", "meta": {"hexsha": "9bbc9fd9f0caf4a28c28e7f3528073dc180c9e92", "size": 20618, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/chapter2.tex", "max_stars_repo_name": "namin/learning_sysf", "max_stars_repo_head_hexsha": "0df65b0d4526d0bf5ee43a6b1f04af446b1afaa1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thesis/chapter2.tex", "max_issues_repo_name": "namin/learning_sysf", "max_issues_repo_head_hexsha": "0df65b0d4526d0bf5ee43a6b1f04af446b1afaa1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis/chapter2.tex", "max_forks_repo_name": "namin/learning_sysf", "max_forks_repo_head_hexsha": "0df65b0d4526d0bf5ee43a6b1f04af446b1afaa1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-07T22:47:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-07T22:47:43.000Z", "avg_line_length": 51.0346534653, "max_line_length": 644, "alphanum_fraction": 0.6878940731, "num_tokens": 6620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251201477015, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3296606911471148}}
{"text": "\\part{Inference}\n\n\\chapter{Bayesian Data Analysis}\\label{bayesian.chapter}\n\n\\noindent\n\\cite{GelmanEtAl:2013} provide the following\ncharacterization of Bayesian data analysis.\n%\n\\begin{quote}\n  By Bayesian data analysis, we mean practical methods for making\n  inferences from data using probability models for quantities we\n  observe and about which we wish to learn.\n\\end{quote}\n%\nThey go on to describe how Bayesian statistics differs from\nfrequentist approaches.\n%\n\\begin{quote}\n  The essential characteristic of Bayesian methods is their explicit\n  use of probability for quantifying uncertainty in inferences based\n  on statistical analysis.\n\\end{quote}\n%\nBecause they view probability as the limit of relative frequencies of\nobservations, strict frequentists forbid probability statements about\nparameters.  Parameters are considered fixed, not random.\n\nBayesians also treat parameters as fixed but unknown.  But unlike\nfrequentists, they make use of both prior distributions over\nparameters and posterior distributions over parameters.  These prior\nand posterior probabilities and posterior predictive probabilities are\nintended to characterize knowledge about the parameters and future\nobservables.  Posterior distributions form the basis of Bayesian\ninference, as described below.\n\n\\section{Bayesian Modeling}\n\n\\citep{GelmanEtAl:2013} break applied Bayesian modeling\ninto the following three steps.\n%\n\\begin{enumerate}\n\\item  Set up a full probability model for all observable and\n  unobservable quantities.  This model should be consistent with\n  existing knowledge of the data being modeled and how it was\n  collected.\n\\item Calculate the posterior probability of unknown quantities\n  conditioned on observed quantities.  The unknowns may include\n  unobservable quantities such as parameters and potentially\n  observable quantities such as predictions for future observations.\n\\item Evaluate the model fit to the data.  This includes evaluating\n  the implications of the posterior.\n\\end{enumerate}\n%\nTypically, this cycle will be repeated until a sufficient fit is\nachieved in the third step.  Stan automates the calculations involved\nin the second and third steps.\n\n\\section{Bayesian Inference}\n\n\\subsection{Basic Quantities}\n\nThe mechanics of Bayesian inference follow directly from Bayes's rule.\nTo fix notation, let $y$ represent observed quantities such as data\nand let $\\theta$ represent unknown quantities such as parameters and\nfuture observations.  Both $y$ and $\\theta$ will be modeled as random.\nLet $x$ represent known, but unmodeled quantities such as constants,\nhyperparameters, and predictors.\n\n\\subsection{Probability Functions}\n\nThe probability function $p(y,\\theta)$ is the joint probability\nfunction of the data $y$ and parameters $\\theta$.  The constants and\npredictors $x$ are implicitly understood as being part of the\nconditioning.  The conditional probability function $p(y|\\theta)$ of\nthe data $y$ given parameters $\\theta$ and constants $x$ is called the\nsampling probability function; it is also called the likelihood\nfunction when viewed as a function of $\\theta$ for fixed $y$ and $x$.\n\nThe probability function $p(\\theta)$ over the parameters given the\nconstants $x$ is called the prior because it characterizes the probability\nof the parameters before any data is observed.  The conditional\nprobability function $p(\\theta|y)$ is called the posterior because\nit characterizes the probability of parameters given observed data $y$\nand constants $x$.\n\n\\subsection{Bayes's Rule}\n\nThe technical apparatus of Bayesian inference hinges on the following\nchain of equations, known in various forms as Bayes's rule (where\nagain, the constants $x$ are implicit).\n%\n\\[\n\\begin{array}{rcll}\np(\\theta|y)  & =  & \\displaystyle \\frac{p(\\theta,y)}{p(y)}\n& \\mbox{{} \\ \\ \\ \\ \\ [definition of  conditional probability]}\n\\\\[16pt]\n& = & \\displaystyle \\frac{p(y|\\theta) \\, p(\\theta)}{p(y)}\n& \\mbox{{} \\ \\ \\ \\ \\ [chain rule]}\n\\\\[16pt]\n& = & \\displaystyle \\frac{p(y|\\theta) \\, p(\\theta)}\n                        {\\int_{\\Theta} p(y,\\theta) \\, d\\theta}\n& \\mbox{{} \\ \\ \\ \\ \\ [law of total probability]}\n\\\\[16pt]\n& = & \\displaystyle \\frac{p(y|\\theta) \\, p(\\theta)}\n                        {\\int_{\\Theta} p(y|\\theta) \\, p(\\theta) \\, d\\theta}\n& \\mbox{{} \\ \\ \\ \\ \\ [chain rule]}\n\\\\[16pt]\n& \\propto & \\displaystyle p(y|\\theta) \\, p(\\theta)\n& \\mbox{{} \\ \\ \\ \\ \\ [$y$ is fixed]}\n\\end{array}\n\\]\n%\nBayes's rule ``inverts'' the probability of the posterior\n$p(\\theta|y)$, expressing it solely in terms of the likelihood\n$p(y|\\theta)$ and prior $p(\\theta)$ (again, with constants and\npredictors $x$ implicit).  The last step is important for Stan, which\nonly requires probability functions to be characterized up to a\nconstant multiplier.\n\n\\subsection{Predictive Inference}\n\nThe uncertainty in the estimation of parameters $\\theta$ from the data\n$y$ (given the model) is characterized by the posterior $p(\\theta|y)$.\nThe posterior is thus crucial for Bayesian predictive inference.\n\nIf $\\tilde{y}$ is taken to represent new, perhaps as yet unknown,\nobservations, along with corresponding constants and predictors\n$\\tilde{x}$, then the posterior predictive probability function is\ngiven by\n%\n\\[\np(\\tilde{y}|y)\n= \\int_{\\Theta} p(\\tilde{y}|\\theta)\n                \\, p(\\theta|y) \\, d\\theta.\n\\]\nHere, both the original constants and predictors $x$ and the new\nconstants and predictors $\\tilde{x}$ are implicit.  Like the posterior\nitself, predictive inference is characterized probabilistically.\nRather than using a point estimate of the parameters $\\theta$,\npredictions are made based on averaging the predictions over a range\nof $\\theta$ weighted by the posterior probability $p(\\theta|y)$ of\n$\\theta$ given data $y$ (and constants $x$).\n\nThe posterior may also be used to estimate event probabilities.  For\ninstance, the probability that a parameter $\\theta_k$ is greater than\nzero is characterized probabilistically by\n%\n\\[\n\\mbox{Pr}[\\theta_k > 0]\n= \\int_{\\Theta} \\mbox{I}(\\theta_k > 0) \\, p(\\theta|y) \\, d\\theta.\n\\]\n%\nThe indicator function, $\\mbox{I}(\\phi)$, evaluates to one if the\nproposition $\\phi$ is true and evaluates to zero otherwise.\n\nComparisons involving future observables may be carried out in\nthe same way.  For example, the probability that $\\tilde{y}_n >\n\\tilde{y}_{n'}$ can be characterized using the posterior predictive\nprobability function as\n\\[\n\\mbox{Pr}[\\tilde{y}_n > \\tilde{y}_{n'}]\n= \\int_{\\Theta} \\int_{Y} \\mbox{I}(\\tilde{y}_n > \\tilde{y}_{n'}) \\,\np(\\tilde{y}|\\theta) p(\\theta|y) \\, d\\tilde{y} \\, d\\theta.\n\\]\n\n\n\\subsection{Posterior Predictive Checking}\n\nAfter the parameters are fit to data, they can be used to simulate a\nnew data set by running the model inferences in the forward\ndirection.  These replicated data sets can then be compared to the\noriginal data either visually or statistically to assess model fit\n\\citep[Chapter 6]{GelmanEtAl:2013}.\n\nIn Stan, posterior simulations can be generated in two ways.  The\nfirst approach is to treat the predicted variables as parameters and\nthen define their distributions in the model block.  The second\napproach, which also works for discrete variables, is to generate\nreplicated data using random-number generators in the generated\nquantities block.\n\n\n\n\\chapter{Markov Chain Monte Carlo Sampling}\\label{mcmc.chapter}\n\n\\noindent\nStan uses Markov chain Monte Carlo (\\MCMC) techniques to\ngenerate samples from the posterior distribution for inference.\n\n\n\\section{Monte Carlo Sampling}\n\nMonte Carlo methods were developed to numerically approximate\nintegrals that are not tractable analytically but for which evaluation\nof the function being integrated is tractable\n\\citep{MetropolisUlam:1949}.\n\nFor example, the mean $\\mu$ of a probability density $p(\\theta)$ is\ndefined by the integral\n\\[\n\\mu = \\int_{\\Theta} \\, \\theta \\times p(\\theta) \\, d\\theta.\n\\]\nFor even a moderately complex Bayesian model, the posterior density\n$p(\\theta|y)$ leads to an integral that is impossible to evaluate\nanalytically.  The posterior also depends on the constants and\npredictors $x$, but from here, they will just be elided and taken as\ngiven.\n\nNow suppose it is possible to draw independent samples from\n$p(\\theta)$ and let $\\theta^{(1)},\\theta^{(2)},\\ldots,\\theta^{(N)}$ be\n$N$ such samples.  A Monte Carlo estimate $\\hat{\\mu}$ of the mean\n$\\mu$ of $p(\\theta)$ is given by the sample average,\n\\[\n\\hat{\\mu} = \\frac{1}{N} \\sum_{n=1}^N \\theta^{(n)}.\n\\]\n\nIf the probability function $p(\\theta)$ has a finite mean and\nvariance, the law of large numbers ensures the Monte Carlo estimate\nconverges to the correct value as the number of samples increases,\n\\[\n\\lim_{N \\rightarrow \\infty} \\hat{\\mu} = \\mu.\n\\]\nAssuming finite mean and variance, estimation error is governed by the\ncentral limit theorem, so that estimation error decreases as the\nsquare root of $N$,\n\\[\n|\\mu - \\hat{\\mu}| \\propto \\frac{1}{\\sqrt{N}}.\n\\]\nTherefore, estimating a mean to an extra decimal place of accuracy\nrequires one hundred times more samples; adding two decimal places\nmeans ten thousand times as many samples.  This makes Monte Carlo\nmethods more useful for rough estimates to within a few decimal places\nthan highly precise estimates.  In practical applications, there is no\npoint estimating a quantity beyond the uncertainty of the data sample\non which it is based, so this lack of many decimal places of accuracy\nis rarely a problem in practice for statistical models.\n\n\n\\section{Markov Chain Monte Carlo Sampling}\n\nMarkov chain Monte Carlo (\\MCMC) methods were developed for situations\nin which it is not straightforward to draw independent samples\n\\citep{Metropolis:1953}.\n\nA Markov chain is a sequence of random variables $\\theta^{(1)},\n\\theta^{(2)},\\ldots$ where each variable is conditionally independent\nof all other variables given the value of the previous value.  Thus if\n$\\theta = \\theta^{(1)}, \\theta^{(2)},\\ldots, \\theta^{(N)}$, then\n\\[\np(\\theta) = p(\\theta^{(1)}) \\prod_{n=2}^N p(\\theta^{(n)}|\\theta^{(n-1)}).\n\\]\nStan uses Hamiltonian Monte Carlo to generate a next state in a manner\ndescribed in \\refchapter{hmc}.\n\nThe Markov chains Stan and other \\MCMC samplers generate are ergodic\nin the sense required by the Markov chain central limit theorem,\nmeaning roughly that there is a reasonable chance of reaching\none value of $\\theta$ from another.  The Markov chains are also\nstationary, meaning that the transition probabilities do not change at\ndifferent positions in the chain, so that for $n, n' \\geq 0$, the\nprobability function $p(\\theta^{(n+1)}|\\theta^{(n)})$ is the same as\n$p(\\theta^{(n'+1)}|\\theta^{(n')})$ (following the convention of\noverloading random and bound variables and picking out a probability\nfunction by its arguments).\n\nStationary Markov chains have an equilibrium distribution on states in\nwhich each has the same marginal probability function, so that\n$p(\\theta^{(n)})$ is the same probability function as\n$p(\\theta^{(n+1)})$.  In Stan, this equilibrium distribution\n$p(\\theta^{(n)})$ is the probability function $p(\\theta)$ being\nsampled, typically a Bayesian posterior density.\n\nUsing \\MCMC methods introduces two difficulties that are not faced by\nindependent sample Monte Carlo methods.  The first problem is determining\nwhen a randomly initialized Markov chain has converged to its\nequilibrium distribution.  The second problem is that the draws from a\nMarkov chain are correlated, and thus the central limit theorem's\nbound on estimation error no longer applies.  These problems are\naddressed in the next two sections.\n\n\n\\section{Initialization and Convergence Monitoring}\\label{convergence.section}\n\nA Markov chain generates samples from the target distribution only\nafter it has converged to equilibrium.  Unfortunately, this is only\nguaranteed in the limit in theory.  In practice, diagnostics must be\napplied to monitor whether the Markov chain(s) have converged.\n\n\\subsection{Potential Scale Reduction}\n\nOne way to monitor whether a chain has converged to the equilibrium\ndistribution is to compare its behavior to other randomly initialized\nchains.  This is the motivation for the \\cite{GelmanRubin:1992}\npotential scale reduction statistic, $\\hat{R}$.  The $\\hat{R}$\nstatistic measures the ratio of the average variance of samples within\neach chain to the variance of the pooled samples across chains; if all\nchains are at equilibrium, these will be the same and $\\hat{R}$ will\nbe one.  If the chains have not converged to a common distribution,\nthe $\\hat{R}$ statistic will be greater than one.\n\nGelman and Rubin's recommendation is that the independent Markov\nchains be initialized with diffuse starting values for the parameters\nand sampled until all values for $\\hat{R}$ are below 1.1.  Stan\nallows users to specify initial values for parameters and it is also\nable to draw diffuse random initializations itself.\n\nThe $\\hat{R}$ statistic is defined for a set of $M$ Markov chains,\n$\\theta_m$, each of which has $N$ samples $\\theta^{(n)}_m$.  The\nbetween-sample variance estimate is\n\\[\nB\n= \\frac{N}{M-1} \\, \\sum_{m=1}^M (\\bar{\\theta}^{(\\bullet)}_{m} - \\bar{\\theta}^{(\\bullet)}_{\\bullet})^2,\n\\]\n%\nwhere\n%\n\\[\n\\bar{\\theta}_m^{(\\bullet)}\n= \\frac{1}{N} \\sum_{n = 1}^N \\theta_m^{(n)}\n\\ \\ \\ \\ \\\n\\mbox{and}\n\\ \\ \\ \\ \\\n\\bar{\\theta}^{(\\bullet)}_{\\bullet}\n= \\frac{1}{M} \\, \\sum_{m=1}^M \\bar{\\theta}_m^{(\\bullet)}.\n\\]\n%\nThe within-sample variance is\n\\[\nW\n= \\frac{1}{M} \\, \\sum_{m=1}^M s_m^2,\n\\]\nwhere\n\\[\ns_m^2 = \\frac{1}{N-1} \\, \\sum_{n=1}^N (\\theta^{(n)}_m - \\bar{\\theta}^{(\\bullet)}_m)^2.\n\\]\n%\nThe variance estimator is\n\\[\n\\widehat{\\mbox{var}}^{+}\\!(\\theta|y)\n= \\frac{N-1}{N}\\, W \\, + \\, \\frac{1}{N} \\, B.\n\\]\n%\nFinally, the potential scale reduction statistic is defined by\n\\[\n\\hat{R}\n\\, = \\,\n\\sqrt{\\frac{\\widehat{\\mbox{var}}^{+}\\!(\\theta|y)}{W}}.\n\\]\n\n\\subsection{Generalized $\\hat{R}$ for Ragged Chains}\n\nNow suppose that each chain may have a different number of samples.\nLet $N_m$ be the number of samples in chain $m$.  Now the formula for\nthe within-chain mean for chain $m$ uses the size of the chain, $N_m$,\n\\[\n\\bar{\\theta}_m^{(\\bullet)}\n= \\frac{1}{N_m} \\sum_{n = 1}^N \\theta^{(m)}_n,\n\\]\nas does the within-chain variance estimate,\n\\[\ns_m^2 = \\frac{1}{N_m-1} \\, \\sum_{n=1}^{N_m} (\\theta^{(n)}_m - \\bar{\\theta}^{(\\bullet)}_m)^2.\n\\]\nThe terms that average over chains, such as\n$\\bar{\\theta}^{(\\bullet)}_{\\bullet}$, $B$, and $W$, have the same\ndefinition as before to ensure that each chain has the same effect on\nthe estimate.  If the averages were weighted by size, a single long\nchain would dominate the statistics and defeat the purpose of\nmonitoring convergence with multiple chains.\n\nBecause it contains the term $N$, the estimate $\\widehat{var}^{+}$\nmust be generalized.  By expanding the first term,\n\\[\n\\frac{N-1}{N}\\, W \\,\n\\ = \\\n\\frac{N-1}{N} \\frac{1}{M} \\, \\sum_{m=1}^M\n\\frac{1}{N-1} \\, \\sum_{n=1}^N (\\theta^{(n)}_m -\n\\bar{\\theta}^{(\\bullet)}_m)^2\n\\ = \\\n\\frac{1}{M}\n\\sum_{m=1}^M\n\\frac{1}{N}\n\\sum_{n=1}^N (\\theta^{(n)}_m -\n\\bar{\\theta}^{(\\bullet)}_m)^2,\n\\]\nand the second term,\n\\[\n\\frac{1}{N}\\, B\n\\ = \\\n\\frac{1}{M-1} \\, \\sum_{m=1}^M (\\bar{\\theta}^{(\\bullet)}_{m} - \\bar{\\theta}^{(\\bullet)}_{\\bullet})^2.\n\\]\nthe variance estimator naturally generalizes to\n\\[\n\\widehat{\\mbox{var}}^{+}\\!(\\theta|y)\n=\n\\frac{1}{M}\n\\sum_{m=1}^M\n\\frac{1}{N_m}\n\\sum_{n=1}^{N_m} (\\theta^{(n)}_m -\n\\bar{\\theta}^{(\\bullet)}_m)^2\n+\n\\frac{1}{M-1} \\, \\sum_{m=1}^M (\\bar{\\theta}^{(\\bullet)}_{m} -\n\\bar{\\theta}^{(\\bullet)}_{\\bullet})^2.\n\\]\n%\nIf the chains are all the same length, this definition is equivalent\nto the one in the last section.  This generalized variance estimator\nand the within-chains variance estimates may be plugged directly into\nthe formula for $\\hat{R}$ from the previous section.\n\n\n\\subsection{Split $\\hat{R}$ for Detecting Non-Stationarity}\n\nBefore calculating the potential-scale-reduction statistic $\\hat{R}$,\neach chain may be split into two halves.  This provides an additional\nmeans to detect non-stationarity in the chains.  If one chain involves\ngradually increasing values and one involves gradually decreasing\nvalues, they have not mixed well, but they can have $\\hat{R}$ values\nnear unity.  In this case, splitting each chain into two parts leads\nto $\\hat{R}$ values substantially greater than 1 because the first\nhalf of each chain has not mixed with the second half.\n\n\n\\subsection{Convergence is Global}\n\nA question that often arises is whether it is acceptable to monitor\nconvergence of only a subset of the parameters or generated\nquantities.  The short answer is ``no,'' but this is elaborated\nfurther in this section.\n\nFor example, consider the value \\code{lp\\_\\_}, which is the log\nposterior density (up to a constant) It is a mistake to declare\nconvergence in any practical sense if \\code{lp\\_\\_} has not converged,\nbecause different chains are really in different parts of the space.\nYet measuring convergence for \\code{lp\\_\\_} is particularly tricky, as\nnoted below.\n\n\\subsubsection{Asymptotics and transience vs.\\ equilibrium}\n\nMarkov chain convergence is a global property in the sense that it\ndoes not depend on the choice of function of the parameters that is\nmonitored.  There is no hard cutoff between pre-convergence\n``transience'' and post-convergence ``equilibrium.''  What happens is\nthat as the number of states in the chain approaches infinity, the\ndistribution of possible states in the chain approaches the target\ndistribution and in that limit the expected value of the Monte Carlo\nestimator of any integrable function converges to the true\nexpectation. There is nothing like warmup here, because in the limit,\nthe effects of initial state are completely washed out.\n\n\\subsubsection{Multivariate convergence of functions}\n\nThe $\\hat{R}$ statistic considers the composition of a Markov chain\nand a function, and if the Markov chain has converged then each Markov\nchain and function composition will have converged. Multivariate\nfunctions converge when all of their margins have converged by the\nCramer-Wold theorem.\n\nThe transformation from unconstrained space to constrained space is\njust another function, so does not effect convergence.\n\nDifferent functions may have different autocorrelations, but if the\nMarkov chain has equilibrated then all Markov chain plus function\ncompositions should be consistent with convergence. Formally, any\nfunction that appears inconsistent is of concern and although it would\nbe unreasonable to test every function, \\code{lp\\_\\_} and other\nmeasured quantities should at least be consistent.\n\nThe obvious difference in \\code{lp\\_\\_} is that it tends to vary\nquickly with position and is consequently susceptible to outliers.\n\n\\subsubsection{Finite numbers of states}\n\nThe question is what happens for finite numbers of states? If we can\nprove a strong geometric ergodicity property (which depends on the\nsampler and the target distribution), then one can show that there\nexists a finite time after which the chain forgets its initial state\nwith a large probability. This is both the autocorrelation time and\nthe warmup time.  But even if you can show it exists and is finite\n(which is nigh impossible) you can't compute an actual value\nanalytically.\n\nSo what we do in practice is hope that the finite number of draws is\nlarge enough for the expectations to be reasonably accurate. Removing\nwarmup iterations improves the accuracy of the expectations but there\nis no guarantee that removing any finite number of samples will be\nenough.\n\n\\subsubsection{Why inconsistent $\\hat{R}$?}\n\nThere are two things to worry about here.\n\nFirstly, as noted above, for any finite number of draws, there will\nalways be some residual effect of the initial state, which typically\nmanifests as some small (or large if the autocorrelation time is huge)\nprobability of having a large outlier. Functions robust to such\noutliers (say, quantiles) will appear more stable and have better\n$\\hat{R}$. Functions vulnerable to such outliers may show fragility.\n\nSecondly, use of the $\\hat{R}$ statistic makes very strong\nassumptions. In particular, it assumes that the functions being\nconsidered are Gaussian or it only uses the first two moments and\nassumes some kind of independence.  The point is that strong\nassumptions are made that do not always hold. In particular, the\ndistribution for the log posterior density (\\code{lp\\_\\_}) almost\nnever looks Gaussian, instead it features long tails that can lead to\nlarge $\\hat{R}$ even in the large $N$ limit.  Tweaks to $\\hat{R}$,\nsuch as using quantiles in place of raw values, have the flavor of\nmaking the samples of interest more Gaussian and hence the $\\hat{R}$\nstatistic more accurate.\n\n\\subsubsection{Final words on convergence monitoring}\n\n``Convergence'' is a global property and holds for all integrable\nfunctions at once, but employing the $\\hat{R}$ statistic requires\nadditional assumptions and thus may not work for all functions equally\nwell.\n\nNote that if you just compare the expectations between chains then we\ncan rely on the Markov chain asymptotics for Gaussian distributions\nand can apply the standard tests.\n\n\n\n\\section{Effective Sample Size}\\label{effective-sample-size.section}\n\nThe second technical difficulty posed by \\MCMC methods is that the\nsamples will typically be autocorrelated within a chain.  This\nincreases the uncertainty of the estimation of posterior quantities of\ninterest, such as means, variances or quantiles.\n\nA nice introductory reference for analyzing MCMC results in general\nand effective sample size in particular is \\citep{Geyer:2011}.  The\nparticular calculations used by Stan follow those for split-$\\hat{R}$,\nwhich involve both cross-chain (mean) and within-chain calculations\n(autocorrelation); they were introduced in this manual and explained\nin more detail in \\citep{GelmanEtAl:2013}.\n\n\\subsection{Definition of Effective Sample Size}\n\nThe amount by which autocorrelation within the chains increases\nuncertainty in estimates can be measured by effective sample size\n({\\sc ess}).  Given independent samples, the central limit theorem\nbounds uncertainty in estimates based on the number of samples $N$.\nGiven dependent samples, the number of independent samples is replaced\nwith the effective sample size $N_{\\mbox{\\scriptsize eff}}$, which is\nthe number of independent samples with the same estimation power as\nthe $N$ autocorrelated samples.  For example, estimation error is\nproportional to $1/\\sqrt{N_{\\mbox{\\scriptsize eff}}}$ rather than\n$1/\\sqrt{N}$.\n\nThe effective sample size of a sequence is defined in terms of the\nautocorrelations within the sequence at different lags.  The\nautocorrelation $\\rho_t$ at lag $t \\geq 0$ for a chain with joint\nprobability function $p(\\theta)$ with mean $\\mu$ and variance\n$\\sigma^2$ is defined to be\n\\[\n\\rho_t\n=\n\\frac{1}{\\sigma^2} \\, \\int_{\\Theta} (\\theta^{(n)} - \\mu)\n(\\theta^{(n+t)} - \\mu) \\, p(\\theta) \\, d\\theta.\n\\]\nThis is just the correlation between the two chains offset by $t$\npositions.  Because we know $\\theta^{(n)}$ and $\\theta^{(n+t)}$ have\nthe same marginal distribution in an \\MCMC setting, multiplying the\ntwo difference terms and reducing yields\n\\[\n\\rho_t\n=\n\\frac{1}{\\sigma^2} \\, \\int_{\\Theta} \\theta^{(n)} \\, \\theta^{(n+t)} \\, p(\\theta) \\, d\\theta.\n\\]\n\nThe effective sample size of $N$ samples generated by a process with\nautocorrelations $\\rho_t$ is defined by\n\\[\nN_{\\mbox{\\scriptsize eff}}\n\\ = \\\n\\frac{N}{\\sum_{t = -\\infty}^{\\infty} \\rho_t}\n\\ = \\\n\\frac{N}{1 + 2 \\sum_{t = 1}^{\\infty} \\rho_t}.\n\\]\n\n\\subsection{Estimation of Effective Sample Size}\n\nIn practice, the probability function in question cannot be tractably\nintegrated and thus the autocorrelation cannot be calculated, nor the\neffective sample size.  Instead, these quantities must be estimated\nfrom the samples themselves.  The rest of this section describes a\nvariogram-based estimator for autocorrelations, and hence effective sample\nsize, based on multiple chains. For simplicity, each chain\n$\\theta_m$ will be assumed to be of length $N$.\n\nOne way to estimate the effective sample size is based on the\nvariograms $V_t$ at lag $t \\in \\setlist{0,1\\ldots}$.  The variograms are\ndefined as follows for (univariate) samples $\\theta_m^{(n)}$, where $m \\in\n\\setlist{1,\\ldots,M}$ is the chain, and $N_m$ is the number of samples\nin chain $m$.\n\\[\nV_t =\n\\frac{1}{M}\n\\,\n\\sum_{m=1}^M\n\\\n\\left(\n\\frac{1}{N_m - t}\n\\sum_{n=t+1}^{N_m}\n\\left(\n\\theta_m^{(n)} - \\theta_m^{(n-t)}\n\\right)^2\n\\right).\n\\]\n%\nThe variogram along with the multi-chain variance estimate\n$\\widehat{\\mbox{var}}^{+}$ introduced in the previous section can be\nused to estimate the autocorrelation at lag $t$ as\n\\[\n\\hat{\\rho}_t\n= 1 - \\frac{\\displaystyle V_t}{\n            \\displaystyle 2 \\, \\widehat{\\mbox{var}}^{+}}.\n\\]\nIf the chains have not converged, the variance estimator\n$\\widehat{\\mbox{var}}^{+}$ will overestimate variance,\nleading to an overestimate of autocorrelation and an underestimate\neffective sample size.\n\nBecause of the noise in the correlation estimates $\\hat{\\rho}_t$ as $t$\nincreases, typically only the initial estimates of $\\hat{\\rho}_t$\nwhere $\\hat{\\rho}_t > 0$ will be used.  Setting $T'$ to be the\nfirst lag such that $\\rho_{T' + 1} < 0$,\n%\n\\[\nT' = \\arg\\min_t \\ \\hat{\\rho}_{t+1} < 0,\n\\]\nthe effective sample size estimator is defined as\n\\[\n\\hat{N}_{\\mbox{\\scriptsize eff}}\n=\n\\frac{1}{2}\n\\,\n\\frac{MN}\n     {1 + \\sum_{t=1}^{T'} \\hat{\\rho}_t}.\n\\]\n%\nExact autocorrelations can happen only on odd lags \\citep{Geyer:2011}.\nBy summing over pairs, the paired autocorrelation is guaranteed to be\npositive modulo estimator noise.  This is the motivation behind the\nmany termination criterion of \\cite{Geyer:2011}. Stan does not (yet)\ndo the paired expectations because NUTS almost by construction avoids\nthe negative autocorrelation regime.  Thus terminating at the first\nnegative autocorrelation is a reasonable approximation for stopping\nwhen the noise in the autocorrelation estimator dominates.\n\nStan carries out the autocorrelation computations for all lags\nsimultaneously using Eigen's fast Fourier transform (FFT) package with\nappropriate padding; see \\citep{Geyer:2011} for more detail on using\nFFT for autocorrelation calculations.\n\n\n\\subsection{Thinning Samples}\n\nIn the typical situation, the autocorrelation, $\\rho_t$, decreases as\nthe lag, $t$, increases.  When this happens, thinning the samples will\nreduce the autocorrelation.  For instance, consider generating one\nthousand samples in one of the following two ways.\n%\n\\begin{enumerate}\n\\item Generate 1000 samples after convergence and save all of\n  them.\n\\item Generate 10,000 samples after convergence and save every tenth\n  sample.\n\\end{enumerate}\n%\nEven though both produce one thousand samples, the second approach\nwith thinning will produce more effective samples.  That's because the\nautocorrelation $\\rho_t$ for the thinned sequence is equivalent to\n$\\rho_{10t}$ in the unthinned samples, so the sum of the autocorrelations\nwill be lower and thus the effective sample size higher.\n\nOn the other hand, if memory and data storage are no object, saving all\nten thousand samples will have a higher effective sample size than\nthinning to one thousand samples.\n\n\n\\chapter{Penalized Maximum Likelihood Point Estimation}\\label{mle.chapter}\n\n\\noindent\nThis chapter defines the workhorses of non-Bayesian estimation,\nmaximum likelihood and penalized maximum likelihood, and relates them\nto Bayesian point estimation based on posterior means, medians, and\nmodes.  Such estimates are called ``point estimates'' because they\nare composed of a single value for the model parameters $\\theta$\nrather than a posterior distribution.\n\nStan's optimizer can be used to implement (penalized) maximum\nlikelihood estimation for any likelihood function and penalty function\nthat can be coded in Stan's modeling language.  Stan's optimizer can\nalso be used for point estimation in Bayesian settings based on\nposterior modes.  Stan's Markov chain Monte Carlo samplers can be used\nto implement point inference in Bayesian models based on posterior\nmeans or medians.\n\n\\section{Maximum Likelihood Estimation}\\label{mle.section}\n\nGiven a likelihood function $p(y|\\theta)$ and a fixed data vector $y$,\nthe maximum likelihood estimate (MLE) is the parameter vector $\\hat{\\theta}$\nthat maximizes the likelihood, i.e.,\n\\[\n\\hat{\\theta} = \\mbox{argmax}_{\\theta} \\ p(y|\\theta).\n\\]\nIt is usually more convenient to work on the log scale.\nAn equivalent%\n%\n\\footnote{The equivalence follows from the fact that densities are\n  positive and the log function is strictly monotonic, i.e.,\n  $p(y|\\theta) \\geq 0$ and for all $a, b > 0$, $\\log a > \\log b$ if and\n  only if $a > b$.}\n%\nformulation of the MLE is\n%\n\\[\n\\hat{\\theta} = \\mbox{argmax}_{\\theta} \\ \\log p(y|\\theta).\n\\]\n\n\\subsection{Existence of Maximum Likelihood Estimates}\n\nBecause not all functions have unique maximum values, maximum\nlikelihood estimates are not guaranteed to exist.  As discussed in\n\\refchapter{problematic-posteriors}, this situation can arise when\n%\n\\begin{itemize}\n\\item there is more than one point that maximizes the likelihood function,\n\\item the likelihood function is unbounded, or\n\\item the likelihood function is bounded by an asymptote that is never\n  reached for legal parameter values.\n\\end{itemize}\n%\nThese problems persist with the penalized maximum likelihood estimates\ndiscussed in the next section, and Bayesian posterior modes as\ndiscussed in the following section.\n\n\n\\subsection{Example: Linear Regression}\n\nConsider an ordinary linear regression problem with an $N$-dimensional\nvector of observations $y$, an $(N \\times K)$-dimensional data matrix\n$x$ of predictors, a $K$-dimensional parameter vector $\\beta$ of\nregression coefficients, and a real-valued noise scale $\\sigma > 0$,\nwith log likelihood function\n\\[\n\\log p(y|\\beta,x) = \\sum_{n=1}^N \\log \\distro{Normal}(y_n|x_n \\beta,\n\\sigma).\n\\]\n%\nThe maximum likelihood estimate for $\\theta = (\\beta,\\sigma)$ is just\n\\[\n(\\hat{\\beta},\\hat{\\sigma})\n\\ = \\\n\\mbox{argmax}_{\\beta,\\sigma}\n\\log p(y|\\beta,\\sigma,x) = \\sum_{n=1}^N \\log \\distro{Normal}(y_n|x_n \\beta, \\sigma).\n\\]\n\n\\subsubsection{Squared Error}\n\nA little algebra on the log likelihood function shows that the\nmarginal maximum likelihood estimate $\\hat{\\theta} =\n(\\hat{\\beta},\\hat{\\sigma})$ can be equivalently formulated for\n$\\hat{\\beta}$ in terms of least squares.  That is, $\\hat{\\beta}$ is\nthe value for the coefficient vector that minimizes the sum of squared\nprediction errors,\n%\n\\[\n\\hat{\\beta}\n\\ = \\\n\\mbox{argmin}_{\\beta} \\sum_{n=1}^N (y_n - x_n \\beta)^2\n\\ = \\\n\\mbox{argmin}_{\\beta} (y - x \\beta)^{\\top} (y - x\\beta).\n\\]\n%\nThe residual error for data item $n$ is the difference between the\nactual value and predicted value, $y_n - x_n \\hat{\\beta}$.  The\nmaximum likelihood estimate for the noise scale, $\\hat{\\sigma}$ is\njust the square root of the average squared residual,\n\\[\n\\hat{\\sigma}^2\n\\ = \\\n\\frac{1}{N} \\sum_{n=1}^N \\left( y_n - x_n \\hat{\\beta} \\right)^2\n\\ = \\\n\\frac{1}{N} (y - x \\hat{\\beta})^{\\top} (y - x\\hat{\\beta}).\n\\]\n\n\\subsubsection{Minimizing Squared Error in Stan}\n\nThe squared error approach to linear regression can be directly coded\nin Stan with the following model.\n%\n\\begin{stancode}\ndata {\n  int<lower=0> N;\n  int<lower=1> K;\n  vector[N] y;\n  matrix[N,K] x;\n}\nparameters {\n  vector[K] beta;\n}\ntransformed parameters {\n  real<lower=0> squared_error;\n  squared_error = dot_self(y - x * beta);\n}\nmodel {\n  target += -squared_error;\n}\ngenerated quantities {\n  real<lower=0> sigma_squared;\n  sigma_squared = squared_error / N;\n}\n\\end{stancode}\n%\nRunning Stan's optimizer on this model produces the MLE for the linear\nregression by directly minimizing the sum of squared errors and using\nthat to define the noise scale as a generated quantity.\n\nBy replacing \\code{N} with \\code{N-1} in the denominator of the\ndefinition of \\code{sigma\\_squared}, the more commonly supplied\nunbiased estimate of $\\sigma^2$ can be calculated; see\n\\refsection{estimation-bias} for a definition of estimation bias and a\ndiscussion of estimating variance.\n\n\n\n\\section{Penalized Maximum Likelihood Estimation}\n\nThere is nothing special about a likelihood function as far as the\nability to perform optimization is concerned.  It is common among\nnon-Bayesian statisticians to add so-called ``penalty'' functions\nto log likelihoods and optimize the new function.  The penalized\nmaximum likelihood estimator for a log likelihood function\n$\\log p(y|\\theta)$ and penalty function $r(\\theta)$ is defined to be\n\\[\n\\hat{\\theta} = \\mbox{argmax}_{\\theta} \\log p(y|\\theta) - r(\\theta).\n\\]\nThe penalty function $r(\\theta)$ is negated in the maximization so\nthat the estimate $\\hat{\\theta}$ balances maximizing the log\nlikelihood and minimizing the penalty.  Penalization is sometimes\ncalled ``regularization.''\n\n\n\\subsection{Examples}\\label{penalized-mle-examples}\n\n\\subsubsection{Ridge Regression}\n\nRidge regression \\citep{HoerlKennard:1970} is based on penalizing the\nEuclidean length of the coefficient vector $\\beta$. The ridge penalty\nfunction is\n%\n\\[\nr(\\beta)\n\\ = \\\n\\lambda \\, \\sum_{k=1}^K \\beta_k^2\n\\ = \\\n\\lambda \\, \\beta^{\\top} \\beta,\n\\]\n%\nwhere $\\lambda$ is a constant tuning parameter that determines the\nmagnitude of the penalty.\n\n\nTherefore, the penalized maximum likelihood estimate for ridge\nregression is just\n%\n\\[\n(\\hat{\\beta},\\hat{\\sigma})\n\\ = \\\n\\mbox{argmax}_{\\beta,\\sigma} \\,\n \\sum_{n=1}^N \\log \\distro{Normal}(y_n|x_n \\beta, \\sigma) - \\lambda\n \\sum_{k=1}^K \\beta_k^2\n\\]\n%\nThe ridge penalty is sometimes called L2 regularization or shrinkage,\nbecause of its relation to the L2 norm.\n\nLike the basic MLE for linear regression, the ridge regression\nestimate for the coefficients $\\beta$ can also be formulated in terms\nof least squares,\n%\n\\[\n\\hat{\\beta}\n\\ = \\\n\\mbox{argmin}_{\\beta} \\, \\sum_{n=1}^N (y_n - x_n \\beta)^2 + \\sum_{k=1}^K \\beta_k^2\n\\ = \\\n\\mbox{argmin}_{\\beta} \\, (y - x\\beta)^{\\top} (y - x\\beta) +\n\\lambda \\beta^{\\top} \\beta.\n\\]\n\nThe effect of adding the ridge penalty function is that the ridge\nregression estimate for $\\beta$ is a vector of shorter length, or in\nother words, $\\hat{\\beta}$ is shrunk.  The ridge estimate does not\nnecessarily have a smaller absolute $\\beta_k$ for each $k$, nor does\nthe coefficient vector necessarily point in the same direction as the\nmaximum likelihood estimate.\n\nIn Stan, adding the ridge penalty involves adding its magnitude as a\ndata variable and the penalty itself to the model block,\n%\n\\begin{stancode}\ndata {\n  // ...\n  real<lower=0> lambda;\n}\n// ...\nmodel {\n  // ...\n  target += - lambda * dot_self(beta);\n}\n\\end{stancode}\n%\nThe noise term calculation remains the same.\n\n\\subsubsection{The Lasso}\n\nThe lasso \\citep{Tibshirani:1996} is an alternative to ridge\nregression that applies a penalty based on the sum of the absolute\ncoefficients, rather than the sum of their squares,\n\\[\nr(\\beta) = \\lambda \\sum_{k=1}^K | \\beta_k |.\n\\]\nThe lasso is also called L1 shrinkage due to its relation to the L1\nnorm, which is also known as taxicab distance or Manhattan distance.\n\nBecause the derivative of the penalty does not depend on the value of\nthe $\\beta_k$,\n\\[\n\\frac{d}{d\\beta_k} \\lambda \\sum_{k=1}^K | \\beta_k | =\n\\mbox{signum}(\\beta_k),\n\\]\nit has the effect of shrinking parameters all the way to 0 in maximum\nlikelihood estimates.  Thus it can be used for variable selection as\nwell as just shrinkage.%\n%\n\\footnote{In practice, Stan's gradient-based optimizers are not\n  guaranteed to produce exact zero values; see\n  \\cite{LangfordEtAl:2009} for a discussion of getting exactly zero\n  values with gradient descent.}\n%\nThe lasso can be implemented in Stan just as easily as ridge\nregression, with the magnitude declared as data and the penalty added\nto the model block,\n%\n\\begin{stancode}\ndata {\n  // ...\n  real<lower=0> lambda;\n}\n// ...\nmodel {\n  // ...\n  for (k in 1:K)\n    target += - lambda * fabs(beta[k]);\n}\n\\end{stancode}\n\n\\subsubsection{The Elastic Net}\n\nThe naive elastic net \\citep{ZouHastie:2005} involves a weighted\naverage of ridge and lasso penalties, with a penalty function\n\\[\nr(\\beta)\n= \\lambda_1 \\sum_{k=1}^K |\\beta_k|\n+ \\lambda_2 \\sum_{k=1}^K \\beta_k^2.\n\\]\nThe naive elastic net combines properties of both ridge regression and\nthe lasso, providing both identification and variable selection.\n\nThe naive elastic net can be implemented directly in Stan by combining\nimplementations of ridge regression and the lasso, as\n%\n\\begin{stancode}\ndata {\n  real<lower=0> lambda1;\n  real<lower=0> lambda2;\n  // ...\n}\n// ...\nmodel {\n  // ...\n  for (k in 1:K)\n    target += -lambda1 * fabs(beta[k]);\n  target += -lambda2 * dot_self(beta);\n}\n\\end{stancode}\n%\nNote that the signs are negative in the program because $r(\\beta)$ is\na penalty function.\n\nThe elastic net \\citep{ZouHastie:2005} involves adjusting the final estimate for\n$\\beta$ based on the fit $\\hat{\\beta}$ produced by the naive elastic\nnet.  The elastic net estimate is\n\\[\n\\hat{\\beta} = (1 + \\lambda_2) \\beta^*\n\\]\nwhere $\\beta^{*}$ is the naive elastic net estimate.\n\nTo implement the elastic net in Stan, the data, parameter, and model\nblocks are the same as for the naive elastic net.  In addition, the\nelastic net estimate is calculated in the generated quantities block.\n%\n\\begin{stancode}\ngenerated quantities {\n  vector[K] beta_elastic_net;\n  // ...\n  beta_elastic_net = (1 + lambda2) * beta;\n}\n\\end{stancode}\n%\nThe error scale also needs to be calculated in the generated\nquantities block based on the elastic net coefficients\n\\code{beta\\_elastic\\_net}.\n\n\n\\subsubsection{Other Penalized Regressions}\n\nIt is also common to use penalty functions that bias the coefficient\nestimates toward values other than 0, as in the estimators of\n\\cite{JamesStein:1961}.  Penalty functions can also be used to bias\nestimates toward population means; see\n\\citep{EfronMorris:1975,Efron:2012}.  This latter approach is similar\nto the hierarchical models commonly employed in Bayesian statistics.\n\n\n\\section{Estimation Error, Bias, and Variance}\\label{estimation-bias.section}\n\nAn estimate $\\hat{\\theta}$ depends on the particular data $y$ and\neither the log likelihood function, $\\log p(y|\\theta)$, penalized log\nlikelihood function $\\log p(y|\\theta) - r(\\theta)$, or log probability\nfunction $\\log p(y,\\theta) = \\log p(y,\\theta) + \\log p(\\theta)$.  In\nthis section, the notation $\\hat{\\theta}$ is overloaded to indicate\nthe estimator, which is an implicit function of the data and\n(penalized) likelihood or probability function.\n\n\\subsection{Estimation Error}\n\nFor a particular observed data set $y$ generated according to true\nparameters $\\theta$, the estimation error is the difference between\nthe estimated value and true value of the parameter,\n\\[\n\\mbox{err}(\\hat{\\theta}) = \\hat{\\theta} - \\theta.\n\\]\n%\n\n\\subsection{Estimation Bias}\n\nFor a particular true parameter value $\\theta$ and a likelihood\nfunction $p(y|\\theta)$, the expected estimation error averaged over\npossible data sets $y$ according to their density under the likelihood\nis\n%\n\\[\n\\mathbb{E}_{p(y|\\theta)}[\\hat{\\theta}]\n\\ = \\\n\\int \\left( \\mbox{argmax}_{\\theta'} p(y|\\theta') \\right) p(y|\\theta) dy.\n\\]\n\nAn estimator's bias is the expected estimation error,\n%\n\\[\n\\mathbb{E}_{p(y|\\theta)}[\\hat{\\theta} - \\theta]\n\\ = \\\n\\mathbb{E}_{p(y|\\theta)}[\\hat{\\theta}] - \\theta\n\\]\n%\nThe bias is a multivariate quantity with the same dimensions as\n$\\theta$.  An estimator is unbiased if its expected estimation error\nis zero and biased otherwise.\n\n\\subsubsection{Example: Estimating a Normal Distribution}\n\nSuppose a data set of observations $y_n$ for $n \\in 1{:}N$ drawn from\na normal distribution.  This presupposes a model $y_n \\sim\n\\distro{Normal}(\\mu,\\sigma)$, where both $\\mu$ and $\\sigma > 0$ are\nparameters.  The log likelihood is just\n\\[\n\\log p(y|\\mu,\\sigma) = \\sum_{n=1}^N \\log\n\\distro{Normal}(y_n|\\mu,\\sigma).\n\\]\nThe maximum likelihood estimator for $\\mu$ is just the sample mean,\ni.e., the average of the samples,\n\\[\n\\hat{\\mu} = \\frac{1}{N} \\sum_{n=1}^N y_n.\n\\]\nThe maximum likelihood estimate for the mean is unbiased.\n\nThe maximum likelihood estimator for the variance $\\sigma^2$ is the\naverage of the squared difference from the mean,\n\\[\n\\hat{\\sigma}^2 = \\frac{1}{N} \\sum_{n=1}^N (y_n - \\hat{\\mu})^2.\n\\]\nThe maximum likelihood for the variance is biased on the low side,\ni.e.,\n%\n\\[\n\\mathbb{E}_{p(y|\\mu,\\sigma)}[\\hat{\\sigma}^2] < \\sigma.\n\\]\n%\nThe reason for this bias is that the maximum likelihood estimate is\nbased on the difference from the estimated mean $\\hat{\\mu}$.  Plugging\nin the actual mean can lead to larger sum of squared differences;  if\n$\\mu \\neq \\hat{\\mu}$, then\n\\[\n\\frac{1}{N} \\sum_{n=1}^N (y_n - \\mu)^2\n>\n\\frac{1}{N} \\sum_{n=1}^N (y_n - \\hat{\\mu})^2.\n\\]\n\nAn alternative estimate for the variance is the sample variance, which\nis defined by\n\\[\n\\hat{\\mu} = \\frac{1}{N-1} \\sum_{n=1}^N (y_n - \\hat{\\mu})^2.\n\\]\nThis value is larger than the maximum likelihood estimate by a factor\nof $N/(N-1)$.\n\n\n\\subsection{Estimation Variance}\n\nThe variance of component $k$ of an estimator $\\hat{\\theta}$ is\ncomputed like any other variance, as the expected squared difference\nfrom its expectation,\n%\n\\[\n\\mbox{var}_{p(y|\\theta})[\\hat{\\theta}_k]\n\\ = \\\n\\mathbb{E}_{p(y|\\theta})[\\, (\\hat{\\theta}_k -\n\\mathbb{E}_{p(y|\\theta)}[\\hat{\\theta}_k])^2 \\,].\n\\]\n%\nThe full $K \\times K$ covariance matrix for the estimator is thus\ndefined, as usual, by\n%\n\\[\n\\mbox{covar}_{p(y|\\theta)}[\\hat{\\theta}]\n\\ = \\\n\\mathbb{E}_{p(y|\\theta})[\\, (\\hat{\\theta} - \\mathbb{E}[\\hat{\\theta}]) \\,\n                         (\\hat{\\theta} -\n                         \\mathbb{E}[\\hat{\\theta}])^{\\top} \\, ].\n\\]\n\nContinuing the example of estimating the mean and variance of a normal\ndistribution based on sample data, the maximum likelihood estimator\n(i.e., the sample mean) is the unbiased estimator for the mean $\\mu$\nwith the lowest variance; the Gauss-Markov theorem establishes this\nresult in some generality for least-squares estimation, or\nequivalently, maximum likelihood estimation under an assumption of\nnormal noise; see \\citep[Section~3.2.2]{HastieTibshiraniFriedman:2009}.\n\n\\chapter{Bayesian Point Estimation}\n\nThere are three common approaches to Bayesian point estimation based\non the posterior $p(\\theta|y)$ of parameters $\\theta$ given observed\ndata $y$: the mode (maximum), the mean, and the median.\n\n\\section{Posterior Mode Estimation}\n\nThis section covers estimates based on the parameters $\\theta$ that\nmaximize the posterior density, and the next sections continue with\ndiscussions of the mean and median.\n\nAn estimate based on a model's posterior mode can be defined by\n%\n\\[\n\\hat{\\theta} = \\mbox{argmax}_{\\theta} \\, p(\\theta|y).\n\\]\n%\nWhen it exists, $\\hat{\\theta}$ maximizes the posterior density of the\nparameters given the data.  The posterior mode is sometimes called the\n``maximum a posteriori'' (MAP) estimate.\n\nAs discussed in \\refchapter{problematic-posteriors} and\n\\refsection{mle}, a unique posterior mode might not\nexist---there may be no value that maximizes the posterior mode or\nthere may be more than one.  In these cases, the posterior mode\nestimate is undefined.  Stan's optimizer, like most optimizers, will\nhave problems in these situations.  It may also return a locally\nmaximal value that is not the global maximum.\n\nIn cases where there is a posterior mode, it will correspond to a\npenalized maximum likelihood estimate with a penalty function equal to\nthe negation of the log prior.  This is because Bayes's rule,\n\\[\np(\\theta|y) = \\frac{p(y|\\theta) \\, p(\\theta)}{p(y)},\n\\]\nensures that\n%\n\\begin{eqnarray*}\n\\mbox{argmax}_{\\theta} \\ p(\\theta|y)\n& = &\n\\mbox{argmax}_{\\theta} \\ \\frac{p(y|\\theta) \\, p(\\theta)}{p(y)}\n\\\\[6pt]\n& = &\n\\mbox{argmax}_{\\theta} \\ p(y|\\theta) \\, p(\\theta),\n\\end{eqnarray*}\n%\nand the positiveness of densities and the strict monotonicity of log\nensure that\n\\[\n\\mbox{argmax}_{\\theta} \\ p(y|\\theta) \\, p(\\theta)\n\\ = \\\n\\mbox{argmax}_{\\theta} \\ \\log p(y|\\theta) + \\log p(\\theta).\n\\]\n%\n\nIn the case where the prior (proper or improper) is uniform, the\nposterior mode is equivalent to the maximum likelihood estimate.\n\nFor most commonly used penalty functions, there are probabilistic\nequivalents.  For example, the ridge penalty function corresponds to a\nnormal prior on coefficients and the lasso to a Laplace prior.  The\nreverse is always true---a negative prior can always be treated as a\npenalty function.\n\n\n\n\\section{Posterior Mean Estimation}\n\nA standard Bayesian approach to point estimation is to use the\nposterior mean (assuming it exists), defined by\n%\n\\[\n\\hat{\\theta} = \\int \\theta \\, p(\\theta|y) \\, d\\theta.\n\\]\n%\nThe posterior mean is often called {\\it the}\\ Bayesian estimator,\nbecause it's the estimator that minimizes the expected square error of\nthe estimate.\n\nAn estimate of the posterior mean for each parameter is returned by\nStan's interfaces;  see the RStan, CmdStan, and PyStan user's guides\nfor details on the interfaces and data formats.\n\nPosterior means exist in many situations where posterior\nmodes do not exist.  For example, in the $\\distro{Beta}(0.1, 0.1)$\ncase, there is no posterior mode, but posterior mean is well defined\nwith value 0.5.\n\nA situation where posterior means fail to exist but posterior modes do\nexist is with a posterior with a Cauchy distribution\n$\\distro{Cauchy}(\\mu,\\tau)$.  The posterior mode is $\\mu$, but the\nintegral expressing the posterior mean diverges.  Such diffuse priors\nrarely arise in practical modeling applications; even with a Cauchy\nCauchy prior for some parameters, data will provide enough constraints\nthat the posterior is better behaved and means exist.\n\nSometimes when posterior means exist, they are not meaningful, as in\nthe case of a multimodal posterior arising from a mixture model or in\nthe case of a uniform distribution on a closed interval.\n\n\n\\section{Posterior Median Estimation}\n\nThe posterior median (i.e., 50th percentile or 0.5 quantile) is\nanother popular point estimate reported for Bayesian models.  The\nposterior median minimizes the expected absolute error of estimates.\nThese estimates are returned in the various Stan interfaces;  see the\nRStan, PyStan and CmdStan user's guides for more information on\nformat.\n\nAlthough posterior medians may fail to be meaningful, they often exist\neven where posterior means do not, as in the Cauchy distribution.\n\n\n\n\\chapter{Variational Inference}\\label{vi-advanced.chapter}\n\n\\noindent\nStan implements an automatic variational inference algorithm that leverages\nthe transformations from \\refchapter{variable-transforms}.\n\nClassical variational inference algorithms are difficult to\nderive. We must first define the family of approximating\ndensities, and then calculate model-specific quantities relative\nto that family to solve the variational optimization problem.  Both\nsteps require expert knowledge.  The resulting algorithm is tied to\nboth the model and the chosen approximation.\n\nWe begin by briefly describing the classical variational inference framework.\nFor a thorough exposition, please refer to\n\\citet{Jordan:1999,Wainwright-Jordan:2008}; for a textbook presentation, please\nsee \\citet{Bishop:2006}. We follow with a high-level description of Automatic\nDifferentiation Variational Inference (ADVI). For more details, see\n\\citep{Kucukelbir:2015}.\n\n\n\\section{Classical Variational Inference}\n\nVariational inference approximates the\nposterior $p(\\theta \\, | \\, y)$ with a simple, parameterized distribution\n$q(\\theta \\, | \\, \\phi)$. It matches the approximation to the\ntrue posterior by minimizing the Kullback-Leibler (KL) divergence,\n%\n\\[\n  \\phi^* = \\argmin_\\phi\n  \\KL{q(\\theta \\, | \\, \\phi) }{ p(\\theta \\mid y)}.\n\\]\n%\nTypically the KL divergence lacks an analytic, closed-form solution.\nInstead we maximize a proxy to the KL divergence, the evidence lower bound\n(ELBO)\n%\n\\[\n  \\mathcal{L} (\\phi)\n  =\n  \\E_{q (\\theta)} \\big[ \\log p (y,\\theta) \\big]\n  -\n  \\E_{q (\\theta)} \\big[ \\log q (\\theta\\, | \\,\\phi) \\big].\n\\]\n%\nThe first term is an expectation of the log\njoint density under the approximation, and the second is the entropy of the\nvariational density. Maximizing the ELBO minimizes the KL\ndivergence \\citep{Jordan:1999,Bishop:2006}.\n\n\n\\section{Automatic Variational Inference}\n\nADVI maximizes the ELBO in the real-coordinate space. Stan transforms the\nparameters from (potentially) constrained domains to\nthe real-coordinate space. We denote the combined transformation as\n$T:\\theta \\to \\zeta$, with the $\\zeta$ variables living in $\\mathbb{R}^K$.\nThe variational objective (ELBO) becomes\n%\n\\[\n  \\mathcal{L}(\\phi)\n  =\n  \\E_{q(\\zeta\\,|\\,\\phi)}\n  \\bigg[\n  \\log p (y, T^{-1}(\\zeta))\n  +\n  \\log \\big| \\det J_{T^{-1}}(\\zeta) \\big|\n  \\bigg]\n  -\n  \\E_{q (\\zeta\\, | \\,\\phi)} \\big[ \\log q (\\zeta\\, | \\,\\phi) \\big].\n\\]\n%\nSince the $\\zeta$ variables live in the real-coordinate space, we can choose a\nfixed family for the variational distribution. We choose a fully-factorized\nGaussian,\n%\n\\[\n  q(\\zeta \\, | \\, \\phi)\n  =\n  \\distro{Normal}\\left(\\zeta \\, | \\, \\mu, \\sigma\\right)\n  =\n  \\prod_{k=1}^K\n  \\distro{Normal}\n  \\left(\\zeta_k \\, | \\, \\mu_k, \\sigma_k\\right),\n\\]\n%\nwhere the vector\n$\\phi = (\\mu_{1},\\cdots,\\mu_{K}, \\sigma_ {1},\\cdots,\\sigma_{K})$\nconcatenates the mean and standard deviation of each Gaussian factor.\nThis reflects the ``mean-field'' assumption in classical variational\ninference algorithms; we will refer to this particular decomposition\nas the \\texttt{meanfield} option.\n\nThe transformation $T$ maps the support of the parameters to the real\ncoordinate space. Thus, its inverse $T^{-1}$ maps back to the support of the\nlatent variables. This implicitly defines the variational approximation in the\noriginal latent variable space as\n%\n\\[\n\\distro{Normal} \\left(T(\\theta) \\, | \\, \\mu, \\sigma\\right)\n\\big| \\det J_{T}(\\theta) \\big|.\n\\]\nThis is, in general, not a Gaussian distribution.\nThis choice may call to mind the Laplace approximation\ntechnique, where a second-order Taylor expansion around the\nmaximum-a-posteriori estimate gives a Gaussian approximation to the\nposterior. However, they are not the same \\citep{Kucukelbir:2015}.\n\nThe variational objective (ELBO) that we maximize is,\n\\[\n  \\mathcal{L}(\\phi)\n  =\n  \\E_{q(\\zeta\\, | \\,\\phi)}\n  \\bigg[\n  \\log p (y, T^{-1}(\\zeta))\n  +\n  \\log \\big| \\det J_{T^{-1}}(\\zeta) \\big|\n  \\bigg]\n  +\n  \\sum_{k=1}^K \\log \\sigma_k,\n\\]\nwhere we plug in the analytic form for the Gaussian entropy and drop all terms\nthat do not depend on $\\phi$. We discuss how we perform the maximization in\n\\refchapter{vi-algorithms}.\n\n", "meta": {"hexsha": "159d172fd0dbc1df170b6e0be19e48aca0cea04f", "size": 50267, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "cmdstan/stan/src/docs/stan-reference/inference.tex", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/src/docs/stan-reference/inference.tex", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/src/docs/stan-reference/inference.tex", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0336917563, "max_line_length": 102, "alphanum_fraction": 0.7407444248, "num_tokens": 13562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.6442251201477015, "lm_q1q2_score": 0.3296606911471148}}
{"text": "\\documentclass[a4paper,11pt]{article}\n\\usepackage[T1]{fontenc}\n\\usepackage[utf8]{inputenc}\n\\usepackage{lmodern}\n\\usepackage[english]{babel}\n\\usepackage{amsmath}\n\\usepackage{graphicx}\n\\usepackage[labelformat=empty]{caption}\n\\usepackage[section]{placeins}\n\\usepackage{textcomp}\n\\usepackage{listings}\n\n\\lstdefinestyle{preformated}{\n  language=C,\n  stepnumber=1,\n  numbersep=7pt,\n  tabsize=2,\n  showspaces=false,\n  showstringspaces=false\n}\n\\lstset{basicstyle=\\small,style=preformated}\n\n\\title{Gelasia binary number representation.}\n\\author{Francisco Casas B.}\n\n\\begin{document}\n\n\\maketitle\n\n\\begin{abstract}\nThe present document shows a way to represent integer numbers of any size on a binary digits array, saving at the same time both it's value and it's size, this in order to store or send a group of well delimited numbers on a compact and scalable way, ensuring the small numbers to use less space. This can also be used when seting up standars, avoiding issues related to indexation (like, the overflow of a fixed space to countain addresses, or a very expensive memory reserve for a large number range, that's not totally used on most of the cases).\n\\end{abstract}\n\n\\tableofcontents\n\n\\section{Deduction}\n\\subsection{Previous analysis}\nNormally, the amount of numbers that's possible to represent on a given space of $n$ bits is $2^n$. If we consider only positive integers (because starting from $0$ makes the deduction harder) the range of representable values is $[1,2^n]$ then, on a rough approach, if it's necessary to represent a number and delimitate it, we would take the number on it's binary form (after substracting $1$) and count the possition of the most significant 1 as the size of it, it's size has to be somehow stored, but that will be threated later, for now, the numbers will be represented this way:\n\\begin{center} \\begin{lstlisting}\n\t 1 = [size:1] 0\n\t 2 = [size:1] 1\n\t 3 = [size:2] 10\n\t 4 = [size:2] 11\n\t 5 = [size:3] 100\n\t 6 = [size:3] 101\n\t 7 = [size:3] 110\n\t 8 = [size:3] 111\n\t 9 = [size:4] 1000\n\t10 = [size:4] 1001\n\t11 = [size:4] 1010\n\t12 = [size:4] 1011\n\t13 = [size:4] 1100\n\t14 = [size:4] 1101\n\t15 = [size:4] 1110\n\t16 = [size:4] 1111\n\t17 = [size:5] 10000\n\t      ...\n\\end{lstlisting} \\end{center}\n\nThen, if both the number and it's size are known, it's logical to think that if a number is big enough to requiere it's size, it's possible to dischard that the number has values that can be represented with smaller sizes:\n\\begin{center} \\begin{lstlisting}\n\t 1 = [size:1] 0\n\t 2 = [size:1] 1\n\t 3 = [size:2] 00\n\t 4 = [size:2] 01\n\t 5 = [size:2] 10\n\t 6 = [size:2] 11\n\t 7 = [size:3] 000\n\t 8 = [size:3] 001\n\t 9 = [size:3] 010\n\t10 = [size:3] 011\n\t11 = [size:3] 100\n\t12 = [size:3] 101\n\t13 = [size:3] 110\n\t14 = [size:3] 111\n\t15 = [size:4] 0000\n\t16 = [size:4] 0001\n\t17 = [size:4] 0010\n\t      ...\n\\end{lstlisting} \\end{center}\nNow every possible value is being used, so, to get a number $N$ given it's size $S$ and this value $X$ (that will be called extra from now), the next formula will be used.\n\\begin{align*}\n\tN&= X +1 + \\sum_{1\\leq i < S}{2^i} \\\\\n\t&= X+1+ \\frac{2^{S}-2}{2-1} \\\\\n\t&= X+2^{S}-1\n\\end{align*}\nNow, since the size $S$ of a number, is also a number, it can be represented the same way, but, because $S>0$, it's better to store $S-1$. We can do so, until the size$-1$ of a size is $0$, The result is as follows:\n\\begin{center} \\begin{lstlisting}\n\t 1 = [size:1] 0\n\t 2 = [size:1] 1\n\t 3 = [size:2] 00 = [size:1] 0 00\n\t 4 = [size:2] 01 = [size:1] 0 01\n\t 5 = [size:2] 10 = [size:1] 0 10\n\t 6 = [size:2] 11 = [size:1] 0 11\n\t 7 = [size:3] 000 = [size:1] 1 000\n\t 8 = [size:3] 001 = [size:1] 1 001\n\t 9 = [size:3] 010 = [size:1] 1 010\n\t10 = [size:3] 011 = [size:1] 1 011\n\t11 = [size:3] 100 = [size:1] 1 100\n\t12 = [size:3] 101 = [size:1] 1 101\n\t13 = [size:3] 110 = [size:1] 1 110\n\t14 = [size:3] 111 = [size:1] 1 111\n\t15 = [size:4] 0000 = [size:2] 00 0000 = [size:1] 0 00 0000\n\t16 = [size:4] 0001 = [size:2] 00 0001 = [size:1] 0 00 0001\n\t17 = [size:4] 0010 = [size:2] 00 0010 = [size:1] 0 00 0010\n\t      ...\t\n\\end{lstlisting} \\end{center}\nThe only information that's then needed to recover a number besides the secuence of digits on the right is how many times the size-1 representation algorithm was applied (this will be called recursivity), since this number grows on a very slow rate it can be represented on the most primitive way that allows an infinite size, this is a series of $1$ ended by a $0$, where the amount of $1$'s is the number of times that the algorithm had to be applied:\n\\begin{center} \\begin{lstlisting}\n           1 = 0 0 \n           2 = 0 1\n           3 = 10 0 00\n           4 = 10 0 01 \n           5 = 10 0 10 \n           6 = 10 0 11 \n           7 = 10 1 000 \n           8 = 10 1 001 \n           9 = 10 1 010 \n          10 = 10 1 011 \n          11 = 10 1 100 \n          12 = 10 1 101 \n          13 = 10 1 110 \n          14 = 10 1 111 \n          15 = 110 0 00 0000 \n          16 = 110 0 00 0001 \n          17 = 110 0 00 0010 \n          18 = 110 0 00 0011 \n\t      \t\t...\t\n\\end{lstlisting} \\end{center}\nNot only the number it's stored on these bits, also it's size, that allows many numbers to be added contiguously on a bit array without need of a delimitator of additional data.\n\\subsection{Unsigned gelasia representation}\nNow, with the last results, it's possible to substract $1$ to the values in order to have a representation for the $0$. This results on the following final representation:\n\\begin{center} \\begin{lstlisting}\n           0 = 0 0 \n           1 = 0 1\n           2 = 10 0 00\n           3 = 10 0 01 \n           4 = 10 0 10 \n           5 = 10 0 11 \n           6 = 10 1 000 \n           7 = 10 1 001 \n           8 = 10 1 010 \n           9 = 10 1 011 \n          10 = 10 1 100 \n          11 = 10 1 101 \n          12 = 10 1 110 \n          13 = 10 1 111 \n          14 = 110 0 00 0000\n          25 = 110 0 00 1011 \n         125 = 110 0 10 111111 \n         625 = 110 1 001 001110011 \n        3125 = 110 1 011 10000110111 \n       15625 = 110 1 101 1110100001011 \n       78125 = 1110 0 00 0000 0011000100101111 \n      390625 = 1110 0 00 0010 011111010111100011 \n     1953125 = 1110 0 00 0100 11011100110101100111 \n     9765625 = 1110 0 00 0111 00101010000001011111011 \n    48828125 = 1110 0 00 1001 0111010010000111011011111 \n   244140625 = 1110 0 00 1011 110100011010100101001010011 \n  1220703125 = 1110 0 00 1110 001000110000100111001110010111 \n  6103515625 = 1110 0 01 00000 01101011110011000100000111101011 \n 30517578125 = 1110 0 01 00010 1100011010111111010100100110001111 \n152587890625 = 1110 0 01 00101 0001110000110111100100110111111000011\n\t             ...\t\n\\end{lstlisting} \\end{center}\nWhere a number is determinated by the next formula, the calculation of the size $S$ will be shown later:\n\\begin{align*}\n\tN &= X+2^{S}-2\n\\end{align*}\n\\subsection{Signed gelasia representation}\nIt's also possible to add a sign bit when necessary, not substracting the $1$ above mentioned to the absolute value of the negative numbers, in order to get only one representation of the value $0$. This sign bit will be $1$ for negative numbers and $0$ otherwise:\n\\begin{center} \\begin{lstlisting}\n\t      ...\n\t-15 = 1 110 0 00 0000 \n\t-14 = 1 10 1 111 \n\t-13 = 1 10 1 110 \n\t-12 = 1 10 1 101 \n\t-11 = 1 10 1 100 \n\t-10 = 1 10 1 011 \n\t -9 = 1 10 1 010 \n\t -8 = 1 10 1 001 \n\t -7 = 1 10 1 000 \n\t -6 = 1 10 0 11 \n\t -5 = 1 10 0 10 \n\t -4 = 1 10 0 01 \n\t -3 = 1 10 0 00\n\t -2 = 1 0 1\n\t -1 = 1 0 0 \n\t  0 = 0 0 0 \n\t  1 = 0 0 1\n\t  2 = 0 10 0 00\n\t  3 = 0 10 0 01 \n\t  4 = 0 10 0 10 \n\t  5 = 0 10 0 11 \n\t  6 = 0 10 1 000 \n\t  7 = 0 10 1 001 \n\t  8 = 0 10 1 010 \n\t  9 = 0 10 1 011 \n\t 10 = 0 10 1 100 \n\t 11 = 0 10 1 101 \n\t 12 = 0 10 1 110 \n\t 13 = 0 10 1 111 \n\t 14 = 0 110 0 00 0000 \n\t        ...\t\n\\end{lstlisting} \\end{center}\nThen, if B is the sign bit of a number, it's value would be:\n\\begin{align*}\n\tN&= (X+2^{S}-2)(1-2B)-B\n\\end{align*}\n\n\\section{Calculation of a number's size}\nFor a positive number $N$ (before substracting $1$) the size $S$ is the position (from right to left, starting from $0$) of the most significant $1$ of the binary representation of the value $N+1$, this also applies to a negative number with it's absolute value. And is deducted from the equation $N = X+2^{S}-1$.\n\\\\ Once the value $S$ is known, the following amounts of bits should be added to $S$ to complete the total size.\n\\begin{center}\n\t\\begin{tabular}{ r || c| c || c}\n\t\tS & recursivity & size indication & total \\\\\n\t\t\\hline \n\t\t1 & 1 & 0 & S+1 \\\\\n\t\t2-3 & 2 & 1 & S+3 \\\\\n\t\t4-7 & 3 & 3 & S+6 \\\\\n\t\t8-15 & 3 & 4 & S+7 \\\\\n\t\t16-31 & 4 & 7 & S+11 \\\\\n\t\t32-63 & 4 & 8 & S+12 \\\\\n\t\t64-127 & 4 & 9 & S+13 \\\\\n\t\t128-255 & 4 & 10 & S+14 \\\\\n\t\t256-511 & 4 & 12 & S+15 \\\\\n\t\t512-1023 & 4 & 13 & S+16 \\\\\n\t\t1024-2047 & 4 & 14 & S+17 \\\\\n\t\t2048-4095 & 4 & 15 & S+18 \\\\\n\t\t4096-8191 & 4 & 16 & S+19 \\\\\n\t\t8192-16383 & 4 & 17 & S+20 \\\\\n\t\t16384-32767 & 4 & 18 & S+21 \\\\\n\t\t32768-65535 & 4 & 19 & S+22 \\\\\t  \n\t\t65536-131071 & 5 & 23 & S+28 \\\\\n\t\t131072-262143 & 5 & 24 & S+29\n\t\\end{tabular}\n\\end{center} \nThen, if an unsigned number is smaller than $2^{21}-1=2097151$ (before substracting $1$) it's granteed to use the same or less of the space that's possible to allocate on 32 bits.\n\tIf the representation is signed, $1$ extra bit should be added.\n\\section{Possible variantions}\nIt's possible to set the minimal recursivity to $0$ instead of $1$, this will give a natural representation for the number $0$ that only requires one bit, but will imply for all the other values to have an aditional $1$ on it's recursivity header.\n\\begin{center} \\begin{lstlisting}\n           0 = 0\n           1 = 10 0 \n           2 = 10 1\n           3 = 110 0 00\n           4 = 110 0 01 \n           5 = 110 0 10 \n           6 = 110 0 11 \n           7 = 110 1 000 \n           8 = 110 1 001 \n           9 = 110 1 010 \n          10 = 110 1 011 \n          11 = 110 1 100 \n          12 = 110 1 101 \n          13 = 110 1 110 \n          14 = 110 1 111 \n          15 = 1110 0 00 0000 \n          16 = 1110 0 00 0001 \n          17 = 1110 0 00 0010 \n          18 = 1110 0 00 0011 \n\t      \t\t...\t\n\\end{lstlisting} \\end{center}\nAlso it's possible to add a base value to the size of all the numbers, for example $3$:\n\\begin{center} \\begin{lstlisting}\n           0 = 0 000\n           1 = 0 001\n           2 = 0 010\n           3 = 0 011\n           4 = 0 100\n           5 = 0 101\n           6 = 0 110\n           7 = 0 111\n           8 = 10 0 00 0000\n           9 = 10 0 00 0001\n          24 = 10 0 01 00000\n           \t   ...\t\n\\end{lstlisting} \\end{center}\nThis modifications, among others, like applying an offset, can be made to ensure that the most frequent numbers use less space.\n\\end{document}\n", "meta": {"hexsha": "393999bd5bf27199f5d31550582e20c2f84e7343", "size": 10634, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "representation/gelasia_representation.tex", "max_stars_repo_name": "Autopawn/gelasia-compacter", "max_stars_repo_head_hexsha": "f5f6a9527d9e354cfc98da8ca5db78867eb7fc2b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "representation/gelasia_representation.tex", "max_issues_repo_name": "Autopawn/gelasia-compacter", "max_issues_repo_head_hexsha": "f5f6a9527d9e354cfc98da8ca5db78867eb7fc2b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "representation/gelasia_representation.tex", "max_forks_repo_name": "Autopawn/gelasia-compacter", "max_forks_repo_head_hexsha": "f5f6a9527d9e354cfc98da8ca5db78867eb7fc2b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8434163701, "max_line_length": 584, "alphanum_fraction": 0.6133157796, "num_tokens": 4159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.32966068415638444}}
{"text": "\n\n    \\filetitle{weeksinyear}{Number of weeks in year}{dates/weeksinyear}\n\n\t\\paragraph{Syntax}\\label{syntax}\n\n\\begin{verbatim}\nN = weeksinyear(Year)\n\\end{verbatim}\n\n\\paragraph{Input arguments}\\label{input-arguments}\n\n\\begin{itemize}\n\\itemsep1pt\\parskip0pt\\parsep0pt\n\\item\n  \\texttt{Year} {[} numeric {]} - Year.\n\\end{itemize}\n\n\\paragraph{Output arguments}\\label{output-arguments}\n\n\\begin{itemize}\n\\itemsep1pt\\parskip0pt\\parsep0pt\n\\item\n  \\texttt{N} {[} numeric {]} - Number of weeks in \\texttt{Year}.\n\\end{itemize}\n\n\\paragraph{Description}\\label{description}\n\nThe number of weeks in a year is either \\texttt{52} or \\texttt{53}, and\ncomplies with the definition of the first week in a year in ISO 8601.\nThe first week of a year is the one that contains the 4th day of January\n(in other words, has most of its days in that year).\n\n\\paragraph{Example}\\label{example}\n\n\\begin{verbatim}\nweeksinyear(2000:2010)\nans =\n    52    52    52    52    53    52    52    52    52    53    52\n\\end{verbatim}\n\n\n", "meta": {"hexsha": "3a32da7f486adb16c496f7ba68d9cff1e674df08", "size": 995, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "-help/dates/weeksinyear.tex", "max_stars_repo_name": "OGResearch/IRIS-Toolbox-For-Octave", "max_stars_repo_head_hexsha": "682ea1960229dc701e446137623b120688953cef", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-12-06T13:38:38.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-06T13:38:38.000Z", "max_issues_repo_path": "-help/dates/weeksinyear.tex", "max_issues_repo_name": "OGResearch/IRIS-Toolbox-For-Octave", "max_issues_repo_head_hexsha": "682ea1960229dc701e446137623b120688953cef", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-03-28T08:13:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-02T10:40:25.000Z", "max_forks_repo_path": "-help/dates/weeksinyear.tex", "max_forks_repo_name": "OGResearch/IRIS-Toolbox-For-Octave", "max_forks_repo_head_hexsha": "682ea1960229dc701e446137623b120688953cef", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-17T07:06:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T07:06:39.000Z", "avg_line_length": 23.1395348837, "max_line_length": 72, "alphanum_fraction": 0.7145728643, "num_tokens": 322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.3296368577597111}}
{"text": "\\documentclass[paper-main.tex]{subfiles}\n\n\\begin{document}\n\nIn this section, we explore how our apparatus can be used to teach a selection of signal processing techniques. \nWe use complex audio signals (such as music and speech) as natural successors to the constant and wandering tones used in Sections~\\ref{sec:single_tone} and~\\ref{sec:viterbi_wandering}, respectively.\nAs complex audio signals are not quasi-monochromatic, the Viterbi algorithm used in Section~\\ref{sec:viterbi_wandering} is not directly applicable here. \nInstead, we use a hierarchy of passive filters which suppress noise, yet do not assume any specific form of the signal, unlike the Fourier-based maximum likelihood filter which is tuned to the sinusoidal signals in Section~\\ref{sec:single_tone} and Appendix~\\ref{app:sinusoid_likelihood}.\n\n\nWe use the Michelson interferometer as an ``optical microphone'' to detect sound, replacing the components of a conventional microphone with a laser interferometer.\nThe only change to our apparatus is replacing the webcam with a photodiode to allow us to capture the higher frequencies necessary for speech and music (see Section~\\ref{sec:photodiode}). \nOptical microphones have precedence in the laser microphones~\\cite{laser_microphone} which are (or were historically) used in the defense industry and operate on a variety of related principles. \nOur objective is to play a recording of speech or music through the speaker attached to mirror M2 (see Fig.~\\ref{fig:ifo_schematic_webcam}), record the resulting interference pattern, and then recover the original signal via a selection of signal processing techniques. \n\n\n\nThe apparatus serves as an independent demonstration for a broader physics and engineering audience, particularly in undergraduate laboratories. \nWe describe additional hardware components required for this demonstration in Section~\\ref{sec:photodiode} and the initial results in Section~\\ref{sec:initialResultsOpMic}. \nWe consider a selection of filter techniques, details of which, along with a summary of digital signal processing resources, can be found in the Supplementary Material. \nIn Section~\\ref{sec:opticalMicResults}, we present the two best-performing techniques from the Supplementary Material. \n\n\n\n\\subsection{Hardware modifications for the optical microphone}\n\\label{sec:photodiode}\nThe human ear can hear frequencies in the range of $\\sim 20\\,{\\rm Hz}$--$20\\,{\\rm kHz}$. \nSpeech intelligibility (the ability to understand speech) requires frequencies up to $3\\,{\\rm kHz}$ and music requires up to and beyond $8\\,{\\rm kHz}$. \nTherefore, the optical microphone requires a sample rate of at least $16\\,{\\rm kHz}$ to capture both speech and music (adjusting for the Nyquist frequency). \nThis cannot be achieved with the webcam used in Sections~\\ref{sec:single_tone} and ~\\ref{sec:viterbi_wandering} as it has a sampling rate of $30\\,{\\rm Hz}$ and thus can only ``hear'' frequencies below $15\\,{\\rm Hz}$.\nTo overcome this issue, we use a photodiode~\\footnote{A photodiode is an electrical component that acts as a regular diode when no light is incident on it, blocking any current flow in the reverse direction. As the intensity of incident light rises, it becomes increasingly conductive in the reverse direction.} at the output of the interferometer to achieve a sampling rate of $16\\,{\\rm kHz}$.\n\nWe place an OSRAM BPW21 photodiode in reverse-bias over an LM358 op-amp which together produce a voltage that depends on the incident intensity. \nThe photodiode records the interference pattern at roughly the same off-center position as the webcam in Sections~\\ref{sec:single_tone} and~\\ref{sec:viterbi_wandering}, again chosen arbitrarily. \nThe voltage signal from the photo-detector is captured by an MCP3008 $10$-bit analog-to-digital converter (ADC) connected to a Raspberry Pi Model 3 v1.2, which provides a convenient means to record the photodiode data.\nTogether, the circuit samples the signal at $\\sim 16\\,{\\rm kHz}$. \nResources for using the Raspberry~Pi and photodiode, including a circuit diagram, are described in the Supplementary Material.\n\nSampling any frequency component of the analog signal above the Nyquist frequency of $8\\,{\\rm kHz}$ leads to aliasing (folding of frequencies greater than half the sampling rate) into the detected range. We include an anti-aliasing Sallen-Key filter with a cut-off frequency of $8\\,{\\rm kHz}$ before the ADC to prevent this from happening. \nThis component attenuates any frequencies above $8\\,{\\rm kHz}$ before they are digitally sampled. We also place a cloth screen over the face of the photodiode to reduce the incident intensity and avoid saturating the ADC -- an improvised, physical solution that could instead be replaced by scaling down the voltage electronically. This cloth screen was re-purposed grill cloth from a commercial speaker.\n\n\n\\subsection{Anti-aliased output}\n\\label{sec:initialResultsOpMic}\n\n\nWe test the optical microphone with a variety of recordings, including the speech of different people and music ranging from simple melodies and rhythms to songs. \nDuring recordings, care is taken to minimize activity around the demonstration to reduce environmental noise coupling into the interferometer. \nThe timeseries data is then directly converted to a .wav file and played as an audio recording using the \\texttt{scipy.io.wavfile.write} function in Python (see Appendix~\\ref{app:code}).\nWhen processing the results, we restrict our analysis to only the first $10\\,{\\rm s}$ of each observation (for efficiency), and only plot the first second here. \\han{NOTE!}\n\n\\han{NOTES!}\nThe raw output of the optical microphone (with anti-aliasing) is noisy with a loud, continuous bass hum. \nThis can be explained by looking at the power spectral density (PSD) of the background noise (i.e., the output with the speaker switched off), shown in Fig.~\\ref{fig:psd_noise}. \nThe spectrum is dominated by AC mains noise with power from the fundamental $50\\,{\\rm Hz}$ Australian mains power grid signal up to and beyond the $8$th harmonic. \nThe mains signal is also present, but far weaker, in the background spectrum taken with the photodiode in darkness, suggesting that ambient lighting has a large contribution. \nBesides lighting, other possible contributions to the mains signal include air conditioning and the photodiode circuit itself. \nThe appearance of harmonics of the mains noise might be due to the non-linearity in the system discussed in Section~\\ref{sec:ifo}. \nThe spectrum in Fig.~\\ref{fig:psd_noise} also has a broad feature at around $750\\,{\\rm Hz}$, the origin of which is yet to be determined.\nEnvironmental noise reduction for gravitational-wave detectors is an active area of research (see the Supplementary Material for further information and resources on this topic).\n\n\n\n\n\\begin{figure}\n\t\\includegraphics[width=.5\\textwidth]{figures/psd_podo_14_6.pdf}\n\t\\caption{\\label{fig:psd_noise}\nPower spectral density (PSD) of background noise from the optical microphone (with the speaker off). \nWe see strong power from the $50\\,{\\rm Hz}$ mains hum and its harmonics (most likely from the photodiode circuit and the room’s lighting and cooling). Otherwise, the PSD is fairly white except for a peak at around 0.75~kHz.\n}\n\\end{figure}\n\n\n\\subsection{Optical microphone results}\n\\label{sec:opticalMicResults}\n\n\\begin{figure*}\n\\begin{center}\n\\includegraphics[width=0.8\\textwidth]{figures/combined_highlight_results_melatos_labelled.pdf}\n\\caption{\\label{fig:notchWienerLogMMSEResults}\nTimeseries (left column) and frequency spectrum (right column) results with the optical microphone. \nThe original input signal in the first row is a $1\\,{\\rm s}$ recording of an adult male voice (saying ``a cathode''). \n The input signal is shifted by 0.12 s to the right to synchronize the manual delay from starting the recording with the Raspberry Pi and starting to play the source through the speaker. \nThe second row shows the raw output from the optical microphone when the input from the first row is played. \nThe third row shows the result of applying the notch and Wiener filters combined. \nThe fourth row shows the result of applying the logMMSE estimator, where the rise at the start of the timeseries is an expected effect when filtering a signal of finite duration. \n}\n\\end{center}\n\\end{figure*}\n\nWe explore several filters to remove the $50\\,{\\rm Hz}$ mains hum and harmonics and improve the speech intelligibility of the recording.\nThe Supplementary Material describes a range of analysis techniques that can be used as examples for the undergraduate laboratory. \nAll filters are tested on the same $1\\,{\\rm s}$ long speech recording.\nThe results of this section are shown in Fig.~\\ref{fig:notchWienerLogMMSEResults}. \nIn the figure, the left and right columns show the timeseries and frequency spectrum, respectively. \nThe first row shows the input signal played through the speaker (see Fig.~\\ref{fig:ifo_schematic_webcam}). \nThe second row shows the raw output from the photodiode recording. \n\n\n\nIn signal processing, the ideal filter would be one that:\n(i) completely attenuates the undesired parts of the spectrum, \n(ii) does not change the rest of the spectrum, and \n(iii) smoothly transitions between these regions, as to not damage the time domain signal when seen under convolution. \nHowever, these three conditions cannot all hold at once. \nFor example, if conditions (i) and (ii) hold, then the filter must be discontinuous at the boundary of the undesired region but this implies that the filter has ``infinite latency'' and so will affect (or damage) the time domain signal for infinite time.\\cite{10.5555/151045}\nTherefore, any filter must compromise between these three conditions. \nFor speech intelligibility, this means that either: (i) some noise remains in the filtered recording, (ii) some of the speech content is lost as certain important frequencies are attenuated, or (iii) the speech is somewhat distorted in time.\nAll three of these cases can, when taken to the extreme, make the speech intelligibility worse than the unfiltered recording. \nTherefore, we choose filters that compromise between achieving the three conditions.\n\n\nIn this section, we present the results of two advanced signal processing techniques applied to the optical microphone recordings. \nThe techniques are only briefly described here and we refer the reader to the Supplementary Material for further details and other analysis techniques. \n\n\n\nFirstly, we consider two signal processing techniques used in combination: the cascaded notch and the Wiener filter (see also the Supplementary Material). \nA notch filter removes signals within a specific frequency range. \nWe want to remove the $50\\,{\\rm Hz}$ mains noise and harmonics, therefore we use a cascaded notch filter where each notch is centered on one of the harmonics. \nThe Wiener filter is an advanced statistical technique that makes use of statistical information from the speech data and noise. \nIt amplifies parts of the signal with a high signal-to-noise ratio while suppressing parts with a low signal-to-noise ratio. \nThe results of the combined cascaded notch and Wiener filter are shown in the third row in Fig.~\\ref{fig:notchWienerLogMMSEResults}. \nMost of the mains noise is removed; however, the recovered voice sounds muffled and is not understandable. \n\n\nSecondly, we apply a speech enhancement technique. \nRef.~\\cite{SubjectiveComparison} compares $13$ speech enhancement methods, finding the log minimum mean-square error (logMMSE) estimator to be the best, qualitatively, at recovering speech (see also the Supplementary Material). \nWe use an existing implementation of the logMMSE from Ref.~\\cite{logmmse}.  \nThe logMMSE estimator results are shown in the bottom panels in Fig.~\\ref{fig:notchWienerLogMMSEResults}. \nWe see significant attenuation of the mains harmonics and general smoothing of the spectrum. \nMost of the background noise is removed; however, the logMMSE still does not significantly enhance the speech as the voice sounds muffled and indistinct.\n\n\nWe find some improvement with music over speech. \nSimple chords and drums can be heard after filtering, but more composite sounds and complex melodies cannot be heard clearly. \nOur observations suggest that this is especially true for certain instruments; in particular flutes and violins sometimes can’t be heard at all. \nThis could be a perceptual effect or a frequency dependence somewhere in the optical microphone.\nSpeculating, perhaps the speaker-mirror coupling is stronger at low frequencies and thus instruments like electric bass and drums sound louder in the results.\nTo address these problems, we need to determine whether the signals that are audibly missing (the diction in the speech and complex melodies in music) are indeed being transmitted through the optical microphone at all. \nTo determine this requires a better understanding of the system, as discussed in Section~\\ref{sec:future_work}.\n\n\n\n\\end{document}\n", "meta": {"hexsha": "febdefefeeac821e97594cc23b38366016ab2711", "size": 12998, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/ifo-complexAudio.tex", "max_stars_repo_name": "daccordeon/gravexplain", "max_stars_repo_head_hexsha": "4fb188b8bb37ba2c4f2b8eaf2ef478d278bbad09", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-11-26T21:44:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T14:36:34.000Z", "max_issues_repo_path": "paper/ifo-complexAudio.tex", "max_issues_repo_name": "daccordeon/gravexplain", "max_issues_repo_head_hexsha": "4fb188b8bb37ba2c4f2b8eaf2ef478d278bbad09", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2019-11-26T21:46:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-11T06:46:14.000Z", "max_forks_repo_path": "paper/ifo-complexAudio.tex", "max_forks_repo_name": "daccordeon/gravexplain", "max_forks_repo_head_hexsha": "4fb188b8bb37ba2c4f2b8eaf2ef478d278bbad09", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 89.0273972603, "max_line_length": 404, "alphanum_fraction": 0.7988152023, "num_tokens": 2890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3296368520330012}}
{"text": "\\documentclass[a4paper,man,natbib]{apa6}\n\\usepackage[english]{babel}\n\n\\usepackage[cache=false]{minted}\n\\usemintedstyle{vs}\n\\usepackage{xcolor}\n\\definecolor{bg}{rgb}{.95,.95,.95}\n\n\\graphicspath{ {./images/} }\n\\usepackage{graphicx}\n\\usepackage{caption}\n\n\\usepackage{setspace}\n\\usepackage{amsmath}\n\n\n\\title{Advanced Statistical Methods Homework 8 \\\\ Support Vector Machine}\n\\shorttitle{DAT 530 HW7}\n\\author{Brandon Hosley}\n\\date{\\today}\n\\affiliation{University of Illinois - Springfield}\n%\\abstract{}\n\n\\begin{document}\n\\maketitle\n\\singlespacing\n\n\\section{Intro to the Algorithm}\n\nSupport Vector Machines are a type of classification algorithm that is most commonly used for binary classification problems. Classification is performed by calculating a boundary to act as a decision line. Typically the boundary is optimized by calculating it to be as far from the sample points as possible.\n\n\\subsection{Intuition}\n\nThe boundary can be thought of as a hyperplane of one dimension less than the number of factors being used. A dataset with two factors may be represented as a two-dimensional graph, the classifier will be a one-dimensional hyperplane (a line) dividing the data, and the classifier will optimized to be a far from each cluster as possible.\n\nThe maximum margin can be achieved by plotting the hyperplane in a way such that at least three of the closest points to the line are equidistant; with at least one point coming from each class. In the case of overlapping classes or classes too close and too dense the hyperplane is calculated such that a fixed margin will contain the fewest possible points.\n\n\\begin{center}\n\t\\includegraphics[width=0.5\\linewidth]{Margins}\n\\end{center}\n\nIn the case of a linear classifier of the classic $y=wx + b$ notation we get the following equation. $\\lambda$ will represent the size of the margin.\n\n\\vspace{1em}\n$ \\left[ \\frac{1}{n} \\sum_{n}^{i=1} \\text{max} (0,1-y_i(w \\cdot x_i-b)) \\right] + \\lambda \\|w\\|^2 $\n\\vspace{1em}\n\n\\subsection{e1071}\n\nThe library used for this project will be e1071, which includes an SVM module. The type of SVM trained by e1071 is one in which the final model is a voting ensemble of $k(k-1)/2$ binary classifiers rather than a $k-1$ dimensional hyperplane. The ensemble method likely generalizes better as a library and is likely more robust under a large variety of user abilities and knowledge levels.\n\n\\clearpage\n\n\\section{Applying the Algorithm to Boston}\n\\subsection{Description of the Problem}\n\nThe \\textcolor{red}{Boston} data set has been a staple of this course. As we have gained a significant familiarity with the dataset it seems like a good option for exercising SVM use. A primary consideration when choosing a dataset for demonstrating SVMs is the limitation of input and output data. Input data should be quantitative and may be either continuous or discrete. The output is binary. \n\nA common use of the \\textcolor{red}{Boston} dataset, and what we will use it for in this assignment is using other attributes to predict crime in certain districts of the city. The data provided in \\textcolor{red}{Boston} is Quantitative with the exception of 'chas' which is a binary variable representing whether or not the district borders the Charles River. It is provided as a dummy variable; for this exercise we will not be using it.\n\n\\subsection{Summary of the Dataset and Preliminaries}\n\nBoston contains data gathered from a Census of the city of Boston Massachusetts taken in 1978. First we will load it into memory, load the e1071 library, and set a seed for repeatability. \n\n\\begin{minted}[bgcolor=bg]{r}\nlibrary(MASS)\nlibrary(e1071)\nset.seed(1234)\n\\end{minted}\n\n\\subsection{Training an SVM Model}\n\nTo begin we will make a copy of our data for preparation, remove the 'chas' variable, and normalize the data such that all variables will have a mean equal to zero and a standard deviation of one.\n\n\\begin{minted}[bgcolor=bg]{r}\nb = Boston\n# Remove Chas variable\nb <- subset(b,select=-c(chas))\n# Normalize the Data (mean=0, SD = 1)\nb <- as.data.frame(scale(b))\n\\end{minted}\n\nNext we will need to change the Crime statistic to be a factor, in this case we will only be predicting whether an area will be 'High Crime' or 'Low Crime' which specifically means whether the district will be in the upper 50\\% of crime or in the lower.\n\n\\begin{minted}[bgcolor=bg]{r}\n# Crim as a Factor(High = 1, Low = 0)\nb$crim <- ifelse(b$crim > 0, 1, 0)\nb$crim <- as.factor(b$crim)\n\\end{minted}\n\nNow we will separate the data into a training set and a test set.\n\n\\begin{minted}[bgcolor=bg]{r}\n# Separate a Training and Testing Set\nind = sort(sample(nrow(b), nrow(b)*0.8))\nb_train <- b[ind,]\nb_test <- b[-ind,]\n\\end{minted}\n\nFor the sake of exploring options we will train both a linear SVM and a polynomial SVM.\n\n\\begin{minted}[bgcolor=bg]{r}\n# Training both a Linear and Polynomial Model\nsvm_lin=svm(crim~., data=b_train, kernel =\"linear\", cost=1, scale=FALSE)\nsvm_poly=svm(crim~., data=b_train, kernel =\"polynomial\", cost=1, \n\t\t\t\tscale=FALSE)\n\\end{minted}\n\nLet us take a look at the summaries of the models trained above.\n\n\\begin{minted}[bgcolor=bg]{r}\nsummary(svm_lin)\n\\end{minted}\n\n\\vspace{-0.5em}\n\n\\begin{minted}{bash}\nCall:\nsvm(formula = crim ~ ., data = b_train, kernel = \"linear\", \n              cost = 1, scale = FALSE)\n\nParameters:\n    SVM-Type:  C-classification \n  SVM-Kernel:  linear \n        cost:  1 \n       gamma:  0.08333333 \n\nNumber of Support Vectors:  16\n( 9 7 )\n\nNumber of Classes:  2 \nLevels: \n0 1\n\\end{minted}\n\n\\begin{minted}[bgcolor=bg]{r}\nsummary(svm_poly)\n\\end{minted}\n\n\\vspace{-0.5em}\n\n\\begin{minted}{bash}\nCall:\nsvm(formula = crim ~ ., data = b_train, kernel = \"polynomial\", \n              cost = 1, scale = FALSE)\n\nParameters:\n    SVM-Type:  C-classification \n  SVM-Kernel:  polynomial \n        cost:  1 \n      degree:  3 \n       gamma:  0.08333333 \n      coef.0:  0 \n\nNumber of Support Vectors:  38\n( 24 14 )\n\nNumber of Classes:  2 \nLevels: \n0 1\n\\end{minted}\n\n\\subsection{Summary of the Results}\n\nThe models both appear to have a reasonable number of support vectors.\nNow we will need some predictions to test how effective the models are.\n\n\\begin{minted}[bgcolor=bg]{r}\n# Calculate Predictions\npred_lin = predict(svm_lin, b_test)\npred_poly = predict(svm_poly, b_test)\n\\end{minted}\n\nWe can then compare these predictions to the ground truth of the test set.\n\n\\begin{minted}[bgcolor=bg]{r}\ntable(predict=pred_lin, truth=b_test$crim)\n\\end{minted}\n\n\\begin{minted}{bash}\n       truth\npredict  0  1\n      0 77  0\n      1  1 24\n\\end{minted}\n\n\\begin{minted}[bgcolor=bg]{r}\ntable(predict=pred_poly, truth=b_test$crim)\n\\end{minted}\n\n\\begin{minted}{bash}\n       truth\npredict  0  1\n      0 77  0\n      1  1 24\n\\end{minted}\n\nThe models performance is identical. In this case with all other hyper-parameters being equal the linear kernel SVM is a better choice. Linear models are simpler than Polynomials; in this case the linear model requires less than half as many support vectors; and in the end, the linear model and the polynomial model make the same mistake.\n\n\\end{document}\n\n\\begin{minted}[bgcolor=bg]{r}\n\\end{minted}", "meta": {"hexsha": "7526a36da9b3603620bceb456ceecbbf666f9dcb", "size": 7105, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "2020-Fall Advanced Statistical Methods/HW 08/HW 08.2_Hosley.tex", "max_stars_repo_name": "bhosley/Schoolwork", "max_stars_repo_head_hexsha": "7c4eb909d2e6c65cd93b1c7fa744a183cebfc952", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2020-Fall Advanced Statistical Methods/HW 08/HW 08.2_Hosley.tex", "max_issues_repo_name": "bhosley/Schoolwork", "max_issues_repo_head_hexsha": "7c4eb909d2e6c65cd93b1c7fa744a183cebfc952", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2020-Fall Advanced Statistical Methods/HW 08/HW 08.2_Hosley.tex", "max_forks_repo_name": "bhosley/Schoolwork", "max_forks_repo_head_hexsha": "7c4eb909d2e6c65cd93b1c7fa744a183cebfc952", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0, "max_line_length": 440, "alphanum_fraction": 0.742575651, "num_tokens": 1927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.3296368447588545}}
{"text": "\\documentclass[12pt, titlepage]{article}\n\n\\usepackage{amsmath, mathtools}\n\n\\usepackage[round]{natbib}\n\\usepackage{amsfonts}\n\\usepackage{amssymb}\n\\usepackage{graphicx}\n\\usepackage{colortbl}\n\\usepackage{xr}\n\\usepackage{hyperref}\n\\usepackage{longtable}\n\\usepackage{xfrac}\n\\usepackage{tabularx}\n\\usepackage{float}\n\\usepackage{siunitx}\n\\usepackage{booktabs}\n\\usepackage{multirow}\n\\usepackage[section]{placeins}\n\\usepackage{caption}\n\\usepackage{fullpage}\n\\usepackage[nottoc, numbib]{tocbibind}\n\n\\hypersetup{\nbookmarks=true,     % show bookmarks bar?\ncolorlinks=true,       % false: boxed links; true: colored links\nlinkcolor=red,          % color of internal links (change box color with linkbordercolor)\ncitecolor=blue,      % color of links to bibliography\nfilecolor=magenta,  % color of file links\nurlcolor=cyan          % color of external links\n}\n\n\\usepackage{array}\n\n%% Comments\n\\newif\\ifcomments\\commentstrue\n\n\\ifcomments\n\\newcommand{\\authornote}[3]{\\textcolor{#1}{[#3 ---#2]}}\n\\newcommand{\\todo}[1]{\\textcolor{orange}{[TODO: #1]}}\n\\else\n\\newcommand{\\authornote}[3]{}\n\\newcommand{\\todo}[1]{}\n\\fi\n\n\\newcommand{\\wss}[1]{\\authornote{blue}{SS}{#1}}\n\\newcommand{\\bmac}[1]{\\authornote{red}{BM}{#1}}\n\\newcommand{\\sam}[1]{\\authornote{magenta}{SC}{#1}}\n\n\\newcommand{\\progname}{Projectile}\n\n\\begin{document}\n\n\\title{Module Interface Specification for Projectile}\n\n\\author{Samuel J. Crawford}\n\n\\date{\\today}\n\n\\maketitle\n\n\\pagenumbering{roman}\n\n\\newpage\n\n\\tableofcontents\n\n\\newpage\n\n\\section{Symbols, Abbreviations and Acronyms}\n\nSee SRS Documentation at \\url{https://jacquescarette.github.io/Drasil/examples/Projectile/srs/Projectile_SRS.pdf}\n\n\\pagenumbering{arabic}\n\n\\section{Introduction}\n\nThe following document details the Module Interface Specifications for the\nimplemented modules in a program simulating projectile motion. It is intended to \nease navigation through the program for design and maintenance purposes.\n\nComplementary documents include the System Requirement Specifications\nand Module Guide.\n%The full documentation and implementation can be\n%found at \\sam{No manual version of Projectile? Should this link be removed or  \n%should there be a link?}.\n\n% The specification is given in terms of functions, rather than sequences.  For\n% instance, the predicted temperature of the water is given as a function of time\n% ($\\mathbb{R} \\rightarrow \\mathbb{R})$, not as a sequence ($\\mathbb{R}^n$). This\n% approach is more straightforward for the specification, but in the\n% implementation stage, it will likely be necessary to introduce a\n% sequence, assuming that a numerical solver is used for the system of ODEs.\n\n\\section{Notation}\n\nThe structure of the MIS for modules comes from \\citet{HoffmanAndStrooper1995},\nwith the addition that template modules have been adapted from\n\\cite{GhezziEtAl2003}.  The mathematical notation comes from Chapter 3 of\n\\citet{HoffmanAndStrooper1995}.  For instance, the symbol := is used for a\nmultiple assignment statement and conditional rules follow the form $(c_1\n\\Rightarrow r_1 | c_2 \\Rightarrow r_2 | ... | c_n \\Rightarrow r_n )$.\n\n\\progname\\ uses strings and real numbers. For information on these data types \n(and others), see \\cite{GhezziEtAl2003}, \\cite{GriesAndSchneider1993}, and \n\\cite{HoffmanAndStrooper1995}. In addition, \\progname\\ uses functions, which are\ndefined by the data types of their inputs and outputs. Local functions are\ndescribed by giving their type signature followed by their specification.\n\n\\newpage\n\\section{Module Decomposition}\n\nThe following table is taken directly from the Module Guide document for this project.\n\n\\begin{table}[h!]\n\\centering\n\\begin{tabular}{p{0.3\\textwidth} p{0.6\\textwidth}}\n\\toprule\n\\textbf{Level 1} & \\textbf{Level 2}\\\\\n\\midrule\n\n{Hardware-Hiding} & ~ \\\\\n\\midrule\n\n\\multirow{5}{0.3\\textwidth}{Behaviour-Hiding} & Input Parameters\\\\\n& Calculations\\\\\n& Output Format\\\\\n% & Output Verification\\\\\n& Control Module\\\\\n& Specification Parameters Module\\\\\n\\midrule\n\n\\multirow{1}{0.3\\textwidth}{Software Decision} & Sequence Data Structure\\\\\n% & Plotting\\\\\n\\bottomrule\n\n\\end{tabular}\n\\caption{Module Hierarchy}\n\\label{TblMH}\n\\end{table}\n\n\\newpage\n\n\\section{MIS of Control Module} \\label{Main}\n\n\\subsection{Module}\n\nmain\n\n\\subsection{Uses}\n\nParam (Section~\\ref{Parameters}), Calculations (Section~\\ref{Calc}),\n% verify\\_output (Section~\\ref{VerifyOutput}), plot(Section~\\ref{Plot}),\nOutput (Section~\\ref{Output})\n\n\\subsection{Syntax}\n\n\\subsubsection{Exported Access Programs}\n\n\\begin{center}\n\\begin{tabular}{p{2cm} p{4cm} p{4cm} p{2cm}}\n\\hline\n\\textbf{Name} & \\textbf{In} & \\textbf{Out} & \\textbf{Exceptions} \\\\\n\\hline\nmain & - & - & - \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\n\\subsection{Semantics}\n\n\\subsubsection{State Variables}\n\nNone\n\n\\subsubsection{Access Routine Semantics}\n\n\\noindent main():\n\\begin{itemize}\n\\item transition: Modify the state of Param module and the environment variables\n  for the Output module by following these steps\\\\\n\\end{itemize}\n\n\\noindent Get (filenameIn: string) from user.\\\\\n\\noindent get\\_input(filenameIn, Param)\\\\\n\\noindent $p_{\\text{land}}$ := func\\_p\\_land(Param)\\\\\n\\noindent $d_{\\text{offset}}$ := func\\_d\\_offset(Param, $p_{\\text{land}}$)\\\\\n\\noindent $s$ := func\\_s(Param, $d_{\\text{offset}}$)\\\\\n\\noindent \\#\\textit{Output calculated values to a file.}\\\\\n% \\noindent verify\\_output($T_w$, $T_p$, $E_w$, $E_p$, $t_\\text{final}$)\\\\\n% \\noindent plot($T_w$, $T_p$, $E_w$, $E_p$, $t_\\text{final}$)\\\\\n\\noindent write\\_output($s$, $d_{\\text{offset}}$)\\\\\n\n\\newpage\n\n\\section{MIS of Input Parameters Module} \\label{Parameters}\n\nThe secrets of this module are the data structure for input parameters and how \nthe values are input and verified.\n\n\\subsection{Module}\n\nParam\n\n\\subsection{Uses}\n\nSpecParam (Section~\\ref{SpecParam})\n\n\\subsection{Syntax}\n\n\\begin{tabular}{p{3cm} p{2.5cm} p{1cm} >{\\raggedright\\arraybackslash}p{7.5cm}}\n\\toprule\n\\textbf{Name} & \\textbf{In} & \\textbf{Out} & \\textbf{Exceptions} \\\\\n\\midrule\nget\\_input & string, Param & - &  FileError \\\\\ninput\\_constraints & Param & - & badSpeed, badAngle, badTargetPosition\\\\\n$v_{\\text{launch}}$ & - & $\\mathbb{R}$ & -\\\\\n$\\theta$ & - & $\\mathbb{R}$ & -\\\\\n$p_{\\text{target}}$ & - & $\\mathbb{R}$ & -\\\\\n\\bottomrule\n\\end{tabular}\n\n\\subsection{Semantics}\n\n\\subsubsection{Environment Variables}\n\ninputFile: sequence of string \\#\\textit{f[i] is the ith string in the text file f}\n\n\\subsubsection{State Variables}\n\n\\# To Support IM1 and IM2 \\\\\n$v_{\\text{launch}}$: $\\mathbb{R}$\\\\\n$\\theta$: $\\mathbb{R}$\\\\\n\\# To Support IM3 and IM4 \\\\\n$p_{\\text{target}}$: $\\mathbb{R}$\\\\\n\n\\subsubsection{Assumptions}\n\n\\begin{itemize}\n\n\\item get\\_input will be called before the values of any state variables will \nbe accessed or verified.\n\n\\item The file contains the string equivalents of the numeric values for\neach input parameter in order, each on a new line. Any comments in the input file \nshould be denoted with a `\\#' symbol.\n\n\\end{itemize}\n\n\\subsubsection{Access Routine Semantics}\n\n\\noindent get\\_input(filename, Param):\n\\begin{itemize}\n\\item transition: The file name ``filename\" is first associated with the file $f$. \nThe following procedural specification is followed:\n\\begin{enumerate}\n\\item Read data sequentially from $f$ to populate the state variables from\nFR1 ($v_{\\text{launch}}$, $\\theta$, and $p_{\\text{target}}$) in Param.\n\\item input\\_constraints()\n\\end{enumerate}\n\n\\item exception: exc := a file name ``filename\" cannot be found OR the format of\ninputFile is incorrect $\\Rightarrow$  FileError\n\\end{itemize}\n\n\\noindent input\\_constraints():\n\\begin{itemize}\n\\item output: \\textit{out} := none\n\\item exception: exc := ( \\\\\n$\\neg (0 < v_{\\text{launch}}) \\Rightarrow$ badSpeed $|$\\\\\n$\\neg (0 < \\theta < \\frac{\\pi}{2}) \\Rightarrow$ badAngle $|$\\\\\n$\\neg (0 < p_{\\text{target}}) \\Rightarrow$ badTargetPosition)\n\\end{itemize}\n \n\\noindent Param.$v_{\\text{launch}}$:\n\\begin{itemize}\n\\item output: \\textit{out} := $v_{\\text{launch}}$\n\\item exception: none\n\\end{itemize}\n\n\\noindent Param.$\\theta$:\n\\begin{itemize}\n\\item output: \\textit{out} := $\\theta$\n\\item exception: none\n\\end{itemize}\n\n\\noindent Param.$p_{\\text{target}}$:\n\\begin{itemize}\n\\item output: \\textit{out} := $p_{\\text{target}}$\n\\item exception: none\n\\end{itemize}\n\n\\subsection{Considerations}\n\nThe value of each state variable can be accessed through its name (getter).  An\naccess program is available for each state variable.  There are no setters for\nthe state variables, since the values will be set by get\\_input and\nnot changed for the life of the program.\n\nSee Appendix (Section~\\ref{Appendix}) for the complete list of exceptions and\n associated error messages.\n\n\\newpage\n\n\\section{MIS of Calculations Module} \\label{Calc}\n\nThe secret of this module is how the required values are calculated.\n\n\\subsection{Module}\n\nCalculations\n\n\\subsection{Uses}\n\nParam (Section~\\ref{Parameters}), SpecParam (Section~\\ref{SpecParam})\n\n\\subsection{Syntax}\n\n\\subsubsection{Exported Access Programs}\n\n\\begin{center}\n \\begin{tabular}{p{3cm} p{3cm} p{1cm} p{8cm}}\n \\hline\n \\textbf{Name} & \\textbf{In} & \\textbf{Out} & \\textbf{Exceptions} \\\\\n \\hline\n func\\_p\\_land & Param & $\\mathbb{R}$ & None \\\\\n \\hline\n func\\_d\\_offset & Param, $\\mathbb{R}$ & $\\mathbb{R}$ & None \\\\\n \\hline\n func\\_s & Param, $\\mathbb{R}$ & String & None \\\\\n \\hline\n \\end{tabular}\n \\end{center}\n\n\\subsection{Semantics}\n\n\\subsubsection{Assumptions}\n\nAll of the fields Param have been assigned values before any of the access\n routines for this module are called.\n\n\\subsubsection{Access Routine Semantics}\n\nfunc\\_p\\_land(Param):\n \\begin{itemize}\n \\item out: $\\textit{out} := \\frac{2 * v_{\\text{launch}}^2 * sin(\\theta) * cos(\\theta)}{g}$\n \\item exception: exc := none\n \\end{itemize}\n \nfunc\\_d\\_offset(Param, $p_{\\text{land}}$):\n \\begin{itemize}\n \\item out: $\\textit{out} := p_{\\text{land}} - p_{\\text{target}}$\n \\item exception: exc := none\n \\end{itemize}\n \nfunc\\_s(Param, $d_{\\text{offset}}$):\n \\begin{itemize}\n \\item out: $\\textit{out} := $ ( \\\\\n$|\\frac{d_{\\text{offset}}}{p_{\\text{target}}}| < \\epsilon \\Rightarrow$ ``The target was hit.\" $|$\\\\\n$d_{\\text{offset}} < 0 \\Rightarrow$ ``The projectile fell short.\"$|$\\\\\n$\\text{True} \\Rightarrow$ ``The projectile went long.\")\n \\item exception: exc := none\n \\end{itemize}\n\n%\\newpage\n%\\section{MIS of Output Verification Module} \\label{VerifyOutput}\n%\n%\\subsection{Module}\n%\n%verify\\_output\n%\n%\\subsection{Uses}\n%\n%Param (Section~\\ref{Parameters})\n%\n%\\subsection{Syntax}\n%\n%\\subsubsection{Exported Constant}\n%\n%ADMIS\\_ER = $1 \\times 10^{-6}$\n%\n%\\subsubsection{Exported Access Programs}\n%\n%\\begin{center}\n%\\begin{tabular}{p{3cm} p{7cm} p{1cm} p{2cm}}\n%\\hline\n%\\textbf{Name} & \\textbf{In} & \\textbf{Out} & \\textbf{Exceptions} \\\\\n%\\hline\n%verify\\_output & $T_W(t):\\mathbb{R} \\rightarrow \\mathbb{R},\n%                 T_P(t):\\mathbb{R} \\rightarrow \\mathbb{R},\n%                 E_W(t):\\mathbb{R} \\rightarrow \\mathbb{R},\n%                 E_P(t):\\mathbb{R} \\rightarrow \\mathbb{R},\n%                 t_\\text{final}: \\mathbb{R}$ & - & EWAT\\_NOT\\_CONSERVE, EPCM\\_NOT\\_CONSERVE \\\\\n%\\hline\n%\\end{tabular}\n%\\end{center}\n%\n%\\subsection{Semantics}\n%\n%\\subsubsection{State Variables}\n%\n%None\n%\n%\\subsubsection{Assumptions}\n%\n%All of the fields of the input parameters structure have been assigned a\n%value.  \n%\n%\\subsubsection{Access Routine Semantics}\n%\n%\\noindent verify\\_output($T_W, T_P, E_W, E_P$, $t_\\text{final}$):\n%\\begin{itemize}\n%\\item exception: exc := (\n%\\end{itemize}\n%\n%\\noindent $\n%(\\forall t | 0 \\leq t \\leq t_\\text{final} : \\text{relErr}(E_W,\n%\\int_{0}^{t} h_C A_C (T_C - T_W(t)) dt - \\int_{0}^{t} h_P A_P (T_W(t)\n%- T_P(t)) dt) < \\text{ADMIS\\_ER}) \\Rightarrow \\text{EWAT\\_NOT\\_CONSERVE}\n%$\n%\n%$|$\n%\n%\\noindent $ \n%(\\forall t | 0 \\leq t \\leq t_\\text{final} : \\text{relErr}(E_{P}, \\int_{0}^{t}\n%h_{P} A_{P} (T_{W}(t) - T_{P}(t)) dt) < \\text{ADMIS\\_ER}) \\Rightarrow\n%\\text{EPCM\\_NOT\\_CONSERVE} \n%$\n%)\n%\n%\\subsubsection{Local Functions}\n%\n%relErr: $\\mathbb{R}$ $\\times$ $\\mathbb{R}$ $\\rightarrow$ $\\mathbb{R}$ \\\\\n%$\\text{relErr}(t, e) \\equiv \\frac{|t - e|}{|t|}$ \\\\\n%\\newline\n\n%\n%\\newpage\n%\\section{MIS of Plotting Module} \\label{Plot}\n%\n%\\subsection{Module}\n%\n%plot\n%\n%\\subsection{Uses}\n%\n%N/A\n%\n%\\subsection{Syntax}\n%\n%\\subsubsection{Exported Access Programs}\n%\n%\\begin{center}\n%\\begin{tabular}{p{2cm} p{8cm} p{2cm} p{2cm}}\n%\\hline\n%\\textbf{Name} & \\textbf{In} & \\textbf{Out} & \\textbf{Exceptions} \\\\\n%\\hline\n%plot & $T_W(t):\\mathbb{R} \\rightarrow \\mathbb{R},\n%                 T_P(t):\\mathbb{R} \\rightarrow \\mathbb{R},\n%                 E_W(t):\\mathbb{R} \\rightarrow \\mathbb{R},\n%       E_P(t):\\mathbb{R} \\rightarrow \\mathbb{R}$, $t_\\text{final}: \\mathbb{R}$ & - & - \\\\\n%\\hline\n%\\end{tabular}\n%\\end{center}\n%\n%\\subsection{Semantics}\n%\n%\\subsubsection{State Variables}\n%\n%None\n%\n%\\subsubsection{Environment Variables}\n%\n%win: 2D sequence of pixels displayed on the screen\\\\\n%\n%\\subsubsection{Assumptions}\n%\n%None\n%\n%\\subsubsection{Access Routine Semantics}\n%\n%\\noindent plot($T_w$, $T_p$, $E_w$, $E_p$, $t_\\text{final}$):\n%\\begin{itemize}\n%\\item transition: Modify win to display a plot where the vertical axis\n%  is time and one horizontal axis is temperature and the other\n%  horizontal axis is energy.  The time should run from $0$ to $t_\\text{final}$\n%\\item exception: none\n%\\end{itemize}\n\n\\newpage\n\\section{MIS of Output Module} \\label{Output}\n\n\\subsection{Module}\n\nOutput\n\n\\subsection{Uses}\n\nParam (Section~\\ref{Parameters})\n\n\\subsection{Syntax}\n\n\\subsubsection{Exported Access Program}\n\n\\begin{center}\n\\begin{tabular}{p{3cm} p{7cm} p{2cm} p{2cm}}\n\\hline\n\\textbf{Name} & \\textbf{In} & \\textbf{Out} & \\textbf{Exceptions} \\\\\n\\hline\nwrite\\_output & String, String, $\\mathbb{R}$ & - & - \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\n\\subsection{Semantics}\n\n\\subsubsection{State Variables}\n\nNone\n\n\\subsubsection{Environment Variables}\n\nfile: The file named ``output\".\n\n\\subsubsection{Access Routine Semantics}\n\n\\noindent write\\_output($s$, $d_{\\text{offset}}$):\n\\begin{itemize}\n\\item transition:  Write to environment variable named ``file\" the calculated values $s$ and $d_{\\text{offset}}$.\n\\item exception: none\n\\end{itemize}\n\n\\newpage\n\n\\section{MIS of Specification Parameters} \\label{SpecParam}\n\nThe secrets of this module is the value of the specification parameters.\n\n\\subsection{Module}\n\nSpecParam\n\n\\subsection{Uses}\n\nN/A\n\n\\subsection{Syntax}\n\n\\subsubsection{Exported Constants}\n\n\\renewcommand{\\arraystretch}{1.2}\n\\begin{longtable*}[l]{l} \n\\# From Table 10 in SRS\\\\\n  $g$ := 9.8\\\\\n  $\\epsilon$ := 0.02\\\\\n\\end{longtable*}\n\n\\subsection{Semantics}\n\nN/A\n\n\\newpage\n\n\\bibliographystyle {plainnat}\n\\bibliography {MIS}\n\n\\section{Appendix} \\label{Appendix}\n\n\\renewcommand{\\arraystretch}{1.2}\n\n\\begin{longtable}{l p{12cm}}\n\\toprule\n\\textbf{Message ID} & \\textbf{Error Message} \\\\\n\\midrule\nbadSpeed & InputError: Speed must be positive.\\\\\nbadAngle & InputError: Angle must be between zero and pi over two radians.\\\\\nbadTargetPosition & InputError: Target position must be positive.\\\\\n\\bottomrule\n\\caption{Possible Exceptions} \\\\\n\\end{longtable}\n\n\n\\end{document}\n", "meta": {"hexsha": "ff550c9b2f7fab43ca97f519d1e15baa8e8dd7fd", "size": 14982, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "code/drasil-example/Drasil/Projectile/MIS/Projectile_MIS.tex", "max_stars_repo_name": "Danki567/Drasil", "max_stars_repo_head_hexsha": "d6bd7d0564710ae70b4847301d3d4df3f83fba11", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-06-24T15:39:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-24T16:57:00.000Z", "max_issues_repo_path": "code/drasil-example/Drasil/Projectile/MIS/Projectile_MIS.tex", "max_issues_repo_name": "Danki567/Drasil", "max_issues_repo_head_hexsha": "d6bd7d0564710ae70b4847301d3d4df3f83fba11", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/drasil-example/Drasil/Projectile/MIS/Projectile_MIS.tex", "max_forks_repo_name": "Danki567/Drasil", "max_forks_repo_head_hexsha": "d6bd7d0564710ae70b4847301d3d4df3f83fba11", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.654109589, "max_line_length": 113, "alphanum_fraction": 0.7067814711, "num_tokens": 4691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.3296368374847078}}
{"text": "\\documentclass[11pt,a4paper]{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage[T1]{fontenc}\n\n\\usepackage[margin=2cm]{geometry}\n\\usepackage{hyperref}\n\\usepackage{amssymb,mathtools}\n\\usepackage[extdef]{delimset}\n\\usepackage{physics}\n\\usepackage{verbatim}\n\\usepackage{enumitem}\n\\setlist{itemsep=1pt,topsep=1pt,parsep=1pt,partopsep=1pt}\n\\usepackage{cleveref}\n\n% Number of spacetime dimensions\n\\let\\olddim\\dim\n\\renewcommand{\\dim}[0]{d}\n% Dimensional regularisation parameter\n\\newcommand{\\eps}[0]{\\epsilon}\n% Colour operators\n\\newcommand{\\colorT}[1]{\\mathbf{T}_{#1}}\n% Merged particles in intermediate mappings\n\\newcommand{\\mpd}[1]{\\widehat{#1}}\n\n\\title{Regularisation of real emissions\nwith distributed soft counterterms}\n\\author{Simone Lionetti}\n\\date{\\today}\n\n\n\\begin{document}\n\n\\maketitle\n\n\n\\section{Process $e^+e^- \\to u\\bar{u}d\\bar{d}$}\n\\label{sec:uuxddx}\n\nIn this \\namecref{sec:uuxddx} we consider the process\n$e^+e^- \\to u_1\\bar{u}_2d_3\\bar{d}_4$\nas a double-real correction to $e^+e^- \\to jj+X$,\nand we attempt to construct a subtraction procedure\nwhich features a minimal number of reduced kinematic configurations.\n\nThe elementary unresolved limits that need to be regulated are\n\\begin{equation}\n\\label{eq:ee2uuxddxelem}\n\tC_{12}, \\quad C_{34}, \\quad\n\tC_{134}, \\quad C_{234}, \\quad C_{123}, \\quad C_{124}, \\quad\n\tS_{12}, \\quad S_{34}.\n\\end{equation}\nAt most three of these limits have a common overlap\nand need to be considered simultaneously.\nDue to the lack of a tree-level diagram for $e^+e^- \\to gg$,\nthe limit of two collinear pairs $C_{12}C_{34}$ is regular.\nThe maximal overlaps that we need to consider are therefore\n\\begin{equation}\n\tC_{123}S_{12}C_{12}, \\quad\n\tC_{124}S_{12}C_{12}, \\quad\n\tC_{134}S_{34}C_{34}, \\quad\n\tC_{234}S_{34}C_{34}.\n\\end{equation}\nThese are all of the same type,\nso it will be sufficient to consider the representative $C_{123}S_{12}C_{12}$.\n\nIn order to have a minimal number of kinematic configurations per evaluation,\nall measurement functions and matrix elements within counterterms\nwill be evaluated for collinear reduced kinematics,\nwhere a set of particles have been merged into a single on-shell parent\nwithout violating overall momentum conservation.\nThe momentum mapping that we use to achieve this\nis the rescaling mapping of ref.~\\cite{Somogyi:2006da}.%\n\\footnote{\nA generalisation of the rescaling mapping\nthat applies to massive particles was presented in \\cite{}.\n}\nCounterterms that are associated to soft configurations\nwill be split into multiple contributions\nand distributed among collinear reduced kinematics.\n\nIn the expression for local currents\nwe make extensive use of the momentum fractions $z_{A,B}$\nand the transverse momenta $k_{A,B}$.\nSince these variables which describe unresolved kinematics\nare shared by multiple counterterms,\nwe find it useful to discuss them here.\nGiven the light-like vector $n$ in the direction of $\\vec{p}_{AB}$\n(where $p_{AB} = p_A+p_B$)\nand an arbitrary reference vector $\\bar{n}$,\nmomentum fractions are defined by\n\\begin{equation}\n\tz_{A,B} \\equiv \\frac{\\bar{n}\\cdot p_A}{\\bar{n}\\cdot p_{AB}},\n\\end{equation}\nand transverse momenta are determined via\n\\begin{equation}\n\tk_A^\\mu \\equiv p_A^\\mu\n\t- \\frac{\\bar{n}\\cdot p_A}{\\bar{n}\\cdot n} n^\\mu\n\t- \\frac{n \\cdot p_A}{n\\cdot\\bar{n}} \\bar{n}^\\mu,\n\t\\qquad\n\tk_{A,B}^\\mu \\equiv k_A^\\mu - z_{A,B} k_{AB}^\\mu.\n\\end{equation}\nWe have verified that the regularisation\nof the unresolved limits \\cref{eq:ee2uuxddxelem}\nis not sensitive to the choice of $\\bar{n}$ among the following:\n\\begin{itemize}\n\t\\item an arbitrary, fixed null vector $(1, \\hat{z})$;\n\t\\item the fixed, time-like total momentum $Q$ of the $e^+ e^-$ collision;\n\t\\item a light-like vector in the anti-collinear direction,\n\twhich is different for the collinear sets $\\set{1,2}$ and $\\set{1,2,3}$.\n\\end{itemize}\n\n\n\\subsection{Counterterm $C_{12}$}\n\nWe subtract the limit of a $q\\bar{q}$ pair going collinear using the current\n\\begin{equation}\n\\label{eq:Pqq}\n\tC_{12}^{\\mu\\nu} = \\frac{T_R}{s_{12}} \\brk[s]*{\n\t\t- g^{\\mu\\nu}\n\t\t+ 4 z_{1,2} z_{2,1} \\frac{k_{1,2}^\\mu k_{1,2}^\\nu}{k_{1,2}^2}\n\t},\n\\end{equation}\nwhich is associated to $12$-collinear kinematics.\n\n\n\\subsection{Counterterm $C_{123}$}\n\nThe triple-collinear counterterm for $q'\\bar{q}'q$\nis determined using the current \\cite{Catani:1999ss}\n\\begin{equation}\n\tC_{123} = \\frac{C_F T_R}{2 s_{123}^2} \\brk[s]*{\n\t\t- \\frac{t_{12,3}^2}{s_{12}^2}\n\t\t+ \\frac{s_{123}}{s_{12}} \\brk*{\n\t\t\t\\frac{4 z_{3,12} + (z_{1,23} - z_{2,13})^2}{z_{12,3}}\n\t\t\t+(1 - 2\\eps) z_{12,3}\n\t\t}\n\t\t- (1 - 2\\eps)\n\t},\n\\end{equation}\nwhere\n\\begin{equation}\n\tt_{12,3}\n\t\\equiv 2 \\frac{z_{1,23} s_{23} - z_{2,13} s_{13}}{z_{12,3}}\n\t+ \\frac{z_{1,23} - z_{2,13}}{z_{12,3}} s_{12}.\n\\end{equation}\nClearly in this case we use $123$-collinear kinematics.\n\n\n\\subsection{Counterterm $S_{12}$}\n\nIn order to construct the $q\\bar{q}$ soft counterterm,\nwe start from the form of the current used in \\cite{Somogyi:2005xz} which reads\n\\begin{equation}\n\t\\frac{T_R}{s_{12}^2} \\sum_i \\sum_j\n\t\\frac{s_{1i}s_{2j} + s_{1j}s_{2i} - s_{12}s_{ij}}{s_{(12)i} s_{(12)j}}\n\t\\colorT{i}\\cdot\\colorT{j},\n\\end{equation}\nwhere the sum runs over all coloured partons of the reduced process\nand includes the case $i=j$.\n\nBefore discussing partial fractioning, we observe\nthat the global factor $s_{12}^{-2}$ may cause the counterterm to diverge\nin limits where neither $s_{12i}$ nor $s_{12j}$ go to zero.\nMore concretely, the contribution from the terms with $i=j$ reads\n\\begin{equation}\n\\label{eq:qqsoftieqj}\n\t\\frac{T_R}{s_{12}^2} \\sum_{i}\n\t\\frac{2s_{1i}s_{2i}}{s_{(12)i}^2}\n\t\\colorT{i}^2,\n\\end{equation}\nand \\emph{all} terms are divergent in the triple-collinear limit $12j$\nfor \\emph{any} $j$.\nThus, although from \\cref{eq:qqsoftieqj} one might be tempted\nto assign the $i$-th term to $12i$-collinear kinematics,\nevery term needs to be distributed among all $12j$-collinear kinematics.\nTo this end, we use colour conservation to move all terms off the colour diagonal\n\\begin{equation}\n\t\\sum_{i}\n\t\\frac{2s_{1i}s_{2i}}{s_{(12)i}^2}\n\t\\colorT{i}^2\n\t= - \\sum_i \\sum_{j\\ne i}\n\t\\frac{2s_{1i}s_{2i}}{s_{(12)i}^2}\n\t\\colorT{i}\\cdot\\colorT{j}\n\t= - \\sum_i \\sum_{j\\ne i} \\brk[s]*{\n\t\\frac{s_{1i}s_{2i}}{s_{(12)i}^2}\n\t+ \\frac{s_{1j}s_{2j}}{s_{(12)j}^2}\n\t}\n\t\\colorT{i}\\cdot\\colorT{j}.\n\\end{equation}\nIn this sense, the kinematics that we assign do not follow the divergent structure\nof the invariant poles but rather the colour,\nin a similar way as proposed for geometric subtraction \\cite{Herzog:2018ggi}.\n\nThe complete off-diagonal soft current reads\n\\begin{equation}\n\\label{eq:qqsoftoffdiag}\n\t\\frac{T_R}{s_{12}^2} \\sum_i \\sum_{j \\ne i}\n\t\\brk[s]*{\n\t\t\\frac{s_{1i}s_{2j} + s_{1j}s_{2i} - s_{12}s_{ij}}{s_{(12)i} s_{(12)j}}\n\t\t- \\frac{s_{1i}s_{2i}}{s_{(12)i}^2} - \\frac{s_{1j}s_{2j}}{s_{(12)j}^2}\n\t} \\colorT{i}\\cdot\\colorT{j}.\n\\end{equation}\nAt this stage, we observe that we may replace\nthe invariants $s_{(12)i} = 2p_{12}\\cdot p_i$ and $s_{(12)j} = 2p_{12}\\cdot p_j$\nin the denominator with $s_{12i}$ and $s_{12j}$ at our leisure.\nIndeed, this operation modifies the counterterm by terms which are of higher order\nin the double-soft limit $S_{12}$, and therefore does not spoil the cancellation\nin the counterterm's defining limit.\nUsing the triple invariant $s_{12i}$ seems convenient\nbecause it makes denominators naturally match the ones of the collinear counterterm\n(which cannot be changed because the modification $s_{123}\\to s_{(12)3}$\nis \\emph{not} higher-order in the triple-collinear limit).\nWe thus use\n\\begin{equation}\n\\label{eq:qqsoftoffdiagmod}\n\tS_{12} = \\frac{T_R}{s_{12}^2} \\sum_{j \\ne i}\n\t\\brk[s]*{\n\t\t\\frac{s_{1i}s_{2j} + s_{1j}s_{2i} - s_{12}s_{ij}}{s_{12i} s_{(12)j}}\n\t\t- \\frac{s_{1i}s_{2i}}{s_{12i}^2} - \\frac{s_{1j}s_{2j}}{s_{(12)j}^2}\n\t} \\colorT{i}\\cdot\\colorT{j}.\n\\end{equation}\nWhether the choice of using $s_{(12)j}$ instead of $s_{12j}$\nis important elsewhere in the subtraction was not documented\nand needs investigation.\n\nIt is easy to partial-fraction \\cref{eq:qqsoftoffdiagmod}\ninto collinear kinematics.\nIn the present implementation we use\n\\begin{equation}\n\t1 = \\frac{s_{12i}}{s_{12i} + s_{12j}} + \\frac{s_{12j}}{s_{12i} + s_{12j}},\n\\end{equation}\nfor each term in the dipole sum which leads to\n\\begin{equation}\n\\label{eq:qqsoftoffdiagmodpf}\n\tS_{12}^{(i)} = \\frac{T_R}{s_{12}^2} \\sum_{j \\ne i}\n\t\\frac{s_{12j}}{s_{12i} + s_{12j}}\n\t\\brk[s]*{\n\t\t\\frac{s_{1i}s_{2j} + s_{1j}s_{2i} - s_{12}s_{ij}}{s_{12i} s_{(12)j}}\n\t\t- \\frac{s_{1i}s_{2i}}{s_{12i}^2} - \\frac{s_{1j}s_{2j}}{s_{(12)j}^2}\n\t} \\colorT{i}\\cdot\\colorT{j}.\n\\end{equation}\nPossibly in the future we may want to change the partial fractions\nto be dependent only on angles and not on energies:\nin the case of two collinear pairs with distributed single-soft limits,\nthis has been noted to be essential for disjoint collinear limits to work\nin combination with distributed soft subtraction.\n\n\n\\subsection{Counterterm $C_{123}S_{12}$}\n\nShifting out of the diagonal the sum over colour dipoles for the $q\\bar{q}$ soft limit\nturns out to be extremely practical also to take its $C_{123}$ triple-collinear limit.\nWe start with either \\cref{eq:qqsoftoffdiagmod} or \\cref{eq:qqsoftoffdiagmodpf}\n(the partial fraction makes no difference in the $C_{123}$ limit), and observe that\nfor a given term to contribute one of $i$ or $j$ needs to be equal to $3$,\nand in the collinear limit the ratio of scalar products with another leg\nis equal to a ratio of momentum fractions.\nAfter this replacement, colour conservation can be used and we find\n\\begin{equation}\n\tC_{123}S_{12} = - \\frac{2T_R}{s_{12}^2} \\colorT{3}^2\n\t\\brk[s]*{\n\t\t\\frac{s_{13} z_{2,13} + s_{23} z_{1,23} - s_{12} z_{3,12}}\n\t\t{s_{123} z_{12,3}}\n\t\t- \\frac{s_{13}s_{23}}{s_{123}^2} - \\frac{z_{1,23} z_{2,13}}{z_{12,3}^2}\n\t}.\n\\end{equation}\nNote that, if the contributions on the diagonal have not been reshuffled,\nsome effort is needed to see that the latter two terms are needed.\nWe also note that subtracting this sub-limit from $C_{123}$\nmany terms simplify and we are left with\n\\begin{equation}\n\tC_{123} - C_{123}S_{12} = \\frac{C_F T_R}{s_{123}^2} \\brk[s]*{\n\t\t\\frac{s_{123}}{s_{12}} \\frac{z_{1,23}^2 + z_{2,13}^2}{z_{12,3}} - 1\n\t\t+ \\eps \\brk*{1 + \\frac{s_{123}}{s_{12}} z_{12,3} }\n\t},\n\\end{equation}\nwhich is what is currently implemented in the code (for $\\eps=0$).\nThis hard triple-collinear counterterm is clearly associated\nto $123$-collinear kinematics, and for the simplifications to occur\nthe momentum fractions have to be computed as in $C_{123}$.\n\n\n\\subsection{Counterterm $C_{123}C_{12}$}\n\nThe strong-ordered collinear limit $C_{123}C_{12}$ is the first nested limit\nthat we encounter whose counterterm we implement in an iterated fashion.\nTo this end we follow the steps of \\cite{Somogyi:2006da}.\nStarting from the counterterm $C_{12}$, we take the extra collinear limit\nof the parent gluon $\\mpd{12}$ of the quark-antiquark pair\ngoing collinear to the mapped, different-species quark $\\mpd{3}$.\nThis involves taking the collinear limit of a spin-correlated matrix element,\nwhich gives the splitting function\n\\begin{equation}\n\tC_{\\mpd{12}\\mpd{3}}^{\\alpha\\beta,ss'} = \\frac{C_F}{s_{\\mpd{12}\\mpd{3}}}\n\t\\delta_{ss'} \\brk[s]*{\n\t\t\\frac{z_{\\mpd{12},\\mpd{3}}}{2} d^{\\alpha\\beta}\n\t\t- 2 \\frac{z_{\\mpd{3},\\mpd{12}}}{z_{\\mpd{12},\\mpd{3}}}\n\t\t\\frac{k_{\\mpd{3},\\mpd{12}}^\\alpha k_{\\mpd{3},\\mpd{12}}^\\beta}\n\t\t{k_{\\mpd{3},\\mpd{12}}^2}\n\t}.\n\\end{equation}\nThe sum over physical polarisations is given by the transverse tensor\nwith respect to the light-cone vector in the collinear direction $p$\nand a reference null vector $n$,\n\\begin{equation}\n\td^{\\alpha\\beta}(p, n) \\equiv\n\t-g^{\\alpha\\beta}\n\t+ \\frac{p^\\alpha n^\\beta + p^\\beta n^\\alpha}{p \\cdot n}.\n\\end{equation}\nWe have indicated with a hat the variables which are computed\nafter merging particles 1 and 2.\nPerforming the Lorentz algebra we find\n\\begin{equation}\n\\label{eq:iterC123C12qq}\n\tC_{\\mpd{12}\\mpd{3}}^{\\alpha\\beta,ss'} C_{12,\\alpha\\beta}\n\t= \\frac{C_FT_R}{s_{12}s_{\\mpd{12}\\mpd{3}}} \\delta^{ss'} \\brk[s]3{\n\t\t\\brk3{\n\t\t\t2 \\frac{z_{\\mpd{3},\\mpd{12}}}{z_{\\mpd{12},\\mpd{3}}}+\n\t\t\tz_{\\mpd{12},\\mpd{3}} (1 - \\eps)\n\t\t} - 2 z_{1,2} z_{2,1} \\brk3{\n\t\t\tz_{\\mpd{12},\\mpd{3}} +\n\t\t\t\\frac{z_{\\mpd{3},\\mpd{12}}}{z_{\\mpd{12},\\mpd{3}}}\n\t\t\t\\frac{(2k_{1,2}\\cdot k_{\\mpd{3},\\mpd{12}})^2}\n\t\t\t{k_{1,2}^2 k_{\\mpd{3},\\mpd{12}}^2}\n\t\t}\n\t}.\n\\end{equation}\nThe reduced matrix element is evaluated for momenta that have been obtained\nmerging particles 1, 2 and 3 with a generalised rescaling mapping.\nThis is equivalent to merging 1 and 2 into $\\mpd{12}$\nrecoiling against all other legs,\nand later merging $\\mpd{12}$ with $\\mpd{3}$\nrecoiling against all remaining momenta.\n\n\n\\subsection{Counterterm $S_{12}C_{12}$}\n\nThe limit where the $q\\bar{q}$ pair is both collinear and soft is over-subtracted\nand needs to be added back.\nThe corresponding counter-counterterm $S_{12}C_{12}$\nmay also be constructed iteratively as done in \\cite{Somogyi:2005xz}.\nAfter the $C_{12}$ limit has been taken the reduced, spin-correlated matrix element \nwhich contains the single parent $\\mpd{12}$ in the limit of soft $\\mpd{12}$\nfactorises with the current\n\\begin{equation}\n\tS_{\\mpd{12}}^{\\mu\\nu}\n\t= \\sum_{i, j}\n\t\\frac{\\mpd{p}_i^\\mu \\mpd{p}_j^\\nu + \\mpd{p}_i^\\nu \\mpd{p}_j^\\mu}\n\t{s_{\\mpd{12}\\mpd{i}} s_{\\mpd{12}\\mpd{j}}}\n\t2\\colorT{i}\\cdot\\colorT{j}.\n\\end{equation}\n\nSince this current multiplies the splitting function for the 12-collinear limit\nwhich features a factor $s_{12}^{-1}$,\nthe counterterm is divergent in all triple-collinear configurations\nand not just in the $12i$- or $12j$-collinear limits.\nSimilarly to the case of $S_{12}$, it is thus convenient\nto shift away the elements on the colour diagonal using colour conservation,\nwhich gives\n\\begin{equation}\n\tS_{\\mpd{12}}^{\\mu\\nu}\n\t= \\sum_{i \\ne j} \\brk[s]*{\n\t\t\\frac{\\mpd{p}_i^\\mu \\mpd{p}_j^\\nu + \\mpd{p}_i^\\nu \\mpd{p}_j^\\mu}\n\t\t{s_{\\mpd{12}\\mpd{i}} s_{\\mpd{12}\\mpd{j}}}\n\t\t- \\frac{\\mpd{p}_i^\\mu \\mpd{p}_i^\\nu}{s_{\\mpd{12}\\mpd{i}}^2}\n\t\t- \\frac{\\mpd{p}_j^\\mu \\mpd{p}_j^\\nu}{s_{\\mpd{12}\\mpd{j}}^2}\n\t} 2 \\colorT{i}\\cdot\\colorT{j}.\n\\end{equation}\nContracting this expression with \\cref{eq:Pqq},\nwith the assumption that $\\mpd{p}_i$ and $\\mpd{p}_j$\nbe massless, we find\n\\begin{multline}\n\\label{eq:S12C12iter}\n\tS_{12}^{\\mu\\nu} C_{12,\\mu\\nu}\n\t= \\frac{T_R}{s_{12}} \\sum_{i \\ne j} \\bigg[\n\t\t- \\frac{s_{\\mpd{i}\\mpd{j}}}{s_{\\mpd{12}\\mpd{i}}s_{\\mpd{12}\\mpd{j}}}\n\t\t+ 2 z_{1,2} z_{2,1}\n\t\t\\frac{(2k_{1,2}\\cdot\\mpd{p}_i)(2k_{1,2}\\cdot\\mpd{p}_j)}\n\t\t{s_{\\mpd{12}\\mpd{i}} s_{\\mpd{12}\\mpd{j}} k_{1,2}^2}\n\t\t\\\\\\times\n\t\t\\brk3{ 1\n\t\t- \\frac{1}{2} \\frac{s_{\\mpd{12}\\mpd{j}}}{s_{\\mpd{12}\\mpd{i}}}\n\t\t\\frac{2k_{1,2}\\cdot\\mpd{p}_i}{2k_{1,2}\\cdot\\mpd{p}_j}\n\t\t- \\frac{1}{2} \\frac{s_{\\mpd{12}\\mpd{i}}}{s_{\\mpd{12}\\mpd{j}}}\n\t\t\\frac{2k_{1,2}\\cdot\\mpd{p}_j}{2k_{1,2}\\cdot\\mpd{p}_i}\n\t\t}\n\t\\bigg] \\colorT{i}\\cdot\\colorT{j}.\n\\end{multline}\n\nAt this stage, the $S_{12}C_{12}$ counterterm may be partial-fractioned\ninto triple-collinear sectors following the colour structure.\nWe choose to perform this operation \\emph{after} the limit $C_{12}$\nhas been taken, as if we were dealing with a single-soft gluon $\\mpd{12}$.%\n\\footnote{\nThis choice might match better the structure of iterated limits,\nsuch that $S_{12}C_{12}$ regulates the $C_{12}$ integrated counterterm\nin the $S_{\\mpd{12}}$ single-unresolved limit\nwithin the single-unresolved phase space.\nHowever the specific form of partial fraction employed\nmay have interplay with other subtraction elements\nand deserves further investigation.\n}\nWe thus use the current\n\\begin{equation}\n\tS_{12}^{(i),\\mu\\nu} C_{12,\\mu\\nu}\n\t= \\frac{s_{\\mpd{12}\\mpd{j}}}{s_{\\mpd{12}\\mpd{i}}+s_{\\mpd{12}\\mpd{j}}}\n\tS_{12}^{\\mu\\nu} C_{12,\\mu\\nu},\n\\end{equation}\nwithin $12i$ triple-collinear kinematics.\n\n\n\\subsection{Counterterm $S_{12}C_{123}C_{12}$}\n\nThe last piece that is missing for the three limits\n$S_{12}$, $C_{123}$ and $C_{12}$ to be regulated is the triple overlap,\nwhich has been subtracted three times in the simple counterterms\nand added back three times in the double overlaps,\nso that it still needs to be subtracted from the original integrand.\nThe singular current, which is constructed to match \\cite{Somogyi:2006da},\ncan be obtained from \\cref{eq:iterC123C12qq} dropping terms\nwhich do not have a $z_{\\mpd{12},\\mpd{3}}$ denominator%\n\\footnote{\nIn performing this step we somewhat arbitrarily decide\nto keep the $z_{\\mpd{3},\\mpd{12}}$ terms at the numerator\nwhich theoretically could or should be set to one.\nVery roughly speaking this is equivalent to taking\nthe $C_{\\mpd{12}\\mpd{3}}$ limit of the soft counterterm for $S_{\\mpd{12}}$,\nas it is sometimes useful to do for single-unresolved\nnested soft-collinear limits.\n}\n\\begin{equation}\n\tS_{\\mpd{12}} C_{\\mpd{12}\\mpd{3}} C_{12}\n\t= \\frac{2 C_F T_R}{s_{12}s_{\\mpd{12}\\mpd{3}}}\n\t\\frac{z_{\\mpd{3},\\mpd{12}}}{z_{\\mpd{12},\\mpd{3}}}\n\t\\brk[s]3{\n\t\t1 - z_{1,2} z_{2,1}\n\t\t\\frac{(2k_{1,2}\\cdot k_{\\mpd{3},\\mpd{12}})^2}\n\t\t{k_{1,2}^2 k_{\\mpd{3},\\mpd{12}}^2}\n\t}.\n\\end{equation}\nThis counterterm is associated to $123$-collinear kinematics.\n\n\n\\subsection{Spurious limits and division by jacobian}\n\nWithin each counterterm we let the limit operation\nact on the phase space volume,\ni.e.\\ we divide each counterterm by the jacobian $\\mathcal{J}$\ndefined by\n\\begin{equation}\n\\label{eq:jaccanonical}\n\t\\dd{\\Phi} = \\mathcal{J}\\times \\dd{\\tilde{\\Phi}}\n\t\\prod_{C} \\frac{\\dd{s_C}}{2\\pi} \\dd{\\Phi_C},\n\\end{equation}\nwhere $\\Phi$ is the full phase space,\n$\\tilde{\\Phi}$ the reduced one,\nand $C$ each merged set of particles.\n\nThis, however, is not sufficient to achieve\nthe desired cancellation pattern.\nIndeed, when the counterterm built from the current \\labelcref{eq:S12C12iter}\nis included with $12k$ collinear kinematics for some $k$,\nwhich clearly reduce to no momentum mapping for soft $p_{12}$,\nit does \\emph{not} automatically match\nthe counterterm $C_{12}$ from \\cref{eq:Pqq} in the $S_{12}$ limit.\nThis is due to our choice of dividing by the jacobian factor\nof \\cref{eq:jaccanonical} which, in the $S_{12}$ limit,\nis different between the mappings that merge\nthe sets $\\set{1,2}$ and $\\set{1,2,3}$.\nTo fix this mismatch we have two options.\nThe first one, which essentially follows \\cite{Somogyi:2006da},\nis to forfeit \\cref{eq:jaccanonical} and divide by jacobians\nwhich are defined by the alternative\ncanonical factorisation of phase space\n\\begin{equation}\n\t\\dd{\\Phi} = \\mathcal{J}\\times \\dd{\\tilde{\\Phi}}\n\t\\prod_{C} \\frac{\\dd{\\alpha_C}}{2\\pi} \\dd{\\Phi_C},\n\\end{equation}\nwhere $\\alpha_C$ are the parameters of the rescaling mapping\ndefined in \\cite{Somogyi:2006da}.\nGiven that $\\alpha_C$ is essentially the light-cone component\nof the momentum of the collinear set in the anti-collinear direction,\ni.e.\\ its `minus' component,\nthis choice amounts to parametrise the virtuality variables\nwith the anti-collinear components of the collinear momenta.\nThe second possibility is to reabsorb the mismatch factor\ninto the definition of the counterterm, replacing for instance\n\\begin{equation}\n\tS_{12}^{(i),\\mu\\nu} C_{12,\\mu\\nu}\n\t\\to \\frac{Q\\cdot p_{12}}{Q\\cdot p_{\\mpd{12}}}\n\tS_{12}^{(i),\\mu\\nu} C_{12,\\mu\\nu}.\n\\end{equation}\nNote that the factor is only defined up to terms\nwhich are higher-order in the $S_{12}$ limit,\nwith the constraint that it goes to 1\nin the $C_{12}$ and $C_{123}$ limits.\nAt the moment it does not seem clear which option\nis the most convenient, but it is relatively easy\nto switch between the two.%\n\\footnote{\nWithin \\texttt{MadNkLO}, the first option can be chosen\nby selecting \\texttt{alpha\\_jacobian} as \\texttt{factor}\nfor the currents, either individually\nor globally in \\texttt{QCD\\_local\\_currents.py}\n(beware that this might affect other schemes).\nThe mismatch factor is instead implemented\nwithin the \\texttt{ee2qqgg-NNLO-IR-limits} branch\nin the \\texttt{cataniseymour} NNLO local current\n\\texttt{QCD\\_final\\_collinear\\_0\\_QQxq},\nand more precisely in the method \\texttt{S12C12\\_kernel}\nwith the variable \\texttt{fix}.\n}\n\n\\begin{comment}\nA potential drawback of this choice is that\nit makes the subtraction of disjoint collinear limits more complicated.\nIn fact, within the formula\n\\begin{equation}\n\t1\n\t- C_{12} - C_{34}\n\t+ C_{\\mpd{3}\\mpd{4}} C_{12} + C_{\\mpd{1}\\mpd{2}} C_{34}\n\t- C_{12;34},\n\\end{equation}\nthe last three terms, which all feature the same kinematics\nthanks to the commutativity property of the rescaling mapping,\nnow differ \\emph{only} because of jacobian factors.\t\n\\end{comment}\n\n\n\\begin{thebibliography}{9}\n\n%\\cite{Catani:1999ss}\n\\bibitem{Catani:1999ss} \n  S.~Catani and M.~Grazzini,\n  %``Infrared factorization of tree level QCD amplitudes at the next-to-next-to-leading order and beyond,''\n  Nucl.\\ Phys.\\ B {\\bf 570}, 287 (2000)\n  doi:10.1016/S0550-3213(99)00778-6\n  [hep-ph/9908523].\n  %%CITATION = doi:10.1016/S0550-3213(99)00778-6;%%\n  %227 citations counted in INSPIRE as of 04 Apr 2019\n\n%\\cite{Somogyi:2005xz}\n\\bibitem{Somogyi:2005xz} \n  G.~Somogyi, Z.~Trocsanyi and V.~Del Duca,\n  %``Matching of singly- and doubly-unresolved limits of tree-level QCD squared matrix elements,''\n  JHEP {\\bf 0506}, 024 (2005)\n  doi:10.1088/1126-6708/2005/06/024\n  [hep-ph/0502226].\n  %%CITATION = doi:10.1088/1126-6708/2005/06/024;%%\n  %111 citations counted in INSPIRE as of 04 Apr 2019\n\n%\\cite{Somogyi:2006da}\n\\bibitem{Somogyi:2006da} \n  G.~Somogyi, Z.~Trocsanyi and V.~Del Duca,\n  %``A Subtraction scheme for computing QCD jet cross sections at NNLO: Regularization of doubly-real emissions,''\n  JHEP {\\bf 0701}, 070 (2007)\n  doi:10.1088/1126-6708/2007/01/070\n  [hep-ph/0609042].\n  %%CITATION = doi:10.1088/1126-6708/2007/01/070;%%\n  %115 citations counted in INSPIRE as of 04 Apr 2019\n  \n\\bibitem{Herzog:2018ggi}\n\tF.~Herzog,\n\tGeometric subtraction for real radiation at NNLO,\n\t\\url{https://www.ggi.infn.it/talkfiles/slides/slides4304.pdf}\n \n\\end{thebibliography}\n\n\\end{document}\n", "meta": {"hexsha": "bbc9d1e8594acface8738effda41ae21359daf81", "size": 21729, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Documentation/SubtractionWithDistributedSofts/SubtractionWithDistributedSofts_MadNkLO.tex", "max_stars_repo_name": "madnklo/madnklo", "max_stars_repo_head_hexsha": "646a3db9c8efd7b4cb00e9d89b9197cd5394c01b", "max_stars_repo_licenses": ["NCSA"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-14T15:25:38.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-14T15:25:38.000Z", "max_issues_repo_path": "Documentation/SubtractionWithDistributedSofts/SubtractionWithDistributedSofts_MadNkLO.tex", "max_issues_repo_name": "madnklo/madnklo", "max_issues_repo_head_hexsha": "646a3db9c8efd7b4cb00e9d89b9197cd5394c01b", "max_issues_repo_licenses": ["NCSA"], "max_issues_count": 26, "max_issues_repo_issues_event_min_datetime": "2018-10-08T15:49:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-15T13:33:36.000Z", "max_forks_repo_path": "Documentation/SubtractionWithDistributedSofts/SubtractionWithDistributedSofts_MadNkLO.tex", "max_forks_repo_name": "madnklo/madnklo", "max_forks_repo_head_hexsha": "646a3db9c8efd7b4cb00e9d89b9197cd5394c01b", "max_forks_repo_licenses": ["NCSA"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-03-25T17:28:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-21T12:15:53.000Z", "avg_line_length": 38.1210526316, "max_line_length": 114, "alphanum_fraction": 0.7102029546, "num_tokens": 7825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.3296241094304886}}
{"text": "%In this section, we first define the problem we address and  then the mathematical notation we use.  \n\n%In this section, we will define our addressing problem with the notation. Also, the background about this paper will be provided.\n\n\n%\\subsection{Background}\n\n%Standard unsupervised algorithms like $k$-means~\\cite{kmeans_original} (and variants) that are commonly used for search results clustering define clusters according to a prototype document centroid in a vector space model, where all search results would be assigned to their closest cluster centroid.  While this approach naturally provides for topical (content) coherence of search results within a cluster, it does not directly guarantee high relevance of clusters.  It also does not directly guarantee coherence of display attributes of clusters such as the spatial and temporal extent of the cluster (i.e., a cluster may have documents spanning a large spatial or temporal range), unless these attributes are incorporated into the distance metric for the vector space model and appropriately traded off with content distance. \n\n\\subsection{Problem definition}\n\nIn this paper, we take a novel perspective on the definition of a cluster and the optimization process for extracting these clusters. To start, we assume the search results have the following three display attributes that can be used to define coherent clusters in terms of spatial, temporal, and topical (i.e., content) constraints:\n%of an AUI to ease the task of monitoring alerts in large-scale displayed networks. The new interface is expected to filter irrelevant information to provide localized context for each event or alert (defined loosely as a relevant related content localized in time, space, and/or keyword usage). \\textcolor{red}{Hence, we argue that the problem we are addressing in this paper is an optimization problem of filter selection.  Furthermore, we assume that selection of information elements to display in a visual interface is obtained via settings of three filters that jointly express a global filter. These three sub-filters are:}\n%%\n%The problem we address in this paper is the proper display of portion in the network for user's easy to investigate large-scale network elements. The new system is expected to filter information to provide localized and relevant element in the interface. This problem is able to be defined as a filter search/recommendation problem, We expect to employ standard IR theory to solve this problem based on our argument about the similarity of AUI and IR system. We assume that display of the elements in the network is obtained via three filters that can jointly express a global filter. These three sub-filters are:\n\\begin{itemize}[topsep=2pt,leftmargin=*]\n\\item {\\bf Space:} limits cluster content to 2D spatially annotated content (e.g., latitude and longitude) according to four parameters for the upper left and lower right bounding box coordinates.  These cluster constraints define the bounding box that is visually displayed to the user, cf. Figure~\\ref{Fig:BPS_FilteredDisplay}.\n\\item {\\bf Time:} limits cluster content to time-stamped results according to two parameters for the lower and upper time bound.  Time can be displayed via cluster labels, and/or through settings of a time slider in the interface.\n%expresses a bounding box of a retrieved set. The location can be expressed as longitude/latitude values, or pure coordinates obtained using a given display layout. \n\\item {\\bf Keyword (or Discrete Attribute):} limits cluster content according to included or excluded keywords (or general discrete attributes of an information element).\nExplicit included and excluded keywords can be used to label the cluster. \n\\end{itemize}\nGiven a query and a probabilistic measure of relevance for each search result w.r.t.\\ this query (e.g., from a language model~\\cite{Zhai2001}), %the problem we address in this paper is how to efficiently optimize content filtering in a visual information display (VID) for\nthe problem we study is how to efficiently extract high-relevance clusters defined according to the above constraints.\n\n%In general, we remark that the choice of which clustering parameters to use is up to the interactive search interface designer according to the display and (meta-)data available.  \nWe note that this clustering work is not limited to these three display attributes -- any continuous or discrete cluster attributes that naturally constrain the search results can be accommodated by our framework.  Nonetheless, we believe time, space, and content constitute three of the most common information display attributes in practice and hence are the ones we focus on in this work.\n%one or multiple filter selection settings to maximize retrieval of relevant content?  \n%\\textcolor{red}{Even though in practice, not all data have such information associated, we can imagine throw away the sub-filters associated with the missing information, e.g., location information which is certainly not available in all datasets.} \n%best set of elements that is assessed using one of the metrics described above, i.e., expected precision, expected recall, or expected F1-score\n\n\\subsection{Mathematical Notation}\n\nWith the cluster definitions above, we now define  formal mathematical notation used throughout the remainder of the paper:\n%portion of our presentation using  \n%Throughout this paper, we present all algorithms for Greedy and Optimal search using \n%the following mathematical notation:\n\n\\begin{itemize}[topsep=2pt,leftmargin=*]\n\\item An information element $j$ (i.e., a search result) may have three types of associated metadata: (i) position coordinates $(x_{j},y_{j})$, (ii) a timestamp $t_j$, which may represent the creation date of $j$, and (iii) textual content, which is composed of a set of unique terms $\\{ t_1,\\ldots,t_n \\}$ of size $n$ (to reduce notational clutter, we assume the element $j$ containing these terms will be clear from context).\n\n\\item Three variables $I(j) \\in \\{0,1\\}$, $B(j) \\in \\{0,1\\}$ and $S(j) \\in [0,1]$ are associated with each information element $j$: $I(j)$ is an indicator referring to whether an element $j$ is retrieved and displayed ($\\textrm{true}\\!=\\!1$); $B(j)$ is a Boolean random variable indicating the (ground truth) relevance of an element $j$ ($\\textrm{relevant}\\!=\\!1$); $S(j)$ is a relevance score indicating the \\emph{probability} relevance of an element $j$. %Note that $I(j)$ is correlated with the UI system. $B(j)$ and $S(j)$ are independent of the system. \n%$\\emph{I(j), B(j)} \\in \\{0, 1\\}$, $\\emph{S(j)} \\in \\left[0, 1\\right]$. \n$B(j)$ follows a \\emph{Bernoulli} distribution with parameter $S(j)$, and hence, the expectation of $B(j)$ \\emph{is} $S(j)$, i.e., \n  $\\mathbb{E}[B(j)] = S(j)$.\n%which allows to derive the expectation of \\emph{B(j)} as follows:\n%\\begin{equation}\n % \\mathbb{E_S}[B(j)] = 0*(1 - S(i))+ 1*S(i) = S(i)\n%\\end{equation}\n\\item We label $GC$ as the global set of all information elements $j$ with total size $|GC|=m$. %Two subsets of $GC$ are particularly important in this research: retrieved set $E$ and relevant set $RS$.  \n\\item $E$ is the set of retrieved information elements that match a user query, where $E \\subseteq  GC$.  We use $E^*$ to refer to further subsets of elements of clusters, i.e., $E^*\\subseteq E$. \n%This variable depends on the UI filtering system. \nNote that $|E|$ is the count of retrieved $I(j)$ among the global collection $GC$. Therefore, we have $|E| = \\sum_{j=1}^m I(j)$.\n\\item We label the set of ground truth relevant information elements as the relevant set $RS$ consisting of $|RS|$ elements. \n%This is independent of the UI-filter system. \nNote that $|RS|$ is the count of relevant $B(j)$ among the global collection $GC$. Therefore, we have $|RS| = \\sum_{j=1}^m B(j)$. %However, $B(j)$ is not available for our estimation of $RS$ size in practice. We have to use expected $RS$ size $|RS|$, $\\mathbb{E_S}|RS|$, to approximate $|RS|$.\n%\\begin{equation}\n  %|RS| \\approx \\mathbb{E_S}|RS| = \\sum_{j=1}^m \\mathbb{E_S}[B(j)] = \\sum_{j=1}^m S(j)\n%\\end{equation}\n\n%\\item Keyword parameters $Q_k=\\{\\neg t_{1}^{*},\\dots \\neg t_{k}^{*}\\}$, are composed of a set of query terms excluded from the cluster, i.e., elements in the cluster cannot contain the terms $t_{1}^{*},\\dots t_{k}^{*}$.\n%\\item Time parameters $Q_t=[t_{start},t_{end}]$ express the lower bound $t_{start}$ and upper bound $t_{end}$ time parameters of the cluster.\n%\\item Position parameters $Q_p=[(x_{min},y_{min}),(x_{max},y_{max})]$ express the upper left $(x_{min},y_{min})$ and lower right $(x_{max},y_{max})$ corners of the spatial parameters of a cluster.%, assuming $(0,0)$ is in the upper left corner of the display window.  \n%search of elements falling in the bounding box represented by the  lower and upper bound coordinates -- respectively $(x_{min},y_{min})$ and $(x_{max},y_{max})$.\n%\\item A cluster $Q$ combines the three selection parameters $Q_k$, $Q_t$, and $Q_p$ in a conjoined set of parameters $Q=[Q_k, Q_t, Q_p]$. \n%$Q=[Q_k\\wedge Q_t\\wedge Q_p]$. \n\n\\end{itemize}\n\n\n\n\n\n\n\n%The goal is to explore an algorithm to obtain an optimal filter setting to retrieve a set of elements with maximum score of the specific metric.\n\n\n\n%\\subsection{Comparison to standard IR search}\n%The comparison between information retrieval for web search and information retrieval for filtering in AUIs can be summarized in Table \\ref{tbl:Comparaison2IR}. Obviously , there are important differences between web search and filtering for AUIs, especially in the indirect selection of results through filter settings. This unexplored field provides new possibilities and challenges of research in this novel information retrieval setting:\n%\\begin{itemize}\n%\\item Evaluation metrics and human factors: Are there new evaluation metrics specific to this AUI filtering setting? What evaluation metrics correlate with AUI user performance? \n%\\item Optimization and algorithms: How do we optimally select filter settings to maximize evaluation metrics in expectation? How can we interpret simple heuristics like average and cumulative relevance? (Answer: expected precision.) How do MILPs, relaxed LP approximations with guarantees, or greedy approaches compare in terms of time and metric quality? Are there properties of different filters (1D for time, 2D for bounding box, or discrete choices for property selection) that lend themselves to specialized greedy approaches? \n%\\item Robustness: As the signal-to-noise ratio varied in the quality of the relevance scoring, how do various algorithms perform? \n%\\item Explanation: Can we provide explanations for filter settings to allow users to understand the reasons for the suggestions? \n%\\item Personalization and learning: Can we learn from observations of manual adaption of the suggested filter settings to understand how to improve the third-party scoring systems? \n%\\item Collaborative filtering: Can we generalize learning across multiple\n%users in a collaborative filtering approach? \n%\\item Learning from implicit feedback: How can we leverage implicit user\n%feedback such as clicks and dwell time to indirectly measure the relevance\n%of filtered content and improve system performance.\n%\\end{itemize}\n\n%\\subsection{Optimization technique definition}\n\n%The \\emph{greedy algorithm} is an algorithmic paradigm that aims to obtain a global optimum of a problem in terms of making the locally optimal decision at each step \\cite{Black2005}. In a search problem, a greedy algorithm does not in general produce an optimal solution, but it still yields locally optimal solutions that approximate a global optimum in a reasonable time.\n\n%The greedy algorithms described in this paper are coupled with a \\emph{Top-down} search strategy, which basically begins with the whole search space, and then partition into several sub-spaces in a lower level for the local optimization search heuristic.\n\n%An \\emph{optimization-based} search is the problem of finding the best solution from all feasible solutions. Usually, the standard form of an optimization problem is defined as the minimization/maximization of a given objective function subject to a set of constraints. \n\n%The search problem will be transformed into Mixed integer linear programming (MILP), which involves problems in which only some of the variables, $x_{i}$, are constrained to be integers, while other variables are allowed to be non-integers.\n\n\n\n%\\subsection{Evaluation metrics}\n\n\n\n\n", "meta": {"hexsha": "4db80e78560d6fecb46670646d4c2ffa3cbfb6e1", "size": 12490, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Documents/UMAP2019/Framework.tex", "max_stars_repo_name": "D3Mlab/visir", "max_stars_repo_head_hexsha": "cd1860984dee8d7aba368857e734ad11c14124c8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-10T07:40:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-10T07:40:04.000Z", "max_issues_repo_path": "Documents/UMAP2019/Framework.tex", "max_issues_repo_name": "D3Mlab/viz-ir", "max_issues_repo_head_hexsha": "cd1860984dee8d7aba368857e734ad11c14124c8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Documents/UMAP2019/Framework.tex", "max_forks_repo_name": "D3Mlab/viz-ir", "max_forks_repo_head_hexsha": "cd1860984dee8d7aba368857e734ad11c14124c8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 111.5178571429, "max_line_length": 831, "alphanum_fraction": 0.7737389912, "num_tokens": 2855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.32958408118057647}}
{"text": "% !TEX TS-program = xelatex\n% !TEX encoding = UTF-8 Unicode\n\\documentclass[11pt,a4paper]{article}\n\\usepackage{amsmath,amssymb}\n\\usepackage{empheq}\n\\usepackage[semibold]{ebgaramond}\n\\usepackage[cmintegrals,cmbraces]{newtxmath}\n\\usepackage{ebgaramond-maths}\n\\usepackage{bm}\n\\usepackage[OMLmathrm, OMLmathsfit, rmdefault=mdugm]{isomath}\n\\usepackage{tocbibind}\n\\usepackage{graphicx}\n\\graphicspath{{./pics/}}\n\\usepackage{wrapfig}\n\n\\makeatletter\n  \\DeclareSymbolFont{ntxletters}{OML}{ntxmi}{m}{it}\n  \\SetSymbolFont{ntxletters}{bold}{OML}{ntxmi}{b}{it}\n  \\re@DeclareMathSymbol{\\leftharpoonup}{\\mathrel}{ntxletters}{\"28}\n  \\re@DeclareMathSymbol{\\leftharpoondown}{\\mathrel}{ntxletters}{\"29}\n  \\re@DeclareMathSymbol{\\rightharpoonup}{\\mathrel}{ntxletters}{\"2A}\n  \\re@DeclareMathSymbol{\\rightharpoondown}{\\mathrel}{ntxletters}{\"2B}\n  \\re@DeclareMathSymbol{\\triangleleft}{\\mathbin}{ntxletters}{\"2F}\n  \\re@DeclareMathSymbol{\\triangleright}{\\mathbin}{ntxletters}{\"2E}\n  \\re@DeclareMathSymbol{\\partial}{\\mathord}{ntxletters}{\"40}\n  \\re@DeclareMathSymbol{\\flat}{\\mathord}{ntxletters}{\"5B}\n  \\re@DeclareMathSymbol{\\natural}{\\mathord}{ntxletters}{\"5C}\n  \\re@DeclareMathSymbol{\\star}{\\mathbin}{ntxletters}{\"3F}\n  \\re@DeclareMathSymbol{\\smile}{\\mathrel}{ntxletters}{\"5E}\n  \\re@DeclareMathSymbol{\\frown}{\\mathrel}{ntxletters}{\"5F}\n  \\re@DeclareMathSymbol{\\sharp}{\\mathord}{ntxletters}{\"5D}\n  \\re@DeclareMathAccent{\\vec}{\\mathord}{ntxletters}{\"7E}\n\\makeatother\n\n\\usepackage{array}\n\\usepackage{enumitem}\n% to produce a comma between multiple footnotes / https://tex.stackexchange.com/questions/40072/incompatibility-between-footmisc-option-multiple-and-hyperref/62091#62091\n\\let\\oldFootnote\\footnote\n\\newcommand\\nextToken\\relax\n\\renewcommand\\footnote[1]{%\n    \\oldFootnote{#1}\\futurelet\\nextToken\\isFootnote}\n\\newcommand\\isFootnote{%\n    \\ifx\\footnote\\nextToken\\textsuperscript{,}\\fi}\n\n\\defaultfontfeatures{Ligatures=TeX} % makes this a feature for all selected fonts\n\\usepackage{esint}\n\\usepackage{polyglossia}\n\\setmainlanguage{english}\n\\usepackage[text={18cm,26cm},centering]{geometry} % \n\\usepackage{natbib}\n\\usepackage{mdframed}\n\\usepackage{lipsum}\n\\usepackage[usenames,dvipsnames,svgnames,table]{xcolor}\n\\usepackage{hyperref}\n\\usepackage{url}\n\\usepackage[export]{adjustbox}\n\n\\hypersetup{\n  colorlinks,\n  citecolor=bleuSU,\n  linkcolor=bleuSU\n}\n\\definecolor{bleuSU}{RGB}{26,39,101}\n\n\\usepackage[normalem]{ulem}\n\\makeatletter\n\\renewcommand*{\\uuline}{%\n  \\bgroup\n  \\UL@setULdepth\n  \\markoverwith{%\n    \\lower\\ULdepth\\hbox{%\n      \\kern-.03em%\n      \\vtop{%\n        \\hrule width.2em%\n        \\kern 0.6pt % distance between the two underlines\n        \\hrule\n      }%\n      \\kern-.03em%\n    }%\n  }%\n  \\ULon\n}\n\\makeatother\n\\setlength{\\ULdepth}{-2pt}  % distance from double underline to letter\n\n\\usepackage{environ}\n\\newtoggle{corrige}\n\n\\NewEnviron{answer}{%\n  \\iftoggle{corrige}\n    {\\begin{mdframed}\\textbf{Answer: } \\BODY\\end{mdframed}}\n    {}%\n  }\n\n\\newcommand{\\delS}{\\delta S}\n\\newcommand{\\delA}{\\delta A}\n\\newcommand{\\delh}{\\delta h}\n\\newcommand{\\delt}{\\delta t}\n\\newcommand{\\delz}{\\delta z}\n\\newcommand{\\delbx}{\\delta \\matrixsym x}\n\\newcommand{\\lp}{\\left(}\n\\newcommand{\\rp}{\\right)}\n\\newcommand{\\itA}{\\textit A}\n\\newcommand{\\itB}{\\textit B}\n\\newcommand{\\dAB}{\\mathcal D_{AB}}\n\\newcommand{\\bA}{\\matrixsym A}\n\\newcommand{\\bff}{\\matrixsym{f}}\n\\newcommand{\\bF}{\\matrixsym{F}}\n\\newcommand{\\bj}{\\matrixsym{j}}\n\\newcommand{\\bJ}{\\matrixsym J}\n\\newcommand{\\bn}{\\matrixsym{n}}\n\\newcommand{\\bN}{\\matrixsym N}\n\\newcommand{\\bP}{\\matrixsym{P}}\n\\newcommand{\\br}{\\matrixsym r}\n\\newcommand{\\bt}{\\matrixsym t}\n\\newcommand{\\be}{\\matrixsym e}\n\\newcommand{\\bu}{\\matrixsym u}\n\\newcommand{\\bv}{\\matrixsym v}\n\\newcommand{\\bw}{\\matrixsym w}\n\\newcommand{\\bx}{\\matrixsym x}\n\\newcommand{\\pd}[2]{\\frac{\\partial #1}{\\partial #2}}\n\\newcommand{\\D}[2]{\\frac{D #1}{D #2}}\n\\newcommand{\\dd}[2]{\\frac{\\mathrm d #1}{\\mathrm d #2}}\n\\newcommand{\\dA}{\\mathrm dA}\n\\newcommand{\\dV}{\\mathrm dV}\n\\newcommand{\\dS}{\\mathrm dS}\n\\newcommand{\\prg}[1]{\\paragraph{$\\rhd$ #1}}\n\\newcommand{\\alphaijkl}{\\alpha_{ijkl}}\n\\newcommand{\\Aijkl}{A_{ijkl}}\n\\newcommand{\\delij}{\\delta_{ij}}\n\\newcommand{\\sigij}{\\sigma_{ij}}\n\\newcommand{\\sigji}{\\sigma_{ji}}\n\\newcommand{\\sigxy}{\\sigma_{xy}}\n\\newcommand{\\matL}{\\mathcal L}\n\\newcommand{\\matO}{\\mathcal O}\n\\newcommand{\\matS}{\\mathcal S}\n\\newcommand{\\kij}{k_{ij}}\n\\newcommand{\\tensor}[1]{\\smash{\\uuline{#1}{}}}\n\\setlength{\\parindent}{0pt} % remove indent\n\n\\setlist[enumerate]{topsep=0pt,itemsep=-1ex,partopsep=1ex,parsep=1ex}\n\n\\begin{document}\n\\setlength{\\unitlength}{1cm}\n\\noindent\n\\parbox{\\textwidth}{\n\\textsc{\nSorbonne Université  \n\\hfill\nYear 2021-2022\n}\n}\n\\parbox{\\textwidth}{\n\\textsc{\nFaculté des Sciences\n\\hfill\nPhysics of Fluids \\& Nonlinear Physics\n}\n}\n\n\\begin{center}\n\\Large\n\\textbf{Hydrodynamics} \\\\ \n\\textsl{Tutorial 2: boundary conditions, capillarity \\& adhesion} \\\\[1ex]\n\\end{center}\n\n\\section{Impermeable obstacles}\n\\togglefalse{corrige}\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[height=3cm,valign=m]{splash.jpg}\n    \\hspace{1cm}\n    \\includegraphics[height=3cm,valign=m]{flow_over_weir.jpg}\n    \\caption[Caption for LOF]{\\textbf{Liquid deflection.} Left: an hydrophobic bead impacts a water pool at $\\simeq 5$ m$\\cdot$s$^{-1}$ and produces a splash (liquid corolla) on impact \\citep{Eggers2007}. Right: a flow over an obstacle in a wave tank givers rise to the \\textit{hydraulic jump} phenomenon (Science Education Resource Center at Carleton College\\setcounter{footnote}{0}\\footnotemark).}\n    \\label{fig:obstacle}\n\\end{figure}\n\\footnotetext{\\url{https://serc.carleton.edu/NAGTWorkshops/geomoph/emriver/index.html}}\n\\prg{Impact.}\nA spherical obstacle of radius $R$ impacts a liquid tank at velocity $-U_\\text{impact} \\be_{z}$. On impact the fluid is violently set into motion by the object.\n\\begin{enumerate}\n\\item Supposing that the object preserves its velocity during impact, determine the position $C$ of the sphere centre through time. Consider that at initial time $t=0$, $C$ is located at $(x,y,z)=(0,0,0)$. Deduce the equation of the sphere surface for all time in the laboratory (i.e. fixed) frame.\n\\item Obtain the expression for the normal vector $\\bn$ at each point of the sphere in cartesian ccoordinates.\n\\item Noting the fluid velocity $\\bu=(u,v,w)$, determine the expression for the impermeability condition at the sphere surface.\n\\begin{answer}\n\\begin{equation*}\nux+vy+w(z+U_\\text{impact}t) = -U_\\text{impact}(z+U_\\text{impact}t)\n\\end{equation*}\n\\end{answer}\n\n\\end{enumerate}\n\\prg{Flow over an obstacle.} We now consider the flow of a river over an obstacle, such as the one illustrated~\\ref{fig:obstacle}. For simplification purposes, we take the flow as uniform far upstream, $\\bu = U \\be_x$, and translation invariant (that is, 2D) in the transverse direction. The vertical direction is given by $\\be_y$ and we note the velocity components $\\bu=(u,v)$. The bottom height is given by the function $y = f(x)$. \n\\begin{enumerate}[resume]\n\\item Determine the vector normal to the river bottom.\n\\item Express the impermeability condition at the bottom.\n\\begin{answer}\n\\begin{equation*}\nv = u f'(x)\n\\end{equation*}\n\\end{answer}\n\n\\item Sketch schematically the vertical velocity near the bottom in the context of the localised obstable (think of a Gaussian hump). Comment.\n\\end{enumerate}\n\\section{Flow around a cylinder with suction}\nWe consider in this exercise the structure of the flow around a cylinder able to exert a suction (or blowing) on the surrounding fluid, as a rudimentary model of a \\textit{turbosail} (see lecture).\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[height=5cm,valign=m]{aspiration_cylindre.jpg}\n    \\caption{\\textbf{Turbosail model at ONERA.} The suction through the cylinder boundary allows the flow to reattach on the cylinder.}\n    \\label{fig:turbosail}\n\\end{figure}\n\nIn the remaining, we consider the flow as translation-invariant (2D), incompressible and potential. We note $\\bu = (u,v)$ the components of the velocity field and we introduce the streamfunction $\\psi$ such that:\n\\begin{empheq}[left=\\empheqlbrace]{alignat=2}\nu &\\,=\\,&\\, \\pd{\\psi}{y} \\\\\nv &\\,=\\,&\\, -\\pd{\\psi}{x}\n\\end{empheq}\nDepending on the context we will use cartesian coordinates $(x,y)$ or polar ones $(r,\\theta)$.\n\\begin{enumerate}\n\\item Show that a flow describe with such a streamfunction automatically satisfies mass conservation.\n\\begin{answer}\nIf the flow is incompressible then mass conservation reduces to:\n\\begin{equation*}\n\\nabla \\cdot \\bu = 0.\n\\end{equation*}\nFor a flow described by a streamfunction the velocity field divergence reads:\n\\begin{equation*}\n\\nabla \\cdot \\bu = \\pd{}{x}\\lp\\pd{\\psi}{y}\\rp-\\pd{}{y}\\lp\\pd{\\psi}{x}\\rp = 0\n\\end{equation*}\nby construction, whatever $\\psi$.\n\\end{answer}\n\\item Show that the potential flow condition implies $\\Delta \\psi = 0$.\n\\begin{answer}\nA potential flow is such that:\n\\begin{equation*}\n\\nabla \\times \\bu = 0.\n\\end{equation*}\nFor a 2D flow this condition reduces to: \n\\begin{equation*}\n\\pd{v}{x}-\\pd{u}{y} = 0.\n\\end{equation*}\nOn using the relation between $(u,v)$ and $\\psi$ we get $-\\Delta \\psi =0$.\n\\end{answer}\n\\item Verify that $\\psi_\\text{unif} = a y$ and $\\psi_\\text{source} = b\\theta$ are elementary solutions of $\\Delta \\psi = 0$. What are the associated flow patterns?\n\\begin{answer}\nThese two streamfunctions are linear in $y$ and $\\theta$, and thus verify Laplace equation trivially.\n\n{\\centering\n      \\includegraphics[width=12cm]{uniform_source.pdf}\n      \\captionof{figure}{Left: the isolines for $\\psi_\\text{uniform}$ evidence a uniform flow. Right: the isolines for $\\psi_\\text{source}$ show the purely radial flow typical of a \\textit{source}.}\n      \\par}\n\\end{answer}\n\\item What is the streamfunction associated with a uniform flow $\\bu = (U,0)$ ?\n\\begin{answer}\nWe have directly:\n\\begin{equation*}\n\\psi = Uy\n\\end{equation*}\n\\end{answer}\n\\item More complex multipolar solutions can be built from the previous elementary solutions. Compute the expression for the dipolar fields $\\psi_{\\parallel} = \\pd{}{x} \\psi_\\text{source}$ and $\\psi_{\\perp} = \\pd{}{y} \\psi_\\text{source}$. Represent the corresponding streamlines with Python.\n\\begin{answer}\nLet's write $\\psi_\\text{source}$ in cartesian coordinates:\n\\begin{equation*}\n\\psi_\\text{source} = \\arctan\\lp\\frac{y}{x}\\rp.\n\\end{equation*}\nUsing $\\partial_x\\lp\\arctan\\lp f \\rp \\rp=\\frac{\\partial_x f}{1+f^2}$ we have:\n\\begin{empheq}[left=\\empheqlbrace]{alignat=2}\n\\psi_{\\parallel}  \\,&=&\\, -\\frac{y}{r^2}\\\\\n\\psi_{\\perp} \\,&=&\\, \\frac{x}{r^2}\n\\end{empheq}\n{\\centering\n      \\includegraphics[width=12cm]{psi_dipoles.pdf}\n      \\captionof{figure}{Left: $\\psi_\\parallel$. Right: $\\psi_\\perp$.}\n      \\par}\n\\end{answer}\n\\item Show that it is possible to build the inviscid potential flow around a cylinder of radius $R$ as the superposition of  $\\psi_\\text{unif}$ and of a dipolar contribution.\n\\begin{answer}\nThe impermeability condition on the cylinder reduces to $\\psi = \\text{cst}$ along its surface, that is on $r = R$. The only way to fulfill this condition with a streamfunction of the form\n$$\n\\psi = \\psi_\\text{unif}  + a \\psi_{\\parallel} + b \\psi_{\\perp} = Uy - a \\frac{y}{r^2} + b \\frac{x}{r^2}\n $$\nis to set $a = U R^2$ and $b = 0$.\n\\end{answer}\n\\item Propose a model for the suction effect, which is characterised with a constant suction velocity  $- u_\\text{suction} \\be_r$ at the wall.\n\\begin{answer}\nThe flow associated to $\\psi_\\text{source}$ is purely radial and can be represented as:\n$$\n\\bu_\\text{source} = \\frac{x}{r^2} \\be_x + \\frac{y}{r^2} \\be_y.\n$$\nAt the cylinder surface,\n$$\n\\left.\\bu_\\text{source}\\cdot\\bn\\right|_{r=R} = \\frac{1}{R}.\n$$\nIn order to impose a wall velocity $- u_\\text{suction} \\be_r$ we need to add the following streamfunction\n$$\n\\psi_\\text{suction} = - u_\\text{suction} R \\theta\n$$\n\\end{answer}\n\\item Represent with Python the streamlines corresponding to $u_\\text{suction} / U = 0, 0.1, 1$.\n\\begin{answer}\nWe represent the streamlines associated to:\n$$\n\\psi = Uy - U R^2  \\frac{y}{r^2} - u_\\text{aspi} R \\theta\n$$\n{\\centering\n      \\includegraphics[width=16cm]{aspi.pdf}\n      \\par}\n\\end{answer}\n\\end{enumerate}\n\\section{Confined diffusion of a chemical species}\nWe aim to characterise the impact of walls or boundaries on the diffusion of a contaminant. In order to simplify the study we suppose that diffusion acts along a single axis (this may be seen as a case of translation-invariance along two directions, or of diffusion in a tube). We note $c(x,t)$ the studied concentration field.\n\nWe show that a solution to the diffusion equation\n\\begin{equation}\n\\pd{c}{t} = D \\frac{\\partial^2 c}{\\partial x^2}\n\\end{equation}\nthat exhibit the \\textit{scale invariance} property is:\n\\begin{equation}\nc(x,t) = \\frac{M}{\\sqrt{4 \\pi D t}} \\exp\\lp-\\frac{x^2}{4 D t}\\rp\n\\end{equation}\n\\begin{enumerate}\n\\item Verify that this field is actually a solution to the diffusion equation.\n\\item Integrate the total concentration field for a given time. What is the meaning of the constant $M$?\n\\item Plot with Python the evolution of this field for different instants (we'll set $M = 1$ and $D = 1$).\n\\end{enumerate}\n\\vspace{2mm}\n\nAs the diffusion equation is linear, any weight sum of elementary solutions will also be a solution. In the following we propose to use this property to build fields that comply with the boundary conditions of the problem. This approach is reminiscent of the use of ``image charges'' in electrostatics to model equipotential surfaces (boundary \\textit{``metallisation''}).\n\\paragraph{$\\rhd$ Diffusion near an impermeable wall}\nA quantity $M$ of passive scalar is deposited at a distance $\\ell$ from an impermeable surface located at $x = 0$. \n\\begin{enumerate}[resume]\n\\item What is the boundary condition for the concentration field at $x = 0$ ?\n\\item By placing a fictitious concentration field symmetric with respect to the wall, show how to build a concentration field respecting the impermeability condition. Give the expression for this field and represent it with Python.\n\\end{enumerate}\n\\paragraph{$\\rhd$ Diffusion near an absorbing wall}\nWe now coat the previous wall with a reactant that recombines with the concentration field so that the effective absorbing condition $c(0,t) = 0$ is now verified.\n\\begin{enumerate}[resume]\n\\item Propose a strategy to find the evolution of the concentration field in these conditions.\n\\item What is the concentration flux towards the wall? \n\\end{enumerate}\n\\paragraph{$\\rhd$ Confined diffusion}\nWe now consider the diffusion of a contaminant when confined between two impermeable walls located at $x=\\pm \\ell$. The contaminant is initially deposited at $x=0$.\n\\begin{enumerate}[resume]\n\\item Is it sufficient to add three elementary solutions to model the influence of the walls? To answer this question it will be helpful to estimate the flux at each wall.\n\\item To circumvent this issue, we propose to model the field as a superposition of an infinite sum of elementary solutions located at $x = 2 j \\ell, \\, j\\in \\mathbb{Z}$.\n\\item In order to determine the weight of each term, write the zero-flux condition at $x = \\ell$.\n\\item Plot with Python the evolution of the field for different instants.\n\\item What is the asymptotic value of the concentration in the gap?\n\\end{enumerate}\n\\section{Liquid puddles}\n \\noindent A liquid laid over a rigid substrate in the gravity field spontaneously adopts a puddle shape, as illustrated in the facing figure. The liquid has a density $\\rho$, a surface tension $\\gamma$ with the air, and presents a contact angle $\\theta$ with the solid. We denote the gravity with $g$. \n\\begin{wrapfigure}{L}{5cm}\n\\centering\n\\includegraphics{flaque.pdf}\n\\end{wrapfigure}\n\n\\noindent We look for the limit thickness $e_c$ of the puddle far from the edges.\n\\begin{enumerate}\n\\item Represent graphically the forces acting on the puddle portion illustrated on the figure.\n\\item Write the equilibrium condition for the puddle, and deduce the thickness $e_c$ as a function of $\\rho$, $g$, $\\theta$ and $\\gamma$. \n\\item What is the asymptotic value of $e_c$ in the limit where $\\theta \\ll 1$ ?\n\\end{enumerate}\n~\n\n\\section{Capillary adhesion of a sphere}\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[valign=m,page=1]{adhesion_sphere.pdf}\n    \\hspace{1cm}\n    \\includegraphics[valign=m,page=2]{adhesion_sphere.pdf}\n    \\caption{\\textbf{Capillary adhesion of a sphere.} Left: a sphere of radius $a$ adheres to a plane thanks to a small meniscus of radius~$\\delta$. Right: the meniscus exhibits a curvature radius $r$ much smaller than the sphere radius.}\n    \\label{fig:adhesion}\n\\end{figure}\n\\noindent We consider in this problem the capillary adhesion undergone by a solid sphere of radius $a$ contacting a rigid plane. The sphere adhesion is induced by the presence of a small meniscus made of a perfectly wetting liquid (zero contact angle). The meniscus presents a radial extension $\\delta$ that will be supposed much smaller than the radius of the sphere (see figure~\\ref{fig:adhesion}). We look for a determination of the vertical component of the capillary force exercée by the meniscus on the sphere, and henceforth noted $F_\\text{cap}$. We note the density $\\rho$ and the surface tension of the liquid with air $\\gamma$. The liquid will be considered quiescent throughout the exercise and we will neglect the influence of gravity.\n\n\\begin{enumerate}\n\\item Justify rapidly why the liquid viscosity cannot enter in the determination of $F_\\text{cap}$. Then show using dimensional analysis that: \n$$\nF_\\text{cap} = \\gamma a \\, \\mathcal F(\\varepsilon),\n$$\nwhere $\\varepsilon$ is a small nondimensional parameter which will be explicited. In this exercise we are interested in the limit~$\\varepsilon \\ll~1$.\n\\item As the contact angle between the liquid and the solids (both the plane and the bead) is zero, the interface is sharply curved, as indicated figure~\\ref{fig:adhesion}. We suppose in particular that the curvature radius $r$ represented on the sketch is much smaller than the interface' second curvature radius. As a result we suppose that the meniscus displays a single radius of curvature $r$ in first approximation. Without calculus, give the sign of the pressure difference between the meniscus and the air $\\Delta p = p_\\text{ménisque} -p_\\text{atm}$ ; is the meniscus in a state of higher or lower pressure with respect to the atmosphere? Explain.\n\\item In order to track the meniscus extension we introduce the angle $\\theta$ represented on figure~\\ref{fig:adhesion}. We remind that $\\delta \\ll a$ and therefore $\\theta \\ll 1$. Give the relation linking $\\delta$ to $a$ and $\\theta$ in first approximation.\n\\end{enumerate}\nThe force exerted by the liquid meniscus on the bead can be decomposed into two contributions: one due to Laplace pressure, and a second corresponding to the contact line action. Let's focus on the first contribution to start with. In the remaining we will not consider the influence of atmospheric pressure\\footnote{In fact we can show that atmospheric pressure contribution naturally cancels out: the intensity of the adhesion force does not depend on it.}.\n\\begin{enumerate}[resume]\n\\item Noting $\\mathcal S_\\text{sphere}$ the portion of the sphere wetted by the meniscus, give the formal expression for the pressure force exerted by the meniscus onto the sphere.\n\\item Show that we can replace this expression with:\n$$\n\\iint_{\\mathcal S_\\text{disc}} \\!\\!\\!\\Delta p \\,\\boldsymbol e_z \\, \\mathrm dS,\n$$\nwhere $\\mathcal S_\\text{disc}$ now represents the surface of the plane wetted by the meniscus.\n\\item On considering that $\\ell \\simeq 2r$ (see figure~\\ref{fig:adhesion}), propose an estimation of the curvature radius $r$ as a function of $a$ and of $\\theta$ to first order in  $\\theta$ (we remindd that $\\cos \\theta = 1 - \\tfrac{1}{2} \\theta^2 + \\tfrac{1}{24} \\theta^4 + O(\\theta^6)$ for $\\theta \\ll 1$).\n\\item Deduce the expression of the pressure contribution in the capillary adhesion force to first order.\n\\item Explain why the contact line contribution is negligible in this problem.\n\\item Conclude on the value of the adhesion force, and comment on the dependence with the meniscus volume. What is the limit of the function $ \\mathcal F(x)$ of question 1 when $x$ tends to 0?\n\\end{enumerate}\n\\section{Curvature of a pendent drop}\n\n\\begin{wrapfigure}{L}{5cm}\n\\centering\n\\includegraphics[width=5cm]{goutte_eau_jussieu.png}\n\\end{wrapfigure}\n \nIn order to develop a device for surface tension measurement, we wish to write a numerical code to compute the shape of an axisymmetric pendent drop.\nTo do so it is necessary to know the curvature $\\kappa(z)$ of the drop, and to link it to the drop profile $r(z)$ (the equation for the interface is then $r = r(z)$).\n\n\\begin{enumerate}\n\\item Explain why working directly with $r(z)$ is not a good strategy. How does this quantity behave near the drop bottom?\n\\end{enumerate}\nWe thus work in the following with the variable $q(z) = r^2(z)$.\n\\begin{enumerate}\n\\setcounter{enumi}{1}\n\\item Propose a function $\\mathcal S(r,z)$ that vanishes at the free surface and involves $q(z)$.\n\\item Compute the normalised gradient of this function. What is the meaning of this field restriction at the drop free surface?\n\\item Show that the drop curvature $\\kappa(z)$ can be expressed as:\n\\begin{equation}\n\\kappa(z) = \\frac{4 q'(z)^2 - 4q(z) (-2 + q''(z))}{(4 q(z)+q'(z)^2)^{3/2}}.\n\\end{equation}\n\\end{enumerate}\n\n\\section*{Appendix: differential operators in cylindrical coordinates}\n\\noindent Let $f(r,\\theta,z)$ be a scalar function of space and $\\boldsymbol{u}(r,\\theta,z) = (u_r(r,\\theta,z), u_\\theta(r,\\theta,z), u_z(r,\\theta,z))$ a vector field. We define:\n\\begin{equation*}\n\\nabla f = \\left(\n\\begin{array}{c}\n\\displaystyle\\frac{\\partial f}{\\partial r}\\\\[1em]\n\\displaystyle\\frac{1}{r}\\frac{\\partial f}{\\partial \\theta}\\\\[1em]\n\\displaystyle\\frac{\\partial f}{\\partial z}\n\\end{array}\n\\right), \n\\quad \\nabla \\cdot \\boldsymbol{u} = \\frac{1}{r} \\frac{\\partial}{\\partial r}\\bigg( r u_r\\bigg) + \\frac{1}{r} \\frac{\\partial u_\\theta}{\\partial \\theta} + \\frac{\\partial u_z}{\\partial z},\n\\quad \\Delta f = \\frac{1}{r} \\frac{\\partial}{\\partial r}\\bigg( r \\frac{\\partial f}{\\partial r}\\bigg) + \\frac{1}{r^2} \\frac{\\partial^2 f}{\\partial \\theta^2} + \\frac{\\partial^2 f}{\\partial z^2}\n\\end{equation*}\n\n\\bibliographystyle{jfm}\n\\bibliography{biblio_tuto}\n\\end{document}", "meta": {"hexsha": "0593afc8ca5164fce03fa02b8e29d597e60c3e27", "size": 22305, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tutorials/tutorial_02.tex", "max_stars_repo_name": "antko/physics-of-fluids", "max_stars_repo_head_hexsha": "307f1c25c59345943a4bce90e031ced5dde105bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tutorials/tutorial_02.tex", "max_issues_repo_name": "antko/physics-of-fluids", "max_issues_repo_head_hexsha": "307f1c25c59345943a4bce90e031ced5dde105bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorials/tutorial_02.tex", "max_forks_repo_name": "antko/physics-of-fluids", "max_forks_repo_head_hexsha": "307f1c25c59345943a4bce90e031ced5dde105bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.9246575342, "max_line_length": 747, "alphanum_fraction": 0.738085631, "num_tokens": 6677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.32952463409139515}}
{"text": "\\documentclass[11pt]{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage[margin=0.3in]{geometry}\n\\usepackage{hyperref}\n%---------------------------------------\n\\title{Basic EDA}\n\\author{Pramod Duvvuri}\n\\date{March 31, 2019}\n\\begin{document}\n\t\\maketitle\n\tThe below notes are written to accompany the book \\textit{Visualizing Data} by William Cleveland and the S670 class notes written by Prof. Dr. Brad Luen. Before learning Exploratory Data Analysis (EDA), one should be familiar with the basics of statistical concepts. One should also be familiar with Regression. The language of choice is \\textbf{R} and the IDE is RStudio and we shall be using the \\textit{ggplot2} package of the \\textit{tidyverse} to plot, analyze and draw conclusions from the data we have. The references section will contain important resources that will aid you in understanding some tricky concepts that you shall encounter. Regarding the data, always pick datasets that have a lot of observations/rows, the minimum should be at least 100 observations.\n\t\\begin{enumerate}\n\t\t\\item Differences between CDA/EDA\n\t\t\\item What is EDA ?\n\t\t\\begin{enumerate}\n\t\t\t\\item Graphing\n\t\t\t\\item Fitting\n\t\t\\end{enumerate}\n\t    \\item The need for EDA\n\t\t\\item \\textbf{Univariate Data} Single Measurement of a Quantitative Variable\n\t\t\\begin{enumerate}\n\t\t\t\\item Histogram\n\t\t\t\\begin{enumerate}\n\t\t\t\t\\item Number of Bins\n\t\t\t\t\\item Binwidth\n\t\t\t\\end{enumerate}\n\t\t\t\\item Density Plot (Frequency Polygon)\n\t\t\t\\item Boxplot\n\t\t\t\\item ECDF\n\t\t\t\\item Normal QQ Plot\n\t\t\t\\item Tukey Mean difference Plot\n\t\t\t\\item Additive Shift\n\t\t\t\\item Fitting a linear model\n\t\t\t\\item Residual Fitted Spread Plot\n\t\t\t\\item Skewness\n\t\t\t\\item Monotone Spread\n\t\t\t\\item Transformations\n\t\t\t\\begin{enumerate}\n\t\t\t\t\\item Log Transform (log2/log10)\n\t\t\t\t\\item Power Transform\n\t\t\t\\end{enumerate}\n\t\t\\item Spread Location Plot\n\t\t\\end{enumerate}\n\t\\item \\textbf{Bivariate Data} - Paired Measurements of Two Quantitative Variables\n\t\\begin{enumerate}\n\t\t\\item Correlation (Spearman/Kendall/Pearson)\n\t\t\\item Scatter Plot\n\t\t\\item loess curve (Parameters)\n\t\t\\begin{enumerate}\n\t\t\t\\item $\\alpha$\n\t\t\t\\item $\\lambda$\n\t\t\\end{enumerate}\n\t    \\item Curve with Confidence Intervals\n\t     \\item Skewed Data\n\t     \\begin{enumerate}\n\t       \\item Leptokurtic (Less Area in the Tails)\n\t     \\item Platykurtic (More Area in the Tails)\n\t     \\end{enumerate}\n        \\item Robust Fits\n        \\item Sliced Distribution Plots\n\t\\end{enumerate}\n\t\\end{enumerate}\n\\newpage\n\\subsection*{References}\n\\begin{enumerate}\n\t\\item \\url{http://docs.statwing.com/interpreting-residual-plots-to-improve-your-regression/}\n\\end{enumerate}\n\\subsection*{ggplot2 functions}\n\\begin{verbatim}\n ECDF - stat_ecdf()\n Histogram - geom_histogram()\n Density Plot - geom_density()\n Boxplot - geom_boxplot()\n Quantile Plot - stat_qq()\n Facet Grid - facet_grid()\n Facet Wrap - facet_wrap() \\\\ m x n display\n Scatter Plot - geom_point()\n Line - geom_abline()\n QQ Plot - qqplot() \\\\ Base R function\n Flip Axes - coord_flip()\n Picking Colors - color()\n Details in Histogram - scale_x_continuous()/scale_y_continuous()\n To Set Axis Limits - coord_cartesian()\n\\end{verbatim}\n\\end{document}\t", "meta": {"hexsha": "ff5fede93729e8454e2cb5c5450b5cfbf713264b", "size": 3136, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Statistics/Basic_EDA.tex", "max_stars_repo_name": "dvpramodkumar/notes", "max_stars_repo_head_hexsha": "7a25ad204c27c63be11608e961c5109c57075703", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Statistics/Basic_EDA.tex", "max_issues_repo_name": "dvpramodkumar/notes", "max_issues_repo_head_hexsha": "7a25ad204c27c63be11608e961c5109c57075703", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Statistics/Basic_EDA.tex", "max_forks_repo_name": "dvpramodkumar/notes", "max_forks_repo_head_hexsha": "7a25ad204c27c63be11608e961c5109c57075703", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8941176471, "max_line_length": 776, "alphanum_fraction": 0.7292729592, "num_tokens": 876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.32952462503647323}}
{"text": "\\documentclass[12pt]{article}\n\n\\usepackage{natbib,amsfonts,graphics,amsmath}\n\\usepackage{graphicx}\n\n\\include{newcommands}\n\n\\begin{document}\n\t\n\t\\title{The Froude number in stratified flow above topography}\n\t\n\t\\author{Eric Mayer and Oliver Fringer}\n\t\n\t\\maketitle\n\t\n\t\\section{Abstract}\n\t\n\tThere is a debate in the literature of stratified flows above topography over the correct dimensionless number to refer to as a Froude number. Common candidates include $U/ND$, $U/Nh_0$, and $Uk/N$. \n%\twhere $U$ is the background horizontal velocity, $N$ the background buoyancy frequency, $D$ the background depth, $h_0$ the maximum height of the topography, and $k$ a characteristic wave number of the topography. \n\tAdditionally, one can use the perturbation quantities $u_0$, $g'$, and $\\delta$, to define an `internal' or `layer' Froude number $Fr_{\\delta}=u_0/\\sqrt{g'\\delta}$. ~\\citep{Rossby1951,Winters2012}. \n\t\n\tIn this paper, we nondimensionalize the 2D boussinesq equations describing the flow of infinitly deep fluid over topography to determine a scaling relationship between inner and outer quantities. Our scaling shows that, although it looks like an inverse Froude number, $Nh_0/U$ is in fact the square of the internal Froude number, $Fr_{\\delta}^2=\\frac{u_0^2}{g'\\delta}$. \n\t\n\t\n\t\n\t\\section{Introduction}\n\t\n\tIn its most generally accepted use, the Froude number represents a ratio of the speed with which two processes,  advection and wave propagation, carry information of a disturbance throughout a system. In the simple case of homogenous open channel flow, the Froude number is given by $Fr=q/\\sqrt{gd}$, where $q$ is the  local depth-averaged velocity, $d$ is the local depth, and $g$ is the acceleration of gravity. \n\t\n\tIn the case of stratified flow with a finite depth, $D$, over a ridge of height, $h_0$, and width, $2\\pi/k$, with uniform upstream velocity, $U$, and buoyancy frequency $N^2=-\\frac{g}{\\rho_0}\\D{\\bar{\\rho}}{z}$ (see sketch), one can form three dimensionless numbers that resemble the Froude number, $U/ND$, $U/Nh_0$, and $Uk/N$. However, not all of these numbers represent a ratio of advection to wave propagation, and thus calling all of these parameters Froude numbers robs the concept of its intuitive dynamic significance. In his seminal text on stratified flow over topography, Baines proposed that, as a solution to this ``Froude for everything syndrome,'' the literature should only refer to the most obvious extension of open channel flow as a Froude number; that is,  $Fr=U/ND$, where $ND$ is the speed of the first mode (fastest) internal gravity wave \\citep{Baines1995}. \n\t\n\tFor oceanic flows away from continents or mid-ocean ridges, however, $Fr=U/ND$ is often very small. For example, in the Drake Passage region of the Antarctic Circumpolar Current, where lee waves are predicted to be dynamically important, typical values for dimensional quantities are $U \\approx 0.1$~m~s$^{-1}$, $N \\approx 10^-3$~rad~s$^{-1}$, and $D \\approx 4000$~m, giving $U/ND \\approx 0.025$ \\citep{Nikurashin2010a}. In these systems, the dynamics are captured better by considering the case of an infinitely deep ocean (e.g. \\cite{Long1953}), for which solutions describe a stationary wave above the ridge, with energy propagating upwards to infinity. \n\t\n\tIn this system, the dimensionless number of primary dynamical significance is $Nh_0/U$, which has various names in the literature. Miles refers to it as the Russel number, $Ru$, after the fluid mechanician John Scott Russel, who described the reduction in drag on a shipping vessels when propelled faster than the shallow water wave speed $\\sqrt{gd}$ ~\\citep{Miles1969}.\n%\t~\\footnote{ In defense of the Russel number, the dynamics of this phenomenon are more closely related to the modern conception of the Froude number than are the dynamics of the system that Froude himself considered, where the length scale was the length of the ship rather than the depth of the channel ~\\citep{Baines1995}. However, rectifying history so dramatically might cause more confusion than it is worth.}\n\t Aguilar and Sutherland refer to it as the Long number, $Lo$, in honor of Robert Long's pioneering work on the lee wave problem \\citep{Aguilar2006a,Long1953}. Nikurashin and Ferrari refer to it as a steepness parameter and use the symbol $\\epsilon$, after showing that in the hydrostatic limit, it is identical to the ratio of topographic slope to wave ray slope, an important parameter in the internal tides literature \\citep{Nikurashin2010a}. And predictably, much of the literature simply refers to $Nh_0/U$ an inverse Froude number \\citep{Laprise1989,Legg2008a,Klymak2010,Eckermann2010,Winters2012}. By nondimensionalizing the equations describing this flow, we will show that regardless of its name,  $Nh_0/U$ is in fact the square of the internal Froude number, $Fr_{\\delta}=u_0/\\sqrt{g'\\delta}$. \n\t\n\tThis relation, however, breaks down if height of the topography is greater than the wavelength of the internal gravity wave, $N/U$, at which point the flow becomes hydraulically controlled, with the internal Froude number held constant at 1 \\citep{Winters2012}. Thereafter, $Nh_0/U$ informs instead the degree of blocking. It is as if these hills larger than a buoyancy wavelength have squeezed all the juice out of the upstream stratified flow. Hence we term this square of an internal Froude number $J$ for Juice. \n\t\n\t\n\t\\section{Nondimensional equations} \\label{eq:equations}\n\t\n\t\\begin{figure}\n\t\t\\centering\n\t\t\\includegraphics[width=1\\textwidth]{system_sketch.png}\n\t\t\\caption{Sketch of the system. Streamlines generated using the iterative solution to Long's model over a Witch of Agnesi as described in ~\\cite{Laprise1989}, with $J=0.8$ and $\\epsilon=0.1$. }\n\t\\end{figure}\n\t\n\tThe two-dimensional flow of an unbounded fluid over an isolated hill of height, $h_0$, and width, $2\\pi/k$ is characterized by the dimensional quantities\n\t$U$, $k$, $N$, and $h_0$, where $U$ and $N$ are the constant horizontal velocity and buoyancy upstream of the hill. Choosing $U$ and $N$ to nondimensionalize $k$ and $h_0$, the governing\n\tnondimensional parameters are $J = N h_0/U$ and $\\epsilon = k U/N$. \n\t\n\tLet $\\ub_{\\mbox{total}} = U {\\bf e}_x + \\ub'$, $\\rho_{\\mbox{total}} = \\rhobar(z) + \\rho'$, and\n\t$p_{\\mbox{total}} = \\rho_0 \\overline{p}(z) + \\rho_0 p'$, where the prime indicates a perturbation of the field from its background state. This notation permits a rigorous separation of external (background) quantities from internal (perturbation) quantities. \n\tMaking the Boussinesq approximation, the steady momentum and density transport equations are given by\n\t\\begin{eqnarray*}\n\tU \\D{u'}{x} + \\ub'\\cdot\\nabla u' &=& -\\D{p'}{x}\\,,\\\\\n\tU \\D{w'}{x} + \\ub'\\cdot\\nabla w' &=& -\\D{p'}{z} - \\frac{\\rho'}{\\rho_0} g\\,,\\\\\n\tU \\D{\\rho'}{x} + \\ub'\\cdot\\nabla\\rho' &=& \\frac{\\rho_0 N^2}{g} w\\,,\n\t\\end{eqnarray*}\n\twhere $N^2 = -g/\\rho_0 \\partial\\rhobar/\\partial z$, subject to continuity $\\nabla\\cdot\\ub'=0$, and\n\tthe kinematic bottom boundary condition\n\t\\[\n\tU\\D{h}{x} + u' \\D{h}{x} = w'\\,.\n\t\\]  \n\tNondimensionalize with the internal quantities\n\t\\begin{eqnarray*}\n\t\tu' &=& u_0 u^*\\,,\\\\\n\t\tw' &=& w_0 w^*\\,,\\\\\n\t\t\\rho' &=& R \\rho^*\\,,\\\\\n\t\tp' &=& P p^*\\,,\\\\\n\t\tx &=& k^{-1} x^*\\,,\\\\\n\t\tz &=& \\delta z^*\\,.\n\t\\end{eqnarray*}\n\tNondimensionalizing the kinematic bottom boundary condition gives\n\t(omitting the $*$ on nondimensional variables)\n\t\\[\n\tk U h_0 \\D{h}{x} + k u_0 h_0 \\D{h}{x} = w_0 w\\,.\n\t\\]\n\tIf we require a balance between the linear terms, this implies $w_0 = k h_0 U$, giving\n\t\\[\n\t\\D{h}{x} + \\frac{u_0}{U} \\D{h}{x} = w\\,.\n\t\\]\n\tNow, the vertical scale of the flow as given by $\\delta$ is not the\n\tsame as the hill height $h_0$, since $\\delta$ must be finite as $h_0\\to 0$ (the linear limit). The \n\tvertical scale is thus dictated by continuity, which requires\n\t\\[\n\tk u_0 \\D{u}{x} + \\frac{w_0}{\\delta} \\D{w}{z} = 0\\,,\n\t\\]\n\tor, since this implies $k u_0 = w_0/\\delta$, then we must have $\\delta = w_0/(k u_0) = k h_0 U/(k u_0) = h_0U/u_0$.\n\tNondimensionalizing the $x$-momentum equation gives\n\t\\begin{eqnarray*}\n\tk u_0 U \\D{u}{x} + k u_0^2\\ub\\cdot\\nabla u  &=& -k P \\D{p}{x}\\,.\n\t\\end{eqnarray*}\n\tIf we require a leading-order balance between the pressure gradient and the linear momentum advection term,\n\twe must have $P = u_0 U$, which gives\n\t\\begin{eqnarray*}\n\t\\D{u}{x} + \\frac{u_0}{U} \\ub\\cdot\\nabla u &=& -\\D{p}{x}\\,.\n\t\\end{eqnarray*}\n\tThe equation for the nondimensional density transport given by\n\t\\[\n\tk U R \\D{\\rho}{x} + k u_0 R \\ub\\cdot\\nabla\\rho = \\frac{k \\rho_0 h_0 N^2 U}{g} w\\,.\n\t\\]\n\tIf we require a balance between the linear advection terms, then the scale for the density\n\tperturbation is \n\t\\[\n\tR = \\frac{\\rho_0 N^2 h_0}{g}\\,,\n\t\\]\n\tso that the nondimensional density equation is\n\t\\[\n\t\\D{\\rho}{x} + \\frac{u_0}{U} \\ub\\cdot\\nabla\\rho = w\\,.\n\t\\]\n\tNondimensionalizing the vertical momentum equation, we have\n\t\\[\n\tk^2 h_0 U^2 \\D{w}{x} + k^2 h_0 u_0^2\\ub\\cdot\\nabla w = -\\frac{P}{\\delta}\\D{p}{z} - \\frac{g R}{\\rho_0} \\rho\\,.\n\t\\]\n\tIf we require a vertical hydrostatic balance to leading order, then we must have \n\t\\[\n\t\\frac{P}{\\delta} = \\frac{g R}{\\rho_0} \n\t= N^2 h_0\\,,\n\t\\]\n\tand\n\t\\[\n\tP = \\delta N^2h_0\n\t= \\frac{N^2h_0^2U}{u_0}.\n\t\\]\n\t%\\[\n\t%P = \\frac{g R \\delta}{\\rho_0} \n\t%  = \\frac{g}{\\rho_0} \\frac{\\rho_0 N^2 h_0}{g} \\frac{h_0}{F}\n\t%  = \\frac{g}{\\rho_0} \\frac{\\rho_0 N^2 h_0}{g} \\frac{U}{N}\n\t%  = U N h_0\\,.\n\t%\\]\n\twhich gives\n\t\\[\n\t\\epsilon^2 \\left(\\D{w}{x} + \\frac{u_0}{U}\\ub\\cdot\\nabla w\\right) = -\\D{p}{z} - \\rho\\,,\n\t\\]\n\twhere \n\t\\[\n\t\\epsilon = \\frac{Uk}{N}\n\t\\]\n\tis the nonhydrostatic parameter, and represents a ratio of the frequency with which the flow over the hill excites a wave, $Uk$, to the frequency of the buoyant response, $N$. A propagating wave is only possible if the excitation frequency is smaller than the buoyancy frequency ($\\epsilon<1$). In other words, for the perturbation from flow over a hill to result in oscillations that buoyancy can carry away from the hill, it must allow buoyancy enough time to oscillate. Within this propagating regime, one can also think of $\\epsilon$ as a ratio of the wavelength of the wave to the width of the hill. For waves much smaller than the hill is long ($\\epsilon<<1$), the wave is approximately hydrostatic and the group velocity of the wave (in the reference frame of the hill) is oriented vertically. \n\t\n\tNow, returning to the pressure, since from the vertical momentum equation we\n\trequire $P = N^2h_0^2U u_0^{-1}$ and from the horizontal momentum equation we require $P = u_0 U$, then equating the\n\ttwo implies that $u_0 = N h_0$ and thus\n\t\\[\n\t\\frac{u_0}{U} = \\frac{N h_0}{U} \\equiv J\\,.\n\t\\] \n\tTherefore, in terms of $J$, the governing nondimensional equations are given by\n\t\\begin{eqnarray*}\n\t\t\\D{u}{x} + J\\ub\\cdot\\nabla u &=& -\\D{p}{x}\\,,\\\\\n\t\t\\epsilon^2 \\left(\\D{w}{x} + J\\ub\\cdot\\nabla w\\right) &=& -\\D{p}{z} - \\rho\\,,\\\\\n\t\t\\D{\\rho}{x} + J \\ub\\cdot\\nabla\\rho &=& w\\,,\n\t\\end{eqnarray*}\n\tsubject to $\\nabla\\cdot\\ub=0$ and the kinematic bottom boundary condition\n\t\\[\n\t\\left(1 + J \\right)\\D{h}{x} = w\\,.\n\t\\]\n\tThese nondimensional equations are consistent with the original nondimensionalization which implied\n\tthat the problem is uniquely characterized by $\\epsilon$ and $J$.\n\tThe relevant scales (nondimensionalized by $N$ and $U$) are given by\n\t\\begin{eqnarray*}\n\t\t\\frac{u_0}{U} &=& J\\,,\\\\\n\t\t\\frac{w_0}{U} &=& \\epsilon J\\,,\\\\\n\t\t\\frac{gR}{\\rho_0 U N} &=& J\\,,\\\\\n\t\t\\frac{P}{U^2} &=& J\\,,\\\\\n\t\t\\frac{\\delta N}{U} &=& 1\\,.\n\t\\end{eqnarray*}\n\tIf we define the internal Froude number as\n\t$Fr_\\delta = u_0/\\sqrt{g' \\delta}$, where $g'\\delta =g (R/\\rho_0) \\delta = J U^2$, this gives\n\t$Fr_{\\delta} = J^{1/2}$. Thus although it looks like an inverse Froude number when expressed in external variables, this scaling shows that it is\n\tin fact appropriate to refer to $J$ as the square of an internal Froude number. \n\t\n\t\\section{Discussion}\n\t\n\tThat the outer and inner variable representations of $J$ should present velocity and gravity inversely results from the fact that the wavelength of the internal gravity wave is determined exclusively from the upstream quantities of the flow, $U$ and $N$. Dynamically, this is analogous to case of a simple pendulum, where the period of oscillation is set by the force of gravity and the length of the string, and is oblivious to the magnitude of the displacement that sets it swinging.  On the other hand, all other internal quantites in the flow scale with the ratio of the hill height to this wavelength, that is, with $J$. Thus in comparing ratios of internal advection to wave speed, the height of the hill enters linearly into the perturbation velocity, but only as a half-power in the wave speed. That is, $u_0=JU$ while $\\sqrt{g'\\delta} = J^{1/2} U$.  \n\t\n\tThat $J$ is the square of the internal Froude number begs for an energetic interpretation of the dynamics. Borrowing from the theory of homogenous open channel flow, a flow with a set amount of energy can conceivably partition its energy into a spectrum of configurations from entirely potential ($Fr=0$) to almost entirely kinetic ($Fr \\to \\infty$). However, the volume flux of the flow, $Q=qd$, is not constant over this spectrum, as clearly a system with all potential energy has no flux (velocity), and a system with all kinetic energy has no volume (depth). Rather, for a given energy, the flow achieves its maximum volume flux when $Fr=1$. Similarly, our scaling shows that the perturbation volume flux, $u_0\\delta$, increases with $J$ from 0 when $h_0=0$ to $U^2/N$ when $h_0=U/N$. \n\t\n\tFrom the literature, however, it is clear that this the flow cannot physically sustain this maximal volume flux. A precondition on the wave solution to the flow is that it remain stable to both convective and shear instabilities ~\\citep{Long1953,Miles1961}. Assymptotic and fully nonlinear solutions for the streamlines of the flow using Long's model ~\\citep{Long1953} show both vertical streamlines (convective instability) and Richardson numbers smaller than 0.25 (shear instability) developing before $J$=1 for flow over a various ridge shapes (see, for example, ~\\cite{Miles1969,Smith1977,Laprise1989}). Even our scaling suggests that shear instability should set in by the time $J=2$, since a reversal of flow occurs twice per wavelength, and thus $Ri\\approx\\frac{2g'/\\delta}{(2u_0/\\delta)^2}=\\frac{1}{2J}$. For this reason, $J$ is generally interpreted as a nonlinearity parameter rather than the square of the internal Froude number ~\\citep{Miles1969,Baines1995,Aguilar2006,Nikurashin2010a,Eckermann2010}. \n\t\n%\tConceptually, we can picture a column of water headed for an isolated hill. As it approaches the hill, it enters the wave field, and the lowest elements are lifted in preparation for a race across the crest. The height of this lift must be enough to overtop the hill, and scales with $h_0$. Then buoyancy acts on these lifted parcels, translating the wave's potential energy into kinetic energy. This is the source of the perturbation velocity over the hill, as indicated by the scaling $u_0=JU=Nh_0$.  This lift is also the source of the perturbation to the density field, and thus the reduced gravity that the background velocity must work against to generate the wave also scales with $h_0$. We see this in the scaling $g'=g (R/\\rho_0)=JUN=N^2h_0$. However, the length scale of this work against gravity is the wavelength, $\\delta$, which is oblivious to $h_0$. \n\t\n\tIndeed, the identification of $J$ with the internal Froude number squared appears to have gone almost without notice the literature. However, an inquiry into the upper limit of this relationship recently emerged from consideration of blocked flow past a half cylinder \\citep{Winters2012}. In the blocked regime, that is, for flow in which $J>O(1)$, the lowest fluid elements upstream of the obstacle lack sufficient kinetic energy to overtop the obstacle, and thus form a pool of stagnant fluid at the obstacle's base \\citep{Baines1995}. As a result, the obstacle takes on the apparent height to the unblocked flow of U/N, that is, exactly the height of the flow's kinetic hill-climbing capacity, giving $J_{unblocked}=1$. In this case, Winter's and Armi show that the $Fr_{\\delta}=1$ at the crest of the hill and, in analogy to hydraulic control of an unstratified river, the flow of the layer defined by the streamline that passes one wavelength above the crest of the hill exhibits a transition from subcritical flow upstream to a supercritical jet downstream followed by a dissipative hydraulic jump. \n\t\n\tIn other words, the relation between $J$ and $Fr_{\\delta}$ holds only up to $J=O(1)$. Below this limit, waves accommodate the disturbance of the hill adiabatically, and carry it away from the site of generation, just as in an unstratified river flowing over a sub-critical sill. As $J$ approaches $O(1)$, the advective component of the perturbation plays a more significant role, until the perturbation volume flux above the hill reaches the maximum value that the system can energetically support. All of this squares with the dynamical significance of a Froude number. Above this limit, however, the instabilities brought on by too great a perturbation velocity restabilize the system such that the jet flowing above the hill is under hydraulic control, $Fr_{\\delta}^2$=1, and $J$ informs the depth of the stagnant layer upstream as well dissipative and mixing effects of the jump downstream \\citep{Winters2012}. \n\t\n\tIn this sense, the upstream characteristics of the flow present the system with a wave making capacity, and it is up top the hill to squeeze the wave into existence. But there is only so much juice in the fruit. \n\t\n\\section{Appendix: Rotation}\nIncluding rotation in the nondimensional equations requires only slight modification. Because rotational effects necessarily involve a spanwise direction, we must now include an equation for the spanwise momentum. \n\nWe begin by aligning the $x$-direction with lines of latitude, and posit that the background currents are in geostrophic balance\n\\begin{eqnarray*}\n\t0 &=& -\\D{P_G}{x} + fV \\,,\\\\\n\t0 &=& -\\D{P_G}{y} - fU \\,,\\\\\n\\end{eqnarray*}\nwhere $P_G$ is a geostrophic pressure field that is decoupled from the perturbation pressure due the lee wave. \n\nTo keep the system as simple as possible, we further assume: it is in steady state; the bathymytery varies only in the $x$-direction; and rotation has a constant rate $f=\\Omega sin(\\bar{\\phi})$, where $\\Omega$ is the earth's rate of rotation, and $\\bar{\\phi}$ is the average lattitude of the domain. The assumption of steady state filters out inertial oscillations, and may be invalid in regions of the ocean where rotation is strong, such as the ACC ~\\citep{Nikurashin2010a}. However, in regions closer to the equator, such as Palau, this assumption is quite good, as the following scaling analysis will demonstrate.  In combination, these three assumptions allow us to neglect all spanwise gradients in the perturbation fields because the hill only perturbs the flow in the $x$-direction, there are no inertial oscillations to deflect the flow from its hill-perturbed state, and rotation remains constant at all locations in the domain. Thus, again making the Boussinesq approximation, the steady momentum and density transport equations that include (some representation of) rotation are given by\n\\begin{eqnarray*}\n\tU \\D{u'}{x} +u' \\D{u'}{x} + w' \\D{u'}{z} &=& -\\D{p'}{x} + fv' \\,,\\\\\n\tU \\D{v'}{x} + u' \\D{v'}{x} + w' \\D{v'}{z} &=& - fu' \\,,\\\\\n\tU \\D{w'}{x} + u' \\D{w'}{x} + w' \\D{w'}{z} &=& -\\D{p}{z} - \\frac{\\rho}{\\rho_0} g \\,,\\\\\n\tU \\D{\\rho'}{x} + u' \\D{\\rho'}{x} + w' \\D{\\rho'}{z} &=& \\frac{\\rho_0 N^2}{g} w\\,,\n\\end{eqnarray*}\nwhere $N^2 = -g/\\rho_0 \\partial\\rhobar/\\partial z$, subject to continuity $\\nabla\\cdot\\ub'=0$, and\nthe kinematic bottom boundary condition\n\\[\nU\\D{h}{x} + u' \\D{h}{x} = w'\\,.\n\\]  \nNote that these equations are unchanged from those in the irrotational case except for the addition of $+fv'$ to the $x$-momentum equation, and of course the presence of the $y$-momentum equation. Thus the scalings resulting from our irrotational work above hold in all cases except for these two equations. \n\nNondimensionalizing as above, with the addition of $v = v_0 v*$, the $y$-momentum equation becomes\n\\begin{eqnarray*}\n\tkUv_0 \\D{v}{x} + ku_0v_0\\left(u \\D{v}{x} + w \\D{v}{z}\\right) &=& - fu_0u \\,.\\\\\n\\end{eqnarray*}\nRequiring a balance of lowest order terms, this gives $v_0 = \\frac{fu_0}{Uk}=u_0/Ro$, where $Ro = Uk/f$ is the Rossby number, and\n\\begin{eqnarray*}\n\t \\D{v}{x} + J\\left(u \\D{v}{x} + w \\D{v}{z}\\right) &=& - u \\,.\\\\\n\\end{eqnarray*}\nTurning next to the $x$-momentum equation, we have \n\\begin{eqnarray*}\n\tk u_0 U \\D{u}{x} + k u_0^2\\left( u\\D{u}{x} + w \\D{u}{z}\\right)  &=& -k P \\D{p}{x} + fv_0v\\,.\n\\end{eqnarray*}\nAgain balancing lowest order terms, we have $P=Uu_0$, and the $x$-momentum equation becomes\n\\begin{eqnarray*}\n\t\\D{u}{x} +J\\left( u\\D{u}{x} + w \\D{u}{z}\\right)  &=& -\\D{p}{x} + Ro^{-2}v\\,.\n\\end{eqnarray*}\t\nFrom this result, we can diagnose the frailty of our assumptions about rotational effects. Using characteristic values of the ACC, $U \\approx 0.1$~m~s$^{-1}$, $N \\approx 10^-3$~rad~s$^{-1}$,  $k \\approx 2\\pi/2$~km, and $f\\approx10^{-4}$~rad~s$^{-1}$, and $h_0\\approx60$~m, we have $Ro \\approx 0.5$, $Ro^{-2}\\approx4$ and $J\\approx 0.6$ ~\\citep{Nikurashin2010a}. In other words, in the ACC, rotational effects on the scale of lee waves are zeroth order, and our assumptions simplifying them were likely misguided. However, if we focus instead on a more equatorial region with equally strong geostrophic currents, such as Palau, $f$ becomes an order of magnitude smaller, and $Ro\\approx5$ for the lee wave system, giving $Ro^{-2}\\approx 0.04$. Here, then, is a part of the ocean where rotation might only enter the equations as meridional jets squirting out of the lee waves.\n\t\n\t\n%\treflecting hydraulic control and a local energy sink, in analogy to a hydraulic jump downstream of open channel flow over a critical height.\n\t\n\t\n\t\n%Winters an Armi's analysis highlights an essential difference between this problem and the single layer channel flow from which our standard understanding of the Froude number derives. Consider the subcritical limit, in which $h$ is much less than $U/N$. Here the ``depth'' of the fluid as it travels over bathymetry is oblivious to both the ocean's depth and the bathymetry's height, and is instead entirely specified according to the impinging flow's properties, namely U and N. \t\n\n%\tWhile we would  expect a larger $N$ to block the flow and\n%\treduce the magnitude of the perturbation above the hill, the scaling shows that\n%\t$u_0 = J U$, implying that the perturbation velocity above the sill increases in step with\n%\tincreasing $J$. However, the gravitational force resulting from the perturbation is\n%\tgiven by $\\sqrt{g'\\delta} = J^{1/2} U$, which grows more slowly than $u_0$ with increasing $J$.\t\n\t\n%\t(In the 2-D case, blocking is an adiabatic advective process while span wise vorticity generation and downslope winds are diabatic. In the 3-D case, horizontal splitting is an adiabatic advective response while vertical vorticity generation represents a nearly adiabatic advective non-linearity with the unique capacity to carry energy away from the site of generation.)\n\t\n\n\n\n\t\n\t%Understanding the kinetic energy in the wave is more nuanced. Beginning with the denominators in the relation $J^{1/2}=(Nh_0/U)^{1/2}=u_0/\\sqrt{g'\\delta}$, and multiplying $J=Nh_0/U$ by $U/U$ for dimensional consistency, we have $\\sqrt{g'\\delta}= U$, this expresses that the gravity wave response exists as a direct consequence of the background velocity. Indeed, in the frame of reference moving with the water, U is the magnitude of the group velocity of this wave (as both borne out in the math and evidenced by observation of the steady state hydrostatic wave standing motionless above a hill). Similarly, considering the numerators: $(Nh_0U)^{1/2}=u_0$, we see that perturbation velocity above the hill is a direct consequence of buoyancy's attempt to restore an element to its equilibrium position, where the maximum possible displacement is the height of the hill. \n\t\n\t\n\t\n\\bibliographystyle{elsarticle-harv}\n\\bibliography{bibliography}\n\t\n\\end{document}", "meta": {"hexsha": "64e18be1536be4d7a712fea1ac1a10ea81e48718", "size": 24240, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "nondimensional/Juice_letter_2.tex", "max_stars_repo_name": "fmayer2010/LeeWavePaper", "max_stars_repo_head_hexsha": "39a0c6edd22da86c12b9cbec560c8fb350ba62be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nondimensional/Juice_letter_2.tex", "max_issues_repo_name": "fmayer2010/LeeWavePaper", "max_issues_repo_head_hexsha": "39a0c6edd22da86c12b9cbec560c8fb350ba62be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nondimensional/Juice_letter_2.tex", "max_forks_repo_name": "fmayer2010/LeeWavePaper", "max_forks_repo_head_hexsha": "39a0c6edd22da86c12b9cbec560c8fb350ba62be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 93.9534883721, "max_line_length": 1106, "alphanum_fraction": 0.7323019802, "num_tokens": 7191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.32952462503647323}}
{"text": "\\include{Preamble}\n\n\\begin{document}\n\n\\title{Draft description of NEMO wetting and drying scheme:     29 November 2017 }\n\n\\author{ Enda O'Dea, Hedong Liu, Jason Holt, Andrew Coward  and Michael J. Bell  }\n\n%------------------------------------------------------------------------\n% End of temporary latex header (to be removed) \n%------------------------------------------------------------------------\n\n% ================================================================\n% Chapter Ocean Dynamics (DYN)\n% ================================================================\n\\chapter{Ocean Dynamics (DYN)}\n\\label{DYN}\n\\minitoc\n\n% add a figure for  dynvor ens, ene latices\n\n$\\ $\\newline    % force a new ligne\n\n% ================================================================\n% Wetting and drying \n% ================================================================\n \n%----------------------------------------------------------------------------------------\n%      The WAD test cases\n%----------------------------------------------------------------------------------------\n\\section   [The WAD test cases (\\textit{usrdef\\_zgr})]\n\t\t\t{The WAD test cases (\\mdl{usrdef\\_zgr})}\n\\label{WAD_test_cases}\n\nThis section contains details of the seven test cases that can be run as part of the\nWAD\\_TEST\\_CASES configuration. All the test cases are shallow (less than 10m deep),\nbasins or channels with 4m high walls and some of topography that can wet and dry up to\n2.5m above sea-level. The horizontal grid is uniform with a 1km resolution and measures\n52km by 34km. These dimensions are determined by a combination of code in the\n\\mdl{usrdef\\_nam} module located in the WAD\\_TEST\\_CASES/MY\\_SRC directory and setting\nread in from the namusr\\_def namelist. The first six test cases are closed systems with no\nrotation or external forcing and motion is simply initiated by an initial ssh slope. The\nseventh test case introduces and open boundary at the right-hand end of the channel which\nis forced with sinousoidally varying ssh and barotropic velocities.\n\n\\namdisplay{nam_wad_usr}\n\nThe $\\mathrm{nn\\_wad\\_test}$ parameter can takes values 1 to 7 and it is this parameter\nthat determines which of the test cases will be run. Most cases can be run with the\ndefault settings but the simple linear slope cases (tests 1 and 5) can be run with lower\nvalues of $\\mathrm{rn\\_wdmin1}$. Any recommended changes to the default namelist settings\nwill be stated in the individual subsections.\n\nTest case 7 requires additional {\\tt namelist\\_cfg} changes to activate the open boundary\nand lengthen the duration of the run (in order to demonstrate the full forcing cycle).\nThere is also a simple python script which needs to be run in order to generate the\nboundary forcing files.  Full details are given in subsection (\\ref{WAD_test_case7}).\n\n\\clearpage\n\\subsection [WAD test case 1 : A simple linear slope]\n                    {WAD test case 1 : A simple linear slope}\n\\label{WAD_test_case1}\n\nThe first test case is a simple linear slope (in the x-direction, uniform in y) with an\nadverse SSH gradient that, when released, creates a surge up the slope. The parameters are\nchosen such that the surge rises above sea-level before falling back and oscillating\ntowards an equilibrium position. This case can be run with $\\mathrm{rn\\_wdmin1}$ values as\nlow as 0.075m. I.e. the following change may be made to the default values in {\\tt\nnamelist\\_cfg} (for this test only):\n\n\\namdisplay{nam_wad_tc1}\n\n%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\\begin{figure}[htb] \\begin{center}\n\\includegraphics[width=0.8\\textwidth]{Fig_WAD_TC1}\n\\caption{ \\label{Fig_WAD_TC1}\nThe evolution of the sea surface height in WAD\\_TEST\\_CASE 1 from the initial state (t=0)\nover the first three hours of simulation. Note that in this time-frame the resultant surge\nreaches to nearly 2m above sea-level before retreating.}\n\\end{center}\\end{figure}\n%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n\\clearpage\n\\subsection [WAD test case 2 : A parabolic channel ]\n                    {WAD test case 2 : A parabolic channel}\n\\label{WAD_test_case2}\n\nThe second and third test cases use a closed channel which is parabolic in x and uniform\nin y.  Test case 2 uses a gentler initial SSH slope which nevertheless demonstrates the\nability to wet and dry on both sides of the channel. This solution requires values of\n$\\mathrm{rn\\_wdmin1}$ at least 0.3m ({\\it Q.: A function of the maximum topographic\nslope?})\n\n\\namdisplay{nam_wad_tc2}\n\n%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\\begin{figure}[htb] \\begin{center}\n\\includegraphics[width=0.8\\textwidth]{Fig_WAD_TC2}\n\\caption{ \\label{Fig_WAD_TC2}\nThe evolution of the sea surface height in WAD\\_TEST\\_CASE 2 from the initial state (t=0)\nover the first three hours of simulation. Note that in this time-frame the resultant sloshing\ncauses wetting and drying on both sides of the parabolic channel.}\n\\end{center}\\end{figure}\n%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n\\clearpage\n\\subsection [WAD test case 3 : A parabolic channel (extreme slope) ]\n                    {WAD test case 3 : A parabolic channel (extreme slope)}\n\\label{WAD_test_case3}\n\nSimilar to test case 2 but with a steeper initial SSH slope. The solution is similar but more vigorous.\n\n\\namdisplay{nam_wad_tc3}\n\n%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\\begin{figure}[htb] \\begin{center}\n\\includegraphics[width=0.8\\textwidth]{Fig_WAD_TC3}\n\\caption{ \\label{Fig_WAD_TC3}\nThe evolution of the sea surface height in WAD\\_TEST\\_CASE 3 from the initial state (t=0)\nover the first three hours of simulation. Note that in this time-frame the resultant sloshing\ncauses wetting and drying on both sides of the parabolic channel.}\n\\end{center}\\end{figure}\n%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n\\clearpage\n\\subsection [WAD test case 4 : A parabolic bowl ]\n                    {WAD test case 4 : A parabolic bowl}\n\\label{WAD_test_case4}\n\nTest case 4 includes variation in the y-direction in the form of a parabolic bowl. The\ninitial condition is now a raised bulge centred over the bowl. Figure \\ref{Fig_WAD_TC4}\nshows a cross-section of the SSH in the X-direction but features can be seen to propagate\nin all directions and interfere when return paths cross.\n\n\\namdisplay{nam_wad_tc4}\n\n%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\\begin{figure}[htb] \\begin{center}\n\\includegraphics[width=0.8\\textwidth]{Fig_WAD_TC4}\n\\caption{ \\label{Fig_WAD_TC4}\nThe evolution of the sea surface height in WAD\\_TEST\\_CASE 4 from the initial state (t=0)\nover the first three hours of simulation. Note that this test case is a parabolic bowl with\nvariations occurring in the y-direction too (not shown here).}\n\\end{center}\\end{figure}\n%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n\\clearpage\n\\subsection [WAD test case 5 : A double slope with shelf channel ]\n                    {WAD test case 5 : A double slope with shelf channel}\n\\label{WAD_test_case5}\n\nSimilar in nature to test case 1 but with a change in slope and a mid-depth shelf.\n\n\\namdisplay{nam_wad_tc5}\n\n%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\\begin{figure}[htb] \\begin{center}\n\\includegraphics[width=0.8\\textwidth]{Fig_WAD_TC5}\n\\caption{ \\label{Fig_WAD_TC5}\nThe evolution of the sea surface height in WAD\\_TEST\\_CASE 5 from the initial state (t=0)\nover the first three hours of simulation. The surge resulting in this case wets to the full \ndepth permitted (2.5m above sea-level) and is only halted by the 4m high side walls.}\n\\end{center}\\end{figure}\n%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n\\clearpage\n\\subsection [WAD test case 6 : A parabolic channel with central bar ]\n                    {WAD test case 6 : A parabolic channel with central bar}\n\\label{WAD_test_case6}\n\nTest cases 1 to 5 have all used uniform T and S conditions. The dashed line in each plot\nshows the surface salinity along the y=17 line which remains satisfactorily constant. Test\ncase 6 introduces variation in salinity by taking a parabolic channel divided by a central\nbar (gaussian) and using two different salinity values in each half of the channel. This\nstep change in salinity is initially enforced by the central bar but the bar is\nsubsequently over-topped after the initial SSH gradient is released. The time series in\nthis case shows the SSH evolution with the water coloured according to local salinity\nvalues. Encroachment of the high salinity (red) waters into the low salinity (blue) basin\ncan clearly be seen.\n\n\\namdisplay{nam_wad_tc6}\n\n%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\\begin{figure}[htb] \\begin{center}\n\\includegraphics[width=0.8\\textwidth]{Fig_WAD_TC6}\n\\caption{ \\label{Fig_WAD_TC6}\nThe evolution of the sea surface height in WAD\\_TEST\\_CASE 6 from the initial state (t=0)\nover the first three hours of simulation. Water is coloured according to local salinity\nvalues. Encroachment of the high salinity (red) waters into the low salinity (blue) basin\ncan clearly be seen although the largest influx occurs early in the sequence between the\nframes shown.}\n\\end{center}\\end{figure}\n%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n\\clearpage\n\\subsection [WAD test case 7 : A double slope with shelf, open-ended channel ]\n                    {WAD test case 7 : A double slope with shelf, open-ended channel}\n\\label{WAD_test_case7}\n\nSimilar in nature to test case 5 but with an open boundary forced with a sinusoidally\nvarying ssh. This test case has been introduced to emulate a typical coastal application\nwith a tidally forced open boundary. The bathymetry and setup is identical to test case 5\nexcept the right hand end of the channel is now open and has simple ssh and barotropic\nvelocity boundary conditions applied at the open boundary. Several additional steps and\nnamelist changes are required to run this test.\n\n\\namdisplay{nam_wad_tc7}\n\nIn addition, the boundary condition files must be generated using the python script\nprovided.\n\n\\begin{verbatim}\npython ./makebdy_tc7.py\n\\end{verbatim}\n\nwill create the following boundary files for this test (assuming a suitably configured\npython environment: python2.7 with netCDF4 and numpy):\n\n\\begin{verbatim}\n  bdyssh_tc7_m12d30.nc   bdyuv_tc7_m12d30.nc\n  bdyssh_tc7_m01d01.nc   bdyuv_tc7_m01d01.nc\n  bdyssh_tc7_m01d02.nc   bdyuv_tc7_m01d02.nc\n  bdyssh_tc7_m01d03.nc   bdyuv_tc7_m01d03.nc\n\\end{verbatim}\n\nThese are sufficient for up to a three day simulation; the script is easily adapted if\nlonger periods are required.\n\n%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\\begin{sidewaysfigure}[htb] \\begin{center}\n\\includegraphics[width=0.8\\textwidth]{Fig_WAD_TC7}\n\\caption{ \\label{Fig_WAD_TC7}\nThe evolution of the sea surface height in WAD\\_TEST\\_CASE 7 from the initial state (t=0)\nover the first 24 hours of simulation. After the initial surge the solution settles into a\nsimulated tidal cycle with an amplitude of 5m. This is enough to repeatedly wet and dry\nboth shelves.}\n\n\\end{center}\\end{sidewaysfigure}\n%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n\n% ================================================================\n\n%\\bibliographystyle{wileyqj}\n%\\bibliographystyle{../../../doc/latex/NEMO/main/ametsoc.bst}\n%\\bibliography{references}\n\n\\end{document}\n", "meta": {"hexsha": "2fc36f6f6a39fbc3e91b131e0ab113f205d9fbd9", "size": 11127, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/nemo_r4.0.4/tests/WAD/MY_DOCS/WAD_doc.tex", "max_stars_repo_name": "yumengch/nemo4_pdafomi", "max_stars_repo_head_hexsha": "c25fa7092ef0ae895d0fe3accdec74254cd85c55", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-24T11:08:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-05T12:32:14.000Z", "max_issues_repo_path": "src/nemo_r4.0.4/tests/WAD/MY_DOCS/WAD_doc.tex", "max_issues_repo_name": "yumengch/nemo4_pdafomi", "max_issues_repo_head_hexsha": "c25fa7092ef0ae895d0fe3accdec74254cd85c55", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-04-24T18:56:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-24T18:56:09.000Z", "max_forks_repo_path": "src/nemo_r4.0.4/tests/WAD/MY_DOCS/WAD_doc.tex", "max_forks_repo_name": "yumengch/nemo4_pdafomi", "max_forks_repo_head_hexsha": "c25fa7092ef0ae895d0fe3accdec74254cd85c55", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-09T16:25:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-09T16:25:26.000Z", "avg_line_length": 44.686746988, "max_line_length": 103, "alphanum_fraction": 0.6813157185, "num_tokens": 2772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.32952462503647323}}
{"text": "\\documentclass[12pt,a4paper]{article}\n\\usepackage[latin1]{inputenc}\n\\usepackage[dutch]{babel}\n\\usepackage{amsmath}\n\\usepackage{amsfonts}\n\\usepackage{amssymb}\n\\usepackage{amsthm}\n\\usepackage{enumerate}\n\\usepackage{tikz}\n\\usepackage{pgfplots}\n\\usepackage{todonotes}\n\\usepackage[left=2cm,right=2cm,top=2cm,bottom=2cm]{geometry}\n\n\\author{Tom Sydney Kerckhove}\n\\title{Oefeningen Numerieke Wiskunde:\\\\ Oefenzitting 9}\n\\date{29 maart 2014}\n\n\\begin{document}\n\\maketitle\n\n\\section{Probleem 1}\n\\[\na_{0}t_1^3+b_0t_1^2+c_0t_1+d_0-a_{1}t_1^3+b_1t_1^2+c_1t_1+d_1=0\n\\]\nHet stelsel $A$ ziet er dus als volgt uit.\n\\[\nA=\n\\left(\n\\begin{array}{ccccccccccccccccc}\nt_1^3 & t_{1}^2 & t_{1} & 1 & -t_1^3 & -t_1^2 & -t_1 & -1 & 0 & 0 & 0 & 0 & \\cdots \\\\\n0 & 0 & 0 & 0 & t_2^3 & t_{2}^2 & t_{2} & 1 & -t_2^3 & -t_2^2 & -t_2 & -1 & \\cdots\\\\\n0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & t_3^3 & t_{3}^2 & t_{3} & 1 & \\cdots\\\\\n\\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\\\\n3t_1^2 & 2t_{1} & 1 & 0 & -3t_1^2 & -2t_1 & -1 & 0 & 0 & 0 & 0 & 0 & \\cdots \\\\\n0 & 0 & 0 & 0 & 3t_2^2 & 2t_{2} & 1 & 0 & -3t_2 & -2t_2 & -1 & 0 & \\cdots\\\\\n0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 3t_3^2 & 2t_{3} & 1 & 0 & \\cdots\\\\\n\\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\\\\n6t_1 & 2 & 0 & 0 & -6t_1 & -2 & 0 & 0 & 0 & 0 & 0 & 0 & \\cdots \\\\\n0 & 0 & 0 & 0 & 6t_2 & 2 & 0 & 0 & -6t_2 & -2 & 0 & 0 & \\cdots\\\\\n0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 6t_3 & 2 & 0 & 0 & \\cdots\\\\\n\\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\\\\n\\end{array}\n\\right)\n\\]\n\n\\section{Probleem 2}\nZie matlab\n\n\\section{Probleem 3}\n\\todo{evalspline}\n\n\\section{Probleem 4}\nZie matlab\n\n\\section{Probleem 5}\n\\todo{fix scripts}\n\n\\end{document}", "meta": {"hexsha": "f8cb3f531fabbddfceefef3b89df48b8ce9bb5a4", "size": 1816, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "oefenzittingen/oefenzitting_09/oplossing.tex", "max_stars_repo_name": "NorfairKing/all-you-can-carry", "max_stars_repo_head_hexsha": "93529f5a94d70af323efbe0e70ae3a7f4e036799", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2016-02-10T13:37:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-30T21:26:39.000Z", "max_issues_repo_path": "oefenzittingen/oefenzitting_09/oplossing.tex", "max_issues_repo_name": "NorfairKing/all-you-can-carry", "max_issues_repo_head_hexsha": "93529f5a94d70af323efbe0e70ae3a7f4e036799", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2015-06-11T10:06:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-17T18:27:01.000Z", "max_forks_repo_path": "oefenzittingen/oefenzitting_09/oplossing.tex", "max_forks_repo_name": "NorfairKing/all-you-can-carry", "max_forks_repo_head_hexsha": "93529f5a94d70af323efbe0e70ae3a7f4e036799", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2015-02-13T08:19:26.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-26T14:09:02.000Z", "avg_line_length": 31.3103448276, "max_line_length": 110, "alphanum_fraction": 0.5776431718, "num_tokens": 947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.32952462503647323}}
{"text": "\\section{Quantum Mechanics}\nThe state of a system is described by a ket in a Hilbert space $H$.\nEvery observable corresponds to a hermitian operator $A$ with\n$A\\ket{a}=a\\ket{a}$,\nwhere $a$ are possible outcomes of a measurement.\nThe probability of measuring $A=a$ is equal to\n$|\\braket{\\psi}{a}|^2$.\n\nThe actual \\emph{amplitude} is $\\braket{\\psi}{a}$ which is a projection onto\n$\\ket{a}$,\nwhich is a complex number.\nThe modulus squared is the probability.\n\nEvery state has magnitude 1,\nso the projection is smaller than one.\n\nHow do I calculate the probability if there is a degenerate state?\nWell you project both.\nIf $\\ket{\\psi}$ is the state of the system at measurement,\nand suppose I have a two-dimensional eigenspace with eigenvalue $a$.\nAny vector in this space has eigenvalue $a$.\nHow do I calculate the probability?\nI take $\\ket{\\psi}$ and project down onto this plane.\nThis probability is\n\\begin{align}\n    \\sum_{a\\in\\text{subspace}} |\\braket{a}{\\psi}|^2\n\\end{align}\nSo in the general case there is a sum here if the eigenvalue is degenerate.\nSometimes it's not so common,\nso if you read Griffiths you may not have noticed.\nUsual things apply,\nit's a probabilistic theory, etc.\n\n\nThere is a misunderstood point.\nSay I have a system, like my keys.\nI measure the position of the car key.\nUse your imagination.\nIt has a bunch of eigenvalues,\nthe angles my key makes with the vertical.\nI look and I find my key here.\nGood that's great.\nWhat happens if immediately after that I make another measurement?\nIf the state of the system was in a state I started out,\nthere would be a probability.\nImmediately afterwards,\nthere's no time for anything to happen.\nWhat's the point of looking?\nIt's not like I can look and extend my 5 fingers to pick it up.\nBut when I move,\nit's here and here.\nWhat's the point of making a measurement?\nThis world would be chaos.\nThere would be nothing.\nThat's not how the universe works.\n\nThe universe works like this.\nYou measure something.\nYou measure again,\nit's in the same darn place.\nThe world is not completely chaotic.\nOf course if I take too long,\nmaybe they key may be in a different place.\n\nHow do I guarantee this in my formalism?\n\nWhat happens is that you need this as well:\n\\begin{itemize}\n    \\item After a measurement $A=a$,\n        then the state $\\ket{\\psi}$ magically instantaneously becomes\n        \\begin{align}\n            \\ket{\\psi}\\to \\ket{a}\n        \\end{align}\n\\end{itemize}\nBut what happens immediately after?\nI'll have probability $1$ of measuring $a$ again.\nThis has a few names.\nIt's called the \\emph{reduction of the wave packet}.\n\nThose eigenvectors can be thought of waves,\nmaybe a bump in space.\nYou measure and you no longer have a bump in space,\njust a Fourier component for example.\nThat's the old lingo for that.\nThere's another name,\nthe \\emph{collapse} of the wave packet,\nor wave function, blah blah blah.\n\nBy the way, what happens if the eigenvalue is degenerate?\nIn principle I can go into any one of these.\nIt goes into the projection,\nthe closest one in the subspace.\n\nPeople are immensely bothered by this,\nso much that textbooks try to hide this.\nThey try to make you pay attention to the Schrodinger equation.\nBecause of this,\nif some people do this lecture,\npeople leave this out in a lecture\nbecause it's so embarrassing.\n\nHave you learnt about a theory like EM where you didn't say why.\nHold this comment.\n\nIn Newtonian mechanics, you say $F=ma$,\nparticles accelerate, you calculate forces,\nthat gives me forces, etc.\nHere,\nthe time evolution of the state of the system is given by a differential equation\nthat is very simple\n\\begin{align}\n    i\\hbar \\frac{d}{dt} \\ket{\\psi(t)} = H\\ket{\\psi(t)}\n\\end{align}\nwhere $H$ is the Hamiltonian.\nI write this without the curly $H$ so it's not a Hilbert space.\nThe time-evolution is given by this magic operator.\nThe point is,\nthere are two ways the state of the system can evolve.\nOne,\naccording to this \\emph{Schrodinger equation},\nthat's what it's called by the way.\nThat's what you do 100\\% of the time in Griffiths.\n\nSometimes though,\nSchrodinger equation stops working,\nwhen you measure.\nAnd then after that Schrodinger again.\nFor example,\nif there is a guy in a white lab coat with a beer\nand a lot of electronics,\nand he's good at messing around with systems,\nand a number pops up saying 42.\nThat's a measurement.\nYou measure the energy and got 42 Joules.\nWhen I measure immediately afterwards I get 40 Joules.\nSo he with a lab coat he can stop Schrodinger equation,\nand then it comes back.\nWhat if he doesn't have a lab coat and doesn't have a beard?\nSome graduate student?\nSo does that apply?\nYes of course,\ngrad students are people too.\nWhat if they are an undergraduate?\nYou know in your heart they are people too.\nWhat is it's a monkey.\nYou train the monkey,\nhe says 42,\nhe has no idea of what 42 means.\nDo you think will the wave function will evolve.\nSome people say no.\nWhat about Neanderthals?\nWhen did we evolve to have the ability to collapse wave functions?\nThat's ridiculous.\n\nOf course the wave function collapses.\nWhat if there's no monkey it's automatic.\n\nPeople can find out it's 42.\nWhen does the wave function collapse?\nDoes it collapse when the number pops up,\nor when the human being looks at it?\n\nSome say this stuff is this hippy dippy stuff.\nThey say\nwhat causes this change is an interaction with the measurement apparatus.\nFor a while,\nit's described not by the Hamiltonian of the system,\nbut the object and the system.\nNo.\nIt's easy to prove this is not true.\n\nBecause let's go back here.\n\nThe wave function in the future is automatically normalized.\nIf I write my state in the future,\nin terms of state in the initial time,\nthere's going to be a linear operator relating those two things.\nAs we see, this thing is a unitary operator\n\\begin{align}\n    \\ket{\\psi(t)} = U(t) \\ket{\\psi(0)}\n\\end{align}\nwhich preserves lengths and angles.\n\nMeasurement operation is not unitary.\nFor example,\nbut part orthogonal to $\\ket{a}$ got shrunk to zero,\nbut unitary just rotates things,\nso it's not unitary.\n\nIt's too facile to say my apparatus interacted with the system,\nbecause it's not unitary.\nIt's not enough.\n\n\nSay my student says it was 42 measured.\nWhen did it collapse?\nWhen the student saw it or before that?\n\nI make a measurement and I see a particular result.\nI know there was some kind of collapse.\nWe can say this measurement axiom is not true,\nbecause it poses this difficult question it is asking.\n\nBy the way,\nno body has a better answer to this.\n\nI tried my whole life to make a particular experiment\nthat depends whether the wave function\nwhen the number pops up or when the grad student sees the result.\nI also never seen a proof of either.\nIt's a hole in the literature.\n\nThere is no experiment that can explain that subtlety of when the collapse\nhappens.\nThe modern understanding is slightly better,\nbut only slightly.\nYou should do an analysis involving the system,\nthe apparatus,\nand maybe the grad student.\nThis is not only unitary evolution,\nbut also deterministic.\nI started in a state,\nand there is no way to manipulate Schrodinger equation\nto come up with a solution which says I collapse into this\nand maybe this as well.\nThink really hard about deterministic evolution\nand somehow derive the measurement axiom.\nYou just have to live with it.\nIt could make you sleep bad at night,\nbut that's just philosophy.\nI don't.\nSomething big and weird is happening there.\n\nThere's one more thing useful for quantum mechanics.\nIf you have a composite system and each one has a Hilbert space $\\mathcal{H}_1$\nand $\\mathcal{H}_2$,\nthe composite system is going to have a Hilbert space\n$\\mathcal{H}_1\\otimes\\mathcal{H}_2$.\nThere's a lot of juice hidden here.\n\nSay that $\\mathcal{H}_1$ is 2-dimensional,\nand $\\mathcal{H}_2$ is 2-dimensional.\nWhat is the composite system?\n4 dimensions.\nWhat if I had a third Hilbert space? 8.\nSo exponential growth.\nWith just 100, you have $2^{100}$.\nIt can be represented as a matrix,\nlike in kindergarten,\nbut how big is the matrix?\nCan you write down the matrix?\nCan the computer calculate?\nIf you transfer planet Earth,\ntake the galaxy,\nuniverse,\nturn it into disk space,\nyou still cannot write the Hamiltonian with 100 systems.\nThis exponential growth is a bummer,\nwell not really a bummer,\nbecause then you'd be able to diagonalize everything\nand I would lose my job.\n\nThat's my summary of QM,\nit's really upstart,\nbut we're going to take this and apply to many cases.\nIt's very upstart,\nbut we've done all the work already.\n\nWe've done all the numbers already,\nyou know how to transform things into concrete equations,\nbecause we spent two weeks.\nStrictly speaking, we're actually done.\nGo home class is over.\n\n\\begin{question}\n    You call a hermitian operator measurable.\n    Is that measurable the same as probability?\n\\end{question}\nNo, measurement in the physics sense.\nAnything you can measure.\nGo to Radio Shack, get a ruler,\nthat's a measurable device.\n\nMeasure is physicist lingo.\n\nWe have to distinguish things like momentum and energy for which there are\ndevices,\nfrom things like kets.\nI cannot by a ket-meter that tells me what the ket is.\nThere will never be such a thing.\nThat is not an observable.\nThat's the end of QM.\nBut before examples,\nI want to make trivial generic comments.\n\n\n\\begin{itemize}\n    \\item An overall phase on $\\ket{\\psi}$ is unphysical.\n        Look at my system and say this is $\\ket{\\psi}$,\n        but my friends says no it's $e^{i\\alpha}\\ket{\\psi}$,\n        it's the same thing.\n        More than that.\n        Suppose I start with a state and evolve,\n        but my friend has a space,\n        in the end the phase doesn't matter.\n        If you want to be nitty-picky,\n        you should say it's not that states are represented by kets.\n        It's not even represented by kets measured 1.\n        It's represented by rays.\n        You can take a vector,\n        you can multiply by any number,\n        including complex numbers.\n        The whole set represents this thing.\n        When I use the wave function to calculate a probability,\n        we're going to get the same result.\n    \\item The Schrodinger equation is linear.\n        If I have two solutions of the Schrodinger equation,\n        I'm going to get another solution.\n        It's like the Maxwell equations.\n\\end{itemize}\nShould I stop to tell Schrodinger stories?\nHe was a great scientist,\nbut he fun part is his personal life of course.\nHe was Australian,\nand compared to other people who invented QM\nwho were like 23,\nhe was in his 30s,\nreceding hairline already.\nHe was a \nHe didn't get along with the Nazis in the 30s.\nHe was not Jewish,\njust cut his pie.\nHe became very uncomfortable,\nand then German invaded Austria.\nHe could be killed.\nHe wrote a letter reneging his position with the Nazis,\nHe regretted,\nso he decided to leave.\nHe needed visa, a job.\nHe had a wife and kids.\nAnd the lover.\nAnd the lover's husband.\nHe has a lot.\nIt was complicated.\nA few years earlier he had written that equation.\nSo he got invitations for jobs.\nSo he went to Oxford.\nThe people look at the situation,\nsay don't think so.\nHe wants to leave with his kids, wife, lover, lover's husband.\nThen at Princeton,\nthere is the Institute of Advanced Studies,\nwhen they hire Einstein, Godel, von Neumann, etc.\nSo he goes the New Jersey.\nPeople at the Institute are given houses,\nIf you get hired there they give you Einstein's house.\nIt's funny,\nyou have to buy it from them and then you have to sell when you leave.\nEinstein's house is a dump.\nNice museum, but it's not nice to live in because it doesn't have all the modern\namenities.\nCan you get a job for the husband of the lover?\nHe was a mathematician.\nPeople in New Jersey were not happy with that.\n\nThere was another institute of advanced studies at the time in Dublin headed by\na Catholic priest.\nYou say there's no chance.\nTurns out he went there,\ndon't know how many people.\nThe reality is very different from the perception by majority of Americans.\nEverything was fine.\nHe got job, visa, for his wife, kids, husband of the lover,\nhusband had someone else too.\nEveryone came to Ireland and everyone was happy.\nThe only unhappy thing was Schrodinger really disliked quantum mechanics.\nHe didn't like collapse axiom.\nAfter trying to fix QM,\nhe gave up and tried to do other things.\nSome people say,\nespecially physicists,\nhe was kind of one of the first ones to think about DNA,\nand how genetic information can be stored in molecules\nbefore DNA was discovered.\nI heard,\nhis little book \\textit{What's Life}\nwas influential for the people who discovered DNA.\nBy the time he wrote this book,\neverything was either known to be right or known to be wrong.\nWatson and Crick weren't even biologists,\nthey where X-Ray physicists.\n\n\\begin{question}\n    Do you know Schrodinger?\n    Or other famous people?\n\\end{question}\nSchrodinger died before I was born.\nI'm not that old!\nHe's not one of the elder kings of QM.\nI met famous people,\nbut not physicists.\nDoes that count?\nThere are physicists famous among physicists.\nDoes that count?\nAt this stage,\nyou don't know the very old people who invented QM.\nI know Heisenberg's son.\nI taught QM to Neils Bohr's great grandson,\nhe was a student here at Maryland.\nHow can you go into physics?\nHis great grandfather won a Nobel prize,\nhis grandfather won a Nobel prize.\nHis father was a slacker.\nWhy would you do this to yourself?\n\nI remember these people of that generation barely walking.\nOur lives did not overlap on this planet.\nI met Hans Bethe.\nI met some Los Alamos people,\nbut they were very old.\nAfter the war,\nthere were a bunch of them,\nvery old.\nI met some Rock stars,\ndoes that count?\n\nAfter telling you those things\nyou knew forever anyway,\nwe can talk about the no cloning theorem from linearity.\nBut, that's for Friday.\n\nCan I write a copy of something on a Xerox?\nOf course I can.\nWhat I'm going to argue is that I cannot do this with quantum sates.\nSay that I start with a system $\\ket{\\psi}$,\nwhich represents blank paper.\nNow I'm going to put together with another system,\nwhich is like blank paper.\nActually, let's make this more interesting.\nSuppose $\\ket{\\psi}$ is money.\nI want to copy it.\nWhat's the Hilbert space of the whole system together?\nSo my state is $\\ket{\\psi}\\otimes\\ket{\\phi}$\nwhere $\\ket{\\phi}$ is like blank paper.\nI'm going to evolve this,\nand arrange my Hamiltonian such that my system is going to be money and money\nlike $\\ket{\\psi}\\otimes\\ket{\\psi}$.\nThat's how you make money.\nIf you do this,\nyou've got it.\nMake a good xerox machine,\nyou can do that.\nNot possible.\nImagine you start with a linear superposition\n\\begin{align}\n    \\frac{\\ket{\\psi_1} + \\ket{\\psi_2}}{\\sqrt{2}}\n    \\otimes\\ket{\\phi}\n    \\to\n    \\frac{\\ket{\\psi_1}\\otimes\\ket{\\psi_1} + \\ket{\\psi_2}\\otimes\n    \\ket{\\psi_2}}{\\sqrt{2}}\n\\end{align}\nBut that's not what I want,\nI want\n\\begin{align}\n    \\frac{\\ket{\\psi_1} + \\ket{\\psi_2}}{\\sqrt{2}}\n    \\otimes\\ket{\\phi}\n    \\to\n    \\frac{\\ket{\\psi_1} + \\ket{\\psi_2}}{\\sqrt{2}}\n    \\otimes\n    \\frac{\\ket{\\psi_1} + \\ket{\\psi_2}}{\\sqrt{2}}\n\\end{align}\nand you can see this is not the same.\nYou can see there a bunch of cross-terms like\n$\\ket{\\psi_1}\\otimes\\ket{\\psi_2}$.\nEven if I can make copies of one-dollar bills,\nI can only print one-dollar bills,\nbut it's not a copier.\nThis little result here is called the no-cloning theorem.\nIt's a completely trivial result.\nWe don't give any importance to this until Zurek\nand people found it interesting.\nEven if this is interesting to prove,\npeople forget sometimes.\n\nIf I tried to send a secret to my friend,\nsomeone can spy on us by intercepting it make a copy.\nSuppose I encode that information in a quantum state.\nIf someone spies on us,\nthey can make a copy,\nbut the most they can do is kill the system.\nNo one can make a copy of a quantum system and run away with it.\nQM is a good way to transfer secrets.\nWhen you to build a quantum computer,\na normal computer depends on copying,\nbut a quantum computer can't do that\nand that's a bummer.\nPeople think it's really cool,\nso I want to mention this.\n", "meta": {"hexsha": "3fd1013ebf67fd71a4d48f57a7dad8f2218a85eb", "size": 16086, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "phys612/lecture6.tex", "max_stars_repo_name": "ehua7365/umdphysnotes", "max_stars_repo_head_hexsha": "00e4e2b6aba3d03baaec5caa36903e5135b014de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-11T12:53:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T12:53:46.000Z", "max_issues_repo_path": "phys612/lecture6.tex", "max_issues_repo_name": "ehua7365/umdphysnotes", "max_issues_repo_head_hexsha": "00e4e2b6aba3d03baaec5caa36903e5135b014de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phys612/lecture6.tex", "max_forks_repo_name": "ehua7365/umdphysnotes", "max_forks_repo_head_hexsha": "00e4e2b6aba3d03baaec5caa36903e5135b014de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2364729459, "max_line_length": 81, "alphanum_fraction": 0.752206888, "num_tokens": 3972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.3292149283724471}}
{"text": "\\section{Statistical Analysis through RAVEN}\n\\label{sec:SAraven}\nIn order to perform a complete analysis of a system under uncertainties,\nit is crucial to be able to compute all the statistical moments of one or even multiple\nFOMs. In addition, it is essential to identify the correlation\namong different FOMs toward a specific input space.\n\nRAVEN is able to compute the most important statistical moments:\nsuch as:\n\\begin{enumerate}\n  \\item \\textit{Expected Value}\n  \\item \\textit{Standard Deviation}\n  \\item \\textit{Variance}\n  \\item \\textit{variationCoefficient}\n  \\item \\textit{Skewness}\n  \\item \\textit{Kurtosis}\n  \\item \\textit{Median}\n  \\item \\textit{Percentile}.\n\\end{enumerate}\nIn addition, RAVEN fully supports the computation of all of the statistical moments defined to\n``measure'' the correlation among variables/parameters/FOMs:\n\\begin{enumerate}\n  \\item \\textit{Covariance matrix}\n  \\item \\textit{Normalized Sensitivity matrix}\n  \\item \\textit{Variance Dependent Sensitivity matrix}\n  \\item \\textit{Sensitivity matrix}\n  \\item \\textit{Pearson matrix}.\n\\end{enumerate}\nThe goals of this section is to show how to:\n \\begin{enumerate}\n   \\item Set up a sampling strategy to perform a final statistical analysis\n   perturbing a driven code\n   \\item Compute all the statistical moments and correlation/covariance\n   metrics.\n\\end{enumerate}\nIn order to accomplish these tasks, the following RAVEN \\textbf{Entities} (XML blocks in the input files) need to be defined:\n\\begin{enumerate}\n   \\item \\textbf{\\textit{RunInfo}}:\n     \\xmlExample{framework/user_guide/StatisticalAnalysis/statisticalAnalysis.xml}{RunInfo}\n   As shown in the other examples, the \\textit{RunInfo} \\textbf{Entity} is intended  to set up the desired analysis. The number of steps specified in (\\xmlNode{Sequence}) are sequentially run, two steps in this specific case, using the number of processors assigned in (\\xmlNode{batchSize}).\n   \\\\In the first step, the original physical model is sampled. The obtained results are  analyzed with the Statistical Post-Processor.\n   \\item \\textbf{\\textit{Models}}:\n     \\xmlExample{framework/user_guide/StatisticalAnalysis/statisticalAnalysis.xml}{Models}\n The goal of this example is to show how the\n principal statistical FOMs can be computed through RAVEN.\n \\\\We use an External model and specify a Post-Processor model (BasicStatistics). The post-process step is performed on all the output FOMs used in this example ($r and t$).\n   \\item \\textbf{\\textit{Distributions}}:\n     \\xmlExample{framework/user_guide/StatisticalAnalysis/statisticalAnalysis.xml}{Distributions}\n  In the Distributions XML section, the stochastic model for the\n  uncertainties are reported. In this case 2 distributions are defined:\n  \\begin{itemize}\n    \\item $vel\\_dist \\sim \\mathbb{N}(30,5)$, used to model the uncertainties\n    associated with  the \\textit{velocity};\n    \\item  $angle\\_dist \\sim \\mathbb{U}(5,85)$,  used to\n    model the uncertainties associated with the \\textit{angle}.\n  \\end{itemize}\n   \\item \\textbf{\\textit{Samplers}}:\n     \\xmlExample{framework/user_guide/StatisticalAnalysis/statisticalAnalysis.xml}{Samplers}\n  In order to obtain the data-set on which the data mining algorithms are going to be applied, a \\textit{MonteCarlo} sampling approach is employed here.\n   \\item \\textbf{\\textit{DataObjects}}:\n     \\xmlExample{framework/user_guide/StatisticalAnalysis/statisticalAnalysis.xml}{DataObjects}\n  In this block, three \\textit{DataObjects} are defined:\n  1) PointSet named ``samples'' used to collect the final outcomes of\n  the code,\n  2) PointSet named ``dummyIN'' used as a placeholder for the \\textit{Multirun} step,\n  3) HistorySet named ``histories'' in which the full time responses of the\n  variables $x,y,t$ are going to be stored.\n\n   \\item \\textbf{\\textit{Steps}}:\n     \\xmlExample{framework/user_guide/StatisticalAnalysis/statisticalAnalysis.xml}{Steps}\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n   Finally, all the previously defined \\textbf{Entities} can be combined in\n   the \\xmlNode{Steps} block. As inferable,\n   2 \\xmlNode{Steps} have been inputted:\n   \\begin{itemize}\n     \\item \\xmlNode{MultiRun} named ``sampleMC'', used to run the\n     multiple\n     instances of the driven code and\n     collect the outputs in the two \\textit{DataObjects}. As it can be\n     seen, the \\xmlNode{Sampler} is inputted to communicate to the\n     \\textit{Step} that the driven code needs to\n     be perturbed through the MonteCarlo sampling strategy.\n     \\item \\xmlNode{PostProcess} named ``statisticalAnalysisMC'', used\n     compute all the statistical moments and FOMs based on the\n     data obtained through the sampling strategy. As it can be noticed,\n     the \\xmlNode{Output} of the ``sampleMC'' \\textit{Step} is the\n     \\xmlNode{Input} of the ``statisticalAnalysisMC''  \\textit{Step}.\n   \\end{itemize}\n\\end{enumerate}\n\nTables \\ref{ScalarMoments}-\\ref{SensitivityComputed} show all the results of the \\textit{PostProcess}\nstep.\n\n\n\\begin{table}[h!]\n\\centering\n\\caption{Computed Moments and Cumulants}\n\\label{ScalarMoments}\n\\begin{tabular}{|c|c|c|}\n\\hline\n{\\ul \\textit{\\textbf{Computed Quantities}}} & \\textbf{r} & \\textbf{t} \\\\ \\hline\n\\textit{expected value}                     & 65.88   & 3.94   \\\\ \\hline\n\\textit{median}                             & 61.74   & 4.12   \\\\ \\hline\n\\textit{variance}                           & 1022.01 & 3.53   \\\\ \\hline\n\\textit{sigma}                              & 31.97   & 1.89  \\\\ \\hline\n\\textit{variation coefficient}              & 0.48    & 0.48   \\\\ \\hline\n\\textit{skewness}                           & 0.55    & -0.03  \\\\ \\hline\n\\textit{kurtosis}                           & -0.01   & -0.96  \\\\ \\hline\n\\textit{percentile 5\\%}                     & 20.21   & 0.85   \\\\ \\hline\n\\textit{percentile 95\\%}                    & 122.83  & 6.90   \\\\ \\hline\n\\end{tabular}\n\\end{table}\n\\begin{table}[h!]\n\\centering\n\\caption{Covariance matrix.}\n\\label{covarianceComputed}\n\\begin{tabular}{|c|c|c|}\n\\hline\n{\\ul \\textit{\\textbf{Covariance}}} & \\textbf{r} & \\textbf{t} \\\\ \\hline\n\\textit{velocity}                     & 95.36   & 3.29   \\\\ \\hline\n\\textit{angle}                        & 25.29   & 40.42   \\\\ \\hline\n\\end{tabular}\n\\end{table}\n\\begin{table}[h!]\n\\centering\n\\caption{Correlation matrix}\n\\label{pearsonComputed}\n\\begin{tabular}{|c|c|c|}\n\\hline\n{\\ul \\textit{\\textbf{Correlation}}} & \\textbf{r} & \\textbf{t} \\\\ \\hline\n\\textit{velocity}                     & 0.61   & 0.36   \\\\ \\hline\n\\textit{angle}                        & 0.03   & 0.92   \\\\ \\hline\n\\end{tabular}\n\\end{table}\n\\begin{table}[h!]\n\\centering\n\\caption{Variance Dependent Sensitivity matrix}\n\\label{VarDepSensitivityComputed}\n\\begin{tabular}{|c|c|c|}\n\\hline\n{\\ul \\textit{\\textbf{Variance Sensitivity}}} & \\textbf{r} & \\textbf{t} \\\\ \\hline\n\\textit{velocity}                     & -1.69   & 0.08   \\\\ \\hline\n\\textit{angle}                        & -3.31   & 0.07   \\\\ \\hline\n\\end{tabular}\n\\end{table}\n\\begin{table}[h!]\n\\centering\n\\caption{Sensitivity matrix}\n\\label{SensitivityComputed}\n\\begin{tabular}{|c|c|c|}\n\\hline\n{\\ul \\textit{\\textbf{Sensitivity (I/O)}}} & \\textbf{r} & \\textbf{t} \\\\ \\hline\n\\textit{velocity}                     & 3.95   & 0.12   \\\\ \\hline\n\\textit{angle}                        & 0.01   & 0.07   \\\\ \\hline\n\\end{tabular}\n\\end{table}\n\n", "meta": {"hexsha": "5d03accd98ee554c6fa3228beedd62f8da9b8306", "size": 7368, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/user_guide/statisticalAnalysisExample.tex", "max_stars_repo_name": "rinelson456/raven", "max_stars_repo_head_hexsha": "1114246136a2f72969e75b5e99a11b35500d4eef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 159, "max_stars_repo_stars_event_min_datetime": "2017-03-24T21:07:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T13:44:40.000Z", "max_issues_repo_path": "doc/user_guide/statisticalAnalysisExample.tex", "max_issues_repo_name": "rinelson456/raven", "max_issues_repo_head_hexsha": "1114246136a2f72969e75b5e99a11b35500d4eef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1667, "max_issues_repo_issues_event_min_datetime": "2017-03-27T14:41:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:50:06.000Z", "max_forks_repo_path": "doc/user_guide/statisticalAnalysisExample.tex", "max_forks_repo_name": "rinelson456/raven", "max_forks_repo_head_hexsha": "1114246136a2f72969e75b5e99a11b35500d4eef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 95, "max_forks_repo_forks_event_min_datetime": "2017-03-24T21:05:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T17:30:22.000Z", "avg_line_length": 46.05, "max_line_length": 291, "alphanum_fraction": 0.6754885993, "num_tokens": 2154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.5, "lm_q1q2_score": 0.32920875698349983}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\marginpar{Monday\\\\ 2021-12-20}\n\n\\begin{extracontent}\n    What is the capacitance of a cylinder with a wire?\n    %\n    \\begin{align}\n    C = \\frac{2 \\pi \\epsilon  L}{\\log R _{\\text{cylinder}} / R _{\\text{wire}}}\n    \\,.\n    \\end{align}\n\\end{extracontent}\n\nLast time we were looking at some particle detectors. \nWe are looking at a detector with a cylindrical shape --- a wire within a cylinder. \n\nWe saw that for a \\(\\sim \\SI{2}{MeV}\\) particle there will be roughly 200 emitted electrons. \n\nThe drift time for a \\SI{1}{cm} detector will roughly be \\SI{200}{\\nano\\second}, \nsince the drift time is roughly \\SI{5}{cm/\\micro\\second}. \n\nThis means that the shape of the pulse, after an RC high-pass filter, is \n%\n\\begin{align}\n\\overline{V}(t) = \\overline{R} \\overline{C} \\dv{V(t)}{t} \\approx \\overline{R} \\overline{C}\n\\frac{ \\delta V}{T_D} = \\overline{R}\\frac{\\overline{C}}{C} \\frac{ \\delta q}{T_D}\n\\,.\n\\end{align}\n\nThe current will roughly be \\(\\delta q / T_D \\approx \\SI{0.16}{nA}\\).\nThe change in tension is roughly \\(\\Delta V \\sim I R \\approx \\SI{8}{nV}\\). \n\nSo, we need an amplification mechanism. \n\nThe anodic wire needs to be very thin, so that we have a large electric field, \nwhich means that we get amplification by the emission of secondary electrons. \nThis gain can be a factor \\num{e5}! \nThis means we get a charge \\(\\delta q \\approx N _{\\text{pair}} e \\times \\text{gain}\\). \n\nWe get \\(\\Delta V \\sim \\SI{0.8}{mV}\\); with better systems we typically get millivolt currents. \n\nWe should also aim to reduce the capacitance of the detector! \n\nAt low values for the high voltage we are in the ionization regime; this means that we \nsee exactly the number of charges produced by the particle. This is the ionization regime. \n\\(\\delta q (V) = \\text{constant}\\). \n\nAt higher voltages, we will be getting a certain gain: this is the proportional regime. \n\\(\\delta q(V) = \\alpha \\delta q\\).\n\nAt even higher voltages, we will get a nonlinear profile, with saturation. \nThis is the limited proportional regime.\n\nAt even higher voltages, we fully saturate: this is the Geiger-Muller regime. \nHere we do not have any information about the particle, we just know that \nsomething has passed through. \n\nThis all depends on the charge of the particle: for \\(\\alpha \\) particle the \\(\\delta q\\) is \nalways \\(Z^2 = 4\\) times higher. \n\nWe can use many of these gas detectors to figure out where a particle passed through. \n\nIf this is the case, we can also get trajectory information! \nThe delay between the arrival time of the particle ionization in different wires tells us about\nhow close to the center of each of them it passed. \nIf we have a star, trigger that's even better! \n\nThis kind of thing is used in LHC. \n\nAn alternative is to have many HV wires in the same chamber. \nThis is called a \\emph{wire chamber}. \n\nThe spatial resolution can be computed as \\(\\sigma _x \\approx v _{\\text{drift}} \\sigma _t\\), \nso if we have millisecond timing we can get a few hundreds of microns. \n\nAnother component is a \\emph{quencher}. \nSome electrons and ions produced might recombine, producing UV photons. \nThose can then ionize the gas again, in a place which is unrelated. \nSo, we need to quench these UV photons (absorb them) so that they do not mess up \nour measurement.\n\nIf we also have a magnetic field, the trajectory of the particle passing through \nwill be bent; this allows us to measure the momentum and charge of the particle, but\nit will also curve the trajectories of the electrons. \n\nWhat to do when the interaction cross-section is very low?\nWe can increase the density of the gas, or even make it a liquid.\n\nThose can be for example liquid Argon or liquid Xenon Time Projection Chambers.\n\n\\subsection{Scintillators}\n\nA fraction of the energy from a particle is emitted as light. \nAtoms are ionized and then recombine; the UV light they emit thus is \ncalled \\emph{scintillation light}. \n\nIf the total energy lost is \\(\\Delta E\\), and \\(W\\) \nis the energy required to produce a scintillation photon (\\(W \\approx \\SI{100}{eV}\\)). \n\nFor a \\SI{2}{MeV} particle, we get about 20000 photons. \nThe wavelength of this light depends on the energy states of the material. \nTypically the emission of these happens within a few nanoseconds. \n\nWe need the material to be transparent to the scintillation photons, \nbut we need to contain it within a reflective material so that the photons are not\ngoing everywhere. \n\nThe mechanism for the absorption of these visible or UV photons will be the photoelectric effect. \n\nThe quantum efficiency of the detector describes the fraction of the photons which are detected. \n\nWe need to give energy to the electron emitted by the photon!\nIt will have low, order-\\SI{}{eV} energy. \nThe way this is typically done is through a series of dynodes. \nWe connect the HV supply to a series of resistors, and have a uniformly decreasing \nvoltage between the dynodes. \nThe gain will depend on the number of secondary electrons produced by the dynode chain\nper incident electron, which is denoted as \\(\\alpha \\). \n\nThe dependence is roughly a powerlaw as a function of the HV. \nThe system is roughly saturated when the current due to the secondary electrons\nroughly equals the HV/\\(R\\) current. \n\nThese are \\emph{photomultipliers}. \n\nWe will have a certain efficiency for our collection \\(\\epsilon _{\\text{coll}}\\), as well as \na quantum efficiency \\(\\epsilon _q\\).\n\nThe signal will be \n%\n\\begin{align}\nN_\\gamma \\epsilon _q \\epsilon _{\\text{coll}} \\times \\text{gain}\n\\,.\n\\end{align}\n\nTypical numbers are about \\(N_ \\gamma \\approx \\num{2e4}\\), and both efficiencies at \\SI{20}{\\percent}. \n\nWith this, we get about \\(N = 800\\) photoelectrons. \n\nThe time required for the detection is a few nanoseconds for the emission, \na few nanoseconds for the propagation, and a further few nanoseconds for \nthe collection by the photomultiplier.\nIn the end, the current will be roughly \\(I \\approx eN / (\\SI{100}{ns})\\); \n\nWith a \\SI{50}{\\ohm} resistor, this means a voltage of \\SI{70}{nV} times the gain. \n\nIn order to get to the millivolt regime, we need a gain on the order of a million. \nSo, if each dynode allows for a doubling of the electrons we need about 20. \n\nWith these kinds of detectors we can do nuclear spectroscopy. \n\n\\end{document}\n", "meta": {"hexsha": "e16c32181dc384f28d85bcef64911b83fe803c58", "size": 6305, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "phd_courses/experimental_high_energy_astroparticle/dec20.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "phd_courses/experimental_high_energy_astroparticle/dec20.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phd_courses/experimental_high_energy_astroparticle/dec20.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 40.9415584416, "max_line_length": 103, "alphanum_fraction": 0.7394131642, "num_tokens": 1672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5350984434543457, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.32913255407431863}}
{"text": "\\documentclass{article}\n\\usepackage{hyperref}\n\\usepackage[USenglish]{babel}\n%\\usepackage{csquotes}\n%\\usepackage{dirtytalk}\n%https://perso.imt-mines-albi.fr/~gaborit/latex/latex-in-french.html\n%\\usepackage[english,francais]{babel}\n%\\usepackage[english,french]{babel}\n\n\n%https://tex.stackexchange.com/questions/248788/the-very-basics-of-french-accents\n%\\documentclass[12pt]{amsart}\n\n\\usepackage[utf8]{inputenc}\n\n%entiers sets https://texblog.org/2007/08/27/number-sets-prime-natural-integer-rational-real-and-complex-in-latex/\n%\\usepackage{amsfonts} \n% or \n\\usepackage{amssymb}\n\n%Majuscules accentuees https://www.xm1math.net/doculatex/caracteres_speciaux.html\n\\usepackage{eurosym}\n\\usepackage{systeme}\n\\usepackage{enumerate}\n\n\\usepackage{physics}\n\n%https://tex.stackexchange.com/questions/304155/%C2%B1-symbol-in-text\n\\usepackage[\n  separate-uncertainty = true,\n  multi-part-units = repeat\n]{siunitx}\n\n%numerotation https://www.xm1math.net/doculatex/structure.html\n\\renewcommand{\\thesubsection}{\\Roman{subsection}}\n\n%\\title{\\textbf{PROPERTIES OF EXPANDING UNIVERSES.}}\n\n\n%https://stackoverflow.com/questions/4262294/remove-default-date-in-latex-article\n\\date{1st february 1966}\n\n\\begin{document}\n\n\n%https://perso.imt-mines-albi.fr/~gaborit/latex/latex-in-french.html\n%\\renewcommand{\\contentsname}{Sommaire}\n\n\n%https://tex.stackexchange.com/questions/59460/custom-title-page-in-report-or-book-class\n%\\textcolor{other}{TRINITY HALL}\n%differential https://tex.stackexchange.com/questions/225523/how-to-write-partial-differential-equation-ex-dq-dt-ds-dt-with-real-partial-d\n\n\n\n\\section{}\nthe field-equations is admissible, but in the direct-particle\n\ninteraction theory only those solutios of the field-equations\n\nare admissible that satisfy the additional requirement :\n \n%physics\n$M_0(x) = \\sum_{}^{} M^{(a)}(x) =  \\sum_{}^{}  \\int_{}^{}  G*(x,a)  \\,da $\n\n\n$ = \\frac{1}{2}  \\cdot \\sum_{}^{}  \\int_{}^{}  G_{ret.}(x,a)  \\,da + \\frac{1}{2}  \\cdot \\sum_{}^{}  \\int_{}^{}  G_{adv.}(x,a)  \\,da$\n\n%= \\[ \\sum_{}^{} G*(x,a) \\cdot \\it{d}a \\]   $\n\n\n\nThis requirement is highly restrictive ; it will be shown\n\nthat it is not satisfied for the cosmological solutions of\n\nthe Einstein field-equations, and it appears that it cannot\n\nbe satisfied for any models of the universe that either\n\ncontain an infinite amount of matter or undergo infinite\n\nexpansion.\n\n\n\n\n\n\n\\section{}The difficulty is similar to that occurring in\n\n  Newtonian theory when it is recognized that the universe\n\n  might be infinite.\n\n  \\section{}\n  The Newtonian potential $\\phi$ obeys the equation :\n\n\n%latex complex conjugate https://tex.stackexchange.com/questions/304155/%C2%B1-symbol-in-text\n\n\\footnote{Written by Peter MOUEZA}\n\\end{document}\n", "meta": {"hexsha": "052819f587c5bbe5c52bb8a41bb3157db6784dda", "size": 2703, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "PAGES/p018/p018.tex", "max_stars_repo_name": "moueza/these-hawking-stephen-pdf-numerisation-project", "max_stars_repo_head_hexsha": "1c5b64137e77a6b7797e6872081d3c0e026b912b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PAGES/p018/p018.tex", "max_issues_repo_name": "moueza/these-hawking-stephen-pdf-numerisation-project", "max_issues_repo_head_hexsha": "1c5b64137e77a6b7797e6872081d3c0e026b912b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2021-03-12T19:38:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-15T02:08:47.000Z", "max_forks_repo_path": "PAGES/p018/p018.tex", "max_forks_repo_name": "moueza/thesis-hawking-stephen-pdf-numerization-project", "max_forks_repo_head_hexsha": "1c5b64137e77a6b7797e6872081d3c0e026b912b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9903846154, "max_line_length": 138, "alphanum_fraction": 0.7447280799, "num_tokens": 811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3291325525050998}}
{"text": "\\chapter{Summary and Outlook}\nFor the operational phase of \\gls{flute}, a stable electron energy enabling stable \\gls{thz} energies will be vital to perform scientific experiments. At the start of the thesis, the stability of the electron gun was unsatisfactory. As the main source of the instability, the cooling system of the electron gun's body was identified.\n\nThis thesis shows that with a control system that interacts with the low power input signal of the klystron, it is possible to improve the stability by creating a closed-loop feedback system using readouts from the \\gls{epics} control system as sensors and a controllable \\gls{rf} attenuator in the signal path as actuator. The system transfer function (plant) between the attenuator and the power in the electron gun cavity shows $PT_2$ behavior, so control with a \\gls{pid} controller is possible and its positive effects on the stability are shown.\n\nWith the controller it is possible to achieve the goal of reducing the variations in the cavity \\gls{rf} power significantly from $\\op{\\%STD}=\\SI{0.11559}{\\percent}$ to $\\op{\\%STD}=\\SI{0.0599}{\\percent}$, which is equals an improvement by about a factor of two.\n\nHowever the studies here also show the limitations of a traditional linear control system. The controller should be designed with a fast response time and sufficient integral gain to reject disturbances quickly. This however leads to small safety margins in the gain and phase response, which makes it likely for the control system to become unstable if system parameters change slightly. Also, the parameterization of the necessary measurement filter is a trade-off between stability of the control system and measurement noise rejection. The control system could be further optimized by switching to a totally different controller architecture, such as model predictive control, which exploits the identified plant transfer function but determines the output through an optimization process.\n\nAt the moment of writing, \\gls{flute} is shut down. With \\gls{flute} operational again, measurements of the electron energies before and after the \\gls{linac} can be performed. The method currently used is based on the electron bunch, which is steered with an electromagnet by the Lorentz force (see \\autoref{eq:fl}). By adjusting the electromagnet's coil current in such a way that the electron beam hits a camera screen in the center, the electron energy can be calculated from the coil current. With this destructive and slow process it will be possible to show how much the stabilization of the cavity \\gls{rf} power actually improves the energies of the accelerated electrons and if the approach using the Faraday cup is an improvement over the cavity \\gls{rf} power solution.\n\nIn the near future, both the electron gun and the klystron are to be upgraded to new versions. Switching to another gun and/or a different \\gls{rf} system could lead to an entirely different behavior of the whole system, but the techniques described in this thesis are universally applicable and the control system can easily be modified for usage with different components.", "meta": {"hexsha": "25e28f8192b7f6459454d619fdb5574ba36d8730", "size": 3133, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chap/SummaryAndOutlook/summary-and-outlook.tex", "max_stars_repo_name": "youcann/thesisvorlage-latex", "max_stars_repo_head_hexsha": "34e58b00e6df11f79a38a3e6c394892bed687be2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chap/SummaryAndOutlook/summary-and-outlook.tex", "max_issues_repo_name": "youcann/thesisvorlage-latex", "max_issues_repo_head_hexsha": "34e58b00e6df11f79a38a3e6c394892bed687be2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chap/SummaryAndOutlook/summary-and-outlook.tex", "max_forks_repo_name": "youcann/thesisvorlage-latex", "max_forks_repo_head_hexsha": "34e58b00e6df11f79a38a3e6c394892bed687be2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 261.0833333333, "max_line_length": 793, "alphanum_fraction": 0.8075327162, "num_tokens": 655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.32913254495395944}}
{"text": "\\chapter{{\\tt ETree}: Elimination and Front Trees}\n\\label{chapter:ETree}\n\\par\nThe {\\tt ETree} object is used to model an elimination tree or a\nfront tree for a sparse factorization with symmetric structure.\nThe tree is defined over a set of vertices in a graph --- the graph\ncan be unit weight or non-unit weight.\nA ``node'' in the tree can be a single vertex (in the context of \nan elimination tree) or a group of vertices (as for a front tree).\n\\par\nThe tree information is stored as a {\\tt Tree} object.\nIn addition there are three {\\tt IV} objects.\nOne stores the total size of the nodes in the fronts,\none stores the size of the boundaries of the fronts,\nand one stores the map from the vertices to the fronts.\n\\par\nThere is a great deal of functionality embodied into the {\\tt ETree} \nobject.\nGiven an elimination tree or a front tree, one can extract the\npermutation vectors (for the fronts or the vertices), extract a\nmultisector based on several criteria, compress the front tree in\nseveral ways, justify the tree (order children of a node in\nmeaningful ways), evaluate metric vectors on the tree (heights,\ndepths, subtree accumulators).\n\\par\nThe front tree we obtain from a low-fill matrix ordering is usually\nnot the front tree that drives the factorization.\nWe provide three methods that transform the former into the latter.\nOne method merges the fronts together in a\nway that adds logical zeros to their structure.\nOne method splits large fronts into smaller fronts.\nOne method combines these two functionalities.\n\n", "meta": {"hexsha": "e45f082ed8b835c06664eb0b66675395a85d4c04", "size": 1529, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ccx_prool/SPOOLES.2.2/ETree/doc/intro.tex", "max_stars_repo_name": "alleindrach/calculix-desktop", "max_stars_repo_head_hexsha": "2cb2c434b536eb668ff88bdf82538d22f4f0f711", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ccx_prool/SPOOLES.2.2/ETree/doc/intro.tex", "max_issues_repo_name": "alleindrach/calculix-desktop", "max_issues_repo_head_hexsha": "2cb2c434b536eb668ff88bdf82538d22f4f0f711", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-09-21T17:03:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-25T16:08:31.000Z", "max_forks_repo_path": "ccx_prool/SPOOLES.2.2/ETree/doc/intro.tex", "max_forks_repo_name": "alleindrach/calculix-desktop", "max_forks_repo_head_hexsha": "2cb2c434b536eb668ff88bdf82538d22f4f0f711", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-08-29T18:41:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-29T18:41:28.000Z", "avg_line_length": 44.9705882353, "max_line_length": 69, "alphanum_fraction": 0.7828646174, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.32913254495395944}}
{"text": "\\section{Matrix-free multigrid}\n  \\label{section:applications:matrix-free-multigrid}\n\n\\chapterDescription\n  {\n    1--2 days.\n  }\n  {\n    Chapter \\ref{chapter:quickstart}. It is advantageous if the reader has\n    studied the implementation of the heat equation before.\n  }\n\nIn this section, we sketch how to solve the convection-diffusion equation\n\\[\n  - \\nabla (\\epsilon \\nabla) u + \\nabla (v\\ u) = f \\qquad \\mbox{with } v \\in\n  \\mathbb{R}^d, \\epsilon \\in \\mathbb{R}^{d \\times d}\n\\]\nwith various geometric multigrid solvers. $epsilon$ is a diagonal matrix with\nentries $\\epsilon _1, \\epsilon _2$ or $\\epsilon _1, \\epsilon _2, \\epsilon _3$,\nrespectively.\nOur realisation is based upon a few design decisions:\n\n\\begin{enumerate}\n  \\item The solvers use the spacetree as computational grid.\n  \\item We use a finite element formalism with $d$-linear shape functions.\n  \\item The material parameters $\\epsilon $ and $v$ are given per cell.\n\\end{enumerate}\n\n\n\\noindent\nFor the implementation, we use Peano's \\texttt{matrixfree} toolbox. \nThis is a tiny little collection of helper classes to work with stencils and\nlocal assembly matrix. \nIt is neither fast, i.e.~computationally mature, nor can it cope with real\nstencil libraries, but it does the job.\n\n\n\n\\subsection{Setup}\n\nWe start with Peano's PDT and generate a project. We also link Peano's sources\ninto the project and unzip the \\texttt{matrixfree} toolbox. \n\\begin{code}\n  java -jar pdt.jar --create-project multigrid multigrid\n  ln -s mypath/src/peano \n  ln -s mypath/src/tarch\n  cp mypath/tarballs/toolboxes/matrixfree.tar.gz .\n  tar -xzvf matrixfree.tar.gz\n\\end{code}\n\n\n\\noindent\nI recommend to hold \\texttt{matrixfree} parallel to the \\texttt{multigrid},\n\\texttt{peano} and \\texttt{tarch} directory.\nAs soon as we use such a toolbox, we also might have to adopt our makefile\naccordingly: we have to add the matrixfree directory to the find pathes when we\nbuild up a list of source codes.\nFurthermore, you might have to add an additional search directory. If you place\nyour toolbox parallel to \\texttt{peano} and \\texttt{tarch}, this however should\nnot be necessary.\nHere's the corresponding excerp from the makefile\\footnote{Please note that some hyphens might not be displayed properly}:\n\\begin{code}\nfiles.mk:\n    touch files.mk\n    echo -n SOURCES= > files.mk\n    find -H $(PEANO_HOME)/peano -name *.cpp | awk { printf \"%s \", $$0 } >> files.mk\n    find -H $(PEANO_HOME)/matrixfree -name *.cpp | awk { printf \"%s \", $$0 } >> files.mk\n    find $(PROJECT_HOME) -name *.cpp | awk { printf \"%s \", $$0 } >> files.mk\n\\end{code}\n% '*.cpp' | awk '{ printf \"%s \", $$0 }' >> files.mk\n%     find -H $(PEANO_HOME)/tarch -name '*.cpp' | awk '{ printf \"%s \", $$0 }' >> files.mk\n%     find -H $(PEANO_HOME)/matrixfree -name '*.cpp' | awk '{ printf \"%s \", $$0 }' >> files.mk\n%     find $(PROJECT_HOME) -name '*.cpp' | awk '{ printf \"%s \", $$0 }' >> files.mk\n\n\\noindent\nWe next add our material parameters to the \\texttt{Cell.def} file\n\\begin{code}\nPacked-Type: short int;\n\nConstant: DIMENSIONS;\n\nclass multigrid::records::Cell {  \n  persistent parallelise double   epsilon[DIMENSIONS];\n  persistent parallelise double   v[DIMENSIONS];\n};\n\\end{code}\n\n\\noindent\nand create a simple first specification file:\n\\begin{code}\ncomponent: Multigrid\n\nnamespace: ::multigrid\n\nvertex:\n  dastgen-file: Vertex.def\n  \ncell:\n  dastgen-file: Cell.def\n\nstate:\n  dastgen-file: State.def\n\nevent-mapping:\n  name: CreateGrid\n\nevent-mapping:\n  name: PlotCells\n\nadapter:\n  name: CreateGrid\n  merge-with-user-defined-mapping: CreateGrid\n  merge-with-user-defined-mapping: PlotCells\n  \n\\end{code}\n\n\\noindent\nWe run this specification file through the PDT\n\n\\begin{code}\njava -jar <mypath>/pdt.jar --generate-gluecode multigrid/project.peano-specification multigrid\n\\end{code}\n\n\n\\noindent\nand implement both the plotter and the creational mapping such that we have a\nfew characteristic setups. \nIt might however make sense to validate that make passes before we start any\nPDE-specific coding:\n\\begin{code}\nmake -f multigrid/makefile\n\\end{code}\n\n\n\\noindent\nWe next introduce an operation \n\\begin{code}\nmatrixfree::stencil::ElementWiseAssemblyMatrix multigrid::Cell::getElementsAssemblyMatrix(\n  const tarch::la::Vector<DIMENSIONS,double>&  h\n) const {\n  matrixfree::stencil::ElementWiseAssemblyMatrix result;\n\n  const matrixfree::stencil::Stencil laplacianStencil = \n    matrixfree::stencil::getLaplacian(_cellData.getEpsilon(), h);\n\n  return matrixfree::stencil::getElementWiseAssemblyMatrix(laplacianStencil);\n}\n\\end{code}\nwhich returns the $\\mathbf{R}^{2^d \\times 2^d}$ local system matrix. \nThe method sets up the stencils that correspond to a regular Cartesian system\ngiven the mesh size \\texttt{h} and the material parameters.\nHere, also the convective term has to be handled.\nFinally, it uses \\texttt{getElementWiseAssemblyMatrix} to extract the actual\nmatrix from this stencil.\n\n\\begin{remark}\n  Peano supports all stencil/linear algebra operations for complex values.\n\\end{remark}\n\n\n\\subsection{Jacobi smoother}\n\nThe basic building block of all of our solvers is a simple Jacobi smoother\nworking on adaptive grids as well as on multiple scales.\nIts realisation is an extension of the solver in \\ref{section:applications:heat-equation}.\nTo make it work without the assembly of any global matrix, we associate each\nvertex a residual value as well as the actual value. \nThere are a few other features such as boundary properties or some level\nanalysis that we either use later on or we pass to the used toolboxes. \nTheir exact semantics and rationale have to be taken from the source code.\n\n\\begin{code}\nPacked-Type: short int;\n\n\nclass multigrid::records::Vertex {  \n  // Solution\n  persistent parallelise double  u;\n\n  // Rhs\n  persistent parallelise double  f;\n  \n  // Residual\n  persistent parallelise double   r;\n\n  // Diagonal element\n  persistent parallelise double   d;\n  \n  enum VertexType {\n    Unknown, Dirichlet, Neumann\n  };\n  \n  persistent VertexType vertexType;\n  \n  // some other attributes\n};\n\\end{code}\n\n\\noindent\nBesides a proper initialisation of the vertices, we extend the specification\nsimilar to the heat equation.\n\\begin{code}\ncomponent: Multigrid\n\nnamespace: ::multigrid\n\nvertex:\n  dastgen-file: Vertex.def\n  read scalar(double): U\n  read scalar(double): R\n  read scalar(double): D\n  read scalar(double): F\n  write scalar(double): U\n  write scalar(double): R\n  write scalar(double): D\n  \n...\n\nadapter:\n  name: CreateGrid\n  merge-with-user-defined-mapping: CreateGrid\n  merge-with-user-defined-mapping: PlotCells\n  merge-with-predefined-mapping: VTKPlotVertexValue(u,getU,u)\n\\end{code}\n\n\\noindent\nOnce this code framework passes (only minor technical helper routines have to\nbe implemented, but by now this should be straightforward to any user), we can\nintroduce a new mapping/adapter \\texttt{JacobiSmoother}, call this one a couple of hundred times in the runner and plot the result file then. \nFor the latter, it makes sense to use a predefined plotter.\nThe interesting new aspects can be found in three routines of the smoother.\nThe design of the code realises matrix-free element-wise mat-vecs 1:1: \n\n\n\\begin{enumerate}\n  \\item Each vertex carries a residual and a diagonal value attribute. \n    They are cleared whenever the vertex is read the very first time in\n    a traversal.\n    \\begin{code}\nvoid multigrid::mappings::JacobiSmoother::touchVertexFirstTime(...) {\n  logTraceInWith6Arguments( \"touchVertexFirstTime(...)\", ... );\n\n  fineGridVertex.clearAccumulatedAttributes();\n\n  logTraceOutWith1Argument( \"touchVertexFirstTime(...)\", fineGridVertex );\n}\n\n// in Vertex files\n\nvoid multigrid::Vertex::clearAccumulatedAttributes() {\n  _vertexData.setR(0.0);\n  _vertexData.setD(0.0);\n}\n    \\end{code}\n    \n    \\noindent\n    Our concept is that we accumulate the diagonal element $d$ and the residual\n    $r$ within these (temporary) attributes per vertex throughout the traversal.\n    \n    \\item When we use a vertex for the very last time, we may thus update the\n    unknown according to the values of the residual and the diagonal value. This\n    is the actual Jacobi smoothing step:\n    \\[\n      u ^{(new)} \\gets u ^{(old)} + \\omega \\frac{1}{d} r\n    \\]\n    \\begin{code}\nvoid multigrid::mappings::JacobiSmoother::touchVertexLastTime(...) {\n  const bool hasUpdated = fineGridVertex.performJacobiSmoothingStep( omega );\n  \n  ...\n}\n\n// in Vertex files\n\ndouble multigrid::Vertex::getResidual() const {\n  return _vertexData.getF() + _vertexData.getR();\n}\n\n\nvoid multigrid::Vertex::performJacobiSmoothingStep( double omega ) {\n  if (_vertexData.getVertexType()== Records::Unknown) {\n    assertion1( _vertexData.getD()>0.0, toString() );\n    assertion2( omega>0.0, toString(), omega );\n    _vertexData.setU( _vertexData.getU() + omega / _vertexData.getD() * getResidual() );\n  }\n}\n    \\end{code} \n    \n    \\noindent\n    Please note that the residual here is modelled as sum of the right-hand\n    side and the accumulated value (cf.~helper operation\n    \\texttt{getResidual()}).\n    We anticipate the minus from the definition \n    \\[ r = f - Au \\]\n    already in the accumulation, i.e.~sum up $-Au$ in the vertex attribute $r$.\n    An additional pitfal is this context stems from the usage of a finite\n    element method.\n    It implies that we have to ensure that $f$ is scaled with $h^d$ ($h$ being the local mesh width), which is something we typically\n    do already in the initialisation. \n    \n    In the present implementation, we make the Jacobi update return a flag that\n    indicates whether a fine grid update has been done or not. \n    Most codes will like to track global data such as a global residual or the\n    maximum value of the solution and can use this flag to decide whether a\n    vertex contributes to global data or not. Please study the accompanying\n    source code for details.\n    \n    \\item The most complicated part is obviously the evaluation of the local\n    mat-vec contributions. Here, we rely on the cell's\n    \\texttt{getElementsAssemblyMatrix} as well as operations from \\newline\n    \\texttt{VertexOperations}. All operations in this class are generated by the\n    PDT and extract from \\texttt{enterCell}'s vertices vectors: you hand in all\n    fine grid data and extract a vector of all $u$ values, e.g. The other way\n    round is supported as well. The operations within this helper class are all\n    generated because of the read and write statements in the specification. \n    \\begin{code}\n#include \"multigrid/VertexOperations.h\"\n\nvoid multigrid::mappings::JacobiSmoother::enterCell(...) {\n  logTraceInWith4Arguments( \"enterCell(...)\", fineGridCell, ... );\n\n  const tarch::la::Vector<TWO_POWER_D,double> u    =\n    VertexOperations::readU( fineGridVerticesEnumerator, fineGridVertices );\n  const tarch::la::Vector<TWO_POWER_D,double> dOld    =\n    VertexOperations::readD( fineGridVerticesEnumerator, fineGridVertices );\n  const tarch::la::Vector<TWO_POWER_D,double> rOld =\n    VertexOperations::readR( fineGridVerticesEnumerator, fineGridVertices );\n  const matrixfree::stencil::ElementWiseAssemblyMatrix A =\n    fineGridCell.getElementsAssemblyMatrix( fineGridVerticesEnumerator.getCellSize() );\n\n  tarch::la::Vector<TWO_POWER_D,double> r = rOld - A * u;\n  tarch::la::Vector<TWO_POWER_D,double> d = dOld + tarch::la::diag(A);\n\n  VertexOperations::writeR( fineGridVerticesEnumerator, fineGridVertices, r );\n  VertexOperations::writeD( fineGridVerticesEnumerator, fineGridVertices, d );\n\n  logTraceOutWith1Argument( \"enterCell(...)\", fineGridCell );\n}\n    \\end{code}\n\\end{enumerate}\n\n\n\n\\subsection{Environment}\n\nThe changes in the environment are straightforward once the smoother is \nin place:\n\\begin{enumerate}\n  \\item We extend the runner such that it switches to the Jacobi smoother once \n  the grid is set up and triggers a fixed number of iterations then.\n  \\item We add a logging device to the runner\n  \\begin{code}\n    class multigrid::runners::Runner {\n      private:\n        static tarch::logging::Log  _log;\n        ...\n    };\n  \\end{code}\n  and make the innermost loop plot residual and other statistics after each \n  grid traversal:\n  \\begin{code}\n  repository.switchToJacobiAndPlot();\n  for (int i=0; i<100; i++) {\n    repository.iterate();\n\n    logInfo(\n      \"runAsMaster(...)\",\n      \"#vertices=\" << repository.getState().getNumberOfInnerLeafVertices() <<\n      \",|res|_2=\" << repository.getState().getResidualIn2Norm() <<\n      \",|res|_max=\" << repository.getState().getResidualInMaxNorm() <<\n      \",|u|_L2=\" << repository.getState().getSolutionInL2Norm() <<\n      \",|u|_max=\" << repository.getState().getSolutionInMaxNorm() <<\n      \",#stencil-updates=\" << repository.getState().getNumberOfStencilUpdates()\n    );\n\n    repository.getState().clearAccumulatedAttributes();\n  }\n  \\end{code}\n  \\item To make the code work, we augment the state with the corresponding\n  fields \n  \\begin{code}\nPacked-Type: short int;\n\nclass multigrid::records::State {  \n  // Stores squared value, i.e. apply sqrt before returning it\n  persistent parallelise double residual2Norm;\n  persistent parallelise double residualMaxNorm;\n  // Stores squared value, i.e. apply sqrt before returning it\n  persistent parallelise double solutionL2Norm;\n  persistent parallelise double solutionMaxNorm;\n  persistent parallelise double numberOfStencilUpdates;\n};\n  \\end{code}\n  and realise the corresponding setters and getters. The design of the state\n  methods (notably a method \\texttt{clearAccumulatedAttributes()} in\n  combination with \\texttt{merge}) follows recommendations motivated in Section\n  \\ref{section:parallelisation:shared-memory}. For the time being, we do not\n  discuss them further.\n  \\item Finally, we extend the \\texttt{main} such that it can read in a\n  well-suited relaxation parameter from the command line. It then sets this\n  relaxation parameter (the static field) in the mapping:\n  \\begin{code}\n    multigrid::mappings::JacobiSmoother::omega = atof( argv[2] );\n  \\end{code}\n\\end{enumerate}\n\n\n\\noindent\nWe may run this code for example the\nwell-known Poisson benchmark ($\\epsilon = 1, v=0, f=d\\ \\pi ^2 \\prod _i \\sin\n\\left( x_i \\pi \\right) $ ), and observe the well-known dependency of Jacobi on\nthe mesh width (below grids with two, three or four compute grid levels):\n\n\\begin{center}\n  \\includegraphics[width=0.3\\textwidth]{42_matrix-free-multigrid/Poisson3.png}\n  \\includegraphics[width=0.3\\textwidth]{42_matrix-free-multigrid/Poisson4.png}\n  \\includegraphics[width=0.3\\textwidth]{42_matrix-free-multigrid/Poisson5.png}\n\\end{center}\n\n\n\\subsection{Dynamically adaptive Jacobi mit FAC}\n\n\\noindent \nWe next implement a dynamically adaptive Jacobi solver that implements the FAC\nscheme.\nIts fundamental idea is that the Jacobi smootherr is applied on each and every\ngrid level in parallel.\nAny hanging node's value is interpolated from coarser grids.\nWhile we update all grid levels, we do overwrite coarse vertices with fine grid\nvalues for all vertices that do exist on finer grid resolutions as well.\nWe inject the solution from the fine grids onto coarser grids.\nThis first solver is capable to handle dynamically adaptive grids with\narbitrary refinement pattern.\nIt also is a preliminary exercise how to implement multigrid full approximation\nstorage (FAS).\n\nWe extend the grid setup slightly such that it creates a very coarse grid even\nif we prescribe a fine minimum mesh size.\nNext, we validate that \\texttt{enterCell} evaluates the stencil on each grid\nlevel.\nThis leaves two tasks: interpolatation and injection.\nThe injection is basically the same we have used in the heat equation before.\n\\begin{code}\nvoid multigrid::mappings::JacobiSmoother::touchVertexLastTime(...) {\n // see code snippets introduced before\n\n if (\n  peano::grid::SingleLevelEnumerator::isVertexPositionAlsoACoarseVertexPosition(\n    fineGridPositionOfVertex\n  )\n ) {\n  const peano::grid::SingleLevelEnumerator::LocalVertexIntegerIndex coarseGridPosition =\n    peano::grid::SingleLevelEnumerator::getVertexPositionOnCoarserLevel\n    (fineGridPositionOfVertex);\n  coarseGridVertices[ coarseGridVerticesEnumerator(coarseGridPosition) ].inject(fineGridVertex);\n }\n}\n\n\n// in the vertex\n\nvoid multigrid::Vertex::inject(const Vertex& fineGridVertex) {\n  _vertexData.setU( fineGridVertex._vertexData.getU() );\n}\n\\end{code}\n\n\n\n\\begin{remark}\n  The \\texttt{matrixfree} toolbox offers a type \\texttt{solver::Smoother} that\n  realises a Jacobi smoother that automatically tracks different residual and\n  solution norms. In the present example we do not use this smoother while we\n  use the toolbox's multigrid class. This is kind of inconsistent. It would\n  probably be better to use the smoother as well.\n\\end{remark}\n\n\\noindent\nThe interpolation follows the idea of the heat equation solver, too.\nHowever, we propose to rely on a premanufactured interpolation operation from\nthe \\texttt{matrixfree} toolbox.\nFor this, we make our smoother mapping hold an instance of\n\\texttt{matrixfree::solver::Multigrid  \\_multigrid}.\nThis object offers us an operation \\texttt{getDLinearInterpolatedValue}: \n\n\\begin{code}\nvoid multigrid::mappings::JacobiSmoother::createHangingVertex(...) {\n  logTraceInWith6Arguments( \"createHangingVertex(...)\", ... );\n\n  fineGridVertex.setU(\n    _multigrid.getDLinearInterpolatedValue(\n      VertexOperations::readU( coarseGridVerticesEnumerator, coarseGridVertices ),\n      fineGridPositionOfVertex\n    )\n  );\n\n  logTraceOutWith1Argument( \"createHangingVertex(...)\", fineGridVertex );\n}\n\\end{code}\n\n\n\\noindent\nObviously, the vertex requires an additional \\texttt{setU( double )} operation\nto make this snippet work.\nIts implementation is trivial.\nThis is the only additional extension required.\nIf we adopt the setup, we might solve the equation on grids alike below where\nthe mesh is resolved up to the finest level along the boundaries. \nThe latter is a proper choice for many problems, though inadequate and thus\nonly a proof of concept for the present case:\n\n\\begin{center}\n  \\includegraphics[width=0.3\\textwidth]{42_matrix-free-multigrid/AdaptivePoisson3.png}\n  \\includegraphics[width=0.3\\textwidth]{42_matrix-free-multigrid/AdaptivePoisson4.png}\n\\end{center}\n\n\n\n\\begin{remark}\n  On some machines, the resulting code will fail in \\texttt{Assert} mode as the\n  plotters complain about nan for the right-hand side. In the release\n  mode, i.e.~without assertions, no complaint is raised, but some visualisation\n  software might complain about the nans. To fix this issue with the plotting,\n  it is important to set the right-hand side $f$ to zero for hanging nodes and\n  for boundary nodes. We propose to introduce a \\texttt{clearF()} operation and\n  to call it prior to any plotting (in the \\texttt{CreateGrid} mapping for\n  example) for hanging and boundary vertices.\n\\end{remark}\n\n\\noindent\nWe close our discussion on the Jacobi smoother with the introducton of a dynamic\nrefinement criterion.\nFor this, we rely on a predefined refinement criterion offered with the\nmatrixfree toolbox.\nWe use\n\\texttt{LinearSurplusRefinementCriterionWithFixedMeshSizes}\nfrom \\\\\n\\texttt{matrixfree::adaptivitycriteria}.\nThere is an extensive documentation how to use it in its superclass' header, so\nwe do not reiterate this here.\nInstead we just show some of the added code:\n\n\\begin{code}\nmultigrid::mappings::RefinementCriterion::RefinementCriterion():\n  _refinementCriterion(\n    0.1,                   // refinementPercentage,\n    0.0,                   // deletePercentage,\n    0.5,                   // minimumMeshSize,\n    0.5                    // maximumMeshSize\n  ) {\n}\n\nvoid multigrid::mappings::RefinementCriterion::touchVertexFirstTime(...) {\n  VertexOperations::writeLinearSurplus(fineGridVertex,0.0);\n}\n\nvoid multigrid::mappings::RefinementCriterion::enterCell(...) {\n  VertexOperations::writeLinearSurplus(\n    fineGridVerticesEnumerator,\n    fineGridVertices,\n    _refinementCriterion.getNewLinearSurplus(\n      VertexOperations::readU(fineGridVerticesEnumerator,fineGridVertices),\n      VertexOperations::readLinearSurplus(fineGridVerticesEnumerator,fineGridVertices)\n    )\n  );\n}\n\nvoid multigrid::mappings::RefinementCriterion::touchVertexLastTime(...) {\n  if ( fineGridVertex.isInside() ) {\n    const tarch::la::Vector<TWO_POWER_D_TIMES_D,double > coarseGridLinearSurplus =\n      VertexOperations::readLinearSurplus(coarseGridVerticesEnumerator, coarseGridVertices)\n      +\n      _refinementCriterion.getLinearSurplusContributionFromFineGrid(\n        VertexOperations::readLinearSurplus( fineGridVertex ),\n        fineGridVertex.getRefinementControl()==Vertex::Records::Unrefined,\n        fineGridPositionOfVertex\n      );\n\n    VertexOperations::writeLinearSurplus( coarseGridVerticesEnumerator, \n      coarseGridVertices, coarseGridLinearSurplus );\n\n    switch (\n      _refinementCriterion.analyse(\n        VertexOperations::readLinearSurplus(fineGridVertex),\n        fineGridVertex.getRefinementControl()==Vertex::Records::Refined,\n        fineGridVertex.getRefinementControl()==Vertex::Records::Unrefined,\n        fineGridH\n      )\n    ) {\n      case matrixfree::adaptivitycriteria::LinearSurplusRefinementCriterion::Refine:\n        fineGridVertex.refine();\n        break;\n      case matrixfree::adaptivitycriteria::LinearSurplusRefinementCriterion::Delete:\n      case matrixfree::adaptivitycriteria::LinearSurplusRefinementCriterion::NoAction:\n        break;\n    }\n  }\n}\n\\end{code}\n\n\\noindent\nThe criterion's idea is to evaluate a stencil that allows us to compare the\nlinear interpoland of the solution within a vertex to the actual vertex's\nsolution value.\nWe anticipate what would happen if we could remove a particular vertex alone.\nThe other way round, we assume that vertices with a big difference are critical,\nand we would benefit a lot if we would refine around this vertex.\n\nThe offered criterion class bucket sorts the linear surplus values. This is not\nexact, but it does not require a real sort being in $\\mathcal{O}(n \\log\nn)$---actually nothing is sorted, but each bucket is flagged (refine, coarse,\ndo nothing).\nIf a vertex falls into a particular bucket, the criterion returns the\ncorresponding flag.\nMore sophisticated criteria might yield better approximation patterns, but this\ngeneric one works surprisingly well.\n\n\\begin{center}\n  \\includegraphics[width=0.24\\textwidth]{42_matrix-free-multigrid/DynamicA00.png}\n  \\includegraphics[width=0.24\\textwidth]{42_matrix-free-multigrid/DynamicA01.png}\n  \\includegraphics[width=0.24\\textwidth]{42_matrix-free-multigrid/DynamicA02.png}\n  \\includegraphics[width=0.24\\textwidth]{42_matrix-free-multigrid/DynamicA03.png}\n\\end{center}\n\n\\noindent\nThis code marks up to ten percent of the vertices for refinemenet and\nconsequently refines all the surrounding cells given that the residual in\nthe vertices underruns the given threshold \\\\\n\\texttt{\\_convergenceThreshold}.\nThe latter magic constant is set to $10^{-2}$ for the plots above.\n\nNow, one simple feature is worth trying: We have so far always used a\npredefined visualisation routine that visualises the finest grid of a\nsimulation.\nAmong the set of standard visualisation routines also is a plotter that plots\nthe individual levels of a grid.\nGiven that we inject the solution to coarse levels anyway, this allows us to\nvisualise all data in a multilevel fashion.\nTo use it, we again extend our specification, regenerate the glue code and\nrecompile.\n\n\\begin{code}\nadapter:\n  name: JacobiAndPlot\n  merge-with-user-defined-mapping: CreateGrid\n  merge-with-user-defined-mapping: JacobiSmoother\n  merge-with-user-defined-mapping: PlotCells\n  merge-with-predefined-mapping: VTKPlotVertexValue(u,getU,u)\n  merge-with-predefined-mapping: VTKPlotVertexMultilevelValue(multiscaleU,getU,u)\n\\end{code}\n\n\\noindent\nSome minor remarks on proper initialisation that are often encountered shall\nclose the discussion.\nFirst, the presented refinement criterion does not properly refine along the\ndomain's boundary, as it does not distinguish whether a stencil is applied along\nthe boundary. \nIn practice, it is reasonable to ensure that the boundary is always refined at\nleast as fine as the vertices next to the boundary. \nIn practive, it is reasonable to avoid hanging vertices along the boundary. \nThis can be achieved if we check within each cell whether there is a boundary\nvertex and whether one vertex is refined.\nIf both properties hold, all unrefined boundary vertices have to be refined. \nThe class \\texttt{peano::grid::aspects::VertexStateAnalysis} provides generic\nhelper routines to realise this behaviour with a few lines:\n\n\\begin{code}\n#include \"peano/grid/aspects/VertexStateAnalysis.h\"\n#include \"peano/utils/Loop.h\"\n\nvoid multigrid::mappings::RefinementCriterion::enterCell(...) {\n  ...\n  if (\n    fineGridCell.isRefined()\n    &&\n    peano::grid::aspects::VertexStateAnalysis::doesOneVertexCarryRefinementFlag(\n      fineGridVertices, fineGridVerticesEnumerator, Vertex::Records::Unrefined\n    )\n  ) {\n    bool isOneVertexABoundaryVertex = false;\n    dfor2(k)\n      isOneVertexABoundaryVertex |= \n        fineGridVertices[ fineGridVerticesEnumerator(k) ].isBoundary();\n    enddforx\n    if (isOneVertexABoundaryVertex) {\n      dfor2(k)\n        if (fineGridVertices[ fineGridVerticesEnumerator(k) ].getRefinementControl()\n          ==Vertex::Records::Unrefined) {\n          fineGridVertices[ fineGridVerticesEnumerator(k) ].refine();\n        }\n      enddforx\n    }\n  }\n \n}\n\\end{code}\n\n\\noindent\nSecond, many codes require a proper balancing. \nAs Peano relies on three-partitioning, a 3:1 balancing is something many codes\nwould like to have: \nNo two neighbouring cells differ in their maximum refinement level by more than\none.\nThis can be realised manually within a mapping. \nOr you may decide to merge the predefined mapping \\texttt{GridBalancer3to1} into \nyour adapters. \n\n\n\nFinally, any dynamically adaptive code should properly initialise new vertices. \nIn the present example, a proper initialisation could rely on $d$-linear\ninterpolation again.\nFor multigrid, higher order schemes are desireable (though in practice I again\nobserved that linear interpolation is sufficient), but higher order\ninterpolation then has to be realised manually with helper variables or some\nadditional code applying the stencil to newly generated vertices.\nWe stick to the linear case here:\n\\begin{code}\nvoid ...::createInnerVertex(...) {\n  fineGridVertex.setU(\n    _multigrid.getDLinearInterpolatedValue(\n      VertexOperations::readU( coarseGridVerticesEnumerator, coarseGridVertices ),\n      fineGridPositionOfVertex\n    )\n  );\n}\n\\end{code}\n\n\n\\begin{center}\n  \\includegraphics[width=0.34\\textwidth]{42_matrix-free-multigrid/DynamicB.png}\n  \\includegraphics[width=0.45\\textwidth]{42_matrix-free-multigrid/MultiLevel.png}\n\\end{center}\n\n\\noindent\nThe right image above presents the result of the multilevel plotter:\nEach grid resolution level is written to a separate file.\nIt is obvious that finer grid solution approximations overwrite coarser vertex\nvalues, while the coarse values determine the hanging node values.\nWe also see that the grid is refined towards the boundary here.\n\n\n\n\\subsection{Multigrid}\n\nWe start with some metaphilosophical considerations.\nMultigrid algorithms work in two types of spaces: the ansatz\n(discretisation) space holding the solution and a set of correction spaces.\nThe latter either are updated all at once (additive multigrid) or one after\nanother (multiplicative) before their contribution is added back to the actual\nrepresentation.\nIn the present discussion, we restrict ourselves to geometrically inspired\nmultigrid where both the correction and the discretisation space are spanned by\nthe spacetree's grid levels.\nOn the previous pages, we have realised a Jacobi directly within the\ndiscretisation space without assembling any bigger matrix.\nObviously, such an approach also works for the correction equations.\n\n\n\nAt first glance, we then however need two variable sets per vertex: one set for\nthe actual discretisation and one for the correction equations.\nAs long as we work on regular grids only, there is no need to store different\ntypes of variables within the vertices: refined vertices hold correction\nequations, fine grid vertices hold the discretisation.\nThis approach becomes problematic for adaptive grids. \nStill, unrefined vertices of the fine grid hold the discretised PDE. \nOn the same level of an arbitrary unrefined level, there might however also be\nan area that is refined further.\nHere, we solve a correction equation. \nIf we realised both the correction equation and the discretisation with the same\nset of variables, what would the right vertex values at the transition between\nunrefined and correction areas be? \nWe have to distinguish carefully in each cell which type of equation we are\nsolving, unless \\ldots\n\n\n\\ldots we solve also the correction equation in a discretisation space. This is\nthe idea of full approximation storage (FAS) which fits perfectly to our\ninjection that we realised anyway. Instead of solving\n\\[ \n  A_{3h} e = \\hat f \n\\]\nin areas that are refined further and thus hold a correction to the actual\nsolution iterate, we solve\n\\begin{eqnarray*}\n  A_{3h} \\left( Iu_h + e \\right)  & = & \\hat f +  A_{3h} Iu_h \\qquad \\mbox{added\n  an additional term on both sides} \\\\\n  & = & R r_h + RA_hPIu_h \\\\\n  & = & R \\left( r_h + A_hPIu_h \\right) \\\\\n  & = & R \\left( f_h - A_hu_h + A_hPIu_h \\right) \\\\\n  & = & R \\left( f_h - A_h\\left( id - PI\\right)u_h \\right) \\\\\n  & =: & R \\left( f_h - A_h \\hat u_h \\right)  =: R \\hat r_h  \n\\end{eqnarray*}\ni.e.~work with a coarsened solution as input to the correction solve \nwhich is a formalism introduced by Griebel as HTMG.\n\n\nSo we can stick to our injections of the solution. \nIn each traversal, we have to determine the hierarchical surplus in each vertex\n$\\hat u = u - PIu_h$ which is simple, as $Iu_h$ is available anyway.\nThis hierarchical transform is a temporary helper. \nWe can throw it away after the traversal again.\nWe can model it as \\texttt{discard} in the \\texttt{Vertex.def}.\n\nOnce we have $\\hat u$, we can simultaneously determine the residual $r$ as well\nas its hierarchical counterpart $\\hat r$. \nWith the residual $r$, we update the solution if we have to---a detail subject\nof discussion in a minute when we finalise whether to realise a multiplicative\nor additive scheme.\nThe hierarchical residual $\\hat r$ in turn is not used to update any solution\ndirectly.\nIt is restricted to the next coarser level to yield a right-hand side there.\n\n\nWe finally observe that we may not just update the solution with the residual.\nIf we did that we would loose the knowledge which correction to prolong to the\nnext finer level.\nWe therefore store the updates in another helper variable and use this update to\nprolong it to a finer level later on.\n\n\\begin{remark}\n  The update helper variable is not the only valid choice to\n  distinguish coarse grid updates from fine grid representation. It is obviously\n  that we also might store the hierarchical surplus persistently and then\n  reconstruct the nodal value with the relation $u_h=\\hat u_h+Pu_{3h}$. This is\n  the implementation variant discussed in (Weinzierl:09), while a more detailed\n  analysis of required helper variables for additive multigrid can be found in\n  (Reps:16).\n\\end{remark}\n\n\n\n\\begin{code}\nclass multigrid::records::Vertex {  \n  persistent parallelise double  u;             // Solution\n  persistent parallelise double  f;             // Rhs\n  discard parallelise double     r;             // Residual\n  discard parallelise double     d;             // Diagonal element\n  discard parallelise double     hierarchicalU; // Hierarchical solution\n  discard parallelise double     hierarchicalR; // Hierarchical residual\n  persistent parallelise double  uUpdate;       // Update of solution\n  discard parallelise double     linearSurplus[DIMENSIONS];\n\n  enum VertexType {\n    Unknown, Dirichlet, Neumann\n  };\n  persistent VertexType vertexType;\n};\n\\end{code}\n\n\n\\noindent\nThe hierarchical surplus has to be determined in \\texttt{touchVertexFirstTime}\nwhere we also clear the temporary variables.\nI decided to realise the generic multigrid operations in a mapping of its own. \nIt is called \\texttt{HierarchicalTransformAndRHSRestriction}.\nOnce more, we rely on an instance of the Multigrid class.\n\n\\begin{code}\nvoid\nmultigrid::mappings::HierarchicalTransformAndRHSRestriction::createHangingVertex(...) { \n fineGridVertex.clearHierarchicalValues();\n}\n\nvoid multigrid::mappings::HierarchicalTransformAndRHSRestriction::touchVertexFirstTime(...) {\n fineGridVertex.clearHierarchicalValues();\n\n if ( fineGridVertex.isInside() ) {\n   const tarch::la::Vector<TWO_POWER_D,double > u_3h  = \n     VertexOperations::readU(coarseGridVerticesEnumerator,coarseGridVertices);\n   const tarch::la::Vector<TWO_POWER_D,double > e_3h  = \n     VertexOperations::readUUpdate(coarseGridVerticesEnumerator,coarseGridVertices);\n   const double                                 Pu_3h = \n     _multigrid.getDLinearInterpolatedValue(u_3h,fineGridPositionOfVertex);\n   const double                                 Pe_3h =\n     _multigrid.getDLinearInterpolatedValue(e_3h,fineGridPositionOfVertex);\n\n   fineGridVertex.correctU(Pe_3h);\n   fineGridVertex.determineUHierarchical(Pu_3h);\n\n   if (fineGridVertex.getRefinementControl()!=Vertex::Records::Unrefined) {\n     fineGridVertex.clearF();\n   }\n }\n\n fineGridVertex.clearAccumulatedAttributes();\n}\n\nvoid multigrid::Vertex::determineUHierarchical(double Pu_3h) {\n  _vertexData.setHierarchicalU( _vertexData.getU()-Pu_3h );\n}\n\\end{code}\n\n\n\\begin{remark}\n  In this presentation, we make the solvers restrict residuals on all levels all\n  the time and prolong all updates all the time.\n  The actual distinction between additive and multiplicative multigrid stems from the decision which\n  level is smoothed, i.e.~where we find an update. This is\n  highly inefficient.\n  Good solvers would compute only those residuals and right-hand sides that have changed and\n  are required. But the purpose of this presentation is to introduce a quick,\n  brief prototype. Speed is a different topic.\n\\end{remark}\n\n\\noindent\nThe accumulation of the hierarchical surplus itself is more or less a\ncut-n-paste from the Jacobi smoother:\n\\begin{code}\n\nvoid multigrid::mappings::HierarchicalTransformAndRHSRestriction::enterCell(...) { \n  const tarch::la::Vector<TWO_POWER_D,double> hierarchicalU    =\n     VertexOperations::readHierarchicalU( fineGridVerticesEnumerator, fineGridVertices );\n   const tarch::la::Vector<TWO_POWER_D,double> hierarchicalROld =\n     VertexOperations::readHierarchicalR( fineGridVerticesEnumerator, fineGridVertices );\n   const matrixfree::stencil::ElementWiseAssemblyMatrix A =\n     fineGridCell.getElementsAssemblyMatrix( fineGridVerticesEnumerator.getCellSize() );\n\n   tarch::la::Vector<TWO_POWER_D,double> hierarchicalR = \n     hierarchicalROld - A * hierarchicalU;\n\n   VertexOperations::writeHierarchicalR\n     ( fineGridVerticesEnumerator, fineGridVertices, hierarchicalR );\n}\n\\end{code}\n\n\\noindent \nFor the restriction, we again rely on the multigrid object, where a specialised\nprolongation function does exist that uses $d$-linear interpolation.\nFurthermore, we stick to the convention $R=P^T$ and thus can write:\n\n\\begin{code}\nvoid\nmultigrid::mappings::HierarchicalTransformAndRHSRestriction::touchVertexLastTime(...) {\n  if ( fineGridVertex.isInside() ) {\n    const tarch::la::Vector<TWO_POWER_D, double > P = \n      _multigrid.calculateP(fineGridPositionOfVertex);\n\n    dfor2(k)\n      // There is no need to exclude boundary points here (the rhs does not play\n      // there a role anyway), but it makes the visualisation nicer.\n      if (\n        coarseGridVertices[ coarseGridVerticesEnumerator(k) ].getRefinementControl()==\n          Vertex::Records::Refined\n        &&\n        coarseGridVertices[ coarseGridVerticesEnumerator(k) ].isInside()\n      ) {\n        coarseGridVertices[ coarseGridVerticesEnumerator(k) ].incF(  \n          P(kScalar) * fineGridVertex.getHierarchicalResidual() \n        );\n      }\n    enddforx\n  }\n}\n\nvoid multigrid::Vertex::incF(double value) {\n  _vertexData.setF( _vertexData.getF()+value );\n}\n\ndouble multigrid::Vertex::getHierarchicalResidual() const {\n  return _vertexData.getF() + _vertexData.getHierarchicalR();\n}\n\\end{code}\n\n\n\\noindent\nWe close the preparatory work with the remark that the specification has to be\naugmented by additional readers and writers to make our code snippets work:\n\n\\begin{code}\ncomponent: Multigrid\n\nnamespace: ::multigrid\n\nvertex:\n  dastgen-file: Vertex.def\n  read scalar(double): U\n  read scalar(double): F\n  read scalar(double): R\n  read scalar(double): D\n  read scalar(double): HierarchicalU\n  read scalar(double): HierarchicalR\n  write scalar(double): U\n  write scalar(double): R\n  write scalar(double): D\n  write scalar(double): HierarchicalU\n  write scalar(double): HierarchicalR\n\n...\n\\end{code}\n\n\\begin{center}\n  \\includegraphics[width=0.8\\textwidth]{42_matrix-free-multigrid/Hierarchical-Jacobi.png}\n\\end{center}\n\n\\noindent\nWe see above a Jacobi smoother (100 iterations) for the Poisson equation on the\nunit square (left) as well as the hierarchical representation (right).\nWe also may augment the adapters with plots of the temporary data \n\n\\begin{code}\nadapter:\n  name: AnyAdapter\n  ...\n  merge-with-predefined-mapping: VTKPlotVertexValue(u,getU,u)\n  merge-with-predefined-mapping: VTKPlotVertexMultilevelValue(multiscaleU,getU,u)\n  merge-with-predefined-mapping: VTKPlotVertexMultilevelValue\n    (multiscaleHierarchicalU,getHierarchicalU,u)\n  merge-with-predefined-mapping: VTKPlotVertexMultilevelPointCloud\n    (multiscaleResidual,getResidual,res)\n  merge-with-predefined-mapping: VTKPlotVertexMultilevelPointCloud\n    (multiscaleHierarchicalResidual,getHierarchicalResidual,res)\n  merge-with-predefined-mapping: VTKPlotVertexMultilevelPointCloud(f,getF,f)\n\\end{code}\n\n\\noindent\nand emphasise that we basically have almost all multigrid ingredients at hands.\nMissing is a projection from coarse grid updates to fine grid values.\nSo far, we update the coarse grid values according to the right-hand side.\nThese updates however are not projected.\nInstead, the updated approximation in a FAS sense are overwritten at the end of\nthe subsequent iteration with fine grid solution data. \n\n\n\\begin{remark}\n  Most default VTK plotters plot the grid as well as values and (for\n  consistency reasons imposed by the VTK data file format) have to plug into\n  \\texttt{touchVertexFirstTime}. For residuals and other temporary data, we\n  typically however are interested to plot the value at the end of the\n  iteration. A quick solution here is to plot the grid with one mapping and to\n  use a second mapping that solely plots a point cloud with the vertex values.\n  We then can visualise both data sets simultaneously.\n\\end{remark}\n\n\n\n\n\n\\subsection{Additive Geometric Multigrid and BPX}\n\nAdditive multigrid is relatively simple to realise as it fits naturally to our\ntree traversals.\nThe most important and useful idea hereby is that you might want to shift the\nactual multigrid cycle by half a tree traversal:\nyour start with the prolongation of the error terms in the very first grid sweep\n(they are zero at this time) and you then trigger all the fine-to-coarse\noperations in the remainder of the sweep.\nIt is not before the second grid sweep that the corrections introduced by the\nfine-to-coarse operators are then added again to the finest grid solution. \nSo for $n$ additive multigrid sweeps, you need $n+1$ grid sweeps.\n\n\n\n%  In additive multigrid, we may not use the same relaxation\n% factor on each and every level. \n% Instead, it is important that the coarser the level the smaller the contribution\n% to the solution update.\n% Otherwise, the solver tends to overshoot and become unstable. \n% We propose to use relaxation factors $\\omega ^k$ with $k=1$ on the fine grid\n% level and increasing by one for each level up the hierarchy.\n% $\\omega $ obviously has to be adopted if the grid changes.\n% It is thus straightforward to compute it on-the-fly. \n% For this, we add an additional variable to the vertex\n% \n% \\begin{code}\n% class multigrid::records::Vertex {  \n%   persistent parallelise int  numberOfFinerLevelsAtSamePosition;\n% };\n% \\end{code}\n% \n% \\noindent\n% and make the grid traversal determine the correct value of this attribute\n% on the fly:\n% \n% \n% \\begin{code}\n% void multigrid::Vertex::clearAccumulatedAttributes() {\n%   _vertexData.setR(0.0);\n%   _vertexData.setD(0.0);\n%   \n%   _vertexData.setNumberOfFinerLevelsAtSamePosition( 1 );\n% }\n% \n% \n% void multigrid::mappings::AdditiveMGProlongation::touchVertexFirstTime(\n%   multigrid::Vertex&               fineGridVertex,\n%   const tarch::la::Vector<DIMENSIONS,double>&                          fineGridX,\n%   const tarch::la::Vector<DIMENSIONS,double>&                          fineGridH,\n%   multigrid::Vertex * const        coarseGridVertices,\n%   const peano::grid::VertexEnumerator&                coarseGridVerticesEnumerator,\n%   multigrid::Cell&                 coarseGridCell,\n%   const tarch::la::Vector<DIMENSIONS,int>&                             fineGridPositionOfVertex\n% ) {\n%   logTraceInWith6Arguments( \"touchVertexFirstTime(...)\", fineGridVertex, fineGridX, fineGridH, coarseGridVerticesEnumerator.toString(), coarseGridCell, fineGridPositionOfVertex );\n% \n%   if (fineGridVertex.isInside()) {\n%     const tarch::la::Vector<TWO_POWER_D,double > e_3h  = VertexOperations::readUUpdate(coarseGridVerticesEnumerator,coarseGridVertices);\n%     const double                                 Pe_3h = _multigrid.getDLinearInterpolatedValue(e_3h,fineGridPositionOfVertex);\n% \n%     fineGridVertex.correctU(\n%       Pe_3h\n%       *\n%       fineGridVertex.getDampingFactorForAdditiveCoarseGridCorrection(multigrid::mappings::JacobiSmoother::omega)\n%     );\n%   }\n% \n%   logTraceOutWith1Argument( \"touchVertexFirstTime(...)\", fineGridVertex );\n% }\n% \\end{code}\n% \n% \n% Update doch spezifisch\n% \n% \n% \n% inject ein bischen falsch. Eigentlich besser R. \n% \n% @todo Instabil. Relaxation mit aufnehmen\n% \n% @todo Kleiner Fehler mit der Injektion. Auf Bram verweisen, aber so lassen\n\n\n\nTo figure exactly out how information propagates through the grid levels is\nstraightforward as long as no adaptivity is involved.\nSome tricks how to handle adaptivity are discussed in \n\n \\begin{framed} \n \\noindent\nReps, Bram and Weinzierl, Tobias: {\\em Complex additive geometric\n  multilevel solvers for Helmholtz equations on spacetrees}, ACM Transactions on\n  Mathematical Software (TOMS), 44(1), 2017, 2:1--2:36\n \\end{framed}\n  \n\\noindent\nA preprint is available as arXiv tech report (arXiv:1508.03954).\nThe report also discusses the extension of an additive multigrid solver into \nBPX.\nAll code for this paper is available through the author's University webpage.\n\n\n\\subsection{Multiplicative Geometric Multigrid}\n\nMultiplicative multigrid is perhaps easier to realise than an additive multigrid\nalgorithm. I usually run through the following steps:\n\n\\begin{itemize}\n  \\item I augment the state (\\texttt{State.def}) with the current smoother step\n  and an enum whether I'm currently smoothing, ascending or descending.\n  \\item The runner triggers one grid sweep per multigrid step and increments and\n  decrements the smoothing levels. It also changes the state's smoothing state.\n  \\item I typically merge the restriction with the smoothing step on the next\n  coarser level. Smoothing steps can accumulate the coarse grid residuals and\n  need typically the new right-hand side not before they are about the touch a\n  vertex for the very last time. So we can do both coarse grid residual\n  accumulation and fine grid rhs computation in one mapping.\n  \\item I typically merge prolongation with the first smoothing step on the next\n  finer grid. If the prolongation is implemented within\n  \\texttt{touchVertexFirstTime}, the actual prolongation is a preamble to the\n  smoother and does not require a grid run-through of its own.\n\\end{itemize}\n\n% \\begin{remark}\n% There is \n% \\end{remark}\n\nDetails on efficient realisations, the extension to algebraic operators,\nas well as better smoothers are subject of dicussion in \n\n \\begin{framed} \n \\noindent\nWeinzierl, Marion and Weinzierl, Tobias: {\\em Quasi-matrix-free hybrid multigrid\non dynamically adaptive Cartesian grids}, arXiv:1607.00648\n \\end{framed}\n  \n\\noindent\nAll important source code fragments required to follow the techniques presented\ntherein are available through the matrixfree toolbox in the Peano repository.\n\n\n\n\\subsection*{Further reading}\n\n\\begin{itemize}\n  \\item Weinzierl, Marion and Weinzierl, Tobias: {\\em Quasi-matrix-free hybrid\n  multigrid on dynamically adaptive Cartesian grids}, arXiv:1607.00648\n  \\item  Reps, Bram and Weinzierl, Tobias: {\\em Complex additive geometric\n  multilevel solvers for Helmholtz equations on spacetrees}, ACM Transactions on\n  Mathematical Software (TOMS), 44(1), 2017, 2:1--2:36, arXiv:1508.03954\n  \\item Weinzierl, Marion: {\\em Hybrid Geometric-Algebraic Matrix-Free Multigrid on\nSpacetrees}, Dissertation, Technische Universit\\\"at M\\\"unchen, 2013\n  \\item   Muntean, Ioan Lucian, Mehl, Miriam, Neckel, Tobias and Weinzierl,\n  Tobias (2008). {\\em Concepts for Efficient Flow Solvers Based on Adaptive\n  Cartesian Grids}. In High Performance Computing in Science and Engineering,\n  Garching 2007. Wagner, Siegfried, Steinmetz, Matthias, Bode, Arndt and Brehm,\n  Matthias Berlin Heidelberg New York: Springer.\n  \\item Weinzierl, Tobias and K\\\"oppl, Tobias (2012). {\\em A Geometric\n  Space-time Multigrid Algorithm for the Heat Equation}. Numerical Mathematics:\n  Theory, Methods and Applications 5(1): 110-130.\n  \\item Mehl, Miriam, Weinzierl, Tobias and Zenger, Christoph (2006). {\\em A\n  cache-oblivious self-adaptive full multigrid method}. Numerical Linear Algebra\n  with Applications 13(2-3): 275-291.\n\\end{itemize}\n", "meta": {"hexsha": "deebd6507132743f7761bb0485a1d9ce1320f922", "size": 45868, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Submodules/Peano/cookbook/42_matrix-free-multigrid.tex", "max_stars_repo_name": "linusseelinger/ExaHyPE-Tsunami", "max_stars_repo_head_hexsha": "92a6e14926862e1584ef1e935874c91d252e8112", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-08-14T22:41:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-04T19:30:24.000Z", "max_issues_repo_path": "Submodules/Peano/cookbook/42_matrix-free-multigrid.tex", "max_issues_repo_name": "linusseelinger/ExaHyPE-Tsunami", "max_issues_repo_head_hexsha": "92a6e14926862e1584ef1e935874c91d252e8112", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Submodules/Peano/cookbook/42_matrix-free-multigrid.tex", "max_forks_repo_name": "linusseelinger/ExaHyPE-Tsunami", "max_forks_repo_head_hexsha": "92a6e14926862e1584ef1e935874c91d252e8112", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-07-22T10:27:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-11T12:25:29.000Z", "avg_line_length": 38.096345515, "max_line_length": 181, "alphanum_fraction": 0.7560608703, "num_tokens": 11503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.32913254495395944}}
{"text": "\n\n\\chapter{Categorical Data}\\label{Ch.2}\n\nRecall from Chapter 1 that a \\textbf{categorical variable} is a variable that can take on one of a limited set of values (which are called \\textit{levels}). In this chapter, we will discuss ways to analyze categorical variables. Throughout this chapter, we use the Titanic data set as a working example. This data set contains information about all of the people who were aboard the RMS Titanic when it sank in 1912, including both passengers and crew. Let's start by reading in this data set.\n\n\\begin{lstlisting}[language=Python]\nimport pandas as pd\n\ndata_dir = \"http://dlsun.github.io/pods/data/\"\ndf_titanic = pd.read_csv(data_dir + \"titanic.csv\")\ndf_titanic.head()\n\\end{lstlisting}\n\n\\small\\begin{verbatim}\n                             name  gender   age class embarked        country  \\\n0             Abbing, Mr. Anthony    male  42.0   3rd        S  United States   \n1       Abbott, Mr. Eugene Joseph    male  13.0   3rd        S  United States   \n2     Abbott, Mr. Rossmore Edward    male  16.0   3rd        S  United States   \n3  Abbott, Mrs. Rhoda Mary 'Rosa'  female  39.0   3rd        S        England   \n4     Abelseth, Miss. Karen Marie  female  16.0   3rd        S         Norway   \n\n   ticketno   fare  survived  \n0    5547.0   7.11         0  \n1    2673.0  20.05         0  \n2    2673.0  20.05         0  \n3    2673.0  20.05         1  \n4  348125.0   7.13         1  \n\\end{verbatim}\n\n\n\nThe categorical variables in this data set are:\n\\begin{itemize}\n\\item \n\\verb|gender| (male or female)\n\n\\item \n\\verb|class|: what class they were in (1st, 2nd, or 3rd) or what type of crew member they were\n\n\\item \n\\verb|embarked|: where they embarked (Belfast, Southampton, Cherbourg, or Queenstown)\n\n\\item \n\\verb|country|: their country of origin\n\n\\item \n\\verb|ticketno|: the ticket number\n\n\\item \n\\verb|survived|: whether or not they survived the disaster\n\n\\end{itemize}\n\nNote that \\verb|age| and \\verb|fare| are quantitative variables. It is tempting to consider \\verb|name| a categorical variable, but it is not, since (almost) every person has a unique name. In order for a variable to be categorical, it must take on a \\textit{limited} set of values, ideally with each level appearing multiple times in the data set. Otherwise, the analyses that we describe in this chapter will not be very meaningful.\n\n\n\n\n\n\n\\section{Analyzing One Categorical Variable}\\label{2.1}\n\nIn this lesson, we focus on a single categorical variable. For a high-level summary of a categorical variable, we can use the \\verb|.describe()| command. Note that the behavior of \\verb|.describe()| will change, depending on whether \\verb|pandas| thinks that the variable is quantitative or categorical, which is why it is important to cast categorical variables to the right type, as we discussed in the previous chapter.\n\n\\begin{lstlisting}[language=Python]\ndf_titanic[\"class\"].describe()\n\\end{lstlisting}\n\n\n\n\nTo completely summarize a single categorical variable, we report the number of times each level appeared, or its \\textbf{frequency}.\n\n\\begin{lstlisting}[language=Python]\nclass_counts = df_titanic[\"class\"].value_counts()\nclass_counts\n\\end{lstlisting}\n\n\n\n\nNotice that the levels are sorted in decreasing order of frequency by default. We can also report the levels in the order they appear in the data set...\n\n\\begin{lstlisting}[language=Python]\ndf_titanic[\"class\"].value_counts(sort=False)\n\\end{lstlisting}\n\n\n\n\n...or in alphabetical order, by sorting the index:\n\n\\begin{lstlisting}[language=Python]\nclass_counts.sort_index()\n\\end{lstlisting}\n\n\n\n\nNote that this produces a \\textit{new} \\verb|Series| with the index sorted. It does not sort the original \\verb|Series| \\verb|class_counts|. To sort the original series, we need to specify that the sorting should be done in place, just like we did for \\verb|.set_index()| in Chapter 1.\n\n\\begin{lstlisting}[language=Python]\nclass_counts.sort_index(inplace=True)\nclass_counts\n\\end{lstlisting}\n\n\n\n\nAny other order would require selecting the levels manually, in the desired order.\n\n\\begin{lstlisting}[language=Python]\nclass_counts.loc[\n    [\"1st\", \"2nd\", \"3rd\",\n     \"deck crew\", \"engineering crew\", \"victualling crew\",\n     \"restaurant staff\"]\n]\n\\end{lstlisting}\n\n\n\n\nThis information can be visualized using a \\textbf{bar chart}.\n\n\\begin{lstlisting}[language=Python]\nclass_counts.plot.bar()\n\\end{lstlisting}\n\n\n\n\nInstead of reporting counts, we can also report proportions or probabilities, or the \\textbf{relative frequencies}. We can calculate the relative frequencies by specifying \\verb|normalize=True| in \\verb|.value_counts()|.\n\n\\begin{lstlisting}[language=Python]\nclass_probs = df_titanic[\"class\"].value_counts(normalize=True)\nclass_probs.sort_index()\n\\end{lstlisting}\n\n\n\n\nThis is equivalent to taking the counts and dividing by their sum.\n\n\\begin{lstlisting}[language=Python]\nclass_counts / class_counts.sum()\n\\end{lstlisting}\n\n\n\n\nNotice that the relative frequencies add up to 1.0, by construction. We can report these relative frequencies using probability notation. For example:\n\n$$ P(\\text{1st class}) = 0.146806. $$\n\nThe complete collection of probabilities of all levels of a variable is called the \\textbf{distribution} of that variable. So the code above calculates the distribution of \"class\" on the Titanic.\n\n\n\nThe bar chart for relative frequencies (i.e., probabilities) looks qualitatively the same as the bar chart for frequencies (i.e., counts). The only difference is that the scale on the $y$-axis is different.\n\n\\begin{lstlisting}[language=Python]\nclass_probs.sort_index().plot.bar()\n\\end{lstlisting}\n\n\n\n\nIn the next lesson, we will see why it is often more useful to plot the relative frequencies (i.e., probabilities) rather than the frequencies (i.e., counts).\n\n\n\n\\subsection{Transforming Categorical Variables}\\label{2.1.1}\n\nA categorical variable can be transformed by mapping its levels to new levels. For example, we may only be interested in whether a person on the titanic was a passenger or a crew member. The variable \\verb|class| is too detailed. We can create a new variable, \\verb|type|, that is derived from the existing variable \\verb|class|. Observations with a \\verb|class| of \"1st\", \"2nd\", or \"3rd\" get a value of \"passenger\", while observations with a \\verb|class| of \"deck crew\", \"engineering crew\", or \"deck crew\" get a value of \"crew\".\n\n\\begin{lstlisting}[language=Python]\ndf_titanic[\"type\"] = df_titanic[\"class\"].map({\n    \"1st\": \"passenger\",\n    \"2nd\": \"passenger\",\n    \"3rd\": \"passenger\",\n    \"victualling crew\": \"crew\",\n    \"engineering crew\": \"crew\",\n    \"deck crew\": \"crew\"\n})\n\ndf_titanic\n\\end{lstlisting}\n\n\n\n\nUpon closer inspection of this \\verb|DataFrame|, we see that we accidentally left out the level \"restaurant staff\" in the input to \\verb|.map()|. Any levels that are unspecified will be mapped to the missing value \\verb|NaN|.\n\nThis suggests a more concise way to define the new variable \\verb|type|. We can specify only the levels for passengers in the mapping and then fill in the missing values afterwards.\n\n\\begin{lstlisting}[language=Python]\ndf_titanic[\"type\"] = df_titanic[\"class\"].map({\n    \"1st\": \"passenger\",\n    \"2nd\": \"passenger\",\n    \"3rd\": \"passenger\"\n})\n\n# Replace all missing values by \"crew\"\ndf_titanic[\"type\"].fillna(\"crew\", inplace=True)\n\ndf_titanic\n\\end{lstlisting}\n\n\n\n\nFor more complex mappings, the \\verb|.map()| method also accepts a function. So the above\n\n\\begin{lstlisting}[language=Python]\ndef class_to_type(c):\n  if c in [\"1st\", \"2nd\", \"3rd\"]:\n    return \"passenger\"\n  else:\n    return \"crew\"\n\ndf_titanic[\"class\"].map(class_to_type)\n\\end{lstlisting}\n\n\n\n\nWe can apply the techniques we learned above to calculate the \\textit{distribution} of this new variable, which only has two levels.\n\n\\begin{lstlisting}[language=Python]\ndf_titanic[\"type\"].value_counts(normalize=True)\n\\end{lstlisting}\n\n\n\n\n\\subsection{Conditional Probabilities}\\label{2.1.2}\n\nWhat fraction of males were crew members? To answer questions like this, we have to filter the \\verb|DataFrame| to include only males.\n\nThe standard way to filter a \\verb|DataFrame| is to use a \\textbf{boolean mask}. A boolean mask is simply a \\verb|Series| of booleans whose index matches the index of the \\verb|DataFrame|.\n\nThe easiest way to create a boolean mask is to use one of the standard comparison operators \\verb|==|, \\verb|<|, \\verb|>|, and \\verb|!=| on an existing column in the \\verb|DataFrame|. For example, the following code produces a boolean mask that is equal to \\verb|True| for the males on the Titanic and \\verb|False| otherwise.\n\n\\begin{lstlisting}[language=Python]\ndf_titanic[\"gender\"] == \"male\"\n\\end{lstlisting}\n\n\n\n\nNotice the subtle way the equality operator \\verb|==| is being used here! We are comparing an array with a string, i.e.,\n\n\\begin{align}\n& \\begin{bmatrix} \\text{\"male\"} \\\\ \\text{\"male\"} \\\\ \\text{\"male\"} \\\\ \\text{\"female\"} \\\\ \\vdots \\\\ \\text{\"male\"} \\end{bmatrix} & \\text{with} & & \\text{\"male\"}.\n\\label{broadcast1}\\end{align}\n\nIn most programming languages, this comparison would make no sense. An array of strings is obviously not equal to a string $\\eqref{broadcast1}$. However, \\verb|pandas| automatically applies the equality operator to \\textit{each} element of the array. As a result, we get an entire array (i.e., a \\verb|Series|) of booleans.\n\n\\begin{align}\n\\begin{bmatrix} \\text{\"male\"} \\\\ \\text{\"male\"} \\\\ \\text{\"male\"} \\\\ \\text{\"female\"} \\\\ \\vdots \\\\ \\text{\"male\"} \\end{bmatrix} &== \\text{\"male\"} &\\Longrightarrow & &  \\begin{bmatrix} \\text{True} \\\\ \\text{True} \\\\ \\text{True} \\\\ \\text{False} \\\\ \\vdots \\\\ \\text{True} \\end{bmatrix}.\n\\label{broadcast2}\\end{align}\n\nWhen an operation is applied to each element of an array, it is said to be \\textbf{broadcast} over that array $\\eqref{broadcast2}$.\n\nNow, we can use the boolean mask as a filter on the \\verb|DataFrame| to extract the rows where the mask equals \\verb|True|.\n\n\\begin{lstlisting}[language=Python]\ndf_male = df_titanic[df_titanic[\"gender\"] == \"male\"]\ndf_male\n\\end{lstlisting}\n\n\n\n\nNote that every person in this new \\verb|DataFrame| is male. If you inspect the index, you will see that rows 4 and 5 are missing. That is because those passengers were female.\n\n\n\nFinally, we can apply the methods we've learned in this lesson to \\verb|df_male| to answer the original question: \"What fraction of males were crew members?\"\n\n\\begin{lstlisting}[language=Python]\ndf_male[\"type\"].value_counts(normalize=True)\n\\end{lstlisting}\n\n\n\n\nIt appears that about \\verb|50.4657%| of the males were crew members. We can notate this using \\textit{conditional probability} notation:\n\n$$ P(\\text{crew} | \\text{male}) = 0.504657. $$\n\nThe bar $|$ is read as \"given\". The information after the bar is the given information. In this case, we were interested in the probability a person was a crew member, \"given\" they were male. That is, after restricting to the male passengers (i.e., using a boolean mask as a filter), we want to know the relative frequency of crew members.\n\n\n\nWe can also filter on multiple criteria. For example, if we want to know the fraction of male \\textit{survivors} who were crew members, we need to combine two boolean masks, one based on the column \\verb|gender| and another based on the column \\verb|survived|. The two masks can be combined using the logical operator \\verb|\\&|.\n\n\\begin{lstlisting}[language=Python]\n(df_titanic[\"gender\"] == \"male\") & (df_titanic[\"survived\"] == 1)\n\\end{lstlisting}\n\n\n\n\nNotice that the logical operator was \\textit{broadcast} (that word again!) over the elements of the two \\verb|Series|. In other words, the logical operator was applied to each element, producing a \\verb|Series| of booleans.\n\nNow we can use this new boolean mask to filter the \\verb|DataFrame|, just as we did before.\n\n\\begin{lstlisting}[language=Python]\ndf_male_survivors = df_titanic[(df_titanic[\"gender\"] == \"male\") & (df_titanic[\"survived\"] == 1)]\ndf_male_survivors\n\\end{lstlisting}\n\n\n\n\nBesides $\\verb|&|$, there are two other logical operators that can be used to modify and combine boolean masks.\n\\begin{itemize}\n\\item \n$\\verb|&|$ means \"and\"\n\n\\item \n$\\verb|||$ means \"or\"\n\n\\item \n$\\verb|~|$ means \"not\"\n\n\\end{itemize}\n\nLike $\\verb|&|$, the operators $\\verb|||$ and $\\verb|~|$ are broadcast over the boolean masks.\n\n\n\n\\subsection{Exercises}\\label{2.1.3}\n\n\n\n\\textit{Exercises 1-2 ask you to continue working with the Titanic data set explored in this lesson.}\n\n\n\n1. What proportion of crew members were male? Express your answer using probability notation. How does this proportion differ from the proportion that was calculated in the lesson?\n\n\n\n2. What is the distribution of gender among passengers on the Titanic? What is the distribution of gender among passengers on the Titanic who survived? Express your answers using probability notation.\n\n\n\n\\textit{Exercises 3-5 deal with the OKCupid data set, which consists of user profiles in the San Francisco Bay Area on the dating website OKCupid. This data set is available at the URL https://dlsun.github.io/pods/data/okcupid.csv.}\n\n\n\n3. Make a visualization of the distribution of drinking status.\n\n\n\n4. Create a new variable that indicates whether the user has, likes, or dislikes cats. Visualize the distribution of this variable.\n\n\n\n5. If you were a heterosexual female interested in dating a non-smoker, how many options would you have in this data set?\n\n\n\n\n\n\n\\section{Two-Way Tables and Two Categorical Variables}\\label{2.2}\n\n\n\nData science is all about relationships between variables. How do we summarize and visualize the relationship between two categorical variables?\n\nFor example, what can we say about the relationship between gender and survival on the Titanic?\n\n\\begin{lstlisting}[language=Python]\nimport pandas as pd\ndata_dir = \"http://dlsun.github.io/pods/data/\"\ndf_titanic = pd.read_csv(data_dir + \"titanic.csv\")\n\\end{lstlisting}\n\n\n\n\nWe can summarize each variable individually like we did in the previous lesson.\n\n\\begin{lstlisting}[language=Python]\ndf_titanic[\"gender\"].value_counts()\n\\end{lstlisting}\n\n\n\\begin{lstlisting}[language=Python]\ndf_titanic[\"survived\"].value_counts()\n\\end{lstlisting}\n\n\n\n\nBut this does not tell us how gender interacts with survival. To do that, we need to produce a \\textit{cross-tabulation}, or \"cross-tab\" for short. (Statisticians tend to call this a \\textit{contigency table} or a \\textit{two-way table}.)\n\n\\begin{lstlisting}[language=Python]\npd.crosstab(df_titanic[\"survived\"], df_titanic[\"gender\"])\n\\end{lstlisting}\n\n\n\n\nA cross-tabulation of two categorical variables is a two-dimensional array, with the levels of one variable along the rows and the levels of the other variable along the columns. Each cell in this array contains the number of observations that had a particular combination of levels. So in the Titanic data set, there were 359 females who survived and 1366 males who died. From the cross-tabulation, we can see that there were more females who survived than not, while there were more males who died than not. Clearly, gender had a strong influence on survival because of the Titanic's policy of \"women and children first\".\n\nTo get probabilities instead of counts, we specify \\verb|normalize=True|.\n\n\\begin{lstlisting}[language=Python]\njoint_survived_gender = pd.crosstab(df_titanic[\"survived\"], df_titanic[\"gender\"], \n                                    normalize=True)\njoint_survived_gender\n\\end{lstlisting}\n\n\n\n\nNotice that the four probabilities in this table add up to 1.0. Each of these probabilities is called a joint probability and can be notated, for example, as\n\n$$ P(\\text{female}, \\text{died}) = 0.058903.$$\n\nCollectively, these probabilities make up the \\textit{joint distribution} of the variables \\textbf{survived} and \\textbf{gender}.\n\n\n\n\\subsection{Marginal Distributions}\\label{2.2.1}\n\nIs it possible to recover the distribution of \\textbf{gender} alone from the joint distribution of \\textbf{survived} and \\textbf{gender}?\n\n\n\nYes! We simply sum the probabilities for each \\textbf{gender} over all the possible levels of \\textbf{survived}.\n\n\\begin{align}\nP(\\text{female}) = P(\\text{female}, \\text{died}) + P(\\text{female}, \\text{survived}) &= 0.058903 + 0.162664 = 0.221567 \\\\\nP(\\text{male}) = P(\\text{male}, \\text{died}) + P(\\text{male}, \\text{survived}) &= 0.618940 + 0.159493 = 0.778433\\end{align}\n\n\n\nIn code, this can be achieved by summing the \\verb|DataFrame| \\textit{over} one of the dimensions. We can specify which dimension to sum over, using the \\verb|axis=| argument to \\verb|.sum()|.\n\\begin{itemize}\n\\item \n\\verb|axis=0| refers to the rows. In the current example, \\textbf{survived} is the variable along this axis.\n\n\\item \n\\verb|axis=1| refers to the columns. In the current example, \\textbf{gender} is the variable along this axis.\n\n\\end{itemize}\n\nSince we want to sum \\textit{over} the \\textbf{survived} variable, we specify \\verb|.sum(axis=0)|.\n\n\\begin{lstlisting}[language=Python]\ngender = joint_survived_gender.sum(axis=0)\ngender\n\\end{lstlisting}\n\n\n\n\nWhen calculated from a joint distribution, the distribution of one variable is called a \\textit{marginal distribution}. So the above is the marginal distribution of \\textbf{gender}.\n\nThe name \"marginal distribution\" comes from the fact that it is customary to write these totals in the \\textit{margins} of the table. In fact \\verb|pd.crosstab()| has an argument \\verb|margins=| that automatically adds these margins to the cross-tabulation.\n\n\\begin{lstlisting}[language=Python]\npd.crosstab(df_titanic[\"survived\"], df_titanic[\"gender\"], \n            normalize=True, margins=True)\n\\end{lstlisting}\n\n\n\n\nWhile the margins are useful for display purposes, they actually make computations more difficult, since it is easy to mix up which numbers correspond to joint probabilities and which ones correspond to marginal probabilities.\n\nLikewise, to obtain the marginal distribution of \\textbf{survived}, we sum over the possible levels of \\textbf{gender} (which is the variable along \\verb|axis=1|).\n\n\\begin{lstlisting}[language=Python]\nsurvived = joint_survived_gender.sum(axis=1)\nsurvived\n\\end{lstlisting}\n\n\n\n\nWe can check this answer by calculating the distribution of \\textbf{survived} directly from the original data, using the techniques from the previous lesson.\n\n\\begin{lstlisting}[language=Python]\ndf_titanic[\"survived\"].value_counts(normalize=True)\n\\end{lstlisting}\n\n\n\n\n\\subsection{Conditional Distributions}\\label{2.2.2}\n\nLet's take another look at the joint distribution of \\textbf{survived} and \\textbf{gender}.\n\n\\begin{lstlisting}[language=Python]\njoint_survived_gender\n\\end{lstlisting}\n\n\n\n\nFrom the joint distribution, it is tempting to conclude that females and males did not differ too much in their survival rates, since\n\n$$ P(\\text{female}, \\text{survived}) = 0.162664 $$\n\nis not too different from\n\n$$ P(\\text{male}, \\text{survived}) = 0.159493. $$\n\nThis is because there were 359 women and 352 men who survived, out of 2207 passengers.\n\nBut this is the wrong comparison. The joint probabilities are affected by the baseline gender probabilities, and over three-quarters of the people aboard the Titanic were men. $P(\\text{male}, \\text{survived})$ and $ P(\\text{female}, \\text{survived})$ should not even be close if men were just as likely to survive as women, simply because of the sheer number of men aboard.\n\n\n\nA better comparison is between the conditional probabilities. We ought to compare\n\n$$ P(\\text{survived} | \\text{female}) $$\n\nto\n\n$$ P(\\text{survived} | \\text{male}). $$\n\nTo calculate each conditional probability, we simply divide the joint probability by the marginal probability. That is,\n\n\\begin{align}\nP(\\text{survived} | \\text{female}) = \\frac{P(\\text{female}, \\text{survived})}{P(\\text{female})} &= \\frac{0.162664}{0.221568} = .7341 \\\\\nP(\\text{survived} | \\text{male}) = \\frac{P(\\text{male}, \\text{survived})}{P(\\text{male})} &= \\frac{0.159493}{0.778432} = .2049\\end{align}\n\nThe conditional probabilities expose the stark difference in survival rates. One way to think about conditional probabilities is that they \\textit{adjust} for the baseline gender probabilities. By dividing by $P(\\text{male})$ and $P(\\text{female})$, we adjust for the fact that there were more men and fewer women on the Titanic, thus enabling an apples-to-apples comparison.\n\n\n\nIn code, this can be achieved by dividing the joint distribution by the marginal distribution (of \\textbf{gender}). However, we have to be careful:\n\\begin{itemize}\n\\item \nThe joint distribution is a two-dimensional array. It is stored as a \\verb|DataFrame|.\n\n\\item \nThe marginal distribution (of \\textbf{gender}) is a one-dimensional array. It is stored as a \\verb|Series|.\n\n\\end{itemize}\n\nHow is it possible to divide a two-dimensional object by a one-dimensional object? Only if we \\textit{broadcast} the one-dimensional object over the other dimension. A toy example is illustrated below.\n\n\\begin{align}\n\\begin{bmatrix} 1 & 2 \\\\ 3 & 4 \\\\ 5 & 6 \\end{bmatrix} \\Big/ \\begin{bmatrix} 7 \\\\ 8 \\end{bmatrix} &= \\begin{bmatrix} 1 & 2 \\\\ 3 & 4 \\\\ 5 & 6 \\end{bmatrix}  \\Big/ \\begin{bmatrix} 7 & 8 \\\\ 7 & 8 \\\\ 7 & 8 \\end{bmatrix} \\\\\n&= \\begin{bmatrix} 1/7 & 2/8 \\\\ 3/7 & 4/8 \\\\ 5/7 & 6/8 \\end{bmatrix}\\end{align}\n\nTo do this in \\verb|pandas|, we use the \\verb|.divide()| method, specifying the dimension on which to align the \\verb|Series| with the \\verb|DataFrame|. Since \\textbf{gender} is on \\verb|axis=1| of \\verb|joint_survived_gender|, we align the \\verb|DataFrame| and \\verb|Series| along \\verb|axis=1|.\n\n\\begin{lstlisting}[language=Python]\ncond_survived_gender = joint_survived_gender.divide(gender, axis=1)\n# In this case, joint_survived_gender / gender would also haved worked,\n# but better to play it safe and be explicit about the axis.\n\ncond_survived_gender \n\\end{lstlisting}\n\n\n\n\nEvery probability in this table represents a conditional probability of gender given survival status. So from the table, we can read that\n\n$$ P(\\text{survived} | \\text{female}) = 0.734151. $$\n\nNotice that each row sums to $1.0$---as it must, since given the information that a person was female, there are only two possibilities: she either survived or died.\n\nIn other words, we have a distribution of \\textbf{survived} for each level of \\textbf{gender}. We might wish to compare these two distributions. When we call \\verb|.plot.bar()| on the \\verb|DataFrame|, it will plot the values in each column as a set of bars with its own color.\n\n\\begin{lstlisting}[language=Python]\ncond_survived_gender.plot.bar()\n\\end{lstlisting}\n\n\n\n\nA different way to visualize a conditional distribution is to use a stacked bar graph. Here, we want one bar for females and another for males, each one divided in proportion to the survival rates for that gender. First, let's take a look at the desired graph.\n\n\\begin{lstlisting}[language=Python]\ncond_survived_gender.T.plot.bar(stacked=True)\n\\end{lstlisting}\n\n\n\n\nNow, let's unpack the code that generated this graphic. Recall that \\verb|.plot.bar()| plots each column of a \\verb|DataFrame| in a different color. Here we want different colors for each level of \\textbf{survived}, so we need to swap the rows and columns of \\verb|cond_survived_gender|. In other words, we need the \\textit{transpose} of the \\verb|DataFrame|, which is accomplished using \\verb|.T|.\n\n\\begin{lstlisting}[language=Python]\ncond_survived_gender.T\n\\end{lstlisting}\n\n\n\n\nWhen we call \\verb|.plot.bar()| on this transposed \\verb|DataFrame|, with \\verb|stacked=True|, we obtain the stacked bar graph above.\n\n\n\n\\subsection{Exercises}\\label{2.2.3}\n\n\n\nExercises 1-4 ask you to continue working with the Titanic data set explored in this lesson.\n\n\n\n1. Filter the data to include passengers only. Calculate the joint distribution between a passenger's class and where they embarked.\n\n\n\n2. Using the joint distribution that you calculated in Exercise 1, calculate the following:\n\\begin{itemize}\n\\item \nthe conditional distribution of their class given where they embarked\n\n\\item \nthe conditional distribution of where they embarked given their class\n\n\\end{itemize}\n\nUse the conditional distributions that you calculate to answer the following questions:\n\\begin{itemize}\n\\item \nWhat proportion of 3rd class passengers embarked at Southampton?\n\n\\item \nWhat proportion of Southampton passengers were in 3rd class?\n\n\\end{itemize}\n\n\n\n3. Make a visualization showing the distribution of a passenger's class, given where they embarked.\n\n\n\n4. Compare the survival rates of crew members versus passengers. Which group appears to survive at higher rates?\n\n(\\textit{Hint:} You will have to transform the \\textbf{class} variable to a variable that indicates whether a person was a passenger or a crew member. Refer to the previous lesson.)\n\n\n\nExercises 5-6 ask you to work with the Florida Death Penalty data set, which is available at  \\verb|https://dlsun.github.io/pods/data/death_penalty.csv|. This data set contains information about the races of the defendant and the victim, as well as whether a death penalty verdict was rendered, in 674 homicide trials in Florida between 1976-1987.\n\n\n\n5. Use the joint distribution to summarize the relationship between the defendant's and the victim's races in Florida homicides.\n\n\n\n6. Does there appear to be a relationship between death penalty verdicts and the defendant's race? If so, in what direction?\n\n\n\n\n\n\n\\section{Multi-Way Tables and Simpson's Paradox}\\label{2.3}\n\n\n\nIn the previous lesson, we summarized two categorical variables by cross-tabulating their frequencies.\n\n\\begin{lstlisting}[language=Python]\nimport pandas as pd\ndata_dir = \"http://dlsun.github.io/pods/data/\"\ndf_titanic = pd.read_csv(data_dir + \"titanic.csv\")\n\ndef class_to_type(c):\n  if c in [\"1st\", \"2nd\", \"3rd\"]:\n    return \"passenger\"\n  else:\n    return \"crew\"\ndf_titanic[\"type\"] = df_titanic[\"class\"].map(class_to_type)\n\njoint_type_survived = pd.crosstab(\n    df_titanic[\"type\"],\n    df_titanic[\"survived\"],\n    normalize=True\n)\njoint_type_survived\n\\end{lstlisting}\n\n\\small\\begin{verbatim}\nsurvived          0         1\ntype                         \ncrew       0.307657  0.095605\npassenger  0.370186  0.226552\n\\end{verbatim}\n\n\n\nEach number in this table represents a joint probability. For example:\n$$ P(\\text{crew}, \\text{survived}) = 0.095605. $$\n\nWe might want to know whether crew members or passengers survived at higher rates. To do this, we have to compare the conditional probabilities\n\\begin{align}\nP(\\text{survived} | \\text{crew}) & & \\text{vs.} & & P(\\text{survived} | \\text{passenger}).\\end{align}\n\nIn the last lesson, we learned to calculate conditional distributions using broadcasting.\n\n\\begin{lstlisting}[language=Python]\nsurvived_given_type = joint_type_survived.divide(\n    joint_type_survived.sum(axis=1),\n    axis=0\n)\nsurvived_given_type\n\\end{lstlisting}\n\n\\small\\begin{verbatim}\nsurvived          0         1\ntype                         \ncrew       0.762921  0.237079\npassenger  0.620349  0.379651\n\\end{verbatim}\n\n\n\nFrom the table, it is apparent that passengers survived at much higher rates than crew members:\n$$ P(\\text{survived}|\\text{crew}) = 0.237079 < 0.379651 = P(\\text{survived}|\\text{passenger}). $$\n\n\n\n\\subsection{Communication Corner: Reporting Differences in Probabilities}\\label{2.3.1}\n\n\n\nHow do we report the difference between the two probabilities $23.71\\%$ and $37.97\\%$ above? There are a number of ways:\n\\begin{enumerate}\n\\item \nAs an \\textit{additive change}: \"Passengers were\n$$ 37.97\\% - 23.71\\% = 14.26 \\text{ percentage points} $$\nmore likely to survive than crew members.\"\n\n\\item \nAs a \\textit{relative change} (or \\textit{relative risk}): \"Passengers were\n$$ 37.97\\% \\big/ 23.71\\% = 1.60 \\text{ times} $$\nas likely to survive as crew members.\"\n\n\\item \nWe can translate relative changes to \\textit{percent changes} by subtracting $1$ and multiplying by $100\\%$. So we can rephrase the above as: \"Passengers were\n$$ 100\\% \\times (1.60 - 1.00) = 60\\% $$\nmore likely to survive than crew members.\"\n\n\\item \nAs an \\textit{odds ratio}: \"The odds of a passenger surviving was\n$$ \\frac{37.97\\% \\big/ (100\\% - 37.97\\%)}{23.71\\% \\big/ (100\\% - 23.71\\%)} = 1.97 \\text{ times} $$\ngreater than the odds of a crew member surviving.\"\n\n\\end{enumerate}\n\nNote that additive changes and percent changes should be compared to a baseline of 0.0 (and can be negative), while relative changes and odds ratios should be compared to a baseline of 1.0 (and cannot be negative).\n\nWatch out: it is incorrect to say that passengers are $14.26\\%$ more likely to survive than crew members, since the percent change is $60\\%$. An additive change should always be reported in units of \"percentage points\".\n\n\n\n\\subsection{Controlling for a Variable}\\label{2.3.2}\n\nBut is this the whole story? We know that survival rates for males and females were very different. Will the trend between the survival rates for crew and passengers still hold after we \\textit{control} for \\textbf{gender}?\n\nTo do this, let's determine the joint distribution of these two variables and a third variable, \\textbf{gender}. In principle, the frequencies could be represented using a three-dimensional table, but it is difficult to visualize more than two dimensions on paper or on a screen. So we put two of the variables along one dimension and one variable along the other, creating a \\textit{three-way table}.\n\n\\begin{lstlisting}[language=Python]\njoint_gender_type_survived = pd.crosstab(\n    [df_titanic[\"gender\"], df_titanic[\"type\"]],\n    df_titanic[\"survived\"],\n    normalize=True\n)\njoint_gender_type_survived\n\\end{lstlisting}\n\n\\small\\begin{verbatim}\nsurvived                 0         1\ngender type                         \nfemale crew       0.001359  0.009062\n       passenger  0.057544  0.153602\nmale   crew       0.306298  0.086543\n       passenger  0.312642  0.072950\n\\end{verbatim}\n\n\n\nOf course, we would have chosen any two of the variables to place along the rows, or had the two variables along the columns instead of the rows. The particular representation above was chosen because it makes it easy to survival rates for each gender and type, i.e.,\n$$ P(\\text{survived} | \\textbf{gender}, \\textbf{type}), $$\nwhere \\textbf{gender} is either \"male\" or \"female\" and \\textbf{type} is either \"crew\" or \"passenger\". Recall that the conditional probability is calculated as\n$$ P(\\text{survived} | \\textbf{gender}, \\textbf{type}) = \\frac{P(\\text{survived}, \\textbf{gender}, \\textbf{type})}{P(\\textbf{gender}, \\textbf{type})}. $$\nThe numerator is the joint distribution above. The denominator can be calculated by summing over the possible values of \\textbf{survived}---in other words, across each row, over the columns.\n\n\\begin{lstlisting}[language=Python]\njoint_gender_type = joint_gender_type_survived.sum(axis=1)\njoint_gender_type\n\\end{lstlisting}\n\n\\small\\begin{verbatim}\ngender  type     \nfemale  crew         0.010421\n        passenger    0.211146\nmale    crew         0.392841\n        passenger    0.385591\ndtype: float64\n\\end{verbatim}\n\n\n\nTo obtain the conditional probabilities, we simply divide the joint distribution by the marginal.\n\n\\begin{lstlisting}[language=Python]\nsurvived_given_gender_type = joint_gender_type_survived.divide(\n    joint_gender_type,\n    axis=0\n)\nsurvived_given_gender_type\n\\end{lstlisting}\n\n\\small\\begin{verbatim}\nsurvived                 0         1\ngender type                         \nfemale crew       0.130435  0.869565\n       passenger  0.272532  0.727468\nmale   crew       0.779700  0.220300\n       passenger  0.810811  0.189189\n\\end{verbatim}\n\n\n\nNow, let's compare the survival rates of passengers and crew members for females and males separately.\n\\begin{itemize}\n\\item \nFor females, crew members survived at a higher rate:\n$$ P(\\text{survived} | \\text{female}, \\text{crew}) = 0.869565 > 0.727468 = P(\\text{survived} | \\text{female}, \\text{passenger}) $$\n\n\\item \nFor males, crew members survived at a higher rate:\n$$ P(\\text{survived} | \\text{male}, \\text{crew}) = 0.220300 > 0.189189 = P(\\text{survived} | \\text{male}, \\text{passenger}) $$\n\n\\end{itemize}\n\nBut remember, we found earlier that passengers survived at a higher rate overall:\n$$ P(\\text{survived} | \\text{crew}) < P(\\text{survived} | \\text{passenger}). $$\n\nHow is it possible that both male and female crew members survived at a higher rate, yet crew members survived at a lower rate overall? This surprising phenomenon is known as \\textit{Simpson's paradox}.\n\n\n\n\\subsection{Simpson's Paradox}\\label{2.3.3}\n\nSimpson's paradox is a phenomenon where a trend disappears or reverses when the data is aggregated. In the Titanic data set, both male and female crew members survived at higher rates, but when we aggregated over gender, the trend reversed.\n\nIn order to investigate Simpson's paradox, we first reorganize the probabilities. First, we keep only the survival rate, dropping the death rate (since it is redundant; it is just one minus the survival rate).\n\n\\begin{lstlisting}[language=Python]\nsurvived_given_gender_type[1]\n\\end{lstlisting}\n\n\\small\\begin{verbatim}\ngender  type     \nfemale  crew         0.869565\n        passenger    0.727468\nmale    crew         0.220300\n        passenger    0.189189\nName: 1, dtype: float64\n\\end{verbatim}\n\n\n\nNext, we rearrange these probabilities into a two-way table, with gender along one dimension and type along the other. This can be achieved in code by \"unstacking\" a level of the index. (There are two \"levels\": \\textbf{gender} and \\textbf{type}.)\n\n\\begin{lstlisting}[language=Python]\nsurvival_rates_by_gender_type = (survived_given_gender_type[1].\n                                 unstack(level=\"type\"))\nsurvival_rates_by_gender_type\n\\end{lstlisting}\n\n\\small\\begin{verbatim}\ntype        crew  passenger\ngender                     \nfemale  0.869565   0.727468\nmale    0.220300   0.189189\n\\end{verbatim}\n\n\n\nCaution: the probabilities in this table do not represent a distribution. They do not add up to 1.0. These probabilities originally came from the conditional distribution of \\textbf{survived} given \\textbf{gender} and \\textbf{type}, but we dropped the death rates from the data.\n\nFinally, we append the overall survival rates (which we calculated at the beginning of this lesson) to the last row of this \\verb|DataFrame|.\n\n\\begin{lstlisting}[language=Python]\nsurvival_rates_by_gender_type.append(survived_given_type[1])\n\\end{lstlisting}\n\n\\small\\begin{verbatim}\ntype        crew  passenger\ngender                     \nfemale  0.869565   0.727468\nmale    0.220300   0.189189\n1       0.237079   0.379651\n\\end{verbatim}\n\n\n\nThe overall survival rates are weighted averages of the survival rates for each gender. If we look at the survival rates for crew members:\n\\begin{itemize}\n\\item \nThe survival rate for female crew is 87.0%.\n\n\\item \nThe survival rate for male crew is 22.0%.\n\n\\item \nThe overall survival rate for all crew is 23.7%, which is between the gender-specific survival rates, but much closer to the survival rate for male crew.\n\n\\end{itemize}\n\nLikewise, if we look at the survival rates for passengers:\n\\begin{itemize}\n\\item \nThe survival rate for female crew is 72.7%.\n\n\\item \nThe survival rate for male crew is 18.9%.\n\n\\item \nThe overall survival rate for all crew is 38.0%, which is closer to the middle of the gender-specific survival rates.\n\n\\end{itemize}\n\nWhy would the survival rate for crew members be so close to the survival rate for male crew? To answer this question, let's examine the weights that go into this weighted average.\n\n\n\nIn mathematical notation, the overall survival rate can be decomposed as:\n$$ \\underbrace{P(\\text{survived} | \\textbf{type})}_{\\text{overall survival rate}} = \\sum_{\\textbf{gender}} \\underbrace{P(\\textbf{gender} | \\textbf{type})}_{\\text{weight}} \\underbrace{P(\\text{survived} | \\textbf{gender}, \\textbf{type})}_{\\text{gender-specific survival rate}}. $$\nSo we see that the weights are $P(\\textbf{gender} | \\textbf{type})$.\n\nFirst, we calculate this conditional distribution from the joint distribution of \\textbf{gender} and \\textbf{type}.\n\n\\begin{lstlisting}[language=Python]\njoint_gender_type = pd.crosstab(\n    df_titanic[\"gender\"],\n    df_titanic[\"type\"],\n    normalize=True\n)\n\ngender_given_type = joint_gender_type.divide(\n    joint_gender_type.sum(axis=0),\n    axis=1\n)\ngender_given_type\n\\end{lstlisting}\n\n\\small\\begin{verbatim}\ntype        crew  passenger\ngender                     \nfemale  0.025843   0.353834\nmale    0.974157   0.646166\n\\end{verbatim}\n\n\n\nNotice that 97.4% of crew members were male! So the lower male survival rate is going to dominate the weighted average when we calculate the overall survival rate for crew members. On the other hand, the gender ratio for passengers was more balanced, so their overall survival rate will end up being closer to the middle of the male and female survival rates.\n\nNow, we calculate the weighted average, using the conditional distribution of gender as \"weights\" that we multiply by the survival rates. Then, we sum over the genders to get the weighted averages---i.e., the overall survival rates.\n\n\\begin{lstlisting}[language=Python]\n(gender_given_type * survival_rates_by_gender_type).sum(axis=0)\n\\end{lstlisting}\n\n\\small\\begin{verbatim}\ntype\ncrew         0.237079\npassenger    0.379651\ndtype: float64\n\\end{verbatim}\n\n\n\nCheck that these match the overall survival rates that we calculated above.\n\nSo the secret of Simpson's Paradox lies in two facts:\n\\begin{enumerate}\n\\item \nSurvival rates were generally much lower for men than for women.\n\n\\item \nBecause crew members were predominantly male, their survival rate was weighted towards the lower male survival rate, that their overall survival rate ended up being lower than the survival rate for passengers.\n\n\\end{enumerate}\n\nSimpson's Paradox means that we have to be careful when comparing proportions from a two-way table, such as survival rates for crew and passengers. When we control for a third variable, such as \\textbf{gender}, the direction of the effect could change!\n\n\n\n\\subsection{Exercises}\\label{2.3.4}\n\n\n\n1. Calculate the \\textit{percent change} in survival rates between passengers and crew members, controlling for where they embarked. Does there appear to be a Simpson's paradox effect here?\n\n\n\nExercise 2 asks you to work with the Florida Death Penalty data set, which is available at  \\verb|https://dlsun.github.io/pods/data/death_penalty.csv|. This data set contains information about the races of the defendant and the victim, as well as whether a death penalty verdict was rendered, in 674 homicide trials in Florida between 1976-1987.\n\n\n\n2. Calculate the \\textit{relative risk} of a death penalty verdict for black defendants (relative to white defendants), adjusting for the race of the victim. How does this compare to what you found at the end of the last chapter? Can you explain intuitively what is going on?\n\n\n\n", "meta": {"hexsha": "c54e23ccf32cf7aa2fb36159d41c376c9c678e35", "size": 38679, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "LatexBook/TesterBook/02_Categorical_Data/out.tex", "max_stars_repo_name": "bfkwong/Latex-Book-Parser", "max_stars_repo_head_hexsha": "07ed107b785c7297eb4a41bbf337bc006a14f00c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LatexBook/TesterBook/02_Categorical_Data/out.tex", "max_issues_repo_name": "bfkwong/Latex-Book-Parser", "max_issues_repo_head_hexsha": "07ed107b785c7297eb4a41bbf337bc006a14f00c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-07-06T00:12:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-06T01:53:58.000Z", "max_forks_repo_path": "LatexBook/TesterBook/02_Categorical_Data/out.tex", "max_forks_repo_name": "bfkwong/Latex-Book-Parser", "max_forks_repo_head_hexsha": "07ed107b785c7297eb4a41bbf337bc006a14f00c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9950884086, "max_line_length": 623, "alphanum_fraction": 0.7407637219, "num_tokens": 10142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.615087848460224, "lm_q1q2_score": 0.3291325411783892}}
{"text": "\\documentclass[a4paper, 11pt]{article}\n\\usepackage{graphicx,wrapfig,subfigure,amsmath,amssymb,epsfig,bm}\n\\usepackage{listings,textcomp,color,geometry}\n\\geometry{hmargin=2cm, vmargin=2cm}\n\n\\def\\Box{\\mathord{\\dalemb{7.9}{8}\\hbox{\\hskip1pt}}}\n\\def\\dalemb#1#2{{\\vbox{\\hrule height.#2pt\n        \\hbox{\\vrule width.#2pt height#1pt \\kern#1pt \\vrule width.#2pt}\n        \\hrule height.#2pt}}}\n\n\\def\\eop{\\mathcal{E}}\n\\def\\bop{\\mathcal{B}}\n\\def\\ba{\\begin{eqnarray}}\n\\def\\ea{\\end{eqnarray}}\n\\def\\be{\\begin{equation}}\n\\def\\ee{\\end{equation}}\n\\def\\tr{{\\rm tr}}\n\\def\\Var{{\\rm Var}}\n\\def\\gtorder{\\mathrel{\\raise.3ex\\hbox{$>$}\\mkern-14mu\n             \\lower0.6ex\\hbox{$\\sim$}}}\n\\def\\ltorder{\\mathrel{\\raise.3ex\\hbox{$<$}\\mkern-14mu\n             \\lower0.6ex\\hbox{$\\sim$}}}\n\n\\def\\bb{{\\mathfrak b}}\n\\newcommand{\\ellb }{\\boldsymbol{\\ell }}\n\n% Personal colors defined here\n\\newcommand{\\skn}[1]{{\\color{red}#1}}\n\\newcommand{\\TIB}[1]{{\\color{blue}#1}}\n\\newcommand{\\assume}[1]{{\\bf#1}}\n\n\\begin{document}\n\n\\title{Birefringence}\n\\maketitle\n\n\\section{Why Birefringence}\n\nFrom WMAP Komatsu paper:\nSince the temperature and E-mode polarization are\nparity-even and the B-mode polarization is parity-odd, the TB and EB correlations should vanish in a universe that conserves parity. For this reason the TB and EB correlations are usually used to check for systematics, and not widely used as a cosmological probe.\nPolarization of photons offers a powerful way of probing the cosmological parity violation, or the “cosmological birefringence”. Let us consider a parity-violating interaction term in the Lagrangian such as the Chern-Simons term ${\\cal L}_{CS}= -\\frac{1}{2}p_{\\alpha}A_{\\beta}{\\tilde F}^{\\alpha \\beta}$ where $F^{\\alpha \\beta}$ and $A_{\\beta}$ are the usual electromagnetic tensor and vector potential, ${\\tilde F}^{\\alpha \\beta}$ is the dual tensor and $p_{\\alpha}$ is an arbitrary timelike vector. This Chern-Simons term makes two polarization states of photons propagate with different group velocities, causing the polarization plane to rotate by an angle $\\alpha$ (Carroll 1990). $p_{\\alpha}$ can be sources by a scalar field. Such a field might have something to do with dark energy, for example. We are therefore looking at a potential parity-violating interaction between the visible section (i.e., photons) and dark sector (i.e., dark energy)\n\n\\section{Effects of Birefringence on the Power Spectra}\n\n(from 1904.12440)\nWhen polarisation angles are rotated uniformly over the sky by an angle $\\alpha$, spherical harmonics coefficients of the observed E- and B-mode polarisation, denoted by \"o\", are related\nto the intrinsic ones by\n\\ba\na_{\\ell m}^{E, o} &=& a_{\\ell m}^{E} \\cos 2\\alpha - a_{\\ell m}^{B} \\sin 2\\alpha  \\nonumber \\\\\na_{\\ell m}^{B, o} &=& a_{\\ell m}^{E} \\sin 2\\alpha + a_{\\ell m}^{B} \\cos 2\\alpha\n\\ea\nFor the power spectra, we obtained\n\\ba\nC^{EE,o}_{\\ell} &=&  C^{EE}_{\\ell} \\cos^{2} 2\\alpha + C^{BB}_{\\ell} \\sin^{2} 2\\alpha -  C^{EB}_{\\ell} \\sin 4\\alpha \\nonumber \\\\\nC^{BB,o}_{\\ell} &=&  C^{EE}_{\\ell} \\sin^{2} 2\\alpha + C^{BB}_{\\ell} \\cos^{2} 2\\alpha + C^{EB}_{\\ell} \\sin 4\\alpha \\nonumber \\\\\nC^{EB,o}_{\\ell} &=&  C^{EE}_{\\ell} \\sin 2\\alpha  \\cos 2\\alpha. - C^{BB}_{\\ell} \\sin 2\\alpha  \\cos 2\\alpha + C^{EB}_{\\ell}(\\cos^{2} 2\\alpha - \\sin^{2} 2\\alpha) \\nonumber \\\\\nC^{EB,o}_{\\ell} &=&  \\frac{\\sin 4 \\alpha}{2} (C^{EE}_{\\ell} . - C^{BB}_{\\ell} ) + \\cos 4\\alpha \\ C^{EB}_{\\ell}\n\\ea\nWe can relate the observed EB power spectrum to the observed EE and BB power spectrum\n\\ba\nC^{EB,o}_{\\ell} &=&  \\frac{1}{2} ( C^{EE,o}_{\\ell} - C^{BB,o}_{\\ell} ) \\tan 4\\alpha  + \\frac{ C^{EB}_{\\ell}}{\\cos 4 \\alpha}\n\\ea\nindeed\n\\ba\nC^{EB,o}_{\\ell} &=&  \\frac{1}{2} ( C^{EE}_{\\ell} \\cos^{2} 2\\alpha + C^{BB}_{\\ell} \\sin^{2} 2\\alpha -  C^{EB}_{\\ell} \\sin 4\\alpha - C^{EE}_{\\ell} \\sin^{2} 2\\alpha - C^{BB}_{\\ell} \\cos^{2} 2\\alpha - C^{EB}_{\\ell} \\sin 4\\alpha \\nonumber) \\tan 4\\alpha  \\nonumber \\\\\n &+& \\frac{ C^{EB}_{\\ell}}{\\cos 4 \\alpha} \\nonumber \\\\\n&=&   \\frac{1}{2} ( C^{EE}_{\\ell}  - C^{BB}_{\\ell} ) \\sin 4\\alpha + C^{EB}_{\\ell}  (\\frac{1 - \\sin^{2}  4 \\alpha}{\\cos 4 \\alpha} ) = \\frac{1}{2} ( C^{EE}_{\\ell}  - C^{BB}_{\\ell} ) \\sin 4\\alpha + C^{EB}_{\\ell}  \\cos 4 \\alpha  \n\\ea \n\n\n\\section{Likelihood}\n\n\nAssuming the intrinsic EB is equal to zero, we can therefore form two different $\\chi^{2}$ \n\\ba\n\\chi^{2} (\\alpha)_{\\rm data} &=& \\sum_{bb'} \\left[C^{EB,o}_{b} -  \\frac{1}{2} ( C^{EE,o}_{b} - C^{BB,o}_{b} ) \\tan 4\\alpha \\right] \\Xi^{-1}_{bb'} \\left[ C^{EB,o}_{b'} -  \\frac{1}{2} ( C^{EE,o}_{b'} - C^{BB,o}_{b'} ) \\tan 4\\alpha \\right] \\\\\n\\chi^{2} (\\alpha)_{\\rm th} &=& \\sum_{bb'} \\left[C^{EB, o}_{b} -  \\frac{1}{2} ( C^{EE}_{b} - C^{BB}_{b} ) \\sin 4\\alpha \\right] \\Xi^{-1}_{bb'} \\left[C^{EB, o}_{b} -  \\frac{1}{2} ( C^{EE}_{b} - C^{BB}_{b} ) \\sin 4\\alpha \\right]\n\\ea\n\n\\section{Fisher}\n\\ba\nF_{\\alpha \\alpha} &=& \\left \\langle \\frac{ \\partial^{2} {\\cal L} }{ \\partial^{2}{\\alpha} }\\right \\rangle \\Bigr\\rvert_{\\alpha=0} = 4 \\sum_{bb'}( C^{EE,o}_{b} - C^{BB,o}_{b} ) \\Xi^{-1}_{bb'} ( C^{EE,o}_{b'} - C^{BB,o}_{b'} ) \\\\\n\\sigma_{\\alpha} &=& \\frac{1}{2} ( \\sum_{bb'}( C^{EE,o}_{b} - C^{BB,o}_{b} ) \\Xi^{-1}_{bb'} ( C^{EE,o}_{b'} - C^{BB,o}_{b'} ))^{-1/2}\n\\ea\n\n\\section{Separating CMB and foregrounds}\n\nThe foregrounds are sensitive to the instrumental miscalibrated angle but is not sensitive to the cosmic birefringence (because fg is at redshift zero) we can therefore separate CMB and fg.\nNow let's call $\\alpha$ the instrumental miscalibrated angle and $\\beta$ the birefringence angle\n\\ba\na_{\\ell m}^{E, o} &=& a^{\\rm fg, E}_{\\ell m} \\cos (2\\alpha) - a^{\\rm fg, B}_{\\ell m} \\sin (2\\alpha)  + a^{\\rm CMB, E}_{\\ell m} \\cos (2\\alpha + 2\\beta) - a^{\\rm CMB, B}_{\\ell m} \\sin (2\\alpha + 2\\beta) + a_{\\ell m}^{E, N} \\nonumber \\\\\na_{\\ell m}^{B, o} &=& a^{\\rm fg, E}_{\\ell m} \\sin (2\\alpha) + a^{\\rm fg, B}_{\\ell m} \\cos (2\\alpha) + a^{\\rm CMB, E}_{\\ell m} \\sin (2\\alpha + 2\\beta ) + a^{\\rm CMB, B}_{\\ell m} \\cos (2\\alpha + 2\\beta) + a_{\\ell m}^{B, N}\n\\ea\nAssuming we form cross spectra\n\\ba\nC^{EE,o}_{\\ell} &=& \\langle( a^{\\rm fg, E}_{\\ell m} \\cos (2\\alpha) - a^{\\rm fg, B}_{\\ell m} \\sin (2\\alpha)  + a^{\\rm CMB, E}_{\\ell m} \\cos (2\\alpha + 2\\beta) - a^{\\rm CMB, B}_{\\ell m} \\sin (2\\alpha + 2\\beta)) \\nonumber \\\\\n&\\times& (a^{\\rm fg, E}_{\\ell m} \\cos (2\\alpha) - a^{\\rm fg, B}_{\\ell m} \\sin (2\\alpha)  + a^{\\rm CMB, E}_{\\ell m} \\cos (2\\alpha + 2\\beta) - a^{\\rm CMB, B}_{\\ell m} \\sin (2\\alpha + 2\\beta)) \\rangle \\nonumber \\\\\n&=& C^{\\rm EE, fg}_{\\ell} \\cos^{2} (2\\alpha) + C^{\\rm BB, fg}_{\\ell} \\sin^{2} (2\\alpha) + C^{\\rm EE, CMB}_{\\ell} \\cos^{2} (2\\alpha + 2\\beta)   + C^{\\rm BB, CMB}_{\\ell} \\sin^{2} (2\\alpha + 2\\beta)  \\nonumber \\\\\n&-& 2 C^{\\rm EB, fg}_{\\ell} \\cos (2\\alpha)\\sin (2\\alpha) -  2 C^{\\rm EB, CMB}_{\\ell} \\cos (2\\alpha + 2\\beta)\\sin (2\\alpha + 2\\beta)  \\nonumber \\\\\nC^{BB,o}_{\\ell}  &=& C^{\\rm EE, fg}_{\\ell} \\sin^{2} (2\\alpha) + C^{\\rm BB, fg}_{\\ell} \\cos^{2} (2\\alpha) + C^{\\rm EE, CMB}_{\\ell} \\sin^{2} (2\\alpha + 2\\beta)   + C^{\\rm BB, CMB}_{\\ell} \\cos^{2} (2\\alpha + 2\\beta)  \\nonumber \\\\\n&+& 2 C^{\\rm EB, fg}_{\\ell} \\cos (2\\alpha)\\sin (2\\alpha) +  2 C^{\\rm EB, CMB}_{\\ell} \\cos (2\\alpha + 2\\beta)\\sin (2\\alpha + 2\\beta)  \\nonumber \\\\\n\\ea\nAnd\n\\ba\nC^{EB,o}_{\\ell} &=&  \\langle( a^{\\rm fg, E}_{\\ell m} \\cos (2\\alpha) - a^{\\rm fg, B}_{\\ell m} \\sin (2\\alpha)  + a^{\\rm CMB, E}_{\\ell m} \\cos (2\\alpha + 2\\beta) - a^{\\rm CMB, B}_{\\ell m} \\sin (2\\alpha + 2\\beta)) \\nonumber \\\\\n&\\times& (a^{\\rm fg, E}_{\\ell m} \\sin (2\\alpha) + a^{\\rm fg, B}_{\\ell m} \\cos (2\\alpha)  + a^{\\rm CMB, E}_{\\ell m} \\sin (2\\alpha + 2\\beta) + a^{\\rm CMB, B}_{\\ell m} \\cos (2\\alpha + 2\\beta)) \\rangle \\nonumber \\\\\n&=&  C^{\\rm EE, fg}_{\\ell} \\cos (2\\alpha) \\sin (2\\alpha)  - C^{\\rm BB, fg}_{\\ell} \\sin (2\\alpha) \\cos (2\\alpha) + C^{\\rm EE, CMB}_{\\ell} \\cos (2\\alpha +2 \\beta) \\sin (2\\alpha +2 \\beta)  \\nonumber \\\\\n&-& C^{\\rm BB, CMB}_{\\ell} \\sin (2\\alpha + 2\\beta) \\cos (2\\alpha + 2\\beta)  +  C^{\\rm EB, fg}_{\\ell} ( \\cos^{2} (2\\alpha) - \\sin^{2} (2\\alpha) )  \\nonumber \\\\\n&+&  C^{\\rm EB, CMB}_{\\ell} ( \\cos^{2} (2\\alpha + 2\\beta) - \\sin^{2} (2\\alpha + 2 \\beta)) \\nonumber \\\\\nC^{EB,o}_{\\ell} &=& \\frac{\\sin(4\\alpha)}{2}(C^{\\rm EE, fg}_{\\ell}  - C^{\\rm BB, fg}_{\\ell} ) + \\frac{\\sin(4\\alpha + 4\\beta)}{2}(C^{\\rm EE, CMB}_{\\ell}  - C^{\\rm BB, CMB}_{\\ell} )  \\nonumber \\\\\n&+& \\cos(4\\alpha) C^{\\rm EB, fg}_{\\ell} + \\cos(4\\alpha + 4\\beta) C^{\\rm EB, CMB}_{\\ell} \n\\ea\nLet's demonstrate that we can refactorize $C^{EB,o}_{\\ell}$ as \n\\ba\nC^{EB,o}_{\\ell} &=& \\frac{\\tan(4\\alpha)}{2} \\left( C^{EB,o}_{\\ell} - C^{BB,o}_{\\ell} \\right) + \\frac{ \\sin(4\\beta)}{2 \\cos(4\\alpha)}( C^{\\rm EE, CMB}_{\\ell} - C^{\\rm BB, CMB}_{\\ell}) \\nonumber \\\\\n&+& \\frac{1}{\\cos(4\\alpha)} C^{\\rm EB, fg}_{\\ell}  + \\frac{ \\cos(4\\beta)}{ \\cos(4\\alpha)} C^{\\rm EB, CMB}_{\\ell} \n\\ea\nWe can expand \n\\ba\n \\left( C^{EE,o}_{\\ell} - C^{BB,o}_{\\ell} \\right) &=&   C^{\\rm EE, fg}_{\\ell} \\cos^{2} (2\\alpha) + C^{\\rm BB, fg}_{\\ell} \\sin^{2} (2\\alpha) + C^{\\rm EE, CMB}_{\\ell} \\cos^{2} (2\\alpha + 2\\beta)   \\nonumber \\\\\n &+& C^{\\rm BB, CMB}_{\\ell} \\sin^{2} (2\\alpha + 2\\beta)  - 2 C^{\\rm EB, fg}_{\\ell} \\cos (2\\alpha)\\sin (2\\alpha) -  2 C^{\\rm EB, CMB}_{\\ell} \\cos (2\\alpha + 2\\beta)\\sin (2\\alpha + 2\\beta)  \\nonumber \\\\\n&-& C^{\\rm EE, fg}_{\\ell} \\sin^{2} (2\\alpha) - C^{\\rm BB, fg}_{\\ell} \\cos^{2} (2\\alpha) - C^{\\rm EE, CMB}_{\\ell} \\sin^{2} (2\\alpha + 2\\beta)   - C^{\\rm BB, CMB}_{\\ell} \\cos^{2} (2\\alpha + 2\\beta)  \\nonumber \\\\\n&-& 2 C^{\\rm EB, fg}_{\\ell} \\cos (2\\alpha)\\sin (2\\alpha) -  2 C^{\\rm EB, CMB}_{\\ell} \\cos (2\\alpha + 2\\beta)\\sin (2\\alpha + 2\\beta) \\nonumber \\\\\n&=&   \\cos (4\\alpha) (C^{\\rm EE, fg}_{\\ell}  - C^{\\rm BB, fg}_{\\ell} ) + \\cos (4\\alpha + 4\\beta) (C^{\\rm EE, CMB}_{\\ell}  - C^{\\rm BB, CMB}_{\\ell} ) \\nonumber \\\\\n&-& 2 C^{\\rm EB, fg}_{\\ell} \\sin (4\\alpha) - 2 C^{\\rm EB, CMB}_{\\ell} \\sin (4\\alpha + 4\\beta)\n\\ea\nso that\n\\ba\nC^{EB,o}_{\\ell} &=& \\frac{\\sin(4\\alpha)}{2}  (C^{\\rm EE, fg}_{\\ell}  - C^{\\rm BB, fg}_{\\ell} ) +  \\frac{\\tan(4\\alpha)}{2} \\cos (4\\alpha + 4\\beta) (C^{\\rm EE, CMB}_{\\ell}  - C^{\\rm BB, CMB}_{\\ell} ) \\nonumber \\\\\n&-& C^{\\rm EB, fg}_{\\ell} \\sin (4\\alpha )\\tan(4\\alpha)  - C^{\\rm EB, CMB}_{\\ell} \\sin (4\\alpha + 4\\beta)\\tan(4\\alpha)  + \\frac{ \\sin(4\\beta)}{2 \\cos(4\\alpha)}( C^{\\rm EE, CMB}_{\\ell} - C^{\\rm BB, CMB}_{\\ell}) \\nonumber \\\\\n&+& \\frac{1}{\\cos(4\\alpha)} C^{\\rm EB, fg}_{\\ell}  + \\frac{ \\cos(4\\beta)}{ \\cos(4\\alpha)} C^{\\rm EB, CMB}_{\\ell}  \\nonumber \\\\\n&=& \\frac{\\sin(4\\alpha)}{2}  (C^{\\rm EE, fg}_{\\ell}  - C^{\\rm BB, fg}_{\\ell} )  +  (C^{\\rm EE, CMB}_{\\ell}  - C^{\\rm BB, CMB}_{\\ell} )\\left( \\frac{\\tan(4\\alpha)}{2} \\cos (4\\alpha + 4\\beta) + \\frac{ \\sin(4\\beta)}{2 \\cos(4\\alpha)}\\right) \\nonumber \\\\\n&+& \\left( \\frac{1}{\\cos(4\\alpha)} - \\sin (4\\alpha )\\tan(4\\alpha) \\right) C^{\\rm EB, fg}_{\\ell} + \\left(\\frac{ \\cos(4\\beta)}{ \\cos(4\\alpha)} - \\sin (4\\alpha + 4\\beta)\\tan(4\\alpha) \\right) C^{\\rm EB, CMB}_{\\ell}\n\\ea\nLet's do some trigometry\n\\ba\n \\frac{1}{\\cos(4\\alpha)} - \\sin (4\\alpha )\\tan(4\\alpha)  &=& \\cos(4\\alpha) \\nonumber \\\\\n \\frac{ \\cos(4\\beta)}{ \\cos(4\\alpha)} - \\sin (4\\alpha + 4\\beta)\\tan(4\\alpha)   &=&  \\frac{ \\cos(4\\beta)}{ \\cos(4\\alpha)}  - (\\sin (4\\alpha) \\cos(4\\beta)+ \\sin (4\\beta) \\cos(4\\alpha) )\\tan(4\\alpha) \\nonumber \\\\\n &=&  \\frac{ \\cos(4\\beta)}{ \\cos(4\\alpha)}   - \\left(\\sin^{2} (4\\alpha)\\frac{ \\cos(4\\beta)}{ \\cos(4\\alpha)}+ \\sin (4\\beta) \\sin(4\\alpha) \\right) \\nonumber \\\\\n &=&  \\frac{ \\cos(4\\beta)}{ \\cos(4\\alpha)}(1 - \\sin^{2} (4\\alpha)) - \\sin (4\\beta) \\sin(4\\alpha) )  \\nonumber \\\\\n &=&  \\cos(4\\beta) \\cos(4\\alpha) -  \\sin (4\\beta) \\sin(4\\alpha)  = \\cos(4\\beta + 4\\alpha) \\nonumber \\\\\n  \\frac{\\tan(4\\alpha)}{2} \\cos (4\\alpha + 4\\beta) + \\frac{ \\sin(4\\beta)}{2 \\cos(4\\alpha)} &=&    \\frac{\\tan(4\\alpha)}{2} [\\cos (4\\alpha) \\cos( 4\\beta)- \\sin(4\\alpha) \\sin( 4\\beta) ]+ \\frac{ \\sin(4\\beta)}{2 \\cos(4\\alpha)} \\nonumber \\\\\n &=& \\frac{\\sin (4\\alpha) \\cos( 4\\beta)}{2} - \\frac{ \\sin^{2}(4\\alpha) \\sin( 4\\beta) }{2 \\cos(4 \\alpha)} + \\frac{ \\sin(4\\beta)}{2 \\cos(4\\alpha)} \\nonumber \\\\\n &=& \\frac{\\sin (4\\alpha) \\cos( 4\\beta)}{2}  -  \\frac{ \\sin(4\\beta)}{2 \\cos(4\\alpha)}  ( \\sin^{2}(4\\alpha)-1)  \\nonumber \\\\\n &=& \\frac{\\sin (4\\alpha) \\cos( 4\\beta)}{2}  + \\frac{\\cos (4\\alpha) \\sin( 4\\beta)}{2} = \\frac{ \\sin(4\\alpha + 4\\beta)}{2}\n\\ea \nWith this, we demonstrate that \n\\ba\nC^{EB,o}_{\\ell} &=& \\frac{\\tan(4\\alpha)}{2} \\left( C^{EB,o}_{\\ell} - C^{BB,o}_{\\ell} \\right) + \\frac{ \\sin(4\\beta)}{2 \\cos(4\\alpha)}( C^{\\rm EE, CMB}_{\\ell} - C^{\\rm BB, CMB}_{\\ell}) \\nonumber \\\\\n&+& \\frac{1}{\\cos(4\\alpha)} C^{\\rm EB, fg}_{\\ell}  + \\frac{ \\cos(4\\beta)}{ \\cos(4\\alpha)} C^{\\rm EB, CMB}_{\\ell} \n\\ea\nis indeed equal to\n\\ba\nC^{EB,o}_{\\ell} &=& \\frac{\\sin(4\\alpha)}{2}(C^{\\rm EE, fg}_{\\ell}  - C^{\\rm BB, fg}_{\\ell} ) + \\frac{\\sin(4\\alpha + 4\\beta)}{2}(C^{\\rm EE, CMB}_{\\ell}  - C^{\\rm BB, CMB}_{\\ell} )  \\nonumber \\\\\n&+& \\cos(4\\alpha) C^{\\rm EB, fg}_{\\ell} + \\cos(4\\alpha + 4\\beta) C^{\\rm EB, CMB}_{\\ell} \n\\ea\nwhich complete the proof.\n\n\n\\section{A Multifrequency likelihood}\nWe can rewrite \n\\ba\nC^{EE,o}_{\\ell} &=& C^{\\rm EE, fg}_{\\ell} \\cos^{2} (2\\alpha) + C^{\\rm BB, fg}_{\\ell} \\sin^{2} (2\\alpha) + C^{\\rm EE, CMB}_{\\ell} \\cos^{2} (2\\alpha + 2\\beta)   + C^{\\rm BB, CMB}_{\\ell} \\sin^{2} (2\\alpha + 2\\beta)  \\nonumber \\\\\n&-& 2 C^{\\rm EB, fg}_{\\ell} \\cos (2\\alpha)\\sin (2\\alpha) -  2 C^{\\rm EB, CMB}_{\\ell} \\cos (2\\alpha + 2\\beta)\\sin (2\\alpha + 2\\beta)  \\nonumber \\\\\nC^{BB,o}_{\\ell}  &=& C^{\\rm EE, fg}_{\\ell} \\sin^{2} (2\\alpha) + C^{\\rm BB, fg}_{\\ell} \\cos^{2} (2\\alpha) + C^{\\rm EE, CMB}_{\\ell} \\sin^{2} (2\\alpha + 2\\beta)   + C^{\\rm BB, CMB}_{\\ell} \\cos^{2} (2\\alpha + 2\\beta)  \\nonumber \\\\\n&+& 2 C^{\\rm EB, fg}_{\\ell} \\cos (2\\alpha)\\sin (2\\alpha) +  2 C^{\\rm EB, CMB}_{\\ell} \\cos (2\\alpha + 2\\beta)\\sin (2\\alpha + 2\\beta)  \\nonumber \\\\\nC^{EB,o}_{\\ell} &=& \\frac{\\sin(4\\alpha)}{2}(C^{\\rm EE, fg}_{\\ell}  - C^{\\rm BB, fg}_{\\ell} ) + \\frac{\\sin(4\\alpha + 4\\beta)}{2}(C^{\\rm EE, CMB}_{\\ell}  - C^{\\rm BB, CMB}_{\\ell} )  \\nonumber \\\\\n&+& \\cos(4\\alpha) C^{\\rm EB, fg}_{\\ell} + \\cos(4\\alpha + 4\\beta) C^{\\rm EB, CMB}_{\\ell} \n\\ea\nIn a matricial form, let's neglect intrinsic EB correlation\n\\ba\n\\begin{pmatrix} \nC^{\\rm E_{i}E_{j},o}_{\\ell} \\cr\nC^{\\rm B_{i}B_{j},o}_{\\ell}\n\\end{pmatrix}\n&=&\n{\\bm R}(\\alpha_{i}, \\alpha_{j}) \n\\begin{pmatrix} \nC^{\\rm E_{i}E_{j},fg}_{\\ell} \\cr\nC^{\\rm B_{i}B_{j},fg}_{\\ell}\n\\end{pmatrix}\n+\n{\\bm R}(\\alpha_{i} + \\beta, \\alpha_{j}+ \\beta) \n\\begin{pmatrix} \nC^{\\rm E_{i}E_{j},CMB}_{\\ell} \\cr\nC^{\\rm B_{i}B_{j},CMB}_{\\ell}\n\\end{pmatrix} \\nonumber \\\\\nC^{\\rm E_{i}B_{j},o}_{\\ell} &=& \\vec{R}^{T} (\\alpha_{i}, \\alpha_{j}) \n\\begin{pmatrix} \nC^{\\rm E_{i}E_{j},fg}_{\\ell} \\cr\nC^{\\rm B_{i}B_{j},fg}_{\\ell}\n\\end{pmatrix}\n+ \n\\vec{R}^{T} (\\alpha_{i} + \\beta, \\alpha_{j}+ \\beta ) \n\\begin{pmatrix} \nC^{\\rm E_{i}E_{j},CMB}_{\\ell} \\cr\nC^{\\rm B_{i}B_{j},CMB}_{\\ell}\n\\end{pmatrix}\n\\ea\nWith  ${\\bm R}$ a rotation matrix and $\\vec{R}$ a rotation vector \n\\ba\n{\\bm R}(\\alpha_{i}, \\alpha_{j})  =\n\\begin{pmatrix} \n\\cos(2\\alpha_{i}) \\cos(2\\alpha_{j}) &\n\\sin(2\\alpha_{i}) \\sin(2\\alpha_{j}) \\cr\n\\sin(2\\alpha_{i}) \\sin(2\\alpha_{j}) &\n\\cos(2\\alpha_{i}) \\cos(2\\alpha_{j}) \n\\end{pmatrix}\n\\ea\n\\ba\n\\vec{R} (\\alpha_{i}, \\alpha_{j}) =\n\\begin{pmatrix} \n\\cos(2\\alpha_{i}) \\sin(2\\alpha_{j}) \\cr\n-\\sin(2\\alpha_{i}) \\cos(2\\alpha_{j}) \n\\end{pmatrix}\n\\ea\nWe can simply re-express $C^{EB,o}_{\\ell} $ as a function of $C^{EE,o}_{\\ell} $ and $C^{BB,o}_{\\ell} $ using the equation above\n\\ba\nC^{\\rm E_{i}B_{j},o}_{\\ell} &=& \\vec{R}^{T} (\\alpha_{i}, \\alpha_{j}) \\left[ {\\bm R}^{-1}(\\alpha_{i}, \\alpha_{j})  \n\\begin{pmatrix} \nC^{\\rm E_{i}E_{j},o}_{\\ell} \\cr\nC^{\\rm B_{i}B_{j},o}_{\\ell}\n\\end{pmatrix} \n- {\\bm R}^{-1}(\\alpha_{i}, \\alpha_{j}) \n{\\bm R}(\\alpha_{i} + \\beta, \\alpha_{j}+ \\beta) \n\\begin{pmatrix} \nC^{\\rm E_{i}E_{j},CMB}_{\\ell} \\cr\nC^{\\rm B_{i}B_{j},CMB}_{\\ell}\n\\end{pmatrix}  \\right] \\nonumber \\\\\n&+& \n\\vec{R}^{T} (\\alpha_{i} + \\beta, \\alpha_{j}+ \\beta ) \n\\begin{pmatrix} \nC^{\\rm E_{i}E_{j},CMB}_{\\ell} \\cr\nC^{\\rm B_{i}B_{j},CMB}_{\\ell}\n\\end{pmatrix} \\nonumber \\\\\n&=& \\vec{R}^{T} (\\alpha_{i}, \\alpha_{j})  {\\bm R}^{-1}(\\alpha_{i}, \\alpha_{j})  \n\\begin{pmatrix} \nC^{\\rm E_{i}E_{j},o}_{\\ell} \\cr\nC^{\\rm B_{i}B_{j},o}_{\\ell}\n\\end{pmatrix}  \\nonumber \\\\\n&+& \\left[  \\vec{R}^{T} (\\alpha_{i} + \\beta, \\alpha_{j}+ \\beta ) -  \\vec{R}^{T} (\\alpha_{i}, \\alpha_{j})  {\\bm R}^{-1}(\\alpha_{i}, \\alpha_{j})  {\\bm R}(\\alpha_{i} + \\beta, \\alpha_{j}+ \\beta) \\right]\n\\begin{pmatrix} \nC^{\\rm E_{i}E_{j},CMB}_{\\ell} \\cr\nC^{\\rm B_{i}B_{j},CMB}_{\\ell}\n\\end{pmatrix}\n\\ea\nThis can finally be rewritten\n\\ba\nC^{\\rm E_{i}B_{j},o}_{\\ell} - {\\bm A}  \n\\begin{pmatrix} \nC^{\\rm E_{i}E_{j},o}_{\\ell} \\cr\nC^{\\rm B_{i}B_{j},o}_{\\ell}\n\\end{pmatrix}\n-   {\\bm B} \n\\begin{pmatrix} \nC^{\\rm E_{i}E_{j},CMB}_{\\ell} \\cr\nC^{\\rm B_{i}B_{j},CMB}_{\\ell}\n\\end{pmatrix}\n= 0\n\\ea\nwith \n\\ba\n{\\bm A} =  \n\\begin{pmatrix} \n \\vec{R}^{T} (\\alpha_{i}, \\alpha_{j})  {\\bm R}^{-1}(\\alpha_{i}, \\alpha_{j}) \n\\end{pmatrix}  \n\\ea\nand \n\\ba\n{\\bm B} = \\vec{R}^{T} (\\alpha_{i} + \\beta, \\alpha_{j}+ \\beta ) -  \\vec{R}^{T} (\\alpha_{i}, \\alpha_{j})  {\\bm R}^{-1}(\\alpha_{i}, \\alpha_{j})  {\\bm R}(\\alpha_{i} + \\beta, \\alpha_{j}+ \\beta)\n\\ea\n%A multifrequency likelihood can be written\n%\\ba\n%-2\\ln {\\cal L} &=& \\sum_{\\ell}  ({\\bm A}  \\vec{C_{\\ell}}^{\\rm o}  - {\\bm B}\\vec{C_{\\ell}}^{\\rm CMB} )^{T} {\\bm C}^{-1}({\\bm A}  \\vec{C_{\\ell}}^{\\rm o}  - {\\bm B}\\vec{C_{\\ell}}^{\\rm CMB} ) \\nonumber \\\\\n%{\\bm C} &=& {\\bm A} {\\rm Cov}( \\vec{C_{\\ell}}^{\\rm o}, \\vec{C_{\\ell}}^{\\rm o}) {\\bm A}^{T}\n%\\ea\n\n\\end{document}\n\n\n", "meta": {"hexsha": "ae7785ea25717c351d1a977a69748692691f90db", "size": 17289, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "project/Planck_pspy/doc/birefringence.tex", "max_stars_repo_name": "simonsobs/ps_py", "max_stars_repo_head_hexsha": "fd34612f6756f693df92e01912fd71b291f1774a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2019-01-25T13:42:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T22:07:33.000Z", "max_issues_repo_path": "project/Planck_pspy/doc/birefringence.tex", "max_issues_repo_name": "simonsobs/ps_py", "max_issues_repo_head_hexsha": "fd34612f6756f693df92e01912fd71b291f1774a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2018-11-22T06:51:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T19:31:14.000Z", "max_forks_repo_path": "project/Planck_pspy/doc/birefringence.tex", "max_forks_repo_name": "sgiardie/PSpipe", "max_forks_repo_head_hexsha": "046c1d68c06fd3e8b7f0d9c068d0ff999bf95a0b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2019-04-19T09:32:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T10:26:09.000Z", "avg_line_length": 61.3085106383, "max_line_length": 951, "alphanum_fraction": 0.5652727168, "num_tokens": 7908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.32913253583360014}}
{"text": "%\\documentclass[UTF8]{ctexart} % use larger type; default would be 10pt\n\\documentclass[a4paper]{article}\n\\usepackage{../mqc}\n\n% TikZFeynman\n\\newcommand{\\qr}{quarter right}\n\\newcommand{\\ql}{quarter left}\n\\newcommand{\\hfr}{half right}\n\\newcommand{\\hfl}{half left}\n\\newcommand{\\el}{edge label}\n\n%\\usepackage{tikz}\n%\\usepackage[european]{circuitikz}\n\\usepackage{tikz-feynman}\n%\\usetikzlibrary{arrows.meta, bending, positioning}\n\n\\title{\\textbf{Modern Quantum Chemistry, Szabo \\& Ostlund}\\\\HW}\n\\author{wsr\n\\vspace{5pt}\\\\\n}\n\\date{\\today} % Activate to display a given date or no date (if empty),\n         % otherwise the current date is printed \n\n\\begin{document}\n% \\boldmath\n\n\\maketitle\n\n\\tableofcontents\n\n\\newpage\n\n\\setcounter{section}{5}\n\n\\section{Many-body Perturbation Theory}\n\\subsection{RS Perturbation Theory}\n\n\\subsection{Diagrammatic Representation of RS Perturbation Theory}\n\\subsubsection{Diagrammatic Perturbation Theory for Two States}\n\\ex{6.1}\n~\\\\\n\\tikzfeynmanset{\nevery vertex={black,dot},\n}\n\n\n\\begin{minipage}{0.3\\linewidth}\n\t\\hfill\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[small]\n\t\\vertex (a);\n\t\\vertex [below=of a] (b);\n\t\\vertex [below=of b] (c);\n\t\\vertex [below=of c] (d);\n\t\\vertex [below=of d] (e);\n\t\\diagram[inline=(c)]{\n\t\t(a) -- [fermion, quarter right, edge label'=1] (b)\n\t\t-- [fermion, quarter right, edge label'=1] (c)\n\t\t-- [fermion, quarter right, edge label'=1] (d)\n\t\t-- [fermion, quarter right, edge label'=1] (e)\n\t\t-- [fermion, quarter right, edge label'=2] (a),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n\\begin{minipage}{0.7\\linewidth}\n\t$ = (-1)^5 \\dfrac{V_{12}V_{21}V_{11}^3}{(E_1^{(0)} - E_2^{(0)})^4} = -\\dfrac{V_{12}V_{21}V_{11}^3}{(E_1^{(0)} - E_2^{(0)})^4} $\\\\\n\\end{minipage}\n~\\vspace{15pt}\\\\\n\\begin{minipage}{0.3\\linewidth}\n\t\\hfill\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[small]\n\t\\vertex (a);\n\t\\vertex [below=of a] (b);\n\t\\vertex [below=of b] (c);\n\t\\vertex [below=of c] (d);\n\t\\vertex [below=of d] (e);\n\t\\diagram[inline=(c)]{\n\t\t(e) -- [fermion, quarter left, edge label=2] (d)\n\t\t-- [fermion, quarter left, edge label=2] (c)\n\t\t-- [fermion, quarter left, edge label=2] (b)\n\t\t-- [fermion, quarter left, edge label=2] (a)\n\t\t-- [fermion, quarter left, edge label=1] (e),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n\\begin{minipage}{0.7\\linewidth}\n\t$ = (-1)^2 \\dfrac{V_{12}V_{21}V_{22}^3}{(E_1^{(0)} - E_2^{(0)})^4} = \\dfrac{V_{12}V_{21}V_{22}^3}{(E_1^{(0)} - E_2^{(0)})^4} $\\\\\n\\end{minipage}\n\n~\\vspace{15pt}\\\\\n\\begin{minipage}{0.3\\linewidth}\n\t\\hfill\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[small]\n\t\\vertex (a);\n\t\\vertex [below=of a] (b);\n\t\\vertex [below=of b] (c);\n\t\\vertex [below=of c] (d);\n\t\\vertex [below=of d] (e);\n\t\\diagram[inline=(c)]{\n\t\t(a) -- [fermion, quarter right, edge label'=1] (b)\n\t\t-- [fermion, quarter right, edge label'=1] (d)\n\t\t-- [fermion, quarter right, edge label'=1] (e)\n\t\t-- [fermion, quarter right, edge label'=2] (c)\n\t\t-- [fermion, quarter right, edge label'=2] (a),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n\\begin{minipage}{0.7\\linewidth}\n\t$ = (-1)^4 \\dfrac{V_{12}V_{21}V_{11}^2 V_{22}}{(E_1^{(0)} - E_2^{(0)})^4} = \\dfrac{V_{12}V_{21}V_{11}^2 V_{22}}{(E_1^{(0)} - E_2^{(0)})^4} $\\\\\n\\end{minipage}\n\n~\\vspace{15pt}\\\\\n\\begin{minipage}{0.3\\linewidth}\n\t\\hfill\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[small]\n\t\\vertex (a);\n\t\\vertex [below=of a] (b);\n\t\\vertex [below=of b] (c);\n\t\\vertex [below=of c] (d);\n\t\\vertex [below=of d] (e);\n\t\\diagram[inline=(c)]{\n\t\t(a) -- [fermion, quarter left, edge label=1] (c)\n\t\t-- [fermion, quarter left, edge label=1] (e)\n\t\t-- [fermion, quarter left, edge label=2] (d)\n\t\t-- [fermion, quarter left, edge label=2] (b)\n\t\t-- [fermion, quarter left, edge label=2] (a),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n\\begin{minipage}{0.7\\linewidth}\n\t$ = (-1)^3 \\dfrac{V_{12}V_{21}V_{11} V_{22}^2}{(E_1^{(0)} - E_2^{(0)})^4} = -\\dfrac{V_{12}V_{21}V_{11} V_{22}^2}{(E_1^{(0)} - E_2^{(0)})^4} $\\\\\n\\end{minipage}\n\n\\newpage\nSimilarly,\\\\\n%~\\vspace{15pt}\\\\\n\\begin{minipage}{0.2\\linewidth}\n\t\\hfill\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[small]\n\t\\vertex (a);\n\t\\vertex [below=of a] (b);\n\t\\vertex [below=of b] (c);\n\t\\vertex [below=of c] (d);\n\t\\vertex [below=of d] (e);\n\t\\diagram[inline=(c)]{\n\t\t(a) -- [fermion, quarter right, edge label'=1] (c)\n\t\t-- [fermion, quarter right, edge label'=1] (d)\n\t\t-- [fermion, quarter right, edge label'=1] (e)\n\t\t-- [fermion, quarter right, edge label'=2] (b)\n\t\t-- [fermion, quarter right, edge label'=2] (a),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n,\n\\begin{minipage}{0.15\\linewidth}\n\t%\\hfill\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[small]\n\t\\vertex (a);\n\t\\vertex [below=of a] (b);\n\t\\vertex [below=of b] (c);\n\t\\vertex [below=of c] (d);\n\t\\vertex [below=of d] (e);\n\t\\diagram[inline=(c)]{\n\t\t(a) -- [fermion, quarter right, edge label'=1] (b)\n\t\t-- [fermion, quarter right, edge label'=1] (c)\n\t\t-- [fermion, quarter right, edge label'=1] (e)\n\t\t-- [fermion, quarter right, edge label'=2] (d)\n\t\t-- [fermion, quarter right, edge label'=2] (a),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n\\begin{minipage}{0.6\\linewidth}\n\t$ = \\dfrac{V_{12}V_{21}V_{11}^2 V_{22}}{(E_1^{(0)} - E_2^{(0)})^4} $\\\\\n\\end{minipage}\n\n~\\vspace{15pt}\\\\\n\\begin{minipage}{0.2\\linewidth}\n\t\\hfill\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[small]\n\t\\vertex (a);\n\t\\vertex [below=of a] (b);\n\t\\vertex [below=of b] (c);\n\t\\vertex [below=of c] (d);\n\t\\vertex [below=of d] (e);\n\t\\diagram[inline=(c)]{\n\t\t(a) -- [fermion, quarter left, edge label=1] (b)\n\t\t-- [fermion, quarter left, edge label=1] (e)\n\t\t-- [fermion, quarter left, edge label=2] (d)\n\t\t-- [fermion, quarter left, edge label=2] (c)\n\t\t-- [fermion, quarter left, edge label=2] (a),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n,\n\\begin{minipage}{0.15\\linewidth}\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[small]\n\t\\vertex (a);\n\t\\vertex [below=of a] (b);\n\t\\vertex [below=of b] (c);\n\t\\vertex [below=of c] (d);\n\t\\vertex [below=of d] (e);\n\t\\diagram[inline=(c)]{\n\t\t(a) -- [fermion, quarter left, edge label=1] (d)\n\t\t-- [fermion, quarter left, edge label=1] (e)\n\t\t-- [fermion, quarter left, edge label=2] (c)\n\t\t-- [fermion, quarter left, edge label=2] (b)\n\t\t-- [fermion, quarter left, edge label=2] (a),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n\\begin{minipage}{0.6\\linewidth}\n\t$ = -\\dfrac{V_{12}V_{21}V_{11} V_{22}^2}{(E_1^{(0)} - E_2^{(0)})^4} $\\\\\n\\end{minipage}\n~\\vspace{10pt}\\\\\nthus, the sum of above terms is\n\\begin{align}\n\\dfrac{V_{12}V_{21}(V_{22}^3 - V_{11}^3)}{(E_1^{(0)} - E_2^{(0)})^4} + 3\\times\\dfrac{V_{12}V_{21}(V_{11}^2 V_{22} - V_{11}V_{22}^2)}{(E_1^{(0)} - E_2^{(0)})^4} \n= \\dfrac{V_{12}V_{21}(V_{22} - V_{11})^3}{(E_1^{(0)} - E_2^{(0)})^4} \n\\end{align}\n\n\\subsubsection{Diagrammatic Perturbation Theory for $ N $ States}\n\\ex{6.2}\nThe 4th-order perturbation energy of state $ i $ can be expressed as\n\\begin{align}\n&\\sum_{k,n,m\\neq i} \\dfrac{V_{ki}V_{nk}V_{mn}V_{im}}{(E_i^{(0)}-E_k^{(0)})(E_i^{(0)}-E_n^{(0)})(E_i^{(0)}-E_m^{(0)})} + \\sum_{n\\neq i} \\dfrac{V_{ii}^2 V_{ni}V_{in}}{(E_i^{(0)}-E_n^{(0)})^3} - \\sum_{m,n\\neq i} \\dfrac{V_{ii}V_{mi}V_{in}V_{nm}}{(E_i^{(0)}-E_m^{(0)})^2(E_i^{(0)}-E_n^{(0)})} \\notag\\\\\n&- \\sum_{m,n\\neq i} \\dfrac{V_{ii}V_{ni}V_{im}V_{mn}}{(E_i^{(0)}-E_m^{(0)})^2(E_i^{(0)}-E_n^{(0)})} - \\sum_{m,n\\neq i} \\dfrac{V_{mi}V_{im}V_{in}V_{ni}}{(E_i^{(0)}-E_m^{(0)})(E_i^{(0)}-E_n^{(0)})(2E_i^{(0)}-E_n^{(0)}-E_m^{(0)})} \\notag\\\\\n&- \\sum_{m,n\\neq i} \\dfrac{V_{mi}V_{im}V_{in}V_{ni}}{(E_i^{(0)}-E_n^{(0)})^2(2E_i^{(0)}-E_n^{(0)}-E_m^{(0)})} \\notag\\\\\n= &\\sum_{k,n,m\\neq i} \\dfrac{V_{ki}V_{nk}V_{mn}V_{im}}{(E_i^{(0)}-E_k^{(0)})(E_i^{(0)}-E_n^{(0)})(E_i^{(0)}-E_m^{(0)})} + \\sum_{n\\neq i} \\dfrac{V_{ii}^2 V_{ni}V_{in}}{(E_i^{(0)}-E_n^{(0)})^3} - 2\\sum_{m,n\\neq i} \\dfrac{V_{ii}V_{mi}V_{in}V_{nm}}{(E_i^{(0)}-E_m^{(0)})^2(E_i^{(0)}-E_n^{(0)})} \\notag\\\\\n&%- \\sum_{m,n\\neq i} \\dfrac{V_{ii}V_{ni}V_{im}V_{mn}}{(E_i^{(0)}-E_m^{(0)})^2(E_i^{(0)}-E_n^{(0)})} \n- \\sum_{m,n\\neq i} \\dfrac{V_{mi}V_{im}V_{in}V_{ni}}{(E_i^{(0)}-E_m^{(0)})(E_i^{(0)}-E_n^{(0)})^2} \n\\end{align}\nwhile\n\\begin{equation}\\label{key}\n\\Braket{n | \\sH | \\Psi_i^{(3)}} + \\Braket{n | \\mathscr{V} | \\Psi_i^{(2)}} = E_i^{(0)} \\Braket{n|\\Psi_i^{(3)}} + E_i^{(1)} \\Braket{n|\\Psi_i^{(2)}} + E_i^{(2)} \\Braket{n|\\Psi_i^{(1)}}\n\\end{equation}\n\\begin{align}\\label{key}\n(E_i^{(0)} - E_n^{(0)})\\Braket{n | \\Psi_i^{(3)}} \n&= \\Braket{n | \\mathscr{V} | \\Psi_i^{(2)}} - E_i^{(1)} \\Braket{n|\\Psi_i^{(2)}} - E_i^{(2)} \\Braket{n|\\Psi_i^{(1)}} \\notag\\\\\n&= \\Braket{n | \\mathscr{V} | \\Psi_i^{(2)}} \n- E_i^{(1)} \\dfrac{\\Braket{n | \\mathscr{V} | \\Psi_i^{(1)}} - E_i^{(1)}\\Braket{n|\\Psi_i^{(1)}}}{E_i^{(0)} - E_n^{(0)}} \n- E_i^{(2)} \\Braket{n|\\Psi_i^{(1)}} \\notag\\\\\n&= \\Braket{n | \\mathscr{V} | \\Psi_i^{(2)}} \n- E_i^{(1)} \\dfrac{\\Braket{n | \\mathscr{V} | \\Psi_i^{(1)}}}{E_i^{(0)} - E_n^{(0)}} \n+ \\qty[E_i^{(1)}]^2 \\dfrac{\\Braket{n|\\mathscr{V}|i}}{\\qty[E_i^{(0)} - E_n^{(0)}]^2} \n- E_i^{(2)} \\dfrac{\\Braket{n|\\mathscr{V}|i}}{E_i^{(0)} - E_n^{(0)}} \n\\end{align}\n\\begin{align}\nE_i^{(4)} &= \\Braket{i | \\mathscr{V} | \\Psi_i^{(3)}} \\notag\\\\\n&= \\sum_{n\\neq i} \\dfrac{\\Braket{i | \\mathscr{V} | n}}{E_i^{(0)} - E_n^{(0)}} \\qty{\\Braket{n | \\mathscr{V} | \\Psi_i^{(2)}} \n- E_i^{(1)} \\dfrac{\\Braket{n | \\mathscr{V} | \\Psi_i^{(1)}}}{E_i^{(0)} - E_n^{(0)}} \n+ \\qty[E_i^{(1)}]^2 \\dfrac{\\Braket{n|\\mathscr{V}|i}}{\\qty[E_i^{(0)} - E_n^{(0)}]^2} \n- E_i^{(2)} \\dfrac{\\Braket{n|\\mathscr{V}|i}}{E_i^{(0)} - E_n^{(0)}} }\\notag\\\\\n&= \\sum_{n\\neq i} \\dfrac{\\Braket{i | \\mathscr{V} | n}}{E_i^{(0)} - E_n^{(0)}} \\Braket{n | \\mathscr{V} | \\Psi_i^{(2)}} \n- E_i^{(1)} \\sum_{n\\neq i} \\dfrac{\\Braket{i | \\mathscr{V} | n}}{\\qty[E_i^{(0)} - E_n^{(0)}]^2} \\Braket{n | \\mathscr{V} | \\Psi_i^{(1)}} \\notag\\\\\n&{}\\quad +  \\qty[E_i^{(1)}]^2 \\sum_{n\\neq i} \\dfrac{V_{in}V_{ni}}{\\qty[E_i^{(0)} - E_n^{(0)}]^3} \n-  E_i^{(2)} \\sum_{n\\neq i} \\dfrac{V_{in}V_{ni}}{\\qty[E_i^{(0)} - E_n^{(0)}]^2} \\notag\\\\\n&= \\sum_{n,m\\neq i} \\dfrac{\\Braket{i | \\mathscr{V} | n}}{E_i^{(0)} - E_n^{(0)}} \\Braket{n | \\mathscr{V} | m} \\Braket{m |\\Psi_i^{(2)}} \n- E_i^{(1)} \\sum_{n,m\\neq i} \\dfrac{\\Braket{i | \\mathscr{V} | n}\\Braket{n | \\mathscr{V} | m}\\Braket{m | \\mathscr{V} | i} }{\\qty[E_i^{(0)} - E_n^{(0)}]^2\\qty[E_i^{(0)} - E_m^{(0)}]}  \\notag\\\\\n&{}\\quad +  \\qty[E_i^{(1)}]^2 \\sum_{n\\neq i} \\dfrac{V_{in}V_{ni}}{\\qty[E_i^{(0)} - E_n^{(0)}]^3} \n-  E_i^{(2)} \\sum_{n\\neq i} \\dfrac{V_{in}V_{ni}}{\\qty[E_i^{(0)} - E_n^{(0)}]^2} \\notag\\\\\n&= \\sum_{n,m\\neq i} \\dfrac{V_{in} V_{nm}}{E_i^{(0)} - E_n^{(0)}} \\dfrac{\\Braket{m | \\mathscr{V} | \\Psi_i^{(1)}} - E_i^{(1)}\\Braket{m|\\Psi_i^{(1)}}}{E_i^{(0)} - E_m^{(0)}} \n- E_i^{(1)} \\sum_{n,m\\neq i} \\dfrac{V_{in}V_{nm}V_{mi} }{\\qty[E_i^{(0)} - E_n^{(0)}]^2\\qty[E_i^{(0)} - E_m^{(0)}]}  \\notag\\\\\n&{}\\quad +  \\qty[E_i^{(1)}]^2 \\sum_{n\\neq i} \\dfrac{V_{in}V_{ni}}{\\qty[E_i^{(0)} - E_n^{(0)}]^3} \n-  E_i^{(2)} \\sum_{n\\neq i} \\dfrac{V_{in}V_{ni}}{\\qty[E_i^{(0)} - E_n^{(0)}]^2} \\notag\\\\\n&= \\sum_{n,m,k\\neq i} \\dfrac{V_{in} V_{nm}}{E_i^{(0)} - E_n^{(0)}} \\dfrac{\\Braket{m | \\mathscr{V} | k} \\Braket{k| \\mathscr{V} | i} }{\\qty[E_i^{(0)} - E_m^{(0)}]\\qty[E_i^{(0)} - E_k^{(0)}]} \n- E_i^{(1)}\\sum_{n,m\\neq i} \\dfrac{V_{in} V_{nm}}{E_i^{(0)} - E_n^{(0)}} \\dfrac{ \\Braket{m| \\mathscr{V} |i}}{\\qty[E_i^{(0)} - E_m^{(0)}]^2} \\notag\\\\\n&{}\\quad- E_i^{(1)} \\sum_{n,m\\neq i} \\dfrac{V_{in}V_{nm}V_{mi} }{\\qty[E_i^{(0)} - E_n^{(0)}]^2\\qty[E_i^{(0)} - E_m^{(0)}]} \n +  \\qty[E_i^{(1)}]^2 \\sum_{n\\neq i} \\dfrac{V_{in}V_{ni}}{\\qty[E_i^{(0)} - E_n^{(0)}]^3} \n-  E_i^{(2)} \\sum_{n\\neq i} \\dfrac{V_{in}V_{ni}}{\\qty[E_i^{(0)} - E_n^{(0)}]^2} \\notag\\\\\n&= \\sum_{n,m,k\\neq i} \\dfrac{V_{in} V_{nm}V_{mk}V_{ki}}{\\qty[E_i^{(0)} - E_n^{(0)}]\\qty[E_i^{(0)} - E_m^{(0)}]\\qty[E_i^{(0)} - E_k^{(0)}]} \n- 2V_{ii}\\sum_{n,m\\neq i} \\dfrac{V_{in} V_{nm} V_{mi}}{\\qty[E_i^{(0)} - E_n^{(0)}]\\qty[E_i^{(0)} - E_m^{(0)}]^2}  \\notag\\\\\n&{}\\quad %- V_{ii} \\sum_{n,m\\neq i} \\dfrac{V_{in}V_{nm}V_{mi} }{\\qty[E_i^{(0)} - E_n^{(0)}]^2\\qty[E_i^{(0)} - E_m^{(0)}]} \n+  V_{ii}^2 \\sum_{n\\neq i} \\dfrac{V_{in}V_{ni}}{\\qty[E_i^{(0)} - E_n^{(0)}]^3} \n-  \\sum_{m\\neq i} \\dfrac{V_{mi}V_{im}}{\\qty[E_i^{(0)} - E_m^{(0)}]} \\sum_{n\\neq i} \\dfrac{V_{in}V_{ni}}{\\qty[E_i^{(0)} - E_n^{(0)}]^2} \n\\end{align}\nwhich agrees with diagrammatic results above.\n\n\\subsubsection{Summation of Diagrams}\n\n\\newpage\n\\subsection{Orbital Perturbation Theory: One-Particle Perturbations}\n\\ex{6.3}\nSince $ n\\neq 0 $ and $ v(i) $ is one-particle operator, $ n $ must be single-excited, i.e. $ \\ket{\\Psi_a^r} $. Thus,\n\\begin{align}\nE_0^{(2)} &= \\sum_{a,r} \\dfrac{\\abs{\\Braket{\\Psi_0 | \\sum_i v(i) | \\Psi_a^r}}^2}{\\Braket{\\Psi_0 | \\sH | \\Psi_0} - \\Braket{\\Psi_a^r| \\sH | \\Psi_a^r}} \\notag\\\\\n&= \\sum_{a,r} \\dfrac{v_{ar} v_{ra}}{\\sum_b \\varepsilon_b^{(0)} - \\qty(\\sum_{b\\neq a}\\varepsilon_b^{(0)} + \\varepsilon_r^{(0)})} \\notag\\\\\n&= \\sum_{a,r} \\dfrac{v_{ar} v_{ra}}{\\varepsilon_a^{(0)} - \\varepsilon_r^{(0)}}\n\\end{align}\n\n\\ex{6.4}\nEq 6.15 in textbook gives\n\\begin{align}\nE_i^{(3)} &= \\sum_{n,m\\neq i} \\dfrac{\\Braket{i|\\mathscr{V}|n} \\Braket{n|\\mathscr{V}|m} \\Braket{m|\\mathscr{V}|i}}{(E_i^{(0)}-E_n^{(0)}) (E_i^{(0)}-E_m^{(0)})} \n- E_i^{(1)}\\sum_{n\\neq i} \\dfrac{\\abs{\\Braket{i|\\mathscr{V}|n}}^2 }{(E_i^{(0)}-E_n^{(0)})^2} \\notag\\\\\n&= A_i^{(3)} + B_i^{(3)}\n\\end{align}\n\\subex{a.}\n\\begin{align}\nB_0^{(3)} &= - E_0^{(1)}\\sum_{n\\neq 0} \\dfrac{\\abs{\\Braket{\\Psi_0|\\mathscr{V}|n}}^2 }{(E_0^{(0)}-E_n^{(0)})^2} \\notag\\\\\n&= -\\sum_b v_{bb} \\sum_{a,r}\\dfrac{v_{ar}v_{ra}}{(\\varepsilon_a^{(0)} - \\varepsilon_r^{(0)})^2} \\notag\\\\\n&= - \\sum_{a,b,r}\\dfrac{v_{aa} v_{br}v_{rb}}{(\\varepsilon_b^{(0)} - \\varepsilon_r^{(0)})^2} \n\\end{align}\n\\subex{b.}\n\\begin{align}\nA_0^{(3)} &= \\sum_{n,m\\neq 0} \\dfrac{\\Braket{\\Psi_0|\\mathscr{V}|n} \\Braket{n|\\mathscr{V}|m} \\Braket{m|\\mathscr{V}|\\Psi_0}}{(E_0^{(0)}-E_n^{(0)}) (E_0^{(0)}-E_m^{(0)})} \\notag\\\\\n&= \\sum_{a,r,b,s} \\dfrac{\\Braket{\\Psi_0|\\mathscr{V}|\\Psi_a^r} \\Braket{\\Psi_a^r|\\mathscr{V}|\\Psi_b^s} \\Braket{\\Psi_b^s|\\mathscr{V}|\\Psi_0}}{(\\varepsilon_a^{(0)} - \\varepsilon_r^{(0)}) (\\varepsilon_b^{(0)} - \\varepsilon_s^{(0)})} \\notag\\\\\n&= \\sum_{a,r,b,s} \\dfrac{v_{ar}v_{sb} \\Braket{\\Psi_a^r|\\mathscr{V}|\\Psi_b^s} }{(\\varepsilon_a^{(0)} - \\varepsilon_r^{(0)}) (\\varepsilon_b^{(0)} - \\varepsilon_s^{(0)})} \n\\end{align}\n\\subex{c.}\nClearly, if $ a\\neq b, r\\neq s $\n\\begin{align}\n\\Braket{\\Psi_a^r | \\mathscr{V} | \\Psi_b^s} = 0\n\\end{align}\nIf $ a=b, r\\neq s $,\n\\begin{align}\n\\Braket{\\Psi_a^r | \\mathscr{V} | \\Psi_b^s} \n&= \\Braket{r| v |s} \\notag\\\\\n&= v_{rs}\n\\end{align}\nIf $ a\\neq b, r= s $,\n\\begin{align}\n\\Braket{\\Psi_a^r | \\mathscr{V} | \\Psi_b^s} \n&= \\Braket{\\Psi_a^r | \\mathscr{V} | \\Psi_b^r} \\notag\\\\\n&= \\Braket{\\Psi_a^r | \\mathscr{V} | -\\Psi_{ab}^{ra}} \\notag\\\\\n&= -\\Braket{b| v |a} \\notag\\\\\n&= -v_{ba}\n\\end{align}\nIf $ a= b, r= s $,\n\\begin{align}\n\\Braket{\\Psi_a^r | \\mathscr{V} | \\Psi_b^s} \n&= \\Braket{\\Psi_a^r | \\mathscr{V} | \\Psi_a^r} \\notag\\\\\n&= \\sum_c v_{cc} - v_{aa} + v_{rr}\n\\end{align}\n\n\\subex{d.}\n\\begin{align}\nE_0^{(3)} &= A_0^{(3)} + B_0^{(3)} \\notag\\\\\n&= \\sum_{a,r,b,s} \n\\dfrac{v_{ar}v_{sb} \\Braket{\\Psi_a^r|\\mathscr{V}|\\Psi_b^s} }{(\\varepsilon_a^{(0)} - \\varepsilon_r^{(0)}) (\\varepsilon_b^{(0)} - \\varepsilon_s^{(0)})} \n- \\sum_{a,b,r}\\dfrac{v_{aa} v_{br}v_{rb}}{(\\varepsilon_b - \\varepsilon_r)^2}\n\\notag\\\\\n&=  \\sum_{a,r\\neq s} \n\\dfrac{v_{ar}v_{sa} v_{rs} }{(\\varepsilon_a^{(0)} - \\varepsilon_r^{(0)}) (\\varepsilon_a^{(0)} - \\varepsilon_s^{(0)})} \n+ \\sum_{a\\neq b,r} \n\\dfrac{v_{ar}v_{rb}(-v_{ba}) }{(\\varepsilon_a^{(0)} - \\varepsilon_r^{(0)}) (\\varepsilon_b^{(0)} - \\varepsilon_r^{(0)})} \n\\notag\\\\\n&\\quad {} + \\sum_{a,r} \n\\dfrac{v_{ar}v_{ra} (\\sum_c v_{cc} - v_{aa} + v_{rr}) }{(\\varepsilon_a^{(0)} - \\varepsilon_r^{(0)})^2} \n- \\sum_{a,b,r}\\dfrac{v_{aa} v_{br}v_{rb}}{(\\varepsilon_b^{(0)} - \\varepsilon_r^{(0)})^2}\n\\notag\\\\\n&=  \\sum_{a,r\\neq s} \n\\dfrac{v_{ar}v_{sa} v_{rs} }{(\\varepsilon_a^{(0)} - \\varepsilon_r^{(0)}) (\\varepsilon_a^{(0)} - \\varepsilon_s^{(0)})} \n+ \\sum_{a\\neq b,r} \n\\dfrac{v_{ar}v_{rb}(-v_{ba}) }{(\\varepsilon_a^{(0)} - \\varepsilon_r^{(0)}) (\\varepsilon_b^{(0)} - \\varepsilon_r^{(0)})} \n\\notag\\\\\n&\\quad {} + \\sum_{a,r} \n\\dfrac{v_{ar}v_{ra} (\\sum_c v_{cc} - v_{aa} + v_{rr}) }{(\\varepsilon_a^{(0)} - \\varepsilon_r^{(0)})^2} \n- \\sum_{a,r}\\dfrac{\\sum_c v_{cc} v_{ar}v_{ra}}{(\\varepsilon_a^{(0)} - \\varepsilon_r^{(0)})^2}\n\\notag\\\\\n&=  \\sum_{a,r\\neq s} \n\\dfrac{v_{ar}v_{sa} v_{rs} }{(\\varepsilon_a^{(0)} - \\varepsilon_r^{(0)}) (\\varepsilon_a^{(0)} - \\varepsilon_s^{(0)})} \n+ \\sum_{a\\neq b,r} \n\\dfrac{v_{ar}v_{rb}(-v_{ba}) }{(\\varepsilon_a^{(0)} - \\varepsilon_r^{(0)}) (\\varepsilon_b^{(0)} - \\varepsilon_r^{(0)})} \n+ \\sum_{a,r} \n\\dfrac{v_{ar}v_{ra} ( - v_{aa} + v_{rr}) }{(\\varepsilon_a^{(0)} - \\varepsilon_r^{(0)})^2} \n\\notag\\\\\n&=  \\sum_{a,r,s} \n\\dfrac{v_{ar}v_{sa} v_{rs} }{(\\varepsilon_a^{(0)} - \\varepsilon_r^{(0)}) (\\varepsilon_a^{(0)} - \\varepsilon_s^{(0)})} \n- \\sum_{a,b,r} \n\\dfrac{v_{ar}v_{rb}v_{ba} }{(\\varepsilon_a^{(0)} - \\varepsilon_r^{(0)}) (\\varepsilon_b^{(0)} - \\varepsilon_r^{(0)})} \n\\end{align}\n\n\\subex{e.}\nThat's obvious.\n\n\\ex{6.5}\nSince $ a,b $ run over all $ n $ occupied orbitals $ i,j $ and $ r $ runs over all $ n $ unoccupied orbitals $ k^* $, we have\n\\begin{align}\n-2\\sum_{a,b,r}^{N/2} \\dfrac{v_{ra}v_{ab}v_{br}}{(\\varepsilon_a^{(0)} - \\varepsilon_r^{(0)}) (\\varepsilon_b^{(0)} - \\varepsilon_r^{(0)})} \n&= -\\dfrac{2}{(2\\beta)^2} \\sum_i^n \\sum_j^n \\sum_k^n \\Braket{i|v|j} \\Braket{j|v|k^*} \\Braket{k^*|v|i} \\notag\\\\\n&= -\\dfrac{2}{(2\\beta)^2} \\sum_i^3\n\\mqty[\\Braket{i|v|i+1} \\Braket{i+1|v|(i+2)^*} \\Braket{(i+2)^*|v|i} \\\\\n+ \\Braket{i|v|i+2} \\Braket{i+2|v|(i+1)^*} \\Braket{(i+1)^*|v|i} ] \\notag\\\\\n&= -\\dfrac{2}{(2\\beta)^2} \\sum_i^3 \\qty[(\\beta/2)(\\beta/2)(-\\beta/2) + (\\beta/2)(-\\beta/2)(\\beta/2)] \\notag\\\\\n&= -\\dfrac{2}{(2\\beta)^2} \\times 3\\times (-\\beta^3/4) \\notag\\\\\n&= 3\\beta/8\n\\end{align}\n\n\\ex{6.6}\n\\subex{a.}\nUsing the general expression, we get\n\\begin{align}\n\\mathscr{E}_0 &= 6\\alpha - 2\\sum_{j=-1}^1 (\\beta_1^2 + \\beta_2^2 + 2\\beta_1\\beta_2\\cos\\dfrac{2j\\pi}{3})^{1/2} \\notag\\\\\n&= 6\\alpha - 2(\\beta_1^2 + \\beta_2^2 + 2\\beta_1\\beta_2\\cos\\dfrac{-2\\pi}{3})^{1/2}\n- 2(\\beta_1^2 + \\beta_2^2 + 2\\beta_1\\beta_2\\cos 0)^{1/2}\n- 2(\\beta_1^2 + \\beta_2^2 + 2\\beta_1\\beta_2\\cos\\dfrac{2\\pi}{3})^{1/2} \n\\notag\\\\\n&= 6\\alpha - 2(\\beta_1^2 + \\beta_2^2 - \\beta_1\\beta_2)^{1/2}\n- 2(\\beta_1^2 + \\beta_2^2 + 2\\beta_1\\beta_2)^{1/2}\n- 2(\\beta_1^2 + \\beta_2^2 - \\beta_1\\beta_2)^{1/2} \\notag\\\\\n&= 6\\alpha \n- 2\\abs{\\beta_1 + \\beta_2}\n- 4(\\beta_1^2 + \\beta_2^2 - \\beta_1\\beta_2)^{1/2} \\notag\\\\\n&= 6\\alpha + 2(\\beta_1 + \\beta_2)\n- 4(\\beta_1^2 + \\beta_2^2 - \\beta_1\\beta_2)^{1/2}\n\\end{align}\n\nUsing H\\\"uckel matrix:\n\\begin{align}\n\\vb{H} = \\mqty( \n\\alpha  & \\beta_1 & 0       & 0       & 0       & \\beta_2\\\\\n\\beta_1 & \\alpha  & \\beta_2 & 0       & 0       & 0      \\\\\n0       & \\beta_2 & \\alpha  & \\beta_1 & 0       & 0      \\\\\n0       & 0       & \\beta_1 & \\alpha  & \\beta_2 & 0      \\\\\n0       & 0       & 0       & \\beta_2 & \\alpha  & \\beta_1\\\\\n\\beta_2 & 0       & 0       & 0       & \\beta_1 & \\alpha  \n)\n\\end{align}\n%Diagonalize $ \\vb{H} - \\bm\\varepsilon $, we get\nEigenvalues of $ \\vb{H} $ are\n\\begin{align}\\label{key}\n&\\alpha + (\\beta_1 + \\beta_2), \\notag\\\\\n&\\alpha - \\sqrt{\\beta_1^2 + \\beta_2^2 - \\beta_1\\beta_2} \\;\\text{ (2-fold)}, \\notag\\\\\n&\\alpha + \\sqrt{\\beta_1^2 + \\beta_2^2 - \\beta_1\\beta_2} \\;\\text{ (2-fold)}, \\notag\\\\\n&\\alpha - (\\beta_1 + \\beta_2),\n\\end{align}\nthus\n\\begin{align}\n\\mathscr{E}_0 &= 2\\qty[\\alpha + (\\beta_1 + \\beta_2)] + 4\\qty[\\alpha - \\sqrt{\\beta_1^2 + \\beta_2^2 - \\beta_1\\beta_2}] \\notag\\\\\n&= 6\\alpha + 2(\\beta_1 + \\beta_2) - 4\\sqrt{\\beta_1^2 + \\beta_2^2 - \\beta_1\\beta_2}\n\\end{align}\n\n\\subex{b.}\n\\begin{align}\nE_R &= \\mathscr{E}_0 - (N\\alpha + N\\beta) \\notag\\\\\n&= 6\\alpha + 2(\\beta_1 + \\beta_2) - 4\\sqrt{\\beta_1^2 + \\beta_2^2 - \\beta_1\\beta_2} - (6\\alpha + 6\\beta) \\notag\\\\\n&= -4\\beta_1 + 2\\beta_2 - 4\\sqrt{\\beta_1^2 + \\beta_2^2 - \\beta_1\\beta_2} \\notag\\\\\n&= 4\\beta\\qty(-1 + \\dfrac{1}{2}x + \\sqrt{1 + x^2 - x})\n\\end{align}\n\n\\subex{c.}\n\\begin{align}\nE_R &= 4\\beta\\qty(-1 + \\dfrac{1}{2}x + \\sqrt{1 + x^2 - x}) \\notag\\\\\n&= 4\\beta\\qty[ -1 + \\dfrac{1}{2}x \n+ 1 + \\dfrac{1}{2}(x^2-x) - \\dfrac{1}{8}(x^2-x)^2 + \\dfrac{1}{16}(x^2-x)^3 - \\dfrac{5}{128}(x^2-x)^4 ] \\notag\\\\\n&= 4\\beta\\qty[ \n\\dfrac{1}{2}x^2 - \\dfrac{1}{8}(x^4 + x^2 - 2x^3) \n+ \\dfrac{1}{16}(-x^3 + 3x^4) - \\dfrac{5}{128}x^4 + \\cdots ] \\notag\\\\\n&= 4\\beta\\qty[ \n\\dfrac{3}{8}x^2 + \\dfrac{3}{16}x^3 + \\dfrac{3}{128}x^4 + \\cdots ] \\notag\\\\\n&= \\beta\\qty[ \n\\dfrac{3}{2}x^2 + \\dfrac{3}{4}x^3 + \\dfrac{3}{32}x^4 + \\cdots ]\n\\end{align}\n\n\\newpage\n\\subsection{Diagrammatic Representation of Orbital Perturbation Theory}\n\\ex{6.7}\n\\subex{a.}\n~\\\\\n\\begin{minipage}{0.2\\linewidth}\n\t\t\\hfill\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[small]\n\t\\vertex (a);\n\t\\vertex [below=of a] (b);\n\t\\vertex [below=of b] (c);\n\t\\vertex [below=of c] (d);\n\t%\\vertex [below=of d] (e);\n\t\\diagram[inline=(c)]{\n\t\t(a) -- [fermion, quarter right, edge label'=a] (b)\n\t\t-- [fermion, quarter right, edge label'=b] (d)\n\t\t-- [fermion, quarter right, edge label'=s] (c)\n\t\t-- [fermion, quarter right, edge label'=r] (a)\n\t\t%-- [fermion, quarter right, edge label'=2] (a),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\t\\\\\n\t\\vspace{25pt}\\\\\n\\end{minipage}\n\\begin{minipage}{0.8\\linewidth}\n\t\\vspace{25pt}~\\\\\n\t\\begin{align}\n\t&= - \\sum_{a,b,r,s} \\dfrac{v_{ab}v_{bs}v_{sr}v_{ra}}{(\\varepsilon_a^{(0)} - \\varepsilon_r^{(0)})(\\varepsilon_b^{(0)} - \\varepsilon_r^{(0)})(\\varepsilon_b^{(0)} - \\varepsilon_b^{(0)})}  &\\notag\\\\\n\t&= -\\dfrac{1}{(2\\beta)^3} \\sum_{i,j,k,l} \\Braket{i|v|j}\\Braket{j|v|k^*}\\Braket{k^*|v|l^*}\\Braket{l^*|v|i} & \\notag\\\\\n\t&= -\\dfrac{2}{(2\\beta)^3} \\sum_i^{N/2} [-1 + 1 -1 -1 +1 -1]\\times (\\beta/2)^4  & \\notag\\\\\n\t&= \\dfrac{N\\beta}{64}  & \\notag\\\\\n\t\\end{align}\n\\end{minipage}\n%\\tikzfeynmanset{\n%}\nThe pictorial representation of the summation are as follows\\\\\n\\begin{center}\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[nodes=circle, large]\n\t\\vertex (a) {$ (i) $};\n\t\\vertex [below right=of a] (b1) {$ (i-1) $};\n\t\\vertex [above right=of a] (b2) {$ (i+1) $};\n\t\\vertex [below right=of b1] (c1) {$ (i-2)^* $};\n\t\\vertex [above right=of b1] (c2) {$ (i)^* $};\n\t\\vertex [above right=of b2] (c3) {$ (i+2)^* $};\n\t\\vertex [above right=of c1] (d1) {$ (i-1)^* $};\n\t\\vertex [above right=of c2] (d2) {$ (i+1)^* $};\n\t\\vertex [above right=of d1] (e) {$ (i) $};\n\t\\diagram[inline=(c)]{\n\t\t(a) -- [plain, edge label'=+] (b1);\n\t\t(a) -- [plain, edge label=+] (b2);\n\t\t(b1) -- [plain, edge label'=--] (c1);\n\t\t(b1) -- [plain, edge label'=+] (c2);\n\t\t(b2) -- [plain, edge label=--] (c2);\n\t\t(b2) -- [plain, edge label=+] (c3);\n\t\t(c1) -- [plain, edge label'=--] (d1);\n\t\t(c2) -- [plain, edge label'=--] (d1);\n\t\t(c2) -- [plain, edge label=--] (d2);\n\t\t(c3) -- [plain, edge label=--] (d2);\n\t\t(d1) -- [plain, edge label'=--] (e);\n\t\t(d2) -- [plain, edge label=+] (e);\n\t\t%-- [fermion, quarter right, edge label'=2] (a),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{center}\n\n\\begin{minipage}{0.2\\linewidth}\n\t\\hfill\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[small]\n\t\\vertex (a);\n\t\\vertex [below=of a] (b);\n\t\\vertex [below=of b] (c);\n\t\\vertex [below=of c] (d);\n\t%\\vertex [below=of d] (e);\n\t\\diagram[inline=(c)]{\n\t\t(a) -- [fermion, out=200, in=150, edge label'=a] (d)\n\t\t-- [fermion, out=45, in=330, edge label'=r] (b)\n\t\t-- [fermion, quarter left, edge label'=b] (c)\n\t\t-- [fermion, quarter left, edge label=s] (a)\n\t\t%-- [fermion, quarter right, edge label'=2] (a),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\t\\\\\n\t\\vspace{25pt}\\\\\n\\end{minipage}\n\\begin{minipage}{0.8\\linewidth}\n\t\\vspace{25pt}~\\\\\n\t\\begin{align}\n\t&= - \\sum_{a,r,b,s} \\dfrac{v_{ar}v_{rb}v_{bs}v_{sa}}{(\\varepsilon_a^{(0)} - \\varepsilon_r^{(0)})(\\varepsilon_a^{(0)} - \\varepsilon_s^{(0)})(\\varepsilon_a^{(0)} + \\varepsilon_b^{(0)} - \\varepsilon_r^{(0)} - \\varepsilon_s^{(0)})}  &\\notag\\\\\n\t&= -\\dfrac{1}{(2\\beta)^2\\times 4\\beta} \\sum_{i,j,k,l} \\Braket{i|v|j^*}\\Braket{j^*|v|k}\\Braket{k|v|l^*}\\Braket{l^*|v|i} & \\notag\\\\\n\t&= -\\dfrac{2}{(2\\beta)^2\\times 4\\beta} \\sum_i^{N/2} 6\\times (\\beta/2)^4  & \\notag\\\\\n\t&= -\\dfrac{3N\\beta}{128}  & \\notag\\\\\n\t\\end{align}\n\\end{minipage}\n%\\tikzfeynmanset{\n%}\nThe pictorial representation of the summation are as follows\\\\\n\\begin{center}\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[nodes=circle, large]\n\t\\vertex (a) {$ (i) $};\n\t\\vertex [below right=of a] (b1) {$ (i-1)^* $};\n\t\\vertex [above right=of a] (b2) {$ (i+1)^* $};\n\t\\vertex [below right=of b1] (c1) {$ (i-2) $};\n\t\\vertex [above right=of b1] (c2) {$ (i) $};\n\t\\vertex [above right=of b2] (c3) {$ (i+2) $};\n\t\\vertex [above right=of c1] (d1) {$ (i-1)^* $};\n\t\\vertex [above right=of c2] (d2) {$ (i+1)^* $};\n\t\\vertex [above right=of d1] (e) {$ (i) $};\n\t\\diagram[inline=(c)]{\n\t\t(a) -- [plain, edge label'=--] (b1);\n\t\t(a) -- [plain, edge label=+] (b2);\n\t\t(b1) -- [plain, edge label'=+] (c1);\n\t\t(b1) -- [plain, edge label'=--] (c2);\n\t\t(b2) -- [plain, edge label=+] (c2);\n\t\t(b2) -- [plain, edge label=--] (c3);\n\t\t(c1) -- [plain, edge label'=+] (d1);\n\t\t(c2) -- [plain, edge label'=--] (d1);\n\t\t(c2) -- [plain, edge label=+] (d2);\n\t\t(c3) -- [plain, edge label=--] (d2);\n\t\t(d1) -- [plain, edge label'=--] (e);\n\t\t(d2) -- [plain, edge label=+] (e);\n\t\t%-- [fermion, quarter right, edge label'=2] (a),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{center}\nthus\n\\begin{equation}\\label{key}\nE_0^{(4)} = 4\\times \\dfrac{N\\beta}{64} + 3\\times\\qty(-\\dfrac{3N\\beta}{128}) =  \\dfrac{N\\beta}{64}\n\\end{equation}\n\n\\subex{b.}\nLet $ N=6 $, we get\n\\begin{equation}\\label{key}\nE_0^{(4)} = \\dfrac{3\\beta}{32}\n\\end{equation}\nwhich agrees with the result in Ex 6.6.\n\n\\subsection{Perturbation Expansion of the Correlation Energy}\n\\ex{6.8}\n\\begin{align}\nE_0^{(2)} &= \n\\dfrac{1}{4}\\sum_{a,b,r,s} \\dfrac{\\abs{\\Braket{ab||rs}}^2}{\\varepsilon_a + \\varepsilon_b - \\varepsilon_r - \\varepsilon_s} \\notag\\\\\n&= \\dfrac{1}{4}\\sum_{a,b,r,s} \n\\dfrac{\\qty(\\Braket{ab|rs} - \\Braket{ab|sr}) \\qty(\\Braket{rs|ab} - \\Braket{sr|ab})}{\\varepsilon_a + \\varepsilon_b - \\varepsilon_r - \\varepsilon_s} \\notag\\\\\n&= \\dfrac{1}{4}\\sum_{a,b,r,s} \n\\dfrac{\\Braket{ab|rs}\\Braket{rs|ab} - \\Braket{ab|sr}\\Braket{rs|ab}  - \\Braket{ab|rs}\\Braket{sr|ab} + \\Braket{ab|sr}\\Braket{sr|ab}}{\\varepsilon_a + \\varepsilon_b - \\varepsilon_r - \\varepsilon_s} \\notag\\\\\n&= \\dfrac{1}{4}\\qty[\\sum_{a,b,r,s} \n\\dfrac{\\Braket{ab|rs}\\Braket{rs|ab}}{\\varepsilon_a + \\varepsilon_b - \\varepsilon_r - \\varepsilon_s}\n- \\sum_{a,b,r,s} \n\\dfrac{\\Braket{ab|sr}\\Braket{rs|ab}}{\\varepsilon_a + \\varepsilon_b - \\varepsilon_r - \\varepsilon_s}\n- \\sum_{a,b,r,s} \n\\dfrac{ \\Braket{ab|rs}\\Braket{sr|ab}}{\\varepsilon_a + \\varepsilon_b - \\varepsilon_r - \\varepsilon_s}\n+ \\sum_{a,b,r,s} \n\\dfrac{\\Braket{ab|sr}\\Braket{sr|ab}}{\\varepsilon_a + \\varepsilon_b - \\varepsilon_r - \\varepsilon_s}\n] \\notag\\\\\n&= \\dfrac{1}{4}\\qty[2\\sum_{a,b,r,s} \n\\dfrac{\\Braket{ab|rs}\\Braket{rs|ab}}{\\varepsilon_a + \\varepsilon_b - \\varepsilon_r - \\varepsilon_s}\n- 2\\sum_{a,b,r,s} \n\\dfrac{\\Braket{ab|rs}\\Braket{sr|ab}}{\\varepsilon_a + \\varepsilon_b - \\varepsilon_r - \\varepsilon_s}\n] \\notag\\\\\n&= \\dfrac{1}{2}\\sum_{a,b,r,s} \n\\dfrac{\\Braket{ab|rs}\\Braket{rs|ab}}{\\varepsilon_a + \\varepsilon_b - \\varepsilon_r - \\varepsilon_s}\n- \\dfrac{1}{2}\\sum_{a,b,r,s} \n\\dfrac{\\Braket{ab|rs}\\Braket{rs|ba}}{\\varepsilon_a + \\varepsilon_b - \\varepsilon_r - \\varepsilon_s}\n\\end{align}\nFor a closed-shell system, the possible spin part of $ a,b,r,s $ of the non-zero terms are\\\\\nfirst term: $ \\alpha,\\alpha,\\alpha,\\alpha $;\\quad $ \\alpha,\\beta,\\alpha,\\beta $;\\quad $ \\beta,\\alpha,\\beta,\\alpha $;\\quad $ \\beta,\\beta,\\beta,\\beta $\\\\\nsecond term: $ \\alpha,\\alpha,\\alpha,\\alpha $;\\quad $ \\beta,\\beta,\\beta,\\beta $\\\\\nthus\n\\begin{align}\nE_0^{(2)} &= 2\\sum_{a,b,r,s}^{N/2}\n\\dfrac{\\Braket{ab|rs}\\Braket{rs|ab}}{\\varepsilon_a + \\varepsilon_b - \\varepsilon_r - \\varepsilon_s}\n- \\sum_{a,b,r,s}^{N/2}\n\\dfrac{\\Braket{ab|rs}\\Braket{rs|ba}}{\\varepsilon_a + \\varepsilon_b - \\varepsilon_r - \\varepsilon_s}\n\\end{align}\n\n\\ex{6.9}\n\\begin{align}\nE_{\\corr} &= \\Delta - (\\Delta^2 + K_{12}^2)^{1/2} \\notag\\\\\n&= \\Delta - \\qty[\\Delta + \\dfrac{K_{12}^2}{2\\Delta}] \\notag\\\\\n&= - \\dfrac{K_{12}^2}{2\\Delta} \\notag\\\\\n&= - \\dfrac{K_{12}^2}{2(\\varepsilon_2-\\varepsilon_1) + J_{11} + J_{22} - 4J_{12} + 2K_{12}} \\notag\\\\\n&= - K_{12}^2 \\qty(\\dfrac{1}{2(\\varepsilon_2-\\varepsilon_1)} - \\dfrac{ J_{11} + J_{22} - 4J_{12} + 2K_{12}}{4(\\varepsilon_2-\\varepsilon_1)^2}) \\notag\\\\\n&= \\dfrac{K_{12}^2}{2(\\varepsilon_1-\\varepsilon_2)} + \\dfrac{K_{12}^2 (J_{11} + J_{22} - 4J_{12} + 2K_{12})}{4(\\varepsilon_1-\\varepsilon_2)^2})\n\\end{align}\n\n\\subsection{The $ N $-dependence of the RS Perturbation Expansion}\n\\ex{6.10}\nFrom Eq 6.68, we get\n\\begin{align}\nE_0^{(1)} &= \\Braket{\\Psi_0 | \\mathscr{V} | \\Psi_0} = -\\dfrac{1}{2}\\sum_{ab}\\Braket{ab||ab} \\notag\\\\\n&= -\\dfrac{1}{2}\\sum_{i=1}^N \\qty[\\Braket{1_i \\bar{1}_i|| 1_i \\bar{1}_i} + \\Braket{\\bar{1}_i 1_i || \\bar{1}_i 1_i}] \\notag\\\\\n&= -\\dfrac{1}{2}\\sum_{i=1}^N \n\\qty[\\Braket{1_i \\bar{1}_i| 1_i \\bar{1}_i} \n- \\Braket{1_i \\bar{1}_i| \\bar{1}_i 1_i} \n+ \\Braket{\\bar{1}_i 1_i | \\bar{1}_i 1_i}\n- \\Braket{\\bar{1}_i 1_i | 1_i \\bar{1}_i} ] \\notag\\\\\n&= -\\dfrac{1}{2}\\times 2N [1_i 1_i| 1_i 1_i] \\notag\\\\\n&= -N J_{11}\n\\end{align}\n\\begin{align}\n\\Braket{\\Psi_{1_i\\bar{1}_i}^{2_i\\bar{2}_i} | \\mathscr{V} | \\Psi_{1_i\\bar{1}_i}^{2_i\\bar{2}_i}} \n&= \\Braket{\\Psi_{1_i\\bar{1}_i}^{2_i\\bar{2}_i} | \\sH | \\Psi_{1_i\\bar{1}_i}^{2_i\\bar{2}_i}} \n- \\Braket{\\Psi_{1_i\\bar{1}_i}^{2_i\\bar{2}_i} | \\sH_0 | \\Psi_{1_i\\bar{1}_i}^{2_i\\bar{2}_i}} \\notag\\\\\n&= (2N-2) h_{11} + 2h_{22} + (N-1)J_{11} + J_{22} - (2N-2)\\varepsilon_1 - 2\\varepsilon_2 \\notag\\\\\n&= (2N-2) h_{11} + 2h_{22} + (N-1)J_{11} + J_{22} - (2N-2)(h_{11} + J_{11}) - 2(h_{22} + 2J_{12} - K_{12}) \\notag\\\\\n&= -(N-1)J_{11} + J_{22} - 4J_{12} + 2K_{12}\n\\end{align}\n\n\\subsection{Diagrammatic Representation of the Perturbation Expansion of the Correlation Energy}\n\n\\subsubsection{Hugenholtz Diagrams}\n\\ex{6.11}\nThe numerator and denominator are obvious.\\\\\n$ h=5 $, and $ l=2 $ since closed loops are $ r\\ra a\\ra d\\ra t\\ra e\\ra r; \\; s\\ra c\\ra b\\ra s $. The number of quivalent line pairs is one ($ r,s $). Thus the pre-factor is $ -\\dfrac{1}{2} $.\n\n\\subsubsection{Goldstone Diagrams}\n\\ex{6.12}\n~\\\\\n1\n\\begin{minipage}{0.4\\linewidth}\n\t\\centering\n\\begin{tikzpicture}\n\\begin{feynman}[large]\n\\vertex (a); \\vertex [below=of a] (b);\n\\vertex [right=of a] (c); \\vertex [right=of b] (d);\n\n\\diagram[%inline=(e.base)\n]{\n\t(a) -- [fermion,  quarter left, edge label=r] (b)\n\t-- [fermion, quarter left, edge label=a] (a),\n\t(c)-- [fermion, quarter left, edge label=s] (d)\n\t-- [fermion, quarter left, edge label=b] (c),\n\t(a) -- [scalar] (c),\n\t(b) -- [scalar] (d),\n\t%-- [fermion, quarter right, edge label'=2] (a),\n};\n\\end{feynman}\n\\end{tikzpicture}\n\\end{minipage}\n$ \\lra  $\n\\begin{minipage}{0.4\\linewidth}\n\t\\centering\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[large]\n\t\\vertex (a); \\vertex [below=of a] (b);\n\t%\\vertex [right=of a] (c); %\\vertex [right=of b] (d);\n\t\\diagram[%inline=(e.base)\n\t]{\n\t\t(a) -- [fermion,  half left, edge label=r] (b)\n\t\t-- [fermion, half left, edge label=a] (a),\n\t\t(a)-- [fermion, quarter left, edge label=s] (b)\n\t\t-- [fermion, quarter left, edge label=b] (a),\n\t\t%(a) -- [scalar] (c),\n\t\t%(b) -- [scalar] (d),\n\t\t%-- [fermion, quarter right, edge label'=2] (a),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n~\\\\\n~\\vspace{10pt}\\\\\n2\n\\begin{minipage}{0.4\\linewidth}\n\t\\centering\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[large]\n\t\\vertex (a); \\vertex [below=of a] (b);\n\t\\vertex [right=of a] (c); \\vertex [right=of b] (d);\n\t\n\t\\diagram[%inline=(e.base)\n\t]{\n\t\t(a) -- [fermion, out=-60, in=150, edge label'=b] (d)\n\t\t-- [fermion, quarter right, edge label=s] (c),\n\t\t(c)-- [fermion, out=240, in=30, edge label=a] (b)\n\t\t-- [fermion, quarter left, edge label=r] (a),\n\t\t(a) -- [scalar] (c),\n\t\t(b) -- [scalar] (d),\n\t\t%-- [fermion, quarter right, edge label'=2] (a),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n$ \\lra  $\n\\begin{minipage}{0.4\\linewidth}\n\t\\centering\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[large]\n\t\\vertex (a); \\vertex [below=of a] (b);\n\t%\\vertex [right=of a] (c); %\\vertex [right=of b] (d);\n\t\\diagram[%inline=(e.base)\n\t]{\n\t\t(b) -- [fermion,  half right, edge label'=r] (a),\n\t\t(b) -- [fermion, half left, edge label'=s] (a),\n\t\t(a)-- [fermion, quarter left, edge label=a] (b),\n\t\t(a) -- [fermion, quarter right, edge label=b] (b),\n\t\t%(a) -- [scalar] (c),\n\t\t%(b) -- [scalar] (d),\n\t\t%-- [fermion, quarter right, edge label'=2] (a),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n~\\\\\n~\\vspace{10pt}\\\\\n1\n\\begin{minipage}{0.4\\linewidth}\n\t\\centering\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[large]\n\t\\vertex (a); \\vertex [below=2.4cm of a] (b);\n\t\\vertex [right=2.5cm of a] (c); \\vertex [right=2.5cm of b] (d);\n\t\\vertex at ($(a)!0.5!(b) + (0.7cm, 0)$) (e); \\vertex at ($(c)!0.5!(d) + (-0.7cm, 0)$) (f);\n\t\n\t\\diagram[%inline=(e.base)\n\t]{\n\t\t(a) -- [anti fermion,  quarter left, edge label=t] (e) \n\t\t-- [anti fermion,  quarter left, edge label=r] (b)\n\t\t-- [anti fermion, quarter left, edge label=a] (a),\n\t\t(c) -- [fermion, quarter left, edge label=b] (d)\n\t\t-- [fermion, quarter left, edge label=u] (f)\n\t\t-- [fermion, quarter left, edge label=s] (c),\n\t\t(a) -- [scalar] (c),\n\t\t(b) -- [scalar] (d),\n\t\t(e) -- [scalar] (f),\n\t\t%-- [fermion, quarter right, edge label'=2] (a),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n$ \\lra  $\n\\begin{minipage}{0.4\\linewidth}\n\t\\centering\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[large]\n\t\\vertex (a); \\vertex [below=of a] (b);\n\t%\\vertex [right=of a] (c); %\\vertex [right=of b] (d);\n\t\\vertex at ($(a)!0.5!(b) $) (e);\n\t\\diagram[%inline=(e.base)\n\t]{\n\t\t(a) -- [anti fermion,  quarter left, edge label=t] (e) \n\t\t-- [anti fermion,  quarter left, edge label=r] (b)\n\t\t-- [anti fermion, half left, edge label=a] (a),\n\t\t(a) -- [fermion, half left, edge label=b] (b)\n\t\t-- [fermion, quarter left, edge label=u] (e)\n\t\t-- [fermion, quarter left, edge label=s] (a),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n~\\\\\n~\\vspace{10pt}\\\\\n2\n\\begin{minipage}{0.4\\linewidth}\n\t\\centering\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[large]\n\t\\vertex (a); \\vertex [below=2.4cm of a] (b);\n\t\\vertex [right=2.5cm of a] (c); \\vertex [right=2.5cm of b] (d);\n\t\\vertex at ($(a)!0.5!(b) + (0.7cm, 0)$) (e); \\vertex at ($(c)!0.5!(d) + (-0.7cm, 0)$) (f);\n\t\n\t\\diagram[%inline=(e.base)\n\t]{\n\t\t(a) -- [fermion,  quarter left, edge label=c] (e) \n\t\t-- [ fermion,  quarter left, edge label=a] (b)\n\t\t-- [ fermion, quarter left, edge label=r] (a),\n\t\t(c) -- [anti fermion, quarter left, edge label=s] (d)\n\t\t-- [anti fermion, quarter left, edge label=d] (f)\n\t\t-- [anti fermion, quarter left, edge label=b] (c),\n\t\t(a) -- [scalar] (c),\n\t\t(b) -- [scalar] (d),\n\t\t(e) -- [scalar] (f),\n\t\t%-- [fermion, quarter right, edge label'=2] (a),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n$ \\lra  $\n\\begin{minipage}{0.4\\linewidth}\n\t\\centering\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[large]\n\t\\vertex (a); \\vertex [below=2.4cm of a] (b);\n\t%\\vertex [right=2.5cm of a] (c); \\vertex [right=2.5cm of b] (d);\n\t\\vertex at ($(a)!0.5!(b) $) (e); \n\t%\\vertex at ($(c)!0.5!(d) + (-0.7cm, 0)$) (f);\n\t\n\t\\diagram[%inline=(e.base)\n\t]{\n\t\t(a) -- [fermion,  quarter left, edge label=c] (e) \n\t\t-- [ fermion,  quarter left, edge label=a] (b)\n\t\t-- [ fermion, half left, edge label=r] (a),\n\t\t(a) -- [anti fermion, half left, edge label=s] (b)\n\t\t-- [anti fermion, quarter left, edge label=d] (e)\n\t\t-- [anti fermion, quarter left, edge label=b] (a),\n\t\t%(a) -- [scalar] (c),\n\t\t%(b) -- [scalar] (d),\n\t\t%(e) -- [scalar] (f),\n\t\t%-- [fermion, quarter right, edge label'=2] (a),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n~\\\\\n~\\vspace{10pt}\\\\\n3\n\\begin{minipage}{0.4\\linewidth}\n\t\\centering\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[large]\n\t\\vertex (a); \\vertex [below=2.4cm of a] (b);\n\t\\vertex [right=2.5cm of a] (c); \\vertex [right=2.5cm of b] (d);\n\t\\vertex at ($(a)!0.5!(b) + (0.7cm, 0)$) (e); \\vertex at ($(c)!0.5!(d) + (-0.7cm, 0)$) (f);\n\t\n\t\\diagram[%inline=(e.base)\n\t]{\n\t\t(a) -- [anti fermion,  quarter left, edge label=s] (e) \n\t\t-- [anti fermion,  quarter left, edge label=r] (b)\n\t\t-- [anti fermion, quarter left, edge label=a] (a),\n\t\t(c) -- [anti fermion, quarter left, edge label=t] (d)\n\t\t-- [anti fermion, quarter left, edge label=c] (f)\n\t\t-- [anti fermion, quarter left, edge label=b] (c),\n\t\t(a) -- [scalar] (c),\n\t\t(b) -- [scalar] (d),\n\t\t(e) -- [scalar] (f),\n\t\t%-- [fermion, quarter right, edge label'=2] (a),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n$ \\lra $\n\\begin{minipage}{0.4\\linewidth}\n\t\\centering\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[large]\n\t\\vertex (a); \\vertex [below=2.4cm of a] (b);\n\t%\\vertex [right=2.5cm of a] (c); \\vertex [right=2.5cm of b] (d);\n\t\\vertex at ($(a)!0.5!(b) $) (e); \n\t%\\vertex at ($(c)!0.5!(d) + (-0.7cm, 0)$) (f);\n\t\n\t\\diagram[%inline=(e.base)\n\t]{\n\t\t(a) -- [anti fermion,  quarter left, edge label=s] (e) \n\t\t-- [anti fermion,  quarter left, edge label=r] (b)\n\t\t-- [anti fermion, half left, edge label=a] (a),\n\t\t(a) -- [anti fermion, half left, edge label=t] (b)\n\t\t-- [anti fermion, quarter left, edge label=c] (e)\n\t\t-- [anti fermion, quarter left, edge label=b] (a),\n\t\t%(a) -- [scalar] (c),\n\t\t%(b) -- [scalar] (d),\n\t\t%(e) -- [scalar] (f),\n\t\t%-- [fermion, quarter right, edge label'=2] (a),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n~\\\\\n~\\vspace{10pt}\\\\\n4\n\\begin{minipage}{0.4\\linewidth}\n\t\\centering\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[large]\n\t\\vertex (a); \\vertex [below=2.4cm of a] (b);\n\t\\vertex [right=2.5cm of a] (c); \\vertex [right=2.5cm of b] (d);\n\t\\vertex at ($(a)!0.5!(b) + (-0.7cm, 0)$) (e); \\vertex at ($(a)!0.5!(b) + (0.7cm, 0)$) (f);\n\t\n\t\\diagram[%inline=(e.base)\n\t]{\n\t\t(a) -- [fermion,  quarter left, edge label=a] (f) \n\t\t-- [ fermion,  quarter left, edge label=b] (b)\n\t\t-- [ fermion, quarter left, edge label=r] (e)\n\t\t-- [ fermion, quarter left, edge label=s] (a),\n\t\t(c) -- [fermion, quarter left, edge label=c] (d)\n\t\t%-- [anti fermion, quarter left, edge label=d] (f)\n\t\t-- [fermion, quarter left, edge label=t] (c),\n\t\t(a) -- [scalar] (c),\n\t\t(b) -- [scalar] (d),\n\t\t(e) -- [scalar] (f),\n\t\t%-- [fermion, quarter right, edge label'=2] (a),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n$ \\lra  $\n\\begin{minipage}{0.4\\linewidth}\n\t\\centering\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[large]\n\t\\vertex (a); \\vertex [below=2.4cm of a] (b);\n\t%\\vertex [right=2.5cm of a] (c); \\vertex [right=2.5cm of b] (d);\n\t\\vertex at ($(a)!0.5!(b) $) (e); \n\t%\\vertex at ($(a)!0.5!(b) + (0.7cm, 0)$) (f);\n\t\n\t\\diagram[%inline=(e.base)\n\t]{\n\t\t(a) -- [fermion,  quarter left, edge label=a] (e) \n\t\t-- [ fermion,  quarter left, edge label=b] (b)\n\t\t-- [ fermion, quarter left, edge label=r] (e)\n\t\t-- [ fermion, quarter left, edge label=s] (a),\n\t\t(a) -- [fermion, half left, edge label=c] (b)\n\t\t%-- [anti fermion, quarter left, edge label=d] (f)\n\t\t-- [fermion, half left, edge label=t] (a),\n\t\t%(a) -- [scalar] (c),\n\t\t%(b) -- [scalar] (d),\n\t\t%(e) -- [scalar] (f),\n\t\t%-- [fermion, quarter right, edge label'=2] (a),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n~\\\\\n~\\vspace{10pt}\\\\\n5\n\\begin{minipage}{0.4\\linewidth}\n\t\\centering\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[large]\n\t\\vertex (a); \\vertex [below=2.4cm of a] (b);\n\t\\vertex [right= of a] (c); \\vertex [right=4cm of b] (d);\n\t\\vertex [below=1.2cm of c] (e); \\vertex [right= of e] (f);\n\t\n\t\\diagram[%inline=(e.base)\n\t]{\n\t\t(a) %-- [fermion,  quarter left, edge label=a] (f) \n\t\t-- [ fermion,  quarter left, edge label=a] (b)\n\t\t%-- [ fermion, quarter left, edge label=r] (e)\n\t\t-- [ fermion, quarter left, edge label=r] (a),\n\t\t(c) -- [fermion, quarter left, edge label=b] (e)\n\t\t%-- [anti fermion, quarter left, edge label=d] (f)\n\t\t-- [fermion, quarter left, edge label=s] (c),\n\t\t(f) -- [fermion, quarter left, edge label=c] (d)\n\t\t%-- [anti fermion, quarter left, edge label=d] (f)\n\t\t-- [fermion, quarter left, edge label=t] (f),\n\t\t(a) -- [scalar] (c),\n\t\t(b) -- [scalar] (d),\n\t\t(e) -- [scalar] (f),\n\t\t%-- [fermion, quarter right, edge label'=2] (a),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n$ \\lra  $\n\\begin{minipage}{0.4\\linewidth}\n\t\\centering\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[large]\n\t\\vertex (a); \\vertex [below=2.4cm of a] (b);\n\t%\\vertex [right= of a] (c); \\vertex [right=4cm of b] (d);\n\t\\vertex [below=1.2cm of a] (e); %\\vertex [right= of e] (f);\n\t\n\t\\diagram[%inline=(e.base)\n\t]{\n\t\t(a) %-- [fermion,  quarter left, edge label=a] (f) \n\t\t-- [ fermion,  half left, edge label=a] (b)\n\t\t%-- [ fermion, quarter left, edge label=r] (e)\n\t\t-- [ fermion, half left, edge label=r] (a),\n\t\t(a) -- [fermion, quarter left, edge label=b] (e)\n\t\t%-- [anti fermion, quarter left, edge label=d] (f)\n\t\t-- [fermion, quarter left, edge label=s] (a),\n\t\t(e) -- [fermion, quarter left, edge label=c] (b)\n\t\t%-- [anti fermion, quarter left, edge label=d] (f)\n\t\t-- [fermion, quarter left, edge label=t] (e),\n\t\t%(a) -- [scalar] (c),\n\t\t%(b) -- [scalar] (d),\n\t\t%(e) -- [scalar] (f),\n\t\t%-- [fermion, quarter right, edge label'=2] (a),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n\n~\\\\\n~\\vspace{10pt}\\\\\n6\n\\begin{minipage}{0.4\\linewidth}\n\t\\centering\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[large]\n\t\\vertex (a); \\vertex [below=2.4cm of a] (b);\n\t\\vertex [right=2.5cm of a] (c); \\vertex [right=2.5cm of b] (d);\n\t\\vertex at ($(a)!0.5!(b) + (0.6cm, 0)$) (e); \\vertex at ($(c)!0.5!(d) + (-0.6cm, 0)$) (f);\n\t\n\t\\diagram[%inline=(e.base)\n\t]{\n\t\t(a) -- [fermion,  quarter left, edge label=a] (e) \n\t\t-- [ fermion,  edge label=s] (c)\n\t\t-- [ fermion, quarter left, edge label=b] (d)\n\t\t-- [ fermion, quarter left, edge label=t] (f)\n\t\t-- [fermion, edge label=c] (b)\n\t\t%-- [anti fermion, quarter left, edge label=d] (f)\n\t\t-- [fermion, quarter left, edge label=r] (a),\n\t\t(a) -- [scalar] (c),\n\t\t(b) -- [scalar] (d),\n\t\t(e) -- [scalar] (f),\n\t\t%-- [fermion, quarter right, edge label'=2] (a),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n$ \\lra  $\n\\begin{minipage}{0.4\\linewidth}\n\t\\centering\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[large]\n\t\\vertex (a); \\vertex [below=2.4cm of a] (b);\n\t%\\vertex [right=2.5cm of a] (c); \\vertex [right=2.5cm of b] (d);\n\t\\vertex at ($(a)!0.5!(b)$) (e); %\\vertex at ($(c)!0.5!(d) + (-0.6cm, 0)$) (f);\n\t\n\t\\diagram[%inline=(e.base)\n\t]{\n\t\t(a) -- [fermion,  quarter left, edge label=a] (e) \n\t\t-- [ fermion,  quarter left, edge label=s] (a)\n\t\t-- [ fermion, half left, edge label=b] (b)\n\t\t-- [ fermion, quarter left, edge label=t] (e)\n\t\t-- [fermion, quarter left, edge label=c] (b)\n\t\t%-- [anti fermion, quarter left, edge label=d] (f)\n\t\t-- [fermion, half left, edge label=r] (a),\n\t\t%(a) -- [scalar] (c),\n\t\t%(b) -- [scalar] (d),\n\t\t%(e) -- [scalar] (f),\n\t\t%-- [fermion, quarter right, edge label'=2] (a),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n~\\\\\n~\\vspace{10pt}\\\\\n7\n\\begin{minipage}{0.4\\linewidth}\n\t\\centering\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[large]\n\t\\vertex (a); \\vertex [below=2.4cm of a] (b);\n\t\\vertex [right=2.5cm of a] (c); \\vertex [right=2.5cm of b] (d);\n\t\\vertex at ($(a)!0.5!(b) + (-0.6cm, 0)$) (e); \\vertex at ($(c)!0.5!(d) + (0.6cm, 0)$) (f);\n\t\n\t\\diagram[]{\n\t\t(a) -- [fermion,  quarter right, edge label'=d] (e) \n\t\t-- [ fermion,  quarter right,  edge label'=a] (b)\n\t\t-- [ fermion,out=20, in=-120,  edge label'=r] (c)\n\t\t-- [ fermion, quarter left, edge label=b] (f)\n\t\t-- [fermion, quarter left, edge label=c] (d)\n\t\t%-- [anti fermion, quarter left, edge label=d] (f)\n\t\t-- [fermion,out=160, in=-60, edge label=s] (a),\n\t\t(a) -- [scalar] (c),\n\t\t(b) -- [scalar] (d),\n\t\t(e) -- [scalar] (f),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n$ \\lra  $\n\\begin{minipage}{0.4\\linewidth}\n\t\\centering\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[large]\n\t\\vertex (a); \\vertex [below=2.4cm of a] (b);\n\t%\\vertex [right=2.5cm of a] (c); \\vertex [right=2.5cm of b] (d);\n\t\\vertex at ($(a)!0.5!(b) $) (e); %\\vertex at ($(c)!0.5!(d) + (0.6cm, 0)$) (f);\n\t\n\t\\diagram[]{\n\t\t(a) -- [fermion,  \\qr, \\el'=d] (e) -- [ fermion,  \\qr,  \\el'=a] (b)\n\t\t-- [ fermion, \\hfr,  \\el'=r] (a) -- [ fermion, \\ql, \\el=b] (e)\n\t\t-- [fermion, \\ql, \\el=c] (b)\n\t\t%-- [anti fermion, quarter left, edge label=d] (f)\n\t\t-- [fermion, \\hfl, \\el=s] (a),\n\t\t%(a) -- [scalar] (c),\n\t\t%(b) -- [scalar] (d),\n\t\t%(e) -- [scalar] (f),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n~\\\\\n~\\vspace{10pt}\\\\\n8\n\\begin{minipage}{0.4\\linewidth}\n\t\\centering\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[large]\n\t\\vertex (a); \\vertex [below=2.4cm of a] (b);\n\t\\vertex [right=2.5cm of a] (c); \\vertex [right=2.5cm of b] (d);\n\t\\vertex at ($(a)!0.5!(b) + (0.7cm, 0)$) (e); \\vertex at ($(c)!0.5!(d) + (-0.7cm, 0)$) (f);\t\n\t\\diagram[]{\n\t\t(a) -- [fermion,  \\qr, \\el'=a] (b) -- [ fermion, \\el=r] (f)\n\t\t-- [ fermion,  \\el'=s] (c) -- [ fermion, \\ql, \\el=b] (d)\n\t\t-- [fermion,  \\el'=t] (e) -- [fermion, \\el=u] (a),\n\t\t(a) -- [scalar] (c), \t(b) -- [scalar] (d), (e) -- [scalar] (f),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n$ \\lra  $\n\\begin{minipage}{0.4\\linewidth}\n\t\\centering\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[large]\n\t\\vertex (a); \\vertex [below=2.4cm of a] (b);\n\t%\\vertex [right=2.5cm of a] (c); \\vertex [right=2.5cm of b] (d);\n\t\\vertex at ($(a)!0.5!(b) $) (e); %\\vertex at ($(c)!0.5!(d) + (-0.7cm, 0)$) (f);\t\n\t\\diagram[]{\n\t\t(a) -- [fermion,  \\hfr, \\el'=a] (b) -- [ fermion,\\qr, \\el'=r] (e)\n\t\t-- [ fermion, \\qr, \\el'=s] (a) -- [ fermion, \\hfl, \\el=b] (b)\n\t\t-- [fermion, \\ql, \\el=t] (e) -- [fermion, \\ql,\\el=u] (a),\n\t\t%(a) -- [scalar] (c), \t(b) -- [scalar] (d), (e) -- [scalar] (f),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n~\\\\\n~\\vspace{10pt}\\\\\n9\n\\begin{minipage}{0.4\\linewidth}\n\t\\centering\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[large]\n\t\\vertex (a); \\vertex [below=2.4cm of a] (b);\n\t\\vertex [right=2.5cm of a] (c); \\vertex [right=2.5cm of b] (d);\n\t\\vertex at ($(a)!0.5!(b) + (-0.7cm, 0)$) (e); \\vertex at ($(a)!0.5!(b) + (0.7cm, 0)$) (f);\t\n\t\\diagram[]{\n\t\t(a) -- [fermion,  \\qr, \\el'=a] (e) -- [ fermion, \\qr, \\el'=b] (b)\n\t\t-- [ fermion,  \\el'=r] (f) -- [ fermion, \\el=s] (c)\n\t\t-- [fermion, \\ql, \\el'=c] (d) -- [fermion, \\el'=t] (a),\n\t\t(a) -- [scalar] (c), \t(b) -- [scalar] (d), (e) -- [scalar] (f),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n$ \\lra  $\n\\begin{minipage}{0.4\\linewidth}\n\t\\centering\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[large]\n\t\\vertex (a); \\vertex [below=2.4cm of a] (b);\n\t%\\vertex [right=2.5cm of a] (c); \\vertex [right=2.5cm of b] (d);\n\t\\vertex at ($(a)!0.5!(b) $) (e); %\\vertex at ($(a)!0.5!(b) + (0.7cm, 0)$) (f);\t\n\t\\diagram[]{\n\t\t(a) -- [fermion,  \\qr, \\el'=a] (e) -- [ fermion, \\qr, \\el'=b] (b)\n\t\t-- [ fermion, \\qr, \\el'=r] (e) -- [ fermion, \\qr, \\el'=s] (a)\n\t\t-- [fermion, \\hfl, \\el=c] (b) -- [fermion, \\hfl, \\el=t] (a),\n\t\t%(a) -- [scalar] (c), \t(b) -- [scalar] (d), (e) -- [scalar] (f),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n~\\\\\n~\\vspace{10pt}\\\\\n10\n\\begin{minipage}{0.4\\linewidth}\n\t\\centering\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[large]\n\t\\vertex (a); \\vertex [below=2.4cm of a] (b);\n\t\\vertex [right=2.5cm of a] (c); \\vertex [right=2.5cm of b] (d);\n\t\\vertex at ($(a)!0.5!(b) + (-0.7cm, 0)$) (e); \\vertex at ($(a)!0.5!(b) + (0.7cm, 0)$) (f);\t\n\t\\diagram[]{\n\t\t(a) -- [fermion,  \\el'=s] (f) -- [ fermion, \\el'=r] (d)\n\t\t-- [ fermion, \\qr,  \\el'=c] (c) -- [ fermion, \\el'=t] (b)\n\t\t-- [fermion, \\ql, \\el=b] (e) -- [fermion,\\ql, \\el=a] (a),\n\t\t(a) -- [scalar] (c), \t(b) -- [scalar] (d), (e) -- [scalar] (f),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n$ \\lra  $\n\\begin{minipage}{0.4\\linewidth}\n\t\\centering\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[large]\n\t\\vertex (a); \\vertex [below=2.4cm of a] (b);\n\t%\\vertex [right=2.5cm of a] (c); \\vertex [right=2.5cm of b] (d);\n\t\\vertex at ($(a)!0.5!(b) $) (e); %\\vertex at ($(a)!0.5!(b) + (0.7cm, 0)$) (f);\t\n\t\\diagram[]{\n\t\t(a) -- [fermion, \\ql, \\el=s] (e) -- [ fermion,\\ql, \\el=r] (b)\n\t\t-- [ fermion, \\hfr,  \\el'=c] (a) -- [ fermion, \\hfr, \\el'=t] (b)\n\t\t-- [fermion, \\ql, \\el=b] (e) -- [fermion,\\ql, \\el=a] (a),\n\t\t%(a) -- [scalar] (c), \t(b) -- [scalar] (d), (e) -- [scalar] (f),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n~\\\\\n~\\vspace{10pt}\\\\\n11\n\\begin{minipage}{0.4\\linewidth}\n\t\\centering\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[large]\n\t\\vertex (a); \\vertex [below=2.4cm of a] (b);\n\t\\vertex [right=3.5cm of a] (c); \\vertex [right= of b] (d);\n\t\\vertex [above=1.2cm of d] (e); \\vertex [below=1.2cm of c] (f);\t\n\t\\diagram[]{\n\t\t(a) -- [fermion,  \\el'=b] (d) -- [ fermion, \\qr, \\el'=s] (e)\n\t\t-- [ fermion,  \\el=a] (b) -- [ fermion, \\ql, \\el=r] (a),\n\t\t(c) -- [fermion, \\ql, \\el=c] (f) -- [fermion,\\ql, \\el=t] (c),\n\t\t(a) -- [scalar] (c), \t(b) -- [scalar] (d), (e) -- [scalar] (f),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n$ \\lra  $\n\\begin{minipage}{0.4\\linewidth}\n\t\\centering\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[large]\n\t\\vertex (a); \\vertex [below=2.4cm of a] (b);\n\t%\\vertex [right=3.5cm of a] (c); \\vertex [right= of b] (d);\n\t\\vertex at ($(a)!0.5!(b)$) (e); %\\vertex [below=1.2cm of c] (f);\t\n\t\\diagram[]{\n\t\t(a) -- [fermion, \\hfl, \\el=b] (b) -- [ fermion, \\qr, \\el'=s] (e)\n\t\t-- [ fermion, \\qr, \\el'=a] (b) -- [ fermion, \\hfl, \\el=r] (a),\n\t\t(a) -- [fermion, \\ql, \\el=c] (e) -- [fermion,\\ql, \\el=t] (a),\n\t\t%(a) -- [scalar] (c), \t(b) -- [scalar] (d), (e) -- [scalar] (f),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n~\\\\~\\vspace{10pt}\\\\\n12\n\\begin{minipage}{0.4\\linewidth}\n\t\\centering\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[large]\n\t\\vertex (a); \\vertex [below=2.4cm of a] (b);\n\t\\vertex [right=of a] (c); \\vertex [right=3.5cm of b] (d);\n\t\\vertex [above=1.2cm of d] (f); \\vertex [below=1.2cm of c] (e);\t\n\t\\diagram[]{\n\t\t(a) -- [fermion,  \\el'=a] (e) -- [ fermion, \\qr, \\el'=s] (c)\n\t\t-- [ fermion,  \\el=b] (b) -- [ fermion, \\ql, \\el=r] (a),\n\t\t(f) -- [fermion, \\ql, \\el=c] (d) -- [fermion,\\ql, \\el=t] (f),\n\t\t(a) -- [scalar] (c), \t(b) -- [scalar] (d), (e) -- [scalar] (f),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n$ \\lra  $\n\\begin{minipage}{0.4\\linewidth}\n\t\\centering\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[large]\n\t\\vertex (a); \\vertex [below=2.4cm of a] (b);\n\t%\\vertex [right=of a] (c); \\vertex [right=3.5cm of b] (d);\n\t%\\vertex [above=1.2cm of d] (f); \n\t\\vertex [below=1.2cm of a] (e);\t\n\t\\diagram[]{\n\t\t(a) -- [fermion, \\qr, \\el'=a] (e) -- [ fermion, \\qr, \\el'=s] (a)\n\t\t-- [ fermion, \\hfl, \\el=b] (b) -- [ fermion, \\hfl, \\el=r] (a),\n\t\t(e) -- [fermion, \\ql, \\el=c] (b) -- [fermion,\\ql, \\el=t] (e),\n\t\t%(a) -- [scalar] (c), \t(b) -- [scalar] (d), (e) -- [scalar] (f),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n~\\\\\n~\\\\~\\\\\nFor the Hugenholtz diagram provided, its value is\\\\\n\\begin{minipage}{0.3\\linewidth}\n\t\\centering\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[large]\n\t\\vertex (a); \\vertex [below=of a] (b);\n\t%\\vertex [right=of a] (c); %\\vertex [right=of b] (d);\n\t\\vertex at ($(a)!0.5!(b) $) (e);\n\t\\diagram[%inline=(e.base)\n\t]{\n\t\t(a) -- [anti fermion,  quarter left, edge label=t] (e) \n\t\t-- [anti fermion,  quarter left, edge label=r] (b)\n\t\t-- [anti fermion, half left, edge label=a] (a),\n\t\t(a) -- [fermion, half left, edge label=b] (b)\n\t\t-- [fermion, quarter left, edge label=u] (e)\n\t\t-- [fermion, quarter left, edge label=s] (a),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n\\begin{minipage}{0.6\\linewidth}\n\t\\vskip0.6cm\n\\begin{align}\n&= \\qty(\\dfrac{1}{2})^3 (-1)^{2+2} \\sum_{a,b,r,s,u,t} \\dfrac{\\Braket{ab||ru} \\Braket{ru||ts}\\Braket{ts||ab}}{(\\varepsilon_a + \\varepsilon_b - \\varepsilon_u - \\varepsilon_r)(\\varepsilon_a + \\varepsilon_b - \\varepsilon_s - \\varepsilon_t)} &&& \\notag\\\\\n& =\\dfrac{1}{8} \\sum_{a,b,r,s,u,t} \\dfrac{\\Braket{ab||ru} \\Braket{ru||ts}\\Braket{ts||ab}}{(\\varepsilon_a + \\varepsilon_b - \\varepsilon_u - \\varepsilon_r)(\\varepsilon_a + \\varepsilon_b - \\varepsilon_s - \\varepsilon_t)}  &&&\n\\notag\n\\end{align}\n\\end{minipage}\n\\begin{align}\n&=\\dfrac{1}{8} \\sum_{a,b,r,s,u,t} \\dfrac{(\\Braket{ab|ru}-\\Braket{ab|ur}) (\\Braket{ru|ts}-\\Braket{ru|st}) (\\Braket{ts|ab}-\\Braket{ts|ba})}{(\\varepsilon_a + \\varepsilon_b - \\varepsilon_u - \\varepsilon_r)(\\varepsilon_a + \\varepsilon_b - \\varepsilon_s - \\varepsilon_t)}  \\notag\\\\\n&= \\dfrac{1}{8} \\sum_{a,b,r,s,u,t} \\dfrac{\\Braket{ab|ru} \\Braket{ru|ts} \\Braket{ts|ab}}{(\\varepsilon_a + \\varepsilon_b - \\varepsilon_u - \\varepsilon_r)(\\varepsilon_a + \\varepsilon_b - \\varepsilon_s - \\varepsilon_t)} \n- \\dfrac{1}{8} \\sum_{a,b,r,s,u,t} \\dfrac{\\Braket{ab|ur} \\Braket{ru|ts} \\Braket{ts|ab}}{(\\varepsilon_a + \\varepsilon_b - \\varepsilon_u - \\varepsilon_r)(\\varepsilon_a + \\varepsilon_b - \\varepsilon_s - \\varepsilon_t)} \\notag\\\\\n&\\quad{} - \\dfrac{1}{8} \\sum_{a,b,r,s,u,t} \\dfrac{\\Braket{ab|ru} \\Braket{ru|st} \\Braket{ts|ab}}{(\\varepsilon_a + \\varepsilon_b - \\varepsilon_u - \\varepsilon_r)(\\varepsilon_a + \\varepsilon_b - \\varepsilon_s - \\varepsilon_t)} \n+ \\dfrac{1}{8} \\sum_{a,b,r,s,u,t} \\dfrac{\\Braket{ab|ur} \\Braket{ru|st} \\Braket{ts|ab}}{(\\varepsilon_a + \\varepsilon_b - \\varepsilon_u - \\varepsilon_r)(\\varepsilon_a + \\varepsilon_b - \\varepsilon_s - \\varepsilon_t)} \n\\notag\\\\\n&\\quad{} - \\dfrac{1}{8} \\sum_{a,b,r,s,u,t} \\dfrac{\\Braket{ab|ru} \\Braket{ru|ts} \\Braket{ts|ba}}{(\\varepsilon_a + \\varepsilon_b - \\varepsilon_u - \\varepsilon_r)(\\varepsilon_a + \\varepsilon_b - \\varepsilon_s - \\varepsilon_t)} \n+ \\dfrac{1}{8} \\sum_{a,b,r,s,u,t} + \\dfrac{\\Braket{ab|ur} \\Braket{ru|ts} \\Braket{ts|ba}}{(\\varepsilon_a + \\varepsilon_b - \\varepsilon_u - \\varepsilon_r)(\\varepsilon_a + \\varepsilon_b - \\varepsilon_s - \\varepsilon_t)} \\notag\\\\\n&\\quad{} + \\dfrac{1}{8} \\sum_{a,b,r,s,u,t} \\dfrac{\\Braket{ab|ru} \\Braket{ru|st} \\Braket{ts|ba}}{(\\varepsilon_a + \\varepsilon_b - \\varepsilon_u - \\varepsilon_r)(\\varepsilon_a + \\varepsilon_b - \\varepsilon_s - \\varepsilon_t)} \n- \\dfrac{1}{8} \\sum_{a,b,r,s,u,t} \\dfrac{\\Braket{ab|ur} \\Braket{ru|st} \\Braket{ts|ba}}{(\\varepsilon_a + \\varepsilon_b - \\varepsilon_u - \\varepsilon_r)(\\varepsilon_a + \\varepsilon_b - \\varepsilon_s - \\varepsilon_t)}  \\notag\\\\\n&= \\dfrac{1}{8} \\sum_{a,b,r,s,u,t} \\dfrac{\\Braket{ab|ru} \\Braket{ru|ts} \\Braket{ts|ab}}{(\\varepsilon_a + \\varepsilon_b - \\varepsilon_u - \\varepsilon_r)(\\varepsilon_a + \\varepsilon_b - \\varepsilon_s - \\varepsilon_t)} \n- \\dfrac{1}{8} \\sum_{a,b,r,s,u,t} \\dfrac{\\Braket{ab|ur} \\Braket{ru|ts} \\Braket{ts|ab}}{(\\varepsilon_a + \\varepsilon_b - \\varepsilon_u - \\varepsilon_r)(\\varepsilon_a + \\varepsilon_b - \\varepsilon_s - \\varepsilon_t)} \\notag\\\\\n&\\quad{} - \\dfrac{1}{8} \\sum_{a,b,r,s,u,t} \\dfrac{\\Braket{ab|ur} \\Braket{ur|st} \\Braket{ts|ab}}{(\\varepsilon_a + \\varepsilon_b - \\varepsilon_r - \\varepsilon_u)(\\varepsilon_a + \\varepsilon_b - \\varepsilon_s - \\varepsilon_t)} \n+ \\dfrac{1}{8} \\sum_{a,b,r,s,u,t} \\dfrac{\\Braket{ab|ru} \\Braket{ur|st} \\Braket{ts|ab}}{(\\varepsilon_a + \\varepsilon_b - \\varepsilon_r - \\varepsilon_u)(\\varepsilon_a + \\varepsilon_b - \\varepsilon_s - \\varepsilon_t)} \n\\notag\\\\\n&\\quad{} - \\dfrac{1}{8} \\sum_{a,b,r,s,u,t} \\dfrac{\\Braket{ab|ru} \\Braket{ru|ts} \\Braket{ts|ba}}{(\\varepsilon_a + \\varepsilon_b - \\varepsilon_u - \\varepsilon_r)(\\varepsilon_a + \\varepsilon_b - \\varepsilon_s - \\varepsilon_t)} \n+ \\dfrac{1}{8} \\sum_{a,b,r,s,u,t} + \\dfrac{\\Braket{ab|ur} \\Braket{ru|ts} \\Braket{ts|ba}}{(\\varepsilon_a + \\varepsilon_b - \\varepsilon_u - \\varepsilon_r)(\\varepsilon_a + \\varepsilon_b - \\varepsilon_s - \\varepsilon_t)} \\notag\\\\\n&\\quad{} + \\dfrac{1}{8} \\sum_{a,b,r,s,u,t} \\dfrac{\\Braket{ab|ur} \\Braket{ur|st} \\Braket{ts|ba}}{(\\varepsilon_a + \\varepsilon_b - \\varepsilon_r - \\varepsilon_u)(\\varepsilon_a + \\varepsilon_b - \\varepsilon_s - \\varepsilon_t)} \n- \\dfrac{1}{8} \\sum_{a,b,r,s,u,t} \\dfrac{\\Braket{ab|ru} \\Braket{ur|st} \\Braket{ts|ba}}{(\\varepsilon_a + \\varepsilon_b - \\varepsilon_r - \\varepsilon_u)(\\varepsilon_a + \\varepsilon_b - \\varepsilon_s - \\varepsilon_t)}  \\notag\\\\\n&= \\dfrac{1}{4} \\sum_{a,b,r,s,u,t} \\dfrac{\\Braket{ab|ru} \\Braket{ru|ts} \\Braket{ts|ab}}{(\\varepsilon_a + \\varepsilon_b - \\varepsilon_u - \\varepsilon_r)(\\varepsilon_a + \\varepsilon_b - \\varepsilon_s - \\varepsilon_t)} \n- \\dfrac{1}{4} \\sum_{a,b,r,s,u,t} \\dfrac{\\Braket{ab|ur} \\Braket{ru|ts} \\Braket{ts|ab}}{(\\varepsilon_a + \\varepsilon_b - \\varepsilon_u - \\varepsilon_r)(\\varepsilon_a + \\varepsilon_b - \\varepsilon_s - \\varepsilon_t)} \\notag\\\\\n&\\quad{} - \\dfrac{1}{4} \\sum_{a,b,r,s,u,t} \\dfrac{\\Braket{ab|ru} \\Braket{ru|ts} \\Braket{ts|ba}}{(\\varepsilon_a + \\varepsilon_b - \\varepsilon_u - \\varepsilon_r)(\\varepsilon_a + \\varepsilon_b - \\varepsilon_s - \\varepsilon_t)} \n+ \\dfrac{1}{4} \\sum_{a,b,r,s,u,t} + \\dfrac{\\Braket{ab|ur} \\Braket{ru|ts} \\Braket{ts|ba}}{(\\varepsilon_a + \\varepsilon_b - \\varepsilon_u - \\varepsilon_r)(\\varepsilon_a + \\varepsilon_b - \\varepsilon_s - \\varepsilon_t)} \\notag\\\\\n&= \\dfrac{1}{4} \\sum_{a,b,r,s,u,t} \\dfrac{\\Braket{ab|ru} \\Braket{ru|ts} \\Braket{ts|ab}}{(\\varepsilon_a + \\varepsilon_b - \\varepsilon_u - \\varepsilon_r)(\\varepsilon_a + \\varepsilon_b - \\varepsilon_s - \\varepsilon_t)} \n- \\dfrac{1}{4} \\sum_{a,b,r,s,u,t} \\dfrac{\\Braket{ab|ur} \\Braket{ru|ts} \\Braket{ts|ab}}{(\\varepsilon_a + \\varepsilon_b - \\varepsilon_u - \\varepsilon_r)(\\varepsilon_a + \\varepsilon_b - \\varepsilon_s - \\varepsilon_t)} \\notag\\\\\n&\\quad{} - \\dfrac{1}{4} \\sum_{a,b,r,s,u,t} \\dfrac{\\Braket{ba|ru} \\Braket{ru|ts} \\Braket{ts|ab}}{(\\varepsilon_a + \\varepsilon_b - \\varepsilon_u - \\varepsilon_r)(\\varepsilon_a + \\varepsilon_b - \\varepsilon_s - \\varepsilon_t)} \n+ \\dfrac{1}{4} \\sum_{a,b,r,s,u,t} + \\dfrac{\\Braket{ba|ur} \\Braket{ru|ts} \\Braket{ts|ab}}{(\\varepsilon_a + \\varepsilon_b - \\varepsilon_u - \\varepsilon_r)(\\varepsilon_a + \\varepsilon_b - \\varepsilon_s - \\varepsilon_t)} \\notag\\\\\n&= \\dfrac{1}{2} \\sum_{a,b,r,s,u,t} \\dfrac{\\Braket{ab|ru} \\Braket{ru|ts} \\Braket{ts|ab}}{(\\varepsilon_a + \\varepsilon_b - \\varepsilon_u - \\varepsilon_r)(\\varepsilon_a + \\varepsilon_b - \\varepsilon_s - \\varepsilon_t)} \n- \\dfrac{1}{2} \\sum_{a,b,r,s,u,t} \\dfrac{\\Braket{ab|ur} \\Braket{ru|ts} \\Braket{ts|ab}}{(\\varepsilon_a + \\varepsilon_b - \\varepsilon_u - \\varepsilon_r)(\\varepsilon_a + \\varepsilon_b - \\varepsilon_s - \\varepsilon_t)} \n\\end{align}\n=\n\\begin{minipage}{0.4\\linewidth}\n\t\\centering\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[large]\n\t\\vertex (a); \\vertex [below=2.4cm of a] (b);\n\t\\vertex [right=2.5cm of a] (c); \\vertex [right=2.5cm of b] (d);\n\t\\vertex at ($(a)!0.5!(b) + (0.7cm, 0)$) (e); \\vertex at ($(c)!0.5!(d) + (-0.7cm, 0)$) (f);\n\t\n\t\\diagram[%inline=(e.base)\n\t]{\n\t\t(a) -- [anti fermion,  quarter left, edge label=t] (e) \n\t\t-- [anti fermion,  quarter left, edge label=r] (b)\n\t\t-- [anti fermion, quarter left, edge label=a] (a),\n\t\t(c) -- [fermion, quarter left, edge label=b] (d)\n\t\t-- [fermion, quarter left, edge label=u] (f)\n\t\t-- [fermion, quarter left, edge label=s] (c),\n\t\t(a) -- [scalar] (c),\n\t\t(b) -- [scalar] (d),\n\t\t(e) -- [scalar] (f),\n\t\t%-- [fermion, quarter right, edge label'=2] (a),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n+\n\\begin{minipage}{0.4\\linewidth}\n\t\\centering\n\t\\begin{tikzpicture}\n\t\\begin{feynman}[large]\n\t\\vertex (a); \\vertex [below=2.4cm of a] (b);\n\t\\vertex [right=2.5cm of a] (c); \\vertex [right=2.5cm of b] (d);\n\t\\vertex at ($(a)!0.5!(b) + (0.7cm, 0)$) (e); \\vertex at ($(c)!0.5!(d) + (-0.7cm, 0)$) (f);\t\n\t\\diagram[]{\n\t\t(a) -- [fermion,  \\qr, \\el'=a] (b) -- [ fermion, \\el=u] (f)\n\t\t-- [ fermion,  \\el'=s] (c) -- [ fermion, \\ql, \\el=b] (d)\n\t\t-- [fermion,  \\el'=r] (e) -- [fermion, \\el=t] (a),\n\t\t(a) -- [scalar] (c), \t(b) -- [scalar] (d), (e) -- [scalar] (f),\n\t};\n\t\\end{feynman}\n\t\\end{tikzpicture}\n\\end{minipage}\n\n\\subsubsection{Summation of Diagrams}\n\n\\subsubsection{What Is the Linked-Cluster Theorem?}\n\\ex{6.13}\nFor the 3rd-order Goldstone diagrams in Table 6.2,\n\\begin{equation}\\label{key}\n\\text{diagram1} = (-1)^4 \\qty(\\dfrac{1}{2}) \\sum_{ab}\\sum_{rsut} \\dfrac{\\Braket{ab|ru}\\Braket{ru|ts}\\Braket{ts|ab} }{(\\varepsilon_a + \\varepsilon_b - \\varepsilon_r - \\varepsilon_u)(\\varepsilon_a + \\varepsilon_b - \\varepsilon_t - \\varepsilon_t)}\n\\end{equation}\n$ a,b,r,s,u,t $ must come from 1 or 2 molecules. If they come from 2 molecules, $ \\Braket{ru|ts} $ must be zero. Thus they only come from 1 molecule, i.e. the value of each Goldstone diagram is $ N $ times the result for a single molecule.\n\n\n\n\n\n\\subsection{Some Illustrative Calculations}\n\n\n\n\n\n\n\\end{document}", "meta": {"hexsha": "7e2b933345e6971d26459f0223867f852b12e4a6", "size": 59263, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chap6/chap6.tex", "max_stars_repo_name": "hebrewsnabla/S-O-MQC-HW", "max_stars_repo_head_hexsha": "58d79bd949d34e310e4ce8c287fe4b7ecda560da", "max_stars_repo_licenses": ["LPPL-1.3c"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2019-10-03T03:37:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T09:26:32.000Z", "max_issues_repo_path": "chap6/chap6.tex", "max_issues_repo_name": "hebrewsnabla/S-O-MQC-HW", "max_issues_repo_head_hexsha": "58d79bd949d34e310e4ce8c287fe4b7ecda560da", "max_issues_repo_licenses": ["LPPL-1.3c"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-04-30T15:45:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-26T13:00:28.000Z", "max_forks_repo_path": "chap6/chap6.tex", "max_forks_repo_name": "hebrewsnabla/S-O-MQC-HW", "max_forks_repo_head_hexsha": "58d79bd949d34e310e4ce8c287fe4b7ecda560da", "max_forks_repo_licenses": ["LPPL-1.3c"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-05-11T11:30:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T08:43:27.000Z", "avg_line_length": 40.7026098901, "max_line_length": 299, "alphanum_fraction": 0.5787422169, "num_tokens": 27824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.3291069151772477}}
{"text": "\\section*{Reduction}\n\nThe \n\\emph{program reducer} $\\Rrightarrow$ is a partial function from\nprograms to\nprograms\nand $\\Rrightarrow^*$ is its reflexive transitive closure.\nWithin the definition of $\\Rrightarrow$, we make use of\nthe following two groups of analogous partial functions:\nThe statement\n\\emph{reducer} $\\Rightarrow$ is a partial function from\nstatements to statements\nand $\\Rightarrow^*$ is its reflexive transitive closure.\nThe expression\n\\emph{reducer} $\\rightarrow$ is a partial function from\nexpressions to expressions\nand $\\rightarrow^*$ is its reflexive transitive closure.\n\nA \\emph{program reduction} is a sequence of programs\n$p_1 \\Rrightarrow \\cdots \\Rrightarrow p_n$,\nwhere $p_n$ is not reducible, i.e. there is no\nprogram $q$ such that $p_n \\Rightarrow q$.\nHere, the program $p_n$ is called the \\emph{result\nof reducing} $p_1$.\n\nA \\emph{value} is a primitive number expression,\nprimitive boolean expression,\na primitive string expression, a function definition\nexpression or a function declaration statement.\n\nThe \\emph{substitution} function \n$p [ n \\leftarrow v ]$ on programs/statements/expressions\nreplaces every free occurrence of the name $n$\nin statement $p$ by value $v$. Care must be taken to introduce\nand preserve\nco-references in this process; substitution can introduce\ncyclic references in the result of the substitution. For example,\n$n$ may occur free in $v$, in which case\nevery occurrence of $n$ in $p$\nwill be replaced by $v$ such that $n$ in $v$ refers cyclically\nto the node at which the replacement happens.\n\nIn summary:\n\n\\begin{enumerate}\n\\item $\\Rrightarrow$: \\emph{program reducer}\n\\item $\\Rrightarrow^*$: transitive closure of \\emph{program reducer}\n\\item $\\Rightarrow$: \\emph{statement reducer}\n\\item $\\Rightarrow^*$: transitive closure of \\emph{statement reducer}\n\\item $\\rightarrow$: \\emph{expression reducer}\n\\item $\\rightarrow^*$: transitive closure of \\emph{expression reducer}\n\\item $p [ n \\leftarrow v ]$: substitution function\n\\end{enumerate}\n\n\\subsection*{How to read inference rules}\n\nTo read the rules below, think of each \"fraction\" as an\n\"if we know X then we can infer Y\" implication statement.\nFor example,\n\n\\[\n\\frac{\n  X = 5\n}{\n  X + 1 = 5 + 1\n}\n\\]\n\ncorresponds to the statement\n\"If we know $X$ is equal to $5$,\nthen we can infer that $X + 1$ is equal to $5 + 1$\".\n\n\n\\subsection*{Programs}\n\n\n\\textbf{First-statement}: In a sequence of statements, we can always\nreduce the first one.\n\\[\n\\frac{\n  \\textit{statement}\\ \\Rightarrow\\ \\textit{statement}'\n}{  \n  \\textit{statement} \\ldots\n  \\Rrightarrow \n  \\textit{statement}' \\ldots\n}\n\\]\n\n\\vspace{10mm}\n\n\\textbf{Eliminate-function-declaration}: Function declarations as first\nstatements are substituted in the remaining statements.\n\\[\n\\frac{\n             f = \\textbf{\\texttt{function}}\\  \\textit{name} \\ \n                 \\textbf{\\texttt{(}}\\  \\textit{parameters}\n                 \\ \\textbf{\\texttt{)}}\\ \\textit{block}\n}{\nf\\ \\textit{statement} \\ldots\\ \n  \\Rrightarrow\\ \n  \\textit{statement} \\ldots[\\textit{name} \\leftarrow f]\n}\n\\]\n\n\\vspace{10mm}\n\\textbf{Eliminate-Values}: Values as first statemments are discarded, if\nthey are preceding one or more statements in a statement sequence.\n\\[\n\\frac{\nv \\ \\mbox{is a value}  \n}{\nv \\textbf{\\texttt{;}} \\textit{statement}+\\ \n   \\Rrightarrow  \\ \n  \\textit{statement}+\n}\n\\]\n\n\\subsection*{Statements: Expression statements}\n\n\\textbf{Expression-statement-reduce}: An expression statement\nis reducible if its expression is reducible.\n\\[\n\\frac{\n  e\\ \\rightarrow\\ e'\n}{  \n  e \\textbf{\\texttt{;}}\n  \\ \\Rightarrow \\ \n  e' \\textbf{\\texttt{;}}\n}\n\\]\n\n\n\\subsection*{Expressions: Binary operators}\n\n\\textbf{Left-binary-reduce}: An expression with binary operator\ncan be reduced if its left sub-expression can be reduced.\n\\[\n\\frac{\n  e_1 \\ \\rightarrow \\ e_1'\n}{\n  e_1\\  \\textit{binary-operator} \\ e_2\n  \\ \\rightarrow \\ \n  e_1'\\  \\textit{binary-operator} \\ e_2\n}\n\\]\n\n\n\\vspace{10mm}\n\\textbf{And-shortcut-false}: An expression with binary operator\n$\\textbf{\\texttt{\\&\\&}}$ whose left sub-expression is\n$\\textbf{\\texttt{false}}$ can be reduced to\n$\\textbf{\\texttt{false}}$.\n\\[\n\\frac{\n}{\n  \\textbf{\\texttt{false}}\\  \\textbf{\\texttt{\\&\\&}}\\ e\n  \\ \\rightarrow \\ \n  \\textbf{\\texttt{false}}\n}\n\\]\n\n\\vspace{10mm}\n\\textbf{And-shortcut-true}: An expression with binary operator\n$\\textbf{\\texttt{\\&\\&}}$ whose left sub-expression is\n$\\textbf{\\texttt{true}}$ can be reduced to\nthe right sub-expression.\n\\[\n\\frac{\n}{\n  \\textbf{\\texttt{true}}\\  \\textbf{\\texttt{\\&\\&}}\\ e\n  \\ \\rightarrow \\ \n  e\n}\n\\]\n\n\\vspace{10mm}\n\\textbf{Or-shortcut-true}: An expression with binary operator\n$\\textbf{\\texttt{||}}$ whose left sub-expression is\n$\\textbf{\\texttt{true}}$ can be reduced to\n$\\textbf{\\texttt{true}}$.\n\\[\n\\frac{\n}{\n  \\textbf{\\texttt{true}}\\  \\textbf{\\texttt{||}}\\ e\n  \\ \\rightarrow \\ \n  \\textbf{\\texttt{true}}\n}\n\\]\n\n\\vspace{10mm}\n\\textbf{Or-shortcut-false}: An expression with binary operator\n$\\textbf{\\texttt{||}}$ whose left sub-expression is\n$\\textbf{\\texttt{false}}$ can be reduced to\nthe right sub-expression.\n\\[\n\\frac{\n}{\n  \\textbf{\\texttt{false}}\\  \\textbf{\\texttt{||}}\\ e\n  \\ \\rightarrow \\ \n  e\n}\n\\]\n\n\\vspace{10mm}\n\\textbf{Right-binary-reduce}: An expression with binary operator\ncan be reduced if its left sub-expression is a value and its right\nsub-expression can be reduced.\n\\[\n\\frac{\n  e_2\\ \\rightarrow\\ e_2', \\textrm{and}\\ \\textit{binary-operator}\n  \\ \\mbox{is not}\\ \\textbf{\\texttt{\\&\\&}}\\ \\textrm{or}\\ \\texttt{\\textbf{||}}\n}{\n  v\\  \\textit{binary-operator} \\ e_2\n  \\ \\rightarrow \\ \n  v\\  \\textit{binary-operator} \\ e_2'\n}\n\\]\n\n\\vspace{10mm}\n\\textbf{Prim-binary-reduce}: An expression with binary operator\ncan be reduced if its left and right sub-expressions are values and\nthe corresponding function is defined for those values.\n\\[\n\\frac{\n  v\\ \\mbox{is result of}\\ v_1\\  \\textit{binary-operator} \\ v_2\n}{\n  v_1\\  \\textit{binary-operator} \\ v_2\n  \\ \\rightarrow \\ \n  v\n}\n\\]\n\n\\subsection*{Expressions: Unary operators}\n\n\\textbf{Unary-reduce}: An expression with unary operator\ncan be reduced if its sub-expression can be reduced.\n\\[\n\\frac{\n  e \\ \\rightarrow \\ e'\n}{\n  \\textit{unary-operator} \\ e\n  \\ \\rightarrow \\ \n  \\textit{unary-operator} \\ e'\n}\n\\]\n\n\\vspace{10mm}\n\\textbf{Prim-unary-reduce}: An expression with unary operator\ncan be reduced if its sub-expression is a value and\nthe corresponding function is defined for that value.\n\\[\n\\frac{\n  v'\\ \\mbox{is result of}\\ \\textit{unary-operator} \\ v\n}{\n  \\textit{unary-operator} \\ v\n  \\ \\rightarrow \\ \n  v'\n}\n\\]\n\n\\subsection*{Expressions: conditionals}\n\n\\textbf{Conditional-predicate-reduce}: A conditional\nexpression can be reduced, if its predicate can be reduced.\n\\[\n\\frac{\n  e_1 \\ \\rightarrow \\ e_1'\n}{\n  e_1\\  \\textbf{\\texttt{?}}\\ e_2\\ \\textbf{\\texttt{:}}\\ e_3\n  \\ \\rightarrow \\ \n  e_1'\\ \\textbf{\\texttt{?}}\\ e_2\\ \\textbf{\\texttt{:}}\\ e_3\n}\n\\]\n\n\\vspace{10mm}\n\\textbf{Conditional-true-reduce}: A conditional\nexpression whose predicate is the value\n$\\textbf{\\texttt{true}}$\ncan be reduced to its consequent expression.\n\\[\n\\frac{\n}{\n  \\textbf{\\texttt{true}}\\  \\textbf{\\texttt{?}}\\ e_1\\ \\textbf{\\texttt{:}}\\ e_2\n  \\ \\rightarrow \\ \n  e_1\n}\n\\]\n\n\\vspace{10mm}\n\\textbf{Conditional-false-reduce}: A conditional\nexpression whose predicate is the value\n$\\textbf{\\texttt{false}}$\ncan be reduced to its alternative expression.\n\\[\n\\frac{\n}{\n  \\textbf{\\texttt{false}}\\  \\textbf{\\texttt{?}}\\ e_1\\ \\textbf{\\texttt{:}}\\ e_2\n  \\ \\rightarrow \\ \n  e_2\n}\n\\]\n\n\n\\subsection*{Expressions: function application}\n\n\\textbf{Application-functor-reduce}: A function application\ncan be reduced if its functor expression can be reduced.\n\\[\n\\frac{\n  e \\ \\rightarrow \\ e'\n}{\n  e\\  \\textbf{\\texttt{(}}\\ \\textit{expressions} \\ \\textbf{\\texttt{)}}\n  \\ \\rightarrow \\ \n  e'\\  \\textbf{\\texttt{(}}\\ \\textit{expressions} \\ \\textbf{\\texttt{)}}\n}\n\\]\n\n\n\\vspace{10mm}\n\\textbf{Application-argument-reduce}: A function application\ncan be reduced if one of its argument expressions can be reduced and all\npreceding arguments are values.\n\\[\n\\frac{\n  e \\ \\rightarrow \\ e'\n}{\n  v\\  \\textbf{\\texttt{(}}\\ v_1 \\ldots v_i \\ e \\ldots\\ \\textbf{\\texttt{)}}\n  \\ \\rightarrow \\ \n  v\\  \\textbf{\\texttt{(}}\\ v_1 \\ldots v_i \\ e' \\ldots\\ \\textbf{\\texttt{)}}\n}\n\\]\n\n\n\n\\vspace{10mm}\n\\textbf{Function-declaration-application-reduce}:\nThe application of a function declaration\ncan be reduced, if all\narguments are values. \n\\[\n\\frac{\n  f = \\textbf{\\texttt{function}}\\  \\textit{n} \\ \n                 \\textbf{\\texttt{(}}\\  x_1 \\ldots x_n\n                 \\ \\textbf{\\texttt{)\\ \\{\\ return}}\\ \\textit{expression}\n                 \\ \\textbf{\\texttt{;\\ \\}}}\n}{\n  f\\ \\textbf{\\texttt{(}}\\ v_1 \\ldots v_n\\ \\textbf{\\texttt{)}}\n  \\ \\rightarrow \\ \n  \\textit{expression} [x_1 \\leftarrow v_1]\\ldots[x_n \\leftarrow v_n]\n  [n \\leftarrow f]\n}\n\\]\n\n\n    \\end{document}\n", "meta": {"hexsha": "dc07a9e66600081b3fc61cc522fcad68eaab2e1d", "size": 8755, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/specs/source_0_rules.tex", "max_stars_repo_name": "jaesimin/js-slang", "max_stars_repo_head_hexsha": "153596c436998e4aa182a61be455febf77eb5510", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 48, "max_stars_repo_stars_event_min_datetime": "2018-07-09T06:16:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T09:40:24.000Z", "max_issues_repo_path": "docs/specs/source_0_rules.tex", "max_issues_repo_name": "jaesimin/js-slang", "max_issues_repo_head_hexsha": "153596c436998e4aa182a61be455febf77eb5510", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1117, "max_issues_repo_issues_event_min_datetime": "2018-07-09T08:08:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T14:47:08.000Z", "max_forks_repo_path": "docs/specs/source_0_rules.tex", "max_forks_repo_name": "jaesimin/js-slang", "max_forks_repo_head_hexsha": "153596c436998e4aa182a61be455febf77eb5510", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 80, "max_forks_repo_forks_event_min_datetime": "2018-08-24T08:55:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T08:56:48.000Z", "avg_line_length": 24.5926966292, "max_line_length": 78, "alphanum_fraction": 0.6861222159, "num_tokens": 2770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.3291069151772477}}
{"text": "%!TEX root = ../gronskiy_phd_thesis.tex\r\n\\chapter[Minimum Spanning Tree Algorithms: Regularization by Stopping]{Minimum Spanning Tree\r\n  Algorithms: \\\\ Regularization by Stopping}\r\n\\label{ch:mst}\r\n\r\n\\hfill\r\n\\begin{minipage}[t]{.75\\textwidth}\r\n\\textit{``Besser ein Spatz in der Hand, als eine Taube auf dem Dach.'' \\\\\r\n  (germ. ``A bird in the hand is worth two in the bush.'')} \\\\\r\n  \\hrule\r\n  \\vspace{.2cm}\r\n  \\hfill\r\n  \\textsc{--- Proverbs}\r\n\\end{minipage}\r\n\r\n\\section{Introduction}\r\n\r\n\\subsection{Motivation and Examples} \r\n\r\n\\index{Minimum Spanning Tree}\r\n\\index{MST|see{Minimum Spanning Tree}}\r\nNoise perturbed combinatorial optimization problems arise in various real-world\r\napplications where problem instances are abstracted by weighted\\footnote{We will\r\nfurther utilize both the terms ``costs'' and ``weights'' in the same meaning.}\r\ngraphs with fluctuations in the weights. In this chapter, we\r\ninvestigate the noisy Minimum Spanning Tree (MST) problems and their ability to\r\ninfer robust spanning trees. Examples of real-world applications of minimum\r\nspanning trees come from various fields of human activity, such as\r\n\\emph{communication networks with delays} (optimizing message delivery times,\r\ncf.~\\citep{Bertsekas:1987}) or \\emph{stock markets} (analyzing stock exchange\r\ncorrelations, cf.~\\citep{Sandoval:2012}), etc. All the applications require\r\ntrees with a high level of robustness to fluctuations since the quality of trees\r\nis measured by expected costs. Wide real-world demand and applicability\r\nstimulated extensive research on the robust minimum spanning trees\r\nproblem~\\citep{Aron:2004, Kozina:1994, Sandoval:2012, Yaman:Karasan:Pinar:2001},\r\nwhich addressed different aspects of the robust spanning tree setting, such as\r\ndevelopment of algorithms, measuring algorithmic complexity, or comparing\r\nrobustness criteria.\r\n\r\nIn this chapter, we use an information-theoretic regularization approach\r\nintroduced in Chapter~\\ref{ch:gen_appch} to analyse and validate MST algorithms\r\nfrom the point of view of how well they can recognize (localize) the true\r\nMinimum Spanning Tree under unknown noise in the graph instance. The validation\r\nconcept is developed for ``contractive'' algorithms that follow a step-by-step\r\nstrategy of shrinking the solution space until a single best solution is\r\nidentified.  This validation approach is based on the \\emph{two-instance\r\nscenario} \\citep{Vapnik:1982} that requires statistical estimates to generalize\r\nto test instances when the estimates have been inferred from a training\r\ninstance. For spanning trees, that means that they have to yield low costs on at\r\nleast two problem instances without being explicitly adapted to the test\r\ninstance.%%% JB: the reference to the IB method is obscure. We should\r\n%%% reformulate it. \r\nSuch regularization remains in the spirit of the \\emph{information bottleneck\r\nmethod}~\\citep{Tishby:1999} in the sense that it tries to optimize the amount of\r\ninformation that the algorithm might transfer from an artificial channel (see\r\nbelow, Section~\\ref{sec:ASReg}).\r\n\\index{Infromation bottleneck method}\r\n\r\n%Suppose we need to construct a delivery\r\n%network with minimal travel time along a given transportation system,\r\n%where travel times along each road section fluctuate due to random\r\n%transport delays caused by possibly unforeseeable events. Another \r\n%real-world application arises from stock financial markets,\r\n%which exhibit strong correlations that can be\r\n%modeled by a temporally evolving dependency graph. A minimalistic\r\n%description of these correlations with a simple conditional\r\n%independence structure requires to find a minimum spanning tree in\r\n%such a noise contaminated graph (see~\\citep{Sandoval:2012}). Both\r\n%applications \r\n\r\n\\subsection{Contributions and Outline of the Chapter}\r\n\\label{sec:mst_contribs}\r\nAs main contributions of this chapter, we\r\n\\begin{itemize}\r\n  \\item define a notion of contractive algorithm and give an general\r\n  extension of the ASC regularization approach (introduced earlier in\r\n  Chapter~\\ref{ch:gen_appch}) for the case of stepwise contractive algorithmic\r\n  problems. We call it Algorithmic ASC;\r\n  \\item provide a specialization of such extension to the case of three major\r\n  algorithms solving the Minimum Spanning Tree (MST) problem, including the\r\n  necessary tools to avoid brute-force enumeration known as a computational\r\n  bottleneck of ASC;\r\n  \\item carry out experiments which justify usage of Algorithmic ASC score as\r\n  a ranking tool related to expected localization error: higher Algorithmic ASC\r\n  score yields lower error.\r\n\\end{itemize}\r\n\r\nThe chapter is outlined as follows. First, a related work overview is given in\r\nSection~\\ref{sec:mst_related_work}. Then, in Section~\\ref{sec:mst_related_work}\r\nwe revisit those ingredients of ASC approach relevant for this chapter. A\r\ncomprehensive introduction into the original approximation set-based approach is\r\nthen given in Section~\\ref{sec:asc_original}. Later, the main contribution is\r\nmade in Section~\\ref{sec:mst_algorithmic_gen}, where we make a generalization of\r\nthe ASC to algorithmic problems, and Section~\\ref{sec:applying_asc_to_mst} where\r\nwe directly apply it to Minimum Spanning Tree (MST) problem and three most\r\nimportant algorithms solving it. Experimental results follow in\r\nSection~\\ref{sec:mst_results}. Finally, we discuss our findings in\r\nSection~\\ref{sec:mst_conclusion}.\r\n\r\n\\section{Related Work Overview} \r\n\\label{sec:mst_related_work}\r\n\r\nLiterature entries on robust spanning trees vary by research purpose\r\n(e.g.~algorithm complexity, robustness), adopted noise model\r\n(e.g.~interval data), regularization strategy (regularizing by\r\npruning, graph preprocessing).  For example,\r\n\\citep{Yaman:Karasan:Pinar:2001} investigated graphs with edge weights\r\nwhich are supposed to fall uniformly into a predefined interval. The\r\napproach is based on regularization \\emph{by preprocessing the graph},\r\nwhich, in turn, involves eliminating selected edges and forcing other\r\nedges to be included into the spanning tree.\r\n\r\n\\index{Pruning (tree)}\r\nRegularizing an MST by \\emph{pruning} as proposed\r\nby~\\citep{Sandoval:2012} identifies the presumably robust part of a\r\nspanning tree. This goal is achieved by means of analyzing the\r\nsurvival matrix constructed from adjacency matrices for training\r\nminimum spanning trees.\r\n\r\nOur approach is similar in that pruning (more precisely, optimal\r\nstopping) is used as a regularization tool, but it rather aims at\r\n\\emph{analysis and comparison} of the algorithm's robustness by means\r\nof such regularization. This approach also exhibits technical\r\ndifferences from the mentioned work, relying only on \\emph{two} data\r\ninstances, and it follows the spirit of learning theory with its goal\r\nto analyse algorithms in a noise distribution independent way.\r\n\r\nIn Section~\\ref{regularization_gen}, the general concepts of the\r\ninformation-theoretic framework are given, as well as the\r\ninformation-theoretic motivation. Then, in\r\nSection~\\ref{sec:mst_algorithmic_gen}, the application to stepwise algorithms\r\nis discussed. The results and conclusion are summarized in\r\nSections~\\ref{sec:mst_results} and~\\ref{sec:mst_conclusion}, respectively.\r\n\r\n\\section{Approximation Set Coding Regularization}\r\n\\label{regularization_gen}\r\n\r\nTo make this chapter self-consistent, we first give a short overview of the approach\r\nfirst introduced in Chapter~\\ref{ch:gen_appch}, as well as of the\r\nnotation and terms used throughout this chapter.\r\n\\index{Regularization}\r\n\r\n\\subsection{Notation and Definitions}\r\n\r\nAssume, there is a data instance $X$ given, for example\r\nmeasurements in a data space $\\mathcal{X}$, so that $X \\in\r\n\\mathcal{X}$. In case of the MST problem, $\\mathcal{X}$ is the set of\r\nall possible combinations of the edge costs and $X$ is a particular realization\r\nof such costs. Let $c$ denote a solution in a general set of solutions $\\C$, so\r\nthat $c \\in \\C$. In case of the MST, $\\C$ is the set of feasible spanning trees.\r\n\r\nAn optimization problem is defined by a cost (objective) function $R:\r\n\\C\\times\\mathcal{X}\\rightarrow \\mathbb{R}_{+}$ that assigns\r\neach solution $c$ a real value $R(c,X)$. Furthermore,\r\n$c^{\\bot}(X) \\in \\arg\\min_{c \\in \\C} R(c, X)$\r\ndenotes\\footnote{In the context where it is clear what $X$ is, we\r\nwill omit the ``$(X)$'' in the notation: $c^\\bot(X) \\equiv\r\nc^\\bot$; $R(c,X) \\equiv R(c)$; $\\C_\\gamma(X) \\equiv\r\n\\C_\\gamma$.} the minimum cost solution.\r\n\r\nFor the sake of referring to it in the rest of the chapter, we give here a\r\ndefinition from Chapter~\\ref{ch:gen_appch}:\r\n\\begin{definition}\r\n\\label{def:mst_ch_approximation_set}\r\nFor a given real number $\\gamma \\ge 0$, an approximation set is defined as follows:\r\n\\begin{equation}\r\n  \\mathcal{C}_\\gamma (X, R) \\coloneqq \r\n  \\{c \\in \\mathcal{C} \\mid R(c, X) - R^\\bot(X) \\le \\gamma\\},\r\n\\end{equation}\r\n\\end{definition}\r\n\r\nIn fact, it is desirable to find a \\emph{robust set} of solutions\r\nrather than a single solution, since we cannot trust the global\r\nminimizer $c^\\bot$ to achieve low costs on test instance due to noise\r\nin the measurements. In this light, the sets $\\C_\\gamma(X)$ play\r\nthe role of a ``trade-off agent'' in the process of finding the robust\r\nsolution to optimization problem. This trade-off is \r\n%%% meant to be the one \r\nbalancing the solution sets between overfitting ($\\gamma = 0$) and underfitting (large\r\n$\\gamma$).\r\n\\index{Global minimizer}\r\n\\index{Overfitting}\r\n\\index{Underfitting}\r\n\r\n%%%%%%%%%%%%%%%%% JB corrections up to here %%%%%%%%%%%%%%%%%\r\n\r\n\\subsection{Robust Solving via ASC Regularization}\r\n\\label{subsec:asc_regularization_crit}\r\nRegularization by the Approximation Sets applies to a situation, when two data\r\ninstances $X', X'' \\in \\mathcal{X}$ are available and when both are generated by\r\ninjecting two noise realizations into the true data instance $X^0 \\in\r\n\\mathcal{X}$ (see Section~\\ref{sec:data_generation_model}). It is required for\r\nboth cases that the noise follows the same noise distribution: $X', X'' \\sim\r\nPG(X^0)$. In the spirit of statistical learning theory, we are interested in\r\ndistribution independent results since the distribution $PG(X^0)$ might be\r\nunknown.\r\n\r\nA robust solution to the noisy optimization problem $(\\mathcal{X}, \\C, R)$ is\r\nobtained by the two-step process described in\r\nAlgorithm~\\ref{alg:robust_solving_via_similarity}.\r\n\r\n\\begin{algorithm}[hb!]\r\n\\caption{Robust Solving via ASC Regularization}\r\n\\label{alg:robust_solving_via_similarity}\r\n  \\KwData{\\\\\r\n  \\quad two instances of the $X', X''$, \\\\ \\\\ \r\n  \\quad cost function $R(c, X)$}\r\n\r\n  \\KwResult{Solution $c \\in \\C$.}\r\n\r\n  {\r\n    Find the optimal regularization parameter $\\gamma^*$ that\r\n    maximizes the log-ratio \r\n    % involving \\emph{the first two data instances}:\r\n    \\begin{equation}\\label{eq:mst_asc_ratio}\r\n      \\hat I_\\gamma(X', X'') \\coloneqq \\log \r\n      \\Bigl(\r\n        \\frac{|\\C| \\; |{\\C}_{\\gamma}(X') \\cap {\\C}_{\\gamma}(X'')|}%\r\n          {|\\mathcal{C}_\\gamma(X')| \\; |\\mathcal{C}_\\gamma(X'')|}\r\n      \\Bigr),\r\n    \\end{equation}\r\n  }\r\n\r\n  {Choose a solution uniformly at random from the intersection of\r\n        optimal approximation sets: $c \\in C_{\\gamma^*}(X') \\cap\r\n        C_{\\gamma^*}(X'')$.}\r\n\\end{algorithm}\r\n\r\n\\myremark Note the difference of~\\eqref{eq:mst_asc_ratio} with previously\r\ndefined~\\eqref{eq:asc_mutual_information_formula}: dropping the \r\nexpectation. This is perfectly legitimate in case when we have no access to the\r\nproblem generation distribution and have to replace the actual value by its\r\nestimator.\r\n\r\n\\subsection{Information-Theoretic Basis for ASC Regularization}\r\n\\label{sec:ASReg}\r\n\r\nApplying of ASC bases itself on the information-theoretic ground which uses\r\napproximation sets $\\C_{\\gamma}(X)$ in a fictitious communication scenario.\r\nThis communication scenario involves sending and receiving a\r\n\\emph{transformation} $\\tau\\colon\r\n\\mathcal{X} \\to \\mathcal{X}$ that maps the data space onto\r\nitself. We briefly recap the necessary information here: for a full\r\nintroduction, refer to Chapter~\\ref{ch:gen_appch}\r\n(Section~\\ref{sec:communication_learning_stability}).\r\n\r\nCommunicating a true $\\tau_{\\mathrm{send}}$ is performed by sending ${\\tau_{\\mathrm{send}} \\circ\r\nX'}$ to the receiver, while the channel perturbs this ``message''\r\nby substituting $X'$ with $X''$. Finally, the receiver obtains\r\n$\\tau_{\\mathrm{send}} \\circ X''$. The reader should note that $X'$ is known to\r\nboth sender and receiver.\r\n\\index{Sender}\r\n\\index{Receiver}\r\n\\index{Approximation Set Coding!Encoding and transmission}\r\n\\index{Approximation Set Coding!Decoding}\r\n\r\nAs the receiver \r\n%%% JB: receives\r\naccepts $\\tau_{\\mathrm{send}} \\circ X''$, it has has to distinguish the\r\nfluctuations in $X''$ relative to $X'$ from the applied\r\ntransformation $\\tau_{\\mathrm{send}}$. Error free communication is guaranteed if the\r\nreceiver can identify the correct transformation $\\tau_{\\mathrm{send}}$ without\r\nbeing deceived by these fluctuations.  The straightforward decoding\r\nrule consists in finding the ``nearby'' transformation $\\hat \\tau$,\r\nwhich maximizes the overlap between the received approximation set\r\n$\\C_\\gamma(\\tau_{\\mathrm{send}} \\circ X'')$ and the ``nearby'' approximation set\r\n$\\C_\\gamma(\\hat\\tau \\circ X')$.\r\n\r\nThe role of the codebook vectors is played by all such transformations\r\nwhich enable us to cover the complete solution space $\\C$\r\nwith approximation sets $\\C_\\gamma(\\tau \\circ X')$. Obviously,\r\n$\\gamma$ controls the number of such codebook vectors since for large\r\n$\\gamma$ we can only select few such sets to cover $\\C$;\r\notherwise we risk decoding errors. The concept is analogous to\r\nclassical coding theory where every codebook vector defines the\r\n``center'' of an ``error-correcting'' sphere, and the elements of this\r\nsphere are \\emph{indistinguishable} from the data transmission point\r\nof view.\r\n\\index{Indistinguishable solutions|see{Solutions}}\r\n\\index{Solutions!Indistinguishable}\r\n\r\nAs derived in Section~\\ref{sec:communication_learning_stability}, an\r\nasymptotically vanishing error probability is achievable for coding rates\r\nbounded by\r\n%%\r\n\\begin{align}\r\n  I_\\gamma(X', X'') &= \\Expct \\hat I_\\gamma(X', X'') \\notag \\\\ \r\n  &=\r\n  \\Expct \\log\\left( \\frac{|\\C| \\, |{\\C}_{\\gamma}(X') \\cap\r\n      {\\C}_{\\gamma}(X'')|}{|{\\C}_{\\gamma}(X')|\r\n      \\, |{\\C}_{\\gamma}(X'')|}\\right), \\label{eq:mst_ch_mutual_inf}\r\n\\end{align}\r\nThe estimator $\\hat I_\\gamma(X', X'')$ in (\\ref{eq:mst_ch_mutual_inf}) measures\r\nthe total information content of a message.\r\n\r\nFor a fixed $\\gamma$, a large overlap means that the evaluation of the first\r\ndataset generalizes to the second dataset, whereas a small or empty intersection\r\nindicates lack of generalization. The fraction of approximation set\r\ncardinalities in (\\ref{eq:mst_ch_mutual_inf}) measures stability of the solutions under\r\nnoise fluctuations.\r\n\r\nThe value $\\Expct \\hat I_{\\gamma}(X', X'')$ is an estimate for the \\emph{mutual\r\ninformation} and, in analogy to information theory\r\n(cf.~\\citep[Ch.~7]{Cover:2006}), the \\emph{approximation capacity} is defined as\r\n$C \\coloneqq\\max_{\\gamma}\\Expct [\\hat I_{\\gamma}(X', X'')]$ (cf.\r\nDefinition~\\ref{def:asc_score}). The expectation $\\Expct$ is taken with respect\r\nto the random variables $X', X''$. If the distribution $PG(X^0)$ is unknown then\r\nwe have to derive learning theoretic large deviation bounds based on the\r\nempirical quantity $\\hat I_{\\gamma}(X', X'')$ and appropriate complexity\r\npenalties.\r\n\r\nIn summary, maximizing the ratio~\\eqref{eq:mst_asc_ratio} allows us to select the\r\noptimal resolution for the solution set, and elements of this approximation set\r\nare considered indistinguishable given the present noise process.\r\n\r\n\\section{ASC Regularization for Stepwise Algorithms}\r\n\\label{sec:mst_algorithmic_gen}\r\n\r\n\\subsection{Application to Stepwise Algorithms: Main Idea}\r\n\r\nDirect application of ASC regularization requires\r\noptimizing~\\eqref{eq:mst_asc_ratio} w.r.t.~$\\gamma$, which, in turn, amounts\r\nto compute the cardinalities \r\n\\begin{equation}\r\n  |{\\C}_{\\gamma}(X') \\cap {\\C}_{\\gamma}(X'')|, \r\n  \\quad |{\\C}_{\\gamma}(X')|, \r\n  \\quad |{\\C}_{\\gamma}(X'')|\r\n\\end{equation}\r\n(cf. Definition~\\ref{def:mst_ch_approximation_set}).  In general, computation or\r\nat least estimation of these cardinalities requires to enumerate the elements of\r\n$\\C$ and to test if they belong to $\\C_\\gamma$. Such enumeration is\r\ncomputationally hard, since $\\C$ grows sometimes very fast (exponentially in\r\ncases of some combinatorial problems).\\footnote{This difficulty emerges as a\r\ncommon bottleneck in many problem settings. We elaborated on it in\r\nSection~\\ref{sec:gen_appch_conclusion} of the previous chapter.}\r\n\r\nFor algorithms, these enumeration problems arise in a constraint form, i.e.,\r\n\\emph{the algorithm itself} might help to optimize this enumeration, eliminating\r\nall those solutions that get ``out of consideration'' as the algorithm\r\nprogresses. In other words, some algorithms feature a step-by-step nature, and\r\nthey shrink the set of feasible solutions at each next step, ending up with the\r\noptimal solution at the last step. Figure~\\ref{fig:mst_contractive_algorithm}\r\nillustrates this intuition. This contraction is very similar to the shrinkage of\r\napproximation sets, as they shrink to the optimal solution as $\\gamma$\r\ndecreases. The feasible sets induced by the algorithm often turn out to be\r\nefficiently computable~-- and we will exploit this property of contractive\r\nalgorithms. \r\n\r\n\\subsection{Contractive Algorithms and Their Approximation Sets}\r\n\\index{Contractive algorithm}We define the algorithmic approximation set at computational step $t$ as the set\r\nof solutions that are still considered as potential answers to be returned by\r\nthe algorithm $\\algo$. This generalized notion of an approximation set for\r\nalgorithm $\\algo$ measures the statistical behavior of a specific algorithm\r\nduring its execution. \r\n\\nomenclature[E, 05a]{$\\algo$}{algorithm\\nomnorefeq}%\r\n\r\n\\myremark Even if $\\algo$ calculates the global minimum of the cost\r\nfunction, the algorithm may not follow a gradient flow on that costs to\r\ndetermine the global minimum.\r\n\r\n\\begin{figure}[ht!]\r\n  \\centering\r\n  \\includegraphics[width=\\textwidth]{figures/ch_mst/contractive_alg}\r\n  \\\\[.5cm]\r\n  \\caption{Illustration of a contractive algorithmic flow: the set of\r\n    feasible (i.e. still possible) solutions contracts from step to step,\r\n    shrinking to $c^\\bot$ at the end of execution.}\r\n  \\label{fig:mst_contractive_algorithm}\r\n\\end{figure}\r\n\r\n\\begin{definition}\r\n\\label{def:contractive_algorithm}\r\n  Assume that for a given data instance $X$ the stepwise execution of the\r\n  algorithm $\\algo$ evaluated on this instance can be expressed as a sequence of\r\n  subsets of feasible solutions\r\n  %%\r\n  \\begin{align}\r\n    \\algo(X) &= \\langle A_0(X), \\ldots, A_T(X)\r\n    \\rangle,\r\n    \\quad\\text{where} \\notag \\\\\r\n  %%\r\n    A_t(X) &\\subseteq \\C, \\quad t = 0, \\ldots, T, \\qquad\\quad\r\n    \\text{and} \\notag\\\\\r\n  %%\r\n    A_0(X) &= \\C \\notag \\\\ \r\n    A_T(X) &= \\{c^\\bot\\}.\r\n  \\end{align}\r\n  \\nomenclature[E, 05b]{$A_i(X)$}{algorithmic feasible set\\mynomdef{def:contractive_algorithm}}%\r\n  \\nomenclature[E, 05b]{$T$}{total number of steps\\nomnorefeq}%\r\n  %%\r\n  We call $\\algo$ contractive, if $A_{t+1} \\subseteq\r\n  A_{t}$.  \r\n\\end{definition}\r\n\r\n\\begin{definition}\\label{def:algorithmic_approximation_set}\r\n  For a contractive algorithm it is natural to define an algorithmic\r\n  $t$-approximation set as follows: $\\C^\\algo_t(X) \\coloneqq A_t(X)$.\r\n  \\nomenclature[E, 05d]{$\\C^\\algo_t(X)$}{algorithmic $t$-approximation set\\mynomdef{def:algorithmic_approximation_set}}%\r\n  \\index{Algorithmic!Approximation set}\r\n  \\index{Approximation set!Algorithmic|see{Algorithmic}}\r\n\\end{definition}\r\n\r\nAn example of such algorithm, as well as comprehensive illustration, will be\r\ngiven in Section~\\ref{sec:applying_asc_to_mst} and\r\nFigure~\\ref{fig:ch_mst_illustration}.\r\n\r\nSpeaking informally, the algorithmic $t$-approximation set is an approximation\r\nset as defined in Definition~\\ref{def:mst_ch_approximation_set}, but taken\r\nw.r.t. the flow of a particular algorithm at update step $t$. The role of the\r\n$\\gamma$ parameter is now (in contrast to\r\nDefinition~\\ref{def:mst_ch_approximation_set}) played by a discrete step\r\nvariable $t$ spanning from $0$ to $T$ (note that, generally, $T$ is not a\r\nconstant). All the other notions remain the same when adopting the new\r\ndefinition of the approximation sets $A_t(X)$. For example, the following\r\ndefines the algorithmic ASC score:\r\n\r\n\\begin{definition}\r\nAs an analogy to~\\eqref{eq:mst_ch_mutual_inf}, we will call the quantity\r\n%%\r\n\\begin{align}\\label{eq:alg_eq:mst_asc_ratio}\r\n  I_t^\\algo = \\Expct \\hat I_t^{\\algo}( X', X'' ) \r\n    &\\coloneqq \\Expct \\log\\biggl( \\frac{|\\C| \\, |{\\C}^\\algo_{t}(X') \\cap\r\n      {\\C}^\\algo_{t}(X'')|}{|{\\C}^\\algo_{t}(X')|\r\n      \\, |{\\C}^\\algo_{t}(X'')|}\\biggr) \\notag \\\\\r\n    &\\equiv \\Expct \\log \\biggl(\\frac{\r\n      |\\C|\\; |A_t(X') \\cap A_t(X'')|\r\n    }{\r\n      |A_t(X')|\\; |A_t(X'')|\r\n    }\\biggr), \r\n\\end{align}\r\n\\nomenclature[E, 05g]{$I_t^\\algo$}{algorithmic ASC $t$-score}%\r\n\\nomenclature[E, 05ga]{$\\hat I_t^\\algo$}{empirical algorithmic ASC $t$-score}%\r\nwhere $A_t(\\cdot)$ are defined above, an algorithmic ASC $t$-score.\r\n\\index{Algorithmic!ASC score}\r\n\\index{Approximation Set Coding!Algorithmic|see{Algorithmic}}\r\n\\end{definition}\r\nAs in Chapter~\\ref{ch:gen_appch}, we will distinguish between \r\nexpected and empirical values.\r\n\r\n\\subsection{Algorithmic ASC Score and Optimal Stopping}\r\n\\begin{figure}[hb!]\r\n  \\centering\r\n  \\includegraphics[width=\\textwidth]{figures/ch_mst/contractive_alg_opt_stop}\r\n  \\\\[.5cm]\r\n  \\caption{The main question addressed in this chapter: which of the steps to\r\n    choose for the optimal stopping.}\r\n  \\label{fig:mst_contractive_algorithm_opt_stop}\r\n\\end{figure}\r\nAs an empirical extension of the notions introduced in\r\nChapter~\\ref{ch:gen_appch}, we claim that the algorithmic channel capacity\r\n\\begin{equation}\r\n  C^\\algo \\coloneqq \\max_{t = [0, \\ldots, T]} I^\\algo_{t} \r\n    = \\max_{t = [0, \\ldots, T]}\\Expct [\\hat I^\\algo_{t}(X', X'')],\r\n\\end{equation} \r\n\\nomenclature[E, 05gb]{$C^\\algo$}{algorithmic approximation capacity}%\r\nalso referred as~\\emph{algorithmic approximation capacity} or \\emph{information\r\ncontent}, equals the maximum amount of information which could be transferred\r\nthrough a fictitious channel described in Section~\\ref{sec:ASReg} (and, in more\r\ndetail, earlier in Section~\\ref{sec:communication_learning_stability}), and\r\nconstrained to the specific algorithm (i.e., algorithmic approximation sets are\r\nallowed). From the learning perspective, the algorithmic approximation capacity\r\nshows how well the algorithm can filter out the noise (by $t$-optimization),\r\nremaining robust to underfitting.\r\n\\index{Algorithmic!Approximation capacity}\r\n\\index{Optimal stopping}\r\n\r\nIn a full analogy with the approach of Chapter~\\ref{ch:gen_appch}\r\n(cf.\\eqref{eq:asc_best_gamma}), one can find the optimal stopping time $t^*$ by\r\nmaximizing the algorithmic ASC $t$-score:\r\n\\begin{equation}\\label{eq:mst_asc_best_step}\r\n  t^* \\in \\arg \\max_{t = [0, \\ldots, T]} \\hat \\Expct I^\\algo_t(X', X'').\r\n\\end{equation}\r\n\\nomenclature[E, 05g]{$t^*$}{optimal stopping time}%\r\nWe are going to use this approach as an optimal stopping criterion for the \r\nrest of the chapter (see Figure~\\ref{fig:mst_contractive_algorithm_opt_stop}).\r\n\r\n\\myremark We will call this approach \\textit{algorithmic ASC} opposed to the\r\noriginal ASC approach developed in Chapter~\\ref{ch:gen_appch}.\r\n\\index{Algorithmic!Approximation Set Coding}\r\n\r\n\\section{ASC Regularization for MST Algorithms}\r\n\\label{sec:applying_asc_to_mst}\r\n\r\n\\subsection{Major MST Algorithms}\r\nIn the rest of the chapter, we will consider the Minimum Spanning Tree (MST)\r\nproblem. Its formulation is as follows: given a weighted undirected graph $G =\r\n(V, E)$, find a spanning tree of the minimum possible weight. \\textit{Spanning\r\ntree} is defined as a connected subgraph of $G$ without cycles, whose vertex set\r\nequals $V$.\r\n\\index{Tree!Spanning}\r\n\\index{Spanning tree|see{Tree}}\r\n\r\nThere are several classical solutions to this problem, of which we will focus on\r\n\\textit{Prim's}, \\textit{Kruskal's} and \\textit{reverse-delete} algorithms. We\r\nbring their definitions in a pseudo-code in\r\nAlgorithms~\\ref{alg:prim_alg_pseudocode},~\\ref{alg:kruskal_alg_pseudocode}\r\nand~\\ref{alg:rd_alg_pseudocode} and explain a verbal intuition behind them below.\r\n\\index{MST Algorithm!Prim's}\r\n\\index{MST Algorithm!Kruskal's}\r\n\\index{MST Algorithm!Reverse-delete}\r\n\\index{Prim's|see{MST Algorithm}}\r\n\\index{Kruskal's|see{MST Algorithm}}\r\n\\index{Reverse-delete|see{MST Algorithm}}\r\n\r\n\r\n\\begin{algorithm}[ht!]\r\n\\caption{Prim's Algorithm for finding MST}\\label{alg:prim_alg_pseudocode}\r\n\\KwIn{undirected graph $G(V, E)$ with non-negative weights}\r\n\\KwOut{spanning tree with minimum total weight}\r\n{initialize current tree $B = (V_B, E_B)$ by choosing first vertex: \r\n  $B \\leftarrow (\\{v^*\\}, \\emptyset)$\\;}\r\n\r\n\\While{$V_B \\ne V$ (not all vertices are in tree)}{\r\n  {find the minimal edge $e_\\mathrm{min} = (v, v_\\mathrm{min})$ \r\n    from $B$ to the rest $G \\setminus B$\\;} \r\n  {add $e_\\mathrm{min}$ to the tree $B$\\;} }\r\n\r\n\\KwRet{current tree $B$}\r\n\\end{algorithm}\r\n\r\n\\begin{algorithm}[ht!]\r\n\\caption{Kruskal's Algorithm for finding MST}\\label{alg:kruskal_alg_pseudocode}\r\n\\KwIn{undirected graph $G(V, E)$ with non-negative weights}\r\n\\KwOut{spanning tree with minimum total weight}\r\n{initialize current tree $B = (V_B, E_B)$: $B \\leftarrow (\\emptyset, \\emptyset)$ \\;}\r\n\r\n\\While{$V_T \\ne V$ (not all vertices are in tree)}{\r\n  {find the minimal edge $e_\\mathrm{min}$ such that: \\\\\r\n    \\quad a) $e_\\mathrm{min} \\not \\in E_B$ and \\\\ \r\n    \\quad b) $B \\cup e_\\mathrm{min}$ has no cycles\\;} \r\n  {add $e_\\mathrm{min}$ to the tree $B$\\;} \r\n}\r\n\r\n\\KwRet{current tree $B$}\r\n\\nomenclature[E, 10a]{$G(V, E)$}{graph\\nomnorefeq}%\r\n\\end{algorithm}\r\n\r\n\\begin{algorithm}[ht!]\r\n\\caption{Reverse-Delete Algorithm for finding MST}\\label{alg:rd_alg_pseudocode}\r\n\\KwIn{undirected graph $G(V, E)$ with non-negative weights}\r\n\\KwOut{spanning tree with minimum total weight}\r\n{initialize current graph $B = (V_B, E_B)$ with the input graph: $B \\leftarrow G$\r\n\\;}\r\n\r\n\\While{$B$ is connected and yet not a tree}{\r\n  {find the maximal edge $e_\\mathrm{max}$ in $B$ such that: \\\\\r\n    \\quad deleting $e_\\mathrm{max} $ does not disconnect $B$\\;} \r\n  \\If{no such edge found}{break\\;}\r\n  \\Else{remove $e_\\mathrm{max}$ from $B$\\;} \r\n}\r\n\r\n\\KwRet{current tree $B$}\r\n\\end{algorithm}\r\n\r\n\\begin{figure}[th!]\r\n  \\centering\r\n  \\begin{subfigure}[b]{.48\\textwidth}\r\n      \\includegraphics[width=\\linewidth]{figures/ch_mst/mst_illustration_0}\r\n      \\caption{Step 2: candidate edges set is large, no restricted edges yet}\r\n      \\label{fig:ch_mst_illustration-0}\r\n  \\end{subfigure}\r\n  \\hfill\r\n  \\begin{subfigure}[b]{.48\\textwidth}\r\n      \\includegraphics[width=\\linewidth]{figures/ch_mst/mst_illustration_1}\r\n      \\caption{Step 3: candidate edges set is large gets smaller, restricted edges appear}\r\n      \\label{fig:ch_mst_illustration-1}\r\n  \\end{subfigure}\r\n  \\\\[.5cm]\r\n  \\begin{subfigure}[b]{.48\\textwidth}\r\n      \\includegraphics[width=\\linewidth]{figures/ch_mst/mst_illustration_2}\r\n      \\caption{Step 4: candidate edges set is large gets even smaller, restricted edges build up}\r\n      \\label{fig:ch_mst_illustration-2}\r\n  \\end{subfigure}\r\n  \\hfill\r\n  \\begin{subfigure}[b]{.48\\textwidth}\r\n      \\includegraphics[width=\\linewidth]{figures/ch_mst/mst_illustration_3}\r\n      \\caption{Step 5: almost everything is restricted}\r\n      \\label{fig:ch_mst_illustration-3}\r\n  \\end{subfigure}\r\n  \\\\[.5cm]\r\n  \\caption{Prim's MST Algorithm: freedom reduces as information\r\n    grows. Edge weights are not shown (figure from the introduction recreated\r\n    here for convenience).}\r\n  \\label{fig:ch_mst_illustration}\r\n\\end{figure}\r\n\r\n\\emph{Prim's algorithm} (``growing tree'' strategy) starts with a tree $B=(V_B,\r\nE_B)$ on an empty set of edges $E_P$ and a starting vertex $v^{*}$. The\r\nalgorithm enlarges $E_B$, adding one edge $e_t$ at step $t$ (the first step\r\nadds an edge incident to $v^{*}$), so that $B$ remains to be a tree, until $B$\r\nbecomes a spanning tree of $G$. It takes $T = n-1$ steps.\r\n\r\n\\emph{Kruskal's algorithm} (``connecting trees in a forest'' strategy) of\r\nfinding MSTs starts with an empty set of edges $E_B$. The algorithm adds\r\na minimal possible $e_t$ at the step $t$, not allowing cycles in $E_B$,\r\nbut yet not requiring $B$ to be connected at all times, until $B$ becomes a spanning tree\r\nof $G$. It takes $T = n-1$ steps.\r\n\r\n\\emph{Reverse-Delete} (``reducing graph'' strategy) algorithm starts\r\nwith a graph on the full set of edges $B = G$ and shrinks it, removing one maximal edge\r\n$e_t$ per step and keeping the graph\r\n$B$ connected, until $B$ becomes a spanning tree. \r\nFor a complete graph, it takes $T = n(n-1)/2 - n + 1$ steps.\r\n\r\n\\myremark All the three algorithms can be easily proven to reach the global\r\nminimizer solution $c^\\bot(X) \\in \\arg \\min_c R(c, X)$.\r\n\r\n\\subsection{Counting Approximation Sets for MST}\r\n\r\n\\paragraph{MST algorithms are contractive} From the description of three\r\nalgorithms in the previous section one can see, that they all comply with the\r\nDefinition~\\ref{def:contractive_algorithm} of a contractive algorithm, due to\r\nthe following line of reasoning. Since each of them yields a set (yet\r\n\\textit{not} an approximation set) of \\textit{candidate edges} which still are\r\nable to make it into the final tree:\r\n\\begin{itemize}\r\n  \\item in case of Prim's and Kruskal's: candidates are edges which are\r\n    either already included or still can be included into $B$;\r\n  \\item in case of Reverse-Delete: candidates are edges which still remain (i.e.\r\n    are no yet removed) in $B$.\r\n\\end{itemize}\r\nTo complete the reasoning, one should notice that an algorithmic approximation\r\nset is exactly the set of spanning trees built on such candidate edges.\r\n\r\nThis concept is illustrated in Figure~\\ref{fig:ch_mst_illustration}, where\r\nseveral steps ($2$ to $5$) of the Prim's algorithm are shown. One can easily see\r\nthat as the algorithm flows, some edges are excluded from consideration (due to\r\nno-cycle condition; shown in red) and hence less and less spanning trees remain\r\npossible.\r\n\r\n\\paragraph{Computing cardinalities for MST} How can we calculate the\r\ncardinalities of algorithmic approximation sets involved in the evaluation of\r\nterm~\\eqref{eq:alg_eq:mst_asc_ratio}? Counting number of spanning trees for a\r\ncomplete graph can be performed analytically via Cayley's\r\nformula~\\citep{Aigner2010}:\r\n\\newtheorem*{cayley_thm}{Theorem (Cayley's Formula for Spanning Trees)}\r\n\\begin{cayley_thm}\r\n  The total number of labeled trees on $n$ vertices is equal to $n^{n-2}$.\r\n  \\index{Labeled tree|see{Tree}}\r\n  \\index{Tree!Labeled}\r\n\\end{cayley_thm}\r\n\r\n\\index{Cayley's formula}\r\nHowever, Cayley's formula works only for complete graphs, while in our case, one\r\nhas to deal with a general case of counting trees on a non-complete subgraph\r\n(candidate edges). In this work, we utilize the Matrix-Tree\r\nTheorem~\\citep[cf.][]{Harris:2008}. For a connected graph $G = (V,E)$, it\r\ninvolves computing the adjacency matrix $M^G_{\\mathrm{adj}}$, the degree matrix\r\n\\begin{equation}\r\n  M^G_{\\mathrm{deg}} = \\mathop{\\mathrm{diag}}(\\deg{v_1}, \\ldots,\r\n\\deg{v_n}),\r\n\\end{equation} \r\nand uses a notion of a cofactor:\r\n\\index{Degree matrix}\r\n\\index{Adjacency matrix}\r\n\\nomenclature[E, 07a]{$M^G_{\\mathrm{adj}}$}{adjacency matrix}%\r\n\\nomenclature[E, 07b]{$M^G_{\\mathrm{deg}}$}{degree matrix}%\r\n\\nomenclature[E, 07f]{$\\mathrm{deg}(v)$}{degree of vertex}%\r\n\r\n\\begin{definition}\r\n  Given an $n \\times n$ matrix M, the $i,j$ cofactor of $M$ is defined to be\r\n  $(-1)^{i+j} \\mathrm{det}(M_{i, j})$, where $M_{i, j}$\r\n  is the submatrix of $M$, where $i$-th row and $j$-th column are removed.\r\n  \\nomenclature[A, 00j]{$\\mathrm{det}(\\cdot)$}{determinant}%\r\n  \\index{Cofactor}\r\n  \\index{Matrix cofactor!see{Cofactor}}\r\n\\end{definition}\r\n\r\n\\newtheorem*{matrix_tree_thm}{Theorem (Kirchhoff's Matrix-Tree Theorem)}\r\n\\begin{matrix_tree_thm}\r\n  The total number of labeled trees on a graph $G = (V,E)$ with adjacency matrix\r\n  $M^G_{\\mathrm{adj}}$, degree matrix $M^G_{\\mathrm{deg}}$ is equal to (any) cofactor\r\n  of the matrix $L = M^G_{\\mathrm{deg}}- M^G_{\\mathrm{adj}}$.\r\n  \\index{Kirchhoff's matrix-tree theorem}\r\n\\end{matrix_tree_thm}\r\n\r\n%%The algorithm of finding the stepwise algorithmic\r\n%%rate~\\eqref{eq:mst_ch_mutual_inf} is thus the one described as\r\n%%Algorithm~\\ref{alg_mutual_inf}.\r\n%%\\begin{algorithm}\r\n%%\\caption{\\textsc AlgApproxSetRatio}\r\n%%\\label{alg_mutual_inf}\r\n%%\\begin{algorithmic}\r\n%%  \\STATE $I\\gets [\\;]$ \\COMMENT{the ratio~\\eqref{eq:alg_eq:mst_asc_ratio} array}\r\n%%  \\STATE $P_1, P_2 \\gets [\\;]$ \\COMMENT{candidate edges left at the\r\n%%    current step (both for $X', X''$)} \\FORALL{t = 1 \\ldots\r\n%%    T} \\STATE $P_1 \\gets P_1\\setminus\\{e_t(X')\\}$ \\STATE $P_2\r\n%%  \\gets P_2\\setminus\\{e_t(X'')\\}$ \\STATE\\COMMENT{Now compute the\r\n%%    cardinalities of aqpproximation sets} \\STATE $N_1\\gets$\r\n%%  ComputeMatrixTreeCount($P_1$) \\STATE $N_2\\gets$\r\n%%  ComputeMatrixTreeCount($P_2$) \\STATE $N_{12}\\gets$\r\n%%  ComputeMatrixTreeCount($P_1 \\cap P_2$) \\STATE $I[t]\\gets$\r\n%%  ComputeRatio($N_1$, $N_2$, $N_{12}$)\r\n%%\\ENDFOR\r\n%%\\end{algorithmic}\r\n%%\\end{algorithm}\r\n\r\nIn our cases, applying the Matrix-Tree theorem to count cardinalities of algorithmic\r\napproximation sets  ${\\C}^\\algo_{t}(X')$ and\r\n${\\C}^\\algo_{t}(X'')$ is straightforward. Computing an intersection of two\r\nalgorithmic approximation sets ${\\C}^\\algo_{t}(X') \\cap\r\n{\\C}^\\algo_{t}(X'')$ is simple as well.\r\n\r\nAs the last step, it we find the optimal stopping step $t^* \\in\r\n\\arg\\max_t\r\n\\hat I^{\\algo}_t( X', X'' )$ which maximizes the\r\nratio. The optimal stopping time $t^*$ then defines a\r\npruning operation on the solution space to make $\\algo$ robust.\r\n\r\n\\subsection{Uniform Sampling an Optimally Stopped Spanning Tree}\r\n\r\nOnce the optimal stopping time $t^*$ is defined, we can sample from \r\nand intersection of two optimally-stopped algorithmic approximation sets \r\n${\\C}^\\algo_{t}(X') \\cap {\\C}^\\algo_{t}(X'')$ using the Pr\\\"ufer encoding of\r\nlabeled trees. This purely algorithmic task, however, goes beyond the scope \r\nof this work and we thus leave it out.\r\n\\index{Pr\\\"ufer codes}\r\n\r\n\\section{Experimental Results} \r\n\\label{sec:mst_results}\r\nWe will experimentally check that algorithmic approximation capacity is a consistent\r\nmeasure of the information that can be extracted by an algorithm from\r\nnoisy data by means of optimal stopping.\r\n\r\n\\begin{figure}[!t]\r\n\\centering\r\n\\includegraphics[width=.9\\textwidth]{figures/ch_mst/gaus_inf_log}\r\n\\caption{Gaussian noise model: information content}\r\n\\label{fig:gaus_inf}\r\n\\end{figure}\r\n\r\n\\subsection{Experiment Setting: Gaussian Noise Model}\r\nTo investigate the general information-theoretic behavior of MST\r\nalgorithms in practice, we generate weighted complete graphs in a\r\nhierarchical way. First, we generate a ``ground truth'' graph with\r\n$n = 50$ vertices and with edges that are attributed by Gaussian weights,\r\nsampled i.i.d. from a Gaussian distribution $\\mathcal{N}(\\mu_0 = 100,\r\n\\sigma_0^2 = 100)$.\r\nSecond, perturbed versions of this ground truth graph are then obtained by\r\nadding Gaussian noise $\\mathcal{N}(\\mu = 0, \\sigma^2)$ to the edge\r\nweights for a given noise range $\\sigma \\in [0,  8\\sigma_0]$.\r\n\r\nIn the experiment with approximation set-regularized algorithms we repeated the\r\nexperiment $400$ times to ensure the statistical significance of the\r\nresults. For some plots a semi-logarithmic scale was used for a better\r\nvisualization of small differences. Confidence intervals were also constructed\r\nand plotted.\r\n\r\n\\subsection{Algorithmic Approximation Capacity Ranking of Algorithms}\r\n\\index{Ranking}\r\nWe plot the algorithmic information content $\\max_t \\Expct \\hat\r\nI_t^{\\algo}(X', X'') $~(cf.~\\eqref{eq:alg_eq:mst_asc_ratio}) for three algorithms (Figure~\\ref{fig:gaus_inf}).\r\n%%% JB: no new paragraph\r\nAt low noise levels (particularly $\\sigma = 0$) all the three\r\nalgorithms exhibit the same information content, which is equal to\r\n$\\log_2{n^{n-2}} = 48 \\log_2{50} \\approx 270,9$ bits of information:\r\nat zero noise, all the three algorithms choose the true MST out of\r\n$|\\C|$ possible spanning trees. For a complete graph,\r\nCayley's tree formula calculates the number of possible solutions as\r\n$|\\C| = n^{n-2}$.\r\n%%% JB: In a noise-free setting, extracting the right tree corresponds\r\n%%% to $\\log_2{n^{n-2}} = 48 \\log_2{50} \\approx 270,9$ bits of\r\n%%% information.    \r\n\r\nThe plot in Figure~\\ref{fig:gaus_inf} provides a clear ranking of the three algorithms\r\nw.r.t. their information content dependent on the noise level. A qualitative explanation \r\nwhich accounts for such ranking and \r\nclarifies the idea behind evaluating information content, is the\r\nfollowing:\r\n%\r\n%\\begin{figure}[!t]\r\n%\\centering\r\n%\\includegraphics[scale=0.3]{figures/ch_mst/gaus_inf_step_log}\r\n%\\caption{Gaussian noise model: information content per step}\r\n%\\label{fig:gaus_inf_step_log}\r\n%\\end{figure}\r\n\r\n\\emph{Prim's algorithm} considers for addition only the edges which\r\nare already connected to the tree built so far.  Among the not yet\r\nconsidered edges there might be low cost edges which are more\r\nefficient to be added in the beginning of the run rather than in the\r\nend, thus making the information extraction inefficient from the point\r\nof view of the algorithm dynamics.\r\n\r\n\\emph{Kruskal's algorithm} explores all the possible edges as\r\ncandidates for addition at each step, thus being less inclined to add\r\ninefficient edges first and using the algorithm dynamics in a\r\nefficient way. This gain is reflected by its increased informativeness\r\nrelative to Prim's algorithm.\r\n\r\n\\emph{Reverse-Delete algorithm} is more informative than Kruskal's,\r\nsince it efficiently discards all those edges which should not be\r\nincluded in any approximate spanning tree. It pursues a strategy of\r\ndelayed decision making, that proved to be favourable also in other\r\nsituations of decision making under uncertainty.\r\n\r\n\\begin{figure}[!t]\r\n\\centering\r\n\\includegraphics[width=0.9\\textwidth]{figures/ch_mst/gaus_loc_err_mod}\r\n\\caption{Gaussian noise model: localization error}\r\n\\label{fig:gaus_loc_err}\r\n\\end{figure}\r\n\r\nThe above insights are proven by the plot showing the stepwise\r\ndynamics of logarithm of the cardinalities $|\\C^\\algo_t(X')|$, $|\\C^\\algo_t(X'')|$\r\n(Figure~\\ref{fig:gaus_as_card}). It visualizes the\r\nfact, that as $t$ progresses, Prim's algorithm contracts for the\r\nsolution faster than Kruskal's, and both contract faster that the\r\nReverse-Delete one, which, in turn, forces earlier stopping and thus\r\nleads to the worse performance. In fact, we can formulate an informal statement:\r\n\\begin{statement}\r\n  Assume that at the step $t$ the algorithm exhibits the edge set $B$ defined\r\n  above in Section~\\ref{sec:applying_asc_to_mst}. Then the reduction of the\r\n  amount of feasible spanning trees with edges in $B$ obtained by adding\r\n  $e_{t+1}$ which is adjacent to $B$  (Prim) is higher than the reduction\r\n  obtained by adding non-adjacent $e_{t+1}$ (Kruskal in general), and both are\r\n  higher than the reduction obtained by deleting $e_{t+1}$ from $B$\r\n  (Reverse-Delete).\r\n\\end{statement}\r\n\r\n\\index{Stepwise dynamics}\r\nThe plot in the Figure~\\ref{fig:gaus_ratio_dyn} explains the discussed ranking\r\nfrom the stepwise dynamics prospective. The algorithm, which reaches maximum of\r\nmutual information earlier, is less informative in overall, and vice versa. This\r\nbehavior reflects a natural trade-off between early decision and informativeness of the\r\nsolution.\r\n\r\n\\subsection{Localization Error Ranking of Algorithms}\r\n\r\n\\index{Ranking}\r\nThe three given algorithms ``explore'' the solution set with different\r\ndynamic behavior, extracting different amount of the information\r\nabout the true solution. This behavior is related to the localization error.\r\n\r\nFor the algorithmically ASC-regularized\r\n(Section~\\ref{subsec:asc_regularization_crit}) solution $\\hat c$\r\nwe plot (Figure~\\ref{fig:gaus_loc_err}) the localization error, which is\r\ncomputed as $E(\\hat c) = 1 - |c^* \\cap \\hat c| / |c^*|$, where straight brackets\r\ndenote the cardinality of edges.\r\n\r\n\\begin{figure}[!t]\r\n\\centering\r\n\\includegraphics[width=.9\\textwidth]{figures/ch_mst/gaus_as_card}\r\n\\caption{Gaussian noise model: stepwise approximation set log-cardinalities ($\\sigma = 48$)}\r\n\\label{fig:gaus_as_card}\r\n\\end{figure}\r\n\r\n\\index{Localization error}\r\nIt can be seen from the figures, that the ranking of the three\r\nalgorithms according to their localization capability is in connection\r\nwith the information content ranking~--- the more informative\r\nalgorithm yields less error in localizing the true solution.\r\n\r\n\\begin{figure}[!t]\r\n\\centering\r\n\\includegraphics[width=.9\\textwidth]{figures/ch_mst/gaus_ratio_dyn}\r\n\\caption{Gaussian noise model: stepwise algorithmic information defined in~\\eqref{eq:alg_eq:mst_asc_ratio} ($\\sigma = 48$)}\r\n\\label{fig:gaus_ratio_dyn}\r\n\\end{figure}\r\n%\r\n%\\begin{figure}[!t]\r\n%\\centering\r\n%\\includegraphics[scale=0.3]{figures/ch_mst/gaus_as_intersection_card}\r\n%\\caption{Gaussian noise model: stepwise approximation set intersection log-cardinalities ($\\sigma = 48$)}\r\n%\\label{fig:gaus_as_intersect_card}\r\n%\\end{figure}\r\n\r\n\\subsection{Algorithmic ASC vs. Original ASC}\r\n\\label{sec:aasc_vs_asc}\r\n\r\nAs the last experiment, we showed that the original ASC regularization (the one\r\nvia $\\gamma$-parameter) works still better than algorithmic ASC and even beats\r\nthe Joint Minimizer (first introduced as a benchmark solution in\r\nChapter~\\ref{ch:gen_appch}), which minimizes the average cost $R(c, X')+R(c, X'')$.\r\n\\index{Joint cost minimizer}\r\n\r\nDue to the computation limitations of the original ASC~--- it yields enumerating\r\nthe whole set of spanning trees ($n^{n-2}$) for each step $t$ --- we could only\r\nrun the experiments for graphs with few vertices ($n = 6$).\r\nFigure~\\ref{fig:aasc_vs_original} shows that the original ASC remains\r\ncompetitive with the Joint Minimizer solution, while algorithmic version shows\r\nweak performance. This is not surprising and comes at a certain cost for which\r\nwe discuss in conclusion.\r\n\r\n\\begin{figure}[!t]\r\n\\centering\r\n\\includegraphics[width=.9\\textwidth]{figures/ch_mst/gen_6_all}\r\n\\caption{Error plotted on the solutions obtained via original ASC\r\n  (Chapter~\\ref{ch:gen_appch} and algorithmic ASC (this chapter), as well as benchmarked on\r\n  Joint Minimizer (Section~\\ref{sec:aasc_vs_asc}).}\r\n\\label{fig:aasc_vs_original}\r\n\\end{figure}\r\n\r\n\\section{Discussion and Conclusion}\r\n\\label{sec:mst_conclusion}\r\n\r\n\\subsubsection{On the ASC-induced ranking of the algorithms}\r\nThe framework of approximation set coding is generalized from\r\nthe domain of models to the domain of algorithms in the\r\nchapter. This framework enables us to apply an information-theoretic\r\nregularization and quality assessment principle to algorithms,\r\nand, in particular, to a minimum spanning tree problem with noisy\r\ngraphs as input.\r\n\r\nWe interpreted the results of the quantitative analysis of the\r\nalgorithms in a qualitative way, binding the strategy of the algorithm\r\nto its information content, showing consistency and agreement with the\r\nlocalization capability of the algorithm.\r\n\r\nThe ranking of the quantities plotted in\r\n% Figure~\\ref{fig:gaus_inf},~\\ref{fig:gaus_loc_err},~\r\n% \\ref{fig:gaus_as_card},~ \\ref{fig:gaus_ratio_dyn}\r\nFigure~\\ref{fig:gaus_inf}--\\ref{fig:gaus_ratio_dyn}\r\nsupport the following conjecture.\r\n\\begin{conj}\r\n  The information content of contractive algorithms applied to the\r\n  same problem establishes a ranking among them. This ranking is\r\n  consistent with the average localization error of these algorithms.\r\n\\end{conj}\r\n\r\nA possible way of investigating this relation is a rigorous analysis of the\r\napproximation set dynamics using the mentioned Matrix-Tree theorem.\r\nAlthough we utilized the simplest model of Gaussian noise,\r\nindependent on separate edges, there exists evidence, which\r\nallows us to expect the same consistent results for a \\emph{structured}\r\nnoise setting, when the edges of the graph are impacted by the noise\r\nin a complex way, involving the statistical dependence of the noise\r\ningredients and other degrees of the noise model complexity.\r\n\r\n\\subsubsection{Algorithmic ASC vs. original ASC}\r\n\r\nShould one use algorithmic approximation approach of this chapter or the\r\noriginal $\\gamma$-approximation approach form Chapter~\\ref{ch:gen_appch}? In\r\nthis section, we address a question on whether the optimal stopping rule derived\r\nby algorithmic ASC can compete with the original ASC (we initiated this discussion\r\nin Section~\\ref{sec:aasc_vs_asc}).\r\n\r\nIn fact, these two approaches serve quite different purposes and feature\r\ndifferent highlights. The original $\\gamma$-parametrized ASC regularization\r\nworks in conjunction with the optimization goal $R(c, X)$, while its algorithmic\r\nversion makes use of algorithm-specific \\textit{flow}. Although the algorithm\r\nfinds the same global optimizer as a bare $R(c, X)$-minimization procedure, the\r\nstructure of approximation sets if very different. Below, we list the main\r\npoints of difference:\r\n\\begin{itemize}\r\n\\item The original ASC relates to the continuous parameter, while algorithmic ASC\r\nworks with a discrete steps. This yields different power of resolution at which \r\nwe coarse-grain the solution set $\\C$. For original ASC, this resolution power \r\nis higher (it can allow much smaller step between approximation set sizes), while \r\nfor algorithmic ASC it fully depends on the algorithm.\r\n\r\n\\item Original ASC is hard to apply computationally, since it boils down to \r\ncomputing and enumerating approximation sets. For algorithmic ASC, it is easier\r\nto derive a problem-specific procedure which makes it \\textit{orders of\r\nmagnitude} faster. For example, in the MST case, we utilized the Matrix-Tree\r\ntheorem and computed the cardinalities analytically at each step!\r\n\\end{itemize}\r\n\r\nHence, the trade-off between the power of resolution and the computational \r\npower exists and should be addressed in each special case.\r\n\r\n\\subsubsection{General notes on the ASC approach to algorithms}\r\n\r\nFrom the statistical physics perspective, a contractive algorithm can be\r\nconsidered as a process, where the temperature decreases step by step, and thus\r\n``freezes'' the solution space, until finding the optimal solution. The\r\nsurvey~\\citep[Sec.~3.2]{Merhav:2010} discusses the connection between such a\r\ncoding framework and statistical physics. This connection \\citep{JB:ISIT:2010}\r\ninspires us to explore the dynamics of the algorithm from a generalization point\r\nof view and to relate it to the information theory~\\citep{Merhav:2010}.\r\n\r\nWe will consider the statistical physics viewpoint on the ASC regularization in the next\r\nchapter.", "meta": {"hexsha": "4f0b5d91f86a9114c3f9d0589439a04c2f676435", "size": 46907, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/ch_mst/ch_mst.tex", "max_stars_repo_name": "agronskiy/phd-thesis", "max_stars_repo_head_hexsha": "182fcc5c09c8aa20df54cf536eb87766bfb6c353", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thesis/ch_mst/ch_mst.tex", "max_issues_repo_name": "agronskiy/phd-thesis", "max_issues_repo_head_hexsha": "182fcc5c09c8aa20df54cf536eb87766bfb6c353", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis/ch_mst/ch_mst.tex", "max_forks_repo_name": "agronskiy/phd-thesis", "max_forks_repo_head_hexsha": "182fcc5c09c8aa20df54cf536eb87766bfb6c353", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.2086330935, "max_line_length": 124, "alphanum_fraction": 0.7449421195, "num_tokens": 12478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.32908726503052177}}
{"text": "%\n%  This file is included by Registration.tex\n%\n%\n%\n\n\\index{itk::Image\\-To\\-Image\\-Metric}\n\nIn OTB, \\doxygen{itk}{ImageToImageMetric} objects quantitatively measure how well\nthe transformed moving image fits the fixed image by comparing the gray-scale\nintensity of the images. These metrics are very flexible and can work with any\ntransform or interpolation method and do not require reduction of the\ngray-scale images to sparse extracted information such as edges.\n\nThe metric component is perhaps the most critical element of the registration\nframework. The selection of which metric to use is highly dependent on the\nregistration problem to be solved. For example, some metrics have a large\ncapture range while others require initialization close to the optimal\nposition.  In addition, some metrics are only suitable for comparing images \nobtained from the same type of sensor, while others can handle \nmulti-sensor comparisons.\nUnfortunately, there are no clear-cut rules as to how to choose a metric.\n\n\\index{itk::Image\\-To\\-Image\\-Metric!GetValue()}\n\\index{itk::Image\\-To\\-Image\\-Metric!GetDerivatives()}\n\\index{itk::Image\\-To\\-Image\\-Metric!GetValueAndDerivatives()}\n\nThe basic inputs to a metric are: the fixed and moving images, a transform and\nan interpolator. The method \\code{GetValue()} can be used to evaluate the\nquantitative criterion at the transform parameters specified in the argument.\nTypically, the metric samples points within a defined region of the fixed\nimage.  For each point, the corresponding moving image position is computed\nusing the transform with the specified parameters, then the interpolator is\nused to compute the moving image intensity at the mapped position. %% Details on\n%% this mapping are illustrated in Figures \\ref{fig:ImageOverlapIterator} and\n%% \\ref{fig:ImageOverlapInterpolator}. \n\nThe metrics also support region based evaluation. The \\code{SetFixedImageMask()} and \n\\code{SetMovingImageMask()} methods may be used to restrict evaluation of the metric \nwithin a specified region. The masks may be of any type derived from \\doxygen{itk}{SpatialObject}.\n\nBesides the measure value, gradient-based optimization schemes also require\nderivatives of the measure with respect to each transform parameter. The\nmethods \\code{GetDerivatives()} and \\code{GetValueAndDerivatives()} can be\nused to obtain the gradient information.\n\n\nThe following is the list of metrics currently available in OTB:\n\\begin{itemize}\n\\item Mean squares\\\\ \\doxygen{itk}{MeanSquaresImageToImageMetric}\n\\item Normalized correlation \\\\ \\doxygen{itk}{NormalizedCorrelationImageToImageMetric}\n\\item Mean reciprocal squared difference \\\\ \\doxygen{itk}{MeanReciprocalSquareDifferenceImageToImageMetric} \n\\item Mutual information by Viola and Wells \\\\ \\doxygen{itk}{MutualInformationImageToImageMetric}\n\\item Mutual information by Mattes \\\\ \\doxygen{itk}{MattesMutualInformationImageToImageMetric}\n\\item Kullback Liebler distance metric by Kullback and Liebler \\\\ \\doxygen{itk}{KullbackLeiblerCompareHistogramImageToImageMetric}\n\\item Normalized mutual information \\\\ \\doxygen{itk}{NormalizedMutualInformationHistogramImageToImageMetric}\n\\item Mean squares histogram \\\\ \\doxygen{itk}{MeanSquaresHistogramImageToImageMetric}\n\\item Correlation coefficient histogram \\\\ \\doxygen{itk}{CorrelationCoefficientHistogramImageToImageMetric}\n\\item Cardinality Match metric \\\\ \\doxygen{itk}{MatchCardinalityImageToImageMetric}\n\\item Kappa Statistics metric\\\\ \\doxygen{itk}{KappaStatisticImageToImageMetric}\n\\item Gradient Difference metric \\\\ \\doxygen{itk}{GradientDifferenceImageToImageMetric}\n\\end{itemize}\n\nIn the following sections, we describe each metric type in detail. \nFor ease of notation, we will refer to the fixed image $f(\\bf{X})$ \nand transformed moving image $(m \\circ T(\\bf{X}))$ as images $A$ and $B$.\n\n\\subsection{Mean Squares Metric}\n\\label{sec:MeanSquaresMetric}\n\\index{itk::Mean\\-Squares\\-Image\\-To\\-Image\\-Metric}\n\nThe \\doxygen{itk}{MeanSquaresImageToImageMetric} computes the mean squared\npixel-wise difference in intensity between image $A$ and $B$ over a user\ndefined region:\n\n\\begin{equation}\nMS(A,B) = \\frac{1}{N} \\sum_{i=1}^N \\left( A_i - B_i \\right)^2\n\\end{equation}\n\\begin{center}\n$A_i$ is the i-th pixel of Image A\\\\ \n$B_i$ is the i-th pixel of Image B\\\\\n$N$ is the number of pixels considered\n\\end{center}\n\nThe optimal value of the metric is zero. Poor matches between images $A$ and\n$B$ result in large values of the metric. This metric is simple to compute and\nhas a relatively large capture radius.\n\nThis metric relies on the assumption that intensity representing the same\nhomologous point must be the same in both images. Hence, its use is restricted\nto images of the same modality. Additionally, any linear changes in the\nintensity result in a poor match value.\n\n\\subsubsection{Exploring a Metric}\n\\label{sec:ExploringAMetric}\n\nGetting familiar with the characteristics of the Metric as a cost function is\nfundamental in order to find the best way of setting up an optimization process\nthat will use this metric for solving a registration problem.\n\n%% The following\n%% example illustrates a typical mechanism for studying the characteristics of a\n%% Metric. Although the example is using the Mean Squares metric, the same\n%% methodology can be applied to any of the other metrics available in the\n%% toolkit.\n\n%% \\ifitkFullVersion\n%% \\input{MeanSquaresImageMetric1.tex}\n%% \\fi\n\n\n\\subsection{Normalized Correlation Metric}\n\\label{sec:NormalizedCorrelationMetric}\n\\index{itk::Normalized\\-Correlation\\-Image\\-To\\-Image\\-Metric}\n\nThe \\doxygen{itk}{NormalizedCorrelationImageToImageMetric} computes pixel-wise\ncross-correlation and normalizes it by the square root of the autocorrelation\nof the images:\n\n\\begin{equation}\nNC(A,B) = -1 \\times \\frac{ \\sum_{i=1}^N \\left( A_i \\cdot B_i \\right) }\n        { \\sqrt { \\sum_{i=1}^N A_i^2  \\cdot \\sum_{i=1}^N B_i^2 } }\n\\end{equation}\n\\begin{center}\n$A_i$ is the i-th pixel of Image A\\\\ \n$B_i$ is the i-th pixel of Image B\\\\\n$N$ is the number of pixels considered\n\\end{center}\n\nNote the $-1$ factor in the metric computation. This factor is used to make the\nmetric be optimal when its minimum is reached.  The optimal value of the metric\nis then minus one. Misalignment between the images results in small measure\nvalues.  The use of this metric is limited to images obtained using the same\nimaging modality.  The metric is insensitive to multiplicative factors\n-- illumination changes -- between\nthe two images.  This metric produces a cost function with sharp peaks and well\ndefined minima.  On the other hand, it has a relatively small capture radius.\n\n\\subsection{Mean Reciprocal Square Differences}\n\\label{sec:MeanReciprocalSquareDifferenceMetric}\n\\index{itk::Mean\\-Reciprocal\\-Square\\-Difference\\-Image\\-To\\-Image\\-Metric}\n\nThe \\doxygen{itk}{MeanReciprocalSquareDifferenceImageToImageMetric} computes\npixel-wise differences and adds them after passing them through a bell-shaped\nfunction $\\frac{1}{1+x^2}$:\n\n\\begin{equation}\nPI(A,B) =  \\sum_{i=1}^N \\frac{ 1 }{ 1 + \\frac{ \\left( A_i - B_i \\right) ^ 2}{ \\lambda^2 }  }\n\\end{equation}\n\\begin{center}\n$A_i$ is the i-th pixel of Image A \\\\\n$B_i$ is the i-th pixel of Image B \\\\\n$N$ is the number of pixels considered \\\\\n$\\lambda$ controls the capture radius\n\\end{center}\n\nThe optimal value is $N$ and poor matches results in small measure values.\nThe characteristics of this metric have been studied by Penney and Holden\n\\cite{Holden1999}\\cite{Penney1998}.\n\nThis image metric has the advantage of producing poor values when few pixels\nare considered.  This makes it consistent when its computation is subject to\nthe size of the overlap region between the images. The capture radius of the\nmetric can be regulated with the parameter $\\lambda$.  The profile of this\nmetric is very peaky. The sharp peaks of the metric help to measure spatial\nmisalignment with high precision. Note that the notion of capture radius is\nused here in terms of the intensity domain, not the spatial domain. In that\nregard, $\\lambda$ should be given in intensity units and be associated with\nthe differences in intensity that will make drop the metric by $50\\%$.\n\nThe metric is limited to images of the same image modality.  The\nfact that its derivative is large at the central peak is a problem for some\noptimizers that rely on the derivative to decrease as the extrema are\nreached.  This metric is also sensitive to linear changes in intensity.\n\n\n\\subsection{Mutual Information Metric}\n\\label{sec:MutualInformationMetric}\n\nThe \\doxygen{itk}{MutualInformationImageToImageMetric} computes the mutual\ninformation between image $A$ and image $B$.  Mutual information (MI)\nmeasures how much information one random variable (image intensity in one\nimage) tells about another random variable (image intensity in the other\nimage). The major advantage of using MI is that the actual form of the\ndependency does not have to be specified.  Therefore, complex mapping between\ntwo images can be modeled.  This flexibility makes MI well suited as a\ncriterion of multi-modality registration~\\cite{Pluim2003}.\n\nMutual information is defined in terms of entropy. Let\n\\begin{equation}\nH(A) = - \\int p_A(a) \\log p_A(a)\\, da\n\\end{equation}\nbe the entropy of random variable $A$, $H(B)$ the entropy of \nrandom variable $B$ and \n\\begin{equation}\nH(A,B) = \\int p_{AB}(a,b) \\log p_{AB}(a,b)\\,da\\,db\n\\end{equation}\nbe the joint entropy of $A$ and $B$. If $A$ and $B$ are independent, then\n\\begin{equation}\np_{AB}(a,b) = p_A(a) p_B(b)\n\\end{equation}\nand\n\\begin{equation}\nH(A,B) = H(A) + H(B).\n\\end{equation}\nHowever, if there is any dependency, then\n\\begin{equation}\nH(A,B)<H(A)+H(B).\n\\end{equation}\nThe difference is called Mutual Information : \\( I(A,B) \\)\n\\begin{equation}\nI(A,B)=H(A)+H(B)-H(A,B)\n\\end{equation}\n\n\\subsubsection{Parzen Windowing}\n\n\\itkpiccaption[Parzen Windowing in Mutual Information]{\nIn Parzen windowing, a continuous density function is constructed by\nsuperimposing kernel functions (Gaussian function in this case) centered on the\nintensity samples obtained from the image.\\label{fig:ParzenWindowing}}\n\\parpic(0.5\\textwidth,5.5cm)[r]{\\includegraphics[width=0.48\\textwidth]{ParzenWindowing13.eps}}\n\nIn a typical registration problem, direct access to the marginal \nand joint probability densities is not available and hence the\ndensities must be estimated from the image data. Parzen windows \n(also known as kernel density estimators) can be used for this purpose.\nIn this scheme, the densities are constructed by taking intensity \nsamples $S$ from the image and super-positioning kernel functions \n$K(\\cdot)$ centered on the elements of $S$ as illustrated in\nFigure \\ref{fig:ParzenWindowing}:\n\nA variety of functions can be used as the smoothing kernel with the\nrequirement that they are smooth, symmetric, have zero mean and\nintegrate to one. For example, boxcar, Gaussian and B-spline functions are\nsuitable candidates.  A smoothing parameter is used to scale the kernel\nfunction.  The larger the smoothing parameter, the wider the kernel function\nused and hence the smoother the density estimate. If the parameter is too\nlarge, features such as modes in the density will get smoothed out.  On the\nother hand, if the smoothing parameter is too small, the resulting density\nmay be too noisy. The estimation is given by the following equation.\n\n\\begin{equation}\np(a) \\approx P^{*}(a) = \\frac{1}{N} \\sum_{s_j \\in S} K\\left(a - s_j\\right)\n\\end{equation}\n\nChoosing the optimal smoothing parameter is a difficult research problem and\nbeyond the scope of this software guide.  Typically, the optimal value of the\nsmoothing parameter will depend on the data and the number of samples used.\n\n\\subsubsection{Viola and Wells Implementation}\n\nOTB, through ITK, has multiple implementations of the mutual information\nmetric. One of the most commonly used is\n\\doxygen{itk}{MutualInformationImageToImageMetric} and follows the method specified\nby Viola and Wells in \\cite{Viola1997}.\n\n\\index{itk::Mutual\\-Information\\-Image\\-To\\-Image\\-Metric}\n\nIn this implementation, two separate intensity samples $S$ and $R$ are drawn\nfrom the image: the first to compute the density, and the second to approximate\nthe entropy as a sample mean:\n\\begin{equation}\nH(A) = \\frac{1}{N} \\sum_{r_j \\in R} \\log P^{*}(r_j).\n\\end{equation}\nGaussian density is used as a smoothing kernel, where the standard deviation\n$\\sigma$ acts as the smoothing parameter.\n\n\\index{itk::Mutual\\-Information\\-Image\\-To\\-Image\\-Metric!SetNumberOfSpatialSamples()}\n\nThe number of spatial samples used for computation is defined using\nthe \\code{SetNumberOfSpatialSamples()} method. Typical values range from 50 to 100.\nNote that computation involves an $N \\times N$ loop and hence, the computation\nburden becomes very expensive when a large number of samples is used.\n\n\\index{itk::Mutual\\-Information\\-Image\\-To\\-Image\\-Metric!SetFixedImageStandardDeviation()}\n\\index{itk::Mutual\\-Information\\-Image\\-To\\-Image\\-Metric!SetMovingImageStandardDeviation()}\nThe quality of the density estimates depends on the choice of the standard\ndeviation of the Gaussian kernel. The optimal choice will depend on the\ncontent of the images.  In our experience with the toolkit, we have found\nthat a standard deviation of 0.4 works well for images that have been\nnormalized to have a mean of zero and standard deviation of 1.0. The standard\ndeviation of the fixed image and moving image kernel can be set separately\nusing methods\n\\code{SetFixedImageStandardDeviation()} and \\code{SetMovingImageStandardDeviation()}.\n\n\\subsubsection{Mattes et al. Implementation}\nAnother form of mutual information metric available in ITK follows the method\nspecified by Mattes et al. in \\cite{Mattes2001} and is implemented by the\n\\doxygen{itk}{MattesMutualInformationImageToImageMetric} class.\n\n\\index{itk::Mattes\\-Mutual\\-Information\\-Image\\-To\\-Image\\-Metric}\nIn this implementation, only one set of intensity samples is drawn from the\nimage.  Using this set, the marginal and joint probability density function\n(PDF) is evaluated at discrete positions or bins uniformly spread within the\ndynamic range of the images. Entropy values are then computed by summing over\nthe bins.\n\n\\index{itk::Mattes\\-Mutual\\-Information\\-Image\\-To\\-Image\\-Metric!SetNumberOfSpatialSamples()}\n\\index{itk::Mattes\\-Mutual\\-Information\\-Image\\-To\\-Image\\-Metric!SetNumberOfHistogramBins()}\n\nThe number of spatial samples used is set using method \n\\code{SetNumberOfSpatialSamples()}. The number of bins used to compute\nthe entropy values is set via \\code{SetNumberOfHistogramBins()}.\n\nSince the fixed image PDF does not contribute to the metric derivatives, it\ndoes not need to be smooth. Hence, a zero order (boxcar) B-spline kernel is\nused for computing the PDF. On the other hand, to ensure smoothness, a third\norder B-spline kernel is used to compute the moving image intensity PDF. The\nadvantage of using a B-spline kernel over a Gaussian kernel is that the\nB-spline kernel has a finite support region. This is computationally\nattractive, as each intensity sample only affects a small number of bins and\nhence does not require a $N \\times N$ loop to compute the metric value.\n\nDuring the PDF calculations, the image intensity values are linearly scaled\nto have a minimum of zero and maximum of one. This rescaling means that a\nfixed B-spline kernel bandwidth of one can be used to handle image data with\narbitrary magnitude and dynamic range.\n\n\n\\subsection{Kullback-Leibler distance metric}\nThe \\doxygen{itk}{KullbackLeiblerCompareHistogramImageToImageMetric} is yet another information based metric. \nKullback-Leibler distance measures the relative entropy between two \ndiscrete probability distributions. The distributions are obtained from the \nhistograms of the two input images, $A$ and $B$. \n\nThe Kullback-Liebler distance between two histograms is given by\n\\begin{equation}\nKL(A,B) =  \\sum_i^N p_A(i) \\times \\log \\frac{ p_A(i) }{p_B(i) }\n\\end{equation}\n\nThe distance is always non-negative and is zero only if the two distributions \nare the same. Note that the distance is not symmetric. In other \nwords, $KL(A,B) \\neq KL(B,A)$. Nevertheless, if the distributions are not too dissimilar, \nthe difference between $KL(A,B)$ and $KL(B,A)$ is small.\n\nThe implementation in ITK is based on \\cite{Chung2002}.\n\n\\subsection{Normalized Mutual Information Metric}\nGiven two images, $A$ and $B$, the normalized mutual information may be computed as \n\\begin{equation}\nNMI(A,B) = 1 + \\frac{I(A,B)}{H(A,B)} = \\frac{H(A) + H(B)}{H(A,B)}\n\\end{equation}\nwhere the entropy of the images, $H(A)$, $H(B)$, the mutual \ninformation, $I(A,B)$ and the joint entropy $H(A,B)$ are computed as mentioned \nin \\ref{sec:MutualInformationMetric}. Details of the implementation may be found in \nthe \\cite{Hajnal2001}.\n\n\\subsection{Mean Squares Histogram}\n\\index{itk::Mean\\-Squares\\-Histogram\\-Image\\-To\\-Image\\-Metric}\n\nThe \\doxygen{itk}{MeanSquaresHistogramImageToImageMetric} is an alternative\nimplementation of the Mean Squares Metric. In this implementation the joint\nhistogram of the fixed and the mapped moving image is built first. The user\nselects the number of bins to use in this joint histogram. Once the joint\nhistogram is computed, the bins are visited with an iterator. Given that each\nbin is associated to a pair of intensities of the form: \\{fixed intensity,\nmoving intensity\\}, along with the number of pixels pairs in the images that\nfell in this bin, it is then possible to compute the sum of square distances\nbetween the intensities of both images at the quantization levels defined by\nthe joint histogram bins.\n\nThis metric can be represented with\nEquation~\\ref{eqn:MeanSquaresHistogramImageToImageMetric}\n\n\\begin{equation}\n\\label{eqn:MeanSquaresHistogramImageToImageMetric}\nMSH = \\sum_f \\sum_m { H(f,m) { \\left( f - m \\right) } ^ 2 }\n\\end{equation}\n\nwhere $H(f,m)$ is the count on the joint histogram bin identified with fixed image\nintensity $f$ and moving image intensity $m$.\n\n\n\\subsection{Correlation Coefficient Histogram}\n\\index{itk::Correlation\\-Coefficient\\-Histogram\\-Image\\-To\\-Image\\-Metric}\n\nThe \\doxygen{itk}{CorrelationCoefficientHistogramImageToImageMetric} computes the\ncross correlation coefficient between the intensities in the fixed image and\nthe intensities on the mapped moving image. This metric is intended to be used\nin images of the same modality where the relationship between the intensities\nof the fixed image and the intensities on the moving images is given by a\nlinear equation. \n\nThe correlation coefficient is computed from the Joint histogram as\n\n\\begin{equation}\n\\label{eqn:CorrelationCoefficientHistogramImageToImageMetric}\nCC = \\frac{ \\sum_f \\sum_m { \\\n            H(f,m) \\left( f \\cdot m - \\\n            \\overline{f} \\cdot \\overline{m} \\right)  } }{ \\\n            \\sum_f { H(f) \\left( (f - \\overline{f})^2 \\right) } \\cdot \\\n            \\sum_m { H(m) \\left( (m - \\overline{m})^2 \\right) } }\n\\end{equation}\n\nWhere $H(f,m)$ is the joint histogram count for the bin identified with the\nfixed image intensity $f$ and the moving image intensity $m$. The values\n$\\overline{f}$ and $\\overline{m}$ are the mean values of the fixed and moving\nimages respectively.  $H(f)$ and $H(m)$ are the histogram counts of the fixed\nand moving images respectively. The optimal value of the correlation\ncoefficient is $1$, which would indicate a perfect straight line in the\nhistogram.\n\n\n\\subsection{Cardinality Match Metric}\n\\index{itk::Match\\-Cardinality\\-Image\\-To\\-Image\\-Metric}\nThe \\doxygen{itk}{MatchCardinalityImageToImageMetric} computes cardinality of the\nset of pixels that match exactly between the moving and fixed images. In other\nwords, it computes the number of pixel matches and mismatches between the two\nimages. The match is designed for label maps. All pixel mismatches are\nconsidered equal whether they are between label 1 and label 2 or between label\n1 and label 500. In other words, the magnitude of an individual label mismatch\nis not relevant, or the occurrence of a label mismatch is important. \n\nThe spatial correspondence between the fixed and moving images is established using \na \\doxygen{itk}{Transform} using the \\code{SetTransform()} method and an interpolator \nusing \\code{SetInterpolator()}. Given that we are matching pixels with labels, \nit is advisable to use Nearest Neighbor interpolation.\n\n\\subsection{Kappa Statistics Metric}\n\\index{itk::Kappa\\-Statistic\\-Image\\-To\\-Image\\-Metric}\nThe \\doxygen{itk}{KappaStatisticImageToImageMetric} computes spatial intersection of \ntwo binary images. The metric here is designed for matching pixels in two images \nwith the same exact value, which may be set using \\code{SetForegroundValue()}. \nGiven two images $A$ and $B$, the $\\kappa$ coefficient is computed as\n \n\\begin{equation}\n\\kappa = \\frac{|A| \\cap |B|}{|A| + |B|}\n\\end{equation}\n\nwhere $|A|$ is the number of foreground pixels in image $A$.  This computes the\nfraction of area in the two images that is common to both the images. In the\ncomputation of the metric, only foreground pixels are considered.\n\n\\subsection{Gradient Difference Metric}\n\\index{it::Gradient\\-Difference\\-Image\\-To\\-Image\\-Metric}\n\nThis \\doxygen{itk}{GradientDifferenceImageToImageMetric} metric evaluates the\ndifference in the derivatives of the moving and fixed images. The derivatives\nare passed through a function $\\frac{1}{1+x}$ and then they are added. The\npurpose of this metric is to focus the registration on the edges of structures\nin the images.  In this way the borders exert larger influence on the result\nof the registration than do the inside of the homogeneous regions on the image.\n\n\n", "meta": {"hexsha": "687b0c96017c739d97d35ca9d256f3c20330fee7", "size": 21617, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Documentation/SoftwareGuide/Latex/ImageMetrics.tex", "max_stars_repo_name": "xcorail/OTB", "max_stars_repo_head_hexsha": "092a93654c3b5d009e420f450fe9b675f737cdca", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-03-30T18:05:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-28T01:03:49.000Z", "max_issues_repo_path": "Documentation/SoftwareGuide/Latex/ImageMetrics.tex", "max_issues_repo_name": "xcorail/OTB", "max_issues_repo_head_hexsha": "092a93654c3b5d009e420f450fe9b675f737cdca", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2015-10-14T10:11:38.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-15T08:26:23.000Z", "max_forks_repo_path": "Documentation/SoftwareGuide/Latex/ImageMetrics.tex", "max_forks_repo_name": "xcorail/OTB", "max_forks_repo_head_hexsha": "092a93654c3b5d009e420f450fe9b675f737cdca", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2015-10-08T12:04:06.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-19T08:00:47.000Z", "avg_line_length": 48.5775280899, "max_line_length": 130, "alphanum_fraction": 0.7799417125, "num_tokens": 5445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.6334102705979902, "lm_q1q2_score": 0.3290701411191007}}
{"text": "\\documentclass[12pt]{article}\n\n% packages\n\\usepackage{setspace}\n\\usepackage{hyperref}\n\\usepackage{array}\n\\usepackage[margin=0.75in]{geometry}\n\\usepackage{amsmath,bm}\n\\usepackage{amssymb}\n\\usepackage{bbold}\n\\usepackage{physics}\n\\usepackage{xcolor}\n\\usepackage{indentfirst}\n\\usepackage{enumerate}\n\\usepackage{mathtools}\n\\usepackage{fancyhdr}\n\n\\pagestyle{fancy}\n\\fancyhf{}\n\\rhead{Creative Destruction Lab}\n\\lhead{Introductions to Projects}\n\\rfoot{Page \\thepage}\n\n\\allowdisplaybreaks\n\n\\title{Project 3: Calculating Franck-Condon Factors}\n\n\\begin{document}\n\n\\maketitle\n\n\\thispagestyle{empty}\n\n\\subsection*{Motivation}\n\nSpectroscopy is the study of how light and matter (atoms and molecules) interact.\nLight can be absorbed by matter (\\textit{absorption}) or matter can emit light (\\textit{emission}).\nIt turns out that spectroscopy is scientists' main tool for discovering properties of molecules (e.g. their molecular structure, bond strengths, etc.) and for chemical identification. Picture for instance an astronomer taking spectroscopic measurements from a gas cloud located millions of light years away from the Earth. To determine what chemicals this gas cloud comprises of, they certainly cannot travel there and take a physical sample of the gas cloud. The astronomer is tasked with utilizing spectroscopic theory (i.e. models wherein numerical studies can be carried out efficiently) to explain what they see.\n\nCountless other applications like drug discovery, magnetic-resonance imaging (MRI) and climate science rely heavily on spectroscopic methods and theory. This week, you'll familiarize yourself with calculating Franck Condon Factors (FCFs), which are useful in studying {\\it vibronic} transitions in molecules. You'll also get to compare your calculations to real experiments.\n\n\\subsection*{Gaussian Boson Sampling}\nAs you have learned in Week 2 in the presentation by Xanadu, Boson Sampling is a powerful tool which demonstrates that a non-universal quantum computer can display exponential speedup over classical computers, especially in the quantum optics or photonics field\\cite{huh2015boson,aaronson2011computational, harrow2017quantum, quesadaFranckCondonFactorsCounting2019}. For our purpose, Gaussian Boson Sampling (GBS), which uses Gaussian input states, can be used to sample a distribution where the probabilities are proportional to the Franck-Condon Factors, which can then be used to construct vibrational spectra.\n\nFranck-Condon Factors involve the overlap of the ``starting\" and ``ending\" wavefunctions of a transition and they are proportional to the amplitude of the vibronic spectrum. The method to calculate the Franck-Condon Factor between state $|m\\rangle$ and $|n\\rangle$ requires the use of the Doktorov operator, $U_{Dok}$, which allows the final state to be represented in terms of the initial state. The overlap can then be calculated as \n\n\\begin{equation}\nFCF=|\\langle m|U_{Dok}|n\\rangle|^2    ~.\n\\end{equation}\n\nThis Doktorov operator can be written in terms of displacement, $D_\\alpha$, squeezing,$\\Sigma_r$ and interferometer operators $U_1$, $U_2$ as\\cite{killoran2019strawberry, bromley2020applications}:\n\n\\begin{equation}\nU_{Dok}=D_\\alpha U_2 \\Sigma_r U_1    ~.\n\\end{equation}\n\nA GBS device can be programmed to perform these operations for a particular molecule, therefore can be used to calculate the FCFs and, in turn, the vibronic spectrum of a molecule. You will have an opportunity to simulate this ``experiment'' in Task 3. \n\\newpage\n\n\\subsection*{Your Tasks}\n\n\\subsubsection*{Task \\#1}\n\nIn this task, you will calculate Franck-Condon Factors for H$_2-$H$_2^+$ using the harmonic oscillator approximation and compare to a real experiment! In a real experiment, we can excite many different vibronic transitions. We would therefore be able to calculate many FCFs that describe different vibronic transitions. For example, it could be that we see excitations corresponding to an H$_2$ molecule in its $n = 0$ vibrational state to H$_2^+$ in its $n = 2$ vibrational state (green line in Fig.~\\ref{fig:visualize_vibronic}) and its $n = 4$ vibrational state. In this task, we will look at only transitions that have a high FCF (i.e. the corresponding transition is very intense).\n\n\\begin{figure} \n    \\begin{center}\n        \\includegraphics[width=0.5\\linewidth]{../figures/potential_energy_curve.pdf}\n    \\end{center}\n    \\caption{A visualization of vibronic transitions. The blue and red curves represent H$_2$ and H$_2^+$, respectively.}\n        \\label{fig:visualize_vibronic}\n\\end{figure}\n\nYou are provided with a \\texttt{python} notebook called \\texttt{Task1.ipynb} which calculates all of the information you require. The \\texttt{FCF\\_helper.py} file contains all of the calculations done under the hood. \\footnote{Calculating FCFs comes down to calculating the overlap between the wavefunctions before and after the vibronic transition. The overlap calculation is an integral which we chose to evaluate numerically. We emphasize that molecular parameters like the reduced mass of H$_2$ and fundamental frequencies of H$_2$ and H$_2^+$ are hard-coded in \\texttt{FCF\\_helper.py}} Currently, the \\texttt{spectrum\\_analysis} function in \\texttt{FCF\\_helper.py} only outputs the following.\n\\begin{itemize}\n    \\item \\texttt{n\\_0} and \\texttt{n\\_p}: The vibrational state numbers of H$_2$ and H$_2^+$, respectively, involved in the vibronic transition\n    \\item \\texttt{FCF}: The corresponding FCF associated to the vibronic transition\n\\end{itemize}\nHere's what we'd like you to do:\n\\begin{enumerate}\n    \\item Open up \\texttt{FCF\\_helper.py} and navigate to the \\texttt{spectrum\\_analysis} function. Modify the \\texttt{data} variable so that it also includes the spectral intensity (\\texttt{Ep - E0}).\n    \\item Plot the corresponding FCF versus spectral intensity (i.e. plot \\texttt{FCF} versus \\texttt{Ep - E0}) and show the results for \\texttt{n\\_0}=0 and \\texttt{n\\_p}=10.\n\\end{enumerate}\n\nCongratulations, you have now successfully predicted the Franck-Condon Factors of H$_2-$H$_2^+$! Figure \\ref{fig:h2_spectrum} shows the photoionization spectrum for H$_2$. Does it look like the real data in Fig.~\\ref{fig:h2_spectrum}?\n\n\\begin{figure}\n    \\begin{center}\n        \\includegraphics[width=\\linewidth]{../figures/H2-expspectrum.pdf}\n    \\end{center}\n    \\caption{\n    Experimental photoionization spectrum of H$_2$-H$_2^+$ from Ref.~\\cite{berkowitz1973comparison} with the vibrational level of H$_2$=0.\n    }\n    \\label{fig:h2_spectrum}\n\\end{figure}\n\n\\subsubsection*{Task \\#2}\n\nYou are provided with a \\texttt{C++} code \\texttt{FC.cxx} created by P.-N. Roy \\cite{yang1995structure}, which calculates the photoionization spectrum for any molecule up to triple excitations and goes beyond the harmonic oscillator approximation. The theory is based on the paper by Ref~\\cite{doktorov1977dynamical}. The molecule you will be investigating is $V_3$.\nThis code takes as input a file which requires the results of diagonalizing the mass-weighted hessian/force-constant matrix (2nd derivative of the Hamiltonian with respect to position). This input file is provided for you (V3).\n\nBrowse the following references (\\cite{yang1995structure,doktorov1977dynamical,quesadaFranckCondonFactorsCounting2019}) to understand how the code works, as you will need a basic understanding of this for the next task, but it's not necessary to fully understand it.  Compile and run the code \\texttt{./FC\\_quick V3}. This code outputs the spectrum \\texttt{V3.spec.out}. Plot it in your favourite plotting program. \n\n\\subsubsection*{Task \\#3}\n\nIn this task, you will be simulating a Gaussian Boson Sampling (GBS) ``experiment.\" This code generates samples for computing a vibronic spectrum. Each sample that is generated starts from the vacuum state and the following gates are performed\\cite{killoran2019strawberry, bromley2020applications}.\n\n\\noindent This code takes as input a file which requires the following information:\n\\begin{enumerate}\n\\item Two-mode squeezing on all  $2N$  modes with parameters \\texttt{t}\n\\item Interferometer \\texttt{U1} on the first $ N$ modes\n\\item Squeezing on the first $N$ modes with parameters \\texttt{r}\n\\item Interferometer \\texttt{U2} on the first  $N$ modes\n\\item Displacement on the first  $N$ modes with parameters \\texttt{alpha}\n\\end{enumerate}\n\nThe energy of the resultant state is calculated and contributes to the spectrum. After running this simulation over many samples and plotting the energies against their frequency, those states (energies) with a high Franck-Condon Factor will have a larger peak on the spectrum and those with a low Franck-Condon Factor will have a smaller peak. It is important to note that it's not the exact values of the peak heights that we care about in this case (since it's based on a probability distribution), it's the relative heights of the peaks of the spectrum.\n\n\\hspace{20mm}\n\nYou are provided with a \\texttt{python} notebook called \\texttt{Task3.ipynb} which calculates all of the information you require. You will be required to use the \\texttt{Strawberry Fields} library\\cite{killoran2019strawberry, bromley2020applications}. Click  \\href{https://strawberryfields.readthedocs.io/en/stable/_static/install.html}{\\underline{\\textbf{here}}} for the install instructions. However, to be able to use this code, you require an input file, which you will have to create. To do this, we will leverage the fact that we have another code that has done this work already, \\texttt{FC.cxx}, which you became familiar with in Task 2. Each piece of information that you need to output has been clearly marked in the code and your task is to write that information to a file, which will then be used as your input file to \\texttt{Sample\\_Vibronic.py}. Once you have that input file, you should be able to produce the spectrum for $V_3$. Compare this spectrum to the previous method. What happens if you decrease the number of samples to 10? 100? 1000? At what number of samples do you feel the spectrum is converged?\n\n\\section*{Challenges}\n\n\\begin{enumerate}\n    \\item An alternative and analogous method to calculating these Franck-Condon Factors using matrix elements is to use a loop hafnian approach. This loop hafnian approach uses Gauss Boson Sampling which would allow these Factors to be calculated using a quantum circuit. Use the result of Task 3 to provide data to a skeleton code provided that uses loop hafnians to calculate the Franck-Condon Factors.\n    \\item Explain briefly the similarities and differences between these three methods.\n\\end{enumerate}\n\n\\section*{Possible Business Outcomes}\n\n\\begin{enumerate}\n    \\item Explain to a layperson what theoretical chemistry/physics is, in the general context of Franck-Condon Factors.\n    \\item What is the importance of theoretical chemistry/physics from an economic point of view.\n    \\item Explain to a layperson what a quantum circuit is and its relationship to theoretical chemistry/physics.\n    \\item These codes use General Public License and Apache 2.0 licenses. Discuss the similarities and differences of these with respect to intellectual property rights of the coder. What are the advantages and disadvantages of codes licensed for the public domain and those that are licensed for private use.\n\\end{enumerate}\n\n\\newpage\n\n\\bibliography{refs}\n\\bibliographystyle{unsrt}\n\n\\end{document}\n", "meta": {"hexsha": "22e0635f8a89e9bf409d53f9a604952b3ef5a714", "size": 11362, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Project_3_Franck_Condon_Factors/Project3_LandingPage.tex", "max_stars_repo_name": "CDL-Week2/CohortProject_2020", "max_stars_repo_head_hexsha": "ce33794267424760926afca0512942ab7e7d28eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-16T03:27:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-16T03:27:28.000Z", "max_issues_repo_path": "Project_3_Franck_Condon_Factors/Project3_LandingPage.tex", "max_issues_repo_name": "CDL-Week2/CohortProject_2020", "max_issues_repo_head_hexsha": "ce33794267424760926afca0512942ab7e7d28eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Project_3_Franck_Condon_Factors/Project3_LandingPage.tex", "max_forks_repo_name": "CDL-Week2/CohortProject_2020", "max_forks_repo_head_hexsha": "ce33794267424760926afca0512942ab7e7d28eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-18T00:58:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-18T00:58:35.000Z", "avg_line_length": 78.3586206897, "max_line_length": 1126, "alphanum_fraction": 0.7876254181, "num_tokens": 2805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.3290701375239353}}
{"text": "\\documentclass[12pt,letterpaper]{article}\n\\usepackage{geometry} % see geometry.pdf on how to lay out the page. There's lots.\n%\\geometry{a4paper} % or letter or a5paper or ... etc\n% \\geometry{landscape} % rotated page geometry\n\n%% LaTeX - Article customise\n\n%%% PACKAGES\n\\usepackage{booktabs} % for much better looking tables\n\\usepackage{array} % for better arrays (eg matrices) in maths\n\\usepackage{paralist} % very flexible & customisable lists (eg. enumerate/itemize, etc.)\n\\usepackage{verbatim} % adds environment for commenting out blocks of text & for better verbatim\n\\usepackage{subfigure} % make it possible to include more than one captioned figure/table in a single float\n% These packages are all incorporated in the memoir class to one degree or another...\n\n%%% PAGE DIMENSIONS\n\\usepackage{geometry} % to change the page dimensions\n%\\geometry{margins=2cm} % for example, change the margins to 2 inches all round\n%\\geometry{landscape} % set up the page for landscape\n% read geometry.pdf for detailed page layout information\n\n%%% HEADERS & FOOTERS\n\\usepackage{fancyhdr} % This should be set AFTER setting up the page geometry\n\\pagestyle{fancy} % options: empty , plain , fancy\n\\renewcommand{\\headrulewidth}{0pt} % customise the layout...\n\\lhead{}\\chead{}\\rhead{}\n\\lfoot{}\\cfoot{\\thepage}\\rfoot{}\n\n%%%% SECTION TITLE APPEARANCE\n%\\usepackage{sectsty}\n%\\allsectionsfont{\\sffamily\\mdseries\\upshape} % (See the fntguide.pdf for font help)\n%% (This matches ConTeXt defaults)\n\n%% LaTeX Preamble - Common packages\n\n\\usepackage[utf8]{inputenc} % Any characters can be typed directly from the keyboard, eg éçñ\n\\usepackage{textcomp} % provide lots of new symbols\n\\usepackage{graphicx}  % Add graphics capabilities\n%\\usepackage{epstopdf} % to include .eps graphics files with pdfLaTeX\n\\usepackage{flafter}  % Don't place floats before their definition\n%\\usepackage{topcapt}   % Define \\topcation for placing captions above tables (not in gwTeX)\n\\usepackage{natbib} % use author/date bibliographic citations\n\n\\usepackage{amsmath,amssymb}  % Better maths support & more symbols\n\\usepackage{bm}  % Define \\bm{} to use bold math fonts\n\n\\usepackage[pdftex,bookmarks,colorlinks,breaklinks]{hyperref}  % PDF hyperlinks, with coloured links\n%\\definecolor{dullmagenta}{rgb}{0.4,0,0.4}   % #660066\n%\\definecolor{darkblue}{rgb}{0,0,0.4}\n%\\hypersetup{linkcolor=red,citecolor=blue,filecolor=dullmagenta,urlcolor=darkblue} % coloured links\n%%\\hypersetup{linkcolor=black,citecolor=black,filecolor=black,urlcolor=black} % black links, for printed output\n\n\\usepackage{memhfixc}  % remove conflict between the memoir class & hyperref\n% \\usepackage[activate]{pdfcprot}  % Turn on margin kerning (not in gwTeX)\n\\usepackage{pdfsync}  % enable tex source and pdf output syncronicity\n\n% Defining Itemized List Levels\n\\renewcommand{\\labelitemi}{$-$}\n%\\renewcommand{\\labelitemii}{$\\cdot$}\n%\\renewcommand{\\labelitemiii}{$\\diamond$}\n%\\renewcommand{\\labelitemiv}{$\\ast$}\n\n% Better margins\n\\usepackage{fullpage}\n\n% Matlab code includer\n% load package with ``framed'' and ``numbered'' option.\n\\usepackage[framed,numbered,autolinebreaks,useliterate]{mcode}\n\n%%% BEGIN DOCUMENT\n\\begin{document}\n\n% Maybe \\noindent\n\n\\begin{center}\n\\huge\nNTRT Scaling Analysis work\\\\\n\\normalsize\n%\\vspace{0.1in}\nAndrew P. (Drew) Sabelhaus\\\\\napsabelhaus@berkeley.edu\n\\end{center}\n\n\\vspace{-2em}\n\n\\section{Nonlinear system example}\n\nIn this example system, there is a rod on a hinge (hinge at (x,y) = (0,0) ) with length $l$.\nThere is an angular (rotational) spring, and an angular damper, acting at the origin also.\nGravity is present, and we assume it acts fully at the center of mass for the rod.\n\nWith the state variables for this system being\n\n\\[\nx = [\\theta, \\dot \\theta]^\\top\n\\]\n\nThe rod makes a triangle with the x-axis and the vertical, and the spring makes a triangle with the y-axis and a horizontal axis drawn from the top of the rod.\n\nThis top triangle has dimensions\n\n\\[\n(l_{horiz-top}, l_{vert-top}) = (l cos \\theta, h_s - l sin\\theta)\n\\]\n\nThe length of the spring (the hypotenuse of this top triangle) is then\n\n\\[\nx_s = \\sqrt( l^2 cos^2\\theta + (h_s - l sin \\theta)^2)\n\\]\n\nFor a given $\\theta$, the force from the spring onto the rod can then be decomposed into the following, assuming that $x_{s0}$ is the rest length of the spring, and we let $\\theta_2$ be the acute angle in the upper triangle close to the rod end:\n\n\\[\nF_{spring} = k x_s = \\sqrt( l^2 cos^2\\theta + (h_s - l sin \\theta)^2)\n\\]\n\\[\nF_{s_x} = F_{spring} cos \\theta_2 = F_{spring} \\frac{ l cos\\theta }{ x_s } = (k)(l)cos\\theta\n\\]\n\\[\nF_{s_y} = F_{spring} sin \\theta_2 = F_{spring} \\frac{ h_s - l sin\\theta}{ x_s} = (k) (h_s - l sin\\theta)\n\\]\n\nSo, then, by Newton's 3rd law, our rigid body dynamics are:\n\\[\n\\sum T = I \\ddot \\theta, (mg)(\\frac{m}{2} sin\\theta) - F_{s_x} l sin\\theta - F_{s_y} l cos\\theta = I \\ddot \\theta\n\\]\n\nFor a solid rod,\n\\[\nI = \\frac{m l^3}{3}\n\\]\n\n\\end{document}\n", "meta": {"hexsha": "7fdb7579548a01b91f9c2630022b6cf5eedbf76e", "size": 4906, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/dev/apsabelhaus/scaling_analysis/backup/scaling_counterexample_backup.tex", "max_stars_repo_name": "wvat/NTRTsim", "max_stars_repo_head_hexsha": "0443cbd542e12e23c04adf79ea0d8d003c428baa", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 148, "max_stars_repo_stars_event_min_datetime": "2015-01-08T22:44:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T18:42:48.000Z", "max_issues_repo_path": "src/dev/apsabelhaus/scaling_analysis/backup/scaling_counterexample_backup.tex", "max_issues_repo_name": "wvat/NTRTsim", "max_issues_repo_head_hexsha": "0443cbd542e12e23c04adf79ea0d8d003c428baa", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 107, "max_issues_repo_issues_event_min_datetime": "2015-01-02T16:41:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-14T22:09:19.000Z", "max_forks_repo_path": "src/dev/apsabelhaus/scaling_analysis/backup/scaling_counterexample_backup.tex", "max_forks_repo_name": "wvat/NTRTsim", "max_forks_repo_head_hexsha": "0443cbd542e12e23c04adf79ea0d8d003c428baa", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 86, "max_forks_repo_forks_event_min_datetime": "2015-01-06T07:02:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T17:36:14.000Z", "avg_line_length": 36.3407407407, "max_line_length": 245, "alphanum_fraction": 0.7331838565, "num_tokens": 1472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.3290701339287698}}
{"text": "\\documentclass[letterpaper]{article}\n\n\\usepackage{fullpage}\n\\usepackage{nopageno}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\allowdisplaybreaks\n\n\\newcommand{\\abs}[1]{\\left\\lvert #1 \\right\\rvert}\n\n\\begin{document}\n\\title{Notes}\n\\date{September 17, 2014}\n\\maketitle\n\\section*{assignment}\nSection 1.4: \\# 17, 19, 20, 23, 24, 27. \n\\renewcommand{\\labelenumi}{2.\\arabic{enumi}}\n\\renewcommand{\\labelenumii}{\\arabic{enumii}.}\n\\renewcommand{\\labelenumiii}{(\\alph{enumiii})}\n\\begin{enumerate}\n\\setcounter{enumi}{2}\n\\item\n  \\begin{enumerate}\n  \\setcounter{enumii}{4}\n  \\item\n  \n  \\item\n  (1),(12),(13),(14),(23),(24),(34),(123),(124),(134),(234),(132),(243),(142),(143),(1234)\n  \\end{enumerate}\n\\end{enumerate}\n\n\\section*{2.3.5 theorem}\nsketch of a proof\n\\begin{align*}\n  \\tau&=\\left(\n  \\begin{aligned}\n    1&\\quad2&\\quad3&\\quad\\dots& n\\\\\n    \\sigma(1)&\\quad\\sigma(2)&\\quad\\sigma(3)&\\quad\\dots&\\sigma(n)\n  \\end{aligned}\n  \\right)\n\\end{align*}\n\\section*{example}\n\\begin{align*}\n  \\sigma&=\\left(\n  \\begin{aligned}\n    &1&&\\quad2&&\\quad3&&\\quad4&&\\quad5&&\\quad6&&7\\\\\n    &7&&\\quad2&&\\quad6&&\\quad3&&\\quad1&&\\quad5&&4\\\\\n  \\end{aligned}\n  \\right)=(1,7,4,3,6,5)\n\\end{align*}\ndefinition: let $\\sigma\\in S$ the least positive integer $m$ such that $\\sigma^m=(1)$ is called the order of $\\sigma$\n\\subsubsection*{example}\n$\\sigma=(123)(45)\\to(123)^3(45)^2=\\sigma^6$\n\\subsubsection*{observation for 2.3.8 proof}\n$(a1a2a3\\dots ak)^i=(1)$ and $(b1b2b3\\dots bk)^i=1$ because they are disjoint and applying the a permutions don't change the b elements and vice versa\n\\end{document}\n\n", "meta": {"hexsha": "afacd132300679290c90f8342db0abc7a29b4d18", "size": 1557, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "abstract algebra/abstract-notes-2014-09-17.tex", "max_stars_repo_name": "ylixir/school", "max_stars_repo_head_hexsha": "66d433f2090b6396c8dd2a53a733c25dbe7bc90f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "abstract algebra/abstract-notes-2014-09-17.tex", "max_issues_repo_name": "ylixir/school", "max_issues_repo_head_hexsha": "66d433f2090b6396c8dd2a53a733c25dbe7bc90f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "abstract algebra/abstract-notes-2014-09-17.tex", "max_forks_repo_name": "ylixir/school", "max_forks_repo_head_hexsha": "66d433f2090b6396c8dd2a53a733c25dbe7bc90f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8448275862, "max_line_length": 150, "alphanum_fraction": 0.6685934489, "num_tokens": 601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.32907013392876977}}
{"text": "%%% Intro.tex --- \n%% \n%% Filename: Intro.tex\n%% Description: \n%% Author: Ola Leifler\n%% Maintainer: \n%% Created: Thu Oct 14 12:54:47 2010 (CEST)\n%% Version: $Id$\n%% Version: \n%% Last-Updated: Thu May 19 14:12:31 2016 (+0200)\n%%           By: Ola Leifler\n%%     Update #: 5\n%% URL: \n%% Keywords: \n%% Compatibility: \n%% \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% \n%%% Commentary: \n%% \n%% \n%% \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% \n%%% Change log:\n%% Completed Language Reading MBS\n%% \n%% RCS $Log$\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% \n%%% Code:\n\n\n\\chapter{Integration of Optimization tool-chain into the Model-Based Development Process}\n\\label{cha:optimization}\n\nThis chapter is based on the following paper:\n\n\\begin{itemize}\n\t\n\t\\item \\textbf{Alachew Shitahun}, Vitalij Ruge, Mahder Gebremedhin, Bernhard Bachmann, Lars Eriksson, Joel Andersson, Moritz Diehl, and Peter Fritzson. \\textbf{Model-Based Optimization with OpenModelica and CasADi.} In Proceedings of IFAC Conference in Tokyo, September 2013. \n\t\n\t\\item  \\textbf{Alachew Shitahun}, Vitalij Ruge, Mahder Gebremedhin, Bernhard Bachmann, Lars Eriksson, Joel Andersson, Moritz Diehl, Peter Fritzson. \\textbf{Tool Demonstration Abstract: OpenModelica and CasADi for Model-Based Dynamic Optimization.} In Proceedings of the 5th International Workshop on Equation-Based Object-Oriented Modeling Languages and Tools, Nottingham, UK, April 19, 2013. \n\t\t\n\\end{itemize}\n\n\n\n\\section{Introduction}\n\\label{sec:optimizationintroduction}\n\nDuring the last decade, nonlinear model predictive control (NMPC) and non-linear optimal control problems (NOCP)\nbased on Differential-Algebraic Equations (DAEs) have had a significant impact in the industrial community, particularly in\nthe control engineering area \\cite{biegler, tamimi}. State-of-the-art methods use numerical\nalgorithms for dynamic optimization based on direct multiple shooting \\cite{bock} or collocation algorithms\n\\cite{biegler}.\n\nUse of equation-based, object-oriented modeling languages such as Modelica for\nindustrial applications has increased. These languages enable users to conveniently model large-scale physical systems described by \ndifferential, algebraic, and discrete equations, primarily with the goal of performing virtual experiments (simulation) \non these systems, but recently also optimization.\n\nDue to the influence of such equation-based, object-oriented modeling languages in the industrial community, there have\nbeen several attempts to integrate tools for such languages with numerical algorithms for optimization. For example,\nDymola \\cite{dymola} supports parameter and design optimization of models written in Modelica, whereas\nJModelica.org \\cite{akesson} and OpenModelica \\cite{bernhard} have native support for optimal\ncontrol.\n\nThis chapter presents results of an effort in which OpenModelica and CasADi \\cite{casadi} have been integrated to perform model-based dynamic optimization. The problem formulation and modeling is done in Modelica \nincluding the optimization \\cite{optimica} language extension. The integration is based\non standardized XML format presented in \\cite{xml} for exchange of \\acrshort{daes} models. \nOpenModelica supports export of models written in Modelica and the optimization language extension using this XML \nformat, while CasADi supports importing of models represented in this format. This allows users to define optimal control problems (OCP) using\nModelica and optimization language specification, and solve the underlying model formulation using a\nrange of optimization methods, including direct collocation and direct multiple shooting. The proposed\nsolution has been tested on several industrially relevant optimal control problems, including a diesel-electric\npower train.\n\n\\section{CasADi}\n\\label{sec:optcasadi}\n\nCasADi \\cite{casadi} is an open-source framework for C++ and Python that provides numerical optimization in general and optimal control in particular. The main idea of the tool is to provide users with the ability to easily and efficiently implement optimal control algorithms with a wide range of methods, including multiple shooting and collocation, rather than providing users with a “black-box” OCP solver.\nThe tool supports symbolic import of OCPs via an extended version of the functional mockup interface (FMI) format as explained in \\cite{optandersson}. This OCP can then be transcribed into a nonlinear programming problem (NLP) and solved with one of CasADi’s interfaced NLP solvers.\n\n\\section{Modelica and the Optimization Language Extension}\n\\label{sec:optimizationoptimica}\n\nModelica is a mature and powerful language with regard to modeling of complex hybrid dynamical systems. However, it\nlacks important features for describing or modeling optimization problems. This is not a surprise since Modelica\nwas not originally designed to help with dynamic optimization problems.\n\nThe optimization language extension \\cite{optimica} complements Modelica by providing features that enable\nformulation of dynamic optimization problems based on Modelica models. The optimization extension to Modelica\nconsists of the following elements:\n\n\\begin{itemize}\n\t\n\\item \\textit{objective} and \\textit{objectiveIntegerand}, which maps the Mayer and the Lagrange term in \n            the objective function respectively.\n\\item \\textit{startTime}, which defines the start of the optimization interval.\n\\item \\textit{finalTime}, which defines the end of the optimization interval.\n\\item A new section: \\textit{constraint}, which defines inequality constraints.\n\\end{itemize}\n\nThe requirement and motivation for introducing these specific features is covered in more detail in \\cite{optimica}.\n\n\\section{Modeling NOCP and XML Export in OpenModelica Compiler}\n\\label{sec:optimizationopenmodelica}\n\nThe OpenModelica compiler front-end has been extended to support the optimization language extension described in\nSection \\ref{sec:optimizationoptimica}. \n\n\\begin{figure} [!h]\n\t\\includegraphics[width=\\linewidth]{opt_modeling_NOCP.png}\n\t\\caption{Modeling NOCP using the OpenModelica Graphical and Textual Editor.}\n\t\\label{fig:nocpmodel}\n\\end{figure}\n\nThis enables users to use the OpenModelica graphical editor (OMEdit) (see Figure \\ref{fig:nocpmodel})to formulate and use model-based NOCP that can be solved by CasADi.\nIn addition, the OpenModelica compiler has recently been extended with XML export of models \\cite{alachew} based on the XML\nformat defined in \\cite{xml}. This schema is an extended version of the XML schema\ndefined by the Functional Mock-up Interface (FMI) \\cite{fmi}, and is the most recent in a series of\nModelica-related XML schemas starting with ModelicaXML \\cite{pop}. The XML export also includes the\noptimization language extension, and OpenModelica is integrated with CasADi for the type of model-based dynamic optimization reported in this thesis.\n\n\\section{Complete Model-Based Dynamic Optimization tool-chain}\n\\label{sec:optimizationtoolchain}\n\nBefore exporting a Modelica and optimization language model to XML, the model should be symbolically\ninstantiated by the compiler in order to get a single flat system of equations. The model variables should also be\nscalarized. The compiler front end performs this, including syntax checking, semantics and type checking, simplification\nand constant evaluation, etc. Then the complete flattened model is exported to XML code. The exported\nXML document can then be imported to CasADi for model-based dynamic optimization. The complete tool chain is\nvisualized in Figure \\ref{fig:optimizationtoolchain}.\n\n\n\\begin{figure} [!h]\n\t\\includegraphics[width=\\linewidth]{opt_tool_chain.png}\n\t\\caption{Model-Based Dynamic Optimization tool-chain for OpenModelica and CasADi.}\n\t\\label{fig:optimizationtoolchain}\n\\end{figure}\n\nThe XML will be imported and symbolically pre-processed in CasADi. In particular, the fully-implicit \\acrshort{dae} from\nModelica is reformulated in a semi-explicit form. With the NOCP now available in CasADi’s native data structures, the\nNOCP can be reformulated to a NLP as outlined in \\cite{alachewoptimization} (See Section 2.2).\n\nAt the time of our work, the efficient symbolic pre-processing model evaluation from OpenModelica is not yet completely\nimplemented to import into CasADi. So the symbolic preprocessing in CasADi can be used. The symbolic work in CasADi makes it easy to create the goal function and constraints.\n\nThe NLP is solved by one of the NLP solvers interfaced to CasADi, e.g., IPOPT \\cite{wachter}. First and second order derivative information will be generated by CasADi using automatic differentiation and passed to the solver.\n\n\\section{Testing the Tool-chain Implementation}\n\\label{sec:optimizationtesting}\n\nIn this section, we describe the solution of an industrially-relevant optimal control problem for a diesel-electric powertrain. The\nformulation of the underlying optimization problem and the corresponding optimization results are presented in the\nfollowing subsections.\n\n\\subsection{Fuel optimal control of a diesel electric powertrain}\n\\label{sec:optimizationdiesel}\n\nThe diesel-electric powertrain model presented in \\cite{sivertsson,bernhard} is a nonlinear\nmean value engine model (MVEM) containing four states and three control inputs, while the generator model is\nsimplified by considering constant efficiency and maximum power over the entire speed range, see Figure \\ref{fig:dieselmodel} for the\nschematic diagram of the model.\n\n\\begin{figure} [!h]\n\t\\includegraphics[width=\\linewidth]{opt_diesel_model.png}\n\t\\caption{Diagram of the diesel-electric powertrain model.}\n\t\\label{fig:dieselmodel}\n\\end{figure}\n\nIn a diesel-electric powertrain the operating point of the diesel engine can be freely chosen, which would potentially\ndecrease fuel consumption. Moreover, the electric machine has better torque characteristics. These are the main reasons\nthat the diesel-electric power-train concept is interesting for further studies.\n\nTo investigate the fuel-optimal transients of the powertrain from idling condition to a certain power level while the\naccelerator pedal position is interpreted as a power level request, the following optimal control problem is solved:\n\n\\begin{equation*}\n \\begin{aligned}\n\t\\text{states}\\quad x = 0, \\quad \\begin{pmatrix} w_{ice} \\\\ p_{im} \\\\p_{em} \\\\w_{tc}  \\end{pmatrix}\\quad = \\quad \\text{controls,}\\quad u = \\begin{pmatrix} u_{f} \\\\ u_{wg} \\\\p_{gen} \\\\w_{tc}  \\end{pmatrix} \\\\\n\t\\text{min}\\;\\int_{0}^{T}\\dot{m}{_f} d_t\n\\end{aligned}\n\\end{equation*}\n\nsubject to\n\n\\begin{equation*}\n\t\\begin{aligned}\n\t\t\\dot{x}_1 = f_2 (x_2,x_3,u_1,u_3 ) \\\\\n\t\t\\dot{x}_2= f_3 (x_1,x_2,x_4 ) \\\\\n\t\t\\dot{x}_3=f_4 (x_1,x_2,x_3,u_1,u_2 ) \\\\\n\t\t\\dot{x}_4=f_5 (x_2,x_3,x_4,u_2 ) \\\\\n\t\t0= f_6 (x_2,x_4 )- f_7 (x_1,x_2 ) \\\\\n\t\t0= f_7(x_1,x_2 ) + f_8 (x_1,u_1 )-f_9 (x_3 )-f_{10}(x_3,u_3 )  \\\\\n\t\t0= \\frac{f_{11}(x_3)-f_{12}(x_1 )} {f_{13}(x_4 )}-f_{14} (x_4 )\n\\end{aligned}\n\\end{equation*}\n\n\\begin{equation*}\n\t\\begin{aligned}\n      54 rps \\;\\leq  \\;  x_1  \\;\\leq \\; 220 rps \\\\\n      0.8 p_{amp} \\;\\leq \\;  x_2 \\; \\leq \\; 2P_{amb} \\\\\n      P_{amb} \\;  \\leq\\; x_3 \\;\\leq \\;  3P_{amb} \\\\\n      300rps  \\; \\leq \\; x_4 \\;\\leq \\;   10000 rps \\\\\n      0 \\;\\leq \\;u_1,u_2 \\;\\leq \\; 1\n\t\\end{aligned}\n\\end{equation*}\n\nand boundary conditions are:\n\n\\begin{equation*}\n \\begin{aligned}\n\t\\text{at}\\quad t = 0,  \\begin{pmatrix} x_1 \\\\ x_2 \\\\x_3 \\\\x_4  \\end{pmatrix} = \\text{idle operating values,} \\\\\n\t\\text{at}\\quad t = T,  \\begin{pmatrix} \\dot{x}_1 \\\\ \\dot{x}_2 \\\\\\dot{x}_3\\\\\\dot{x}_4 \\end{pmatrix} = 0,  \\begin{pmatrix} x1 \\\\ x2 \\\\x3 \\\\x4  \\end{pmatrix} = \\text{desired values} \\\\\n\t\\text{and}\\quad v_3 = P_{required}.\n \\end{aligned}\n\\end{equation*}\n\nThe constraints are originated from components’ limitations and the functions $ f_i$ are described in \\cite{sivertsson}.\n\n\\subsection{Model import into CasADi and NLP transcription}\n\\label{sec:optimizationxmlimport}\n\nWe used OpenModelica to translate Modelica/ Optimization\nlanguage extension code into an OCP in DAE and Lagrange\ncost function. This OCP is then exported into an XML-based\nsymbolic expression format and imported into CasADi via\nOpenModelica. The OCP can then be transcribed into a\nnonlinear programming problem (NLP) using the approach\noutlined in \\cite{bernhard} of Section 5, and solved with one of CasADi’s interfaced NLP solvers.\n\n\\subsection{Solution of the NLP}\n\\label{sec:optimizationnlp}\n\nThe NLP was solved using IPOPT \\cite{wachter} running by default with the MUMPS linear solver.\nThe right scaling is important for a solution without oscillations.\nOn the other hand, if the scaling does not work in all steps\nthen changing of the solver tolerance is helpful. By itself, the diesel model\nscales well in the time interval [0.32, 0.5],\nwhich is the critical interval here.\n\nIn order to cover the optimal solution of the diesel-electric\npowertrain model, 140 NLP iterations for 128 sub-intervals\nwith the total collocation (Lobatto6 and Radau5) are required by\nIPOPT.\n\nA better initial guess will change the NLP iterations.\nTable \\ref{tab:table1} shows the total CPU time for the optimization. The calculations have been done on a Dell Latitude E6410 laptop\nwith an Intel Core i7 processor of 2.8 GHz, 8 GB of RAM, 4M Cache, running Windows.\n\n\\begin{table} [!h]\n\\begin{center}\n\t\\caption{Execution times for the diesel-electric powertrain model.} \n\t\\label{tab:table1} \n\t\\begin{tabular}{ cc } \n\t\t\\hline\n\t\t\\bfseries Step & \\bfseries Time  \\\\ \n\t\tIPOPT (without function evaluation) & 2.140s \\\\ \n\t\tNLP function evaluations & 1.158s \\\\ \n\t\t\\hline\n\t\\end{tabular}\n\\end{center}\n\\end{table}\n\nThe control and state trajectories of the optimal solutions are shown in Figure \\ref{fig:optimizationresultstatevariables} and Figure \\ref{fig:optimizationresultcontrolvariables}, respectively. \n\n%%% \\begin{figure} [!h]\n%%%\t\\includegraphics[width=\\linewidth]{opt_initial_guess_state_variables.jpg}\n%%%\t\\caption{Initial guess for diesel model - state variables.}\n%%%\t\\label{fig:initialguessstatevariables}\n%%% \\end{figure}\n\n%%% \\begin{figure} [!h]\n%%%\t\\includegraphics[width=\\linewidth]{opt_initial_guess_control_variables.jpg}\n%%%\t\\caption{Initial guess for diesel model - control variables.}\n%%%\t\\label{fig:initialguesscontrolvariables}\n%%% \\end{figure}\n\nThe problem solved here is a minimum fuel problem for a transient from idle to 170 kW, for an end time of 0.5 s. For simplicity, only diesel operating condition is assumed which\nmeans $(u_3=P_{gen} = 0)$. As expected, the fuel optimal results happen when the engine is accelerated only near the\nend of the time interval $(t\\approx 0.32 s)$, to meet the end constraints while minimizing the fuel consumption.\n\n\\begin{figure} [!h]\n\t\\includegraphics[width=\\linewidth]{opt_result_state_variables.jpg}\n\t\\caption{Optimization result for diesel model - state variables.}\n\t\\label{fig:optimizationresultstatevariables}\n\\end{figure}\n\n\\begin{figure} [!h]\n\t\\includegraphics[width=\\linewidth]{opt_result_control_variables.jpg}\n\t\\caption{Optimization result for diesel model - control variables.}\n\t\\label{fig:optimizationresultcontrolvariables}\n\\end{figure}\n\n\\clearpage\nWith amendments to the initial values, the process is robust. For this purpose, the initial values are changed slightly.\n\n\\begin{figure} [!h]\n\t\\includegraphics[width=\\linewidth]{opt_result_state_variables_changed.jpg}\n\t\\caption{Optimization result for diesel model with changed initial values - state variables.}\n\t\\label{fig:optimizationresultchangedstatevariables}\n\\end{figure}\n\n\\begin{figure} [!h]\n\t\\includegraphics[width=\\linewidth]{opt_result_control_variables_changed.jpg}\n\t\\caption{Optimization result for diesel model with changed initial values - control variables.}\n\t\\label{fig:optimizationresultchangedcontrolvariables}\n\\end{figure}\n\n\\clearpage\n\\section{Summary}\n\\label{sec:optimizationsummary}\n\nThis chapter demonstrates simulation-based optimization through the coupling of two open-source tools: OpenModelica, which is a Modelica-based modeling and simulation platform, and CasADi, a framework for numerical optimization. The coupling uses a standardized XML format for exchange of\ndifferential-algebraic equations (DAE) models. OpenModelica supports export of models written in Modelica and the optimization language extension using this XML format, while CasADi supports import of models represented in this format. This allows users to define optimal control problems (OCP) using\nModelica and optimization language specification, and to solve the underlying model formulation using a range of optimization methods, including direct collocation and direct multiple shooting. The proposed solution has been tested on several industrially-relevant optimal control problems, including a diesel-electric power train.\n\n\\subsection*{Acknowledgements}\n\\label{sec:optimizationacknowledgements}\n\nThis work has been partially supported by Serc, by SSF in the EDOp project and by Vinnova as well as the German\nMinistry BMBF (BMBF F\\\"{o}rderkennzeichen: 01IS09029C) in the ITEA2 OPENPROD project and in the ITEA2 MODRIO\nproject. The open-source Modelica Consortium supports the OpenModelica work.\nJA and MD acknowledge support by PFV/10/002 OPTEC, GOA/10/09 and GOA/10/11, FWO G.0320.08, G.0377.09,\nSBO LeCoPro; Belspo IUAP P7 DYSCO, FP7-EMBOCON (ICT-248940), SADCO (MC ITN-264735),\nERC ST HIGHWIND (259 166), Eurostars SMART, vicerp, ACCM.\n\n\n%\\nocite{scigen}\n%We have included Paper \\ref{art:scigen}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Intro.tex ends here\n\n\n%%% Local Variables: \n%%% mode: latex\n%%% TeX-master: \"demothesis\"\n%%% End: \n\n", "meta": {"hexsha": "e1f8eef4221614c06f3d480c72c4798087bd067d", "size": 17647, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "optimization.tex", "max_stars_repo_name": "alash325/lictest", "max_stars_repo_head_hexsha": "1dce77ac23d71017c6bf728efbb910850d43e8c2", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "optimization.tex", "max_issues_repo_name": "alash325/lictest", "max_issues_repo_head_hexsha": "1dce77ac23d71017c6bf728efbb910850d43e8c2", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "optimization.tex", "max_forks_repo_name": "alash325/lictest", "max_forks_repo_head_hexsha": "1dce77ac23d71017c6bf728efbb910850d43e8c2", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.4489795918, "max_line_length": 410, "alphanum_fraction": 0.7681758939, "num_tokens": 4507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.5660185351961016, "lm_q1q2_score": 0.3290283238714609}}
{"text": "\\section{Performance indexes}\\label{sec:indexes}\n\nWe have defined the following performance indexes:\n\\begin{description}\n\t\\item[Total broadcast time] (\\(t_B\\)) The time required in order to\n\t\tdeliver the message to all reachable users.\n\t\\item[Percentage of covered users] (\\(\\mathit{\\%U}\\)) The number of\n\t\tusers infected.\n\t\\item[Energy efficiency] (\\(\\mathit{Eff}\\)) We define the energy\n\t\tefficiency as an index that decreases with the increase of the\n\t\tbroadcast radius \\(R\\) and the total number of transmissions\n\t\t\\(M\\). We will not develop a well-defined mathematical formula\n\t\tfor the energy efficiency of wireless communications; we will\n\t\tjust state that \\(\\mathit{Eff} \\propto \\frac{1}{R \\cdot M}\\). Of\n\t\tcorse, this index is of great interest in wireless ad-hoc\n\t\tnetworks where each communicating device must optimize the\n\t\tenergy used in order to avoid frequent battery recharges or\n\t\treplacements. Moreover, we note that from the point of view of a\n\t\tsingle user of our model, where the user must relay the message\n\t\tat most one time only, the only factor affecting this index is\n\t\t\\(R\\). So our network should try to minimize \\(R\\) in order to\n\t\tmaximize the energy efficiency. We may consider the total number\n\t\tof transmissions only to evaluate the efficiency of the\n\t\t\\emph{entire} network.\n\t\\item[Total number of collisions] (\\(C\\)) The total number of\n\t\tcollisions. This is of course highly related to the number of\n\t\tusers in the network. We must consider that a network with an\n\t\thigher user density may have an higher number of collisions. So\n\t\tthis index may not be user to compare the performance of\n\t\tnetworks with different number of users (at least, not without\n\t\tnormalization).\n\\end{description}\n", "meta": {"hexsha": "45ac1232e012de54f64ed74c06e3f2ac9831de46", "size": 1726, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/chapters/design/indexes.tex", "max_stars_repo_name": "SpeedJack/pecsn", "max_stars_repo_head_hexsha": "40c757cddec978e06de766c9dff00abf57ccd6b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/chapters/design/indexes.tex", "max_issues_repo_name": "SpeedJack/pecsn", "max_issues_repo_head_hexsha": "40c757cddec978e06de766c9dff00abf57ccd6b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/chapters/design/indexes.tex", "max_forks_repo_name": "SpeedJack/pecsn", "max_forks_repo_head_hexsha": "40c757cddec978e06de766c9dff00abf57ccd6b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.303030303, "max_line_length": 68, "alphanum_fraction": 0.7578215527, "num_tokens": 438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3290283238714608}}
{"text": "%2multibyte Version: 5.50.0.2890 CodePage: 932\n\n\\documentclass[11pt]{article}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\usepackage{amssymb}\n\\usepackage{amsmath}\n\\usepackage{amsfonts}\n\\usepackage{geometry}\n\\usepackage[onehalfspacing]{setspace}\n\\usepackage{numinsec}\n\\usepackage{harvard}\n\\usepackage{hyperref}\n\\usepackage{rotating}\n\\usepackage[labelsep=none,format=default,labelfont={footnotesize},textfont={footnotesize},font={footnotesize},justification=justified,labelformat=empty]{caption}\n\\usepackage{bibmods}\n\\usepackage{appendix}\n\n\\setcounter{MaxMatrixCols}{10}\n%TCIDATA{OutputFilter=LATEX.DLL}\n%TCIDATA{Version=5.50.0.2890}\n%TCIDATA{Codepage=932}\n%TCIDATA{<META NAME=\"SaveForMode\" CONTENT=\"1\">}\n%TCIDATA{BibliographyScheme=Manual}\n%TCIDATA{Created=Saturday, July 19, 2008 23:46:52}\n%TCIDATA{LastRevised=Tuesday, November 20, 2018 00:49:35}\n%TCIDATA{<META NAME=\"GraphicsSave\" CONTENT=\"32\">}\n%TCIDATA{<META NAME=\"DocumentShell\" CONTENT=\"Standard LaTeX\\Blank - Standard LaTeX Article\">}\n%TCIDATA{Language=American English}\n%TCIDATA{CSTFile=40 LaTeX article.cst}\n\n\\setlength{\\topmargin}{-0.8in}\n\\geometry{top=0.93in}\n\\setlength{\\textheight}{9in}\n\\setlength{\\evensidemargin}{0in}\n\\setlength{\\oddsidemargin}{0in}\n\\setlength{\\textwidth}{6.5in}\n\\renewcommand{\\baselinestretch}{1.4}\n\\newtheorem{theorem}{Theorem}[section]\n\\newtheorem{acknowledgement}[theorem]{Acknowledgement}\n\\newtheorem{algorithm}[theorem]{Algorithm}\n\\newtheorem{axiom}[theorem]{Axiom}\n\\newtheorem{case}[theorem]{Case}\n\\newtheorem{claim}[theorem]{Claim}\n\\newtheorem{conclusion}[theorem]{Conclusion}\n\\newtheorem{condition}[theorem]{Condition}\n\\newtheorem{conjecture}[theorem]{Conjecture}\n\\newtheorem{corollary}[theorem]{Corollary}\n\\newtheorem{criterion}[theorem]{Criterion}\n\\newtheorem{definition}[theorem]{Definition}\n\\newtheorem{example}[theorem]{Example}\n\\newtheorem{exercise}[theorem]{Exercise}\n\\newtheorem{lemma}{Lemma}[section]\n\\newtheorem{notation}[theorem]{Notation}\n\\newtheorem{problem}[theorem]{Problem}\n\\newtheorem{proposition}[theorem]{Proposition}\n\\newtheorem{remark}[theorem]{Remark}\n\\newtheorem{solution}[theorem]{Solution}\n\\newtheorem{summary}[theorem]{Summary}\n\\newtheorem{assumption}{Assumption}[section]\n\\newenvironment{proof}[1][Proof]{\\noindent \\textbf{#1.} }{\\  \\rule{0.5em}{0.5em}}\n\\input{tcilatex}\n\\begin{document}\n\n\n\\noindent \n%TCIMACRO{\\TeXButton{Today}{\\today}}%\n%BeginExpansion\n\\today%\n%EndExpansion\n\n\\bigskip\n\n\\section{Robust Inference for Risk Prices}\n\n\\subsection{Asymptotic Distribution of the Reduced-Form Parameter}\n\nWrite $\\omega :=(\\omega _{1},\\omega _{2},\\omega _{3})^{\\prime },$ where $%\n\\omega _{1}=(\\rho ,c,\\delta )\\in O_{1},$ $\\omega _{2}=(\\gamma ,\\beta ,\\psi\n)\\in O_{2},$ and $\\omega _{3}=\\zeta \\in O_{3}.$ The parameter space for $%\n\\omega $ is $O=O_{1}\\times O_{2}\\times O_{3}\\subset R^{d_{\\omega }}.$ The\ntrue value of $\\omega $ is assumed to be in the interior of the parameter\nspace.\n\nBelow we describe the estimator $\\widehat{\\omega }:=(\\widehat{\\omega }_{1},%\n\\widehat{\\omega }_{2},\\widehat{\\omega }_{3})^{\\prime }$ and provide its\nasymptotic distribution. We estimate these parameters separately because $%\n\\omega _{1}$ only shows up in the conditional mean and variance of $\\sigma\n_{t+1}^{2},$ $\\omega _{2}$ only shows up in the conditional mean of $r_{t+1},\n$ and $\\omega _{3}$ only shows up in the conditional variance of $r_{t+1}.$\n\nWe first estimate $\\omega _{1}=(\\rho ,c)$ based on the conditional mean and\nvariance of $\\sigma _{t+1}^{2}$, which can be equivalently written as \n\\begin{eqnarray}\nE[\\sigma _{t+1}^{2}|\\sigma _{t}^{2}] &=&A\\text{ and }E[\\sigma\n_{t+1}^{4}|\\sigma _{t}^{2}]=B,\\text{ where }  \\notag \\\\\nA &=&\\rho \\sigma _{t}^{2}+c\\delta \\text{ and }B=A^{2}+\\left( 2c\\rho \\sigma\n_{t}^{2}+c^{2}\\delta \\right) .\n\\end{eqnarray}%\nBecause the conditional mean of $\\sigma _{t+1}^{2}$ and $\\sigma _{t+1}^{4}$\nare linear and quadratic functions, respectively, of the conditioning\nvariable $\\sigma _{t}^{2},$ without loss of efficiency, they can be\ntransformed to the unconditional moments%\n\\begin{equation}\nE[h_{t}(\\omega _{10})]=0,\\text{ where }h_{t}(\\omega _{1})=[(1,\\sigma\n_{t}^{2})\\otimes (\\sigma _{t+1}^{2}-A),(1,\\sigma _{t}^{2},\\sigma\n_{t}^{4})\\otimes (\\sigma _{t+1}^{4}-B)]^{\\prime },\n\\end{equation}%\nwhere $\\omega _{10}$ represents the true value of $\\omega _{1}.$ The\ntwo-step GMM estimator of $\\omega _{1}$ is%\n\\begin{equation}\n\\widehat{\\omega }_{1}=\\underset{\\omega _{1}\\in O_{1}}{\\arg \\min }\\left(\nT^{-1}\\sum_{t=1}^{T}h_{t}(\\omega _{1})\\right) ^{\\prime }\\widehat{V}%\n_{1}\\left( T^{-1}\\sum_{t=1}^{T}h_{t}(\\omega _{1})\\right) ,\n\\label{omega 1 est}\n\\end{equation}%\nwhere $\\widehat{V}_{1}$ is a consistent estimator of $V_{1}=\\sum_{m=-\\infty\n}^{\\infty }\\mathbb{C}ov[h_{t}(\\omega _{10}),h_{t+m}(\\omega _{10})].$\n\nWe estimate $\\omega _{2}$ by the generalized least squares (GLS) estimator\nbecause the conditional mean of $r_{t+1}$ is a linear function of the\nconditioning variable $\\sigma _{t}^{2}$ and $\\sigma _{t+1}^{2}$ and the\nconditional variance is proportional to $\\sigma _{t+1}^{2}.$ The GLS\\\nestimator of $\\omega _{2}$ is%\n\\begin{eqnarray}\n\\widehat{\\omega }_{2} &=&\\left( \\sum_{t=1}^{T}x_{t}x_{t}^{\\prime }\\right)\n^{-1}\\sum_{t=1}^{T}x_{t}y_{t},\\text{ where }  \\notag \\\\\nx_{t} &=&\\sigma _{t+1}^{-1}(1,\\sigma _{t}^{2},\\sigma _{t+1}^{2})^{\\prime }%\n\\text{ and }y_{t}=\\sigma _{t+1}^{-1}r_{t+1}.  \\label{omega 2 est}\n\\end{eqnarray}%\nWe estimate $\\omega _{3}$ by the sample variance estimator%\n\\begin{equation}\n\\widehat{\\omega }_{3}=T^{-1}\\sum_{t=1}^{T}\\left( y_{t}-\\widehat{y}%\n_{t}\\right) ^{2},\\text{ where }\\widehat{y}_{t}=x_{t}^{\\prime }\\widehat{%\n\\omega }_{2}.  \\label{omega 3 est}\n\\end{equation}\n\nLet \n\\begin{equation}\nf_{t}(\\omega )=\\left( \n\\begin{array}{c}\nh_{t}(\\omega _{1}) \\\\ \nx_{t}(y_{t}-x_{t}^{\\prime }\\omega _{2}) \\\\ \n(y_{t}-x_{t}^{\\prime }\\omega _{2})^{2}%\n\\end{array}%\n\\right) \\in R^{d_{f}}\\text{ and }V=\\sum_{m=-\\infty }^{\\infty }\\mathbb{C}%\n\\mathbf{ov}[f_{t}(\\omega _{0}),f_{t+m}(\\omega _{0})].\n\\end{equation}%\nThe estimator $\\widehat{\\omega }$ defined above is based on the first moment\nof $f_{t}(\\omega ).$ Let $\\widehat{V}$ denote a heteroskeasticity and\nautocorrelation consistent (HAC) estimator of $V$. The estimator $\\widehat{V}%\n_{1}$ is a submatrix of $\\widehat{V}$ associate with $V_{1}.$\n\nLet $P$ denote the distribution of the data $\\mathcal{W}=\\{W_{t}=(r_{t+1},%\n\\sigma _{t+1}^{2}):t\\geq 1\\}$ and $\\mathcal{P}$ denote the parameter space\nof $P$. Note that the true values of the structural parameter and the\nreduced-form parameters are all determined by $P.$ We allow $P$ to change\nwith $T.$ For notational simplicity, the dependence on $P$ and $T$ is\nsuppressed. Let $H_{t}(\\omega _{1})=\\partial h_{t}(\\omega _{1})/\\partial\n\\omega _{1}^{\\prime }.$ \n\n\\smallskip \n\n\\noindent \\textbf{Assumption R}. The following conditions hold uniformly\nover $P\\in \\mathcal{P}$.\n\n\\noindent (i) $V^{-1/2}\\{T^{-1/2}(\\sum_{t=1}^{T}f_{t}(\\omega _{0})-\\mathbb{E[%\n}f_{t}(\\omega _{0})\\mathbb{]\\} \\rightarrow }_{d}N(0,I)$ and $\\widehat{V}%\n-V\\rightarrow _{p}0.$\n\n\\noindent (ii) $T^{-1}\\sum_{t=1}^{T}(h_{t}(\\omega _{1})-\\mathbb{E[}%\nh_{t}(\\omega _{1}))\\rightarrow _{p}0$ and $T^{-1}\\sum_{t=1}^{T}(H_{t}(\\omega\n_{1})-\\mathbb{E[}H_{t}(\\omega _{1})\\mathbb{])}\\rightarrow _{p}0,$ $\\mathbb{E[%\n}H_{t}(\\omega _{1})\\mathbb{]}$ is continuous in $\\omega _{1},$ all uniformly\nover the parameter space of $\\omega _{1}.$\n\n\\QTP{Body Math}\n\\noindent (iii) $T^{-1}\\sum_{t=1}^{T}(x_{t}x_{t}^{\\prime }-\\mathbb{E[}%\nx_{t}x_{t}^{\\prime }\\mathbb{])\\rightarrow }_{p}0.$\n\n\\noindent (iv) $C^{-1}\\leq \\lambda _{\\min }(A)\\leq \\lambda _{\\max }(A)\\leq C$\nfor $A=V,\\mathbb{E[}H_{t}\\left( \\omega _{1,0}\\right) ^{\\prime }H_{t}\\left(\n\\omega _{1,0}\\right) ]),\\mathbb{E[}x_{t}x_{t}^{\\prime }],\\mathbb{E[}%\nz_{t}z_{t}^{\\prime }],$ where $z_{t}=(1,\\sigma _{t}^{2},\\sigma\n_{t}^{4})^{\\prime }.$\n\n\\smallskip \n\nAssumptions R(i)-(iii) are the central limit theorem and the uniform law of\nlarge numbers applied to weakly dependent time series data. Assumption\nR(iv)-R(v) are typical regularity conditions for the identification and $%\nT^{1/2}$ normality of the reduced-form parameter estimator.\n\nLet $H(\\omega _{1})=\\mathbb{E[}H_{t}(\\omega _{1})]$ and $\\overline{H}(\\omega\n_{1})=T^{-1}\\sum_{t=1}^{T}H_{t}(\\omega _{1}).$ Define%\n\\begin{eqnarray}\nF &=&diag\\{[H(\\omega _{10})V_{1}^{-1}H(\\omega _{10})]^{-1}H(\\omega\n_{10})V_{1}^{-1},\\mathbb{E[}x_{t}x_{t}^{\\prime }]^{-1},1\\},  \\notag \\\\\n\\widehat{F} &=&diag\\{[\\overline{H}(\\widehat{\\omega }_{1})^{\\prime }\\widehat{V%\n}_{1}^{-1}\\overline{H}(\\widehat{\\omega }_{1})]^{-1}\\overline{H}(\\widehat{%\n\\omega }_{1})^{\\prime }\\widehat{V}_{1}^{-1},[T^{-1}%\n\\sum_{t=1}^{T}x_{t}x_{t}^{\\prime }]^{-1},1\\}.  \\label{Fhat}\n\\end{eqnarray}%\nThe following Lemma provides the asymptotic distribution of the reduced-form\nparameter and a consistent estimator of its asymptotic covariance. Note that\nwe put the asymptotic covariance on the left side of the convergence to\nallow the distribution of the data to change with sample size $T.$ \n\n\\begin{lemma}\n\\label{Lemma Reduce}Suppose Assumption R holds. The following results hold\nuniformly over $P\\in \\mathcal{P}$.\n\n\\noindent \\emph{(i)} $\\xi _{T}:=\\Omega ^{-1/2}T^{-1/2}(\\widehat{\\omega }%\n-\\omega _{0})\\rightarrow _{d}\\xi \\sim N(0,I),$ where $\\Omega =FVF^{\\prime }.$\n\n\\noindent \\emph{(ii)} $\\widehat{\\Omega }-\\Omega \\rightarrow _{p}0,$ where $%\n\\widehat{\\Omega }=\\widehat{F}\\widehat{V}\\widehat{F}^{\\prime }.$\n\\end{lemma}\n\n\\subsection{Weak Identification}\n\nThe true value of the structural parameter $\\lambda $ and the reduced-form\nparameter $\\omega $ satisfies the link function $g(\\lambda _{0},\\omega\n_{0})=0.$In a standard problem without any identification issue, we can\nestimate $\\lambda _{0}$ by the minimum distance estimator $\\widehat{\\lambda }%\n=(\\widehat{\\theta },\\widehat{\\pi },\\widehat{\\phi })$ that minimizes $%\nQ_{T}(\\lambda )=g(\\lambda ,\\widehat{\\omega })^{\\prime }W_{T}g(\\lambda ,%\n\\widehat{\\omega })$ for some weighting matrix $W_{T}$ and construct tests\nand confidence sets for $\\lambda _{0}$ based on the asymptotic normal\ndistribution of $T^{1/2}(\\widehat{\\lambda }-\\lambda _{0})$. However, this\nstandard method does not work in the present problem when $\\pi _{0}$ is only\nweak identified. In this case, $g(\\lambda ,\\widehat{\\omega })$ is almost\nflat in $\\pi $ and the minimum distance estimator of $\\widehat{\\pi }$ is not\neven consistent. To make the problem even more complicated, the\ninconsistency of $\\widehat{\\pi }$ has a spillover effect on $\\widehat{\\theta \n}$ and $\\widehat{\\phi },$ making the distribution of $\\widehat{\\theta }$ and \n$\\widehat{\\phi }$ non-normal even in large sample.\n\nBefore presenting the robust test, we first introduce some useful quantities\nand provide some heuristic discussions of the identification problem and its\nconsequence. Let $G(\\lambda ,\\omega )$ denote the partial derivative of $%\ng(\\lambda ,\\omega )$ wrt $\\omega .$ Let $g_{0}(\\lambda )=g(\\lambda ,\\omega\n_{0})$ and $G_{0}(\\lambda )=G(\\lambda ,\\omega _{0})$ be the link function\nand its derivative evaluated at $\\omega _{0}$ and $\\widehat{g}(\\lambda\n)=g(\\lambda ,\\widehat{\\omega })$ and $\\widehat{G}(\\lambda )=G(\\lambda ,%\n\\widehat{\\omega })$ be the same quantities evaluate at the estimator $%\n\\widehat{\\omega }.$ The delta method gives \n\\begin{equation}\n\\eta _{n}(\\lambda ):=T^{1/2}\\left[ \\widehat{g}(\\lambda )-g_{0}(\\lambda )%\n\\right] =G_{0}(\\lambda )\\Omega ^{1/2}\\cdot \\xi _{T}+o_{p}(1),\n\\label{emp pro}\n\\end{equation}%\nwhere $\\xi _{T}\\rightarrow _{d}N(0,I)$ following Lemma \\ref{Lemma Reduce}.\nThus, $\\eta _{n}(\\cdot )$ weakly converges to a Gaussian process $\\eta\n(\\cdot )$ with covariance function $\\Sigma (\\lambda _{1},\\lambda\n_{2})=G_{0}(\\lambda _{1})\\Omega G_{0}(\\lambda _{2})^{\\prime }.$\n\nFollowing (\\ref{emp pro}), we can write $T^{1/2}\\widehat{g}(\\lambda )=\\eta\n_{n}(\\lambda )+T^{1/2}g_{0}(\\lambda ),$ where $\\eta _{n}(\\lambda )$ is the\nnoise from the reduced-form parameter estimation and $T^{1/2}g_{0}(\\lambda )$\nis the signal from the link function. Under weak identification, $%\ng_{0}(\\lambda )$ is almost flat in $\\lambda ,$ modelled by the signal $%\nT^{1/2}g_{0}(\\lambda )$ being finite even for $\\lambda \\neq \\lambda _{0}$\nand $T\\rightarrow \\infty .$ Thus, the signal and the noise are of the same\norder of magnitude, yielding an inconsistent minimum distance estimator $%\n\\widehat{\\lambda }.$ This is in contrast with the strong identification\nscenario, where $T^{1/2}g_{0}(\\lambda )\\rightarrow \\infty $ for $\\lambda\n\\neq \\lambda _{0}$ as $T\\rightarrow \\infty $ and $g_{0}(\\lambda _{0})=0.$ In\nthis case, the signal is so strong that the minimum distance estimator is\nconsistent.\n\nThe identification strength of $\\lambda _{0}$ is determined by the function $%\nT^{1/2}g_{0}(\\lambda ).$ However, this function is unknown and cannot be\nconsistently estimated (due to $T^{1/2}$). Thus, we take the conditional\ninference procedure as in Andrews and Mikusheva (2016)\\ and view $%\nT^{1/2}g_{0}(\\lambda )$ as an infinite dimensionalnuisance parameter for the\ninference for $\\lambda _{0}$. The goal is to control robust confidence set\n(CS) for $\\lambda _{0}$ that has correct size asymptotically regardless of\nthis unknown nuisance parameter.\n\n\\subsection{Conditional QLR\\ Test}\n\nWe construct a confidence set for $\\lambda $ by inverting the test $%\nH_{0}:\\lambda =\\lambda _{0}$ vs $H_{1}:\\lambda \\neq \\lambda _{0}$. The test\nstatistic is a QLR\\ statistic that takes the form%\n\\begin{equation}\nQLR(\\lambda _{0})=T\\widehat{g}(\\lambda _{0})^{\\prime }\\widehat{\\Sigma }%\n(\\lambda _{0},\\lambda _{0})^{-1}\\widehat{g}(\\lambda _{0})-\\underset{\\lambda\n\\in \\Lambda }{\\min }T\\widehat{g}(\\lambda )^{\\prime }\\widehat{\\Sigma }%\n(\\lambda ,\\lambda )^{-1}\\widehat{g}(\\lambda ),  \\label{QLR stat}\n\\end{equation}%\nwhere $\\widehat{\\Sigma }(\\lambda _{1},\\lambda _{2},)=\\widehat{G}(\\lambda\n_{1})\\widehat{\\Omega }\\widehat{G}(\\lambda _{2})^{\\prime }$ and $\\widehat{%\n\\Omega }$ is the consistent estimator of $\\Omega $ defined above$.$\n\nAndrews and Mikusheva (2016) provide the conditional QLR\\ test in a\nnonlinear GMM problem, where $\\widehat{g}(\\lambda )$ is replaced by a sample\nmoment. The same method can be applied to the present nonlinear minimum\ndistance problem. Following AM, we first project $\\widehat{g}(\\lambda )$\nonto $\\widehat{g}(\\lambda _{0})$ and construct a residual process%\n\\begin{equation}\n\\widehat{r}(\\lambda )=\\widehat{g}(\\lambda )-\\widehat{\\Sigma }(\\lambda\n,\\lambda _{0})\\widehat{\\Sigma }(\\lambda _{0},\\lambda _{0})^{-1}\\widehat{g}%\n(\\lambda _{0}).  \\label{red process}\n\\end{equation}%\nThe limiting distribution of $\\widehat{r}(\\lambda )$ and $\\widehat{g}%\n(\\lambda _{0})$ are Gaussian and independent. Thus, conditional on $\\widehat{%\nr}(\\lambda ),$ the asymptotic distribution of $\\widehat{g}(\\lambda )$ no\nlonger depends on the nuisance parameter $T^{1/2}g_{0}(\\lambda ),$ making\nthe procedure robust to all identification strength.\n\nSpecifically, we obtain the $1-\\alpha $ conditional quantile of the QLR\nstatistic, denoted by $c_{1-\\alpha }(r,\\lambda _{0}),$ as follows. For $%\nb=1,..,B,$ we take independent draws $\\eta _{b}^{\\ast }\\sim N(0,\\widehat{%\n\\Sigma }(\\lambda _{0},\\lambda _{0}))$ and produce a simulated process \n\\begin{equation}\ng_{b}^{\\ast }(\\lambda )=\\widehat{r}(\\lambda )+\\widehat{\\Sigma }(\\lambda\n,\\lambda _{0})\\widehat{\\Sigma }(\\lambda _{0},\\lambda _{0})^{-1}\\eta\n_{b}^{\\ast }\n\\end{equation}%\nand a simulated statistic%\n\\begin{equation}\nQLR_{b}^{\\ast }(\\lambda _{0})=T\\widehat{g}(\\lambda _{0})^{\\prime }\\widehat{%\n\\Sigma }(\\lambda _{0},\\lambda _{0})^{-1}\\widehat{g}(\\lambda _{0})-\\underset{%\n\\lambda \\in \\Pi }{\\min }Tg_{b}^{\\ast }(\\lambda )^{\\prime }\\widehat{\\Sigma }%\n(\\lambda ,\\lambda )^{-1}g_{b}^{\\ast }(\\lambda ).\n\\end{equation}%\nLet $b_{0}=\\lceil (1-\\alpha )B\\rceil ,$ the smallest integer no smaller than \n$(1-\\alpha )B$. Then the critical value $c_{1-\\alpha }(r,\\lambda _{0})$ is\nthe $b_{0}^{th}$ smallest value among $\\{QLR_{b}^{\\ast },b=1,...,B\\}.\\Omega $\n\n\\smallskip \n\nTo sum up, we execute the following steps for a robust CS for $\\lambda .$\n\n\\noindent (i) Estimate the reduced-form parameter $\\widehat{\\omega }=(%\n\\widehat{\\omega }_{1},\\widehat{\\omega }_{2},\\widehat{\\omega }_{3})^{\\prime }$\nfollowing the estimators defined in (\\ref{omega 1 est}) and (\\ref{omega 2\nest}). Obtain a consistent estimator of its asymptotic covariance $\\widehat{%\n\\Omega }=\\widehat{F}\\widehat{V}\\widehat{F}^{\\prime },$ where $\\widehat{F}$\nis define in (\\ref{Fhat}) and $\\widehat{V}$ is a heteroskedastic and\nautocorrelation consistent (HAC) estimator of $V.$\n\n\\noindent For $\\lambda _{0}\\in \\Lambda ,$ execute steps (ii)-(iv) below.\n\n\\noindent (ii) Construct the QLR statistic $QLR(\\lambda _{0})$ in (\\ref{QLR\nstat}) using $g(\\lambda ,\\omega ),$ $G(\\lambda ,\\omega ),$ $\\widehat{\\omega }%\n,$ and $\\widehat{\\Omega }.$\n\n\\noindent (iii) Compute the residual process $\\widehat{r}(\\lambda )$ in (\\ref%\n{red process}).\n\n\\noindent (iv) Given $\\widehat{r}(\\lambda ),$ compute the critical value $%\nc_{1-\\alpha }(r,\\lambda _{0})$ described above.\n\n\\noindent (v) Repeat steps (ii)-(iv) for different values of $\\lambda _{0}$.\nConstruct a confidence set by collecting the null values that are not\nrejected, i.e., nominal level $1-\\alpha $ confidence set for $\\lambda _{0}$\nis%\n\\begin{equation}\nCS_{T}=\\{ \\lambda _{0}:QLR_{T}(\\lambda _{0})\\leq c_{1-\\alpha }(r,\\lambda\n_{0})\\}.\n\\end{equation}\n\n\\smallskip \n\nTo obtain confidence intervals for each element of $\\lambda _{0},$ one\nsimple solution is to project the confidence set constructed above to each\naxis. The resulting confidence interval also has correct coverage. An\nalternative solution is to first concentrate out the nuisance parameters\nbefore apply the conditional inference approach above, see Section 5\\ of AM.\nHowever, this concentration approach only works when the nuisance parameter\nis strongly identified. In the present set-up, this approach does not work\nfor $\\theta $ and $\\phi $ because the nuisance parameter $\\pi $ is weakly\nidentified.\n\n\\smallskip \n\n\\noindent \\textbf{Assumption S}. The following conditions hold over $P\\in \n\\mathcal{P},$ for any $\\lambda $ in its parameter space, and any $\\omega $\nin some fixed neighborhood around its true value. \n\n\\noindent (i) $g(\\lambda ,\\omega )$ is twice continuously differentiable in $%\n\\omega $ and the second order derivative $G_{\\omega }(\\lambda ,\\omega )$\nsatisfies $||G_{\\omega }(\\lambda ,\\omega )||\\leq C.$\n\n\\noindent (ii) $C^{-1}\\leq \\lambda _{\\min }(G(\\lambda ,\\omega )^{\\prime\n}G(\\lambda ,\\omega ))\\leq \\lambda _{\\max }(G(\\lambda ,\\omega )^{\\prime\n}G(\\lambda ,\\omega ))\\leq C$.\n\n\\smallskip \n\n\\begin{lemma}\n\\label{Lemma CS}Suppose Assumption R and S hold. Then, \n\\begin{equation*}\n\\underset{T\\rightarrow \\infty }{\\lim \\inf }\\underset{P\\in \\mathcal{P}}{\\inf }%\n\\Pr \\left( \\lambda _{0}\\in CS_{T}\\right) \\geq 1-\\alpha .\n\\end{equation*}\n\\end{lemma}\n\nThis Lemma states that the confidence set constructed by the conditional\nQLR\\ test has correct uniform asymptotic size. Uniformity is important for\nthis confidence set to cover the true parameter with a probability close to $%\n1-\\alpha $ in finite-sample. Most importantly, this uniform result is\nestablished over a parameter $\\mathcal{P}$ that is large enough to allow the\nweak identification of the structural parameter $\\lambda .$\n\n\\bigskip \n\n\\bigskip \n\n\\noindent Proof of Lemma \\ref{Lemma Reduce}. Under the assumption that (i) $%\n\\mathbb{E(}z_{t}z_{t}^{\\prime })$ has the smallest eigenvalue bounded away\nfrom 0 and (ii) $c>\\varepsilon $ and $\\delta >\\varepsilon $ for some $%\n\\varepsilon >0,$ we not only have $\\omega _{10}$ as an uniquely minimizer of \n$||\\mathbb{E}[h_{t}(\\omega _{1})]||$ but also have a uniform positive lower\nbound for $||E[h_{t}(\\omega _{1})]||$ for $||\\omega _{1}-\\omega _{10}||\\geq\n\\varepsilon .$ Thus, consistency of $\\widehat{\\omega }_{1}$ follows from\nstandard arguments for the consistency of a GMM estimator under an uniform\nconvergence of the criterion under Assumption R(ii). \n\nLet $\\overline{h}(\\omega _{1})=T^{-1}\\sum_{t=1}^{T}h_{t}(\\omega _{1})$ and $%\n\\overline{H}(\\omega )=T^{-1}\\sum_{t=1}^{T}H_{t}(\\omega _{1}).$ By\nconstruction, the estimator satisfies the first order condition%\n\\begin{eqnarray}\n0 &=&\\left( \n\\begin{array}{c}\n\\overline{H}(\\widehat{\\omega }_{1})^{\\prime }\\widehat{V}_{1}^{-1}\\overline{h}%\n(\\widehat{\\omega }_{1}) \\\\ \nT^{-1}\\sum_{T=1}^{T}x_{t}(y_{t}-x_{t}^{\\prime }\\widehat{\\omega }_{2}) \\\\ \n\\widehat{\\omega }_{3}-T^{-1}\\sum_{t=1}^{T}\\left( y_{t}-\\widehat{y}%\n_{t}\\right) ^{2}%\n\\end{array}%\n\\right)   \\notag \\\\\n&=&\\left( \n\\begin{array}{c}\n\\overline{H}(\\widehat{\\omega }_{1})^{\\prime }\\widehat{V}_{1}^{-1}\\overline{h}%\n(\\omega _{10})+\\overline{H}(\\widehat{\\omega }_{1})^{\\prime }\\widehat{V}%\n_{1}^{-1}\\overline{H}(\\widetilde{\\omega }_{1})(\\widehat{\\omega }_{1}-\\omega\n_{10}) \\\\ \nT^{-1}\\sum_{t=1}^{T}x_{t}(y_{t}-x_{t}^{\\prime }\\omega\n_{20})-T^{-1}\\sum_{t=1}^{T}x_{t}x_{t}^{\\prime }\\left( \\widehat{\\omega }%\n_{2}-\\omega _{20}\\right)  \\\\ \n\\left( \\widehat{\\omega }_{3}-\\omega _{3}\\right) +\\omega\n_{3}-T^{-1}\\sum_{t=1}^{T}\\left( y_{t}-x_{t}\\widehat{\\omega }_{2}\\right) ^{2}%\n\\end{array}%\n\\right) ,  \\label{L-R-1}\n\\end{eqnarray}%\nwhere the second equality follows from a mean value expansion of $\\overline{h%\n}(\\widehat{\\omega }_{1})$ around $\\omega _{10},$ with $\\widetilde{\\omega }%\n_{1}$ between $\\omega _{10}$ and $\\widehat{\\omega }_{1}$. Let%\n\\begin{equation}\n\\widetilde{F}=diag\\{[\\overline{H}(\\widehat{\\omega }_{1})^{\\prime }\\widehat{V}%\n_{1}^{-1}\\overline{H}(\\widetilde{\\omega }_{1})]^{-1}\\overline{H}(\\widehat{%\n\\omega }_{1})^{\\prime }\\widehat{V}_{1}^{-1},[T^{-1}%\n\\sum_{t=1}^{T}x_{t}x_{t}^{\\prime }]^{-1},1\\}.\n\\end{equation}%\nThen (\\ref{L-R-1}) implies that \n\\begin{eqnarray}\nT^{1/2}\\left( \\widehat{\\omega }-\\omega \\right)  &=&\\widetilde{F}\\cdot\nT^{-1/2}\\sum_{t=1}^{T}\\left( \n\\begin{array}{c}\n-h_{t}(\\omega _{10}) \\\\ \nx_{t}(y_{t}-x_{t}^{\\prime }\\omega _{20}) \\\\ \n\\left( y_{t}-x_{t}\\widehat{\\omega }_{2}\\right) ^{2}-\\omega _{3}%\n\\end{array}%\n\\right)   \\notag \\\\\n&=&\\widetilde{F}\\cdot T^{-1/2}\\sum_{t=1}^{T}\\left( \n\\begin{array}{c}\n-h_{t}(\\omega _{10}) \\\\ \nx_{t}(y_{t}-x_{t}^{\\prime }\\omega _{20}) \\\\ \n\\left( y_{t}-x_{t}^{\\prime }\\omega _{20}\\right) ^{2}-\\mathbb{E}[\\left(\ny_{t}-x_{t}^{\\prime }\\omega _{20}\\right) ^{2}]%\n\\end{array}%\n\\right) +\\left( \n\\begin{array}{c}\n0 \\\\ \n0 \\\\ \n\\varepsilon _{T}%\n\\end{array}%\n\\right) ,  \\label{L-R-2}\n\\end{eqnarray}%\nwhere the second equality uses $\\omega _{3}=\\mathbb{E}[\\left(\ny_{t}-x_{t}^{\\prime }\\omega _{20}\\right) ^{2}]$ by definition and \n\\begin{eqnarray}\n\\varepsilon _{T} &=&T^{-1/2}\\sum_{t=1}^{T}\\left[ \\left( y_{t}-x_{t}^{\\prime }%\n\\widehat{\\omega }_{2}\\right) ^{2}-\\left( y_{t}-x_{t}^{\\prime }\\omega\n_{20}\\right) ^{2}\\right]   \\notag \\\\\n&=&2T^{-1}\\sum_{t=1}^{T}\\left( y_{t}-x_{t}^{\\prime }\\omega _{20}\\right)\nx_{t}^{\\prime }\\left[ T^{1/2}\\left( \\widehat{\\omega }_{2}-\\omega\n_{20}\\right) \\right] +o_{p}(1)  \\notag \\\\\n&=&o_{p}(1)  \\label{L-R-3}\n\\end{eqnarray}%\nbecause $T^{-1}\\sum_{t=1}^{T}\\left( y_{t}-x_{t}^{\\prime }\\omega _{20}\\right)\nx_{t}^{\\prime }\\rightarrow _{p}0$ and $T^{1/2}(\\widehat{\\omega }_{2}-\\omega\n_{20})=O_{p}(1)$ following Assumption R. In addition, \n\\begin{equation}\n\\widetilde{F}\\rightarrow _{p}F  \\label{L-R-4}\n\\end{equation}%\nfollowing from the consistency of $\\widehat{\\omega }_{1}$ and Assumption R.\nFinally, the desirable result follows from (\\ref{L-R-2})-(\\ref{L-R-4}) and\nAssumption R. The consistency of $\\widehat{\\Omega }$ follows from the\nconsistency of $\\widehat{F}$ and $\\widehat{V}.$ $_{\\square }$\n\n\\bigskip \n\n\\noindent Proof of Lemma \\ref{Lemma CS}. Assumptions 1-3 of AM holds under\nAssumption R, S, and Lemma \\ref{Lemma Reduce}. This Lemma then follows from\nTheorem 1 of AM. $_{\\square }$\n\n\\end{document}\n", "meta": {"hexsha": "2d69d811062f99312717ddd8087123d69d7d9e2f", "size": 23821, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/early versions/Risk Price CLR Inference.tex", "max_stars_repo_name": "sangrey/RiskPriceInference", "max_stars_repo_head_hexsha": "9ec8b235e3d1f24281890a5f689840affd3f495e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/early versions/Risk Price CLR Inference.tex", "max_issues_repo_name": "sangrey/RiskPriceInference", "max_issues_repo_head_hexsha": "9ec8b235e3d1f24281890a5f689840affd3f495e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/early versions/Risk Price CLR Inference.tex", "max_forks_repo_name": "sangrey/RiskPriceInference", "max_forks_repo_head_hexsha": "9ec8b235e3d1f24281890a5f689840affd3f495e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.6164383562, "max_line_length": 252, "alphanum_fraction": 0.6660509634, "num_tokens": 8438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.32902831536038285}}
{"text": "\n\\documentclass{article}\n\n\\usepackage{fontspec}\n\\usepackage{unicode-math}\n\\usepackage{siunitx}\n\\sisetup{separate-uncertainty}\n\\usepackage{booktabs}\n\\usepackage{biblatex}\n\\addbibresource{main.bib}\n\n\\begin{document}\n\n\\thispagestyle{empty}\n\\subsection*{Highly unscientific calculation of expected $B\\to D\\mu\\mu$ yields}\n\n\\begin{itemize}\n  \\item $\\mathcal{L} = \\SI{3.189}{\\per\\femto\\barn}$\n  \\item $σ_{b\\overline{b}} = \\SI{295 \\pm 29}{\\micro\\barn}$\n  \\item $f_d \\approx \\num{0.4}$\n  \\item $ε_\\text{geom} \\approx \\num{0.15}$\n  \\item $ε_\\text{trig} \\approx \\num{0.8}$\n  \\item $ε_\\text{strip} \\approx \\num{0.2}$\n  \\item All BRs for $q^2 > \\SI{1}{GeV}$\n  \\item $\\mathrm{BR}(D^{0}\\to K^-\\pi^+) = \\SI{3.87 \\pm 0.05}{\\percent}$\n  \\item $\\mathrm{BR}(D^+\\to K^-\\pi^+\\pi^+) = \\SI{9.13 \\pm 0.19}{\\percent}$\n  \\item $\\mathrm{BR}(D_s^+\\to K^+K^-\\pi^+) = \\SI{5.49 \\pm 0.27}{\\percent}$\n  \\item $\\mathrm{BR}(D^{*0} \\to D^0\\pi^0) = \\SI{61.9 \\pm 2.9}{\\percent}$\n  \\item $\\mathrm{BR}(D^{*+} \\to D^0\\pi^+) = \\SI{67.7 \\pm 0.5}{\\percent}$\n  \\item $\\mathrm{BR}(D_s^{+*}\\to D_s^+\\pi^0) = \\SI{5.8 \\pm 0.7}{\\percent}$\n\\end{itemize}\n\n\\vspace{3em}\n\n\\begin{tabular}{l S S}\n  \\toprule\n  Decay & {\\text{Predicted BR}} \\cite{evans1}\\cite{evans2} & {\\text{Expected yield}} \\\\\n  \\midrule\n  $B^0\\to D\\mu\\mu$ & 2.6e-9 & 1.8 \\\\\n  $B^0\\to D^*\\mu\\mu$ & 1.4e-8 & 6.1 \\\\\n  $B^+\\to D^+\\mu\\mu$ & 2.5e-12 & 0.41e-2 \\\\\n  $B^+\\to D^{+*}\\mu\\mu$ & 1.0e-11 & 0.48e-2 \\\\\n  $B^+\\to D_s^+\\mu\\mu$ & 4.3e-11 & 0.17e-2 \\\\\n  $B^+\\to D_s^{+*}\\mu\\mu$ & 2.0e-10 & 0.12e-1 \\\\\n  $B_c\\to D_s^+\\mu\\mu$ & ? & ? \\\\\n  $B_c\\to D_s^{*+}\\mu\\mu$ & ? & ? \\\\\n  \\bottomrule\n\\end{tabular}\n\n\\newpage\n\n\\printbibliography\n\n\\end{document}\n", "meta": {"hexsha": "5e2c9308ff363e6868282951ec837d96daeef39a", "size": 1657, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "logbook/decays/table.tex", "max_stars_repo_name": "ibab/lhcb-b2dmumu", "max_stars_repo_head_hexsha": "c1334c381032af9459602640e17541377fd16606", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-06-24T10:56:34.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-24T10:57:11.000Z", "max_issues_repo_path": "logbook/decays/table.tex", "max_issues_repo_name": "ibab/lhcb-b2dmumu", "max_issues_repo_head_hexsha": "c1334c381032af9459602640e17541377fd16606", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "logbook/decays/table.tex", "max_forks_repo_name": "ibab/lhcb-b2dmumu", "max_forks_repo_head_hexsha": "c1334c381032af9459602640e17541377fd16606", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1272727273, "max_line_length": 87, "alphanum_fraction": 0.5769462885, "num_tokens": 805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3289806418366218}}
{"text": "\\section{Method}\nTo evaluate the effect of method compression we will explore how the combination of said methods effects two Information Retrieval tasks: Question Answering and Passage Retrieval. For each of the aforementioned tasks, we train tasks specific models built on bert-base-uncased. Given this baseline, we proceed to train variants with layers removed, with distillation, and with various degrees of unstructured pruning.\n\\subsection{Question Answering}\nQuestion answering is the goal of providing an answer to a query $q$ given some sort of context passage $p$. While there are abstractive methods because of difficulty in evaluation we will focus on extractive methods. Extractive systems predict two attributes for each query and context passage: $token_{start}$ and $token_{end}$ each of which denotes an token index in a context passage. As a result, the answer $a$ to a query $q$ is $a=\\{t_{token_{start}},...,t_{token_{end}}\\}$. \\\\\nThe \\textbf{S}tanford \\textbf{QU}estion \\textbf{A}nswering \\textbf{D}ataset 1.1 (SQUAD) dataset has become the standard for extractive question answering. Constructed out of 500 context passages derived from Wikipedia it contains 100,000+ question-answer where each question was written by a human annotator. While there have been updates to the dataset and additional question answering datasets the widespread use of SQUAD makes it a logical choice. \\\\\n\\subsection{Passage Re-Ranking}\nPassage ranking is a task which seeks to provide relevant short context passages for a given user query. These systems are commonly used as first stage retrievers for con question answering models. Since passages tend to have short context windows (under 512 tokens) transformer \\cite{Vaswani2017AttentionIA} have become efficient models. With the introduction of large scale ranking datasets like MSMARCO \\cite{Campos2016MSMA} and ODQA \\cite{Karpukhin2020DensePR} data hungry neural methods thrived. Passage Retrieval has three main formulations, sparse retrieval,  dense retrieval, and hybrid retrieval. Sparse retrieval leverages traditional retrieval mechanisms like BM25 to rank relevant candidates. Dense retrieval leverages encoders which map queries and passages to a shared vector space and ranks candidates using an Approximate Nearest Neighbor index. Hybrid retrieval focuses on some combination of dense retrieval and commonly includes a sparse 1st stage ranker followed by a dense re-ranker. Our work focuses on Hybrid Retrieval on the MSMARCO Passage Retrieval dataset.\\\\\nThe MSMARCO dataset was originally a 1,000,000+ sample question answering dataset where given 10 context passages $p$, a human judge selected the most relevant passage and wrote the answer. This dataset was re-purposed for passage ranking by creating a collection of all unique passages and evaluating candidates ranking ability. Since the corpus does not contain a definitive ranking to optimize models train using negative and positive examples of query-passage relevance. Since relevance labels are binary, we follow standard training procedures and treat the task as a binary classification task. Given a query $q$ and a passage $p$ a model predicts how likely this pair is to belong in the relevant class. \n\\subsection{Distillation}\nDistillation can be considered an effective method for label smoothing \\cite{Hinton2015DistillingTK}. Our focus is on self distillation where a teacher model is used to distill its learning into a student model. The teacher model is trained to convergence using cross entropy loss while the student is trained with a combination of the cross entropy loss and the Kullback–Leibler divergence between the student and teacher logits. Cross entropy is represented in equation \\ref{cross}, and the distillation loss is shown in equation \\ref{distill} where $sl$ are student logits, $tl$ are teacher logits, $\\lambda$ is a distillation hardness,and $KL$ is the Kullback–Leibler divergence. \n\\begin{equation}\nL_{crossentropy} = - \\sum_{i} ({y_i' \\log(y_i) + (1-y_i') \\log (1-y_i)})\n\\label{cross}\n\\end{equation}\n\\begin{equation}\nL_{distill} = (1- \\lambda )(L_{crossentropy}) + \\lambda (KL(sl, tl))\n\\label{distill}\n\\end{equation}\n\\subsection{Compression}\nOur work explores compression via unstructured pruning and layer removal. Language models like BERT are created by stacking identical layers of transformers and as a result compression can be achieved by simply removing these layers. We assign a mapping of layers to keep given target network depth based on experiments on most efficient methodologies and we find that for 1 layer networks we keep the first layer, for 3 we keep 1,6,12, for 6 we keep odd layers(1,3,5,7,9,11), for 9 we keep 1,3,4,5,7,8,9,10,12.\nUnstructured pruning is the removal of weights in a network until a desired amount of weights remain. This is commonly achieved by setting weights in a network to zero or by adding a mask on top of network weights. Our work focuses on the the gradual removal of weight which have the smallest magnitude (magnitude pruning). Network layers are pruned independently of each other meaning that all components in a network share sparsity levels. Pruning is implement using Neural Magic's \\footnote{https://neuralmagic.com/} sparseML library which introduces configurable sparsity in models with minimal overhead. \\\\\nLayer removal is perhaps the simplest method we study as it solely focus on removing layers from a language model. Language models like BERT are created by stacking identical layers of transformers and as a result compression can be achieved by simply removing these layers. ", "meta": {"hexsha": "6b5bf3f1bcda97faa09cb5713eefdaec9ee51ad3", "size": 5607, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "project/method.tex", "max_stars_repo_name": "spacemanidol/CS510IR", "max_stars_repo_head_hexsha": "84def6a199aafe9a845d3235585204f3a3c060e4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "project/method.tex", "max_issues_repo_name": "spacemanidol/CS510IR", "max_issues_repo_head_hexsha": "84def6a199aafe9a845d3235585204f3a3c060e4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project/method.tex", "max_forks_repo_name": "spacemanidol/CS510IR", "max_forks_repo_head_hexsha": "84def6a199aafe9a845d3235585204f3a3c060e4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 254.8636363636, "max_line_length": 1085, "alphanum_fraction": 0.8072052791, "num_tokens": 1237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521105, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3289596207350076}}
{"text": "\\subsection{Clustering Substitute Embeddings (${\\bf S}$)}\n\\label{sec:clustering-s}\n\nIn the previous section we group word types rather than word tokens by\nclustering the word embeddings.  In this section we remove this\none-tag-per-word restriction and group word tokens according to the\nembeddings of their substitutes.  We sample 64 random substitutes for\neach word token and input them to S-CODE as word (${\\bf W}$) --\nsubstitute (${\\bf S}$) pairs.  The resulting embeddings of the\nsubstitutes are clustered using the instance weighted k-means\nalgorithm.  The process yields 64 cluster-ids for each target word\ntoken's context.  The predicted category for the target word token is\nchosen to be the majority cluster-id among these 64 cluster-ids.  Ties\nfor the majority are broken randomly.  In effect, we are using random\nsubstitutes as features of the context, and we are clustering contexts\nof individual word tokens.  The many-to-one accuracy is \\wsymto\\ and\nthe V-measure is \\wsyvm\\ which is lower than word type clustering.\nHowever, we show that the performance on highly ambiguous words\nimprove significantly.\n\nIn order to explain the merit of the token based POS induction, we\nfirst define the gold-tag perplexity for word types as follows:\n\\begin{equation} \\label{eq:tag-perp}\nGP(w) = 2^{H(p_w)} = 2^{-\\sum_{t} p_w(t)log_2 p_w(t)}\n\\end{equation}\n\\noindent where $w$ is a word, $t$ is a tag, $p_w$ is the gold POS tag\ndistribution of the word type $w$ and $H(p_w)$ is the entropy of the\n$p_w$ distribution.  The gold-tag perplexity ($GP$) is used to determine\nthe POS ambiguity of a word type, relating how often a word type is\nassociated with different POS tags in the test corpus.  A $GP$ of 1\nfor a word type $w$ indicates $w$ is associated with same POS tag\nthroughout the test corpus, meaning the word type $w$'s POS is\nunambiguous.  A word with $N$ equally probable tags would have a $GP$\nof $N$.  As the $GP$ increases the ambiguity of a word type increases and\nthis poses a handicap for induction models that limits tag variety for\nthe word types.  To display the limitations, we split the test corpus\ninto two subsets: word types with $GP$ less than 1.75 and word types\nwith $GP$ equal to or greater than 1.75.  We performed \\mto\\ evaluation\non our induction output and obtained the induced-tag -- gold-tag\nmappings. Using the mappings obtained over the test corpus, we\nevaluated the accuracy in the two subsets.\n\n\\begin{table}[h]\n  \\small\n  \\centering\n  \\caption{The \\mto\\ accuracy of ${\\bf W}$, ${\\bf S}$ and ${\\bf W}\\oplus{\\bf S}$\n    based models on two subsets that consist of words with $GP$ smaller\n    and larger than 1.75, respectively.  The\n    percentage of each subset in the test data is reported in the title\n    bar.  The average $GP$ of each\n    clustering over the whole corpus is reported in the last column.  Each\n    score is an average of 10 random starts of our algorithm and the\n    standard error of each one is reported in parenthesis while\n    statistically the best \\mto\\ score of each column is reported in bold.  \n  }\n  \\label{tab:bins}\n  \\begin{tabular}{|c|c|c|c||c|}\n    \\hline\n    Model & \\specialcell{$GP < 1.75$\\\\$89\\%$} & \\specialcell{$GP \\ge 1.75$\\\\$11\\%$} & \\specialcell{$GP \\ge 1$ \\\\ $100\\%$} & Average $GP$ \\\\\n    \\hline\n    \\specialcell{Clustering ${\\bf W}$ embeddings\\\\(Type based)} & {\\bf .8054 (.0065)} & .4383 (.0104) & {\\bf \\wsmto} & 1.0 (.0)\\\\\n    \\hline\n    \\specialcell{Clustering ${\\bf W} \\oplus {\\bf S}$ embeddings\\\\(Sparse-token based)}& .7322 (.0079) & {\\bf .4671 (.0174)} & \\wsxymto & 1.3406 (.0057)\\\\ \n    \\hline\n    \\specialcell{Clustering ${\\bf S}$ embeddings\\\\(Token based)} & .6620 (.0051) & .4309 (.0093) & \\wsymto & 1.5318 (.0076)\\\\\n    \\hline  \n  \\end{tabular}\n\\end{table}\n\nThe performance of our algorithm clustering the ${\\bf S}$ embeddings\nis summarized in Table~\\ref{tab:bins}.  Due to the one-tag-per-word\nnature of POS induction, the type based model outperforms the token\nbased one on the unambiguous words. The token based model achieves\nstatistically comparable results with the type based model on the\nambiguous words.  Type based model can not handle words with ambiguity\nwhile the token based model can.  In order to take advantage of both\nmodels we apply our algorithm on concatenation of ${\\bf W}$ and ${\\bf\n  S}$ embeddings in the next section.\n\n\\subsection{Clustering Concatenation of Word and Context Embeddings (${\\bf W}\\oplus{\\bf S}$)}\n\\label{sec:clustering-concatenation}\n\nTwo models presented in earlier sections perform POS induction either\nby assuming (Section~\\ref{sec:clustering-w}) or discarding\n(Section~\\ref{sec:clustering-c}) the one-tag-per-word assumption.  In\nthis section we define a sparse-token based model which clusters the\nconcatenation of ${\\bf W}$ and ${\\bf S}$ embeddings.  This model not\nonly tends to put instances of a word type into the same cluster but\nalso performs token based clustering by incorporating the word type\nand context information together.\n\nSimilar to the previous models, we generate ${\\bf W}$ -- ${\\bf S}$\npairs as the input to S-CODE.  For each observed ${\\bf W}$ -- ${\\bf\n  S}$ pair in the S-CODE input, corresponding 25-dimensional $\\phi_w$\nand $\\psi_c$ embeddings are concatenated to create a 50-dimensional\nrepresentation.  We used the same experimental setting of the previous\nsection and predict the token clusters according to the majority\ncluster-id of the corresponding pairs.  The many-to-one accuracy of\nthis model is \\wsxymto\\ and the V-measure is \\wsxyvm\\ .\n\nTable~\\ref{tab:bins} presents the performance of the ${\\bf\n  W}\\oplus{\\bf S}$ based model over the subsets and it achieves\nstatistically better \\mto\\ than both of the ${\\bf W}$ and ${\\bf S}$\nbased models on ambiguous words.  Due to the bias towards to the\nsparse clustering, sparse-token based model statistically improves the\n\\mto\\ accuracy on unambiguous words compared to the ${\\bf S}$ based\nmodel but it still can not achieve the performance of the ${\\bf W}$\nbased model.  The ${\\bf W}\\oplus{\\bf S}$ based model constructs token\nbased clusters that tend to assign instances of a word type into the\nsame cluster which leads to a smaller average $GP$ than the ${\\bf S}$\nbased model as shown in Table~\\ref{tab:bins}.\n\n%% We don't really need this part\n%% \\subsubsection{Paradigmatic vs Syntagmatic Representations of Word Context}\n%% \\label{sec:bigram-token}\n%% In order to compare the token clustering performance of the\n%% paradigmatic and the syntagmatic context representations we use the\n%% same 4 models defined in Section~\\ref{sec:bigram-type}.  Following the\n%% previous section we concatenate the 25-dimensional $\\phi_x$ and\n%% $\\psi_y$ ($\\psi_{y_{1}}$ and $\\psi_{y_{2}}$ in the fourth model)\n%% embeddings of the corresponding observed pairs (tuples in the fourth\n%% model) and represent the first three models outputs with a\n%% 50-dimensional vectors (75-dimensional vectors in the fourth model).\n%% The resulting vectors are clustered using k-means algorithm with 128\n%% restarts.\n%% \\begin{table}[ht]\n%% \\centering\n%% \\small\n%% \\caption{Accuracies of the token based S-CODE models on the gold-tag\n%%   perplexity separated subsets.}\n%% \\begin{tabular}{|l|l|l|l|}\n%% \\hline\n%% Model & \\specialcell{$GP < 1.75$\\\\$89\\%$} & \\specialcell{$GP \\ge 1.75$\\\\$11\\%$} & \\specialcell{$GP \\ge 1.0$\\\\$100\\%$}\\\\\n%% \\hline\n%% $X$ (word) - $Y$ (left bigram) & .5950 (.0051) & .4783 (.0005) & .5821 (.0041)\\\\\n%% $X$ (word) - $Y$ (right bigram) & .6239 (.0049) & .3075 (.0153) & .5891 (.0046)\\\\\n%% $X$ (word) - $Y$ (left and right bigram concatenation) & .7523 (.0065) & .4492 (.0240) & .7190 (.0049)\\\\\n%% $X$ (word) - $Y_1$, $Y_2$ (left and right bigrams) & .6697 (.0065) & .4579 (.0052) & .6464 (.0051)\\\\\n%% $X$ (word) - $Y$ (random substitutes) & .7322 (.0079) & .4671 (.0174) & .7030 (.0073)\\\\\n%% \\hline\n%% \\end{tabular}\n%% \\label{tab:tokens}\n%% \\end{table}\n", "meta": {"hexsha": "0dc0708fcb9e614be9b26c0a1c93a579d9860448", "size": 7871, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "papers/cl2012/cl/token.tex", "max_stars_repo_name": "ai-ku/upos", "max_stars_repo_head_hexsha": "27d610318a0c777e2ca88b1ab2de5aa48f5a399f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2015-01-24T11:27:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-18T11:35:02.000Z", "max_issues_repo_path": "papers/cl2012/cl/token.tex", "max_issues_repo_name": "ai-ku/upos", "max_issues_repo_head_hexsha": "27d610318a0c777e2ca88b1ab2de5aa48f5a399f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "papers/cl2012/cl/token.tex", "max_forks_repo_name": "ai-ku/upos", "max_forks_repo_head_hexsha": "27d610318a0c777e2ca88b1ab2de5aa48f5a399f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-04-06T07:56:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-06T07:56:00.000Z", "avg_line_length": 54.6597222222, "max_line_length": 154, "alphanum_fraction": 0.7184601702, "num_tokens": 2280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.32895962073500756}}
{"text": "\\documentclass[journal]{IEEEtran}\n\n\\usepackage[pdfpagemode={UseOutlines},bookmarks=true,bookmarksopen=true,\n   bookmarksopenlevel=0,bookmarksnumbered=true,hypertexnames=false,\n   colorlinks,linkcolor={blue},citecolor={blue},urlcolor={blue},\n   pdfstartview={FitV},unicode,breaklinks=true]{hyperref}\n\n% *** MATH PACKAGES ***\n\\usepackage{amsmath,amssymb,bm}\n\n% *** GRAPHICS RELATED PACKAGES ***\n\\ifCLASSINFOpdf\n\t\\usepackage[pdftex]{graphicx}\n\t\\graphicspath{{images/}}\n\t% \\DeclareGraphicsExtensions{.pdf,.jpeg,.png}\n\\else\n\t\\usepackage[dvips]{graphicx}\n\t\\graphicspath{{images/}}\n\t% \\DeclareGraphicsExtensions{.eps}\n\\fi\n\n% *** SUBFIGURE PACKAGES ***\n\\ifCLASSOPTIONcompsoc\n  \\usepackage[caption=false,font=normalsize,labelfont=sf,textfont=sf]{subfig}\n\\else\n  \\usepackage[caption=false,font=footnotesize]{subfig}\n\\fi\n\n\\usepackage[pdftex,dvipsnames]{xcolor}\n\\usepackage{listings,xargs}\n\\usepackage[colorinlistoftodos,prependcaption,textsize=tiny]{todonotes}\n\n\\definecolor{dkgreen}{rgb}{0,0.6,0}\n\\definecolor{gray}{rgb}{0.5,0.5,0.5}\n\\definecolor{mauve}{rgb}{0.58,0,0.82}\n\\newcommand{\\fsize}{\\scriptsize}\n%\\newcommand{\\fsize}{\\tiny}\n\\newcommand{\\tabsize}{4}\n\n\\lstdefinelanguage{diff}{\n  morecomment=[f][\\color{blue}]{@@},\t\t% group identifier\n  morecomment=[f][\\color{red}]-,\t\t% deleted lines\n  morecomment=[f][\\color{dkgreen}]+,\t\t% added lines\n  morecomment=[f][\\color{magenta}]{---},\t% Diff header lines (must appear after +,-)\n  morecomment=[f][\\color{magenta}]{+++},\n}\n\n\\lstset{frame=tb,\n  language=C++,\n%  aboveskip=0mm,\n  belowskip=0mm,\n  showstringspaces=false,\n  columns=flexible,\n  basicstyle={\\fsize\\ttfamily},\n  numberstyle=\\fsize\\color{gray},\n%  numbers=left,\n  keywordstyle=\\color{blue},\n  commentstyle=\\color{dkgreen},\n  stringstyle=\\color{mauve},\n  breaklines=true,\n  breakatwhitespace=true,\n  tabsize=\\tabsize\n}\n\n% correct bad hyphenation here\n\\hyphenation{op-tical net-works semi-conduc-tor}\n\n\\newcommand{\\fref}[1]{\\figurename~\\ref{#1}}\n\\newcommand{\\eref}[1]{(\\ref{#1})}\n\\newcommand{\\tref}[1]{\\tablename~\\ref{#1}}\n\\newcommand{\\lref}[1]{LISTING~\\ref{#1}}\n\n\\newcommandx{\\improv}[2][1=]{\\todo[linecolor=Plum,backgroundcolor=Plum!25,bordercolor=Plum,#1]{#2}}\n\\newcommand{\\improvi}[1]{\\improv[inline]{#1}}\n\n\\begin{document}\n\n% paper title\n\\title{Acceleration of An SVM Classifier}\n\n% author names and IEEE memberships\n\\author{Group 6: Yubo~Zhi (yz4116), Jiayang~Sun (js11815)}\n\n% The paper headers\n\\markboth{ADSD Design Coursework}%\n{ADSD Design Coursework}\n\n% make the title area\n\\maketitle\n\n\\begin{abstract}\nThis course work aims to design and optimise a hardware Support Vector Machine (SVM) classifier on an embedded system using High Level Synthesis (HLS) language. The hardware implementation was optimised by various directives in HLS. In addition, the performance of software and hardware implementations were also assessed and compared in this excise.\n\\end{abstract}\n\n\\section{Introduction}\n\nDedicated hardware accelerators can perform a particular task faster then generalised software design. However, there are a few trade-offs associated with using hardware accelerators. In this exercise, an SVM classifier IP core was developed and optimised using Vivado HLS toolkit. The hardware platform used in this exercise is Zedboard, which include a Xilinx Zynq SoC FPGA. This FPGA has an ARM Cortex-A9 core together with the FPGA fabric. Hardware acceleration modules developed on the FPGA fabric can communicate with the ARM core through AXI interconnect. The procedure of designing and optimising the accelerator will be explained in details. Finally, the performance differences between hardware and software implementations were evaluated and discussed.\n\n\\hfill \\today\n\n\\section{IP core implementation}\n\n\\subsection{Overview}\n\n\\fref{fig:ip} shows the purposed SVM classifier accelerator architecture, designed according to \\eref{eq:cls}.\n\n\\begin{align}\n\tf(\\bm{x}) &= sgn \\left( bias + \\sum_{i=1}^{N_{SV}} \\alpha_i k(\\bm{{sv}_i}, \\bm{x}) \\right)\n\t\\label{eq:cls}\\\\\n\t\\text{where}~k(\\bm{x}, \\bm{y}) &= tanh(2 ( \\bm{x} \\cdot \\bm{y} ) )\n\\end{align}\n\n\\begin{figure}[t]\n\t\\centering\n\t\\includegraphics[width=0.6\\columnwidth]{IP}\n\t\\caption{Flow chart of purposed SVM classifier IP core}\n\t\\label{fig:ip}\n\\end{figure}\n\nAccording to the provided sample data, vectors have a width of 16 elements and there are 1050 support vectors. These numbers were replaced by macro definitions in the design, which can be easily adjusted to meet the properties of potentially other sample data.\n\n\\subsection{Dot product calculation}\n\nDot product between 2 vectors was calculated using the module designed previously in Part I.\n\n\n\\subsection{\\texttt{tanh} calculation}\n\nCOordinate Rotation DIgital Computer (CORDIC) \\cite{volder1959cordic} was used to calculate the \\texttt{tanh} function.\n\n\\subsubsection{CORDIC}\n\nCORDIC calculates trigonometric functions through vector rotation in 2-dimension space. It can be generalised to calculate \\texttt{sinh} and \\texttt{cosh} functions. The computations involved with CORDIC are simple integer addition, subtraction and shifting. This makes it suitable to use on a resource constrained embedded platform.\n\n\\subsubsection{Range and precision}\\label{subsubsec:range}\n\nThe precision of CORDIC can be improved by allowing more iterations, however, the input range of CORDIC is non-ideal. The CORDIC implementation used in this design has an input range of about $\\pm 1.10$ radians, but the sample dataset can give an input as large as $83.6$ radians.\n\nIn order to improve the performance of the \\texttt{tanh()}, the algorithm for optimising range detection for CORDIC based on the trigonometric rules were implemented. \n\n\\begin{align}\n\\sinh(\\theta + \\alpha) = \\cosh(\\theta)\\sinh(\\alpha) + \\sinh(\\theta)\\cosh(\\alpha)\n\\label{eq:tri}\\\\\n\\cosh(\\theta + \\alpha) = \\cosh(\\theta)\\cosh(\\alpha) + \\sinh(\\theta)\\sinh(\\alpha)\n\\end{align}\n\nAs equations \\eref{eq:tri} describe, the $\\theta$ can be used as a offset in order to increase the range of CORDIC.  In addition, declare a flag (\\texttt{neg})to store whether the input is negative. If it is negative set the flag to one and invert the value to positive. Furthermore, it is easy to observe that $tanh()$ is infinitely approximate to 1 when the angle lager than 6 \\texttt{rads}. As the result, when the input angle is larger than 6 \\texttt{rads}, the result will be directly equal to \\texttt{1}. Otherwise, the \\texttt{trigo\\_index} will be equal to the \\texttt{round(theta)}. Also, \\texttt{trigo\\_index} is the index of look up table(LUT) of \\texttt{lut\\_sinh[]} and \\texttt{lut\\_cosh[]}. These value is used as the offset $\\theta$ in the previous equation \\eref{eq:tri}. After that the rest part of the result will be calculated inside \\texttt{cordic()}. The results from \\texttt{cordic()} can be used as $\\alpha$ in equation \\eref{eq:tri}. Moreover, do the operation from trigonometric rules inside \\lref{lst:ext}, it will combine the results from CORDIC and offset in order to get the final output. Finally, if the \\texttt{neg} is one, invert the output to negative. \\cite{llamocca2007fixed}\n\n\\begin{lstlisting}[float,floatplacement=h,caption={Extending the range of CORDIC},captionpos=b,label=lst:ext]\n\tif (theta >= (mdata_t)6.0) {\n\t\tresult = 1.0;\n\t} else {\n\t\t// Trigo index to extend range\n\t\tint trigo_index = theta;\n\t\ttheta = theta - trigo_index;\n\t\t// Call Cordic function\n\t\tldata_t outcosh, outsinh;\n\t\tcordic(theta, &outcosh, &outsinh);\n\t\t// Trigo rules\n\t\tresult_sinh = (lut_sinh[trigo_index] * outcosh + lut_cosh[trigo_index] * outsinh);\n\t\tresult_cosh = (lut_cosh[trigo_index] * outcosh + lut_sinh[trigo_index] * outsinh);\n\t\tresult = result_sinh / result_cosh;\n\t\t*output = neg ? (ldata_t)-result : result;\n\t}\n\\end{lstlisting}\n\n\\subsection{SVM classifier}\n\nThe top-level SVM classifier was designed according to the flow chart \\fref{fig:ip}, as shown in \\lref{lst:clas}. It iterates through all support vectors, accumulates each result, finally output a boolean value according to the sign of accumulator after bias removal. The function \\texttt{k()} is the same as the k inside of equation \\eref{eq:cls}. It will calculate the dot product of two vectors, and apply \\texttt{tanh()} to the dot product in order to get the output. Finally, output will be checked whether it is negative. If it is positive, then output 0, otherwise output 1.\n\n\\begin{lstlisting}[float,floatplacement=h,caption={Top-level SVM classifier},captionpos=b,label=lst:clas]\nstatic void k(ldata_t u[N], ldata_t v[N], ldata_t *output)\n{\n\tmdata_t res;\n\tdotp(u, v, &res);\n\tres = res << 1u;\t// * 2\n\tfp_tanh(res, output);\n}\n\nvoid classifier(ldata_t x[N], int *output)\n{\n\thdata_t sum = 0;\n\tfor (int i = 0; i != ASIZE(alpha); i++) {\n\t\tldata_t res;\n\t\tk(SVs[i], x, &res);\n\t\tsum += res * alpha[i];\n\t}\n\t*output = sum + bias >= 0 ? 0 : 1;\n}\t\n\\end{lstlisting}\n\n\\subsection{Hardware verification}\n\n\\subsubsection{Test bench}\n\nThe design of SVM classifier was verified using C simulation test benches. The test bench iterates through all \\texttt{testData} vectors from the sample dataset and executes the classifier. The results from classifier were compared with \\texttt{testDataLabel} ground truths from the same sample dataset. Any difference will be recorded, and an overall error rate will be calculated at the end of simulation.\n\n\\subsubsection{Reference generation}\n\nA double precision example classifier implementation was available from the dataset. It produces 170 incorrect results from all 2000 ground truths values, corresponding to an error rate of $8.5 \\%$. The results including errors from the double precision were considered the reference output, therefore it can reflect any precision mismatches between the hardware implementation and software double precision implementation.\n\n\\subsection{Design evaluation}\n\nThe original implementation without any optimisation directives gives a maximum latency of 164877 clock cycles, as shown by \\tref{tbl:res_unopt}.\n\n\\begin{table}[ht]\n\t% increase table row spacing, adjust to taste\n\t\\renewcommand{\\arraystretch}{1.3}\n\t\\caption{Performance and resource usage of unoptimised version}\n\t\\label{tbl:res_unopt}\n\t\\centering\n\t% Some packages, such as MDW tools, offer better commands for making tables\n\t% than the plain LaTeX2e tabular which is used here.\n\t\\begin{tabular}{llll}\n\t\t\\hline\n\t\tItem\t\t\t& Unoptimised\t\\\\\n\t\t\\hline\n\t\tEstimated clock timing\t& $8.77$\t\\\\\n\t\tLatency\t\t\t& $164877$\t\\\\\n\t\tInterval\t\t& $164878$\t\\\\\n\t\tCo-simulation (average)\t& $203$\t\t\\\\\n\t\t\\hline\n\t\tBRAM\\_18K\t\t& $36~(12\\%)$\t\\\\\n\t\tDSP48E\t\t\t& $6~(2\\%)$\t\\\\\n\t\tFF\t\t\t& $1436~(1\\%)$\t\\\\\n\t\tLUT\t\t\t& $4086~(7\\%)$\t\\\\\n\t\t\\hline\n\t\\end{tabular}\n\\end{table}\n\nRunning RTL co-simulation using all 2000 test vectors with this order of delay interval between every test vector will be very time-consuming and not very useful. Therefore, only C simulation was used to ensure the correctness of the unoptimised design. RTL co-simulations were still used in later optimised design.\n\n\\section{Performance optimisation}\n\n\\subsection{Interface optimisation}\n\nThe interface for specified input vectors was optimised by reducing the interface width to a minimum and using the \\texttt{ARRAY\\_RESHAPE} directive. This directive can combine multiple elements of the input vector to a single 32-bit buffer, reduces the number of data transfers needed between the ARM core and the hardware accelerator.\n\n\\subsection{Resource usage optimisation}\n\nIn order to balanced the resources and accuracy, the bits of fix point number should be controlled by different bits of \\texttt{ap\\_fixed} type, as shown in \\lref{lst:data_t}. The number of fractional bits for all types is 12. The only changed part is integer part, in order to have enough range to represent different data. For example, \\texttt{hdata\\_t} it is used for the accumulation, final result, and bias. Multiple times experimental tests are set in order to get exact number of bits for integer part of different arrays due to different range of data.\n\n\\begin{lstlisting}[float,floatplacement=h,caption={Optimised data type},captionpos=b,label=lst:data_t]\ntypedef ap_fixed<22, 10> hdata_t;\ntypedef ap_fixed<19, 7> mdata_t;\ntypedef ap_fixed<16, 4> data_t;\ntypedef ap_fixed<16, 4> ldata_t;\n\\end{lstlisting}\n\n\\subsection{Throughput optimisation}\n\n\\subsubsection{Pipelining}\n\nBy using the technique of pipelining, the throughput can be greatly improved without significant increases of hardware resource usages. This can be achieved by applying the \\texttt{PIPELINE} directive. Vivado HLS will automatically insert pipeline stage registers in appropriate locations. An iteration interval of 1 clock cycles was achieved by pipelining. With the addition of a few pipeline stages filling the entire pipeline beforehand, the iteration of all 1050 support vectors now takes only over 1100 clock cycles.\n\n\\subsubsection{Loop unrolling}\n\nThere are also some small iteration loops in the design, such as the iteration inside dot product calculation which only iterates about 16 times. These loops can be unrolled to allow parallel computation of iterations, at the cost of more hardware resource usages. This can be achieved by applying the \\texttt{UNROLL} directive. Vivado HLS is capable of duplicating the loop body multiple times, and applying map-reduce techniques to resolve dependencies automatically. Together with pipelining, this can reduce the number of pipeline stages.\n\n\\subsubsection{Parallel chains}\n\nThe latency can be further reduced by executing multiple iterations of the support vector loop inside the main classifier function in parallel. Instead of sequentially iterates through all 1050 support vectors, ideally this parallel execution can reduce the latency by a factor of parallel chains.\nThe disadvantage of this method is, the hardware resource usage will be increased by the same factor in order to implement multiple parallel chains. A trade-off between throughput and resource usage is implied.\nThis parallel execution was done by unrolling the main loop while specifying unroll factor. All constant values such as support vectors and alpha implemented by ROMs need to be partitioned by the same factor to prevent Vivado duplicating the entire ROM for each parallel chain. The array partition was done by specifying the \\texttt{ARRAY\\_PARTITION} directive.\n\\lref{lst:opt_cla} shows the classifier function with optimisations applied.\n\n\\begin{lstlisting}[float,floatplacement=h,caption={Optimised classifier top-level function},captionpos=b,label=lst:opt_cla]\nvoid classifier(ldata_t x[N], int *output)\n{\n#pragma HLS ARRAY_RESHAPE variable=x cyclic factor=16 dim=1\n#pragma HLS ARRAY_PARTITION variable=SVs cyclic factor=10 dim=1\n#pragma HLS ARRAY_RESHAPE variable=SVs cyclic factor=16 dim=2\n#pragma HLS ARRAY_PARTITION variable=alpha cyclic factor=10 dim=1\n#pragma HLS INTERFACE s_axilite port=output\n#pragma HLS INTERFACE s_axilite port=return\n#pragma HLS INTERFACE s_axilite port=x\n\thdata_t sum = 0, sums[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};\n#pragma HLS ARRAY_PARTITION variable=sums cyclic factor=10 dim=1\nloop:\tfor (int i = 0; i != ASIZE(alpha); i++) {\n#pragma HLS PIPELINE\n#pragma HLS UNROLL factor=10\n\t\tldata_t res;\n\t\tk(SVs[i], x, &res);\n\t\tsums[i % 10] += res * alpha[i];\n\t}\n\tfor (int i = 0; i != 10; i++) {\n#pragma HLS PIPELINE\n#pragma HLS UNROLL\n\t\tsum += sums[i];\n\t}\n\t*output = sum + bias >= 0 ? 0 : 1;\n}\n\\end{lstlisting}\n\nThe \\texttt{ARRAY\\_PARTITION} directive is used for cutting the array into small parts in order to parallel the program. \\texttt{ARRAY\\_RESHAPE} also can separate the array, however, it will combine the array together after the progress so it is better to use inside the dot product in order to save resources. The main \\texttt{for} loop is optimised by \\texttt{PIPELINE} and \\texttt{UNTROLL} together. The factor of \\texttt{UNROLL} means the number of threads paralleled is 10. The maximum number of threads is ten because of the limitation of hard ware resources. \n\n\\subsection{Clock timing issue}\n\n\\begin{figure*}[!t]\n\t\\centering\n\t\\includegraphics[width=0.9\\textwidth]{bd}\n\t\\caption{Block diagram design of the entire system}\n\t\\label{fig:bd}\n\\end{figure*}\n\nAn unexpected issue occurred when applying unroll optimisations. The target clock period specified for this design is $10 ns$, but Vivado kept generating paths exceeding that clock constrain. By analysing the warning messages about the critical path, it is possible to resolve this issue by separating the arithmetic involved in the critical path, letting Vivado insert pipeline registers between them.\n\nAn example of resolving the timing issue is given by \\lref{lst:tim}. The original multiplication and accumulation operation was broken into 10 separate \\texttt{sums} variables as caches, partitioned to match the loop unroll factor. So that each parallel chain has a dedicated accumulator, summarised together in later stages. This removes the need for accumulate all 10 parallel chains in each iteration, hence reduces the length of the critical path.\n\n\\begin{lstlisting}[float,floatplacement=h,language=diff,caption={Code modification to resolve timing issue},captionpos=b,label=lst:tim]\n--- old/classifier.cpp\n+++ new/classifier.cpp\n@@ -62,12 +62,19 @@ void classifier(ldata_t x[N],\n #pragma HLS INTERFACE s_axilite port=output\n #pragma HLS INTERFACE s_axilite port=return\n     hdata_t sum = 0;\n+    hdata_t sums[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};\n+#pragma HLS ARRAY_PARTITION variable=sums cyclic factor=10 dim=1\n     for (int i = 0; i != ASIZE(alpha); i++) {\n #pragma HLS PIPELINE\n #pragma HLS UNROLL factor=10\n        ldata_t res;\n        k(SVs[i], x, &res);\n-       sum += res * alpha[i];\n+       sums[i % 10] += res * alpha[i];\n+    }\n+    for (int i = 0; i != 10; i++) {\n+#pragma HLS PIPELINE\n+#pragma HLS UNROLL\n+       sum += sums[i];\n     }\n     *output = sum + bias >= 0 ? 0 : 1;\n }\n\\end{lstlisting}\n\n\\subsection{New \\texttt{tanh()} reflection}\n\nAs the subsection \\ref{subsubsec:range} mentioned, there is a new technique to enhance the range and accuracy of the \\texttt{tanh()} fuction. However, it needs more resource and more instructions to complete, which means that it has higher latency than the previous CORDIC (133 cycles). However, the final latency of the design is shown in \\fref{fig:latency}, which is 150 cycle. Although there are 17 more cycles to complete the calculation, it gets as accurate as the double precision answer generated by software test bench. Because if using the previous method to complete \\texttt{tanh()} there are in total 169 errors, nonetheless it is different from the result come from the test bench which is 170 errors. As the result, the final implementation choose a more accuracy method in order to get enhanced classification.\n\n\\subsection{Design verification}\n\nCorrectness verifications by C simulations were done after every optimisations and code modifications, using the golden reference output generated from double precision implementation.\n\nAn unexpected discrepancy between Vivado HLS' C language and ISO C language standard (6.7.8.19 \\cite{iso1999iec}) was discovered. All array elements must be explicitly initialised in Vivado HLS for a defined behaviour, whereas in ISO C standard, uninitialised elements in a partially initialised array should have the value 0, the same as static storage initialisation. Hence the 10 zeros written in the initialisation of \\texttt{sums} in \\lref{lst:tim}.\n\nAfter applied all optimisations, the latency reduced significantly. RTL co-simulation was done at this stage before exporting as an IP core, to ensure the exported RTL implementation has the same functionality as the C implementation.\n\n\\subsection{Design evaluation}\n\n\\fref{fig:latency} shows the latency and varies aspects of hardware resources versus main loop unrolling factor.\n\n\\begin{figure}[ht]\n\t\\centering\n\t\\includegraphics[width=0.9\\columnwidth]{latency}\n\t\\caption{Latency and resource usage versus loop unrolling. unopt: Unoptimised version}\n\t\\label{fig:latency}\n\\end{figure}\n\nAs loop unroll factor increases, hardware resource usages increase linearly. However, the effect on latency decreases exponentially. The latency can be estimated by \\eref{eq:latency}.\n\n\\begin{equation}\n\t\\text{latency} = \\frac{N_{SV}}{\\text{factor}} + \\text{stages}\n\t\\label{eq:latency}\n\\end{equation}\n\n$N_{SV}$ equals the number of support vectors, which is 1050. Stages is the depth of pipeline, which is 44 in most cases, given by the loop latency value.\n\nThe equation shows, there is always some factors that can not be parallelised. Therefore the effect on performance will become more and more insignificant. Moreover, with a loop unroll factor of 10, DSP resource usage had already reached $95.45 \\%$, impossible for further adjustments.\n\n\n\\section{System implementation}\n\nAfter multiple optimisations, the improved implementation was packaged into Vivado as an IP core. The setup of Vivado and SDK were the same as in previous dot product exercise. \\fref{fig:bd} shows the block diagram design of the system on FPGA. \\fref{fig:sdk} describes an abstract structural overview of the testing program running on the ARM core, developed on the SDK.\n\n\\begin{figure}[t]\n\t\\centering\n\t\\includegraphics[width=0.3\\columnwidth]{sdk}\n\t\\caption{Overview of the testing program}\n\t\\label{fig:sdk}\n\\end{figure}\n\n\\section{System evaluation}\n\nUsing the global timer inside ARM core, it is possible to get cycle accurate profiling information.\n\n\\lref{lst:test_int} shows one example of the tests. This test aims to record the time consumption of different procedures of the whole system. The whole progress can be divided into three parts which include data transmission from ARM core to IP core, starting, and calculation. After running this program, the total time and the time for each part will be print in the terminal. \n\n\\begin{lstlisting}[float,floatplacement=h,caption={Code for recoding execution time for different procedures},captionpos=b,label=lst:test_int]\nunsigned int test_cls_hls_interrupt()\n{\n\tXTime tick[4], perf[3] = {0, 0, 0};\n\tunsigned int err = 0;\n\tint *label = &testDataLabel[0];\n\tint16_t *x = &testDataI[0][0];\n\tfor (size_t ix = ASIZE(testDataLabel); ix != 0; ix--) {\n\t\tXTime_GetTime(&tick[0]);\n\t\tXClassifier_Set_x_V(&cls, *(XClassifier_X_v *)x);\n\t\tXTime_GetTime(&tick[1]);\n\t\tXClassifier_Start(&cls);\n\t\tXTime_GetTime(&tick[2]);\n\t\tinterrupt_wait();\n\t\tXTime_GetTime(&tick[3]);\n\t\terr += (!XClassifier_Get_output_r(&cls)) != (!*label++);\n\t\tperf[0] += tick[1] - tick[0];\n\t\tperf[1] += tick[2] - tick[1];\n\t\tperf[2] += tick[3] - tick[2];\n\t\tx += N;\n\t}\n\tprintf(\"Data %llu, starting %llu, result %llu\\r\\n\", perf[0], perf[1], perf[2]);\n\treturn err;\n}\n\\end{lstlisting}\n\nAn example output of the test program was given by \\lref{lst:test_int_out}.\n\n\\begin{lstlisting}[float,floatplacement=h,language=,caption={Example output from testing program},captionpos=b,label=lst:test_int_out]\nBuild @ Mar 16 2017 22:15:28\nHLS peripheral is ready\nConverting data...\nConversion finished, 863684 ticks\n\nStarting tests...\n<double precision classifier> finished, 450697222 ticks, error count 170\n<fixed point classifier> finished, 200704648 ticks, error count 170\nData 1097219, starting 266571, result 1100144\n<HLS classifier by polling> finished, 2651697 ticks, error count 170\nData 1089646, starting 267273, result 1287449\n<HLS classifier by interrupt> finished, 2826942 ticks, error count 170\nSVM classifiers testing done.\n\\end{lstlisting}\n\n\\subsection{Performance and resource usage}\n\nThe support vector classifier was also implemented as software using double precision and fixed point CORDIC inside the ARM core, as a performance comparison to hardware implementation.\n\nThe performance data of software and notable hardware implementations are summarised in \\tref{tbl:throughput}. \\fref{fig:throughput} shows detailed hardware implementation throughputs and resource usage values. Both polling and interrupt methods for waiting results ready were implemented, however, only performance data from polling method was shown. The polling method gives slightly better overall performance values, probably due to some interfacing overheads of supporting interrupt.\n\n\\begin{table}[ht]\n\t% increase table row spacing, adjust to taste\n\t\\renewcommand{\\arraystretch}{1.3}\n\t\\caption{Performance and resource usages of system implementations}\n\t\\label{tbl:throughput}\n\t\\centering\n\t% Some packages, such as MDW tools, offer better commands for making tables\n\t% than the plain LaTeX2e tabular which is used here.\n\t\\begin{tabular}{llll}\n\t\t\\hline\n\t\tType\t\t\t& Throughput (k vectors / second)\t\\\\\n\t\t\\hline\n\t\tDouble precision\t& $2.96$\t\\\\\n\t\tFixed precision CORDIC\t& $6.64$\t\\\\\n\t\t\\hline\n\t\tUnoptimised hardware\t& $1.47$\t\\\\\n\t\tPipelined hardware\t& $152.17$\t\\\\\n\t\tUnrolled with factor 10\t& $541.18$\t\\\\\n\t\t\\hline\n\t\\end{tabular}\n\\end{table}\n\nIt can be seen from the table, the final optimised hardware implementation gives a speed-up of 182 times over the double precision and 80.5 times over the fixed precision software implementation, quite substantial. However, as the figure suggests, the throughput almost saturates as loop unroll factor increases above 9.\n\n\\begin{figure}[ht]\n\t\\centering\n\t\\includegraphics[width=0.9\\columnwidth]{throughput}\n\t\\caption{System throughput and resource usages versus loop unroll factor}\n\t\\label{fig:throughput}\n\\end{figure}\n\n\\fref{fig:time} shows a detailed breakdown of total time spent on each stage of interfacing the hardware SVM classifier. The time values shown on the figure were summarised for all 2000 test vectors.\n\n\\begin{figure}[ht]\n\t\\centering\n\t\\includegraphics[width=0.9\\columnwidth]{time}\n\t\\caption{Detailed time usage breakdown of interfacing hardware classifier}\n\t\\label{fig:time}\n\\end{figure}\n\nIt can be seen from the figure that transferring the 16 elements input vectors (\\texttt{tData}) and starting the classifier (\\texttt{tStart}) are very inefficient and unavoidable, taking almost the same time as actual computation (\\texttt{tResult}) in the final version where loop unroll factor is 10. These unavoidable overheads limit the maximum throughput achievable, result in the saturation.\n\n\\subsection{Reflection and Limitations}\n\nDifferent from previous dot product exercise, the SVM classifier hardware accelerator designed in this exercise improves the system throughput by a large factor. The benefits of using a massively paralleled hardware accelerator greatly overcome the overheads of interfacing the accelerator, based on the number of computations offloaded onto hardware each time. The processor core is also freed to do some other sequential computations while waiting for the results to be available, further increases system performance and efficiency.\n\n\\section{Conclusion}\n\nBy evaluating the performance data of software and hardware implementation of the same algorithm, the advantages, use case and limiting factors of using hardware accelerators were investigated. Although the computation speed of dedicated hardware accelerator can be faster than software implementation, overheads such as data transfer performance may limit the actual efficiency.\n\n% References section\n\\bibliographystyle{IEEEtran}\n\\bibliography{Reference}\n\n% that's all folks\n\\end{document}\n", "meta": {"hexsha": "c203fed777a8c50f5c0a0ae9de139310d94bffcb", "size": 27121, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/report.tex", "max_stars_repo_name": "zhiyb/SVM_hls", "max_stars_repo_head_hexsha": "e1223c8528eccd8d48e52c4614c8596db4c253da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-11-11T13:04:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-03T06:30:18.000Z", "max_issues_repo_path": "report/report.tex", "max_issues_repo_name": "zhiyb/SVM_hls", "max_issues_repo_head_hexsha": "e1223c8528eccd8d48e52c4614c8596db4c253da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/report.tex", "max_forks_repo_name": "zhiyb/SVM_hls", "max_forks_repo_head_hexsha": "e1223c8528eccd8d48e52c4614c8596db4c253da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-04-11T03:05:59.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-11T03:05:59.000Z", "avg_line_length": 54.9008097166, "max_line_length": 1210, "alphanum_fraction": 0.7688507061, "num_tokens": 7066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.32895962073500756}}
{"text": "\\documentclass{article}\r\n\r\n\\usepackage{amsmath,amssymb,amsthm,bm,graphicx,enumerate}\r\n\\usepackage{color}\r\n\r\n\\newcommand{\\be}{\\begin{equation}}\r\n\\newcommand{\\ee}{\\end{equation}}\r\n\r\n\r\n\\usepackage{geometry}\r\n \\geometry{\r\n a4paper,\r\n total={210mm,297mm},\r\n left=35mm,\r\n right=35mm,\r\n top=30mm,\r\n bottom=30mm,\r\n }\r\n \r\n % make a note\r\n\\newcommand{\\mynote}[1]{\\noindent \\textcolor{red} {{$\\blacktriangleright$\r\n   \\small{\\textsf{#1}} $\\blacktriangleleft$}}}\r\n\r\n\\title{Covid-19 epidemic control}\r\n\\author{Lauri Neuvonen, Matthias Wildemeersch}\r\n\\date{}\r\n\r\n\\begin{document}\r\n\r\n\\maketitle\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\section{Scenarios of interest}\r\n\\begin{enumerate}[-]\r\n\\item Limitations of the current model: (i) All asymptomatic become symptomatic (ii) recovered cannot turn susceptible again. These shortcomings can be resolved rather easily, but the corresponding transition rates are unknown and would require a sensitivity analysis. Possible extension in a later phase. \r\n\\item Distinction between lock-down and quarantine: Known infected people are put in quarantine with contact probability $\\lambda^Q$; people in lockdown have a contact probability $\\lambda^{LD}$; baseline contact probability is $\\lambda$; $\\lambda^Q < \\lambda^{LD}<\\lambda$.\r\n\\item Economic output\r\n\\be\r\nY = NQ + \\frac{\\lambda^{LD}}{\\lambda} LD + \\frac{\\lambda^Q}{\\lambda} Q \\, ,\r\n\\ee\r\nwith NQ, Q, and LD representing the number of people not in quarantine, in quarantine, and in lockdown. \r\n\\mynote{MW: need to think if we need another scaling factor in this formula} Loss in output can be calculated then as $Y_\\mathrm{loss} = Y_\\mathrm{baseline} - Y$. \r\n\\item number of objectives: (i) output or loss of output/working hours, (ii) number of deaths / number of hospitalized people, (iii) cost of the strategy. The loss of output could potentially be combined with the cost of the strategy. Another alternative is to look at the loss of working hours over the cost of the strategy. \r\n\\item scenarios of interest\r\n\\begin{enumerate}[i.]\r\n\\item generalized lock-down: Control strength of the lock-down by means of the parameter $\\lambda^{LD}$; testing only for people who start developing symptoms. Trade-off between economic cost vs health cost as a function of $\\lambda^{LD}$. Testing cost small. \r\n\\item Paul Romer scenario: massive population-scale testing without a generalized lock-down. Only people who test positive are put in quarantine; tradeoff related to sensitivity of diagnostic testing, where false negatives can freely circulate. Cost of strategy is high. This approach requires implementing repeated testing (see below). Testing cost high. \r\n\\item test-and-trace: No generalized lockdown. Only people who develop symptoms are tested, and if positive track the (on average) 10 (?sensitivity?) people with whom infected person was in contact. These 10 people should be distributed over different compartments; requires some tweaks in the model.  \\mynote{MW: to be worked out in the coming weeks} Test-and-trace cost moderately high. \r\n\\end{enumerate}\r\n\\item repeated testing: requires transition from NA* to NA, and transition from NA* to IA without star. The transition from NA* to NA happens on average in 7 days (sensitivity), so transition probability is $\\sigma = 1/7$. Fixes are marked in excel file in green. \r\n\\end{enumerate}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\section{Test and trace}\r\nIn this section, we present two methods that capture test-and-trace for compartmental models. Test-and-trace can easily be implemented in individual based models, which keep track of the history and individual contacts of each agent. In compartmental models, working with expected values and perfect mixing, test-and-trace is less straightforward. The aim of this section is to quantify how many undiagnosed people will get traced and quarantined. The test-and-trace can be implemented in two different ways, (i) people that are reached through contact tracing go into quarantine without diagnosis, or (ii) people that are traced get tested if the testing capacity is sufficient, and get quarantined based the test result. \r\n\r\n\\subsection{Method 1}\r\nIn the baseline model, the following compartments are affected by test-and-trace, NA-NQ (undiagnosed and diagnosed), IA-NQ undiagnosed, and FN-NQ. All said compartments transition to the quarantined state if they get traced. The transition probability from compartment $X$ to $Y$ can be written as\r\n\\be\r\n\\xi_{X \\to Y} = \\xi_\\mathrm{TT} f^X \\, , \r\n\\ee \r\nwhere $\\xi_\\mathrm{TT}$ is a generic test-and-trace efficiency parameter which is scaled by the fraction $f^X$ of the compartment with respect to the unquarantined population \r\n\\be\r\nf^X = \\frac{N_t^X}{N_t^\\mathrm{U}} = \\frac{N_t^X}{N_t^\\mathrm{NA-NQ-U}+N_t^\\mathrm{NA-NQ-D} + N_t^\\mathrm{IA-NQ-U} + N_t^\\mathrm{FN-NQ}} \\, .\r\n\\ee\r\nThis method has as pro that it is easy and that we consider the test-and-trace strength over a large interval. (The scaling parameter could even be disregarded) As disadvantage, the method is coarse and it does not take into account changes of tracing efforts over time as a result of the number of newly identified cases. Delays between testing and sequential tracing can be included by introducing additional compartments for the different phases in the incubation and symptomatic period. \r\n\r\n\r\n\\subsection{Method 2}\r\nWe aim to describe the efficiency of test-and-trace as a function of time, in other words, as a function of the trajectory of the epidemic. Assuming approach (i) of contact tracing where contact-traced people go into quarantine, we can define the transition probability between the non-quarantined compartment $X$ and the quarantined compartment $Y$ as $\\xi_{X \\to Y}^\\mathrm{CT}$, which can be expressed as\r\n\\begin{align}\r\n\\xi_{X \\to Y}^\\mathrm{CT}(t) &= P(\\mathrm{CT} \\, | \\,C_\\mathrm{T}) \\cdot P(C_\\mathrm{T}) \\nonumber \\\\\r\n& = \\eta \\cdot P(C_\\mathrm{T}) \\, ,\r\n\\end{align}\r\nwhere $\\eta$ represents the efficiency of the test-and-trace strategy, the probability that an individual get contact-traced conditioned on the event $C_\\mathrm{T}$ that this person was in contact with a diagnosed/tested person. The probability $P(C_\\mathrm{T})$ stands for the contact probability with a diagnozed person. We can further write\r\n\\begin{align}\r\n\\xi_{X \\to Y}^\\mathrm{CT}(t) &= \\eta \\cdot \\Big( P(C_\\mathrm{I}) \\cdot P(\\mathrm{IT}) + P(C_\\mathrm{N}) \\cdot P(\\mathrm{FP}) \\Big)\\nonumber \\\\\r\n&= \\eta \\cdot \\Big( \\lambda^X \\, \\pi_t^I \\cdot (\\pi_t^\\mathrm{IST} + \\pi_t^\\mathrm{IAT}) + \\lambda^X \\pi_t^N \\cdot \\pi_t^\\mathrm{FP} \\Big) \\, ,\r\n\\end{align} \r\nwhere $\\pi_t^I$ and $\\pi_t^N$ are the probabilities to meet an infected and non-infected individual conditioned on the meeting an individual, $\\lambda^X$ stands for the meeting rate and depends on the compartment $X$, $\\pi_t^\\mathrm{IST}$ and $\\pi_t^{IAT}$ represent the probability at time $t$ that an infected person is tested in the case of  symptomatic and asymptomatic individuals, and $\\pi_t^\\mathrm{FP}$ is the probability at time $t$ that a non-infected person falsely tested positive. \r\n\\begin{align}\r\n\\pi_t^\\mathrm{IST} & = \\frac{ \\delta (\\lambda^\\mathrm{Q} \\, M^\\mathrm{IA-Q}_{t-1} + \\lambda \\, M^\\mathrm{IA-NQ}_{t-1})}{M_t^\\mathrm{I}} \\nonumber \\\\\r\n\\pi_t^\\mathrm{IAT} &= \\frac{\\lambda \\, M_{t-1}^\\mathrm{IA-NQ}\\cdot \\tau \\,q^{sens} + \\lambda^\\mathrm{Q} \\, M_{t-1}^\\mathrm{IA-Q}\\cdot \\tau \\,q^{sens}}{M_t^\\mathrm{I}} \\nonumber \\\\\r\n\\pi_t^\\mathrm{FP} &= \\frac{\\lambda \\, M_{t-1}^\\mathrm{NA-NQ}\\cdot \\tau \\,(1-q^{spec}) + \\lambda^\\mathrm{Q} \\, M_{t-1}^\\mathrm{NA-Q}\\cdot \\tau \\,(1- q^{spec})}{M_t^\\mathrm{N}} \\, .\r\n\\end{align}\r\nIn order to avoid double counting, only the new infected symptomatic individuals at time $t$ are accounted in the formulation of the diagnosis probability $\\pi_t^\\mathrm{IST}$, which depends on multiple compartments at time $t-1$. The same idea is used in the formulation of $\\pi_t^\\mathrm{IAT}$ and $\\pi_t^\\mathrm{FP}$. We assume here that a symptomatic person is correctly diagnosed with probability 1. Note that by including test-and-trace into the model, the difference equations can now be written as $X_{t+1} = f(X_t, X_{t-1})$. \r\n\r\nThe quarantine rate $\\xi^{CT}$ would work for a situation, where the share of infected people  in those who have been contact traced would be the same that in total population. This is however not the case as both the risk of infection and chance of getting traced increases when you meet an infected person. Therefore, the transition rate $\\xi^{CT}$ must be split into two different rates, $\\xi^{CT, I}$ and $\\xi^{CT, N}$ for infected and non-infected compartments respectively. This can be modeled by adjusting the rates as $\\xi^{CT, I} = w^I \\xi^{CT}$ and $\\xi^{CT, N} = w^N \\xi^{CT}$ \r\n\r\n\r\n\\subsection{Lauri's new formulation}\r\nOne thing to note is that tracing probability and infection probability are affected by the same meeting. This means that the meeting rate should only be counted once for those who get traced, they don't neeed a separate meeting for getting traced after having met the person who gives (or doesn't) them the infection.\r\n\r\nThe following transition paths can now be defined from NA-NQ:\r\n\r\n\\textbf{Path 1: meeting a newly diagnosed infected person and getting infected and traced}: The chance of having met such a person on last time step, given a meeting, is\r\n\\begin{align}\r\n\t\\pi_t^\\mathrm{IST} &= \\frac{\\delta (\\lambda^\\mathrm{Q} \\, M^\\mathrm{IA-Q}_{t-1} + \\lambda \\, M^\\mathrm{IA-NQ}_{t-1})}{ M_t^\\mathrm{total}}\\nonumber  \\\\\r\n\t\\pi_t^\\mathrm{IAT} &= \\frac{\\lambda \\, M_{t-1}^\\mathrm{IA-NQ}\\cdot \\tau \\,q^{sens} + \\lambda^\\mathrm{Q} \\, M_{t-1}^\\mathrm{IA-Q}\\cdot (\\tau + \\tau^{CT}) \\,q^{sens}}{M_t^\\mathrm{total}} \\nonumber \\\\\r\n\t\\pi_t^\\mathrm{FP} &= \\frac{\\lambda \\, M_{t-1}^\\mathrm{NA-NQ}\\cdot \\tau \\,(1-q^{spec}) + \\lambda^\\mathrm{Q} \\, M_{t-1}^\\mathrm{NA-Q}\\cdot (\\tau + \\tau^{CT}) \\,(1- q^{spec})}{M_t^\\mathrm{total}} \r\n\\end{align}\r\nMeeting such a person (out of all meetings) can lead to infections  at conditional rate $\\rho^S$, giving an infection rate per random meeting:\r\n\\begin{equation}\r\n  \\alpha^{IS}_{t-1} = \\pi^{IST}_{t-1}\\rho^S + \\pi^{IAT}_{t-1}\\rho^A\r\n\\end{equation}\r\nAt this point these persons will move to IANQ compartment, at rate: \r\n\\begin{equation}\r\n\t\\lambda\\alpha^{IS}_{t-1} = \\lambda \\pi^{IST}_{t-1}\\rho^S\r\n\\end{equation} and the mass calculated below. This mass is the one infected mass that can be traced on the next time step. It is a 'compartment in compartment' within IA-NQ.\r\n\\begin{equation}\r\n\tM_t^{TI} = \\lambda\\alpha^{IS}_{t-1} M_{t-1}^{NA-NQ} = \\lambda (\\pi^{IST}_{t-1}\\rho^S + \\pi^{IAT}_{t-1}\\rho^A)M_{t-1}^{NA-NQ}\r\n\\end{equation}\r\nIn our model, this transition happens as part of the total transition from NA-NQ to IA-NQ, happening at rate\r\n\\begin{equation}\r\n\t\\lambda \\alpha_{t-1} = \\lambda \\pi_t^I[\\pi_t^{IS} \\rho^S + \\pi_t^{IA} \\rho^A]\r\n\\end{equation}\r\nfrom where they may proceed to IA-Q, based on the tracing efficiency $\\eta$. \r\n\r\nThis means that only part of the 'new arrivals' , and therefore also only part of the total mass in IA-NQ are subject to potential tracing efforts. Also, at this point the chance that they have already met an infected person is accounted for (because we know they have, that's how they got infected). Considering the share of these new members in the whole group of infected persons in IANQ leads to transition rate of:\r\n\\begin{equation}\r\n\\xi^{CT, I} = \\eta   M^\\mathrm{IT}_t  / M^\\mathrm{IA-NQ}_t\r\n\\end{equation}\r\nto IA-Q. \r\nFully extended, this becomes:\r\n\\begin{equation}\r\n\\xi^{CT, I} = \\eta \\cdot \\lambda \\rho^S   \\frac{\\lambda^{Q} (\\delta  + (\\tau + \\tau^{CT}) \\,q^{sens}) M^{IA-Q}_{t-2} + \\lambda(\\delta  + \\tau \\,q^{sens} ) M^{IA-NQ}_{t-2}) }{M_{t-1}^{total}} \\frac{M_{t-1}^{NA-NQ}}{M^{IA-NQ}_t} \r\n\\end{equation}\r\n\\\\\r\n\\\\\r\n\\textbf{Path 1: meeting a newly diagnosed infected person and getting traced but not infected}:\r\n\r\nThis process moves on similarly to the one above. Instead of infection chance, one only needs to consider the complement, and instead of target compartment IA-NQ, the compartment NA-NQ. This gives:\r\n\\begin{equation}\r\n\t\\xi^{CT, N} = \\eta  M^\\mathrm{NT}_t / M^\\mathrm{NA-NQ}_t\r\n\\end{equation}\r\n\r\nOne way to think about this would be to build pass-through compartments for 'traceable' IA-NQ and NA-NQ that would be kept separate from the 'main' IN-NQ and NA-NQ compartments. The only transitions to quarantine through test and trace would then be from these 'traceable' compartments with rate $\\eta$ (rest would go to main compartments because their 'traceability' would be lost). These both structures (with and without extra compartments) should lead to same transition \\emph{massess} to quarantine compartments. This might clarify this process but is perhaps not necessary.\r\n\r\n\\end{document}\r\n\r\n", "meta": {"hexsha": "bf648a982514c1ba65b6d58100ff36296f47f1bc", "size": 12800, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "documentation/Notes_MW_Covid19_202009_v4.tex", "max_stars_repo_name": "lauri-neuvonen/BHM_Covid_Testing", "max_stars_repo_head_hexsha": "24b2023280f225112b5376e7a44f117856e5cda2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "documentation/Notes_MW_Covid19_202009_v4.tex", "max_issues_repo_name": "lauri-neuvonen/BHM_Covid_Testing", "max_issues_repo_head_hexsha": "24b2023280f225112b5376e7a44f117856e5cda2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "documentation/Notes_MW_Covid19_202009_v4.tex", "max_forks_repo_name": "lauri-neuvonen/BHM_Covid_Testing", "max_forks_repo_head_hexsha": "24b2023280f225112b5376e7a44f117856e5cda2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 91.4285714286, "max_line_length": 724, "alphanum_fraction": 0.72359375, "num_tokens": 3547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.32895962073500756}}
{"text": "% ---------------------------------------------------------------------\n\\documentclass{article}\n\n\\usepackage{nberpreamble}\n\\usepackage{tikz}\n\\usetikzlibrary{\n  arrows,\n  patterns,\n  positioning,\n  calc,\n  fit,\n  intersections,\n  decorations.text,\n  decorations.markings,\n  decorations.pathmorphing,\n  shadows.blur\n}\n\n\\title{\\bfseries Notes on Parametric Power \\\\ for Clustered Randomization}\n\\author{\\sffamily Prepared by Mauricio C\\'aceres}\n\\date{\\sffamily \\today}\n\n\\renewcommand{\\displayoptions}{\n  \\maketitle\n  \\pagenumbering{arabic}\n}\n\n% ---------------------------------------------------------------------\n\\begin{document}\n\\displayoptions\n\n%----------------------------------------------------------------------\n\\section{MDE and Sample Size with a Cluster Design}\n\\label{sec:mde_and_sample_size_with_a_cluster_design}\n\nRecall \\Cref{eq:cluster_reg}; without controls we have\n\\begin{equation}\n\\label{eq:cluster_reg}\nY_{ij} = \\alpha + \\beta T_j + \\varepsilon_{ij},\n\\end{equation}\n\nwith $E (\\varepsilon_{ij} \\varepsilon_{i^\\prime j}) \\ne 0$ and the randomization $T_j$ at the cluster level ($j = 1, \\ldots, J$ clusters and $n_j$ individuals per cluster, $\\sum^{J}_{j = 1} n_j = N$). Following \\citet[p. 3921-2]{DufloGlennersterKremer2007}, suppose we can additively decompose the error term $\\varepsilon_{ij}$ as\n\\begin{equation}\n\\label{eq:cluster_reg_additive}\nY_{ij} = \\alpha + \\beta T_j + v_j + u_{ij},\n\\end{equation}\n\nwith $v_j \\stackrel{iid}{\\sim} (0, \\sigma_v^2), u_{ij} \\stackrel{iid}{\\sim} (0, \\sigma_u^2)$. \\citeauthor{DufloGlennersterKremer2007} provide a formula for the case when we have equal cluster sizes, but not the case when cluster sizes vary. Let us further assume $n_j \\stackrel{iid}{\\sim} (\\mu_n, \\sigma^2_n)$ and $\\rho \\equiv \\sigma_v^2 / \\sigma_\\varepsilon^2$ so that $E (\\varepsilon_{ij} \\varepsilon_{i^\\prime j}) = \\rho \\sigma_\\varepsilon^2$. For significance level $\\alpha$, power $\\kappa$, and proportion randomized $P$ we have\n\\begin{equation}\n  \\begin{array}{rl}\n    J   & = \\left(\\dfrac{t_{1 - \\kappa} + t_{\\alpha / 2}}{MDE}\\right)^2 \\dfrac{DE \\cdot \\sigma_\\varepsilon^2}{\\mu_n P(1 - P)}\n          = N_0 \\dfrac{DE}{\\mu_n} \\\\[9pt]\n    MDE & = \\Fabs{t_{1 - \\kappa} + t_{\\alpha / 2}} \\sqrt{\\dfrac{DE \\cdot \\sigma_\\varepsilon^2}{J \\mu_n P(1 - P)}}\n          = MDE_0 \\cdot \\sqrt{DE},\n  \\end{array}\n\\end{equation}\n\nwhere $MDE_0, N_0$ are the MDE and sample size required if the model used individual data and $DE$ is the so-called design effect (DE) or variance inflation factor (VIF):\n\\begin{equation}\n  DE =\n  \\begin{cases}\n    1 + \\rho (\\mu_n - 1) & \\sigma^2_n = 0 \\\\\n    1 + \\rho ((\\sigma^2_n / \\mu_n^2 + 1) \\mu_n - 1) & \\sigma^2_n > 0\n  \\end{cases}.\n\\end{equation}\n\nThe formulas above are a slight modification of equations (1) and (3) in \\citet{manatunga_sample_2001} to account for the case when the proportion randomized $P \\ne 0.5$. Note we're leveraging the fact that testing the significance of $\\widehat{\\beta}_{OLS}$ is equivalent to a paired $t$-test in this case. If $Y_{ij}$ is also binary then we need to adjust the variance. Equation (3) in \\citet{kong_sample_2003} gives\n\\begin{equation}\nJ = \\left(\\dfrac{t_{1 - \\kappa} + t_{\\alpha / 2}}{MDE}\\right)^2 \\dfrac{DE}{\\mu_n P(1 - P)}\n    \\Big(\\mu_T (1 - \\mu_T) (1 - P) + \\mu_C (1 - \\mu_C) P\\Big).\n\\end{equation}\n\nAgain, we modify the formula slightly so we account for $P \\ne 0.5$. Note that the variance of $\\widehat{\\beta}_{OLS}$ is\n\\begin{equation}\n\\begin{array}{rl}\n    V_{\\widehat{\\beta}} & = \\widehat{V}_T + \\widehat{V}_C \\\\\n    V_{k} & = \\dfrac{\\sum^{J}_{j = 1} n_{ik} \\left(1 + (n_{jk} - 1) \\rho\\right)}{\\left(\\sum^{J}_{j = 1} n_{jk}\\right)^2} \\sigma^2_{\\varepsilon}\n        \\quad\\quad k = T, C.\n  \\end{array}\n\\end{equation}\n\n$J V_{\\widehat{\\beta}} \\xrightarrow{P} \\sigma^2_{\\varepsilon} DE / \\mu_n$ as $J \\to \\infty$, meaning we can estimate $DE$ if the cluster sizes are known, given an estimate of $\\rho$. \\citeauthor{kong_sample_2003} suggests using an ANOVA-based estimate. Intuitively, from \\cref{eq:cluster_reg_additive} we see that a random effects model $Y_{ij} = \\alpha + v_j + u_{ij}$ is the true model under the null of $H_0: \\beta = 0$; then $\\rho = \\sigma_v^2 / (\\sigma_u^2 + \\sigma_v^2)$.\n\n%----------------------------------------------------------------------\n\\section{The Effect of Covariates}\n\\label{sec:the_effect_of_covariates}\n\nAdding controls has the effect of absorbing some of the variation in the error terms, thereby reducing $\\sigma_\\varepsilon^2$ and $\\rho$ and improving the precision of our estimates. The proportion of the unexplained variation absorbed by the covariates will be $R^2$, meaning we can adjust our parametric estimates to account for covariates by multiplying the variance by $1 - R^2$.\n\nFor the intra-cluster correlation $\\rho$ there is no trivial way of accounting for an arbitrary number of covariates---however, it is possible to make a simple adjustment for any one covariate. We follow the approach outlined in \\citet{stanish_estimation_1983} and adjust the ANOVA-based estimate for $\\rho$ to account for the lag of the outcome variable. Taking $MSB$ and $MSW$ as they are usually defined, we have\n\\begin{align*}\n  n & = \\dfrac{1}{J - 1} \\left[N - \\sum^{}_{j} n_j^2 / N \\right] \\\\\n  k & = \\dfrac{1}{J - 1} \\left[\\dfrac{\\sum^{}_{j} n_j^2 (\\overline{x}_j - \\overline{x})^2}{\\sum^{}_{j} \\sum^{}_{i} (x_{ij} - \\overline{x})^2}\\right] \\\\\n  \\widehat{\\rho} & = \\dfrac{MSB - MSW}{MSB + (n - k - 1) MSW},\n\\end{align*}\n\nwhere the unadjusted $\\widehat{\\rho}$ would simply use $k = 0$.\n\n%----------------------------------------------------------------------\n% \\clearpage\n\n\\bibliographystyle{apalike}\n\\bibliography{power.bib}\n\n%----------------------------------------------------------------------\n\\end{document}\n", "meta": {"hexsha": "51dd7e43d88ba7dc028728bcd45e44e4e1abb57b", "size": 5754, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "notes/power-clustered-notes.tex", "max_stars_repo_name": "mcaceresb/stata-power", "max_stars_repo_head_hexsha": "8d224e77b389bbb049158166f75e9c4bb10a088e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-06-20T21:43:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T15:43:37.000Z", "max_issues_repo_path": "notes/power-clustered-notes.tex", "max_issues_repo_name": "arlionn/stata-power", "max_issues_repo_head_hexsha": "8d224e77b389bbb049158166f75e9c4bb10a088e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notes/power-clustered-notes.tex", "max_forks_repo_name": "arlionn/stata-power", "max_forks_repo_head_hexsha": "8d224e77b389bbb049158166f75e9c4bb10a088e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-08-06T16:32:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-05T17:05:13.000Z", "avg_line_length": 53.7757009346, "max_line_length": 533, "alphanum_fraction": 0.6395550921, "num_tokens": 1844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.32895961728210554}}
{"text": "\\documentclass{article}\n\n\\usepackage[T1]{fontenc}\n\\usepackage[osf]{libertine}\n\\usepackage[scaled=0.8]{beramono}\n\\usepackage[margin=1.5in]{geometry}\n\\usepackage{url}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{nicefrac}\n\\usepackage{microtype}\n\\usepackage{subcaption}\n\\usepackage{bm}\n\n\\usepackage{sectsty}\n\\sectionfont{\\large}\n\\subsectionfont{\\normalsize}\n\n\\usepackage{titlesec}\n\\titlespacing{\\section}{0pt}{10pt plus 2pt minus 2pt}{0pt plus 2pt minus 0pt}\n\\titlespacing{\\subsection}{0pt}{5pt plus 2pt minus 2pt}{0pt plus 2pt minus 0pt}\n\n\\usepackage{pgfplots}\n\\pgfplotsset{\n  compat=newest,\n  plot coordinates/math parser=false,\n  tick label style={font=\\footnotesize, /pgf/number format/fixed},\n  label style={font=\\small},\n  legend style={font=\\small},\n  every axis/.append style={\n    tick align=outside,\n    clip mode=individual,\n    scaled ticks=false,\n    thick,\n    tick style={semithick, black}\n  }\n}\n\n\\pgfkeys{/pgf/number format/.cd, set thousands separator={\\,}}\n\n\\usepgfplotslibrary{external}\n\\tikzexternalize[prefix=tikz/]\n\n\\newlength\\figurewidth\n\\newlength\\figureheight\n\n\\setlength{\\figurewidth}{12cm}\n\\setlength{\\figureheight}{6cm}\n\n\\newlength\\squarefigurewidth\n\\newlength\\squarefigureheight\n\n\\setlength{\\squarefigurewidth}{4cm}\n\\setlength{\\squarefigureheight}{4cm}\n\n\\newlength\\smallsquarefigurewidth\n\\newlength\\smallsquarefigureheight\n\n\\setlength{\\smallsquarefigurewidth}{3.25cm}\n\\setlength{\\smallsquarefigureheight}{3.25cm}\n\n\\newlength\\smallfigurewidth\n\\newlength\\smallfigureheight\n\n\\setlength{\\smallfigurewidth}{6.25cm}\n\\setlength{\\smallfigureheight}{4cm}\n\n\\setlength{\\parindent}{0pt}\n\\setlength{\\parskip}{1ex}\n\n\\newcommand{\\acro}[1]{\\textsc{\\MakeLowercase{#1}}}\n\\newcommand{\\given}{\\mid}\n\\newcommand{\\mc}[1]{\\mathcal{#1}}\n\\newcommand{\\data}{\\mc{D}}\n\\newcommand{\\intd}[1]{\\,\\mathrm{d}{#1}}\n\\newcommand{\\inv}{^{-1}}\n\\newcommand{\\trans}{^\\top}\n\\newcommand{\\mat}[1]{\\bm{\\mathrm{#1}}}\n\\renewcommand{\\vec}[1]{\\bm{\\mathrm{#1}}}\n\\newcommand{\\R}{\\mathbb{R}}\n\\renewcommand{\\epsilon}{\\varepsilon}\n\n\\DeclareMathOperator{\\var}{var}\n\\DeclareMathOperator{\\cov}{cov}\n\\DeclareMathOperator{\\diag}{diag}\n\\DeclareMathOperator*{\\argmin}{arg\\,min}\n\\DeclareMathOperator*{\\argmax}{arg\\,max}\n\n\\begin{document}\n\n\\section*{The Kernel Trick}\n\nConsider the assumption of linear regression with an explicit feature\nexpansion $\\phi\\colon \\vec{x} \\mapsto \\phi(\\vec{x})$:\n\\begin{equation*}\n  y(\\vec{x}) = \\phi(\\vec{x})\\trans \\vec{w} + \\epsilon(\\vec{x}).\n\\end{equation*}\nGiven training data $\\data = \\bigl\\{ (\\vec{x}, y) \\bigr\\} = (\\mat{X},\n\\vec{y})$, recall we modeled the residuals $\\epsilon(\\vec{x})$ as\nzero-mean independent, identically distributed Gaussians with variance\n$\\sigma^2$:\n\\begin{equation*}\n  p(\\vec{\\epsilon})\n  =\n  \\mc{N}(\\vec{\\epsilon}; \\vec{0}, \\sigma^2 \\mat{I}),\n\\end{equation*}\ngiving rise to the following likelihood:\n\\begin{equation*}\n  p(\\vec{y} \\given \\mat{X}, \\vec{w}, \\sigma^2)\n  =\n  \\mc{N}(\\vec{y};\\mat{\\Phi}\\trans \\vec{w}, \\sigma^2 \\mat{I}).\n\\end{equation*}\nwhere we have defined $\\mat{\\Phi} = \\phi(\\mat{X})$.\n\nIn Bayesian linear regression, we further chose a multivariate\nGaussian prior for $\\vec{w}$:\n\\begin{equation*}\n  p(\\vec{w}) = \\mc{N}(\\vec{w}; \\vec{\\mu}, \\mat{\\Sigma}).\n\\end{equation*}\nFor simplicity, in the below we assume the prior mean for $\\vec{w}$ is\n$\\vec{\\mu} = \\vec{0}$.\n\nGiven these assumptions, we were able to derive the posterior\ndistribution of $\\vec{w}$ given the data $\\data$:\n\\begin{equation*}\n  p(\\vec{w} \\given \\data, \\sigma^2)\n  =\n  \\mc{N}(\\vec{w};\n  \\vec{\\mu}_{\\vec{w}\\given\\data},\n  \\mat{\\Sigma}_{\\vec{w}\\given\\data}\n  ),\n\\end{equation*}\nwhere\n\\begin{align*}\n  \\vec{\\mu}_{\\vec{w}\\given\\data}\n  &=\n  \\mat{\\Sigma}\n  \\mat{\\Phi}\\trans\n  (\\mat{\\Phi}\\mat{\\Sigma}\\mat{\\Phi}\\trans + \\sigma^2 \\mat{I})\\inv\n  \\vec{y};\n  \\\\\n  \\mat{\\Sigma}_{\\vec{w}\\given\\data}\n  &=\n  \\mat{\\Sigma}\n  -\n  \\mat{\\Sigma}\n  \\mat{\\Phi}\\trans\n  (\\mat{\\Phi}\\mat{\\Sigma}\\mat{\\Phi}\\trans + \\sigma^2 \\mat{I})\\inv\n  \\mat{\\Phi}\n  \\mat{\\Sigma},\n\\end{align*}\n\nIf we wish to use our model to predict the outputs $\\vec{y}_\\ast$\nassociated with a set of inputs $\\mat{X}_\\ast$, we previously derived:\n\\begin{equation*}\n  p(\\vec{y}_\\ast \\given \\mat{X}_\\ast, \\data, \\sigma^2)\n  =\n  \\mc{N}(\n  \\vec{y}_\\ast;\n  \\mat{\\Phi}_\\ast \\vec{\\mu}_{\\vec{w}\\given\\data},\n  \\mat{\\Phi}_\\ast \\mat{\\Sigma}_{\\vec{w}\\given\\data} \\mat{\\Phi}_\\ast\\trans + \\sigma^2 \\mat{I}).\n\\end{equation*}\nExamining the forms of these expressions, we see that the feature\nexpansion $\\phi$ always appears in one of the following expressions:\n\\begin{equation*}\n  \\mat{\\Phi}\\mat{\\Sigma}\\mat{\\Phi}\\trans\n  \\qquad\n  \\mat{\\Phi}_\\ast\\mat{\\Sigma}\\mat{\\Phi}\\trans\n  \\qquad\n  \\mat{\\Phi}\\mat{\\Sigma}\\mat{\\Phi}_\\ast\\trans\n  \\qquad\n  \\mat{\\Phi}_\\ast\\mat{\\Sigma}\\mat{\\Phi}_\\ast\\trans.\n\\end{equation*}\nThe entries of these matrices are always of the form\n$\\phi(\\vec{x})\\trans \\mat{\\Sigma} \\phi(\\vec{x}')$, where $\\vec{x}$ and\n$\\vec{x}'$ are two arbitrary inputs.  To simply our expressions, we\ndefine a function\n\\begin{equation*}\n  K(\\vec{x}, \\vec{x}')\n  =\n  \\phi(\\vec{x})\\trans\\mat{\\Sigma}\\phi(\\vec{x}').\n\\end{equation*}\nBecause $\\mat{\\Sigma}$ is positive definite, it has a ``matrix square\nroot,'' $\\mat{\\Sigma}^{\\nicefrac{1}{2}}$ with the property\n$(\\mat{\\Sigma}^{\\nicefrac{1}{2}})^2 = \\mat{\\Sigma}$.\\footnote{You can\n  prove this via the singular value decomposition (\\acro{SVD}): write\n  $\\mat{\\Sigma} = \\mat{U}\\mat{D}\\mat{U}\\trans$, where $\\mat{U}$ is\n  unitary and $\\mat{D}$ is diagonal with positive entries (because\n  $\\mat{\\Sigma}$ is positive definite), then define\n  $\\mat{\\Sigma}^{\\nicefrac{1}{2}} =\n  \\mat{U}\\mat{D}^{\\nicefrac{1}{2}}\\mat{U}\\trans$.} If we define the\nfunction $\\psi(\\vec{x}) =\n\\mat{\\Sigma}^{\\nicefrac{1}{2}}\\phi(\\vec{x})$, we can see that\n$K$ is simply an inner product:\n\\begin{equation*}\n  K(\\vec{x}, \\vec{x}')\n  =\n  \\psi(\\vec{x})\\trans \\psi(\\vec{x}').\n\\end{equation*}\nSuch a function $K$ is guaranteed to always produce positive-definite\nGram matrices (a \\emph{Gram matrix} is a square matrix of inner\nproducts between pairs of elements), and is called a \\emph{kernel} or\n\\emph{covariance function.}\n\nSometimes it is possible to specify a covariance function $K$ directly\nwithout ever computing the feature map explicitly.  With such a\nfunction, we could perform efficient Bayesian linear regression even\nwith a high-dimensional (or even infinite dimensional!) feature\nexpansion $\\phi$ \\emph{implicitly.} This idea of computing inner\nproducts in a feature space directly is called the \\emph{kernel trick}\nand has been the basis of a large amount of work in the\nmachine-learning community.  Effectively, any algorithm that operates\npurely in terms of inner products between input vectors can be made\nnonlinear by replacing normal inner products with the evaluation of a\nkernel.\n\nWith this definition, we may rewrite the predictive distribution\nfor $\\vec{y}_\\ast$:\n\\begin{equation*}\n  p(\\vec{y}_\\ast \\given \\mat{X}_\\ast, \\data, \\sigma^2)\n  =\n  \\mc{N}(\n  \\vec{y}_\\ast;\n  \\mu_{\\vec{y}_\\ast \\given \\data},\n  K_{\\vec{y}_\\ast \\given \\data}),\n\\end{equation*}\nwhere\n\\begin{align*}\n  \\vec{\\mu}_{\\vec{y}_\\ast\\given\\data}\n  &=\n  K(\\mat{X}_\\ast, \\mat{X})\n  \\bigl(K(\\mat{X}, \\mat{X}) + \\sigma^2 \\mat{I}\\bigr)\\inv\n  \\vec{y};\n  \\\\\n  K_{\\vec{y}_\\ast\\given\\data}\n  &=\n  K(\\vec{X}_\\ast, \\vec{X}_\\ast)\n  -\n  K(\\mat{X}_\\ast, \\mat{X})\n  \\bigl(K(\\mat{X}, \\mat{X}) + \\sigma^2 \\mat{I}\\bigr)\\inv\n  K(\\mat{X}, \\mat{X}_\\ast).\n\\end{align*}\n\n\\subsection*{Examples}\n\nPerhaps the most-commonly used kernel is the \\emph{squared exponential\n  covariance function:}\n\\begin{equation*}\n  K(\\vec{x}, \\vec{x}'; \\lambda, \\ell)\n  =\n  \\lambda^2\n  \\exp\\biggl(-\\frac{\\lVert \\vec{x} - \\vec{x}' \\rVert^2}{2\\ell^2}\\biggr),\n\\end{equation*}\nwhere $\\lambda$ and $\\ell$ are parameters.  The former is simply a\nmultiplicative scaling constant (you can think of this as an implicit\nscalar multiplication in the implicit feature map $\\phi$).  The latter\ntakes the role of a \\emph{length scale;} vectors separated by more\nthan a couple length scales will have a kernel value near zero.\n\nAn example of Bayesian linear regression using this kernel function is\nshown in Figure \\ref{kernel_example}.  We see that the use of this\nkernel function allowed us to achieve nice nonlinear regression\nwithout computing explicit basis expansions.  In fact, you can show\nthat the squared exponential kernel corresponds to an\n\\emph{infinite-dimensional} basis expansion, where we use a Gaussian\nbasis function \\emph{centered on every point.}  Such a feature\nexpansion would be impossible to use if we attempted to use explicit\nfeature computation.\n\n\\begin{figure}\n  \\centering\n  \\input{figures/kernel_example.tex}\n  \\caption{Example of Bayesian linear regression using the squared\n    exponential covariance function.  The true function is $f =\n    \\sin(x)$.  The kernel parameters are $\\lambda = \\ell = 1$, and the\n    noise variance was set to $\\sigma^2 = 0.1^2$.}\n  \\label{kernel_example}\n\\end{figure}\n\nSometimes thinking in terms of the kernel can help even when you have\nan explicit feature expansion on hand.  As an example, imagine our\ninputs are binary vectors of length $n$ (so each input $\\vec{x}$ is a\nsubset, a member of the power set $\\mc{P}(n)$).  One rather expensive\nfeature expansion we could try would be to enumerate every member of\n$\\mc{P}(n)$ and define $\\phi(\\vec{x})_i = \\vec{s}_i \\subset \\vec{x}$,\nwhere $\\vec{s}_i$ is the $i$th element of the power set.  So we\nrepresent our set $\\vec{x}$ by a feature vector of length $2^n$\nindicating every subset of $\\vec{x}$.  This is a very expensive\nfeature expansion, requiring exponential space to store for each\ninput.  However, if we take $\\mat{\\Sigma} = \\mat{I}$, we can compute\nthe dot product as:\n\\begin{equation}\n  K(\\vec{x}, \\vec{x}') = 2^{\\lvert x \\cap x' \\rvert},\n\\end{equation}\nwhich only requires time and space linear in $n$!\n\n\\end{document}\n", "meta": {"hexsha": "cf83ae482289d12c071f6e8366c4e094e50325dc", "size": 9832, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "lecture_notes/The Kernel Trick/notes.tex", "max_stars_repo_name": "yahoochen97/cse515t", "max_stars_repo_head_hexsha": "fd589d247b625f995c576e0cb66cc96ddbb4194f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lecture_notes/The Kernel Trick/notes.tex", "max_issues_repo_name": "yahoochen97/cse515t", "max_issues_repo_head_hexsha": "fd589d247b625f995c576e0cb66cc96ddbb4194f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lecture_notes/The Kernel Trick/notes.tex", "max_forks_repo_name": "yahoochen97/cse515t", "max_forks_repo_head_hexsha": "fd589d247b625f995c576e0cb66cc96ddbb4194f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9932885906, "max_line_length": 94, "alphanum_fraction": 0.6968063466, "num_tokens": 3207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.3289596138292035}}
{"text": "\\documentclass[10pt]{article}\n\\usepackage{algorithm}\n\\usepackage{algpseudocode}\n\\usepackage[T1]{fontenc}\n\\usepackage[utf8]{inputenc}\n\\usepackage{mathptmx}\n\\begin{document}\n\n\\title{Supplementary Information for ``A Theoretically-Sufficient And Computationally-Practical Technique For Deterministic Frequency Seriation''}\n\\author{Carl P. Lipo, Mark E. Madsen, and Robert C. Dunnell}\n\\date{March 2015}\n\\maketitle\n\n\n\n\\section*{S1 Text:  Pseudo-code representation of the IDSS algorithm}\n\n\n\\begin{algorithm}[h]\n\\caption{Algorithm for IDSS seriation}\\label{alg:idss}\n\\begin{algorithmic}[1]\n\n \\Require  Input file $I$ format:  \n \\State Tab-delimited text, column 0 contains assemblage name\n \\State Remaining columns contain type counts as integers\n\n\\Procedure{IDSS}{$I$}\n   \n   \\State Read input file $I$\n   \\State Calculate relative frequency of each type\n   \\State Calculate max frequency difference between assemblage pairs\n   \\State Create list of assemblages $A$\n    \n    \\ForAll{triplets of assemblages $T$}\n        \\If{using continuity threshold $t_c$}\n            \\If{max frequency difference $> t_c$ for pairs $\\in T$}\n            \\State Skip triplet\n            \\EndIf\n        \\EndIf\n\n        \\If{triplet $T$ is valid given unimodality for all types}\n            \\State Store triplet in candidate solutions $\\mathbf{C}$\n        \\EndIf\n\n        \n\n        \\State $R \\gets$ assemblages $\\notin \\mathbf{C}$  \n        \\Comment Remaining assemblages\n        \n\n        \\Repeat\n            \\ForAll{assemblages $ a \\in R$}\n                \\If{using continuity threshold $t_c$}\n                    \\If{max freq difference $> t_c$ for $a$ and all $\\mathbf{C}$}\n                        \\State Skip assemblage $a$ for this loop\n                    \\EndIf\n                \\EndIf\n                \n                \\If{assemblage $a$ + candidate solution $c \\in \\mathbf{C}$}\n                    \\State Replace $c$ in $\\mathbf{C}$ with $c+a$\n                    \\State Remove $a$ from $R$\n                    \\Comment Grow existing solutions\n                \\EndIf\n            \n            \\EndFor        \n            \n        \\Until{ $R = \\empty$ or loop repeats with no changes }\n\n            \\ForAll{candidate solutions $c \\in \\mathbf{C}$}\n                \\If{$c$ is strict subset of another solution in $\\mathbf{C}$}\n                    \\State Remove $c$ from $\\mathbf{C}$\n                \\EndIf\n            \\EndFor\n\n    \\EndFor\n    \\Comment $\\mathbf{C}$ now contains the set of solutions\n    \n    \\State Output $\\mathbf{C}$ in various formats\n    \n\n\\EndProcedure\n\\end{algorithmic}\n\\end{algorithm}\n\n\n\\end{document}\n", "meta": {"hexsha": "20e9e0ab8b2091f99091d945ec18ecfee0527b5a", "size": 2604, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/S1Text.tex", "max_stars_repo_name": "mmadsen/lipomadsen2015-idss-seriation-paper", "max_stars_repo_head_hexsha": "37791b7af3974c88ac089e42360644c8b00cead6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-05-06T03:51:43.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-20T15:57:30.000Z", "max_issues_repo_path": "paper/S1Text.tex", "max_issues_repo_name": "mmadsen/lipomadsen2015-idss-seriation-paper", "max_issues_repo_head_hexsha": "37791b7af3974c88ac089e42360644c8b00cead6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/S1Text.tex", "max_forks_repo_name": "mmadsen/lipomadsen2015-idss-seriation-paper", "max_forks_repo_head_hexsha": "37791b7af3974c88ac089e42360644c8b00cead6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9310344828, "max_line_length": 146, "alphanum_fraction": 0.5971582181, "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011686727232, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.32893012766862273}}
{"text": "\\chapter{Setting up the linear system}\n\\label{section:setup-linear-system}\n\\par\nOur typical user is interested in solving $A X = Y$,\nwhere $A$ is square, large and sparse,\nand $X$ and $Y$ are dense matrices with one or more columns.\n{\\bf SPOOLES} is a very large sophisticated library with \na commensurate learning curve to master its functionality.\nBut what is the bare minimum a user has to know to obtain a\nsolution to their linear system?\n\\begin{itemize}\n\\item\nThey need to construct an {\\tt InpMtx} object that holds\nthe entries of $A$. ({\\tt InpMtx} stands for \n{\\tt Inp}ut {\\tt m}a{\\tt t}ri{\\tt x},\nfor it is an easy to use object that one uses to input, \nassemble, sort and manipulate entries in a sparse matrix.)\n\\item\nThey need to construct a {\\tt DenseMtx} object that holds\nthe entries of $Y$.\n\\item\nThey need to construct a {\\tt DenseMtx} object to hold\nthe entries of $X$.\n\\end{itemize}\nThese two objects encapsulate the minimal interface to the \n{\\bf SPOOLES} library.\nthe application program needs to know how to construct\nthe {\\tt InpMtx} and {\\tt DenseMtx} objects, either directly inside\nan application program, or by reading in a custom matrix file.\nThis is what we now describe.\n\\par\n\\section{Constructing an {\\tt InpMtx} object}\n\\label{subsection:construct-InpMtx}\n\\par\nThe {\\tt InpMtx} object is more of an ``Input'' object \nthan a ``Matrix'' object.\nIt descended from an out-of-core assembly code that assembled and\nsorted entries of a sparse matrix.\nSimplicity and functionality are its goals, at some expense of \nefficiency in storage and computation.\n{\\it Note: all indices are zero-based as in C, not 1-based as in\nFORTRAN.}\n\\par\nThe {\\tt InpMtx} object is simplest understood as a ``bag'' of\ntriples $\\langle r(i,j),c(i,j),a_{i,j}\\rangle$, \nwhere $r()$ and $c()$ are some\nfunctions that define the first and second coordinates.\nEach {\\tt InpMtx} object has a ``coordinate type'', one of\n\\begin{itemize}\n\\item\n{\\tt INPMTX\\_BY\\_ROWS}, where $r(i,j) = i$, $c(i,j) = j$.\n\\item\n{\\tt INPMTX\\_BY\\_COLUMNS}, where $r(i,j) = j$, $c(i,j) = i$.\n\\item\n{\\tt INPMTX\\_BY\\_CHEVRONS}, \nwhere $r(i,j) = \\min(i,j)$, $c(i,j) = j - i$.\n\\end{itemize}\nRows and columns are self-explanatory, the first coordinate\n$r(i,j)$ is either the row or column of $a_{i,j}$.\nThe $j$-th ``chevron'' is composed of the diagonal entry $a_{j,j}$,\nentries in the $j$-th row of the upper triangle,\nand entries in the $j$-th column of the lower triangle.\nIt is the natural data structure for the assembly of the matrix\nentries into the ``fronts'' used to factor the matrix.\n\\par\n% ``Entries'' of the {\\tt InpMtx} object can be one of three types.\nThe {\\tt InpMtx} object can hold one of three types of entries as\n``indices only'' (no entries are present),\nreal entries, or complex entries.\nThe type is specified by the {\\tt inputMode}\nparameter to the {\\tt InpMtx\\_init()} method.\n\\begin{itemize}\n\\item\n{\\tt INPMTX\\_INDICES\\_ONLY} where the triples\n$langle r(i,j),c(i,j),-\\rangle$ are really only pairs,\ni.e., no numerical values are present.\nThis mode is useful for assembling graphs.\n\\item\n{\\tt SPOOLES\\_REAL} where $a_{i,j}$ is a real number,\na {\\tt double} value.\n\\item\n{\\tt SPOOLES\\_COMPLEX} where $a_{i,j}$ is a complex number,\nreally two consecutive {\\tt double} values.\n\\end{itemize}\n``Coodinate type'' and ``input mode'' (equivalently, the type of\nentries) are the two parameters that must be specified when\ninitializing an {\\tt InpMtx} object.\n\\begin{verbatim}\nInpMtx   *mtxA = InpMtx_new() ;\nInpMtx_init(mtxA, coordType, inputMode, 0, 0) ;\n\\end{verbatim}\nEvery object in the {\\bf SPOOLES} library is initialized\nvia an {\\tt {\\it ObjectName}\\_new()} method, which allocates space\nfor the object and sets its fields to default values.\nIf you wish to use an {\\it automatic} variable, then one must\nexplicitly set the default fields, as follows.\n\\begin{verbatim}\nInpMtx   mtxA ;\nInpMtx_setDefaultFields(&mtxA) ;\nInpMtx_init(&mtxA, coordType, inputMode, 0, 0) ;\n\\end{verbatim}\nOnly the coordinate type and input mode are necessary.\nThe fourth and fifth arguments are upper bounds on the number of\nentries and vectors for the object. (More on vectors in just a\nmoment.) The user does not need to know values for the number of\nentries or vectors, for the object resizes itself as necessary \nas information is placed into it.\n\\par\n``Vectors'' is one way that the entries can be stored.\nThere are actually three ways, specified by the \n{\\tt storageMode} field of the {\\tt InpMtx} object.\n\\begin{itemize}\n\\item\n{\\tt INPMTX\\_RAW\\_DATA}, where the pairs or triples are stored in\nunordered form.\n\\item\n{\\tt INPMTX\\_SORTED}, where the pairs or triples are stored in\nascending lexicographic order of the first two coordinates.\n\\item\n{\\tt INPMTX\\_BY\\_VECTORS}, where the pairs or triples are sorted\nand stored in vectors defined by their first coordinate.\n\\end{itemize}\nThe storage mode can be changed via a call to\n{\\tt InpMtx\\_changeStorageMode()}.\n\\par\nThe user does not really need to know about this \n``storage mode''. Fill the {\\tt InpMtx} object with data in any way\nat all (we will describe this shortly). \nThe wrapper method will check that the data is in the form it needs. \nIf is isn't, the object will be transformed as necessary.\nThe ``sort'' operation is really ``sort-and-compress'', the pairs\nor triples are sorted into ascending order, and then the list is\nscanned duplicates are ``merged'' together, i.e., if real or\ncomplex entries are present, they are added together.\n(This allows us to assemble finite element matrices.)\nThe knowledgeable user can change the storage mode as necessary,\nand thus avoiding expensive sorts when possible.\nFor example, after reading in the matrix data from the CSAR-Nastran \nfile,\nthe entries are already in sorted form, and the explicit sort\ncan be avoided.\n\\par\nNow let us see how we ``input'' information into the {\\tt InpMtx}\nobject.\nThere are several input methods, e.g., single entries, rows,\ncolumns, and submatrices, and each input method has three types of\ninput, e.g, indices only, real entries, or complex entries.\nHere are the prototypes below.\n\\begin{itemize}\n\\item Input methods for ``indices only'' mode.\n\\begin{verbatim}\nvoid InpMtx_inputEntry ( InpMtx *mtxA, int row, int col ) ;\nvoid InpMtx_inputRow ( InpMtx *mtxA, int row, int rowsize, int rowind[] ) ;\nvoid InpMtx_inputColumn ( InpMtx *mtxA, int col, int colsize, int colind[] ) ;\nvoid InpMtx_inputMatrix ( InpMtx *mtxA, int nrow, int ncol, int rowstride, \n                          int colstride, int rowind[], colind[] ) ;\n\\end{verbatim}\n\\item Input methods for real entries.\n\\begin{verbatim}\nvoid InpMtx_inputRealEntry ( InpMtx *mtxA, int row, int col, double value ) ;\nvoid InpMtx_inputRealRow ( InpMtx *mtxA, int row, int rowsize, \n                           int rowind[], double rowent[] ) ;\nvoid InpMtx_inputRealColumn ( InpMtx *mtxA, int col, int colsize, \n                              int colind[], double colent[] ) ;\nvoid InpMtx_inputRealMatrix ( InpMtx *mtxA, int nrow, int ncol, int rowstride, \n                    int colstride, int rowind[], colind[], double mtxent[] ) ;\n\\end{verbatim}\n\\item Input methods for complex entries.\n\\begin{verbatim}\nvoid InpMtx_inputComplexEntry ( InpMtx *mtxA, int row, int col, \n                                double real, double imag ) ;\nvoid InpMtx_inputComplexRow ( InpMtx *mtxA, int row, int rowsize, \n                               int rowind[], double rowent[] ) ;\nvoid InpMtx_inputComplexColumn ( InpMtx *mtxA, int col, int colsize, \n                                 int colind[], double colent[] ) ;\nvoid InpMtx_inputComplexMatrix ( InpMtx *mtxA, int nrow, int ncol, int rowstride, \n              int colstride, int rowind[], colind[], double mtxent[] ) ;\n\\end{verbatim}\n\\end{itemize}\nThe {\\tt rowind[]} row indices and {\\tt colind[]} column indices \nare precisely that. \nDon't worry about what coordinate type the {\\tt InpMtx} object has,\nthe translation from row and column indices into the particular\ncoordinate is done inside the input methods.\n\\par\nLet us look at a particular example, where we have a \n${\\tt n1} \\times {\\tt n2}$ grid and we want to have a\n$\\left \\lbrack \\begin{array}{ccc}\n   & -1 &    \\\\\n-1 &  4 & -1 \\\\\n   & -1 & \n\\end{array} \\right \\rbrack$ \n5-point operator at each grid point.\nNote, this matrix is symmetric, so we need input only the upper\ntriangle (or the lower triangle) of the matrix.\n\\begin{verbatim}\nmtxA = InpMtx_new() ;\nInpMtx_init(mtxA, INPMTX_BY_ROWS, SPOOLES_REAL, 0, 0) ;\nfor ( ii = 0 ; ii < n1 ; ii++ ) {\n   for ( jj = 0 ; jj < n2 ; jj++ ) {\n      ij = ii + jj*n1 ;\n      indices[0] = ij ;\n      entries[0] = 4.0 ;\n      count = 1 ;\n      if ( ii < n1 ) {\n         indices[count] = ij + 1 ;\n         entries[count] = -1.0 ;\n         count++ ;\n      }\n      if ( jj < n2 ) {\n         indices[count] = ij + n1 ;\n         entries[count] = -1.0 ;\n         count++ ;\n      }\n      InpMtx_inputRealRow(mtxA, ij, count, indices, entries) ;\n   }\n}\nInpMtx_changeStorageMode(mtxA, INPMTX_BY_VECTORS) ;\n\\end{verbatim}\nThe process begins by allocating an {\\tt InpMtx} object {\\tt mtxA}\nusing the {\\tt InpMtx\\_new()} method,\ninitializing it with the {\\tt InpMtx\\_init()} method, \nand filling it with matrix entries with the {\\tt\nInpMtx\\_inputRealRow()} method.\nThe last method, {\\tt InpMtx\\_changeStorageMode()},\n``assembles'' the data (not really necessary because the entries\nare disjoint, \n``sorts'' the data (again not necessary since the entries were\ninput in ascending order,\nand creates a vector structure inside the {\\tt InpMtx} object that\nallows easy access to each individual row.\n\\par\nWe could have input all the entries and treated it as a\nnonsymmetric matrix, but that would not be efficient with respect\nto storage or factorization cost.\nAlternatively, we could have input all the entries and called the \n{\\tt InpMtx\\_dropLowerTriangle()} method to drop the lower\ntriangular entries.\n\\par\n\\section{Constructing an {\\tt DenseMtx} object}\n\\label{subsection:construct-DenseMtx}\n\\par\nThe {\\tt DenseMtx} stores a real or complex dense matrix.\nIt is not just an array of numbers, it also has row indices and\ncolumn indices.\nThis allows it to exist in a distributed MPI environment where each\nprocessors has only a submatrix of the matrix.\nHere is how to initialize a {\\tt DenseMtx} object.\n\\begin{verbatim}\nint        type, rowid, colid, nrow, ncol, inc1, inc2 ;\nDenseMtx   *mtx = DenseMtx_new() ;\nDenseMtx_init(mtx, type, rowid, colid, nrow, ncol, inc1, inc2) ;\n\\end{verbatim}\n\\begin{itemize}\n\\item\nThe {\\tt type} is either {\\tt SPOOLES\\_REAL} \nor {\\tt SPOOLES\\_COMPLEX}.\n\\item\nThe {\\tt rowid} and {\\tt colid} values are used to identify a \n{\\tt DenseMtx} as a submatrix of a larger matrix.\nAny values are suitable.\n\\item\n{\\tt nrow} and {\\tt ncol} are the number of rows and columns in the\nmatrix, respectively.\n\\item\nThe entries of the matrix can be stored in either row major or\ncolumn major form.\nFor row major, use {\\tt inc1 = ncol} and {\\tt inc2 = 1}.\nFor column major, use {\\tt inc1 = 1} and {\\tt inc2 = nrow}.\nNote, all solve and matrix-matrix multiply methods require that the\n{\\tt DenseMtx} object be column major.\n\\end{itemize}\nFor example, here is the call to initialize a {\\tt DenseMtx} object \nto have real entries, 100 rows and 5 columns, entries column major.\n\\begin{verbatim}\nDenseMtx_init(mtx, SPOOLES_REAL, 0, 0, 100, 5, 1, 100) ;\n\\end{verbatim}\nDuring the initialization, \nthe row indices are set to $0, 1, \\dots, \\mathtt{nrow - 1}$\nand the column indices are set to $0, 1, \\dots, \\mathtt{ncol - 1}$.\nThe entries are {\\bf not} initialized.\nZero the entries with a call to {\\tt DenseMtx\\_zero()}.\n(This is crucial when loading a sparse right hand side into\nthe {\\tt DenseMtx} object.)\n\\par\nOnce we have the {\\tt DenseMtx} object initialized, we want to be\nable to access the row indices, the column indices and the entries.\nWe do this through instance methods.\n\\begin{verbatim}\nvoid DenseMtx_rowIndices ( DenseMtx *mtx, int *pnrow, int *prowind ) ;\nvoid DenseMtx_columnIndices ( DenseMtx *mtx, int *pncol, int *pcolind ) ;\ndouble * DenseMtx_entries ( DenseMtx *mtx ) ;\n\\end{verbatim}\nWe would use them as follows.\n\\begin{verbatim}\ndouble   *entries ;\nint      ncol, nrow, *colind, *rowind ;\n\nDenseMtx_rowIndices(mtx, &nrow, &rowind) ;\nDenseMtx_columnIndices(mtx, &ncol, &colind) ;\nentries = DenseMtx_entries(mtx) ;\n\\end{verbatim}\nWe can now fill the indices or the entries.\nThe location of the {\\tt (irow,jcol)} entry is found\nat {\\tt offset = irow*inc1 + jcol*inc2}.\nThe row and column increments can be found as follows.\n\\begin{verbatim}\nint inc1 = DenseMtx_rowIncrement(mtx) ;\nint inc2 = DenseMtx_columnIncrement(mtx) ;\n\\end{verbatim}\n\\par\nTo avoid dealing with row and column increments, \nwe can retrieve and set values of a particular entry.\n\\begin{verbatim}\ndouble   value, real, imag ;\nint      irow, jcol ;\n\nDenseMtx_realEntry(mtx, irow, jcol, &value) ;\nDenseMtx_complexEntry(mtx, irow, jcol, &real, &imag) ;\nDenseMtx_setRealEntry(mtx, irow, jcol, value + 10.) ;\nDenseMtx_setComplexEntry(mtx, irow, jcol, real + 1., imag + 2.) ;\n\\end{verbatim}\nAs a real example, consider the ${\\tt n1} \\times {\\tt n2}$ grid\nfrom the previous subsection, where we assembled a finite\ndifference matrix. \nAssume that the right hand side is zero except for points where\n{\\tt (n1-1,0:n2-1)}, where a unit load is applied.\nHere is the code to generate the {\\tt DenseMtx} object.\n\\begin{verbatim}\nmtxY = DenseMtx_new();\nDenseMtx_init(mtxY, SPOOLES_REAL, 0, 0, n1*n2, 1, 1, n1*n2) ;\nDenseMtx_zero(mtxY) ;\nii = n1 - 1 ;\nfor ( jj = 0 ; jj < n2 ; jj++ ) {\n   ij = ii + jj*n1 ;\n   DenseMtx_setRealEntry(mtxY, ij, 1, 1.0) ;\n}\n\\end{verbatim}\nDo not forget to zero the entries in {\\tt mtxY} before setting any\nentries.\n\\par\n\\section{IO for the {\\tt InpMtx} and {\\tt DenseMtx} objects}\n\\label{subsection:IO}\n\\par\nThe three driver programs that we describe in the next sections\nread $A$ and $Y$ from files and write $X$ to a file. \nSo the first thing we know is that the {\\tt InpMtx} and {\\tt\nDenseMtx} objects can read and write themselves from and to files.\nThis convention is supported by most of the objects in the \n{\\bf SPOOLES} library. \nIn fact, there is a common {\\it protocol} that is followed.\nLet us take a look at the common IO methods for the {\\tt InpMtx}.\n\\begin{itemize}\n\\item\n{\\tt int InpMtx\\_readFromFile ( InpMtx *obj, char *filename ) ;}\n\\item\n{\\tt int InpMtx\\_readFromFormattedFile ( InpMtx *obj, FILE *fp ) ;}\n\\item\n{\\tt int InpMtx\\_readFromBinaryFile ( InpMtx *obj, FILE *fp ) ;}\n\\item\n{\\tt int InpMtx\\_writeToFile ( InpMtx *obj, char *filename ) ;}\n\\item\n{\\tt int InpMtx\\_writeToFormattedFile ( InpMtx *obj, FILE *fp ) ;}\n\\item\n{\\tt int InpMtx\\_writeToBinaryFile ( InpMtx *obj, FILE *fp ) ;}\n\\item\n{\\tt int InpMtx\\_writeForHumanEye ( InpMtx *obj, FILE *fp ) ;}\n\\end{itemize}\nThere are corresponding methods for the {\\tt DenseMtx} object,\njust replace ``{\\tt Inp}'' by ``{\\tt Dense}'' in the above prototypes.\n\\par\nTwo methods take as input {\\tt char *} file names. Each object can\nbe archived in its own file with a particular suffix.\nFor example, {\\tt InpMtx} objects can be read from and written to\nfiles of the form {\\tt *.inpmtxf} for a formatted file and\n{\\tt *.inpmtxb} for a binary file.\nFor a {\\tt DenseMtx} object, the file names are\n{\\tt *.densemtxf} and {\\tt *.densemtxb}.\nThe {\\tt InpMtx\\_readFromFile()} method looks at the {\\tt filename}\nargument, and calls the binary or formatted read methods, depending on\nthe suffix of {\\tt filename}. \nA normal return code is {\\tt 1}.\nIf the suffix does not match either {\\tt *.inpmtxf} or {\\tt *.inpmtxb},\nan error message is printed and the return code is {\\tt 0}.\nSomething similar works for writing an {\\tt InpMtx} object to a\nfile using {\\tt InpMtx\\_writeToFile()}, except if {\\tt filename}'s\nsuffix does not match, the {\\tt InpMtx\\_writeForHumanEye()} method\nis called.\n\\par\nHere are three approaches to link $A$ and $Y$ from an application\ncode to the {\\tt InpMtx} and {\\tt DenseMtx} objects demanded by the\n{\\bf SPOOLES} application.\n\\begin{itemize}\n\\item\nAn application could take the simple approach of creating an {\\tt\nInpMtx} and {\\tt DenseMtx} object to hold $A$ and $Y$, write them\nto a file, and then call a totally separate code that functions\nmuch like our drivers, reading in $A$ and $Y$, computing $X$ and\nwriting $X$ to a file, which is then read in by the application code.\n\\item\nA second approach, one that was taken during the first integration \nof the {\\bf SPOOLES} library into CSAR-Nastran, was to have the\nCSAR-Nastran code generate two files for $A$ and $Y$ in CSAR-Nastran \nformat.\n(This way CSAR-Nastran did not need to know any of the {\\bf SPOOLES}\ninterface.)\nTwo custom routines were written to read in the entries of $A$ and \n$Y$ from the CSAR-Nastran files and construct {\\tt InpMtx} and {\\tt\nDenseMtx} objects.\nThe wrapper routines we describe in the next three chapters were\ncalled to solve for $X$ which was then written to a CSAR-Nastran file.\n\\item\nA third approach would be to generate the {\\tt InpMtx} and {\\tt\nDenseMtx} objects in the application program, and then call the\nwrapper methods to solve for $X$, i.e., no IO would be necessary.\n\\end{itemize}\n", "meta": {"hexsha": "10cbdc26e89f55d037b0f5983c1dc522832e100c", "size": 17163, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ccx_prool/SPOOLES.2.2/LinSol/doc/setup.tex", "max_stars_repo_name": "alleindrach/calculix-desktop", "max_stars_repo_head_hexsha": "2cb2c434b536eb668ff88bdf82538d22f4f0f711", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ccx_prool/SPOOLES.2.2/LinSol/doc/setup.tex", "max_issues_repo_name": "alleindrach/calculix-desktop", "max_issues_repo_head_hexsha": "2cb2c434b536eb668ff88bdf82538d22f4f0f711", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-09-21T17:03:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-25T16:08:31.000Z", "max_forks_repo_path": "ccx_prool/SPOOLES.2.2/LinSol/doc/setup.tex", "max_forks_repo_name": "alleindrach/calculix-desktop", "max_forks_repo_head_hexsha": "2cb2c434b536eb668ff88bdf82538d22f4f0f711", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-08-29T18:41:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-29T18:41:28.000Z", "avg_line_length": 41.1582733813, "max_line_length": 82, "alphanum_fraction": 0.7189885218, "num_tokens": 5080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3289301195342143}}
{"text": "\\section{Homogenization and the Two-Scale Approach}\n\\label{sec:61homogenization}\n\n\\minitoc{70mm}{4}\n\n\\noindent\nWe roughly follow the presentation given in\n\\multicite{%\n  Huebner14Mehrdimensionale,%\n  Valentin14Hierarchische,%\n  Valentin16Hierarchical%\n}.\nThe necessary notation is summarized in\n\\cref{tbl:glossaryTopologyOptimization}.\n\n\\begin{table}\n  \\setnumberoftableheaderrows{0}%\n  \\newcommand*{\\pnst}[1]{\\printnotationsymbol{#1}&\\printnotationtext{#1}}%\n  \\begin{tabular}{%\n    >{\\kern\\tabcolsep}=l<{\\kern-1.5mm}+l<{\\kern2.9mm}+l<{\\kern-1.5mm}+l%\n    <{\\kern2.9mm}+l<{\\kern-1.25mm}+l<{\\kern\\tabcolsep}%\n  }\n    \\toprulec\n    \\pnst{\\objdomain}&       \\pnst{\\force}&        \\pnst{\\densglobal}\\\\\n    \\pnst{\\dimobjdomain}&    \\pnst{\\displacement}& \\pnst{\\denscell}\\\\\n    $d$&\\#micro-cell param.& \\pnst{\\compliance}&   \\pnst{\\densub}\\\\\n    \\pnst{\\mcp}&             \\pnst{\\vol}&          \\pnst{\\etensor}\\\\\n    &&                       \\pnst{\\voldens}&      \\pnst{\\cholfactor}\\\\\n    \\bottomrulec\n  \\end{tabular}%\n  \\caption[Glossary for topology optimization]{%\n    Glossary of the notation for topology optimization.%\n  }%\n  \\label{tbl:glossaryTopologyOptimization}%\n\\end{table}\n\n\n\n\\subsection{Homogenization}\n\\label{sec:611homogenization}\n\n\\paragraph{Density function}\n\nLet $\\objdomain \\subset \\real^{\\dimobjdomain}$ be the object domain.%\n\\footnote{%\n  We use tildes to denote variables and quantities\n  that correspond to the object domain $\\objdomain$\n  (e.g., $\\tilde{\\*x}$ is a point in $\\objdomain$).\n  In contrast, variables without a tilde will correspond\n  to the sparse grid domain $\\clint{\\*0, \\*1} = \\clint{0, 1}^d$\n  (e.g., $\\gp{\\*l,\\*i} \\in \\clint{\\*0, \\*1}$ will be a sparse grid point).%\n}\nUsually, we assume $\\dimobjdomain = 2$ or $\\dimobjdomain = 3$,\nalthough the method can be generalized to\narbitrary dimensionalities $\\dimobjdomain \\in \\nat$.\nShapes and topologies are described by \\term{density functions}\n$\\densglobal\\colon \\objdomain \\to \\clint{0, 1}$.\nThe function values $\\densglobal(\\tilde{\\*x}) \\in \\clint{0, 1}$\ntell if $\\tilde{\\*x}$ is contained in the object (value of one) or\nnot (value of zero).\nThe \\term{homogenization} approach also allows values between\nzero and one, giving the physical density of the material in $\\tilde{\\*x}$.\n\n\\paragraph{Optimization of compliance values}\n\nFurthermore, for every density function $\\densglobal$,\nlet $\\compliance(\\densglobal)$ be an objective function value.\nIn our setting, which is shown in \\cref{fig:topoOptExample},\nwe exert a force $\\force$ on the object,\nmeasure the resulting deformation, and\ncompute the \\term{compliance} (i.e., the inverse of the stiffness) as\nthe objective function value~$\\compliance(\\densglobal)$:\n\\begin{equation}\n  \\compliance(\\densglobal)\n  = \\int_{\\objdomain} \\tr{\\force} \\displacement_{\\densglobal}(\\tilde{\\*x})\n  \\diff\\tilde{\\*x},\n\\end{equation}\nwhere the \\term{displacement function}\n$\\displacement_{\\densglobal}\\colon \\objdomain \\to \\real^{\\dimobjdomain}$\ndepends on the density \\cite{Huebner14Mehrdimensionale}.\nWe want to find the density function\nwith the minimal compliance value:\n\\begin{equation}\n  \\label{eq:topoOptProblemContinuous}\n  \\min_{\\densglobal}\\, \\compliance(\\densglobal).\n\\end{equation}\nIf we do not impose additional conditions,\nthen there are often uninteresting trivial solutions.\nFor example, choosing $\\densglobal :\\equiv 1$\n(i.e., filling the entire domain $\\objdomain$ with material)\nusually leads to the topology with the\nhighest stiffness and, thus, the smallest displacement and compliance value.\nTherefore, we introduce the following volume constraint:\n\\begin{equation}\n  \\frac{\\voldens{\\densglobal}{\\objdomain}}{\\vol{\\objdomain}} \\le \\densub,\\quad\n  \\voldens{\\densglobal}{\\objdomain}\n  \\ceq \\int_{\\objdomain} \\densglobal(\\tilde{\\*x}) \\diff\\tilde{\\*x},\\quad\n  \\vol{\\objdomain}\n  \\ceq \\voldens{1}{\\objdomain},\n\\end{equation}\nwhere $\\vol{\\objdomain} = \\int_{\\objdomain} 1 \\diff\\tilde{\\*x}$\nis the volume of the object domain and\n$\\densub \\in \\clint{0, 1}$ is an upper bound on the volume fraction.\n\n\\begin{SCfigure}\n  \\includegraphics{topoOptExample_1}%\n  \\caption[%\n    Example scenario for topology optimization%\n  ]{%\n    Example scenario for topology optimization.\n    An object \\emph{\\textcolor{hellblau}{(light blue)}}\n    is fixed on the left side\n    of the object domain $\\objdomain$\n    \\emph{\\textcolor{mittelblau!50}{(darker blue)}}\n    and deformed by a force $\\force$, resulting in a displaced object\n    \\emph{(dashed).}\n    The density function $\\densglobal(\\tilde{\\*x})$ is one inside the object\n    and zero outside.%\n  }%\n  \\label{fig:topoOptExample}%\n\\end{SCfigure}\n\n\n\n\\subsection{Two-Scale Approach}\n\\label{sec:612twoScale}\n\n\\paragraph{Discretization and two-scale approach}\n\nOf course, we cannot solve the problem \\eqref{eq:topoOptProblemContinuous}\nnumerically,\nas there are infinitely many density functions $\\densglobal$.\nFor simplicity, we assume that $\\objdomain$ is some hyper-rectangle\n$\\clint{\\tilde{\\*a}, \\tilde{\\*b}}\n= \\clint{\\tilde{a}_1, \\tilde{b}_1} \\times \\dotsb \\times\n\\clint{\\tilde{a}_{\\dimobjdomain}, \\tilde{b}_{\\dimobjdomain}}$;\nif it is not, we replace $\\objdomain$ with its bounding box.\nThe object domain $\\objdomain$ can then be split into\n$M_1 \\times \\dotsb \\times M_{\\dimobjdomain}$\nequally-sized and axis-aligned sub-hyper-rectangles,\nwhich we call \\term{macro-cells}\n(where $M_1, \\dotsc, M_{\\dimobjdomain} \\in \\nat$).\n\nIn the \\term{two-scale approach,}\nwe assume the material of the macro-cells to be\nrepetitions of infinitesimally small periodic structures\n(i.e., identical for each macro-cell),\ncalled \\term{micro-cells.}\nThese micro-cells have a specific shape, which is parameterized by\n$d$ \\term{micro-cell parameters} $x_1, \\dotsc, x_d$,\nnormalized to values in the unit interval $\\clint{0, 1}$.\nFor instance, in two dimensions,\nthis shape may be an axis-aligned cross\nwith thicknesses $x_1$ and $x_2$, as shown in \\cref{fig:twoScale}.\nThe choice of a suitable \\term{micro-cell model}\n(parametrization of the micro-cells)\ndepends on the optimization scenario and has to be done a priori.\n\n\\begin{figure}\n  \\includegraphics{twoScale_1}%\n  \\caption[%\n    Two-scale approach for topology optimization%\n  ]{%\n    Two-scale approach to discretize the homogenized topology\n    optimization problem in two dimensions ($\\dimobjdomain = 2$).\n    \\emph{Left:} The object domain $\\objdomain$ is\n    subdivided into $M_1 \\times M_2$ macro-cells,\n    each with its own density \\emph{(gray squares).}\n    \\emph{Center:} Every macro-cell is the repetition of infinitesimally small\n    periodic micro-cells.\n    \\emph{Right:} The shape of the structure in every micro-cell is\n    described by a micro-cell model with $d$ parameters $x_1, \\dotsc, x_d$.\n    Here, the micro-cell model is a cross with two parameters\n    that represent the thickness of each crossbar.%\n  }%\n  \\label{fig:twoScale}%\n\\end{figure}\n\n\\paragraph{Elasticity tensors}\n\nNote that while the shape of all micro-cells in one macro-cell is identical,\nthe micro-cell parameters corresponding to different macro-cells differ\nin general.\nThis enables varying densities in different regions of $\\objdomain$.\nWe denote the micro-cell parameters corresponding to the $q$-th macro-cell\nwith $\\mcp{q} = (\\mcpentry{1}{q}, \\dotsc, \\mcpentry{d}{q}) \\in\n\\clint{\\*0, \\*1} = \\clint{0, 1}^d$,\nwhere $q = 1, \\dotsc, M$ and\n$M \\ceq M_1 \\dotsm M_{\\dimobjdomain}$ is the number of macro-cells.\nWith linear elasticity,\none can compute so-called \\term{elasticity tensors} $\\etensor^{(q)}$,\nwhich encode information about the material properties\nof the different macro-cells.\nThe elasticity tensors can be written as symmetric matrices\nin $\\real^{3 \\times 3}$ (for $\\dimobjdomain = 2$) or\nin $\\real^{6 \\times 6}$ (for $\\dimobjdomain = 3$).%\n\\footnote{%\n  In general, the elasticity tensor is a fourth-order tensor in\n  $\\real^{\\dimobjdomain \\times \\dimobjdomain \\times \\dimobjdomain \\times \\dimobjdomain}$.\n  One can reduce the size of the tensor by exploiting various symmetries\n  \\cite{Huebner14Mehrdimensionale}\n  to obtain $6$ or $21$ stiffness coefficients\n  in two or three dimensions, respectively.\n  These coefficients can then be expressed as a symmetric matrix.%\n}\nTo simplify the following considerations,\nwe assume that $\\dimobjdomain = 3$, i.e.,\n$\\etensor^{(q)} \\in \\real^{6 \\times 6}$.\nThe elasticity tensors are usually computed as the solution of a \\fem problem\n\\term{(micro-problem).}\nOnce all $\\etensor^{(q)}$ are known,\nwe can compute the compliance value\nby solving another \\fem problem \\term{(macro-problem),}\nsee \\cite{Allaire04Topology} and \\cite{Huebner14Mehrdimensionale}.\n\n\\vspace{-0.5em}\n\n\\paragraph{Discretized optimization problem}\n\nThe new optimization problem emerging from the\ntwo-scale discretization process has the form\n\\begin{subequations}\n  \\label{eq:topoOptProblemDiscrete}\n  \\setlength{\\belowdisplayskip}{5pt}%\n  \\begin{gather}\n    \\min J(\\mcp{1}, \\dotsc, \\mcp{M}),\\quad\n    \\mcp{1}, \\dotsc, \\mcp{M} \\in \\clint{\\*0, \\*1}\n    \\quad\\text{s.t.}\\quad\n    \\densmean(\\mcp{1}, \\dotsc, \\mcp{M}) \\le \\densub,\\\\\n    \\densmean(\\mcp{1}, \\dotsc, \\mcp{M})\n    \\ceq \\frac{1}{M} \\sum_{q=1}^M \\denscell^{(q)}(\\mcp{q}).\n  \\end{gather}\n\\end{subequations}\nHere, $\\denscell^{(q)}(\\mcp{q}) \\in \\clint{0, 1}$ is the\ndensity of the $q$-th macro-cell with micro-cell parameter $\\mcp{q}$\n(i.e., the fraction of material volume of one micro-cell\nwith respect to its total volume)\nand $\\densmean(\\mcp{1}, \\dotsc, \\mcp{M}) \\in \\clint{0, 1}$\nis the resulting total mean density.\nThis discretized optimization problem can now be implemented and\nsolved numerically.\n", "meta": {"hexsha": "9bad9b88d3856591c494cc10ff669af14e44b8ac", "size": 9593, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/document/61homogenization.tex", "max_stars_repo_name": "valentjn/thesis-arxiv", "max_stars_repo_head_hexsha": "ae30179e67cd6a7813385e140b609546fd65b897", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-10-12T09:28:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T21:07:17.000Z", "max_issues_repo_path": "tex/document/61homogenization.tex", "max_issues_repo_name": "valentjn/thesis-arxiv", "max_issues_repo_head_hexsha": "ae30179e67cd6a7813385e140b609546fd65b897", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/document/61homogenization.tex", "max_forks_repo_name": "valentjn/thesis-arxiv", "max_forks_repo_head_hexsha": "ae30179e67cd6a7813385e140b609546fd65b897", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6404958678, "max_line_length": 89, "alphanum_fraction": 0.7201084124, "num_tokens": 2944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.32893011953421425}}
{"text": "%\n% personal commentary:\n%        DRAFT DRAFT DRAFT\n%        - KFALL\n% RNG section reviewed and revised 11-Sep-98, johnh.\n%\n% RNG section revised 28-Aug-02 by Tim Buchheim to include material\n% from Michelle Weigle which describes the new implementation of RNG\n\n\\chapter{Mathematical Support}\n\\label{chap:math}\n\nThe simulator includes a small collection of mathematical\nfunctions used to implement random variate generation and integration.\nThis area of the simulator is currently undergoing some\nchanges.\n\nThe procedures and functions described in this chapter can be found in\n\\nsf{tools/rng.\\{cc, h\\}},\n\\nsf{tools/random.\\{cc, h\\}},\n\\nsf{tools/ranvar.\\{cc, h\\}},\n\\nsf{tools/pareto.\\{cc, h\\}},\n\\nsf{tools/expoo.\\{cc, h\\}},\n\\nsf{tools/integrator.\\{cc, h\\}}, and\n\\nsf{tcl/lib/ns-random.tcl}.\n\n\n\\section{Random Number Generation}\n\\label{sec:random}\n\nThe RNG class contains an implementation of the combined multiple\nrecursive generator MRG32k3a proposed by L'Ecuyer\n\\cite{lecuyer99}. The C++ code was adapted from \\cite{lecuyer01}.\nThis replaces the previous implementation of \\code{RNG}, which used\nthe minimal standard multiplicative linear congruential generator of\nPark and Miller~\\cite{Park88:Random}.  The newer (MRG32k3a) \\code{RNG} is\nused in ns versions 2.1b9 and later.\n\nThe MRG32k3a generator provides $1.8$x$10^{19}$ independent\nstreams of random numbers, each of which consists of\n$2.3$x$10^{15}$ substreams. Each substream has a period\n(\\emph{i.e.}, the number of random numbers before overlap) of\n$7.6$x$10^{22}$. The period of the entire generator is\n$3.1$x$10^{57}$. Figure \\ref{streams} provides a graphical idea of\nhow the streams and substreams fit together.\n\\begin{figure}[ht]\n\\centering\n\\includegraphics[angle=270,width=6 in]{rng-streams.eps}\n\\caption{Overall arrangement of streams and substreams.\n\\cite{lecuyer01}} \\label{streams}\n\\end{figure}\n\nA default RNG ({\\tt defaultRNG}), created at simulator initialization\ntime, is provided. If multiple random variables are used in a\nsimulation, each random variable should use a separate RNG object.\nWhen a new RNG object is created, it is automatically seeded to\nthe beginning of the next independent stream of random numbers.\nUsed in this manner, the implementation allows for a maximum of\n$1.8$x$10^{19}$ random variables.\n\nOften, multiple independent replications of a simulation are\nneeded (\\emph{i.e.}, to perform statistical analysis given\nmultiple runs with fixed parameters).  For each replication, a\ndifferent substream should be used to ensure that the random\nnumber streams are independent. (This process is given as an OTcl\nexample later.) This implementation allows for a maximum of\n$2.3$x$10^{15}$ independent replications. Each random variable in\na single replication can produce up to $7.6$x$10^{22}$ random\nnumbers before overlapping.\n\n{\\bf Note:} Only the most common functions are described here. For\nmore information, see \\cite{lecuyer01} and the source code found\nin {\\tt tools/rng.h} and {\\tt tools/rng.cc}.  For a comparison of this RNG to\nthe more common LCG16807 RNG (and why LCG16807 is not a good RNG), \nsee \\cite{lecuyer-wsc}.\n\\subsection{Seeding The RNG}\nDue to the nature of the RNG and its implementation, it is not\nnecessary to set a seed (the default is 12345).  If you wish to\nchange the seed, functions are available. You should only set the\nseed of the default RNG.  Any other RNGs you create are\nautomatically seeded such that they produce independent streams.\nThe range of valid seeds is 1 to {\\tt MAXINT}.\n\nTo get non-deterministic behavior, set the seed of the default RNG\nto 0.  This will set the seed based on the current time of day and\na counter.  {\\bf This method should not be used to set seeds for\nindependent replications.}  There is no guarantee that the streams\nproduced by two random seeds will not overlap.  The only way to\nguarantee that two streams do not overlap is to use the substream\ncapability provided by the RNG implementation.\n\n\\subsubsection{Example}\n\\begin{verbatim}\n # Usage: ns rng-test.tcl [replication number]\n\n if {$argc > 1} {\n    puts \"Usage: ns rng-test.tcl \\[replication number\\]\"\n    exit\n }\n set run 1\n if {$argc == 1} {\n    set run [lindex $argv 0]\n }\n if {$run < 1} {\n    set run 1\n }\n\n # seed the default RNG\n global defaultRNG\n $defaultRNG seed 9999\n\n # create the RNGs and set them to the correct substream\n set arrivalRNG [new RNG]\n set sizeRNG [new RNG]\n for {set j 1} {$j < $run} {incr j} {\n    $arrivalRNG next-substream\n    $sizeRNG next-substream\n }\n\n # arrival_ is a exponential random variable describing the time\n # between consecutive packet arrivals\n set arrival_ [new RandomVariable/Exponential]\n $arrival_ set avg_ 5\n $arrival_ use-rng $arrivalRNG\n\n # size_ is a uniform random variable describing packet sizes\n set size_ [new RandomVariable/Uniform]\n $size_ set min_ 100\n $size_ set max_ 5000\n $size_ use-rng $sizeRNG\n\n # print the first 5 arrival times and sizes\n for {set j 0} {$j < 5} {incr j} {\n    puts [format \"%-8.3f  %-4d\" [$arrival_ value] \\\n            [expr round([$size_ value])]]\n }\n\\end{verbatim}\n\n\\subsubsection{Output}\n\n\\begin{verbatim}\n % ns rng-test.tcl 1\n 6.358     4783\n 5.828     1732\n 1.469     2188\n 0.732     3076\n 4.002     626\n\n % ns rng-test.tcl 5\n 0.691     1187\n 0.204     4924\n 8.849     857\n 2.111     4505\n 3.200     1143\n\\end{verbatim}\n\n\\subsection{OTcl Support}\n\n\\subsubsection{Commands}\n\nThe following commands on the RNG class can be accessed from OTcl\nand are found in {\\tt tools/rng.cc}:\n\\begin{description}\n    \\item[{\\tt seed $n$}] -- seed the RNG to $n$, if $n == 0$, the seed\n    is set according to the current time and a counter\n    \\item[{\\tt next-random}] -- return the next random number\n    \\item[{\\tt seed}] -- return the current value of the seed\n    \\item[{\\tt next-substream}] -- advance to the next substream\n    \\item[{\\tt reset-start-substream}] -- reset the stream to the beginning\n    of the current substream\n    \\item[{\\tt normal $avg$ $std$}] -- return a number sampled from a normal\n    distribution with the given average and standard deviation\n    \\item[{\\tt lognormal $avg$ $std$}] -- return a number sampled from a\n      lognormal distribution with the given average and standard deviation\n\\end{description}\n\nThe following commands on the RNG class can be accessed from OTcl\nand are found in {\\tt tcl/lib/ns-random.tcl}:\n\\begin{description}\n    \\item[{\\tt exponential $mu$}] -- return a number sampled from an\n      exponential distribution with mean $mu$ \n    \\item[{\\tt uniform $min$ $max$}] -- return an integer sampled from a\n    uniform distribution on [$min$, $max$]\n    \\item[{\\tt integer $k$}] -- return an integer sampled from a uniform\n    distribution on [0, $k$-1]\n\\end{description}\n\n\\subsubsection{Example}\n\n\\begin{verbatim}\n # Usage: ns rng-test2.tcl [replication number]\n\n if {$argc > 1} {\n    puts \"Usage: ns rng-test2.tcl \\[replication number\\]\"\n    exit\n }\n set run 1\n if {$argc == 1} {\n    set run [lindex $argv 0]\n }\n if {$run < 1} {\n    set run 1\n }\n\n # the default RNG is seeded with 12345\n\n # create the RNGs and set them to the correct substream\n set arrivalRNG [new RNG]\n set sizeRNG [new RNG]\n for {set j 1} {$j < $run} {incr j} {\n    $arrivalRNG next-substream\n    $sizeRNG next-substream\n }\n\n # print the first 5 arrival times and sizes\n for {set j 0} {$j < 5} {incr j} {\n    puts [format \"%-8.3f  %-4d\" [$arrivalRNG lognormal 5 0.1] \\\n            [expr round([$sizeRNG normal 5000 100])]]\n }\n\\end{verbatim}\n\n\\subsubsection{Output}\n\n\\begin{verbatim}\n % ns rng-test2.tcl 1\n 142.776   5038\n 174.365   5024\n 147.160   4984\n 169.693   4981\n 187.972   4982\n\n % ns rng-test2.tcl 5\n 160.993   4907\n 119.895   4956\n 149.468   5131\n 137.678   4985\n 158.936   4871\n\\end{verbatim}\n\n\\subsection{C++ Support}\n\n\\subsubsection{Member Functions}\nThe random number generator is implemented by the RNG class and is\ndefined in {\\tt tools/rng.h}.\n\n{\\bf Note:} The Random class in {\\tt tools/random.h} is an older\ninterface to the standard random number stream.\n\nMember functions provide the following operations:\n\n\\begin{description}\n    \\item[{\\tt void set\\_seed (long seed)}] -- set the seed of the RNG, if\n    $seed == 0$, the seed is set according to the current time and a\n    counter\n    \\item[{\\tt long seed (void)}] -- return the current seed\n    \\item[{\\tt long next (void)}] -- return the next random number as an\n    integer on [0, {\\tt MAXINT}]\n    \\item[{\\tt double next\\_double (void)}] -- return the next random number\n    on [0, 1]\n    \\item[{\\tt void reset\\_start\\_substream (void)}] -- reset the stream\n    to the beginning of the current substream\n    \\item[{\\tt void reset\\_next\\_substream (void)}] -- advance to the next\n    substream\n    \\item[{\\tt int uniform (int k)}] -- return an integer sampled from a\n      uniform distribution on [0, k-1]\n    \\item[{\\tt double uniform (double r)}] -- return a number sampled from a\n      uniform distribution on [0, r]\n    \\item[{\\tt double uniform (double a, double b)}] -- return a number\n      sampled from a uniform distribution on [a, b]\n    \\item[{\\tt double exponential (void)}] -- return a number sampled from an\n    exponential distribution with mean 1.0\n    \\item[{\\tt double exponential (double k)}] -- return a number sampled from\n      an exponential distribution with mean k \n    \\item[{\\tt double normal (double avg, double std)}] -- return a number\n      sampled from a normal distribution with the given average and standard \n    deviation\n    \\item[{\\tt double lognormal (double avg, double std)}] -- return a number\n      sampled from a lognormal distribution with the given average and\n      standard deviation\n\\end{description}\n\n\\subsubsection{Example}\n\n\\begin{verbatim}\n /* create new RNGs */\n RNG arrival (23456);\n RNG size;\n\n /* set the RNGs to the appropriate substream */\n for (int i = 1; i < 3; i++) {\n   arrival.reset_next_substream();\n   size.reset_next_substream();\n }\n\n /* print the first 5 arrival times and sizes */\n for (int j = 0; j < 5; j++) {\n   printf (\"%-8.3f  %-4d\\n\", arrival.lognormal(5, 0.1),\n             int(size.normal(500, 10)));\n }\n\\end{verbatim}\n\n\\subsubsection{Output}\n\\begin{verbatim}\n 161.826   506\n 160.591   503\n 157.145   509\n 137.715   507\n 118.573   496\n\\end{verbatim}\n\n\n\n\n\n\\section{Random Variables}\n\\label{sec:ranvar}\n\nThe \\clsref{RandomVariable}{../ns-2/ranvar.h}\nprovides a thin layer of functionality on top\nof the base random number generator and the default random number stream.\nIt is defined in \\nsf{ranvar.h}:\n\n\\begin{program}\n  class RandomVariable : public TclObject \\{\n  public:\n        virtual double value() = 0;\n        int command(int argc, const char*const* argv);\n        RandomVariable();\n  protected:\n        RNG* rng_;\n  \\};\n\\end{program}\n\nClasses derived from this abstract class implement specific\ndistributions.  Each distribution is parameterized with the values of\nappropriate parameters.  The value method is used to return a value\nfrom the distribution.  \n\nThe currently defined distributions, and their associated parameters are:\n\n\\begin{tabular}{rl}\n\\clsref{UniformRandomVariable}{tools/ranvar.h} & \\code{min_}, \\code{max_} \\\\\n\\clsref{ExponentialRandomVariable}{tools/ranvar.h} & \\code{avg_} \\\\\n\\clsref{ParetoRandomVariable}{tools/ranvar.h} & \\code{avg_}, \\code{shape_}\\\\\n\\clsref{ParetoIIRandomVariable}{tools/ranvar.h} & \\code{avg_}, \\code{shape_}\\\\\n\\clsref{ConstantRandomVariable}{tools/ranvar.h} & \\code{val_}\\\\\n\\clsref{HyperExponentialRandomVariable}{tools/ranvar.h} & \\code{avg_}, \\code{cov_}\\\\\n\\clsref{NormalRandomVariable}{tools/ranvar.h} & \\code{avg_}, \\code{std_}\\\\\n\\clsref{LogNormalRandomVariable}{tools/ranvar.h} & \\code{avg_}, \\code{std_}\\\\\n\\end{tabular}\n\nThe RandomVariable class is available in OTcl.  For instance, to\ncreate a random variable that generates number uniformly on [10, 20]:\n\\begin{program}\n        set u [new RandomVariable/Uniform]\n        $u set min_ 10\n        $u set max_ 20\n        $u value\n\\end{program}\nBy default, RandomVariable objects use the default random number\ngenerator described in the previous section.  The use-rng method can\nbe used to associate a RandomVariable with a non-default RNG:\n\\begin{program}\n        set rng [new RNG]\n        $rng seed 0\n\n        set e [new RandomVariable/Exponential]\n        $e use-rng $rng\n\\end{program}\n\n\n\\section{Integrals}\n\\label{sec:integral}\n\nThe  \\clsref{Integrator}{../ns-2/integrator.h}\nsupports the approximation of (continuous) integration by (discrete)\nsums; it is defined in \\nsf{integrator.h} as\n\\begin{program}\n{\\rm From integrator.h:}\n        class Integrator : public TclObject \\{\n        public:\n                Integrator();\n                void set(double x, double y);\n                void newPoint(double x, double y);\n                int command(int argc, const char*const* argv);\n        protected:\n                double lastx_;\n                double lasty_;\n                double sum_;\n        \\};\n\n{\\rm From integrator.cc:}\n        Integrator::Integrator() : lastx_(0.), lasty_(0.), sum_(0.)\n        \\{\n                bind(\"lastx_\", &lastx_);\n                bind(\"lasty_\", &lasty_);\n                bind(\"sum_\", &sum_);\n        \\}\n\n        void Integrator::set(double x, double y)\n        \\{\n                lastx_ = x;\n                lasty_ = y;\n                sum_ = 0.;\n        \\}\n\n        void Integrator::newPoint(double x, double y)\n        \\{\n                sum_ += (x - lastx_) * lasty_;\n                lastx_ = x;\n                lasty_ = y;\n        \\}\n\n        int Integrator::command(int argc, const char*const* argv)\n        \\{\n                if (argc == 4) \\{\n                        if (strcmp(argv[1], \"newpoint\") == 0) \\{\n                                double x = atof(argv[2]);\n                                double y = atof(argv[3]);\n                                newPoint(x, y);\n                                return (TCL_OK);\n                        \\}\n                \\}\n                return (TclObject::command(argc, argv));\n        \\}\n\\end{program}\nThis class provides a base class used by other classes such\nas \\code{QueueMonitor} that keep running sums.\nEach new element of the running sum is added by\nthe \\fcn[x, y]{newPoint} function.\nAfter the $k$th execution of \\code{newPoint}, the running sum\nis equal to $\\sum_{i=1}^{k}y_{i-1}(x_i - x_{i-1})$ where\n$x_0 = y_0 = 0$ unless \\code{lastx\\_}, \\code{lasty\\_}, or \\code{sum\\_}\nare reset via OTcl.\nNote that a new point in the sum can be added either by the\nC++ member \\code{newPoint} or the OTcl member \\code{newpoint}.\nThe use of integrals to compute certain types of averages\n(e.g. mean queue lengths) is given in (pp. 429--430, \\cite{Jain91:Art}).\n\n\\section{\\code{ns-random}}\n\n{\\bf \\code{ns-random} is an obsolete way to generate random numbers. \nThis information is provided only for backward compatibility.}\n\n\\code{ns-random} is implemented in \\nsf{misc.\\{cc,h\\}}. \nWhen called with no argument, it generates a random number with\nuniform distribution between 0 and \\code{MAXINT}.\nWhen an integer argument is provided, it seeds the random generater\nwith the given number.\nA special case is when \\code{ns-random 0} is called, it randomly seeds\nthe generator based on current time.\nThis feature is useful to produce non-deterministic results across\nruns.\n\n\\section{Some mathematical-support related objects}\n\\label{sec:mathobjects}\n\n\\textsc{Integrator objects}\nIntegrator Objects support the approximate computation of continuous\nintegrals using discrete sums. The running sum(integral) is computed as:\n\\code{sum_ += [lasty_ * (x lastx_)]} where (x, y) is the last element\nentered and\n(lastx\\_, lasty\\_) was the element previous to that added to the sum.\nlastx\\_ and lasty\\_ are updated as new elements are added. The first\nsample point defaults to (0,0) that can be changed by changing the values\nof (lastx\\_,lasty\\_). \n\\code{$integrator newpoint <x> <y>}\\\\ %$\nAdd the point (x,y) to the sum. Note that it does not make sense for x to\nbe less than lastx\\_. \n\nThere are no configuration parameters specific to this object. \\\\\n\nState Variables are:\n\\begin{description}\n\\item[lastx\\_]\nx-coordinate of the last sample point. \n\n\\item[lasty\\_]\ny-coordinate of the last sample point. \n\n\\item[sum\\_] Running sum (i.e. the integral) of the sample points. \n\\end{description}\n\n\n\\textsc{Samples Object}\nSamples Objects support the computation of mean and variance statistics\nfor a given sample. \n\n\\code{$samples mean}\\\\\nReturns mean of the sample. \n\n\\code{$samples variance}\\\\\nReturns variance of the sample. \n\n\\code{$samples cnt}\\\\\nReturns a count of the sample points considered. \n\n\\code{$samples reset }\\\\\nReset the Samples object to monitor a fresh set of samples. \n\nThere are no configuration parameters or state variables specific to this\nobject. \n\n\n\n\\section{Commands at a glance}\n\\label{sec:mathcommand}\n\nFollowing is a list of mathematical support related commands commonly used\nin simulation scripts:\n\\begin{flushleft}\n\\code{set rng [new RNG]}\\\\\nThis creates a new random number generator.\n\n\n\\code{$rng seed <0 or n>}\\\\\nThis command seeds the RNG. If 0 is specified, the RNG is seeded\nheuristically. Otherwise the RNG is seeded with the value <n>.\n\n\n\\code{$rng next-random}\\\\\nThis returns the next random number from RNG.\n\n\n\\code{$rng uniform <a> <b>}\\\\\nThis returns a number uniformly distributed on <a> and <b>.\n\n\n\\code{$rng integer <k>}\\\\\nThis returns an integer uniformly distributed on 0 and k-1.\n\n\n\\code{$rng exponential}\\\\\nThis returns a number that has exponential distribution with average 1.\n\n\n\\code{set rv [new Randomvariable/<type of random-variable>]}\\\\\nThis creates an instance of a random variable object that generates random \nvariables with specific distribution. The different types of random \nvariables derived from the base class are:\\\\\nRandomVariable/Uniform, RandomVariable/Exponential, RandomVariable/Pareto,\nRandomVariable/Constant, RandomVariable/HyperExponential.\nEach of these distribution types are parameterized with values of\nappropriate parameters. For details see section \\ref{sec:ranvar} of this\nchapter.\n\n\n\\code{$rv use-rng <rng>}\\\\\nThis method is used to associated a random variable object with a\nnon-default RNG. Otherwise by default, the random variable object is\nassociated with the default random number generator.\n\n\n\\end{flushleft}\n\n\n\n\n% LocalWords:  ranvar pareto expoo tcl lib ns cc integrator RNG rng TclObject\n% LocalWords:  enum RNGSources PREDEF int MAXINT rX edv prob edp setbit iph ECN\n% LocalWords:  ip ecn eed OURCE OTcl RandomVariable argc const argv min avg val\n% LocalWords:  UniformRandomVariable ExponentialRandomVariable cov newPoint pp\n% LocalWords:  ParetoRandomVariable ConstantRandomVariable lastx lasty strcmp\n% LocalWords:  HyperExponentialRandomVariable newpoint atof QueueMonitor\n", "meta": {"hexsha": "edaf2c2e0f8222fb0760dd8309404f6a819d3acf", "size": 18727, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ns-allinone-2.35/ns-2.35/doc/math.tex", "max_stars_repo_name": "nitishk017/ns2project", "max_stars_repo_head_hexsha": "f037b796ff10300ffe0422580be5855c37d0b140", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-29T13:04:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-29T13:04:42.000Z", "max_issues_repo_path": "ns-allinone-2.35/ns-2.35/doc/math.tex", "max_issues_repo_name": "nitishk017/ns2project", "max_issues_repo_head_hexsha": "f037b796ff10300ffe0422580be5855c37d0b140", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-01-20T17:35:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-22T21:41:38.000Z", "max_forks_repo_path": "ns-allinone-2.35/ns-2.35/doc/math.tex", "max_forks_repo_name": "nitishk017/ns2project", "max_forks_repo_head_hexsha": "f037b796ff10300ffe0422580be5855c37d0b140", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-29T16:06:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T16:06:57.000Z", "avg_line_length": 33.1451327434, "max_line_length": 84, "alphanum_fraction": 0.6985635713, "num_tokens": 5121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.32893011953421425}}
{"text": "\\documentclass[11pt,twoside,a5paper]{article}\n\n\\usepackage[a4paper,top=2.5cm,bottom=2.5cm,left=2.2cm,right=2.2cm]{geometry}\n\\usepackage[T1]{fontenc}\n\\usepackage{verbatim}\n\\usepackage[normalem]{ulem} % for striking out with \\sout\n\\usepackage{amsfonts,amsmath,amssymb} % for more math support\n\\usepackage{times}\n\\usepackage[italic]{mathastext} % use normal text font (times) in equations\n\\usepackage{enumitem}\n%\\usepackage[draft]{hyperref}\n\\usepackage[colorlinks,linkcolor=blue,citecolor=blue,urlcolor=blue]{hyperref}\n\\usepackage{color}\n\\usepackage{listings}\n\n\\newcommand{\\dc}{\\mathcal{D} }\n\n\\begin{document}\n\\title{3x2 Covariance emulator}\n%\\author{Tom McClintock}\n\\maketitle\n\n\\section{Emulator in the big picture}\nOur covariance emulator will be quite simple: it will only take in a cosmology and then spit out a matrix to the user. The function signature for making predictions will look something like\n\\begin{lstlisting}[language=Python]\ndef predict_matrix(cosmology):\n    \"\"\"\n    Inputs:\n    cosmology - a container of the cosmological parameters\n\n    Outputs:\n    C_inverse - an NxN array containing the inverse covariance matrix. \n    The dimensions will be specified by the training data, \n    which we have to assume will never change, unless we \n    want to get real fancy.\n    \"\"\"\n    #do things\n    return C_inverse.\n\\end{lstlisting}\nInternally, the algorithm used to make a prediction with the emulator will look like the following:\n\\begin{enumerate}\n\\item Predict some small number of important quantities, $X$, that depend on cosmology $\\Omega$ such as PCA components of some matrix.\n\\item Use $X$ to reconstruct the diagonal components $D$ and the off-diagonal components $T$ of the GCD components.\n\\item Reassemble the GCD components into the inverse covariance matrix $C^{-1}$.\n\\end{enumerate}\nThis algorithm is thus the reverse of section 3 from Morrison \\& Schneider (2013), where they describe how the emulator is designed. The prediction could be made with Gaussian processes, but doesn't have to be. If, for instance, we observed that some PCA components depended very simply on a certain cosmological parameter then we could model that directly.\n\nThus, to train our emulator we would apply this prediction code in reverse: take all the input inverse covariance matrices, reduce them to only a few numbers, find a good interpolation of those numbers as a function of cosmology. The following sections will describe how the emulator should be trained.\n\n\\section{Matrix decomposition: GCD}\nFollowing Morrison \\& Schneider, we should probably use GCD, but this isn't a necessity. The inverse covariance matrix, which is $N\\times N$ gets decomposed like (I'm using slightly different notation than in their paper, for convenience)\n\\begin{equation}\n  \\label{eq:gcd}\n  C^{-1} = L^TDL\n\\end{equation}\nwhere $L$ is a lower triangular matrix (and therefore has $N(N-1)/2$ indepenent elements) and $D$ is a diagonal semi-positive definite matrix (with $N$ independent elements). Emulating $N(N-1)/2+N$ independent elements isn't feasible, so we have to reduce this further with PCA.\n\nBefore moving on, I should note that elements of $L$ can take on any numerical value, but since $D$ is semi-positive then we will work with $\\ln D = d$ instead. In other words, we will work with the logarithm of the elements of $D$. This is important because the Gaussian process wouldn't have knowledge that $D$ is semi-positive, and could yield unphysical predictions.\n\nWe also subtract of the mean of all $d$ values and rescale the values of $d$ so that they have variance 1. This looks like\n\\begin{equation}\n  \\label{eq:rescale}\n  d \\rightarrow \\frac{d - \\bar{d}}/\\sigma_d.\n\\end{equation}\nThis makes PCA described next slightly cleaner. When making the prediction, once we have $d$ from the Gaussian processes, we can transform it back to its original form by multiplying on $\\sigma_d$ and adding $\\bar{d}$. The same treatment goes for the avlues of $L$.\n\n\\section{PCA on the GCD parts}\nLet's pretend that we have run $M$ different simulations (so for us, $M\\sim16$). Let's think just about $d$ first. If we take all the $d$s obtained for each $M$ simulation and ``stack'' them on top of each other into a new matrix $\\dc$ which is now $N\\times M$ (row/column order doesn't matter). Performing PCA on this gives us\n\\begin{equation}\n  \\label{eq:PCA}\n  \\dc = UBV^T\n\\end{equation}\nwhere if $p=\\min(N,M)$ then $U$ is a $N\\times p$ matrix with $U^TU=I_p$, $V$ is a $M\\times p$ with $V^TV=I_p$ and $VV^T=I_M$, and $B$ is $p\\times p$ diagonal matrix of singular values. Basis vectors are formed by $\\Phi = \\frac{1}{\\sqrt{M}}UB$ which is $N\\times p$, with weights $w=\\sqrt{M}V^T$ normalized by $\\frac{1}{\\sqrt{M}}w^Tw=I_M$. The columns of $\\Phi$, which are of length $N$, represent descreasingly important principle components of the original matrix $\\dc$. This means we only need to use the first few of them. In the Coyote papers they found that using the first five was sufficient. This will be something to test.\n\nThe $i$th column of $\\Phi$ corresponds to the $i$th row of $w$, or $w_i$. This $w_i$ has mean zero, and (according to the papers...) contains all of the cosmologial dependence, and is also a function of the domain. \n\nIn the coyote papers, the domain was $k$, whereas in our paper we have this very strange behaviour where the domain is not monotonic, since the ``full'' data vector is a combination of a bunch of data vectors. In other words, looking at Figure 5 of Elizabeth's paper, the data vectors are $\\xi_+$, $\\xi_-$, $\\gamma_t$, and $w$. The domain is not monotonically changing along the edge, which isn't viable for design of the emulator. We will have to think of something, like using just bin number or something. The downside of doing so would mean that the number of bins would have to remain fixed forever.\n\n\\section{Gaussian Process}\nIn this design if we keep five columns then we would utilize five interpolators. We can do this because the weights are all independent of each other, so the prediction by one interpolator is independent of any other interpolator. The challenge we have is to figure out the best way to interpolate $w_i$ across cosmologies and domain. Gaussian processes (GPs) were used in the past because they provide an estimate of the expectation value $\\langle w_i(\\Omega,x)\\rangle$ as well as an estimate of the variance ${\\rm Var}(w_i)$. Note that we could achieve the same thing if we defined a model (a line, a quadratic, something else) for $w_i$ and knew the posterior distributions of the parameters in our model. Using GPs or such a model means that we can propogate the uncertainty in our estimate forward in a Bayesian way. On the other hand this could be computational expensive and end up being not adding much to a cosomological analysis.\n\nI'll fill the rest of this out later, but the important thing that we care about is picking kernels with hyperparameters, writing a likelihood, and then finding the best hyperparameters.\n\n\n\\end{document}\n", "meta": {"hexsha": "8dd5972077ba4d61d45a7b81e01e8788d86467c6", "size": 7003, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "cov_emu_sketch/cov_emu.tex", "max_stars_repo_name": "tmcclintock/TeX_Documents", "max_stars_repo_head_hexsha": "8fd83d85b2c0060d61b2cc6c9c72a408f936c4b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cov_emu_sketch/cov_emu.tex", "max_issues_repo_name": "tmcclintock/TeX_Documents", "max_issues_repo_head_hexsha": "8fd83d85b2c0060d61b2cc6c9c72a408f936c4b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cov_emu_sketch/cov_emu.tex", "max_forks_repo_name": "tmcclintock/TeX_Documents", "max_forks_repo_head_hexsha": "8fd83d85b2c0060d61b2cc6c9c72a408f936c4b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 81.4302325581, "max_line_length": 939, "alphanum_fraction": 0.7618163644, "num_tokens": 1773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.3289301113998058}}
{"text": "%Appendix -- January 2015\r\n\\appendix\r\n\\renewcommand{\\thechapter}{B}\r\n\\renewcommand{\\chaptername}{Appendix}\r\n\r\n\\chapter{New Experiments}\r\n\r\nThe understanding of nonlinear processes in optical fibers is crucial towards \r\nextending the capabilities of modern optical communication systems based on \r\nwavelength division multiplexing (WDM), where each communication channel is \r\nrepresented by a unique wavelength. One of the nonlinear processes that \r\nlimits the information carrying capacity of a WDM system is four-wave mixing \r\n(FWM), which causes cross-talk between neighboring channels. This places a \r\nlower limit on the wavelength separation between adjacent channels and an\r\nupper limit on the input power in each channel. In this study, we describe\r\na process by which the evolution of FWM processes in an optical fiber can be \r\nused to estimate the inhomogeneities in the fiber core material, in particular \r\nthe fluctuations in the linear refractive index of the fiber core.  \r\n\r\nExperiments measuring the evolution of FWM processes along a length of fiber \r\nwere carried out by Hart {\\it et al.}\\ \\cite{hart1} and are described in detail in \r\nSec.\\ 2.2. In this experiment, two input pump waves at frequencies\r\n$\\omega_1$ and $\\omega_2$, interacted with each other through the third-order \r\nnonlinearity of the fiber material to generate first-order sidebands at frequencies \r\n$\\omega_3 = 2\\omega_1 - \\omega_2$ and $\\omega_4 = 2\\omega_2 - \\omega_1$. \r\nThese waves further interacted to produce second-order sidebands at \r\n$\\omega_5 = 2\\omega_3 - \\omega_4$ and $\\omega_6 = 2\\omega_4 - \\omega_3$. \r\nHigher-order sidebands were also generated. The normalized power in the \r\nsideband at frequency $\\omega_m$ was represented by $\\rho_m$. The \r\nevolution of the FWM processes was characterized by the evolution of \r\n$\\rho_m$(z) as a function of fiber length z. \r\n\r\n\\section{Background}\r\n\r\nIn the present work, we make a quantitative comparison between these \r\nexperimental results and our numerical results based on efficient algorithms \r\n\\cite{Agrawal2} to solve the nonlinear Schr\\\"odinger equation (NLSE) that\r\ngoverns the system. The numerical model, its underlying assumptions and\r\nthe results are described in Sec.\\ B.3. A realistic description of a \r\nstandard single mode optical fiber must take into account the random phase \r\nperturbations a light wave undergoes while propagating through it, without \r\ndisturbing the underlying conservative properties of the system. The NLSE \r\nneeds to be suitably modified in order to incorporate the stochastic nature \r\nof the propagation. In order to preserve the conservative properties of the \r\nsystem, the stochastic terms in the NLSE must necessarily be multiplicative in \r\nnature as an additive term acts as a source or a sink. An algorithm that \r\nachieves this with linear, Gaussian, $\\delta$-correlated noise is outlined in \r\nSec.\\ B.3. This algorithm preserves the unconditional stability of the \r\nsystem. At the same time, care is taken to transform the stochastic NLSE from \r\nits original Ito representation \\cite{ito} to the computationally feasible Stratanovich \r\nrepresentation \\cite{stratanovich} by compensating for the \r\nspurious linear drift that results from integrating such stochastic \r\ndifferential equations \\cite{risken,werner2,drummond1,carter3}. The dominant \r\nsources of phase noise are discussed in Sec.\\ B.4. \r\n\r\nConclusions on the relevance of the experiments of Hart {\\it et al.}\\ \\cite{hart1} \r\nand the stochastic modeling presented here are summarized in Sec.\\ B.5.    \r\n\r\n\\section{Experimental and Computational Background}\r\n\r\nIn this work, we focus on tracing the evolution of the sidebands, generated \r\nthrough FWM, along a length of optical fiber. The FWM spectral evolution along\r\n50\\,m of fiber for two input pump power regimes (2.1\\,W and 5.5\\,W) was\r\ninvestigated \\cite{hart1}. In the 2.1\\,W case, the sideband evolution followed a damped \r\nsinusoid along the length of the fiber. The experiments also found that the \r\ntwo first-order sidebands ($\\rho_3$-blueshifted and $\\rho_4$-redshifted from \r\nthe two pumps) had different evolutions along the fiber (with different \r\nspatial wavelengths). For the 5.5\\,W case, the evolution of both first- and \r\nsecond-order sidebands was measured. The damping in the first-order sidebands \r\n($\\rho_3$ and $\\rho_4$) occured faster than in the 2.1\\,W case. Experiments \r\nprobing the dependence of the sideband power on the input power (ranging from \r\n2\\,W to 17\\,W) were also performed at a fixed output length of 50\\,m of the fiber.\r\nAt the same fiber length, the optical spectra for input powers ranging from \r\n2\\,W to 17\\,W were also recorded \\cite{hart1}. The spectral envelopes were observed to fit \r\nwell to a hyperbolic secant function and the fit parameters were recorded. \r\nMeasurements with a high-resolution wavemeter showed that one of the two pumps \r\nconsisted of two very closely spaced longitudinal modes \r\n($\\Delta\\nu\\sim$ 0.5\\,GHz) which were not resolved by the spectrometer used to \r\nrecord the FWM spectra. Inclusion of this multimode nature of the pump input \r\nin their model was found to alter the sideband dynamics dramatically and \r\npartly explained the asymmetry between the blue-shifted and red-shifted \r\nsidebands though it did not account for the damping in the sidebands. This \r\nwas accounted for by adding weak phase fluctuations to the waves as they \r\npropagated along the fiber \\cite{hart1}. The physical source of these phase fluctuations \r\nwas not known at that time. However, the inclusion of the phase fluctuations \r\ninto the model gave excellent qualitative and quantitative agreement with \r\nexperiment. Their model involved integration of a system of coupled ODEs \r\nderived from the NLSE \\cite{thompson1} by a process of truncation that \r\nretained only the leading frequency components (the pumps and the first- and \r\nsecond-order sidebands), a process justified by the fact that the input pump \r\nwaves are well approximated by a combination of monochromatic waves. Their \r\nfinal numerical results are based on simulations using the truncated-ODE model\r\nwith Langevin noise terms representing phase fluctuations in the fiber. \r\nAnother physical source of stochasticity in their experiment was the inherent \r\npower fluctuation in the lasers used as the input pumps. The level of \r\nfluctuations (5-20\\%) was measured and incorporated appropriately into their \r\nmodel through stochastic initial conditions. This explained the evolution of \r\nthe level of observed fluctuations in the sideband trajectories although it \r\nwas found to be inadequate by itself, to account for the damping of the \r\ntrajectories. They found that all three physical characteristics mentioned \r\nabove, namely the multimode nature of the pump input, the stochastic phase \r\nfluctuations along the length of the fiber, and the stochastic initial power \r\nfluctuations were crucial to explaining the different features of the \r\nexperimental measurements \\cite{hart1}. \r\n\r\n\\section{Stochastic NLSE Model}\r\n\r\nIn the present work, we have developed and implemented an unconditionally \r\nstable scheme for integrating the NLSE that successfully incorporates phase \r\nnoise into the SSFM. Thus, we are now in a position to harness the high \r\nfrequency / time resolution of the SSFM together with its efficient \r\nconvergence properties. Due to these advances, we are now able to do \r\nsimulations with much higher frequency resolution (60\\,MHz as compared to \r\n300\\,GHz in the ODE model). This high resolution, coupled with an appropriate \r\nconvolution scheme, enables us to compare these simulated spectra with the \r\ncomposite spectra observed by the spectrometers which had a resolution of \r\n$\\sim$ 60\\,GHz. This was not possible with the truncated ODE model as the \r\nresolution of the simulated spectra in that case was $\\sim$ 300\\,GHz. For \r\nexactly the same levels of phase fluctuations, and initial condition \r\nfluctuations as used in Ref.\\ \\cite{hart1}, comparisons for the present NLSE \r\nmodel with the experimental sideband evolution functions $\\rho_i(z)$ show \r\nexcellent quantitative agreement. These results, along with the algorithms \r\nemployed, are described in detail in this section. We have identified linear \r\nrefractive index fluctuations along the fiber length to be a strong candidate \r\nfor a physical source of the stochastic phase fluctuations. A comparison \r\nbetween the various possible sources is given in Sec.\\ B.4.\r\n\r\nUnder the assumption that the electric field of the light in the fiber has a \r\nslowly varying envelope $A(z,\\tau)$, and that the fiber medium has an \r\ninstantaneous nonlinear response, the system is well described by the \r\nnonlinear Schr\\\"{o}dinger equation (NLSE) with a linear multiplicative\r\nstochastic term\r\n%B.1\r\n\\begin{equation}\r\n{\\partial U \\over \\partial z} + {i\\beta^{(2)} \\over 2T_0^2} \r\n{\\partial^2 U \\over \\partial\\tau^2} + {\\alpha U \\over 2}\r\n + i\\Gamma(z,\\tau)U-i\\gamma P_0 |U|^2 U = 0.\r\n\\end{equation}\r\n$Z$ is distance along the length of the fiber, \r\n$U(z,\\tau)=A(z,\\tau)/\\sqrt{P_0}$ is the complex electric field envelope \r\n$A(z,\\tau)$ normalized to the absolute amplitude of the field $\\sqrt{P_0}$, \r\n$P_0$ is the total power in the fiber, $\\tau$ is time normalized to a \r\nconvenient time scale $T_0(\\sim 1\\ ns)$ measured in a reference frame \r\nmoving with the group velocity of the pulse [$\\tau=(t-z/v_g)/T_0$]. The \r\nsimulations are carried out for exactly the same physical parameters as the \r\nexperiments and simulations reported by Hart {\\it et al}.\\ \\cite{hart1}, i.e., \r\n$\\beta^{(2)}=55\\,(ps)^2/km$, is the group velocity dispersion of the fiber at \r\nthe operating wavelength $\\lambda_{0}\\sim$ 632\\,nm \r\n($k_0\\sim 10^7\\,m^{-1}$). A loss of $\\sim$ 6\\,dB/km gives $\\alpha$ = 0.0014\\,m$^{-1}$ as the \r\nloss in the fiber at this wavelength. The nonlinearity coefficient \r\n$\\gamma=0.019\\,W^{-1}m^{-1}$ is given by \r\n%B.2\r\n\\begin{equation}\r\n\\gamma = {\\omega_{ave}n_2^I \\over cA_{eff}},\r\n\\end{equation}\r\nwhere $A_{eff}$ is the effective core area of the fiber,\r\n$n_2^I$ is the Kerr coefficient for the intensity-dependent refractive index, and \r\n$\\omega_{ave}$ is the average angular frequency of the wave envelope. \r\n$\\Gamma(z,\\tau)$ is a linear multiplicative phase noise field. In this study \r\nthe noise field is assumed to be $\\delta$-correlated in both space and time. \r\nThe evolution of the FWM dynamics is found to be sensitive to the strength of \r\nthis noise field. It can be physically interpreted as phase noise arising due \r\nto fluctuations in the linear refractive index of the fiber medium. A detailed \r\ndiscussion of its physical origin is given in Sec.\\ B.4.\r\n\r\nThe system was simulated using the Split-Step Fourier Method (SSFM) \r\n\\cite{Agrawal2}. An algorithm for appropriately incorporating stochastic\r\nphase fluctuations along the length of the fiber in the SSFM was developed\r\nand is summarized below.\r\n\r\nThe NLSE is composed of linear and nonlinear terms, and can be written in operator form as\r\n%B.3\r\n\\begin{eqnarray}\r\n{\\partial U \\over \\partial z} & = & (\\hat{D}+\\hat{S}+\\hat{N})U \\nonumber \\\\\r\n\\hat{D}& = & {-i\\beta^{(2)} \\over 2T_0^2}\r\n{\\partial^2 \\over \\partial\\tau^2} - {\\alpha \\over 2} \\nonumber \\\\\r\n\\hat{S} & = & i\\Gamma(z,\\tau) \\nonumber \\\\\r\n\\hat{N} & = & i\\gamma P_0|U|^2,\r\n\\end{eqnarray}\r\nwhere $\\hat{D}$, $\\hat{S}$ and $\\hat{N}$ are linear\r\n(dispersive), nonlinear \r\nand stochastic operators, respectively. It has an exact solution for \r\ninfinitesimal $\\Delta z$ given by - \r\n%B.4\r\n\\begin{equation}\r\nU(z + \\Delta z,\\tau) = exp[\\Delta z(\\hat{D} + \\hat{S} + \\hat{N})]U(z,\\tau) ,\r\n\\end{equation}\r\nwhich can be approximated by\r\n%B.5\r\n\\begin{equation}\r\nU(z + \\Delta z,\\tau) \\approx exp[\\Delta z \\hat{D}]exp[\\Delta z \\hat{S}]exp[\\Delta z \\hat{N}]U(z,\\tau) .\r\n\\end{equation}\r\n\r\nThe execution of $exp[\\Delta z \\hat{N}]$ is carried out in $\\tau$-space:\r\n%B.6\r\n\\begin{equation}\r\nB_1(z,\\tau)=exp[\\Delta z \\hat{N}]U(z,\\tau) .\r\n\\end{equation}\r\n\r\nThe execution of $exp[\\Delta z \\hat{S}]$ and $exp[\\Delta z \\hat{D}]$ is \r\ncarried out in $\\omega$-space.\r\n\r\nIn particular, the stochastic phase fluctuations are introduced by modifying \r\nthe phase $\\phi_j$ of each frequency component $\\omega_j$ of the complex \r\nfield according to\r\n%B.7\r\n\\begin{eqnarray}\r\nB_2(z,\\omega) & = & {\\cal{F}}[B_1(z,\\tau)] \\nonumber \\\\\r\nB_3(z,\\omega_{j}) & = & exp[i \\delta\\phi(z,\\omega_j)]B_2(z,\\omega_j) ,\r\n\\end{eqnarray}\r\nwhere $\\cal{F}$ represents the Fourier transform operation.\r\n\r\nThis process only modifies the phase of each complex frequency component, \r\nleaving its absolute value unchanged. Thus the algorithm conserves the total \r\npower and the unconditional stability of the system.\r\n\r\nThe stochastic phase fluctuations $\\delta\\phi(z,\\omega_j)$ are taken to be \r\n$\\delta$-correlated in frequency as well as spatially along the fiber length. \r\nThe Box-Muller algorithm \\cite{boxmuller} was used to generate Gaussian random\r\ndeviates from computer-generated uniform random deviates $r_{1j}$ and $r_{2j}$\r\nat each spatial step and for each frequency component $\\omega_j$. The \r\nfluctuations are given by\r\n%B.8\r\n\\begin{equation}\r\n\\delta\\phi(z,\\omega_{j}) = \\sqrt{-2\\sigma_{\\phi}^2 \\Delta z ln(r_{1j})}cos(2 \\pi r_{2j}) .\r\n\\end{equation}\r\n\r\nThis is followed by the execution of $exp[\\Delta z \\hat{D}]$, which is also \r\ncarried out in Fourier space, followed by the inverse transform\r\n%B.9\r\n\\begin{equation}\r\nU(z + \\Delta z,\\tau) = {\\cal{F}}^{-1}[exp[\\Delta z \\hat{D}(i\\omega)]B_{3}(z,\\omega)] .\r\n\\end{equation}\r\n\r\n$\\hat{D}(i\\omega)$ is obtained by replacing $(\\partial / \\partial \\tau)$ \r\nby $i \\omega$.\r\n\r\n%Figure B.1\\renewcommand{\\baselinestretch}{1}\r\n\r\n\\begin{figure}\r\n\\begin{center}\r\n\\includegraphics[0in,0in][3.25in,4.266in]{nlsetime.eps}\r\n\\end{center}\r\n\\renewcommand{\\baselinestretch}{1}\r\n\\small\\normalsize\r\n\\begin{quote}\r\n\\caption{Multimode pulse input to the NLSE: (a) input pulse in time\r\ndomain and (b) input spectrum.}\r\n\\label{figB.1}\r\n\\end{quote}\r\n\\end{figure}\r\n\\renewcommand{\\baselinestretch}{2}\r\n\\small\\normalsize\r\n\r\nThe basic form of the initial complex wave envelope function is \r\n%B.10 \r\n\\begin {equation}\r\nU(0,\\tau) = exp \\left( - {\\tau^2 \\over 2\\tau_p^2} \\right)\r\n\\left\\{ \r\n\\begin{array}{l}\r\nexp\\left( {i\\Omega\\tau \\over 2} \\right) + \\\\\r\nexp\\left( - {i\\Omega\\tau \\over 2} \\right)\r\n\\end{array}\r\n\\right\\} ,\r\n\\end{equation}\r\nwhere $\\tau_p$ is the pulse width T$_p$ =5\\,ns FWHM, normalized to the time scale \r\nT$_0$, $\\Omega$=366\\,GHz is the frequency detuning between the two laser \r\nsources normalized to a frequency scale $\\Omega_0$ = 62.5\\,MHz.  Figure B.1(a) \r\nshows a plot of this pulse $|U(0,\\tau)|^2$. The overall Gaussian envelope \r\nhas an FWHM of 5\\,ns, the closely spaced dark lines are due to the 366\\,GHz \r\n($\\sim$3\\,ps) beating between the two input pump frequencies. The 2\\,ns \r\nmodulations on the pulse are due to the 0.5\\,GHz mode-structure in the \r\nblue-shifted pump wave. Figure 2.1(b) shows the input spectrum of this pulse \r\nwhich consists of two highly monochromatic pump waves with a detuning of \r\n$\\Omega$=366\\,GHz. The spectrum of the blue-shifted pump, upon magnification, \r\nis seen to be composed of two very closely spaced peaks, with a separation of \r\n$\\Delta\\nu$=0.5\\,GHz. Hart {\\it et al}.\\ \\cite{hart1} did not use pulsed \r\nwave functions in their NLSE simulations as the size of the FFT required to do \r\nso made it computationally prohibitive at that time. The size of the FFT was \r\nchosen such that it would accommodate a time span of 16\\,ns in order to go \r\nsufficiently far into the wings on the Gaussian pulse; and a frequency span of \r\n16\\,THz in order to accommodate all the sidebands generated and prevent \r\nspurious effects due to the reflection boundary conditions implicit in the \r\nSSFM algorithm. These considerations dictated the size of the FFT to be \r\n$\\geq$(16 THz)$\\cdot$(16 ns) = 256000. The nearest power of 2 is \r\n2$^{18} = 262144$, which has been used throughout the present work. The \r\nincorporation of the pulsed nature of the light was found to be necessary in \r\nexplaining the dynamics. From the perspective of the coupled amplitude \r\nequations used by Hart {\\it et al}.\\ \\cite{hart1}, the present model is equivalent \r\nto a coupled-ODE model with $2^{18}$ coupled ODEs. \r\n\r\n%Figure B.2\r\n\\begin{figure}\r\n\\begin{center}\r\n\\includegraphics[0in,0in][6in,4.572in]{modestruc21ornot.eps}\r\n\\end{center}\r\n\\renewcommand{\\baselinestretch}{1}\r\n\\small\\normalsize\r\n\\renewcommand{\\baselinestretch}{1}\r\n\\small\\normalsize\r\n\\begin{quote}\r\n\\caption[Short caption for Figure B.2.]\r\n{Effects of inclusion of the multimode nature ($\\Delta\\nu = 0.5$\\,GHz) of the blue-shifted input pump laser on the 1st order sideband evolution as a function of fiber length for P$_0 = 2.1$\\,W. Dashed curves represent simulations without the multimode nature and solid curves represent simulations with the multimode nature. $\\Omega = 366$\\,GHz, $\\gamma = 0.019$\\,W$^{-1}$\\,m$^{-1}$, and $\\beta^{(2)} = 55$\\,ps$^2$/km (a) power in the blue-shifted sideband, (b) power in the red-shifted sideband.}\r\n\\label{figB.2}\r\n\\end{quote}\r\n\\end{figure}\r\n\\renewcommand{\\baselinestretch}{2}\r\n\\small\\normalsize\r\n\r\n%Figure B.3\r\n\\begin{figure}\r\n\\begin{center}\r\n\\includegraphics[0in,0in][6in,4.572in]{modestruc55ornot.eps}\r\n\\end{center}\r\n\\renewcommand{\\baselinestretch}{1}\r\n\\small\\normalsize\r\n\\begin{quote}\r\n\\caption[Effects of inclusion of the multimode nature]\r\n{Effects of inclusion of the multimode nature ($\\Delta\\nu = 0.5$\\,GHz) of the blue-shifted input pump laser on the 1st order sideband evolution as a function of fiber length for P$_0 = 5.5$\\,W. Dashed curves represent simulations without the multimode nature and solid curves represent simulations with the multimode nature. $\\Omega = 366$\\,GHz, $\\gamma = 0.019$\\,W$^{-1}$\\,m$^{-1}$, and $\\beta^{(2)} = 55$\\,ps$^2$/km (a) power in the first-order blue-shifted sideband, (b) power in the first-order red-shifted sideband, (c) power in the second-order blue-shifted sideband, (d) power in the second-order red-shifted sideband.}\r\n\\label{figB.3}\r\n\\end{quote}\r\n\\end{figure}\r\n\\renewcommand{\\baselinestretch}{2}\r\n\\small\\normalsize\r\n\r\n%Figure B.4\r\n\\begin{figure}\r\n\\begin{center}\r\n\\includegraphics[0in,0in][6in,4.572in]{nlsez21cwpulse.eps}\r\n\\end{center}\r\n\\renewcommand{\\baselinestretch}{1}\r\n\\small\\normalsize\r\n\\begin{quote}\r\n\\caption[Effects of inclusion of the pulsed nature]\r\n{Effects of inclusion of the pulsed nature (5\\,ns FWHM) of the input pump laser light on the first-order sideband evolution as a function of fiber length for P$_0 = 2.1$\\,W. Dashed curves represent cw simulations and solid curves represent pulsed simulations. $\\Omega = 366$\\,GHz, $\\Delta\\nu = 0.5$, $\\gamma = 0.019$\\,W$^{-1}$m$^{-1}$, and $\\beta^{(2)} = 55$\\,ps$^2$/,km (a) power in the blue-shifted sideband, (b) power in the red-shifted sideband.}\r\n\\label{fig24}\r\n\\end{quote}\r\n\\end{figure}\r\n\\renewcommand{\\baselinestretch}{2}\r\n\\small\\normalsize\r\n\r\n\r\n%Figure B.5\r\n\\begin{figure}\r\n\\begin{center}\r\n\\includegraphics[0in,0in][6in,4.572in]{nlsez55cwpulse.eps}\r\n\\end{center}\r\n\\renewcommand{\\baselinestretch}{1}\r\n\\small\\normalsize\r\n\\begin{quote}\r\n\\caption\r\n[Other effects of inclusion of the pulsed nature]\r\n{Effects of inclusion of the pulsed nature (5\\,ns FWHM) of the input pump laser on the first- and second-order sideband evolution as a function of fiber length for P$_0 = 5.5$\\,W. Dashed curves represent cw simulations and solid curves represent pulsed simulations. $\\Omega = 366$\\,GHz, $\\Delta\\nu = 0.5$, $\\gamma = 0.019$\\,W$^{-1}$m$^{-1}$, and $\\beta^{(2)} = 55$\\,ps$^2$/,km (a) power in the first-order blue-shifted sideband, (b) power in the first-order red-shifted sideband, (c) power in the second-order blue-shifted sideband, (d) power in the second-order red-shifted sideband.}\r\n\\label{fig25}\r\n\\end{quote}\r\n\\end{figure}\r\n\\renewcommand{\\baselinestretch}{2}\r\n\\small\\normalsize\r\n\r\nUpon incorporation of the multimode nature of the blue input pump laser source \r\nand the stochastic fluctuations in the initial power in the lasers, the \r\ninitial wave function takes the form\r\n%B.11\r\n\\begin {equation}\r\nU(0,\\tau) = exp\\left( - {\\tau^2 \\over 2\\tau_p^2} \\right)\r\n\\left\\{\r\n\\begin{array}{l}\r\n\\sqrt{{1 + \\delta\\rho_1 \\over 2}} \r\n\\left[ \\begin{array}{l}\r\nexp \\left( {i(\\Omega+\\Delta\\nu)\\tau \\over 2} \\right) + \\\\\r\nexp \\left( {i(\\Omega-\\Delta\\nu)\\tau \\over 2} \\right) \r\n\\end{array} \\right]\\\\\r\n+ \\sqrt{1 + \\delta\\rho_2} exp\\left( - {i\\Omega\\tau \\over 2} \\right)\r\n\\end{array}\r\n\\right\\}.\r\n\\end{equation}\r\n\r\n\\\r\n\r\n\\noindent $\\Delta\\nu = 0.5$\\,GHz is the frequency separation between the two longitudinal \r\nmodes in the blue-shifted pump. $\\delta\\rho_1$ and $\\delta\\rho_2$ are \r\nGaussian random deviates (generated using the Box-Muller algorithm \r\n\\cite{boxmuller}) that represent the initial power fluctuations in each of the \r\npump laser sources. Their standard deviations were taken to be, \r\n$\\sigma_{\\rho_1} = 0.2$, $\\sigma_{\\rho_2} = 0.11$ for simulations from 0\\,m to \r\n20\\,m, $\\sigma_{\\rho_1} = 0.12$, $\\sigma_{\\rho_2} = 0.05$ for simulations from \r\n20\\,m to 50\\,m along the length of the fiber. This is exactly the same \r\nprescription used by Hart {\\it et al}.\\ \\cite{hart1} in their simulations and is \r\ndictated by their experimental measurements of the fluctuations in the pump \r\nlaser intensities.\r\n\r\nAt this point it is worth noting the effects of the inclusion of two attributes of \r\nthe input laser light, namely, the multimode nature of the blue-shifted pump, and \r\nthe pulsed nature of the input light (assumed to be cw in the simulations reported by \r\nHart {\\it et al}.\\ \\cite{hart1}). \r\n\r\nFigure B.2 shows a comparison between simulations with (solid curves) and without (dashed curves) the multimode nature for an input pump power of 2.1 Watts. The simulations with the mode structure show the asymmetry between the blue- and red-shifted sideband evolution, in particular, the difference in spatial wavelength between the two, and a non-return to zero nature of the evolution, as observed in the experimental data (black dots with error bars). These features are absent in the simulations without mode-structure. $\\rho_3$ and $\\rho_4$ stands for the first order blue- and red-shifted sidebands respectively.  Figure 2.3 shows the corresponding comparison for the case of 5.5 Watts of input pump power.  Here, too, the simulations incorporating the multimode nature of the blue-shifted pump (solid curves) are seen to be an improvement over those not incorporating it (dashed curves). A feature of the experimental data (black dots with errorbars) is that for the $\\rho_3$ sideband, the initial part of the evolution involves a peak followed by a shoulder, while for the $\\rho_4$ sideband, the initial part of the evolution involves a shoulder followed by a peak. This feature, too, is seen to occur as a result of the inclusion of the multimode nature of the blue-shifted pump.  \r\n\r\nThe effect of inclusion of the pulsed nature of the input beam is seen in Fig.\\ B.4 (for the 2.1 Watt case) and Fig.\\ B.5 (for the 5.5 Watt case). The solid dashes represent simulations for a cw input beam and the solid curves represent those for a pulsed input beam. The incorporation of the pulsed nature clearly results in damping of the sideband trajectories which are seen to come closer to the experimental data \\cite{hart1} (black dots with error bars). \r\n\r\nUse of the FFT algorithm makes evaluation relatively fast compared to other \r\nfinite-difference schemes. The computational error is $O(\\Delta z^2)$, thus \r\nthe solution converges with decreasing spatial step-size $\\Delta z$. \r\n\r\nThe simulations were tested for the conservation of total power along the \r\nfiber length (by setting the loss $\\alpha$ to zero) and for the conservation \r\nof asymmetry \\cite{thompson1,hart1} given by \r\n%B.12\r\n\\begin{equation}\r\nC(Z) = \\sum_{i=1}^{\\infty}(2i-1)[\\rho_{2i-1}(Z)-\\rho_{2i}(Z)] .\r\n\\end{equation}\r\n\r\nA clearer picture of the evolution of the sidebands is obtained by plotting both the \r\npower in the sidebands and their standard deviations as a function of length along the fiber. Figures B.6(a) and B.6(b) show a comparison between simulation and experiment of the evolution \r\nof the first-order blue-shifted ($\\rho_3$) and red-shifted ($\\rho_4$) sidebands,  \r\nrespectively, for an input power of 2.1 W. The dashed curves represent NLSE simulations \r\nwhich include the stochastic nature of the input powers of the pump lasers but exclude \r\nthe stochastic phase fluctuations added along the length of the fiber, an attribute \r\nwhich is included in the simulations represented by the solid curves. The black dots \r\nwith error bars represent the experimental data. The measured sideband \r\npower, normalized to the total power in the fiber, is periodic in length but \r\nappears to be damping to a constant value. The measured data also show a clear \r\ndifference between the spatial wavelengths of oscillation of the blue-shifted ($\\rho_3$) and red-shifted ($\\rho_4$) sidebands trajectories, respectively. Both these features are captured well by both the simulations. Figures B.6(c) and B.6(d) compare experimental and simulated \r\nmeasures of the evolution of the standard deviation in the sideband power \r\nalong the fiber length. It is clearly observed that simulations with phase noise \r\nadded to the light field along the length of the fiber (solid curves) are closer to the \r\nexperimental data as compared to those that exclude this feature (dashed curves). This indicates\r\nthe instrumental nature of the phase fluctuations in explaining key features of the dynamics.\r\n\r\n%Figure B.6\r\n\\begin{figure}\r\n\\begin{center}\r\n\\includegraphics[0in,0in][6in,4.572in]{nlsez21phaseornot.eps}\r\n\\end{center}\r\n\\renewcommand{\\baselinestretch}{1}\r\n\\small\\normalsize\r\n\\begin{quote}\r\n\\caption\r\n[Comparison between experiments measurements]\r\n{Comparison between the experimental measurements \\cite{hart1}(black), the random initial condition NLSE model excluding phase noise (dashed curves) and the stochastic phase noise NLSE model (solid curves) showing the first-order sideband evolution as a function of fiber length for P$_{0} = 2.1$\\,W, $\\Omega = 366$\\,GHz, $\\Delta\\nu = 0.5$\\,GHz,$\\gamma = 0.019$\\,W$^{-1}$m$^{-1}$, and $\\beta^{(2)} = 55$ps$^2$/km: dynamical evolution of the: (a) power in the blue-shifted sideband, (b) power in the red-shifted sideband, (c) fluctuations in the blue-shifted sideband, (d) fluctuations in the red-shifted sideband.}\r\n\\label{figB.6}\r\n\\end{quote}\r\n\\end{figure}\r\n\\renewcommand{\\baselinestretch}{2}\r\n\\small\\normalsize\r\n\r\nThe apparent damping of the periodic sideband trajectory is seen more \r\ndramatically in Figs.\\ B.7(a) and B.7(b), which show the evolution of the \r\nfirst-order sideband power along the fiber for an input power of 5.5\\,W. \r\nThe two first-order sidebands evolve differently. They appear to \r\ndamp to a constant value at a faster rate than for the case with an input pump \r\npower of 2.1\\,W. Here again, NLSE simulations that incorporate phase noise along the length\r\nof the fiber (solid curves) are much more successful in accurately capturing the dynamical features of the system than NLSE simulations that do not take this feature into account (dashed curves).  Figures B.7(c) and B.7(d) show a comparison between the simulated and measured standard deviations. Comparisons for the second-order blue-shifted ($\\rho_5$) and red-shifted ($\\rho_6$) sidebands, respectively, are shown in Figs.\\ B.7(e) and B.7(f). \r\n\r\n\r\n%Figure B.7\r\n\\begin{figure}\r\n\\begin{center}\r\n\\includegraphics[0in,0in][6in,4.572in]{nlsez55phaseornot.eps}\r\n\\end{center}\r\n\\renewcommand{\\baselinestretch}{1}\r\n\\small\\normalsize\r\n\\begin{quote}\r\n\\caption\r\n[This figure caption is indented and single-spaced.]\r\n{This figure caption is indented and single-spaced.  Comparison between the experimental measurements \\cite{hart1} (black), the random initial condition NLSE model excluding phase noise (dashed curves) and the stochastic phase noise NLSE model (solid curves) showing the first- and second-order sideband evolution as a function of fiber length for P$_{0} = 5.5$\\,W, $\\Omega = 366$\\,GHz, $\\Delta\\nu = 0.5$\\,GHz, $\\gamma = 0.019$\\,W$^{-1}$m$^{-1}$, and $\\beta^{(2)} = 55$\\,ps$^2$/km: dynamical evolution of the: (a) power in the first-order blue-shifted sideband, (b) power in the first-order red-shifted sideband, (c) fluctuations in the first-order blue-shifted sideband, (d) fluctuations in the first-order red-shifted sideband, (e) power in the second-order blue-shifted sideband, (f) power in the second-order red-shifted sideband.}\r\n\\label{figB.7}\r\n\\end{quote}\r\n\\end{figure} \r\n\\renewcommand{\\baselinestretch}{2}\r\n\\small\\normalsize\r\n\r\nThe observed dynamical evolution of the sidebands is found to depend \r\nsensitively on the strength of the stochastic phase fluctuations. Yet, best \r\nagreement with the experimental results of Hart {\\it et al}.\\ \\cite{hart1} is \r\nachieved with exactly the same noise strength $\\sigma^2_\\phi$ as used in \r\ntheir truncated ODE model, namely, $\\sigma^2_\\phi = 0.0067$\\,m$^{-1}$. They \r\nreport that including phase noise in their FWM calculations resulted in a \r\nspurious linear drift in the trajectories for the sideband power with length. \r\nTo remove this artifact of the computations, they added a linear loss to their \r\ncoupled ODEs. They set the loss coefficient $\\alpha = 0.0046$\\,m$^{-1}$ by \r\nfinding the value that removed this increasing slope. We have observed exactly \r\nthe same secular growth phenomenon for a wide range of the noise strength \r\n$\\sigma^2_\\phi$ and have arrived at an empirical prescription for $\\alpha$ \r\nnamely, $\\alpha\\sim\\sigma^2_\\phi$, where $\\sigma^2_\\phi$ is the \r\nvariance of the added phase noise. This indicates the general nature of \r\ndynamics resulting from the addition of stochastic, $\\delta$-correlated phase \r\nfluctuations to systems governed by nonlinear partial differential equations \r\n\\cite{risken}. \r\n\r\nIt is remarkable that the strength of the phase noise required is the same in \r\nboth the 2.1\\,W and the 5.5\\,W cases. Further, it is worth noting that exactly \r\nthe same noise strength was used by Hart {\\it et al}.\\ \\cite{hart1}, the difference \r\nbeing that they introduced phase noise only in the pump frequencies, whereas \r\nwe have introduced it in all the Fourier modes ($\\sim2^{18}$). As a \r\nconfirmation of this result, they also performed experiments and numerical \r\nsimulations examining the sideband power dependence on the input power at a \r\nfixed length of 50.4\\,m of the same fiber. We have repeated these simulations \r\nwith the stochastic NLSE model and the results are shown in Figs.\\ B.8(a) \r\n(blue-shifted sideband) and B.8(b) (red-shifted sideband). The experimental \r\nmeasurements of the sideband powers are represented by filled squares and the \r\nresults of numerical simulations are represented by triangles (without phase \r\nnoise) and by circles (with phase noise). The simulations are seen to follow \r\nthe general trend seen in the experiments. As the pump power is increased, the \r\ntriangles (without phase noise) start to disagree with experiment, whereas the \r\ncircles (with phase noise) are much closer to experiment. The phase noise \r\nstrength used in these simulations was exactly the same as that used in the \r\nsimulations depicted in Figs.\\ B.6 and B.7. The agreement between the phase noise \r\nsimulations and the experimental data was (once again) highly sensitive to the \r\nnoise strength. Since this experiment (unlike those shown in Figs.\\ B.2 - B.7) \r\nis non-destructive, it can be used to deduce the strength of phase noise \r\nprocesses in a given optical fiber. It will be shown in Sec.\\ B.4 that a \r\nlikely cause of the phase noise is fluctuation in the linear refractive index \r\nof the fiber. The noise strength deduced from the present computational study \r\ncorresponds to a refractive index inhomogeneity of \r\n$\\langle \\Delta n^{2} \\rangle \\sim 10^{-16}$.   \r\n\r\n%Figure B.8\r\n\\begin{figure}\r\n\\hspace{1.25in}\r\n\\includegraphics[0in,0in][6in,4.572in]{nlsefinal.eps}\r\n\\renewcommand{\\baselinestretch}{1}\r\n\\small\\normalsize\r\n\\begin{quote}\r\n\\caption\r\n[Comparison between the experiments measurements (filled squares]\r\n{Comparison between the experimental measurements (filled squares), simulations without stochastic phase fluctuations (open triangles) and with stochastic phase fluctuations (open circles) of the first-order sideband power versus pump input power for L=50.39\\,m, and $\\Omega = 366$\\,GHz: power in the (a) blue-shifted sideband and (b) red-shifted sideband.}\r\n\\label{figB.8}\r\n\\end{quote}\r\n\\end{figure}\r\n\\renewcommand{\\baselinestretch}{2}\r\n\\small\\normalsize\r\n\r\n\r\n%Figure B.9\r\n\\begin{figure}\r\n\\begin{center}\r\n\\includegraphics[0in,0in][6in,4.572in]{fig292.eps}\r\n\\end{center}\r\n\\renewcommand{\\baselinestretch}{1}\r\n\\small\\normalsize\r\n\\begin{quote}\r\n\\caption\r\n[Evolution of the FWM spectrum]\r\n{Evolution of the FWM spectrum along the fiber (a) P=2.1\\,W, experiment, \r\n(b) P=5.5\\,W, experiment, (c) P=2.1\\,W, stochastic-NLSE model, (d) P=5.5\\,W, stochastic-NLSE model.}\r\n\\label{figB.9}\r\n\\end{quote}\r\n\\end{figure}\r\n\\renewcommand{\\baselinestretch}{2}\r\n\\small\\normalsize\r\n\r\nTill now the comparisons between our simulations of the full NLSE and the \r\ntruncated ODE model give basically the same results, although with much better \r\nagreement with experiment. However, the full NLSE can also provide a detailed \r\ncomparison with the experimental spectra. This was not available from the \r\ntruncated ODE model. The simulations reported in this work were carried out \r\nwith a very high frequency and time resolution in order to incorporate the \r\nfact that the input light was not cw, but was composed of $\\sim$ 5\\,ns long \r\npulses; and that the number of sidebands generated required the frequency \r\nspread of the FFT to be $\\sim$ 16\\,THz, while resolving a longitudinal \r\nmode-structure of $\\Delta\\nu$ $\\sim 0.5$\\,GHz. The spectral resolution used was \r\n$\\sim$ 0.05\\,GHz, whereas the spectrometer used to observe the spectra had a \r\nresolution 1000 times larger ($\\sim$ 50\\,GHz). To account for this difference, \r\nthe simulated spectra were first convolved with a Gaussian of unit peak and \r\n62\\,GHz FWHM, before they were compared with the observed spectra.  \r\n\r\nFigures B.9(a) and B.9(b) show three-dimensional plots of the average experimental \r\nFWM output spectrum along the length of the fiber for input pump powers of 2.1\\,W and 5.5\\,W,\r\n respectively (courtesy Hart {\\it et al}.\\ \\cite{hart1}). The vertical \r\naxis represents the intensity, normalized to the peak power in one of the \r\ninput pumps, plotted on a logarithmic scale. The pump frequencies are centered \r\non $+/-\\Omega/2$ and the fiber length is increasing into the page. Figures B.9(c) \r\nand B.9(d) show the corresponding comparisons based on simulations using \r\nthe stochastic-NLSE model. The basic features of the spectral evolution are \r\ncaptured by the simulations. \r\n\r\n%Figure B.10\r\n\\begin{figure}\r\n\\begin{center}\r\n\\includegraphics[0in,0in][6in,4.573in]{nlsespec.eps}\r\n\\end{center}\r\n\\renewcommand{\\baselinestretch}{1}\r\n\\small\\normalsize\r\n\\begin{quote}\r\n\\caption\r\n[Experimental FWM output spectrum]\r\n{Experimental FWM output spectrum (solid line), convolved spectra from simulations of the stochastic NLSE model (dashed line), and hyperbolic secant envelope fit (dotted line) for pump input powers P$_0$ of (a) 2.1\\,W, (b) 5.5\\,W, (c) 6.7\\,W, (d) 8.3\\,W, (e) 12.7\\,W, (f) 17.4\\,W, fiber length L$= 50.39$\\,m, $\\Omega = 366$\\,GHz, $\\Delta\\nu = 0.5$\\,GHz, $\\gamma = 0.019$\\,W$^{-1}$m$^{-1}$, and $\\beta^{(2)} = 55$\\,ps$^2$/km.}\r\n\\label{figB.10}\r\n\\end{quote}\r\n\\end{figure}\r\n\\renewcommand{\\baselinestretch}{2}\r\n\\small\\normalsize\r\n\r\nHart {\\it et al}.\\ \\cite{hart1} also documented the experimentally observed FWM \r\noutput spectra for a fixed fiber length of 50.39 meters for 6 different input \r\npump powers. They state the coefficients A and B of the hyperbolic secant \r\nenvelopes that best fit the output spectra which are given by\r\n%B.13\r\n\\begin{equation}\r\nf(\\omega) = Asech(B\\omega) ,\r\n\\end{equation}\r\nwhere A and B are the experimental fit parameters.\r\n\r\nThe hyperbolic secant parameters A and B, that best fit the simulated spectra \r\nare exactly the same as those that best fit the experimental spectra \r\n\\cite{hart1} for all the 6 cases of input power considered. Figure 2.10 shows an \r\noverlap of the simulated spectra (dashed line), with the experimental spectra \r\n(solid line) and the experimental hyperbolic secant envelope (dotted line) for \r\n6 different pump powers, namely, (a) 2.1\\,W, (b) 5.5\\,W, (c) 6.7\\,W, (d) 8.3\\,W, (e) \r\n12.7\\,W, (f) 17.4\\,W. The hyperbolic secant parameters for each of these pump \r\npowers are (a) A=3.85 and B=0.36, (b) A=2.26 and B=0.27, (c) A=1.81, B=0.25, \r\n(d) A=1.56 and B=0.23, (e) A=0.98,B=0.20, and (f) A=0.81 and B=0.20. The exact \r\nshapes of the simulated spectra match very well with the experimental spectra \r\nfor low input pump powers (2.1\\,W and 5.5\\,W), but tend to lack the \"filled-in\" \r\ncharacter of the experimental spectra at higher powers (6.7\\,W, 8.3\\,W, 12.7\\,W and \r\n17.4\\,W).\r\n\r\n\\section{Discussion}\r\n\r\nHart {\\it et al}.\\ \\cite{hart1} postulated that strong candidates for the possible \r\nphysical sources of the phase fluctuations are stimulated Brillouin \r\nscattering, stimulated Raman scattering and fiber medium inhomogeneities. \r\nBrillouin scattering was eliminated as a source, since a backward propagating \r\nwave, which is a signature of Brillouin scattering in optical fibers, was not \r\nobserved in the experiments. We have  modeled stimulated Raman scattering \r\n\\cite{Agrawal8, headley} for our system and have found no evidence to\r\nsupport the hypothesis that it could be a possible source of the stochastic phase \r\nfluctuations for fiber lengths up to 50 meters and pump power levels up to 5.5 Watts. \r\nA more detailed discussion of the Raman scattering simulations performed is given in Chap.\\ 3.\r\nApart from these, quantum phase fluctuations are another well \r\nknown, though extremely weak, source of phase noise in optical fibers \r\n\\cite{Agrawal2,perlmutter1}.\r\n\r\nFiber medium inhomogeneities were identified as the major cause of the \r\nstochastic phase fluctuations. These inhomogeneities can manifest themselves \r\nthrough spatial and/or temporal fluctuations in the fiber parameters, namely, \r\nthe linear refractive index $n_0$, the group velocity $v_g$, the group \r\nvelocity dispersion $\\beta^{(2)}$ and the nonlinearity \r\n$\\gamma$ \\cite{abdullaev}. Of these, the fluctuation in the linear refractive \r\nindex was found to be the only source of phase fluctuation that had a \r\nsignificant effect on the dynamics. A relationship between the level of \r\nrefractive index fluctuations and the  corresponding level of phase \r\nfluctuations has been arrived at. It is found that refractive index \r\nfluctuations as small as $\\sigma_n^2 \\sim 10^{-17}$\\,m$^{-1}$ can cause the \r\ndesired phase fluctuations. Possible sources of these refractive index \r\nfluctuations are discussed below.   \r\n\r\nConsider the modified nonlinear Schr\\\"odinger equation (NLSE) which is\r\nstated below, with the linear multiplicative noise term represented in terms of \r\nspatial and temporal fluctuations in the refractive index of the fiber.\r\n%B.14\r\n\\begin{equation}\r\n{\\partial U \\over \\partial z} + {i\\beta^{(2)} \\over 2T_0^2} {\\partial^2U \\over \\partial\\tau^2} + {\\alpha U \\over 2} + ik_0 \\delta n(z,\\tau)U - i\\gamma P_{0}|U|^2 U = 0 ,\r\n\\end{equation}\r\nwhere $\\delta n(z,\\tau)$ is the spatial and temporal variation of the refractive \r\nindex along the fiber. It can be caused by temperature and density \r\nfluctuations in the fiber \\cite{glenn}. \r\n\r\nThe thermodynamic estimate for $\\Delta n$ is given by \\cite{glenn}\r\n%B.15\r\n\\begin{equation}\r\n\\langle \\Delta n^{2} \\rangle = {-kT\\rho^2 \\over V^2}  \r\n\\left( {\\partial V \\over \\partial P} \\right)_{T} \r\n\\left( {\\partial n \\over \\partial \\rho} \\right)_{T}^{2}\r\n + {kT^2 \\over \\rho VC_v} \\left( {\\partial n \\over \\partial T} \\right)_{\\rho}^2 .\r\n\\end{equation} \r\n\r\nThis gives the mean-square index fluctuation in terms of the properties of \r\nthe material. It can be rewritten as\r\n%B.16\r\n\\begin{equation}\r\n\\langle \\Delta n^{2} \\rangle = {V_{\\rho}+V_T \\over V} = \\langle \\Delta n^{2} \\rangle_{\\rho}+\\langle \\Delta n^{2} \\rangle_{T} .\r\n\\end{equation}\r\n\r\nFor a fiber of length z=1\\,m and radius r=2.82\\,$\\mu$m \r\n(Volume V=2.5 $\\times 10^{-12}$\\,m$^3$), these have been calculated to be \r\n%B.17\r\n\\begin{eqnarray}\r\n\\langle \\Delta n^2 \\rangle_{\\rho} \\sim 10^{-21} & \\equiv & \\langle \\Delta \\rho^2 \\rangle \\sim 10^{-14} \r\n{kg^2 \\over m^6}, \\nonumber \\\\\r\n\\langle \\Delta n^2 \\rangle_T \\sim 10^{-23} & \\equiv & \\langle \\Delta T^2 \\rangle \\sim 10^{-12}~{^\\circ}C^2 .\r\n\\end{eqnarray}\r\n\r\nIt should be noted that $\\langle \\Delta n^2 \\rangle \\propto (1/z) \\Rightarrow \\delta n \\propto  (1 / \\sqrt{z})$. The corresponding phase fluctuation that this would lead to in the NLSE is given by $\\delta \\phi=k_{0} \\delta n z \\propto \\sqrt {z}$, which is equivalent to the prescription for incorporating phase fluctuations into the stochastic NLSE model described in Sec.\\ 2.3, namely,  $\\langle \\Delta \\phi^2 \\rangle = 6.7 \\times 10^{-3}z$. Hart {\\it et al}.\\ \\cite{hart1} used the same prescription and the same noise strength in their truncated-ODE model. From this we can estimate the level of refractive index fluctuation that corresponds to the noise strength used in the simulations described in Sec.\\ 2.3 \r\n%B.18\r\n\\begin{eqnarray}\r\n\\langle \\Delta n^2 \\rangle = {6.7 \\times 10^{-3} \\over k_0^2} = 6.78 \\times 10^{-17} \\nonumber\\\\\r\n\\equiv \\langle \\Delta T^{2} \\rangle \\sim 10^{-6}~{^\\circ}C^2 \\equiv \\Delta T \\sim 10^{-3}~{^\\circ}C \r\n\\end{eqnarray}\r\n\r\nThe temperature coefficient of the refractive index of silica \\cite{glenn}, \r\n$(\\partial n / \\partial T)_{\\rho} \\sim 10^{-5} ~{^\\circ}C^{-1}$. Thus even small spatio-temporal temperature fluctuations of $\\sim 10^{-3} ~{^\\circ}C$ are enough to cause the inferred level of refractive index fluctuations.\r\n\r\nThe refractive index fluctuations could also be due to inhomogeneities in the \r\ndensity of the fiber material, frozen in at the time of manufacture of the \r\nfiber. The simulations were averaged over $\\sim$ 600 iterations to get a good \r\nestimate of the power fluctuations in the sidebands. Initially, simulations \r\nwere performed with a different phase noise distribution for each iteration. \r\nLater, a particular (arbitrary) phase noise distribution was selected and \r\nfrozen for all the iterations.\r\nThis did not reduce the level of damping observed in the sideband trajectories \r\nprovided that the strength of the phase noise was kept the same, thus \r\nindicating that density fluctuations induced during fiber manufacture could be \r\na possible source. The phase noise was modeled as $\\delta$-correlated in\r\nboth space and time. A more realistic approach would be to use correlated\r\nnoise. Numerical methods to incorporate linear multiplicative correlated noise \r\ninto the NLSE have been developed by M.J. Werner {\\it et al}.\\ \\cite{werner2}.\r\n\r\n\\section{Conclusions}\r\n\r\nThe role of stochasticity in the dynamical evolution of four-wave-mixing \r\nprocesses in an optical fiber has been investigated. This research consisted \r\nof theoretical and numerical computations. It focuses on tracing the evolution \r\nof the sidebands, generated through FWM, along a length of optical fiber. \r\nDetailed comparisons were made with the experimental results of \r\nHart {\\it et al}.\\ \\cite{hart1} and the agreement was excellent. The present work \r\nuses numerical techniques that have much higher resolution and better \r\nefficiency, and it presents a theoretical basis for the role of the \r\nstochasticity in the dynamics. The system is known to be governed by the \r\nnonlinear Schr\\\"odinger equation (NLSE) to a very good \r\napproximation \\cite{Agrawal2}. \r\n\r\nA powerful technique that can be used for simulations of the stochastic NLSE \r\nis the Split-step Fourier Method (SSFM) \\cite{Agrawal2}. An algorithm for the \r\ndirect implementation of stochastic processes along the length of the fiber in \r\nthe SSFM has been developed. The advantages of this approach with respect to \r\nthe coupled-ODE approach are that we can carry out simulations with much \r\nhigher frequency and time resolution without sacrificing computational \r\nefficiency.\r\n \r\nThe physical sources of these stochastic phase fluctuations are investigated \r\nquantitatively and are identified to be due to fluctuations in the linear \r\nrefractive index of the fiber. Strong candidates for the causes of these \r\nrefractive index fluctuations are temperature fluctuations in the fiber medium \r\ncaused by the fluctuating temperature of the fiber environment, density \r\nfluctuations in the fiber medium frozen into the fiber during manufacture, and \r\nintrinsic thermodynamic fluctuations in the temperature and density of the \r\nfiber.  \r\n\r\nThe experiments performed by Hart {\\it et al}.\\ \\cite{hart1} can be used to \r\ndetermine the level of these refractive index fluctuations in commercial \r\nfibers. Results described in Figs.\\ 2 and 3 represent a destructive \r\nexperiment that measures the sideband evolution with fiber length for a fixed \r\ninput pump power, necessarily requiring the fiber to be cut repeatedly. The \r\nlevel of refractive index fluctuations can be used as a parameter in the \r\nsimulations to best fit the experimental results. Alternatively, Fig.\\ 4 \r\nrepresents a non-destructive experiment that measures the sideband evolution \r\nwith input pump power for a fixed fiber length. These experiments are found to \r\nbe effective for estimating the refractive index fluctuations, as the dynamics \r\nis observed to be sensitively dependent on the strength of the phase \r\nfluctuations. \r\n\r\n", "meta": {"hexsha": "294f00e572796b1df3b1de5a8fbd1ee003830bbe", "size": 45599, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "AppendixB.tex", "max_stars_repo_name": "cmhill/dissertation", "max_stars_repo_head_hexsha": "eddb7f6aa5de14aacce98d6172eec30a8bca379e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-10-05T12:13:13.000Z", "max_stars_repo_stars_event_max_datetime": "2016-10-07T23:12:04.000Z", "max_issues_repo_path": "AppendixB.tex", "max_issues_repo_name": "cmhill/dissertation", "max_issues_repo_head_hexsha": "eddb7f6aa5de14aacce98d6172eec30a8bca379e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AppendixB.tex", "max_forks_repo_name": "cmhill/dissertation", "max_forks_repo_head_hexsha": "eddb7f6aa5de14aacce98d6172eec30a8bca379e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 60.476127321, "max_line_length": 1292, "alphanum_fraction": 0.7473190202, "num_tokens": 12260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3289301109503505}}
{"text": "\\documentclass{article}\r\n\r\n\\usepackage{fancyhdr}\r\n\\usepackage{extramarks}\r\n\\usepackage{amsfonts}\r\n\\usepackage{syntax}\r\n\\usepackage{stmaryrd}\r\n\\usepackage{mathpartir}\r\n\r\n%\r\n% Basic Document Settings\r\n%\r\n\r\n\\topmargin=-0.45in\r\n\\evensidemargin=0in\r\n\\oddsidemargin=0in\r\n\\textwidth=6.5in\r\n\\textheight=9.0in\r\n\\headsep=0.25in\r\n\r\n\\linespread{1.1}\r\n\r\n\\pagestyle{fancy}\r\n\\chead{Tuple Unboxing}\r\n\\lfoot{\\lastxmark}\r\n\\cfoot{\\thepage}\r\n\r\n\\renewcommand\\headrulewidth{0.4pt}\r\n\\renewcommand\\footrulewidth{0.4pt}\r\n\r\n\\setlength\\parindent{30pt}\r\n\r\n\\newcommand{\\Z}{\\mathbb{Z}}\r\n\\newcommand{\\Zt}{$\\Z$}\r\n\r\n% Create a relational rule\r\n% [#1] - Additional mathpartir arguments\r\n% {#2} - Name of the rule\r\n% {#3} - Premises for the rule\r\n% {#4} - Conclusions for the rule\r\n\\newcommand{\\relationRule}[4][]{\\inferrule*[lab={\\sc #2},#1]{#3}{#4}}\r\n\r\n\\newcommand{\\rel}[1]{\\ensuremath{\\llbracket {#1} \\rrbracket}}\r\n\\newcommand{\\ttt}{\\texttt}\r\n\\newcommand{\\transform}{\\rightsquigarrow}\r\n\\newcommand{\\proj}{\\pi}\r\n\\newcommand{\\ttuple}{\\tau_1 * \\ldots * \\tau_n}\r\n\\newcommand{\\etuple}{(e_1,\\ldots,e_n)}\r\n\r\n\r\n\\begin{document}\r\nThis document defines a transformation $\\transform$, such that every\r\nexpression with a tuple type is a tuple expression. The following invariant\r\nshould hold after this transformation:\r\n$$ \\Gamma \\vdash e : \\ttuple \\rightarrow e = \\etuple$$\r\n\r\nFor defining tuple unboxing we add a tuple projection construct\r\nin the language $\\proj_i$.\r\n\r\n\\section*{Values}\r\n\r\n\\begin{mathpar}\r\n\t\\relationRule{identifer - tuple}{\r\n\t\t\\null\r\n\t}{\r\n\t\t\\Gamma \\vdash x : \\ttuple \\transform (\\proj_1 x, \\ldots, \\proj_n x)\r\n\t}\r\n\\end{mathpar}\r\n\r\n\\begin{mathpar}\r\n\t\\relationRule{identifer}{\r\n\t\t\\tau \\neq \\ttuple\r\n\t}{\r\n\t\t\\Gamma \\vdash x : \\tau \\transform x\r\n\t}\r\n\\end{mathpar}\r\n\r\n\\begin{mathpar}\r\n\t\\relationRule{literal}{\r\n\t\t\\tau \\in \\{\\texttt{bool}, \\texttt{int}\\}\r\n\t}{\r\n          \\Gamma \\vdash n : \\tau \\transform n\r\n\t}\r\n\\end{mathpar}\r\n\r\n\\begin{mathpar}\r\n\t\\relationRule{Function}{\r\n          e \\transforms e'\r\n\t}{\r\n\t\t\\Gamma \\vdash \\texttt{fun}\\ x \\to e : \\tau_1 \\to \\tau_2 \\transforms \\ttt{fun}\\ x \\to e'\r\n\t}\r\n\\end{mathpar}\r\n\r\n\\section*{Expressions}\r\n\r\n\r\n\\begin{mathpar}\r\n\t\\relationRule{Tuple}{\r\n\t\t\\null\r\n\t}{\r\n          \\Gamma \\vdash \\etuple : \\tau \\transform \\etuple\r\n\t}\r\n\\end{mathpar}\r\n\r\n\\begin{mathpar}\r\n\t\\relationRule{Not}{\r\n          e \\transforms e'\r\n\t}{\r\n\t\t\\Gamma \\vdash !e : \\tau \\transforms !e'\t\r\n\t}\r\n\\end{mathpar}\r\n\t\r\n\\begin{mathpar}\r\n\\relationRule{Binop}{\r\n\t \\oplus \\mbox{ is a binary operator} \\\\ e_1 \\transforms e_1' \\\\ e_2 \\transforms e_2'\r\n   }{\r\n   \t\\Gamma \\vdash e_1 \\oplus e_2 : \\tau \\transforms e_1' \\oplus e_2'\r\n   }\r\n\\end{mathpar}\r\n\r\n\\begin{mathpar}\r\n\t\\relationRule{Function application}{\r\n\t\te_1 \\transforms e_1' \\\\ e_2 \\transforms e_2'\r\n\t}{\r\n\t\t\\Gamma \\vdash e_1 e_2 : \\tau \\transforms e_1' e_2'\t\r\n\t}\r\n\\end{mathpar}\r\n\r\n\\begin{mathpar}\r\n\t\\relationRule{Let-binding-tuple}{\r\n          e_1 \\transforms e_1' \\\\ e_2 \\transforms (e_{21},\\ldots,e_{2n})\r\n\t}{\r\n\t\t\\Gamma \\vdash \\ttt{let}\\ p = e_1\\ \\ttt{in}\\ e_2 : \\ttuple \\transforms \r\n                (\\ttt{let}\\ p = \\ e_1' \\ttt{in}\\ e_{21},\\ldots,\\ttt{let}\\ p = \\ e_1' \\ttt{in}\\ e_{2n})\r\n\t}\r\n\\end{mathpar}\r\n\r\n\\begin{mathpar}\r\n\t\\relationRule{Let-binding}{\r\n          \\tau \\neq \\ttuple \\\\ e_1 \\transforms e_1' \\\\ e_2 \\transforms e_2'\r\n\t}{\r\n\t\t\\Gamma \\vdash \\ttt{let}\\ p = e_1\\ \\ttt{in}\\ e_2 : \\tau \\transforms \\ttt{let}\\ p = \\ e_1' \\ttt{in}\\ e_2'\t\r\n\t}\r\n\\end{mathpar}\r\n\r\n\\begin{mathpar}\r\n\t\\relationRule{Match-Tuple}{\r\n          e \\transforms e' \\\\ e_1 \\transforms (e_{11},\\ldots,e_{1n}) \\\\ \\ldots \\\\ (e_{k1},\\ldots,e_{kn})\r\n\t}{\r\n\t\t\\Gamma \\vdash \\ttt{match}\\ e\\ \\ttt{with}\\ |\\ p_1 \\to e_1 \\dots |\\ p_k \\to e_k : \\ttuple \\transforms \r\n\t\t(\\ttt{match}\\ e'\\ \\ttt{with}\\ |\\ p_1 \\to e_{11} \\dots |\\ p_k \\to e_{k1}, \\ldots,\r\n                \\ttt{match}\\ e'\\ \\ttt{with}\\ |\\ p_1 \\to e_{1n} \\dots |\\ p_k \\to e_{kn})\r\n\t}\r\n\\end{mathpar}\r\n\r\n\\begin{mathpar}\r\n\t\\relationRule{Match}{\r\n          \\tau \\neq \\ttuple \\\\ e \\transforms e' \\\\ e_1\r\n\t}{\r\n          \\Gamma \\vdash \\ttt{match}\\ e\\ \\ttt{with}\\ |\\ p_1 \\to e_1 \\dots |\\ p_k \\to e_k : \\tau = \r\n\t\t\\ttt{match}\\ e'\\ \\ttt{with}\\ |\\ p_1 \\to e_1' \\dots |\\ p_k \\to \\rel{e_k}\r\n\t}\r\n\\end{mathpar}\r\n\r\n\\begin{mathpar}\r\n\t\\relationRule{If-else}{\r\n\t\t\\null\r\n\t}{\r\n\t\t\\rel{\\ttt{if}\\ e_1\\ \\ttt{then}\\ e_2\\ \\ttt{else}\\ e_3} = \r\n\t\t\\ttt{if}\\ \\rel{e_1}\\ \\ttt{then}\\ \\rel{e_2}\\ \\ttt{else}\\ \\rel{e_3}\r\n\t}\r\n\\end{mathpar}\r\n\r\n\\section*{Declarations}\r\n\r\n\\begin{mathpar}\r\n\t\\relationRule{Let declaration}{\r\n\t\t\\null\r\n\t}{\r\n\t\t\\rel{\\ttt{let}\\ x = e} = \\ttt{let}\\ x = \\rel{e}\r\n\t}\r\n\\end{mathpar}\r\n\r\n\\begin{mathpar}\r\n\t\\relationRule{Attribute type - not $\\tau_m$}{\r\n\t\t\\tau \\neq \\tau_m\r\n\t}{\r\n\t\t\\rel{\\ttt{type attribute} = \\tau} = \\ttt{type attribute} = \\tau\r\n\t}\r\n\\end{mathpar}\r\n\r\n\r\n\\begin{mathpar}\r\n\t\\relationRule{Attribute type - $\\tau_m$}{\r\n\t\t\\null\r\n\t}{\r\n\t\t\\rel{\\ttt{type attribute} = \\tau_m} = \\ttt{type attribute} = \\tau_t\r\n\t}\r\n\\end{mathpar}\r\n\r\n\\begin{mathpar}\r\n\t\\relationRule{Symbolic type - not $\\tau_m$}{\r\n\t\t\\tau \\neq \\tau_m\r\n\t}{\r\n\t\t\\rel{\\ttt{symbolic}\\ x : \\tau} = \\ttt{symbolic}\\ x : \\tau\r\n\t}\r\n\\end{mathpar}\r\n\r\n\\begin{mathpar}\r\n\t\\relationRule{Symbolic type - $\\tau_m$}{\r\n\t\t\\null\r\n\t}{\r\n\t\t\\rel{\\ttt{symbolic}\\ x : \\tau_m} = \\ttt{symbolic}\\ x : \\tau_t\r\n\t}\r\n\\end{mathpar}\r\n\r\n\\begin{mathpar}\r\n\t\\relationRule{Symbolic value}{\r\n\t\t\\null\r\n\t}{\r\n\t\t\\rel{\\ttt{symbolic}\\ x = e} = \\ttt{symbolic}\\ x = \\rel{e}\r\n\t}\r\n\\end{mathpar}\r\n\r\n\\begin{mathpar}\r\n\t\\relationRule{Require}{\r\n\t\t\\null\r\n\t}{\r\n\t\t\\rel{\\ttt{require}\\ e} = \\ttt{require}\\ \\rel{e}\r\n\t}\r\n\\end{mathpar}\r\n\r\n\\begin{mathpar}\r\n\t\\relationRule{Node declaration}{\r\n\t\t\\null\r\n\t}{\r\n\t\t\\rel{\\ttt{let nodes} = n} = \\ttt{let nodes}\\ = n\r\n\t}\r\n\\end{mathpar}\r\n\r\n\\begin{mathpar}\r\n\t\\relationRule{Edge declaration}{\r\n\t\t\\null\r\n\t}{\r\n\t\t\\rel{\\ttt{let edges} = lst} = \\ttt{let edges}\\ = lst\r\n\t}\r\n\\end{mathpar}\r\n\r\n\\section*{Map expressions}\r\nEach of the following expressions have at least one subexpression which must be a map. The following rules apply if and only if those subexpressions have type $\\tau_m$. If not, we recurse as usual but don't otherwise change the expression.\r\n\r\nI'm noting that some of these rules involve a lot of duplication, so we might want to look into translations\r\nwhich e.g. store duplicated expressions in a local variable first.\r\n\r\nThey also involve a lot of extra unpacking since we don't have syntax for getting/setting with tuples. It\r\nwould probably be good to extend the map syntax to work on tuples as well, so long as that doesn't mess\r\nanything up; we could also create a new syntax for tuples.\r\n\r\n\\begin{mathpar}\r\n\t\\relationRule{CreateDict}{\r\n\t\te' = \\rel{e}\r\n\t}{\r\n\t\t\\rel{\\ttt{createDict}\\ e} = (e', \\dots, e')\t\r\n\t}\r\n\\end{mathpar}\r\n\r\n\\begin{mathpar}\r\n\t\\relationRule{Get}{\r\n\t\tk = k_i \\\\\r\n\t\tx_i \\mbox{ fresh}\r\n\t}{\r\n\t\t\\rel{m[k_i]} = \r\n\t\t\\ttt{let}\\ (\\_, \\dots, x_i, \\dots, \\_) = \\rel{m}\\ \\ttt{in}\\ \r\n\t\tx_i\r\n\t}\r\n\\end{mathpar}\r\n\r\n\\begin{mathpar}\r\n\t\\relationRule{Set - known key}{\r\n\t\tk = k_i \\\\\r\n\t\tx_1, \\dots, x_n \\mbox{ fresh}\r\n\t}{\r\n\t\t\\rel{m[k := e]} = \r\n\t\t\\ttt{let}\\ (x_1, \\dots, x_n) = \\rel{m}\\ \\ttt{in}\\ \r\n\t\t(x_1, \\dots, \\rel{e}, \\dots, x_n)\r\n\t}\r\n\\end{mathpar}\r\n\r\n\\begin{mathpar}\r\n\t\\relationRule{Set - unknown key}{\r\n\t\t\\forall i.k \\neq k_i \\\\\r\n\t\tx_1, \\dots, x_n \\mbox{ fresh}\r\n\t}{\r\n\t\t\\rel{m[k := e]} = \\rel{m}\r\n\t}\r\n\\end{mathpar}\r\n\r\n\\begin{mathpar}\r\n\t\\relationRule{Map}{\r\n\t\tf' = \\rel{f} \\\\\r\n\t\tx_1, \\dots, x_n \\mbox{ fresh}\r\n\t}{\r\n\t\t\\rel{\\ttt{map}\\ f\\ m} = \r\n\t\t\\ttt{let}\\ (x_1, \\dots, x_n) = \\rel{m}\\ \\ttt{in}\\ \r\n\t\t(f'\\ x_1, \\dots, f'\\ x_n)\r\n\t}\r\n\\end{mathpar}\r\n\r\n\\begin{mathpar}\r\n\t\\relationRule{MapIf}{\r\n\t\tf' = \\ttt{fun}\\ (k, v)\\ \\to \\ttt{if}\\ p\\ k\\ \\ttt{then}\\ \\rel{f}\\ v\\ \\ttt{else}\\ v \\\\\r\n\t\tx_1, \\dots, x_n \\mbox{ fresh}\r\n\t}{\r\n\t\t\\rel{\\ttt{mapIf}\\ p\\ f\\ m} = \r\n\t\t\\ttt{let}\\ (x_1, \\dots, x_n) = \\rel{m}\\ \\ttt{in}\\ \r\n\t\t(f'\\ (k_1, x_1), \\dots, f'\\ (k_n, x_n))\r\n\t}\r\n\\end{mathpar}\r\n\r\n\\begin{mathpar}\r\n\t\\relationRule{Filter}{\r\n\t\tp' = \\ttt{fun}\\ (k, v)\\ \\to \\ttt{if}\\ p\\ k\\ \\ttt{then}\\ v\\ \\ttt{else}\\ \\ttt{false} \\\\\r\n\t\tx_1, \\dots, x_n \\mbox{ fresh}\r\n\t}{\r\n\t\t\\rel{\\ttt{filter}\\ p\\ m} = \r\n\t\t\\ttt{let}\\ (x_1, \\dots, x_n) = \\rel{m}\\ \\ttt{in}\\ \r\n\t\t(p'\\ (k_1, x_1), \\dots, p'\\ (k_n, x_n))\r\n\t}\r\n\\end{mathpar}\r\n\r\n\\begin{mathpar}\r\n\t\\relationRule{Combine}{\r\n\t\tf' = \\rel{f} \\\\\r\n\t\tx_1, \\dots, x_n, y_1, \\dots y_n \\mbox{ fresh}\r\n\t}{\r\n\t\t\\rel{\\ttt{combine}\\ f\\ m_1\\ m_2} = \r\n\t\t\\ttt{let}\\ ( x_1, \\dots, x_n) = \\rel{m_1}\\ \\ttt{in}\\ \r\n\t\t\\ttt {let}\\ (y_1, \\dots,  y_n) = \\rel{m_2}\\ \\ttt{in}\\ \\\\ \r\n\t\t(f'\\ x_1\\ y_1, \\dots, f'\\ x_n\\ y_n))\r\n\t}\r\n\\end{mathpar}\r\n\r\n\\begin{mathpar}\r\n\t\\relationRule{Union}{\r\n\t\tf' = \\rel{f} \\\\\r\n\t\tx_1, \\dots, x_n, y_1, \\dots y_n \\mbox{ fresh}\r\n\t}{\r\n\t\t\\rel{m_1\\ \\ttt{union}\\ m_2} = \r\n\t\t\\ttt{let}\\ (x_1, \\dots, x_n) = \\rel{m_1}\\ \\ttt{in}\\ \r\n\t\t\\ttt{let}\\ (y_1, \\dots, y_n) = \\rel{m_2}\\ \\ttt{in}\\\r\n\t\t(x_1\\ \\|\\ y_1, \\dots, x_n\\ \\|\\ y_n)\r\n\t}\r\n\\end{mathpar}\r\n\r\n\r\n\\begin{mathpar}\r\n\t\\relationRule{Intersection}{\r\n\t\tf' = \\rel{f} \\\\\r\n\t\tx_1, \\dots, x_n, y_1, \\dots y_n \\mbox{ fresh}\r\n\t}{\r\n\t\t\\rel{m_1\\ \\ttt{inter}\\ m_2} = \r\n\t\t\\ttt{let}\\ (x_1, \\dots, x_n) = \\rel{m_1}\\ \\ttt{in}\\ \r\n\t\t\\ttt{let}\\ (y_1, \\dots, y_n) = \\rel{m_2}\\ \\ttt{in}\\\r\n\t\t(x_1\\ \\&\\&\\ y_1, \\dots, x_n\\ \\&\\&\\ y_n)\r\n\t}\r\n\\end{mathpar}\r\n\r\n\\end{document}", "meta": {"hexsha": "03581cc829de88dbfd440d952f0463f1a68a9f4b", "size": 9069, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "specs/tuple unboxing.tex", "max_stars_repo_name": "NetworkVerification/nv", "max_stars_repo_head_hexsha": "0a9d69e08142cd894a1594674edb5fbca7a4f8b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2020-03-05T23:45:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T10:28:44.000Z", "max_issues_repo_path": "specs/tuple unboxing.tex", "max_issues_repo_name": "princedpw/nv", "max_issues_repo_head_hexsha": "a82b2b4530d41ece98bd39c5d7ecb18c1dfaf9b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 43, "max_issues_repo_issues_event_min_datetime": "2018-10-01T13:12:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-14T17:55:54.000Z", "max_forks_repo_path": "specs/tuple unboxing.tex", "max_forks_repo_name": "NetworkVerification/nv", "max_forks_repo_head_hexsha": "0a9d69e08142cd894a1594674edb5fbca7a4f8b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-07-12T18:33:19.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-30T02:15:07.000Z", "avg_line_length": 24.6440217391, "max_line_length": 240, "alphanum_fraction": 0.5877163965, "num_tokens": 3703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.32879269837837494}}
{"text": "%************************************************\n\\chapter{Protocol Design}\\label{ch:protocol}\n%************************************************\n\n\n% What is the goals of an adversary?\n% - Be able to forge authentication\n% - Be able to link different identities to the same user.\n% - Be able to use/hijack an active session\n\n\nIn the previous chapter, we present a design for a \\gls{cta} authentication scheme. In this chapter we will present a protocol, which is simply a sequence of well-chosen messages, that can support this scheme. In this chapter, we will only highlight a few important properties from the previous chapter in regards to certain choices, and will then later evaluate which properties the proposed protocol achieves.\n\n\\section{Definition of Authentication}\n\nSo far we have not clearly defined what `authentication' actually entails. In his well-renowned article ``A Hierarchy of Authentication Specifications'' \\citet{lowe1997hierarchy} puts forward the following definition:\n\n\\begin{definition}[Injective Agreement]\nWe say that a protocol guarantees to an initiator $A$ agreement with a responder $B$ on a set of data items $ds$ if, whenever $A$ (acting as initiator) completes a run of the protocol, apparently with responder $B$ , then $B$ has previously been running the protocol, apparently with $A$, and $B$ was acting as responder in his run, and the two agents agreed on the data values corresponding to all the variables in $ds$, and each such run of $A$ corresponds to a unique run of $B$.\n\\end{definition}\n\nThis definition infer that if two parties agree on a set of data (or evidence of identity), and if there is a one-to-one relationship between the protocol run at the responder and verifier, then they achieve (injective) agreement, and thus the responder authenticates with the verifier.\n\n\\section{Design Rationale}\nOur design inspires from this definition, and effectively, the \\gls{server} $S$, will on request from the \\gls{client} $C$, issue a fresh challenge. If the client can reply with a proper response to the challenge then it should be authenticated for a given period of time. Let us consider a simple example in which the \\gls{server} encrypts a random nonce with the public-key of the \\gls{client}, and sends the cipher to the client. The client then decrypts the cipher and responds to the challenge with the recovered nonce.\n{\\setlength{\\mathindent}{0cm}\n\\begin{align}\n    \\tag{message 1} && S \\rightarrow C &: enc(n,pk_c)\\\\\n    \\tag{message 2} && C \\rightarrow S &: n\n\\end{align}}\n\nOnly an actor in possession of $sk_c$ would be able to recover the correct answer, and thus presenting $n$, serves as evidence of knowing $sk_c$. This can be used to authenticate if the server links the public key to a user-identity. This will serve as a starting point for this protocol. However, a few design features from the previous chapter needs to be considered:\n\\begin{itemize}\n    \\item The \\gls{client} should ask the \\gls{authenticator} for `permission' to authenticate.\n    \\item The \\gls{authenticator} should only give permission if unlocked; thus in range of the \\gls{sibling}.\n    \\item The \\gls{client} should not be exposed to any piece of information that could be used in a later successful round of authentication. \n    \\item  Hijacking an active session or token should not give an \\gls{adversary} unauthorized access for longer than the session is actively kept alive by the \\gls{server} and \\gls{authenticator}.\n\\end{itemize}\n\nIn the design, we mention that the \\gls{authenticator} can be in a state of either unlocked, locked or lockdown. In practice, we take a different approach to implementing these states. As we envision using general-purpose commodity platforms such as e.g. iOS and Android devices, compromised devices are a concern that should be inherently designed for, and solely trusting a single device to uphold these states is therefore not an option.\n\n\\subsection{Distributed Authentication}\n\n\nTo ensure that \\gls{authenticator} and \\gls{sibling} are always involved in an authentication run, the unlocked state will in practice be implemented by forcing the \\gls{authenticator} and \\gls{sibling} to collaborate, in computing the response to an authentication challenge. If communication between \\gls{authenticator}, \\gls{sibling} and \\gls{client} are forced onto a local channel (such as Bluetooth), then authentication is only possible when all three devices are in each others proximity.\\\\\n\nIn comparison, Pico~\\cite{stajano2011pico} functions by having a main device, the Pico, that is the users key-store. The key-store is encrypted with a \\textit{$k$-out-of-$n$} threshold encryption system. This means that at least $k$ siblings (small wearable tokens) must be in its vicinity for it to unlock. On request from the Pico, the siblings send their key-share, allowing the Pico to unlock its key-store. An assumption is made on the Pico, that it periodically `forgets' the key, thus forcing it to continuously interact with its siblings.\n\nWe see this as a problem because if the Pico is compromised in the unlocked state, then \\textit{all} of the user's services are compromised. In the original paper, it is assumed that an adversary is not capable of compromising the Pico in the unlocked state. This is an unrealistic assumption when using general-purpose devices.\n\nThe rationale behind having a central unit holding all keys, and having peripheral devices unlocking, instead of having all devices actively participate, was taken with consideration to the technical limitations of wearables~\\cite{stannard2012good}. However, since the Pico was proposed in 2011, these limitations are diminishing, and modern wearables are now fully capable of making cryptographic calculations without draining their battery.\\\\\n\nThe collaboration between \\gls{authenticator} and \\gls{sibling} can be achieved with `secure multiparty computations' (MPC). MPC entails a group of agents jointly computing a function, such as decrypting a cipher, without revealing anything about their individual input to the function. Furthermore, only with full participation from all actors will the output of the function be meaningful. This means that both devices would have to be compromised, for an adversary to be able to obtain the secrets needed to compromise the user's services. In practice, MPC can be implemented by utilizing a partial crypto system.\\\\\n\n\n\n\n\n\\begin{comment}\n\\paragraph{Security Goals}\n\\begin{itemize}\n\n    \\item An adversary should not be able to forge evidence of identity without compromising the secrets of both \\gls{authenticator} and \\gls{sibling}.\n    \n    \\item Hijacking an active session or token should not give the \\gls{adversary} unauthorized access for longer than the session is actively kept alive by the \\gls{server} and \\gls{authenticator}.\n    \n\\end{itemize}\n\\end{comment}\n\n\\section{Partial Crypto Systems}\n\nA partial crypto systems is a system in which multiple actors have to collaborate to encrypt and decrypt messages. Such systems are useful because they ensure that even if one of the actors is compromised, then the system is not compromised. Many such systems exists, but in this section we will present Distributed ElGamal, which is a partial crypto system~\\cite{brandt2005efficient}.\n\n\n\\paragraph{ElGamal Crypto System}\n\nElGamal is a probabilistic and homomorphic public-key crypto system based on the Diffie-Hellman assumption. ElGamal is secure against \\Glspl{cpa} (\\acrshort{cpa}), if the Decisional Diffie–Hellman (DDH) problem is hard~\\cite[page 400]{katz2014introduction}.\n\nUsing the cyclic prime order groups, as defined in section~\\ref{par:cyclic}, we can define ElGamal in the following way:\n\n\\begin{itemize}\n    \\item \\textbf{Gen:} on input $1^n$ run $\\mathcal{G}(1^n)$ to obtain a cyclic group $\\langle \\mathbb{G},q,g \\rangle$. Then choose a uniform $x \\in \\mathbb{Z}_q$ and compute $y := g^x$. Then output the public-key $\\langle \\mathbb{G},q,g,y \\rangle$ and the private-key $\\langle \\mathbb{G},q,g,x \\rangle$\n    \n    \\item \\textbf{Enc:} on input of a public-key and a message $m \\in \\mathbb{G}$, choose a uniform $r \\in \\mathbb{Z}_q$ and output the ciphertext $c := ( my^r, g^r )$.\n    \n    %\\begin{align*}\n    %    && \\langle m\\cdot y^r, g^r \\rangle\n    %\\end{align*}\n    \n    \\item \\textbf{Dec:} on input of a private-key and a ciphertext $c = ( \\alpha, \\beta )$, output the message $m := \\alpha / \\beta^x$.\n    \n    %\\begin{align*}\n    %    && m := \\alpha / \\beta^x\n    %\\end{align*}\n\\end{itemize}\n\n\\paragraph{Distributed ElGamal}\\label{sec:deg}\n\nThe distributed variant of ElGamal leverages that the original crypto system is homomorphic. Although the system is homomorphic over both message and keys for both encryption and descryption, the following is focused on homomorphism over the keys for decryption\\footnote{For some set of operators `$+$' and `$\\times$'}. \n{\\setlength{\\mathindent}{0cm}\n\\begin{align*}\n&&    Dec(c,sk_1) \\times Dec(c,sk_2) = Dec(c,sk_1 + sk_2)\n\\end{align*}}\\vspace{-1em}\n\nLet each participating actor $i$ in the distributed system generate an ElGamal key-pair $( pk_i, sk_i )$, using the same cyclic group $\\langle \\mathbb{G}, q, g \\rangle$, by choosing an uniform $x_i \\in \\mathbb{Z}_q$ and calculating $y_i = g^{x_i}$~\\cite{brandt2005efficient}. The joint public and private-key is now given as: \n{\\setlength{\\mathindent}{0cm}\n\\begin{align*}\n&& y = \\prod^n_{i=1} y_i && x = \\sum^n_{i=1} x_i\n\\end{align*}}\n\nAn encrypted message $Enc(m,pk) \\rightarrow ( \\alpha, \\beta )$ can be jointly decrypted by each participant calculating $\\beta^{x_i}$. The message can then be recovered as:\n{\\setlength{\\mathindent}{0cm}\n\\begin{align*}\n&&    m := \\frac{\\alpha}{\\prod^n_{i=1} \\beta^{x_i}} = \\frac{\\alpha}{\\beta^{x}}\n\\end{align*}}\n\nThe advantage of this is that the computation and sharing of $\\beta^{x_i}$, following the DDH assumption, does not leak any information about the private-keys. Neither does the shares leak any information about the encrypted message before all shares are combined. We define the new operations as:\n\\begin{itemize}\n\n    \\item \\textbf{Gen':} on input of a cyclic group $\\langle \\mathbb{G}, q, g \\rangle$, choose a uniform $x \\in \\mathbb{Z}_q$ and calculate $y = g^{x}$. Then output the public-key $\\langle \\mathbb{G},q,g,y \\rangle$ and the private-key $\\langle \\mathbb{G},q,g,x \\rangle$\n\n    \\item \\textbf{Dec':} on input of a private-key and a ciphertext $c = ( \\alpha, \\beta )$, output the partial decryption $c' := ( \\alpha, \\beta^{x_i} )$\n    \n    \\item \\textbf{Combine:} on input of two partially decrypted ciphertexts $c'_1 = ( \\alpha, \\beta^{x_1} )$ and $c'_2 = ( \\alpha, \\beta^{x_2} )$\\marginpar{notice that the $\\alpha$'s must match}, output\n    {\\setlength{\\mathindent}{0cm} \n    \\begin{align*}\n    && c' := \\left( \\alpha, \\beta^{x_1} \\cdot \\beta^{x_2} \\right) = \\left( \\alpha, \\beta^{{x_1}+{x_2}} \\right)\n    \\end{align*}}\\vspace{-2em}\n    \n    \\item \\textbf{Recover:} on input of a partially decrypted ciphertext $c' = ( \\alpha, \\beta^x )$, output the message $m := \\alpha / \\beta^x$\n    \n\\end{itemize}\n\nWe denote the recovery of a message from combining partially decrypted ciphers as $m := Dec'(\\cdot) \\times Dec'(\\cdot)$. Furthermore, we denote the product of public-keys as $pk := pk_1 \\times pk_2$.\n\n\\section{The Protocol}\n\nTwo steps of the protocol has to be defined. A \\gls{registration} and \\gls{authentication} step. The purpose of the registration step is to establish a set of shared knowledge. The purpose of the authentication step is to provide the \\gls{server} with evidence, and for the \\gls{server} to be able to verify the authenticity of the evidence based on the knowledge acquired during the registration. The proposed protocol builds on the Distributed ElGamal crypto system as presented in the previous section.\n\n\n\\subsection{Registration}\n\nThe registration is initiated by the \\gls{client} (and thus the end-user) by sending a message to the \\gls{authenticator} with a universally unique user-id (such as a uuid\\footnote{See \\url{https://en.wikipedia.org/wiki/Universally_unique_identifier}}). The \\gls{client} might have asked the \\gls{server} in advance to issue this id based on some data such as a username. The \\gls{authenticator} then forwards the message to the \\gls{sibling} and starts computing a new Distributed ElGamal key-pair. The \\gls{sibling} also computes a new Distributed ElGamal key-pair and sends its public-key to the \\gls{authenticator}. The \\gls{authenticator} now combines the keys to a joint public-key and sends it back to the \\gls{client}. Lastly the \\gls{client} sends the new public-key to the server along with the user-id. This is shown in figure~\\ref{msc:register}.\n\n\\begin{figure}[bth]\n\\centering\n\\resizebox{\\linewidth}{!}{\n\\begin{msc}{Registration}\n\n\\setlength{\\instdist}{1.5cm}\n\\setlength{\\actionwidth}{3cm}\n\n\\declinst{as}{}{$As$} \n\\declinst{a}{}{$A$} \n\\declinst{c}{}{$C$}\n\\declinst{s}{}{$S$} \n\n\\nextlevel\n\\mess{$username$}{c}{s}\n\\nextlevel[2]\n\\mess{$id$}{s}{c}\n\\nextlevel\n\\mess{$id$}{c}{a}\n\\nextlevel\n\\mess{$id$}{a}{as}\n\\nextlevel\n\\action{Generate $( pk_{A}, sk_{A} )$}{a}\n\\action{Generate $( pk_{As}, sk_{As} )$}{as}\n\\nextlevel[4]\n\\mess{$pk_{As}$}{as}{a}\n\\nextlevel\n\\action{$pk = pk_A \\times pk_{As}$}{a}\n\\nextlevel[4]\n\\mess{$id, pk$}{a}{c}\n\\nextlevel\n\\mess{$id, pk$}{c}{s}\n\\nextlevel\n\n\\end{msc}}\n\\caption[Registration sequence diagram]{The sequence of messages involved in a successful registration.}\n\\label{msc:register}\n\\end{figure}\n\n\\subsection{Authentication}\nAuthentication is initiated by the \\gls{client} by sending an authentication request with a user-id to the \\gls{server}. The \\gls{server} responds with a challenge $c \\leftarrow enc(n,pk)$, where $pk$ is the public-key corresponding to the user-id, and $n$ is an arbitrary nonce in $\\mathbb{G}$. After sending the challenge the \\gls{server} starts a timer $T$. The challenge is forwarded to the \\gls{authenticator} and \\gls{sibling} which both partly decrypts the challenge. The \\gls{sibling} sends its partial decryption to the \\gls{authenticator} which combines and recovers the nonce and sends it back to the \\gls{server}. If the received nonce is correct then the \\gls{server} issues a token to the client, valid for a given duration (in regards to the timer T). Before the token expires, the process is repeated to continuously keep the session active. This is shown in figure~\\ref{msc:auth}.\n\n\\begin{figure}[bh]\n\\centering\n\\resizebox{\\linewidth}{!}{\n\\begin{msc}{Authentication}\n\n\\setlength{\\instdist}{1.5cm}\n\\setlength{\\actionwidth}{3cm}\n\n\\declinst{as}{$\\left(sk_{As}\\right)$}{$As$} \n\\declinst{a}{$\\left(sk_{A}\\right)$}{$A$} \n\\declinst{c}{}{$C$}\n\\declinst{s}{$\\left(pk\\right)$}{$S$} \n\n\\nextlevel\n\\mess{$id$}{c}{s}\n\\nextlevel\n\\inlinestart[1.75cm][1.75cm]{exp1}{loop}{as}{s}\n\\nextlevel\n\\action{$c \\leftarrow enc(n,pk)$}{s}\n\\nextlevel[3]\n\\settimer[r]{T}{s}\n\\nextlevel\n\\mess{$c$}{s}{c}\n\\nextlevel\n\\mess{$c, id $}{c}{a}\n\\nextlevel\n\\mess{$c, id$}{a}{as}\n\\nextlevel\n\\action{$c'_{As} = Dec'(c,sk_{As})$}{as}\n\\action{$c'_{A} = Dec'(c,sk_{A})$}{a}\n\\nextlevel[5]\n\\mess{$c'_{As}$}{as}{a}\n\\nextlevel\n\\action{$n' = c'_A \\times c'_{As}$}{a}\n\\nextlevel[3]\n\\mess{$n'$}{a}{c}\n\\nextlevel\n\\mess{$n'$}{c}{s}\n\\nextlevel\n\\action{if $n \\stackrel{?}{=} n'$ then proceed}{s}\n\\nextlevel[5]\n\\mess{$token$}{s}{c}\n\\nextlevel\n\\inlinestart[2.75cm][1.5cm]{exp2}{while $T < x$}{c}{s}\n\\nextlevel[2]\n\\mess*{$request, token$}{c}{s}\n\\nextlevel[2]\n\\mess*{$data$}{s}{c}\n\\nextlevel\n\\inlineend{exp2}\n\\nextlevel\n\\stoptimer[r]{T}{s}\n\\nextlevel\n\\inlineend{exp1}\n\\end{msc}}\n\\caption[Authentication sequence diagram]{The sequence of messages involved in a successful authentication.}\n\\label{msc:auth}\n\\end{figure}\n\n\n%*****************************************\n%*****************************************\n%*****************************************\n%*****************************************", "meta": {"hexsha": "deed8345179dc1fe8d16aeb1bc9ff742015e2051", "size": 15852, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/Chapters/Protocol.tex", "max_stars_repo_name": "cholewa1992/cta", "max_stars_repo_head_hexsha": "880b6d6fcd2826e0439ce726c5c3fad44441643e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "report/Chapters/Protocol.tex", "max_issues_repo_name": "cholewa1992/cta", "max_issues_repo_head_hexsha": "880b6d6fcd2826e0439ce726c5c3fad44441643e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/Chapters/Protocol.tex", "max_forks_repo_name": "cholewa1992/cta", "max_forks_repo_head_hexsha": "880b6d6fcd2826e0439ce726c5c3fad44441643e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 63.408, "max_line_length": 897, "alphanum_fraction": 0.7274791824, "num_tokens": 4318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.32879269837837494}}
{"text": "\\input{../templates/assignment.tex}\n\n\\usepackage{mathtools}\n\\usepackage{relsize}\n\n% Default fixed font does not support bold face\n\\DeclareFixedFont{\\ttb}{T1}{txtt}{bx}{n}{10} % for bold\n\\DeclareFixedFont{\\ttm}{T1}{txtt}{m}{n}{10}  % for normal\n\n% Custom colors\n\\definecolor{deepblue}{rgb}{0,0,0.5}\n\\definecolor{deepred}{rgb}{0.6,0,0}\n\\definecolor{deepgreen}{rgb}{0,0.5,0}\n\\definecolor{lbcolor}{rgb}{0.99,0.99,0.99}\n\n\\usepackage{listings}\n\n% Python style for highlighting\n\\newcommand\\pythonstyle{\\lstset{\nlanguage=Python,\nbasicstyle=\\ttm,\nnumbers=left,\notherkeywords={self},\nkeywordstyle=\\ttb\\color{deepblue},\nstringstyle=\\color{deepgreen},\nbackgroundcolor=\\color{lbcolor},\nframe=single,\nshowstringspaces=false\n}}\n\n% Python environment\n\\lstnewenvironment{python}[1][]\n{\n\\pythonstyle\n\\lstset{#1}\n}\n{}\n\n% Python for external files\n\\newcommand\\pythonexternal[2][]{{\n\\pythonstyle\n\\lstinputlisting[#1]{#2}}}\n\n% Python for inline\n\\newcommand\\pythoninline[1]{{\\pythonstyle\\lstinline!#1!}}\n\n\\title{\n\\normalfont \\normalsize\n\\textsc{Norwegian University of Science and Technology\\\\TDT4137 -- Cognitive Architectures}\n\\horrule{0.5pt} \\\\[0.4cm]\n\\huge Assignment 4:\\\\ Fuzzy Reasoning\\\\\n\\horrule{2pt} \\\\[0.5cm]\n}\n\n\\author{Per Magnus Veierland\\\\permve@stud.ntnu.no}\n\n\\date{\\normalsize\\today}\n\n\\newacro{COG}{Centre of Gravity}\n\n\\begin{document}\n\n\\maketitle\n\n\\section*{Fuzzy sets and rules}\n\n\\begin{enumerate}[label=\\alph*)]\n\\item\n\nThe distance between the robot car and the car in front is 3.6. This value intersects with the linguistic sets \\textsc{Small} and \\textsc{Perfect}:\n\n\\begin{displaymath}\n\\mu_{\\textsc{Small}} = \\frac{4.5 - 3.6}{4.5 - 3.0} = 0.6\n\\end{displaymath}\n\n\\begin{displaymath}\n\\mu_{\\textsc{Perfect}} = \\frac{3.6 - 3.5}{5.0 - 3.5} \\approx 0.07\n\\end{displaymath}\n\nThe gradient of the distance is the delta variable which has the value 1.1 and belongs to the linguistic sets \\textsc{Stable} and \\textsc{Growing}:\n\n\\begin{displaymath}\n\\mu_{\\textsc{Stable}} = \\frac{1.5 - 1.1}{1.5 - 0} \\approx 0.27\n\\end{displaymath}\n\n\\begin{displaymath}\n\\mu_{\\textsc{Growing}} = \\frac{1.1 - 0.5}{2 - 0.5} = 0.4\n\\end{displaymath}\n\n\\begin{enumerate}[label=\\textsc{Rule \\arabic*}:]\n\\item \\textbf{If} \\textsc{Distance} \\textbf{is} \\textsc{Small} \\textbf{and} \\textsc{Delta} \\textbf{is} \\textsc{Growing} \\textbf{then} \\textsc{Action} \\textbf{is} \\textsc{None}\n\n\\begin{displaymath}\n\\mu_{\\textsc{None}} = \\min(\\mu_{\\textsc{Small}}, \\mu_{\\textsc{Growing}}) = \\min(0.6, 0.4) = 0.4\n\\end{displaymath}\n\n\\item \\textbf{If} \\textsc{Distance} \\textbf{is} \\textsc{Small} \\textbf{and} \\textsc{Delta} \\textbf{is} \\textsc{Stable} \\textbf{then} \\textsc{Action} \\textbf{is} \\textsc{SlowDown}\n\n\\begin{displaymath}\n\\mu_{\\textsc{SlowDown}} = \\min(\\mu_{\\textsc{Small}}, \\mu_{\\textsc{Stable}}) = \\min(0.6, 0.27) = 0.27\n\\end{displaymath}\n\n\\item \\textbf{If} \\textsc{Distance} \\textbf{is} \\textsc{Perfect} \\textbf{and} \\textsc{Delta} \\textbf{is} \\textsc{Growing} \\textbf{then} \\textsc{Action} \\textbf{is} \\textsc{SpeedUp}\n\n\\begin{displaymath}\n\\mu_{\\textsc{SpeedUp}} = \\min(\\mu_{\\textsc{Perfect}}, \\mu_{\\textsc{Growing}}) = \\min(0.07, 0.4) = 0.07\n\\end{displaymath}\n\n\\item \\textbf{If} \\textsc{Distance} \\textbf{is} \\textsc{VeryBig} \\textbf{and} \\big(\\textsc{Delta} \\textbf{is not} \\textsc{Growing} \\textbf{or} \\textsc{Delta} \\textbf{is not} \\textsc{GrowingFast}\\big) \\textbf{then} \\textsc{Action} \\textbf{is} \\textsc{FloorIt}\n\n\\begin{align*}\n\\mu_{\\textsc{FloorIt}} &= \\min\\big(\\mu_{\\textsc{VeryBig}}, \\max(\\neg\\mu_{\\textsc{Growing}}, \\neg\\mu_{\\textsc{GrowingFast}})\\big)\\\\\n&= \\min\\big(0, \\max(1 - 0.4, 1 - 0)\\big)\\\\\n&= \\min\\big(0, \\max(0.6, 1)\\big)\\\\\n&= \\min(0, 1)\\\\\n&= 0\n\\end{align*}\n\n\\item \\textbf{If} \\textsc{Distance} \\textbf{is} \\textsc{VerySmall} \\textbf{then} \\textsc{Action} \\textbf{is} \\textsc{BrakeHard}\n\n\\begin{displaymath}\n\\mu_{\\textsc{BrakeHard}} = \\mu_{\\textsc{VerySmall}} = 0\n\\end{displaymath}\n\n\\end{enumerate}\n\nThe resulting defuzzified output can be calculated as the \\ac{COG} of the aggregated fuzzy set $A$. Rule outputs are clipped before they are aggregated.\n\n%Raw data:\n%-10 = 0\n%-9  = 0\n%-8  = 0\n%-7  = 0\n%-6  = 0.2\n%-5  = 0.2\n%-4  = 0.2\n%-3  = 0.2\n%-2  = 0.3\n%-1  = 0.4\n%0   = 0.4\n%1   = 0.4\n%2   = 0.3\n%3   = 0.07\n%4   = 0.07\n%5   = 0.07\n%6   = 0.07\n%7   = 0\n%8   = 0\n%9   = 0\n%10  = 0\n\n\\begin{align*}\n\\text{COG} &= \\frac{\\mathlarger{\\int_{-10}^{10} x \\cdot \\mu_A(x)~dx}}{\\mathlarger{\\int_{-10}^{10} \\mu_A(x)~dx}}\\\\[0.2cm]\n&\\approx \\frac{\\sum\\limits_{n=-10}^{-7}(n) \\cdot 0 + \\sum\\limits_{n=-6}^{-3}(n) \\cdot 0.2 + (-2) \\cdot 0.3 + \\sum\\limits_{n=-1}^{1}(n) \\cdot 0.4 + (2) \\cdot 0.3 + \\sum\\limits_{n=3}^{6}(n) \\cdot 0.07 + \\sum\\limits_{n=7}^{10}(n) \\cdot 0}{4 \\cdot 0 + 4 \\cdot 0.2 + 0.3 + 3 \\cdot 0.4 + 0.3 + 4 \\cdot 0.07 + 4 \\cdot 0}\\\\[0.2cm]\n&= \\frac{0 + -3.6 + -0.6 + 0 + 0.6 + 1.26 + 0}{2.88} = \\frac{-2.34}{2.88} = -0.8125\n\\end{align*}\n\n\\item\nPerforming \\textit{Mamdani} reasoning with \\ac{COG} defuzzification using segmentation steps yielded an output of -1.1066.\n\n\\newpage\n\n\\pythonexternal{fuzzy.py}\n\n\\end{enumerate}\n\n\\end{document}\n\n", "meta": {"hexsha": "bda4f527e63ecf7f2a55625524149ec6ca9d85b5", "size": 5018, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "assignment_4/permve-ntnu-tdt4137-assignment-4.tex", "max_stars_repo_name": "pveierland/permve-ntnu-tdt4137", "max_stars_repo_head_hexsha": "673f10b8159719cf9f23fe4b4923bfa6c3fc9086", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assignment_4/permve-ntnu-tdt4137-assignment-4.tex", "max_issues_repo_name": "pveierland/permve-ntnu-tdt4137", "max_issues_repo_head_hexsha": "673f10b8159719cf9f23fe4b4923bfa6c3fc9086", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignment_4/permve-ntnu-tdt4137-assignment-4.tex", "max_forks_repo_name": "pveierland/permve-ntnu-tdt4137", "max_forks_repo_head_hexsha": "673f10b8159719cf9f23fe4b4923bfa6c3fc9086", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6923076923, "max_line_length": 322, "alphanum_fraction": 0.6677959346, "num_tokens": 2090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3287926983783749}}
{"text": "\\chapter{Fast Pathfinding on Graphs via Lazy Evaluation}\n\\label{chap:lazysp}\n\nThe roadmap methods described in Chapter~\\ref{chap:roadmaps}\ncreate a discretization of the configuration space using\na graph $G = (V,E)$.\nThis allows the motion planning problem to be solved by way of\na pathfinding algorithm on $G$\n-- and there are a large variety of such algorithms available\nin the literature to choose from.\nHowever,\nthe computational efficiency of suitable algorithms\ndepends intimately on the underlying problem domain.\n\nIn this chapter,\nwe consider the general shortest path problem\nwith a particular focus on domains (such as robot motion planning)\nwhere evaluating the edge weight function\ndominates algorithm running time.\nInspired by lazy approaches in robotics,\nwe define and investigate the \\emph{Lazy Shortest Path} class of\nalgorithms which is differentiated by the choice of\nan \\emph{edge selector} function.\nWe show that several algorithms in the literature are equivalent to\nthis lazy algorithm for appropriate choice of this selector.\nFurther, we propose various novel selectors inspired by\nsampling and statistical mechanics,\nand find that these selectors outperform\nexisting algorithms on a set of example problems.\n\n\\begin{figure}\n\\centering\n\\begin{tikzpicture}\n   \\tikzset{>=latex} % arrow heads\n   %\\draw[step=1cm,black!10,very thin] (0,0) grid (8,4);\n   \\node[draw,align=center,minimum height=1.0cm,thick]\n      at (2.5,2.5) {Graph\\\\$G=(V,E)$};\n   \\node[draw,align=center,minimum height=1.0cm,thick]\n      at (5.5,2.5) {Weight Function\\\\$w:E \\rightarrow [0,+\\infty]$};\n   \\node[draw,align=center,minimum height=1.0cm,minimum width=3cm,thick]\n      (alg) at (4,1) {Shortest Path\\\\Algorithm};\n   \\node[draw,align=center,shape=document,minimum width=1.5cm,ultra thin]\n      (query) at (1,1) {Query $u$};\n   \\node[draw,align=center,shape=document,minimum width=1.5cm,ultra thin]\n      (path) at (7,1) {Path $p^*$};\n   \\draw[->] (3,2) -- (3,1.5);\n   \\draw[->] (5,2) -- (5,1.5);\n   \\draw[->] (query.east) -- (alg.west);\n   \\draw[->] (alg.east) -- (path.west);\n\\end{tikzpicture}\n\\caption{While solving a shortest path query,\n   a shortest path algorithm incurs computation cost from three sources:\n   examining the structure of the graph $G$,\n   evaluating the edge weight function $w$,\n   and maintaining internal data structures.}\n\\label{fig:sp-intro}\n\\end{figure}\n\n\\section{The Shortest Path Problem}\n\nGraphs provide a powerful abstraction\ncapable of representing problems in a wide variety of domains\nfrom computer networking to puzzle solving\nto robotic motion planning.\n%\\ajnote{Way too vague and general -- disconnected from second sentence.\n%Maybe mention ``standard problems'' on graphs.}\nIn particular,\nmany important problems can be captured\nas \\emph{shortest path problems} (Figure~\\ref{fig:sp-intro}),\nwherein a path $p^*$ of minimal length is sought\nbetween two query vertices through a graph $G$\nwith respect to an edge weight function $w$.\n%As such,\n%a large number of algorithms have been proposed in the literature\n%for solving shortest path problems efficiently.\n\nDespite the expansive applicability of this single abstraction,\nthere exist a wide variety of algorithms in the literature\nfor solving the shortest path problem efficiently.\n%\\ajnote{You say ``despite'' but the second part seems to follow from\n%the first.\n%There are many solutions because there are many problems.}\nThis is because the measure of computational efficiency,\nand therefore the correct choice of algorithm,\nis inextricably tied to the underlying problem domain.\n\nThe computational costs incurred by an algorithm\ncan be broadly categorized into three sources\ncorresponding to the blocks in Figure~\\ref{fig:sp-intro}.\nOne such source consists of queries on the structure\nof the graph $G$ itself.\nThe most commonly discussed such operation,\n\\emph{expanding} a vertex (determining its successors),\nis especially fundamental\n%\\ajnote{especially costly?}\nwhen the graph is represented implicitly,\ne.g. for domains with large graphs\nsuch as the 15-puzzle or Rubik's cube.\nIt is with respect to vertex expansions\nthat A* \\citep{hart1968astar} is optimally efficient.\n\nA second source of computational cost consists of maintaining\nordered data structures inside the algorithm itself,\nwhich is especially important for problems with large branching\nfactors.\nFor such domains,\napproaches such as partial expansion \\citep{yoshizumi2000peastar}\nor iterative deepening \\citep{korf1985idastar}\nsignificantly reduce the number of vertices generated and stored\nby either selectively filtering surplus vertices from the frontier,\nor by not storing the frontier at all.\n\nThe third source of computational cost arises not from reasoning\nover the structure of $G$,\nbut instead from evaluating the edge weight function $w$\n(i.e. we treat discovering an out-edge and determining its weight\nseparately).\nConsider for example the problem of articulated robotic motion planning\nusing roadmap methods \\citep{kavrakietal1996prm}.\nWhile these graphs are often quite small\n(fewer than $10^5$ vertices),\ndetermining the weight of each edge requires performing many\ncollision and distance computations for the complex geometry\nof the robot and environment,\nresulting in planning times of multiple seconds to find a path.\n\nAs described in Chapter~\\ref{chap:roadmaps},\nwe consider problem domains in which evaluating the edge weight\nfunction $w$ dominates algorithm running time.\nIn this chapter,\nwe investigate the following research question:\n\\begin{quote}\n{\\normalsize\nHow can we minimize the number of edges we need to evaluate\nto answer shortest-path queries?\n}\n\\end{quote}\n\nWe make three primary contributions.\nFirst,\ninspired by lazy collision checking techniques from \nrobotic motion planning \\citep{bohlin2000lazyprm},\nwe formulate a class of shortest-path algorithms \nthat is well-suited to problem domains with expensive edge evaluations.\nSecond,\nwe show that several existing algorithms in the literature\ncan be expressed as special cases of this algorithm.\nThird,\nwe show that the extensibility afforded by the algorithm allows for\nnovel edge evaluation strategies,\nwhich can outperform existing algorithms\nover a set of example problems.\n\n\\section{Lazy Shortest Path Algorithm}\n\nWe describe a lazy approach to finding short paths\nwhich is well-suited to domains with\nexpensive edge evaluations.\n\n\\subsection{Problem Definition}\n\nA path $p$ in a graph $G = (V,E)$\nis composed of a sequence of adjacent edges \nconnecting two endpoint vertices.\nGiven an edge weight function\n$w : E \\rightarrow [0,+\\infty]$,\nthe length of the path with respect to $w$ is then:\n\\begin{equation}\n   \\mbox{len}(p, w) = \\sum_{e \\in p} w(e).\n   \\label{eqn:lazysp:len-definition}\n\\end{equation}\nGiven a single-pair planning query\n$u: (v_{\\ms{start}}, \\, v_{\\ms{goal}})$\ninducing a set of satisfying paths $P_u$,\nthe \\emph{shortest-path problem} is:\n\\begin{equation}\n   p^* = \\argmin_{p \\, \\in \\, P_u} \\mbox{len}(p, w).\n   \\label{eqn:objective}\n\\end{equation}\n\nA shortest-path algorithm computes a satisfying solution $p^*$\ngiven $(G, u, w)$.\nMany such algorithms have been proposed\nto efficiently accommodate a wide array of underlying problem domains.\n%(outlined in Section~\\ref{sec:discussion}).\nThe well-known principle of best-first search (BFS)\nis commonly employed to select vertices for expansion\nso as to minimize such expansions while guaranteeing optimality.\nSince we seek to minimize edge evaluations,\nwe apply BFS to the question of selecting candidate paths in\n$G$ for evaluation.\nThe resulting algorithm, Lazy Shortest Path (LazySP),\nis presented in Algorithm~\\ref{alg:lazy-outline},\nand can be applied to graphs defined implicitly or explicitly.\n\n%\\cdnote{To Sidd: You might not like this paragraph -- but I feel like\n%going directly from the problem definition to the algorithm doesn't\n%connect to the rationale strongly enough without it.\n%What do you think?}\n\n\\subsection{The Algorithm}\n\n\\begin{algorithm}[t]\n\\caption{Lazy Shortest Path (LazySP)}\n\\label{alg:lazy-outline}\n\\begin{algorithmic}[1]\n\\Function {\\textsc{LazyShortestPath}}{$G, u, w, w_{\\ms{est}}$}\n\\State $E_{\\ms{eval}} \\leftarrow \\emptyset$ %\\Comment Initialize evaluated edges to empty\n\\State $w_{\\ms{lazy}}(e) \\leftarrow w_{\\ms{est}}(e) \\quad \\forall e \\in E$ %\\Comment Initialize lazy edge weights to estimate (inexpensive)\n\\Loop\n   \\State $p_{\\ms{candidate}} \\leftarrow\n      \\mbox{\\sc ShortestPath}(G, u, w_{\\ms{lazy}})$ %\\Comment Compute the shortest path with lazy edge weights\n      \\label{line:lazy-outline-shortestpath}\n   \\If {$p_{\\ms{candidate}} \\subseteq E_{\\ms{eval}}$} %\\Comment If all edges on path have already been evaluated,\n      \\State \\Return $p_{\\ms{candidate}}$ %\\Comment path returned is provably optimal\n   \\EndIf\n   \\State $E_{\\ms{selected}} \\leftarrow  \\mbox{\\sc Selector}(G, p_{\\ms{candidate}})$ %\\Comment Select edges on path to process\n   \\label{line:lazy-outline-chooseedges} \n   \\For {$e \\in E_{\\ms{selected}} \\setminus E_{\\ms{eval}}$} %\\Comment For all unevaluated selected edges\n      \\State $w_{\\ms{lazy}}(e) \\leftarrow w(e)$ \\Comment Evaluate (expensive)\n      \\State $E_{\\ms{eval}} \\leftarrow E_{\\ms{eval}} \\cup e$ %\\Comment Add to evaluated edge set\n   \\EndFor\n\\EndLoop\n\\EndFunction\n\\end{algorithmic}\n\\end{algorithm}\n\nWe track evaluated edges with the set $E_{\\ms{eval}}$.\nWe are given an estimator function $w_{\\ms{est}}$ of the true edge weight $w$.\nThis estimator is inexpensive to compute\n(e.g. edge length or even $0$).\nWe then define a \\emph{lazy} weight function $w_{\\ms{lazy}}$\nwhich returns the\ntrue weight of an evaluated edge and otherwise\nuses the inexpensive estimator $w_{\\ms{est}}$.\n\nAt each iteration of the search,\nthe algorithm uses $w_{\\ms{lazy}}$ to compute a candidate path\n$p_{\\ms{candidate}}$\nby calling an existing solver \\textsc{ShortestPath}\n(note that this invocation requires no evaluations of $w$).\nOnce a candidate path has been found,\nit is returned if it is fully evaluated.\nOtherwise,\nan \\emph{edge selector} is employed which selects\ngraph edge(s) for evaluation.\nThe true weights of these edges are then evaluated\n(incurring the requisite computational cost),\nand the algorithm repeats.\n\n%\\subsection{Theoretical Properties}\n\nLazySP is complete and optimal:\n\\marginnote{Proof of all theorems are available\nin Appendix~\\ref{sec:appendix-proofs}.}\n\n\\begin{theorem}[Completeness of LazySP]\nIf the graph $G$ is finite,\n\\textsc{ShortestPath} is complete,\nand the set $E_{\\ms{selected}}$\nreturned by \\textsc{Selector}\nreturns at least one unevaluated edge on $p_{\\ms{candidate}}$,\nthen \\textsc{LazyShortestPath} is complete.\n\\label{thm:lazy-completeness}\n\\end{theorem}\n\n\\begin{theorem}[Optimality of LazySP]\nIf $w_{\\ms{est}}$ is chosen such that\n$w_{\\ms{est}}(e) \\leq \\epsilon \\, w(e)$ for some parameter\n$\\epsilon \\geq 1$ and\n\\textsc{LazyShortestPath} terminates\nwith some path $p_{\\ms{ret}}$,\nthen $\\mbox{len}(p_{\\ms{ret}}, w) \\leq \\epsilon \\, \\ell^*$\nwith $\\ell^*$ the length of an optimal path.\n\\label{thm:lazy-optimality}\n\\end{theorem}\n\nThe optimality of LazySP depends on the admissibility of\n$w_{\\ms{est}}$\nin the same way that the optimality of A* depends on\nthe admissibility of its goal heuristic $h$.\nTheorem~\\ref{thm:lazy-optimality} establishes the general\nbounded suboptimality of LazySP\nw.r.t. the inflation parameter $\\epsilon$.\nWhile our theoretical results (e.g. equivalences)\nhold for any choice of $\\epsilon$,\nfor clarity our examples and experimental results\nfocus on cases with $\\epsilon = 1$.\n\n\\subsection{The Edge Selector: Key to Efficiency}\n\n\\begin{algorithm}[t]\n\\caption{Various Simple LazySP Edge Selectors}\n\\begin{algorithmic}[1]\n\\Function {\\textsc{SelectExpand}}{$G, p_{\\ms{candidate}}$}\n   \\State $e_{\\ms{first}} \\leftarrow$ first unevaluated $e \\in p_{\\ms{candidate}}$\n   \\State $v_{\\ms{frontier}} \\leftarrow G.\\mbox{source}(e_{\\ms{first}})$\n   \\State $E_{\\ms{selected}} \\leftarrow G.\\mbox{out\\_edges}(v_{\\ms{frontier}})$\n   \\State \\Return $E_{\\ms{selected}}$\n\\EndFunction\n\\vspace{0.02in}\n\\Function {\\textsc{SelectForward}}{$G, p_{\\ms{candidate}}$}\n   \\State \\Return $\\{ \\mbox{first unevaluated } e \\in p_{\\ms{candidate}} \\}$\n\\EndFunction\n\\vspace{0.02in}\n\\Function {\\textsc{SelectReverse}}{$G, p_{\\ms{candidate}}$}\n   \\State \\Return $\\{ \\mbox{last unevaluated } e \\in p_{\\ms{candidate}} \\}$\n\\EndFunction\n\\vspace{0.02in}\n\\Function {\\textsc{SelectAlternate}}{$G, p_{\\ms{candidate}}$}\n   \\If {LazySP iteration number is odd}\n      \\State \\Return $\\{ \\mbox{first unevaluated } e \\in p_{\\ms{candidate}} \\}$\n   \\Else\n      \\State \\Return $\\{ \\mbox{last unevaluated } e \\in p_{\\ms{candidate}} \\}$\n   \\EndIf\n\\EndFunction\n\\vspace{0.02in}\n\\Function {\\textsc{SelectBisection}}{$G, p_{\\ms{candidate}}$}\n   \\State \\Return $\\left\\{ \\begin{array}{ll}\n      \\mbox{unevaluated } e \\in p_{\\ms{candidate}} \\\\\n      \\mbox{furthest from nearest evaluated edge}\n      \\end{array} \\right\\}$\n\\EndFunction\n\\end{algorithmic}\n\\label{alg:simple-selectors}\n\\end{algorithm}\n\n%The algorithm purposely leaves undecided\n%the edge evaluation selector codified in\n%\\textsc{Selector} (line~\\ref{line:lazy-outline-chooseedges}),\n%and therefore describes a class of algorithms\n%differentiated by the choice of this selector.\n%This paper discusses particular choices.\n\nThe LazySP algorithm exhibits a rough similarity to optimal\nreplanning algorithms such as\nD* \\citep{stentz1994dstar,stentz1995focusseddstar}\nwhich plan a sequence of shortest paths for a mobile robot\nas new edge weights are discovered during its traverse.\nD* treats edge changes\npassively as an aspect of the problem setting\n(e.g. a sensor with limited range).\n\nThe key difference is that our problem setting treats \nedge evaluations as an active choice that can be exploited.\nWhile any choice of edge selector that meets the conditions above\nwill lead to an algorithm that is complete and optimal,\nits \\emph{efficiency} is dictated by the choice of this\nselector.\nThis motivates the theoretical and empirical investigation of different\nedge selectors in this chapter.\n\n\\textbf{Simple selectors.}\nWe codify five common strategies in\nAlgorithm~\\ref{alg:simple-selectors}.\nThe Expand selector captures the edge weights that are evaluated\nduring a conventional vertex expansion.\nThe selector identifies the first unevaluated edge\n$e_{\\ms{first}}$ on the candidate path,\nand considers the source vertex of this edge a \\emph{frontier} vertex.\nIt then selects all out-edges of this frontier vertex\nfor evaluation.\nThe Forward and Reverse selectors select the first and last\nunevaluated edge on the candidate path, respectively\n(note that Forward returns a subset of Expand).\n\nThe Alternate selector simply alternates between Forward\nand Reverse on each iteration.\nThis can be motivated by both bidirectional search algorithms\nas well as motion planning algorithms such as\nRRT-Connect \\citep{kuffner2000rrtconnect}\nwhich tend to perform well w.r.t. state evaluations.\n\nThe Bisection selector\nchooses among those unevaluated edges\nthe one furthest from an evaluated edge on the candidate path.\nThis selector is roughly analogous to the collision checking strategy\nemployed by the Lazy PRM \\citep{bohlin2000lazyprm}\nas applied to our problem on abstract graphs.\n\nIn the following section,\nwe demonstrate that instances of LazySP using simple selectors\nyield equivalent results to existing vertex algorithms.\nWe then discuss two more sophisticated\nselectors motivated by weight function sampling\nand statistical mechanics.\n\n% prob-box2d00-halton-roots16\n% fwd:34 partall:22 rev:24 fwdexpand:77\n% bisect:25 worlddist:22 alt:23 partsimple:22\n\\begin{figure*}[t!]%\n   \\!\\!%\n   \\subfloat[Expand(77)]{%\n      \\centering%\n      \\begin{tikzpicture}\n         \\node at (0,-0.0) {\\includegraphics{build/lazysp-example-1/alg-fwdexpand-after5}};\n         \\node at (0,-2.5) {\\includegraphics{build/lazysp-example-1/alg-fwdexpand-end}};\n         \\node at (0,-4.8) {\\includegraphics{build/lazysp-example-1/alg-fwdexpand-path-bars}};\n      \\end{tikzpicture}%\n   }%\n   \\!\\!%\n   \\subfloat[Forward(34)]{%\n      \\centering%\n      \\begin{tikzpicture}\n         \\node at (0,-0.0) {\\includegraphics{build/lazysp-example-1/alg-fwd-after5}};\n         \\node at (0,-2.5) {\\includegraphics{build/lazysp-example-1/alg-fwd-end}};\n         \\node at (0,-4.8) {\\includegraphics{build/lazysp-example-1/alg-fwd-path-bars}};\n      \\end{tikzpicture}%\n   }%\n   \\!\\!%\n   \\subfloat[Reverse(24)]{%\n      \\centering%\n      \\begin{tikzpicture}\n         \\node at (0,-0.0) {\\includegraphics{build/lazysp-example-1/alg-rev-after5}};\n         \\node at (0,-2.5) {\\includegraphics{build/lazysp-example-1/alg-rev-end}};\n         \\node at (0,-4.8) {\\includegraphics{build/lazysp-example-1/alg-rev-path-bars}};\n      \\end{tikzpicture}%\n   }%\n   \\!\\!%\n   \\subfloat[Alternate(23)]{%\n      \\centering%\n      \\begin{tikzpicture}\n         \\node at (0,-0.0) {\\includegraphics{build/lazysp-example-1/alg-alt-after5}};\n         \\node at (0,-2.5) {\\includegraphics{build/lazysp-example-1/alg-alt-end}};\n         \\node at (0,-4.8) {\\includegraphics{build/lazysp-example-1/alg-alt-path-bars}};\n      \\end{tikzpicture}%\n   }%\n   \\!\\!%\n   \\subfloat[Bisect(25)]{%\n      \\centering%\n      \\begin{tikzpicture}\n         \\node at (0,-0.0) {\\includegraphics{build/lazysp-example-1/alg-bisect-after5}};\n         \\node at (0,-2.5) {\\includegraphics{build/lazysp-example-1/alg-bisect-end}};\n         \\node at (0,-4.8) {\\includegraphics{build/lazysp-example-1/alg-bisect-path-bars}};\n      \\end{tikzpicture}%\n   }%\n   \\!\\!%\n   \\subfloat[WeightSamp(22)]{%\n      \\centering%\n      \\begin{tikzpicture}\n         \\node at (0,-0.0) {\\includegraphics{build/lazysp-example-1/alg-worlddist1000-after5}};\n         \\node at (0,-2.5) {\\includegraphics{build/lazysp-example-1/alg-worlddist1000-end}};\n         \\node at (0,-4.8) {\\includegraphics{build/lazysp-example-1/alg-worlddist1000-path-bars}};\n      \\end{tikzpicture}%\n   }%\n   \\!\\!%\n   \\subfloat[Partition(22)]{%\n      \\centering%\n      \\begin{tikzpicture}\n         \\node at (0,-0.0) {\\includegraphics{build/lazysp-example-1/alg-partall-after5}};\n         \\node at (0,-2.5) {\\includegraphics{build/lazysp-example-1/alg-partall-end}};\n         \\node at (0,-4.8) {\\includegraphics{build/lazysp-example-1/alg-partall-path-bars}};\n      \\end{tikzpicture}%\n   }%\n   \\caption[Snapshots of the LazySP algorithm using each edge selector\n      discussed in this chapter on the same obstacle roadmap graph problem,\n      with start and goal.\n      At top, the algorithms after evaluating five edges\n      (evaluated edges labeled as valid or invalid).\n      At middle, the final set of evaluated edges.\n      At bottom, for each unique path considered from left to right,\n      the number of edges on the path that are\n      already evaluated, evaluated and valid, evaluated and invalid,\n      and unevaluated.\n      The total number of edges evaluated is noted in brackets.\n      Note that the scale on the Expand plot has been adjusted\n      because the selector evaluates many edges not on the candidate\n      path at each iteration.\n   ]{Snapshots of the LazySP algorithm using each edge selector\n      discussed in this chapter on the same obstacle roadmap graph problem,\n      with start (\\protect\\tikz[baseline=-0.5ex]{\\protect\\node[circle,fill=blue,inner sep=1pt]{};})\n      and goal (\\protect\\tikz[baseline=-0.5ex]{\\protect\\node[circle,fill=green,inner sep=1pt]{};}).\n      At top, the algorithms after evaluating five edges\n      (evaluated edges labeled as\n      \\protect\\tikz{\\protect\\draw[very thick] (0,0) -- (0.15,0.15);}  valid\n      or \\protect\\tikz{\\protect\\draw[very thick,red] (0,0) -- (0.15,0.15);} invalid).\n      At middle, the final set of evaluated edges.\n      At bottom, for each unique path considered from left to right,\n      the number of edges on the path that are\n      \\protect\\tikz{\\protect\\node[fill=green!40!white,draw=black]{};}\\;already evaluated,\n      \\protect\\tikz{\\protect\\node[fill=green!70!black,draw=black]{};}\\;evaluated and valid,\n      \\protect\\tikz{\\protect\\node[fill=red!70!black,draw=black]{};}\\;evaluated and invalid,\n      and \\protect\\tikz{\\protect\\node[fill=black!10!white,draw=black]{};}\\;unevaluated.\n      The total number of edges evaluated is noted in brackets.\n      Note that the scale on the Expand plot has been adjusted\n      because the selector evaluates many edges not on the candidate\n      path at each iteration.\n      }\n   \\label{fig:snapshots}\n\\end{figure*}\n\n\\section{Edge Equivalence to A* Variants}\n\nIn the previous section,\nwe introduced LazySP as the path-selection analogue\nto BFS vertex-selection algorithms.\nIn this section,\nwe make this analogy more precise.\nIn particular,\nwe show that LazySP-Expand\n%(that is, LazySP with the Expand selector)\n%\\ajnote{name consistency}\nis edge-equivalent to a variant of A*\n(and Weighted A*),\nand that LazySP-Forward is edge-equivalent to a variant of\nLazy Weighted A*\n(see Table~\\ref{table:equivalences}).\n%\\ajnote{Say ``as described below''?}\nIt is important to be specific about the conditions under which\nthese equivalences arise,\nwhich we detail here.\n\n\\begin{table}\n   \\centering\n   {\\small%\n   \\begin{tabular}{lll}\n      \\toprule\n      LazySP & Existing & \\\\\n      Selector & Algorithm & Result \\\\\n      \\midrule\n      Expand & (Weighted) A* & Edge-equivalent \\\\\n      & & (Theorems \\ref{thm:astar-equiv-from-lazy},\n                 \\ref{thm:astar-equiv-to-lazy}) \\\\\n      \\addlinespace[0.3em]\n      Forward & Lazy Weighted A* & Edge-equivalent \\\\\n      & & (Theorems \\ref{thm:lwastar-equiv-from-lazy},\n                 \\ref{thm:lwastar-equiv-to-lazy}) \\\\\n      \\addlinespace[0.3em]\n      Alternate & Bidirectional Heuristic & Conjectured \\\\\n      & Front-to-Front Algorithm & \\\\\n      \\bottomrule\n   \\end{tabular}%\n   }%\n   \\caption{LazySP equivalence results.\n      The A*, LWA*, and BHFFA algorithms use reopening and the dynamic\n      $h_{\\ms{lazy}}$ heuristic (\\ref{eqn:h_lazy}).}\n   \\label{table:equivalences}\n\\end{table}\n\n\\textbf{Edge equivalence.}\nWe say that two algorithms are \\emph{edge-equivalent} if they\nevaluate the same edges in the same order.\nWe consider an algorithm to have evaluated an edge\nthe first time the edge's true weight is requested.\n\n\\textbf{Arbitrary tiebreaking.}\nFor some graphs,\nan algorithm may have multiple allowable choices at each iteration\n(e.g. LazySP with multiple shortest candidate paths,\nor A* with multiple vertices in OPEN with lowest $f$-value).\nWe will say that algorithm A is equivalent to algorithm B\nif for any choice available to A,\nthere exists an allowable choice available to B\nsuch that the same edge(s) are evaluated by each.\n\n\\textbf{A* with reopening.}\nWe show equivalence to variants of A* and Lazy Weighted A*\nthat do not use a CLOSED list to prevent\nvertices from being visited more than once.\n%\\ssnote{Why this comparison?! Not explained.}.\n%Note that if the heuristic used is $h(v) = \\epsilon h_c(v)$\n%with $h_c(v)$ consistent,\n%a CLOSED list could potentially reduce edge evaluations\n%while still guaranteeing $\\epsilon$-suboptimality.\n\n\\begin{figure}\n   \\centering\n   \\begin{tikzpicture}\n      \\tikzset{>=latex} % arrow heads\n      %\\draw[step=1cm,black!10,very thin] (0,0) grid (8,4);\n      \\node[draw,circle,inner sep=1pt,fill=black!20] (S) at (1,1) {S};\n      \\node[draw,circle,inner sep=1pt] (X) at (2,2.7) {X};\n      \\node[draw,circle,inner sep=1pt,fill=black!20] (Y) at (3,1) {Y};\n      \\node[draw,circle,inner sep=1pt] (G) at (5,1) {G};\n      \\draw[->] (S) -- (Y) node [midway,fill=white] {1,1};\n      \\draw[->] (Y) -- (G) node [midway,fill=white] {1,3};\n      \\draw[->] (S) -- (X) node [midway,fill=white] {1,1};\n      \\draw[->,densely dotted] (X) -- (Y) node [midway,fill=white] {1,?};\n      \\node[anchor=west] at (2.3,2.9) {$h_{\\ms{est}} = 2$};\n      \\node[anchor=west] at (2.3,2.5) {$h_{\\ms{lazy}} = 4$};\n      \n      % for legend\n      %\\node at (7,2.9) {unevaluated:};\n      %\\draw[->,dashed] (6,2.5) -- (8,2.5)\n      %   node [midway,fill=white] {($w_{est}$)\\,?};\n      %\\node at (7,1.9) {evaluated:};\n      %\\draw[->] (6,1.5) -- (8,1.5)\n      %   node [midway,fill=white] {($w_{est}$)\\,$w$};\n      \\draw[->,densely dotted] (4.5,2.9) -- (6.5,2.9)\n         node[midway,yshift=0.03cm,fill=white,inner sep=1pt,font=\\small] {unevaled};\n      \\draw[->] (4.5,2.55) -- (6.5,2.55)\n         node[midway,yshift=0.03cm,fill=white,inner sep=1pt,font=\\small] {evaled};\n      \\node at (5.5,2.2) {$w_{\\ms{est}},w$};\n      \\draw[black!10] (4.25,1.95) rectangle (6.75,3.2);\n   \\end{tikzpicture}\n   \\caption{A* comparison between\n      the static goal heuristic $h_{\\ms{est}}$ (\\ref{eqn:h_est})\n      and the dynamic goal heuristic $h_{\\ms{lazy}}$ (\\ref{eqn:h_lazy})\n      on a simple graph from start S to goal G.\n      The values of both the edge weight estimate $w_{\\ms{est}}$\n      and the true edge weight $w$ (for evaluated edges) are shown.\n      Using either goal heuristic,\n      the A* algorithm first expands vertices S and Y,\n      evaluating three edges in total and leaving X and G on OPEN.\n      After finding that edge YG has $w=3$,\n      the dynamic heuristic value $h_{\\ms{lazy}}(\\mbox{X})$\n      is updated from 2 to 4.\n      While the A* using the static $h_{\\ms{est}}$ would next expand X,\n      the A* using the dynamic $h_{\\ms{lazy}}$ would next expand G\n      and terminate, having never evaluated edge XY.}\n   \\label{fig:updating-heuristic}\n\\end{figure}\n\n\\textbf{A* with a dynamic heuristic.}\nIn order to apply A* and Lazy Weighted A* to our problem,\nwe need a goal heuristic over vertices.\nThe most simple may be\n\\begin{equation}\n   h_{\\ms{est}}(v) = \\min_{p : v \\rightarrow v_g} \\mbox{len}(p, w_{\\ms{est}}).\n   \\label{eqn:h_est}\n\\end{equation}\nNote that the value of this heuristic could be computed as a\npre-processing step using Dijkstra's algorithm \\citep{dijkstra1959anote}\nbefore iterations begin.\nHowever,\nin order for the equivalences to hold,\nwe require the use of the lazy heuristic\n\\begin{equation}\n   h_{\\ms{lazy}}(v) = \\min_{p : v \\rightarrow v_g} \\mbox{len}(p, w_{\\ms{lazy}}).\n   \\label{eqn:h_lazy}\n\\end{equation}\nThis heuristic is dynamic in that it depends on $w_{\\ms{lazy}}$\nwhich changes as edges are evaluated.\nTherefore,\nheuristic values must be recomputed for all affected vertices on OPEN\nafter each iteration.\n%An illustrative example is shown in\n%Figure~\\ref{fig:updating-heuristic}.\n%(We discuss efficient implementation of $h_{\\ms{lazy}}$ as it relates\n%to the D* family of algorithms in Section~\\ref{sec:discussion}.)\n\n\\subsection{Equivalence to A*}\n\nWe show that the LazySP-Expand algorithm\nis edge-equivalent to a variant of the A*\nshortest-path algorithm.\n%We consider the variant of A* which allows a vertex $v$ to be reopened\n%if its stored cost $g[v]$ is improved.\nWe make use of two invariants that are maintained during the\nprogression of A*.\n\\marginnote{Proof of all invariants are available\nin Appendix~\\ref{sec:appendix-proofs}.}\n\\begin{invariant}\nIf $v$ is discovered by A* and $v'$ is undiscovered,\nwith $v'$ a successor of $v$,\nthen $v$ is on OPEN.%\n\\label{inv:astar-cundisc-popen}%\n\\end{invariant}\n\\begin{invariant}\nIf $v$ and $v'$ are discovered by A*,\nwith $v'$ a successor of $v$,\nand $g[v] + w(v,v') < g[v']$,\nthen $v$ is on OPEN.%\n\\label{inv:astar-wless-popen}%\n\\end{invariant}\nWhen we say a vertex is \\emph{discovered},\nwe mean that it is either on OPEN or CLOSED.\nNote that Invariant \\ref{inv:astar-wless-popen} holds\nbecause we allow vertices to be reopened;\nwithout reopening (and with an inconsistent heuristic),\nlater finding a cheaper path to $v$ (and not reopening $v'$)\nwould invalidate the invariant.\n\nWe will use the goal heuristic $h_{\\ms{lazy}}$ from (\\ref{eqn:h_lazy}).\nNote that if an admissible edge weight estimator $\\hat{w}$ exists\n(that is, $\\hat{w} \\leq w$),\nthen our A* can approximate the Weighted A* algorithm\n\\citep{pohl1970weightedastar}\nwith parameter $\\epsilon$\nby using $w_{\\ms{est}} = \\epsilon \\, \\hat{w}$,\nand the suboptimality bound from\nTheorem~\\ref{thm:lazy-optimality} holds.\n\n\\begin{figure}[t]\n   \\centering\n   \\begin{tikzpicture}\n      %\\draw[step=1cm,gray,very thin] (0,0) grid (8,3);\n      \n      \\draw[fill=black!05] (2.1,1.5) ellipse (0.4cm and 0.5cm);\n      \\draw[fill=black!05] (5.9,1.5) ellipse (0.4cm and 0.5cm);\n      \\draw[fill=black!05] (4,1) ellipse (0.4cm and 0.4cm);\n      \n      \\node[align=center] at (0.75,1.5) {$P_{\\ms{candidate}}$\\\\(LazySP)};\n      \\node[align=center] at (7.25,1.5) {$S_{\\ms{candidate}}$\\\\(A*)};\n      \\node[align=center] at (4,1.75) {$V_{\\ms{frontier}}$};\n      \n      \\node[fill=black,circle,inner sep=1pt] (p1) at (2.15,1.7) {};\n      \\node[fill=black,circle,inner sep=1pt] (p2) at (2.05,1.3) {};\n      \n      \\node[fill=black,circle,inner sep=1pt] (s1) at (5.95,1.8) {};\n      \\node[fill=black,circle,inner sep=1pt] (s2) at (5.85,1.3) {};\n      \n      \\node[fill=black,circle,inner sep=1pt] (v1) at (4.1,0.9) {};\n      \n      \\draw[->] (p1) -- (v1);\n      \\draw[->] (p2) -- (v1);\n      \n      \\draw[->] (s1) -- (v1);\n      \\draw[->] (s2) -- (v1);\n      \n   \\end{tikzpicture}\n   \\caption{Illustration of the equivalence\n      between A* and LazySP-Expand.\n      After evaluating the same set of edges,\n      the next edges to be evaluated by each algorithm\n      can both be expressed as a surjective mapping onto\n      a common set of unexpanded\n      frontier vertices.\n      }\n   \\label{fig:astar-equiv-mapping}\n\\end{figure}\n\n\\textbf{Equivalence.}\nIn order to show edge-equivalence,\nwe consider the case where both algorithms\nare beginning a new iteration\nhaving so far evaluated the same set of edges.\n\nLazySP-Expand has some set $P_{\\ms{candidate}}$ of allowable\ncandidate paths minimizing $\\mbox{len}(p,w_{\\ms{lazy}})$;\nthe Expand selector will then identify a vertex on the chosen path\nfor expansion.\n\nA* will iteratively select a set of vertices from OPEN to expand.\nBecause it is possible that a vertex is expanded multiple times\n(and only the first expansion results in edge evaluations),\nwe group iterations of A* into \\emph{sequences},\nwhere each sequence $s$ consists of\n(a) zero or more vertices from OPEN that have already been expanded,\nfollowed by (b) one vertex from OPEN that is to be expanded\nfor the first time.\n\nWe show that both the set of allowable candidate paths $P_{\\ms{candidate}}$\navailable to LazySP-Expand\nand the set of allowable candidate vertex sequences $S_{\\ms{candidate}}$\navailable to A*\nmap surjectively to the same set of unexpanded frontier vertices $V_{\\ms{frontier}}$\nas illustrated in Figure~\\ref{fig:astar-equiv-mapping}.\nThis is described by way of\nTheorems \\ref{thm:astar-equiv-from-lazy}\nand \\ref{thm:astar-equiv-to-lazy} below.\n\\marginnote{Proof of all theorems are available\nin Appendix~\\ref{sec:appendix-proofs}.}\n\n\\begin{theorem}\nIf LazySP-Expand and A* have evaluated the same set of edges,\nthen for any candidate path $p_{\\ms{candidate}}$ chosen by LazySP\nyielding frontier vertex $v_{\\ms{frontier}}$,\nthere exists an allowable A* sequence $s_{\\ms{candidate}}$\nwhich also yields $v_{\\ms{frontier}}$.\n\\label{thm:astar-equiv-from-lazy}\n\\end{theorem}\n\n\\begin{theorem}\nIf LazySP-Expand and A* have evaluated the same set of edges,\nthen for any candidate sequence $s_{\\ms{candidate}}$ chosen by A*\nyielding frontier vertex $v_{\\ms{frontier}}$,\nthere exists an allowable LazySP path $p_{\\ms{candidate}}$\nwhich also yields $v_{\\ms{frontier}}$.\n\\label{thm:astar-equiv-to-lazy}\n\\end{theorem}\n\n\\subsection{Equivalence to Lazy Weighted A*}\n\n%\\begin{algorithm}\n%   \\caption{Forward Edge Evaluation Selector}\n%   \\begin{algorithmic}[1]\n%   \\Function {\\textsc{SelectForward}}{$G, p_{\\ms{candidate}}$}\n%   \\State $e_{\\ms{first}} \\leftarrow$ first unevaluated $e \\in p_{\\ms{candidate}}$\n%   \\State \\Return $\\{ e_{\\ms{first}} \\}$\n%   \\EndFunction\n%   \\end{algorithmic}\n%   \\label{alg:selectforward}\n%\\end{algorithm}\n\nIn a conventional vertex expansion algorithm,\ndetermining a successor's cost is a function of both\nthe cost of the edge and the value of the heuristic.\nIf either of these components is expensive to evaluate,\nan algorithm can defer its computation by maintaining the successor\non the frontier with an approximate cost until it is expanded.\nThe Fast Downward algorithm \\citep{helmert2006fastdownward} is motivated\nby expensive heuristic evaluations in planning,\nwhereas the Lazy Weighted A* (LWA*) algorithm \\citep{cohen2014narms}\nis motivated by expensive edge evaluations in robotics.\n\nWe show that the LazySP-Forward algorithm\nis edge-equivalent to a variant of the Lazy Weighted A*\nshortest-path algorithm.\nFor a given candidate path,\nthe Forward selector returns the first unevaluated edge.\n\n\\textbf{Variant of Lazy Weighted A*.}\nWe reproduce a variant of LWA* without a CLOSED list\nin Algorithm~\\ref{alg:lwastar}.\nFor the purposes of our analysis,\nthe reproduction differs from the original presentation,\nand we detail those differences here.\nWith the exception of the lack of CLOSED,\nthe differences do not affect the behavior of the algorithm.\n\n\\begin{algorithm}[t]\n\\caption{Lazy Weighted A* (without CLOSED list)}\n\\label{alg:lwastar}\n\\begin{algorithmic}[1]\n\\Function {\\textsc{LazyWeightedA*}}{$G, w, \\hat{w}, h$}\n\\State $g[v_{\\ms{start}}] \\leftarrow 0$\n\\State $Q_v \\leftarrow \\{ v_{\\ms{start}} \\}$\n   \\Comment Key: $g[v] + h(v)$\n   \\label{line:lwastar-key-qvertices}\n\\State $Q_e \\leftarrow \\emptyset$\n   \\Comment Key: $g[v] + \\hat{w}(v,v') + h(v')$\n   \\label{line:lwastar-key-qedges}\n\\While {$\\min(Q_v.{\\mbox{TopKey}}, Q_e.{\\mbox{TopKey}}) < g[v_{\\ms{goal}}]$}\n   \\If {$Q_v.{\\mbox{TopKey}} \\leq Q_e.{\\mbox{TopKey}}$}\n      \\State $v \\leftarrow Q_v.{\\mbox{Pop}}()$\n      \\For {$v' \\in G.\\mbox{GetSuccessors}(v)$}\n         \\State $Q_e.\\mbox{Insert}((v,v'))$\n      \\EndFor\n   \\Else\n      \\State $(v,v') \\leftarrow Q_e.{\\mbox{Pop}}()$\n      \\If {$g[v'] \\leq g[v] + \\hat{w}(v,v')$}\n         \\label{line:lwastar-test}\n         \\State {\\bf continue}\n      \\EndIf\n      \\State $g_{\\ms{new}} \\leftarrow g[v] + w(v,v')$\n         \\Comment evaluate\n      \\If {$g_{\\ms{new}} < g[v']$}\n         \\State $g[v'] = g_{\\ms{new}}$\n         \\State $Q_v.\\mbox{Insert}(v')$\n      \\EndIf\n   \\EndIf\n\\EndWhile\n\\EndFunction\n\\end{algorithmic}\n\\end{algorithm}\n\nThe most obvious difference is that we present the original OPEN list\nas separate vertex ($Q_v$) and edge ($Q_e$) priority queues,\nwith sorting keys shown on lines \\ref{line:lwastar-key-qvertices}\nand \\ref{line:lwastar-key-qedges}.\nA vertex $v$ in the original OPEN with $trueCost(v) = true$\ncorresponds to a vertex $v$ in $Q_v$,\nwhereas a vertex $v'$ in the original OPEN\nwith $trueCost(v') = false$ (and parent $v$)\ncorresponds to an edge $(v,v')$ in $Q_e$.\nUse of the edge queue obviates the need for\nduplicate vertices on OPEN with different parents\nand the $conf(v)$ test for identifying such duplicates.\nThis presentation also highlights the similarity between LWA*\nand the inner loop of the Batch Informed Trees (BIT*) algorithm\n\\citep{gammell2015bitstar}.\n\nThe second difference is that the edge usefulness test\n(line 12 of the original algorithm)\nhas been moved from before inserting into OPEN\nto after being popped from OPEN,\nbut before being evaluated\n(line~\\ref{line:lwastar-test} of Algorithm~\\ref{alg:lwastar}).\nThis change is partially in compensation for removing the CLOSED\nlist.\nThis adjustment\ndoes not affect the edges evaluated.\n\nWe make use of an invariant that is maintained during the\nprogression of Lazy Weighted A*.\n\\marginnote{Proof of all invariants are available\nin Appendix~\\ref{sec:appendix-proofs}.}\n\\begin{invariant}\nFor all vertex pairs $v$ and $v'$,\nwith $v'$ a successor of $v$,\nif $g[v] + \\max(w(v,v'), \\hat{w}(v,v')) < g[v']$,\nthen either vertex $v$ is on $Q_{v}$\nor edge $(v,v')$ is on $Q_e$.%\n\\label{inv:lwastar}%\n\\end{invariant}\nWe will use $h(v) = h_{\\ms{lazy}}(v)$ from (\\ref{eqn:h_lazy})\nand $\\hat{w} = w_{\\ms{lazy}}$.\nNote that the use of these dynamic heuristics requires that the\n$Q_v$ and $Q_e$ be resorted after every edge is evaluated.\n\n\\textbf{Equivalence.}\nThe equivalence follows similarly to that for A* above.\nGiven the same set of edges evaluated,\nthe set of allowable next evaluations is identical for each\nalgorithm.\n\\marginnote{Proof of all theorems are available\nin Appendix~\\ref{sec:appendix-proofs}.}\n\n\\begin{theorem}\nIf LazySP-Forward and LWA* have evaluated the same set of edges,\nthen for any allowable candidate path $p_{\\ms{candidate}}$\nchosen by LazySP yielding first unevaluated edge $e_{ab}$,\nthere exists an allowable LWA* sequence $s_{\\ms{candidate}}$\nwhich also yields $e_{ab}$.\n\\label{thm:lwastar-equiv-from-lazy}\n\\end{theorem}\n\n\\begin{theorem}\nIf LazySP-Forward and LWA* have evaluated the same set of edges,\nthen for any allowable sequence of vertices and edges $s_{\\ms{candidate}}$\nconsidered by LWA* yielding evaluated edge $e_{ab}$,\nthere exists an allowable LazySP candidate path $p_{\\ms{candidate}}$\nwhich also yields $e_{ab}$.\n\\label{thm:lwastar-equiv-to-lazy}\n\\end{theorem}\n\n\\subsection{Relation to Bidirectional Heuristic Search}\n\nLazySP-Alternate chooses unevaluated edges from either\nthe beginning or the end of the candidate path at each iteration.\nWe conjecture that an alternating version of the Expand selector\nis edge-equivalent to the\nBidirectional Heuristic Front-to-Front Algorithm\n\\citep{champeauxsint1977bhffa}\nfor appropriate lazy vertex pair heuristic,\nand that LazySP-Alternate is edge-equivalent\nto a bidirectional LWA*.\n\n\\begin{algorithm}[t]\n   \\caption{Maximum Edge Probability Selector\n      \\emph{(for WeightSamp and Partition path distributions)}}\n   \\begin{algorithmic}[1]\n   \\Function {\\textsc{SelectMaxEdgeProb}}{$G, p_{\\ms{candidate}}, \\mathcal{D}_p$}\n   \\State $p(e) \\leftarrow \\Pr( \\, e \\in P \\, )\n      \\mbox{ for } P \\sim \\mathcal{D}_p$\n   \\State $e_{\\ms{max}} \\leftarrow$ unevaluated $e \\in p_{\\ms{candidate}}$\n      maximizing $p(e)$\n   \\State \\Return $\\{ e_{\\ms{max}} \\}$\n   \\EndFunction\n   \\end{algorithmic}\n   \\label{alg:selectmaxscore}\n\\end{algorithm}\n\n\\section{Novel Edge Selectors}\n\nBecause we are conducting a search over paths,\nwe are free to implement selectors which are not constrained to\nevaluate edges in any particular order\n(i.e. to maintain evaluated trees rooted at the start and goal\nvertices).\nIn this section,\nwe describe a novel class of edge selectors which is designed\nto reduce the total number of edges evaluated during the course\nof the LazySP algorithm.\nThese selectors operate by maintaining a distribution over potential\npaths at each iteration of the algorithm\n(see Figure~\\ref{fig:maxprob-selectors-overview}).\nThis path distribution induces a Bernoulli distribution for each\nedge $e$ which indicates its probability $p(e)$ to lie on\nthe potential path;\nat each iteration,\nthe selectors then choose the unevaluated edge that maximizes\nthis edge indicator probability (Algorithm~\\ref{alg:selectmaxscore}).\nThe two selectors described in this section differ\nwith respect to how they maintain this distribution over potential paths.\n\n% make -f e8_experiments/scripts/Makefile.lazysp-fig-dists\n\\begin{figure}[t]\n   \\centering\n   \\begin{tikzpicture}\n      \\tikzset{>=latex}\n      \n      \\node[draw,minimum width=2.4cm,minimum height=3.0cm] (startbox) at (-3.0,0) {};\n      \\node[inner sep=0pt] at (-3.0,-0.35) {\\includegraphics[scale=2.0]{build/lazysp-fig-dists/fig-sofar}};\n      \\node[align=center,font=\\small,below] at (startbox.north) {known\\\\edges};\n      \n      \\node[draw] (quesbox) at (-1.2,0) {?};\n      \n      \\node[draw,minimum width=2.1cm,minimum height=3.0cm] (pathsbox) at (0.4,0) {};\n      \\node[inner sep=0pt] at (-0.05, 0.1) {\\includegraphics[scale=0.8]{build/lazysp-fig-dists/fig-path-00}};\n      \\node[inner sep=0pt] at ( 0.85, 0.1) {\\includegraphics[scale=0.8]{build/lazysp-fig-dists/fig-path-01}};\n      \\node[inner sep=0pt] at (-0.05,-0.8) {\\includegraphics[scale=0.8]{build/lazysp-fig-dists/fig-path-02}};\n      \\node[inner sep=0pt] at ( 0.85,-0.8) {\\includegraphics[scale=0.8]{build/lazysp-fig-dists/fig-path-03}};\n      \\node[align=center,font=\\small,below] at (pathsbox.north) {path\\\\distribution};\n      \\node[align=center,font=\\normalsize,above] at (pathsbox.south) {$\\dots$};\n      \n      \\node[draw,minimum width=2.4cm,minimum height=3.0cm] (goalbox) at (3.0,0) {};\n      \\node[inner sep=0pt] at (3.0,-0.35) {\\includegraphics[scale=2.0]{build/lazysp-fig-dists/fig-dist-probs}};\n      \\node[align=center,font=\\small,below] at (goalbox.north) {edge indicator\\\\distributions};\n      \n      \\draw[->] (startbox) -- (quesbox);\n      \\draw[->] (quesbox) -- (pathsbox);\n      \\draw[->] (pathsbox) -- (goalbox);\n      \n   \\end{tikzpicture}\n   \\caption{Illustration of maximum edge probability selectors.\n      A distribution over paths\n      (usually conditioned on the known edge evaluations)\n      induces on each edge $e$ a Bernoulli distribution\n      with parameter $p(e)$\n      giving the probability that it belongs to the path.\n      The selector chooses the edge with the largest such probability.}\n   \\label{fig:maxprob-selectors-overview}\n\\end{figure}\n\n\\subsection{Weight Function Sampling Selector}\n\nThe first selector, WeightSamp,\nis motivated by the intuition that it is preferable to evaluate edges\nthat are most likely to lie on the true shortest path.\nTherefore,\nit computes its path distribution $\\mathcal{D}_p$\nby performing shortest path queries\non sampled edge weight functions drawn from a distribution\n$\\mathcal{D}_w$.\nThis edge weight distribution is conditioned on the the known weights\nof all previously evaluated edges $E_{\\ms{eval}}$:\n\\begin{equation}\n   \\mathcal{D}_p : \\mbox{SP}(w)\n   \\mbox{ for } w \\sim \\mathcal{D}_w(E_{\\ms{eval}})\n   \\label{eqn:weightsamp}.\n\\end{equation}\n\nFor example,\nthe distribution $\\mathcal{D}_w$ might consist of\nthe edge weights induced by a model of the distribution of\nenvironment obstacles\n(Figure~\\ref{fig:weightsamp}).\nSince this obstacle distribution is conditioned on the results\nof known edge evaluations,\nwe consider the subset of worlds which are consistent\nwith the edges we have evaluated so far.\nHowever,\ndepending on the fidelity of this model,\nsolving the corresponding shortest path problem for a given\nsampled obstacle arrangement might require as much computation as\nsolving the original problem,\nsince it requires computing the resulting edge weights.\nIn practice,\nwe can approximate $\\mathcal{D}_w$\nby assuming that each edge is independently distributed.\n\n\\begin{figure}[t]\n   \\centering\n   \\begin{tikzpicture}\n      \\tikzset{>=latex}\n      \n      \\node[draw,minimum width=1.8cm,minimum height=2.6cm] (startbox) at (-4.4,0) {};\n      \\node[inner sep=0pt] at (-4.4,-0.35) {\\includegraphics[scale=1.5]{build/lazysp-fig-dists/fig-sofar}};\n      \\node[align=center,font=\\small,below] at (startbox.north) {known\\\\edges};\n      \n      \\node[draw,minimum width=1.8cm,minimum height=6cm] (abox) at (-2.2,0) {};\n      \\node[inner sep=0pt] at (-2.2, 1.3) {\\includegraphics[scale=1.5]{build/lazysp-fig-dists/fig-world-00}};\n      \\node[inner sep=0pt] at (-2.2,-0.3) {\\includegraphics[scale=1.5]{build/lazysp-fig-dists/fig-world-01}};\n      \\node[inner sep=0pt] at (-2.2,-1.9) {\\includegraphics[scale=1.5]{build/lazysp-fig-dists/fig-world-02}};\n      \\node[align=center,font=\\small,below] at (abox.north) {obstacle\\\\distribution};\n      \\node[align=center,font=\\normalsize,above] at (abox.south) {$\\dots$};\n      \n      \\node[draw,minimum width=1.8cm,minimum height=6cm] (bbox) at (0,0) {};\n      \\node[inner sep=0pt] at (0, 1.3) {\\includegraphics[scale=1.5]{build/lazysp-fig-dists/fig-wfn-00}};\n      \\node[inner sep=0pt] at (0,-0.3) {\\includegraphics[scale=1.5]{build/lazysp-fig-dists/fig-wfn-01}};\n      \\node[inner sep=0pt] at (0,-1.9) {\\includegraphics[scale=1.5]{build/lazysp-fig-dists/fig-wfn-02}};\n      \\node[align=center,font=\\small,below] at (bbox.north) {weight fn\\\\distribution};\n      \\node[align=center,font=\\normalsize,above] at (bbox.south) {$\\dots$};\n      \n      \\node[draw,minimum width=1.8cm,minimum height=6cm] (cbox) at (2.2,0) {};\n      \\node[inner sep=0pt] at (2.2, 1.3) {\\includegraphics[scale=1.5]{build/lazysp-fig-dists/fig-path-00}};\n      \\node[inner sep=0pt] at (2.2,-0.3) {\\includegraphics[scale=1.5]{build/lazysp-fig-dists/fig-path-01}};\n      \\node[inner sep=0pt] at (2.2,-1.9) {\\includegraphics[scale=1.5]{build/lazysp-fig-dists/fig-path-02}};\n      \\node[align=center,font=\\small,below] at (cbox.north) {path\\\\distribution};\n      \\node[align=center,font=\\normalsize,above] at (cbox.south) {$\\dots$};\n      \n      \\draw[->] (startbox) -- (abox);\n      \\draw[->] (abox) -- (bbox);\n      \\draw[->] (bbox) -- (cbox);\n   \\end{tikzpicture}\n   \\caption{The WeightSamp selector uses the path distribution induced by\n      solving the shortest path problem on a distribution over possible\n      edge weight functions $\\mathcal{D}_w$.\n      In this example, samples from $\\mathcal{D}_w$ are computed by\n      drawing samples from $\\mathcal{D}_O$,\n      the distribution of obstacles that are consistent with\n      the known edge evaluations.}\n   \\label{fig:weightsamp}\n\\end{figure}\n\n\\subsection{Partition Function Selector}\n\nWhile the WeightSamp selector captures the intuition that it is\npreferable to focus edge evaluations in areas that are useful for\nmany potential paths,\nthe computational cost required to calculate it at each iteration\nmay render it intractable.\nOne candidate path distribution that is more efficient to compute\nfollows an exponential form:\n\\begin{equation}\n   \\mathcal{D}_p : f_P(p) \\propto\n   \\exp( - \\beta \\, \\mbox{len}(p, w_{\\ms{lazy}}) ).\n\\end{equation}\nIn other words,\nwe consider all potential paths $P$\nbetween the start and goal vertices,\nwith shorter paths assigned more exponentially probability\nthan longer ones\n(with positive parameter $\\beta$).\nWe call this the Partition selector\nbecause this distribution is closely related to calculating\npartition functions from statistical mechanics.\nThe corresponding partition function is:\n\\begin{equation}\n   Z(P) = \\sum_{p \\in P}\n      \\exp( - \\beta \\, \\mbox{len}(p, w_{\\ms{lazy}}) ).\n   \\label{eqn:partitionfn}\n\\end{equation}\nNote that the edge indicator probability\nrequired in Algorithm~\\ref{alg:selectmaxscore}\ncan then be written:\n\\begin{equation}\n   p(e) = 1 - \\frac{Z(P \\setminus e)}{Z(P)}.\n   \\label{eqn:edge-ind-prob}\n\\end{equation}\nHere, $P \\setminus e$ denotes paths in $P$ that do not\ncontain edge $e$.\n\n\\begin{figure}\n   \\centering\n   \\subfloat[Initial $p(e)$ scores on a constant-weight\n         grid with $\\beta$: 50, 33, 28]{%\n      \\centering\n      \\includegraphics{build/lazysp-selscores/empty-50}\n      \\includegraphics{build/lazysp-selscores/empty-33}\n      \\includegraphics{build/lazysp-selscores/empty-28}\n      \\label{subfig:partition-empty}\n   }\n   \n   \\subfloat[Initial $p(e)$ scores with $\\infty$-weight\n         obstacles with $\\beta$: 50, 33, 28]{%\n      \\centering\n      \\includegraphics{build/lazysp-selscores/gap-50}\n      \\includegraphics{build/lazysp-selscores/gap-33}\n      \\includegraphics{build/lazysp-selscores/gap-28}\n      \\label{subfig:partition-passage}\n   }\n   \n   % $ rosrun e8_experiments lazysp-partall-figure.py\n   % --probdir=prob-box2d08-halton-roots12\n   % --snapshot-afteredges=0 --out-tikz=partall-figure-0.tex\n   \\subfloat[Initial $p(e)$ scores]{%\n      \\centering\n      \\;\n      \\includegraphics{build/lazysp-partall/partall-figure-0}\n      \\;\n      \\label{subfig:partition-example-initial}\n   }\n   % $ rosrun e8_experiments lazysp-partall-figure.py\n   % --probdir=prob-box2d08-halton-roots12\n   % --snapshot-afteredges=5 --out-tikz=partall-figure-5.tex\n   \\subfloat[Scores after five evaluations]{%\n      \\centering\n      \\;\n      \\includegraphics{build/lazysp-partall/partall-figure-5}\n      \\;\n      \\label{subfig:partition-example-after5}\n   }\n   \\vspace{0.2cm}\n\n   \\caption{Examples of the Partition selector's\n      $p(e)$ edge score function.\n      %(\\subref{subfig:partition-empty})\n      With no known obstacles,\n      a high $\\beta$ assigns near-unity score to only edges on the\n      shortest path;\n      as $\\beta$ decreases and more paths are considered,\n      edges immediately adjacent to the roots score highest.\n      %(\\subref{subfig:partition-passage})\n      Since all paths must pass\n      through the narrow passage,\n      edges within score highly.\n      %(\\subref{subfig:partition-example-initial})\n      For a problem with two a-priori known obstacles (dark gray),\n      the score first prioritizes evaluations between the two.\n      %(\\subref{subfig:partition-example-after5})\n      Upon finding these edges are blocked,\n      the next edges that are prioritized lie along the top of the world.}\n   \\label{ref:example-scores}\n\\end{figure}\n\nIt may appear advantageous to restrict $P$ to only\n\\emph{simple} paths,\nsince all optimal paths are simple.\nUnfortunately,\nan algorithm for computing (\\ref{eqn:edge-ind-prob}) efficiently is not\ncurrently known in this case.\nHowever,\nin the case that $P$ consists of all paths,\nthere does exist an efficient incremental calculation of\n(\\ref{eqn:partitionfn}) via a recursive formulation.\n\nWe use the notation $Z_{xy} = Z(P_{xy})$,\nwith $P_{xy}$ the set of paths from $x$ to $y$.\nSuppose the values $Z_{xy}$ are known between\nall pairs of vertices $x, y$ for a graph $G$.\n(For a graph with no edges,\n$Z_{xy}$ is 1 if $x = y$ and 0 otherwise.)\nConsider a modified graph $G'$ with one additional edge $e_{ab}$\nwith weight $w_{ab}$.\nAll additional paths use the new edge $e_{ab}$ a non-zero\nnumber of times;\nthe value $Z'_{xy}$ can be shown to be\n\\begin{equation}\n   Z'_{xy} = Z_{xy} + \\frac{Z_{xa} Z_{by}}{\\exp(\\beta w_{ab}) - Z_{ba}}\n   \\mbox{ if }\n   \\exp(\\beta w_{ab}) > Z_{ba}.\n\\end{equation}\nThis form is derived from simplifying the induced geometric series;\nnote that if $\\exp(\\beta w_{ab})  \\leq Z_{ba}$,\nthe value $Z'_{xy}$ is infinite.\nOne can also derive the inverse:\ngiven values $Z'$,\ncalculate the values $Z$ if an edge were removed.\nA derivation of this formulation is given in\nAppendix~\\ref{chap:appendix-partition}.\n\nThis incremental formulation of (\\ref{eqn:partitionfn})\nallows for the corresponding score $p(e)$ for edges\nto be updated efficiently during each iteration of LazySP as\nthe $w_{\\ms{lazy}}$ value for edges chosen for evaluation are updated.\nIn fact,\nif the values $Z$ are stored in a square matrix,\nthe update for all pairs after an edge weight change consists of a single\nvector outer product.\n\n\\section{Experiments}\n\nWe compared the seven edge selectors on three classes of shortest path\nproblems.\nThe average number of edges evaluated by each,\nas well as timing results from our implementations,\nare shown in Figure~\\ref{fig:results}.\nIn each case,\nthe estimate was chosen so that $w_{\\ms{est}} \\leq w$,\nso that all runs produced optimal paths.\nThe experimental results serve primarily to illustrate that\nthe A* and LWA* algorithms\n(i.e. Expand and Forward)\nare not optimally edge-efficient,\nbut they also expose differences in behavior and prompt\nfuture research directions.\nAll experiments were conducted using an open-source\nimplementation.\nMotion planning results were implemented using\nOMPL \\citep{sucan2012ompl}.\n\n\\textbf{Random partially-connected graphs.}\nWe tested on a set of 1000 randomly-generated undirected graphs\nwith $|V|=100$,\nwith each pair of vertices sharing an edge with probability 0.05.\nEdges have an independent 0.5 probability of having infinite weight,\nelse the weight is uniformly distributed on $[1,2]$;\nthe estimated weight was unity for all edges.\nFor the WeightSamp selector,\nwe drew 1000 $w$ samples.\nFor the Partition selector, we used $\\beta = 2$.\n\n\\textbf{Roadmap graphs on the unit square.}\nWe considered roadmap graphs formed via the first 100 points\nof the $(2,3)$-Halton sequence on the unit square\nwith a connection radius of 0.15,\nwith 30 pairs of start and goal vertices chosen randomly.\nThe edge weight function was derived from 30 sampled obstacle fields\nconsisting of 10 randomly placed boxes\nwith dimensions uniform on $[0.1,0.3]$,\nwith each edge having infinite weight on collision,\nand weight equal to its Euclidean length otherwise.\nOne of the resulting 900 example problems is shown in\nFigure~\\ref{fig:snapshots}.\nFor the WeightSamp selector,\nwe drew 1000 $w$ samples\nwith a na\\\"{\\i}ve edge weight distribution in which\neach edge had an independent 0.1 collision probability.\nFor the Partition selector, we used $\\beta = 21$.\n\n\\textbf{Roadmap graphs for robot arm motion planning.}\nWe considered roadmap graphs in the configuration space\ncorresponding to 7-DOF right arm of the HERB home robot across three\nmotion planning problems inspired by a table clearing scenario\n(see Figure~\\ref{fig:herbbin0}).\nThe problems consisted of first moving from the robot's\nhome configuration to one of 7 feasible grasp configurations for a mug\n(pictured),\nsecond transferring the mug to one of 72 feasible configurations with\nthe mug above the blue bin,\nand third returning to the home configuration.\nEach problem was solved independently.\nThis common scenario spans various numbers of starts/goals\nand allows a comparison w.r.t. difficulty at different problem\nstages as discussed later.\n\nFor each problem,\n50 random graphs were constructed by applying a random offset to\nthe 7D Halton sequence with $N = 1000$,\nwith additional vertices for each problem start and goal configuration.\nWe used an edge connection radius of 3 rad,\nresulting $|E|$ ranging from 23404 to 28109.\nEach edge took infinite weight on collision,\nand weight equal to its Euclidean length otherwise.\nFor the WeightSamp selector,\nwe drew 1000 $w$ samples\nwith a na\\\"{\\i}ve edge weight distribution in which\neach edge had an independent 0.1 probability of collision.\nFor the Partition selector, we used $\\beta = 3$.\n\n\\begin{figure*}\n\\centering\n%\\includegraphics[width=3cm]{figs/herbbin0.png}\n\\includegraphics[width=3.1cm]{figs/lazysp-herbarm/herbarm-roadmap.png}\n\\includegraphics[width=3.1cm]{figs/lazysp-herbarm/herbarm-path02.png}\n%\\includegraphics[width=3cm]{figs/lazysp-herbarm/herbarm-path11.png}\n%\\includegraphics[width=3cm]{figs/lazysp-herbarm/herbarm-path21.png}\n\\includegraphics[width=3.1cm]{figs/lazysp-herbarm/herbarm-path33.png}\n\\includegraphics[width=3.1cm]{figs/lazysp-herbarm/herbarm-path42.png}\n\\includegraphics[width=3.1cm]{figs/lazysp-herbarm/herbarm-path46.png}\n\\caption{Visualization of the first of three articulated motion\n   planning problems in which the HERB robot must move its right arm\n   from the start configuration (pictured)\n   to any of seven grasp configurations for a mug.\n   Shown is the progression of the Alternate selector on one of the\n   randomly generated roadmaps;\n   approximately 2\\% of the 7D roadmap is shown in gray by projecting\n   onto the space of end-effector positions.}\n\\label{fig:herbbin0}\n\\end{figure*}\n\n\\begin{figure}[t!]\n   \\centering\n   \\subfloat[\n      Average number of edges evaluated for each problem class\n         and selector.\n         The minimum selector,\n         along with any selector within one unit of its standard error,\n         is shown in bold.\n         The ArmPlan class is split into its three constituent problems.\n         Online timing results are also shown,\n         including the components from the invoking the selector\n         and evaluating edges.\n         \\dag PartConn and UnitSquare involve trivial edge evaluation\n         time.\n         \\ddag Timing for the Partition selector does not include\n         pre-computation time.\n         See Figure~\\ref{fig:table-timing-results} for details.]\n   {%\n      \\centering\n      {\\small%\n      \\setlength{\\tabcolsep}{0.06cm}%\n      \\begin{tabular}{lrrrrrrr}\n         \\toprule\n            & E\\;\\;\\;\\;\n            & F\\;\\;\\;\\; & R\\;\\;\\;\\; & A\\;\\;\\;\\;\n            & B\\;\\;\\;\\; & W\\;\\;\\;\\; & P\\ddag\\;\\; \\\\\n         \\midrule\n         \\addlinespace[0.3em]\n         PartConn &  87.10 & 35.86 & 34.84 & 22.23 & 44.81 & \\textbf{20.66} & \\textbf{20.39} \\\\\n         \\;\\;\\emph{online\\dag (ms)} & \\bf\\emph{1.22} & \\emph{1.96} & \\emph{1.86} & \\bf\\emph{1.20} & \\emph{2.41} & \\emph{4807.19} & \\emph{3.32} \\\\\n         \\;\\;\\;\\;\\emph{sel (ms)} & \\emph{0.02} & \\emph{0.01} & \\emph{0.01} & \\emph{0.01} & \\emph{0.03} & \\emph{4805.64} & \\emph{2.07} \\\\\n         \\addlinespace[0.3em]\n         UnitSquare &  69.21 & 27.29 & 27.69 & 17.82 & 32.62 & 15.58 & \\textbf{14.08} \\\\\n         \\;\\;\\emph{online\\dag (ms)} & \\bf\\emph{0.91} & \\emph{1.47} & \\emph{1.49} & \\bf\\emph{0.94} & \\emph{1.71} & \\emph{3864.95} & \\emph{1.72} \\\\\n         \\;\\;\\;\\;\\emph{sel (ms)} & \\emph{0.01} & \\emph{0.01} & \\emph{0.01} & \\emph{0.01} & \\emph{0.02} & \\emph{3863.49} & \\emph{0.87} \\\\\n         \\addlinespace[0.3em]\n         ArmPlan(avg) & 949.05 & 63.62 & 74.94 & 55.48 & 68.01 & 56.93 & \\textbf{48.07} \\\\\n         \\;\\;\\emph{online (s)} & \\emph{269.82} & \\bf\\emph{5.90} & \\emph{8.22} & \\bf\\emph{5.96} & \\emph{7.34} & \\emph{3402.21} & \\bf\\emph{5.80} \\\\\n         \\;\\;\\;\\;\\emph{sel (s)} & \\emph{0.00} & \\emph{0.00} & \\emph{0.00} & \\emph{0.00} & \\emph{0.00} & \\emph{3392.76} & \\emph{1.54} \\\\\n         \\;\\;\\;\\;\\emph{eval (s)} & \\emph{269.78} & \\emph{5.87} & \\emph{8.20} & \\emph{5.94} & \\emph{7.31} & \\emph{9.39} & \\emph{4.21} \\\\\n         \\addlinespace[0.3em]\n         ArmPlan1 &  344.74 & \\textbf{49.72} & 95.58 & 59.44 & 58.90 & 73.72 & \\textbf{50.66} \\\\\n         \\;\\;\\emph{online (s)} & \\emph{109.09} & \\bf\\emph{4.81} & \\emph{14.81} & \\emph{7.03} & \\emph{7.91} & \\emph{3375.35} & \\emph{7.25} \\\\\n         \\;\\;\\;\\;\\emph{sel (s)} & \\emph{0.00} & \\emph{0.00} & \\emph{0.00} & \\emph{0.00} & \\emph{0.00} & \\emph{3358.82} & \\emph{1.61} \\\\\n         \\;\\;\\;\\;\\emph{eval (s)} & \\emph{109.07} & \\emph{4.78} & \\emph{14.77} & \\emph{7.01} & \\emph{7.88} & \\emph{16.47} & \\emph{5.59} \\\\\n         \\addlinespace[0.3em]\n         ArmPlan2 &  657.02 & \\textbf{62.24} & 98.54 & 69.96 & 75.88 & \\textbf{66.24} & \\textbf{62.16} \\\\\n         \\;\\;\\emph{online (s)} & \\emph{166.19} & \\bf\\emph{3.27} & \\emph{7.36} & \\emph{5.95} & \\emph{5.63} & \\emph{4758.04} & \\emph{5.99} \\\\\n         \\;\\;\\;\\;\\emph{sel (s)} & \\emph{0.00} & \\emph{0.00} & \\emph{0.00} & \\emph{0.00} & \\emph{0.00} & \\emph{4750.16} & \\emph{2.03} \\\\\n         \\;\\;\\;\\;\\emph{eval (s)} & \\emph{166.17} & \\emph{3.26} & \\emph{7.34} & \\emph{5.93} & \\emph{5.61} & \\emph{7.82} & \\emph{3.91} \\\\\n         \\addlinespace[0.3em]\n         ArmPlan3 & 1845.38 & 78.90 & \\textbf{30.70} & 37.04 & 69.26 & \\textbf{30.82} & \\textbf{31.38} \\\\\n         \\;\\;\\emph{online (s)} & \\emph{534.16} & \\emph{9.61} & \\bf\\emph{2.50} & \\emph{4.91} & \\emph{8.47} & \\emph{2073.23} & \\emph{4.17} \\\\\n         \\;\\;\\;\\;\\emph{sel (s)} & \\emph{0.00} & \\emph{0.00} & \\emph{0.00} & \\emph{0.00} & \\emph{0.00} & \\emph{2069.29} & \\emph{0.98} \\\\\n         \\;\\;\\;\\;\\emph{eval (s)} & \\emph{534.10} & \\emph{9.58} & \\emph{2.48} & \\emph{4.89} & \\emph{8.44} & \\emph{3.90} & \\emph{3.15} \\\\\n         \\addlinespace[0.15em]\n         \\bottomrule\n      \\end{tabular}%\n      }%\n      \\label{subfig:table-results}\n   }\n   \n   \\vspace{0.1in}\n   \n   \\subfloat[PartConn]{%\n      \\centering\n      \\begin{tikzpicture}\n      \\begin{axis}[\n         width=4.1cm,\n         height=4.0cm,\n         ybar,\n         bar width=7,\n         ymin=0,ymax=90,\n         ytick pos=bottom,\n         symbolic x coords={E, F, R, A, B, W, P},\n         xtick=data,\n         xtick pos=left,\n         ymajorgrids,\n         ymajorticks=false,\n         ticklabel style={font=\\small}\n         ]\n      \\node[circle,fill=white,inner sep=1pt,text=black!40] at (axis cs:P,40) {\\scriptsize 40};\n      \\node[circle,fill=white,inner sep=1pt,text=black!40] at (axis cs:P,60) {\\scriptsize 60};\n      \\node[circle,fill=white,inner sep=1pt,text=black!40] at (axis cs:P,80) {\\scriptsize 80};\n      \\addplot[color=black,fill=black!20,error bars/.cd,y dir=both,y explicit] coordinates {\n         (E, 87.10) +- (2.39,2.39)\n         (F, 35.86) +- (1.04,1.04)\n         (R, 34.84) +- (1.04,1.04)\n         (A, 22.23) +- (0.60,0.60)\n         (B, 44.81) +- (1.11,1.11)\n         (W, 20.66) +- (0.57,0.57)\n         (P, 20.39) +- (0.56,0.56)\n      };\n      \\end{axis}\n      \\end{tikzpicture}\n   }\n   \\subfloat[UnitSquare]{%\n      \\centering\n      \\begin{tikzpicture}\n      \\begin{axis}[\n         width=4.1cm,\n         height=4.0cm,\n         ybar,\n         bar width=7,\n         ymin=0,ymax=90,\n         ytick pos=bottom,\n         symbolic x coords={E, F, R, A, B, W, P},\n         xtick=data,\n         xtick pos=left,\n         ymajorgrids,\n         ymajorticks=false,\n         ticklabel style={font=\\small}\n         ]\n      \\node[circle,fill=white,inner sep=1pt,text=black!40] at (axis cs:P,40) {\\scriptsize 40};\n      \\node[circle,fill=white,inner sep=1pt,text=black!40] at (axis cs:P,60) {\\scriptsize 60};\n      \\node[circle,fill=white,inner sep=1pt,text=black!40] at (axis cs:P,80) {\\scriptsize 80};\n      \\addplot[color=black,fill=black!20,error bars/.cd,y dir=both,y explicit] coordinates {\n         (E, 69.21) +- (2.55,2.55)\n         (F, 27.29) +- (1.03,1.03)\n         (R, 27.69) +- (1.02,1.02)\n         (A, 17.82) +- (0.60,0.60)\n         (B, 32.62) +- (0.72,0.72)\n         (W, 15.58) +- (0.47,0.47)\n         (P, 14.08) +- (0.46,0.46)\n      };\n      \\end{axis}\n      \\end{tikzpicture}\n   }\n   \\subfloat[ArmPlan]{%\n      \\centering\n      \\begin{tikzpicture}\n      \\begin{axis}[\n         width=4.1cm,\n         height=4.0cm,\n         ybar,\n         bar width=7,\n         ymin=0,ymax=115,\n         max space between ticks=10,\n         ytick pos=bottom,\n         symbolic x coords={E, F, R, A, B, W, P},\n         xtick=data,\n         xtick pos=left,\n         ymajorgrids,\n         ymajorticks=false,\n         ticklabel style={font=\\small}\n         ]\n      \\node[circle,fill=white,inner sep=0pt,text=black!40] at (axis cs:P,60) {\\scriptsize 60};\n      \\node[circle,fill=white,inner sep=0pt,text=black!40] at (axis cs:P,80) {\\scriptsize 80};\n      \\node[circle,fill=white,inner sep=0pt,text=black!40] at (axis cs:P,100) {\\scriptsize 100};\n      \\addplot[color=black,fill=black!20,error bars/.cd,y dir=both,y explicit] coordinates {\n         (E, 115) +- (0,0) % 49.06 +- 61.63.46\n         (F, 63.62) +- (4.15,4.15)\n         (R, 74.94) +- (5.07,5.07)\n         (A, 55.48) +- (2.95,2.95)\n         (B, 68.01) +- (3.86,3.86)\n         (W, 56.93) +- (3.37,3.37)\n         (P, 48.07) +- (2.44,2.44)\n      };\n      \\node[align=center,anchor=north,inner sep=0pt] at (axis cs:E,111) {\\scriptsize $\\uparrow$};\n      \\end{axis}\n      \\end{tikzpicture}\n   }\n   \\caption{\n      Experimental results for the three problem classes\n      across each of the seven selectors,\n      E:Expand, F:Forward, R:Reverse,\n      A:Alternate, B:Bisection,\n      W:WeightSamp, and P:Partition.\n      In addition to the summary table (a),\n      the plots (b-d) show summary statistics for\n      each problem class.\n      The means and standard errors in (b-c) are across the\n      1000 and 900 problem instances, respectively.\n      The means and standard errors in (d) are for\n      the average across the three constituent problems\n      for each of the 50 sampled roadmaps.\n      A more detailed table of results is available\n      in Appendix~\\ref{sec:appendix-proofs}.}\n   \\label{fig:results}\n\\end{figure}\n\n\\section{Discussion}\n%\\label{sec:discussion}\n\nThe first observation that is evident from the experimental results\nis that lazy evaluation\n-- whether using Forward (LWA*) or one of the other selectors --\ngrossly outperforms Expand (A*).\nThe relative penalty that Expand incurs by evaluating all edges from\neach expanded vertex is a function of the graph's branching factor.\n\nSince the Forward and Reverse selectors are simply mirrors of each\nother,\nthey exhibit similar performance\naveraged across the PartConn and UnitSquare problem classes,\nwhich are symmetric.\nHowever,\nthis need not the case for a particular instance.\nFor example,\nthe start of ArmPlan1 and the goal of ArmPlan3 consist\nof the arm's single home configuration in a relatively confined space.\nAs shown in the table in\nFigure~\\ref{fig:results}\\subref{subfig:table-results},\nit appears that the better selector on these problems attempts\nto solve the more constrained side of the problem first.\nWhile it may be difficult to determine a priori which part of the\nproblem will be the most constrained,\nthe simple Alternate selector's respectable performance\nsuggests that it may be a reasonable compromise.\n\nThe per-path plots at the bottom of Figure~\\ref{fig:snapshots}\nallow us to characterize the selectors' behavior.\nFor example,\nAlternate often evaluates several edges on each path before finding\nan obstacle.\nIts early evaluations also tend to be useful later,\nand it terminates after considering 10 paths on the illustrated problem.\nIn contrast, Bisection exhibits a fail-fast strategy,\nquickly invalidating most paths after a single evaluation,\nbut needing 16 such paths (with very little reuse)\nbefore it terminates.\nIn general, the Bisection selector did not outperform any of the\nlazy selectors in terms of number of edges evaluated.\nHowever,\nit may be well suited to problem domains in which\nevaluations that fail tend be less costly.\n\nThe novel selectors based on path distributions tend to minimize\nedge evaluations on the problems we considered.\nWhile the WeightSamp selector performs similarly to Partition on the\nsimpler problems,\nit performs less well in the ArmPlan domain.\nThis may be because many more samples are needed to approximate\nthe requisite path distribution.\n\nThe path distribution selectors are motivated by focusing evaluation\neffort in areas that are useful for many distinct candidate paths,\nas illustrated in Figure~\\ref{ref:example-scores}.\nNote that in the absence of a priori knowledge,\nthe edges nearest to the start and goal tend to have the highest\n$p(e)$ score,\nsince they are members of many potential paths.\nBecause it tends to focus evaluations in a similar way,\nthe Alternate selector may serve as a simple proxy for the\nmore complex selectors.\n\nWe note that\nan optimal edge selector could be theoretically achieved by posing the\nedge selection problem as a POMDP,\ngiven a probabilistic model of the true costs.\nWhile likely intractable in complex domains,\nexploring this solution may yield useful approximations or insights.\n", "meta": {"hexsha": "f5bc7f0bc96c67c37edf323c146b8f23e990a171", "size": 66043, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis-ch03-lazysp.tex", "max_stars_repo_name": "siddhss5/phdthesis-dellin", "max_stars_repo_head_hexsha": "62ca559db0ad0a6285012708ef718f4fde4e1dcd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-09-06T21:45:42.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-06T21:45:42.000Z", "max_issues_repo_path": "thesis-ch03-lazysp.tex", "max_issues_repo_name": "siddhss5/phdthesis-dellin", "max_issues_repo_head_hexsha": "62ca559db0ad0a6285012708ef718f4fde4e1dcd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis-ch03-lazysp.tex", "max_forks_repo_name": "siddhss5/phdthesis-dellin", "max_forks_repo_head_hexsha": "62ca559db0ad0a6285012708ef718f4fde4e1dcd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.6149968494, "max_line_length": 145, "alphanum_fraction": 0.698953712, "num_tokens": 19819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.32879269032159997}}
{"text": "\\chapter{Magnetic Inversion}\\label{Chp:cook:magnetic inversion}\n\n\\begin{figure}\n\\centering\n\\includegraphics[width=0.7\\textwidth]{QLDWestMagneticDataPlot.png}\n\\caption{Magnetic anomaly data in $nT$ from Western Queensland, Australia\n    (file \\examplefile{data/QLDWestMagnetic.nc}). Data obtained from Geoscience Australia.}\n\\label{FIG:P1:MAG:0}\n\\end{figure}\n\nMagnetic data report the observed magnetic flux density over a region above the\nsurface of the Earth.\nSimilar to the gravity case the data are given as deviation from an expected\nbackground magnetic flux density $B^b$ of the Earth.\nExample data in units of $nT$ (nano Tesla) are shown in Figure~\\ref{FIG:P1:MAG:0}.\nIt is the task of the inversion to recover the susceptibility distribution $k$\nfrom the magnetic data collected. The approach for inverting magnetic data is\nalmost identical to the one used for gravity data. \nIn fact the \\downunder script~\\ref{code: magnetic1} used for the magnetic\ninversion is very similar to the script~\\ref{code: gravity1} for gravity inversion.\n\n\\begin{pyc}\\label{code: magnetic1}\n\\\n\\begin{python}\n# Header:\nfrom esys.downunder import *\nfrom esys.weipa import *\nfrom esys.escript import unitsSI as U\n\n\n# Step 1: set up domain\ndom=DomainBuilder()\ndom.setVerticalExtents(depth=40.*U.km, air_layer=6.*U.km, num_cells=25)\ndom.setFractionalPadding(pad_x=0.2, pad_y=0.2)\nB_b = [2201.*U.Nano*U.Tesla,  31232.*U.Nano*U.Tesla, -41405.*U.Nano*U.Tesla]\ndom.setBackgroundMagneticFluxDensity(B_b)\ndom.fixSusceptibilityBelow(depth=40.*U.km)\n\n# Step 2: read magnetic data\nsource0=NetCdfData(NetCdfData.MAGNETIC, 'MagneticSmall.nc', \n    scale_factor=U.Nano * U.Tesla)\ndom.addSource(source0)\n\n# Step 3: set up inversion\ninv=MagneticInversion()\ninv.setSolverTolerance(1e-4)\ninv.setSolverMaxIterations(50)\ninv.fixMagneticPotentialAtBottom(False)\ninv.setup(dom)\n\n# Step 4: run inversion \ninv.getCostFunction().setTradeOffFactorsModels(0.1) \nk = inv.run()\n\n# Step 5: write reconstructed susceptibility to file\nsaveVTK(\"result.vtu\", susceptibility=k)\n\\end{python}\n\\end{pyc}\n\n\\begin{figure}\n\\centering\n\\includegraphics[width=0.7\\textwidth]{QLDMagContourMu01.png}\n\\caption{Contour plot of the susceptibility from a three-dimensional magnetic inversion (with $\\mu=0.1$).\nColours represent values of susceptibility where high values are represented by\n    blue and low values are represented by red.}\n\\label{FIG:P1:MAG:1}\n\\end{figure}\n\nThe structure of the script is identical to the gravity case.\nFollowing the header section importing the necessary modules the domain of the\ninversion is defined in step one.\nIn step two the data are read and added to the domain builder.\nStep three sets up the inversion and step four runs it.\nFinally in step five the result is written to the result file, here\n\\file{result.vtu} in the \\VTK format.\nResults are shown in Figure~\\ref{FIG:P1:MAG:1}.\n\nAlthough scripts for magnetic and gravity inversion are largely identical there\nare a few small differences which we are going to highlight now.\nThe magnetic inversion requires data about the background magnetic flux density\nover the region of interest which is added to the domain by the statements \n\\begin{verbatim}\nB_b = [2201.*U.Nano*U.Tesla, 31232.*U.Nano*U.Tesla,  \n    -41405.*U.Nano*U.Tesla]\ndom.setBackgroundMagneticFluxDensity(B_b)\n\\end{verbatim}\nHere it is assumed that the background magnetic flux density is constant across\nthe domain and is given as the list\n\\begin{verbatim}\nB_b= [ B_E,  B_N, B_V ]\n\\end{verbatim}\nin units of Tesla (T) where \n\\member{B_N}, \\member{B_E} and \\member{B_V} refer to the north, east and\nvertical component of the magnetic flux density, respectively.\nValues for the magnetic flux density can be obtained by the International\nGeomagnetic Reference Field (IGRF)~\\cite{IGRF} (or the Australian Geomagnetic\nReference Field (AGRF)~\\cite{AGRF} via \\url{http://www.ga.gov.au/oracle/geomag/agrfform.jsp}).\nSimilar to the gravity case susceptibility below a certain depth can be set to\nzero via the statement\n\\begin{verbatim}\ndom.fixSusceptibilityBelow(depth=40.*U.km)\n\\end{verbatim}\nwhere here the susceptibility below $40km$ is prescribed (this has no effect as\nthe depth of the domain is $40km$)\\footnote{Notice that the method called is\ndifferent from the one in the case of gravity inversion.}. \n\nMagnetic data are read and added to the domain with the following statements:\n\\begin{verbatim}\nsource0=NetCdfData(NetCdfData.MAGNETIC, 'MagneticSmall.nc', \\\n                   scale_factor=U.Nano * U.Tesla)\ndom.addSource(source0)\n\\end{verbatim}\nThe first argument \\member{NetCdfData.MAGNETIC} identifies the data read from\nfile \\file{MagneticSmall.nc} (second argument) as magnetic data.The argument\n\\file{scale_factor} specifies the units (here $nT$) of the magnetic flux\ndensity data in the file.\nIf scalar data are given it is assumed that the magnetic flux density anomalies\nare measured in direction of the background magnetic flux density\\footnote{The\ndefault for \\file{scale_factor} for magnetic data is $nT$.}.\n\nFinally the inversion is created and run:\n\\begin{verbatim}\ninv=MagneticInversion()\ninv.fixMagneticPotentialAtBottom(False)\nk = inv.run()\n\\end{verbatim}\nThe result for the susceptibility is named \\member{k}. In this case the magnetic potential is\nnot fixed at the bottom of the domain. The magnetic potential is still set zero at the top of the domain.\n\nWe then write the result\nto a \\VTK file using\n\\begin{verbatim}\nsaveVTK(\"result.vtu\", susceptibility=k)\n\\end{verbatim}\nwhere the result of the inversion is tagged with the name \\member{susceptibility}\nas an identifier for the visualization software. \n\n\\begin{figure}\n    \\begin{center}\n        \\subfigure[$\\mu=0.001$]{%\n            \\label{FIG:P1:MAG:10 MU0001}\n            \\scalebox{0.95}{\\includegraphics[width=0.45\\textwidth]{QLDMagContourMu0001.png}}\n        }%\n        \\subfigure[$\\mu=0.01$]{%\n            \\label{FIG:P1:MAG:10 MU001}\n            \\scalebox{0.95}{\\includegraphics[width=0.45\\textwidth]{QLDMagContourMu001.png}}\n        }\\\\ %  ------- End of the first row ----------------------%\n        \\subfigure[$\\mu=0.1$]{%\n            \\label{FIG:P1:MAG:10 MU01}\n            \\scalebox{0.95}{\\includegraphics[width=0.45\\textwidth]{QLDMagContourMu01.png}}\n        }%\n        \\subfigure[$\\mu=1.$]{%\n            \\label{FIG:P1:MAG:10 MU1}\n            \\scalebox{0.95}{\\includegraphics[width=0.45\\textwidth]{QLDMagContourMu1.png}}\n        }\\\\ %  ------- End of the second row ----------------------%\n        \\subfigure[$\\mu=10.$]{%\n            \\label{FIG:P1:MAG:10 MU10}\n            \\scalebox{0.95}{\\includegraphics[width=0.45\\textwidth]{QLDMagContourMu10.png}}\n        }%\n    \\end{center}\n    \\caption{3-D contour plots of magnetic inversion results with data from\n    Figure~\\ref{FIG:P1:MAG:0} for various values of the model trade-off\n    factor $\\mu$. Visualization has been performed in \\VisIt.}\n    \\label{FIG:P1:MAG:10}\n\\end{figure}\n\n\\begin{figure}\n    \\begin{center}\n        \\subfigure[$\\mu=0.001$]{%\n            \\label{FIG:P1:MAG:11 MU0001}\n            \\scalebox{0.95}{\\includegraphics[width=0.45\\textwidth]{QLDMagDepthMu0001.png}}\n        }%\n        \\subfigure[$\\mu=0.01$]{%\n            \\label{FIG:P1:MAG:11 MU001}\n            \\scalebox{0.95}{\\includegraphics[width=0.45\\textwidth]{QLDMagDepthMu001.png}}\n        }\\\\ %  ------- End of the first row ----------------------%\n        \\subfigure[$\\mu=0.1$]{%\n            \\label{FIG:P1:MAG:11 MU01}\n            \\scalebox{0.95}{\\includegraphics[width=0.45\\textwidth]{QLDMagDepthMu01.png}}\n        }%\n        \\subfigure[$\\mu=1.$]{%\n            \\label{FIG:P1:MAG:11 MU1}\n            \\scalebox{0.95}{\\includegraphics[width=0.45\\textwidth]{QLDMagDepthMu1.png}}\n        }\\\\ %  ------- End of the second row ----------------------%\n        \\subfigure[$\\mu=10.$]{%\n            \\label{FIG:P1:MAG:11 MU10}\n            \\scalebox{0.95}{\\includegraphics[width=0.45\\textwidth]{QLDMagDepthMu10.png}}\n        }%\n    \\end{center}\n    \\caption{3-D slice plots of magnetic inversion results with data from\n    Figure~\\ref{FIG:P1:MAG:0} for various values of the model trade-off\n    factor $\\mu$. Visualization has been performed \\VisIt.}\n    \\label{FIG:P1:MAG:11}\n\\end{figure}\n\nFigures~\\ref{FIG:P1:MAG:10} and~\\ref{FIG:P1:MAG:11} show results from the\ninversion of the magnetic data shown in Figure~\\ref{FIG:P1:MAG:0}.\nIn Figure~\\ref{FIG:P1:MAG:10} surface contours are used to represent the\nsusceptibility while Figure~\\ref{FIG:P1:MAG:11} uses contour lines\non a lateral plane intercept and two vertical plane intercepts.\nThe images show the strong impact of the trade-off factor $\\mu$ on the result.\nLarger values give more emphasis to the misfit term in the cost function\nleading to rougher susceptibility distributions.\nThe result for $\\mu=0.1$ seems to be the most realistic.\n\n", "meta": {"hexsha": "a0484119af422a75b1e7df8bdaae036fced7b5a2", "size": 8781, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/inversion/CookMagnetic.tex", "max_stars_repo_name": "markendr/esys-escript.github.io", "max_stars_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/inversion/CookMagnetic.tex", "max_issues_repo_name": "markendr/esys-escript.github.io", "max_issues_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-01-14T03:07:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-14T03:07:43.000Z", "max_forks_repo_path": "doc/inversion/CookMagnetic.tex", "max_forks_repo_name": "markendr/esys-escript.github.io", "max_forks_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.6262135922, "max_line_length": 105, "alphanum_fraction": 0.7175720305, "num_tokens": 2502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804478040617, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.32870197393392786}}
{"text": "\\section{Why PID is so generally applicable}\n\\subsection{}\n\n\\begin{frame}\n\\frametitleTC{The second-order process case}\n\\framesubtitleTC{aka ``one size fits many''}\n\\myPause\n \\begin{itemize}[<+-| alert@+>]\n \\item We consider an asymptotically  process with two poles and one zero at most, i.e.,\n       \\begin{displaymath}\n        P(z) = \\mu \\frac{z-z_1}{(z-p_1)(z-p_2)}, \\qquad |p_{1,2}|<1.\n       \\end{displaymath}\n \\item We want to show that this gives rise to the four possible cases\n       \\begin{displaymath}\n        \\begin{array}{rcll}\n         P_1(z) &=& \\frac{\\mu}{z-p_1},                                               \\\\\n         P_2(z) &=& \\frac{\\mu}{(z-p_1)(z-p_2)},                                      \\\\\n         P_3(z) &=& \\frac{\\mu(z-z_1)}{(z-p_1)(z-p_2)}, & |z_1|<1,                    \\\\\n         P_4(z) &=& \\frac{\\mu(z-z_1)}{(z-p_1)(z-p_2)}, & |z_1|>1 \\text{ or } z_1=-1, \\\\\n        \\end{array}\n       \\end{displaymath}\n       and that each of these is very naturally paired to a PI(D) controller.\n \\item But: why not a case with one pole and one zero? Why not $z_1=1$?\n \\item We need another short \\emph{intermezzo}...\n \\end{itemize}\n\\end{frame}\n\n\\begin{frame}\n\\frametitleTC{Why not $z_1=1$}\n\\framesubtitleTC{}\n\\myPause\n \\begin{itemize}[<+-| alert@+>]\n \\item We start from the simple. If $z_1=1$ the process output $y$ tends asymptotically to zero\n       for any constant input $u$, as it comes to depend on $u(k)-u(k-1)$.\n \\item This means that to keep $y$ at a certain constant reference value, $u$ should indefinitely\n       increase at a corresponding constant \\TC{rate}, up to infinity---or overflow.\n       Apparently, such a process cannot be managed (control people use to say ``you cannot prescribe\n       the steady state'').\n \\item If conversely $z_1=-1$ one can prescribe the steady state, but not cancel the zero with a\n       pole of $C$, or the cancellation would be critical, as we already know.\n \\item We thus consider $z_1=-1$ and $|z_1|>1$ the same case, and we know\\\\\n       what the outcome will be.\n \\item More interesting is to discuss why we assume $P$ to be always strictly\\\\\n       proper (more poles than zeroes). \n \\end{itemize}\n\\end{frame}\n\n\\begin{frame}\n\\frametitleTC{A controller's execution timeline}\n\\framesubtitleTC{Some considerations}\n\\myPause\n \\begin{itemize}[<+-| alert@+>]\n \\item Let us first point a further peculiarity of control in computers.\n       \\begin{itemize}[<+-| alert@+>]\n       \\item When the controlled object is outside the computer, it always evolves in \\TC{physical}\n             parallel with the controller's execution; when it is inside, that parallel might be physical\n             or just emulated, if the two entities share a CPU. Said otherwise, \\TC{running the controller\n             can halt the process}.\n       \\item More in general, in non-computer applications, running controllers adds value to the process\n             by improving its operation. In computers, on the contrary, time to compute the control signals\n             is \\TC{anyway stolen} from that devoted to applications. And since value ultimately comes from\n             running applications, time for running controllers must be almost negligible.\n       \\end{itemize}\n \\item For the sake of completeness, the second statement may not hold\\\\\n       if the control payback is really huge, or if controllers have dedicated\\\\\n       hardware to run; we leave discussing such cases to advanced\\\\\n       activities, however.\n \\end{itemize}\n\\end{frame}\n\n\\begin{frame}\n\\frametitleTC{A controller's execution timeline}\n\\framesubtitleTC{Some considerations}\n\\myPause\n \\begin{itemize}[<+-| alert@+>]\n \\item In general -- i.e., considering also cases we do not address in our activity -- one can distinguish\n       three cases (thinking for simplicity of a sampled signals context):\n       \\begin{itemize}[<+-| alert@+>]\n       \\item the time $\\tau(k)$ to compute the generic $u(k)$ is negligible wrt the sampling period $T_s$;\n       \\item $\\tau(k)$ is not negligible wrt $T_s$ but it is -- almost -- invariant (no branches, no operations\n             with operand-dependent duration, no or negligible cache effects, and so on---or countermeasures taken\n             in the code for such issues);\n       \\item $\\tau(k)$ is not negligible wrt $T_s$ and can vary significantly over the control steps.\n       \\end{itemize}\n \\item We do not have the time to investigate the matter (but those who want to deal\\\\\n       safely with high-performance real-time control \\TC{should} study it very\\\\\n       carefully in control technology courses).\n \\item In fact a PI(D) algorithm can be made very lightweight (down to a\\\\\n       few tens of clock cycles, to give a figure) so that we are practically\\\\\n       always in the first case.\n \\end{itemize}\n\\end{frame}\n\n\\begin{frame}\n\\frametitleTC{A controller's execution timeline}\n\\framesubtitleTC{Some considerations}\n\\myPause\n \\begin{itemize}[<+-| alert@+>]\n \\item The timeline is therefore as follows:\n       \\begin{center}\n        \\vspace{1mm}\\includegraphics[width=0.70\\columnwidth]{./Unit-07/img/CtrlTimeline.pdf}\n       \\end{center}\n \\item As can be seen, the effect of $u(k)$ can be seen only at step $k+1$,\\\\\n       hence the process is correctly viewed as a strictly proper model.\n \\item Incidentally, being in the first case is essential to make the P action\\\\\n       possible.\n \\item ...end of the \\emph{intermezzo}.\n \\end{itemize}\n\\end{frame}\n\n\\begin{frame}\n\\frametitleTC{Back to the second-order process}\n\\framesubtitleTC{for a reasoned recap and a systematisation}\n\\myPause\n \\begin{itemize}[<+-| alert@+>]\n \\item Exercise: take the four cases\n       \\begin{displaymath}\n        \\begin{array}{rcll}\n         P_1(z) &=& \\frac{\\mu}{z-p_1},                                               \\\\\n         P_2(z) &=& \\frac{\\mu}{(z-p_1)(z-p_2)},                                      \\\\\n         P_3(z) &=& \\frac{\\mu(z-z_1)}{(z-p_1)(z-p_2)}, & |z_1|<1,                    \\\\\n         P_4(z) &=& \\frac{\\mu(z-z_1)}{(z-p_1)(z-p_2)}, & |z_1|>1 \\text{ or } z_1=-1. \\\\\n        \\end{array}\n       \\end{displaymath}\n \\item For each of them select a controller structure, devise a way to provide\\\\\n       a response speed specification, and formalise a tuning procedure;\\\\\n       then build a Modelica LTI scheme to simulate the so obtained\\\\\n       loops, design and carry out experiments, and comment.\n \\end{itemize}\n\\end{frame}\n\n", "meta": {"hexsha": "60ee69b2c9e49a89f27a07ae0aeede2d957a0d31", "size": 6407, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "slides/Unit-07/sections/02-PIDgenerality.tex", "max_stars_repo_name": "albertoleva/PID4CSE", "max_stars_repo_head_hexsha": "66ec14c204e16c97a5792c2e240b2daed4b39e83", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-19T16:38:10.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-19T16:38:10.000Z", "max_issues_repo_path": "slides/Unit-07/sections/02-PIDgenerality.tex", "max_issues_repo_name": "albertoleva/PID4CSE", "max_issues_repo_head_hexsha": "66ec14c204e16c97a5792c2e240b2daed4b39e83", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slides/Unit-07/sections/02-PIDgenerality.tex", "max_forks_repo_name": "albertoleva/PID4CSE", "max_forks_repo_head_hexsha": "66ec14c204e16c97a5792c2e240b2daed4b39e83", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.5378787879, "max_line_length": 114, "alphanum_fraction": 0.6475729671, "num_tokens": 1758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.32870197393392786}}
{"text": "\\section{Discussion} \\label{sec:discuss}\n\\subsection{Impact of Model Priors}\nThe most significant limitation of the {\\sc PROVABGS} SED modeling in\ninferring the true galaxy properties is the prior on galaxy properties imposed\nby the model. \nThe effect of such priors is  a major limitation for any SED modeling\nmethods~\\citep[\\emph{e.g.}][]{carnall2017, leja2019} and is a consequence of\nthe fact that galaxy properties are \\emph{not} parameters of the SPS model.\nFor instance, $\\avgsfr$, $\\zmw$, and $\\tage$ are derived by integrating the SFH\nand ZH (Eq.~\\ref{eq:prop_eqs}), which are parameterized by $\\beta_1, \\beta_2,\n\\beta_3, \\beta_4$ and $\\gamma_1, \\gamma_2$. \nUniform priors on $\\beta$s and $\\gamma$s (Section~\\ref{sec:infer} and\nTable~\\ref{tab:params}) do not translate into uniform priors on $\\avgsfr$,\n$\\zmw$ and $\\tage$.\nOther galaxy properties (\\emph{e.g.}~SFH, and ZH) likewise have\nnon-uniform, and undesireable, priors. \n\nOne way to address this issue is to choose an SED model parameterization that\ndoes not impose extreme priors on galaxy properties and to characterize the\npriors in detail so that final posteriors can be appropriately interpreted. \nFor the {\\sc PROVABGS} model, we explicitly chose our SFH prescription so that\nthe prior on $\\log\\avgssfr$ extends the range $-12$ to $-9$ dex.\nFurthermore, we fully characterize the prior on $\\avgssfr$, $\\zmw$, $\\tage$,\nSFH, and ZH in Appendix~\\ref{sec:model_priors} (Figures~\\ref{fig:model_prior}\nand~\\ref{fig:sfh_prior}). \nThis way, we understand exactly how the model prior impacts the derived\nposteriors as we discuss in detail in Section~\\ref{sec:results}. \nBeyond mitigating the effect of the priors, we can impose uniform prior (or any\nother desired prior distribution) on the derived galaxy properties by adjusting\nthe priors on the SED model parameters. \n\\cite{handley2019} recently demonstrated that maximum-entropy priors can be\nused for this purpose to impose uniform priors on the inferred sum of neutrino\nmasses in cosmological analyses. \nIn an upcoming paper, Hahn (in prep.), I will demonstrate that maximum-entropy\npriors can also be used in Bayesian SED modeling to correct for the impact of\npriors on infer posteriors on derived galaxy properties. \n\n%With this prior correction, we will be able to infer even more accurate posteriors on the physical properties of galaxies with our {\\sc PROVABGS} SED modeling.\n\n%However, we can go beyond minimizing the impact of the priors and use maximum-entropy.  With an estimate of the prior distribution, we can impose maximum-entropy priors in a specified distribution~\\citep{handley2019}.  From an estimate of the prior distribution on the galaxy properties, we can derive a new prior on the SPS model parameters that would impose uniform priors on the galaxy properties. \n\n\\subsection{Aperture Effects}\nIn this work, we use forward modeled mock observations to demonstrate that we\ncan infer accurate and precise posteriors on certain galaxy properties.\nThe mock observations are constructed from \\lgal~and include photometry and\nspectra. \nIn generating the mock spectra, we model the fiber aperture effect ---\n\\emph{i.e.} spectra only include light from a galaxy collected within its fiber\ndiameter --- by scaling the SED flux (Section~\\ref{sec:spec}).\nIn our SED modeling, we account for this fiber aperture effect using a\nnormalization factor, $f_{\\rm fiber}$ (Section~\\ref{sec:sps}). \nHence, our mock observations and SED modeling have a consistent treatment of\nthe fiber aperture effect. \nIn observations, however, aperture effects can be wavelength\ndependent~\\citep{gerssen2012, richards2016} and if the dependence is strong,\nan overall $f_{\\rm fiber}$ factor would not be sufficient.\nIn order to examine the wavelength dependence, we compare the ratio of the\nfiber aperture flux over total flux, $f^{\\rm fiber}_X/f_X$, in $g$, $r$, and\n$z$ bands of BGS targets from LS.\nWe find find no significant difference in the flux ratios of the different\nbands, which suggests that the fiber aperture effect in DESI does not have a\nstrong wavelength dependence. \n\nFlux calibration performed on DESI spectra can also induce wavelength dependent\nresiduals. \nDESI spectra are measured using three-arm spectrographs that split the spectra\ninto three $b$, $r$, and $z$ channels with overlapping wavelength ranges: \n$3600 - 5930$, $5660 - 7720$, and $7470 - 9800 \\AA$.  \nAfter flat fielding and sky subtraction, flux calibration is performed on each\nchannel of the spectra by matching physical stellar models to spectra of\nspectrohotometric standard stars observed in the same exposure\n(Guy~\\etal~in prep.). \nSince the calibration is performed for each channel seaparately, imperfections\ncan imprint a wavelength dependent residual. \nIn a subsequent paper, Ramos \\etal~(in prep.), we examine the fiber aperture\neffect and wavelength dependent imprints on DESI spectra using BGS\nspectra from the DESI Survey Validation data and observations from the Mapping\nNearby Galaxies at APO (MaNGA) survey. \nUsing galaxy properties derived using the {\\sc PROVABGS} pipeline for spectra\nfrom integrated field unit MaNGA observations, we will present aperture\ncorrections that can be applied on derived BGS galaxy properties. \nWe also note that the {\\sc PROVABGS} SED modeling pipeline already includes flux\ncalibration models beyond a single $f_{\\rm fiber}$ and can easily be extended\nto include more sophisticated models~\\citep[\\emph{e.g.} Chebyschev\npolynomial;][]{carnall2017, tacchella2021}. \n\n%\\todo{paragraph on how we handle theoretical assumptions --- isochrones and stellar libraries, summary of the appendix}\n\\subsection{Stellar Model Choices}\nIn both our {\\sc PROVABGS} SED model and mock observations, we use the MIST\nisochrones, \n\\edits{\n    the combined MILES+BaSeL spectral library,\n}\nand the \\cite{chabrier2003} IMF.\nWith the same set of choices, our analysis does not consider how different\nchoices for stellar evolution or IMF can affect the inferred galaxy properties. \nYet, it is well-established that there are major uncertainties in each of these\nchoices~\\citep{conroy2009, conroy2013}.\nFor instance, recent observational works suggest that there may be significant\nvariations in IMF~\\citep[\\emph{e.g.}][]{treu2010, vandokkum2010, rosani2018,\nsonnenfeld2019}. \nDifferent SPS model choices can also significantly impact the derived galaxy\npropeties~\\citep[\\emph{e.g.}][]{ge2019}.\nWe reserve a detailed examination of this effect for future work. \nIn the meantime, for the {\\sc PROVABGS} catalog we will release multiple\ncatalogs each with different sets of choices for isochrone, spectral library,\nand IMF.\n\n\\subsection{Advantages of PROVABGS}\nWe demonstrate with the mock challenge that we can derive accurate and precise\nconstraints on specific galaxy properties using the {\\sc PROVABGS} SED modeling.\nThe {\\sc PROVABGS} catalog will have a number of key advantages over other\nvalue-added galaxy catalogs. \nFirst, {\\sc PROVABGS} will provide full Bayesian posteriors on galaxy\nproperties instead of ``best-fit'' point estimates from maximizing the\nlikelihood. \nPosterior distributions are essential for accurately estimating uncertainties\non galaxy properties.  \nAs we find earlier, these uncertainties are significant, especially for\nproperties such as $\\zmw$ (Figure~\\ref{fig:prop_inf}). \nIgnoring the uncertainties dramatically overestimates the statistical precision\nof the derived galaxy properties and can significantly bias any galaxy study.\n%We also note that the maximum-entropy method, mentioned earlier, to correct for the effect of priors on derived galaxy properties requires full posterior distributions.\n\nFurthermore, the {\\sc PROVABGS} posteriors will be derived from MCMC sampling\nrather than grid-based methods often used in the\npast~\\citep[\\emph{e.g.}][]{dacunha2008, moustakas2013, boquien2019}.\nAs a result, they can accurately estimate posterior distributions with\nsignificant parameter degeneracies or multiple modes (peaks). \nFor instance, in the posterior of Figure~\\ref{fig:posterior} we find\ndegeneracies between $f_{\\rm burst}$ and $\\{\\beta_1, \\beta_2, \\beta_3,\n\\beta_4\\}$ and between $\\{\\gamma_1, \\gamma_2\\}$ and $\\{\\beta_1, \\beta_2,\n\\beta_3, \\beta_4\\}$. \nThe posterior is also multi-modal. \nAccurate estimates of the full posterior distribution are especially important,\nas they enable the maximum-entropy method, mentioned earlier, \nto correct for the significant impact of priors on derived galaxy properties.\nGrid-based methods also scale exponentially with the number of SPS parameters\nso they quickly become infeasible as the dimensionality of SPS models increase. \nMCMC, on the other hand, scales approximately linearly with the number of\nparameters. \n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=0.7\\textwidth]{figs/sfh_demo.pdf}\n    \\caption{\n        With the {\\sc PROVABGS} SPS model, we can infer posteriors on the full\n        star formation and metallicity histories. \n        We present the inferred SFH and ZH for an arbitrarily chosen\n        star-forming (blue) and quiescent galaxy (orange).\n        The shaded region represent the 64 and 95\\% confidence intervals of the\n        SFH and ZH posteriors. \n        For comparison, we include the true SFH and ZH (dashed). \n        The inferred SFH and ZH show good agreement with the true values;\n        however, similar to the inferred $\\avgsfr$ and $\\zmw$, the SFH and ZH\n        are significantly impacted by priors imposed by the SPS model. \n    } \\label{fig:sfh_demo}\n\\end{center}\n\\end{figure}\n%\\todo{Beyond the galaxy properties we discuss in Section~\\ref{sec:results}, we can also derive SFH and ZH}\n\nIn this work, we primarily focus on the following physical properties of\ngalaxies: $\\log M_*$, $\\log\\avgsfr$, $\\log\\zmw$, $\\tage$, and $\\tauism$. \nThe {\\sc PROVABGS} SPS model, however, can constrain galaxy properties beyond\nthese properties. \nThe SPS model employs nonparametric SFH and ZH prescriptions based on NMF bases\nand the model parameters include coefficients for these bases. \nPosteriors on the SPS model parameters can, thus, be used to derive constraints\non the SFH and ZH. \nIn Figure~\\ref{fig:sfh_demo}, we present the inferred SFH and ZH of two\nsimulated galaxies from our \\lgal~sample: a star-forming (blue) and a quiescent\ngalaxy (orange). \nWe mark the 68 and 95\\% confidence intervals in the shaded regions. \nFor comparison, we include the true SFH and ZH from \\lgal~(dashed).  \nThe inferred SFH and ZH is able to generally recover the true histories. \nWe emphasize that current SPS models typically assume constant ZHs that does\nnot vary over time~\\citep{carnall2017, leja2019}. \nHence inferring ZH over time is a key advantage of the {\\sc PROVABGS} SPS\nmodel. \nSimilar to the inferred $\\avgsfr$ and $\\zmw$, the SFH and ZH constraints are\nalso impacted by the priors imposed by our SPS model\n(Appendix~\\ref{sec:model_priors}, Figure~\\ref{fig:sfh_prior}).\n\nAnother key advantage of {\\sc PROVABGS} is that it will infer galaxy\nproperties from joint SED modeling of photometry \\emph{and spectra}. \nOur results illustrate the advantages of including spectra in SED modeling. \nGalaxy spectra provide substantial statistical power for constraining \ngalaxy properties. \nIn addition to tightening constraints overall, their statistical power is\nessential for mitigating the effect of the model priors. \nFor instance, including spectra in the SED modeling significantly reduces the\nbias of our $\\zmw$ and $\\tage$ constraints (Figure~\\ref{fig:etas}). \nIt also reduces the lower bound on the inferred $\\avgsfr$. \nIn fact, without spectra, we are dominated by priors on $\\avgsfr$ and cannot\nrobustly infer galaxy properties of quiescent galaxies with $\\log\\avgsfr < 0$\ndex.\n%We emphasize that all of these benefits come from spectra with the SNR of BGS, which is observing during bright time. \n\n\\subsection{Applications of PROVABGS}\n{\\sc PROVABGS} will be a value-added galaxy catalog with unprecedented\nstatistical power. \nWith physical galaxy properties of over $10$ million DESI BGS galaxies, \n{\\sc PROVABGS} will provide a transformational galaxy sample to extend\nprevious statistical galaxy studies. \nFor example, we will be able to make the most precise measurement of the\nstellar mass function~\\citep[SMF]{li2009, moustakas2013}, star-forming\nsequence~\\citep{noeske2007}, mass-metallicity relation~\\citep{tremonti2004}, or\nany other summary statistic of galaxy populations. \n{\\sc PROVABGS} will also include large sample of dwarf galaxies thanks to the\nfaint apparent magnitude limit of BGS. \nDwarf galaxies are dark matter dominated and, thus, probe the physics of\ndark matter; they are also sensitive to star formation feedback and can help\ndistinguish different aspects of galaxy formation~\\citep{mao2021}. \nGalaxy studies examining the galaxy-halo connection can also be extended to\nexploit the additional statistical power of {\\sc\nPROVABGS}~\\citep[\\emph{e.g.}][]{tinker2011, wetzel2013, zu2015, hahn2017,\nhahn2019b}. \nWith detailed galaxy properties, {\\sc PROVABGS} will also enable\nmultiple-tracer galaxy clustering analyses that can circumvent cosmic variance\nin inferring cosmological parameters~\\citep{seljak2009, mcdonald2009,\nwang2020}.\nAnalyses exploiting new forward modeling approaches, such as \\cite{hahn2021},\nwill also greatly benefit from the statistical power of {\\sc PROVABGS}.\n%\\ch{Text above will be updated with more science applications based on any feedback.}\n\nIn addition to the applications above, {\\sc PROVABGS} will also unlock\napplications that can exploit the full posteriors of the probabilistic catalog.\nIn this work, we utilized the posteriors in order to quantify accuracy and\nprecision of galaxy population constraints using population inference with a\nhierarchical Bayesian approach. \nThis is only the \\emph{simplest} illustration of such an approach. \n\\edits{\n    Another application is to use posteriors on $M_*$, \n    $p(M_* \\given {\\bfi X}_i)$, to measure $p(M_* \\given \\{ {\\bfi X_i} \\})$ ---\n    the \\emph{probabilistic} SMF.\n    With full posteriors, we can probe even the lowest signal-to-noise regime\n    accurately so the SMF will be reliable even at the lowest mass end, down to\n    ${\\sim}10^{7} M_\\odot$ (Figure~\\ref{fig:bgs_mstar}). \n    This will constrain the SMF of dwarf galaxies and have important\n    implications for both galaxy evolution and cosmology. \n}\n\n%With the {\\sc PROVABGS} posteriors we can infer fully probabilistic galaxy\n%population statistics, which will allow us to robustly probe even the lowest\n%signal-to-noise regime.\n%A probabilistic SMF of BGS, for example, will provide accurate constraints on\n%the low mass end down to ${\\sim}10^{7} M_\\odot$ (Figure~\\ref{fig:bgs_mstar}),\n%which has important implications for both galaxy evolution and cosmology. \n\\edits{\n    Probabilistic analyses can extend to higher dimensions. \n    Joint posteriors on $M_*$ and SFR, $p(M_*, {\\rm SFR} \\given {\\bfi X}_i)$\n    can be used to measure the probabilistic star formation sequence. \n    Since the posteriors reliably estimate the uncertainties and parameter\n    degeneracies, we will more accurately infer the intrinsic width of the\n    SFS, which encodes information about star formation and stellar and AGN\n    feedback in galaxies~\\citep{davies2021}. \n    We can even extend the approach to infer the distribution of \\emph{all}\n    galaxy properties given observations, $p(\\theta | \\{X_i\\})$, which would\n    exploit the \\emph{full} statistical power of observations and reveal new\n    trends among galaxy properties. \n    This is only possible with population inference using the posterior\n    distributions of every galaxy.\n}\n\n%We can also use population inference to robustly derive galaxy property distributions of galaxy subpopulations --- \\emph{without stacking observations}.\nPopulation inference also allows us to avoid stacking observations. \nStacking makes the strong assumption that galaxies that are grouped together in\nsome \\emph{e.g.} color-space are from a subpopulation with the same properties. \nThis assumption fails if, for instance, there are contaminants or multiple\ndisparate galaxy subpopulations that are degenerate in color-space and\ntherefore are included in the stack. \nWith all of the applications listed above, {\\sc PROVABGS} will enable us to\nfully extract the statistical power of >10 million BGS galaxies.\n", "meta": {"hexsha": "e9b9f0f4b06777798189c6c1b938a5f2b9fb5ead", "size": 16361, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/paper/discuss.tex", "max_stars_repo_name": "changhoonhahn/gqp_mc", "max_stars_repo_head_hexsha": "abdfadac2e7d7e12c1642743e2b3c6a6a6fe370b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-12-18T20:51:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T05:59:24.000Z", "max_issues_repo_path": "doc/paper/discuss.tex", "max_issues_repo_name": "changhoonhahn/gqp_mc", "max_issues_repo_head_hexsha": "abdfadac2e7d7e12c1642743e2b3c6a6a6fe370b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44, "max_issues_repo_issues_event_min_datetime": "2020-02-20T06:02:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-13T20:00:50.000Z", "max_forks_repo_path": "doc/paper/discuss.tex", "max_forks_repo_name": "changhoonhahn/gqp_mc", "max_forks_repo_head_hexsha": "abdfadac2e7d7e12c1642743e2b3c6a6a6fe370b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-10-04T22:25:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:05:03.000Z", "avg_line_length": 59.7116788321, "max_line_length": 402, "alphanum_fraction": 0.7824705091, "num_tokens": 4087, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3287019664650117}}
{"text": "% !TeX root = article.tex\n\\section{Description of plasticity in the framework of physics engines}\n\nIn this section, key concepts related to the introduced model are explained. The main differences between \ntraditional structural analysis and physics engines based approaches are reviewed and discussed.\n\nVelocity-based formulation of constraint based rigid body simulation \nis  commonly used by physics based game\ndevelopers and film production teams.\n%\\citet[p.~45]{erleben.thesis} \n\\cite{erleben.thesis} \nprovides reasoning and theoretical details for the popularity of \nvelocity-based formulation in constraint-based rigid body simulation instead of accelaration based. \nThe main reason is that collision handling can be done without the use of additional procedures.\n\nWork presented by  \n\\cite{erleben.thesis} provides the basis for the velocity-based formulation discussed in this work.\n%\\citet[p.~45-50]{erleben.thesis}.\n% pdf page 64\nIn the following section, these formulations will be clarified by a simple example using \\cbullet\\ implementation.\n\nImpulse $\\vec{J}$\nin the time interval $\\Delta t $ can be written as:\n\\begin{equation} \\label{eq:impulseIntegral}\n\\vec{J} = \\int_{0}^{\\Delta t} \\vec{f}_{true}(t) dt,\n\\end{equation}\nwhere $\\vec{f}_{true}(t)$ is force.\n\nUsing Newton's second law of motion $\\vec{F}=m\\vec{a}$ ,\n$\\vec{v}^{\\Delta t}$ can be solved for the velocity as:\n\\begin{equation} \\label{eq:impulseIntegraWithNewton}\n\\int_{0}^{\\Delta t} m \\frac{d\\vec{v}}{dt}dt= \\int_{0}^{\\Delta t} \\vec{f}_{true}(t)\n\\end{equation}\n\\begin{equation} \\label{eq:impulse}\nm(\\vec{v}^{\\, \\Delta t} - \\vec{v}^{\\, 0})=\\vec{J},\n\\end{equation}\nwhere superscripts denote time, i.e. ${\\vec{v}}^{\\Delta t}=\\vec{v}(\\Delta t)$.\nNext position can be found\nby integrating the velocity.\nUpdates after each step can be summarized  for locations and  \nfor velocities respectively as follows:\n\n\\begin{equation} \\label{eq:eomL} % pdf page 69\n\\vec{s}^{\\, t+\\Delta t} = \\vec{s}^{\\, t}+\\Delta t S \\vec{u}^{\\, t+\\Delta t}\n\\end{equation}\n\n\\begin{equation} \\label{eq:eomV}\n\\vec{u}^{\\, t+\\Delta t} = \\vec{u}^{\\, t}+\\Delta t M^{-1}(C N \\vec{f}^{\\ t+\\Delta t} + \\vec{f}_{ext}) .\n\\end{equation}\n\nThe symbols used in Equations \\ref{eq:eomL} and \\ref{eq:eomV}\nare summarized in Table \\ref{tab:eom}.\nFigure \\ref{fig:eom-contact} describes the collision of two\nbodies, rectangular body $B_1$ and triangular body $B_2$\nwhere $\\vec{r}_i$ is position of body $i$,\n$\\vec{p}_k $ is position of contact point $k$,\n$\\vec{r}_{ik} $ is a vector between the center of gravity of body $i$ and contact point $k$, \nand\n$\\vec{n}_{k}$ is the contact normal for contact point $k$.\nIt is common convention that the contact normal points\nfrom the body with the smallest index to the body with the largest index, \\cite{erleben.thesis}.\nIn case of point or edge contacts, averaging the normals of neighboring polygons can be used, \\cite{Hahn:1998}.\n\n\\begin{figure}[tb!]\n\\centering\n\\begin{tikzpicture}\n\\coordinate (O1) at(2,1);\n\\coordinate (O2) at(2,4);\n\\coordinate (C) at(2,2);\n\\draw (0,0) -- (4,0) -- (4,2) -- (0,2) --(0,0);\n\\draw (2,2) -- (3.5,5) -- (0.5,5) -- (2,2) ;\n\\node at (3.5,0.4) {$B_1$};\n\\filldraw (O1) circle (0.5mm) node[anchor=north] {$\\vec{r}_1$};\n\\node at (2.8,4.5) {$B_2$};\n\\filldraw (O2) circle (0.5mm) node[anchor=south] {$\\vec{r}_2$};\n\\filldraw (C) circle (0.5mm) node[anchor=north west] {$\\vec{p}_1$};\n\\draw[-{Stealth[length=3mm]}] (O1) -- (C) node[anchor=north east] {$\\vec{r}_{11}$};\n\\draw[-{Stealth[length=3mm]}] (O2) -- (C) node[anchor=south east] {$\\vec{r}_{21}$};\n\\draw[-latex,thick] (C) -- ++(0,1.4) node[anchor=west] {$\\vec{n}_{1}$};\n\\node[anchor=west] at (4.5,4.5) {\n$\\vec{r}_i$  =  position of body $i$\n};\n\\node[anchor=west] at (4.5,4) {$\\vec{p}_k $ = position of contact point $k$};\n\\node[anchor=west] at (4.5,3.5) {$\\vec{r}_{ik} $ = $\\vec{p}_k - \\vec{r}_i $};\n\\node[anchor=west] at (4.5,3) {$\\vec{n}_{k} $ = normal for contact point $k$};\n\\end{tikzpicture}\n\\caption{Illustration of nomenclature for equations of motion for collision.}\n\\label{fig:eom-contact}\n\\end{figure}\n\n% pdf page 33, notation in typical ODEs\n\\begin{table}\n\\tbl{Nomenclature for equations of motion}{\n\\begin{tabular}{|l| l|}\n\\hline\n{\\bf Symbol} & {\\bf Description} \\\\  \\hline\n$\\vec{r}_i$ & position of center of mass for body $i$  \\\\ \\hline\n$\\vec{q}_i$ & orientation for body $i$ as quaternion $\\lbrack s_i, x_i, y_i, z_i \\rbrack ^T $ \\\\\n\\hline\n$\\vec{p}_h$ & contact or joint point $k$  \\\\ \\hline\n$\\vec{r}_{ki}$ & $\\vec{p}_k - \\vec{r}_i$  \\\\ \\hline\n$\\vec{s}$ & $\\lbrack \\vec{r}_1, \\vec{q}_1,...,\\vec{r}_n, \\vec{q}_n \\rbrack ^T $\\\\ \\hline\n$Q_i$ & \\begin{tabular}{@{}c}\nrotation of quaternion $\\vec{q}_i$\nas matrix \\\\ where \n$\\frac{1}{2}\\vec{\\omega}_i \\vec{q}_i=Q_i \\vec{\\omega}_i$\n\\end{tabular}\n   $\n\\frac{1}{2} \\left[ \\begin{array}{ccc}\n-x_i & -y_i & -z_i \\\\\ns_i & z_i & -y_i \\\\\n-z_i & s_i & x_i \\\\\ny_i & -x_i & s_i\n\\end{array} \\right]\n$\n\\\\ \\hline\n$S$ & \n\\begin{tabular}{@{}c}\ngeneralized transformation matrix \\\\\n$ S \\in \\mathbb{R}^{7n \\times 6n}$\n\\end{tabular}\n $ \\left[ \\begin{array}{ccccc}\n1 &  &  & & 0 \\\\\n & Q_i  \\\\\n & & \\ddots  \\\\\n & & & 1 \\\\\n0 & & & & Q_n \n\\end{array} \\right]\n$\n\\\\ \\hline\n$\\vec{v}_i$ & linear velocity of  center of mass for body $i$   \\\\ \\hline\n$\\vec{\\omega}_i$ & angular velocity of center of mass for body $i$  \\\\ \\hline\n$\\vec{u}$ & $\\lbrack \\vec{v}_1, \\vec{\\omega}_1,...,\\vec{v}_n, \\vec{\\omega}_n \\rbrack ^T $\\\\ \\hline\n$M$ &\n\\begin{tabular}{@{}c}\n generalized mass matrix \\\\\n$ M \\in \\mathbb{R}^{6n \\times 6n}$  \n\\end{tabular}\n$\n\\left[ \\begin{array}{ccccc}\nm_i 1 &  &  & & 0 \\\\\n & I_1  \\\\\n & & \\ddots  \\\\\n & & & m_n 1 \\\\\n0 & & & & I_n \n\\end{array} \\right]\n$\n\\\\ \\hline\n$I_i$ & inertia tensor for body $i$  \\\\ \\hline\n$C$ & contact condition matrix  $ C \\in \\mathbb{R}^{6n \\times 3K}$ \\\\ \\hline\n$N$ & contact normal matrix  $ N \\in \\mathbb{R}^{3K \\times K}$ \\\\ \\hline\n\\end {tabular}}\n\\label{tab:eom}\n\\end{table}\n\nFriction in contacts and joint constraints can be handled in a unified way by refactoring\nequation \\ref{eq:eomV} as,  \n\\cite{erleben.thesis}\n%\\citet[p.~66-67]{erleben.thesis}\n\\begin{equation} \\label{eq:eomV2}\n\\vec{u}^{\\, t+\\Delta t} = \\vec{u}^{\\, t}+\\Delta t M^{-1}(\n J_{contact}^T \\vec{\\lambda}_{contact}\n+ J_{joint}^T \\vec{\\lambda}_{joint}\n+ \\vec{f}_{ext}),\n\\end{equation}\nwhere Jacobian terms $J_{joint}^T$ for joints are \nderived by taking time derivatives of the kinematic constraints.\nSymbols used in Equation \\ref{eq:eomV2} are summarized in Table\n\\ref{tab:eom-g} and Figure \\ref{fig:eom-joint},\nwhere $\\vec{r}_{anc}^{\\,i}$ is used to define at which point\njoint constraint is applied relative to body $i$.\n\n\\begin{figure}\n\\centering\n\\begin{tikzpicture}\n\\coordinate (O1) at(1,1);\n\\coordinate (O2) at(1,3);\n\\coordinate (C) at(1,2);\n\\draw (0,0) -- (2,0) -- (2,2) -- (0,2) --(0,0);\n\\draw (0,2) -- (2,2) -- (2,4) -- (0,4) --(0,2) ;\n\\node at (0.5,0.4) {$B_1$};\n\\filldraw (O1) circle (0.5mm) node[anchor=north] {$\\vec{r}_1$};\n\\node at (0.5,3.5) {$B_2$};\n\\filldraw (O2) circle (0.5mm) node[anchor=south] {$\\vec{r}_2$};\n\\draw[-{Stealth[length=3mm]}] (O1) -- (C) node[anchor=north east] {$\\vec{r}_{anc}^{\\,1}$};\n\\draw[-{Stealth[length=3mm]}] (O2) -- (C) node[anchor=south east] {$\\vec{r}_{anc}^{\\,2}$};\n\\node[anchor=west] at (4.5,3.5) {\n$\\vec{r}_i$  =  position of body $i$ \n};\n\\node[anchor=west] at (4.5,3) {$\\vec{r}_{anc}^{\\,i} $ = body frame vector $i$};\n\\end{tikzpicture}\n\\caption{Illustration of nomenclature for equations of motion for joint.}\n\\label{fig:eom-joint}\n\\end{figure}\n\n\n% pdf page 33, notation in typical ODEs\n\\begin{table}\n\\tbl{Additional terms  for generalized equations of motion}{\n\\begin{tabular}{|l| l|}\n\\hline\n{\\bf Symbol} & {\\bf Description} \\\\  \\hline\n$J_{contact}$ & Jacobian matrix for contacts  \\\\ \\hline\n$\\lambda_{contact}$ & vector of lagrange multipliers for contacts  \\\\ \\hline\n$J_{joint}$ & Jacobian matrix for joints  \\\\ \\hline\n$\\lambda_{joint}$ & vector of lagrange multipliers for joints  \\\\ \\hline\n\\end {tabular}}\n\\label{tab:eom-g}\n\\end {table}\n\nConstraint processing in \\cbullet\\ is based on ODE, \\cite{ode}.\nJoints are also discussed in detail in  \n\\cite{erleben.thesis}.\n%\\citet[p.~60-90]{erleben.thesis}.\nEquations \\ref{eq:constraintEquation}, \\ref{eq:lambdaLow} and\n\\ref{eq:lambdaHigh} \nare created for each constraint. \nDerivation for terms in Equation \\ref{eq:constraintEquation}\ncan be done using the position and orientation of connected bodies\ne.g. for ball joint formulation is based on both joint points having the same position.\nIn contact cases, formulation is easier if it is done using velocities, \\cite{ode.joints}.\n\n\\begin{equation} \\label{eq:constraintEquation}\nJ_1 \\vec{v}_1 + \\Omega_1 \\vec{\\omega}_1 + \nJ_2 \\vec{v}_2 + \\Omega_2 \\vec{\\omega}_2 = \\vec{c} + C \\vec{\\lambda}\n\\end{equation}\n\n\\begin{equation} \\label{eq:lambdaLow}\n\\vec{\\lambda} \\geq \\vec{l}\n\\end{equation}\n\n\\begin{equation} \\label{eq:lambdaHigh}\n\\vec{\\lambda} \\leq \\vec{h}\n\\end{equation}\n\nIn the following section, these equations will be explained by a simple example.\nThe main parameters  and corresponding fields in \\cbullet\\  \nare given in Table \\ref{tab:constraintParameters}.\n\n\\begin {table}\n\\tbl {Constraint parameters}{\n\\begin{tabular}{|c| l| l|}\n\\hline\n{\\bf Parameter} & {\\bf Description} & {\\bf btConstraintInfo2 pointer}\\\\  \\hline\n$J_1, \\Omega_1$ & Jacobian & m\\_J1linearAxis, m\\_J1angularAxis \\\\\n$J_2, \\Omega_2$ & & m\\_J2linearAxis, m\\_J2angularAxis \\\\ \\hline\n$\\vec{v}$ & linear velocity & \\\\ \\hline\n$\\vec{\\omega}$ & angular velocity & \\\\ \\hline\n$\\vec{c}$        &  right side vector   & m\\_constraintError \\\\ \\hline\n$C$  & constraint force mixing & cfm \\\\  \\hline\n$\\vec{\\lambda}$ & constraint force &  \\\\ \\hline\n$\\vec{l}$ & low limit for constraint force & m\\_lowerLimit \\\\ \\hline\n$\\vec{h}$ & high limit for constraint force & m\\_upperLimit \\\\ \\hline\n\\end {tabular}}\n\\label{tab:constraintParameters} \n\\end {table}\n\nIn structural analysis, a formulation and associated numerical solution procedure are selected \nbased on needed features.\nOften,  finite element method is used.\nIn most cases, a static solution with an assumption of linear strain-displacement relation\nusing displacement based boundary conditions is used.\n\\cite{bathe-1975} provides a description for handling of various nonlinearities.\nIn large displacement analysis, formulation may be based on updated formulation (Eulerian) or\nLagrangian formulation where initial configuration is used.\nFurther enhancements are material nonlinearity and dynamic analysis.\nPhysics engine provides dynamic analysis with large reference translations and rotations\nwhile assuming bodies to be undeformable.\n\nMaterial plasticity can be accounted for in simulations by using a suitable coefficient of restitution.\nThis provides a reasonable means to simulate loss of energy in collisions.\nIn this work simulation of breaking of bodies made of ductile material is made more realistic \nby splitting the rigid body\nto multiple bodies that are connected by energy absorbing joints.\nA typical engineering stress-strain curve of ductile steel is shown in Figure \\ref{fig:sscurve}.\n\n\\begin{figure}\n\\centering\n\\begin{tikzpicture}\n\\coordinate (Y) at (1,4);\n\\draw[->] (0,0) -- (6,0) node[right] {\\large{$\\epsilon$}};\n\\draw[->] (0,0) -- (0,5) node[above] {\\large{$\\sigma$}};\n\\draw(0,0) -- (Y) -- (2,4) .. controls (5,5) .. (6,4);\n\\draw[dashed](0,4) -- (Y);\n\\node at (-0.2,4) [align=right] {$f_y$};\n\\draw(0.25,1) -- (0.5,1) -- (0.5,2);\n\\node at (0.75,1.5) {$E$};\n\\node at (0.8,2.5) [anchor=west] {$\\sigma = E \\epsilon$ if $\\sigma \\le f_y$};\n\\end{tikzpicture}\n\\caption{Engineering stress-strain curve of ductile steel (not to scale).}\n\\label{fig:sscurve}\n\\end{figure}\n\nIn Figure \\ref{fig:sscurve}, $\\sigma$ is stress, $E$ is Youngs modulus and $f_y$ is yield stress.\nEngineering stress and strain mean that original dimensions are used in stress calculation,\n\\cite{dowling}.\n%\\citet[p.~108]{dowling}.\nThe stress-strain curve is not drawn to scale as elastic strain could not be seen as it is typically \n0.001 to 0.005 and fracture strain can be 100 times larger.\n\nIn this work, an elastic-fully plastic material model is used in most scenarios.\nHaving elastic part allows elastic displacements for slender structures. \nElastic material behavior is ignored in approach introduced in this work if\nthe deformation is related to ahigher frequency\nthan integration stability would allow.\nIt should be noted that geometry\nof bodies is not updated during analysis and thus engineering stress-strain properties are used.\n\nIn this work, strain hardening is taken into account by assuming that plastic volume in bending\nexpands, \n\\cite{dowling}.\n%\\citet[p.~672]{dowling}.\nMaterial that starts to yield first is hardened and as a result of which yielding moves.\n\nThe difference between the elastic and plastic section modulus is depicted in Figure \\ref{fig:wp}.\n\n\\begin{figure}[htb!]\n\\centering\n\\begin{tikzpicture}\n\\coordinate (S) at (2.5,5);\n\\draw (0,5) -- (4,5) ;\n\\draw (0,0) -- (4,0) ;\n\\draw (2,0) -- (2,5) ;\n\\draw (1.5,0) -- (S); \n\\node[above] at (S) [align=center] {\\large{$\\sigma<f_y$}};\n\\node[anchor=west] at (3,3) {\n\\begin{tabular}{l}\nUnder elastic load\\\\\nstress increases\\\\\nlinearly from zero\\\\\nat neutral axis to\\\\\nmaximum value at \\\\\nsurface of body\n\\end{tabular}\n};\n\\end{tikzpicture}\n\\hspace{1cm}\n\\begin{tikzpicture}\n\\coordinate (S) at (3,5);\n\\draw (0,5) -- (4,5) ;\n\\draw (0,0) -- (4,0) ;\n\\draw (2,0) -- (2,5) ;\n\\draw (1,0) -- (1,2.5) -- (3,2.5) -- (S); \n\\node[above] at (S) [align=center] {\\large{$\\sigma=f_y$}};\n\\node[anchor=west] at (3,3) {\n\\begin{tabular}{l}\nUnder fully plastic load\\\\\nstress is at yield\\\\\nlevel over full\\\\\ncross section\n\\end{tabular}\n};\n\\end{tikzpicture}\n\\caption{Axial stress distribution over a cross section for bending under elastic and fully plastic loads.}\n\\label{fig:wp}\n\\end{figure}\n\nAs shown in Figure 2.4, if stress is below yield limit $f_y$, stress and strain are linear within the material.\nIf cross section is fully plastic, stress is assumed to be at yield level over the whole cross section such that \nthe plastic section modulus is higher than the elastic section modulus.\n\nIn this work, plasticity is handled by defining maximum forces\nin Equations \\ref{eq:lambdaLow} and  \n\\ref{eq:lambdaHigh} using plastic capacities, which are defined below.\n\nMaximum force acting in a direction of $\\vec{r}_{anc}^{\\,i} $\nis product of area and yield stress as follows:\n\n\\begin{equation} \\label{eq:fN}\nN_{max}= \\int_A f_y.\n\\end{equation}\n\nMaximum forces acting perpendicular to $\\vec{r}_{anc}^{\\,i} $\nare a product of area and shear yield stress $\\tau_y$ as follows:\n\\begin{equation} \\label{eq:fQ}\nQ_{max}= \\int_A \\tau_y.\n\\end{equation}\n\nMaximum moments acting around the axis perpendicular to $\\vec{r}_{anc}^{\\,i} $\nare integrals of the perpdendicular distance \nand yield stress $f_y$ as given for the moment around the $x$-axis \nand moment around the $z$-axis, respectively:\n\n\\begin{equation} \\label{eq:Mx}\nM_{max}^x= \\int_A z f_y,\n\\end{equation}\n\n\\begin{equation} \\label{eq:Mz}\nM_{max}^z= \\int_A x f_y.\n\\end{equation}\n\nMaximum moment around $\\vec{r}_{anc}^{\\,i} $\nis an integral of distance $d$ from the joint point\nand shear yield stress $\\tau_y$ as: \n\n\\begin{equation} \\label{eq:My}\nM_{max}^y= \\int_A d \\tau_y.\n\\end{equation}\n\nMaximum forces and moments for a\nrectangular section with width $b$ and height $h$ using constant yield stress\nare given in Table \\ref{tab:maxForces}.\nYield shear stress is assumed to be $ 0.5\\, f_y$ using the Tresca yield critetion.\nIf the von Mises yield criterion is used 0.5 is replaced by 0.58 ($1/\\sqrt{3}$), \\cite{dowling}.\n% p. 262, p. 268\nThese are not exact values in a multiaxial stress state but they\nshould be acceptable in most gaming scenarios.\n\n\\begin {table}\n\\tbl {Maximum forces and moments for \nrectangular section with width $b$ and height $h$ using constant yield stress $f_y$}{\n\\begin{tabular}{| c| c|}\n\\hline\n{\\bf Direction} & {\\bf Maximum value}  \\\\ \\hline\nmaximum shear force & $0.5\\, b\\, h f_y$ \\\\ \\hline\nmaximum normal force & $b\\, h\\, f_y$  \\\\ \\hline\nmaximum bending moment in direction of $h$& $0.25\\, b\\, h^2 \\, f_y$  \\\\ \\hline\nmaximum bending moment in direction of $b$ & $0.25\\, b^2\\, h\\, f_y$  \\\\ \\hline\nmaximum torque & $ \\approx 0.19\\, b\\, h\\, \\frac{b\\, + h}{2} f_y$  \\\\ \\hline\n\\end{tabular}}\n\\label{tab:maxForces} \n\\end {table}\n\nFor torque there is a closed form solution only for\ncircular cross sections.\nGiven approximation is \nbest suited for cases where $b$ and $h$ are similar.\nBetter approximation for any given $b$ and $h$ can be obtained \nby integrating distance from the center of the joint over cross section and\nmultiplying it with the yield shear stress e.g. using Octave, \\cite{octave}.\nAn example of calculation of the maximum moment  around $\\vec{r}_{anc}^{\\,i} $\nis shown in Figure \\ref{fig:octave-mp}.\n\n\\begin{figure}\n\\centering\n\\lstset{language=octave}\n\\begin{lstlisting}\nb=0.01; h=0.01; fy=200e6;\nwpy=fy/2*dblquad(@(x,z)...\n sqrt(x.*x+z.*z),-b/2,b/2,-h/2,h/2)\n38.2\n\\end{lstlisting}\n\n\\caption{Calculation of maximum moment  around $\\vec{r}_{anc}^{\\,i} $ using Octave.}\n\\label{fig:octave-mp}\n\\end{figure}\n\n\nThe basic idea introduced in this study can be tested with any framework having motors and hinge constraints.\nThis can be done by setting the target velocity of the motor to zero and limiting \nthe maximum motor impulse to plastic moment multiplied by a timestep.\n\nFurther enhancements were created and tested by forking \\cbullet\\ source code\nand adding new constraints, \\cite{pbullet}.\nInstructions for using  windows executable and  source code are available, \\cite{bp}.\n\n", "meta": {"hexsha": "5d238740e4b5a484233187b66593d0ee9b5fd7cc", "size": 17549, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "pdocs/thesis/article-section-2.tex", "max_stars_repo_name": "simo-11/bullet3", "max_stars_repo_head_hexsha": "af7753f5d7fbc0030a3abbe43356d9a9ea784a62", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pdocs/thesis/article-section-2.tex", "max_issues_repo_name": "simo-11/bullet3", "max_issues_repo_head_hexsha": "af7753f5d7fbc0030a3abbe43356d9a9ea784a62", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pdocs/thesis/article-section-2.tex", "max_forks_repo_name": "simo-11/bullet3", "max_forks_repo_head_hexsha": "af7753f5d7fbc0030a3abbe43356d9a9ea784a62", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4004376368, "max_line_length": 114, "alphanum_fraction": 0.6939426748, "num_tokens": 5830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.3287019664650117}}
{"text": "\\documentclass[a4paper,11pt]{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage{algorithmic}\n\\usepackage{algorithm}\n\\usepackage{pst-plot}\n\\usepackage{graphicx}\n\\usepackage{endnotes}\n\\usepackage{graphics}\n\\usepackage{floatflt}\n\\usepackage{wrapfig}\n\\usepackage{amsfonts}\n\\usepackage{amsmath}\n\\usepackage{verbatim}\n\\usepackage{hyperref}\n\\usepackage{multirow}\n\\usepackage{pdflscape}\n\n\\usepackage{hyperref}\n\\hypersetup{pdfborder={0 0 0 0}}\n\n\\pdfpagewidth 210mm\n\\pdfpageheight 297mm \n\\setlength\\topmargin{0mm}\n\\setlength\\headheight{0mm}\n\\setlength\\headsep{0mm}\n\\setlength\\textheight{250mm}\t\n\\setlength\\textwidth{159.2mm}\n\\setlength\\oddsidemargin{0mm}\n\\setlength\\evensidemargin{0mm}\n\\setlength\\parindent{7mm}\n\\setlength\\parskip{0mm}\n\n\\newenvironment{exercise}[3]{\\paragraph{Exercise #1: #2 \\textsc{(#3pt)}}\\ \\\\}{\n\\medskip}\n\\newcommand{\\question}[2]{\\setlength\\parindent{0mm}\\ \\\\$\\mathbf{Q_#1:}$ #2\\ \\\\}\n\n\\author{\\large{Ilya Kuzovkin, Raul Vicente}}\n\\title{\\huge{Introduction to Computational Neuroscience}\\\\\\LARGE{Practice II: Data Analysis - Continuous Data}}\n\n\\begin{document}\n\\maketitle\n\\ \\\\\nThis is how usual EEG recording of one channel looks like:\n\\begin{figure}[H]\n   \\centering\n   \\includegraphics[width=0.8\\textwidth]{eegrecording.png} \n\\end{figure}\nOn the $x$ axis there is time, on the $y$ axis strength of the recorded signal in $\\mu$V. The dashed line at the time point $x=1000$ is the moment when the \\emph{stimulus} (picture) was shown to the test subject.\n\n%\n% ERP\n%\n\\begin{exercise}{1}{Event Related Potential (ERP)}{1}\nBy looking at the plot above one cannot say that showing the stimulus had any considerable effect on the test subject. It seems that there is an increase starting at the time point 1200 and ending at the time point 1500, but that can be a random event, which is not related to the stimulus.\n\nIn such studies the way to go is to conduct the same experiment several times and then average the results. In this way the response, if it is there, will reveal itself much more clearly.\n\nIn the \\texttt{data} folder you have file \\texttt{erptrials.csv}. One row is one trial recorded for 2 seconds with sampling rate of 1000 Hz. The stimulus was shown at the time point 1000 (1 second). There are 79 trials in this file. Your task is to plot an average of all 79 trials and see whether there is a clear ERP response or not.\n\\end{exercise}\n\n%\n% Apply fourier\n%\n\\begin{exercise}{2}{Frequency Analysis}{2}\nThe most popular operation that you can do with continuous brain data is converting it from the \\emph{time domain} to the \\emph{frequency domain}. Due to the fact that any function can be represented as a sum of sinusoids we can decompose our signal into such sinusoids and observe from which frequency components it consists. In terms of the brain data such transformation makes particular sense, because of the \\emph{brain rhythms} -- different frequencies of the firings of the neurons are related to the different kinds of mental activity\\footnote{\\url{http://en.wikipedia.org/wiki/Electroencephalography\\#Wave_patterns}}.\n\n\\ \\\\\nIn this exercise we will plot \\emph{power spectrum} and see how \\emph{alpha wave} emerges when the test subject's eyes are closed. In the \\texttt{data} folder you can find two files: \\texttt{eyes\\_open.csv} and \\texttt{eyes\\_closed.csv}. The data is recorded from the channel \\texttt{Pz}. One row contains 4 seconds of the signal, sampling rate is 512. Each file has 15 recordings.\n\n\\ \\\\\nYour task is to perform Fourier analysis on both datasets, plot power spectra and compare the results. Do it as follows:\n\\begin{enumerate}\n\t\\item Plot some of the signals just to see how they look like.\n\t\\item For each recorded signal (2048 data points):\n\t\t\\begin{enumerate}\n\t\t\t\\item Use \\texttt{fft(signal)} to compute power spectrum of this signal. You will get a vector of complex numbers.\n\t\t\t\\item Use \\texttt{abs(result\\_of\\_fft)} to obtain the magnitude\\footnote{\\url{http://www.mathworks.se/help/matlab/ref/abs.html}}. \\texttt{abs(result\\_of\\_fft)}$^2$ will give you power.\n\t\t\\end{enumerate}\n\t\\item Sum together 15 power spectrum distributions, that you got from the previous step.\n\t\\item And divide the resulting vector by 15 to obtain the average.\n\t\\item Plot it. You will see that the right part of the graph is mirror image of the left part. Discard the right part.\n\t\\item Your $x$ axis goes from 1 to 1024, which does not correspond to actual frequencies. Compute correct $x$ axis as follows:\n\t\t\\begin{verbatim}\n\t\tdt = 1/512;             % time step\ndf = 1/4;               % frequency step\nfNQ = 1/dt/2;           % fNQ is the maximal frequency, in our case it is 256\n                        %   if you have discarded part of the data in step 5 \n                        %   or 512 if you did not\nxaxis = (0:df:fNQ-df);  % points for your X axis, should be of the same length \n                        %   as the vector of frequencies\n\t\t\\end{verbatim}\n\t\\item And plot it again\n\t\t\\begin{verbatim}\n\t\tplot(xaxis, powers_average);\n\t\t\\end{verbatim}\n\t\tNow your axis goes from 0 to 256 (or 512) with step of 4, which corresponds to the frequency range \\texttt{pow} function produced.\n\\end{enumerate}\n\n\\ \\\\\nAfter making the plot more beautiful and focusing on the range from 0 to 30 Hz you should obtain the result that looks something like this:\n\\begin{figure}[H]\n   \\centering\n   \\includegraphics[width=1\\textwidth]{fouriereyes.png} \n\\end{figure}\n\\end{exercise}\n\n\n%\n% Epilepsy\n%\n\\begin{exercise}{3}{Epilepsy}{2}\nIn the folder \\texttt{data/epilepsy} you have two data files: \\texttt{sz4\\_pre.dat} and \\texttt{sz4\\_ict.dat}. This data was recorded using ECoG\\footnote{http://en.wikipedia.org/wiki/Electrocorticography} array. The file with the suffix \\texttt{\\_pre} is recorded before the seizure and the \\texttt{\\_ict} file is recorded during the epilepsy seizure. Read the \\texttt{README.txt} file for the description of the data. Your task is to perform Fourier analysis on both files and see how brain activity changes during the epilepsy seizure. Speculate what is the nature of the peak around 60Hz.\n\\paragraph{Hint.} Reuse the code from the previous exercise.\n\\paragraph{Hint.} The data has readings from the 76 electrodes. First make Fourier transform on each of them separately, then compute the power spectra (each one separately) and then compute the average and plot that.\n\\end{exercise}\n\n\n\n%\n% Discuss\n%\n\\begin{exercise}{4}{Nyquist theorem}{1}\nWhat does Nyquist theorem say? What does it mean? What are the implications?\\\\\nWhat does this picture illustrate?\n\\begin{figure}[H]\n   \\includegraphics[width=0.4\\textwidth]{nyquist.png} \n\\end{figure}\n\\ \\\\\nPrepare to present and explain the theorem to your fellow students.\n\\end{exercise}\n\n\n%\n% Play DFT\n%\n\\begin{exercise}{5*}{Discrete Fourier Transform (DFT)}{bonus 2}\nNow let us have a look on what happens behind the scenes when you call the \\texttt{fft}\\footnote{Actually Fast Fourier Transform (FFT) is a specific algorithm. In this exercise we do not analyse that, but rather look at the equations, which FFT solves in his own mysterious way.} function. Fourier transform is possible because, as we mentioned before, any function can be represented as a sum of sinusoidal functions of different frequencies and amplitudes. If you have some variable changing over time you can transform this data from the \\emph{time domain} (time on the $x$ axis and the value of the variable on the $y$ axis) to the \\emph{frequency domain} (frequency on the $x$ axis and it's \\emph{power} on the $y$ axis) to see if there is any periodicity in the changes of that variable.\n\n\\ \\\\\nTransformation is defined both for continuous and discrete data. On practice we mostly work with a discrete signal and therefore we use Discrete Fourier Transform (DFT). The equation for the discrete transform is\n$$X_f = \\displaystyle\\sum_{t=0}^{N-1}x_t e^{-i2\\pi f\\frac{t}{N}}$$\nwhere\n\\begin{itemize}\n\\itemsep 0em\n\t\\item $f$ is the frequency of the component, contribution of which you are trying to estimate.\n\t\\item $X_f$ is a complex number, that encodes both amplitude and phase of the sinusoidal component.\n\t\\item $x_t$ is a value of your signal at the time point $t$.\n\t\\item $N$ is the total number of time points.\n\\end{itemize}\nLet us say that you would like to know contribution of sinusoidal components of frequencies from 1 to 100 Hz. Then you should apply this equation 100 times. As a result you will get 100 complex numbers.\nTo extract amplitude from these numbers use the following equation on each of them:\n$$A_f = 2\\frac{\\sqrt{\\text{Re}(X_f)^2 + \\text{Im}(X_f)^2}}{N}$$\nNow you have all the contributions and you have completed Discrete Fourier Transform of your signal. For example if 7th number is \"25\" then it means that the amplitude of the sinusoidal component with frequency 7 $\\times$ df Hz is 25.\n\n\\ \\\\\nHere you see a curve, that is a sum of three sinusoids. Your task is to apply DFT and find out frequencies and amplitudes of those components. You can find data points for this curve in the file \\texttt{curve.csv}.\n\\begin{figure}[htbp]\n   \\centering\n   \\includegraphics[width=0.6\\textwidth]{dodft.png} \n\\end{figure}\n\\end{exercise}\n\n\\ \\\\\n\\ \\\\\n\\ \\\\\n\\ \\\\\nPlease submit a \\texttt{pdf} report with the answers to the questions, plots and comments about your solutions. Also submit the code for the programming exercise(s). Pack those into the \\texttt{zip} archive and upload to the course web page.\n\n\\end{document}\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "44b8722b7c5b2f58599b428c98ba2e17a3e4fc65", "size": 9421, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "2015/Practices/03 - Continuous Data/text/cns-continuousdata.tex", "max_stars_repo_name": "kuz/Computational-Neuroscience-Course", "max_stars_repo_head_hexsha": "b5657c8672397fa845dca88c2740277e7206cb5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2015-01-24T01:14:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T20:40:00.000Z", "max_issues_repo_path": "2015/Practices/03 - Continuous Data/text/cns-continuousdata.tex", "max_issues_repo_name": "NeuroCSUT/Computational-Neuroscience-Course", "max_issues_repo_head_hexsha": "cef9ef2dfc83cbfa91aa9b9ea1f23556aba2e9a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2015/Practices/03 - Continuous Data/text/cns-continuousdata.tex", "max_forks_repo_name": "NeuroCSUT/Computational-Neuroscience-Course", "max_forks_repo_head_hexsha": "cef9ef2dfc83cbfa91aa9b9ea1f23556aba2e9a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2018-02-20T12:20:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-08T20:09:22.000Z", "avg_line_length": 52.3388888889, "max_line_length": 793, "alphanum_fraction": 0.7513002866, "num_tokens": 2542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3286161252430486}}
{"text": "\\section{Introduction} \\label{introduction}\nThe scenario used for this thesis is an application which constantly receives data in form of a time series stream from\none or more sensors. The application itself does not have a general interest in a long term evaluation of the data. Only\nthe most recent time series window has to be classified in the evaluation. The result of the evaluation can be stored or\nprocessed by an other application, the time series window moves on and has to be evaluated again. This process is\ncontinuously repeated with every times series window being readable only once. Dynamic Time Warping (DTW) in combination\nwith a 1-Nearest-Neighbour (1NN) classification for the evaluation is an obvious approach for such a scenario. The\ndisadvantage is that this approach is computationally too demanding for many real time applications \\cite{xi2006fast}.\nThis disadvantage becomes even more tragic under the assumption that perhaps a large amount of incoming time series\nwindows is unclassifiable due to a too large distance to the nearest neighbour.\n\nThis bachelor thesis explains the approach of a sliding window filter for time series ahead of the 1NN in combination\nwith DTW (1NN-DTW) to reduce the execution of 1NN-DTW on unclassifiable time series windows. The condition for such a\nfilter is linear complexity. Furthermore the combination of the filter ahead of the 1NN-DTW should perform with a\nsimilar accuracy as 1NN-DTW on its own.\n\nAn experiment that simulates an above described scenario was carried out to expose the additional benefit of a filter\nahead of 1NN-DTW under the given conditions.%TODO double of\n\nThe bachelor thesis is organized as follows. Section \\ref{background_and_notation} is explaining the sliding window\ntechnique and basics around time series similarity measures that are used in this bachelor thesis. Furthermore\nthe sliding window filter is described at the end of the same section. The description of the experiment and the\nevaluation of the results are contained in section \\ref{experiment}. Conclusions are offered and future work\nis suggested in section \\ref{conclusion_and_future_work}.\n", "meta": {"hexsha": "0485c9a99e17f1982ed7faa00aeda2e84a2ae6dd", "size": 2149, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "bachelor-thesis/introduction.tex", "max_stars_repo_name": "GordonLesti/SlidingWindowFilter", "max_stars_repo_head_hexsha": "22c11f2912a5c523ae8ad85a849e2d0b123536ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-06-22T09:37:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-14T11:43:53.000Z", "max_issues_repo_path": "bachelor-thesis/introduction.tex", "max_issues_repo_name": "GordonLesti/SlidingWindowFilter", "max_issues_repo_head_hexsha": "22c11f2912a5c523ae8ad85a849e2d0b123536ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bachelor-thesis/introduction.tex", "max_forks_repo_name": "GordonLesti/SlidingWindowFilter", "max_forks_repo_head_hexsha": "22c11f2912a5c523ae8ad85a849e2d0b123536ec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-11T23:15:57.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-11T23:15:57.000Z", "avg_line_length": 85.96, "max_line_length": 120, "alphanum_fraction": 0.8222429037, "num_tokens": 445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3286161252430486}}
{"text": "\\section{Solution} \n\\label{sec:sol}\n% (The actual solution in details. Note that there is no need for code or\n% specific software component tools description here. Also, you do not explain things\n% already known by the theory, e.g., do not start elaborating on what is clustering and\n% how useful it is.)\nIn this section, we present an algorithm to deal with the problem. \nFurthermore, we also describe some optimizations, whose improvement will be \nshown in Section~\\ref{sec:eval} along with the evaluation results.\n\n\\subsection{Proposed solution}\nThe solution we propose is based on the A-Priori algorithm. \n\nThe general idea is that we first group the tweets by the period they belong to, \nand then, for each period, we find the popular topics in the period by\nexploiting the A-Priori algorithm. In this case, the transactions are represented by \nthe tweets and the items of a transaction are the relative tokens. Consequently, \nthe frequent itemsets returned by the algorithm are the popular topics of the period.\nSo, we extract the popular topics in the period using the A-Priori algorithm, \nsetting as threshold $s$. \n\nBy doing so, we build another dataset which will be the input for another \ninstance of the A-Priori: in \nthe new dataset, we have a transaction for each period of time and the items of a transaction\nare the popular topics in that period. As threshold for this second instance we use $r$.\n\nThis algorithm answer exactly the problem stated in Section~\\ref{sec:ps}, as \nit finds the topics which are $s$-popular in a fraction of periods of time greater than or equal to $r$,\nwhich is the definition of $s$-popular-$r$-consistent. \n\nActually, since in the second instance of the algorithm we only need to find \nitemsets of size $1$, i.e. single topics,\nwe only need to count in how many periods of time a topic is found to be frequent.\nThus, we only need to perform the first pass of A-Priori, without the need to build \ncandidate pairs and so on. The complete process is shown in Algorithm~\\ref{alg:pcis}. \n\n\\input{algorithms/popular_consistent_itemsets.tex}\n\n\nThe classical A-Priori algorithm is described in Section~\\ref{sec:rw}.\nHowever, if the dataset is not too big, we can exploit this \nfact to implement it more efficiently, by storing some additional \ndata structures. We now proceed to describe these optimizations. \n\n% \\input{algorithms/apriori_standard.tex}\n\n\\subsection{Optimizations}\n\nThe idea is illustrated in Algorithm~\\ref{alg:apriori_opt}.\n\n\\input{algorithms/apriori_std_opt.tex}\n\n\nFirst, Procedure~\\ref{alg:getItems} is called. The procedure scans all the transactions \nand the items in them, building three data structures:\n\\begin{description}\n    \\item[itemIndex, indexItem] used to map items to numbers and vice versa. In fact, \n        the algorithm finds frequent itemsets of numbers corresponding to items, to \n        be more efficient both in terms of time and memory. \n        Once the itemsets of numbers are found, they are converted back to sets of items.  \n    \\item[items] that is a set composed of the sets containing single items, i.e. the candidates \n        of size $1$. \n    \\item[indexTransactions] an array where the $i$-th entry is the set of the transactions \n        containing the $i$-th item.\n\\end{description}\n\nThe rest of the algorithm is almost the same as the classical \nversion, except for the computation of the support of an itemset\nin Procedure~\\ref{alg:getSupport}, \nwhich exploits the \\emph{indexTransactions} structure to speed up the \ncomputation. In fact, having in main memory the set of transactions \ncontaining each item allows us to get the support of the \nitemset fast by computing the size of the intersection of the transactions set of\neach item in the itemset.\n\nFinally, once found the frequent itemsets are found, the algorithm maps back \nset of numbers to sets of items, as shown in Procedure~\\ref{alg:mapItems}.\n\n% \\input{algorithms/apriori_opt.tex}\n\n\\input{algorithms/apriori_std_get_items.tex}\n\n\\input{algorithms/apriori_std_get_support.tex}\n\n\\input{algorithms/apriori_std_map_items.tex}\n", "meta": {"hexsha": "511615450094841194486aff055bef8f1a0ec727", "size": 4081, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/Report/04-solution.tex", "max_stars_repo_name": "masinag/popular_twitter_topics_mining", "max_stars_repo_head_hexsha": "b86e05d7700cfca4dbf9db67cde50664d99e60f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/Report/04-solution.tex", "max_issues_repo_name": "masinag/popular_twitter_topics_mining", "max_issues_repo_head_hexsha": "b86e05d7700cfca4dbf9db67cde50664d99e60f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/Report/04-solution.tex", "max_forks_repo_name": "masinag/popular_twitter_topics_mining", "max_forks_repo_head_hexsha": "b86e05d7700cfca4dbf9db67cde50664d99e60f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.4534883721, "max_line_length": 104, "alphanum_fraction": 0.7745650576, "num_tokens": 966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3286161252430486}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\chapter{Symmetry analysis}\n\nThe symmetry analysis performed by \\calcprog\\ is relatively extensive\nand flexible.  While the program doesn't find all\nof the symmetry elements possessed by molecules, it does get a lot of\nthem. \n\nIn order to make the symmetry analysis as flexible as possible, the\nmolecule can first be moved to the center of mass frame of reference. \nThe \nmoments of inertia are then found and the whole molecule is rotated\ninto the principle axis frame.  This allows molecules which are not\nlocated exactly at the origin or aligned perfectly with the Cartesian\naxes to be analyzed.  \n\nThe transformation to the principle axis frame is controlled by the\nkeyword {\\sf Principle Axes}.  If this keyword is not specified, the\nsymmetry analysis will be done in the orientation specified in the\n{\\sf Geometry} section.\n\nThe program searches for the following\nsymmetry elements:\n\n\\begin{itemize}\n\n\\item {\\bf an inversion center}\n\n\\item {\\bf rotation axes} from C$_2$ through C$_8$ about the three\nCartesian axes.\n\n\\item {\\bf improper rotation axes} from S$_3$ through S$_8$ about the\nthree Cartesian axes.\n\n\\item {\\bf mirror planes} perpendicular to the Cartesian axes.\n\n\\end{itemize}\n\nThe elements found, their axes, and atoms which are equivalent under\neach operation are printed to the output file.\n\nThe characters of the wavefunctions with respect to each operation are\ndetermined by constructing the appropriate transformation matrix for\neach operation and transforming the vector of atomic orbital\ncoefficients for each molecular orbital.  The result of this process\nis the actual character of the wavefunction with respect to the\nsymmetry operation, not just a symmetric/anti-symmetric label.\nIt is important to realize that the results of this method of\ndisplaying the results of symmetry analysis can give results which\nare, at first, confusing for degenerate orbitals.  If you are looking\nat the characters of a set of degerate orbitals and trying to compare\nthem to the characters given in a character table, it is very\nimportant that you sum the characters of each of the members of the\ndegenerate set.\n\n\nWhen a reaction coordinate is being followed, \\calcprog\\ first\ngenerates all the geometries along the coordinate and determines the\nsymmetry elements which they possess.  The only symmetry elements\nreported are those which are conserved along the entire distortion.\nThis means that you don't have to worry about moving from high to low\nsymmetry geometries or {\\it vice versa}.  {\\bf Note:} It is possible\nthat loss of symmetry elements will lead to problems in constructing a\nWalsh diagram.  In these cases {\\bf {\\sf fit\\_walsh}} will warn you.\nIf the diagram as constructed is incorrect, you can either change your\nreaction coordinate to not include geometries with problematic\ndegeneracies or edit the {\\tt .WALSH} file by hand to fix it.  This is\nexplained in more detail below in the section on fitting programs.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n", "meta": {"hexsha": "ad831105db259f63a94c654d60092a588989c5e6", "size": 3065, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/symmetry.tex", "max_stars_repo_name": "richardjgowers/yaehmop", "max_stars_repo_head_hexsha": "d8c7e437b949af4868f7d79c68faf77433081549", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2016-08-07T05:17:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T16:57:28.000Z", "max_issues_repo_path": "docs/symmetry.tex", "max_issues_repo_name": "richardjgowers/yaehmop", "max_issues_repo_head_hexsha": "d8c7e437b949af4868f7d79c68faf77433081549", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 26, "max_issues_repo_issues_event_min_datetime": "2016-07-28T18:59:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-22T13:03:01.000Z", "max_forks_repo_path": "docs/symmetry.tex", "max_forks_repo_name": "richardjgowers/yaehmop", "max_forks_repo_head_hexsha": "d8c7e437b949af4868f7d79c68faf77433081549", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2016-07-28T18:57:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T17:07:25.000Z", "avg_line_length": 43.1690140845, "max_line_length": 70, "alphanum_fraction": 0.7676998369, "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3284657645629408}}
{"text": "% Like most advanced LaTeX files, this one begins with a lot of\n% boilerplate. You don't need to understand (or even read) most of it.\n% All you need to do is fill in your name, UMN ID, email address,\n% and the number of the pset. (Search for \"METADATA\" to find the place\n% for this.) Then, you can go straight to the \"EXERCISE 1\"\n% section and start writing your solutions.\n% The \"VARIOUS USEFUL COMMANDS\" section is probably worth taking a\n% look at at some point.\n\n%----------------------------------------------------------------------------------------\n%\tPACKAGES AND OTHER DOCUMENT CONFIGURATIONS\n%----------------------------------------------------------------------------------------\n\\documentclass[paper=a4, fontsize=12pt]{scrartcl} % A4 paper and 12pt font size\n\\usepackage[T1]{fontenc} % Use 8-bit encoding that has 256 glyphs\n\\usepackage[english]{babel} % English language/hyphenation\n\\usepackage{amsmath,amsfonts,amsthm,amssymb} % Math packages\n\\usepackage{mathrsfs}    % More math packages\n\\usepackage{sectsty}  % Allows customizing section commands\n\\allsectionsfont{\\centering \\normalfont\\scshape} % Make all section titles centered, the default font and small caps %remove this to left align section tites\n\\usepackage{hyperref} % Turns cross-references into hyperlinks,\n                      % and defines \\url and \\href commands.\n\\usepackage{graphicx} % For embedding graphics files.\n\\usepackage{framed}   % For the \"leftbar\" environment used below.\n\\usepackage{ifthen}   % Used for the \\powset command below.\n\\usepackage{lastpage} % for counting the number of pages\n\\usepackage[headsepline,footsepline,manualmark]{scrlayer-scrpage}\n\\usepackage[height=10in,a4paper,hmargin={1in,0.8in}]{geometry}\n\\usepackage[usenames,dvipsnames]{xcolor}\n\\usepackage{tikz}     % This is a powerful tool to draw vector\n                      % graphics inside LaTeX. In particular, you can\n                      % use it to draw graphs.\n\\usepackage{verbatim} % For the \"verbatim\" environment, in which\n                      % special symbols can be used freely without\n                      % confusing the compiler. (And it's typeset in\n                      % a constant-width font.)\n                      % Useful, e.g., for quoting code (or ASCII art).\n\n%\\numberwithin{table}{section} % Number tables within sections (i.e. 1.1, 1.2, 2.1, 2.2 instead of 1, 2, 3, 4)\n\n\\setlength\\parindent{20pt} % Makes indentation for paragraphs longer.\n                           % This makes paragraphs stand out more.\n\n%----------------------------------------------------------------------------------------\n%\tVARIOUS USEFUL COMMANDS\n%----------------------------------------------------------------------------------------\n% The commands below might be convenient. For example, you probably\n% prefer to write $\\powset[2]{V}$ for the set of $2$-element subsets\n% of $V$, rather than writing $\\mathcal{P}_2(V)$.\n% Notice that you can easily define your own commands like this.\n% Caveat: Some of these commands need to be properly \"guarded\" when\n% they occur in subscripts or superscripts. So you should not write\n% $K_\\CC$, but rather $K_{\\CC}$.\n\\newcommand{\\CC}{\\mathbb{C}} % complex numbers\n\\newcommand{\\RR}{\\mathbb{R}} % real numbers\n\\newcommand{\\QQ}{\\mathbb{Q}} % rational numbers\n\\newcommand{\\NN}{\\mathbb{N}} % nonnegative integers\n\\newcommand{\\DD}{{\\mathbb{D}}} % dual numbers\n\\newcommand{\\PP}{\\mathbb{P}} % positive integers\n\\newcommand{\\KK}{\\mathbb{K}} % notation for a ring\n\\newcommand{\\LL}{\\mathbb{L}} % notation for a ring\n\\newcommand{\\MM}{\\mathbb{M}} % notation for a ring\n\\newcommand{\\FF}{\\mathbb{F}} % notation for a field\n\\newcommand{\\Z}[1]{\\mathbb{Z}/#1\\mathbb{Z}} % integers modulo k\n                                            % (syntax: \"\\Z{k}\")\n\\newcommand{\\ZZ}{\\mathbb{Z}} % integers\n\\newcommand{\\id}{\\operatorname{id}} % identity map\n\\newcommand{\\op}{\\operatorname{op}} % opposite ring\n\\newcommand{\\End}{\\operatorname{End}} % endomorphism ring\n\\newcommand{\\lcm}{\\operatorname{lcm}}\n% Lowest common multiple. For historical reasons, LaTeX has a \\gcd\n% command built in, but not an \\lcm command. The preceding line\n% rectifies that.\n\\newcommand{\\Int}{\\operatorname{Int}} % integer-valued polynomials\n\\newcommand{\\set}[1]{\\left\\{ #1 \\right\\}}\n% $\\set{...}$ compiles to {...} (set-brackets).\n\\newcommand{\\abs}[1]{\\left| #1 \\right|}\n% $\\abs{...}$ compiles to |...| (absolute value, or size of a set).\n\\newcommand{\\tup}[1]{\\left( #1 \\right)}\n% $\\tup{...}$ compiles to (...) (parentheses, or tuple-brackets).\n\\newcommand{\\ive}[1]{\\left[ #1 \\right]}\n% $\\ive{...}$ compiles to [...] (Iverson bracket, aka truth value; also, set of first n integers; also, polynomial).\n\\newcommand{\\ivee}[1]{\\left[ \\left[ #1 \\right] \\right]}\n% $\\ivee{...}$ compiles to [[...]] (formal power series).\n\\newcommand{\\floor}[1]{\\left\\lfloor #1 \\right\\rfloor}\n% $\\floor{...}$ compiles to |_..._| (floor function).\n\\newcommand{\\underbrack}[2]{\\underbrace{#1}_{\\substack{#2}}}\n% $\\underbrack{...1}{...2}$ yields\n% $\\underbrace{...1}_{\\substack{...2}}$. This is useful for doing\n% local rewriting transformations on mathematical expressions with\n% justifications. For example, try this out:\n% $ \\underbrack{(a+b)^2}{= a^2 + 2ab + b^2 \\\\ \\text{(by the binomial formula)}} $\n\\newcommand{\\powset}[2][]{\\ifthenelse{\\equal{#2}{}}{\\mathcal{P}\\left(#1\\right)}{\\mathcal{P}_{#1}\\left(#2\\right)}}\n% $\\powset[k]{S}$ stands for the set of all $k$-element subsets of\n% $S$. The argument $k$ is optional, and if not provided, the result\n% is the whole powerset of $S$.\n\\newcommand{\\calF}{\\mathcal{F}}\n\\newcommand{\\horrule}[1]{\\rule{\\linewidth}{#1}} % Create horizontal rule command with 1 argument of height\n\\newcommand{\\nnn}{\\nonumber\\\\} % Don't number this line in an \"align\" environment, and move on to the next line.\n\n%----------------------------------------------------------------------------------------\n%\tMAKING SUMMATION SIGNS ALWAYS PUT THEIR BOUNDS ABOVE AND BELOW\n%\tTHE SIGN\n%----------------------------------------------------------------------------------------\n% The following are hacks to ensure that sums (such as\n% $\\sum_{k=1}^n k$) always put their bounds (i.e., the $k=1$ and the\n% $n$) underneath and above the sign, as opposed to on its right.\n% Same for products (\\prod), set unions (\\bigcup) and set\n% intersections (\\bigcap). Remove the 8 lines below if you do not want\n% this behavior.\n\\let\\sumnonlimits\\sum\n\\let\\prodnonlimits\\prod\n\\let\\cupnonlimits\\bigcup\n\\let\\capnonlimits\\bigcap\n\\renewcommand{\\sum}{\\sumnonlimits\\limits}\n\\renewcommand{\\prod}{\\prodnonlimits\\limits}\n\\renewcommand{\\bigcup}{\\cupnonlimits\\limits}\n\\renewcommand{\\bigcap}{\\capnonlimits\\limits}\n\n%----------------------------------------------------------------------------------------\n%\tENVIRONMENTS\n%----------------------------------------------------------------------------------------\n% The incantations below define how theorem environments\n% (\\begin{theorem} ... \\end{theorem}) and their likes will look like.\n\\newtheoremstyle{plainsl}% <name>\n  {8pt plus 2pt minus 4pt}% <Space above>\n  {8pt plus 2pt minus 4pt}% <Space below>\n  {\\slshape}% <Body font>\n  {0pt}% <Indent amount>\n  {\\bfseries}% <Theorem head font>\n  {.}% <Punctuation after theorem head>\n  {5pt plus 1pt minus 1pt}% <Space after theorem headi>\n  {}% <Theorem head spec (can be left empty, meaning `normal')>\n\n% Environments which make the text inside them slanted:\n\\theoremstyle{plainsl}\n  \\newtheorem{theorem}{Theorem}[section]\n  \\newtheorem{proposition}[theorem]{Proposition}\n  \\newtheorem{lemma}[theorem]{Lemma}\n  \\newtheorem{corollary}[theorem]{Corollary}\n  \\newtheorem{conjecture}[theorem]{Conjecture}\n% Environments that don't:\n\\theoremstyle{definition}\n  \\newtheorem{definition}[theorem]{Definition}\n  \\newtheorem{example}[theorem]{Example}\n  \\newtheorem{exercise}[theorem]{Exercise}\n  \\newtheorem{examples}[theorem]{Examples}\n  \\newtheorem{algorithm}[theorem]{Algorithm}\n  \\newtheorem{question}[theorem]{Question}\n \\theoremstyle{remark}\n  \\newtheorem{remark}[theorem]{Remark}\n\\newenvironment{statement}{\\begin{quote}}{\\end{quote}}\n\\newenvironment{fineprint}{\\begin{small}}{\\end{small}}\n\n%----------------------------------------------------------------------------------------\n%\tMETADATA\n%----------------------------------------------------------------------------------------\n\\newcommand{\\myname}{Darij Grinberg} % ENTER YOUR NAME HERE\n\\newcommand{\\myid}{00000000} % ENTER YOUR UMN ID HERE\n\\newcommand{\\mymail}{dgrinber@umn.edu} % ENTER YOUR EMAIL HERE\n\\newcommand{\\psetnumber}{3} % ENTER THE NUMBER OF THIS PSET HERE\n\n%----------------------------------------------------------------------------------------\n%\tHEADER AND FOOTER\n%----------------------------------------------------------------------------------------\n\\ihead{Solutions to midterm \\#\\psetnumber} % Page header left\n\\ohead{page \\thepage\\ of \\pageref{LastPage}} % Page header right\n\\ifoot{\\myname, \\myid} % left footer\n\\ofoot{\\mymail} % right footer\n\n%----------------------------------------------------------------------------------------\n%\tTITLE SECTION\n%----------------------------------------------------------------------------------------\n\\title{\t\n\\normalfont \\normalsize \n\\textsc{University of Minnesota, School of Mathematics} \\\\ [25pt] % Your university, school and/or department name(s)\n\\horrule{0.5pt} \\\\[0.4cm] % Thin top horizontal rule\n\\huge Math 4281: Introduction to Modern Algebra, \\\\\nSpring 2019:\nMidterm \\psetnumber\\\\% The assignment title\n\\horrule{2pt} \\\\[0.5cm] % Thick bottom horizontal rule\n}\n\\author{\\myname}\n\n\\begin{document}\n\n\\maketitle % Print the title\n\n\\begin{center} % Delete this if you want to save space!\n{\\large due date: \\textbf{Monday, 6 May 2019 at 20:00} on Canvas or by email. \\\\\n\n\\textbf{No collaboration allowed} -- this is a midterm.\n\nPlease solve \\textbf{at most 3 of the 6 exercises}!}\n\\end{center}\n\n%----------------------------------------------------------------------------------------\n%\tEXERCISE 1\n%----------------------------------------------------------------------------------------\n\\horrule{0.3pt} \\\\[0.4cm]\n\n\\section{Exercise 1: Nonunital rings and local unities}\n\n\\subsection{Problem}\n\nA \\textit{nonunital ring} is defined in the same way as we defined a ring,\nexcept that we don't require it to be endowed with an element $1$ (and,\ncorrespondingly, we omit the ``Neutrality of one'' axiom).\nThis does not mean that a nonunital ring must not contain an element $1$\nthat would satisfy the ``Neutrality of one'' axiom; it simply means that\nsuch an element is not required (and not considered part of the ring\nstructure).\nSo, formally speaking, a nonunital ring is a\n$4$-tuple $\\tup{\\KK, +, \\cdot, 0}$\n(while a ring in the usual sense is a $5$-tuple\n$\\tup{\\KK, +, \\cdot, 0, 1}$)\nthat satisfies all the ring axioms except for ``Neutrality of one''.\n\nThus, every ring becomes a nonunital ring if we forget its unity (i.e., if\n$\\tup{\\KK, +, \\cdot, 0, 1}$ is a ring, then $\\tup{\\KK, +, \\cdot, 0}$\nis a nonunital ring).\nBut there are other examples as well:\nFor instance, if $n \\in \\ZZ$ is arbitrary, then\n$n \\ZZ := \\set{ nz \\mid z \\in \\ZZ }\n= \\set{ \\text{all multiples of } n }$ is a nonunital ring\n(when endowed with the usual $+$, $\\cdot$ and $0$).\n\nAn element $z$ of a nonunital ring $\\KK$ is said to be a \\textit{unity}\nof $\\KK$ if every $a \\in \\KK$ satisfies $az = za = a$.\nIn other words, an element $z$ of a nonunital ring $\\KK$ is said\nto be a \\textit{unity} of $\\KK$ if equipping $\\KK$ with the unity\n$z$ results in a ring (in the usual sense of this word).\n\nProve the following:\n\n\\begin{enumerate}\n\n\\item[\\textbf{(a)}] If $n \\in \\ZZ$, then the nonunital ring $n \\ZZ$\nhas a unity if and only if $n \\in \\set{1, 0, -1}$.\n\n\\item[\\textbf{(b)}] Any nonunital ring has \\textbf{at most one} unity.\n\n\\end{enumerate}\n\nNow, let $\\KK$ be a nonunital ring.\nAs usual, we write $+$ and $\\cdot$ for its two operations,\nand $0$ for its zero.\n\nLet $z \\in \\KK$. Define a subset $U_z$ of $\\KK$ by\n\\[\nU_z = \\set{ r \\in \\KK \\mid rz = zr = r }.\n\\]\n\n\\begin{enumerate}\n\n\\item[\\textbf{(c)}] Prove that $0 \\in U_z$, and that every\n$a, b \\in U_z$ satisfy $a + b \\in U_z$ and $ab \\in U_z$.\n\n\\end{enumerate}\n\nThus, we can turn $U_z$ into a nonunital ring by endowing $U_z$\nwith the binary operations $+$ and $\\cdot$ (inherited from $\\KK$) and\nthe element $0$. Consider this nonunital ring $U_z$.\n\n\\begin{enumerate}\n\n\\item[\\textbf{(d)}]\nAssume that $z^2 = z$.\nProve that $z$ is a unity of the nonunital ring $U_z$.\n\n\\end{enumerate}\n\n[\\textbf{Hint:} In \\textbf{(b)}, what would the product of two unities be?]\n\n\\subsection{Solution}\n\n[...]\n\n%----------------------------------------------------------------------------------------\n%\tEXERCISE 2\n%----------------------------------------------------------------------------------------\n\\horrule{0.3pt} \\\\[0.4cm]\n\n\\section{Exercise 2: Rings from nonunital rings}\n\n\\subsection{Problem}\n\nLet $\\KK$ be a nonunital ring.\n(See Exercise 1 for the definition of this notion.)\nLet $\\LL$ be the Cartesian product $\\ZZ \\times \\KK$ (so far, just a set).\nDefine a binary operation $+$ on $\\LL$ by setting\n\\[\n\\tup{n, a} + \\tup{m, b} = \\tup{n+m, a+b}\n\\qquad\n\\text{for all } \\tup{n, a}, \\tup{m, b} \\in \\LL .\n\\]\n(This is an entrywise addition.)\nDefine a binary operation $\\cdot$ on $\\LL$ by\n\\[\n\\tup{n, a} \\tup{m, b} = \\tup{nm, nb + ma + ab}\n\\qquad\n\\text{for all } \\tup{n, a}, \\tup{m, b} \\in \\LL .\n\\]\n(Here, $nb$ and $ma$ are defined in the usual way:\nIf $n \\in \\ZZ$ and $a \\in \\KK$, then $na \\in \\KK$ is defined by\n\\[\nna=\n\\begin{cases}\n\\underbrace{a+a+\\cdots+a}_{n \\text{ times}},           & \\text{if } n \\geq 0;\\\\\n- \\tup{\\underbrace{a+a+\\cdots+a}_{-n \\text{ times}}} , & \\text{if } n < 0\n\\end{cases}\n.\n\\]\nThis does not require $\\KK$ to have a unity.)\n\nProve that $\\LL$, endowed with these two operations $+$ and $\\cdot$ and\nthe zero $\\tup{0, 0}$ and the unity $\\tup{1, 0}$, is a ring\n(in the usual sense of this word).\n\n[\\textbf{Hint:} You can use rules like $n \\tup{a + b} = na + nb$ and\n$\\tup{n + m} a = na + ma$ and $\\tup{nm} a = n \\tup{ma}$\n(for $n, m \\in \\ZZ$ and $a, b \\in \\KK$) without proof; they can be\nproven just as for usual rings.\nYou can also use the fact that finite sums of elements of $\\KK$ are\nwell-defined and behave as we would expect them to\n(we already tacitly used that in writing\n``$\\underbrace{a+a+\\cdots+a}_{n \\text{ times}}$'' without parentheses).\n\nYou don't need to check the ``additive'' axioms (associativity of\naddition, commutativity of addition, neutrality of zero, and\nexistence of additive inverses); as far as addition and zero are\nconcerned, $\\LL$ is just a Cartesian product.]\n\n\\subsection{Remark}\n\nThis exercise gives a way to ``embed'' any nonunital ring $\\KK$\ninto a ring $\\LL$.\nThis helps proving properties of nonunital rings, assuming that\nyou can prove them for rings.\n\nThere is also a much simpler notion of a Cartesian product of two nonunital\nrings (in which both addition and multiplication are defined entrywise). This\nlets us define a nonunital ring $\\ZZ \\times \\KK$. But this is\n\\textbf{not} the ring $\\LL$; it does not generally have a unity.\n\n\\subsection{Solution}\n\n[...]\n\n%----------------------------------------------------------------------------------------\n%\tEXERCISE 3\n%----------------------------------------------------------------------------------------\n\\horrule{0.3pt} \\\\[0.4cm]\n\n\\section{Exercise 3: More sums from number theory}\n\n\\subsection{Problem}\n\n\\begin{enumerate}\n\n\\item[\\textbf{(a)}]\nLet $n$ be a positive integer.\nProve that\n\\[\n\\sum_{j=1}^{n} \\gcd \\tup{j, n}\n= \\sum_{d \\mid n} d \\phi\\tup{ \\dfrac{n}{d} }.\n\\]\nMore generally, if $\\tup{a_1, a_2, a_3, \\ldots}$ is a sequence\nof reals, then prove that\n\\[\n\\sum_{j=1}^{n} a_{\\gcd \\tup{j, n}}\n= \\sum_{d \\mid n} a_d \\phi\\tup{ \\dfrac{n}{d} }.\n\\]\n\n\\item[\\textbf{(b)}]\nLet $n \\in \\NN$. Prove that\n\\begin{align*}\n& \\tup{ \\text{the number of $\\tup{x, y} \\in \\ZZ^2$ satisfying\n              $x^2 + y^2 \\leq n$} } \\\\\n& = 1 + 4\\sum_{k \\in \\NN} \\tup{-1}^k \\floor{ \\dfrac{n}{2k+1} } \\\\\n& = 1 + 4 \\tup{   \\floor{\\dfrac{n}{1}} - \\floor{\\dfrac{n}{3}} \n                + \\floor{\\dfrac{n}{5}} - \\floor{\\dfrac{n}{7}}\n                + \\floor{\\dfrac{n}{9}} - \\floor{\\dfrac{n}{11}}\n                \\pm \\cdots } .\n\\end{align*}\n(The infinite sums in this equality have only finitely many nonzero addends,\nand thus are well-defined.)\n\n\\end{enumerate}\n\n[\\textbf{Hint:} Parts \\textbf{(a)} and \\textbf{(b)} have nothing to do with\neach other.\n\nThis is a good place for a reminder that results proven in the notes, as well\nas problems from previous homework sets and midterms, can be freely used. Both\nparts have rather short solutions if you remember the right results to use!]\n\n\\subsection{Remark}\n\nPart \\textbf{(b)} of this exercise is a ``discrete'' version of the\nfamous Madhava--Gregory--Leibniz series\n\\[\n\\dfrac{\\pi}{4}\n= \\dfrac{1}{1} - \\dfrac{1}{3} + \\dfrac{1}{5} - \\dfrac{1}{7}\n  + \\dfrac{1}{9} - \\dfrac{1}{11} \\pm \\cdots\n\\]\n(where $\\pi$, at last, does denote the area of the unit circle).\nIndeed, if we divide the number of $\\tup{x, y} \\in \\ZZ^2$ satisfying\n$x^2 + y^2 \\leq n$ by $n$, then we obtain an approximation to\nthe area of the unit circle that gets better as $n$\ngrows\\footnote{Just observe that the pairs\n$\\tup{x, y} \\in \\ZZ^2$ satisfying $x^2 + y^2 \\leq n$, regarded\nas points in the Euclidean plane, are precisely the lattice points\ninside the circle with center $0$ and radius $\\sqrt{n}$.\nThus, by counting these pairs, we are approximating the area of this\ncircle. See \\cite[Theorem 12.1]{Clark18} for a rigorous proof.}.\nOn the other hand, it appears reasonable that dividing\n\\[\n1 + 4 \\tup{   \\floor{\\dfrac{n}{1}} - \\floor{\\dfrac{n}{3}} \n                + \\floor{\\dfrac{n}{5}} - \\floor{\\dfrac{n}{7}}\n                + \\floor{\\dfrac{n}{9}} - \\floor{\\dfrac{n}{11}}\n                \\pm \\cdots }\n\\]\nby $n$, we obtain an approximation to\n$4 \\tup{\\dfrac{1}{1} - \\dfrac{1}{3} + \\dfrac{1}{5} - \\dfrac{1}{7}\n        + \\dfrac{1}{9} - \\dfrac{1}{11} \\pm \\cdots}$.\nI am not sure whether this can be rigorously proven,\nhowever.\\footnote{Of course, for any given $k \\in \\NN$,\nthe number\n$\\dfrac{1}{n}\\tup{\\floor{\\dfrac{n}{2k+1}} - \\dfrac{n}{2k+1}}$\ndoes converge to $0$ when $n \\to \\infty$.\nBut here we are taking an alternating sum of infinitely many\nsuch numbers; we can ignore all but the first $n$, but even\nthe first $n$ may no longer converge to $0$ when summed\ntogether.}\n\n\\subsection{Solution}\n\n[...]\n\n%----------------------------------------------------------------------------------------\n%\tEXERCISE 4\n%----------------------------------------------------------------------------------------\n\\horrule{0.3pt} \\\\[0.4cm]\n\n\\section{Exercise 4: Squares in finite fields II}\n\n\\subsection{Problem}\n\nLet $\\FF$ be a finite field such that\n$2 \\cdot 1_{\\FF} \\neq 0_{\\FF}$.\nIn Exercise 5 of\n\\href{http://www.cip.ifi.lmu.de/~grinberg/t/19s/hw6s.pdf}{homework set \\#6},\nwe have seen that\n$\\abs{\\FF}$ is odd, and that the number of squares in $\\FF$ is\n$\\dfrac{1}{2} \\tup{ \\abs{\\FF} + 1 }$.\n\nIn the following, the word ``square'' shall always mean\n``square in $\\FF$''.\n\nA \\textit{nonsquare} shall mean an element of $\\FF$ that is not\na square.\n\nProve the following:\n\n\\begin{enumerate}\n\n\\item[\\textbf{(a)}]\nThe product of two squares is always a square.\n\n\\item[\\textbf{(b)}]\nThe product of a nonzero square with a nonsquare is always\na nonsquare.\n\n\\item[\\textbf{(c)}]\nThe product of two nonsquares is always a square.\n\n\\end{enumerate}\n\n[\\textbf{Hint:} It is easiest to solve the three parts in\nthis exact order.\nFor \\textbf{(c)}, recall that if a subset\n$Y$ of a finite set $X$ satisfies $\\abs{Y} \\geq \\abs{X}$,\nthen $Y = X$.]\n\n\\subsection{Solution}\n\n[...]\n\n%----------------------------------------------------------------------------------------\n%\tEXERCISE 5\n%----------------------------------------------------------------------------------------\n\\horrule{0.3pt} \\\\[0.4cm]\n\n\\section{Exercise 5: Formal differential calculus}\n\n\\subsection{Problem}\n\nLet $\\KK$ be a commutative ring.\nFor each FPS\\footnote{Just as in class, the abbreviation ``FPS''\nstands for ``formal power series''.\nAll FPSs and polynomials in this exercise are in $1$ indeterminate\nover $\\KK$; the indeterminate is called $x$.}\n\\[\nf = \\sum_{k \\in \\NN} a_k x^k = a_0 x^0 + a_1 x^1 + a_2 x^2 + \\cdots \\in \\KK\\ivee{x}\n\\qquad\n\\text{(where $a_i \\in \\KK$),}\n\\]\nwe define the \\textit{derivative} $f'$ of $f$ to be the FPS\n\\[\n\\sum_{k > 0} k a_k x^{k-1}\n= 1 a_1 x^0 + 2 a_2 x^1 + 3 a_3 x^2 + \\cdots \\in \\KK\\ivee{x} .\n\\]\n(This definition imitates the standard procedure for differentiating\npower series in analysis, but it does not require any analysis or\ntopology itself. In particular, $\\KK$ may be any commutative ring\n-- e.g., a finite field.)\n\nLet $D : \\KK\\ivee{x} \\to \\KK\\ivee{x}$ be the map sending\neach FPS $f$ to its derivative $f'$.\nWe refer to $D$ as \\textit{(formal) differentiation}.\nAs usual, for any $n \\in \\NN$, we let $D^n$ denote\n$\\underbrace{D \\circ D \\circ \\cdots \\circ D}_{n \\text{ times}}$\n(which means $\\id$ if $n = 0$).\n\nProve the following:\n\n\\begin{enumerate}\n\n\\item[\\textbf{(a)}]\nIf $f \\in \\KK\\ive{x}$, then $f' \\in \\KK\\ive{x}$ and\n$\\deg \\tup{f'} \\leq \\deg f - 1$.\n(In other words, the derivative of a polynomial is again\na polynomial of degree at least $1$ less.)\n\n\\item[\\textbf{(b)}]\nThe map $D : \\KK\\ivee{x} \\to \\KK\\ivee{x}$ is $\\KK$-linear\n(with respect to the $\\KK$-module structure on $\\KK\\ivee{x}$\ndefined in class -- i.e., both addition and scaling of FPSs\nare defined entrywise).\n\n\\item[\\textbf{(c)}]\nWe have $\\tup{fg}' = f' g + f g'$ for any two FPSs\n$f$ and $g$.\n(This is called the \\textit{Leibniz rule}.)\n\n\\item[\\textbf{(d)}]\nWe have $D^n \\tup{x^k} = n! \\dbinom{k}{n} x^{k-n}$\nfor all $n \\in \\NN$ and $k \\in \\NN$.\nHere, the expression ``$\\dbinom{k}{n} x^{k-n}$'' is\nto be understood as $0$ when $k < n$.\n\n\\item[\\textbf{(e)}]\nIf $\\QQ$ is a subring of $\\KK$, then\nevery polynomial $f \\in \\KK\\ive{x}$ satisfies%\n\\footnote{Just as in class, I am using the notation\n``$f \\ive{u}$'' for the evaluation of $f$ at $u$.\nThe more common notation for this is $f \\tup{u}$,\nbut is too easily mistaken for a product. \\\\\nNote also that we need to require $f$ to be a\npolynomial here, since $f \\ive{x+a}$ would not\nbe defined if $f$ was merely an FPS.}\n\\[\nf \\ive{x+a} = \\sum_{n \\in \\NN} \\dfrac{1}{n!} \\tup{D^n \\tup{f}} \\ive{a} \\cdot x^n\n\\qquad \\text{for all $a \\in \\KK$} .\n\\]\n(The infinite sum on the right hand side has only\nfinitely many nonzero addends.)\n\n\\item[\\textbf{(f)}]\nIf $p$ is a prime such that $p \\cdot 1_\\KK = 0$\n(for example, this happens if $\\KK = \\ZZ / p$),\nthen $D^p \\tup{f} = 0$ for each $f \\in \\KK\\ivee{x}$.\n\n\\end{enumerate}\n\nNow, assume that $\\QQ$ is a subring of $\\KK$.\nFor each FPS\n\\[\nf = \\sum_{k \\in \\NN} a_k x^k = a_0 x^0 + a_1 x^1 + a_2 x^2 + \\cdots \\in \\KK\\ivee{x}\n\\qquad\n\\text{(where $a_i \\in \\KK$),}\n\\]\nwe define the \\textit{integral} $\\int f$ of $f$ to be the FPS\n\\[\n\\sum_{k \\geq 0} \\dfrac{1}{k+1} a_k x^{k+1}\n= \\dfrac{1}{1} a_0 x^1 + \\dfrac{1}{2} a_1 x^2 + \\dfrac{1}{3} a_2 x^3 + \\cdots \\in \\KK\\ivee{x} .\n\\]\n(This definition imitates the standard procedure for integrating\npower series in analysis, but again works for any commutative\nring $\\KK$ that contains $\\QQ$ as subring.)\n\nLet $J : \\KK\\ivee{x} \\to \\KK\\ivee{x}$ be the map sending\neach FPS $f$ to its integral $\\int f$.\nProve the following:\n\n\\begin{enumerate}\n\n\\item[\\textbf{(g)}]\nThe map $J : \\KK\\ivee{x} \\to \\KK\\ivee{x}$ is $\\KK$-linear.\n\n\\item[\\textbf{(h)}]\nWe have $D \\circ J = \\id$.\n\n\\item[\\textbf{(i)}]\nWe have $J \\circ D \\neq \\id$.\n\n\\end{enumerate}\n\n[\\textbf{Hint:} Don't give too much detail; workable outlines\nare sufficient.\nFeel free to interchange summation signs without justification.\nFor part \\textbf{(c)}, it is easiest to first prove it\nin the particular case when $f = x^a$ and $g = x^b$ for some\n$f$ and $g$, and then obtain the general case by interchanging\nsummations.]\n\n\\subsection{Remark}\n\nThis exercise is just the beginning of ``algebraic calculus''.\nA lot more can be done: Differentiation can be extended to\nrational functions; partial derivatives can be defined for\nmultivariate polynomials and FPSs; differential equations can\nbe solved formally in FPSs (rather than functions); even a\npurely algebraic analogue of the classical\n$f'\\tup{x} = \\lim\\limits_{\\varepsilon\\to 0} \\dfrac{f\\tup{x+\\varepsilon} - f\\tup{x}}{\\varepsilon}$\ndefinition exists\\footnote{See Theorem 5 in\n\\url{https://math.stackexchange.com/a/2974977/} .}.\nThese algebraic derivatives play crucial roles in the\nstudy of fields (including finite fields!), in algebraic\ngeometry (where they help define what a\n``singularity'' of an algebraic variety is) and in\nenumerative combinatorics (where they aid in computing\ngenerating functions).\n\nPart \\textbf{(e)} is perhaps the easiest instance of\nthe well-known Taylor formula (no error terms, no\nsmoothness requirements, no convergence issues).\n\nThe ``integral'' $\\int f$ we defined above is, of course,\nonly one possible choice of an FPS $g$ satisfying $g' = f$.\nJust as in calculus, you can add any constant to it, and\nyou get another.\nPart \\textbf{(h)} is an algebraic version of one half of\nthe Fundamental Theorem of Calculus.\nYou can easily prove the other half: For each FPS $f$,\nthe FPS $\\tup{J \\circ D} \\tup{f}$ differs from $f$ only\nin its constant term.\n\nIf $\\KK$ contains $\\QQ$ as a subring, then both $J$ and $D$ are\nelements of the $\\KK$-algebra $\\End \\tup{\\KK\\ivee{x}}$\n(by parts \\textbf{(b)} and \\textbf{(g)} of this exercise).\nPart \\textbf{(h)} of this exercise shows that $J$ is a right\ninverse of $D$; but part \\textbf{(i)} shows that $J$ is not a\nleft inverse (and thus not an inverse) of $D$.\nThis yields an example of a left inverse that is not a right\ninverse.\n\n\\subsection{Solution}\n\n[...]\n\n%----------------------------------------------------------------------------------------\n%\tEXERCISE 6\n%----------------------------------------------------------------------------------------\n\\horrule{0.3pt} \\\\[0.4cm]\n\n\\section{Exercise 6: Formal difference calculus and integer-valued polynomials}\n\n\\subsection{Problem}\n\nLet $\\KK$ be a commutative ring.\n\nFor any polynomial $f \\in \\KK\\ive{x}$,\nwe define the \\textit{first finite difference} $f^\\Delta$ of $f$\nto be the polynomial\n\\[\nf \\ive{x+1} - f \\ive{x} \\in \\KK\\ive{x} .\n\\]\n(This is a ``discrete analogue'' of the derivative,\nin case the analysis-free derivative from Exercise 5\nwas not discrete enough for you.\nIt cannot be extended to FPSs, however, since you cannot\nsubstitute $x+1$ for $x$ in an FPS.)\n\nLet $\\Delta : \\KK\\ive{x} \\to \\KK\\ive{x}$ be the map sending\neach polynomial $f$ to $f^\\Delta$.\nAs usual, for any $n \\in \\NN$, we let $\\Delta^n$ denote\n$\\underbrace{\\Delta \\circ \\Delta \\circ \\cdots \\circ \\Delta}_{n \\text{ times}}$\n(which means $\\id$ if $n = 0$).\n\nProve the following:\n\n\\begin{enumerate}\n\n\\item[\\textbf{(a)}]\nThe map $\\Delta : \\KK\\ive{x} \\to \\KK\\ive{x}$ is $\\KK$-linear\n(with respect to the $\\KK$-module structure on $\\KK\\ive{x}$\ndefined in class -- i.e., both addition and scaling of\npolynomials are defined entrywise).\n\n\\item[\\textbf{(b)}]\nWe have $\\tup{fg}^\\Delta = f^\\Delta g + f\\ive{x+1} g^\\Delta$\nfor any two polynomials $f$ and $g$.\n\n\\end{enumerate}\n\nNow, assume that $\\QQ$ is a subring of $\\KK$.\n\nFor any $n \\in \\NN$, we define a polynomial%\n\\footnote{Note that we are within our rights to divide\nby $n!$ here, since $\\QQ$ is a subring of $\\KK$.}\n\\[\n\\dbinom{x}{n} := \\dfrac{x\\tup{x-1}\\tup{x-2}\\cdots\\tup{x-n+1}}{n!}\n\\in \\KK\\ive{x} .\n\\]\nWe also set $\\dbinom{x}{n} := 0$ for every negative $n$.\n\nProve the following:\n\n\\begin{enumerate}\n\n\\item[\\textbf{(c)}]\nWe have $\\Delta^n \\tup{\\dbinom{x}{k}} = \\dbinom{x}{k-n}$\nfor all $n \\in \\NN$ and $k \\in \\ZZ$.\n\n\\item[\\textbf{(d)}]\nIf $m \\in \\NN$, and if $f \\in \\KK\\ive{x}$ is a polynomial\nof degree $\\leq m$,\nthen there exist elements $a_0, a_1, \\ldots, a_m \\in \\KK$\nsuch that $f = \\sum_{i=0}^m a_i \\dbinom{x}{i}$.\n\n\\item[\\textbf{(e)}]\nEvery polynomial $f \\in \\KK\\ive{x}$ satisfies\n\\[\nf \\ive{x+a} = \\sum_{n \\in \\NN} \\tup{\\Delta^n \\tup{f}} \\ive{a} \\cdot \\dbinom{x}{n}\n\\qquad \\text{for all $a \\in \\KK$} .\n\\]\n(The infinite sum on the right hand side has only\nfinitely many nonzero addends.)\n\n\\item[\\textbf{(f)}]\nLet $m \\in \\NN$, and let $f \\in \\KK\\ive{x}$ be a polynomial\nof degree $\\leq m$.\nAssume that $f\\ive{k} \\in \\ZZ$ for each $k \\in \\set{0, 1, \\ldots, m}$.\nThen, there exist integers $a_0, a_1, \\ldots, a_m$\nsuch that $f = \\sum_{i=0}^m a_i \\dbinom{x}{i}$.\n\n\\end{enumerate}\n\n[\\textbf{Hint:} Part \\textbf{(d)} is easiest to prove by\ninduction on $m$.\nYou can then prove part \\textbf{(e)} for $f = \\dbinom{x}{i}$\nfirst (where $i \\in \\NN$), and then extend it to arbitrary $f$\nby means of part \\textbf{(d)}.\nPart \\textbf{(f)}, in turn, can be derived from part\n\\textbf{(e)} through a strategic choice of $a$.]\n\n\\subsection{Remark}\n\nJust as $\\Delta$ is an analogue of the differentiation\noperator $D$ from Exercise 5,\nwe can define an analogue of the integration operator\n$J$ from Exercise 5.\nThis will be a $\\KK$-linear map $\\Sigma : \\KK\\ive{x} \\to \\KK\\ive{x}$\nthat sends each polynomial\n$\\sum_{i=0}^m a_i \\dbinom{x}{i}$ to\n$\\sum_{i=0}^m a_i \\dbinom{x}{i+1}$\n(this definition makes sense, because part \\textbf{(d)}\nof this exercise\nshows that each polynomial can be written in the form\n$\\sum_{i=0}^m a_i \\dbinom{x}{i}$, uniquely except for\n``leading zeroes'').\nAgain, we have $\\Delta \\circ \\Sigma = \\id$ but\n$\\Sigma \\circ \\Delta \\neq \\id$.\n\nMoreover, if $f \\in \\KK\\ive{x}$ is a polynomial, then\n$\\tup{\\Sigma\\tup{f}} \\ive{0} = 0$\nand\n$\\tup{\\Sigma\\tup{f}} \\ive{n}\n = \\tup{\\Sigma\\tup{f}} \\ive{n-1} + f \\ive{n-1}$\nfor each $n \\in \\ZZ$ (indeed, the former equality\nfollows easily from the definition of $\\Sigma$,\nwhile the latter follows from $\\Delta \\circ \\Sigma = \\id$).\nHence, by induction, we can see that\n\\[\n\\tup{\\Sigma\\tup{f}} \\ive{n}\n= f\\ive{0} + f\\ive{1} + \\cdots + f\\ive{n-1}\n\\qquad \\text{for each polynomial $f \\in \\KK\\ive{x}$\n             and each $n \\in \\NN$}.\n\\]\nIn other words, the value of $\\Sigma\\tup{f}$ at an\n$n \\in \\NN$ is the sum of the first $n$ values of\n$f$ on nonnegative integers! (Whence the notation $\\Sigma$.)\nFor example, if we set $f = x^2$, then it is easy to see\nthat $\\Sigma\\tup{f} = 2 \\dbinom{x}{3} + \\dbinom{x}{2}$\n(to see this, just expand $f$ in the form\n$\\sum_{i=0}^m a_i \\dbinom{x}{i}$ -- namely,\n$f = x^2 = 2 \\dbinom{x}{2} + \\dbinom{x}{1}$ --, and\nthen apply the definition of $\\Sigma$); thus we obtain\n\\[\n2 \\dbinom{n}{3} + \\dbinom{n}{2}\n= 0^2 + 1^2 + \\cdots + \\tup{n-1}^2 .\n\\]\nSimilarly you can find a formula for\n$0^k + 1^k + \\cdots + \\tup{n-1}^k$ whenever $k \\in \\NN$.    \n\nPart \\textbf{(e)} of this exercise is a result of Newton.\n\n\\subsection{Solution}\n\n[...]\n\n\\begin{thebibliography}{99999999}                                                                                         %\n\n% Feel free to add your sources -- or copy some from the source code\n% of the class notes ( http://www.cip.ifi.lmu.de/~grinberg/t/19s/notes.tex ).\n\n% \\bibitem[Clark07]{Clark07}\n% Pete Clark, \\textit{Gauss's circle problem},\n% \\url{http://math.uga.edu/~pete/4400gausscircle.pdf} .\n\n\\bibitem[Clark18]{Clark18}\nPete L. Clark, \\textit{Number Theory: A Contemporary Introduction},\n8 January 2018. \\\\\n\\url{http://math.uga.edu/~pete/4400FULL.pdf}\n\n\\end{thebibliography}\n\n\\end{document}\n\n", "meta": {"hexsha": "676a2b82f83f685be9b7bfe8f59cd8bc85db69b0", "size": 31214, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "mt3.tex", "max_stars_repo_name": "darijgr/algebra19s", "max_stars_repo_head_hexsha": "16476909502a4566bd33b4f11ade52829ef9b16f", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-03-21T05:38:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-17T00:48:51.000Z", "max_issues_repo_path": "mt3.tex", "max_issues_repo_name": "darijgr/algebra19s", "max_issues_repo_head_hexsha": "16476909502a4566bd33b4f11ade52829ef9b16f", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mt3.tex", "max_forks_repo_name": "darijgr/algebra19s", "max_forks_repo_head_hexsha": "16476909502a4566bd33b4f11ade52829ef9b16f", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5619735259, "max_line_length": 157, "alphanum_fraction": 0.6213878388, "num_tokens": 9726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.3284657645629408}}
{"text": "\\XtoCBlock{Sign}\r\n\\label{block:Sign}\r\n\\begin{figure}[H]\\includegraphics{Sign}\\end{figure} \r\n\r\n\\begin{XtoCtabular}{Inports}\r\nIn & Input u\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n\r\n\\begin{XtoCtabular}{Outports}\r\nOut & Value corresponding to sign of u\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n\\subsubsection*{Description:}\r\nSignum function.\r\n\n% include optional documentation file\r\n\\InputIfFileExists{\\XcHomePath/Library/Math/Doc/Sign_Info.tex}{\\vspace{1ex}}{}\r\n\r\n\\subsubsection*{Implementations:}\r\n\\begin{tabular}{l l}\r\n\\textbf{FiP8} & 8 Bit Fixed Point Implementation\\tabularnewline\r\n\\textbf{FiP16} & 16 Bit Fixed Point Implementation\\tabularnewline\r\n\\textbf{FiP32} & 32 Bit Fixed Point Implementation\\tabularnewline\r\n\\end{tabular}\r\n\r\n\\XtoCImplementation{FiP8}\r\n\\index{Block ID!4896}\r\n\\nopagebreak[0]\r\n% Implementation details\r\n\\begin{tabular}{l l}\r\n\\textbf{Name} & FiP8 \\tabularnewline\r\n\\textbf{ID} & 4896 \\tabularnewline\r\n\\textbf{Revision} & 0.1 \\tabularnewline\r\n\\textbf{C filename} & Sign\\_FiP8.c \\tabularnewline\r\n\\textbf{H filename} & Sign\\_FiP8.h \\tabularnewline\r\n\\end{tabular}\r\n\\vspace{1ex}\r\n\r\n8 Bit Fixed Point Implementation\r\n\r\n% Implementation data structure\r\n\\XtoCDataStruct{Data Structure:}\r\n\\begin{lstlisting}\r\ntypedef struct {\r\n     uint16        ID;\r\n     int8          *In;\r\n     int8          Out;\r\n} SIGN_FIP8;\r\n\\end{lstlisting}\r\n\r\n\\ifdefined \\AddTestReports\r\n\\InputIfFileExists{\\XcHomePath/Library/Math/Doc/Test_Sign_FiP8.tex}{}{}\r\n\\fi\r\n\\XtoCImplementation{FiP16}\r\n\\index{Block ID!4897}\r\n\\nopagebreak[0]\r\n% Implementation details\r\n\\begin{tabular}{l l}\r\n\\textbf{Name} & FiP16 \\tabularnewline\r\n\\textbf{ID} & 4897 \\tabularnewline\r\n\\textbf{Revision} & 0.1 \\tabularnewline\r\n\\textbf{C filename} & Sign\\_FiP16.c \\tabularnewline\r\n\\textbf{H filename} & Sign\\_FiP16.h \\tabularnewline\r\n\\end{tabular}\r\n\\vspace{1ex}\r\n\r\n16 Bit Fixed Point Implementation\r\n\r\n% Implementation data structure\r\n\\XtoCDataStruct{Data Structure:}\r\n\\begin{lstlisting}\r\ntypedef struct {\r\n     uint16        ID;\r\n     int16         *In;\r\n     int16         Out;\r\n} SIGN_FIP16;\r\n\\end{lstlisting}\r\n\r\n\\ifdefined \\AddTestReports\r\n\\InputIfFileExists{\\XcHomePath/Library/Math/Doc/Test_Sign_FiP16.tex}{}{}\r\n\\fi\r\n\\XtoCImplementation{FiP32}\r\n\\index{Block ID!4898}\r\n\\nopagebreak[0]\r\n% Implementation details\r\n\\begin{tabular}{l l}\r\n\\textbf{Name} & FiP32 \\tabularnewline\r\n\\textbf{ID} & 4898 \\tabularnewline\r\n\\textbf{Revision} & 0.1 \\tabularnewline\r\n\\textbf{C filename} & Sign\\_FiP32.c \\tabularnewline\r\n\\textbf{H filename} & Sign\\_FiP32.h \\tabularnewline\r\n\\end{tabular}\r\n\\vspace{1ex}\r\n\r\n32 Bit Fixed Point Implementation\r\n\r\n% Implementation data structure\r\n\\XtoCDataStruct{Data Structure:}\r\n\\begin{lstlisting}\r\ntypedef struct {\r\n     uint16        ID;\r\n     int32         *In;\r\n     int32         Out;\r\n} SIGN_FIP32;\r\n\\end{lstlisting}\r\n\r\n\\ifdefined \\AddTestReports\r\n\\InputIfFileExists{\\XcHomePath/Library/Math/Doc/Test_Sign_FiP32.tex}{}{}\r\n\\fi\r\n", "meta": {"hexsha": "c326a73bfece1cc4e7686ef5c3760f0678b0d4aa", "size": 2917, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Library/Math/Doc/Sign.tex", "max_stars_repo_name": "AlexisTM/X2C", "max_stars_repo_head_hexsha": "31f39b598afe271a7fd46ef1ee9e06c410b1120c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Library/Math/Doc/Sign.tex", "max_issues_repo_name": "AlexisTM/X2C", "max_issues_repo_head_hexsha": "31f39b598afe271a7fd46ef1ee9e06c410b1120c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Library/Math/Doc/Sign.tex", "max_forks_repo_name": "AlexisTM/X2C", "max_forks_repo_head_hexsha": "31f39b598afe271a7fd46ef1ee9e06c410b1120c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.814159292, "max_line_length": 79, "alphanum_fraction": 0.7151182722, "num_tokens": 930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.3284657610098199}}
{"text": "\\documentclass[12pt]{article}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{geometry}\n\\usepackage{enumerate}\n\\usepackage{natbib}\n\\usepackage{float}%稳定图片位置\n\\usepackage{graphicx}%画图\n\\usepackage[english]{babel}\n\\usepackage{a4wide}\n\\usepackage{indentfirst}%缩进\n\\usepackage{enumerate}%加序号\n\\usepackage{multirow}%合并行\n\\title{\\large UM-SJTU JOINT INSTITUTE\\\\DISCRETE MATHEMATICS\\\\(VE203)\\\\\\ \\\\\\ \\\\\\ \\\\\\ \\\\\\ \\\\\\ \\\\\\ \\\\\\ \\\\\\ \\\\\\ \\\\\\\nASSIGNMENT 8\\\\\\ \\\\\\ \\\\\\ \\\\\\ \\\\\\ \\\\\\ }\n\\author{Name: Pan Chongdan\\\\ID: 516370910121}\n\\date{Date: \\today}\n\n\n\\begin{document}\n\\maketitle\n\\newpage\n\\section{Q1}\n\\begin{enumerate}[(i)]\n\\item \\textbf{Input}: $a_1,\\cdots,a_n,n$ unsorted elements \n\\par \\textbf{Output}: All the $a_i,1\\leq i\\leq n$ in an increasing order.\n\n\\par \\textbf{for} $p=1$ to $n-1$\n\\par $x=a_{p+1};$\n\\par \\setlength\\parindent{2em}\\textbf{If} $a_p>a_{p+1}$ \\textbf{then}\n\\par \\setlength\\parindent{4em}$i=1;j=p;$\n\\par \\textbf{while} $i<j$ \\textbf{do}\n\\par \\setlength\\parindent{6em}$m\\leftarrow\\lceil(i+j/2）\\rceil;$\n\\par \\textbf{if} $x>a_m$ \\textbf{then} $i\\leftarrow(m+1);$\n\\par \\textbf{else} $j\\leftarrow m;$ \n\\par \\setlength\\parindent{4em}\\textbf{end while}\n\\par \\textbf{for} $k=p$ to $i$\n\\par \\setlength\\parindent{6em}$a_{k+1}=a_k;$\n\\par \\setlength\\parindent{4em}\\textbf{end for}\n\\par $a_i=x;$\n\\par \\setlength\\parindent{2em}\\textbf{end if}\n\\par \\setlength\\parindent{0em}\\textbf{end for}\n\\par \\textbf{return} $(a_1\\cdots a_{n+1});$ \n\\item \nFor the Insertion Sort Algorithm, $n=\\sum_1^7=28$\n\\par For the Binary Insertion Sort Algorithm, $n=1+1+1+2+2+2+3=12$\n\\item $f(n)=\\sum_1^{n-1}=\\frac{n^2-n}{2}$, which is order $n^2$\n\\item $f(n)$ is $O(\\log_2n)$, which is faster than Insertion Sort.\n\\end{enumerate}\n\\section{Q2}\n\\begin{enumerate}[(i)]\n\\item Assume $n=b^k,k=\\log_bn$ then \n$$f(n)=b^d\\cdot f(b^{k-1})+cb^{kd}$$\n$$f(n)=b^d\\cdot[b^d\\cdot f(b^{k-2})+cb^{kd-d}]+cb^{kd}=b^{2d}f(b^{k-2})+2cb^{kd}$$\n$$f(n)=b^{2d}f(b^{k-2})+2cb^{kd}=b^{3d}f(b^{k-3})+3cb^{kd}$$\n$$\\cdots$$\n$$f(n)=b^{kd}f(1)+kcn^d=f(1)n^d+cn^d\\log_bn$$\n\\item Assume $n=b^k,$ where $k=A+B,A\\in\\mathbb{Z}$ and $0<B<1$, then similarly to (i)\n$$f(n)=f(\\frac{n}{b^A})b^{Ad}+Acn^d$$\n$$\\lim_{n\\to\\infty}|\\frac{f(n)}{n^d\\log_bn}|=c$$\n$$\\therefore f\\quad\\mathrm{is}\\quad O(n^d\\log_b(n))$$ \n\\item Assume $n=b^k,k=\\log_bn$ then\n$$f(n)=a\\cdot f(b^{k-1})+cb^{kd}$$\n$$f(n)=a\\cdot[a\\cdot f(b^{k-2})+cb^{kd-d}]+cb^{kd}=a^2f(b^{k-2})+(1+\\frac{a}{b^d})cb^{kd}$$\n$$\\cdots$$\n$$f(n)=a^kf(1)+[1+\\frac{a}{b^d}\\cdots(\\frac{a}{b^d})^{k-1}]cb^{kd}=a^kf(1)+\\frac{a^k-b^{kd}}{ab^{kd-d}-b^{kd}}\\cdot cn^d$$\n$$f(n)=a^kf(1)+c\\cdot\\frac{b^d(n^d-a^k)}{b^d-a}=a^k\\cdot(f(1)+\\frac{cb^d}{a-b^d})+c\\cdot\\frac{b^dn^d}{b^d-a}$$\n$$f(n)=c_1n^d+c_2a^k$$\n$$a^k=a^{\\log_nb}=n^{\\log_ba}$$\n$$\\therefore f(n)=c_1n^d+c_2n^{\\log_ba}$$\n\\item $$\\lim_{n\\to\\infty}|\\frac{f(n)}{n^d}|=|c_1+c_2n^{\\log_ba-d}|$$\n$$\\because a<b^d\\Rightarrow\\log_ba-d<0\\Rightarrow|c_1+c_2n^{\\log_ba-d}|<|c_1+c_2|$$\n$$\\therefore f\\quad\\mathrm{ is }\\quad O(n^d)$$\n\\item Similarly to last question,\n$$\\lim_{n\\to\\infty}|\\frac{f(n)}{n^{log_ba}}|=|c_1n^{d-\\log_ba}+c_2|$$\n$$\\because a>b^d\\Rightarrow\\log_ba-d>0\\Rightarrow|c_1n^{d-\\log_ba}+c_2|<|c_1+c_2|$$\n$$\\therefore f\\quad\\mathrm{ is }\\quad O(n^{\\log_ba})$$\n\\end{enumerate}\n\\section{Q3}\nSince there is only on real root then \n$$a_n=2\\alpha a_{n-1}-\\alpha^2a_{n-2}$$\n$$2\\alpha a_{n-1}-\\alpha^2a_{n-2}=2\\alpha(q_1\\alpha^{n-1}+q_2n\\alpha^{n-1})-\\alpha^2(q_1\\alpha^{n-2}+q_2n\\alpha^{n-2})=q_1\\alpha^n+q_2n\\alpha^n=a_n$$\n\\section{Q4}\n$$\\lambda^3-2\\lambda^2-\\lambda+2=0$$\n$$\\lambda_1=2,\\lambda_2=1,\\lambda_1=-1$$\n$$\\therefore a_n=q_12^n+q_2+q_3(-1)^n$$\n$$3=q_1+q_2+q_3$$\n$$6=2q_1+q_2-q_3$$\n$$0=4q_1+q_2+q_3$$\n$$q_1=-1,q_2=6,q_3=-2$$\n$$a_n=-2^n+6-2(-1)^n$$\n\\section{Q5}\n$$\\lambda^2-5\\lambda+6=0$$\n$$\\lambda_1=2,\\lambda_2=3$$\n$$p_n=bn2^n+cn^2+dn+e$$\n$$p_n=5p_{n-1}-6p_{n-2}$$\n$$b=-2,c=1,d=\\frac{15}{2},e=\\frac{67}{4}$$\n$$a_n=q_12^n+q_23^n-2n2^n+n^2+\\frac{15}{2}n+\\frac{67}{4}$$\n$$q_1=-33,q_2=\\frac{65}{4}$$\n$$a_n=-33\\cdot2^n+\\frac{65}{4}\\cdot3^n-2n2^n+n^2+\\frac{15}{2}n+\\frac{67}{4}$$\n\\section{Q6}\n$$\\lambda^3-7\\lambda^2+16\\lambda-12=0$$\n$$\\lambda_1=3,\\lambda_2=\\lambda_3=2$$\n$$p_n=kn4^n+b4^n$$\n$$kn4^n+b4^n=7k(n-1)4^{n-1}-16k(n-2)4^{n-2}+12k(n-3)4^{n-3}+n4^n+3b4^n$$\n$$k=16,b=-80$$\n$$a_n=q_13^n+q_22^n+q_3n2^n+16n4^n-80\\cdot4^n$$\n$$a_n=49\\cdot3^n+28\\cdot2^n+27.5n2^n+16n4^n+\\frac{5}{2}4^n$$\n\\section{Q7}\n$$a_{n+1}=a_n+(n+1)^4$$\n$$a_n=an^5+bn^4+cn^3+dn^2+en+f$$\n$$a(n+1)^5+(b-1)(n+1)^4+c(n+1)^3+d(n+1)^2+e(n+1)+f=an^5+bn^4+cn^3+dn^2+en+f$$\n$$a=\\frac{1}{5},b=\\frac{1}{2},c=\\frac{1}{3},d=0,e=-\\frac{1}{30},f=0$$\n$$a_n=\\frac{n^5}{5}+\\frac{n^4}{2}+\\frac{n^3}{3}-\\frac{n}{30}$$\n\\section{Q8}\n$$a_n-b_n=2a_{n-1}\\Rightarrow b_n=a_n-2a_{n-1}\\Rightarrow a_{n}=5a_{n-1}-4a_{n-2}$$\n$$\\lambda^2-5\\lambda+4=0$$\n$$\\lambda_1=4,\\lambda_2=1$$\n$$a_n=q_14^n+q_2\\Rightarrow a_n=2\\cdot4^{n}-1$$\n$$\\therefore b_n=4^n+1$$\n\\section{Q9}\n$$\\lambda^2-2\\lambda+2=0$$\n$$\\lambda_1=1+i,\\lambda_2=1-i$$\n$$p_n=k3^n\\Rightarrow k=\\frac{2}{3}k-\\frac{2}{9}k+1\\Rightarrow k=\\frac{9}{5}\\Rightarrow p_n=\\frac{9}{5}\\cdot3^n$$\n$$a_n=(\\sqrt{2})^n(q_1\\cos\\frac{n\\pi}{4}+q_2\\sin\\frac{n\\pi}{4})+\\frac{9}{5}\\cdot 3^n\\Rightarrow q_1=-\\frac{4}{5},q_2=-\\frac{13}{5}$$\n$$a_n=(\\sqrt{2})^n(-\\frac{4}{5}\\cos\\frac{n\\pi}{4}-\\frac{13}{5}\\sin\\frac{n\\pi}{4})+\\frac{9}{5}\\cdot 3^n$$\n\\end{document}", "meta": {"hexsha": "8261329df7b5ed52ed38cf3067be3462d47ca6e9", "size": 5255, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "VE203DiscreteMaths/Assignment/Assignment 8/8.tex", "max_stars_repo_name": "PANDApcd/Algorithm", "max_stars_repo_head_hexsha": "3017c3abd6f3df227addaa924ff5b1a6d28d9b7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "VE203DiscreteMaths/Assignment/Assignment 8/8.tex", "max_issues_repo_name": "PANDApcd/Algorithm", "max_issues_repo_head_hexsha": "3017c3abd6f3df227addaa924ff5b1a6d28d9b7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "VE203DiscreteMaths/Assignment/Assignment 8/8.tex", "max_forks_repo_name": "PANDApcd/Algorithm", "max_forks_repo_head_hexsha": "3017c3abd6f3df227addaa924ff5b1a6d28d9b7c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3779527559, "max_line_length": 149, "alphanum_fraction": 0.6110371075, "num_tokens": 2743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3284004833826601}}
{"text": "\\documentclass[11pt,a4paper]{article}\n\\usepackage{jheppub}\n\\usepackage{hyperref}\n\\usepackage{amsmath}\n\\usepackage{float}\n\\usepackage{amssymb}\n\\usepackage{youngtab}\n\n\\newcommand{\\fund}{$\\Yboxdim{6pt}\\yng(1)$}\n\\newcommand{\\barfund}{$\\bar{\\Yboxdim{6pt}\\yng(1)}$}\n\n\\title{MTC from Argyres-Douglas theory}\n\\author[a]{Hao-Rong Feng,}\n\\author[a]{Satoshi Nawata,}\n\\author[a]{Hao Derrick Zhang}\n\\author[b]{and Rui-Dong Zhu}\n\\affiliation[a]{Department of Physics and Center for Field Theory and Particle Physics, Fudan University, 220, Handan Road, 200433 Shanghai, China}\n\\affiliation[b]{Institute for Advanced Study and School of Physical Science and Technology, Soochow University, 215006 Suzhou, China}\n\\emailAdd{snawata@gmail.com,haozhangphys@gmail.com}\n\\abstract{}\n\\keywords{}\n\n\\begin{document}\n\\maketitle\n\n\n\\section{Argyres-Douglas theory}\nFor a generalized Argyres-Douglas theory $\\mathcal T$, we can construct $3d$ TQFT by choosing the four-dimensional spacetime to be $M_4 = S^1 \\times M_3$. $\\mathcal T$ possesses a $\\mathbb{Z}_F$ global symmetry.\n\\begin{table}[H]\n\\centering\n\\begin{tabular}{c|cccc}\n    $\\mathcal T$ & $(A_1, A_{2N})$ & $(A_1, A_{2N-1})$ & $(A_1, D_{2N})$ & $(A_1, D_{2N+1})$ \\\\\n    \\hline\n    $F$ & $2N + 3$ & $N + 1$ & $N$ & $2N + 1$\\\\\n    fixed points of $\\mathcal M_{\\mathcal T}$ & $N+1$ & $\\frac12N(N+1)$ & $N^2$ & $2N+1$\n\\end{tabular}\n\\end{table}\nWe can turn on a non-trivial holonomy $\\gamma \\in \\mathbb Z_F$ along the $S^1$.\nFurther, the theory is topologically twisted along $M_3$ by identifying the Riemannian holonomy group Spin(3) with $SU(2)_R \\subset SU(2)_R \\times U(1)_r$ of the R-symmetry of the $4d$ $\\mathcal N = 2$ Argyres-Douglas theory.\nWhen the holonomy is co-prime to $F$, $\\gamma \\in \\mathbb Z_F^{\\times}$, the TQFT is expected to be semisimple and is associated to a modular tensor category (MTC), $\\mathcal C_{\\mathcal T}^\\gamma$.\n\nWhile most Argyres-Douglas theories are believed to be non-Lagrangian, one might reach them by RG flows starting from $4d$ $\\mathcal N = 1$ Lagrangian theories.\n\n\\subsection{$SU(N)$ with $2N$ flavors to $(A_1, A_{2N-1})$ theory}\n$\\mathcal T$ is $\\mathcal N = 2 ~SU(N)$ gauge theory with $2N$ fundamental hypermultiplets. This theory has $SU(2N) \\times U(1)$ flavor symmetry. The central charges are\n\\begin{equation}\n    a = \\frac{7N^2 - 5}{24}, \\qquad c = \\frac{2N^2 - 1}{6}, \\qquad k_{SU(N)} = 2N.\n\\end{equation}\nUpon coupling the $SU(N)$ adjoint chiral multiplet $M$, and Higgsing via nilpotent vev, the remaining components of $M$ are $M_j$, where $j = 1, \\cdots, 2N - 1$ with charge $(J_+, J_-) = (0, 2+2j)$. $J_+$ is just the $R$-charge, $R = J_+$ and the flavor charge is given by $\\mathcal F = \\frac12 (J_+ - J_-)$.\n\n$\\mathrm{Tr}\\phi^i$ ($i = 2, 3, \\cdots, N$) and the $M_j$ with $j = 1, 2, \\cdots, N$ will decouple. We are left with $M_j$ with $j=N+1, \\cdots, 2N-1$. The matter content is given by\n\\begin{table}[H]\n\\centering\n\\begin{tabular}{c|cccc}\n    ~        & $q$        & $\\tilde q$      & $\\phi$     & $M_j$ \\\\\n    \\hline\n    $SU(N)$  & \\fund      & \\barfund  & adj        & 1   \\\\\n    $U(1)_B$ & 1          & -1        & 0          & 0   \\\\\n    %$(J_+, J_-)$ & $(1, -2N+1)$  & $(1,-2N+1)$ & $(0,2)$ & $(0,2j+2)$\\\\\n    $U(1)_R$ & 1 & 1 & 0 & 0\\\\\n    $U(1)_{\\mathcal F}$ & $N$ & $N$ & $-1$ & $-(j+1)$\n\\end{tabular}\n\\end{table}\nThe superpotential is given by\n\\begin{equation}\n    W = \\sum_{j = 1}^{2N - 1} M_j(\\phi^{2N - 1 - j}q \\tilde q).\n\\end{equation}\n\n\\subsection{$Sp(N)$ with $2N+2$ flavors to $(A_1, A_{2N})$ theory}\n$\\mathcal T$ is $\\mathcal N =2~Sp(N)$ gauge theory with $2N+2$ fundamental hypermultiplets. This theory has the $SO(4N+4)$ flavor symmetry. The central charges are\n\\begin{equation}\n    a = \\frac{1}{24}N(14 N + 9),\\qquad c = \\frac{1}{6}N(4 N + 3), \\qquad k_{SO(4N+4)} = 4N.\n\\end{equation}\nWe now couple a chiral multiplet $M$ transforming in the adjoint representation of $SO(4N+4)$ and give the principal nilpotent vev to $M$. This will break the $SO(4N + 4)$ flavor symmetry completely, and the remaining components of $M$ would be $M_j$ with $j = 1, 3, \\cdots, 4 N + 1$; $2 N + 1$ having charges $(J_+, J_-) = (0, 2j + 2)$. Note there are two $M$'s with $j = 2 N + 1$. The decoupled operators are all the Coulomb branch operators $\\mathrm{Tr}\\phi^{2i}$ with $i = 1, 2, \\cdots, N$ and $M_j$ with $j = 1, 3, \\cdots, 2 N + 1$ (there are two $M_j$'s with $j = 2 N + 1$) so we are left with $N$ singlet $M_j$ with $j = 2 N + 3, 2 N + 5, \\cdots, 4 N + 1$. The matter content is\n\\begin{table}[H]\n\\centering\n\\begin{tabular}{c|ccccc}\n    ~        & $q$        & $q'$      & $\\phi$     & $M_j$  & $M'_{2N+1}$\\\\\n    \\hline\n    $Sp(N)$  & \\fund      & \\fund     & adj        & 1      & 1\\\\\n    %$(J_+, J_-)$ & $(1, 0)$  & $(1,-4 N - 2)$ & $(0,2)$ & $(0,2j+2)$ & $(0, 4 N + 4)$ \\\\\n    $U(1)_R$ & 1 & 1 & 0 & 0 & 0\\\\\n    $U(1)_{\\mathcal F}$ & $\\frac12$ & $\\frac12(4N+3)$ & $-1$ & $-(j+1)$ & $-(2N + 2)$\\\\\n    %$(R_0, \\mathcal F)$ & $(\\frac12, \\frac12)$ & $(\\frac12(-4N-1), \\frac12(4N + 3))$ & $(1,-1)$ & $(j + 1, - j - 1)$ & $(2 N + 2, - 2 N - 2)$\n\\end{tabular}\n\\end{table}\nThe superpotential is given by\n\\begin{equation}\n    W = \\phi q q + \\sum_{i=1}^{2N+1}M_{2i-1}(\\phi^{4N+3-2i} q' q') + M'_{2N+1}qq'~.\n\\end{equation}\n\n\\subsection{$(A_1,D_{2N})$ theory}\nMatter content of $(A_1, D_{2N})$ theory is given by\n\\begin{table}[H]\n\\centering\n\\begin{tabular}{c|cccccc}\n    ~ & $q_1$ & $\\tilde q_1$ & $q_2$ & $\\tilde q_2$ & $\\phi$ & $M_j$\\\\\n    \\hline\n    $SU(N)$ & \\fund & \\barfund & \\fund & \\barfund & adj & 1\\\\\n    $U(1)_1$ & 1 & $-1$ & 1 & $-1$ & 0 & 0 \\\\\n    $U(1)_2$ & $2N-1$ & $-(2N-1)$ & $-1$ & 1 & 0 & 0\\\\\n    $U(1)_R$ & $1$ & $1$ & $1$ & $1$ & $0$ & $0$\\\\\n    $U(1)_{\\mathcal F}$ & $\\frac12$ & $\\frac12$ & $\\frac{2N-1}{2}$ & $\\frac{2N-1}{2}$ & $-1$ & $-(j+1)$\n\\end{tabular}\n\\end{table}\nwhere $N \\le j \\le 2N-2$.\n\n\\subsection{$(A_1,D_{2N+1})$ theory}\nMatter content of $(A_1, D_{2N+1})$ theory is given by\n\\begin{table}[H]\n\\centering\n\\begin{tabular}{c|cccc}\n    ~ & $q_1$ & $q_2$ & $\\phi$ & $M_j$\\\\\n    \\hline\n    $Sp(N)$ & \\fund & \\fund & adj & 1\\\\\n    $SO(3)$ & 3 & 1 & 1 & 1\\\\\n    $U(1)_R$ & $1$ & $1$ & $0$ & $0$\\\\\n    $U(1)_{\\mathcal F}$ & $\\frac12$ & $\\frac{4N+1}{2}$ & $-1$ & $-(j+1)$\n\\end{tabular}\n\\end{table}\nwhere $j = 2k+1$ and $N\\le k \\le 2N-1$.\n\n\\subsection{Examples}\nIn the following examples, we multiply the previous $U(1)_{\\mathcal F}$ charge by a factor $2/F$.\n\\subsubsection{$(A_1, A_2)$ theory}\nSuperpotential is given by\n\\begin{equation}\n    W = q \\phi q + u q' \\phi q'~.\n\\end{equation}\nThe matter content is given by\n\\begin{table}[H]\n\\centering\n\\begin{tabular}{c|cccc}\n    ~        & $q$        & $q'$      & $\\phi$     & $M_5$ \\\\\n    \\hline\n    $SU(2)$  & \\fund      & \\fund     & adj        & 1   \\\\\n    $U(1)_R$ & 1          & 1         & 0          & 0   \\\\\n    $U(1)_\\mathcal F$     & $\\frac15$ & $\\frac75$  & $-\\frac25$ & $-\\frac{12}{5}$\n\\end{tabular}\n\\end{table}\n\\noindent Number of fixed points is $2$. Decoupled operator: $\\mathrm{Tr}\\phi^2$.\n\n\\subsubsection{$(A_1, A_3)$ theory}\nSuperpotential is given by\n\\begin{equation}\n    W = u q \\tilde q~.\n\\end{equation}\nThe matter content is given by\n\\begin{table}[H]\n\\centering\n\\begin{tabular}{c|cccc}\n    ~        & $q$        & $\\tilde q$& $\\phi$   & $M_3$ \\\\\n    \\hline\n    $SU(2)$  & \\fund      & \\fund     & adj      & 1   \\\\\n    $U(1)_B$ & 1          & -1        & 0        & 0   \\\\\n    $U(1)_R$ & 1          & 1         & 0        & 0   \\\\\n    $U(1)_\\mathcal F$     & $\\frac43$ & $\\frac43$  & $-\\frac23$ & $-\\frac{8}{3}$\n\\end{tabular}\n\\end{table}\n\\noindent Number of fixed points is $3$. Decoupled operator: $\\mathrm{Tr}\\phi^2$.\n\n\\subsubsection{$(A_1, A_4)$ theory}\nThe matter content is given by\n\\begin{table}[H]\n\\centering\n\\begin{tabular}{c|ccccc}\n    ~        & $q$        & $\\tilde q$& $\\phi$     & $M_7$ & $M_9$ \\\\\n    \\hline\n    $Sp(2)$  & \\fund      & \\fund     & adj        & 1     & 1     \\\\\n    $U(1)_R$ & 1          & 1         & 0          & 0     & 0     \\\\\n    $U(1)_\\mathcal F$     & $\\frac17$ & $\\frac{11}{7}$  & $-\\frac27$ & $-\\frac{16}{7}$ & $-\\frac{20}{7}$\n\\end{tabular}\n\\end{table}\n\\noindent Number of fixed points is $3$. Decoupled operator: $\\mathrm{Tr}\\phi^2, \\mathrm{Tr}\\phi^4$.\n\n\\subsubsection{$(A_1, A_5)$ theory}\nThe matter content is given by\n\\begin{table}[H]\n\\centering\n\\begin{tabular}{c|ccccc}\n    ~ & $q$ & $\\tilde q$ & $\\phi$ & $M_4$ & $M_5$\\\\\n    \\hline\n    $SU(3)$ & \\fund & \\barfund & adj & 1 & 1\\\\\n    $U(1)_B$ & 1 & $-1$ & 0 & 0 & 0\\\\\n    $U(1)_R$ & 1 & 1 & 0 & 0 & 0\\\\\n    $U(1)_{\\mathcal F}$ & $\\frac32$ & $\\frac32$ & $-\\frac12$ & $-\\frac52$ & $-3$\n\\end{tabular}\n\\end{table}\n\\noindent Number of fixed points is 6. Decoupled operator: $\\mathrm{Tr}\\phi^2, \\mathrm{Tr}\\phi^3$.\n\n\\subsubsection{$(A_1, D_3)$ theory}\nThe matter content is given by\n\\begin{table}[H]\n\\centering\n\\begin{tabular}{c|cccc}\n    ~        & $q_1$      & $q_2$     & $\\phi$     & $M_3$ \\\\\n    \\hline\n    $SU(2)$  & \\fund      & \\fund     & adj        & 1     \\\\\n    $SO(3)$  & 3          & 1         & 1          & 1     \\\\\n    $U(1)_R$ & 1          & 1         & 0          & 0     \\\\\n    $U(1)_\\mathcal F$     & $\\frac13$ & $\\frac{5}{3}$  & $-\\frac23$ & $-\\frac83$\n\\end{tabular}\n\\end{table}\n\\noindent Number of fixed points is $3$. Decoupled operator:\n\n\\subsubsection{$(A_1, D_4)$ theory}\nThe matter content is given by\n\\begin{table}[H]\n\\centering\n\\begin{tabular}{c|cccccc}\n    ~ & $q_1$ & $\\tilde q_1$ & $q_2$ & $\\tilde q_2$ & $\\phi$ & $M_2$ \\\\\n    \\hline\n    $SU(2)$ & \\fund & \\fund & \\fund & \\fund & adj & 1\\\\\n    $U(1)_1$ & 1 & $-1$ & 1 & $-1$ & 0 & 0\\\\\n    $U(1)_2$ & 3 & $-3$ & $-1$ & 1 & 0 & 0\\\\\n    $U(1)_R$ & 1 & 1 & 1 & 1 & 0 & 0\\\\\n    $U(1)_{\\mathcal F}$ & $\\frac12$ & $\\frac12$ & $\\frac32$ & $\\frac32$ & $-1$ & $-3$\n\\end{tabular}\n\\end{table}\n\\noindent Number of fixed points is 4. Decoupled operator: $\\mathrm{Tr} \\phi^2$.\n\n\n\\section{$\\mathcal{N} = 1$ gauge theories on $\\mathbb{R}^2 \\times T^2$}\nThe effective twisted superpotential, $\\mathcal{W}(u,\\nu;\\tau)$ and the effective dilaton $\\Omega(u,\\nu;\\tau)$ are locally holomorphic in all variables.\nThe Bethe equations are\n\\begin{equation}\n    \\exp\\left(2\\pi i \\partial_{u_a} \\mathcal{W}(u,\\nu;\\tau)\\right) = 1, \\quad a = 1, \\cdots, \\mathrm{rk}(\\mathfrak{g})\n\\end{equation}\nWe can build some operators as\n\\begin{itemize}\n    \\item $\\Pi_a = \\exp(2\\pi i \\partial_{u_a} \\mathcal W)$, the \\emph{gauge flux operator};\n    \\item $\\Pi_\\alpha = \\exp(2\\pi i \\partial_{\\nu_\\alpha} \\mathcal W)$, the \\emph{flavor flux operator};\n    \\item $\\mathcal{H}~ = \\exp(2\\pi i \\Omega)\\det(\\partial_{u_a}\\partial_{u_b}\\mathcal W)$, the\n    \\emph{handle-gluing operator};\n    \\item $\\mathcal{F}~ = \\exp(2\\pi i \\partial_\\tau \\mathcal W)$, the \\emph{fibering operator}.\n\\end{itemize}\nThe parameter $\\nu$ and $\\tau$ are related to the fugacities $y$ and $q$ by\n\\begin{equation}\n    y = e^{2\\pi i \\nu}, \\qquad q = e^{2\\pi i \\tau}.\n\\end{equation}\n\n%-------------------- commented --------------------%\n\\iffalse\n\\subsection{The twisted superpotential}\nThe twisted superpotential only receives contributions from charged\nchiral multiplets. For semisimple Lie algebras, the W-bosons and their superpartners do not contribute.\n\n\\subsubsection{Chiral multiplet contribution}\nConsider chiral multiplet of charge 1 under some $U(1)$ in the Cartan of the gauge group, with $u$ the $U(1)$ complexified flat connection.\nDefine the \\emph{elliptic dilogarithm},\n\\begin{equation}\n    \\psi(u;\\tau) \\equiv -\\frac{1}{2\\pi i}\\int_0^u du' \\log\\theta(u';\\tau),\n\\end{equation}\nwhere the theta-function is defined as\n\\begin{equation}\n    \\theta(u;\\tau) = e^{-\\pi i u} q^{\\frac{1} {12}}\\prod_{k=0}^\\infty (1 - x q^k) (1 - x^{-1} q^{k+1})\n\\end{equation}\nThen the contribution to twisted superpotential is\n\\begin{equation}\n    \\mathcal W_\\Phi(u; \\tau) = -\\frac{u^3}{6 \\tau} + \\psi(u; \\tau).\n\\end{equation}\n\n\\subsubsection{W-boson contribution}\n\\begin{equation}\n    \\mathcal{W}_{\\mathrm{vec}} = -\\rho_W(u), \\qquad \\rho_W \\equiv \\frac12 \\sum_{\\alpha>0}\\alpha.\n\\end{equation}\n\n\\subsubsection{General gauge theory}\nConsider chiral multiplets $\\Phi_i$ in representations $R_i$ of semisimple Lie algebra $\\mathfrak{g}$. We also turn on generic background parameters $\\nu_\\alpha$ for any flavor symmetry, then\n\\begin{equation}\n    \\mathcal{W}(u,\\nu;\\tau) = \\sum_i \\sum_{\\rho \\in R_i} \\mathcal{W}_\\Phi (\\rho_i(u) + \\nu_i; \\tau)\n\\end{equation}\n\\fi\n%----------------------------------------\n\\subsection{Flux operators}\nFor a single chiral multiplet, we have the contribution\n\\begin{equation}\n    \\Pi^\\Phi(u; \\tau) \\equiv e^{2\\pi i(-\\frac{u^2}{2\\tau}+\\frac u 2 - \\frac{\\tau}{12})} \\frac{1}{\\theta_0(u; \\tau)},\n\\end{equation}\nwith $\\theta_0$ the reduced theta function\n\\begin{equation}\n    \\theta_0(u;\\tau) = \\prod_{k=0}^\\infty(1-x q^k)(1-x^{-1}q^{k+1})\n\\end{equation}\nThen we obtain\n\\begin{align}\n    \\Pi_a(u,\\nu; \\tau) &= e^{2\\pi i \\partial_{u_a}\\mathcal W}\n    = \\prod_i\\prod_{\\rho_i \\in R_i} \\Pi^\\Phi(\\rho_i(u)+\\nu_i)^{\\rho_i^a}, \\\\\n    \\Pi_\\alpha(u,\\nu; \\tau) &= e^{2\\pi i \\partial_{\\nu_\\alpha}\\mathcal W}\n    = \\prod_i\\prod_{\\rho_i \\in R_i} \\Pi^\\Phi(\\rho_i(u)+\\nu_i)^{\\omega_i^\\alpha}\n\\end{align}\nfor the gauge and flavor flux operators, respectively.\n\n\\subsection{Fibering operators}\n\\subsubsection{Chiral multiplet contribution to $\\mathcal{F}$}\nDefine\n\\begin{equation}\n    \\Gamma_0(u;\\tau) \\equiv \\prod_{n=0}^\\infty\n    \\left(\\frac{1-x^{-1}q^{n+1}}{1-xq^{n+1}}\\right)^{n+1}\n\\end{equation}\nThen\n\\begin{equation}\n    \\mathcal F^\\Phi(u;\\tau) = \\exp\\left(2\\pi i \\left(\\frac{u^3}{6 \\tau^2} - \\frac{u}{12}\\right)\\right) \\Gamma_0(u; \\tau).\n\\end{equation}\n\n\\subsubsection{General gauge theory}\nThe fibering operators are given by\n\\begin{equation}\n    \\mathcal F({\\bf u};\\tau) = \\prod_I \\mathcal{F}_I^\\Phi(Q_I({\\bf u}); \\tau),\n\\end{equation}\nwhere $I = (\\rho_i)$ run over all the chiral multiplets (that is, over all weights $\\rho_i$ for each $i$) and $Q_I$ is the $U(1)$ charge of $\\Phi_I$, that is $Q_{\\rho_i}^a = \\rho_i^a$ and $Q^\\alpha_{\\rho_i} = \\omega_i^\\alpha$ in terms of the weights of the gauge and flavor representations.\n\n\\subsection{Effective dilaton and handle-gluing operator}\nConsider matter fields in chiral multiplets $\\Phi_i$ of $R$-charges $r_i \\in \\mathbb{Z}$, we have\n\\begin{equation}\n    \\Omega = \\Omega_{\\mathrm{mat}} + \\Omega_{\\mathrm{vec}},\n\\end{equation}\nsuch that\n\\begin{equation}\n\\begin{aligned}\n    \\exp\\left(2\\pi i \\Omega_{\\mathrm{mat}}(u,\\nu; \\tau)\\right) &= \\prod_i \\prod_{\\rho_i \\in R_i} \\Pi^\\Phi(\\rho_i(u)+\\nu_i;\\tau)^{r_i - 1}\\\\\n    \\exp\\left(2\\pi i \\Omega_{\\mathrm{vec}}(u,\\nu; \\tau)\\right) &= \\eta(\\tau)^{-2 \\mathrm{rk}(\\mathfrak{g})}\\prod_{\\alpha \\in \\mathfrak{g}} \\Pi^\\Phi(\\alpha(u); \\tau),\n\\end{aligned}\n\\end{equation}\nwhere the Dedekind eta function is defined as\n\\begin{equation}\n    \\eta(\\tau) \\equiv q^{\\frac{1}{24}} \\prod_{k=1}^\\infty(1 - q^k), \\qquad q = e^{2\\pi i \\tau}.\n\\end{equation}\nThen the Hessian determinant of the twisted superpotential,\n\\begin{equation}\n    H(u, \\nu; \\tau) \\equiv \\det \\frac{\\partial^2 \\mathcal{W}(u, \\nu; \\tau)}{\\partial u_a \\partial u_b} = \\det \\left(\\frac{1}{2\\pi i} \\frac{\\partial \\log \\Pi_a}{\\partial u_b}\\right).\n\\end{equation}\nAnd the handle-gluing operator is given by\n\\begin{equation}\n    \\mathcal{H}(u,\\nu; \\tau) = e^{2 \\pi i \\Omega(u,\\nu; \\tau)} H(u, \\nu; \\tau).\n\\end{equation}\n\n\\section{Holonomy saddles}\n\n\\section{$\\mathcal B_{n+1}$ algebra}\n\n\\section{$\\mathcal W_n$ algebra}\nThis algebra can be obtained by a nonregular quantum Hamiltonian reduction of \\\\$\\widehat{\\mathfrak{sl}}(n+1)_{-\\frac{(n-1)^2}{n}}$\n\n\\nocite{Dedushenko:2018bpp}\n\\nocite{Closset:2017bse}\n\\nocite{Maruyoshi:2016aim}\n\\nocite{Agarwal:2016pjo}\n\\nocite{Hwang:2018riu}\n\\nocite{Nekrasov:2014xaa}\n\\nocite{Fredrickson:2017yka}\n\\nocite{Auger:2019gts}\n\\nocite{Cho:2020ljj}\n\\bibliography{MTC.bib}\n\\bibliographystyle{JHEP}\n\\end{document}", "meta": {"hexsha": "1c9cf6de3195074f48bc0feb9f845a4fcf3ebf20", "size": 15777, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "notes/MTC.tex", "max_stars_repo_name": "Derrick-Zhang/MTC", "max_stars_repo_head_hexsha": "da4b6ea7e0aef6a4ab73cb5d046fa9b9bc933807", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notes/MTC.tex", "max_issues_repo_name": "Derrick-Zhang/MTC", "max_issues_repo_head_hexsha": "da4b6ea7e0aef6a4ab73cb5d046fa9b9bc933807", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notes/MTC.tex", "max_forks_repo_name": "Derrick-Zhang/MTC", "max_forks_repo_head_hexsha": "da4b6ea7e0aef6a4ab73cb5d046fa9b9bc933807", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.4422535211, "max_line_length": 685, "alphanum_fraction": 0.5939025163, "num_tokens": 6356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3284004754831641}}
{"text": "\\documentclass{article}\n\n\\usepackage[left=1.25in,top=1.25in,right=1.25in,bottom=1.25in,head=1.25in]{geometry}\n\\usepackage{amsfonts,amsmath,amssymb,amsthm}\n\\usepackage{verbatim,float,url,enumerate}\n\\usepackage{graphicx,subfigure,psfrag}\n\\usepackage{natbib}\n\\usepackage{environ}\n\\usepackage{hyperref}\n\\usepackage{pifont}\n\\usepackage{xcolor}\n\n\\newtheorem{algorithm}{Algorithm}\n\\newtheorem{theorem}{Theorem}\n\\newtheorem{lemma}{Lemma}\n\\newtheorem{corollary}{Corollary}\n\n\\theoremstyle{remark}\n\\newtheorem{remark}{Remark}\n\\theoremstyle{definition}\n\\newtheorem{definition}{Definition}\n\n\\newcommand{\\argmin}{\\mathop{\\mathrm{argmin}}}\n\\newcommand{\\argmax}{\\mathop{\\mathrm{argmax}}}\n\\newcommand{\\minimize}{\\mathop{\\mathrm{minimize}}}\n\\newcommand{\\maximize}{\\mathop{\\mathrm{maximize}}}\n\\newcommand{\\st}{\\mathop{\\mathrm{subject\\,\\,to}}}\n\\newcommand{\\dist}{\\mathop{\\mathrm{dist}}}\n\n\\newcommand{\\reals}{\\mathbb R}\n\\newcommand{\\prox}{\\operatorname{prox}}\n\\newcommand{\\dom}{\\operatorname{dom}}\n\\def\\R{\\mathbb{R}}\n\\def\\E{\\mathbb{E}}\n\\def\\P{\\mathbb{P}}\n\\def\\Cov{\\mathrm{Cov}}\n\\def\\Var{\\mathrm{Var}}\n\\def\\half{\\frac{1}{2}}\n\\def\\sign{\\mathrm{sign}}\n\\def\\supp{\\mathrm{supp}}\n\\def\\th{\\mathrm{th}}\n\\def\\tr{\\mathrm{tr}}\n\\def\\dim{\\mathrm{dim}}\n\\def\\hbeta{\\hat{\\beta}}\n\n\\begin{document}\n\n\\title{Underactuated Robotics 16-748: Project Proposal \\\\ iLQR for Probabalistic Vehicle Control and Maneuvering}\n\\author{\n  Josh Bennett\\\\\n  \\texttt{jjbennet@andrew.cmu.edu}\n  \\and\n  Ting Che Lin\\\\\n  \\texttt{tingchel@andrew.cmu.edu}\n}\n\\maketitle\n\n\\section{Motivation}\n\nAutonomous vehicles need to respond to detected obstacles quickly and handle sensor uncertainty in a safe, reliable way. Planning a path around obstacles is best accomplished by considering both a) the vehicle dynamics, and b) the probability of collision within a close-range window of time. Trajectory optimization effectively incorporates the dynamics model to constrain the set of potential control strategies, but must be augmented with additional constraints to incorporate collision information. The Iterative Linear Quadratic Regulator (ILQR) provides a way to optimize over the set of feasible trajectories due to vehicle dynamics.\n\n\\section{Proposal}\n\nChen et al. \\cite{chen_zhan_tomizuka_2017} discuss the use of Constrained iLQR (CILQR) for motion planning in autonomous vehicles. We propose an extension of their work, where uncertainty in collision information is incorporated. Uncertainty in both current position and future trajectory of surrounding obstacles will enable the CILQR algorithm to generate trajectories that are robustified to poor sensor measurements, while enabling lower safety trajectories to stil be executed in the absence of safer paths. The resulting vehicular control system will be 1) robust to sensor noise and error, and 2) fast at finding feasible trajectories.\n\n\\section{Research Plan}\n\nWe will implement the CILQR algorithm with probabilistic collision constraints as a C++ library. Linking to this library using Python bindings, we will show effective trajectory planning in a set of simulated vehicle scenarios. The project will be considered a success if a) feasible trajectories are consistently generated, b) unavoidable collisions are handled without erratic behaviour, and c) the planner is able to operate at a cycle rate of 20 Hz on modern multi-core processor.\n\nWe will first establish a set of baseline navigation scenarios which will act as a gating set of tests for the planner. After establishing this baseline standard, we will implement CILQR and evaluate tests which cause a failure.\n\n\\bibliographystyle{plain}\n\\bibliography{bibliography.bib}\n\\small\n\n\n\n\\end{document}\n", "meta": {"hexsha": "23fa49e0f99233f988edfec6e787208c9beab899", "size": 3661, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "proposal/project_proposal_jjbennet.tex", "max_stars_repo_name": "joshuajbennett/av-trajectory-planner", "max_stars_repo_head_hexsha": "522e5193c6aeeeba1ebaca3d43e26bdd21c56340", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-13T23:32:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T17:36:42.000Z", "max_issues_repo_path": "proposal/project_proposal_jjbennet.tex", "max_issues_repo_name": "joshuajbennett/av-trajectory-planner", "max_issues_repo_head_hexsha": "522e5193c6aeeeba1ebaca3d43e26bdd21c56340", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "proposal/project_proposal_jjbennet.tex", "max_forks_repo_name": "joshuajbennett/av-trajectory-planner", "max_forks_repo_head_hexsha": "522e5193c6aeeeba1ebaca3d43e26bdd21c56340", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-04-07T02:29:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-09T02:14:28.000Z", "avg_line_length": 46.3417721519, "max_line_length": 642, "alphanum_fraction": 0.7896749522, "num_tokens": 946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.32837585429482763}}
{"text": "\\documentclass[a4paper,twoside, 10pt]{article}\n\\usepackage[%CJKbookmarks=true,\n\tunicode=true,\n\thyperindex=true,\n\tpdfstartview=FitH,\n\tbookmarksnumbered=true,\t%注释掉此行则书签前没有数字编号\n\tbookmarksopen=true,  \t%注释掉此行则默认不展开书签\n\tcolorlinks=true, \t%注释掉此项则交叉引用为彩色边框(将colorlinks和pdfborder同时注释掉)\n\tpdfborder=001,   \t%注释掉此项则交叉引用为彩色边框\n\tcitecolor=red\n]{hyperref}\n\n\\usepackage{graphicx}\t\t%图像宏包\n\\usepackage{amsmath}\t\t%ams数学宏包\n\\usepackage{algorithm}\t\t% algorithm package\n\\usepackage{algpseudocode}\t% algorithmicx package is included therein\n\\usepackage{simplewick}\n\n\\usepackage[utf8]{inputenc}\n\\usepackage[english]{babel}\n\\usepackage{amsthm}\n\\DeclareMathOperator{\\Tr}{Tr}\n\n\\newtheorem{theorem}{Theorem}\n\\theoremstyle{wick}\n\\newtheorem*{wick}{Wick's Theorem}\n\n\\newtheorem{lemma}[theorem]{Lemma}\n\n\\usepackage{extarrows}\t\t%长等号、等号上下\n\\usepackage{textcomp}\t\t%摄氏度\n\\usepackage{multirow,makecell}\n\\usepackage{mhchem}\n\\usepackage{pifont}\n\\usepackage{subfig}\t\t%subfloat\n\n\\newcommand{\\mr}{\\mathrm}\n\\newcommand{\\tr}{\\textrm}\n\\newcommand{\\tN}{\\tr{N}}\n\\newcommand{\\md}{\\mathrm{d}}\n\\newcommand{\\mi}{\\mathrm{i}}\n\\newcommand{\\me}{\\mathrm{e}}\n\\newcommand{\\mg}{\\mathrm{g}}\n\\newcommand{\\br}{\\bm{r}}\n\\newcommand{\\bR}{\\bm{R}}\n\\newcommand{\\bt}{\\bm{\\tau}}\n\\newcommand{\\bk}{\\bm{k}}\n\\newcommand{\\bK}{\\bm{K}}\n\\newcommand{\\ba}{\\bm{a}}\n\\newcommand{\\bb}{\\bm{b}}\n\\newcommand{\\bG}{\\bm{G}}\n\\newcommand{\\bq}{\\bm{q}}\n\\newcommand{\\bB}{\\bm{B}}\n\\newcommand{\\bx}{\\bm{x}}\n\\newcommand{\\vD}{\\varDelta}\n\\newcommand{\\Ao}{\\mathring{\\mr{A}}}\n\\newcommand{\\tc}{\\textcelsius}\n\\newcommand{\\oo}{$\\ddot{\\mathrm{o}}$}\n\\newcommand{\\hh}{\\hat{E}}\n\\newcommand{\\mcH}{\\mathcal{H}}\n\\newcommand{\\mcS}{\\mathcal{S}}\n\\newcommand{\\mcM}{\\mathcal{M}}\n\\newcommand{\\psik}{\\psi_{\\bm{k}}(\\bm{r})}\n\\newcommand{\\vpr}{V^{\\mr{psd}}(\\bm{r})}\n\\newcommand{\\vpq}{V^{\\mr{psd}}(q)}\n\\newcommand{\\rlh}{\\rightleftharpoons}\n\\newcommand{\\II}{\\tr{\\textit{II}}}\n\\newcommand{\\IV}{\\tr{\\textit{IV}}}\n\\newcommand{\\oscf}{$\\varOmega$-SCF}\n\\newcommand{\\sscf}{$\\sigma$-SCF}\n\\newcommand{\\Oo}{\\varOmega(\\omega)}\n\\newcommand{\\mcF}{\\mathcal{F}}\n\n\\newcommand{\\sff}{\\sffamily}\n\n\\newcommand{\\cd}{c^{\\dagger}}\n\\newcommand{\\ad}{a^{\\dagger}}\n\\newcommand{\\exphf}[1]{\\langle{}#1\\rangle_0}\n\\newcommand{\\mn}{ij\\lambda\\sigma}\n\\newcommand{\\mnp}{i'j'\\lambda'\\sigma'}\n\\newcommand{\\ti}{\\langleij|\\lambda\\sigma\\rangle}\n\\newcommand{\\tiv}{\\langleij|\\sigma\\lambda\\rangle}\n\\newcommand{\\tip}{\\langlei'j'|\\lambda'\\sigma'\\rangle}\n\\newcommand{\\tipv}{\\langlei'j'|\\sigma'\\lambda'\\rangle}\n\\newcommand{\\ex}[1]{\\langle{}#1\\rangle}\n\\newcommand{\\ket}[1]{|#1\\rangle}\n\\newcommand{\\bra}[1]{\\langle{}#1|}\n\\newcommand{\\var}{\\sigma_H^2}\n\\newcommand{\\Ns}{N_{s}}\n\\newcommand{\\Nt}{N_{t}}\n\\newcommand{\\sums}[1]{\\sum_{#1}^{s}}\n\\newcommand{\\sumt}[1]{\\sum_{#1}^{t}}\n\\newcommand{\\mat}[1]{\\mathbf{#1}}\n\\newcommand{\\mmp}{ii'}\n\\newcommand{\\nnp}{jj'}\n\\newcommand{\\llp}{\\lambda\\lambda'}\n\\newcommand{\\ssp}{\\sigma\\sigma'}\n\\newcommand{\\pfrac}[2]{\\frac{\\partial{}#1}{\\partial{}#2}}\n\n\\usepackage{amssymb}\n\\usepackage{color}\n\\usepackage{xcolor}\t\t%颜色\n\\usepackage{bm}\t\t\t%数学矢量宏包\n\\usepackage{mathrsfs}\n\\pagestyle{plain}\n\\usepackage[raggedright]{titlesec}\n\\usepackage[procnames]{listings}\n\n\\usepackage{pict2e}\n\\usepackage{keyval}\n%\\usepackage{fp}\n\\usepackage{diagbox}\t\t%这几个宏包用于画表头的斜线\n\\usepackage{booktabs}\t\t%三种粗细不同的线：\\toprule、\\midrule 和 \\bottomrule 对应顶部、中部、底部\n\\usepackage[font=small,labelfont=bf,width=1.0\\textwidth]{caption}\n\\captionsetup{tablename=Tab. }\n\\captionsetup{figurename=Fig.}\n\n\n\\usepackage[font=small,labelfont=bf,width=1.0\\textwidth]{caption}\n\\usepackage{multirow}\n\\usepackage{cases}\n\n\\usepackage{appendix}\t\t%附录\n\n\\bibliographystyle{unsrt}\n\\newcommand{\\upcite}[1]{\\textsuperscript{\\cite{#1}}}\t%upcite命令\n\n\\usepackage{geometry}\n\\geometry{left=2.7cm,right=2.6cm,top=2.5cm,bottom=2.5cm}\t%页边距\n\n%%\\linespread{1.2}\t\t\t\t%行距\n\n\\title{Basic Exercises for Scientific Programming}\n\\author{Hongzhou Ye}\n\\date{January 1, 2018}\t\t\t\t\t\t\t%开启我则不显示日期\n\n\\newcommand{\\ttf}{\\ttfamily}\n\\newcommand{\\ttt}{\\texttt}\n\n\\begin{document}\n\t\\maketitle{}\n\n\t\\begin{abstract}\n\t\tScientific programming involves many topics of applied math, varying from basic linear algebra to optimization algorithms. This file is a collection of several basic exercises that help you practice some of the essential skills.\n\t\\end{abstract}\n\n\t\\section{Linear least square fitting}\n\n\tIn the most general sense, the task of least square fitting is to find an approximate mapping $\\tilde{f}$ to a given mapping\n\t\\begin{equation}\n\t\\begin{split}\n\t\tf:&\\, \\mathbb{X} \\rightarrow \\mathbb{Y}\t\\\\\n\t\t  &\\, \\bm{x} \\rightarrow \\bm{y} = f(\\bm{x})\n\t\\end{split}\n\t\\end{equation}\n\tby minimizing the least square loss\n\t\\begin{equation}\n\t\t\\mathcal{L}\n\t\t\t= \\sum_{i} \\big\\|\\tilde{f}(\\bm{x}^{(i)}) - \\bm{y}^{(i)}\\big\\|_2^2\n\t\\end{equation}\n\tbased on a set of known data $\\{(\\bm{x}^{(i)}, \\bm{y}^{(i)})\\}$, where\n\t\\begin{equation}\n\t\t\\|\\bm{a}\\|_2\n\t\t\t= \\sqrt{\\bm{a} \\cdot \\bm{a}}\n\t\t\t= \\bigg(\\sum_{\\mu} a_{\\mu}^2\\bigg)^{1/2}\n\t\\end{equation}\n\tis the $2$-norm of vector $\\bm{a}$.\n\n\tAs a special case, linear least square fitting assumes a linear functional form for the approximate mapping $\\tilde{f}$, i.e.\n\t\\begin{equation}\t\\label{eq:lls_ansatz}\n\t\t\\tilde{f}(\\bm{x})\n\t\t\t= \\mat{A}^{\\tr{T}}\\bm{x} + \\bm{b},\n\t\\end{equation}\n\twhere $\\mat{A}$ and $\\bm{b}$ are determined from experimental data. In this exercise, we are going to explore the properties of linear least square fitting.\n\n\t\\begin{enumerate}\n\t\t\\item First let us consider an even simpler case, $\\bm{b} = \\bm{0}$. Show that $\\mat{A}$ is determined by the following equation\n\t\t\\begin{equation}\t\\label{eq:lls_equation}\n\t\t\t\\mat{X} \\mat{X}^{\\tr{T}} \\mat{A}\n\t\t\t\t= \\mat{X} \\mat{Y}^{\\tr{T}}\n\t\t\\end{equation}\n\t\twhere\n\t\t\\begin{equation}\t\\label{eq:data_set_def}\n\t\t\t\\mat{X}\n\t\t\t\t= [\\bm{x}^{(1)}, \\bm{x}^{(2)}, \\cdots{}, \\bm{x}^{(N)}],\\quad{}\n\t\t\t\\mat{Y}\n\t\t\t\t= [\\bm{y}^{(1)}, \\bm{y}^{(2)}, \\cdots{}, \\bm{y}^{(N)}].\n\t\t\\end{equation}\n\n\t\t\\textit{Hint}: $\\mathcal{L}$ is a function of $\\mat{A}$\n\t\t\\begin{equation}\t\\label{eq:lsloss}\n\t\t\\begin{split}\n\t\t\t\\mathcal{L}\n\t\t\t\t&= \\sum_i \\| \\mat{A}^{\\tr{T}} \\bm{x}^{(i)} - \\bm{y}^{(i)} \\|^2_2\n\t\t\t\t= \\sum_i (\\mat{A}^{\\tr{T}} \\bm{x}^{(i)} - \\bm{y}^{(i)})^{\\tr{T}}\n\t\t\t\t(\\mat{A}^{\\tr{T}} \\bm{x}^{(i)} - \\bm{y}^{(i)})\t\\\\\n\t\t\t\t\\iffalse\n\t\t\t\t&= \\mat{A}^{\\tr{T}} \\bigg[\\sum_{i} \\bm{x}^{(i)} \\bm{x}^{(i)\\tr{T}}\\bigg] \\mat{A}\n\t\t\t\t- \\mat{A}^{\\tr{T}} \\bigg[\\sum_{i} \\bm{x}^{(i)} \\bm{y}^{(i)\\tr{T}}\\bigg]\n\t\t\t\t- \\bigg[\\sum_{i} \\bm{y}^{(i)} \\bm{x}^{(i)\\tr{T}} \\bigg] \\mat{A}\n\t\t\t\t+ \\sum_i \\bm{y}^{(i)\\tr{T}} \\bm{y}^{(i)}\n\t\t\t\t\\fi\n\t\t\\end{split}\n\t\t\\end{equation}\n\t\tYou might need the following trick\n\t\t\\begin{equation}\n\t\t\\begin{split}\n\t\t\t\\sum_i \\bm{x}^{(i)\\tr{T}} \\mat{A} \\mat{A}^{\\tr{T}} \\bm{x}^{(i)}\n\t\t\t\t&= \\sum_i \\sum_{\\mu\\nu\\lambda} x^{(i)}_{\\mu} A_{\\mu\\nu}\n\t\t\t\tA^{\\tr{T}}_{\\nu\\lambda} x^{(i)}_{\\lambda}\n\t\t\t\t= \\sum_{\\mu\\nu\\lambda} A^{\\tr{T}}_{\\nu\\lambda} \\bigg[\\sum_i x^{(i)}_{\\lambda}\n\t\t\t\tx^{(i)}_{\\mu}\\bigg] A_{\\mu\\nu}\t\\\\\n\t\t\t\t&= \\sum_{\\mu\\nu\\lambda} A^{\\tr{T}}_{\\nu\\lambda} (XX^{\\tr{T}})_{\\lambda \\mu} A_{\\mu\\nu}\n\t\t\t\t= \\mat{A}^{\\tr{T}} \\mat{X} \\mat{X}^{\\tr{T}} \\mat{A}\n\t\t\\end{split}\n\t\t\\end{equation}\n\t\tSame trick can be played to all other terms in the expansion. Then you can take derivative with $\\mat{A}^{\\tr{T}}$ and obtain the desired equation (you can treat $\\mat{A}$ and $\\mat{A}^{\\tr{T}}$ two independent variables).\n\n\t\t\\item We now have the equation and let us see how it works! In \\ttt{data/least\\_square} you can find the data file \\ttt{X1.txt} and \\ttt{Y1.txt}, which contains $20$ data points. Fit a linear equation with zero $\\bm{b}$ and plot the fitted curve along with the original data. Your result should be something like the following\n\t\t\\begin{figure}[H]\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=0.6\\linewidth]{plot/least_square/XY1.png}\n\t\t\\end{figure}\n\n\t\t\\item The example above is one-dimensional and trivial. A non-trivial multi-dimensional data set can be found in \\ttt{X2.txt} and \\ttt{Y2.txt}, where $\\bm{x}^{(i)} \\in \\mathbb{R}^{5}$ and $\\bm{y}^{(i)} \\in \\mathbb{R}^3$ and there are $20$ of them. Find an $\\mat{A} \\in \\mathbb{R}^{5 \\times{} 3}$ that minimizes the square loss. If you do the math correctly, the least square loss as defined in eqn (\\ref{eq:lsloss}) should be $3.431402129330746$.\n\t\\end{enumerate}\n\n\t\\section{Non-linear fitting in terms of LLS}\n\n\tThe reason why linear least square (LLS) is important is that one can go beyond linear fitting by introducing basis functions.\n\n\tTo be specific, let us first specify the dimension for each quantity:\n\t\\begin{equation}\n\t\t\\bm{x} \\in \\mathbb{R}^n,\\quad{}\n\t\t\\bm{y} \\in \\mathbb{R}^m,\\quad{}\n\t\t\\tr{data set: }\\{(\\bm{x}^{(i)}, \\bm{y}^{(i)})\\}_{i = 1}^N.\n\t\\end{equation}\n\tNow we introduce a basis function:\n\t\\begin{equation}\n\t\\begin{split}\n\t\t\\phi:&\\, \\mathbb{R}^n \\to \\mathbb{R}^l\t\t\\\\\n\t\t\t &\\, \\bm{x} \\to \\bm{\\phi} = \\phi(\\bm{x})\n\t\\end{split}\n\t\\end{equation}\n\tFor example, $\\phi(x) = [x_1^2, x_2^2, x_1x_2]^{\\tr{T}}$ is a basis function transforming a $\\mathbb{R}^2$ vector $\\bm{x} = [x_1, x_2]^{\\tr{T}}$ to a $\\mathbb{R}^3$ vector $\\bm{\\phi}$. With this in hands, our ansatz in eqn (\\ref{eq:lls_ansatz}) needs to be modified\n\t\\begin{equation}\t\\label{eq:lls_ansatz_with_basis}\n\t\t\\tilde{f}(\\bm{x})\n\t\t\t= \\mat{A}^{\\tr{T}} \\phi(\\bm{x}) + \\bm{b}\n\t\\end{equation}\n\tand $\\mat{A} \\in \\mathbb{R}^{l \\times{} m}$.\n\n\tThough eqn (\\ref{eq:lls_ansatz_with_basis}) is still linear in $\\bm{\\phi}$, it does not need to be linear in $\\bm{x}$ because the basis function could be non-linear. In this way, one can achieve non-linearity within the framework of LLS.\n\n\t\\begin{enumerate}\n\t\t\\item In a way similar to the derivation of eqn (\\ref{eq:lls_equation}), show that $\\mat{A}$ in eqn (\\ref{eq:lls_ansatz_with_basis}) is determined by solving\n\t\t\\begin{equation}\n\t\t\t\\mat{\\Phi} \\mat{\\Phi}^{\\tr{T}} \\mat{A}\n\t\t\t\t= \\mat{\\Phi} \\mat{Y}^{\\tr{T}}\n\t\t\\end{equation}\n\t\twhere $\\mat{Y}$ is defined in eqn (\\ref{eq:data_set_def}), and\n\t\t\\begin{equation}\n\t\t\t\\mat{\\Phi}\n\t\t\t\t= [\\bm{\\phi}^{(1)}, \\bm{\\phi}^{(2)}, \\cdots{}, \\bm{\\phi}^{(N)}].\n\t\t\\end{equation}\n\n\t\t\\item \\textit{Polynomial basis}. LLS with basis function\n\t\t\\begin{equation}\n\t\t\t\\phi(x)\n\t\t\t\t= [1, x, x^2, \\cdots{}, x^{l-1}]\n\t\t\\end{equation}\n\t\tis equivalent to fitting a polynomial of order $l-1$. Perform LLS fit with $l = 2, 4, 6$ and $8$ for data sets \\ttt{X1.txt} and \\ttt{Y1.txt} in \\ttt{data/non\\_linear\\_least\\_square}. Then\n\t\t\\begin{enumerate}\n\t\t\t\\item report the loss for each $l$\n\t\t\t\\item report the RMS of $\\mat{A}$ for each $l$\n\t\t\t\\begin{equation}\n\t\t\t\t\\tr{RMS}\\,\\mat{A}\n\t\t\t\t\t= \\frac{1}{nm} \\sum_{\\mu}^n \\sum_{\\nu}^m A_{\\mu\\nu}^2\n\t\t\t\t\t= \\ttt{mean(sum(sum(A.*A)))}\\qquad{}\\tr{(In MATLAB)}\n\t\t\t\\end{equation}\n\t\t\t\\item plot all fitted curves along with the data points\n\t\t\\end{enumerate}\n\t\tWhat trend(s) do you observe?\n\n\t\t\\textit{Hint}: wrapping the fitting and plotting processes each in a function would make your life much easier. Specifically, they could be like\n\t\t\\begin{verbatim}\n\t\t    A = lls_poly(X, Y, l)\n\t\t        % X/Y: data sets; l: polynomial order\n\t\t        % A: LLS coefficient matrix.\n\t\t\\end{verbatim}\n\t\tand\n\t\t\\begin{verbatim}\n\t\t    y = lls_poly_plot(x, A, l)\n\t\t        % x: grid points for plotting (e.g. x = [-1.5:0.1:2.5])\n\t\t        % A: optimized LLS coefficient matrix\n\t\t        % l: polynomial order\n\t\t        % y: function values on grid x, so that you can plot with plot(x, y)\n\t\t\\end{verbatim}\n\n\t\t\\item \\textit{Polynomial basis (cnt'd)}. The data set above is generated as follows\n\t\t\\begin{equation}\n\t\t\ty\n\t\t\t\t= 1 - 2x + x^3 + g\n\t\t\\end{equation}\n\t\tfor $x$ randomly drawn from $-1.5$ to $2$, where $g \\sim \\mathcal{N}(0, 1)$ is a Gaussian random variable that mimics a random noise (from, e.g.\\ measure error). Now plot your fitted curves and the original data points along with the ``real\" solution (set $g = 0$).\n\t\t\\begin{enumerate}\n\t\t\t\\item Does it approach the ``real\" solution for larger $l$?\n\t\t\t\\item Does a small loss always mean a \\emph{good} fitting?\n\t\t\\end{enumerate}\n\n\t\t\\item \\textit{Polynomial basis (cnt'd)}. In the example above, we see how increasing the \\emph{model complexity} (in this case, $l$) can result in \\emph{overfitting}. However, by using more data points, we can have a more complex model without overfitting. Data sets \\ttt{X2.txt} and \\ttt{Y2.txt} are generated in the same way, but of a much larger size! Now re-do all fittings with the new data and plot the fitted curves along with the ``real\" solution. What new trend(s) do you observe?\n\n\t\t\\item \\textit{Sinusoidal basis}. Copy everything from \\ttt{lls\\_poly} to a new function named \\ttt{lls\\_sin} that uses the following basis\n\t\t\\begin{equation}\n\t\t\t[1, \\sin x, \\cos x, \\cdots{}, \\sin (l-1)x, \\cos (l-1)x]^{\\tr{T}}\n\t\t\\end{equation}\n\t\tfor an order-$l$ fitting. Then re-do the fitting for $l = 2, 4, 6$ and $8$. Report variation of the loss as the model complexity increases. Plot all fitted curves along with the ``real\" solution. Do you notice any artificial feature for large $l$?\n\t\\end{enumerate}\n\n\n\\end{document}\n", "meta": {"hexsha": "bcc591c53fbd2f8d9f09909ba1217b0132d1cad7", "size": 12826, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "exercises/exercises.tex", "max_stars_repo_name": "hongzhouye/basic_sciprog", "max_stars_repo_head_hexsha": "37121e76f183a36f411a374383ad1ce350c4ef7b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exercises/exercises.tex", "max_issues_repo_name": "hongzhouye/basic_sciprog", "max_issues_repo_head_hexsha": "37121e76f183a36f411a374383ad1ce350c4ef7b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercises/exercises.tex", "max_forks_repo_name": "hongzhouye/basic_sciprog", "max_forks_repo_head_hexsha": "37121e76f183a36f411a374383ad1ce350c4ef7b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.9563862928, "max_line_length": 491, "alphanum_fraction": 0.6574146265, "num_tokens": 4969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.3282330904745324}}
{"text": "\\documentclass[11pt]{article}\n%============Macros==================%\n% you don't need to change anything. start editing from main body.\n\\usepackage{amsmath,amsfonts,amssymb,amsthm, cancel, float, enumitem, hyperref}\n\\usepackage{qcircuit}\n\\usepackage[margin=1in]{geometry}\n%--------------Cosmetic----------------%\n\\usepackage{mathtools}\n\\usepackage{hyperref}\n\\usepackage{fullpage}\n\\usepackage{microtype}\n\\usepackage{xspace}\n\\usepackage[svgnames]{xcolor}\n\\usepackage[sc]{mathpazo}\n\\usepackage{enumitem}\n\\setlist[enumerate]{itemsep=1pt,topsep=2pt}\n\\setlist[itemize]{itemsep=1pt,topsep=2pt}\n%--------------Header------------------%\n\\def\\course{CS 410/510 Introduction to Quantum Computing}\n\\def\\term{Portland State U, Spring 2017}\n\\def\\prof{Lecturer: Fang Song}\n\\newcommand{\\handout}[5]{\n   \\renewcommand{\\thepage}{\\arabic{page}}\n   \\begin{center}\n   \\framebox{\n      \\vbox{\n    \\hbox to 5.78in { \\hfill \\large{\\course} \\hfill }\n       \\vspace{2mm}\n       \\hbox to 6in { {\\Large \\hfill #5  \\hfill} }\n       \\vspace{2mm}\n       \\hbox to 6in { \\term \\hfill \\emph{#2}}\n       \\hbox to 6in { {#3 \\hfill \\emph{#4}}}\n      }\n   }\n   \\end{center}\n   \\vspace*{4mm}\n}\n\\newcommand{\\lecture}[4]{\\handout{#1}{#2}{#3}{#4}{{Lecture #1}}}\n\n\\def\\complex{\\mathbb{C}}\n\\def\\real{\\mathbb{R}}\n\\def\\natural{\\mathbb{N}}\n\\def\\integer{\\mathbb{Z}}\n\n\\newcommand{\\norm}[1]{\\left\\lVert#1\\right\\rVert}\n\\newcommand{\\snorm}[1]{\\lVert#1\\rVert}\n\\newcommand{\\abs}[1]{\\left\\lvert #1 \\right\\rvert}\n\\newcommand{\\ceil}[1]{\\left\\lceil #1 \\right\\rceil}\n\\newcommand{\\floor}[1]{\\left\\lfloor #1 \\right\\rfloor}\n\\newcommand{\\set}[1]{\\left\\{ #1 \\right\\}}\n\\newcommand{\\vecb}[1]{\\boldsymbol{\\vec{#1}}}\n\\newcommand{\\conj}[1]{\\overline{#1}}\n\\newcommand{\\op}[2]{#1#2#1^\\dag}\n\n\\newcommand{\\h}{\\operatorname{H}}\n\\newcommand{\\tf}{\\operatorname{Tf}}\n\\newcommand{\\pr}{\\operatorname{Pr}}\n\\newcommand{\\poly}{\\operatorname{poly}}\n\\newcommand{\\sign}{\\operatorname{sign}}\n\\newcommand{\\rank}{\\operatorname{rank}}\n\\renewcommand{\\det}{\\operatorname{Det}}\n\n\\newcommand{\\bqp}{\\operatorname{BQP}}\n\\newcommand{\\bpp}{\\operatorname{BPP}}\n\\newcommand{\\p}{\\operatorname{P}}\n\\newcommand{\\np}{\\operatorname{NP}}\n\\newcommand{\\pspace}{\\operatorname{PSPACE}}\n\\renewcommand{\\exp}{\\operatorname{EXP}}\n\\newcommand{\\pp}{\\operatorname{PP}}\n\\newcommand{\\qma}{\\operatorname{QMA}}\n\\newcommand{\\qnp}{\\operatorname{QNP}}\n\\newcommand{\\ma}{\\operatorname{MA}}\n\\newcommand{\\ip}{\\operatorname{IP}}\n\\newcommand{\\qip}{\\operatorname{QIP}}\n\\newcommand{\\gnm}{\\operatorname{GNM}}\n\n\n\\newcommand{\\bra}[1]{\\langle #1 \\rvert}\n\\newcommand{\\ket}[1]{\\lvert #1 \\rangle}\n\\newcommand{\\bret}[2]{\\langle{#1}|{#2}\\rangle}\n\\newcommand{\\dbret}[3]{\\langle{#1}|{#2}|{#3}\\rangle}\n\\newcommand{\\kret}[2]{\\ket{#1}\\bra{#2}}\n\\newcommand{\\kera}[1]{\\kret{#1}{#1}}\n\\newcommand{\\Example}[1]{{\\bf Example #1}:}\n\n\\def\\X{\\mathcal{X}}\n\\def\\Y{\\mathcal{Y}}\n\\def\\Z{\\mathcal{Z}}\n\\def\\W{\\mathcal{W}}\n\\def\\A{\\mathcal{A}}\n\\def\\B{\\mathcal{B}}\n\\def\\V{\\mathcal{V}}\n\\def\\U{\\mathcal{U}}\n\\def\\C{\\mathcal{C}}\n\\def\\D{\\mathcal{D}}\n\\def\\E{\\mathcal{E}}\n\\def\\F{\\mathcal{F}}\n\\def\\M{\\mathcal{M}}\n\\def\\R{\\mathcal{R}}\n\\def\\P{\\mathcal{P}}\n\\def\\Q{\\mathcal{Q}}\n\\def\\S{\\mathcal{S}}\n\\def\\T{\\mathcal{T}}\n\\def\\K{\\mathcal{K}}\n\\def\\L{\\mathcal{L}}\n\n\\def\\fill{   \\hfill}\n\n%=============Main Doc=================%\n\\begin{document}\n%-----Specs: change accordingly--------%\n\\def\\lecdate{May 25, 2017} % put lecture date here\n\\def\\scribe{Scribe: Enis K. Inan} % put your name here\n\\def\\lecnum{16} % change the lecture number\n\n\\lecture{\\lecnum}{\\lecdate}{\\prof}{\\scribe}%\n\n\\begin{center}\n{\\textsc{Version: \\today}}  \n\\end{center}\n\n\n\\noindent Last time we talked about quantum complexity classes. Recall\nthat we used the quantum circuit model (1) as the basis for doing our\nquantum computations instead of quantum Turing machines (2). Both\nmodels are equivalent, it's just easier to use (1) instead of\n(2). With (1), we have a collection of quantum circuits\n$Q = \\set{Q_x \\: | \\: x \\in \\set{0, 1}^*}$, i.e. $Q$ contains one\nquantum circuit for each string $x$. We say that $Q$ is\n\\emph{polynomial-time uniform} or \\emph{polynomial-time generated} if\nthere exists a polynomial algorithm that outputs a classical\ndescription of $Q_x$ given input $x$. We then proceeded to state some\nimportant complexity classes.\n\nOf interest is $\\bqp$, which states that a promise problem\n$A \\in \\bqp$ if there exists a collection of quantum circuits $Q$ such\nthat for all $Q_x \\in Q$ where $x$ is a valid input,\n$\\abs{Q_x} = \\poly(\\abs{x})$, i.e. the circuit $Q_x$ is polynomial in\nthe size of the input,\n\\begin{itemize}\n\\item If $x \\in A_{y}$, then $\\dbret{1}{Q_x}{1} \\geq 2/3$.\n\n\\item If $x \\in A_{n}$, then $\\dbret{1}{Q_x}{1} \\leq 1/3$\n\\end{itemize}\nwhere the fancy $\\dbret{1}{Q_x}{1}$ is understood as follows. When we run $Q_x$, we do not start with any zeros. When $Q_x$ finishes its computation, we will end up with a 1-qubit mixed state (ignoring ancilla qubits) that we also denote as $Q_x$ since the circuit $Q_x$ produces it. Then $\\dbret{1}{Q_x}{1}$ is the probability that $Q_x$ will measure the outcome $1$, i.e. output that input $x$ is a YES instance. Thus, Case 1 is saying that if $x$ is a YES instance, then $Q_x$ should indicate it is so with at least $2/3$ probability. Case 2 states that if $x$ is a NO instance, then $Q_x$ should give a false-positive YES result with \\emph{at-most} $1/3$ probability. Note that Cases 1 and 2 are known as the \\emph{completeness} and \\emph{soundness} conditions, respectively.\n\n\\fill\n\n\\noindent \\Example{1} Integer factorization is in $\\bqp$.\n\\begin{itemize}\n\\item {\\bf Input:} $(N, k)$, $2 \\leq k \\leq N$\n\\item {\\bf Output:} Whether there exists a proper factorization of $N$ where each factor $a \\in \\set{2, \\dots, k}$. Using Shor's algorithm, we can answer this question in $O(\\poly(\\log(N)))$ time.\n\\end{itemize}\n\n\\fill\n\n\\noindent Note that $\\p \\subseteq \\bqp$ and $\\bpp \\subseteq \\bqp$, but we do not know if $\\bqp \\subseteq \\bpp$, i.e. if $\\bqp = \\bpp$. We know the first two statements are true because we have showed in the beginning of class that we can turn \\emph{any} classical circuit into a quantum circuit in a polynomial number of steps with a polynomial change in size. \n\n%==============================%\n\\section{$\\bqp \\in \\exp$}\n%==============================%\nWe will now prove that $\\bqp \\in \\exp$. Intuitively, this containment is formalizing the notion that a classical computer can simulate a quantum computer in exponential time. The proof idea is to take a quantum circuit $Q_x$ for an input $x$ that outputs $1$ with probability $p_1$ and $0$ with probability $p_0$ and create a classical algorithm which simulates it, i.e., given an input $x$, it outputs 1 with probability $\\widetilde{p_1}$ and 0 with probability $\\widetilde{p_0}$ such that $p_1 \\approx \\widetilde{p_1}$ and $p_0 \\approx \\widetilde{p_0}$. Remember that a classical algorithm and a classical circuit are the same thing, so what we really want to do is to create a classical circuit that sufficiently approximates our quantum circuit.\n\n\\fill\n\n\\noindent Now we proceed to the proof. First, note that \\emph{any} quantum circuit can be approximated by a combination of Toffoli and Hadamard gates. As a brief recap, here's what these gates do:\n\\begin{itemize}\n\\item $\\h$ acts on a single qubit, and induces the following mappings:\n\\begin{equation*}\n\\begin{split}\n\\h\\ket{0} &\\rightarrow \\frac{1}{\\sqrt{2}}\\left(\\ket{0} + \\ket{1}\\right) \\\\\n\\h\\ket{1} &\\rightarrow \\frac{1}{\\sqrt{2}}\\left(\\ket{0} - \\ket{1}\\right)\n\\end{split}\n\\end{equation*}\n\n\\item $\\tf$ acts on three qubits. Given a three qubit state $\\ket{abc}$, we get the following mapping:\n\\begin{equation*}\n\\tf\\ket{abc} \\rightarrow \\ket{ab}\\ket{(a \\land b) \\oplus c}\n\\end{equation*} \nwhere the first two qubits do not change while the last qubit gets flipped if the first two qubits are both 1.\n\\end{itemize}\n\n\\fill\n\n\\noindent The first thing we do is reconstruct $Q_x$ so that it consists of \\emph{only} $\\h$ and $\\tf$ gates that are sequenced one after the other. For example if we want to apply $H^{\\otimes 2}$, we break it up into the equivalent sequence $(H \\otimes I)(I \\otimes H)$. This can be done in polynomial time. From here on out when we reference $Q_x$, assume that it is the reconstructed version. Now pretend we are a classical computer trying to simulate $Q_x$ starting with an initial input $\\ket{\\psi_0}$. We go through $Q_x$ one gate at a time. If we encounter an $\\h_x$ gate, where $\\h_x$ is applying $\\h$ to the $x^{th}$ qubit, then we branch off two computation paths: one with the $x^{th}$ qubit set to 0, and the other with the $x^{th}$ qubit set to 1, keeping track of the resulting amplitudes for each. This makes sense upon examining our description of $\\h$ above, where we see that it turns a classical bit to a superposition -- forking off two distinct computational paths \\emph{captures} that superposition in the classical world. If we encounter a $\\tf_{xyz}$ gate, where $\\tf_{xyz}$ is applying $\\tf$ to the $x^{th}$, $y^{th}$ and $z^{th}$ qubits, then we follow our description of $\\tf$ above: leave $x$ and $y$ alone but flip $z$ iff $x \\land y = 1$. With $\\tf$ then, we see that we do not need to fork any additional paths as it does not create a new superposition. Thus our simulation of $Q_x$ is really maintaining a \\emph{tree} where the nodes represent intermediate stages in the computation. Assume that we have $m$ gates in our circuit. Then each level $i$ of the tree represents the resulting superposition after applying the first $i$ gates, where $0 \\leq i \\leq m$. The nodes of the tree are the components of the superposition at their corresponding level. Thus for each node, we would like to maintain two pieces of information: the binary representation of that specific component, and its corresponding amplitude. In fact because we are applying only $\\h$ and $\\tf$ gates, every node will have the same amplitude as any other node on that level; this amplitude is $\\frac{1}{\\sqrt{2^m}}$ where $m$ is the number of nodes on that level. The leaves of our tree will contain the final superposition. Thus, a path from the root to \\emph{a} leaf represents \\emph{one} possible outcome assuming that we measure all of our qubits. Because we are using $\\tf$ and $\\h$ gates, it is possible to have two \\emph{different} computation paths that produce the same final result (i.e. nodes on the same level can have the same superposition component). The exponential time complexity comes from the size of our tree, where we need to compute each superposition component in the internal nodes  \n\n\\fill\n\n\\noindent \\Example{2} Say our circuit consists of the gates $H_1$, $H_2$, $\\tf$, and $H_1$ in that order. Assume that we start with an initial state of $\\ket{000}$. Then our resulting computation tree will be: %NOTE: I couldn't create the tree from lecture, for some reason I was getting a ''no driver specified at all'' error when using qtree. So I have put this handwritten tree instead:\n\n\\includegraphics[scale = 0.7]{tree}\n\n\\fill\n\n\\noindent Notice in our tree that we have two possible computation paths that result in $000$ as the final outcome. These are $000, 000, 000, 000, 000$ and $000, 100, 100, 100, 000$.\n\n\\fill\n\n\\noindent Assume without any loss of generality that the first qubit in our final superposition contains our desired output, i.e. that $\\dbret{1}{Q_x}{1} \\approx \\widetilde{p_1} = \\pr(\\text{First qubit} = 1)$ -- the remaining qubits are ancilla qubits. Then, we see that $\\widetilde{p_1}$ is just the absolute value squared of the sum of the amplitudes of all the qubit-leaves where the first qubit is $1$. Because each path from root to leaf is unique, we can represent our final superposition at the leaves using the individual paths as our orthonormal basis. Let $P$ be the set of computation paths. Then our superposition is expressed as:\n\\begin{equation} \\label{eq:bqp-psp}\n\\sum_{p \\in P} \\left(\\frac{1}{\\sqrt{2}}\\right)^{\\abs{P}} \\sign(p) \\ket{p}\n\\end{equation}\nwhere $\\sign(p)$ is the signum function that indicates if the final superposition component upon traversing the path $p$ has negative or positive amplitude. Let $\\alpha_x$ be the amplitude that represents outcome $x$ where $x \\in \\set{0, 1}^m$, with $m$ being the number of qubits at our leaf nodes. Then we see that our final superposition is also:\n\\begin{equation} \\label{eq:bqp-sp}\n\\sum_{x \\in \\set{0, 1}^m} \\alpha_x \\ket{x}\n\\end{equation}\nwhere\n\\begin{equation} \\label{eq:bqp-alph}\n\\alpha_x =  \n\\sum_{p \\in P \\text{ s.t. } p = x}  \\left(\\frac{1}{\\sqrt{2}}\\right)^{\\abs{P}} \\sign(p)\n\\end{equation}\nwhere $p = x$ means that the path $p$ leads to the outcome $x$ -- remember that multiple paths can have the same outcome, which is why Eqn. \\ref{eq:bqp-alph} is a summation. Thus, we see that we can calculate $\\widetilde{p_1}$ as:\n\\begin{equation} \\label{eq:bqp-p1tilde}\n\\widetilde{p_1} = \\abs{\\sum_{x \\text{ s.t. } x_1 = 1} \\alpha_x}^2\n\\end{equation}\nwhere $x \\in \\set{0, 1}^m$ and $x_1 = 1$ indicates that $x$'s first qubit is $1$. Equation \\ref{eq:bqp-p1tilde} is mathematically expressing what we said earlier.\n\n\\fill\n\n\\noindent Because new computational paths are only forked when we apply $\\h$, our worst-case complexity for the size of our tree is when $Q_x$ has $h$ Hadamard gates. Here $|P| = 2^h$ so that there are $2^h$ leaves in the tree and hence $2^h$ possible paths, resulting in an exponential worst-case time. Thus, $\\bqp \\subseteq \\exp$.\n\n\\fill\n\n\\noindent In fact if we reuse the space when calculating the amplitudes, it turns out that we only need polynomial space to calculate $\\widetilde{p_1}$ so that $\\bqp \\subseteq \\pspace$. We can adapt the proof even further to show that $\\bqp \\subseteq \\pp$.\n\n%==============================%\n\\section{$\\qma$}\n%==============================%\nWe will now present the quantum analogue of $\\np$, $\\qma$. We use $\\ma$ instead of $\\np$ because the quantum world is random. Like $\\np$ for a classical computer, $\\qma$ represents problems that are efficiently verifiable by a quantum computer.\n\n\\fill\n\n\\noindent We say that a promise $A \\in \\qma$ if there exists a collection of quantum circuits $Q$ such that for all $Q_x \\in Q$ where $x$ is a valid input, $\\abs{Q_x} = \\poly(\\abs{x})$,\n\\begin{itemize}\n\\item \\emph{Completeness:} If $x \\in A_y$ then there exists a state $\\rho$ on $\\poly(\\abs{x})$ qubits such that\n\\begin{equation*}\n\\dbret{1}{Q_x(\\rho)}{1} \\geq \\frac{2}{3}\n\\end{equation*}\nWe say that $\\rho$ is a ``quantum certificate'' which verifies that $x \\in A_y$.\n\n\\item \\emph{Soundness:} If $x \\in A_n$ then for all states $\\rho$ on $\\poly(\\abs{x})$ qubits:\n\\begin{equation*}\n\\dbret{1}{Q_x(\\rho)}{1} \\leq \\frac{1}{3}\n\\end{equation*}\n\\end{itemize}\nWe assume that in $Q_x$, the first qubit yields the answer to our decision problem.\n\n\\fill\n\n\\noindent Here are some things we can say about $\\qma$. \n\\begin{enumerate}\n\\item $\\bqp \\subseteq \\qma$ and $\\bpp \\subseteq \\qma$ since we do not need a certificate to decide a $\\bqp$ or $\\bpp$ instance -- we can just directly solve the problem by running $x$ through our circuit $Q_x$.\n\n\\item $\\np \\subseteq \\ma \\subseteq \\qma$. We know why $\\np \\subseteq \\ma$. $\\ma \\subseteq \\qma$ for the same reason as $\\bpp \\subseteq \\bqp$ -- we can create a polynomial-size reversible quantum circuit from any classical circuit, and encode any classical certificate as a corresponding quantum certificate.\n\n\\item $\\qma \\subseteq \\pp$\n\\end{enumerate}\nFor more information on all the complexity classes out there, see the \\href{https://complexityzoo.uwaterloo.ca/Complexity_Zoo}{Complexity Zoo}.\n\n%==============================%\n\\section{Interactive Proofs}\n%==============================%\nThere is a recurrent pattern in the complexity classes $\\np$, $\\ma$ and $\\qma$. In each case, we have an all-powerful ``prover'' (think computing machine) that prepares a certificate $c$ which we pass along to a verifier. $c$ represents a possible ``solution'' candidate to a problem instance encoded by some input $x$. $A$ is the general category that these problems fall under, where $A_y$ represents instances that do have a solution and $A_n$ those instances that don't. For example if $A$ is integer factorization, then $x$ is the encoded input $(N, k)$. If $x$ \\emph{has} a solution, i.e. if $x \\in A_y$, then our verifier will accept any $c$ that \\emph{is} a solution -- we don't care what it does for those $c$s that don't correspond to valid solutions. However if our problem does not have a solution, i.e. if $x \\in A_n$, then our verifier will reject \\emph{all} certificates $c$ -- it cannot be fooled by the prover into accepting a solution candidate for an unsolvable problem. Our verifier must makes its decision in polynomial time with respect to the input size, represented by the sizes of $x$ and $c$. What we have just now (informally) described is the complexity class $\\np$. For $\\ma$ and $\\qma$, our verifier can make mistakes; the probability that it does so is bounded. In $\\qma$ for example, we require our verifier to accept a solution certificate $c$ for $x \\in A_y$ with at least $2/3$ probability (1), while ensuring that any certificate $c$ for an $x \\in A_n$ is accepted with probability at most $1/3$ (2). The mistake in (1) is rejecting a solution certificate $c$ while in (2), it is accepting any certificate $c$. In both cases, the mistake probability is bounded above by $1/3$. \n\n\\fill\n\n\\noindent We can generalize the interaction between the prover and the verifier by letting the prover send multiple certificates (messages) instead of a single certificate to the verifier, which is still required to make its decision in polynomial time. Here, we say that the prover and the verifier form an \\emph{interactive proof system}. The complexity class $\\ip$ represents those problems $A$ that have an interactive proof system; $\\qip$ is similar to $\\ip$ except that the prover can send quantum messages to the verifier in addition to classical ones. From our preceding discussion, $\\np$ and $\\ma$ are special cases of $\\ip$ while $\\qma$ is a special case of $\\qip$. Several breakthrough results have shown that $\\ip = \\qip = \\pspace$.\n\n\\fill\n\n\\noindent {\\bf Aside:} You might be wondering why we coined the term $\\ma$. The answer is from the tale of King Arthur. There, Merlin was an all-powerful wizard while Arthur was an ordinary mortal. In $\\ip$, we have an ``all-powerful'' prover (Merlin) and a ``puny'' verifier (Arthur) -- putting Merlin and Arthur together, we get the name $\\ma$.\n\n%==============================%\n\\section{Group Non-membership}\n%==============================%\nWe now present the group non-membership (GNM) problem. This is a problem that we know is in $\\qma$ but not if it is in $\\ma$. Experts think that it probably isn't. Here is our problem statement.\n\\begin{itemize}\n\\item {\\bf Input:} $\\left<g_1, \\dots, g_k\\right> = H \\leq G$ and $x \\in G$\n\\item {\\bf Output:} If $x \\notin H$, then YES. Otherwise, NO.\n\\end{itemize}\nwhere $g_1, \\dots, g_k$ are the generators of some subgroup $H$ of a group $G$ -- remember from group theory that we can specify any group $G$ using only its generators. Informally, given a subgroup $H$ and an element $x$ from the subsuming group $G$, $\\gnm$ asks if $x \\notin  H$. We will now prove that $\\gnm \\in \\qma$ by constructing our verifier.\n\n\\fill\n\n\\noindent We will represent the subgroup $H$ as a uniform superposition over its group elements, defined as:\n\\begin{equation} \\label{eq:gnm-h}\n\\ket{H} = \\frac{1}{\\sqrt{\\abs{H}}} \\sum_{h \\in H} \\ket{h}\n\\end{equation}\nNow consider $\\ket{H_x}$ defined below:\n\\begin{equation} \\label{eq:gnm-hx}\n\\ket{H_x} = \\frac{1}{\\sqrt{\\abs{H}}} \\sum_{h \\in H} \\ket{h\\bullet x}\n\\end{equation}\nwhere $H_x = \\set{h_1x, h_2x, \\dots} = Hx$ is a coset of $H$ in $G$. If $x \\in H$, then we know from group theory that $H_x = H$ implying that $\\ket{H_x} = \\ket{H}$. Otherwise if $x \\notin H_x$, then $H_x \\cap H = \\emptyset$. In quantum terms, this means that $\\ket{H_x}$ is orthogonal to $\\ket{H}$, i.e. that $\\bret{H_x}{H} = 0$. This makes sense since here, $H_x$ and $H$ are independent sets and orthogonality captures independence. Now consider the following circuit that will form our verifier:\n\n\\centerline{\n\t\\Qcircuit @C=1em @R=0.75em {\n\t\t\\lstick{\\ket{0}} & \\gate{\\h} & \\ctrl{1} & \\gate{\\h} & \\meter \\\\\n\t\t\\lstick{\\ket{H}} & \\qw & \\gate{M_x} & \\qw & \\qw\n\t}\n}\n\nwhere $M_x$ is the controlled unitary that's defined as follows:\n\\begin{equation*} \\label{eq:gnm-mx}\n\\begin{split}\nM_x\\left(\\ket{0}\\ket{H}\\right) &\\rightarrow \\ket{0}\\ket{H} \\\\\nM_x\\left(\\ket{1}\\ket{H}\\right) &\\rightarrow \\ket{1}\\ket{H_x}\n\\end{split}\n\\end{equation*}\nLet's see what this circuit does starting with the initial state $\\ket{0}\\ket{H}$. After applying the first Hadamard gate to the first qubit, we get:\n\\begin{equation*}\n\\frac{1}{\\sqrt{2}}(\\ket{0}\\ket{H} + \\ket{1}\\ket{H})\n\\end{equation*}\nApplying $M_x$, we get:\n\\begin{equation*}\n\\frac{1}{\\sqrt{2}}(\\ket{0}\\ket{H} + \\ket{1}\\ket{H_x})\n\\end{equation*}\nFinally applying the last Hadamard gate to the first qubit, we get:\n\\begin{equation} \\label{eq:gnm-final}\n\\frac{1}{2}\n  \\ket{0}\\left(\\ket{H} + \\ket{H_x}\\right)\n+ \\frac{1}{2}\n\\ket{1}\\left(\\ket{H} - \\ket{H_x}\\right)\n\\end{equation}\nWe now have two cases to consider:\n\\begin{enumerate}\n\\item $x \\in H$ so that $H_x = H$. Here, Eqn. \\ref{eq:gnm-final} reduces to $\\ket{0}\\ket{H}$ so that we will measure $0$ with certainty.\n\n\\item $x \\notin H$. Then examining Eqn. \\ref{eq:gnm-final}, we see that there is a $1/2$ chance of measuring $0$, and a $1/2$ chance of measuring $1$.\n\\end{enumerate}\nLooking at Cases 1 and 2, we will say that our verifier outputs YES when we measure a $1$ on the first qubit, otherwise it outputs NO. Here's why we do this. When $x \\in H$ and our prover gives us $\\ket{H}$ as a certificate, we know for sure that our circuit will measure $0$ from Case 1 so we output NO to correctly reject $\\ket{H}$ -- the case when the prover gives us a certificate that isn't $\\ket{H}$ will be considered shortly.\n\n\\fill\n\n\\noindent Consider the \\emph{completeness} requirement. Here, when $x \\notin H$ and we are given $\\ket{H}$ as our certificate, we want our verifier to output YES with probability $p \\geq 2/3$. Unfortunately from Case 2, $p = 1/2$ so our verifier is not good enough. However, all is not lost. We can tweak our verifier to instead run the circuit at most $t$ times. This is OK since our prover is all powerful, so it can generate as many copies of $\\ket{H}$ as we need. This time, our verifier will output YES as soon as it measures a $1$. Now, our probability $p$ is the chance that we measure $1$ \\emph{at least} once within $t$ trials, which we can calculate using a binomial distribution as:\n\\begin{equation*}\np = 1 - \\left(\\frac{1}{2}\\right)^t\n\\end{equation*} \nSetting $t = 2$ will yield $p = 3/4$, which is good enough.\n\n\\fill\n\n\\noindent Now we consider the \\emph{soundness} requirement, using our tweaked verifier from above. Here we know that $x \\in H$. We must show that our verifier will output NO for \\emph{any} certificate given to it by the prover with probability \\emph{at least} $2/3$ (complement of outputting YES with probability at most 1/3). We have two cases to consider here. If the prover gives us $\\ket{H}$ as the certificate, then Case 1 from our analysis shows that we will always measure a $0$ in all $t$ iterations of running our circuit so that we correctly output NO with certainty. However if the prover gives us a certificate $c$ that isn't $\\ket{H}$, we cannot pass $c$ into our verifier as-is because our circuit is only defined for $c = \\ket{H}$. But we can construct a new circuit $T$ that does the following. If $c = \\ket{H}$, it will run our verifier as described in the completeness proof above. Otherwise, $T$ will output NO. Thus, $T$ becomes our new verifier. The question now is how to test that $c = \\ket{H}$. We cannot just check the generators of $H$ because the check is not always guaranteed to complete in polynomial time. \n\n\\fill\n\n\\noindent What we can do, however, is use a slightly modified version of the main circuit as a part of our testing procedure. This circuit is below:\n\n\\centerline{\n\t\\Qcircuit @C=1em @R=0.75em {\n\t\t\\lstick{\\ket{0}} & \\gate{\\h} & \\ctrl{1} & \\gate{\\h} & \\meter \\\\\n\t\t\\lstick{c} & \\qw & \\gate{M_z} & \\qw & \\qw\n\t}\n}\n\n\\noindent where $M_z$ is the same as $M_x$ except that $z$ is a randomly chosen element of $H$, and we compute the coset $cz$ instead of $Hz$. From Case 1 above, if $c = \\ket{H}$ then we will measure $0$ with certainty. Thus when we see a $1$, we know that $c \\ne \\ket{H}$ so that our test can output NO to correctly reject $c$. To ensure that our test works with the required probability for rejection, we can repeat our testing procedure several times using different, random elements of $z$ -- remember that our prover is all-powerful, so it can generate as many copies of $c$ as we need to do this. For more details on the analysis for this case, see \\href{https://www.cs.cmu.edu/~odonnell/quantum15/lecture24.pdf}{these lectures notes}.\n\n\\fill\n\n\\noindent The above argument establishes that our new verifier exhibits the correct behavior for the soundness case; it is also polynomial in the size of the input. Further, our completeness argument still holds with this new verifier because the testing procedure will always measure $0$ when $c = \\ket{H}$ so that the probability of outputting YES still depends only on the main circuit.\n\n\\fill\n\n\\noindent This completes our proof that $\\gnm \\in \\qma$.\n\n\n\\end{document}", "meta": {"hexsha": "5973221660e22062d690425a8dbb308545b8f305", "size": 25457, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "teaching/s17_4510_qc/170525_ei_lec16.tex", "max_stars_repo_name": "fangsonghub/fangsonghub.github.io", "max_stars_repo_head_hexsha": "31a42b297a4644b307b97acd293d9111e567f5c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "teaching/s17_4510_qc/170525_ei_lec16.tex", "max_issues_repo_name": "fangsonghub/fangsonghub.github.io", "max_issues_repo_head_hexsha": "31a42b297a4644b307b97acd293d9111e567f5c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-05-06T23:19:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-06T23:19:12.000Z", "max_forks_repo_path": "teaching/s17_4510_qc/170525_ei_lec16.tex", "max_forks_repo_name": "fangsonghub/fangsonghub.github.io", "max_forks_repo_head_hexsha": "31a42b297a4644b307b97acd293d9111e567f5c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 69.5546448087, "max_line_length": 2711, "alphanum_fraction": 0.7064461641, "num_tokens": 7719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.32823308122685046}}
{"text": "\\documentclass[twocolumn,fleqn,layout]{article}\n\\usepackage{alltt}\n\n\\pagestyle{plain}\n\\flushbottom\n\\sloppy\n\\begin{document}\n\n\\input{macros}\n\\sloppy\n\n\n\n\\twocolumn[{\\scriptsize \\parbox{100mm}{Preprint of a paper\nto appear in the Proceedings of the 1991 International Tutorial\nand Workshop on the HOL Theorem Proving System, 27--30 August 1991,\nDavis California (IEEE Computer Society Press).}}\\vskip10mm\n\\begin{center}\n{\\Large\\bf A Package for Inductive Relation Definitions in HOL}\\\\\n\\vskip24pt\nT.\\ F.\\ Melham\\\\\n\\vskip12pt\nUniversity of Cambridge Computer Laboratory\\\\\nNew Museums Site, Pembroke Street\\\\\nCambridge, CB2 3QG, England.\\\\\n\\mbox{}\\\\\n\\vskip3mm\n\\end{center}]\n\n\\subsection*{\\centering Abstract}\n\n{\\it\\sloppy This paper describes a set of theorem proving tools based on a new\nderived principle of definition in HOL, namely the introduction of relations\ninductively defined by a set of rules.  Such inductive definitions abound in\ncomputer science. Example application areas \\mbox{include} reasoning about\nstructured operational semantics, type judgements, transition relations for\nprocess algebras, \\mbox{reduction} relations, and compositional proof systems.\nThe package described in this paper automates the derivation of certain\ninductive definitions involved in these applications and provides the basic\ntools needed for reasoning about the relations introduced by them.}\n\n\\vskip12pt\n\\section{Introduction}\n\nThe HOL user community has a strong tradition of taking a purely {\\it\ndefinitional\\/} approach to using higher order logic. That is, the syntax of\nthe logic is extended with new notation not simply by postulating axioms to\ngive meaning to it, but rather by defining it in terms of existing expressions\nof the logic that already have the required semantics.  The advantage of this\napproach, as opposed to the axiomatic method, is that each of the primitive\nrules of definition in the {\\small HOL} logic---namely, constant definition,\nconstant specification, and type definition---is guaranteed to preserve\nconsistency.  The disadvantage is that these rules admit only\n\\mbox{definitions} that satisfy certain very restrictive rules of formation.\nDefinitions expressed in any other form must always be justified formally by\nderiving them from equivalent, but possibly rather complex, primitive\ndefinitions.\n\nThe {\\small ML} metalanguage allows users to implement derived inference rules\nin the {\\small HOL} system and thus provides a facility for automating proofs\nthat justify derived rules of definition.  For example, recursive\n\\mbox{definitions} are not admitted by the primitive rules of definition of the\n{\\small HOL} logic.  But certain recursive type definitions and function\ndefinitions are supported in the system by derived inference rules written in\n{\\small ML}~\\cite{description,melham}.  The details of the primitive\ndefinitions that underlie these rules are hidden from the user, and their\n{\\small ML} implementations are highly optimized. So these \\mbox{derived}\nprinciples of definition may simply be regarded as primitive by most users of\nthe system.\n\nThis paper describes a set of theorem-proving tools based on a new derived\nprinciple of definition in {\\small HOL} for defining relations inductively by a\nset of rules. \\mbox{Sections~\\ref{ind-defs}} and~\\ref{in-logic} give a general\nintroduction to the class of inductive definitions handled by the package and\nexplain the logical basis for these definitions.  The remaining sections\ndescribe the {\\small ML} functions provided by the package and briefly mention\nsome applications for which the package can be used.\n\n\\section{Inductive definitions}\\label{ind-defs}\n\nThe following is a simple but typical example of a relation defined inductively\nby a set of rules. (This example is taken from~\\cite{pitts}.) Let $R \\subseteq\nA \\times A$ be a binary relation on a set $A$.  The reflexive-transitive\nclosure of $R$ can be defined to be the least relation $R^{*} \\subseteq A\n\\times A$ for which the following deduction rules hold.\n\n\\medskip\n\n\\[ \\begin{array}[t]{@{}l}\n   \\hbox{{\\small\\bf R}\\bf 1}\\quad\\Rule{}{R^{*}(x,y)}\\;\\; R(x,y) \\\\[6mm]\n   \\hbox{{\\small\\bf R}\\bf 2}\\quad\\Rule{}{R^{*}(x,x)}\\\\[8mm]\n   \\hbox{{\\small\\bf R}\\bf 3}\\quad\\Rule{R^{*}(x,z)\\qquad R^{*}(z,y)}\n         {R^{*}(x,y)}\n\\end{array} \\]\n\n\\medskip\n\n\\noindent These rules state precisely the properties required of the\nreflexive-transitive closure of the relation $R$.  Rule {{\\small\\bf R}\\bf 1}\nstates that it must contain at least all the values in $R$; rule {{\\small\\bf\nR}\\bf 2} states that it must be reflexive; and rule {{\\small\\bf R}\\bf 3} states\nthat it must be transitive.  The reflexive-transitive closure $R^{*}$ may\ntherefore simply be {\\it defined\\/} to be the least relation that satisfies\nthese conditions.  It then follows simply by definition that the rules\n{{\\small\\bf R}\\bf 1}, {{\\small\\bf R}\\bf 2} and {{\\small\\bf R}\\bf 3} are in fact\nsatisfied by $R^{*}$.  Moreover, it follows immediately that $R^{*}$ is a\nsubset of any other relation that satisfies these rules, since $R^{*}$ is\ndefined to be the {\\it least\\/} such relation.  This means that $R^{*}$\ncontains only those pairs of values that it must contain by virtue of\nsatisfying the rules. As will be discussed below, this property gives rise to\nan induction principle for reasoning about the relation $R^{*}$.\n\nThe definition given above is valid because the rules {{\\small\\bf R}\\bf 1},\n{{\\small\\bf R}\\bf 2}, and {{\\small\\bf R}\\bf 3} make only positive statements\nabout the elements of $R^{*}$.  This guarantees that the least relation\nsatisfying these rules does exist.  In particular, if the rules have this form,\nthen one can show that the intersection of any set of relations that satisfy\nthe rules also satisfies the rules.  Moreover, at least one binary relation\nsatisfies the rules, namely the maximal relation $A \\times A$. The `least' or\nsmallest relation that satisfies the rules may therefore legitimately be\ndefined to be the intersection of all such relations.\n\nIn general, an inductive definition of an $n$-place \\mbox{relation} $R$\nconsists of a set of rules of the form:\n\n\\smallskip\n\n\\[ \\Rule{R(t_1^1,\\dots,t_n^1) \\quad \\cdots \\quad R(t_1^i,\\dots,t_n^i)}\n        {R(t_1,\\dots,t_n)}\\;\\;C_1\\:\\cdots\\:C_j \\]\n\n\\smallskip\n\n\\noindent The terms above the line are the {\\it premisses\\/} of the rule, each\nof which makes a positive assertion of membership in the relation $R$.  The\nterm below the line, called the {\\it conclusion\\/} of the rule, likewise\nasserts membership in $R$. The terms $C_1$,\\dots,$C_j$ are {\\it side\nconditions\\/} on the rule; these may be arbitrary propositions not involving\nthe relation $R$ being defined. A relation $R$ is {\\it closed\\/} under such a\nrule if whenever the premisses and side conditions hold, the conclusion also\nholds.  The relation {\\it inductively defined\\/} by a collection of such rules\nis the least relation closed under all the rules.\n\n\\subsection{Rule induction}\\label{rule-ind}\n\nBy virtue of its definition as the {\\it least\\/} relation closed under a set of\nrules, every inductively defined relation comes with an associated induction\nprinciple.  This principle of {\\it rule induction\\/} is essential for many\nproofs involving such relations. (The term `rule induction' was coined by Glynn\nWinskel in~\\cite{winskel}).\n\nThe principle of rule induction for an inductively defined relation may be\nstated briefly as follows. Let $R$ be an $n$-place relation inductively defined\nby a set of rules, and suppose we wish to show that every element in $R$ has a\ncertain property $P$:\n\n{\\samepage\n\\begin{equation}\\label{fact1}\n\\hbox{\\rm\nif}\\;\\;R(x_1,\\dots,x_n)\\;\\;\\hbox{then}\\;\\;P[x_1,\\dots,x_n]\n\\end{equation}\n\n\\noindent Since $R$ is} \\pagebreak[3] the least relation closed under the\nrules, any relation $S$ which is also closed under the rules has the property\nthat $R \\subseteq S$.  Now, let\n\n\\[S = \\{(x_1,\\dots,x_n) \\mid P[x_1,\\dots,x_n]\\}\\]\n\n\\noindent Then to prove the desired property of $R$, it suffices to show that\nthe relation $S$ is closed under the rules that define $R$. For if the relation\n$S$ in fact is closed under the rules, then we have that $R \\subseteq S$ and\ntherefore that every element of $R$ has the defining property of $S$---i.e.\\\nstatement~(\\ref{fact1}) holds of the relation $R$.\n\nFor the relation $R^{*}$ defined above, the principle of rule induction is\nstated as follows. In order to prove that a property $P[x,y]$ holds for all\n$x$ and $y$ for which $R^{*}(x,y)$, it suffices to show that:\n\n\\begin{itemize}\n\n\\item for all $x$ and $y$, $R(x,y)$ implies $P[x,y]$\n\n\\item for all $x$, $P[x,x]$\n\n\\item for all $x$, $y$, and $z$, $P[x,z]$ and $P[z,y]$ imply $P[x,y]$\n\n\\end{itemize}\n\n\\noindent This is an inductive form of argument: if the property $P$ holds in\nthe `base cases' corresponding to rules {{\\small\\bf R}\\bf 1} and {{\\small\\bf\nR}\\bf 2}, and if $P$ is preserved by the rule {{\\small\\bf R}\\bf 3} (the `step\ncase' of the induction), then every pair in $R^{*}$ has the property $P$.  A\nsimilar induction principle holds for every relation inductively defined by a\nset of rules.\n\n\\section{Inductive definitions in logic}\\label{in-logic}\n\n\nInductive definitions are based on the concept of a relation being closed under\na set of rules.  Since rules are essentially implications---{\\it if\\/} the\npremisses and side conditions hold, {\\it then\\/} the conclusion holds---it is\nstraightforward to express this concept in logic.\n\nConsider, for example, the rules given above for reflexive-transitive closure.\nLet $R : \\alpha{\\rightarrow}\\alpha{\\rightarrow}bool$ be a fixed but arbitrary\n relation on $\\alpha$. (Here, a relation is represented by a curried function;\nbut we shall continue to speak loosely of a pair of values $x$ and $y$ as being\n`in' the relation $R$ when $R\\;x\\;y$ holds.)  The following formula then\nasserts that a relation $P : \\alpha{\\rightarrow}\\alpha{\\rightarrow}bool$ is\nclosed under the rules defining the reflexive-transitive closure of $R$:\n\n\\smallskip\n\\[\\begin{array}[t]{@{}l}\n (\\forall x\\:y.\\:R\\;x\\;y \\supset P\\;x\\;y)\\; \\wedge \\\\\n (\\forall x.\\:P\\;x\\;x)\\; \\wedge \\\\\n (\\forall x\\:y.\\:(\\exists z.\\:P\\;x\\;z \\wedge P\\;z\\;y) \\supset P\\;x\\;y)\n\\end{array}\\]\n\\smallskip\n\n\\noindent Each rule is expressed by a quantified implication of its conclusion\nby the conjunction of its premisses and side conditions.  A rule with no side\nconditions or premisses is just represented by a universally quantified\nassertion of its conclusion. Closure of a relation under any set of rules of\nthe form discussed above can be expressed in logic in a similar way.\n\nUsing this method of expressing the notion of \\mbox{closure} under a set of\nrules, one can define the {\\it least\\/} relation closed under a set of rules\nsimply by taking the intersection of all such relations.  For example, a\nfunction\n\n\\[ {\\sf Rtc} : (\\alpha{\\rightarrow}\\alpha{\\rightarrow}bool) \\rightarrow\n(\\alpha{\\rightarrow}\\alpha{\\rightarrow}bool) \\]\n\n\\noindent that maps an arbitrary relation $R :\n\\alpha{\\rightarrow}\\alpha{\\rightarrow}bool$ to its reflexive-transitive closure\n${\\sf Rtc}\\;R$ can be defined in the {\\small HOL} logic by the constant\ndefinition:\n\n\\[\\vdash \\begin{array}[t]{@{}l}\n\\forall R\\:x\\:y.\\:{\\sf Rtc}\\;R\\;x\\;y\\;= \\\\\n\\quad\\forall P.\\:(\\begin{array}[t]{@{}l}\n  (\\forall x\\: y.\\:R\\;x\\;y \\supset P\\;x\\;y)\\; \\wedge \\\\\n  (\\forall x.\\:P\\;x\\;x)\\; \\wedge \\\\\n  (\\forall x\\: y.\\:(\\exists z.\\:P\\;x\\;z \\wedge P\\;z\\;y) \\supset P\\;x\\;y)) \\\\\n\\quad\\supset\\\\\nP\\;x\\;y\n\\end{array}\\end{array}\\]\n\n\\noindent This definition states that a pair $x$ and $y$ is in the relation\n${\\sf Rtc}\\;R$ exactly when it is in every relation $P$ closed under the rules\nfor reflexive-transitive closure. That is, ${\\sf Rtc}\\;R$ is \\mbox{defined} to\nbe the intersection of all relations closed under these rules.  As will be\ndiscussed in the section that follows, this indeed makes ${\\sf Rtc}\\;R$ the\nleast such relation, as required.\n\n\n\\subsection{Deriving the rules and rule induction}\n\nAny relation intended to be defined inductively by a set of rules can be\ndefined formally in the {\\small HOL} logic by a constant definition of the kind\nillustrated by the {\\sf Rtc} example given above.  Such a definition, however,\nmerely introduces the relation as the intersection of all relations that\nsatisfy the desired set of rules.  The proof obligations of a derived principle\nof inductive definition are, first of all, to show that the resulting relation\nin fact does satisfy these rules, and secondly to show that it is indeed the\nleast such relation.  It is these proof obligations which are automated by the\n{\\small HOL} inference rule described below in section~\\ref{newind}.\n\nIn the case of the simple reflexive-transitive closure example, the first proof\nobligation is to show that:\n\n\\[ \\begin{array}[t]{@{}l}\n   \\vdash \\forall R\\:x\\:y.\\:R\\;x\\;y \\supset {\\sf Rtc}\\;R\\;x\\;y \\\\[2mm]\n   \\vdash \\forall R\\:x.\\:{\\sf Rtc}\\;R\\;x\\;x \\\\[2mm]\n   \\vdash \\forall R\\:x\\:y.\\:\n        (\\exists z.\\:{\\sf Rtc}\\;R\\;x\\;z \\wedge {\\sf Rtc}\\;R\\;z\\;y) \\supset\n        {\\sf Rtc}\\;R\\;x\\;y\n\\end{array}\\]\n\n\\noindent That is, one must prove that the rules {{\\small\\bf R}\\bf 1},\n{{\\small\\bf R}\\bf 2}, and {{\\small\\bf R}\\bf 3} follow from the somewhat\nindirect formal definition of the relation ${\\sf Rtc}\\;R$ given in the previous\nsection.  The second proof obligation is to show that ${\\sf Rtc}\\;R$ is the\nleast relation that satisfies these rules:\n\n\\[\\vdash \\begin{array}[t]{@{}l}\n\\forall R\\:P.\\:\\begin{array}[t]{@{}l}\n  (\\begin{array}[t]{@{}l}\n  (\\forall x\\:y.\\:R\\;x\\;y \\supset P\\;x\\;y)\\; \\wedge \\\\\n  (\\forall x.\\:P\\;x\\;x)\\; \\wedge \\\\\n  (\\forall x\\:y.\\:(\\exists z.\\:P\\;x\\;z \\wedge P\\;z\\;y)\n    \\supset P\\;x\\;y))\\end{array}\\\\\n\\quad\\supset\\\\\n\\forall x\\:y.\\: {\\sf Rtc}\\;R\\;x\\;y \\supset P\\;x\\;y\n\\end{array}\\end{array}\\]\n\n\\noindent This is the principle of rule induction for ${\\sf Rtc}\\;R$.  These\nfour theorems constitute a complete statement of the defining properties of\nreflexive-transitive closure. All four can be proved fully automatically in\n{\\small HOL} by the derived inference rule described in the next section.\n\n\\section{Automation}\\label{newind}\n\nThe main component of the inductive definitions package is an {\\small ML}\nfunction that takes as an argument a list of rules and automatically proves the\ndefining properties of the \\mbox{relation} inductively defined by them.  More\nprecisely, this derived {\\small HOL} inference rule builds a term that denotes\nthe least relation closed under the rules using the intersection construction\ndescribed in the previous section.  A constant is then introduced (via a\nconstant specification) to name this relation.  The result is a set of theorems\nstating that the newly-defined relation is the least relation closed under the\nrules supplied by the user.\n\nThe {\\small ML} function that implements this principle of inductive definition\nis:\n\n\\medskip\n\n\\noindent\\begin{tabular}{@{\\hskip\\mathindent}l@{\\hskip4.6mm}l@{}}\n\\verb!new_inductive_definition! & \\mbox{} \\\\\n\\verb! : bool ->! & ({\\it infix flag\\/})\\\\\n\\verb!   string ->! & ({\\it defn.\\ name\\/})\\\\\n\\verb!   (term # term list) ->! & ({\\it pattern\\/})\\\\\n\\verb!   (term list # term) list ->! & ({\\it rules\\/})\\\\\n\\verb!   (thm list # thm)! & ({\\it result\\/})\n\\end{tabular}\n\n\\medskip\n\n\\noindent The first argument to this function is a boolean flag which indicates\nif the constant that is defined is to have infix syntactic status.  The second\nargument is the name under which the resulting definition will be saved on\ndisk.  The third argument is a `pattern' that supplies information which is\nneeded because this {\\small ML} function can be used to define classes of\ninductively defined relations, rather than just single instances of these\nrelations. Details of the purpose and format of this pattern will be explained\nlater.  The final argument is a list of rules, each of which is represented by\na pair of the form:\n\n\\[ \\hbox{\\verb!([!}\\,\n\\hbox{\\it premisses and side conditions\\/}\\,\\hbox{\\verb!], !}\n \\hbox{\\it conclusion\\/}\\hbox{\\verb!)!} \\]\n\n\\noindent The first component is a list of the premisses and side conditions,\nwhich may be arranged in any order.  The second component is the conclusion of\nthe rule.  Side conditions can be arbitrary boolean terms, provided they do not\nmention the relation being defined.  The premisses and conclusion must be\npositive assertions of membership in the relation being defined.  The precise\nform that these assertions must take is explained later, but roughly speaking\nthe premisses and conclusion of a rule must be terms of form\n\\verb!\"!$R\\;\\,t_1\\;\\,\\dots\\;\\,t_n$\\verb!\"!, where\n\n\\[ R\\; \\hbox{\\verb!:!}\\; \\sigma_1 \\;\\hbox{\\verb!->!}\\; \\dots\n\\;\\hbox{\\verb!->!}\\; \\sigma_n \\;\\hbox{\\verb!->!}\\; \\hbox{\\verb!bool!}\\]\n\n\\noindent is a variable representing the $n$-place relation that is to be\ndefined, and each $t_i \\hbox{\\verb!:!} \\sigma_i$ is an arbitrary term not\ncontaining $R$.\n\nGiven an infix flag, a name, a pattern, and a list of rules, the {\\small ML}\nfunction \\verb!new_inductive_definition! automatically proves the existence of\nthe least relation that satisfies these rules.  A constant is then introduced\nto denote this relation using a constant specification, the result of which is\nsaved on disk under the supplied name. The value returned is a pair consisting\nof a list of theorems which state that the newly-defined relation satisfies the\nrules, together with a \\mbox{theorem} asserting rule induction for the\nrelation.  These theorems give a complete statement of the defining properties\nfor the least relation closed under the specified set of rules.\n\n\\subsection{A simple example}\n\nThe following example {\\small HOL} session shows how the function\n\\verb!new_inductive_definition! can be used to inductively define the set of\neven natural numbers.\n\n\\begin{session}\\begin{verbatim}\n#let (rules,ind) =\n   let Even = \"Even:num->bool\" in\n   new_inductive_definition false `Even`\n   (\"^Even n\", [])\n\n   [ [\n     % ----------------------------- % ],\n                 \"^Even 0\"           ;\n\n     [           \"^Even n\"\n     % ----------------------------- % ],\n               \"^Even (n+2)\"        ];;\n\\end{verbatim}\\end{session}\n\n\n\\noindent The first rule in this definition states that \\verb!0! is an even\nnatural number, and the second rule states that if \\verb!n! is even then\n\\verb!n+2! is also even.  (Antiquotation and {\\small ML} comments are used to\ngive a readable presentation of these rules.)  Since the even natural numbers\nare \\mbox{exactly} those numbers obtainable from zero by adding multiples of\ntwo, these rules inductively define `\\verb!Even n!' such that it holds\n\\mbox{precisely} when \\verb!n! is even.\n\nThe value supplied for the pattern in this example is the pair\n\\verb!(\"Even n\",[])!.  The first component of this pair indicates that\nthe constant to be defined, namely \\verb!Even!, is a one-place\nfunction with typical argument \\verb!n!.  In general, the second\ncomponent of a pattern is a non-empty list only when a {\\it class\\/}\nof relations is being defined (see below).  In this example,\n{\\verb!Even!} is a single inductively-defined predicate, and the list\ncomponent of the pattern is therefore empty.\n\n\nWhen the definition shown in box 1 is evaluated,\n\\verb!new_inductive_definition! automatically proves the existence of the least\npredicate closed under the given list of rules and then defines the constant\n\\verb!Even! to denote this predicate.  The following automatically-proved\ntheorems about \\verb!Even! are then returned:\n\n\\begin{session}\\begin{alltt}\nrules =\n[\\(\\vdash\\) Even 0;\n \\(\\vdash\\) \\(\\forall\\,\\)n. Even n \\(\\supset\\) Even(n + 2)] : thm list\nind =\n\\(\\vdash\\) \\(\\forall\\,\\)P. P 0 \\(\\wedge\\) (\\(\\forall\\,\\)n. P n \\(\\supset\\) P(n + 2)) \\(\\supset\\)\n      \\(\\,\\)(\\(\\forall\\,\\)n. Even n \\(\\supset\\) P n)\n\\end{alltt}\\end{session}\n\n\n\\noindent The theorems bound to the {\\small ML} identifier \\verb!rules! state\nthat the required rules hold of the predicate \\verb!Even!. And the rule\ninduction theorem bound to \\verb!ind! states that the set of numbers for which\n\\verb!Even! holds is the least set that satisfies these rules.\n\nAn analogous set of defining theorems can be proved automatically for any\nparticular relation inductively defined by a list of rules.  The next section\nshows how this derived principle of inductive definition in {\\small HOL} can\nalso be used to define a parameterized class of relations.\n\n\\subsection{Defining a class of relations}\n\nThe constant {\\sf Rtc} defined in section~\\ref{in-logic} is not itself an\ninductively-defined relation, but rather a function that maps an arbitrary\nrelation $R$ to an inductively-defined relation ${\\sf Rtc}\\;R$.  The function\n{\\sf Rtc} therefore represents an entire class of inductively-defined\nrelations, one for each possible value of $R$.\n\nThe information that is required by the derived rule\n\\verb!new_inductive_definition! in order to handle the definition of such\nfunctions is supplied by its pattern argument.  In the general case, a pattern\nis a pair of the following form:\n\n\\[\\hbox{\\verb!(\"!}R\\;v_1\\;\\dots\\;v_n\\hbox{\\verb!\",!}\\;\n \\hbox{\\verb![\"!}v_i\\hbox{\\verb!\";!}\\dots\\hbox{\\verb!;\"!}v_j\\hbox{\\verb!\"])!}\n\\]\n\n\\noindent The first component of the pattern is an application of the $n$-place\ncurried function that is to be defined (in this case, $R$) to $n$ distinct\nvariables $v_1$, \\dots, $v_n$.  The second component is a list of those\nvariables that occur at the positions in this application which correspond to\nthe parameters of class of inductively-defined relations, rather than to the\nactual arguments to these relations.\n\nAn example of the role of the pattern argument in defining a class of relations\nis provided by the following definition of reflexive-transitive closure in\n{\\small HOL}.\n\n\\begin{session}\\begin{verbatim}\n#let (rules,ind) =\n   let Rtc = \"Rtc:(*->*->bool)->*->*->bool\"\n in\n   new_inductive_definition false `Rtc`\n   (\"^Rtc R x y\", [\"R:*->*->bool\"])\n\n   [ [      \"R (x:*) (y:*):bool\"\n     % ----------------------------- % ],\n               \"^Rtc R x y\"          ;\n\n     [\n     %------------------------------ % ],\n               \"^Rtc R x x\"          ;\n\n     [  \"^Rtc R x z\";  \"^Rtc R z y\"\n     %------------------------------ % ],\n               \"^Rtc R x y\"          ];;\n\\end{verbatim}\\end{session}\n\n\\noindent The pattern in this case is the pair:\n\n\\medskip\n\n\\noindent\\hskip\\mathindent\\verb!(\"Rtc R x y\", [\"R:*->*->bool\"])!\n\n\\medskip\n\n\\noindent The first component of this pattern specifies that the function\n\\verb!Rtc! is to take three arguments in total---a \\mbox{relation} \\verb!R!,\nand two values \\verb!x! and \\verb!y!.  The \\mbox{second} part of the pattern\n(the list containing just \\verb!R!) specifies that the relation argument\n\\verb!R! is to be a parameter to the class of inductively-defined relations\nthat will be represented by \\verb!Rtc!.  The remaining variables \\verb!x! and\n\\verb!y! are assumed to indicate the positions of actual arguments to the\npredicate that represents these relations.\n\nThe result of evaluating this inductive definition in {\\small HOL} is the\nfollowing collection of theorems:\n\n\\begin{session}\\begin{alltt}\nrules =\n[\\(\\vdash\\) \\(\\forall\\,\\)R x y. R x y \\(\\supset\\) Rtc R x y;\n \\(\\vdash\\) \\(\\forall\\,\\)R x. Rtc R x x;\n \\(\\vdash\\) \\(\\forall\\,\\)R x y. (\\(\\exists\\,\\)z. Rtc R x z \\(\\wedge\\) Rtc R z y)\n              \\(\\supset\\)\n            Rtc R x y] : thm list\nind =\n\\(\\vdash\\) \\(\\forall\\,\\)R P.\n   (\\(\\forall\\,\\)x y. R x y \\(\\supset\\) P x y) \\(\\wedge\\)\n   (\\(\\forall\\,\\)x. P x x) \\(\\wedge\\)\n   (\\(\\forall\\,\\)x y. (\\(\\exists\\,\\)z. P x z \\(\\wedge\\) P z y) \\(\\supset\\) P x y)\n      \\(\\supset\\)\n   (\\(\\forall\\,\\)x y. Rtc R x y \\(\\supset\\) P x y)\n\\end{alltt}\\end{session}\n\n\\noindent Here, the {\\small ML} variable \\verb!rules! has been bound to a list\nof theorems which state the three rules that inductively define the\nreflexive-transitive closure of a relation.  The \\mbox{theorem} \\verb!ind!\nstates the corresponding principle of rule induction for an inductively-defined\nrelation \\verb!Rtc R!.\n\n\\subsection{Stating premisses and conclusions}\n\nIn addition to the use of the pattern argument, the \\verb!Rtc! example also\nillustrates a restriction on the form in which the premisses and conclusions of\nrules must be supplied to \\verb!new_inductive_definition!.  As was mentioned\nabove, premisses and conclusions must be positive assertions of membership of\nthe form\n\n\\medskip\n\n\\noindent\\hskip\\mathindent\\verb!\"!$R\\;\\,t_1\\;\\,\\dots\\;\\,t_n$\\verb!\"!\n\n\\medskip\n\n\\noindent where $R$ is a variable that stands for the function to be defined.\nThe restriction is that some of the terms among the arguments $t_1$, \\dots,\n$t_n$ in such an \\mbox{assertion} must be variables---namely, the terms that\noccur at \\mbox{positions} which, according to the supplied pattern,\n\\mbox{correspond} to the parameters of a class of relations.  In particular,\nthe terms that occur at these positions must be the same variables given in the\npattern itself.\n\nThe rules for reflexive-transitive closure shown in box 3 conform to\nthis restriction.  Here, the pattern indicates that in the typical\nassertion of membership \\verb!\"Rtc R x y\"! (i.e.\\ the first component\nof the pattern), the variable \\verb!R! marks the position of a\nparameter to the class of relations to be defined.  Every premiss and\nconclusion mentioned in the rules must therefore be a term of the form\n$\\hbox{\\verb!\"Rtc R!}\\;\\,t_1\\;\\,t_2\\hbox{\\verb!\"!}$, where the\narguments $t_1$ and $t_2$ may be arbitrary terms but the parameter\n\\verb!R! must be the variable given in the pattern.\n\n\\section{A tactic for rule induction}\n\nThe inductive definitions package in {\\small HOL} includes a number of\nauxiliary functions that support reasoning about inductively-defined relations,\nin addition to the derived rule of definition itself.  The most important of\nthese is the following general tactic for goal-directed proofs by rule\ninduction:\n\n\\medskip\n\n\\noindent\\begin{tabular}{@{\\hskip\\mathindent}l@{\\hskip12.7mm}l@{}}\n\\verb!RULE_INDUCT_THEN! & \\mbox{} \\\\\n\\verb! : thm ->! & ({\\it induction thm\\/})\\\\\n\\verb!   (thm -> tactic) ->! & ({\\it premiss cont.\\/})\\\\\n\\verb!   (thm -> tactic) ->! & ({\\it side cond.\\ cont.\\/})\\\\\n\\verb!   tactic! & ({\\it result\\/})\n\\end{tabular}\n\n\\medskip\n\n\\noindent The first argument to this function is the rule \\mbox{induction}\ntheorem returned by \\verb!new_inductive_definition! for a given\ninductively-defined relation.  Like the general structural induction tactic in\n{\\small HOL}, the rule induction tactic is parameterized by functions that\ndetermine what is done with induction hypotheses. These may be either premisses\nor side conditions, and the user may wish to treat these two kinds of induction\nhypotheses differently. Two separate theorem continuations are therefore\nsupplied as the second and third arguments to the function\n\\verb!RULE_INDUCT_THEN!.\n\nGiven the rule induction theorem for an inductively-defined $n$-ary relation\n$R$, the function described above returns a specialized rule induction tactic\nthat reduces goals of the form:\n\n\\[ \\hbox{\\verb!\"!}\\forall x_1\\;\\dots\\;x_n\\hbox{\\verb!.!}\\;\n  R \\;x_1\\;\\dots\\;x_n \\supset P[x_1,\\dots,x_n]\\hbox{\\verb!\"!} \\]\n\n\\noindent to the subgoal(s) of proving that the property $P$ is preserved by\nthe rules that inductively define $R$.  The rule induction theorem for\n\\verb!Rtc!, for example, is:\n\n\\begin{session}\\begin{alltt}\n#ind;;\n\\(\\vdash\\) \\(\\forall\\,\\)R P.\n   (\\(\\forall\\,\\)x y. R x y \\(\\supset\\) P x y) \\(\\wedge\\)\n   (\\(\\forall\\,\\)x. P x x) \\(\\wedge\\)\n   (\\(\\forall\\,\\)x y. (\\(\\exists\\,\\)z. P x z \\(\\wedge\\) P z y) \\(\\supset\\) P x y)\n      \\(\\supset\\)\n   (\\(\\forall\\,\\)x y. Rtc R x y \\(\\supset\\) P x y)\n\\end{alltt}\\end{session}\n\n\\noindent A rule induction tactic for \\verb!Rtc! can be constructed from this\ntheorem by making the simple {\\small ML} definition:\n\n\\begin{session}\\begin{alltt}\n#let Rtc_INDUCT_TAC =\n   RULE_INDUCT_THEN ind\n      ASSUME_TAC ASSUME_TAC;;\nRtc_INDUCT_TAC = - : tactic\n\\end{alltt}\\end{session}\n\n\\noindent The use of \\verb!ASSUME_TAC! in this definition means that the\ninduction hypotheses arising from the premisses and side conditions of the\nrules are to be added to the assumptions of the subgoals that are generated.\nThe resulting rule induction tactic for \\verb!Rtc!  is described by:\n\n\\bigskip\n\n\\noindent\\begin{tabular}{@{\\hskip\\mathindent}c@{}}\n$\\Gamma\\;\\:$\\verb!?-!$\\;\\:\\forall x\\:y$\\verb!. Rtc!$\\;R\\;x\\;y \\supset P[x,y]$\\\\\n\\trule{62mm}\\\\\n$\\Gamma \\cup \\{R\\;x\\;y\\}\\;\\:$\\verb!?-!$\\;\\:P[x,y]$\\\\[1mm]\n$\\Gamma\\;\\:$\\verb!?-!$\\;\\:\\forall x$\\verb!.!$\\;P[x,x]$\\\\[1mm]\n$\\Gamma\\;{\\cup}\\;\\{P[x,z],\\:P[z,y]\\}\\;\\:$\\verb!?-!$\\;\\:P[x,y]$\n\\end{tabular}\n\n\\bigskip\n\n\\noindent This tactic implements the induction scheme described above in\nsection~\\ref{rule-ind}. It reduces the goal of proving that a property $P[x,y]$\nholds for all pairs $x$ and $y$ related by $\\hbox{\\verb!Rtc!}\\;R$ to showing\nthat this property is preserved by the rules that inductively define this\nrelation.\n\n\\subsection{An example}\n\nThe following session shows how the rule induction tactic for \\verb!Rtc!\nconstructed in the previous section can be used to prove a simple theorem about\nthis relation.  The aim is to show that the reflexive-transitive closure of a\nsymmetric relation is also symmetric.  The proof begins by using the {\\small\nHOL} subgoal package (see~\\cite{description}) to set up an appropriate goal to\nbe proved:\n\n\\smallskip\n\n\\begin{session}\\begin{alltt}\n#set_goal\n   ([\"\\(\\forall\\,\\)x:*. \\(\\forall\\,\\)y. R x y \\(\\supset\\) R y x\"],\n     \"\\(\\forall\\,\\)x:*. \\(\\forall\\,\\)y. Rtc R x y \\(\\supset\\) Rtc R y x\");;\n\"\\(\\forall\\,\\)x y. Rtc R x y \\(\\supset\\) Rtc R y x\"\n    [ \"\\(\\forall\\,\\)x y. R x y \\(\\supset\\) R y x\" ]\n\n() : void\n\\end{alltt}\\end{session}\n\n\\smallskip\n\n\\noindent The assumption of the goal is that the relation \\verb!R! is\nsymmetric, and the conclusion states that the closure \\verb!Rtc R! is also\nsymmetric.  The conclusion of the goal is in precisely the right form for a\nproof by rule induction using the induction tactic described above.  Applying\nthis tactic results in:\n\n\\smallskip\n\n\\begin{session}\\begin{alltt}\n#expand Rtc_INDUCT_TAC;;\nOK..\n3 subgoals\n\"Rtc R y x\"                       {\\rm({\\it{subgoal 1\\/}})}\n    [ \"\\(\\forall\\,\\)x y. R x y \\(\\supset\\) R y x\" ]\n    [ \"Rtc R z x\" ]\n    [ \"Rtc R y z\" ]\n\n\"\\(\\forall\\,\\)x. Rtc R x x\"                   \\(\\!\\){\\rm({\\it{subgoal 2\\/}})}\n    [ \"\\(\\forall\\,\\)x y. R x y \\(\\supset\\) R y x\" ]\n\n\"Rtc R y x\"                       {\\rm({\\it{subgoal 3\\/}})}\n    [ \"\\(\\forall\\,\\)x y. R x y \\(\\supset\\) R y x\" ]\n    [ \"R x y\" ]\n\n() : void\n\\end{alltt}\\end{session}\n\n\\smallskip\n\n\\noindent Subgoals 1 and 2 are trivial, since the relation \\verb!Rtc R! is\ntransitive and reflexive by definition. The tactic proofs for these subgoals\ncan simply use the rules shown above in box~4. The proof of subgoal 3 is also\neasy. The proposition \\verb!\"R y x\"! follows immediately from the two\nassumptions of the subgoal; and this proposition \\mbox{together} with the fact\nthat\n\n\\bigskip\n\n\\noindent\\hskip\\mathindent$\\vdash\\forall\\,$\\verb!R x y. R x y !$\\supset\n$\\verb! Rtc R x y!\n\n\\bigskip\n\n\\noindent directly entail the required conclusion.\n\nThe proof sketched above is a trivial example of the kind of reasoning\nsometimes referred to as induction over the structure (or the depth) of\nderivations in a deductive system stated by a set of rules.  This form of\ninductive \\mbox{argument}, which is very common in certain \\mbox{areas} of\ntheory (for example, operational semantics and process algebras), is made\ndirectly accessible in {\\small HOL} by the tactic described in this section.\n\n\\section{Tactics and inference rules}\n\nIn addition to the rule induction tactic described above, the inductive\ndefinitions package also provides mechanized support for generating tactics\nfrom the theorems that state the rules for an inductively-defined relation.\nThis takes the form of an {\\small ML} function:\n\n\\medskip\n\n\\noindent\\hskip\\mathindent\\verb!RULE_TAC : thm -> tactic!\n\n\\medskip\n\n\\noindent The theorem argument to this function is expected to be a rule\nexpressed in the form proved by the derived principle of inductive definition\ndescribed in section~\\ref{newind}. Given such a theorem, \\verb!RULE_TAC!\nconstructs a tactic that inverts the rule stated by it.  The resulting tactic\nreduces goals that match the conclusion of the rule to subgoals consisting of\nthe corresponding instances of its premisses and side conditions.\n\nConsider, for example, the theorem which states the transitivity rule for\n\\verb!Rtc!:\n\n\\[\\vdash \\forall\\,\\hbox{\\verb!R x y. !}\\begin{array}[t]{@{}l}%\n\\hbox{\\verb!(!}\\exists\\,\n\\hbox{\\verb!z. Rtc R x z !}\\wedge\\hbox{\\verb! Rtc R z y)!}\\\\\n\\quad \\supset \\\\\n\\hbox{\\verb!Rtc R x y!}\n\\end{array} \\]\n\n\\noindent When applied to this theorem, the function \\verb!RULE_TAC! returns\nthe tactic described by:\n\n\\bigskip\n\n\\noindent\\begin{tabular}{@{\\hskip\\mathindent}c@{}}\n$\\Gamma\\;\\:$\\verb!?-!$\\;\\:$\\verb!Rtc!$\\;R\\;x\\;y$ \\\\\n\\trule{62mm}\\\\\n$\\Gamma\\;\\:$\\verb!?-!$\\;\\:\\exists z\n$\\verb!.!$\\;$\\verb!Rtc!$\\;R\\;x\\;z\\;\\:\\wedge\\;\\;$\\verb!Rtc!$\\;R\\;z\\;y$\n\\end{tabular}\n\n\\bigskip\n\n\\noindent This tactic can then be used in goal-directed proofs about membership\nin the inductively-defined relation {\\verb!Rtc!$\\;R$}.  The other two rules\nthat define \\verb!Rtc!$\\;R$ can also be converted into tactics using the\nfunction \\verb!RULE_TAC!.  The result is a complete set of {\\small HOL} tactics\nfor goal-directed proofs in the deductive system comprising the three rules\nthat define reflexive-transitive closure.\n\nIt is intended that the inductive definitions package will also include a\nfunction that maps rules stated as theorems to forward inference rules in\n{\\small HOL} (i.e.\\ to {\\small ML} functions).  For example, the transitivity\ntheorem shown above can be used to implement the following derived\ninference rule:\n\n\\bigskip\n\n\\noindent\\begin{tabular}{@{\\hskip\\mathindent}c@{}}\n$\\Gamma_1\\;{\\vdash}\\;$\\verb!Rtc!$\\;R\\;x\\;z$\\qquad\n$\\Gamma_2\\;{\\vdash}\\;$\\verb!Rtc!$\\;R\\;z\\;y$\\\\\n\\rrule{62mm}\\\\\n$\\Gamma_1 \\cup \\Gamma_2\\;{\\vdash}\\;$\\verb!Rtc!$\\;R\\;x\\;y$\n\\end{tabular}\n\n\\bigskip\n\n\\noindent Any rule expressed as a theorem of the form proved by the derived\nprinciple of inductive definitions can likewise be converted into a forward\ninference rule.  A function that \\mbox{automatically} constructs such rules has\nnot yet been implemented, partly because it has not been found necessary for\nthe applications done so far (see section~\\ref{appl}).  For completeness,\nhowever, the author intends in future to add this function to the inductive\ndefinitions package.\n\n\\section{Case analysis}\n\nThe final major component of the {\\small HOL} package for inductive definitions\nis an {\\small ML} function that proves an \\mbox{exhaustive} case analysis\ntheorem for any given relation inductively defined by a set of rules.  The name\nand type of this function are:\n\n\\medskip\n\n\\noindent\\hskip\\mathindent\\verb!derive_cases_thm : (thm list # thm) -> thm!\n\n\\medskip\n\n\\noindent The arguments to this function are the list of rules satisfied by an\ninductively defined relation, together with its rule induction theorem. (These\nare precisely the defining theorems which are proved and returned by\n\\verb!new_inductive_definition!.)  When supplied with these theorems,\n\\verb!derive_cases_thm! proves that if an assertion of membership in the\nrelation holds, then it holds only by virtue of the fact that one of the rules\ncan be used to derive it.  This allows one to drive the rules that define a\nrelation `backwards', inferring from the conclusion of one of the rules that\nthe premisses and side conditions hold.\n\nThe following interaction with the {\\small HOL} system shows the theorem proved\nby \\verb!derive_cases_thm! for the \\verb!Rtc! example introduced above.  The\n{\\small ML} variables \\verb!rules! and \\verb!ind! are assumed to have the\nbindings shown above in box~4.\n\n\\smallskip\n\n\\begin{session}\\begin{alltt}\n#derive_cases_thm (rules,ind);;\n\\(\\vdash\\) \\(\\forall\\,\\)R x y.\n    Rtc R x y \\(\\supset\\)\n      R x y   \\(\\vee\\)\n      (y = x) \\(\\vee\\)\n      (\\(\\exists\\,\\)z. Rtc R x z \\(\\wedge\\) Rtc R z y)\n\\end{alltt}\\end{session}\n\n\\smallskip\n\n\\noindent Roughly speaking, the resulting theorem states that if\n\\verb!Rtc R x y! holds, then either:\n\n\\begin{itemize}\n\n\\item it is derivable by the inclusion rule {{\\small\\bf R}\\bf 1}, in which\ncase \\verb!x! and \\verb!y! are related by \\verb!R!; or\n\n\\item it is derivable by the reflexivity rule {{\\small\\bf R}\\bf 2}, in which\ncase \\verb!x! and \\verb!y! are equal; or\n\n\\item it is derivable by the transitivity rule {{\\small\\bf R}\\bf 3}, in which\ncase there must be an intermediate value \\verb!z! such that \\verb!Rtc R x z!\nand \\verb!Rtc R z y!.\n\n\\end{itemize}\n\n\\noindent A similar theorem can be proved automatically for any relation\ndefined inductively using the package. Work is currently underway to strengthen\nthis theorem from an implication to an equation, so that it can be used for\nrewriting.\n\n\\section{Applications}\\label{appl}\n\nIn a joint project with Juanito Camilleri, a set of example proofs has\nbeen developed to illustrate the potential for applications of the inductive\n\\mbox{definitions} package.  These examples include: the definition of an\noperational semantics for a simple programming language and a proof that its\nevaluation relation is \\mbox{deterministic}; the definition of a reduction\nrelation for combinatory logic and a proof that it has the Church-Rosser\nproperty; a definition of \\mbox{provability} in a Hilbert style proof system\nfor minimal intuitionistic logic; the definition of a type system for\ncombinatory logic and a proof of the Curry-Howard isomorphism for typed\ncombinatory logic and minimal intuitionistic logic; and definitions of the\ntrace and transition semantics for a simple process algebra, \\mbox{together}\nwith the proof of a formal statement of the relationship between them. A report\non this work is in preparation, and the {\\small HOL} source code for the\nexamples will be made available to interested users.\n\n\\newpage\n\n\\begin{thebibliography}{9}\n\n\\bibitem{description}\nDSTO, The University of Cambridge, and SRI\n\\mbox{International}, {\\it The HOL System: DESCRIPTION} (1991).\n\n\\bibitem{melham}\nT.\\ F.\\ Melham, `Automating Recursive Type Definitions\nin Higher Order Logic',\nin: {\\it Current Trends in Hardware Verification and\nAutomated Theorem Proving\\/}, edited by G.\\ Birtwistle\nand P.A.\\ Subrahmanyam\n(Springer-Verlag, 1989), pp.\\ 341--386.\n\n\\bibitem{pitts}\nA.\\ M.\\ Pitts, `Semantics of Programming Languages',\nunpublished lecture notes, University of Cambridge Computer Laboratory\n(October 1989).\n\n\\bibitem{winskel}\nG.\\ Winskel, `Introduction to the Formal Semantics of\nProgramming Languages', unpublished lecture notes, University of Cambridge\nComputer Laboratory (October 1985).\n\n\\end{thebibliography}\n\n\\end{document}\n", "meta": {"hexsha": "a6d9736fc9c90623db42164d84d2478188238f1a", "size": 38720, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/IndDef/Manual/paper.tex", "max_stars_repo_name": "dwRchyngqxs/HOL", "max_stars_repo_head_hexsha": "3b1931c130fcab243da332adb2c1413c42c59cf9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 492, "max_stars_repo_stars_event_min_datetime": "2015-01-07T16:36:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T22:18:48.000Z", "max_issues_repo_path": "src/IndDef/Manual/paper.tex", "max_issues_repo_name": "dwRchyngqxs/HOL", "max_issues_repo_head_hexsha": "3b1931c130fcab243da332adb2c1413c42c59cf9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 759, "max_issues_repo_issues_event_min_datetime": "2015-01-01T00:40:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T17:33:39.000Z", "max_forks_repo_path": "src/IndDef/Manual/paper.tex", "max_forks_repo_name": "dwRchyngqxs/HOL", "max_forks_repo_head_hexsha": "3b1931c130fcab243da332adb2c1413c42c59cf9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 126, "max_forks_repo_forks_event_min_datetime": "2015-02-17T03:20:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T00:42:55.000Z", "avg_line_length": 42.974472808, "max_line_length": 96, "alphanum_fraction": 0.7220041322, "num_tokens": 11035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.32822173550935885}}
{"text": "\\documentclass{beamer}\n%\n% Choose how your presentation looks.\n%\n% For more themes, color themes and font themes, see:\n% http://deic.uab.es/~iblanes/beamer_gallery/index_by_theme.html\n%\n\\usetheme{Ilmenau}      % or try Darmstadt, Madrid, Warsaw, ...\n\\usecolortheme{seahorse} % or try albatross, beaver, crane, ...\n\\usefonttheme{default}  % or try serif, structurebold, ...\n\\setbeamertemplate{navigation symbols}{}\n\\setbeamertemplate{caption}[numbered]\n\\usepackage{tikz}\n\\usepackage{pgfplots}\n\\usepackage{pgf}\n\\usepackage{units}\n\\usepackage{graphicx}\n\\usepackage{caption}\n\\usepackage[mode=buildnew]{standalone}% requires -shell-escape\n\\usepackage{amsmath}\n\n\\usepackage[english]{babel}\n\\usepackage[utf8x]{inputenc}\n\\setbeamertemplate{footline}[frame number]\n\n\\title{Building an end-to-end speech recognizer}\n\\author{Moritz Wolter}\n\n\\date{01.02.2017}\n\n\\begin{document}\n\\begin{frame}\n  \\titlepage\n\\end{frame}\n\n\n% Uncomment these lines for an automatically generated outline.\n\\begin{frame}{Outline}\n  \\tableofcontents\n\\end{frame}\n\n\\section{Introduction}\n\\begin{frame}{The problem}\n\t\\begin{itemize}\n\t\t\\item What is being said? \n\t\t\\item What is interesting?\n\t\t\\item What model architecture?\n\t\t\\item Which hyper-parameters?\n\t\t\\item How to ensure generalization?\n\t\\end{itemize}\n\\end{frame}\n\n\\subsection{Listen Attend and Spell}\n\\begin{frame}{Long Short Term Memory}\n\t\\begin{figure}\n\t\t\\begin{tikzpicture}\n\t\t    \\node[anchor=south west,inner sep=0] at (0,0) {\\includestandalone[height=6.5 cm]{../tikz/lstm}};\n\t\t    %\\draw[red,ultra thick,rounded corners] (0.0,0.0) rectangle (5.0,2.5);\n\t\t\\end{tikzpicture}\n\t\t\\caption{LSTM cell architecture visualization.}\n\t\\end{figure}\n\\end{frame}\n\n\n\\begin{frame}{The LAS-Architecture}\n\t\\begin{figure}\n\t\t\\begin{tikzpicture}\n\t\t    \\node[anchor=south west,inner sep=0] at (0,0) {\\includestandalone[height=6.5 cm]{../tikz/lasArcBottomUp}};\n\t\t    %\\draw[red,ultra thick,rounded corners] (0.0,0.0) rectangle (5.0,2.5);\n\t\t\\end{tikzpicture}\n\t\t\\caption{Listener and speller.}\n\t\\end{figure}\n\\end{frame}\n\n\\begin{frame}{The LAS-Equations}\nAttend and spell cell computations:\n\\begin{align}\n\t \\mathbf{s}_i &= \\text{RNN}(\\mathbf{s}_{i-1}, \\mathbf{y}_{i-1}, \\mathbf{c}_{i-1}), \\\\\n\t \\mathbf{c}_i &= \\text{AttentionContext}(\\mathbf{s}_i,\\mathbf{H}), \\\\\n\t  P(\\mathbf{y}_i|\\mathbf{x}, \\mathbf{y}_{<i}) &= \\text{CharacterDistribution}(\\mathbf{s}_i,\\textbf{c}_i).\n\\end{align}\n\nAttentionContext computations:\n\\begin{align}\n\te_{i,u} = \\phi(\\mathbf{s}_i)^T \\psi(\\mathbf{h_u}), \\\\\n\t\\alpha_{i,u} = \\frac{ \\exp(e_{i,u})}{ \\sum\\limits_{u} \\exp(e_{i,u})}, \\\\\n\t\\label{eq:alphas}\n\t\\mathbf{c}_i = \\sum\\limits_{u} \\alpha_{i,u} \\mathbf{h}_u.\n\\end{align}\n\\end{frame}\n\n\n\\section{Methodology}\n\\begin{frame}{Used methods}\n\t\\begin{itemize}\n\t\t\\item Object oriented programming, python.\n\t\t\t\\begin{itemize}\n\t\t\t\t\\item data encapsulation, partly replaced by \\texttt{tf.variable\\_scope}(\"...\").\n\t\t\t\t\\item code structure and re-usability.\n\t\t\t\\end{itemize}\n\t\t\\item Shape invariants, tensorflow.\n\t\t\t\\begin{itemize}\n\t\t\t\t\\item Programmer must explicitly state changing dimensions in loop.\n\t\t\t\t\\item Makes code easier to read, and prevents bugs.\n\t\t\t\\end{itemize}\n\t\t\\item Code quality, pylint.\n\t\t\t\\begin{itemize}\n\t\t\t\t\\item if the python foundation' style guide is being followed. \n\t\t\t\t\\item looks for errors in the code.\n\t\t\t\\end{itemize}\n\t\t\\item Version control, git.\n\t\\end{itemize}\n\\end{frame}\n\n\\section{Implementation}\n\\begin{frame}{Attend and spell cell layout}\n\t\\begin{figure}\n\t\\includestandalone[height=6.5 cm]{../tikz/asCellType1}\n\t\\caption{Attend and spell cell flow chart.}\n\t\\end{figure}\n\\end{frame}\n\n\\begin{frame}[fragile]\n\\frametitle{Decoding loop logic}\n\\begin{block}{body loop logic}\n\t\\begin{semiverbatim}\n\twhile keep_working:\n\t  not_done_count = reduce_sum( logical_not( d ))\n\t  done = equal(not_done_count, 0)\n\t  stop = logical_or(done, greater(time, max_steps))\n\t  keep_working = logical_not(stop)\n\t\\end{semiverbatim}\n\\end{block}\n\\begin{block}{setting the sequence length}\n\t\\begin{semiverbatim}\n\t  decoded = decode(logits)\n\t  mask = tf.equal(decoded, <eos>)\n\t  time_vec = ones(self.batch_size)*(time+1)\n\t  sequence_lengths = select(d,\n\t                            logits_sequence_length,\n\t                            time_vec)\n\t  d = logical_or(mask, d)\n\t\\end{semiverbatim}\n\\end{block}\n\\end{frame}\n\n\\begin{frame}{Dropout}\n\t\\begin{figure}\n\t\t\\includestandalone[height=6.5 cm]{../tikz/las_dropout}\n\t\t\\caption{Input dropout - light red. Hidden dropout - dark red.}\n\t\\end{figure}\n\\end{frame}\n\n\\section{Results}\n\\begin{frame}{The Listener with CTC}\n\t\\begin{figure}\n\t\t\\includestandalone[width=0.49\\textwidth]{../tikz/CTC_Listener_plot_e10_loss}\n\t\t\\includestandalone[width=0.49\\textwidth]{../tikz/CTC_Listener_plot_e10_error}\n\t\t\\caption{Listener with attached CTC.}\n\t\\end{figure}\n\\end{frame}\n\n\n\\subsection{Custom attention}\n\n\\begin{frame}{Greedy Decoding}\n\t\\begin{figure}\n\t\\includestandalone[width=0.49\\linewidth]{../tikz/LAS_no_reg_e40_p07_loss}\n\t\\includestandalone[width=0.49\\linewidth]{../tikz/LAS_no_reg_e40_p07_error}\n\t\\caption{The training progress shown for the full las architecture with greedy decoding, over 40 epochs, network output reuse probability 0.7 and input noise standard deviation 0.65 .}\n\t\\label{fig:lasGreedy}\n\t\\end{figure}\n\\end{frame}\n\n\\begin{frame}{Alignment plots}\n\t\\begin{figure}\n\t\\centering\n\t\\includestandalone[width=0.49\\linewidth]{../tikz/alpha}\n\t\\includestandalone[width=0.42\\linewidth]{../tikz/align}\n\t\\caption{Plot of the alignment vectors computed by the network for all 45 labels assigned to timit utterance \\texttt{fmld0\\_sx295} (left), and alignments assigned by a human listener (right).}\n\t\\label{fig:fullAttention}\n\t\\end{figure}\n\\end{frame}\n\n\\begin{frame}{Alignment plots}\n\t\\begin{block}{Target labels}\n\t\t\\begin{semiverbatim}\n\t\t<sos>  sil  ih  f  sil  k  eh  r  l  sil  k  ah  m  z\n\t\t       sil  t  ah  m  aa  r  ah  hh  ae  v  er  r  ey\n\t\t       n  jh  f  er  m  iy  dx  iy  ng  ih  \n\t\t       sil  t  uw  sil\n\t\t<eos>\n\t\t\\end{semiverbatim}\n\t\\end{block}\n\n\t\\begin{figure}\n\t\\centering\n\t\\includestandalone[height=0.26\\linewidth]{../tikz/alphaZoom}\n\t\\includestandalone[height=0.26\\linewidth]{../tikz/alphaZoom2}\n\t\\includestandalone[height=0.26\\linewidth]{../tikz/alphaZoom3}\n\t\\caption{Attention weights $\\alpha$ and network output.}\n\t\\label{fig:attention3}\n\t\\end{figure}\n\\end{frame}\n\n\\begin{frame}\n\t\\begin{figure}\n\t\\centering\n\t\\includestandalone[width=0.24\\linewidth]{../tikz/LAS_no_reg_e10_p02_loss}\n\t\\includestandalone[width=0.24\\linewidth]{../tikz/LAS_no_reg_e10_p02_error}\n\t\\includestandalone[width=0.24\\linewidth]{../tikz/LAS_no_reg_e10_p04_loss}\n\t\\includestandalone[width=0.24\\linewidth]{../tikz/LAS_no_reg_e10_p04_error}\n\t\\includestandalone[width=0.24\\linewidth]{../tikz/LAS_no_reg_e10_p06_loss}\n\t\\includestandalone[width=0.24\\linewidth]{../tikz/LAS_no_reg_e10_p06_error}\n\t\\includestandalone[width=0.24\\linewidth]{../tikz/LAS_no_reg_e10_p08_loss}\n\t\\includestandalone[width=0.24\\linewidth]{../tikz/LAS_no_reg_e10_p08_error}\n\t\\caption{Repetitions of the same experiment with increasing network output reuse probabilities $0.2, 0.4, 0.6, 0.8$, one experiment per row.}\n\t\\label{fig:lasGreedy2468}\n\t\\end{figure}\n\\end{frame}\n\n\\begin{frame}{Dropout las with beam search}\n\t\\begin{figure}\n\t\\includestandalone[width=0.49\\textwidth]{../tikz/LAS_dropout0805_in00_p06_e120_double_loss}\n\t\\includestandalone[width=0.49\\textwidth]{../tikz/LAS_dropout0805_in00_p06_e120_double_error}\n\t\\caption{Dropout las results.}\n\t\\end{figure}\n\\end{frame}\n\n\n\\begin{frame}{Default attention}\nTODO\n\\end{frame}\n\n\\begin{frame}{Conclusion}\nTODO\n\\end{frame}\n\n\n\\section{Questions}\n\\begin{frame}{Questions}\n\tThank's for your attention. Questions? \\\\\n\tNow, or later \\texttt{moritz@wolter.tech}.\n\\end{frame}\n\n\n\\end{document}\n", "meta": {"hexsha": "967deecb7b831b5ddfafb36e2ad1fe1bfaba1dc5", "size": 7701, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "finalpresentation/presentation.tex", "max_stars_repo_name": "v0lta/masterThesis", "max_stars_repo_head_hexsha": "ee80552c2ba44117c50c7524c85f12b9eb39f412", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-12-13T16:37:28.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-19T09:53:23.000Z", "max_issues_repo_path": "finalpresentation/presentation.tex", "max_issues_repo_name": "v0lta/masterThesis", "max_issues_repo_head_hexsha": "ee80552c2ba44117c50c7524c85f12b9eb39f412", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "finalpresentation/presentation.tex", "max_forks_repo_name": "v0lta/masterThesis", "max_forks_repo_head_hexsha": "ee80552c2ba44117c50c7524c85f12b9eb39f412", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0524193548, "max_line_length": 193, "alphanum_fraction": 0.7238021036, "num_tokens": 2559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.32814587438460197}}
{"text": "\\chapter{Key Types}\n\n\\section{Alphabetically}\n\n\\subsection{A}\n\n\\begin{code}\ntype Assertion = (Term, SideCond)                                    --VarData\n\\end{code}\n\n\\begin{code}\ndata AtmSideCond                                                    --SideCond\n = SD  GenVar VarSet -- Disjoint\n | SS  GenVar VarSet -- Superset (covers)\n | SP  GenVar        -- Pre\npattern Disjoint gv vs = SD  gv vs  --  vs `intersect`  gv = {}\npattern Covers   gv vs = SS  gv vs  --  vs `supersetof` gv\npattern IsPre    gv    = SP  gv     --  gv is pre-condition\n\\end{code}\n\n\n\n\\subsection{B}\n\n\\begin{code}\ntype BVS = Set GenVar\n\\end{code}\n\n\\subsection{C}\n\n\\begin{code}\ntype CalcStep                                                         --Proofs\n  = ( Justification  -- step justification\n    , Assertion )         -- previous term\n\\end{code}\n\n\\begin{code}\ntype Calculation                                                      --Proofs\n  = ( Term -- end (or current) term\n    , [ CalcStep ] )  -- calculation steps, in proof order\n\\end{code}\n\n\\begin{code}\ntype Candidate = Term\n\\end{code}\n\n\\begin{code}\ntype CBVS = BVS\n\\end{code}\n\n\\newpage\n\\subsection{E}\n\n\n\\begin{code}\npattern EVal t k           =  K (E t) k                                  --AST\npattern EVar t v          <-  V (E t) v\npattern ECons t n ts       =  C (E t) n ts\npattern EBind t n vs tm   <-  B (E t) n vs tm\npattern ELam t n vl tm    <-  L (E t) n vl tm\npattern ESub t tm s        =  S (E t) tm s\npattern EIter t na ni lvs  =  I (E t) na ni lvs\npattern E2 t n t1 t2       =  C (E t) n [t1,t2]                          --AST\n\\end{code}\n\n\n\\subsection{G}\n\n\\begin{code}\ndata GenVar                                                        --Variables\n = GV Variable -- regular variable\n | GL ListVar  -- variable denoting a list of variables\npattern StdVar v = GV v\npattern LstVar lv = GL lv\ntype VarList = [GenVar]\ntype VarSet = Set GenVar\n\\end{code}\n\n\\begin{code}\ndata GroupSpec                                                          --Laws\n  = Assoc LeftRight\n  | Gather LeftRight Int\n  | Split Int\n\\end{code}\n\n\\subsection{H}\n\n\\begin{code}\ndata HowUsed                                                          --Proofs\n  = ByMatch MatchClass  -- replace focus with binding(match)\n  | ByInstantiation     -- replace focus=true with binding(law)\n\\end{code}\n\n\\subsection{I}\n\n\\begin{code}\ndata Identifier = Id String Int                                    -- LexBase\npattern Identifier nm u <- Id nm u\n\\end{code}\n\n\\newpage\n\\subsection{J}\n\n\\begin{code}\ndata Justification                                                    --Proofs\n  = UseLaw             -- used a law\n      HowUsed              -- how law was used in proof step\n      String               -- law name\n      Binding              -- binding from law variables to goal components\n      [Int]                -- zipper descent arguments\n  | Substitute         -- performed a substitution\n      [Int]                -- zipper descent arguments\n  | NormQuant          -- performed a quantifier normalisation\n      [Int]                -- zipper descent arguments\n  | NestSimp           -- simplified nested quantifiers\n      [Int]                -- zipper descent arguments\n  | Switch             -- switched focus at sequent level\n      SeqFocus             -- focus before switch -- needed to reverse this.\n      SeqFocus             -- focus after switch\n  | CloneH Int         --  Cloned hypothesis i\n  | Flatten Identifier -- flattened use of associative operator\n  | Associate          -- grouped use of an associative operator\n      Identifier           -- operator\n      GroupSpec            -- grouping details.\n\\end{code}\n\n\n\\subsection{L}\n\n\\begin{code}\ntype Law = (NmdAssertion,Provenance)                                    --Laws\n\\end{code}\n\n\\begin{code}\ndata Laws'                                                          --Sequents\n  = CLaws' { -- currently focussed on conjecture component\n      hyp0  :: Theory -- hypothesis theory\n    , whichC :: LeftRight -- which term is in the focus\n    , otherC :: Term  -- the term not in the focus\n    }\n  | HLaws' { -- currently focussed on hypothesis component\n      hname     :: String -- hyp. theory name\n    , hknown    :: VarTable\n    , hbefore   :: [Law] -- hyp. laws before focus (reversed)\n    , fhName    :: String -- focus hypothesis name\n    , fhSC      :: SideCond -- focus hypothesis sc (usually true)\n    , fhProv    :: Provenance -- focus hypothesis provenance (?)\n    , hOriginal :: Term -- the original form of the focus hypothesis\n    , hafter    :: [Law] -- hyp. laws after focus\n    , cleft0    :: Term -- left conjecture\n    , cright0   :: Term -- right conjecture\n    }\n\\end{code}\n\n\n\\begin{code}\ndata LeftRight = Lft | Rght                                             --Laws\n\\end{code}\n\n\\begin{code}\ndata LogicSig                                                           --Laws\n  = LogicSig\n     { theTrue  :: Term\n     , theFalse :: Term\n     , theEqv   :: Identifier\n     , theImp   :: Identifier\n     , theAnd   :: Identifier\n     , theOr    :: Identifier\n     }\n\\end{code}\n\n\\begin{code}\ndata LstVarBind                                                      --Binding\n = BL  VarList\n | BS  VarSet\n | BX  [LVarOrTerm]\npattern BindList vl      =  BL vl\npattern BindSet  vs      =  BS vs\npattern BindTLVs tlvs    =  BX tlvs\n\\end{code}\n\n\\begin{code}\ntype ListVarBinding = M.Map ListVarKey LstVarBind\n\\end{code}\n\n\\begin{code}\ntype ListVarKey = (Identifier,VarClass,[Identifier],[Identifier])\n\\end{code}\n\n\\begin{code}\ndata LiveProof                                                    --LiveProofs\n  = LP {\n      conjThName :: String -- conjecture theory name\n    , conjName :: String -- conjecture name\n    , conjecture :: Assertion -- assertion being proven\n    , conjSC :: SideCond -- side condition\n    , strategy :: String -- strategy\n    , mtchCtxts :: [MatchContext] -- current matching contexts\n    , focus :: SeqZip  -- current sub-term of interest\n    , fPath :: [Int] -- current term zipper descent arguments\n    , matches :: Matches -- current matches\n    , stepsSoFar :: [CalcStep]  -- calculation steps so far, most recent first\n    }\n\\end{code}\n\n\\begin{code}\ntype LiveProofs = Map (String,String) LiveProof                   --LiveProofs\n\\end{code}\n\n\\begin{code}\ndata LstVarMatchRole -- ListVar Matching Roles                       --VarData\n = KL VarList        -- Known Variable-List, all of which are themselves known\n      [Variable]     -- full expansion\n      Int            -- length of full expansion\n | KS VarSet         -- Known Variable-Set, all of which are themselves known\n      (Set Variable) -- full expansion\n      Int            -- size of full expansion\n | AL                -- Abstract Known Variable-List\n | AS                -- Abstract Known Variable-Set\n | UL                -- Unknown List-Variable\npattern KnownVarList vl vars len  =  KL vl vars len\npattern KnownVarSet  vs vars siz  =  KS vs vars siz\npattern AbstractList              =  AL\npattern AbstractSet               =  AS\npattern UnknownListVar            =  UL\n\\end{code}\n\n\\begin{code}\ntype LVarSub = Set (ListVar,ListVar) -- target/replacement              --AST\n\\end{code}\n\n\\subsection{M}\n\n\\begin{code}                                                      --LiveProofs\ndata Match\n = MT { mName  ::  String     -- assertion name\n      , mAsn   ::  Assertion  -- matched assertion\n      , mClass ::  MatchClass -- match class\n      , mBind  ::  Binding    -- resulting binding\n      , mLocSC ::  SideCond   -- goal side-condition local update\n      , mLawSC ::  SideCond   -- law side-condition mapped to goal\n      , mRepl  ::  Term       -- replacement term\n      }\n\\end{code}\n\n\\begin{code}\ndata MatchClass                                                       --Proofs\n  = MA       -- match all of law, with replacement 'true'\n  | ME [Int] -- match subpart of 'equiv' chain\n  | MIA      -- match implication antecedent A, replacement A /\\ C\n  | MIC      -- match implication consequent C, replacement A \\/ C\n  -- MEV should be last, so these matches rank low by default\n  | MEV Int  -- match PredVar at given position\npattern MatchAll       = MA\npattern MatchEqv is    = ME is\npattern MatchAnte      = MIA\npattern MatchCnsq      = MIC\npattern MatchEqvVar i  = MEV i\n\\end{code}\n\n\\begin{code}\ntype MatchContext                                                 --LiveProofs\n  = ( String       -- Theory Name\n    , [Law]        -- all laws of this theory\n    , [VarTable] ) -- all known variables here, and in dependencies\n\\end{code}\n\n\\subsection{N}\n\n\\begin{code}\ntype NmdAssertion = (String,Assertion)                                  --Laws\n\\end{code}\n\n\\subsection{P}\n\n\\begin{code}\ntype Pattern = Term                                                 --Matching\n\\end{code}\n\n\\begin{code}\ntype PBVS = BVS\n\\end{code}\n\n\\begin{code}\ntype Proof                                                            --Proofs\n  = ( String -- assertion name\n    , Assertion\n    , String -- Strategy\n    , Calculation -- Simple calculational proofs for now\n    )\n\\end{code}\n\n\\begin{code}\ndata Provenance                                                         --Laws\n  = Axiom          --  considered as `self-evidently` True\n  | Proven String  --  demonstrated by (named) proof\n  | Assumed        --  conjecture asserted w/o proof\n\\end{code}\n\n\\begin{code}\npattern PVal k             =  K P k                                      --AST\npattern PVar v            <-  V P v\npattern PCons n ts         =  C P n ts\npattern PBind n vs tm     <-  B P n vs tm\npattern PLam n vl tm      <-  L P n vl tm\npattern PSub tm s          =  S P tm s\npattern PIter na ni lvs    =  I P na ni lvs\npattern P2   n t1 t2       =  C P n [t1,t2]\n\\end{code}\n\n\\subsection{S}\n\n\\begin{code}\ndata SeqFocus = CLeft | CRight | Hyp Int                              --Proofs\n\\end{code}\n\n\\begin{code}\ndata Sequent                                                        --Sequents\n  = Sequent {\n     ante :: [Theory] -- antecedent theory context\n   , hyp :: Theory -- the goal hypotheses -- we can \"go\" here\n   , sc :: SideCond -- of the conjecture being proven.\n   , cleft :: Term -- never 'true' to begin with.\n   , cright :: Term -- often 'true' from the start.\n   }\n\\end{code}\n\n\\begin{code}\ndata Sequent'                                                       --Sequents\n  = Sequent' {\n      ante0 :: [Theory] -- context theories\n    , sc0       :: SideCond -- sequent side-condition\n    , laws'     :: Laws'\n    }\n\\end{code}\n\n\\begin{code}\ntype SeqZip = (TermZip, Sequent')                                   --Sequents\n\\end{code}\n\n\\begin{code}\ntype SideCond = ( [AtmSideCond]  -- all must be true                 --VarData\n                , VarSet )       -- must be fresh\n\\end{code}\n\n\n\\begin{code}\ntype Subscript = String                                            --Variables\n\\end{code}\n\n\\begin{code}\ndata Substn --  pair-sets below are unique in fst part                  --AST\n  = SN TermSub LVarSub\n\\end{code}\n\n\\subsection{T}\n\n\\begin{code}\ndata Term                                                                --AST\n = K TermKind Value                    -- Value\n | V TermKind Variable                 -- Variable\n | C TermKind Identifier [Term]        -- Constructor\n | B TermKind Identifier VarSet Term   -- Binder (unordered)\n | L TermKind Identifier VarList Term  -- Binder (ordered)\n | X Identifier Term                   -- Closure (always a predicate)\n | S TermKind Term Substn              -- Substitution\n | I TermKind                          -- Iterator\n     Identifier  -- top grouping constructor\n     Identifier  -- component constructor, with arity a\n     [ListVar]   -- list-variables, same length as component arity\n | ET Type                              -- Embedded TypeVar\npattern Val  tk k          =   K tk k\npattern Var  tk v          <-  V tk v\npattern Cons tk n ts       =   C tk n ts\npattern Bnd  tk n vs tm    <-  B tk n vs tm\npattern Lam  tk n vl tm    <-  L tk n vl tm\npattern Cls     n    tm    =   X n tm\npattern Sub  tk tm s       =   S tk tm s\npattern Iter tk na ni lvs  =   I tk na ni lvs\npattern Typ  typ           =   ET typ\n\\end{code}\n\n\\newpage\n\\begin{code}\ndata Term'                                                        --TermZipper\n  = Cons'   TermKind Identifier [Term] -- terms before focus, reversed\n                                [Term] -- terms after focus\n  | Bnd'   TermKind Identifier VarSet\n  | Lam'    TermKind Identifier VarList\n  | Cls'             Identifier\n  | Sub'    TermKind Substn\n  | Substn' TermKind Term LVarSub TermSubL  -- subst-pairs before, reversed\n                                  Variable -- focus target variable\n                                  TermSubL  -- subst-pairs after focus\n\\end{code}\n\n\\begin{code}\ndata TermKind                                                            --AST\n = P -- predicate\n | E Type -- expression (with type annotation)\n\\end{code}\n\n\\begin{code}\ntype TermSub = Set (Variable,Term) -- target/replacememt                --AST\n\\end{code}\n\n\n\\begin{code}\ntype TermSubL = [(Variable, Term)]                              --TermZipper\n\\end{code}\n\n\\begin{code}\ntype TermZip = (Term,[Term'])                                    --TermZipper\n\\end{code}\n\n\\begin{code}\ndata Theories\n  = Theories { tmap :: TheoryMap\n             , sdag :: SDAG String }\n\\end{code}\n\n\\begin{code}\ndata Theory                                                         --Theories\n  = Theory {\n      thName   :: String\n    , thDeps   :: [String]\n    , known    :: VarTable\n    , subable  :: SubAbilityMap\n    , laws     :: [Law]\n    , proofs   :: [Proof]\n    , conjs    :: [NmdAssertion]\n    }\n\\end{code}\n\n\\begin{code}\ntype TheoryMap = Map String Theory                                  --Theories\n\\end{code}\n\n\\begin{code}\ndata Token                                                         -- LexBase\n = TA String\n | TI Identifier\npattern ArbTok s = TA s\npattern IdTok i = TI i\n\\end{code}\n\n\\begin{code}\ntype Txt = String                                                        --AST\n\\end{code}\n\n\n\\begin{code}\ndata Type -- most general types first                                   --AST\n = T  -- arbitrary type\n | TV Identifier -- type variable\n | TC Identifier [Type] -- type constructor, applied\n | TA Identifier [(Identifier,[Type])] -- algebraic data type\n | TF Type Type -- function type\n | TG Identifier -- given type\npattern ArbType = T\npattern TypeVar i  = TV i\npattern TypeApp i ts = TC i ts\npattern DataType i fs = TA i fs\npattern FunType tf ta = TF tf ta\npattern GivenType i = TG i\n\\end{code}\n\n\n\\subsection{V}\n\n\\begin{code}\ndata Value                                                               --AST\n = VB Bool\n | VI Integer\n | VT Txt\npattern Boolean b  =  VB b\npattern Integer i  =  VI i\npattern Txt     t  =  VT t\n\\end{code}\n\n\\begin{code}\ndata VarBind = BI Identifier | BV Variable | BT Term                 --Binding\npattern BindVar  v  =  BV v\npattern BindTerm t  =  BT t\n\\end{code}\n\n\\begin{code}\ntype VarBinding = M.Map (Identifier,VarClass) VarBind                --Binding\n\\end{code}\n\n\\begin{code}\ndata VarClass                                                     --Variables\n  = VO -- Observation\n  | VE -- Expression\n  | VP -- Predicate\npattern ObsV  = VO\npattern ExprV = VE\npattern PredV = VP\n\\end{code}\n\n\\begin{code}\nnewtype Variable  = VR (Identifier, VarClass, VarWhen)            --Variables\n\\end{code}\n\n\\begin{code}\ndata VarMatchRole -- Variable Matching Role                          --VarData\n  =  KC Term     -- Known Constant\n  |  KV Type     -- Known Variable\n  |  KG          -- Generic Variable\n  |  KI Variable -- Instance Variable ! variable must be known as generic\n  |  UV          -- Unknown Variable\npattern KnownConst trm = KC trm\npattern KnownVar typ   = KV typ\npattern GenericVar     = KG\npattern InstanceVar v  = KI v\npattern UnknownVar     = UV\n\\end{code}\n\n\n\\begin{code}\ndata VarWhen -- Variable role                                      --Variables\n  = WS            --  Static\n  | WB            --  Before (pre)\n  | WD Subscript  --  During (intermediate)\n  | WA            --  After (post)\n  | WT            --  Textual\npattern Static    =  WS\npattern Before    =  WB\npattern During n  =  WD n\npattern After     =  WA\npattern Textual   =  WT\n\\end{code}\n\n\n% ==========================================================================\n\\section{By Module}\n\n\\subsection{LexBase}\n\n\\begin{code}\ndata Identifier = Id String Int                                    -- LexBase\npattern Identifier nm u <- Id nm u\n\\end{code}\n\n\n\\begin{code}\ndata Token                                                         -- LexBase\n = TA String\n | TI Identifier\npattern ArbTok s = TA s\npattern IdTok i = TI i\n\\end{code}\n\n\\subsection{Variables}\n\n\\begin{code}\ndata VarClass                                                     --Variables\n  = VO -- Observation\n  | VE -- Expression\n  | VP -- Predicate\npattern ObsV  = VO\npattern ExprV = VE\npattern PredV = VP\n\\end{code}\n\n\\begin{code}\ntype Subscript = String                                           --Variables\n\\end{code}\n\n\\begin{code}\ndata VarWhen -- Variable role                                     --Variables\n  = WS            --  Static\n  | WB            --  Before (pre)\n  | WD Subscript  --  During (intermediate)\n  | WA            --  After (post)\n  | WT            --  Textual\npattern Static    =  WS\npattern Before    =  WB\npattern During n  =  WD n\npattern After     =  WA\npattern Textual   =  WT\n\\end{code}\n\n\n\\begin{code}\nnewtype Variable  = VR (Identifier, VarClass, VarWhen)            --Variables\n\\end{code}\n\n\\begin{code}\ndata GenVar                                                        --Variables\n = GV Variable -- regular variable\n | GL ListVar  -- variable denoting a list of variables\npattern StdVar v = GV v\npattern LstVar lv = GL lv\ntype VarList = [GenVar]\ntype VarSet = Set GenVar\n\\end{code}\n\n\n\\subsection{AST}\n\n\\begin{code}\ntype TermSub = Set (Variable,Term) -- target/replacememt                --AST\ntype LVarSub = Set (ListVar,ListVar) -- target/replacement\ndata Substn --  pair-sets below are unique in fst part\n  = SN TermSub LVarSub\n\\end{code}\n\n\\newpage\n\\begin{code}\ndata Type -- most general types first                                   --AST\n = T  -- arbitrary type\n | TV Identifier -- type variable\n | TC Identifier [Type] -- type constructor, applied\n | TA Identifier [(Identifier,[Type])] -- algebraic data type\n | TF Type Type -- function type\n | TG Identifier -- given type\npattern ArbType = T\npattern TypeVar i  = TV i\npattern TypeApp i ts = TC i ts\npattern DataType i fs = TA i fs\npattern FunType tf ta = TF tf ta\npattern GivenType i = TG i\n\\end{code}\n\n\n\\begin{code}\ntype Txt = String                                                        --AST\ndata Value\n = VB Bool\n | VI Integer\n | VT Txt\npattern Boolean b  =  VB b\npattern Integer i  =  VI i\npattern Txt     t  =  VT t\n\\end{code}\n\n\\begin{code}\ndata TermKind                                                            --AST\n = P -- predicate\n | E Type -- expression (with type annotation)\n\\end{code}\n\n\\begin{code}\ndata Term                                                                --AST\n = K TermKind Value                    -- Value\n | V TermKind Variable                 -- Variable\n | C TermKind Identifier [Term]        -- Constructor\n | B TermKind Identifier VarSet Term   -- Binder (unordered)\n | L TermKind Identifier VarList Term  -- Binder (ordered)\n | X Identifier Term                   -- Closure (always a predicate)\n | S TermKind Term Substn              -- Substitution\n | I TermKind                          -- Iterator\n     Identifier  -- top grouping constructor\n     Identifier  -- component constructor, with arity a\n     [ListVar]   -- list-variables, same length as component arity\n | ET Type                              -- Embedded TypeVar\npattern Val  tk k          =   K tk k\npattern Var  tk v          <-  V tk v\npattern Cons tk n ts       =   C tk n ts\npattern Bnd  tk n vs tm    <-  B tk n vs tm\npattern Lam  tk n vl tm    <-  L tk n vl tm\npattern Cls     n    tm    =   X n tm\npattern Sub  tk tm s       =   S tk tm s\npattern Iter tk na ni lvs  =   I tk na ni lvs\npattern Typ  typ           =   ET typ\n\\end{code}\n\n\n\\begin{code}\npattern EVal t k           =  K (E t) k                                  --AST\npattern EVar t v          <-  V (E t) v\npattern ECons t n ts       =  C (E t) n ts\npattern EBind t n vs tm   <-  B (E t) n vs tm\npattern ELam t n vl tm    <-  L (E t) n vl tm\npattern ESub t tm s        =  S (E t) tm s\npattern EIter t na ni lvs  =  I (E t) na ni lvs\n\\end{code}\n\n\\newpage\n\\begin{code}\npattern PVal k             =  K P k                                      --AST\npattern PVar v            <-  V P v\npattern PCons n ts         =  C P n ts\npattern PBind n vs tm     <-  B P n vs tm\npattern PLam n vl tm      <-  L P n vl tm\npattern PSub tm s          =  S P tm s\npattern PIter na ni lvs    =  I P na ni lvs\n\\end{code}\n\n\\begin{code}\npattern E2 t n t1 t2  = C (E t) n [t1,t2]                                --AST\npattern P2   n t1 t2  = C P     n [t1,t2]\n\\end{code}\n\n\n\\subsection{VarData}\n\n\\begin{code}\ndata VarMatchRole -- Variable Matching Role                          --VarData\n  =  KC Term     -- Known Constant\n  |  KV Type     -- Known Variable\n  |  KG          -- Generic Variable\n  |  KI Variable -- Instance Variable ! variable must be known as generic\n  |  UV          -- Unknown Variable\npattern KnownConst trm = KC trm\npattern KnownVar typ   = KV typ\npattern GenericVar     = KG\npattern InstanceVar v  = KI v\npattern UnknownVar     = UV\n\\end{code}\n\n\\begin{code}\ndata LstVarMatchRole -- ListVar Matching Roles                       --VarData\n = KL VarList        -- Known Variable-List, all of which are themselves known\n      [Variable]     -- full expansion\n      Int            -- length of full expansion\n | KS VarSet         -- Known Variable-Set, all of which are themselves known\n      (Set Variable) -- full expansion\n      Int            -- size of full expansion\n | AL                -- Abstract Known Variable-List\n | AS                -- Abstract Known Variable-Set\n | UL                -- Unknown List-Variable\npattern KnownVarList vl vars len  =  KL vl vars len\npattern KnownVarSet  vs vars siz  =  KS vs vars siz\npattern AbstractList              =  AL\npattern AbstractSet               =  AS\npattern UnknownListVar            =  UL\n\\end{code}\n\n\\subsection{SideCond}\n\n\\begin{code}\ndata AtmSideCond                                                    --SideCond\n = SD  GenVar VarSet -- Disjoint\n | SS  GenVar VarSet -- Superset (covers)\n | SP  GenVar        -- Pre\npattern Disjoint gv vs = SD  gv vs  --  vs `intersect`  gv = {}\npattern Covers   gv vs = SS  gv vs  --  vs `supersetof` gv\npattern IsPre    gv    = SP  gv     --  gv is pre-condition\n\\end{code}\n\n\\begin{code}\ntype SideCond = ( [AtmSideCond]  -- all must be true                 --VarData\n                , VarSet )       -- must be fresh\n\\end{code}\n\n\\begin{code}\ntype Assertion = (Term, SideCond)                                    --VarData\n\\end{code}\n\n\\subsection{Laws}\n\n\\begin{code}\ndata LogicSig                                                           --Laws\n  = LogicSig\n     { theTrue  :: Term\n     , theFalse :: Term\n     , theEqv   :: Identifier\n     , theImp   :: Identifier\n     , theAnd   :: Identifier\n     , theOr    :: Identifier\n     }\n\\end{code}\n\n\\begin{code}\ndata LeftRight = Lft | Rght                                             --Laws\n\ndata GroupSpec                                                          --Laws\n  = Assoc LeftRight\n  | Gather LeftRight Int\n  | Split Int\n\\end{code}\n\n\\begin{code}\ntype NmdAssertion = (String,Assertion)                                  --Laws\n\\end{code}\n\n\\begin{code}\ndata Provenance                                                         --Laws\n  = Axiom          --  considered as `self-evidently` True\n  | Proven String  --  demonstrated by (named) proof\n  | Assumed        --  conjecture asserted w/o proof\n\\end{code}\n\n\\begin{code}\ntype Law = (NmdAssertion,Provenance)                                    --Laws\n\\end{code}\n\n\\subsection{Binding}\n\n\\begin{code}\ndata VarBind = BI Identifier | BV Variable | BT Term                 --Binding\npattern BindVar  v  =  BV v\npattern BindTerm t  =  BT t\ntype VarBinding = M.Map (Identifier,VarClass) VarBind\n\\end{code}\n\n\\begin{code}\ndata LstVarBind                                                      --Binding\n = BL  VarList\n | BS  VarSet\n | BX  [LVarOrTerm]\npattern BindList vl      =  BL vl\npattern BindSet  vs      =  BS vs\npattern BindTLVs tlvs    =  BX tlvs\ntype ListVarKey = (Identifier,VarClass,[Identifier],[Identifier])\ntype ListVarBinding = M.Map ListVarKey LstVarBind\n\\end{code}\n\n\\subsection{Matching}\n\n\\begin{code}\ntype Pattern = Term                                                 --Matching\ntype Candidate = Term\ntype BVS = Set GenVar\ntype PBVS = BVS\ntype CBVS = BVS\n\\end{code}\n\n\\subsection{TermZipper}\n\n\\begin{code}\ntype TermSubL = [(Variable, Term)]                              --TermZipper\n\\end{code}\n\n\\begin{code}\ndata Term'                                                        --TermZipper\n  = Cons'   TermKind Identifier [Term] -- terms before focus, reversed\n                                [Term] -- terms after focus\n  | Bnd'   TermKind Identifier VarSet\n  | Lam'    TermKind Identifier VarList\n  | Cls'             Identifier\n  | Sub'    TermKind Substn\n  | Substn' TermKind Term LVarSub TermSubL  -- subst-pairs before, reversed\n                                  Variable -- focus target variable\n                                  TermSubL  -- subst-pairs after focus\n\\end{code}\n\n\\begin{code}\ntype TermZip = (Term,[Term'])                                    --TermZipper\n\\end{code}\n\n\\subsection{Proofs}\n\n\\begin{code}\ndata MatchClass                                                       --Proofs\n  = MA       -- match all of law, with replacement 'true'\n  | ME [Int] -- match subpart of 'equiv' chain\n  | MIA      -- match implication antecedent A, replacement A /\\ C\n  | MIC      -- match implication consequent C, replacement A \\/ C\n  -- MEV should be last, so these matches rank low by default\n  | MEV Int  -- match PredVar at given position\npattern MatchAll       = MA\npattern MatchEqv is    = ME is\npattern MatchAnte      = MIA\npattern MatchCnsq      = MIC\npattern MatchEqvVar i  = MEV i\n\\end{code}\n\n\\begin{code}\ndata HowUsed                                                          --Proofs\n  = ByMatch MatchClass  -- replace focus with binding(match)\n  | ByInstantiation     -- replace focus=true with binding(law)\n\\end{code}\n\n\\begin{code}\ndata SeqFocus = CLeft | CRight | Hyp Int                              --Proofs\n\\end{code}\n\n\\begin{code}\ndata Justification                                                    --Proofs\n  = UseLaw             -- used a law\n      HowUsed              -- how law was used in proof step\n      String               -- law name\n      Binding              -- binding from law variables to goal components\n      [Int]                -- zipper descent arguments\n  | Substitute         -- performed a substitution\n      [Int]                -- zipper descent arguments\n  | NormQuant          -- performed a quantifier normalisation\n      [Int]                -- zipper descent arguments\n  | NestSimp           -- simplified nested quantifiers\n      [Int]                -- zipper descent arguments\n  | Switch             -- switched focus at sequent level\n      SeqFocus             -- focus before switch -- needed to reverse this.\n      SeqFocus             -- focus after switch\n  | CloneH Int         --  Cloned hypothesis i\n  | Flatten Identifier -- flattened use of associative operator\n  | Associate          -- grouped use of an associative operator\n      Identifier           -- operator\n      GroupSpec            -- grouping details.\n\\end{code}\n\n\\begin{code}\ntype CalcStep                                                         --Proofs\n  = ( Justification  -- step justification\n    , Assertion )         -- previous term\n\\end{code}\n\n\\begin{code}\ntype Calculation                                                      --Proofs\n  = ( Term -- end (or current) term\n    , [ CalcStep ] )  -- calculation steps, in proof order\n\\end{code}\n\n\\begin{code}\ntype Proof                                                            --Proofs\n  = ( String -- assertion name\n    , Assertion\n    , String -- Strategy\n    , Calculation -- Simple calculational proofs for now\n    )\n\\end{code}\n\n\n\\subsection{Theories}\n\n\\begin{code}\ndata Theory                                                         --Theories\n  = Theory {\n      thName   :: String\n    , thDeps   :: [String]\n    , known    :: VarTable\n    , subable  :: SubAbilityMap\n    , laws     :: [Law]\n    , proofs   :: [Proof]\n    , conjs    :: [NmdAssertion]\n    }\n\\end{code}\n\n\\begin{code}\ntype TheoryMap = Map String Theory                                  --Theories\ndata Theories\n  = Theories { tmap :: TheoryMap\n             , sdag :: SDAG String }\n\\end{code}\n\n\\subsection{Sequents}\n\n\\begin{code}\ndata Sequent                                                        --Sequents\n  = Sequent {\n     ante :: [Theory] -- antecedent theory context\n   , hyp :: Theory -- the goal hypotheses -- we can \"go\" here\n   , sc :: SideCond -- of the conjecture being proven.\n   , cleft :: Term -- never 'true' to begin with.\n   , cright :: Term -- often 'true' from the start.\n   }\n\\end{code}\n\n\\newpage\n\\begin{code}\ndata Laws'                                                          --Sequents\n  = CLaws' { -- currently focussed on conjecture component\n      hyp0  :: Theory -- hypothesis theory\n    , whichC :: LeftRight -- which term is in the focus\n    , otherC :: Term  -- the term not in the focus\n    }\n  | HLaws' { -- currently focussed on hypothesis component\n      hname     :: String -- hyp. theory name\n    , hknown    :: VarTable\n    , hbefore   :: [Law] -- hyp. laws before focus (reversed)\n    , fhName    :: String -- focus hypothesis name\n    , fhSC      :: SideCond -- focus hypothesis sc (usually true)\n    , fhProv    :: Provenance -- focus hypothesis provenance (?)\n    , hOriginal :: Term -- the original form of the focus hypothesis\n    , hafter    :: [Law] -- hyp. laws after focus\n    , cleft0    :: Term -- left conjecture\n    , cright0   :: Term -- right conjecture\n    }\n\\end{code}\n\n\n\\begin{code}\ndata Sequent'                                                       --Sequents\n  = Sequent' {\n      ante0 :: [Theory] -- context theories\n    , sc0       :: SideCond -- sequent side-condition\n    , laws'     :: Laws'\n    }\n\\end{code}\n\n\n\\begin{code}\ntype SeqZip = (TermZip, Sequent')                                   --Sequents\n\\end{code}\n\n\\subsection{LiveProofs}\n\n\\begin{code}                                                      --LiveProofs\ndata Match\n = MT { mName  ::  String     -- assertion name\n      , mAsn   ::  Assertion  -- matched assertion\n      , mClass ::  MatchClass -- match class\n      , mBind  ::  Binding    -- resulting binding\n      , mLocSC ::  SideCond   -- goal side-condition local update\n      , mLawSC ::  SideCond   -- law side-condition mapped to goal\n      , mRepl  ::  Term       -- replacement term\n      }\n\\end{code}\n\n\\begin{code}\ntype MatchContext                                                 --LiveProofs\n  = ( String       -- Theory Name\n    , [Law]        -- all laws of this theory\n    , [VarTable] ) -- all known variables here, and in dependencies\n\\end{code}\n\n\\begin{code}\ndata LiveProof                                                    --LiveProofs\n  = LP {\n      conjThName :: String -- conjecture theory name\n    , conjName :: String -- conjecture name\n    , conjecture :: Assertion -- assertion being proven\n    , conjSC :: SideCond -- side condition\n    , strategy :: String -- strategy\n    , mtchCtxts :: [MatchContext] -- current matching contexts\n    , focus :: SeqZip  -- current sub-term of interest\n    , fPath :: [Int] -- current term zipper descent arguments\n    , matches :: Matches -- current matches\n    , stepsSoFar :: [CalcStep]  -- calculation steps so far, most recent first\n    }\n\\end{code}\n\n\\begin{code}\ntype LiveProofs = Map (String,String) LiveProof                   --LiveProofs\n\\end{code}\n", "meta": {"hexsha": "7440cbefcbc92b539774c7d8ad62cc9e2943b2f1", "size": 32112, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/KeyTypes.tex", "max_stars_repo_name": "leomcclean/reasonEq", "max_stars_repo_head_hexsha": "86b4c70c4a2ca1d0f05b6d1384059f13e26abd2b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-10-02T15:29:38.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-23T23:06:56.000Z", "max_issues_repo_path": "doc/KeyTypes.tex", "max_issues_repo_name": "ConchuirORiain/reasonEq", "max_issues_repo_head_hexsha": "79a3513db4444d9ce4cf66cf8c53e614cbad7725", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/KeyTypes.tex", "max_forks_repo_name": "ConchuirORiain/reasonEq", "max_forks_repo_head_hexsha": "79a3513db4444d9ce4cf66cf8c53e614cbad7725", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-02-15T17:08:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-13T09:57:38.000Z", "avg_line_length": 31.2373540856, "max_line_length": 78, "alphanum_fraction": 0.5349090683, "num_tokens": 8002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.32814587438460197}}
{"text": "\\documentclass[../main]{subfiles}\n\\pagestyle{fancy}\n\n\\begin{document}\n\n\\chapter{Notation}\n\\thispagestyle{fancy}\n\n\\setlength{\\parindent}{18pt}\n\\begin{onehalfspacing}\n\n  We will denote the class of ordinals by $\\on$. For $X,Y$ sets we denote by ${^X}Y$ the set of all functions from $X$ to $Y$. For an infinite cardinal $\\kappa$, we let $H_\\kappa$ be the set of sets $X$ such that the cardinality of the transitive closure of $X$ is strictly less than $\\kappa$. $\\zf^-$ will denote $\\zf$ with the Collection scheme but without the Power Set axiom, following the results of \\cite{ZFwithoutPowerSet}. We write \\gbc\\ for G\\\"odel-Bernays class theory with the Axiom of Choice, and \\gb\\ for \\gbc\\ without the Axiom of Choice. The symbol $\\contr$ will denote a contradiction and $\\p(X)$ denotes the power set of $X$. We will sometimes denote elementary embeddings $\\pi\\colon(\\M,\\in)\\to(\\N,\\in)$ by simply $\\pi\\colon\\M\\to\\N$. Generally, $\\alpha,\\beta,\\gamma,\\zeta$ will denote ordinals and $\\kappa,\\lambda,\\theta,\\delta$ cardinals. We will always assume elementary embeddings to be non-trivial unless otherwise stated, meaning that the elementary embedding in question is not the identity. We will sometimes abuse notation and denote a generic extension $V[g]$ by simply $V^{\\mathbb P}$, where $g\\subset\\mathbb P$ is $V$-generic.\n\n\n\\end{onehalfspacing}\n\\setlength{\\parindent}{0pt}\n\n\\end{document}\n", "meta": {"hexsha": "fde9dc62a57e47b05ae6d4a5baca2da7bf6b623b", "size": 1388, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "frontbackmatter/notation.tex", "max_stars_repo_name": "saattrupdan/phd", "max_stars_repo_head_hexsha": "21481596be517c874e311797f5a70829e0cba7d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "frontbackmatter/notation.tex", "max_issues_repo_name": "saattrupdan/phd", "max_issues_repo_head_hexsha": "21481596be517c874e311797f5a70829e0cba7d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "frontbackmatter/notation.tex", "max_forks_repo_name": "saattrupdan/phd", "max_forks_repo_head_hexsha": "21481596be517c874e311797f5a70829e0cba7d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 73.0526315789, "max_line_length": 1154, "alphanum_fraction": 0.7391930836, "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.6001883592602049, "lm_q1q2_score": 0.3281458743846019}}
{"text": "\\section{Evaluation}\\label{sec:refinedhaskell:evaluation}\n\nOur goal is to build a practical and effective \nSMT \\& refinement type-based verifier for Haskell. \n%\nWe have shown that lazy evaluation requires the \nverifier to reason about divergence; we have proposed \nan approach for implicitly reasoning about divergence \nby eagerly proving termination, thereby optimizing \nthe precision of the verifier.\n%\nNext, we describe an experimental evaluation of our \napproach that uses \\toolname to prove termination \non the already verified libraries from Chapter~\\ref{chapter:tool}.\n%\nOur evaluation seeks to determine whether our approach is\n%\n\\emph{suitable} for a lazy language (\\ie do most Haskell functions terminate?),\n\\emph{precise}  enough to  capture the termination reasons (\\ie is \\toolname able to prove that most functions terminate?), \n\\emph{usable}   without placing an unreasonably high burden on the user in the form of explicit termination annotations, and\n\\emph{effective}  enough to  enable the verification of functional correctness properties.\n%\n\n%%\\spara{Implementation} \\toolname takes as input:\n%%%\n%%(1)~A Haskell \\emph{source} file, \n%%%\n%%(2)~Refinement type \\emph{specifications}, \n%%    including refined datatype definitions,\n%%    measures, predicate and type aliases,\n%%    and function signatures, and\n%%%\n%%(3)~Predicate fragments called \\emph{qualifiers}\n%%    which are used to infer refinement types using \n%%    the abstract interpretation framework of Liquid\n%%    Typing~\\cite{LiquidPLDI08}.\n%%%\n%%The verifier returns as output, \\textsc{Safe} or \\textsc{Unsafe}, \n%%depending on whether the code meets the specifications or not, \n%%and, importantly for debugging the code (or specification!) \n%%the inferred types for all sub-expressions.\n\n\\spara{Benchmarks}\nAs benchmarks, we used the following famous Haskell libraries:\n%\n\\texttt{GHC.List} and \\texttt{Data.List}, which implement many standard\nlist operations,\n\\texttt{Data.Set.Splay}, which implements an splay functional set,\n\\texttt{Data.Map.Base}, which implements a functional \nmap,\n\\libvectoralgos, \nwhich includes a suite of ``imperative'' % (\\ie monadic)\narray-based sorting algorithms,\n\\bytestring, a library for manipulating byte arrays, and\n\\libtext, a library for high-performance Unicode text processing. \n%\n%%These benchmarks represent a wide spectrum of idiomatic\n%%Haskell code: the first three are widely used libraries \n%%based on recursive data structures, the fourth and fifth \n%%perform subtle, low-level arithmetic manipulation of array\n%%indices and pointers, and the last is a rich, high-level\n%%library with sophisticated application-specific invariants,\n%%well outside the scope of Haskell's expressive type system.\n%%Thus, this suite provides a diverse and challenging test-bed \n%%for evaluating \\toolname.\nThe verification of functional correctness on our benchmarks\nis already discussed in~\\S~\\ref{sec:realworld:evaluation}. \n%\nHere we focus only on the extra proof obligations \nrequired to reason about function termination. \n\n\\input{text/refinedhaskell/results}\n\n\\spara{Results}\nTable~\\ref{table:realworldhaskell:results} summarizes our experiments, which \ncovered 39 modules totaling 10,209 non-comment lines of \nsource code. % and 1,652 lines of specifications.\n%\nThe results were collected on a machine with an Intel Xeon \nX5600 and 32GB of RAM~(no benchmark required more than 1GB).\n%\nTiming data was for runs that performed full\nverification of safety and functional correctness \nproperties in addition to termination. %; we only discuss the latter here.\n\n\\begin{itemize}\n  \\item{\\emph{Suitable:}} Our approach of eagerly proving termination is in\n    fact, \\emph{highly} suitable: of the % a total of 1,539 functions, including\n    504 recursive functions, only 12 functions were \\emph{actually}\n    non-terminating (\\ie non-inductive).\n    That is, 97.6\\% of recursive functions \n    % (or 99.1\\% of all functions)\n    are inductively defined.\n\n  \\item{\\emph{Precise:}} Our approach is extremely precise, as refinements\n    provide auxiliary invariants and extensibility that is crucial for \n    proving termination. We successfully \\emph{prove} that 96.0\\% of \n    recursive functions % (or 98.6\\% of all functions)\n    terminate. \n    % (Of the 8 that we fail on, 1 terminates for reasons not fully clear to us!)\n\n  \\item{\\emph{Usable:}} Our approach is highly usable and only places a \n    modest annotation burden on the user. The default metric, namely the first \n    parameter with an associated size measure, suffices to automatically \n    prove 65.7\\% of recursive functions terminating. Thus, only 34.3\\% require \n    explicit termination metric, totaling about 1.7 witnesses (about 1 line\n    each) per 100 lines of code.\n\n  \\item{\\emph{Effective:}} Our approach is extremely effective at improving the\n    precision of the overall verifier (by allowing the VC to use facts\n    about binders that provably reduce to values).\n    % As shown in the \\textbf{Err} column in Table~\\ref{table:results}, \n    Without the termination optimization, \\ie by only using information \n    for matched-binders (thus in WHNF), \\toolname reports 1,395 \n    unique functional correctness warnings -- about 1 per 7 lines.\n    With termination information, this number goes to zero.\n\\end{itemize}\n\n\n\n\\begin{comment}\n\n\nNext, we present a qualitative overview of how to prove termination\nproperties using \\toolname.\n\\subsection{Proving Termination with Refinements}\n\\label{sec:proving-termination-with-refinements}\n{\n\n% 1. Nats\n% 2. structural recursion on Lists\n% 3. auxiliary invariants that need ghost variables or termination\n% expressions, e.g. list merge\n% 4. Bytestring\n\\ES{Assuming we have already outlined the approach with sized types\n  encoded via refinements in the overview.}\n\nLet us begin with one of the simplest recursive functions, the\nfibonacci function.\n%\n\\begin{code}\n  fib  :: Nat -> Int\n  fib 0 = 1\n  fib 1 = 1\n  fib n = fib (n-1) + fib (n-2)\n\\end{code}\n%\nRecall that we have simply defined @Nat@ as @{v:Int | v>=0}@. In\nthis case, the argument @n@ can itself be used as the termination\nmetric. The precondition ensures that @n@ will be non-negative, \\ie\n@n@ is \\emph{well-founded}, and \\toolname knows from the type of\n@(-)@ that @n-1@ and @n-2@ are both strictly less than @n@, therefore\n@fib@ \\emph{must} terminate. \n\nNot all recursive functions on @Nat@s have such simple termination\nmetrics, one famous example is the Ackermann function.\n%\n\\begin{code}\n  ack m n \n    | m == 0    = n + 1\n    | n == 0    = ack (m-1) 1 \n    | otherwise = ack (m-1) (ack m (n-1))\n\\end{code}\n%\nNeither @m@ nor @n@ can be shown to decrease in each recursive call,\nhowever @ack@ can still be proven terminating because \\emph{either}\n@m@ decreases \\emph{or} @m@ remains the same and @n@ decreases. In\nother words, the pair @(m,n)@ strictly decreases according to a\nwell-founded \\emph{lexicographic} ordering. We express lexicographic\ntermination in \\toolname using \\emph{termination expressions}, which\ntake the form @x :: t / e@ where @e@ is a list of \\toolname\nexpressions that should be used to prove termination. In the case of\n@ack@ the expressions will simply be references to the parameters @m@\nand @n@\n%\n\\begin{code}\n  ack :: m:Nat -> n:Nat -> Nat / [m,n]\n\\end{code}\n%\nencoding the requirement that @(m,n)@ is a lexicographically\ndecreasing pair.\n\n\\spara{Measuring the Size of Structures}\nMany functions are structurally recursive and can be proven\nterminating by showing that they always recur on a \\emph{substructure}.\nConsider the function @map@ defined over the standard list type.\n%\n\\begin{code}\n  map f []     = [] \n  map f (x:xs) = f x : map f xs\n\\end{code}\n%\nIn @map@, the recursive call is made with a ``smaller'' input.\nWe formalize the notion of size with \\emph{measures}.\n%\n\\begin{code}\n  measure len :: [a] -> Nat\n  len []     = 0\n  len (x:xs) = 1 + len xs\n\\end{code}\n%\nWith the above definition, \nthe @measure@ strengthens the type of the data constructors to:\n%\n\\begin{code}\n  []  :: {v: [a] | len v = 0}\n  (:) :: x:a -> xs:[a]\n      -> {v:[a] | len v = 1 + len xs}\n\\end{code}\n%\nwhere @len@ is simply an uninterpreted function in the SMT\nlogic~\\cite{LiquidPLDI09}. With the strengthened data constructors,\n\\toolname happily proves that @map@ is always called recursively with\nsmaller inputs\\footnote{\\toolname defaults to the second parameter\n  here for proving termination because it has no notion of the size of\n  a function.}, and that the input size is bounded below by 0,\ntherefore it must terminate.\n\\spara{Expressing Termination} \nSometimes, the decreasing metric cannot be associated with a single\nparameter or lexicographically ordered sequence of parameters, but is\ninstead an auxiliary value that is a \\emph{function} of the\nparameters.\n%\nFor example, here is the @union@ function from the splay-tree-based\nset library\n%\n\\begin{code}\n  union Leaf         t = t\n  union (Node x a b) t = Node x taa tbb\n    where \n      taa          = union ta a\n      tbb          = union tb b\n      (ta, _, tb)  = split x t\n\\end{code}\n%\nwhich uses the following datatype:\n%\n\\begin{code}\n  data Splay a = Leaf \n               | Node a (Splay a) (Splay a)\n\\end{code}\n%\nHere, as the recursive call ``swaps'' the parameters, \\ie the first\n(resp. second) argument of the recursive call is computed from the\nsecond (resp. first) parameter, neither parameter provably decreases,\nnor do they form a lexicographically-ordered pair.\n%\nHowever, on closer inspection it turns out that the \\emph{sum}\nof the sizes of the trees strictly decreases, as @split@ has type\n%\n\\begin{code}\n  a -> t:Splay a -> (SplayL a t, SplayL a t)\n\\end{code}\n%\nwhere the output type uses the alias\n%\n\\begin{code}\n  type SplayL a T \n    = {v:Splay a | size v <= size T}\n\\end{code}\n%\nand @size@ is a \\emph{measure} akin to @len@.\n%\n\\begin{code}\n  measure size     :: Splay a -> Nat\n  size Leaf         = 0\n  size (Node v l r) = 1 + size l + size r\n\\end{code}\n%\nWe already know how to express this type of termination metric using\nour handy termination expressions, so we give @union@ the following type:\n%\n\\begin{code}\n  union :: Ord a => x:Splay a -> y:Splay a\n        -> Splay a / [size x + size y]\n\\end{code}\n\n% For example, here is the standard @merge@ function from the eponymous sorting\n% procedure:\n% %\n% \\begin{code}\n%     merge xs@(x:xs') ys@(y:ys') \n%       | x < y     = x : merge xs' ys\n%       | otherwise = y : merge xs  ys'\n% \\end{code}\n% %\n% neither parameter provably decreases in both calls, but the \\emph{sum}\n% of the sizes of the parameters strictly decreases. \n\n% In these cases, we can reuse our termination expression syntax from\n% above, but with a more complex expression.\n% %\n% \\begin{code}\n%     merge :: xs:[a] -> ys:[a] -> [a] \n%           / [len xs + len ys]\n% \\end{code}\n% %\n% This is equivalent to rewriting @merge@ to take a \\emph{ghost}\n% parameter that acts as a termination witness, \\eg\n% %\n% \\begin{code}\n%     merge :: xs:[a] -> ys:[a] \n%           -> {v:Nat | v = len xs + len ys} \n%           -> [a] \n% \\end{code}\n% %\n% except that with the termination expression, one need not modify the\n% actual code! Now, \\toolname verifies that in each recursive call the\n% expression @len xs + len ys@ is strictly smaller, thereby proving that\n% @merge@ terminates.\n\n\\spara{Pointer-based Termination}\nFor our last example we will look at the \\bytestring\nlibrary. \\bytestring is an interesting target for our termination\nexperiments because proving termination of \\bytestring functions often\nrequires reasoning about the length of the memory segment that a\npointer points to.\n\nA (strict) @ByteString@ is a triple of a @pay@load pointer, \nan @off@set into the memory buffer referred to by the pointer \n(at which the string actually ``begins'') and a @len@gth \ncorresponding to the number of bytes in the string, which is \nthe size of the buffer \\emph{after} the @off@set, that\ncorresponds to the string.\n%\nWe define a measure for the \\emph{size} of \na @ForeignPtr@'s buffer, and use it to define \nthe key invariants as a refined datatype \n%\n\\begin{code}\n  measure fplen  :: ForeignPtr a -> Nat\n  data ByteString = PS\n   { pay :: ForeignPtr Word8\n   , off :: {v:Nat | v       <= fplen pay}\n   , len :: {v:Nat | off + v <= fplen pay} \n   }\n\\end{code}\n%\n\\ES{can probably kill this para about invariants if we need space}\nThe definition states that \nthe offset is a @Nat@ no bigger than the size of \nthe @payload@'s buffer, and that\nthe sum of the @off@set and non-negative @len@gth\nis no more than the size of the payload buffer.\nFinally, we encode a @ByteString@'s size as a measure.\n%\n\\begin{code}\n  measure blen   :: ByteString -> Nat\n  blen (PS p o l) = l\n\\end{code}\n\nConsider the function @findIndex@, which searches through a\n@ByteString@ for a @Word8@ that satisfies some predicate @p@.\n\n\\begin{code}\n  findIndex p (PS x s l) = inlinePerformIO $ \n    withForeignPtr x $ \\f -> \n      go l (f `plusPtr` s) 0\n  where\n    go :: ptr:_ -> n:_ -> _ / [l - n]\n    go ptr n\n      | n >= l    = return Nothing\n      | otherwise = do \n          w <- peek ptr\n          if p w\n            then return (Just n)\n            else go (ptr `plusPtr` 1) (n+1)\n\\end{code}\n\nThe bulk of the work is done by the recursive inner function @go@,\nwhich repeatedly increments @ptr@ until it finds an appropriate byte\nor it reaches the end of the valid memory region. We use @l - n@ as\nthe termination metric for @go@, which denotes the number of bytes\nremaining in the valid memory region.\n\n\\spara{Nested Data}\nFor our final example, consider @group@, which\nsplits a string like @\"aart\"@ into the list\n@[\"aa\",\"r\",\"t\"]@.\n% , \\ie a list of\n% (a)~non-empty @ByteString@s whose \n% (b)~total length equals that of the input. \n% To specify these requirements, we define a measure for \n% the total length of strings in a list and use it to\n% write an alias for a list of \\emph{non-empty} strings\n% whose total length equals that of another string:\n\n% \\begin{code}\n% measure blens :: [ByteString] -> Int \n% blens ([])     = 0\n% blens (x:xs)   = blen x + blens xs\n\n% type ByteStringNE \n%   = {v:ByteString | blen v > 0}\n% type ByteStringsEq B\n%   = {v:[ByteStringNE] | blens v = blen b}\n% \\end{code}\n%\n% \\toolname uses the above to verify that \n%\n\\begin{code}\n  group xs\n    | null xs   = []\n    | otherwise = (y `cons` ys) : group zs\n    where\n      x         = unsafeHead xs\n      xs'       = unsafeTail xs\n      (ys, zs)  = spanByte x xs' \n\\end{code}\n%\nThis example illustrates why refinements are critical for\nproving termination. \\toolname determines that @unsafeTail@ \nreturns a \\emph{shorter} @ByteString@ than its input, and that\neach element returned by @spanByte@ is no longer than the \ninput, concluding that @zs@ is smaller than @xs@, and hence\nchecking the body under the termination-weakened environment.\n\n\\ES{figure out why things break when we change spanByte to use term exprs}\n\nLet's also look at @spanByte@, which splits strings into a pair, to\nsee how \\toolname infers its crucial type:\n%\n\\begin{code}\n  spanByte c ps@(PS x s l) \n    = inlinePerformIO $ withForeignPtr x $\n        \\p -> go (p `plusPtr` s) 0\n    where\n      go :: p:_ -> i:_ -> _ / [l - i]\n      go p i \n        | i >= l    = return (ps, empty)\n        | otherwise = do\n            c' <- peekByteOff p i\n            if c /= c'\n            then let b1 = unsafeTake i ps\n                     b2 = unsafeDrop i ps\n                 in  return (b1, b2)\n            else go p (i+1)\n\\end{code}\n%\nHere again, the work is all done by the inner recursive function @go@,\nwhich uses the same termination metric as above. \\toolname can \ninfer that both @ByteString@s in the pair are no longer than @ps@\nthrough a case analysis. In the base case, @blen ps <= blen ps@ and \n@blen empty <= blen ps@ both hold trivially, and in the recursive case\n@blen b1 <= blen ps@ and @blen b2 <= blen ps@ both hold because\n\\toolname infers that @unsafeTake@ and @unsafeDrop@ both\nreturn shorter strings. Thus, both @ByteString@s returned by\n@spanByte@ are at most as long as its input @xs'@, which is\n\\emph{strictly} shorter than the input to @group@; therefore @group@\nis only called recursively on smaller inputs and it must terminate!\n\nSo the bright side is that, although sound and precise refinements in\na lazy language incurs the additional burden of termination proofs,\nrefinements make proving termination easy!\n\n\\end{comment}\n\n%%% Local Variables: \n%%% mode: latex\n%%% TeX-master: \"main\"\n%%% End: \n", "meta": {"hexsha": "21d148303e271110dd5ab5654cd203e0e8dc5289", "size": 16458, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "text/refinedhaskell/evaluation.tex", "max_stars_repo_name": "nikivazou/thesis", "max_stars_repo_head_hexsha": "a12f2e857a358e3cc08b657bb6b029ac2d500c3b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2016-12-02T00:46:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-20T07:04:01.000Z", "max_issues_repo_path": "text/refinedhaskell/evaluation.tex", "max_issues_repo_name": "nikivazou/thesis", "max_issues_repo_head_hexsha": "a12f2e857a358e3cc08b657bb6b029ac2d500c3b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "text/refinedhaskell/evaluation.tex", "max_forks_repo_name": "nikivazou/thesis", "max_forks_repo_head_hexsha": "a12f2e857a358e3cc08b657bb6b029ac2d500c3b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-12-02T00:46:51.000Z", "max_forks_repo_forks_event_max_datetime": "2016-12-02T00:46:51.000Z", "avg_line_length": 35.6233766234, "max_line_length": 124, "alphanum_fraction": 0.7056142909, "num_tokens": 4492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.3278524180688653}}
{"text": "\\section{Implementation}\n\\label{sec:implementation}\n\nThe RZ implementation consists of several sequential passes.\n\nAfter the initial parsing, a \\emph{type reconstruction} phase checks\nthat the input is well-typed%\n\\iflong \n\\ (and checks for well-formedness to the\nextent that it is easily decidable)%\n\\fi\n, and if successful produces an\nannotated result with all variables explicitly tagged with types. The\ntype checking phase uses a system of dependent types, with limited\nsubtyping (implicit coercions) for sum types and subset types. \n\\iflong\nThe\ndetails are fairly standard, so are omitted here. One non-obvious\nconsequence of the realizability translation, however, is that the\nsubset types with logically equivalent predicates, e.g.,\n$\\isubset{\\ix}{\\iS}{\\iand{\\ipp_1(\\ix)}{\\ipp_2(\\ix)}}$ and\n$\\isubset{\\ix}{\\iS}{\\iand{\\ipp_2(\\ix)}{\\ipp_1(\\ix)}}$ are isomorphic\nbut not equal in general. An\nexplicit coercion is required to go from one type to the other,\nbecause subset values will be pairs containing realizers for\n$\\iand{\\ipp_1(\\ix)}{\\ipp_2(\\ix)}$ and\n$\\iand{\\ipp_2(\\ix)}{\\ipp_1(\\ix)}$, and these realizers have\npotentially different types $|\\ipp_1(\\ix)| * |\\ipp_2(\\ix)|$ and\n$|\\ipp_2(\\ix)| * |\\ipp_1(\\ix)|$ respectively.\n\\fi % \\iflong\n\nNext the realizability translation is performed as described in\nSection~\\ref{sec:translation}, producing interface code. The\nflexibility of the full input language (e.g., $n$-ary sum types and\ndependent product types) makes the translation code fairly involved,\nand so it is performed in a ``naive'' fashion whenever possible. The\nimmediate result of the translation is not easily readable.\n \nThus, up to four more passes simplify the output before it is displayed to\nthe user. A \\emph{thinning} pass removes all references to trivial\nrealizers produced by stable formulas.\n\\iflong\nFor example, direct translation\nof the $\\mathtt{free}$ axiom in the output for Kuratowski-finite sets,\nsee Figure~\\ref{fig:kuratowski} and Section~\\ref{sec:finite-sets},\nyields a value specification for $\\mathtt{free}$ of type\n%\n\\begin{equation*}\n  (\\f{A.a} \\to \\f{S.s}) \\to \n  (\\f{fin} \\to \\f{S.s}) * (\\ounit * (\\f{A.a} \\to\n  \\ounit) *\n  (\\f{fin} \\to \\f{fin} \\to \\ounit))\n\\end{equation*}\n%\nwhere $\\ounit$ is the unit (terminal) type classifying the trivial\nrealizer. Thinning replaces this by the isomorphic type\n%\n\\begin{equation*}\n  (\\f{A.a} \\to \\f{S.s}) \\to \\f{fin} \\to \\f{S.s}\n\\end{equation*}\n%\nand appropriately modifies references to $\\f{free}$ in the assertions to account for this change in type.\n\n\\fi % \\iflong\n%\nAn \\emph{optimization} pass applies an ad-hoc collection of\nbasic logical and term simplifications in order to make the output more readable. \n\\iflong\nLogical simplifications include applications of truth table rules\n($\\iand{\\itrue}{\\ip}$ becomes $\\ip$), detection of syntactically\nidentical premises and conclusions\n($\\iimply{\\ip_1}{\\iand{\\ip_1}{\\ip_2}}$ becomes\n$\\iimply{\\ip_1}{\\ip_2}$), and optimization of other common patterns we have\nseen arise\n($\\iforall{\\ix}{\\is}{\\iimply{(\\iequal{\\ix}{\\ie})}{\\ipp(\\ix)}}$ becomes\n$\\ipp(\\ie)$).\n\\fi % \\iflong\nSome redundancy may remain, but in practice the optimization pass\nhelps significantly.\n\nFinally, the user can specify two optional steps occur.\nRZ can perform a \\emph{phase-splitting} pass~\\cite{harper+:popl90}. \nThis is an experimental implementation of an transformation that can replace a functor (a relatively heavyweight language construct) by\nparameterized types and/or polymorphic values. \n\\iflong\nThe idea is that although\nfunctors map modules containing types and terms to other modules containing types\nand terms, constraints on the programming language ensure that output types\ndepend only on input types (and not input terms).  Thus, we can split each\nfunctor into a mapping from input types to output types, and then a separate\n(polymorphic) term mapping input types and terms to an output term.\nSee Section~\\ref{sec:finite-sets} for an example.\n\\fi\n\n\nThe other optional transformation is a \\emph{hoisting} pass which\nmoves obligations in the output to top-level positions.  Obligations\nappear in the output inside assertions, at the point where an uncheckable property was needed.\nMoving these obligations to the top-level \nmake it easier to see exactly what one is obliged to verify, and can\nsometimes make them easier to read, at the cost of losing information about\nwhy the obligation was required at all. \n\\iflong\nSee\nSection~\\ref{sec:exampl-with-oblig} for an example of hoisting.\n\\fi % \\iflong\n\n%%% Local Variables: \n%%% mode: latex\n%%% TeX-master: \"cie\"\n%%% End: \n", "meta": {"hexsha": "852713f00995147b377ee91a2e01cfaf686f4cc6", "size": 4584, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "private/cie/implementation.tex", "max_stars_repo_name": "andrejbauer/rz", "max_stars_repo_head_hexsha": "d92cacaf78fb50d61fc6712c74b8fdaf5d2c6d28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-08-28T10:12:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-07T21:04:22.000Z", "max_issues_repo_path": "private/cie/implementation.tex", "max_issues_repo_name": "andrejbauer/rz", "max_issues_repo_head_hexsha": "d92cacaf78fb50d61fc6712c74b8fdaf5d2c6d28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "private/cie/implementation.tex", "max_forks_repo_name": "andrejbauer/rz", "max_forks_repo_head_hexsha": "d92cacaf78fb50d61fc6712c74b8fdaf5d2c6d28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9285714286, "max_line_length": 135, "alphanum_fraction": 0.7541448517, "num_tokens": 1262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3278524180688652}}
{"text": "\\chapter{Sample Session} \\label{appx:example}\n\nThe following is an example session with \\caps{\\PROGRAM}. Text following\nthe \\caps{\\PROGRAM} prompt (\\verb|ALG>|) is supplied by the user. The\nprogram response (if any) is shown directly below the equation or\ncommand. Comments on the example are in {\\em italics}.\n\n\\newenvironment{comments} {\\em}{}\n\n\\verb|ALG>| \\cmd{LIST VARS}\n\\begin{verbatim}\nDatabase:  /User/me/testing/input_databse.e\n\nSAMPLE DATABASE FOR ALGEBRA\n\nNumber of coordinates per node       =     2\nNumber of nodes                      =   644\nNumber of elements                   =   480\nNumber of element blocks             =     1\n\nNumber of node sets                  =     0\nNumber of side sets                  =     0\n\nCode:  MISCPROG  version  1.0       on  12/23/85  at  10:21:59\n\\end{verbatim}\n\n\\verb|ALG>| \\cmd{LIST STEPS}\n\\begin{verbatim}\nNumber of time steps = 21\n   Minimum time =  0.00\n   Maximum time = 10.00\n\\end{verbatim}\n\n\\newpage\n\\verb|ALG>| \\cmd{SHOW TMAX}\n\\vspace{-\\medskipamount} \n\\begin{verbatim}\nSelect all times from 0.0 to 10.0\n   Number of selected times = 21\n\\end{verbatim}\n\\verb|ALG>| \\cmd{TMAX 5.0}\n\\vspace{-\\medskipamount} \n\\begin{verbatim}\nSelect all times from 0.0 to 5.0\n   Number of selected times = 11\n\\end{verbatim}\n\\verb|ALG>| \\cmd{NINTV 5}\n\\vspace{-\\medskipamount} \n\\begin{verbatim}\nSelect times 0.0 to 5.0 in 5 intervals with delta offset\n   Number of selected times = 5\n\\end{verbatim}\n\n\\begin{comments}\nThese commands select up to 5 time steps between 0.0 and 5.0 starting at\nan offset (1.0) from 0.0. The steps with the times nearest 1.0, 2.0,\n3.0, 4.0, and 5.0 are selected. The equations are evaluated and the\nresults written to the output database only for the selected steps.\n\\end{comments}\n\n\\verb|ALG>| \\cmd{LIST NAMES}\n\\begin{verbatim}\nCoordinate names: R Z\n\nVariables Names:\n   Global:   RESIDUAL  ENERGY    NORM      L2NORM\n   Nodal:    DISPLR    DISPLZ    VELR      VELZ      ACCELR    ACCELZ\n   Element:  SIGR      SIGZ      SIGT      TAURZ     EPSR      EPST\n             EPSRZ\n\\end{verbatim}\n\n\\verb|ALG>| \\cmd{SAVE NODAL}\n\n\\begin{comments}\nAll the input database nodal variables (\\cmd{DISPLR}, \\cmd{DISPLZ}, \\ldots,\n\\cmd{ACCELZ}) will be written unchanged to the output database (unless\nthey are assigned a value or listed in a \\cmd{DELETE} command).\n\\end{comments}\n\n\\newpage\n\\verb|ALG>|\n\\cmd{VONMISES = (1.0$/$SQRT(2.0)) $*$ TMAG(SIGR,SIGZ,SIGT,TAURZ,0,0)} \\\\\n\\verb|ALG>|\n\\cmd{EFFSTR = SQRT(1.5) $*$ 5.79E-3 $*$ VONMISES$**$4 $*$\nEXP(-12.0$/$300.0$*$1.987)} \\\\\n\\verb|ALG>|\n\\cmd{PRESS = (SIGR $+$ SIGZ $+$ SIGT) $/$ 3.0} \\\\\n\\verb|ALG>|\n\\cmd{PRESS100 = (SIGR\\$100 + SIGZ\\$100 + SIGT\\$100) $/$ 3.0} \\\\\n\\verb|ALG>|\n\\cmd{PHI = EFFSTR $-$ 0.023 $-$ PRESS $*$ (4.43E$-$8 $-$ 3.7E$-$15 $*$\nPRESS)} \\\\\n\\verb|ALG>|\n\\cmd{ALPHA = SIGR\\$56} \\\\\n\\verb|ALG>|\n\\cmd{BETA = ALPHA $+$ 1.414}\n\n\\begin{comments}\nAssign element variables \\cmd{VONMISES}, \\cmd{EFFSTR}, \\cmd{PRESS}, and\n\\cmd{PHI} and global variables \\cmd{PRESS100}, \\cmd{ALPHA}, and\n\\cmd{BETA}. Note that the \\cmd{PRESS100} equation could be replaced by\n``\\cmd{PRESS100 = PRESS\\$100}''.\n\\end{comments}\n\n\\verb|ALG>| \\cmd{DELETE ALPHA}\n\n\\begin{comments}\n\\cmd{ALPHA} (assigned in the equation ``\\cmd{ALPHA = SIGR\\$56}'' above)\nbecomes a temporary variable and will not be written to the output\ndatabase.\n\\end{comments}\n\n\\verb|ALG>| \\cmd{BAD = (A + 1)) + SIN (1,2)}\n\\vspace{-\\medskipamount} \n\\begin{verbatim}\n*** Expected 1 parameter(s) for function SIN, found 2\n*** Parenthesis do not balance\n*** \"A\" is not a database variable\n    Equation ignored\n\\end{verbatim}\n\n\\begin{comments}\nThis equation contains several errors. Each error is flagged and the\nequation is ignored.\n\\end{comments}\n\n\\verb|ALG>| \\cmd{END}\n\n\\begin{comments}\nNo further user input is accepted and the equation evaluation\nbegins.\n\\end{comments}\n", "meta": {"hexsha": "e73e1cb1e4e2965c73ffc03c80ea511d384aa38c", "size": 3821, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "packages/seacas/doc-source/algebra/algexample.tex", "max_stars_repo_name": "jschueller/seacas", "max_stars_repo_head_hexsha": "14c34ae08b757cba43a3a03ec0f129c8a168a9d3", "max_stars_repo_licenses": ["Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "NetCDF", "BSL-1.0", "X11", "BSD-3-Clause"], "max_stars_count": 82, "max_stars_repo_stars_event_min_datetime": "2016-02-04T18:38:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T03:01:49.000Z", "max_issues_repo_path": "packages/seacas/doc-source/algebra/algexample.tex", "max_issues_repo_name": "jschueller/seacas", "max_issues_repo_head_hexsha": "14c34ae08b757cba43a3a03ec0f129c8a168a9d3", "max_issues_repo_licenses": ["Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "NetCDF", "BSL-1.0", "X11", "BSD-3-Clause"], "max_issues_count": 206, "max_issues_repo_issues_event_min_datetime": "2015-11-20T01:57:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:12:04.000Z", "max_forks_repo_path": "packages/seacas/doc-source/algebra/algexample.tex", "max_forks_repo_name": "jschueller/seacas", "max_forks_repo_head_hexsha": "14c34ae08b757cba43a3a03ec0f129c8a168a9d3", "max_forks_repo_licenses": ["Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "NetCDF", "BSL-1.0", "X11", "BSD-3-Clause"], "max_forks_count": 68, "max_forks_repo_forks_event_min_datetime": "2016-01-13T22:46:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T06:25:05.000Z", "avg_line_length": 28.7293233083, "max_line_length": 75, "alphanum_fraction": 0.6650091599, "num_tokens": 1312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.5428632831725051, "lm_q1q2_score": 0.3278524180688652}}
{"text": "%\n% Chapter 1\n%\n\\chapter {Introduction}\n\nAlgorithms designed for quantum computers have the potential to solve some problems that cannot be efficiently solved by algorithms designed for classical computers. However, estimating how much resources are needed to execute a quantum algorithm that outperforms a classical one is a difficult task. There are many quantum programming languages and tools built around them such as Q\\#\\cite{QSharp_Svore_2018}, Qiskit\\cite{Qiskit_2021} and Cirq\\cite{Cirq_2021} that allow execution of quantum algorithms on simulators but out-of-the-box options to estimate resources are limited to the logical level or not existent.\n\n\\section{The Purpose of This Thesis}\n\nThis thesis aims to estimate the resources required at the physical level to run Shor's semiprime integer factorization algorithm for trapped-ion and superconducting quantum hardware platforms. To do this, we will extend the simulators infrastructure built around Q\\# to calculate the maximum number of physical qubits, the total number of physical gates, and the maximum runtime required to execute a particular quantum algorithm. \n\nFurthermore, we will also analyze the effects of errors introduced by the physical gates, analyze the feasibility of obtaining reliable results without implementing fault-tolerance, and estimate the cost of running the algorithm using error-corrected qubits and fault-tolerant gates.\n\nIn order to make this thesis more accesible to people from different backgrounds, we dedicate the next few chapters to provide a brief overview of the basics of quantum computing, quantum error correction, and Shor's semiprime integer factorization algorithm.\n", "meta": {"hexsha": "f42eaadec948083011aecf9e30c8bc25dc3aa604", "size": 1676, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Thesis/chapter01.tex", "max_stars_repo_name": "cesarzc/qc-resources-estimation", "max_stars_repo_head_hexsha": "2909d8d51c51e69183622e039af6eaa1ed74d1c0", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Thesis/chapter01.tex", "max_issues_repo_name": "cesarzc/qc-resources-estimation", "max_issues_repo_head_hexsha": "2909d8d51c51e69183622e039af6eaa1ed74d1c0", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Thesis/chapter01.tex", "max_forks_repo_name": "cesarzc/qc-resources-estimation", "max_forks_repo_head_hexsha": "2909d8d51c51e69183622e039af6eaa1ed74d1c0", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 111.7333333333, "max_line_length": 616, "alphanum_fraction": 0.826372315, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.3278524180688652}}
{"text": "\\section{Introduction}\n\\begin{frame}{\\insertsec}\n\t\\begin{itemize}\n    \\item Nowadays Machine Learning it's widely used\n    \\item Medical images can be obtained using MRI, PET or CT scans but are underused\n    \\item Different methods have appeared to analyze these data for image classification,\n    object detection, segmentation...\n    \\item Deep learning models aim to be able to unlock the full potential of medical imaging\n  \\end{itemize}\n\\end{frame}\n\n\\subsection{Survival Analysis}\n\\begin{frame}{\\insertsubsec}\n  Survival analysis models usually have:\n  \\begin{itemize}\n    \\item Baseline data \\( x \\)\n    \\item Event \\( E \\in \\{0, 1\\} \\)\n    \\item Time \\( T \\)\n  \\end{itemize}\n\n  Casting the survival problem as a ranking is a way of dealing with censored data.\n  \\vspace{.3cm}\n  \\begin{columns}\n    \\begin{column}{.5\\textwidth}\n      \\begin{figure}\n        \\centering\n        \\input{drawings/graph_no_censored.tikz.tex}\n        \\caption{Uncensored data}\n      \\end{figure}\n    \\end{column}\n    \\begin{column}{.5\\textwidth}\n      \\begin{figure}\n        \\centering\n        \\input{drawings/graph_censored.tikz.tex}\n        \\caption{Censored data}\n      \\end{figure}\n    \\end{column}\n  \\end{columns}\n  \n\\end{frame}", "meta": {"hexsha": "647aefaccec8594d052288b4c743dbd8d1857d32", "size": 1217, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "LATEX/GEP_presentation/sections/01_introduction.tex", "max_stars_repo_name": "jmigual/FIB-TFG", "max_stars_repo_head_hexsha": "7551a3c13a985ee7eecf7a4f38a6ee4803b05ff1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-02T15:17:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-02T15:17:51.000Z", "max_issues_repo_path": "LATEX/GEP_presentation/sections/01_introduction.tex", "max_issues_repo_name": "jmigual/FIB-TFG", "max_issues_repo_head_hexsha": "7551a3c13a985ee7eecf7a4f38a6ee4803b05ff1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LATEX/GEP_presentation/sections/01_introduction.tex", "max_forks_repo_name": "jmigual/FIB-TFG", "max_forks_repo_head_hexsha": "7551a3c13a985ee7eecf7a4f38a6ee4803b05ff1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-10-23T08:11:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-23T08:11:28.000Z", "avg_line_length": 30.425, "max_line_length": 93, "alphanum_fraction": 0.6754313887, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.32785241032908846}}
{"text": "\\section{Abstract}\nThis article describes an attempt to reproduce key findings of a study of murine hippocampal oscillations published in 2007 \\cite{hentschke_muscarinic_2007}. Being a submission to the 'Ten Years Reproducibility Challenge', it focuses on the process of reviving the Matlab code underlying the analyses, particularly the neuronal signal processing toolbox created for the study and its follow-ups.\n\n\\section{Introduction}\n\\subsection{Neuroscientific background}\n\\label{subsec:background}\nNeuronal activity in mammalian central nervous systems is often oscillatory. Intensity, frequency, and other characteristics of the oscillations are closely associated with behavior and arousal state. As this association suggests a functional role of oscillations, they have been studied extensively. One of the most conspicuous cases of behavior-dependent oscillatory neuronal activity occurs in hippocampus, a brain region pivotal for navigation and memory formation: prominent rhythms exist in the theta (4-12 Hz) and gamma (30-90 Hz) bands. \nInterestingly, the oscillations are coupled in a nonlinear fashion: the magnitude of gamma oscillations varies cyclically at theta frequency \\cite{soltesz_low-_1993} (Fig.~\\ref{fig:hip_oscill}). Such phase-amplitude coupling (PAC), also termed 'nesting' of oscillations, has been postulated to be important for memory formation and retrieval \\cite{lisman_storage_1995, hyafil_neural_2015}.\n\nA large body of research has shown that both theta and gamma rhythms depend on the neuromodulator acetylcholine, but before our study \\cite{hentschke_muscarinic_2007} it had not been clear whether and how their PAC would change with cholinergic signalling. As a first step towards shedding light on this, we performed experiments on mice with extracellular multielectrode arrays implanted into area CA1 of hippocampus. Each extracellular electrode picked up local field potentials (LFPs) -- tiny, local, time-dependent changes in the electrical potential relative to a distant reference point (Fig.~\\ref{fig:hip_oscill}B). The mice were behaviorally scored and the LFPs recorded for periods of ca.\\ 90 min, including administration of a blocker of muscarinic cholinergic receptors 30 min into the experiments. \n\n\\subsection{Code base and scope of reproduction}\nThe code presented here consists of two major parts. One is a toolbox of bespoke data crunching routines which performed classical time and frequency domain analyses. These were geared towards revealing spatial and temporal relations between signals from the different recording electrodes (crosscorrelations, coherence, etc.), with a focus on within-site phase-amplitude coupling. The 'main' function of this toolbox -- termed 'rmouse' -- integrated behavioral scoring data, partitioned the computational results according to the animals' behavior, and created summary figures for each recording (Fig.~\\ref{fig:rmouse_workingstyle}). Also included were numerous post-processing routines with specific jobs like aggregation of data.\n\nThe other part of the code consisted of project-specific routines for statistical analyses of the data, and for the generation of publication-style plots.\n\nThe major focus here is on getting the toolbox and associated post-processing code to run with a Matlab version as recent as possible. Moreover, I attempted to reproduce those figures of the original study which conveyed the key finding of the paper, namely a reduction of PAC in the presence of muscarinic blockers (Fig.~\\ref{fig:repro}).\n\n\\subsection{Expectations and results in a nutshell}\nAs Matlab code is generally quite backwards compatible, I was optimistic about overall success. The optimism was justified in terms of a general repeatability of the analysis; both toolbox and post-processing code could be brought into a functional state, and figures be created from the newly computed analysis results. However, data could only be retrieved for three of the five experimental animals of the original study, so the figures shown here are not exact reproductions, but must rather be seen as proofs of concept. \n\n\n\\begin{figure}\n\t\\centering\n\t\\includegraphics[width=0.9\\textwidth]{figures/figures_tenYears_01.png}\n\t\\caption{Theta and gamma oscillations, two prominent hippocampal oscillations under investigation in the original study. A, sketch of a section of rodent hippocampus and the location of the multielectrode recording arrays (orange circles). Shown are also two pyramidal cells with their basal dendrites in \\textit{stratum oriens} and apical dendrites in \\textit{strata radiatum} and \\textit{lacunosum-moleculare}. B, wide-band local field potential data (top trace), and filtered versions (center and bottom, respectively) of a short stretch of oscillatory activity in the hippocampus of a mouse exploring its surroundings. Note how troughs of the slower theta oscillation (4-12 Hz) coincide with peaks in the envelope of the faster gamma oscillations (30-90 Hz).}\n\t\\label{fig:hip_oscill}\n\\end{figure}\n\n\n\\subsection{Computational context}\n% Describe the computational context: Which hardware was used to run the code? Which software infrastructure? Which constraints existed on software development? Which technical choices (language, libraries, ...) were made? Were reproducibility and/or re-usability important criteria? \n% About the original source code: Was it published? Was it archived somewhere? Was there a license for it? \n\nI developed the largest part of the code during a postdoctoral stay 2003-2005 in the laboratory of Robert A. Pearce (University of Wisconsin at Madison). The core of the analysis strategy had been devised by Matthew I. Banks (also UW Madison), who had also implemented a first version in a spreadsheet-cum-script language (Origin). Due to limitations inherent in the language it was decided to implement and extend the analysis in a more versatile language. Matlab was the natural way to go, as it was (and still is) the standard programming environment in many electrophysiology laboratories, and I had used it extensively before. In our original study \\cite{hentschke_muscarinic_2007}, Matlab versions 6.5 - 7.4 (R13 - R2007a) were used. For later projects, the code has been continuously adapted to Matlab versions up to 7.9 (R2009b), after which it lay dormant. Various Matlab toolboxes were required: most importantly, the Signal Processing Toolbox; depending on the exact post-processing routines, the Curve Fitting and Statistics Toolboxes were also required. \n\nA pivotal issue for the project, and in general for any data-focused undertaking, was the import of raw data. The time series data existed in a proprietary format, the Axon Binary Format (ABF), in which each data point is stored as a 16-bit integer. A function for efficiently importing data of this format into Matlab did not exist. Although the software package provided by the vendor (former Axon Instruments, now Molecular Devices) allowed an export of the data into text format, this was not considered practical (tedium involved in manual conversion, inflation of data size). Hence, I wrote a routine for importing raw data in this format into Matlab and submitted it to the MathWorks Central File Exchange \\cite{hentschke_abfload_nodate}. Initially considered a spin-off of minor importance, this routine and its upgrade \\cite{collman_fcollmanabfload_nodate} found a widespread distribution in the neuroscience community, and also sparked implementations in other languages \\cite{caldwell_abfload_nodate, harden_swhardenpyabf_nodate}. An ironic twist is that the more fail-safe way of implementing a data importing routine for the windows operating system, namely code employing Molecular Devices' dynamic link library (DLL), would have made sense at the project's start in 2003, but has since the introduction of 64-bit versions of Matlab been rendered impractical by the limitation of this DLL to 32 bit (confirmed via an exchange with Molecular Devices Customer Support in December 2019). Readers further interested in this topic may want to consult the \"Unofficial Guide to the ABF File Format\" by Scott Harden \\cite{harden_scott_w_unofficial_nodate}.\n\nAs all code was written in pure Matlab, and data import had been solved within Matlab, there were no extraneous dependency issues.\n\nAlthough reproducibility of the study results was not an imminent concern to me back then, reusability of the code had definitely been an important design aspect early on. Series of experiments with a similar setup were in the pipeline, and given the limited term of my stay it was clear that the code would also be used by my colleagues \\cite{perouansky_amnesic_2007, hentschke_altered_2009, balakrishnan_midazolam_2014}. Therefore, I wrote a manual with illustrations, with the intent of providing sufficient information for lab members familiar with the scientific background to find their way through the code. I also commented the code prolifically, especially the scripts calling the toolbox functions. The source code has never been properly archived or published, except for the data importing routine (until the reproducibility challenge came along) for two reasons: first, I considered it too specialized and tailor-made to be of much use for other groups. Second, making the toolbox open access would have required making it more user-friendly and extending the documentation substantially. Absent an academic reward system for such efforts not only for myself but also the hosting lab, I considered the necessary investment of time inappropriate.\n\nI developed the code without any kind of version control worth the term, and left it 'as is' on my then machine in the laboratory. The toolbox's core code was in one dedicated directory, but auxiliary code was scattered throughout my Matlab code base, which of course also contained a great deal of unrelated code. I never saw the necessity of properly packaging the code: it would not be published, and almost all auxiliary functions employed by the toolbox were quite general and therefore also part of other (and future) programming projects. So, my justification for this practice was to avoid redundancy and the usual problems associated with maintaining multiple copies of code.\n\nTowards the end of my stay in the laboratory, I simply mirrored my Matlab directory on other users' machines to get the toolbox to run there. After I left, I developed it further and adapted it to the needs of the subsequent projects, which went on for quite a while. \n\nHardware was an issue, albeit an uncritical one. The analyses were run on 32-bit Windows PCs with 4 GB of RAM and not-too-bad Intel Pentium processors available at the time (more precise specs are not known anymore). The electrophysiological signals were sampled at ca. 1000 Hz from up to 16 channels and typically lasted for 30 minutes; the resulting individual raw data files occupied less than 100 Mb on disk. Their size in RAM, after conversion from 16-bit integers to the default 64-bit floating type in Matlab, posed no critical challenge. However, the code also implemented the creation of surrogate time series. Dealing with these, as well as multiple filtered copies of the data in RAM in parallel required some thought-through strategies and juggling with computer resources, and was taxing for the CPU. Yet, even full-blown analyses of the whole data set were accomplished overnight.\n\n\n\\section{Retrieval of the software}\n% Was it easy to find a copy of your source code? \n% Was it easy to locate and setup the dependencies? \n% Provide a list of all dependencies (libraries but also tools such as compilers). \n\nRetrieval of the source code was easy; in fact, most of it did not have to be retrieved. As code files are ridiculously small even by the standards of the mid-2000s, I generally leave them on the hard disks of the computers in my hands. The hard part was figuring out the organization of the code files. There were the toolbox folder, still in my Matlab code base, and the folder containing code files for generating the publication figures. Localizing both required just a few minutes. I was also aware that several auxiliary functions, including the data-importing function, were outside the toolbox folder but inside my Matlab code base. However, I forgot that back then I placed scripts defining analysis parameters for each individual data file in yet a different location: namely, in the root folder for the raw data, as well as the subfolders therein. Only after I tried to run the first analysis step did I realize this.\n\n\\section{Execution}\n% Describe what you did in order to run the software today.\n% • Did you succeed in running the software in a modern computational environment? Or did you have to search for old versions of tools and libraries? \n% • Describe the computational environment of the reproduction: hardware, operating system, compiler versions etc. \n% • Did you have to modify the software in order to make it run today? \n% • Were the original instructions that came with the software sufficient, or did you have to modify or extend them? \n% • How close were the results you got to the originally published ones? Include the replicated data table and figure, as we do in other ReScience articles. \n% If you had to make any modifications to the software or to the instructions that were supplied with it, try to describe which competence another researcher would need in order to do the same work. Would a general familiarity with your programming language and environment have been sufficient?\n\nReproduction was performed on a PC with Windows 7 and Matlab R2020a with the Signal Processing, Statistics and Machine Learning, and Parallel Computing Toolboxes installed. The PC had 32 GB of RAM, ample space on both hard disk and solid state drive, an Intel Core i7-4770K CPU with four physical cores, and an nvidida GeForce GTX1060 graphics card.\n\nReproducing data analysis including selected figure panels of the original paper required several processing steps. \nI started with the first step -- processing the raw data -- by trying to locate the scripts which defined the analysis parameters for each individual file to be processed. After finding only one, I read the manual, and realized that both the majority of the data and data-specific scripts were missing, contrary to my first cursory impression when entering the challenge. Thanks to the efforts of a former colleague (acknowledgements) I was able to retrieve six complete sets of data and data-specific scripts from three of five experimental animals used in the original study. With these available, I finally remembered how the toolbox was supposed to work.\n\nBefore actually trying to run it, I assembled all code files I could identify at this stage as belonging to the project into a directory structure such that submitting the code to a repository would be possible. Next, I ran a dependency analysis on the main function of the toolbox and could identify a number of additional code files that were missing. After copying these to the project directory, I excluded my general Matlab code base from the path. Then, I tried in earnest to start number crunching. It took me about three hours to get the analyses to run on three experiments (two data files each). The adjustments required were, in order of severity:\n\n\\begin{enumerate}\n\t\\item Retrieval of functions that were still missing from my general Matlab code base (about two dozen of files).\n\t\\item 'Downgrading' auxiliary functions which had been in my general code base and together with it had evolved over time to the point of being incompatible with the toolbox.\n\t\\item Updating code to be compatible with the recent version of Matlab.\n\\end{enumerate}\n\nI was shocked to learn how many of the required functions I had to retrieve from my '\\_legacy' folder. Had I not exerted caution in getting rid of code and instead deleted them, I would have spent hours on end to recapitulate what they were supposed to do, and possibly given up. A pleasant confirmation of expectations was the little effort I had to spend adapting the code to the most recent Matlab version. Essentially, all I had to do was write a wrapper for function \\texttt{diag}, which did not accept cell arrays as inputs anymore. Surprisingly, graphics, including one very simple GUI, worked without hiccups; thanks to a major revision of graphics in R2014b, it also produced more aesthetically pleasing figures. \n\nMoreover, with little effort, it was possible to run number crunching in an embarassingly parallel way using \\texttt{parfeval}. This, as well as moving the data to a solid state drive, cut down processing time from a baseline of 152 min to a very agreeable 66 min (three experimental subjects, two recordings each, 100 instances of surrogate data generation each). Although exact numbers are impossible to come by, my estimate is that the combination of recent software and more modern (certainly not recent) hardware sped up the computations by a factor of at least eight. Yet more speedup would have required fundamental re-coding of the toolbox.\n\n\\begin{figure}\n\t\\centering\n\t\\includegraphics[width=0.9\\textwidth]{figures/example_summaryFig_rmouse.jpg}\n\t\\caption{Example of a summary figure produced by the rmouse toolbox from one of the analyzed data files. These summary figures were meant to provide a quick overview of the data and a glimpse at the computed quantities. The top panel and pie chart on the left illustrate the temporal sequence and proportions of time spent in various behavioural states, respectively, and also quantify recording periods unsuitable for analysis. Examples of data segments considered artifacts are depicted on the left, below the pie chart. All other panels show the results of spectral and time domain analyses.}\n\t\\label{fig:rmouse_workingstyle}\n\\end{figure}\n\nThe next task was aggregating the data from the different experiments, and (re-)producing selected figure panels of the original study. Numerous scripts for various visualizations of the results existed; as these were not strictly documented and kept up to date, a trial-and-error period of identifying key pieces of code responsible for producing the plots ensued. Apart from this, and on top of adjustments similar to those required for the toolbox, I expected two additional problems here. First, the original code made use of the Curve Fitting Toolbox, which was not at my disposition now. Second, code producing 'Christmas Tree' plots -- adorned horizontal bar plots often featuring a coniferous shape (Fig.~\\ref{fig:repro}) -- featured low-level graphics commands. Due to substantial changes of Matlab graphics in the interim, I knew that this code would have to be modified.\nBoth challenges proved surmountable. For the simple fits of 1D data, I used function \\texttt{fitnlm}, and refurbished the affected code accordingly. The function producing the horizontal bar plots could also be updated without major pains. Following these fixes, key findings of the original study could be reproduced, albeit only with said partial data (Fig.~\\ref{fig:repro}). All other figure panels featuring above-mentioned horizontal bar plots could be reproduced with the same data base by  changing the name of a target variable in a script and adapting the curve-fitting code (data not shown).\n\n\\begin{figure}\n\t\\centering\n\t\\includegraphics[width=0.9\\textwidth]{figures/figures_tenYears_02.png}\n\t\\caption{Reproduction of key findings. A, exemplary power spectral densities of the wide-band LFP ('raw') and of the gamma envelope of the LFP recorded at the hippocampal fissure. The light shaded area corresponds to the power of the gamma envelope in the theta range; the gray area represents the power of the gamma oscillations. This graph corresponds to Figure 5B in the original paper. B, laminar profile of the power of the gamma envelope in the theta band for immobile and exploring  animals (three of five from which data could be retrieved). The vertical position of the bars illustrates the location of the recording sites underlying the data. Gray, control; black, with the muscarinic blocker atropine. Error bars are standard deviations. Dotted lines are exponential fits to the data. This graph corresponds to Figure 5C in the original paper. C, laminar profile of the crosscorrelation between theta and the gamma envelope. Same conventions as in B apply. Dotted lines are polynomial fits (order 2) to the data. This graph corresponds to Figure 7A in the original paper. D, artistic rendering of theta oscillations, illustrating their highly dynamic nature. Time runs horizontally from left to right. Each set of concentric rings represents a theta peak (green) or trough (orange) detected on each of the 16 electrodes spanning hippocampus (and a trifle of the surrounding tissue). The more rings in a set, the stronger the normalized peak or trough amplitude (as amplitudes differ strongly between the layers, they were normalized for each recording electrode separately). The orientation of recording sites is as in the sketch in B (topmost row corresponds to \\textit{stratum oriens/alveus}). On average, there is a phase lag of almost half a theta period between the layers harboring the apical and basal dendrites of the pyramidal cells, but individual theta 'beats' are very variable. The increase of such variability in the presence of atropine (data not shown) is a major cause of the deteriorated coordination between theta and gamma (as shown in C). Modeled after Figure 9A in the original paper.}\n\t\\label{fig:repro}\n\\end{figure}\n\n\n\n\\section{Conclusion and personal evaluation}\nDuring my last years in academia, I focused increasingly on professional programming, and eventually left academia in 2019 to work as a Data Scientist. Having along the way picked up at least a modicum of formal software education, my opinion on my original source code is mixed. \n\nOn the positive side, I commented the code heavily, particularly the scripts which other users of the code were to use. Later on, I also spent a considerable amount of time on the documentation. A crude form of logging was implemented. Moreover, I had a knack for making code run fast, and consider some aspects of the implementation valid even today.\n\nHowever, a few of my past code design choices strike me as odd now, to say the least. First and foremost, this is above-mentioned liberal dispersal of code files across my entire code base, and the placement of scripts defining parameters in data directories. The cascades of scripts required for running analyses with the toolbox required immersion into the code, and could have been replaced by a more user-friendly graphical user interface. For post-processing, there had been a proliferation of poorly documented and partly redundant helper or plotting functions. Over time, 13 (thirteen) variants of a 'combine\\_X'-function had accumulated, the job of which was to assemble the results of the computations by the toolbox. Moreover, I would have compartmentalized the toolbox code much more. Finally, for a toolbox of this scope, more time should have been devoted to the documentation. All things considered, I believe that resurrecting the code would have been very arduous for anyone else, even a Matlab expert, due to a dearth of documentation.\n\nYet, I view these deficiencies in context. As a scientist-cum-programmer, one also has the science to do, not to mention actually making sense of the analysis results and writing papers about them. As mentioned before, spending a large amount of time on the documentation would have been hard to justify. Moreover, like many of my former colleagues, I was a self-taught programmer essentially without formal computer science education, so most of my design choices were not based on traded wisdom, but self-accrued, patchy knowledge. \n\nMy former self was certainly not alone in this position, as academia in general seems to be a fertile ground for 'organically home-grown' code that may or may not be 'good enough' to publish \\cite{barnes_publish_2010}. It is heartening to see that programming scientists are increasingly given a hand in producing reproducible and efficient code \\cite{wilson_good_2017}.\n\n\\section{Acknowledgements}\nI owe profound thanks to Claudia Holt, Section of Experimental Anesthesiology, University Hospital of Tübingen, who unearthed the data for this study. Many thanks also go to Matthew I. Banks for discussions of the manuscript, and to Robert A. Pearce for consenting to the publication of the code.", "meta": {"hexsha": "dd1788bb90d315f7b815d4f4a15a13da97bb026f", "size": 24586, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/content.tex", "max_stars_repo_name": "oliviaguest/ReScience_10yrReproChallenge", "max_stars_repo_head_hexsha": "1edebb30bce66160303ef93687fa9a7b67b1e3f7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-11T10:13:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-11T10:13:42.000Z", "max_issues_repo_path": "paper/content.tex", "max_issues_repo_name": "oliviaguest/ReScience_10yrReproChallenge", "max_issues_repo_head_hexsha": "1edebb30bce66160303ef93687fa9a7b67b1e3f7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/content.tex", "max_forks_repo_name": "oliviaguest/ReScience_10yrReproChallenge", "max_forks_repo_head_hexsha": "1edebb30bce66160303ef93687fa9a7b67b1e3f7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-10T13:01:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-10T13:01:22.000Z", "avg_line_length": 215.6666666667, "max_line_length": 2119, "alphanum_fraction": 0.8104205645, "num_tokens": 5126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.32782401151233864}}
{"text": "% Chapter X\n\n\\chapter{Decisions} % Chapter title\n\n\\label{Decisions} % For referencing the chapter elsewhere, use \n\nFigaro also contains the ability to solve and query structured decision problems. These types of models, also known as influence diagrams, are generalizations of Bayesian networks that contain additional decision and utility variables. Figaro generalizes ordinary decision models by allowing the information on which a decision is based to be an arbitrary data structure. Also, the full power of the programming language is available to build decision models. However, Figaro does require that the possible values of the decision variables themselves be discretely enumerated.\n\nIn this section, we first give a very brief introduction into decision models and decision-making. We then provide a small example of decision-making in Figaro. We also delve deeper into the decision- making implementation in Figaro. Finally, we discuss the different ways that decision-making can be performed on single and multiple decision models.\n\n\\section{Decision models}\n\nDecision models are generalizations of Bayesian networks that contain two additional variable types. The first is a decision variable, which represents a set of actions that a decision-maker can perform. The parents of a decision variable represent the information available to the decision-maker at the time of the decision. Decision models also contain utility variables, which represent some gain or loss in the model that directly or indirectly depends upon some previous decisions or random variables.\n\nThe purpose of a decision model is usually to compute an optimal policy for each decision in the model, where a policy defines what action a decision-maker should take for every possible value of the decision's parent variable(s). An optimal policy is when every action specified by the policy for each value of the parents is optimal with respect to some measure. To measure the optimality of an action, Figaro uses the maximum expected utility of the action. That is, for each value of a decision's parents, Figaro determines the action that will result in the highest expected utility of the model.\n\n\\section{Basic example}\n\nUsing Figaro's decision-making capabilities is generally quite simple. For example, consider the code for a simple decision model shown below:\n\n\\begin{flushleft}\n\\marginpar{This example can be found in SingleDecision.scala}\n\\texttt{import com.cra.figaro.language.\\_\n\\newline import com.cra.figaro.algorithm.decision.\\_\n\\newline import com.cra.figaro.library.compound.\\_\n\\newline import com.cra.figaro.library.decision.\\_ \n\\newline \n\\newline val market = Select(0.5 -> 0, 0.3 -> 1, 0.2 -> 2)\n\\newline val survey = CPD(market, \n\\newline \\tab 0 -> Select(0.6 -> 0, 0.3 -> 1, 0.1 -> 2),\n\\newline \\tab 1 -> Select(0.3 -> 0, 0.4 -> 1, 0.3 -> 2),\n\\newline \\tab 2 -> Select(0.1 -> 0, 0.4 -> 1, 0.5 -> 2))\n\\newline \n\\newline val found = Decision(survey, List(true, false))\n\\newline \n\\newline def valueFcn(f: Boolean, m: Int): Double = \\{\n\\newline \\tab if (f) \\{\n\\newline \\tab m match \\{\n\\newline \\tab case 0 => -7.0 \n\\newline \\tab case 1 => 5.0 \n\\newline \\tab case 2 => 20.0\n\\newline \\}\n\\newline \\} else \\{\n\\newline\\tab  0.0\n\\newline \\}\n\\newline \\}\n\\newline \n\\newline val value = Apply(found, market, valueFcn)\n\\newline \n\\newline val alg = DecisionVariableElimination(List(value), found)\n\\newline alg.start()\n\\newline alg.setPolicy(found)\n}\n\\end{flushleft}\n\nThe first four lines import the packages needed for decision models. The elements \\texttt{market} and \\texttt{survey} are random variables in a normal Figaro model. We create a decision variable called \\texttt{found} that uses the element \\texttt{survey} as a parent, with the possible actions of the decision as \\texttt{true} or \\texttt{false}. The element named \\texttt{value} is a utility variable that computes a \\texttt{Double} conditioned upon the action of the decision (\\texttt{found}) and the current value of the \\texttt{market} element. It uses the function \\texttt{valueFcn} to compute current utility. Finally, we use Figaro's decision variable elimination to compute an optimal policy for the \\texttt{found} decision, and set the policy in the \\texttt{found} element when the algorithm completes so that it can be used for querying.\n\n\\section{Decisions in Figaro}\n\nAs can be seen in the previous section, decision-making can be implemented in Figaro with little effort. Decisions are created using the \\texttt{Decision[T,U]} element. The \\texttt{Decision[T,U]} element actually inherits from \\texttt{Chain}; that is, a decision is simply an element that uses an \\texttt{Element[T]} as a parent, and generates an \\texttt{Element[U]} as the action. A new decision is instantiated simply as:\n\n\\begin{flushleft}\n\\texttt{Decision(Flip(0.7), List(0, 1, 2))}\n\\end{flushleft}\n\nwhere the first argument is the parent of the decision, and the second argument is a list of the possible actions of the decision. The possible actions must always be finite and discrete. However, the parent of a decision may be an element over any Scala type. So, we could imagine making a decision based on a social network or a DNA sequence. One thing to note is that decision elements only support single parent decisions. However, multiple parent decisions can be easily created by grouping several parent elements into an element tuple. There are various other ways to instantiate a decision that can be found in the code for the \\texttt{Decision} class.\n\nAlso, the no-forgetting assumption in decision models is not explicitly enforced in Figaro, hence Limited Memory Influence Diagrams (LIMIDs) can be represented in Figaro, though there is not an explicit LIMID reasoning algorithm implemented.\n\nIn decision models, there are also variables that represent the utility of the model. In Figaro, there is no need to explicitly create a utility element; this can be easily done using the \\texttt{Apply} element, as shown in the example above. Utility elements must be of type \\texttt{Element[Double]}.\n\nA decision is similar to a chain, but unlike the chain, a decision element can change its functionality after an optimal policy has been computed for the decision. Most of the time, setting the policy of a decision can be done simply through the algorithm that computes the optimal policy. However, a user may manually set the policy of a decision element by calling the \\texttt{setPolicy} function of the decision, defined as:\n\n\\begin{flushleft}\n\\texttt{def setPolicy(new\\_fcn: (T => Element[U])): Unit}\n\\end{flushleft}\n\nThat is, setting the policy of a decision is just providing a new function from the value of a parent to an \\texttt{Element[U]}. Users can also get the policy for a specific value of the parent by calling \\texttt{getPolicy(p: T): Element[U]}. Various other ways to set the policy can also be found in the Decision code.\n\n\\section{Single decision models and policy generation}\n\nSingle decision models can be created in Figaro by simply inserting a \\texttt{Decision} element into the model. Once the model has been created, the goal is usually to compute the optimal policy for the decision that maximizes the expected utility of the model. This is done as two explicit steps in Figaro;computing the expected utility of each parent and decision pair, then determining the decision that has the maximum expected utility for each parent value. The policy is then set as a function that returns the maximum expected utility decision as a \\texttt{Constant}  for any parent value. This policy computation is performed using one of Figaro's built-in inference algorithms. Two alternative methods are provided. One is generally used when the support of the parent is finite, the other when it is infinite. However, there are some cases where the support is finite but very large and the infinite support method is preferable. Alternatively, for some distributions with infinite support, like Poisson or Geometric, only a small number of values are likely, and the finite support method can be used.\n\n\\subsection{Finite parent support}\n\nIn this case, computing the optimal policy can be performed using the variable elimination, importance sampling, or Metropolis-Hastings algorithms. In addition to the normal parameters that each algorithm takes (as explained in previous sections), the decision version of these algorithms also takes a \\texttt{List[Element[Double]]} that indicates the utility nodes in the model. The target of the algorithm is always the decision you wish to compute an optimal policy for. To find the optimal policy for discrete decisions, you simply instantiate one of the algorithms, for example:\n\n\\begin{flushleft}\n\\texttt{val alg = DecisionVariableElimination(List(value), found)\n\\newline val alg = DecisionImportanceSampling(10000,\tList(value), found)\n\\newline val alg = DecisionMetropolisHastings(10000, ProposalScheme.default,\n1000, List(value), found)\n}\n\\end{flushleft}\n\nWhere \\texttt{List(value)} is the list of utilities in the model, and \\texttt{found} is the decision. To compute the optimal policy, you simple start the algorithm, i.e., \\texttt{alg.start()}. One the algorithm has completed running, you can call \\texttt{alg.setPolicy(found)}, which will set the optimal policy in the \\texttt{Decision} element that was computed from the algorithm.\n\n\\subsection{Infinite parent support}\n\nWhen the parent(s) of a decision have infinite support, it is more difficult to compute an exact optimal policy. This is because it is not possible to compute the maximum expected utility action for each value of the parent since the range of the parent is infinite. In such a case, we use Figaro's sampling algorithms to compute an \\emph{approximate} optimal policy that attempts to provide a maximal expected utility decision for any possible value of the parent. Since we use sampling algorithms to compute the approximation, only importance sampling and Metropolis-Hastings can be used with continuous decisions.\n\nInstantiating a decision with infinite parent support is similar to finite parent support, except that one must explicitly instantiate a \\texttt{NonCachingDecision}, which is based on \\texttt{NonCachingChain}:\n\n\\begin{flushleft}\n\\texttt{NonCachingDecision(Normal(0.0, 1.0), List(0, 1, 2))}\n\\end{flushleft}\n\nThe creation of the algorithm and setting of the policy is the same as discrete decisions. Internally in Figaro, however, there are major differences between the implementation of policies for discrete and continuous decisions.\n\nWhen a sampling algorithm is run on a continuous decision, the algorithm records the utility of the model for each parent and action value that is randomly sampled. When \\texttt{setPolicy} is called on the algorithm, all of the generated samples are stored in the decision element. That is, no optimal policy is generated when \\texttt{setPolicy} is called; the optimal action to take for a parent value is only computed when the model is queried for a decision with a particular parent value.\n\nWhen the decision is queried, i.e., \\texttt{getPolicy(p: T)} or \\texttt{generate()} is invoked on the decision element, the optimal action for parent value p is computed using a nearest-neighbor method. The N closest samples to the parent value are retrieved from the stored samples, the expected utility is computed for each possible action, and the maximum is chosen as the optimal action for this parent value.\n\nSince nearest-neighbor is used to find nearby parent values, a distance metric must also be defined for the parent type \\texttt{T}. To use an \\texttt{Element[T]} as the parent to a decision, the type \\texttt{T} must implement the \\texttt{Distance[T]} trait, defined as:\n\n\\begin{flushleft}\n\\texttt{trait Distance[T] \\{\n\\newline \\tab def distance(that : T) : Double\n\\newline \\} }\n\\end{flushleft}\n\nThis trait just defines a function that computes a Double distance between two values of the type. For built-in types (Double, Int and Boolean), we use Scala's implicit conversion mechanism to automatically handle conversion to a class that implements the \\texttt{Distance[T]} interface so that no changes are needed by the user. For examples, the Double implementation is:\n\n\\begin{flushleft}\n\\texttt{case class DoubleDistance(value : Double) extends Distance[Double] \\{\n\\newline \\tab def distance(that : Double) = math.abs(value-that)\n\\newline \\}\n\\newline implicit def double2Dist(x : Double) = DoubleDistance(x)\n}\n\\end{flushleft}\n\nSee the \\texttt{Distance} class for more details on default conversions of basic types and parents that are element tuples. For user defined classes, all the user needs to do is implement a distance function in the \\texttt{Distance} trait, and the type can be used as a parent to a decision element. For instance, we can use an element over the range of graphs as a parent to a decision by declaring the \\texttt{dGraph} class as such:\n\n\\begin{flushleft}\n\\texttt{class dGraph() extends Distance[dGraph] \\{\n\\newline \\tab ...\n\\newline \\tab def distance(that: dGraph): Double = \\{\n\\newline \\tab \\tab ...\n\\newline \\}\n\\newline \\} }\n\\end{flushleft}\n\nSince the number of samples generated from the algorithm may be large, and the optimal policy method retrieves the nearest neighbors for \\emph{every} parent value that is queried from the decision, computing the optimal action can be quite slow. To ameliorate this slowdown, Figaro stores the samples in an index. The default implementation is a VP-index, used for metric distances. Different indices can be created an integrated as well. See the \\texttt{Index} and \\texttt{DecisionPolicy} classes for more information.\n\n\\section{Multiple decision models and policy generation}\n\nFigaro also supports for multiple decision models using a backward induction algorithm. \nIn this algorithm, the optimal policies are computed in reverse order on a set of partially ordered decision variables. To create policies for multiple decision models, a user uses the multi-decision versions of the algorithms:\n\n\\begin{flushleft}\n\\marginpar{A multiple decision example can be found in MultiDecision.scala} \n\\texttt{val alg = MultiDecisionVariableElimination(List(utility1, utility2), decision1, decision2)\n\\newline val alg = MultiDecisionImportanceSampling(10000,\tList(utility1, utility2), decision1, decision2)\n\\newline val alg = MultiDecisionMetropolisHastings(10000, maker: ProposalMakerType, 1000, List(utility1, utility2), decision1, decision2)\n}\n\\end{flushleft}\n\nNote that the interface for the \\texttt{MultiDecisionMetropolisHastings} is different than the \\texttt{DecisionMetropolisHastings} algorithm. \\texttt{MultiDec\\-isionMetropolisHastings} needs a \\texttt{ProposalMakerType}, since inside the algorithm, \\texttt{Decision\\-MetropolisHastings} is run for each decision. The \\texttt{ProposalMakerType} is defined as:\n\n\\begin{flushleft}\n\\texttt{type ProposalMakerType = (Universe, Element[\\_]) => ProposalScheme}\n\\end{flushleft}\n\nOnly the one-time versions of the decision algorithms can be used for multi-decision models. To compute the optimal policy for every decision in the model, the user simply does, for example,:\n\n\\begin{flushleft}\n\\texttt{val propmaker = (mv: Universe, e: Element[\\_]) => ProposalScheme.default(mv)\n\\newline val alg = MultiDecisionMetropolisHastings(200000, propmaker, 20000, List(value, cost), test, found)\n\\newline alg.start()}\n\\end{flushleft}\n\nThe ProposalMaker for this small example just uses the default proposal for each instantiation of \\texttt{DecisionMetropolisHastings} for a decision. However, we could also change the proposal scheme for each decision. There is also no need to call \\texttt{alg.setPolicy}, since the multi-decision algorithm will set the optimal policy for each decision as it is needed for backward induction. Figaro will automatically compute the partial order of the decisions that are in the parameter list.\n", "meta": {"hexsha": "98bcc7c11b9d884b6de04bf01f6997849d70ec6d", "size": 15881, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "FigaroLaTeX/Tutorial/Sections/7Decisions.tex", "max_stars_repo_name": "wkretschmer/figaro", "max_stars_repo_head_hexsha": "ab45d86d7f2b23c77d242b15396f0f704d40570c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FigaroLaTeX/Tutorial/Sections/7Decisions.tex", "max_issues_repo_name": "wkretschmer/figaro", "max_issues_repo_head_hexsha": "ab45d86d7f2b23c77d242b15396f0f704d40570c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FigaroLaTeX/Tutorial/Sections/7Decisions.tex", "max_forks_repo_name": "wkretschmer/figaro", "max_forks_repo_head_hexsha": "ab45d86d7f2b23c77d242b15396f0f704d40570c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 91.7976878613, "max_line_length": 1112, "alphanum_fraction": 0.7901895347, "num_tokens": 3604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241911813151, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3277261426255976}}
{"text": "\\chapter{Conclusion and Future Work}\n\\label{ch:Conclusion-and-Future-Work}\nIn this study, we have shown that the application of a clustering step that utilizes dimensionality reduction techniques such as \\gls{t-sne} and hierarchical, density-based clustering in the form of \\gls{hdbscan} leads to significant improvements in forecasting accuracy when taking individual households into consideration. While this technique is certainly more complex, in particular with regards to the number of steps and moving parts associated with the entire pipeline, we maintain that the benefits in terms of improved forecasting accuracy outweigh the overall increase with regards to the time and effort it would take to train and set up such a model. The practicality of the model lies in the availability of the data that it requires to function -- primarily with respect to historical energy consumption data for the individual households in question (which is becoming easier and easier to obtain thanks to the prevalence of smart meters) and meteorological data that can easily be obtained from numerous sources. Furthermore, it is highly likely that, given enough historical data, the need to further train the model(s) after the initial setup is rather low further compounding the efficacy of our method.\n\n\\noindent \\newline Furthermore, one of the benefits of our method that we previously discussed is that no prior knowledge of the number of clusters is required. As there is no guarantee that any 2 individual households contain a similar number of \\textit{repeating} patterns we avoid running into the problem of overly generalizing a single working solution that may or may not work given said change in energy consumption patterns and instead present a solution that could potentially extend to a much larger scale. A potential issue with this implementation however, is that an individual household \\textit{may} contain a large number of repeating consumption patterns which could possibly lead to an overall decline in what can already be considered sub-par performance from our classifier. That said, there is definitely room for improvement that could accommodate these potential risks, specifically with regards to the feature engineering step -- for example, improvements in classifier accuracy could be seen through the utilization of a more efficient classifier. Alternatively, the current lack of contextual information that serves to explain the emergence of the clusters as part of the clustering step could likely be the reason for obtaining sub-par accuracy scores as, in its current iteration, the premise of our clustering step was to group together days that exhibited the highest similarity purely in terms of their energy consumption patterns and, given that this information is not readily available to us when considering a new day, we are left reaching for straws when attempting to explain when any individual household is likely to observe energy consumption patterns that fall within any of the obtained clusters. Evidently, temporal and meteorological information is not enough to explain the emergence of said clusters and other information (perhaps patterns in terms of cluster labels leading up to the new sample) could serve to improve classifier accuracy. This is definitely an area of this study that could be looked into as part of future research. Additionally, regardless of the fact that the performance of our forecasting model is the highlight of this paper, it is interesting to note that a byproduct of our method is the potential to extract insights into variables that have an effect on the daily energy consumption patterns of unique households. A cursory glance at applying our method to a portion of the data at hand, as an example of the insights that we can obtain, shows us that some households have frequently occurring patterns that tend to deviate among the different days of the week while other households have an even bigger separation across months of the year or even among meteorological factors such as the temperature or chance of rain.\n\n\\noindent \\newline To conclude, we note that, as a result of pre-clustering our data, and then training separate models on a per-cluster basis we achieved an improvement in overall forecasting accuracy with superior \\gls{mape} scores in contrast to the current state-of-the-art (\\gls{lstm} networks, clustering based on K-means, etc.).", "meta": {"hexsha": "81cac7839b473f90f83d0abef928343901438f1a", "size": 4431, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Report/LaTeX source/Chapters/7. Chapter_07.tex", "max_stars_repo_name": "rug-ds-lab/msc-thesis-s3877043-al-saudi-kareem", "max_stars_repo_head_hexsha": "43efeff1d1303814e538dbbb7f217118e240b587", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Report/LaTeX source/Chapters/7. Chapter_07.tex", "max_issues_repo_name": "rug-ds-lab/msc-thesis-s3877043-al-saudi-kareem", "max_issues_repo_head_hexsha": "43efeff1d1303814e538dbbb7f217118e240b587", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Report/LaTeX source/Chapters/7. Chapter_07.tex", "max_forks_repo_name": "rug-ds-lab/msc-thesis-s3877043-al-saudi-kareem", "max_forks_repo_head_hexsha": "43efeff1d1303814e538dbbb7f217118e240b587", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 633.0, "max_line_length": 2795, "alphanum_fraction": 0.8230647709, "num_tokens": 816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.32772614262559757}}
{"text": "\n\\subsection{Continuous utility functions}\n\nWith non-discrete choice a consumer chooses how much of product \\(x\\) to consume.\n\nThe utility function is of the form:\n\n\\(U_i(x_1,...,x_m;d)\\)\n\nAnd the consumer chooses how much of \\(x_i\\) to consume to maximise this, subject to the budget constraint.\n\nWe include features relating to the individual, \\(d\\).\n\n\\subsection{Discrete choice}\n\nThe utility customer \\(i\\) gets from product \\(j\\) is:\n\n\\(U_{ij}=f_i(p,d)+\\epsilon_{ij}\\)\n\nThe customer chooses the product with the highest utility.\n\n\\subsection{The outside option}\n\nWe need to know the market share of the outside option. Do this theoretically. Eg number of customers in area, and 1 per day.\n\n", "meta": {"hexsha": "2ff9a2df3a559421c21ac18764bb438aadb39306", "size": 695, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/pug/theory/economics/consumerDiscrete/01-01-discreteRandom.tex", "max_stars_repo_name": "adamdboult/nodeHomePage", "max_stars_repo_head_hexsha": "266bfc6865bb8f6b1530499dde3aa6206bb09b93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pug/theory/economics/consumerDiscrete/01-01-discreteRandom.tex", "max_issues_repo_name": "adamdboult/nodeHomePage", "max_issues_repo_head_hexsha": "266bfc6865bb8f6b1530499dde3aa6206bb09b93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-03-03T12:36:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-01T22:16:09.000Z", "max_forks_repo_path": "src/pug/theory/economics/consumerDiscrete/01-01-discreteRandom.tex", "max_forks_repo_name": "adamdboult/nodeHomePage", "max_forks_repo_head_hexsha": "266bfc6865bb8f6b1530499dde3aa6206bb09b93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7307692308, "max_line_length": 125, "alphanum_fraction": 0.7424460432, "num_tokens": 166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3277261353223074}}
{"text": "\\chapter{Introduction}\\label{chap:introduction}\n\nA neural network, also known as an Artificial Neural Network (ANN), is an algorithm that mimics the way a human brain operates. It took millions of years of evolution for the human brain to achieve the level of intelligence we observe today. This intelligence helps us quickly interpret and evaluate what we see in our surroundings. For example, consider the following image of hand-written digits from the MNIST dataset \\cite{mnist}:\n\n\\begin{figure}[h]\n\t\\centering\n\t\\includegraphics[width=0.5\\linewidth]{images/introduction/digits.png}\n\t\\caption[Hand-written digits]%\n\t{\\textbf{Hand-written digits}: Each hand-written digit is a $28\\times28$ pixel grayscale image. The entire MNIST dataset contains a total of $70000$ such images that split into a training set of $60000$ images and a test set of $10000$ images.}\n\t\\label{fig:digits}\n\\end{figure}\n\nOne can quickly recognize these digits as $04192$, thanks to the network of billions of neurons available in our brain that makes it easy to identify visual patterns. Past experiences and memories stored in our brain make this process so simple that it happens subconsciously most of the time. This simple process becomes much more difficult when we try to write computer programs to identify similar patterns due to the lack of precise rules and hundreds of exceptions and varieties of a single pattern.\n\nNeural networks tackle this problem by inferring rules from a large set of related training data. For example, to train a neural network to efficiently recognize hand-written digits shown in figure \\ref{fig:digits}, a dataset large enough to include different styles of hand-written digits is needed.\n\nNeural networks and their variations such as Convolutional Neural Networks (CNNs), Recurrent Neural Networks (RNNs) are proven to be useful in many different application areas such as image recognition \\cite{image_recon}, machine translation \\cite{russian}, recommender systems \\cite{recommender}. Despite this state-of-the-art performance, neural networks are computationally complex and memory-intensive due to their deep structures.\n\nSparse Neural Networks are a viable option to make neural networks less complex and make them memory efficient. Such sparsity in neural networks can be induced by pruning weights, utilizing skip connections, or generating random architectures based on graphs. Sparsity in a neural network can reduce that network's size by many times with little to no drop in performance \\cite{sparse_nn, dey, liu}. Therefore, in this thesis, we implement two different ways to achieve sparsity in Recurrent Neural Networks and analyze its performance impact.\n\n\n% -----------------------------------------------------------------------------------------------------------\n% ------------------------------------------------ MOTIVATION -----------------------------------------------\n% -----------------------------------------------------------------------------------------------------------\n\n\\section{Motivation}\\label{section:motivation}\n\nAs stated before, deep neural networks are likely to have an increased performance but at the cost of higher complexity and increased fast memory requirements. One way to mitigate this issue while maintaining the performance is to introduce sparsity into a network's connections \\cite{deep_res}. For example, Mao et al. in \\cite{mao} report a higher-compression ratio with coarse-grained pruning without loss of accuracy while saving about twice the memory references. Similarly, Sun et al. in \\cite{sparse_face} reported that the sparse ConvNet model, which only has 12\\% of the original parameters, still performs similarly to the baseline model.\n\nThese are just a few examples where Sparse Neural Networks have proven advantageous in time, energy, and memory savings. Sparsity in traditional neural networks and CNNs is studied widely by many researchers but is not explored much in Recurrent Neural Networks that are difficult to train due to their nonlinear iterative nature. Sparse structures in traditional neural networks have shown a promise of training potential \\cite{sparse_nn} which, if applied to Recurrent Neural Networks, can also make training RNNs less difficult by reducing their network size while retaining their performance.\n\n% -----------------------------------------------------------------------------------------------------------\n% -------------------------------------------- RESEARCH QUESTIONS -------------------------------------------\n% -----------------------------------------------------------------------------------------------------------\n\n\\newpage\n\\section{Research questions}\\label{section:research_questions}\n\nThe primary research goal of this master thesis is to investigate the effects of sparse structure on the performance of the Recurrent Neural Networks and its variants, namely Long Short-Term Memory and Gated Recurrent Unit. To do so, we have defined the following set of correlated research questions:\n\n\\begin{enumerate}\n\t\\item\\label{rq:q1} What is the effect of weights pruning on a recurrent network's accuracy?\n\t    \n\t\\item\\label{rq:q2} What percentage of weights pruning is permissible without triggering a significant reduction in the performance?\n\t    \n\t\\item\\label{rq:q3} After pruning a certain percent of weights, if we see a significant reduction in the accuracy,  how many re-training epochs can regain accuracy?\n\t    \n\t\\item\\label{rq:q4} How does a randomly structured recurrent network's performance correlate with the graph properties of its internal structure?\n\t\n\t\\item\\label{rq:q5} Is it possible to predict a randomly structured recurrent network's performance using the graph properties of its base random graph?\n\\end{enumerate}\n\nWe will answer all these questions for four different recurrent networks, namely RNN with Tanh nonlinearity (RNN-Tanh), RNN with ReLU nonlinearity (RNN-ReLU), Long Short-Term Memory (LSTM), and Gated Recurrent Unit (GRU), by following the approach explained in section \\ref{section:proposed_approach}.\n\n% -----------------------------------------------------------------------------------------------------------\n% -------------------------------------------- PROPOSED APPROACH --------------------------------------------\n% -----------------------------------------------------------------------------------------------------------\n\n\\newpage\n\\section{Proposed approach}\\label{section:proposed_approach}\n\nTo investigate the effects of sparse structures in recurrent networks, we propose the following three experiments:\n\\begin{enumerate}\n\t\\item \\textbf{Investigating the effects of weights pruning on recurrent networks}: \\\\\n\t    In this experiment, we prune input-to-hidden and hidden-to-hidden weights, both simultaneously and individually.\n\t    \n\t    We start by training a recurrent network on a dataset for a certain number of epochs. Once this training is complete, we follow the process shown in the following flowchart:\n\t    \n\t    \\begin{figure}[h]\n            \\centering\n            \\includegraphics[width=0.5\\linewidth]{images/introduction/flow_1.png}\n            \\caption[Flowchart for the pruning experiment]{The basic flowchart depicting the process of pruning and re-training a trained recurrent network.}\n            \\label{fig:flowchart_pruning}\n        \\end{figure}\n        \n    \t To outline this flowchart, once the initial training is complete, retrieve the learned weights of the trained model, prune the lower $p\\%$ of weights (where $p \\in \\mathbb{Z}:p \\in [1, 100]$), and re-train this pruned model to check for the number of epochs required to regain accuracy.\n    \t \n    \t This experiment will help answer research questions \\ref{rq:q1}, \\ref{rq:q2}, and \\ref{rq:q3}.\n    \t\n\t\\item \\textbf{Analyzing the performance of recurrent networks with randomly structured recurrent networks}: \\\\\n\t    We start by generating randomly structured neural networks by following the technique described by Stier et al. in \\cite{julian} that generate Sparse Neural Networks.\n\n        After generating Sparse Neural Networks, we introduce recurrent connections to generate Sparse RNNs. These recurrent connections are necessary to make each subsequent run dependent on the previous run.\n\n        Once we have Sparse RNNs, we train them on a dataset and compute the correlation between its accuracy and its internal structure's graph properties.\n        \n        This experiment will help answer the \\ref{rq:q4}th research question.\n\t    \n    \\item \\textbf{Performance prediction of a randomly structured neural network:}: \\\\\n        Once we have trained Sparse RNNs, we train three different regressor algorithms with graph properties as features and corresponding accuracy as the target. Since this is a regression problem, we finally report an R-squared value for each RNN variant and each regressor algorithm.\n        \n        This experiment will help answer the \\ref{rq:q5}th research question.\n\\end{enumerate}\n\nAll these three approaches are described in detail in the later chapters.\n\n% -----------------------------------------------------------------------------------------------------------\n% ------------------------------------------------ STRUCTURE ------------------------------------------------\n% -----------------------------------------------------------------------------------------------------------", "meta": {"hexsha": "df073eee8512b2ecdaaaf394904183055cfb4224", "size": 9396, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "LaTeX/chapters/introduction.tex", "max_stars_repo_name": "harshildarji/Master-Thesis", "max_stars_repo_head_hexsha": "062bcba76bb2a7784b388a70a37d615589c13e72", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LaTeX/chapters/introduction.tex", "max_issues_repo_name": "harshildarji/Master-Thesis", "max_issues_repo_head_hexsha": "062bcba76bb2a7784b388a70a37d615589c13e72", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LaTeX/chapters/introduction.tex", "max_forks_repo_name": "harshildarji/Master-Thesis", "max_forks_repo_head_hexsha": "062bcba76bb2a7784b388a70a37d615589c13e72", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 94.9090909091, "max_line_length": 648, "alphanum_fraction": 0.6834823329, "num_tokens": 1748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.3277261353223074}}
{"text": "\\chapter{Hartree-Fock}\n\n\\begin{Exercise}\n    Answer each of the following in one sentence, using words only.\n    \\Question{Define canonical Hartree-Fock orbitals.}\\label{canon_hf}\n    \\Question{Explain why the choice of Hartree-Fock orbitals is not unique.}\\label{unique_hf}\n\\end{Exercise}\n\n\\begin{Answer}\n    \\ref{canon_hf}. Hartree-Fock orbitals are ``canonical'' when the Lagrange multiplier matrix is diagonal.\n    \\ref{unique_hf}. The Hartree-Fock energy and the orbital overlaps are invariant to a unitary transformation, so any unitary variation of the canonical orbitals satisfies the Hartree-Fock optimization conditions.\n\\end{Answer}\n\n\\begin{Exercise}\n    Briefly explain how the Lagrangian approach to constrained optimization works. Draw pictures where necessary.\n\\end{Exercise}\n\n\\begin{Exercise}\n  Determine the functional derivatives of the Hartree-Fock Lagrangian,\n  $\\dfr{\\d\\mc{L}}{\\d\\y_k^*}$\n  and\n  $\\dfr{\\d\\mc{L}}{\\d\\y_k}$.\n\\end{Exercise}\n\n\\begin{Exercise}\n    Derive the following expression for the energy expectation value of a Slater determinant, known as the \\textit{first Slater rule}.\n    \\begin{align*}\n      \\ip{\\F|\\op{H}_e|\\F}\n    =\n    \\sum_{i}^n\n      \\ip{\\y_i|\\op{h}|\\y_i}\n    +\\fr{1}{2}\\sum_{ij}^n\n      \\ip{\\y_i\\y_j||\\y_i\\y_j}\n    \\end{align*}\n\\end{Exercise}\n", "meta": {"hexsha": "ce9c3f8fd40d0affb4a5b8611ef1d375834c8528", "size": 1293, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "exercises/sections/hartree-fock.tex", "max_stars_repo_name": "GQCG-edu/chem-8950", "max_stars_repo_head_hexsha": "a5f58a5feacbae16b02fddd2c74723da1486b8d2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exercises/sections/hartree-fock.tex", "max_issues_repo_name": "GQCG-edu/chem-8950", "max_issues_repo_head_hexsha": "a5f58a5feacbae16b02fddd2c74723da1486b8d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-07-13T12:11:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-13T15:31:47.000Z", "max_forks_repo_path": "exercises/sections/hartree-fock.tex", "max_forks_repo_name": "GQCG-edu/chem-8950", "max_forks_repo_head_hexsha": "a5f58a5feacbae16b02fddd2c74723da1486b8d2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9166666667, "max_line_length": 215, "alphanum_fraction": 0.716937355, "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3277261353223074}}
{"text": "\\documentclass[a4paper, fleqn, 10pt]{report}\n\\usepackage[utf8]{inputenc}\n\\usepackage{t1enc}\n\\usepackage[table, usenames,dvipsnames,svgnames]{xcolor}\n\\usepackage[pdftex]{graphicx}\n\\usepackage{booktabs}\n\\usepackage{setspace}\n\\onehalfspacing\n\\usepackage{fullpage}\n\\usepackage{enumerate}\n\\usepackage{multicol}\n\\usepackage{tikz}\n\\usepackage{amsmath, amsthm, amssymb}\n\\usepackage{caption}\n\\usepackage{subcaption}\n\\usepackage{multirow}\n\n\\usepackage{newtxtext}\n\\usepackage[libertine]{newtxmath}\n%\\usepackage{fourier}\n\n\n\\theoremstyle{definition}\n\\newtheorem{prb}{Problem}[chapter]\n\\newenvironment{prb*}[1]\n  {\\renewcommand\\theprb{\\thechapter.\\arabic{prb}\\rlap{$^{#1}$}}\\prb}\n  {\\endprb}\n  \n\n\\newcommand{\\R}{\\mathbf{R}}\n\\newcommand{\\N}{\\mathbf{N}}\n\\newcommand{\\Z}{\\mathbf{Z}}\n\\newcommand{\\Q}{\\mathbf{Q}}\n\\newcommand{\\C}{\\mathbf{C}}\n\\renewcommand{\\P}{\\mathbf{P}}\n\n\\renewcommand{\\labelitemi}{$\\blacktriangleright$}\n\\renewcommand{\\tan}{\\mathrm{tg}}\n\n\\newcommand{\\mc}[1]{{\\color{Blue}\\tt #1}}\n\\newcommand{\\mck}[1]{{\\tt#1}}\n\n\\DeclareMathOperator{\\ch}{cosh}\n\n\\frenchspacing\n\n\\title{Introduction to Matlab Programming}\n\\author{Problems \\\\[2em] Budapest University of Technology and Economics}\n\\date{2014}\n\n\n\\begin{document}\n\\maketitle\n\\chapter{Arrays and Graphics}\n\\section{Exercises}\n\\begin{prb*}{1}\nUse the documentation to look up the functions: \\mc{atan} and \\mc{atan2}.\nIllustrate the similarity and difference between them.\n\\end{prb*}\n\n\n\\begin{prb*}{1}\nWhat are the results of the following expressions and why:\n\\[\\frac{1}{0},\\: \\frac{0}{0},\\: \\frac{0}{\\infty},\\: \\frac{\\infty}{0},\\: \\frac{\\infty}{\\infty},\\: \\infty + \\infty,\\: \\infty - \\infty,\\: 0\\cdot\\infty, \\: 1^\\infty, 0^0,\\: 0^\\infty,\\: \\infty^0,\\: \\infty^\\infty.\\]\n\\end{prb*}\n\n\\begin{prb*}{1}\nLet $x:=3$ and $y:=7,$ using variables $x$ and $y$ find the value of the following expressions:\n\\begin{multicols}{3}\n\\begin{enumerate}[a)]\n \\item $\\dfrac{x^2-y^2}{x^3y}$\n \\item $x^y-y^x$\n \\item $\\sin(\\pi(x+y)) - \\sqrt{y-x}$\n \\item $\\log_x(y)$\n \\item $e^x + e^{-x} - 2\\ch(x)$\n \\item $\\sqrt[x]{y}$\n\\end{enumerate}\n\\end{multicols}\n\\end{prb*}\n\n\\begin{prb*}{1}\nWrite a program, that converts from kilometers to miles by reading an input (number) from the user.\n\\end{prb*}\n\n\\begin{prb*}{1}\nExplain the results of the following expressions:\n\\[\\mc{uint8}(5-17), \\quad [\\text{'M'},\\: 65,\\: 84,\\: 76,\\: 65,\\: 66], \\quad \\mc{int8}(1-2^{10}), \\quad 1+0.1\\times\\mc{eps}\\: \\text{ opposed to }\\: 1+100\\times\\mc{eps}.\\]\n\\end{prb*}\n\n\\begin{prb*}{2}\nMake the following lists using only the colon operator (\\mc{:}), \\mc{linspace} and arithmetics:\n\\begin{multicols}{2}\n\\begin{enumerate}[a)]\n \\item $[0, 2, 4, 6, \\dots, 20]$\n \\item $[11, 9, \\dots, -9, -11]$\n \\item $[0.001, 0.01, \\dots, 1000, 10000]$\n \\item $[1, 2, 4, 8, \\dots, 1024]$\n \\item $[\\underbrace{1,-1,1,-1,\\dots, 1,-1}_{20}]$\n \\item the list obtained by dividing the unit interval $[0, 1]$ to 5 equal parts (boundary points included) \n \\item the list obtained by dividing the interval $[0, 2\\pi)$ to 7 equal parts ($0$ included, $2\\pi$ excluded) \n\\end{enumerate}\n\\end{multicols}\n\\end{prb*}\n\n\\begin{prb*}{1}\nRun the following command and explain the result:  \n\\[\\mathrm{\\mc{char}}(\\mathrm{\\mc{cumsum}}([117,\\:-2,\\:-14,\\:13,\\:-50,\\:45,\\:-12,\\:8,\\:3,\\:-62,\\:53,\\:12,\\:-2])).\\]\nCan you do your own version?\n\\end{prb*}\n\n\\begin{prb*}{2}\nMake a list $X$ of 20 random integers: $-10\\le X_k\\le 30$ with uniform distribution.\nNow, select the following entries of this list:\n\\begin{multicols}{2}\n\\begin{enumerate}[a)]\n \\item negative entries\n \\item entries greater than or equal to $7$\n \\item entries greater than $-5$ and less than or equal to $12$\n \\item odd entries\n \\item entries divisible by 3 or 7\n \\item entries dividing 360\n\\end{enumerate}\n\\end{multicols}\n\\end{prb*}\n\n\\begin{prb*}{2}\nDefine the following functions using anonymus functions:\n\\begin{multicols}{2}\n\\begin{enumerate}[a)]\n \\item $\\mathrm{sum\\_n}(n) := 1 + 2 + \\dots + n$\n \\item $\\mathrm{sum\\_square}(n):= 1^2 + 2^2 + \\dots + n^2$\n \\item $\\mathrm{fact}(n) := n!$\n \\item $\\mathrm{binom}(n,k) := \\binom{n}{k}$\n \\item $\\mathrm{ln2}(n) := 1 - \\frac{1}{2} + \\frac{1}{3} - \\frac{1}{4} + \\dots + \\frac{(-1)^{n+1}}{n}$\n \\item $\\mathrm{sol\\_quad}(a, b) := [\\frac{-a-\\sqrt{a^2-4b}}{2}, \\frac{-a+\\sqrt{a^2-4b}}{2}]$\n \\item $\\mathrm{cum\\_avr}([x_1, x_2, \\dots, x_n]) := [x_1, \\frac{x_1 + x_2}{2}, \\dots, \\frac{x_1 + x_2 + \\dots + x_n}{n}]$\n \\item $\\mathrm{first}([x_1, x_2, \\dots, x_n]) := x_1$\n \\item $\\mathrm{rest}([x_1, x_2, \\dots, x_n]) := [x_2, x_3, \\dots, x_n]$\n \\item $\\mathrm{take}([x_1, x_2, \\dots, x_n], m) := [x_1, x_2, \\dots, x_m]$\n \\item $\\mathrm{drop}([x_1, x_2, \\dots, x_n], m) := [x_{m+1}, x_{m+2}, \\dots, x_n]$\n\\end{enumerate}\n\\end{multicols}\n\\end{prb*}\n\n\\begin{prb*}{2}\nMake the following matrices using only the colon operator (\\mc{:}), \\mc{diag}, \\mc{zeros},\n\\mc{ones}, \\mc{eye}, \\mc{repmat}, \\mc{reshape}, \\mc{cat}, \\mc{flipdim}, \\mc{padarray} and arithmetics:\n\\begin{multicols}{3}\n\\begin{enumerate}[a)]\n\\item $\\displaystyle\n\\begin{bmatrix}\n0 & 1 & 0 & 1 & 0 & 1\\\\\n1 & 0 & 1 & 0 & 1 & 0\\\\\n0 & 1 & 0 & 1 & 0 & 1\\\\\n1 & 0 & 1 & 0 & 1 & 0\n\\end{bmatrix}\n$\n\\item $\\displaystyle\n\\begin{bmatrix}\n2 & 5 & 0 & 0 & 0 & 0\\\\\n7 & 2 & 5 & 0 & 0 & 0\\\\\n0 & 7 & 2 & 5 & 0 & 0\\\\\n0 & 0 & 7 & 2 & 5 & 0\\\\\n0 & 0 & 0 & 7 & 2 & 5\\\\\n0 & 0 & 0 & 0 & 7 & 2\n\\end{bmatrix}\n$\n\n\\item $\\displaystyle\n\\begin{bmatrix}\n1 & 1 & 1 & 1\\\\\n2 & 2 & 2 & 2\\\\\n3 & 3 & 3 & 3\\\\\n4 & 4 & 4 & 4\n\\end{bmatrix}\n$\n\n\\item $\\displaystyle\n\\begin{bmatrix}\n1 & 4 & 7 & 10\\\\\n0 & 0 & 0 & 0\\\\\n2 & 5 & 8 & 11\\\\\n0 & 0 & 0 & 0\\\\\n3 & 6 & 9 & 12\\\\\n0 & 0 & 0 & 0\n\\end{bmatrix}\n$\n\n\\item $\\displaystyle\n\\begin{bmatrix}\n0 & 0 & 0 & 0 & 0 & 0 & 0\\\\\n0 & 0 & 1 & 1 & 1 & 0 & 0\\\\\n0 & 0 & 1 & 1 & 1 & 0 & 0\\\\\n0 & 0 & 0 & 0 & 0 & 0 & 0\n\\end{bmatrix}\n$\n\n\\item $\\displaystyle\n\\begin{bmatrix}\n0 & 0 & 0 & 3 & 3 & 1 & 1\\\\\n0 & 0 & 0 & 3 & 3 & 1 & 1\\\\\n2 & 2 & 2 & 3 & 3 & 1 & 1\\\\\n2 & 2 & 2 & 3 & 3 & 5 & 5\\\\\n0 & 0 & 0 & 3 & 3 & 5 & 5\\\\\n0 & 0 & 0 & 3 & 3 & 5 & 5\n\\end{bmatrix}\n$\n\\end{enumerate}\n\\end{multicols}\n\\end{prb*}\n\n\\begin{prb*}{1}\nMake a $10\\times10$ multiplication table. Could you do it in modulo $11$ residue class?\n\\end{prb*}\n\n\\begin{prb*}{2}\nMake a $5\\times6$ matrix $X$ of random integers $0\\le X_{ij}\\le 50,$\nthen determine the\n\\begin{multicols}{3}\n\\begin{enumerate}[a)]\n \\item maximum of each column,\n \\item minimum of each row,\n \\item sum of the rows,\n \\item sum of the even columns,\n \\item sum of the first and last columns,\n \\item even entries,\n \\item number of zeros,\n \\item largest entry,\n \\item three smallest entries.\n\\end{enumerate}\n\\end{multicols}\n\\end{prb*}\n\n\\begin{prb*}{3}\nConsider Table \\ref{tab:experiment} containing experiment data on 30 subjects.\nMake a random test table, and determine the:\n\\begin{multicols}{2}\n\\begin{enumerate}[a)]\n \\item IDs of all female,\n \\item ID of the youngest male,\n \\item IDs of those scored $\\ge0.5,$\n \\item mean and standard deviation of the scores\n \\item mean age of those scored $\\le 0.2,$\n \\item gender ratio,\n \\item IDs of females past 35,\n \\item mean scores of males younger than 37,\n \\item gender ratio of those scored $\\ge 0.7,$\n \\item IDs of females scored $\\le 0.3$ or younger than $40.$\n\\end{enumerate}\n\\end{multicols}\n\\begin{table}[ht!]\n\\centering\n\\begin{tabular}{cccc}\n\\toprule\n ID & Gender (1--M, 2--F) & Age (20--50) & Score (0--1)\\\\\n \\midrule\n 1  & 2 & 32 & 0.68\\\\\n 2  & 2 & 28 & 0.78\\\\\n 3  & 1 & 47 & 0.98\\\\\n 4  & 2 & 45 & 0.43\\\\\n \\vdots & \\vdots & \\vdots & \\vdots\\\\[0.5em]\n 30  & 1 & 22 & 0.73\\\\\n \\bottomrule\n\\end{tabular}\n\\caption{Example of the experiment data}\\label{tab:experiment}\n\\end{table}\n\\end{prb*}\n\n\\begin{prb*}{3}\nGiven a round table with 10 seats.\nLet $0$ and $1$ denote the empty and occupied seats, respectively.\nThe seats are randomly taken, that is we have a list of random 0's and 1's.\nCount the number of (non-empty) neighbours within distance of 2 for all seats.\nHow about if the table wasn't round?\n\\end{prb*}\n\n\n\\begin{prb*}{3}\nPlot the following functions in one figure, but in three -- vertically arranged -- seperate axes:\n \\[ \\frac{\\sin(x)}{x},\\: -10\\le x\\le 10, \\qquad \\sin\\left(\\frac{1}{x}\\right),\\: -10\\le x\\le 10, \\qquad x^2e^{-x}\\cos(5x),\\: 0\\le x\\le 10.\\]\n\\end{prb*}\n\n\\begin{prb*}{1}\nSimulate a hundred rolls with two dice, and plot the histogram of the result. \n\\end{prb*}\n\n\\begin{prb*}{1}\n Plot the pie chart of the age data in Table \\ref{tab:experiment} for the age groups: 20--30--40--50,\n highlight the most numerous group.\n\\end{prb*}\n\n\\begin{prb*}{1}\n Make 5 figures arranged in an X pattern.\n Make sure that your solution works with any screen resolution. \n\\end{prb*}\n\n\\begin{prb*}{2}\n Draw the following pictures using graphics primitives.\n \\begin{figure}[ht!]\n\\centering\n\\includegraphics[height=4cm]{stop}\\hspace{4cm}\n\\includegraphics[height=4cm]{owl}\n\\end{figure}\n\\end{prb*}\n\n\\begin{prb*}{2}\nDesign your own clock showing the time given by a triplet \\mck{[h, m, s]}.\n\\end{prb*}\n\n\n\n\\newpage\n\\section{Projects}\n\\subsection*{Random Walk in 2D$^{10}$}\nConsider a particle sitting at the origin.\nEvery step the particle makes one of the moves: left, right, up or down\nrandomly with equal probability.\nPlot the particle's trajectory for a few hundred steps as shown in Figure \\ref{fig:rw}.\n\n\\begin{figure}[ht!]\n\\centering\n\\includegraphics[width=0.5\\linewidth]{rwFig}\n\\caption{Trajectory of a random walk.}\\label{fig:rw}\n\\end{figure}\n\n\\subsection*{Monte Carlo Simulation$^{20}$}\nConsider the square having vertices $A(1,-1),\\: B(1,1),\\: C(-1,1),\\: D(-1,-1)$ and -- inside this square -- the unit disk.\nChoose $n$ random points $P(x,y)$ inside the square, i.e. $-1\\le x,y \\le 1.$\nLet $N$ denote the number of points inside the disk, that is $x^2+y^2\\le 1.$\nNow, if $n$ is large enough, then\n\\[\\frac{N}{n} \\approx \\frac{A_{\\text{disk}}}{A_{\\text{square}}} = \\frac{\\pi}{4}.\\]\nWrite a program that simulates the above process.\nDisplay the unit disk and the points, also plot the relative frequency: $\\frac{N}{n}$ for\nall $n=1,2,\\dots$ as shown in Figure \\ref{fig:mc}.\n\n\\begin{figure}[ht!]\n\\centering\n\\includegraphics[width=0.48\\linewidth]{mcFig1}\n\\includegraphics[width=0.48\\linewidth]{mcFig2}\n\\caption{Results of the simulation.}\\label{fig:mc}\n\\end{figure}\n\n\n\n\\subsection*{Convay's Game of Life$^{30}$}\nThis game is played on an $n\\times n$ grid of 1's and 0's,\nwhere 1 and 0 represent living and dead cells, respectively.\nIt is clear that every cell has exactly 8 neighbours,\nexcept along the border.\nHowever, we can view these border cells, as if they had 8 neighbours,\nconsidering the cells outside the border dead.\nThe population of cells advances to a new generation by\napplying the following rules for every cell (from Wikipedia):\n\\begin{itemize}\n \\item Any live cell with fewer than two live neighbours dies, as if caused by under-population.\n \\item Any live cell with two or three live neighbours lives on to the next generation.\n \\item Any live cell with more than three live neighbours dies, as if by overcrowding.\n \\item Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.\n\\end{itemize}\n\nWrite a program that for a given table, computes the next generation.\nFor example:\n\\[\n\\begin{bmatrix}\n 0 & 1 & 1 & 0\\\\\n 1 & 1 & 0 & 1\\\\\n 0 & 1 & 1 & 1\\\\\n 1 & 0 & 1 & 1\n\\end{bmatrix}\n\\quad \\longrightarrow\n\\quad\n\\begin{bmatrix}\n 1 & 1 & 1 & 0\\\\\n 1 & 0 & 0 & 1\\\\\n 0 & 0 & 0 & 0\\\\\n 0 & 0 & 0 & 1\n\\end{bmatrix}\n\\]\nLook up the \\mc{image} object in the documentation, and\nuse it to display the original and new generation in separate figures.\n\n\\subsection*{PageRank$^{30}$}\nThis algorithm was first used by Google to order search results.\nAccording to Google:\n\\begin{quote}\nPageRank works by counting the number and quality of links to a page to determine a rough estimate of how important the website is.\nThe underlying assumption is that more important websites are likely to receive more links from other websites.\n\\end{quote}\nFrom this perspective the internet consists of webpages and links between them (see Figure \\ref{fig:graph}).\n\\begin{figure}[ht!]\n \\centering\n \\includegraphics[width=0.5\\textwidth]{graph}\n \\caption{An example graph with $n=4$ edges.}\\label{fig:graph}\n\\end{figure}\nThe graph in Figure~\\ref{fig:graph} is represented as two arrays: vertecies ($V$) and edges ($E$)\nin the following way:\n\\[V=\n\\begin{bmatrix}\n1 & 2 & 3 & 4\n\\end{bmatrix},\n\\quad\nE=\\begin{bmatrix}\n1 & 1 & 3 & 3 & 4\\\\\n2 & 3 & 1 & 2 & 2\n\\end{bmatrix}.\n\\]\nDenote the number of vertices by $n,$ which is $n=4$ in our example.\nNow we construct the adjacency matrix $A$ of the graph, that is we have $A_{ij}=1$\nif and only if the graph has the edge $i\\to j,$ otherwise $A_{ij}=0.$\nIt could be that, some of the rows have only zero entries, which are quite problematic, therefore\nwe need to substitute every such row with a row full of ones to get a new matrix $B.$\nThis means, that if we have webpages that don't link to anywere, than we assume\ninstead they link to everywhere.\nFor the example graph, they look like this:\n\\[\nA = \n\\begin{bmatrix}\n0 & 1 & 1 & 0\\\\\n0 & 0 & 0 & 0\\\\\n1 & 1 & 0 & 0\\\\\n0 & 1 & 0 & 0\n\\end{bmatrix}\n\\qquad\\longrightarrow\n\\qquad\nB = \n\\begin{bmatrix}\n0 & 1 & 1 & 0\\\\\n1 & 1 & 1 & 1\\\\\n1 & 1 & 0 & 0\\\\\n0 & 1 & 0 & 0\n\\end{bmatrix}.\n\\]\nThe next step is to make sure that every row sums up to one, thus we need to normalize the rows of $B$\nby which we obtain the matrix $M$ with entries\n\\[M_{ij} := \\frac{B_{ij}}{\\sum_{k=1}^n B_{ik}} = \\frac{B_{ij}}{B_{i1} + B_{i2} + \\dots + B_{in}}.\\]\nContinuing the example, we have:\n\\[\nM = \n\\begin{bmatrix}\n0 & \\frac{1}{2} & \\frac{1}{2} & 0\\\\\n\\frac{1}{4} & \\frac{1}{4} & \\frac{1}{4} & \\frac{1}{4}\\\\\n\\frac{1}{2} & \\frac{1}{2} & 0 & 0\\\\\n0 & 1 & 0 & 0\n\\end{bmatrix}.\n\\]\nIn order to regularize the problem, we need to perturb the matrix $M$ with the matrix $S,$\nthat is \\[P:=\\alpha M + (1-\\alpha)S,\\]\nwhere  $S_{ij} := 1/n.$\nFollowing Google's recommendation we set $\\alpha := 0.8.$ The example becomes:\n\\[P = \\frac{4}{5}\\begin{bmatrix}\n0 & \\frac{1}{2} & \\frac{1}{2} & 0\\\\\n\\frac{1}{4} & \\frac{1}{4} & \\frac{1}{4} & \\frac{1}{4}\\\\\n\\frac{1}{2} & \\frac{1}{2} & 0 & 0\\\\\n0 & 1 & 0 & 0\n\\end{bmatrix} + \\frac{1}{5} \n\\begin{bmatrix}\n\\frac{1}{4} & \\frac{1}{4} & \\frac{1}{4} & \\frac{1}{4}\\\\\n\\frac{1}{4} & \\frac{1}{4} & \\frac{1}{4} & \\frac{1}{4}\\\\\n\\frac{1}{4} & \\frac{1}{4} & \\frac{1}{4} & \\frac{1}{4}\\\\\n\\frac{1}{4} & \\frac{1}{4} & \\frac{1}{4} & \\frac{1}{4}\n\\end{bmatrix}=\n\\frac{1}{20}\n\\begin{bmatrix}\n1 & 9 & 9 & 1\\\\\n5 & 5 & 5 & 5\\\\\n9 & 9 & 1 & 1\\\\\n1 & 17 & 1 & 1\n\\end{bmatrix}\n\\]\nNow, in the last step we need to solve the linear equation $P^\\top x=x$ for the unkown vector $x.$\nThis $x$ vector will contain the ranking scores for each webpage.\nThe equation $P^\\top x=x$ is equivalent to the homogeneous equation $(P^\\top-I)x=0,$\nwhere $I$ is the $n\\times n$ identity matrix.\nDue to the earlier regularization, we can be sure there is only one\n$x$ vector satisfying this equation\\footnote{It is clear that both $x$ and let's say $1.34\\cdot x$\nimply the same ranking.\nSo actually, there are infinitely many solutions for $P^\\top x = x,$\nbut they only differ in a scalar factor, thus implying the same ranking.}.\nFinally, normalize the result, so that the ranking scores sum up to 1:\n\\[r := \\frac{x}{\\sum_{i=1}^n x_i}.\\]\nThe ranking scores for the example: $r = [0.223,\\: 0.426,\\: 0.223,\\: 0.128],$\nso the ranking is $R = [2,\\: 3,\\: 1,\\: 4].$\n\nWrite a program that for a given $V$ and $E$ computes the ranking.\nUse randomly generated test graphs to test your program.\nMake sure that the test graph is a simple (directed) graph, i.e. it does not contain\nloops or multiple edges.\n\n\n\n\n\n\n\\chapter{Data Types, Functions and Flow Control}\n\\section{Exercises}\n\\begin{prb*}{3}\nCreate a structure array named {\\tt subject} with the following fields: {\\tt .name}, {\\tt.age}, {\\tt.weight}, {\\tt.height}\nusing data from Table~\\ref{tab:sub}, and determine the\n\\begin{multicols}{2}\n \\begin{enumerate}[a)]\n  \\item average age\n  \\item mean and standard deviation of the weights \n  \\item names of the 3 oldest subjects\n  \\item names of those who are younger than $25$\n  \\item average age of those who are taller than 160\\,cm, and not heavier than 60\\,kg\n  \\item names of those who have height above average\n \\end{enumerate}\n\\end{multicols}\n\\begin{table}[ht!]\n \\centering\n \\begin{tabular}{lccc}\n  \\toprule\n  \\multicolumn{4}{c}{Subject}\\\\\n  \\midrule\n  Name & Age & Weight & Height\\\\\n  \\midrule\n  Judy Garcia  \t  & 23 & 59 & 167\\\\\n  Robert Baker \t  & 22 & 66 & 180\\\\\n  Laura Ross \t  & 28 & 70 & 171\\\\\n  Kimberly Price  & 21 & 45 & 162\\\\\n  Nancy Thompson  & 27 & 90 & 165\\\\\n  Tina Clark \t  & 28 & 77 & 191\\\\\n  \\bottomrule\n \\end{tabular}\n \\caption{Data for creating the structure {\\tt subject}.}\\label{tab:sub}\n\\end{table}\n\\end{prb*}\n\n\\begin{prb*}{5}\n Write a script that you can use to manage the structure {\\tt subject}.\n At the start it should be checked (\\mc{exist}) whether there is a variable in the Work Space called {\\tt subject}\n or not, in the latter case it should be checked if there is a file {\\tt subject.m}, and then loaded (\\mc{load}) into the Work Space.\n If neither the variable nor the file exist; an empty structure should be initialized. \n Create a menu for your program with the following items:\n \\begin{description}\n  \\item[New] Create new entry in {\\tt subject}. The program should ask for the subject's name, age, weight and height. \n  \\item[View] Print out the name of every subject.\n  \\item[Exit] Before quitting, the program should ask whether to save the changes or not, and act accordingly (\\mc{save}). \n \\end{description}\n\\end{prb*}\n\n\n\n\n\\begin{prb*}{5}\nWrite a function that, for a given subject,\ncalculates the body mass index.\nSpecifically, write a function named \\mc{get\\_bmi} with one input and three (optional) outputs:\n\\begin{description}\n \\item[\\mc{get\\_bmi}\\mck{(s)}] prints out the name and textual classification of the subject {\\tt s},\n \\item[\\mck{bmi = }\\mc{get\\_bmi}\\mck{(s)}] gives the body mass index of subject {\\tt s},\n \\item[\\mck{[bmi, bmi\\_class] = }\\mc{get\\_bmi}\\mck{(s)}] gives the body mass index and numeric classification. \n\\end{description}\n\n\\begin{table}[ht!]\n \\centering\n \\begin{tabular}{clc}\n  \\toprule\n  & \\multicolumn{2}{c}{Classification}\\\\\n  \\cmidrule(r){2-3}\n  BMI [$\\mathrm{kg}/\\mathrm{m}^2$] & Text & Number \\\\\n  \\midrule\n  --15 \t & very severely underweight \t& $-3$\\\\\n  15--16 & severely underweight \t& $-2$\\\\\n  16--18.5 & underweight \t\t& $-1$\\\\\n  \\midrule\n  18.5--25 & normal \t\t\t& $0$\\\\\n  \\midrule\n  25--30   & overweight\t\t\t& $1$\\\\\n  30--35   & moderately obese \t\t& $2$\\\\\n  35--   & severely obese \t\t& $3$\\\\\n  \\bottomrule\n \\end{tabular}\\label{tab:BMI}\n \\caption{BMI classification}\n\\end{table}\n\\end{prb*}\n\n\\begin{prb*}{2}\nUsing the following cells\n\\begin{center}\n\\mck{ranks =  \\{2,3,4,5,6,7,8,10,J,Q,K,A\\}},\\quad \\mck{suits =  \\{Clubs,Diamonds,Hearts,Spades\\}}\n\\end{center}\ncreate the standard 52-card deck as a cell containing all pairs: \\mck{\\{\\{'2','Clubs'\\}, \\{'3','Clubs'\\},\\dots\\}}. \n\\end{prb*}\n\n\n\\begin{prb*}{2}\nDetermine how many different ways the number $1729$ can be decomposed to a sum of two cubes of positive integers, i.e. integers $a,b>0$ satisfying $a^3 + b^3 = 1729.$\nUse trial and error for all integers $1\\le a\\le b\\le 12.$\n\\end{prb*}\n\n\n\\begin{prb*}{2}\nUsing trial and error, determine the Pythagorean triples: $a^2 + b^2 = c^2$ for all $1\\le a\\le b\\le c\\le 100$.\n\\end{prb*}\n\n\\begin{prb*}{5}\nLet $M$ a natural number, and consider the (finite) sequence $u(M)=\\begin{bmatrix}u_0 & u_1 & \\dots & u_n\\end{bmatrix}^\\top$\ngenerated by a given function $f\\colon \\N\\to \\N$ in the following way:\n\\[u(M) = \\begin{bmatrix}\n          M& f(M)&\\ f(f(M)) & f^3(M) & \\dots & f^n(M)\n         \\end{bmatrix}\\quad \\text{or equivalently} \\quad u_0:=M,\\ u_{k+1} = f(u_k),\\]\nwhere \n\\[f(n) = \\begin{cases}\n            n/2, & \\text{if }n \\text{ is even,}\\\\\n            3n+1 & \\text{if }n \\text{ is odd,}\n           \\end{cases}\n\\]\nThe famous Collatz conjecture states that starting from any natural number $M$ the sequence $u(M)$ will eventually\nreach $1.$\nAssuming the conjecture is true, let $n$ the smallest number such that $f^n(M) = 1,$\nso that the last element in the list $u(M)$ is $u_n=1.$ \nThe number of steps taken to reach 1 is called stopping time $T(M)$.\nFor example:\n\\[u(17)=[17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1], \\quad T(17) = 12.\\]\nWrite a function named \\mck{u = }\\mc{collatz}\\mck{(M)}.\nPlot $(M,\\max u(M)).$ Plot the histogram of the stopping time $T(M)$ for $2\\le M \\le 500.$\n\\end{prb*}\n\n\\begin{prb*}{4}\nImplement the quicksort algorithm as a function \\mck{v = }\\mc{quicksort}\\mck{(u)}, where\n$u,\\,v$ are lists, and $v$ is the sorted version of $u.$\n\\begin{quote}\nThe quicksort algorithm (from Wikipedia):\n\\begin{enumerate}\n \\item Pick an element, called a pivot, from the array.\n \\item Reorder the array so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.\n \\item Recursively apply the above steps to the sub-array of elements with smaller values and separately to the sub-array of elements with greater values.\n\\end{enumerate}\n\n\n\\end{quote}\n\n\\end{prb*}\n\n\n\\section{Projects}\n\\subsection*{Simple Game$^{30}$}\nIn this game the computer thinks of a number $ 1\\le n\\le 100$, then you have to guess that number.\nEach time you guess, the computer tells you whether your guess is too small or too large.\nAs soon as you guess the correct number the game is over.\nEvery time the game is played the time (score) that was needed to find the number should be recorded.\n\nTo store information about the players and their scores use the structure \\mck{game} with fields:\n\\begin{description}\n \\item[\\mck{.player}] A structure array with fields:\n  \\begin{description}\n  \\item[\\mck{.name}] A string, the name of the player.\n  \\item[\\mck{.time}] A vector containing the player's scores. Should be an empty vector, if no game has been played yet.\n \\end{description}\n \\item[\\mck{.cp}] An integer representing the current player, such that \\mck{game.player(game.cp)} refers to the\n\t\t  structure corresponding to the current player.\n\\end{description}\nMake sure, that the variable \\mck{game} exists in the Work Space by\nloading a previously saved one, or -- if the file does not exist then -- initializing one (with at least one player). \n\nCreate a menu for the game with the following items:\n\\begin{description}\n\\item[Start] \n    Starts the game by calling the function \\mc{start\\_game}.\n    Write a function named \\mck{game\\_new =}\\mc{ start\\_game}\\mck{(game)}, so that -- after finishing the game --\n    it appends the time (needed to succed) to the current player's time vector; and returns with the updated structure \\mck{game\\_new}.\n\\item[Change Player]\n    Change the current player by calling the function \\mc{change\\_player}.\n    Write a function named \\mck{game\\_new = }\\mc{change\\_player}\\mck{(game)} that\n    lists all players, from which the user can choose one; and returns with the structure \\mck{game\\_new}\n    where the current player (\\mck{game.cp}) has been updated -- in accordance with the user's choice.\n\\item[New Player]\n    Add a new player by calling the function \\mc{new\\_player}. Write a function named \\mck{game\\_new = }\\mc{new\\_player}\\mck{(game)} that adds a new entry to the structure array \\mck{game.player} by asking the player's name,\n    and returning with the updated structure \\mck{game\\_new}.\n    The new player's  time vector should be empty. When a new player is added, make sure that the the current player is set to the new player.\n\\item[View Ranking]\n    List the top 5 players and their scores by calling the function \\mc{view\\_ranking}.\n\\item[Quit]\n    Quit the program. Save the variable \\mck{game} using \\mc{save}.\n\\end{description}\nMake sure that besides the menu the current player's name is also displayed.\n\n\\subsection*{Euler Solver$^{30}$}\nDifferential equations play a central role in modeling dynamical systems, such as the weather,\nthe chemical processes in a cell or the motion of a commet.\nHenceforth, we only consider deterministic continuous models that can be described by\nan explicit, first order ordinary differential equation in the form:\n\\begin{equation}\n\\dot x(t) = f(t,x(t)),\\quad x(t_0) = x_0,\\label{eq:ode} \n\\end{equation}\nfor some interval $t\\in [t_0, t_N],$\nwhere $x\\colon \\R\\to\\R^n$ the state variable, and $f\\colon\\R\\times\\R^n\\to\\R^n$ is the model.\nIn general, we can only calculate the approximate solution of \\eqref{eq:ode} in discrete points $t_1,t_2,\\dots,t_N.$\nThe solution at these points are approximated $x(t_n)\\approx x_n$ by using the forward Euler method:\n\\[t_{n+1} = t_n + h, \\quad x_{n+1} = x_n + h f(t_n, x_n), \\qquad n=0,1,\\dots,N-1\\]\nwhere $h$ is the step size, a fixed small positive number.\n\nWrite a function named \\mck{sol = }\\mc{euler\\_solve}\\mck{(ivp)}\nwhere the input \\mck{ivp} is a structure defining the initial value problem \\eqref{eq:ode},\nhaving the following fields:\n\\begin{description}\n \\item[\\mck{.model}] is a function handle for the function $f\\colon \\R\\times\\R^n\\to\\R^n,$\n \\item[\\mck{.initial\\_value}] is the initial vector $x_0\\in\\R^n,$\n \\item[\\mck{.interval}] is an array \\mck{[t0, tN]}, where $t_0$ and $t_N$ are the initial and final time, respectively.\n \\item[\\mck{.step\\_size}] is the step size $h,$ if it's empty use $h:=|t_N-t_0|\\cdot 10^{-3}.$\n\\end{description}\nThe output \\mck{sol} is a structure with fields \\mck{.t} which contains the time vector $[t_0,t_0+h,\\dots,t_0+Nh],$\nand \\mck{.x} which contains the approximation of the solutions $x_1(t),\\,x_2(t),\\dots,x_n(t)$ in its rows.\n\nTest your solver by writing scripts for the following problems:\n\\begin{enumerate}[a)]\n\\item Solve the logistic equation: $\\dot x = x(1-x)$ for the initial values $x(0):=x_0\\in\\{0,0.25,0.5,\\dots,2\\},$\n      and plot the solutions (see Figure \\ref{fig:logistic}).\n\\item Solve the equation $\\ddot u + 2\\xi\\dot u + u = 0$ of a damped oscillator -- with the initial value\n$u(0) := 1,\\: \\dot u(0) := 0$ -- for the damping parameters $\\xi =0.2,0.3,\\dots,1.4,$\n      and plot the solutions (see Figure \\ref{fig:damped}).\\\\\n      {\\it \\small Hint: to write the oscillator in the form of \\eqref{eq:ode} set $x=(x_1\\ \\ x_2)^\\top:=(u\\ \\ \\dot u)^\\top.$}\n      \\begin{figure}[ht!]\n\t\\centering\n\t\\begin{subfigure}[b]{0.48\\textwidth}\n\t  \\includegraphics[width=\\textwidth]{logistic}\n\t  \\caption{Logistic equation for different initial values.}\n\t  \\label{fig:logistic}\n\t\\end{subfigure}\n\t\\begin{subfigure}[b]{0.48\\textwidth}\n\t \\includegraphics[width=\\textwidth]{damped}\n\t \\caption{Damped oscillator for different dampings.}\n\t  \\label{fig:damped}\n\t\\end{subfigure}\n\t\\caption{Solutions of the logistic equation and the damped oscillator.}\n      \\end{figure}\n\n\\item Solve the Lorenz system:\n\t\\begin{equation}\n\t    \\dot u = 10(v-u),\\qquad\n\t    \\dot v = u(28-w)-v,\\qquad\n\t    \\dot w = uv - \\frac{8}{3}z,\\label{eq:lorenz}\n\t\\end{equation}\n\t\\begin{figure}[ht!]\n\t\\centering\n\t \\includegraphics[width=0.8\\textwidth]{lorenz}\n\t \\caption{A trajectory and its projections of the Lorenz System.}\\label{fig:lorenz}\n\t\\end{figure}\n\n      for the initial value $x(0) = (u(0)\\ v(0)\\ w(0))^\\top := (1\\ 1\\ 1)^\\top,$\n      and plot the  trajectory $t\\mapsto (u(t), v(t), w(t))$ in three dimensions using \\mc{plot3} (see Figure~\\ref{fig:lorenz}).\n      Show the following projections of the trajectory as well: $t\\mapsto (30, v(t), w(t)),\\: t\\mapsto (u(t), 30, w(t)),\\: t\\mapsto (u(t), v(t), 0).$\n\\end{enumerate}\n\n\\subsection*{Cellular Automaton$^{30}$}\nLet $x_1=[x_{1,1},x_{1,2},\\dots,x_{1,m}]$ a list of zeros and ones representing the state of the automaton.\nAt each step the state of automaton evolves by a set of rules.\nFor a given rule $r$ the state is updated by\n\\[x_{i+1,k} = f_r(x_{i,k-1}, x_{i,k}, x_{i,k+1}),\\quad k=1,2,\\dots,m\\]\nwith the assumption $x_{i,0} = x_{i,m+1} = 0$ for all $i=1,2,\\dots,n.$\n\\begin{table}[ht!]\\centering\n \\begin{tabular}{ccccccccccccc}\n \\toprule\n      &     &     &  &\\multicolumn{8}{c}{rules} \\\\\n      \\cmidrule{5-13}\n  $a$ & $b$ & $c$ &  & 0 & 1 & 2 & 3 & 4 &\\dots & 30 &\\dots  & 255 \\\\\n  \\midrule\n%  & & & & \\multicolumn{5}{c}{$f_r(u_{k-1},u_k,u_{k+1})$} \\\\\n  0 & 0 & 0 & $d_0(r)$ & 0 & 1 & 0 & 1 & 0 & \\dots & 0 &\\dots & 1\\\\\n  0 & 0 & 1 & $d_1(r)$ & 0 & 0 & 1 & 1 & 0 & \\dots & 1 &\\dots & 1\\\\\n  0 & 1 & 0 & $d_2(r)$ & 0 & 0 & 0 & 0 & 1 & \\dots & 1 &\\dots & 1\\\\\n  0 & 1 & 1 & $d_3(r)$ & 0 & 0 & 0 & 0 & 0 & \\dots & 1 &\\dots & 1\\\\\n  1 & 0 & 0 & $d_4(r)$ & 0 & 0 & 0 & 0 & 0 & \\dots & 1 &\\dots & 1\\\\\n  1 & 0 & 1 & $d_5(r)$ & 0 & 0 & 0 & 0 & 0 & \\dots & 0 &\\dots & 1\\\\\n  1 & 1 & 0 & $d_6(r)$ & 0 & 0 & 0 & 0 & 0 & \\dots & 0 &\\dots & 1\\\\\n  1 & 1 & 1 & $d_7(r)$ & 0 & 0 & 0 & 0 & 0 & \\dots & 0 &\\dots & 1\\\\\n  \\bottomrule\n \\end{tabular}\n\\caption{All possible rules. Columns $0,1,2,\\dots$ contain the digits of the corresponding rule in base 2.}\\label{tab:rules}\n\\end{table}\nAny rule $r=0,1,2,\\dots,255$ in base 2 has at most 8 digits, and can be written as\n\\[r = d_0(r) + 2 d_1(r) + 2^2d_2(r) + \\dots + 2^7d_7(r), \\qquad d_i(r)\\in\\{0,1\\},\\quad i=0,2,\\dots,7.\\]\nThe map $f_r$ is defined as $f_r(a,b,c) = d_i(r),$ where $i=2^2a + 2b + c.$\nFor instance, consider $r = 30 = 2^1 + 2^2 + 2^3 + 2^4,$ so $d_0(30) = 0,\\: d_1(30) = 1,\\: d_2(30) = 1,$ etc.\nTherefore $f_{30}(0,0,0)=d_0(30) = 0,\\: f_{30}(0,0,1)=d_1(30) = 1,\\: f_{30}(0,1,0)=d_2(30) = 1,$ etc., for summary see Table~\\ref{tab:rules}.\n\\begin{figure}[ht!]\n\\centering\n  \\includegraphics[width=0.7\\textwidth]{rule30}\n  \\caption{Rule 30, generated using \\mc{cellular\\_automaton}\\mck{(30,\\,[50,\\,100],\\,50)}.}\\label{fig:automaton}\n\\end{figure}\n\nThe evolution of an initial state $x_1=[x_{1,1},x_{1,2},\\dots,x_{1,m}]$ for $n$ steps is collected in the matrix\n\\[X = \\begin{bmatrix}\n       x_1\\\\\n       x_2\\\\\n       \\vdots\\\\\n       x_n\n      \\end{bmatrix} = \n     \\begin{bmatrix}\n       x_{1,1} & x_{1,2} & \\dots & x_{1,m}\\\\\n       x_{2,1} & x_{2,2} & \\dots & x_{2,m}\\\\\n       \\vdots & \\vdots & \\ddots & \\vdots\\\\\n       x_{n,1} & x_{n,2} & \\dots & x_{n,m}\n      \\end{bmatrix}.\n      \\]\nWrite a function named \\mc{cellular\\_automaton} considering the following specification:\n\\begin{description}\n  \\item[\\mc{cellular\\_automaton}\\mck{(r, [n,\\,m])}] shows the evolution of the initial state $x_1$  as an image by the rule $r$ for $n$ steps, where the initial state is $x_{1,1}=1,$ $x_{1,i}=0$ for all $i=2,\\dots,m.$\n  \\item[\\mc{cellular\\_automaton}\\mck{(r, n)}] is the same as before except $m=n.$\n  \\item[\\mc{cellular\\_automaton}\\mck{(r, [n,\\, m], [i1,\\,i2\\,\\dots,\\,ik])}] is the same as before except the initial state is defined by $x_{1,i}=1$ for all $i\\in\\{i_1,i_2,\\dots,i_k\\}$ and $x_{1,i}=0$ otherwise. See an example in Figure \\ref{fig:automaton}.\n  \\item[\\mck{X = }\\mc{cellular\\_automaton}\\mck{(r, \\dots)}] instead of plotting, it returns with a matrix $X$ containing the states of the automaton as its rows.\n\\end{description}\n\n\\subsection*{Iterated Function System$^{30}$}\nGiven a polygon $S$ in the plane represented by its $m$ vertices $u_{i}=(x_i\\ y_i)^\\top,$ and a set of of affine contraction maps:\n\\[S =  \\begin{bmatrix}\n\t    u_{1}\\\\\n\t    u_{2}\\\\\n\t    \\vdots\\\\\n\t    u_{m}\n        \\end{bmatrix},\\qquad F_i(u):=A_i u + b_i, \\quad A_i\\in\\R^{2\\times 2},\\,b_i\\in\\R^2, \\quad i=1,2,\\dots,n.\\]\nOne can apply $F_i$ to the polygon $S$ and get an other polygon $F_i(S)$ by applying $F_i$\nto every vertices of the polygon in the following way:\n\\[F_i(S) = \n\t    \\begin{bmatrix}\n\t      F_i(u_{1})\\\\\n\t      F_i(u_{2})\\\\\n\t      \\vdots\\\\\n\t      F_i(u_{m})\\\\\n\t    \\end{bmatrix}=\n\t    \\begin{bmatrix}\n\t      A_iu_{1}+b_i\\\\\n\t      A_iu_{2}+b_i\\\\\n\t      \\vdots\\\\\n\t      A_iu_{m}+b_i\\\\\n\t    \\end{bmatrix}.\n\\]\nGenerate new polygons recursively by\n\\[X_{k+1} = \\begin{bmatrix}\n             F_1(X_k) & F_2(X_k) & \\dots\\ & F_n(X_k)\n            \\end{bmatrix}\n, \\qquad X_0 = S,\\]\nwhere $X_k$ is a matrix containing polygons as its columns, and $F_i(X_k)$ means that $F_i$\napplied column-wise, that is applied to every polygon contained in $X_k.$\n\nFor example, when the polygons are triangles $m=3$, and we have two transformations $F_1,\\,F_2$ so that $n=2.$ \n\\[\nX_0 =\\begin{bmatrix}\n      u_{1}\\\\\n      u_{2}\\\\\n      u_{3}\n     \\end{bmatrix},\\quad\nX_1 =\\begin{bmatrix}\n      F_1(X_0) & F_2(X_0)\n     \\end{bmatrix},\\quad\n\\]\n\\[\nX_2 =\\begin{bmatrix}\n      F_1(X_1) & F_2(X_1))\n     \\end{bmatrix}=\n     \\begin{bmatrix}\n      F_1(F_1(X_0)) & F_1(F_2(X_0)) & F_2(F_1(X_0)) & F_2(F_2(X_0))\n     \\end{bmatrix}.\n\\]\n\nWrite a function named \\mc{ifs} considering the following specification:\n\\begin{description}\n \\item[\\mc{ifs}\\mck{(ifs\\_data)}] shows the polygons determined by the input (see below the input specification).\n \\item[\\mck{X = }\\mc{ifs}\\mck{(ifs\\_data)}] instead of plotting it gives the matrix $X_k.$\n \\item[\\mc{ifs}\\mck{(ifs\\_data, 'Color', [1,0,0], \\dots)}] excepts extra arguments as an option for \\mc{patch} object.\n\\end{description}\n\nThe input structure \\mck{ifs\\_data} has the following fields:\n\\begin{description}\n \\item[\\mck{.initial\\_shape}] a vector representing the initial polygon $S.$\n \\item[\\mck{.transformation}] a cell containing the matrices $A_i,\\ i=1,2\\dots,n$\n \\item[\\mck{.dilation}] a cell containing the dilations $b_i,\\ i=1,2\\dots,n$\n \\item[\\mck{.step}] is an integer $N,$ then the iteration goes $N$ steps, thus calculating $X_N.$\n\t\t    Note that the size of $X_N$ is $2m\\times n^N.$\n\\end{description}\n\nTest your function by writing a script for the following problems:\n\\begin{enumerate}[a)]\n \\item Show the 6th approximation of the Sierpinski triangle:\n \\[A_1 = A_2 = A_3 = \\begin{bmatrix}\n          1/2 & 0\\\\\n          0   & 1/2\n         \\end{bmatrix},\\quad\n         b_1 = \\begin{bmatrix}\n          0 \\\\\n          0  \n         \\end{bmatrix},\\quad\n         b_2 = \\begin{bmatrix}\n          1/2 \\\\\n          0  \n         \\end{bmatrix},\\quad\n         b_3 = \\begin{bmatrix}\n          1/4 \\\\\n          \\sqrt{3}/4\n         \\end{bmatrix},\n\\]\nstarting from the equilateral triangle: $S=\\begin{bmatrix}0 & 0 & 1 & 0 & 1/2 & \\sqrt{3}/2\\end{bmatrix}^\\top.$\nThe Figure \\ref{fig:ifs}. shows the first three approximation of the Sierpinski triangle.\nTry out what happens when you start from the square: $S=\\begin{bmatrix}0 & 0 & 1 & 0 & 1 & 1 & 0 & 1\\end{bmatrix}^\\top.$\n\\begin{figure}[ht!]\n\\centering\n  \\includegraphics[width=0.3\\textwidth]{ifs1}\n  \\includegraphics[width=0.3\\textwidth]{ifs2}\n  \\includegraphics[width=0.3\\textwidth]{ifs3}\n  \\caption{Approximations of the the Sierpinski triangle: $X_0,\\,X_1,\\,X_2$.}\\label{fig:ifs}\n\\end{figure}\n\\item Show the 4th approximation of the Sierpinski carpet:\n \\[A_1 =  \\dots = A_8 = \\begin{bmatrix}\n          1/3 & 0\\\\\n          0   & 1/3\n         \\end{bmatrix}\\]\n\\[       b_1 = \\begin{bmatrix}\n          0 \\\\\n          0  \n         \\end{bmatrix},\\\n         b_2 = \\begin{bmatrix}\n          1 \\\\\n          0  \n         \\end{bmatrix},\\\n         b_3 = \\begin{bmatrix}\n          2 \\\\\n          0\n         \\end{bmatrix},\\\n         b_4 = \\begin{bmatrix}\n          0 \\\\\n          1\n         \\end{bmatrix},\\\n         b_5 = \\begin{bmatrix}\n          2 \\\\\n          1\n         \\end{bmatrix},\\\n         b_6 = \\begin{bmatrix}\n          0 \\\\\n          2\n         \\end{bmatrix},\\\n         b_7 = \\begin{bmatrix}\n          1 \\\\\n          2\n         \\end{bmatrix},\\\n         b_8 = \\begin{bmatrix}\n          2 \\\\\n          2\n         \\end{bmatrix},\n\\]\nstarting from the square: $S=\\begin{bmatrix}0 & 0 & 3 & 0 & 3 & 3 & 0 & 3\\end{bmatrix}^\\top.$\n\\begin{figure}[ht!]\n\\centering\n  \\includegraphics[width=0.3\\textwidth]{carpet1}\n  \\includegraphics[width=0.3\\textwidth]{carpet2}\n  \\includegraphics[width=0.3\\textwidth]{carpet3}\n  \\caption{Approximations of the Sierpinski triangle: $X_0,\\,X_1,\\,X_2$.}\\label{fig:ifs}\n\\end{figure}\n\\item Show the 9th approximation of the Dragon curve:\n\\[\nA_1 = \\frac{1}{\\sqrt{2}}\\begin{bmatrix}\n          \\cos(\\pi/4) & \\sin(\\pi/4)\\\\\n          -\\sin(\\pi/4) & \\cos(\\pi/4)\n         \\end{bmatrix},\\quad\nA_2 = \\frac{1}{\\sqrt{2}}\\begin{bmatrix}\n          \\cos(5\\pi/4) & -\\sin(5\\pi/4)\\\\\n          \\sin(5\\pi/4) & \\cos(5\\pi/4)\n         \\end{bmatrix}\n\\]\n\\[       b_1 = \\begin{bmatrix}\n          0 \\\\\n          0  \n         \\end{bmatrix},\\\n         b_2 = \\begin{bmatrix}\n          1 \\\\\n          0  \n         \\end{bmatrix}\n\\]\nin blue (see Figure \\ref{fig:dragon}.), starting from the initial polygon $S= \\begin{bmatrix}0 & -0.05 & 1 & -0.05 & 1 & 0.05 & 0 & 0.05\\end{bmatrix}^\\top.$\n\\begin{figure}[ht!]\n\\centering\n  \\includegraphics[width=0.3\\textwidth]{dragon1}\n  \\includegraphics[width=0.3\\textwidth]{dragon2}\n  \\includegraphics[width=0.3\\textwidth]{dragon3}\n  \\caption{Approximations of the dragon curve: $X_0,\\ X_1,\\ X_2$.}\\label{fig:dragon}\n\\end{figure}\n\\end{enumerate}\n\n\\end{document}\n\n\n\n\\[S_1 = \\begin{bmatrix}\n\t    F_1(u_{1,1}) & F_2(u_1) & \\dots & F_n(u_1)\\\\\n\t    F_1(u_{2,1}) & F_2(u_2) & \\dots & F_n(u_2)\\\\\n\t    \\vdots\\\\\n\t    F_1(u_{m,1}) & F_2(u_m) & \\dots & F_n(u_m)\\\\\n        \\end{bmatrix}\n\\]", "meta": {"hexsha": "700e67d77deedf809dac36952f0c8cd3b4659c79", "size": 36885, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Problems/01_Problems/Problem_01_Matlab.tex", "max_stars_repo_name": "csikja/matlab", "max_stars_repo_head_hexsha": "8151998f9f0242aa16d63155ec9656cd7ec3a40b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Problems/01_Problems/Problem_01_Matlab.tex", "max_issues_repo_name": "csikja/matlab", "max_issues_repo_head_hexsha": "8151998f9f0242aa16d63155ec9656cd7ec3a40b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Problems/01_Problems/Problem_01_Matlab.tex", "max_forks_repo_name": "csikja/matlab", "max_forks_repo_head_hexsha": "8151998f9f0242aa16d63155ec9656cd7ec3a40b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.295247725, "max_line_length": 303, "alphanum_fraction": 0.6441642944, "num_tokens": 13436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6261241702517976, "lm_q1q2_score": 0.3277261316706622}}
{"text": "% Format: LaTeX\n\\documentstyle{report}\n\n\\setlength{\\parskip}{\\baselineskip}\n\\setlength{\\parindent}{0pt}\n\n\\begin{document}\n\n\\chapter{Unsolved Problems}\n\n\\section{Odd Perfect Numbers}\n\nA number is said to be {\\em perfect\\/} if it\nis the sum of its divisors.  For example, $6$ is\nperfect because \\(1+2+3 = 6\\), and $1$, $2$, and $3$\nare the only numbers that divide evenly into $6$ \n(apart from 6 itself).\n\nIt has been shown that all even perfect numbers\nhave the form \\[2^{p-1}(2^{p}-1)\\] where $p$\nand \\(2^{p}-1\\) are both prime.\n\nThe existence of {\\em odd\\/} perfect numbers is \nan open question.\n\\end{document}\n", "meta": {"hexsha": "3119cf8bab454c7fe9b09198e5caaf0f5660f01d", "size": 612, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/examples/perf-ltx.tex", "max_stars_repo_name": "d277/MakingTeXWork", "max_stars_repo_head_hexsha": "1d5bed9ab9f5e078a78d0ed0dbaddc0cf4829777", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-11-18T05:16:30.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-11T07:28:18.000Z", "max_issues_repo_path": "tex/examples/perf-ltx.tex", "max_issues_repo_name": "d277/MakingTeXWork", "max_issues_repo_head_hexsha": "1d5bed9ab9f5e078a78d0ed0dbaddc0cf4829777", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/examples/perf-ltx.tex", "max_forks_repo_name": "d277/MakingTeXWork", "max_forks_repo_head_hexsha": "1d5bed9ab9f5e078a78d0ed0dbaddc0cf4829777", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-09-15T18:03:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T05:34:18.000Z", "avg_line_length": 23.5384615385, "max_line_length": 52, "alphanum_fraction": 0.6928104575, "num_tokens": 192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.32772613167066217}}
{"text": "\\section{Update PAULI-ISO-QMDD after Clifford unitary}\n\nRoughly: two parts. 1: Update rule for general matrices and general (Pauli group) isomorphism QMDD. 2: Update rule for Clifford gates on Pauli isomorphism QMDDs representing stabilizer states.\n\n\n\\subsection{General update rule}\n\n(We assume that the data structures for vectors and matrices have been described in earlier sections.)\n\n1. Produce $\\ket{\\psi}:=A\\ket{\\phi}$, namely  $A\\ket{phi_0}$ en $A\\ket{phi_1}$. Here $A$ \n\n2. Check whether the node $\\ket{\\psi}$ is already in the database.\n\n3. Otherwise, check whether $\\ket{\\psi}$ is $\\mathcal{G}$-isomorphic to a node already in the database. If so, reroute the edges of $\\ket{\\psi}$ to that node, and delete all newly orphaned nodes.\n\n(Bonus algorithm: Compute expectation values: $\\bra{\\psi} H \\ket{\\psi}$. Find a place to put this.)\n\nTODO: Sketch of algorithm on A4.\n\n\\subsection{Special update rule}\n\n\\subsubsection{Applying a CNOT gate}\n\n1. Update rule for CNOT\n\n2. Try to prune the isomorphism into a single global phase\n\n\\subsubsection{Applying a Single-qubit Clifford gate}\n\n1. Expression for Hadamard gate, Phase gate\n\n2. Finding a new isomorphism (work in progress)\n\n\n\n(The remainder of this text is old)\n\nHere, we explain briefly why updating Pauli-ISO-QMDDs after a Clifford is nontrivial in the general case.\nBelow, an algorithm that performs the task is presented\n\n\\subsection{Why the Clifford update is nontrivial}\n\nStabilizer states in Pauli-iso-qmdd has multiple flavours:\n\n\\begin{itemize}\n\\item Z-flavour: read the QMDD as 'in the computational basis'\n\\item Graph-State-flavour: use Z-flavour but only use Pauli strings containing I and Z (at this point, this flavour precisely contains all graph states), while keeping a list of single-qubit Cliffords that will be applied to the graph state.\n\\item Pauli-flavour: for each qubit, keep a flag that indicates whether it is stored in the X,Y or Z-basis\n\\end{itemize}\n\n\nPerforming a single-qubit Clifford in Z-flavour requires an algorithm to update a subpart of the tree with $(\\unit + \\beta P) / \\sqrt{2}$ where $P$ is a Pauli string and $\\beta \\in \\{\\pm 1, \\pm i\\}$.\nThis follows from a local basis transform, which for example for Z to X-basis follows from the identity\n\\[\n    \\ket{0} \\otimes \\ket{\\phi} + \\ket{1} \\otimes P\\ket{\\phi}\n    = \n    \\ket{+} \\otimes \\frac{\\unit + P}{\\sqrt{2}} \\ket{\\phi} + \\ket{-} \\otimes \\frac{\\unit - P}{\\sqrt{2}}\\ket{\\phi}\n.\n\\]\nCNOTs, on the other hard, are straightforward in Z-flavour.\n\nFor Pauli-flavour, the story is reversed: for the same reason, CNOTs are hard but single-qubit Cliffords are trivial.\n\n[For more explanation, see the presentation \\url{miscellaneous/2020_05_19_treeform_clifford_update_difficulty.pdf}]\n\n\n\n\\subsection{An algorithm for the Clifford update}\n\nHere, we sketch how to update a stabilizer state in treeform after application of a single-qubit Clifford or a CNOT.\nWe use the Z-flavour of treeform, i.e. a stabilizer state on $n$ qubit is recursively defined as $\\ket{\\phi} = \\ket{a} \\otimes \\ket{\\psi}$ or $\\ket{\\phi} = (\\ket{0} \\otimes \\ket{\\psi} + \\alpha \\ket{1}\\otimes \\otimes P \\ket{\\psi}) / \\sqrt{2}$, where $a \\in \\{0, 1, \\pm 1, \\pm i\\}$ and $\\alpha \\in \\{\\pm 1, \\pm i\\}$ and $\\ket{\\psi}$ is an $n-1$ qubit stabilizer state (or equals $1$ in case $n=1$).\n\nFirst note that if the most significant qubit is not involved in the application of a Clifford $C$, then in both the knife- and fork cases, it can easily be seen that the Clifford 'propogates' down the tree with little overhead until it meets the first qubit it acts upon:\n\nknife: $C\\ket{a} \\otimes \\ket{\\psi} = \\ket{a} \\otimes \\left( C\\ket{\\psi}\\right)$\n\nfork:\n$\nC \\left( \\ket{0} \\otimes \\ket{\\psi} + \\alpha \\ket{1} \\otimes Q\\ket{\\psi}\\right)\n=\n\\ket{0} \\otimes C\\ket{\\psi} + \\alpha \\ket{1} \\otimes \\left(CQC^{\\dagger}\\right) \\left(C\\ket{\\psi}\\right)\n$\n\n\\subsubsection{Updating stabilizer state in Treeform after a CNOT}\n\nDenote the stabilizer state by $\\ket{\\phi}$\n\n\\textbf{Claim: updating after a CNOT can be done in time $\\mathcal{O}(n^2)$, where $n$ is the number of qubits of $\\ket{\\phi}$.}\n\nWe distinguish two cases.\n\nIf $\\ket{\\phi}$ is a `knife', i.e. $\\ket{\\phi} = \\ket{a} \\otimes \\ket{\\psi}$ for some $a \\in \\{0, 1, \\pm 1, \\pm i\\}$ and $\\ket{\\psi}$ is an $(n-1)$-qubit stabilizer state, then the update is straightforward: if $a\\in \\{0, 1\\}$, then the post-CNOT state is a knife and becomes a fork otherwise.\nFor example, if $\\ket{\\phi} = \\ket{+}\\otimes\\ket{\\psi}$, then $CNOT\\ket{\\phi} = \\ket{0} \\ket{\\psi} + \\ket{1} \\otimes X \\ket{\\psi}$.\n(Note we could still ``reduce'' the tree [in the sense of reducing a decision diagram], which we treat below]\n\nIf $\\ket{\\phi}$ is a `fork', i.e. $\\ket{\\phi} = \\ket{0} \\otimes \\ket{\\psi} + \\alpha \\ket{1}\\otimes \\otimes P \\ket{\\psi}$ (omitting normalization), then $CNOT\\ket{\\phi} = \\ket{0} \\otimes \\ket{\\psi} + \\alpha \\ket{1} \\otimes XP \\ket{\\psi}$.\n\nThe only remaining question is: can we reduce this tree?\nThat is, are the post-CNOT states which are a fork, really a fork or can they also be written as knife?\n\nWe claim that this can be done in time $\\mathcal{O}(n^2)$ by distinguishing the modulus of the expectation value of the fork-operator (i.e. the Pauli-string $Q$ in $\\ket{0} \\otimes \\ket{\\psi} + \\alpha \\ket{1} \\otimes Q\\ket{\\psi}$) with $\\ket{\\phi}$ to equal 1, or to be less.\nTo be precise: if $|\\bra{\\phi} Q \\ket{\\phi}| = 1$, then $Q\\ket{\\phi} = \\bra{\\phi} Q\\ket{\\phi} \\ket{\\phi}$ and thus the fork can be reduced to $\\left(\\ket{0} + \\alpha \\bra{\\phi} Q\\ket{\\phi} \\ket{1} \\right) \\otimes \\ket{\\psi}$, and otherwise it remains as it is.\n\nWe now claim that $\\bra{\\phi} Q \\ket{\\phi}$ can be determined in time $\\mathcal{O}(n^2)$ by recursing over the $n$ qubits, and each step takes at most time $\\mathcal{O}(n)$.\nThe knife case is straightforward: $\\bra{\\phi} A \\ket{\\phi} = \\bra{\\phi} A_0 \\ket{\\phi} \\cdot \\bra{\\phi} A_r \\ket{\\phi}$, and the lefmost expectation value is computed in constant time.\n\n[TODO: IDEA: below, we assume that $A$ is a general string. Can we exploit the fact that we know its structure (i..e $X \\cdot P$ where $P$ is a known string)?]\n\nThe fork case is a bit more involved (omitting adjoint signs since Pauli strings are self-adjoint):\n\\begin{eqnarray}\n\\bra{\\phi} A \\ket{\\phi}\n    &=&\n\\bra{0} A_0 \\ket{0} \\otimes \\bra{\\psi} A_r \\ket{\\psi}\n+\n\\\\\n    &&\n\\bra{1} A_0 Q_0 \\ket{0} \\otimes \\bra{\\psi} A_r Q_r \\ket{\\psi}\n+\n\\\\\n    &&\n\\bra{1} Q_0 A_0 \\ket{0} \\otimes \\bra{\\psi} Q_r A_r \\ket{\\psi}\n+\n\\\\\n    &&\n\\bra{1} Q_0 A_0 Q_0 \\ket{1} \\otimes \\bra{\\psi} Q_r A_r Q_r \\ket{\\psi}\n\\end{eqnarray}\n\nNote by the fact that $Q$ and $A$ are Pauli strings, either the first and last terms or the second and third terms are zero (because Pauli strings either commute or anticommute).\nThe remaining terms only differ by a $\\pm 1$ factor.\nWhich is the case, can be determined by computing whether the string commute or anticommute, which can be done in time $\\mathcal{O}(n)$ since the strings are of length $n$.\nWhat remains is to compute $\\bra{\\psi} Q_r A_r \\ket{\\psi}$ or $\\bra{\\psi} A_r \\ket{\\psi}$ (depending on which terms survive), which is done in the recursive step.\n\n\n\n\n\n\n\\subsubsection{Updating Treeform after a single-qubit Clifford}\n\nUpdating a stabilizer state in treeform $\\ket{\\phi}$ after a single-qubit Clifford for a knife-case is straightforward and uses the fact that the set $\\{\\ket{0}, \\ket{1}, \\ket{\\pm}, \\ket{\\pm i}$ is closed under single-qubit Cliffords.\n\n\nFor a fork, the algorithm requires slightly different operations for each Clifford, but for each, the underlying principle is the same and is again based on the fact that they map the set of single-qubit stabilizer states to itself.\n\nAs an example, we treat the application of $H$ to the first qubit of the state $\\ket{0} \\otimes \\ket{\\psi} + \\alpha \\ket{1} \\otimes P \\ket{\\psi}$, which equals\n\\[\n\\ket{+} \\otimes \\ket{\\psi} + \\alpha \\ket{-} \\otimes P \\ket{\\psi}\n\\]\nand can be rewritten as\n\\[\n    \\ket{0} \\otimes (\\unit + \\alpha P) \\ket{\\psi} + \\ket{1} \\otimes (\\unit - \\alpha P) \\ket{\\psi}\n    .\n\\]\n\nNow we need two things:\n\n- a pauli string $A$ that maps $\\unit + \\alpha P$ to $\\unit - \\alpha P$. Any string that anitcommutes with $P$ will do [TODO NEEDS CHECKING!] and can be found in time $\\mathcal{O}(n)$.\n\n- rewriting $(\\unit + \\alpha P) \\ket{\\psi}$ in treeform. This is more involved and can be done recursively on the size of $\\ket{\\psi}$. At each level, it is required to check whether $P$ and the fork-operator of that level commute or anticommute (in a similar fashion to the `reduction of the tree' in the CNOT-application explained above) and thus requires a total runtime of $\\mathcal{O}(n^2)$.\n\n\n\n\n", "meta": {"hexsha": "89ffb9fe5eeeb9c9080957a4f1da8a66354f95cb", "size": 8661, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Src/CS/sections/stabilizer_update_rule.tex", "max_stars_repo_name": "Katafotic/latex_parsing", "max_stars_repo_head_hexsha": "f00a9547b2034f4592e732a382cdbd34e11e13db", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Src/CS/sections/stabilizer_update_rule.tex", "max_issues_repo_name": "Katafotic/latex_parsing", "max_issues_repo_head_hexsha": "f00a9547b2034f4592e732a382cdbd34e11e13db", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Src/CS/sections/stabilizer_update_rule.tex", "max_forks_repo_name": "Katafotic/latex_parsing", "max_forks_repo_head_hexsha": "f00a9547b2034f4592e732a382cdbd34e11e13db", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.8109756098, "max_line_length": 396, "alphanum_fraction": 0.6991109572, "num_tokens": 2688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.327726128019017}}
{"text": "\\documentclass{report}\n\n\\usepackage[a4paper, margin=2cm]{geometry}\n\\usepackage{textgreek}\n\\usepackage{mathpartir}\n\\usepackage{mathtools}\n\\usepackage{amssymb}\n\n\\allowdisplaybreaks[1]\n\\newtagform{nowidth}{\\llap\\bgroup(}{)\\egroup}\n\n\\newcommand{\\theLang}{myml}\n\\newcommand{\\code}{\\mathtt}\n\\newcommand{\\backtick}{{}^{\\backprime}}\n\\newcommand{\\ruleTag}[1]{\\label{#1}\\tag{\\textsc{#1}}}\n\\DeclareMathOperator{\\domain}{dom}\n\\DeclareMathOperator{\\union}{union}\n\\DeclareMathOperator{\\find}{find}\n\\DeclareMathOperator{\\describeContextScheme}{descCtxScm}\n\\DeclareMathOperator{\\describeScheme}{descScm}\n\\DeclareMathOperator{\\describeType}{descType}\n\\DeclareMathOperator{\\describeRow}{descRow}\n\\DeclareMathOperator{\\describePresence}{descPre}\n\\DeclareMathOperator{\\describePresenceWithType}{descPT}\n\\DeclareMathOperator{\\instantiate}{inst}\n\\DeclareMathOperator{\\instantiateType}{instType}\n\\DeclareMathOperator{\\instantiateRow}{instRow}\n\\DeclareMathOperator{\\instantiatePresence}{instPre}\n\\DeclareMathOperator{\\generalizeValue}{genVal}\n\\DeclareMathOperator{\\generalize}{gen}\n\\DeclareMathOperator{\\freeVariable}{fv}\n\\DeclareMathOperator{\\freeVariableWithKind}{fvKind}\n\\DeclareMathOperator{\\dangerousVariable}{dv}\n\\DeclareMathOperator{\\dangerousVariableRecordRow}{dvRcdRow}\n\\DeclareMathOperator{\\dangerousVariableRecordPresence}{dvRcdPre}\n\\DeclareMathOperator{\\dangerousVariableVariantRow}{dvVariantRow}\n\\DeclareMathOperator{\\dangerousVariableVariantPresence}{dvVariantPre}\n\\DeclareMathOperator{\\unify}{unify}\n\\DeclareMathOperator{\\unifyRow}{unifyRow}\n\\DeclareMathOperator{\\unifyPresence}{unifyPre}\n\\DeclareMathOperator{\\unifyPresenceWithType}{unifyPT}\n\\newcommand{\\newVariable}{newvar}\n\\newcommand{\\newVariables}{newvars}\n\\newcommand{\\entails}{\\vdash}\n\\newcommand{\\typingRelation}[5]{#1, #2 \\entails #3 \\;:\\; #4 ,\\; #5}\n\\newcommand{\\composite}{\\circ}\n\\newcommand{\\definedAs}{\\stackrel{def}{=}}\n\\newcommand{\\sequencing}{;\\;}\n\n\\title{The Definition of \\theLang}\n\\author{Lin Yinfeng}\n\n\\begin{document}\n\n\\maketitle\n\n\\tableofcontents\n\n\\chapter{\\theLang{} the Calculus}\n\n\\section{Syntax}\n\n\\subsection{Term}\n\n\\begin{align*}\n\\code{t} \\Coloneqq \\quad & & \\text{term} \\\\\n& \\code{\\lambda\\ x.\\ t} & \\text{abstraction} \\\\\n| \\quad & \\code{t\\ t} & \\text{application} \\\\\n| \\quad & \\code{x} & \\text{variable} \\\\\n| \\quad & \\code{let\\ x = t\\ in\\ t} & \\text{let-in} \\\\\n| \\quad & \\code{\\{\\ \\}} & \\text{empty record} \\\\\n| \\quad & \\code{extend(l)} & \\text{record extend} \\\\\n| \\quad & \\code{update(l)} & \\text{record update} \\\\\n| \\quad & \\code{access(l)} & \\text{record access} \\\\\n| \\quad & \\code{[\\ ]} & \\text{empty match} \\\\\n| \\quad & \\code{extend(\\backtick l)} & \\text{match extend} \\\\\n| \\quad & \\code{update(\\backtick l)} & \\text{match update} \\\\\n| \\quad & \\code{\\backtick l} & \\text{variant creation} \\\\\n| \\quad & \\code{ref} & \\text{reference} \\\\\n| \\quad & \\code{!} & \\text{dereference} \\\\\n| \\quad & \\code{\\coloneqq} & \\text{assignment} \\\\\n| \\quad & \\code{l} & \\text{location} \\\\\n| \\quad & \\code{new} & \\text{new}\n\\end{align*}\n\n\\subsection{Derived Form}\n\n\\begin{align*}\n\\lambda\\ \\_ .\\ \\code{t} \\definedAs & \\lambda\\ \\code{x}.\\ \\code{t} \\quad \\text{where \\(\\code{x} \\not\\in \\freeVariable(\\code{t})\\)} \\\\\n\\code{t}_1\\sequencing\\code{t}_2 \\definedAs & (\\lambda\\ \\_ .\\ \\code{t}_2)\\ \\code{t}_1\n\\end{align*}\n\n\\subsection{Value}\n\n\\begin{align*}\n\\code{v} \\Coloneqq \\quad & & \\text{value} \\\\\n& \\code{\\lambda\\ x.\\ t} & \\text{abstraction} \\\\\n| \\quad & \\code{rv} & \\text{record value} \\\\\n| \\quad & \\code{mv} & \\text{match value} \\\\\n| \\quad & \\code{\\backtick l\\ v} & \\text{variant} \\\\\n| \\quad & \\code{extend(l)} & \\text{record extend 1} \\\\\n| \\quad & \\code{extend(l)\\ v} & \\text{record extend 2} \\\\\n| \\quad & \\code{update(l)} & \\text{record update 1} \\\\\n| \\quad & \\code{update(l)\\ v} & \\text{record update 2} \\\\\n| \\quad & \\code{access(l)} & \\text{record access} \\\\\n| \\quad & \\code{extend(\\backtick l)} & \\text{match extend 1} \\\\\n| \\quad & \\code{extend(\\backtick l)\\ v} & \\text{match extend 2} \\\\\n| \\quad & \\code{update(\\backtick l)} & \\text{match update 1} \\\\\n| \\quad & \\code{update(\\backtick l)\\ v} & \\text{match update 2} \\\\\n| \\quad & \\code{\\backtick l} & \\text{variant creation} \\\\\n| \\quad & \\code{ref} & \\text{reference} \\\\\n| \\quad & \\code{!} & \\text{dereference} \\\\\n| \\quad & \\code{\\coloneqq} & \\text{assignment 1} \\\\\n| \\quad & \\code{\\coloneqq\\ v} & \\text{assignment 2} \\\\\n| \\quad & \\code{l} & \\text{location}\n\\end{align*}\n\n\\begin{align*}\n\\code{rv} \\Coloneqq \\quad & & \\text{record value} \\\\\n& \\code{\\{\\ \\}} & \\text{empty record} \\\\\n| \\quad & \\code{extend(l)\\ v\\ rv} & \\text{record extend}\n\\end{align*}\n\n\\begin{align*}\n\\code{mv} \\Coloneqq \\quad & & \\text{match value} \\\\\n& \\code{[\\ ]} & \\text{empty match} \\\\\n| \\quad & \\code{extend(\\backtick l)\\ v\\ mv} & \\text{match extend}\n\\end{align*}\n\n\\subsection{Type}\n\n\\begin{align*}\n\\code{T, MT} \\Coloneqq \\quad & & \\text{monomorphic type} \\\\\n& \\code{X} & \\text{type variable} \\\\\n& \\code{MT \\rightarrow MT} & \\text{arrow} \\\\\n& \\code{\\{\\ R\\ \\}} & \\text{record} \\\\\n& \\code{[\\ R\\ ]} & \\text{variant} \\\\\n& \\code{\\mu X.\\ MT} & \\text{recursive} \\\\\n& \\code{Ref\\ MT} & \\text{reference}\n\\end{align*}\n\n\\begin{align*}\n\\code{R} \\Coloneqq \\quad & & \\text{row} \\\\\n& \\code{\\cdot} & \\text{empty row} \\\\\n& \\code{X} & \\text{row variable} \\\\\n& \\code{l : P, R} & \\text{presence} \\\\\n& \\code{\\mu X.\\ R} & \\text{recursive}\n\\end{align*}\n\n\\begin{align*}\n\\code{P} \\Coloneqq \\quad & & \\text{presence} \\\\\n& \\code{Absent} & \\text{absent} \\\\\n& \\code{Present\\ MT} & \\text{present} \\\\\n& \\code{X} & \\text{variable} \\\\\n& \\code{X\\ MT} & \\text{variable with type}\n\\end{align*}\n\n\\begin{align*}\n\\code{PT} \\Coloneqq \\quad & & \\text{presence with type} \\\\\n& \\code{PTAbsent} & \\text{absent} \\\\\n& \\code{PTPresent} & \\text{present} \\\\\n& \\code{X} & \\text{variable}\n\\end{align*}\n\n\\begin{align*}\n\\code{PT} \\Coloneqq\\quad & & \\text{polymorphic type} \\\\\n& \\code{MT} & \\text{monomorphic type} \\\\\n& \\code{\\forall\\ X :: K.\\ PT} & \\text{universal qualified}\n\\end{align*}\n\n\\subsection{Kind}\n\n\\begin{align*}\n\\code{K} \\Coloneqq \\quad & & \\text{kind} \\\\\n& \\code{*} & \\text{proper} \\\\\n& \\code{Presence} & \\text{presence} \\\\\n& \\code{Row} & \\text{row} \\\\\n& \\code{K \\Rightarrow K} & \\text{arrow}\n\\end{align*}\n\n\\subsection{Typing Context}\n\n\\begin{align*}\n\\Gamma \\Coloneqq \\quad & & \\text{typing context} \\\\\n& \\code{\\emptyset} & \\text{empty} \\\\\n& \\code{\\Gamma, \\code{x}:\\code{PT}} & \\text{binding}\n\\end{align*}\n\n\\section{Evaluation}\n\nEvaluation of \\theLang{} is defined in small step operational semantic. The relation \\(\\code{t}\\mid\\mu \\longrightarrow \\code{t}\\mid\\mu\\) is the smallest relation satisfying all instances of the following rules.\n\n\\usetagform{nowidth}\n\\begin{gather}\n\\inferrule\n{}\n{(\\lambda\\ \\code{x}.\\ \\code{t}_{12})\\ \\code{v}_2\\mid\\mu \\longrightarrow [\\code{x}\\mapsto\\code{v}_2]\\code{t}_{12} \\mid\\mu}\n\\ruleTag{E-AppAbs}\n\\\\\n\\inferrule\n{\\code{t}_1\\mid\\mu \\longrightarrow \\code{t}'_1\\mid\\mu'}\n{\\code{t}_1\\ \\code{t}_2\\mid\\mu \\longrightarrow \\code{t}'_1\\ \\code{t}_2\\mid\\mu'}\n\\ruleTag{E-App1}\n\\\\\n\\inferrule\n{\\code{t}_2\\mid\\mu \\longrightarrow \\code{t}'_2\\mid\\mu'}\n{\\code{v}_1\\ \\code{t}_2\\mid\\mu \\longrightarrow \\code{v}_1\\ \\code{t}'_2\\mid\\mu'}\n\\ruleTag{E-App2}\n\\\\\n\\inferrule\n{}\n{\\code{let}\\ \\code{x} = \\code{v}_1\\ \\code{in}\\ \\code{t}_2\\mid\\mu \\longrightarrow [\\code{x}\\mapsto\\code{v}_1]\\code{t}_2\\mid\\mu}\n\\ruleTag{E-LetV}\n\\\\\n\\inferrule\n{\\code{t}_1\\mid\\mu \\longrightarrow \\code{t}'_1\\mid\\mu'}\n{\\code{let}\\ \\code{x} = \\code{t}_1\\ \\code{in}\\ \\code{t}_2\\mid\\mu \\longrightarrow \\code{let}\\ \\code{x} = \\code{t}'_1\\ \\code{in}\\ \\code{t}_2\\mid\\mu'}\n\\ruleTag{E-Let}\n\\\\\n\\inferrule\n{}\n{(\\code{extend}(\\backtick \\code{l}_1)\\ \\code{v}_1\\ \\code{mv}_1)\\ (\\backtick \\code{l}_2\\ \\code{v}_2)\\mid\\mu\\longrightarrow\n\\code{mv}_1\\ (\\backtick \\code{l}_2\\ \\code{v}_2)\\mid\\mu}\n\\ruleTag{E-Match1}\n\\\\\n\\inferrule\n{}\n{(\\code{extend}(\\backtick \\code{l})\\ \\code{v}_1\\ \\code{mv}_1)\\ (\\backtick \\code{l}\\ \\code{v}_2)\\mid\\mu\\longrightarrow\n\\code{v}_1\\ \\code{v}_2\\mid\\mu}\n\\ruleTag{E-Match2}\n\\\\\n\\inferrule\n{}\n{\\code{update}(\\backtick \\code{l}_1)\\ \\code{v}_1\\ (\\code{extend}(\\backtick \\code{l}_2)\\ \\code{v}_2\\ \\code{mv}_2)\\mid\\mu\\longrightarrow \\\\\\\\\n\\code{extend}(\\backtick \\code{l}_2)\\ \\code{v}_2\\ (\\code{update}(\\backtick \\code{l}_1)\\ \\code{v}_1\\ \\code{mv}_2)\\mid\\mu}\n\\ruleTag{E-MatUpdate1}\n\\\\\n\\inferrule\n{}\n{\\code{update}(\\backtick \\code{l})\\ \\code{v}_1\\ (\\code{extend}(\\backtick \\code{l})\\ \\code{v}_2\\ \\code{mv}_2)\\mid\\mu\\longrightarrow\n(\\code{extend}(\\backtick \\code{l})\\ \\code{v}_1\\ \\code{mv}_2)\\mid\\mu}\n\\ruleTag{E-MatUpdate2}\n\\\\\n\\inferrule\n{}\n{\\code{access}(\\code{l}_1)\\ (\\code{extend}(\\code{l}_2)\\ \\code{v}_2\\ \\code{mv}_2)\\mid\\mu\\longrightarrow\n\\code{access}(\\code{l}_1)\\ \\code{mv}_2\\mid\\mu}\n\\ruleTag{E-RcdAccess1}\n\\\\\n\\inferrule\n{}\n{\\code{access}(\\code{l})\\ (\\code{extend}(\\code{l})\\ \\code{v}_2\\ \\code{mv}_2)\\mid\\mu\\longrightarrow\n\\code{v}_2\\mid\\mu}\n\\ruleTag{E-RcdAccess2}\n\\\\\n\\inferrule\n{}\n{\\code{update}(\\code{l}_1)\\ \\code{v}_1\\ (\\code{extend}(\\code{l}_2)\\ \\code{v}_2\\ \\code{mv}_2)\\mid\\mu\\longrightarrow \\\\\\\\\n\\code{extend}(\\code{l}_2)\\ \\code{v}_2\\ (\\code{update}(\\code{l}_1)\\ \\code{v}_1\\ \\code{mv}_2)\\mid\\mu}\n\\ruleTag{E-RcdUpdate1}\n\\\\\n\\inferrule\n{}\n{\\code{update}(\\code{l})\\ \\code{v}_1\\ (\\code{extend}(\\code{l})\\ \\code{v}_2\\ \\code{mv}_2)\\mid\\mu\\longrightarrow\n(\\code{extend}(\\code{l})\\ \\code{v}_1\\ \\code{mv}_2)\\mid\\mu}\n\\ruleTag{E-RcdUpdate2}\n\\\\\n\\inferrule\n{\\code{l}\\notin\\domain(\\mu)}\n{\\code{ref}\\ \\code{v}\\mid\\mu\\longrightarrow\\code{l}\\mid(\\mu, \\code{l}\\mapsto\\code{v})}\n\\ruleTag{E-Ref}\n\\\\\n\\inferrule\n{\\mu(\\code{l}) = \\code{v}}\n{\\code{!}\\ \\code{l}\\mid\\mu\\longrightarrow v\\mid\\mu}\n\\ruleTag{E-Deref}\n\\\\\n\\inferrule\n{\\code{l}\\in\\domain(\\mu)}\n{\\code{l}\\coloneqq\\code{v}\\mid\\mu\\longrightarrow \\code{unit}\\mid[\\code{l}\\mapsto\\code{v}]\\mu}\n\\ruleTag{E-Assign}\n\\end{gather}\n\n\\section{Substitution}\n\nA substitution \\([\\code{x}\\mapsto\\code{t}]\\) is a mapping from term or type variables to terms or types. Apply substition \\([\\code{x}\\mapsto\\code{t}_1]\\) to \\(\\code{t}_3\\), is written \\([\\code{x}\\mapsto\\code{t}_1]\\code{t}_2 = \\code{t}_3\\), which replace all occurrence of variable \\(\\code{x}\\) in \\(\\code{t}_2\\) to \\(\\code{t}_1\\). Free variables in \\(\\code{t}_1\\) should not be bound in \\(\\code{t}_3\\). Use \\textalpha-conversion to prevent free variables in \\(\\code{t}_1\\) being bound.\n\n\\section{Typing}\n\n\\subsection{Equivalence Relation}\n\nMaintain an equivalence relation \\(E\\) with Union-Find algorithm.\n\nEvery equivalence class has a descriptor, which is an element in the equivalence class.\n\nThe operation \\(\\find(E, e) = e'\\) return the descriptor of the element \\(e\\) in the equivalence relation \\(E\\).\n\nThe operation \\(\\union(E, a, b) = E'\\) equate the equivalence class of element \\(a\\) and \\(b\\), make the descriptor of the equivalence class of element \\(b\\) as the descriptor of the unioned equivalence class. Return the new equivalence relation \\(E'\\).\n\n\\subsection{Type Description from Equivalence Relation}\n\nEquivalence relation of type, row and presence forms tree representations of monomorphic type.\n\noperation \\(\\describeType(E, V, \\code{T})\\) to convert a monomorphic type \\(\\code{T}\\) into a complete type by continuous replacing variables with its descriptor in equivalence relation \\(E\\).\\(V\\) is a set of variable, variable in the set will not be converted.\n\n\\(\\describeRow(E, V, \\code{R})\\), \\(\\describePresence(E, V, \\code{P})\\), \\(\\describePresenceWithType(E, V, \\code{PT})\\) do the same thing as \\(\\describeType\\) for other kind of types.\n\n\\(\\describeScheme(E, V, \\code{PT})\\) only convert non qualified variables.\n\n\\begin{gather}\n\\inferrule\n{\\describeScheme(E, V \\cup \\{\\code{X}\\}, \\code{PT}) = \\code{PT}'}\n{\\describeScheme(E, V, \\forall\\ \\code{X} :: \\code{K} .\\ \\code{PT}) = \\forall\\ \\code{X} :: \\code{K} .\\ \\code{PT}'}\n\\ruleTag{DescScm-PT}\n\\\\\n\\inferrule\n{}\n{\\describeScheme(E, V, \\code{MT}) = \\describeType(E, V, \\code{MT})}\n\\ruleTag{DescScm-MT}\n\\end{gather}\n\n\\begin{gather}\n\\inferrule\n{\\code{X} \\in V}\n{\\describeType(E, V, \\code{X}) = \\code{X}}\n\\ruleTag{DescType-Var1}\n\\\\\n\\inferrule\n{\\code{X} \\not\\in V \\and\n \\find(E, \\code{X}) = \\code{X}}\n{\\describeType(E, V, \\code{X}) = \\code{X}}\n\\ruleTag{DescType-Var2}\n\\\\\n\\inferrule\n{\\code{X} \\not\\in V \\and\n \\find(E, \\code{X}) = \\code{MT} \\and\n \\code{MT} \\not= \\code{X} \\\\\\\\\n \\describeType(E, V \\cup \\{\\code{X}\\}, \\code{MT}) = \\code{MT}' \\and\n \\code{X} \\not\\in \\freeVariable(\\code{MT}')}\n{\\describeType(E, V, \\code{X}) = \\code{MT}'}\n\\ruleTag{DescType-Var3}\n\\\\\n\\inferrule\n{\\code{X} \\not\\in V \\and\n \\find(E, \\code{X}) = \\code{MT} \\and\n \\code{MT} \\not= \\code{X} \\\\\\\\\n \\describeType(E, V \\cup \\{\\code{X}\\}, \\code{MT}) = \\code{MT}' \\and\n \\code{X} \\in \\freeVariable(\\code{MT}')}\n{\\describeType(E, V, \\code{X}) = \\mu\\code{X}.\\code{MT}'}\n\\ruleTag{DescType-VarRec}\n\\\\\n\\inferrule\n{\\describeType(E, V, \\code{MT}_1) = \\code{MT}'_1 \\\\\\\\\n \\describeType(E, V, \\code{MT}_2) = \\code{MT}'_2}\n{\\describeType(E, V, \\code{MT}_1\\rightarrow\\code{MT}_2) = \\code{MT}'_1\\rightarrow\\code{MT}'_2}\n\\ruleTag{DescType-Arr}\n\\\\\n\\inferrule\n{\\describeRow(E, V, \\code{R}) = \\code{R}'}\n{\\describeType(E, V, \\{\\ \\code{R}\\ \\}) = \\{\\ \\code{R}'\\ \\}}\n\\ruleTag{DescType-Rcd}\n\\\\\n\\inferrule\n{\\describeRow(E, V, \\code{R}) = \\code{R}'}\n{\\describeType(E, V, [\\ \\code{R}\\ ]) = [\\ \\code{R}'\\ ]}\n\\ruleTag{DescType-Variant}\n\\\\\n\\inferrule\n{\\describeType(E, V, \\code{MT}) = \\code{MT}'}\n{\\describeType(E, V, \\code{Ref}\\ \\code{MT}) = \\code{Ref}\\ \\code{MT}'}\n\\ruleTag{DescType-Ref}\n\\\\\n\\inferrule\n{\\describeType(E, V \\cup \\{\\code{X}\\}, \\code{MT}) = \\code{MT}'}\n{\\describeType(E, V, \\mu\\code{X}.\\code{MT}) = \\mu\\code{X}.\\code{MT}'}\n\\ruleTag{DescType-Rec}\n\\end{gather}\n\n\\begin{gather}\n\\inferrule\n{}\n{\\describeRow(E, V, \\cdot) = \\cdot}\n\\ruleTag{DescRow-Empty}\n\\\\\n\\inferrule\n{\\code{X} \\in V}\n{\\describeRow(E, V, \\code{X}) = \\code{X}}\n\\ruleTag{DescRow-Var1}\n\\\\\n\\inferrule\n{\\code{X} \\not\\in V \\and\n \\find(E, \\code{X}) = \\code{X}}\n{\\describeRow(E, V, \\code{X}) = \\code{X}}\n\\ruleTag{DescRow-Var2}\n\\\\\n\\inferrule\n{\\code{X} \\not\\in V \\and\n \\find(E, \\code{X}) = \\code{R} \\and\n \\code{R} \\not= \\code{X} \\\\\\\\\n \\describeRow(E, V \\cup \\{\\code{X}\\}, \\code{R}) = \\code{R}' \\and\n \\code{X} \\not\\in \\freeVariable(\\code{R}')}\n{\\describeRow(E, V, \\code{X}) = \\code{R}'}\n\\ruleTag{DescRow-Var3}\n\\\\\n\\inferrule\n{\\code{X} \\not\\in V \\and\n \\find(E, \\code{X}) = \\code{R} \\and\n \\code{R} \\not= \\code{X} \\\\\\\\\n \\describeRow(E, V \\cup \\{\\code{X}\\}, \\code{R}) = \\code{R}' \\and\n \\code{X} \\in \\freeVariable(\\code{R}')}\n{\\describeRow(E, V, \\code{X}) = \\mu\\code{X}.\\code{R}'}\n\\ruleTag{DescRow-VarRec}\n\\\\\n\\inferrule\n{\\describePresence(E, V, \\code{P}) = \\code{P}' \\and\n \\describeRow(E, \\code{R}) = \\code{R}'}\n{\\describeRow(E, V, (\\code{l}:\\code{P},\\code{R})) = \\code{l}:\\code{P}',\\code{R}'}\n\\ruleTag{DescRow-Pre}\n\\\\\n\\inferrule\n{\\describeRow(E, V \\cup \\{\\code{X}\\}, \\code{R}) = \\code{R}'}\n{\\describeRow(E, V, \\mu\\code{X}.\\code{R}) = \\mu\\code{X}.\\code{R}'}\n\\ruleTag{DescRow-Rec}\n\\end{gather}\n\n\\begin{gather}\n\\inferrule\n{}\n{\\describePresence(E, V, \\code{Absent}) = \\code{Absent}}\n\\ruleTag{DescPre-Abs}\n\\\\\n\\inferrule\n{\\describeType(E, V, \\code{MT}) = \\code{MT}'}\n{\\describePresence(E, V, \\code{Present}\\ \\code{MT}) = \\code{Present}\\ \\code{MT}'}\n\\ruleTag{DescPre-Pre}\n\\\\\n\\inferrule\n{\\find(E, \\code{X}) = \\code{X}}\n{\\describePresence(E, V, \\code{X}) = \\code{X}}\n\\ruleTag{DescPre-Var1}\n\\\\\n\\inferrule\n{\\find(E, \\code{X}) = \\code{P} \\and\n \\code{MT} \\not= \\code{X} \\and\n \\describePresence(E, V, \\code{P}) = \\code{P}'}\n{\\describePresence(E, V, \\code{X}) = \\code{P}'}\n\\ruleTag{DescPre-Var2}\n\\\\\n\\inferrule\n{\\describePresenceWithType(E, V, \\code{X}) = \\code{X} \\\\\\\\\n \\describeType(E, V, \\code{MT}) = \\code{MT}'}\n{\\describePresence(E, V, \\code{X}\\ \\code{MT}) = \\code{X}\\ \\code{MT}')}\n\\ruleTag{DescPre-PTVar1}\n\\\\\n\\inferrule\n{\\describePresenceWithType(E, V, \\code{X}) = \\code{PTAbsent}}\n{\\describePresence(E, V, \\code{X}\\ \\code{MT}) = \\code{Absent}}\n\\ruleTag{DescPre-PTVar2}\n\\\\\n\\inferrule\n{\\describePresenceWithType(E, V, \\code{X}) = \\code{PTPresent} \\\\\\\\\n \\describeType(E, V, \\code{MT}) = \\code{MT}'}\n{\\describePresence(E, V, \\code{X}\\ \\code{MT}) = \\code{Present}\\ \\code{MT}'}\n\\ruleTag{DescPre-PTVar3}\n\\end{gather}\n\n\\begin{gather}\n\\inferrule\n{}\n{\\describePresenceWithType(E, V, \\code{PTAbsent}) = \\code{PTAbsent}}\n\\ruleTag{DescPT-Abs}\n\\\\\n\\inferrule\n{}\n{\\describePresenceWithType(E, V, \\code{PTPREsent}) = \\code{PTPREsent}}\n\\ruleTag{DescPT-Pre}\n\\\\\n\\inferrule\n{\\find(E, \\code{X}) = \\code{X}}\n{\\describePresenceWithType(E, V, \\code{X}) = \\code{X}}\n\\ruleTag{DescPT-Var1}\n\\\\\n\\inferrule\n{\\find(E, \\code{X}) = \\code{PT} \\and\n \\code{PT} \\not= \\code{X}}\n{\\describePresenceWithType(E, V, \\code{X}) = \\describePresenceWithType(E, V, \\code{PT})}\n\\ruleTag{DescPT-Var2}\n\\end{gather}\n\n\\begin{gather}\n\\inferrule\n{}\n{\\describeContextScheme(E, V, \\code{\\emptyset}) = \\code{\\emptyset}}\n\\ruleTag{DescCtxScm-Empty}\n\\\\\n\\inferrule\n{}\n{\\describeContextScheme(E, V, (\\code{x}:\\code{PT}, \\Gamma)) = \\code{x}:\\describeScheme(E, V, \\code{PT}), \\Gamma}\n\\ruleTag{DescCtxScm-Bind}\n\\end{gather}\n\n\\subsection{Instantiation}\n\nInstantiation first replace every qualified type variable with fresh variables, then encode the type as a tree in equivalence relation.\n\n\\begin{gather}\n\\inferrule\n{\\instantiate(E, \\code{PT}) = E', \\code{PT'}}\n{\\instantiate(E, \\code{\\forall\\ X.\\ PT}) = E' , [\\code{X}\\mapsto\\newVariable]\\code{PT'}}\n\\ruleTag{Inst-PT}\n\\\\\n\\instantiate(E, \\code{MT}) = \\instantiateType(E, \\code{MT})\n\\ruleTag{Inst-MT}\n\\end{gather}\n\n\\begin{gather}\n\\inferrule\n{}\n{\\instantiateType(E, \\code{X}) = E , \\code{X}}\n\\ruleTag{InstType-Var}\n\\\\\n\\inferrule\n{\\instantiateType(E, \\code{T}_1) = E_1, \\code{T}'_1 \\and\n\\instantiateType(E_1, \\code{T}_2) = E_2, \\code{T}'_2}\n{\\instantiateType(E, \\code{T}_1\\rightarrow\\code{T}_2) = E_2, \\code{T}'_1\\rightarrow\\code{T}'_2}\n\\ruleTag{InstType-Arr}\n\\\\\n\\inferrule\n{\\instantiateRow(E, \\code{R}) = E', \\code{R}'}\n{\\instantiateType(E, \\{\\ \\code{R}\\ \\}) = E', \\{\\ \\code{R}'\\ \\}}\n\\ruleTag{InstType-Rcd}\n\\\\\n\\inferrule\n{\\instantiateRow(E, \\code{R}) = E', \\code{R}'}\n{\\instantiateType(E, [\\ \\code{R}\\ ]) = E', [\\ \\code{R}'\\ ]}\n\\ruleTag{InstType-Variant}\n\\\\\n\\inferrule\n{\\instantiateType(E, \\code{MT}) = E', \\code{MT}' \\and\n \\union(E', \\code{X}, \\code{MT}') = E''}\n{\\instantiateType(E, \\mu \\code{X}.\\code{MT}) = E'', \\code{X}}\n\\ruleTag{InstType-Rec}\n\\\\\n\\inferrule\n{\\instantiateType(E, \\code{MT}) = E', \\code{MT}'}\n{\\instantiateType(E, \\code{Ref}\\ \\code{MT}) = E', \\code{Ref}\\ \\code{MT}'}\n\\ruleTag{InstType-Ref}\n\\end{gather}\n\n\\begin{gather}\n\\inferrule\n{}\n{\\instantiateRow(E, \\cdot) = E, \\cdot}\n\\ruleTag{InstRow-Empty}\n\\\\\n\\inferrule\n{}\n{\\instantiateRow(E, \\code{X}) = E, \\code{X}}\n\\ruleTag{InstRow-Var}\n\\\\\n\\inferrule\n{\\instantiatePresence(E, \\code{P}) = E', \\code{P}' \\and\n \\instantiateRow(E', \\code{R}) = E'', \\code{R}'}\n{\\instantiateRow(E, (\\code{l}:\\code{P}, \\code{R})) = E'', (\\code{l}:\\code{P}', \\code{R}')}\n\\ruleTag{InstRow-Pre}\n\\\\\n\\inferrule\n{\\instantiateRow(E, \\code{R}) = E', \\code{R}' \\and\n \\union(E', \\code{X}, \\code{R}') = E''}\n{\\instantiateRow(E, \\mu\\code{X}.\\code{R}) = E'', \\code{X}}\n\\ruleTag{InstRow-Rec}\n\\end{gather}\n\n\\begin{gather}\n\\inferrule\n{}\n{\\instantiatePresence(E, \\code{Absent}) = E, \\code{Absent}}\n\\ruleTag{InstPre-Abs}\n\\\\\n\\inferrule\n{\\instantiateType(E, \\code{MT}) = E', \\code{MT}'}\n{\\instantiatePresence(E, \\code{Present}\\ \\code{MT}) = E', \\code{Present}\\ \\code{MT}'}\n\\ruleTag{InstPre-Pre}\n\\\\\n\\inferrule\n{}\n{\\instantiatePresence(E, \\code{X}) = E, \\code{X}}\n\\ruleTag{InstPre-Var}\n\\\\\n\\inferrule\n{\\instantiateType(E, \\code{MT}) = E', \\code{MT}'}\n{\\instantiatePresence(E, \\code{X}\\ \\code{MT}) = E', \\code{X}\\ \\code{MT}'}\n\\ruleTag{InstPre-VarWithType}\n\\end{gather}\n\n\\subsection{Generalization}\n\n\\begin{equation}\n\\begin{split}\n\\generalizeValue(\\Gamma, E, \\code{MT}) & = \\forall\\ \\overline{\\freeVariable(\\code{MT}') \\setminus \\freeVariable(\\Gamma')}.\\ \\code{MT}' \\\\\n\\Gamma' & = \\describeContextScheme(\\Gamma) \\\\\n\\code{MT}' & = \\describeType(E, \\emptyset, \\code{MT})\n\\end{split}\n\\ruleTag{Gen-Value}\n\\end{equation}\n\n\\begin{equation}\n\\begin{split}\n\\generalize(\\Gamma, E, \\code{MT}) & = \\forall\\ \\overline{\\freeVariable(\\code{MT}') \\setminus \\freeVariable(\\Gamma') \\setminus \\dangerousVariable(\\code{MT}')}.\\ \\code{MT}' \\\\\n\\Gamma' & = \\describeContextScheme(\\Gamma) \\\\\n\\code{MT}' & = \\describeType(E, \\emptyset, \\code{MT})\n\\end{split}\n\\ruleTag{Gen-NonValue}\n\\end{equation}\n\n\\subsubsection{Dangerous Variable}\n\nWorking in progress.\n\n\\subsubsection{Replace Covariant Only Present}\n\nWorking in progress.\n\n\\subsection{Typing Relation}\n\n\\begin{gather}\n\\inferrule\n{\\code{X}:\\code{PT} \\in \\Gamma \\and\n \\instantiate(\\code{PT}) = \\code{MT}}\n{\\typingRelation{\\Gamma}{E}{\\code{X}}{\\code{MT}}{E}}\n\\ruleTag{T-Var}\n\\\\\n\\inferrule\n{\\typingRelation{\\Gamma}{E}{\\code{t}_1}{\\code{MT}_1}{E_1} \\and\n \\typingRelation{\\Gamma}{E_1}{\\code{t}_2}{\\code{MT}_2}{E_2} \\\\\\\\\n \\code{X} = \\newVariable \\and\n \\unify(E_2, \\code{MT}_1, \\code{MT}_2\\rightarrow\\code{X}) = E_3}\n{\\typingRelation{\\Gamma}{E}{\\code{t}_1\\ \\code{t}_2}{\\code{X}}{E_3}}\n\\ruleTag{T-App}\n\\\\\n\\inferrule\n{\\code{X} = \\newVariable \\and\n \\typingRelation{(\\Gamma, \\code{x}:\\code{X})}{E}{\\code{t}}{\\code{MT}}{E'}}\n{\\typingRelation{\\Gamma}{E}{\\lambda\\ \\code{x}.\\ \\code{t}}{\\code{X}\\rightarrow\\code{MT}}{E'}}\n\\ruleTag{T-Abs}\n\\\\\n\\inferrule\n{\\typingRelation{\\Gamma}{E}{\\code{t}_1}{\\code{MT}_1}{E_1} \\and\n \\generalize(\\Gamma, E_1, \\code{MT}_1) = \\code{PT}_1 \\\\\\\\\n \\typingRelation{(\\Gamma, \\code{x}:\\code{PT}_1)}{E_1}{\\code{t}_2}{\\code{MT}_2}{E_2}}\n{\\typingRelation{\\Gamma}{E}{\\code{let}\\ \\code{x} = \\code{t}_1\\ \\code{in}\\ \\code{t}_2}{\\code{MT}_2}{E_2}}\n\\ruleTag{T-Let}\n\\\\\n\\inferrule\n{\\typingRelation{\\Gamma}{E}{\\code{t}_1}{\\code{MT}_1}{E_1} \\and\n \\generalizeValue(\\Gamma, E_1, \\code{MT}_1) = \\code{PT}_1 \\\\\\\\\n \\typingRelation{(\\Gamma, \\code{x}:\\code{PT}_1)}{E_1}{\\code{t}_2}{\\code{MT}_2}{E_2}}\n{\\typingRelation{\\Gamma}{E}{\\code{let}\\ \\code{x} = \\code{v}_1\\ \\code{in}\\ \\code{t}_2}{\\code{MT}_2}{E_2}}\n\\ruleTag{T-LetVal}\n\\end{gather}\n\n\\begin{gather}\n\\inferrule\n{}\n{\\typingRelation{\\Gamma}{E}{\\{\\ \\}}{\\{\\ \\cdot\\ \\}}{E}}\n\\ruleTag{T-EmptyRcd}\n\\\\\n\\inferrule\n{\\code{P}, \\code{R}, \\code{PT}, \\code{MT} = \\newVariables}\n{\\typingRelation{\\Gamma}{E}{\\code{extend(l)}}\n {\\code{MT}\\rightarrow\\{\\ \\code{l}:\\code{P}, \\code{R}\\ \\}\\rightarrow\\{\\ \\code{l}:\\code{PT}\\ \\code{MT}, \\code{R}\\ \\}}\n {E}}\n\\ruleTag{T-RcdExtend}\n\\\\\n\\inferrule\n{\\code{R}, \\code{PT}, \\code{MT}_1, \\code{MT}_2 = \\newVariables}\n{\\typingRelation{\\Gamma}{E}{\\code{update(l)}}\n {\\code{MT}_1\\rightarrow\\{\\ \\code{l}:\\code{Present}\\ \\code{MT}_2, \\code{R}\\ \\}\\rightarrow\\{\\ \\code{l}:\\code{PT}\\ \\code{MT}_1, \\code{R}\\ \\}}\n {E}}\n\\ruleTag{T-RcdUpdate}\n\\\\\n\\inferrule\n{\\code{R}, \\code{MT} = \\newVariables}\n{\\typingRelation{\\Gamma}{E}{\\code{access(l)}}\n {\\{\\ \\code{l}:\\code{Present}\\ \\code{MT}, \\code{R}\\ \\}\\rightarrow\\code{MT}}\n {E}}\n\\ruleTag{T-RcdAccess}\n\\\\\n\\inferrule\n{\\code{MT} = \\newVariable}\n{\\typingRelation{\\Gamma}{E}{[\\ ]}{[\\ \\cdot\\ ]\\rightarrow\\code{MT}}{E}}\n\\ruleTag{T-EmptyMatch}\n\\\\\n\\inferrule\n{\\code{MT}_1, \\code{MT}_2, \\code{R}, \\code{P}, \\code{PT} = \\newVariables \\\\\\\\\n \\code{MT} = (\\code{MT}_1\\rightarrow\\code{MT}_2)\\rightarrow([\\ \\code{\\backtick l}:\\code{P}, \\code{R}\\ ]\\rightarrow\\code{MT}_2)\\rightarrow[\\ \\code{\\backtick l}:\\code{PT}\\ \\code{MT}_1, \\code{R}\\ ]\\rightarrow\\code{MT}_2}\n{\\typingRelation{\\Gamma}{E}{\\code{extend(\\backtick l)}}{\\code{MT}}{E}}\n\\ruleTag{T-MatchExtend}\n\\\\\n\\inferrule\n{\\code{MT}_1, \\code{MT}_2, \\code{MT}_3, \\code{R}, \\code{P}, \\code{PT} = \\newVariables \\\\\\\\\n \\code{MT} = (\\code{MT}_1\\rightarrow\\code{MT}_3)\\rightarrow([\\ \\code{\\backtick l}:\\code{Present}\\ \\code{MT}_2, \\code{R}\\ ] \\rightarrow\\code{MT}_3) \\\\\\\\\n \\rightarrow[\\ \\code{\\backtick l}:\\code{PT}\\ \\code{MT}_1, \\code{R}\\ ]\\rightarrow\\code{MT}_3}\n{\\typingRelation{\\Gamma}{E}{\\code{extend(\\backtick l)}}{\\code{MT}}{E}}\n\\ruleTag{T-MatchUpdate}\n\\\\\n\\inferrule\n{\\code{MT}, \\code{R} = \\newVariable}\n{\\typingRelation{\\Gamma}{E}{\\code{\\backtick l}}{\\code{MT}\\rightarrow[\\ \\code{\\backtick l}:\\code{Present}\\ \\code{MT}, \\code{R}\\ ]}{E}}\n\\ruleTag{T-Variant}\n\\\\\n\\inferrule\n{\\code{MT} = \\newVariable}\n{\\typingRelation{\\Gamma}{E}{\\code{ref}}{\\code{MT}\\rightarrow\\code{Ref}\\ \\code{MT}}{E}}\n\\ruleTag{T-Ref}\n\\\\\n\\inferrule\n{\\code{MT} = \\newVariable}\n{\\typingRelation{\\Gamma}{E}{\\code{!}}{\\code{Ref}\\ \\code{MT}\\rightarrow\\code{MT}}{E}}\n\\ruleTag{T-Deref}\n\\\\\n\\inferrule\n{\\code{MT} = \\newVariable}\n{\\typingRelation{\\Gamma}{E}{\\code{:=}}{\\code{Ref}\\ \\code{MT}\\rightarrow\\code{MT}\\rightarrow\\{\\ \\cdot\\ \\}}{E}}\n\\ruleTag{T-Assign}\n\\\\\n\\inferrule\n{\\code{MT} = \\newVariable}\n{\\typingRelation{\\Gamma}{E}{\\code{new}}{(\\code{Ref} \\code{MT}\\rightarrow\\code{MT})\\rightarrow\\code{MT}}{E}}\n\\ruleTag{T-New}\n\\end{gather}\n\n\\subsection{Unification}\n\n\\begin{align*}\n\\unify(E, \\code{MT}_1, \\code{MT}_2) = \\;\n& \\text{let}\\ \\code{S} = \\find(E, \\code{MT}_1)\\ \\text{in} \\\\\n& \\text{let}\\ \\code{T} = \\find(E, \\code{MT}_2)\\ \\text{in} \\\\\n& \\text{if}\\ \\code{S} = \\code{T} \\\\\n& \\quad \\text{then}\\ E \\\\\n& \\text{else}\\ \\text{if}\\ \\code{S} = \\code{X} \\\\\n& \\quad \\text{then}\\ \\union(E, \\code{X}, \\code{T}) \\\\\n& \\text{else}\\ \\text{if}\\ \\code{T} = \\code{X} \\\\\n& \\quad \\text{then}\\ \\union(E, \\code{X}, \\code{S}) \\\\\n& \\text{else} \\\\\n& \\quad \\text{let}\\ E' = \\union(E, \\code{S}, \\code{T})\\ \\text{in} \\\\\n& \\quad \\text{if}\\ \\code{S} = \\code{S}_{1}\\rightarrow\\code{S}_{2}\\ \\text{and}\\ \\code{T} = \\code{T}_{1}\\rightarrow\\code{T}_{2} \\\\\n& \\quad \\quad \\text{then}\\ \\text{let}\\ E'' = \\unify(E', \\code{S}_{1}, \\code{T}_{1})\\ \\text{in}\\ \\unify(E'', \\code{S}_{2}, \\code{T}_{2}) \\\\\n& \\quad \\text{else}\\ \\text{if}\\ \\code{S} = \\{\\ \\code{R}_1\\ \\}\\ \\text{and}\\ \\code{T} = \\{\\ \\code{R}_2\\ \\} \\\\\n& \\quad \\quad \\text{then}\\ \\unifyRow(E', \\code{R}_1, \\code{R}_2) \\\\\n& \\quad \\text{else}\\ \\text{if}\\ \\code{S} = [\\ \\code{R}_1\\ ]\\ \\text{and}\\ \\code{T} = [\\ \\code{R}_2\\ ] \\\\\n& \\quad \\quad \\text{then}\\ \\unifyRow(E', \\code{R}_1, \\code{R}_2) \\\\\n& \\quad \\text{else}\\ \\text{if}\\ \\code{S} = \\code{Ref}\\ \\code{S}'\\ \\text{and}\\ \\code{T} = \\code{Ref}\\ \\code{T}' \\\\\n& \\quad \\quad\\text{then}\\ \\unify(E', \\code{S}', \\code{T}') \\\\\n& \\quad \\text{else} \\\\\n& \\quad \\quad \\text{fail}\n\\end{align*}\n\n\\begin{align*}\n\\unify(E, \\code{R}_1, \\code{R}_2) = \\;\n& \\text{let}\\ \\code{R}'_1 = \\find(E, \\code{R}_1)\\ \\text{in} \\\\\n& \\text{let}\\ \\code{R}'_2 = \\find(E, \\code{R}_2)\\ \\text{in} \\\\\n& \\text{if}\\ \\code{R}'_1 = \\code{R}'_2 \\\\\n& \\quad \\text{then}\\ E \\\\\n& \\text{else}\\ \\text{if}\\ \\code{R}'_1 = \\code{X} \\\\\n& \\quad \\text{then}\\ \\union(E, \\code{X}, \\code{R}'_2) \\\\\n& \\text{else}\\ \\text{if}\\ \\code{R}'_2 = \\code{X} \\\\\n& \\quad \\text{then}\\ \\union(E, \\code{X}, \\code{R}'_1) \\\\\n& \\text{else}\\ \\text{if}\\ \\code{R}'_1 = \\cdot\\ \\text{and}\\ \\code{R}'_2 = \\code{l}:\\code{P},\\code{R}''_2 \\\\\n& \\quad \\text{then}\\ \\text{let}\\ E' = \\unifyPresence(E, \\code{P}, \\code{Absent})\\ \\text{in}\\ \\unifyRow(E', \\code{R}''_2, \\cdot) \\\\\n& \\text{else}\\ \\text{if}\\ \\code{R}'_1 = \\code{l}:\\code{P},\\code{R}''_1\\ \\text{and}\\ \\code{R}'_2 = \\cdot \\\\\n& \\quad \\text{then}\\ \\text{let}\\ E' = \\unifyPresence(E, \\code{P}, \\code{Absent})\\ \\text{in}\\ \\unifyRow(E', \\code{R}''_1, \\cdot) \\\\\n& \\text{else}\\ \\text{if}\\ \\code{R}'_1 = \\code{l}:\\code{P}_1,\\code{R}''_1\\ \\text{and}\\ \\code{R}'_2 = \\code{l}:\\code{P}_2,\\code{R}''_2 \\\\\n& \\quad \\text{then}\\ \\text{let}\\ E' = \\unifyPresence(E, \\code{P}_1, \\code{P}_2)\\ \\text{in}\\ \\unifyRow(E', \\code{R}''_1, \\code{R}''_2) \\\\\n& \\text{else}\\ \\text{if}\\ \\code{R}'_1 = \\code{l}_1:\\code{P}_1,\\code{R}''_1\\ \\text{and}\\ \\code{R}'_2 = \\code{l}_2:\\code{P}_2,\\code{R}''_2 \\\\\n& \\quad \\text{then}\\ \\text{let}\\ \\code{R}_3 = \\newVariable\\ \\code{in} \\\\\n& \\qquad \\text{let}\\ E' = \\unifyRow(E, \\code{R}''_1, (\\code{l}_2:\\code{P}_2,\\code{R}_3))\\ \\text{in}\\ \\unifyRow(E', \\code{R}''_2, (\\code{l}_1:\\code{P}_1,\\code{R}_3)) \\\\\n& \\text{else} \\\\\n& \\quad \\text{fail}\n\\end{align*}\n\n\\begin{align*}\n\\unifyPresence(E, \\code{P}_1, \\code{P}_2) = \\;\n& \\text{let}\\ \\code{P}'_1 = \\find(E, \\code{P}_1)\\ \\text{in} \\\\\n& \\text{let}\\ \\code{P}'_2 = \\find(E, \\code{P}_2)\\ \\text{in} \\\\\n& \\text{if}\\ \\code{P}'_1 = \\code{P}'_2 \\\\\n& \\quad \\text{then}\\ E \\\\\n& \\text{else}\\ \\text{if}\\ \\code{P}'_1 = \\code{X}\\ \\text{then} \\\\\n& \\quad \\text{then}\\ \\union(E, \\code{X}, \\code{P}'_2) \\\\\n& \\text{else}\\ \\text{if}\\ \\code{P}'_2 = \\code{X}\\ \\text{then} \\\\\n& \\quad \\text{then}\\ \\union(E, \\code{X}, \\code{P}'_1) \\\\\n& \\text{else}\\ \\text{if}\\ \\code{P}'_1 = \\code{Present}\\ \\code{MT}_1\\ \\text{and}\\ \\code{P}'_2 = \\code{Present}\\ \\code{MT}_2\\ \\text{then} \\\\\n& \\quad \\text{then}\\ \\unify(E, \\code{MT}_1, \\code{MT}_2) \\\\\n& \\text{else}\\ \\text{if}\\ \\code{P}'_1 = \\code{X}_1\\ \\code{MT}_1\\ \\text{and}\\ \\code{P}'_2 = \\code{Absent}\\ \\text{then} \\\\\n& \\quad \\text{then}\\ \\unifyPresenceWithType(E, \\code{X}_1, \\code{PTAbsent}) \\\\\n& \\text{else}\\ \\text{if}\\ \\code{P}'_1 = \\code{Absent}\\ \\text{and}\\ \\code{P}'_2 = \\code{X}_2\\ \\code{MT}_2\\ \\text{then} \\\\\n& \\quad \\text{then}\\ \\unifyPresenceWithType(E, \\code{X}_2, \\code{PTAbsent}) \\\\\n& \\quad \\text{then}\\ \\unify(E, \\code{MT}_1, \\code{MT}_2) \\\\\n& \\text{else}\\ \\text{if}\\ \\code{P}'_1 = \\code{X}_1\\ \\code{MT}_1\\ \\text{and}\\ \\code{P}'_2 = \\code{Present}\\ \\code{MT}_2\\ \\text{then} \\\\\n& \\quad \\text{then}\\ \\text{let}\\ E' = \\unifyPresenceWithType(E, \\code{X}_1, \\code{PTPresent})\\ \\text{in}\\ \\unify(E', \\code{MT}_1, \\code{MT}_2) \\\\\n& \\text{else}\\ \\text{if}\\ \\code{P}'_1 = \\code{Present}\\ \\code{MT}_1\\ \\text{and}\\ \\code{P}'_2 = \\code{X}_2\\ \\code{MT}_2\\ \\text{then} \\\\\n& \\quad \\text{then}\\ \\text{let}\\ E' = \\unifyPresenceWithType(E, \\code{X}_2, \\code{PTPresent})\\ \\text{in}\\ \\unify(E', \\code{MT}_1, \\code{MT}_2) \\\\\n& \\text{else}\\ \\text{if}\\ \\code{P}'_1 = \\code{X}_1\\ \\code{MT}_1\\ \\text{and}\\ \\code{P}'_2 = \\code{X}_2\\ \\code{MT}_2\\ \\text{then} \\\\\n& \\quad \\text{then}\\ \\text{let}\\ E' = \\unifyPresenceWithType(E, \\code{X}_1, \\code{X}_2)\\ \\text{in}\\ \\unify(E', \\code{MT}_1, \\code{MT}_2) \\\\\n& \\text{else} \\\\\n& \\quad \\text{fail}\n\\end{align*}\n\n\\begin{align*}\n\\unifyPresenceWithType(E, \\code{PT}_1, \\code{PT}_2) = \\;\n& \\text{let}\\ \\code{PT}'_1 = \\find(E, \\code{PT}_1)\\ \\text{in} \\\\\n& \\text{let}\\ \\code{PT}'_2 = \\find(E, \\code{PT}_2)\\ \\text{in} \\\\\n& \\text{if}\\ \\code{PT}'_1 = \\code{PT}'_2 \\\\\n& \\quad \\text{then}\\ E \\\\\n& \\text{else}\\ \\text{if}\\ \\code{PT}'_1 = \\code{X}\\ \\text{then} \\\\\n& \\quad \\text{then}\\ \\union(E, \\code{X}, \\code{PT}'_2) \\\\\n& \\text{else}\\ \\text{if}\\ \\code{PT}'_2 = \\code{X}\\ \\text{then} \\\\\n& \\quad \\text{then}\\ \\union(E, \\code{X}, \\code{PT}'_1) \\\\\n& \\text{else} \\\\\n& \\quad \\text{fail}\n\\end{align*}\n\n\\chapter{\\theLang{} the Language}\n\nWorking in progress.\n\n\\end{document}\n", "meta": {"hexsha": "1105b45030105b39a8eeaaf5021e9e1ce946bc68", "size": 30145, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "spec/specification.tex", "max_stars_repo_name": "linyinfeng/myml", "max_stars_repo_head_hexsha": "6959228bc4f0b35c7e678954b3072c167d662d93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-03-19T08:18:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-25T09:14:07.000Z", "max_issues_repo_path": "spec/specification.tex", "max_issues_repo_name": "linyinfeng/myml", "max_issues_repo_head_hexsha": "6959228bc4f0b35c7e678954b3072c167d662d93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spec/specification.tex", "max_forks_repo_name": "linyinfeng/myml", "max_forks_repo_head_hexsha": "6959228bc4f0b35c7e678954b3072c167d662d93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4070048309, "max_line_length": 485, "alphanum_fraction": 0.6267042627, "num_tokens": 11977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3275202523698191}}
{"text": "% \\documentclass[journal,peerreview,onecolumn]{IEEEtran}\n\\documentclass[journal,10pt]{IEEEtran}\n\\usepackage{etex}\n\\usepackage{cite}\n\\usepackage[pdftex]{graphicx}\n\\graphicspath{{./Fig/}}\n\\DeclareGraphicsExtensions{.pdf,.jpg,.png}\n\\usepackage{amsmath,amssymb,amsthm}\n\\usepackage{algorithm}\n\\usepackage{algorithmic}\n\\usepackage{array}\n\\usepackage[caption=false,font=footnotesize]{subfig}\n% \\usepackage{fixltx2e} % it trigers a warning. It may be useless ?\n\\usepackage{url}\n\\usepackage{listings}\n\\usepackage{multirow}\n\\usepackage{tikz}\n\\usepackage{pgfplots}\n\\usepackage{tabularx}\n\\usepackage{empheq}\n\\usepackage{hyperref}\n\\usepackage{booktabs}\n\\usepackage{minted}\\definecolor{bg}{rgb}{0.95,0.95,0.95}\n\\newcommand\\MyBox[2]{\n  \\fbox{\\lower0.75cm\n    \\vbox to 1.2cm{\\vfil\n      \\hbox to 1.2cm{\\hfil\\parbox{1.4cm}{#1\\\\#2}\\hfil}\n      \\vfil}%\n  }%\n}\n\n% for peerreview\n% \\usepackage{setspace}\n% \\onehalfspacing\n\n\\newtheorem{prop}{Proposition}\n\n% correct bad hyphenation here\n% \\hyphenation{op-tical net-works semi-conduc-tor}\n% \\newcommand{\\rev}[1]{\\textcolor{black}{\\emph{#1}}}\n\\newcommand{\\rev}[1]{\\textcolor{black}{#1}}\n\n\\begin{document}\n%\n% paper title\n% Titles are generally capitalized except for words such as a, an, and, as,\n% at, but, by, for, in, nor, of, on, or, the, to and up, which are usually\n% not capitalized unless they are the first or last word of the title.\n% Linebreaks \\\\ can be used within to get better formatting as desired.\n% Do not put math or special symbols in the title.\n\\title{Large-scale feature selection with Gaussian mixture models for the classification of high dimensional remote sensing images}\n%\n%\n% author names and IEEE memberships\n% note positions of commas and nonbreaking spaces ( ~ ) LaTeX will not break\n% a structure at a ~ so this keeps an author's name from being broken across\n% two lines.\n% use \\thanks{} to gain access to the first footnote area\n% a separate \\thanks must be used for each paragraph as LaTeX2e's \\thanks\n% was not built to handle multiple paragraphs\n%\n\n\\author{Adrien~Lagrange ̃\\IEEEmembership{Student, IEEE},~Mathieu~Fauvel~\\IEEEmembership{Senior, IEEE}~and~Manuel~Grizonnet% <-this % stops a space\n\\thanks{A. Lagrange and M. Fauvel are with the Universit\\'{e} de Toulouse,\nINP-ENSAT, UMR 1201 DYNAFOR, France and with the INRA, UMR 1201\nDYNAFOR, France.}%\n\\thanks{M. Grizonnet is with Centre National d'\\'{E}tudes Spatiales, French Space Agency, Toulouse, France.}%\n\\thanks{This  work was  supported  by the  French National  Research Agency  (ANR)  under  Project Grant  ANR-13-JS02-0005-01  (Asterix project).}}\n\n% The paper headers\n\\markboth{Transactions on Computational Imaging,~Special Issue on Computational Imaging for Earth Sciences, September~2016}{}\n\n% make the title area\n\\maketitle\n\n% \\tableofcontents\n% \\clearpage\n\\begin{abstract}\n  A  large  scale  feature  selection wrapper  is  discussed  for  the\n  classification  of high  dimensional  remote  sensing. An  efficient\n  implementation is proposed based on intrinsic properties of Gaussian\n  mixtures models and  block matrix.  The criterion  function is split\n  into two parts  : one that is  updated to test each  feature and one\n  that needs to be updated only once per feature selection. This split\n  saved  a  lot  of  computation  for each  test.   The  algorithm  is\n  implemented in  \\texttt{C++} and integrated into  the Orfeo Toolbox.\n  It has been compared to  other classification algorithms on two high\n  dimension remote sensing images. Results show that the approach\n  provides good classification accuracies with low computation time.\n\\end{abstract}\n\n% Note that keywords are not normally used for peerreview papers.\n\\begin{IEEEkeywords}\nremote sensing, hyperspectral imaging, feature selection, gaussian mixture model, fast computing.\n\\end{IEEEkeywords}\n\n% For peer review papers, you can put extra information on the cover\n% page as needed:\n% \\ifCLASSOPTIONpeerreview\n% \\begin{center} \\bfseries EDICS Category: 3-BBND \\end{center}\n% \\fi\n%\n% For peerreview papers, this IEEEtran command inserts a page break and\n% creates the second title. It will be ignored for other modes.\n\\IEEEpeerreviewmaketitle\n\n\\section{Introduction}\n\\label{sec:intro}\n\n\\IEEEPARstart{W}{ith} the increasing number of remote sensing missions, the\nquantity of available Earth observation data for a given landscape becomes\nlarger and larger. Satellite missions produce a huge amount of data on a regular\n(daily) basis. From 2018, the EnMAP (Environmental Mapping and Analysis Program)\nsatellites managed by the German space agency will produce images with 244\nspectral bands, a spatial resolution of 30x30m per pixel and with a frequency of\nrevisit of 4 days\\cite{Müller09enmap}. The Hyperspectral Infrared Imager\n(HyspIRI) of NASA will also deliver images with 212 spectral bands. Additionally\nto hyperspectral data, the amount of available hypertemporal data increases a\nlot. For instance, the European satellites Sentinel-2 were launched recently and\n2 Terabytes of data will be released every day~\\cite{drusch2012sentinel}. The\nLandsat open archive\n(\\url{http://landsat.usgs.gov/products_data_at_no_charge.php}) has also released\nthousands of images. Such high volume of Earth observation data provides\naccurate information of land state and functions, and helps to improve the\nunderstanding of the planet~\\cite{rs1010001}. However, processing such data is\nmore and more challenging because of statistical and computational issues.\n\nIn the spectral or temporal domain, a pixel is represented by a vector\nfor   which  each   component  corresponds   to  a   spectral/temporal\nmeasurement.   The size  of  the  vector is  therefore  the number  of\nspectral  or temporal  measurements.  For  hyperspectral images,  this\nnumber is  typically about several  hundreds while for  the Sentinel-2\nmultitemporal images, the number of spectro-temporal measurement for a\ngiven  year  is approximately  one  thousand.   When working  in  high\ndimensional  spaces,  statistical  methods  made for  low  or  moderate\ndimensional  spaces do  not  adapt  well.  For  instance,  the rate  of\nconvergence of the statistical estimation decreases when the dimension\ngrows while jointly the number of parameters to estimate increases,\nmaking    the    estimation    of   the    model    parameters    very\ndifficult~\\cite{donoho}.  Consequently,  with a limited  training set,\nbeyond a certain limit, the classification accuracy actually decreases\nas the number of features increases~\\cite{hughes}.  For the purpose of\nclassification,  these  problems are  related  to  the \\emph{curse  of\n  dimensionality}~\\cite{donoho}.  This is  a  major  drawback in  many\nremote sensing  applications since it  is difficult to collect  a large\nand accurate ground-truth.  An intensive work has been performed in\nthe remote  sensing community to  build accurate classifiers  for high\ndimensional  images.   Bayesian models~\\cite{book:landgrebe},  feature\nextraction              and             feature              reduction\ntechniques~\\cite{book:landgrebe,DR:guided:tour},                random\nforest~\\cite{1396322},   neural  networks~\\cite{5411821}   and  kernel\nmethods~\\cite{kernel:methods:rs}  have   been  investigated   for  the\nclassification of such images.\n\nThe volume of the data is  increasing dramatically with respect to the\nnumber of measurement  per pixel. The data volume  of an hyperspectral\nimage  is  typically several  hundreds  of  Gigabytes per  acquisition\n($\\approx$  300km$^2$). Multitemporal  data are  now available  freely\nfrom  internet  stream  (see  for instance  the  Copernicus  data  hub\n\\url{https://cophub.copernicus.eu/}).  This very  large volume of data\nrequires   specific   computing  infrastructure.    High   performance\ncomputing   is   actually   investigated   by   the   remote   sensing\ncommunity~\\cite{christophe2011remote,plaza2011high}.  Main  issues are\nrelated to the use of parallel approaches (multi-core, GPU, clusters) to\nimprove the  processing time, and  to the use of  streaming techniques\nwhen data  does not fit in  memory.  One popular open  source software\nsolution  is  the Orfeo  Toolbox,  developed  by the  French  Space\nAgency (CNES)~\\cite{christophe2008orfeo}.   Streaming and  parallel computing\nare  conveniently proposed  to  users/developers through  several ``\\emph{ready to use}'' modules.\n\nA method  to reduce  both statistical and  computational issues  is to\nperform a reduction of the dimension. In fact, with the \\emph{curse of\n  dimensionality}     comes     the      \\emph{blessing     of     the\n  dimensionality}~\\cite{bouveyron2014model}:  high   dimensional  data\nspaces   exhibit  interesting   properties   for    classification\npurpose.  In  particular,  it  is   possible  to  get  a  parsimonious\nrepresentation  of  the  data  while  maintaining  or  increasing  the\nclassification  accuracy~\\cite{jimenez1998supervised}.  For  instance,\nin land-cover  classification, given  a set  of spatial,  temporal and\nspectral features, it is possible to  extract those which are the most\ndiscriminant      for      the     purpose      of      classification\n\\cite{fassnacht2014comparison}.   In  hyperspectral   data,  from  the\nhundreds of available spectral channels,  it is possible to reduce the\nnumber of channels  to make the processing more efficient  in terms of\nstatistical complexity  and computational load. In  short, by reducing\nthe dimension, better classification results are expected with a reduced\ncomputational load.\n\nThere  are  two  main  strategies  to  reduce  dimension~\\cite[Chapter\n1]{Guyon:2006:FEF:1208773}: feature extraction and feature selection.\nFeature extraction means reformulate  and summarize the information by\ncreating new features in combining  the existing ones, it is sometimes\nreferred to as \\emph{feature construction}.  Linear combination of the\ninitial features  can be extracted using  Principal Component Analysis\n(PCA)~\\cite{jimenez1998supervised}  or Independent  Component Analysis\n\\cite{villa2011hyperspectral}.  Supervised extraction  method has also\nbeen investigated  such as Fischer discriminant  analysis and decision\nboundary feature  extraction~\\cite{book:landgrebe}.  To  the contrary,\nfeature selection  extracts a subset of  existing features identified\nas  the most  relevant  by a  given criterion.   This  subset has  the\nadditional advantage to  be much more understandable  for the end-user\nthan those constructed by a (non-)linear combination.\n\nFeature selection/extraction algorithms can be divided into three classes. The first class is called \\emph{filter methods}. They select features independently of the classifier. Features are ranked according to some statistical measures, \\emph{e.g.}, correlation or independence. For example,  PCA is a typical unsupervised filter method. Bruzzone \\emph{et al.}\\cite{bruzzone1995extension} develop a supervised filter method based on Jeffries-Matusita distance to maximize the separability of class distribution. Correlation between bands has been explored for feature selection in hyperspectral data~\\cite{demir2008phase}. In general, these methods are fast and do not depend on any classifier. But they do not take into account the properties of the chosen classifier and do not optimize directly the classification accuracy.\n\nThe second class are known as \\emph{wrapper methods}. They search for the best subset of variables for a given learning model. Since exhaustive searches are too expensive in terms of processing time, several sub-optimal search strategies have been designed, mainly iterative forward or backward search~\\cite{whitney1971direct,marill1963effectiveness} or a combination of both~\\cite{somol1999adaptive}. The advantage of such methods compared to filter methods is that they are dedicated to a particular model and to a particular learning problem. On the other hand, as they require the training of multiple models to test various set of variables, they are more time consuming.\n\n\nThe third class corresponds to the \\emph{embedded methods}. They do not separate the feature selection process from the learning algorithm and allow interactions between the two processes. A popular embedded method is the \\emph{Random Forest}. Embedded methods also exist for other models, \\emph{e.g.} SVM \\cite{guyon2002gene,weston2003use,tuia2015multiclass}.\n\nDespite a large diversity of methods, feature selection algorithms usually do not scale well with the number of pixels to be processed~\\cite{fauvel2015fast}. The training computational load is too important to compensate the reduced prediction computational load. Hence, feature selection is not widely used in operational situations. However, methods based on Gaussian Mixture Models (GMM) have several interesting properties that make them suitable for feature selection in the context of large amount of data. By taking advantage of their intrinsic properties, it is possible to increase the computational efficiency with respect to standard implementation.\n\n\\rev{The contribution of this paper is a extension of the forward feature selection method proposed in~\\cite{fauvel2015fast}. A smart implementation of the feature selection update rules are presented in order to perform efficiently on large amount of data. The rules use on linear algebra on block matrices applied to the covariance matrix of the conditional class density function.  Furthermore, a floating version of the algorithm is proposed and evaluated. Several \\emph{correctness of fit} criteria are proposed to handle unbalanced training sets, extending the conventional \\emph{overall accuracy} measure.  Finally, the developed algorithm is made available to the scientific community as a remote module of the Orfeo Toolbox~\\cite{christophe2008orfeo}.}\n\nThe     remaining    of     the     article     is    organized     as\nfollows.   Section~\\ref{sec:gmm-hd}  presents   GMM  classifiers   and\nproblems  related to  high-dimensional  feature  spaces. The  feature\nselection methods are detailed in Section~\\ref{sec:selection}. Then, an\nefficient         implementation        is         presented        in\nSection~\\ref{sec:implementation}.  Experimental  results on  two  real\nhigh dimensional datasets are given Section~\\ref{sec:test}. Conclusion\nand perspectives conclude the paper in Section~\\ref{sec:conclusion}.\n\n\\section{Gaussian Mixture Models in high dimensional spaces}\n\\label{sec:gmm-hd}\n\nThe    following    notations    are   used    in    the    remaining.\n$\\mathcal{S}  = \\{\\mathbf{x}_i,y_i\\}_{i=1}^{n}$  denotes the  training\nset where $\\mathbf{x}_i \\in \\mathbb{R}^d$ is the vector of features of\nthe  $i^{th}$ sample,  $d$  the number  of spectral/temporal  features,\n$y_i = 1,...,C$ the associated label, $C$ the total number of classes,\n$n$ the  number of samples  and $n_c$ the  number of samples  of class\n$c$.\n\n    \\subsection{Gaussian Mixture Models}\n\n    For mixture models, it is assumed  that a given sample $\\mathbf{x}$ is\n    the realization  of a  random vector which  distribution is  a mixture\n    (convex     combination)     of      several     class     conditioned\n    distributions~\\cite{Fraley00model-basedclustering}:\n    \\begin{align}\n        p(\\mathbf{x}) = \\sum_{c=1}^{C} \\pi_c f_c(\\mathbf{x}|\\theta),\n    \\end{align}\n    where $\\pi_c$ is  the prior, \\emph{i.e.}, the  proportion of class\n    $c$  and  $f_c$  a  parametric density  function  controlled by\n    $\\theta$.\n\n    Among the possible parametric models,  the Gaussian one is the most\n    used~\\cite{bouveyron2014model}.   It assumes  that each  $f_c$ is,\n    conditionally  to  $c$,  a  Gaussian  distribution  of  parameters\n    $\\boldsymbol{\\mu}_c$    and    $\\boldsymbol{\\Sigma}_c$:\n    \\begin{multline}\n        f_c(\\mathbf{x}|\\boldsymbol{\\mu}_c, \\boldsymbol{\\Sigma}_c) = \\\\ \\frac{1}{(2\\pi)^{\\frac{d}{2}} |\\boldsymbol{\\Sigma}_c|^{\\frac{1}{2}}} \\exp \\left( -\\frac{1}{2} (\\mathbf{x} - \\boldsymbol{\\mu}_c)^t \\boldsymbol{\\Sigma}_c^{-1} (\\mathbf{x} - \\boldsymbol{\\mu}_c) \\right).\n    \\end{multline}\n\n    It  is  referred  to  as  Gaussian  mixture  model  (GMM).   In  a\n    supervised    learning    framework,    the    class    parameters\n    $\\boldsymbol{\\mu}_c$,   $\\boldsymbol{\\Sigma}_c$   and  the   prior\n    $\\pi_c$ are  usually estimated  through the  conventional unbiased\n    empirical estimators:\n    \\begin{align}\n        \\hat{\\pi}_c &= \\frac{n_c}{n},\\\\\n        \\hat{\\boldsymbol{\\mu}}_c &= \\frac{1}{n_c} \\sum_{\\{i|y_i = c\\}} \\mathbf{x}_i ,\\\\\n        \\hat{\\boldsymbol{\\Sigma}}_c &= \\frac{1}{(n_c - 1)} \\sum_{\\{i|y_i = c\\}} (\\mathbf{x}_i - \\boldsymbol{\\mu}_c) (\\mathbf{x}_i - \\boldsymbol{\\mu}_c)^t.\n    \\end{align}\n    To predict the  class of a new unseen sample,  the maximum \\emph{a\n      posteriori}  rule  is  used:\n    \\begin{equation*}\n        \\mathbf{x} \\text{ belongs to } c \\Leftrightarrow c = \\text{arg} \\max_{c \\in C} p(c) p(\\mathbf{x}|c).\n    \\end{equation*}\n    Under the GMM,  and identifying $p(c)$ as $\\pi_c$  and $p(\\mathbf{x}|c)$ as\n    $f_c(\\mathbf{x}|\\theta)$ and by taking the log, the decision function is obtained\n    \\begin{eqnarray}\\label{eq:decision}\n      Q_c(\\mathbf{x}) &=& 2 \\log \\left( p(c) p(\\mathbf{x}|c) \\right) \\nonumber \\\\\n                      &=& - (\\mathbf{x} - \\boldsymbol{\\mu}_c)^t \\boldsymbol{\\Sigma}_c^{-1} (\\mathbf{x} - \\boldsymbol{\\mu}_c) \\nonumber \\\\\n                      & &-\\log (|\\boldsymbol{\\Sigma}_c|) + 2 \\log (\\pi_c) - d \\log (2\\pi).\n    \\end{eqnarray}\n\n    \\subsection{Curse of dimensionality in GMM}\n    \\label{sec:curse:gmm}\n\n    The computation of  eq.~(\\ref{eq:decision}) requires the inversion\n    of the covariance  matrix and the computation of  the logarithm of\n    the determinant.  The  estimation of these terms  suffers from the\n    curse of dimensionality\\cite{bouveyron2014model}. In practice, the\n    number of parameters $\\eta_c$ to estimate for each class increases\n    quadratically  with   respect  to  the  number   of  features,  as\n    illustrated in Figure~\\ref{fig:nb-param}.  Hence, if the number of\n    observation $n_c$  is small compared  to the number  of parameters\n    $\\eta_c$, the estimated covariance matrix is badly conditioned and\n    thus the computation  of its inverse and its  determinant would be\n    unstable.  The  worst situation is  $n_c<\\eta_c$ which leads  to a\n    singular covariance matrix.  Unfortunately, this situation happens\n    regularly in remote sensing.   For instance in hyperspectral image\n    classification,  very few  labeled samples  are usually  available\n    because of the difficulty and the cost to collect ground-truth.\n\n    \\begin{figure}[!t]\n        \\centering\n        \\begin{tikzpicture}\n          \\begin{axis}[ymode=log,xmin=0,xmax=200,width=0.8\\columnwidth,grid,axis x line=left ,axis y line=left, tick align=outside,xlabel = $d$,ylabel = $\\eta_c$,small]\n            \\addplot+[very thick,mark=none,smooth,domain=0:200,samples=200] (\\x,{\\x*(\\x+3)/2+1});\n            \\end{axis}\n        \\end{tikzpicture}\n        \\caption{Number of parameters $\\eta_c$ per class in function of dimension $d$: $\\eta_c=d(d+3)/2+1$.\\label{fig:nb-param}}\n    \\end{figure}\n\n    There are two major solutions to this problem. The first option is to stabilize the inversion of the covariance matrices. Some methods investigate the use of constraints on the direct problem. Reynolds \\emph{et al.} \\cite{reynolds1995robust} proposed to use diagonal covariance matrices. It is also possible to force the diagonal element to be higher than a given value by maximizing the GMM likelihood \\cite{hathaway1985constrained}. Celeux and Govaert \\cite{celeux1995gaussian} suggest to use equality constraints between coefficients of the covariance matrix in a parsimonious cluster-based GMM framework. Other papers propose to work on the inverse problem. A classical method is to use a regularization method as the well-known ridge regularization \\cite{hoerl1970ridge}. A ridge regularization aims to stabilize the inversion by replacing the covariance matrix $\\boldsymbol{\\Sigma}_c$ by $\\boldsymbol{\\Sigma}_c + \\tau \\mathbf{I}$ where $\\tau$ is a positive parameter and $\\mathbf{I}$ the identity matrix. Jensen \\emph{et al.} \\cite{jensen2008regression} propose a different approach using a sparsity approximation to inverse the covariance matrix.\n\n    The second option is to reduce the dimension. Feature extraction/selection methods have been developed in order to reduce the dimension with various approaches described in Section~\\ref{sec:intro}. In this study, this latter option is explored and a feature selection method named sequential forward features selection is presented.\n\n\\section{Sequential forward features selection}\n\\label{sec:selection}\n\nThe feature selection method proposed in this work is a wrapper method associated to GMM models. Two elements are needed to set up a wrapper method:\n\\begin{enumerate}\n\\item A function that ranks the features according to some good classification or class separability criterion,\n\\item A search strategy to optimize the function.\n\\end{enumerate}\n\nSection~\\ref{sec:criterion} describes the various criteria used in this work and two search strategies are discussed in~\\ref{sec:selection:method}.\n\n\n    \\subsection{Criterion function}\n    \\label{sec:criterion}\n    The criterion evaluates how a given model built with a subset of features performs for the classification task. It can be an estimation of the correct classification or a measure of separability/similarity between class distributions. The former are in general more demanding in terms of processing time than the later.\n\n        \\subsubsection{Measures of correct classification}\n        \\label{sec:criterion-rate}\n\n        A measure of correct classification is based on an error matrix $M$, or \\emph{confusion matrix}~\\cite[Chapter 4]{congalton2008assessing}. The confusion matrix allows the computation of several global and per-class indices related to the classification accuracy~\\cite{congalton2008assessing}. Three global criteria were used in this work:\n\n        \\begin{itemize}\n        \\item  \\emph{The overall  accuracy} (OA)  is the  rate of  the\n          number of samples with the  correct predicted label over the\n          total  number of  samples~\\cite{congalton2008assessing}. This\n          metric is  easy to interpret  but is  biased in the  case of\n          unbalanced classes.\n\n        \\item \\emph{The Cohen's kappa} (K) is a statistic which measures the probability of agreement between predictions and ground-truth~\\cite{congalton2008assessing}.\n\n        \\item \\emph{The mean F1 score}  (F1mean) is the average of the\n          F1 score  for each class  and the  F1 score is  the harmonic\n          mean of  the precision  (number of  True Positive  over True\n          Positive plus False Positive) and the recall (number of True\n          Positive over True Positive plus False Negative)~\\cite{powers2011evaluation}.\n        \\end{itemize}\n        High  values  of  theses  indices  correspond  to  an  accurate\n        classification.\n\n        These  indices  are  estimated  from the  training  set  by  a\n        $n_{cv}$- cross-validation ($n_{cv}$-CV)~\\cite{opac-b1127878}.\n        To  compute   the  $n_{cv}$-CV,  a  subset   is  removed  from\n        $\\mathcal{S}$  and  the  GMM  is learned  with  the  remaining\n        training samples.  A test error  is computed with  the removed\n        training samples  used as validation samples.   The process is\n        iterated $n_{cv}$ times and  the estimated classification rate\n        is computed as  the mean test error over  the $n_{cv}$ subsets\n        of $\\mathcal{S}$.\n\n        \\subsubsection{Similarity between distributions}\n        The similarity  between two distributions can be  quantified using\n        divergence  measures~\\cite{opac-b1097517}. Contrary  to measures\n        of correct  classification, divergences are  computed directly\n        on  the  trained  model,  with  no  need  of  cross-validation\n        estimation.  Two particular divergences are used in this work:\n        the     \\emph{Kullback-Leibler}     divergence     and     the\n        \\emph{Jeffries-Matusita}  distance.   The advantage  of  these\n        divergences is  that they have  an explicit expression  in the\n        case of Gaussian models. The  simplification allows to get rid\n        of  any integration  calculations which  is a  major problem  when\n        dealing with high-dimensional data.\n\n        \\emph{The   Kullback-Leibler   divergence}   (KL   divergence)\n        measures  the  amount  of  information  lost  when  the  first\n        distribution     is     approximated     by     the     second\n        one\\cite{kullback1987letter}. It can be explicitly computed in\n        the case of Gaussian distributions:\n        \\begin{align}\n            &KL_{cc^\\prime} = \\frac{1}{2} \\biggl\\{ \\text{Tr} (\\boldsymbol{\\Sigma}_c^{-1} \\boldsymbol{\\Sigma}_{c^\\prime}) \\nonumber \\\\\n            & + (\\boldsymbol{\\mu}_c - \\boldsymbol{\\mu}_{c^\\prime})^t \\boldsymbol{\\Sigma}_c^{-1} (\\boldsymbol{\\mu}_c - \\boldsymbol{\\mu}_{c^\\prime}) - d + \\log \\left( \\frac{|\\boldsymbol{\\Sigma}_c|}{|\\boldsymbol{\\Sigma}_{c^\\prime}|} \\right) \\biggr\\},\n        \\end{align}\n        where Tr is the trace operator and $d$ the dimension of the distribution.\n\n        The    KL   divergence    is   not    symmetric,   \\emph{i.e.},\n        $KL_{cc^\\prime} \\ne KL_{c^\\prime c}$.  A symmetrical version  is used to\n        compute the criterion function:\n        \\begin{align}\\label{eq:skl}\n          SKL_{cc^\\prime} &=KL_{cc^\\prime} + KL_{c^\\prime c} \\nonumber \\\\\n            &= \\frac{1}{2} \\biggl\\{ \\text{Tr} (\\boldsymbol{\\Sigma}_c^{-1} \\boldsymbol{\\Sigma}_{c^\\prime} + \\boldsymbol{\\Sigma}_{c^\\prime}^{-1} \\boldsymbol{\\Sigma}_c) \\nonumber \\\\\n            &~~+ (\\boldsymbol{\\mu}_c - \\boldsymbol{\\mu}_{c^\\prime})^t (\\boldsymbol{\\Sigma}_c^{-1} + \\boldsymbol{\\Sigma}_{c^\\prime}^{-1}) (\\boldsymbol{\\mu}_c - \\boldsymbol{\\mu}_{c^\\prime}) - 2d \\biggr\\}.\n        \\end{align}\n\n        The extension  to the multiclass  problem is done  by taking\n        the weighted mean  of the KL divergences computed  on all pair\n        of classes~\\cite{bruzzone1995extension}:\n        \\begin{equation}\n            C_{SKL} = \\sum_{c=1}^{C} \\sum_{c^\\prime = c + 1}^{C} \\pi_c \\pi_{c^\\prime} SKL_{cc^\\prime}.\n        \\end{equation}\n\n        \\emph{The Bhattacharyya distance} is defined in the case of Gaussian model as\n        \\begin{align}\n            {B}_{cc^\\prime} = &\\frac{1}{8} (\\boldsymbol{\\mu}_c - \\boldsymbol{\\mu}_{c^\\prime})^t \\left( \\frac{\\boldsymbol{\\Sigma}_c + \\boldsymbol{\\Sigma}_{c^\\prime}}{2} \\right)^{-1} (\\boldsymbol{\\mu}_c - \\boldsymbol{\\mu}_{c^\\prime}) \\nonumber \\\\\n            &+ \\frac{1}{2} \\log \\left( \\frac{|\\boldsymbol{\\Sigma}_c + \\boldsymbol{\\Sigma}_{c^\\prime}|}{\\sqrt{|\\boldsymbol{\\Sigma}_c| |\\boldsymbol{\\Sigma}_{c^\\prime}|}} \\right).\n        \\end{align}\n\n        The \\emph{Jeffries-Matusita distance} is a measure based on the Bhattacharyya distance. It saturates when the separability between the two distributions increases~\\cite{bruzzone2009novel}. The JM distance is defined as\n        \\begin{equation}\\label{eq:jm}\n            {JM}_{cc^\\prime} = \\sqrt{ 2 \\{1 - \\text{exp}(-B_{cc^\\prime})\\} }.\n        \\end{equation}\n\n        Similar to the KL divergence,  a weighted mean of the distance\n        between two classes is computed to aggregate the measures in a\n        single value:\n        \\begin{equation}\n            {C}_{JM} = \\sum_{c=1}^{C} \\sum_{c^{\\prime} = c + 1}^{C} \\pi_c \\pi_{c^\\prime} {JM}_{cc^\\prime}.\n        \\end{equation}\n\n        Table~\\ref{tab:crit} summarizes the presented criterion functions and their characteristics. In the following $J$ denotes one criterion from Table~\\ref{tab:crit}.\n\n        \\begin{table}[!t]\n            \\centering\n            \\caption{Summary of the different criterion functions.\\label{tab:crit}}\n            \\begin{tabular}[b]{lcc}\n              \\toprule\n              Criterion & Type & Complexity \\\\\n              \\midrule\n              Overall accuracy            & Accuracy   & High \\\\\n              Cohen's kappa               & Accuracy   & High\\\\\n              F1 mean                     & Accuracy   & High\\\\\n              \\midrule\n              Kullback-Leibler divergences & Divergence & Low \\\\\n              Jeffries-Matusita distance  & Divergence & Low \\\\\n              \\bottomrule\n            \\end{tabular}\n        \\end{table}\n\n        \\subsection{Selection method}\n        \\label{sec:selection:method}\n        Two  sequential  search  algorithms have been  implemented  in  this\n        work~\\cite{Guyon:2006:FEF:1208773}:  the   sequential  forward\n        selection and the sequential  floating forward.  The later one\n        is  an   extension  of   the  former.  Both   select  features\n        iteratively.\n\n        \\subsubsection{Sequential forward features selection}\n        \\label{sec:forward-presentation}\n\n        The Sequential Forward Selection (SFS) starts with an empty set of selected features.  At each  step, the feature associated to the highest criterion function $J$  is added  to the set. This feature is definitively added to the pool of selected features and the algorithm stops when a given number of variables \\emph{maxVarNb} has been reached. The Algorithm~\\ref{alg:sfs} presents the process in details.\n\n        \\begin{algorithm}\n        \\caption{Sequential forward features selection\\label{alg:sfs}}\n        {\\footnotesize\n        \\begin{algorithmic}[1]\n        \\REQUIRE $\\Omega,J,\\text{maxVarNb}$\n        \\STATE $\\Omega=\\emptyset$\n        \\STATE $F=\\text{\\{all variables $f_i$\\}}$\n        \\WHILE{$\\text{card}(\\Omega) < maxVarNb$}\n        \\FORALL{$f_i \\in F$}\n        \\STATE $R_i = J(\\{\\Omega + f_i\\})$\n        \\ENDFOR\n        \\STATE $j=\\text{arg} \\max_{i} R_i$\n        \\STATE $\\Omega = \\{\\Omega + f_j\\}$\n        \\STATE $F = F \\setminus f_j$\n        \\ENDWHILE\n        \\RETURN $\\Omega$\n        \\end{algorithmic}\n        }\n        \\end{algorithm}\n\n        \\subsubsection{Sequential floating forward feature selection}\n        \\label{sec:floating-presentation}\n\n        The Sequential Floating Forward Selection (SFFS)\\cite{somol1999adaptive} is based on two algorithms: the SFS described above and the Sequential Backward Selection (SBS). The SBS is the backward equivalent of SFS. The difference is that it starts with every features in the pool of selected features and tries at each step to remove the less significant one in term of the given criterion function.\n\n        The SFFS works as the SFS but between each step of the SFS algorithm, a backward selection is operated to identify the less important feature. If the criterion value is higher than the best value ever obtained with a set of same size, the identified feature is picked out. The SBS step is repeated while removing the less important feature leads to an increase of the criterion value. Then SFS is called again. The algorithm stops when a given number of features \\emph{maxVarNb} has been selected. The Algorithm~\\ref{alg:sffs} provides details about the process.\n\n        This SFFS algorithm evaluates more solutions than the SFS algorithm. The results are expected to be better but the trade-off is an increased computational time which is dependent on the complexity of the dataset.\n\n        \\begin{algorithm}\n        \\caption{Sequential floating forward features selection\\label{alg:sffs}}\n        {\\footnotesize\n        \\begin{algorithmic}[1]\n        \\REQUIRE $J,\\text{maxVarNb}$\n        \\STATE $\\Omega=\\overbrace{(\\emptyset,...,\\emptyset)}^{maxVarNb}$\n        \\STATE $F=\\text{\\{all variables $f_i$\\}}$\n        \\STATE $k=0$\n        \\WHILE{$k < \\text{maxVarNb}$}\n        \\FORALL{$f_i \\in F$}\n        \\STATE $R_i = J(\\{\\Omega_k + f_i\\})$\n        \\ENDFOR\n        \\STATE $j=\\text{arg} \\max_{i} R_i$\n        \\STATE $k=k+1$\n        \\IF{$R_j \\geq J(\\Omega_k)$}\n        \\STATE $\\Omega_k = \\{\\Omega_{k-1} + f_j\\}$\n        \\STATE $\\text{flag}=1$\n        \\WHILE{$k > 2 \\text{ and } \\text{flag}=1$}\n        \\FORALL{$f_i \\in \\Omega_k$}\n        \\STATE $R_i = J(\\{\\Omega_k \\setminus f_i\\})$\n        \\ENDFOR\n        \\STATE $j=\\text{arg} \\max_{i} R_i$\n        \\IF{$R_j > J(\\Omega_{k-1})$}\n        \\STATE $\\Omega_{k-1} = \\{\\Omega_k \\setminus f_j\\}$\n        \\STATE $k=k-1$\n        \\ELSE\n        \\STATE $\\text{flag}=0$\n        \\ENDIF\n        \\ENDWHILE\n        \\ENDIF\n        \\ENDWHILE\n        \\RETURN $\\Omega_{\\text{maxVarNb}}$\n        \\end{algorithmic}\n        }\n        \\end{algorithm}\n\n\n\\section{Efficient implementation}\n\\label{sec:implementation}\nThe most  demanding part  of the  algorithm is  the evaluation  of the\ncriterion  for  all   the  remaining  variables  (see   lines  5-7  in\nAlgorithm~\\ref{alg:sfs}). Calculations are based on linear algebra, and the\nnumerical  complexity is  on average  $O(d^3)$.  Furthermore,  for the\n\\emph{accuracy}-type  criterion the  complexity  is  augmented by  the\ncross-validation procedure.\n\nAn efficient implementation of  the criterion optimization is detailed\nin  the following.   It  is  based on  the  symmetry  property of  the\ncovariance matrix  and block inverse  formula~\\cite{IMM2012-03274}.  It is shown  that the criterion  can be split  into two\nparts: one that needs to be computed for each tested variable, and one\nthat  needs to  be  computed only  once per  selection  step. For  the\ncross-validation part,  updates rules  are given to  derive sub-models\nwithout the necessity to learn a GMM models for each fold.\n\n\\subsection{Statistical update rules}\n        \\subsubsection{Update for cross validation}\n        \\label{sec:update-cv}\n        Based on \\cite{fauvel2015fast}, a method to accelerate the $n_{cv}$-fold cross-validation process in the case of criterion functions based on correct classification measures was implemented. The idea is to estimate the GMM with the whole training set once and then, instead of training models on $(n_{cv}-1)$ folds, parameters of the complete model are used to derive those of sub-models, thus reducing the whole complexity.\n\n        \\begin{prop}[Mean update for cross-validation]\n            \\label{eq:update-cv1}\n            \\begin{equation*}\n                \\boldsymbol{\\hat{\\mu}}_c^{n_c-\\nu_c} = \\frac{n_c \\boldsymbol{\\hat{\\mu}}_c^{n_c} - \\nu_c \\boldsymbol{\\hat{\\mu}}_c^{\\nu_c}}{n_c - \\nu_c} \\nonumber\n            \\end{equation*}\n        \\end{prop}\n        \\begin{prop}[Covariance matrix update cross-validation]\n            \\label{eq:update-cv2}\n            \\begin{align*}\n              \\boldsymbol{\\hat{\\Sigma}}_c^{n_c-\\nu_c} = &\\frac{1}{n_c-\\nu_c-1} \\biggl\\{ (n_c-1) \\boldsymbol{\\hat{\\Sigma}}_c^{n_c} - (\\nu_c-1)\\boldsymbol{\\hat{\\Sigma}}_c^{\\nu_c} \\nonumber \\\\\n                                                        &- \\frac{n_c \\nu_c}{(n_c-\\nu_c)} (\\boldsymbol{\\hat{\\mu}}_c^{\\nu_c}-\\boldsymbol{\\hat{\\mu}}_c^{n_c})(\\boldsymbol{\\hat{\\mu}}_c^{\\nu_c}-\\boldsymbol{\\hat{\\mu}}_c^{n_c})^t \\biggr\\} \\nonumber\n            \\end{align*}\n        \\end{prop}\n        \\noindent where $n_c$ is the number of samples of class $c$, $\\nu_c$ is the number of samples of class $c$ removed from the initial set, exponents on $\\boldsymbol{\\Sigma}_c$ and $\\boldsymbol{\\mu}_c$ denotes the set of samples used to compute them.\n\n        \\subsubsection{Criterion function computation}\n        \\label{sec:update-crit}\n        At iteration $k$, depending on the criterion, three terms have\n        to  be computed:  the inverse  of the  covariance matrix,  the\n        logarithm of the determinant of  the covariance matrix and the\n        quadratic term in  eq.~(\\ref{eq:decision}). However, all these\n        terms  have already  been computed  for iteration  $(k-1)$. By\n        using the  positive definiteness of the  the covariance matrix\n        and block formulae~\\cite[Chapter 9.2]{webb2003statistical}, it\n        is possible to factorize these terms at iteration $k$.\n\n        In the remaining of the paper, $\\boldsymbol{\\Sigma}_c^{(k-1)}$\n        denotes the  covariance matrix of the  $(k-1)^{th}$ iteration,\n        \\emph{i.e.}, the  covariance matrix  of the  selected features\n        and $\\boldsymbol{\\Sigma}_c^{(k)}$ denotes  a covariance matrix\n        at the $k^{th}$ iteration,  \\emph{i.e.}, the covariance matrix\n        augmented  by  the  feature  $x_k$.  Then,  since\n        $\\boldsymbol{\\Sigma}_c^{(k)}$ is a positive definite symmetric\n        matrix, the covariance matrix can be written as\n\n        \\begin{equation}\\label{eq:cov}\n            \\boldsymbol{\\Sigma}_c^{(k)} =\n            \\bigg[\\begin{array}{cc}\n            \\boldsymbol{\\Sigma}^{(k-1)}_c & \\mathbf{u}_c      \\\\\n            \\mathbf{u}_c^t          & \\sigma^{(k)}_c \\\\\n            \\end{array}\\bigg],\n        \\end{equation}\n        where  $\\sigma^{(k)}_c$  is  the variance  of  $x_c$,\n        $\\mathbf{u}_c$ is  the $k^{th}$  column of the  matrix without\n        the          diagonal           element,          \\emph{i.e.},\n        $\\mathbf{u}_{c}(i) =  \\boldsymbol{\\Sigma}^{(k)}_{c}(i,k)$ with\n        $i  \\in [1,k-1]$.   Using block  matrix inverse  formulae, the\n        inverse of  the covariance  matrix is  given by  the following\n        proposition.\n        \\begin{prop}[Forward update rule for the inverse of the covariance matrix]\n        \\label{eq:update-inv}\n        \\begin{equation}\\label{eq:cov:inv}\n                (\\boldsymbol{\\Sigma}_c^{(k)})^{-1} =\n                \\bigg[\\begin{array}{cc}\n                \\mathbf{A}_c & \\mathbf{v}_c \\\\\n                \\mathbf{v}_c^t  & \\frac{1}{\\alpha_c} \\\\\n                \\end{array}\\bigg]\n            \\end{equation}\n        \\end{prop}\n        \\noindent                                                where\n        $\\mathbf{A}_c     =     (\\boldsymbol{\\Sigma}^{(k-1)}_c)^{-1}     +\n        \\frac{1}{\\alpha_c} (\\boldsymbol{\\Sigma}^{(k-1)}_c)^{-1} \\mathbf{u}_c\n        \\mathbf{u}_c^t              (\\boldsymbol{\\Sigma}^{(k-1)}_c)^{-1}$,\n        $\\mathbf{v}_c           =           -           \\frac{1}{\\alpha_c}\n        (\\boldsymbol{\\Sigma}^{(k-1)}_c)^{-1}       \\mathbf{u}_c$       and\n        $      \\alpha_c      =      \\sigma^{(k)}_c      -      \\mathbf{u}_c^t\n        (\\boldsymbol{\\Sigma}^{(k-1)}_c)^{-1}  \\mathbf{u}_c$.  This  update\n        formulae      is     used      to      obtain     all      the\n        $(\\boldsymbol{\\Sigma}^{(k)}_c)^{-1}$  corresponding  to all  the\n        possible augmented set of a given selection iteration. Similar\n        update formulae can be written for the backward step.\n\n        Using eq.~(\\ref{eq:cov}) and~(\\ref{eq:cov:inv}), it is possible to\n        deduce  the   following  propositions  (proof  are   given  in\n        Appendix~\\ref{app:proof-update}).\n        \\begin{prop}[Update rule for the quadratical term]\n        \\label{eq:update-quad}\n            \\begin{align}\n              (\\mathbf{x}^{(k)})^t (\\boldsymbol{\\Sigma}^{(k)}_c)^{-1} \\mathbf{x}^{(k)} = &\\underbrace{(\\mathbf{x}^{(k-1)})^t (\\boldsymbol{\\Sigma}^{(k-1)}_c)^{-1} \\mathbf{x}^{(k-1)}}_{\\substack{\\text{computed once per selection step}}} \\nonumber \\\\\n                                                                                       &+ \\underbrace{\\alpha_c ( \\left[\\begin{array}{cc} \\mathbf{v}_c^t & \\frac{1}{\\alpha_c} \\end{array}\\right] \\mathbf{x}^{(k)} )^2}_{\\substack{\\text{computed for each augmented set}}}.\n            \\end{align}\n        \\end{prop}\n        \\begin{prop}[Update rule for logdet]\n        \\label{eq:update-log}\n            \\begin{equation}\n                \\log \\left(|\\boldsymbol{\\Sigma}^{(k)}_c|\\right) = \\underbrace{\\log \\left(|\\boldsymbol{\\Sigma}^{(k-1)}_c|\\right)}_{\\substack{\\text{computed once}\\\\ \\text{per selection step}}} + \\underbrace{\\log \\alpha_c}_{\\substack{\\text{computed for} \\\\ \\text{each augmented set}}}.\n            \\end{equation}\n        \\end{prop}\n\n        From these update rules, it is now possible to split each criterion into two parts: one computed once per selection step and one computed for each augmented set.\n\n        \\begin{prop}[Decision function~(\\ref{eq:decision})]\n            \\begin{align}\n            \\label{eq:q-update}\n                Q_c(\\mathbf{x}) = &- \\underbrace{(\\mathbf{x}^{(k-1)} - \\boldsymbol{\\mu}_c^{(k-1)})^t (\\boldsymbol{\\Sigma}^{(k-1)}_c)^{-1} (\\mathbf{x}^{(k-1)} - \\boldsymbol{\\mu}^{(k-1)}_c)}_{\\substack{\\text{computed once per selection step}}} \\nonumber \\\\\n                &- \\underbrace{\\log \\left(|\\boldsymbol{\\Sigma}^{(k-1)}_c|\\right) + 2 \\log (\\pi_c) + k \\log(2 \\pi)}_{\\substack{\\text{computed once per selection step}}} \\nonumber \\\\\n                &- \\underbrace{\\alpha_c \\left( \\left[\\begin{array}{cc} \\mathbf{v}_c^t & \\frac{1}{\\alpha_c} \\end{array}\\right] (\\mathbf{x}^{(k)} - \\boldsymbol{\\mu}_c^{(k)}) \\right)^2 - \\log \\alpha_c}_{\\substack{\\text{computed for each augmented set}}}.\n            \\end{align}\n        \\end{prop}\n\n      \\begin{prop}[Kullback-Leibler divergence~(\\ref{eq:skl})]\n        \\begin{align}\n        \\label{eq:skl-update}\n            & SKL_{cc^\\prime} = \\frac{1}{2} \\biggl\\{ \\underbrace{\\text{\\normalfont Tr} \\left((\\boldsymbol{\\Sigma}_c^{(k)})^{-1} \\boldsymbol{\\Sigma}_{c^\\prime}^{(k)} + (\\boldsymbol{\\Sigma}_{c^\\prime}^{(k)})^{-1} \\boldsymbol{\\Sigma}_c^{(k)}\\right)}_{\\substack{\\text{computed for each augmented set}}} \\nonumber \\\\\n            &+ \\underbrace{\\alpha ( \\left[\\begin{array}{cc} \\mathbf{v}_c^t & \\frac{1}{\\alpha_c} \\end{array}\\right] (\\boldsymbol{\\mu}_c^{(k)} - \\boldsymbol{\\mu}_{c^\\prime}^{(k)}) )^2}_{\\substack{\\text{computed for each augmented set}}} \\nonumber \\\\\n            &+ \\underbrace{\\alpha ( \\left[\\begin{array}{cc} \\mathbf{v}_{c^\\prime}^t & \\frac{1}{\\alpha_{c^\\prime}} \\end{array}\\right] (\\boldsymbol{\\mu}_c^{(k)} - \\boldsymbol{\\mu}_{c^\\prime}^{(k)}) )^2 - 2k}_{\\substack{\\text{computed for each augmented set}}} \\nonumber \\\\\n            &+ \\underbrace{(\\boldsymbol{\\mu}_c^{(k-1)} - \\boldsymbol{\\mu}_{c^\\prime}^{(k-1)})^t (\\boldsymbol{\\Sigma}_c^{(k-1)})^{-1}(\\boldsymbol{\\mu}_c^{(k-1)} - \\boldsymbol{\\mu}_{c^\\prime}^{(k-1)})}_{\\substack{\\text{computed once per selection step}}} \\nonumber\\\\\n          & + \\underbrace{(\\boldsymbol{\\mu}_c^{(k-1)} - \\boldsymbol{\\mu}_{c^\\prime}^{(k-1)})^t(\\boldsymbol{\\Sigma}_{c^\\prime}^{(k-1)})^{-1} (\\boldsymbol{\\mu}_c^{(k-1)} - \\boldsymbol{\\mu}_{c^\\prime}^{(k-1)})}_{\\substack{\\text{computed once per selection step}}} \\biggr\\},\n        \\end{align}\n      \\end{prop}\n      \\noindent with $(\\boldsymbol{\\Sigma}_c^{(k)})^{-1}$ computed with Proposition~\\ref{eq:update-inv}.\n\n      \\begin{prop}[Jeffries-Matusita distance~(\\ref{eq:jm})]\n      \\begin{align}\n        \\label{eq:jm-update}\n            &\\text{B}_{cc^\\prime} = \\underbrace{\\frac{1}{4} (\\boldsymbol{\\mu}_c^{(k-1)} - \\boldsymbol{\\mu}_{c^\\prime}^{(k-1)})^t ( \\boldsymbol{\\tilde{\\Sigma}}^{(k-1)} )^{-1} (\\boldsymbol{\\mu}_c^{(k-1)} - \\boldsymbol{\\mu}_{c^\\prime}^{(k-1)})}_{\\substack{\\text{computed once per selection step}}} \\nonumber \\\\\n            &+ \\underbrace{\\frac{1}{2} \\log \\left( \\frac{|\\boldsymbol{\\tilde{\\Sigma}}^{(k-1)}|}{\\sqrt{|\\boldsymbol{\\Sigma}_c^{(k-1)}| |\\boldsymbol{\\Sigma}_{c^\\prime}^{(k-1)}|}} \\right)}_{\\substack{\\text{computed once per selection step}}} \\nonumber \\\\\n            &+ \\underbrace{\\frac{1}{4} \\tilde{\\alpha} ( \\left[\\begin{array}{cc} \\mathbf{\\tilde{v}}^t & \\frac{1}{\\tilde{\\alpha}} \\end{array}\\right] (\\boldsymbol{\\mu}_c^{(k)} - \\boldsymbol{\\mu}_{c^\\prime}^{(k)}) )^2 + \\frac{1}{2} \\log \\left( \\frac{\\tilde{\\alpha}}{\\sqrt{\\alpha_c \\alpha_{c^\\prime}}} \\right)}_{\\substack{\\text{computed for each augmented set}}},\n      \\end{align}\n    \\end{prop}\n    \\noindent where $\\boldsymbol{\\tilde{\\Sigma}} = \\boldsymbol{\\Sigma}_c + \\boldsymbol{\\Sigma}_{c^\\prime}$ and $\\tilde{\\alpha}$ and $\\mathbf{\\tilde{v}}$ are defined as $\\alpha_c$ and $\\mathbf{v}_c$ but using $\\boldsymbol{\\tilde{\\Sigma}}$ instead of $\\boldsymbol{\\Sigma}_c$.\n    \n    The  Algorithm~\\ref{alg:sffs-update} illustrates  the optimization\n    of the Algorithm~\\ref{alg:sffs} using these formulae.\n\n    \\subsection{Numerical issues}\n\n        \\begin{algorithm}\n    \\caption{Sequential floating forward features selection with updates\\label{alg:sffs-update}}\n    {\\footnotesize\n    \\begin{algorithmic}[1]\n    \\REQUIRE $J,\\text{maxVarNb}$\n    \\STATE $\\Omega=\\overbrace{(\\emptyset,...,\\emptyset)}^{maxVarNb}$\n    \\STATE $F=\\text{\\{all variables $f_i$\\}}$\n    \\STATE $k=0$\n    \\WHILE{$k < \\text{maxVarNb}$}\n    \\FORALL{$c \\in \\{1,...,C\\}$}\n    \\STATE Diagonalize $\\boldsymbol{\\Sigma}^{(k-1)}_c = \\mathbf{P}_c \\boldsymbol{\\Lambda}_c \\mathbf{P}_c^t$\n    \\STATE {\\bfseries for all} $\\lambda_{c}(i)$ {\\bfseries do} $\\lambda_{c}(i) = \\max (\\text{EPS\\_FLT},\\lambda_{c}(i))$\n    \\STATE Precompute {\\scriptsize $(\\boldsymbol{\\Sigma}^{(k-1)}_c)^{-1}$, $(\\mathbf{x}^{(k-1)} - \\boldsymbol{\\mu}^{(k-1)}_c)^t (\\boldsymbol{\\Sigma}^{(k-1)}_c)^{-1} (\\mathbf{x}^{(k-1)}- \\boldsymbol{\\mu}^{(k-1)}_c)$ and $\\log \\left(|\\boldsymbol{\\Sigma}^{(k-1)}_c|\\right)$} using Propositions (\\ref{eq:update-inv}), (\\ref{eq:update-quad}) and (\\ref{eq:update-log})\n    \\ENDFOR\n    \\FORALL{$f_i \\in F$}\n    \\FORALL{$c \\in \\{1,...,C\\}$}\n    \\STATE Compute update constant $\\alpha_c$\n    \\STATE $\\alpha_c = \\max (\\text{EPS\\_FLT},\\alpha_c)$\n    \\ENDFOR\n    \\STATE $R_i = J(\\{\\Omega_k + f_i\\})$ using Equations (\\ref{eq:q-update}), (\\ref{eq:skl-update}) or (\\ref{eq:jm-update})\n    \\ENDFOR\n    \\STATE $j=\\text{arg} \\max_{i} R_i$\n    \\STATE $k=k+1$\n    \\IF{$R_j \\geq J(\\Omega_k)$}\n    \\STATE $\\Omega_k = \\{\\Omega_{k-1} + f_j\\}$\n    \\STATE $\\text{flag}=1$\n    \\WHILE{$k > 2 \\text{ and } \\text{flag}=1$}\n    \\FORALL{$c \\in \\{1,...,C\\}$}\n    \\STATE Diagonalize $\\boldsymbol{\\Sigma}^{(k-1)}_c = \\mathbf{P}_c \\boldsymbol{\\Lambda}_c \\mathbf{P}_c^t$\n    \\STATE {\\bfseries for all} $\\lambda_{c}(i)$ {\\bfseries do} $\\lambda_{c}(i) = \\max (\\text{EPS\\_FLT},\\lambda_{c}(i))$\n    \\STATE Precompute {\\scriptsize $(\\boldsymbol{\\Sigma}^{(k-1)}_c)^{-1}$, $(\\mathbf{x}^{(k-1)} - \\boldsymbol{\\mu}^{(k-1)}_c)^t (\\boldsymbol{\\Sigma}^{(k-1)}_c)^{-1} (\\mathbf{x}^{(k-1)}- \\boldsymbol{\\mu}^{(k-1)}_c)$ and $\\log \\left(|\\boldsymbol{\\Sigma}^{(k-1)}_c|\\right)$} using Propositions (\\ref{eq:update-inv}), (\\ref{eq:update-quad}) and (\\ref{eq:update-log})\n    \\ENDFOR\n    \\FORALL{$f_i \\in \\Omega_k$}\n    \\FORALL{$c \\in \\{1,...,C\\}$}\n    \\STATE Compute update constant $\\alpha_c$\n    \\STATE $\\alpha_c = \\max (\\text{EPS\\_FLT},\\alpha_c)$\n    \\ENDFOR\n    \\STATE $R_i = J(\\{\\Omega_k \\setminus f_i\\})$ using Equations (\\ref{eq:q-update}), (\\ref{eq:skl-update}) or (\\ref{eq:jm-update})\n    \\ENDFOR\n    \\STATE $j=\\text{arg} \\max_{i} R_i$\n    \\IF{$R_j > J(\\Omega_{k-1})$}\n    \\STATE $\\Omega_{k-1} = \\{\\Omega_k \\setminus f_j\\}$\n    \\STATE $k=k-1$\n    \\ELSE\n    \\STATE $\\text{flag}=0$\n    \\ENDIF\n    \\ENDWHILE\n    \\ENDIF\n    \\ENDWHILE\n    \\RETURN $\\Omega_{\\text{maxVarNb}}$\n    \\end{algorithmic}\n    }\n    \\end{algorithm}\n\n    For each  iteration $k$, after  the selection of  optimal features\n    w.r.t  the  selected criterion,  the  inverses  of the  covariance\n    matrices and their log-determinant  needs to be computed. However,\n    the lack of training samples or the highly correlated features may\n    induce  a  badly-conditioned  matrix  with  very  small,  or  even\n    negative, eigenvalues.   Such values will degrade  drastically the\n    estimation of the  inverse and of the log-determinant,  and so the\n    numerical stability.\n\n    To deal with this limitation, the choice has been made to perform an eigenvalues decomposition of the covariance matrix $\\boldsymbol{\\Sigma}^{(k)}_c$:\n\n    \\begin{eqnarray}\n    \\boldsymbol{\\Sigma}^{(k)}_c = \\mathbf{P}^{(k)}_c \\boldsymbol{\\Lambda}^{(k)}_c (\\mathbf{P}^{(k)}_c)^t\\label{eq:eigendecomp}\n    \\end{eqnarray}\n\n\n    where $\\boldsymbol{\\Lambda}^{(k)}_c$  and $\\mathbf{P}^{(k)}_c$ are\n    the diagonal  matrix of eigenvalues  of the covariance  matrix and\n    the    orthonormal   matrix    of   corresponding    eigenvectors,\n    respectively.  To prevent numerical instability, \\rev{non strictly\n      positive eigenvalues are thresholded to a fixed value EPS\\_FLT}.\n    In our  implementation, EPS\\_FLT  is set  to the  floating machine\n    precision.\n\n    Then, the inverse of the covariance matrix can be computed as\n\n    \\begin{eqnarray}\n      (\\boldsymbol{\\Sigma}^{(k)}_c)^{-1} = \\mathbf{P}^{(k)}_c (\\tilde{\\boldsymbol{\\Lambda}}^{(k)}_c)^{-1} (\\mathbf{P}^{(k)}_c)^t\\label{eq:eigendecomp:inv}\n    \\end{eqnarray}\n\n    and the log-determinant as\n\n    \\begin{eqnarray}\n      \\label{eq:log:det}\n      \\log \\left(|\\boldsymbol{\\Sigma}_c^{(k)}|\\right) = \\sum_{i=1}^d\\log(\\tilde{\\lambda}_{c}^{(k)}(i)),\n    \\end{eqnarray}\n    where the \\textasciitilde{} indicated thresholded values and $\\lambda_{c}(i)$ the ith eigenvalue.\n\n    Same reasoning applied  to the term $\\alpha$ in  the update rules:\n    it       is       also        thresholded       to       EPS\\_FLT.\n    Algorithm~\\ref{alg:sffs-update}    details   when    computational\n    stability is enforced (lines 7, 13, 25 and 31).\n\n    \\subsection{Implementation}\n    \\label{sec:otb-module}\n    \\begin{figure} \n        \\centering %Pas touche l'indentation !\n        \\begin{minted}[fontsize=\\tiny,bgcolor=bg]{sh} \notbcli_TrainGMMSelectionApp -io.il hyper.tif \\\n                            -io.vd reference.shp \\\n                            -gmm.varnb 20 -gmm.method forward -gmm.crit jm\\\n                            -gmm.best 1 -gmm.seed 0\\\n                            -io.out model.txt\n\notbcli_PredictGMMApp -in hyper.tif \\\n                     -model model.txt -modeltype selection\\\n                     -out ThematicMap.tif\n        \\end{minted}\n        \\caption{OTB Module: The feature selection is done on the image \\emph{hyper.tif} using the training set from \\emph{reference.shp}. The feature selection algorithm is the forward search used with the Jeffries-Matusita criterion, 20 features are extracted and the corresponding GMM model is saved in \\emph{model.txt}. Then the whole image is classified using the model and the results is saved in the geotiff \\emph{ThematicMap.tif}.}\n        \\label{fig:otb:ffs}\n    \\end{figure}\n\n    \n    The proposed  method has been implemented  in \\texttt{C++} through\n    the  Orfeo  Toolbox (OTB)~\\cite{christophe2008orfeo}.   The  Orfeo\n    Toolbox  is  an  open-source  library  for  remote  sensing  image\n    processing,  developed by  the  French Space  Agency (CNES).   The\n    feature selection algorithm  can be installed as  a remote module,\n    the           source            code           is           freely\n    available\\footnote{\\url{https://www.orfeo-toolbox.org/external-projects/}}.\n\n    Following  OTB framework,  two  applications  are available.   The\n    first,  called  \\texttt{otbcli\\_TrainGMMSelectionApp}, performs  a\n    feature selection algorithm  (SFS or SFFS) with  the one criterion\n    given      from Table~\\ref{tab:crit}.       The      second,      called\n    \\texttt{otbcli\\_PredictGMMApp},   generates   the  thematic   maps\n    according to the  learn model. The only  technical limitation that\n    the  training set  must  fit  in the  RAM  of  the computer.   The\n    classification step is streamed and there is no limitation in term\n    of image  size. The Figure~\\ref{fig:otb:ffs} shows  a code excerpt\n    to run the application.\n\n\\section{Datasets}\n\\label{sec:datasets}\nNumerical experiments have been  conducted on two different datasets.\nThe  first  one,  called  \\emph{Aisa}, is  an  airborne  hyperspectral\ndataset  and  the  second,  called \\emph{Potsdam},  is  an  very  high\nresolution multispectral airborne image.\n\n    \\subsection{Aisa dataset}\n    \\label{sec:aisa-dataset}\n    The Aisa dataset has been acquired by the AISA Eagle sensor during\n    a  flight campaign  over Heves,  Hungary.  It  contains 252  bands\n    ranging from  395 to 975  nm. 16 classes  have been defined  for a\n    total of 361,971  referenced pixels, Table~\\ref{tab:aisa} presents\n    the number of pixel per  class.  The Figure~\\ref{fig:aisa} shows a\n    colored composition of the image and the ground-truth.\n\n    \\begin{figure}[!t]\n        \\centering\n        \\begin{tabular}{c}\n            \\includegraphics[width=0.6\\columnwidth]{Fig/aisa.png} \\\\\n            {\\bfseries{(a)}} \\\\\n            \\includegraphics[width=0.6\\columnwidth]{Fig/aisa_gt.png} \\\\\n            {\\bfseries{(b)}} \\\\\n        \\end{tabular}\n        \\caption{Aisa dataset: {\\bfseries{(a)}} colored composition of the image (R: 634nm, G: 519nm, B: 477nm), {\\bfseries{(b)}} ground-truth.\\label{fig:aisa}}\n    \\end{figure}\n\n    \\begin{table}[!t]\n        \\centering\n        \\caption{Information classes for the Aisa dataset.\\label{tab:aisa}}\n        \\begin{tabular}[b]{lc}\\toprule\n          Class & Number of samples \\\\ \\midrule\n          Winter wheat & 136,524 \\\\\n          Sunflower & 61,517 \\\\\n          Green fallow last year treatment & 30,197 \\\\\n          Alfalfa & 17,626 \\\\\n          Maize & 18,278 \\\\\n          Millet & 7,199 \\\\\n          Broadleaved forest & 10,746 \\\\\n          Meadow & 23,283 \\\\\n          Winter barley & 2,799 \\\\\n          Reed & 4,222 \\\\\n          Water course & 4,773 \\\\\n          Rape & 26,566 \\\\\n          Green fallow with shrub & 9,272 \\\\\n          Green fallow last year treated & 3,426 \\\\\n          Pasture & 2,107 \\\\\n          Oat & 3,436 \\\\ \\bottomrule\n        \\end{tabular}\n    \\end{table}\n\n    \\subsection{Potsdam dataset}\n    \\label{sec:pots-dataset}\n\n    This  second dataset  is built  from a  dataset of  remote sensing\n    images distributed by the International Society for Photogrammetry\n    and                         Remote                         Sensing\n    (ISPRS)\\footnote{\\url{http://www2.isprs.org/commissions/comm3/wg4/2d-sem-label-potsdam.html}}. The\n    dataset is composed of aerial images of the urban area of Potsdam.\n    The area  is divided  into 38  patches of  6000$\\times$6000 pixels\n    with a  resolution of 5cm by  pixel and 4 channels  are available:\n    Red, Blue,  Green and Infrared  (RGBIR).  A Digital  Surface Model\n    with  the  same  resolution  is  also  provided  and  a  so-called\n    normalized  DSM   representing  the   height  above   ground.  The\n    ground-truth  for  24  tiles  are provided  with  6  classes:  Low\n    vegetation, High vegetation, Impervious surfaces, Buildings, Cars,\n    Clutter.   Three tiles  have  been  used in  this  work, they  are\n    displayed             in            Figure~\\ref{fig:potsdam-expl}.\n    Table~\\ref{tab:potsdam} summarizes  the number of samples  of each\n    class.\n\n    \\begin{figure}[!t]\n        \\centering\n        \\begin{tabular}{c@{~}c@{~}c}\n            \\includegraphics[width=0.3\\columnwidth]{Fig/top_potsdam_5_11_RGB.jpg} &\n            \\includegraphics[width=0.3\\columnwidth]{Fig/top_potsdam_5_12_RGB.jpg} &\n            \\includegraphics[width=0.3\\columnwidth]{Fig/top_potsdam_3_10_RGB.jpg} \\\\\n            \\includegraphics[width=0.3\\columnwidth]{Fig/top_potsdam_5_11_label.jpg} &\n            \\includegraphics[width=0.3\\columnwidth]{Fig/top_potsdam_5_12_label.jpg} &\n            \\includegraphics[width=0.3\\columnwidth]{Fig/top_potsdam_3_10_label.jpg} \\\\\n            \\includegraphics[width=0.3\\columnwidth]{Fig/dsm_potsdam_05_11_normalized_lastools.jpg} &\n            \\includegraphics[width=0.3\\columnwidth]{Fig/dsm_potsdam_05_12_normalized_lastools.jpg} &\n            \\includegraphics[width=0.3\\columnwidth]{Fig/dsm_potsdam_03_10_normalized_lastools.jpg} \\\\\n            {\\bfseries{(a)}} & {\\bfseries{(b)}}  & {\\bfseries{(c)}}\\\\\n        \\end{tabular}\n        \\caption{From top to bottom, true color composition, ground-truth and normalized DSM of: {\\bfseries{(a)}} tile 5\\_11, {\\bfseries{(b)}} tile 5\\_12 and {\\bfseries{(c)}} tile 3\\_10.\\label{fig:potsdam-expl}}\n    \\end{figure}\n\n    \\begin{table}[!t]\n        \\centering\n        \\caption{Information classes for the three tiles of the Postdam dataset.\\label{tab:potsdam}}\n        \\begin{tabular}[b]{lrrr}\\toprule\n          & \\multicolumn{3}{c}{Number of samples per tile}\\\\\n            \\cmidrule{2-4}\n            Class &   5\\_11  &   5\\_12  & 3\\_10 \\\\\n          \\midrule\n          Clutter             & 1,078,611  & 812,038    & 1,890,467 \\\\\n          Trees               & 4,493,295  & 2,132,368  & 8,780,245 \\\\\n          Cars                & 900,076    & 1,101,541  & 434,615 \\\\\n          Buildings           & 13,469,575 & 17,501,421 & 5,128,149 \\\\\n          Low vegetation      & 4,718,219  & 3,210,596  & 11,428,326 \\\\\n          Impervious surfaces & 11,340,224 & 11,242,036 & 8,338,198 \\\\\n          \\bottomrule\n        \\end{tabular}\n    \\end{table}\n\n    In order to increase the dimensionality of the data,\n\n    \\rev{Conventionally,  the following  features are  extracted using  the\n    RGBIR  images in  order to  increase the  classification accuracy,\n    similarly to \\cite{tuia2015multiclass}:}\n    \\begin{itemize}\n        \\item Fifteen Radiometric indexes: NDVI, TNDVI, RVI, SAVI, TSAVI, MSAVI, MSAVI2, GEMI, IPVI, NDWI2, NDTI, RI, CI, BI, BI2~\\cite{otb}.\n        \\item Morphological profile build on each band with a disk of radius 5, 9, 13, 17, 21, 25, 29, 33, 37 and 41 (80 features)~\\cite{fauvel2013advances};\n        \\item Attribute profile build on each band with area as attribute and 1000, 2000, 5000, 10000 and 15000 as thresholds (40 features)~\\cite{dalla2010morphological}.\n        \\item Attribute profile build on each band with diagonal of bounding box as attribute and 100, 200, 500, 1000 and 20000 as thresholds (40 features)~\\cite{dalla2010morphological}.\n        \\item Textural features for  each channel with neighborhood of\n          19x19 pixels:  mean, standard  deviation, range  and entropy\n          (16 features)~\\cite{otb}.\n    \\end{itemize}\n    The normalized DSM and the raw  RGBIR image are added to these 191\n    features and  then stacked to create  a new image with  196 bands.\n    \\rev{The  resulting  data cube  is  therefore  high-dimensional.} \n    \n\n\n\\section{Experimental results}\n\\label{sec:test}\n\n    \\subsection{Method}\n    \\label{sec:method}\n\n    The aim  of the experiments is  to compare the proposed  method to\n    standard    classifiers    used    in   operational    land    map\n    production~\\cite{rs70912356}. A non-optimized  previous version of\n    the method has been already compared to other selection methods in\n    \\cite{fauvel2015fast}.  Hence, the primary  objective is to assess\n    the  operational  efficiency  and  it is  compared  to  other  OTB\n    classifiers   used  operationally   through  their   command  line\n    applications\\footnote{\\url{http://otbcb.readthedocs.io/en/latest/OTB-Applications.html}}.\n\n    The following classifiers are tested:\n    \\begin{itemize}\n        \\item A k-nearest-neighbors classifier (KNN) with OTB default parameters (32 as number of neighbors).\n        \\item A Random Forest classifier with parameters optimized by grid search (200 trees, 40 as max depth, 50 as size of the randomly selected subset of features at each tree node)\n        \\item A GMM classifier with ridge regularization (GMM ridge) with regularization constant optimized by grid search.\n    \\end{itemize}\n    The GMM classifier is part of the external module described in Section~\\ref{sec:otb-module}.\n\n    All these classifiers are compared with 3 configurations of the proposed GMM classifier:\n    \\begin{itemize}\n    \\item One with forward selection and JM distance as criterion (GMM SFS JM);\n    \\item One with forward selection and Cohen's kappa as criterion (GMM SFS kappa);\n    \\item One with floating forward selection and JM distance as criterion (GMM SFFS JM).\n    \\end{itemize}\n    Other configurations  have been  investigated and  performs either\n    equally     or     lower     in    terms     of     classification\n    accuracy~\\cite{al:report}. For the sake of clarity, only the three\n    aforementioned configurations are discussed here \\rev{and the results for all other configurations is available in the supplementary material}.\n\n    The training set has been created  with an equal number of samples\n    for each class and additionally  a spatial stratification has been\n    performed, \\emph{i.e.}, each training  sample belongs to a spatial\n    polygon  that  does  not  intersect  spatially  with  any  spatial\n    polygons used  for the validation.   Several size of  training set\n    have been  tested.  For  the Aisa  dataset, experiments  have been\n    conducted using  250, 500 and  1000 samples  by class and  for the\n    Potsdam dataset, 1000 and 50000 samples by class.\n\n    For SFS and  SFFS selection, the number of variables  to select is\n    set to  30 for the  Aisa dataset and  60 for the  Potsdam dataset.\n    After  the selection  procedure, the  optimal number  of extracted\n    variables is selected as follow.  Rather than selecting the number\n    of variables corresponding to the  highest value of the criterion,\n    the number of  retained variables is set when  the criterion stops\n    to  increase significantly.   \\rev{It  is found  by computing  the\n      discrete derivative  of the criteria between  two iterations and\n      normalizing it  by its  maximum value.   The number  of selected\n      features  corresponds to  the  last iteration  before the  value\n      drops    below    $10^{-3}$     for    all    datasets}.     See\n    Figure~\\ref{fig:crit-evol} for an example.\n\n    \\begin{figure}[!t]\n        \\centering\n        \\begin{tikzpicture}\n            \\begin{axis}[ymin=0.2,ymax=0.9,grid,axis x line=left,axis y line=left,xlabel={\\# variables},ylabel={Cohen's kappa},small]\n                \\addplot[thick,black] table[x=nb,y=crit] {criterion_1000spl_aisa.txt};\n                \\draw[thick,red] (axis cs:18,\\pgfkeysvalueof{/pgfplots/ymin}) -- (axis cs:18,\\pgfkeysvalueof{/pgfplots/ymax});\n                \\draw[thick,black] (axis cs:24,\\pgfkeysvalueof{/pgfplots/ymin}) -- (axis cs:24,\\pgfkeysvalueof{/pgfplots/ymax});\n            \\end{axis};\n        \\end{tikzpicture}\n        \\caption{Criterion evolution (kappa) in function of the number of selected variables for first trial with Aisa dataset with 500 samples by class. Red vertical line is the retained number of variables and black vertical line is the maximum of the criterion.\\label{fig:crit-evol}}\n    \\end{figure}\n\n    The    classification   rate    is    presented   using    Cohen's\n    kappa \\rev{but scores computed with overall accuracy and mean of f1-score are available in supplementary material}. Processing  time has been  evaluated on a  desktop computer\n    with  8Gb of  RAM  and  Intel(R) Core(TM)  i5-3570  CPU @  3.40GHz\n    $\\times$ 4 processors.\n\n    \\subsection{Aisa dataset}\n    \\label{sec:aisa}\n\n    When creating training and validation  sets, special care is taken\n    to assure that training samples are picked out from distinct areas\n    than test  samples.  The  polygons of the  reference are  split in\n    smaller polygons and then 50\\%  of the polygons are taken randomly\n    for training and the remaining 50\\% for validation.  An example of\n    training      and     validation      set     is      shown     in\n    Figure~\\ref{fig:set-aisa}.  From the  training  polygons, a  given\n    number of samples  were selected to build the  training set, while\n    all  the pixels  from the  validation polygons  were used  for the\n    validation.  Moreover 20  random trials were run  with a different\n    training  set (different  polygons).  Table~\\ref{tab:aisa-otbsimu}\n    presents  the results  of the  experiment with  mean and  standard\n    deviation  of  the  Kappa  coefficient  over  the  20  trials  and\n    Table~\\ref{tab:aisa-otbsimu-time}  the   corresponding  processing\n    time. Bold values corresponds to best results. In Table~\\ref{tab:aisa-otbsimu}, when several bold scores appears for the same experiment, it means that the scores has been assessed as equivalent with a Wilcoxon rank-sum test \\cite{mann1947test}. Additionally, \\ref{tab:aisa-otbsimu-time} summarizes the mean of the number of selected variables for each variation of the GMM classifier with selection.\n\n    \\begin{figure}[!t]\n        \\centering\n        \\begin{tabular}{c}\n            \\includegraphics[width=0.6\\columnwidth]{Fig/aisa_gt_train.png} \\\\\n            {\\bfseries{(a)}} \\\\\n            \\includegraphics[width=0.6\\columnwidth]{Fig/aisa_gt_test.png} \\\\\n            {\\bfseries{(b)}} \\\\\n        \\end{tabular}\n        \\caption{Aisa dataset: {\\bfseries{(a)}} training polygons of first trial, {\\bfseries{(b)}} test polygons of first trial.\\label{fig:set-aisa}}\n    \\end{figure}\n\n    \\begin{table}[!t]\n        \\centering\n        \\caption{Average classification accuracy 20 trials (standard deviation in parenthesis).\\label{tab:aisa-otbsimu}}\n        \\begin{tabular}{lccc}\\toprule\n             & \\multicolumn{3}{c}{\\bfseries Cohen's kappa} \\\\ \\cmidrule{2-4}\n            \\# samples by class & 250 & 500 & 1000 \\\\ \\midrule\n\n            GMM SFS kappa & {\\bfseries 0.678 (0.029)} & {\\bfseries 0.687 (0.029)} & {\\bfseries 0.699 (0.028)} \\\\\n            GMM SFS JM &    {\\bfseries 0.685 (0.030)} & {\\bfseries 0.689 (0.030)} & {\\bfseries 0.701 (0.029)} \\\\\n            GMM SFFS JM &   {\\bfseries 0.685 (0.030)} & {\\bfseries 0.689 (0.030)} & {\\bfseries 0.701 (0.029)} \\\\\n            GMM ridge &     0.611 (0.040) & 0.620 (0.036) & 0.642 (0.034) \\\\\n            KNN &           0.551 (0.035) & 0.563 (0.033) & 0.574 (0.030) \\\\\n            Random Forest & 0.645 (0.026) & 0.673 (0.023) & {\\bfseries 0.693 (0.023)} \\\\\n            \\bottomrule\n        \\end{tabular}\n    \\end{table}\n\n    \\begin{table*}[!t]\n        \\centering\n        \\caption{Mean processing time for training and classification for results in Table \\ref{tab:aisa-otbsimu}.\\label{tab:aisa-otbsimu-time}}\n        \\begin{tabularx}{0.8\\textwidth}{l*{9}{>{\\centering\\arraybackslash}X}}\n            \\toprule\n             & \\multicolumn{3}{c}{\\bfseries Training time (s)} & \\multicolumn{3}{c}{\\bfseries Classification time (s)} & \\multicolumn{3}{c}{\\bfseries \\# of selected features} \\\\ \\cmidrule{2-10}\n            \\# samples by class & 250 & 500 & 1000 & 250 & 500 & 1000 & 250 & 500 & 1000 \\\\ \\midrule\n\n            GMM SFS kappa & 257             & 496             & 955             & {\\bfseries 5.2} & {\\bfseries 5.2} & {\\bfseries 5.5} & 11.95 & 12    & 12.05\\\\\n            GMM SFS JM &    {\\bfseries 8.6} & {\\bfseries 8.9} & {\\bfseries 9.1} & {\\bfseries 5.7} & {\\bfseries 5.7} & {\\bfseries 5.9} & 11.95 & 12    & 12.05\\\\\n            GMM SFFS JM &   {\\bfseries 8.8} & {\\bfseries 9.0} & {\\bfseries 9.3} & {\\bfseries 5.0} & {\\bfseries 5.0} & {\\bfseries 5.4} & 21.45 & 24.35 & 27.05\\\\\n            GMM ridge &     71.7            & 105             & 167             & 530 & 530 & 530    & all & all & all \\\\\n            KNN &           {\\bfseries 8.9} & 19.6            & 59.7            & 387 & 639 & 887    & all & all & all \\\\\n            Random Forest & 24.5            & 49.3            & 105             & 33.0 & 41.7 & 45.9 & all & all & all \\\\\n            \\bottomrule\n        \\end{tabularx}\n    \\end{table*}\n\n    % \\begin{figure}\n    %   \\centering\n    %   \\begin{tikzpicture}\n    %     \\begin{axis}[ylabel=$\\bar{n}_s$,ymax=25,\n    %       symbolic x coords={0,250,500,1000,1050},\n    %       enlargelimits=0.15,legend pos=outer north east,xtick=data,legend cell align=left,\n    %       ybar,\n    %       bar width=5pt,grid,xlabel=Number of training samples per class,small,area legend]\n    %       \\addplot coordinates {(250,15.9) (500,21.85) (1000,26.65)};\n    %       \\addplot coordinates {(250,11.95) (500,12) (1000,12.05)};\n    %       \\addplot coordinates {(250,11.95) (500,12) (1000,12.05)};\n    %       \\legend{{\\footnotesize SFS kappa},{\\footnotesize SFS JM},{\\footnotesize SFFS JM}}\n    %     \\end{axis}\n    %   \\end{tikzpicture}\n    %   \\caption{Mean number $\\bar{n}_s$ of selected features for the different variation of selection methods for Aisa data set. The original number of features is 252.}\n    %   \\label{fig:meanNbVar-aisa}\n    % \\end{figure}\n\n\n    The results show that, on this  dataset, GMM classifiers with feature selection get the best classification rate. Among the three variations of the selection algorithm, none appears to perform better than the others. Using kappa or Jeffries-Matusita distance as criterion is equal and using SFFS does not give any advantage.\n\n    The difference with the second best classifier, Random Forest, appears to be significant when using 250 and 500 samples. Random Forest has similar performance in term of classification rate with 1000 samples \\rev{and one could expect to get a better classification rate with RF if more samples were available}. The GMM classifier with ridge regularization and the KNN classifier are both outperformed.\n\n    In term of computational time, the GMM classifiers are as expected very fast for classification and also for training, except when the criterion function is a classification rate. In this case, using JM distance as criterion and SFS as search strategy is the best choice in term of time efficiency. The good performance in time can be explained by the dimension reduction. Actually, the decision rule corresponding to Equation~(\\ref{eq:decision}) has a complexity in $d^3$ where $d$ is the dimension. Thus, reducing $d$ induces a reduction of the classification time.\n\n    The processing times of the three standard classifiers suffer from the increase of training samples. For the GMM classifier with ridge, the selection of regularization parameter is more costly with more samples because of the classification rate estimation needed. For the KNN classifier, the model stores all the training samples and the prediction implies to compute the distance to all the training samples which explains the increase of the processing time and additionally of the size of the model file. Finally, for the Random Forest classifier, the trees tends to be deeper in order to capture the additional information available with more samples and that explains the increase of the processing time.\n\n    \\subsection{Potsdam dataset}\n\n    For the Potsdam  dataset, training samples were  selected from one\n    tile (5\\_11)  and validation  samples were all  the pixel  of tile\n    5\\_12     or    3\\_10.      Table~\\ref{tab:potsdam-otbsimu}    and\n    Table~\\ref{tab:potsdam-otbsimu-big} present  the results  in terms\n    of classification accuracy and processing time. Bold values corresponds to best results. In Table~\\ref{tab:potsdam-otbsimu}, when several bold scores appears for the same experiment, it means that the scores has been assessed as equivalent with a Wilcoxon rank-sum test \\cite{mann1947test}.\n\n    \\begin{table*}[!t]\n        \\centering\n        \\caption{Kappa coefficient and processing time for 1,000 samples by class and averaged over 5 trials (standard deviation in parenthesis). Processing times are given in second.\\label{tab:potsdam-otbsimu}}\n        \\begin{tabular}{lcccccc}\\toprule\n            & {\\bfseries 5\\_11 (train)} & {\\bfseries 5\\_12 (test)} & {\\bfseries 3\\_10 (test)} & {\\bfseries Train. Time} & {\\bfseries Classif. time} & {\\bfseries \\# of selected features} \\\\ \\cmidrule{2-7}\n            GMM SFS kappa & 0.694 (0.002)             & {\\bfseries 0.669 (0.005)} & {\\bfseries 0.533 (0.008)} & 400 & 310  & 13.2 \\\\\n            GMM SFS JM &    0.624 (0.028)             & 0.631 (0.034)             & 0.461 (0.027)             & 2   & 310  & 11 \\\\\n            GMM SFFS JM &   0.624 (0.028)             & 0.631 (0.034)             & 0.461 (0.027)             & 2.6 & 310  & 11 \\\\\n            GMM ridge &     0.632 (0.007)             & 0.592 (0.010)             & 0.433 (0.008)             & 10  & 2000 & all \\\\\n            KNN &           0.637 (0.005)             & 0.607 (0.005)             & 0.478 (0.002)             & 0.7 & 9500 & all \\\\\n            Random Forest & {\\bfseries 0.729 (0.004)} & {\\bfseries 0.673 (0.005)} & {\\bfseries 0.529 (0.009)} & 20  & 840  & all \\\\\n            \\bottomrule\n        \\end{tabular}\n    \\end{table*}\n\n    \\begin{table*}[!t]\n        \\centering\n        \\caption{Kappa coefficient and processing time for 50,000 samples by class and averaged over 5 trials (standard deviation in parenthesis). Processing times are given in second. NB: the test has not been conduct with KNN because of a too long processing time for classification.\\label{tab:potsdam-otbsimu-big}}\n        \\begin{tabular}{lcccccc}\\toprule\n            & {\\bfseries 5\\_11 (train)} & {\\bfseries 5\\_12 (test)} & {\\bfseries 3\\_10 (test)} & {\\bfseries Train. Time} & {\\bfseries Classif. time} & {\\bfseries \\# of selected features} \\\\ \\cmidrule{2-7}\n            GMM SFS kappa & 0.713 (0.001) & 0.684 (0.001) & 0.531 (0.005) & 20000 & 340 & 29 \\\\\n            GMM SFS JM &    0.560 (0.111) & 0.576 (0.104) & 0.435 (0.085) & 6 & 330 & 10 \\\\\n            GMM SFFS JM &   0.560 (0.111) & 0.576 (0.104) & 0.435 (0.085) & 6.6 & 340 & 10 \\\\\n            GMM ridge &     0.641 (0.015) & 0.611 (0.026) & 0.440 (0.015) & 460 & 2000 & all \\\\\n            KNN &           /             & /             & /             & / & / & / \\\\\n            Random Forest & {\\bfseries 0.851 (0.001)} & {\\bfseries 0.715 (0.001)} & {\\bfseries 0.573 (0.002)} & 2000 & 2000 & all \\\\\n            \\bottomrule\n        \\end{tabular}\n    \\end{table*}\n\n    With this second dataset, the Random Forest classifier and the GMM classifier with kappa as selection criterion perform the best in terms of classification accuracy. When using 1000 samples per class, no significant difference of classification rate has been observed on test set. But, with 50,000 samples per class, the Random Forest classifier becomes significantly better in terms of classification accuracy.\n\n    The  Postdam classes  are  more difficult  to discriminate,  since\n    Gaussianity assumption  does not  hold. For instance,  a building\n    can  be  made of  various  materials,  resulting in  heterogeneous\n    distribution.   Hence,  GMM  with  ridge  regularization  performs\n    baldy. Random  Forest classifier is  more adapted to  this problem\n    and reached the  best classification accuracy. However,  it can be\n    note  that letting  the algorithm  be driven  by a  classification\n    quality criterion such as the Kappa coefficient helps in improving\n    the  classification   accuracy.  The   KNN  classifier   is  again\n    outperformed.\n\n    From        the        tables~\\ref{tab:potsdam-otbsimu}        and\n    Table~\\ref{tab:potsdam-otbsimu-big},   the  number   of  extracted\n    variables shows that JM criterion identifies less relevant samples\n    than with the kappa criterion. Moreover, the selection method with\n    criterion kappa manages to get good performance with only 6.7\\% of\n    the  initial variables  with  1000 samples  and  15\\% with  50,000\n    samples.\n\n    In term of processing time, results are similar than with the Aisa\n    dataset.  GMM  classifiers  with   selection  are  very  fast  for\n    prediction.  For  example,  the   GMM  classifier  with  kappa  as\n    criterion for the selection is  63\\% faster than the Random Forest\n    classifier for prediction  with 1000 samples and  83\\% faster with\n    50,000  samples.  However, the  training  time  is increased  with\n    respect to random forest.\n\n\\section{Conclusion and perspectives}\n\\label{sec:conclusion}\n\nAn algorithm for the classification of high dimensional Earth observation images has been proposed. The algorithm is based on Gaussian mixture model and a forward feature selection strategy to reduce the dimension of the data to be processed. From experimental results, this strategy has shown to be robust the \\emph{curse of dimensionality}. As a side effect, the volume of data is reduced and the final classification processing time is reduced. \n\nTo cope with the large volume of data during the learning step, updates rules from the forward search have been split into two parts in order to save computation. One part is only computed once per iteration, and the other part needs to be computed for each tested features. Several criteria have been included, three based on classification accuracy and two based on divergence measures.\n\nExperiments have been conducted on two real high dimensional data set, and the results have been compared to standards classifiers. Results show that the proposed approach  performs, in most cases, at least as best as classifiers (Random Forest) and even outperforms all of them in term of classification time.\n\nThe resulting code is available as a remote module of the Orfeo ToolBox on GitHub and makes it possible to process large high dimensional images efficiently. The \\texttt{C++} code is freely available for download: \\url{https://www.orfeo-toolbox.org/external-projects/}.\n\nPerspectives of this work concern the selection of continuous interval of features rather than a single feature~\\cite{serpico2007extraction,1468090}. It will be of  highest interest for continuous features, such as temporal feature or spectral feature.\n\n\\appendices\n\\section{Proof of update rules}\n\\label{app:proof-update}\n\n\\begin{proof}[Proof of proposition~(\\ref{eq:update-quad})]\n    \\begin{alignat*}{3}\n    (&\\mathbf{x}^{(k)})^t && (\\boldsymbol{\\Sigma}^{(k)}_c)^{-1} \\mathbf{x}^{(k)} \\\\\n     &= &&\\left[\\begin{array}{cc} (\\mathbf{x}^{(k-1)})^t   & x_k \\end{array}\\right]\n        \\left[\\begin{array}{cc}\n            \\mathbf{A}_c   & \\mathbf{v}_c \\\\\n            \\mathbf{v}_c^t & \\frac{1}{\\alpha_c}\n        \\end{array}\\right]\n        \\left[\\begin{array}{c} \\mathbf{x}^{(k-1)} \\\\ x_k \\end{array}\\right] \\\\\n     &= &&\\left[\\begin{array}{cc} (\\mathbf{x}^{(k-1)})^t   & x_k \\end{array}\\right]\n            \\left[\\begin{array}{c} \\mathbf{A}_c \\mathbf{x}^{(k-1)} + x_k \\mathbf{v}_c \\\\ \\mathbf{v}_c^t \\mathbf{x}^{(k-1)} + \\frac{x_k}{\\alpha_c} \\end{array}\\right] \\\\\n     &= &&(\\mathbf{x}^{(k-1)})^t \\mathbf{A}_c \\mathbf{x}^{(k-1)} + x_k \\mathbf{v}_c^t \\mathbf{x}^{(k-1)} \\\\\n     & &&+ (\\mathbf{x}^{(k-1)})^t \\mathbf{v}_c x_k + \\frac{(x_k)^2}{\\alpha_c} \\\\\n     &= &&(\\mathbf{x}^{(k-1)})^t \\Big((\\boldsymbol{\\Sigma}_c^{(k-1)})^{-1} \\\\\n     & &&+ \\frac{1}{\\alpha_c} (\\boldsymbol{\\Sigma}_c^{(k-1)})^{-1} \\mathbf{u}_c \\mathbf{u}_c^t (\\boldsymbol{\\Sigma}_c^{(k-1)})^{-1}\\Big) \\mathbf{x}^{(k-1)}\\\\\n     & &&+ 2 x_k \\mathbf{v}_c^t \\mathbf{x}^{(k-1)} + \\frac{(x_k)^2}{\\alpha_c} \\\\\n     &= &&(\\mathbf{x}^{(k-1)})^t \\Big((\\boldsymbol{\\Sigma}_c^{(k-1)})^{-1} + \\alpha_c \\mathbf{v}_c \\mathbf{v}_c^t\\Big) \\mathbf{x}^{(k-1)}\\\\\n     & &&+ 2 x_k \\mathbf{v}_c^t \\mathbf{x}^{(k-1)} + \\frac{(x_k)^2}{\\alpha_c} \\\\\n     &= &&(\\mathbf{x}^{(k-1)})^t (\\boldsymbol{\\Sigma}_c^{(k-1)})^{-1} \\mathbf{x}^{(k-1)} + \\alpha_c \\Big( (\\mathbf{x}^{(k-1)})^t \\mathbf{v}_c \\mathbf{v}_c^t \\mathbf{x}^{(k-1)} \\\\\n     & &&+ 2 \\frac{x_k}{\\alpha_c} \\mathbf{v}_c^t \\mathbf{x}^{(k-1)} + \\frac{(x_k)^2}{\\alpha_c^2}\\Big) \\\\\n     &= &&(\\mathbf{x}^{(k-1)})^t (\\boldsymbol{\\Sigma}_c^{(k-1)})^{-1} \\mathbf{x}^{(k-1)} + \\alpha_c \\Big( (\\mathbf{x}^{(k-1)})^t \\mathbf{v}_c + \\frac{x_k}{\\alpha_c} \\Big)^2 \\\\\n     &= &&(\\mathbf{x}^{(k-1)})^t (\\boldsymbol{\\Sigma}_c^{(k-1)})^{-1} \\mathbf{x}^{(k-1)} + \\alpha_c ( \\left[\\begin{array}{cc} \\mathbf{v}_c^t & \\frac{1}{\\alpha_c} \\end{array}\\right] \\mathbf{x}^{(k)} )^2\n    \\end{alignat*}\n\\end{proof}\n\n\\begin{proof}[Proof of proposition~(\\ref{eq:update-log})]\n\n  From eq.~(\\ref{eq:cov}) and standard results for the determinant of block matrix~\\cite[Chapter 9]{IMM2012-03274} we have immediately:\n  \\begin{align*}\n    \\log \\left(|\\boldsymbol{\\Sigma}_c^{(k)}|\\right)  & = \\log\\left(|\\boldsymbol{\\Sigma}_c^{(k-1)}|\\right)\\log\\left(\\sigma^{(k)}_c  - \\mathbf{u}_c^t (\\boldsymbol{\\Sigma}_c^{(k-1)})^{-1}  \\mathbf{u}_c\\right)\\\\\n    &= \\log\\left(|\\boldsymbol{\\Sigma}_c^{(k-1)}|\\right)\\log\\left(\\alpha_c\\right)\n  \\end{align*}\n  \n\\end{proof}\n\n% \\section*{Acknowledgment}\n\n% The authors would like to thank...\n\n\\bibliographystyle{IEEEtran}\n\\bibliography{IEEEabrv,biblio}\n\n% biography section\n%\n% If you have an EPS/PDF photo (graphicx package needed) extra braces are\n% needed around the contents of the optional argument to biography to prevent\n% the LaTeX parser from getting confused when it sees the complicated\n% \\includegraphics command within an optional argument. (You could create\n% your own custom macro containing the \\includegraphics command to make things\n% simpler here.)\n%\\begin{IEEEbiography}[{\\includegraphics[width=1in,height=1.25in,clip,keepaspectratio]{mshell}}]{Michael Shell}\n% or if you just want to reserve a space for a photo:\n\n\\begin{IEEEbiography}[{\\includegraphics[width=1in,height=1.25in,clip,keepaspectratio]{Fig/lagrange.jpg}}]{Adrien Lagrange} received an Engineering degree in Robotics and Embedded Systems from ENSTA ParisTech, Paris (Palaiseau), France, and the M.Sc. degree in Machine Learning from the Paris Saclay University, both in 2016.\n\nHe is currently a Ph.D. student at the National Polytechnic Institute of Toulouse, within the Signal and Communications Group of the IRIT Laboratory. He is working on the subject of multi-resolution learning for hierarchical analysis of hyperspectral and hypertemporal images under the supervision of Nicolas Dobigeon and Mathieu Fauvel. His research interests are remote sensing, statistical modeling, image processing.\n\\end{IEEEbiography}\n\n\\begin{IEEEbiography}[{\\includegraphics[width=1in,height=1.25in,clip,keepaspectratio]{fauvel.pdf}}]{Mathieu Fauvel}\n graduated in  electrical engineering  from the Grenoble  Institut of\n Technology (Grenoble  INP), Grenoble, France, in  2004.  He  received\n the M.S and  Ph.D.  degrees in image and signal  processing from  the\n Grenoble INP  in 2004  and 2007,  respectively.  In  2007, he  was a\n teaching assistant  in Grenoble  INP. From  2008 to  2010, he  was a\n postdoctoral research associate with the MISTIS Team of the  National\n Institute  for Research  in  Computer Science  and Control  (INRIA).\n Since 2011,  Dr.  Fauvel  has been an  Associate Professor  with  the\n National Polytechnic  Institute of  Toulouse (ENSAT -  University of\n Toulouse) within  the DYNAFOR lab  (University of Toulouse  -  INRA).\n His  research interests  are  remote sensing,  data fusion,  pattern\n recognition, multicomponent signal and image processing. From  2013 to 2016,\n he was the president of the French Chapter of the GRSS. He is  now in charge of the European GRSS Chapters activities.\n\\end{IEEEbiography}\n\n\\begin{IEEEbiography}[{\\includegraphics[width=1in,height=1.25in,clip,keepaspectratio]{Fig/manuel}}]{Manuel Grizonnet} received the Mathematical modeling, Vision, Graphics and\n  Simulation Engineer degree from the \\'{E}cole Nationale Sup\\'{e}rieure d'Informatique\n  et de Math\\'{e}matiques Appliqu\\'{e}es de Grenoble, France, in 2007. From 2007 to 2009\n  he worked for the BRGM (French geological survey) in Niamey, Niger where he was a\n  Systems and Geological Information System (GIS) engineer. He is currently with\n  the Centre National d'\\'{E}tudes Spatiales (French Space Agency), Toulouse,\n  France, where he is developing image processing algorithms and software for\n  the exploitation of Earth observation images.\n\\end{IEEEbiography}\n\n% % if you will not have a photo at all:\n% \\begin{IEEEbiographynophoto}{John Doe}\n% Biography text here.\n% \\end{IEEEbiographynophoto}\n\n% insert where needed to balance the two columns on the last page with\n% biographies\n%\\newpage\n\n\\end{document}\n", "meta": {"hexsha": "68dbd0f3bd367ed98912b58582a8d24a37b3dd2c", "size": 83028, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper.tex", "max_stars_repo_name": "Laadr/FFSforGMMArticle", "max_stars_repo_head_hexsha": "07313596c17e6ecf6fd7980e26833b1ce6887867", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paper.tex", "max_issues_repo_name": "Laadr/FFSforGMMArticle", "max_issues_repo_head_hexsha": "07313596c17e6ecf6fd7980e26833b1ce6887867", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper.tex", "max_forks_repo_name": "Laadr/FFSforGMMArticle", "max_forks_repo_head_hexsha": "07313596c17e6ecf6fd7980e26833b1ce6887867", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 65.3249409913, "max_line_length": 1157, "alphanum_fraction": 0.6699065376, "num_tokens": 23987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.3275202523698191}}
{"text": "%!TEX root = ../thesis.tex\n%*******************************************************************************\n%****************************** Third Chapter **********************************\n%*******************************************************************************\n\\chapter{Validating Reduced Order Models}\n\n\\ifpdf\n    \\graphicspath{{Chapter4/Figs/Raster/}{Chapter4/Figs/PDF/}{Chapter4/Figs/}}\n\\else\n    \\graphicspath{{Chapter4/Figs/Vector/}{Chapter4/Figs/}}\n\\fi\n\n\\section{Summary}\nThis chapter focuses on validating the hierarchy of models developed in Chapter 3. In the context of this work, model validation is the process of both estimating the parameters of models in such a way that they simultaneously minimize the difference between these models and experimental data, and give reasonable uncertainty in the model output and estimated parameters.\n\nThe chapter begins with a formulation of parameter estimation as a nonlinear optimization problem, followed by a discussion of different methods of optimization, with an emphasis on Particle Swarm Optimization (PSO), a review of challenges in optimization, and a discussion about how uncertainty of parameters can be quantified through confidence regions. We wrap up the algorithmic component of our discussion by presenting a novel optimization framework that is used to simultaneously validate models, establish confidence in our results, and determine the number of experiments needed to yield a user-defined balance of fitting models with a high degree of accuracy, and giving a meaningful distribution of estimated parameters and model outputs. Subsequently, we present a two part discussion on the results of our novel algorithm when applied to our reduced comb-drive actuator in electrolyte models, and the accompanying experiments. The first part of the discussion, focuses on observing the results of our algorithm in the scenario where we are concerned only with determining which of the reduced models fit the data with the greatest degree of fidelity. In this part of the discussion, we make use of all our experiments, and comment on the simplest model that best fits the data. The second part of our discussion examines the results of our algorithm more holistically. Here, we observe the confidence regions found by our algorithms when applied to different reduced order models, at different numbers of experiments and measurements. We then comment on how the confidence regions, as well as the distribution of model outputs, change for each model as a function of the amount of data used in the fit, and at a particular confidence, $1-\\alpha$. Finally, we discuss how we can use the in-depth results of our algorithm to select the correct combination of reduced order models, and amount of data that allows us to explain the behavior of the comb-drive actuator with some balance of fit to data, and an appropriate distributions of model outputs and estimated parameters. \n\n\\section{Parameter Estimation as an Optimization Problem}\nThe problem of estimating the parameters of a model that best fits the data can be represented as the following nonlinear optimization problem\n\n\\begin{equation} \\label{orig_optim_problm}\n\\begin{aligned}\n& \\underset{x}{\\text{minimize}}\n& & y(\\mathbf{x},\\mathbf{z}) = y(\\mathbf{x}) = ||\\mathbf{f}(\\mathbf{x},\\mathbf{z}) - \\mathbf{g}(\\mathbf{z})||_p \\\\\n& \\text{subject to}\n& & x_{i,min} \\leq x_i \\leq x_{i,max} , \\; i = 1, \\ldots, m.\n\\end{aligned}\n\\end{equation}\n\nwhere $\\mathbf{x}$ is the vector of tune-able parameters that the model takes as in input, $\\mathbf{z}$ is the vector of inputs to the model that are not tune-able, $\\mathbf{f}$ is the vector of values that are output by the model given a particular set of $\\mathbf{x}$ and $\\mathbf{z}$, $\\mathbf{g}$ is the vector of values that are output given $\\mathbf{z}$, $p$ is an integer that indicates the type of norm we are taking (eg. $p=1 \\implies \\textrm{ L1 norm}$), $x_i$ is the $i_{th}$ component of the vector $\\mathbf{x}$, and $m$ is the number of components in that vector. This is a standard bounded nonlinear optimization problem. In our case, we bound the parameters of the model, $\\mathbf{x}$, so that our optimization framework only selects physically realizable values, and we select $p=2$ so that the above objective function becomes L2 (least-squares).\n\n\\section{Optimization Techniques}\nThis section focuses on reviewing different optimization techniques. We discuss gradient methods, with a focus on the trust region reflective algorithm, and stochastic methods, with a focus on particle swarm optimisation. \n\n\\subsection{Gradient Methods}\n\nGradient methods for optimization are among the most popular in literature. These methods use the gradients, or approximate gradients, of functions with respect to their tuneable inputs in order to find the value of these inputs that minimize or maximize said function. The most common gradient optimization method is gradient descent, which has gained particular favor in the machine learning community \\textbf{CITE NG}. Given the optimization problem, \\ref{orig_optim_problm}, and neglecting the constraints, gradient descent involves making an initial guess at the solution, $\\mathbf{x}^{0}$, and iterating on that guess using,\n\n\\begin{equation} \\label{grad_descent}\n    \\mathbf{x}^{n+1} = \\mathbf{x}^{n} - \\alpha g, \\quad g = \\nabla_\\mathbf{x} y(\\mathbf{x}^{n},\\mathbf{z})\n\\end{equation}\nwhere $\\alpha$ is the learning rate, $x^{n}$ is the guess of the solution at the $nth$ iteration of gradient descent, $x^{n+1}$ is the guess at the $(n+1)th$ iteration based on the gradient of the objective function, and $\\nabla_\\mathbf{x} y(\\mathbf{x}^{n},\\mathbf{z})$ is the numeric or analytic gradient of $y$ with respect $\\mathbf{x}$, evaluated at $\\mathbf{x}^{n}$. While gradient descent is a powerful optimization method, it can be very expensive, especially when optimizing a nonlinear function. In particular, while the gradient moves in the direction of greatest change in the function, it does so at an arbitrary distance, making it more prone to \"overreacting\" to local curvature in a nonlinear function \\textbf{illustration of this}.\n\nIn order to address this issue, a class of gradient based methods, termed Trust Region, methods were developed. These optimization methods in particular involve first determining the maximum magnitude, $\\delta$, of change that can be imposed on the current guess of the solution. The size of $\\delta$ is determined primarily by the extent to which the objective function being minimized reduces in the region around the current guess of a solution. There are a variety of algorithms for implementing this class of algorithms, the details of which are illustrated by Yuan et al., \\textbf{CITE TRUST REGION}. To end our discussion on gradient methods, we will outline the general trust region problem.\n\nThe first step of the Trust-Region algorithm is making a local quadratic approximation of the objective function.\n\n\\begin{equation} \\label{quad_approx}\n    \\tilde{y}(\\mathbf{x}+\\delta,\\mathbf{z}) = y(\\mathbf{x},\\mathbf{z}) + g^T \\delta + \\delta^T B \\delta \n\\end{equation}\nwhere g is as defined in \\ref{grad_descent}, $\\delta$ is some perturbation to $\\mathbf{x}$, and $B$ is an approximation of the hessian of the objective function.\\textbf{CITE TRUST REGION} If Like gradient descent, the Trust Region Algorithm is iterative. It selects a vector step by which to change $\\mathbf{x}^n$ by using \\ref{quad_approx} to solve the following constrained optimization problem,\n\n\\begin{equation} \\label{trust_region_optim_problm}\n\\begin{aligned}\n& \\underset{\\delta}{\\text{minimize}}\n& & y_n(\\mathbf{x}^n,\\mathbf{z}) + g_n^T \\delta + \\delta^T B_n \\delta\\\\\n& \\text{such that}\n& & ||\\delta||_2 \\leq \\Delta_n.\n\\end{aligned}\n\\end{equation}\n\nwhere $g_n$ is the gradient of the objective function evaluated at $\\mathbf{x}^n$, $B_n$ is the approximation of the Hessian at the $\\mathbf{x}^n$, and $\\Delta_n$ is the trust region at iteration $n$. The size of $\\Delta_n$ is determined by the extent to which the objective function, $y$, can be minimized within this region. If on the previous iteration, $n-1$, the objective function is sufficiently reduced, then the trust region generally expands. If not, it reduces. Since we simply use a Python implementation of the Trust Region Algorithm, we do not go into specifics. Details on a variety of Trust Region Algorithms can be found in Yuan et al, \\textbf{CITE TRUST REGION}.  \n\n\\subsection{Stochastic Optimization Methods: Particle Swarm Optimization (PSO)}\nGradient based methods have two main limitations. The first is that they require the calculation of gradients, which can be expensive, and the second is that they are prone to local minima when given poor initial conditions. Stochastic optimization methods attempts to address both of these issues. Rather than taking gradients, stochastic optimization methods randomly search the solution space in order to minimize an objective function. Some of these algorithms have heuristically been shown to be more efficient at finding the global minimum of an objective function, \\textbf{CITE PSO Thesis}. The stochastic optimization method of interest to us is Particle Swarm Optimization (PSO). In this section we will review PSO, and its key variants.  \n\nThe basic version of PSO was developed by Kennedy et al. \\textbf{Cite Basic PSO Paper}. In this version of PSO, the user initializes a \"swarm\" of $m$ guesses at an optimal solution, $(\\mathbf{x}_1,...,\\mathbf{x}_m)$, and evaluates the function at each of these guesses. The guess that results in the most optimal function, $\\mathbf{x}_{Best}$, is stored. Each guess is called a particle, and the best solution each particle has ever seen during the optimization process is stored as $\\mathbf{x}_{i,Best}$. During an iteration of particle swarm optimization, each particle's velocity is updated as \n\n\\begin{equation} \\label{pso_vel}\n    \\begin{aligned}\n    v_{i,j}(k+1) &= w v_{i,j}(k) + c_1 r_{1,j}((\\mathbf{x}_{i,Best}(k))_j - x_{i,j}(k)) + c_2 r_{2,j} ((\\mathbf{x}_{Best}(k))_{i,j} - x_{i,j}(k)), \\\\ \n    &i=1,...,m \\quad j=1,...,n\n    \\end{aligned}\n\\end{equation}\nwhere $v_{i,j}(k)$ is the velocity of the $j^{th}$ dimension of the $i^{th}$ particle at iteration $k$, $w$ is an inertial weight that states the extent to which the current velocity should impact the subsequent one, $c_1$ is a user determined constant, and $r_{1,j}$ and $r_{2,j}$ are random variables distributed uniformly in the interval $[0,1]$, i.e $r_1 \\sim U(0,1)$ and $r_2 \\sim U(0,1)$. This velocity equation is then used to update each solution guess (particle), as\n\n\\begin{equation} \\label{pso_pos}\n    x_{i,j}(k+1) = x_{i,j}(k) + \\mathbf{x}_{i,j}(k)\n\\end{equation}\nAlgorithm \\ref{pso_algorithm} sketches out the PSO in detail, assuming that the goal is to minimize some objective function $f$. A couple of things should be clarified from the algorithm sketch. Three of these clarifications involve the position and velocity of each particle. First, it is standard to guess the initial particles by sampling a multivariate uniform distribution in the domain defined by $\\mathbf{x}_{max}$ and $\\mathbf{x}_{min}$. Second, a maximum, $\\mathbf{v}_{max}$, and minimum, $\\mathbf{v}_{min}$, speed, is used to bound the velocity of each particle at each iteration of PSO. This is in order to help keep the particle dynamics stable, a point that will be expounded on shortly. Third, the re-initialization of particles that move outside of the solution domain is not well part of the original PSO algorithm. However, we added this in order to help insure that most of the particles remained within the defined solution domain.\n\nThe next set of points that need to be expanded upon are the values of user defined hyper-parameters, $c_1$, $c_2$, and $w$. These parameters control the relative impact of a particle's personal best solution, the best solution in the swarm, and the particle's own previous velocity on it's subsequent movement in solution space. There a variety of methods for determining the value of the inertial weights during optimization, including the strategy of decreasing the weight linearly as a function of iteration, \\textbf{Cite Shi and Ebehart Emprical Study}. However, Shi et al. found that selecting values of inertial weight that satisfies $0.9 \\leq w \\leq 1.2$ tends to enhance the ability of PSO to converge globally \\textbf{Cite Shi and Ebehart Modified PSO}. Additionally, it was found that choosing values of $c_1 \\textrm{ and } c_2$ to satisfy $0 \\leq c_1, c_2 \\leq 2.0$ allows for the PSO performance. The values of these hyper-parameters are summarized in Table \\ref{pso_hyperparam_vals}. \n\n\\begin{breakablealgorithm}\n\\caption{PSO}\\label{pso_algorithm}\n\\begin{algorithmic}[1]\n\\State Define $n_{max}$ \\Comment{Maximum iterations of NP-PSO}\n\\State Define $n_{samples}$ \\Comment{Maximum iterations of sampling particles}\n\\State Initialize $tol$  \\Comment{Minimum change in best solution}\n\\EndProcedure\n\n\\Procedure{Initialize Particle Positions and Velocities}{}\n\\State Define maximum and minimum allowed velocities and positions, $\\mathbf{v}_{max}$, $\\mathbf{v}_{min}$, $\\mathbf{x}_{max}$ and $\\mathbf{x}_{min}$\n\\State Randomly initialize solutions, $\\mathbf{x}_i \\quad i=1...m$ in the domain bounded by $\\mathbf{x}_{max}$ and $\\mathbf{x}_{min}$\n\\State Randomly initialize velocities, $\\mathbf{v}_i \\quad i=1...m$ to zero or in the domain bounded by $\\mathbf{v}_{max}$ and $\\mathbf{v}_{min}$\n\\EndProcedure\n\n\\Procedure{Initialize Best Particles}{}\n\\State $\\mathbf{x}_{Best} \\leftarrow \\underset{\\mathbf{x}_i}{\\textrm{min}}(y(\\mathbf{x}_1)...y(\\mathby{x}_m))$\n\\For{$\\mathbf{x}_i$ in $[\\mathbf{x}_1,....\\mathbf{x}_m]$}\n    \\State $x_{i,Best} \\leftarrow \\mathbf{x}_i$\n\\EndFor\n\\EndProcedure\n\n\\Procedure{Run PSO}{}\n\\State $k \\leftarrow 0$\n\\While{$k<=n_{max} \\text{ or } f_{Best}>tol$}\n    \\State Update each particle velocity using \\ref{pso_vel}\n    \\If {$v_{i,j}(k+1) > \\mathbf{v}_{max}_{i,j}$ or $v_{i,j}(k+1) < \\mathbf{v}_{min}_{i,j}$}\n    \\State $v(k+1)_{i,j} = \\textrm{max}(\\textrm{min}(v(k+1)_{i,j},\\mathbf{v}_{max}_{i,j}),\\mathbf{v}_{min}_{i,j})$\n    \\EndIf\n    \\State Update each particle position using \\ref{pso_pos}\n    \\If {$x_{i,j}(k+1) > \\mathbf{x}_{max}_{i,j}$ or $x_{i,j}(k+1) < \\mathbf{x}_{min}_{i,j}$}\n    \\State Randomly reinitialize particle $i$ in the domain bounded by \n    \\EndIf\n    \\For{$\\mathbf{x}_i$ in $[\\mathbf{x}_1,....\\mathbf{x}_m]$}\n        \\If {$y(\\mathbf{x}_i) < y_{i,Best}$ }\n            \\State $\\mathbf{x}_{i,Best} = \\mathbf{x}_i$\n        \\EndIf\n        \\If {$y(\\mathbf{x}_i) < y_{Best}$ }\n            \\State $\\mathbf{x}_{Best} = \\mathbf{x}_i$\n        \\EndIf\n    \\EndFor\n    $k \\leftarrow k+1$\n\\EndWhile\n\\EndProcedure\n\\end{algorithmic}\n\\end{breakablealgorithm}\n\nThe initial PSO algorithm was promising, and has found applications ranging from tuning the hyper-parameters of neural networks, \\textbf{DNN PSO Paper}, to estimating the value of circuit elements in PV Cells, \\textbf{Cite PV Cells Paper}. Despite the promise of PSO, it has multiple issues. The first is that it is prone to premature convergence to local minima, and the second is that the dynamics of some particles tend toward instability \\textbf{PSO Thesis}. More specifically, their velocities can grow exponentially, causing these particles to quickly move away from their defined solution domain. Multiple variants of PSO have been proposed to address these issues. In this work, we focus on the constricted PSO \\textbf{Constriction PSO Paper}, and the Nonparametric PSO (NPSO) \\textbf{NPSO Paper}.\n\n\\begin{table}[!htb]\n\\begin{center}\n{\\begin{tabular}{|c|c|}\n\t\\hline\n\t\\textbf{PSO Hyper-parameters} & \\textbf{Recommended Range of Values} \\\\\n    \\hline\n    $w$ & $0.9 \\leq w \\leq 1.2$ \\\\\n    \\hline\n    $c_1$  & $0 \\leq c_1 \\leq 2.0$ \\\\\n    \\hline\n    $c_2$  & $0 \\leq c_2 \\leq 2.0$ \\\\\n    \\hline  \n\\end{tabular}}\n\\caption{Typical range of Hyper-parameters of the PSO algorithm found in literature}\\label{pso_hyperparam_vals}\n\\end{center}\n\\end{table}\n\n\n\\subsection{Stochastic Optimization: Nonparametric Particle Swarm Optimization and Constricted PSO}\nIn this subsection we review the constricted PSO, and the NPSO optimization algorithms mentioned above. The constricted PSO was derived through Clerc et al.'s study of the stability of the PSO algorithm, \\textbf{Cite Clerc et al}, assuming a function with a scalar solution, $x^*$. Before summarizing the work of Clerc et al, we introduce a few key expressions. The first is a combination of $x$ and $x_{Best}$,\n\\begin{equation} \\label{combined_point}\n    p = \\frac{\\phi_1 x + \\phi_2 x_{Best}}{\\phi} \\quad \\phi = \\phi_1 + \\phi_2\n\\end{equation}\nwhere $\\phi_1 = r_1 c_1$ and $\\phi_2 = r_2 c_2$, which are both random quantities. However, for the purpose of the stability analysis, $\\phi_1$ and $\\phi_2$ are taken to be fixed quantities. Using this, Clerc et al. wrote a system of equations for the trajectories of the PSO particle as \\textbf{Cite PSO Thesis}\n\n\\begin{equation} \\label{continous_pso_states_clerc}\n    \\begin{aligned}\n        v(k+1) &= v(k) + \\phi (p-x(k)) \\\\\n        x(k+1) &= x(k) + v(k+1) \n    \\end{aligned}\n\\end{equation}\n\nThis system is subsequently transformed to a discrete time dynamic system, \n\\begin{equation} \\label{discrete_pso_states_clerc}\n   \\begin{aligned}\n    v_{k+1} &= v_k + \\phi z_k  \\\\\n    z_{k+1} &= -v_{k} + (1-\\phi)z_{k} \n    \\end{aligned} \n\\end{equation}\nwhere $z_k = p - x_k$. Clerc et al. were able to show that the behavior of this system is governed by two eigenvalues, $\\lambda_1$ and $\\lambda_2$, where the system is guaranteed to converge when $max(|\\lambda_1|,|\\lambda_2|) < 1$. Clerc et al. wanted to be able to explicitly control this rate of convergence, so they further transformed the system into one in which the eigenvalues can be written as $\\lambda_1' = \\chi_1 \\lambda_1$ and $\\lambda_2' = \\chi_2 \\lambda_2$ with tune-able\ncoefficients, $\\beta, \\gamma, \\delta, \\eta, \\textrm{ and } \\alpha$.\n\\begin{equation} \\label{discrete_controllable_pso_states_clerc}\n   \\begin{aligned}\n    v_{k+1} &= \\alpha v_k + \\beta \\phi z_k  \\\\\n    z_{k+1} &= -\\gamma v_{k} + (\\delta- \\eta \\phi)z_{k} \n    \\end{aligned} \n\\end{equation}\nDifferent choices of the above control parameters result in the system defined by \\ref{discrete_controllable_pso_states_clerc} converging. Clerc et al. generalized the results of analyzing this system to the original Particle Swarm Optimization equations, \\ref{pso_vel} and \\ref{pso_pos}, in order to obtain a constricted velocity update equation,\n\\begin{equation} \\label{pso_vel_constrict}\n    \\begin{aligned}\n    v_{i,j}(k+1) &= \\chi (v_{i,j}(k) + c_1 r_{1,j}((\\mathbf{x}_{i,Best}(k))_j - x_{i,j}(k)) + c_2 r_{2,j} ((\\mathbf{x}_{Best}(k))_{i,j} - x_{i,j}(k))), \\\\ \n    &i=1,...,m \\quad j=1,...,n\n    \\end{aligned}\n\\end{equation}\n\nwhere $\\chi$ satisfies\n\\begin{equation}\n    \\chi = \\frac{2}{|2 - \\psi \\sqrt{\\psi^2 - 4\\psi}|}, \\quad \\psi = c_1 + c_2\n\\end{equation}\nand $c_1=c_2=4.05$. With this update equation, it is no longer necessary to bound the maximum and minimum velocity as in the original PSO algorithm, \\ref{pso_algorithm}. Thus, the constriction PSO is simply algorithm  algorithm \\ref{pso_algorithm}, where the velocity update equation is now governed by \\ref{pso_vel_constrict}, and there is no need to bound particle velocities. Additionally, Clerc et al. performed a variety of experiments on test functions which showed that the constricted PSO alleviated the issues of premature convergence. \n\nDespite this improvement, constricted PSO still has some issues with convergence. Moreover, like many PSO algorithms in literature, its dynamics are governed by a host of parameters that the user most choose, or tune. In order to address these issues, Beheshti et al. proposed a variant of PSO called the Nonparametric Particle Swarm Optimization (NP-PSO). \\textbf{Cite NP-PSO Paper} The NP-PSO proposes three main changes. First, the standard PSO velocity update, \\ref{pso_vel}, is changed to\n\\begin{equation} \\label{pso_vel_nppso}\n    \\begin{aligned}\n    v_{i,j}(k+1) &= v_{i,j}(k) + r_{1,j}((\\mathbf{x}_{i,Best}(k))_j - x_{i,j}(k)) + r_{2,j} ((\\mathbf{x}_{i,lBest}(k))_{i,j} - x_{i,j}(k)). \\\\ \n    &i=1,...,m \\quad j=1,...,n\n    \\end{aligned}\n\\end{equation}\nRecalling that $\\mathbf{x}_{i,Best}$ is the best solution that particle $i$ has seen in it's history, and defining a neighborhood of size $2l$ of these as $({x}_{i-l,Best},...{x}_{i-1,Best},{x}_{i,Best},{x}_{i+1,Best},...{x}_{i-l,Best})$, $\\mathbf{x}_{i,lBest}$ is the best of these particles. Additionally, the update equation, \\ref{pso_vel_nppso}, removes the tuneable parameters $w$, $c_1$, and $c_2$. \nSecond, the standard PSO position update, \\ref{pso_pos}, becomes\n\\begin{equation} \\label{pso_pos_nppso}\n    x_{i,j}(k+1) = x_{i,j}(k) + \\mathbf{x}_{i,j}(k) + r_3 ((\\mathbf{x}_{Best}(k))_{i,j} - x_{i,j}(k))\n\\end{equation}\nwhere $r_3$ is uniformly distributed similarly to $r_1$ and $r_2$. This incorporates knowledge of the best solution found by the entire particle swarm into a particle's motion in solution space. Finally, the global best particle, $x_{Best}$, is updated differently at each iteration. The process of updating $\\mathbf{x}_{Best}$ starts by randomly selecting two particles in the swarm, $(\\mathbf{x}_J \\textrm{ and } \\mathbf{x}_K$, where we require that $\\mathbf{x}_J \\neq \\mathbf{x}_K \\neq \\mathbf{x}_{Best}$. Two new particles, $\\mathbf{x}_1'$ and $\\mathbf{x}_2'\n$, are introduced to the system using the following quadratic interpolations,\n\\begin{align} \\label{nppso_interpolations}\n    \\mathbf{x}_1' &= \\frac{1}{2} \\frac{(\\mathbf{x}_J^2 - \\mathbf{x}_{Best}^2 - \\mathbf{x}_K^2) \\times y(\\mathbf{x}_J) \\times y(\\mathbf{x}_K)}{(\\mathbf{x}_J - \\mathbf{x}_K) \\times y(\\mathbf{x}_{Best}) + (\\mathbf{x}_K - \\mathbf{x}_{Best}) \\times y(\\mathbf{x}_J) + (\\mathbf{x}_{Best} - \\mathbf{x}_J) \\times y(\\mathbf{x}_K)} \\label{nppso_interp_1}\\\\ \\nonumber\\\\\n    \\mathbf{x}_2' &= \\frac{1}{2} \\frac{(\\mathbf{x}_J^2 - \\mathbf{x}_K^2) \\times y(\\mathbf{x}_{Best}) + (\\mathbf{x}_K^2 - \\mathbf{x}_{Best}^2) \\times y(\\mathbf{x}_J) + (\\mathbf{x}_{Best}^2 - \\mathfb{x}_J^2) \\times y(\\mathbf{x}_K)}{(\\mathbf{x}_J - \\mathbf{x}_K) \\times y(\\mathbf{x}_{Best}) + (\\mathbf{x}_K - \\mathbf{x}_{Best}) \\times y(\\mathbf{x}_J) + (\\mathbf{x}_{Best} - \\mathbf{x}_J) \\times y(\\mathbf{x}_K)}  \\label{nppso_interp_2}\n\\end{align}\nThese interpolations artificially expand the amount of solution space that our particle swarm is able to explore. We note that we have overloaded notation in equations \\ref{nppso_interp_1} and \\ref{nppso_interp_2}, and that the interpolation is performed separately on each element of the vectors. Subsequently, $\\mathbf{x}_{Best}$ is first compared to $\\mathbf{x}_1'$, and, if $\\mathbf{x}_1'$ is more fit than $\\mathbf{x}_{Best}$, $\\mathbf{x}_{Best}$ is assigned to be $\\mathbf{x}_1'$. The full NP-PSO algorithm is sketched out in \\ref{nppso_algorithm}. We make an important point of clarification, during the step in which we sample new particles, $\\mathbf{x}_J$ and $\\mathbf{x}_K$. In order to meet the condition that $\\mathbf{x}_J \\neq \\mathbf{x}_K \\neq \\mathbf{x}_{Best}$, we require that no elements of the vectors are equal. If it is the case that they are, we re-sample $\\mathbf{x}_J$ and $\\mathbf{x}_K$ for a maximum of $n_{samples}$ iterations. Behesti et al. tested NP-PSO on nineteen unimodal and  multimodal, and found that it outperformed PSO, constricted PSO, and four other popular variants of PSO in almost every scenario. \n\n\\begin{breakablealgorithm}\n\\caption{NP-PSO}\n\\label{nppso_algorithm}\n\\begin{algorithmic}[1]\n\\Procedure{Initialize Stopping Criterion}{}\n\\State Define $n_{max}$ \\Comment{Maximum iterations of NP-PSO}\n\\State Define $n_{samples}$ \\Comment{Maximum iterations of sampling particles}\n\\State Initialize $tol$  \\Comment{Minimum change in best solution}\n\\EndProcedure\n\n\\Procedure{Initialize Particle Position and Velocities}{}\n\\State Define maximum and minimum allowed velocities and positions, $\\mathbf{v}_{max}$, $\\mathbf{v}_{min}$, $\\mathbf{x}_{max}$ and $\\mathbf{x}_{min}$\n\\State Randomly initialize velocities, $\\mathbf{v}_i \\quad i=1...m$ to zero or in the domain bounded by $\\mathbf{v}_{max}$ and $\\mathbf{v}_{min}$\n\\State Randomly initialize solutions, $\\mathbf{x}_i \\quad i=1...m$ in the domain bounded by $\\mathbf{x}_{max}$ and $\\mathbf{x}_{min}$\n\\EndProcedure\n\n\\Procedure{Initialize Best particles}{}\n\\State Define neighborhood size, $l$\n\\State $\\mathbf{x}_{Best} \\leftarrow \\underset{\\mathbf{x}_i}{\\textrm{min}}(y(\\mathbf{x}_1)...y(\\mathbf{x}_m))$\n\\State $x_{i,Best} \\leftarrow \\mathbf{x}_i \\quad i=1,..m$\n\\State $\\mathbf{x}_{i,lBest} \\leftarrow \\underset{\\mathbf{x}}{\\textrm{min}}(y(\\mathbf{x}_{i-l,Best}),...,y(\\mathbf{x}_{i-1,Best}),y(\\mathbf{x}_{i,Best}),y(\\mathbf{x}_{i+1,Best}))  \\quad i=1,..m$\n\\EndProcedure\n\n\\Procedure{Run NP-PSO}{}\n\\State $k \\leftarrow 0$\n\\While{$k<=n_{max} \\text{ or } f_{Best}>tol$}\n    \\For {$\\mathbf{x}_i$ in $[\\mathbf{x}_1,....\\mathbf{x}_m]$}\n        \\State Update each particle velocity using \\ref{pso_vel_nppso}\n        \\If {$v_{i,j}(k+1) > \\mathbf{v}_{max}_{i,j}$ or $v_{i,j}(k+1) < \\mathbf{v}_{min}_{i,j}$}\n        \\State $v(k+1)_{i,j} = \\textrm{max}(\\textrm{min}(v(k+1)_{i,j},\\mathbf{v}_{max}_{i,j}),\\mathbf{v}_{min}_{i,j})$\n        \\EndIf\n        \\State Update each particle position using \\ref{pso_nppso}\n        \\If {$x_{i,j}(k+1) > \\mathbf{x}_{max}_{i,j}$ or $x_{i,j}(k+1) < \\mathbf{x}_{min}_{i,j}$}\n        \\State Randomly reinitialize particle $i$ in the domain bounded by \n        \\EndIf\n        \\If {$y(\\mathbf{x}_i) < y_{i,Best}$ }\n            \\State $\\mathbf{x}_{i,Best} = \\mathbf{x}_i$\n        \\State $j \\leftarrow 0$\n        \\State Randomly select particles $\\mathbf{x}_J$ and $\\mathbf{x}_K$ from the swarm\n        \\While{$j < n_{sample}_{max}$ and ($\\mathbf{x}_J == \\mathbf{x}_K$ or $\\mathbf{x}_J == \\mathbf{x}_{Best}$ or $\\mathbf{x}_{Best} == \\mathbf{x}_K$)}\n            \\State Randomly sample particles $\\mathbf{x}_J$ and $\\mathbf{x}_K$ from the swarm\n            \\State $j \\leftarrow j+1$\n        \\EndWhile\n        \\If {$j < n_{samples}$}\n            \\State Calculate $\\mathbf{x}_1'$ using \\label{nppso_interp_1}\n            \\If {$y(\\mathbf{x}_1') < y_{Best}$ }\n                \\State $\\mathbf{x}_{Best} = \\mathbf{x}_1'$\n            \\EndIf \n            \\State Calculate $\\mathbf{x}_2'$ using \\label{nppso_interp_2}\n            \\If {$y(\\mathbf{x}_2') < y_{Best}$ }\n                \\State $\\mathbf{x}_{Best} = \\mathbf{x}_2'$\n            \\EndIf \n        \\EndIf\n        \\If {$y(\\mathbf{x}_i) < y_{Best}$ }\n            \\State $\\mathbf{x}_{Best} = \\mathbf{x}_i$\n        \\EndIf \n    \\EndFor\n    $k \\leftarrow k+1$\n\\EndWhile\n\\EndProcedure\n\\end{algorithmic}\n\\end{breakablealgorithm}\n\n\\section{Hybrid Algorithms and Challenges to Optimization}\nWe have reviewed gradient based and stochastic optimization algorithms. We have seen that, while gradient methods are very accurate when they are initialized in the vicinity of global optima, they are very prone to local minima. Additionally, the computation of a numerical gradient can be very expensive. Stochastic algorithms were subsequently developed in order to remove the necessity of computing gradients during the process of optimization, and to allow for a more thorough exploration of solution space, so that there is a higher probability of finding the global optimum. While stochastic algorithms have a better chance of converging to the region of a global optima, they can require a large amount of extraneous function evaluations. Moreover, they can result in final values that are at least slightly sub-optimal, even in the vicinity of some global optimum. \n\nIn order to address some of these issues, a variety of researchers have proposed hybrid algorithms that combine Particle Swarm Optimization and gradient based methods. Recently, Han et al. and Salajegheh et al. proposed DGPSOGS and PSOG respectively, both of which are variants of PSO that use local gradient and hessian information in it's update equations, \\textbf{CITE DGPSOGS and PSOG Papers}. Additionally, Chen et al. and Plevris et al. proposed hybrid algorithms that used standard PSO, algorithm \\ref{pso_algorithm}, to initially explore the solution space. \\textbf{Cite HybridPSOSQR and HybridPSOConjugate} The best solution from PSO is then used to initialize gradient methods that fine tune the optimization. All of the above hybrid methods were found to be more effective than PSO alone.\n\n\\section{Quantifying Uncertainty in Parameter Estimates}\nWe have, to this point, formulated parameter estimation of models as a nonlinear optimization problem, reviewed multiple approaches for optimization, and presented our algorithm for performing parameter estimation. An essential part of parameter estimation is quantifying the extent to which we trust the values obtained by our parameters. Two popular methods of quantifying this uncertainty are confidence intervals, and confidence regions.\n\nConfidence intervals define the possible bounds on individual estimated parameters using equation \n\n\\begin{equation} \\label{norm_conf_interval}\n    x_i \\pm t_{n-p}^{1-\\frac{\\alpha}{2}}(s^2 c_{ii})^{\\frac{1}{2}}\n\\end{equation}\n\nwhere $n$ is the total number of data points, $p$ is the number of parameters being estimated, $t_{n-p}^{1-\\frac{\\alpha}{2}}$ is a t-score with $n-p$ degrees of freedom at a confidence level of $1-\\alpha$, $c_{ii}$ is the variance of parameter $x_i$ which corresponds to the diagonal of parameter covariance matrix $\\mathbf{C}_\\mathbf{x}$, and $s = \\sqrt{\\frac{y(\\mathbf{x}_{Best})}{n-p}}$. \n\nConfidence regions differ, because they define joint confidence in all of the parameters simultaneously. A common approach for defining the confidence region is as a hyper-ellipse that satisfies\n\n\\begin{equation} \\label{norm_conf_region}\n    (\\mathbf{x}-\\mathbf{x}_{Best})^T \\mathbf{C}_\\mathbf{x}^{-1}(\\mathbf{x}-\\mathbf{x}_{Best}) \\leq \\frac{p}{n-p} y(\\mathbf{x}_{Best})F_{p,n-p}^{1-\\alpha}\n\\end{equation}\n\nwhere $F_{p,n-p}^{1-\\alpha}$ is the F statistic with $p$ and $n-p$ degrees of freedom, at a confidence of $1-\\alpha$. The definition of confidence intervals and confidence regions given by equations \\ref{norm_conf_interval} and \\ref{norm_conf_region}, both assume that the parameters and experiments follow a normal distribution. While this is a valid assumption for models that are linear in estimated parameters, this is generally not valid for nonlinear models, even if the experiments are normally distributed. In order to address this issue, Beale et al. proposed the following approximation for confidence regions of nonlinear models. \\textbf{Cite Beale Paper}\n\n\\begin{equation} \\label{nonlin_confidence_regions}\n    y(\\mathbf{x}) \\leq y(\\mathbf{x}_{Best})\\bigg(1 + \\frac{p}{n-p}F_{p,n-p}^{1-\\alpha}\\bigg)\n\\end{equation}\n\nThe above approximation gives an exact result for linear models, assuming that experiments are normally distributed. More generally, equation \\ref{nonlin_confidence_regions} can be written as $ y(\\mathbf{x}) \\leq cy(\\mathbf{x}_{Best})$, where $c$ is determined based on the distribution of parameters and experiments. However, it is difficult to determine the distribution of parameters and experiments. Instead, the assumption of normality in experimental errors is made in order to define $c$ as $c=\\bigg(1 + \\frac{p}{n-p}F_{p,n-p}^{1-\\alpha}\\bigg)$. A big advantage of equation \\ref{nonlin_confidence_regions} is that it does not require the confidence regions to be ellipsoids, so it allows for more accurate approximations of confidence regions in the case of nonlinear models. Despite this advantage, equation \\ref{nonlin_confidence_regions} is expensive, since it requires a large amount of objective function evaluations in order to form a reasonable confidence region. \n\nSchwaab et al. addressed this issue using Particle Swarm Optimization (PSO). \\textbf{cite Schwaab nonlinear}. The number of function evaluations necessary for PSO algorithms are usually viewed as a downside. However, Schwaab et al. presented work in which they used these function evaluations to construct confidence intervals. Specifically, Schwaab et al. kept track of every function evaluation done during the process of PSO, and all the parameter values that satisfy equation \\ref{nonlin_confidence_regions} are used to construct the confidence region. In their work, Schwaab et al. demonstrated the ability of this method  to create non-ellipsoid confidence regions for a variety of nonlinear models. \\textbf{cite Schwaab nonlinear} In order to do so, it was necessary for them to run PSO for an extended number of iterations, and to make sure to use enough particles to thoroughly explore the solution space. \\textbf{cite Schwaab nonlinear} One thing worth noting is that, using the above method, it is straight forward to create confidence regions of combinations of relevant parameters. This will allow us to find the confidence regions of physical constants. We will use this technique described here to not only quantify uncertainty in our parameter estimates, but to perform physical model selection and experimental design. \n\n\\section{x-PSO-TRF-y: Parameter Estimation, Model Selection, and Experimental Design}\nUp until this point we have reviewed a variety of methods for optimization, with a strong emphasis on PSO based methods. We also discussed a method for estimating the confidence in our optimal  We propose two hybrid algorithms, collectively called x-PSO-TRF-y, that make use of multiple variants of Particle Swarm Optimization (PSO), and can use information from all the particles in the gradient step. The x satisfies $\\textrm{x} \\in [\\varnothing,\\textrm{constrict},\\textrm{NP}]$, and the y satisfies $\\textrm{y} \\in [1,2]$. In the scenario when y is 1, the relevant variant of PSO is run for some number of trials, and the best solution from each trial is used to initialize the TRF algorithm. When y is 2, rather than using the best solution of each swarm in each trial to initialize TRF, we run TRF using the best solution each particle has seen in it's history as an initial guess. We generally run these algorithms for a user defined number of trials, $n_{Trials}$. Every function evaluation run during the PSO phase of our  algorithm is stored, as are the final results of the TRF algorithm. Two separate confidence regions are then formed. One is formed using only the function evaluations stored during the PSO phase of our algorithms, and the other using both the function evaluations from PSO, and the results of the TRF. The outputs of this algorithm, which will be used in physical model selection and experimental design, is represented in the following plots: \n\n\\begin{enumerate}\n    \\item Plot of data, and model output from most optimal parameter\n    \\item Plot of data, and model outputs from all parameters in each confidence region\n    \\item Histogram of fitness of particles in each confidence region\n    \\item Plot of confidence regions of every pair of parameters\n    \\item Plot of confidence regions of physical constants of system that are constructed by combining the parameters\n\\end{enumerate}\n\nIn order to use this algorithm for physical model selection, and experimental design, we run the described algorithm for the reduced models under consideration, and at different numbers of experiments and data points within the experiments. The full procedure is given by algorithm \\ref{xPSOTRFy_algorithm}. \n\n\\begin{breakablealgorithm}\n\\caption{x-PSO-TRF-y}\n\\label{xPSOTRFy_algorithm} \n\\begin{algorithmic}[1]\n\\Procedure{Initialize Experimental Conditions and confidence}{}\n\\State Define $n_{Experiments}$ \\Comment{Define number of experiments run for physical system}\n\\State Define $n_y$  \\Comment{Define number of measurements collected in each experiment}\n\\State Define confidence level, $1-\\alpha$\n\\EndProcedure\n\n\\Procedure{Initialize Algorithm and Number of Trials}{}\n\\State Define $n_{Trials}$ \\Comment{Define number of times PSO will be run}\n\\State Select variant of x-PSO, x,$\\textrm{x} \\in [\\varnothing,\\textrm{constrict},\\textrm{NP}]$ \n\\EndProcedure\n\n\\For{k=1:$\\textrm{n}_{\\textrm{Trials}}$}\n\\State Run x-PSO, and store all function evaluations, and the corresponding parameters\n\\State Define the confidence regions for only PSO as all the parameters,$\\mathbf{x}$, seen during x-PSO that satisfies equation \\ref{nonlin_confidence_regions}\n\\If{y=1}\n\\State Extract best solution from x-PSO, $\\mathbf{x}_{Best}$.\n\\State Initialize guess for TRF as $\\mathbf{x}_{Best}$, and run TRF\n\\State $\\mathbf{x}_{Best} \\leftarrow \\underset{\\mathbf{x}}{min}[y(\\mathbf{x}_{Best}),y(\\mathbf{x}_{Best-TRF})]$\n\\EndIf\n\\If{y=2}\n\\State Extract best solutions of each particle $\\mathbf{x}_{i,Best}$ \n\\For{$\\mathbf{x}_{i,Best}$ in [$\\mathbf{x}_{1,Best}$,...,$\\mathbf{x}_{m,Best}$ ]}\n\\State Initialize guess for TRF as $\\mathbf{x}_{i,Best}$, and run algorithm\n\\State Store Solution\n\\EndFor\n\\State $\\mathbf{x}_{Best} \\leftarrow \\underset{\\mathbf{x}}{min}[y(\\mathbf{x}_{1,Best}),y(\\mathbf{x}_{1,Best-TRF}),...,y(\\mathbf{x}_{m,Best}),y(\\mathbf{x}_{m,Best-TRF})]$\n\\EndIf\n\\State Define new confidence regions that satisfies equation \\ref{nonlin_confidence_regions}\n\\EndFor\n\\end{algorithmic}\n\\end{breakablealgorithm}\n\n\\section{Selecting the Reduced Comb-Drive Model of Best Fit}\nIn this section, we analyze how well each of our reduced comb-drive models fits all the data, and select the simplest model that best explains the data. We do so, for the set of experiments described at the end of chapter 2. Briefly, we measure the displacement of the comb-drive actuator at concentrations of 0.1 $mM$, 0.5 $mM$, 1 $mM$, and 10 $mM$ KCl for two types of comb-drive actuators. One comb-drive actuator has 200 pairs of fingers with gaps of 2 $\\mu m$, and one with 100 pairs of fingers wit gaps of 5 $\\mu m$. These are done at 2 signals with magnitudes of 2 $V_{p-p}$.\n\n\n\n\n", "meta": {"hexsha": "1b5a312cbba4f1720636e60cdeaeec3da0b16d0b", "size": 37942, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapter4/chapter4.tex", "max_stars_repo_name": "odibua/thesisnstuff", "max_stars_repo_head_hexsha": "86322a040cb27d6af5c8dfbbb636ef380a468ed4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter4/chapter4.tex", "max_issues_repo_name": "odibua/thesisnstuff", "max_issues_repo_head_hexsha": "86322a040cb27d6af5c8dfbbb636ef380a468ed4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter4/chapter4.tex", "max_forks_repo_name": "odibua/thesisnstuff", "max_forks_repo_head_hexsha": "86322a040cb27d6af5c8dfbbb636ef380a468ed4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 104.523415978, "max_line_length": 2087, "alphanum_fraction": 0.736097201, "num_tokens": 10332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.327520252369819}}
{"text": "\n\\typeout{}\\typeout{If latex fails to find aiaa-tc, read the README file!}\n%\n\n\n\\documentclass[]{aiaa-tc}% insert '[draft]' option to show overfull boxes\n\n\n\\usepackage{amsmath}          % for formula writing (i.e. 'split', etc)\n\\usepackage{rotate}           %rotate/mirror images\n\\usepackage{cancel}           %draw lines through math to show \"goes to zero\"\n\\usepackage{xfrac}            %allows slated and side fractions\n\\usepackage{subcaption}       %allows captioning individual subfigures\n\\usepackage{multicol}         %enable environment with multiple columns\n\\usepackage[mode=buildnew]{standalone}% requires -shell-escape\n  % compile with `pdflatex -shell-escape main` or `xelatex  -shell-escape main`\n\n\n\\usepackage{tikz}             %for creating vector graphics diagrams\n\\usetikzlibrary{backgrounds}  %put backgrounds behind tikz figures\n\\usetikzlibrary{calc}         %perform calculations within $$\n\\usetikzlibrary{positioning}  %position tikz elements using \"right of, etc\"\n\\usetikzlibrary{angles}       %label angles between lines with arcs\n\\usetikzlibrary{quotes}       %Put angle label in quotes\n\\usetikzlibrary{patterns}     %Patterns to fill shapes with\n\n\n\n\n\n\n  \\title{MAE 298 Aeroacoustics -- Homework \\#2 \\\\ Lilley's Equation Solution and Application to Jet Noise}\n\n\\author{\n  Logan D. Halstrom \\\\\n  {\\normalsize\\itshape Graduate Student} \\\\\n  {\\normalsize\\itshape Department of Mechanical and Aerospace Engineering} \\\\\n  {\\normalsize\\itshape University of California, Davis, CA 95616}\n       }\n\n\n % Define commands to assure consistent treatment throughout document\n \\newcommand{\\eqnref}[1]{(\\ref{#1})}\n \\newcommand{\\class}[1]{\\texttt{#1}}\n \\newcommand{\\package}[1]{\\texttt{#1}}\n \\newcommand{\\file}[1]{\\texttt{#1}}\n \\newcommand{\\BibTeX}{\\textsc{Bib}\\TeX}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{document}\n\n\\maketitle\n\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% \\begin{abstract}\n\n% Abstract about homework\n\n% \\end{abstract}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section*{Nomenclature}\n\n\\begin{multicols}{2}\n\n\\begin{tabbing}\n  XXX \\= \\kill% this line sets tab stop\n  $\\infty$            \\> Ambient flow parameter subscript \\\\\n  $j$                 \\> Jet exit flow parameter subscript \\\\\n  $r$                 \\> Radial location in flow \\\\\n  $R_j$               \\> Axisymmetric jet radius \\\\\n  $\\theta$            \\> Angular location in flow \\\\\n  $z$                 \\> Axial location in flow \\\\\n  $M$                 \\> Mach number \\\\\n  $W(r)$              \\> Radial distribution of mean axial velocity \\\\\n  $\\overline{a^2}(r)$ \\> Radial distribution of speed of sound squared\\\\\n  $\\overline{\\rho}$   \\> Mean density \\\\\n  $\\gamma$            \\> Specific heat ratio \\\\\n  $\\overline{p}$      \\> Mean pressure \\\\\n  $p'$                \\> Perturbation pressure \\\\\n  $P(r)$              \\> Pressure profile in radial direction  \\\\\n  $k$                 \\> Wavenumber \\\\\n  $\\omega$            \\> Wave oscillating frequency \\\\\n  $n$                 \\> Characteristic integer \\\\\n  $i$                 \\> Imaginary number $\\sqrt{-1}$ \\\\\n  $\\exp$              \\> Exponential ($e$) \\\\\n  $E$                 \\> Exponential term: $kz + n\\theta -\\omega t$ \\\\\n  $\\lambda$           \\> Constant term in Bessel equation \\\\\n  $J$                 \\> First-order Bessel function \\\\\n  $Y$                 \\> Second-order Bessel function \\\\\n  $H^{(n)}$           \\> nth-order Hankel function \\\\\n  $x$                 \\> Placeholder variable for $\\lambda r$ \\\\\n  $A,B$               \\> Arbitrary Bessel function constants \\\\\n  $C,D$               \\> Arbitrary Hankel constants \\\\\n  $\\vec{V}$           \\> General velocity vector \\\\\n  $V_r$               \\> Velocity component in radial direction \\\\\n  $\\nu$               \\> Constant velocity parameter \\\\\n  $\\chi$              \\> Constant position parameter \\\\\n  $\\zeta$             \\> Position of vortex sheet dividing inner/outer solution \\\\\n  $+/-$               \\> Outer/Inner solution, respectively \\\\\n\n\n\n\n\\end{tabbing}\n\n\\end{multicols}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Background} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nThe following analysis will derive solutions to Lilley's equation for parallel axisymmetric flow (Eqn~\\ref{Lilley}):\n\n\\begin{equation} \\label{Lilley}\n\\left( \\dfrac{\\partial}{\\partial t} + W \\dfrac{\\partial}{\\partial z} \\right)^3 p'\n- \\left( \\dfrac{\\partial}{\\partial t} + W \\dfrac{\\partial}{\\partial z} \\right) \\left( \\overline{a^2} \\nabla^2p' \\right)\n- \\dfrac{d \\overline{a^2}}{dr} \\left( \\dfrac{\\partial}{\\partial t} + W \\dfrac{\\partial}{\\partial z} \\right) \\dfrac{dp'}{dr}\n+ 2\\overline{a^2} \\dfrac{dW}{dr}\\dfrac{\\partial^2 p'}{\\partial z \\partial r}\n= S(\\vec{x}, t)\n\\end{equation}\n\n\\begin{center}\nwhere $\\nabla^2 \\equiv \\dfrac{1}{r}\\dfrac{\\partial}{\\partial r} \\left( r\\dfrac{\\partial}{\\partial r} \\right)\n+ \\dfrac{1}{r^2}\\dfrac{\\partial^2}{\\partial \\theta^2}\n+ \\dfrac{\\partial^2}{\\partial z^2}$\n\\end{center}\n\n\n$W(r)$ is the radial distribution of axial velocity and $\\overline{a^2}(r)$ is the radial distribution of speed of sound squared.\n\nAfter a general solution is derived, it will be applied to find homogeneous solutions to the far-field and potential core regions of an axial jet.  Finally, the conditions for matching the solutions for this regions will be discussed.\n\n\n\\clearpage\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Problem 1 -- Solution to Lilley's Equation} \\label{SecLilley}%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nIn this section, we will seek solutions of Lilley's equation in the form:\n\n\\begin{equation} \\label{SolnForm}\np'(r, \\theta, z, t) \\sim P(r) \\exp\\left[ i(kz + n\\theta -\\omega t) \\right]\n\\end{equation}\n\n\\noindent We will assume isentropic flow and constant mean pressure:\n\\begin{enumerate}\n  \\item $\\overline{a^2} = \\dfrac{\\gamma \\overline{p}}{\\overline{\\rho}}$\n  \\item $\\overline{p} = const$\n\\end{enumerate}\n\n\\noindent where $\\overline{\\rho}(r)$ is the radial distribution of the mean density.  With these assumptions, we will show that Lilley's equation reduces to (Eqn~\\ref{LilleySoln}):\n\n\\begin{equation} \\label{LilleySoln}\n\\dfrac{d^2 P}{dr^2}\n+ \\left\\{ \\dfrac{1}{r}\n  - \\dfrac{1}{\\overline{\\rho}} \\dfrac{d\\overline{\\rho}}{dr}\n  + \\dfrac{2k}{(\\omega - kW)} \\dfrac{dW}{dr}\n\\right\\} \\dfrac{dP}{dr}\n+ \\left\\{ \\dfrac{(\\omega - kW)^2}{\\overline{a^2}} - k^2 - \\dfrac{n^2}{r^2}\n\\right\\} P = RHS\n\\end{equation}\n\nTo aid in this derivation, we find the results for the first-order partial derivatives of parameters relevant to the solution.  First, we compute the derivative of the perturbation pressure $p'$ with respect to (WRT) time $t$:\n\n\\newcommand\\expterm{i(kz + n\\theta -\\omega t)}%terms in exponential\n\n\\begin{align*}\n\\dfrac{\\partial p'}{\\partial t} &= \\dfrac{\\partial}{\\partial t}\n  \\left\\{ P(r) \\exp\\left[ \\expterm \\right]\\right\\} \\\\\n&= P \\dfrac{\\partial}{\\partial t} [\\expterm] \\exp[\\expterm] \\\\\n&= iP \\left[\\cancelto{0}{\\dfrac{\\partial}{\\partial t}(kz)      }\n          + \\cancelto{0}{\\dfrac{\\partial}{\\partial t}(n\\theta)}\n                       - \\dfrac{\\partial}{\\partial t}(\\omega t)\n    \\right] \\exp[\\expterm]\n\\end{align*}\n\n\\begin{equation} \\label{dpdt}\n\\boxed{\\dfrac{\\partial p'}{\\partial t}\n  = -iP\\omega \\exp[\\expterm] = -iP\\omega e^{iE} }\n\\end{equation}\n\n\\noindent where $E=kz + n\\theta -\\omega t$, $\\dfrac{\\partial E}{\\partial t} = -\\omega$, and $\\dfrac{\\partial E}{\\partial z} = k$.  Next, we compute the derivative of $p'$ WRT the angular direction $\\theta$:\n\n\\begin{align*}\n\\dfrac{\\partial p'}{\\partial \\theta} &= \\dfrac{\\partial}{\\partial \\theta}\n  \\left\\{ P(r) \\exp\\left[ \\expterm \\right]\\right\\} \\\\\n&= P \\dfrac{\\partial}{\\partial \\theta} [\\expterm] \\exp[\\expterm] \\\\\n&= iP \\left[\\cancelto{0}{\\dfrac{\\partial}{\\partial \\theta}(kz)      }\n                      + \\dfrac{\\partial}{\\partial \\theta}(n\\theta)\n          - \\cancelto{0}{\\dfrac{\\partial}{\\partial \\theta}(\\omega t)}\n    \\right] \\exp[\\expterm]\n\\end{align*}\n\n\\begin{equation} \\label{dpdtheta}\n\\boxed{\\dfrac{\\partial p'}{\\partial \\theta} = iPn \\exp[\\expterm] = iPn e^{iE} }\n\\end{equation}\n\n\nNext, we compute the derivative of $p'$ WRT the axial flow direction $z$:\n\n\n\n\\begin{align*}\n\\dfrac{\\partial p'}{\\partial z} &= \\dfrac{\\partial}{\\partial z}\n  \\left\\{ P(r) \\exp\\left[ \\expterm \\right]\\right\\} \\\\\n&= P \\dfrac{\\partial}{\\partial z} [\\expterm] \\exp[\\expterm] \\\\\n&= iP \\left[             \\dfrac{\\partial}{\\partial z}(kz)\n          + \\cancelto{0}{\\dfrac{\\partial}{\\partial z}(n\\theta)}\n          - \\cancelto{0}{\\dfrac{\\partial}{\\partial z}(\\omega t)}\n    \\right] \\exp[\\expterm]\n\\end{align*}\n\n\\begin{equation} \\label{dpdz}\n\\boxed{\\dfrac{\\partial p'}{\\partial z} = iPk \\exp[\\expterm] = iPk e^{iE} }\n\\end{equation}\n\n\nNext, we compute the derivative of $p'$ WRT the radial direction $r$:\n\n\\begin{align*}\n\\dfrac{\\partial p'}{\\partial r} &= \\dfrac{\\partial}{\\partial r}\n  \\left\\{ P(r) \\exp\\left[ \\expterm \\right]\\right\\}\n\\end{align*}\n\n\\begin{equation} \\label{dpdr}\n\\boxed{\\dfrac{\\partial p'}{\\partial r} = \\dfrac{dP}{dr} \\exp[\\expterm] = \\dfrac{dP}{dr} e^{iE} }\n\\end{equation}\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Term 1}\n\nTo simplify the derivation, we will apply the solution form individually to each term in Lilley's equation.  For the first term, we must apply the multi-derivative operator a total of three times:\n\n% \\begin{equation} \\label{LilleyTerm1}\n% \\left( \\dfrac{\\partial}{\\partial t} + W \\dfrac{\\partial}{\\partial z} \\right)^3 p'\n% \\end{equation}\n\n\n\\begin{align*}\n\\left( \\dfrac{\\partial}{\\partial t} + W \\dfrac{\\partial}{\\partial z} \\right)^3 p'\n&= \\left( \\dfrac{\\partial}{\\partial t} + W \\dfrac{\\partial}{\\partial z}\n   \\right)^2\n   \\left( \\dfrac{\\partial}{\\partial t} + W \\dfrac{\\partial}{\\partial z}\n   \\right)p' \\\\\n&= \\left( \\dfrac{\\partial}{\\partial t} + W \\dfrac{\\partial}{\\partial z}\n   \\right)^2\n   \\left( \\dfrac{\\partial p'}{\\partial t} + W \\dfrac{\\partial p'}{\\partial z}\n   \\right) \\\\\n&= \\left( \\dfrac{\\partial}{\\partial t} + W \\dfrac{\\partial}{\\partial z}\n   \\right)^2\n   \\left( -P\\omega ie^{iE} + PkW ie^{iE}\n   \\right) \\\\\n&= \\left( \\dfrac{\\partial}{\\partial t} + W \\dfrac{\\partial}{\\partial z}\n   \\right)\n   \\left( \\dfrac{\\partial}{\\partial t} + W \\dfrac{\\partial}{\\partial z}\n   \\right) (-\\omega + kW)P i (e^{iE}) \\\\\n&= \\left( \\dfrac{\\partial}{\\partial t} + W \\dfrac{\\partial}{\\partial z}\n   \\right) (-\\omega + kW)P i\n   (-i\\omega e^{iE} + ikW e^{iE}) \\\\\n&= \\left( \\dfrac{\\partial}{\\partial t} + W \\dfrac{\\partial}{\\partial z}\n   \\right) (-\\omega + kW)^2 P i^2 (e^{iE}) \\\\\n&= (-\\omega + kW)^3 P i^3(e^{iE}) = (-\\omega + kW)^3P(-i) (e^{iE}) \\\\\n&= (\\omega - kW)^3iP (e^{iE})\n\\end{align*}\n\nThe cubed imaginary number $i^3$ simplifies to $-i$ and the $-1$ is distributed into the cubed factor.  This results in the final expression for Term 1:\n\n\\begin{equation} \\label{term1soln}\n\\boxed{ \\left( \\dfrac{\\partial}{\\partial t}\n          + W \\dfrac{\\partial}{\\partial z} \\right)^3 p'\n    =  i\\exp[i(kz + n\\theta -\\omega t)] (\\omega - kW)^3 P}\n\\end{equation}\n\n\n\n\n\n\\clearpage\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Term 2}\n\nApplication of the solution form to the second term (Eqn~\\ref{term2}) of Lilley's equation is slightly more involved.\n\n\\begin{equation}\\label{term2}\n\\left( \\dfrac{\\partial}{\\partial t} + W \\dfrac{\\partial}{\\partial z} \\right) (\\overline{a^2}\\nabla^2p')\n\\end{equation}\n\nTerm 2 requires computing the double divergence of perturbation pressure $\\nabla^2 p'$:\n\n\\begin{align*}\n\\nabla^2p'\n  &= \\dfrac{1}{r}\\dfrac{\\partial}{\\partial r} \\left( r\\dfrac{\\partial p'}{\\partial r} \\right)\n      + \\dfrac{1}{r^2} \\dfrac{\\partial^2 p'}{\\partial \\theta^2}\n      + \\dfrac{\\partial^2 p'}{\\partial z^2} \\\\\n&= \\dfrac{1}{r}\\dfrac{\\partial}{\\partial r} \\left( r \\dfrac{dP}{dr} e^{iE} \\right)\n      + \\dfrac{1}{r^2} \\dfrac{\\partial }{\\partial \\theta} \\left( Pn ie^{iE} \\right)\n      + \\dfrac{\\partial}{\\partial z} \\left( Pk ie^{iE} \\right) \\\\\n&= \\dfrac{1}{r} e^{iE} \\left(\n    \\dfrac{dP}{dr} + r \\dfrac{d^2P}{dr^2} \\right)\n      + \\dfrac{1}{r^2} Pn^2 i^2 e^{iE}\n      + Pk^2 i^2  e^{iE} \\\\\n&= e^{iE} \\dfrac{d^2P}{dr^2}\n    + e^{iE} \\dfrac{1}{r} \\dfrac{dP}{dr}\n    + i^2 e^{iE} \\left( \\dfrac{n^2}{r^2} + k^2 \\right) P\n\\end{align*}\n\nThus, the double divergence of $p'$ can be expressed in the following expression, which is separated into like differential terms of $P$:\n\n\\begin{equation} \\label{doubledivp}\n\\boxed{ \\nabla^2p'= \\exp[i(kz + n\\theta -\\omega t)] \\left[\n      \\dfrac{d^2P}{dr^2}\n    + \\dfrac{1}{r} \\dfrac{dP}{dr}\n    - \\left( \\dfrac{n^2}{r^2} + k^2 \\right) P \\right] }\n\\end{equation}\n\nSubstituting Eqn~\\ref{doubledivp} into Term 2 (Eqn~\\ref{term2}), we can perform the multi-derivative expression to derive the final term.  All terms grouped with $P$ along with $a$ are constant WRT $t$ and $z$ and can be carried outside of the derivative expression.\n\n\\begin{align*}\n\\left( \\dfrac{\\partial}{\\partial t}\n  + W \\dfrac{\\partial}{\\partial z} \\right)\n  (\\overline{a^2}\\nabla^2p')\n&= \\left( \\dfrac{\\partial}{\\partial t}\n  + W \\dfrac{\\partial}{\\partial z}\n  \\right) \\overline{a^2} e^{iE} \\left[\n      \\dfrac{d^2P}{dr^2}\n    + \\dfrac{1}{r} \\dfrac{dP}{dr}\n    - \\left( \\dfrac{n^2}{r^2} + k^2 \\right) P \\right] \\\\\n&= \\overline{a^2} \\left[ \\dfrac{d^2P}{dr^2}\n          + \\dfrac{1}{r} \\dfrac{dP}{dr}\n          - \\left( \\dfrac{n^2}{r^2} + k^2 \\right) P \\right]\n    \\left( \\dfrac{\\partial}{\\partial t}\n  + W \\dfrac{\\partial}{\\partial z}\n  \\right) e^{iE} \\\\\n&= \\overline{a^2} \\left[ \\dfrac{d^2P}{dr^2}\n          + \\dfrac{1}{r} \\dfrac{dP}{dr}\n          - \\left( \\dfrac{n^2}{r^2} + k^2 \\right) P \\right]\n  \\left( -\\omega ie^{iE} + kW ie^{iE}\\right) \\\\\n&= - \\overline{a^2} ie^{iE} (\\omega - kW) \\left[ \\dfrac{d^2P}{dr^2}\n          + \\dfrac{1}{r} \\dfrac{dP}{dr}\n          - \\left( \\dfrac{n^2}{r^2} + k^2 \\right) P \\right]\n\\end{align*}\n\nThis results in the final expression for Term 2:\n\n\\begin{equation} \\label{term2soln}\n\\boxed{ \\left( \\dfrac{\\partial}{\\partial t}\n  + W \\dfrac{\\partial}{\\partial z} \\right)\n  (\\overline{a^2}\\nabla^2p')\n= - \\overline{a^2} i\\exp[i(kz + n\\theta -\\omega t)]\n    (\\omega - kW) \\left[ \\dfrac{d^2P}{dr^2}\n    + \\dfrac{1}{r} \\dfrac{dP}{dr}\n    - \\left( \\dfrac{n^2}{r^2} + k^2 \\right) P \\right] }\n\\end{equation}\n\n\n\n\n\n\\clearpage\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Term 3}\n\nNow, we apply the solution form to third term of Lilley's equation:\n\n\\begin{align*}\n\\dfrac{d \\overline{a^2}}{dr} \\left( \\dfrac{\\partial}{\\partial t} + W \\dfrac{\\partial}{\\partial z} \\right) \\dfrac{dp'}{dr}\n&= \\dfrac{d \\overline{a^2}}{dr}\n   \\left( \\dfrac{\\partial}{\\partial t} + W \\dfrac{\\partial}{\\partial z} \\right)\n   \\dfrac{dP}{dr} e^{iE}  \\\\\n&= \\dfrac{d \\overline{a^2}}{dr} \\dfrac{dP}{dr}\n   \\left( \\dfrac{\\partial}{\\partial t} + W \\dfrac{\\partial}{\\partial z} \\right) e^{iE} \\\\\n&= \\dfrac{d \\overline{a^2}}{dr} \\dfrac{dP}{dr}\n    i(-\\omega + kW) e^{iE}\n\\end{align*}\n\nApply the isentropic relationship assumption for speed of sound and taking the derivative WRT $r$:\n\n\\begin{align*}\n\\dfrac{d \\overline{a^2}}{dr} \\dfrac{dP}{dr}\n    i(-\\omega + kW) e^{iE}\n&= \\dfrac{d}{dr} \\left(\\dfrac{\\gamma \\overline{p}}{\\overline{\\rho}}\\right)\n    \\dfrac{dP}{dr} i(-\\omega + kW) e^{iE} \\\\\n&= -\\left(\\dfrac{\\gamma \\overline{p}}{\\overline{\\rho}^2}\\right) \\frac{d \\overline{\\rho}}{dr}\n    \\dfrac{dP}{dr} i(-\\omega + kW) e^{iE} \\\\\n&= \\left(\\dfrac{\\overline{a^2}}{\\overline{\\rho}}\\right) \\frac{d \\overline{\\rho}}{dr} \\dfrac{dP}{dr} i(\\omega - kW) e^{iE}\n\\end{align*}\n\nThis results in the final expression for Term 3:\n\n\\begin{equation} \\label{term3soln}\n\\boxed{\\dfrac{d \\overline{a^2}}{dr} \\left( \\dfrac{\\partial}{\\partial t} + W \\dfrac{\\partial}{\\partial z} \\right) \\dfrac{dp'}{dr}\n= \\overline{a^2} i\\exp[i(kz + n\\theta -\\omega t)] (\\omega - kW)\n    \\dfrac{1}{\\overline{\\rho}}\\frac{d \\overline{\\rho}}{dr} \\dfrac{dP}{dr} }\n\\end{equation}\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Term 4}\n\nFinally, we will apply the solution form to fourth term of Lilley's equation:\n\n\n\\begin{align*}\n2\\overline{a^2} \\dfrac{dW}{dr}\\dfrac{\\partial^2 p'}{\\partial z \\partial r}\n  &= 2\\overline{a^2} \\dfrac{dW}{dr} \\dfrac{\\partial }{\\partial z}\n    \\dfrac{\\partial p'}{\\partial r}\n    = 2\\overline{a^2} \\dfrac{dW}{dr} \\dfrac{\\partial }{\\partial z}\n    \\left( \\dfrac{dP}{dr} e^{iE} \\right) \\\\\n&= 2\\overline{a^2} \\dfrac{dW}{dr} \\dfrac{dP}{dr}\n    \\dfrac{\\partial }{\\partial z} \\left( e^{iE} \\right)\n    = 2\\overline{a^2} \\dfrac{dW}{dr} \\dfrac{dP}{dr} ike^{iE}\n\\end{align*}\n\nThis results in the final expression for Term 4:\n\n\\begin{equation} \\label{term4soln}\n\\boxed{2\\overline{a^2} \\dfrac{dW}{dr}\\dfrac{\\partial^2p'}{\\partial z\\partial r}\n  = \\overline{a^2} i\\exp[i(kz + n\\theta -\\omega t)]\n    2k \\dfrac{dW}{dr} \\dfrac{dP}{dr} }\n\\end{equation}\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Lilley's Equation Solution}\n\nTo derive the final form of Lilley's equation, we combine Terms 1 through 4:\n\n\\begin{align*}\nEqn~\\ref{term1soln} - Eqn~\\ref{term2soln} - Eqn~\\ref{term3soln} + Eqn~\\ref{term4soln} = S(\\vec{x}, t)\n\\end{align*}\n\nWhich becomes the following in expanded form:\n\n\\begin{align*}\n\\left\\{ ie^{iE} (\\omega - kW)^3 P \\right\\}\n- \\left\\{ - \\overline{a^2} ie^{iE}\n    (\\omega - kW) \\left[ \\dfrac{d^2P}{dr^2}\n    + \\dfrac{1}{r} \\dfrac{dP}{dr}\n    - \\left( \\dfrac{n^2}{r^2} + k^2 \\right) P \\right] \\right\\} \\\\\n- \\left\\{ \\overline{a^2} ie^{iE} (\\omega - kW)\n    \\dfrac{1}{\\overline{\\rho}}\\frac{d \\overline{\\rho}}{dr} \\dfrac{dP}{dr} \\right\\}\n+ \\left\\{ \\overline{a^2} ie^{iE} 2k \\dfrac{dW}{dr} \\dfrac{dP}{dr} \\right\\}\n= S(\\vec{x}, t)\n\\end{align*}\n\nDividing both sides of the equation by the term $\\overline{a^2} ie^{iE} (\\omega - kW)$:\n\n\\begin{align*}\n\\dfrac{(\\omega - kW)^2}{\\overline{a^2}} P\n+ \\dfrac{d^2P}{dr^2}\n+ \\dfrac{1}{r} \\dfrac{dP}{dr}\n- \\left( \\dfrac{n^2}{r^2} + k^2 \\right) P\n- \\dfrac{1}{\\overline{\\rho}}\\frac{d \\overline{\\rho}}{dr} \\dfrac{dP}{dr}\n+ \\dfrac{1}{\\omega - kW} 2k \\dfrac{dW}{dr} \\dfrac{dP}{dr}\n= \\dfrac{S(\\vec{x}, t)}{\\overline{a^2} ie^{iE} (\\omega - kW)} \\\\\n\\dfrac{d^2P}{dr^2}\n+ \\dfrac{1}{r} \\dfrac{dP}{dr}\n- \\dfrac{1}{\\overline{\\rho}}\\frac{d \\overline{\\rho}}{dr} \\dfrac{dP}{dr}\n+ \\dfrac{1}{\\omega - kW} 2k \\dfrac{dW}{dr} \\dfrac{dP}{dr}\n+ \\dfrac{(\\omega - kW)^2}{\\overline{a^2}} P\n- \\left( \\dfrac{n^2}{r^2} + k^2 \\right) P\n= \\dfrac{S(\\vec{x}, t)}{\\overline{a^2} ie^{iE} (\\omega - kW)} \\\\\n\\end{align*}\n\nGrouping like terms of $P$, we obtain the final form of the general solution of Lilley's Equation:\n\n\\begin{equation} \\label{lilleysoln}\n\\boxed{\n\\dfrac{d^2P}{dr^2}\n+ \\left\\{\n    \\dfrac{1}{r}\n    - \\dfrac{1}{\\overline{\\rho}}\\frac{d \\overline{\\rho}}{dr}\n    + \\dfrac{1}{\\omega - kW} 2k \\dfrac{dW}{dr}\n\\right\\} \\dfrac{dP}{dr}\n+ \\left\\{\n    \\dfrac{(\\omega - kW)^2}{\\overline{a^2}}\n    - \\left( \\dfrac{n^2}{r^2} + k^2 \\right)\n\\right\\} P\n= \\dfrac{S(\\vec{x}, t)}{\\overline{a^2} ie^{iE} (\\omega - kW)} }\n\\end{equation}\n\n\\noindent where $E=kz + n\\theta -\\omega t$.\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Problem 2 -- General Solution for Jet Flow Far-Field} \\label{secprob2}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nNext, we will solve the homogeneous form of Lilley's equation (Eqn~\\ref{lilleysoln}) to determine the general solution for the pressure fluctuation outside of the jet in the ambient medium where the sources vanish.  This region can be considered to be the far-field of the jet, so the solution must be chosen to ensure decaying solutions (outgoing waves).\n\nSince this is far-field, ambient flow, we will assume that the mean velocity and density in this region are equal to the ambient mean values:\n\n\\begin{equation}\n\\begin{split}\n&W(r)= W_{\\infty}=const \\\\\n&\\overline{\\rho} = \\overline{\\rho_0} = const\n\\end{split}\n\\end{equation}\n\n\\noindent which allows us to simplify the homogeneous equation:\n\n\\begin{align*}\n\\dfrac{d^2P}{dr^2}\n+ \\left\\{\n    \\dfrac{1}{r}\n    - \\dfrac{1}{\\overline{\\rho}}\\frac{d \\overline{\\rho}}{dr}\n    + \\dfrac{1}{\\omega - kW} 2k \\dfrac{dW}{dr}\n\\right\\} \\dfrac{dP}{dr}\n+ \\left\\{\n    \\dfrac{(\\omega - kW)^2}{\\overline{a^2}}\n    - \\left( \\dfrac{n^2}{r^2} + k^2 \\right)\n\\right\\} P = 0 \\\\\n\\dfrac{d^2P}{dr^2}\n  + \\left\\{\n    \\dfrac{1}{r}\n    - \\dfrac{1}{\\overline{\\rho_0}} \\cancelto{0}{\\frac{d \\overline{\\rho_0}}{dr}}\n    + \\dfrac{1}{\\omega - kW_{\\infty}} 2k \\cancelto{0}{\\dfrac{dW}{dr}}\n\\right\\} \\dfrac{dP}{dr}\n + \\left\\{\n    \\underbrace{ \\dfrac{(\\omega - k W_{\\infty} )^2}{\\overline{a^2} }\n    - k^2 }_{\\lambda^2}\n    - \\dfrac{n^2}{r^2}\n\\right\\} P = 0\n% \\dfrac{d^2P}{dr^2}\n%   + \\left\\{\n%     \\dfrac{1}{r}\n%   \\right\\} \\dfrac{dP}{dr}\n% + \\left\\{\n%     \\lambda^2\n%     - \\dfrac{n^2}{r^2}\n% \\right\\} P = 0 \\\\\n\\end{align*}\n\nResulting in the homogeneous Bessel equation:\n\n\\begin{equation} \\label{BesselEqn}\n\\boxed{ \\dfrac{d^2P}{dr^2} + \\left\\{ \\dfrac{1}{r} \\right\\} \\dfrac{dP}{dr}\n      + \\left\\{ \\lambda_{\\infty}^2 - \\dfrac{n^2}{r^2} \\right\\} P = 0 }\n\\end{equation}\n\n\\noindent where the constant term is collected in $\\lambda_{\\infty}$:\n\n\\begin{align*}\n\\lambda_{\\infty} &= \\sqrt{\\dfrac{(\\omega - k W_{\\infty} )^2}{\\overline{a^2} } - k^2}\n\\end{align*}\n\nSubstituting the definition of wavenumber $k=\\dfrac{\\omega}{\\overline{a}}$, the expression can be reduced:\n\n\\begin{align*}\n\\lambda_{\\infty} &= \\sqrt{\n  \\dfrac{ \\left(\\omega -\\dfrac{\\omega}{\\overline{a}} W_{\\infty} \\right)^2}{\\overline{a^2}}\n  - \\dfrac{\\omega^2}{\\overline{a^2}}\n  } \\\\\n&= \\sqrt{\n  \\dfrac{ \\omega^2 \\left(1 -\\dfrac{W_{\\infty}}{\\overline{a}} \\right)^2}{\\overline{a^2}}\n  - \\dfrac{\\omega^2}{\\overline{a^2}}\n  } \\\\\n&= \\sqrt{ \\dfrac{\\omega^2}{\\overline{a^2}}\n    \\left[ \\left(1 -\\dfrac{W_{\\infty}}{\\overline{a}} \\right)^2 - 1  \\right]\n  } \\\\\n&= \\sqrt{ \\dfrac{\\omega^2}{\\overline{a^2}}\n    \\left( 1 -2\\dfrac{W_{\\infty}}{\\overline{a}} + \\dfrac{W_{\\infty}^2}{\\overline{a^2}} - 1  \\right) } \\\\\n&= \\sqrt{ \\dfrac{\\omega^2}{\\overline{a^2}}\n    \\left( \\dfrac{W_{\\infty}^2}{\\overline{a^2}} -2\\dfrac{W_{\\infty}}{\\overline{a}} \\right) } \\\\\n&= \\sqrt{ \\dfrac{\\omega^2}{\\overline{a^2}} \\dfrac{W_{\\infty}}{\\overline{a}}\n    \\left( \\dfrac{W_{\\infty}}{\\overline{a}} - 2 \\right) }\n\\end{align*}\n\n\n\nSubstituting the definition of Mach number $M_{\\infty} = \\dfrac{W_{\\infty}}{\\overline{a}}$, we obtain:\n\n\\begin{equation} \\label{lambda}\n\\lambda_{\\infty} = \\sqrt{ \\dfrac{\\omega^2}{\\overline{a^2}} M_{\\infty} ( M_{\\infty} - 2 ) }\n\\end{equation}\n\n\\noindent where $M_{\\infty}$ is the freestream Mach number and $\\lambda_{\\infty}$ is an imaginary quantity for $M_{\\infty} < 2$.\n\nEqn~\\ref{BesselEqn} is of the same form as Bessel's ordinary differential equation and can be solved using the first $H_n^{(1)}(\\lambda_{\\infty} r)$ and second $H_n^{(2)}(\\lambda_{\\infty} r)$ order Hankel functions:\n\n\\begin{equation}\nP = C H_n^{(1)}(\\lambda_{\\infty} r) + D H_n^{(2)}(\\lambda_{\\infty} r)\n\\end{equation}\n\n\\noindent where $C$ and $D$ are arbitrary constants and the first and second order Hankel functions are equal to the outgoing $H_n^{+}(x)$ and incoming $H_n^{+}(x)$ wave solutions, respectively, and $x = \\lambda_{\\infty} r$:\n\n\\begin{align}\nH_n^{(1)}(\\lambda_{\\infty} r) = H_n^{+}(x) = J_n(x) + i Y_n(x) \\\\\nH_n^{(2)}(\\lambda_{\\infty} r) = H_n^{-}(x) = J_n(x) - i Y_n(x)\n\\end{align}\n\n\\noindent where the Hankel functions are composed of the first and second order Bessel functions $J_n$ and $Y_n$, respectively.\n\nTaking the limit of $H_n^{+}(x)$ and $H_n^{-}(x)$ as $x$ and $r$ approach infinity (far-field condition):\n\n\\begin{align*}\n\\lim_{x\\to\\infty} H_n^{+}(x) &= (-i)^{n+1} \\dfrac{e^{ix}}{x} \\\\\n\\lim_{x\\to\\infty} H_n^{+}(x) &= i^{n+1}    \\dfrac{e^{-ix}}{x}\n\\end{align*}\n\nIn the far-field, flow velocity is subsonic ($M_{\\infty}<1$), making $\\lambda_{\\infty}$ imaginary according to Eqn~\\ref{lambda}.  This, in turn, makes the limit of $H_n^{+}(x)$ a diminishing exponential and the limit of $H_n^{-}(x)$ an increasing exponential, which is impossible.  Thus, Eqn~\\ref{BesselEqn} reduces to Eqn~\\ref{BesselFar} for final solution of the far-field outside of the potential core of the jet:\n\n\\begin{equation} \\label{BesselFar}\n\\boxed{P = C H_n^{(1)}(\\lambda_{\\infty} r)}\n\\end{equation}\n\n\n\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Problem 3 -- General Solution for Jet Potential Core} \\label{SecProb3}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nIn this section, we will solve the homogeneous form of Lilley's equation (Eqn~\\ref{lilleysoln}) to determine the general solution for the potential core region of the jet.  We will assume that the mean velocity and density in this region are constant and equal to the jet exit values:\n\n\\begin{align}\nW(r)=W_j=const \\\\\n\\overline{\\rho} = \\overline{\\rho_j} = const\n\\end{align}\n\nThese assumptions are similar to those made in Section~\\ref{secprob2}, which allows the reduction of Eqn~\\ref{lilleysoln} to the Bessel equation:\n\n\\begin{equation} \\label{BesselEqnJet}\n\\boxed{ \\dfrac{d^2P}{dr^2} + \\left\\{ \\dfrac{1}{r} \\right\\} \\dfrac{dP}{dr}\n      + \\left\\{ \\lambda_{j}^2 - \\dfrac{n^2}{r^2} \\right\\} P = 0 }\n\\end{equation}\n\n\\noindent with\n\n\\begin{equation} \\label{lambdaJ}\n\\lambda_{j} = \\sqrt{ \\dfrac{\\omega^2}{\\overline{a^2}} M_{j} ( M_{j} - 2 ) }\n\\end{equation}\n\n\\noindent where $M_{j}=\\dfrac{W_j}{\\overline{a}}$ is the jet exit Mach number and $\\lambda_{j}$ is an imaginary quantity for $M_{j} < 2$.\n\nFor this potential core solution, we assume the Bessel equation is equivalent to the first $J_n$ and second $Y_n$ order Bessel functions:\n\n\\begin{equation}\nP = A J_n(\\lambda_j r) + B Y_n(\\lambda_j r)\n\\end{equation}\n\n\\noindent where $A$ and $B$ are arbitrary constants.\n\nThe second order Bessel function $Y_n$ is defined as having a singularity where $\\lambda_j r = 0$, so inside the potential core region where $0<r<R_j$, we can leave the singular $Y_n$ out of Eqn~\\ref{BesselEqnJet}, resulting in the final expression for the solution inside of the potential core:\n\n\\begin{equation} \\label{BesselCore}\n\\boxed{P = A J_n(\\lambda_j r)}\n\\end{equation}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Problem 4 -- Matching of Far-Field and Potential Core Solutions}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nIn Section~\\ref{secprob2} we derived a solution for the pressure fluctuations ($P^+$) outside of the jet potential core in the far-field (Eqn~\\ref{BesselFar}) and in Section~\\ref{SecProb3} we derived a solution for the pressure fluctuations ($P^-$) inside the jet potential core (Eqn~\\ref{BesselCore}).  Ideally, we would like to combine these near and far solutions by joining them at the edge of the potential core.\n\nOne method of accomplishing this solution is to replace the potential core boundary with a vortex sheet located at $r = R_j$.  To successfully join the two solutions, we require two matching boundary conditions at this vortex sheet, which can be described according the two following conditions:\n\n\\begin{enumerate}\n  \\item Pressure fluctuations on either edge of the vortex sheet must match:\n        \\begin{align} \\label{constraint1}\n          P^+ = P^-\n        \\end{align}\n  \\item Radial velocity fluctuations across the vortex sheet must match:\n        \\begin{align} \\label{constraint2}\n          V_r^+ = V_r^-\n        \\end{align}\n\\end{enumerate}\n\nThe first constraint (Eqn~\\ref{constraint1}) of matched pressure fluctuation can be written using the Bessel equation solutions for the outer flow (Eqn~\\ref{BesselFar}) and inner flow (Eqn~\\ref{BesselCore}):\n\n\\begin{equation} \\label{constantsEqn1}\n\\boxed{C H_n^{(1)}(\\lambda_{\\infty} r) = A J_n(\\lambda_j r)}\n\\end{equation}\n\nThe second constraint will be achieved by relating the radial gradient of pressure $\\dfrac{dP}{dr}$ with the radial velocity at the vortex sheet $V_r$:\n\n\\begin{equation}\nV_r = \\nu \\exp[i(-\\omega t + kz)]\n\\end{equation}\n\n\\noindent where $\\nu$ is a constant value of velocity in the radial direction that is modulated by the expression $\\exp[i(-\\omega t + kz)]$, which is a function of time and the jet flow direction $z$.\n\nWe will first obtain an expression relating $V_r$ and the pressure fluctuation using the momentum equation:\n\n\\begin{equation} \\label{momentum}\n\\overline{\\rho_0} \\dfrac{D\\vec{V} }{Dt} = - \\nabla P\n\\end{equation}\n\nBecause the matching conditions apply only across the vortex sheet in the radial direction, we look at the radial component of Eqn~\\ref{momentum} by taking the dot product of both sides WRT the radial unit vector $\\hat{r}$:\n\n\\begin{align*}\n\\overline{\\rho_0} \\dfrac{D\\vec{V}}{Dt} \\cdot \\hat{r}\n    &= - \\nabla P \\cdot \\hat{r} \\\\\n\\overline{\\rho_0} \\dfrac{D V_r}{Dt} &= - \\dfrac{\\partial P}{\\partial r}\n\\end{align*}\n\nThe total time derivative of $V_r$ is (see Section~\\ref{SecLilley}):\n\n\\begin{align*}\n\\dfrac{D V_r}{Dt}\n  &= \\left(\\dfrac{\\partial}{\\partial t} + W \\dfrac{\\partial}{\\partial z}\\right)\n  V_r \\\\\n  &= \\left(\\dfrac{\\partial}{\\partial t} + W \\dfrac{\\partial}{\\partial z}\\right)\n  \\nu \\exp[i(-\\omega t + kz)] \\\\\n  &= - i( \\omega - kW ) \\nu\\exp[i(-\\omega t + kz)] \\\\\n  &= - i( \\omega - kW ) V_r\n\\end{align*}\n\nSubstituting $\\dfrac{D V_r}{Dt}$ into Eqn~\\ref{momentum}, we obtain:\n\n\\begin{align}\n\\overline{\\rho_0} i( \\omega - kW ) V_r = \\dfrac{d P}{d r}\n\\end{align}\n\n\\noindent which can be rearranged in terms of $V_r$, allowing us to satisfy our second constraint:\n\n\\begin{align} \\label{VrMomentum}\n\\boxed{V_r = \\dfrac{\\dfrac{d P}{d r}}{\\overline{\\rho_0} i( \\omega - kW )}}\n\\end{align}\n\n\nNext, we will define the radial velocity fluctuation $V_r$ instead as the time derivative of the radial displacement $\\zeta$ of fluid particles located at the vortex sheet.\n\n\\begin{equation}\nV_r = \\dfrac{D\\zeta}{Dt}\n\\end{equation}\n\n\\noindent where\n\n\\begin{equation}\n\\zeta(z,t) = \\chi \\exp[i(-\\omega t + kz)]\n\\end{equation}\n\n\\noindent and where $\\chi$ is a constant value of radial position that is modulated by the same expression $\\exp[i(-\\omega t + kz)]$, which governs the oscillation of the vortex sheet.\n\nTaking the time derivative of $\\zeta$ (see Section~\\ref{SecLilley}):\n\n\\begin{align*}\nV_r &= \\dfrac{D\\zeta}{Dt} =\n    \\left(\\dfrac{\\partial}{\\partial t} + W \\dfrac{\\partial}{\\partial z}\\right)\n    \\zeta \\\\\n    &=\\left(\\dfrac{\\partial}{\\partial t} + W \\dfrac{\\partial}{\\partial z}\\right)\n    \\chi \\exp[i(-\\omega t + kz)]  \\\\\n&= -\\chi \\exp[i(-\\omega t + kz)] i ( \\omega - kW )  \\\\\n&= -\\zeta i ( \\omega - kW )\n\\end{align*}\n\nApplying the solution for $V_r$ to the outer and inner vortex sheet velocity fluctuations:\n\n\\begin{align}\nV_r^+ &= -i(\\omega - kW_{\\infty} )\\zeta  \\label{Vplus}\\\\\nV_r^- &= -i(\\omega - kW_j )       \\zeta  \\label{Vminus}\n\\end{align}\n\nRearranging the solution of $V_r$ for $\\zeta$, and setting Eqns~\\ref{Vplus} and~\\ref{Vminus} equal to each other:\n\n\\begin{align} \\label{VrVel}\n\\boxed{\\zeta = \\dfrac{V_r^+}{-i(\\omega - kW_{\\infty})}\n    = \\dfrac{V_r^-}{-i(\\omega - kW_{j})}}\n\\end{align}\n\nNext, the second constraint (Eqn~\\ref{constraint2}) can be put into terms of pressure rather than $V_r$ by substituting Eqn~\\ref{VrMomentum} applied to the inner and outer solutions:\n\n\\begin{align*}\nV_r^+ &=\\dfrac{\\dfrac{dP}{dr}^+}{\\overline{\\rho_0} i( \\omega - kW_{\\infty})} \\\\\nV_r^- &= \\dfrac{\\dfrac{dP}{dr}^-}{\\overline{\\rho_0} i( \\omega - kW_{j})}\n\\end{align*}\n\n\\noindent into Eqn~\\ref{VrVel}:\n\n\\begin{align*}\n\\dfrac{V_r^+}{-i(\\omega - kW_{\\infty})}\n    &= \\dfrac{V_r^-}{-i(\\omega - kW_{j})} \\\\\n\\dfrac{\\dfrac{dP}{dr}^+}{-i^2(\\omega - kW_{\\infty})^2}\n    &= \\dfrac{\\dfrac{dP}{dr}^-}{-i^2(\\omega - kW_{j})^2} \\\\\n\\end{align*}\n\n\\begin{equation} \\label{constraints}\n\\boxed{\\dfrac{\\dfrac{dP}{dr}^+}{(\\omega - kW_{\\infty})^2}\n    = \\dfrac{\\dfrac{dP}{dr}^-}{(\\omega - kW_{j})^2}}\n\\end{equation}\n\nFinally, we can calculate the pressure differentials from the solutions for the outer flow (Eqn~\\ref{BesselFar}) and inner flow (Eqn~\\ref{BesselCore}):\n\n\\begin{align*}\n\\dfrac{dP}{dr}^+ &= \\dfrac{d}{dr} \\left[C H_n^{(1)}(\\lambda_{\\infty} r) \\right]\n    = C \\dfrac{d}{dr}\\left[H_n^{(1)}(\\lambda_{\\infty} r)\\right] \\\\\n\\dfrac{dP}{dr}^- &= \\dfrac{d}{dr} \\left[A J_n(\\lambda_j r) \\right]\n    = A \\dfrac{d}{dr}\\left[ J_n(\\lambda_j r) \\right]\n\\end{align*}\n\n\\noindent and substitute the resulting expressions into Eqn~\\ref{constraints}:\n\n\\begin{align*}\n\\dfrac{C \\dfrac{d}{dr}\\left[H_n^{(1)}(\\lambda_{\\infty} r)\\right]}{(\\omega - kW_{\\infty})^2}\n    = \\dfrac{A \\dfrac{d}{dr}\\left[ J_n(\\lambda_j r) \\right]}{(\\omega - kW_{j})^2}\n\\end{align*}\n\n\\noindent Rearranging, we obtain a second equation containing the unknown constants $A$ and $C$.\n\n\\begin{equation} \\label{constantsEqn2}\n\\boxed{\nC(\\omega - kW_{j})^2 \\dfrac{d}{dr}\\left[H_n^{(1)}(\\lambda_{\\infty} r)\\right]\n    = A(\\omega - kW_{\\infty})^2 \\dfrac{d}{dr}\\left[ J_n(\\lambda_j r) \\right]}\n\\end{equation}\n\nThus, achieving the two constraints set at the beginning of this section and substituting the known equations for pressure fluctuations inside and outside the potential core, we rewrite the resulting two equations (Eqns~\\ref{constantsEqn1} and~\\ref{constantsEqn2}) with two constant unknowns:\n\n\\begin{align*}\nC H_n^{(1)}(\\lambda_{\\infty} r) &= A J_n(\\lambda_j r) \\\\\nC(\\omega - kW_{j})^2 \\dfrac{d}{dr}\\left[H_n^{(1)}(\\lambda_{\\infty} r)\\right]\n    &= A(\\omega - kW_{\\infty})^2 \\dfrac{d}{dr}\\left[ J_n(\\lambda_j r) \\right]\n\\end{align*}\n\nThis system of ordinary differential equations can be solved to correctly determine $A$ and $C$ and thus provide an explicit solution for the combined interior and exterior axial jet flow.\n\nIt should be noted that this solution only applies for subsonic and supersonic jet flows with $M<2$ as previously demonstrated in Eqn~\\ref{lambda}.\n\n\n\n\n\n\n\n\n\n\n\\end{document}\n\n\n", "meta": {"hexsha": "9042d6ef7faf4a546ddeeb822b735ec31a749918", "size": 33826, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "hw2_LilleyEqn/writeup/MAE298_LHalstrom_HW2_LilleyEqn.tex", "max_stars_repo_name": "lhalstro/mae298_aeroacoustics", "max_stars_repo_head_hexsha": "8a4490d63028be49927c7777fd1c13f84e780b8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-06-23T20:04:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-28T19:50:49.000Z", "max_issues_repo_path": "hw2_LilleyEqn/writeup/MAE298_LHalstrom_HW2_LilleyEqn.tex", "max_issues_repo_name": "lhalstro/mae298_aeroacoustics", "max_issues_repo_head_hexsha": "8a4490d63028be49927c7777fd1c13f84e780b8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw2_LilleyEqn/writeup/MAE298_LHalstrom_HW2_LilleyEqn.tex", "max_forks_repo_name": "lhalstro/mae298_aeroacoustics", "max_forks_repo_head_hexsha": "8a4490d63028be49927c7777fd1c13f84e780b8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-05-25T06:42:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-30T17:28:26.000Z", "avg_line_length": 39.9834515366, "max_line_length": 417, "alphanum_fraction": 0.6124578726, "num_tokens": 11808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.327520252369819}}
{"text": "\\documentclass{anstrans}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\title{Mixed Hybrid Finite Element Method Eddington Acceleration of Discrete Ordinates Source Iteration}\n\\author{Samuel S. Olivier*, Jim E. Morel}\n\n\\institute{Department of Nuclear Engineering, Texas A\\&M University, College Station, TX 77843}\n\n\\email{smsolivier@tamu.edu}\n\n\n%%%% packages and definitions (optional)\n\\usepackage{graphicx} % allows inclusion of graphics\n\\usepackage{booktabs} % nice rules (thick lines) for tables\n\\usepackage{microtype} % improves typography for PDF\n\n\\usepackage{xspace}\n\\usepackage{siunitx}\n\n\\newcommand{\\SN}{S$_N$\\xspace}\n\\renewcommand{\\vec}[1]{\\bm{#1}} %vector is bold italic\n\\newcommand{\\vd}{\\bm{\\cdot}} % slightly bold vector dot\n\\newcommand{\\grad}{\\vec{\\nabla}} % gradient\n\\newcommand{\\ud}{\\mathop{}\\!\\mathrm{d}} % upright derivative symbol\n\\newcommand{\\pderiv}[2]{\\frac{\\partial #1}{\\partial #2}}\n\\newcommand{\\dderiv}[2]{\\frac{\\ud #1}{\\ud #2}}\n\\newcommand{\\edd}{\\langle \\mu^2 \\rangle} \n\n% add section on MHFEM system \n% order of accuracy of accelerated system \n\n\\begin{document}\n\\section{Introduction} \n\t% Two of the most challenging computational tasks are radiation transport and hydrodynamics. \n\tOne of the most challenging computational tasks is simulating the interaction of radiation with matter. \n\tA full description of a particle in flight includes three spatial variables ($x$,$y$ and $z$), two angular or direction of flight variables ($\\mu =$ the cosine of the polar angle and $\\gamma =$ the azimuthal angle), one energy variable ($E$) and one time variable ($t$). Numerical solutions require discretizing all seven variables leading to immense systems of algebraic equations. In addition, material properties can lead to vastly different solution behaviors making generalized numerical methods for radiation transport difficult to attain \\cite{adams}. \n\n\t% The conservation of mass, momentum and energy in hydrodynamics simulations leads to a hyperbolic system of partial differential equations dependent on the time derivatives of velocity and two state variables. This results in five variables but only three equations leading to the requirement of additional equations to reach problem closure \\cite{hydro}. \n\n\t% Radiation transport and hydrodynamics can be combined using operator splitting, where the radiation transport and hydrodynamics \n\n\tA national lab with whom we work has plans to develop a high-order radiation-hydrodynamics code. The hydrodynamics portion is discretized using the Mixed Hybrid Finite Element Method (MHFEM) where values are taken to be constant within a cell with discontinuous jumps at both cell edges \\cite{mhfem}. MHFEM is particularly suited for hydrodynamics but not for radiation transport. This work seeks to develop an acceleration scheme capable of robustly reducing the number of iterations in Discrete Ordinates Source Iteration calculations while being compatible with MHFEM multiphysics.   \n\n\\section{Background}\n\tThe steady-state, mono-energetic, isotropically-scattering, fixed-source Linear Boltzmann Equation in slab geometry is: \n\t\t\\begin{equation} \\label{eq:bte}\n\t\t\t\\mu \\pderiv{\\psi}{x}(x, \\mu) + \\Sigma_t(x) \\psi(x,\\mu) = \n\t\t\t\\frac{\\Sigma_s(x)}{2} \\int_{-1}^{1} \\psi(x, \\mu') d\\mu' + \\frac{Q(x)}{2} \\,,\n\t\t\\end{equation}\n\twhere $\\mu = \\cos\\theta$ is the cosine of the angle of flight $\\theta$ relative to the $x$--axis, $\\Sigma_t(x)$ and $\\Sigma_s(x)$ the total and scattering macroscopic cross sections, $Q(x)$ the isotropic fixed-source and $\\psi(x, \\mu)$ the angular flux \\cite{adams}. The factors of 1/2 are consistent with the following definition of the scalar flux:\n\t\t\\begin{equation} \\label{eq:phiDef}\n\t\t\t\\phi(x) = \\int_{-1}^1 \\psi(x, \\mu) \\ud \\mu \\,.\n\t\t\\end{equation}\n\tEquation \\ref{eq:bte} is an integro-differential equation due to the placement of the unknown, $\\psi(x,\\mu)$, under both a derivative and an integral.\n\n\tThe Discrete Ordinates (\\SN) angular discretization sets $\\mu$ to discrete values stipulated by an $N$--point Gauss quadrature rule. The scalar flux is then \n\t\t\\begin{equation} \\label{eq:quad}\n\t\t\t\\phi(x) = \\int_{-1}^1 \\psi(x, \\mu) \\ud\\mu \n\t\t\t\t\\xrightarrow{\\text{S}_N} \\sum_{n=1}^N w_n \\psi_n(x) \\,,\n\t\t\\end{equation}\n\twhere $\\psi_n(x) = \\psi(x,\\mu_n)$ and the $w_n$ are the quadrature weights corresponding to each $\\mu_n$ \\cite{llnl}. To remain consistent with Eq. \\ref{eq:phiDef}, the quadrature weights sum to 2. The \\SN equations are then \n\t\t\\begin{equation} \\label{eq:sn}\n\t\t\t\\mu_n \\dderiv{\\psi_n}{x}(x) + \\Sigma_t(x) \\psi_n(x) = \n\t\t\t\\frac{\\Sigma_s(x)}{2} \\phi(x) + \\frac{Q(x)}{2} \\,, \n\t\t\\end{equation}\n\twhere $n = 1, 2, \\dots, N$ and $\\phi(x)$ is defined by Eq. \\ref{eq:quad}. This is now a system of $N$ coupled, ordinary differential equations. \n\n\tThe Source Iteration (SI) solution method decouples the \\SN equations by lagging the right side of Eq. \\ref{eq:si}. In other words, \n\t\t\\begin{equation} \\label{eq:si}\n\t\t\t\\mu_n \\dderiv{\\psi_n^{\\ell+1}}{x}(x) + \\Sigma_t(x) \\psi_n^{\\ell+1}(x) = \n\t\t\t\\frac{\\Sigma_s(x)}{2} \\phi^{\\ell}(x) + \\frac{Q(x)}{2} \\,, 1 \\leq n \\leq N \\,,\n\t\t\\end{equation}\n\twhere the superscripts indicate the iteration index. \n\tEquation \\ref{eq:si} represents $N$ independent, first-order, ordinary differential equations each of which are easily solved by the well-known sweeping process. \n\n\tThe iteration process begins with an initial guess for the scalar flux, $\\phi^0(x)$. Equation \\ref{eq:si} is solved, using $\\phi^0(x)$ on the right side, for $\\psi_n^1(x)$. $\\phi^1(x)$ is then computed using Eq. \\ref{eq:quad} and is used to update the right side of Eq. \\ref{eq:si}. \n\tThis process is repeated until \n\t\t\\begin{equation} \\label{eq:converg}\n\t\t\t\\frac{\\|\\phi^{\\ell+1}(x) - \\phi^{\\ell}(x)\\|}{\\|\\phi^{\\ell+1}(x)\\|} < \\epsilon \\,,\n\t\t\\end{equation}\n\twhere $\\epsilon$ is a sufficiently small tolerance. \n\n\tIf $\\phi^0(x) = 0$, then $\\phi^\\ell(x)$ is the scalar flux of particles that have undergone at most $\\ell - 1$ collisions \\cite{adams}. Thus, the number of iterations until convergence is directly linked to the number of collisions in a particle's lifetime. Typically, SI becomes increasingly slow to converge as the ratio of $\\Sigma_s$ to $\\Sigma_t$ approaches unity and the amount of particle leakage from the system goes to zero. SI is slowest in large, optically thick systems with small losses to absorption. In full radiation transport simulations each iteration could involve solving for hundreds of millions of unknowns. To minimize computational expense, acceleration schemes must be developed to rapidly increase the rate of convergence of SI. \n\n\tFortunately, the regime where SI is slow to converge is also the regime where Diffusion Theory is most accurate. A popular method for accelerating SI is Diffusion Synthetic Acceleration (DSA) where each source iteration involves both a transport sweep and a diffusion solve. DSA requires carefully differencing the \\SN and diffusion steps in a consistent manner to prevent instability in highly scattering media with coarse spatial grids \\cite{alcouffe,morel}. DSA is not applicable in the setting of this presentation due to the incompatibility of MHFEM and \\SN and the increased computational expense of solving consistently differenced diffusion. A new acceleration method is needed that avoids the consistency pitfall of DSA. \n\n\\section{Eddington Acceleration}\n\tThe zeroth and first angular moments of Eq. \\ref{eq:bte} are \n\t\t\\begin{subequations} \n\t\t\\begin{equation} \\label{eq:zero}\n\t\t\t\\dderiv{}{x} J(x) + \\Sigma_a(x) \\phi(x) = Q(x) \\,,\n\t\t\\end{equation} \n\t\t\\begin{equation} \\label{eq:first}\n\t\t\t\\frac{\\ud}{\\ud x} \\edd(x) \\phi(x) + \\Sigma_t(x) J(x) = 0 \\,,\n\t\t\\end{equation}\n\t\t\\end{subequations}\n\twhere $J(x) = \\int_{-1}^{1} \\mu \\ \\psi(x, \\mu) \\ud \\mu$ is the current and \n\t\t\\begin{equation} \\label{eq:eddington} \n\t\t\t\\edd(x) = \\frac{\\int_{-1}^1 \\mu^2 \\psi(x, \\mu) \\ud \\mu}{\\int_{-1}^1 \\psi(x, \\mu) \\ud \\mu}\n\t\t\t% \\xrightarrow{\\text{S}_N} \\frac{\\sum_{n=1}^N \\mu_n^2 w_n\\psi_n(x)}{\\sum_{n=1}^N w_n \\psi_n(x)} \n\t\t\\end{equation}\n\tthe Eddington factor. In \\SN, the Eddington factor is \n\t\t\\begin{equation} \\label{eq:edd_sn}\n\t\t\t\\edd(x) = \\frac{\\sum_{n=1}^N \\mu_n^2 w_n\\psi_n(x)}{\\sum_{n=1}^N w_n \\psi_n(x)} \\,.\n\t\t\\end{equation}\n\tNote that no approximations have been made to arrive at Eqs. \\ref{eq:zero} and \\ref{eq:first}. The Eddington factor is the true angular flux weighted average of $\\mu^2$ and therefore Eqs. \\ref{eq:zero} and \\ref{eq:first} are just as accurate as Eq. \\ref{eq:bte}. \n\n\tThis formulation is beneficial because Eq. \\ref{eq:zero} is a conservative balance equation and---if $\\edd(x)$ is known---the moment equations' system of two first-order, ordinary differential equations can be solved directly with well-established methods. However, computing $\\edd(x)$ requires knowledge of the angular flux. \n\n\tIn Eddington Acceleration, \\SN is used to compute the Eddington factor needed to solve the moment equations. Source iteration is then:  \n\t\t\\begin{enumerate}\n\t\t\t\\item Given the previous estimate for the scalar flux, $\\phi^{\\ell}(x)$, solve Eq. \\ref{eq:si} for $\\psi_n^{\\ell+1/2}(x)$. \n\t\t\t\\item Compute $\\edd^{\\ell+1/2}(x)$ with Eq. \\ref{eq:edd_sn}. \n\t\t\t% \\item Interpolate $\\edd(x)$ onto the MHFEM grid \n\t\t\t\\item Solve the moment equations for $\\phi^{\\ell+1}(x)$ using $\\edd^{\\ell+1/2}(x)$. \n\t\t\t% \\item Use the moment equations' $\\phi(x)$ on the right hand side of Eq. \\ref{eq:si}.  \n\t\t\t\\item Update the scalar flux estimate on the right side of Eq. \\ref{eq:si} with $\\phi^{\\ell+1}(x)$ and repeat the iteration process until the scalar flux converges. \n\t\t\\end{enumerate}\n\t% This process is one source iteration consisting of an \\SN transport step to compute the Eddington factor and an MHFEM acceleration step to compute $\\phi(x)$. The scalar flux from the acceleration step is used in the right hand side of Eq. \\ref{eq:si} and steps 1--4 are repeated until the acceleration step's $\\phi(x)$ converges according to Eq. \\ref{eq:converg}.  \nW\n\tAcceleration occurs because the angular shape of the angular flux, and thus the Eddington factor, converges much faster than the scalar flux. In addition, the moment equations model the contributions of all scattering events at once, reducing the dependence on source iterations to introduce scattering information. The solution from the moment equations is then an approximation for the full flux and not the $\\ell - 1$ collided flux as it was without acceleration. \n\n\tIn addition to acceleration, this scheme allows the \\SN equations and moment equations to be solved with arbitrarily different spatial discretization methods. \\SN can be spatially discretized using normal methods, such as Linear Discontinuous Galerkin or Diamond Difference, while the moment equations can be solved with MHFEM. \n\n\\section{Results}\n\t\\begin{figure}\n\t\t\\centering\n\t\t\\includegraphics[width=8.5cm]{figs/accel.pdf}\n\t\t\\caption{A comparison of the number of iterations until convergence for unaccelerated, Eddington accelerated, and DSA S$_8$ SI. }\n\t\t\\label{fig:comparison}\n\t\\end{figure}\n\n\tAs a proof of concept for Eddington Acceleration, a Diamond Differenced \\SN code was created along with an MHFEM solver for Eqs. \\ref{eq:zero} and \\ref{eq:first}. The test problem of steady-state, one-group, isotropically-scattering, fixed-source radiation transport in slab geometry with a reflecting left boundary and vacuum right boundary was used to compare unaccelerated, Eddington accelerated, and DSA S$_8$ SI. The slab had a thickness of \\SI{20}{cm} and was discretized into 100 spatial cells. The total macroscopic cross section was set to \\SI{1}{cm^{-1}} leading to a total optical thickness of 20 and an optical thickness per cell of 0.2. \n\n\tFigure \\ref{fig:comparison} shows the number of iterations until the convergence criterion in  Eq. \\ref{eq:converg} was met with $\\epsilon = \\num{1e-6}$ for varying ratios of $\\Sigma_s$ to $\\Sigma_t$. Aside from $\\Sigma_s/\\Sigma_t = 0$ where acceleration is not possible, the ratio of unaccelerated to Eddington accelerated iterations ranged between 2.5 and 750. This suggests that acceleration is occurring and that Eddington Acceleration does not just do twice the amount of work in each iteration. \n\n\t\\begin{figure}\n\t\t\\centering\n\t\t\\includegraphics[width=8.5cm]{figs/eddCon_si.pdf}\n\t\t\\caption{The convergence rate of $\\phi(x)$ compared to $\\edd(x)$ for unaccelerated S$_8$ with $\\Sigma_s/\\Sigma_t = 0.75$. }\n\t\t\\label{fig:conv_si}\n\t\\end{figure}\n\n\tFigure \\ref{fig:conv_si} shows the convergence criterion \n\t\t\\begin{equation}\n\t\t\t\\frac{\\|f^{\\ell+1} - f^{\\ell}\\|}{\\|f^{\\ell+1}\\|}\n\t\t\\end{equation}\n\tas a function of unaccelerated iteration number for $f = \\phi(x)$ and $f = \\edd(x)$. The large drop in the convergence criterion between the first and second iterations supports the claim that the angular shape of the angular flux, and thus the Eddington factor, converges much more rapidly than the scalar flux. When compared to Fig. \\ref{fig:conv_edd}, a plot of the convergence criterion versus number of iterations for Eddington accelerated S$_8$, it is clear that Eddington Acceleration transfers the fast rate of convergence of $\\edd(x)$ to $\\phi(x)$. \n\n\t\\begin{figure}\n\t\t\\centering\n\t\t\\includegraphics[width=8.5cm]{figs/eddCon_mu.pdf}\n\t\t\\caption{The convergence rate of $\\phi(x)$ compared to $\\edd(x)$ for Eddington accelerated S$_8$ with $\\Sigma_s/\\Sigma_t = 0.75$. }\n\t\t\\label{fig:conv_edd}\n\t\\end{figure}\n\n\t% add convergence rate of phi v edd \n\t% include discussion on acceleration v just doing 2 times as much work. ie actual acceleration is happening \n\n\\section{Conclusions}\n\tThe proposed acceleration scheme successfully accelerated S$_8$ source iteration calculations in slab geometry for a wide range of $\\Sigma_s/\\Sigma_t$. In the pure scattering regime ($\\Sigma_s = \\Sigma_t$), source iteration was accelerated by a factor of 750. This scheme is especially suited for multiphysics applications because the transport and acceleration steps do not need to be consistently differenced. In addition, the acceleration step produces a conservative solution that is computationally inexpensive compared to a transport sweep. Future work that will also be presented is the application of Eddington Acceleration to Linear Discontinuous Galerkin discretized \\SN. \n\n% \\section{Acknowledgments}\n\n\\bibliographystyle{ans}\n\\bibliography{../bibliography.bib}\n\\end{document}", "meta": {"hexsha": "622578a6fcb99298270e9801371e6a1ab769c8b7", "size": 14325, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/summary/ans.tex", "max_stars_repo_name": "smsolivier/rh", "max_stars_repo_head_hexsha": "a12da9464328b0fd1af0878a1f55aaf961f47e05", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-30T15:24:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-30T15:24:42.000Z", "max_issues_repo_path": "tex/summary/ans.tex", "max_issues_repo_name": "smsolivier/rh", "max_issues_repo_head_hexsha": "a12da9464328b0fd1af0878a1f55aaf961f47e05", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/summary/ans.tex", "max_forks_repo_name": "smsolivier/rh", "max_forks_repo_head_hexsha": "a12da9464328b0fd1af0878a1f55aaf961f47e05", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-10-22T00:02:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-02T08:58:46.000Z", "avg_line_length": 86.2951807229, "max_line_length": 755, "alphanum_fraction": 0.7418499127, "num_tokens": 3993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.5, "lm_q1q2_score": 0.32744736452106377}}
{"text": "\\chapter{Conclusion}\\label{chap:conclusion}\nIn order to combat the issue of contamination of publicly accessible water supplies, namely fecal contamination, the \\cp{} Biological Sciences Department teamed up with the \\cp{} Computer Science Department to build a library-based \\mst{} method, called \\cplop{}.\nUsing the \\ecoli{} isolated from fecal samples as \\fiblong{}, \\cp{} students pyrosequence the \\pcr{}-amplified \\itslong{} regions of the \\ecoli{} and store the resulting vector, called a \\pyro{}, in the \\cplop{} database for later retrieval, analysis, and comparison.\nThis thesis investigates two \\mst{} methodologies: a \\dbased{} clustering method built for \\cplop{} that clusters for \\bslongs{} in order to classify an unknown \\isol{} and the \\kraplong{} (\\krap{}), a set of four \\knnlong{} list resolution strategies for data with multiple \\compfuncs{}.\n\n\\section{Clustering for \\BSlongs{}}\n\nIn this paper, we study the accuracy of a clustering-based MST approach which scales significantly better: the bacterial isolate information stored in \\cplop{} is clustered using an efficient density-based clustering technique.\nIt clusters data by taking two parameters --- the minimum number of neighbors and an \\eps{} range that those neighbors must be within to form a cluster --- and performs range queries in a spatial index that performs \\bigo{\\log{n}} look-up on neighbors using a comparison metric.\nCompared to previous work \\cite{DBLP:conf/bibm/McGovernDKBVG15, montana2013ontological}, it requires fewer comparisons to other \\isols{} and computational resources, by being able to perform reasonably fast clusterings on a consumer laptop in minutes.\n\nTo ascertain how well this technique classifies, we build a notion of cluster purity.\nBy calculating the proportion of the entire cluster that the most-plural \\spec{} makes up, we hope to understand how a density-based clustering algorithm clusters the \\cplop{} data.\nFurthermore, we inspect coverage and overall accuracy.\n\nResults are that for \\minneigh{} between 1 and 5, respectively, we are able to cluster between 72.9\\% and 52.1\\% of the \\isols{} in \\cplop{}, with between 51.0\\% and 41.2\\% falling into pure clusters and another 34.4\\% to 43.8\\% falling into clusters where their \\spec{} is the most dominant. \nMost clusters have high purity and low number of unique species, which is promising for using this for \\mst{}.\nTransient strains are also visible in the clustering technique, which will further aid the biologists working on \\cplop{} in researching transient strains and improving \\mst{} techniques. \nFuture work will leverage other \\mst{} techniques designed for \\cplop{} against this to make up for the lack of coverage and transient strains.\n\\section{\\krap{} Effectiveness}\nGenerally, when using \\kNN{}, it is preferred to use single digit $k$ values. Through our investigation of these various \\kNN{} classification algorithms, we find that that general advice holds true. For our dataset, using $k\\geq5$ does not produce significantly different results. Choosing $k<5$ is a dangerous notion, since it is likely that an outlier may make its way into the \\knnlong{} list, confounding the results. Staying with $5\\leq k\\leq9$ appears to be a safe and reasonable option, providing a good balance between accuracy and filtering of isolates.\n\n%\\subsection{Choosing $\\alpha$}\nOutside of this study, we choose to differentiate between strains of \\ecoli{} using $\\alpha=0.99$. It appears that using this value is advantageous. There were, however, some exceptions to those results, motivating us to consider non-thresholded \\knnlong{} lists when classifying an unknown isolate.\n\n%\\subsection{Choosing a Resolution Algorithm}\nThe four resolution algorithms --- meanwise, winner, union, and intersection --- each have their own quirks and behaviors as we alter $k$ and $\\alpha$. \n\nMeanwise, which currently uses the Euclidean norm to resolve different metrics, did not respond to the $\\alpha$ threshold and completely stopped classifying anything for $\\alpha$ near 1. This is very likely due to Euclidean norm mapping $([0,1],\\dots,[0,1])\\rightarrow [0,\\sqrt{1+\\dots+1}]$. To get around this, we multiplied the resulting norm by a factor of $\\sqrt2$, which may have unexpected results. We may investigate this further, or choose a more natural norming method, like arithmetic or geometric mean. With no $\\alpha$ filtering, it performed third best with an overall 73.2\\% classification accuracy.\n\nWinner performs worst, classifying accurately between 65\\% and 68\\% of the time. Some alterations to this algorithm may make it more reliable, such as only counting the species that appear in all lists.\n\nUnionwise performs very well. Without filtering the \\knnlong{} lists by $\\alpha$, we find that the unionwise method classifies best, with an overall accuracy of 76.4\\%. However, once we add in $\\alpha$ filtering, the unionwise does not improve, staying relatively close to 76\\%. \n\nIntersection performs best when we use $\\alpha$. This is likely due to the ``list'' actually being a set of common isolates. Overall, the accuracy was 74.7\\%, 78\\%, and 85.9\\% for $\\alpha = $0.00 (no filtering), 0.98, and 0.99 respectively. \n\nOverall, we find that the intersection algorithm performs the best and recommend moving forward with it. While unionwise did perform well, it did not respond well to thresholding and still did not perform as well as the intersection algorithm overall. Meanwise and winner may be more useful with previously mentioned modifications and we may investigate these in the future.\n\n%The high performance of the intersection method is likely due to the fundamental structure and strain differentiation methods we use in CPLOP. Give the pyroprint of two \\ecoli{} cultures, a Pearson Correlation within 0.99 defines a strain. Restricting $\\alpha$ to values near this limit gave us better overall accuracy, since we get are allowed to search a wide distance around the \\isol{} to find \\isol{}s that mathch both regions, and we filter out \\isol{} that are a different strain. While we find that resolution by intersection is a very good method, we will likely still use variations of the other methods to aid in classification.\n\n%\\subsection{Species Representation}\nPoorly distributed representation of species and environmental incomparabilities are issues endemic to library-based MST. CPLOP has an overabundance of Cow and Human \\isol{}s, and an underrepresentation of many of the species in the database. This dilutes the \\knnlong{} list considerably for species like the Chicken and Cat. \n\nLibrary population issues aside, environmental limitations are another concern for accuracy. Nearly every sample in the library comes from a 30 mile radius around Cal Poly, making the collected \\pyro{}s potentially incomparable to \\pyro{}s collected from a different region.\n\n%Interestingly, environment factors in in another way, which our data shows about Bats . Classifying Bats is highly accurate and may be due to their limited involvement in other species' environment and small size. Cows have a wide variety of \\ecoli{} strains, which allows them to show up in many other species' \\knnlong{} lists. Bats on the other hand only have 37 \\isol{}s in CPLOP all from a single \\host{}, yet manage to be above 95\\%, regardless of the method. We hypothesize that this is due to their limited interaction and we may investigate further.\n\n\\section{Future Work}\nFuture work should incorporate \\krap{} into \\cplop{}, study the \\dbscan{} clustering method using the overall clustering entropy, and investigate whether combining the strain-based and \\isol{}-based approach improves \\mst{} and is more efficient on the \\cplop{} database.\nIncorporating \\krap{} into \\cplop{} will provide researchers the ability to make transparent, repeatable assertions as to the \\spec{} of an unknown \\isol{}.\nInvestigating clustering entropy can give us more insight into the makeup of clusters and extending this concept to \\krap{} classifications, to measure how ``close the competition is'' between \\spec{} in the \\knnlong{} lists.\nMerging strains into the \\krap{} methods will reduce the number of comparisons, since querying against the database will involve querying against clusters of \\isols{}, as opposed to \\isols{} themselves.\nWhether this benefits the accuracy of \\mst{} with \\cplop{} needs to be investigated.\n\n\\subsection{\\cplop{} Incorporation of \\krap{}}\nFuture work needs to incorporate \\krap{} into \\cplop{} directly, so \\cp{} researchers have direct access to the \\mst{} methodologies.\n\\cplop{} researchers showed interest in viewing the \\knnlong{} lists when using \\krap{} on an \\isol{}.\nBuilding an interactive \\mst{} workflow can give researchers a better insight into \\spec{} determinations and help them avoid having to painstakingly perform \\mst{} by hand.\nFuture work needs to at least make \\krap{} available to researchers in \\cplop{} and should consider building an visually interactive way of using it.\n\n\\subsection{Entropy}\nEntropy \\index{clustering entropy} is another validity measure that for clusterings, represents the ``degree to which each cluster consists of objects of a single class'' \\cite{tan2006introduction} and for \\krap{} can tell us how contentious the \\spec{} determination was.\nSimilar to the cluster and clustering purity, cluster and clustering entropy can give us an idea of the nature of \\bslongs{} created by a clustering method.\nIdeally, a good clustering method minimizes the clustering entropy.\n\nConsider a cluster $C$, consisting of datapoints with class labels from $\\mathcal{L}$.\nGiven a class label $L\\in\\mathcal{L}$, the value $P_C(L)$ calculates the proportion of datapoints in $C$ that have class label $L$.\nThe individual \\textit{cluster entropy} is:\n\\index{cluster entropy}\n\\begin{equation}\ne(C) = \\sum_{L\\in\\mathcal{L}}^{} P_C(L)\\log_2{P_C(L)}\n\\end{equation}\n\nIn addition to computing the entropy of individual clusters we want to have an understanding of the overall entropy on the entire dataset for a given clustering.\nAs before, given a \\textit{clustering} $\\mathcal{C} = \\{C_1,\\dots,C_n\\}$ on a dataset, we define the size $\\mathcal{M}$ of the set of clusters: \n\\index{clustering}\n\\begin{equation}\n\\mathcal{M} = \\sum_{i = 1}^{n} |C_i|\n\\end{equation}\nThe overall \\textit{clustering entropy} is:\n\\index{clustering entropy}\n\\begin{equation}\\label{eq:clustering:entropy}\n\\sum_{i=1}^{n} \\frac{|C_i|}{\\mathcal{M}}\\cdot\\nu(C_i)\n\\end{equation}\nOne can think of \\eqref{eq:clustering:entropy} as a form of weighted arithmetic mean of the individual entropies.\nLarger clusters, as a result, affect this overall value more.\nFuture work should use this metric to compare clusterings with different parameters or methodologies, seeking to minimize the entropy, and extend the analysis to \\krap{} classifications.\n\n\\subsection{\\kNClong{}}\nCombining the strain-based and \\isol{}-based method of classification is a natural next step.\nUsing \\krap{} as a simple fallback method when the strain-based method fails to classify an unknown \\spec{} \\isol{} is one approach.\nIncorporating strains directly into \\krap{} is yet another, wherein the neighbors in the \\knnlong{} list may be either \\isols{} or strains --- which we can represent as clusters.\nAs a result, we would instead have a \\kNClong{} classification algorithm, through which, we can still apply the resolution strategies from \\krap{}.\nFuture work should consider different cluster weighting methods for the \\spec{} in clusters that appear in the \\knnlong{} list and determine whether any of them are useful for \\mst{}.\n\n\\subsection{Efficiency Study}\nThe efficiency of the classification methodologies in this work and any combinations thereof needs to be investigated as well as their performance on the hardware that supports the \\cplop{} database.\nOffline determination of strains, be it through clustering or otherwise, can occur offline, speeding up the determination of strain membership during \\mst{}.\nCombining the two approaches in this work into a \\kNClong{} methodology may also speed up \\mst{}.\n\\kNN{}, and \\krap{} as a result, compares the unknown \\isol{} to every datapoint in the database, but if instead the datapoints might be clusters, fewer comparisons may need to be made.", "meta": {"hexsha": "386b22eb4a3250fab02263847ae27a328f4b809b", "size": 12267, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/conclusion/000.tex", "max_stars_repo_name": "jmcgover/thesis", "max_stars_repo_head_hexsha": "25664684158d00864dbe697276d2691ba84461cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/conclusion/000.tex", "max_issues_repo_name": "jmcgover/thesis", "max_issues_repo_head_hexsha": "25664684158d00864dbe697276d2691ba84461cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/conclusion/000.tex", "max_forks_repo_name": "jmcgover/thesis", "max_forks_repo_head_hexsha": "25664684158d00864dbe697276d2691ba84461cb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 122.67, "max_line_length": 640, "alphanum_fraction": 0.7810385587, "num_tokens": 2832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.5, "lm_q1q2_score": 0.32744736452106377}}
{"text": "\\chapter{Interpretations: 3rd generation squarks}\n    \\label{chapter:Interpretations}\n\nIn this chapter, the model independent upper limits on the visible cross section are presented for the monojet analysis.\nThe monojet results are then interpreted in terms of searches for new physics in different models with stops or sbottoms in the final state.\nWhen it is possible, these interpretations are then compared to the bounds set by other searches.\n\n\n\\section{Model independent upper limits}\n    \\label{sec:ModelIndependentLimits}\n\nThe agreement between the data and the Standard Model predictions for the different selections is interpreted in terms of model independent 95\\% confidence level (CL) upper limits on the visible cross section.\nThe visible cross section, $\\sigma_{\\text{vis}}$, is defined as:\n\n\\begin{equation}\n\\sigma_{\\text{vis}} = A\\times\\epsilon\\times\\sigma = N / L,\n\\label{eq:visibleXSec}\n\\end{equation}\n\n\\noindent where $\\sigma$ is the production cross section, $A$ is the acceptance of the selection (without considering detector effects), $\\epsilon$ is the experimental efficiency to select the signal events, $N$ are the expected events for the process and $L$ is the integrated luminosity.\n    \nValues of $\\sigma \\times A \\times \\epsilon$ in the range between 96~fb and 5.2~fb are excluded at 95\\% CL.\nThe limits are derived with pseudo-experiments and with the asymptotic approximation (see Chapter~\\ref{chapter:StatisticalModel}), leading to similar results with both approaches, as shown in Table \\ref{tab:modelIndependent}.\n\n\\begin{table}[tb]\n\\begin{center}\n\\begin{tabular}{cccccc}\n\\hline\n{\\bf Signal channel} & & $\\mathbf{\\langle A\\times\\epsilon\\times\\sigma\\rangle^{95}_\\text{\\textbf{obs}}\\,\\text{\\textbf{[fb]}}}$ & $\\mathbf{S^{95}_\\text{\\textbf{obs}}}$ & $\\mathbf{S^{95}_\\text{\\textbf{obs}}}$ & $\\mathbf{CL_b}$ \\\\\n\\hline\n\\multirow{2}{*}{M1} & asymp & $95.42$ & $1934.8$ & $1953.6^{847.2}_{291.7}$ & $0.49$ \\\\\n                    & toy   & $96.23$ & $1951.2$ & $1962.0^{839.8}_{319.3}$ & $0.49$ \\\\\n\\multirow{2}{*}{M2} & asymp & $28.67$ & $581.4$  & $596.9^{200.4}_{122.7} $ & $0.48$ \\\\\n                    & toy   & $28.36$ & $575.0$  & $590.6^{205.0}_{117.2} $ & $0.48$ \\\\\n\\multirow{2}{*}{M3} & asymp & $9.63$  & $195.3$  & $193.9^{68.8}_{54.1}$    & $0.49$ \\\\\n                    & toy   & $9.63$  & $195.3$  & $193.7^{68.7}_{53.2}$    & $0.49$ \\\\\n\\multirow{2}{*}{M4} & asymp & $13.16$ & $266.8$  & $262.4^{89.5}_{68.5}$    & $0.52$ \\\\\n                    & toy   & $13.22$ & $268.0$  & $264.4^{90.6}_{70.1}$    & $0.52$ \\\\\n\\multirow{2}{*}{M5} & asymp & $5.45$  & $110.5$  & $84.2^{33.0}_{23.3}$     & $0.79$ \\\\\n                    & toy   & $5.45$  & $110.5$  & $84.2^{33.0}_{23.3}$     & $0.79$ \\\\\n\\multirow{2}{*}{M6} & asymp & $5.22$  & $105.8$  & $61.7^{21.7}_{16.3}$     & $0.96$ \\\\\n                    & toy        & $5.22$  & $105.8$  & $61.9^{21.2}_{16.1}$     & $0.96$ \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\caption[Model independent 95\\% CL limits for the different signal regions.]{Observed and expected 95$\\%$ CL limits on the visible cross section, defined as cross sections times acceptance time efficiency for the different signal selections.}\n\\label{tab:modelIndependent}\n\\end{table}\n\n\n\\section{Notes on the computation of the limits}\n    \\label{sec:ComputationOfLimits}\n\nFor the models that will be studied in this chapter, the signal regions M1-M3 are considered (see Section~\\ref{sec:EventSelection}), and the one providing the best expected $CL_s$ (best exclusion) is used for the results that are reported.\n\nThe computation of the limits for these models is based on the profile likelihood method discussed in Section \\ref{sec:StatisticalTreatment}.\nA simultaneous fit of the MC expectations to the data in the signal and control regions is performed including statistical and systematic uncertainties.\nUncertainties on the signal acceptance times efficiency, the background predictions and the luminosity are considered, and correlations between systematic uncertainties on signal and background predictions are taken into account.\nThe fit accounts for any potential contamination of signal events in the control regions which a priory has been estimated to be very small.\n\nA statistical test is performed and the $CL_s$ value is computed for each signal model.\nThose signal models with a $CL_s<0.05$ are considered excluded.\nOnce the $CLs$ values are known for all the signal models generated, a linear interpolation between them in the parameter space is performed, so that a continuous exclusion plane can be generated.\n\n\n\\section{Signal samples simulation}\n    \\label{sec:SignalSimulation}\n\nThe stop pair production with $\\stoptocharm$ is simulated using {\\madgraph} with one additional jet from the matrix element and \\pythia-6 for the showering.\nCTEQ6L1 PDFs and AUET2B tune are used for the parton distribution functions and the simulation of the underlying event, respectively.\nCross sections are calculated to NLO in the strong coupling constant, adding the resummation of soft gluon emission at NLO+NLL accuracy.\nThe renormalization and factorization scales are set to the mass of the stop.\nThe samples are produced with stop masses between $\\unit[100]{GeV}$ and $\\unit[400]{GeV}$ and neutralino masses between $\\unit[70]{GeV}$ and $\\unit[390]{GeV}$.\nThe difference between the $\\stopone$ and the $\\ninoone$ masses, $\\Delta m$, varies between $\\unit[2]{GeV}$ and $\\unit[82]{GeV}$, in a maximum step size of $\\unit[30]{GeV}$. Cases in which $\\Delta m < \\unit[2]{GeV}$ have not been considered, since in this regime the stop can become long-lived, leading to different signatures, as for example, the one studied in Ref.~\\cite{Johansen:2010ac}.\n\nThe stop pair production with $\\stopfourbody$ is simulated with the same prescriptions as the $\\stoptocharm$ MC simulation.\nFor this process, samples with stop mass ranges between $\\unit[110]{GeV}$ and $\\unit[300]{GeV}$ and $\\Delta m$ that varies between $\\unit[10]{GeV}$ and $\\unit[80]{GeV}$ are produced.\n\nSamples with asymmetric decay are generated with $\\BR{\\stoptocharm}=0.5$ and $\\BR{\\stopfourbody}=0.5$ for stops with masses $\\unit[110]{GeV}$, $\\unit[200]{GeV}$, $\\unit[250]{GeV}$ and $\\unit[300]{GeV}$, and with $\\Delta m$ equal to $\\unit[10]{GeV}$ and $\\unit[80]{GeV}$.\nThese samples, combined with the $\\stoptocharm$ and $\\stopfourbody$ exclusive decays, allow to simulate different branching fraction scenarios.\n\nFinally, the sbottom pair production with $\\sbottomtob$ is simulated similarly, with sbottom masses between $\\unit[100]{GeV}$ and $\\unit[350]{GeV}$, and neutralino masses between $\\unit[1]{GeV}$ and $\\Delta m = \\unit[10]{GeV}$.\n\n\n\\section{Systematic uncertainties on the signal}\n    \\label{sec:SysUncertaintiesSignal}\n\nA complete study on systematic uncertainties, including both experimental and theoretical uncertainties, have been performed for each of the models studied.\nSimilar systematic effects have been found for all the models.\nHere, the uncertainties for the stop pair production model with $\\stoptocharm$ are presented.\n\nThe experimental uncertainties account for effects related to the estimation of the jet and $\\met$ reconstruction, energy scale and resolution, pileup and jet vertex fraction mismodeling, and the luminosity.\nThese uncertainties introduce variations in the signal yield of the order of 3\\% to 7\\% depending on the third generation squark and neutralino mass configuration, and the signal selection under consideration.\n\nThe theoretical uncertainties account for effects related to the modeling of the processes.\nThese uncertainties can affect either the acceptance or the cross section of the model.\nThe theoretical uncertainties on the acceptance are parametrized with nuisance parameters in the fit, in a similar way as the experimental uncertainties are modeled.\nInstead, a different procedure is followed to account for the theoretical uncertainties on the cross section.\nIn this case, the fit is performed three times, for the nominal and for the $\\pm 1 \\sigma$ variations on this uncertainty.\nThe theoretical uncertainties affecting the acceptance and the cross section are listed in Tables~\\ref{tab:signalsyst_mono} and~\\ref{tab:signalxsecuncert} respectively, and include:\n\n\\paragraph{Scale variations:} The uncertainties on the factorization and renormalization scales are the dominant theoretical uncertainties and affect mainly the cross section.\nThey are computed by varying both scales by factors two and one-half.\nThese uncertainties introduce variations between 13\\% and 15\\% on the cross section depending on the stop mass.\nThe effect of these uncertainties on the acceptance is found to be between 1\\% and 6\\% depending on the stop and neutralino mass configuration and the selection under consideration.\n\n\\paragraph{ISR/FSR:} The uncertainty on the modeling of the initial- and final-state radiation (ISR/FSR) is evaluated by varying the parameters that regulate the parton shower in a range that is consistent with the experimental data.\nAltogether, these uncertainties introduce a variation between 3\\% and 6\\% on the cross sections.\nThe uncertainty on the ISR also introduces variations on the acceptance up to 8\\% for configurations in which the masses of the stop and the neutralino are similar, whereas its effect is negligible for configurations in which this mass difference is large.\nThe FSR uncertainty introduces effects on the acceptance between 1\\% and 9\\% depending on the stop and neutralino mass configurations and the signal region under study.\n\n\\paragraph{PS to ME matching scale:}The impact in the signal yields from the variation of the parton shower to matrix element matching is also considered.\nThe parameters regulating this matching in the MC generator are varied by a factor of two up and down. \nThe effect of this uncertainty on the cross section can be up to 5\\%.\nThis systematic uncertainty also introduces an effect up to 10\\% on the signal acceptance, as the leading jet $\\pt$ and the $\\met$ requirements tighten.\n\n\\paragraph{PDF:} The uncertainty due to PDFs are evaluated using the Hessian method described in Ref.~\\cite{Pumplin:2001ct} with the PDF error sets associated with CTEQ6L1.\nThis uncertainty affects the cross section of the model up to 8\\%, while its effect is negligible in the acceptance.\n\n\\paragraph{}\n\n%--- \\ref{tab:signalsyst_mono}\n\\input{Interpretations/Tables/SignalAcceptanceUncertainties.tex}\n\n%--- \\ref{tab:signalxsecuncert}\n\\input{Interpretations/Tables/SignalXSecUncertainties.tex}\n\nThe $\\met$ distributions for the nominal samples and the samples with renormalization/factorization scale variations in the signal region M1 are shown in Figure~\\ref{fig:signalscalesysta6}.\nFigures~\\ref{fig:signalisrsysta6} (\\ref{fig:signalfsrsysta6}) show the impact of ISR (FSR) variations in the missing transverse energy.\nFinally, Figure~\\ref{fig:signalmlmsysta6} shows the $\\met$ distribution for the nominal sample and the samples with the matching scale variations.\n\n\\begin{figure}[tb]\n\\begin{center}\n  \\includegraphics[width=0.49\\textwidth]{Interpretations/Figures/stop_100_70_factScale.eps}\n  \\includegraphics[width=0.49\\textwidth]{Interpretations/Figures/stop_100_95_factScale.eps}\n  \\includegraphics[width=0.49\\textwidth]{Interpretations/Figures/stop_200_125_factScale.eps}\n  \\includegraphics[width=0.49\\textwidth]{Interpretations/Figures/stop_200_195_factScale.eps}\n\\end{center}\n\\caption[Impact of the renormalization/factorization scale uncertainties on several signal models.]{Impact of the renormalization/factorization scale uncertainties on the missing transverse\n  energy for a signal with a scalar\n  stop mass of $m_{\\tilde{t}}$ = 100\\,GeV\\ and LSP mass of\n  $m_{\\tilde{\\chi}^0_1}$ = 70\\,GeV\\ (top left), $m_{\\tilde{t}}$ = 100\\,GeV\\ and\n  $m_{\\tilde{\\chi}^0_1}$ = 95\\,GeV\\ (top right), $m_{\\tilde{t}}$ = 200\\,GeV\\ and\n  $m_{\\tilde{\\chi}^0_1}$ = 125\\,GeV\\ (bottom left) and $m_{\\tilde{t}}$ = 200\\,GeV\\ and\n  $m_{\\tilde{\\chi}^0_1}$ = 195\\,GeV\\ (bottom right).  All plots are\n  shown for signal region M1.} \n\\label{fig:signalscalesysta6}\n\\end{figure}\n\n\\begin{figure}[tb]\n\\begin{center}\n  \\includegraphics[width=0.49\\textwidth]{Interpretations/Figures/stop_100_70_Alpha_s.eps} \n  \\includegraphics[width=0.49\\textwidth]{Interpretations/Figures/stop_100_95_Alpha_s.eps} \n  \\includegraphics[width=0.49\\textwidth]{Interpretations/Figures/stop_200_125_Alpha_s.eps}\n  \\includegraphics[width=0.49\\textwidth]{Interpretations/Figures/stop_200_195_Alpha_s.eps}\n\\end{center}\n\\caption[Impact of the ISR uncertainty on several signal models.]{Impact of the ISR uncertainty on the missing transverse\n  energy for a signal with a scalar\n  stop mass of $m_{\\tilde{t}}$ = 100\\,GeV\\ and LSP mass of\n  $m_{\\tilde{\\chi}^0_1}$ = 70\\,GeV\\ (top left), $m_{\\tilde{t}}$ = 100\\,GeV\\ and\n  $m_{\\tilde{\\chi}^0_1}$ = 95\\,GeV\\ (top right), $m_{\\tilde{t}}$ = 200\\,GeV\\ and\n  $m_{\\tilde{\\chi}^0_1}$ = 125\\,GeV\\ (bottom left) and $m_{\\tilde{t}}$ = 200\\,GeV\\ and\n  $m_{\\tilde{\\chi}^0_1}$ = 195\\,GeV\\ (bottom right). All plots are\n  shown for signal region M1.}\n\\label{fig:signalisrsysta6}\n\\end{figure}\n\n\\begin{figure}[tb]\n\\begin{center}\n  \\includegraphics[width=0.49\\textwidth]{Interpretations/Figures/stop_100_70_FSR.eps} \n  \\includegraphics[width=0.49\\textwidth]{Interpretations/Figures/stop_100_95_FSR.eps} \n  \\includegraphics[width=0.49\\textwidth]{Interpretations/Figures/stop_200_125_FSR.eps}\n  \\includegraphics[width=0.49\\textwidth]{Interpretations/Figures/stop_200_195_FSR.eps}\n\\end{center}\n\\caption[Impact of the FSR uncertainty on several signal models.]{Impact of the FSR uncertainty on the missing transverse\n  energy for a signal with a scalar\n  stop mass of $m_{\\tilde{t}}$ = 100\\,GeV\\ and LSP mass of\n  $m_{\\tilde{\\chi}^0_1}$ = 70\\,GeV\\ (top left), $m_{\\tilde{t}}$ = 100\\,GeV\\ and\n  $m_{\\tilde{\\chi}^0_1}$ = 95\\,GeV\\ (top right), $m_{\\tilde{t}}$ = 200\\,GeV\\ and\n  $m_{\\tilde{\\chi}^0_1}$ = 125\\,GeV\\ (bottom left) and $m_{\\tilde{t}}$ = 200\\,GeV\\ and\n  $m_{\\tilde{\\chi}^0_1}$ = 195\\,GeV\\ (bottom right).  All plots are\n  shown for signal region M1.}\n\\label{fig:signalfsrsysta6}\n\\end{figure}\n\n\\begin{figure}[tb]\n\\begin{center}\n  \\includegraphics[width=0.49\\textwidth]{Interpretations/Figures/stop_100_70_Q.eps} \n  \\includegraphics[width=0.49\\textwidth]{Interpretations/Figures/stop_100_95_Q.eps} \n  \\includegraphics[width=0.49\\textwidth]{Interpretations/Figures/stop_200_125_Q.eps}\n  \\includegraphics[width=0.49\\textwidth]{Interpretations/Figures/stop_200_195_Q.eps}\n\\end{center}\n\\caption[Impact of the MLM matching scale uncertainty on several signal models.]{Impact of the matrix element to parton shower matching scale uncertainty on the missing transverse energy for a signal with a scalar\n  stop mass of $m_{\\tilde{t}}$ = 100\\,GeV\\ and LSP mass of\n  $m_{\\tilde{\\chi}^0_1}$ = 70\\,GeV\\ (top left), $m_{\\tilde{t}}$ = 100\\,GeV\\ and\n  $m_{\\tilde{\\chi}^0_1}$ = 95\\,GeV\\ (top right), $m_{\\tilde{t}}$ = 200\\,GeV\\ and\n  $m_{\\tilde{\\chi}^0_1}$ = 125\\,GeV\\ (bottom left) and $m_{\\tilde{t}}$ = 200\\,GeV\\ and\n  $m_{\\tilde{\\chi}^0_1}$ = 195\\,GeV\\ (bottom right).  All plots are\n  shown for signal region M1.}\n\\label{fig:signalmlmsysta6}\n\\end{figure}\n\n\n\\clearpage\n\\section{Direct stop pair production}\n    \\label{sec:DirectStopProduction}\n\nThe results of the monojet analysis are translated into exclusion limits on the pair production of top squarks as a function of the stop mass for different neutralino masses.\n\n\n\\subsection{Stop decaying to a charm quark and a neutralino}\n\nIn this model, each top squark produced is assumed to decay in a charm-quark and a neutralino, $\\stoptocharm$, with a branching fraction of $100\\%$.\nA Feynman diagram for this process is shown in Figure~\\ref{fig:Diagrams3rdGen} (left).\nThis final state is characterized by the presence of two jets from the hadronization of the charm quarks, and missing transverse energy from the two undetected LSPs.\nHowever, given the relatively small difference between the stop and the neutralino masses, $\\Delta m$, both the transverse momenta of the two charm jets and the $\\met$ are low, making it very difficult to extract the signal from the large multijet background.\nInstead, the presence of initial-state radiation jets is required to boost the squark-pair, leading to larger $\\met$.\n\nThe monojet analysis is expected to be sensitive in the very low $\\Delta m$ region of the phase space, where the charm jets are not boosted enough to be detected.\nFigure~\\ref{fig:modelIndependent} shows the fiducial cross section, $\\sigma\\times A \\times \\epsilon$, as a function of the mass of the stop for different $\\Delta m$ configurations in each selection.\nFor illustration, the model independent limits from Table~\\ref{tab:modelIndependent} are included.\nThe stop and neutralino mass configurations excluded by the monojet analysis can already be approximately inferred from this figure.\n\n\\begin{figure}[!ht]\n  \\begin{center}\n    \\mbox{\n      \\includegraphics[width=0.495\\textwidth]{MonojetAnalysis/Figures/ModelIndependent_Stop_M1.eps}\n      \\includegraphics[width=0.495\\textwidth]{MonojetAnalysis/Figures/ModelIndependent_Stop_M2.eps}\n    }\n    \\mbox{\n      \\includegraphics[width=0.495\\textwidth]{MonojetAnalysis/Figures/ModelIndependent_Stop_M3.eps}\n      \\includegraphics[width=0.495\\textwidth]{MonojetAnalysis/Figures/ModelIndependent_Stop_M4.eps}\n    }\n    \\mbox{\n      \\includegraphics[width=0.495\\textwidth]{MonojetAnalysis/Figures/ModelIndependent_Stop_M5.eps}\n      \\includegraphics[width=0.495\\textwidth]{MonojetAnalysis/Figures/ModelIndependent_Stop_M6.eps}\n    }\n  \\end{center}\n  \\caption[Model independent 95\\% CL limits for the different signal regions.]{Observed and expected 95\\% CL model independent limits on the visible cross section for the regions M1-M6 compared to the $\\stoptocharm$ predictions as a function of the stop mass for different $\\Delta m$.}\n  \\label{fig:modelIndependent}\n\\end{figure}\n\nThe 95\\% CL limits on this model are computed with the $CL_s$ method described in Section~\\ref{sec:ComputationOfLimits}, which properly accounts for the correlations on the systematic uncertainties among the different signal and background processes.\nObserved and expected limits are computed separately in the different signal regions, and the one with best expected limit is adopted as the nominal result.\nThe signal region that gives the best expected limit for each stop and neutralino mass is shown in Figure~\\ref{fig:ExclusionStoptocharm} (top).\nThe selection M1 drives the exclusion limits for low stop masses, while M2 and M3 enhance the sensitivity for very low $\\Delta m$ as the stop mass increases.\nFigure~\\ref{fig:ExclusionStoptocharm} (bottom) shows the exclusion plane at 95\\% CL for the stop pair production with $\\stoptocharm$ as a function of the $m_{\\stop}$ and $m_{\\ninoone}$.\nThe 95\\% CL observed limits corresponding to the $\\pm 1 \\sigma$ variations on the SUSY theoretical cross sections are also added.\nIn the region of phase space where the stop and the neutralino masses are almost degenerated, stop masses up to $\\unit[260]{GeV}$ are excluded.\nThe sensitivity of the analysis reduces as the $\\Delta m$ increases, as a consequence of the maximum jet multiplicity requirement in the monojet selection.\nLarge $\\Delta m$ scenarios can be excluded if the mass of the stop is smaller than $\\unit[170]{GeV}$.\nThese results significantly extend the previous exclusion limits from LEP~\\cite{Aaltonen:2012tq} and CDF~\\cite{Abazov:2008rc} in this channel, as shown in the figure.\n\n\\begin{figure}[!ht]\n\\begin{center}\n\\mbox{\n\\includegraphics[width=0.795\\textwidth]{Interpretations/Figures/limitPlotStop_Stop_combined_M1_M2_M3_BestRegion.eps}\n}\n\\mbox{\n\\includegraphics[width=0.795\\textwidth]{Interpretations/Figures/limitPlotStop_Stop_combined_M1_M2_M3_.eps}\n}\n\\end{center}\n\\caption[Exclusion plane at 95\\% CL for stop pair production with $\\stoptocharm$ as a function of the $m_{\\stop}$ and $m_{\\ninoone}$, combining the selections M1 to M3.]{Exclusion plane at 95\\% CL as a function of stop and neutralino masses. The observed (red line) and expected (blue line) upper limits from this analysis are compared to previous results from Tevatron experiments~\\cite{Abazov:2008rc}, and from LEP experiments~\\cite{Aaltonen:2012tq} at CERN with squark mixing angle $\\theta=0^{\\circ}$. The dotted lines around the observed limit indicate the range of observed limits corresponding to $\\pm 1 \\sigma$ variations on the NLO SUSY cross section predictions. The shaded area around the expected limit indicates the expected $\\pm 1 \\sigma$ ranges of limits in the absence of a signal. A band for $m_{\\stopone} - m_{\\ninoone}< \\unit[2]{GeV}$ indicates the region in the phase space for which the stop can become long-lived \\protect\\cite{Aad:2014nra}.}\n\\label{fig:ExclusionStoptocharm}\n\\end{figure}\n\nThe monojet analysis results can be combined with the results of a dedicated analysis optimized for moderate $\\Delta m \\gt \\unit[20]{GeV}$.\nIn this regime, the charm jets receive a large enough boost to be detected.\nFor this reason, in addition to the requirements on the presence of an initial-state radiation, the identification of jets containing the decay products of charm hadrons is used.\nThis analysis is referred as ``charm-tagged'', and is detailed in Ref.~\\cite{Aad:2014nra}.\nIn this region of the phase space, the charm-tagged C1 and C2 selections (see Appendix~\\ref{app:CharmTaggedAnalysis}) give the best expected limits, as Figure~\\ref{fig:ExclusionStoptocharmCombinedAll} (top) indicates.\nThe combination of both analyses leads to the exclusion limits shown in Figure~\\ref{fig:ExclusionStoptocharmCombinedAll} (bottom).\nThe charm-tagged analysis complements the monojet analysis and increases the exclusion region for moderate and large $\\Delta m$.\nAfter the combination, masses for the stop up to 240~GeV are excluded at 95\\%~CL for arbitrary neutralino masses, within the kinematic boundaries.\nFor neutralino masses of about 200~GeV, stop masses below 270~GeV are excluded at 95\\%~CL.\n\n\\begin{figure}[!ht]\n\\begin{center}\n\\mbox{\n\\includegraphics[width=0.795\\textwidth]{Interpretations/Figures/limitPlotStop_Stop_combined_M1_M2_M3_C1_C2_BestRegion.eps}\n}\n\\mbox{\n\\includegraphics[width=0.795\\textwidth]{Appendix_CharmTagged/Figures/limitPlotStop_Stop_combined_M1_M2_M3_C1_C2_.eps}\n}\n\\end{center}\n\\caption[Exclusion plane at 95\\% CL for stop pair production with $\\stoptocharm$ as a function of the $m_{\\stop}$ and $m_{\\ninoone}$, combining the monojet and the charm-tagged approaches]{Exclusion plane at 95\\% CL as a function of stop and neutralino masses for the monojet and charm-tagged approaches (see Appendix~\\ref{app:CharmTaggedAnalysis}), combined. The observed (red line) and expected (blue line) upper limits from this analysis are compared to previous results from Tevatron experiments~\\cite{Abazov:2008rc}, and from LEP experiments~\\cite{Aaltonen:2012tq} at CERN with squark mixing angle $\\theta=0^{\\circ}$. The dotted lines around the observed limit indicate the range of observed limits corresponding to $\\pm 1 \\sigma$ variations on the NLO SUSY cross section predictions. The shaded area around the expected limit indicates the expected $\\pm 1 \\sigma$ ranges of limits in the absence of a signal. A band for $m_{\\stopone} - m_{\\ninoone}< \\unit[2]{GeV}$ indicates the region in the phase space for which the stop can become long-lived \\protect\\cite{Aad:2014nra}.}\n\\label{fig:ExclusionStoptocharmCombinedAll}\n\\end{figure}\n\n\n\\subsection{Stop decaying to a $b$-quark, two fermions and a neutralino}\n\nThe monojet results are also interpreted in terms of exclusion limits on the stop pair production, with each stop decaying into a bottom quark, two fermions (either leptons or quarks) and a neutralino, $\\stopfourbody$, with 100\\% branching fraction.\nThe Feynman diagram for this process are shown in Figure~\\ref{fig:Diagrams3rdGen} (center).\nThe exclusion limits are computed with the same $CL_s$ approach used above, with the region giving the best expected $CL_s$ taken as the nominal.\nThe selections M1 to M3 are combined, as indicated in Figure~\\ref{fig:ExclusionStopToFourbody} (top)\n\nFigure \\ref{fig:ExclusionStopToFourbody} (bottom) presents the 95\\% CL limits as a function of the stop and neutralino masses.\nStop masses up to $\\unit[255]{GeV}$ can be excluded.\nThis result is similar to the exclusion found for the $\\stoptocharm$ decay, since in a mass-degenerated scenario the decay products of the squarks are too soft to be identified in the final state, and the signal selection only relies on the presence of an ISR jet.\nFor large $\\Delta m$, the bottom jets and the fermions receive a larger boost, which allows them to be detected.\nThe increase in the fermion multiplicity decreases the sensitivity of the monojet analysis to this final state, due to the jet multiplicity requirement and the lepton veto in the selection.\n\n\\begin{figure}[!ht]\n\\begin{center}\n\\mbox{\n\\includegraphics[width=0.795\\textwidth]{Interpretations/Figures/limitPlotFourBody_Stop_combined_M1_M2_M3_BestRegion.eps}\n}\n\\mbox{\n\\includegraphics[width=0.795\\textwidth]{Interpretations/Figures/limitPlotFourBody_Stop_combined_M1_M2_M3_.eps}\n}\n\\end{center}\n\\caption[Exclusion plane at 95\\% CL for stop pair production with $\\stopfourbody$ as a function of the $m_{\\stop}$ and $m_{\\ninoone}$]{Exclusion plane at 95\\% CL as a function of stop and neutralino masses for the decay channel $\\stopfourbody$ (BR=100\\%). The dotted lines around the observed limit indicate the range of observed limits corresponding to $\\pm 1 \\sigma$ variations on the NLO SUSY cross section predictions. The shaded area around the expected limit indicates the expected $\\pm 1 \\sigma$ ranges of limits in the absence of a signal. A band for $m_{\\stopone} - m_{\\ninoone}< \\unit[2]{GeV}$ indicates the region in the phase space for which the stop can become long-lived \\protect\\cite{Aad:2014nra}.}\n\\label{fig:ExclusionStopToFourbody}\n\\end{figure}\n\n\n\\subsection{Mixed scenarios}\n\nThe exclusion limits shown in Figures \\ref{fig:ExclusionStoptocharm} and \\ref{fig:ExclusionStopToFourbody} are produced assuming a 100\\% branching ratio to $\\stoptocharm$ and $\\stopfourbody$, respectively.\nIn the following, the monojet analysis is interpreted in terms of stop pair production, considering the stops decays $\\stoptocharm$ or $\\stopfourbody$, with different branching ratios, and assuming that $\\text{BR}(\\stoptocharm)$ + $\\text{BR}(\\stopfourbody)$ = 1.\nFor this purpose, new samples are generated, following the prescriptions detailed in Section~\\ref{sec:MCSamples}, and assuming each stop to decay in a different final state.\nThe expected number of events for a model with a $\\text{BR}(\\stoptocharm) = \\alpha$ can be computed with the following expression:\n\n\\begin{equation}\n\\begin{split}\nN_{\\alpha} &= \\alpha^2 N_{\\stopone\\stopone \\;\\rightarrow \\;c\\ninoone \\; c\\ninoone} + 2\\alpha(1-\\alpha)N_{\\stopone\\stopone \\;\\rightarrow \\;c\\ninoone \\; bff'\\ninoone} \\\\\n&+ (1-\\alpha)^2 N_{\\stopone\\stopone \\;\\rightarrow \\;bff'\\ninoone \\;bff'\\ninoone},\n\\end{split}\n\\label{eq:MixedSamplesCombination}\n\\end{equation}\n\n\\noindent where $N_{\\stopone\\stopone \\;\\rightarrow \\;c\\ninoone \\; c\\ninoone}$, $N_{\\stopone\\stopone \\;\\rightarrow \\;c\\ninoone \\; bff'\\ninoone}$, and $N_{\\stopone\\stopone \\;\\rightarrow \\;bff'\\ninoone \\;bff'\\ninoone}$ are the number of events from the stop pair production assuming BR$(\\stoptocharm)=1$, BR$(\\stopfourbody)=1$, and $\\text{BR}(\\stoptocharm) = \\text{BR}(\\stopfourbody) = 0.5$, respectively.\n\nFigure \\ref{fig:ExclusionMixed} shows the 95\\% CL upper cross section limits as a function of the stop mass and the branching fractions (red lines) for two different $\\Delta m$ configurations.\nThese upper limits can be compared to the nominal $\\stopone$ pair production cross section (blue line).\n\n\\begin{figure}[!t]\n\\begin{center}\n\\mbox{\n\\includegraphics[width=0.795\\textwidth]{Interpretations/Figures/upperLimitXSectionBR_Stop_dM_10_M1_M2_M3.eps}\n}\n\\mbox{\n\\includegraphics[width=0.795\\textwidth]{Interpretations/Figures/upperLimitXSectionBR_Stop_dM_80_M1_M2_M3.eps}\n}\n\\end{center}\n\\caption[Upper limits on the stop pair production cross section at 95\\% CL as a function of $m_{\\stopone}$ for different branching ratios.]{95\\% CL upper cross section limits as a function of the stop mass (in red) compared to the $\\stopone$ pair nominal cross section (in blue). $\\Delta m = \\unit[10]{GeV}$ and $\\Delta m = \\unit[80]{GeV}$ models are considered in the top and bottom figures respectively.}\n\\label{fig:ExclusionMixed}\n\\end{figure}\n\nWhen $\\Delta m = \\unit[10]{GeV}$, the available phase space for the products of the stop decay is reduced, and thus the selection relies only on the production of an ISR jet.\nThe exclusion is independent on the branching ratio, when the stop and the neutralino are almost degenerated in mass.\nInstead, when $\\Delta m = \\unit[80]{GeV}$ the Standard Model decay products of each stop are boosted enough to be reconstructed.\nThe $\\stopfourbody$ decay of the stop is more affected by the jet multiplicity requirement and the lepton vetoes, than the $\\stoptocharm$.\nFor this reason, less stringent limits on the mass of the stop can be set, as the branching ratio to $\\stopfourbody$ increases.\n\n\n\\section{Direct sbottom pair production}\n    \\label{sec:DirectSbottomProduction}\n\nIn the case of bottom squark pair production, it is assumed a SUSY particle mass hierarchy such that the sbottom decays exclusively into a bottom quark and a neutralino, $\\sbottomtob$.\nFigure~\\ref{fig:Diagrams3rdGen} (right) shows a Feynman diagram for this decay.\nThe expected signal for the direct sbottom pair is characterized by the presence of two energetic jets from the hadronization of the bottom quarks and large $\\met$ from the two LSPs in the final state.\nThe monojet results are interpreted in terms of this search, $\\sbottomtob$, in compressed scenarios.\nThe sbottom and the neutralino masses are almost degenerated, leading to two soft $b$-jets and an energetic ISR in the final state.\n\nSignal regions M1 to M3 are used, and for each mass point the one with best expected $CL_s$ is chosen, as shown in Figure~\\ref{fig:ExclusionSbottomtob} (top).\nFigure \\ref{fig:ExclusionSbottomtob} (bottom) shows the exclusion limits at 95\\% CL for the $\\sbottomtob$ model, as a function of the sbottom and neutralino masses.\nThe fact that the exclusion for very low or very high $\\Delta m$ is better than for medium $\\Delta m$ has to do with the acceptance, with the negotiation between mass and momentum investment for the neutralino, and the phase space available for extra radiation.\nThe cross section is independent of the $\\Delta m$ for fixed sbottom masses, so the $CL_s$ values for the different mass configurations depend exclusively on acceptance and efficiency.\nFor all neutralino masses, the sbottoms are boosted by an initial-state radiation.\nScenarios with small $\\Delta m$ (large neutralino mass), are characterized by soft $b$-jets (hardly ever identified) and little extra ISR/FSR.\nAs the mass of the neutralino decreases (medium $\\Delta m$), the two $b$-jets are reconstructed and there is more phase space available for extra jet radiations.\nTherefore, more events fail the jet veto selection and the sensitivity of the monojet analysis to this region of the phase space decreases.\nFor large $\\Delta m$ configurations (low neutralino masses), the loss of sensitivity due to extra jet radiation is compensated by the increase in $\\met$ due to the highly boosted neutralinos.\n\nSbottom masses below $\\unit[180]{GeV}$ can be excluded for arbitrary neutralino masses.\nIn the case of sbottom and neutralino degenerated in mass, this analysis excludes sbottom masses up to $\\unit[255]{GeV}$, thus expanding the exclusion limits set by other searches \\cite{Aaltonen:2010dy,Abazov:2010wq,Aad:2013ija}.\nFor very low neutralino masses, the analysis also excludes sbottom masses up to $\\unit[255]{GeV}$.\n\n\n\\begin{figure}[!ht]\n\\begin{center}\n\\mbox{\n\\includegraphics[width=0.795\\textwidth]{Interpretations/Figures/limitPlotSbottom_Stop_combined_M1_M2_M3_BestRegion.eps}\n}\n\\mbox{\n\\includegraphics[width=0.795\\textwidth]{Interpretations/Figures/limitPlotSbottom_Stop_combined_M1_M2_M3_.eps}\n}\n\\end{center}\n\\caption[Exclusion plane at 95\\% CL for sbottom pair production with $\\sbottomtob$ as a function of the $m_{\\sbottom}$ and $m_{\\ninoone}$]{Exclusion plane at 95\\% CL as a function of sbottom and neutralino masses for the decay channel $\\sbottomtob$ (BR=100\\%). The observed (red line) and expected (blue line) upper limits from this analysis are compared to previous results from CDF~\\cite{Aaltonen:2010dy}, D0~\\cite{Abazov:2010wq}, and ATLAS~\\cite{Aad:2013ija}. For the latter, the area below the dashed-dotted line is excluded. The dotted lines around the observed limit indicate the range of observed limits corresponding to $\\pm 1 \\sigma$ variations on the NLO SUSY cross section predictions. The shaded area around the expected limit indicates the expected $\\pm 1 \\sigma$ ranges of limits in the absence of a signal. A band for $m_{\\sbottomone} - m_{\\ninoone}< \\unit[2]{GeV}$  indicates the region in the phase space for which the sbottom can become long-lived. \\protect\\cite{Aad:2014nra}.}\n\\label{fig:ExclusionSbottomtob}\n\\end{figure}\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\cleardoublepage\n\\chapter{Interpretations: inclusive squarks or gluinos}\n    \\label{chapter:SquarkGluinoProduction}\n\nThis chapter presents the interpretation of the monojet analysis in terms of models involving the direct production of inclusive squarks, or gluinos.\nOnly the signal regions M1 to M3 are considered, and the one giving the best expected exclusion is used for the results.\n\n\n\\section{Inclusive squark pair production}\n    \\label{sec:InclusiveSquarkProduction}\n\nThis section presents the interpretation of the analysis in terms of pair production of degenerated light-flavour squarks, with each squark decaying into a light quark and a neutralino (see Figure \\ref{fig:DiagramsInclusiveProduction} left).\nThe MC samples for this model have been simulated with \\madgraph{} and \\pythia{}, using the PDF set CTEQ6L1.\nThe renormalization and factorization scales are set to the mass of the mean mass of the participating particles, $Q=(m_{\\squark}+m_{\\gluino})/2$.\nThe AUET2B tune has been used for the simulation of the underlying event, while the MLM matching scheme is used with up to one additional jet in the \\madgraph{} matrix element.\nMore detailed information on these samples can be found in Ref.~\\cite{Aad:2014wea}.\nDifferent mass points have been generated for this process, in a grid with squark masses ranging between $\\unit[87]{GeV}$ and $\\unit[1225]{GeV}$, and neutralino masses between $\\unit[0]{GeV}$ and those corresponding to a $\\Delta m = m_{\\squark} - m_{\\ninoone}$ equal to $\\unit[10]{GeV}$.\nThe signal cross sections are calculated to NLO in the strong coupling constant, adding the resummation of soft gluon emission at next-to-leading-logarithmic pQCD accuracy (NLO+NLL).\n\nExperimental and theoretical systematic uncertainties for the different mass configurations have been computed, as explained in Section~\\ref{sec:SysUncertaintiesSignal}.\nFigure~\\ref{fig:signalAcceptanceSquark} shows the impact of the scale variations on the signal acceptance for different squark masses as a function of $\\Delta m$.\nThe uncertainties on the factorization and renormalization scales can be modeled as shown in Ref.~\\cite{Aad:2014wea}.\nThe validity of this parametrization, shown in the figure by the dashed blue line, has been carefully checked for the monojet analysis, and is finally adopted.\nIn the case of the matching scale uncertainty, a flat 10\\% is considered, based on the studies from Fig.~\\ref{fig:signalAcceptanceSquark} (right).\nAltogether, the systematic uncertainty on the acceptance for the signal is parametrized as:\n\n\\begin{equation}\n\\left(\\frac{\\Delta N}{N}\\right)_{\\text{signal}} = 0.15 \\times e^{-{\\Delta m / 250}} \\oplus 0.20 \\times e^{-{\\Delta m / 250}} \\oplus 0.1.\n\\label{eq:systematicAcceptanceSquark}\n\\end{equation}\n\n\\begin{figure}[t!]\n\\begin{center}\n\\includegraphics[width=0.32\\textwidth]{Interpretations/Figures/signalUncert_mu_M1.eps}\n\\includegraphics[width=0.32\\textwidth]{Interpretations/Figures/signalUncert_Q_M1.eps}\n\\includegraphics[width=0.32\\textwidth]{Interpretations/Figures/signalUncert_Matching_M1.eps}\n\\end{center}\n\\caption[Parametrization of the theoretical systematic uncertainties for the squark pair production when $\\squarktoq$.]{The red points show the impact of (left) renormalization/factorization $\\mu$, (center) $Q(\\alpha _s)$ and (right) matching scales used in \\madgraph{}+\\pythia{} on the number of expected events $N$ for a simplified model with $\\squark$ pair production (\\squark$\\rightarrow q+$\\ninoone). The relative effect $\\Delta N/N$ after proper normalization to the same total cross section is shown as a function of $\\Delta m = m_{\\tilde{q}} - m_{\\tilde{\\chi}_1^0}$. The dashed lines show the parameterization used to compute the uncertainties on the signal acceptance~\\cite{Aad:2014wea}. The points in black and green show similar measurements in the monojet M1 signal region done with \\madgraph{} samples for the low $\\Delta m$ points used in the monojet-like analysis.}\n\\label{fig:signalAcceptanceSquark}\n\\end{figure}\n\n\n\\subsection{Exclusion Limits at 95\\% CL}\n\nThe exclusion limits at 95\\% CL for the first- and second-generation squark pair production are shown in Figure~\\ref{fig:ExclusionSquarktoq}, as a function of the squark and neutralino masses.\nThe shape of the exclusion is related to the acceptance of the monojet analysis for each mass configuration, and follows the same arguments as for the sbottom pair production with $\\sbottomtob$, shown in Section~\\ref{sec:DirectSbottomProduction}.\n\nSquark masses up to $\\unit[320]{GeV}$ are excluded at 95\\% CL for arbitrary neutralino masses.\nFor very compressed scenarios, the monojet analysis excludes squark masses up to $\\unit[440]{GeV}$, thus extending the exclusion limits of the analysis in Ref.~\\cite{Aad:2014wea} and shown in the figure.\nMasses up to $\\unit[660]{GeV}$ are also excluded for neutralino masses below 20~GeV.\n\n\n\\begin{figure}[!t]\n  \\begin{center}\n    \\mbox{\n      \\includegraphics[width=0.795\\textwidth]{Interpretations/Figures/limitPlotSquark_Stop_combined_M1_M2_M3_.eps}\n    }\n  \\end{center}\n  \\caption[Exclusion plane at 95\\% CL for sbottom pair production with $\\squarktoq$ as a function of the $m_{\\squark}$ and $m_{\\ninoone}$]{Exclusion plane at 95\\% CL as a function of the squark and neutralino masses for the $\\squarktoq$ process. The dotted lines around the observed limit indicate the range of observed limits corresponding to the $\\pm 1 \\sigma$ variations on the cross section predictions. The shaded area around the expected limit indicates the expected $\\pm 1 \\sigma$ ranges of limits in the absence of a signal.\n  The upper limits from this analysis are also compared to the previous results from ATLAS~\\cite{Aad:2014wea}, shown in the figure with a dot-dashed red line.}\n  \\label{fig:ExclusionSquarktoq}\n\\end{figure}\n\n\n\\section{Gluino pair production}\n    \\label{sec:GluinoProduction}\n\nSimilarly, the results have been interpreted in terms of final states involving the production of pairs of gluinos.\nTwo different decay modes of the gluino have been considered.\nFirst, the gluino is assumed to decay with 100\\% branching fraction into a bottom quark and a virtual sbottom, which then decays into another bottom quark plus a neutralino, $\\gluinotobb$.\nIn the second decay mode under consideration, the gluino decays exclusively to a gluon and a neutralino, $\\gluinotog$, via a loop in which the interchange of a quark is involved.\nThe Feynman diagrams for both processes are shown in the middle and right panes of Figure~\\ref{fig:DiagramsInclusiveProduction}.\nThe calculation of experimental and theoretical uncertainties follows the procedure explained in Section~\\ref{sec:SysUncertaintiesSignal}.\n\n\n\\subsection{Gluino decaying to two $b$-quarks and a neutralino}\n\nSamples for gluino pair production with $\\gluinotobb$ have been simulated using \\madgraph{} with one additional jet from matrix element and \\pythia{-6} for the showering, following the same prescriptions as for the $\\squarktoq$ simulated samples.\nA grid of points with the gluino mass between $\\unit[200]{GeV}$ to $\\unit[1600]{GeV}$ and neutralino masses between $\\unit[1]{GeV}$ and values corresponding to a $\\Delta m = \\unit[25]{GeV}$ has been produced.\n\nThe 95\\% CL exclusion limits as a function of the gluino and neutralino masses are shown in Figure~\\ref{fig:ExclusionGluinoGbb}.\nThe monojet analysis allows to expand the excluded parameter space in Ref.~\\cite{TheATLAScollaboration:2013tha} towards compressed gluino and neutralino mass configurations.\nGluino masses up to $\\unit[580]{GeV}$ can be excluded for low $\\Delta m = m_{\\gluino} - m_{\\ninoone}$ values.\nAs the difference between the gluino and neutralino masses increases, the bottom quarks from the gluino decays are more boosted and the $b$-jets can be reconstructed.\nTherefore, the analysis looses sensitivity to these configurations due to the jet veto requirement in the selections.\nGluino masses up to $\\unit[420]{GeV}$ are excluded for very low neutralino masses.\n\n\\begin{figure}[!ht]\n  \\begin{center}\n    \\mbox{\n      \\includegraphics[width=0.795\\textwidth]{Interpretations/Figures/limitPlotGluinoGbb_Stop_combined_M1_M2_M3_.eps}\n    }\n  \\end{center}\n  \\caption[Exclusion plane at 95\\% CL for gluino pair production with $\\gluinotobb$ as a function of the $m_{\\gluino}$ and $m_{\\ninoone}$]{Exclusion plane at 95\\% CL as a function of the gluino and neutralino masses for the $\\gluinotobb$ process. The dotted lines around the observed limit indicate the range of observed limits corresponding to the $\\pm 1 \\sigma$ variations on the cross section predictions. The shaded area around the expected limit indicates the expected $\\pm 1 \\sigma$ ranges of limits in the absence of a signal.\n  The upper limits from this analysis are also compared to the previous results from ATLAS~\\cite{TheATLAScollaboration:2013tha}, shown in the figure with a dot-dashed red line.}\n  \\label{fig:ExclusionGluinoGbb}\n\\end{figure}\n\n\n\\subsection{Gluino decaying to a gluon and a neutralino}\n\nFinally, a second grid for gluino pair production with $\\gluinotog$ has been produced with the same prescriptions as the $\\gluinotobb$ samples.\nThe production consists of several samples with gluino masses between $\\unit[150]{GeV}$ and $\\unit[1500]{GeV}$, and neutralino masses between $\\unit[0]{GeV}$ and values corresponding to $\\Delta m = \\unit[50]{GeV}$.\nFigure \\ref{fig:ExclusionGluinoGg} shows the 95\\% CL exclusion plane as a function of the gluino and neutralino masses.\nGluinos with masses up to 600~GeV are excluded at 95\\% CL for the very compressed scenario.\nFor massless neutralinos, gluino masses up to 850~GeV can be excluded.\n\n\\begin{figure}[!ht]\n  \\begin{center}\n    \\mbox{\n      \\includegraphics[width=0.795\\textwidth]{Interpretations/Figures/limitPlotGluinoGg_Stop_combined_M1_M2_M3_.eps}\n    }\n  \\end{center}\n  \\caption[Exclusion plane at 95\\% CL for gluino pair production with $\\gluinotog$ as a function of the $m_{\\gluino}$ and $m_{\\ninoone}$]{Exclusion plane at 95\\% CL as a function of the gluino and neutralino masses for the $\\gluinotog$ process. The dotted lines around the observed limit indicate the range of observed limits corresponding to the $\\pm 1 \\sigma$ variations on the cross section predictions. The shaded area around the expected limit indicates the expected $\\pm 1 \\sigma$ ranges of limits in the absence of a signal.}\n  \\label{fig:ExclusionGluinoGg}\n\\end{figure}\n\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\cleardoublepage\n\\chapter{Interpretations: Dark Matter related}\n\nThis chapter presents interpretations of the monojet analysis in terms of models involving the direct production of potential Dark Matter candidates.\nThis includes models based on effective theories, simplified models involving the pair production of Weakly Interacting Massive Particles, or the production of gravitinos in Gauge Mediated SUSY breaking scenarios.\nSensitivity studies of the monojet analysis to models involving the direct production of charginos or neutralinos are also collected in Appendix~\\ref{sec:CharginoNeutralinoProduction}.\n\n%------------------\n%--- Section for the WIMPs, wrongly included first as an appendix!!!\n%------------------\n\\input{Appendix_WIMPs/Appendix_WIMPs.tex}\n%------------------\n%------------------\n%------------------\n\n\n\\section{Gravitino production in GMSB}\n    \\label{sec:GravitinoProduction}\n\nIn Gauge Mediated SUSY breaking scenarios, the gravitino mass gives direct access to the scale of the SUSY breaking, and can potentially contribute to the total amount of Dark Matter in the Universe.\nIn this section, the monojet results are interpreted in the context of gravitino production in association with a squark or a gluino in the final state.\nFigure~\\ref{fig:DiagramsGravitinoGMSB} shows some of the Feynman diagrams for this process.\nA simplified SUSY model is used for which the squark or the gluino decays to a gravitino, and a quark or a gluon in the final state (see Figure~\\ref{fig:DiagramsVertexGravitinoGMSB}), thus leading to a monojet signature.\n\nMonte Carlo samples corresponding to gravitino production in association with a gluino or a squark in the final state, $\\pp\\rightarrow\\squark\\gravino+X$ and $\\pp\\rightarrow\\gluino\\gravino+X$ are generated at LO using \\madgraph{}, interfaced with \\pythia{} for the showering.\nThe ATLAS detector simulation is provided by the ATLAS fast simulation, while the PDF set used is CTEQ6L1.\nThe renormalization and factorization scales are set to the average of the mass of the final state particles involved in the hard interaction $(m_{\\gravino} + m_{\\squark , \\gluino})/2 \\simeq m_{\\squark , \\gluino}/2$.\nA grid with different mass configurations has been generated with $m_{\\squark, \\gluino}$ from $\\unit[50]{GeV}$ to $\\unit[2.6]{TeV}$ and $m_{\\squark}/m_{\\gluino} = 0.25, 0.5, 1, 2, 4$, and a gravitino mass $m_{\\gravino} = \\unit[5 \\times 10^{-4}]{eV}$.\nBoth experimental and theoretical systematic uncertainties for the different mass configurations are computed as for the previous models discussed in Section~\\ref{sec:SysUncertaintiesSignal}.\nExperimental uncertainties result into a 4.6\\% to 2.9\\% effect on the signal yield in M3, and a 16\\% to 3\\% effect in M6 for squark and gluino masses of 200~GeV and 2.4~TeV, respectively.\nThe theoretical uncertainties on the acceptance introduce a variation in the signal yield of about 15\\%, while the theoretical uncertainties on the cross section contribute altogether to a 24\\% to 55\\% on the signal yield for different squark and gluino masses.\n\n\n\\subsection{Exclusion Limits at 95\\% CL}\n\nIn this case, the 95\\% CL limits on the visible cross section of the monojet analysis shown in Table~\\ref{tab:modelIndependent} are used to extract the limits on the gravitino mass as a function of the masses of the squark or the gluinos.\nThe best sensitivity to the gravitino production is obtained for the selections M3, M5 and M6, and depends on the squark and gluino mass configuration.\nFigure~\\ref{fig:modelIndependentGravitino} shows, for the signal region M5, the fiducial cross section as a function of the squark and gluino mass, for different gravitino masses.\nFor comparison, the model independent limits from Table~\\ref{tab:modelIndependent} are shown.\nThe intersection between the model independent limit and the signal fiducial cross section determines the exclusion in terms of the parameters of the model.\nThe following limits are calculated:\n\n\\begin{figure}[!ht]\n\\begin{center}\n\\mbox{\n\\includegraphics[width=0.995\\textwidth]{Interpretations/Figures/ModelIndependentGravitino_mGVariable_Stop_A9.eps}\n}\n\\end{center}\n\\caption[Fiducial cross section for the $\\gravino + \\squark / \\gluino$ production as a function of the squark/gluino mass for degenerate squark and gluinos in the signal region M5.]{Fiducial cross section, $\\sigma \\times A \\times \\epsilon$, for the $\\gravino + \\squark / \\gluino$ production as a function of the squark/gluino mass for degenerate squark and gluinos in the signal region M5. Different values of the gravitino mass are considered and the predictions are compared to the model independent limits (see Table \\ref{tab:modelIndependent}).}\n\\label{fig:modelIndependentGravitino}\n\\end{figure}\n\n\\begin{itemize}\n\\item{Observed:}\nintersection between the observed model independent limit and the signal visible cross section.\n\\item{Observed $- 1\\sigma_{\\text{total}}^{\\text{signal}}$:}\nintersection between the observed model independent limit and the signal visible cross section $- 1\\sigma$ of the total uncertainty on the signal.\nThe total uncertainty is computed by summing in quadrature the experimental uncertainties and both the theoretical uncertainties on the acceptance and on the cross section.\n\\item{Observed $- 1\\sigma_{\\text{exp}}^{\\text{signal}}$:}\nintersection between the observed limit and the signal visible cross section $-1\\sigma$ of the experimental uncertainty on the signal together with the effects of the modeling uncertainty on the signal acceptance (no cross section uncertainty is considered in this case).\n\\item{Expected:}\nintersection between the expected model independent limit and the signal visible cross section.\n\\item{Expected $\\pm 1\\sigma$ or $\\pm 2\\sigma$:}\nintersection between the signal visible cross section and the expected limit with $\\pm 1\\sigma$ or $\\pm 2\\sigma$ experimental uncertainty on the Standard Model background.\n\\end{itemize}\n\nThis approach does not take into account the correlations between the signal and the background uncertainties.\nThe $CL_s$ computation for each of the mass configurations in the grid would require a huge computational power, thus making the analysis very time consuming.\nTests performed for several cases showed that the exclusions using the model independent limits or using the $CL_s$ method return compatible, almost identical, results.\n\nFigure~\\ref{fig:GravitinoMassExclusion_mqmg} shows the 95\\% CL limits on the gravitino mass, $m_{\\gravino}$, for equal squark and gluino masses.\nGravitino masses below $3.5\\times10^{-4}$~eV, $3\\times10^{-4}$~eV and $2\\times10^{-4}$~eV are excluded at 95\\% CL for squark/gluino masses of 500~GeV, 1~TeV and 1.5~TeV.\nFor very high squark/gluino masses the narrow-width approximation (NWA) employed is violated since the partial width for the gluino and squark to decay into a gravitino and a parton becomes more than 25\\% of its mass.\nIn this case, other decay channels for the gluino and squarks should be considered, leading to a different final state.\nFigures~\\ref{fig:GravitinoMassExclusion_xmqmg} and~\\ref{fig:GravitinoMassExclusion_mqxmg} show the limits on the gravitino mass, for $m_{\\gluino} = 2\\times m_{\\squark}$ and $m_{\\gluino} = 4\\times m_{\\squark}$; and $m_{\\gluino} = m_{\\squark}/2$ and $m_{\\gluino} = m_{\\squark}/4$, respectively.\nIn this case, lower bounds on gravitino mass in the range between $5\\times10^{-4}$ and $5\\times10^{-5}$ are set depending on the squark and gluino masses.\n\n\\begin{figure}[!ht]\n\\begin{center}\n\\mbox{\n\\includegraphics[width=0.795\\textwidth]{Interpretations/Figures/ModelIndependentGravitino_combined_mGLimit_Stop_A4_A9_A10.eps}\n}\n\\end{center}\n\\caption[95\\% CL lower limits on the gravitino mass as a function of the squark mass for equal squark and neutralino masses.]{Observed (solid line) and expected (dashed line) 95\\% CL lower limits on the gravitino mass as a function of the squark mass for equal squark and neutralino masses. The dotted line indicates the impact on the observed limit of the $\\pm1\\sigma$ LO theoretical uncertainty. The shaded bands around the expected line indicate the expected $\\pm1\\sigma$ and $\\pm2\\sigma$ ranges of limits. \n  The region above the black dotted line defines the validity of the narrow-width approximation (NWA) for which the decay width is smaller than 25\\% of the squark/gluino mass.}\n\\label{fig:GravitinoMassExclusion_mqmg}\n\\end{figure}\n\n\\begin{figure}[!ht]\n\\begin{center}\n\\mbox{\n\\includegraphics[width=0.795\\textwidth]{Interpretations/Figures/ModelIndependentGravitino_combined_mGLimit_Stop_A4_A9_A102mqmg.eps}\n}\n\\mbox{\n\\includegraphics[width=0.795\\textwidth]{Interpretations/Figures/ModelIndependentGravitino_combined_mGLimit_Stop_A4_A9_A104mqmg.eps}\n}\n\\end{center}\n\\caption[95\\% CL lower limits on the gravitino mass as a function of the squark mass for $m_{\\gluino} = 2 \\times m_{\\squark}$ and $m_{\\gluino} = 4 \\times m_{\\squark}$.]{Observed (solid line) and expected (dashed line) 95\\% CL lower limits on the gravitino mass as a function of the squark mass for $m_{\\gluino} = 2 \\times m_{\\squark}$ (top) and $m_{\\gluino} = 4 \\times m_{\\squark}$ (bottom). The dotted line indicates the impact on the observed limit of the $\\pm1\\sigma$ LO theoretical uncertainty. The shaded bands around the expected line indicate the expected $\\pm1\\sigma$ and $\\pm2\\sigma$ ranges of limits. \n  The region above the black dotted line defines the validity of the narrow-width approximation (NWA) for which the decay width is smaller than 25\\% of the squark/gluino mass.}\n\\label{fig:GravitinoMassExclusion_xmqmg}\n\\end{figure}\n\n\\begin{figure}[!ht]\n\\begin{center}\n\\mbox{\n\\includegraphics[width=0.795\\textwidth]{Interpretations/Figures/ModelIndependentGravitino_combined_mGLimit_Stop_A4_A9_A10mq2mg.eps}\n}\n\\mbox{\n\\includegraphics[width=0.795\\textwidth]{Interpretations/Figures/ModelIndependentGravitino_combined_mGLimit_Stop_A4_A9_A10mq4mg.eps}\n}\n\\end{center}\n\\caption[95\\% CL lower limits on the gravitino mass as a function of the squark mass for $m_{\\gluino} = 1/2 \\times m_{\\squark}$ and $m_{\\gluino} = 1/4 \\times m_{\\squark}$.]{Observed (solid line) and expected (dashed line) 95\\% CL lower limits on the gravitino mass as a function of the squark mass for $m_{\\gluino} = 1/2 \\times m_{\\squark}$ (top) and $m_{\\gluino} = 1/4 \\times m_{\\squark}$ (bottom). The dotted line indicates the impact on the observed limit of the $\\pm1\\sigma$ LO theoretical uncertainty. The shaded bands around the expected line indicate the expected $\\pm1\\sigma$ and $\\pm2\\sigma$ ranges of limits. \n  The region above the black dotted line defines the validity of the narrow-width approximation (NWA) for which the decay width is smaller than 25\\% of the squark/gluino mass.}\n\\label{fig:GravitinoMassExclusion_mqxmg}\n\\end{figure}\n\nThe limits on the gravitino mass shown in Figures~\\ref{fig:GravitinoMassExclusion_mqmg} to~\\ref{fig:GravitinoMassExclusion_mqxmg} can be translated into 95\\% CL upper limits on the breaking scale of SUSY, $\\sqrt{\\langle F \\rangle}$.\nThese limits are shown in Figures~\\ref{fig:GravitinoSqrtFExclusion_mqmg} to~\\ref{fig:GravitinoSqrtFExclusion_mqxmg}, for the different squark and gluino mass configurations.\nValues of the $\\sqrt{\\langle F \\rangle}$ below 1~TeV can be excluded for squark/gluino masses of 1~TeV.\n\n\\begin{figure}[!ht]\n\\begin{center}\n\\mbox{\n\\includegraphics[width=0.795\\textwidth]{Interpretations/Figures/ModelIndependentGravitino_combined_sqrtFLimit_Stop_A4_A9_A10.eps}\n}\n\\end{center}\n\\caption[95\\% CL lower limits on the SUSY breaking scale $F$ as a function of the squark mass for equal squark and neutralino masses.]{Observed (solid line) and expected (dashed line) 95\\% CL lower limits on the SUSY breaking scale $F$ as a function of the squark mass for equal squark and neutralino masses. The dotted line indicates the impact on the observed limit of the $\\pm1\\sigma$ LO theoretical uncertainty. The shaded bands around the expected line indicate the expected $\\pm1\\sigma$ and $\\pm2\\sigma$ ranges of limits. \n  The region above the black dotted line defines the validity of the narrow-width approximation (NWA) for which the decay width is smaller than 25\\% of the squark/gluino mass.}\n\\label{fig:GravitinoSqrtFExclusion_mqmg}\n\\end{figure}\n\n\\begin{figure}[!ht]\n\\begin{center}\n\\mbox{\n\\includegraphics[width=0.795\\textwidth]{Interpretations/Figures/ModelIndependentGravitino_combined_sqrtFLimit_Stop_A4_A9_A102mqmg.eps}\n}\n\\mbox{\n\\includegraphics[width=0.795\\textwidth]{Interpretations/Figures/ModelIndependentGravitino_combined_sqrtFLimit_Stop_A4_A9_A104mqmg.eps}\n}\n\\end{center}\n\\caption[95\\% CL lower limits on the SUSY breaking scale $F$ as a function of the squark mass for $m_{\\gluino} = 2 \\times m_{\\squark}$ and $m_{\\gluino} = 4 \\times m_{\\squark}$.]{Observed (solid line) and expected (dashed line) 95\\% CL lower limits on the SUSY breaking scale $F$ as a function of the squark mass for $m_{\\gluino} = 2 \\times m_{\\squark}$ (top) and $m_{\\gluino} = 4 \\times m_{\\squark}$ (bottom). The dotted line indicates the impact on the observed limit of the $\\pm1\\sigma$ LO theoretical uncertainty. The shaded bands around the expected line indicate the expected $\\pm1\\sigma$ and $\\pm2\\sigma$ ranges of limits. \n  The region above the black dotted line defines the validity of the narrow-width approximation (NWA) for which the decay width is smaller than 25\\% of the squark/gluino mass.}\n\\label{fig:GravitinoSqrtFExclusion_xmqmg}\n\\end{figure}\n\n\\begin{figure}[!ht]\n\\begin{center}\n\\mbox{\n\\includegraphics[width=0.795\\textwidth]{Interpretations/Figures/ModelIndependentGravitino_combined_sqrtFLimit_Stop_A4_A9_A10mq2mg.eps}\n}\n\\mbox{\n\\includegraphics[width=0.795\\textwidth]{Interpretations/Figures/ModelIndependentGravitino_combined_sqrtFLimit_Stop_A4_A9_A10mq4mg.eps}\n}\n\\end{center}\n\\caption[95\\% CL lower limits on the SUSY breaking scale $F$ as a function of the squark mass for $m_{\\gluino} = 1/2 \\times m_{\\squark}$ and $m_{\\gluino} = 1/4 \\times m_{\\squark}$.]{Observed (solid line) and expected (dashed line) 95\\% CL lower limits on the SUSY breaking scale $F$ as a function of the squark mass for $m_{\\gluino} = 1/2 \\times m_{\\squark}$ (top) and $m_{\\gluino} = 1/4 \\times m_{\\squark}$ (bottom). The dotted line indicates the impact on the observed limit of the $\\pm1\\sigma$ LO theoretical uncertainty. \n  The shaded bands around the expected line indicate the expected $\\pm1\\sigma$ and $\\pm2\\sigma$ ranges of limits. \n  The region above the black dotted line defines the validity of the narrow-width approximation (NWA) for which the decay width is smaller than 25\\% of the squark/gluino mass.}\n\\label{fig:GravitinoSqrtFExclusion_mqxmg}\n\\end{figure}\n\n\n\\clearpage\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\cleardoublepage\n\\chapter{Interpretations: ADD Large Extra Dimensions}\n    \\label{chapter:ADDGravitonProduction}\n\nThis chapter presents the results of the monojet analysis interpreted in the context of the LED ADD scenario discussed in Section \\ref{sec:ADD}.\nThis model postulates the presence of $n$ extra spacial dimensions of size $R$, with only the graviton field being able to propagate through them.\nThis results in a reduction of the gravitational strength, with $M_D$, the fundamental Planck scale in $4+n$ dimensions, close to the electroweak scale for large enough $R$, and thus solving the hierarchy problem.\nThe agreement between the data and the MC background simulation for the selections M1 to M6 is translated into $95\\%$~CL limits on the parameters of this model.\n\n\n\\section{ADD LED signal samples and systematic uncertainties on the signal}\n\nMonte Carlo samples for different $n$ and $M_D$ parameter configurations of the ADD LED model, are generated using \\exograviton{}\\footnote{\\exograviton{} is a dedicated module of \\pythia{8}} and the CTEQ6.6 PDFs set.\nThe renormalization and factorization scales are set to $\\sqrt{m_G^2 / 2 + \\pt^2}$, where $m_G$ is the graviton mass and $\\pt$ denotes the transverse momentum of the recoiling parton \\cite{ATLAS:2012zim}.\n\nDifferent sources of systematic uncertainties on the ADD signals are considered, as detailed in Section~\\ref{sec:SysUncertaintiesSignal} for the case of third generation SUSY searches.\nExperimental uncertainties include: uncertainties on the jet and $\\met$ energy scales and resolutions; uncertainties on the simulated lepton identification, energy scales and resolutions; and the uncertainty on the total integrated luminosity.\nThe uncertainty on the PDFs; the uncertainty on the factorization, renormalization and matching scales; and the uncertainty on the initial- and final-state gluon radiation constitute the theoretical uncertainties, that affect both the acceptance and the cross section of the model.\nThe theoretical uncertainties on the acceptance introduce a 10\\% effect on the total signal yield, inspired by the previous studies found in Ref.~\\cite{ATLAS:2012zim}.\nThis reference also provides a computation for the theoretical uncertainty on the cross section, which is also adopted for this analysis.\nThis uncertainty results into a $36\\%$ to $62\\%$ in all the signal regions for $n$ increasing from~2 to~6.\n\n\n\\section{Exclusion Limits on $M_D$ and $n$}\n\nThe interpretation of the LED ADD model follows the same strategy as the light gravitino production in GMSB scenarios explained in Section~\\ref{sec:GravitinoProduction}.\nThe exclusion in terms of the number of extra dimensions, $n$, and the fundamental Planck scale, $M_D$ is computed from the intersection between the model independent limit on visible cross section (in Table \\ref{tab:modelIndependent}) and the ADD LED signal fiducial cross section for the different parameter configurations.\nThe uncertaities on the backgrounds and the signal are considered as independent in this simplified approach, and therefore no correlation between them is taken into account.\nAs an illustration, Figure \\ref{fig:ADDModelIndependentLOM5} shows the fiducial cross section as a function of $M_D$ for $n=2, 4, 6$ in the signal region M5.\nThe band around the signal represents the total uncertainty (experimental, modeling effect on acceptance and on cross section all together).\n\n\\begin{figure}[!ht]\n\\begin{center}\n\\mbox{\n\\includegraphics[width=0.795\\textwidth]{Interpretations/Figures/ModelIndependentADD_LO_Stop_A9.eps}\n}\n\\end{center}\n\\caption[Fiducial cross section, $\\sigma \\times A \\times \\epsilon$, for the ADD LED model as a function of $M_D$ parameter for $n=2$, $n=4$ and $n=6$ (LO signal cross sections) compared to the observed and expected model independent limits in M5.]{Fiducial cross section, $\\sigma \\times A \\times \\epsilon$, as a function of $M_D$ parameter for $n=2$, $n=4$ and $n=6$ (LO signal cross sections) compared to the observed and expected model independent limits in the signal region M5. The colored band on the signal curves represent the total uncertainty (experimental and modeling uncertainties on acceptance and cross section).}\n\\label{fig:ADDModelIndependentLOM5}\n\\end{figure}\n\nThe best sensitivity for this model is obtained for the signal regions M3, M5 and M6, depending on $n$ and $M_D$.\nThe limits on $M_D$ parameter versus $n$ of the ADD model at leading order (LO) are reported in Table~\\ref{tab:ADD_Limits_LO} and shown in Figure \\ref{fig:ADDExclusionLOCombined}.\nThe green and yellow bands represent the $\\pm 1\\sigma$ and $\\pm 2\\sigma$ experimental uncertainty on the SM background yield respectively.\nThe limits on $M_D$ have been significantly improved with respect to the previous analysis in ATLAS~\\cite{ATLAS:2012zim}, performed with $\\unit[10]{fb^{-1}}$.\n\n%--- ref{tab:ADD_Limits_LO}\n\\input{Interpretations/Tables/ADD_LO.tex}\n\n\\begin{figure}[!ht]\n\\begin{center}\n\\mbox{\n\\includegraphics[width=0.795\\textwidth]{Interpretations/Figures/plotExclusionADD_LO_combined_Stop_A4_A9_A10.eps}\n}\n\\end{center}\n\\caption{The 95\\% CL lower limits on the $M_D$ parameter of the ADD model for a number of extra dimensions $n$, considering LO signal cross sections.}\n\\label{fig:ADDExclusionLOCombined}\n\\end{figure}\n\nThe next-to-leading order cross section (NLO) for ADD signal is obtained by applying the scale factors extracted from Ref.~\\cite{CMS:rwa}. \nThese scale factors have values of $1.5$ for $n=2, 3$ and $1.4$ for $n=4, 5, 6$.\nAs discussed in Ref.~\\cite{ATLAS:2012ky}, the analysis partially probes the phase space region with $\\sqrt{\\hat{s}}>M_D$, where $\\sqrt{\\hat{s}}$ is the center-of-mass energy of the interaction.\nThis challenges the validity of the lower bounds on $M_D$, since they depend on the unknown ultraviolet behavior of the effective theory.\nFor this reason, the 95\\% CL limits are re-computed after suppressing all the events with $\\sqrt{\\hat{s}}>M_D$.\nFigure~\\ref{fig:ADDModelIndependentNLOtruncatedM5} shows the variation of the visible cross section for different ADD models as a function of $M_D$, after suppressing the events with $\\hat{s} > M_D^2$ for signal region M5.\nThe limits on $M_D$ as a function of the number of extra dimensions are reported on Table~\\ref{tab:ADD_Limits_NLO_truncated} and shown in Figure~\\ref{fig:ADDExclusionNLOtruncatedCombined}.\nThis figure also shows that the limits are not affected by the truncation of the events with $\\hat{s} > M_D^2$, and compares the results obtained from this analysis to the latest CMS results in Ref.~\\cite{CMS:rwa}.\n\n\\begin{figure}[!ht]\n\\begin{center}\n\\mbox{\n\\includegraphics[width=0.795\\textwidth]{Interpretations/Figures/ModelIndependentADD_NLO_truncated_Stop_A9.eps}\n}\n\\end{center}\n\\caption[Fiducial cross section, $\\sigma \\times A \\times \\epsilon$, for the ADD LED model as a function of $M_D$ parameter for $n=2$, $n=4$ and $n=6$ (NLO signal cross sections, removing events with $\\hat{s} > M_D$) compared to the observed and expected model independent limits in the signal region M5.]{Fiducial cross section, $\\sigma \\times A \\times \\epsilon$, as a function of $M_D$ parameter for $n=2$, $n=4$ and $n=6$ (NLO signal cross sections, removing events with $\\hat{s} > M_D^2$) compared to the observed and expected model independent limits in M5. The colored band on the signal curves represent the total uncertainty (experimental and modeling uncertainties on acceptance and cross section).}\n\\label{fig:ADDModelIndependentNLOtruncatedM5}\n\\end{figure}\n\n%--- ref{tab:ADD_Limits_NLO_truncated}\n\\input{Interpretations/Tables/ADD_NLO_truncated.tex}\n\n\n\\begin{figure}[!ht]\n\\begin{center}\n\\mbox{\n\\includegraphics[width=0.795\\textwidth]{Interpretations/Figures/plotExclusionADD_ALLDistr_NLO_combined_Stop_A4_A9_A10.eps}\n}\n\\end{center}\n\\caption{The 95\\% CL lower limits on the $M_D$ parameter of the ADD model for a number of extra dimensions $n$, considering NLO signal cross sections and removing events with $\\hat{s} > M_D^2$.}\n\\label{fig:ADDExclusionNLOtruncatedCombined}\n\\end{figure}\n\n\\clearpage\n", "meta": {"hexsha": "19af6a9f780cbe360326bdccdfce4673427740e7", "size": 66739, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Interpretations/Interpretations.tex", "max_stars_repo_name": "rogercaminal/PhDThesis", "max_stars_repo_head_hexsha": "b4582c8c1c5858878dfdb8e69986a55c1aeb9e3e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Interpretations/Interpretations.tex", "max_issues_repo_name": "rogercaminal/PhDThesis", "max_issues_repo_head_hexsha": "b4582c8c1c5858878dfdb8e69986a55c1aeb9e3e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Interpretations/Interpretations.tex", "max_forks_repo_name": "rogercaminal/PhDThesis", "max_forks_repo_head_hexsha": "b4582c8c1c5858878dfdb8e69986a55c1aeb9e3e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 84.9096692112, "max_line_length": 1080, "alphanum_fraction": 0.7685760949, "num_tokens": 18036, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.5, "lm_q1q2_score": 0.32744736452106377}}
{"text": "\n\\section{Model-based Analysis}\n\nAs described in the introduction, prefetching has the potential to enable visualization systems to respond with interactive latencies.  However, current approaches are designed for interfaces with limited options for user interaction~\\cite{}; many have suggested that increasing the expressivity of the interface (e.g., the number of possible user actions) makes the prediction task significantly more challenging.  In this section, we seek to understand the minimum accuracy for model needs in order to support low user perceived latencies, as well as the conditions that affect this accuracy.\n\n\\subsection{The Model}\n\nOur goal is to estimate the minimum prediction accuracy $\\alpha$ needed in order to ensure that the user perceived latency $l_{user}$ is below a fixed threshold (e.g. 100ms~\\cite{} or 500ms).\nLet $T=0$ be the time.\nWe assume that the user will perform her request at $T=t$ where $t \\ge 0$, and that the cost of answering a request consists of fetching and rendering the results.\n$l_{user}$ is defined as the time between $t$ and the change reflected in the visualization. \nLet $l_{net}$ be the latency to execute a request, transfer the results across the network, and render it on screen.   In a typical system, $l_{user} = l_{net}$, which can be undesirable when query processing or the network latency are high.\nPrefetching allows the client to proactively answer a request at $T=0$ and store the results in a client cache.\nIf a future request accessed data in the cache, then it can take much less time $l_{cache} < l_{net}$ and result in a more responsive user perceived experience.\n\nWe now model the expected user perceived latency as $l_{cache} + max(0, l_{net} - t)$ if model accurately predicted the request, and $l_{net}$ if it mispredicted.  The $max()$ operation accounts for cases when the cost of a cache miss is larger than $t$:\n$$l_{user} = (l_{cache} + max(0, l_{net}-t))\\times \\alpha + l_{net}\\times(1-\\alpha) $$\nRearranging the terms, we can derive the minimum prediction accuracy in order to maintain $l_{user}$.\n%$$\\alpha = \\frac{l_{net} - l_{user}}{l_{net} - l_{cache}}$$\n$$\\alpha = \\frac{l_{user} - l_{net}}{l_{cache} + max(0, l_{net}-t) - l_{net}}$$\n\nPrior perception and interactive visualization literature have used both $100$ and $500$ millisecond response times as thresholds for what is considered interactive~\\cite{liu2014effects}.   Similarly, we assume request latencies can vary from $0$ to $2$ seconds~\\cite{}, which embodies latencies that stem from query processing, serialization, network latencies and client overheads.  Finally, it is typically challenging to make accurate predictions more than several hundred milliseconds into the future~\\cite{pasqual2014mouse}; we vary the ratio $\\frac{t}{l_{net}}$ between $0.5$ and $1$.   We use the above constants in our analysis below.\n\nFigure~\\ref{fig:model_base} plots the model accuracy for two commonly cited $l_{user}$ thresholds (100 and 500ms).  The x-axis varies $l_{net}$ and each line represents the percentage of the prefetching costs that the user will experience.  For instance, when $\\frac{t}{l_{net}}=1$, the user initiates the request at $T=t=l_{net}$ and does not experience any of the prefetching costs, whereas when $\\frac{t}{l_{net}}=0.5$, the prefetching request is only half complete by the time the user initiates her request at $T=0.5\\times l_{net}$.  We use a vertical line to mark the network latency at $1$ second.  \n\nThe first observation is that when $l_{net}$ is smaller than the threshold, the user perceived accuracy is independent of the model accuracy.  When the threshold is $100$, the minimum model accuracy quickly exceeds $80\\%$ by even a request latency of $500$ms; although the minimum accuracy is lower under the $500$ms threshold, the accuracy converges to $70\\%$.\nIt is challenging to guarantee such high user prediction accuracy for a single request---the accuracy in existing literature is slightly above $50\\%$ for a constrained user interface with 9 interaction options~\\cite{battle2016dynamic}.\n\n\\ewu{Argue that assuming $t < l_{net}$ is a reasonable assumption.}\n\n\\begin{figure}[ht]\n\t\\centering\n\t\\includegraphics[width=1\\columnwidth]{figures/model_base}\n \t\\caption{Minimum $\\alpha$ vs network latency (x-axis), $\\frac{t}{l_{net}}$ ratios (lines), and two thresholds (facets).}\n    \\label{fig:model_base}\n\\end{figure}\n\n\n\n\\stitle{Vary Prefetch Concurrency}\nMost modern data processing systems are able to execute multiple concurrent requests~\\cite{ebenstein2016fluxquery,giannikis2012shareddb}, thus we now modify the model to vary the number of concurrent prefetch requests $N$.\nThe $(1-\\alpha)^N$ term is the probability that none of the prefetch requests match the user's actual request at $T=t$:\n%\n$$l_{user} = (l_{cache} + max(0, l_{net} - t)\\times (1-(1-\\alpha)^N) + l_{net}\\times(1-\\alpha)^N $$\n%\nRearranging the terms results in the following minimum prediction accuracy:\n%\n$$\\alpha = 1 - \\left(\\frac{l_{cache}+max(0,l_{net}-t)-l_{user}}{max(0,l_{net}-t)-l_{net}}\\right)^{1/N}$$\n\n\\begin{figure}[h]\n\t\\centering\n\t\\includegraphics[width=1\\columnwidth]{figures/model_concurrency}\n \t\\caption{Minimum $\\alpha$ vs network latency (x-axis), concurrency (lines), and two latency thresholds (facets).}\n  \\label{fig:model_concurrency}\n\\end{figure}\n\n\nFigure~\\ref{fig:model_concurrency} shows that increasing the number of concurrent requests has an immediate effect on $\\alpha$ ($t=l_{net}$ in these plots).    With $N=20$, a prediction model need only be $12\\%$ accurate to ensure an interactive latency of $l_{user}=100$, while ensuring  $l_{user}=500$ only requires an accuracy of $3.5\\%$.  At the limit, sending concurrent requests for all possible queries (assuming the cost is $l_{net}$) means the user latency is independent of prediction accuracy.  These results suggest that increasing the concurrency is an effective counter balance to model accuracy.\n\n\n\\stitle{Network Latency Variance}\nFigure~\\ref{fig:model_std} simulates $l_{net}$ drawn from a gaussian distribution with standard deviation of $std \\in \\{0, 100, 500\\}$ milliseconds.  We set $N=20$, $t=l_{net}$, and the y-axis is from 0 to $0.4$.  Although the request variance affects the required model accuracy when $l_{net}$ is low, the curves for each threshold converge to the same levels independent of $std$; this is simply because $l_{net}$, rather than $std$, is the dominant factor as it increases.\n\n\\begin{figure}[h]\n\t\\centering\n\t\\includegraphics[width=1\\columnwidth]{figures/model_std}\n \t\\caption{Minimum $\\alpha$ vs network latency (x-axis), concurrency (lines), and two latency thresholds (facets).}\n  \\label{fig:model_std}\n\\end{figure}\n\n\\begin{figure}[h]\n\t\\centering\n\t\\includegraphics[width=1\\columnwidth]{figures/model_partial}\n \t\\caption{Required prediction accuracy as a function of network latency, under progressive conditions where partial responses are sufficient.}\n    \\label{fig:model_partial}\n\\end{figure}\n\n\n\\stitle{Progressive Results}\nThe visualization and database communities have argued for approximate visualizations that are slightly inaccurate but potentially much faster to compute.  Techniques such as Online Aggergation~\\cite{control,wanderjoin} or streaming wavelet compression~\\cite{} are considered {\\it progressive} because they are able to immediately return (and render) approximate results that improve over time; thus providing a natural trade-off between latency and result quality.  Our final analysis studies progressive results that require a fraction of the full request latency to be ``sufficiently good''.\n\\ewu{Use sampling and immens arguments as basis for 25\\% partial results.} We find that $5\\%$ accuracy is enough to maintain user perceived latency of $100$ when $25\\%$ of the results is sufficient; at threshold of $500$, the perceived latency is independent of the model accuracy when $l_{net}\\le 2000$.\n\n\n\n\n\n\n\\subsection{Discussion}\nWe find that a careful combination of existing techniques (concurrency and progressive results) can dramatically reduce the required model accuracy to enable low user perceived latency---in some extreme cases when the threshold is $500$, the model accuracy can even be $0\\%$.  \n\\ewu{Argue that given  fixed network throughput between client and server, increasing concurrency beyond a certain point naturally requires partial results.  Thus the two go hand in hand.   We also see that the prediction model simply needs to be ``good enough'' with an accuracy of $5-10\\%$.  When the number of possible interactions are limited to $10-20$ possible interactions, then even a random model is sufficient.  However in rich interfaces with potentially dozens or a hundred possible interactions, there may simply be too many choices to learn a good model.}\n\n", "meta": {"hexsha": "c9f3487215f9f6721c2828f94d7c4e8737607f36", "size": 8785, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/vldb17/content/model.tex", "max_stars_repo_name": "Ultra-Seven/newStream", "max_stars_repo_head_hexsha": "6ae7c152d33c0a0d02b44b13a45f72b20ba8ef16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/vldb17/content/model.tex", "max_issues_repo_name": "Ultra-Seven/newStream", "max_issues_repo_head_hexsha": "6ae7c152d33c0a0d02b44b13a45f72b20ba8ef16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/vldb17/content/model.tex", "max_forks_repo_name": "Ultra-Seven/newStream", "max_forks_repo_head_hexsha": "6ae7c152d33c0a0d02b44b13a45f72b20ba8ef16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 95.4891304348, "max_line_length": 643, "alphanum_fraction": 0.7653955606, "num_tokens": 2166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.32718134379056174}}
{"text": "\\input{permve-ntnu-latex-assignment.tex}\n\n\\usepackage{float}\n\n\\title{\t\n\\normalfont \\normalsize \n\\textsc{Norwegian University of Science and Technology\\\\IT3105 -- Artificial Intelligence Programming}\n\\horrule{0.5pt} \\\\[0.4cm]\n\\huge Module 4:\\\\ Using Minimax with\\\\ Alpha-Beta Pruning to play 2048\\\\\n\\horrule{2pt} \\\\[0.5cm]\n}\n\n\\author{Per Magnus Veierland\\\\permve@stud.ntnu.no}\n\n\\date{\\normalsize\\today}\n\n\\begin{document}\n\n\\fancyfoot[C]{}\n\\maketitle\n\n\\newpage\n\\fancyfoot[C]{\\thepage~of~\\pageref{LastPage}} % Page numbering for right footer\n\\setcounter{page}{1}\n\n\\section*{Branching factor}\n\nThe aim of module~4 is to achieve a winning score in the game \\textsc{2048}. The game consists of a two-dimensional $4\\times 4$ grid where each tile in the grid is either empty or has a number between $2^1$ and $2^{17}$ (inclusive). An upper bound of the game's branching factor can be found by multiplying the number of possible player moves~(4) by the maximum number of empty tiles~(16) by the number of possible tile spawns~(2):\n\n\\begin{displaymath}\nb_{\\textit{upper}} = 4 \\cdot 16 \\cdot 2 = 128\n\\end{displaymath}\n\n\\section*{State representation}\n\nGiven such a large branching factor for each player move it is evident that a large number of states must be evaluated to perform even a shallow search involving a low number of moves. To enable a large number of states to be considered an efficient state representation scheme is beneficial.\n\nEven if the theoretical maximum tile is $2^{17}$, the largest tile required to win the game, 2048, is only $2^{11}$. Given that the number 1 is not present in the game, it is possible to represent the empty tile and tiles for powers of two between $2^1$ and $2^{15}$ by using 4~bits to represent each tile. With 4~bits reserved for each tile, all 16~tiles can be represented by a single 64-bit integer. Using a commonly available 64-bit processor architecture, each board state can be held in a single CPU register.\n\nThe resulting representation with example values is shown in Figure~\\ref{figure:represent} showing tile values and the corresponding bit values.\n\n\\begin{figure}[H]\n\\centering\n\\includegraphics[scale=1.0]{images/2048_state}\n\\caption{64-bit integer state representation}\n\\label{figure:represent}\n\\end{figure}\n\n\\section*{Lookup tables}\n\nAnother benefit from the compact state representation is that it allows for efficient use of lookup tables. The logic necessary to compute the successor state when given a move requires loops and branches. The effect of performing a move is also local to each row or column, depending on the direction of the move. Each row or column can then be considered in isolation and depend on the exact same logic to produce their successor. The number of possible rows or columns is $2^{16}=65536$, so representing a lookup table for a single direction will take $2^{16}*8=524288$~bytes, or $0.52$~MB. By using four lookup tables, one for each direction, successor states can be evaluated by performing four lookups, one for each row or column.\n\nLookup tables can also be used to evaluate both board heuristics and board scores. The board heuristic may be a costly function to evaluate, making it very beneficial to pre-compute. However, unlike the state transitions which can be considered as functions considering each row and column individually, the heuristic function evaluates the entire board state. Since a lookup table containing entries for all states would be $2^{64}*8=18.45$~exabytes, this is currently infeasible. However by imposing the limitation that the heuristic function can only consider a single row or column at a time, only a single lookup table with $2^{16}$ entries is needed. This limits the information available to the heuristic function, but the implemented heuristic function is still able to provide sufficient guidance to the search. When evaluating the heuristic value for a state; 8~lookups are performed, one for each row and column, and the result is summed. The advantage of this approach is that the heuristic evaluation can use very costly operations in the pre-computation, since its effective use consists only of lookups.\n\nEvaluating the score of a given state is also done using lookup tables. This is a simple convenience such that the scoring of a state can be performed using four row lookups.\n\n\\section*{Expectimax}\n\nThe algorithm used to solve \\textsc{2048} is \\textit{Expectimax} with pruning based on a probability threshold and a transposition table. \\textit{Expectimax} was chosen over \\textit{Minimax} since the ``adversary'' is stochastic and not actively minimizing the expected outcome. The code centers around the two functions \\texttt{score\\_player\\_node} and \\texttt{score\\_chance\\_node} which calls each other recursively with successive board evaluations, until either the search is pruned due to the node having a probability beneath the probability threshold, or because the depth exceeds the depth threshold, or if the current board state is found in the transposition table.\n\nWhen traversing downwards into the search, the current probability is tracked such that nodes falling beneath a probability threshold is pruned and heuristically evaluated instead of diving further down their state space. This is done to avoid spending time evaluating unlikely cases, such as when a $4$-tile spawns three times in a row. Using pruning based on probability is very effective, and the pruning rate can typically be 60-80\\% without harming the effectiveness of the algorithm.\n\nIn addition to pruning based on probability, a configurable depth limit is also imposed to control the algorithm.\n\nWhen evaluating the game state space, there will be many overlaps where different moves and/or different chance scenarios will end up resulting in the same game state. To improve the algorithm, a transposition table is used where evaluated states in chance nodes are added with their score and depth to a transposition table. If later on, a node is evaluated with a board state which exists in the transposition table, and where the stored depth is greater or equal to the current depth of the new search node, meaning that the current node's state has been evaluated at least as deep as what what the current search would do; the existing score stored in the transposition table is used instead of evaluating the node's state space again. The transposition table typically has a hit rate of 60-70\\%.\n\n\\section*{Heuristic}\n\nThe \\textit{Expectimax} algorithm requires a heuristic to evaluate the quality of a given state as it is unfeasible to fully evaluate the full state space for a given node due to a high branching ratio and a typical ``win'' state after approximately 2000~plies.\n\nThe chosen heuristic depends on four metrics and six constants. Since a lookup approach is used with the heuristic, the heuristic function can only evaluate a single row or column in isolation. For a given row the number of direct merges, $M_1$, secondary merges, $M_2$, and ternary merges, $M_3$, are recorded. E.g. for a row ``2 2 4 8'' the number of direct merges possible is one (``2'' with ``2'' resulting in ``4''), and the number of secondary merges is one (the resulting ``4'' with the existing ``4'', resulting in ``8''). The number of ternary merges is one (the resulting ``8'' with the existing ``8''). The last metric tracked is the number of ``bad tiles''; $B$. This is simply all non-zero tiles in a row which are not part of a merge.\n\nThe first constant, $k_L$, is a base used to distinguish losing states from non-losing states. Since losing states, i.e. states where there are no possible moves, are evaluated to zero -- the heuristic should result in a positive number for any non-losing state.\n\nThe three next constants is used to value the different merges, while the constants $k_{B1}$ and $k_{B2}$ is used to adjust the value of ``bad tiles''. A base constant is raised to the power of the number of bad tiles; penalizing each additional ``bad tile'' increasingly.\n\n\\begin{displaymath}\nH(\\textit{row}) = k_L + k_1 \\cdot M_1 + k_2 \\cdot M_2 + k_3 \\cdot M_3 - \\frac{{k_{B1}}^{B}}{k_{B2}}\n\\end{displaymath}\n\nMore sophisticated heuristics can be constructed which takes into account the monotonicity of the board state, the values of the tiles involved, and the number of empty tiles. However, the implemented heuristic performs well for shallow depths and is able to achieve a ``2048'' tile on ~80\\% of runs with a maximum depth of 4 in under 3 minutes. It also regularly accomplishes the ``4096'' tile; but has not been able to score ``8196'', despite attempts with a maximum depth of 10.\n\nThe following constants have been found by thought, trial and error. Achieving good constants for the heuristic will likely involve a meta-search using e.g. a gradient descent approach to tune the algorithm.\n\n\\begin{displaymath}\nk_L = 100, k_1 = 10, k_2 = 5, k_3 = 2.5, k_{B1} = 5, k_{B2} = 0.08\n\\end{displaymath}\n\n\\end{document}\n\n", "meta": {"hexsha": "bdc1c57986dd555bd9efe61d22bc92887dfd1105", "size": 8952, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "module_4/report/permve-ntnu-it3105-module-4.tex", "max_stars_repo_name": "pveierland/permve-ntnu-it3105", "max_stars_repo_head_hexsha": "6a7e4751de47b091c1c9c59560c19a8452698d81", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "module_4/report/permve-ntnu-it3105-module-4.tex", "max_issues_repo_name": "pveierland/permve-ntnu-it3105", "max_issues_repo_head_hexsha": "6a7e4751de47b091c1c9c59560c19a8452698d81", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "module_4/report/permve-ntnu-it3105-module-4.tex", "max_forks_repo_name": "pveierland/permve-ntnu-it3105", "max_forks_repo_head_hexsha": "6a7e4751de47b091c1c9c59560c19a8452698d81", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 98.3736263736, "max_line_length": 1118, "alphanum_fraction": 0.7802725648, "num_tokens": 2115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.32714952413492776}}
{"text": "\\section{Tests}\n\tTests have been taken from the ones used in laboratories and from TSPLIB, a library of sample instances for the TSP from various sources and of various types. A total of 13 instances, ranging in size from 12 to 100, have been tested 10 times for each method. Higher size tests should have been included but ILP solver already starts to slow at 100 nodes and the time to test was not so much.\n\t\n\t\\subsection{ILP}\n\t\tResults obtained testing the ILP solver gives expected results, as it always finds optimal solution, and execution times grow with problem size. Average solution times on 10 runs are displayed in Table 1.\\\\\n\t\t\n\t\t\\begin{center}\n\t\t\t\\begin{tabular}{ | l | c | r | }\n\t\t\t\t\\hline\n\t\t\t\t\\multicolumn{1}{|c|}{Test} & Size & \\multicolumn{1}{|c|}{Avg Time (s)}\\\\\n\t\t\t\t\\hline\n\t\t\t\ttsp12.dat\t\t& 12\t\t& 0,133\\\\\n\t\t\t\ttsp15.dat\t\t& 15\t\t& 0,062\\\\\n\t\t\t\ttsp17.dat\t\t& 17\t\t& 0,162\\\\\n\t\t\t\ttsp26.dat\t\t& 26\t\t& 0,298\\\\\n\t\t\t\ttsp29a.dat\t\t& 29\t\t& 0,633\\\\\n\t\t\t\ttsp29b.dat\t\t& 29\t\t& 0,668\\\\\n\t\t\t\ttsp42.dat\t\t& 42\t\t& 2,462\\\\\n\t\t\t\ttsp48a.dat\t\t& 48\t\t& 8,371\\\\\n\t\t\t\ttsp48b.dat\t\t& 48\t\t& 10,357\\\\\n\t\t\t\ttsp48c.dat\t\t& 48\t\t& 2,275\\\\\n\t\t\t\ttsp60.dat\t\t& 60\t\t& 27,066\\\\\n\t\t\t\ttsp100a.dat\t& 100\t& 101,527\\\\\n\t\t\t\ttsp100b.dat\t& 100\t& 128,637\\\\\n\t\t\t\t\\hline\n\t\t\t\\end{tabular}\n\t\t\\end{center}\n\t\t\\captionof{table}{ILP tests results}\n\t\t\\vspace{1em}\n\t\tWe can see that while solving small instances is very efficient, bigger ones require more time and going from size 60 to 100 (5/3 ratio) it gets way slower (more than 5 times), and the trend continue growing in size. This is due to exponential growth of the solution space the solver has to explore to find and prove optimality.\n\t\t\n\t\\subsection{Genetic Algorithm}\n\t\tGenetic algorithms, due to their random nature, give different results at each execution, so an average of 10 runs is considered. Obtained solutions and computation time are also greatly related to set parameters, which are reported for each instance. Parameters don't differ so much, but more generations and bigger populations are used for bigger instances, and to keep computational times low populations evaluated are reduced. Results obtained with specified tests are reported in Table 2.\n\t\t\n\t\t\\begin{center}\n\t\t\t\\hspace*{-1.2cm}\n\t\t\t\\begin{tabular}{ | l | c | r | r | c | c | c | c |}\n\t\t\t\t\\hline\n\t\t\t\t\\multicolumn{1}{|c}{\\multirow{2}{*}{Test}} & \\multicolumn{1}{|c|}{\\multirow{2}{*}{Size}} & Average & Avg. opt. & Opt. & \\multicolumn{3}{c|}{Parameters} \\\\\n\t\t\t\t\\cline{6-8}\n\t\t\t\t& & \\multicolumn{1}{c}{time} & \\multicolumn{1}{|c|}{distance} & found & Populations & Pop. size & Generations\\\\\n\t\t\t\t\\hline\n\t\t\t\ttsp12.dat\t\t& 12\t\t& 0,405\t& 0,00\\%\t& 10/10\t& 5\t& 500\t& 200\\\\\n\t\t\t\ttsp15.dat\t\t& 15\t\t& 0,401\t& 0,00\\%\t& 10/10\t& 5\t& 500\t& 200\\\\\n\t\t\t\ttsp17.dat\t\t& 17\t\t& 0,502\t& 0,02\\%\t& 9/10\t& 5\t& 500\t& 250\\\\\n\t\t\t\ttsp26.dat\t\t& 26\t\t& 1,037\t& 0,36\\%\t& 9/10\t& 10\t& 500\t& 250\\\\\n\t\t\t\ttsp29a.dat\t\t& 29\t\t& 1,038\t& 0,68\\%\t& 2/10\t& 10\t& 500\t& 250\\\\\n\t\t\t\ttsp29b.dat\t\t& 29\t\t& 1,049\t& 0,40\\%\t& 3/10\t& 10\t& 500\t& 250\\\\\n\t\t\t\ttsp42.dat\t\t& 42\t\t& 1,246\t& 0,75\\%\t& 2/10\t& 10\t& 500\t& 300\\\\\n\t\t\t\ttsp48a.dat\t\t& 48\t\t& 1,779\t& 2,30\\%\t& 0/10\t& 7\t& 1000\t& 300\\\\\n\t\t\t\ttsp48b.dat\t\t& 48\t\t& 1,777\t& 1,65\\%\t& 0/10\t& 7\t& 1000\t& 300\\\\\n\t\t\t\ttsp48c.dat\t\t& 48\t\t& 1,859\t& 2,91\\%\t& 0/10\t& 7\t& 1000\t& 300\\\\\n\t\t\t\ttsp60.dat\t\t& 60\t\t& 1,802\t& 3,19\\%\t& 0/10\t& 7\t& 1000\t& 300\\\\\n\t\t\t\ttsp100a.dat\t& 100\t& 3,053\t& 7,46\\%\t& 0/10\t& 7\t& 1000\t& 500\\\\\n\t\t\t\ttsp100b.dat\t& 100\t& 3,083\t& 6,33\\%\t& 0/10\t& 7\t& 1000\t& 500\\\\\n\t\t\t\t\\hline\n\t\t\t\\end{tabular}\n\t\t\\end{center}\n\t\t\\captionof{table}{Genetic algorithm tests results}\n\t\t\\vspace{1em}\n\t\tNote that computation time is highly dependent on set parameters, so if time is less important parameters could be increased to get better solutions. A direct consequence is that with genetic algorithms it's possible to get the desired precision/efficiency ratio. However as GAs don't provide an optimality proof, if an optimal solution is found, all remaining computation is executed anyway.\n\t\t\n\t\tAnother thing to consider is that, because of GAs random nature, solution effectiveness might vary a lot from run to run. This is however not the case as the solutions found, even in bigger instances, are not more than 2\\% over the average. This means that implemented genetic algorithm is reliable even if random.\n\t\t\n\t\\subsection{Tests details}\n\t\tHere have been shown the most important results, all recorded data can be found in this spreadsheet:\n\t\t\n\t\t\\href{https://docs.google.com/spreadsheets/d/1wJ98av-soxw_okteJ7X8zMJUfesh_16ECjA9uRbP8Hg/edit?usp=sharing}{\\color{blue}{https://docs.google.com/spreadsheets/d/1wJ98av-soxw\\_okteJ7X8zMJUfesh\\_16ECjA9uRbP8Hg/edit?usp=sharing}}\n\t\t", "meta": {"hexsha": "7cc93a1034738201eed65d9d3ce2a3b8d1e7aaa7", "size": 4607, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/sections/tests.tex", "max_stars_repo_name": "abeccaro/MeMOC-project", "max_stars_repo_head_hexsha": "74d6b79ac72ed573c280478820a221424fc138f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-02-07T13:28:49.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-07T13:28:49.000Z", "max_issues_repo_path": "report/sections/tests.tex", "max_issues_repo_name": "abeccaro/MeMOC-project", "max_issues_repo_head_hexsha": "74d6b79ac72ed573c280478820a221424fc138f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/sections/tests.tex", "max_forks_repo_name": "abeccaro/MeMOC-project", "max_forks_repo_head_hexsha": "74d6b79ac72ed573c280478820a221424fc138f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 66.768115942, "max_line_length": 495, "alphanum_fraction": 0.667896679, "num_tokens": 1783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.3271451592776988}}
{"text": "\\documentclass[parskip=half]{scrartcl}\n\n\\usepackage{amsmath}\n\\usepackage{mathtools}\n\\usepackage{graphicx}\n\\usepackage{hyperref}\n\\usepackage[textsize=tiny]{todonotes}\n\\graphicspath {{images/}}\n\\hypersetup{\n    colorlinks=true,\n    citecolor=blue\n}\n\n\\begin{document}\n\n\\title{CS698 (Winter 2017) Notes}\n\\author{Vineet John (v2john@uwaterloo.ca)}\n\\date{\\today}\n\\maketitle\n\n\\section{Supervised Learning}\\label{supervised-learning}\n\n    Classification: domain of output is categorical (discrete)\\\\\n    Regression: domain of output is numerical (continuous)\n\n    Input domain can be either discrete or continuous for both.\n\n    Examples:\\\\\n    Appln - Domain - Range - Type of Problem\\\\\n    Spam Identification - Words/Characters - spam/ham - classification\\\\\n    Stock Prices - Prev price/news - predicted value - regression\\\\\n    Speech recognition - Audio signal - words - classification\\\\\n    Digit recognition - Image - Digits - classification\\\\\n    Housing value - Area/bedrooms/baths - market value - regression\\\\\n    Weather prediction - Local weather/Prev weather - Temp/Rain - Regression/Classificn\n\n    Consider space of probably hypotheses\\\\\n    Approximation of a best solution is done within this space\\\\\n    A good hypothesis generalizes well\n\n    When is it not possible to find a consistent hypothesis\n\n    \\begin{itemize}\n        \\item\n        Insufficient Hypothesis space\n        \\item\n        Noise in the training data\n    \\end{itemize}\n\n    Tradeoff: Expressiveness vs complexity in finding a hypothesis - in the\n    hypothesis space\n\n\\section{Statistical Learning}\\label{statistical-learning}\n\n    \\begin{itemize}\n        \\item\n        Joint probabilities\n        \\item\n        Marginalization - sum up a join probability over a variable to express\n        it in terms of another variable\n        \\item\n        Conditional probabilities i.e A, given B\n        \\item\n        Conditional probabilies need not sum up to 1, since the idea of a\n        context is introduced.\n    \\end{itemize}\n\n    \\subsection{Bayes Rule}\\label{bayes-rule}\n\n    \\begin{itemize}\n        \\item\n        Posterior probabiliy = prediction, Prior = hypothesis, evidence =\n        input variables, likelihood = probability of evidence given the prior\n        hypothesis\n        \\item\n        Weigh each hypothesis and use all hypothesis to get an avg prediction\n        \\item\n        No overfitting, all hypotheses considered and weighed according to\n        their probabilities\n    \\end{itemize}\n\n\n\\section{Logistic Regression}\n\\label{logistic-regression}\n\n    \\subsection{Overview - Logistic Regression} % (fold)\n    \\label{sub:overview_logistic_regression}\n    \\begin{itemize}\n        \\item \n        In Mixture of Gaussians, we learn the prior and the likelihood and used Bayesian learning to compute the posterior.\n        \\item \n        Unlike Mixture of Gaussians, we learn the posterior directly by maximum likelihood\n    \\end{itemize}\n\n    % subsection overview_logistic_regression (end)\n\n    \\subsection{Problem - Singular Hessian}\\label{problem---singular-hessian}\n\n    \\begin{itemize}\n        \\item\n        Attempt is to make the ridge of the sigmoid function as shape as\n        possible\n        \\item\n        When weights tend to negative infinity, the sigmoid function tends to\n        zero\n        \\item\n        As the sigmoid is a component of the hessian, the hessian diagonal\n        then is comprised of zeoes.\n        \\item\n        This could result in the Hessian becoming a singular matrix\n    \\end{itemize}\n\n    \\subsection{Solutions}\\label{solutions}\n\n    \\begin{itemize}\n        \\item\n        Adding a penalty term to the loss function\n        \\item\n        Boils down to adding a magnified identity matrix to the Hessian\n    \\end{itemize}\n\n\\section{Generalized Linear models}\\label{generalized-linear-models}\n\n    \\begin{itemize}\n        \\item\n        Mapping the input space into a lower dimensional space\n        \\item\n        Perform linear regression of the dataset\n        \\item\n        Polynomial class of functions used as basis functions.\n        \\item\n        Basis functions are used for the mapping\n        \\item\n        The input space x is mapped as $\\Phi(x)$\n    \\end{itemize}\n\n\n\\newpage\n\n\n\\section{Perceptron \\& Neural Nets}\\label{perceptron-neural-nets}\n\n    \\begin{itemize}\n        \\item\n        Output in the form of a non-linear function\n        \\item\n        A neuron produces a single output, which may, in turn, be fed to\n        multiple other neurons.\n        \\item\n        Types of activation function:\n\n        \\begin{itemize}\n            \\item\n            Threshold: Step function, non-linear\n            \\item\n            Sigmoid: Smoother version of the step function\n        \\end{itemize}\n        \\item\n        Nets can be trained by tuning the weights.\n    \\end{itemize}\n\n    \\section{Threshold Perceptron Learning}\\label{threshold-perceptron-learning}\n\n    \\begin{itemize}\n        \\item\n        Add/subtract the input vector to/from the weights if the predicted\n        value doesn't match the target.\n        \\item\n        Eta determines the magnitude of the step-size\n        \\item\n        Gradient descent: Assuming threshold perceptron, will converge if data\n        is linearly separable.\n        \\item\n        If the data isn't linearly separable\n\n        \\begin{itemize}\n            \\item\n            The algorithm will never converge\n            \\item\n            The step vector keeps being reset back \\& forth\n        \\end{itemize}\n    \\end{itemize}\n\n    \\section{Sigmoid Perceptron}\\label{sigmoid-perceptron}\n\n    \\begin{itemize}\n        \\item\n        Similar to logistic regression in that it computes a sigmoid\n        separator.\n        \\item\n        Multiple sigmoid hyperplanes could be used to simulate a ridge-like\n        hyperplane. Further compounding can lead to simulating a bump-like\n        hyperplane.\n    \\end{itemize}\n\n    \\section{Multi-layer neural networks}\\label{multi-layer-neural-networks}\n\n    \\begin{itemize}\n        \\item\n        Mapping inputs into a linear feature space, and then applying linear\n        learning algorithms like linear regression, threshold functions,\n        mixtures of gaussians and logistic regression.\n        \\item\n        A neural net could be used to approximately just about any function\n        using a combination of neurons.\n    \\end{itemize}\n\n    \\subsection{Feedforward neural\n    network}\\label{feedforward-neural-network}\n\n    \\begin{itemize}\n        \\item\n        Adaptive non-linear basis function = function chaining\n    \\end{itemize}\n\n    \\section{Multi-Layer Neural Nets}\\label{multi-layer-neural-nets}\n\n    \\begin{itemize}\n        \\item\n        Sequential gradient descent used, similar to a gradient descent\n        approach for linear regression.\n        \\item\n        Backpropagation permits simultaneous calculation of weights for the\n        perceptrons in a multi-layered neural network.\n        \\item\n        Involves a forward and a backward phase.\n        \\item \n        The forward phase calculates the output $z_j$ for each unit $j$\n        \\item\n        The backward phase propagates errors to the input units, error denoted\n        by $\\delta_j$ at each unit $j$\n    \\end{itemize}\n\n    Neural net = composition of functions\n    \\begin{itemize}\n        \\item\n        Decompose the derivative of the error function, using the chain rule\n        \\item\n        $w_{ij}$ is the weight metric from unit i to unit j\n        \\item\n        $\\delta_{ij}$ is the error metric from unit j to unit i\n        \\item\n        Example using tanh as a hypothesis function to calculate the\n        activation weights\n    \\end{itemize}\n\n\n\\newpage\n\n\n\\section{Kernel methods}\\label{kernel-methods}\n\n    \\begin{itemize}\n        \\item\n        Avoids the complexity of convex optimization\n        \\item\n        Kernel Trick - Related to duality\n        \\item\n        Derived from the dot product of the input and it's embedding into a\n        new feature space.\n    \\end{itemize}\n\n    \\subsection{Generalized linear\n    functions}\\label{generalized-linear-functions}\n\n    \\begin{itemize}\n        \\item\n        Fixed non-linear basis functions\n        \\item\n        Limited hypothesis space\n        \\item\n        Easier to optimize\n    \\end{itemize}\n\n    \\subsection{Neural networks}\\label{neural-networks}\n\n    \\begin{itemize}\n        \\item\n        Adaptive non-linear basis functions\n        \\item\n        Rich hypothesis space\n        \\item\n        Difficult to opitimize (by virtue of being non-convex)\n    \\end{itemize}\n\n    \\section{Kernel methods (contd.)}\\label{kernel-methods-contd.}\n\n    \\begin{itemize}\n        \\item\n        Rather than trying to compute the function $\\Phi$, the\n        objective is to be able to start with an arbitrary Gram matrix.\n        \\item\n        Slide 10 - dimensionality of each vector is 2. The square function is\n        the new space than the gram matrix can emulate by computing the dot\n        product of the x vector and the z vector.\n        \\item\n        Gaussian kernel is unrelated to the PDF of a gaussian distribution.\n        \\item\n        Primal solution - scales with the number of basis functions\n        \\item \n        Dual solution - scales with data\n        \\item \n        A valid kernel must has non-zero eigenvalues, if it's being guessed rather than computed\n    \\end{itemize}\n\n\n\\newpage\n\n\n\\section{Gaussian Processes} % (fold)\n\\label{sec:gaussian_processes}\n\\begin{itemize}\n    \\item\n    Uncertainty in the weights for a linear regressor can be translated into a corresponding uncertainty for the output space. Both are modeled as Gaussian distributions.\n    \\item\n    Continuous functions implies that there are infinite Gaussian distributions that describe the output space.\n    \\item\n    Kernel function is used as a covariance matrix to indicate that the Gaussian distribution of the output space is very similar for points that are closely-correlated.\n    \\item \n    Describes a distribution over each point in the target function. \n    \\item \n    Bayesian Learning used to learn a posterior distribution of what the Gausian processes look like.\n    \\item \n    Function space view: Scales with the amount of data rather than the number of dimensions. Useful for problems where the dimensions might be infinitely many. The weight space view applies to the opposite scenario.\n    \\item \n    Example of Gait Optimization shown in Figure \\ref{fig:gait_optimization}.\n    \\begin{itemize}\n        \\item \n        Experimentation done using new feature vectors (denoted by $X_{new}$).\n        \\item \n        Minimizes the magnitude of the Gaussian deviation.\n        \\item \n        Iteratively run new experiments with different values of $X_{new}$ to converge to a result.\n    \\end{itemize}\n    \\begin{figure}[th]\n    \\centering\n    \\includegraphics[width=0.6\\textwidth]{gait_optimization}\n    \\caption{Gait Optimization}\n    \\label{fig:gait_optimization}\n    \\end{figure}\n\\end{itemize}\n\n% section gaussian_processes (end)\n\n\n\\newpage\n\n\n\\section{Support Vector Machines} % (fold)\n\\label{sec:support_vector_machines}\n\n    \\subsection{Overview - SVM} % (fold)\n    \\label{sub:overview_svm}\n\n    \\begin{itemize}\n        \\item \n        Also uses kernel trick, but the kernel uses a subset of the data.\n        \\item \n        SVM attempt to maximize the margin between the support vectors and the hyperplane. Ref Figure \\ref{fig:svm_general}\n        \\begin{figure}[th]\n        \\centering\n        \\includegraphics[width=0.4\\textwidth]{svm_general}\n        \\caption{SVM Diagram}\n        \\label{fig:svm_general}\n        \\end{figure}\n        \\item \n        SVMs are also called max-margin classifiers. $a > b$ in Figure \\ref{fig:max_margin}\n        \\begin{figure}[th]\n        \\centering\n        \\includegraphics[width=0.4\\textwidth]{max_margin}\n        \\caption{Max margin}\n        \\label{fig:max_margin}\n        \\end{figure}\n        \\item \n        $w^T \\Phi(x) = 0$ represents the linear separator\n        \\item \n        Dividing by $\\Vert w\\Vert$ ensures that the distance to the linear separator is normalized in terms of unit length.\n        \\item \n        The problem is made tractable in terms of the data by relying only on the support vectors while performing the quadratic optimization.\n        \\item \n        The quadrative objective is reformulated as a dual representation in $\\Phi(x)$\n        \\item \n        The result is an optimization objective in the auxilliary variable $a$, which is the weight for the penalty term. $a_n = 0$ for any data-points apart from the support vectors.\n    \\end{itemize}    \n    % subsection overview_svm (end)\n\n    \\subsection{Overlapping classes and slack variables} % (fold)\n    \\label{sub:overlapping_classes_and_slack_variables}\n\n    \\begin{itemize}\n        \\item $\\epsilon$ parameterized the soft-margin which is an allowance for some data point to lie beyond the margin.\n        \\item If misclassfied, $\\epsilon > 1$.\\\\ If within the soft margin, $1 > \\epsilon > 0$.\\\\ If on the margin, $\\epsilon = 0$\\\\\n        Refer to figure \\ref{fig:soft_margins}\n        \\begin{figure}[ht]\n            \\centering\n            \\includegraphics[width=0.4\\textwidth]{soft_margins.png}\n            \\caption{Soft Margins - SVM}\n            \\label{fig:soft_margins}\n        \\end{figure}\n        \\item $C$ controls how much to weigh vanilla SVMs over the new optimization problem for soft margins. Hard margin classifier implies that we're assuming the data is linearly separable.\n        \\item For the new optimization problem, earlier only support vectors were considered, but now, we consider points on the margin, points within the margin as well as misclassified points.\n        \\item Computation complexity increases as the number of vectors increase.\n    \\end{itemize}\n    \n    % subsection overlapping_classes_and_slack_variables (end)\n\n    \\subsection{Muticlass SVMs} % (fold)\n    \\label{sub:muticlass_svms}\n    \\begin{itemize}\n        \\item One vs Rest, for all classes, then combine. \n            \\begin{figure}[ht]\n                \\centering\n                \\includegraphics[width=0.4\\textwidth]{one_vs_all_and_pairwise.png}\n                \\caption{One vs. All / Pairwise}\n                \\label{fig:one_vs_all_and_pairwise}\n            \\end{figure}\n            Shaded regions are uncertain\n        \\item Pairwise comparison - exhaustive\n            Similar to the prev. SVM, there are areas of uncertainty between classes.\n        \\item Continuous ranking - Best ranked\n            \\begin{figure}[ht]\n                \\centering\n                \\includegraphics[width=0.4\\textwidth]{continuous_rank_svm.png}\n                \\caption{Continuous Ranking}\n                \\label{fig:continuous_rank_svm}\n            \\end{figure}\n            No uncertainty as we pick the highest ranked class.\n            This needs a vector $w$ to define the hyperplane for each class. where $w$ represents the distance of a point to the separating hyperplane.\n    \\end{itemize}\n    % subsection muticlass_svms (end)\n\n    \\subsection{Multi-class Classification} % (fold)\n    \\label{sub:multi_class_classification}\n    \\begin{itemize}\n        \\item Multi-class expression is a generalization of the binary SVM expression.\n        \\item The concept of soft-margins can also be applied here.\n    \\end{itemize}\n    % subsection multi_class_classification (end)\n\n    \\subsection{Comparison to Perceptrons} % (fold)\n    \\label{sub:comparison_to_perceptrons}\n\n    Perceptrons:\n    \\begin{itemize}\n        \\item \n        Linear separator - depends on starting values\n        \\item \n        Simple update rule\n        \\item \n        Prone to over-fitting\n    \\end{itemize}\n\n    Support vector machines\n    \\begin{itemize}\n        \\item \n        Unique max-margin linear separator\n        \\item \n        Quadratic optimization\n        \\item \n        Robust to over-fitting\n    \\end{itemize}\n    \n    % subsection comparison_to_perceptrons (end)\n\n% section support_vector_machines (end)\n\n\n\\newpage\n\n\n\\section{Hidden Markov Models} % (fold)\n\\label{sec:hidden_markov_models}\n\n    \\subsection{Overview - Hidden Markov Models} % (fold)\n    \\label{sub:overview_hidden_markov_models}\n        \n        \\begin{itemize}\n            \\item Data-points are not always IID. Context taken into account while predicting current value.\n            \\item Correlation with the prior data-points are leveraged.\n            \\item Stationary assumption: Assumes that the correlation between 2 output variables remains constant over the output space.\n            \\item Emission - $P(x|y)$, Transition - $P(y_t, y_{t-1})$\n            \\item Both the emission and transition are defined in terms of multinomial (discrete) distributions. e.g. values of a dice\n            \\item Joint Distribution - $P(y_{1..t}, x_{1..t}) = P(y_i) \\prod_i P(x_i|y_i) \\prod_i P(y_i|y_{i-1}) $\n            \\item Example - cascading uncertainty for a robot's movements over time.\n            \\item HMM Problem: $P(y_t|x_t .. x_1) $\n        \\end{itemize}\n\n    % subsection overview_hidden_markov_models (end)\n\n    \\subsection{Applications of HMMs} % (fold)\n    \\label{sub:applications_of_hmms}\n\n        \\textbf{Monitoring}\n        \\begin{itemize}\n            \\item Predicting the current output state given a historical set of inputs.\n            \\item Can be expressed in terms of a recursive algorithm, that will required the output classes of the previous epochs.\n            \\item Forward algorithm - computes from the 0th epoch. Linear complexity in the number of epochs.\n        \\end{itemize}\n\n        \\textbf{Prediction/Forecasting}\n        \\begin{itemize}\n            \\item Similar approach to monitoring. Can be expressed recursively.\n        \\end{itemize}\n\n        \\textbf{Hindsight}\n        \\begin{itemize}\n            \\item Computing the output class at a given epoch, given input observations in the past and future. $1 < k < t$\n            \\item Forward-backward algorithm - uses epochs $1..k$ in the forward phase and $k..t$ in the backward phase.\n        \\end{itemize}\n\n        \\textbf{Most likely explanation}\n        \\begin{itemize}\n            \\item Predict entire sequence of output class $y_1..y_t$. Can be used in the context of speech recognition.\n        \\end{itemize}\n\n        Viterbi algorithm - dynamic programming formulation. Discrete distribution of the output class y depends on the Initial State ($\\pi$), Transition ($\\theta$) and Emission ($\\phi$)\n\n        \\textbf{Example}\n        \\begin{itemize}\n            \\item 2 classes - walking($c_1$) and sitting ($c_2$)\n            \\item input measurements (accelerometer) - high ($v_1$) and low ($v_2$)\n            \\item 100 training experiments\n            \\item \n                Statistics\n                \\begin{itemize}\n                    \\item $\\#c_1^{start} = 90$, $\\#c_2^{start} = 10$\n                    \\item $\\#(c_1, c_1) = 80000$, $\\#(c_2, c_1) = 20000$\n                    \\item $\\#(c_1, c_2) = 10000$, $\\#(c_2, c_2) = 90000$\n                    \\item $\\#(v_1, c_1) = 75000$, $\\#(v_2, c_1) = 25000$\n                    \\item $\\#(v_1, c_2) = 30000$, $\\#(v_2, c_2) = 70000$\n                    \\item $P(y_{start} = c_1) = 0.9$, $P(y_{start} = c_2) = 0.1$\n                    \\item Frequency of starting with a particular class\n                        \\begin{itemize}\n                            \\item Transition\n                            \\begin{table}[ht]\n                                \\centering\n                                \\begin{tabular}{| l | c c |}\n                                    \\hline\n                                    \\textbf{} & \\textbf{$c_1$} & \\textbf{$c_2$} \\\\\n                                    \\hline\\hline\n                                        $c_1$ & 0.8 & 0.2 \\\\\n                                    \\hline\n                                        $c_2$ & 0.1 & 0.9 \\\\\n                                    \\hline\n                                \\end{tabular}\n                                \\caption{Transition Probabilities}\n                                \\label{tab:transition_probabilities}\n                            \\end{table}\n                            \\item Emission\n                            \\begin{table}[ht]\n                                \\centering\n                                \\begin{tabular}{| l | c c |}\n                                    \\hline\n                                    \\textbf{} & \\textbf{$v_1$} & \\textbf{$v_2$} \\\\\n                                    \\hline\\hline\n                                        $c_1$ & 0.75 & 0.25 \\\\\n                                    \\hline\n                                        $c_2$ & 0.3 & 0.7 \\\\\n                                    \\hline\n                                \\end{tabular}\n                                \\caption{Emission Probabilities}\n                                \\label{tab:emission_probabilities}\n                            \\end{table}\n                        \\end{itemize}\n                \\end{itemize}\n        \\end{itemize}\n\n        \\textbf{Forward algorithm - Example of Monitoring}\n        \\begin{itemize}\n            \\item Input set is $[v_1, v_1, v_2, v_2]$. Could be accelometer readings.\n            \\item $P(y_1|v_1) \\propto P(v_1|y_1)P(y_1) = [0.675, 0.03] \\propto [0.9574,  0.0426] (normalized) $\n            \\item $P(y_2|v_1, v_1) \\propto P(v_1|y_2) \\sum_{y_1} P(y_2|y_1) P(y_1|v_1) = [0.5809, 0.0402] \\propto [0.9553, 0.0647] (c_1, c_2) $\n            \\item $P(y_3|v_1, v_1, v_2) \\propto P(v_3|y_3) \\sum_{y_2} P(y_3|y_2) P(y_2|v_1, v_1) = [0.1903, 0.1063] \\propto [0.6417, 0.3583] $\n            \\item $P(y_4|v_1, v_1, v_2, v_2) \\propto P(v_4|y_4) \\sum_{y_3} P(y_4|y_3) P(y_3|v_1, v_1, v_2) = [0.1463, 0.2707] \\propto [0.3308, 0.6492] $\n        \\end{itemize}\n        \n        \\textbf{Most likely explanation - Example}\n        \\begin{itemize}\n            \\item \n            $$f(y_1, y_2) = P(y_2|y_1) P(v_1|y_1) P(y_1)$$\n            $$[y_1 = c_1, y_1 = c_2] [y_2 = c_1, y_2 = c_2] = [[0.54, 0.135], [0.003, 0.027]] $$\n            $$\\max_{y_1} P(y_1y_2|v_1) = \\max_{y_1} f(y_1, y_2) = [0.54, 0.135] $$\n            \\item \n            $$f(y_2, y_3) = P(y_3|y_2) P(v_1|y_2) \\max_{y_1} P(y_1y_2|v_1)$$\n            $$[y_2 = c_1, y_1 = c_2] [y_3 = c_1, y_2 = c_2] = [[0.324, 0.081], [0.0041, 0.0345]] $$\n            $$\\max_{y_1y_2} P(y_1y_2y_3|v_1v_1) = \\max_{y_2} f(y_2, y_3) = [0.324, 0.081] $$\n            \\item \n            $$f(y_3, y_4) = P(y_4|y_3) P(v_2|y_3) \\max_{y_1y_2} P(y_1y_2y_3|v_1v_1)$$\n            $$[y_3 = c_1, y_1 = c_2] [y_4 = c_1, y_2 = c_2] = [[0.0648, 0.0162], [0.0057, 0.0310]] $$\n            $$\\max_{y_1y_2y_3} P(y_1y_2y_3y_4|v_1v_1v_2) = \\max_{y_3} f(y_3, y_4) = [0.0648, 0.051] $$\n            \\item \n            $$f(y_4) = P(v_2|y_4) \\max_{y_1y_2y_3} P(y_1y_2y_3y_4|v_1v_1v_2)$$\n            $$[y_4 = c_1, y_4 = c_2] = [0.0162, 0.357] $$\n            $$\\max_{y_1y_2y_3y_4} P(y_1y_2y_3y_4|v_1v_1v_2v_2) \\propto \\max_{y_4} f(y_4) = 0.0357 $$\n        \\end{itemize}\n\n    \n    % subsection applications_of_hmms (end)\n\n% section hidden_markov_models (end)\n\n\\newpage\n\n\n\\section{Deep Neural Networks} % (fold)\n\\label{sec:deep_neural_networks}\n\n    \\begin{itemize}\n        \\item \n        Example of scaling w.r.t. depth of the network as opposed to a single hidden layer (Parity function.)\n        \\item \n        Most popular activation functions for units - sigmoid (0 to 1) and tanh (-1 to 1)\n        \\item \n        \\textbf{Vanishing gradient}\n        \\begin{itemize}\n            \\item \n            Vanishing gradient problem: Appearing to converge too soon. Gradient might not result in any change in the initial layers after backpropagation.\n            \\item \n            Sequential squashing of the gradient results in gradually vanishing over time. Chain rule results in multiplying multiple numbers between 0 and 1, which could lead to computing a gradient below the required threshold to take a step in the direction of the minima of the convex function.\n            \\item \n            Compounded product of the output value ranges over multiple layers resultings in the gradient converging to 0. This is because both the output and the gradient for both logistic sigmoid units and hyperbolic tan units are always between 0 and 1 in terms of magnitude.\n            \\item \n            Possible solutions include \n            \\begin{itemize}\n                \\item \n                Using a larger gradient for the layers close to the output layer.\n                \\item \n                Using pre-trained units.\n                \\item \n                Using recitified linear units.\n            \\end{itemize}\n        \\end{itemize}\n    \\end{itemize}\n\n    \\subsection{Rectified Linear Units} % (fold)\n    \\label{sub:rectified_linear_units}\n    \n    \\begin{itemize}\n        \\item \n        $h(a) = max(0, a) $\n        \\item \n        Softplus: $h(a) = log(1 + e^a) $, where $a = \\sum_i w_i x_i $\n        \\item \n        If gradient is negative, don't back-propagate, if not, then set gradient to 1. This ensures that the gradient doesn't vanish for pathways in the network with $a > 0$.\n        \\item \n        Softplus might also result in a vanishing gradient if the network has several layers.\n        \\item \n        The disadvantage of using the rectified linear function is that it only approximately a linear function at most. Piecewise linear function (Figure \\ref{fig:piecewise-linear-function}). \n        \\begin{figure}[ht]\n            \\centering\n            \\includegraphics[width=0.4\\textwidth]{piecewise-linear-function}\n            \\caption{Piecewise Linear Function}\n            \\label{fig:piecewise-linear-function}\n        \\end{figure}\n    \\end{itemize}\n\n    % subsection rectified_linear_units (end)\n\n    \\subsection{Maxout Units} % (fold)\n    \\label{sub:maxout_units}\n\n        \\begin{itemize}\n            \\item Maxout Unit (Figure \\ref{fig:maxout-unit})\n            \\begin{figure}[ht]\n                \\centering\n                \\includegraphics[width=0.4\\textwidth]{maxout-unit}\n                \\caption{Maxout Unit}\n                \\label{fig:maxout-unit}\n            \\end{figure}\n            \\item \n            Choose $a$ such that $a = max(a_1, a_2, a_3)$, where $a_{ij} = \\sum_j w_{ij} z_j $\n            \\item \n            Produces a piecewise linear function, which is also convex.\n        \\end{itemize}\n    \n    % subsection maxout_units (end)\n\n    \\subsection{Overfitting} % (fold)\n    \\label{sub:overfitting}\n\n    \\begin{itemize}\n        \\item \n        Due to high expressivity, the data could be very easily overfit.\n        \\item \n        Solutions:\n        \\begin{itemize}\n            \\item \n            Regularization: Penalizing large weights\n            \\item \n            Data augmentation: Minor variations in the input data to allow the network to train a model that is invariant to small changes in the input data.\n            \\item \n            Dropout: Randomly drop some units from the network during the training phase. Intended to increase network robustness against overfitting to specific datapoints.\\\\\n            Dropout can be viewed as an approximation ensemble learning. Units need to stay in memory for this to work.\n        \\end{itemize}\n    \\end{itemize}\n    \n    % subsection overfitting (end)\n    \n% section deep_neural_networks (end)\n\n\n\n\\section{Convolutional Neural Networks} % (fold)\n\\label{sec:convolutional_neural_networks}\n\n    \\begin{itemize}\n        \\item \n        Convolution: A mathematical operation on two function that produced a third, which can be viewed as a modified version of one of the initial two functions.\n        \\item \n        Example of convolution: smoothing a function. (Figure \\ref{fig:cnn-smoothing})\n        \\begin{figure}[ht]\n            \\centering\n            \\includegraphics[width=0.4\\textwidth]{cnn-smoothing}\n            \\caption{Smoothing function - convolution}\n            \\label{fig:cnn-smoothing}\n        \\end{figure}\n        \\item \n        $x$, the original input, is multiplied by a weight factor $w$ to obtain an output (either discrete or continous)\n        \\item \n        Image example: white-to-black produces a black edge and vice-versa. Simple convolution.\n        \\item \n        Could also be used for feature extraction when combined with an activation function.\n        \\item \n        A convolution is a linear subset of units based on a specific weight vector.\n        \\item \n        Activation functions confirm the existence of a patter.\n        \\item \n        Gabor filters: Base weights used for image recognition. Comparisons against them could be use to detect patterns via convolutions.\n        \\item \n        Architecture: Comprised of alternating convolutional and pooling layers. (Figure \\ref{fig:cnn-arch})\n        \\begin{figure}[ht]\n            \\centering\n            \\includegraphics[width=0.4\\textwidth]{cnn-arch}\n            \\caption{CNN Architecture}\n            \\label{fig:cnn-arch}\n        \\end{figure}\n        \\item \n        Pooling: Aggregating the output of the result of the convolutional layer. It could be using a max/sum/avg function.\n        \\item \n        A max pooling function could simulate an invariant i.e. doesn't matter which section of a given patch a pattern is found in.\n        \\item \n        Pooling function is typically a commutative math operator.\n    \\end{itemize}\n\n\n    \\subsection{CNN Properties} % (fold)\n    \\label{sub:cnn_properties}\n    \n        \\begin{itemize}\n            \\item \n            CNNs won't usea fully connected network. Connections are sparse because only contiguous patches of the image are considered as input features to the convolutional layers.\n            \\item \n            Weights are the same across a single layer, so the fact that they are shared simplifies the network.\n        \\end{itemize}\n\n    % subsection cnn_properties (end)\n\n    \\subsection{MNIST CNN Example} % (fold)\n    \\label{sub:mnist_cnn_example}\n\n        \\begin{itemize}\n            \\item \n            32x32 images, 5x5 patches as features for the convolutional layer, resulting in an abstracted 28x28 input space. Pooling layer of 2x2 dimensions, which means that every 4 units is pooled, reducing the feature space to a 14x14 space.\n            \\item \n            This 14x14 is now treated as the original 32x32 image, and recursively worked on by alternating convolutional and pooling layers.\n        \\end{itemize}\n    \n    % subsection mnist_cnn_example (end)\n\n% section convolutional_neural_networks (end)\n\n\n\\newpage\n\n\n\\section{Recurrent/Recursive Neural Networks} % (fold)\n\\label{sec:recurrent_recursive_neural_networks}\n\n    \\begin{itemize}\n        \\item \n        Typically used when the input data is comprised of sequences, time series, textual data.\n        \\item \n        Weights are shared across time steps.\n        \\item \n        Unit representation: (Figure \\ref{fig:rnn-units})\n        \\begin{figure}[ht]\n            \\centering\n            \\includegraphics[width=0.4\\textwidth]{rnn-units}\n            \\caption{RNN Units}\n            \\label{fig:rnn-units}\n        \\end{figure}\n        \\item \n        Errors tend to cascade in RNNs, as they are based on sequential data. The errors might also be compounded.\n        \\item \n        HMMs can be a specific implementation of an RNN. \n        Belief monitoring can be done as shown below. Figure \\ref{fig:rnn}\n        $P(Y_1|X_1)$ could be computed as either the sigmoid or softmax (binary/categorical outputs), or a Gaussian distribution (continuous outputs)\n        \\begin{figure}[ht]\n            \\centering\n            \\includegraphics[width=0.7\\textwidth]{rnn}\n            \\caption{RNN - Belief Monitoring}\n            \\label{fig:rnn}\n        \\end{figure}\n        \\item \n        Prediction cannot be done since the output $y$ at a given time-step depends on it's input at the same step.\n        \\item \n        HMM: more flexible queries\\\\\n        RNN: more expressive distributions\n    \\end{itemize}\n\n\n    \\subsection{Bi-directional RNN} % (fold)\n    \\label{sub:bi_directional_rnn}\n        \\begin{itemize}\n            \\item Hindsight queries : Figure \\ref{fig:bi-directional_rnn}\n            \\begin{figure}[ht]\n            \\centering\n            \\includegraphics[width=0.7\\textwidth]{bi-directional_rnn}\n            \\caption{Bi-directional RNN - Hindsight queries}\n            \\label{fig:bi-directional_rnn}\n        \\end{figure}\n            \\item \n            $P(y_2| x_1, x_2, x_3, x_4)$ is an example of a hindsight prediction that can be made using bi-directional RNNs.\n        \\end{itemize}\n    % subsection bi_directional_rnn (end)\n\n    \\subsection{Encoder - Decoder Model} % (fold)\n    \\label{sub:encoder_decoder_model}\n\n        \\begin{itemize}\n            \\item \n            \\textbf{Usage in Machine translation:}\n            \\begin{itemize}\n                \\item \n                Encoding sentences into a vector representation.\n                \\item \n                The encoded segment is the context.\n                \\item \n                While decoding, each step in the model stores what the network has translated thus far, the output for this is the word in the new language.\n            \\end{itemize}\n        \\end{itemize}\n    \n    % subsection encoder_decoder_model (end)\n\n    \\subsection{Recursive Neural Networks} % (fold)\n    \\label{sub:recursive_neural_networks}\n\n        \\begin{itemize}\n            \\item \n            Generalize recurrent neural networks from chains to trees.\n            \\item \n            Useful to identify vector representation of variable length data.\n            \\item \n            Applications for Semantic Parsing. Figure \\ref{fig:dependency-parser}\n            \\begin{figure}[ht]\n                \\centering\n                \\includegraphics[width=0.7\\textwidth]{dependency-parser}\n                \\caption{Dependency Parsing}\n                \\label{fig:dependency-parser}\n            \\end{figure}\n        \\end{itemize}\n    \n    % subsection recursive_neural_networks (end)\n\n    \\subsection{LSTM} % (fold)\n    \\label{sub:lstm}\n\n        \\begin{itemize}\n            \\item \n            Gate units determine if the input is to be kept in memory or discarded\n            \\item \n            Recurrent gate units decide whether or not to preserve the memory contents of the previous time-step\n            \\item \n            Similarly there exists a gated output which decides whether or not the LSTM unit produces an output at the given time-step\n        \\end{itemize}\n    \n    % subsection lstm (end)\n        \n% section recurrent_recursive_neural_networks (end)\n\n\n\\section{Autoencoders} % (fold)\n\\label{sec:autoencoders}\n\n    \\begin{itemize}\n        \\item \n        $x \\Rightarrow f(x) \\Rightarrow g(f(x)) \\Rightarrow x$\n        \\item \n        Architecture: Figure \\ref{fig:autoencoders}.\n        \\begin{figure}[ht]\n            \\centering\n            \\includegraphics[width=0.7\\textwidth]{autoencoders}\n            \\caption{Autoencoders}\n            \\label{fig:autoencoders}\n        \\end{figure}\n    \\end{itemize}\n\n    \\textbf{Linear Autoencoder}\n    \\begin{itemize}\n        \\item \n        No activation function involved. The hidden layer is infered from the weights.\n        \\item \n        $W_g W_f x = x$\n        \\item \n        $W_g W_f$ would need to be an identity matrix. This derivation is not trivial due to the reduced dimensionality. $W_g$ and $W_f$ are pseudo-inverses of each other.\n        \\item \n        Deriving the weights using the Euclidean norm objective is equivalent to PCA.\n    \\end{itemize}\n\n    \\textbf{Non-linear Autoencoder}\n    \\begin{itemize}\n        \\item \n        Non-linear manifold \n        \\item \n        $f$ is a non-linear function that can map data into a lower-dimensional representation. $g$ is another non-linear function that does the exact opposite.\n    \\end{itemize}\n\n    \\textbf{Deep Autoencoder:}\n    $f$ and $g$ both consist of multiple layers\n\n    \\textbf{Sparse Representation:}\n    The hidden layer can be just as large as the input layer, but the loss function penalizes non-zero entries, and tries to create the intermediate representation of the data which is sparse.\n\n    \\textbf{Denoising Data:}\n    Loss function would use the noisy version as input and the clean version as output.\n\n    \\textbf{Probabilistic Autoencoder:}\n    Illustration: Figure \\ref{fig:autoencoders}.\n    \\begin{figure}[ht]\n        \\centering\n        \\includegraphics[width=0.7\\textwidth]{probabilistic-autoencoder}\n        \\caption{Probabilistic Autoencoder}\n        \\label{fig:probabilistic-autoencoder}\n    \\end{figure}\n\n    \\textbf{Generative Model:}\n    Sample the hidden `h' and use it as a generative base by which to generate values of `x'.\n\n\n% section autoencoders (end)\n\n\n\\section{Generative Adversarial Networks} % (fold)\n\\label{sec:generative_adversarial_networks}\n\n    \\begin{itemize}\n        \\item \n        Similar to Probabilistic Autoencoders, we can use the distribution $P(h)$ to sample new values for $x$.\n        \\item \n        Problem: how to come up with a $P(h)$?\n    \\end{itemize}\n\n    \\textbf{Variational Autoencoder:}\n    \\begin{itemize}\n        \\item \n        The encoded representation $h$ should be a Gaussian distribution with mean 0 and variance 1.\n        \\item \n        Encoder part of network should approximate the mean and the variance.\n        \\item \n        Illustration: Figure \\ref{fig:variation-autoencoder}.\n        \\begin{figure}[ht]\n            \\centering\n            \\includegraphics[width=0.7\\textwidth]{variation-autoencoder}\n            \\caption{Variational autoencoder}\n            \\label{fig:variation-autoencoder}\n        \\end{figure}\n        \\item \n        Sampling hinders backpropagation.\n    \\end{itemize}\n\n    \\textbf{Generative Adversarial Network:}\n    \\begin{itemize}\n        \\item \n        Game theoretic basis\n        \\item \n        Generator vs Discriminator (compete; trained simultaneously)\n        \\item \n        $W_d$ is minimized by a gradient descent algorithm during which $W_g$ remains static.\n        Conversely, $W_g$ is maximized by a gradient ascent algorithm during which $W_d$ remains static.\n        \\item \n        Illustration: Figure \\ref{fig:gan-architecture}.\n        \\begin{figure}[ht]\n            \\centering\n            \\includegraphics[width=0.5\\textwidth]{gan-architecture}\n            \\caption{GAN Architecture}\n            \\label{fig:gan-architecture}\n        \\end{figure}\n    \\end{itemize}\n\n% section generative_adversarial_networks (end)\n\n\n\\newpage\n\n\n\\section{Ensemble Learning} % (fold)\n\\label{sec:ensemble_learning}\n\n    \\begin{itemize}\n        \\item \n        Method to combine several hypotheses into a single stronger hypotheses.\n        \\item \n        Bagging: Majority voting for a hypothesis, in classification problems\n        \\item \n        Boosting: Computes a weighted majority\n    \\end{itemize}\n\n    \\textbf{Bagging vs. Boosting}\n    \\begin{itemize}\n        \\item \n        Bagging\n        \\begin{itemize}\n            \\item \n            Majority vote of a set of hypotheses\n            \\item\n            Assumptions: Hypotheses are independent (error probability independent and roughly the same)\n        \\end{itemize}\n        \\item \n        Boosting\n        \\begin{itemize}\n            \\item \n            Weighted majority vote\n            \\item \n            Weighted based on respective error rates\n            \\item \n            Different hypotheses can be obtained by varying the weight of each datapoint in the training set.\n        \\end{itemize}\n    \\end{itemize}\n\n    \\begin{figure}[ht]\n        \\centering\n        \\includegraphics[width=.4\\textwidth]{bagging_independent_classifiers}\n        \\caption{Bagging - Independent Classifiers}\n        \\label{fig:bagging_independent_classifiers}\n    \\end{figure}\n\n    \\textbf{Random forests:} Bagging, with decision trees (only classification)\n\n    \\textbf{Combining classifier parameters: } Might not always provide the benefits of ensemble learning. Combining the predictions usually proves to be more useful. Refer to Figure \\ref{fig:parameter_averaging}. The 2 neural networks are independently accurate at computing the XOR, but averaging the weights yields an incorrect computation.\n    \\begin{figure}[ht]\n        \\centering\n        \\includegraphics[width=.4\\textwidth]{parameter_averaging}\n        \\caption{Parameter Averaging}\n        \\label{fig:parameter_averaging}\n    \\end{figure}\n\n% section ensemble_learning (end)\n\n\n\\newpage\n\n\n\\section{Stream Learning} % (fold)\n\\label{sec:stream_learning}\n\n    \\begin{itemize}\n        \\item \n        Model continuously refreshed as new training data arrives.\n        \\item \n        Bayesian learning being inherently suited to stream/online learning.\n        \\item \n        Posterior hypothesis at each point is used as the prior belief for the next point.\n        \\item \n        To avoid iterating multiple times over the training data, stochastic gradient descent is used.\n    \\end{itemize}\n\n    \\textbf{Robbins-Monro sufficient conditions}\n    \\begin{itemize}\n        \\item \n        Choose learning rate $a_n$ such that $\\sum_{n=1}^{\\infty} a_n = \\infty$, but $\\sum_{n=1}^{\\infty} (a_n)^2 < \\infty$\n        \\item \n        Example of $a_n$ is $\\frac{1}{n} $\n    \\end{itemize}\n\n% section stream_learning (end)\n\n\n\\newpage\n\n\n\\section{Formulae} % (fold)\n\\label{sec:formulae}\n\n    \\begin{itemize}\n\n        \\item \n        KNN: \n        $$y_x = mode({y_{x'}| x' \\in knn(x)})$$\n\n        \\item \n        Weighted KNN (used for regression): \n        $$y_x = \\sum_{x' \\in knn(x)} w(x, x') y_{x'}$$\n\n        \\item \n        Euclidean Loss: \n        $$L(w) = \\frac{1}{2} \\sum_{n=1}^{N} (y(x_n, w) - t_n)^2 $$\n\n        \\item \n        Linear regression Convex Optimization Objective:\n        $$w = A^{-1}b$$\n        where\n        $$A = \\sum_{n=1}^{N} \\bar{x_n} \\bar{x_n}^T$$ and $$b = \\sum_{n=1}^{N} t_n \\bar{x_n}$$\n\n        \\item \n        Regularized Ridge Regression: \n        $$w = argmin_w \\frac{1}{2} \\sum_{n=1}^{N} (y(x_n, w) - t_n)^2 + \\lambda \\lVert w \\rVert $$\n        equivalent to \n        $$w = (\\lambda I + A)^{-1}b$$\n\n        \\item \n        Joint distribution marginalization\n        $$Pr(A = a) = \\sum_b Pr(A = a \\wedge B = b) $$\n\n        \\item \n        Conditional Probability\n        $$Pr(A|B) = \\frac{Pr(A \\wedge B)}{Pr(B)} $$\n        implying the chain rule,\n        $$Pr(A \\wedge B) = Pr(A|B) Pr(B)$$\n\n        \\item \n        Bayes Rule:\n        $$Pr(B|A) = \\frac{Pr(A|B) Pr(B))}{Pr(A)} $$\n\n        \\item \n        Bayesian Learning: \\\\\n        Prior: $Pr(H)$ \\\\\n        Likelihood: $Pr(e|H)$ \\\\\n        Evidence: $e = <e_1, e_2, ... e_n>$\n        $$Pr(H|e) = k Pr(e|H) Pr(H)$$\n        where $k$ is a normalizing constant equivalent to $Pr(e)$ in Bayes Rule\n\n        For a given hypothesis,\n        $$Pr(e|h) = \\prod_n P(e_n|h)$$\n\n        \\item \n        Maximum a posteriori (MAP):\n        $$h_{map} = argmax_{h_i} P(h_i|e)$$\n        $$h_{map} = argmax_{h_i} P(h) P(e|h_i)$$\n\n        \\item \n        Maximum likelihood estimation:\n        Same as MAP, except that all the hypotheses have an equal prior probability.\n        $$h_{mle} = argmax_{h_i} P(e|h_i)$$\n        $$h_{mle} = argmax_{h_i} \\sum_n \\log P(e_n|h)$$\n\n        \\item \n        Gaussian PDF:\n        $$\\frac{1}{\\sqrt{2\\pi\\sigma}} e^{- \\frac{(x - \\mu)^2}{2 \\sigma^2}}$$\n\n        \\item \n        Bias - Variance tradeoff\n        $$E[loss] = bias^2 + variance + noise$$\n\n        \\item \n        Bayesian Linear Regression:\n        $$\\bar{w} = \\sigma^{-2} A^{-1} \\bar{X}^T y $$\n        where\n        $$A = \\sigma^{-2} \\bar{X}^T \\bar{X} + \\Sigma^{-1}$$\n\n        \\item \n        Mixture of Gaussians Posterior Distribution:\n        $$Pr(C_k|x) = \\frac{1}{1 + e^{-(w^Tx + w_0)}}$$\n        where\n        $$w = \\Sigma^{-1} (\\mu_k - \\mu_j)$$\n        $$w_0 = -\\frac{1}{2} \\mu_k^T \\Sigma^{-1} \\mu_k + \\frac{1}{2} \\mu_j^T \\Sigma^{-1} \\mu_j + \\ln\\frac{\\pi_k}{\\pi_j}$$\n\n        \\item \n        Mixture of Gaussians MLE Solution:\n        $$\\pi = \\frac{\\sum_{n \\in c_1} 1}{N}$$\n        $$\\mu_1 = \\frac{\\sum_{n \\in c_1} x_n}{N}; \\mu_2 = \\frac{\\sum_{n \\in c_2} x_n}{N}$$\n        $$\\Sigma = \\frac{S_1 + S_2}{N}$$\n        where \n        $$S_1 = \\sum_{n \\in c_1} (x_n - \\mu_1) (x_n - \\mu_1)^T; S_2 = \\sum_{n \\in c_2} (x_n - \\mu_2) (x_n - \\mu_2)^T$$\n\n        \\item \n        Logistic Regression Loss function:\n        $$L(w) = - \\sum_n y_n \\ln \\sigma(w^T \\bar{x}) + (1 - y_n) \\ln (1 - \\sigma(w^T \\bar{x})) $$\n\n        \\item \n        Logistic Regression Gradient descent:\n        $$w = w - H^{-1} \\nabla L(w)$$\n        where H is the Hessian matrix\n        $$H = \\bar{X} R \\bar{X}^T$$\n        R is a diagonal matrix with $R_{ii} = \\sigma_i(1 - \\sigma_i)$ and $\\sigma_i = \\sigma(w^T \\bar{x}_n)$\n\n        \\item \n        Perceptron Learning Gradient Descent:\n        $$w = w - \\eta \\nabla E$$\n        where $$E = - \\sum_{(x_n, y_n) \\in M} y_n w^T x_n$$\n        and M is a set of misclassified examples and $y \\in (1, -1) \\forall y$\n\n        \\item\n        Sigmoid perceptron learning min squared error:\n        $$E(w) = \\frac{1}{2} \\sum_n (y_n - \\sigma(w^T x_n))^2 $$\n        $Also, \\nabla(\\sigma) = \\sigma(1 - \\sigma)$\n\n        \\item \n        Multi-layer neural network error function:\n        $$E(w) = \\frac{1}{2} \\lVert f(x_n, W) - y_n \\rVert_2^2 $$\n\n        \\item \n        Multi-layer neural network Gradient descent\n        $$w_{ji} = w_{ji} - \\eta \\frac{\\partial E_n}{\\partial w_{ji}} $$\n\n        \\item \n        Backpropagation algorithm\n        \\begin{equation*}\n        \\delta_j = \\left\\{\n        \\begin{array}{@{}ll@{}}\n        h'(a_j) (z_j - y_j), & \\text{base case, if j is an output unit} \\\\\n        h'(a_j) \\sum_k w_{kj}\\delta_k, & \\text{recursion, if j is a hidden unit}\n        \\end{array}\\right.\n        \\end{equation*} \n\n        \\item \n        Kernel function:\n        $$k(x, x') = \\phi(x)^T \\phi(x') $$\n\n        \\item \n        Weights:\n        $$w = - \\frac{1}{\\lambda} \\sum_n (w^T \\phi(x_n) - y_n) \\phi(x_n) $$\n        $$\\Phi = [\\phi(x_1), \\phi(x_2) ... \\phi(x_N)] $$\n        $$w = \\Phi a $$\n        $$a_n = - \\frac{1}{\\lambda} (w^T \\phi(x_n) - y_n) $$\n\n        \\item \n        Gram matrix\n        $$K = \\Phi^T \\Phi$$\n        Optimal $a$\n        $$a = (K + \\lambda I)^{-1} y $$\n\n        \\item \n        Kernel prediction:\n        $$y_* = \\phi(x_*)^T w $$\n        $$y_* = \\phi(x_*)^T \\Phi a $$\n        $$y_* = k(x_*, X) (K + \\lambda I)^{-1} y $$\n        where $(X, y)$ is the training set and $(x_*, y_*)$ is the test instance\n\n        \\item\n        Given that $k_1(x, x')$ and $k_2(x, x')$ are valid kernels, the below kernels are valid too\n        \\begin{itemize}\n            \\item \n            $ck_1(x, x') \\forall c>0 $\n            \\item \n            $f(x)k_1(x, x')f(x') $\n            \\item \n            $q(k_1(x, x')) $ where q is a polnomial with co-efficients $\\geq 0$\n            \\item \n            $exp(k_1(x, x')) $\n            \\item \n            $k_1(x, x') + k_2(x, x')$\n            \\item \n            $k_1(x, x')k_2(x, x')$\n            \\item \n            $k_3(\\phi(x), \\phi(x'))$\n            \\item \n            $x^T A x'$ where A is symmetric positive semi-definite\n            \\item \n            $k_a(x_a, x'_a) + k_b(x_b, x'_b)$\n            \\item \n            $k_a(x_a, x'_a)k_b(x_b, x'_b)$ where $x = \\left(\\begin{array}{c} x_a\\\\ x_b\\\\ \\end{array} \\right)$\n        \\end{itemize}\n\n    \\end{itemize}\n\n    % section formulae (end)\n\n\\end{document}\n\n", "meta": {"hexsha": "06c8b8e3d0feb71a01ca8dc08347c0aed9c47ba7", "size": 47242, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "cs698_w17_notes.tex", "max_stars_repo_name": "v1n337/cs698-w17-notes", "max_stars_repo_head_hexsha": "113f7388473938511c5eea6788dc2c5c4c556999", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cs698_w17_notes.tex", "max_issues_repo_name": "v1n337/cs698-w17-notes", "max_issues_repo_head_hexsha": "113f7388473938511c5eea6788dc2c5c4c556999", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cs698_w17_notes.tex", "max_forks_repo_name": "v1n337/cs698-w17-notes", "max_forks_repo_head_hexsha": "113f7388473938511c5eea6788dc2c5c4c556999", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1984251969, "max_line_length": 343, "alphanum_fraction": 0.6039541086, "num_tokens": 12591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.3271451558090056}}
{"text": "\\documentclass[a4paper,UKenglish]{lipics-v2016}\n\\usepackage{microtype}\n\\usepackage{bussproofs}\n\\usepackage{stmaryrd}\n\n\\newcommand{\\new}{\\mathsf{new}}\n\\newcommand{\\for}{\\mathrm{for }}\n\\newcommand{\\Ncal}{\\mathcal{N}}\n\\newcommand{\\interp}[1]{\\llbracket #1 \\rrbracket}\n\\newcommand{\\interpp}[1]{\\{\\!| #1 |\\!\\}}\n\\newcommand{\\from}{\\leftarrow}\n\\newcommand{\\maps}{\\colon}\n\\newcommand{\\Th}{\\mathrm{Th}}\n\\newcommand{\\Gph}{\\mathrm{Gph}}\n\\newcommand{\\FinSet}{\\mathrm{FinSet}}\n\\newcommand{\\FPGphCat}{\\mathrm{FPGphCat}}\n\\newcommand{\\Set}{\\mathrm{Set}}\n\\newcommand{\\Cat}{\\mathrm{Cat}}\n\\newcommand{\\Calc}{\\mathrm{Calc}}\n\\newcommand{\\Mon}{\\mathrm{Mon}}\n\\newcommand{\\op}{\\mathrm{op}}\n\\newcommand{\\NN}{\\mathbb{N}}\n\\newcommand{\\pic}{$\\pi$-calculus}\n\n\\title{Representing operational semantics with enriched Lawvere theories}\n\\author[1]{\nMichael Stay\n}\n\\author[2]{\nL.\\ G.\\ Meredith\n}\n\\affil[1]{\n  Pyrofex Corp., Kirkland, WA, USA\\\\\n  {\\tt stay@pyrofex.net}\n}\n\\affil[2]{\n{RChain Cooperative, Seattle, WA, USA}\\\\\n{\\tt greg@rchain.coop}\n}\n\\Copyright{Michael Stay, Lucius Gregory Meredith}\n\\subjclass{F.1.2 Modes of computation, F.3.2 Semantics of Programming Languages, F.4 Mathematical Logic and Formal Languages, D.1.3 Concurrent Programming, D.3.1 Formal Definitions and Theory, D.3.3 Language Constructs and Features}\n\\keywords{Concurrent combinator, nominal, pi calculus}\n\n%Editor-only macros:: begin (do not touch as author)%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\EventEditors{John Q. Open and Joan R. Acces}\n\\EventNoEds{2}\n\\EventLongTitle{42nd Conference on Very Important Topics (CVIT 2016)}\n\\EventShortTitle{CVIT 2016}\n\\EventAcronym{CVIT}\n\\EventYear{2016}\n\\EventDate{December 24--27, 2016}\n\\EventLocation{Little Whinging, United Kingdom}\n\\EventLogo{}\n\\SeriesVolume{42}\n\\ArticleNo{23}\n% Editor-only macros::end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\begin{document}\n\\maketitle\n\\begin{abstract}\n  \\noindent\n  Many term calculi, like $\\lambda$-calculus or {\\pic}, involve\n  binders for names, and the mathematics of bound variable names is\n  subtle.  Sch\\\"onfinkel introduced the SKI combinator calculus in\n  1924 to clarify the role of quantified variables in intuitionistic\n  logic by eliminating them. Yoshida demonstrated how to\n  eliminate the bound names coming from the input prefix in the\n  asynchronous {\\pic}, but her combinators still depend on the $\\new$\n  operator to bind names.  Recently, Meredith and Stay\n  showed how to modify Yoshida's combinators by replacing $\\new$ and\n  replication with reflective operators to provide the first\n  combinator calculus with no bound names into which the asynchronous\n  {\\pic} has a faithful embedding. Here we provide an alternative set\n  of combinators built from $\\mathsf{SKI}$ plus reflection that also\n  eliminates all nominal phenomena, yet provides a faithful\n  embedding  of a reflective higher-order pi calculus. \n  We show that with the nominal features effectively\n  eliminated as syntactic sugar, multisorted Lawvere theories enriched\n  over graphs suffice to capture the operational semantics of the\n  calculus.\n\\end{abstract}\n\\EnableBpAbbreviations\n\n\\section{Introduction}\nMany term calculi, like $\\lambda$-calculus or {\\pic}, involve binders\nfor names, and the mathematics of bound variable names is subtle.\nSch\\\"onfinkel introduced the SKI combinator calculus in 1924 to\nclarify the role of quantified variables in intuitionistic logic by\neliminating them \\cite{finkel}. Yoshida demonstrated how to eliminate\nthe bound names coming from the input prefix in the asynchronous\n{\\pic}, but her combinators still depend on the $\\new$ operator to\nbind names. Curry developed Sch\\\"onfinkel's ideas much\nfurther. Recently, Meredith and Stay \\cite{Rhocomb} showed how to\nmodify Yoshida's combinators by replacing $\\new$ and replication with\nreflective operators to provide the first combinator calculus with no\nbound names into which the asynchronous {\\pic} has a faithful\nembedding of a reflective higher-order pi calculus. \nHere we provide an alternative set of combinators built\nfrom $\\mathsf{SKI}$ plus reflection that also eliminates all nominal\nphenomena, yet provides a faithful embedding.\n\nThe recent work by Jamie Gabbay and Andrew Pitts\n\\cite{DBLP:journals/fac/GabbayP02} and others\n\\cite{DBLP:journals/jcss/Clouston14} on nominal set theory has put the\nstudy of bound names and substitution on a much nicer foundation, at\nthe cost of an increase in the complexity of the semantic\nframework. It interprets nominal phenomena in terms of atoms in\nFraenkl-Mostowski set theory. Clouston's work in particular makes\nevident the additional machinery needed to interpret nominal phenomena\nas Lawvere theories. On the other hand, with the nominal features\neffectively eliminated as syntactic sugar, we show that multisorted\nLawvere theories enriched over graphs suffice to capture the\noperational semantics of the calculus.\n\n\\section{Previous work}\n\nThere is a long history and an enormous body of work on modeling term rewriting and operational semantics with various notions of category enriched over category-like structures; we only have room here for a sampling.  L\\\"uth and Ghani \\cite{DBLP:conf/ctcs/LuethG97} use poset-enriched categories to study the modularity of strong normalization.  One approach to nominality is the one we mentioned in the introduction; a different approach deals with nominal issues by allowing ``funtion types'' in the signature:  Seely \\cite{DBLP:conf/lics/Seely87} \n% R. A. G. Seely, Modeling computations: a 2-categorical framework, in Proc. Symp. Logic Comp. Sci. 1987, Computer Society of the IEEE, pp. 65–71. Also available at http://www.math.mcgill.ca/rags/WkAdj/LICS.pdf.\nsuggested using 2-categories for modeling the denotational semantics of lambda calculus in Scott domains to capture the adjunction between $\\beta$ reduction and $\\eta$ conversion;  Hilken \\cite{DBLP:journals/tcs/Hilken96}\n% B. Hilken, Towards a proof theory of rewriting: the simply-typed 2λ- calculus, Theor. Comp. Sci. 170 (1996), 407–444. Also available at http://math.ucr.edu/home/baez/qg-winter2007/hilken_2lambda_calculus.ps\nexpands Seely's work by exploring the proof theory using categorical logic; and Hirschowitz \\cite{DBLP:journals/corr/Hirschowitz13}\n% Tom Hirschowitz, Cartesian closed 2-categories and permutation equivalence in higher-order rewriting, Logical Methods in Computer Science, IfCoLog (Interna- tional Federation of Computational Logic), 9 (3) (2013), 10–28. Also available at https://hal.archives-ouvertes.fr/hal-00540205/file/macy.pdf\ngeneralizes algebraic signatures to cartesian closed 2-signatures.  A third approach is to model substitution explicitly: Stell \\cite{Stell}\n% http://www.comp.leeds.ac.uk/jgs/caen.ps\nconsidered sesquicategories for term rewriting; in his system, objects are finite sets of variables, morphisms are substitutions, and 2-morphisms are roughly rewrite rules.\n\n\\section{Gph-enriched categories}\nHere we review some standard definitions and results in enriched category theory; see \\cite{CIS-335497}, \\cite{Power99EnrichedLawvereTheories}, \\cite{DBLP:journals/acs/LackR11}, and \\cite{Trimble} for more details.\n\nA {\\bf directed multigraph with self loops}, hereafter {\\bf graph}, consists of a set $E$ of edges, a set $V$ of vertices, two functions $s,t\\maps E \\to V$ picking out the source and target of each edge, and a function $a\\maps V \\to E$ such that $s\\circ a$ and $t \\circ a$ are both the identity on $V$---that is, $a$ equips each vertex in $V$ with a chosen self loop.  There are no constraints on $E, V, s,$ or $t$, so a graph may have infinitely many vertices and infinitely many edges between any pair of vertices.  A {\\bf graph homomorphism} from $(E, V, s, t, a)$ to $(E', V', s', t', a')$ is a pair of functions $(\\epsilon\\maps E \\to E', \\upsilon\\maps V \\to V')$ such that $\\upsilon\\circ s = s' \\circ \\epsilon$ and $\\upsilon\\circ t = t' \\circ \\epsilon$.  {\\bf Gph} is the category of graphs and graph homomorphisms.  Gph has finite products: the terminal graph is the graph with one vertex and one loop, while the product of two graphs $(E, V, s, t, a) \\times (E', V', s', t', a')$ is $(E \\times E', V \\times V', s \\times s', t\\times t', a \\times a').$\n\nA {\\bf Gph-enriched category} consists of\n\\begin{itemize}\n  \\item a set of objects;\n  \\item for each pair of objects $x, y,$ a graph $\\hom(x,y);$\n  \\item for each triple of objects $x, y, z,$ a composition graph homomorphism $\\circ\\maps \\hom(y, z) \\times \\hom(x, y) \\to \\hom(x, z);$ and\n  \\item for each object $x,$ a vertex of $\\hom(x, x),$ the identity on $x,$\n\\end{itemize}\nsuch that composition is associative, and composition and the identity obey the unit laws.  A Gph-enriched category has finite products if the underlying category does.\n\nAny category is trivially Gph-enrichable by treating the elements of the hom sets as vertices and adjoining a self loop to each vertex.  The category Gph is nontrivially Gph-enriched: Gph is a topos, and therefore cartesian closed, and therefore enriched over itself.  Given two graph homomorphisms $F, F'\\maps (E, V, s, t, a) \\to (E', V', s', t', a'),$ a {\\bf graph transformation} assigns to each vertex $v$ in $V$ an edge $e'$ in $E'$ such that $s'(e') = F(v)$ and $t'(e') = F'(v).$  Given any two graphs $G$ and $G',$ there is an exponential graph $G'^G$ whose vertices are graph homomorphisms between them and whose edges are graph transformations.\n\nA {\\bf Gph-enriched functor} between two Gph-enriched categories $C, D$ is a functor between the underlying categories such that the graph structure on each hom set is preserved, {\\em i.e.} the functions between hom sets are graph homomorphisms between the hom graphs.\n\nLet $S$ be a finite set, $\\FinSet$ be a skeleton of the category of finite sets and functions between them, and $\\FinSet/S$ be the category of functions into $S$ and commuting triangles.  A {\\bf multisorted Gph-enriched Lawvere theory}, hereafter {\\bf Gph-theory} is a Gph-enriched category with finite products Th equipped with a finite set $S$ of {\\bf sorts} and a Gph-enriched functor $\\theta\\maps \\FinSet^{\\op}/S \\to \\Th$ that preserves products strictly.  Any Gph-theory has an underlying multisorted Lawvere theory given by forgetting the edges of each hom graph.\n\nA {\\bf model} of a Gph-theory Th is a Gph-enriched functor from Th to Gph that preserves products up to natural isomorphism.  A {\\bf homomorphism of models} is a braided Gph-enriched natural transformation between the functors.  Let FPGphCat be the 2-category of small Gph-enriched categories with finite products, product-preserving Gph-functors, and braided Gph-natural transformations.  The forgetful functor $U\\maps \\FPGphCat[\\Th, \\Gph] \\to \\Gph$ that picks out the underlying graph of a model has a left adjoint that picks out the free model on a graph.\n\nGph-enriched categories are part of a spectrum of 2-category-like structures.  A strict 2-category is a category enriched over Cat with its usual product.  Sesquicategories are categories enriched over Cat with the ``funny'' tensor product \\cite{Lack2010}; a sesquicategory can be thought of as a 2-category where the interchange law does not hold.  A Gph-enriched category can be thought of as a sesquicategory where 2-morphisms (now edges) cannot be composed.  Any strict 2-category has an underlying sesquicategory, and any sesquicategory has an underlying Gph-enriched category; these forgetful functors have left adjoints.\n\n\\section{Gph-theories as models of computation}\n\nLawvere theories and their generalizations are categories with infinitely many objects and morphisms, but most theories of interest are finitely generated.  A presentation of the underlying multisorted Lawvere theory of a finitely-generated Gph-theory is a signature for a term calculus, consisting of a set of sorts, a set of term constructors, and a set of equations, while the edges in the hom graphs of the theory encode the reduction relation.\n\nHere is a presentation of the SKI combinator calculus as a Gph-theory:\n\\begin{itemize}\n  \\item one sort $T$, for terms\n  \\item term constructors\n  \\[\\begin{array}{rl}\n    S&:1 \\to T\\\\\n    K&:1 \\to T\\\\\n    I&:1 \\to T\\\\\n    (-\\; -)&: T^2 \\to T\\\\\n  \\end{array}\\]\n  \\item structural congruence (no equations)\n  \\item rewrites\n  \\[\\begin{array}{rl}\n    \\sigma&:(((S\\; x)\\; y)\\; z) \\Rightarrow ((x\\; z)\\; (y\\; z))\\\\\n    \\kappa&:((K\\; y)\\; z) \\Rightarrow y\\\\\n    \\iota&:(I\\; z) \\Rightarrow z\\\\\n  \\end{array}\\]\n\\end{itemize}\nwhere in the rewrites we have used expressions like $((K\\; y)\\; z)$ as shorthand for\n\\[ T\\times T \\xrightarrow{\\mbox{\\tiny left}^{-1}} 1\\times T \\times T \\xrightarrow{K \\times T \\times T} T\\times T \\times T \\xrightarrow{(-\\;-)\\times T} T\\times T \\xrightarrow{(-\\;-)} T. \\]\n\nA model $M$ of this Gph-theory in Gph picks out a graph $M(T)$ of terms and rewrites.  It picks out three special vertices $S,K,$ and $I$ of $M(T)$; it equips $M(T)$ with a graph homomorphism from $M(T)^2$ to $M(T)$ that says for every pair of vertices $(u,v),$ there is a vertex $(u\\;v)$, and similarly for edges; and it equips $M(T)$ with graph transformations asserting the existence of an edge out of a reducible expression to the term it reduces to.\n\nThat this Gph-theory captures the operational semantics of the SKI calculus is almost definitional: there is an edge between distinct vertices in the free model on the empty graph if and only if the source vertex is reducible to the target vertex in a single step.\n\nIt is straightforward to verify that Gph-theories suffice to capture the operational semantics of any calculus where every context is a reduction context.  This restriction on reduction contexts is a consequence of the fact that models map term constructors to graph homomorphisms: given a model $M$, a graph homomorphism $F\\maps M(T) \\to M(T)$, and an edge $e\\maps t_1 \\to t_2,$ there is necessarily an edge $F(e)\\maps F(t_1) \\to F(t_2).$\n\n\\section{Gph-theory for SKI with the weak head normal form evaluation strategy}\n\\label{whnf}\nIn modern programming languages, many contexts are {\\em not} reduction contexts.  In Haskell, for instance, there are no reductions under a lambda abstraction: even if $t_1$ reduces to $t_2$ as a program, the term $\\backslash x \\to t_1$ does not reduce to $\\backslash x \\to t_2.$\n\nGph-theories can still capture the operational semantics of calculi with restrictions on reduction contexts by introducing term constructors that explicitly mark the reduction contexts.  For example, suppose that we want an evaluation strategy for the SKI calculus that only reduces the leftmost combinator when it has been applied to sufficiently many arguments, {\\em i.e.} we want the {\\em weak head normal form}; we can accomplish this by introducing a term constructor $R\\maps T \\to T$ that explicitly marks the reduction contexts.  We then add a structural congruence rule for propagating the context and modify the existing reduction rules to apply only to marked contexts.\n\n\\begin{itemize}\n  \\item one sort $T$, for terms\n  \\item term constructors\n  \\[\\begin{array}{rl}\n    S&:1 \\to T\\\\\n    K&:1 \\to T\\\\\n    I&:1 \\to T\\\\\n    (-\\; -)&: T^2 \\to T\\\\\n    R&:T \\to T\\\\\n  \\end{array}\\]\n  \\item structural congruence\n  \\[\\begin{array}{rl}\n    R(x\\; y) &= (Rx\\; y)\\\\\n  \\end{array}\\]\n  \\item rewrites\n  \\[\\begin{array}{rl}\n    \\sigma&:(((RS\\; x)\\; y)\\; z) \\Rightarrow ((Rx\\; z)\\; (y\\; z))\\\\\n    \\kappa&:((RK\\; y)\\; z) \\Rightarrow Ry\\\\\n    \\iota&:(RI\\; z) \\Rightarrow Rz\\\\\n  \\end{array}\\]\n\\end{itemize}\n\n\\begin{theorem}\n  Let $t$ be a term in which $R$ does not appear.  Then $Rt$ reduces to $Rt',$ where $t'$ is the weak head normal form of $t.$\n\\end{theorem}\n\n\\begin{proof}\nIf we form the term $Rt$ where $t$ contains no uses of $R$, no reductions will ever take place in the right-hand argument of an application: the structural congruence and rewrite rules enforce that the $R$ context can only move to the left term in an application, never the right.  The result follows by induction on the number of steps to reach $t'.$\n\\end{proof}\n\n\\section{Explicit reduction contexts as gas}\nThe Ethereum \\cite{wood2014ethereum} and RChain \\cite{RChain} projects are building virtual machines on the blockchain.  Both use the concept of a linear resource called ``gas'' (as in gasoline) that is consumed as the virtual machine executes.  Gph-theories can capture the operational semantics of a calculus where reduction contexts are consumable, and thus play a role similar to that of gas \\cite{DBLP:journals/corr/StayM15}.\n\n\\begin{itemize}\n  \\item one sort $T$, for terms\n  \\item term constructors\n  \\[\\begin{array}{rl}\n    S&:1 \\to T\\\\\n    K&:1 \\to T\\\\\n    I&:1 \\to T\\\\\n    (-\\; -)&: T^2 \\to T\\\\\n    R&:T \\to T\\\\\n  \\end{array}\\]\n  \\item structural congruence\n  \\[\\begin{array}{rl}\n    R(x\\; y) &= (Rx\\; y)\\\\\n  \\end{array}\\]\n  \\item rewrites\n  \\[\\begin{array}{rl}\n    \\sigma&:(((RS\\; x)\\; y)\\; z) \\Rightarrow ((x\\; z)\\; (y\\; z))\\\\\n    \\kappa&:((RK\\; y)\\; z) \\Rightarrow y\\\\\n    \\iota&:(RI\\; z) \\Rightarrow z\\\\\n  \\end{array}\\]\n\\end{itemize}\n\n\\begin{theorem}\n  Let $t$ be a term in which $R$ does not appear; let $t'$ be the weak head normal form of $t$; let $m$ be the number of steps by which $Rt$ reduces to $Rt'$ in the calculus of section \\ref{whnf}; and let $n\\ge m$.  Then in this calculus, $R^n t$ reduces to $R^{n-m}t'$ in $m$ steps.\n\\end{theorem}\n\n\\begin{proof}\nAs before, if we form the term $Rt$ where $t$ contains no uses of $R$, no reductions will ever take place in the right-hand argument of an application.  Each application of the reduction rules reduces the number of $R$s by one, and structural equivalence preserves the number of $R$s.  The result follows by induction on the number of steps to reach $t'.$\n\\end{proof}\n\n\\section{Gph-theory for a pi calculus variant}\n\\label{rhocomb}\nGph-theories can capture the operational semantics of concurrent calculi as well as serial calculi like SKI above.\n\n  Meredith and Radestock \\cite{DBLP:journals/entcs/MeredithR05} describe a reflective higher-order variant of pi calculus we call the RHO calculus.  Rather than the usual replication and $\\new$ operators, they have quoting and unquoting operators.  Quoting turns a process into a name and unquoting does the opposite; freshness of names is obtained using a type discipline.  They prove that there is a faithful embedding of the monadic asynchronous pi calculus into the RHO calculus.\n\n\\subsection{The RHO calculus}\n\\subsubsection{Syntax}\n\\[\\begin{array}{rlr}\n  P, Q &::= 0 & \\mbox{the stopped process}\\\\ \n  &| \\quad \\for(y \\from x)P & \\mbox{input guarded process} \\\\ \n  &| \\quad x!P & \\mbox{output process}\\\\ \n  &| \\quad P \\;|\\; Q & \\mbox{parallel composition}\\\\\n  &| \\quad *x & \\mbox{deference}\\\\ \n  &\\\\\n  x, y &::= \\&P & \\mbox{quotation}\\\\ \n\\end{array}\\]\n\nNote that in the original rho-calculus papers the notation was\nsomewhat different. The quotation and dereference constructions were\noriginally written, $\\ulcorner P \\urcorner$ and $\\urcorner x \\ulcorner$,\nrespectively. Here we have adopted a more programmer\nfriendly style employing the $\\&$ and $*$ of the $\\mathsf{C}$ programming\nlanguage for reference (quotation) and dereference, respectively. Input\nguards which were written with a whimper $?$ in more traditional process calculi style  are now written in for-comprehension style as adopted\nin languages like $\\mathsf{Scala}$; e.g. $x?(y)P$ is written\nhere $\\mathsf{for}( y \\from x )P$.\n\n\\subsubsection{Free and bound names}\n\\[\\begin{array}{rl}\nFN(0) &= \\emptyset \\\\\nFN(\\for(y \\from x)P) &= \\{x\\}\\cup (FN(P)\\backslash \\{y\\}) \\\\\nFN(x!P) &= \\{x\\}\\cup FN(P) \\\\\n\\end{array}\\quad\\quad\n\\begin{array}{rl}\nFN(P|Q) &= FN(P)\\cup FN(Q) \\\\\nFN(*x) &= \\{x\\}\n\\end{array}\\]\n\\subsubsection{Structural congruence}\nStructural (process) congruence is the smallest congruence $\\equiv$ containing $\\alpha$-equivalence and making $(|, 0)$ into a commutative monoid.\n\\subsubsection{Name equivalence}\nName equivalence is the smallest equivalence relation $\\equiv_N$ on names such that \n\\begin{center}\n  \\AXC{} \\UIC{$\\&*x \\equiv_N x$} \\DP and \\AXC{$P \\equiv Q$} \\UIC{$\\&P \\equiv_N \\&Q$} \\DP.\n\\end{center}\n\\subsubsection{Substitution}\nSyntactic substitution:\n\\[\\begin{array}{rl}\n  (0)\\{\\&Q/\\&P\\} &= 0\\\\\n  (\\for (y \\from x) R)\\{\\&Q/\\&P\\} &= \\for (z \\from (x\\{\\&Q/\\&P\\})) (R\\{z/y\\}\\{\\&Q/\\&P\\})\\\\\n  (x!R)\\{\\&Q/\\&P\\} &= (x\\{\\&Q/\\&P\\})!(R\\{\\&Q/\\&P\\})\\\\\n  (R|S)\\{\\&Q/\\&P\\} &= (R\\{\\&Q/\\&P\\}) \\;|\\; (S\\{\\&Q/\\&P\\})\\\\\n  (*x)\\{\\&Q/\\&P\\} &= \\left\\{\\begin{array}{rl}\n    *\\&Q & \\mbox{when } x \\equiv_N \\&Q\\\\\n    *x & \\mbox{otherwise,}\n  \\end{array}\\right.\n\\end{array}\\]\nwhere\n\\[ x\\{\\&Q/\\&P\\} = \\left\\{\\begin{array}{rl}\n                  \\&Q & \\mbox{if } x\\equiv_N \\&P \\\\\n                  x & \\mbox{ otherwise}\n                \\end{array}\\right.\\]\nand, in the rule for input, $z$ is chosen to be distinct from $\\&P, \\&Q,$ the free names in $Q,$ and all the names in $R.$\n\nSemantic substitution, for use in $\\alpha$-equivalence:\n\\[ (*x)\\{\\&Q/\\&P\\} = \\left\\{\\begin{array}{rl}\n  Q & \\mbox{when } x \\equiv_N \\&Q\\\\\n  *x & \\mbox{otherwise}\n\\end{array}\\right. \\]\n\n\\subsubsection{Reduction rules}\nWe use $\\to$ to denote single-step reduction.\n\\begin{center}\n\\AXC{$x_0 \\equiv_N x_1$} \n\\UIC{$\\for(y \\from x_1)P \\;|\\; x_0!Q \\quad \\to\\quad P\\{\\&Q / y\\}$} \\DP \\quad \\quad\n\\end{center}\n\n\\begin{center}\n\\AXC{$P\\to P'$}\n\\UIC{$P\\;|\\; Q \\quad \\to \\quad P' \\;|\\; Q$} \\DP\n\\end{center}\n\n\\begin{center}\n\\AXC{$P\\equiv P'$} \\AXC{$P' \\to Q'$} \\AXC{$Q' \\equiv Q$}\n\\TIC{$P\\to Q$} \\DP\n\\end{center}\n\\subsection{RHO combinators}\nWe can define an embedding $\\interp{-}$ of closed RHO calculus terms into a set of RHO combinators.  We follow Milner \\cite{milner91polyadicpi} in thinking of an input-prefixed process $\\for(x \\from y)P$ as consisting of two parts: the first names the channel $y$ on which the process is listening, while the second describes the continuation $\\lambda x.P$ in terms of an abstracted name.  The right hand side of the communication rule, in effect, applies the continuation to the name to be substituted.  Since the only bound names in the RHO calculus come from input prefixing, we can completely eliminate bound names by using abstraction elimination on the continuation.  Like the weak head normal form SKI calculus above, this combinator calculus uses a linear resource $C$ to reify reduction contexts.\n\nA Gph-theory for the operational semantics of these combinators has:\n\\begin{itemize}\n  \\item one sort $T$, for terms\n  \\item term constructors\n    \\[\\begin{array}{rl}\n      C &: 1 \\to T \\\\ \n      0 &: 1 \\to T \\\\ \n      | &: 1 \\to T \\\\ \n      \\for &: 1 \\to T \\\\ \n      ! &: 1 \\to T \\\\ \n      \\& &: 1 \\to T \\\\ \n    \\end{array}\\quad\\quad\n    \\begin{array}{rl}\n      * &: 1 \\to T \\\\ \n      S &: 1 \\to T \\\\ \n      K &: 1 \\to T \\\\ \n      I &: 1 \\to T \\\\ \n      () &: T \\times T \\to T \\\\ \n    \\end{array}\\]\n  \\item structural congruence rules\n    \\[\\begin{array}{rll}\n      ((|\\; 0)\\; P) &= P & \\mbox{unit law}\\\\\n      ((|\\; ((|\\; P)\\; Q))\\; R) &= ((|\\; P)\\; ((|\\; Q)\\; R) & \\mbox{associativity}\\\\\n      ((|\\; P)\\; Q) &= ((|\\; Q)\\; P) &\\mbox{commutativity}\\\\\n    \\end{array}\\]\n  \\item reduction rules\n    \\[\\begin{array}{ll}\n      \\sigma\\maps (((S\\; P)\\; Q)\\; R) \\Rightarrow ((P\\; R)\\; (Q\\; R)) & \\mbox{action of }S \\\\ \n      \\kappa\\maps ((K\\; P)\\; Q) \\Rightarrow P & \\mbox{action of }K\\\\ \n      \\iota\\maps (I\\; P) \\Rightarrow P & \\mbox{action of }I\\\\ \n      \\xi\\maps ((|\\; C)\\; ((|\\; ((\\for\\; (\\&\\; P))\\; Q))\\; ((!\\; (\\&\\; P))\\; R))) \\Rightarrow ((|\\; C)\\; (Q\\; (\\&\\; R))) & \\mbox{communication}\\\\\n      \\epsilon\\maps ((|\\; C)\\;(*\\; (\\&\\; P))) \\Rightarrow ((|\\; C)\\; P) & \\mbox{evaluation} \\\\\n    \\end{array}\\]\n\\end{itemize}\n\n\\subsection{Embeddings}\nWe define an interpretation function $\\interp{-}$ from RHO calculus terms into RHO combinators by\n\n\\[\\begin{array}{rl}\n  \\interp{0} &= 0 \\\\\n  \\interp{\\for(x \\from \\&P)Q} &= ((for\\; (\\&\\; \\interp{P}))\\; \\interp{Q}_x)\\\\\n  \\interp{\\&P!Q} &= ((!\\; (\\&\\; \\interp{P}))\\; \\interp{Q}) \\\\\n  \\interp{P|Q} &= ((|\\; \\interp{P})\\; \\interp{Q})\\\\\n  \\interp{*\\&P} &= (*\\; (\\&\\; \\interp{P}))\n\\end{array}\\]\nwhere $\\interp{-}_x$ eliminates the free name $x:$\n\\[\\begin{array}{rl}\n  \\interp{P}_x &= (K\\; \\interp{P}) \\mbox{ where $x$ is not free in } P \\\\\n  \\interp{\\for(y \\from \\&P)Q}_x &= ((S\\; ((S\\; (K for))\\; ((S\\; (K\\; \\&))\\; \\interp{P}_x)))\\; \\interp{\\interp{Q}_y}_x) \\\\\n  \\interp{\\&P!Q}_x &= ((S\\; ((S\\; (K\\; !))\\; ((S\\; (K\\; \\&))\\; \\interp{P}_x)))\\; \\interp{Q}_x) \\\\\n  \\interp{P|Q}_x &= ((S\\; ((S\\; (K\\; |))\\; \\interp{P}_x))\\; \\interp{Q}_x) \\\\\n  \\interp{*\\&P} &= \\left\\{\\begin{array}{ll}\n    ((S\\; (K\\; *))\\; I) & \\mbox{when } \\&P \\equiv_N x\\\\\n    ((S\\; (K\\; *))\\; ((S (K\\; \\&))\\; \\interp{P}_x) & \\mbox{otherwise.}\n  \\end{array}\\right.\n\\end{array}\\]\n\nConsider the following sorting on RHO combinators:\n\\[\\begin{array}{rl}\n  C &: W\\\\\n  0 &: W\\\\\n  | &: W \\Rightarrow W \\Rightarrow W\\\\\n  \\for &: N \\Rightarrow (N \\Rightarrow W) \\Rightarrow W\\\\\n  ! &: N \\Rightarrow W \\Rightarrow W\\\\\n\\end{array}\\quad\\quad\n\\begin{array}{rl}\n  \\& &: W \\Rightarrow N\\\\\n  * &: N \\Rightarrow W\\\\\n  S &: \\forall X,Y,Z.(Z \\Rightarrow Y \\Rightarrow X) \\Rightarrow (Z \\Rightarrow Y) \\Rightarrow Z \\Rightarrow X\\\\\n  K &: \\forall X,Y.X \\Rightarrow Y \\Rightarrow X\\\\\n  I &: \\forall X.X \\Rightarrow X\\\\\n\\end{array}\\]\n\nThe left- and right-hand sides of each of the structural congruence and rewrite rules have the sort $W,$ the interpretation of any RHO calculus term has the sort $W,$ and the result of eliminating an abstraction has the sort $N \\Rightarrow W.$\n\nWe define an interpretation function $\\interpp{-}$ from $W$-sorted RHO combinators not containing $C$ into the RHO calculus by\n\\[\\begin{array}{rl}\n  \\interpp{0} &= 0\\\\\n  \\interpp{P\\;|\\;Q} &= \\interpp{P} \\;|\\; \\interpp{Q}\\\\\n  \\interpp{((\\for\\; (\\&\\; P))\\; Q)} &= for (\\&\\interpp{R} \\leftarrow \\&\\interpp{P})\\interpp{(Q\\; (\\&\\; R))}\\\\\n  \\interpp{((!\\; (\\&\\; P))\\; Q)} &= \\&\\interpp{P}!\\interpp{Q}\\\\\n  \\interpp{(*(\\&\\; P))} &= *\\&\\interpp{P}\\\\\n  \\interpp{(((S\\; P)\\; Q)\\; R)} &= \\interpp{((P\\; R)\\; (Q\\; R))}\\\\\n  \\interpp{((K\\; P)\\; Q)} &= \\interpp{P}\\\\\n  \\interpp{(I\\; P)} &= \\interpp{P}\n\\end{array}\\]\nwhere $R$ is any $W$-sorted RHO combinator.\n\nSome simple calculation shows that\n\\begin{theorem}\n\\label{roundtrip}\n  $\\interpp{\\interp{P}}$ is $\\alpha$-equivalent to $P$, $Q$ is reducible to $\\interp{\\interpp{Q}}$ without using the rewrite $\\xi,$ and $\\interp{\\interpp{-}}$ is idempotent.\n\\end{theorem}\nSee the appendix for more details.\n\n\\subsection{Barbed bisimilarity}\nAn {\\bf observation relation} $\\downarrow_\\Ncal$ over a set of names $\\Ncal$ is the smallest relation satisfying\n\\begin{center}\n  \\AXC{$y \\in \\Ncal$} \\AXC{$x \\equiv_N y$} \\BIC{$x!P \\downarrow_\\Ncal x$} \\DP $\\quad$ and $\\quad$ \\AXC{$P  \\downarrow_\\Ncal x \\mbox{ or } Q \\downarrow_\\Ncal x$} \\UIC{$P\\;|\\;Q  \\downarrow_\\Ncal x$} \\DP\n\\end{center}\nfor the RHO calculus or\n\\begin{center}\n  \\AXC{$y \\in \\Ncal$} \\AXC{$x \\equiv_N y$} \\BIC{$((!\\; x)\\; P) \\downarrow_\\Ncal x$} \\DP $\\quad$ and $\\quad$ \\AXC{$P  \\downarrow_\\Ncal x \\mbox{ or } Q \\downarrow_\\Ncal x$} \\UIC{$((|\\; P)\\; Q)  \\downarrow_\\Ncal x$} \\DP.\n\\end{center}\nfor the RHO combinators.\n\nWe denote eventual reduction by $\\to^*$ and write $P \\downarrow^*_\\Ncal x$ if there exists a process $Q$ such that $P \\to^* Q$ and $Q \\downarrow_\\Ncal x.$\n\nAn {\\bf $\\Ncal$-barbed bisimulation} over a set of names $\\Ncal$ is a symmetric binary relation $S_\\Ncal$ between agents such that $P \\mathop{S_\\Ncal} Q$ implies\n\\begin{enumerate}\n  \\item if $P \\to P'$ then $Q \\to^* Q'$ and $P' \\mathop{S_\\Ncal} Q',$ and \n  \\item if $P \\downarrow_\\Ncal x,$ then $Q \\downarrow^*_\\Ncal x.$\n\\end{enumerate}\n$P$ is $\\Ncal$-barbed bisimilar to $Q,$ written $P \\approx Q,$ if $P \\mathop{S_\\Ncal} Q$ for some $\\Ncal$-barbed bisimulation $S_\\Ncal.$\n\n\\subsection{Faithfulness}\n\n\\begin{theorem}\n  $P \\approx_{\\mbox{\\tiny calc}} Q \\iff  ((|\\; C)\\; \\interp{P}) \\approx_{\\mbox{\\tiny comb}} ((|\\; C)\\; \\interp{Q})$.\n\\end{theorem}\n\n\\begin{proof}[Proof sketch]\nThe only occurrence of $C$ on the right is at the topmost context and the rewrite rules preserve the location of $C$, so the only reduction context is the topmost one.  The rest follows from the two interpretation functions and theorem \\ref{roundtrip}.  In particular, while the only reduction rule in the RHO calculus is synchronizing on a name, there are extra reduction rules for the RHO combinators; however, these extra reduction rules never send or receive on a name and never prevent sending or receiving on a name.  Therefore, each synchronization in the evaluation of a RHO calculus term corresponds to a synchronization in the corresponding RHO combinator term and some number of reductions of $S,K,I,$ or evaluating a quoted process.\n\\end{proof}\n\nIn fact, we believe a much stronger property than bisimilarity should hold: since $S,K,$ and $I$ are only used for eliminating dummy variables and the $\\epsilon$ reduction plays the role of semantic substitution, $\\interp{\\interpp{-}}$ should pick out a normal form for a RHO combinator.  We should get a set of normal-form equivalence classes of $W$-sorted RHO combinators that is isomorphic to the set of $\\alpha$-equivalence classes of RHO calculus terms.  Then we should get\n\\[ P \\xrightarrow{\\mbox{\\tiny comm}} P' \\quad \\iff \\quad \\interp{P} \\xrightarrow{\\xi} \\interp{P'}\\]\nand\n\\[ Q \\xrightarrow{\\xi} Q' \\quad \\iff \\quad \\interpp{Q} \\xrightarrow{\\mbox{\\tiny comm}} \\interpp{Q'}, \\]\nwhere we now regard the left and right sides as being equivalence classes.\n\n\\section{Conclusion and future work}\nThis paper is part of a pair of papers demonstrating that reflection\nprovides a powerful technique for treating nominal phenomena as\nsyntactic sugar, thus paving the way for simpler semantic treatments\nof richly featured calculi, such as the {\\pic} and other calculi of\nconcurrency. We illustrated the point by providing faithful semantics\nof both the $\\lambda$-calculus and the {\\pic} in terms of graph-enriched\nLawvere theories. This work may be considered preparatory for a more\nelaborate study of logics for concurrency in which the nominal\nphenomena have logical status, but may be treated in a technically\nsimpler fashion.\n\n\\section{Appendix: abstraction elimination calculations}\n\\[\\begin{array}{rl}\n  & ((K\\; \\interp{P})\\; x) \\\\\n  = & \\interp{P}\\\\\n  \\\\\n  \n  & (((S\\; ((S\\; (K\\; for))\\; ((S\\; (K\\; \\&))\\; \\; \\interp{P}_x)))\\; \\interp{\\interp{Q}_y}_x)\\; x)\\\\\n  =&  ((((S\\; (K\\; for))\\; ((S\\; (K\\; \\&))\\; \\; \\interp{P}_x))\\; x)\\; (\\interp{\\interp{Q}_y}_x\\; x))\\\\\n  =&  ((((K\\; for)\\; x)\\; (((S\\; (K\\; \\&))\\; \\; \\interp{P}_x)\\; x))\\; \\interp{Q}_y)\\\\\n  =&  ((for\\; (((K\\; \\&)\\; x)\\; (\\interp{P}_x\\; x)))\\; \\interp{Q}_y)\\\\\n  =&  ((for\\; (\\&\\; \\interp{P}))\\; \\interp{Q}_y)\\\\\n  \\\\\n  & (((S\\; ((S\\; (K\\; !))\\; ((S\\; (K\\; \\&))\\; \\interp{P}_x)))\\; \\interp{Q}_x)\\; x)\\\\\n  =&  (((((S\\; (K\\; !))\\; ((S\\; (K\\; \\&))\\; \\interp{P}_x)))\\; x)\\; (\\interp{Q}_x\\; x))\\\\\n  =&  ((((K\\; !)\\; x)\\; (((S\\; (K\\; \\&))\\; \\interp{P}_x)\\; x))\\; \\interp{Q})\\\\\n  =&  ((!\\; (((K\\; \\&)\\; x)\\; (\\interp{P}_x\\; x)))\\; \\interp{Q})\\\\\n  =&  ((!\\; (\\&\\; \\interp{P}))\\; \\interp{Q})\\\\\n  \\\\\n  & (((S\\; ((S\\; (K\\; |))\\; \\interp{P}_x))\\; \\interp{Q}_x)\\; x)\\\\\n  =& ((((S\\; (K\\; |))\\; \\interp{P}_x)\\; x)\\; (\\interp{Q}_x\\; x))\\\\\n  =& ((((K\\; |)\\; x)\\; (\\interp{P}_x\\; x))\\; \\interp{Q})\\\\\n  =& (|\\; \\interp{P})\\; \\interp{Q})\\\\\n  \\\\\n  & (((S\\; (K\\; *))\\; I)\\; x)\\\\\n  =&  (((K\\; *)\\; x)\\; (I\\; x))\\\\\n  =&  (*\\; x)\\\\\n  \\\\\n  & (((S\\; (K\\; *))\\; ((S\\; (K\\; \\&))\\; \\interp{P}_x))\\; x)\\\\\n  =&  (((K\\; *)\\; x)\\; (((S\\; (K\\; \\&))\\; \\interp{P}_x)\\; x))\\\\\n  =&  (*\\; (((K\\; \\&)\\; x)\\; (\\interp{P}_x\\; x)))\\\\\n  =&  (*\\; (\\&\\; \\interp{P}))\\\\\n\\end{array}\\]\n\n\\bibliographystyle{plainurl}\n\\bibliography{calco}\n\\end{document}\n", "meta": {"hexsha": "080b65f53fa9fbc125fc05b05ed4dbadb2619a88", "size": 31570, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Representing operational semantics with enriched Lawvere theories calco2017/calco_orig.tex", "max_stars_repo_name": "leithaus/pi4u", "max_stars_repo_head_hexsha": "c87163938857589153eb5225d0e4ac17597fd189", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2015-10-12T20:35:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T00:37:17.000Z", "max_issues_repo_path": "Representing operational semantics with enriched Lawvere theories calco2017/calco_orig.tex", "max_issues_repo_name": "leithaus/pi4u", "max_issues_repo_head_hexsha": "c87163938857589153eb5225d0e4ac17597fd189", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2018-07-06T19:01:06.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-19T22:39:58.000Z", "max_forks_repo_path": "Representing operational semantics with enriched Lawvere theories calco2017/calco_orig.tex", "max_forks_repo_name": "leithaus/pi4u", "max_forks_repo_head_hexsha": "c87163938857589153eb5225d0e4ac17597fd189", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2016-10-03T06:03:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-16T00:37:25.000Z", "avg_line_length": 60.7115384615, "max_line_length": 1057, "alphanum_fraction": 0.6789990497, "num_tokens": 10004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442250928250374, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3271451454029258}}
{"text": "\n\\chapter{Self-organization}\n\\label{sec:selfOrganization}\n\nThis chapter describes the algorithms emplyed by \\emph{HyCube} for joining/leaving the network, as well as maintenance and recovery processes, maintaining good routing properties under dynamically changing conditions. The algorithms are based on nodes exchanging information about references stored in routing tables and neighborhood sets. When a node receives a notification about existence of some other peer or receives references maintained by some other node (requested for example in the recovery or joining process, or generated by the notifying node itself), it should analyze the node and check if the reference should be stored in the routing tables or the neighborhood set. Every node is analyzed as a candidate to the neighborhood set and appropriate routing table slots. \nFor the primary routing table, this is the slot at the level calculated based on the common prefix length with the node ($l - 1 - commonPrefixLength$, $l$ - the number of hierarchy levels) at the position equal to the first different digit (group of $d$ bits, $d$ - the number of dimensions).\nFor the secondary routing table, the slot corresponds to the lowest-level hypercube containing the analyzed node, adjacent to the hypercube of the analyzing node. A simple check may be performed to verify this condition: nodes $X$ and $Y$ are in adjacent hypercubes at levels $l - 1 - j$ to $l - 1 - i$ if and only if $i$ first digits ($d$-bit groups) of $X$ and $Y$ are equal, and $i$-th to $j$-th digits (numbered starting from 0) differ on one (the same for all these digits) bit - this bit corresponds to the dimension in which the two hypercubes are adjacent, and only the slot at the lowest level should be considered (to prevent placing the same nodes in overlapping routing table slots at different levels). Furthermore, depending on settings, additional rules described in Section \\ref{sec:rtOverlapping} may apply to prevent storing nodes in the primary routing table slots overlapping with the lower-level secondary routing table slots.\nFor selecting nodes within individual routing table slots and within the neighborhood set, the algorithms described in Sections \\ref{sec:HyCubeNodeSelection} and \\ref{sec:uniformNSDistribution} apply.\n\n\n\n\n\\section{Maintenance and recovery}\n\nMaintenance is a process of ensuring good system properties that takes place continuously (ensuring the relevance of routing tables, updating information about neighbors). The maintenance mechanism used in \\emph{HyCube} is directly connected with the routing table neighbor selection (described in detail in Section \\ref{sec:HyCubeNodeSelectionLNS}). Every node periodically sends keepalive messages to all the nodes in its routing tables, and, depending on whether the keepalive response is received or not, the node's liveness value is updated. Based on the liveness value, the routing table reference may be skipped in the next hop selection (to avoid failed paths), may be replaced, or removed from the routing tables.\n\nRecovery is a process of repairing the network topology and propagating necessary information over the network on account of a topology change (new nodes joining/leaving the system), topology breakdown (node failures) or attacks. The recovery technique, employed by \\emph{HyCube}, is a periodic procedure, run every specified time interval (parameter value). The value of the interval should be adjusted depending on the DHT nature. The higher is the level of churn, the recovery should be run more often, while if the system has a very stable nature, this interval might be larger. The recovery algorithm in \\emph{HyCube} proceeds in two phases:\n\n\\begin{enumerate}\n\n\\item In the first phase, the node sends a recovery request to all nodes in its routing tables, which it turn return their routing tables to the requesting node. Upon receiving the responses, the requesting node processes the references returned and updates its routing tables and neighborhood set.\n\n\\item In the second recovery step, the node performing the recovery sends a notification (NOTIFY message) about its existence to all nodes in its neighborhood set and routing tables (immediately after sending the recovery requests). The notification is also sent to the routing tables nodes to spread the information about the node to more distant parts of the hypercube. However, to limit the overhead, the maximum number of the routing table nodes to which notification is sent should be limited - the message would be sent to certain maximum number of nodes (random selection from all routing table nodes).\n\n\\end{enumerate}\n\nBecause such an approach may lead to exchanging a large number of messages and also increase processing overhead at the node level, neighborhood set recovery - a variant of the recovery was introduced. Nodes performing the neighborhood set recovery send the recovery requests only to nodes in their neighborhood sets, which dramatically decreases the network traffic and processing overhead. In addition to the recovery interval, \\emph{HyCube} allows defining the recovery plan - determining a sequence of recovery variants (for individual recovery runs, successive recovery types from the recovery plan are performed - following a cyclical pattern). Full recovery has better properties in terms of keeping the routing tables up-to-date. However, especially for larger networks, the overhead is significantly larger. Although there might be situations in which the neighborhood set is completely corrupt, and sending recovery requests to the routing table nodes would return much more nodes, usually it is sufficient to repeat the neighborhood set recovery instead. Therefore, the neighborhood set recovery is the default recovery method used in \\emph{HyCube}.\n\nTo spread the information about the node in an even greater degree, it is possible to send a notification also to every node to which a reference is returned in recovery responses. However, this approach proved to generate enormous network traffic, as well as very high nodes' processing overhead. Performed simulations proved that notifying all neighborhood set nodes and 16 random routing table nodes during every recovery does not significantly increase the overhead, and, if the recovery procedure is run frequently enough, it is sufficient to properly propagate the information about the node's existence. Furthermore, depending on configuration, nodes may process the recovery request messages as notifications (analyze the sender as a routing table candidate), in which case, a notification message does not have to be later sent to the nodes to which the recovery requests were sent.\n\n\n\n\n\\section{Joining the system (connecting to the DHT)}\n\nWhen a new node joins the existing DHT, it should have knowledge about any node already connected to the system. \\emph{HyCube} implements two different approaches for joining the system. One of them is based on routing a JOIN message through the system to the node closest to the new node's ID, and the routing tables are formed by the references returned by intermediate nodes along the path (including also themselves), as well as the closest node. The second method is based on searching for the nodes closest to the new node's ID, which form initial routing tables for a new node. The routing approach requires much less overhead - a smaller number of messages are exchanged. However the search method is not vulnerable to any single node possibly causing the join message to be dropped. This section presents both join techniques.\n\n\n\n\\subsection{``Route-join'' procedure}\n\nThe route-join procedure is based on the joining mechanism presented in \\cite{pastry}. To initiate the route-join procedure, the joining node should send a ``join'' request (JOIN message) to any node already participating in the system. The message is routed to the closest possible node to the joining node's ID (however, omitting the exact match, as the message would be possibly routed back to the joining node). All intermediate nodes send back (directly to the joining node) JOIN\\_REPLY messages that contain all references stored by them in their routing tables. Every node returned is analyzed by the joining node and its routing tables are updated based on the criteria described in Sections \\ref{sec:HyCubeNodeSelection} and \\ref{sec:uniformNSDistribution}. As the message gets closer to the new node ID, references returned are more likely to be good candidates for the neighborhood set. Furthermore, as the common prefix length with the joining node ID increases, more and more routing table slots correspond to the same hypercubes as the one of the joining node, so more and more references returned by the intermediate nodes might be also used for building the routing tables. For that reason, it is a good idea to disable the prefix mismatch heuristic for JOIN messages (the behavior is configured by a system parameter).\n\n\n\n\n\\subsection{``Search-join'' procedure}\n\nIn the search-join procedure, the joining node initially retrieves all references from routing tables from a known node connected to the system. The references returned are used to perform a search (Section \\ref{sec:search}) for the closest nodes to the joining node ID with certain values of parameters $\\alpha$, $\\beta$, $\\gamma$: $\\alpha_{join}$, $\\beta_{join}$ and $\\gamma_{join}$ (system parameters), and the $ITN$ (ignore target node) parameter set to \\emph{true}. The value of $k$ is not important, because all nodes returned by intermediate nodes are processed (updating the routing tables). Initially, the set $\\Gamma$ is filled with $\\gamma$ closest (Euclidean) nodes retrieved in the initial phase - from the bootstrap node. Afterwards, the search procedure proceeds as described in Section \\ref{sec:search}.\n\nBecause the node performing the search is the node whose identifier is being looked for, to allow the use of the Steinhaus transform, the initial values of Steinhaus points should not be set to the joining node ID (Euclidean metric would be then used for local next hop selections), but should be given the values of IDs of the initial nodes themselves (only for the initial nodes returned by the bootstrap nodes - for any nodes added to $\\Gamma$ later, the Steinhaus point is updated based on the information contained in the response message that contained the node reference).\n\n\n\n\n\n\n\n\n\n\n\\section{Leaving the system (disconnecting from the DHT)}\n\nThe maintenance and recovery mechanisms should be able to maintain connection graph consistency and keep routing tables of nodes up-to-date, ensuring good routing and searching properties. However, these algorithms have certain ``inertia'' and react with a certain delay. A simple solution to overcome this problem is sending the leave information (LEAVE message) to all neighbors in the leaving node's neighborhood set. Such LEAVE messages should contain the list of neighborhood set nodes of the leaving node, and the nodes receiving it should remove references to the LEAVE sender from the routing tables and the neighborhood set, and process all the nodes included in the message to immediately fill the lost routing table or/and neighborhood references.\n\n\n\n\n\n\n\n\n\n% ex: set tabstop=4 shiftwidth=4 softtabstop=4 noexpandtab fileformat=unix filetype=tex encoding=utf-8 fileencodings= fenc= spelllang=pl,en spell:\n\n", "meta": {"hexsha": "23c750bf92ac616b345e00985dd7e963c6001c57", "size": 11401, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/documentation/protocol_doc_tex/tex/self-organization.tex", "max_stars_repo_name": "arturolszak/hycube", "max_stars_repo_head_hexsha": "e7dc0bc7ff5d7c1d406bfee952398515f3f6b6c8", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-07-18T14:05:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-18T02:15:36.000Z", "max_issues_repo_path": "src/documentation/protocol_doc_tex/tex/self-organization.tex", "max_issues_repo_name": "suhasagg/hycube", "max_issues_repo_head_hexsha": "e7dc0bc7ff5d7c1d406bfee952398515f3f6b6c8", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2016-10-02T14:25:30.000Z", "max_issues_repo_issues_event_max_datetime": "2016-11-27T18:10:58.000Z", "max_forks_repo_path": "src/documentation/protocol_doc_tex/tex/self-organization.tex", "max_forks_repo_name": "suhasagg/hycube", "max_forks_repo_head_hexsha": "e7dc0bc7ff5d7c1d406bfee952398515f3f6b6c8", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-10T16:08:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T16:08:30.000Z", "avg_line_length": 150.0131578947, "max_line_length": 1335, "alphanum_fraction": 0.8055433734, "num_tokens": 2255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.3271036931285786}}
{"text": "\\section{Introduction}\n\\label{sec:background}\n\n%In this chapter we provide background for the 802.11 wireless communications standard, including its 802.11af \\ac{TVWS} extensions, with a focus on \\ac{MU-MIMO} transmission techniques in 802.11ac/ax and key performance factors for general \\ac{MU-MIMO}.\nIn this chapter we provide background for wireless communications systems with a focus on \\ac{MU-MIMO} transmission techniques such as those used in \\ac{IEEE} 802.11ac/ax and key performance factors for \\ac{MU-MIMO}.\n\nWe will also review software-defined radios and their implementation in order to provide context for the innovative \\ac{SDR} system design in this thesis.\n\n\n\t%#######################################################\n\t%\\section{Wi-Fi: the IEEE 802.11 Standard}\n\t%\\label{sec:back_80211}\n%\n%\\iftoggle{isready} {\n%\n\t%As the second widespread use of spectrum sharing,\\footnote{The IEEE 802.11a standard includes \\ac{DFS} sensing and protection of radar signals between [5.260, 5.700]~GHz.} \n%\n\t%\\rgnote{Basic background about 802.11, random access, frame structure, terminology. 802.11ac extension for MU-MIMO. This is where \\ac{STA} and \\ac{AP} get defined}\n%\n\t%%#######################################################\n\t%\\subsection{IEEE 802.11af Standard Extension for TVWS}\n\t%\\label{sec:back_80211af}\n%\n\t%\\rgnote{Motivation and constraints of 802.11af, pulling from my IEEE article content. Database vs. sensing approaches--we focus on database-driven approaches.}\n%\n\t%Wifi over TVWS: \\cite{bahl2009white}\n%\n%}{ \\rgnote{The WiFi background section is pending.}}\n\n%#######################################################\n\\section{Multi-user Beamforming}\n\\label{sec_mubf_back}\n\tMulti-user beamforming is a multi-antenna transmission technique that allows a transmitter to spatially reuse a wireless channel by transmitting multiple concurrent data streams on the same radio frequency using linear pre-coding.\n\tThis is achieved in two steps: first, the wireless channel is estimated and represented as a complex matrix $\\mathbf{H}_c\\in \\mathbb{C}^{M\\times K}$ representing the narrowband scalar channel weights for each path between $M$ transmit antennas and $K$ receive antennas for each of $C$ narrowband subcarriers within the wideband.\n\tShown in Figure~\\ref{fig_h_matrix}, this wireless channel representation is called the \\ac{OFDM} wideband channel representation since it treats each subcarrier independently and is used for \\ac{OFDM} transmission techniques \\cite{perahia2008}.\n\tAn underlying assumption for this channel model is that the bandwidth of the subcarriers is chosen such that a complex scalar coefficient, $h_{mkc}$, is sufficient to accurately represent the magnitude and phase of the channel state of subcarrier $c$.\n\tFor the remainder of this thesis, we will forgo the subscript $c$ when discussing the wireless $\\mathbf{H}$ matrix channel representation.\n\t\n\t\\begin{figure}[h]\n\\centering\n  \\includegraphics[width=4.5in]{figs/general/beamforming_h_matrix}   \n    \\caption{H-matrix representation of the physical wireless channel.}\n\\label{fig_h_matrix}\n\\end{figure}\n\n\tThe second step for multi-user beamforming is the application of downlink beam-steering weights.\n\tEach data stream for each of $K$ receive antennas, $\\mathbf{S}\\in \\mathbb{C}^{K\\times 1}$, is left-multiplied by a matrix of complex steering weights $\\mathbf{W}\\in \\mathbb{C}^{M\\times K}$  resulting in $\\mathbf{X} = \\mathbf{W}\\cdot \\mathbf{S} \\in\\mathbb{C}^{1\\times M}$ pre-coded signals containing a linear combination of each data stream to transmit from each of the \\ac{AP}'s $M$ antennas.\n\t\n\tThe $K$ antennas may each be on a single separate \\ac{STA} or may be in any combination where a subset of $K$ is on a single receiver \\ac{STA}.\n\tWhen all $K$ are on a single \\ac{STA} this reduces to a simple single-user \\ac{MIMO} transmission.\n\tThe key distinction is that \\acp{STA} are independent receivers in \\ac{MU-MIMO} transmissions and do not share receive information between each other.\n\n\n%#######################################################\n\\subsection{Pre-coding Weight Selection}\n\tThe linear pre-coding weights $\\textbf{W}$, also called ``beam-steering weights,'' are chosen such that the interference between the parallel streams is minimal.  \n\tTo compute these weights, the transmitter must first measure the channel state matrix $\\textbf{H}$.\n\tThe optimal method of constructing the steering matrix is \\acf{DPC} \\cite{costa1983dpc}; however, its computational complexity makes it impractical to implement in full. \n\t\n\t\n\tInstead, a practical method for calculating $\\mathbf{W}$ from $\\mathbf{H}$ that approaches optimal performance is \\ac{ZFBF}\\cite{goldsmith2006zf}.  \n Zero-forcing drives interference between spatial streams to zero, and can be inefficient when users' \\ac{CSI} is not sufficiently orthogonal \\cite{aryafar2010design} or in low \\ac{SNR} environments.\n \\ac{ZFBF} requires calculation of the $\\mathbf{H}$ matrix's Moore-Penrose pseudo-inverse:\n\\begin{equation}\n\\mathbf{W} = \\mathbf{H}^\\dagger =  (\\mathbf{H}^\\textsc{H} \\mathbf{H})^{-1} \\mathbf{H}^\\textsc{H}, \\label{eq:zf}\n\\end{equation}\nwhere $(\\cdot)^\\textsc{H}$ represents the matrix conjugate transpose and $(\\cdot)^\\dagger$ is the Moore-Penrose pseudo-inverse.\n%When the transmitter precodes with perfect \\ac{ZFBF} weights, $\\mathbf{W}$, signals ideally cancel the effects of the wireless channel at the receiver, allowing each user to receive their own, independent streams.\n\n\tA key element of \\ac{ZFBF} is the zero-interference condition which is a direct result of the pseudo-inverse.\n\tBecause $\\textbf{W}=\\textbf{H}^\\dagger$, then $\\textbf{H}\\cdot\\textbf{W}$ is the identity matrix, meaning that the interference from the data stream from user $k=i$ on the data stream for user $k=j$ is nulled and vice versa.\n\t\\ac{ZFBF} pre-codes the transmitted data streams such that the combined wireless channel between the transmitter and the receivers is separated.\n\tIf \\ac{ZFBF} works perfectly, we can express the pre-coded transmission $\\mathbf{X}$ as:\n\\begin{align}\n\\mathbf{X} = \\mathbf{W} \\cdot \\mathbf{S} \\xrightarrow[\\mathbf{H}]{\\text{Transmit}} & \\mathbf{H}\\cdot (\\mathbf{W} \\cdot \\mathbf{S}) \\notag \\\\\n = & \\cancel{\\mathbf{H}} \\cdot (\\cancel{\\mathbf{W}} \\cdot \\mathbf{S}) = \\mathbf{S}\n\\end{align}\n\n\tThere are additional ways to calculate the pre-coding weights for digital beamforming systems; two of the most notable alternatives are conjugate beamforming \\cite{yang2013performance} and \\ac{MMSE} beamforming \\cite{joham2005linear}, both of which are optimal under certain conditions.\n\tIn our work, due to the computational complexity of \\ac{MMSE} beamforming implementation, we focus on the zero-forcing beamforming technique for \\ac{MU-MIMO}, though most of the insights and systems could be easily applied to alternative types of beamforming.\n\n\n%#######################################################\n\\subsection{MIMO Channel Correlation and Temporal Correlation Function}\n%\\rgnote{Beamforming Performance Limits Clean this notation and discusion up}\n\tThe key to the success of the precoding operation is that $\\textbf{H}\\cdot \\textbf{W}$ is designed to reduce to the identity matrix so the transmitted streams are received separately at each receiver.\n\tWe are generally interested in two characteristics of $\\textbf{H}$ that can degrade the performance of this precoding operation: an ill-conditioned $\\textbf{H}$ \\cite{zhong2011distribution} or an out-dated $\\textbf{H}$ \\cite{kaltenberger2008correlation}, each related to different statistical correlation concepts.\n\n\\textbf{MIMO Channel Correlation.}\n\tAn ill-conditioned $\\textbf{H}$ matrix renders matrix inversion inaccurate \\cite{greenbaum2012numerical, peel2005vector} which is required to calculate the pseudo-inverse in Equation~\\ref{eq:zf}.\n\tThis results in $\\textbf{H}\\cdot \\textbf{W}$ becoming far less likely to equal $\\textbf{I}$ and causes ``inter-stream interference'' as a result of beamformed data streams interfering and degrading the received signal strength of a data stream to its intended receiver \\cite{kaltenberger2008correlation}.\n\tIll-conditioned $\\textbf{H}$ matrices can be a result of \\ac{MIMO} channel correlation, a characteristic of the physical arrangement of the \\ac{MIMO} antenna array or the wireless environment that measures how similar the independent paths between \\ac{MIMO} antennas are to each other by relating their individual path random processes \\cite{loyka2001channel}.\n\tWith sufficiently high \\ac{MIMO} channel correlation, any particular realization of the matrix channel random process is likely to not be full-rank, which makes it non-invertible or singular \\cite{peel2005vector}.\n\tIncreasing channel correlation in general results in a decrease in \\ac{SNR} for a \\ac{MIMO} system \\cite{loyka2001channel}, and can be interpreted as a lack of physically independent information channels in the environment or radio array available to convey information.\n\n\\textbf{Channel Correlation Function.}\n\tChannel correlation is a property of the wireless \\ac{MIMO} channel matrix $\\textbf{H}$ and is not to be confused with the channel \\emph{temporal correlation} function, which is a property of the individual channel random process $h_{mk}$ and indicates how correlated the channel condition is as a function of time.\n\tTemporal correlation is the expected autocorrelation between channel snapshots at varying intervals of time calculated as described in \\cite{wallace2003experimental}.\n\tAn intrinsic property of the channel random process, an empirical temporal correlation function can be estimated from time series of channel state observations.\n\tThe empirical correlation coefficient for a single channel $\\rho$ at time interval $\\ell$ is defined as:\n\\begin{align}\n\\rho_\\ell = \\frac{\\mathbb{E}\\big[h_{m}[k]h^{*}_{mn}[k+\\ell]\\big]}{\\mathbb{E}\\big[h_{mn}[k]h^{*}_{mn}[k]\\big]}\n\\label{eq_corr_coeff}\n\\end{align}\nwhere the expectation is calculated for all combinations of transmit antenna $m$, receive antenna $n$ and starting time sample $k$.\n %Assuming each channel path is generated by the same random process, the resulting empirical correlation functions for each \\ac{MIMO} channel path can be averaged together for an overall estimate of channel temporal performance.\n\n\tOut-dated $\\textbf{H}$ matrices are a direct result of the latency between the measurement of the $\\textbf{H}$ matrix and the transmission of the $\\textbf{W}$ precoded data streams.  \n\tIncreased time between the measurement of $\\textbf{H}$ and the transmission of $\\textbf{W}\\cdot \\textbf{S}$, results in a higher probability of incorrect transmit precoding.  \n\tEssentially, the transmitter measures $\\textbf{H}_{t}$ and then calculates $\\textbf{W}_t = \\textbf{H}_t^\\dagger$.\nHowever, the subsequent precoded transmission is $\\textbf{H}_{t+\\Delta}\\cdot \\textbf{W}_{t}$, which may not equal $\\textbf{I}$ since the channel has changed since estimation at time $t$.\n\tThe temporal correlation function is a way of estimating how much the channel will change over time.\n\tWhether or not $\\textbf{H}_{t}=\\textbf{H}_{t+\\Delta}$ is based on environmental variability and user mobility; and, like channel conditioning, is also an environment and frequency dependent characteristic. \n\n\tWhile a large number of studies have characterized the indoor and outdoor propagation environment for the purpose of network planning and algorithm design, few are applicable to evaluating \\ac{MU-MIMO} performance and most have focused on a single frequency band \\cite{boyer2007mimo, hammons2008cooperative, jung2011multipath}.\n\tThis makes measurement studies of different frequencies and radio technologies difficult to compare.\n\nAt the same time, the implementation complexity and computation required for real-time implementation of multi-carrier \\ac{MU-MIMO} has traditionally been prohibitive for software-defined radio platforms \\cite{aryafar2010design}, thus providing a challenge to empirical measurement of \\ac{MU-MIMO} performance.\n\n%\\subsection{Systemic CSI Estimation Error}\n%\\label{sec_systemic_csi_error}\n%\n%\\rgnote{review this section--I wanted to include it because I constantly have to explain this and it's not immediately clear until you actually prove it with math. This might get cut.}\n%\n%Recall that given a channel estimate, $\\Hb$, the precoding weights for the zero-forcing transmitter are $\\mathbf{W} = \\mathbf{H}^\\dagger =  (\\mathbf{H}^\\textsc{H} \\mathbf{H})^{-1} \\mathbf{H}^\\textsc{H}$.\n\t%Arbitrary magnitude and phase offsets may be present in any one estimate of the \\ac{CSI} due to receive gain control or timing estimation jitter, respectively.\n\t%These are normal effects in \\ac{OFDM} transceivers that are compensated by the receive \\ac{OFDM} channel equalization, yet become part of the channel estimation at the receiver \\cite{park2003timing, breit2009coherencetime}.\n\t%While not a new finding, it is useful to discuss the effect that these types of systemic \\ac{CSI} estimation error components and how they differ from estimation error due to stale \\ac{CSI}.\n\t%\n\t%We define a systemic \\ac{CSI} estimation error as any error matrix $\\Phi \\in \\mathbb{C}^{M\\times K}$ that can be represented as a diagonal matrix: $\\Phi = diag(\\alpha_1,\\ldots,\\alpha_M)$.\n%\n\t%It is a well-known property of beamforming that the input \\ac{CSI}, $\\Hb$, can be perturbed by an arbitrary diagonal matrix $\\Phi = diag(\\alpha_1,\\ldots,\\alpha_M)$ such that the \\ac{CSI} used for precoding is $\\hat{\\Hb} = \\Hb\\Phi$.\n\t%The resulting original beamformed streams, $\\mathbf{Y} = \\mathbf{W}\\Hb$, and the received perturbed beamformed streams, $\\mathbf{Y'} = \\hat{\\Hb}^\\dagger\\Hb$, still preserve the orthogonal separation of the user streams owing to the diagonality of $\\Phi$.\n\t%In other words, $\\mathbf{Y'} = (\\Phi)^{-1}\\mathbf{Y}$, and beamforming performance is not significantly impacted by such measurement artifacts.\n%\n\t%This is a powerful result \\rgnote{finish this section when I'm less tired}\n\n%#######################################################\n%\\section{Many-Antenna and Massive MIMO}\n%\\label{sec_mami_back}\n%\n%\\iftoggle{isready} {\n%\n%\n%}{ \\rgnote{The Massive MIMO background section is pending.}}\n\n%#######################################################\n\\section{Software Defined Radio Architecture}\n\\label{sec_sdr_back}\n\nA \\acf{SDR} is a radio that replaces analog signal processing components with programmable digital logic.\nThis radio architecture increases flexibility by replacing analog signal processing components with digital logic, enabling the use of more flexible and complex waveforms such as \\ac{OFDM} and simplifying cross-layer system design.\n\n\\begin{figure}[ht] % Idealized AGC block diagram\n\\centering\n\\includegraphics[width=1\\linewidth]{./figs/agc/generic_sdr}\n\\caption{Block diagram of a generalized Software-Defined Radio system.}\n\\label{fig_sdr_ideal}\n\\end{figure}\n\nWe present a generalized block diagram model of a single-radio \\ac{SDR} in Figure~\\ref{fig_sdr_ideal}.\nWhile implementations of \\acp{SDR} vary, our model captures key components (from left to right) considered in this work and generalizes well to most commercial \\ac{SDR} architectures:\n\\begin{itemize}\n\t\\item \\textbf{Network stack} - signal processing components with non time-critical functions; for example: user scheduling, priority queuing, or layer-2 routing.\n\t\\item \\textbf{Programmable logic} - signal processing components with time-critical or hardware-accelerated functions, specifically for networks layers 1 and 2; for example: gain control, digital pre-distortion, forward error correction.\n\t\\item \\textbf{Analog/Digital interface} - \\acp{ADC} and \\acp{DAC} provide the interface between digital and analog domains by converting digital samples to analog voltages and vice-versa.\n\t\\item \\textbf{Analog Gain Block (1)} - controls the amplitude of the signal entering or leaving the ADC/DAC.\n\t\\item \\textbf{Anti-aliasing filter (2)} - provides a low-pass filtering function on the analog signal to limit its information bandwidth to below the Nyquist sampling rate of the digital conversion step in order to avoid aliasing.\n\t\\item \\textbf{Analog Gain Block (3)} - controls the amplitude of the signal entering or leaving the analog mixer.\n\t\\item \\textbf{Frequency Up/Downconversion Mixing (4)} - a local center frequency, or \\textit{carrier}, is multiplied by the analog signal to either up-convert or down-convert the signal to/from the RF frequency.\n\t\\item \\textbf{RF Gain Block (5)} - the input and output RF signal is amplified in order to meet the linearity or power budget requirements of the system's components.\n\t\\item \\textbf{Receive Band-Pass Filter (6)} - a band-pass filter limits the frequency content of the signal input to the receive radio chain in order to limit noise ingress and harmonic interference from strong out-of-band signals.\n\t\\item \\textbf{Transmit/Receive Switch (7)} - shares a signal antenna with the transmit and receive circuits; while this work generally considers \\ac{TDD} protocols, this system component can be replaced with a frequency duplexer to support \\ac{FDD} protocols, as well.\n\\end{itemize}\n\n\tThis is by no means an exhaustive enumeration of the signal conditioning components present in all \\ac{SDR} systems, but captures the important features needed for the techniques and systems in this work while being generic enough to apply across a wide range of commercial \\ac{SDR} platforms.\n\n\tIn addition, the division of functions between ``programmable logic'' and ``network stack'' blocks is a soft delineation made for ease of discussion.\n\tFor the purpose of this work, we consider programmable logic to be an \\ac{FPGA} or similar digital logic, whereas the network stack is implemented in embedded C or higher layer computer languages on a general-purpose processor.\n\tThis division matches well-known experimental \\ac{SDR} platforms like those mentioned in Section~\\ref{sec_related_sdr}.\n\n\\subsection{Direct Sampling RF}\n\tAs digital circuit integration and speed increases, a new \\ac{SDR} paradigm is emerging in recent years that further reduces the amount of analog components necessary, shifting the dividing line between digital and analog domains in Figure~\\ref{fig_sdr_ideal} nearly all the way to the antenna.\n\t``Direct sampling RF'' systems first used a combination of filtering and aliased sampling to directly sample RF signals without a down-conversion mixing step \\cite{psiaki2005design}.\n\tMore recently, increases in the integration and speed of digital circuits now permit direct sampling \\acp{ADC} at RF frequencies without the drawback of aliased sampling \\cite{xilinx2017rfsoc}.\n\tAlthough widespread use of direct sampling architectures will obviate the need for some of the analog components discussed in this thesis, key contributions of \\ac{AGC}, environmental \\ac{MU-MIMO} studies, and our protocol design remain unchanged.\n\n%#######################################################\n\\section{Two Port Scattering Parameters}\n\\label{sec_scattering}\n\n\tIn order to present some of our circuit design techniques, it will be necessary to be familiar with the definition and notation of normalized scattering, or S-parameters.\n\tThe following discussion is a summary of the discussion and derivation by Yarman \\cite{yarman2010design} and Orfanidis \\cite{orfanidis2002electromagnetic} to describe a lossless two-port device.\n\t\n\\begin{figure}[h]\n\\centering\n  \\includegraphics[width=0.4\\linewidth]{figs/matching/general_2_port}   \n    \\caption{General diagram of a lossless linear 2-port device with scattering parameters.}\n\\label{fig_general_2_port}\n\\end{figure}\n\t\n\tConsider Figure~\\ref{fig_general_2_port}, a linear two-port microwave device that is excited by a complex source or ``generator'' impedance $Z_G$ and terminated in a complex load impedance $Z_L$.\n\tAssuming it it lossless, it is possible to describe the two-port system by describing the relationship of any incident and reflected voltage wave characterized by the wave variables $a_i, b_i$, where the current is defined in the direction of the corresponding $a_i$ vector and the characteristic reference impedance of the system is $Z_0$.\n\\begin{align}\na_1 &= \\frac{V_1+Z_0 I_1}{2\\sqrt{Z_0}}  &a_2 = \\frac{V_2+Z_0 I_2}{2\\sqrt{Z_0}} \\\\\nb_1 &= \\frac{V_1-Z_0 I_1}{2\\sqrt{Z_0}}  &b_2 = \\frac{V_2-Z_0 I_2}{2\\sqrt{Z_0}}\n\\end{align}\nThis results in a relationship between incident and reflected traveling waves:\n\\begin{align}\n\tb_1 &= S_{11}a_1 + S_{12}a_2 \\\\\n\tb_2 &= S_{21}a_1 + S_{22}a_2.\n\\end{align}\n\tThe system of traveling wave equations forms a scattering matrix, $\\mathbf{S}\\in\\mathbb{C}^{2\\times2}$ for a two-port device, $\\mathbf{S}\\in\\mathbb{C}^{4\\times4}$ for a four-port device, etc, that completely characterizes the device's linear, lossless behavior.\n\t\n\tThere are two important assumptions related to the use of S-parameters; the first is that each set of empirical S-parameter is measured within a system with arbitrary characteristic impedance $Z_0$.\n\tAs a matter of convention, nearly all S-parameters are measured in reference to 50~$\\Omega$ and we will assume that in the rest of this thesis.\n\t\n\tSecond, S-parameters only capture \\emph{linear} steady-state device behavior, and for this reason they are generally described as ``small-signal'' parameters. For example, as the input signal power to a two-port amplifier is increased close to the IP1dB point, or the point where the amplifier becomes saturated and the output power decreases by 1~dB from ideal, non-linear behavior will be observed, requiring ``large-signal'' design techniques like load-pull analysis.\n\tQuaglia and Cripps present an excellent discussion of recent developments and models for power amplifiers operating in the saturated regime \\cite{quaglia2017reappraisal}.\n\tWe instead focus on linear operating conditions and small-signal designs for our system in order to preserve the simplicity of each radio chain within a complex many-antenna system, leaving energy efficiency optimization to future work.\n\nFor the system in Figure~\\ref{fig_general_2_port}, it is also useful to define generator and load \\emph{reflection coefficients} that describe the portion of a reflected incident wave with characteristic reference impedance $Z_0$ into a load.\n\\begin{equation}\n\\Gamma_G = \\frac{Z_G - Z_0}{Z_G + Z_0},~~~ \\Gamma_L = \\frac{Z_L - Z_0}{Z_L + Z_0}\n\\end{equation}\n\n\tIn this work, we will use the $\\hat{(\\cdot)}$ notation to indicate a reflection coefficient that is cascaded into a non-reference impedance.\n\tFor example, $\\hat{S}_{11}$ in Figure~\\ref{fig_general_2_port} is the reflection coefficient of the active two-port terminated in an arbitrary load impedance $Z_L$ and can be written:\n\\begin{equation} \\label{eq_}\n\\hat{S}_{11}=S_{11}+\\frac{S_{12}S_{21}\\Gamma_L}{1-S_{22}\\Gamma_L},\n\\end{equation}\nwhere in the case of $Z_L = Z_0 = 50~\\Omega$, we see that this reduces to $\\hat{S}_{11} = S_{11}$.\n\tSimilarly, we can see that:\n\\begin{equation}\n\\hat{S}_{22}=S_{22}+\\frac{S_{21}S_{12}\\Gamma_G}{1-S_{11}\\Gamma_G}.\n\\end{equation}\n\n\tWe now have the tools needed to address the broadband power transfer network design problems presented in Section~\\ref{sec_wurc_pa_design}.\n\t", "meta": {"hexsha": "8640ade48a8c4506bb3d21f1a36aab3b0921ee66", "size": 23144, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "sec/background.tex", "max_stars_repo_name": "RyanEGuerra/ryan_guerra_phd_thesis", "max_stars_repo_head_hexsha": "acf1ebafee00a8e4375008e60e35da8affc97d9b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sec/background.tex", "max_issues_repo_name": "RyanEGuerra/ryan_guerra_phd_thesis", "max_issues_repo_head_hexsha": "acf1ebafee00a8e4375008e60e35da8affc97d9b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sec/background.tex", "max_forks_repo_name": "RyanEGuerra/ryan_guerra_phd_thesis", "max_forks_repo_head_hexsha": "acf1ebafee00a8e4375008e60e35da8affc97d9b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 96.8368200837, "max_line_length": 471, "alphanum_fraction": 0.765295541, "num_tokens": 5718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.3269121699274927}}
{"text": "\\section{Methodology} \\label{method}\n% what is TIMES\n\\subsection{TIMES Model Description}\n\\gls{TIMES} models dynamic energy systems and simulates transition scenarios as a mixed-integer linear optimisation problem that is subject to a primary objective function and additional constraints \\cite{loulou_etsap-tiam_2008}. The generation, refinement, supply, storage, and trade of energy commodities are modelled across multiple sectors and multiple regions using a wide variety of in-built commodity and process types. Emissions can be associated with energy commodities or processes as an emission coefficient per unit commodity produced or consumed. \n\n%basic features of model\nWe outline salient features of our model in this section, while the data used for our simulations are in \\ref{Appendix}. The relevant input files can be accessed online \\cite{chaube_arfci2cner_2021}. The objective function in our single-region model is the overall cost of the transition. The major constraints in our simulations are the demand for electricity (Table \\ref{demand}), emission constraints on the electricity-generation sector based on Japan's \\gls{INDC} (Table \\ref{co2-limits}), and feasible nameplate capacity deployment limits (Table \\ref{caplim}). Miscellaneous assumptions are summarised in Table \\ref{misc-assump}. In summary, our model minimises the transition cost while meeting the increasing electricity demand and achieving the required emission cuts using a combination of generation and storage technologies. \n\n\\begin{table}[H]\n\\centering\n\t\\caption{Electricity demand increase over the simulation time frame.}\n\t\\vspace{0.1in}\n\t\\begin{tabularx}{0.4\\textwidth}{p{0.15\\textwidth} p{0.25\\textwidth}}\n\t\t\\hline\n\\textbf{Year} & \\textbf{Annual demand} \\\\\n & \\textbf{increase} \\\\\n\\hline\n2017-2030 & 1.7 \\% \\cite{noauthor_electricity_2019} \\\\\n2031-2050 & 1.0 \\% \\\\\n2051-2070 & 0.5 \\% \\\\\n2070-2100 & 0.0 \\% \\\\\n\\hline \n\t\\end{tabularx}\n\\label{demand}\n\\end{table}\n\n\\begin{table}[H]\n\\centering\n\t\\caption{Emission constraints.}\n\t\\vspace{0.1in}\n\t\\begin{tabularx}{0.6\\textwidth}{p{0.05\\textwidth} p{0.2\\textwidth}p{0.05\\textwidth} p{0.3\\textwidth}}\n\t\t\\hline\n\\textbf{Year} & \\textbf{Emission limit} & \\textbf{Base} & \\textbf{Reduction} \\\\\n & & \\textbf{year} & \\textbf{from base year} \\\\\n\\hline\n2030 & 438 Mt CO$_2$-eq. & 2013 & 26 \\% \\\\\n2050 & 75 Mt CO$_2$-eq. & 1990 & 80 \\% \\\\\n2100 & 75 Mt CO$_2$-eq. & 2050 & 0 \\% \\\\\n\\hline \n\t\\end{tabularx}\n\\label{co2-limits}\n\\end{table}\n\nWhile Japanese electricity demand is expected to grow in the near future  \\cite{noauthor_electricity_2019}, long-term electricity demand in Japan is expected to plateau, or even decrease, due to Japan's ageing population. However, precisely quantifying this rate of decrease is challenging, as this reduction in population will likely be accompanied by increased electrification of transportation and industrial sectors. Hence, post-2030, we have assumed a demand curve based on increased electrification driving increasing demand, which eventually plateaus due to the aforementioned expected demographic changes. The model captures the initial condition of the post-Fukushima Japanese electricity supply system using The Energy Data and Modelling Centre's data from 2013-2016 \\cite{the_institute_of_energy_economics_japan_energy_2018}. Long term impacts of factors such as the retirement of the existing nuclear reactor fleet and the deployment of emerging technology is assessed by simulating the system until 2100. We account for the carbon cost of each technology using an emission coefficient that incorporates both direct emissions and life cycle emissions averaged over the entire operating lifetime for each technology. Using \\gls{TIMES} day-night and seasonal time periods \\cite{loulou_etsap-tiam_2008}, the daily and seasonal variability of renewables is incorporated. The availability of renewables varies during these time periods based on the annually averaged capacity factors of renewables in Japan \\cite{the_institute_of_energy_economics_japan_energy_2018, irena_renewable_2020}.\n\n%scenario description\nTo explore possible pathways to curbing \\gls{GHG} emissions, we simulated five transition scenarios of varying likelihoods, with different sets of technologies enabled for deployment, as described in Table \\ref{scen-table}. The first set includes conventional technologies such as  \\gls{USC}, \\gls{lng}, solar photovoltaic, wind energy (with onshore, offshore-fixed, and offshore-floating considered separately), and utility-scale lithium-ion battery storage. New deployments of oil-fuelled power plants are disabled due to the declining use of oil for electricity generation in accordance with Japan's goal of energy security and independence, as per the Basic Energy Plan. The second set of technologies considered includes emerging carbon-neutral technologies that are already commercialised or close to commercialisation, namely emerging solar photovoltaic (modelled as a composite of perovskites and CdTe solar cells), \\gls{CCS}, and utility-scale hydrogen power. For hydrogen power, steam reforming, steam reforming with \\gls{CCS}, \\glspl{AEC}, \\glspl{PEMEC}, \\glspl{PEMFC}, and \\glspl{SOFC} were incoporated based on their technological potential. Along with these two technology groups, we also explore the potential impact of nuclear energy. Nuclear power has significant advantages over renewables including long operational lifetimes, extremely low life-cycle emissions, and high capacity factors. However, nuclear power faces extremely low public acceptance in Japan after the Fukushima-Daiichi accident, therefore its future in Japan is highly uncertain. Hence, transition scenarios with and without new nuclear reactor deployment must be juxtaposed to assess the importance of the role of nuclear in emission reduction. Finally, the long-term impact of nascent hydrogen technologies on the hydrogen economy is assessed in an additional scenario. In this scenario, the potential commercialisation of \\gls{SOEC} and \\gls{PWS} post-2050 is explored in the absence of new nuclear power.\n\n\\begin{table}[H]\n\\centering\n\t\\caption{Electricity supply transition scenario definition based on enabled technologies.}\n\t\\vspace{0.1in}\n\t\\begin{tabularx}{0.65\\textwidth}{p{0.1\\textwidth} p{0.18\\textwidth} p{0.15\\textwidth} p{0.18\\textwidth}}\n\\hline \n\\textbf{Scenario}& \\textbf{Emerging} & \\textbf{New} & \\textbf{Nascent}\\\\\n & \\textbf{tech.} & \\textbf{nuclear} & \\textbf{tech.}\\\\\n\n%                 & \\textbf{enabled} & \\textbf{enabled} & \\textbf{enabled}\\\\\n                  \\hline\n%1               &   \\xmark       &      \\xmark     &   \\xmark     \\\\ \n%2               &   \\xmark       &      \\greencheck     &   \\xmark     \\\\ \n%3               &   \\greencheck       &      \\xmark     &   \\xmark     \\\\ \n%4               &   \\greencheck       &      \\greencheck     &   \\xmark     \\\\ \n%5               &   \\greencheck       &      \\xmark     &   \\greencheck     \\\\ \n1               &  No       &         No     &     No  \\\\ \n2               &   No       &      Yes     &     No  \\\\ \n3               &   Yes     &         No      &     No   \\\\\n4               &   Yes     &      Yes     &     No  \\\\ \n5               &   Yes     &      No     &     Yes  \\\\ \n\\hline\n\t\\end{tabularx}\n\\label{scen-table}\n\\end{table}\n\n\n%misc assumptions\nExogenous variables such as economic data, emission coefficients, nameplate capacity limits, and growth rates are detailed in Tables \\ref{eco}, \\ref{caplim}, and \\ref{growrate} respectively. Prices and projections for fossil fuels and nuclear fuel are incorporated \\cite{wittenstein_projected_2015, world_bank_commodity_2016, international_energy_agency_world_2019}. Learning curves for costs and life-cycle emissions are compiled from existing data (Table \\ref{eco}) based on expected scaling of manufacturing, availability of manufacturing materials, and the use of clean energy for manufacturing energy system components. These learning curves are modelled as piecewise linear functions interpolated between the available data points, with the curve plateauing at the latest value for a given parameter, as detailed in Table \\ref{eco}. Capacity limits of renewables and \\gls{PWS} are based on their land-use requirements. The maximum annual capacity growth rates for existing technologies are held constant. The growth rate of nuclear power is based on historic trends and current pressure vessel manufacturing limitations \\cite{iaea_pris_nodate}. The reactor size assumed in this study is 1165 MWe, based on Watts-Bar Unit 2 \\cite{iaea_pris_nodate-1}. Due to a projected increase in the share of renewables, nuclear power plants must be able to load-follow to a certain extent, which is approximated in our model based on French reactors' range of capacity factors. The growth rates of all emerging technologies are modelled on the rates observed for solar photovoltaic technology, with rapid initial growth followed by gradual reduction, eventually reaching a moderate maximum attainable growth rate. One notable exception is the maximum growth rate of emerging solar technologies, which we have assumed to be the same as that of existing solar photovoltaic technologies. We assume that these technologies, some of which are already commercialised or close to commercialisation, will benefit immensely from the already streamlined solar photovoltaic manufacturing and supply chain. Therefore, they could be deployed as rapidly as conventional solar photovoltaic cells. \n\nAll hydrogen storage devices are operated with a maximum availability factor of 90\\%, making them extremely flexible for load-following. Long-term storage of hydrogen is also available using hydrogen tanks with appropriate loss factors \\cite{iea_technology_2015}. For hydrogen electrolysers and fuel cells, life-cycle emissions from just the stack are considered, as balance-of-plant emissions from utility scale hydrogen depend strongly on the type of plant and the source of energy used for electrolysis. Our assumptions about the reduction in the investment costs and life-cycle emissions of batteries are conservative due to the rising cost of cobalt and nickel, and lithium-ion battery manufacturing being concentrated in high \\gls{GHG}-emitting nations, respectively \\cite{oliveira_environmental_2015,emilsson_lithium-ion_2019,turcheniuk_ten_2018,simon_potential_2015}. \n\n\n\n\n\\subsection{Sensitivity analysis}\n%approach, goal, what are we hoping to learn\n%variables, sampling approach, median, range, which variables, which base case scenario, why\nWhile the aforementioned scenarios identify potential pathways that are likely to result in deep emission cuts, many parameters, such as the investment cost, life cycle emissions, and lifetimes, are highly uncertain for novel technologies like \\gls{CCS} and hydrogen generation and conversion technologies. Therefore, our sensitivity analysis is focused on investigating the impact of such parameters (Table \\ref{sa-vars}). We analyse the sensitivity of the share of each of these technologies in the electricity-generation mix and of the system transition cost with respect to these variables.\n\n\\begin{table}[H]\n\\centering\n\t\\caption{Candidate parameters and their variation in our sensitivity analysis.}\n\t\\vspace{0.1in}\n\t\\begin{tabularx}{0.9\\textwidth}{p{0.3\\textwidth} p{0.15\\textwidth} p{0.15\\textwidth}p{0.3\\textwidth}}\n\\hline \n\\textbf{Technology}  & \\textbf{Sampled} & \\textbf{Distribution}& \\textbf{Distribution}\\\\\n\\textbf{Parameter} & \\textbf{Distribution} & \\textbf{Mean}& \\textbf{Range}\\\\\n\\hline\n\\gls{PWS} Investment Cost       & Gaussian    & 3088 \\$/kW & $\\pm$20\\%. \\\\                  \n\\gls{SOEC} Investment Cost      & Gaussian    & 1388 \\$/kW & $\\pm$20\\%.\\\\                  \n\\gls{PEMEC} Investment Cost     & Gaussian    & 3800 \\$/kW & $\\pm$20\\%.\\\\                  \n\\gls{SOFC} Investment Cost      & Gaussian    & 7399 \\$/kW & $\\pm$20\\%.\\\\                  \n\\gls{PEMFC} Investment Cost     & Gaussian    & 7399 \\$/kW & $\\pm$20\\%.\\\\                  \n\\gls{CCS} Gas Investment Cost   & Gaussian    & 2626 \\$/kW & $\\pm$20\\%.\\\\                  \n\\gls{CCS} Coal Investment Cost  & Gaussian    & 5252 \\$/kW & $\\pm$20\\%.\\\\\n\\gls{PWS} Emission Coefficient  & Triangular  & 1.08 g/kWh & 0.2-5.405 g/kWh. \\\\                  \n\\gls{SOEC} Emission Coefficient & Triangular  & 1.08 g/kWh & 0.2-5.405 g/kWh. \\\\\n\\gls{PWS} Efficiency            & Triangular  & 0.525 & 0.5-0.58. \\\\                               \n\\hline\n\t\\end{tabularx}\n\\label{sa-vars}\n\\end{table}\n\nWhile there is significant uncertainty in the investment cost of nuclear power plants \\cite{lovering_historical_2016}, it varies for individual plants and not for the technology as a whole. Preliminary simulations also demonstrated that nuclear power dominates the energy mix, and its share is fairly insensitive to perturbations over known ranges of investment costs \\cite{lovering_historical_2016} due to its low life cycle emissions. Consequently, we eliminated nuclear power's investment cost as a candidate for sensitivity analysis. Furthermore, Japan has been exploring low-emission alternatives to nuclear since the Fukushima Daiichi disaster. In order to assess these potential alternatives which would otherwise be eliminated from the energy mix if new nuclear reactors were deployed, we chose Scenario 5 (Table \\ref{scen-table}) as our base scenario for sensitivity analysis. Ten model parameters were sampled 30 times from appropriate distributions (Table \\ref{sa-vars}). The parameter value at the first year of deployment (Table \\ref{eco}) was varied, but the parameter's learning curve was held constant throughout all scenarios. For example, a 20\\% change in the deployment year (2030) investment cost of \\gls{SOFC}s with respect to the base case scenario reduces their investment cost in 2050 by 20\\% as well. This makes learning-based cost-reductions proportionate across all sensitivity analysis runs. These parameters were randomly co-varied in 30 simulations. The share of each electricity generation technology (as the ratio of cumulative technology output to the cumulative electricity demand) and output of hydrogen technologies was plotted versus each varying parameter to correlate the effect of these parameters with the penetration of these technologies into the mix. A similar approach was also used to correlate these parameters with the system's transition cost.", "meta": {"hexsha": "112d36829926ba514ed07fe1de726bec0a76a636", "size": 14396, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "publications/2020-03-paper/methods.tex", "max_stars_repo_name": "arfc/I2CNER", "max_stars_repo_head_hexsha": "29248cf5fdb0fa8c20f2a58794ef028448bb3e41", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-01T03:40:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-01T03:40:33.000Z", "max_issues_repo_path": "publications/2020-03-paper/methods.tex", "max_issues_repo_name": "arfc/i2cner", "max_issues_repo_head_hexsha": "29248cf5fdb0fa8c20f2a58794ef028448bb3e41", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 87, "max_issues_repo_issues_event_min_datetime": "2018-01-05T21:27:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-19T23:18:20.000Z", "max_forks_repo_path": "publications/2020-03-paper/methods.tex", "max_forks_repo_name": "arfc/i2cner", "max_forks_repo_head_hexsha": "29248cf5fdb0fa8c20f2a58794ef028448bb3e41", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-01-03T20:00:35.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-03T20:00:35.000Z", "avg_line_length": 127.3982300885, "max_line_length": 2174, "alphanum_fraction": 0.7557654904, "num_tokens": 3462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.32691216154586383}}
{"text": "\\documentclass[11pt]{article}\n% \\textwidth=6in\n% \\textheight=9in\n% \\oddsidemargin=0.25in\n% \\evensidemargin=0.25in\n% \\marginparwidth=0in\n% \\marginparsep=0in\n% \\topmargin=0in\n% \\headheight=0in\n% \\headsep=0in\n% \\topskip=0in\n\\usepackage{amssymb}\n\\usepackage{hyperref}\n\\usepackage{lscape}\n\\usepackage{longtable}\n\\usepackage{graphics}\n\\usepackage[pdftex]{graphicx}\n\\usepackage{color}\n\\usepackage{rotating}\n\\newcommand{\\hilight}[1]{\\colorbox{yellow}{#1}}\n\n\\newenvironment{packed_itemize}{\n\\begin{itemize}\n  \\setlength{\\itemsep}{1pt}\n  \\setlength{\\parskip}{0pt}\n  \\setlength{\\parsep}{0pt}\n}{\\end{itemize}}\n\n\\title{Options for a consistent GraphBLAS notation}\n\\author{Tim Davis, Gabor Szarnyas}\n\\date{\\today}\n\\begin{document}\n\n\\maketitle\n\n\\section{Creating matrices}\n\n\\begin{itemize}\n\\item[] in the C API: \\verb'GrB_Matrix_new (&A, m, n, GrB_INT64)'\n\\item[] in ASCII: \\verb'A = int16(m,n)' (I'm open to suggestions for this)\n\\item[] in LaTeX: $\\mbox{let: } {\\bf A} \\in \\mathbb{Z}^{m \\times n}_{16}$\n\\end{itemize}\n\n\\section{Mask computation}\n\nIn the following table the ``mask'' column is the value of the\nmask after applying the value/structural option and optionally\ncomplementing the mask.  If no mask is present (and not complemented)\nthen mask is 1.  If no mask is present (yet complemented) then the mask is\nalways 0; this has no effect unless the Replace option is also used.\n\nThe repl column in the table is ``yes'' if Replace is enabled, ``no'' otherwise.\nThe accum column in the table is ``yes'' if the accum is \npresent, ``no'' otherwise.\nThe ${\\bf C}$ column is listed as $c_{ij}$ if that entry is present,\nand a dash otherwise, likewise for the ${\\bf A}$ column.\n\n\\begin{table}\n{\\small\n\\begin{tabular}{lllll|l}\n\\hline\nrepl & accum & ${\\bf C}$ & ${\\bf A}$ & mask & action taken by ${\\bf C \\langle M \\rangle = C \\odot A}$ \\\\\n\\hline\n\\hline\n       &    &          &           &      & \\verb'C<M>=A' and \\verb'C<!M>=A' \\\\\n\\hline\n    -  &-   & $c_{ij}$ & $a_{ij}$  & 1    &  $c_{ij} = a_{ij}$, update \\\\\n    -  &-   &  -       & $a_{ij}$  & 1    &  $c_{ij} = a_{ij}$, insert \\\\\n    -  &-   & $c_{ij}$ &  -        & 1    &  delete $c_{ij}$ because $a_{ij}$ not present \\\\\n    -  &-   &  -       &  -        & 1    &   \\\\\n\\hline\n    -  &-   & $c_{ij}$ & $a_{ij}$  & 0    &   \\\\\n    -  &-   &  -       & $a_{ij}$  & 0    &   \\\\\n    -  &-   & $c_{ij}$ &  -        & 0    &   \\\\\n    -  &-   &  -       &  -        & 0    &   \\\\\n\\hline\n\\hline\n       &    &          &           &      & \\verb'C<M,repl>=A' and \\verb'C<!M,repl>=A' \\\\\n\\hline\n    yes&-   & $c_{ij}$ & $a_{ij}$  & 1    &  $c_{ij} = a_{ij}$, update \\\\\n    yes&-   &  -       & $a_{ij}$  & 1    &  $c_{ij} = a_{ij}$, insert \\\\\n    yes&-   & $c_{ij}$ &  -        & 1    &  delete $c_{ij}$ because $a_{ij}$ not present \\\\\n    yes&-   &  -       &  -        & 1    &   \\\\\n\\hline\n    yes&-   & $c_{ij}$ & $a_{ij}$  & 0    &  delete $c_{ij}$  (because of \\verb'GrB_REPLACE') \\\\\n    yes&-   &  -       & $a_{ij}$  & 0    &   \\\\\n    yes&-   & $c_{ij}$ &  -        & 0    &  delete $c_{ij}$  (because of \\verb'GrB_REPLACE') \\\\\n    yes&-   &  -       &  -        & 0    &   \\\\\n\\hline\n\\hline\n       &    &          &           &      & \\verb'C<M>+=A' and \\verb'C<!M>+=A' \\\\\n\\hline\n    -  &yes & $c_{ij}$ & $a_{ij}$  & 1    &  $c_{ij} = c_{ij} \\odot a_{ij}$, apply accumulator \\\\\n    -  &yes &  -       & $a_{ij}$  & 1    &  $c_{ij} = a_{ij}$, insert \\\\\n    -  &yes & $c_{ij}$ &  -        & 1    &   \\\\\n    -  &yes &  -       &  -        & 1    &   \\\\\n\\hline\n    -  &yes & $c_{ij}$ & $a_{ij}$  & 0    &   \\\\\n    -  &yes &  -       & $a_{ij}$  & 0    &   \\\\\n    -  &yes & $c_{ij}$ &  -        & 0    &   \\\\\n    -  &yes &  -       &  -        & 0    &   \\\\\n\\hline\n\\hline\n       &    &          &           &      & \\verb'C<M,repl>+=A' and \\verb'C<!M,repl>+=A' \\\\\n\\hline\n    yes&yes & $c_{ij}$ & $a_{ij}$  & 1    &  $c_{ij} = c_{ij} \\odot a_{ij}$, apply accumulator \\\\\n    yes&yes &  -       & $a_{ij}$  & 1    &  $c_{ij} = a_{ij}$, insert \\\\\n    yes&yes & $c_{ij}$ &  -        & 1    &   \\\\\n    yes&yes &  -       &  -        & 1    &   \\\\\n\\hline\n\n\\hline\n    yes&yes & $c_{ij}$ & $a_{ij}$  & 0    &  delete $c_{ij}$  (because of \\verb'GrB_REPLACE') \\\\\n    yes&yes &  -       & $a_{ij}$  & 0    &   \\\\\n    yes&yes & $c_{ij}$ &  -        & 0    &  delete $c_{ij}$  (because of \\verb'GrB_REPLACE') \\\\\n    yes&yes &  -       &  -        & 0    &   \\\\\n\\hline\n\\end{tabular}\n}\n\\caption{Results of the mask/accumulator phase \\label{tab:maskaccum}}\n\\end{table}\n\n\\newpage\n\\section{For Mask/Accum/Replace: there are 32 variants}\n\nAll these options can affect each other so there are 32 variants total,\nexcept that when no mask is present, the value/structural option makes\nno difference.\n\n\\begin{itemize}\n\\item the mask ${\\bf M}$ can be present, or not present.\n\\item the mask can be complemented, or not (even when no mask is present)\n\\item the mask can be valued or structural\n\\item the replace option can be enabled, or not.\n\\item the accumulator can be present, or not.\n\\end{itemize}\n\n\nHere are some options:\n\n\\begin{itemize}\n\\item plain mask, with accum:\n\n    \\begin{itemize}\n    \\item[] in ASCII: \\verb'C<M>+=A'\n    \\item[] in LaTex: $\\bf C \\langle M \\rangle \\odot\\!\\!= A $\n    \\end{itemize}\n\n\\item negated mask, with accum.  Several options for LaTeX.\nI like the $\\overline{\\bf M}$ since it is more compact, but it\nhas problems when $\\bf M$ is also structural (see below).\n\n    \\begin{itemize}\n    \\item[] in ASCII: \\verb'C<!M>+=A'\n    \\item[] in LaTex: $\\bf C \\langle \\neg M \\rangle \\odot\\!\\!= A$\n    \\item[] in LaTex:  $\\bf C \\langle \\overline{M} \\rangle \\odot\\!\\!= A$\n    \\end{itemize}\n\n\\item structural mask, not complemented:\nusing $s({\\bf M})$ where $s$ stands for structural.\nThis feels wordy to me.  Not elegant.\nThe letter $s$ could be confused for a vector or scalar.\n\n    \\begin{itemize}\n    \\item[] in ASCII: \\verb'C<s(M)>+=A'\n    \\item[] in LaTex:  ${\\bf C} \\langle s({\\bf M}) \\rangle \\odot\\!\\!= {\\bf A}$\n    \\end{itemize}\n\n\\item structural mask alternatives.  The letter $s$ could be confused\nfor a scalar or vector, so a Greek letter could be used instead,\nsuch as sigma ($\\sigma$).  But this is also wordy.\n\n    \\begin{itemize}\n    \\item[] in ASCII: \\verb'C<s(M)>+=A'\n    \\item[] in LaTex:  ${\\bf C} \\langle \\sigma({\\bf M}) \\rangle \\odot\\!\\!= {\\bf A}$\n    \\end{itemize}\n\n\\item structural mask alternative.  The notation \n$s({\\bf M})$ is a little wordy.  The Mask cannot be transposed in a\nsingle call to \\verb'GrB_anything' so a superscript would work.  But a\nsubscript might be better, because someone might want to indicate a\ntransposed mask (which would have to be done as a separate call to\n\\verb'GrB_transpose').  This doesn't look good in ASCII however:\n\n    \\begin{itemize}\n    \\item[] in ASCII: \\verb'C<M_s>+=A'\n    \\item[] in LaTex:  ${\\bf C} \\langle {\\bf M}_s \\rangle \\odot\\!\\!= {\\bf A}$\n    \\end{itemize}\n\n\\item structural mask: why not use set notation?  The structure of ${\\bf M}$\nis a set of the entries of ${\\bf M}$.  In a sense, selecting the\nstructural option in the descriptor converts ${\\bf M}$\ninto a set.  So how about set notation, with curly brackets?\nWe don't use curly brackets anywhere else in GraphBLAS, so this is unambigous.\nI like this the best.\n\n    \\begin{itemize}\n    \\item[] in ASCII: \\verb'C<{M}>+=A'\n    \\item[] in LaTex:  ${\\bf C} \\langle \\{{\\bf M}\\} \\rangle \\odot\\!\\!= {\\bf A}$\n    \\end{itemize}\n\n\\item complemented structural mask, for $s({\\bf M})$:\n\n    \\begin{itemize}\n    \\item[] in ASCII: \\verb'C<!s(M)>+=A'\n    \\item[] in LaTex:  ${\\bf C} \\langle \\neg s({\\bf M}) \\rangle \\odot\\!\\!= {\\bf A}$\n    \\end{itemize}\n\n\\item  complemented structural mask, for the curly bracket option:\nIt is important to note that the structure of ${\\bf M}$ is taken\nfirst, and then complemented.  Not the other way around.\nI like this option the best (with $\\neg$).\n\n    \\begin{itemize}\n    \\item[] ASCII: \\verb'C<!{M}>+=A'\n    \\item[] LaTeX: ${\\bf C} \\langle \\neg \\{{\\bf M}\\} \\rangle \\odot\\!\\!= {\\bf A}$\n    \\item[] LaTeX:\n    ${\\bf C} \\langle \\overline{ \\{{\\bf M}\\}} \\rangle \\odot\\!\\!= {\\bf A}$\n    ouch.  That is a long overline, and could be confused with\n    ${\\bf C} \\langle  \\{\\overline{\\bf M}\\} \\rangle \\odot\\!\\!= {\\bf A}$\n    \\end{itemize}\n\n\\end{itemize}\n\n(Gabor) I like the set notation for the ``structure'' option and the $\\neg$\nsymbol for negation.  (Tim): I think this is the best option I've seen so far,\ntoo.\n\n\\newpage\n\n\\section{Replace option}\n\nThe examples consider all options except for Replace.\nHere are some ideas; I am not really happy with any of them.\n\n\\begin{itemize}\n\n\\item simple case: a mask with replace\n\n    \\begin{itemize}\n    \\item[] in ASCII: \\verb'C<M,replace>+=A'\n    \\item[] in LaTex: $\\bf C \\langle M, \\mbox{replace} \\rangle \\odot\\!\\!= A $\n    \\end{itemize}\n\n\\item complemented structural mask with replace\n\n    \\begin{itemize}\n    \\item[] ASCII: \\verb'C<!{M},replace>+=A'\n    \\item[] LaTeX: ${\\bf C} \\langle \\neg \\{{\\bf M}\\}, \\mbox{replace}\n    \\rangle \\odot\\!\\!= {\\bf A}$\n    \\end{itemize}\n\n\\item no mask, yet complemented, with replace.  This does actual work that\ndoes not depend on the input matrix $\\bf A$ or input scalar.\n\n    \\begin{itemize}\n    \\item[] ASCII: \\verb'C<!,replace>=A'\n    \\item[] LaTeX: ${\\bf C} \\langle \\neg, \\mbox{replace}\n    \\rangle \\odot\\!\\!= {\\bf A}$\n    \\end{itemize}\n\n\\end{itemize}\n\n\\subsection{(Gabor) Alternative. (Tim): I like this}\n\nHow about double angle brackets for ``replace''? This could symbolize that the computation only keeps that part by the mask and discards the rest.\n\n(Tim):  I like this idea.  It indicates to me that the Mask is ``strong,''\nin the sense that stuff outside the mask (where the final mask value is\nfalse after possibly taking the structure and/or complementing)\ngets obliterated.\n\n\\begin{itemize}\n\n    \\item simple case: a mask with replace\n    \n        \\begin{itemize}\n        \\item[] in ASCII: \\verb'C<<M>>+=A'\n        \\item[] in LaTex: $\\bf C \\langle\\!\\langle M \\rangle\\!\\rangle \\odot\\!\\!= A $\n        \\end{itemize}\n    \n    \\item complemented structural mask with replace\n    \n        \\begin{itemize}\n        \\item[] ASCII: \\verb'C<<!{M}>>+=A'\n        \\item[] LaTeX: ${\\bf C} \\langle\\!\\langle \\neg \\{{\\bf M}\\}\n        \\rangle\\!\\rangle \\odot\\!\\!= {\\bf A}$\n        \\end{itemize}\n    \n    \\item no mask, yet complemented, with replace\n    \n        \\begin{itemize}\n        \\item[] ASCII: \\verb'C<<!>>=A'\n        \\item[] LaTeX: ${\\bf C} \\langle\\!\\langle \\neg \\rangle\\!\\rangle \\odot\\!\\!= {\\bf A}$\n        \\end{itemize}\n\n\\end{itemize}\n\n\\section{Different accum operators}\n\nThe accum operator can be any function, such as PLUS, TIMES, FIRST, MIN, MAX,\nANY, logical OR, logical AND etc.  I propose using using symbols from C/C++ if \navailable, or spelling out the function otherwise.\nAssuming no mask/replace/complement, in ASCII:\n\n    \\begin{itemize}\n    \\item[] \\verb'C +=A ' plus\n    \\item[] \\verb'C *= A ' times\n    \\item[] \\verb'C &&= A ' logical AND\n    \\item[] \\verb'C &= A ' bitwise AND\n    \\item[] \\verb'C ||= A ' logical OR\n    \\item[] \\verb'C |= A ' bitwise OR\n    \\item[] \\verb'C ^= A ' logical XOR, but see the XOR in LaTeX below\n    \\item[] \\verb'C /= A ' divide\n    \\item[] \\verb'C max= A ' maximum\n    \\item[] \\verb'C any= A ', this is Tim's \\verb'GxB_ANY_*' operator.\n    \\item[] \\verb'C first= A '\n    \\item[] and so on\n    \\end{itemize}\n\nIn LaTeX, it is very similar.  Note the spacing:\n\n    \\begin{itemize}\n    \\item[] $\\bf C \\,+\\!\\!= A $, plus\n    \\item[] Latex source of the above: \\verb'$\\bf C \\,+\\!\\!= A$'\n    \\item[] $\\bf C \\,*\\!\\!= A $, times\n    \\item[] $\\bf C \\,\\wedge\\!\\!= A $, logical AND\n    \\item[] $\\bf C \\,\\&\\!\\!= A $, bitwise AND\n    \\item[] $\\bf C \\,\\vee\\!\\!= A $, logical OR\n    \\item[] $\\bf C \\,|\\!\\!= A $, bitwise OR\n    \\item[] $\\bf C \\,\\oplus\\!\\!= A $, logical XOR?  but this conflicts with\n        the use of $\\oplus$ to denote a generic additive operator.\n        So perhaps logical XOR should be written\n        $\\bf C \\,\\mbox{xor}\\!\\!= A $.\n    \\item[] $\\bf C \\,/\\!\\!= A $, divide, or perhaps\n        $\\bf C \\,\\div\\!\\!= A $\n    \\item[] $\\bf C \\,\\mbox{max}\\!\\!= A $, maximum\n    \\item[] $\\bf C \\,\\mbox{any}\\!\\!= A $, ANY\n    \\item[] $\\bf C \\,\\mbox{first}\\!\\!= A $, FIRST\n    \\item[] and so on\n    \\end{itemize}\n\n(Gabor) I propose to use \\verb+\\mathbin{}+ for spacing around the operator,\ne.g., $\\bf C \\mathbin{+\\!\\!=} A $.\n(Tim) I like that suggestion, which looks like this in the LaTeX:\n\\verb'$\\bf C \\mathbin{+\\!\\!=} A$'.\n\n\n\\end{document}\n\n", "meta": {"hexsha": "21f6c26a06884393f53f39331dae8cf87b341399", "size": 12455, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Notation/notation.tex", "max_stars_repo_name": "GraphBLAS/LAGraph-Working-Group", "max_stars_repo_head_hexsha": "30662a6ad814baeda21c46025411254558b977db", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-04-01T14:13:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-26T17:09:05.000Z", "max_issues_repo_path": "Notation/notation.tex", "max_issues_repo_name": "GraphBLAS/LAGraph-Working-Group", "max_issues_repo_head_hexsha": "30662a6ad814baeda21c46025411254558b977db", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-03-18T14:24:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-25T10:26:37.000Z", "max_forks_repo_path": "Notation/notation.tex", "max_forks_repo_name": "GraphBLAS/LAGraph-Working-Group", "max_forks_repo_head_hexsha": "30662a6ad814baeda21c46025411254558b977db", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-06-03T14:51:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-13T14:15:35.000Z", "avg_line_length": 35.4843304843, "max_line_length": 146, "alphanum_fraction": 0.5681252509, "num_tokens": 4297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3269121615458638}}
{"text": "%!TEX root = /home/renaud/Documents/EPL/tfe/latex/tfe.tex\n%-------------------------------------------CLUSTERING OVERTURNER-----------------------------------------------%\n\\newpage\n\\section{Clustering of the overturner problem}\n% 1. Expliquer ce qu'on va faire\n% 2. Décomposition du domaine en boxes, on cherche ce que donne le clustering sur ces boxes.\n% 3. Résultats pour nboxy = 15, nboxz = 10 (et expliquer que ces choix permettent que y0 et z0 correspondent à des frontières de box)\n\nThis section presents the results of applying a stability-based community detection algorithm on the overturner problem. First, we explain how the method is applied and then we present the results for a given set of data's.\n\n% %-----------------------DESCRIPTION OF THE METHOD---------------------------------%\n% \\subsection{Description of the method}\n% In order to apply a clustering algorithm on the overturner problem, we have to define how the model can be considered as a graph. To this end, the domain is decomposed into $\\nby \\times \\nbz$ boxes. We note $N_{box} = \\nby\\nbz$ the total number of boxes. Figure~\\ref{fig:box_scheme} represents an example of such a domain decomposition with $\\nby = 15$ and $\\nbz = 10$. For any time $T$, the corresponding directed graph is build as follows : each node represents a box, and the weight of the edge between nodes $i$ and $j$ is the probability $m_{ij}(T)$ that a particle ends up in box $j$ after a time $T$ if it was initially in box $i$. If $m_{ij}(T) = 0$, one can equivalently consider that there is no edge between nodes $i$ and $j$. Since the problem is stationary, $m_{ij}(T)$ depends only on the elapsed time $T$, not on the initial time. Hence, the initial time can indifferently be considered as being zero. The adjacency matrix $\\b M(T)$ of the graph is build from the weights $m_{ij}(T)$: $[\\b M(T)]_{ij} = m_{ij}(T)$. For any time $T$, $\\b M(T)$ is row-stochastic, i.e. $\\b M(T)\\b 1 = \\b 1$, where $\\b 1$ is the $N_{box}$-dimensional unit column vector. The latter has a straightforward physical interpretation: every particle remains in the domain.\n% \\begin{figure}[h!]\n% \t\\centering\n% \t\\input{fig/clusters/box_scheme}\n% \t\\caption{Illustration of the decomposition of the domain into boxes with $\\nby = 15$ and $\\nbz = 10$.}\n% \t\\label{fig:box_scheme}\n% \\end{figure}\n\n% To estimate the probabilities $m_{ij}(T)$, the program is run for a time $T$ with each box containing initially $J$ uniformly distributed particles. $m_{ij}(T)$ is then numerically estimated as the number of particles having started in box $i$ and ending up in box $j$, divided by $J$. This \\textit{box counting} method has been extensively used to estimate the concentration in studies using random walk modeling, see e.g. \\cite{riddle1998specification}. Nevertheless, this method suffers some drawbacks; the most important of them are pointed in \\cite{spivakovskaya2007lagrangian}, but we recall them here for the sake of completeness. The estimated transition probability depends on the choice of the boxes, in particular of their size and their center. Moreover, the number of boxes cannot be chosen to be too large; otherwise the estimated concentration tends to become very irregular or noisy. Finally, the resolution of the estimated concentration is limited to the size of the boxes, as it cannot be described in a box more precisely than a constant. But it is the perfect method for our problem since the volume average over such boxes (the nodes) is precisely what we want. Note however that other methods exist for estimating the concentration, that might be better suited for other studies. For example, the \\textit{kernel estimation} method allows to reduce drastically the number of particles, and does not suffer from the resolution limit inherent to the box counting method. This method is briefly presented in \\cite{spivakovskaya2007lagrangian}. Classical references are \\cite{silverman1986density} and \\cite{wand1995kernel}.\n\n\n% %-------------------------USE OF THE TOOLBOX----------------------------%\n% \\subsection{Use of the stability software}\n% % \\newcommand\\localFontSize@mlpr{10}\n% We present here briefly how the \\textit{PartitionStability} software is used to compute the partitions. Every concept appearing here has been presented in chapter~\\ref{chap:clustering}. The \\mtlb{stability} function is simply called as follows : \\vspace{-.2cm}\n% \\begin{center}\n% \t\\mtlb{[S,N,VI,C] = stability(M,Markov_T,'directed','plot','teleport',0.01);}\n% \\end{center} %style = Matlab-bw for black and white\n% Here, \\mtlb{M} is the matrix $\\b M(T)$ at the desired time $T$; \\mtlb{Markov_T} is the vector containing every Markov times at which the optimal stability partition has to be computed (ideally, the sampling should be exponential); the \\mtlb{'directed'} option specifies that we consider a directed graph; \\mtlb{'plot'} asks the program to plot the stability, number of communities and variation of information as a function of the Markov time; and \\mtlb{'teleport',0.01} allows to specify the value of the teleportation probability $\\tau$ to $0.01$, the default value being $0.15$. The choice of $0.01$ is motivated by the fact that we believe the graph to be ergodic, even if we cannot prove it. Note that the program allows to choose which type of laplacian should be used to calculate the stability. However, the question does not arise here since both laplacians are equivalent in our case. Indeed, the total outgoing weight is the same at every node and is precisely equal to the number of particles $J$ released in each box. Hence, $k_i = J$ for every node $i$ and $\\langle \\b k \\rangle = J$, so that $\\bs \\lambda_{combi}(\\b k) = \\b k/ \\langle \\b k \\rangle = \\b 1 = \\bs \\lambda_{norm}(\\b k)$. We let thus the program run with the default normalized Laplacian, since it does not make any difference in our case. The output arguments \\mtlb{S}, \\mtlb{N}, \\mtlb{VI} and \\mtlb{C} contain respectively the stability, the number of communities, the variation of information, and the optimal partition for each Markov time contained in \\mtlb{Markov_T}. If the latter is of size $n$, then \\mtlb{S}, \\mtlb{N} and \\mtlb{VI} are $n$-dimensional vectors and \\mtlb{C} is a $N_{box} \\times n$ matrix. At the $j$th Markov time, communities are labeled by consecutive integers between $0$ and \\mtlb{N(j)}$-1$ such that \\mtlb{C(i,j)} $= k$ means that node $i$ belongs to community $k$ at Markov time \\mtlb{Markov_T(j)}.  \n\n\n\n%--------------------------RESULTS--------------------------------------%\n\\subsection{Results}\nNow we present some results on a particular discretization of the overturner problem. The box decomposition of the domain is the one shown in figure~\\ref{fig:box_scheme}, and $J = 10\\,000$ particles are released in each box. More precisely, a box is decomposed into a $100 \\times 100$ sub-grid, and one particle is initially located at every point of the sub-grid, so that the particles are initially uniformly distributed within the box. The transition probability matrices $\\b M(T)$ are generated for different values of $T$. We show here the results for $T = 1$, $10$, $50$ and $100$ years. The vector of the Markov times \\mtlb{Markov_T} is sampled exponentially from $0.1$ to $100$ : $\\log_{10}($\\mtlb{Markov_T}$) = [-1,\\, -0.98, \\dots ,\\, 1.98,\\, 2]$. Notice that the physical meaning of the Markov time changes with $T$ : a Markov time step of $1$ is equal to a physical time step of $T$. Hence, for $a >0$, if for $\\b M(T)$ we find some communities in the range of Markov times $[t_{M_1},\\, t_{M_2}]$, then for $\\b M(aT)$ we expect to find similar communities in the range of Markov times $\\frac{1}{a}[t_{M_1},\\, t_{M_2}]$.\n\n% \\begin{figure}[!htp]\n% \t\\centering\n% \t\\input{fig/clusters/box_scheme}\n% \t\\caption{Illustration of the decomposition of the domain into boxes with $\\nby = 15$ and $\\nbz = 10$.}\n% \t\\label{fig:box_scheme}\n% \\end{figure}\n\nFigures~\\ref{fig:stab0}, \\ref{fig:stab1}, \\ref{fig:stab5} and~\\ref{fig:stab10} show the stability curves, the number of communities and the variation of information as functions of the Markov time for $T = 1$, $10$, $50$ and $100$ years respectively. As discussed in section~\\ref{subsec:robustness}, robust partitions correspond to plateaux in the community curve of the graphs. By using this criterion, partitions of 6, 5, 4, 3 and 2 communities are found at different time scales. Those partitions are summarized in table~\\ref{tab:partitions_summary} along with the physical time range at which they reveal themselves. Figure~\\ref{fig:cluster0}, \\ref{fig:cluster1}, \\ref{fig:cluster5} and~\\ref{fig:cluster10} shows the most robust clusterings for $T=1$, $10$, $50$ and $100$ respectively. From table~\\ref{tab:partitions_summary}, we observe that some similar partitions happen to be the most relevant at different time scales when we modify $T$. For example, for $T=1$, 6 communities are found in the time range 9 - 12 years (figure~\\ref{fig:cluster0_6_}). A similar clustering is found for $T = 10$ and $T = 50$ but in the time ranges 24 - 48 years and 36-48 years respectively (figures~\\ref{fig:cluster1_6_} and~\\ref{fig:cluster5_6_}).\n\nIt is important to notice that the community detection algorithm may fail to detect the right number of communities. Take figure~\\ref{fig:cluster1_2_} for example : the stability software detects 2 communities. However, the white community consists of two noncontiguous blocks. Intuitively, particles leaving the lower white block should enter the khaki block first before entering the upper white block. Hence, there should be 3 communities rather than 2 for this partitioning. A way to quantify this intuition is by looking at\n\\begin{equation}\n\t\\b M_{\\P}(T) = \\diag^{-1}(\\b n)\\b H^{\\t}_{\\P} \\b M(T) \\b H_{\\P},\n\\end{equation}\nwhere $\\b n$ is the $c$-dimensional vector containing the number of blocks in each community. $[\\b M_{\\P}]_{kl}$ is the transition probability from community $k$ to community $l$. By considering the clustering where the lower and the upper white blocks are separated communities, we get\n\\begin{equation}\n\t\\b M_{\\P}(10) = \n\t\\begin{pmatrix}\n\t\t0.886 & 0.114 & 0.000\\\\\n\t    0.052 & 0.895 & 0.053\\\\\n\t    0.017 & 0.256 & 0.727\\\\\n    \\end{pmatrix}.\n\\end{equation}\nHere, community 1 is the lower white block, community 2 is the khaki block and community 3 is the upper white block. We observe that $[\\b M_{\\P}]_{13} = 0$ and $[\\b M_{\\P}]_{31} = 0.017$, indicating very weak links between the lower and the upper white blocks. Hence, they should indeed be considered as separated communities. However, this does not mean that~\\ref{fig:cluster1_2_} provides then the optimal clustering with 3 communities ! Such a clustering is rather given by figure~\\ref{fig:cluster1_3_}, and the clustering proposed in figure~\\ref{fig:cluster1_2_} should simply be disregarded as being non-relevant.\n\nNow, let us analyze a seemingly relevant community structure. By looking at table~\\ref{tab:partitions_summary} together with figures~\\ref{fig:cluster1_5_} and~\\ref{fig:cluster5_5_}, we observe that two similar 5-communities clusterings arise in the time range 50 - 63 years when $T = 10$ and $T = 50$. This indicates that those community structures might be more resilient than others. There is only a 2 boxes difference between the two clusterings; we will therefore focus on the clustering found for $T = 10$, namely the one from figure~\\ref{fig:cluster1_5_}. The communities are numbered from 1 to 5 on the figure. The matrix $\\b M_{\\P}$ for this community structure is\n\\begin{equation}\n\t\\b M_{\\P}(10) = \n\t\\begin{pmatrix}\n\t0.907 & 0.024 &     0 & 0.024 & 0.045\\\\\n    0.073 & 0.827 & 0.043 & 0.057 & 0\\\\\n        0 & 0.029 & 0.925 & 0.036 & 0.010\\\\\n    0.039 & 0.041 & 0.089 & 0.776 & 0.055\\\\\n    0.020 &     0 & 0.048 & 0.022 & 0.910\\\\\n\t\\end{pmatrix}.\n\\end{equation}\nObviously, particles in a community tends to stay in that community. But what are the main interconnections between communities ? By looking at matrix $\\b M_{\\P}$, we observe that particles leaving community 1 goes preferentially to community 5; from community 2, the main tendency is to go to community 1; from 3 to 4 and 2; from 4 to 3 (mainly because of the size of 3) and from 5 to 3. Hence, the dominant tendency is that the particles tend to describes a clockwise cycle in the domain, which is exactly the expected behavior. \n\n\\textcolor{blue}{J'aimerais aller un peu plus loin dans mes commentaires mais les idées ne se bousculent pas... Et les commentaires que je fais ci-dessus ne nous apprennent rien. Cela fait sans doute beaucoup d'images d'images pour au final pas grand chose.}\n\n\\begin{table}[H]\n\\centering\n\\caption{Summary of the dominant clusterings found by inspection of the transition probability matrix $\\b M(T)$ for $T = 1$, $10$, $50$ and $100$ years.}\n\\label{tab:partitions_summary}\n\\begin{tabular}{l|ccccc}\n\\hline\n\\multirow{2}{*}{$T$} & \\multicolumn{5}{c}{Time range [year]} \\\\ \\cline{2-6} \n                  &  6 communities &  5 communities  &  4 communities  &  3 communities &  2 communities \\\\ \\hline\n              1   & \\phantom{0}9 - 12  & 15 - 26 & 28 - 36 & \\phantom{0}38 - $\\dots$  &   \\\\\n              10  & 24 - 48 &  50 - 63 & & \\phantom{0}91 - 316 & 331 - $\\dots$ \\\\\n              50  & 36 - 48 & 50 - 66 & & \\phantom{0}69 - 138 & 144 - 190 \\\\\n              100 & 58 - 76 & 79 - 105 & &120 - 229 & 240 - 316 \\\\ \\hline\n\\end{tabular}\n\\end{table}\n\n%------------------ T = 1 ------------------------------%\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width = .7\\textwidth]{clusters/stab0.eps}\n\t\\caption{Stability, number of communities and variation of information as a function of the Markov time for $T=1$ year.}\n\t\\label{fig:stab0}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\begin{subfigure}[t]{0.49\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{clusters/cluster0_6_.eps}\n\t\t\\caption{6 communities.}\n\t\t\\label{fig:cluster0_6_}\n\t\\end{subfigure}\n\t\\begin{subfigure}[t]{0.49\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{clusters/cluster0_5_.eps}\n\t\t\\caption{5 communities.}\n\t\t\\label{fig:cluster0_5_}\n\t\\end{subfigure}\n\t\\begin{subfigure}[t]{0.49\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{clusters/cluster0_4_.eps}\n\t\t\\caption{4 communities.}\n\t\t\\label{fig:cluster0_4_}\n\t\\end{subfigure}\n\t\\begin{subfigure}[t]{0.49\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{clusters/cluster0_3_.eps}\n\t\t\\caption{3 communities.}\n\t\t\\label{fig:cluster0_3_}\n\t\\end{subfigure}\n\t\\caption{The relevant clusterings detected at different time scales for $T=1$ year.}\n\t\\label{fig:cluster0}\n\\end{figure}\n\n%------------------ T = 10 -----------------------------%\n\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width = .7\\textwidth]{clusters/stab1.eps}\n\t\\caption{Stability, number of communities and variation of information as a function of the Markov time for $T=10$ years.}\n\t\\label{fig:stab1}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\begin{subfigure}[t]{0.49\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{clusters/cluster1_6_.eps}\n\t\t\\caption{6 communities.}\n\t\t\\label{fig:cluster1_6_}\n\t\\end{subfigure}\n\t\\begin{subfigure}[t]{0.49\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{clusters/cluster1_5_num.eps}\n\t\t\\caption{5 communities.}\n\t\t\\label{fig:cluster1_5_}\n\t\\end{subfigure}\n\t\\begin{subfigure}[t]{0.49\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{clusters/cluster1_3_.eps}\n\t\t\\caption{3 communities.}\n\t\t\\label{fig:cluster1_3_}\n\t\\end{subfigure}\n\t\\begin{subfigure}[t]{0.49\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{clusters/cluster1_2_.eps}\n\t\t\\caption{2 communities detected by the algorithm which should rather be considered as being 3 communities.}\n\t\t\\label{fig:cluster1_2_}\n\t\\end{subfigure}\n\t\\caption{The relevant clusterings detected at different time scales for $T=10$ years.}\n\t\\label{fig:cluster1}\n\\end{figure}\n\n%------------------ T = 50 -----------------------------%\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width = .7\\textwidth]{clusters/stab5.eps}\n\t\\caption{Stability, number of communities and variation of information as a function of the Markov time for $T=50$ years.}\n\t\\label{fig:stab5}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\begin{subfigure}[t]{0.49\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{clusters/cluster5_6_.eps}\n\t\t\\caption{6 communities.}\n\t\t\\label{fig:cluster5_6_}\n\t\\end{subfigure}\n\t\\begin{subfigure}[t]{0.49\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{clusters/cluster5_5_.eps}\n\t\t\\caption{5 communities.}\n\t\t\\label{fig:cluster5_5_}\n\t\\end{subfigure}\n\t\\begin{subfigure}[t]{0.49\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{clusters/cluster5_3_.eps}\n\t\t\\caption{3 communities.}\n\t\t\\label{fig:cluster5_3_}\n\t\\end{subfigure}\n\t\\begin{subfigure}[t]{0.49\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{clusters/cluster5_2_.eps}\n\t\t\\caption{2 communities.}\n\t\t\\label{fig:cluster5_2_}\n\t\\end{subfigure}\n\t\\caption{The relevant clusterings detected at different time scales for $T=50$ years.}\n\t\\label{fig:cluster5}\n\\end{figure}\n\n%------------------ T = 100 ----------------------------%\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width = .7\\textwidth]{clusters/stab10.eps}\n\t\\caption{Stability, number of communities and variation of information as a function of the Markov time for $T=100$ years.}\n\t\\label{fig:stab10}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\begin{subfigure}[t]{0.49\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{clusters/cluster10_3_.eps}\n\t\t\\caption{3 communities.}\n\t\t\\label{fig:cluster10_3_}\n\t\\end{subfigure}\n\t\\begin{subfigure}[t]{0.49\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{clusters/cluster10_2_.eps}\n\t\t\\caption{2 communities.}\n\t\t\\label{fig:cluster10_2_}\n\t\\end{subfigure}\n\t\\caption{The relevant clusterings detected at different time scales for $T=100$ years.}\n\t\\label{fig:cluster10}\n\\end{figure}", "meta": {"hexsha": "46522673d7034986277b8fdecdcfa518b5e8222b", "size": 17723, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "inputs/method/overturner_clustering.tex", "max_stars_repo_name": "dufaysr/tfe", "max_stars_repo_head_hexsha": "75c6191e1533da84233d4a38dea3cc3f3884a286", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inputs/method/overturner_clustering.tex", "max_issues_repo_name": "dufaysr/tfe", "max_issues_repo_head_hexsha": "75c6191e1533da84233d4a38dea3cc3f3884a286", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inputs/method/overturner_clustering.tex", "max_forks_repo_name": "dufaysr/tfe", "max_forks_repo_head_hexsha": "75c6191e1533da84233d4a38dea3cc3f3884a286", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 81.2981651376, "max_line_length": 1911, "alphanum_fraction": 0.7181064154, "num_tokens": 5245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.3269121531642348}}
{"text": "%!TEX root = /home/renaud/Documents/EPL/tfe/latex/tfe.tex\n\\section{The code} \\label{sec:thecode}\nThe preceding sections cover all the material needed to implement a Lagrangian code that solves a two-dimensional advection-diffusion problem. For the need of this work, a \\Cpp code has been implemented. The choice of \\Cpp is motivated by the fact that it is \\textit{fast}, and that it comes together with a wide range of \\textit{open source} supporting tools. Another reason is that \\Cpp is an \\textit{object-oriented language}, and it is widely held that writing in an object-oriented style leads to programs which are easier to understand, to extend, to maintain and to refactor \\cite{pitt2012guide}.\n\nThe code deals with the two-dimensional transport equation\n\\begin{equation} \\label{eq:TEcode}\n\t\\frac{\\partial C}{\\partial t} = \\nabla \\cdot (-\\b u C + \\b K \\nabla C)\n\\end{equation}\non rectangular domains with no-through boundary conditions. It allows to simulate trajectories, to compute the concentration and to build the transition probability matrix for a given partitioning of the domain. The trajectories are simulated using the backward Euler method, applied on the system of backward Itô SDE's~\\eqref{eq:bi-TM}.\n% The user can choose between the Euler-Maruyama \\textcolor{red}{attention implémenter drift gradient term} and backward-Itô method to simulate the trajectories. In view of the preceding sections, the Itô SDE corresponding to~\\eqref{eq:TEcode} is\nIn this work, only the box-counting method is used for the estimation of the concentration (and thus also for the computation of the transition probability matrix) but the density kernel estimation method has also been implemented for the sake of completeness.\n\nIn order to use the code on a particular problem meeting the above specifications, a class that defines the problem must be implemented. That class must inherit from the abstract base class \\mintinline{c++}{AbstractAdvDiffProblem} (see listing~\\ref{listing:abstractadvdiffproblem}), and must at least implement the two pure virtual functions of the abstract base class:\n\\begin{listing}[ht!]\n\\caption{The abstract base class \\cppcode{AbstractAdvDiffProblem}.}\n\\label{listing:abstractadvdiffproblem}\n\\begin{minted}[breaklines,tabsize=4,fontsize=\\footnotesize,style=tango,escapeinside=||]{c++}\nclass AbstractAdvDiffProblem\n{\n\tprotected:\n\t\tdouble mH0, mH1; // boundaries of the domain in the z-direction : H0 <= z <= H1\n\t\tdouble mL0, mL1; // boundaries of the domain in the y-direction : L0 <= y <= L1\n\n\tpublic:\n\t\tAbstractAdvDiffProblem(double H0, double H1, double L0, double L1);\n\t\tvirtual ~AbstractAdvDiffProblem(){};\n\t\tdouble getH0() const;\n\t\tdouble getH1() const; \n\t\tdouble getL0() const;\n\t\tdouble getL1() const;\n\t\tvirtual SymMatrix getK(double y, double z) const=0; // diffusivity tensor\n\t\tvirtual LowerTriMatrix getB(double y, double z) const; // 2K = BB'\n\t\tvirtual Vec2 getU(double y, double z) const=0; // velocity vector\n\t\tvirtual void printInfo(std::ofstream& f) const;\n};\n\\end{minted}\n\\end{listing}\n\\begin{itemize}[nosep]\n\t\\item \\mintinline[style=tango]{c++}{SymMatrix getK(double y, double z)}: returns the diffusivity tensor $\\b K$ evaluated at $(y,z)$. The return value is of type \\cppcode{SymMatrix}, a structure intended to store a $2\\times 2$ symmetric matrix with only three elements stored in memory. Instantiating an object \\cppcode{A} of type \\cppcode{SymMatrix} is pretty simple: \\cppcode{SymMatrix A(a,b,c)} creates the matrix\n\t\\[\n\t\tA = \\begin{pmatrix} a & b \\\\ b & c \\end{pmatrix},\n\t\\] \n\twhere \\cppcode{a}, \\cppcode{b} and \\cppcode{c} are of type \\cppcode{double}. The elements of \\cppcode{A} are then accessed via the syntax \\cppcode{A(i,j)} which uses one-based indexing. Hence, \\cppcode{A(1,1) = a}, \\cppcode{A(1,2) = A(2,1) = b} and \\cppcode{A(2,2) = c}. The same syntax can be used to modify the elements of \\cppcode{A}.\n\t\\item \\mintinline[style=tango]{c++}{Vec2 getU(double y, double z)}: returns the velocity vector $\\b u$ evaluated at $(y,z)$. The return value is of type \\cppcode{Vec2}, a structure that stores two elements of type \\cppcode{double}. The syntax \\cppcode{Vec2 v(a,b)} is used to create the two-dimensional vector $v = (a,b)$. The elements of \\cppcode{v} are accessed via the syntax \\cppcode{v(i)} which also uses one-based indexing: \\cppcode{v(1) = a} and \\cppcode{v(2) = b}.\n\\end{itemize}\nBy default, the code computes the matrix $\\b B$ using~\\eqref{eq:B} and~\\eqref{eq:Bstar}. This is done by the function \\cppcode{LowerTriMatrix GetB(double y, double z)}. In some cases, it can be interesting to overload that definition of \\cppcode{GetB}, which is possible since this function is virtual. The return value must be of type \\cppcode{LowerTriMatrix}, which is a structure similar to \\cppcode{SymMatrix} but is intended to store lower triangular $2\\times2$ matrices instead of symmetric $2\\times2$ matrices.\n\nNotice that the code as such implements the dimensional form of the transport model. However, it can be used to run simulations on the adimensional form of the transport model. To this end, it suffice to define the functions \\cppcode{getK} and \\cppcode{getU} accordingly: \\cppcode{getK} shall return the inverse of the Peclet matrix, and \\cppcode{getU} shall return the adimensional velocity vector.\n\nOnce a class describing the problem is properly defined, three methods can be used to compute either the trajectories, the normalized concentration or the transition probability matrix. We call those methods the \\textit{compute methods}. Their signatures are given in listing~\\ref{listing:signature_compute}. Since those functions are well documented in the code, we invite the interested reader to refer to the code for further explanations about those functions.\n\\begin{listing}[ht!]\n\\caption{Signatures of the \\textit{compute methods}.}\n\\label{listing:signature_compute}\n\\begin{minted}[breaklines,tabsize=4,fontsize=\\footnotesize,style=tango,escapeinside=||]{c++}\nvoid ComputeTrajectories(const AbstractAdvDiffProblem& prob, std::string model, \n\t\t\t\t\t\t double dt, double T, int Nloc, double yStart, double zStart);\nvoid ComputeConcentration(const AbstractAdvDiffProblem &prob, std::string model,\n\t\t\t\t\t\t  double dt, double T, std::string estimator, int Nloc,\n\t\t\t\t\t\t  double yStart, double zStart, int nboxy, int nboxz);\nvoid ComputeTransitionProbabilities(const AbstractAdvDiffProblem& prob,\n\t\t\t\t\t\t\t\t\tstd::string model, int nboxy, int nboxz, int nyloc,\n\t\t\t\t\t\t\t\t\tint nzloc, double dt, double Times[], int nTimes,\n\t\t\t\t\t\t\t\t\tbool binary, std::string estimator = \"box\");\n\\end{minted}\n\\end{listing}\n\nTest cases with analytical solutions have been built to assess the validity of the implementation. They are presented in appendix~\\ref{app:test_case} and the numerical solution is compared to the analytical solution, producing satisfying results.\n% \\begin{itemize}\n% \t\\item \\mintinline{c++}{LowerTriMatrix getB(double y, double z)}:\n% \t\\item io \n% \\end{itemize} \n% Le code résout des probleme 2D generaux sur un domaine rectangulaire avec des conditions frontières no trough.\n% Choix entre Ito (attention alors il faut implémenter le drift gradient velocity) et backward Ito.\n% --> Pour résoudre un problème particulier :\n% \t1. Implémenter une class problem qui hérite de abstractadvdiff, et dont les méthode minimales sont : ...\n% \tAbstractAdvDiff implémente Cholesky par défaut mais on peut aussi implémenter sa propre méthode getB,\n%\tce qui permet d'autre choix de B et dans certains cas une meilleure efficacité. (+ exemple)\n%\tSi on veut de l'adim il suffit de faire K = 1/Pe et U = ...\n%\t2. Ensuite les méthodes Compute permette de calculer trajectoire, concentration et matrice de transition de proba.\n%\tCes méthodes font entre autre appel aux méthodes de la classe solver et de ses enfant. Par exemple backward ito est implémenté dans \n%\tbiSlver par <CODE>.\n%\t3. Mettre le code \"main\" dans un studycase (à voir si c'est vraiment intéressant de parler des studycases)\n% \n% \\begin{listing}[ht!]\n% \\caption{Implementation of the backward Euler method.}\n% \\label{listing:updateposition}\n% \\begin{minted}[breaklines,tabsize=4,fontsize=\\footnotesize,style=tango,escapeinside=||]{c++}\n% void BISolver::UpdatePosition(const AbstractAdvDiffProblem& prob)\n% {\n% \tLowerTriMatrix B;\n% \tVec2 U;\n% \tdouble R1, R2, dY, dZ, y, z, ypred, zpred;\n% \tdouble sqrt_dt = sqrt(mdt);\n% \tfor (int i=0; i<mParticles.mN; i++)\n% \t{\n% \t\t// position and speed of particle i at time t\n% \t\ty = mParticles.mY[i];\n% \t\tz = mParticles.mZ[i];\n% \t\tU = prob.getU(y,z);\n% \t\tB = prob.getB(y,z);\n% \t\t// realisations of the noises\n% \t\tR1 = wiener(generator);\n% \t\tR2 = wiener(generator);\n% \t\t// prediction step of the backward-Ito scheme\n% \t\tdY = B(1,1)*sqrt_dt*R1;\n% \t\tdZ = B(2,1)*sqrt_dt*R1 + B(2,2)*sqrt_dt*R2;\n% \t\t// No-through BC also applies on the predictions -> bouncing on the walls\n% \t\typred = y+dY;\n% \t\tzpred = z+dZ;\n% \t\typred = (ypred < prob.getL0()) ? 2*prob.getL0()-|\\color{black}{ypred}| : \n% \t\t\t\t(ypred > prob.getL1()) ? 2*prob.getL1()-|\\color{black}{ypred}| : ypred;\n% \t\tzpred = (zpred < prob.getH0()) ? 2*prob.getH0()-|\\color{black}{zpred}| : \n% \t\t\t\t(zpred > prob.getH1()) ? 2*prob.getH1()-|\\color{black}{zpred}| : zpred;\n% \t\t// amplitude of the noises\n% \t\tB = prob.getB(ypred,zpred);\n% \t\t/* update particles positions using backward-Ito scheme\n% \t\t* No-flux BC : Bounce on the wall */\n% \t\typred = mParticles.mY[i] + U(1)*mdt + B(1,1)*sqrt_dt*R1;\n% \t\tzpred = mParticles.mZ[i] + U(2)*mdt + B(2,1)*sqrt_dt*R1 + B(2,2)*sqrt_dt*R2;\n% \t\tmParticles.mY[i] = (ypred < prob.getL0()) ? 2*prob.getL0()-|\\color{black}{ypred}| : \n% \t\t\t\t\t\t   (ypred > prob.getL1()) ? 2*prob.getL1()-|\\color{black}{ypred}| : ypred;\n% \t\tmParticles.mZ[i] = (zpred < prob.getH0()) ? 2*prob.getH0()-|\\color{black}{zpred}| :\n% \t\t\t\t\t\t   (zpred > prob.getH1()) ? 2*prob.getH1()-|\\color{black}{zpred}| : zpred;\n% \t}\n% \tmParticles.mTime += mdt;\n% }\n% \\end{minted}\n% \\end{listing}", "meta": {"hexsha": "c65159fd4f225b43845e68ac0692ec6c3dbc5746", "size": 9898, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "inputs/numerical/sde2D.tex", "max_stars_repo_name": "dufaysr/tfe", "max_stars_repo_head_hexsha": "75c6191e1533da84233d4a38dea3cc3f3884a286", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inputs/numerical/sde2D.tex", "max_issues_repo_name": "dufaysr/tfe", "max_issues_repo_head_hexsha": "75c6191e1533da84233d4a38dea3cc3f3884a286", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inputs/numerical/sde2D.tex", "max_forks_repo_name": "dufaysr/tfe", "max_forks_repo_head_hexsha": "75c6191e1533da84233d4a38dea3cc3f3884a286", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 77.328125, "max_line_length": 603, "alphanum_fraction": 0.7340876945, "num_tokens": 2845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.32690955191512305}}
{"text": "\\documentclass[12pt]{cdblatex}\n\\usepackage{eqtns}\n\n\\begin{document}\n\n\\section*{PhysRevD.62.044034 equation (15)}\n\n\\begin{cadabra}\n   from shared import *\n   import cdblib\n\n   jsonfile = 'eqtn15.json'\n   cdblib.create (jsonfile)\n\n   defG2GBar = cdblib.get ('defG2GBar','gamma.json')\n\n   # --------------------------------------------------------------------------\n   # Rphi = the part of Rab from the conformal factor\n\n   Rab := R_{a b}.                                                   # cdb (eq15.101,Rab)\n\n   substitute     (Rab, defRab)                                      # cdb (eq15.102,Rab)\n   substitute     (Rab, defRiem)                                     # cdb (eq15.103,Rab)\n   substitute     (Rab, defG2GBar)                                   # cdb (eq15.104,Rab)\n   distribute     (Rab)                                              # cdb (eq15.105,Rab)\n   product_rule   (Rab)                                              # cdb (eq15.106,Rab)\n   Rab = product_sort (Rab)                                          # cdb (eq15.107,Rab)\n   rename_dummies (Rab)                                              # cdb (eq15.108,Rab)\n   canonicalise   (Rab)                                              # cdb (eq15.109,Rab)\n   substitute     (Rab, $gBar_{b c} gBar^{c a} -> gBar^{a}_{b}$)\n   substitute     (Rab, $\\partial_{a}{gBar^{a}_{b}} -> 0$)\n   substitute     (Rab, $\\partial_{a}{gBar_{b}^{c}} -> 0$)\n   substitute     (Rab, $gBar^{a}_{a} -> 3$)\n   eliminate_kronecker (Rab)                                         # cdb (eq15.110,Rab)\n   Rab = product_sort (Rab)                                          # cdb (eq15.111,Rab)\n   rename_dummies (Rab)                                              # cdb (eq15.112,Rab)\n   canonicalise   (Rab)                                              # cdb (eq15.113,Rab)\n   substitute     (Rab, $gBar_{b c} gBar^{c a} -> gBar^{a}_{b}$)     # cdb (eq15.114,Rab)\n   substitute     (Rab, $gBar^{a}_{a} -> 3$)                         # cdb (eq15.115,Rab)\n   eliminate_kronecker (Rab)                                         # cdb (eq15.116,Rab)\n\n   # |\\clearpage|\n   # isolate Rphi from Rab by switching to local RNC\n\n   Rphi := @(Rab).\n\n   substitute (Rphi, $GammaBar^{a}_{b c}->0$)                        # cdb (eq15.117,Rphi)\n   substitute (Rphi, $\\partial_{a}{gBar_{b c}}->0$)                  # cdb (eq15.118,Rphi)\n   substitute (Rphi, $\\partial_{a}{gBar^{b c}}->0$)                  # cdb (eq15.119,Rphi)\n\n   substitute (Rphi, $\\partial_{a b}{\\phi} -> DBar_{a b}{\\phi}$)     # cdb (eq15.120,Rphi)\n   substitute (Rphi, $\\partial_{a}{\\phi} -> DBar_{a}{\\phi}$)         # cdb (eq15.121,Rphi)\n\n   defRphi := Rphi_{a b} -> @(Rphi).\n\n   cdblib.put ('defRphi',defRphi,jsonfile)\n\\end{cadabra}\n\n\\clearpage\n\n\\begin{dgroup*}[spread=5pt]\n   \\begin{dmath*}\n      \\cdb{eq15.101}\n         = \\Cdb*{eq15.102}\n         = \\Cdb*{eq15.103}\n         = \\Cdb*[\\hskip2.5cm\\hfill]{eq15.104}\n         = \\Cdb*{eq15.105}\n         = \\Cdb*{eq15.106}\n         = \\Cdb*{eq15.107}\n   \\end{dmath*}\n\\end{dgroup*}\n\n\\clearpage\n\n\\begin{dgroup*}[spread=5pt]\n   \\begin{dmath*}\n      \\cdb{eq15.101}\n         = \\Cdb*{eq15.108}\n         = \\Cdb*[\\hskip2cm\\hfill]{eq15.109}\n         = \\Cdb*{eq15.110}\n         = \\Cdb*{eq15.111}\n         = \\Cdb*{eq15.112}\n   \\end{dmath*}\n\\end{dgroup*}\n\n\\clearpage\n\n\\begin{dgroup*}[spread=5pt]\n   \\begin{dmath*}\n      \\cdb{eq15.101}\n         = \\Cdb*[\\hskip2.5cm\\hfill]{eq15.113}\n         = \\Cdb*[\\hskip2.5cm\\hfill]{eq15.114}\n         = \\Cdb*{eq15.115}\n         = \\Cdb*{eq15.116}\n   \\end{dmath*}\n\\end{dgroup*}\n\nThe above doesn't look much like equation (15). So, what do we do? First note that {\\tt (eq15.116)}\nrepresents the full $R_{ab}$, that is, equation (14). To isolate the contributions from $\\phi$\nwe can first set $\\bar{\\Gamma}$ and its derivatives to zero (which in turn requires setting\n$\\partial_{a} \\bar{g}_{bc}=0$). The result is equation {\\tt (eq15.119)} below. Having set\n$\\bar{\\Gamma}$ to zero means that we can replace $\\partial$ with $\\bar{D}$ leading to equation\n{\\tt (eq15.121)}. But that is clearly a tensor equation and so by the usual arguments it must be true\nin all frames (not just this frame with $\\bar{\\Gamma}=0$). It's a standard argument and I've\nprobably overdone the discussion. Anyway, equation {\\tt (eq15.121)} is exactly equation $(15)$ from\nthe paper. Yeah.\n\n\\begin{dgroup*}[spread=5pt]\n   \\begin{dmath*}\n      R^{\\phi}_{ab}\n         = \\Cdb*{eq15.117}\n         = \\Cdb*{eq15.118}\n         = \\Cdb*{eq15.119}\n         = \\Cdb*{eq15.120}\n         = \\Cdb*{eq15.121}\n   \\end{dmath*}\n\\end{dgroup*}\n\n\\clearpage\n\n\\begin{cadabra}\n   # --------------------------------------------------------------------------\n   # Check against prd62.\n\n   foo := @(Rphi).                                      # cdb(eq15.lcb,foo)\n   bah  = cdblib.get('prd62.eq15.rhs','prd62.json')     # cdb(eq15.prd,bah)\n\n   diff := @(foo) - @(bah).\n\n   distribute     (diff)\n   diff = product_sort (diff)\n   rename_dummies (diff)\n   map_sympy      (diff, \"simplify\")\n   canonicalise   (diff)                                # cdb(eq15.chk,diff)\n\\end{cadabra}\n\n% \\clearpage\n\n\\begin{dgroup*}\n   \\begin{dmath*} \\cdb*{eq15.lcb} \\end{dmath*}\n   \\begin{dmath*} \\cdb*{eq15.prd} \\end{dmath*}\n   \\begin{dmath*} \\cdb*{eq15.chk} \\end{dmath*}\n\\end{dgroup*}\n\n\\end{document}\n", "meta": {"hexsha": "ce2d6bf8178e071f8bfc6de7b109d9127f20d4d9", "size": 5286, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "source/eqtn15.tex", "max_stars_repo_name": "leo-brewin/adm-bssn-equations", "max_stars_repo_head_hexsha": "4fc58cb7db16b87851dfd33950d6540b5c81db50", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-13T18:47:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-13T18:47:34.000Z", "max_issues_repo_path": "source/eqtn15.tex", "max_issues_repo_name": "leo-brewin/adm-bssn-equations", "max_issues_repo_head_hexsha": "4fc58cb7db16b87851dfd33950d6540b5c81db50", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/eqtn15.tex", "max_forks_repo_name": "leo-brewin/adm-bssn-equations", "max_forks_repo_head_hexsha": "4fc58cb7db16b87851dfd33950d6540b5c81db50", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2054794521, "max_line_length": 101, "alphanum_fraction": 0.4956488838, "num_tokens": 1726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.32687308068501086}}
{"text": "\\newcommand{\\sigmatwo}{\\overline{\\sigma}}\nThe current query evaluation mechanism for \\datalogM is a bottom-up naive\\cite{Green:2013:DRQ:2688167.2688168} evaluation. It is based on the fixpoint-theoretic semantics, deriving tuples from rules until no new tuples may be derived. The rule evaluation is performed using relational algebra (see e.g. \\cite{Abiteboul:1995:FDL:551350}) and a thorough description is given in Appendix A.\n\n\\subsection{Mutual Dependencies and Predicate Ordering}\nWith multiple rules and potentially many mutual dependencies between the predicates, there is a need to find an order in which to apply the rules. Indeed, for mutually dependent predicates, all rules which may derive new facts for those predicates need to be iterated together. \\textit{Stratification}\\cite{Green:2013:DRQ:2688167.2688168} is the process of clustering the predicates that need to be computed together into so called \\textit{strata} as well as to find an optimal order between the strata. The iterative fix-point algorithm is then run over each \\textit{stratum} following the computed order. The process is formalized below.\n\nA predicate $P_i$ \\textit{directly depends} on predicate $P_j$ iff there exists a rule for which $P_i$ is in the head and $P_j$ is in the body. Let $Dep(P_i)$ be the set of predicates which $P_i$ directly depends on. The dependency graph $G_{DEP}$ has the set of predicate symbols as vertices and there is an edge from $P_i$ to $P_j$ iff $P_j \\in DEP(P_i)$. A strongly connected component in $G_{DEP}$ then contains the predicates which are mutually recursive. Such a connected component can be found e.g. using Tarjan's algorithm \\cite{Tarjan72depthfirst} and is called a stratum. By merging the vertices of $G_{DEP}$ into such strata we get a graph $G_{STRAT}$ with vertices being the strata of $G_{DEP}$ and edges the collapsed multi-edges from $G_{DEP}$. By construction there exists a total order on $G_{STRAT}$ with $S_1 < S_2$ iff $(S_1, S_2) \\in Edge(G_{STRAT})$. The desired order is found by a reverse post-order search of $G_{STRAT}$.\n\\begin{figure*}[!hbt]\n\t\\includegraphics[scale=0.7]{img/souffleEval.pdf}\n\t\\caption{Souffle Printing Pipeline. \\textbf{Yellow}: A Datalog Program. \\textbf{Blue}: An evaluation mechanism. \\textbf{Green}: A compiler stage. }\n\t\\label{figure:soufflePipeline}\n\\end{figure*}\n\\subsection{Cross Compilation}\nIn addition to internal evaluation, $Datalog^M$ supports cross-compilation, or pretty-printing, to Souffle\\cite{SouffleHome}. The compilation pipeline is shown in figure \\ref{figure:soufflePipeline}. First, a number of semantic checks are performed. For example, the semantic check ensures that all variables used in the head of a rule also occures in the body of the rule (the range restriction property\\cite{Ceri:1989:YAW:627272.627357}). In the next stage, the program is type checked (type-checking is described in more detail in the following section). As was mentioned in the introduction (and will be explained in the next section), \\datalogM supports meta-predicates. Souffle however has no such support so naturally it does not recognize the meta-semantics. To this end, a separate pre-process Datalog program is generated to evaluate all meta-predicates and subsequently output them as EDB files. Finally, the program is pretty-printed to a Souffle program $P_{Souffle}$. $P_{Souffle}$ declares the meta-predicates and loads them from the EDB files; the meta-predicates can then be used as ordinary predicates within the Souffle environment.", "meta": {"hexsha": "9ad9ac665f4c1ef45e0617071346bfbf82524c53", "size": 3523, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/src/corelanguageimpl.tex", "max_stars_repo_name": "HampusBalldin/EDAN70Datalog", "max_stars_repo_head_hexsha": "f288d96b2b7923a717617412358fb40d07d6ee20", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "report/src/corelanguageimpl.tex", "max_issues_repo_name": "HampusBalldin/EDAN70Datalog", "max_issues_repo_head_hexsha": "f288d96b2b7923a717617412358fb40d07d6ee20", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/src/corelanguageimpl.tex", "max_forks_repo_name": "HampusBalldin/EDAN70Datalog", "max_forks_repo_head_hexsha": "f288d96b2b7923a717617412358fb40d07d6ee20", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 251.6428571429, "max_line_length": 1151, "alphanum_fraction": 0.7885325007, "num_tokens": 906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.32679494560810607}}
{"text": "% !TeX root = ../main.tex\n% Add the above to each chapter to make compiling the PDF easier in some editors.\n\\graphicspath{{./figures/ch4/}}\n\n\\chapter{Simulation}\\label{chapter:simulation}\n\nTo find out how the HPB format influences efficiency and revenue in comparison to the SMRA, I ran several simulations based on the findings in the previous chapter. For the bidders to act as agents in the auction simulations, they need a strategy and a suitable selection heuristic to model their behaviour and thus to place bids. In this chapter I will at first give an overview of the structure of the implementation, followed by a further description of the simulation process by defining the setup as well as the strategy and the selector model. Afterwards, I will present the findings of the experiment.\n\n\\section{Structure of the Project}\nIn order to run the simulations I extended an existing project from the university chair. In this project, an abstract structure on how to run auction simulations was given by an already defined software architecture. \\autoref{fig:structure-sim} visualises the structure I used for my experiment. The whole project was implemented in Python.\n\nAs can be seen from the visualisation, a main \\textbf{Auction} object exists, that has an own \\textbf{AuctionFormat} which specifies the auction characteristics and the procedure, as well as a collection of agents participating. Every \\textbf{Agent} possesses a bidding \\textbf{Strategy} which in turn holds a \\textbf{Selector}. The latter computes optimal bidding vectors based on the chosen selector model (e.g. a naive exhaust approach by iterating over each possible bid). Then the strategy translates these into according actions like submitting a bid based on the selector's result or calling a waiver to exclude the agent from bidding in the current round. The strategy class realises this by comparing the payoff $ \\pi_{combination} $ of different combinations, where payoff is defined as a \\textit{quasilinear utility function} by subtracting the prices $ p(combination) $ a bidder has to pay from the bidder's valuation $ v(combination) $ for a certain bidding combination.\n\n\\begin{equation}\n\t\\centering\n\t\\pi_{combination} = v(combination) - p(combination)\n\t\\label{eq:payoff}\n\\end{equation}\n\nThe valuation $ v(combination) $ can be obtained by the strategy class using its \\textbf{ValueModel}. This model has access to the \\textbf{ItemStructure}, which holds the \\textbf{Items} of the auction as well as possible packages, mapping (e.g. to frequency bands), or hierarchies. Before submitting a bid, the action gets validated by the \\textbf{BidderInfo} class (e.g. to check if spectrum cap instructions were followed). After each successful round, the important information like \\textit{payments, prices}, and the current \\textit{allocation} are saved in the \\textbf{RoundInfo}.\n\n\\begin{figure}[h]\n\t\\centering\n\t\\includegraphics[scale=0.4]{structure.png}\n\t\\caption{Structure of the simulation implementation} \\label{fig:structure-sim}\n\\end{figure}\n\nTo simulate the auctions I had to extend the existing auction formats for SMRA and HPB. Making it possible to fill them with the specific characteristics of the German auction. In particular, this included implementing the spectrum cap of three blocks in the 900 MHz band and extending mechanisms in the HPB format. Also, I needed to implement the mathematical formulation of the value model (see \\autoref{subsection:value-model}) as well as the specific selector model, which is based on the value model. Furthermore, I implemented a sealed bid model to calculate the optimal allocation needed to compare the two auction formats.\n\n\n\\section{The Simulation Process}\nAs stated in the previous section, in order to run the simulations based on the information and data of the German Auction I needed to extend and further develop the existing project. In this section I will describe the set-up of the auctions (e.g. the items and hierarchies used) as well as the implementation of the value, strategy and selector model.\n\n\\subsection{Auction Set-Up}\nAs discussed in the Value Model section, the simulation concentrated on the 700, 900 and 1800 MHz frequency bands, which include a total of 23 items. Each bidder was able to bid on every item and item combination. For the first round, the starting prices were appointed according to the official definition of the German Auction \\cite{Bundesnetzagentur2015} as provided in \\autoref{tbl:start-parms}.\n\n\\begin{table}[h]\n\t\\centering\n\t\\begin{tabular}{|c|c|c|c|}\n\t\t\\hline\n\t\t\\textbf{block} & \\textbf{quantity} & \\textbf{\\begin{tabular}[c]{@{}c@{}}starting\\\\ price\\end{tabular}} & \\textbf{\\begin{tabular}[c]{@{}c@{}}eligibility\\\\ points\\end{tabular}} \\\\ \\hline\n\t\t700 MHz        & 6                 & EUR 75 mn                                                         & 2                                                                     \\\\ \\hline\n\t\t900 MHz        & 7                 & EUR 75 mn                                                         & 2                                                                     \\\\ \\hline\n\t\t1800 MHz       & 10                & EUR 37.5 mn                                                       & 2                                                                     \\\\ \\hline\n\t\\end{tabular}\n\t\\caption{Starting parameters for the items in the auction}\n\t\\label{tbl:start-parms}\n\\end{table}\nThe activity level was chosen to be 65\\% of the eligibility points held by each bidder in every round. This is the activity level chosen in the first phase of the German Auction. As no mathematical progression rule for the phase shifts exists, because they are decided by the auction moderator \\cite{Bundesnetzagentur2015}, the activity level stayed the same throughout the auction simulations. \nFurthermore, the exposure ratio (the degree to which a bidder can overbid the valuation of an item) was set very high, practically eliminating exposure. This decision was made, as deriving a fitting exposure ratio for the simulation was out of the scope of this thesis. I will discuss the implications in \\autoref{chapter:conclusion}. \n\nAs HPB makes use of pre-defined packaging of items using a tree structure, I needed to develop a useful item hierarchy to be used in the simulation. To show how the hierarchy affects the bidding and thus efficiency and revenue, I created two slightly different hierarchy models. As the 900 MHz band had a spectrum cap, the bidders were limited on how many items they can acquire (here: maximum of three blocks). The other bands had no such limitations, thus each bidder would try to acquire the most items possible under the constraints of item valuations and maximizing payoff. To research the impact of the hierarchies on the bidding behaviour, I devised two different hierarchies that had different pre-packaging in the 900 MHz band, because bidders were only allowed to acquire up to three blocks, a combination that had super-additive valuation for the bidders (\\autoref{subsection:value-model}) and I assumed the competition to be high in this band. \\autoref{fig:hpb-hierarchy-competition} shows the item hierarchy called $ H_{competition} $, where one package of three items (reflecting a desired bundling) exists in the structure. The hierarchy is called \"competition\" as only one of the desired bundling exists. \n\n\\begin{figure}[]\n\t\\centering\n\t\\input{./figures/ch4/hierarchy_competition.tikz}\n\t\\input{./figures/ch4/h_1800.tikz}\n\t\\caption{HPB Hierarchy \"Competition\", packages with bonus in red}\n\t\\label{fig:hpb-hierarchy-competition}\n\\end{figure}\n\nAs the 900 MHz band consists of seven items, it has enough items for incorporating two bundles of three items each. I assumed that following the formulation and the bonuses of the value model (see \\autoref{subsection:value-model}) at least two bidders will try to acquire bonus enabling packages. This is what $ H_{VM} $ in \\autoref{fig:hpb-hierarchy-vm-predict} incorporates. \nNote, that bidders were still able to gain super-additive valuation by bidding on single items (in different packages) and still be able to successfully secure three items in the 900 MHz band. In the HPB simulation, the advantage for bidders was that they could bid on packages, signalling an interest in a certain item combination. When bidding on the package, the bidder either acquires all the items in its desired packaging or none, thus resulting in a reduced exposure risk for the bidders as it prevents him from potentially bidding above an item's valuation in order to realise a certain item combination.\n\n\\begin{figure}[]\n\t\\centering\n\t\\input{./figures/ch4/hierarchy_vm_predict.tikz}\n\t\\input{./figures/ch4/h_1800.tikz}\n\t\\caption{HPB Hierarchy \"VM Prediction\", packages with bonus in red}\n\t\\label{fig:hpb-hierarchy-vm-predict}\n\\end{figure}\n\n\\subsection{Strategy and Selector Model}\nIn the simulation, the participating agents needed to emulate a certain bidding behaviour. This is realised by the strategy model. In this experiment, the bidders followed a \\textbf{straightforward bidding} behaviour, essentially meaning that they always bid according to the minimum prices in each round \\cite[p. 270.]{Milgrom2000}. This can be described as a function $ p(I) $ that returns the bidding price of an item according to minimum prices, where $ \\beta $ is the current bid price \\cite[p. 6 ff.]{Wellman2008}.\n\n\\begin{equation}\n\tp(I) = \n\t\t\\begin{cases}\n\t\t\t\\beta & \\text{if item is already won} \\\\  \n\t\t\t\\beta + increment & \\text{otherwise}\n\t\t\\end{cases} \n\t\t\\label{eq:sb-prices}\n\\end{equation}\n\nThe straightforward bidding is also called \\textit{\"myopic best response\"} \\cite{Brooks2000}. Additionally, the strategy used in the simulation is payoff maximizing.\n \nAs explained in the section above, value models return the valuation of certain item combinations and selectors return optimal bidding vectors $ \\vec{\\theta} $. The strategy model translates the results into an according action, e.g. a bid based on a payoff maximizing strategy.  \n\nOne could argue that once the simulations are run on a computer, finding the best bidding combination should be done via an exhaustive iteration over every single possible combination. However, using this approach showed to be an ineffective use of time and to be computationally expensive. The number of items in the simulation was 23. Lining up all the items in fixed order and using a binary vector to display if each respective item should be included into a bid creates the vector $ \\vec{\\theta} \\in \\{0,1\\}^{23} $. With simple combinatorics it can be deduced, that computing every possible allocation takes $ 2^{23} \\approx 8.388 \\times 10^{6} $ iterations. Remembering that 700 MHz had 6 blocks, 900 MHz 7 blocks and 1800 MHz 10 blocks and taking into account, that bidders were only allowed to acquire up to three blocks in the 900 MHz band, the number of iteration can be reduced to $$ 2^6 * \\sum_{i=1}^{3} \\binom{n}{k} * 2^{10} = 2^6 * (2^6 - 1) * 2^{10} = 2^{16} * (2^6-1) = 2^{22} - 2^{16} \\approx 4.1 \\times 10^6 $$\nDue to the current implementation in the project, this has to be done twice for each of the three bidders, requiring an amount of $ 2 \\times 3 \\times 2^{22} - 2^{16} \\approx 25.1 \\times 10^{6} $ computation steps each auction round.   \nClearly, a different approach was needed to select the optimal bidding vector. \n\nInstead, a \\textbf{mixed integer linear program} (MILP) %TODO abbr\nwas used to compute the optimized bidding vector $ \\vec{\\theta} $. For that, I extended existing code for an additive payoff selector from the main project and added the specific bonuses and caps to the LP. Additionally, the bidders had to incorporate bidding on packages, when the payoff for single items and package bids were the same. This behaviour was integrated by adding a \\textit{very small} bonus for using packages to the objective function (Epsilon-Method). When a bidder would bid on a package, the payoff would be marginally higher than when bidding on the single items, but by only a very small number which does not affect the overall allocation. The MILP formulation is very similar to the one in \\autoref{subsection:meth-evaluation}, but this time only computes the best allocation for a single bidder. Also, the bidder's objective function was extended by the small \"bidding-on-HPB-package-bonus\", so that the selector MILP can take the existing package hierarchy into account. So for each super-additive package $ p \\in Hierarchy $ the objective function increases by a very small amount (in comparison to the sum of all the valuations) if the package was bid on. This leads to the following MILP formulation, where $ Hierarchy_{900}, Hierarchy_{1800} \\in Hierarchy $ are the respective subsets of packages in the 900 and 1800 MHz bands and $ Hierarchy_{900bonus} \\in Hierarchy_{900}, Hierarchy_{1800bonus} \\in Hierarchy_{1800} $ the respective subsets with bonus packages. Additionally, $ bonusV_{900} $ and $ bonusV_{1800} $ stand for the bidder's valuation of the bonuses, they correspond to the $ V_{MNO}^{900_3} $ and $ V_{MNO}^{1800_4} $ from \\autoref{subsection:value-model}  where $ MNO $ equals the respective bidder.\n\n\\begin{align*}\n\t& {\\text{maximize}}\n\t& & \\sum_{i \\in Items} ass_{i} * V_{i} + b_{900} * bonusV_{900}  + b_{1800} *bonusV_{1800} \\\\ \n\t& & & + \\varepsilon * \\Bigg[ \\sum_{p \\in Hierarchy_{900bonus}} m_p + \\sum_{p \\in Hierarchy_{1800bonus}} m_p \\Bigg] \\\\\n\t& \\text{subject to}\n\t& & \\sum_{i \\in Items_{900}}  ass_{i}  \\geq 3 *  b_{900} \\tag{\\textit{Bonus in 900 MHz}}  \\\\\n\t&&& \\sum_{i \\in Items_{1800}}  ass_{i}  \\geq 4 *  b_{1800} \\tag{\\textit{Bonus in 1800 MHz}} \\\\\n\t&&& \\sum_{i \\in Items_{900}}  ass_{i}  \\leq 3 \\tag{\\textit{Caps in 900 MHz}} \\\\\n\t&&& \\sum_{i \\in p} ass_i \\geq |p| * m_p \\quad \\forall p \\in Hierarchy_{900bonus} \\cup Hierarchy_{1800bonus} \\tag{\\textit{Preemptive bundle selection}} \\\\\n\t& \\text{where}\n\t& & V_{i}, bonusV_{900}, bonusV_{1800} \\in \\mathbb{N}, \\quad \\forall i \\in Items \\\\\n\t&&& ass_{i}, b_{900}, b_{1800} \\in \\{0,1\\} \\\\\n\t&&& m_p \\in \\{0,1\\}, \\quad \\forall p \\in Hierarchy\n\\end{align*}\\label{eq:selector-lp}\n\n\\section{Results}\nNow, with the project incorporating all the characteristics of the German Auction I was able to simulate the SMRA and HPB auctions. To research the sensitivity of efficiency and revenue towards the change of the set-up parameters I ran simulations iterating over sequences of the parameters $ \\beta_{900}, \\beta_{1800} $ and $ s_{DT}, s_{VOD} $ for both Hierarchies $ H_{competition}, H_{vm-prediction} $. Because of the high number of possible parameter combinations I will focus on the most important results below. To answer the question \\textit{\"How well does HPB perform in comparison to SMRA in the context of the German Auction?\"}, my analysis was mainly guided by the following questions:\n\n\\begin{itemize}\n\t\\item How sensitive are \\textit{efficiency} and \\textit{revenue} to \\textit{bonus valuations}?\n\t\\item What is the impact of the \\textit{HPB hierarchy} on both metrics?\n\t\\item How does \\textit{efficiency} and \\textit{revenue} change in relation to the environment of \\textit{bidder strengths}?\n\\end{itemize}\n\n\\subsection{Efficiency of the Formats}\\label{subsection:eff-formats}\nA \\textit{\"well performing\"} auction results in a (near-)optimal allocation of the bidding items to the bidders, meaning reaching a high efficiency is desired. As described in \\autoref{subsection:meth-evaluation}, efficiency is described as the ratio of the total welfare achieved in relation to the optimal welfare, which is calculated by running a sealed-bid model on the parameters. Therefore, the efficiency of the sealed-bid model is always equal to one and the other formats are judged on this basis.\n\n\\begin{figure}[h]\n\t\\centering\n\t\\includegraphics[scale=0.5]{eff_both_betas_moving.pdf}\n\t\\caption{Sensitivity of efficiency against $ \\beta_{900} = \\beta_{1800} $ in $ H_{competition} $} \\label{fig:eff-both-beta-mov}\n\t\n\t\\vspace*{\\floatsep}\n\t\n\t\\includegraphics[scale=0.5]{eff_both_betas_moving_VMP.pdf}\n\t\\caption{Sensitivity of efficiency against $ \\beta_{900} = \\beta_{1800} $ in $ H_{vm-prediction} $} \\label{fig:eff-both-beta-mov-vmp}\n\\end{figure}\n\n%\\paragraph{The influence of bonus valuations and hierarchies.}\nWhen running simulations iterating over the bonuses valuations, differences between both hierarchies became clear. \\autoref{fig:eff-both-beta-mov} shows the development of efficiency in relation to the bonuses valuations in the $ H_{competition} $ hierarchy and \\autoref{fig:eff-both-beta-mov-vmp} for $ H_{vm-prediction} $ respectively. Despite the fact that the efficiency levels of HPB showed to be more stable than SMRA, there were differences in the results between the two hierarchies. \nIn $ H_{competition} $ HPB showed to be superior to SMRA with $ HPB \\succ SMRA $. Also, HPB showed to be much more stable in resulting in a high efficiency level, which was near-optimal. In comparison, the overall allocation in SMRA seems to be more susceptible to the bonuses valuations, but still resulting in a high efficiency.\n\nFrom the data it seems that in HPB the valuation of the bonus inducing packages has little effect on the overall allocation and efficiency of the auction, making it a versatile tool to auction items with such characteristics. But the correct choice of the structure appears to be an important question. The findings indicate, that a competitive HPB hierarchy might help in reaching a better overall allocation in comparison SMRA. But this needs to be verified by further experiments (see \\autoref{chapter:conclusion}). \n\n%\\begin{figure}[h]\n%\t\\centering\n%\t\\includegraphics[scale=0.5]{eff_s_both_mov.pdf}\n%\t\\caption{Sensitivity of efficiency against bidder strength $ [s_{DT} = s_{VOD}] $} \\label{fig:eff-s-both}\n%\t\n%\t\\vspace*{\\floatsep}\n%\t\n%\t\\includegraphics[scale=0.5]{eff_s_singlemov.pdf}\n%\t\\caption{Sensitivity of efficiency with one stronger bidder $ s_{TEF} = s_{DT} = 1 $} \\label{fig:eff-s-single}\n%\\end{figure}\n%\n%\\paragraph{The competition environment.}\n%Following the findings from the previous section, I will focus the analysis of the competition environment on the $ H_{competition} $ as maximizing efficiency is a desired property of an auction.\n\n\\subsection{Revenue of the Formats}\nWhile reaching an optimal allocation is especially relevant to the participating bidders of an auction, maximizing revenue - to an appropriate level - mostly concerns the auctioneer. As revenue has no upper bound (like efficiency), there is no \\textit{perfect} revenue. To analyse the sensitivity of revenue I will at first have a look on the influence of bonus valuations and the hierarchies. Afterwards, I will establish an understanding of the competition environment of the auction formats, meaning the sensitivity towards the distribution of bidder strength.\n\n\\paragraph{The influence of bonus valuations and hierarchies.}\n\\begin{figure}[h]\n\t\\centering\n\t\\includegraphics[scale=0.5]{rev_both_beta_mov.pdf}\n\t\\caption{Sensitivity of revenue against $ \\beta_{900} = \\beta_{1800} $ in $ H_{competition} $} \\label{fig:rev-both-beta-mov}\n\t\n\t\\vspace*{\\floatsep}\n\t\n\t\\includegraphics[scale=0.5]{rev_both_beta_mov_VMP.pdf}\n\t\\caption{Sensitivity of revenue against $ \\beta_{900} = \\beta_{1800} $ in $ H_{vm-prediction} $} \\label{fig:rev-both-beta-mov-VMP}\n\\end{figure}\n\nThe general tendency is that $ \\beta_{900} \\text{ and } \\beta_{1800} $ have a positive impact on the development of revenues. With higher bonuses valuations, the overall revenue rises, as can be seen in \\autoref{fig:rev-both-beta-mov} and \\autoref{fig:hpb-hierarchy-vm-predict}. Interestingly, the effect of the different HPB hierarchies can be observed. \nWhen using $ H_{competition}  $ in most cases $ \\text{HPB} \\succ \\text{SMRA} $, where the HPB format produced slightly higher revenues in comparison to SMRA. This is contrary to the effect seen in \\autoref{fig:hpb-hierarchy-vm-predict}, where $ \\text{HPB} \\prec \\text{SMRA}$ and through beta-space HPB generated prominently lower revenues. Note that in $ H_{vm-prediction} $ two bonuses inducing pre-packaged bundles in the 900 MHz band exist, instead of only one in $ H_{competition}  $. This is an indicator, that HPB might help bidders to coordinate earlier in the auction if the respective hierarchies enable them to, but simultaneously  leading to lower revenue.  Whereas a more competitive HPB hierarchy tends to drive competition and thus revenue.\n\n\\paragraph{The competition environment.}\nIn this section, I will focus on the findings using the  $ H_{competition}  $ hierarchy as it produced the higher efficiency (see \\autoref{subsection:eff-formats}) and thus higher social welfare, which I argue to be an optimization goal of an auctioneer.\n\n\\begin{figure}[h]\n\t\\centering\n\t\\includegraphics[scale=0.6]{rev_hpb_comp_environment.pdf}\n\t\\caption{Competition environment of HPB with $ H_{competition} \\text{ \\& } [rev \\sim s_{DT}, s_{VOD}] $} \\label{fig:rev-hpb-comp-env}\n\\end{figure}\n\n\\autoref{fig:rev-hpb-comp-env} shows the competition environment of the HPB format in the simulation. Each tile shows the revenue generated according to the set-up of the bidder strengths. As can be seen from the figure, when all bidders have the same strength ($ s_{TEF}=s_{DT}=s_{VOD}=1 $) the highest revenues were generated due to the fact, that each bidder had to bid very close to its valuation. In an environment with one very strong bidder, revenues tend to yield much lower level as the strong bidder can much earlier outbid its competitors and thus decrease overall revenue.\nAs the revenues from both formats were very similar when using the competitive hierarchy (see \\autoref{fig:rev-both-beta-mov}), the competition environment also looks very similar. To compare both environments, \\autoref{fig:rev-diff-comp-env} depicts the difference between the revenues yielded in HPB and SMRA. The figure suggests, that there is no systematic relation in the superiority or inferiority of an auction format when dealing with different bidder strength environments.\n\n\\begin{figure}[b]\n\t\\centering\n\t\\includegraphics[scale=0.45]{rev_diff.pdf}\n\t\\caption{Competition environment of HPB vs. SMRA $ [rev_{HPB} - rev_{VOD} \\sim s_{DT}, s_{VOD}] $} \\label{fig:rev-diff-comp-env}\n\\end{figure}\n\nTo compare both formats further, \\autoref{fig:rev-s-both} and \\autoref{fig:rev-s-single} show the development of revenue in relation to two different bidder strength. As both depict that revenue decreases with increasing bidder strengths, \\autoref{fig:rev-s-both} shows that in less unequally distributed bidder environments $ \\text{HPB} \\succ \\text{SMRA} $, where HPB can yield slightly higher revenues even when bidder strengths are high. On the other hand, in an environment where one bidder is much stronger than the other participating bidders, this not only results in much lower revenues, but also slightly lower revenues by the HPB format in comparison to SMRA, even though the difference is marginal.\n  \n\n\\begin{figure}[h]\n\t\\centering\n\t\\includegraphics[scale=0.5]{rev_s_bothmov.pdf}\n\t\\caption{Sensitivity of revenue against bidder strength $ [s_{DT} = s_{VOD}] $} \\label{fig:rev-s-both}\n\t\n\t\\vspace*{\\floatsep}\n\t\n\t\\includegraphics[scale=0.5]{rev_s_singlemov.pdf}\n\t\\caption{Sensitivity of revenue with one stronger bidder $ [s_{TEF} = s_{DT} = 1] $} \\label{fig:rev-s-single}\n\\end{figure}\n\n\\subsection{Summary of the Results}\nThe following table summarises the findings of the simulations, where $ \\beta $ means $ \\beta_{900} = \\beta_{1800} $ and $ s $ means $ s_{DT} = s_{VOD} $.\n\n\\begin{table}[h]\n\t\\centering\n\\begin{tabular}{cc|l|l|}\n\t\\cline{3-4}\n\t\\multicolumn{1}{l}{}                       & \\multicolumn{1}{l|}{} & \\multicolumn{1}{c|}{\\textbf{$\\beta$}} & \\multicolumn{1}{c|}{\\textbf{$s$}} \\\\ \\hline\n\t\\multicolumn{1}{|c|}{\\multirow{2}{*}{\\textbf{Efficiency}}} & $ H_{competition} $                    & $  HPB \\succ SMRA $                         & $ HPB \\equiv SMRA $ after $ s= 1.5 \n\t$                      \\\\ \\cline{2-4} \n\t\\multicolumn{1}{|c|}{}                     & $ H_{vm-predict} $                 & $ HPB \\approx SMRA$                         & $ HPB \\prec SMRA $ when $ s > 1 $                      \\\\ \\hline\n\t\\multicolumn{1}{|c|}{\\multirow{2}{*}{\\textbf{Revenue}}} & $ H_{competition} $                    & $ HPB \\succ SMRA $                         & $ HPB \\succ SMRA $, rapidly decreasing                      \\\\ \\cline{2-4} \n\t\\multicolumn{1}{|c|}{}                     & $ H_{vm-predict} $                  & $ HPB \\prec SMRA $                         & $ HPB \\prec SMRA $                      \\\\ \\hline\n\\end{tabular}\n\t\\caption{Summary of the findings in the simulations}\\label{tbl:sim-results-summary}\n\\end{table}\n\nFrom the table it can be seen, that the simulations indicate that HPB might be helpful in enabling bidders to find more efficient overall allocations when choosing an appropriate bidding hierarchy. This improvement came with the reduction of overall revenue as bidder signalling improved. SMRA was superior when a less competitive HPB hierarchy was used, indicating that choosing a suitable hierarchy is key to the success of the auction. \n\n\n% BACKUP\n%\\begin{figure}[h]\n%\t\\centering\n%\t\\includegraphics[scale=0.5]{rev_smra_comp_environment.pdf}\n%\t\\caption{Competition environment of SMRA $ [rev \\sim s_{DT}, s_{VOD}] $} \\label{fig:rev-smra-comp-env}\n%\t\n%\t\\vspace*{\\floatsep}\n%\t\n%\t\\includegraphics[scale=0.5]{rev_hpb_comp_environment.pdf}\n%\t\\caption{Competition environment of HPB $ [rev \\sim s_{DT}, s_{VOD}] $} \\label{fig:rev-hpb-comp-env}\n%\\end{figure}\n\n%\\begin{figure}[h]\n%\t\\centering\n%\t\\includegraphics[scale=0.5]{rev_b900mov.pdf}\n%\t\\caption{Sensitivity of revenue against $ \\beta_{900} $ with $ \\beta_{1800} = 1$} \\label{fig:rev-b900-mov}\n%\t\n%\t\\vspace*{\\floatsep}\n%\t\n%\t\\includegraphics[scale=0.5]{rev_b1800mov.pdf}\n%\t\\caption{Sensitivity of revenue against $ \\beta_{1800} $ with $ \\beta_{900} = 1$} \\label{fig:rev-b1800-mov}\n%\t\n%\t\\vspace*{\\floatsep}\n%\t\n%\t\\includegraphics[scale=0.5]{rev_both_beta_mov.pdf}\n%\t\\caption{Sensitivity of revenue against $ \\beta_{1800} = \\beta_{900} $} \\label{fig:rev-both-beta-mov}\n%\\end{figure}\n\n%\\begin{figure}[h]\n%\t\\centering\n%\t\\includegraphics[scale=0.5]{rev_hpb_comp_environment.pdf}\n%\t\\caption{Competition environment of HPB $ [rev \\sim s_{DT}, s_{VOD}] $} \\label{fig:rev-hpb-comp-env}\n%\t\n%\t\\vspace*{\\floatsep}\n%\t\n%\t\\includegraphics[scale=0.5]{rev_diff.pdf}\n%\t\\caption{Competition environment of HPB vs. SMRA $ [rev_{HPB} - rev_{VOD} \\sim s_{DT}, s_{VOD}] $} \\label{fig:rev-diff-comp-env}\n%\\end{figure}\n\n%The impact of the betas are different, because with the caps in the 900 MHz band\n%at $ \\beta_{1800} = 3 $ are the bonuses that high that it is feasible to buy cheapest four items instead of package (?) and then get the bonus, at $ \\beta_{1800} = 2.5 $ it doesnt pay off to do that \n", "meta": {"hexsha": "267d5e888774447df3b050167015bc1bb84e2c4d", "size": 26828, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/chapters/05_simulation.tex", "max_stars_repo_name": "timbrgr/auction-simulation-SMRA-HPB-BA-thesis", "max_stars_repo_head_hexsha": "4b34b0ab019ebf969b91dc2f8ee755a1cc8aba02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thesis/chapters/05_simulation.tex", "max_issues_repo_name": "timbrgr/auction-simulation-SMRA-HPB-BA-thesis", "max_issues_repo_head_hexsha": "4b34b0ab019ebf969b91dc2f8ee755a1cc8aba02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis/chapters/05_simulation.tex", "max_forks_repo_name": "timbrgr/auction-simulation-SMRA-HPB-BA-thesis", "max_forks_repo_head_hexsha": "4b34b0ab019ebf969b91dc2f8ee755a1cc8aba02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 101.2377358491, "max_line_length": 1745, "alphanum_fraction": 0.7404577307, "num_tokens": 6924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.32679493745252003}}
{"text": "\\documentclass{article}\n\n\\usepackage{amsthm}\n\\usepackage{amssymb}\n\\usepackage{bussproofs}\n\\usepackage{pstricks,pst-node}\n\\usepackage{url}\n\n\\newtheorem{theorem}{Theorem}[section]\n\\newtheorem{lemma}[theorem]{Lemma}\n\\newtheorem{corollary}[theorem]{Corollary}\n\n\\title{Qeditas: A Formal Library as a Bitcoin Spin-Off}\n\n\\author{Bill White\\footnote{\\mbox{Email:~billwhite@protonmail.com} \\mbox{BTC: 12pbhpqEg7cjaCLLcvdhJhBWGUQWkRK3zS}}}\n\n\\date{{Draft of \\today}}\n\n\\def\\cB{\\mathcal{B}}\n\\def\\cH{\\mathcal{H}}\n\\def\\cM{\\mathcal{M}}\n\\def\\cC{\\mathcal{C}}\n\\def\\Addr{\\mathcal{A}}\n\\def\\asset{\\mathfrak{A}}\n\\def\\Val{\\mathcal{V}}\n\\def\\coqtt{\\tt}\n\\def\\hash#1{\\ulcorner #1 \\urcorner}\n\\def\\hasho#1{\\ulcorner #1 \\urcorner^{\\bot}}\n\\def\\hashroot#1{\\mathbf{R} #1}\n\\def\\outsum#1{\\overleftarrow{\\Sigma}(#1)}\n\\def\\insum{\\vec{\\Sigma}}\n\\def\\trans#1#2{[#2]^{#1}}\n\\def\\myapprox{\\blacktriangleright}\n\\def\\subqh{\\sqsubseteq}\n\\def\\subqm{\\sqsubseteq}\n\\def\\subqc{\\sqsubseteq}\n\\def\\lub{\\sqcup}\n\\def\\normalize#1{\\langle #1\\rangle}\n\n\\begin{document}\n\n\\maketitle\n\n\\begin{abstract}\nFormalization of mathematical theories is a time consuming process\nfor which there is currently little reward. We describe how block chain\ntechnology can be used to support the formalization of mathematics by\nencouraging and rewarding useful work while discouraging repeating the\nwork of others. The block chain will contain a record of definitions made\nand propositions proven. In addition the block chain can be used as a\nregistry to record the first participant to make a definition or prove a\ntheorem as the owner of the object or proposition as intellectual property.\nFuture users may be required to buy rights to make use of the object or\nproposition. Purchasing of these rights can be avoided by repeating the\ncontent, but at the expense of larger documents and increased fees to the\ncreators of blocks.\n\\end{abstract}\n\n\\section{Introduction}\n\nQeditas\nis a project to apply block chain technology to\nsupport the construction of a library of formalized mathematics.\nMotivations for building such a library\nwere spelled out in an anonymously published document in\n1994 with the title The QED Manifesto~\\cite{QED}.\nIn order to construct such a library there must be\na clear record of which definitions have been made\nand which theorems have been proven.\nIn addition the record may include unproven conjectures\nof interest.\nQeditas will use a block chain to secure such a record in a decentralized manner.\nIn addition a block chain can be used to reward those who\nmake useful definitions and prove useful theorems.\n\nBitcoin~\\cite{Nakamoto2008} introduced the notion of a block chain\nto have a secure distributed record of currency transactions.\nThe Ethereum project~\\cite{WoodEtheriumYellow} uses a block chain\nto provide a distributed platform for computation.\nQeditas will use a block chain to provide a distributed platform for deduction.\nQeditas will also include an internal currency whose initial\ndistribution will be based on a snapshot of the Bitcoin block chain.\nIn other words Qeditas will be a Bitcoin spin-off~\\cite{Spinoff}.\n\nThe task of building a formal mathematical library is enormous.\nWiedijk estimated the work to formalize the mathematics that mathematicians\n``take for granted'' as requiring 140 man-years~\\cite{WiedijkEstimating}.\nAchieving such a goal will require the work of many independent people.\nThe system in which the formalization takes place must allow people\nsubmit definitions, conjectures and theorems (with proofs)\nindependently. Their contributions to the library should be appropriately\nrewarded and other users should be encouraged to build on previous work.\n\nFor the most part the work of formally proving theorems\nhas been limited to\ngraduate students who formalize certain areas of mathematics or computer science\nas part of obtaining their degrees.\nThis is sometimes done as part of a larger project.\nOne example of such a large project is the recently completed Flyspeck project~\\cite{Flyspeck2015}\nto formalize Hales' proof of the Kepler conjecture.\nGonthier's work formalizing\ntheorems about the classification of finite simple groups~\\cite{Gonthier2013}\nprovides another prominent example.\n\nIn the academic world {\\em{wealth}} is largely measured in publications,\nand academics who create formalizations\nreceive their reward in the form of the resulting publications.\nOutside of academia there is currently little reward for doing such work.\nTo some degree this is surprising since theorem proving can\nbe used to ensure properties of programs and protocols.\n\nIn Qeditas there will be two ways to be rewarded.\n\\begin{enumerate}\n\\item Users will be able to place bounties on conjectures\nand the bounties can be collected by the publisher\nof the first document resolving the conjecture.\n\\item If a user is the first to define an object or prove a proposition,\nthen the user will be able to claim ownership of the object or proposition.\nIn order for future users to make use of the definition or theorem without repeating the\ncontent,\nthey may (at the discretion of the owner) be required to purchase corresponding rights.\n\\end{enumerate}\nThe second point means that mathematical objects and propositions\nwill become essentially a form of {\\em{decentralized intellectual property}}\n(within the system) and the purchasing and usage of rights will be enforced by the network.\nThis is similar to the requirement that academics include appropriate references\nto previous work in their publications.\nNote, however, that in the current academic world many publications\nhave copyright restrictions and are often behind paywalls.\nIn contrast all documents published in the Qeditas block chain\nwill be freely available.\n\nIn this white paper we will give a high level description of the Qeditas project.\nThe code is still being written and details are subject to change.\n\nIn Section~\\ref{sec:currency} we describe the Qeditas currency units\nincluding the plan for an initial distribution taken from a snapshot of\nthe Bitcoin block chain. The remaining currency units will be given as block\nrewards.\nThe current plan is to use\na lightweight block chain~\\cite{Bruce2014,White2015b} so that\neach member of the network need not permanently store, for example, every formal document.\nThe consensus mechanism will likely be proof of stake~\\cite{ProofOfStakeDefinite} in some combination with proof of\nstorage~\\cite{MillerJSPK14}.\nThese choices are discussed in Section~\\ref{sec:ledger}.\nWe use a small\nexample to show how formal documents can be specified and published into the\nblock chain\nin Section~\\ref{sec:docs}.\nIn Section~\\ref{sec:rights} we extend the small example to demonstrate how ownership of objects and propositions can be recorded into the block\nchain.\nIn Section~\\ref{sec:bounties} we describe how bounties can be placed on\nconjectures and later collected by someone who proves the conjecture (or possibly its negation).\nCurrency units, ownership, rights, and bounties can generally be described as {\\em{assets}}\nwhich are held at addresses. This is described in Section~\\ref{sec:assets}.\nAll of the concepts above are generic and could be instantiated to many\ndifferent theorem provers. In Section~\\ref{sec:provers}\nwe list some pros and cons of a few theorem provers which could be used as the underlying engine\nfor Qeditas, leaving the definite choice for later.\n\n\\section{Currency}\\label{sec:currency}\n\nOne of the oft-repeated complaints about Bitcoin is\nthat the same name was given to both the network and the currency units.\nThis is remedied in print by writing ``Bitcoin'' for the network\nand ``bitcoin'' for the currency unit. Actually, the basic currency unit\nis called a ``satoshi'' and a bitcoin consists of 100 million satoshis.\nIt is also possible that subdivisions of satoshis will be included at some\npoint in the future.\n\nAs the value of bitcoin has increased, community members have engaged in long debates about\nthe possible names to give to units between satoshis and bitcoins.\nIn an attempt to preempt such debates in Qeditas, we give names for the units\nhere. We do not use the term ``qeditas'' for any of the units.\nInstead we derive the names from the names of some mathematicians who have contributed\nto the understanding of the foundations of mathematics.\nThe names are listed in Table~\\ref{tab:currencyunits}\nand the pronounciations are intended to be the same as the\npronounciations of the names of the corresponding mathematicians.\nThe names are given in full form (both singular and plural)\nand in a short abbreviated form (both singular and plural).\nFor the remainder of the paper we will use the abbreviated names.\n\n\\begin{table}\n\\begin{center}\n{\\scriptsize{\n\\begin{tabular}{llll}\n& & {\\scriptsize{Basic Unit}} & {\\scriptsize{Corresponding}} \\\\\n{\\scriptsize{Full Name}} & {\\scriptsize{Short Name}} & {\\scriptsize{Factor}} & {\\scriptsize{Bitcoin Units}} \\\\ \\hline\nCantor (Cantors) & cant (cants) & $1$ & 0.001 satoshis \\\\\nFrege (Freges) & freg (fregs) & $10^2$ & 0.1 satoshis \\\\\nChurch (Churches) & church (churches) & $10^5$ & 1 microbit \\\\\nZermelo (Zermelos) & zerm (zerms) & $10^8$ & 1 millibit \\\\\nFraenkel (Fraenkels) & fraenk (fraenks) & $10^{11}$ & 1 bitcoin \\\\\nGrothendieck (Grothendiecks) & groth (groths) & $10^{14}$ & 1000 bitcoins\n\\end{tabular}\n}}\n\\end{center}\n\\caption{Qeditas currency units}\\label{tab:currencyunits}\n\\end{table}\n\nThe intention is that one fraenk corresponds directly to one bitcoin\n(in terms of units, not value),\nand so the number of fraenks in Qeditas is capped at 21 million.\nThe first (approximately) 14 million ($\\frac{2}{3}$) will be distributed by taking a snapshot of the\nfirst 350,000 blocks of the Bitcoin block chain.\\footnote{To be precise, the snapshot will include all pay-to-public-key-hash addresses, including those derived from pay-to-public-key outputs. The snapshot will also include native multisig outputs. In addition, all pay-to-script-hash outputs will be included, but we cannot guarantee the Qeditas script interpreter is 100\\% compatible with the script interpreter of Bitcoin. A preliminary script interpreter has been written and tested on already spent pay-to-script-hash outputs in the Bitcoin block chain and it succeeds in over 99.8\\% of cases.}\nThe remaining 7 million will be distributed as block rewards with\nthe same schedule Bitcoin is using (starting from block 350,000). That is, the block reward will\nbegin with 25 fraenks for the first 70,000 blocks\nand will then halve to 12.5 fraenks. After block 70,000\nthe block reward will halve each 210,000 blocks.\nA block time of 10 minutes will be targetted, so that the number of fraenks\nshould always be approximately the same as the number of bitcoins.\nNote that since there are finer units in Qeditas than Bitcoin,\nvery small Qeditas block rewards will continue after the Bitcoin block\nrewards have stopped.\n\nArguments in favor of such a snapshot distribution\ncan be found in the ``spin-off'' thread begun by Peter R~\\cite{Spinoff}.\\footnote{While the cited thread contains the primary discussion on the topic, the idea seems to be older. See for example the earlier thread begun by go1111111~\\cite{PreSpinoff}.}\nOne can view the Bitcoin block chain as recording an efficient distribution\nof wealth in a voluntary environment.\nBitcoin was sufficiently well-known by 2015\nthat each individual had a chance to make an independent judgement about the idea.\nConsequently each person at that point held the amount of bitcoins that reflected their own judgment.\n\nHaving $\\frac{2}{3}$ of the total Qeditas currency supply in the initial distribution\nmay lead to an unhealthy level of uncertainty. It is likely that a significant percentage of the initial\ndistribution will never be claimed, either due to lack of interest or due to lost private keys.\nOne solution to this problem (also discussed in the spin-off thread~\\cite{Spinoff})\nis to have a {\\em{claim window}}. That is, there would be a block height after which\ncurrency units from the initial distribution could no longer be claimed.\nAn argument in favor of such a claim window is that it removes the uncertainty about the long-term supply.\nAn argument against having such a claim window is that it is redistributive and punishes bitcoin holders\nwho did not become aware of the spin-off in time.\n\nThe current plan in Qeditas is to have an initial claim window of roughly 5 years.\nDuring these 5 years, for each satoshi the bitcoin address had, the controller of the corresponding\nprivate key will be able to claim 1000 cants from the initial Qeditas distribution, held at the corresponding\nQeditas address.\nAfter these 5 years, there will be new claim windows coinciding with the halving of the block rewards.\nIn particular, each time the block reward halves (roughly every 4 years) the value of the \nunclaimed initial distribution will also halve. For example, a bitcoin address that held 1 satoshi\nat the time of the snapshot, would only be able to claim 500 cants during this second claim window.\nDuring the third claim window (roughly years 9 through 13) the corresponding initial distribution (if still unclaimed)\nwould be worth 250 cants.\nAs a consequence, even a claim corresponding to a single satoshi in the snapshot will\nbe able to be claimed for at least one cant for roughly the first 40 years of the network.\\footnote{Trent Russell \nsuggested this idea for halving the value of unclaimed currency from the initial distribution\nafter noting problems caused by similar issues in the case of the Clams cryptocurrency.}\n\n\\section{Lightweight Ledger}\\label{sec:ledger}\n\nQeditas will use a lightweight ledger in the sense described in~\\cite{White2015b}.\nThe idea is similar to the mini-blockchain scheme\nimplemented in the cryptocurrency Cryptonite~\\cite{Bruce2014}\nas well as to the intended use of Merkle-Patricia trees in Ethereum~\\cite{WoodEtheriumYellow}.\nThe state of the ledger will be represented by a compact form of a trie\ncombined with a Merkle structure (a Merkle-Patricia tree up to some details).\nThe full trie allows one to look up the assets held by an address.\nThese assets may include currency units but may also include formal documents,\nownership information, rights and bounties.\n\nWe distinguish between assets {\\em{held}} by an address and assets being {\\em{controlled}}\nby addresses. An asset $a$ is {\\em{held}} by an address $\\alpha$ if $a$\ncan be found in the trie at address $\\alpha$. The asset itself contains {\\em{obligations}}\n(see~\\cite{White2015b}) indicating who can spend the asset. The obligations allow\nfor an address to hold an asset without being able to spend the asset.\n\nThe two most popular kinds of consensus mechanisms used by cryptocurrencies are proof of work and proof of stake. Proof of work (PoW) was first\ndescribed by Back~\\cite{Back2002}\nand is used by Bitcoin.\nProof of stake (PoS) was introduced by King and Nadal~\\cite{KingNadal2012}, and first implemented\n(as a proof of work/proof of stake hybrid) in Peercoin.\nAnother consensus mechanism, proof of retrievability\n(PoR), described by Miller, et. al., is designed to support data preservation~\\cite{MillerJSPK14}.\n\nSince Qeditas is intended to support a library, some form of PoR seems to be\na good choice. On the other hand, the amount of data being secured by Qeditas\nis likely to be relatively small (especially at first) and it is not clear that PoR is\nappropriate in this case. Conceivably, PoR could be used to ensure storage of\nthe syntactic terms which hash to give addresses of objects and possibly storage\nof proofs of theorems. While the consensus mechanism is not yet fixed, it is\nlikely to be some combination of PoS and PoR.\\footnote{The current design of Qeditas does not make use of erasure codes when storing data, and so it would likely make use of ``Proof of Storage'' instead of PoR.}\n\nThe original PoS mechanism used a notion of coin age.\nWhen coin age is coupled with a block reward proportional to the stake,\nthe incentive to constantly stake (and thereby support the security of the network) is decreased.\nThe Qeditas network will not suffer from this problem since it will have a fixed\nblock reward independent of the stake of the forger of the block. This idea has\nbeen described earlier as ``proof of stake definite''~\\cite{ProofOfStakeDefinite}. Qeditas may use a notion\nof coin age, but since there is a fixed block reward potential stakers maximize\ntheir reward by keeping their nodes online as much as possible.\n\nThe currency units held by an address $\\alpha$ are part of the stake of that address.\nAccordingly, if an address holds some currency units, then\nthe private key for $\\alpha$\nwill be able to forge new blocks in the block chain.\nIn order to check $\\alpha$ holds the alleged stake it is sufficient\nto look at an approximation of the current state showing the\nstake is among the assets held by $\\alpha$. The approximation\nneed not include information about assets held by any other address.\nMore details can be found in~\\cite{White2015b}.\n\nNote that if $\\beta$ controls some currency units, then $\\beta$ can allow the asset to be\nheld by $\\alpha$ so that $\\alpha$ can use them to forge blocks. \nThis would allow a staker to keep the keys for spending offline while having the staking keys online.\nIt would also allow for a non-staker (controlling $\\beta$) to ``loan'' their currency units to a staker (controlling $\\alpha$).\nIn return $\\alpha$\nmight pay some of the block rewards back to $\\beta$.\nSince $\\beta$ still controls the asset, the owner of the private key for $\\beta$\ncan spend the asset even though it is held by $\\alpha$.\n(Though the obligation may contain a block height before which the asset cannot be spent.)\n\nThere are strong arguments that PoS cannot provide the same level\nof distributed consensus as PoW~\\cite{Poelstra2014}.\nOne reason is that if someone had stake in the currency at one time,\nthen this previously owned stake could, in principle, be used to create\na fork of the block chain starting from that earlier time.\nIn practice PoS cryptocurrency can avoid a long range attack\nof this kind by preventing long reorganizations.\nFor example, the cryptocurrency Nxt~\\cite{Nxt} disallows reorganization beyond\n720 blocks. The cost of this solution is that if someone new enters the network\nthey may need a way, outside the network itself, to determine the ``correct'' chain.\nButerin calls such a criteria ``weakly subjective''\nin contrast to the ``objective'' criteria used by\nBitcoin~\\cite{Buterin2014}.\nShort range attacks are still possible, though simulations\nby Consensus Research show them to be unlikely\neven in the face of participants signing competing chains~\\cite{Chepurnoy2014d,multistrategy,ConsensusResearch}.\n\nThe initial distribution may provide a protection against certain\nkinds of attacks.\nIn the first place, it would be very difficult\nfor an individual or group to obtain 50\\% of the currency units since this would\nrequire obtaining the private keys corresponding to at least 3.5 million bitcoins\nas of block height 350,000. On the other hand, a 51\\% attack on a proof of stake\ncoin only requires having more than 50\\% of the {\\emph{actively staking}} coins.\nThere is a threat that if a single wealthy bitcoin holder decided to attack\nthe Qeditas network before many others are participating, the network could\nbe strangled in its cradle.\nThe economic rationality of such an attack is questionable, since they would be doing work to\ndestroy a block chain that would add to their wealth if left alone. Nevertheless,\nthe threat exists.\nThe hope is that the wide initial distribution will make it likely\nthat for each participant with a certain amount of the distribution\nthere will be others with a similar amount.\n\n\\section{Documents}\\label{sec:docs}\n\nSome examples of formal mathematical libraries include\nthe Mizar Mathematical Library~\\cite{RudnickiTrybulec2001},\nthe Archive of Formal Proofs supported by\nIsabelle-HOL~\\cite{Nipkow-Paulson-Wenzel:2002}\nand the Mathematical Components library of ssreflect~\\cite{Gonthier2010}.\nIn each case the library is made up of documents.\nEach of these documents extends the mathematical content of the library\nby including mathematical items, mainly definitions and theorems.\nThe organization of these libraries tends to be handled by experts who have\na familiarity with the current contents of the library.\nThese experts can determine if the content is new and whether the document\nconforms to the expectations of the library.\n\nSince Qeditas will be decentralized, there will be no ``expert'' to filter out\nsubmissions. The protocol itself must ensure the submission meets the necessary\ncriteria. In this section we walk through a small example of how a document\nmight be created and published.\n\nSuppose a user creates a document {\\tt{Relns}} which\ndefines the converse of a relation, defines when a binary relation is symmetric\nand proves a theorem that the converse of a relation is symmetric if the relation is symmetric.\nThe particular syntax and format of such a document depends on the system\nused to check the proofs. For now, we can remain system-independent by\nusing informal mathematical language.\nThe mathematical content of {\\tt{Relns}} is shown in Figure~\\ref{fig:docrelns}.\n\n\\begin{figure}\n\\begin{center}\n\\fbox{\\parbox{11.5cm}{\n{\\bf{Definition 1.}} Let $R$ be a binary relation. The binary relation $R^{-1}$ is\ndefined such that $R^{-1}(x,y)$ holds if $R(x,y)$ holds.\n\n{\\bf{Definition 2.}} A binary relation $R$ is {\\em{symmetric}} if $R(y,x)$ holds whenever $R(x,y)$ holds.\n\n{\\bf{Theorem 1.}} Let $R$ be a binary relation. If $R$ is symmetric, then $R^{-1}$ is also symmetric.\n\\begin{proof} Assume $R$ is symmetric and $R^{-1}(x,y)$ holds. By Definition 1, $R(y,x)$ holds. By symmetry of $R$ and Definition 2, $R(x,y)$ holds. By the Definition 1 again, $R^{-1}(y,x)$ holds.\n\\end{proof}\n}}\n\\end{center}\n\\caption{Mathematical Content of {\\tt{Relns}}}\n\\label{fig:docrelns}\n\\end{figure}\n\nNote that the document contains a proof of the theorem. There are a variety\nof representations for proofs, but a fundamental requirement is that\nit must be easy for a proof checker to determine whether or not the proof is correct.\nWe return to this issue in Section~\\ref{sec:provers}.\n\nThe first criteria for the document to be accepted by the network for publication\nis that it is formally correct. This ensures that only correct definitions and\ntheorems will be included in the library.\nThere are a number of other criteria which will be discussed in the remainder of the paper.\nFor this section, let us consider how plagiarism is avoided.\n\nSuppose the author of {\\tt{Relns}}, Alice, controls an address $\\alpha$.\nSuppose {\\tt{Relns}} is signed with the address $\\alpha$\nand submitted to the Qeditas network for publication.\nAnother network participant, Bob, controlling an address $\\beta$,\ncould easily remove Alice's signature and replace it with his own.\nIf Bob's version were confirmed before Alice's, then\nAlice would lose credit for having done the work.\n\nA solution to this problem is to enforce the following protocol.\n\\begin{enumerate}\n\\item The author chooses a salt and includes it in the document.\n\\item The author computes a hash of the signed salted document and publishes it as an {\\em{intention}}.\n\\item After the intention is sufficiently confirmed, the author releases the signed salted document to be published.\n\\end{enumerate}\nThe network will only allow a document to be confirmed if it has a sufficiently confirmed intention.\nNow for an attacker to take credit for another document, the attacker would\nneed to publish a new intention, wait for enough confirmations, and then\nattempt to publish the plagiarized document all before the original author's document is\nconfirmed.\n\nPublishing an intention and a document will likely require fees,\nand the fees will likely depend on the size of the document.\nThis gives the first in-system use of the currency.\nWe will see other in-system uses of the currency in the next sections.\n\n\\section{Ownership and Rights}\\label{sec:rights}\n\nIn this section we consider the notions of ownership of objects and propositions\nand rights of use.\nWe use the example document Relns with the contents\ndescribed in Figure~\\ref{fig:docrelns} to guide the discussion.\n\nIn a document a formal definition declares a certain name to be an abbreviation for a certain syntactic term. Likewise, a formal theorem declares a name\nto be a reference to the fact that a certain syntactic term (representing a proposition) is provable (with the proof following the declaration). These syntactic\nterms can be hashed in order to assign a unique address corresponding for each\nterm.\n\nConsider the first definition in {\\tt{Relns}}.\nThis defines an operation $-^{-1}$ on relations.\nAs a $\\lambda$-term~\\cite{Church40} the definition can be written as\n$$\\lambda R\\lambda x\\lambda y.R(y,x).$$\nThis definition can then be converted to a nameless (de Bruijn) representation~\\cite{deBruijn72}\n$$\\lambda \\_\\lambda \\_\\lambda \\_.2(0,1).$$\nThis nameless version can be serialized and hashed to given an address.\nLet $\\delta_1$ be the address corresponding to the first definition.\nLikewise, we can compute an address $\\delta_2$ corresponding to the second definition\nand $\\delta_3$ corresponding to the proposition of the theorem.\n\nSuppose Alice (the author of {\\tt{Relns}})\nis the first to make both of the definitions, the first to mention the proposition\nof the theorem and the first to prove the theorem.\nIn this case $\\alpha$ (the address of Alice)\nwill be marked as the owner of the objects $\\delta_1$ and $\\delta_2$\nand the owner of both the object and proposition $\\delta_3$\nwhen the document is published (and confirmed).\nThis ownership information is held as a kind of asset at the addresses $\\delta_1$, $\\delta_2$\nand $\\delta_3$\nand will include a {\\em{royalty}} requirement.\nThe royalty requirement is used to determine under\nwhat conditions others may use the object or proposition.\nThe owner may either allow everyone to freely use the item,\nmay allow no one to use the item,\nor may allow others to purchase rights for each use.\nOwnership can also be transfered to a different address using the private key for $\\alpha$.\nThe royalty information can be changed by the current owner.\n\nLet us suppose that Alice publishes the document {\\tt{Relns}}\nand assigns ownership of $\\delta_1$, $\\delta_2$ and $\\delta_3$ to her address $\\alpha$.\nSuppose Alice allows $\\delta_1$ to be freely used,\ndoes not allow the use of $\\delta_2$ at all,\nand requires a payment of 3 zerms for each right to use $\\delta_3$.\n\nNow suppose Bob, the controller of address $\\beta$, wants to author a document\nextending Alice's work by proving that $(R^{-1})^{-1}$ is symmetric\nif $R$ is symmetric.\nBob has a number of options for doing this.\nWe will discuss three options as documents {\\tt{Relns2v1}}, {\\tt{Relns2v2}} and  {\\tt{Relns2v3}}.\n\n\\begin{figure}\n\\begin{center}\n\\fbox{\\parbox{11.5cm}{\n{\\bf{Definition 1.}} Let $R$ be a binary relation. The binary relation $R^{-1}$ is\ndefined such that $R^{-1}(x,y)$ holds if $R(x,y)$ holds.\n\n{\\bf{Definition 2.}} A binary relation $R$ is {\\em{symmetric}} if $R(y,x)$ holds whenever $R(x,y)$ holds.\n\n{\\bf{Theorem 1.}} Let $R$ be a binary relation. If $R$ is symmetric, then $R^{-1}$ is also symmetric.\n\\begin{proof} Assume $R$ is symmetric and $R^{-1}(x,y)$ holds. By Definition 1, $R(y,x)$ holds. By symmetry of $R$ and Definition 2, $R(x,y)$ holds. By the Definition 1 again, $R^{-1}(y,x)$ holds.\n\\end{proof}\n\n{\\bf{Theorem 2.}} Let $R$ be a binary relation. If $R$ is symmetric, then $(R^{-1})^{-1}$ is also symmetric.\n\\begin{proof} Assume $R$ is symmetric. Applying Theorem 1 with $R$ we know $R^{-1}$ is symmetric. Applying Theorem 1 again, this time with $R^{-1}$, we know $(R^{-1})^{-1}$ is symmetric.\n\\end{proof}\n}}\n\\end{center}\n\\caption{Mathematical Content of {\\tt{Relns2v1}}}\n\\label{fig:docrelns2v1}\n\\end{figure}\nIn {\\tt{Relns2v1}} (see Figure~\\ref{fig:docrelns2v1}) Bob copies Alice's work and adds one new theorem.\nThe new theorem (Theorem 2) is easily proven using Alice's theorem twice.\nTheorem 2 is new and will have a corresponding address $\\delta_4$ which currently has no owner.\n\nBob can publish {\\tt{Relns2v1}} signed using the private key for his address $\\beta$.\nThe first three items already have an owner, Alice, and she will remain the owner of these\nthree items. The address $\\beta$ for Bob will be assigned the owner of the new item $\\delta_4$.\n\nSimply repeating Alice's work is not the best way to import previous work.\nIn this case as in many others it would be a superior choice to only record the\nparts of the work that are needed.\nFor this reason suppose Bob is unsatisfied and does not publish {\\tt{Relns2v1}}.\nBob could examine his proof of Theorem 2 and recognize that he did not\nneed the actual definitions of $-^{-1}$ or the property of being symmetric, but only needed\nthe fact that the proposition of Theorem 1 has been proven.\nArmed with this information Bob can create {\\tt{Relns2v2}} (see Figure~\\ref{fig:docrelns2v2})\nby omitting the definitions and first proof.\n\n\\begin{figure}\n\\begin{center}\n\\fbox{\\parbox{11.5cm}{\n{\\bf{Object 1.}} $(-)^{-1}$ is the object with address $\\delta_1$.\n\n{\\bf{Object 2.}} {\\em{symmetric}} is the object with address $\\delta_2$.\n\n{\\bf{Known 1.}} Let $R$ be a binary relation. If $R$ is symmetric, then $R^{-1}$ is also symmetric.\n\n{\\bf{Theorem 2.}} Let $R$ be a binary relation. If $R$ is symmetric, then $(R^{-1})^{-1}$ is also symmetric.\n\\begin{proof} Assume $R$ is symmetric. Applying Known 1 with $R$ we know $R^{-1}$ is symmetric. Applying Known 1 again, this time with $R^{-1}$, we know $(R^{-1})^{-1}$ is symmetric.\n\\end{proof}\n}}\n\\end{center}\n\\caption{Mathematical Content of {\\tt{Relns2v2}}}\n\\label{fig:docrelns2v2}\n\\end{figure}\n\nThe correctness of the proof of Theorem 2 in {\\tt{Relns2v2}} can still be checked.\nMore information is needed to ensure that there really are objects with addresses $\\delta_1$\nand $\\delta_2$. This can be verified by looking up $\\delta_1$ and $\\delta_2$ in the trie.\nAssuming they are previously defined objects, the information will be there.\nFurthermore, the system must verify that the proposition in Known 1 has been previously proven.\nThis can be verified by computing the address corresponding to the proposition, $\\delta_3$,\nand then looking up the relevant information in the trie at this address.\n\nThe document {\\tt{Relns2v2}} is shorter than {\\tt{Relns2v1}}.\nConsequently it should be less expensive (in terms of fees) to publish it.\nIn general fees are expected to encourage succinctness.\n\nHowever, the network will not allow Bob to publish {\\tt{Relns2v2}}.\nIn addition to checking $\\delta_1$ and $\\delta_2$ are objects and $\\delta_3$ is a known proposition,\nthe permission to make use of them must be determined.\nAlice has allowed free use of $\\delta_1$, but Alice has not allowed use of $\\delta_2$ at all.\nIn addition, Alice requires the purchase of rights to use $\\delta_3$.\nAt the moment, Bob has no such rights.\n\nArmed with this further information, Bob purchases the rights to use $\\delta_3$ twice.\nHe can do this by creating a transaction\nwith outputs\nsending $6$ zerms to $\\alpha$ (the owner of $\\delta_3$) and\nsending $2$ {\\em{$\\delta_3$-rights}} to himself.\nNote that Alice need not be involved in this transaction.\nIn the future Alice may change the royalty requirements for $\\delta_3$,\nbut this will not affect Bob's right to use $\\delta_3$ twice.\nPurchasing such rights are the second in-system use of the currency.\n\nBob then creates a third document {\\tt{Relns2v3}} (see Figure~\\ref{fig:docrelns2v3}).\nIn this case Bob avoids the fact that Alice does not allow use of $\\delta_2$ by\nsimply repeating the work of defining the property of being symmetric.\nBob can then publish an intention to publish {\\tt{Relns2v3}}\nand later publish {\\tt{Relns2v3}}.\nThe transaction publishing {\\tt{Relns2v3}}\nwill spend the two rights purchased above, consuming them.\n\n\\begin{figure}\n\\begin{center}\n\\fbox{\\parbox{11.5cm}{\n{\\bf{Object 1.}} $(-)^{-1}$ is the object with address $\\delta_1$.\n\n{\\bf{Definition 2.}} A binary relation $R$ is {\\em{symmetric}} if $R(y,x)$ holds whenever $R(x,y)$ holds.\n\n{\\bf{Known 1.}} Let $R$ be a binary relation. If $R$ is symmetric, then $R^{-1}$ is also symmetric.\n\n{\\bf{Theorem 2.}} Let $R$ be a binary relation. If $R$ is symmetric, then $(R^{-1})^{-1}$ is also symmetric.\n\\begin{proof} Assume $R$ is symmetric. Applying Known 1 with $R$ we know $R^{-1}$ is symmetric. Applying Known 1 again, this time with $R^{-1}$, we know $(R^{-1})^{-1}$ is symmetric.\n\\end{proof}\n}}\n\\end{center}\n\\caption{Mathematical Content of {\\tt{Relns2v3}}}\n\\label{fig:docrelns2v3}\n\\end{figure}\n\nIn the end the previous work that is repeated in vs. imported into a document\nwill be (at least partially) economically determined based on fees (relative\nto the size of documents) and royalty requirements.\nIf the owners of items determine new documents are opting to repeat work\nand pay higher fees, then these owners are likely to reduce the royalty requirements.\nHowever, as developments\nbecome increasingly complicated, repeating work becomes less feasible. The\nreason is simple: to repeat a definition or a proof, one will generally need to\ninclude other dependencies. In the most extreme case, to avoid all dependencies a document can include every definition and proof all the way down to the foundation.\n\n\\section{Bounties}\\label{sec:bounties}\n\nWe next consider bounties on conjectures.\nThis gives a third in-system use of the currency\nand allows users to guide the development the library.\nA document may include conjectures (unproven propositions)\nand include a bounty in the form of currency units.\nThe bounty will be automatically paid out to the publisher\nof a document resolving the conjecture.\nBy {\\em{resolving}} we mean either proving the conjecture\nor proving its negation.\n\nA similar notion of bounties for bitcoin is available\nat Sakaguchi's website {\\tt{proofmarket.org}}~\\cite{ProofMarket}.\nAt {\\tt{proofmarket.org}} there is a list of Coq~\\cite{Coq:manual} and Agda~\\cite{Norell08} propositions\nwith bitcoin bounties. These can be collected by submitting formal proofs to\nthe website. If the proofs are checked by the corresponding system to be correct,\nthen the bounty is paid out.\nThe bounty mechanism at\nproofmarket.org is centralized and carries counterparty risk.\n\nQeditas will handle bounties in a decentralized manner as follows.\nSuppose $\\delta$ is the address of the syntactic term specifying a conjecture.\nAll bounties will be held (as bounties, not currency) at address $\\delta$.\nSuppose Alice, with address $\\alpha$, publishes a document which contains\na proof of the proposition.\nAs a result of this publication, $\\alpha$ will be entered as the owner of $\\delta$ (as a proposition).\nThe owner of a proposition will always be allowed to spend bounties held at the address back into currency units (to any address).\nTo handle the case when Alice proves the negation of the conjecture,\nwe say the owners of propositions will also be allowed to spend bounties\nheld at the {\\em{negation}} of propositions\nback into currency units.\n\nNote that it is possible for a proposition to be {\\em{independent}} -- meaning\nneither the proposition nor its negation is provable.\nUsing currency units to place bounties on independent propositions\nessentially {\\em{burns}} the currency.\n\nThe collection of bounties seems to have a ``winner takes all'' quality. However, as the conjectures become increasingly complicated, it seems likely that\nthe document which resolves the conjecture is built from previous work. In\npractice, we assume the creators of this previous work required royalties, and\nthey will be rewarded by the purchase of rights instead of the bounty. This\nmeans bounties can indirectly encourage users to publish intermediate results\nintended to build towards a solution to a conjecture with a bounty.\n\n\\section{Assets}\\label{sec:assets}\n\nIn previous sections we have described currency units, intentions, documents, ownership, rights and bounties.\nWe combine these under the general notion of a preasset.\nA preasset can be combined with other information to give an asset.\nHere we mostly follow the presentation in~\\cite{White2015b}, with some modifications.\n\nA {\\em{preasset}} is one of the following:\n\\begin{itemize}\n\\item a currency unit ($64$-bit number giving the number of cants),\n\\item a bounty on a conjecture (with a 64-bit number giving the number of currency units),\n\\item a deed for an object (with the address of the owner and an optional $64$-bit number indicating the cost of rights to use it as an object),\n\\item a deed for a proposition (with the address of the owner and an optional $64$-bit number indicating the cost of rights to use it as a known proposition),\n\\item a deed for the negation of a proposition (useful only for collecting bounties when a conjecture is resolved in the negative),\n\\item a right to use an object (with the address of the object and the number of times it may be used as an object),\n\\item a right to use a proposition (with the address of the proposition and the number of times it may be used as a known proposition),\n\\item a marker to indicate the intention to reveal and publish a document or\n\\item a published document (arbitrary, but checked to ensure correctness, intention and appropriate rights).\n\\end{itemize}\n\nAn {\\em{obligation}} $\\omega$ is a triple $(\\alpha,n,r)$ where $\\alpha$\nis an address, $n$ is a block height and $r$ is a boolean.\nThe address $\\alpha$ is either a pay-to-public-key-hash or pay-to-script-hash address\nand gives the signature required to spend the corresponding asset.\nThe block height $n$ gives the earliest block height at which the corresponding asset\ncan be spent. The boolean $r$ indicates if the corresponding asset is a reward\nfrom staking. Rewards are subject to extra conditions, including the possibility\nof forfeiture in case double signing on two short forks is detected.\n\nAn {\\em{asset}} is a triple $(h,b,\\omega,u)$\nwhere $h$ is a unique identifier of the asset (in practice, a hash value),\n$b$ is a block height,\n$\\omega$ is an obligation, and $u$ is a preasset.\nThe obligation $\\omega$ may be omitted, in which case it is treated as\n$(\\alpha,0,{\\mathtt{false}})$ where $\\alpha$ is the address where the asset is held.\nThe block height $b$ is the {\\emph{birthday}} of the asset, and is\nthe block height at which the asset entered the ledger tree.\nInitially distributed assets will have birthday $0$.\nThe first block of the Qeditas block chain will have height $1$,\nand assets created in this first block will have birthday $1$.\n\nIf $b>0$ and $u$ is a currency preasset with $v$ units, the value of the asset $(h,b,\\omega,u)$\nis $v$ cants.\nWe consider the case where $b=0$ special, as these are assets from the initial distribution.\nAs discussed in Section~\\ref{sec:currency} the value of unclaimed (unspent) assets from the initial distribution\nwill halve over time. In particular, if $u$ is a currency preasset with $v$ units,\nthen value of the asset $(h,0,\\omega,u)$ at block height $n$\nis (the floor of) $\\frac{v}{2^{f(n)}}$ where $f(n) = 0$ if $n \\leq 280000$\nand $f(n) = \\frac{n-70000}{210000}$ for $n > 280000$.\nIf $n \\geq 11410000$ (which should be after roughly 200 years),\nall the assets from the initial distribution will have value $0$.\n\nThe state of the system can be representated as a function taking addresses\nto lists of assets.\nSuch a state can be represented using tries (similar to Merkle Patricia trees)\nas described in~\\cite{White2015b}.\nOne can use the same representation to keep up with only the portions of the state\nrelevant to the node in question.\n\n\\section{Theorem Provers and Proof Checkers}\\label{sec:provers}\n\nIn this section we discuss what kind of theorem prover or proof checker\nis appropriate for Qeditas. We begin by distinguishing between theorem provers and\nproof checkers. A theorem prover is a system in which one constructs proofs,\noften with varying degrees of automated assistance. (Given this role, such a\nsystem is sometimes called a proof assistant.) A proof checker is a system which\ntakes a preexisting proof and simply checks that it is correct. For Qeditas the\nvital ingredient is a proof checker. Each time a document is published each node\nwill need to use the proof checker to ensure its correctness. For the project to\nbe successful, there should also be (at least one) theorem prover in which users\ncan create documents and construct proofs.\n\nFor concrete examples, we can contrast two early groundbreaking systems:\nAUTOMATH~\\cite{debr68,DeBruijn80} and Mizar~\\cite{RudnickiTrybulec2001}.\n\nAUTOMATH was the first proof checker. The user would give definitions in\nfull detail. Each of the definitions would have a declared type and the system\nwould check that the given term has the given type. Some of the types would\ncorrespond to propositions and the terms would correspond to proofs, giving\na first implementation of what is now known as the Curry-Howard-de Bruijn\ncorrespondence~\\cite{debr68,DeBruijn80,howa80}. The AUTOMATH project is no longer active.\n\nMizar was an early example of a theorem prover (dating back to the 1970s)\nand is still in use today.\\footnote{The Mizar project was not known outside the Soviet block until the Iron Curtain fell. One can find exciting discussions on the old QED mailing list prompted by the discovery that a small Polish group led by Andrzej Trybulec had already implemented a system doing many of the things under discussion.}\nMizar is the only widely used system based on set theory and provides\nsupport for some set theoretic notation similar to\nthat used by traditional mathematicians.\nThe proofs are given in a declarative and\n(relatively) readable style.\nThe foundation of Mizar is essentially first-order Tarski-Grothendieck\nwhich is known to be consistent assuming the existence of certain large cardinals.\nMizar has been used to build the Mizar Mathematical Library\nwhich comprises an impressive collection of mathematics.\n\nWhat we require for Qeditas is a proof checker (like AUTOMATH)\nwith a reasonably small ``trusted'' code base, and a theorem prover which can\nbe used to construct the proofs to be checked. As long as the underlying logic\nof a theorem prover is clearly defined, it should be easy enough to write a\nsmall proof checker independent of the theorem prover. If the theorem prover\nfollows the Curry-Howard-de Bruijn correspondence, then it should be possible\nto ``compile'' proofs constructed with the system's assistance into proof terms\nto be independently checked.\n\nMany popular theorem provers today follow a different scheme: the LCF\napproach. In this alternative, abstraction in the meta-language is used to guarantee correctness.\nWhile it seems to be feasible to produce different proof representations (e.g., proof terms) by\ntranslating from LCF style provers, it is\nnot as simple as one might hope in practice~\\cite{ckak-itp13,ckju-cade13}. Theorem provers in the\nLCF style include Isabelle-HOL~\\cite{Nipkow-Paulson-Wenzel:2002} and those in the HOL family~\\cite{Gordon91} such as\nHOL-light~\\cite{harrison-hollight}.\n\nA well-known theorem prover based on Curry-Howard-de Bruijn is Coq~\\cite{Coq:manual,BC04,chlipalacpdt2011,Pierce:SF}\nand Coq's ssreflect variant~\\cite{Gonthier2010}. Coq is a widely used and well developed system,\neven winning the 2013 ACM Software System award. Ssreflect was used to formally prove both the four color theorem~\\cite{Gonthier2007} and later the\nOdd Order Theorem~\\cite{Gonthier2013}. Coq has also been applied to theories directly related\nto cryptocurrencies~\\cite{Miller2014gpads,multibranch,multistrategy,White2015a,White2015b}. There is clear evidence that it is possible\nto formalize serious mathematics in Coq and ssreflect. Coq supports the construction of proofs with some automation, but always compiles to a proof term\ncheckable by a kernel. This would seem to make Coq (or ssreflect) the clear\nchoice to use with Qeditas.\n\nOn the other hand, there are aspects of Coq which are experimental and\nthis makes it somewhat dangerous to use in a context in which value depends\non its stability. It is reasonable to be skeptical of the consistency of Coq's\nfairly sophisticated logic. For example, proofmarket.org placed a bounty on\nthe proposition False. In other words, there was a bitcoin bounty placed on\nproving Coq inconsistent. While this should not have been provable in principle,\nin practice it was proven twice (for two different reasons). In addition, the\nfoundational logic of Coq is not quite fixed and may change in subtle ways with\neach new version. Even with Coq's very attractive properties, it is also clear\nthat it was not designed for a purpose like Qeditas.\n\nAn alternative to trying to use Coq directly is to have\na small proof checker in a sublogic of Coq, e.g., Egal~\\cite{Brown2014}. Like Coq, Egal constructs\nCurry-Howard-de Bruijn style proof terms, but for the logic of simple type theory~\\cite{Church40}.\nThe subset of the code used for proof checking in Egal\nwas easy to extract (and simplify) for use as the\nkernel proof checker for Qeditas. Now that this kernel has been\nextracted, Qeditas users could make use of any number of\ntheorem provers to construct proofs, so long as the prover\nis capable of producing documents with Qeditas-checkable proof terms.\nIt should be easy to obtain such proof terms from a prover like Coq,\nso long as one works within a fragment of Coq's logic (e.g., avoiding\ntype universes and inductive types).\n\nEgal itself could also be used to construct Qeditas documents.\nEgal seems to have been designed to specifically support a\nhigher-order set theory (higher-order Tarksi-Grothendieck),\nwhich would likely be one of many Qeditas foundational theories.\nLike Mizar's foundation, higher-order Tarski-Grothendieck is a\ntheory which is known to be consistent assuming the existence of certain large\ncardinals. That is, if someone were to prove a contradiction in Egal, then either\nthere is an implementation bug or there is a proof of a surprising mathematical\nresult (that certain large cardinals cannot exist).\nAnother advantage of using Egal is that a few people from the cryptocurrency community\ngained some experience using Egal in the bitcoin theorem proving treasure hunt\nat mathgate.info in 2014. It is likely that during this process a few bitcoin\nenthusiasts got over the critical hump required to learn to use such a prover.\nThe drawbacks of choosing to use Egal are obvious: Egal does not provide\nthe rich environment of other provers, either in terms of the system or in terms\nof a community. Moreover, the proof tactics in Egal are of only modest power,\nleaving the user to do most of the work. Finally, the development of the system\nseems to have ended.\nIt would likely make sense to use Egal while bootstrapping the Qeditas network\nuntil other more advanced theorem provers (e.g., Coq, Isabelle-HOL, HOL-light, etc.)\nare modified to produce Qeditas checkable documents.\n\nIn addition to the systems above, there are two other systems that do not yet\nexist. A peer-to-peer system called ProofPeer~\\cite{ProofPeer} supporting formalization is in\ndevelopment. It is unclear at this early stage how similar ProofPeer and Qeditas\nwill be. Another similar project is BitFuncTor~\\cite{bitFuncTor}. BitFuncTor is intended to\ntarget functional programming instead of mathematics.\n\n\\section{Conclusion}\\label{sec:concl}\n\nWe have described Qeditas, a project to support distributed formalization of\nmathematics using block chain technology. The underlying currency will be\nsimilar to bitcoin in that there will be a similar 21 million unit cap. Two thirds\nof these units will be part of an initial distribution based on a snapshot of the\nBitcoin block chain. Qeditas will support the publication of formal documents,\nthe ownership of mathematical objects and propositions as intellectual property, the purchasing of rights to use such property and bounties on unproven\nconjectures. The hope is that this will be sufficient to motivate and reward\nparticipants to do the time consuming work of formalizing mathematics.\n\n\n\\bibliographystyle{plain}\n\\bibliography{refs}\n\n\\end{document}\n\n", "meta": {"hexsha": "1b21af1935a9b1e21d1189502d06f929c6b93b0b", "size": 48239, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/whitepaper/qeditas.tex", "max_stars_repo_name": "dalcoder/dalilcoin", "max_stars_repo_head_hexsha": "aa6a377abd3c0d244e276eadde6a84f5badb8549", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2017-01-26T10:54:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T15:10:52.000Z", "max_issues_repo_path": "doc/whitepaper/qeditas.tex", "max_issues_repo_name": "tezosprime/tezosprime", "max_issues_repo_head_hexsha": "151c6aaadea7b2d1ba46a172955ef2122bb66528", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/whitepaper/qeditas.tex", "max_forks_repo_name": "tezosprime/tezosprime", "max_forks_repo_head_hexsha": "151c6aaadea7b2d1ba46a172955ef2122bb66528", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-12-28T12:22:45.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-17T14:39:32.000Z", "avg_line_length": 57.633213859, "max_line_length": 599, "alphanum_fraction": 0.7838263646, "num_tokens": 11780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030761371502, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3267949292969337}}
{"text": "\\part[Excursion into Parameterized Systems]{Excursion Into\\\\Parameterized Systems\\\\ \\ \\\\ \\LARGE Guarded and Token-ring Systems}\n\n\\section*{Overview of Part II}\n\nConcurrent systems are hard to implement and even harder to debug.\nOn the other side, they are relatively easy to specify.\nConsider, for example, the arbiter serving many clients.\nA possible specification is\n$\n  \\forall i \\neq j. \\G \\neg ( g_i \\land g_j ) \\land \\G (r_i \\impl \\F g_i),\n$\n%\\[\n%\\begin{array}{ll}\n%  \\forall i \\neq j.~ & \\G \\neg ( g_i \\land g_j ) \\land \\\\\n%  \\forall i.~ & \\G (r_i \\impl \\F g_i),\n%  \\end{array}\n%\\]\nwhich says that, for every client, every request should be eventually granted,\nand the grants are mutually exclusive.\nIf a human implements such an arbiter,\nhe would try to come up with a basic block that handles a single client,\nand connect such a block into a system, that handles as many clients as needed.\nOn the other side,\nthe computer tries to synthesize a system as one monolithic block.\nThis hides the insight that\na system for $n+1$ clients is very similar to a system for $n$ clients.\nThis leads to the scalability problem, once we require a large number of clients.\n\nThe parameterized synthesis approach~\\cite{JB14} addresses the issue.\nThe idea is---just like the human would do---%\nto automatically synthesize a basic block that\ncan be arranged into a system of any desired size.\nThere are several ways to arrange such blocks into a system,\ndepending on how they communicate with each other.\nIn this thesis part we will look into two system architectures.\n\nThe first architecture is inspired by cache coherence protocols found in modern processors.\nSuch a protocol is described by states,\nwhere transitions between states happen depending on whether or not there is a processor in a particular state.\nI.e., the transitions are guarded.\nChapter~\\ref{chap:guarded-systems} studies guarded systems.\n\nThe second kind of systems is token-ring systems.\nIn such a system, the single token circulates in the system.\nA process possessing the token knows that no other process has the token.\nBased on this information, the process can, for example, raise the grant.\nIf all processes raise the grant only when they posses the token,\nthen the grants will be mutually exclusive.\nChapter~\\ref{chap:token-systems} studies token-ring systems.\n\nFor both architectures we study their parameterized synthesis problems.\nThe parameterized synthesis problems asks, given a parameterized specification,\nto find a process implementation,\nsuch that a system of any size composed of such processes,\nsatisfies the specification.\nThe solution to the seemingly difficult problem---we now ask for correctness of a system of \\emph{any} size---is based on the cutoff reduction:\nto synthesize a process that works for all system sizes,\nit is enough to synthesize a process that works in a system of a cutoff size.\nFor example, for the specification of the arbiter mentioned above,\nthe cutoff for token-ring systems is 4.\nThis means that it is enough to find a process implementation that\nworks in a system with 4 such processes.\nOnce we find it, a system of size 5, 6, 7,... is also correct.\n\nIn Chapter~\\ref{chap:guarded-systems} we prove cutoff results for guarded systems.\nOur results extend the results of Emerson and Kahlon~\\cite{EmersonK03}.\nOur contribution concerns both parameterized synthesis and parameterized verification.\nWe prove new cutoff results that are applicable to a previously unconsidered setting\nof open systems with liveness properties under fairness assumptions.\nWe also prove new cutoff results for deadlock detection.\nThe work is theoretical; it is yet to find its application.\n\nIn Chapter~\\ref{chap:token-systems} on token-ring systems,\nwe extend the cutoffs of Emerson and Namjoshi~\\cite{Emerso03}\nto a new setting of fully asynchronous systems and richer specifications.\nThen we apply them to an industrial arbiter protocol called AMBA.\nThus, we synthesize for the first time the AMBA protocol in the parameterized sense.\n\nThe chapters can be read in any order.\n\n\\input{guarded-systems/main}\n\n\\input{token-systems/main}\n", "meta": {"hexsha": "fcb35878394be957b74bf17039bac72ce4d6a6cc", "size": 4121, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/param_synthesis.tex", "max_stars_repo_name": "5nizza/phd-thesis", "max_stars_repo_head_hexsha": "74a7a4c6ed06aa2894d2ba05f417f5f812730b78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thesis/param_synthesis.tex", "max_issues_repo_name": "5nizza/phd-thesis", "max_issues_repo_head_hexsha": "74a7a4c6ed06aa2894d2ba05f417f5f812730b78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis/param_synthesis.tex", "max_forks_repo_name": "5nizza/phd-thesis", "max_forks_repo_head_hexsha": "74a7a4c6ed06aa2894d2ba05f417f5f812730b78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.0595238095, "max_line_length": 143, "alphanum_fraction": 0.7862169376, "num_tokens": 932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3267404342984972}}
{"text": "The semantics of the combination $\\pi$-OZ specification S can then be described by the \\picalc{} process $S_{OZ\\_part_\\pi} \\mid S_{\\pi\\_part}$, where $S_{OZ\\_part_\\pi}$ is the syntactic transformation of \\oz{} part into \\picalc{} process. For example, the semantics of \\refFig{comp_oz_pi_statefull_vm} is $VM\\_OZ\\_PI \\mid VM\\_PI$, where $VM\\_OZ\\_PI$ is as described in \\refLis{tra_vm_OZ_listing}. Unfortunately, this will not work well, since the parallel operator ``$|$'' only allows the binary synchronization via a channel, not like in $CSP$ where the parallel operator ``$||$'' allows the multiple synchronization via a channel. That will be problematic when we try to combine the $\\pi$-OZ specification of an entity S with a $\\pi$-OZ specification of another entity R in parallel. To solve this problem we can use \\textbf{broadcast channel} or  \\textbf{non-atomic reaction} concept as follows:\n\n\\subsubsection{\\findex[channel!shared]{Shared channel}:}\nTo allow the multiple synchronization via a channel in \\picalc{}, we use the concept of the shared channel. \\cite{ene} introduces the b$\\pi$, which is an extension of \\picalc{} implementing broadcast communications. Additionally, the UPPAAL model checker introduces the broadcast channel too \\cite{olderog08}. For simplicity, we use the broadcast channel from UPPAAL with a little change. On a shared channel one sender synchronizes with at least one receiver. Thus, like binary synchronization, a shared channel blocks the sender if there are no receivers. Furthermore, we can send and receive on a shared channel. We extend the transition rules of \\picalc{} defined in \\refDef{def_pi_trans_system}, with an additional rule:\n\\begin{figure}[H]\n\\begin{gather*}\n\\kalRuleM[if\\ x: Shared]{Shared\\_Chan\\_PAR}{}{P \\transs{\\out{x}{\\vec{y}}} P'}{Q \\transs{\\inp{x}{\\vec{y}}} Q'}{R \\transs{\\inp{x}{\\vec{z}}} R'}{\\procpar{\\procpar{P}{Q}}{R} \\transs{\\tau} \n\\procpar{P'}{\\procpar{\\substitue{\\vec{y}}{\\vec{z}}Q'}{\\substitue{\\vec{y}}{\\vec{z}}R'}}\n}\n\\end{gather*}\n\\caption{Transition rule for shared channel.}\n\\label{fig_broadcast_channel}\n\\end{figure}\n\n\n\n\\refFig{comp_oz_pi_statefull_vm_broadcast} shows the $\\pi$-OZ specification of our $VM$ using shared channels.\nThe combination's process $S_{OZ\\_part_\\pi} \\mid S_{\\pi\\_part}$ for $VM$ is $VM\\_OZ\\_PI \\mid VM\\_PI$. The main advantage of the shared channels in $VM$ is that, if we combine the combination's processes with a third processes $Cus$ representing a customer which issues a signal on the $coffee$ channel, this will enforce both $VM\\_OZ\\_PI$ and $VM\\_PI$ to evolve, since they are listening on coffee, which is a shared channel in  $Cus$, $VM\\_OZ\\_PI$ and $VM\\_PI$. The behavior of $VM$ can be seen as the intersection of the behavior of  $VM\\_OZ\\_PI$ and $VM\\_PI$, i.e., the intersection of the transition graphs, i.e., the automates. Unfortunately, our tools do not support the shared channel, thus we will not proceed with this approach.\n\\input{./images/the_compination_pi_oz/comp_oz_pi_statefull_vm_broadcast}\n\n\n\n\\subsubsection{\\findex[non-atomic reaction]{Non-atomic reaction}:} Let us examine the process $Cus \\mid VM\\_OZ\\_PI \\mid VM\\_PI$ shown in \\refFig{binary_reactoin}. When $Cus$ issues a signal on the $coffee$ channel, it is required that $VM\\_OZ\\_PI$ and $VM\\_PI$ receives the signal and evolve together. This is not possible, since the \\picalc{} communications are binary, so either $VM\\_OZ\\_PI$ or $VM\\_PI$ will evolve and the other will not. To solve this problem using binary communications we propose to break the channel $coffee$ down into two channels: $ex\\_coffee$ and $in\\_coffee$ as shown in \\refFig{non_atomic_reactoin}. The channel $ex\\_coffee$ is for the external, outside $VM$, communication between $Cus$ and $VM\\_PI$. The channel $in\\_coffee$ is for the internal, inside $VM$, communication between $VM\\_PI$ and $VM\\_OZ\\_PI$. In \\refFig{non_atomic_reactoin} the numbered arrows represent the communication flow from $VM\\_PI$'s point of view. $VM\\_PI$  receives a signal via $ex\\_coffee$ and re-sends it via $in\\_coffee$. When $VM\\_OZ\\_PI$ ends its processing it sends a done signal via  $done\\_in\\_coffee$ to $VM\\_PI$ which re-sends the done signal to $Cus$ via $done\\_ex\\_coffee$. This way the combination's process $S_{OZ\\_part_\\pi} \\mid S_{\\pi\\_part}$, i.e., $VM\\_OZ\\_PI \\mid VM\\_PI$, behaves as a one processes from the view point of its environment, i.e., $Cus$, by breaking down the channel, reproducing the signal, and using the done signal. All that makes the reaction $ordering\\ a\\ coffee$ a non-atomic reaction. Furthermore, we can notice  that the non-atomic reaction concept is overburdening, since we now have four channels \\textit{ex\\_coffee, in\\_coffee, done\\_in\\_coffee, done\\_ex\\_coffee} instead of having one channel for $coffee$.\n\n\\refFig{comp_oz_pi_statefull_vm_non_atomic} shows how the $\\pi$-OZ specification of $VM$ implements the non-atomic reaction concept. In the interface part it defines the needed channels. For $coffee$ four channels: one external, one internal and two for done signaling. The internal channels $in\\_coffee,done\\_in\\_coffee$ are invisible outside $VM$. Thus, we need to extend \\oz{} with a new construct $chan\\ local$ to define local channels. The local channel is like the $new$ operator in the \\picalc{}, i.e., restriction as follows: $VM = new\\ in\\_coffee,done\\_in\\_coffee...(VM\\_PI\\mid VM\\_OZ\\_PI)$. For $tea$ and $talk$ the same is done like $coffee$. The behavior sequence part $VM\\_PI = ex\\_coffee().\\out{in\\_coffee}{}\\\\.done\\_in\\_coffee() .... $ reflects exactly the numbered arrows shown in \\refFig{non_atomic_reactoin}. \n\nThe $\\pi$-OZ specification of $VM$ reads: the combination is ready to participate in an $ex\\_coffee$ action issued by the environment. On receiving a signal via $ex\\_coffee$, the $\\pi$ part will make a transition and issue a signal via $in\\_coffee$ enforcing the OZ part to make a transition specified with the operation schema $in\\_coffee$. When the OZ part ends its transition it sends a signal via $done\\_in\\_coffee$ enforcing the $\\pi$ part to make a transition, and finally the $\\pi$ part issues a done signal via $done\\_ex\\_coffee$ to the environment declaring that ordering a coffee has done successfully. Notice that the specification has a schema for $in\\_coffee$ which represents the conditions on the data, and there no schemes for $ex\\_coffee$, $done\\_ex\\_coffee$ and $done\\_in\\_coffee$, since they serve for orchestrating.\n\n\\refFig{comp_oz_pi_statefull_activeShop_non_atomic} and \\refFig{comp_oz_pi_statefull_idleShop_non_atomic} show the $\\pi$-OZ specification of $ActiveShop$ and $IdleShop$ respectively, using the non-atomic reaction concept. \\refFig{sys_non_atomic_reactoin} shows a big picture of a system consisting of a customer, vending machine and two shops.\n\n\\begin{figure}[H]%\n\\centering\n\\fbox{\\includegraphics[keepaspectratio,width=0.5\\textwidth]{./images/the_compination_pi_oz/binary_reactoin.png}}%\n\\caption{The process $Cus \\mid VM\\_OZ\\_PI \\mid VM\\_PI$.}\n\\label{binary_reactoin}%\n\\end{figure}\n\n\\begin{figure}[H]%\n\\centering\n\\fbox{\\includegraphics[keepaspectratio,width=0.95\\textwidth]{./images/the_compination_pi_oz/non_atomic_reactoin.png}}%\n\\caption{Action reproducing and non-atomic reaction.}\n\\label{non_atomic_reactoin}%\n\\end{figure}\n\n\\input{./images/the_compination_pi_oz/comp_oz_pi_statefull_vm_non_atomic}\n\n\\input{./images/the_compination_pi_oz/comp_oz_pi_activeShop_non_atomic}\n\n\\input{./images/the_compination_pi_oz/comp_oz_pi_idleShop_non_atomic}\n\n\\begin{figure}[H]%\n\\centering\n\\fbox{\\includegraphics[keepaspectratio,width=0.95\\textwidth]{./images/the_compination_pi_oz/sys.png}}%\n\\caption{System consisting of a customer, vending machine and two shops.}\n\\label{sys_non_atomic_reactoin}%\n\\end{figure}\n\nAdditionally, \\refLis{vm_PI_non_atomic} shows the direct implementation of the $\\pi$-part of $VM$ specification shown in \\refFig{comp_oz_pi_statefull_vm_non_atomic} using ABC code. We can notice that: \\\\\nex\\_coffee.\\textquotesingle in\\_coffee.done\\_in\\_coffee.\\textquotesingle done\\_ex\\_coffee.VM\\_PI... exactly reflects the $\\pi$-part of \\refFig{comp_oz_pi_statefull_vm_non_atomic}, where the parameters are removed for clarity.\n\n\\lstinputlisting[backgroundcolor=\\color{white},caption={VM ($\\pi$-part) in ABC code.},captionpos=b, label={vm_PI_non_atomic}]{listings/vm_PI_non_atomic.abc}\n\n\\refLis{vm_OZ_non_atomic} shows the direct implementation of the OZ-part of $VM$ specification shown in \\refFig{comp_oz_pi_statefull_vm_non_atomic} using ABC code.\n\n\\lstinputlisting[backgroundcolor=\\color{white},caption={VM (OZ-part) in ABC code.},captionpos=b, label={vm_OZ_non_atomic}]{listings/vm_OZ_non_atomic.abc}\n\n\\refLis{vm_OZ_and_PI_non_atomic} shows the direct implementation of the $\\pi$-part $\\mid$ OZ-part of $VM$ specification shown in \\refFig{comp_oz_pi_statefull_vm_non_atomic} using ABC code.\n\n\\lstinputlisting[backgroundcolor=\\color{white},caption={ the combination $\\pi$-OZ of VM in ABC code.},captionpos=b, label={vm_OZ_and_PI_non_atomic}]{listings/vm_OZ_and_PI_non_atomic.abc}\n\n\\refLis{system_non_atomic} shows a part of the direct implementation of the system consisting of a customer, vending machine, and two shops shown in \\refFig{sys_non_atomic_reactoin} using ABC code.\nFor the full code please see the appendix.\n\n\\lstinputlisting[backgroundcolor=\\color{white},caption={ the system consisting of: customer, vending machine and two shops in ABC code.},captionpos=b, label={system_non_atomic}]{listings/system_non_atomic.abc}", "meta": {"hexsha": "da3c1209b0e7f24754c6dcca3c6e1fd1364d0a98", "size": 9493, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/mainpart/the_compination_pi_oz/sections/transformational_semantics/transformational_semantics.tex", "max_stars_repo_name": "MuhammadEkbal/thesis", "max_stars_repo_head_hexsha": "dcb71d5d7af7a8e87d7d230d58f18c01dbdfe13a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/mainpart/the_compination_pi_oz/sections/transformational_semantics/transformational_semantics.tex", "max_issues_repo_name": "MuhammadEkbal/thesis", "max_issues_repo_head_hexsha": "dcb71d5d7af7a8e87d7d230d58f18c01dbdfe13a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/mainpart/the_compination_pi_oz/sections/transformational_semantics/transformational_semantics.tex", "max_forks_repo_name": "MuhammadEkbal/thesis", "max_forks_repo_head_hexsha": "dcb71d5d7af7a8e87d7d230d58f18c01dbdfe13a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 128.2837837838, "max_line_length": 1761, "alphanum_fraction": 0.7749920994, "num_tokens": 2622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3267404342984972}}
{"text": "\\chapterquote{%\nThe two operations of our understanding, intuition and deduction, on which alone we have said we must rely in the acquisition of knowledge.}\n{-- Rene Descartes, \\textit{Key Philosophical Writings} (1997)}\n\nThe purpose of this chapter is to characterize the distribution of the interference in a typical packet transmitted through an asynchronous channel, where fixed-length packets arrive according to a Poisson process.\n%\nAlthough simple and theoretical, because we do not consider spatial positions or fading effects, we deemed it important to build intuition on the structure of our main problem of characterizing the spatio-temporal interference on Poisson networks.\n\n\\newpage\n\n\\section{The Interference Model}\n\nLet $\\tau$ be the transmission time of the packets that use the channel. Let the homogeneous Poisson point process $\\Pi$ on $\\R$ with density $\\lambda > 0$ be the times for which a transmission starts.\n\nWe are interested in the stochastic process $\\{I_0(t)\\}_{t\\in[0,\\tau]}$, which corresponds to the number of simultaneous interfering packets on a typical packet that started its transmission at $t=0$. Then, the interference is defined as a shot-noise field given by\n\\begin{align} \\label{eq:interf_I0}\n    I_0(t) \\triangleq \\sum_{x\\in\\Pi^!_0} \\ind_{[0,\\tau)}(t-x), \\quad t\\in[0,\\tau),\n\\end{align}\nwhere $\\Pi^!_0$ is the \\textit{reduced Palm version} of $\\Pi$, i.e., $\\Pi$ conditioned to having a point at the origin and excluding it.\n%\nSlivnyak's theorem (Theorem~\\ref{th:slivnyak}) guarantees that the distribution of $\\Pi^!_0(\\cdot)$ is the same as $\\Pi(\\cdot)$ for a Poisson point process.\n\nIn view of the general network model of Chapter~\\ref{cap:P2_00}, we provide two of many possible scenarios for which this model can be applied.\n\n\\begin{example}\n    Consider a stationary bipolar high-mobility Poisson network with density of transmitters $\\lambda_{\\S}>0$ on the plane $\\S=\\R^2$, and transmission time $\\tau_i = \\tau$ and transmission power $P_i \\equiv 1$ for every user $i\\in\\N$.\n    \n    Suppose packets arrive at each transmitter according to a Poisson point process of density $a>0$ on time $\\T = \\R$ and there is no buffer in the transmitters, thus packets are transmitted upon arrival and discarded afterward (independently of successful transmission), i.e., $A_{i} = T_{i} = T^*_{i}$ for all users $i\\in\\N$.\n    \n    In a scenario without small-scale fading ($H_{ij} \\equiv 1$ for all $i,j\\in\\N$) and with path loss function $\\ell(r) = \\ind\\{r < r_0\\}$, $r_0>0$,\n    %\n    the interference model presented in \\eqref{eq:interf_I0} applies to this network with $\\lambda = \\pi r_0^2\\,\\lambda_\\S\\,a$.\n\\end{example}\n\n\\begin{example}\n    Consider a stationary bipolar static network with $n\\in\\N$ transmitters and $n$ receivers on a small disk of radius $1$ ($\\S=\\{x\\in\\R^2: ||x|| < 1\\}$) such that small-scale fading and path loss can be ignored, i.e., $H_{ij} \\equiv 1$ for all $i,j\\in\\{1,2,\\dots,n\\}$ and $\\ell \\equiv 1$.\n    %\n    Further, the transmission time $\\tau_i = \\tau$ and transmission power $P_i \\equiv 1$ for every user $i\\in\\{1,2,\\dots,n\\}$.\n    \n    Suppose that the medium access protocol is to transmit a packet after an iid exponentially distributed time of parameter $\\lambda_p > 0$ after the last transmission, i.e., $T_i$ is a Poisson point process of density $\\lambda_p$ on $\\T = \\R$ for each $i\\in\\{1,2,\\dots,n\\}$.\n\n    Let us consider that each transmitter has a buffer and we have saturated traffic, i.e., all transmitter's queues are non-empty at all times, so $A_i$ does not matter and $T_i^* = T_i$, because there is always a packet to transmit.\n    %\n    Then, the interference model presented in \\eqref{eq:interf_I0} applies to this network with $\\lambda = n\\lambda_p$.\n\\end{example}\n\nThe above examples do not specify the transmission probability model $\\mathscr{S}$. This is not done because it depends on the adopted model for success probability and each of the following sections presents a different model.\n\nAlthough we provided only two scenarios, it is not hard to see that we must have a stationary network with a single user class, which implies that the throughput is given by the product of the traffic with the transmission success probability, i.e., $\\mathscr{T} = \\upsilon\\,p_s$.\n\nLet us begin the characterization of $I_0$ through its auto-covariance function, which is given by, for $\\Delta t\\in(-\\tau,\\tau)$,\n\\begin{align*}\n    \\mathrm{K}_{I_0}(\\Delta t)\n        &\\triangleq \\E[I_0(t) I_0(t+\\Delta t)] - \\E[I_0(t)] \\E[I_0(t+\\Delta t)], \\quad t\\in[0,\\tau)\\cap[-\\Delta t, \\tau-\\Delta t),\\\\\n        &= \\sum_{k_0\\ge 0}\\sum_{k_1\\ge 0}\\sum_{k_2\\ge 0} (k_0+k_1)(k_0+k_2) \\frac{\\lambda^{k_0}(\\tau-|\\Delta t|)^{k_0}}{k_0!}\\,\\euler^{-\\lambda(\\tau-|\\Delta t|)}\\\\\n        &\\hspace{30mm} \\times\\frac{\\lambda^{k_1}|\\Delta t|^{k_1}}{k_1!}\\euler^{-\\lambda|\\Delta t|} \\,\\frac{\\lambda^{k_2}|\\Delta t|^{k_2}}{k_2!}\\euler^{-\\lambda|\\Delta t|} - (\\lambda\\tau)^2\\\\\n        &= \\lambda(\\tau - |\\Delta t|),\n\\end{align*}\nwhere we have used the identity $\\displaystyle\\sum_{k\\ge0} \\frac{x^k}{k!} = \\euler^x$, for any $x\\in\\R^*$.\n\nAs expected of a Poisson point process, which is independent across space (or, in this case, time), the factor responsible for correlation in the stochastic process $I_0$ is related to the duration $\\tau$ of each transmitted packet. That is why $\\mathrm{K}_{I_0}(\\tau) = 0$.\n\n\\begin{remark} \\label{remark:Ch5_I0}\n    To illustrate a (rarely mentioned) dichotomy, we have calculated \\textit{(i)} the Laplace transform of $I_0$ on the interval $[0,\\tau)$ and \\textit{(ii)} the Laplace transform of the distribution of $I_0(t)$ at $t\\in[0,\\tau)$.\n    %\n    On the one hand, \\textit{(i)} characterizes the stochastic process on time, but not in distribution.\n    %\n    On the other hand, \\textit{(ii)} characterizes the distribution of the stochastic process at a point in time, but we cannot analyze the process as a whole, which is essential to decide whether a transmission is successful.\n    %\n    The calculations follow.\n    \n    \\textit{(i)} Let $s\\in\\C\\backslash\\{0\\}$. The Laplace transform of $I_0$ on the interval $[0,\\tau)$ is given by\n    \\begin{align}\n        \\mathscr{L}\\{I_0\\}(s)\n            &= \\int_0^\\tau I_0(t)\\,\\euler^{-s t}\\,\\d t \\nonumber\\\\\n            &= \\sum_{x\\in\\Pi} \\int_0^\\tau \\ind_{[0,\\tau]}(t-x)\\,\\euler^{-s t}\\,\\d t\\nonumber\\\\\n            &= \\sum_{x\\in\\Pi} \\left(\\euler^{-s \\lfloor -x\\rceil_0^\\tau} - \\euler^{-s \\lfloor \\tau-x \\rceil_0^\\tau} \\right)\\frac{\\euler^{-s x}}{s}, \\label{eq:Ch5_LT_I0}\n    \\end{align}\n    where $\\lfloor \\cdot\\rceil_a^b = \\max\\{\\min\\{\\cdot,b\\},a\\}$.\n    \n    \\textit{(ii)} Let $s\\in\\C$. The Laplace transform of the distribution of $I_0(t)$, $t\\in[0,\\tau)$ is\n    \\begin{align*}\n        \\mathscr{L}_{I_0(t)}(s) &= \\E[\\euler^{-s\\,I_0(t)}]\\\\\n            &= \\E\\!\\left[-\\sum_{x\\in\\Pi} s\\ind_{[0,\\tau)}(t-x) \\right]\\\\\n            &= \\exp\\!\\left(-\\int_\\R \\left(1 - \\euler^{-s\\ind_{[0,\\tau)}(t-x)}\\right)\\lambda\\,\\d x \\right)\\\\\n            &= \\exp\\!\\left(-\\int_0^\\tau \\left(1 - \\euler^{-s}\\right)\\lambda\\,\\d x \\right)\\\\\n            &= \\euler^{-\\lambda\\tau(1-\\euler^{-s})},\n    \\end{align*}\n    % Then, using Campbell Theorem (Theorem~\\ref{th:campbell}),\n    % \\begin{align*}\n    %     \\E\\!\\left[\\frac{1}{\\tau}\\mathscr{L}\\{I_0(t)\\}(s)\\right]\n    %         &= \\int_\\R \\left(\\euler^{-s \\lfloor -x\\rceil_0^\\tau} - \\euler^{-s \\lfloor \\tau-x \\rceil_0^\\tau} \\right)\\frac{\\euler^{-s x}}{\\tau s} \\lambda\\,\\d x \\\\\n    %         &= \\lambda\\tau \\frac{1-\\euler^{-\\tau s}}{\\tau s}.\n    % \\end{align*}\n    where we have used Campbell's theorem (Theorem~\\ref{th:campbell}) in the third equality.\n    \n    To analyze a successful transmission we need the characterization of the interference both in distribution and in time. As shown, it is easy to do one of them, however, both at the same time (e.g. calculating the Laplace transform of the distribution of \\eqref{eq:Ch5_LT_I0}) does not yield a tractable formula.\n\\end{remark}\n\nAs illustrated in Remark~\\ref{remark:Ch5_I0}, it is hard to characterize the distribution of $I_0$ on the interval $[0,\\tau)$ and in distribution concomitantly.\n%\nThus, we shall define a meaningful functional (related to a success probability) that receives as argument $I_0$ and give us a real number, e.g. the mean value of $I_0$ on $[0,\\tau)$.\n%\nThen, we characterize the distribution of this functional\\footnote{In the general model of Chapter~\\ref{cap:P2_00} the transmission success probability model $\\mathscr{S}$ receives as argument the $\\SIR$ instead of the interference $I_0$, however, this is easy to adapt, because the $\\SIR$ includes the interference.}.\n\n% % % % % % % % % % % % % % % % % % % % % \n\\section{Error Correcting Code model}\n\nIn the Error Correcting Code model (ECC model) we assume that a packet is successfully transmitted if the proportion of the packet that was affected by interference is smaller than or equal to $\\beta\\in[0,1)$. %, i.e., the transmission fails if the proportion of the transmission time subjected to interference is greater than $\\beta$.\n%\nThus, the transmission success probability is given by $p_s = \\P\\!\\left(\\overline{S_0} \\le \\beta\\right)$, where the random variable $\\overline{S_0}$ is the proportion of the packet that was affected by interference and is defined as\n\\begin{align}\\label{eq:ECC_I}\n    \\overline{S_0} \\triangleq \\frac{1}{\\tau}\\int_0^\\tau \\ind\\{I_0(t) > 0\\}\\,\\d t.\n\\end{align}\n%\n\\begin{figure}[htb]\n    \\centering\n    \\if\\printfig1\n        \\includegraphics{Figures/Ch5_PacketsRandomChannel.pdf}\n    \\else\n        \\includegraphics[draft]{Figures/Ch5_PacketsRandomChannel.pdf}\n    \\fi\n    \\caption{An early and late interfering packets with respect to the typical packet. The hachured regions correspond to packet overlapping. If $E+L>\\beta\\tau$, then the packet transmission fails.}\n    \\label{fig:P2_diagram_ECC}\n\\end{figure}%\n\n~\\\\\n\n\\begin{theorem} \\label{th:F_S0}\n    The cumulative distribution function of $\\overline{S_0}$ is\n    \\begin{align*}\n        F_{\\overline{S_0}}(x) = \n        \\begin{cases}\n            0, & \\text{if } x < 0, \\\\\n            (1 + \\upsilon\\,x)\\,\\euler^{-\\upsilon\\,(2-x)}, & \\text{if } 0 \\le x < 1,\\\\\n            1, & \\text{if } x \\ge 1,\n        \\end{cases}\n    \\end{align*}\n    where $\\upsilon = \\lambda\\tau$.\n\\end{theorem}\n%\n\\begin{proof}\n    Since $\\Pi$ is a Poisson point process on $\\R$, the inter-arrival times follow iid exponential distributions of parameter $\\lambda$. This can be shown through the void probabilities of the PPP, i.e., $\\P(\\Pi((0,t))=0) = \\euler^{-\\lambda t}$.\n    \n    Let the inter-arrival time of the early interferer and the late interferer be represented by the random variables $T_E\\sim\\mathscr{E}(\\lambda)$ and $T_L\\sim\\mathscr{E}(\\lambda)$, respectively.\n    %\n    Then, the superposition of the late interfering packet with the typical packet is given by $L = (\\tau - T_L)_+$, where $(\\cdot)_+ = \\max\\{\\cdot,0\\}$ as illustrated in Fig.~\\ref{fig:P2_diagram_ECC}. Analogously for the early interferer $E = (\\tau - T_E)_+$.\n    %\n    Thus, the cdf of $E$ and $L$ is\n    \\[\n        F_E(t) = F_L(t) = % \\ind\\{t > \\tau\\} + \\ind\\{0\\le t \\le \\tau\\} \\euler^{-\\lambda(\\tau-t)} =\n        \\begin{cases}\n            0, &\\text{if } t < 0 \\\\\n            \\euler^{-\\lambda(\\tau-t)}, &\\text{if } 0 \\le t < \\tau,\\\\\n            1, &\\text{if } t \\ge \\tau.\n        \\end{cases}\n    \\]\n    Note there is a discontinuity at $t=0$, thus the density does not exist with respect to the Lebesgue measure. Then, it is convenient to use the Lebesgue–-Stieltjes notation (Definition~\\ref{def:lebesgue-stieltjes}).\n    \n    From \\eqref{eq:ECC_I} we can see that $\\overline{S_0}\\,\\tau = \\max\\{E+L,\\tau\\}$. Thus, for $x\\in[0,1)$, we have that\n    \\begin{align*}\n        \\qquad \n        \\P(\\overline{S_0} \\le x)\n            &= \\P(\\max\\{E+L,\\tau\\} \\le x\\,\\tau) \\\\\n            &= \\P(E+L \\le x\\,\\tau) &&\\hspace{-10mm}\\text{as }\\tau > x\\,\\tau\\\\\n            &= \\int F_E(x\\,\\tau - t)\\,\\d F_L(t) &&\\hspace{-10mm}\\text{as $E$ and $L$ are independent}\\\\\n            &= \\euler^{-\\lambda(\\tau-x\\,\\tau)} \\euler^{-\\lambda\\tau} + \\int_0^{x\\,\\tau} \\euler^{-\\lambda(\\tau-x\\,\\tau+t)} \\lambda\\euler^{-\\lambda(\\tau-t)}\\d t \\\\\n            &= (1+\\lambda\\tau\\,x)\\,\\euler^{-\\lambda\\tau(2-x)}.\n    \\end{align*}\n    The cases for which $x\\notin[0,1)$ are trivial.\n\\end{proof}\n\n% Note that the random variable $\\overline{S_0}$ does not admit a density with respect to the Lebesgue measure, because of the discontinuities of the cdf at $0$ and $1$, that is why we used the Lebesgue--Stieltjes notation.\n\n\\begin{proposition}\n\tIn the ECC model, where $\\beta\\in[0,1)$, the transmission success probability and throughput is given, respectively, by\n    \\begin{align*} \\label{AlohaECC_thr}\n        p_s     &= (1 + \\beta\\,\\upsilon)\\,\\euler^{-(2-\\beta)\\,\\upsilon},\\\\\n    \t\\mathscr{T} &= \\upsilon\\,(1 + \\beta\\,\\upsilon)\\,\\euler^{-(2-\\beta)\\,\\upsilon},\n    \\end{align*}\n    where $\\upsilon = \\lambda\\tau$ is the occupation rate of the channel.\n    \n    Further, the unique and global maximum throughput is achieved when $\\upsilon = \\upsilon^*$, where\n    \\begin{equation*} \\label{AlohaECC_max}\n\t    \\upsilon^* = \\frac{\\sqrt{(2-\\beta)^2+4\\beta^2}-(2-3\\beta)}{2\\beta\\,(2-\\beta)}.\n    \\end{equation*}\n\\end{proposition}\n\\begin{proof}\n    The transmission success probability and throughput follow directly from Theorem~\\ref{th:F_S0} along with $p_s = \\P(\\overline{S_0}\\le\\beta) = F_{\\overline{S_0}}(\\beta)$ and $\\mathscr{T} = \\lambda\\tau\\,p_s$.\n    \n    Then, we use Theorem~\\ref{th:unique_opt} to verify that the throughput has a unique local maximum which is a global maximum.\n\\end{proof}\n\nIf we let $\\beta = 0$ in the ECC model we recover the unslotted ALOHA model \\cite{abramson1970aloha}.\n%\nOn the other hand, to achieve the maximum throughput of the slotted ALOHA, which is $1/\\euler$, we must have $\\beta \\approx 0.56$.\n\nFigures \\ref{fig:P2_ECC} and \\ref{fig:P2_ECC_ps} show the throughput $\\mathscr{T}$ as a function of the traffic $\\upsilon$ and as a function of the transmission success probability $p_s$, respectively.\n%\nAs expected, the throughput grows when the system is more robust (when $\\beta$ increases), even if we consider a fixed transmission success probability.\n\n\\begin{figure}[htb]\n    \\centering\n    \\if\\printfig1\n        % \\input{Plots/Ch5_ECC.tex}\n        \\includegraphics[]{Figures/Ch5_ECC.pdf}\n    \\else\n        \\includegraphics[draft, width=\\textwidth]{Figures/Ch5_ECC.pdf}\n    \\fi\n    \\caption{Throughput $\\mathscr{T}$ of the ECC model as a function of occupation rate of the channel $\\upsilon$ for different values of $\\beta$.}\n    \\label{fig:P2_ECC}\n\\end{figure}%\n%\n\\begin{figure}[htb]\n    \\centering\n    \\if\\printfig1\n        % \\input{Plots/Ch5_ECC_ps.tex}\n        \\includegraphics[]{Figures/Ch5_ECC_ps.pdf}\n    \\else\n        \\includegraphics[draft, width=\\textwidth]{Figures/placeholder.png}\n    \\fi\n    \\caption{Parametric curve of the throughput $\\mathscr{T}$ and the transmission success probability $p_s$ as we vary $\\upsilon$ in the ECC model for different values of $\\beta$.}\n    \\label{fig:P2_ECC_ps}\n\\end{figure}\n\n% % % % % % % % % % % % % % % % % % % % % \n\\section{Average Interference model}\n\\label{sec:AI_model}\n\nIn the Average Interference model (AI model) we assume that a packet is successfully transmitted if the average of the received interference does not exceed the threshold $\\beta \\ge 0$.\n%\nThus, the transmission success probability is given by $p_s = \\P(\\overline{I_0}\\le\\beta)$, where the random variable $\\overline{I_0}$ is the mean interference on the typical packet and is defined as\n\\begin{align}\\label{eq:AI_I}\n    \\overline{I_0} \\triangleq \\frac{1}{\\tau}\\int_0^\\tau I_0(t)\\,\\d t.\n\\end{align}\n\n\\begin{theorem} \\label{th:F_I0}\n    The cumulative distribution function of $\\overline{I_0}$ is given by the finite sum\n    \\begin{equation*}\n    \tF_{\\overline{I_0}}(x) = \\euler^{-2\\upsilon} \\sum_{k=0}^{\\lfloor x \\rfloor} \\dfrac{(-1)^k}{k!} \\left(\\sqrt{2\\,\\upsilon\\,(x-k)}\\right)^k \\cal{I}_k\\!\\left(\\sqrt{8\\,\\upsilon\\,(x-k)}\\right),\\quad x \\geq 0,\n    \\end{equation*}\n    where $\\cal{I}_k$ is the $k$th order modified Bessel function of the first kind\\footnote{Let $k\\in\\N$. The $k$th order modified Bessel function of the first kind is defined as \\vspace{-2mm}\\[\\cal{I}_k(x) \\triangleq \\frac{1}{\\pi}\\int_0^\\pi \\euler^{x\\cos\\theta}\\cos(k\\theta)\\,\\d\\theta,\\quad x\\in\\R.\\vspace{-3mm}\\]}, $\\lfloor \\cdot \\rfloor$ is the floor function\\footnote{The floor function returns the biggest integer less than or equal to the argument.}, and $\\upsilon = \\lambda\\tau$.\n\\end{theorem}\n\\begin{proof}\n    From \\eqref{eq:interf_I0} and \\eqref{eq:AI_I}, we have that\n    \\begin{align*}\\label{eq:AI_I}\n        \\overline{I_0} \n            &= \\frac{1}{\\tau}\\int_0^\\tau \\sum_{x\\in\\Pi} \\ind_{[0,\\tau]}(t-x)\\,\\d t \\\\\n            &= \\frac{1}{\\tau}\\sum_{x\\in\\Pi} \\int_0^\\tau  \\ind_{[0,\\tau]}(t-x)\\,\\d t \\\\\n            &= \\frac{1}{\\tau}\\sum_{x\\in\\Pi\\cap[-\\tau,\\tau]} (\\tau - |x|),\n    \\end{align*}\n    where we used the Fubini--Tonelli theorem (Theorem~\\ref{th:fubini-tonelli}) to interchange the sum with the integral, because we have positive terms.\n    %\n    Note that the term $(\\tau - |x|)$ gives the superposition time between an interfering packet and the typical packet.\n    \n    Now, using the Campbell theorem (Theorem~\\ref{th:campbell}) we have that the Laplace--Stieltjes transform of the distribution of $\\overline{I_0}$ is\n    \\begin{align*}\n    \t\\E\\!\\left[\\euler^{-s \\overline{I_0}}\\right]\t&= \\exp\\!\\left[ -\\int_{-\\tau}^\\tau(1-\\euler^{-s(1-|x|/\\tau)}) \\,\\lambda\\,dx \\right] \\\\\n        \t\t\t\t&= \\exp\\!\\left[ -2\\upsilon\\left( 1 - \\frac{1-\\euler^{-s}}{s} \\right) \\right],\\quad s\\in\\C \\backslash \\{0\\},\n    \\end{align*}\n    where we used that the traffic $\\upsilon = \\lambda\\tau$.\n    \n    Using the power series expansion of the exponential function on $\\exp(-2\\upsilon\\,\\euler^{-s}/s)$ and dividing by $s$ both sides of the equation, we can rewrite it as\n    \\begin{equation*}\n    \t\\frac{1}{s}\\E\\!\\left[\\euler^{-s \\overline{I_0}}\\right] = \\euler^{-2\\upsilon} \\sum_{k\\geq0} \\frac{(-2\\upsilon)^k}{k!} \\frac{\\euler^{2\\upsilon/s}}{s^{k+1}}\\,\\euler^{-k s},\\quad s\\in\\C \\backslash \\{0\\}.\n    \\end{equation*}\n    \n    % Para $k$ suficientemente grande, os valores absolutos dos termos dessa série podem ser limitados por cima pela função $e^-s$. Logo, podemos aplicar o teorema da convergência dominada para calcular a transformada de Laplace–Stieltjes inversa termo a termo.\n    %Aplicando a transformada inversa de Laplace–Stieltjes nos dois lados da equação e usando o Teorema da convergência dominada de Lebesgue \\cite[Teorema~1.34]{rudin1987real} para trocar o limite da soma com a transformada inversa, obtemos a c.d.f. de $\\overline{I_0}$,\n    Then, we apply the inverse Laplace–-Stieltjes transform on both sides of the equation to obtain the cdf of $\\overline{I_0}$, which concludes the proof.\n\\end{proof}\n\n\\begin{proposition}\nIn the AI model with $\\beta\\in[0,1]$, the transmission success probability and throughput is given, respectively, by\n\\begin{align*}\n    p_s &= \\cal{I}_0\\!\\left( \\sqrt{8\\,\\beta\\,\\upsilon} \\right) \\euler^{-2\\,\\upsilon},\\\\\n\t\\mathscr{T} &= \\upsilon\\,\\cal{I}_0\\!\\left( \\sqrt{8\\,\\beta\\,\\upsilon} \\right) \\euler^{-2\\,\\upsilon},\n\\end{align*}\nwhere $\\cal{I}_0$ is the zeroth order modified Bessel function of the first kind.\n\nFor $\\beta \\ge 0$, then $p_s = F_{\\overline{I_0}}(\\beta)$ and $\\mathscr{T} = \\upsilon\\,p_s$, where $F_{\\overline{I_0}}$ is given by Theorem~\\ref{th:F_I0}.\n\\end{proposition}\n\n\\begin{proof}\nWe know that the packet success probability $p_s = \\P(\\overline{I_0}\\leq \\beta) = F_{\\overline{I_0}}(\\beta)$ and throughput $\\mathscr{T} = \\upsilon\\,p_s$.\n%\nNow, note that if $\\beta\\in[0,1]$, then the sum in Theorem~\\ref{th:F_I0} consists of a single term.\n\\end{proof}\n\nSince $\\cal{I}_0(0) = 1$, we recover the classical result of the unslotted ALOHA for $\\beta = 0$ as expected.\n%\nOn the other hand, to achieve the maximum throughput of the slotted ALOHA, we need to have $\\beta\\approx0.621$.\n\nAnalogously to the ECC model, Figures \\ref{fig:P2_AI} and \\ref{fig:P2_AI_ps} show the throughput $\\mathscr{T}$ as a function of the traffic $\\upsilon$ and as a function of the transmission success probability $p_s$, respectively.\n%\nAgain, we observe the same behavior that the throughput grows when the system is more robust ($\\beta$ increases).\n\nFurthermore, for the same $\\beta$ and $\\upsilon$, we have that the transmission success probability of the ECC model is bigger than the one of the AI model. This happens because $\\overline{S_0} \\le \\overline{I_0}$.\n\n\\begin{figure}[htb]\n    \\centering\n    \\if\\printfig1\n        % \\input{Plots/Ch5_AI.tex}\n        \\includegraphics[]{Figures/Ch5_AI.pdf}\n    \\else\n        \\includegraphics[draft, width=\\textwidth]{Figures/placeholder.png}\n    \\fi\n    \\caption{Throughput $\\mathscr{T}$ of the AI model as a function of occupation rate of the channel $\\upsilon$ for different values of $\\beta$.}\n    \\label{fig:P2_AI}\n\\end{figure}%\n%\n\\begin{figure}[htb]\n    \\centering\n    \\if\\printfig1\n        % \\input{Plots/Ch5_AI_ps.tex}\n        \\includegraphics[]{Figures/Ch5_AI_ps.pdf}\n    \\else\n        \\includegraphics[draft, width=\\textwidth]{Figures/placeholder.png}\n    \\fi\n    \\caption{Parametric curve of the throughput $\\mathscr{T}$ and the transmission success probability $p_s$ as we vary $\\upsilon$ in the AI model for different values of $\\beta$.}\n    \\label{fig:P2_AI_ps}\n\\end{figure}\n\n% % % % % % % % % % % % % % % % % % % % % \n\\section{High Interference model}\n\\label{sec:HI_model}\n\nIn the High Interference model (HI model) we assume that a packet is successfully transmitted if the proportion of the packet that was affected by \\textit{high interference} is smaller than or equal to $\\beta\\in[0,1]$. We define the period of \\textit{high interference} as the times for which the number of interfering packets is greater than a threshold $h\\in\\N$.\n\nThus, the transmission success probability is given by $p_s = \\P\\!\\left(\\overline{S_h} \\le \\beta\\right)$, where $\\overline{S_h}$ is the proportion of time the typical packet was affected by \\textit{high interference} and is defined as\n\\begin{align}\\label{eq:Sh_def}\n    \\overline{S_h} \\triangleq \\frac{1}{\\tau}\\int_0^\\tau \\ind\\{I_0(t) > h\\}\\,\\d t.\n\\end{align}\n\nConsidering every $h\\in\\N$, the distribution of the random variable $\\overline{S_h}$ would provide a thorough characterization of the stochastic process $\\{I(t)\\}_t$,\n%\nbecause it would capture every interference level and the distribution of its duration in the typical packet.\n%\nHowever, as we shall see, the distribution of $\\overline{S_h}$ is quite intricate.\n\n\\begin{remark} \\label{remark:Ch5_ineq}\n    The HI model is a generalization of the ECC model because we recover the latter by making $h=0$ in the former.\n    %\n    Also, one can show that the HI model is related to the AI model through the following identity\n    \\begin{align*}\n        \\sum_{h\\ge 0} \\overline{S_h} = \\overline{I_0}.\n    \\end{align*}\n    Furthermore, $\\overline{S_0} \\ge \\overline{S_1} \\ge \\cdots$.\n\\end{remark}\n\nLet the number of interferers that start transmitting during the transmission of the typical packet be represented by the random variable $LI$ (late interferers) and the number of interferers that stop transmitting during the transmission of the typical packet be represented by the random variable $EI$ (early interferers), i.e.,\n\\begin{align*}\n    EI \\triangleq I_0(0) \\sim \\mathscr{P}(\\lambda\\tau), \\qquad LI \\triangleq I_0(\\tau) \\sim \\mathscr{P}(\\lambda\\tau).\n\\end{align*}\nThen, since $\\Pi$ is a Poisson point process, it is easy to see that $EI$ and $LI$ are independent and follow a Poisson distribution of parameter $\\upsilon = \\lambda\\tau$.\n\nLet $(t_k)_{k=1}^{EI+LI}$ be the sequence of times for which an interferer stops or starts a transmission.\n%\nThen, it is possible to uniquely determine $\\{I(t)\\}_t$ from the sequences $(t_1,\\dots,t_{EI+LI})$ and $(I(0),I(t_1),\\dots,I(t_{EI+LI}))$.\n%\nFurthermore, the proportion of time the typical packet was affected by \\textit{high interference} can be written as\n\\begin{align} \\label{eq:ch5_Sh}\n    \\overline{S_h}\n        &= \\sum_{k=0}^{EI+LI} \\dfrac{\\Delta t_k}{\\tau}\\,\\ind{\\{I(t_k) > h\\}},\n\\end{align}\nwhere $\\Delta t_k \\triangleq t_{k+1} - t_{k}$ and we use $t_0 = 0$, $t_{EI+LI+1} = \\tau$.\n\nGiven $EI = k$ and $LI = l$, the distribution of the $k+l$ times of starting or stopping a transmission are independent and uniformly distributed on $[0,\\tau)$. \n\\begin{note}\n    We can check the above-mentioned property by showing the random variable that represents the number of points of the PPP that are in a subset $T$ of $[0,\\tau)$ follow a binomial distribution of parameters $(k+l,\\mu(T))$, where $\\mu(T)$ is the length of the subset.\n    \n    To prove this property in a more general form, it is enough to show that for every $A,B\\in\\cal{B}(\\R)$ such that $A\\subset B$ the random variable $\\Pi(A)|\\Pi(B)$ follows a binomial distribution of parameters $(\\Pi(B), \\mu(A)/\\mu(B))$ , where $\\mu$ is the Lebesgue measure.\n\\end{note}\n\nFurther, the random vector $(I(t_i))_{i=0}^{k+l}$ is a symmetric Bernoulli random walk\\footnote{A symmetric Bernoulli random walk is a random walk on $\\Z$ that performs unitary steps and each step has equal probability of being $+1$ or $-1$.} subject to begin at $k$ and end at $l$ with $k+l$ steps.\n%\n% In this random walk, every path is equiprobable.\nThe total number of different paths is given by the binomial coefficient $\\binom{k+l}{k}$.\n%\nWe are interested to know how many of these paths stay a total number of $m\\in\\N$ steps above the threshold $h$. Let us denote the number of paths that satisfy this as $C_{k,l}^{h,m}\\in\\N$.\n%\nFormally, we can write that\n\\begin{align} \\label{eq:Ch5_Cklhm}\n    C_{k,l}^{h,m} \\triangleq \\sum_{\\bm{x}\\in\\mathscr{X}_{k,l}}\\ind\n        \\!\\left\\{ \\sum_{i=0}^{k+l} \\ind\\{x_i > h\\} = m\\right\\},\n\\end{align}\nwhere $\\mathscr{X}_{k,l} \\subset \\N^{k+l+1}$ is the set that contains all paths from $k$ to $l$ with $k+l$ unit steps.\n\nNow we can express the probability of having exactly $m$ times of the random vector $(t_i)_{i=0}^{k+l}$ for which the typical packet is affected by an interference greater than $h$ as $C_{k,l}^{h,m}/\\binom{k+l}{k}$.\n\nFig.~\\ref{fig:random_walk} illustrate some random walks that starts at $k=5$ and end at $l=3$ in $k+l=8$ steps. We show $3$ of the $\\binom{8}{3} = 56$ possible paths.\n%\nNote that for this case, the only path that surpass $h=7$ (\\textit{high interference}) is the red path and it stays above $h$ for only $m=1$ step.\n%\nIndeed, $C_{5,3}^{7,m} = \\ind\\{m=1\\}$, thus there is only one path that does that.\n\\begin{figure}[htb]\n\\centering\n    \\if\\printfig1\n        \\includegraphics[width=0.45\\textwidth]{Figures/Ch5_RandomWalk.pdf}\n    \\else\n        \\includegraphics[draft, width=0.5\\textwidth]{Figures/Ch5_RandomWalk.pdf}\n    \\fi\n\t\\caption{Examples of random walks starting at $k=5$ and finishing at $l = 3$.}\n\t\\label{fig:random_walk}\n\\end{figure}\n%\nIt is worth remembering that in the original problem the $i$th step of the random walk stays in the corresponding state a time given by the random variable $\\Delta t_i$.\n\nDifferent from the other models, the HI model is much more complex, because the calculation of $C_{k,l}^{h,m}$ is done case by case despite having a (strictly speaking) \\textit{closed form} expression.\n%\nAs we shall see, we need $C_{k,l}^{r,m}$ for an infinite number of argument combinations and, then, we stumble upon a difficult problem.\n\n\\begin{remark} \\label{rem:Ch5_Crmkl}\n    On the other hand, we can find simple formulas for some special argument values of $C_{k,l}^{r,m}$ as follows.\n    \\begin{itemize}\n        \\item $C_{k,l}^{r,m} = C_{l,k}^{r,m}$ by symmetry;\n        \n        \\item If $k\\leq r$ and $l\\leq r$, then $C_{k,l}^{r,0} = \\binom{k+l}{k} - \\binom{k+l}{r+1}$ by the reflection method \\cite{feller1968introduction};\n        \n        \\item If $k>r$ and $l>r$, then $C_{k,l}^{r,k+l+1} = \\binom{k+l}{k} - \\binom{k+l}{r}$ by the reflection method again;\n        \n        \\item If $k\\leq r$ and $k+l-(r-k) \\leq m \\leq k+l$, then $C_{k,l}^{r,m}=0$,\n    \\end{itemize}\n    where we consider the binomial coefficient $\\binom{n}{k} = 0$ when $k \\notin \\{0,1,\\dots,n\\}$.\n\\end{remark}\n\nAssuming that we have $m$ intervals of time with \\textit{high interference}, then we need to find the probability that the sum of $m$ intervals of \\textit{high interference} is smaller or equal than $\\beta\\tau$, which is the condition for successful transmission.\n%\nIndeed, we have that\n\\[\n    \\P(\\Delta t_0 + \\Delta t_1 + \\cdots + \\Delta t_{m-1} \\leq \\beta\\tau) = \\cal{P}_{k+l,m}(\\beta),\n\\]\nwhere\n\\begin{align} \\label{eq:Ch5_Pdef}\n    \\cal{P}_{n,m}(x) \\triangleq\n    \\begin{cases}\n        \\ind\\{m = 0\\}, &\\text{if } x = 0,\\\\\n        \\displaystyle\\sum_{i=m}^{n} \\binom{n}{i}x^i(1-x)^{n-i}, &\\text{if } x\\in(0,1),\\\\\n        1, &\\text{if } x = 1,\n    \\end{cases}\n\\end{align}\nbecause we have $k+l$ independent random variables uniformly distributed on $[0,\\tau)$ and we want that at least $m$ of them are in the interval $[0,\\beta\\tau]$.\n%\nFrom order statistics theory we can generalize this result to\n\\begin{align} \\label{eq:ch5_Pdeltat}\n\t\\P(\\Delta t_{\\nu(0)} + \\Delta t_{\\nu(1)} + \\cdots + \\Delta t_{\\nu(m-1)} \\leq \\beta\\tau) = \\cal{P}_{k+l,m}(\\beta),\n\\end{align}\nwhere $\\nu:\\{0,1,\\cdots,m-1\\} \\longrightarrow \\{0,1,\\cdots,k+l\\}$ is an arbitrary injective function.\n%\nThis takes into account the cases where the intervals of \\textit{high interference} are not contiguous.\n\nFinally, we can conclude from \\eqref{eq:ch5_Sh} and \\eqref{eq:ch5_Pdeltat} that\n\\begin{align} \\label{eq:Ch5_Sh_EIEL}\n    \\P(\\overline{S_h} \\leq x~|~EI=k,LI=l) \n\t    &= \\sum_{m=0}^{k+l+1} \\dfrac{C_{k,l}^{r,m}}{\\binom{k+l}{k}} \\cal{P}_{k+l,m}(x), \\quad x\\in[0,1].\n\\end{align}\n\nNow, we are prepared to prove the following theorem.\n\\begin{theorem} \\label{th:F_Sh}\n    The cumulative distribution function of $\\overline{S_h}$, $h\\in\\N$, is\n    \\begin{align*}\n        F_{\\overline{S_h}}(x)\n            &= \\euler^{-2\\upsilon} \\sum_{n \\geq 0} \\frac{\\upsilon^n}{n!} \\sum_{m=0}^{n+1}  \\cal{P}_{n,m}(x) \\sum_{k=0}^n C^{h,m}_{k,n-k}, \\quad x\\in[0,1],\n    \\end{align*}\n    where $\\upsilon = \\lambda\\tau$, $C$ is defined in \\eqref{eq:Ch5_Cklhm} and $\\cal{P}$ is defined in \\eqref{eq:Ch5_Pdef}.\n    \n    Further, we can express the probabilities at the discontinuities of $F_{\\overline{S_h}}$ in \\textit{closed form}:\n    \\begin{align*}\n        \\P(\\overline{S_h}=0) \n            &= \\left( f_{h}(\\upsilon) \\right)^2 + (\\upsilon-h) \\frac{\\upsilon^{h+1}\\euler^{-\\upsilon}}{(h+1)!} f_{h}(\\upsilon)  - \\dfrac{\\upsilon^{2(h+1)}\\euler^{-2 \\upsilon}}{h!(h+1)!},\\\\\n        \\P(\\overline{S_h}=1) \n            &= \\left( 1 - f_{h}(\\upsilon) \\right)^2 + (h+1-\\upsilon) \\left( 1 - f_{h-1}(\\upsilon) \\right) \\frac{\\upsilon^h \\euler^{-\\upsilon}}{h!} -(h+1)\\frac{\\upsilon^{2h}\\euler^{-2\\upsilon}}{(h!)^2},\n    \\end{align*}\n    where $f_h(\\upsilon)\\triangleq \\euler^{-\\upsilon}\\displaystyle\\sum_{k=0}^{h}\\frac{\\upsilon^h}{h!}$.\n\\end{theorem}\n\\begin{proof}\n    We know that the random variables $EI$ and $LI$ follow a Poisson distribution of parameter $\\upsilon=\\lambda\\tau$. Thus, we can decondition \\eqref{eq:Ch5_Sh_EIEL} on $EI$ and $LI$ to obtain, for $x\\in[0,1]$,\n    \\begin{align}\n    \t\\P(\\overline{S_h} \\leq x)\n    \t    &= \\euler^{-2\\upsilon}\\sum_{k \\geq 0}\\sum_{l \\geq 0} \\frac{\\upsilon^{k+l}}{k!l!}\\sum_{m=0}^{k+l+1} \\dfrac{C_{k,l}^{r,m}}{\\binom{k+l}{k}} \\cal{P}_{k+l,m}(x) \\label{eq:Ch5_F_Sh_aux1}\\\\\n    \t\t&= \\euler^{-2\\upsilon}\\sum_{k \\geq 0}\\sum_{l \\geq 0} \\frac{\\upsilon^{k+l}}{(k+l)!}\\sum_{m=0}^{k+l+1} C_{k,l}^{r,m} \\cal{P}_{k+l,m}(x) \\label{eq:Ch5_F_Sh_aux2}\\\\\n        \t&= \\euler^{-2\\upsilon}\\sum_{n \\geq 0} \\sum_{m=0}^{n+1}  \\sum_{k=0}^n C^{r,m}_{k,n-k} \\cal{P}_{n,m}(x)  \\frac{\\upsilon^n}{n!},\n    \\end{align}\n    where we performed the variable change $l=n-k$ and we can interchange the sums because all terms are positive (Fubini–-Tonelli theorem, Theorem~\\ref{th:fubini-tonelli}).\n    %\n    This proves the first result because $F_{\\overline{S_h}}(x) = \\P(\\overline{S_h} \\le x).$\n    \n    Now, using \\eqref{eq:Ch5_F_Sh_aux2} and Remark~\\ref{rem:Ch5_Crmkl} we have that\n    \\begin{align*}\n    \\P(\\overline{S_h} = 0)\n    \t &= \\euler^{-2\\upsilon}\\sum_{k \\geq 0}\\sum_{l \\geq 0} \\frac{\\upsilon^{k+l}}{(k+l)!}\\sum_{m=0}^{k+l} C_{k,l}^{h,m} \\cal{P}_{k+l,m}(0)\\\\\n         &= \\euler^{-2\\upsilon}\\sum_{k \\geq 0}\\sum_{l \\geq 0} \\frac{\\upsilon^{k+l}}{(k+l)!} C_{k,l}^{h,0}\\\\\n         &= \\euler^{-2\\upsilon}\\sum_{k \\geq 0}\\sum_{l \\geq 0} \\frac{\\upsilon^{k+l}}{(k+l)!} \\left( \\binom{k+l}{k} - \\binom{k+l}{h+1} \\ind_{\\{k+l > h\\}} \\right)\\ind_{\\{k \\leq h\\}}\\ind_{\\{l \\leq h\\}}\\\\\n         &= \\euler^{-2\\upsilon}\\sum_{k = 0}^h \\sum_{l = 0}^h \\frac{\\upsilon^{k+l}}{k!l!} \\left( 1 - \\frac{\\binom{k+l}{h+1}}{\\binom{k+l}{k}} \\right).\n    \\end{align*}\n    %\n    Now, using $f_h$ and some tedious manipulations we find the \\textit{closed form} of $\\P(\\overline{S_h} = 0)$.\n    \n    Using \\eqref{eq:Ch5_F_Sh_aux1} and Remark~\\ref{rem:Ch5_Crmkl} we have that\n    \\begin{align*}\n\t\\P(\\overline{S_h}=1)\n\t    &= F_{\\overline{S_h}}(1) - \\lim_{x\\uparrow 1} F_{\\overline{S_h}}(x)\\\\\n    \t&= \\euler^{-2\\upsilon}\\sum_{k > 0}\\sum_{l > 0} \\frac{\\upsilon^{k+l}}{k!l!} \\dfrac{C_{k,l}^{h,k+l+1}}{\\binom{k+l}{k}}\\\\\n    \t&= \\euler^{-2\\upsilon} \\sum_{k > 0}\\sum_{l > 0} \\frac{\\upsilon^{k+l}}{k!l!} \\left( 1 - \\frac{\\binom{k+l}{h}}{\\binom{k+l}{k}} \\right)\\ind_{\\{k>h\\}}\\ind_{\\{l>h\\}}\\\\\n    \t&= \\euler^{-2\\upsilon} \\sum_{k > h}\\sum_{l > h} \\frac{\\upsilon^{k+l}}{k!l!} \\left( 1 - \\frac{\\binom{k+l}{h}}{\\binom{k+l}{k}} \\right).\n    \\end{align*}\n    %\n    Again, using $f_h$ and some tedious manipulations we find the \\textit{closed form} of $\\P(\\overline{S_h} = 1)$.\n\\end{proof}\n\nUsing Theorem~\\ref{th:F_Sh} we can find simple expressions for the probability of not receiving \\textit{high interference} at all during a typical packet transmission, i.e., $\\P(\\overline{S_h} = 0)$, for $h=0,1,2,\\dots$.\n%\n\\begin{align*}\n    \\P(\\overline{S_0} = 0) &= \\euler^{-2\\,\\upsilon},\\\\\n    \\P(\\overline{S_1} = 0) &= \\left( 1+2\\upsilon+{\\upsilon}^{2}/2 \\right){\\euler^{-2\\,\\upsilon}} ,\\\\\n    \\P(\\overline{S_2} = 0) &= \\left( 1+2\\,\\upsilon+2\\,\\upsilon^2+(2/3)\\,\\upsilon^3+(1/12)\\,\\upsilon^4 \\right){{\\euler}^{-2\\,\\upsilon}},\\\\\n                &~\\,\\vdots\\\\\n    \\P(\\overline{S_h} = 0) &= \\frac{\\upsilon^{2h}\\euler^{-2\\upsilon}}{h!(h+1)!} + \\cal{O}(\\upsilon^{2h-1}\\euler^{-2\\upsilon}), \\quad \\text{as } \\upsilon\\to\\infty.\n\\end{align*}\n\nThe same can be done for the case of receiving \\textit{high interference} during all transmission, i.e., $\\P(\\overline{S_h} = 1)$.\n%\n\\begin{align*}\n    \\P(\\overline{S_0} = 1) &= 1 - (1+\\upsilon)\\,\\euler^{-\\upsilon},\\\\\n    \\P(\\overline{S_1} = 1) &= (1-\\euler^{-\\upsilon})^2 - \\upsilon^2\\,\\euler^{-\\upsilon},\\\\\n    \\P(\\overline{S_2} = 1) &= (1-(1+\\upsilon)\\,\\euler^{-\\upsilon})^2 + (1-\\upsilon-\\euler^{-\\upsilon})\\,\\frac{\\upsilon^2}{2}\\,\\euler^{-\\upsilon},\\\\\n        &~\\,\\vdots\\\\\n    \\P(\\overline{S_h} = 1) &= 1 - \\frac{\\upsilon^{h+1}}{h!}\\,\\euler^{-\\upsilon} + \\cal{O}\\left(\\upsilon^h\\euler^{-\\upsilon}\\right), \\quad \\text{as } \\upsilon\\to\\infty.\n\\end{align*}\n\n\\begin{figure}[htb]\n    \\centering\n    \\if\\printfig1\n        \\begin{subfigure}{.45\\textwidth}\n          \\centering\n            % \\input{Plots/Ch5_HI_0.tex}\n            \\includegraphics[width=\\columnwidth]{Figures/Ch5_HI_0.pdf}\n            % \\caption{$\\beta = 0$.}\n        \\label{fig:HI_0}\n        \\end{subfigure}%\n        \\begin{subfigure}{.05\\textwidth}\n        \\hspace{.05\\textwidth}\n        \\end{subfigure}%\n        \\begin{subfigure}{.45\\textwidth}\n          \\centering\n            % \\input{Plots/Ch5_HI_1.tex}\n            \\includegraphics[width=\\columnwidth]{Figures/Ch5_HI_1.pdf}\n            % \\caption{$\\beta \\uparrow 1$.}\n        \\label{fig:HI_1}\n        \\end{subfigure}\n    \\else\n        \\includegraphics[draft, width=\\textwidth]{Figures/placeholder.png}\n    \\fi\n    \\caption{Transmission success probability $p_s$ as a function of traffic $\\upsilon$ in the HI model. The blue and red curves represent the slotted and unslotted ALOHA, respectively.} \\label{fig:HI}\n\\end{figure}\n\nAs shown in the plots of Fig.~\\ref{fig:HI}, the transmission success probability $p_s$ increases with $h$, because more concurrent interfering transmissions are necessary to cause \\textit{high interference} in the typical packet transmission.\n\nWhen we fix the threshold $h$ and let the traffic $\\upsilon\\to\\infty$, we have that ${\\P(\\overline{S_h}=0)=0}$ and $\\P(\\overline{S_h}=1)=1$.\n%\nOn the other hand, when we fix $\\upsilon$ and let $h\\to\\infty$, then ${\\P(\\overline{S_h}=0)=1}$ and $\\P(\\overline{S_h}=1)=0$.\n%\nThus, an interesting scenario to analyse is what happens when we increase the traffic $\\upsilon$ along with the threshold $h$, i.e., let $\\upsilon\\to\\infty$ and $h\\to\\infty$ such that $\\frac{h}{\\upsilon} \\to 1$.\n%\nIn this case we can show that\n\\begin{align*}\n   \\lim_{\\substack{h,\\upsilon\\to\\infty\\\\ h/\\upsilon\\to1}} \\P(\\overline{S_h} = 0) &=  \\lim_{\\substack{h,\\upsilon\\to\\infty\\\\ h/\\upsilon\\to1}} \\P(\\overline{S_h} = 1) = \\frac{1}{4}\\left( 1 - \\frac{2}{\\pi}\\right) \\approx 0.091.\n\\end{align*}\n\n\\begin{note}\n    To find the above result it is necessary to calculate an interesting limit problem, which cannot be solved through standard techniques, indeed the Software \\textit{Mathematica} (version 12) does not solve it. In a simpler form, the problem is to show that\n    \\begin{align*}\n        \\lim_{n\\to\\infty} f_n(n) = \\lim_{n\\to\\infty} \\frac{\\Gamma(n,n)}{\\Gamma(n)} = \\frac{1}{2},\n    \\end{align*}\n    where $\\Gamma(\\cdot,\\cdot)$ is the incomplete gamma function and is defined as $\\Gamma(s,x)\\triangleq \\int_{x}^\\infty t^{s-1} \\euler^{-t}\\,\\d t$, and $\\Gamma(\\cdot) \\triangleq \\Gamma(\\cdot,0)$ is the gamma function.\n    \n    To prove this identity we use the central limit theorem!\n    \n    Let $\\{X_k\\}_k$ be iid exponentially distributed random variables with parameter $1$. Let the sum $S_n = \\sum_{k=1}^n X_k$, then $S_n$ follows an Erlang distribution of parameters $(n,1)$. Then, $\\P(S_n > n) = \\frac{\\Gamma(n,n)}{\\Gamma(n)}$. However, $\\P(S_n > n) = \\P(\\frac{S_n-n}{\\sqrt{n}} > 0) \\xrightarrow{n\\to\\infty} 1/2$ by the central limit theorem.\n\\end{note}\n\nTo conclude this part, let us state the following inequalities, for $\\beta > 0$, $\\upsilon > 0$, $h\\ge 0$,\n\\begin{align*}\n    p_s^{\\mathrm{(ALOHA)}} &\\le p_s^{\\mathrm{(ECC)}} \\le p_s^{\\mathrm{(AI)}} \\le p_s^{\\mathrm{(HI)}},\\\\\n    \\mathscr{T}^{\\mathrm{(ALOHA)}} &\\le \\mathscr{T}^{\\mathrm{(ECC)}} \\le \\mathscr{T}^{\\mathrm{(AI)}} \\le \\mathscr{T}^{\\mathrm{(HI)}},\n\\end{align*}\nwhich are easily obtained from Remark~\\ref{remark:Ch5_ineq} and the definitions of throughput and transmission success probability.\n\n% % % % % % % % % % % % % % \n\\section{Summary} \\label{sec:summ_P2_01}\n\nIn this chapter, we characterized the distribution of the interference in a typical packet, where interferers transmit according to a Poisson process.\n%\nThe characterization was performed through the analysis of some transmission success models (ECC, AI, HI), for which we obtained the throughput and the transmission success probability in closed form.\n%\nWe also compared the obtained distributions with those of the slotted/unslotted ALOHA.\n", "meta": {"hexsha": "8af6c7f787f4ac238ea7fefe69bf8a81f218d73c", "size": 39186, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "P2_01.tex", "max_stars_repo_name": "pliniodester/PhD_thesis", "max_stars_repo_head_hexsha": "65b00b31ebdac9dda68b1e83e937fcaed92ce354", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "P2_01.tex", "max_issues_repo_name": "pliniodester/PhD_thesis", "max_issues_repo_head_hexsha": "65b00b31ebdac9dda68b1e83e937fcaed92ce354", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "P2_01.tex", "max_forks_repo_name": "pliniodester/PhD_thesis", "max_forks_repo_head_hexsha": "65b00b31ebdac9dda68b1e83e937fcaed92ce354", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 65.6381909548, "max_line_length": 487, "alphanum_fraction": 0.6609503394, "num_tokens": 13170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3266777688084485}}
{"text": "% BEGIN LICENSE BLOCK\n% Version: CMPL 1.1\n%\n% The contents of this file are subject to the Cisco-style Mozilla Public\n% License Version 1.1 (the \"License\"); you may not use this file except\n% in compliance with the License.  You may obtain a copy of the License\n% at www.eclipse-clp.org/license.\n% \n% Software distributed under the License is distributed on an \"AS IS\"\n% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.  See\n% the License for the specific language governing rights and limitations\n% under the License. \n% \n% The Original Code is  The ECLiPSe Constraint Logic Programming System. \n% The Initial Developer of the Original Code is  Cisco Systems, Inc. \n% Portions created by the Initial Developer are\n% Copyright (C) 2006 Cisco Systems, Inc.  All Rights Reserved.\n% \n% Contributor(s): \n% \n% END LICENSE BLOCK\n\n\\chapter{Propia and CHR}\n\\label{chappropiachr}\n%HEVEA\\cutdef[1]{section}\n\n\\section{Two Ways of Specifying Constraint Behaviours}\nThere are two elegant and simple ways of building constraints\navailable in \\eclipse{}, called {\\em Propia} and {\\em Constraint\nHandling Rules} (or {\\em CHR}'s).  \nThey are themselves built using the facilities\ndescribed in chapter \\ref{chapimpl}.\n\n\\index{noclash}\nConsider a simple {\\em noclash} constraint requiring that two\nactivities cannot be in progress at the same time.  \nFor the sake of the example, the constraint involves two variables,\nthe start times $S1$ and $S2$ \nof the two activities, which both have duration $5$.\nLogically this constraint states that\n{\\em noclash} $ \\Leftrightarrow (S1 >= S2 + 5 \\vee S2 >= S1 + 5)$.\nThe same logic can be expressed as two \\eclipse{} clauses:\n\\begin{code}\nnoclash(S1,S2) :-\n    ic:(S1 \\$>= S2+5).\nnoclash(S1,S2) :-\n    ic:(S2 \\$>= S1+5).\n\\end{code}\nConstraint propagation elicits information from constraints without\nleaving any choice points.  Constraint propagation behaviour can be\nassociated with each of the above representations, by CHR's\nand by Propia.\n\nOne way to propagate information from {\\em noclash} is to wait until\nthe domains of the start times are reduced sufficiently that only one\nordering of the tasks is possible, and then to enforce the constraint\nthat the second task not start until the first is finished.\n\n\\index{constraints/1}\nThis behaviour can be implemented in CHR's as follows:\n\\begin{code}\n:- constraints noclash/2.\nnoclash(S1,S2) <=> ic:(S2 #< S1+5) | ic:(S1 #>= S2+5).\nnoclash(S1,S2) <=> ic:(S1 #< S2+5) | ic:(S2 #>= S1+5).\n\\end{code}\n\nConsider the query:\n\\begin{quote}\n\\begin{verbatim}\n?- ic:([S1,S2]::1..10),\n   noclash(S1,S2),\n   S1 #>= 6.\n\\end{verbatim}\n\\end{quote}\nIn this query {\\em noclash} achieves no propagation when it is\ninitially posted with the start time domains set to \\verb91..109.\nHowever, after imposing $S1>=6$, \nthe domain of $S1$ is reduced to \\verb96..109.\nImmediately the {\\em noclash}\nconstraint wakes, detects that the first\ncondition $S1+5 >= S2$ is entailed, \nand narrows the domain of $S2$ to \\verb91..59.\n\nThe same behaviour can be expressed in Propia, but this time the\noriginal \\eclipse{} representation of {\\em noclash} as two clauses is\nused directly.  The propagation behaviour is automatically\nextracted from the two clauses by Propia when the {\\em noclash} goal\nis annotated as follows:\n\\begin{quote}\n\\begin{verbatim}\n?-      [S1,S2]::1..10,\n        noclash(S1,S2) infers most,\n        S1 #>= 6.\n\\end{verbatim}\n\\end{quote}\n%For readability \\verb0infers0 is declared to be an infix operator,\n%enabling the annotation to be written thus: \n%\\begin{quote}\n%\\begin{verbatim}\n%?- [S1,S2]::1..10, noclash(S1,S2) infers most, S1 #>= 6\n%\\end{verbatim}\n%\\end{quote}\n\n\\quickref{Building Constraints without Tears}{\nPropia and CHRs make it easy to turn the logical statement of a\nconstraint into code that efficiently enforces that constraint.\n}\n\n\\section{The Role of Propia and CHR in Problem Modelling}\n\n\\index{modelling}\nTo formulate and solve a problem in \\eclipse{} the standard pattern is\nas follows:\n\\begin{enumerate}\n\\item Initialise the problem variables\n\\item State the constraints\n\\item Specify the search behaviour\n\\end{enumerate}\nVery often, however, the constraints involve logical implications or\ndisjunctions, as in the case of the {\\em noclash} constraint above.   \nSuch constraints are most naturally formulated in a way that would\nintroduce choice points during the constraint posting phase. \nThe two \\eclipse{} clauses defining {\\em noclash}, above, are a case in\npoint. \n\nThere are two major disadvantages of introducing choice points during\nconstraint posting:\n\\begin{itemize}\n\\item Posting and reposting constraints during search is an\nunnecessary and computationally expensive overhead\n\\item Mixing constraint behaviour and search behaviour makes it harder\nto explore and optimize the algorithm executed by the program.\n\\end{itemize}\nPropia and CHR's support the separation of constraint setup and search\nbehaviour, by allowing constraints to be formulated naturally without\ntheir execution setting up any choice points.\n\nThe effect on performance is illustrated by the following small\nexample.\nThe aim is to choose a set of $9$ products (\\verb0Products0,\nidentified by their product number 101-109) to\nmanufacture, with a \nlimited quantity of raw materials (\\verb0Raw10 and \\verb0Raw20), \nso as to achieve a profit (\\verb0Profit0) of over\n$40$.  \nThe amount of raw materials (of two kinds) needed to produce\neach product is listed in a table, together with its profit.\n\n\\index{product\\_plan}\n\\index{product}\n\\begin{code}\nproduct_plan(Products) :-\n    length(Products,9),\n    Raw1 #=< 95,\n    Raw2 #=< 95,\n    Profit #>= 40,\n    sum(Products,Raw1,Raw2,Profit),\n    labeling(Products).\n\nproduct( 101,1,19,1).  product( 102,2,17,2).  product( 103,3,15,3).\nproduct( 104,4,13,4).  product( 105,10,8,5).  product( 106,16,4,4).\nproduct( 107,17,3,3).  product( 108,18,2,2).  product( 109,19,1,1).\n\nsum(Products,Raw1,Raw2,Profit) :-\n    ( foreach(Item,Products),\n      foreach(R1,R1List),\n      foreach(R2,R2List),\n      foreach(P,PList)\n    do\n        product(Item,R1,R2,P)\n    ),\n    Raw1 #= sum(R1List),\n    Raw2 #= sum(R2List),\n    Profit #= sum(PList).\n\n\\end{code}\n\nThe drawback of this program is that the \\verb0sum0 constraint calls\n\\verb0product0 which chooses an item and leaves a choice point at each\ncall. \nThus the setup of the \\verb0sum0 constraint leaves $9$ choice points.\nTry running it, and the program\nfails to terminate within a reasonable amount of time.\n\nNow to make the program run efficiently, we can simply annotate the call\nto \\verb0product0 as a Propia constraint making:\n\\verb0product(Item,R1,R2,P) infers most0.\nThis program leaves no choice points during constraint setup, and\nfinds a solution in a fraction of a second.\n\nIn the remainder of this chapter we show how to use Propia and CHR's,\ngive some \nexamples, and outline their implementation.\n\n\\quickref{Modelling without Choice Points}{\nPropia and CHRs can be used to build clear problem models that have no\n(hidden) choice points.\n}\n\n\\section{Propia}\n\\label{secpropia}\n\n\\index{propia}\n\\index{generalised propagation}\nPropia is an implementation of {\\em Generalised Propagation}\nwhich is described in the paper  \\cite{LeProvost93b}.\n\n\\subsection{How to Use Propia}\n\\index{infers/2}\nIn principle Propia propagates information from an annotated goal by\nfinding all solutions to the goal and extracting any information that\nis common to all the different solutions.\n(In practice, as we shall see later, Propia does not typically need to\nfind all the solutions.)\n\nThe ``common'' information that can be extracted depends upon what\nconstraint solvers are used when evaluating the underlying\nun-annotated \\eclipse{} goal.  To illustrate this, consider another\nsimple example.\n\n\\begin{quote}\n\\begin{verbatim}\np(1,3).\np(1,4).\n\n?-  p(X,Y) infers most.\n\\end{verbatim}\n\\end{quote}\nIf the {\\tt ic} library is not loaded when this query is\ninvoked, then the information propagated by Propia is that $X=1$.\nIf, on the other hand, {\\tt ic} is loaded, then more common\ninformation is propagated.  Not only does Propia propagate $X=1$ but\nalso the domain of $Y$ is tightened from \\verb0-inf..inf0 to \n\\verb03..40. (In this case the additional common information is that\n$Y \\neq  0$, $Y \\neq 1$, $Y \\neq 2$ and so on for all values except $3$\nand $4$!)\n\n\\index{most}\n\\index{consistent}\n\\index{unique}\n\\index{ac}\nAny goal \\verb0Goal0 in an \\eclipse{} program, can be transformed into a\nconstraint by annotating it thus: \\verb0Goal infers Parameter0.\nDifferent behaviours can be specified with different parameters, viz:\n\\begin{itemize}\n\\item \\verb0Goal infers most0\\\\\nPropagates all common information produced by the loaded solvers\n\\item \\verb0Goal infers unique0\\\\\nFails if there is no solution, propagates the solution if it is\nunique, and succeeds without propagating further information if there\nis more than one solution.\n\\item \\verb0Goal infers consistent0\\\\\nFails if there is no solution, and propagates no information otherwise \n\\end{itemize}\n\n%\\item \\verb0Goal infers ic0\\\\\n%Tightens the domains of the variables.  \n%\\item \\verb0Goal infers ac0\\\\\n%Tightens the domains of the variables: more efficient than \\verb0ic0,\n%but can only handle goals with a finite set of ground answers.\n\n\\index{crossword}\nThese behaviours are nicely illustrated by the crossword demonstration\nprogram \\verb0crossword0 in the examples code directory.\nThere are 72 ways to complete the crossword grid with words from the\naccompanying directory.  \nFor finding all 72 solutions,\nthe comparative performance of the different annotations is given in the\ntable {\\em Comparing Annotations}.\n\n\\begin{table}[tb]\n\\begin{center}\n\\begin{tabular}{|c|c|c|c|}\n\\hline\nAnnotation & CPU time (secs)\\\\\n\\hline\nconsistent & 13.3 \\\\\nunique & 2.5 \\\\\nmost & 9.8 \\\\\nac & 0.3 \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\caption{Comparing Annotations}\n\\end{table}\n\nThe example program also illustrates the effect of specifying the waking\nconditions for Propia.  By only waking a Propia constraint when it\nbecomes instantiated, the time to solve the crossword problem can be\nchanged considerably.  For example by changing the annotation from\n\\verb0Goal infers most0 to \n\\verb0suspend(Goal,4,Goal->inst) infers most0 \nthe time needed to find all solutions goes down from 10 seconds to\njust one second.\n\nFor other problems, such as the square tiling problem in the example\ndirectory, the fastest version is the \none using \\verb0infers consistent0.  To find the best Propia\nannotation it is necessary to experiment with the current problem\nusing realistic data sets.\n\n\\quickref{Transforming Procedures to Constraints}{\nPropia extracts information from a procedure which may be defined by\nmultiple \\eclipse{} clauses.  \nThe information to be extracted is\ncontrolled by the Propia annotation.\n% (e.g. \\verb0consistent0, \\verb0unique0, \\verb0most0 and \\verb0ac0).\n}\n\n\\subsection{Propia Implementation}\nIn this section we describe how Propia works.\n\n\\subsubsection{Outline}\nWhen a goal is annotated as a Propia constraint, eg. \n\\verb0p(X,Y) infers most0, first the goal \\verb0p(X,Y)0 is in effect \nevaluated in the normal way by \\eclipse{}.\nHowever Propia does not stop at the first solution, but continues to\nfind more and more solutions, each time combining the information from\nthe solutions retrieved.\nWhen all the information has been accumulated, Propia propagates this\ninformation (either by narrowing the domains of variables in the goal,\nor partially instantiating them).\n\nPropia then suspends the goal again, until the variables become\nfurther constrained, at which point it wakes, extracts information\nfrom solutions to the more constrained goal, propagates it, and\nsuspends again.\n\nIf Propia detects that the goal is entailed (i.e. the goal would\nsucceed whichever way the variables were instantiated), then after\npropagation it does not suspend any more.\n\n\\subsubsection{Most Specific Generalisation}\n\\index{most specific generalisation}\n\\index{MSG}\nPropia works by treating its input both as a {\\em goal} to be called,\nand as a term which can be manipulated as data.\nAs with any \\eclipse{} goal, when executed its result is a further\ninstantiation of the term.  \nFor example the first result of calling \\verb0member(X,[a,b,c])0 is\nto further instantiate the term yielding \\verb0member(a,[a,b,c])0.\nThis instantiated term represents the (first) solution to the goal.\n\nPropia combines information from the solutions to a goal using their\n{\\em most specific generalisation} ({\\em MSG}).\nThe MSG of two terms is a term\nthat can be instantiated (in different ways) to either of the two\nterms. For example\n$p(a,f(Y))$ is the MSG of $p(a,f(b))$ and $p(a,f(c))$.\nThis is the meaning of {\\em generalisation}. \nThe meaning of {\\em most specific} is that any other term that\ngeneralises the two terms, is more general than the MSG.\nFor example, any other term that generalises $p(a,f(b)$ and\n$p(a,f(c))$ can be instantiated to $p(a,f(Y))$.\nThe MSG of two terms captures only information that is common to both\nterms (because it generalises the two terms), and it captures all the\ninformation possible in the two terms (because it is the most specific\ngeneralisation).\n\nSome surprising information is caught by the MSG.  For example the MSG\nof $p(0,0)$ and $p(1,1)$ is $p(X,X)$.\nWe can illustrate this being exploited by Propia in the following\nexample:\n\\begin{code}\n% Definition of logical conjunction\nconj(1,1,1).\nconj(1,0,0).\nconj(0,1,0).\nconj(0,0,0).\n\nconjtest(X,Z) :-\n    conj(X,Y,Z) infers most,\n    X=Y.\n\\end{code}\nThe test succeeds, recognising that $X$ must take the same truth value\nas $Z$.  Running this in \\eclipse{} yields:\n\\begin{quote}\n\\begin{verbatim}\n[eclipse]: conjtest(X,Z).\nX = X\nZ = X\nDelayed goals:\n        conj(X, X, X) infers most\nYes (0.00s cpu)\n\\end{verbatim}\n\\end{quote}\n\nIf the {\\tt ic} library is loaded more information can be extracted,\nbecause the MSG of $0$ and $1$ is a variable with domain \\verb90..19.\nThus the result of the above example is not only to equate $X$ and $Z$\nbut to associate with them the domain \\verb90..19.\n\nThe MSG of two terms depends upon what information is expressible in\nthe MSG term.  As the above example shows, if the term can employ\nvariable domains the MSG is more precise. \n\nBy choosing the class of terms in which the MSG can be\nexpressed, we can capture more or less information in the MSG.\nIf, for example, we allow only terms of maximum depth 1 in the class,\nthen MSG can only capture functor and arity.\nIn this case the MSG of $f(a,1)$ and $f(a,2)$ is simply $f(_,_)$, even\nthough there is more shared information at the next depth.\n\nIn fact the class of terms can be extended to a lattice, by\nintroducing a bottom $\\bot$ and a top $\\top$.  \n$\\bot$ is a term carrying no\ninformation; $\\top$ is a term representing inconsistent information;\nthe \nmeet of two terms is the result of unifying them; and their join is\ntheir MSG.\n\n\\subsubsection{The Propia Algorithm}\nWe can now specify the Propia algorithm more precisely.\nThe Propia constraint is \n\\begin{verbatim}Goal infers Parameter \\end{verbatim}\n\n\\begin{itemize}\n\\item  Set $OutTerm := \\top$\n\\item  Repeat\n\\begin{itemize}\n\\item   Find a solution $S$ to $Goal$ which is {\\em not} an instance of\n$OutTerm$  \n\\item   Find the MSG, in the class specified by \\verb0Parameter0, \nof $OutTerm$ and $S$.  Call it $MSG$\n\\item   Set $OutTerm := MSG$\n\\end{itemize}\nuntil either $Goal$ is an instance of $OutTerm$, or no such\nsolution remains \n\\item Return $OutTerm$\n\\end{itemize}\n\nWhen \\verb0infers most0 is being handled, the class of terms admitted\nfor the MSG is the biggest class expressible in terms of the currently\nloaded solvers.  In case $ic$ is loaded, this includes variable\ndomain, but otherwise it includes any \\eclipse{} term without variable\nattributes.\n\nThe algorithm supports \\verb0infers consistent0 by admitting only the\ntwo terms $\\top$ and $\\bot$ in the MSG class.\n\\verb0infers unique0 is a variation of the algorithm in which the\nfirst step $OutTerm := \\top$ is changed to finding a first solution\n$S$ to $Goal$ and initialising $OutTerm := S$.\n\nPropia's termination is dramatically improved by the check that the\nnext solution found is not an \ninstance of $OutTerm$.  In the absence of domains, there is no\ninfinite sequence of terms that strictly generalise each other.\nMoreover, if\nthe variables in $Goal$ have finite domains, the same result holds. \nThus, because of this check, Propia will terminate as long as each\ncall of $Goal$ terminates. \n\nFor example the Propia constraint \n\\verb0member(Var,List) infers Parameter0 will \nalways terminate, if each call of \\verb0member(Var,List)0 does, even in\ncase \n\\verb0member(Var,List)0 has infinitely many solutions!\n\n\\quickref{Most Specific Generalisation}{\nPropia computes the Most Specific Generalisation (MSG) of the set of\nsolutions to a procedure.  It does so without, necessarily,\nbacktracking through all the solutions to the procedure.\nThe MSG depends upon the annotation of the Propia call.\n}\n\n\\subsection{Propia and Related Techniques}\nIf the finite domain solver is loaded then \\verb0Goal infers most0 prunes\nthe variable domains so every value is supported by values in the\ndomains of the other variables.  If every problem constraint was\nannotated this way, then Propia would enforce arc consistency.\n\n\\index{arc consistency}\nPropia generalises traditional arc consistency in two ways.  Firstly\nit admits n-ary constraints, and secondly it handles predicates\ndefined by rules, as well as ground facts.  In the special case that\nthe goal can be ``unfolded'' into a finite set of ground solutions,\nthis can be exploited by using \\verb0infers ac0 to make Propia run\nmore efficiently.   When called with parameter \\verb0infers ac0,\nPropia simply finds all solutions and \napplies n-ary arc-consistency to the resulting tables.\n\n%associates an identifier with each tuple.  Arc-consistency is then\n%applied to the binary constraints between the tuple identifiers and\n%tuple values for each attribute, using the \\verb0element0 constraint\n%in the {\\tt ic} library.\n\n\\index{constructive disjunction}\nPropia also generalises {\\em constructive disjunction}.  Constructive\ndisjunction could be applied in case the\npredicate was unfolded into a finite set of solutions, where each\nsolution was expressed using {\\tt ic} constraints (such as equations,\ninequations etc.).\nPropia can also handle recursively defined predicates, like\n\\verb0member0, exampled above, which may have an infinite number of\nsolutions. \n\n\n\\section{CHR}\n\\label{secchr}\n\\index{CHR}\nConstraint Handling Rules were originally implemented in \\eclipse{}.\nThey are introduced in the paper \\cite{Fruehwirth}.\n\n\\subsection{How to Use CHR}\n\\index{simplification rule}\n\\index{propagation rule}\nCHR's offer a rule-based programming style to express constraint\nsimplification and constraint propagation.\nThe rules all have a {\\em head}, an explicit or implicit {\\em guard},\nand a {\\em body}, and are written either\n\\begin{quote}\n\\begin{verbatim}\nHead <=> Guard | Body.  %Simplification Rule\n\\end{verbatim}\n\\end{quote}\nor\n\\begin{quote}\n\\begin{verbatim}\nHead ==> Guard | Body.   %Propagation Rule\n\\end{verbatim}\n\\end{quote}\nWhen a constraint is posted that is an instance of the head, the guard\nis checked to determine whether the rule can fire.\nIf the guard is satisfied (i.e. CHR detects that it is entailed by the\ncurrent search state), the \nrule {\\em fires}. \nUnlike \\eclipse{} clauses, the rules leave no choice points.\nThus if several rules share the same head and one fires, the other\nrules are never fired even after a failure.\n\nNormally the guards exclude each other, as in the \\verb0noclash0\nexample:\n\\begin{code}\n:- lib(ech).\n:- constraints noclash/2.\nnoclash(S1,S2) <=> ic:(S2 #< S1+5) | ic:(S1 #>= S2+5).\nnoclash(S1,S2) <=> ic:(S1 #< S2+5) | ic:(S2 #>= S1+5).\n\\end{code}\nHenceforth we will not explicitly load the {\\tt ech} library.\n\nThe power of guards lies in the behaviour of the rules when they are\nneither entailed, nor disentailed.\nThus in the query\n\\begin{quote}\n\\begin{verbatim}\n?- ic:([S1,S2]::1..10),\n   noclash(S1,S2),\n   S1 #>= 6.\n\\end{verbatim}\n\\end{quote}\n\\begin{sloppypar}\nwhen the \\verb0noclash0 constraint is initially posted, neither guard\nis entailed, and CHR simply postpones the handling of the constraint\nuntil further constraints are posted.\nAs soon as a guard becomes entailed, however, the rule fires.\nFor simplification rules, of the form \n\\verb0Head <=> Guard | Body0, \nthe head is replaced by the body.\nIn this example, therefore, \\verb0noclash(S1,S2)0 is replaced by\n\\verb0S1 #>= S2+50.\n\\end{sloppypar}\n\nPropagation rules are useful to add constraints, instead of replacing\nthem.\nConsider, for example, an application to temporal reasoning.\nIf the time $T1$ is before time $T2$, then we can propagate an\nadditional $ic$ constraint saying $T1 =< T2$:\n\\begin{code}\n:- constraints before/2.\nbefore(T1,T2) ==> ic:(T1 \\$=< T2)\n\\end{code}\nThis rule simply posts the constraint \\verb0T1 $=< T20 to $ic$.\nWhen a propagation rule fires its body is invoked, but its head\nremains in the constraint store.\n\n\\subsection{Multiple Heads}\n\nSometimes different constraints interact, and more can be deduced\nfrom the combination of constraints than can be deduced from the\nconstraints separately.  Consider the following query:\n\\begin{quote}\n\\begin{verbatim}\n?- ic:([S1,S2]::1..10),\n   noclash(S1,S2),\n   before(S1,S2).\n\\end{verbatim}\n\\end{quote}\nUnfortunately the {\\tt ic} bounds are not tight enough for the\n\\verb0noclash0 rule to fire.\nThe two constraints can be combined so as to propagate $S2 \\ge S1+5$\nusing a two-headed\nCHR:\n\\begin{quote}\n\\begin{verbatim}\nnoclash(S1,S2), before(S1,S2) ==> ic:(S2 #>= S1+5).\n\\end{verbatim}\n\\end{quote}\nWe would prefer to write a set of rules that captured this kind of\ninference in a general way.\n\n\\index{simpagation rule}\nThis can be achieved by writing a more complete solver for\n\\verb0prec0, and combining it with \\verb0noclash0.\n$prec(S1,D,S2)$ holds if the time $S1$ precedes the time $S2$ by at\nleast $D$ units of time.\nFor the following code to work, $S1$ and $S2$ may be numbers or\nvariables, but $D$ must be a number.\n\\begin{code}\n:- constraints prec/3.\nprec(S,D,S) <=> D=<0.\nprec(S1,0,S2), prec(S2,0,S1) <=> S1=S2.\nprec(S1,D1,S2), prec(S2,D2,S3) ==> D3 is D1+D2, prec(S1,D3,S3).\nprec(S1,D1,S2) \\verb.\\. prec(S1,D2,S2) <=> D2=<D1 | true.     % Simpagation\n\nnoclash(S1,S2), prec(S1,D,S2) ==> D > -5 | prec(S1,5,S2).\nnoclash(S1,S2), prec(S2,D,S1) ==> D > -5 | prec(S2,5,S1).\n\\end{code}\nNote the {\\em simpagation} rule, whose head has two parts \n\\verb0Head1 \\ Head20. \nIn a simpagation rule \\verb0Head20 is replaced, but \\verb0Head10 is\nkept in the constraint store.\n\n\\quickref{CHRs}{\nCHRs are guarded rules which fire without leaving choice points.\nA CHR rule may have one or many goals in the head, and may take the\nfollowing forms: Simplification rule, Propagation rule or Simpagation\nrule. \n%\\begin{itemize}\n%\\item[{\\em Simplification} rule] \\verb0Head <=> Guard | Body0\n%\\item[{\\em Propagation} rule] \\verb0Head ==> Guard | Body0\n%\\item[{\\em Simpagation} rule] \\verb0Head1 \\ Head2 <=> Guard | Body0\n%\\end{itemize}\n\n}\n\n\\section{A Complete Example of a CHR File}\n\nSometimes whole sets of constraints can be combined.\nConsider, for example, a program where disequalities on pairs of\nvariables are accumulated during search.\nWhenever a point is reached where any subset of the variables are all\nconstrained to be different an \\verb0alldifferent0 constraint can be\nposted on that subset, thus supporting more powerful propagation.\nThis can be achieved by finding {\\em cliques} in the graph whose nodes\nare variables and edges are disequality constraints.\n\n\\index{clique}\nWe start our code with a declaration to load the {\\em ech} library.\nThe constraints are then declared, and subsequently defined by rules.\nThe CHR encoding starts by generating a clique whenever two variables\nare constrained to be different.\n\\begin{code}\n:- lib(ech).\n:- constraints neq/2.\n\nneq(X,Y) ==>\n    sort([X,Y],List),\n    clique(List),\n    neq(Y,X).\n\\end{code}\nEach clique is held as a sorted list to avoid any duplication.\nThe symmetrical disequality is added to simplify the detection of new\ncliques, below.\nWhenever a clique is found, the \\verb0alldifferent0 constraint is\nposted, and the CHRs seek to extend this clique to\ninclude another variable:\n\\begin{code}\n:- constraints clique/1.\n\nclique(List) ==> alldifferent(List).\nclique(List),neq(X,Y) ==>\n    in_clique(Y,List), not in_clique(X,List) |\n    sort([X|List],Clique),\n    extend_clique(X,List,Clique).\n\nin_clique(Var,List) :-\n    member(El,List), El==Var, !.\n\\end{code}\nThe idea is to search the constraint store for a disequality between\nthe new variable \\verb0X0 and each other variable in the original\nclique.  This is done by recursing down the list of remaining\nvariables.\nWhen there are no more variables left, a new clique has been found.\n\\begin{code}\nneq(X,Y) \\verb.\\. extend_clique(X,[Y|Tail],Clique) <=>\n    extend_clique(X,Tail,Clique).\nextend_clique(_,[],Clique) <=> \n    clique(Clique).\n\\end{code}\n\nFinally, we add three optimisations.\nDon't try and find a clique that has already been found, or\nfind the same clique twice.  If the new variable is equal to a\nvariable in the list, then don't try any further.\n\\begin{code}\nclique(Clique) \\verb.\\. extend_clique(_,_,Clique) <=> true.\nextend_clique(_,_,Clique) \\verb.\\. extend_clique(_,_,Clique) <=> true.\nextend_clique(Var,List,_) <=> in_clique(Var,List) | true.\n\\end{code}\n\n\\subsection{CHR Implementation}\nCHR's are implemented using the \\eclipse{} suspension and waking\nmechanisms. \nA rule is woken if:\n\\begin{itemize}\n\\item a new goal is posted, which matches one of the goals in its head\n\\item a goal which has already been posted earlier becomes further\ninstantiated.\n\\end{itemize}\n\n\\index{entailment}\nThe rule cannot fire unless the goal is more instantiated than the\nrule head.  Thus the rule\n\\verb0p(a,f(Y),Y) <=> q(Y)0 is really a shorthand for the guarded\nrule:\n\\begin{quote}\n\\begin{verbatim}\np(A,B,C) <=> A=a, B=f(Y), C=Y | q(Y)\n\\end{verbatim}\n\\end{quote}\nThe guard is ``satisfied'' if, logically, it is entailed by the\nconstraints posted already.\n\nIn practice the CHR implementation cannot always detect the\nentailment.\nThe consequence is that goals may fire later than they could.\nFor example consider the program\n\\begin{code}\n:- constraints p/2.\np(X,Y) <=> ic:(X \\$> Y) | q(X,Y).\n\\end{code}\nand the goal\n\\begin{quote}\n\\begin{verbatim}\n?-  ic:(X $> Y),\n    p(X,Y).\n\\end{verbatim}\n\\end{quote}\nAlthough the guard is clearly satisfied, the CHR implementation cannot\ndetect this and \\verb0p(X,Y)0 does not fire.\nIf the programmer needs the entailment of inequalities to be detected,\nit is necessary to express inequalities as CHR constraints, which\npropagate {\\tt ic} constraints as illustrated in the example\n\\verb0prec(S1,D,S2)0 above.\n\nCHRs can detect entailment via variable bounds, so \\verb.p(X,0).\ndoes fire in the following example:\n\\begin{quote}\n\\begin{verbatim}\n?-  ic:(X $> 1),\n    p(X,0).\n\\end{verbatim}\n\\end{quote}\n\nThe implementation of this entailment test in \\eclipse{} is to impose\nthe guard as a constraint, and fail (the entailment test) as soon as\nany variable becomes more constrained.\nA variable becomes more constrained if:\n\\begin{itemize}\n\\item it becomes more instantiated\n\\item its domain is tightened\n\\item a new goal is added to its suspension list\n\\end{itemize}\n\nThere are many examples of applications expressed in CHR in the\n\\eclipse{} distribution.\nThey are held as files in the {\\em chr} subdirectory of the standard\n\\eclipse{} library directory {\\em lib}. \n\n\\quickref{CHR Implementation}{\nCHRs suspend on the variables in the rule head.  On waking the CHR\ntests if its guard is entailed by the current constraint store.  The\nentailment test is efficient but incomplete, and therefore rules may\nfail to fire as early as they could in theory.\n}\n\n\\section{Global Reasoning}\n\\index{global reasoning}\nConstraints in {\\tt ic} are handled separately and individually.  More\nglobal consistency techniques can be achieved using global\nconstraints.\nPropia and CHRs provide alternative methods of achieving more global\nconsistency.\nPropia allows any subproblem to be treated as a single constraint.\nCHRs allow any set of constraints to be handled by a single rule.\nEach technique has special strengths.  Propia is good for handling\ncomplicated logical combinations of constraints.  CHRs are good for\ncombining sets of constraints to extract transitive closures, and\ncliques.\n\nBoth are fun to implement and use!\n\n\\section{Propia and CHR Exercise}\n\n\nThe problem is to implement three constraints, \\verb'and', \\verb'or'\nand \\verb'xor' \nin CHRs and, as a separate exercise, in Propia.\nThe constraints are specified as follows:\nAll boolean variables have domain $\\{0,1\\}$: $0$ for 'false' and $1$\nfor 'true'. \n\\begin{quotation}\n\\noindent and(X,Y,Z) =def (X \\& Y) = Z\\\\\nor(X,Y,Z)  =def (X or Y) = Z\\\\\nxor(X,Y,Z) =def ((X \\& -Y) or (-X \\& Y)) = Z\n\\end{quotation}\n\nSuppose your constraints are called \n\\verb0cons_and0, \\verb0cons_or0 and \\verb0cons_xor0\nNow write enter the following procedure:\n\\begin{code}\nfull_adder(I1,I2,I3,O1,O2) :-\n    cons_xor(I1,I2,X1),\n    cons_and(I1,I2,Y1),\n    cons_xor(X1,I3,O1),\n    cons_and(I3,X1,Y2),\n    cons_or(Y1,Y2,O2).\n\\end{code}\nThe problem is solved if you enter the query:\n\\begin{quote}\n\\begin{verbatim}\n?- full_adder(I1,I2,0,O1,1).\n\\end{verbatim}\n\\end{quote}\nand get the correct answer.\n\nNote: you are not allowed to load the ic library nor to use search and\nbacktracking!\n\n%HEVEA\\cutend\n", "meta": {"hexsha": "089d33d8682c64d3e3c788cfd03e68ad67165672", "size": 29568, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "usr/eclipseclp/documents/tutorial/propiachr.tex", "max_stars_repo_name": "lambdaxymox/barrelfish", "max_stars_repo_head_hexsha": "06a9f54721a8d96874a8939d8973178a562c342f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 111, "max_stars_repo_stars_event_min_datetime": "2015-02-03T02:57:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T23:57:09.000Z", "max_issues_repo_path": "usr/eclipseclp/documents/tutorial/propiachr.tex", "max_issues_repo_name": "lambdaxymox/barrelfish", "max_issues_repo_head_hexsha": "06a9f54721a8d96874a8939d8973178a562c342f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2016-03-22T14:44:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-18T13:30:29.000Z", "max_forks_repo_path": "usr/eclipseclp/documents/tutorial/propiachr.tex", "max_forks_repo_name": "lambdaxymox/barrelfish", "max_forks_repo_head_hexsha": "06a9f54721a8d96874a8939d8973178a562c342f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 55, "max_forks_repo_forks_event_min_datetime": "2015-02-03T05:28:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T05:00:03.000Z", "avg_line_length": 35.5812274368, "max_line_length": 75, "alphanum_fraction": 0.7530776515, "num_tokens": 7946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3266777688084485}}
{"text": "\\documentclass{article}\n\\input{/Users/ayberkt/Developer/latex-basis/basis.tex}\n\n\\usepackage{boxproof}\n\\usepackage{mathpazo}\n\n\\author{Ayberk Tosun}\n\\title{\n  Practical Foundations of Mathematics\\\\\n  Exercise Solutions\n}\n\n\\begin{document}\n\\maketitle\n\n\\section*{Chapter 1}\n\n\\subsection*{Exercise 22}\n\n\\begin{proposition}\n  \\( (\\alpha \\land \\beta) \\Rightarrow \\gamma\n     \\dashv \\vdash \\alpha \\Rightarrow (\\beta \\Rightarrow \\gamma) \\).\n\\end{proposition}\n\n\\begin{proof}\n\\begin{proofbox}\n   \\lbl{1}\\: (\\alpha \\land \\beta) \\Rightarrow \\gamma \\\\\n   \\[\n      \\lbl{2}\\: \\alpha\\= \\mathsf{hyp} \\\\\n      \\[\n        \\: \\beta \\= \\mathsf{hyp} \\\\\n        \\: \\alpha \\= (\\ref{2}) \\\\\n        \\: \\alpha \\land \\beta \\= \\land\\mathcal{I}\\\\\n        \\: \\gamma \\= \\elim\\Rightarrow\n      \\]\n      \\: \\beta \\Rightarrow \\gamma \\= \\intro\\Rightarrow\n   \\]\n   \\: \\alpha \\Rightarrow (\\beta \\Rightarrow \\gamma) \\= \\intro\\Rightarrow\n\\end{proofbox}\n\\end{proof}\n\n\\end{document}\n", "meta": {"hexsha": "a1181ebb60f3296d2c4367c4bc9e7a02afc7648b", "size": 940, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "pfm-exercises.tex", "max_stars_repo_name": "ayberkt/pfm-exercises", "max_stars_repo_head_hexsha": "b7a7343b0999d22b7a3b04ae596b177403d4e6b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-10-27T17:11:28.000Z", "max_stars_repo_stars_event_max_datetime": "2016-10-27T17:11:28.000Z", "max_issues_repo_path": "pfm-exercises.tex", "max_issues_repo_name": "ayberkt/pfm-exercises", "max_issues_repo_head_hexsha": "b7a7343b0999d22b7a3b04ae596b177403d4e6b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pfm-exercises.tex", "max_forks_repo_name": "ayberkt/pfm-exercises", "max_forks_repo_head_hexsha": "b7a7343b0999d22b7a3b04ae596b177403d4e6b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8604651163, "max_line_length": 72, "alphanum_fraction": 0.620212766, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3266777688084485}}
{"text": "\\chapter{Background}\\label{chap:background}\nSome background knowledge is necessary for the reader to have an understanding of the principles behind semantic segmentation and convolutional neural networks.\nThis chapter on the background of this work will discuss semantic segmentation, machine learning with artificial neural networks and convolutional neural networks, curb segmentation, loss functions, network optimizers, and binary dilation.\n\n\\section{Semantic Segmentation}\\label{section:background-segmentation}\nUnlike image classification, which classifies the contents of an image as a whole, semantic segmentation is the use of some algorithm to process an image and assign class labels to each individual pixel~\\cite{segmentation-medium}.\nThis adds the ability to locate and classify multiple objects in a given scene.\nFor example, the ground truth segmentation of the street-level image in \\figref{fig:background-raw} can be seen in \\figref{fig:background-segmented}.\nEach pixel of the image has been assigned a class, which is represented by the different colors in the segmented image.\nThis allows a computer or program to understand what objects are in the image it is shown.\n\n\\input{figures/background/segmentation}\n\nBy segmenting an image in this way, the program can interpret the scene semantically.\nFor example, by receiving the segmented image, a program can identify that there are line markings on the road and that there is a vehicle in front of it.\nThe segmentation of images in this way is essential in many robotic applications as it allows further higher level processing of the scene.\n\nTowards the goal of this work, the segmentation of traversability classes in a scene allows Obelix to more accurately find a path allowing for the safe traversal from sidewalk to street level via curb cuts.\n\n\\input{chapters/3_1-neural-networks}\n\n\\section{Curbs and Curb Cuts}\\label{section:background-curbs}\nCurbs are the concrete or stone edging of a road. Curbs usually separate the road from some other area with a different elevation, usually a pedestrian sidewalk.\nAn example of a sidewalk with a curb can be seen in Figure \\ref{fig:background-curb}.\nCurb cuts are \"cuts\" in the curb that allow a pedestrian sidewalk to have a gentle slope down to street level.\nAn example of a sidewalk with a curb cut can be seen in Figure \\ref{fig:background-curbcut}.\nOriginally, these cuts were made to allow accessibility access, especially for those requiring wheelchairs.\nTo a wheelchair user, curbs represent a significant barrier in terms of traversability, as was discussed in the article \"Curb Cuts\" by Cynthia Gorney and Delaney Hall \\cite{99pi}. \nCurb cuts first started appearing fifty years ago from the efforts of activist Ed Roberts and his push to make city streets more accessible.\n\nWheeled robots are also unable to traverse curbs.\nThey therefore require curb cuts to traverse urban environments where curbs are present.\n\n\\input{figures/background/curbs}\n\n\\section{Loss Functions}\\label{section:background-loss}\nThe loss function $\\ell$ maps the output of a neural network $\\hat{y}$ and the target $y$ onto a real number and represents the \"cost\" of an output.\nThe goal of learning is to minimize this cost value.\nEffectively, the loss function measures the difference between the predicted value and the target.\nIn our case, the target value is the ground truth labeling of an image and the output is the softmax class predictions from the network.\nThere are many different loss functions that are commonly used. For the purposes of image segmentation, the most commonly used function is cross entropy loss.\n\n\\subsection{Cross Entropy Loss}\\label{section:background-crossentropy}\nThe cross entropy loss is formally defined as:\n\\begin{align}\n\t\\ell(y, \\hat{y}) &=\\sum_{m}-y_m\\log(\\hat{y}_m)\n\\end{align}\nwhere $m$ is the class, $y_m$ the ground truth value for a class $m$, and $\\hat{y}_m$ the softmax prediction of a class $m$ by the model. \nAs such, cross entropy loss calculates the error of the model to classify a certain value correctly.\nThe loss of two predictions could be the same, as long as the prediction for the true class, i.e. the class that has value 1 in $y$, remains constant.\nThe loss is thus independent of how the probability is split between the remaining classes.\n\nFor example, let the ground truth classification be class 0, i.e. $y = \\{1, 0, 0\\}$ with one-hot encoding.\nLet the current model prediction be $\\hat{y} = \\{0.5, 0.2, 0.3\\}$, also with one-hot encoding.\nThe loss would then be:\n\\begin{equation}\n\t\\begin{split}\n\t\t\\ell(y, \\hat{y}) \t&= \\sum_{m}-y_m \\log(\\hat{y}_m) \\\\\n\t\t&= -(1)\\log(0.5) + (-0)\\log(0.2) + (-0)\\log(0.3)\\\\\n\t\t&= -\\log(0.5) \\\\\n\t\t&= 0.301...\n\t\\end{split}\n\\end{equation}\nAlternatively, if model prediction is exactly the same as the ground truth, then we would have:\n\\begin{equation}\n\t\\begin{split}\n\t\ty\t\t\t\t\t&= \\hat{y} = \\{1, 0, 0\\}\\\\\n\t\t\\ell(y, \\hat{y}) \t&= \\sum_{m}-y_m \\log(\\hat{y}_m) \\\\\n\t\t&= -(1)\\log(1) + (-0)\\log(0) + (-0)\\log(0)\\\\\n\t\t&= -\\log(1) \\\\\n\t\t&= 0\n\t\\end{split}\n\\end{equation}\nApplying this on the full image, this becomes:\n\\begin{align}\n\t\\ell(y, \\hat{y}) &=\\sum_u \\sum_v \\sum_{m}-y_{m, u, v}\\log(\\hat{y}_{m,u,v})\n\\end{align}\nwhere $u$ and $v$ are the pixel coordinates.\n\nThe weighted variant, known simply as weighted cross entropy loss, is defined as:\n\\begin{align}\n\t\\ell(y, \\hat{y}) &=\\sum_{m}-y_m\\log(\\hat{y}_m) \\cdot d_m\n\\end{align}\nwhere $d_m$ is the weight for a given class $m$.\n\nUsing the weighted version allows changes to how much each class contributes to the loss.\nThis is done to counteract class imbalance that could be caused by having an imbalance in the distribution or frequency of each class in the dataset.\n\n\\section{Optimizers}\\label{section:background-optimizers}\nDuring training, network parameters must be updated to minimize the loss function at each iteration.\nThis is done by the optimizer.\nThe optimizer updates the network parameters in such a way as to minimize the loss function~\\cite{optimizer-intro}.\n\nGradient Descent is one of the earliest optimizers.\nIt works by calculating what a small change in each network parameter would do to the loss function, i.e. determines the gradient of the loss for the current iteration.\nIt then adjusts the network parameters according to this gradient.\nThis process is repeated at each iteration to further minimize the loss function.\nThis process can be time-consuming, especially with larger datasets.\nStochastic Gradient Descent (SGD) is a more commonly used variant of gradient descent and works similarly, but working only on randomly selected batches of the training data at each iteration~\\cite{optimizer-intro}.\nDue to the large size of datasets, training is usually done in batches.\nBy using SGD, the optimization step can occur after processing every batch, rather than after the entire dataset is processed.\nThis speeds up with respect to wall-clock time network training.\n\nAdaptive Moment Estimation (Adam) is another optimizer that is commonly used and first proposed in the paper \"Adam: A method for stochastic optimization\" by Diederik Kingma and Jimmy Ba~\\cite{adam}.\nIt combines concepts from Adaptive Gradient Algorithm (AdaGrad), which has per-parameter learning rates, and Root Mean Square Propagation (RMSProp), whose learning rates are adapted based on the average of the magnitude of recent gradients~\\cite{adam}.\nAdam utilizes the concept of momentum, which incorporates previous gradients into the current one.\nIt does this by calculating an exponential moving average and the square of previous gradients and using these to determine the next gradient.\n\n\\section{Backpropagation}\\label{section:background-backpropagation}\nBackpropagation is a learning procedure used in artificial neural networks to adjust network weights and produce internal representations of \"important features in the task domain,\" first described in 1986 by David E. Rumelhart, Geoffrey E. Hinton, and Ronald J. Williams in their paper \"Learning representations by back-propagating errors\"~\\cite{backprop}.\nBackpropagation efficiently and repeatedly adjusts the network weights to minimize the network error, which is calculated by the loss function.\n\nCalculating the network weights is done layer by layer, starting with the final output layer.\nThe partial derivative of $\\ell$ with respect to $y_j$, intuitively the effect the output unit has on the loss, is defined as:\n\\begin{align}\\label{eq:loss-1}\n\t\\frac{\\partial \\ell}{\\partial y_j}\n\\end{align}\nwhere $y_j$ is the output of a single unit in the final layer.\nThe contribution of the input of the unit $j$ on the error can then be calculated using the value previously calculated in \\eqref{eq:loss-1} using the chain rule for differentiation as\n\\begin{align}\\label{eq:loss-2}\n\t\\frac{\\partial\\ell}{\\partial x_j} &= \\frac{\\partial \\ell}{\\partial y_j} \\cdot \\frac{\\partial y_j}{\\partial x_j}\n\\end{align}\nWe now have a description of how changing the input of unit $j$ will affect the loss.\nAs such, we can then also represent how changing the weight $w_{ji}$ of a connection between the unit $j$ and a unit in the previous layer $i$ will effect the error as\n\\begin{align}\\label{eq:loss-3}\n\t\\frac{\\partial \\ell}{\\partial w_{ji}} &= \\frac{\\partial \\ell}{\\partial x_j} \\cdot \\frac{\\partial x_j}{\\partial w_{ji}}\n\\end{align}\nIn this case, the previous layer means the layer which during forwards-propagation would be calculated immediately before the layer in which unit $j$ is.\nAgain, due to the use of the chain rule, the previous value calculated in \\eqref{eq:loss-2} can be used here.\nThis gives us the contribution of the weight $w_{ji}$ on the error and, by multiplying by the learning rate, the amount by which the gradient must be changed for the next training iteration.\n\nThe error contribution of the output of unit $i$ via a single successor unit $j$ can also similarly be calculated using the value from \\eqref{eq:loss-2}.\n\\begin{align}\\label{eq:loss-4}\n\t\\frac{\\partial \\ell}{\\partial y_i} &= \\frac{\\partial \\ell}{\\partial x_j} \\cdot w_{ji}\n\\end{align}\nSince unit $i$ is connected to multiple successor units, its value is a summation of its output contribution via all units $j \\in J$, where $J$ is the set of all units in successive layers that $i$ is connected to.\n\\begin{align}\n\t\\frac{\\partial \\ell}{\\partial y_i} &= \\sum_{j \\in J} \\frac{\\partial \\ell}{\\partial x_j} \\cdot w_{ji}\n\\end{align}\nThis calculation can be done in parallel, thanks to parallel computing architecture, completing the gradient calculations for the penultimate layer.\nThis procedure is then repeated for all layers, each time using the previously computed values to allow for efficient computation.\n\n\\input{chapters/3_2-hyperparameters}\n\n\\section{Binary Dilation}\\label{section:background-dilation}\nBinary dilation is a basic morphological operation and is usually represented by the operator $\\oplus$.\nWith regards to this work, binary dilation is used in our loss function.\nFor a given binary image viewed as an integer grid $\\mathbb{Z}^d$ for some dimension $d$, let $E$ be an integer grid, $A \\in E$ a binary image, and $B \\in \\{0,1\\}^d$ a structuring element.\nThe binary dilation of $A$ by $B$ is then defined as:\n\\begin{align}\n\tA \\oplus B &= \\bigcup_{b \\in B}A_b\n\\end{align}\nwhere $A_b$ is the translation of $A$ by $b$.\nThis can be seen as extending the area of the binary image $A$ by locus of the points covered by $B$ given that $B$ has a center on the origin~\\cite{morphology}.", "meta": {"hexsha": "f25babbe88c2b4ef7cc97597ee1b985929c30bf4", "size": 11470, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/3-background.tex", "max_stars_repo_name": "yvan674/bachelor-thesis", "max_stars_repo_head_hexsha": "00121f35245c20ddf77bd5d0ca9467460849902c", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/3-background.tex", "max_issues_repo_name": "yvan674/bachelor-thesis", "max_issues_repo_head_hexsha": "00121f35245c20ddf77bd5d0ca9467460849902c", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/3-background.tex", "max_forks_repo_name": "yvan674/bachelor-thesis", "max_forks_repo_head_hexsha": "00121f35245c20ddf77bd5d0ca9467460849902c", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 74.4805194805, "max_line_length": 357, "alphanum_fraction": 0.7715780296, "num_tokens": 2827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.3266777607297404}}
{"text": "\\vssub\n\\subsection{~Depth variations in time} \\label{sub:num_depth}\n\\vssub\n\nTemporal depth variations result in a change of the local wavenumber\ngrid. Because the wavenumber spectrum is invariant with respect to temporal\nchanges of the depth, this corresponds to a simple interpolation of the\nspectrum from the old grid to the new grid, without changes in the spectral\nshape. As discussed above, the new grid simply follows from the globally\ninvariant frequency grid, the new water depth $d$ and the dispersion relation\nEq. (\\ref{eq:disp}). The time step of updating the water level is generally\ndictated by physical time scales of water level variations, but not by\nnumerical considerations \\citep{tol:GAOS98b}.\n\nThe interpolation to the new wavenumber grid is performed with a simple\nconservative interpolation method. In this interpolation the old spectrum is\nfirst converted to discrete action densities by multiplication with the\nspectral bin widths. This discrete action then is redistributed over the new\ngrid cf.\\ a regular linear interpolation. The new discrete actions then are\nconverted into a spectrum by division by the (new) spectral bin widths. The\nconversion requires a parametric extension of the original spectrum at high\nand low frequencies because the old grid generally will not completely cover\nthe new grid. Energy/action in the old spectrum at low wavenumbers that are\nnot resolved by the new grid is simply removed. At low wavenumbers in the new\ngrid that are not resolved by the old grid zero energy/action is assumed. At\nhigh wavenumbers in the new grid the usual parametric tail is applied if\nnecessary. The latter correction is rare, as the highest wavenumbers usually\ncorrespond to deep water.\n\nIn practical applications the grid modification is usually relevant for a\nsmall fraction of the grid points only. To avoid unnecessary calculations, the\ngrid is transformed only if the smallest relative depth $kd$ in the discrete\nspectrum is smaller than 4. Furthermore, the spectrum is interpolated only if\nthe spatial grid point is not covered by ice, and if the largest change of\nwavenumber is at least $0.05 \\Delta k$.\n", "meta": {"hexsha": "bdcbc2d1675d3eed7cc95b252eebfe6fe7d3ea07", "size": 2148, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "WW3/manual/num/depth.tex", "max_stars_repo_name": "minsukji/ci-debug", "max_stars_repo_head_hexsha": "3e8bbbe6652b702b61d2896612f6aa8e4aa6c803", "max_stars_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WW3/manual/num/depth.tex", "max_issues_repo_name": "minsukji/ci-debug", "max_issues_repo_head_hexsha": "3e8bbbe6652b702b61d2896612f6aa8e4aa6c803", "max_issues_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-05-31T15:49:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-04T14:17:45.000Z", "max_forks_repo_path": "WW3/manual/num/depth.tex", "max_forks_repo_name": "minsukji/ci-debug", "max_forks_repo_head_hexsha": "3e8bbbe6652b702b61d2896612f6aa8e4aa6c803", "max_forks_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-01T09:29:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T09:29:46.000Z", "avg_line_length": 59.6666666667, "max_line_length": 78, "alphanum_fraction": 0.8133147114, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6584175005616829, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.32663685924431657}}
{"text": "\\documentclass{beamer}\n\\usetheme{Warsaw}\n\\usepackage{nhtvslides}\n\\usepackage{graphicx}\n\\usepackage{listings}\n\\lstset{language=CAML,\nbasicstyle=\\ttfamily\\footnotesize,\nframe=shadowbox,\nbreaklines=true}\n\\usepackage[utf8]{inputenc}\n\n\\title{Building a physics engine - part 3: collision response}\n\n\\author{Dr. Giuseppe Maggiore}\n\n\\institute{NHTV University of Applied Sciences \\\\ \nBreda, Netherlands}\n\n\\date{}\n\n\\begin{document}\n\\maketitle\n\n\\begin{frame}{Table of contents}\n\\tableofcontents\n\\end{frame}\n\n\\section{Collision response}\n\\begin{slide}{Collision response}{Collision response system}{\n\\item Solving physical constraints in addition to the equations of motion\n\\item Constraints are mostly contact constraints, but also\n\\begin{itemize}\n\\item Friction constraints\n\\item Distance constraints\n\\item Joint angle constraints\n\\item ...\n\\end{itemize}\n\\item The ideal collision response system deals with all of these\n}\\end{slide}\n\n\\begin{slide}{Collision response}{Naïve take}{\n\\item Apply the constraints to the objects in pairs\n\\item Use the laws of \\textit{conservation of motion} for each collision; $P_0$ is the point of collision, $x_A$ and $x_B$ are the centres of mass of the objects, $v^{-1}$ is the pre-impact velocity of the objects, $v^+$ is the post-impact velocity of the objects\n\\begin{itemize}\n\\item $f = \\frac{-(1 + \\epsilon)(N_0 \\cdot (v_A^{-1} - v_B^{-1})) + (\\omega_A^- \\cdot (r_A \\times N_0) - \\omega_B^- \\cdot (r_B \\times N_0)))}{1/m_A + 1/m_B + (r_A \\times N_0)^T J_A^{-1} (r_A \\times N_0) + (r_B \\times N_0)^T J_B^{-1} (r_B \\times N_0)}$\n\\item $r_A = P_0 - x_A$, $r_B = P_0 - x_B$\n\\item $v_A^+ = v_A^- + \\frac{f N_0}{m_A}$\n\\item $\\omega_A^+ = \\omega_A^- + J_A^- (r_A \\times (f N_0))$\n\\end{itemize}\n\\item Push away from interpenetration as long as interpenetration exists\n}\\end{slide}\n\n\\begin{slide}{Collision response}{Naïve take}{\n\\item Jitters a lot, and does not support stacking\n\\item May be acceptable in very sparse scenarios (space/flight simulator)\n}\\end{slide}\n\n\\begin{slide}{Collision response}{Naïve take number 2}{\n\\item Apply the constraints to the objects in pairs\n\\item Apply again during the same tick\n\\item Average/combine the various impulses\n\\item Push apart objects so they do not penetrate\n\\pause\n\\item Constraints are still broken\n\\item \\textit{Hack-y method}, gives no guarantees\n\\item Still does not support stacking\n}\\end{slide}\n\n\\section{Constrained dynamics}\n\\begin{slide}{Constrained dynamics}{Unconstrained kinematics}{\n\\item A rigid body is characterised by\n\\item $\\dot x = v$\n\\item $\\dot q = \\frac{1}{2}wq$\n}\\end{slide}\n\n\\begin{slide}{Constrained dynamics}{Unconstrained kinematics}{\n\\item For a system of $N$ bodies, we can define the system derivative as\n$$V = \\left[ \\begin{matrix}\nv_1 \\\\ \\omega_1 \\\\ \\vdots \\\\ v_N \\\\ \\omega_N\n\\end{matrix} \\right]$$\n}\\end{slide}\n\n\\begin{slide}{Constrained dynamics}{Constraints}{\n\\item Our system allows \\textit{pairwise} constraints between bodies\n\\item The $k$-th constraint, between bodies $i$ and $j$, has the form $C_k(x_i,q_i,x_j,q_j) = 0$\n\\item The vector $C$ holds all the constraints. $C = 0$, or $C(x) = 0$, is a function of the state vector, so by the chain rule $\\dot C = J V = 0$\n}\\end{slide}\n\n\\begin{slide}{Constrained dynamics}{Constraint forces}{\n\\item Each constraint causes a reaction force $f_c$ and a reaction torque $\\tau_c$\n\\item The vector of all reaction forces is $$F_c = \\left[ \\begin{matrix}\nf_{c1} \\\\ \\tau_{c1} \\\\ \\vdots \\\\ f_{cN} \\\\ \\tau_{cN}\n\\end{matrix} \\right]$$\n}\\end{slide}\n\n\\begin{slide}{Constrained dynamics}{Constraint forces}{\n\\item We know that $\\dot C = J V = 0$\n\\item $J V = \\left[ \\begin{matrix}\nJ_1 \\cdot V \\\\ \\vdots \\\\ J_M \\cdot V \\\\\n\\end{matrix} \\right] = 0$\n\\item This means that $V$ is orthogonal to each row of $J$\n}\\end{slide}\n\n\\begin{slide}{Constrained dynamics}{Constraint forces}{\n\\item Constraint forces perform no work, so $F_c \\cdot V = 0$\n}\\end{slide}\n\n\\begin{frame}{Principle of virtual work}\n\\center\n\\includegraphics[width=7cm]{Pics/VirtualWork.png}\n\\end{frame}\n\n\\begin{slide}{Constrained dynamics}{Constraint forces}{\n\\item We can use $F_c = J^T \\lambda$ for some vector $\\lambda$ of undetermined force multipliers\n\\item $F_c \\cdot V = J^T \\lambda \\cdot V = (\\sum_i J_i \\lambda_i) \\cdot V = \\sum_i J_i \\cdot V \\lambda_i = \\sum_i 0 \\lambda_i = 0$\n}\\end{slide}\n\n\\begin{slide}{Constrained dynamics}{Constraint forces}{\n\\item We will thus compute the matrix $J$ of constraints from the collision system\n\\item We then solve for $\\lambda$, compute $F_c$, and finally obtain $V$\n}\\end{slide}\n\n\\section{Setting up the constraints}\n\\begin{slide}{Constrained dynamics}{Distance constraints}{\n\\item The simplest constraint is a distance constraint\n\\item Two points of two bodies must remain at a given distance\n\\item $C(x_i,q_i,x_j,q_j) = \\frac{1}{2}(|p_j-p_i|^2 - L^2) = 0$\n\\item If we derive this, we get $\\dot C(x_i,q_i,x_j,q_j) = \\underbrace{(p_j-p_i)}_{d}(v_j + \\omega_j \\times r_j - v_i - \\omega_i \\times r_i)$\n\\item We split this into a row for $J$ and a part of $V$:\n\\item $\\dot C(x_i,q_i,x_j,q_j) = \\underbrace{\\left[ -d^T\\ -(r_i \\times d)^T\\ d^T\\ (r_j \\times d)^T \\right]}_{\\text{a row of }J} \\underbrace{\\left[ v_i\\ \\omega_i\\ v_j\\ \\omega_j \\right]^T}_{\\text{some columns of } V}$\n}\\end{slide}\n\n\\begin{frame}{Distance constraint}\n\\center\n\\includegraphics[width=7cm]{Pics/DistanceConstraint.png}\n\\end{frame}\n\n\\begin{slide}{Constrained dynamics}{Distance constraints}{\n\\item We are abusing the notation; the ``row of $J$'' also contains many zeroes $(6 \\times (N_{\\text{bodies}} - 2))$\n\\item The only columns that are not zeroed are those corresponding to the bodies $i$ and $j$\n\\item $\\dot C(x_i,q_i,x_j,q_j) = \\underbrace{\\left[ \\dots\\ 0\\ -d^T\\ -(r_i \\times d)^T\\ 0\\ \\dots\\ 0\\ d^T\\ (r_j \\times d)^T\\ \\dots\\ 0\\right]}_{\\text{a row of }J} V$\n}\\end{slide}\n\n\\begin{slide}{Constrained dynamics}{Contact constraints}{\n\\item We may also model contact constraints\n\\item The contact constraint measures the object separation; it is negative in case of overlap\n\\item $C(x_i,q_i,x_j,q_j) = (x_j + r_j - x_i - r_i) \\cdot n_i = 0$\n\\item $\\dot C(x_i,q_i,x_j,q_j) = (v_j + \\omega_j \\times r_j - v_i - \\omega_i \\times r_i) \\cdot n_i + (x_j + r_j - x_i - r_i) \\cdot \\omega_i \\times n_i$\n\\item We assume that both penetration and angular velocity are small, so we ignore the second term\n\\item $\\dot C(x_i,q_i,x_j,q_j) \\approx (v_j + \\omega_j \\times r_j - v_i - \\omega_i \\times r_i) \\cdot n_i$\n}\\end{slide}\n\n\\begin{frame}{Contact constraint}\n\\center\n\\includegraphics[height=5cm]{Pics/ContactConstraint.png}\n\\end{frame}\n\n\\begin{slide}{Constrained dynamics}{Contact constraints}{\n\\item We can now separate $\\dot C$ into $J$ and $V$:\n\\item $\\dot C(x_i,q_i,x_j,q_j) = (v_j + \\omega_j \\times r_j - v_i - \\omega_i \\times r_i) \\cdot n_i = \\left[ -n_i^T\\ -(r_i \\times n_i)^T\\ n_i^T\\ (r_j \\times n_i)^T\\ \\right] \\left[ v_i\\ \\omega_i\\ v_j\\ \\omega_j \\right]^T$\n}\\end{slide}\n\n\\begin{slide}{Constrained dynamics}{Contact constraints}{\n\\item Notice that the force between bodies in contact can push them apart, but not pull them together\n\\item This means that $0 \\leq \\lambda_k \\leq +\\infty$, where $k$ is the constraint index for a contact constraint\n}\\end{slide}\n\n\\begin{slide}{Constrained dynamics}{Contact constraints}{\n\\item In some cases penetration might happen anyway\n\\item Numerical errors or issues with discrete steps\n\\item We allow the velocity to be augmented with a \\textit{pushing factor} which is proportional to the penetration\n\\item This means that for contact constraints $J_i V = -\\ \\beta C_i$, for $\\beta \\leq \\frac{1}{\\Delta t}$\n}\\end{slide}\n\n\\begin{slide}{Constrained dynamics}{Friction constraints}{\n\\item Friction constraints are very similar to contact constraints\n\\item Friction happens along the tangent plane, so we have two constraints (one for $u_i = T$ and one for $u_j = B$)\n\\begin{itemize}\n\\item $\\dot C_{u_i}(x_i,q_i,x_j,q_j) = (v_j + \\omega_j \\times r_j - v_i - \\omega_i \\times r_i) \\cdot u_i = \\left[ -u_i^T\\ -(r_i \\times u_i)^T\\ u_i^T\\ (r_j \\times u_i)^T\\ \\right] \\left[ v_i\\ \\omega_i\\ v_j\\ \\omega_j \\right]^T$ \n\\item $\\dot C_{u_j}(x_i,q_i,x_j,q_j) = (v_j + \\omega_j \\times r_j - v_i - \\omega_i \\times r_i) \\cdot u_j = \\left[ -u_j^T\\ -(r_i \\times u_j)^T\\ u_j^T\\ (r_j \\times u_j)^T\\ \\right] \\left[ v_i\\ \\omega_i\\ v_j\\ \\omega_j \\right]^T$\n\\end{itemize}\n}\\end{slide}\n\n\\begin{slide}{Constrained dynamics}{Friction constraints}{\n\\item We must also bound the friction value (this is an approximation) to take the friction coefficient into account\n\\item $-\\mu m_c g \\leq \\lambda_{u_1} \\leq \\mu m_c g$ and $-\\mu m_c g \\leq \\lambda_{u_2} \\leq \\mu m_c g$, where $m_c$ is the mass assigned to the contact point\n}\\end{slide}\n\n\\section{Equations of motion}\n\\begin{slide}{Equations of motion}{Equations of motion}{\n\\item We now integrate our constraint system with the equations of motion\n\\item We know the $Newton-Euler$ equations of motion are \n$\\begin{matrix}\nm \\dot v & = & F & = & f_c + f_{\\text{ext}} \\\\\nI \\dot w & = & \\tau & = & \\tau_c + \\tau_{\\text{ext}} \\\\\n\\end{matrix}$\n}\\end{slide}\n\n\\begin{slide}{Equations of motion}{Equations of motion}{\n\\item We can define a single, big matrix for all the bodies \n$M = \\left( \\begin{matrix}\nm_1 E _{3 \\times 3} & 0 & \\dots & 0 & 0  \\\\\n0 & I_1 & \\dots & 0 & 0  \\\\\n\\vdots & \\vdots & \\ddots & \\vdots & \\vdots \\\\\n0 & \\dots & 0 & m_n E _{3 \\times 3} & 0  \\\\\n0 & \\dots & 0 & 0 & I_n \\\\\n\\end{matrix} \\right)$\n\\item $E_{3 \\times 3}$ is just the identity matrix\n}\\end{slide}\n\n\\begin{slide}{Equations of motion}{Equations of motion}{\n\\item We can easily invert this matrix\n$M^{-1} = \\left( \\begin{matrix}\n(m_1 E _{3 \\times 3})^{-1} & 0 & \\dots & 0 & 0  \\\\\n0 & I_1^{-1} & \\dots & 0 & 0  \\\\\n\\vdots & \\vdots & \\ddots & \\vdots & \\vdots \\\\\n0 & \\dots & 0 & (m_n E _{3 \\times 3})^{-1} & 0  \\\\\n0 & \\dots & 0 & 0 & I_n^{-1} \\\\\n\\end{matrix} \\right)$\n}\\end{slide}\n\n\\begin{slide}{Equations of motion}{Equations of motion}{\n\\item We can define a single, big vector for all the external forces \n$F_{\\text{ext}} = \\left[ \\begin{matrix}\nf_{\\text{ext}1} \\\\\n\\tau_{\\text{ext}1} \\\\\n\\vdots \\\\\nf_{\\text{ext}N} \\\\\n\\tau_{\\text{ext}N} \\\\\n\\end{matrix} \\right]$\n}\\end{slide}\n\n\\begin{slide}{Equations of motion}{Equations of motion}{\n\\item Since we know that $F_C = J^T \\lambda$, we can rewrite the equations of motion for $n$ bodies as\n$\\left\\{ \\begin{matrix}\nM \\dot V & = & J^T \\lambda + F_{\\text{ext}} \\\\\nJV & = & \\epsilon \\\\\n\\end{matrix} \\right.$\n\\item $\\epsilon$ is the vector of force offsets which allows contact forces to perform work\n\\item We have too many unknowns: $V$, $\\dot V$, and $\\lambda$\n}\\end{slide}\n\n\\begin{slide}{Equations of motion}{Equations of motion}{\n\\item We approximate $\\dot V \\approx \\frac{V_2 - V_1}{\\Delta t}$\n\\item We replace $\\dot V$\n$\\left\\{\\begin{matrix}\nM \\frac{V_2 - V_1}{\\Delta t} & = & J^T \\lambda + F_{\\text{ext}} \\\\\nJV_2 & = & \\epsilon \\\\\n\\end{matrix} \\right.$\n\\item We solve for $V_2$\n$\\left\\{ \\begin{matrix}\nV_2 & = & \\Delta t M^{-1}(J^T \\lambda + F_{\\text{ext}}) + V_1\\\\\nV_2 & = & J^T \\epsilon\n\\end{matrix} \\right.$\n}\\end{slide}\n\n\\begin{slide}{Equations of motion}{Equations of motion}{\n\\item We can now finish solving for $\\lambda$\n\\item $J^T \\epsilon = \\Delta t M^{-1}(J^T \\lambda + F_{\\text{ext}}) + V_1$\n\\item $J^T \\epsilon - V_1 - \\Delta t M^{-1}F_{\\text{ext}} = \\Delta t M^{-1}(J^T \\lambda)$\n\\item $\\frac{\\epsilon}{\\Delta t} - J V_1 - \\Delta t J M^{-1}F_{\\text{ext}} = J M^{-1} J^T \\lambda$\n}\\end{slide}\n\n\\begin{slide}{Equations of motion}{Equations of motion}{\n\\item The equation $\\frac{\\epsilon}{\\Delta t} - J V_1 - \\Delta t J M^{-1}F_{\\text{ext}} = J M^{-1} J^T \\lambda$ admits infinite solutions; this is due to redundant constraints, such as a table with more than three legs\n\\item The force combinations that solve the system are usually infinite\n}\\end{slide}\n\n\\begin{slide}{Equations of motion}{Equations of motion}{\n\\item Once $\\lambda$ is computed, we can determine $F_c$, $F$, and then $V_2$\n\\item A regular integration step is then performed with the new velocities $V_2$\n}\\end{slide}\n\n\\section{Iterative solution of a system of equations}\n\\begin{slide}{Iterative solution}{System of equations}{\n\\item The equation $\\frac{\\epsilon}{\\Delta t} - J V_1 - \\Delta t J M^{-1}F_{\\text{ext}} = J M^{-1} J^T \\lambda$ can be restated in simpler form\n\\item $\\underbrace{\\frac{\\epsilon}{\\Delta t} - J V_1 - \\Delta t J M^{-1}F_{\\text{ext}}}_{b} = \\underbrace{J M^{-1} J^T}_{A} \\underbrace{\\lambda}_{x}$\n\\item $A x = b$ for some $A,b$\n\\item These systems can be solved iteratively with a method such as Projected Gauss-Seidel (PGS)\n}\\end{slide}\n\n\\begin{frame}[fragile]{(Projected) Gauss-Seidel}\n\\begin{lstlisting}[mathescape=true]\nwhile not converged\n  $\\Delta x_i$ = $(b_i - \\sum_j a_{ij} x_j) / A_{ii}$\n  $x_i$ = clamp$(x_i + \\Delta x_i, min_i, max_i)$\n\\end{lstlisting}\n\\end{frame}\n\n\\begin{slide}{Iterative solution}{Sparse matrices}{\n\\item Remember that $A$ is going to be very sparse\n\\item You may optimize the summation $\\Delta x_i$ \\texttt{=} $(b_i - \\sum_j a_{ij} x_j) / A_{ii}$ a lot by ignoring the zero entries of $A$\n}\\end{slide}\n\n\\section{Contact caching}\n\\begin{slide}{Contact caching}{Contact caching}{\n\\item PGS is faster the closer the initial $x$ vector is to the solution\n\\item If we store previous contact points and their $\\lambda_i$ values, PGS converges sooner\n\\item Just be aware of this\n\\begin{itemize}\n\\item Also be aware that it is rather hard to build in practice\n\\item If you attempt it, chances of success may be low\n\\end{itemize}\n}\\end{slide}\n\n\\section{Assignment}\n\\begin{slide}{Assignment}{Assignment}{\n\\item Before the end of next week\n\\item Group-work archive/video on Natschool or uploaded somewhere else and linked in your report\n\\item Individual report by each of you on Natschool\n\\item Build a collision response system that supports collisions between multiple objects\n}\\end{slide}\n\n\\begin{frame}{That's it}\n\\center\n\\fontsize{18pt}{7.2}\\selectfont\nThank you!\n\\end{frame}\n\n\\end{document}\n\n\n\\begin{slide}{SECTION}{SLIDE}{\n\\item i\n}\\end{slide}\n\n\\begin{frame}[fragile]{SLIDE}\n\\begin{lstlisting}\nCODE\n\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}{SLIDE}\n\\center\n%\\includegraphics[height=5cm]{Pics/recursive_multiplier.png}\n\\end{frame}\n", "meta": {"hexsha": "a629c7ba1881e0dac0d9cde4b40dc5f72681da6a", "size": 14160, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Slides/Lecture 6/Lecture 6.tex", "max_stars_repo_name": "hogeschool/TINWIS01-7", "max_stars_repo_head_hexsha": "410b0064f541474f102a3037866e625725fed4c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2015-10-02T23:38:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T04:08:27.000Z", "max_issues_repo_path": "Slides/Lecture 6/Lecture 6.tex", "max_issues_repo_name": "hogeschool/TINWIS01-7", "max_issues_repo_head_hexsha": "410b0064f541474f102a3037866e625725fed4c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2015-08-16T10:05:36.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-16T10:05:47.000Z", "max_forks_repo_path": "Slides/Lecture 6/Lecture 6.tex", "max_forks_repo_name": "hogeschool/TINWIS01-7", "max_forks_repo_head_hexsha": "410b0064f541474f102a3037866e625725fed4c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-02-25T02:31:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-04T07:48:25.000Z", "avg_line_length": 42.0178041543, "max_line_length": 263, "alphanum_fraction": 0.6973163842, "num_tokens": 4642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.32663685924431657}}
{"text": "The GWT Model simulates three-dimensional transport of a single solute species in flowing groundwater.  The GWT Model solves the solute transport equation using numerical methods and a generalized control-volume finite-difference approach, which can be used with regular MODFLOW grids (DIS Package) or with unstructured grids (DISV and DISU Packages).  The GWT Model is designed to work with most of the new capabilities released with the GWF Model, including the Newton flow formulation, unstructured grids, advanced packages, and the movement of water between packages.  The GWF and GWT Models operate simultaneously during a \\mf simulation to represent coupled groundwater flow and solute transport.  The GWT Model can also run separately from a GWF Model by reading the heads and flows saved by a previously run GWF Model.  The GWT model is also capable of working with the flows from another groundwater flow model, as long as the flows from that model can be written in the correct form to flow and head files.  \n\nThe purpose of the GWT Model is to calculate changes in solute concentration in both space and time.  Solute concentrations within an aquifer can change in response to multiple solute transport processes.  These processes include (1) advective transport of solute with flowing groundwater, (2) the combined hydrodynamic dispersion processes of velocity-dependent mechanical dispersion and chemical diffusion, (3) sorption of solutes by the aquifer matrix either by adsorption to individual solid grains or by absorbtion into solid grains, (4) transfer of solute into very low permeability aquifer material (called an immobile domain) where it can be stored and later released, (5) first- or zero-order solute decay or production in response to chemical or biological reactions, (6) mixing with fluids from groundwater sources and sinks, and (7) direct addition of solute mass.\n\nWith the present implementation, there can be multiple domains and multiple phases.  There is a single mobile domain, which normally consists of flowing groundwater, and there can be one or more immobile domains.  The GWT Model simulates the dissolved phase of chemical constituents in both the mobile and immobile domains.  The dissolved phase is also referred to in this report as the aqueous phase.  If sorption is represented, then the GWT Model also simulates the solid phase of the chemical constituent in both the mobile and immobile domains.  The dissolved and solid phases of the chemical constituent are tracked in the different domains by the GWT Model and can be reported as output as requested by the user.\n\nThis section describes the data files for a \\mf Groundwater Transport (GWT) Model.  A GWT Model is added to the simulation by including a GWT entry in the MODELS block of the simulation name file.  There are three types of spatial discretization approaches that can be used with the GWT Model: DIS, DISV, and DISU.  The input instructions for these three packages are not described here in this section on GWT Model input; input instructions for these three packages are described in the section on GWF Model input.\n\nThe GWT Model is designed to permit input to be gathered, as it is needed, from many different files.  Likewise, results from the model calculations can be written to a number of output files. The GWT Model Listing File is a key file to which the GWT model output is written.  As \\mf runs, information about the GWT Model is written to the GWT Model Listing File, including much of the input data (as a record of the simulation) and calculated results.  Details about the files used by each package are provided in this section on the GWT Model Instructions.\n\nThe GWT Model reads a file called the Name File, which specifies most of the files that will be used in a simulation. Several files are always required whereas other files are optional depending on the simulation. The Output Control Package receives instructions from the user to control the amount and frequency of output.  Details about the Name File and the Output Control Package are described in this section.\n\nFor the GWT Model, ``flows'' (unless stated otherwise) represent solute mass ``flow'' in mass per time, rather than groundwater flow.  \n\n\\subsection{Information for Existing Solute Transport Modelers}\nThe \\mf GWT Model contains most of the functionality of MODFLOW-GWT, MT3DMS, MT3D-USGS and MODFLOW-USG.  The following list summarizes major differences between the GWT Model in \\mf and previous MODFLOW-based solute transport programs.\n\n\\begin{enumerate}\n\n\\item The GWT Model simulates transport of a single chemical species; however, because \\mf allows for multiple models of the same type to be included in a single simulation, multiple species can be represented by using multiple GWT Models.\n\n\\item There is no specialized flow and transport link file \\citep{zheng2001modflow} used to pass the simulated groundwater flows to the transport model.  Instead, simulated flows from the GWF Model are passed in memory to the GWT Model while the program is running.  Alternatively, the GWT Model can read binary flow and head files saved by the GWF Model while it is running.  If the user intends to simulate transport through the advanced stress packages and Water Mover Package, then flows from these advanced packages must also be saved to binary files.  Names for these binary files are provided as input to the FMI Package.\n\n\\item The GWT Model is based on a generalized control-volume finite-difference method, which means that solute transport can be simulated using regular MODFLOW grids consisting of layers, rows, and columns, or solute transport can be simulated using unstructured grids.\n\n\\item Advection can be simulated using central-in-space weighting, upstream weighting, or an implicit second-order TVD scheme.  The GWT model does not have the Method of Characteristics (particle-based approaches) or an explicit TVD scheme.  Consequently, the GWT Model may require a higher level of spatial discretization than other transport models that use higher order terms for advection dominated systems.  This can be an important limitation for some problems, which require the preservation of sharp solute fronts. \n\n\\item Variable-density flow and transport can be simulated by including a GWF Model and a GWT Model in the same \\mf simulation.  The Buoyancy Package should be activated for the GWF Model so that fluid density is calculated as a function of simulated concentration.  If more than one chemical species is represented then the Buoyancy Package allows the simulated concentration for each of them to be used in the density equation of state.   \\cite{langevin2020hydraulic} describe the hydraulic-head formation that is implemented in the Buoyancy Package for variable-density groundwater flow and present the results from \\mf variable-density simulations.  The variable-density capabilities available in \\mf replicate and extend the capabilities available in SEAWAT to include the Newton flow formulation and unstructured grids, for example.  \n\n\\item The GWT Model has a Source and Sink Mixing (SSM) Package for representing the effects of GWF stress package inflows and outflows on simulated concentrations.  There are two ways in which users can assign concentrations to the individual features in these stress package.  The first way is to activate a concentration auxiliary variable in the GWF stress package.  In the SSM input file, the user provides the name of the auxiliary variable to be used for concentration.  The second way is to create a special SSMI file, which contains user-assigned time-varying concentrations for stress package boundaries.\n\n\\item The GWT model includes the MST and IST Packages.  These two package collectively comprise the capabilities of the MT3DMS Reactions Package.\n\n\\item The MST Package contains the linear, Freundlich, and Langmuir isotherms for representing sorption.  The IST Packages contains only the linear isotherm for representation of sorption. \n\n\\item The GWT model was designed so that the user can specify as many immobile domains and necessary to represent observed contaminant transport patterns and solute breakthrough curves.  The effects of an immobile domain are represented using the Immobile Storage and Transfer (IST) Package, and the user can specify as many IST Packages as necessary.  \n\n\\item Although there is GWF-GWF Exchange, a GWT-GWT Exchange has not yet been developed to connect multiple transport models, as might be done in a nested grid configuration.  \n\n\\item There is no option to automatically run the GWT Model to steady state using a single time step.  This is an option available in MT3DMS \\citep{zheng2010supplemental}.  Steady state conditions must be determined by running the transport model under transient conditions until concentrations stabilize.\n\n\\item The GWT Model described in this report is capable of simulating solute transport in the advanced stress packages of \\mf, including the Lake, Streamflow Routing, Multi-Aquifer Well and Unsaturated Zone Transport Packages.  The present implementation simulates solute advection between package features, such as between two stream reaches, but dispersive transport is not represented.  Likewise, solute transport between the advanced packages and the aquifer occurs only through advection.\n\n\\item The GWT Model has not yet been programmed to work with the Skeletal Storage, Compaction, and Subsidence (CSUB) Package for the GWF Model.  \n\n\\item There are many other differences between the \\mf GWT Model and other solute transport models that work with MODFLOW, especially with regards to program design and input and output.  Descriptions for the GWT input and output are described here.\n\n\\end{enumerate}\n\n\\subsection{Units of Length and Time}\nThe GWF Model formulates the groundwater flow equation without using prescribed length and time units. Any consistent units of length and time can be used when specifying the input data for a simulation. This capability gives a certain amount of freedom to the user, but care must be exercised to avoid mixing units.  The program cannot detect the use of inconsistent units.\n\n\\subsection{Solute Mass Budget}\nA summary of all inflow (sources) and outflow (sinks) of solute mass is called a mass budget.  \\mf calculates a mass budget for the overall model as a check on the acceptability of the solution, and to provide a summary of the sources and sinks of mass to the flow system.  The solute mass budget is printed to the GWT Model Listing File for selected time steps.\n\n\\subsection{Time Stepping}\n\nFor the present implementation of the GWT Model, all terms in the solute transport equation are solved implicitly.  With the implicit approach applied to the transport equation, it is possible to take relatively large time steps and efficiently obtain a stable solution.  If the time steps are too large, however, accuracy of the model results will suffer, so there is usually some compromise required between the desired level of accuracy and length of the time step.  An assessment of accuracy can be performed by simply running simulations with shorter time steps and comparing results.\n\nIn \\mf time step lengths are controlled by the user and specified in the Temporal Discretization (TDIS) input file.  When the flow model and transport model are included in the same simulation, then the length of the time step specified in TDIS is used for both models.  If the GWT Model runs in a separate simulation from the GWT Model, then the time steps used for the transport model can be different, and likely shorter, than the time steps used for the flow solution.  Instructions for specifying time steps are described in the TDIS section of this user guide; additional information on GWF and GWT configurations are in the Flow Model Interface section.  \n\n\n\n\\newpage\n\\subsection{GWT Model Name File}\n\\input{gwt/namefile.tex}\n\n%\\newpage\n%\\subsection{Structured Discretization (DIS) Input File}\n%\\input{gwf/dis}\n\n%\\newpage\n%\\subsection{Discretization with Vertices (DISV) Input File}\n%\\input{gwf/disv}\n\n%\\newpage\n%\\subsection{Unstructured Discretization (DISU) Input File}\n%\\input{gwf/disu}\n\n\\newpage\n\\subsection{Initial Conditions (IC) Package}\n\\input{gwt/ic}\n\n\\newpage\n\\subsection{Output Control (OC) Option}\n\\input{gwt/oc}\n\n\\newpage\n\\subsection{Observation (OBS) Utility for a GWT Model}\n\\input{gwt/gwt-obs}\n\n\\newpage\n\\subsection{Advection (ADV) Package}\n\\input{gwt/adv}\n\n\\newpage\n\\subsection{Dispersion (DSP) Package}\n\\input{gwt/dsp}\n\n\\newpage\n\\subsection{Source and Sink Mixing (SSM) Package}\n\\input{gwt/ssm}\n\n\\newpage\n\\subsection{Mobile Storage and Transfer (MST) Package}\n\\input{gwt/mst}\n\n\\newpage\n\\subsection{Immobile Storage and Transfer (IST) Package}\n\\input{gwt/ist}\n\n\\newpage\n\\subsection{Constant Concentration (CNC) Package}\n\\input{gwt/cnc}\n\n\\newpage\n\\subsection{Mass Source Loading (SRC) Package}\n\\input{gwt/src}\n\n\\newpage\n\\subsection{Streamflow Transport (SFT) Package}\n\\input{gwt/sft}\n\n\\newpage\n\\subsection{Lake Transport (LKT) Package}\n\\input{gwt/lkt}\n\n\\newpage\n\\subsection{Multi-Aquifer Well Transport (MWT) Package}\n\\input{gwt/mwt}\n\n\\newpage\n\\subsection{Unsaturated Zone Transport (UZT) Package}\n\\input{gwt/uzt}\n\n\\newpage\n\\subsection{Flow Model Interface (FMI) Package}\n\\input{gwt/fmi}\n\n\\newpage\n\\subsection{Mover Transport (MVT) Package}\n\\input{gwt/mvt}\n\n", "meta": {"hexsha": "837e698466274ad0acfc3923ff52d03bb3d41248", "size": 13391, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/mf6io/gwt/gwt.tex", "max_stars_repo_name": "scharlton2/modflow6", "max_stars_repo_head_hexsha": "83ac72ee3b6f580aaffef6352cf15c1697d3ce66", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 102, "max_stars_repo_stars_event_min_datetime": "2017-12-19T09:56:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T01:47:28.000Z", "max_issues_repo_path": "doc/mf6io/gwt/gwt.tex", "max_issues_repo_name": "scharlton2/modflow6", "max_issues_repo_head_hexsha": "83ac72ee3b6f580aaffef6352cf15c1697d3ce66", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 331, "max_issues_repo_issues_event_min_datetime": "2018-01-10T21:22:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T05:57:00.000Z", "max_forks_repo_path": "doc/mf6io/gwt/gwt.tex", "max_forks_repo_name": "scharlton2/modflow6", "max_forks_repo_head_hexsha": "83ac72ee3b6f580aaffef6352cf15c1697d3ce66", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 87, "max_forks_repo_forks_event_min_datetime": "2017-12-13T21:40:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T05:31:40.000Z", "avg_line_length": 92.9930555556, "max_line_length": 1018, "alphanum_fraction": 0.805391681, "num_tokens": 2924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300698514777, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.3266073334110084}}
{"text": "\n\\subsection{The Golden Rule savings rate}\n\nThe Golden Rule savings rate is the rate which maximises long term consumption per capita.\n\nIf the savings rate is \\(0\\) there is no capital and no income. If the savings rate is \\(1\\) then then there is no consumption.\n\n", "meta": {"hexsha": "03fb41a1a965cf0cb4c80ca46c1e041c95e1debd", "size": 265, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/pug/theory/economics/neoClassical/03-04-goldenRule.tex", "max_stars_repo_name": "adamdboult/nodeHomePage", "max_stars_repo_head_hexsha": "266bfc6865bb8f6b1530499dde3aa6206bb09b93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pug/theory/economics/neoClassical/03-04-goldenRule.tex", "max_issues_repo_name": "adamdboult/nodeHomePage", "max_issues_repo_head_hexsha": "266bfc6865bb8f6b1530499dde3aa6206bb09b93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-03-03T12:36:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-01T22:16:09.000Z", "max_forks_repo_path": "src/pug/theory/economics/neoClassical/03-04-goldenRule.tex", "max_forks_repo_name": "adamdboult/nodeHomePage", "max_forks_repo_head_hexsha": "266bfc6865bb8f6b1530499dde3aa6206bb09b93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.125, "max_line_length": 127, "alphanum_fraction": 0.7622641509, "num_tokens": 58, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.63341027751814, "lm_q1q2_score": 0.32659895391199534}}
{"text": "\\paragraph{}\nThe IGES\\citep{IGES1983} files introduced in Sec.~\\ref{lr_sec:IGES} are used as the bridge between the engineering design and the numerical analysis in the proposed method.\nAs a standard file format in engineering design industry, it is supported by almost all design softwares all over the world.\nConsequently, it offers a possibility to minimize the human efforts spent on geometric modeling.\n\n\\subsection{Parse geometry in IGES file}\n\\paragraph{}\nThe IGES file provides all information that describe the geometric input.\nAbstract structure of the IGES file that describes the 2D geometry can be regarded as a simple curve-surface structure.\nIn other words, it defines the geometric input as certain number of surfaces with their boundaries in different colors, which represents different materials in engineering practice.\nEach surface contains a list of curve indices which are corresponding to the curve information described in IGES file.\n\n\\paragraph{}\nWhen the IGES file is feed into the programme, each line in the directory entry will be parsed entity by entity.\nParameters in directory entry describe the type and reference to other useful values for the entity.\nAn entity may refer to one or many entities in directory entry.\nDetail of the specification of each entity is explained in \\cite{Nasr2007}.\n\n%=====================================================================================================================%\n\\subsection{Output to mesh generator}\n\\label{qdt_section:iges_output}\n\\paragraph{}\nThe output file that the mesh generator read in will be a shorter summary of the geometric input.\nBoundary representation will be kept as the data structure to describe the geometric input.\nHowever, some fields apart from the curves or the surfaces will be added.\nIn the output file, the geometry will be organized in key points, polylines and surfaces.\nThe key points define the coordinates of all points and polylines are used to represent all curves including NURBS curves for simplification.\nNURBS curves introduced in in \\ref{lr_sec:NURBS} can be used directly by the mesh generator as well but it is found that the computational cost in the calculation of the distance between points to NURBS curves surpasses the merits of using it directly.\nThe exact geometry can be retained by projecting the nodes on the boundary back to the origin NURBS curves after the mesh is generated.\n\n\\paragraph{}\nRepresenting a straight line with polyline can be natural, first and the last points will be enough to achieve an exact representation.\nHowever, that is not the case for curves whose curvature is not always zero.\nAlthough adding more key points can increase the quality of polyline representation, computational cost in calculating the distance increases at the same time.\nYet, having only few key points may result in a bad polyline representation which leads to a poor mesh quality.\nElements may be twisted after the nodes on the boundary are projected to the origin curves.\nAs a consequence, a quantified indicator that is able to control the number and the position of the vertices on the polyline can be necessary.\n\n%=====================================================================================================================%\n\\subsection{Discretization of the circular arc}\n\\paragraph{}\nThe chord ratio can be a good indicator for circular arc.\nThe arc length to chord length ratio $\\frac{a}{L}$ illustrated in Fig.~\\ref{qt_fig:iges_chord_ratio} can be expressed in angle $\\alpha$ as:\n    \\begin{equation}\n        \\frac{a}{L} = \\frac{\n            \\sqrt{2-2\\cos\\alpha}\n        }{\\alpha}\n        = \\frac{\n            2\\sin\\frac{\\alpha}{2}\n        }{\\alpha}\n    \\end{equation}\n%\nThe maximum angle $\\alpha$ satisfy arc length to chord length ratio $\\frac{a}{L} > 1-\\epsilon$ with $\n    \\sin\\frac{\\alpha}{2} = 1 - \\frac{x^3}{6} + O(x^7)\n$ can be derived as:\n    \\begin{equation}\n        \\alpha < \\sqrt{24 \\epsilon}\n    \\end{equation}\n\n    \\begin{figure}[h!]\n        \\centering\n        \\scalebox{1}{\n            \\includegraphics{quadtree/images/iges_chord_ratio.eps}\n        }\n        \\caption{Chord length for circular arc}\n        \\label{qt_fig:iges_chord_ratio}\n    \\end{figure}\n%\n%=====================================================================================================================%\n\\subsection{Discretization of the NURBS curve}\n\\paragraph{}\nFor NURBS curves who have no closed form chord ratio, similar idea can be applied numerically.\nThe NURBS curve is first divided into serval smaller ones based on the knot vector as described in Sec.~\\ref{lr_sec:nurbs_knot_ins}.  % may be explained in detail\nSince the order of each subdivided NURBS curve used in engineering softwares are predominantly lower or equal to three, the sub-curves then can be divided into two classes, convex curves or concave curves with an inflection point as shown in Fig.~\\ref{qt_fig:iges_chord_ratio_nurbs}.\n    \\begin{figure}\n        \\begin{subfigure}[b]{0.5\\linewidth}\n            \\centering\n            \\scalebox{0.5}{\n                \\includegraphics{quadtree/images/iges_chord_ratio_nurbs_convex.eps}\n            }\n            \\caption{Convex}\n        \\end{subfigure}\n        \\begin{subfigure}[b]{0.5\\linewidth}\n            \\centering\n            \\scalebox{0.5}{\n                \\includegraphics{quadtree/images/iges_chord_ratio_nurbs_concave.eps}\n            }\n            \\caption{Concave with an inflection point}\n        \\end{subfigure}\n    \\caption{Type of sub-devided NURBS curves: convex and concave with an inflection point}\n    \\label{qt_fig:iges_chord_ratio_nurbs}\n    \\end{figure}\n%\nIn order to determine the target NURBS curve is convex one or concave one, a cross product will be conducted.\nby assuming the subdivided NURBS curve is cubic, there will be four control points $P_1,P_2,P_3$ and $P_4$.\nIf the signs of $cross(\\overrightarrow{P_1P_2},\\overrightarrow{P_2P_3})$ and $cross(\\overrightarrow{P_1P_2},\\overrightarrow{P_2P_3})$ are the same, then the curve is convex.\nOtherwise it will be concave.\n\n%=====================================================================================================================%\n\\subsubsection{Convex curves}\n\\label{qt_ssc:convex_curves}\n\\paragraph{}\nStart with the simple case, in the situation illustrated in Fig.~\\ref{qt_fig:iges_chord_split_convex_sum} where line $C(u_0)C(u_n)$ and the NURBS curve form a convex set, we are looking for a point $C(u_m)$ on the curve so that $C'(u_m)$ is parallel to $\\overrightarrow{C(u_0)C(u_n)}$\n    \\begin{figure}[h!]\n        \\centering\n        \\scalebox{0.6}{\n            \\includegraphics{quadtree/images/iges_chord_split_convex_sum.eps}\n        }\n        \\caption{Discretization for convex NURBS curve}\n        \\label{qt_fig:iges_chord_split_convex_sum}\n    \\end{figure}\n%\nThe target is to split one NURBS curve segment into two.\nThe splitting will be processed until the arc length to chord length ratio of any splitted curves are smaller than the tolerance.\nBased on the property of the convex set, there can be one and only one parameter $u_m$ that satisfies the condition.\nAs a consequence, numerical methods such as Newton's method can be adopted to determine it.\nFor a given $u_m$, the next iteration will be:\n    \\begin{equation}\n        u_{m_{new}} =  u_n - \\frac{f(u_m)}{f'(u_m)}\n    \\end{equation}\n%\nwhere \n    \\begin{equation}\n        f(u) = C'(u) \\begin{bmatrix}\n            - C_y(u_n) + C_y(u_0) \\\\\n            C_x(u_n) - C_x(u_0)\n        \\end{bmatrix}\n    \\end{equation}\n%\nThe procedure to find $u_m$ can be concluded in Algorithm.~\\ref{qdt_alg:split_convex_nurbs} and Algorithm.~\\ref{qdt_alg:discrete_convex_nurbs} describes the procedure to find all knots corresponding to the vertexes of the polylines recursively.\n\\begin{algorithm}\n    function splitConvexCurve(curve,u\\_0, u\\_n) \\\\\n    \\Input{\n        curve, the input NURBS curve \\\\\n        u\\_0,u\\_n, two end knots of the NURBS curve\n    }\n    \\Output{\n        u\\_m, in Fig.~\\ref{qt_fig:iges_chord_split_convex_sum}\n    }\n    u\\_m = (u\\_n + u\\_0) * 0.5 \\\\\n    pt\\_0, pt\\_n = getCurvePts(u\\_0, u\\_n) \\\\\n    vector\\_0n = Vector(pt\\_0,pt\\_n) \\\\\n    angle = vector\\_0n.atan2() \\\\\n    deri1\\_m = getCurveDeri(u\\_m,1) \\\\\n    angle\\_m = deri1\\_m.atan2() \\\\\n    \\While{abs(angle\\_m-anlge)$<10^{-4}$}\n      {\n        deri1\\_m, deri2\\_m = getCurveDeri(u\\_m,2) \\\\\n        angle\\_m = atan2(deri1\\_m.y, deri1\\_m.x)  \\\\\n        fu = deri1\\_m * vector\\_0n.normalVector() \\\\\n        fu\\_deri = deri2\\_m * vector\\_0n.normalVector() \\\\\n        u\\_m = u\\_m - fu / fu\\_deri \\\\\n        deri1\\_m = getCurveDeri(u\\_m,1) \\\\\n        angle\\_m = deri1\\_m.atan2()\n      }\n    \\caption{Split a convex NURBS curve into two}\n    \\label{qdt_alg:split_convex_nurbs}\n\\end{algorithm}\n%\n%\n\\begin{algorithm}\n    function discreteConvexCurve(curve,eps,u\\_0,u\\_n,u)\n    \\Input{\n        curve, the input NURBS curve \\\\\n        eps, the tolerance of the chord to arc-length ratio \\\\\n        u\\_0,u\\_n, two end knots of the NURBS curve\n    }\n    \\Output{\n        u, the vector of the knot corresponding to vertexes of the polylines\n    }\n    arcLength = curve.arcLength(u\\_0,u\\_n) \\\\\n    chordLength = curve.getPt(u\\_0).distanceTo(curve.getPt(u\\_n)) \\\\\n    \\eIf{1-chordLength/arcLength $<$ eps}{\n        return\n    }{\n        u\\_m = (splitConvexCurve(curve,u\\_0,u\\_n))\n        u.add(u\\_m)\n        discreteConvexCurve(curve,eps,u\\_0,u\\_m)\n        discreteConvexCurve(curve,eps,u\\_m,u\\_n)\n        return\n    }    \n\\caption{Discrete a convex NURBS curve recursively}\n\\label{qdt_alg:discrete_convex_nurbs}\n\\end{algorithm}\n%=====================================================================================================================%\n\\subsubsection{Concave curves}\n\\paragraph{}\nAs can be seen in Fig.~\\ref{qt_fig:iges_chord_ratio_nurbs}, the extracted cubic NURBS curve will have no more than one inflection point.\nThe reason for that is because the target function is cubic and hence its second derivative will be in first order.\nConsequently, numerical methods such as Newton's method can be used to find this unique point.\nAfter that, the curve can be divided into two convex ones and the algorithms introduced in \\ref{qt_ssc:convex_curves} can be used separately.\nThe Newton's iteration can be written as\n    \\begin{equation}\n        u_{n_{new}} = u_n - \\frac{f(u_n)}{f'(u_n)}\n    \\end{equation}\n\nwhere\n    \\begin{equation}\n        f(u) = C''(u)\n    \\end{equation}\n%\n%=====================================================================================================================%\n\\subsubsection{Calculation of the arc length}\n\\paragraph{}\nThe arc length of the NURBS curve defined on $u \\in [u_0, u_n]$ can be expressed as\n    \\begin{equation}\n        L = \\int_{u_0} ^{u_n} \\sqrt{C_x^2(u) + C_y^2(u)} du\n    \\end{equation}\n%\nThe integration can be solved by the help of the numerical integration quadrature described in \\ref{iso_section:numerical_integration} as:\n    \\begin{equation}\n        L = \\sum_{i=0}^n a_i \\sqrt{C_x^2(u_i) + C_y^2(u_i)}\n    \\end{equation}\n", "meta": {"hexsha": "0de8dcf7adb99cba4daa4d992e9e056559935867", "size": 11050, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "quadtree/iges.tex", "max_stars_repo_name": "fa93hws/thesis", "max_stars_repo_head_hexsha": "c397ddc18e5ff5d6e9b8d6de2e53be4c9c7b7a2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-10-30T12:14:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-30T12:14:47.000Z", "max_issues_repo_path": "quadtree/iges.tex", "max_issues_repo_name": "fa93hws/thesis", "max_issues_repo_head_hexsha": "c397ddc18e5ff5d6e9b8d6de2e53be4c9c7b7a2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "quadtree/iges.tex", "max_forks_repo_name": "fa93hws/thesis", "max_forks_repo_head_hexsha": "c397ddc18e5ff5d6e9b8d6de2e53be4c9c7b7a2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.6355140187, "max_line_length": 284, "alphanum_fraction": 0.6657013575, "num_tokens": 2846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.32652163014698166}}
{"text": "\\chapter{Sized Dependent Types} \\label{ch:sized-dep-types}\n\n\\input{figures/sized.tex}\n\\input{figures/ind.tex}\n\nThis chapter can be divided into two halves:\nthe first gives the formal description of the syntax, judgements, and rules of \\lang,\nwhile the second provides a number of examples written in \\lang to show how sized types can be used.\nThey are kept separate so that the examples don't detract from the formal description\nand vice versa, but can be read in parallel;\nthe examples provide intuition for understanding the rules,\nwhile the rules ensure proper understanding of why the examples are correct.\n\nIn the sections to follow,\nI use ellipses \\new{$\\seq$} as metanotation for denoting a repeated sequence of some syntactic construct,\noverlines \\new{$\\vec{\\phantom{I}}$} for sequences of variables or terms specifically (\\eg $\\vec{z}$, $\\vec{p}$),\nand \\new{$\\mt$} for denoting an empty sequence (particularly in the context of environments).\nIrrelevant constructs are omitted using an underscore \\new{$\\any$}.\nMetafunctions are introduced in the prose as needed.\n\n\\section{Base \\lang}\n\nAlthough sized types are quite pointless without any inductive types to be sized,\nI present in this subsection the sublanguage of \\lang without naturals or well-founded trees\nto not only get the preliminary details out of the way first,\nbut also to show that the sublanguage is independent of the chosen inductive types.\n\n\\FigSyntax{fig:syntax}\n\\cref{fig:syntax} gives its syntax, which consists of universes $U$,\nsizes $s$, and terms $e$, which includes term functions and size abstractions.\nNote that the hierarchy of universes above $\\Prop$ start at $\\Type{1}$, not $\\Type{0}$.\nMost judgements use two environments: a term environment $\\Gamma$ with assumptions $\\annot{x}{\\tau}$\nand type-annotated definitions $\\define{x}{\\tau}{e}$,\nand a size environment $\\Phi$ with unbounded and bounded size variables.\nI also use the assumption environment%\n\\footnote{These are conventionally called \\emph{telescopes}\\index{telescopes} due to \\citet{telescope}.}\n$\\Delta$ as a shorthand when writing nested expressions with assumptions;\nin particular, letting for instance $\\Delta_{xy} = \\annot{x}{\\sigma_1}, \\annot{y}{\\sigma_2}$,\nI use \\new{$\\arr*{\\Delta_{xy}}{\\tau}$} to mean $\\funtype{x}{\\sigma_1}{\\funtype{y}{\\sigma_2}{\\tau}}$.\nSimilarly, I use \\new{$\\arr*{\\sigma}{\\tau}$} to mean the nondependent function type $\\funtype{\\any}{\\sigma}{\\tau}$\nAs a loose convention, I use $\\tau, \\sigma$ for type-like terms,\n$P$ for the \\emph{motive} of eliminators,\n$z$ for variables representing constructor arguments, and\n$f, g$ for variables representing functions.\n\nAs mentioned in \\cref{ch:introduction}, the judgement forms of \\lang include\nreduction, its various closures, $\\alpha$-cumulativity, subtyping, and typing.\nOn top of those, there are also judgement forms for subsizing, sizes,\nand well-formedness of size and term environments.\n\n\\FigRed{fig:reduction}\nThe reduction rules and their reflexive, transitive closure are described in \\cref{fig:reduction}.\n\\new{$\\subst{e}{x}{e'}$} denotes capture-avoiding substitution of $x$ for $e'$ within $e$,\nand correspondingly \\new{$\\subst{e}{x_1, \\seq, x_n}{e_1, \\seq, e_n}$} denotes simultaneous substitution.\nFor every syntactic form of a composite term there is a corresponding congruence rule,\nwhich is summarized by the last reduction rule using substitution;\nthe full set of rules can be found in \\cref{app:cong:red}.\nBy convention, the reduction rules for function applications are also referred to as $\\beta$-reduction,\nfor $\\kw{let}$ expressions as $\\zeta$-reduction,\nand for defined variables as $\\delta$-reduction.\n\nThese rules can be thought of as a description of nondeterministic evaluation of open terms,\n``running'' from the left term to the right.\nSeparating them into reduction rules that only step once somewhere in the term\nand their reflexive, transitive closure,\nas opposed to the convention used by \\eg \\citet{wjb}\nwhere $\\rhd^*$ corresponds to the reflexive, transitive, \\emph{compatible} closure,\nallows for the usual proof techniques to prove confluence.\n\n\\FigSubtype{fig:subtyping}\nRather than a single subtyping\\index{subtyping} judgement like in\n\\GCC\\index{Calculus of Constructions!Generalized \\textasciitilde},\nI use the same presentation as MetaCoq\\index{MetaCoq}\nand split it into a subtyping judgement\nand a separate $\\alpha$-cumulativity\\index{$\\alpha$-cumulativity} judgement,\nlisted in \\cref{fig:subtyping}.\nThis overcomes some technical proof complications specific to the syntactic model\nthat appear in the single-judgement presentation due to the transitivity rule.\nAside from the expected cumulativity of universes,\nthe function type and size quantification are covariant in the codomain\n(\\ie are $\\alpha$-cumulative when their codomains are),\nwhile remaining invariant in the domain\\punctstack{.}%\n\\footnote{The domain could be made contravariant instead if function type subtyping\nin \\CICE were similarly contravariant,\nbut to my knowledge, there is no such variant of CIC with untyped conversion\\index{conversion}\nand without $\\eta$-conversion that has been proven consistent.}\nAll other types are invariant, as reflected by \\rref{acum-refl}.\nA term is then a subtype of another if they are confluent up to $\\alpha$-cumulativity.\n% Conversion can be defined as the confluence of two terms,\n% but conversion isn't needed for any judgements so I exclude the definition.\n\nNotably, \\lang does \\emph{not} have a notion of $\\eta$-conversion\\index{$\\eta$-conversion}\nin either the reduction rules or in the subtyping rules,\nwhich would otherwise allow conversion between $\\fun{x}{\\tau}{\\app{f}{x}}$ and $f$.\nMixing $\\eta$-conversion and untyped conversion is notoriously difficult~\\citep{eta},\nand remains to date an unresolved problem in MetaCoq\\index{MetaCoq}, so I exclude it here.\n\n\\clearpage % TODO: clearpage\n\\FigSubsize{fig:subsizing}\n\\cref{fig:subsizing} describes a preorder on sizes such that\nthe successor operator is monotonic with respect to the order.\nThe base size $\\circ$ is smaller than all sizes,\nand the strict preorder $\\bound{\\alpha}{s}$ arising from bounded quantification or abstraction\nis defined as $\\sss{\\alpha} \\mathrel{\\leqslant} s$.\nAn additional size judgement ensures well-scopedness of sizes.\nThe size environment must be well formed as well;\nits rules are listed in \\cref{fig:wf},\nalong with those for well-formedness of term environments.\n\\FigWF{fig:wf}\n\n\\FigRulesAxioms{fig:rules-axioms}\n\\FigTyping{fig:typing}\nFinally, the typing rules for the base \\lang are given in \\cref{fig:typing}.\nThey use the metafunctions $\\axioms{\\mt}$ for the type of a universe,\n$\\rules{\\mt}{\\mt}$ for the type of a function type,\ndefined in \\cref{fig:rules-axioms},\nand $\\fresh{\\seq}$ for fresh variables.\n\n\\clearpage % TODO: clearpage\n\\rref{var, univ, let} are the usual rules for variables, universes, and $\\kw{let}$ expressions\nin \\GCC,\\index{Calculus of Constructions!Generalized \\textasciitilde}\nwhile \\rref{pi, lam, app} are the usual ones for functions.\nThe $\\Prop$ universe is impredicative\\index{impredicativity} because\na function type quantifying over any type is itself in $\\Prop$\nas long as its codomain is as well,\nallowing a restricted form of circularity.\nFor example, a function $\\id \\mathrel{\\coloneqq} \\fun{\\tau}{\\Prop}{\\fun{x}{\\tau}{x}}$\ncan be assigned the type $\\Id \\mathrel{\\coloneqq} \\funtype{\\tau}{\\Prop}{\\arr*{\\tau}{\\tau}}$ in $\\Prop$\nand applied to its own type and itself to yield $\\app{\\id}{\\Id}{\\id}$\nof type $\\Id$.\n\n\\rref{conv} uses the subtyping judgement and essentially allows casting a term\nfrom one type to a supertype as needed.\nIf we were working in a bidirectional presentation,\nwhere the typing judgement is replaced by either\n\\emph{type checking}, which checks an input term against an input type,\nor \\emph{type synthesis}, which synthesizes an output type for an input term,\nthis rule for $\\type{\\Phi; \\Gamma}{e}{\\tau}$ would be the sole checking rule,\nfirst synthesizing types $\\sigma$ and $U$ for $e$ and $\\tau$ respectively,\nthen checking $\\sigma$ against $U$,\nand lastly asserting that $\\sigma$ is indeed a subtype of $\\tau$.\nThis is why, despite $\\type{\\Phi; \\Gamma}{\\sigma}{U}$ being derivable,\nI choose to retain it as a premise.\n\n\\rref{forall, forall<, slam, slam<, sapp, sapp<} are the new rules relevant to sized types,\ndescribing bound and unbound size quantification, abstraction, and application,\nwhich work similarly to functions.\nOf note is the bounded size application rule,\nwhich only allows applications to smaller sizes following the subsizing judgement.\n\n\\iffalse\nLastly are \\rref{eq, refl, J} for propositional equality.\nThe constructor $\\refl{e}$ is a reflexive proof of $\\eq{e}{\\tau}{e}$,\nthat $e$ of type $\\tau$ is equal to itself.\nGiven some equality proof $p$ of $\\eq{e_1}{\\tau}{e_2}$\nand a motive\\index{motive} $P$ taking some $y$ of type $\\tau$ and a proof that $\\eq{e_1}{\\tau}{y}$,\nthe $\\J*$ eliminator is a proof of $\\app{P}{e_2}{p}$ when provided a proof of $\\app{P}{e_1}{\\refl{e_1}}$.\nOther usual functions on proofs of equality can be derived from it,\nsuch as coercion (when the motive is a constant function on types in its first argument)\nor substitution (when the motive ignores the second argument).\n$\\J*$ is only well typed when fully applied;\nit can be manually uncurried for a specific universe $U$ as the function\n\\marginnote{The type annotation for the equality type and argument to $\\refl{}$ may be omitted when evident from context.}\n$$\\fun{\\tau}{U}{\\fun{e_1}{\\tau}{\\fun{e_2}{\\tau}{\\fun{P}{(\\funtype{y}{\\tau}{\\funtype{z}{\\eq{e_1}{}{y}}{U}})}{\\fun{d}{\\app{P}{e_1}{\\refl{}}}{\\fun{p}{\\eq{e_1}{}{e_2}}{\\J{P}{d}{p}}}}}}},$$\nand similarly for $\\refl{}$.\n\\fi\n\n\\section{Inductive Types: Naturals and Well-Founded Trees}\\label{sec:ind-types}\n\n\\FigSyntaxInd{fig:syntax-ind}\n\\cref{fig:syntax-ind} extends the grammar with sized naturals, sized well-founded trees,\n$\\kw{case}$ expressions, and fixpoint expressions.\nInformally, borrowing syntax from the definition of general inductives,\nsized naturals and well-founded trees can be thought of as being defined by the following:\n%\n\\begin{align*}\n&\\data{\\N{\\alpha}}{\\Type{1}} && \\data{\\App{\\app{\\W*}{(\\annot{A}{\\Type{i}})}{(\\annot{B}{\\arr*{A}{\\Type{i}}})}}{\\alpha}}{\\Type{i+1}} \\\\\n&\\quad \\annot{\\zero*}{\\Funtype<{\\beta}{\\alpha}{\\N{\\alpha}}} && \\quad \\annot{\\sup*}{\\Funtype<{\\beta}{\\alpha}{\\arr{x}{A}{\\arr*{(\\arr*{\\app{B}{x}}{\\app{\\App{\\W*}{\\beta}}{A}{B}})}{\\App{\\app{\\W*}{A}{B}}{\\alpha}}}}} \\\\\n&\\quad \\annot{\\succ*}{\\Funtype<{\\beta}{\\alpha}{\\arr*{\\N{\\beta}}{\\N{\\alpha}}}}\n\\end{align*}\n\n\\clearpage % TODO: clearpage\nThe types of naturals and well-founded trees can then be considered to be (nonuniformly) parametrized by a size,\nand constructing an element of that type requires providing a strictly smaller size,\nwhich is the size%\n\\footnote{The ``size of'' some construction is more precisely the size by which its \\emph{inductive type} is parametrized.}\nof the constructor's recursive arguments.\nConstructors therefore always construct elements whose sizes are larger than their arguments'.\nIn \\lang, the constructors are annotated with their types\nsince the parameter-like sizes cannot otherwise be synthesized.\nAdditionally, W types have explicit binders for convenience:\nthe variable $x$ is bound within $\\tau$ in the type $\\W{x}{\\sigma}{\\tau}{s}$.\n\nThe expression\n$\\match{e}{\\fun*{x}{P}}{(\\app{\\App{c}{\\alpha}}{z_1}{\\seq}{z_m} \\Rightarrow e_c) \\seq}$\ncontains three parts:\nthe \\emph{target} $e$ it destructs,\nthe motive $P$ denoting the return type of the expression abstracted over a target,\nand the \\emph{branches} $e_c$, one for each constructor of the target's type,\nabstracted over the constructor's size and term arguments.\nIts reduction rules for each constructor are given in \\cref{fig:reduction-ind},\nalong with the reduction rule for fixpoint expressions.\nBy convention, the reduction rules for $\\kw{case}$ expressions\nare also referred to as $\\iota$-reduction,\nand for fixpoint expressions as $\\mu$-reduction.\n\\FigRedInd{fig:reduction-ind}\n\nFixpoints reduce when applied to some size $s$ by substitution of itself into its own body.\nFixpoints' bodies are well typed when recursive applications occur only on smaller sizes,\nso the substitution wraps itself in a bound size abstraction.\nMost importantly, they reduce only when there exists some size strictly smaller than $s$;\nintuitively, this restriction prevents fixpoints from reducing indefinitely\nbecause subsizing is well founded, and there cannot be an infinite chain of smaller sizes.\n\nThis reduction strategy supersedes the usual restriction that fixpoints only reduce\nwhen applied to a constructor,\nsince all sized constructors carry a smaller size argument\nthat will satisfy the subsizing premise.\nFurthermore, reduction can also occur when the fixpoint is applied to a successor size\nby reflexivity of subsizing, \\ie $\\App{(\\fix{f}{\\alpha}{\\tau}{e})}{\\sss{s}}$ will reduce to\n$\\subst{e}{\\alpha, f}{\\sss{s}, \\Fun<{\\beta}{s}{\\App{(\\fix{f}{\\alpha}{\\tau}{e})}{\\beta}}}$\nsince $s < \\sss{s}$.\n\n\\FigTypingInd{fig:typing-ind}\n\nThe typing rules for all new constructs are given in \\cref{fig:typing-ind}.\nOne additional metafunction $\\FV{\\mt}$ produces the free variables in the given term.\nThe type of naturals and well-founded trees are well typed\nwhen the sizes they are applied to are well formed, and\ntheir constructors are well typed when applied to smaller sizes.\n\n$\\kw{case}$ expressions match on these size arguments in addition to the usual term arguments,\nasserting within their branches that they are strictly smaller than the target's size.\nThe motive is dependent on the target,\nand the type of a branch is the motive with its target as the constructor being destructed.\nIn other words, $\\kw{case}$ expressions are inversion principles:\nfor instance, one proves $P$ for some natural $x$ when one can prove it\nfor the base case where $x$ is some $\\zero*$\nand for the step case where $x$ is some $\\succ*$.\n\nAs discussed, the body of a fixpoint is only well typed\nwhen the fixpoint is recursively applied to a smaller size,\nas enforced by its type in the environment when type checking the body.\n\nSizes aside, the only difference from regular, unsized naturals and well-founded trees\nis that their types live in a universe one level higher than they usually are.\n$\\N{s}$ lives in $\\Type{1}$ rather than in $\\Type{0}$,\nand $\\W{x}{\\sigma}{\\tau}{s}$ lives in $\\axioms{U}$ rather than in $U$.\nThis is a direct consequence of the way that the translation is defined,\nand is necessary to maintain its type preservation\\index{type preservation} properties.\nWhile not incorrect, inductive types living in the ``wrong'' universe is aesthetically unpleasant\nand removes some of the impredicativity\\index{impredicativity} of their parameters\nby preventing them from quantifying over the inductive types themselves.\nI discuss potential methods of circumventing this undesirable trait to varying degrees of success\nlater in \\cref{sec:universe-levels}.\n\n\\section{Examples}\\label{sec:examples}\n\nNow that the rules of \\lang have been established,\nthis section presents examples of using \\lang\nfor programming and proving.\nAlthough it only has naturals and well-founded trees,\nI also use other sized inductive types as examples,\ninformally defining them similarly to \\cref{sec:ind-types}.\nAdditionally, I omit the type annotation of $\\kw{let}$-bound expressions\nwhen the type is evident or deducible from context.\n\n\\subsection{Concrete natural numbers}\n\nConcrete numbers can be constructed easily using the base size $\\circ$ as a starting point\nand its successors as strictly larger sizes.\nFor convenience, I use the notation \\new{$s+n$} for some fixed $n$ to mean the $n$th size successor of $s$.\nThe same number can be represented as terms of different types by changing the annotation since,\nfor instance, both $\\circ+2$ and $\\circ+3$ are strictly larger than $\\sss{\\circ}$.\nSimilarly, two different naturals can have the same size\nbecause the size of an inductive type represents \\emph{at most}\nhow many layers of constructors deep an element is.\n%\n\\begin{alignat*}{4}\n&\\Let{\\const{0}&&}{\\N{\\sss{\\circ}}&&}{\\zero{\\hat{\\circ}}{\\circ}} \\\\\n&\\Let{\\const{0'}&&}{\\N{\\circ+2}&&}{\\zero{\\circ+2}{\\circ}} \\\\\n&\\Let{\\const{1}&&}{\\N{\\circ+2}&&}{\\succ{\\circ+2}{\\hat{\\circ}}{\\const{0}}} \\\\\n&\\Let{\\const{1'}&&}{\\N{\\circ+3}&&}{\\succ{\\circ+3}{\\hat{\\circ}}{\\const{0}}} \\\\\n\\end{alignat*}\n\n\\clearpage % TODO: clearpage\nTwo terms representing the same number might not be definitionally equal,\nas shown by the terms $\\const{0}$ and $\\const{0'}$,\nor by $\\const{1}$ and $\\const{1'}$;\nthis requires \\emph{shape irrelevance}\\index{shape irrelevance}~\\citep{NbE},\nwhich is beyond the scope of this thesis.\nHowever, any natural can be ``lifted'' to a larger size\nsimply by recursively reconstructing the natural with different sizes.\n\n\\begin{align*}\n&\\Let{\\liftN}{\\Funtype{\\alpha}{\\Funtype<{\\beta}{\\alpha}{\\arr*{\\N{\\beta}}{\\N{\\alpha}}}}}{\\\\\n&\\fix{\\lift}{\\alpha}{\\Funtype<{\\beta}{\\alpha}{\\arr*{\\N{\\beta}}{\\N{\\alpha}}}}{\\\\\n&\\quad \\Fun<{\\beta}{\\alpha}{\\fun{n}{\\N{\\beta}}{\\\\\n&\\quad \\match{n}{\\fun*{\\any}{\\N{\\alpha}}}{\\\\\n&\\qquad \\App{\\zero*}{\\gamma} \\Rightarrow \\zero{\\alpha}{\\beta} \\\\\n&\\qquad \\app{\\App{\\succ*}{\\gamma}}{z} \\Rightarrow \\succ{\\alpha}{\\beta}{(\\app{\\App{\\lift}{\\beta}{\\gamma}}{z})}}}}}}\n\\end{align*}\n\nA lifting function can also be defined for well-founded trees\n(and for strictly-positive sized inductive types in general).\n%\n\\begin{align*}\n&\\Let{\\liftW}{\\funtype{A}{\\Type{i}}{\\funtype{B}{\\arr*{A}{\\Type{i}}}{\\Funtype{\\alpha}{\\Funtype<{\\beta}{\\alpha}{\\arr*{\\W{x}{A}{\\app{B}{x}}{\\beta}}{\\W{x}{A}{\\app{B}{x}}{\\alpha}}}}}}}{\\\\\n&\\fun{A}{\\Type{i}}{\\fun{B}{\\arr*{A}{\\Type{i}}}{\\\\\n&\\fix{\\lift}{\\alpha}{\\Funtype<{\\beta}{\\alpha}{\\arr*{\\W{x}{A}{\\app{B}{x}}{\\beta}}{\\W{x}{A}{\\app{B}{x}}{\\alpha}}}}{\\\\\n&\\quad \\Fun<{\\beta}{\\alpha}{\\fun{w}{\\W{x}{A}{\\app{B}{x}}{\\beta}}{\\\\\n&\\quad \\match{w}{\\fun*{\\any}{\\W{x}{A}{\\app{B}{x}}{\\alpha}}}{\\\\\n&\\qquad \\app{\\App{\\sup*}{\\gamma}}{a}{f} \\Rightarrow \\sup{x}{A}{\\app{B}{x}}{\\alpha}{\\beta}{a}{(\\fun{x}{A}{\\app{\\App{\\lift}{\\beta}{\\gamma}}{(\\app{f}{x})}})}}}}}}}}\n\\end{align*}\n\n\\iffalse\n\\begin{align*}\n\\Let{&\\liftW}{\\funtype{A}{\\Type{i}}{\\funtype{B}{\\arr*{A}{\\Type{i}}}{\\Funtype{\\alpha}{\\Funtype<{\\beta}{\\alpha}{\\arr*{\\W{x}{A}{\\app{B}{x}}{\\beta}}{\\W{x}{A}{\\app{B}{x}}{\\alpha}}}}}}}{\\\\\n&\\liftW \\: A \\: B \\: [\\alpha] \\: [\\beta] \\: (\\app{\\App{\\sup*}{\\gamma}}{a}{f}) = \\sup* \\: [\\beta] \\: a \\: (\\fun{x}{A}{\\liftW \\: A \\: B \\: [\\beta] \\: [\\gamma] \\: (\\app{f}{x})})}\n\\end{align*}\n\\fi\n\n\\subsection{Size-preserving functions}\n\nOne of the most important uses of sized types is the ability to define\n\\emph{size-preserving}\\index{size preservation} functions,\nwhere the sizes of the input and output are the same.\nThis guarantees that the output is never larger than the input,\nand size-preserving functions can be used in recursive calls of fixpoints.\nFor instance, the predecessor function $\\pred$ which computes\n$\\maximum{0, n - 1}$ for some number $n$ is size preserving.\n%\n\\begin{align*}\n&\\Let{\\pred}{\\Funtype{\\alpha}{\\arr*{\\N{\\alpha}}{\\N{\\alpha}}}}{ \\\\\n&\\Fun{\\alpha}{\\fun{n}{\\N{\\alpha}}{\\match*{n}{ \\\\\n&\\quad \\App{\\zero*}{\\beta} \\Rightarrow \\zero{\\alpha}{\\beta} \\\\\n&\\quad \\app{\\App{\\succ*}{\\beta}}{m} \\Rightarrow \\app{\\App{\\liftN}{\\alpha}{\\beta}}{m}}}}}\n\\end{align*}\n\nThe $\\monus$ function, which computes $\\maximum{0, n - m}$ given numbers $n, m$,\nis similarly size preserving in its first argument,\nsince $n - m$ is never greater than $n$.\n\n\\begin{align*}\n&\\Let{\\monus}{\\Funtype{\\alpha}{\\Funtype{\\beta}{\\arr*{\\N{\\beta}}{\\N{\\alpha}}{\\N{\\beta}}}}}{ \\\\\n&\\fix{\\monus*}{\\alpha}{\\Funtype{\\beta}{\\arr*{\\N{\\beta}}{\\N{\\alpha}}{\\N{\\beta}}}}{ \\\\\n&\\quad \\Fun{\\beta}{\\fun{n}{\\N{\\beta}}{\\fun{m}{\\N{\\alpha}}{\\match*{m}{ \\\\\n&\\qquad \\App{\\zero*}{\\gamma} \\Rightarrow n \\\\\n&\\qquad \\app{\\App{\\succ*}{\\gamma}}{k} \\Rightarrow \\app{\\App{\\monus*}{\\gamma}{\\beta}}{(\\app{\\App{\\pred}{\\beta}}{n})}{k}}}}}}}\n\\end{align*}\n\nWe see the benefit of size preservation with $\\divv$,\nwhich computes Euclidean division of $n$ by $m$, or $\\left\\lceil\\frac{n}{m+1}\\right\\rceil$.\nThis is computed recursively by subtracting $m$ from the numerator using $\\monus$\nuntil $\\zero*$ is reached, and counting the number of times the subtraction is performed.\nThe recursive call is done on the result of $\\monus$;\n$\\divv$ then only type checks because $\\monus$ is size preserving.\nBecause the first argument of the recursive call to $\\divv$ isn't \\emph{structurally}\na subterm with the call to $\\monus$ in the way,\na guardedness check wouldn't accept the corresponding unsized function,\nas is the case for CIC.\n%\n\\begin{align*}\n&\\Let{\\divv}{\\Funtype{\\alpha}{\\Funtype{\\beta}{\\arr*{\\N{\\alpha}}{\\N{\\beta}}{\\N{\\alpha}}}}}{ \\\\\n&\\fix{\\divv*}{\\alpha}{\\Funtype{\\beta}{\\arr*{\\N{\\alpha}}{\\N{\\beta}}{\\N{\\alpha}}}}{ \\\\\n&\\quad \\Fun{\\beta}{\\fun{n}{\\N{\\alpha}}{\\fun{m}{\\N{\\beta}}{\\match*{n}{ \\\\\n&\\qquad \\App{\\zero*}{\\gamma} \\Rightarrow \\zero{\\alpha}{\\gamma} \\\\\n&\\qquad \\app{\\App{\\succ*}{\\gamma}}{k} \\Rightarrow\n\\succ{\\alpha}{\\gamma}{\n  (\\underbrace{\\app{\\App{\\divv*}{\\gamma}{\\beta}}{\n    (\\underbrace{\\app{\\App{\\monus}{\\beta}{\\gamma}}{k}{\n      (\\underbrace{\\app{\\App{\\pred}{\\beta}}{m}}_{\\N{\\beta}})\n    }}_{\\N{\\gamma}})\n  }{m}}_{\\N{\\gamma}})\n}}}}}}}\n\\end{align*}\n\n\\subsection{Large sized functions}\n\nSo far, none of these examples have made use of dependent types:\ntheir unsized variants could have all been written in System F.\nWe therefore now turn to the $n$-ary size-preserving function type,\nwhich does \\emph{large elimination}\\index{large elimination}\non a natural $n$, \\ie returns a type.\nThis example is due to \\citet{MiniAgda}.\n\n\\begin{align*}\n&\\Let{\\Nary}{\\Funtype{\\alpha}{\\arr*{\\N{\\alpha}}{\\Funtype{\\beta}{\\Type{1}}}}}{\\\\\n&\\fix{\\nary}{\\alpha}{\\arr*{\\N{\\alpha}}{\\Funtype{\\beta}{\\Type{1}}}}{\\\\\n&\\quad \\fun{n}{\\N{\\alpha}}{\\Funtype{\\beta}{\\match{n}{\\fun*{\\any}{\\Type{1}}}{\\\\\n&\\qquad \\App{\\zero*}{\\beta} \\Rightarrow \\N{\\beta} \\\\\n&\\qquad \\app{\\App{\\succ*}{\\beta}}{m} \\Rightarrow \\arr*{\\N{\\beta}}{\\App{\\app{\\nary}{m}}{\\beta}}}}}}}\n\\end{align*}\n\nIntuitively, $\\Nary$ constructs the function type\n\n$$\\App{\\app{\\App{\\Nary}{\\alpha}}{n}}{\\beta} = \\arr*{\\underbrace{\\arr*{\\N{\\beta}}{\\seq}{\\N{\\beta}}}_{\\text{$n$ arguments}}}{\\N{\\beta}}.$$\n\n$n$-ary size-preserving functions can then be typed using $\\Nary$,\nsuch as a $\\MaX$ function that takes the maximum of $n+1$ numbers\nall of the same size.\nFor concision, I define $\\maX$ in a pattern-matching style of syntax,\nbut it can easily be translated to proper \\lang as a fixpoint and two $\\kw{case}$ expressions.\n%\n\\begin{align*}\n\\Let{&\\maX}{\\Funtype{\\alpha}{\\arr*{\\N{\\alpha}}{\\N{\\alpha}}{\\N{\\alpha}}}}{ \\\\\n&\\maX \\: \\sqbr{\\alpha} \\: n \\: (\\App{\\zero*}{\\beta}) = n \\\\\n&\\maX \\: \\sqbr{\\alpha} \\: (\\App{\\zero*}{\\beta}) \\: m = m \\\\\n&\\maX \\: \\sqbr{\\alpha} \\: (\\app{\\App{\\succ*}{\\beta}}{n'}) \\: (\\app{\\App{\\succ*}{\\beta}}{m'}) = \\succ{\\alpha}{\\beta}{(\\app{\\App{\\max}{\\beta}}{n'}{m'})}}\n\\end{align*}\n\\iffalse\n\\begin{align*}\n&\\Let{\\maX}{\\Funtype{\\alpha}{\\arr*{\\N{\\alpha}}{\\N{\\alpha}}{\\N{\\alpha}}}}{ \\\\\n&\\fix{\\mathit{max}}{\\alpha}{\\arr*{\\N{\\alpha}}{\\N{\\alpha}}{\\N{\\alpha}}}{ \\\\\n&\\quad \\fun{n}{\\N{\\alpha}}{\\fun{m}{\\N{\\alpha}}{ \\\\\n&\\quad \\match*{n}{ \\\\\n&\\qquad \\App{\\zero*}{\\beta} \\Rightarrow m \\\\\n&\\qquad \\app{\\App{\\succ*}{\\beta}}{n'} \\Rightarrow \\\\\n&\\qquad \\quad \\match*{m}{ \\\\\n&\\qquad \\qquad \\App{\\zero*}{\\beta} \\Rightarrow n \\\\\n&\\qquad \\qquad \\app{\\App{\\succ*}{\\beta}}{m'} \\Rightarrow \\succ{\\alpha}{\\beta}{(\\app{\\App{\\mathit{max}}{\\beta}}{n'}{m'})}}}}}}}\n\\end{align*}\n\\fi\n%\n\\begin{align*}\n&\\Let{\\MaX}{\\Funtype{\\alpha}{\\funtype{k}{\\N{\\alpha}}{\\Funtype{\\beta}{\\arr*{\\N{\\beta}}{\\App{\\app{\\App{\\Nary}{\\alpha}}{k}}{\\beta}}}}}}{\\\\\n&\\fix{\\MaX*}{\\alpha}{\\funtype{k}{\\N{\\alpha}}{\\Funtype{\\beta}{\\arr*{\\N{\\beta}}{\\App{\\app{\\App{\\Nary}{\\alpha}}{k}}{\\beta}}}}}{\\\\\n&\\quad \\fun{k}{\\N{\\alpha}}{\\Fun{\\beta}{\\fun{n}{\\N{\\beta}}{\\match{k}{\\fun*{x}{\\App{\\app{\\App{\\Nary}{\\alpha}}{x}}{\\beta}}}{\\\\\n&\\qquad \\App{\\zero*}{\\gamma} \\Rightarrow n \\\\\n&\\qquad \\app{\\App{\\succ*}{\\gamma}}{k'} \\Rightarrow \\fun{m}{\\N{\\beta}}{\\app{\\App{\\app{\\App{\\MaX*}{\\gamma}}{k'}}{\\beta}}{(\\app{\\App{\\max}{\\beta}}{n}{m})}}}}}}}}\n\\end{align*}\n\n\\subsection{Sized lists}\n\nImplementing sized quicksort~\\citep{term-check} and mergesort~\\citep{Abel-diss} are perhaps the most classic examples,\ndemonstrating their ease of programming compared to na\\\"ive unsized implementations that otherwise\nimpose a significant termination proof burden to the programmer.\nAlthough \\lang has no lists for simplicity's sake,\nthey are no more complicated than naturals.\nUsing the same informal syntax from \\cref{sec:ind-types},\nthey can be defined by the following:\n\n\\begin{align*}\n&\\data{\\List{(\\annot{A}{\\Type{i}})}{\\alpha}}{\\Type{i+1}} \\\\\n&\\quad \\annot{\\nil*}{\\Funtype<{\\beta}{\\alpha}{\\List{A}{\\alpha}}} \\\\\n&\\quad \\annot{\\cons*}{\\Funtype<{\\beta}{\\alpha}{\\arr*{A}{\\List{A}{\\beta}}{\\List{A}{\\alpha}}}}\n\\end{align*}\n\nA similar lifting function for lists can be defined, whose type is\n\n$$\\annot{\\liftL}{\\funtype{A}{\\Type{i}}{\\Funtype{\\alpha}{\\Funtype<{\\beta}{\\alpha}{\\arr*{\\List{A}{\\beta}}{\\List{A}{\\alpha}}}}}}.$$\n\nI also use an encoding for \\emph{weak dependent pairs}\\index{weak dependent pair}\nto express pairing a sized type with some particular size\nin situations where the size expressions of \\lang aren't expressive enough\nto specify the exact size.\n%\n\\begin{align*}\n\\Pairtype{\\alpha}{\\tau} &= \\funtype{\\sigma}{\\Type{i}}{\\arr*{(\\Funtype{\\alpha}{(\\arr*{\\tau}{\\sigma})})}{\\sigma}} \\\\\n\\Pair{s}{e}_{\\Pairtype{\\alpha}{\\tau}} &= \\fun{\\sigma}{\\Type{i}}{\\fun{f}{\\Funtype{\\alpha}{(\\arr*{\\tau}{\\sigma})}}{\\app{\\App{f}{s}}{e}}} \\\\\n\\unpair{\\alpha}{x}{\\alpha}{\\tau}{e_1}{\\annot{e_2}{\\sigma}} &= \\app{e_1}{\\sigma}{(\\Fun{\\alpha}{\\fun{x}{\\tau}{e_2}})}\n\\end{align*}\n\nThis encoding is used in the $\\append$ function, written in pattern-matching style,\nwhere the precise size of the resulting list should be the sum of the sizes of the input lists,\nbut \\lang has no addition operator for sizes.\nSuppose that $A$ is some type.\n%\n\\begin{align*}\n\\Let{&\\append}{\\Funtype{\\alpha}{\\Funtype{\\beta}{\\arr*{\\List{A}{\\alpha}}{\\List{A}{\\beta}}{\\Pairtype{\\gamma}{\\List{A}{\\gamma}}}}}}{ \\\\\n&\\append \\: \\sqbr{\\alpha} \\: \\sqbr{\\beta} \\: (\\nil* \\: \\sqbr{\\alpha'}) \\: r = \\Pair{\\beta}{r} \\\\\n&\\append \\: \\sqbr{\\alpha} \\: \\sqbr{\\beta} \\: (\\cons* \\: \\sqbr{\\alpha'} \\: \\hd \\: \\tl) \\: r =\n  \\unpair*{\\gamma}{x}{\\append \\: \\sqbr{\\alpha'} \\: \\sqbr{\\beta} \\: \\tl \\: r}{\n    \\cons* \\: \\sqbr{\\gamma} \\: hd \\: x\n  }}\n\\end{align*}\n\n$\\append$ retains the order of the elements of the lists.\nOn the other hand, if given some ordering function on $A$\n$$\\annot{\\ifleq}{\\funtype{C}{\\Type{i}}{\\arr*{A}{A}{C}{C}{C}}}$$\nwhich selects one of two branches $C$ based on the order of the elements of $A$,\nwe can define a similar $\\mrg$ function that merges two lists such that\nthe resulting list is sorted with respect to $\\ifleq$ if the input lists were.\nIn pattern-matching style, the recursion appears lexicographical,\nbut it can be translated to nested fixpoints~\\citep{Abel-diss}.\n\n\\begin{align*}\n\\Let{&\\mrg}{\\Funtype{\\alpha}{\\Funtype{\\beta}{\\arr*{\\List{A}{\\alpha}}{\\List{A}{\\beta}}{\\Pairtype{\\gamma}{\\List{A}{\\gamma}}}}}}{ \\\\\n&\\mrg \\: \\sqbr{\\alpha} \\: \\sqbr{\\beta} \\: (\\nil* \\: \\sqbr{\\alpha'}) \\: r = \\Pair{\\beta}{r} \\\\\n&\\mrg \\: \\sqbr{\\alpha} \\: \\sqbr{\\beta} \\: l \\: (\\nil* \\: \\sqbr{\\beta'}) = \\Pair{\\alpha}{l} \\\\\n&\\mrg \\: \\sqbr{\\alpha} \\: \\sqbr{\\beta} \\: (\\cons* \\: \\sqbr{\\alpha'} \\: a \\: l) \\: (\\cons* \\: \\sqbr{\\beta'} \\: b \\: r) = \\\\\n&\\quad \\ifleq \\: (\\List{A}{\\gamma}) \\: a \\: b \\\\\n&\\qquad (\\unpair*{\\gamma}{x}{\\mrg \\: \\sqbr{\\alpha'} \\: \\sqbr{\\beta} \\: l \\: (\\cons* \\: \\sqbr{\\beta'} \\: b \\: r)}{\\Pair{\\sss{\\gamma}}{\\cons* \\: \\sqbr{\\gamma} \\: a \\: x}}) \\\\\n&\\qquad (\\unpair*{\\gamma}{x}{\\mrg \\: \\sqbr{\\alpha} \\: \\sqbr{\\beta'} \\: (\\cons* \\: \\sqbr{\\alpha'} \\: a \\: l) \\: r}{\\Pair{\\sss{\\gamma}}{\\cons* \\: \\sqbr{\\gamma} \\: b \\: x}})}\n\\end{align*}\n\nQuicksort and mergesort are both divide-and-conquer algorithms,\nso we need some way of dividing up a list.\nThe simplest to implement recursively is to simply $\\spt$ it into two lists of alternating elements,\nwritten in continuation-passing style since \\lang has no pairs.\n%\n\\begin{align*}\n\\Let{&\\spt}{\\Funtype{\\alpha}{\\funtype{C}{\\Type{i}}{\\arr*{\\List{A}{\\alpha}}{(\\arr*{\\List{A}{\\alpha}}{\\List{A}{\\alpha}}{C})}{C}}}}{ \\\\\n&\\spt \\: \\sqbr{\\alpha} \\: C \\: (\\nil* \\: \\sqbr{\\beta}) \\: k = \\app{k}{(\\nil* \\: \\sqbr{\\beta})}{(\\nil* \\: \\sqbr{\\beta})} \\\\\n&\\spt \\: \\sqbr{\\alpha} \\: C \\: (\\cons* \\: \\sqbr{\\beta} \\: \\hd \\: \\tl) \\: k = \\\\\n&\\quad \\spt \\: \\sqbr{\\beta} \\: C \\: \\tl \\:\n  (\\fun{l}{\\List{A}{\\beta}}{\\fun{r}{\\List{A}{\\beta}}{\n    \\app{k}{(\\cons* \\: \\sqbr{\\beta} \\: \\hd \\: r)}{(\\liftL \\: A \\: \\sqbr{\\alpha} \\: \\sqbr{\\beta} \\: l)}\n  }})}\n\\end{align*}\n\nAlternatively, the list can be $\\partition$ed relative to some pivot element\ninto two according to $\\ifleq$,\nsuch that one list contains only elements that are smaller or equal to the pivot\nand the other contains elements larger than it.\n%\n\\begin{align*}\n\\Let{&\\partition}{\\Funtype{\\alpha}{\\funtype{C}{\\Type{i}}{\\arr*{A}{\\List{A}{\\alpha}}{(\\arr*{\\List{A}{\\alpha}}{\\List{A}{\\alpha}}{C})}{C}}}}{ \\\\\n&\\partition \\: \\sqbr{\\alpha} \\: C \\: a \\: (\\nil* \\: \\sqbr{\\beta}) \\: k = \\app{k}{(\\nil* \\: \\sqbr{\\beta})}{(\\nil* \\: \\sqbr{\\beta})} \\\\\n&\\partition \\: \\sqbr{\\alpha} \\: C \\: a \\: (\\cons* \\: \\sqbr{\\beta} \\: \\hd \\: \\tl) \\: k = \\\\\n&\\quad \\partition \\: \\sqbr{\\beta} \\: C \\: a \\: \\tl \\:\n  (\\fun{l}{\\List{A}{\\beta}}{\\fun{r}{\\List{A}{\\beta}}{ \\\\\n    &\\qquad \\ifleq \\: C \\: \\hd \\: a \\\\\n    &\\qquad \\quad (\\app{k}{(\\cons* \\: \\sqbr{\\beta} \\: \\hd \\: l)}{(\\liftL \\: A \\: \\sqbr{\\alpha} \\: \\sqbr{\\beta} \\: r)}) \\\\\n    &\\qquad \\quad (\\app{k}{(\\liftL \\: A \\: \\sqbr{\\alpha} \\: \\sqbr{\\beta} \\: l)}{(\\cons* \\: \\sqbr{\\beta} \\: \\hd \\: r)})\n  }})}\n\\end{align*}\n\nQuicksort sorts a list by picking a pivot element,\n$\\partition$ing the rest of the list into sublists of elements smaller and greater than the pivot,\nrecursively sorting them,\nthen $\\append$ing the sorted lists with the pivot in the middle.\nMeanwhile, mergesort sorts a list by $\\spt$ing the list into sublists,\nrecursively sorting them,\nthen $\\mrg$ing the sorted lists while maintaining ordering.\nBoth involve recursive calls on lists that are not structurally smaller,\nbut do have smaller sizes,\nand differ in where $\\ifleq$ is applied ($\\partition$ or $\\mrg$).\n\n\\vspace{-\\baselineskip}\n\\begin{multicols}{2}\n\\begin{align*}\n&\\Let{\\qsort}{\\Funtype{\\alpha}{\\arr*{\\List{A}{\\alpha}}{\\Pairtype{\\gamma}{\\List{A}{\\gamma}}}}}{ \\\\\n&\\fix{\\qsort*}{\\alpha}{\\arr*{\\List{A}{\\alpha}}{\\Pairtype{\\gamma}{\\List{A}{\\gamma}}}}{ \\\\\n&\\quad \\fun{l}{\\List{A}{\\alpha}}{\\match*{l}{ \\\\\n&\\qquad \\App{\\nil*}{\\beta} \\Rightarrow \\Pair{\\alpha}{l} \\\\\n&\\qquad \\app{\\App{\\cons*}{\\beta}}{\\hd}{\\tl \\Rightarrow \\\\\n  &\\qquad \\quad \\app{\\App{\\partition}{\\beta}}{(\\Pairtype{\\gamma}{\\List{A}{\\gamma}})}{\\hd}{\\tl}{ \\\\\n    &\\qquad \\quad (\\fun{l}{\\List{A}{\\beta}}{\\fun{r}{\\List{A}{\\beta}}{ \\\\\n      &\\qquad \\qquad \\unpair{\\delta}{x}{\\gamma}{\\List{A}{\\gamma}}{\\app{\\App{\\qsort*}{\\beta}}{l}}{ \\\\\n      &\\qquad \\qquad \\unpair{\\varepsilon}{y}{\\gamma}{\\List{A}{\\gamma}}{\\app{\\App{\\qsort*}{\\beta}}{r}}{ \\\\\n      &\\qquad \\qquad \\app{\\App{\\append}{\\delta}{\\sss{\\varepsilon}}}{x}{(\\cons{A}{\\sss{\\varepsilon}}{\\varepsilon}{\\hd}{y})}}}\n    }})}}}}}}\n\\end{align*}\n\n\\begin{align*}\n&\\Let{\\msorted}{\\Funtype{\\alpha}{\\arr*{A}{\\List{A}{\\alpha}}{\\Pairtype{\\gamma}{\\List{A}{\\gamma}}}}}{ \\\\\n&\\fix{\\msort*}{\\alpha}{\\arr*{A}{\\List{A}{\\alpha}}{\\Pairtype{\\gamma}{\\List{A}{\\gamma}}}}{ \\\\\n&\\quad \\fun{a}{A}{\\fun{l}{\\List{A}{\\alpha}}{\\match*{l}{ \\\\\n&\\qquad \\App{\\nil*}{\\beta} \\Rightarrow \\Pair{\\sss{\\alpha}}{\\cons{A}{\\sss{\\alpha}}{\\alpha}{a}{l}} \\\\\n&\\qquad \\app{\\App{\\cons*}{\\beta}}{b}{\\tl} \\Rightarrow \\\\\n&\\qquad \\quad \\app{\\App{\\spt}{\\beta}}{(\\Pairtype{\\gamma}{\\List{A}{\\gamma}})}{\\tl}{ \\\\\n&\\qquad \\quad (\\fun{l}{\\List{A}{\\beta}}{\\fun{r}{\\List{A}{\\beta}}{ \\\\\n&\\qquad \\qquad \\unpair{\\delta}{x}{\\gamma}{\\List{A}{\\gamma}}{\\app{\\App{\\msort*}{\\beta}}{a}{l}}{ \\\\\n&\\qquad \\qquad \\unpair{\\varepsilon}{y}{\\gamma}{\\List{A}{\\gamma}}{\\app{\\App{\\msort*}{\\beta}}{b}{r}}{ \\\\\n&\\qquad \\qquad \\app{\\App{\\mrg}{\\delta}{\\varepsilon}}{x}{y}}}}})}}}}}} \\\\\\\\\n&\\Let{\\msort}{\\Funtype{\\alpha}{\\arr*{\\List{A}{\\alpha}}{\\Pairtype{\\gamma}{\\List{A}{\\gamma}}}}}{ \\\\\n&\\Fun{\\alpha}{\\fun{l}{\\List{A}{\\alpha}}{\\match*{l}{ \\\\\n&\\quad \\App{\\nil*}{\\beta} \\Rightarrow \\Pair{\\alpha}{l} \\\\\n&\\quad \\app{\\App{\\cons*}{\\beta}}{\\hd}{\\tl \\Rightarrow \\app{\\App{\\msorted}{\\beta}}{\\hd}{\\tl}}}}}}\n\\end{align*}\n\\end{multicols}\n\n\\subsection{Higher-rank sizes}\n\nThe final example, demonstrating higher-rank size quantification,\nis a traversal of a well-founded tree with a size-preserving function,\nadapted from the rose tree traversal example by \\citet{NbE}.\nGiven some size-preserving function on a well-founded tree,\nthe function is applied to subtrees prior to traversal.\nSuppose that $B$ here is some type operator on $A$.\n%\n\\begin{align*}\n&\\Let{\\traverseW}{\\arr*{(\\Funtype{\\gamma}{\\arr*{\\W{x}{A}{\\app{B}{x}}{\\gamma}}{\\W{x}{A}{\\app{B}{x}}{\\gamma}}})}{ \\\\\n&\\phantom{\\kw{let} \\: \\traverseW \\mathrel{:} \\phantom{}} \\Funtype{\\alpha}{\\arr*{\\W{x}{A}{\\app{B}{x}}{\\alpha}}{\\W{x}{A}{\\app{B}{x}}{\\alpha}}}}}{ \\\\\n&\\quad \\fun{f}{\\Funtype{\\gamma}{\\arr*{\\W{x}{A}{\\app{B}{x}}{\\gamma}}{\\W{x}{A}{\\app{B}{x}}{\\gamma}}}}{ \\\\\n&\\quad \\fix{\\traverse}{\\alpha}{\\arr*{\\W{x}{A}{\\app{B}{x}}{\\alpha}}{\\W{x}{A}{\\app{B}{x}}{\\alpha}}}{ \\\\\n&\\qquad \\fun{w}{\\W{x}{A}{\\app{B}{x}}{\\alpha}}{\\match*{w}{ \\\\\n&\\qquad \\quad \\app{\\App{\\sup*}{\\beta}}{a}{g} \\Rightarrow \\sup{x}{A}{\\app{B}{x}}{\\alpha}{\\beta}{a}{(\\fun{b}{\\app{B}{a}}{\\app{\\App{\\traverse}{\\beta}}{(\\app{\\App{f}{\\beta}}{(\\app{g}{b})})}})}}}}}}\n\\end{align*}\n\n\\subsection{Limitations} \\label{sec:examples:limitations}\n\nAs expressive as bounded, higher-rank sized types are,\nthere still exist limitations to what can be expressed in comparison to ordinary inductive types\nor to sized type theories which have an infinite size\\index{infinite size},\nsuch as the ones listed in \\cref{sec:sized-types}.\nLimitations typically arise when dealing with inductive definitions where\nrecursive arguments appear as the return type of a function.\nConsider the following inductive definition\nrepresenting the Brouwer notation for ordinals (see \\eg \\citet{ordinals})\nwith zero, successor, and limit ordinals:\n%\n\\begin{align*}\n&\\data{\\Ord{\\alpha}}{\\Type{1}} \\\\\n&\\quad \\annot{\\zord*}{\\Funtype<{\\beta}{\\alpha}{\\Ord{\\alpha}}} \\\\\n&\\quad \\annot{\\sord*}{\\Funtype<{\\beta}{\\alpha}{\\arr*{\\Ord{\\beta}}{\\Ord{\\alpha}}}} \\\\\n&\\quad \\annot{\\lord*}{\\Funtype<{\\beta}{\\alpha}{\\arr*{(\\Funtype<{\\gamma}{\\beta}{\\arr*{\\N{\\gamma}}{\\Ord{\\beta}}})}{\\Ord{\\alpha}}}}\n\\end{align*}\n\nThe limit ordinal, taking some function on naturals returning an ordinal,\nconstructs an ordinal meant to be ``larger'' than any of the returned ordinals.\nSuch a function should be able to return an ordinal far larger than any natural,\nhence the bounded size quantification in its domain.\nConversely, the naturals embed quite naturally within the ordinals.\n%\n\\begin{align*}\n&\\Let{\\natOrd}{\\Funtype{\\alpha}{\\arr*{\\N{\\alpha}}{\\Ord{\\alpha}}}}{ \\\\\n&\\fix{\\natOrd*}{\\alpha}{\\arr*{\\N{\\alpha}}{\\Ord{\\alpha}}}{ \\\\\n&\\quad \\fun{n}{\\N{\\alpha}}{\\match*{n}{ \\\\\n&\\qquad \\App{\\zero*}{\\beta} \\Rightarrow \\zord{\\alpha}{\\beta} \\\\\n&\\qquad \\app{\\App{\\succ*}{\\beta}}{m} \\Rightarrow \\sord{\\alpha}{\\beta}{(\\app{\\App{\\natOrd*}{\\beta}}{m})}}}}}\n\\end{align*}\n\nIn an unsized type theory, supposing that $\\const{natOrd'}$ is an unsized version of $\\natOrd$,\nthe first limit ordinal $\\const{\\omega'}$ is easily defined as\n$\\Let{\\const{\\omega'}}{\\const{Ord}}{\\app{\\lord*}{\\const{natOrd'}}}$.\nHowever, in \\lang, things are not so easy; the na\\\"ive attempt yields the following:\n%\n\\begin{align*}\n&\\Let{\\liftO}{\\Funtype{\\alpha}{\\Funtype<{\\beta}{\\alpha}{\\arr*{\\Ord{\\beta}}{\\Ord{\\alpha}}}}}{\\seq} \\\\\n&\\Let{\\omegaOrd}{\\Ord{\\sss{\\hole}}}{\\lord{\\sss{\\hole}}{\\hole}{(\\Fun<{\\gamma}{\\hole}{\\fun{n}{\\N{\\gamma}}{\\app{\\App{\\liftO}{\\hole}{\\gamma}}{(\\app{\\App{\\natOrd}{\\gamma}}{n})}}})}}\n\\end{align*}\n\nAside from the additional bounds and size lifting, there is one crucial problem: what size fills in the hole \\new{$\\hole$}?\nIntuitively, this size must be larger than the size of \\emph{any} natural.\nTherefore, a corresponding ``limit size'' is needed;\nthe infinite size in other sized type theories can fill this r\\^ole since it's larger than all sizes\nand therefore the limit of \\emph{all} sizes.\nI further discuss the infinite size and its absence from \\lang in \\cref{sec:infinity}.", "meta": {"hexsha": "ff2b3c67ed870d8d91f2fbd1b230eff3d9feac7e", "size": 36419, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/sized.tex", "max_stars_repo_name": "ionathanch/msc-thesis", "max_stars_repo_head_hexsha": "8fe15af8f9b5021dc50bcf96665e0988abf28f3c", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/sized.tex", "max_issues_repo_name": "ionathanch/msc-thesis", "max_issues_repo_head_hexsha": "8fe15af8f9b5021dc50bcf96665e0988abf28f3c", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/sized.tex", "max_forks_repo_name": "ionathanch/msc-thesis", "max_forks_repo_head_hexsha": "8fe15af8f9b5021dc50bcf96665e0988abf28f3c", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.9046875, "max_line_length": 212, "alphanum_fraction": 0.6783821632, "num_tokens": 11745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5888891307678319, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3265216301469816}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                                                                 %\n%   HBOOK User Guide -- LaTeX Source                              %\n%                                                                 %\n%   Chapter 6                                                     %\n%                                                                 %\n%   The following external EPS files are referenced:              %\n%                                                                 %\n%   Editor: Michel Goossens / CN-AS                               %\n%   Last Mod.: 20 Oct 1993  9:20 mg                               %\n%                                                                 %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n\\Filename{H1Operations-on-Histograms}\n\\chapter{Operations on Histograms}\n\\label{HOPERFIT}\n\n\\Filename{H2Arithmetic-Operations}\n\\section{Arithmetic Operations}\n\\label{HARITHME}\n\n\\index{histogram!operations}\n\\index{histogram!addition}\n\\index{add histograms}\n\\index{histogram!substraction}\n\\index{subscract histograms}\n\\index{histogram!multiplication}\n\\index{multiply histograms}\n\\index{histogram!division}\n\\index{divide histograms}\nHistograms can be added, subtracted, divided or multiplied, provided\ntheir number of channels are the same.\n \n\\Shubr{HOPERA}{(ID1,CHOPER,ID2,ID3,C1,C2)}\n \n\\Action\nFills an histogram \\Lit{I3} with values such that,\nlogically (operands are the bin contents)\n \n\\begin{verbatim}\nID3 = C1 * ID1 (OPERATION) C2 * ID2\n\\end{verbatim}\n \n\\begin{DLtt}{123456}\n\\item[{\\rm\\bf Input parameters:}]\n\\item[ID1,ID2] Operand histogram identifiers.\n\\item[CHOPER] Character variable specifying the\n     kind of operation to be performed\n     (\\Lit{+,-,*,/});\\\\\n     \\Lit{'B'} compute binomial errors;\\\\\n     \\Lit{'E'} compute error bars on the resulting\n      histograms correctly, assuming that the\n      input histograms \\Lit{ID1} and \\Lit{ID2} are independent.\\\\\n     For instance \\Lit{/BE} will generate binomial errors for the\n     division of \\Lit{ID1} by \\Lit{ID2}.\n\\item[ID3] Identifier of the histogram containing\nthe result after the operation.\n\\item[C1,C2] Multiplicative constants.\n\\end{DLtt}\n\n\\Remark\n\\begin{UL}\n\\item \\Lit{ID1}, \\Lit{ID2} and \\Lit{ID3}\n      must have the same number of channels.\n\\item If histogram \\Lit{ID3} is not empty, its contents are overwritten\n\\item The output histogram \\Lit{ID3} can be either one of the input \n      histograms \\Lit{ID1} or \\Lit{ID2}.\n\\item If histogram \\Lit{ID3} does not exist, it is created\n      by \\Rind{HOPERA} with the same specification as for histogram \\Lit{ID1}.\n\\item The mean value, standard deviation, etc. are calculated from the\n      contents of the resulting histogram \\Lit{ID3},\n      unless the \\Lit{'STAT'} option\\Iind{STAT} is active and the\n      operation is an addition or subtraction, in which case\n      they are computed exactly.\n\\item A division by zero gives zero.\n\\item Negative results for bin contents in a packed histogram are\n      meaningless\n\\item The number of entries in the resulting histogram \\Lit{ID3} is set\n      to the sum of the entries in histograms \\Lit{ID1} and \\Lit{ID2}.\n\\item When an operation is performed on two 1-dimensional histograms with\n      the sum of the squares of the weights stored (option \\Rind{HBARX}), the\n      error on the resulting histogram is calculated\n      supposing that the contents of the two input histograms \\Lit{ID1} and\n      \\Lit{ID2} are uncorrelated.\n      This is valid also for projections, slices and\n      bands of 2-dimensional histograms.\n\\item If histogram \\Lit{ID3} is packed the\n      number of bits allocated per channel (cell) has to be sufficient\n      to store the results.\n\\end{UL}\n \n\\newpage\n\\section{Statistical differences between histograms}\n\\label{HSTATDIF}\n\\index{difference! between histograms}\n\\index{test!Kolmogorov}\n\n\\Shubr{HDIFF}{(ID1,ID2,PROB*,CHOPT)}\n \n\\Action\nStatistical test of compatibility in shape between\ntwo histograms using the Kolmogorov test.\nThe histograms are compared and the probability that they\ncould come from the same parent distribution is calculated.\n \nThe comparison may be done between two 1-dimensional\nhistograms or between two 2-dimensional histograms.\n\\index{Kolmogorov test}\nFor further details on the method, see \\ref{HSTATCON}\nbelow.\n \n\\begin{DLtt}{123456}\n\\item[{\\rm\\bf Input parameters:}]\n\\item[ID1] Identifier of first histogram to be compared.\n\\item[ID2] Identifier of second histogram to be compared.\n\\item[CHOPT] A character string specifying the options desired.\n\\begin{DLtt}{1234}\n\\item['D'] Debug printout, produces a blank line and two lines of\ninformation at each call, including the identifier numbers \\Lit{ID},\nthe number\nof events in each histogram, the value of \\Lit{PROB}, and the maximum\nKolmogorov distance between the two histograms.\nFor 2-dimensional histograms,\nthere are two Kolmogorov distances (see below). If option \\Lit{'N'} is\nspecified, there is a third line of output giving the probalility\n\\Lit{PROB}\nfor shape and normalization alone separately.\n\\item['F1'] Histogram \\Lit{ID1} has no errors (it is a function).\n\\item['F2'] Histogram \\Lit{ID2} has no errors (it is a function).\n\\item['N'] Include a comparison of the relative normalization\nof the\ntwo histograms, in addition to comparing the shapes.\nThe output parameter \\Lit{PROB} is then\na combined confidence level taking into account absolute contents.\n\\item['O'] Overflow, requests that overflow bins be taken\ninto account (also valid for 2-dim).\n\\item['U'] Underflow, requests that underflow bins be taken\ninto account (also valid for 2-dim).\n\\item[{\\rm\\bf For 2-dimensional histograms only}]\n\\item['L'] Left, include X-underflows in the calculation.\n\\item['R'] Right, include X-overflows in the calculation.\n\\item['B'] Bottom, include Y-underflows in the calculation.\n\\item['T'] Top, include Y-overflows in the calculation.\n\\end{DLtt}\n\\item[{\\rm\\bf Output Parameter:}]\n\\item[PROB] The probability of compatibility between the two histograms.\n\\end{DLtt}\n\\Remark\n\\begin{UL}\n\\item\nOptions \\Lit{'O'} and \\Lit{'U'} can also refer to 2-dimensional\nhistograms, so that, for example the string \\Lit{'UT'} means that\nunderflows in  X and Y and overflows in Y should be\nincluded in the calculation.\n\\item The histograms \\Lit{ID1} and \\Lit{ID2} must exist and already\nhave been filled before the call to \\Rind{HDIFF}. They must also have\nidentical binning (lower and upper limits as well as number of bins).\n\\item The probability \\Lit{PROB} is returned as a number\nbetween zero and one.\nA values close to one\nindicates very similar histograms, and a value near zero\nmeans that it is very unlikely that the two arose from the same\nparent distribution.\n\\item By default (no options selected with \\Lit{CHOPT})\nthe comparison is done only\non the shape of the two histograms, without consideration of\nthe difference in number of events, and ignoring all\nunderflow and overflow bins.\n\\end{UL}\n \n\\subsection{Weights and Saturation}\n\\label{HWEIGSAT}\n \n\\subsubsection*{Weighted 1-dimensional histograms}\n \nIt is possible to compare weighted with weighted histograms,\nand weighted with unweighted histograms, but only\nif \\Lit{HBOOK} has been instructed to maintain the necessary\ninformation by appropriate calls (before filling) to\n\\Rind{HBARX}.\nHowever it is not possible to take into account underflow\nor overflow bins if the events are weighted.\n \n\\subsubsection*{Saturated 1-dimensional histograms}\n \nIf there is saturation\n(more than the maximum allowed contents in one or more bins),\nthe probability \\Lit{PROB} is calculated as if the bin contents\nwere exactly\nat their maximum value, ignoring the saturation.\nThis usually will result in a higher value of \\Lit{PROB} than would\nbe the case if the memory allowed the full contents to be stored,\nbut not always.\n\\index{saturation}\nIt should therefore be realized that the results of \\Rind{HDIFF} are\nnot accurate when there is saturation, and it is the user's\nresponsability to avoid this condition.\n \n\\subsubsection*{2-dimensional histograms}\n \nRoutine \\Rind{HDIFF} cannot work if the events are weighted,\nsince, in the current version of \\Lit{HBOOK}, the necessary information\nis not maintained.\n\\Rind{HDIFF} will also refuse to compare 2-dimensional histograms if\nthere is saturation, since it does not have enough information\nin this case.\n \n\\subsection{Statistical Considerations}\n\\label{HSTATCON}\n \n\\subsubsection*{The Kolmogorov Test}\n \nThe calculations in routine \\Rind{HDIFF} are based on the Kolmogorov Test\n\\index{Kolmogorov test}\n\\index{Chisquare test}\n(See, e.g. \\cite{bib-EADIE}, pages 269-270).\nIt is usually superior to the better-known Chisquare Test\nfor the following reasons:\n\\begin{UL}\n\\item\nIt does not require a minimum number of events per bin,\nand in fact it is intended for unbinned data (this is discussed\nbelow).\n\\item\nIt takes account not only of the differences between corresponding\nbins, but also the sign of the difference, and in particular it is\nsensitive to a sequence of consecutive deviations of the same sign.\n\\end{UL}\n\\par In discussing the Kolmogorov test, we must distinguish\nbetween the two most important properties of any test: its\n{\\bf power} and the calculation of its {\\bf confidence level.}\n \n\\subsubsection*{The Power}\n \n\\index{null hypothesis}\nThe job of a statistical test is to distinguish between a\nnull hypothesis (in this case: that the two histograms are\ncompatible) and the alternative hypothesis (in this case:\nthat the two are not compatible). The power of a test is defined\nas the probability of rejecting the null hypothesis when the\nalternative is true. In our case, the alternative is not\nwell-defined (it is simply the ensemble of all hypotheses\nexcept the null) so it is not possible to tell whether one test\nis more powerful than another\nin general, but only with respect to certain particular\ndeviations from the null hypothesis.\nBased on considerations such as those given above, as well as\nconsiderable computational experience, it is generally believed\nthat tests like the Kolmogorov or\nSmirnov-Cramer-Von-Mises\n\\index{Smirnov-Cramer-Von-Mises test}\n(which is similar but more complicated to calculate)\nare probably the most powerful for the kinds of phenomena\ngenerally of interest to high-energy physicists.\nThis is especially true for two-dimensional data where\nthe Chisquare Test is of little practical use since it requires\neither enormous amounts of data or very big bins.\n \n\\subsubsection*{The Confidence Level for 1-dimensional data}\n \n\\index{confidence level}\nUsing the terms introduced above, the confidence level is just\nthe probability of rejecting the null hypothesis when it\nis in fact true. That is, if you accept the two histograms\nas compatible whenever the value of \\Lit{PROB} is greater than 0.05,\nthen truly compatible histograms should fail the test\nexactly 5\\% of the time.\nThe value of \\Lit{PROB} returned by \\Rind{HDIFF} is calculated such that\nit will be uniformly distributed between {\\it zero} and {\\it one}\nfor compatible histograms, provided the\ndata are not binned (or the number of bins is very large compared\nwith the number of events).\nUsers who have access to unbinned data and wish exact confidence\nlevels should therefore not put their data into histograms,\nbut should save them in ordinary Fortran arrays and call the\nroutine \\Rind{TKOLMO} which is being introduced into the Program Library.\nOn the other hand, since \\Lit{HBOOK} is a convenient way of collecting\ndata and saving space, the routine \\Rind{HDIFF} has been provided,\nand we believe it is the best test for comparison even on binned\ndata. However, the values of \\Lit{PROB} for binned data will be shifted\nslightly higher than expected, depending on the effects of the\nbinning.\nFor example, when comparing two uniform distributions of 500\nevents in 100 bins, the values of \\Lit{PROB}, instead of being\nexactly uniformly distributed between {\\it zero} and {\\it one},\nhave a mean value of about 0.56.\nSince we are physicists, we can apply a useful rule:\nAs long as the bin width is small compared with any significant\nphysical effect (for example the experimental resolution)\nthen the binning cannot have an important effect.\nTherefore,\nwe believe that for all practical purposes, the probability value\n\\Lit{PROB} is calculated correctly provided the user is aware that:\n\\begin{UL}\n\\item\nThe value of \\Lit{PROB} should not be expected to have\n{\\bf exactly} the correct distribution for binned data.\n\\item\nThe user is responsible for seeing to it that the bin widths are\nsmall compared with any physical phenomena of interest.\n\\item\nThe effect of binning (if any) is always to make the value of \\Lit{PROB}\nslightly too big. That is, setting an acceptance criterion of\n(\\Lit{PROB>0.05} will assure that {\\bf at most}\n5\\% of truly\ncompatible histograms are rejected, and usually somewhat less.\n\\end{UL}\n \n\\subsubsection*{The Confidence Level for Two-dimensional Data}\n \nThe Kolmogorov Test for 2-dimensional data is not as well\nunderstood as for one dimension.\nThe basic problem is that it requires the unbinned data to be\nordered, which is easy in one dimension, but is not\nwell-defined\n(i.e. not scale-invariant) in higher dimensions.\nParadoxically, the binning which was a nuisance in one dimension\nis now very useful, since it enables us to define\nan obvious ordering.\nIn fact there are two obvious orderings (horizontal and vertical)\nwhich give rise to two (in general different) Kolmogorov\ndistance measures.\nRoutine \\Rind{HDIFF} takes the average of the two distances\nto calculate the probability value \\Lit{PROB},\nwhich gives very satisfactory results.\nThe precautions necessary for 1-dimensional data also apply to this case.\n \n%\\finalnewpage%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\Filename{H2Bin-by-bin-histogram-comparisons}\n\\section{Bin by bin histogram comparisons}\n\n\\Shubr{HDIFFB}{(ID1,ID2,TOL,NBINS,CHOPT,NBAD*,DIFFS*)}\n\n\\Action Compare two histograms, bin by bin. For each bin, return the\n        probability that the contents are from the same distribution.  \n        For details of the method see below.\n\n        The comparison may be done between two 1-dimensional histograms,\n        two 2-dimensional histograms, or between two profile histograms.\n\n\\begin{DLtt}{12345}\n\\item[{\\rm\\bf Input parameters:}]\n\\item[ID1]   The first histogram to be compared.\n             The ``reference'' histogram in options \\Lit{A} and \\Lit{C}.\n\\item[ID2]   The second histogram to be compared.\n             The ``data'' histogram in options \\Lit{A} and \\Lit{C}.\\\\\n             \\Lit{ID1}, \\Lit{ID2} are a pair of 1-D, 2-D, or profile\n             histograms booked with the same number of bins.\n\\item[TOL]   The tolerance for a passing the test.\n             Under options \\Lit{S} and \\Lit{C}, \\Lit{TOL}\n             is a number between 0 and 1 which\n             represents the smallest probability considered as an acceptable\n             match. \n             \\mbox{\\Lit{TOL}=0.05} will cause \\Lit{DIFFS} to reject the \n             bin as bad if there is less than a 5\\% probability the \n             two bins came from the same distribution.\n             Under option \\Lit{A}, \\Lit{TOL} is the degree of precision  of\n             match required for the test to be considered as passed. \n             \\mbox{\\Lit{TOL}=2.0}\n             means that a data bin differing from the reference mean by\n             less than 2.0 times the reference error is compatible.\n\\item[NBINS] The number of bins in the comparison. For a 1-dimensional\n             histogram, this is the number of bins plus 0, 1 or 2, depending\n             on whether the overflow and underflow channels are included.\n             For a 2-dimensional histogram, this will have the total number of\n             bins plus room for overflow bins along any of the axes requested.\n             For more detail, see the discussion of \\Lit{DIFFS} below.\n\\item[CHOPT] A string allowing specification of the following options:\n             \\begin{DLtt}{1}\n             \\item[N]  Use the absolute contents of each histogram, thus\n                       including the normalization of the histogram as well as \n                       its shape in the comparison.  \n                       By default, for the \\Lit{S} and \\Lit{C} options,\n                       in 1- and 2-dimensional histograms, \n                       the means are adjusted for the\n                       relative numbers of entries (including any overflow or\n                       underflow bins requested) in \\Lit{ID1} and \\Lit{ID2}.\n                       No adjustment is ever made for profile histograms.\n             \\item[O]  Overflow, requests that overflow bins be taken into\n                       account.\n             \\item[U]  Underflow, requests that underflow bins be taken into\n                       account.\n             \\item[R]  Right overflow bin. For a 2-dimensional histogram, it\n                       includes the X-Axis overflow bin in the comparisons.  \n                       If the \\Lit{O} option is used, this is automatic.\n             \\item[L]  Left underflow bin.  Same as above, but the X-Axis\n                       underflow is used.  \n                       The \\Lit{U} option uses this automatically.\n             \\item[T]  Top overflow bin.  Same as \\Lit{R}, but for the Y-Axis.\n             \\item[B]  Bottom underflow bin.  Option \\Lit{L} for the Y-Axis.\n             \\item[S]  Statistical comparison. Calculates the probability that\n                       both bins were produced from a distribution with the \n                       same mean. \n                       This probability is referred to in \\Lit{TOL} and \n                       \\Lit{DIFFS}.\n             \\item[C]  Compatibility test.  \n                       Considers bins of the reference histogram (\\Lit{ID1}) \n                       as perfectly describing the true distribution.\n                       Calculates the probability that the data \n                       (from \\Lit{ID2}) was produced from that distribution.   \n                       For 1- or 2-dimensional histograms, the Poisson \n                       mean is deduced from \\Lit{ID1}. \n                       For profile histograms, the test assumes a Gaussian \n                       with mean and standard deviation given by the \\Lit{ID1}. \n                       The \\Lit{C} option should be used when comparing data \n                       to a function, a well-known reference, or a\n                       calibration distribution.\n             \\item[A]  Absolute test. Like the \\Lit{C} test, except that\n                       \\Lit{TOL} and \\Lit{DIFFS} are in terms of the number \n                       of standard deviations, rather probability.\n                       The test is on the number of standard deviations by \n                       which the data from \\Lit{ID2} deviates from the mean.  \n                       Both the mean and the standard deviation are deduced \n                       from \\Lit{ID1}.\n                       Error bars must be on for this option.  \n                       This forbids overflow bins, underflow bins, and \n                       2-dimensional histograms.  \n                       The \\Lit{A} option ignores bins with zero contents \n                       in reference histogram.\n             \\item[Z]  Ignores bins with zero contents in the comparison.  \n                       For the \\Lit{S} option, ignores bins with zero \n                       contents in either histogram.\n                       For the \\Lit{C} and \\Lit{A} option, ignores bins \n                       with zero contents in the reference histogram.  \n                       The default action is to consider all\n                       bins as significant.\n             \\item[D]  Debug printout, dumps the critical variables in the\n                       comparisons, along with indicators of its weight, etc.\n                       The default (no options selected) does the \\Lit{S} \n                       option (statistical comparison), ignores underflow \n                       and overflow bins, and automatically corrects for the\n                       difference in entries between \\Lit{ID1} and \\Lit{ID2}.\n             \\end{DLtt}\n\\item[{\\rm\\bf Output parameters:}]\n\\item[NBAD*]  The number of bins failing the compatibility test according\n              to the criteria defined by \\Lit{TOL} and \\Lit{CHOPT}.\n\\item[DIFFS*] An array of length the number of bins being compared, which\n              gives the results of the test bin by bin (confidence levels for\n              options \\Lit{S} and \\Lit{C}, deviations for option \\Lit{A}).\n              Results are passed back in the form:\n              \\begin{DL}{1-D}\n              \\item[1-D] \\Lit{DIFFS(NX)} for no over or underflow or\n                         \\Lit{DIFFS(0:NX+1)},\n                         for overflow and/or underflow.\n              \\item[2-D] \\Lit{DIFFS(NX,NY)} or \\Lit{DIFFS(0:NX+1, 0:NY+1)}.\n              \\end{DL}\n\\end{DLtt}\n\n\n\\subsection*{When to use \\Rind{HDIFFB} instead of \\Rind{HDIFF}:}\n\n\\Rind{HDIFFB} treats the histogram bins individually, while \\Rind{HDIFF}\ntreats the histogram as a whole.  \nIn \\Rind{HDIFF}, one is comparing the overall shapes of a\nprobability distribution. \nTypically, an event is entered only in one\nchannel, and the choice of channel depends on a measured value of a continuous\ncoordinate, so that it makes sense for downward fluctuations in one bin to be\nconsidered as compensated by upward fluctuations in another bin.  \nIn \\Rind{HDIFFB},\neach bin is considered independently, except, perhaps, for an overall\nnormalization factor which is the sum over all bins.\n\nThus \\Rind{HDIFFB} is appropriate when:\n\\begin{UL}\n\\item It makes sense to identify a single channel as ``bad'', \n      for example if the bin contents correspond to hits in a \n      given detector element.\n\\item The data is heterogeneous, for example if the contents \n      are counts versus trigger bit.\n\\item You have already found a discrepancy on a shape with \\Rind{HDIFF} \n      and wish to focus on where disagreement is worst.\n\\end{UL}\n\nA plot of hits versus detector element, where the detector elements\ncover some angular range, is an example of a histogram which might \nbe considered with either comparison utility.  \nThe choice depends on the question you wish to answer:\n\n\\begin{UL}\n\\item If you want to know if the angular distribution looks the same, \n      use \\Rind{HDIFF}.\n\\item If you want a report on bad detector elements, use \\Rind{HDIFFB}.\n\\end{UL}\n\n\\subsection{Choice of \\protect\\Lit{TOL}:}\n\nIf you choose 0.05 for \\Lit{TOL}, you should expect 5 or so bad bins per\ntrial from a histogram with 100 channels.  \nFor monitoring, you must compromise\nbetween the number of false messages you can tolerate (based on the total\nnumber of channels you monitor), and the amount of data you will need to\ncollect to claim a channel is bad.  \nIn general, a somewhat smaller fraction of\nchannels than \\Lit{TOL} will be flagged as bad, \nsince for discrete distributions\n(Poisson statistics), the probability is quantized.  \nFor example, the probability might be 0.053 for 4 entries, and 0.021 for 3.  \nIf \\Lit{TOL}=0.05, only bins with 3 or fewer entries would be flagged as bad.\n\n\\subsection*{When to use the \\protect\\Lit{S} option:}\n\nThe \\Lit{S} option should be used when both histograms are filled with\nstatistical data, for example a momentum distribution from two successive \ndata runs.  \nUsing the \\Lit{S} option when comparing data to a function or known \nreference yields poor results because it attributes errors to both histograms. \nIn this case, the \\Lit{C} option should be selected.\n\n\\subsection*{When to use the \\Lit{C} option:}\n\nThe \\Lit{C} option assumes that the reference histogram contains the\ntheoretically expected values with no (or negligible) errors.  \nExamples might be a flat distribution hand-inserted as the expectation \nfor a phi distribution, or\na long data run to be compared with shorter data runs.\n\n\\subsection*{When to use the \\Lit{A} option:}\n\nThe \\Lit{A} option can be used as an equivalent to the \\Lit{C}\noption by choosing \\Lit{TOL}\nin terms of standard deviations instead of probability, and returns $z$ values\nin \\Lit{DIFFS} for each bin.\n\nThe \\Lit{A} option is intended for setting by hand absolute minima and maxima.\nTo restrict an efficiency between 80 and 100\\%, load the reference histogram\nwith a mean of 0.9 (via \\Rind{HPAK}) and the error bar of 0.1 (via \\Rind{HPAKE}),\nand use \\Rind{HDIFFB} with \\mbox{\\Lit{TOL}=1.0} and the \\Lit{A} option.  \nThe \\Lit{N} option should also be selected for this application.\n\n\\subsection*{Comparison of Weighted versus Unweighted events:}\n\nThis is in general undesirable, as it forces you into the less accurate\nGaussian approximation.  \nThus it is preferable, for example, to have unweighted Monte Carlo events \nif you need to use \\Rind{HDIFFB} to compare with data.  \nThe only useful case is if the weighted histogram is the reference\nhistogram in the \\Lit{C} comparison, which only makes sense if you have much\nbetter accuracy than your data.\n\n\\subsection*{Using Profile histograms:}\n\nThe \\Lit{N} option is irrelevant for profile histograms.  \nThe overflow/underflow options are illegal for profile histograms because \ninsufficient information is stored to calculate the error bars.  \nNone of the test options (\\Lit{S}, \\Lit{C}, or \\Lit{A}) check on the number\nof entries in a profile histogram bin.  \n(To do that, make a separate 1-dimensional histogram.)  \nThis has an unexpected effect when the number of entries are small.  \nBins with no entries always pass the \\Lit{S} and \\Lit{C} options \n(no data is compatible with any distribution), so in such\ncases more bins pass than called for by \\Lit{TOL}.\n\n\\subsection*{Values of \\Lit{DIFFS}:}\n\nThe value of \\Lit{DIFFS} may depend somewhat on the value of \\Lit{TOL}\nchosen, as the approximation chosen to calculate \\Lit{DIFFS} depends \non both the number of entries and on the size of \\Lit{TOL} \n(how accurately \\Lit{DIFFS} must be calcuated).\n\nThe \\Lit{S} option sometimes returns a confidence level of 1.0 in the small\nstatistics calculation, i.e. there is no probability that the two numbers\ncame from different distributions.  \nThis is due to finite precision.\nValues slightly higher than 1.0 will be returned when the two content\nvalues are identical, since no statistical test could claim they came from\ndifferent distributions.\n\n\\subsection*{Other notes:}\n\nThe normalization scaling (used unless \\Lit{N} option selected) is based on\nchannel contents for all channels requested (including overflow/underflow),\nprovided you select one of the overflow/underflow options.\n\nNegative bin contents are flagged as bad bins in \\Lit{S}, \\Lit{C} options.\n\n\\subsection*{Statistical methods and numerical notes:}\n\n(For simplicity, this is written as if the \\Lit{N} option were in effect.)\n\nThe methods used for the \\Lit{S} and \\Lit{C} options are correct for\nunweighted events and Poisson statistics for 1- or 2- dimensional histograms.  \nErrors may result in either the \\Lit{S} and \\Lit{C} options for small \ntolerances if bin contents are greater than the largest allowed integer.\n\nFor the \\Lit{S} option with unweighted events, the test (which is\nuniformly most powerful) treats \\Lit{N} = \\textem{sum of the two bin contents} \nas having chosen via a binomial distibution which histogram to enter.  \nThe binomial parameter \\Lit{p} is given by the relative normalization of the\nhistograms (0.5 if the total number of entries in each histogram was the same). \nFor \\Lit{DIFFS} values greater than \\Lit{TOL}, the first two digits are correct. \nFor values less than \\Lit{TOL}, the two digits to the right of the first \nnon-zero \\Lit{TOL} digit are significant,\ni.e. for \\mbox{\\Lit{TOL}=0.0001}, 0.000xxx are significant.  \nOne can force higher accuracy by setting \\Lit{TOL} smaller (or even 0), \nbut calculation time will increase, and warning messages will be issued.  \nA Gaussian approximation is used when there are 25 or more events in each bin, \nand \\mbox{\\Lit{TOL}$>$0.001}.\n\nThe \\Lit{C} option for unweighted events in the data histogram simply \ncalculates the Poisson probability of finding $n$, the \\Lit{ID2} bin value,  \ngiven a mean equal to the bin value of \\Lit{ID1}. \nA Gaussian approximation is used when the the mean is $10^{6}$ or larger, \nand \\Lit{TOL} is 0.001 or larger.  \nGiven the expected mean, the choice of \\Lit{TOL} implies bounds \n($n_{<},n_{>}$) on $n$ (i.e. $n$ within these bounds passes).  \nAn error occurs when the approximations used in calculating \n\\Lit{DIFFS} give an incorrect value for $n_{<}$ or $n_{>}$.  \nNo such errors occur for mean $<10^{5}$ and \\Lit{TOL} $>10^{-15}$.\nThe errors in $n_{<}$ or $n_{>}$ are less than 2 for mean $<10^{6}$,\n\\Lit{TOL} $>10^{-6}$, or\n    mean $<10^{7}$, \\Lit{TOL} $>10^{-5}$.  \nThere is a maximum $n$ beyond which \\Lit{DIFFS}\nreturns zero, so bins with $n > n_{max}$ always fail.  For mean $<10^{7}$,\nthis is irrelevant for values of \\Lit{TOL} $>10^{-9}$ .\n\nFor the profile histogram \\Lit{S} option, \\Rind{HDIFFB} calculates\nthe $t$ test probability that both bin means were produced from a population \nwith the same mean.  \nThe \\Lit{C} option calculates the probability of finding the\nvalue in \\Lit{ID1} given a Gaussian with $\\mu$ and $\\sigma$ given by the\n\\Lit{ID2} contents.\nSmall numbers of entries for either test give \\Lit{DIFFS} values which are\ntoo large, and \\Rind{HDIFFB} will reject too many events in profile histograms.\n\nFor weighted events, the \\Lit{S} and \\Lit{C} options use a Gaussian\napproximation.\nThis results in \\Lit{DIFFS} values which are too low.  \n\\Rind{HDIFFB} rejects too many bins for weighted events, \nparticularly for small numbers of equivalent events.\n\n\n\\subsection*{Error messages of \\Rind{HDIFFB}:}\n\n\\newcommand{\\erritem}[1]{\\item[\\underline{\\tt#1}]\\mbox{}\\\\}\n\\begin{DLtt}{xx}\n\\erritem{Warning: Zero tolerance}\n    The passed value \\Lit{TOL} is less than or equal to 0. \n    \\Lit{TOL}=0. can be\n    used to force highest accuracy in the \\Lit{S} option.\n\\erritem{Warning: Only one comparison at a time, please.}\n    More than one type of comparison was selected.  \n    Only one of options \\Lit{S}, \\Lit{C}, and \\Lit{A} may be used. \n    The default \\Lit{S} option will be used.\n\\erritem{Warning: Different binning.}\n    The \\Lit{XMIN} values for a 1-dimensional histogram or the \n    \\Lit{XMIN} and/or \\Lit{YMIN}\n    values on a 2-dimensional histogram are different.  \n    This may give inaccurate results.\n\\erritem{Warning: Weighted or saturated events in 2-dimensions.}\n    HBOOK does not compute error bars for two dimensional histograms, thus\n    weighted event are not allowed, and \\Rind{HDIFFB} can not compute \n    the correct statistics.  \n    An answer is still given, but it is probably not right.\n    The only reliable case is a weighted 2-dimenension histogram as the\n    reference histogram for the \\Lit{C} option.\n\\erritem{Sum of histogram contents is zero!}\n    The sum of the content bins is zero.\n\\erritem{Histograms must be the same dimension.}\n    A 1-dimensional and a 2-dimensional histogram have been specified.  In\n    order for the routine to work, both must be the same dimensionality.\n\\erritem{Both histograms must be the standard or profile type.}\n    Two different types of histograms have been specified.  \n    Both must be profile or non-profile.  \n    You cannot mix types.\n\\erritem{Not enough bins in DIFFS to hold result.}\n    The parameter \\Lit{NBINS} is less that the number of bins in \n    the histograms.\n\\erritem{Number of channels is different.}\n    The number of channels in the two histograms to compare are different. \n    They must be the same before the routine will process the data.\n\\erritem{U/O/L/R/T/B Option with weighted events.}\n    HBOOK does not compute an error bar for over-/under-flow bins, \n    thus it may not be used with weighted events.\n\\erritem{U/O/L/R/T/B Option with profile histograms.}\n    HBOOK  does not compute an error bar for over-/under-flow bins, \n    thus it may not be used with profile histograms.\n\\erritem{Weighted options and no HBARX.}\n    The user had not told HBOOK to figure the error bars for the histograms.\n    Therefore, the operations will not be valid.\n\\erritem{A-option with no error bars on reference histogram.}\n    The user has not told HBOOK to compute error bars for the reference\n    histogram. \n    This error is also returned when the user attempts to select\n    the \\Lit{A} option to compare 2-dimensional histograms.\n\\end{DLtt}\n\n\\subsection*{Statistical comments:}\n\nThe methods used for the \\Lit{S} and \\Lit{C} mode are correct for unweighted events and\nPoisson statistics for one or two-dimensional histograms.  \nFor weighted events,\na Gaussian approximation is used, which results in \\Lit{DIFFS} values which are\ntoo low when there are fewer than 25 or so ``equivalent events'' (defined\nunder \\Rind{HSTATI}) per bin.  \nThis is caused by either few entries or by wide fluctuation in weights.  \nThe result is that \\Rind{HDIFFB} rejects to many bins in this case.\n\nComparisons for profile histograms assume Gaussian statistics\nfor the \\Lit{S} and \\Lit{C} mode comparisons of the channel mean.  \nFewer that 25 or so events will result in \\Lit{DIFFS} values which are too large.  \nThe result is that \\Rind{HDIFFB} rejects too many event in these low statistic cases.\n\n% Local Variables: \n% mode: latex\n% TeX-master: \"hboomain\"\n% End: \n", "meta": {"hexsha": "78e776ac197b892a1108fcefa9ab98aafbe7cab3", "size": 33507, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "hbook/hbookch6.tex", "max_stars_repo_name": "berghaus/cernlib-docs", "max_stars_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-24T12:30:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-24T12:30:01.000Z", "max_issues_repo_path": "hbook/hbookch6.tex", "max_issues_repo_name": "berghaus/cernlib-docs", "max_issues_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hbook/hbookch6.tex", "max_forks_repo_name": "berghaus/cernlib-docs", "max_forks_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.2595204513, "max_line_length": 87, "alphanum_fraction": 0.7043901274, "num_tokens": 8150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982315512489, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3264295261365004}}
{"text": "\\documentclass{article}\n\n\\begin{document}\n\n\\title{Equations used in Stephen R. Berggren's Apple Nuclear Power Plant Simulation}\n\\author{Kevin Riggle}\n\n\\maketitle\n\n\nOr, \\emph{Nuclear Power Plant: The Board Game}.\n\nEach turn represents a day in the life of a nuclear power plant.\n\n\\section{Warning Thresholds}\n\nNotify the player when these thresholds are exceeded:\n\n\\begin{itemize}\n\\item Reactor overheats above 800$^{\\circ}$C.\n\\item Heat Exchanger overheats above 500$^{\\circ}$C.\n\\item Turbine output is low below 1000 kW.\n\\item Turbine output overloads above 2000 kW.\n\\item Cooling Tower overheats above 300$^{\\circ}$C.\n\\item Emergency Cooling System coolant volume is low below 200 gal.\n\\item Primary Cooling System coolant volume is low below 100 gal.\n\\item Secondary Cooling System coolant volume is low below 100 gal.\n\\end{itemize}\n\nNotify the player when these levels are met:\n\n\\begin{itemize}\n\\item The Reactor core is damaged when it has 4 or more points of damage.\n\\item The Reactor core has melted down when it has 6 or more points of damage.  This ends the game in a loss.\n\\item The Primary Cooling System is leaking when it has 5 or more points of damage.\n\\item The Secondary Cooling System is leaking when it has 5 or more points of damage.\n\\item The Emergency Cooling System is leaking when it has 3 or more points of damage.\n\\end{itemize}\n\nNotify the player of these status conditions:\n\n\\begin{itemize}\n\\item The Primary Cooling System is broken.  Report the coolant pump failure percentage as $10\\times$ the number of points of damage the system has, up to a maximum of 100\\% (10 or more points).\n\\item The Secondary Cooling System is broken.  Report the coolant pump failure percentage as $10\\times$ the number of points of damage the system has, up to a maximum of 100\\% (10 or more points).\n\\item The Heat Exchanger is broken.\n\\item The Turbine is broken.\n\\end{itemize}\n\n\\section{Calculating Component Damage}\n\\subsection{Reactor overheated}\n\nEvery turn when the Reactor is overheated (above 800$^{\\circ}$C), the reactor gains:\n\\begin{itemize}\n\\item 1 point of damage always\n\\item 1 point if it is above 850$^{\\circ}$C\n\\item 1 point if it is above 900$^{\\circ}$C\n\\item 1 point if it is above 950$^{\\circ}$C\n\\end{itemize}\n\nSo the Reactor can gain up to 4 points of damage a turn.\n\nEvery turn when the Reactor is overheated the Primary Cooling System gains 1 point of damage.\n\nEvery turn when the Reactor is overheated the Emergency Cooling System gains 1 point of damage.  The Emergency Coolant system gains 1 additional point of damage if the Reactor temperature is above 850$^{\\circ}$C.\n\n\\subsection{Heat Exchanger overheated}\n\nEvery turn when the Heat Exchanger is overheated:\n\\begin{itemize}\n\\item The Heat Exchanger gains 1 point of damage.  The Heat Exchanger gains 1 additional point of damage if the Heat Exchanger is above 600$^{\\circ}$C.\n\\item The Primary Cooling System gains 1 point of damage.\n\\item The Secondary Cooling System gains 1 point of damage.\n\\end{itemize}\n\n\\subsection{Turbine overloaded}\n\nEvery turn when the Turbine is overloaded (output is above 2000 RPM):\n\\begin{itemize}\n\\item The Turbine gains 1 point of damage.  The Turbine gains 1 additional point of damage if its output is above 2500 RPM.\n\\item The Secondary Cooling System gains 1 point of damage.\n\\end{itemize}\n\n\\subsection{Cooling Tower overheated}\n\nEvery turn when the Cooling Tower is overheated (above 300$^{\\circ}$C), the Secondary Cooling System gains 1 point of damage.\n\n\\subsection{Primary Cooling System coolant volume low}\n\nEvery turn when the Primary Cooling System coolant volume is low (below 100 gal.), the Primary Cooling System gains 1 point of damage.\n\nIf the Primary Cooling System has 5 or more points of damage, the Primary Cooling System is leaking.  Every turn reduce coolant volume by the number of points of damage the system has.\n\n\\subsection{Secondary Cooling System coolant volume low}\n\nEvery turn when the Secondary Cooling System coolant volume is low (below 100 gal.), the Secondary Cooling System gains 1 point of damage.\n\nIf the Secondary Cooling System has 5 or more points of damage, the Secondary Cooling System is leaking.  Every turn reduce coolant volume by the number of points of damage the system has.\n\n\\subsection{Emergency Cooling System damage}\n\nIf the Emergency Cooling System has 3 or more points of damage, the Emergency Cooling System is leaking.  Every turn reduce coolant volume by twice (2$\\times$) the number of points of damage the system has.\n\n\\end{document}\n", "meta": {"hexsha": "b842013371cd4b227d20a749615c997747176abc", "size": 4517, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "apple-nuclear-power-plant-sim/equations.tex", "max_stars_repo_name": "AllSafeCyberSecur1ty/Nuclear-Engineering", "max_stars_repo_head_hexsha": "302d6dcc7c0a85a9191098366b076cf9cb5a9f6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-26T20:01:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T20:01:13.000Z", "max_issues_repo_path": "apple-nuclear-power-plant-sim/equations.tex", "max_issues_repo_name": "AllSafeCyberSecur1ty/Nuclear-Engineering", "max_issues_repo_head_hexsha": "302d6dcc7c0a85a9191098366b076cf9cb5a9f6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "apple-nuclear-power-plant-sim/equations.tex", "max_forks_repo_name": "AllSafeCyberSecur1ty/Nuclear-Engineering", "max_forks_repo_head_hexsha": "302d6dcc7c0a85a9191098366b076cf9cb5a9f6e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-26T19:59:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T19:59:13.000Z", "avg_line_length": 43.4326923077, "max_line_length": 212, "alphanum_fraction": 0.7779499668, "num_tokens": 1105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3264295192838106}}
{"text": "\\begin{multicols}{3}\n\\textbf{Solving Abrupt Silicon PN Junction Question}\n\n\\begin{enumerate}\n\\item Calculate $V_{bi}$.\n\\item Look up $D_p$ on the diffusion coefficient chart. \\ref{fig:pictureonright}\n% find that chart in volume one and include? on seperate page?, also reference that picture, figure from Lecture I- Jan 16, p.7\n\\item Calculate the diffusion length: $L_p = \\sqrt{D_p \\tau_p}$ (for $p^+n$) - or - $L_n=\\sqrt{D_n \\tau_n}$ (for $pn^+$)\n\\item If: $L_p > x_p $ (for $p^+n$) - or - $L_n > x_n$ (for $pn^+)$, the diode is short-base.\n\\end{enumerate}\n\n\\subsection{Bipolar Junction Transistor}\n\n\\begin{tabular}{p{5.30cm}p{3.5cm}}\n$\\beta_F = \\frac{\\alpha_F}{1-\\alpha_F}$; $\\beta_{dc}=\\frac{\\alpha_{dc}}{1-\\alpha_{dc}}$ & Gain \\\\ %\\hline \n$\\alpha_F = \\gamma_F \\alpha_T$; $\\alpha_{dc}=\\gamma \\alpha_T$ \\hfill \\break  $\\alpha_R=\\gamma_R \\alpha_T$ & Base Transport \\hfill \\break  Factor (BTF) \\\\ %\\hline\n$\\alpha_{T(npn)}=\\cfrac{I_{Cn}}{I_{En}}$; $\\alpha_{T(pnp)}= \\cfrac{I_{Cp}}{I_{EP}}$ & BTF ($\\approx 0.999$) \\\\\n$\\alpha_T= 1-\\frac{x_B^2}{2D_n\\tau_n}=1-\\frac{x_B^2}{2Ln^2}$ & BTF ($D_n$. Fig 3,5) \\\\\n$I_{pE}= \\frac{-qA_En_i^2 D_p}{N_{dE}x_E} \\exp\\left(\\frac{qV_{BE}}{k_BT}-1\\right)$ & Short Emitter \\hfill \\break \n$L_{pE}= \\sqrt{D_{pE}\\tau_n}>x_E$ \\\\\n$I_{pE}= \\frac{-qA_E n_i^2 D_p}{N_{dE}L_p} \\exp\\left(\\frac{qV_{BE}}{k_BT}-1\\right)$ & Long Emitter \\hfill \\break \n$L_{pE}= \\sqrt{D_{pE}\\tau_n}<x_E$ \n\\end{tabular}\n%\n\\begin{tabular}{p{3.8cm}p{5cm}}\n$\\gamma_F= \\left[1+\\frac{x_B N_{aB} D_{pE}}{x_E N_{dE} D_{nB}}\\right]^{-1}$ \n$\\gamma_R = \\left[1+\\frac{x_B N_{aB} D_{pC}}{x_E N_{dC} D_{nB}}\\right]^{-1}$ & Short Emitter Forward and \\hfill \\break Reverse Emitter Injection (REI) \\hfill \\break Efficiency ($\\gamma_R$ swap roles, E \\& C) \\\\\n%\n\\end{tabular}\n%\n\\begin{tabular}{p{4.2cm}p{4.6cm}}\n$\\gamma_F= \\left[1+\\frac{x_B N_{aB} D_{pE}}{L_{PE} N_{dE} D_{nB}}\\right]^{-1}$ \n$\\gamma_R = \\left[1+\\frac{x_B N_{aB} D_{pC}}{L_{PC} N_{dC} D_{nB}}\\right]^{-1}$ & Long Emitter Forward and \\hfill \\break (REI) Efficiency (for $\\gamma_R$ swap roles of E \\& C) \\\\\n\\end{tabular}\n\n\\begin{tabular}{p{5cm}p{3.8cm}}\n$\\gamma_{(npn)}= \\cfrac{I_{En}}{I_E}= \\cfrac{|I_{En}|}{|I_{En}|+|I_{Ep}|}$  \\hfill \\break $\\gamma_{(pnp)}= \\cfrac{I_{Ep}}{I_E}= \\cfrac{|I_{Ep}|}{|I_{En}|+|I_{Ep}|}$ & \\hfill \\break  Emitter injection \\hfill \\break  Efficiency \\\\\n\\end{tabular}\n\n\\begin{tabular}{l l}\n$I_E=I_{Ep}+I_{En}$ $I_C = I_{Cp}+I_{Cn}$ & $I_B = \\cfrac{I_C-I_{CE0}}{\\beta_{dc}}$ \\\\\n$I_C = \\alpha_{dc}I_E+I_{CB0}$ $I_C=\\beta I_B+I_{CE0}$ & $I_{Cn} \\approx I_{BC0}$ \\\\\n\\end{tabular}\n\n\\begin{tabular}{p{5cm}p{3.8cm}}\n$I_{Cn} \\approx I_{BC0}$ & Collector Reverse  \\hfill \\break Saturation Current \\\\\n$I_{Cn} \\approx I_{BC0}$ & Emitter-Collector \\hfill \\break Saturation Current \\\\\n\\end{tabular}\n\nElectron Current Density (ECD) - constant base doping \\hfill \\break \n$J_n= \\frac{qD_n n_i^2}{x_B N_{aB}}\\left[\\exp\\left(\\frac{qV_{BC}}{k_BT}\\right)-\\exp\\left(\\frac{qV_{BE}}{k_BT}\\right)\\right]$  (A/$\\text{cm}^2$)\n\nECD - non-constant base doping   (A/$\\text{cm}^2$) \\hfill \\break \n$J_n= J_0\\left[\\exp\\left(\\frac{qV_{BC}}{k_BT}\\right)-\\exp\\left(\\frac{qV_{BE}}{k_BT}\\right)\\right]$ \\hfill \\break \n$J_0= \\frac{q^2n_i^2 \\tilde{D}_n}{Q_B}$, $\\tilde{D}_n= \\text{avg}(D_n)$  \\hfill \\break \n%\n%\nCollector Current Density (under active bias)  \\hfill \\break  \n$J_C \\approx J_0 \\exp\\left(\\frac{qV_{BE}}{k_BT}\\right)$  \\hfill \\break  \n%\n%\nRecombination of excess minority carriers in the base  \\hfill \\break\n$I_{rB}=\\frac{qA_gn_i^2x_B}{2N_{aB}\\tau_n}\\left[\\exp\\left(\\frac{qV_{BE}}{k_BT}\\right)-1\\right]$  \\hfill \\break\n%\n%\nCollector-Emitter Breakdown Voltage  in terms of the Collector-Base\nBreakdown. Note that $m \\approx 4$ \\hfill \\break\n$BV_{CE0}=\\frac{BV_{CB0}}{\\beta^{1/m}}$ \\hfill \n% \\vfill\\null \\columnbreak\n  \\textbf{Finding}  $\\beta$ \\textbf{Of a BJT}\n  \\begin{enumerate}\n  \\item  Look-up $D_{pE}$ amd $D_{pC}$ on chart\n  \\item  Find $L_{pE}=\\sqrt{D_{pE}\\tau_{pE}}$ and $L_{pC}=\\sqrt{D_{pC}\\tau_{pC}}$ \n  \\item  Check if emitter is long or short $L_{pE}>x_B \\rightarrow $ long emitter or $L_{pE}<x_B \\rightarrow$ short emitter.\n  \\end{enumerate}\n  % act like an indent \n\\begin{flushright}\n   4. Find $\\gamma_F$, (Short Emitter Forward Efficiency) \\break \n   5.  Find $\\alpha_T$ (Base Transport Factor)            \\break \n   6.  Find $\\alpha_F$ (Base Transport Factor)            \\break \n   7.  Find $\\beta_F$  (Current Gain)                    \n\\end{flushright}\n\\vspace*{-0.75cm}\n\\begin{flushright}\n\\textbf{Designing an Prototype NPN  \\\\ Structure for an Amplifier} \\break \n1. Assume these doping levels: \\\\ $N_{dC}=10^{16} \\text{cm}^{-3}$ \nand $N_{aB}=5 \\times 10^{16} \\text{cm}^{-3}$ \\\\\n2. Calculate $V_{bi}=\\frac{k_BT}{q} \\ln \\left[\\frac{N_dN_a}{n_i^2}\\right]$ \\\\\n3. Use $V_a$, desired punch through voltage. $x_B= \\left(\\frac{N_{aB}}{N_{dC}}\\right)^{-1}\\left[\\frac{2\\epsilon_s}{q}\\left(\\frac{1}{N_{aB}}+\\frac{1}{N_{dC}}\\right)(V_A-V_{bi})\\right]^{1/2}$ \\\\\n4. Calculate (shown as a design parameter) $x_{p0}=\\left(\\frac{N_{aB}}{N_{dC}}\\right)^{-1}\\left[\\frac{2\\epsilon_s}{q}\\left(\\frac{1}{N_{aB}}+\\frac{1}{N_{dC}}\\right)(V_{bi})\\right]^{1/2}$ \\\\\n5. Calculate $\\alpha_T=1-\\frac{x_B^2}{2D_n \\tau_n}$ use hole curve ($D_n=23 \\text{cm}^2 s^{-1})$ for doping levels above. \\\\\n6. With these doping levels $\\alpha_t \\cong 1$. Since $\\alpha_T \\cong 1$, assume $\\alpha_F = \\gamma_F$. \\\\\n7. Find the ratio = $\\frac{N_{dE}}{D_{pE}} = \\underbrace{\\left(\\frac{x_BN_{aB}}{x_ED_{nB}}\\right)\\left(\\frac{1}{\\gamma_F}-1\\right)}_{ratio}$ \\\\\n8. Using $D_{pE}=\\frac{N_{dE}}{ratio}$, find a good value for \\\\\n$N_{dE}$ that allows you to look up $D_{pE}$ on the diffusion chart. Use the curve for holes.\n\\end{flushright}\n\n\\textbf{Ebers-Moll Equations}\n\\hfill \\break \n\\begin{tabular}{p{4.8cm}p{4cm}}\n$I_E=I_F-\\alpha_RI_R$ & Emitter Current \\\\\n$I_C=\\alpha_FI_F-I_R$ & Collector Current \\\\\n$I_B=I_E-I_C$ \\\\\n$I_B=(1-\\alpha_F)I_F+(1-\\alpha_R)I_R $& Base Current \\\\\n$I_{F0}=qA \\left[\\frac{D_En_{E0}}{L_e}+\\frac{D_Bp_{B0}}{W}\\right]$ & Forward Coefficient \\\\\n$I_F=I_{F0} \\left[e^{(eV_{eB}/k_BT)}-1\\right]$ & For Curr Component \\\\\n$I_{R0}=qA \\left[\\frac{D_E N_{c0}}{L_C}+\\frac{D_Bp_{B0}}{W}\\right]$ & Reverse Coefficient \\\\\n$I_R=I_{R0}\\left[e^{(qV_{cB}/k_BT)}-1\\right]$& Rev Cur Component \\\\\n$\\alpha_FI_{F0}=\\alpha_R I_{R0}=I_S$ \\\\ $\\frac{I_{F0}}{I_{R0}}=\\frac{\\alpha_R}{\\alpha_F}$ & reciprocity Relation. \\\\\n$\\beta_f = \\frac{\\alpha_F}{1-\\alpha_F}$ & Normal Forward $\\beta$\n\\end{tabular}\n$\\alpha_R I_R = \\frac{qAD_Bp_{B0}}{W} \\left[ e^{(qV_{cB}/k_BT)-1}\\right]$  Ebers-Moll Eqns \\\\\n\n$\\alpha_R I_R = \\frac{qAD_Bp_{B0}}{W} \\left[ e^{(qV_{cB}/k_BT)-1}\\right]$ Vol III - 47.\n\n\\textbf{Transit Time and Frequency Response} \\hfill \\break\n\\begin{tabular}{p{1.75cm}p{7.05cm}}\n$\\tau_1=r_e C_{jE}$ & Emitter-Base Capacitance Charging Time \\\\\n$\\tau_2=r_CC_{jC}$ & Collector Capacitance Charging Time \\\\\n$\\tau_B=\\frac{x_B^2}{2D_{nB}}$ & Base Transit Time \\\\\n$\\tau_C = \\cfrac{x_{dc}}{v_{sat}}$ & Collector Depletion Region Transit Time \\hfill \\break ($x_{dc}$:Depletion region width of collector) \\hfill \\break ($v_{sat}$: Saturation velocity, $\\approx 10^7$ m/s)\n\\end{tabular}\n$\\tau_{EC}=\\tau_1+\\tau_2+\\tau_B+\\tau_C$ $\\tau_{EC}=\\tau_C+\\tau_B+\\tau_E$ \\hfill \\break Emitter to Collector Transit Time.  $f_T = \\frac{1}{2 \\pi \\tau_{EC}}$ Cut-off Frequency.\n\n\\textbf{Amplification}: For amplifying BJTs, the thickness and resistivity of the collector are both large.  Th\nis results in an increased breakdown voltage and reduces the early effect. \\hfill \\break\n\n\\textbf{Switching}: For switching BJT's, saturation (On-State) resistance must be minimized, which requires a very thin collector layer with a resistivity of a few tenths of an $\\Omega$-cm. \n\nThe Early Effect results in an increase in $I_C$ due to base-width modulation when $V_{CB}$ is increased. \n\n\\textbf{Finding} $V_T$: Using substrate resistivity $\\rho \\rightarrow N_A \\& N_D$ (Vol I - pg 71) 2. Calculate $\\phi_p$ 3. Calculate $Q_f$ from given data $Q_f/q$ 4. Calculate $C_{ox} $ 5. Find $\\phi_{MS}$ (depends on gate material, use Vol I - pg 96.\n6. Calculate $V_{FB}$\n7. Calculate $V_T$.\n\n\\textbf{MOSFET's} \\hfill \\break \n\\begin{tabular}{p{1.8cm}p{7cm}}\n$K_s=11.8$ & Dielectric Constant of Si (at 300 K) \\\\\n$K_o=3.9$  & Dielectric Constant of Si$O_2$ (at 300K) \\\\ \n\\end{tabular}\n\\begin{tabular}{p{4.6cm}p{4.2cm}}\n$\\epsilon_s=K_s\\epsilon_0=1.1045 \\times 10^{-12}\\frac{F}{cm}$ & Permittivity of Si (at 300K) \\\\\n\\end{tabular}\n\\begin{tabular}{p{4.8cm}p{4.2cm}}\n$\\epsilon_{ox}=K_0\\epsilon_0=345.15 \\times 10^{-15}\\frac{F}{cm}$  & Permittivity Si$O_2$ (300K) \\\\ \n\\end{tabular}\nP-type Si MOS Structure $\\rightarrow$ N-channel Device \\hfill \\break \nN-type Si MOS Structure $\\rightarrow$ P-channel Device \\hfill \\break\nRef Voltage rel to the semicond doping concent.\n$\\phi_{F(p-type)}= \\phi_p = \\frac{kT}{q}\\ln\\left(\\frac{N_A}{n_i}\\right)$ \\hfill \\break \n$\\phi_{F(n-type)}= \\phi_p = - \\frac{kT}{q}\\ln\\left(\\frac{N_D}{n_i}\\right)$ Semicond Surf Pot at Depletion-Inversion Transition\nPoint \n$\\phi_S = 2 \\phi_F$ \\hfill \\break \n%\n%\nFlat-band voltage (voltage that produces flat energy bands in the oxide and silicon) \\hfill \\break \n$V_{FB} = \\phi_{MS}-\\frac{Q_f}{C_{ox}}$ With a charge on the oxide layer.\n$V_{FB}=\\phi_M-\\phi_S=\\phi_{MS}$ oxide layer free of charge.\n\n\\begin{tabular}{p{4.4cm}p{4.2cm}}\n$W_T=\\left[\\frac{2K_s\\epsilon_0}{qN_A}(2\\phi_p)\\right]^{1/2}$ & Depletion Width Iv p 43 \n\\\\\n$\\phi(x)=\\frac{1}{q}[E_f-E_i(x)]$ & Potential in Silicon \\\\\n%\n$\\phi_S=\\phi(0)=\\frac{1}{q}(E_f-E_i(0))$ & Surface Potential \\\\\n%\n%\n$C_{ox}=\\frac{\\epsilon_{ox}}{x_{ox}}$ $\\dot{A} = 10^{-10} m$ & Oxide Layer Capacitance \\\\\n\\end{tabular}\n\\begin{tabular}{p{4.4cm}p{4.4cm}}\n$Q_{d(max)}=\\sqrt{4k_s\\epsilon_0qN_A|\\phi_P|}$ & Space Charge Density (max) \\\\\n\\end{tabular}\n$V_T =V_{FB}+2|\\phi_p| + \\frac{|Q_{d(max)}|}{C_{ox}}$, Threshold Voltage(T.V.) \\hfill \\linebreak\n$V_T=2\\phi_F-\\frac{K_s x_{ox}}{K_{ox}} \n\\left[\\frac{4qN_A}{K_S \\epsilon_0}\\phi_F\\right]$\n\\hfill \\break\n$\\Delta V_G=V_T^\\prime-V_T$ (Threshold Adjustment)\n$\\Delta V_G= \\frac{-Q_l}{C_{ox}}$ $Q_l=\\pm qN_l \n\\rightarrow N_l = \\pm \\frac{Q_l}{q}$ $V_T^\\prime$ Un-adjusted T.V. $V_T$: Adjusted T.V. $N_l$: \\# of implanted ions $Q_l$: Implant-related charge/$\\text{cm}^2$  Donor\\{+\\} or Acceptor \\{-\\}\n\n$I_D = \\frac{Z \\bar{\\mu}_n C_{ox}}{L} \\left[(V_G-V_T)V_D - \\frac{V_D^2}{2}\\right]$ Square-law theory\n\nZ: Width of MOSFET $\\bar{\\mu}_n$ Effe hole mobil Vol IV. Pg 73\n\n\\textbf{Long Channel MOSFET Equation} Bulk Charge Factor ($\\alpha$) %\\hfill \\break \n$I_D= \\mu C_{ox}\\frac{W}{L} \\left[\\left(V_G-V_T-\\frac{1}{2}V_D\\right)V_D\\right]$ \\hfill \\break \n$I_D= \\mu C_{ox}\\frac{W}{2\\alpha L} \\left[\\left(V_G-V_T-\\frac{1}{2}V_D\\right)V_D\\right]$\n\n\\textbf{Channel Carrier Velocity} (Using Long-Channel Theory)\n$V=\\cfrac{\\mu_n C_{ox}\\left[\\left(V_G-V_T-\\frac{1}{2}V_D\\right)V_D\\right]}{Q_NL}$\n\n%\\hfill \\break \nNote: The saturation velocity of carriers in Silicon is: $v_{sat} \\approx 10^7$ cm/s.\nIf this equation yields a velocity $v > v_{sat}$, long channel theory does not apply in this situation. $Q_{n(source)}=C_{ox}(V_G-V_T)$, $Q_{n(drain)}=C_{ox}(V_G-V_D-V_T)$.\n\n\\textbf{Drain Saturation Voltage}\n$V_{D(sat)}=V_G-V_T$ $V_{D(sat)}=\\frac{V_G-V_T}{\\alpha}$.\n\\vspace*{-0.4cm}\n\\begin{flushright}\n$g_d$, $g_m$ Small Signal Parameters and Conductance % Vol.IV - pg 83\n$f_{max}=\\frac{g_m}{2\\pi C_{ox}}=\\frac{\\bar{\\mu}_nV_D}{2\\pi L^2}$ Cutoff f $V_D \\leq V_{D(sat)}$ \\break\nUsing $I_{D(sat)}=\\mu_nC_{ox}\\frac{W}{2L}(V_G-V_T)^2$ \\linebreak\n%\nChannel Dimensions $\\frac{W}{L}=\\frac{2I_{D(sat)}}{\\mu_nC_{ox}(V_G-V_T)^2}$\n\\end{flushright}\n\\textbf{MOSFET Integrated Circuit Applications} \\hfill \\break \n$V_T=V_{FB}+2|\\phi_p|+\\cfrac{Q_{d(max)}}{\\epsilon_{ox}}(d_1+d_2)+\\cfrac{Q_{fg}}{\\epsilon_{ox}}d_1$ \nCharge stored on a floating gate memory cell\n\n$|Q_{fg}|=\\frac{\\epsilon_{ox}}{d_1}\\left[V_T-V_{FB}-2\\phi_P-\\frac{Q_{d(max)}}{\\epsilon_{ox}}(d_1+d_2)\\right]$, $Q_{fg}=$ Floating Gate Charge Density $V_{FB}=\\phi_{MS}$\n\nStep 1: Find $V_{bi}$ (n-well to source/drain junction) using $N_d$ from, the n-well and $N_a$ from the p-channel source/drain.\n\\vspace*{-0.4cm}\n\\begin{flushright}\nStep 2: Find $x_d$ using the doping levels and $V_{bi}$. \\break \nStep 3: Find $V_{bi}$ (n-well to p-substrate junction) using $N_d$ from the n-well and $N_a$ from the p-substrate. \\break \nStep 4: Find $x_n$ using $V_{bi}$ and $V_a=V_{DD}$, and the same doping level as step 3. \\break \nStep 5: The minimum required n-well depth to prevent punchthrough at this voltage is: $d_{n-well}=d_{p-channel src/drn}+x_{d(step 2)}+ x_{n(step 4)}$\n\\end{flushright}\n$V_{bi}=\\frac{k_BT}{q}\\ln\\left(\\frac{N_dN_a}{n_i^2}\\right)$ \\hfill \\break \n$x_d=x_n+x_p=\\left[\\frac{2\\epsilon_s}{q} \\left(\\frac{1}{N_a}+\\frac{1}{N_d}\\right)(V_a-V_{bi})\\right]^{1/2}$, \\hfill \\break \n$x_n= \\left\\{\\frac{2K_s\\epsilon_0}{q}(V_{bi}+V_a)\\left[\\frac{N_a}{N_d(N_a+N_d)}\\right]\\right\\}^{1/2}$\nNote: The p-channel source/drain depth $d_{p-channel src/drn}$ should be given in the question. \n\nCMOS Well-Depth Design: Finding minimum well\ndepth to prevent vertical punch through.\n\n\n\\textbf{CMOS Structures}\nP-Well: The substrate is N-Type. The N-Channel device is built into a P-Type well within the parent N-Type substrate.\nThe P-channel device is built directly on the substrate. \n\nN-Well: The substrate is P-Type. The N-channel device is built directly on the substrate, while the P-channel device is\nbuilt into a N-type well within the parent P-Type substrate. \n\n$g_d=\\frac{Z\\bar{\\mu}_n C_o}{L}(V_G-V_T) \\ \\ (V_D=0)$\n\n\\textbf{Practise Test 2}\n1) Which of the following can reduce the base transit time? c) Short base width.\n\n2) Design the doping levels and dimensions of a silicon npn bipolar transistor such that the dc current gain is 320 and the Gummel Number is $10^{12} \\text{cm}^{-2}$. Assume that $\\tau_n=10^{-7} s$ in the base, $\\tau_p=10^{-8}s$ in the collector.\n\n$GN = Q_B = \\int_0^{x_B}N_{aB} (x) dx$. \n\n$\\phi(S) = 4.05 - (4.05+E_g/2+E_f-E_i)$\n\\end{multicols}\n\\newpage\n\n% Get figures Vol IV. Pg 73, Iv p 43\n\\begin{multicols}{2}\n%\\begin{minipage}{\\linewidth}\n%\\centering\n%\\raisebox{-.8in}{\n%\\includegraphics[width=1\\linewidth]{DiffusionCoefficientChart.png}}\n%\\hspace{1em}\n%\\parbox[c]{4in}{\\captionof{figure}{Diffusion Chart from Lecture I},\n%\\label{fig:pictureonright}}\n%\\end{minipage}\n\n\\begin{minipage}{\\linewidth}\n\\centering\n\\raisebox{-.8in}{\n\\includegraphics[width=1\\linewidth]{MOSFETTable.png}}\n\\hspace{1em}\n\\parbox[c]{4in}{\\captionof{figure}{Vol IV Mosfet table},\n\\label{fig:pictureonright}}\n\\end{minipage}\n\\begin{minipage}{\\linewidth}\n\\centering\n\\raisebox{-.8in}{\n\\includegraphics[width=1\\linewidth]{MOSFETgraphdopants.PNG}}\n\\hspace{1em}\n\\parbox[c]{4in}{\\captionof{figure}{Doping dependence of the maximum equilibrium depletion width inside silicon devices maintained at 300 K.},\n\\label{fig:pictureonright}}\n\\end{minipage}\n\n\\begin{minipage}{\\linewidth}\n\t\\centering\n\t\\raisebox{-.8in}{\n\t\t\\includegraphics[width=1\\linewidth]{NeamanTable12-1.png}}\n\t\\hspace{1em}\n\t%\\parbox[c]{4in}{\\captionof{figure}{Resistivity Plot},\n\t\\label{fig:pictureonrigh8194}\n\\end{minipage}\n\\begin{minipage}{\\linewidth}\n\\centering\n\\raisebox{-.8in}{\n\\includegraphics[width=0.6\\linewidth]{MOSFETgraphVd_0.PNG}}\n\\hspace{1em}\n\\parbox[c]{4in}{\\captionof{figure}{Vol IV Mosfet Gate voltages},\n\\label{fig:pictureonright}}\n\\end{minipage}\n\n\\begin{minipage}{\\linewidth}\n\t\\centering\n\t\\raisebox{-.8in}{\n\t\t\\includegraphics[width=1\\linewidth]{Fig43VolIV.png}}\n\t\\hspace{1em}\n\t\\parbox[c]{4in}{\\captionof{figure}{Workfunction difference as a function of a n- and p-type dopant conecntration in $n^+$ poly-Si-gate and Al-gate $SiO_2-Si$ structures. ($T=300 K$. $\\phi_M^\\prime-\\chi^\\prime=-0.18 \\ eV$ for the $n^\\prime$ poly-Si-gate structure; $\\phi_M^\\prime-\\chi^\\prime=0.03 eV$ for the Al-gate structure.)},\n\t\t\\label{fig:pictureonright78}}\n\\end{minipage}\n\\begin{minipage}{\\linewidth}\n\t\\centering\n\t\\raisebox{-.8in}{\n\t\t\\includegraphics[width=0.7\\linewidth]{GroupIIIGroupV.png}}\n\t%\\hspace{1em}\n%\t\\parbox[c]{4in}{\\captionof{figure}{Boron Diffusion Chart},\n\t\t\\label{fig:59}\n\\end{minipage}\n\n\\begin{minipage}{\\linewidth}\n\t\\centering\n\t\\raisebox{-.8in}{\n\t\t\\includegraphics[width=0.7\\linewidth]{boronChart.png}}\n\t\\hspace{1em}\n\t\\parbox[c]{4in}{\\captionof{figure}{Boron Chart},\n\t\t\\label{fig:4}}\n\\end{minipage}\n\\end{multicols}\n\\begin{minipage}{\\linewidth}\n\t\\centering\n\t\\raisebox{-.8in}{\n\t\t\\includegraphics[height=1\\textheight]{V1Figure3-5.png}}\n% \t\\hspace{1em}\n% \t\\parbox[c]{4in}{\\captionof{figure}{Diffussion Constant},\n% \t\t\\label{fig:pictureonright79}}\n\\end{minipage}\n\n\\begin{minipage}{\\linewidth}\n\t\\centering\n\t\\raisebox{-.8in}{\n\t\t\\includegraphics[width=1\\textheight]{VIFigure3-7.png}}\n\t\\hspace{1em}\n\t%\\parbox[c]{4in}{\\captionof{figure}{Resistivity Plot},\n\t\t\\label{fig:pictureonrigh819}\n\\end{minipage}", "meta": {"hexsha": "912631c2f0859a0125ca01fb3da4374f4b248d76", "size": 16692, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "public/CheatSheets/elec320Final.tex", "max_stars_repo_name": "FriendlyUser/PortfolioWebsite", "max_stars_repo_head_hexsha": "82843816c07239c457d2d820bb50577333a75855", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "public/CheatSheets/elec320Final.tex", "max_issues_repo_name": "FriendlyUser/PortfolioWebsite", "max_issues_repo_head_hexsha": "82843816c07239c457d2d820bb50577333a75855", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "public/CheatSheets/elec320Final.tex", "max_forks_repo_name": "FriendlyUser/PortfolioWebsite", "max_forks_repo_head_hexsha": "82843816c07239c457d2d820bb50577333a75855", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.6785714286, "max_line_length": 330, "alphanum_fraction": 0.6749341002, "num_tokens": 6553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3264295192838106}}
{"text": "\n\\documentclass[conference]{IEEEtran}\n\n\\usepackage{graphicx}\n\\usepackage{float}\n\\usepackage[ruled,vlined,linesnumbered,noresetcount]{algorithm2e}\n\\usepackage{amsmath}\n\\usepackage{booktabs}\n%\\usepackage[options ]{algorithm2e}\n% correct bad hyphenation here\n\\hyphenation{op-tical net-works semi-conduc-tor}\n\n\n\\begin{document}\n\n\\title{A Novel Heuristic for Evolutionary Clustering}\n\n\n% author names and affiliations\n% use a multiple column layout for up to three different\n% affiliations\n\n\n\n\n\n% make the title area\n\\maketitle\n\n% As a general rule, do not put math, special symbols or citations\n% in the abstract\n\\begin{abstract}\nClustering is considered a challenging problem of data mining due to its unsupervised nature. The literature is inundated with algorithms and concepts related to determining the most suitable clustering structure in data. These techniques have a mathematical model of a cluster and attempt to obtain a result that shall represent this model as closely as possible. However as the problem of clustering is NP hard such strategies have disadvantages such as converging to local optima or suffering from the curse of dimensionality. In such scenario, meta heuristics could be more suitable strategies. Such techniques utilizes biologically inspired techniques such as swarm intelligence, evolution etc. to traverse the search space. Due to their inherent parallel nature, they are most robust towards converging to a local optima. The objective (cost) function used by such meta heuristics is responsible for guiding the agents of the swarm towards the best solution. Hence it should be designed to achieve trade-off between multiple objectives and constraints and at the same time produce relevant clustering. In this paper, a cost function is proposed (PSO-2) to produce compact well separated clusters by using the concept of intracluster and intercluster distances. Experiments have been performed on artificial benchmark datasets where performance of the particle swarm optimizer using the proposed cost function is evaluated against other evolutionary and non evolutionary algorithms. The clustering structures produced by the  methods have been evaluated using distance based and internal cluster validation metrics to demonstrate that the performance of PSO-2 is comparable to other techniques.  \\\\\n\\end{abstract}\n\n% no keywords\n\\begin{IEEEkeywords}Data clustering, Applications of evolutionary algorithms, Genetic\nalgorithm.    \n\\end{IEEEkeywords}\n\n\n\n% For peer review papers, you can put extra information on the cover\n% page as needed:\n% \\ifCLASSOPTIONpeerreview\n% \\begin{center} \\bfseries EDICS Category: 3-BBND \\end{center}\n% \\fi\n%\n% For peerreview papers, this IEEEtran command inserts a page break and\n% creates the second title. It will be ignored for other modes.\n\\IEEEpeerreviewmaketitle\n\n\n\n\\section{Introduction}\n% no \\IEEEPARstart\nClustering involves creating coarse grained descriptions of data. This is done with the main purpose of highlighting a set of autonomous regions in the data known as clusters. Clustering has found wide applicability in multiple fields ranging from web mining and information retrieval through customer segmentation and bio-informatics \\cite{hur}. Regardless of the domain to which it is applied or the algorithm used, the goal of clustering is uniform i.e. to maximize homogeneity within cluster and heterogeneity between clusters \\cite{cha}. Clustering algorithms produce partitions of data which may be hard (nodes have unique memberships to clusters), soft (nodes have memberships to multiple clusters) or fuzzy (nodes have varying degrees of memberships to every cluster). Thus, a hard partition of a dataset X = ${x_1, x_2, x_3, x_4 ... x_n}$ where $x_i$ is a data point which stands for a n-dimensional feature vector, is a collection $C = {C_1, C_2, ... , C_k}$ of non null clusters such that $C_i \\cap C_j = \\phi$ for $ i \\neq j$. Relaxing the mutual dis-junction condition to allow $C_i \\cap C_j \\neq \\phi$ for $ i \\neq j$ creates overlapping partitions \\cite{ma}. \\\\\n\nClustering is considered the most challenging task of machine learning due to the unavailability of spatial distribution of the data in terms of its clustering tendency \\cite{hur} \\cite{cha} \\cite{ma}. Furthermore, the requirement of dealing with various types of attributes (binary, categorical, continuous, discrete), their conditions (complete or missing) and scales (nominal, ratio, interval, ordinal) has to be factored in while deciding the approach of clustering.  In addition to this, the lack of information about the orientation of the clusters, their numbers, shapes, densities and volumes makes it difficult in selecting a particular clustering technique and in evaluating the results obtained by it \\cite{val1} \\cite{val2}. From the optimization perspective, Clustering is considered as a NP-hard grouping problem and the literature consists of a wide range of objective functions, approximation algorithms and heuristics for solving it \\cite{hur}.\\\\\n\nEach approach has its own bias and comes with certain advantages and disadvantages to a given analysis or application scenario. Popular partition based clustering algorithms are K-means, PAM, CLARA, CLARANS. These algorithms have a objective function which is non-convex and hence the results might be locally optimal. Hierarchical algorithms too exist like AGNES, DIANA, BIRCH, ROCK and CHAMALEON etc. but these are computationally expensive. One inherent weakness of hierarchical clustering is that clusters formed in an iteration cannot be undone in subsequent iterations. DBSCAN, OPTICS are approaches that define clusters as dense regions separated by less dense regions. DBSCAN though is popular but the prior specification on $\\epsilon$ and $MinPts$ makes it sensitive to parameter tuning. In real life experiments, various types of noise are introduced at different experimental stages during data collection, due to which the performance of these algorithms are less than ideal \\cite{hur} \\cite{ma}. To effectively handle noisy data, we need an algorithm that is able to overcome noise. These traditional algorithms are based on gradient based methods and are difficulty to extend to multi-objective problems as their basic design doesn't allow the consideration of multiple solutions \\cite{zha} \\cite{luo}. Population based methods such as evolutionary algorithms have an inherent advantage here \\cite{muk} \\cite{muktwo}.\\\\\n\nIn the context of solving NP-hard optimization problems, evolutionary algorithms are considered to be particularly effective in obtaining near optimal solutions in reasonable time \\cite{lih} \\cite{sid}. Evolutionary algorithms are meta-heuristics based on optimization of a fitness function that guides the process of evolutionary search. Computational advantages are also present as the algorithms can be parallelized leading to increased coverage and possibly faster convergence \\cite{lin}. However, evolutionary algorithms have their owns drawbacks as different features of these algorithms have to chosen in advance such as encoding scheme for the data points, choice of operators for crossover and mutation and a fitness (cost) function. Fitness functions are basically validity criteria and hence it is better to use multiple criteria in order to avoid the drawbacks of individual ones. One strategy for this is to assign weights to individual criteria and then optimize, but this approach only works when the multiple criteria are commensurable. In this paper, the fitness function proposed computes cost using a variation of intra cluster distance and inter cluster distance. This variation allows computation to be performed in linear time. The conventional definitions of these distances requires $O(n^2)$ computations. Hence a reduction in computations is achieved leading to faster execution.\\\\\n\n\n\nThe rest of this paper is organized as follows. In Section II, an overview of the existing clustering algorithms used\nfor identification of clusters in data is presented, these include both evolutionary and non evolutionary approaches. In Section III, the mathematical model of the proposed evolutionary algorithm and its intuition is described. In Section IV, the algorithm is evaluated and compared with existing clustering algorithms using benchmark artificial datasets. Experimental results are presented to highlight the suitability of the proposed technique. Section V consists of the summary of the work along with the conclusion. \\\\\n      \n\n\\section{Related Work}\nClustering algorithms follow evolutionary and non evolutionary strategies and a selection of the best known algorithms \\cite{ma} of both categories are described below.\\\\\n\\subsection{Traditional Clustering Algorithms}\n\nClustering techniques belonging to the k-partitioning family minimize the objective criterion known as variance or sum of squared distances $SSD = \\sum_{k=1}^{k} \\sum_{x_i \\epsilon c_k} \\left \\| x_i - c_k \\right \\| ^2$ and hence the detected clustering structures correspond to minimum variance. K-Means is the popular algorithm of this category with a time complexity of $O(kN)$ and hence is scalable. Hierarchical clustering algorithms have a fully unsupervised approach but time complexity is     higher i.e. $O(n^3)$ and $O(n^2 log n)$ for priority queue implementations. This makes scalability an issue on larger datasets. Model based clustering algorithms assume that clusters are generated by probability distributions whose parameters such as mean and covariance matrix have to be estimated using maximum likelihood estimation. Eqn. 1 is the prior probability that denotes the percentage of instances that came from a cluster $c$. Eqn. 2 gives the mean i.e. expected value of attribute $j$ from cluster $c$. Eqn. 3 gives the covariance matrix denoting the covariance of attributes $j,k$ in cluster $c$.\n\n\n\\begin{equation}\nP(c)= \\frac{1}{n} \\sum_{i=1}^{n} P(c\\vert\\vec{x_i})\n\\end{equation}\n\\begin{equation}\n\\mu_{c,j} = \\sum_{i=1}^{n} \\Bigl(\\frac{P(c\\vert\\vec{x_i})}{nP(c)}\\Bigr)x_{i,j}\n\\end{equation}\n\\begin{equation}\n\\sum_{c}{\\mathstrut}_{j,k} = \\sum_{i=1}^{n}\\Bigl(\\frac{P(c\\vert\\vec{x_i})}{nP(c)}\\Bigr)(x_{i,j} - \\mu_{c,j})(x_{i,k} - \\mu_{c,k})\n\\end{equation}\n\\begin{equation}\n P(c\\vert\\vec{x_i}) = \\frac{P(\\vec{x_i}\\vert c)P(c))}{\\sum_{i=1}^{k}P(\\vec{x_i}\\vert c)P(c)}\n \\end{equation}\n \\begin{equation}\nP(\\vec{x_i}|c) = \\frac{1}{\\sqrt{2\\pi\\sum_{c}}} \\exp\\Bigl(- \\frac{1}{2}(\\vec{x_i} - \\vec{\\mu_c})^T \\sum_{c}^{-1}(\\vec{x_i} - \\vec{\\mu_c})\\Bigr)\n\\end{equation}\n\\vspace{10px}\n\n\\subsection{Neural Network Based Clustering}\nUnsupervised learning using neural networks has two main models which are Kohenon's Self Organizing Maps and Grossberg's Adaptive Resonance Theory. ART represents a family of neural networks in which the current input vector is matched to the category prototype vector. If the input vector doesn't match with the prototype then a new prototype is selected. This means that other prototypes are not affected by new input. In ART systems, there are two layers: $L1$ has the comparison field where input patterns and expectations are compared. Layer 2 $L2$ is the competition layer where winner takes all learning strategy is implemented. Connections from Layer 1 to Layer 2 perform clustering operations and each row of weights is a prototype pattern. Layer 2 to Layer 1 connections perform pattern recall (expectation). The vigilance parameter is a user defined gain control mechanism that controls the degree of similarity required for patterns to be assigned to the same cluster. \\\\\n\nKohenon's Self Organizing Map are neural networks that map their weights (without any target vector) to conform to the given input data with the goal of representing multidimensional data in a lower dimension. SOM's have a two layered architecture with input nodes connected to every computational nodes to form a lattice pattern. Weight vectors $W_{ij} = W_{ij1}, W_{ij2}, ... , W_{ijn}$ are of the same dimensions as the input vectors $V$. The SOM algorithm has following steps:\\\\\n\n\\begin{itemize}\n\\item Each nodes weights are initialised randomly.\n\\item A vector is chosen at random from the set of input vectors and presented to the training data.\n\\item Every nodes is compared to the input pattern to determine which nodes weights are closest to the input pattern. This winning node is the Best Matching Unit (codebook vector). Closeness measure is euclidean distance.\n\\item Once the BMU is identified, codebook vectors in the neighbourhood of the BMU are updated. The update rule for the codebook vectors in the neighbourhood is given in Eqn.6 is the BMU, $h_{ci}$ is a non increasing neighbourhood function.\n\\item The neighbourhood function is given in Eqn. 7\\\\  \n\\end{itemize}\n\nWhere,\n\\begin{equation}\nm_i(t+1) = m_i(t) + h_{ci}(t)[x(t) - m_i(t)]\n\\end{equation}\n\\begin{equation}\nh_{ci}(t) = \\alpha(t) . exp(- \\frac{||r_i - r_c||^2}{2 \\sigma(t)^2})\n\\end{equation}\n\n\n\\subsection{Evolutionary Clustering Algorithms}\nParticle swarm optimization is an intelligent optimization algorithm which belongs to a class of optimization algorithms called Meta Heuristics. It is based on the paradigm of \"swarm intelligence\" and is inspired by social behavioral animals like birds or fish proposed by J. Kennedy \\textit{et al} in 2007 and modified in 2011 by M. Clerc \\textit{et al} \\cite{pso}\\cite{pso1}\\cite{pso2}. Swarm intelligence systems have simple agents that interact locally with each other and with the environment (without any central control as to how individual agents should behave). Local interaction between the agents however lead to emergence of a complex global behavior. In PSO, solutions are assumed as points in an n-dimensional space. The swarm particles $\\overrightarrow{x_i}$ are solutions that are randomly initialized in the search space $X$ and these have to traverse it in search of the global optima with a velocity $v_i$. \\\\\n\nDifferential evolution \\cite{da} is a stochastic direct search method that minimizes the objective (cost) function  by using the difference of solution vectors to create new candidate solutions. NP D-dimensional parameter vectors $x_{i,G} i = 1, 2, ..., NP$ are used as a population for each generation $G$. DE generates new parameter\nvectors by adding the weighted difference between two population vectors to a\nthird vector. The parameters of this new vector also called the \"mutated vector\" are mixed with the parameters of another predetermined vector, the target\nvector, to obtain the \"trial vector\". If the\ntrial vector results in a lower cost than the target vector it\nreplaces the target vector in the subsequent generation. At every stage of the process each population vector has to serve once as the target vector so that NP\ncompetitions take place in one generation. \\\\\n\nGenetic algorithms are a class of computational models inspired by biological evolution and selection. The mechanism followed by these models is to encode a potential solution to a problem on a chromosome like data structure and apply recombination operators to preserve critical information. Problem dependent parts are selection of suitable objective function and problem encoding. The optimization problems are often non linear and so it is not possible to treat each parameter as an independent variable which can be solved in isolation from others \\cite{ga}. \n\n\\section{Mathematical Model}\n   \nThe mathematical model of a meta heuristic algorithm has structured sections with each section having a logical meaning. The sections in the meta heuristic in this section are Problem definition, Parameters definition, Initialization and the Iterative procedure. The meta heuristic follows the same structure as the standard PSO implemented in \\cite{pso1} \\cite{pso2}.\n\n\\subsection{Problem Definition}\n\n\\subsubsection{Cost Function} \nThe key component of the problem definition is the cost function which is to be optimized using the meta-heuristics. The aim is to achieve clusters well separated and compact. This is done using two distances $WCD$ and $ICD$. \n\n\\begin{equation}\nWCD = \\sum_{i = 1}^{n} \\text{dist}(c_i , C)\n\\end{equation}\n\\begin{equation}\nICD = \\sum_{j = 1}^{k} \\sum_{i = 1}^{n}\\text{dist}(c_i , C_j)\n\\end{equation}\nThus $WCD$ is the distance of a point from its centroid summing over all points. $ICD$ is the distance of point from other centroids summing over all points. $WCD$ is to be minimised and $ICD$ maximized, and this is the objective of PSO-2. To achieve efficiency the cost to be minimized is taken as $\\frac{WCD}{ICD}$.\\\\\n\n\n\\begin{algorithm}\n\\SetAlgoLined\n\\KwResult{Cost of the cluster: z}\n m = coordinates of centroids\\;\n X = coordinates of data points\\;\n M = Calculate distance of each point from all centroids\\;\n ind = Assign point to centroid closest to it\\;\n WCD = Add distances of all points to assigned to a centroid\\;\n ICD = M - WCD\\;\n z = WCD / ICD\\;\n \\caption{Cost function: PSO-2}\n\\end{algorithm}\n\nThe dissimilarity matrix isn't required to be calculated and the computations for $WCD$ , $ICD$ are completed in $O(n)$ computations.\\\\\n\n\n\n\\subsubsection{Decision Variables} \nThe decision variables are the $k$ centroids of the data, where each centroid can be represented as a $n$ dimensional vector $\\overrightarrow{R^n}$. Thus the total decision variables are $n * k$. The range of the decision variables is limited to be between the maximum $VarMax$ and minimum value $VarMin$ of the points in the data, this also achieves the objective of restricting the search space. \n\n\\subsection{Parameters of Meta heuristics}\nThe parameters of the meta heuristics are maximum iterations allowed for the model, the size of the swarm, coefficients of inertia $w$ and its damping ratio $w_{damp}$ , personal acceleration coefficient $c_1$ (assigned to every particle) and the social acceleration coefficient $c_2$ (assigned to the entire swarm). In addition, limits are set to restrict the velocities of individual particles to the range $VelMin$ to $VelMax$. Constrictions coefficients $phi_1$, $phi_2$, $phi$, $chi$ are also defined as per the Eqn.\\ref{eq:1} and Eqn.\\ref{eq:2}. The values for these variables are set according to standard settings which may be modified. \n\n\\begin{equation}\\label{eq:1}\nphi = phi_1 + phi_2 \n\\end{equation}\\label{eq:2}\n\\begin{equation}\nchi = \\frac{2}{phi - 2 + \\sqrt{phi^2 - 4*phi}}\n\\end{equation}\n\\begin{equation}\nw = chi\n\\end{equation}\n\\begin{equation}\nc_1 = phi_1 * chi\n\\end{equation}\n\\begin{equation}\nc_2 = phi_2 * chi\n\\end{equation}\n\n\\subsection{Initialization and the Iterative Procedure}\n\nEach particle in the swarm has the components such as position $x_{pos}$, velocity $x_{vel}$, cost $x_{cost}$, best position $x_{pbest}$ and best cost $x_{cbest}$. The Global best $x_{gbest}$ is also defined to be $- \\infty$ as the objective function is to be maximized. The positions of the particles are initialized using uniform distribution between $VarMax$ and $VarMin$. The velocities of the particles is initialized to zero. The values for the best position of a particle and the cost at the best position is currently set to the initial position and the cost at the initial position respectively. \\\\\n\nThe iterative procedure updates the values for the best position and best cost obtained so far by each particle in the swarm and also update the variable that records the global best cost and position obtained by the swarm together. The update rule for the particle velocity is given by Eqn. \\ref{eq:3}\\\\\n\n  \\begin{equation}\\label{eq:3}\n   x_{i+1}(vel) = w * x_{i}(vel) + c_1 * (x_{pbest} - x_{pos}) + c_2 * (x_{gbest} - x_{pos})\\\\\n  \\end{equation}\n  \nThe velocity limits are applied as in Eqn: \\ref{eq:4} and \\ref{eq:5} to prevent the particle velocity from increasing or decreasing beyond the thresholds.\n  \n  \\begin{equation}\\label{eq:4}\n  x_{i+1}(vel) = max(x_{i+1}(vel), VelMin)\n  \\end{equation}\n   \\begin{equation}\\label{eq:5}\n  x_{i+1}(vel) = min(x_{i+1}(vel), VelMax)  \n  \\end{equation}\n  \n The position of the particle is updated by the Eqn \\ref{eq:6}\n   \\begin{equation}\\label{eq:6}\n  x_{i+1}(pos) = x_{i}(pos) * x_{i+1}(vel)\n  \\end{equation}\n  \n  If the position of the particle is outside the thresholds $VarMax, VarMin$ it is updated by the rule in Eqn: \\ref{eq:7} and \\ref{eq:8}\n  \n    \\begin{equation}\\label{eq:7}\n  x_{i+1}(pos) = max(x_{i+1}(pos), VarMin)\n  \\end{equation}\n   \\begin{equation}\\label{eq:8}\n  x_{i+1}(pos) = min(x_{i+1}(pos), VarMax)  \n  \\end{equation}\n  \nIf the cost of the particle at its new position is better than the cost of the particle at its old position, then the values of personal best cost $x_{cbest}$ and position $x_{pbest}$ so far of the particle are updated to the new values. The values of the global best cost and position of the entire swarm is updated at every iteration to store the best global value at every iteration.\n\n \n\\section{Experiments}\n\nThe efficiency of the objective function proposed in this paper is demonstrated vis-a-vis other evolutionary and non evolutionary algorithms on artificial clustering datasets. Standard internal cluster validation metrics such as Separation index $S_i$, Calinski and Harabasz index $CH_i$, Entropy of the distribution of cluster memberships $E$, Pearson Gamma index $P$ and Dunn index $D$ along with distance based statistics such as Within cluster sum of squared distances $M_{wcd}$, Average distance between clusters $M_{avg-CD}$ and Average silhouette width $S_w$  are used to evaluate \\cite{val1} \\cite{val2}.\n\n\\subsection{Dataset}\nThe artificial benchmarks used for the experiment are given below:\n\n\\begin{table}[h!]\n\\renewcommand{\\arraystretch}{1.3}\n\\caption{Description of the datasets}\n\\label{table}\n\\centering\n\\begin{tabular}{|c|c|c|}\n  \\hline\n\\multicolumn{1}{|c|}{\\textbf{Sr. No}} & \\multicolumn{1}{c|}{\\textbf{Name}} & \\multicolumn{1}{c|}{\\textbf{Size}} \\\\\n  \\hline\n  1 & Banana &  4811 \\\\\n   \\hline\n  2 & Cluto &  8000 \\\\\n   \\hline\n  3 & Cure &  4200 \\\\\n   \\hline\n  4 & Long &  1261 \\\\\n   \\hline\n  5 & 2d-4c &  1000 \\\\\n   \\hline\n  6 & Demo &  300 \\\\\n   \\hline\n\\end{tabular}\n\\end{table}\n\n\n\\subsection{Results}\n\n\\subsubsection{Distance based Statistics}\n\nThe within-cluster sum of squares is a measure of the variability of the observations within each cluster. Clusters that have higher values exhibit greater variability of the observations within the cluster. The results of PSO-2 are comparable to other clustering algorithms as seen in Table \\ref{mwcd}.\n\n\\begin{table}[H]\n\\caption{Within cluster sum of squares}\n\\label{mwcd}\n\\centering\n\\begin{tabular}{||c|c|c|c|c|c|c||}\n  \\hline\n\\multicolumn{1}{|c|}{\\textbf{Name}} & \\multicolumn{1}{c|}{\\textbf{Banana}} & \\multicolumn{1}{c|}{\\textbf{Cluto}} & \\multicolumn{1}{c|}{\\textbf{Cure}} & \\multicolumn{1}{c|}{\\textbf{Long}} & \\multicolumn{1}{c|}{\\textbf{2d-4c}} & \\multicolumn{1}{c|}{\\textbf{Demo}}\\\\\n  \\hline\\hline\n  KMeans & 185.20 & 3.42 & 383.25 & 637.02 & 20434.32 & 593.39 \\\\ [0.5ex]\n   \\hline\n  PAM & 192.88 & 3.42 & 402.30 & 666.56 & 20434.32 & 593.39 \\\\\n   \\hline\n  ART2 & 190.09 & 37.78 & 1712.27 & 594.87 & 1127417 & 996.77 \\\\\n   \\hline\n  DE & 185.21 & 3.94 & 385.31 & 637.53\n & 20434.32 & 593.39 \\\\\n   \\hline\n  PSO & 185.21 & 3.43 & 383.36 & 637.53 & 20434.32 & 593.39 \\\\\n   \\hline\n  GA & 185.21 & 3.42 & 383.41 & 637.52 & 20434.32 & 593.39 \\\\\n   \\hline\n  \\textbf{PSO-2} & 193.23 & 3.98 & 403.29 & 1051.73 &  94470.4 & \\textbf{593.38} \\\\  [1ex]\n  \\hline\n\\end{tabular}\n\\end{table}\n\n\n\nAverage distance between clusters should be large as this would mean that the clusters are well separated. Table \\ref{wcad} shows the that PSO-2 produces well separated clusters comparable to other algorithms.\n\n\\begin{table}[H]\n\\caption{Average distance between clusters}\n\\label{wcad}\n\\centering\n\\begin{tabular}{||c|c|c|c|c|c|c||}\n  \\hline\n\\multicolumn{1}{|c|}{\\textbf{Name}} & \\multicolumn{1}{c|}{\\textbf{Banana}} & \\multicolumn{1}{c|}{\\textbf{Cluto}} & \\multicolumn{1}{c|}{\\textbf{Cure}} & \\multicolumn{1}{c|}{\\textbf{Long}} & \\multicolumn{1}{c|}{\\textbf{2d-4c}} & \\multicolumn{1}{c|}{\\textbf{Demo}}\\\\\n \\hline\\hline\n  KMeans & 0.49 & 300.36 & 1.22 & 1.84 & 62.26 & 5.38 \\\\ [0.5ex]\n   \\hline\n  PAM & 0.50 & 300.35 & 1.22 & 1.85 & 62.26 & 5.37 \\\\\n   \\hline\n  ART2 & 0.5 & NaN & 1.18 & 1.72 & \\textbf{74.44} & 4.92 \\\\\n   \\hline\n  DE & 0.49 & 301.83 & 1.22 & 1.85 & 62.26 & 5.37 \\\\\n   \\hline\n  PSO & 0.49 & 300.36 & 1.22 & 1.85 & 62.26 & 5.37 \\\\\n   \\hline\n  GA & 0.49 & 300.36 & 1.22 & 1.85 & 62.26 & 5.37 \\\\\n   \\hline\n  \\textbf{PSO-2} & 0.50 & \\textbf{303.46} & \\textbf{1.22} &  \\textbf{2.26} & 66.9 & 5.37 \\\\  [1ex]\n  \\hline\n\\end{tabular}\n\\end{table}\n\nSilhouette value is a measure of how similar an object is to its own cluster compared to other clusters. The silhouette ranges from −1 to +1, where a high value indicates that the object is well matched to its own cluster and poorly matched to neighboring clusters. Clusters produced by PSO-2 have moderate scores of silhoutte width compared to other algorithms as seen in Table \\ref{asw}. \n\n\\begin{table}[H]\n\\caption{Average silhouette width}\n\\label{asw}\n\\centering\n\\begin{tabular}{||c|c|c|c|c|c|c||}\n  \\hline\n\\multicolumn{1}{|c|}{\\textbf{Name}} & \\multicolumn{1}{c|}{\\textbf{Banana}} & \\multicolumn{1}{c|}{\\textbf{Cluto}} & \\multicolumn{1}{c|}{\\textbf{Cure}} & \\multicolumn{1}{c|}{\\textbf{Long}} & \\multicolumn{1}{c|}{\\textbf{2d-4c}} & \\multicolumn{1}{c|}{\\textbf{Demo}}\\\\\n  \\hline\\hline\n  KMeans & 0.46 & 0.43 & 0.48 & 0.43 & 0.87 & 0.61 \\\\ [0.5ex]\n   \\hline\n  PAM & 0.47 & 0.43 & 0.45 & 0.42 & 0.87 & 0.61 \\\\\n   \\hline\n  ART2 & 0.47 & NULL & 0.08 & 0.33 & 0.56 & 0.33 \\\\\n   \\hline\n  DE & 0.46 & 0.41 & 0.48 & 0.43 & 0.87 & 0.61 \\\\\n   \\hline\n  PSO & 0.46 & 0.43 & 0.48 & 0.43 & 0.87 & 0.61 \\\\\n   \\hline\n  GA & 0.46 & 0.43 & 0.48 & 0.43 & 0.87 & 0.61\n \\\\\n   \\hline\n  \\textbf{PSO-2} &  \\textbf{0.47} & 0.41 &  0.44 & 0.36 & 0.86 & 0.61 \\\\  [1ex]\n  \\hline\n\\end{tabular}\n\\end{table}\n\n\\subsubsection{Internal Cluster Validation Metrics}\n\nSeparation index is computed on the distances for every point to the closest point not in the same cluster. The separation index is then the mean of the smallest proportion of these. Larger value of separation index indicates better clustering and PSO-2 has exceeded baseline SI set by other algorithms on two datasets as seen in Table \\ref{si}.\n\n\\begin{table}[H]\n\\caption{Separation Index}\n\\label{si}\n\\centering\n\\begin{tabular}{||c|c|c|c|c|c|c||}\n  \\hline\n\\multicolumn{1}{|c|}{\\textbf{Name}} & \\multicolumn{1}{c|}{\\textbf{Banana}} & \\multicolumn{1}{c|}{\\textbf{Cluto}} & \\multicolumn{1}{c|}{\\textbf{Cure}} & \\multicolumn{1}{c|}{\\textbf{Long}} & \\multicolumn{1}{c|}{\\textbf{2d-4c}} & \\multicolumn{1}{c|}{\\textbf{Demo}}\\\\\n  \\hline\\hline\n  KMeans & 0.03 & 9.27 & 0.04 & 0.1 & 15.68 & 0.85 \\\\ [0.5ex]\n   \\hline\n  PAM & 0.03 & 8.79 & 0.04 & 0.10 & 15.68 & 0.85 \\\\\n   \\hline\n  ART2 & 0.02  & Inf & 0.04 & 0.06 & 50.92 & 0.27 \\\\\n   \\hline\n  DE & 0.03 & 7.87 & 0.04 & 0.12 & 15.68 & 0.85 \\\\\n   \\hline\n  PSO & 0.03 & 8.66 & 0.04 & 0.12 & 15.68 & 0.85 \\\\\n   \\hline\n  GA & 0.03 & 8.59 & 0.04 & 0.12 & 15.68 & 0.85 \\\\\n   \\hline\n  \\textbf{PSO-2} & 0.02 & 8.45 &  0.03 & \\textbf{0.21} & 43.43 &  \\textbf{0.85}\\\\  [1ex]\n  \\hline\n\\end{tabular}\n\\end{table}\n\nAlthough a higher value of CH index as seen in Table \\ref{chin} is considered a better result, CH criterion is preferred where clusters are spherical. CH index value obtained by PSO-2 is comparable to other algorithms.\n\n\\begin{table}[H]\n\\caption{Calinski and Harabasz index}\n\\label{chin}\n\\centering\n\\begin{tabular}{||c|c|c|c|c|c|c||}\n  \\hline\n\\multicolumn{1}{|c|}{\\textbf{Name}} & \\multicolumn{1}{c|}{\\textbf{Banana}} & \\multicolumn{1}{c|}{\\textbf{Cluto}} & \\multicolumn{1}{c|}{\\textbf{Cure}} & \\multicolumn{1}{c|}{\\textbf{Long}} & \\multicolumn{1}{c|}{\\textbf{2d-4c}} & \\multicolumn{1}{c|}{\\textbf{Demo}}\\\\\n  \\hline\\hline\n  KMeans & 5689.28 & 11473.7 & 5683.4 & 1092.8 & 36113.1 & 679.9 \\\\ [0.5ex]\n   \\hline\n  PAM & 5271.64 & 11447.1 & 5374.5 & 1000.1 & 36113.1 & 679.9 \\\\\n   \\hline\n  ART2 & 5419.3 & NaN & 517.4 & 619.8 & 730.5 & 229.0 \\\\\n   \\hline\n  DE & 5688.92 & 9819.6 & 5648.6 & 1091.1 & 36113.1 & 679.9 \\\\\n   \\hline\n  PSO & 5688.83 & 11450.1 & 5681.6 & 1091.1 & 36113.1 & 679.9 \\\\\n   \\hline\n  GA & 5688.83 & 11453.2 & 5680.6 & 1091.1 & 36113.1 & 679.9 \\\\\n   \\hline\n  \\textbf{PSO-2} & 5253.3 &  9691.4 & 5359.3 & 268.3 & 11233.4  &  \\textbf{679.9}\\\\  [1ex]\n  \\hline\n\\end{tabular}\n\\end{table}\n\nA higher value of entrophy as seen in Table \\ref{ent} indicates higher disorder in the clustering and a lower value is preferred. PSO-2 has produced clustering with lower value for entrophy than other algorithms on three datasets.\n\n\\begin{table}[H]\n\\caption{Entrophy}\n\\label{ent}\n\\centering\n\\begin{tabular}{||c|c|c|c|c|c|c||}\n  \\hline\n\\multicolumn{1}{|c|}{\\textbf{Name}} & \\multicolumn{1}{c|}{\\textbf{Banana}} & \\multicolumn{1}{c|}{\\textbf{Cluto}} & \\multicolumn{1}{c|}{\\textbf{Cure}} & \\multicolumn{1}{c|}{\\textbf{Long}} & \\multicolumn{1}{c|}{\\textbf{2d-4c}} & \\multicolumn{1}{c|}{\\textbf{Demo}}\\\\\n  \\hline\\hline\n  KMeans & 0.69 & 2.08 & 1.78 & 0.69 & 1.23 & 1.1 \\\\ [0.5ex]\n   \\hline\n  PAM & 0.65 & 2.08 & 1.77 & 0.68 & 1.23 & 1.1 \\\\\n   \\hline\n  ART2 & 0.66 & 0 & 1.31 & 0.99 & 0.38 & 1.34 \\\\\n   \\hline\n  DE & 0.69 & 2.03 & 1.77 & 0.69 & 1.23 & 1.1 \\\\\n   \\hline\n  PSO & 0.69 & 2.08 & 1.78 & 0.69 & 1.23 & 1.1 \\\\\n   \\hline\n  GA & 0.69 & 2.08 & 1.78 & 0.69 & 1.23 & 1.1 \\\\\n   \\hline\n  \\textbf{PSO-2} & \\textbf{0.65} & \\textbf{1.98} & 1.76 & \\textbf{0.24} & 0.98 & 1.1 \\\\  [1ex]\n  \\hline\n\\end{tabular}\n\\end{table}\n\nHigher values of Pearson Gamma Coefficient obtained by PSO-2 indicates better clustering compared to other approaches on three datasets whereas performance on the remaining is in acceptable range as seen in Table \\ref{pgc}.\n\n\\begin{table}[H]\n\\caption{Pearson Gamma Coefficient}\n\\label{pgc}\n\\centering\n\\begin{tabular}{||c|c|c|c|c|c|c||}\n  \\hline\n\\multicolumn{1}{|c|}{\\textbf{Name}} & \\multicolumn{1}{c|}{\\textbf{Banana}} & \\multicolumn{1}{c|}{\\textbf{Cluto}} & \\multicolumn{1}{c|}{\\textbf{Cure}} & \\multicolumn{1}{c|}{\\textbf{Long}} & \\multicolumn{1}{c|}{\\textbf{2d-4c}} & \\multicolumn{1}{c|}{\\textbf{Demo}}\\\\\n  \\hline\\hline\n  KMeans & 0.66 & 0.51 & 0.62 & 0.53 & 0.89 & 0.78 \\\\ [0.5ex]\n   \\hline\n  PAM & 0.67 & 0.51 & 0.61 & 0.51 & 0.891 & 0.78 \\\\\n   \\hline\n  ART2 & 0.67 & NA & 0.25 & 0.44 & 0.54 & 0.56 \\\\\n   \\hline\n  DE & 0.66 & 0.51 & 0.62 & 0.53 & 0.89 & 0.78 \\\\\n   \\hline\n  PSO & 0.66 & 0.51 & 0.62 & 0.53 & 0.89 & 0.78 \\\\\n   \\hline\n  GA & 0.66 & 0.51 & 0.62 & 0.53 & 0.89 &  0.78 \\\\\n   \\hline\n  \\textbf{PSO-2} & \\textbf{0.67} & \\textbf{0.53} & 0.62 & 0.39 & \\textbf{0.93} & 0.78 \\\\  [1ex]\n  \\hline\n\\end{tabular}\n\\end{table}\n\nHigher value of Dunn index as seen in Table \\ref{dunn} indicates better clustering results and PSO-2 has obtained clusters with dunn index comparable to those produced by other approaches.\n\n\\begin{table}[H]\n\\caption{Dunn Index}\n\\label{dunn}\n\\centering\n\\begin{tabular}{||c|c|c|c|c|c|c||}\n  \\hline\n\\multicolumn{1}{|c|}{\\textbf{Name}} & \\multicolumn{1}{c|}{\\textbf{Banana}} & \\multicolumn{1}{c|}{\\textbf{Cluto}} & \\multicolumn{1}{c|}{\\textbf{Cure}} & \\multicolumn{1}{c|}{\\textbf{Long}} & \\multicolumn{1}{c|}{\\textbf{2d-4c}} & \\multicolumn{1}{c|}{\\textbf{Demo}}\\\\\n  \\hline\\hline\n  KMeans & 0.01 & 0.004 & 0.002 & 0.003 & 0.45 & 0.06  \\\\ [0.5ex]\n   \\hline\n  PAM & 0.003 & 0.003 & 0.005 & 0.01 & 0.45 & 0.06 \\\\\n   \\hline\n  ART2 & 0.002 & Inf & 0.002  & 0.004 & 0.605 & 0.01 \\\\\n   \\hline\n  DE & 0.002 & 0.003 & 0.002 & 0.012 & 0.45 & 0.06 \\\\\n   \\hline\n  PSO & 0.002 & 0.01 & 0.003 & 0.01 & 0.45 & 0.06 \\\\\n   \\hline\n  GA & 0.002 & 0.001 & 0.003 & 0.01 & 0.45 & 0.06 \\\\\n   \\hline\n  \\textbf{PSO-2} & \\textbf{0.004} & 0.003 & \\textbf{0.004} &  0.005 &  \\textbf{0.94} & 0.05 \\\\  [1ex]\n  \\hline\n\\end{tabular}\n\\end{table}\n\n\n\n\\section{Conclusion}\nMeta heuristics are considered as efficient alternatives to classical techniques in terms of traversing a search space which is non convex and not solvable in polynomial time. The inherent nature of such algorithms gives them capabilities such as parallelized implementation, fast convergence, ability to consider multiple solutions and the capability to avoid local optima. The objective function for such algorithms has to be chosen to achieve both fast computation as well as achieve a trade-off between multiple objectives. PSO-2 implemented in this paper seeks to uncover clustering structure while respecting constraints of efficiency. The cost function provides modified definitions of intra and inter cluster distances that are calculated in linear time. This achieves an improvement over the existing methods that need $O(n^2)$ to compute both the within and between cluster distances. Clustering structure uncovered by PSO-2 shows compact and well seperated clusters. It however fails to discover non convex clusters in the data. Yet the performance of PSO-2 is comparable to the standard PSO which is based on minimizing within cluster distance only. The experiments have demonstrated that clustering output provided by PSO-2 is comparable to other evolutionary as well as non evolutionary algorithms. \n\n\n\n\n\n\n\n\n\n\n% trigger a \\newpage just before the given reference\n% number - used to balance the columns on the last page\n% adjust value as needed - may need to be readjusted if\n% the document is modified later\n%\\IEEEtriggeratref{8}\n% The \"triggered\" command can be changed if desired:\n%\\IEEEtriggercmd{\\enlargethispage{-5in}}\n\n% references section\n\n% can use a bibliography generated by BibTeX as a .bbl file\n% BibTeX documentation can be easily obtained at:\n% http://mirror.ctan.org/biblio/bibtex/contrib/doc/\n% The IEEEtran BibTeX style support page is at:\n% http://www.michaelshell.org/tex/ieeetran/bibtex/\n%\\bibliographystyle{IEEEtran}\n% argument is your BibTeX string definitions and bibliography database(s)\n%\\bibliography{IEEEabrv,../bib/paper}\n%\n% <OR> manually copy in the resultant .bbl file\n% set second argument of \\begin to the number of references\n% (used to reserve space for the reference number labels box)\n\\begin{thebibliography}{}\n\n\\bibitem{hur}\nHruschka, E.R., Campello, R.J. and Freitas, A.A., 2009. A survey of evolutionary algorithms for clustering. IEEE Transactions on Systems, Man, and Cybernetics, Part C (Applications and Reviews), 39(2), pp.133-155.\n\n\\bibitem{cha}\nChakrabarti, Deepayan, Ravi Kumar, and Andrew Tomkins. \"Evolutionary clustering.\" In Proceedings of the 12th ACM SIGKDD international conference on Knowledge discovery and data mining, pp. 554-560. ACM, 2006.\n\n\\bibitem{ma}\nMa, P.C., Chan, K.C., Yao, X. and Chiu, D.K., 2006. An evolutionary clustering algorithm for gene expression microarray data analysis. IEEE Transactions on Evolutionary Computation, 10(3), pp.296-314.\n\n\\bibitem{zha}\nZhang, Xingyi, et al. \"A decision variable clustering-based evolutionary algorithm for large-scale many-objective optimization.\" IEEE Transactions on Evolutionary Computation (2016).\n\n\\bibitem{luo}\nLuo, J., Jiao, L. and Lozano, J.A., 2016. A sparse spectral clustering framework via multiobjective evolutionary algorithm. IEEE Transactions on Evolutionary Computation, 20(3), pp.418-433.\n\n\\bibitem{lin}\nLin, K.P., 2014. A novel evolutionary kernel intuitionistic fuzzy $ c $-means clustering algorithm. IEEE Transactions on Fuzzy Systems, 22(5), pp.1074-1087.\n\n\\bibitem{muk}\nMukhopadhyay, A., Maulik, U., Bandyopadhyay, S. and Coello, C.A.C., 2014. A survey of multiobjective evolutionary algorithms for data mining: Part I. IEEE Transactions on Evolutionary Computation, 18(1), pp.4-19.\n\n\\bibitem{muktwo}\nMukhopadhyay, A., Maulik, U., Bandyopadhyay, S. and Coello, C.A.C., 2014. Survey of multiobjective evolutionary algorithms for data mining: Part II. IEEE Transactions on Evolutionary Computation, 18(1), pp.20-35.\n\n\\bibitem{lih}\nLi, H., Zhang, Q. and Deng, J., 2017. Biased multiobjective optimization and decomposition algorithm. IEEE transactions on cybernetics, 47(1), pp.52-66.\n\n\\bibitem{sid}\nSiddiqi, U.F. and Sait, S.M., 2017. A New Heuristic for the Data Clustering Problem. IEEE Access.\n\n\\bibitem{pso}\nEberhart, R. and Kennedy, J., 1995, October. A new optimizer using particle swarm theory. In Micro Machine and Human Science, 1995. MHS'95., Proceedings of the Sixth International Symposium on (pp. 39-43). IEEE.\n\\bibitem{pso1}\nBratton, D. and Kennedy, J., 2007, April. Defining a standard for particle swarm optimization. In Swarm Intelligence Symposium, 2007. SIS 2007. IEEE (pp. 120-127). IEEE.\n\\bibitem{pso2}\nClerc, M., 2010. Particle swarm optimization (Vol. 93). John Wiley \\& Sons.\n\n\n\\bibitem{da}\nStorn, R. and Price, K., 1997. Differential evolution–a simple and efficient heuristic for global optimization over continuous spaces. Journal of global optimization, 11(4), pp.341-359.\n\n\\bibitem{ga}\nWhitley, D., 1994. A genetic algorithm tutorial. Statistics and computing, 4(2), pp.65-85.\n \\bibitem{val1} \nHennig, C. and Liao, T. (2013) How to find an appropriate clustering for mixed-type variables with application to socio-economic stratification, Journal of the Royal Statistical Society, Series C Applied Statistics, 62, 309-369.\n \\bibitem{val2}\nHennig, C. (2013) How many bee species? A case study in determining the number of clusters. In: Spiliopoulou, L. Schmidt-Thieme, R. Janning (eds.): \"Data Analysis, Machine Learning and Knowledge Discovery\", Springer, Berlin, 41-49. \n\n\n\\end{thebibliography}\n\n\n\n\n% that's all folks\n\\end{document}\n\n\n", "meta": {"hexsha": "c7220a5550f7a13e9d9ff60abd5da9a6c502c78c", "size": 37340, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ppr5/indersci-paper-5.tex", "max_stars_repo_name": "pranavn91/PhD", "max_stars_repo_head_hexsha": "ac44783a1c7c418cafcfc7eb35ef2fc9641688bc", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ppr5/indersci-paper-5.tex", "max_issues_repo_name": "pranavn91/PhD", "max_issues_repo_head_hexsha": "ac44783a1c7c418cafcfc7eb35ef2fc9641688bc", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ppr5/indersci-paper-5.tex", "max_forks_repo_name": "pranavn91/PhD", "max_forks_repo_head_hexsha": "ac44783a1c7c418cafcfc7eb35ef2fc9641688bc", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 64.7140381282, "max_line_length": 1703, "alphanum_fraction": 0.7343331548, "num_tokens": 11234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.3264295192838106}}
{"text": "\\section{Conclusion and Outlook}\nThe understanding of the thermalization process of gluons plays a central role in finding an appropriate theoretical description of the complex interplay of physical processes during relativistic heavy-ion collisions. \\\\\n\\noindent\nUsing kinetic theory and statistical transport equations we were able to estimate important quantities such as the equilibration time $\\tau_{\\mathrm{eq}}$ by understanding thermalization as a dynamical interplay of elastic and inelastic scatterings. \\\\\n\\noindent\nOne explanation for the apparent excess of particles in the thermal spectrum compared to the expected equilibrium distribution is the formation of a Bose-Einstein condensate which may survive during most of the thermalization process. This option seems however not to be the favored interpretation amongst the researchers nowadays as the understanding of the various inelastic contributions to the gluon scattering is understood better than back when the idea of the condensate came up first.\\\\\n\\noindent\nIn the second part we focused on the derivation and solution of a nonlinear boson diffusion equation providing further insights into the thermalization process and an analytically accessible model to study different aspects of thermalization in more detail.\\\\\n\\noindent\nIn the future one may elaborate on the different approximation schemes and solution techniques for example by considering the time- and energy-dependence of the values of the transport coefficients or by extending the model in more than $1+1$ spacetime dimensions to be able to account for example for possible anisotropies.", "meta": {"hexsha": "38a3c5d4b38b6b129d9284c07018fe94b2df6966", "size": 1626, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "summary/content/05_conclusion.tex", "max_stars_repo_name": "mathieukaltschmidt/Thermalization-of-Gluons", "max_stars_repo_head_hexsha": "4fa0a9503f82c007fbb196df3e665772b259355e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "summary/content/05_conclusion.tex", "max_issues_repo_name": "mathieukaltschmidt/Thermalization-of-Gluons", "max_issues_repo_head_hexsha": "4fa0a9503f82c007fbb196df3e665772b259355e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "summary/content/05_conclusion.tex", "max_forks_repo_name": "mathieukaltschmidt/Thermalization-of-Gluons", "max_forks_repo_head_hexsha": "4fa0a9503f82c007fbb196df3e665772b259355e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 162.6, "max_line_length": 494, "alphanum_fraction": 0.8357933579, "num_tokens": 304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.32633087729784727}}
{"text": "\\section{Introduction}\n\\label{sec:introduction}\n\nType errors are a common stumbling block for students\ntrying to learn typed functional languages like \\ocaml\\\nand \\haskell.\n%\nConsider the ill-typed @fac@ function on the left in\nFigure~\\ref{fig:factorial}.\n%\nThe function returns @true@ in the base case (instead of @1@),\nand so \\ocaml responds with the error message:\n%\n\\begin{verbatim}\n  This expression has type\n    bool\n  but an expression was expected of type\n    int.\n\\end{verbatim}\n%\nThis message makes perfect sense to an expert who is familiar\nwith the language and has a good mental model of how the type\nsystem works.\n%\nHowever, it may perplex a novice who has yet to develop such a\nmental model.\n%\nTo make matters worse, unification-based type inference algorithms\noften report errors far removed from their source.\n%\nThis further increases the novice's confusion and can actively mislead\nthem to focus their investigation on an irrelevant piece of code.\n%\nMuch recent work has focused on analyzing unification constraints\nto properly \\emph{localize} a type error~\\cite{Lerner2007-dt,Chen2014-gd,Zhang2014-lv,Pavlinovic2014-mr},\nbut an accurate source location does not explain \\emph{why} the\nprogram is wrong.\n\n\n\\begin{figure}[t]\n\\centering\n\\begin{minipage}{.49\\linewidth}\n\\centering\n\\begin{ecode}\n  let rec fac n =\n    if n <= 0 then\n      true\n    else\n      n * (*@\\hlOcaml{fac (n-1)}@*)\n\\end{ecode}\n\\vspace{2em}\n\\includegraphics[height=1.5in]{fac-overview.png}\n\\end{minipage}\n\\begin{minipage}{.49\\linewidth}\n\\centering\n\\includegraphics[height=3in]{fac-long.png}\n\\end{minipage}\n\\vspace{1em}\n\\caption{(top-left) An ill-typed \\texttt{fac} function \\hlOcaml{highlighting} the error location reported by \\ocaml. (bottom-left) Dynamically witnessing the type error in \\texttt{fac}, showing only function call-return pairs. (right) The same trace, fully expanded to show each small-step reduction in the computation.}\n\\label{fig:factorial}\n\\end{figure}\n\nIn this paper we propose a new approach that explains\nstatic type errors by \\emph{dynamically} witnessing\nhow an ill-typed program goes wrong.\n%\nWe have developed \\toolname, an interactive tool that uses\nthe source of the ill-typed function to automatically synthesize\nthe result on the bottom-left in Figure~\\ref{fig:factorial}, which\nshows how the recursive calls reduce to a configuration where\nthe program ``goes wrong'' --- \\ie\\ the @int@ value @1@ is to be\nmultiplied with the @bool@ value @true@.\nWe achieve this via three concrete contributions.\n\n\\paragraph{1. Finding Witnesses}\nOur first contribution is an algorithm for searching for\n\\emph{witnesses} to type errors, \\ie\\ inputs that cause a\nprogram to go wrong~(\\S~\\ref{sec:searching-witness}).\n%\nThis problem is tricky when we cannot rely on\nstatic type information, as we must avoid the\ntrap of \\emph{spurious} inputs that cause\nirrelevant problems that would be avoided\nby picking values of a different, relevant type.\n%\nWe solve this problem by developing a novel\noperational semantics that combines evaluation\nand type inference.\n%\nWe execute the program with \\emph{holes} --- values whose type is\nunknown --- as the inputs.\n%\nA hole remains abstract until the evaluation\ncontext tells us what type it must have, for\nexample the parameters to an addition operation\nmust both be integers.\n%\nOur semantics conservatively instantiates holes\nwith concrete values, dynamically inferring the\ntype of the input until the program goes wrong.\n%\nWe prove that our procedure synthesizes \\emph{general}\nwitnesses, which means, intuitively, that if a witness\nis found for a given ill-typed function, then, \\emph{for all}\n(inhabited) input types, there exist values that can make\nthe function go wrong.\n\nGiven a witness to a type error, the novice may still be at a loss.\n%\nThe standard \\ocaml\\ interpreter and debugging infrastructure expect\nwell-typed programs, so they cannot be used to investigate \\emph{how}\nthe witness causes the program to crash.\n%\nMore importantly, the execution itself may be quite long and may contain\ndetails not relevant to the actual error.\n\n\\paragraph{2. Visualizing Witnesses}\nOur second contribution is an interactive visualization of the\nexecution of purely functional \\ocaml\\ programs, well-typed or not~(\\S~\\ref{sec:interactive}).\n%\nWe extend the semantics to also build a \\emph{reduction graph}\nwhich records all of the small-step reductions and the context\nin which they occur.\n%\nThe graph lets us visualize the sequence of\nsteps from the source witness to the stuck term. The user can\ninteractively expand the computation to expose intermediate steps\nby selecting an expression and choosing a traversal strategy.\n%\nThe strategies include many of the standard debugging moves, \\eg\\\nstepping \\emph{forward} or \\emph{into} or \\emph{over} calls, as well\nstepping or jumping \\emph{backward} to understand how a particular\nvalue was created, while preserving a context of the intermediate\nsteps that allow the user to keep track of a term's provenance.\n\nWe introduce a notion of \\emph{jump-compressed} traces to abstract away\nthe irrelevant details of a computation.\n%\nA jump-compressed trace includes only function\ncalls and returns. For example, the trace in the bottom-left of\nFigure~\\ref{fig:factorial} is jump-compressed.\n%\nJump-compressed traces are similar to stack traces in that both show a\nsequence of function calls that lead to a crash. However, jump-compressed\ntraces also show the return values of successful calls, which can be\nuseful in understanding why a particular path was taken.\n\n\\paragraph{3. Evaluating Witnesses}\n%\nOf course, the problem of finding witnesses is\nundecidable in general. In fact, due to the necessarily\nconservative nature of static typing, there\nmay not even exist any witnesses for a given\nill-typed program.\n%\nThus, our approach is a heuristic that is only useful\nif it can find \\emph{compact} witnesses for\n\\emph{real-world} programs.\n%\nOur third contribution is an extensive evaluation of our approach\non two different sets of ill-typed programs obtained by instrumenting\ncompilers used in beginner's classes~(\\S~\\ref{sec:evaluation}).\n%\nThe first is the \\uwbench\\ data set~\\cite{Lerner2007-dt}\ncomprising \\uwsize\\ ill-typed programs.\n%\nThe second is a new \\ucsdbench\\ data set, comprising \\ucsdsize\\\nill-typed programs.\n%\nWe show that for both data sets, our technique is able to generate\nwitnesses for around 85\\% of the programs, in under a second in the\nvast majority of cases.\n%\nFurthermore, we show that a simple interactive strategy yields\ncompact counterexample traces with at most 5 steps for 60\\%\nof the programs, and at most 10 steps for over 80\\% of the programs.\n%\nWe can even use witnesses to \\emph{localize} type errors with a simple\nheuristic that treats the values in a ``stuck'' term as \\emph{sources}\nof typing constraints and the term itself as a \\emph{sink},\nachieving around 70\\% accuracy in locating the source of the error.\n\nThe ultimate purpose of an error report is to help the programmer\n\\emph{comprehend} and \\emph{fix} problematic code.\n%\nThus, our final contribution is a user study that compares \\toolname's\ndynamic witnesses against \\ocaml's type errors along the dimension of\ncomprehensibility~(\\S~\\ref{sec:user-study}).\n%\nOur study finds that students given one of our witnesses are\nconsistently more likely to correctly explain and fix a type\nerror than those given the standard error message produced by\nthe \\ocaml compiler.\n\n\n%\n% \\subparagraph{Witness Utility}\n%\n% Even if we can find small witnesses for the majority of type errors, it\n% may be that the witnesses do not actually help developers\n% \\emph{understand} the errors.\n%\n% In other words, perhaps the static error message is sufficient to\n% diagnose and fix the error, or perhaps the witness simply does not add\n% enough information to make a difference.\n%\n%\n% Thus, our final contribution is a user study that compares the utility\n% of our witnesses with that of the error messages provided by the \\ocaml\n% compiler~(\\S~\\ref{sec:user-study}).\n%\n\n\\smallskip\nAll together, our results show that in the vast majority of cases, (novices') ill-typed\nprograms \\emph{do} go wrong, and that the witnesses to these errors can be\nhelpful in understanding the source of the error. This, in turn, opens the\ndoor to a novel dynamic way to explain, understand, and appreciate the\nbenefits of static typing.\n\n\\paragraph{Contributions Relative to Prior Publications}\nThis paper extends our ICFP '16 paper of the same\nname~\\cite{Seidel2016-ul}, focusing on the experimental evaluation.\n%\nFirst, in \\S~\\ref{sec:how-safe} we investigate the student programs for\nwhich we were unable to synthesize a witness. We group the failures into\nfive categories, give representative examples, and suggest ways to\nimprove our feedback in these cases. Interestingly, we find that in the\nmajority of these failed cases, the programs do not actually admit a\nwitness in our semantics.\n%\nSecond, in \\S~\\ref{sec:locating} we attempt to use our witnesses to\nlocalize type errors with a simple heuristic. We treat the stuck term as\na sink for typing constraints, and the values it contains as sources of\nconstraints. We can then predict that either the stuck term or one of\nthe terms that \\emph{produced} a value it contains is likely at fault\nfor the error. We compare our localizations to \\ocaml and two\nstate-of-the-art type error localization tools, and find that we are\ncompetitive with the state of the art.\n%\nFinally, we have also extended \\S~\\ref{sec:user-study} with an analysis\nof the statistical significance of our user study results.\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: \"main\"\n%%% End:\n", "meta": {"hexsha": "075827254d77c6f7cb3cdc9ce00be36dc1879965", "size": 9669, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/jfp-submission/introduction.tex", "max_stars_repo_name": "gridaphobe/nanoml", "max_stars_repo_head_hexsha": "0de06f2c3a41063b1bf87d5f6dd11ad830be0512", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2017-02-06T02:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-25T23:09:59.000Z", "max_issues_repo_path": "paper/jfp-submission/introduction.tex", "max_issues_repo_name": "gridaphobe/nanoml", "max_issues_repo_head_hexsha": "0de06f2c3a41063b1bf87d5f6dd11ad830be0512", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-05-16T05:03:45.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-16T17:37:54.000Z", "max_forks_repo_path": "paper/jfp-submission/introduction.tex", "max_forks_repo_name": "gridaphobe/nanoml", "max_forks_repo_head_hexsha": "0de06f2c3a41063b1bf87d5f6dd11ad830be0512", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-10-11T21:36:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-08T21:52:40.000Z", "avg_line_length": 39.1457489879, "max_line_length": 320, "alphanum_fraction": 0.7816733892, "num_tokens": 2372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.3263265952414386}}
{"text": "\\section{Dense gas dispersion in obstructed terrain}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Falcon series}\nThe Falcon series were conducted by LLNL in 1987. These comprises 5 large-scale LNG spill tests aiming at evaluating the effectiveness of impoundment walls as a mitigation technique for accidental releases of LNG. LNG was spilled onto a rectangular water pond (60m x 40m). The evaporation rate could be roughly equivalent to the spill flow rate as the designed recirculation system was involved to maximize the evaporation process \\cite{Gavelli2008}. LNG was supplied to the pond through 4 pipes, fitted with 0.11m diameter orifices and spaced at 900 intervals. The vapour fence, about 8.7m high, surrounded the water pond of a total area of 44m x 88m. The billboard of 13.3m tall, 17.1m wide was used to simulate the effect of a storage tank or other obstruction. The terrain was flat and the atmospheric condition was stable or neutrally stable. \n\nThree Falcon tests included in MEP, Falcon 1, Falcon 3 and Falcon 4 are simulated in OpenFOAM to examine the effective of proposed models in simulating field LNG dispersion in present of obstacles.\n\n\\subsection{Boundary conditions}\n\\paragraph{Atmospheric inlet boundary}\nMonin-Obukhov similarity theory is used to specify the wind velocity and temperature profile at the inlet. The velocity profile is calculated from Equation~\\ref{eq:MO-velocity}. All required meteorological parameters:\n\\begin{table}[h!]\n\t\\caption{Falcon tests meteorological parameters} \\label{tab:falcon_params}\n\t\\centering\n\t\\begin{tabular}{lrrr}\n\t\t\\toprule\n\t\t& Falcon 1\t& Falcon 3\t& Falcon 4\t\t\\\\\n\t\t\\midrule\n\t\tStability & G & D & D-E \\\\\n\t\t$L$\t\t& 4.96 & -422 & 69.4\t\\\\\n\t\t$u_*$\t& 0.061 & 0.305 & 0.369\t\\\\\n\t\t$T_*$\t& 0.058 & -0.018 & 0.152\t\\\\\n\t\t$z_0$ \t& 0.008 & 0.008 & 0.008 \\\\\n\t\t\\bottomrule\n\t\\end{tabular}\n\\end{table}\n\n\\paragraph{Vapour gas inlet}\nVapour gas inlet condition is usually obtained from separate source term modelling. There is not much information about the vaporisation of LNG from the experimental data. Therefore, uncertainty arises at the setting of this condition. \n\nMass flux of LNG or the LNG vaporization rate is used to derive source term of LNG spill. \\textcite{Luketa-Hanlin2007} reviewed a number of experiments conducting to estimate the LNG vaporization rate of the spill on water, the range of this value varied between approximately \\SIrange[range-units=single]{0.029}{0.195}{\\kilogram\\per\\square\\meter\\per\\second}. In the case of Burro test, the simulated vaporisation rate is assumed to be $\\dot{m} = $\\SI{0.167}{\\kilogram\\per\\square\\meter\\per\\second}. The spill diameter is derived from this vaporization rate, reported spill mass $m$ and duration $\\delta t$:\n\\begin{equation}\nD = \\sqrt{\\frac{4m}{\\pi \\dot{m} \\delta t}}\n\\end{equation}\nLNG spill variables used in simulation are tabulated in Table~\\ref{tab:burro_releaseVar}.\n\\begin{table}[h!]\n\t\\caption{Falcon test spill condition} \\label{tab:falcon_releaseVar}\n\t\\centering\n\t\\begin{tabular}{rrrr}  \n\t\t\\toprule\n\t\t& Falcon 1\t& Falcon 3\t& Falcon 4\t\t\\\\\n\t\t\\midrule\n\t\tVaporization rate (\\si{\\kilogram\\per\\square\\meter\\per\\second}) & 0.167 & 0.167 & 0.167 \\\\\n\t\tSpill mass (\\si{\\kilogram}) \t\t& 28074 \t& 21435 \t& 18984  \t\\\\\n\t\tSpill duration (\\si{\\second}) \t\t& 131 \t& 154 \t& 301  \t\\\\\n\t\tSpill pool diameter (\\si{\\meter}) \t\t& 19.5 \t& 16.0 \t& 10.8 \t\\\\\n\t\t\\bottomrule\n\t\\end{tabular}\n\\end{table}\n\n\\subsection{Results and Discussion}\n\\subsubsection{Arcwise prediction}\nMaximum concentration at four arcwise sensor arrays at $50 m$, $150 m$ and $250 m$ of three Falcon tests are compared with experimental data. Prediction of maximum concentration are best for Falcon 4 test.\n\n\\begin{figure}[htbp]\n\t\\centering\n\t\\begin{subfigure}[]{0.49\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{Falcon1ConMax}\n\t\t\\caption{}\n\t\\end{subfigure} \n\t~\n\t\\begin{subfigure}[]{0.49\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{Falcon3ConMax}\n\t\t\\caption{}\n\t\\end{subfigure}\n\t%a blank line to force the subfigure onto a new line\n\t\n\t\\begin{subfigure}[]{0.49\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{Falcon4ConMax}\n\t\t\\caption{}\n\t\\end{subfigure} \n\t\n\t\\caption{Maximum arc-wise concentration (a) Falcon 1 (b) Falcon 3 (c) Falcon 4}\n\t\\label{fig:FalconConMax}\n\\end{figure}\n\n\\subsubsection{SPMs}\nStatistical performance of \\bera{OpenFOAM} results are compared with \\bera{FLACS} which data extracted from \\cite{Hansen2010a} in Table~\\ref{tab:Falcon_SPMs}:\n\n\\begin{table}[h!]\n\t\\caption{Statistical performance measure values of Falcon} \\label{tab:Falcon_SPMs}\n\t\\centering\n\t\\begin{tabular}{lrrrrr}\n\t\t\\toprule\n\t\t& MRB & MG & RMSE & VG  &FAC2 \\\\\n\t\t\\midrule\n\t\t$FLACS$\t&1.35 &5.56 &1.88 &23.65 &0\t\\\\\n\t\t\\bottomrule\n\t\\end{tabular}\n\\end{table}", "meta": {"hexsha": "8898db6572087c334814c936a46f57b881e2840d", "size": 4702, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "GasDispersionFalcon.tex", "max_stars_repo_name": "stevietran/phdThesis", "max_stars_repo_head_hexsha": "c6ccf59f7fa9b63d6af2ba1f9d48efddbf8980f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GasDispersionFalcon.tex", "max_issues_repo_name": "stevietran/phdThesis", "max_issues_repo_head_hexsha": "c6ccf59f7fa9b63d6af2ba1f9d48efddbf8980f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GasDispersionFalcon.tex", "max_forks_repo_name": "stevietran/phdThesis", "max_forks_repo_head_hexsha": "c6ccf59f7fa9b63d6af2ba1f9d48efddbf8980f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.8314606742, "max_line_length": 848, "alphanum_fraction": 0.7396852403, "num_tokens": 1469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.3263265952414386}}
{"text": "%%%%%%%%%%%%%%%%\r\n% LaTeX\r\n%%%%%%%%%%%%%%%%%%\r\n\\documentclass[12pt]{article}\r\n\\oddsidemargin 0in \\evensidemargin 0in \\textheight 9in \\textwidth\r\n6.5in \\topmargin 0in \\headheight 0in\r\n\\parindent 20 pt\r\n\\headsep 0 in\r\n\r\n\\usepackage{amsthm,amssymb}\r\n\r\n\\usepackage{gb4e} % by me\r\n\r\n\\newtheorem*{thm}{Theorem}\r\n%\\newtheorem{cor}[thm]{Corollary}\r\n\\newtheorem{theorem}{Theorem}%[section]\r\n\\newtheorem{corollary}[theorem]{Corollary}\r\n\\newtheorem{proposition}[theorem]{Proposition}\r\n\\newtheorem{lemma}[theorem]{Lemma}\r\n\\newtheorem{hypothesis}[theorem]{Hypothesis}\r\n\\newtheorem{example}[theorem]{Example}\r\n\r\n%\\newenvironment{proof}[1][Proof]%\r\n%{\\par\\addvspace{6pt}\\noindent{\\bf #1.}\\hskip\\labelsep\\ignorespaces}%\r\n%{{\\hfill $\\square$}\\par\\addvspace{6pt}}\r\n\r\n\r\n\\def\\bull{\\vrule height .9ex width .8ex depth -.1ex }\r\n%\\magnification=\\magstep1\r\n\\raggedbottom\r\n\\def\\card#1{\\vert #1 \\vert}\r\n\\def\\gpindex#1#2{\\card {#1\\colon #2}}\r\n\\def\\irr#1{{\\textrm  Irr}(#1)}\r\n\\def\\ibr#1{{\\textrm IBr} (#1)}\r\n\\def\\irri#1#2{{\\textrm Irr}_{#1} (#2)}\r\n\\def\\cd#1{{\\textrm  cd}(#1)}\r\n\\def\\cent#1#2{{\\bf C}_{#1}(#2)}\r\n\\def\\gpcen#1{{\\bf Z} (#1)}\r\n\\def\\ker#1{{\\textrm ker} (#1)}\r\n%\\def\\ref#1{{\\bf [#1]}}\r\n\\def\\form#1#2#3{\\langle\\langle #1, #2 \\rangle\\rangle_{#3}}\r\n\\def\\empform#1{\\form {\\cdot}{\\cdot}{#1}}\r\n\\def\\norm#1#2{{\\textrm N}_{#1} (#2)}\r\n\\def\\NN{{\\cal N}}\r\n\\def\\SS{{\\cal S}}\r\n\\def\\UU{{\\cal U}}\r\n\\def\\TT{{\\cal T}}\r\n\\def\\B#1#2{{\\textrm B}_{#1} (#2)}\r\n\\def\\Bpi#1{\\B {\\pi}{#1}}\r\n\\def\\D#1#2{{\\textrm D}_{#1} (#2)}\r\n\\def\\Dpi#1{\\D {\\pi} {#1}}\r\n\\def\\I#1#2{{\\textrm I}_{#1} (#2)}\r\n\\def\\Ipi#1{\\I {\\pi}{#1}}\r\n\\def\\phi{\\varphi}\r\n\r\n\\newcommand \\IIpi[3] {{\\textrm I}_{#1} (#2 \\mid #3)}\r\n\r\n\\begin{document}\r\n\r\n\\title{Inducing $\\pi$-partial characters with a given vertex}\r\n\r\n\\author {\r\n       Mark L.\\ Lewis\r\n    \\\\ {\\it Department of Mathematical Sciences, Kent State University}\r\n    \\\\ {\\it Kent, Ohio 44242}\r\n    \\\\ E-mail: lewis@math.kent.edu\r\n       }\r\n%\\date{July 17, 2010}\r\n\r\n\\maketitle\r\n\r\n\\begin{abstract}\r\nLet $G$ be a solvable group.  Let $p$ be a prime and let $Q$ be a\r\n$p$-subgroup of a subgroup $V$.  Suppose $\\phi \\in \\ibr G$.  If\r\neither $|G|$ is odd or $p = 2$, we prove that the number of Brauer\r\ncharacters of $H$ inducing $\\phi$ with vertex $Q$ is at most $|\\norm\r\nGQ: \\norm VQ|$.\r\n\r\nMSC Primary: 20C20, MSC Secondary: 20C15\r\n\r\nKeywords: Brauer characters, partial characters, vertices\r\n\\end{abstract}\r\n\r\n%Inducing partial characters with a given vertex\r\n\r\n\r\n%These were originally notes written in December 2010.  This result\r\n%arose in some work that I doing with JP.\r\n\r\n\\section{Introduction}\r\n\r\nThroughout this note, $G$ is a finite group, and $\\irr G$ is the set\r\nof irreducible characters of $G$.  Suppose $\\chi \\in \\irr G$ and $H$\r\nis a subgroup of $G$.  It is easy to obtain an upper bound on the\r\nnumber of characters in $\\irr H$ that induce $\\chi$.  Let $\\phi_1,\r\n\\dots, \\phi_n \\in \\irr H$ be the characters so that $\\phi_i^G =\r\n\\chi$.  Evaluating at $1$, we obtain $\\phi_i (1) = \\chi (1)/|G:H|$\r\nfor each $i$.  By Frobenius reciprocity (Lemma 5.2 of \\cite{text}),\r\neach $\\phi_i$ is a constituent of $\\chi_H$ with multiplicity $1$.\r\nSince there are $n$ such characters occurring as constituents of\r\n$\\chi_H$, it follows that $n (\\chi (1)/|G:H|) \\le \\chi (1)$.  We\r\ndeduce that $n \\le |G:H|$, and we have an upper bound.  If $H$ is\r\nnormal in $G$, this bound is obtained, and it is not particularly\r\ndifficult to find nonnormal subgroups where this bound is obtained.\r\n\r\nWe now turn our attention to Brauer characters.  Fix a prime $p$. We\r\nwill write $\\ibr G$ for the irreducible $p$-Brauer characters of\r\n$G$.  If $\\phi \\in \\ibr G$, then it is easy to adapt the above proof\r\nto show that $\\phi$ is induced by at most $|G:H|$ Brauer characters\r\nof $H$.  However, associated with $\\phi$ are certain $p$-subgroups\r\nof $G$ called the vertex subgroups.  When $G$ is a $p$-solvable\r\ngroup, a $p$-subgroup $Q$ of $G$ is defined to be a vertex for\r\n$\\phi$ if there is a subgroup $U$ of $G$ so that $\\phi$ is induced\r\nby a Brauer character of $U$ with $p'$-degree and $Q$ is a Sylow\r\nsubgroup of $U$.  It is known that all the vertex subgroups of\r\n$\\phi$ are conjugate in $G$. If $\\phi$ is induced from $\\tau \\in\r\n\\ibr H$, it is easy to see that a vertex for $\\tau$ is a vertex for\r\n$\\phi$.  Thus, $H$ contains some vertex $Q$ for $\\phi$.  Now,\r\ndifferent Brauer characters of $H$ that induce $\\phi$ may have\r\nvertex subgroups that are not conjugate in $H$ but are necessarily\r\nconjugate in $G$. Hence, one can ask the following question: Suppose\r\n$\\phi \\in \\ibr G$ has vertex $Q$, and $Q \\le H$, how many characters\r\nin $\\ibr H$ with vertex $Q$ induce $\\phi$?  When either $|G|$ is odd\r\nor $G$ is solvable and $p = 2$, we can obtain an upper bound for\r\nthis question.\r\n\r\n\\begin{theorem} \\label{main}\r\nLet $G$ be a solvable group and $p$ a prime.  Assume either $|G|$ is\r\nodd or $p = 2$. Let $Q$ be a $p$-subgroup of $H$. If $\\phi \\in \\ibr\r\nG$, then the number of Brauer characters of $H$ with vertex $Q$ that\r\ninduce $\\phi$ is at most $|\\norm GQ:\\norm HQ|$.\r\n\\end{theorem}\r\n\r\nAt this time, we are not able to determine whether or not this\r\ntheorem is true if we loosen the hypothesis that either $|G|$ is odd\r\nor $p = 2$.  In other words, is the conclusion still true if $G$ is\r\na solvable group of even order and $p$ is an odd prime. \r\n\r\n%%%%%%%%%%%%%%%%%%INSERT HERE\r\n\r\n\r\n\r\n%%%%%%%%%%%END INSERT\r\n\r\nThis result\r\nwas motivated by our work with J. P. Cossey. If we could prove the\r\nconclusion of Theorem \\ref{main} when $p$ is odd, then we would be\r\nable to prove J. P. Cossey's conjecture that the number of lifts of\r\na Brauer character is bounded by the index of a vertex subgroup in\r\nthe vertex subgroup when $p$ is odd. Our argument can be found in\r\nthe preprint \\cite{preprint}.\r\n\r\nWe would like to thank J. P. Cossey and I. M. Isaacs for several\r\nhelpful discussions while we were preparing this note.\r\n\r\n\\section{Results}\r\n\r\nWe will in the more general setting of irreducible $\\pi$-partial\r\ncharacters of a $\\pi$-separable group $G$.  We here briefly mention\r\nthat if $\\pi$ is a set of primes and $G$ is a $\\pi$-separable group,\r\none can define (see \\cite{pipart} for more details) a set of class\r\nfunctions $\\Ipi G$ from the set $G^o$ (which consists of the\r\nelements of $G$ whose order is divisible by only the primes in\r\n$\\pi$) to ${\\bf C}$ that plays the role of $\\ibr G$, and in fact\r\n$\\Ipi G = \\ibr G$ if $\\pi = \\{ p' \\}$, the complement of the prime\r\n$p$.\r\n\r\n%In this note, I fix a $\\pi$-partial character $\\phi$ and a subgroup\r\n%$V$ that contains a $\\pi'$-subgroup $Q$.  I obtain the upper bound\r\n%of $|\\norm GQ:\\norm VQ|$ on the number of $\\pi$-partial characters\r\n%of $V$ with vertex $Q$ that induce $\\phi$ under the assumption that\r\n%$G$ is solvable and either $|G|$ is odd or $2 \\not\\in \\pi$.\r\n%\r\n%Of course, the case I need for the work with JP is the case when $2\r\n%\\in \\pi$.  :-(\r\n\r\nWe start by considering vertices in Clifford correspondence (see\r\nProposition 3.2 of \\cite{Fong}).  Let $G$ be a $\\pi$-separable\r\ngroup. Let $N$ be a normal subgroup of $G$.   Fix $\\phi \\in \\Ipi G$.\r\nIf $\\alpha \\in \\Ipi N$ is a constituent of $\\phi_N$, then we write\r\n$G_\\alpha$ for the stabilizer of $\\alpha$ in $G$, and we write\r\n$\\phi_\\alpha$ for the Clifford correspondent of $\\phi$ with respect\r\nto $\\alpha$. In particular, the vertices of the Clifford\r\ncorrespondent form an orbit under the action of the normalizer of a\r\nparticular vertex.\r\n\r\n\\begin{lemma}\\label{cliff}\r\nLet $G$ be a $\\pi$-separable group.  Let $N$ be a normal subgroup of\r\n$G$.  Suppose that $\\alpha \\in \\Ipi N$.  Let $\\phi \\in \\Ipi G$ and\r\n$\\hat\\phi \\in \\Ipi {G_\\alpha}$ so that $\\hat\\phi^G = \\phi$.  Suppose\r\nthat $Q$ is a vertex for $\\hat\\phi$.  Then $Q$ is a vertex is\r\n$\\hat\\phi^g$ if and only if there exists $n \\in \\norm GQ$ so that\r\n$G_\\alpha g = G_\\alpha n$.\r\n\\end{lemma}\r\n\r\n\\begin{proof}\r\nWe first suppose that there exists $n \\in \\norm GQ$ so that\r\n$G_\\alpha g = G_\\alpha n$.  Thus, $g = tn$ for some $t \\in\r\nG_\\alpha$.  We see that $\\hat\\phi^g = \\hat\\phi^{tn} = \\hat\\phi^n$.\r\nWe see that $Q = Q^n$ is a vertex for $\\hat\\phi^n = \\hat\\phi^g$.\r\n\r\nConversely, suppose that $Q$ is a vertex for $\\hat\\phi^g$.  Then\r\n$Q^{g^{-1}}$ is a vertex for $\\hat\\phi$.  Since $Q$ is also a vertex\r\nfor $\\hat\\phi$, we have $Q^{g^{-1}} = Q^t$ for some $t \\in\r\nG_\\alpha$.  It follows that $Q = Q^{tg}$, and so, $tg \\in \\norm GQ$.\r\nThis implies that $tg = n$ for some $n \\in \\norm GQ$.  This implies\r\nthat $n \\in G_\\alpha g$, and we conclude that $G_\\alpha n = G_\\alpha\r\ng$.\r\n\\end{proof}\r\n\r\nWe continue to work in the context of the Clifford correspondence.\r\nIn this case, we can get an exact count of the number of partial\r\ncharacters in $N$ whose Clifford correspondent has vertex $Q$.\r\n\r\n\\begin{corollary}\\label{cliff count}\r\nLet $G$ be a $\\pi$-separable group.  Let $N$ be a normal subgroup of\r\n$G$, let $\\phi \\in \\Ipi G$ have vertex $Q$, and suppose that $\\beta$\r\nis an irreducible constituent of $\\phi_N$ so that $\\phi_\\beta$ has\r\nvertex $Q$. Then $|\\{ \\alpha \\in \\Ipi N \\mid \\phi_\\alpha {\\textrm ~\r\nhas~vertex~} Q \\}| = |\\norm GQ : \\norm {G_\\beta}Q|$.\r\n\\end{corollary}\r\n\r\n\\begin{proof}\r\n%We know that $\\phi_\\beta$ has vertex $Q^*$. Observe that $Q^*$ is a\r\n%vertex for $\\phi$ so $(Q^*)^g = Q$ for some $g \\in G$.  Replacing\r\n%$\\beta$ by $\\beta^g$, we may assume that $Q^* = Q$, so $Q$ is a\r\n%vertex for $\\phi_\\beta$.\r\nBy Lemma \\ref{cliff}, we see that $\\phi_\\alpha$ has $Q$ as a vertex\r\nif and only if $\\alpha = \\beta^g$ where $g \\in G$ and $g \\in G_\\beta\r\nn$ for some $n \\in \\norm GQ$. Finally, we observe that $G_\\beta n_1\r\n= G_\\beta n_2$ if and only if $\\norm {G_\\beta}Q n_1 = \\norm\r\n{G_\\beta}Q n_2$ for $n_1, n_2 \\in \\norm GQ$.  We have $|\\{ \\alpha\r\n\\in \\Ipi N \\mid \\phi_\\alpha {\\textrm ~ has~vertex~} Q \\}| = | \\{ G_\\beta\r\nn \\mid n \\in \\norm GQ \\} | = |\\norm GQ :\\norm {G_\\beta}Q|$.\r\n\\end{proof}\r\n\r\nWe now look at the conditions of a minimal counterexample.  For this\r\nwe need to review and develop more notation.  We make use of the\r\ncanonical set of $\\pi$-lifts, $\\Bpi G$, that was defined in\r\n\\cite{pisep} by Isaacs.  In other words, $\\Bpi G \\subseteq \\irr G$\r\nand the map $\\chi \\mapsto \\chi^o$ is a bijection from $\\Bpi G$ to\r\n$\\Ipi G$.  Closely related to this set is the subnormal nucleus\r\nwhich also was defined in \\cite{pisep}.  To define the subnormal\r\nnucleus, we need the $\\pi$-special characters.  Let $G$ be a\r\n$\\pi$-separable group.  A character $\\chi \\in \\irr G$ is\r\n$\\pi$-special if $\\chi (1)$ is a $\\pi$-number and for every\r\nsubnormal group $M$ of $G$, the irreducible constituents of $\\chi_M$\r\nhave determinants that have $\\pi$-order.  Many of the basic results\r\nof $\\pi$-special characters can be found in Section 40 of\r\n\\cite{hupte} and Chapter VI of \\cite{Mawo}. One result that is\r\nproved is that if $\\alpha$ is $\\pi$-special and $\\beta$ is\r\n$\\pi'$-special, then $\\alpha \\beta$ is necessarily irreducible. We\r\nsay that $\\chi$ is {\\bf factored} if $\\chi = \\alpha \\beta$ where\r\n$\\alpha$ is $\\pi$-special and $\\beta$ is $\\pi'$-special.  We also\r\nnote that if $\\chi \\in \\Bpi G$ and $N$ is normal in $G$, then the\r\nirreducible constituents of $\\chi_N$ lie in $\\Bpi N$.\r\n\r\n%We need to define Dpi and then Cpi.  We also need to talk about the\r\n%magic character automorphism.\r\n\r\n%Next, we prove a simple lemma regarding $\\pi$-special characters\r\n%that essentially follows from \\cite{gajen} or Lemma 21.4 of\r\n%\\cite{Mawo}.  We should note that this lemma is not particularly\r\n%new.\r\n\r\n%\\begin{lemma} \\label{pispec}\r\n%Let $N \\le K$ be normal subgroups of a $\\pi$-separable group $G$.\r\n%Suppose that $K/N$ is a $p$-group for some prime $p$.  If $\\alpha\r\n%\\in \\irr N$ is $\\pi$-special, then all irreducible constituents of\r\n%$\\alpha^K$ lying in $\\Cpi K$ are $\\pi$-special.\r\n%\\end{lemma}\r\n\r\n\r\n%The proof needs to be changed for Cpi.\r\n%\\begin{proof}\r\n%If $p \\in \\pi$, then by Lemma 21.4 of \\cite{Mawo} all the\r\n%irreducible constituents of $\\alpha^K$ are $\\pi$-special, and the\r\n%result follows. Thus, we may assume that $p$ is not in $\\pi$. Thus,\r\n%$\\alpha (1) o(\\alpha)$ is coprime to $|K:N|$. By Corollary 6.28 of\r\n%\\cite{text}, $\\alpha$ extends to $K$, and $\\alpha$ has a unique\r\n%extension $\\beta$ with $o(\\beta) = o (\\alpha)$.  By Lemma 21.4 of\r\n%\\cite{Mawo}, $\\beta$ is $\\pi$-special.  On the other hand, we have\r\n%by Gallagher's theorem (Corollary 6.17 of \\cite{text}), the\r\n%irreducible constituents of $\\alpha^K$ have the form $\\beta \\nu$\r\n%where $\\nu \\in \\irr {K/N}$.  Since $K/N$ is a $\\pi'$-group, $\\nu$ is\r\n%$\\pi'$-special.  We now apply Lemma 5.4 of \\cite{pisep} to see that\r\n%a character in $\\Bpi K$ is factored if and only if it is\r\n%$\\pi$-special.  Since all the irreducible constituents of $\\alpha^K$\r\n%are $\\pi$-factored, the irreducible constituents of $\\alpha^K$ lying\r\n%in $\\Bpi K$ are $\\pi$-special.\r\n%\\end{proof}\r\n\r\nIf $\\chi \\in \\irr G$, Isaacs constructs the subnormal vertex as\r\nfollows.  Let $M$ be maximal so that $M$ is subnormal in $G$ and the\r\nirreducible constituents of $\\chi_M$ are factored.  Let $\\mu$ be an\r\nirreducible constituent of $\\chi_M$ and let $T$ be the stabilizer of\r\n$(M,\\mu)$ in $G$.  Isaacs proved in \\cite{pisep} that there is a\r\nClifford theorem for $T$.  In other words, there is a unique\r\ncharacter $\\tau \\in \\irr {T \\mid \\mu}$ so that $\\tau^G = \\chi$.  He\r\nalso proved that $(M,\\mu)$ is unique up to conjugacy, and so,\r\n$(T,\\tau)$ is unique up to conjugacy.  If $T = G$, then $\\chi$ is\r\n$\\pi$-factored and we take $(G,\\chi)$ to be the subnormal nucleus of\r\n$\\chi$.  If $T < G$, then inductively, the subnormal nucleus for\r\n$\\tau$ is the subnormal nucleus for $\\chi$.  We write $(W,\\gamma)$\r\nfor the subnormal nucleus of $\\chi$, and Isaacs showed that\r\n$\\gamma^G = \\chi$, $\\gamma$ is factored, and $(W,\\gamma)$ is unique\r\nup to conjugacy.  A character $\\chi \\in \\irr G$ is in $\\Bpi G$ if\r\nand only if the character of its nucleus is $\\pi$-special.\r\n\r\nIf $Q$ is a $\\pi'$-subgroup of $G$, then we use $\\Ipi {G \\mid Q}$ to\r\ndenote the $\\pi$-partial characters in $\\Ipi G$ that have vertex\r\n$Q$.  If $\\phi \\in \\Ipi G$ and $V \\le G$, then we write $\\IIpi\r\n{\\phi}VQ = \\{ \\eta \\in \\Ipi {V \\mid Q} \\mid \\eta^G = \\phi \\}$.  We\r\nnow find details about properties of a minimal counterexample.  We\r\nwill see that a counterexample cannot occur when either $|G|$ is odd\r\nor $2$ is not in $\\pi$.  Our goal is find enough information so that\r\nwe can either find a contradiction or build an example when $|G|$ is\r\neven and $2 \\in \\pi$.\r\n\r\n\\begin{theorem} \\label{min counter}\r\nLet $G$ be a solvable group.  Assume $\\phi \\in \\Ipi G$ has vertex\r\n$Q$, let $V$ be a subgroup of $G$, and let $N$ be the core of $V$ in\r\n$G$. If $G$ and $V$ are chosen so that $|G| + |G:V|$ is minimal\r\nsubject to the condition that $|\\IIpi {\\phi}VQ| > |\\norm GQ:\\norm\r\nVQ|$, then the following are true:\r\n\r\n\\begin{enumerate}\r\n\\item $V$ is a nonnormal maximal subgroup of $G$,\r\n\\item $|G:V|$ is a power of $2$,\r\n\\item $2 \\in \\pi$,\r\n\\item $Q \\le V$,\r\n\\item $\\phi_N = a \\alpha$ for some $\\alpha \\in \\ibr N$,\r\n\\item $\\alpha (1)$ is a $\\pi$-number,\r\n\\item if $K$ is normal in $G$ so that $K/N$ is a chief factor for\r\n$G$, then $\\alpha$ is fully ramified with respect to $K/N$.\r\n\\end{enumerate}\r\n\\end{theorem}\r\n\r\n\\begin{proof}\r\nIf either $V = G$ or $\\IIpi {\\phi}VQ$ is empty, then $|\\IIpi\r\n{\\phi}VQ| \\le |\\norm GQ:\\norm VQ|$ contradicting the hypotheses.\r\nThus, $V < G$ and $\\IIpi {\\phi}VQ$ is not empty, and so, $Q \\le V$\r\nand there exist characters in $\\Ipi V$ that induce $\\phi$ and have\r\nvertex $Q$.\r\n\r\nWe begin by showing that $V$ is a maximal subgroup.  Suppose that $V\r\n< M < G$ for some subgroup $M$.  Let $\\IIpi {\\phi}MQ = \\{ \\eta_1,\r\n\\dots, \\eta_m \\}$.  Using minimality, we have $m = |\\IIpi {\\phi}MQ|\r\n\\le |\\norm GQ:\\norm MQ|$. Suppose that $\\zeta \\in \\IIpi {\\phi}VQ$,\r\nthen $\\zeta^M \\in \\Ipi M$ and $\\zeta^M$ has $Q$ as a vertex.  Since\r\n$(\\zeta^M)^G = \\zeta^G = \\phi$, we see that $\\zeta^M \\in \\IIpi\r\n{\\phi}MQ$.  It follows that $\\zeta^M = \\eta_i$ for some $i$.  We\r\nconclude that $|\\IIpi {\\phi}VQ| \\le \\sum_{i=1}^m |\\IIpi\r\n{\\eta_i}VQ|$.  Since this contradicts our hypothesis, we obtain\r\n$|\\IIpi {\\eta_i}VQ| \\le |\\norm MQ:\\norm VQ|$.  We deduce that\r\n$$\r\n|\\IIpi {\\phi}VQ| \\le m|\\norm MQ:\\norm VQ| \\le\r\n|\\norm GQ:\\norm MQ||\\norm MQ: \\norm VQ| = |\\norm GQ:\\norm VQ|.\r\n$$\r\nSince this violates the hypotheses, $V$ is maximal in $G$.\r\n\r\nIf $V$ is normal in $G$, then either $\\phi$ is induced from $V$ or\r\n$\\phi$ restricts irreducibly to $V$.  If $\\phi$ is induced from $V$,\r\nthen we can apply Corollary \\ref{cliff count} to see that $|\\IIpi\r\n{\\phi}VQ| \\le |\\norm GQ:\\norm VQ|$ in violation of the hypotheses.\r\nIf $\\phi$ restricts irreducibly, then it cannot be induced from $V$,\r\nand we have seen that this is also a contradiction.  We conclude\r\nthat $V$ is not normal in $G$.\r\n\r\nSuppose $\\alpha \\in \\Ipi N$ is a constituent of $\\phi_N$.  We use\r\n$\\phi_\\alpha \\in \\Ipi {G_\\alpha \\mid \\alpha}$ to denote the Clifford\r\ncorrespondent for $\\phi$ with respect to $\\alpha$ (see Proposition\r\n3.2 of \\cite{Fong} again).   Write $\\{ \\alpha \\in \\Ipi N \\mid\r\n\\phi_\\alpha {\\textrm ~has~vertex~} Q \\} = \\{ \\alpha_1, \\dots, \\alpha_k\r\n\\}$, and let $\\phi_i = \\phi_{\\alpha_i}$ and $G_i = G_{\\alpha_i}$. By\r\nLemma \\ref{cliff count}, we know that $k = |\\norm GQ:\\norm {G_i}Q|$.\r\n\r\nSuppose $\\eta \\in \\IIpi {\\phi}VQ$.  Denote $\\{ \\beta \\in \\Ipi N \\mid\r\n\\eta_\\beta {\\textrm ~has~vertex~} Q \\} = \\{ \\beta_1, \\dots, \\beta_l \\}$,\r\nand let $\\eta_j = \\eta_{\\beta_j}$ and $V_j = V_{\\beta_j}$.  By Lemma\r\n\\ref{cliff count}, $l = |\\norm VQ: \\norm {V_i}Q|$.\r\n\r\nWe see that $(\\eta_j)^G = ((\\eta_j)^V)^G = \\eta^G = \\phi$.  This\r\nimplies that $(\\eta_j)^{G_{\\beta_j}}$ is irreducible and has vertex\r\n$Q$.  It follows that $\\beta_j = \\alpha_{i_j}$ for some $i_j$.  We\r\nobtain $G_{\\beta_j} = G_{i_j}$ and $(\\beta_j)^{G_{i_j}} =\r\n\\alpha_{i_j}$. Observe that $V_j = G_{i_j} \\cap V$, and we denote\r\nthis subgroup by $V^*_{i_j}$.\r\n\r\nNow, we assume that $k > 1$, and we start to count.  We see that\r\n$\\eta \\in \\IIpi {\\phi}GQ$ is induced by $|\\norm VQ:\\norm\r\n{V^*_{i_j}}Q|$ partial characters in $\\bigcup \\IIpi\r\n{\\phi_i}{V^*_i}Q$.  Because $G_i < G$, we may use minimality of $|G|\r\n+ |G:V|$ to deduce $|\\IIpi {\\phi_i}{V^*_i}Q| \\le |\\norm {G_i}Q:\\norm\r\n{V^*_i}Q|$. We compute\r\n$$\r\n|\\IIpi {\\phi}VQ| = \\sum_{i=1}^k \\frac 1{|\\norm VQ:\\norm {V^*_i}Q|}\r\n|\\IIpi {\\phi_i}{V^*_i}Q| \\le \\sum_{i=1}^k \\frac 1{|\\norm VQ:\\norm\r\n{V^*_i}Q|} |\\norm {G_i}Q:\\norm {V^*_i}Q|.\r\n$$\r\nWe determine that\r\n$$\r\n\\frac 1{|\\norm VQ:\\norm {V^*_i}Q|} |\\norm {G_i}Q:\\norm {V^*_i}Q| =\r\n\\frac {|\\norm {G_i}Q|}{|\\norm VQ|},\r\n$$\r\nfor each $i$.   Notice that\r\n$|\\norm {G_i}Q| = |\\norm {G_1}Q$ for all $i$ and $k = |\\norm GQ:\r\n\\norm {G_1} Q$. This yields\r\n$$\r\n|\\IIpi {\\phi}VQ| \\le \\sum_{i=1}k \\frac {|\\norm {G_1}Q}{\\norm VQ} =\r\n\\frac {|\\norm GQ:\\norm {G_1}Q| |\\norm {G_1}Q|}{|\\norm VQ|} = |\\norm\r\nGQ:\\norm VQ|.\r\n$$\r\nThis contradicts the hypothesis.  We deduce that $k = 1$, and\r\n$\\alpha$ is invariant in $G$.\r\n\r\nSet $\\alpha = \\alpha_1$, and let $\\alpha^*$ be the character in\r\n$\\Bpi N$ satisfying $(\\alpha^*)^o = \\alpha$.  Write $(W,\\hat\\alpha)$\r\nfor the nucleus of $\\alpha^*$, and take $T$ to be the stabilizer of\r\n$(W,\\hat\\alpha)$ in $G$. By Lemma 2.3 of \\cite{Laradji}, there is a\r\nunique character $\\hat\\phi \\in \\IIpi {}T{\\hat\\alpha}$ so that\r\n$\\hat\\phi^G = \\phi$ and $Q$ is a vertex for $\\hat\\phi$.  Similarly,\r\nif $\\eta \\in \\IIpi {\\phi}VQ$, then there is a unique character\r\n$\\hat\\eta \\in \\IIpi {}{T \\cap V}{\\hat\\alpha}$ so that $\\hat\\eta^V =\r\n\\eta$ and $Q$ is a vertex for $\\hat\\eta$. Observe that $\\hat\\eta^T\r\n\\in \\IIpi {}T{\\hat\\alpha}$ and induces $\\phi$, so $\\hat\\eta^T =\r\n\\hat\\phi$.  It follows that $|\\IIpi {\\phi}VQ| = |\\IIpi {\\hat\\phi}{T\r\n\\cap V}Q|$.  If $T < G$, then we can use the minimality of $|G| +\r\n|G:V|$ to see that $|\\IIpi {\\hat\\phi}{T \\cap V}Q| \\le |\\norm TQ:\r\n\\norm {V \\cap T}Q|$.  By the diamond lemma, we have $|\\norm TQ:\r\n\\norm {V \\cap T}Q| = |\\norm TQ: V \\cap \\norm TQ| \\le |\\norm GQ :\r\n\\norm VQ|$.  This contradicts the hypotheses, and so $T = G$.\r\n\r\nWe now have that $(W,\\hat\\alpha)$ is $G$-invariant.  By the\r\nconstruction of the subnormal, this implies that $W = N$.  Since\r\n$\\alpha^* \\in \\Bpi N$, the nucleus for $\\alpha^*$ has a character\r\nthat is $\\pi$-special.  Thus, $\\hat\\alpha$ is $\\pi$-special, and\r\nsince $W = N$, we see that $\\hat\\alpha = \\alpha^*$.  In particular,\r\n$\\hat\\alpha$ is $\\pi$-special.  We deduce that $\\alpha (1)$ is a\r\n$\\pi$-number.\r\n\r\nTake $K$ normal in $G$ so that $K/N$ is a chief factor for $G$. This\r\nis the point where we use the fact that $G$ is solvable to see that\r\n$G = VK$ and $V \\cap K = N$ where $K/N$ is an elementary abelian\r\n$p$-group for some prime $p$.  (This is the only place we use the\r\nhypothesis that $G$ is solvable in place of $G$ being\r\n$\\pi$-separable.)\r\n%By Lemma \\ref{pispec}, the constituents of\r\n%$(\\alpha^*)^K$ that lie in $\\Cpi K$ are $\\pi$-special.\r\n%, then the irreducible constituents of  ${\\phi^*}_K$ lie in $\\Cpi K$.  Notice\r\n%that some irreducible constituent $\\delta$ of ${\\phi^*}_K$ is a\r\n%constituent of $(\\alpha^*)^K$.  Since $\\delta$ is a constituent of\r\n%$(\\alpha^*)^K$ and $\\delta \\in \\Bpi K$, we see that $\\delta$ must be\r\n%$\\pi$-special, and so, all the irreducible constituents of\r\n%$(\\phi^*)_K$ are $\\pi$-special.\r\n%\r\n%This needs more explanation.\r\n%It follows that $Q \\cap K$ is a Hall $\\pi$-complement of $L$.  Since\r\n%$Q \\cap K \\le N$, it follows that $K/N$ is a $\\pi$-group and $p \\in\r\n%\\pi$.\r\n%\r\nLet $L/K$ be a chief factor for $G$.  We know that $(|L:K|,|K:N|) =\r\n1$ and $\\cent {L \\cap V/N}{K/N}$.  (See Lemma 5.1 of \\cite{max} for\r\na proof of this.)  By Problem 6.12 of \\cite{text}, either $\\alpha^*$\r\nextends to $K$ or $\\alpha^*$ is fully-ramified with respect to\r\n$K/N$.  .\r\n\r\nSuppose first that $\\alpha^*$ extends to $K$. Notice that\r\nmultiplication by $\\irr {K/L}$ is a transitive action on the\r\nirreducible constituents of $(\\alpha^*)^K$.  Also, $(V \\cap K)/L$\r\nacts on compatibly on the irreducible constituents of $(\\alpha^*)^K$\r\nand on $\\irr {K/L}$ where the action on $\\irr {K/L}$ is coprime.  We\r\ncan use Glauberman's lemma (Lemma 13.8 of \\cite{text}) to see that\r\n$\\alpha^*$ has a $V \\cap L$-invariant extension.  The corollary to\r\nGlauberman's lemma (Corollary 13.9 of \\cite{text}) can be applied to\r\nsee that $\\alpha^*$ has a unique $V \\cap L$-invariant extension\r\n$\\delta$. Since $V$ permutes the $V \\cap L$-extensions of\r\n$\\alpha^*$, it follows that $\\delta$ is $V$-invariant.  We now use\r\nCorollary 4.2 of \\cite{pisep} to see that restriction is a bijection\r\nfrom $\\irr {G \\mid \\beta}$ to $\\irr {V \\mid \\alpha^*}$.\r\n\r\nLet $\\eta \\in \\IIpi {\\phi}VQ$ so that $\\eta^G = \\phi$.  We can find\r\n$\\eta^* \\in \\Bpi V$ so that $(\\eta^*)^o = \\eta$. Since\r\n$({\\eta^*}^G)^o = ({\\eta^*}^o)^G = \\eta^G = \\phi \\in \\ibr G$, we see\r\nthat $\\eta^G$ is irreducible.  On the other hand, $({\\eta^*}^o)_N =\r\n(\\eta_N)^o = b \\alpha$ for some integer $b$.  Since the irreducible\r\nconstituents of ${\\eta^*}_N$ lie in $\\Bpi N$, we deduce that $\\eta^*\r\n\\in \\irr {V \\mid \\alpha^*}$.  But we saw that this implies that\r\n$\\eta^*$ extends to $G$.  Since $V < G$, it is not possible for\r\n$\\eta^*$ to both extend to $G$ and induce irreducibly.  Therefore,\r\nwe have a contradiction.  We see that $\\alpha^*$ (and hence,\r\n$\\alpha$) is fully ramified with respect to $K/N$.  Notice that if\r\n$p$ is not in $\\pi$, then Corollary 6.28 of \\cite{text} applies and\r\n$\\alpha^*$ extends to $K$. Therefore, $p \\in \\pi$.\r\n\r\n%Suppose $|G|$ is odd or $2 \\in \\pi$, and let $\\eta^* \\in \\Bpi V$. We\r\n%know that $({\\eta^*}^G)^\\sigma = ({\\eta^*}^\\sigma)^G = (\\eta^*)^G$\r\n%and .  It follows that $\\eta^* \\in \\Bpi G$. We conclude that\r\n%$(\\eta^*)^G = \\phi^*$.\r\n%We need more details here\r\n%We now suppose $2 \\not\\in \\pi$, and we let $\\eta^* \\in \\Dpi V$ so\r\n%that $(\\eta^*)^o$. We see that $(s_{(G:V)} \\eta^*)^G = \\phi^*$.  In\r\n%either case, $\\phi^*$ is induced from $V$ and this is a\r\n%contradiction.\r\nWe suppose that $p$ is odd, and we work for a contradiction.  Since\r\n$\\alpha^*$ is fully-ramified with respect to $K/N$ and $|K:N|$ has\r\nodd order, main theorem of \\cite{fram} implies that no character in\r\n$\\irr {V \\mid \\alpha}$ induces irreducibly to $G$.  (A stronger\r\ntheorem is proved in \\cite{brown}.) As in the previous paragraph,\r\nthis implies that $\\phi$ is not induced from $V$ which contradicts\r\nthe assumption that $\\IIpi {\\phi}VQ$ is not empty. (This strongly\r\nuses the fact that $p$ is odd. When $p = 2$, it is tempting to try\r\nuse the correspondence in \\cite{strong}, but that correspondence\r\ndoes not preclude inducing characters in $\\irr {G \\mid \\alpha}$ from\r\n$V$. In fact, ${\\textrm GL}_2 (3)$ is an example where this occurs.) We\r\nconclude that $p = 2$. Since $|G:V| = |K:N|$, we see that $|G:V|$ is\r\na power of $2$. This proves the theorem.\r\n\\end{proof}\r\n\r\nAs a corollary, we obtain Theorem \\ref{main} stated for\r\n$\\pi$-partial characters.\r\n\r\n\\begin{corollary}\r\nLet $G$ be a solvable group.  Assume either $|G|$ is odd or $2\r\n\\not\\in \\pi$.  Let $Q$ be a $\\pi'$-subgroup of $G$ and suppose that\r\n$Q \\le V$.  If $\\phi \\in \\Ipi G$, then $|\\IIpi {\\phi}VQ| \\le |\\norm\r\nGQ:\\norm VQ|$.\r\n\\end{corollary}\r\n\r\n\\begin{proof}\r\nWe suppose the result is not true.  Let $G$ be a counterexample with\r\n$|G| + |G:V|$ as in Theorem \\ref{min counter}.  By that result, we\r\nhave that $|G:V|$ is a nontrivial power of $2$ which is a\r\ncontradiction if $|G|$ is odd.  We also have $2 \\in \\pi$ which is a\r\ncontradiction to $2 \\not\\in \\pi$.  This proves the corollary.\r\n\\end{proof}\r\n\r\n\\begin{thebibliography}{99}\r\n\r\n\\bibitem{preprint} J.~P.~Cossey and M.~L.~Lewis, Counting lifts of\r\n        Brauer characters, $\\langle$arXiv:1007.3011v1$\\rangle$\r\n\r\n\\bibitem{hupte} B. Huppert, ``Character Theory of Finite Groups,''\r\n         Walter de Gruyter, Berlin, 1998.\r\n\r\n\\bibitem{gajen} D. Gajendragadkar, A characteristic class of\r\n    characters of finite $\\pi$-separable groups,\r\n    {\\it J. Algebra} {\\bf 59} (1979), 237-259.\r\n\r\n\\bibitem{brown}   I.~M.~Isaacs, Characters of solvable and symplectic groups,\r\n                  {\\it Amer. J. Math.} {\\bf 95} (1973), 594-635.\r\n\r\n\\bibitem{text}    I.~M.~Isaacs, ``Character Theory of Finite\r\n        Groups,'' Academic Press, San Diego, California, 1976.\r\n\r\n\\bibitem{strong}  I.~M.~Isaacs, Character correspondences in\r\n                  solvable groups, {\\it Adv. Math.} {\\bf 43} (1982),\r\n                  284-306.\r\n\r\n\\bibitem{fram}    I.~M.~Isaacs, On the character theory of fully ramified sections,\r\n                  {\\it Rocky Mountain J. Math.} {\\bf 13} (1983),\r\n                  689-698.\r\n\r\n\\bibitem{pisep}   I.~M.~Isaacs, Characters of $\\pi$-separable groups,\r\n                  {\\it J. Algebra} {\\bf 86} (1984), 98-128.\r\n\r\n\\bibitem{Fong}    I.~M.~Isaacs, Fong characters in $\\pi$-separable\r\n        groups, {\\it J. Algebra} {\\bf 99} (1986), 89-107.\r\n\r\n\\bibitem{pipart}  I.~M.~Issacs, Partial characters of $\\pi$-separable\r\n        groups.  In: Representation Theory of Finite Groups\r\n        and Finite Dimensional Algebras (Bielefield, 1991) in Progr. Math,\r\n        vol. 95, Birkhauser, Basel, 1991, 273-287.\r\n\r\n\\bibitem{Laradji} A.~Laradji, On normal subgroups and simple modules\r\n        with a given vertex in a $p$-solvable group, {\\it J. Algebra}\r\n        {\\bf 308} (2007), 484-492.\r\n\r\n\\bibitem{max}    M.~L.~Lewis, Characters of maximal subgroups of\r\n       $M$-groups, {\\it J. Algebra} {\\bf 183} (1996), 864-897.\r\n\r\n\\bibitem{Mawo} O. Manz and T. R. Wolf, ``Representation of Solvable\r\n        Groups,'' Cambridge University Press, Cambridge, 1993.\r\n\r\n\\end{thebibliography}\r\n\\end{document}\r\n", "meta": {"hexsha": "135a1cffee6ef2d2a4b3ac7b6b2a136d91135bc7", "size": 27522, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "benchmark/src/with-lang/empty-lang/1008.1633-bl.tex", "max_stars_repo_name": "e-sim/pdf-text-extraction-benchmark", "max_stars_repo_head_hexsha": "42eede9867e5795a6fc040b0a7ce92da3ddd3120", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-08-23T19:07:01.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-23T19:07:01.000Z", "max_issues_repo_path": "benchmark/src/with-lang/empty-lang/1008.1633-bl.tex", "max_issues_repo_name": "e-sim/pdf-text-extraction-benchmark", "max_issues_repo_head_hexsha": "42eede9867e5795a6fc040b0a7ce92da3ddd3120", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmark/src/with-lang/empty-lang/1008.1633-bl.tex", "max_forks_repo_name": "e-sim/pdf-text-extraction-benchmark", "max_forks_repo_head_hexsha": "42eede9867e5795a6fc040b0a7ce92da3ddd3120", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.8858603066, "max_line_length": 84, "alphanum_fraction": 0.6384347068, "num_tokens": 9679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.32629314705710766}}
{"text": "\\documentclass{article}\n\\title{Differential Geometry Notes}\n\\author{Lucas Simon}\n\\date{\\copyright\\ 2015 Markus Pflaum, All Rights Reserved} \n\n\\usepackage{amsmath}\n\\usepackage{amsfonts}\n\\usepackage{amssymb}\n\\usepackage{amsthm}\n\\usepackage{hyperref}\n\\usepackage{tikz}\n\\usepackage{tikz-cd}\n\\usepackage{mathrsfs}\n\\usepackage[all]{xy}\n\n\\newcommand{\\cat}[1]{\\textbf{#1}}\n\\newcommand\\Lie{\\mathcal{L}}\n%\\newcommand{\\det}[1]{\\text{det}(#1 )}\n\n\\begin{document}\n\n\\maketitle\n\n\\section{Notice}\nThese notes contain errors. Please put an issue on github or just fork the repository and make the changes yourself.\n\n\\section{March 6, 2015}\n\nIf we have $f:M \\to N$ and $q \\in N$. The claim was $f^{-1}(q) \\subset M$ is a submanifold. We have to find charts. Let $p \\in f^{-1}(q)$. By the rank theorem on charts, there are charts $(U, x)$ around $p$ and $(V,y)$ around $q$ such that $x(p) = 0$ and $y(q) = 0$, and $y \\circ f \\circ x^{-1}(v)=(v_1, \\ldots, v_n)$. for $v$ in a neighborhood of origin in $\\mathbb{R}^m$. For $v$ in a neighborhood of origin in $\\mathbb{R}^m$ the chart we are looking for, find $f^{-1}(q)$ is $(x_{n+1}, \\ldots, x_m)$. Then $f^{-1}(q) \\cap U = (x_{n+1}, \\ldots, x_m)^{-1}(\\mathbb{R}^{m-n})$\n\n\\textbf{Theorem (Ehresmann):} A proper surjective submersion is a fiber bundle with fiber\n\n\\textbf{Orientation:} Let $M$ be a smooth connected $m$-manifold. and let $\\Lambda^kT^*M \\sim O_N := \\{ \\omega_p \\in \\Lambda^kT^*M | p \\in M \\text{ and } \\omega_p \\neq 0\\} \\subset \\Lambda^m T^*M$. These $\\omega$'s are nonzero in some fiber. Then $\\text{dim}\\Lambda^m T^*_pM = 1$, this is the space of determinants. This is a subspace. A manifold $M$ is called \\textbf{orientable} if $\\Lambda^k T^*M \\sim 0_M$ has exactly two connected components. An \\textbf{orientation} of an orientable smooth manifold $M$ is a choice of a component of $\\Lambda^kT^*M \\sim 0_M$.\n\nThe zero section of a vector bundle $p:V \\to M$ is a $M \\to v, p \\mapsto 0_p$ where $0_M$ is the zero section of $\\Lambda^kT^*M$ or better its image. \n\nThe tangent bundle recap: take $TM$ of some smooth manifold $M$, and let $(U,x)$ and $(V,y)$ be smooth charts such that $U \\cap V \\neq \\varnothing$. Then $x \\circ x^{-1}|_{U \\cap V}:x(U \\cap V) \\to y(U \\cap V)$ are smooth transition maps of $M$. Then the induced map on trivializations $x(U \\cap V)\\times \\mathbb{R}^m \\to y(U \\cap V)\\times \\mathbb{R}^m$ where $(p,v) \\mapsto (y \\circ x^{-1}(p), D(y \\circ x^{-1})(p)v)$\n\n\\textbf{Counterexample:} Mobius band.\n\n\\textbf{Example:} Chiral molecules have a defined orientation. Similar, but not the same.\n\n\\textbf{Theorem:} Let $M$ be a connected smooth $m$-manifold. Then the following are equivalent:\n\n(1) $M$ is orientable\n\n(2) There is an atlas $\\mathcal{A}$ of $M$ such that the det($D(x \\circ y^{-1})(y(p))) > 0$   for each $(U,x), (V,y) \\in \\mathcal{A}$ and $p \\in U \\cap V$\n\n(3) There is a nowhere vanishing $m$-form $\\omega \\in \\Omega^m(M)$.  \n\nProof: $(1) \\Rightarrow (2)$ Let $\\Lambda$ be an orientation have have $\\Lambda \\cap \\Lambda^mT^*_pM \\sim 0_p$ is a component of $\\Lambda^mT^*_pM \\sim 0_p$ Define $\\mathcal{A}$ be the set of all charts $(U,x)$ of $M$ such that $dx_1 \\wedge \\cdots \\wedge dx_m(p) \\in \\Lambda$ for all $p \\in U$. Assume also that each $U$ is connected. We need to compute the transition functions to check ....WHAT?..... Let $(V,y)$ be a second chart from $\\mathcal{A}$ such that $p \\in U \\cap V$ then \n\\[\ndx_1 \\wedge \\cdots \\wedge dx_m |_p = \\text{det}(\\frac{\\partial x_k}{\\partial y_j})(p)dy_1 \\wedge \\cdots \\wedge dy_m|p\n\\] \nSince $\\text{det}(\\frac{\\partial x_k}{\\partial y_j})(p) = \\text{det}(D(x \\circ y^{-1})(y(p))) > 0$. hence the transition functions are positive.\n\n\\section{March 9, 2015}\n\n\\textbf{Theorem} Let $M$ be a connected manifold. The following are equivalent\n\n(1) $M$ is orientable\n\n(2) There exists an atlas $\\mathscr{A}$ of $M$ such that the detereminant of $D(x \\circ y^{-1})(y(p)) > 0$ for all $(U,x), (V,y) \\in \\mathscr{A}$ and $p \\in U \\cap V$.\n\n(3) There is a nowhere vanishing $\\omega \\in \\Omega^m(M)$ with $m = \\text{dim}(M)$.\n\\begin{proof}\n$(2) \\Rightarrow (3)$.  Under the hypotheses of $(2)$. Chose a smooth partition of unity $(\\phi_i)_{i \\in \\mathbb{N}}$ of $M$ subordinate to $\\mathscr{A}$; that is, for each $i \\in \\mathbb{N}$ there is $(U_i, x^{(i)}) \\in \\mathscr{A}$ such that $\\text{supp}(\\phi_i) \\subset U$ is relatively compact; that is, it's closure is compact and contained in $U$. ($\\sum \\phi_i = 1$, (supp($\\phi_i$)) is locally finite). Put $\\omega := \\sum_{i \\in \\mathbb{N}} \\phi_i \\cdot dx_1^{(i)} \\wedge \\cdots \\wedge dx_m^{(i)}$. If $p \\in U^{(i)} \\cap U^{(j)}$, then $dx_1^{(i)} \\wedge \\cdots \\wedge dx_m^{(i)} = \\lambda_{ij}dx_1^{(j)}\\wedge \\cdots \\wedge dx_m^{(j)}$ where $\\lambda_{ij} = \\text{det}(D(x^{(i)} \\circ x^{(j)-1}) (x^{(j)}(p)) > 0$. Then $\\omega(p) = (\\sum_{i \\in \\mathbb{N}} \\phi_j(p) \\lambda_{ji}(p))dx_1^{(j)}\\wedge \\cdots \\wedge dx_m^{(m)}(p)$. Since each term is greater than $0$.\n\n$(3) \\Rightarrow (1)$. Under the hypotheses of (3), there is a nowhere vanishing $\\omega \\in \\Omega^m(M)$ such that $\\omega(p)$ is nonzero for all $p \\in M$. Then $\\Lambda^mT^*M \\sim 0_m$ is the union of $\\Lambda^+ := \\{ \\rho \\in \\lambda^m T^*M : \\rho = \\lambda \\cdot \\omega_{\\pi(\\rho)} \\text{ for some } \\lambda > 0 \\}$ and $\\Lambda^- := \\{ \\rho \\in \\lambda^m T^*M : \\rho = \\lambda \\cdot \\omega_{\\pi(\\rho)} \\text{ for some } \\lambda < 0 \\}$. Notice $\\Lambda^+ \\cap \\Lambda^- = \\varnothing$. Then show $\\Lambda^+$ and $\\Lambda^-$ are path connected. Take $(p, \\rho)$ and $(q, \\tau)$. We may connect $\\rho$ by a path to $\\omega(p)$ where $\\gamma(t) = (\\lambda(1-t) + t)\\omega(p) + \\rho = \\lambda\\omega(p)$ where $\\lambda > 0$. Then, $\\omega(p)$ may be connected by a path with $\\omega(q)$ by taking $\\tilde{\\gamma}(t)$ a path where $\\tilde{\\gamma}(0) = p$ and $\\tilde{\\gamma}(1) = q$ and put $\\gamma(t) = \\omega(\\tilde{\\gamma}(t))$. We do this so we can integrate on $M$.\n\n\\end{proof}\n\nWe have orientation so we may properly integrate. Reminder: $D \\subset \\mathbb{R}^n$ is open and bounded, $\\phi: D \\to \\tilde{D} \\subset \\mathbb{R}^n$ is a diffeomorphism, and $f: \\phi(D) \\to \\mathbb{R}$ a continuous function, then\n\\[\n\\int_{\\phi(A)}f = \\int_{A}f \\circ \\phi |\\text{det}(D\\phi)| \\text{ (transformation formula)}\n\\]  \nCHECK OUT PAGE 264 TU\n\nAssume $\\omega \\in \\Omega^n(\\tilde{D})$. Then $\\omega = f dx_1 \\wedge \\cdots \\wedge dx_n$ for some $f \\in C^\\infty(\\tilde{D})$. Put $\\tilde{A} = \\phi(A)$, and define\n\\[\n\\int_{\\tilde(A)}\\omega := \\int_{\\tilde{A}}f\n\\]\ncondsider $\\phi^*(\\omega) \\in \\Omega^n(D)$. Then $\\phi^*(f dx_1 \\wedge \\cdots \\wedge dx_n) = (f \\circ \\phi)\\cdot \\text{det}(D\\phi) \\cdot dx_1 \\wedge \\cdots \\wedge dx_n$ \n\nLet $M$ be an oriented manifold and $\\mathscr{A}$ an oriented atlas. Choose a partition of unity $(\\phi_i)_{i \\in \\mathbb{N}}$ subordinate to $\\mathscr{A}$. For each $\\omega \\in \\Omega^m_c(M)$, put \n\\[\n\\int_M \\omega = \\sum_{i \\in \\mathbb{N}} \\int_{\\tilde{U_i}} \\phi_ix^{-1*}\\omega\n\\]\nProve this is independent of atlas.\n\n\\section{March 11, 2015}\n\\textbf{Notations:}\n\n(1) Denote $\\mathbb{H}^n$ as the upper-half space which is the set $\\{ (x_1, \\ldots, x_n) \\in \\mathbb{R}^n | x_1 \\geq 0 \\}$.\n\n(2) The interior of a manifold with boundary is denoted $M^\\circ = M \\sim \\partial M$.\n\n\\textbf{Definition:} A \\textbf{manifold with boundary} $M$ is a topolgical space which is Hausdorff and second countable subject to the following conditions: \n\n(1) A chart of $M$ in $\\mathbb{H}^n$ is a homeomorphism $x: U \\subset M \\to \\hat{U} \\subset \\mathbb{H}^n$ where $U, \\hat{U}$ are open.\n\n(2) Two charts $(U, x), (V,y)$ of $M$ in $\\mathbb{H}^n$ are called $C^\\infty$-compatible charts if $x \\circ y^{-1}|_{U \\cap V}: y(U \\cap V) \\to x(U \\cap V)$ is a $C^\\infty$-diffeomorphism.\n\n(3) An atlas of $M$ in $\\mathbb{H}^n$ consists of a set of $C^\\infty$-compatible charts in $\\mathbb{H}^n$ which cover $M$.\n\n(4) A maximal atlas $\\mathscr{A}$\n\n\\textbf{Definition:} Let $M$ be a manifold with boundary. Define $\\partial M \\subset M$ as the set of points $p \\in M$ such that there is a chart $(U, x)$ around $p$ with $x(p) = (0, x_2(p), \\ldots, x_n(p))$ with $p \\in x^{-1}(\\{ 0 \\}\\times \\mathbb{R}^{n-1}$.\n\n\\textbf{Observations:}\n\n(1) $\\partial M$ is a manifold of dimension $n-1$. It's atlas is given by charts $(U\\cap M, \\bar{x}|_{U \\cap \\partial M})$ where $(U,x) \\in \\mathscr{A}$ and $p \\in V$, with $\\bar{x}(p) = (x_2(p), \\ldots, x_n(p))$ (from $(0, x_2(p), \\ldots, x_n(p))$). This gives us transition functions $\\bar{x} \\circ \\bar{y}^{-1}: \\bar{y}(U \\cap V \\cap \\partial M) \\to \\bar{x}(U \\cap V \\cap \\partial M)$ is a diffeomorphism.\n\n(2) The tangent spaces of the interior are obvious. On the boundary, using curves ends up being very technical. The space of derivations definition gives a more obvious definition of the tangent space on the boundary. So, $T_pM = \\text{Der}(C^\\infty_p, \\mathbb{R})$ for $p \\in \\partial M$. Then the tangent space is spanned by $\\{ \\frac{\\partial}{\\partial x_1}|_p, \\ldots, \\frac{\\partial}{\\partial x_n}|_p \\}$.\n\n(3) Orientation is defined in the same way. Notice that the boundary has an induced orientation. We get this from ...\n\n\\textbf{Theorem: (Stokes)} Given a compact oriented $m$-manifold $M$ with boundary. Then for each $\\omega \\in \\Omega^{m-1}(M)$ Then\n\\[\n\\int_{\\partial M} \\omega|_{\\partial M} = \\int_M d\\omega\n\\]\nwhere $\\partial M$ has the indeuced orientation.\n\n\\begin{proof} Recall the fundamental theorem of calculus:\n\\begin{align*}\n\\int_0^a \\frac{\\partial}{\\partial s} f(s, t_2, \\ldots, t_m) ds & = f(A, t_2, \\ldots, t_m) - f(0, t_2, \\ldots, t_m) \\\\\n& = \\int_{\\{ A \\}} f(t, t_2, \\ldots, t_n) dt - \\int_{\\{ 0 \\}}f(t, t_2, \\ldots t_n)dt \\\\\n\\end{align*}\nNow, let $Q \\subset \\mathbb{H}^n$ be a cube; that is, $Q = [a_1, b_1] \\times \\cdots [a_n, b_n]$ with $a_1 \\geq 0$ and $a_2,\\ldots a_n \\in \\mathbb{R}$, $b_i > a_i$ for all $i \\in \\{ 1, \\ldots, n \\}$. Let $\\omega \\in \\Omega^{m-1}(Q)$ with the support of $\\omega$ compactly contained in $Q$. Locally, we may represent $\\omega$ as $\\sum_{i=1}^m \\omega_i dx_1 \\wedge \\cdots \\wedge \\hat{dx_i} \\wedge \\cdots \\wedge dx_m$ for $\\omega_i \\in C^\\infty(Q)$. Then\n\\begin{align*}\n\\int_Q d\\omega & = \\sum_i (-1)^i \\int_Q \\frac{\\partial \\omega_i}{\\partial x_i}dx_1 \\wedge \\cdots \\wedge dx_m \\\\\n& = \\sum_i \\int_{Q_i}\n\\end{align*}\n\n\\end{proof}\n\n\\section{Friday, March 13}\nWe have $Q = [A_1, B_1] \\times \\cdots \\times [A_n, B_n] \\subset \\mathbb{R}^n$, $\\omega \\in \\Omega^{n-1}(M)$, and \n\\[\n\\text{supp}(\\omega) \\subset \\subset \\begin{cases}\n(A_1, B_1) \\times \\cdots \\times (A_n, B_n) & A_1 > 0 \\\\\n[0, B_1) \\times (A_2, B_2) \\times \\cdots \\times (A_n, B_n)\n\\end{cases}\n\\]\n$\\omega = \\sum_i \\omega_i dx_1 \\wedge \\cdots \\wedge \\hat{dx_i} \\wedge \\cdots \\wedge dx_n$, $d\\omega$ $= \\sum_i (-1)^i\\frac{\\partial \\omega_i}{\\partial x_i} dx_1 \\wedge \\cdots dx_n$, and\n\\begin{align*}\n\\int_M d \\omega & = \\sum_i \\int_{Q_i}(\\int_{A_i}^{B_i} \\frac{\\partial \\omega_i}{\\partial x_i} dx_i )\\wedge dx_1 \\wedge \\cdots \\wedge \\hat{dx_i} \\wedge \\cdots \\wedge dx_n\\\\\n& = -\\int_{Q_1} \\omega_1 dx_2 \\wedge \\cdots \\wedge dx_n\n\\end{align*}\nwhere $Q_i = [A_1, B_1] \\times \\cdots \\times \\hat{[A_i, B_i]} \\times \\cdots \\times [A_n, B_n]$, because\n\\[\n\\int_{A_i}^{B_i} \\frac{\\partial \\omega_i}{\\partial x_i}dx_i = \\omega_i(B_i) - \\omega_i(A_i) = 0 - 0 = 0\n\\]\nFor the boundary, we have \n\\[\n\\int_{\\partial Q} \\omega = \\int_{Q_1} \\omega = \\int_{Q_1} -\\omega_1 d\\tilde{x}_2 \\wedge \\cdots \\wedge d\\tilde{x}_n\n\\]\nWe want an outward pointing orientation. Notice $\\frac{\\partial}{\\partial x_1}$ points invward to $M$ (with respect to $Q$) but we want to orient $Q$, resp $M$ such that \n\\[\n-\\frac{\\partial}{\\partial x_1}, \\frac{\\partial}{\\partial x_2}, \\ldots, \\frac{\\partial}{\\partial x_n}\n\\]\nNotice $\\partial Q_1 \\cup \\cup_{l \\geq 2} Q_l$\n\nNow we choose an oriented atlas $\\mathscr{A}$ of $M$, after passing to a finite atlas, we can assume that $\\tilde{U} \\subset \\mathbb{R}^n$ for $(U,x) \\in \\mathscr{A}$ has form $[A_1, B_1] \\times \\cdots \\times[A_n, B_n] \\subset \\mathbb{H}^n$ and $x: U \\to \\tilde{U} \\subset \\mathbb{H}^n$ and such that $\\mathscr{A}$ is countable. Choose a smooth partition of unity. Choose a smooth partition of unity $(\\phi_{(U,x)})_{(U,x) \\in \\mathscr{A}}$ subordinate to $\\mathscr{A}$ where $\\text{supp}(\\phi_{(U,x)}) \\subset \\subset U \\Rightarrow x_*(\\phi_{(U,x)} \\omega \\subset \\subset \\tilde{U} \\subset \\mathbb{H}^n)$ and\n\\begin{align*}\n\\int_M d\\omega &= \\sum_{(U,x) \\in \\mathscr{A}} \\int_{\\tilde{U}}d(x_*\\phi_{(U,x)} \\omega) \\\\\n&= \\sum_{(U,x) \\in \\mathscr{A}} \\int_{\\partial \\tilde{U}} x_*(\\phi_{(U,x)}\\omega)\\\\\n&= \\sum_{(U,x) \\in \\mathscr{A}} \\int_{\\partial \\tilde{U}} x_*(\\phi_{(U,x)}\\omega|_{\\partial M}) \\\\\n&= \\int_{\\partial M} \\omega\n\\end{align*}\n\n\\textbf{Corollary:} If $M$ is a closed manifold (compact and no boundary) then \n\\[\n\\int_M d \\omega = 0\n\\]\nFor $\\omega \\in \\Omega^{\\text{dim}M}(M)$\n\n\\textbf{Integration of Vector Fields}\nLet $\\xi: M \\to TM$ be a $C^\\infty$ vector field on a smooth manifold $M$. A curve $\\gamma: I \\to M$, $I = (a,b) \\subset \\mathbb{R}$ is called an integral curve of $M$ if $\\xi(\\gamma(t)) \\in T_{\\gamma(t)}M$ is equal to $\\dot{\\gamma}(t)$ for all $t \\in I$.\n\n\\textbf{Question:}\n\n\\section{March 16, 2015}\n\\textbf{Integral Curves:} Let $\\xi: M \\to TM$ be a smooth vector field on a manifold $M$. By an integral curve of $\\xi$, one understands a smooth map $\\gamma: I \\to M$, with $I \\subset \\mathbb{R}$ an open interval, such that\n\\[\n\\dot{\\gamma}(t) = \\xi(\\gamma(t)) \\text{ for all } t \\in I\n\\]\n\\textbf{Observations:}\n\n(1) For each $p \\in M$, there exists an open interval $I \\subset \\mathbb{R}$ containing the origin 0, and a smooth integral curve $\\gamma: I \\to M$ of $\\xi$ such that $\\gamma(0) = p$.\n\\begin{proof}\nChoose coordinates $(U,x)$ of $M$ around $p$, and then consider the following ordinary differential equation:\n\\begin{align*}\n\\dot{c}(t) = F(c(t)) & & c(0) = x(p)\n\\end{align*}\nwhere $F := (pr_2 \\circ Tc \\circ \\xi \\circ x^{-1}): \\hat{U} \\to \\mathbb{R}^n$. By existence and uniqueness (Picard-Lindelof theorem), there exists $c:(-\\varepsilon, \\varepsilon) \\to \\hat{U}$ such that the initial value problem is satisfied. We put $\\gamma := x^{-1} \\circ c: (-\\varepsilon, \\varepsilon) \\to M$, then $\\gamma(0) = p$ and $\\dot{\\gamma}(t) = (Tx)^{-1}(c(t), \\dot{c}(t)) = Tx^{-1}(c(t), F(c(t))) = \\xi(x^{-1}(c(t))) = \\xi(\\gamma(t))$. (Note that this holds true in Banach manifolds)\n\\end{proof}\n\n(2) If $\\gamma_1, \\gamma_2$ are integral curves of $\\xi$ with $\\gamma_1(0) = \\gamma_2(0) = p$, then $\\gamma_1|_{I_1 \\cap I_2} = \\gamma_2|_{I_1 \\cap I_2}$ (Note $I_1 \\cap I_2$ is nonempty since they both implicitly contain 0)\n\\begin{proof}\nLet $K = \\{ t \\in I_1 \\cap I_2 : \\gamma_1(t) = \\gamma_2(t) \\}$. We have $K = (\\gamma_1, \\gamma_2)^{-1}(\\Delta_M)$. (note $(\\gamma_1, \\gamma_2): I_1 \\cap I_2 \\to M \\times M$). By continuity of $\\gamma_1$ and $\\gamma_2$ and $M$ being Hausdorff, $I_1 \\cap I_2$ is an open interval around the origin, hence connected. Let $t \\in K$. Consider $\\tilde{\\gamma_1}: I_1 - t \\to M$ and $\\tilde{\\gamma_2}: I_2 + t \\to M$ where $\\tilde{\\gamma_i}(s) = \\gamma_i(s+t)$. So $\\tilde{\\gamma_1}(0) = \\gamma_1(t) = \\gamma_2(t) = \\tilde{\\gamma_2}(0)$, so $\\dot{\\tilde{\\gamma_i}}(s) = \\dot{\\gamma_i}(s+t) = \\xi(\\gamma_i(x + t)) = \\xi(\\tilde{\\gamma_i}(s))$. By local uniqueness of the initial value problem, there exists an $\\varepsilon$ such that $\\tilde{\\gamma_1}(s) = \\tilde{\\gamma_2}(s)$ for $s \\in (-\\varepsilon, \\varepsilon)$. Hence $\\gamma_1$ and $\\gamma_2$ agree on an $\\varepsilon$-neighborhood of $t$.\n\\end{proof}\n\n(3) For each $p \\in M$, let $I_p = (t_p^-, f_p^+)$ with $t_p^- < t_p^+$ and $t_p^-, t_p^+ \\in \\mathbb{R} \\cup \\{ \\pm \\infty \\}$. There of all intervals $I$ such that there exists an integral curve $\\gamma : I \\to M$ of $\\xi$ with $\\gamma(0) = p$. Define $\\gamma_p: I_p \\to M$ by $t \\mapsto \\gamma(t)$, where $t \\in I$ with $\\gamma:I \\to M$ (If $M$ is compact , the $I_p = \\mathbb{R}$, a counterexample is the plane with a point removed and having a constant vector field oriented upwards). Now put $\\mathcal{D} = \\cup_{p \\in M}I_p \\times \\{ p \\} \\subset \\mathbb{R} \\times M$, and $\\phi:\\mathcal{D} \\to M$, $(t,p) \\mapsto \\gamma_p(t)$. Then $\\phi$ is called the flow of the vector field $\\xi$. It has the following nice properties:\n\n(a) $\\mathcal{D} \\subset \\mathbb{R} \\times M$ is open.\n \n(b) The domain $\\phi_t \\circ \\phi_s \\subset $ domain $\\phi_{t+s}$ where $\\phi_t: M \\to M$ where $p \\mapsto \\phi(t,p)$\n\n(c) $\\phi_{t+ s}(p) = \\phi_t \\circ \\phi_s(p)$ for $p \\in \\text{dom}(\\phi_t \\circ \\phi_s)$.\n\n(d) $\\phi_d$\n\\begin{proof}\n\\end{proof}\n\n\\section{18 March, 2015 (Wednesday)}\n\n\\textbf{Banach Fixed Point Theorem:} If you have a complete metric space with a Lipschitz contraction, then the space has a unique fixed point.\n\n\\textbf{Proposition:} Let $J$ be an open interval containing $0$, $U$ an open set of a banach space $\\mathbb{E}$, and $x_0 \\in \\mathbb{E}$. Let $a \\in (0,1)$ such that the closed ball $\\bar{B}_{3a} \\subset U$. Assume that $f: J \\times U \\to \\mathbb{E}$ be a bounded continuous map, bounded by constant $L \\geq 1$, and satisfying on $U$ uniformly with respect to $J$ a Lipschitz condition with Lipschitz constant $K \\geq 1$. Then $\\| f(t,x) - f(t,y) \\| \\leq K \\| x - y \\|$ for all $t \\in J$ and $x,y \\in U$. If $b < \\frac{a}{LK}$, then for each $x \\in \\bar{B}_a(x_0)$ there exists a unique flow $\\phi: J_b \\times B_a(x) \\to U$; that is, $\\frac{d}{dt}\\phi(t,x) = f(t, \\phi(t,x))$ and $\\phi(0,x) = x$. Letting $I_b = [-b,b]$, and let $x$ be fixed in $\\bar{B}_a(x_0)$. Let $M$ be a set of continuous maps\n\\[\na: I_b \\to \\bar{B}_{2a}(x_0)\n\\]\nWe have that $M$ is a complete metric space with distance given by the sup-norm.\n\\begin{align*}\nS: M \\to M && s\\alpha(t) = x + \\int_0^t f(u,\\alpha(u))du\n\\end{align*}\nChoose $S$ fulfills Lipschitz-condition with Lipschitz-constant $L_x < 1$ which implies there exists a unique fixed point by the Banach Fixed Point Theorem. Call this $\\phi_x \\in M$ with $s\\phi_x = \\phi_x$. By the fundamental theorem of calculus, we have $\\phi_x(t) = x + \\int_0^t f(u, \\phi_x(u))du$ is differentiable; that is, $\\dot{\\phi_x}(t) = f(t,\\phi_x(t))$ with $\\phi_x(0) = x$. If $f$ is $C^k$ for $k \\in \\mathbb{N}^* \\cup \\{ +\\infty \\}$, then $\\phi$ is $C^k$. Look at Lang Differentiable Manifolds for the full proof.\n\nLast lecture we had $\\phi: \\mathcal{D} \\to M$ by $(t,p) \\mapsto \\gamma_p(t)$. Then $\\phi$ has the following properties:\n\n(1) $\\mathcal{D}\\subset \\mathbb{R} \\times M$ is open\n\n(2) $\\text{dom}(\\phi_s \\circ \\phi_t) \\subset \\text{dom}(\\phi_{s + t})$ where $\\phi_t :\\mathcal{D} \\cap \\{t\\} \\times M = \\mathcal{D}_y = \\text{dom}(\\phi_t)$ by $p \\mapsto \\phi(t,p)$\n\n(3) We also have $\\phi_{t+s} = \\phi_t \\circ \\phi_s$ for $p \\in \\text{dom}(\\phi_t \\circ \\phi_s)$\n\n(4) $\\phi_t: \\mathcal{D}_t \\to \\mathcal{D}_{-t}$ is a diffeomorphism with inverse $\\phi_{-t}$\n\n\\begin{proof}\n(a) Local flow theorem from Lang\n\n(b) Let $s \\in (t_-(p),t_+(p))$ %and $t \\in (t_-(\\gamma_p(s)), t_+(\\gamma_p(s)))$\nThen $f \\mapsto \\gamma_p(s+t)$ is an integral curve of $\\mathcal{G}$ and has maximal domain \n$(t_-(p) - s,t_+(p) - s) = (t_-(\\gamma_p(s)), t_+(\\gamma_p(s)))$.\nSince $\\gamma_p(s+0) = \\gamma_p(s)$. Now \n$p \\in \\text{dom}(\\phi_t \\circ \\phi_s) \\Rightarrow p \\in \\text{dom}(\\phi_s) \\Rightarrow s \\in (t_-(p), t_+(p))$\nand $t \\in (t_-(\\gamma_p(s)),t_+(\\gamma_p(s)) \\Rightarrow t+s \\in (t_-(p), t_+(p))$.\n\n\\end{proof}\n\n\\section{March 20, 2015 (Friday)}\n\\textbf{Lie Derivatives:} We want to take derivatives of vector fields $\\xi: M \\to TM$ which gives a tangent map $T\\xi: TM \\to T(TM)$. Assume $W: M \\to TM$ is a second vector field. We want to define a derivative of $\\xi$ with respect to $W$.\n\n\\textbf{Lie Derivative:} Looking at the flow of $W$, $\\phi:\\mathcal{D} \\to M$ with\n\\[\n\\Lie_W \\xi(p) := \\lim_{t \\to 0} \\frac{T\\phi_{-t}(\\xi_{\\phi_t(p)}) - \\xi_p}{t} = \\frac{d}{dt}T\\phi_{-t}(\\xi_{\\phi_t(p)})|_{t=0}\n\\]\nNotice that the limit exists in coordinates since all the functions are smooth. The map $\\Lie_W$ is called the Lie derivative.\\\\\n\\textbf{Observations:}\n\n(1) $\\Lie_W f = W(f)$\n\n(2) $\\Lie_W \\xi = [W, \\xi]$\n\n(3) $\\Lie_W$ is tensorial in $W$ only over $\\mathbb{R}$, not $C^{\\infty}(M)$.\n\n(4) $\\Lie_W: \\Omega^\\bullet(M) \\to \\Omega^\\bullet(M)$ commutes with $d$.\n\n(5) $\\Lie_W(\\omega \\wedge \\rho) = \\Lie_W\\omega \\wedge \\rho + \\omega \\wedge \\Lie_W \\rho$\n\n(6) \\textbf{Cartan's Magical Formula:} $\\Lie_W\\omega = i_Wd\\omega + di_W \\omega$ for $\\omega \\in \\Omega^k(M)$ where $i_W \\in \\Omega^{k-1}(M)$ is defined by $i_W\\omega(Y_1, \\ldots, Y_{k-1}) = \\omega(W, Y_1, \\ldots, Y_k)$ (useful for proving Poincare's lemma).\n\\begin{proof}\n(1) $\\Lie_Wf(p) = \\frac{d}{dt}(\\phi_t^*f)(p) = \\frac{d}{dt}(f \\circ \\phi_t(p))|_{t = 0} = W(p)\\cdot [f]_p$. \\\\\n(2) We show that the bracket is a derivation to show that the bracket is still a vector field. \\textbf{Exercise:} do this. \\\\\n(3) Omitted \\\\\n(4) We have $\\Lie_W d \\omega = \\frac{d}{dt}\\phi_t^*(d \\omega) |_{t=0} = \\frac{d}{dt}d(\\phi_t^* \\omega)|_{t=0} = d(\\frac{d}{dt} \\phi_t^*\\omega)|_{t=0}$ \\\\\n(5) Same argument as (4) \\\\\n(6) We prove this by induction on $k$. For $k = 0$, $\\Lie_Wf = Wf$ and $i_w df + di_Wf = i_wdf = Wf$. Assume this holds true for $k-1$.\n\\end{proof}\n\n\\section{March 30, 2015 (Monday)}\n\\textbf{Proposition:} $\\mathcal{L}_XY = [X,Y]$\n\\begin{proof}\nFor $f \\in C^\\infty(M)$ we have\n\\begin{align*}\n\\mathcal{L}_XY(f) & = (\\lim_{t \\to 0} \\frac{TX_{-t}Y_{x_y(m)} - y_m}{t})(f) \\\\\n& = \\frac{d}{dt}|_{t=0}(TX_{-t}Y_{X_t(m)})(t) \\\\\n& = \\frac{d}{dt}|_{t=0}Y_{X_t(m)}(f \\circ X_{-t})\n\\end{align*}\nFor the auxillary function $H(t,u) = f(X_{-t}(Y_u(X_t(m))))$ with $(t,u) \\in \\mathbb{R}^2$, small enough. We have\n\\begin{align*}\nY_{X_t(m)}(f \\circ X_{-t}) = \\frac{\\partial}{\\partial r_2}|_{(t,0)}H(t,r_2) \\\\\n%\\mathcal{L}_Yg(p) = Y_g(p) = Y_pg \n\\end{align*}\nThen we have $\\mathcal{L}_XY(f) = \\frac{\\partial^2}{\\partial r_1 \\partial r_2}|_{(0,0)}$. Consider another auxillary function $K(t,u,s) = f(X_s(Y_u(X_t(m))))$ we have $H(t,u) = K(t,u,-t)$\nThen\n\\begin{align*}\n\\mathcal{L}_XY(f) & = \\frac{\\partial^2 K}{\\partial r_1 \\partial r_2}|_{(0,0,0)} - \\frac{\\partial^2 K}{\\partial r_2 \\partial r_3}|_{(0,0,0)} \\\\\n\\frac{\\partial K}{\\partial r_2}|_{(t,0,0)}& = Y_{X_t(m)}f = (Yf)(X_t(m)) \\\\\n\\frac{\\partial^2 K}{\\partial r_1 \\partial r_2}|_{(0,0,0)} & = X_m(Yf) \\\\\n\\frac{\\partial K}{\\partial r_3}|_{(0,0,0)} & = Xf(Y_u(m)) \\\\\n\\frac{\\partial^2 K}{\\partial r_1 \\partial r_3}|_{(0,0,0)} &= Y_m(Xf) \n\\end{align*}\n\\end{proof}\n\n\\textbf{Cartan's Magic Formula} $\\mathcal{L}_X \\omega = i_X d \\omega + d i_X \\omega$ for $\\omega \\in \\Omega^k(M)$.\n\\begin{proof}\nThis proof follows from induction. For $k = 0$\n\\[\n\\mathcal{L}_Xf = Xf = i_X df = i_X df + d i_X f\n\\]\nNow, for the induction step, take\n\\begin{align*}\n\\mathcal{L}_X(df \\wedge \\omega) & = \\Lie_Xdf \\wedge \\omega + df \\wedge \\Lie_X \\omega \\\\\n(i_Xd + di_X)(df \\wedge \\omega) & = -df \\wedge i_Xd\\omega + d(i_Xdf \\wedge \\omega - df \\wedge i_X \\omega) \\\\ \n& = - df \\wedge i_X d \\omega + d i_X df \\wedge \\omega + (i_Xdf)\\wedge d \\omega + df \\wedge di_X\\omega \\\\\n& = \\Lie_X df \\wedge \\omega  \\cdots \\text{ look in Tu }\n\\end{align*}\n\n\\textbf{Exercise:} Show $i_X(\\rho \\wedge \\omega) = i_X \\rho \\wedge \\omega + (-1)^{deg(\\rho)} \\rho \\wedge i_X \\omega$\n\\end{proof}\n\n\\section{April 1, 2015 (Wednesday)}\n\n\\textbf{Andy} Given a smooth n-manifold $M$, a \\textbf{Riemannian metric} $g$ is a smooth symmetry covariant 2-tensor field on $M$ that is positive definite at each point in $M$; that is, $g \\in \\Gamma(T*M \\otimes T*M)$. Locally, we may express $g$ as $g_{ij}dx^i \\otimes dx^j$ for coordinates $(U, x^1, \\ldots, x^n)$ where $(g_{ij})$ is a positive definite matrix of smooth functions.\n\nA Kahler structure on a Riemannian manifold $(M^n, g)$ is given by a 2-form $\\omega$ and a field of endomorphisms $J$ on the tangent bundle such that\n\nAlgebraic conditions:\n\n(1) $J$ is an almost complex structure; that is, $J^2 = -Id$ as an endomorphism on the tangent space\n\n(2) $g(X,Y) = g(JX, JY)$ for each $X,Y \\in \\Gamma(TM)$\n\n(3) $\\omega(X,Y)= g(JX,Y)$\n\nAnalytic conditions:\n\n(4) The 2-form $\\omega$ is closed; ie, $d\\omega = 0$\n\n(5) $J$ is integrable\n\nNote that $(1)$ and $(5)$ are equivalent to having a holomorphic structure. If $N(X,Y) = 2([JX, JY] - [X,Y] - [JX, Y] - [X,JY]) = 0$ we have the holomorphic structure.\n\nLocally, we may express $\\omega$ as $ih_{\\alpha \\beta}dz_\\alpha \\wedge dz_{\\bar{\\beta}}$ where $h_{\\alpha \\beta} = h(\\frac{\\partial}{\\partial z_{\\alpha}}, \\frac{\\partial}{\\partial z_{\\bar{\\beta}}})$ and $h$ is hermitian. Also, $\\frac{\\partial^2 u}{\\partial z_\\alpha \\partial z_{\\bar{\\beta}}}$ where $u$ is the Kahler potential. As a side remark, the only solutions found to the Einstein vacuum equation $R_{\\alpha \\beta} = 0$ are Kahler manifolds.\n\nA complex manifold is a smooth manifold of dimension $2n$ which admits a holomorphic atlas $\\{U_i, \\phi_i \\}$ such that the transition functions $\\phi_i$ are biholomorphic and map into $\\mathbb{C}^n$. Remember that a functions $F = f + ig$ is holomorphic if it satisfies the Cauchy-Riemann equations\n\\begin{align*}\n\\frac{\\partial f}{\\partial x} = \\frac{\\partial g}{\\partial y} && \\frac{\\partial f}{\\partial y} = -\\frac{\\partial g}{\\partial x}\n\\end{align*}\n\n\\textbf{Exercise:} Show that this is equivalent to the equation $\\frac{\\partial F}{\\partial \\bar{z}} = 0$\n\nThe canonical examples of a kahler manifolds are the complex projective plane, tori, $\\mathbb{C}^n$, and Riemann surfaces. Note that every complex variety may be embedded in $\\mathbb{CP}^n$.\n\n\\textbf{Nicholas:} A \\textbf{Calabi-Yau manifold} is a compact Kahler manifold where the holonomy group is $SU(d)$ where $d$ is the complex dimension.\n\n\\textbf{Definition:} Take $C^\\infty(M, TM)$ as the space of vector fields on $M$. A bilinear map $\\nabla: C^\\infty(M, TM) \\to C^\\infty(M, TM)$ where $(X,Y) \\mapsto \\nabla_X Y$ is a connection if it satisfies\n\n(1) $\\nabla_{fX}Y = f\\nabla_XY$ for each $f \\in C^\\infty(M, TM)$\n\n(2) $\\nabla_X(fX) = X(f)Y + f\\nabla_XY$\n\n\\textbf{Definition:} A vector field $X$ is parallel if $\\nabla_YX = 0$ for every $Y \\in C^\\infty(M, TM)$\n\nTake $\\gamma: [a,b] \\to M$ be a smooth curve on $M$. A vector field $X$ on $\\gamma([a,b])$ is called a parallel transport of a vector $v \\in T_{\\gamma(a)M}$ if $\\nabla_{\\dot{\\gamma(t)}}X = 0$ for each $t$ and $X(a) = v$.\n\nIf $X$ is a parallel transport of $v$ and $Y$ is a parallel transport of $w$ (both along $\\gamma$) Then $c_1X + c_2Y$ is the unique parallel transport of $c_1v + c_2w$ along $\\gamma$. Let $X^{e_i}$ be a parallel transport of $e_i$ along $\\gamma$. Taking $f_\\gamma:T_{\\gamma(a)}M \\to T_{\\gamma(b)}M$ by $v = i^ie_i \\mapsto i^i X^{e_i}$.\n\nConsidering all loops in $M$ based at $p \\in M$. Taking $\\alpha$ as a loop of $M$, the map $f_\\alpha: T_{\\gamma(a)} \\to T_{\\gamma(b)}M \\in GL(n; \\mathbb{R})$\n\n\\section{April 6, 2015 (Monday)}\n\nLet $V$ be a finite dimensional $\\mathbb{R}$-vector space and $\\lambda:V \\times V \\to \\mathbb{R}$ a \\textbf{symmetric bilinear form}; that is, $\\lambda$ satisfies the following properites:\n\n(1) $\\lambda(v + v',w) = \\lambda(v,w) + \\lambda(v',w)$\n\n(2) $\\lambda(av,w) = \\lambda(v,aw) = a\\lambda(v,w)$\n\n(3) $\\lambda(v,w) = \\lambda(w,v)$\n\nMoreover, we say $\\lambda$ is \\textbf{nondegenerate} if $\\lambda(v,w) = 0$ if $v = 0$ or $w = 0$.\n\n\\textbf{Theorem:}(Sylvester) If $\\Lambda: V\\times V \\to \\mathbb{R}$ is a symmetric bilinear form, then there is a basis $(b_i)_{i=1}^n$ of $V$ such that $\\lambda$ has the matrix\n%% Look at photograph\n\n\\textbf{Observation:} $\\lambda$ is non-degenerate iff $ker(\\lambda_ij) = 0$.\n\n\\textbf{Definitions:} The \\textbf{signature} of $\\lambda$ is $(n_+,n_-)$ where $n_+$ is the number of positive eigenvalues and $n_-$ is the number of negative eigenvalues. If $n_+$ is the dimension of $V$, then $\\lambda$ is called \\textbf{positive-definite}. Also, $n_-$ is called the \\textbf{index} of $\\lambda$.\n\n\\textbf{Definition:} A \\textbf{semi-riemannian} n-manifold is a manifold $M$ together with a nondegenerate symmetric tensor $g \\in \\Gamma(T^*M \\otimes T^*M)$ such that the index $g_p$ at $p \\in M$ is constant for any $p \\in M$. If the index of $g$ is 0, then $(M,g)$ is called \\textbf{riemannian}. Locally, for some chart $(U,\\phi)$ with local coordinates, $x^1, \\ldots, x^n$, we can express g as\n\\[\ng = g_{ij}dx^i\\otimes dx^j\n\\]\n\n\\textbf{Sidenote:} General relativity is the geometry of 4-dimensional semi-Riemannian manifolds with index 1. A semi-riemannian metric with index 1 is called a \\textbf{Lorentz metric}.\n\n\\textbf{Remark:} There is no Lorentz metric on $S^2$. (Of topological nature)\n\n\\textbf{Theorem:} Every manifold admits a Riemannian metric\n\\begin{proof}\nLet $\\mathscr{A}$ be an atlas of $M$. For each $(U,x) \\in \\mathscr{A}$, put $g_U:=x^*(\\langle -,- \\rangle)$ of the standard euclidean metric on $\\mathbb{R}^n$. Choose a partition of unity subordinate to $\\mathscr{A}$, $(\\phi_V)$. Put\n\\[\ng(v,w) = \\sum_{(U,\\phi)\\in \\mathscr{A}} \\phi_U(p) g_U(v,x) \\text{ for } v,w \\in T_pM\n\\]\nNotice that each point $g_p$ is positive definite and symmetric.\n\\end{proof}\n\n\\textbf{Observation:} For a lorentz metric, it may cancel out on the partition of unity. Observe\n%\\[\n%\\frac{1}{2} \\left(\\begin{array}1&0\\\\-1&0\\end{array}\\right) + \\frac{1}{2}(-1010) = 0\n%\\]\n\nAssume $(M,g)$ is semi-riemannian metric. Let $(U,x)$ be a chart and $\\frac{\\partial}{\\partial x_i}$ a local frame of $TM$. Put $g_{ij}^{(U,x)} := g(\\frac{\\partial}{\\partial x_i}, \\frac{\\partial}{\\partial x_j}) \\in C^\\infty(U)$. If $(V,y)$ is another coordinate chart with $U\\cap V \\neq \\varnothing$, we want to know how the local expression of $g$ transforms.\n\\begin{align*}\n\\frac{\\partial}{\\partial y_j}|_p = \\sum_{k=1}^n \\frac{\\partial (x_k \\circ y^{-1})}{\\partial y_j}(p) \\frac{\\partial}{\\partial x_k}|p \\text{ and } \\\\\ng_{ij}^{(V,y)}(p) = \\sum_{k,l=1}^n \\frac{\\partial (x_k \\circ y^{-1})}{\\partial y_j}(p) \\cdot \\frac{\\partial (x_l \\circ y^{-1})}{y_j}(p)g_{kl}^{(U,x)}(p) \n\\end{align*}\n\nAssume $N \\hookrightarrow M$ is a submanifold, and that $g$ is a semi-riemannian metric on $M$. Then, one can pull-back $g$ to $N$ to a get a symmetric 2-tensor $i^*g \\in C^\\infty(T^*M \\otimes T^*M)$ with\n\\[\ni^*g(p)(v,w) = g(i(p))(Ti(y), Ti(w))\n\\]\n\n\\textbf{Observations:}\n\n(1) If $g$ is positive definite, the $i^*g$ is so as well.\n\n(2) The pull-back of a semi-riemannian metric may not be semi-riemannian. The obstructions for this are topological, but \n\n\\section{April 8, 2015 (Wednesday)}\n\\textbf{Exotic Spheres:}(Milnor) There is a family of smooth 7-manifolds with are homeomorphic to $S^7 \\subset \\mathbb{R}^8$, but not diffeomorphic.\n\n\\textbf{Example} Consider\n\\[\n\\begin{tikzcd}\n\\tilde{\\mathbb{R}} \\arrow[d, \"\\psi\"] & x \\arrow[d, mapsto] & & \\mathbb{R} \\arrow[d, \"Id\"]\\\\\n\\mathbb{R} & x^3 & & \\mathbb{R}\n\\end{tikzcd}\n\\]\nObserve that these manifolds do not have the same smooth structure, but are diffeomorphic by $\\tilde{\\mathbb{R}} \\xrightarrow{x^{3}} \\mathbb{R}$.\n\n(1) We want $M$ to be homeomorphic to $S^n$\n\n(2) Construct $M^7_k$ by sphere bundles $E \\to S^4$\n\n(3) Prove that $M^7_k \\cong S^n$ as a homeomorphism.\n\n(4) (Black Magic) Construct an invariant $\\lambda(M^7_k) \\neq \\lambda(S^7)$.\n\nFirst $p \\in M$ is a point, and $f:M \\to \\mathbb{R}$ is a morse function if the Hessian matrix of the critical points is non-singular. Recall that the critical points are the $p \\in M$ such that $dH_p = 0$. The Hessian matrix can be represented as the matrix\n\\[\n\\left( \\frac{\\partial^2 f}{\\partial x_i \\partial x_j} \\right)_{i,j}\n\\]\n\n\\textbf{Theorem:} If $M$ is a compact n-manifold with $f$ a morse function with 2 critical points, then $M$ is homeomorphic to $S^n$.\n\n\\textbf{Theorem:} Let $f \\in C^\\infty(M)$, $M^r = f^{-1}(-\\infty, r)$, $a< b \\in \\mathbb{R}$. If $f^{-1}([a,b])$ is compact with no critical points, then $M^a$ is diffeomorphic to $M^b$.\n\\begin{proof}\nLet $g$ be a Riemannian metric $g(X,Y) = \\langle X, Y \\rangle$. Let $\\text{grad}(f) \\in \\mathcal{X}(M)$ with $\\langle \\text{grad}(f), Y \\rangle = \\tilde{X}(f)$. Observe $X = \\phi\\text{grad}(f)$ for $\\phi \\in C^\\infty(f^{-1}[[a,b])$ with \\[\n\\phi = \\frac{1}{ \\| \\text{grad}(f) \\|^2}\n\\] is a vector field of compact support. Defines a flow $\\phi_t$ with $X(p) = \\frac{d}{dt} \\phi_t(p)$; consider $f(\\phi_t(q))$ as a function of $t$. If $\\phi_t(q) \\in f^{-1}[a,b]$, then $\\frac{d}{dt}f(\\phi(q))) = \\langle  \\frac{d \\phi_t(q)}{dt}, \\text{grad}(f) \\rangle = X(f) = \\phi \\| \\text{grad}(f) \\|^2 = 1$. This implies that $f(\\phi_t(q)) = f(q) + t$. If $f(q) \\leq a$, then $f(\\phi_{b-a}(q)) = f(q) + b - a \\leq b$.\n\\end{proof}\n\n(2) For constructing $M_k^7$, consider a sphere bundle $S^2 \\hookrightarrow  M_k^7 \\to S^4$. Observe that $S^4 = U^+ \\cup U^-$ for $U^+ = S^4 \\sim N$ and $U^- = S^4 \\sim S$ and each of these sets are homeomorphic to $\\mathbb{R}^4$. Decompose $M^7_k$ are the union of the preimage of these sets, and denote them $V^+$ and $V^-$ respectively, these are homeomorphic to $\\mathbb{R}^4 \\times S^3$. Define a map $V^+ \\to V-$ by\n\\[\n(u;v) \\mapsto \\left( \\frac{u}{\\| u \\|^2}; \\frac{u^ivu^j}{\\| u \\|} \\right) = (u';v')\n\\]\nwith $u \\in \\mathbb{H}$ and $v \\in S^3 \\subset \\mathbb{H}$. We define a morse function $f(u;v)$ by\n\\[\n\\frac{\\text{Re}(v)}{(1 + \\| u \\|^2)^{1/2}} = \\frac{\\text{Re}(u'')}{(1+ \\| u'' \\|^2)^{1/2}}\n\\]\nwhere $u'' = u'(v')^{-1}$.\n\n\\section{April 10, 2015}\n\n\\textbf{Morse Theory:} Studies smooth functions on a manifold to better understand the underlying topological structure.\n\nLet $f: M \\to \\mathbb{R}$ be a smooth function. Then the points $p \\in M$ such that the differential of $f$ is the 0 map are called \\textbf{critical points}. In local coordinates, this may be expressed as\n\\[\n\\frac{\\partial f}{\\partial x_i}(p) = 0\n\\]\n\n\\textbf{Definition:} The Hessian matrix is the matrix\n\\[\nH_f \\left[\\frac{\\partial^2}{\\partial x_i \\partial x_j} \\right] = \\left(\\frac{\\partial^2f}{\\partial x_i \\partial x_j} \\right)_{i,j}\n\\]\n\n\\textbf{Definition:} A critical point is nondegenerate at $p$ of $f$ is the Hessian matrix is nonsingular.\n\n\\textbf{Proposition:} The nondegeneracy of a point is independent of the chart used.\n\n\\textbf{Definition:} A smooth function $f \\in C^\\infty(M)$ is called a \\textbf{Morse function} if all its critical points are nondegenerate.\n\n\\textbf{Lemma:}(Morse Lemma) For a smooth $m$-manifold $M$, a point $b$ is a nondegenerate critical point of a smooth function $f$, there exists a chart $(x_1, \\ldots, x_m)$ such that $x_i(b) = 0$ and\n\\[\nf = -x_1^2 - x_2^2 - \\cdots - x_\\alpha^2 + x_{\\alpha + 1}^2 + \\ldots + x_m^2 + f(b)\n\\]\n\n\\textbf{Corollary:} Nondegenerate critical points are isolated (there exists a neighborhood of $b$ such that $b$ is the only critical point in this neighborhood)\n\n\\textbf{Corollary:} A Morse function on a compact $m$-manifold $M$ has only finitely many critical points.\n\n\\textbf{Definition:} Two functions $f,g$ on a smooth $m$-manifold $M$ are called $(C^2, \\varepsilon)$-close if the following three properties hold:\n\n(1) $|f(p) - g(p) | < \\varepsilon$\n\n(2) $|\\frac{\\partial f}{\\partial x_i}(p) - \\frac{\\partial g}{\\partial x_i}(p)| < \\varepsilon$\n\n(3) $|\\frac{\\partial^2 f}{\\partial x_i \\partial x_j}(p) - \\frac{\\partial^2 g}{\\partial x_i \\partial x_j}(p)| < \\varepsilon$\n\n\\textbf{Theorem:} Let $g: M \\to \\mathbb{R}$ be a smooth function. Then there exists a Morse function $f$ such that $f$ and $g$ are $(C^2,\\varepsilon)$-close.\n\n\\section{13 April, 2015 (Monday)}\n\\textbf{Definition:} The \\textbf{Minkowski Metric} over $\\mathbb{R}^4$ is the metric $g$ such that for any vectors $v,w \\in \\mathbb{R}^4$, $g(v,w) = -v_1w_1 + v_2w_2 + v_3w_3 + v_4w_4$.\n\n\\textbf{Definition:} Recall that a local diffeomorphism\n\n\\textbf{Definition:} A local diffeomorphism $\\phi:M \\to N$ between semi-riemannian manifolds $(M,g_M)$ and $(N,g_N)$ is a local isometry if for all $p \\in M$ and $v,w \\in T_pM$,\n\\[\ng_M(v,w) = g_N(T_p\\phi(v), T_p\\phi(w))\n\\]\n\n\\textbf{Observation:} For each semi-riemannian manifold $(M, g)$, the set of isometries form a group, denoted by $Isom(M,g)$.\\\\\n\\textbf{Exercise:} Check that $Isom(M,g)$ is a group.\\\\\n\\textbf{Examples:}\n\n(1) Maps from $\\mathbb{R}^n, g_{euc})$ to itself of the form $f: \\mathbb{R}^n \\to \\mathbb{R}^n$, by $v \\mapsto Av + b$, where $A \\in O(n, \\mathbb{R})$ and $v, b \\in \\mathbb{R}^n$. This space of maps are called the \\textbf{Euclidean transformations}. We denote this by $Trans_{euc}(\\mathbb{R}^n)$. Notice that compositions of such transformations are an orthogonal transformation.\\\\\n\\textbf{Theorem:} $Trans_{euc}(\\mathbb{R}^n) = Isom(\\mathbb{R}^n, g_{euc})$ This is highly nontrivial to prove\n\n(2) Maps $f:(\\mathbb{R}^n, g_{Min}) \\to (\\mathbb{R}^n, g_{Min})$ of the form $f(v) = Av + b$ for $A \\in O(n,1) = \\{ A \\in GL(n+1, \\mathbb{R})) : g_{Min}(Av,Aw) = g_{Min}(v,w) \\}$. The set of all transformations is a group called the poincare group. This is the isometry group.\n\n(3) The set of isometries of the sphere $S^n$ is $O(n+1)$.\n\n\\textbf{Covariant Derivatives:} Let $\\eta: M \\to TM$ be a vector field. It's exterior derivative is a map $T\\eta: TM \\to TTM$. If $\\xi \\in T_pM$, then $T\\eta \\xi \\in T_{\\eta(p)}TM \\neq TM$; this is a problem!\n\n\\textbf{Definition:} By a covariant derivative (or connection) on a manifold $M$ is a map $\\nabla: \\mathfrak{X}^\\infty(M) \\to \\Omega^1(M) \\otimes_{C^\\infty (M)} \\mathfrak{X}^\\infty(M)$ such that the following holds true:\n\\[\n\\nabla_\\xi(f\\eta) = df \\otimes \\eta + f\\nabla_\\xi(\\eta)\n\\]\nThis implies the following properties:\n\n\\section{April 15, 2015 (Wednesday)}\n\n\\end{document}", "meta": {"hexsha": "a6e7561a29cc5d279e3f0fe76e8e7a858bdf283e", "size": 37338, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "notes.tex", "max_stars_repo_name": "lusi8559/MATH_6250_notes", "max_stars_repo_head_hexsha": "78b06255d12defe8979fdd3a49883705c16b3592", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notes.tex", "max_issues_repo_name": "lusi8559/MATH_6250_notes", "max_issues_repo_head_hexsha": "78b06255d12defe8979fdd3a49883705c16b3592", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notes.tex", "max_forks_repo_name": "lusi8559/MATH_6250_notes", "max_forks_repo_head_hexsha": "78b06255d12defe8979fdd3a49883705c16b3592", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 68.3846153846, "max_line_length": 970, "alphanum_fraction": 0.6457764208, "num_tokens": 14164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.3262931470571076}}
{"text": "\\section{Introduction}\n\nThis workshop is going to help you learn about computers -- but not how to \\emph{use} computers. Rather, when we are finished, you will understand a little bit about how and why computers really do work and get answers to math problems. To get to that goal, you'll need to learn some new topics in math, and learn about electricity. You'll also need to learn about basic \\emph{electronic components}, too. These are the small pieces that are used together in \\emph{circuits} to do useful things with electricity. When assembled, circuits (whether simple or complex) enable electricity to do all the things we can make electricity do, like light our homes, play music on the radio, find directions with a GPS, run a gasoline engine, or show you a web page.\n\nComputers are wonderful, multipurpose machines. But computers can't add or subtract the way you do. They can't read the way you do. They don't think. Really,  \\emph{they only do math.} Everything computers do is controlled by a series of instructions that \\emph{all boil down to math and logic,} even if it looks like magic. The way computers do all the things they do can always be described as a series of instructions. Each of these actions can be performed by some combination of special circuit types, and each circuit is made up of basic electronic components. You can learn enough about each basic component to understand what it does, without needing to do a bunch of math. And, you can understand all the individual instructions, even if you don't want to build your own computer!\n\nUltimately this workshop will make it possible for you to make, from the most basic electronic components, a simple digital computer that can add two numbers and correctly display the result, or tell you whether or not two numbers are equal. Along the way you'll see how each piece works, and how to put the pieces together. Some workshops will also teach you how to solder components, so you can actually \\emph{make} some of the building blocks of computers. There are follow-on discussions about other topics like subtraction and using circuits to store information so a computer can use it later.\n\nThis time together should be fun! You can help make it fun for everyone by asking questions and by telling the instructor what you think about the parts of this course. It's not easy to teach this material, so your feedback will help the authors improve this course over time, as the feedback from many people has already improved this workshop.\n\nI'm so glad you're interested in computers. It makes me feel good when people learn things and have fun with this course. Thank you!\n\n\\noindent Jesse Hamner, PhD\\\\\n\\noindent 2018--2021\\\\\n", "meta": {"hexsha": "047ecea4e6dfe6e1f223a1e8c0df608e4b3eab5c", "size": 2707, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "workbook_introduction.tex", "max_stars_repo_name": "jessehamner/TechMillForKids", "max_stars_repo_head_hexsha": "f064bf1408537f71e4e7dc14f02a8e7e20c2af3a", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2017-11-13T21:45:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T09:31:54.000Z", "max_issues_repo_path": "workbook_introduction.tex", "max_issues_repo_name": "jessehamner/TechMillForKids", "max_issues_repo_head_hexsha": "f064bf1408537f71e4e7dc14f02a8e7e20c2af3a", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2017-03-10T21:46:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-25T19:21:58.000Z", "max_forks_repo_path": "workbook_introduction.tex", "max_forks_repo_name": "jessehamner/TechMillForKids", "max_forks_repo_head_hexsha": "f064bf1408537f71e4e7dc14f02a8e7e20c2af3a", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-11-14T04:40:14.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-17T05:31:36.000Z", "avg_line_length": 180.4666666667, "max_line_length": 789, "alphanum_fraction": 0.7927595124, "num_tokens": 575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.3262931470571076}}
{"text": "\\chapter{3. Control Strategy}\n\nThe objective of this chapter is to present the control strategy used in the PEV, based on the Direct Tilt Control (DTC). First, the lateral stability of the vehicle is studied, in order to understand the different strategies for lateral control. Then, the dynamic model is transformed into an space state model, much more easy to work with in control theory. Finally, the theory behind Linear Quadratic Regulator (LQR) and the Regulator Problem with Internal Stability (RPIS) is explained and the control gains are calculated.\n\n\\section{Stability Study}\n\\begin{marginfigure}[10cm]\n\t\\includegraphics[width=1.2\\linewidth]{figs/03/yz2}\n\t\\caption{Forces acting on the center of gravity}\n\t\\label{yz2}\n\\end{marginfigure}\n\\subsubsection{\\textbf{Lateral Acceleration}}\n\nThe lateral acceleration $a_{lat}$ denotes the normal acceleration induced by the curvilinear motion of the vehicle, measured in the plane $XY$ at ground level at point D (Figure \\ref{yz2}), and directed towards the center of rotation of the trajectory.\n\\[a_{lat}=\\ddot{y}+V_{x}\\dot{\\psi}\\]\nTherefore, $a_{lat}$ is a function of the yaw rate (and hence the steering angle) and the longitudinal speed imposed by the driver. It is independent of the vertical position (angle of inclination) of the chassis.\n\n\\subsubsection{\\textbf{Perceived Lateral Acceleration}}\n\nIn the frame reference $y',z'$, the acceleration at the point G decomposes into $a_{per}$ in the $y'$ direction and into $a_{z}$ in the $z'$ direction. The perceived lateral acceleration $a_{per}$ is the result of the accelerations at the center of gravity of the vehicle along the $y'$. \n\\begin{equation}\na_{per}=a_{lat}\\cos\\theta+h\\ddot{\\theta}-g\\sin\\theta\n\\label{a_per}\n\\end{equation}\nThe objective for the control of lateral stabilization of the vehicle and the comfort of the driver will be to impose $a_{per}=0$. The vehicle is in lateral equilibrium if the perceived lateral acceleration is zero, i.e. $a_{per}=0$ (\\textbf{sufficient condition for lateral stability})\\cite[-2cm]{mourad:tel-00787310}.\n\\newpage\nThe fact that $a_{per}$ depends on $a_{lat}$ and $\\theta$, implies that it depends on the trajectory, on the longitudinal velocity, and on the angle of inclination. However, the angle of inclination $\\theta$ will be the key variable to ensure stability. We define by $\\theta_{des}$ the desired position of $\\theta$ which ensures $a_{per}=0$. \n\n\\subsection{Lateral Stability}\n\\begin{marginfigure}[10cm]\n\t\\includegraphics[width=1.2\\linewidth]{figs/03/stability}\n\t\\caption{Forces acting on the center of gravity}\n\t\\label{stability}\n\\end{marginfigure}\nIn this section the dynamics of the vehicle are examined from the expression of $a_{per}$, in three distinct cases: \n\\begin{enumerate}\n\\item \\textbf{Vertical vehicle in straight path}\n\nIn this case $\\theta=0$ and $a_{lat}=0$, therefore $a_{per}=0$ and the problem of lateral stability does not arise, except for the cases of rejection of lateral disturbance forces (i.e. side winds), or disturbances due to an asymmetric pavement on the left and right wheels. \n\n\\item \\textbf{Vertical vehicle in circular trajectory}\n\nWhen the vehicle does not tilt (i.e $\\theta=0$), then $a_{per}=a_{lat}$ (see equation (\\ref{a_per})). If the intersection of the resultant accelerations at the center of gravity $G$ with the plane of the ground (point $x_G$) is outside the base of the vehicle, then it will be unstable. \n\\[a_{G}=a_{lat}\\,\\vec{j} -g\\,\\vec{k}\\]\nOn the contrary, if the point $x_G$ recalls inside the width of the vehicle, it will be stable. Then, the maximum lateral acceleration tolerated without inclination before the overturn is:\n\\begin{equation}\na_{lat-max}=\\frac{gb}{2h}\n\\end{equation}\n\\\\[-1cm]\n\\item \\textbf{Inclined vehicle in circular trajectory}\n\nWhen the vehicle is inclined at a certain angle $\\theta$, its center of gravity has an offset, as well as the point $x_G$. The vehicle is stable as long as $x_G$ belongs to the segment $b$ and is, therefore, located between the two wheels of the vehicle. Let $\\theta_n$ be the nominal inclination angle for which all accelerations in G are compensated, so that is solution of $a_{per}=0$. The computation of $\\theta_n$ can seem complicated, but by considering the steady state (i.e. $\\ddot{\\theta}=\\dot{\\theta}=0$): $a_{per}=a_{lat}\\cos\\theta-g\\sin\\theta$. We then deduce the following expression:\n\\[\\theta_{ref}=\\theta_{n}=\\tan^{-1}\\Big(\\frac{a_{lat}}{g}\\Big)\\]\nThis angle gives a resultant $a_{G}$ colinear with the axis $z'$ of the vehicle. Thus, the angle $\\theta_{n}$ (solution of $a_{per}=0$) is an angle that guarantees the lateral stability of the vehicle.\n\\end{enumerate}\n\n\\subsection{Different strategies for lateral control}\n\nThe objective is to control the inclination of the vehicle so as to ensure its stability. In this way, the lateral stability of the vehicle and the comfort of passengers go hand in hand. From the sufficient condition of the stability explained above, the way to achieve this is by having null perceived acceleration at the center of gravity, $a_{per}=0$.\n\nTwo control strategies can be followed to reach this objective:\n\n\\begin{enumerate}\n\\item The stability is ensured by a \\textbf{direct angular position control}, considering the angle of inclination of reference $\\theta_{ref}$ ensuring $a_{per}=0$. This strategy has been widely adopted by researchers working on this issue. However, this strategy has some drawbacks: approximations have to be made to obtain at each moment the adapted reference angle, and its calculation potentially induces a \\textbf{delay in the control}. \n\n\\item An alternative solution is to \\textbf{directly control the perceived acceleration}, and to pursue the $a_{per}=0$ objective. This is the strategy followed in this thesis. \n\\end{enumerate}\n\nProvided that the most readily available measurements on the vehicle are those provided by an inertial unit (IMU), the choice of direct control of $a_{per}$ was better adapted for these sensors.\n\n\\section{State of the Art for DTC, STC and SDTC systems}\nHaving defined the vehicle model, explained the problem of lateral stability, and calculated the various quantities concerned (lateral acceleration, perceived acceleration) it is now possible to clearly explain the work and results obtained by different researchers.\n\n\\begin{itemize}\n\\begin{itemize}\n\t\\item \\textbf{Hibbard Robbin \\textit{et al.} 1996}\\cite{hibbard1996twenty}, considered the problem of DTC vehicles and proposed to control the angle of inclination with the value of the reference calculated according to $\\theta_{ref}$. The lateral acceleration was approximated by $V_{x}\\dot{\\psi}$, ignoring the dependence in $\\ddot{y}$\n\\[\\theta_{ref}=\\tan^{-1}\\Big(\\frac{a_{lat}}{g}\\Big)=\\tan^{-1}\\Big(\\frac{\\ddot{y}+V_{x}\\dot{\\psi}}{g}\\Big)\\approx\\frac{V_{x}\\dot{\\psi}}{g}\\] The control used for position feedback was a Proportional Derivative (PD) that has the error input on $\\theta$, $e=\\theta-\\theta_{ref}$ with a feedforward function $a_{lat}=V_{x}\\doc{\\psi}$. The model used for regulator adjustment was reduced to the simplified transfer function between $\\theta$ and $M_t$.\n\n\\item \\textbf{So S. \\textit{et al.}, 1997a}\\cite{doi:10.1080/00423119708969321}, were interested in a system where STC and DTC actuated alternately, depending on the longitudinal speed of the vehicle.\n\\begin{itemize}\n\\item A filtered PD regulator was used for the DTC system: \\[M_{t}=\\Big(K_{p}+\\frac{K_{d}}{\\tau_{1}s+1}\\Big)(\\theta-\\theta_{ref})\\]\n\\item The STC strategy similarly used a PD with filtered derivative to calculate the appropriate steering angle.\n\\item The authors exploited the approximate relationship between $a_{lat}$ and $\\delta$: $a_{lat}=\\ddot{y}+V\\dot{\\psi}=(\\dot{V}\\,L_{r}\\,\\delta+V\\,L_{r}\\,\\dot{\\delta}+V^{2}\\delta)/(L_{f}+L_{r})$. So $\\theta_{ref-STC}=a_{lat}/g=f(\\delta,\\dot{\\delta})$ and the control signal STC is written: \\[\\delta=\\Big(G_{p}+\\frac{G_{d}s}{\\tau_{2}s+1}\\Big)(\\theta-\\theta_{ref-STC})\\]\n\\item The two controllers were first simulated separately, considering only the simplified transfer functions between $\\delta$ and $\\theta$ in STC and between the tilt torque $M_t$ and $\\theta$ for DTC. The proposed results showed that the perceived acceleration in DTC was much greater than in STC, and that at the same time the steering angle was significantly modified in STC; \n\\item Switching between STC and DTC systems was also considered, at speeds of $7.5 m/s$ and $8.5m/s$ depending on a hysteresis cycle. To circumvent the jump problems with respect to the static control value, the authors proposed a variable gain for the STC, which increased gradually to optimal value.\n\\end{itemize}\n\n\\item In their work, \\textbf{So S. \\textit{et al.}, (1997)}\\cite{doi:10.1504/IJVD.1997.062071} replaced the PD controller with a PI for the DTC system to solve the static error problem and minimize discontinuity during STC-DTC switching. They added an additional feedback gain as a function of $\\theta$ and $\\dot{\\theta}$. \n\nThe validation of this work was very basic since no stability study was available, the lateral $a_{lat}$ and perceived $a_{per}$ accelerations were reconstructed by their approximate mathematical expressions and were not supposed to be directly measured; The simulations were carried out on a simplified model, linearized around $\\theta=0$, considering the lateral and longitudinal dynamics.\n\\newpage\n\\item At the University of Minneapolis, the researchers addressed several aspects of lateral control of narrow tilting vehicles. In their work, \\textbf{Piyabongkran D. \\textit{et al.} (2004)}\\cite{piyabongkarn2004active}, proposed three DTC control strategies in order to control the angle of inclination at $\\theta_{ref}=\\tan^{-1}(V\\dot{\\psi}/g)$, based on the linearized lateral model. \n\n\\begin{itemize}\n\\item The first strategy was based on a Linear Quadratic Regulator (LQR) using a simplified model whose states only corresponded to $\\theta$ and $\\dot{\\theta}$, hence ignoring the coupling with other important variables such as the yaw rate $\\dot{\\psi}$. A model of the driver was implemented to correct errors on the trajectory in simulation. \n\\item The second strategy was based on the LQR control with a predictive aspect provided by the predictive estimation of the reference inclination angle, based on the knowledge of the future trajectory (i.e. on-board camera, GPS, etc. thus predicting the curvature of the road). The reference angle was obtained through a predictive command with a Receding Horizon Controller. \n\\item The third proposed control strategy was nonlinear; it proceeded by inversion of the dynamics of the inclination angle (linearization by looping), which resulted in a double integrator dynamics $M_{t}=\\ddot{\\theta}$. A PID was then used such that $M_{t}=(K_{p}+K_{d}s+K_{i}/s)(\\theta-\\theta_{ref})$ \n\\end{itemize}\n\nThe simulations showed that the nonlinear controller (strategy 3) was much more efficient than the LQ controller (strategy 2) in minimizing the tilt torque. The best performances were nevertheless obtained with the RCH controller (strategy 2), underlining the importance of the anticipation of the transient performance of the inclination control.\n\n\\item The SDTC commands were discussed by \\textbf{Kidane, S. \\textit{et al.} (2008), (2010})\\cite{doi:10.1080/00423110701352987,5356230}. The authors proposed 3 DTC strategies, and 3 STC strategies, in order to find the methodology ensuring the best switching in SDTC. \n\nThe \\textbf{DTC strategies} were all based on a PD controller, but differed in the expression of the reference $\\theta_{ref}$ chosen:\n\\begin{enumerate}\n\\item $\\theta_{ref}=\\frac{V\\dot{\\psi}}{g}=\\frac{V^2}{gR}$\n\\item $\\theta_{ref}=\\frac{\\ddot{y}+V\\dot{\\psi}}{g}-\\frac{2(I_{wheel rot}\\,w\\,\\dot{\\psi}/(hm)}{g}$\n\\item $\\theta_{ref}=k_{s}(\\delta_{driver})$\n\\end{enumerate}\n\nThe first expression is the most simplified; it neglects the term of lateral slip $\\ddot{y}$, which leads to a significant increase in the transient torque. The second expression is more rigorous and the term $2(I_{wheel rot}\\,w\\,\\dot{\\psi}/(mgh)$, which takes into account the gyroscopic moments at the level of the wheels, leads to a zero static error, but it is difficult to calculate. Finally, to circumvent the problem of contradictory STC and DTC control signals, the authors retained the third expression (i.e. $\\theta_{des}=k_{s}(\\delta_{driver})$), although it is very approximate and does not optimize the torque required in transient situations. \n\nThe \\textbf{STC strategies} also used a PD controller, with an additional term $\\delta_{ss}$, which allowed a steering angle equal to that desired by the driver to be obtained in steady state: $\\delta=K_{p}(\\theta-\\theta_{ref})+K_d{\\dot{\\theta}-\\dot{\\theta}_{ref})+\\delta_{ss}$. The three STC strategies differed in their choice of $\\delta_{ss}$:\n\n\\begin{enumerate}\n\\item The most complete proposed expression uses the value of unmeasured and therefore inaccessible variables.\n\\item An alternative expression performs the rewriting of expression 1. as a function of $\\theta_{ref}$ and parameters to be estimated.\n\\item The last strategy replaces $\\delta_{ss}$ by an integral term on the deviation $(\\theta-\\theta_{ref})$. This is the solution chosen for the SDTC command.\n\\end{enumerate}\n\n\\item The \\textbf{SDTC controller} was then made up of two independent PIDs; one controller generated the motor torque $M_{t}$, and the second the steering angle $\\delta$ applied to the wheels. $V_o$ and $V_f$ were two threshold values, $V_{o}<V_{f}$ for the longitudinal velocity. For $V<V_{o}$, the DTC system is active; for $V>V_{f}$, the STC system takes over; For $V_{o}<V<V_{f}$ a function dependent on $V$ shared the control between DTC and STC. \n\nThe controller was validated in simulation and experimentally by \\textbf{Kidane S. \\textit{et al.}, 2010}\\cite{5356230}. The results were acceptable, but the perceived lateral acceleration was not given, and no stability study was proposed. On the other hand, the proposed SDTC controller did not explicitly optimize the energy required for implementing this strategy.\n\\newpage\n\n\\item In the Netherlands, \\textbf{Carver Europe} developed a three-wheel recliner called Carver. This vehicle was equipped with a Dynamic Vehicle Control system that used the DTC and STC strategies. The publications relating to this system remain evasive, probably due to the confidentiality of the project. However, several patents are filed separately concerning the use of the steering angle in the tilt controller (CR Van Den Brink \\textit{et al.}, 1999)\\cite[-3cm]{van1999realization}, the simultaneous action of the STC and DTC systems (CR Van Den Brink And Kroonen, 2004)\\cite{van1997dynamic}.\n\n\\item At the \\textbf{University of Bath}, researchers worked on the \\textbf{Clever} project: a three-wheeled vehicle, in which only the chassis and front wheel were tilted. This vehicle was equipped with a DTC system, operating with hydraulic actuators. In their work, Berote \\textit{et al.}, (2008)\\cite{bath15090} the authors focused on the analysis of the Clever dynamics, emphasizing the importance of rear wheel steering to limit the risk of over-turning of the vehicle. The authors also evoked the advantage of having the axis of rotation of the vehicle inclined (and not horizontal), which affects the inertia of the inclination movement. The DTC controller remained very basic: a PD to control the angle of inclination. \n\n\\end{itemize}\n\\end{itemize}\n\n\\newpage\n\\section{DTC: Summary of Difficulties and Solutions}\n\nIn this section the problems of DTC control are identified, and solutions are proposed to improve the performance of the controller.\n\n\\subsection{Difficulties related to DTC} \n\nDTC strategies are generally based on a pursue of the angle of inclination $\\theta$, such that $\\theta\\rightarrow\\theta_{ref}$, where $\\theta_{ref}$ is given by the expression  $\\theta_{ref}=\\tan^{-1}(a_{lat}/g)$ or even more simplified or approximate versions which have been described in detail in the previous section (i.e. $\\theta_{ref}=V_{x}\\dot{\\psi}/g$, or $\\theta_{ref}=k_{s}(\\delta_{driver})$, etc.). The weak points of these strategies can be summarized as follows:\n\\begin{enumerate}\n\\item \\textbf{High torque from the actuator on the transient phase}: the calculation of $\\theta_{ref}$ from the measurement of lateral acceleration $a_{lat}$ or yaw angle $\\dot{\\psi}$, induces an \\textbf{intrinsic delay}: the actuator is only activated after the detection of the lateral acceleration through the accelerometer. The inclination torque must therefore compensate for the lateral acceleration already present, which inclines the vehicle towards the outside of the curve before being able to incline it in the opposite direction with the actuator. \n\n\\begin{figure*}[!h]\n\t\\includegraphics[width=1.0\\linewidth]{figs/03/torque}\n\t\\caption{Transitional phase of the vehicle approaching a turn: increasing $a_{lat}$, inclining the vehicle outside the turn and requiring a greater $M_t$}\n\t\\label{torque}\n\\end{figure*}\n\nThe longer the $M_t$ reaction, the greater the lateral acceleration, and the greater the required tilt torque. When other sensors that allow the trajectory prediction are installed on the vehicle (camera), this anticipation makes it possible to reduce the tilting torque significantly (Piyabongkran D. and Al., 2004)\\cite[0cm]{piyabongkarn2004active}. In addition, the lateral acceleration ($a_{lat}=\\ddot{y}+V\\dot{\\psi}\\cos\\beta$) is proportional to the speed. Thus, the higher the speed, the greater the lateral acceleration and the greater the torque $M_t$ required.\n\\newpage\n\\item \\textbf{Static error}: Given the way in which the reference is calculated,  $\\theta=\\theta_{ref}$ does not mean that $a_{per}$ is strictly null. Consequently, the actuator must permanently supply a non-zero torque to maintain the inclination of the vehicle at $\\theta_{ref}$.\n\\end{enumerate}\n\\subsection{Proposed solutions} \n\nThe two main solutions to improve the operation of the DTC systems are: A) Using the steering angle input from the driver as a regulator and B) Directly controlling the perceived lateral acceleration.\n\\begin{enumerate}\n\\item \\textbf{Reduction of the actuator torque in DTC}\n\nWhen driving of a motorcycle, the rider tilts it as soon as the turn begins, before the appearance of the lateral acceleration. Consequently the effort required for the inclination is relatively small; and this is also the case for a vehicle whose path is known in advance. It is, thus, essential to initiate the inclination as soon as possible. \n\nThe first measurable signal containing information about the near trajectory is the \\textbf{angle (or even the torque) of steering}. This signal must be used in order to initiate the inclination of the vehicle before the perception of lateral acceleration. %This will be an essential part of the strategy followed in this thesis.\n\nThe steering angle is considered as a \\textbf{disturbance} which induces an increase in the perceived lateral acceleration, such as to destabilize the vehicle. In order to be able to use this signal in the controller, a control methodology is chosen to be able to take into account this knowledge of the environment. \n\n\\item \\textbf{Cancellation of the static error and improvement of the DTC performance}\n\nThe lateral stability is obtained by the appropriate inclination of the vehicle. It is therefore intuitive to seek to control the angle of inclination $\\theta\\rightarrow\\theta_{ref}$ by calculating the necessary torque to achieve an inclination coherent with the terminal objective: $a_{per}=0$. To reduce the problem of the approximation and to reduce the risks of instability ($\\theta_{ref}$ is deduced from the state variables) the \\textbf{direct control of the perceived lateral acceleration} $a_{per}$ is proposed.\\cite{6315042}\n\nTherefore, the objective variable is now the $a_{per}=0$ rather than $\\theta=\\theta_{ref}$. In addition, in order to ensure the robust asymptotic cancellation of the static error, the integral of $a_{per}$ ($a_{per}^{I}$) will be taken into account. This approach is much more interesting since $a_{per}$ is measured by the inertial motion unit (IMU).\n\\end{enumerate}\n\\newpage\n\\section{Design of the DTC Controller}\n\\subsection{Dynamic Model}\nIn the previous chapter, the linearized dynamic model was obtained:\n\\begin{eqnarray}\n\\label{dynamic_model_1}\nm\\ddot{y}+mV \\dot{\\psi}+mh\\ddot{\\theta}=F_{f}+F_{r} \\\\\nI_{z}\\,\\ddot{\\psi}=L_{f}F_{f}-L_{r}L_{r}-(I_{wr,\\theta}-I_{wr,rot})w_{rot}\\dot{\\theta}-M_{\\delta}\\\\\nI_{x} \\ddot{\\theta}=mgh\\theta -F_{f}h-F_{r}h + +2(I_{wf,\\psi}-I_{wf,rot})w_{rot}(\\dot{\\psi}+\\dot{\\delta}) +M_{t}\\\\\n2\\,I_{wf,\\psi}\\ddot{\\delta}=M_{\\delta}+M_{trail}-2(I_{wf,\\theta}-I_{wf,rot})w_{rot}\\dot{\\theta}\n\\label{dynamic_model_2}\n\\end{eqnarray}\n\\[F_{f}=2 C_{f}\\Big(\\delta - \\frac{\\dot{y}+L_{f} \\dot{\\psi}}{V} \\Big) + 2 \\lambda_{f} \\theta\\]\n\\[F_{r}=C_{r}\\Big(- \\frac{\\dot{y}-L_{r} \\dot{\\psi}}{V} \\Big) +\\lambda_{r} \\theta\\]\n\nThe inputs to this model are the steering angle $\\delta$ and the tilting torque $M_{t}$.\n\n\\subsection{Methodological Approach}\nThe general idea consists in formalizing the problem through the construction of a generic model, called standard, allowing the reformulation of the problem of control in an optimization problem $H_{2}$\\cite[-2cm]{Zhou:1996:ROC:225507}. This model $P(S)$ is structured and consists of the aggregation of:\n\\begin{itemize}\n\\begin{itemize}\n\\item \\textbf{Plant}: A model of the system to be monitored, displaying disturbance and control signals and well as the output variables to be controlled.\n\\item \\textbf{Disturbance}: A model of the environment of the system to be controlled, generating the exogenous signals such as perturbations and setpoints.\n\\item \\textbf{Output}: A model of the quantities to be regulated, including weights constituting adjustment coefficients.\n\\end{itemize}\n\\end{itemize}\n\\begin{marginfigure}[-4.5cm]\n\t\\includegraphics[width=1.2\\linewidth]{figs/03/standard}\n\t\\caption{Standard Problem}\n\t\\label{standard}\n\\end{marginfigure}\n\nThe associated $H_{2}$ is considered in the generic form, which consists in determining $K_{s}$ stabilizing the process model and minimizing: $\\lVert P(s)\\,K(s) \\rVert _{2}$\n\n\\subsection{State Space Model}\nThe obtained model of the form described by equations (\\ref{dynamic_model_1}-\\ref{dynamic_model_2}) is reduced to its controllable and observable part which has 4 states $(\\dot{y},\\dot{\\psi},\\theta,\\dot{\\theta})$.\nThe Linear Parameter Variant (LTV) model is parameterized by the longitudinal speed $V$ of the vehicle:\n%\\begin{equation}\n%\\begin{cases}\\dot{x}(t)=A(V)\\,x(t)+B\\,u(t)\\\\ y(t)=C\\,x(t)+D\\,u(t)\\end{cases}\n%\\end{equation}\n\\begin{equation}\n\\begin{cases}\\dot{x}=A\\,x+B_{u}\\,u+B_{d}\\,d\\\\ y=C\\,x+D_{u}\\,u+D_{d}\\,d\\end{cases}\n\\end{equation}\n\nwith $x^{T}=\\begin{bmatrix}\n\\dot{y} & \\dot{\\psi} & \\theta & \\dot{\\theta}\n\\end{bmatrix}^{T} \\in \\Re^4$, $u=M_{t}$ and $d=\\delta$\n\n$A=\\begin{bmatrix} \n\\frac{1}{V}\\big(-\\frac{a}{m}-\\frac{h^{2}a}{I_{x}}\\big) & \\frac{1}{V}\\big(-\\frac{b}{m}-\\frac{h^{2}b}{I_{x}}\\big)-V & (2\\lambda_{f}+\\lambda_{r})\\big(\\frac{1}{m}+\\frac{h^2}{I_{x}}\\big)-\\frac{mgh^2}{I_{x}} & 0\\\\\n-\\frac{b}{V\\,I_{z}} & -\\frac{2C_{f}L_{f}^{2}+C_{r}L_{r}^{2}}{V\\,I_{z}} & \\frac{2\\lambda_{f}L_{f}-\\lambda_{r}L_{r}}{I_{z}} & 0\\\\\n0 & 0 & 0 & 1\\\\\n\\frac{h\\,a}{V\\,I_{x}} & \\frac{h\\,b}{V\\,I_{x}} & \\frac{mgh-h(2\\lambda_{f}+\\lambda_{r}}{I_{x}} & 0\n\\end{bmatrix}\n$\\\\[10pt]\n$B_{d}=B_{\\delta}=\\begin{bmatrix} 2C_{f}\\big(\\frac{1}{m}+\\frac{h^2}{I_{x}} & \\frac{2C_{f}L_{f}}{I_{z}} & 0 & -\\frac{2C_{f}h}{I_{x}} \\end{bmatrix}^{T}$,\\\\[10pt]\n$B_{u}=B_{M_{t}}=\\begin{bmatrix} -\\frac{h}{I_{x}} & 0 & 0 & \\frac{1}{I_{x}} \\end{bmatrix}^{T}$, $a=2\\,C_{f}+C_{r}$, $b=2\\,C_{f}L_{f}-C_{r}L_{r}$\n\nThe model becomes an Linear Time Invariant (LTI) model when a constant longitudinal velocity $V$ is considered. The vector $x$ denotes the states , $y$ the measured the outputs, $u$ the control input and $d$ is considered as a disturbing exogenous signal\\cite{kCraig}.\n\n\\subsection{Estimation of $\\dot{y}$}\nThe PEV will include a Inertial Measurement Unit (IMU), which will provide the state values $\\theta$, $\\dot{\\theta}$, and $\\dot{\\psi}$, but not $\\dot{y}$. The IMU will also give the value for the perceived lateral acceleration $a_{per}$. Note that this measure was not used in the previous strategy, nor in the classical strategy of controlling $\\theta$ such that $\\theta=\\theta_{des}$ steering angle $\\delta$ and its derivative $\\dot{\\delta}$ will be measured.\n\nThe state signal $\\dot{y}$ can be estimated from the measured signals: $y_{p}=\\begin{bmatrix}\n\\dot{\\psi} & \\theta & \\dot{\\theta} & a_{per} \\end{bmatrix}^{T}$, according to:\\\\[8pt]\n\\begin{aligned}\n\\hat{\\dot{y}}=(a_{11}+ha_{41})^{-1}\\Big[a_{per}-(a_{12}+ha_{42}+V_{x})\\dot{\\psi}-(a_{13}+ha_{43}-g)\\theta \\\\- (a_{14}+ha_{44})\\dot{\\theta}-(b_{\\delta 1}+hb_{\\delta 4})\\delta-(b_{u1}+hb_{u4})M_{t}\\Big]\n\\end{aligned}\n\\\\[8pt] where terms $a_{ij}$, $b_{\\delta i}$ and $b_{ui}$ are coefficients of matrices $A$, $B_{\\delta}$ and $B_{u}$ respectively.\n\n\\subsection{Expressing $a_{per}$ as function of $x$}\nLateral stability of the vehicle is obtained when the sum of lateral forces and torques at its center of gravity is zero ($a_{per}=0$). \n\n$\\hspace{1.5cm} a_{per}=a_{lat}\\cos\\theta+h\\ddot{\\theta}-g\\sin\\theta$\\quad with  \\quad $a_{lat}=\\ddot{y}+V\\,\\dot{\\psi}$\n\nThe $a_{per}$ is a measured signal, but is not part of the state vector. Using small angle approximations, it can be expressed as a function of the state vector as follows:\n\\[a_{per}\\approx\\ddot{y}+V\\,\\dot{\\psi}+h\\ddot{\\theta}-g\\theta=a_{per}^{lin}\\]\n\\[a_{per}^{lin}=\\begin{bmatrix} 0 & V & -g & 0 \\end{bmatrix} x + \\begin{bmatrix} 1 & 0 & 0 & h \\end{bmatrix} \\dot{x}=G_{1}\\,x+G_{2}\\,\\dot{x}\\]\n\nReplacing $\\dot{x}$ by $A\\,x+B_{u}\\,u+B_{d}\\,d$ leads to:\n\\[a_{per}^{lin}=G_{1}\\,x+G_{2}(A\\,x+B_{u}\\,u+B_{d}\\,d)=G\\,x+H_{u}\\,u+H_{d}\\,d\\]\nwith $G=G_{1}+G_{2}\\,A$, $H_{u}=G_{2}\\,B_{u}$ and $H_{d}=G_{2}\\,B_{d}$. The output vector is defined as $y=\\begin{bmatrix} a_{per} & \\dot{\\psi} & \\theta & \\dot{\\theta} & \\delta \\end{bmatrix}^{T}$ Therefore:\n\n$\\hspace{2cm} C=\\begin{bmatrix}\nG \\\\ \\begin{bmatrix} 0_{3x1} I_{3} \\end{bmatrix} \\\\ 0_{1x4} \n\\end{bmatrix}$, $D_{u}=\\begin{bmatrix}\nH_{u} \\\\ 0_{4x1}\n\\end{bmatrix}$, $D_{d}=\\begin{bmatrix}\nH_{d} \\\\ 0_{3x1} \\\\ 1\n\\end{bmatrix}$\n\n\\subsection{Regulator Problem with Internal Stability \\cite{6315042}}\n\nThe fundamental control objective to ensure the lateral stability is to solve the regulation problem $a_{per}=0$. The problem formulation is recast as a standard regulator problem with internal stability (RPIS) where $\\delta$ is considered as a disturbance, and its effect on the perceived lateral acceleration $a_{per}$ should be canceled by the tilt torque $M_{t}$. \n\n\\begin{figure}[!h]\n\t\\includegraphics[width=0.95\\linewidth]{figs/03/control}\n\t\\caption{Control diagram: Feedforward and feedback loops}\n\t\\label{control}\n\\end{figure}\n\n\\textbf{Plant Model}\n\\begin{equation}\n\\begin{cases}\\dot{x}=A\\,x+B_{u}\\,u+B_{d}\\,d\\\\ y=C\\,x+D_{u}\\,u+D_{d}\\,d\\\\ z=G\\,x+H_{u}\\,u+H_{d}\\,d\\end{cases}\n\\end{equation}\nwith $G=\\begin{bmatrix}\n-{a}/{V\\,m} & -{b}/{V\\,m} & (2\\lambda_{f}+\\lambda_{r})/m - g & 0\n\\end{bmatrix} \\\\[6pt] H_{u}=0, H_{d}={2C_{f}}/{m}$\n\n\\textbf{Disturbance Model} \n\\begin{equation}\n\\begin{cases}\\dot{x_{e}}=A_{e}\\,x+B_{e}\\,w\\\\ d=C_{e}\\,x_{e}\\end{cases}\n\\end{equation}\nwith $x_{e}^{T}=\\begin{bmatrix}\n\\delta & \\dot{\\delta}\n\\end{bmatrix}^{T}$, $C_{e}=\\begin{bmatrix}\n1 & 0\n\\end{bmatrix} $, $A_{e}=\\begin{bmatrix}\n0 & 1 \\\\ -\\tau\\alpha & -(\\tau +\\alpha) \n\\end{bmatrix}$, $B_{e}=\\begin{bmatrix}\n0 \\\\ \\beta\n\\end{bmatrix}$\n\nwhere $w$ is an impulse signal, $\\alpha$, $\\tau$ and $\\beta$ determine the time constants and amplitude of the $2^{nd}$ order signal. This model is critical to obtain good performances in transient phases, while the feedback takes care of the static ones and guarantees robust regulation.\n\n\\textbf{Standard Model}\\\\[6pt]\n\\[\\begin{bmatrix} \\dot{x} \\\\ \\dot{x_{e}} \\end{bmatrix} = \\begin{bmatrix}\nA & B_{d}\\,C_{e} \\\\ 0 & A_{e}\\end{bmatrix}\\begin{bmatrix} x \\\\ x_{e} \\end{bmatrix} +\\begin{bmatrix} B_{u} \\\\ 0 \\end{bmatrix} u + \\begin{bmatrix}0 \\\\ B_{e} \\end{bmatrix} w\\]\n\n\\[e=z=\\begin{bmatrix}G & H_{d}\\,C_{e}\\end{bmatrix}\\begin{bmatrix}x \\\\ x_{e}\\end{bmatrix} + H_{u}\\,u\\]\n\n\\[y=\\begin{bmatrix}x \\\\ x_{e}\\end{bmatrix}=\\begin{bmatrix}\n\\dot{y} & \\dot{\\psi} & \\theta & \\dot{\\theta} & \\delta & \\dot{\\delta}\\end{bmatrix}^{T}\\]\n\n\\textbf{Solution for RPIS}\n\nAssuming that the plant model is stabilizable, a solution for the RPIS problem exists in the feedback form if the unique solution ($T_{a},F_{a}$) of the occultation equations exists:\n\\begin{eqnarray}\n-A\\,T_{a}+T_{a}\\,A_{e}+B_{d}\\,C_{e}=-B_{u}\\,F_{a} \\\\\n-G\\,T_{a}+H_{d}\\,C_{e}=H_{u}\\,F_{a}\n\\end{eqnarray}\n\nIf $\\exists\\, T_{a}, F_{a} \\rightarrow u_{ref}=-F_{a}\\,x_{e}$ and $x_{ref}=-T_{a}\\,x_{e}$ is the unique reference trajectory for the plant model that satisfies the control objective $e=a_{per}=0$. Therefore this trajectory satisfies the dynamic of the system:\n\\begin{equation}\n\\begin{cases}\\dot{x}_{ref}=A\\,x_{ref}+B_{u}\\,u_{ref}+B_{d}\\,d\\\\ z_{ref}=G\\,x_{ref}+H_{u}\\,u_{ref}+H_{d}\\,d\\end{cases}\n\\label{sylvester}\n\\end{equation}\nDefining $(\\tilde{u},\\,\\tilde{x},\\,e)=(u-u_{ref},\\,x-x_{ref},\\,z-z_{ref})$ the difference between the actual and desired values of the current control input, states and controlled output.\n\nThe first step is to compute the feedback gain $K$, designed such that $\\tilde{u}=-K\\tilde{x}$ guarantees $\\tilde{x}\\rightarrow 0$ and $e\\rightarrow 0$ (stabilization of the plant). The second step a feedforward gain is designed in order for $(u,x)$ to follow the reference trajectory $u_{ref},x_{ref}$ in an optimal way.\n\n\\textbf{Feedback Gains}\n\nFor the calculation of the feedback gains, the Linear Quadratic Regulator (LQR)\\cite{lec5}\\cite{rob3}\\cite{Wonham:1614618} has been chosen based on the good robustness properties, few tuning parameters and the explicit minimization of the energy of control signals required to follow the reference.\n\nThe LQR consists on finding the state feedback $\\tilde{u}=-K\\tilde{x}$ that minimizes the criteria:\n\\[J_{LQR}=\\int_{0}^{\\infty}{\\big(z^{T}\\,Q\\,z + u^{T}\\,R\\,u \\big) dt}=\\int_{0}^{\\infty}{\\big(x^{T}\\,Q_{x}\\,x + u^{T}\\,R\\,u + 2 x^{T}\\,N_{xu}\\,u\\big) dt}\\]\nThe weighting matrices $Q$ and $R$ must be positive and will balance the minimization of the state vector or the control signal.\n\\[Q_{x}=G^{T}\\,Q\\,G\\]\n\\[R_{u}=H_{u}^{T}\\,Q\\,H_{u} + R\\]\n\\[N_{ux}=G^{T}\\,Q\\,H_{u}\\]\nThe solution is given by:\n\\[K=-R_{u}^{-1}\\,B_{u}^{T}\\,P\\]\nWhere $P$ is the unique solution of the Riccati equation applied to the plant model:\n\\[A^{T}\\,P+P\\,A-P\\,B_{u}\\,R_{u}^{-1}\\,B_{u}^{T}\\,P+Q_{x}=0\\]\n\n\\textbf{Feedforward Gains}\n\nSolving the Sylvester equations in (\\ref{sylvester}) and using the feedback gains $K$, the feedforward gain is calculated as $K_{d}=F_{a}+K\\,T_{a}$.\n\n\\begin{aligned}\n\\tilde{u}=-K\\tilde{x} \\quad \\rightarrow \\quad & u-u_{ref}=-K\\,(x-x_{ref}) \\\\[6pt] & u + F_{a}\\,x_{e}=-K(x+T_{a}\\,x_{e} \\\\\n& u=-K\\,x -(F_{a}+K\\,T_{a})x_{e}=-K\\,x-K_{d}\\,x_{e}\n\\end{aligned}\n\n\\subsection{Extended model with the integral of $a_{per}$: $a_{per}^_{I}$}\nIn order to avoid any static error, the integrated value of the lateral perceived acceleration will be controlled, and its value will be added to the state vector. In fact, it is unavoidable to have some model errors due to parameters uncertainty, neglected dynamics or linearization of the model.\n\nThe equation to add to the model is very simple: \n\\[\\dot{a_{per}^_{I}}=a_{per}=G\\,x+H_{u}\\,u+H_{d}\\,d\\]\nThe augmented state is then $x_{i}=\\begin{bmatrix} \\dot{y} & \\dot{\\psi} & \\theta & \\dot{\\theta} & a_{per}^_{I} \\end{bmatrix}$, and the new system:\n\\begin{equation}\n\\begin{cases}\\dot{x_{i}}=A\\,x_{i}+B_{iu}\\,u+B_{id}\\,d\\\\ z=a_{per}^_{I}}=G_{i}\\,x_{i}+H_{iu}\\,u+H_{id}\\,d\\end{cases}\n\\end{equation}\n\n\\[A_{i}=\\begin{bmatrix} A & 0_{4x1} \\\\ G & 0{1x1} \\end{bmatrix}, \\quad B_{iu}=\\begin{bmatrix} B_{u} \\\\ H_{u} \\end{bmatrix}, \\quad B_{id}=\\begin{bmatrix} B_{d} \\\\ H_{d} \\end{bmatrix}\\]\n\\[G_{i}=\\begin{bmatrix} 0 & 0 & 0 & 0 & 1 \\end{bmatrix}, \\quad H_{iu}=0, \\quad H_{id}=0\\]\n\n\\textbf{Extended Standard Model}\\\\[6pt]\n\\[\\begin{bmatrix} \\dot{x_i} \\\\ \\dot{x_{e}} \\end{bmatrix} = \\begin{bmatrix}\nA_{i} & B_{id}\\,C_{e} \\\\ 0_{2x5} & A_{e}\\end{bmatrix}\\begin{bmatrix} x_{i} \\\\ x_{e} \\end{bmatrix} +\\begin{bmatrix} B_{iu} \\\\ 0_{2x1} \\end{bmatrix} u + \\begin{bmatrix}0_{2x1} \\\\ B_{e} \\end{bmatrix} w\\]\\\\[6pt]\n\\[e=z=a_{per}^_{I}}=\\begin{bmatrix}G_{i} & H_{id}\\,C_{e}\\end{bmatrix}\\begin{bmatrix}x_{i} \\\\ x_{e}\\end{bmatrix} + H_{iu}\\,u\\]\\\n\\[y=\\begin{bmatrix}x \\\\ x_{e}\\end{bmatrix}=\\begin{bmatrix}\n\\dot{y} & \\dot{\\psi} & \\theta & \\dot{\\theta} & a_{per}^_{I} & \\delta & \\dot{\\delta}\\end{bmatrix}^{T}\\]\n\n\\textbf{Feedback Gains}\n\nThe Linear Quadratic Regulator is adapted to the extended model: \n\\[J_{LQR}=\\int_{0}^{\\infty}{\\big(z^{T}\\,Q\\,z + u^{T}\\,R\\,u \\big) dt}=\\int_{0}^{\\infty}{\\big(x^{T}\\,Q_{x}\\,x + u^{T}\\,R\\,u + 2 x^{T}\\,N_{xu}\\,u\\big) dt}\\]\n\\[Q_{x}=G_{i}^{T}\\,Q\\,G_{i} \\hspace{1cm} R_{u}=H_{iu}^{T}\\,Q\\,H_{iu} + R \\hspace{1cm} N_{ux}=G_{i}^{T}\\,Q\\,H_{iu}\\]\nThe solution is given by:\n\\[K=-R_{u}^{-1}\\,B_{iu}^{T}\\,P\\]\nWhere $P$ is the unique solution of the Riccati equation applied to the plant model:\n\\[A_{i}^{T}\\,P+P\\,A_{i}-P\\,B_{iu}\\,R_{u}^{-1}\\,B_{iu}^{T}\\,P+Q_{x}=0\\]\n\n\\textbf{Feedforward Gains}\n\nThe Sylvester equations in (\\ref{sylvester}) need to be adapted to the new model:\n\\begin{eqnarray}\n-A_{i}\\,T_{a}+T_{a}\\,A_{e}+B_{id}\\,C_{e}=-B_{iu}\\,F_{a} \\\\\n-G_{i}\\,T_{a}+H_{id}\\,C_{e}=H_{iu}\\,F_{a}\n\\end{eqnarray}\nBy solving these equations and using the feedback gains $K$, the feedforward gain is calculated as $K_{d}=F_{a}+K\\,T_{a}$.\n\n\\textbf{Simple Method Gains Calculation}\n\nA straightforward way of calculating the gains is to solve the Riccati and the Sylvester equations as it is indicated in (Friedland, Chapter 9.6)\\cite{control-system-design} book:\n\n\t-- Riccati eq: $\\quad M_{1}\\,A_{i} + A_{i}^{T}\\,M_{1} - M_{1}\\,B_{iu}\\,R_{u}^{-1}B_{iu}^{T}M_{1} + Q_{x}=0$\n\n\t-- Slyvester eq: $\\quad M_{2}\\,A_{e}+(A_{i}^{T}-M_{1}\\,B_{iu}\\,R_{u}^{-1}\\,B_{iu}^{T})M_{2}+M_{1}\\,B_{id}\\,C_{e}=0$\n\nThen, the gains can be easily calculated:\n\\begin{itemize}\n\\begin{itemize}\n\\item Feedback gains: $K=R_{u}^{-1}\\,B_{iu}^{T}\\,M_{1}$\n\\item Feedforward gains: $K_{d}=R_{u}^{-1}\\,B_{iu}^{T}\\,M_{2}$\n\\end{itemize}\n\\end{itemize}\n\n\\subsection{Derivation of the Gains}\n\nAs was discussed previously, the state variable $\\dot{y}$ is not measured and can only be estimated as:\n\n\\begin{aligned}\n\\hat{\\dot{y}}=(a_{11}+ha_{41})^{-1}\\Big[a_{per}-(a_{12}+ha_{42}+V_{x})\\dot{\\psi}-(a_{13}+ha_{43}-g)\\theta \\\\- (a_{14}+ha_{44})\\dot{\\theta}-(b_{\\delta 1}+hb_{\\delta 4})\\delta-(b_{u1}+hb_{u4})M_{t}\\Big]\n\\end{aligned}\n\nTo calculate the real gains on the controller, a simple but tedious derivation has to be carry out:\n\\[u=-K\\,x_{i}-K_{e}\\,x_{e}\\]\n\\[u=-K_{\\dot{y}}\\,\\dot{y}-K_{\\dot{\\psi}}\\,\\dot{\\psi}-K_{\\theta}\\,\\theta-K_{\\dot{\\theta}}\\,\\dot{\\theta}-K_{a_{per}^{I}}\\,a_{per}^{I}-K_{\\delta}\\,\\delta-K_{\\dot{\\delta}}\\,\\dot{\\delta}\\]\n\\newpage\n\\begin{aligned}\nu&=-\\frac{K_{\\dot{y}}}{a_{11}+ha_{41}}\\,a_{per} - \\Big(K_{\\dot{\\psi}}-K_{\\dot{y}}\\frac{a_{12}+ha_{42}+V_{x}}{a_{11}+ha_{41}}\\Big)\\dot{\\psi} -  \\Big(K_{\\theta}-K_{\\dot{y}}\\frac{a_{13}+ha_{43}-g}{a_{11}+ha_{41}}\\Big)\\theta - \\Big(K_{\\dot{\\theta}}-K_{\\dot{y}}\\frac{a_{14}+ha_{44}}{a_{11}+ha_{41}}\\Big)\\dot{\\theta} - \\\\[10pt] &\\quad -  K_{a_{per}^{I}}\\,a_{per}^{I} - \\Big(K_{\\delta}-K_{\\dot{y}}\\frac{b_{\\delta 1}+hb_{\\delta 4}}{a_{11}+ha_{41}}\\Big)\\delta-K_{\\dot{\\delta}}\\,\\dot{\\delta}-K_{\\dot{y}}\\,\\frac{b_{u1}+hb_{u4}}{a_{11}+ha_{41}}\\,u\n\\end{aligned}\n\\\\\n\n\\begin{aligned}\nu=\\frac{1}{1+K_{\\dot{y}}\\,\\frac{b_{u1}+hb_{u4}}{a_{11}+ha_{41}}}\\Big[&-\\frac{K_{\\dot{y}}}{a_{11}+ha_{41}}\\,a_{per} - \\Big(K_{\\dot{\\psi}}-K_{\\dot{y}}\\frac{a_{12}+ha_{42}+V_{x}}{a_{11}+ha_{41}}\\Big)\\dot{\\psi} - \\Big(K_{\\theta}-K_{\\dot{y}}\\frac{a_{13}+ha_{43}-g}{a_{11}+ha_{41}}\\Big)\\theta - \\\\[10pt] & - \\Big(K_{\\dot{\\theta}}-K_{\\dot{y}}\\frac{a_{14}+ha_{44}}{a_{11}+ha_{41}}\\Big)\\dot{\\theta} -  K_{a_{per}^{I}}\\,a_{per}^{I} - \\Big(K_{\\delta}-K_{\\dot{y}}\\frac{b_{\\delta 1}+hb_{\\delta 4}}{a_{11}+ha_{41}}\\Big)\\delta-K_{\\dot{\\delta}}\\,\\dot{\\delta}\\Big]\n\\end{aligned}\n\\\\\n\n\\begin{aligned}\nu=\\frac{1}{a_{11}+ha_{41}+K_{\\dot{y}}\\,(b_{u1}+hb_{u4})}\\Big[&-K_{\\dot{y}}\\,a_{per} - \\big[K_{\\dot{\\psi}}(a_{11}+ha_{41})-K_{\\dot{y}}(a_{12}+ha_{42}+V_{x})\\big]\\dot{\\psi} - \\\\[8pt] & - \\big[K_{\\theta}(a_{11}+ha_{41})-K_{\\dot{y}}(a_{13}+ha_{43}-g)\\big]\\theta - \\\\[8pt] & - \\big[K_{\\dot{\\theta}}(a_{11}+ha_{41})-K_{\\dot{y}}(a_{14}+ha_{44})\\big]\\dot{\\theta} -  K_{a_{per}^{I}}(a_{11}+ha_{41})\\,a_{per}^{I} - \\\\[8pt] & - \\big[K_{\\delta}(a_{11}+ha_{41})-K_{\\dot{y}}(b_{\\delta 1}+hb_{\\delta 4})\\big]\\delta-K_{\\dot{\\delta}}(a_{11}+ha_{41})\\,\\dot{\\delta}\\Big]\n\\end{aligned}\n\\\\\n\nWith this estimation all the signals are measured and have a gain:\n\\begin{eqnarray}\nK_{a_{per}}^{'}=\\frac{K_{\\dot{y}}}{a_{11}+ha_{41}+K_{\\dot{y}}\\,(b_{u1}+hb_{u4})} \\\\[10pt]\nK_{\\dot{\\psi}}^{'}=\\frac{K_{\\dot{\\psi}}(a_{11}+ha_{41})-K_{\\dot{y}}(a_{12}+ha_{42}+V_{x})}{a_{11}+ha_{41}+K_{\\dot{y}}\\,(b_{u1}+hb_{u4})} \\\\[10pt]\nK_{\\theta}^{'}=\\frac{K_{\\theta}(a_{11}+ha_{41})-K_{\\dot{y}}(a_{13}+ha_{43}-g)}{a_{11}+ha_{41}+K_{\\dot{y}}\\,(b_{u1}+hb_{u4})} \\\\[10pt]\nK_{\\dot{\\theta}}^{'}=\\frac{K_{\\dot{\\theta}}(a_{11}+ha_{41})-K_{\\dot{y}}(a_{14}+ha_{44})}{a_{11}+ha_{41}+K_{\\dot{y}}\\,(b_{u1}+hb_{u4})} \\\\[10pt]\nK_{a_{per}^{I}}^{'}=\\frac{K_{a_{per}^{I}}(a_{11}+ha_{41})}{a_{11}+ha_{41}+K_{\\dot{y}}\\,(b_{u1}+hb_{u4})} \\\\[10pt]\nK_{\\delta}^{'}=\\frac{K_{\\delta}(a_{11}+ha_{41})-K_{\\dot{y}}(b_{\\delta 1}+hb_{\\delta 4})}{a_{11}+ha_{41}+K_{\\dot{y}}\\,(b_{u1}+hb_{u4})} \\\\[10pt]\nK_{\\dot{\\delta}}^{'}=\\frac{K_{\\dot{\\delta}}(a_{11}+ha_{41})}{a_{11}+ha_{41}+K_{\\dot{y}}\\,(b_{u1}+hb_{u4})}\n\\end{eqnarray}\n\\[K^{'}=\\begin{bmatrix}\nK_{a_{per}}^{'} & K_{\\dot{\\psi}}^{'} & K_{\\theta}^{'} & K_{\\dot{\\theta}}^{'} & K_{a_{per}^{I}}^{'} & K_{\\delta}^{'} & K_{\\dot{\\delta}}^{'}\n\\end{bmatrix} \\]\n\\newpage\n\\subsection{Gain Scheduled Controller}\nThe previous regulator was synthesized by considering a constant value of the longitudinal speed $V_{x}$. But the state space model is LPV and the matrices $A$ and $C$ depend on $V$ or $1/V$. Thus, the proposed controller is not valid for the whole speed range. In this section, a controller that depends on the longitudinal speed of the vehicle is proposed. \n\nThe approach adopted is pragmatic, and proceeds by interpolation of the LTI regulators obtained for a discrete set of longitudinal speeds. It thus guarantees a good performance at every operating point. Stability guarantees will also be provided by a posteriori analysis. \n\nThe first step is the observation of the gain variation of this regulator as a function of velocity for $V \\in {2,3,...18}\\,m/s $. A regulator is synthesized for each value of $V$ and the variation of the gains can be approximated by a function of the form:\n\\[K(V)=K_{c}+K_{V}\\,V+K_{1/V)\\V\\]\nDependent on $V$ and $1/V$, with $K_{c}$, $K_{V}$ and $K_{1/V}$ the constants to be identified. These values can be easily deduced from the least squares resolution of the following system of equations:\n\\[\n\\underbrace{\\begin{pmatrix}\n1 & V_{1} & 1/V_{1} \\\\ 1 & V_{2} & 1/V_{2} \\\\ ... & ... & ... \\\\ 1 & V_{17} & 1/V_{17} \\\\\n\\end{pmatrix}}_{M} \n\\begin{pmatrix} K_{c} \\\\ K_{V} \\\\ K_{1/V} \\end{pmatrix}=\n\\underbrace{\\begin{pmatrix} K_{V_{1}}^{'} \\\\K_{V_{2}}^{'} \\\\ ... \\\\ K_{V_{17}}^{'} \\end{pmatrix}}_{K_{M}}\n\\Rightarrow\n\\begin{pmatrix} K_{c} \\\\ K_{V} \\\\ K_{1/V} \\end{pmatrix}=(M^{T}\\,M)^{-1}\\,M^{T}\\,K_{M}\\]\n\n\\newpage\n\\section{Control Strategy Summary}\nIn this chapter the control strategy has been completely derived and developed. The process of calculating the gains can be resumed in few steps:\n\\begin{enumerate}\n\\item To obtain or measure the \\textbf{parameters to complete the dynamic model}. This includes the vehicle and the wheels variables: \n\n$\\hspace{2cm} m \\enspace L_{f} \\enspace L_{r} \\enspace I_{x} \\enspace I_{z} \\enspace C_{f} \\enspace C_{r} \\enspace \\lambda_{f} \\enspace \\lambda_{r} \\enspace ...$.\n\n\\item To suppose a \\textbf{constant $V$ for the model}, so that $V \\in {2,3,...18}\\,m/s $\n\n\\item To generate the \\textbf{matrices of the state space} model:\n\n$\\hspace{1.5cm} A \\enspace B_{u} \\enspace B_{d} \\enspace C \\enspace D_{u} \\enspace D_{d} \\enspace G \\enspace H_{u} \\enspace H_{d} \\enspace A_{e} \\enspace B_{e} \\enspace C_{e} \\enspace ...$\n\n\\item \\textbf{Feedback gains}: To solve the Riccati equation for the selected model and calculate the gains: \n\n$\\hspace{1.5cm} M_{1}\\,A_{i} + A_{i}^{T}\\,M_{1} - M_{1}\\,B_{iu}\\,R_{u}^{-1}B_{iu}^{T}M_{1} + Q_{x}=0$\n\n$\\hspace{3.5cm} K=R_{u}^{-1}\\,B_{iu}^{T}\\,M_{1}$\n\n\\item \\textbf{Feedforward gains}: To solve the Slyvester equation for the selected model and calculate the gains: \n\n$\\hspace{1cm}M_{2}\\,A_{e}+(A_{i}^{T}-M_{1}\\,B_{iu}\\,R_{u}^{-1}\\,B_{iu}^{T})M_{2}+M_{1}\\,B_{id}\\,C_{e}=0$\n\n$\\hspace{3.5cm} K_{d}=R_{u}^{-1}\\,B_{iu}^{T}\\,M_{2}$\n\n\\item \\textbf{Gain Scheduling}: To repeat the steps 2 to 5 with all the speed range and calculate the constants $K_{c}$, $K_{V}$ and $K_{1/V}$  with:\n\n$\\hspace{2.5cm}\\begin{pmatrix} K_{c} \\\\ K_{V} \\\\ K_{1/V} \\end{pmatrix}=(M^{T}\\,M)^{-1}\\,M^{T}\\,K_{M}$\n\n\\end{enumerate}\n", "meta": {"hexsha": "414add377d3a430acf58d16e29ad897232d16c6e", "size": 41201, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "pages/03controlStrategy.tex", "max_stars_repo_name": "imartinezl/MIT-Media-Lab-latex-thesis", "max_stars_repo_head_hexsha": "f547c9879ca2c2b12ee57ceff9d533061167b701", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-11-25T16:15:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-08T15:09:27.000Z", "max_issues_repo_path": "pages/03controlStrategy.tex", "max_issues_repo_name": "imartinezl/MIT-Media-Lab-latex-thesis", "max_issues_repo_head_hexsha": "f547c9879ca2c2b12ee57ceff9d533061167b701", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pages/03controlStrategy.tex", "max_forks_repo_name": "imartinezl/MIT-Media-Lab-latex-thesis", "max_forks_repo_head_hexsha": "f547c9879ca2c2b12ee57ceff9d533061167b701", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-10-31T00:54:01.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-16T07:29:54.000Z", "avg_line_length": 84.0836734694, "max_line_length": 728, "alphanum_fraction": 0.7069245892, "num_tokens": 13574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.3262931470571076}}
{"text": "\\documentclass{article}\n\\usepackage[usenames,dvipsnames,svgnames]{xcolor}\n\\usepackage[utf8]{inputenc}\n\\usepackage{algpseudocode}\n\\usepackage{amsfonts}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{amsthm}\n\\usepackage{algorithm}\n\\usepackage{tikz}\n\\usepackage{subcaption}\n\\usepackage{fancyvrb}\n\\usepackage{bm}\n\\usepackage{textcomp}\n\\usepackage{listings}\n\\usepackage{todonotes}\n\\usepackage{mathtools} % long right arrow\n\\usepackage{proof} % for infer\n\\usepackage{setspace} % set line spacing\n\\usepackage{amsthm}\n\n\\newtheorem{theorem}{Theorem}[section]\n\\newtheorem{corollary}{Corollary}[theorem]\n\\newtheorem{lemma}[theorem]{Lemma}\n\\newtheorem{definition}{Definition}[section]\n\n\\newcommand{\\code}[1]{\\texttt{\\small{\\textbf{#1}}}}\n\\newcommand{\\reals}[0]{\\mathbb{R}}\n\\newcommand{\\naturals}[0]{\\mathbb{N}}\n\\newcommand{\\integers}[0]{\\mathbb{Z}}\n\\newcommand{\\rationals}[0]{\\mathbb{Q}}\n\\newcommand\\doubleplus{\\mathbin{+\\mkern-5mu+}}\n\\newcommand{\\concat}[0]{\\doubleplus}\n\\newcommand{\\dom}[1]{\\mbox{dom}{~#1}}\n\\newcommand{\\emptyassignment}[0]{\\epsilon}\n\\newcommand{\\gen}[0]{\\mbox{\\scriptsize gen}}\n\\newcommand{\\force}[0]{\\mbox{\\scriptsize force}}\n\\newcommand{\\fix}[0]{\\mbox{\\scriptsize fix}}\n\\newcommand{\\free}[0]{\\mbox{\\scriptsize free}}\n\\newcommand{\\contained}[0]{\\sqsubseteq}\n\\newcommand{\\auxassign}[0]{\\alpha}\n\\newcommand{\\aux}[0]{\\mbox{\\scriptsize aux}}\n\n% coordinates for tikz address schematics\n\\newcommand{\\innerll}[0]{(0.25 + 0.625, 0.625)}\n\\newcommand{\\innerlr}[0]{(0.25 + 0.625 + 0.5, 0.625)}\n\\newcommand{\\innerur}[0]{(0.25 + 0.625 + 0.5, 0.625 + 0.5)}\n\\newcommand{\\innerul}[0]{(0.25 + 0.625, 0.625 + 0.5)}\n\\newcommand{\\outerll}[0]{(0.25, 0)}\n\\newcommand{\\outerlr}[0]{(0.25 + 1.75, 0)}\n\\newcommand{\\outerur}[0]{(0.25 + 1.75, 1.75)}\n\\newcommand{\\outerul}[0]{(0.25, 1.75)}\n\\newcommand{\\all}[0]{(0, 0)}\n\\newcommand{\\alr}[0]{(2, 0)}\n\\newcommand{\\aur}[0]{(2, 2)}\n\\newcommand{\\aul}[0]{(0, 2)}\n\\newcommand{\\bll}[0]{(0.25, -0.25)}\n\\newcommand{\\blr}[0]{(2.25, -0.25)}\n\\newcommand{\\bur}[0]{(2.25, 1.75)}\n\\newcommand{\\bul}[0]{(0.25, 1.75)}\n\n\\title{Gen Semantics}\n\\author{Marco Cusumano-Towner}\n\n\\begin{document}\n\n\\maketitle\n\n\\section{Assignments}\nA \\emph{assignment} is a finite map from a countable set of \\emph{addresses} to \\emph{values}, which for simplicity, we assume are elements of some finite set $V$.\nThe `set of addresses' in an assignment $t$ is its domain $\\dom{t}$.\nFor assignments $s$ and $t$ with disjoint domains $\\dom{s}$ and $\\dom{t}$, let $u = s \\concat t$ denote the assignment $u$ with $\\dom{u} = \\dom{s} \\cup \\dom{t}$ and $u(a) = s(a)$ for $a \\in \\dom{s}$ and $u(a) = t(a)$ for $a \\in \\dom{t}$.\nFor two assignments $s$ and $t$, let $s \\contained t$ denote the relation that $\\dom{s} \\subseteq \\dom{t}$ and that $s(a) = t(a)$ for all $a \\in \\dom{s}$ ($s$ is a restriction of $t$).\nLet $t|_S$ denote the restriction of a assignment $t$ to a set $S$ of addresses, so that $\\dom{t|_S} = \\dom{t} \\cap S$.\nLet $\\emptyassignment$ denote the empty assignment ($\\dom \\emptyassignment = \\varnothing$).\n\n\\section{Probabilistic Module}\nA \\emph{probabilistic module} is a tuple $(X, P, \\theta, f, U^{\\gen}, Q^{\\gen}, Q^{\\fix}, Q^{\\free})$.\nEach of these elements is explained below.\n\n\\paragraph{Input type}\n$X$ is the set of valid \\emph{inputs} to the module, denoted $x \\in X$.\n\n\\paragraph{Generative distribution}\nThe \\emph{generative distribution} of a probabilistic module for input $x \\in X$ is denoted $P_x$, where $P_x(t) \\ge 0$ where $t$ is a assignment and $\\sum_t P_x(t) = 1$.\nLet $T_x := \\{t : P_x(t) > 0 \\}$ denote the set of \\emph{possible assignments} for input $x \\in X$.\nWe require that $P$ satisfies the following \\emph{well-behaved addresses property}:\nFor all $x \\in X$ and all $s, t \\in T_x$, if $\\dom{s} \\ne \\dom{t}$ then $\\exists a \\in \\dom{s} \\cap \\dom{t}$ such that $s(a) \\ne t(a)$.\nIn words, different address sets for the same arguments $x$ must be explained by different value{s} for some shared address(es).\n\n\\paragraph{Output function}\nThe \\emph{output function} $f : \\{(x, t) : x \\in X, t \\in T_x\\} \\to Y$ defines the \\emph{output value} $y \\in Y$ given the inputs $x$ and an assignment.\n\n\\paragraph{Static parameters}\nThe generative distribution may be parametrized by trainable \\emph{static parameters} $\\theta$, in which case $P_x(t)$ is replaced with $P_{x,\\theta}(t)$.\nSee \\code{backprop\\_params} below.\n\n% TODO all of the methods will accept arbitary configuration, which is\n% recursively dispatched throughout the call hierarchy during calls to methods.\n% the address selection is one example type of configuration used to configure\n% free_update.\n\n%%%%%%%%%%%%%%\n%% generate %%\n%%%%%%%%%%%%%%\n\n\\paragraph{Generate Method (\\code{generate})}\nFor each $x \\in X$, $U^{gen}_x$ is a set of assignments, called \\emph{valid generation constraints}, such that for each $u \\in U^{\\gen}_x$ there exists some $t \\in T_x$ where $u \\contained t$.\n$U^{\\gen}_x$ need not include all such $u$ (i.e. $U^{\\gen}_x$ is not necessarily the set of all projections of all assignments in $T_x$).\nWe require that $\\emptyassignment \\in U^{\\gen}_x$ and that $T_x \\subseteq U^{\\gen}_x$.\nFor each $x \\in X$ and $u \\in U^{\\gen}_x$, $Q^{\\gen}_{x,u}$ is a probability distribution on assignments $s$ such that $Q^{\\gen}_{x,u}(s) > 0$ if and only if $t = s \\concat u$ for some $t \\in T_x$.\nThe distribution is normalized ($\\sum_s Q^{\\gen}_{x,u}(s) = 1$).\nGiven $x \\in X$ and $u \\in U^{\\gen}_x$, sample $s \\sim Q^{\\gen}_{x,u}(\\cdot)$, and return $t = s \\concat u$ and a weight $P_x(t) / Q^{\\gen}_{x,u}(s)$.\nAlso return $y = f(x, t)$.\n\n%% generate address schematic %%\n\\begin{figure}[t]\n\\centering\n% dom t\n\\begin{subfigure}[b]{0.3\\textwidth}\n\\centering\n\\begin{tikzpicture}\n\\draw (0, 0) rectangle (1, 1);\n\\draw (0.25, 0.25) rectangle (0.75, 0.75);\n\\filldraw [gray, fill opacity=0.5, draw opacity=0.0] (0, 0) -- (0, 1) -- (1, 1) -- (1, 0);\n\\end{tikzpicture}\n\\caption{$\\dom{t}$}\n\\end{subfigure}%\n% dom u\n\\begin{subfigure}[b]{0.3\\textwidth}\n\\centering\n\\begin{tikzpicture}\n\\draw (0, 0) rectangle (1, 1);\n\\draw (0.25, 0.25) rectangle (0.75, 0.75);\n\\filldraw [gray, fill opacity=0.5, draw opacity=0.0] (0.25, 0.25) -- (0.25, 0.75) -- (0.75, 0.75) -- (0.75, 0.25);\n\\end{tikzpicture}\n\\caption{$\\dom{u}$}\n\\end{subfigure}\n% dom s\n\\begin{subfigure}[b]{0.3\\textwidth}\n\\centering\n\\begin{tikzpicture}\n\\draw (0, 0) rectangle (1, 1);\n\\draw (0.25, 0.25) rectangle (0.75, 0.75);\n\\filldraw [gray, fill opacity=0.5, draw opacity=0.0] (0, 0) -- (1, 0) -- (1, 1) -- (0, 1) (0.25, 0.25) -- (0.25, 0.75) -- (0.75, 0.75) -- (0.75, 0.25);\n\\end{tikzpicture}\n\\caption{$\\dom{s}$}\n\\end{subfigure}\n\\caption{Schematic showing addresses of assignments involved in \\code{generate}}\n\\end{figure}\n\n\\paragraph{Propose Method (\\code{propose})}\nGiven $x \\in X$, and a set of addresses $A$ such that for all $t \\in T_x$, $t|_A \\in U^{\\gen}_x$, sample $t \\sim P_x(\\cdot)$, then decompose $t = u \\concat s$ where $u = t|_A$, and return $u$ and the weight $P_x(t) / Q^{\\gen}_{x,u}(s)$.\nAlso return $y = f(x, t)$.\n\n\n%%%%%%%%%%%%%%%%%%\n%% force update %%\n%%%%%%%%%%%%%%%%%%\n\n\\paragraph{Force Update Method (\\code{force\\_update})}\nFor $x, x' \\in X$, and $t \\in T_x$, let $U^{\\force}_{x,x',t}$ denote the set of assignments $u$ such that there exists $t' \\in T_{x'}$ where $u \\contained t'$ and $\\{ a: t(a) \\ne t'(a)\\} \\subseteq \\dom{u}$, and $\\dom{t'} \\setminus \\dom{t} \\subseteq \\dom{u}$.\nThat is, $u$ contains values for at least all addresses that differ between $t$ and $t'$, and all addresses in $t'$ that are not in $t$.\nReturn $t'$ (see Lemma~\\ref{lemma:force-update-unique} for uniqueness of $t'$), and the weight $p(t'; x') / p(t; x)$ and $y = f(x', t')$.\nAlso return the \\emph{discard assignment} $v$ given by $v(a) = t(a)$ for $a \\in (\\dom{t'} \\setminus \\dom{t}) \\cup (\\dom{t} \\cap \\dom{u})$.\n\n\\begin{lemma} \\label{lemma:force-update-unique}\nFor any such $x, x', t, u$, the assignment $t'$ is unique.\n\\end{lemma}\n\\begin{proof}\nSuppose there exists $t'_1 \\ne t'_2$ such that $u \\contained t'_1$ and $u \\contained t'_2$ and such that $\\dom{u} \\supseteq \\{a : t(a) \\ne t'_1(a) \\lor t(a) \\ne t'_2(a)\\} \\cup ((\\dom{t'_1} \\cup \\dom{t'_2}) \\setminus \\dom{t})$.\nIf $\\dom{t'_1} = \\dom{t'_2}$ then there must be an address $b$ such that $t'_1(b) \\ne t(b)$ or $t'_2(b) \\ne t(b)$, which implies $b \\in \\dom{u}$, which implies $t'_1(b) = t'_2(b) = u(b)$, which is a contradiction.\nIf $\\dom{t'_1} \\ne \\dom{t'_2}$, then by the well-behaved address property, there must be an address $b$ such that $t'_1(b) \\ne t'_2(b)$, which implies $b \\in \\dom{u}$, which implies $t'_1(b) = t'_2(b) = u(b)$, which is a contradiction.\n\\end{proof}\n\n%% force update address schematic %%\n\\begin{figure}[t]\n\\centering\n% dom t\n\\begin{subfigure}[b]{0.2\\textwidth}\n\\centering\n\\begin{tikzpicture}\n\\draw \\all{} rectangle \\aur{};\n\\draw \\bll{} rectangle \\bur{};\n\\draw \\innerll{} rectangle \\innerur{};\n\\filldraw [gray, fill opacity=0.5, draw opacity=0.0] \\all{} -- \\alr{} -- \\aur{} -- \\aul{};\n\\end{tikzpicture}\n\\caption{$\\dom{t}$}\n\\end{subfigure}%\n% dom t'\n\\begin{subfigure}[b]{0.2\\textwidth}\n\\centering\n\\begin{tikzpicture}\n\\draw \\all{} rectangle \\aur{};\n\\draw \\bll{} rectangle \\bur{};\n\\draw \\innerll{} rectangle \\innerur{};\n\\filldraw [gray, fill opacity=0.5, draw opacity=0.0] \\bll{} -- \\blr{} -- \\bur{} -- \\bul{};\n\\end{tikzpicture}\n\\caption{$\\dom{t'}$}\n\\end{subfigure}%\n% dom u\n\\begin{subfigure}[b]{0.2\\textwidth}\n\\centering\n\\begin{tikzpicture}\n\\draw \\all{} rectangle \\aur{};\n\\draw \\bll{} rectangle \\bur{};\n\\draw \\innerll{} rectangle \\innerur{};\n\\filldraw [gray, fill opacity=0.5, draw opacity=0.0] \\innerll{} -- \\innerlr{} -- \\innerur{} -- \\innerul{};\n\\filldraw [gray, fill opacity=0.5, draw opacity=0.0] \\outerll{} -- \\outerlr{} -- \\outerur{} -- \\bur{} -- \\blr{} -- \\bll{} -- \\outerll{};\n\\end{tikzpicture}\n\\caption{$\\dom{u}$}\n\\end{subfigure}%\n% dom v\n\\begin{subfigure}[b]{0.2\\textwidth}\n\\centering\n\\begin{tikzpicture}\n\\draw \\all{} rectangle \\aur{};\n\\draw \\bll{} rectangle \\bur{};\n\\draw \\innerll{} rectangle \\innerur{};\n\\filldraw [gray, fill opacity=0.5, draw opacity=0.0] \\innerll{} -- \\innerlr{} -- \\innerur{} -- \\innerul{};\n\\filldraw [gray, fill opacity=0.5, draw opacity=0.0] \\outerll{} -- \\outerul{} -- \\outerur{} -- \\aur{} -- \\aul{} -- \\all{} -- \\outerll{};\n\\end{tikzpicture}\n\\caption{$\\dom{v}$}\n\\end{subfigure}%\n% dom r\n\\begin{subfigure}[b]{0.2\\textwidth}\n\\centering\n\\begin{tikzpicture}\n\\draw \\all{} rectangle \\aur{};\n\\draw \\bll{} rectangle \\bur{};\n\\draw \\innerll{} rectangle \\innerur{};\n\\filldraw [gray, fill opacity=0.5, draw opacity=0.0] \\outerll{} -- \\outerlr{} -- \\outerur{} -- \\outerul{} \\innerll{} -- \\innerul{} -- \\innerur{} -- \\innerlr{};\n\\end{tikzpicture}\n\\caption{$\\dom{r}$}\n\\end{subfigure}\n\\caption{Schematic showing addresses of assignments involved in \\code{force\\_update}}\n\\end{figure}\n\n\n%%%%%%%%%%%%%%%%\n%% fix update %%\n%%%%%%%%%%%%%%%%\n\n\\paragraph{Fix Update Method (\\code{fix\\_update})}\nFor $x, x' \\in X$ and $t \\in T_x$, let $U^{\\fix}_{x,x',t}$ denote the set of assignments $u$ such that $\\dom{u} \\subseteq \\dom{t}$ and such that there exists assignments $s$ and $r$ with $\\dom{s} \\cap \\dom{t} = \\varnothing$, $\\dom{r} \\subseteq \\dom{t}$, $\\dom{r} \\cap \\dom{u} = \\varnothing$ where $u \\concat s \\concat r \\in T_{x'}$.\nFor each $x, x' \\in X$, $t \\in T_x$, and $u \\in U^{\\fix}_{x,x',t}$, there is a probability distribution on assignments $s$, denoted $Q^{\\fix}_{x,x',t,u}(s)$, such that $Q^{\\fix}_{x,x',t,u}(s) > 0$ if and only if there exists a assignment $r$ with $\\dom{r} \\subseteq \\dom{t}$ and $\\dom{r} \\cap \\dom{u} = \\varnothing$ where $t' = u \\concat s \\concat r \\in T_{x'}$.\n\n\\begin{lemma} \\label{lemma:fix-update-unique}\nFor any such $x, x', t, u, s$, the assignments $r$ and $t'$ are unique.\n\\end{lemma}\n\\begin{proof}\n\\end{proof}\n\nGiven $x, x' \\in X, t \\in T_x, u \\in U^{\\fix}_{x,x',t}$, sample $s \\sim Q^{\\fix}_{x,x',t,u}(\\cdot)$ and return $t' = u \\concat s \\concat r$, the \\emph{discard assignment} $v$ where $v(a) = t(a)$ for $a \\in \\dom{u}$, and the weight:\n\\[\n\\frac{p(t'; x')}{p(t; x)} \\frac{Q^{\\fix}_{x',x,t',v}(s')}{Q^{\\fix}_{x,x',t,u}(s)}\n\\]\nwhere $s' = t|_{\\dom{t} \\setminus \\dom{t'}}$ contains the part of $t$ that was \\emph{deleted}.\nAlso return $y = f(x', t')$.\n\n\\begin{lemma} \\label{lemma:fix-update-reverse}\nIf $x, x' \\in X, t \\in T_x, u \\in U^{\\fix}_{x, x', t}$, and $s$ where $Q^{\\fix}_{x,x',t,u}(s) > 0$, $v \\in U^{\\fix}_{x',x,t'}$ and $Q^{\\fix}_{x',x,t'}(s') > 0$, then $v \\concat s' \\concat r = t$.\n\\end{lemma}\n\\begin{proof}\n\\end{proof}\n\n%% fix update address schematic %%\n\\begin{figure}[t]\n\\centering\n% dom t\n\\begin{subfigure}[b]{0.3\\textwidth}\n\\centering\n\\begin{tikzpicture}\n\\draw \\all{} rectangle \\aur{};\n\\draw \\bll{} rectangle \\bur{};\n\\draw \\innerll{} rectangle \\innerur{};\n\\filldraw [gray, fill opacity=0.5, draw opacity=0.0] \\all{} -- \\alr{} -- \\aur{} -- \\aul{};\n\\end{tikzpicture}\n\\caption{$\\dom{t}$}\n\\end{subfigure}%\n% dom t'\n\\begin{subfigure}[b]{0.3\\textwidth}\n\\centering\n\\begin{tikzpicture}\n\\draw \\all{} rectangle \\aur{};\n\\draw \\bll{} rectangle \\bur{};\n\\draw \\innerll{} rectangle \\innerur{};\n\\filldraw [gray, fill opacity=0.5, draw opacity=0.0] \\bll{} -- \\blr{} -- \\bur{} -- \\bul{};\n\\end{tikzpicture}\n\\caption{$\\dom{t'}$}\n\\end{subfigure}%\n% dom u = dom v\n\\begin{subfigure}[b]{0.3\\textwidth}\n\\centering\n\\begin{tikzpicture}\n\\draw \\all{} rectangle \\aur{};\n\\draw \\bll{} rectangle \\bur{};\n\\draw \\innerll{} rectangle \\innerur{};\n\\filldraw [gray, fill opacity=0.5, draw opacity=0.0] \\innerll{} -- \\innerlr{} -- \\innerur{} -- \\innerul{};\n\\end{tikzpicture}\n\\caption{$\\dom{u} = \\dom{v}$}\n\\end{subfigure}\\\\\n% dom s\n\\begin{subfigure}[b]{0.3\\textwidth}\n\\centering\n\\begin{tikzpicture}\n\\draw \\all{} rectangle \\aur{};\n\\draw \\bll{} rectangle \\bur{};\n\\draw \\innerll{} rectangle \\innerur{};\n\\filldraw [gray, fill opacity=0.5, draw opacity=0.0] \\outerll{} -- \\outerlr{} -- \\outerur{} -- \\bur{} -- \\blr{} -- \\bll{} -- \\outerll{};\n\\end{tikzpicture}\n\\caption{$\\dom{s}$}\n\\end{subfigure}%\n% dom s'\n\\begin{subfigure}[b]{0.3\\textwidth}\n\\centering\n\\begin{tikzpicture}\n\\draw \\all{} rectangle \\aur{};\n\\draw \\bll{} rectangle \\bur{};\n\\draw \\innerll{} rectangle \\innerur{};\n\\filldraw [gray, fill opacity=0.5, draw opacity=0.0] \\outerll{} -- \\outerul{} -- \\outerur{} -- \\aur{} -- \\aul{} -- \\all{} -- \\outerll{};\n\\end{tikzpicture}\n\\caption{$\\dom{s'}$}\n\\end{subfigure}%\n% dom r\n\\begin{subfigure}[b]{0.3\\textwidth}\n\\centering\n\\begin{tikzpicture}\n\\draw \\all{} rectangle \\aur{};\n\\draw \\bll{} rectangle \\bur{};\n\\draw \\innerll{} rectangle \\innerur{};\n\\filldraw [gray, fill opacity=0.5, draw opacity=0.0] \\outerll{} -- \\outerlr{} -- \\outerur{} -- \\outerul{} \\innerll{} -- \\innerul{} -- \\innerur{} -- \\innerlr{};\n\\end{tikzpicture}\n\\caption{$\\dom{r}$}\n\\end{subfigure}\n\\caption{Schematic showing addresses of assignments involved in \\code{fix\\_update}}\n\\end{figure}\n\n\n%%%%%%%%%%%%%%%%%\n%% free update %%\n%%%%%%%%%%%%%%%%%\n\n\\paragraph{Free Update Method (\\code{free\\_update})}\nGiven $x, x' \\in X$, and $t \\in T_x$, $Q^{\\free}_{t,x,x'}(t')$ is a distribution on assignments such that $Q^{\\free}_{t,x,x'}(t') > 0$ implies $t' \\in T_{x'}$, and such that $Q^{\\free}_{t,x,x'}(t') > 0$ implies $Q^{\\free}_{t',x',x}(t) > 0$.\nSample $t' \\sim Q^{\\free}_{t,x,x'}(\\cdot)$ and return $t'$, and a weight:\n\\[\n    \\frac{p(t'; x')}{p(t; x)} \\frac{Q^{\\free}_{t',x',x}(t)}{Q^{\\free}_{t,x,x'}(t')}\n\\]\nAlso return $y' = f(x', t')$.\nNote that `regenerate', where we provide a set of addresses that should be resimulated, is an example of this.\n\n\\paragraph{Backpropagate to Parameters Method (\\code{backprop\\_params})}\nGiven $x \\in X$ and $t \\in T_x$, and $\\nabla_y J$, return $\\nabla_x (J + \\log p(t; x))$ and $\\nabla_{\\theta} (J + \\log p(t; x))$.\n\n% \\paragraph{Backpropagate to Trace (\\code{backprop\\_assignment})}\n% TODO doesn't make sense if values come from a discrete set\n\nEach probabilistic module may also possess an indexed collection of families of distributions for use in \\code{generate} and \\code{update}.\nProbabilistic modules may also have update procedures that make arbitrary changes to their assignment, and return the appropriate weight.\nThese two features are not yet implemented.\n\n\\section{Auxiliary Randomness}\nIn this section, we generalize the above interface to support \\emph{auxiliary random choices}, which permit encapsulation of internal randomness within a probabilistic module.\nUnlike traced assignments ($t$), auxiliary assignments (denoted $\\auxassign$) are not exposed as user-readable.\nWe replace the generative distribution $P_x(t)$ with a distribution $P_x(\\auxassign, t)$ where $\\auxassign$ is an assignment with $\\dom{\\auxassign} \\cap \\dom{t} = \\varnothing$ for all $\\auxassign, t$.\nThe marginal distribution of $P_x(\\auxassign, t)$ is $P_x(t) := \\sum_{\\auxassign} P_x(\\auxassign, t)$.\nWe define $T_x$ as $\\{t : P_x(t) > 0\\}$.\nWe replace the function $f$ with $f : \\{(x, \\auxassign, t) : P_x(\\auxassign, t) > 0 \\} \\to Y$ (i.e. the output value can depend on the auxiliary randomness).\nThe module tuple is extended to include a family of distributions on the untraced assignments, denoted $Q^{\\aux}_{x,t}(\\auxassign)$, where $Q^{\\aux}_{x,t}(\\auxassign) > 0$ if and only if $P_x(\\auxassign, t) > 0$.\nEach of the methods above is adjusted as follows:\n\n\\paragraph{Generate Method (\\code{generate})}\nIn addition to sampling $s \\sim Q^{\\gen}_{x,u}(\\cdot)$, we also sample $\\auxassign \\sim Q^{\\aux}_{x,t}(\\cdot)$.\nWe return the weight $P_x(\\auxassign, t) / (Q^{\\gen}_{x,u}(s) Q^{\\aux}_{x,t}(\\auxassign))$\nWe return $t$ and $\\auxassign$.\n\n\\paragraph{Propose Method (\\code{propose})}\nInstead of sampling $t \\sim P_x(\\cdot)$, we sample jointly $\\auxassign, t \\sim P_x(\\cdot, \\cdot)$.\nWe return $t$ and $\\auxassign$.\nWe return the weight $P_x(\\auxassign, t) / (Q^{\\gen}_{x,u}(s) Q^{\\aux}_{x,t}(\\auxassign))$\n\n\\paragraph{Force Update Method (\\code{force\\_update})}\nIn addition to $x, x', t, u$, we accept $\\auxassign$ such that $P_x(\\auxassign, t) > 0$.\nAfter computing $t'$, we sample $\\auxassign' \\sim Q^{\\aux}_{x',t'}(\\cdot)$.\nWe return the weight:\n\\[\n\\left( \\frac{P_{x'}(\\auxassign', t')}{Q^{\\aux}_{x',t'}(\\auxassign')} \\right)\n\\bigg/\n\\left( \\frac{P_x(\\auxassign, t)}{Q^{\\aux}_{x,t}(\\auxassign)} \\right)\n\\]\n\n\\paragraph{Fix Update Method (\\code{fix\\_update})}\nIn addition to $x, x', t, u$, we accept $\\auxassign$ such that $P_x(\\auxassign, t) > 0$.\nAfter sampling $s$ and computing $t'$, we sample $\\auxassign' \\sim Q^{\\aux}_{x',t'}(\\cdot)$.\nWe return $(t, \\auxassign)$ in addition to the weight:\n\\[\n\\left( \\frac{P_{x'}(\\auxassign', t')}{Q^{\\fix}_{x,x',t,u}(s) Q^{\\aux}_{x',t'}(\\auxassign')} \\right)\n\\bigg/\n\\left( \\frac{P_x(\\auxassign, t)}{Q^{\\fix}_{x',x,t',v}(s') Q^{\\aux}_{x,t}(\\auxassign)} \\right)\n\\]\n\n\\paragraph{Free Update Method (\\code{free\\_update})}\nIn addition to $x, x', t$, we accept $\\auxassign$ such that $P_x(\\auxassign, t) > 0$.\nAfter sampling $t'$, we sample $\\auxassign' \\sim Q^{\\aux}_{x',t'}(\\cdot)$.\nWe return $(t, \\auxassign)$ in addition to the weight:\n\\[\n\\left( \\frac{P_{x'}(\\auxassign', t')}{Q^{\\free}_{x,x',t}(t') Q^{\\aux}_{x',t'}(\\auxassign')} \\right)\n\\bigg/\n\\left( \\frac{P_x(\\auxassign, t)}{Q^{\\free}_{x',x,t'}(t') Q^{\\aux}_{x,t}(\\auxassign)} \\right)\n\\]\n\n\\subsection{Untraced Auxiliary Assignments}\nBecause auxiliary assignments are not exposed as user-readable, modules may choose to make use of the following optimization.\nNote that auxiliary assignments are only ever referenced as part of ratios of the form $P_x(t) / Q^{\\aux}_{x,t}(\\auxassign)$.\nTherefore, modules may compactly summarize the sufficient information about the auxiliary randomness in the form of this ratio.\n\n\\section{Generative Functions}\nGenerative functions are one type of probabilistic module, in which the generative function $P_x$ is defined as a Julia function extended with probabilistic semantics.\nThis section informally describes how generative functions implement each of the components of the probabilitsic module interface.\n\n\\paragraph{Input type}\nThe input type $X$ is the Julia type of the arguments to the function.\n\n\\paragraph{Generative Distribution}\nThe assignments $t$ generated by a generative function have a hierarchical structure.\nEach \\emph{address key} used with the \\code{@addr} keyword is either a \\emph{primitive address}, which is the address of a single random choice sampled from a probability distribution with known probability mass function, or a \\emph{namespace}, under which the assignment of a called probabilistic module is generated.\nThe generative distribution $P_x(t)$ is defined by the product of probabilities of primitive addresses taking given values, with the probability of assignments to namespaces determined by the called probabilistic modules.\nAuxiliary randomness $\\auxassign$ consists of random choices that are not annotated with \\code{@addr}.\nFor $Q^{\\aux}_{x,t}$ we use forward evaluation, so that $P_x(t) / Q^{\\aux}_{x,t}(\\auxassign)$ is typically computed simply as a product of probabilities that skips over factors for the auxiliary addresses, due to cancellation of factors.\n\n\\paragraph{Output function}\nThe output function maps a terminating state of the function to the output value $y$, where the state of the function is a (deterministic) function of $x$, $\\auxassign$, and $t$.\n\n\\paragraph{Generate Method (\\code{generate})}\nFor $Q^{\\gen}_{x,u}$ we use forward evaluation for primitive addresses, so that the weight is computed as a product of probabilities in $\\dom{u}$ only, due to cancellation of factors for addresses in $\\dom{s}$.\nFor addresses in namespaces we recursively invoke \\code{generate}.\n\n\\paragraph{Propose Method (\\code{propose})}\nSee `Generative Method'.\n\n\\paragraph{Force Update Method (\\code{force\\_update})}\nFor addresses in namespaces we recursively invoke \\code{force\\_update}.\n\n\\paragraph{Fix Update Method (\\code{fix\\_update})}\nFor $Q^{\\fix}_{x,t}$ we use forward simulation of primitive addresses, and we for addresses in namespaces we recursively invoke \\code{fix\\_update}.\n\n\\paragraph{Free Update Method (\\code{free\\_update})}\n% TODO accepts a set of addresses to resimulate... recursiely calls?\n\n\\subsection{Untraced Auxiliary Assignments}\nBecause auxiliary assignments are not exposed as user-readable, modules may choose to make use of the following optimization.\nNote that auxiliary assignments are only ever referenced as part of ratios of the form $P_x(t) / Q^{\\aux}_{x,t}(\\auxassign)$.\nTherefore, modules may compactly summarize the sufficient information about the auxiliary randomness in the form of this ratio.\n\n\n\n\n\\clearpage\n\\bibliographystyle{abbrv}\n\\bibliography{references}\n\n\\end{document}\n", "meta": {"hexsha": "e1987f7c42684b791b79fb8a4edba5782dc65167", "size": 22456, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/semantics.tex", "max_stars_repo_name": "BoltzmannBrain/Gen", "max_stars_repo_head_hexsha": "a9ab5b41cd5974aa40c38ffdcb9ecabd224f42b9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/semantics.tex", "max_issues_repo_name": "BoltzmannBrain/Gen", "max_issues_repo_head_hexsha": "a9ab5b41cd5974aa40c38ffdcb9ecabd224f42b9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/semantics.tex", "max_forks_repo_name": "BoltzmannBrain/Gen", "max_forks_repo_head_hexsha": "a9ab5b41cd5974aa40c38ffdcb9ecabd224f42b9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.3965517241, "max_line_length": 362, "alphanum_fraction": 0.6682846455, "num_tokens": 7631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3262931396429256}}
{"text": "\\documentclass[12pt]{article}\n\n\\usepackage[vmargin=1in,hmargin=1in]{geometry}\n\\usepackage{amsmath}\n\\usepackage[parfill]{parskip}\n\\usepackage{hyperref}\n\\usepackage{natbib}\n\\usepackage{bm}\n\\usepackage{amsfonts}\n\\usepackage{graphicx}\n\\usepackage{abstract}\n\\usepackage{lineno}\n\\usepackage{setspace}\n\n\\hypersetup{pdfstartview={Fit},hidelinks}\n\n\n\\usepackage{caption}\n\\captionsetup[figure]{labelformat=empty}% redefines the caption setup of the figures environment in the beamer class.\n\n\n\\title{Ecology Appendix S2 \\\\ Simulation study accompanying the paper: \\\\ \\it Modeling abundance, distribution, movement, and space\n  use with camera and telemetry data}\n\\author{Richard B. Chandler$^1$\\footnote{Corresponding author: rchandler@warnell.uga.edu}, Daniel A. Crawford$^2$, Elina P. Garrison$^3$, \\\\\n  Karl V. Miller$^1$, Michael J. Cherry$^2$}\n\n\\begin{document}\n\n\n\n\\maketitle\n\n\\vspace{12pt}\n\n\\begin{description}%[labelindent=1pt]%[leftmargin=1cm]%,labelwidth=\\widthof{\\bfseries Example:}]\n%  \\large\n\\item[$^1$] Warnell School of Forestry and Natural Resources, University of Georgia %\\\\\n\\item[$^2$] Caesar Kleberg Wildlife Research Institute at Texas A\\&M University-Kingsville %\\\\\n\\item[$^3$] Florida Fish and Wildlife Conservation Commission %\\\\\n\\end{description}\n\n\\clearpage\n\n\\section*{Introduction and Methods}\n\nWe conducted a small simulation study to evaluate the performance of the\nspatial capture-recapture model with an explicit movement process\ndescribed in the manuscript.\nThe design and parameter values were chosen to resemble the estimates\nfrom the deer example in the manuscript. A uniform capture process was\nsimulated to resemble aerial capture and transmitter\ndeployment. The camera design in the simulation study was the same as\nin the deer example, with 60 cameras spaced by 200--500 m. We simulated\n90 occasions and used a fix rate of 1 location every 3\noccasions. Parameters (defined in the manuscript) were $N=100$,\n$p^{\\rm cap}=0.25$, $\\lambda_0=2$, $\\sigma^{{\\rm det}}=50$,\n$\\sigma^{\\rm move}=600$. We \nconsidered 5 scenarios in which the autocorrelation parameter ($\\rho$)\nof the Ornstein-Uhlenbeck movement model was assigned values: 0.55,\n0.65, 0.75, 0.85, and 0.95. \n\nFor each scenario, we simulated 100 datasets and fit both\nthe data generating model (SCR-move) and a mis-specified SCR model\n(SCR0) with no movement process. Inference was made using 10,000 MCMC\nsamples from the joint posterior following a 2,000 iteration\nburn-in. Code to reproduce the simulation study can be found at\n\\url{10.5281/zenodo.5167653}.\n\n% \\begin{table}[h!]\n%   \\centering\n  \n%   \\caption{Scenarios considered in the simulation study}\n%   \\label{tab:sims}\n% \\end{table}\n\n\n\\section*{Results and Discussion}\n\nThe number of individuals captured and outfitted with telemetry\ndevices ranged from 13--35 in the simulated datasets. As with the deer\nexample, only a small fraction (ranging from 0--10) were detected by\ncameras. \n\nBias was reduced in all 5 cases when switching from the SCR0 model to\n%the SCR-move model (Fig.~\\ref{fig:bias}). Improvement in bias ranged\nthe SCR-move model (Figure S1). Improvement in bias ranged\nfrom 2--6\\%. Bias of the SCR+move model was $\\le2\\%$ for the first two\nscenarios. For the other three scenarios (with \n$\\rho=$0.75, 0.85, and 0.95), bias of the SCR+move model was\n5--8\\%, although some of this was likely attributable to Monte Carlo\nerror resulting from the small number of simulated datasets.\nCoverage of 95\\% credible intervals was close to 0.95 for\nthe SCR+move model in all scenarios and was better than the SCR0 model\n%(Fig.~\\ref{fig:bias}). Variance of the estimator was greater for the\n(Figure S1). Variance of the estimator was greater for the\nSCR+move model than for the mis-specified SCR0 model.\n\n\n\\clearpage\n\n\\begin{figure}[h!]\n  \\centering\n  \\includegraphics[width=0.5\\textwidth, trim=0mm 15mm 0mm 15mm, clip]{../R/sims/bias-N.pdf} \\\\\n  \\includegraphics[width=0.5\\textwidth, trim=0mm 15mm 0mm 15mm, clip]{../R/sims/cover-N.pdf} \\\\\n  \\includegraphics[width=0.5\\textwidth, trim=0mm 0mm 0mm 15mm, clip]{../R/sims/var-N.pdf}\n  \\caption{Figure S1. Bias, 95\\% CI coverage, and variance of the posterior mode\n    as a point estimator of population size ($N$) under five values of\n    the parameter $\\rho$ controlling autocorrelation in movement. The\n    data generating value of abundance was $N=100$. } \n  \\label{fig:bias}\n\\end{figure}\n\n\n\n\\end{document}\n\n\n", "meta": {"hexsha": "87b87219864ac78d69052f8992fded1aba207b3e", "size": 4402, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "supp/Appendix-S2.tex", "max_stars_repo_name": "rbchan/scr-move", "max_stars_repo_head_hexsha": "30d3ed9f8c3f554b6867f6dc923a6fa143de4551", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-08-08T20:07:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T06:45:50.000Z", "max_issues_repo_path": "supp/Appendix-S2.tex", "max_issues_repo_name": "rbchan/scr-move", "max_issues_repo_head_hexsha": "30d3ed9f8c3f554b6867f6dc923a6fa143de4551", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "supp/Appendix-S2.tex", "max_forks_repo_name": "rbchan/scr-move", "max_forks_repo_head_hexsha": "30d3ed9f8c3f554b6867f6dc923a6fa143de4551", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3050847458, "max_line_length": 140, "alphanum_fraction": 0.7560199909, "num_tokens": 1254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.3262587452107406}}
{"text": "\\documentclass[]{article}\n\n\\usepackage{paralist} % Used for the compactitem environment which makes bullet points with less space between them\n\n\\usepackage{amsmath}\n\\usepackage{graphicx}\n\\graphicspath{ {pics/} }\n\\usepackage{algorithm}% http://ctan.org/pkg/algorithm\n\\usepackage{algpseudocode}% http://ctan.org/pkg/algorithmicx\n\\usepackage{multirow}\n\\usepackage{wrapfig}\n\n\n\\usepackage[a4paper, total={6in, 10in}]{geometry}\n\n\n\n\\usepackage{tabularx}\n\\newcolumntype{Y}{>{\\centering\\arraybackslash}X}\n\n% ADD THE FOLLOWING COUPLE LINES INTO YOUR PREAMBLE\n\\let\\OLDthebibliography\\thebibliography\n\\renewcommand\\thebibliography[1]{\n    \\OLDthebibliography{#1}\n    \\setlength{\\parskip}{0pt}\n\\setlength{\\itemsep}{0pt plus 0.3ex}\n}\n\n\\usepackage[affil-it]{authblk} \n\\usepackage{etoolbox}\n\\usepackage{lmodern}\n\n\n\\makeatletter\n\\patchcmd{\\@maketitle}{\\LARGE \\@title}{\\fontsize{16}{8}\\selectfont\\@title}{}{}\n\\makeatother\n\n\\renewcommand\\Authfont{\\fontsize{10}{8}\\selectfont}\n\\renewcommand\\Affilfont{\\fontsize{7}{8}\\itshape}\n\n\n\n%----------------------------------------------------------------------------------------\n%\tTITLE SECTION\n%----------------------------------------------------------------------------------------\n\n\\title{\\vspace{-2.0cm}Towards Bayesian lifelong learning in mapping}\n\n\n\\author{Panagiotis Chatzichristodoulou, Rico  M\\\"{o}ockel, Kurt Driessens, Anne Van Rossum}\n\\affil{University of Maastricht, DoBots B.V.}\n\n\n\\date{}\n\n%----------------------------------------------------------------------------------------\n\n\\begin{document}\n\\maketitle % Insert title\n\n%----------------------------------------------------------------------------------------\n%\tARTICLE CONTENTS\n%----------------------------------------------------------------------------------------\n\n\\section{Introduction}\n\nSimultaneous localization and mapping is one of the fundamental problems of autonomous systems\\cite{probRobs}. In order for robots to be truly autonomous they have to be able to enter an environment and map its structure. To that direction, a lot of effort has been put in algorithms that are able to map static environments; with solutions like EKF-slam\\cite{ekf} and FastSlam\\cite{slam} we can now efficiently map such environments. \nThe logical extension to methods that can map static environments is methods that remove this restriction. The idea of lifelong robot learning was introduced as a general concept to the literature by Sebastian Thrun\\cite{liflonglearning}. Konolige et al.\\cite{lifelongmaps} specifically focus on lifelong learning in mapping. In the PhD thesis of Walcott\\cite{aishalong} long term mapping methods are decomposed to 4 basic subproblems: the problem of being able to continuously incorporate new information, tracking the growing DPG, detecting changes and update the map online, being able to handle changes to the map as changes occur with the passage of time.\n\nThe first two problems can be though of as compression problems as the map increases over time whereas the latter ones can be though of as dynamic environment problems. In this project the focus will be directed towards slam methods that use RGBD devices like Microsoft's Kinect to perform slam. The goal of this thesis is to introduce a novel approach to tackle the compression problem of long term mapping methods that use the Kinect devices while using Bayesian non parametric methods as the base of the solution.\n\nDirichlet processes and Dirichlet process mixture models\\cite{nonParam} are the cornerstone of Bayesian non parametric statistics. The strength of those models lies in the fact that they allow the model's mixture components to grow as much as needed so as to best fit the data. The main motivation of this thesis is to integrate such methods to mapping algorithms as a means of creating compressed representations of the environment that also retain enough expressivenes so that they can be used as reference points when navigating through the environment. That would tackle the compression subproblem of long term mapping and would be a solid first step towards a general Bayesian solution to the long term mapping problem.\n\nThe rest of the paper is structured as follows. In Section \\ref{sec:literature} relevant literature review will be reviewed, Section~\\ref{sec:theory} will introduce the basic background theories of the model, Section~\\ref{sec:model} will define the method presented in this paper, Section ~\\ref{sec:results} will show experimental results of the method. Finally, conclusion and future directions are presented in Section ~\\ref{sec:discussion}.\n%------------------------------------------------\n\n\\section{Literature review}\n\\label{sec:literature}\nLiterature review will be focused on 4 related sub fields: Object based slam or semantic slam, point cloud object segmentation, non-parametric clustering methods ad the correspondence problem in slam.\n\n\\subsection{Object based slam}\nSalas-Moreno et al.\\cite{slam++} define a method of performing object based slam for specific classes of objects. The objects are identified by camera that is on top of the robot. By having a model of pre-trained objects, slam can be performed on environments where the robot knows what objects to expect. \nCastle et al. use object recognition to perform object based slam with the use of a hand-held cameras. Selvatici et al.\\cite{objslam} use a similar approach while exploiting structural information such as object height and position within the room. That way a couch that is a large object situated in floor level is easier to be recognized.\nChoudhary et al.\\cite{objectpointslam} use point clouds and an object database to match objects currently seen with known objects within their database. They use omnimaper\\cite{omnimaper} as their mapping method and as a representation a combination of the downsampled  voxel grids with additional normal and curvature information.  Finally, all their operations are done in the non-planar components of the point cloud.\nSeongyong Koo et al.\\cite{objectDisc} introduce a method of unsupervised object individuation from RGB-D image sequences. They cluster their initial cloud into candidate objects using Euclidean clustering and proceed to extract features like the Euclidean distance(L2) and the Kullback-Leibler distance between point cloud objects. They use IMFT to solve their tracking problem.\n\n\\subsection{Point Cloud Object clustering}\n\nTrevor et al.\\cite{pointSeg} take positional information, Euclidean distances and the normal of points to as input to their functions and output segments that are part of the same object. PCL library\\cite{pcl} introduces methods like Euclidean clustering and conditional Euclidean clustering that use a number of heuristics that take normal as well as curvature information to extract segments in the point cloud that represent objects. Furthermore, a there is a lot of research on segmentation of point clouds in scenes, the emphasis is usually on extracting geometric primitives~\\cite{planarSeg},\\cite{planarSeg2} using cues like normals and curvature. Rabbani et al.\\cite{segOverview} introduce a new method of object segmentation using KNN as their base algorithm. They also present a very informative literature review along with the strengths and weaknesses of existing methods. Finally Triebel et al.\\cite{smartSeg} introduce a general clustering framework that does not rely on plane segmentation. Instead of segmenting the plane by using classical approaches like RANSAC or MLASAC they introduce a framework where they make no assumptions regarding plane data. \n\n\\subsection{Non Parametric Bayesian methods}\n\nDirichlet processes and Dirichlet process mixture models are the cornerstone of Bayesian non-parametric statistics. Radford M. Neal\\cite{bayes:neal} with his paper regarding MCMC methods for Dirichlet process mixture models made the definitive step towards Dirichlet process mixture models(DPMM's) receiving a lot of attention. Variational inference for DPMM's, introduced by Jordan et al.\\cite{bayes:jordan} introduces deterministic tools to perform inference and approximate the posterior distribution and marginals of a dataset. Both methods have strengths and weaknesses and many tools have been established by using the two approaches as their base. Particle filter approaches of inference  have also been established with  Doucet et al.\\cite{bayes:smc} introduce Sequential Monte Carlo as a fast way to approximate inference. For the purpose of this paper an SMC sampler will be defined in detail in the Model definition section.\n\n\n\\subsection{Correspondence}\n\nUnder the semantic slam context, correspondence refers to the problem of identifying objects as ones that have been encountered before during the mapping process. Towards that direction Cree et al.\\cite{corresp:first} create a histogram of line segments of each landmark and compute their root mean square error. They then proceed to calculate their RGB signature to calculate the distance between different landmarks. Low et al.\\cite{corres:sec} match Scale Invariant Feature Transform (SIFT) features, an approach which transforms image data into scale-invariant coordinates relative to local features. Lamon et al.\\cite{corres:three} store a database of fingerprints which indicate the location in the robot's environment. The features are ordered and stored at a database at as they appear in the robot's immediate surroundings. A new fingerprint is computed for each new view and matched against existing ones. Finally, in Seghal et al.\\cite{corres:four} an extension of SIFT descriptors to 3D data and point clouds is given.\n\n\\section{Theory background}\n\\label{sec:theory}\n\nThe basic theory background regarding the sampler will be presented in this section. Generalized Polya Urn is an extension on basic Urn\\cite{caron} models for Dirichlet processes and serves as the base of the sampler presented in the theory section.\n\n\\subsection{Generalized Polya's Urn}\n\nDirichlet process priors have been widely used in the literature as non parametric Bayesian tools to estimate the number of clusters in the data\\cite{antoniak}. Dependent dirichlet processes extend those tools by allowing the clusters in the data to vary with some variance over time by introducing dependencies on the data which can be temporal, positional etc. The DDPs are a natural extension of the DP's in domains where data cannot be considered exchangeable. The main motivation behind using such tools is that they can naturally be extended to dynamic environments to tackle the dynamic part of the long term slam problem.\n\nA DDP also known as Generalized Polya Urn(GPU)\\cite{caron} and has the property of randomly deleting partitions of clusters on every iteration. That way, it can cope with the variance of the data. The current notation defines the $n_{th}$ datapoint at time $t$,$x_{t,n}$ having an assignment $c_{t,n}$ at cluster $k \\in \\{1,2,..., K\\} $. The size of cluster $k$ at time $t$ is defined as $s_t^k$. The GPU of this model at time $t$ can now be defined as:\n\n\\begin{algorithm}\n    \\caption{GPU}\\label{GPU}\n    \\begin{algorithmic}[1]\n        \\Procedure{GPU}{$pointCloud, t$}\n\n        \\For{\\texttt{$k = 1,...K_{t-1,N_{t-1}}$}}\n        \\State Draw $\\Delta s_{t-1}^k \\sim Binom(s_{t-1,N_{t-1}}^k, \\rho) $ \n        \\State Set $s_{t,0}^{k} = s_{t-1,N_{t-1}}^{k} -\\Delta s_{t-1}^k$\n        \\EndFor\n        \\For{\\texttt{$n = 1,...N_t$}}\n        \\State Draw $c_{t,n} \\sim Cat( \\frac{ s_{t,n-1}^{1} }{\\alpha + \\sum_k s_{t,n-1}^{k} }, \\frac{ s_{t,n-1}^{K_{t,n-1}} }{\\alpha + \\sum_k s_{t,n-1}^{k} } , \\frac{ \\alpha}{\\alpha + \\sum_k s_{t,n-1}^{k} }) $\n        \\State If $c_{t,n} \\leq K_{t,n-1}\\ set:\\ s_{t,n}^{c_t,n} = s_{t,n-1}^{c_t,n} + 1 , K_{t,n} = K_{t,n-1}$\n        \\State If $c_{t,n} > K_{t,n-1}\\ set:\\ s_{t,n}^{c_t,n} = 1 , K_{t,n} = K_{t,n-1} + 1$\n        \\EndFor\n        \\EndProcedure\n    \\end{algorithmic}\n\\end{algorithm}\n\nWhere Cat is a categorical distribution, Bin is the binomial distribution, $\\alpha$ is the DP concentration parameter and $\\rho$ is the deletion parameter of the GPU. This Generative Polya Urn distribution also has the shorthand notation GPU($\\alpha,\\rho$)\n\nThis process can be though of in the terms of a general chinese restaurant process\\cite{antoniak} as shown in Fig.~\\ref{generalPolya}. At time $t$, suppose there are $n$ customers seating at several tables in the restaurant. Each customer has to decide if he/she will remain at table with probability $p$ or leave the restaurant with probability $1-p$. Once all the customers make their decisions they leave the restaurant or remain seated (b). Each table occupied is moved according to the number of customers still seating in that table (c). A new customer then enters the table and either chooses to sit on one of the existing tables (e) or choose a new with probability proportional to the strength parameter $\\alpha$ of the model(f).\n\n\n\\begin{wrapfigure}{l}{0.4\\textwidth}\n    \\includegraphics[width=0.9\\linewidth]{generalPolya}\n    \\caption{General Polya}\n    \\label{generalPolya}\n\\end{wrapfigure}\n\n\n\\section{Model definition}\n\\label{sec:model}\n\n\\subsection{General pipeline}\n\nThe general flow of operations that occur in the EKF module is presented in Fig.~\\ref{pipeline}. The slam module requests new observation readings given the cloud currently read by the sensors and the position of the robot. The pipeline takes that cloud, extracts clusters and returns the landmarks currently being observed while taking into account landmarks that where observed in the past. Landmarks and clusters are identical concepts representing a different layer in the pipeline. More specifically, clusters are output from the sampler from the sampler and are given as an input of landmarks to the EKF module.\n\n\\begin{wrapfigure}{l}{0.4\\textwidth}\n    \\centering\n    \\includegraphics[width=.4\\textwidth]{workflowSpec}\n    \\caption{Pipeline flow}\n    \\label{pipeline}\n\\end{wrapfigure}\n\n\n\\begin{algorithm}\n    \\caption{Landmark Layer}\\label{euclid}\n    \\begin{algorithmic}[1]\n        \\Procedure{getLandmarkIds}{$pointCloud, timepoint, existingLandmarks$}\n        \\State $initialize(landMarkIds)$\n        \\State $pointCloudReduced \\gets extractMetaFeatures(pointCloud)$ \n        \\State $features \\gets extractMetaFeatures(pointCloudReduced)$\n        \\State $landmarks \\gets cluster(features)$  \n        \\For{\\texttt{$landmarks$ as $landmark$}}\n        \\State $ (similarity, landId) \\gets calcBestSim(landmark, existingLandmarks) $\n        \\If{$similarity >threshold$}\n        \\State $ addLandmarks(landMarkIds, landId)$\n        \\Else \n        \\State $ newLandID \\gets addLandmarkDB(landmarkDB, landmark)$\n        \\State $addLandmarks(newLandID)$\n        \\EndIf\n        \\EndFor\n        \\State \\textbf{return} $ landMarkIds$\\Comment{Return landmarks}\n        \\EndProcedure\n    \\end{algorithmic}\n\\end{algorithm}\n\n\n\\textbf{Method input:} The method takes as input a point cloud as it is currently being read by the kinect sensor.\n\n\\textbf{Lines 3-4:} The preprocessing the cloud is done in these steps. Feature extraction is done through the pcl\\cite{pcl} library. A voxel grid is used to reduce the dataset size. A leaf size of approximately 3cm produces a good trade-off between precision and speed. The object representation used approach is similar to\\cite{objectpointslam}. Instead of using the CSHOT descriptor, fpfh\\cite{fpfh} histogram is used instead. A fast point feature histogram(fpfh) represents an angular signature between a point and its neighbors. The color signature of the cloud is being encoded with an approach similar to ~\\cite{smcddp}. The color spectrum is discretized and what is extracted is the count of different color signatures between a point and its k nearest neighbors. Finally the position of every point is also given as input to the algorithm. The pipeline is presented in figure Fig.~\\ref{pipeline}. The preprocessing outputs a vector of $\\textbf{x} =(x_s, x_c, x_a)$ where $s$ represents the position information of the point, $c$ the color information of the point's neighbors and $a$ the angle information of the point's neighbors.\n\n\\textbf{Lines 5:} The clustering takes place in this line. The input of the method is the feature vector for every data point which is calculated in the previous steps. The clustering is done using the SMC sampler presented in the model definition section. \n\n\\textbf{Lines 6-12:} The correspondence of previously seen landmarks to current observations is computed in lines 6-12. The calcBestSim function returns the landamrk with the highest similarity match with the landmarks already stored in the database.\n\n\\textbf{Lines 15:} The algorithm returns the list of the landmarks the robot sees in this current time.\n\nNow that the basic theories are defined, the pipeline's components and its operating mechanisms can be presented in more detail.\n\n\\subsection{The sampler}\n\n\\subsubsection{The data distribution}\n\\label{data:dist}\n\nEach point $x$ in the cloud is represented as a tuple $x =(x^s, x^a, x^c) $ where superscript $s$ represents spatial information, $a$ angle information, and $c$ color information. The method those features are extracted is explained in lines 3 and 4 in the general pipeline section. For the purpose of this project each point in the cloud is represented by vector of length 33 with the first three elements representing the space information, elements 4-6 angle information, and the rest color information.\n\nThe object model is a mixture of distributions over the data with each object being modeled as D($\\theta_t^k$) where $\\theta$ represents the parameters of object $k$ at time $t$. More specifically, each set \\textbf{x} with $n$ datapoints at time $t$ is distributed as:\n$$ x_{t,n} \\sim D(\\theta_t^k) = Normal(x_{t,n}^s| \\mu_t, \\Sigma_t) Mult(x_{t,n}^c | \\delta_t) Exp(x_{t,n}^a | \\lambda_t) $$\n\n\\begin{wrapfigure}{l}{0.25\\textwidth}\n    \\centering\n    \\includegraphics[width=.25\\textwidth]{Kullback-Leibler}\n    \\caption{Exponential trend of distances}\n    \\label{pcl:kl}\n\\end{wrapfigure}\n\nWhere Normal is a three dimensional Gaussian distribution with mean $\\mu$ and covariance $\\Sigma$ representing the positional distribution of the data; Mult is a Categorical multinomial distribution with parameter vector $\\delta$ representing the weights of the color distribution and Exp is an exponential with shape parameter $\\lambda$ representing the angle distribution of the data within the cluster. The exponential distribution was chosen to model angular information after empiric evaluation showed that it would be a good fit for the angle signature distribution of the data as shown in Fig.~\\ref{pcl:kl}.\n\n\nNow that the distribution of the objects is defined, the progression of the sufficient statistics at time $t$ given $t-1$ given by:\n\n$\\theta_t^k | \\theta_{t-1}^k \\sim\n\\begin{cases} T (\\theta_{t-1}^k) &\\mbox{if } k \\leq K_{t-1} \\\\\nG_0 & \\mbox{if } k > K_{t-1}. \\end{cases}$\n\nWhere $T$ represents the transition kernel of the data given the previous state in the model. The case $ k > K_{t-1} $ represents the creation of a new cluster and $G_0$ is the base distribution of the DDP. In our case, the conjugate priors of the distributions of the data were chosen to model the base distribution. Therefore, $G_0$ is defined as:\n\n$$ G_0(\\theta_t^k)  = NiW( \\mu_t^k, \\Sigma_t^k | \\kappa_0, \\mu_0, \\nu_0, \\Lambda_0 ) Dir(\\delta_t^k | q_0) Gam( \\lambda_t^k | \\alpha_0, \\beta_0) $$\n\nWhere NiW is a Normal inverse Wishart distribution, Dir denotes a Dirichlet distribution, and Gam the Gamma distribution. $ \\kappa_0, \\mu_0, \\nu_0, \\Lambda_0, q_0,\\alpha_0$ and $\\beta_0$ are predefined parameters of the model. The generative process for the Dependent Dirichlet mixture model can be written for each timestep $t$ as:\n\n\n\\begin{compactitem}\n\\item Draw  $c_t$ $\\sim$ $GPU(\\alpha, \\rho) $\n\\item $\\forall$  k draw: $ \\theta_t^k | \\theta_{t-1}^k \\sim\n    \\begin{cases} T (\\theta_{t-1}^k) &\\mbox{if } k \\leq K_{t-1} \\\\\nG_0 & \\mbox{if } k > K_{t-1}. \\end{cases}$\n\\item $\\forall$  point $n$ draw $ x_{t,n} \\sim F(\\theta_t^{c_t,n})$\n\\end{compactitem}\n\nGiven the theory in \\cite{caron}, the transition Kernel must satistfy:\n\n$$ \\int G_0(\\theta_k) T(\\theta_t^k | \\theta_{t-1}^k) d\\theta_{t-1}^k =  G_0(\\theta_k) $$\n\nThe equation means that the invariant distribution must equal its base distribution. A typical way of meeting this restriction and forcing the sampler to converge to the original target density\\cite{smc:theory} is to introduce a set of M auxiliary variables \\textbf{z} such that:\n\n$$ P(\\theta_t^k | \\theta_{t-1}^k) =  \\int P(\\theta_t^k | z_{t}^k)   P(z_t^k| \\theta_{t-1}^k) dz_t^k $$\n\nThe transition kernel of the model can now be sampled by using the following formula\n\n$\\theta_t^k \\sim T(\\theta_{t-1}^k) = T_2 \\circ T_1(\\theta_{t-1}^k)$ with:\n\\begin{equation} \\label{eq1}\n    \\begin{split}\n        z_t^k  & \\sim T_1(\\theta_{t-1}^k)\n        = Normal(\\mu_{t-1}, \\Sigma_{t-1}) Mult( \\delta_{t-1}) Exp( \\lambda_{t-1})\\\\\n        \\mu_t, \\Sigma_t, \\delta_t,  \\lambda_t & \\sim T_2(z_t^k)\n        = NiW( \\kappa_0, \\mu_0, \\nu_0, \\Lambda_0 ) Dir(q_0) Gam(\\alpha_0, \\beta_0) \n    \\end{split}\n\\end{equation}\n\nwhere $\\mu_t, \\Sigma_t, \\delta_t,  \\lambda_t$  are posterior parameters given the auxiliary variables $z$.\n\n\\subsubsection{Sequential monte carlo sampler}\n\nSequential monte carlo samplers for Dirichlet process mixture models where introduced by Doucet et al~\\cite{doucet} and serve as fast alternative to MCMC and VI methods of performing posterior inference. Given the previous definitions, the sampler is now defined as:\n\n\n\\begin{algorithm}[h]\n    \\caption{SMC for DDPM}\\label{SMC}\n    \\begin{algorithmic}[1]\n        \\State \\textbf{Input:} Points \\{$x_{1,1:N_t}, ..x_{T,1:N_t}$\\}with extracted features\n        \\State \\textbf{Output:} Clusters representing of the data\n        \\For{$t = 1,...T$} \n        \\For{$ l = 1,...L$} \n        \\For{$ iter = 1,...S$} \n        \\State Sample $(c_t)^{(l)} \\sim Q_1$  \n        \\State Sample $(\\theta^k ) \\sim Q_2$\n        \\EndFor\t\t\n        \\EndFor\n        \\For{$ k = 1,...K$} \n        \\State Sample $\\Delta s_{t-1}^k \\sim Binom( (s_{t-1,N_{t-1}}^k)^{(l)}, \\rho) $ \n        \\State Set $s_{t,0}^{k} = s_{t-1,N_{t-1}}^{k} -\\Delta s_{t-1}^k$\n        \\State Sample $( (z_{t+1}^k)^{(l)} ) \\sim T_1((\\theta_t^k))^{(l)} $\n        \\EndFor\n        \\State compute particle weights $w_t^l$\n        \\EndFor\n        \\State Normalize and resample weights\n    \\end{algorithmic}\n\\end{algorithm}\n\n\\subsubsection{Gibbs updates}\nThe proposal distribution $Q_1$ is the probability of an assignment $c_{t,n}$ given cluster sizes, parameters and concentration $\\alpha$. Formally $Q_1$ can be written as:\n\\begin{equation} \\label{Gibbs}\n    Q_1(c_{t,n} | s_{t,n}^k, \\theta_t^k, \\alpha) \\propto Cat( s_{t,n}^1,...s_{t,n}^K, \\alpha ) \\times\n    \\begin{cases} \n        F(x_{t,n} | \\theta_t^{c_t} )  &\\mbox{if } k \\leq K_{t-1} \\\\\n    \\int P(x_{t,n} | \\theta_t )G_0(\\theta) d\\theta & \\mbox{if } k > K_{t-1}. \\end{cases}\n    \\end{equation}\n    Where $c_{t,n}$ represents cluster $c$ of point $n$ at time $t$, $s$ represents cluster sizes. The integral represents the posterior predictive distribution of the cluster times the base distribution with the parameters integrated out. A review of the literature helps understand how the posterior predictive formula is derived. More specifically, the analytic expression of the integral is:\n\n\n    \\begin{equation} \\label{Q1}\n        \\begin{split}\n            \\int P(x_{t,n} | \\theta_t )G_0(\\theta) d\\theta\n            = t_{\\nu_0-1}( x_{t,n}^s | \\mu_0, \\frac{\\Lambda_0(\\kappa_0+1)}{\\kappa_0(\\nu_0-1)}) \\times \\prod_{j=1}^V \\frac{\\Gamma(x_{t,n}^c)}{\\Gamma(q_0)} \\times \\\\ \\frac{\\Gamma(\\sum_{j=1}^V q_0)}{\\Gamma(\\sum_{j=1}^V x_{t,n}^c)} \\times Lomax(\\alpha_0 + s_{t,n}^c, \\beta_0 \\sum_{j=1}^V x_{t,n}^c)\n        \\end{split}\n    \\end{equation}\n\n    Where $t$ represents student's t-distribution with $\\nu$ degrees of freedom, Lomax represents Lomax distribution with shape and scale, $\\alpha$ and $\\beta$ repsectively and the rest represent a Dirichlet-Multinomial(aka DirMul) distribution. The formulas of the posterior predictive distributions can be found in the literature with \\cite{compendium} being a good example. \n\n    The conjugacy of the base and prior distribution allows for an easy sampling formula for proposal distribution $Q_2$ which is of the form: \n\n    \\begin{equation} \\label{Q_2}\n        \\begin{split}\n            Q_2(\\theta_t^k | \\theta_{t-1}^k , x_t^k, z_t^k) \\propto F( x_t^k | \\theta_k) \\times T_2(\\theta_t^k | z_t^k) \\\\\n            = NiW( \\mu_t^k, \\Sigma_t^k | \\kappa_n, \\mu_n, \\nu_n, \\Lambda_n ) Dir(\\delta_t^k | q_n) Gam(\\lambda_t^k | \\alpha_n, \\beta_n)\n        \\end{split}\n    \\end{equation}\n\n    With:\n\n    \\begin{equation} \\label{udpates}\n        \\begin{split}\n            \\kappa_n = \\kappa_0 + N, \n            \\nu_n = \\nu_0 + N, \n            \\mu_n = \\frac{\\kappa_0}{\\kappa_0 + N} \\mu_0 +  \\frac{N}{\\kappa_0 + N} \\overline{x}^s\\\\\n            \\Lambda_n = \\Lambda_0 + s_{x}^s,\n            q_N = q_0 +  \\sum_n x_i^c,\n            \\alpha_n = \\alpha_0 +  N,\n            \\beta_n = \\beta_0 +  \\sum^n x_i^a\\\\\n        \\end{split}\n    \\end{equation}\n\n\n    Where $\\overline{x}$ defines the sample mean for the elements assigned at cluster $c$, $s_{x}$ the sample variance and $N$ denotes the number of observations. The formulas for the updates can be found at the literature of cojugate priors like\\cite{compendium}.\n\n    \\subsubsection{Weight updates}\n\n    The only thing left is to define the weight update step. More specifically, on every time step $t$ the weight of particle $l$ is calculated as:\n\n    \\begin{equation}\n        w_t^{(l)} = \\frac {P(c_t^{(l)} , \\theta_t^{(l)}, x_t| \t\\theta_{t-1} )}{P(c_t^{(l)} , \\theta_t^{(l)}| \t\\theta_{t-1} )}\n    \\end{equation}\n\n    Using Bayes rule, the numerator can be written as:\n\n    \\begin{equation}\n        P(x_t , | c_t^{(l)} , \\theta_t^{(l)} \\theta_{t-1} ) \\times P(c_t^{(l)} , \\theta_t^{(l)}|  \\theta_{t-1} )\n    \\end{equation}\n\n    Which can be calculated using equations $Q_2$ and $Q_1$ for the first and second part respectively. After the particle weights are normalized particles are drawn with probability proportional to their weights.\n\n    \\subsection{Decision Layer}\n\n    The decision layer calculates how similar a cluster is to ones encountered before. To achieve that, distance measures must be defined between the stored clusters and the ones that are inferred at the current iteration of the algorithm. Distances between distributions are called divergences and a large amount of literature on divergences exists.\n\n    Every cluster consists of a three part distribution as it was defined in section \\ref{data:dist}. Now let $l$ be the distribution of a stored cluster and $o$ the distribution of a currently observed cluster. $l$ and $o$ can be decomposed into 3 parts: $l_G$,$l_C$,$l_E$ where G,C and E stand for Gaussian, Categorical and Exponential respectively. With that notation the distances between those distributions can be defined. For each individual landmark distribution $l$ and observation distribution $o$ the distances computed where the following: Wesserstein($l_G,o_G$), Kullback-Leibler($l_G,o_G$), SquaredHellinger($l_E,o_E$), Kullback-Leibler($l_E,o_E$), Kullback-Leibler($l_C,o_C$).\n\n    The distance between every distribution can be transposed of a vector of length 5. That way, deciding if a cluster is part of a landmark that has been encountered before is now a problem of finding the optimal decision boundary given the distances at hand. For this project, the decision boundary by empiric evaluation of the landmarks.\n\n\n\n    \\subsection{Complexity}\n\n    The complexity can be decomposed into three parts. The cloud downsampling, the clustering and the decision making process.\n    $$\n    O(total) = O(filter) + O(cluster) + O(decision)\n    $$\n    \\textbf{Downsampling}: The complexity of the cloud downsampling pipeline can be decomposed to the one of its components. This means that the decomposed complexity is defined as follows:\n    $$O(filter) = O(Downsampling + Stat\\ Removal + RANSAC+ FPFH + Color\\ estimation) $$\n\n    Voxel downsampling searches for neighbors within a distance defined by the user and keeps an average value that equally represents the cloud. Since the operation involves searching for neighbors of a point, and since search operations take $O(log\\ n)$ time where N is the number of points within the cloud, the complexity of voxelGrid downsampling is $O(k log n)$ where $k$ is the number of neighbors and $n$ the number of points in the cloud.\n    Statistial outlier removal searches for k nearest neigbhors and removes those whose deviation is passed a certain threshold. Searching for k neighbors in cloud has a complexity of $O(k\\ log\\ n)$.A high amount of research has been done regarding the optimal complexity of RANSAC~\\cite{RANSAC}. RANSAC has a complexity of $ O(k+ m_s*N)$ where k is the maximum amount of iterations defined by the user, $m_s$ the average number of models per sample $N$ the number of data points.\n    FPFH operations have a complexity of $O(nk)$ as given in~\\cite{fpfh}.\n    Finally, for the operation of color estimation, the k nearest neighbors are chosen and some constant operation is performed on them. The complexity for color estimation then becomes $O(k\\ log\\ n)$ where $k$ is the number of neighbors, $n$ the number of points. \n\n    The downsampling pipeline has a total complexity of:\n    \\begin{equation} \\label{Q_filt}\n        O(filter) = O(k_{0}\\ log\\ n_{init} + k_{1}\\ log\\ n_{1} + k_{2}+ m_s*n_{2} + n_{3}k_{3} + k_{4}\\ log\\ n_{3} )\n    \\end{equation}\n\n    Different $k$ indexes represent the number of neighbors defined for every operation. The $n$ represents the number of points used as input. Using the notation  of equation \\ref{Q_filt}, $n_{init}$ defines the whole cloud, $n_1$ the cloud after operation 1, $n_2$ the cloud after operations 2 etc.\n\n    \\textbf{Clustering}: The complexity of the SMC sampler is defined in \\cite{smcddp} as $O(TLKSN)$ where $T$ defines the time frames, $L$ the number of particles, $K$ the number of clusters, $S$ the number of samples, and $N$ the size of the dataset. \n\n    \\textbf{Decision making}: The decision making takes $ O(\\kappa * l^2) $ computational time where $\\kappa$ defines the number of clusters output by the sampler and $l$ the number of landmarks currently stored in the database.\n\n    The final complexity of the method can then be defined as:\n\n    \\begin{equation} \\label{Complexity}\n        O= O(k_{0}logn_{0} + k_{1}logn_{1} + k_{2}(t_M)+ m_s*n_{2} + n_{3}k_{3} + k_{4}logn_{3} + LKSn_3 + \\kappa * l^2)\n    \\end{equation}\n\n    \\subsection{Landmark size}\n\n    The basic block of this algorithm is a cluster containing an environment signature. In order to be able to compute how scalable the method is, the size of a single landmark will be computed. Each landmark is represented by a single row in an SQLite database. Each row consists of 32 real numbers and 1 auto increment integer. Given that SQLite databases assign the memory dynamically, the maximum amount of memory a cell can take will be calculated so that every other case is also included. According to the SQLite manual of datatypes a real value takes up to 8 bytes of memory. An auto increment integer takes up to 4 bytes of information, so the total number  of memory for a worst case scenario landmark is 260 bytes. This number can vary greatly over different environments and is a safe assumption to calculate the memory this method occupies.\n\n    \\section{Results}\n    \\label{sec:results}\n\n    \\subsection{Simple datasets}\n\n    In this section the algorithm was tested against a simple dataset. Testing the method on simple datasets will make easier the extension to more complex clouds that will be used when mapping the environment. In order to test the sampling as well as the decision layer of the algorithm, a simple dataset provided by the pcl\\cite{pcl} library was used. More specifically, a cloud consisting of two milk cartridges with different colors and poses where used. The initial cloud is shown in Fig.\\ref{pcl:clust}(a). The cloud was given as input to the downsampling pipeline. The reduced cloud was then passed as input to the sampler and the clustering results are shown in Fig.\\ref{pcl:clust}(b).\n\n    \\begin{wrapfigure}{l}{0.5\\textwidth}\n        \\begin{tabular}{c}\n            \\includegraphics[width=.4\\textwidth]{clusterings/coloursSource} \\\\\n            (a) Raw cloud  \\\\\n            \\includegraphics[width=.4\\textwidth]{clusterings/coloursCorrect} \\\\\n            (b) Post clustering \\\\[6pt]\n        \\end{tabular}\n        \\label{pcl:clust}\n    \\end{wrapfigure}\n\n    More specifically, the reduced point cloud is shown in the top left part. It is significantly smaller in size and this cloud along with all the meta-information needed to perform the clustering are given as input to the sampler. The sampler outputs a mixture of distributions that best fits the input data. The clustering output is shown in Fig.\\ref{pcl:clust}(b) with the top right being the Gaussian distributions inferred, bottom left the exponential and bottom right the categorical representing the color information of the cloud. The height of the objects leads to distribution with high variance in the z axis. The sampler outputs 2 clusters for the data with each box being assigned separately. The color signature each cluster carries is correctly captured in the bottom right part of Fig.\\ref{pcl:clust}(b). The two boxes are similar in size but their orientation is different and this slight difference is shown in the exponential part of the signature. Each box is now captured as an environment signature that consists of a Gaussian, a Categorical, and an Exponential part.\n\n\n    \\begin{center}\n        \\begin{tabularx}{1.01\\textwidth}{|c *{6}{|Y}|}\n            \\hline\n            \\multicolumn{6}{|l|}{\\centerline{UUID 1}} \\\\\n            \\hline LandUUID & GausKL & GausWes & ExpHel & ExpHel & CatKL \\\\\n            \\hline\n            1&0&1.18111e-07&0&0.164045&0 \\\\\n            \\hline\n            2&13.5579&22449.9&1.56956&0.376699&13.8155 \\\\\n            \\hline\n        \\end{tabularx}    \n        \\label{dist}\n    \\end{center}\n\n    Table~\\ref{dist} shows the distances between every cluster computed against the first. The Gaussian counterparts of the clusters have significant distances due to the distance every cluster has in space. On the other hand, the Distances between their Exponential parts are not that large and the overlap between the categorical singatures leads to medium distances in their Categorical counterparts. Those distances are the information that is being passed to the decision layer to match existing landmarks with new ones. \n\n    \\subsection{Expresiveness and decision layer}\n\n    Post clustering, of operations in the pipeline have to do the comparison of clusters currently extracted with landmarks already stored in the database. The accuracy of the operations is dependent on the expressiveness of the signatures the clusters carry and this is displayed in the examples presented in Fig.\\ref{pip:bounds}. The decision boundary of the pipeline can be decomposed into three basic parts; a positional, a color and an angular boundary. Fig.\\ref{pip:bounds} shows the behavior of the decision layer with respect to the Gaussian(positional) and Categorical(color) parts. \n\n    \\begin{wrapfigure}{l}{0.65\\textwidth}\n        \\begin{tabular}{cc}\n            \\includegraphics[width=.3\\textwidth]{colorBound} &   \\includegraphics[width=.3\\textwidth]{colorBound2} \\\\\n            (a) Yellow Folder& (b) Blue trashcan \\\\[6pt]\n            \\includegraphics[width=.3\\textwidth]{posBound} &   \\includegraphics[width=.3\\textwidth]{posBound2} \\\\\n            (c) Folder initial  & (d) Folder moved \\\\[6pt]\n        \\end{tabular}\n        \\caption{Expresiveness \\& decision bounds}\n        \\label{pip:bounds}\n    \\end{wrapfigure}\n\n    In Fig.\\ref{pip:bounds}(a) the yellow folder allong with some of its environment to the left are being assigned to landmark with id 7383. The folder is then removed and a blue trashcan is put in its place. The folder and the trashcan are similar in size and due to that their Gaussian counterparts will not have large distances. Their main difference lies in the color signature they carry. Since the distance in their color is substantial, a new landmark with id 7412 is created to capture the change in the signature of the environment at that place of the map. The different landmark assigned to the cluster can be seen in Fig.\\ref{pip:bounds}(b). In Fig.\\ref{pip:bounds}(c) and(d) the positional decision boundary is displayed. In the initial position as shown in Fig.\\ref{pip:bounds}(c) the yellow folder is assigned to the green landmark of the cloud. As the object is moved a different position in the cloud, it is being assigned to a different cluster. The reason the cluster is assigned to multiple landmarks is due to the fact that the folder is decomposed to several clusters and each one of them is being assigned to a different part of the cloud with respect to their position. This can be seen in Fig.\\ref{pip:bounds}(c) where the bottom left of the folder is being assigned to the red cluster. Parameter tweaking is possible but the purpose of a general pipeline is to use as little parameter tweaking as possible so that the method is general and can easily be applied to a different scenarios.\n\n\n    The exponential part of the distribution is responsible for the angle signature elements within a cluster have. Practically, having a large amount of different angle distributions in a single cluster leads to objects that have texture and their surface is not smooth. Having a very strict limit in the angle distribution can lead to very small clusters and subsequently to a high amount of landmarks within the data. Using the data from the kinect camera, angle distributions are sensitive to noise that is found in parts of the cloud that are near the end of Kinect sensor's range. Practical evaluation has shown that using an angle limit that is close to the average distance between angle signatures produces stable results and reasonably sized landmarks in the cloud.\n\n    \\subsection{EKF-slam experiments}\n\n    Finally, the pipeline was used in real life scenarios as a sensor model in a Landmark based EKF slam algorithm and was tested in its precision and memory requirements. In Fig.\\ref{slam} an end result of a slam session using the pipeline as a sensor model is shown. As the robot progresses through the environment, the EKF module requests from the sensor model to observe what landmarks are currently detected given the current cloud readings and the existing Landmark database. The pipeline follows the procedure defined in the general pipeline section and returns the landmarks currently detected. The end results shows the amount of landmarks the method requires in order to map a medium sized room. Each sphere represents an environment signature at that specific point the same way it was shown in the simple datasets sections. If the decision layer is chosen to be very strict the number of landmarks the algorithm outputs will increase, and the environment will be represented in more detail. It is important to notice that a strict decision layer must be handled with care as it can lead to a pipeline that continuously adds new landmarks making the sensor module non-converging.\n\n\n    \\begin{wrapfigure}{l}{0.4\\textwidth}\n        \\begin{tabular}{c}\n            \\includegraphics[width=.353\\textwidth]{slam110landmarks2} \\\\\n            (a) Slam session \\\\\n            \\includegraphics[width=.353\\textwidth]{memoryRequirements} \\\\\n            (b) Memory requirements \\\\[6pt]\n        \\end{tabular}\n        \\caption{SLAM session and memory requirements}\n        \\label{slam}\n    \\end{wrapfigure}\n\n    The compression that method introduces is not directly observable from the figure. As the environment is being reduced from a cloud to a landmarks, the memory needs change from using point clouds to using the landmarks extracted in those clouds. Since every landmark represents a signature of the environment at this particular point, the compression is done by reducing a high amount of points to that specific signature. The number of parameters needed to define the three distributions in the signature is all the information this method requires and hence the memory gains are substantial. The expresiveness of the distributions greatly affects the objects as well as object shapes that could be represented. Finally it is always possible to extend the method presented by adding new features and new priors to those features.\n\n\n    \\subsection{Memory requirements}\n\n    The memory requirements of the method is related to the Dirichlet strength parameter $\\alpha$ of the sampler. As the $\\alpha$ parameter increases, the sampler will output more clusters on every iteration. The higher amount the of cluster will result a higher amount of landmarks and, consequently, in larger memory requirements in the method. Fig.\\ref{slam}(b) shows memory requirements as a function of strength parameter alpha.\n\n    As it can be seen, the number of landmarks follows the logarithmic trend of the Dirichlet prior in relation to $\\alpha$. Constantly increasing the alpha value will not make the algorithm follow the logarithmic trend indefinitely. That is due to the fact that despite the alpha increase, the decision layer has an upper bound to the number of landmarks it can have and will eventually saturate. It must also be noted that as the alpha parameter is set to higher numbers, the sampler outputs more clusters making it a more accurate environment descriptor, but also takes more time, making it non feasible to use in real time scenarios. Values of alpha between 0 and 10 provide a robust and fast enough sampler that can be used in online mapping scenarios.\n\n    \\subsection{Limits of the method}\n\n    Limits of the method exist in relation to the two basic layers of the pipeline. The clustering layer and the decision making.\n\n    \\subsubsection{Clustering layer}\n    \\begin{wrapfigure}{l}{.6\\textwidth}\n        \\begin{tabular}{cc}\n            \\includegraphics[width=.26\\textwidth]{singlecluster} &  \\includegraphics[width=.26\\textwidth]{onlyclusters2} \\\\\n            (a) Low $\\alpha$ & (b) High $\\alpha$ pipeline\\\\\n        \\end{tabular}\n        \\caption{Pipeline fail cases.}\n        \\label{pip:limits}\n    \\end{wrapfigure}\n\n    An important limit of the pipeline exists with respect to the Dirichlet hyper-parameter $\\alpha$. During the clustering, choosing a correct value for the hyper-parameter $\\alpha$ is very important in order to have optimal results. Having sampler run with a very low $\\alpha$ can lead to the whole cloud being assigned a single cluster. Having every point in the cloud being part of the same cluster leads to a a significant amount of information loss as no environment specific information are incorporated to the cloud. Fig.[\\ref{pip:limits}](a) shows the behaviour of the sampler for $\\alpha$ values lower than 1. \n\n\n\n    On the other hand, having a very large $\\alpha$ can lead to a very large amount of clusters being output by the sampler every time. That can lead to a non-converging pipeline since every time a new landmark that does not fit the landmark database is output. This leads to many small clusters each containing small number of points each. Furthermore, having a high value in the hyperparameter leads to a slower sampling procedure since the complexity of the sampler is $O(TKLSN)$ where $K$ is the number of clusters. Fig.[\\ref{pcl:kl}](b) displays the behavior of the sampler for very large values $\\alpha$. The spheres represent landmarks and it can be seen that most of the points in the environment are considered individually clusters.\n\n\n    \\subsubsection{Decision layer}\n\n    The restrictions imposed by the decision layer are straightforward due to the constant nature of the decision process. Taking very small distances in the distance threshold operation can lead to pipeline that continuously adds new landmarks to the database. An example is shown in Fig.~\\ref{pip:expo} where limiting the landmark matching operation to very small exponential distances, leads to a cloud where objects are decomposed to a lot entitites.\n\n    \\begin{wrapfigure}{l}{.45\\textwidth}\n        \\includegraphics[width=.4\\textwidth]{monsterchair} \\\\\n        \\caption{Strict exponential limit}\n        \\label{pip:expo}\n    \\end{wrapfigure}\n\n    Object decomposition is even more intense when camera movement is involved due to the different angles. Finally, since the number of landmarks is also a function of noise, areas of the cloud that are near the maximum range of the sensor can lead to different landmarks added frequently.\n    %------------------------------------------------\n\n    \\section{Conclusion and future work}\n    \\label{sec:discussion}\n\n    In this paper a novel method for cloud representation by using non-parametric Bayesian tools was introduced. By reducing parts of the environment to distribution signatures, a large amount of compression is provided making the method highly suitable to target long term slam problems; the expresiveness of the representation is enough to perform slam and is robust even in the noisy parts of the environment. The strengths and weaknesses of the method were presented and an application on how this method could be used to tackle the compression problem of long term slam were given.\n\n    There is a number of directions which could be explored to improve the method. Choosing more complex environment representations could increase the expresive strength of the sampler making it easier to represent with higher precision more complex structures. Also, a hierarchical clustering approach would be an interesting extension since it would both have the ability to capture the structure in a top-down maner and as well as handle the dynamic component that long term slam problems introduce. Furthermore, having a more complex decision layer would also increase the robustness of the method making it able to handle more complex environment structures and more expresive landmarks. Finally, those additions could help lift the dynamic environment restrictions that were defined in Walcotts PhD thesis and make the pipeline tackle in a fully Bayesian way the implications of life-long slam.\n\n    %----------------------------------------------------------------------------------------\n    %\tREFERENCE LIST\n    %----------------------------------------------------------------------------------------\n\n    \\begin{thebibliography}{99} % Bibliography - this is intentionally simple in this template\n\n        \\bibitem{probRobs}\n            \\newblock Thrun, S. (2002). Probabilistic robotics. Communications of the ACM, 45(3), 52-57.\n\n\n        \\bibitem{ekf} \\newblock Bailey, T., Nieto, J., Guivant, J., Stevens, M., \\& Nebot, E. (2006, October). Consistency of the EKF-slam algorithm. In Intelligent Robots and Systems, 2006 IEEE/RSJ International Conference on (pp. 3562-3568). IEEE.  \n\n        \\bibitem{liflonglearning}\n            \\newblock Thrun, S., \\& Mitchell, T. M. (1995). Lifelong robot learning. The Biology and Technology of Intelligent Autonomous Agents, 165-196.\n\n        \\bibitem{lifelongmaps}\n            \\newblock Konolige, K., \\& Bowman, J. (2009, October). Towards lifelong visual maps. In Intelligent Robots and Systems, 2009. IROS 2009. IEEE/RSJ International Conference on (pp. 1156-1163). IEEE.\n\n        \\bibitem{aishalong}\n            \\newblock Walcott, A. (2011). Long-term robot mapping in dynamic environments. \n\n        \\bibitem{pcl}\n            \\newblock{Rusu, R. B., \\& Cousins, S. (2011, May). 3d is here: Point cloud library (pcl). In Robotics and Automation (ICRA), 2011 IEEE International Conference on (pp. 1-4). IEEE.}\n\n\n        \\bibitem{slam++}\n            \\newblock Salas-Moreno, R. F., Newcombe, R. A., Strasdat, H., Kelly, P. H., \\& Davison, A. J. (2013, June). Slam++: Simultaneous localisation and mapping at the level of objects. In Computer Vision and Pattern Recognition (CVPR), 2013 IEEE Conference on (pp. 1352-1359). IEEE.\n\n        \\bibitem{objslam}\n            \\newblock Selvatici, A. H., \\& Costa, A. H. (2008). Object-based visual slam: How object identity informs geometry.\n\n        \\bibitem{objectpointslam}\n            \\newblock Choudhary, S., Trevor, A. J., Christensen, H. I., \\& Dellaert, F. (2014, September). slam with object discovery, modeling and mapping. In Intelligent Robots and Systems (IROS 2014), 2014 IEEE/RSJ International Conference on (pp. 1018-1025). IEEE.\n\n        \\bibitem{objectDisc}\n            \\newblock Koo, S., Lee, D., \\& Kwon, D. S. (2014, September). Unsupervised object individuation from RGB-D image sequences. In Intelligent Robots and Systems (IROS 2014), 2014 IEEE/RSJ International Conference on (pp. 4450-4457). IEEE.\n\n        \\bibitem{fpfh}\n            \\newblock{Fast point feature histogram.Rusu, R. B., Blodow, N., \\& Beetz, M. (2009, May). Fast point feature histograms (FPFH) for 3D registration. In Robotics and Automation, 2009. ICRA'09. IEEE International Conference on (pp. 3212-3217). IEEE.}\n\n        \\bibitem{segOverview}\n            \\newblock {Rabbani, T., van den Heuvel, F., \\& Vosselmann, G. (2006). Segmentation of point clouds using smoothness constraint. International Archives of Photogrammetry, Remote Sensing and Spatial Information Sciences, 36(5), 248-253.}\n\n        \\bibitem{nonParam}\n            \\newblock{Wainwright, M. J., \\& Jordan, M. I. (2008). Graphical models, exponential families, and variational inference. Foundations and Trends in Machine Learning, 1(1-2), 1-305.}\n            ``\n        \\bibitem{omnimaper}\n            \\newblock{A.Trevor,  J.Rogers, and  H.Christensen.  Omnimapper:  A  modular multimodal  mapping  framework.   In IEEE  International  Conference on Robotics and Automation (ICRA), 2014}\n\n        \\bibitem{pointSeg}\n            \\newblock Trevor, A. J., Gedikli, S., Rusu, R. B., \\& Christensen, H. I. (2013). Efficient organized point cloud segmentation with connected components. Semantic Perception Mapping and Exploration\n        \\bibitem{planarSeg}\n            \\newblock Unnikrishnan, R., \\& Hebert, M. (2003, October). Robust extraction of multiple structures from non-uniformly sampled data. In Intelligent Robots and Systems, 2003. Proceedings. 2004 IEEE/RSJ International Conference on IEEE. \n\n        \\bibitem{planarSeg2}\n            \\newblock Rabbani, T., van den Heuvel, F., \\& Vosselmann, G. (2006). Segmentation of point clouds using smoothness constraint. International Archives of Photogrammetry, Remote Sensing and Spatial Information Sciences, 36(5), 248-253.\n\n        \\bibitem{smartSeg}\n            \\newblock Triebel, R., Shin, J., \\& Siegwart, R. (2010, June). Segmentation and unsupervised part-based discovery of repetitive objects. In Robotics: Science and Systems (Vol. 2).\n\n        \\bibitem{smcddp}\n            \\newblock Neiswanger, W., Wood, F., \\& Xing, E. (2014, August). The dependent dirichlet process mixture of objects for detection-free tracking and object modeling. In Proceedings of the Seventeenth International Conference on Artificial Intelligence and Statistics (pp. 660-668).\n\n        \\bibitem{corresp:first}\n            \\newblock Cree, M. J., Jefferies, M. E., \\& Baker, J. T. Using 3D Visual Landmarks to Solve the Correspondence Problem in Simultaneous Localisation and Mapping.\n\n        \\bibitem{corres:sec}\n            \\newblock Lowe, D. G. (2004). Distinctive image features from scale-invariant keypoints. International journal of computer vision, 60(2), 91-110.\n\n        \\bibitem{corres:three}\n            \\newblock Lamon, P., Tapus, A., Glauser, E., Tomatis, N., \\& Siegwart, R. (2003, October). Environmental modeling with fingerprint sequences for topological global localization. In Intelligent Robots and Systems, 2003. Proceedings. 2003 IEEE/RSJ International Conference on IEEE.\n\n\n        \\bibitem{corres:four}\n            \\newblock Sehgal, A., Cernea, D., \\& Makaveeva, M. (2010). Real-time scale invariant 3D range point cloud registration. In Image Analysis and Recognition (pp. 220-229). Springer Berlin Heidelberg.\n\n        \\bibitem{bayes:neal}\n            \\newblock Neal, R. M. (2000). Markov chain sampling methods for Dirichlet process mixture models. Journal of computational and graphical statistics, 9(2), 249-265.\n\n        \\bibitem{bayes:jordan}\n            \\newblock Blei, D. M., \\& Jordan, M. I. (2006). Variational inference for Dirichlet process mixtures. Bayesian analysis, 1(1), 121-143.\n\n        \\bibitem{slam}\n            \\newblock{Montemerlo, M., Thrun, S., Koller, D., \\& Wegbreit, B. (2002). Fastslam: A factored solution to the simultaneous localization and mapping problem. AAAI/IAAI, 593-598.}\n\n        \\bibitem{bayes:smc}\n            \\newblock Doucet, A., De Freitas, N., \\& Gordon, N. (2001). An introduction to sequential Monte Carlo methods (pp. 3-14). Springer New York.\n\n        \\bibitem{antoniak}\n            \\newblock{Charles E Antoniak,Mixtures of dirichlet processes with applications to bayesian nonparametric problems, The annals of statistics (1974), 1152–1174}\n\n        \\bibitem{caron}\n            \\newblock{F. Caron, M. Davy, and A. Doucet, Generalized Polya urn for time-varying Dirichlet process mixtures, 23rd Conference on\n                Uncertainty in Artificial Intelligence (UAI’2007), Vancouver,\n            Canada, July 2007, 2007}\n\n        \\bibitem{compendium}\n            \\newblock{Fink, D. (1997). A compendium of conjugate priors.}\n\n        \\bibitem{smc:theory}\n            \\newblock{Ülker, Y., Günsel, B., \\& Cemgil, A. T. (2010). Sequential Monte Carlo samplers for Dirichlet process mixtures. In International Conference on Artificial Intelligence and Statistics}\n\n        \\bibitem{doucet}\n            \\newblock{Del Moral, P., Doucet, A., \\& Jasra, A. (2006). Sequential monte carlo samplers. Journal of the Royal Statistical Society: Series B (Statistical Methodology), 68(3), 411-436.}\n\n        \\bibitem{RANSAC}\n            \\newblock{Meer, P., Mintz, D., Rosenfeld, A., \\& Kim, D. Y. (1991). Robust regression methods for computer vision: A review. International journal of computer vision, 6(1), 59-70.}\n\n    \\end{thebibliography}\n\n    %----------------------------------------------------------------------------------------\n\n\n    \\end{document}\n", "meta": {"hexsha": "490e478423fde1487ecb9abce4238182f65ee6f9", "size": 54504, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Master Thesis paper/Paper.tex", "max_stars_repo_name": "hadjichristslave/SMC", "max_stars_repo_head_hexsha": "415dd5156dd2d7272b5e846940fce79e8407bf8c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Master Thesis paper/Paper.tex", "max_issues_repo_name": "hadjichristslave/SMC", "max_issues_repo_head_hexsha": "415dd5156dd2d7272b5e846940fce79e8407bf8c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-05-27T12:34:03.000Z", "max_issues_repo_issues_event_max_datetime": "2015-07-13T13:12:04.000Z", "max_forks_repo_path": "Master Thesis paper/Paper.tex", "max_forks_repo_name": "hadjichristslave/SMC", "max_forks_repo_head_hexsha": "415dd5156dd2d7272b5e846940fce79e8407bf8c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 87.2064, "max_line_length": 1514, "alphanum_fraction": 0.729487744, "num_tokens": 13644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.32609275617109024}}
{"text": "\\section{Trapezoidal channel steady uniform flow case}\nThis scenario simulates steady, uniform flow in a trapezoidal channel. It tests the ability of the model to compute the correct flow depth, and the correct lateral distribution of flow velocity, and to conserve mass.\n\n\\subsection{Results}\nFigure~\\ref{fig:fig1mid_channel} shows the along-channel depth and velocity (in the deepest part of the channel). Both should be nearly constant away from the boundaries, and be close to the analytical solutions. \n\nWe do not expect perfect agreement, because the mesh is not very fine in this example (triangle side length of around 1m, just enough to resolve the banks). There will probably be some numerical diffusion in the cross-channel velocity profiles, which will in turn cause errors in the mid-channel velocity and free surface elevation. We deliberately choose to not use a finer mesh, because in realistic problems, it is often not possible to resolve all channels very well.\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=0.9\\textwidth]{fig1mid_channel.png}\n\\caption{Depth and $y$-velocity in the middle of the channel, in the downstream direction.}\n\\label{fig:fig1mid_channel}\n\\end{center}\n\\end{figure}\n\nFigure~\\ref{fig:xsect_vels} shows the cross-channel velocity profiles at a number of cross-sections. Ideally it should agree with the analytical solution, however, this may be difficult due to numerical diffusion in the cross-channel direction. Irrespective, the velocity profile should be qualitatively correct -- highest velocities should be in the channel centre, with lower velocities towards the banks.\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=0.75\\textwidth]{fig2upstream_channel.png}\n\\includegraphics[width=0.75\\textwidth]{fig3central_channel.png}\n\\includegraphics[width=0.75\\textwidth]{fig4downstream_channel.png}\n\\caption{$y$-velocity distribution over a number of cross-sections.}\n\\label{fig:xsect_vels}\n\\end{center}\n\\end{figure}\n\nFigure~\\ref{fig:hydrographs} show the hydrographs through various cross sections showing the flows limiting to the \nexpected inflow $Q$ (For coarser grids there is a discrepency between the expected and calculated limiting \nhydrograph due to the error in back-calculating the hydrograph from ANUGA outputs - although in ANUGAs internal computations the discharge is correct). It is also noted that the transient flow is quite different \nfor different grid sizes. We theorize that the coarser grids produce a rougher bed which slows down the flow. \n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=\\textwidth]{cross_section_10_500_790.png}\n\\caption{Hydrographs over a number of cross-sections.}\n\\label{fig:hydrographs}\n\\end{center}\n\\end{figure}\n\n%Table~\\ref{tab:trapztab} shows the discharge computed at a number of cross-sections in the channel, at a number of time-steps on the way to near steady-state. By the end of the simulation they should all be essentially the same. Large variations may suggest mass conservation errors (small variations are probably due to the interpolation that occurs in the routine:\n%\\begin{equation*}\n%\\textrm{compute\\_flow\\_through\\_cross\\_section}.\n%\\end{equation*}\n\n\n%\\DTLloaddb{dischargeout}{../analytical_exact/trapezoidal_channel/discharge_outputs.txt}\n%\\DTLloaddb{dischargeout}{discharge_outputs.txt}\n%\\begin{table}\n%\\caption{Discharge through cross-sections at a number of $x$-position, at different instants in time}\n%\\label{tab:trapztab}\n%\\DTLdisplaydb{dischargeout}\n%\\end{table}\n\n\\endinput\n", "meta": {"hexsha": "e06c17f4b92d34a12114110b90a8b69e7fe7b360", "size": 3509, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "validation_tests/analytical_exact/trapezoidal_channel/results.tex", "max_stars_repo_name": "samcom12/anuga_core", "max_stars_repo_head_hexsha": "f4378114dbf02d666fe6423de45798add5c42806", "max_stars_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_stars_count": 136, "max_stars_repo_stars_event_min_datetime": "2015-05-07T05:47:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T03:07:40.000Z", "max_issues_repo_path": "validation_tests/analytical_exact/trapezoidal_channel/results.tex", "max_issues_repo_name": "samcom12/anuga_core", "max_issues_repo_head_hexsha": "f4378114dbf02d666fe6423de45798add5c42806", "max_issues_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_issues_count": 184, "max_issues_repo_issues_event_min_datetime": "2015-05-03T09:27:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-20T04:22:48.000Z", "max_forks_repo_path": "validation_tests/analytical_exact/trapezoidal_channel/results.tex", "max_forks_repo_name": "samcom12/anuga_core", "max_forks_repo_head_hexsha": "f4378114dbf02d666fe6423de45798add5c42806", "max_forks_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_forks_count": 70, "max_forks_repo_forks_event_min_datetime": "2015-03-18T07:35:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-01T07:07:29.000Z", "avg_line_length": 61.5614035088, "max_line_length": 471, "alphanum_fraction": 0.8045027073, "num_tokens": 843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.32609275617109024}}
{"text": "\\documentclass[journal,onecolumn]{IEEEtran}\n\n\\usepackage{cite}\n\\usepackage[pdftex]{graphicx}\n\\usepackage[cmex10]{amsmath}\n\\interdisplaylinepenalty=2500\n\\usepackage{array}\n\\usepackage{url}\n\\usepackage{fancyvrb}\n\\usepackage{color}\n\\usepackage[ascii]{inputenc}\n\\usepackage{listings}\n\\lstset{language=Python,\n        numbers=left,\n        keywordstyle=\\color[rgb]{0,0,1},\n        commentstyle=\\color[rgb]{0.133,0.545,0.133},\n        stringstyle=\\color[rgb]{0.627,0.126,0.941},\n        columns=fixed,}\n\n\\markboth{EE643}{Jonathan Klein}\n\n\n\\begin{document}\n\\title{Parallelized Viterbi Algorithm in Python using PyCUDA and PP}\n\\author{\\IEEEauthorblockN{Jonathan Klein}\\\\\n    \\IEEEauthorblockA{Department of Electrical and\\\\Computer Engineering\\\\\n    University of Alaska, Fairbanks\\\\\n    Fairbanks, Alaska 99775, USA\\\\\n    Email: kleinjt@ieee.org}}\n\n\n\\maketitle\n\n\\begin{abstract}\n%\\boldmath\nPyterbi is an open source Viterbi decoder parallelized either with CUDA or SMP. It is written in Python and uses the PyCUDA and PP modules. The PyCUDA parallelized Viterbi decoder is approximately 100 times faster than the single core unparallelized reference implementation. Each probable path at each state is computed in parallel, and the backtraces of multiple trellises is computed in parallel. The PP parallelized path can process multiple Viterbi trellises simultaneously and can dispatch them across multiple cores or computers.  \n\n\\hfill \\today \n\\end{abstract}\n\n\\section{Introduction}\nPyterbi is an open source parallelized Viterbi decoder. It is capable of finding the most likely sequence of states through an arbitrary number of probabilistic finite state machines given noisy output observations. The PyCUDA parallelized path extracts parallelism by computing the most likely previous state for each possible state every time step in parallel. The PP parallelized path dispatches trellises to multiple CPU cores, or servers over a network.\n\n\nViterbi decoders have applications to pattern recognition and communication systems, including speech recognition, convolution code decoding, and continuous phase modulation decoding [1] [2]. A parallelized Viterbi decoder could be useful for wireless base stations communicating with many devices using convolutional coding or continuous phase modulation or a call center performing voice recognition on several incoming calls. More realistically, pyterbi provides an open source example of PyCUDA, PP, and generating graphs using matplotlib.   \n\n\nThe Viterbi algorithm maintains the most likely sequence of states leading to state. This is repeated for each observation. See Figure 2 for the reference Python implementation of the forward pass of the Viterbi algorithm.\n\\begin{figure}[h!]\n\\begin{lstlisting}\n# set initial probabilities\npath_p[0,:] = init_p + emit_p[obs[0]]\n\nfor n in range(1, nobs):\n    for m in states:\n        # calculate probabilities of previous states transitioning to state m    \n        p = emit_p[obs[n]][m] + trans_p[:,m] + path_p[n-1]\n        # select most likely previous state for state m\n        back[n][m] = numpy.argmax(p)\n        # set that as probability of state m at time n \n        path_p[n][m] = numpy.amax(p)\n\\end{lstlisting}\n    \\label{fig:forcode}\n    \\caption{Python code for Viterbi forward path.}\n\\end{figure} \n\nOnce the most likely prior state for each state and observation in the trellis has been tabulated, the most likely path through a trellis can be computed. Starting with the most likely final state, the most likely sequence of states can be traced back through the trellis. See Figure 2 for Python code implementing the backwards pass of the Viterbi algorithm. \n\\begin{figure}[h!]\n\\begin{lstlisting}\nroute = numpy.zeros(nobs,dtype=numpy.int16)\n# find the most likely final state\nroute[-1] = numpy.argmax(path_p[-1,:])\n\nfor n in range(2,nobs+1):\n    # backtrace through trellis selecting the most likely previous trace\n    route[-n] = back[nobs-n+1,route[nobs-n+1]]\n\\end{lstlisting}\n    \\label{fig:backcode}\n    \\caption{Python code for Viterbi backtrace.}\n\\end{figure}\n\n\\section{Hardware Platform}\nPyterbi was tested on a Lenovo T420-41786VU laptop. This platform has a few limitations which add uncertainty to the benchmarks. \n\n\\subsection{Host Processor}\nThe Intel i5-2520M processor supports Intel Turbo Boost, which dynamically scales core frequencies to maintain temperature limits [4]. This means that an application running on one core could see higher clock frequencies than an application which keeps two cores active. Additionally, the T420 laptop can't sustain full processor usage on both cores for an extended period of time. The laptop provided warning messages to a terminal stating that processor speed was being scaled back to avoid overheating while running an extended PP benchmark. These factors will increase the relative performance of shorter single core tasks.  \n\n    \\begin{figure}[!h]\n            \\begin{tabular}{ | l | l |}\n                \\hline\n                Processor & Intel i5-2520M, 2.50GHz \\\\ \\hline\n                Cache & 3MB Cache \\\\ \\hline\n                Cores & 2 Hyper-Threaded cores \\\\ \\hline\n                Memory & 4096MB RAM \\\\ \\hline\n                OS & Linux 2.6.38-10 \\\\ \\hline\n            \\end{tabular}\n    \\end{figure}\n    \n\\subsection{Graphics Card}\n    PyCUDA was written and tested on a NVIDIA NVS4200M graphics card. This is a low-end laptop graphics card with only a 64-bit memory bus and 48 cores. Performance of pyterbi would probably increase on a higher performance desktop graphics card. \n     \\begin{figure}[!h]\n            \\begin{tabular}{ | l | l |}\n                \\hline\n                Graphics Card& Nvidia NVS 4200M \\\\ \\hline\n                Memory & 1024 MB DDR3\\\\ \\hline\n                CUDA Cores & 48 \\\\ \\hline\n                Memory Bus Width & 64 bits\\\\ \\hline\n                Driver & 270.41.19 \\\\ \\hline\n                CUDA Version & 4.0 \\\\ \\hline\n                Core Speed & 800 MHz \\\\ \\hline\n                Device to Host Bandwidth & 2600MB/s \\\\ \\hline\n                Host to Device Bandwidth & 3000MB/s \\\\ \\hline\n                Compute Capability & 2.1 \\\\ \\hline\n            \\end{tabular}\n    \\end{figure}\n\n\\section{Parallelization}\n        The PyCUDA path of pyterbi was parallelized by computing the most likely previous state for each state in parallel for an observation. This is equivalent to parallelizing the for loop on line 5 of Figure 1. These can be computed in parallel, because each state only depends on information from previous observations. See Figure~\\ref{fig:cpm} for an illustration of this. In this this figure, each thread is represented by a color, and lines represent accessing the probability of prior states. The treads are synchronized at every observation after computing the most likely previous state. Each trellis is mapped to a block of threads, which can share a grid with other trellises. \n\n        \\begin{figure}\n            \\includegraphics[width=.8\\textwidth]{figures/cpmfulltrelliscolored.png}\n            \\caption{Viterbi algorithm at time T=2Ts. Figure adapted from Proakis [2].}\n            \\label{fig:cpm}\n        \\end{figure}\n\nThe PP path is parallelized by dispatching processes to compute each trellis. This is coarser parallelism than the PyCUDA path. Finer grained parallelism was not easily possible using the standard Python interpreter because of the global interpreter lock, which prevents concurrent execution of multiple threads. Processes are more expensive to create than threads and cannot share memory as easily, so instead of creating threads for each state in a trellis, the PP path of pyterbi creates a process for each trellis.    \n\n\\section{Software Design and Data Location}\nThe first version of the PyCUDA path of pyterbi was 15 times faster than the reference path. Many optimizations and tweaks later, this was improved to a 100 times speedup. \n        \nThe first optimization of pyterbi was moving the emission probability, observation, and transmission probability matrices from global to constant memory. This slowed down execution time by 50\\%. This is possibly due to stuffing too much information into the constant cache and ignoring the L1/L2 cache present for global memory on compute capability 2.1 cards. Moving only the observation sequence to constant memory increased execution by 5\\%. Eventually, the observation sequence and all other constant information was cached in shared memory instead of constant memory to support an arbitrary number of trellises.\n\nThe next optimization to Pyterbi was caching the emission probability, observation, and transmission matrices in shared memory. These matrices are filled from global memory at the start of the kernel in parallel, with a coalesced memory access pattern. Caching the constant matrices in shared memory at the start of each kernel reduced execution time by another 5\\%. In addition to caching constant information in shared memory, the slices of the probability matrix representing the current and previous state probabilities are stored in shared memory.\n\nThe largest speed up for the PyCUDA path of pyterbi came from reducing communication between the host and graphics card. The initial version of pyterbi called a kernel for each observation, implicitly synchronizing. Moving the observation loop to the kernel and explicitly synchronizing threads in a kernel reduced the number of kernel calls from the number of observations to once per trellis, which led to over a 100\\% speedup.\n\nThe final optimization to pyterbi was moving the backtrace computation from the host to the device. This meant the backtrace of multiple trellises could be computed in parallel, and only the route information needs to be copied back to the host for each trellis, instead of copying back the final path probabilities and the entire backtrace matrix, which is much larger. Optimizing the backtrace led to a 40\\% speedup.\n\n\\section{Results}\nThe SMP PP path of pyterbi approaches a two times speedup on a dual core hardware platform as the complexity of a trellis increases. See Figure \\ref{fig_rhost} for a plot of the speedup of the PP path across observation sequence lengths and number of states. The speedup may be approaching two for more complicated inputs because the constant time associated with creating and dispatching jobs becomes dwarfed by time spent processing the trellises. The speedup will probably approach four on a four core processor given a sufficiently large number of complex trellises.\n\n\\begin{figure*}[!t]\n    \\centering\n    \\includegraphics[width=.5 \\linewidth]{figures/speedupgraphhost.png}\n    \\caption{Speedup of multiple process parallelized pyterbi over a single process decoder.}\n    \\label{fig_rhost}\n\\end{figure*}\n\nIn addition parallelizing for multiple core processors, PP also allows parallelization on clusters of computers. As a proof of concept, I tested pyterbi in a cluster consisting of a T420 laptop connected to a low-end VPS sharing a single AMD Opteron core with an unknown number of other virtual machines through a tethered internet connection from a cell phone. Clustering a single core of the T420 with the server led to a 10\\% speedup. The speedup would probably be improved by using a cluster of faster computers connected with a more suitable network connection.\n\nThe PyCUDA path of pyterbi provides over 100 times speedup compared the reference implementation for sufficiently complex trellises. See Figure \\ref{fig_rcuda} for a graph of PyCUDA speedup as the observation length and number of states increases. The speedup generally increases as the observation length increases, and as the number of states in the trellis increases. This is probably because the increased complexity with an increase in states is $O(N)$ for the PyCUDA path, and $O(N^2)$ for the reference path. The speedup also increases as the observation length increases. This is probably because the relatively constant setup time of creating and initializing the kernel is overtaken by the time spend traversing the trellis.\n\n\\begin{figure*}[!t]\n    \\centering\n    \\includegraphics[width=.5 \\linewidth]{figures/speedupgraphcuda.png}\n    \\caption{Speedup from CUDA parallelized viterbi decoder.}\n    \\label{fig_rcuda}\n\\end{figure*}\n\n\n\\section{Conclusion}\nPyterbi achieves a noticeable speedup over a non-parallelized reference implementation. It provided an opportunity to learn about CUDA and the PyCUDA and PP libraries. \nSeveral improvements to pyterbi are possible:\n\\begin{itemize}\n    \\item Rewriting the host code in a faster language (C)\n    \\item Rewriting host code for finer-grained parallelism with threads\n    \\item Testing kernel concurrency on more powerful graphics cards\n    \\item Testing realistic cases of cluster computing\n    \\item Getting PyCUDA working with PP for CUDA accelerated cluster computing \n\\end{itemize}\n\nPyCUDA made accessing the CUDA API more pleasant than using CUDA from C. Abstracting away the cleanup of objects, error checking, and some of the syntax for memory transfers was helpful. While it doesn't save the programmer from understanding what is happening (and the kernel must still be written in C), it makes programming and debugging faster and easier. Learning CUDA through PyCUDA is a little more gentle. Likewise, the PP module was impressive. Easy to use parallelism libraries for higher level languages make parallel programming very accessible, and reduce the cost of parallelizing suitable applications.\n\nAll the source code from this project, including this paper, are available under an MIT license at \\url{http://github.com/loxodes/pyterbi}\n\n\\section*{References}\n        [1] Lou, H.-L.; , ``Implementing the Viterbi algorithm,'' Signal Processing Magazine, IEEE , vol.12, no.5, pp.42-52, Sep 1995 \\\\\n\n        [2] John Proakis. Digital Communications. McGraw-Hill Science/Engineering/Math, 5 edition, 2007. \\\\\n\n        [3] C. Liu, ``CuHMM: a CUDA Implementation of Hidden Markov Model Training and Classification,'' 2009 \\\\\n\n        [4] Intel, ``Intel Turbo Boost Technology 2.0,'' 2011, URL: \\url{http://www.intel.com/content/www/us/en/architecture-and-technology/turbo-boost/turbo-boost-technology.html}\\\\\n\n        [5] Vanovschi V., ``Parallel Python Software,'', 2011, \\url{http://www.parallelpython.com}\\\\\n\n        [6] Andreas Kloeckner, ``PyCUDA,'', 2011, \\url{http://mathema.tician.de/software/pycuda}\\\\\n\n\\end{document}\n", "meta": {"hexsha": "d96045b23516206a41a1fd811d720703005aaa09", "size": 14412, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/pycuda_paper.tex", "max_stars_repo_name": "loxodes/pyterbi", "max_stars_repo_head_hexsha": "1c6255d610877d786a95ea9a026e6a8499affe14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2015-03-12T18:02:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-03T18:07:45.000Z", "max_issues_repo_path": "doc/pycuda_paper.tex", "max_issues_repo_name": "loxodes/pyterbi", "max_issues_repo_head_hexsha": "1c6255d610877d786a95ea9a026e6a8499affe14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/pycuda_paper.tex", "max_forks_repo_name": "loxodes/pyterbi", "max_forks_repo_head_hexsha": "1c6255d610877d786a95ea9a026e6a8499affe14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-06-06T13:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-31T16:44:45.000Z", "avg_line_length": 75.8526315789, "max_line_length": 734, "alphanum_fraction": 0.7612406328, "num_tokens": 3310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3260927561710902}}
{"text": "\\chapter{Inversion Drivers}\\label{chapter:ref:Drivers}\n\nOur task in the inversion\\index{inversion} is to find the geological structure within a given three-dimensional region $\\Omega$ from given geophysical \nobservations\\index{observation}. \nThe structure is described by a \\emph{level set function} $m$\\index{level set function}.\nThis function can be a scalar function or may have several components,\nsee Chapter~\\ref{Chp:ref:regularization} for more details.\nIts values are dimensionless and should be between zero and one.\nHowever, the latter condition is not enforced.\nThrough a mapping (see Chapter~\\ref{Chp:ref:mapping}\\index{mapping}) the values\nof the level set function are mapped onto physical parameter $p^f$\\index{physical parameter}.\nThe physical parameter feeds into one or more forward models\\index{forward model}\nwhich return a prediction for the observations, see Chapter~\\ref{Chp:ref:forward models}.\nAn inversion may consider several forward models at once which we call\n\\emph{joint inversion}\\index{joint inversion}.\n\n\nThe level set function describing the actual geological structure is given as\nthe function which minimizes a particular \\emph{cost function}\n$J$\\index{cost function}.\nThis cost function is a composition of the difference of the predicted\nobservations to the actual observations for the relevant forward models, and\nthe regularization term\\index{regularization} which controls the smoothness of\nthe level set function.\nIn general the cost function $J$ takes the form\n\\begin{equation}\\label{REF:EQU:INTRO 1}\nJ(m) = J^{reg}(m) + \\sum_{f} \\mu^{data}_{f} \\cdot J^{f}(p^f)\n\\end{equation} \nwhere $J^{f}(p)$ is a measure of the defect of the observations predicted for\nthe parameter $p^f$ against the observations for forward model $f$, and\n$J^{reg}(m)$ is the regularization term.\nThe weighting factors $\\mu^{data}_{f}$ are dimensionless, non-negative\ntrade-off factors\\index{trade-off factor}.\nPotentially, values for the trade-off factors are altered during the inversion\nprocess in order to improve the balance between the regularization term and\nthe data defect terms\\footnote{The current version does not support an automated selection \nof trade-off factors}.\nThe physical parameter $p^f$ depends on the level set function\n$m$ in a known form:\n\\begin{equation}\\label{REF:EQU:INTRO 1b}\np^f = M_{f}(m)\n\\end{equation} \nwhere $M_f$ is a given mapping. For the case of gravity inversion\nthe $M_f$ is a simple linear function mapping the level set function $m$ with dimensionless values \nto physical density anomaly values $\\rho$.\n(see Chapter~\\ref{Chp:ref:mapping}\\index{mapping}). In its simplest from the mapping is given as \n$\\rho = \\rho_0 \\cdot m$ where $\\rho_0$ is a reference density. It is pointed out that \nthe inversion techniques applied do not constrain limits to the values of the level set function\nalthough there is the notion that its values are between zero and one. However, \nlimits can be enforced to physical parameters using appropriate mappings.\n\nThe level set function $m$ and consequently the physical parameters $p^f$ are \ndefined over a three dimensional domain $\\Omega$ which represented by an \\escript \n\\class{Domain} object, see \\cite{ESCRIPT}. The domain builder methods provide \nfunctions to build appropriate domains from field data sets, see Section~\\ref{Chp:ref:domain builder}.\nIn general the domain is a rectangular three-dimensional domain where the third dimension $x_2=z$ represents\ndepth. The $z=0$ surface defines the surface of the earth where $z<0$ is defining the subsurface region and\n$z>0$ is defining the region above the surface, see Figure~\\ref{fig:cartesianDomain}. In general physical parameters such as\ndensity and susceptibility anomaly are known above the surface, typically assumed to be zero. \nFor subregions where a physical parameter is known it is assumed that the corresponding level set function as \nthe value zero. If required, non-zero values for the physical parameters can be set using appropriate mapping.      \n\n\\begin{figure}[ht]\n    \\centering\\includegraphics{classdep}\n    \\caption{Class dependencies}\n    \\label{fig:classes}\n\\end{figure} \n\n\\section{Class Dependencies}\nFor simplification of usage \\downunder provides predefined classes that drive inversion for particular \nproblems. The usage of this classes is being discussed in Part~\\ref{part1}. More details are shown in\nSection~\\ref{chapter:ref:Drivers:Drivers}. It is the role of the driver class to orchestration an \ninversion. New inversions can easily be implemented by modifying the available drivers.\n\nAs illustrated in Figure~\\ref{fig:classes} the driver class uses geophysical data as\nmanaged through the \\class{DataSource} class (see Chapter~\\ref{Chp:ref:data sources}) and \nan \\escript domain to define an appropriate\ncosts function to be minimized. The driver class also run the minimization solver.\nThe \\escript domain~\\cite{ESCRIPT} is created using the \\class{DomainBuilder}, see Chapter~\\ref{Chp:ref:domain builder},\nwhich builds an appropriate domain and mesh based on the geophysical data used in the inversion. \n\\class{ReferenceSystem} defines the coordinate system to be used. \nBased on the inversion to be performed (gravity, magnetic, joint) the \ndriver class builds an appropriate cost function $J$ including the regularization term $J^{reg}$, see\n\\class{Regularization} class in Chapter~\\ref{Chp:ref:regularization}, \nthe forward models, see Chapter~\\ref{Chp:ref:forward models} and\nthe required mappings, see \\class{Mapping} class in Chapter~\\ref{Chp:ref:mapping},\nto connect the level set function with physical parameters. Finally the driver class calls the\nsolver to minimize the cost function, see Chapter~\\ref{chapter:ref:Minimization}.\n\nThe driver classes cover commonly used cases for the convenience of users. In fact, \nmore general cases can be implemented in an easy way. Script \\examplefile{nodriver.py} is an example \non how to implement an inversion without using one of the driver classes.   \n\n\n\n\n\n\n\n\\input{Drivers}\n\n\n\n\n\n\n\n \n", "meta": {"hexsha": "d74bbed51fe55d961a01f495cad7cb79f55ff38a", "size": 6020, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/inversion/IntroPart2.tex", "max_stars_repo_name": "markendr/esys-escript.github.io", "max_stars_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/inversion/IntroPart2.tex", "max_issues_repo_name": "markendr/esys-escript.github.io", "max_issues_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-01-14T03:07:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-14T03:07:43.000Z", "max_forks_repo_path": "doc/inversion/IntroPart2.tex", "max_forks_repo_name": "markendr/esys-escript.github.io", "max_forks_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.2293577982, "max_line_length": 151, "alphanum_fraction": 0.7873754153, "num_tokens": 1423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3260927561710902}}
{"text": "\n\\chapter*{Introduction}   \\addcontentsline{toc}{chapter}{Introduction} \\label{intro}\n\nThe tessellation of surfaces and solids into complexes of small elements such as triangles, quadrilaterals, tetrahedra or hexahedra is one of the major ingredients for many computational algorithms.\nApplications range from rendering, most notably in computer games, to computational science, in particular for the numerical solution of partial differential equations on complex meshes for the study of physical phenomena.\nThese various areas lead to a broad range of different requirements for a mesh library, which certainly cannot be fulfilled by a single, predetermined data structure.\n{\\ViennaGrid} employs a highly configurable internal representation of meshes, while providing a uniform interface for the storage and access of data on mesh elements as well as STL-compatible iteration over such elements.\n\nAs an example, consider the basic building block of triangular meshes, the triangle:\nThe three vertices fully define the shape of the triangle, the edges can be derived from vertices if a common reference orientation of the triangles is provided.\nDepending on the underlying algorithm, edges of the triangle may or may not be of interest:\n\\begin{itemize}\n \\item Consider a class \\lstinline|triangle|, holding the three vertices only.\n       A triangular mesh is then some array or list of \\lstinline|triangle|s and an algorithm \\texttt{algo1} working only on vertices on a per-cell basis can be executed efficiently.\n       An example for such an algorithm is the assembly of a linear, nodal finite element method.\n\n \\item An \\texttt{algo2} may need to have global edge information available, i.e.~only one instance of an interfacing edge of two triangles should exist in an explicit manner.\n       Thus, storing the edges globally in the mesh will allow the use of \\texttt{algo2}, but will at the same time introduce unnecessary edge information for \\texttt{algo1}.\n       Finite volume schemes can be seen as an example for this second type of algorithms.\n\n \\item A third algorithm \\texttt{algo3} may need global edge information, as well as information about the local orientation of edges with respect to each triangular cell.\n      In such a case it may be preferred to additionally store mappings from global orientations to local orientations of the edges on each triangle if fast execution is desired.\n      Such an additional storage of orientations will render the data structure well suited for \\texttt{algo3}, but less suited for \\texttt{algo1} and \\texttt{algo2}.\n      An example for such a third type of algorithm are -- at least to some extent -- high-order finite element methods.\n\\end{itemize}\nThe situation for tetrahedral meshes is even more complicated, because additional orientation issues of shared facets come into play.\n\n\\begin{figure}[bt]\n \\centering\n\\mbox{\n\\subfigure[Store only vertices globally, do not store edges.]{\n \\includegraphics[scale=0.9]{figures/storage-vglob-cglob}\n\\label{subfig:storage-vglob-cglob}\n} \\hspace{0.5cm}\n\\subfigure[Store vertices and edges globally.]{\n \\includegraphics[scale=0.9]{figures/storage-vglob-eglob-cglob}\n\\label{subfig:storage-vglob-eglob-cglob}\n} }\n \\caption{Two storage schemes for a triangle and the underlying triangular mesh data structure.}\n \\label{fig:storage-schemes-triangle}\n\\end{figure}\n\nThe aim of {\\ViennaGrid} is to be highly customizable such that all three algorithms outlined above can be supported with an optimal data layout.\nIn particular, {\\ViennaGrid} allows for a user-specification of the storage of elements, in particular which boundary elements are stored inside the mesh as well as which topological information is stored on each element.\nAfter a brief introduction into the nomenclature used in this manual in Chapter \\ref{chap:entities}, the configuration of the data storage layout is explained in Chapter \\ref{chap:meshsetup}, and the basic steps required to fill a mesh with cells is explained in Chapter \\ref{chap:meshsetup}.\n\nIn addition to high flexibility with respect to the underlying data structures, {\\ViennaGrid} provides STL-compatible iterators and access to sub-elements of a mesh, cf.~Chapter \\ref{chap:iterators}.\nThis allows for writing generic code that is a-priori independent of the underlying spatial dimension, yet enables compiler optimizations such as loop unrolling for tight loops.\nIn particular, a single implementation for algorithms operating in multiple dimensions and using different mesh types (triangular, hexahedral, etc.) can be obtained.\n\nOne of the strengths of {\\ViennaGrid} is the generic facility provided for storing arbitrary quantities on a mesh, cf.~Chapter \\ref{chap:data}.\nThis is achieved by the use of set of concepts which provide uniform access to data through so called accessors or fields.\n\nA typical requirement for a meshing library is mesh refinement.\nThis is in particular of interest for computational science, where singularities near corners need to be resolved sufficiently well.\n{\\ViennaGrid} provides both uniform and adaptive refinement algorithms, cf.~Chapter \\ref{chap:algorithms}, where also other geometric algorithms such as Voronoi information is covered.\n\nInput/Output facilities are discussed in Chapter \\ref{chap:io}.\nSome of the library internals are discussed in Chapter \\ref{chap:internals} and design decisions are outlined in Chapter \\ref{chap:design}.\n\nThere are of course a number of other free software libraries having functional overlap with {\\ViennaGrid}.\nWe give a brief discussion of the pros and cons of selected libraries in the following.\nThis should allow potential users of our library to get a better feeling of what to expect and what not to expect from {\\ViennaGrid}.\nWe have carefully checked the documentation of each project, but clearly cannot guarantee that all information is fully accurate.\n\\begin{itemize}\n  \\item \\textbf{CGAL} \\cite{CGAL}: The focus of the Computational Geometry Algorithms Library (\\texttt{CGAL}) is on geometrical algorithms such as the computation of convex hulls of point sets.\n        It offers a mesh generation facility and provides iterators over cell vertices.\n        However, the storage of quantities and the convenient traversal of mesh elements is not provided.\n\n  \\item \\textbf{DUNE} \\cite{DUNE}: \\texttt{DUNE} follows a similar approach for the generic representation of meshes.\n        It provides support for conforming and non-conforming grids, as well as support for parallel and distributed meshes.\n        However, unlike {\\ViennaGrid}, we could not find any mechanism providing a convenient means to store data on mesh elements (users are essentially required to handle their data themselves), and for the customization about the internal storage of mesh elements.\n\n  \\item \\textbf{GrAL} \\cite{GrAL}: The Grid Algorithms library (\\texttt{GrAL}) provides mesh data structures and algorithms operating on them.\n        A number of concepts used in {\\ViennaGrid} such as $n$-\\textit{cells} are implemented in \\texttt{GrAL} as $k$-\\textit{Elements}, however it does not provide any facilities to store data on mesh elements or to refine meshes.\n\n  \\item \\textbf{libmesh} \\cite{libmesh}: The \\texttt{libmesh} library is not only a mesh library, but also a framework for numerical simulations.\n        Since {\\ViennaGrid} is designed to be as general as possible without tying one to a particular application prematurely, we only compare the parts in \\texttt{libmesh} related to mesh handling.\n        \\texttt{libmesh} supports one-, two- and three-dimensional meshes and also allows to generate meshes for simple meshs.\n        Iterations over elements of a mesh are carried out in a runtime manner, thus causing potential overhead.\n        One of the strengths of \\texttt{libmesh} is the support for mesh refinement and parallel computations.\n        Support for user-defined data on mesh elements is also provided.\n\n  \\item \\textbf{OpenMesh} \\cite{OpenMesh}: \\texttt{OpenMesh} provides a generic data structure for representing and manipulating polygonal meshes.\n        The main goals are flexibility, efficiency and ease-of-use.\n        Similarly to {\\ViennaGrid}, generic programming paradigms are used.\n        \\texttt{OpenMesh} allows storing custom data of arbitrary type on mesh elements, but it seems to rely on potentially slow string comparisons at run-time to retrieve the data.\n        Moreover, \\texttt{OpenMesh} is specifically designed for surface (i.e.~non-volumetric) meshes, and thus only the concepts of vertices, edges and faces are used.\n\n  \\item \\textbf{trimesh2} \\cite{trimesh2}: \\texttt{trimesh2} is a C++ library that is particularly designed for triangular meshes in 3D only.\n        It explicitly targets efficiency, possibly at the expense of some generality.\n        We could not find further information for a comparison with {\\ViennaGrid} from the documentation provided.\n\n  \\item \\textbf{VCGlib} \\cite{VCGlib}: \\texttt{VCGlib} processes triangular and tetrahedral meshes.\n        Similar to \\texttt{OpenMesh}, \\texttt{VCGlib} uses the concepts of vertices, edges and faces only, so the processing of volume meshes is hampered.\n        Again similar to \\texttt{OpenMesh}, the provided facility to store data on mesh elements relies on potentially slow string comparisons.\n\\end{itemize}\n\n\n\n\n", "meta": {"hexsha": "eaa4e158368b1c0d45d83ba61a8efabad5d49d51", "size": 9356, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/manual/introduction.tex", "max_stars_repo_name": "viennagrid/viennagrid-dev", "max_stars_repo_head_hexsha": "6e47c8d098a0b691d6b9988f2444cd11d440f4c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-09-13T03:50:58.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-27T14:24:49.000Z", "max_issues_repo_path": "doc/manual/introduction.tex", "max_issues_repo_name": "viennagrid/viennagrid-dev", "max_issues_repo_head_hexsha": "6e47c8d098a0b691d6b9988f2444cd11d440f4c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/manual/introduction.tex", "max_forks_repo_name": "viennagrid/viennagrid-dev", "max_forks_repo_head_hexsha": "6e47c8d098a0b691d6b9988f2444cd11d440f4c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2015-07-03T07:14:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-20T00:51:58.000Z", "avg_line_length": 91.7254901961, "max_line_length": 292, "alphanum_fraction": 0.7869816161, "num_tokens": 2022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3260927561710902}}
{"text": "\\documentclass[10pt, a4paper, twoside]{basestyle}\n\n\\usepackage[backend=biber,firstinits=true,maxnames=100,style=alphabetic,maxalphanames=4,doi=true,isbn=false,url=false,eprint=true]{biblatex}\n\\bibliography{bibliography}\n\n\\usepackage[Mathematics]{semtex}\n\\usepackage{chngcntr}\n\\counterwithout{equation}{section}\n\n%%%% Shorthands.\n\n%%%% Title and authors.\n\n\\title{%\n\\textdisplay{%\nOn an Article by Celledoni et al.%\n}%\n}\n\\author{Pascal~Leroy (phl)}\n\\begin{document}\n\\maketitle\n\\begin{sloppypar}\n\\noindent\nThis document provides clarifications, corrections, and accuracy improvements to the formul{\\ae} presented in \\cite{Celledoni2007}.  It follows the notation\nand conventions of that paper.  Note that the preprint \\cite{Celledoni2007} differs in some of the formul{\\ae} from the final publication \\cite{Celledoni2008},\nand that we follow the former because the latter introduced errors.\n\\end{sloppypar}\n\n\\section*{Preamble}\nWe remind the reader of the derivation formul{\\ae} for the Jacobian elliptic functions (\\cite{NistHMF2010}, section 22.13(i)):\n\\[\n\\begin{dcases}\n\\derivop{u}{\\JacobiSN u} &= \\JacobiCN u \\JacobiDN u \\\\\n\\derivop{u}{\\JacobiCN u} &= -\\JacobiSN u \\JacobiDN u \\\\\n\\derivop{u}{\\JacobiDN u} &= -k^2 \\JacobiSN u \\JacobiCN u\n\\end{dcases}\n\\]\nand for the hyperbolic functions (\\cite{NistHMF2010}, section 4.34):\n\\[\n\\begin{dcases}\n\\derivop{u}{\\HyperbolicTangent u} &= \\HyperbolicSecant^2 u \\\\\n\\derivop{u}{\\HyperbolicSecant u} &= -\\HyperbolicSecant u \\HyperbolicTangent u\n\\end{dcases}\n\\]\n\n\\section*{The equations of motion}\nWe start by writing equation (1) of \\cite{Celledoni2007} in coordinates.  The coordinates of $\\vm$ and $\\VectorSymbol{I}$ are defined by:\n\\[\n\\vm\\DefineAs\n\\begin{pmatrix}\nm_1 \\\\ m_2 \\\\ m_3\n\\end{pmatrix}\n\\]\nand:\n\\[\n\\VectorSymbol{I}\\DefineAs\n\\begin{pmatrix}\nI_1 & 0 & 0 \\\\ 0 & I_2 & 0 \\\\ 0 & 0 & I_3\n\\end{pmatrix}\n\\]\nwith $I_1 \\leq I_2 \\leq I_3$.\n\nEuler's equation $\\TimeDerivative{\\vm} = \\commutator{\\vm}{\\VectorSymbol{\\gw}}$ can be written in coordinates in the principal axes frame:\n\\[\n\\TimeDerivative{\\vm} =\n\\begin{pmatrix}\nm_1 \\\\ m_2 \\\\ m_3\n\\end{pmatrix}\n\\times\n\\begin{pmatrix}\nm_1/I_1 \\\\ m_2/I_2 \\\\ m_3/I_3\n\\end{pmatrix}\n\\]\nthus:\n\\begin{equation}\n\\begin{dcases}\n\\TimeDerivative{m}_1 &= m_2 m_3 \\pa{1/I_3 - 1/I_2}\\\\\n\\TimeDerivative{m}_2 &= m_3 m_1 \\pa{1/I_1 - 1/I_3}\\\\\n\\TimeDerivative{m}_3 &= m_1 m_2 \\pa{1/I_2 - 1/I_1}\n\\end{dcases}\n\\label{eqneuler}\n\\end{equation}\n\\section*{Solution of Euler's equation}\nThe solution of Euler's equation has three cases depending on the initial value of $\\vm$ (more precisely, on the sign of\n$\\gD_2 = m_1^2 \\frac{I_{12}}{I_1} + m_3^2 \\frac{I_{32}}{I_3}$, see discussion below).  Figure~\\ref{figm} illustrates the \npossible evolutions of $\\vm$. The sphere is the surface $\\norm\\vm = G$, which is an invariant of motion.  The planes are\nthe surfaces $\\gD_2 = 0$ and separate different modes of the motion.\nThe blue curve is called case (i) in \\cite{Celledoni2007}: $\\vm$ follows a periodic curve, and when that curve is close to the $m_1$\naxis we have a classical case of precession.  The red curve is case (ii), and again the motion of $\\vm$ is periodic and exhibits \nprecession when the curve remains close to the $m_3$ axis.  The green curve is case (iii): $\\vm$ takes an infinite amount\nof time to reach the point $\\tuple{0, G, 0}$; furthermore, the motion is unstable as any perturbation moves it either to\nthe blue or the red region where $\\vm$ oscillates between points close to $\\tuple{0, G, 0}$ and $\\tuple{0, -G, 0}$; this is \nthe Джанибеков effect.\n\\begin{figure}[htb!]\n\\centering\n\\includegraphics[scale=0.45]{Celledoni-m}\n\\caption{Possible trajectories of $\\vm$: the blue and red curves are cases (i) and (ii), respectively, and correspond to motion\nwith precession.  The green curve is the (unstable) case (iii) and any perturbation demonstrates the Джанибеков effect.\\label{figm}}\n\\end{figure}\n\nThe solutions may also be visualized by intersecting the sphere $\\norm\\vm = 1$ with ellipsoids defined by the value of the kinetic energy $T$,\nwhich is also a constant of motion.  Since $T = \\frac{G^2 - \\gD_2}{2 I_2}$, different values of $T$ determine the same modes as above.\n\\begin{figure}[htb!]\n\\centering\n\\includegraphics[scale=0.45]{Celledoni-G-T}\n\\caption{Possible trajectories of $\\vm$: the sphere is identical to that of Figure~\\ref{figm}.\nThe ellipsoids are surfaces of equal kinetic energy and intersect the sphere on the blue, red, and green curves depending on the\nvalue of $T$ .\\label{figGT}}\n\\end{figure}\n\nIn the rest of this section, we derive (corrected) formul{\\ae} for the three cases described above.\n\\subsection*{Case (i)}\nCase (i) of the solution of Euler's equation in section 2.2 of \\cite{Celledoni2007} is:\n\\[\n{\\vm}_t =\n\\begin{pmatrix}\n\\gs B_{13} \\JacobiDN\\of{\\gl t - \\gn, k} \\\\\n-B_{21} \\JacobiSN\\of{\\gl t - \\gn, k} \\\\\nB_{31} \\JacobiCN\\of{\\gl t - \\gn, k}\n\\end{pmatrix}\n\\]\nIf we derive this expression with respect to $t$, inject in into (\\ref{eqneuler}), and eliminate the elliptic functions we obtain:\n\\begin{equation}\n\\begin{dcases}\n-\\gs \\gl k^2 B_{13} &= -B_{21} B_{31} \\pa{1/I_3 - 1/I_2} \\\\\n-\\gl B_{21} &= \\gs B_{13} B_{31} \\pa{1/I_1 - 1/I_3} \\\\\n-\\gl B_{31} &= -\\gs B_{13} B_{21} \\pa{1/I_2 - 1/I_1}\n\\end{dcases}\n\\label{solneuleri}\n\\end{equation}\nThe last equation of (\\ref{solneuleri}) yields the following value for $\\gl$:\n\\begin{align*}\n\\gl &= \\gs \\frac{B_{13} B_{21}}{B_{31}} \\frac{I_1 - I_2}{I_1 I_2}\n= \\gs\\sqrt{\\frac{I_1 \\gD_3}{I_{13}} \\frac{I_2 \\gD_1}{I_{21}} \\frac{I_{31}}{I_3 \\gD_1}} \\frac{I_1 - I_2}{I_1 I_2} \\\\\n&= \\gs\\sqrt{\\frac{\\gD_3}{I_{21} I_1 I_2 I_3}} \\pa{I_1 - I_2}\n= -\\gs\\sqrt{\\frac{\\gD_3 I_{21}}{I_1 I_2 I_3}}\n= -\\gs \\gl_3\n\\end{align*}\nThe sign change when moving $I_1 - I_2$ under the radical is necessary because $I_1 - I_2 < 0$.\n\nIt is straightforward to check that this value of $\\gl$ also satisfies the other equations of (\\ref{solneuleri}).  Note that it\ndiffers in sign from the one given by \\cite{Celledoni2007}: the sign error is visible in that it does not yield the proper precession \ndirection.\n\n\\subsection*{Case (ii)}\nCase (ii) of the solution of Euler's equation in section 2.2 of \\cite{Celledoni2007} is:\n\\[\n{\\vm}_t =\n\\begin{pmatrix}\nB_{13} \\JacobiCN\\of{\\gl t - \\gn, k^{-1}} \\\\\n-B_{23} \\JacobiSN\\of{\\gl t - \\gn, k^{-1}} \\\\\n\\gs B_{31} \\JacobiDN\\of{\\gl t - \\gn, k^{-1}}\n\\end{pmatrix}\n\\]\nJust as we did above, we derive this expression with respect to $t$, inject in into (\\ref{eqneuler}), and eliminate the elliptic functions:\n\\begin{equation}\n\\begin{dcases}\n-\\gl B_{13} &= -\\gs B_{23} B_{31} \\pa{1/I_3 - 1/I_2} \\\\\n-\\gl B_{23} &= \\gs B_{13} B_{31} \\pa{1/I_1 - 1/I_3} \\\\\n-\\gs \\gl k^{-2} B_{31} &= -B_{13} B_{23} \\pa{1/I_2 - 1/I_1}\n\\end{dcases}\n\\label{solneulerii}\n\\end{equation}\nThe first equation of (\\ref{solneulerii}) yields the following value for $\\gl$:\n\\begin{align*}\n\\gl &= \\gs \\frac{B_{23} B_{31}}{B_{13}} \\frac{I_2 - I_3}{I_2 I_3}\n= \\gs\\sqrt{\\frac{I_2 \\gD_3}{I_{23}} \\frac{I_3 \\gD_1}{I_{31}} \\frac{I_{13}}{I_1 \\gD_3}} \\frac{I_2 - I_3}{I_2 I_3} \\\\\n&= \\gs\\sqrt{\\frac{\\gD_1}{I_{23} I_1 I_2 I_3}} \\pa{I_2 - I_3}\n= -\\gs\\sqrt{\\frac{\\gD_1 I_{23}}{I_1 I_2 I_3}}\n= -\\gs \\gl_1\n\\end{align*}\nAgain, note the change of sign due to the fact that $I_2 - I_3 < 0$.  And again, the same value of $\\gl$ can be shown to satisfy the other\nequations of (\\ref{solneulerii}).\n\n\\subsection*{Case (iii)}\nCase (iii) of the solution of Euler's equation in section 2.2 of \\cite{Celledoni2007} is clearly incorrect as it implies that $m_1$ and $m_3$\nalways have the same sign, whereas it is straightforward to choose initial conditions where they do not (because the separatrix is made of two\nplanes, see Figure~\\ref{figm}).  Instead, we introduce an extra parameter $\\gs'' = ±1$ and posit a solution of the form:\n\\[\n{\\vm}_t =\n\\begin{pmatrix}\n\\gs' B_{13} \\HyperbolicSecant\\of{\\gl t - \\gn} \\\\\n\\HyperbolicTangent\\of{\\gl t - \\gn} \\\\\n\\gs'' B_{31} \\HyperbolicSecant\\of{\\gl t - \\gn}\n\\end{pmatrix}\n\\]\nDeriving this expression and injecting it into (\\ref{eqneuler}) yields:\n\\begin{equation}\n\\begin{dcases}\n-\\gs' \\gl B_{13} &= \\gs'' B_{31} \\pa{1/I_3 - 1/I_2} \\\\\n\\gl &= \\gs' \\gs'' B_{13} B_{31} \\pa{1/I_1 - 1/I_3} \\\\\n-\\gs'' \\gl B_{31} &= \\gs' B_{13} \\pa{1/I_2 - 1/I_1}\n\\end{dcases}\n\\label{solneuleriii}\n\\end{equation}\nThe second equation of (\\ref{solneuleriii}) gives the following value for $\\gl$:\n\\[\n\\gl = \\gs' \\gs'' B_{13} B_{31} \\frac{I_3 - I_1}{I_1 I_3}\n= \\gs' \\gs'' \\sqrt{\\frac{I_1 \\gD_3}{I_{13}} \\frac{I_3 \\gD_1}{I_{31}}} \\frac{I_3 - I_1}{I_1 I_3}\n= \\gs' \\gs'' \\sqrt{\\frac{\\gD_1 \\gD_3}{I_1 I_3}}\n\\]\nIn this case it is a bit less obvious that the other equations yield the same value of $\\gl$.  We detail the derivation for the first equation,\nusing the fact that ${\\gs'}^2 = 1$:\n\\begin{align*}\n\\gl &= -\\gs' \\gs'' \\frac{B_{31}}{B_{13}} \\frac{I_2 - I_3}{I_2 I_3}\n= -\\gs' \\gs'' \\sqrt{\\frac{I_3 \\gD_1}{I_{31}} \\frac{I_{13}}{I_1 \\gD_3}} \\frac{I_2 - I_3}{I_2 I_3} \\\\\n&= -\\gs' \\gs'' \\sqrt{\\frac{\\gD_1}{I_1 I_3 \\gD_3}} \\frac{I_2 - I_3}{I_2}\n= \\gs' \\gs'' \\sqrt{\\frac{\\gD_1}{I_1 I_3 \\gD_3}} \\pa{\\frac{I_3}{I_2} - 1}\n\\end{align*}\nNow note that in case (iii) we have $2 T I_2 = 1$ thus $1/I_2 = 2 T$.  $\\gl$ can be rewritten as:\n\\[\n\\gl = \\gs' \\gs'' \\sqrt{\\frac{\\gD_1}{I_1 I_3 \\gD_3}} \\pa{2 T I_3 - 1} = \\gs' \\gs'' \\sqrt{\\frac{\\gD_1 \\gD_3}{I_1 I_3}}\n\\]\nwhere we have used the fact that $2 T I_3 - 1 = 2 T \\pa{I_3 - I_2} > 0$.\n\nWe then define:\n\\[\n\\gl_2 = \\sqrt{\\frac{\\gD_1 \\gD_3}{I_1 I_3}}\n\\]\nIt is easy to see that $\\gl_2$ is the common value of $\\gl_1$ and $\\gl_3$ in case (iii), that $\\gs'$ and $\\gs''$ are free parameters and that:\n\\[\n\\gl = \\gs' \\gs'' \\gl_2\n\\]\n\n\\subsection*{Phase and initial value}\nThe phase $\\gn$ and the free parameters $\\gs$, $\\gs'$ and $\\gs''$ are determined from the initial value ${\\vm}_0$ by setting $t = 0$.\n\\subsubsection*{Case (i)}\nWe have:\n\\[\n{\\vm}_0 =\n\\begin{pmatrix}\n\\gs B_{13} \\JacobiDN\\of{-\\gn, k} \\\\\n-B_{21} \\JacobiSN\\of{-\\gn, k} \\\\\nB_{31} \\JacobiCN\\of{-\\gn, k}\n\\end{pmatrix}\n\\]\nFirst, we set $\\gs$ to be the sign of $m_{01}$.  Then, forming the quotient of the last two coordinates we find:\n\\[\n\\frac{m_{02}}{m_{03}} = \\frac{B_{21}}{B_{31}}\\TrigonometricTangent\\of{\\JacobiAmplitude\\of{\\gn, k}}\n\\]\nthus:\n\\[\n\\InverseTrigonometricTangent\\of{\\frac{m_{02}}{m_{03}} \\frac{B_{31}}{B_{21}}} = \\JacobiAmplitude\\of{\\gn, k}\n\\]\nand finally we obtain $\\gn$ as:\n\\[\n\\gn = F\\of{\\InverseTrigonometricTangent\\of{\\frac{m_{02}}{m_{03}} \\frac{B_{31}}{B_{21}}}, k}\n\\]\n\n\\subsubsection*{Case (ii)}\nStarting from:\n\\[\n{\\vm}_0 =\n\\begin{pmatrix}\nB_{13} \\JacobiCN\\of{-\\gn, k^{-1}} \\\\\n-B_{23} \\JacobiSN\\of{-\\gn, k^{-1}} \\\\\n\\gs B_{31} \\JacobiDN\\of{-\\gn, k^{-1}}\n\\end{pmatrix}\n\\]\nwe set $\\gs$ to be the sign of $m_{03}$ and form the quotient of the first two coordinates.  We obtain:\n\\[\n\\frac{m_{02}}{m_{01}} = \\frac{B_{23}}{B_{13}} \\TrigonometricTangent\\of{\\JacobiAmplitude\\of{\\gn, k^{-1}}} \n\\]\nand for $\\gn$:\n\\[\n\\gn = F\\of{\\InverseTrigonometricTangent\\of{\\frac{m_{02}}{m_{01}} \\frac{B_{13}}{B_{23}}}, k^{-1}}\n\\]\n\n\\subsubsection*{Case (iii)}\nThe initial value ${\\vm}_0$  is:\n\\[\n{\\vm}_0 =\n\\begin{pmatrix}\n\\gs' B_{13} \\HyperbolicSecant\\of{-\\gn} \\\\\n\\HyperbolicTangent\\of{-\\gn} \\\\\n\\gs'' B_{31} \\HyperbolicSecant\\of{-\\gn}\n\\end{pmatrix}\n\\]\n$\\gs'$ and $\\gs''$ are set to be the signs of $m_{01}$ and $m_{03}$, respectively.  The second coordinate immediately gives:\n\\[\n\\gn = -\\InverseHyperbolicTangent\\of{m_{02}}\n\\]\n\n\\subsection*{Implementation considerations}\nSome of the formul{\\ae} given by \\cite{Celledoni2007} do not lend themselves to an easy implementation or lead to numerical inaccuracies.  We\ndescribe in this section the modifications we make to these formul{\\ae} in our implementation.  We also restore dimensionful formul{\\ae} as needed.\n\n\\subsubsection*{The quantity $I_{jh}$}\nIt is simpler and more efficient to avoid absolute values, so we define:\n\\[\nI_{jh} \\DefineAs I_j - I_h\n\\]\nThis is the same quantity as in \\cite{Celledoni2007} when $j \\geq h$ but it has the opposite sign (it is negative) when $j < h$\n\n\\subsubsection*{The quantity $\\gD_j$}\nWe notice that the computation of $\\gD_j$ may entail cancellations, so we go back to the definition of $\\norm{\\vm}$ and of the kinetic energy:\n\\[\n\\begin{dcases}\nG^2 &= m_1^2 + m_2^2 + m_3^2 \\\\\n2 T &= \\frac{m_1^2}{I_1} + \\frac{m_2^2}{I_2} + \\frac{m_3^2}{I_3}\n\\end{dcases}\n\\]\nand we define a dimensionful $\\gD_j$ without absolute values:\n\\[\n\\gD_j \\DefineAs G^2 - 2 T I_j\n\\]\nWhen, for instance, $j = 2$, this yields:\n\\begin{align*}\n\\gD_2 &= m_1^2 \\pa{1 - \\frac{I_2}{I_1}} + m_3^2 \\pa{1 - \\frac{I_2}{I_3}} \\\\\n&= m_1^2 \\frac{I_{12}}{I_1} + m_3^2 \\frac{I_{32}}{I_3}\n\\end{align*}\nand similarly:\n\\[\n\\begin{dcases}\n\\gD_1 &= m_2^2 \\frac{I_{21}}{I_2} + m_3^2 \\frac{I_{31}}{I_3} \\\\\n\\gD_3 &= m_1^2 \\frac{I_{13}}{I_1} + m_2^2 \\frac{I_{23}}{I_2}\n\\end{dcases}\n\\]\nIt is easy to see that $\\gD_1$ and $\\gD_3$ are the sums of terms of the same sign, so they can be computed without cancellations.  Furthermore,\n$\\gD_1 \\geq 0$ and $\\gD_3 \\leq 0$.  $\\gD_2$ can have either sign, which correspond exactly to cases (i) ($\\gD_2 < 0$), (ii) ($\\gD_2 > 0$) and \n(iii) ($\\gD_2 = 0$).\n\n\\subsubsection*{The elliptic modulus}\nFor the computation of the elliptic functions and integrals \\cite{Celledoni2007} gives the value of the elliptic modulus $k$ but we need the value of\nthe complementary parameter $m_c = 1 - m$ (see \\cite{NistHMF2010}, section 19.1.2 for an overview of the notation).  In case (i) we have:\n\\[\nm_c = 1 - k^2 = 1 + \\frac{\\gD_1 I_{32}}{\\gD_3 I_{21}}\n\\]\nwhere we have used $\\gD_3 \\leq 0$.  This can be rewritten as follows:\n\\begin{align*}\nm_c &= \\frac{\\gD_3 I_{21} + \\gD_1 I_{32}}{\\gD_3 I_{21}}\n=\\frac{\\pa{G^2 - 2 T I_3}\\pa{I_2 - I_1} + \\pa{G^2 - 2 T I_1}\\pa{I_3 - I_2}}{\\gD_3 I_{21}} \\\\\n&=\\frac{G^2\\pa{I_3 - I_1} + 2 T I_2\\pa{I_1 - I_3}}{\\gD_3 I_{21}}\n=\\frac{\\gD_2 I_{31}}{\\gD_3 I_{21}}\n\\end{align*}\n\nSimilarly, in case (ii):\n\\[\nm_c = 1 - k^{-2} = 1 + \\frac{\\gD_3 I_{21}}{\\gD_1 I_{32}}\n=\\frac{\\gD_1 I_{32} + \\gD_3 I_{21}}{\\gD_1 I_{32}}\n=\\frac{\\gD_2 I_{31}}{\\gD_1 I_{32}}\n\\]\nNote that in both cases we have $m_c \\geq 0$.\n\n\\subsubsection*{The dimensionful equations}\n$I_{jh}$ has the physical dimension of an inertial momentum $L^2 M$.  $G$ has the dimension of an angular momentum $L^2 M T^{-1} A$.  $\\gD_j$ has \nthe same dimension as $G^2$.  $B_{jh}$ has the same dimension as $\\sqrt{\\gD_h}$, i.e., the same dimension as $G$.  $\\gl_1$ and $\\gl_3$ have the\nsame dimension as the quotient $\\frac{G}{I_j}$, i.e., $T^{-1} A$ which is appropriate for their usage.\n\nThis analysis shows that most of the formul{\\ae} in \\cite{Celledoni2007} have proper physical dimensions, expect for the $1$ in the definition of\n$\\gD_j$ (which should be $G^2$) and for the second coordinate of $\\vm$ in case (iii) which should be:\n\\[\nm_{2t} = G \\HyperbolicTangent\\of{-\\gn}\n\\]\nWith this adjustment we obtain the dimensionful formul{\\ae}:\n\\begin{align*}\n\\gn &= -\\InverseHyperbolicTangent\\of{\\frac{m_{02}}{G}} \\\\\n\\gl_2 &= \\frac{1}{G} \\sqrt{\\frac{\\gD_1 \\gD_3}{I_1 I_3}}\n\\end{align*}\nIt is easy to verify that the argument of the $\\InverseHyperbolicTangent$ is dimensionless and that $\\gl_2$ has the same dimension as the quotient \n$\\frac{\\gD_j}{G I_j}$, which has the same dimension as $\\frac{G}{I_j}$, namely, $T^{-1} A$.\n\\printbibliography\n\\end{document}", "meta": {"hexsha": "2fbd5757e792b2363f2a413357ad0ecb5f8cc918", "size": 15181, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "documentation/Celledoni.tex", "max_stars_repo_name": "tnuvoletta/Principia", "max_stars_repo_head_hexsha": "25cf2fb70c512cf86a842ed525f6ab10e57f937c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-02-23T19:32:16.000Z", "max_stars_repo_stars_event_max_datetime": "2015-04-07T03:55:53.000Z", "max_issues_repo_path": "documentation/Celledoni.tex", "max_issues_repo_name": "tnuvoletta/Principia", "max_issues_repo_head_hexsha": "25cf2fb70c512cf86a842ed525f6ab10e57f937c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "documentation/Celledoni.tex", "max_forks_repo_name": "tnuvoletta/Principia", "max_forks_repo_head_hexsha": "25cf2fb70c512cf86a842ed525f6ab10e57f937c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.8209366391, "max_line_length": 159, "alphanum_fraction": 0.6730781898, "num_tokens": 5885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166195971441, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.3259792447307847}}
{"text": "﻿\\documentclass[11pt]{article}\n\\usepackage{cite}\n\\usepackage{pgf}\n\\usepackage{tikz}\n\\usepackage{amsmath,amssymb}\n\\usepackage{amsthm}\n\\usepackage{url}\n\\usepackage{hvorost}\n\n\\begin{document}\n\n\\title{Computing All Pure Squares in Compressed Texts}\n\\author{L. Khvorost\\thanks{The author acknowledges support from the Federal\nEducation Agency of Russia, grant  2.1.1/3537.}\\\\\nUral State University\\\\\njaamal@mail.ru}\n\\date{}\n\\maketitle\n\n\\begin{abstract}\nA square $xx$ is called pure if $x$ is a primitive string. We consider the problem of computing all pure squares\nin a string represented by a straight-line program (SLP). An instance of the problem is an SLP $\\slp{S}$ that\nderives some string $S$ and we seek a solution in the form of a table that contains information about all pure\nsquares in $S$ in a compressed form. We present an algorithm that solves the problem in $O(|\\slp{S}|^4\\cdot\n\\log^2{|S|})$ time and requires $O(|\\slp{S}|\\cdot \\max\\{ |\\slp{S}|, \\log{|S|}\\})$ space, where $|\\slp{S}|$\n(respectively $|S|$) is the size of the SLP $\\slp{S}$ (respectively the length of the string $S$).\n\\end{abstract} \n\n\\section{Introduction}\n\nVarious compressed representations of strings are known: straight-line programs (SLPs) \\cite{14,15,16,18},\ncollage-systems \\cite{12}, string representations using antidictionaries \\cite{13}, etc. Nowadays text compression\nbased on context-free grammars such as SLPs attracts much attention. The reason for this is not only that grammars\nprovide well-structured compression but also that the SLP-based compression is in a sense polynomially equivalent\nto the compression achieved by the Lempel-Ziv algorithm that is widely used in practice. It means that, given a\ntext $S$, there is a polynomial relation between the size of an SLP that derives $S$ and the size of the\ndictionary stored by the Lempel-Ziv algorithm \\cite{18}.\n\nWhile compressed representations save storage space, there is a price to pay: some classical problems on strings\nbecome computationally hard when one deals with compressed data and measures algorithms' speed in terms of the\nsize of compressed representations. As examples we mention here the problems \\textbf{Hamming distance} \\cite{15} and\n\\textbf{Literal shuffle} \\cite{4}. On the other hand, there exist problems that admit algorithms working rather well on\ncompressed representations: \\textbf{Pattern matching} \\cite{15, 10}, \\textbf{Longest common substring} \\cite{16}, \n\\textbf{Computing all palindromes} \\cite{16}. This dichotomy gives rise to the following research direction: to\nclassify important string problems by their behavior with respect to compressed data.\n\nThe \\textbf{Computing All Squares} (\\textbf{CAS}) problem is a well-known problem on strings. It is of importance, for\nexample, in molecular biology. (We just mention in passing that the story of origin and migration of mice on the\nEurasia continent was restored thanks to information on squares in DNA sequences in mouse genome \\cite{19}.) It is\nnot yet known whether or not \\textbf{CAS} admits an algorithm polynomial in the size of a compressed representation\nof a given text.\\footnote{A polynomial algorithm that solves \\textbf{CAS} for strings represented by Lempel-Ziv\nencodings was announced in~\\cite{8}. This representation is slightly more general than that by SLPs. However no\ndetails of the algorithm have ever been appeared.} In general, a string can have exponentially many squares with\nrespect to the size of its compressed representation. For example, the string $a^n$ has $\\Theta(n^2)$ squares,\nwhile it is easy to build an SLP of size $O(\\log n)$ that derives $a^n$. So we must store information about\nsquares in a compressed form. Also this implies that we cannot search for squares consecutively by moving from one\nsquare to the ``next'' one. Squares should be somehow grouped in relatively large families that are to be\ndiscovered at once. So far we are able to overcome these difficulties for pure squares only.\n\nA string $x$ is \\emph{primitive} if $x = u^k$ for some integer $k$ implies that $k = 1$ and $u = x$. A \\emph{pure}\nsquare is a square $xx$ where $x$ is primitive. Otherwise, $xx$ is called a \\emph{repetition}. We formulate the \\textbf{\nComputing all pure squares} problem in terms of SLPs as follows:\n\n\\problem{CAPS}{an SLP $\\slp{S}$ that derives some text $S$;}{a data structure (a PS-table) that contains\ninformation about all pure squares in $S$ in a compressed form.}\n\nObserve that restricting to pure squares by no means makes the problem easy: the difficulties mentioned above\npersist for pure squares. Indeed, the same string $a^n$ has $n-1$ pure squares, thus exponentially many with\nrespect to the size of its compressed representation.\n\nLet us describe in more detail the content of the present paper and its structure. Section~2 gathers some\npreliminaries about SLPs. In Section~3 we present some basic operations over SLPs widely used in paper. In\nSection~4 we present two algorithms. The first algorithm, given an SLP $\\slp{S}$, checks whether or not the text\n$\\slp{S}$ generates is square free. (A polynomial algorithm for testing square-freeness of a compressed text has been\nrecently developed in~\\cite{new} but only for the special case of SLPs, in which the parse tree of the text is\nbalanced.) The second algorithm, given SLP $\\slp{S}$, fills out the corresponding PS-table. Both algorithms use time\nand space resources that depend polynomially on the size of $\\slp{S}$ and logarithmically on the size of the text\ngenerated by $\\slp{S}$. Our algorithms closely follows the approach from~\\cite{2} where an efficient solution\nto \\textbf{CAS} for non-compressed strings has been proposed and we reproduce the key lemmas from~\\cite{2} for the reader's\nconvenience. Also in Section~4 we discuss functionality of PS-tables and list several problems that can be easily solved\nwhenever a PS-table is available. In Section~5 we summarize our results. Appendix A contains illustrative examples.\n\n\\section{Preliminaries}\n\nWe consider strings of characters from a fixed finite alphabet $\\Sigma$. The \\emph{length} of a string $S$ is the number\nof its characters and is denoted by $|S|$. The \\emph{concatenation} of strings $S_1$ and $S_2$ is denoted by $S_1 \\cdot\nS_2$.  A \\emph{position} in a string $S$ is a point between consecutive characters. We number positions from left to \nright by $1,2,\\dots,|S|-1$. It is convenient to consider also the position 0 preceding the text and the position $|S|$ \nfollowing it. For a string $S$ and an integer $i (0 \\leq i \\leq |S|)$ we define $S[i]$ as character between positions\n$i$ and $i+1$ of $S$. For example $S[0]$ is a first character of $S$. A \\emph{substring} of $S$ starting at a position\n$\\ell$  and ending at a position $r$, $0\\leq \\ell < r \\leq |S|$, is denoted by $S[\\ell \\dots r]$ (in other words \n$S[\\ell \\dots r] = S[\\ell] \\cdot S[\\ell + 1] \\cdot \\mbox{\\dots} \\cdot S[r-1]$). We say that a substring $S[\\ell \\dots\nr]$ \\emph{touches} some position $t$ if $\\ell \\leq t \\leq r$. The position $|x|$ of a square $xx$ is called the\n\\emph{center} of $xx$ and $x$ is referred to as the \\emph{root} of $xx$.\n\nA \\emph{straight-line program} (SLP) $\\slp{S}$ is a sequence of assignments of the form:\n\n\\begin{center}\n$\\slp{S}_1 = expr_1,\\ \\slp{S}_2 = expr_2, \\dots, \\slp{S}_n = expr_n,$\n\\end{center}\nwhere $\\slp{S}_i$ are \\emph{rules} and $expr_i$ are expressions of the form:\n\\begin{itemize}\n\\item $expr_i$ is a symbol of $\\Sigma$ (we call such rules \\emph{terminal}), or\n\\item $expr_i = \\slp{S}_\\ell\\cdot \\slp{S}_r \\ (\\ell, r < i)$ (we call such rules \\emph{nonterminal}).\n\\end{itemize}\n\nThus, an SLP is a context-free grammar in Chomsky normal form. Every SLP $\\slp{S}$ generates exactly one string\n$S\\in\\Sigma^+$ and we refer to it as the \\emph{text} generated by $\\slp{S}$.\n\n{\\bf Example}: The following SLP $\\slp{F}_7$ generates the 7-th Fibonacci word $F_7$= \\emph{a~b~a~a~b~a~b~a~a~b~a~a~b}:\n\\begin{center}\n$\\slp{F}_1 = a,\\ \\slp{F}_2 = b,\\ \\slp{F}_3 = \\slp{F}_1\\cdot \\slp{F}_2,\\ \\slp{F}_4 = \\slp{F}_3\\cdot \\slp{F}_1,$\n\n$\\slp{F}_5 = \\slp{F}_4\\cdot \\slp{F}_3,\\ \\slp{F}_6 = \\slp{F}_5\\cdot \\slp{F}_4,\\ \\slp{F}_7 = \\slp{F}_6\\cdot\n\\slp{F}_5$;\n\\end{center}\n\nWe accept the following conventions in the paper: every SLP is denoted by a capital blackboard bold letter, for\nexample, $\\slp{S}$. Every rule of this SLP is denoted by the same letter with indices, for example,\n$\\slp{S}_1,\\slp{S}_2,\\dots$. The text that is derived from a rule is denoted by the same indexed capital letter in\nthe standard font, for example, the text that is derived from $\\slp{S}_i$ is denoted by $S_i$. \n\nThe \\emph{size} of an SLP $\\slp{S}$ is the number of its rules and is denoted by $|\\slp{S}|$. The \\emph{concatenation}\nof SLPs $\\slp{S}_1$ and $\\slp{S}_2$ is an SLP that derives $S_1 \\cdot S_2$ and denoted by $\\slp{S}_1 \\cdot \\slp{S}_2$. \nThe \\emph{cut position} of a nonterminal rule $\\slp{S}_i = \\slp{S}_\\ell\\cdot \\slp{S}_r$ is the position $|S_\\ell|$ in\nthe text $S_i$. For instance, the cut position of $\\slp{F}_4$ in the example in Figure~1 is equal to~2. For every\nterminal rule we define its cut position to be equal to~0.\n\n\\begin{figure}[t]\n\t\\FibonacciWordSLP\n\\end{figure}\n\n\\section{Basic operations}\n\nIn this section we present some basic operation over SLPs widely used in the paper. \n\n\\subsection{Subgrammar cutting}\n\n\\problem{SubCut}{an SLP $\\slp{S}$ that derives text $S$ and $0 \\leq \\ell < r \\leq |\\slp{S}| $ are integers;}{an SLP\n$\\slp{S}\\substr{\\ell}{r}$ that derives text $S\\substr{\\ell}{r}$;}\n\n\\noindent {\\sc Algorithm:} The algorithm descends from the root of $\\slp{S}$ to a son that touches both positions $\\ell$\nand $r$ while it finds a rule $\\slp{S}'$ such that $\\slp{S}'$ is a terminal rule or a nonterminal rule that left son\ntouches only $\\ell$ and right son touches only $r$. Notice that original values of $\\ell$ and $r$ may change during the\nprocess. If $\\slp{S}'$ is a terminal rule then the algorithm returns $\\slp{S}'$. Let $\\slp{S}' = \\slp{L} \\cdot \\slp{R}$\nbe a nonterminal rule and $\\gamma$ be a cut position of $\\slp{S}'$. The algorithm decompose $\\slp{L}$ into rules\n$\\slp{L}_p, \\dots, \\slp{L}_1 \\in \\slp{L}$ such that $\\slp{L}_p \\cdot \\mbox{\\dots} \\cdot \\slp{L}_1$ derives\n$S\\substr{\\ell}{\\gamma}$ and decompose $\\slp{R}$ into rules $\\slp{R}_1, \\dots, \\slp{R}_q \\in \\slp{R}$ such that\n$\\slp{R}_1 \\cdot \\mbox{\\dots} \\cdot \\slp{R}_q$ derives $S\\substr{\\gamma}{r}$. At Figure 2 presented pseudo code that\nillustrate how the algorithm obtains $\\slp{L}_p, \\dots, \\slp{L}_1$. The set of rules $\\slp{R}_1, \\dots, \\slp{R}_q$ obtains similarly.\n\n\\SubCutPseudoCode\n\nFinally the algorithm concatenates two set of rules into a single SLP in the following order: $$\\slp{L}_p \\cdot\n(\\slp{L}_{p-1} \\cdot \\mbox{\\dots} \\cdot (\\slp{L}_1 \\cdot (\\slp{R}_1 \\cdot \\mbox{\\dots} \\cdot (\\slp{R}_{q-1} \\cdot\n\\slp{R}_q) ) ) ).$$\n\n\\noindent \\textsc{Complexity:} To find a rule $\\slp{S}'$ the algorithm descends along a path between the root of\n$\\slp{S}$ and some leaf of $\\slp{S}$ at worst case, so the algorithm needs $O(|\\slp{S}|)$ time. To decompose $\\slp{L}$\ninto rules $\\slp{L}_p, \\dots, \\slp{L}_1$ the algorithm descends along a path between the root of $\\slp{L}$ and some leaf\nof $\\slp{L}$ at worst case, so the algorithm needs $O(|\\slp{L}|)$ time. Similarly the algorithm needs $O(|\\slp{R}|)$ time\nto decompose $\\slp{R}$ into rules $\\slp{R}_1, \\dots, \\slp{R}_q$. Altogether there is algorithm that solves\n\\textbf{SubCut} problem using $O(|\\slp{S}|)$ time and $O(|\\slp{S}|)$ space.\n\n\\subsection{Pattern matching}\n\n\\problem{PM}{SLP's $\\slp{S}, \\slp{T}$ such that $|S| \\leq |T|$;}{$O(|\\slp{T}|)$ arithmetic progressions that describe\nstart positions of all occurrences $S$ in $T$;}\n\n\\begin{thm}[{\\rm\\cite{15}}]\nThere is algorithm that solves \\textbf{PM} problem using $O(|\\slp{T}|^2|\\slp{S}|)$ time and $O(|\\slp{T}||\\slp{S}|)$\nspace.\n\\end{thm}\n\n\\subsection{Substrings extending}\n\n\\problem{SubsExt}{an SLP $\\slp{S}$ and integers $\\ell_1, r_1, \\ell_2, r_2 (0 \\leq \\ell_1 < r_1 \\leq |\\slp{S}|, 0 \\leq\n\\ell_2 < r_2 \\leq |\\slp{S}|)$ such that $S\\substr{\\ell_1}{r_1} = S\\substr{\\ell_2}{r_2}$;}{integers $\\ell_{ex}$ and \n$r_{ex}$, where $\\ell_{ex}$ is the length of the longest common suffix of $S\\substr{1}{r_1}$ and $S\\substr{1}{r_2}$,\n$r_{ex}$ is the length of the longest common prefix of $S\\substr{\\ell_1}{|S|}$ and $S\\substr{\\ell_2}{|S|}$;}\n\n\\vspace{2pt}\n\n\\noindent \\textsc{Algorithm:} The algorithm obtains $r_{ex}$ by induction.\n\n\\vspace{2pt}\n\n\\noindent \\textsc{Base:} The algorithm set $r_{ex}$ is equal to $\\min \\{|S| - r_1, |S| - r_2\\}$. Using \\textbf{SubCut}\nproblem the algorithm constructs $\\subslp{S}{r_1}{r_1 + r_{ex}}$ and $\\subslp{S}{r_2}{r_2 + r_{ex}}$.  Next it runs\n\\textbf{PM} problem with the SLPs as input. If the result set is not empty then algorithm stops. Otherwise it sets\n$step = \\lfloor \\frac{r_{ex}}{2} \\rfloor$ and $r_{ex} = 0$.\n\n\\vspace{2pt}\n\n\\noindent \\textsc{Step:} Using \\textbf{SubCut} problem the algorithm constructs $\\subslp{S}{r_1}{r_1 + r_{ex} + step}$\nand $\\subslp{S}{r_2}{r_2 + r_{ex} + step}$.  Next it runs \\textbf{PM} problem with the SLPs as input. If the result set\nis not empty then the algorithm sets $r_{ex} = r_{ex} + step$ and $step = step + \\lceil \\frac{step}{2} \\rceil$.\nOtherwise it sets $step = step - \\lceil \\frac{step}{2} \\rceil$.\n\nThe algorithm obtains $\\ell_{ex}$ analogously.\n\n\\vspace{2pt}\n\n\\noindent \\textsc{Complexity:} There are $O(\\log |S|)$ steps. At each step the algorithm runs \\textbf{SubCut} problem\ntwo times and \\textbf{PM} problem one time. Totally it needs $O(|\\slp{S}|^3)$ time and $O(|\\slp{S}|^2)$ space for each\nstep. Altogether there is algorithm that solves \\textbf{SubsExt} problem $O(|\\slp{S}|^3 \\log|S|)$ time and \n$O(|\\slp{S}|^2)$ space.\n\nUsing \\textbf{SubsExt} problem we can easy solve the following problem:\n\n\\problem{Period termination}{an SLP $\\slp{S}$, an integer $p > 0$ and positions $0 \\leq \\ell < r \\leq |\\slp{S}|$ such that\n$S\\substr{\\ell}{r}$ is $p$-periodic substring;}{$t_L, t_R$ are positions in the text $S$ where $p$-periodicity of\n$S\\substr{\\ell}{r}$ terminates from the left and from the right correspondingly;}\n\n\\vspace{2pt}\n\n\\noindent \\textsc{Algorithm:} Using \\textbf{SubCut} problem the algorithm constructs SLP $\\slp{P}$ that derives\n$S\\substr{\\ell}{\\ell + p}$. Let $k$ be an odd integer that $p^k > |S|$. Using $\\Theta(\\log k)$ time the algorithm constructs\nSLP $\\slp{P}^k$ that derives $S\\substr{\\ell}{\\ell+p}^k$. Finally it runs \\textbf{SubsExt} problem with the following parameters:\n$\\slp{S} \\cdot \\slp{P}^k$, $\\ell_1 = \\ell, r_1 = r, \\ell_2 = |S| + p \\cdot \\frac{k-1}{2}, r_2 = |S| + p \\cdot \\frac{k-1}{2} + (r\n- \\ell)$.\n\n\\vspace{2pt}\n\n\\noindent \\textsc{Complexity:} The algorithm runs \\textbf{SubCut} problem one time. Next it spends $\\log k \\leq \\log\n|S|$ operations to construct $\\slp{P}^k$. Finally in runs \\textbf{SubsExt} problem one time. Altogether there is\nalgorithm that solves \\textbf{Period termination} problem using $O(|\\slp{S}|^3 \\log|S|)$ time and\n$O(|\\slp{S}|^2)$ space.\n\n%TODO move to SAPS algorithm section\n\\subsection{Purity check}\n\n\\problem{Purity check}{an integer $p > 0$ and an SLP $\\slp{S}$ such that $|S| \\geq 2p$ and for every position $c \\in\n\\overline{p \\dots |S| - p}$ $S\\substr{c-p}{c+p}$ is a repetition;}{\\textbf{true}, if all the\nrepetitions are pure squares, otherwise \\textbf{false};}\n\n\\begin{lem}[{\\rm\\cite{2}}]\nA family of repetitions contains a pure square if and only if all the repetitions in the family are pure squares.\n\\end{lem}\n\nIf square $xx$ is not pure then $x$ contains at least one pure square. It follows form definition of pure square. To\nsolve \\textbf{Purity check} problem enough to check whether exists pure square that belongs to $S\\substr{\\ell - |x|}{\\ell}$. \n\nSketch: \n\nThe algorithm starts from root of $\\slp{S}$ and recursively goes down in parse tree of $\\slp{S}$. \n\n\\section{The algorithm}\n\n\\subsection{Idea of pure squares location}\n\nLet us fix a rule $\\slp{S}_j = \\slp{S}_l \\cdot \\slp{S}_r$ and its cut position $\\gamma$. There exists a number\n$i_0$ such that $2^{i_0} \\geq \\max\\{|S_l|, |S_r|\\}$. Let us fix a number $i \\in \\{ 1, \\dots, i_0 \\}$. So for\nevery pair $(j, i)$ the algorithm looks for the following set of pure squares: $\\{xx \\ | \\ |x| \\in\n[2^{i-1}, 2^i-1] \\mbox{ and $xx$ touches $\\gamma$}\\}$.\n\n\\noindent \\textsc{Correctness:} Let us show that the algorithm doesn't miss any pure square by contradiction. Let $xx$\nbe a pure square that was not found using the search algorithm. Let $\\ell, r$ be left and right position of $xx$ in the\ntext $S$. Using $O(|\\slp{S}|)$ time we can obtain a rule $\\slp{S}_j$ that $S_j$ fully contains $xx$ and $xx$ touches cut\nposition of $\\slp{S}_j$ (just walk down from root of $\\slp{S}$ while not found a first rule that cut position is in\n$[\\ell, r]$). There exist number $i$ that $|x| \\in [2^{i-1}, 2^i-1]$. Since $xx$ touches $\\gamma$ and $|xx| < 2^{i+1}$ \nthen $xx$ belongs to $2^{i+1}$-environment of $\\gamma$. So we have contradiction with condition that for fixed rule \n$\\slp{S}_j$ and number $i$ we able to found all pure squares.\n\n\\subsection{Idea of local search}\n\nLet partition the $2^{i+1}$-environment of $\\gamma$ into 16 text blocks of equal length. Thus the length of each\nblock is $2^{i-2}$. Partition starts from $\\gamma$ so leftmost and rightmost blocks in the partition may have\nlength less than $2^{i-2}$. Let us enumerate the blocks from $B_1$ to $B_{16}$. Notice centers of pure squares\nshould locate at blocks from $B_5$ to $B_{12}$ otherwise we get contradiction with length of pure square or\ntouching $\\gamma$.\n\nLet $c$ be center of a pure square $xx$ and it belongs to one of the eight blocks $B_k$. Since $|x| \\geq 2^{i-1}$\nthen $xx$ should contain at least three consecutive blocks $B_{k-1}, B_{k}$ and $B_{k+1}$. For example, let $c$\nbelong to block $B_7$ then $xx$ must contains blocks $B_6$ and $B_8$. Let us fix $B_{k-1}$. Using pattern matching\nalgorithm we able to find all occurrences of $B_{k-1}$ in $B_{k+1}\\cdot B_{k+2}$. Next the algorithm take pair of\nblocks ($B_{k-1}$ and its occurrence in $B_{k+1}\\cdot B_{k+2}$) and extend both to check whether or not they form\na square.\n\n\\noindent \\textsc{Correctness:} Let us show correctness of the idea by contradiction. Let $xx$ be a pure square that\nfully contains in $S_j$, touches $\\gamma$ and $|x| \\in [2^{i-1}, 2^i-1]$. Suppose $xx$ was not found using the search\nalgorithm. Let $c$ be a center of $xx$. If $c$ not belong to blocks from $B_5$ to $B_{12}$ then we have contradiction\nas shown above. Let $c$ belong to block $B_k$ where $k\\in \\{ 5, \\dots, 12 \\}$. If two adjacent blocks of $B$ not\nbelong to $xx$ then we have contradiction with length of $xx$. Since $|x| \\geq 2^{i-1}$ then $xx$ contains at least\nthree consecutive blocks of the partition. Let $B_{k-1}$ is one of two adjacent blocks. If start position of occurrence\nof $B_{k-1}$ belong to $B_k$ then $|x| < 2\\cdot 2^{i-2} < 2^{i-1}$ that contradicts with $|x| \\in [2^{i-1},2^i-1]$. If\nstart position of occurrence of $B_{k-1}$ belong to $B_{k+3}$ (or even greater) then $|x| > 4\\cdot 2^{i-2} > 2^i-1$\nthat contradicts with $|x| \\in [2^{i-1},2^i-1]$ also. Otherwise we have contradiction with condition that we able to\nfind all pure squares between a block and its occurrences in some area.\n\n\\subsection{Square-freeness problem}\n\n\\problem{Square-freeness}{an SLP $\\slp{S}$ that derives text $S$;}{Whether or not $S$ is square-free?}\n\nThe following lemma is helpful for solving square-freeness problem:\n\n\\begin{lem}[{\\rm\\cite{2}}]\nAssume that the period of a string $B$ is $p$. If $B$ occurs only at positions $p_1 < p_2 < \\dots < p_k$ of a text\n$S$ and $p_k - p_1 \\leq \\frac{|B|}{2}$ then the $p_i$'s form an arithmetic progression with difference $p$.\n\\end{lem}\n\n\\SquareFreenessCode\n\nSo for every block $B_{k-1}$ we obtain all occurrences of $B_{k-1}$ in $B_{k+1}\\cdot B_{k+2}$. From the lemma\nabove follows that we can represent all occurrences using four arithmetic progressions. Therefore we need to check\nwhether on not block $B_{k-1}$ and progression $\\prog{a}{p}{t}$ of its occurrences form a square? We propose the following\nalgorithm for the check:\n\n\\begin{itemize}\n\\item If $t = 0$ then there are no squares. The algorithm moves to the next block;\n\n\\item If $t = 1$ then we obtain $\\ell_{ex}$, $r_{ex}$ using \\textbf{SubsExt} problem for $B_{k-1}$ and $S_j[a\\dots a +\n2^{i-2}]$. If $\\ell_{ex} + r_{ex} > a - (k-1)\\cdot 2^{i-2}$ then there exist at least one square and the  algorithm returns\n$\\bf{false}$. Otherwise there are no squares and the algorithm moves to the next block;\n\n\\item If $t \\geq 2$ there exists at least one square. The algorithm returns $\\bf{false}$. \n\\end{itemize}\n\nPseudo code for square-freeness checking presented at figure 3.\n\n\\begin{thm}\nThere is algorithm that solves square-freeness problem using $O(|\\slp{S}|^4\\cdot \\log^2{|S|})$ time and $O(|\\slp{S}|^2)$ space.\n\\end{thm}\n\n\\subsection{PS-table}\n\nThe \\emph{pure squares table} (PS-table) is a rectangular table $PS(\\slp{S})$ that stores information about all pure\nsquares in the text in a compressed form. The size of $PS(\\slp{S})$ is equal to $(\\lfloor\\log |S|\\rfloor+1) \\times\n(|\\slp{S}|+1)$. It is convenient to start numbering of rows and columns of PS-tables with 0. We denote the cell in\nthe $i$-th row and $j$-th column of table by $PS(i,j)$. The cell $PS(0,0)$ is always left blank. The cells $PS(0,j)$\nwith $j>0$ contain the rules of the SLP $\\slp{S}$ ordered such that the lengths of the texts they derive increase. (If some\nrules derive texts of the same length then the rules are listed in an arbitrary but fixed order). Thus, the first cells \nof the 0-th row contain terminal rules followed by rules that derive texts of length~2, etc.  The cells $PS(i,0)$ with\n$i>0$ contain segments $[2^{i-1}, 2^i - 1]$. In every cell $PS(i, j)$ with $i,j>0$, we shall store information about\nfamilies of pure squares. There exist three types of stored families:\n\n\\begin{itemize}\n  \\item empty family (stored as $\\emptyset$);\n  \\item family of pure squares with fixed root length (stored using triple $\\{|x|, c_l, c_r \\}$ where $|x|$ is length\n  of root, $c_l$ is center position of leftmost pure square in $\\slp{S}_j$, $c_r$ is center position of rightmost pure\n  square in $\\slp{S}_j$);\n  \\item family of pure squares with float root length;\n\\end{itemize}\n\nThe reader may wish to look at the example of the PS-table for the SLP $\\slp{F}_7$ in Appendix~A in which all square\nfamilies has fixed root length.\n\nOnce a PS-table is constructed, it is easy to solve the following problems:\n\n\\begin{itemize}\n  \\item to find information about all pure squares of fixed length;\n  \\item to compute the number of pure squares that are contained in $S$.\n\\end{itemize}\n\nMore complicated questions also can be answered. For instance, suppose we are given SLPs $\\slp{S}$ and $\\slp{P}$ such\nthat $\\slp{P}$ derives a pure square $xx$. The question is whether or not $xx$ occurs in the text $S$?\n\nSketch of algorithm:\n\nThe algorithm computes length of $xx$ using $O(|\\slp{P}|)$ time. Next it find a row of the PS-table such that\n$2^{i-1} < |x| < 2^i$ using $O(\\log{|S|})$ time. Finally the algorithm checks whether $xx$ belongs to a family encoded\nin any cell of the row. Obviously the algorithm skip empty families. The following cases are remained to be\nconsidered:\n\n\\begin{itemize}\n  \\item the algorithm process the following family: $\\{|y|, c_l, c_r\\}$. If $|x| \\neq |y|$ then the algorithm moves to\n  the next family. Otherwise it take subgrammar $\\slp{S}\\substr{c_l - |x|}{c_r + |x|}$ using $O(|\\slp{S}|)$ time and run\n  pattern matching algorithm on $\\slp{S}\\substr{c_l - |x|}{c_r + |x|}$ and $\\slp{P}$ using $O(|\\slp{P}|^3)$ time.\n  \\item the algorithm process the following family: $k, \\prog{a}{p}{t}, \\alpha_L, \\alpha_R, \\gamma_L, \\gamma_R$. If\n  there is no integer $t' \\in \\overline{0 \\dots t}$ such that $t' = \\frac{|x| - a + (k-1) \\cdot 2^{i-2} }{p}$ or $|x|\n  \\geq \\min(\\alpha_R -\\alpha_L, \\gamma_R - \\gamma_L)$ then the algorithm moves to the next family. Otherwise the\n  family reduced to family with fixed root length $\\{|x|, \\max(\\alpha_L + |x|, \\gamma_L) + 1, \\min(\\alpha_R,\n  \\gamma_R - |x|)\\}$ and processed as shown above.\n\\end{itemize}\n\nIf the algorithm find match at some family then it immediately stops and return \\textbf{true}. If the algorithm find no\nmatch checking all families in the row then it return \\textbf{false}.\n\nIn the worst case we need $O(\\max\\{ |\\slp{S}|, \\log |S|\\} \\cdot |\\slp{P}|^3)$ time. Moreover, we can modify the\nalgorithm to save information about all occurrences of $xx$ in $S$. Clearly, the general pattern matching algorithm also\nsolves these problem, but it needs $O(|\\slp{P}||\\slp{S}|^2)$ time. Therefore using information from the PS-table will be\nmore effective if $|\\slp{S}|$ much larger than $|\\slp{P}|$. \n\nAnother natural problem is the following. Let an SLP $\\slp{S}$ derive the text $S$ and let a position $i$ be fixed.\nThe problem is to construct an SLP that derives all pure squares starting from the position $i$ in $S$. (Since by the\ndefinition each SLP derives only one string, we mean here an SLP that derives a string consisting of all pure squares\nin question separated by a new symbol.)  Altogether there are $O(\\log|\\slp{S}|)$ rules that contain $i$.\n\n\\begin{lem}[{\\rm\\cite{11}}]\nIf there are three squares $xx, yy, zz$ with $|x| < |y| < |z|$ that start at the same position of some string, then $|x|\n+ |y| \\leq |z|$.\n\\end{lem}\n\nThe lemma implies that for every interval of lengths there exist at most two squares starting from an arbitrary\nposition. Therefore altogether there are $O(|\\slp{S}|)$ pure squares starting at a particular position. So we can\ngather information about all pure squares in an explicit form. We can build an SLP that derives all pure squares\nstarting in a particular position in $O(|\\slp{S}|^2)$ time using the substring taking algorithm.\n\n\\subsection{Searching all pure squares problem}\n\nRemind the main problem:\n\n\\problem{Searching all pure squares}{an SLP $\\slp{S}$ that derives text $S$;}{a compressed presentation of all\npure squares in $S$;}\n\nTo solve the problem remain to recognize all pure squares between a block $B_k$ and an arithmetic progression\n$\\prog{a}{p}{t}$ of its occurrences. Since $t$ can be exponentially large relative to $|\\slp{S}|$ the algorithm\ncannot consecutively check every occurrence of $B_k$.\n\nLet $\\alpha_L, \\alpha_R$ be output of \\textbf{Period termination} problem for $\\slp{S}_j, B_k =\nS_j\\substr{(k-1)\\cdot2^{i-2}}{k\\cdot 2^{i-2} -1}$. $\\alpha_L, \\alpha_R$ called \\emph{defined} if they satisfies\nthe following inequalities: $(2k-1)\\cdot2^{i-2} - (a + p\\cdot t) \\leq \\alpha_L$, $\\alpha_R < a + 2^{i-2}$.\nOtherwise they are called \\emph{undefined}. Since $2^{i} - 1$ is the greatest length of a root then start\npositions of pure squares can not be further right than $(2k-1)\\cdot2^{i-2} - (a + p\\cdot t)$. So it does not\nmatter where the $p$-periodicity terminates outside. Analogously $\\gamma_L, \\gamma_R$ defined as output of\n\\textbf{Period termination} problem for $\\slp{S}_j, S_j\\substr{a}{a + p\\cdot t}$. $\\gamma_L, \\gamma_R$  called\n\\emph{defined} if they satisfies the following inequalities: $(k-1)2^{i-2} \\leq \\gamma_L$ and $\\gamma_R < 2(a + p\\cdot\nt) - (k-1)2^{i-2}$. Otherwise they are called \\emph{undefined}.\n\nFor the positions $\\alpha_L, \\alpha_R, \\gamma_L$ and $\\gamma_R$ the following lemmas are valid:\n\n\\begin{lem}[{\\rm\\cite{2}}]\nIf one of $\\alpha_R$ or $\\gamma_L$ is defined, then the other one is defined, and $\\alpha_R - \\gamma_L \\leq p$.\n\\end{lem}\n\n\\begin{lem}[{\\rm\\cite{2}}]\nIf both $\\alpha_R$ and $\\gamma_L$ are undefined, then none of the repetitions possible containing $B_k$ are a\nsquare.\n\\end{lem}\n\nTherefore squares exists if and only if $\\alpha_R$ and $\\gamma_L$ are defined. Let us consider possible relative\npositions of $\\alpha_R$ and $\\gamma_L$:\n\\begin{itemize}\n\\item If $\\alpha_R < \\gamma_L$ then centers of pure squares may located at $[k \\cdot 2^{i-2}, \\alpha_R]$, $(\\alpha_R, \\gamma_L]$, \n$(\\gamma_L, (k+1)\\cdot2^{i-2}]$;\n\\item If $\\alpha_R > \\gamma_L$ then centers of pure squares may located at $[k \\cdot 2^{i-2}, \\gamma_L]$, $(\\gamma_L, \\alpha_R]$, \n$(\\alpha_R, (k+1)\\cdot2^{i-2}]$;\n\\end{itemize}\n\nMost cases (except $(\\gamma_L, \\alpha_R]$) can be solved using the following lemma:\n\n\\begin{lem}[{\\rm\\cite{2}}]\nIf both $\\alpha_R, \\gamma_L$ are defined then:\n\n\\begin{enumerate}\n\\item Repetitions that are contain $B_k$ and centered at positions $h$, such that $h \\leq \\gamma_L$, may exist only if\n$\\alpha_L$ is defined. These repetitions constitute a family of repetitions that corresponds to the difference\n$|x| = a + t'\\cdot p - (k-1)2^{i-2}$, provided that there exists some $t' \\in \\overline{0\\dots t}$ such that\n$\\gamma_L - \\alpha_L = a + t'\\cdot p - (k-1)2^{i-2}$.\n\\item Repetitions that are contain $B_k$ and centered at positions $h$, such that $\\alpha_R < h$, may exist only if\n$\\gamma_R$ is defined. These repetitions constitute a family of repetitions that corresponds to the difference\n$|x| = a + t''\\cdot p - (k-1)2^{i-2}$, provided that there exists some $t'' \\in \\overline{0\\dots t}$ such that\n$\\gamma_L - \\alpha_L = a + t''\\cdot p - (k-1)2^{i-2}$.\n\\end{enumerate}\nNotice that if $\\alpha_R < \\gamma_L$, then repetitions whose center $h$ satisfies $\\alpha_R < h \\leq\\gamma_L$ may\nexist only if both $\\alpha_L$ and $\\gamma_R$ are defined and $\\gamma_R - \\alpha_R = \\gamma_L - \\alpha_L$.\n\\end{lem}\n\nAt each case of the previous lemma the algorithm may obtain exponentially many repetitions. Therefore it stores in\ncompressed way: $\\{|x|, c_l, c_r\\}$ where $|x|$ is length of the root, $c_l$ is center of leftmost repetition,\n$c_r$ is center of rightmost repetition. So if $\\alpha_R < \\gamma_L$ the algorithm may obtain the following three\nfamilies of repetitions at worst case: $\\{\\gamma_L - \\alpha_L, k \\cdot 2^{i-2}, \\alpha_R\\}, \\{\\gamma_R - \\alpha_R,\n\\alpha_R + 1, \\gamma_L\\}, \\{\\gamma_L - \\alpha_L, \\gamma_L + 1, \\min\\{a,(k+1) \\cdot 2^{i-2}\\}\\}$. Else the algorithm may\nobtain the following two families of repetitions at worst case: $\\{\\gamma_L - \\alpha_L, k \\cdot 2^{i-2}, \\gamma_L - 1\\},\n\\{\\gamma_R - \\alpha_R, \\alpha_R, \\min\\{a,(k+1) \\cdot 2^{i-2}\\}\\}$.\n\nThe last case can be solved using the following lemma:\n\n\\begin{lem}[{\\rm\\cite{2}}]\nIf $\\alpha_R, \\gamma_L$ are defined and $\\gamma_L < \\alpha_R$, then there might be a family of repetitions\nassociated with each of the differences $|x| = a + p\\cdot t' - (k-1)\\cdot 2^{i-2}$ where $t' \\in \\overline{0\\dots t}$,\nwith centers at positions $h$, such that $\\gamma_L < h \\leq \\alpha_R$. The repetitions in each such family are all\npure squares, and they are centered at positions $h$, such that $\\max(\\alpha_L + |x|, \\gamma_L) < h \\leq\n\\min(\\alpha_R, \\gamma_R-|x|)$. Notice that such a family is not empty only if $|x| < \\min(\\alpha_R-\\alpha_L,\n\\gamma_R-\\gamma_L)$.\n\\end{lem}\n\nSince families of pure squares have float centers and float length of root the algorithm store it exactly:\n$k, \\prog{a}{p}{t}, \\alpha_L, \\alpha_R, \\gamma_L, \\gamma_R$. \n\nPseudo code of the algorithm presented at figure 4.\n\n\\SearchingPureSquaresCode\n\n\\begin{thm}\nThere is algorithm that solves Searching all pure squares problem using $O(|\\slp{S}|^4 \\cdot \\log^2{|S|})$ time and\n$O(|\\slp{S}| \\cdot \\max(|\\slp{S}|, \\log{|S|}))$ space.\n\\end{thm}\n\n\\section{Conclusion}\n\nWe have presented an algorithm that, given an SLP $\\slp{S}$ deriving a text $S$, fills out a table containing\ninformation about all pure squares that occur in $S$ in time $O(|\\slp{S}|^4\\cdot \\log^2{|S|})$ using\n$O(|\\slp{S}|\\cdot \\max\\{ |\\slp{S}|, \\log{|S|}\\})$ space. We would like to emphasize some features of the\nalgorithm:\n\n\\begin{itemize}\n\\begin{item}\nThis algorithm is divided into independent steps in contrast to classical algorithms in this area which\nconsecutively accumulate information about required objects. As a result it can be parallelized.\n\\end{item}\n\\begin{item}\nThe algorithm is quite difficult from the viewpoint of practical implementation. Also it is not excluded that the\nconstants hidden in the ``$O$'' notation  are actually very big.\n\\end{item}\n\\end{itemize}\n\n\\bibliography{saps_journal}{}\n\\bibliographystyle{plain}\n\n\\begin{appendix}\n\\section{Examples}\n\n\\subsection{Leech word square-freeness}\nLet us consider the SLP $\\slp{L}$ that derives substring of Leech square free word: \n\n\\begin{center}\n$\\slpterm{L}{1}{a}, \\slpterm{L}{2}{b}, \\slpterm{L}{3}{c}, \\slpnonterm{L}{4}{2}{3}, \\slpnonterm{L}{5}{2}{1},\n\\slpnonterm{L}{6}{1}{4}$\n\n$\\slpnonterm{L}{7}{3}{4}, \\slpnonterm{L}{8}{6}{5}, \\slpnonterm{L}{9}{8}{4}, \\slpnonterm{L}{10}{8}{7},\n\\slpnonterm{L}{11}{10}{9}$\n\\end{center}\n\nParse tree for $\\slp{L}$ presented at figure 4.\n\n\\begin{figure}[th]\n\\LeechSLP\n\\end{figure}\n\nLet us check square freeness of $\\slp{L}$. Since $|L| = 15$ then the algorithm check the following segments of root\nlength: [1, 1], [2, 3], [4, 7]. Notice that rules of $\\slp{L}$ already ordered by length of derived text.\n\n\\begin{itemize}\n  \\item \\textbf{checking square freeness of squares that root length equals to 1}\n  \n  Firstly the algorithm skip terminal rules. Next it consecutively look for squares exactly in other rules. For\n  instance, let us consider how it checks $\\slpnonterm{L}{10}{8}{7}$. The algorithm find $L_8[5] = a$ and $L_7[1] = c$\n  using $\\slp{L}_{10}$. Since $a \\neq c$ it moves to $\\slp{L}_{11}$.\n  \n  It is clear that $\\slp{L}_4, \\dots, \\slp{L}_{11}$ have no squares of length 2 around its cut positions.\n  \\item \\textbf{checking square freeness of squares that root length belong to [2, 3]}\n  \n  The algorithm skip all rules that have length less 4 (i.e. $\\slp{L}_1, \\dots, \\slp{L}_7$). For instance, let us\n  consider how it checks $\\slpnonterm{L}{8}{6}{5}$. Since $|L_8| = 5$ and block length is equal to 1 then the algorithm\n  construct an SLP $\\slp{L}_8'$ that derives text \\emph{\\$~\\$~\\$~\\$~\\$~a~b~c~b~a~\\$~\\$~\\$~\\$~\\$~\\$}, where \\emph{\\$} is\n  special symbol not from $\\Sigma$. At figure 5 presented partition of $L_8'$ into blocks of length 1.\n  \n  \\LeechWordPartitionSimple\n  \n  Remind that the algorithm necessary to check blocks $B_5, \\dots, B_{12}$. It no need to check $B_5$ since it contains\n  \\emph{\\$}. Also it no need to check $B_9$ and $B_{10}$ since the search area is out of $L_8$. For instance, let us\n  consider how it checks $B_7$. The algorithm build $\\slp{L}_8'\\substr{6}{7}$ that derives $B_7$ and  \n  $\\slp{L}_8'\\substr{8}{11}$ that derives search area $B_9 \\cdot B_{10}$. Next it runs pattern matching algorithm on\n  $\\slp{L}_8'\\substr{6}{7}$, $\\slp{L}_8'\\substr{8}{11}$ and obtain occurrence of $B_7$ at position 9 of $L_8'$. Finally\n  it runs \\textbf{SubsExt} problem with the following parameters: $\\slp{L}_8'$ and positions 6, 7, 8, 9. The algorithm\n  obtains $\\ell_{ex} = r_{ex} = 0$. Since $\\ell_{ex} + r_{ex} = 0 = a - (k - 1) \\cdot 2^{i-2} = 8 - (9 - 1) \\cdot 1$ then\n  algorithm moves to $L_9$.\n\n  \\item \\textbf{checking square freeness of squares that root length belongs to [4, 7]}\n  \n  The algorithm skip all rules that have length less 8 (i.e. $\\slp{L}_1, \\dots, \\slp{L}_9$). For instance, let us\n  consider how it checks $\\slpnonterm{L}{11}{10}{9}$. Firstly it construct an SLP $\\slp{L}_{11}'$ that derives $L$\n  surrounded with \\emph{\\$} and $|L_{11}'| = 32$. At figure 6 presented partition of $L_{11}'$ into blocks of length\n  2. \n  \n  \\LeechWordPartitionComplex\n\n  Next the algorithm find no squares for $B_5, \\dots, B_8$ since pattern matching algorithm returns empty set of\n  results. Next the algorithm find occurrence of $B_9$ at position 22 of $L_{11}'$ and run \\textbf{SubsExt}\n  problem with the following parameters: $\\slp{L}_{11}'$ and positions 16, 18, 20, 22. Since $\\ell_{ex} = r_{ex} = 0$ the\n  algorithm moves to $B_{10}$. Finally the algorithm find no squares for $B_{10}, B_{11}, B_{12}$ since correspond\n  search areas contains \\emph{\\$}.\n\\end{itemize}\n\n\\subsection{Construction PS-table for $\\slp{F}_7$}\n\nLet us consider how the algorithm construct PS-table for $\\slp{F}_7$ that derives text \\emph{a~b~a~a~b~a~b~a~a~b~a~a~b}.\nThe PS-table size is equal to $(\\lfloor\\log |F_7|\\rfloor+1)\\times (|\\slp{F}_7|+1) = 4 \\times 8$. \n\n\\begin{itemize}\n  \\item \\textbf{looking for squares that root length equals to 1}\n  \n  Firstly the algorithm mark cells with $\\varnothing$ for rules with length less than 2. Next it consecutively look for\n  squares exactly in other rules. PS(1, 3) = $\\varnothing$ since $F_1[1] = a \\neq b = F_2[1]$. Analogously PS(1, 4) =\n  PS(1, 6) = $\\varnothing$. PS(1, 5) = \\{1, 3, 3\\} since $F_4[3] = a = F_3[1]$. PS(1, 7) = \\{1, 8, 8\\} since $F_6[8] = a\n  = F_5[1]$. After first step PS-table has the following view: \n  \n  \\begin{figure}[h]\n\t  {\\footnotesize\\noindent\n\t\t\\begin{tabular}{|c|c|c|c|c|c|c|c|} \\hline\n\t \t& $\\slpterm{F}{1}{a}$ & $\\slpterm{F}{2}{b}$ & $\\slpnonterm{F}{3}{1}{2}$ & $\\slpnonterm{F}{4}{3}{1}$ &\n\t \t$\\slpnonterm{F}{5}{4}{3}$ & $\\slpnonterm{F}{6}{5}{4}$ & $\\slpnonterm{F}{7}{6}{5}$ \\\\ \\hline\n\t\n\t \t[1, 1] & $\\varnothing$ & $\\varnothing$ & $\\varnothing$ & $\\varnothing$ & \\{1, 3, 3\\} & $\\varnothing$ & \\{1, 8, 8\\} \\\\\n\t \t\\hline\n\t\n\t \t[2, 3] & & & & & & & \\\\ \\hline\n\t\n\t \t[4, 7] & & & & & & & \\\\ \\hline\n\t\t\\end{tabular}\n\t  }\n  \\end{figure}\n  \n  \\item \\textbf{looking for squares that root length belongs to [2, 3]}\n  \n  The algorithm mark cells with $\\varnothing$ for rules with length less than 4. For instance, let us consider\n  how the algorithm fill PS(2, 6). The algorithm construct SLP $\\slp{F}_6'$ that derives text\n  \\emph{\\$~\\$~\\$~a~b~a~a~b~a~b~a~\\$~\\$~\\$~\\$~\\$} of length 16. At figure 7 presented partition of $F_6'$ into blocks.\n  \n  \\FibonacciWordPartition\n  \n  $B_5$: using \\textbf{PM} problem the algorithm obtain occurrence of $B_5$ at position 8 of $F_6'$ on  \n  $\\slp{F}_{6}'\\substr{5}{6}, \\slp{F}_{6}'\\substr{7}{9}$; the substring extending algorithm obtain $\\ell_{ex} = r_{ex} = 1$\n  on $\\slp{F}_{6}'$ with parameters 5, 6, 8, 9; so family of repetitions \\{3, 7, 7\\} was found;\n  \n  $B_6$: using \\textbf{PM} problem the algorithm obtain occurrence of $B_6$ at position 9 of $F_6'$ on  \n  $\\slp{F}_{6}'\\substr{6}{7}, \\slp{F}_{6}'\\substr{8}{10}$; the substring extending algorithm obtain $\\ell_{ex} = 2, r_{ex}\n  = 0$ on $\\slp{F}_{6}'$ with parameters 6, 7, 9, 10; so family of repetitions \\{3, 7, 7\\} was found;\n  \n  $B_7$: using \\textbf{PM} problem the algorithm obtain occurrence of $B_7$ at position 9 of $F_6'$ on  \n  $\\slp{F}_{6}'\\substr{7}{8}, \\slp{F}_{6}'\\substr{9}{11}$; the substring extending algorithm obtain $\\ell_{ex} = 0, r_{ex}\n  = 1$ on $\\slp{F}_{6}'$ with parameters 7, 8, 9, 10; so no family of repetitions was found;\n  \n  $B_8$: using \\textbf{PM} problem the algorithm obtain occurrence of $B_8$ at position 10 of $F_6'$ on  \n  $\\slp{F}_{6}'\\substr{8}{9}, \\slp{F}_{6}'\\substr{10}{12}$; the substring extending algorithm obtain $\\ell_{ex} = r_{ex}\n  = 1$ on $\\slp{F}_{6}'$ with parameters 8, 9, 10, 11; so family of repetitions \\{2, 8, 9\\} was found;\n  \n  $B_9$: using \\textbf{PM} problem the algorithm obtain occurrence of $B_9$ at position 11 of $F_6'$ on  \n  $\\slp{F}_{6}'\\substr{9}{10}, \\slp{F}_{6}'\\substr{11}{13}$; the substring extending algorithm obtain $\\ell_{ex} = 1,\n  r_{ex} = 0$ on $\\slp{F}_{6}'$ with parameters 9, 10, 11, 12; so family of repetitions \\{2, 9, 9\\} was found;\n  \n  The algorithm skip blocks $B_{10}, \\dots, B_{12}$ since the search area consist of \\emph{\\$}. After merging families \n  of repetitions the algorithm have the following result: \\{3, 7, 7\\}, \\{2, 8, 9\\}. Finally the algorithm check purity\n  of families and shift them form $F_{6}'$ to $F_6$. \n  \n  After second step PS-table has the following view:\n  \n  \\begin{figure}[h]\n\t  {\\footnotesize\\noindent\n\t\t\\begin{tabular}{|c|c|c|c|c|c|c|c|} \\hline\n\t \t& $\\slpterm{F}{1}{a}$ & $\\slpterm{F}{2}{b}$ & $\\slpnonterm{F}{3}{1}{2}$ & $\\slpnonterm{F}{4}{3}{1}$ &\n\t \t$\\slpnonterm{F}{5}{4}{3}$ & $\\slpnonterm{F}{6}{5}{4}$ & $\\slpnonterm{F}{7}{6}{5}$ \\\\ \\hline\n\t\n\t \t[1, 1] & $\\varnothing$ & $\\varnothing$ & $\\varnothing$ & $\\varnothing$ & \\{1, 3, 3\\} & $\\varnothing$ & \\{1, 8, 8\\} \\\\\n\t \t\\hline\n\t\n\t \t[2, 3] & $\\varnothing$ & $\\varnothing$ & $\\varnothing$ & $\\varnothing$ & $\\varnothing$ & \\{3, 4, 4\\}, \\{2, 5, 6\\} &\n\t \t\\{3, 10, 10\\} \\\\ \t\\hline\n\t\n\t \t[4, 7] & & & & & & & \\\\ \\hline\n\t\t\\end{tabular}\n\t  }\n  \\end{figure}\n  \n  \\item \\textbf{looking for squares that root length belongs to [4, 7]}\n  \n  The algorithm mark cells with $\\varnothing$ for rules with length less than 8. The algorithm construct SLP\n  $\\slp{F}_7'$ that surrounds with \\emph{\\$} and has length 32. At figure 8 presented partition of $F_7'$ into\n  blocks. Let us consider how the algorithm fill PS(3, 7). It skips $B_5$ since $B_5$ contains \\emph{\\$}. \n  \n   \\FibonacciWordPartitionComplex\n  \n  $B_6$: using \\textbf{PM} problem the algorithm obtain occurrence of $B_6$ at position 15; the substring extending algorithm\n  obtain $\\ell_{ex} = 1, r_{ex} = 3$ on $\\slp{F}_{7}'$ with parameters 10, 12, 14, 18; so family of repetitions \\{5, 14,\n  15\\} was found;\n  \n  $B_7$: using \\textbf{PM} problem the algorithm obtain occurrence of $B_7$ at position 17; the substring extending algorithm\n  obtain $\\ell_{ex} = 3, r_{ex} = 1$ on $\\slp{F}_{7}'$ with parameters 12, 14, 16, 20; so family of repetitions \\{5, 14,\n  15\\} was found;\n  \n  $B_8$: using \\textbf{PM} problem the algorithm obtain occurrence of $B_8$ at position 20; the substring extending algorithm\n  obtain $\\ell_{ex} = r_{ex} = 0$ on $\\slp{F}_{7}'$ with parameters 14, 16, 18, 22; so there are no families of\n  repetitions;\n  \n  $B_9$: using \\textbf{PM} problem the algorithm obtain no occurrence of $B_9$; so there are no families of repetitions;\n  \n  The algorithm skips $B_{10}$ and $B_{11}$ since search areas consist of \\emph{\\$}. It skips $B_{12}$ since $B_{12}$\n  contains \\emph{\\$}. After merging families of repetitions the algorithm have the following result: \\{5, 14, 15\\}. \n  Finally the algorithm check purity of families and shift them form $F_{7}'$ to $F_7$.\n  \n  Finally PS-table has the following view:\n  \n  \\begin{figure}[h]\n\t  {\\footnotesize\\noindent\n\t\t\\begin{tabular}{|c|c|c|c|c|c|c|c|} \\hline\n\t \t& $\\slpterm{F}{1}{a}$ & $\\slpterm{F}{2}{b}$ & $\\slpnonterm{F}{3}{1}{2}$ & $\\slpnonterm{F}{4}{3}{1}$ &\n\t \t$\\slpnonterm{F}{5}{4}{3}$ & $\\slpnonterm{F}{6}{5}{4}$ & $\\slpnonterm{F}{7}{6}{5}$ \\\\ \\hline\n\t\n\t \t[1, 1] & $\\varnothing$ & $\\varnothing$ & $\\varnothing$ & $\\varnothing$ & \\{1, 3, 3\\} & $\\varnothing$ & \\{1, 8, 8\\} \\\\\n\t \t\\hline\n\t\n\t \t[2, 3] & $\\varnothing$ & $\\varnothing$ & $\\varnothing$ & $\\varnothing$ & $\\varnothing$ & \\{3, 4, 4\\}, \\{2, 5, 6\\} &\n\t \t\\{3, 10, 10\\} \\\\ \\hline\n\t\n\t \t[4, 7] & $\\varnothing$ & $\\varnothing$ & $\\varnothing$ & $\\varnothing$ & $\\varnothing$ & $\\varnothing$ & \\{5, 5, 6\\}\n\t \t\\\\ \\hline\n\t\t\\end{tabular}\n\t  }\n  \\end{figure}\n\\end{itemize}\n\n\\subsection{Text with complex family of pure squares}\nLet us consider an SLP $\\slp{E} = \\slp{E}_l \\cdot \\slp{E}_r$ such that $\\slp{E}_l$ derives text $(a~b~a~b~a)^6~a~b~a$\nand $\\slp{E}_r$ derives text $b~a~a~b~a~(a~b~a~b~a)^7$. So $\\slp{E}$ derives text $(a~b~a~b~a)^7~a~b~a~(a~b~a~b~a)^7$\nand $|E| = 73$. Let us consider how the algorithm looking for pure squares for rule $\\slp{E}$ and segment [16, 31]. The \nalgorithm construct SLP $\\slp{E}'$ that surrounds with \\emph{\\$} and has length 128. The partition of $E'$ into blocks\npresented at figure 9. \n\n\\ComplexExamplePartititon\n\nLet us consider how the algorithm process block $B_8$. It find occurrence of $B_8$ in $B_9 \\cdot B_{10}$ at positions\n$\\prog{72}{2}{5}$. Since the algorithm find more than one occurrence it extends periodicity to calculate parameters\n$\\alpha_L, \\alpha_R, \\gamma_L, \\gamma_R$. So $\\alpha_L = \\infty, \\alpha_R = 69, \\gamma_L = 66, \\gamma_R = \\infty$.\nAccording to lemma !!! the algorithm find complex family of pure squares associated with each of root length \\{18, 23\\} \nand centred at positions \\{66, 67, 68, 69\\}. Next we write every root from the family exactly: \n\n\\begin{itemize}\n  \\item \\textbf{roots of length 18}\n\n  $a~b~a(a~b~a~b~a)^3$, $b~a(a~b~a~b~a)^3a$, $a(a~b~a~b~a)^3a~b$, $(a~b~a~b~a)^3a~b~a$;\n  \\item \\textbf{roots of length 23}\n  \n  $a~b~a(a~b~a~b~a)^4$, $b~a(a~b~a~b~a)^4a$, $a(a~b~a~b~a)^4a~b$, $(a~b~a~b~a)^4a~b~a$;\n\\end{itemize}\n\n\\end{appendix}\n\n\\end{document}", "meta": {"hexsha": "da846b00537c082dd0ee487d4397786c9a23288f", "size": 44235, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "texfiles/Khvorost/saps/paper/saps_journal.tex", "max_stars_repo_name": "jaamal/overclocking", "max_stars_repo_head_hexsha": "b40db5a72710c691ca558e22626c5c382fd3677a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "texfiles/Khvorost/saps/paper/saps_journal.tex", "max_issues_repo_name": "jaamal/overclocking", "max_issues_repo_head_hexsha": "b40db5a72710c691ca558e22626c5c382fd3677a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-04-11T12:58:50.000Z", "max_issues_repo_issues_event_max_datetime": "2015-04-12T10:54:35.000Z", "max_forks_repo_path": "texfiles/Khvorost/saps/paper/saps_journal.tex", "max_forks_repo_name": "jaamal/overclocking", "max_forks_repo_head_hexsha": "b40db5a72710c691ca558e22626c5c382fd3677a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 60.6790123457, "max_line_length": 133, "alphanum_fraction": 0.6898609698, "num_tokens": 14971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.32597922819105174}}
{"text": "\\section{Algorithms}\n\n\\subsection{B and B+ Algorithms}\n% kenny, put a section here about B+ algorithms\nThe theory for the implementation was deceptively simple, since we had\nworked it out on paper in class, and the algorithms were simple enough\nto read through.  However general human intuition turned out to be\nfairly complicated to translate into usable Javascript code.  In order\nof complexity of implementation we had the general tree and node\nobject structue, then the search methods, followed distantly by the\ninsertion and deletion methods, which turned out to be quite complex\nto implement appropriately.\n\nSetting up the general structure for the objects that would represent\nour trees and the nodes that make them up was simple enough.  For B\ntrees we created an object with properties to hold a master list of\nall nodes in the tree, the order of the tree, a direct reference to\nthe tree's root node, a counter forthe number of nodes in the tree,\nand references to the methods for searching, insertion, and deletion\nmethods, as well as a helper method called \\texttt{insertUp}, which is\ncalled recursively after a node overflows to handle splitting the node\nand inserting the appropriate key into the parent node.  For B+ trees,\nthe object we created has almost all the same properties, but its\n\\texttt{insertUp} method is only for internal node overflow handling,\nand it also has a reference to a method called\n\\texttt{bp\\_leaf\\_split} which handles overflow in a leaf node.\n\nThe node objects we created were designed to be used for both tree\nstructures.  They contain a list of the values/keys in the node, a\nlist of the children to the node, a reference to the node's parent,\ncounters for the number of values/keys and for the number of children,\na flag to signify if the node is a leaf node, and a reference to a\nhelper method that returns the list of children to the node.\n\nInside our tree objects, we maintain a list of all the nodes in the\ntree. This is necessary because Javascript does not have pointers as\nseen in languages such as C. In order to implement the tree, we needed\nto simulate pointers. Our solution is to maintain an array to which we\nstore all our nodes. The indices of this array serve as the equivalent\nof pointer references for our tree. This method has the same memory\nfootprint as a method that would have used pointers, though it adds a\nfew extra lines of code where we have to constantly reference back to\nthe trees node list and look up the index value of whatever node we\nwant to reference.\n\nImplementing search for the two tree types was fairly straight forward\nand was accomplished in as few as 27 lines of code.  For B trees, the\nmethod for searching consists of starting at the root, inspecting in\nthe search value is in the node, if not then we decide which child\nnode it would be in and then recursively call the search function\nstarting from the child node the value should be in.  If we encounter\na dead end and have not yet found our value, then we return that the\nvalue did not exist in the tree.  If we do find the value we return\nthe index of the node it was found in and a true flag to indicate that\nthe value was found.  The method for searching a B+ tree was similar\nexcept we do not check to see if the search value is in the current\nnode until we've reached a leaf node.  Until we reach a leaf we just\ndecide which child to explore next and recursively call the search\nfunction starting from that child.  Once we've reached a leaf node, if\nwe find the value in the node, we return the node index amd a true\nflag.  If we reach a leaf node, and it does not contain our search\nvalue, then we return falseto indicate the value does not exist in the\ntree.\n\nImplementing insertion into the trees was where things became a bit\ncomplicated.  Specifically having to handle overflow and node\nsplitting.  The insertion mothed for B trees starts out fairly simple,\nwe do a search through the tree for the insertion value.  Regardless\nof whether the value is found or not, the search method should return\nus the node that the value should be inserted into.  We then do a\nbrute force insert into the node, temporarily ignoring order, just to\nget the nodes values sorted.  Once we have the value inserted, we\ncheck if the node is now overflowing or not, if not we are done and\nend the function.  If we do encounter overflow then we quickly\ncalculate the median value and partition the values into two separate\nsets around the median, but neither including the median value.  We\nthen pass the two sets of values, the median value, the index of the\nmedian value, and the current node to out \\texttt{insertUp} method to\nhandle the spliting of the node.  The \\texttt{insertUp} method\nrecieves these values and that check to see if the current node is the\nroot node or not.  If we are splitting the root node then the split is\neasy enough to accomplish.  We create two new nodes that will become\nthe children to the root, and each inherit half the children of the\nprevious root.  We want to keep the root of the tree at index 0 in the\narray of all nodes in the tree for convenience, which is why the new\nnodes created are the children to our new root, and not one of the\nchildren and the new root node.  We assign the appropriate values and\nchildren to the new nodes, and set them to look at the root node as\ntheir parent, we then assign the the new root the median value from\nthe split node, and set its children to include the new children nodes\nwe have created.\n\nIf the node to be split was instead a leaf or internal node then the\nmethod of splitting is slightly different.  In this case we are only\ncreating one new node to the tree, all the appropriate values and\nchildren, if any exist, are split between the original node we are\nsplitting and the new node we are creating to take in half the values,\nand possible half the children.  We then recursively call the\n\\texttt{insertUp} method to insert the median value into the split\nnode's parent.  The function will recurse until either no node needs\nto be split, or we've split the root node.\n\nInsertion for B+ trees in almost identical, except it has to handle an\nextra specific case that B trees do not deal with.  Splitting internal\nnodes and the root node function identically, but B+ trees behave\ndifferently than B trees when splitting leaf nodes, and so an extra\nmethod to handle this case called \\texttt{bp\\_leaf\\_split} is\nimplemented.  When splitting a leaf node, it is similar to splitting\nan internal node, with slight changes.  When splitting a leaf node, we\nsplit the node down the middle, but do not separate out the median\nvalue to be inserted up into the parent node.  Instead, we select the\nsmallest value from the right side of the split node and insert that\nas a key into the parent node, this being because all values are\nstored at the leaf level in B+ trees.  After splitting a leaf node we\nthen call the B+ tree's insertUp method to handle insertion of the new\nkey and potential splitting of the parent node.\n\nAfter some tweaking and discussion about our implementation for\ndeletion in both B and B+ trees, we made the decision to change from\nour original intended method in exchange for a more streamlined,\nthough more costly method.  In investigating methods for implementing\ndeletion from B and B+ trees we found there to be two popular methods\nof accomplishing this task.  The first is the most obvious, but also\nthe more complex of the two to implement.  It consists of search for\nthe value in the tree, removing it from where it lies, and then if the\nnode should underflow, borrow from or merge with sibling nodes, and if\nneed be change keys in parent nodes, which could then result in\nunderflow propagating upward in the tree, which in turn would need to\nbe handled.  The other method suggested passing through the tree and\nrestructuring it such that no underflow would occur when the value is\nremoved.  We had originally intended to implement the first method,\nbut found that in development that the way we had things structured\nmade it mush easier to implement the second method.  Our\nimplementation of this method was fairly straight forward. First, we search\nfor the value to be deleted. If we find it and no underflow will\noccur, we remove it and are done.  If underflow does occur, then\nutilizing the tree's master list of values in the tree, we reconstruct\nthe tree from these values, less the deleted value.  Our\nimplementation run approximately in time $O(n \\text{\\,log\\,} n)$, but for small n\nthe effect on performance in negligible.\n\n\\subsection{Graph Layout Algorithms}\nThe UI portion of this project requires a sizable amount of\nalgorithmic work. The most difficult factor is the development of a\nnode layout algorithm that prevents node overlap, while also giving an\nideal spacing between the nodes in the tree. This is especially\nimportant as the size of the tree grows.\n\nA popular method for solving this problem is the use of the\nforce-based algorithm. This algorithm works well for spreading nodes\nout over 2 or 3 dimensional space. However, it does not take into\naccount the movement limitations that are imposed in a B+\ntree. Namely, the nodes in a B+ tree can only move horizontally except\nfor in the case of a node split or join.\n\nA secondary issue with the use of force-based algorithms is that they\nhave a running time of O$(n^3)$. This long running time is not ideal\nfor large trees. Our design helps mitigate the issues presented by\nthis running time. Namely, the size of the tree that can be visible to\nthe user is limited by the available screen real estate. This limits\nthe number of nodes down to a reasonable level, and thus keeps our\nrunning time within reason.\n\nForce based algorithms operate by modeling interaction between the\ngraph nodes using equations borrowed from physics. Each node is\ntreated as an electrically charged particle, repelling the other nodes\nin the graph according to Coulomb's Law. Each edge on the graph is\ntreated as a spring, attracting the two connected nodes according to\nHooke's Law. The simulation randomizes initial node positions and then\nsimulates each time step in the model until equilibrium is reached. At\nequilibrium, the nodes should be placed in such a way that overlap is\nminimized.\n\n%% what we did\nAdapting this algorithm to work with our constraints proved to be an\ninteresting challenge. Of primary concern was the limitation that each\nnode should stay on its own level in the tree throughout the\nsimulation. This problem turned to be simple to solve. We modified the\ninitial force-based algorithm so that nodes could only apply force on\nthe X coordinate plane.\n\nAfter implementing this system, it became clear that there were still\nsome serious issues to address. The nodes in the tree were becoming\nfar to spread apart. Furthermore, they were also off-center from their\nexpected locations. After some experimentation, it was determined that\nthe issue sprouted from an assumption the original algorithm made. The\noriginal algorithm assumed that all nodes would repel each-other, as\nwould make sense in a 2-dimensional model. Unfortunately, the same\nrule did not apply for 1-dimensional models. The solution to this\nproblem was to modify the code in such a way that the nodes in the\nmodel would only repel against other nodes on that level of the tree.\n\nThe next issue encountered was that of node ordering. In the\nstandard force-based algorithm, all edge endpoints for a given node\nhave the same $(x,y)$ coordinates, and ordering does not matter. In\nthe case of B and B+ Trees, this is not true. Not only does each node\nhave multiple edge endpoints, but ordering also is extremely\nimportant.\n\nThe endpoint problem was trivially solved by simply adjusting our\n$(x,y)$ coordinates for the parent node. The issue of ordering proved\nto be a bit more difficult. The solution we designed relies on the\nalgorithm used to build the tree. This algorithm inserts nodes one at\na time in a left to right order. With this in mind, our force-based\nalgorithm inserts all new nodes at the proper level, but to the far\nright of the graph. This causes all of the nodes to shift to the left\nas the model reaches equilibrium. Because the nodes should not cross\neach other on the x-axis, they should maintain the same ordering throughout.\n%% WIP\n\n\\subsection{Example of Tree Construction}\n\n\\begin{figure}[htp!]\n\\centering\n\\includegraphics[scale=0.25]{images/Insert_one.png}\n\\caption{B tree after inserting value 1}\n\\label{EX1}\n\\end{figure}\n\n\\begin{figure}[htp!]\n\\centering\n\\includegraphics[scale=0.25]{images/Insert_two.png}\n\\caption{B tree after inserting value 2}\n\\label{EX2}\n\\end{figure}\n\n\\begin{figure}[htp!]\n\\centering\n\\includegraphics[scale=0.25]{images/Insert_three_split_root.png}\n\\caption{B tree after inserting value 3, splitting root}\n\\label{EX3}\n\\end{figure}\n\n\\begin{figure}[htp!]\n\\centering\n\\includegraphics[scale=0.25]{images/Insert_four.png}\n\\caption{B tree after inserting value 4}\n\\label{EX4}\n\\end{figure}\n\\clearpage\n\n\\begin{figure}[htp!]\n\\centering\n\\includegraphics[scale=0.25]{images/Insert_zero.png}\n\\caption{B tree after inserting value 0}\n\\label{EX5}\n\\end{figure}\n", "meta": {"hexsha": "1d86619ac4c5acd75c399f014762aa3b87c26636", "size": 13167, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tree/bp_b_tree_visual/paper/algorithms.tex", "max_stars_repo_name": "NewGuonx/DST_algorithm", "max_stars_repo_head_hexsha": "8c4b2f0fe1f43044a5c37a7f993d339862d9182c", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-23T05:29:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T05:29:17.000Z", "max_issues_repo_path": "tree/bp_b_tree_visual/paper/algorithms.tex", "max_issues_repo_name": "sonaspy/dst_algorithms", "max_issues_repo_head_hexsha": "8c4b2f0fe1f43044a5c37a7f993d339862d9182c", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tree/bp_b_tree_visual/paper/algorithms.tex", "max_forks_repo_name": "sonaspy/dst_algorithms", "max_forks_repo_head_hexsha": "8c4b2f0fe1f43044a5c37a7f993d339862d9182c", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.0927419355, "max_line_length": 81, "alphanum_fraction": 0.7934229513, "num_tokens": 3026, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.32597922819105174}}
{"text": "% OUTLINE:\n% * Introduction: a bright comet is coming!\n% * Observations: COBS, criteria.\n% * Light curve analysis: model, model fitting.\n% * Discussion & caveats:\n%   - compare surface brightness to stars\n\n\\documentclass[RNAAS]{aastex63}\n\n%% Define new commands here\n\\newcommand\\latex{La\\TeX}\n\\graphicspath{{./}{figures/}}\n\\begin{document}\n\n\\title{A Probabilistic Brightness Prediction for Comet C/2019 Y4 (ATLAS)}\n\n\\correspondingauthor{Geert Barentsen}\n\\email{hello@geert.io}\n\n\n\\author[0000-0002-3306-3484]{Geert Barentsen}\n\\affiliation{Bay Area Environmental Research Institute, P.O. Box 25, Moffett Field, CA 94035, USA}\n\n\\keywords{Long period comets}\n\n\n\\section{Introduction} \\label{sec:intro}\n\nSeveral media outlets recently reported that comet C/2019 Y4 may soon provide a spectacular \\textit{Great Comet} display.\nThe object was originally discovered on 2019 Dec 28 at magnitude $V\\approx19.5$ \\citep{CBET4712}. The comet's brightness increased rapidly thereafter, reaching $V\\approx8$ by late March (Fig.~\\ref{fig:1}). \nThe comet is expected to reach peak brightness near its perihelion date on 2020 May 31.\nIn this research note, we estimate the comet's brightness evolution in a probabilistic way by combining citizen science observations with prior information from previous comets.\n\n\\begin{figure}[h!]\n\\begin{center}\n\\includegraphics[scale=0.85,angle=0]{2019y4-prediction.pdf}\n\\caption{Light curve of comet C/2019 Y4. Plusses and crosses show visual and CCD observations from the COBS database. The mean model fit is shown as a thick dashed line. Thin black lines show random MCMC draws to visualize the model uncertainty. The grey hatched area indicates when the comet will be within 20 degrees from the Sun as seen from Earth.\\label{fig:1}}\n\\end{center}\n\\end{figure}\n\n\n\\section{Observations}\n\nThe \n\\textit{\\href{https://cobs.si}{Comet Observation Database}} \\citep[COBS;][]{2018JBAA..128..279Z} contains nearly 250,000 brightness estimates of 1285 comets dating back to 1884. The data are predominantly contributed by citizen scientists.\nAt the time of writing, the database contained 354 observations of C/2019 Y4 contributed by 52 volunteers across 18 countries.\nFig.~\\ref{fig:1} shows the subset of 296 good-quality observations that met the selection criteria\\footnote{We use observations reported with the COBS method codes S, B, M, I, E, Z, V, or O. Observations flagged as ``poor'' or ``upper limit'' are excluded.} for our analysis.\n\n\n\\section{Light curve analysis}\n\nThe canonical method to model the total magnitude $m$ of a comet (integrated across the coma) as a function of the body's geocentric and heliocentric distances ($\\Delta$ and $r$) is a power-law formula in the form\n\\begin{equation}\nm = H + 5 \\log{\\Delta} + 2.5\\,n\\,\\log{r},\n\\end{equation}\nwhere $H$ is the absolute magnitude, and $n$ is the \\textit{activity index} which is a proxy for the rate of dust production as a function of heliocentric distance. The typical value for $n$ is 4 \\citep[][]{2001A&G....42a..11G}, but values exceeding $n>8$ have been reported for segments of light curves associated with enhanced activity \\citep[e.g.][]{1990acm..proc..327H}.\n\nWe use \\texttt{\\href{https://docs.pymc.io}{PyMC3}} \\citep{pymc} to fit the power law model to the observations in a probabilistic way.\nWe model the residuals using a zero-centered Cauchy distribution with scale parameter $\\beta$.\nWe adopt empirical Gaussian priors $\\beta \\sim \\mathcal{N}(\\mu=0.47,\\,\\sigma=0.02)\\,$, \n$n \\sim \\mathcal{N}(3.5,\\,1.4)\\,$,\nand\n$H \\sim \\mathcal{N}(6.7,\\,2.0)\\,$.\nWe derived these priors by fitting the same model to the 12 brightest long-period comets available in the COBS database.\nFinally, we sample the model posterior using the default Markov Chain Monte Carlo algorithm provided by \\texttt{PyMC3}.  We verified that changing the priors does not significantly alter the posterior.\n\n\\section{Results}\n\nThe model light curve corresponding to the mean posterior parameters is shown as a dashed line in Fig.~\\ref{fig:1}.\nWe find a mean value of $n=4.5\\pm0.5$ for the activity index, and $H=5.9\\pm0.3$ for the absolute magnitude. This corresponds to a peak brightness $m=-1\\pm1$ on 2020 May 31. \n\n\n\\section{Discussion}\n\nGiven the current observations and the canonical light curve model, C/2019 Y4 is on track to become the brightest comet since C/2011 W3 (Lovejoy).\nWe caution the reader for three important caveats however:\n\\begin{enumerate}\n\\item The comet will be located very close to the Sun in the sky on 2020 May 31 ($13^o$ elongation). This will severely hinder the comet's visibility.\nThe observing conditions will be more favorable on or before 2020 May 20 ($24^o$ elongation), but the comet is expected to be much fainter on that date ($m=+1\\pm1$).\n\\item We find that the early observations of the comet prior to mid-March do not fit the canonical model well, suggesting that the activity has decreased over time.\nThis indicates that the comet's surface may have been covered by a thin layer of volatile materials which have now been depleted. If we exclude the outlier observations recorded prior to 2020 March 15 from the model fit, the expected peak brightness drops significantly to $m=+5\\pm1$.\n\\item Finally, we caution that comets are notoriously difficult to predict.\nFor example, we cannot exclude the possibility that C/2019 Y4 may break into fragments and brighten dramatically, or conversely, the object may lose its volatiles and fade away more quickly than expected.\n\\end{enumerate}\n\n%The coma brightness is likely to be spread out across several arcminutes however, likely making the comet look fainter to the eye than a star of a similar brightness.\n\n%In summary, given the current observations and a canonical light curve model, we do not currently expect comet C/2019 Y4 to appear as a \\textit{Great Comet}.\n\n\nThe code used in this analysis is available as generic Python package called \\texttt{cometcurve} available at \\url{github.com/barentsen/cometcurve}. The reader can use this tool to keep track of the comet's evolution.\n\n%The parameter $n$ is able to fit the light curves of many comets in a statistical sense. It is insufficient to capture intricate details in the light curves of comets, which are known to show variability (e.g. cite).\n\n\n\\acknowledgments\n\nThe COBS database is the product of the volunteer observers and database maintainers.\nThe data is available under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.\n% obs = cc.read_cobs(comet=\"2019Y4\", allowed_methods='all')\n% \", \".join(obs.observer_name.value_counts().keys())\nSpecifically, this analysis depends on observations contributed by\nThomas Lehmann, Artyom Novichonok, Denis Buczynski, Steffen Fritsche, Christian Harder, Carl Hergenrother, Piotr Guzik, Maik Meyer, Maciej Kwinta, Nick James, Alex Scholten, Jerzy Bohusz, Johan Warell, David Swan, Mike Collins, Maciej Reszelski, Gerhard Scheerle, Jacek Powichrowski, Martin Masek, Tomasz Sciezor, Gideon van Buitenen, Sandor Szabo, Timo Karhula, Robin Hegenbarth, Nirmal Paul, Marek Biely, Harri Kiiskinen, Piotr Nowak, Andreas Kammerer, Kevin Hills, Volker Kasten, Marcin Filipek, Walter Kutschera, Pavol Dubovsky, Juan Jose Gonzalez Suarez, Jakub Cerny, Pedro Pérez Corujo, Peter De Schrijver, Kristof Friedrich, Teerasak Thaluang, Uwe Pilz, Adam Tuznik, Jose Pablo Navarro Pina, Mikolaj Sabat, Salvador Aguirre, Vladimir Bespalov, Miroslav Lostak, Seiichi Yoshida, Mariusz Swietnicki, Carlos Labordena, Michael Linnolt, and Tibor Csorgei.\n\n\\begin{thebibliography}{}\n\n\\bibitem[Green et al.(2001)]{2001A&G....42a..11G} Green, D.~W.~E., Marsden, B.~G., \\& Morris, C.~S.\\ 2001, Astronomy and Geophysics, 42, 1.11\n\n\\bibitem[Green(2019)]{CBET4712} Green, D.~W.~E.\\ 2019, Central Bureau Electronic Telegrams 4712\n\n\\bibitem[Hughes(1990)]{1990acm..proc..327H} Hughes, D.~W.\\ 1990, Asteroids, Comets, Meteors III, 327\n\n\\bibitem[Salvatier et al.(2016)]{pymc}\nSalvatier, J., Wiecki, T.~V., Fonnesbeck, C.\\ 2016, PeerJ Computer Science, 2, e55\n\n\\bibitem[Tonry et al.(2018)]{2018PASP..130f4505T} Tonry, J.~L., Denneau, L., Heinze, A.~N., et al.\\ 2018, \\pasp, 130, 064505\n\n\\bibitem[Zakrajsek \\& Mikuz(2018)]{2018JBAA..128..279Z} Zakrajsek, J., \\& Mikuz, H.\\ 2018, Journal of the British Astronomical Association, 128, 279\n\n\\end{thebibliography}\n\n\\end{document}\n", "meta": {"hexsha": "6091ea3edfdc934cfc651052a925fb89178d717a", "size": 8321, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/research-note-2019y4/research-note-c2019y4.tex", "max_stars_repo_name": "barentsen/cometcurve", "max_stars_repo_head_hexsha": "1a99b0eb048201d6afe122cb4e0b582a7115342b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-04-06T02:15:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-29T16:19:07.000Z", "max_issues_repo_path": "paper/research-note-2019y4/research-note-c2019y4.tex", "max_issues_repo_name": "barentsen/cometcurve", "max_issues_repo_head_hexsha": "1a99b0eb048201d6afe122cb4e0b582a7115342b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-08T17:22:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-08T17:22:12.000Z", "max_forks_repo_path": "paper/research-note-2019y4/research-note-c2019y4.tex", "max_forks_repo_name": "barentsen/cometcurve", "max_forks_repo_head_hexsha": "1a99b0eb048201d6afe122cb4e0b582a7115342b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-04-06T23:46:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-08T16:50:44.000Z", "avg_line_length": 67.6504065041, "max_line_length": 858, "alphanum_fraction": 0.7690181469, "num_tokens": 2359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.32597922819105174}}
{"text": "% !TEX root = ../zeth-protocol-specification.tex\n\n\\chapter{Instantiation of the cryptographic primitives}\\label{chap:instantiation}\n\nIn this chapter, we start by instantiating the cryptographic building blocks used in previous sections to describe the \\zeth~\\dapscheme~design. Finally, we proceed by providing security proofs justifying that our instantiation complies with the security requirements listed in previous sections.\n\nNote that, in several cases, it is necessary to specify details in terms of concrete properties of the curve \\Curve~and associated scalar field $\\FFx{\\rCURVE}$. In these cases, we focus on two curves of interest: \\BNCurve~and \\BLSCurve. We note, however, that other suitable curves could be used.\n\n\\BNCurve~\\cite{bn-prime} has several properties that make it implementation-friendly. Elements of both the base field and scalar field can be represented in \\ethWordLen~bits (the native word size of the \\evm), allowing efficient encoding and manipulation of such elements. Moreover, a subset of operations on \\BNCurve are supported by the \\evm~through precompiled contracts. These precompiled contracts enable verification of signatures (\\cref{instantiation:otsig}) and zero-knowledge proofs (\\cref{instantiation:zksnark}), required by this protocol, with minimal gas overhead.\n\n\\BLSCurve~\\cite{bowe18zexe}, like \\BNCurve, has the advantage that scalar field elements can be represented within \\ethWordLen-bit words (although the same is not true of base field elements). However, the \\evm~provides no native support for \\BLSCurve, which increases the complexity of the \\mixer~implementation (see \\cref{zeth-protocol:process-tx}~for details of the operations to be performed). An advantage that \\BLSCurve does provide, is that is it the ``inner'' curve of a one-layer chain (as described in \\cite{bowe18zexe,housni2020onelayer}). Therefore zero-knowledge proofs using \\BLSCurve can be efficiently verified by statements in other zero-knowledge proofs using an approporiate ``outer'' pairing. Support for \\BLSCurve in \\zeth~therefore admits several applications (no explicitly covered by this document), such as aggregation of proofs over multiple \\zeth~transactions (e.g.~\\cite{rondelet2020zecale}).\n\nFurther details related to implementation and optimization are given in \\cref{chap:implementation}.\n\n\\input{./chapters/chap03-sec01.tex} % PRFs, COMM and CRHs (may need to be split if we decide to instantiate these with different functions)\n\\input{./chapters/chap03-sec02.tex} % MKHASH\n\\input{./chapters/chap03-sec03.tex} % Zeth statement after instantiation\n\\input{./chapters/chap03-sec04.tex} % OT-SIG\n\\input{./chapters/chap03-sec05.tex} % Encryption scheme\n\\input{./chapters/chap03-sec06.tex} % ZkSNARK\n", "meta": {"hexsha": "55111db983625342d6e398a9fb2aa4df824ea71f", "size": 2735, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/chap03-base.tex", "max_stars_repo_name": "clearmatics/zeth-specifications", "max_stars_repo_head_hexsha": "ba29c67587395f5c7b26b52ee7ab9cba12f1cc6b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-29T18:22:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-29T18:22:00.000Z", "max_issues_repo_path": "chapters/chap03-base.tex", "max_issues_repo_name": "clearmatics/zeth-specifications", "max_issues_repo_head_hexsha": "ba29c67587395f5c7b26b52ee7ab9cba12f1cc6b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2020-10-27T10:41:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-16T10:57:05.000Z", "max_forks_repo_path": "chapters/chap03-base.tex", "max_forks_repo_name": "clearmatics/zeth-specifications", "max_forks_repo_head_hexsha": "ba29c67587395f5c7b26b52ee7ab9cba12f1cc6b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-26T04:51:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T04:51:29.000Z", "avg_line_length": 130.2380952381, "max_line_length": 920, "alphanum_fraction": 0.7992687386, "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.4726834766204329, "lm_q1q2_score": 0.32582338143000356}}
{"text": "\\documentclass{article}\n\\usepackage{amsmath,amssymb,amsthm,fullpage,enumerate,bm,hyperref}\n\\theoremstyle{definition}\n\\newtheorem{prop}{Proposition}\n\\newtheorem{defi}{Definition}\n\\begin{document}\n\\section{Shorter proof that $\\mathbb{C}^n/L$ is a manifold}\nLet us assume that $L$ acts freely and properly discontinuously.\n\nLet $U\\subseteq\\mathbb{C}^n$ open, then\n\\[\\pi^{-1}(\\pi(U))=\\bigcup_{\\lambda\\in L}\\lambda+U,\\]\nSo $\\pi(U)$ is open. Pick $U$ such that $(\\lambda+U)\\cap U=\\emptyset$ for every $\\lambda\\neq 0$. Then $\\pi:U\\to\\pi(U)$ is bijective, and therefore a homeomorphism.\n\nLet $x_0+L$ be a point in $\\mathbb{C}^n/L$. Take $x_0'\\in x_0+L$ and let $U$ be a neighborhood of $x_0'$ making $\\pi:U\\to\\pi(U)$ a homeomorphism.\n\nLet $\\mathcal{U}=(\\pi(U),\\phi)$ be given by $\\phi(u)=\\pi^{-1}(u)$. Then $\\mathcal{U}$ is a coordinate system at $x_0+L$.\n\nSuppose $(\\pi(U),\\phi)$ and $(\\pi(V),\\psi)$ are coordinate systems at $[x_0]$ and $[y_0]$ respectively. Then if $\\pi(U)\\cap\\pi(V)\\neq\\emptyset$ and $a\\in\\pi(V)\\cap\\pi(U)$, we get\n\\[\\phi\\circ\\psi^{-1}(u)=\\phi(\\pi(u))=u,\\]\nso the transition maps are holomorphic.\n\n%Let $\\hat{U}=\\pi^{-1}(\\pi(U))$. Then $\\hat{U}$ is saturated (follows from bijectivity) and hence\n%\\[\\pi^{-1}(\\pi(\\hat{U}))=\\bigcup_{u\\in\\hat{U}}u+L.\\]\n%Let now $\\mathbf{f}:\\hat{U}\\to\\mathbb{C}^n$ be defined by\n%\\[\\mathbf{f}(\\lambda+x)=x.\\]\n%This is well-defined because ``freely and properly discontinuously'' implies that the $\\lambda+U$ are disjoint.\n%\n%Let $\\phi(\\pi(z))=z$\n\\end{document}\n", "meta": {"hexsha": "d945770580453b6f060d7a27844c2766ecc3d150", "size": 1504, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "talk1/torus_mfld.tex", "max_stars_repo_name": "zin0vka/katz_modular_forms", "max_stars_repo_head_hexsha": "75dc6e38a6d09a78c090ee356de293e947050839", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "talk1/torus_mfld.tex", "max_issues_repo_name": "zin0vka/katz_modular_forms", "max_issues_repo_head_hexsha": "75dc6e38a6d09a78c090ee356de293e947050839", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "talk1/torus_mfld.tex", "max_forks_repo_name": "zin0vka/katz_modular_forms", "max_forks_repo_head_hexsha": "75dc6e38a6d09a78c090ee356de293e947050839", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.1333333333, "max_line_length": 178, "alphanum_fraction": 0.664893617, "num_tokens": 565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3258202309944153}}
{"text": "\\chapter{Introduction}\n\\label{chap:intro}\n\n\\section{Motivation}\n\nLinear least-squares (\\stsc{LS}) regression is, without doubt, the workhorse of\ndata analysis in social sciences, economics and related fields. The reasons for\nthe popularity of \\stsc{LS} regression are obvious. The procedure convinces by\nits formal and practical simplicity. \\stsc{LS} regression is easy to implement\nfrom a technical point of view and its results, the estimated regression\ncoefficients, are easy to interpret. Furthermore, \\stsc{LS} regression is easy\nto teach because its math is relatively simple and is didactically convenient\nbecause \\stsc{LS} solutions for small datasets can easily be computed manually\nfor purpose of exercise and understanding. From a statistical point of view,\n\\stsc{LS} regression is favorable because it can be shown that under the\nassumption of homoscedastic (i.e., equal-variance) and normally distributed\nerrors the \\stsc{LS} estimator is the best (i.e., most efficient) unbiased\nestimator (\\stsc{BUE}) for the coefficients of a linear regression model. That\nis, among all possible unbiased estimators, the \\stsc{LS} estimator has the\nsmallest sampling variance under these conditions.\\footnote{Noting the\nequivalence between the \\stsc{LS} estimator and the arithmetic mean, the\n\\stsc{BUE} property of the \\stsc{LS} estimator is not much of a surprise given\nthe fact that Carl Friedrich Gauß derived the normal distribution as a\njustification for the arithmetic mean. That is, the normal distribution is\n\\emph{defined} as the distribution under which the \\stsc{LS} procedure leads to\nthe best unbiased estimator for the expected value (for historical background\nsee \\citealp{huber72}).} Also under relaxed assumption, such as non-normal or\nheteroscedastic (i.e., non-equal-variance) errors, the \\stsc{LS} estimator is\nconsistent and has, in many cases, good efficiency\nproperties.\\footnote{Although in the later case, the ordinary \\stsc{LS} estimate\nof the sampling variance is biased and needs to be adjusted by applying\nheteroscedasticity-robust variance estimation; see \\citealp{white80}.} For\nexample, in case of homoscedastic non-normal errors, the \\stsc{LS} estimator is\nthe beast linear unbiased estimator (\\stsc{BLUE}), that is, has the smallest\nsampling variance among all “linear” unbiased estimators.\\footnote{The term\n“linear” does not refer to the fact that the coefficients of a linear\nregression model are to be estimated. An estimator is said to be \\emph{linear}\nif it is a linear function of the observations $Y_1,\\ldots,Y_n$ of the\ndependent variable of the regression model. More precisely,\n$\\sthat{\\boldsymbol\\beta}$ is a linear estimator of the regression parameters\nvector $\\boldsymbol\\beta \\in {\\mathbb R}^p$ if there exists a matrix $\\stmat{A}\n\\in {\\mathbb R}^{p \\times n}$ such that\n$\\sthat{\\boldsymbol\\beta}=\\stmat{A}\\stvec{Y}$ with\n$\\stvec{Y}=(Y_1,\\ldots,Y_n)^t$.}\n\nThe outstanding usefulness of \\stsc{LS} regression should not be challenged\nhere. It is important, however, to realize that \\stsc{LS} regression may not\nalways be the best---or at least not the only---choice for analyzing a given\ndataset. The restrictiveness of the conditions under which the \\stsc{LS}\nestimator is deemed best---homoscedasticity and normality of errors---implies\nthat situations are possible in which alternative estimators can be valuable.\nFor example, as mentioned above, if the errors are homoscedastic but\nnon-normal, the \\stsc{LS} estimator may be the best linear unbiased estimator,\nbut this also means that there can be non-linear estimators that, depending on\nthe nature of the deviation from normality, substantially outperform the\n\\stsc{LS} estimator in terms of efficiency.\\footnote{The limitation to linear\nestimators is not much less restrictive than the limitation to normal errors.}\nIn particular, in case of distributions with heavy tails, that is, if extreme\nvalues are more frequent than in a normal distribution (an example being the\n$t$-distribution with few degrees of freedom), the efficiency of the \\stsc{LS}\nestimator can quickly become poor. Furthermore, the \\stsc{LS} estimator may\nyield misleading results if the data are “contaminated” by erroneous\nobservations or, more generally, by a secondary data-generating process.\n\n\\paragraph{Efficiency under alternative error distributions}\n\nAssume, for now, that the data are not contaminated and, more or less, follow a\nuniform data-generating process that can be described by a linear regression\nmodel. Why, under such a condition, can a low efficiency of the \\stsc{LS}\nestimator be a problem? Although the\n\\stsc{LS} estimator is unbiased, more efficient estimators would be preferable\nbecause the precision of an estimator has a direct effect on the value of the\nresults. For example, the power of a significance test and, therefore, the\npotential of the test to find an existing relation, decisively depends on the\nefficiency of the employed estimator.\n\nIn the context of error distributions with heavy tails the efficiency argument\ncan also be motivated as follows. Although the \\stsc{LS} estimator is unbiased\non average, there is a good chance for a single sample---and in practice often\nonly one sample is available---to contain extreme values that bias the\nregression results in one or the other direction. Robust regression methods\nthat are less sensitive to such outliers will typically provide more valid\nresults in such situations, being closer to the true value of the parameter to\nbe estimated.\n\nFigure~\\ref{fig:outliers-and-fits} shows two examples of data sets that have\nbeen generated according to model\n\\[\n    Y = \\beta_0 + \\beta_1 X + \\epsilon\n\\]\nwith $\\beta_0 = \\beta_1 = 0$ (that is, the “true” regression function is a\nhorizontal line at $y=0$) and $\\epsilon$ following a $t$ (Student) distribution with two\ndegrees of freedom, that is $\\epsilon \\sim t_2$. Included as lines are the\nestimated regression fits using \\stsc{LS} estimation, as well as two robust\nestimators (an \\stsc{M} estimator and an \\stsc{MM} estimator). As is evident,\nthe \\stsc{LS} solution is affected by the outliers and suggests a positive\nrelation between $X$ and $Y$ in the two examples, whereas the two robust\nestimator are relatively stable. Robust methods, so to say, contain a safeguard\nagainst extreme data constellations that can occur at random due to sampling or\na stochastic data-generating process. As a diagnostic by-product, robust\nmethods inform about whether given data are characterized by an anomalous\nconstellation or not, because only in the former case the results from\n\\stsc{LS} and the robust methods will substantially differ.\n\n\n\\begin{figure}[h!]\n    \\centering\n    \\epsfig{file=eps/2/1}\n    \\caption{Example scatter plots with outliers and different regression fits}\n    \\label{fig:outliers-and-fits}\n\\end{figure}\n\n\\paragraph{Bias due to data contamination}\n\nNow assume that the data are “contaminated”, that is, that the majority of data\npoints follows a well-defined model, but that there are also some observations\nthat come from a different distribution. For example, while collecting the\ndata, coding errors could have occurred for some of the observations. In a\nstudy by \\citet{jasso85} on the relation between marital duration and coital\nfrequency there were four observations with a value of 88 for the monthly\ncoital frequency. Although such values would not be impossible (as argued by\n\\citealp{jasso85}), the observations were highly suspicious as no other values\nof comparable magnitude existed in the data. As argued by \\citet{kahnudry86},\nthe four observations probably were miscoded missing values, whose designated\nvalue was 99. The problem with such miscoded observations is that they can have\nstrong effects on the results provided by a \\stsc{LS} regression. That is,\nregression results and the substantive conclusions drawn from them may differ\ndepending on whether the miscoded observations are kept in the data or not. It\nseems important to use methods for data analysis that are able to identify such\nproblems because, in the words of \\citet[18]{anscombe73}, “[w]e are usually\nhappier about asserting a regression relation if the relation is still apparent\nafter a few observations (any ones) have been deleted---that is, we are happier\nif the regression relation seems to permeate all the observations and does not\nderive largely from one or two.”\n\nConceptually, contamination can be understood as a situation in which the\nobserved data are the result of a mixture of two or more data-generating\nprocesses. In the case of coding errors there may be a main process of\nsubstantive interest (e.g., the relation between marital duration and coital\nfrequency), as well as a secondary process (data miscoding by interviewers)\nthat leads to observations that follow a different distribution and have a\ndifferent interpretation. \\stsc{LS} regression will not be able to distinguish\nthe two processes and its results will be valid for neither one of the\nprocesses. If, however, the data are dominated by one of the processes (that\nis, if one of the processes is responsible for the bulk of the data) and the\ntwo processes do lead to distinguishable data structures, statistical\nprocedures to identify the main process are possible. This is where robust\nregression comes in. One of the goals of robust regression techniques is to\nprovide estimates that are resistant against partial contamination of the data.\nRobust methods are supposed to correctly identify the primary relation in the\ndata even if, for example, parts of the data are glaringly erroneous.\n\nAn illustrative example comes from astronomy. Figure~\\ref{fig:hrdiagram} shows\nthe Hertzsprung-Russell diagram of star cluster CYG OB1 (see\n\\citealt[27]{rousseeuw:leroy:1987}). Displayed is the logarithm of the light\nintensity of the stars against the logarithm of their effective surface\ntemperature (using a reversed axis). Furthermore, the graph shows as lines the results of three\ndifferent regression estimators, the \\stsc{LS} estimator (solid line), a low\nbreakdown point \\stsc{M} estimator (dashed line), and a high breakdown point\n\\stsc{MM} estimator (dotted line). The results from the \\stsc{LS} estimator and\nthe low breakdown point \\stsc{M} estimator are almost identical. They are\nstrongly influenced by the group of four stars in the upper right corner of the\ndiagram. In contrast, the high breakdown point \\stsc{MM} estimator completely\nignores the four outliers and adequately captures the trend in the main part of\nthe data. Hence, at least one of the two employed robust estimators\nsuccessfully identified the main process (due to the estimator's high breakdown\npoint; see below).\n\n\n\\begin{figure}[h!]\n    \\centering\n    \\epsfig{file=eps/2/2}\n    \\caption{Hertzsprung-Russell diagram of the star cluster CYG OB1 including different regression fits (source: \\citealp[27]{rousseeuw:leroy:1987})}\n    \\label{fig:hrdiagram}\n\\end{figure}\n\nAgain, from a diagnostic perspective, the interesting cases are the ones in\nwhich \\stsc{LS} regression and robust estimators lead to differing results.\nSubstantial differences between robust regression and the \\stsc{LS} estimator\nindicate that the data cannot be fully descried by a uniform model and that a\npart of the observations stands in stark contrast to the main trend in the\ndata. With the help of the residuals from robust regression, the atypical\nobservations can be identified and, for example, be subjected to a separate\nanalysis. In this way, robust regression can contribute to a better\nunderstanding of the data and, potentially, give way to new insights and new\nhypotheses. In fact, according to \\citet[1]{kruskal60}, the atypical\nobservations may prove to be the most interesting part of the data: “An\napparently wild (or otherwise anomalous) observation is a signal that says:\n`Here is something from which we may learn a lesson, perhaps of a kind not\nanticipated beforehand, and perhaps more important than the main object of the\nstudy.'” The four outliers in figure~\\ref{fig:hrdiagram}, by the way, are not\nerrors. The explanation is that there are two different types of stars:\nmain-sequence stars and giants. That is, conceptually, the observation stem\nfrom two different populations.\n\n\\paragraph{Goals and use of robust regression}\n\nTo summarize, we can state that robust regression estimators (1) should achieve\ngood efficiency also in case of non-normal errors and (2) should be resistant\nagainst contamination of the data by outliers. The maximum proportion of\ncontamination a robust estimator is able to absorb is called the\n\\emph{breakdown point}.\n\nBoth aspects can be formalized with the help of the viewpoint coined by \n\\citet{huber64} that observed data follow a mixture distribution\n\\[\n    F_\\varepsilon = (1 - \\varepsilon) F_{\\boldsymbol\\theta} + \\varepsilon G\n\\]\nwhere $F_{\\boldsymbol\\theta}$ is the distribution of interest according to the\nsupposed model, $G$ is an arbitrary alternative distribution, and $\\varepsilon\n\\in [0,1]$ determines the mixing proportion. For example, in line with the\nassumptions of classic linear regression, $F_{\\boldsymbol\\theta}$ could be a\ndistribution according to the linear model\n\\[\n    Y = \\beta_0 + \\beta_1 X + \\epsilon\n\\]\nwhere $X$ has a given distribution and $\\epsilon$ is an independent and\nidentically normally distributed error term. The distribution of the observed\ndata, however, is contaminated by observations from an unspecified alternative\ndistribution $G$ and does not fully follow this model. The goal of robust\nregression now is to deliver reasonable results for $F_{\\boldsymbol\\theta}$\neven if the model is somewhat misspecified, that is, if $\\varepsilon>0$. In the\nwords of \\citet[7]{heritier.etal.09}, robust methods are “a set of statistical\ntools for correct estimation and inference about $F_{\\boldsymbol\\theta}$ when the\ndata-generating process is $F_\\varepsilon$, not only when $\\varepsilon=0$, as\nwith classical methods, but also for relatively small $\\varepsilon$ and\n\\emph{any} $G$. As a by-product, data not fitting $F_{\\boldsymbol\\theta}$ exactly can be\neasily identified, and the model can possibly be changed and refitted\". In\naddition, to be of diagnostic value, robust estimators should be serious\ncompetitors of classic methods in case of $\\varepsilon=0$. In particular,\nrobust estimators should achieve good “gaussian efficiency”, that is, they\nshould achieve a high relative efficiency compared to \\stsc{LS} estimation in\nthe ideal case of normally distributed errors.\\footnote{Note that the\nestimation of “robust standard errors” is not the primary concern of robust\nregression. The term “robust standard errors” refers to estimators for the\nsampling variances of the coefficient estimates that are consistent also if the\nassumption of identically distributed errors is violated (i.e., if the errors\nare heteroscedastic; see \\citealp{white80}). To prevent false conclusions with\nrespect to confidence intervals and significance tests, it is always a good\nidea to consider “robust standard errors”, be it with classic regression or\nwith robust regression.}\n\nYet, robust regression should be seen as a complement and not so much as a\nsubstitute to \\stsc{LS} regression. In our view, the main use of robust\nregression lies in its diagnostic potential. Classic regression techniques may\nlead to meaningful results in many situations, but a comparison to robust\nresults is always advisable. Before drawing far-reaching conclusions based on\nclassic methods one should evaluate whether the conclusions are “robust”, that\nis, whether methods that rely on less restrictive assumptions and are less\naffected by outliers and atypical data constellations come to the same\nconclusions.\n\nIf classic procedures and robust regression lead to substantially diverging or\neven contradicting results, the robust results can provide an immediate\ncontribution to a better understanding of the data. As a by-product of robust\nestimation, observations that do not fit the supposed model can easily be\nidentified, offering clues about possible misspecification, the nature of\noutliers, and alternative data-generating processes. Compared to classic\nregression diagnostics for the identification of influential observations (see\n\\citealp{belsley80,cookweisberg82,Chatterjee88,fox91}) robust regression\nmethods have the advantage that they can also identify “masked” multiple\noutliers that would go undetected by classic diagnostics. However, robust\ntechniques are no panacea and cannot, for example, fully replace diagnostic\nmethods that are concerned with the identification of structural\nmisspecification (such as omitted variable bias, wrong functional form, or\nmissing interaction terms).\n\n\n\n\\alert{\n[Should there also be some text giving a brief historical account of the development \nof robust statistics and robust regression?]\n}\n\n\n\\section{What is covered in this book?}\n\n\\alert{\n\\dots\n}\n\n\n\\section{Robust statistics in Stata}\n\n\\alert{\n\\begin{itemize}\n    \\item\n    Summary of existing tools\n    \\item\n    Brief presentation of our new packages; basic usage and syntax\n\\end{itemize}\n}\n\n\n\\endinput\n", "meta": {"hexsha": "3bdcb0a3103526e2f2faff3f00654c89c4f2cc67", "size": 17127, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "stbook/chapter1.tex", "max_stars_repo_name": "benjann/robregbk", "max_stars_repo_head_hexsha": "8bda32e4ce56fc354c3f469ba52ca7163e53b43f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-25T14:21:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T14:21:56.000Z", "max_issues_repo_path": "stbook/chapter1.tex", "max_issues_repo_name": "benjann/robregbk", "max_issues_repo_head_hexsha": "8bda32e4ce56fc354c3f469ba52ca7163e53b43f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stbook/chapter1.tex", "max_forks_repo_name": "benjann/robregbk", "max_forks_repo_head_hexsha": "8bda32e4ce56fc354c3f469ba52ca7163e53b43f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-05-19T07:27:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-26T02:04:46.000Z", "avg_line_length": 57.8614864865, "max_line_length": 150, "alphanum_fraction": 0.7976294739, "num_tokens": 4005, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.32582022322991394}}
{"text": "\\documentclass{article}\n\\usepackage{amsmath,amssymb}\n\\usepackage{hyperref}\n\\usepackage{graphicx}\n\\usepackage{todonotes}\n\n\\title{\\bf{Laboratory Project Two: Calibration of an Orifice Meter}}\n\\author{Jon Langston \\& Nicholas Malaya \\& Owen O'Neal \\\\ Department of Mechanical Engineering \\\\ University of Texas at Austin} \\date{}\n\n\\begin{document}\n\\maketitle\n\\date{}\n\\newpage\n\\section{Presentation of Calibration Data}\n\n\\textbf{A calibration of the $C_d$ vs $Re$ and comment on whether your\nresults were as expected.}   \n\nWe have adjusted the sample rates down  300 samples at a rate of 100\nHz. The results are shown in Figure \n\\ref{oriface-time}, below. The samples appear to still be correlated in\ntime. \n\n\\begin{figure}[!htb]\n  \\begin{center}\n    \\includegraphics[width = 12 cm]{figs/oriface_time.png}\n    \\caption{Example raw time series data from a single orifice meter \n      run. The calculated mean of the signal is shown in black, along with\n      the two $\\sigma$ (standard deviation) confidence interval in\n      red.}\n    \\label{oriface-time}\n  \\end{center}\n\\end{figure}\n\nLet's go deeper, and look at the samples over a shorter period of time. Instead of the full 3 \nsecond sampling time, we examine just 0.4 seconds. The result of this is shown in \\ref{oriface-time-4}.\nFrom this perspective, it appears we are still indeed oversampling, as at least subsequent points \ntend to be correlated with each other. \n\n\\begin{figure}[!htb]\n  \\begin{center}\n    \\includegraphics[width = 12 cm]{figs/oriface_time_04.png}\n    \\caption{Example raw time series data from a single orifice meter \n      run, plotted over a shorter time period.}\n    \\label{oriface-time-4}\n  \\end{center}\n\\end{figure}\n\n\nExamining the probability distribution functions in Figure \\ref{oriface-hist},\nwe can see that while the results are clearly better than the other lab, where we used 1000 Hz and 1000 samples. \nHowever, while these results are closer to that of a gaussian, \nthey are still not normally distributed. In other words, we still have not found an ideal data sampling rate \nfor the pressure transducer.  \n\n  \\begin{figure}[!htb]\n   \\begin{center}\n    \\includegraphics[width = 12 cm]{figs/oriface_hist.png}\n    \\caption{Histogram depicting the frequency of voltages in our\n    signal. This was generated with fifty bins, but the results did not\n    appear to be sensitive to the number selected.}\n    \\label{oriface-hist}\n   \\end{center}\n  \\end{figure}\n\nWe proceed with our calculations of the quantities of interest. We\nintend to plot $C_d$ as a function of Reynolds number. We have not made\na direct measurement of either quantity, and must calculate them as\nsurrogate quantities from our data. \n\nThe Reynolds number is defined as, \n\\begin{equation}\n \\text{Re} = \\frac{UL}{\\nu}.\n\\end{equation}\n\nThe kinematic viscosity ($\\nu$) and the orifice diameter ($L$) are\ngiven. We can calculate the bulk fluid velocity ($U$) from our knowledge\nof the flow rate and the system dimensions, \n\\begin{equation}\n U = \\frac{Q}{A} = \\frac{Q}{\\pi r^2} = \\frac{Q}{\\pi d^2/4}.\n\\end{equation}\nThe Reynolds number is therefore calculated as,\n\\begin{equation}\n Re = \\frac{Q L}{\\pi \\nu d^2/4}.\n\\end{equation}\n\nTurning our attention to the calibration coefficient, Equation (9.2)\nfrom page 211 in Stavros' text describes a relation for  \nthe flow rate as a function of the pressure drop,  \n\\begin{equation*}\n Q = C_d \\frac{\\pi d^2 / 4}{\\sqrt{1-(d/D)^4}}\\sqrt{\\frac{2 \\Delta p}{\\rho}}.\n\\end{equation*}\nThis can be manipulated to provide an equation for $C_d$ as, \n\\begin{equation}\n C_d = \\frac{Q (1-\\beta^4)^{1/2}}{\\pi d^2/4} \\left(\\frac{\\rho}{2 \\Delta\n\t\t\t\t\t      P}\\right)^{1/2}.\n\\end{equation}\n\nThe results of $C_d$ vs. Re are plotted in Figure \\ref{orif}. We can see a general trend of increasing \nvalues of $C_d$ as a function of $Re$, followed by the curve ``flattening out''. For flow in a duct, \nthe transition between laminar and turbulent flow occurs around a few thousand Re, so the vast majority \nof our data lies in the turbulent regime. Our expectation is that the $C_d$ becomes independent of Re at high \n(e.g. turbulent) Re, and the data appears to be consistent with this. The value of $C_d$ asymptotes to a value near 0.6, which is roughly in line with values we found in the literature for these aspect ratios ($\\beta$ values).\n\n  \\begin{figure}[!htb]\n   \\begin{center}\n    \\includegraphics[width = 12 cm]{figs/cd_v_re_zero_axis.jpg}\n    \\caption{A plot of $C_d$ as a function of Reynolds Number. Only the first point is likely to be \noutside of the fully developed turbulence regime. }\n    \\label{orif}\n   \\end{center}\n  \\end{figure}\n\n  \\begin{figure}[!htb]\n   \\begin{center}\n    \\includegraphics[width = 12 cm]{figs/cd_v_re.jpg}\n    \\caption{A plot of $C_d$ as a function of Reynolds Number. This plot is zoomed into the region of the data, \n    to make the difference between points more pronounced.}\n    \\label{orif}\n   \\end{center}\n  \\end{figure}\n\nThe first data point, as previously mentioned, appears to be anomalously low. The value of this point is \nstill high enough ($\\approx 5000$) that we would expect it to be turbulent. However, it is possibly close enough \nto the transition that it is not yet fully developed. A zoomed in version of this plot is shown \nin figure \\ref{oriface-time-4}.  \n\n\\subsection{Checking the Zero Setting}\n\nBefore beginning data collection, the pressure transducers were both recorded at zero \nflow in order to ensure zero pressure measurement.  The constants for the intercepts \nof the given calibrations were adjusted so that the transducers output zero pressure \ndrop when disconnected from the laminar flow element (transducer A) and orifice meter \n(transducer B).  The intercept constant for transducer A was changed from -1.075 inH2O \nto -1.06 inH2O; for transducer B, from -1.026 inH2O to -1.00 inH2O.  As the LabVIEW \nVirtual Instrument limited these calibration constants to the hundredths place, \nthese options provided zero pressure drop within $\\pm .005$ inH2O.\n \nIn order to further ensure accuracy of the given transducer calibrations, each transducer \nwas separately coupled to a micro-manometer and measurements were taken at the selected \npressures of 1 and 2 inH2O.  Transducer A output readings of 0.9919 and 1.9920 inH2O, \nrespectively, while B output readings of 0.9842 and 1.9716 inH2O, respectively.  \nConsidering the uncertainty associated with setting the manometer at the desired \npressure, these results corroborate the stated accuracy of the transducer calibrations.\n\n\\subsection{Repeatibility of the Measurements}\n\nWe attempted to control for several factors to enhance repeatability of the experiment. \nWe observed a large transient period  between adjusting the voltage and the measured \npressure drop. It is our expectation that the blower had a long equilibration time \nbefore reaching a statistically steady state. Small fluctuations in voltage, on \nthe order of 0.01-0.02 volts, which persisted after the blower reached \nquasi-steady state can be attributed to variations in velocity associated with turbulent flow. \n\nWe have qualitatively assessed the repeatability of measurements in this case by gathering \na second set of statistics. This was conducted with the same practitioners at the same time \nof day, after the first set of experimental data had been saved. The air blower was \nturned off and the zero-flow measurements were checked; once again, both transducers \noutput $\\pm0.005$ inH2O of a zero reading.  The data were not gathered at precisely \nthe same pressure drop locations, making direct comparison between data gathering \nseries impossible. However, the results from both series, when plotted \nagainst each other clearly exhibit the same trend to within a small margin. \n\n  \\begin{figure}[!htb]\n   \\begin{center}\n    \\includegraphics[width = 12 cm]{figs/Q_dP_fits.jpg}\n    \\caption{A plot of repeatability of the experiment. }\n    \\label{orif-zoom}\n   \\end{center}\n  \\end{figure}\n\n\\newpage\n\\section{Uncertainty Analysis}\n\n\\textbf{Uncertainty of flow rate measured using the orifice meter with\nyour calibration.} \n\nTaking the differences in pressure measured across the laminar flow element and orifice meter, \nwe can calculate the discharge coefficient using the equations below. The average discharge coefficient \ncalculated from our pressure measurements was nominally 0.615 across both series.\n\n\\begin{equation}\n  C_d = \\frac{Q_{\\text{LFE}} }{A_0} * (1-\\beta^4)^{1/2} * \\left(\\frac{\\rho}{\\Delta P_{\\text{trans}}}\\right)^{1/2}\n\\end{equation}\nwhere, \n\\begin{equation}\n  Q_{\\text{LFE}} = 20.5 \\Delta P_{\\text{LFE}} * \\frac{\\mu(21 C)}{\\mu(\\text{actual})}\n\\end{equation}\n\nThe uncertainty in the discharge coefficient, $U_{C_d}$, has contributions from the uncertainties in\nthe flow rate, $U_Q$, measured from the laminar flow element and the change in pressure, $U_{\\Delta P}$, \nmeasured from the pressure transducer. We can neglect uncertainties in the area of the orifice, $A_o$, \nand the ratio of diameters from the pipe and orifice meter, $\\beta$, because they are taken into account \nwhen calibrating $C_d$ as a correction factor. Changes in the density of air, $\\rho$, are neglected because our \nreynolds number while turbulent should remain well below Mach 0.3.\n\nNeglecting uncertainties in $A_o$, $\\beta$, and $\\rho$, the percent error for $C_d$ can be expressed as:\n\\begin{equation}\n  \\frac{U_{C_d}}{C_d} = \\sqrt{ \\left(\\frac{U_{Q}}{Q}\\right)^2 + \\left( 0.5 \\frac{U_{C_d}}{C_d} \\right)^2}\n\\end{equation}\n\nFor the subsequent calculations, we assume $U_Q$ and $U_{\\Delta P}$ are bias uncertainties and cannot be \nmade more accurate by taking multiple measurements. Taking the specifications given in the lab \nguidelines, $U_{\\Delta P}$ is assumed to be a constant 0.002 in. H20. $U_Q$ is a piecewise function equal to \n0.2\\%*RDG from $10-100\\%$ FS and 0.02\\%*FS below 10\\% FS. Full scale for the laminar flow element is 160 \nCFM, so the measurements at 5, 10, and 15 CFM use this latter value for uncertainty.\n\nResults: \n\\begin{itemize}\n\\item Series 1: $\\frac{U_{C_d}}{C_d} = 0.066$ @ 5 CFM and 0.0021 @ 50 CFM\n\\item Series 2: $\\frac{U_{C_d}}{C_d} = 0.076$ @ 5 CFM and 0.0021 @ 50 CFM\n\\end{itemize}\n\n  \\begin{figure}[!htb]\n   \\begin{center}\n    \\includegraphics[width = 12 cm]{figs/PercentUncertaintyCdVsQ_Series1.jpg}\n    \\caption{The uncertainty quantification for discharge coefficient, $C_d$ for the first series of measurements.}\n    \\label{orif-s1}\n   \\end{center}\n  \\end{figure}\n\n  \\begin{figure}[!htb]\n   \\begin{center}\n    \\includegraphics[width = 12 cm]{figs/PercentUncertaintyCdVsQ_Series2.jpg}\n    \\caption{The uncertainty quantification for discharge coefficient, $C_d$ for the second series of measurements.}\n    \\label{orif-s2}\n   \\end{center}\n  \\end{figure}\n\nBoth series of measurements showed the percent error of Cd decreasing exponentially as flow \nrate increased. Upon examination of our sources of error this makes sense. At low flow rates, i.e. Q < 15 \nCFM, we need to detect a smaller change in pressure. The constant uncertainty of 0.002 in H20 for our \npressure transducer is a much greater percentage of the pressure readings at these low flow rates. The \nchange in pressure increases non-linearly as flow rate increases, and so at high CFMs the percent error is \nnot as significant.\n\nHaving calibrated the orifice meter by determining the best obtainable value for $C_d$, we can \ncalculate the uncertainty of subsequent measurements of flow rate, $Q_{\\text{orifice}}$, using this device.\n\n\\begin{equation}\n  Q_{\\text{orifice}} = \\frac{C_d * A_0}{(1-\\beta^4)^{1/2}} \\left(\\frac{2 \\Delta P_{\\text{trans}}}{\\rho}\\right)^{1/2}\n\\end{equation}\n\nNeglecting uncertainties in $A_o$, $\\beta$, and $\\rho$, the percent error for $Q_{\\text{orifice}}$ \ncan be expressed using the equation below. Uncertainties for Q were calculated \nassuming a best and worst case scenario: where $U_{\\Delta P}$ is a precision\n and bias uncertainty, respectively.\n\n\\begin{equation}\n  \\frac{U_{Q}}{Q} = \\sqrt{ \\left(\\frac{U_{C_d}}{C_d}\\right)^2 + \\left( 0.5 \\frac{U_{\\Delta P}}{\\Delta P} \\right)^2}\n\\end{equation}\n\nResults:\n\\begin{itemize}\n\\item Series 1: Worst: $\\frac{U_Q}{Q} = 0.093$ @ 5CFM and 0.0023 @ 50 CFM\n\\item Series 1: Best:  $\\frac{U_Q}{Q} = 0.066$ @ 5CFM and 0.00084 @ 50 CFM\n\\item Series 2: Worst: $\\frac{U_Q}{Q} = 0.11$ @ 5CFM and 0.0023 @ 50 CFM\n\\item Series 2: Best:  $\\frac{U_Q}{Q} = 0.076$ @ 5CFM and 0.00084 @ 50 CFM\n\\end{itemize}\n\nThese results show a similar trend as the uncertainty of the discharge coefficient, decreasing \nexponentially as flow rate increases. For flow rates above 20 CFM, both series predict an uncertainty \nwell below 1\\% of the flow rate measurement from the orifice meter.\n\n  \\begin{figure}[!htb]\n   \\begin{center}\n    \\includegraphics[width = 12 cm]{figs/PercentUncertaintyQVsQ_Series1.jpg}\n    \\caption{The uncertainty quantification for flow rate, $Q$ for the first series of measurements.}\n    \\label{orif-s1}\n   \\end{center}\n  \\end{figure}\n\n  \\begin{figure}[!htb]\n   \\begin{center}\n    \\includegraphics[width = 12 cm]{figs/PercentUncertaintyQVsQ_Series2.jpg}\n    \\caption{The uncertainty quantification for flow rate, $Q$ for the second series of measurements.}\n    \\label{orif-s2}\n   \\end{center}\n  \\end{figure}\n\n%\n%\n%\n\\end{document}\n\n% LocalWords:  reynolds H20 piecewise RDG yar\n", "meta": {"hexsha": "1d6738e434bd5fcc762be4ebf290450dfcc2ca93", "size": 13308, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "exp/oriface/measurement/report.tex", "max_stars_repo_name": "nicholasmalaya/paleologos", "max_stars_repo_head_hexsha": "11959056caa80d3c910759b714a0f8e42f986f0f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-04T17:49:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T17:49:42.000Z", "max_issues_repo_path": "exp/oriface/measurement/report.tex", "max_issues_repo_name": "nicholasmalaya/paleologos", "max_issues_repo_head_hexsha": "11959056caa80d3c910759b714a0f8e42f986f0f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exp/oriface/measurement/report.tex", "max_forks_repo_name": "nicholasmalaya/paleologos", "max_forks_repo_head_hexsha": "11959056caa80d3c910759b714a0f8e42f986f0f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-01-04T16:08:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-16T19:34:24.000Z", "avg_line_length": 46.3693379791, "max_line_length": 226, "alphanum_fraction": 0.7421851518, "num_tokens": 3760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.32582022322991394}}
{"text": "To begin with, let us focus on the problem that has been used in section \\ref{sec:MPM} to illustrate shortcomings of the MPM which motivated the derivation of the DGMPM.\nWe thus consider an infinite medium in directions $\\vect{e}_2$ and $\\vect{e}_3$ and of length $L$ in direction $\\vect{e}_1$. The Cauchy stress and infinitesimal strain tensor are of the form:\n\\begin{align*}\n  & \\tens{\\sigma} = \\sigma \\: \\vect{e}_1\\otimes \\vect{e}_1 \\\\\n  & \\tens{\\eps} = \\eps \\: \\vect{e}_1\\otimes \\vect{e}_1\n\\end{align*}\nso that the bar assumption holds. Riemann-type initial conditions on the horizontal velocity $v=\\vect{v}\\cdot\\vect{e}_1$ are prescribed in the bar, that is, $v=v_0>0$ for $x_1\\in\\[0,L/2\\]$ and $v=-v_0$ for $x_1\\in \\:]L/2,L]$.\n\n\n% Parameters:\n% CFL=0.5\n% NTmaxi = 300\n% length = 6.0\n% ppc=1\n% Nelem = 50\n% E = 2.0e11\n% Sigy = 400.0e6\n% H = 10e9\n% rho = 7800.0\n% c=np.sqrt(E/rho)\n% sigd =0.\n% v0=1.*Sigy/(2*rho*c)\n% v0=2.*Sigy/(rho*c)\n% factor=1.\n% timeOut = 1.*length/c\n% t_order=1\n% timeUnload = 2*timeOut\n% algo = 'USL'\n% update_position=False\n% mpm_mapping=True\n% limit=-1\n% hardening='kinematic'\n% fvmlimiter=-1\n\n\\subsection{Elastoviscoplastic material}\n\nJuste comparer DGMPM et MPM avec du strang et godunov 1ppc et 2ppc. Stiff $dt/tau=100$ non-stiff $dt/tau=1/50$ bdf3 pour strang. Pas de RK2 godunov car le RK2 n'a une influence que sur la partie convective qui est équivalent au 1ppc Euler.\n\n\\begin{figure}[h!]\n  \\centering\n  {\\input{chapter4/pgfFigures/evp_dgmpm_mpm_stressnon-stiff20}}\n  {\\input{chapter4/pgfFigures/evp_dgmpm_mpm_stressnon-stiff30}}\n  {\\input{chapter4/pgfFigures/evp_dgmpm_mpm_stressnon-stiff45}}\n  \\caption{elastic-viscoplastic RP stress (non-stiff)}\n  \\label{fig:stress_elastoviscoplastic_RP}\n\\end{figure}\n\n\\begin{figure}[h!]\n  \\centering\n  {\\input{chapter4/pgfFigures/evp_dgmpm_mpm_epspnon-stiff20}}\n  {\\input{chapter4/pgfFigures/evp_dgmpm_mpm_epspnon-stiff30}}\n  {\\input{chapter4/pgfFigures/evp_dgmpm_mpm_epspnon-stiff45}}\n  \\caption{elastic-viscoplastic RP epsp (non-stiff)}\n  \\label{fig:epsp_elastoviscoplastic_RP}\n\\end{figure}\n\n\\begin{figure}[h!]\n  \\centering\n  {\\input{chapter4/pgfFigures/evp_dgmpm_mpm_stressstiff20}}\n  {\\input{chapter4/pgfFigures/evp_dgmpm_mpm_stressstiff30}}\n  {\\input{chapter4/pgfFigures/evp_dgmpm_mpm_stressstiff45}}\n  \\caption{elastic-viscoplastic RP stress (stiff)}\n  \\label{fig:stress_elastoviscoplastic_RP}\n\\end{figure}\n\n\\begin{figure}[h!]\n  \\centering\n  {\\input{chapter4/pgfFigures/evp_dgmpm_mpm_epspstiff20}}\n  {\\input{chapter4/pgfFigures/evp_dgmpm_mpm_epspstiff30}}\n  {\\input{chapter4/pgfFigures/evp_dgmpm_mpm_epspstiff45}}\n  \\caption{elastic-viscoplastic RP epsp (stiff)}\n  \\label{fig:epsp_elastoviscoplastic_RP}\n\\end{figure}\n\n\\subsection{Elastoplastic material}\nComparison with mpm for 1ppc which does not involve the treatment of rhs and so the choice of some parameter for integrating it.\n\\begin{figure}[h!]\n  \\centering\n  {\\input{chapter4/pgfFigures/EP_dgmpm_mpm_stress20}}\n  {\\input{chapter4/pgfFigures/EP_dgmpm_mpm_stress30}}\n  {\\input{chapter4/pgfFigures/EP_dgmpm_mpm_stress45}}\n  \\caption{elastic-plastic RP stress (1ppc)}\n  \\label{fig:stress_elastoplastic_RP}\n\\end{figure}\n\\begin{figure}[h!]\n  \\centering\n  {\\input{chapter4/pgfFigures/EP_dgmpm_mpm_epsp20}}\n  {\\input{chapter4/pgfFigures/EP_dgmpm_mpm_epsp30}}\n  {\\input{chapter4/pgfFigures/EP_dgmpm_mpm_epsp45}}\n  \\caption{elastic-plastic RP epsp (1ppc)}\n  \\label{fig:epsp_elastoplastic_RP}\n\\end{figure}\n% \\begin{figure}[h!]\n%   \\centering\n%   {\\input{chapter4/pgfFigures/EP_dgmpm_mpm_velo20}}\n%   {\\input{chapter4/pgfFigures/EP_dgmpm_mpm_velo30}}\n%   {\\input{chapter4/pgfFigures/EP_dgmpm_mpm_velo45}}\n%   \\caption{elastic-plastic RP velo}\n%   \\label{fig:velo_elastoplastic_RP}\n% \\end{figure}\nComparison with mpm for 1ppc and 2ppcs with RK2 (requires additional bc treatment and constitutive). Only ep solver\n\\begin{figure}[h!]\n  \\centering\n  {\\input{chapter4/pgfFigures/EP_dgmpm_ppc_stress20}}\n  {\\input{chapter4/pgfFigures/EP_dgmpm_ppc_stress30}}\n  {\\input{chapter4/pgfFigures/EP_dgmpm_ppc_stress45}}\n  \\caption{elastic-plastic RP stress}\n  \\label{fig:stress_elastoplastic_RP}\n\\end{figure}\n\\begin{figure}[h!]\n  \\centering\n  {\\input{chapter4/pgfFigures/EP_dgmpm_ppc_epsp20}}\n  {\\input{chapter4/pgfFigures/EP_dgmpm_ppc_epsp30}}\n  {\\input{chapter4/pgfFigures/EP_dgmpm_ppc_epsp45}}\n  \\caption{elastic-plastic RP epsp}\n  \\label{fig:epsp_elastoplastic_RP}\n\\end{figure}\n\n\nComparison with fvm and FEM (lumped mass matrix + radial return for integrating constitutive equations)\n\\begin{figure}[h!]\n  \\centering\n  {\\input{chapter4/pgfFigures/EP_dgmpm_fvm_stress20}}\n  {\\input{chapter4/pgfFigures/EP_dgmpm_fvm_stress30}}\n  {\\input{chapter4/pgfFigures/EP_dgmpm_fvm_stress45}}\n  \\caption{elastic-plastic RP stress}\n  \\label{fig:stress_elastoplastic_RP}\n\\end{figure}\n\\begin{figure}[h!]\n  \\centering\n  {\\input{chapter4/pgfFigures/EP_dgmpm_fvm_epsp20}}\n  {\\input{chapter4/pgfFigures/EP_dgmpm_fvm_epsp30}}\n  {\\input{chapter4/pgfFigures/EP_dgmpm_fvm_epsp45}}\n  \\caption{elastic-plastic RP epsp}\n  \\label{fig:epsp_elastoplastic_RP}\n\\end{figure}\n\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: \"../mainManuscript\"\n%%% End:", "meta": {"hexsha": "da4e41b35ae59ddbfb14a9e7bd48d1e0d63d4cc5", "size": 5139, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "manuscript/chapter4/1dhpp.tex", "max_stars_repo_name": "adRenaud/research", "max_stars_repo_head_hexsha": "2f0062a1800d7a17577bbfc2393b084253d567f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-18T14:52:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-18T14:52:03.000Z", "max_issues_repo_path": "manuscript/chapter4/1dhpp.tex", "max_issues_repo_name": "adRenaud/research", "max_issues_repo_head_hexsha": "2f0062a1800d7a17577bbfc2393b084253d567f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-01-07T13:11:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-07T13:11:11.000Z", "max_forks_repo_path": "manuscript/chapter4/1dhpp.tex", "max_forks_repo_name": "adRenaud/research", "max_forks_repo_head_hexsha": "2f0062a1800d7a17577bbfc2393b084253d567f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1901408451, "max_line_length": 239, "alphanum_fraction": 0.7561782448, "num_tokens": 1926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.32582022322991394}}
{"text": "% File              : tensorRGflow.tex\n% Author            : Xinliang(Bruce) Lyu <lyu@issp.u-tokyo.ac.jp>\n% Date              : 12.02.2021\n% Last Modified Date: 20.03.2021\n% Last Modified By  : Xinliang(Bruce) Lyu <lyu@issp.u-tokyo.ac.jp>\n%% ****** Start of file apstemplate.tex ****** %\n%\\documentclass[aps,prb,preprint,groupedaddress]{revtex4-2}\n%\\documentclass[aps,prl,preprint,superscriptaddress]{revtex4-2}\n\\documentclass[aps,prr,reprint,superscriptaddress,nofootinbib,floatfix]{revtex4-2}\n% Enable some packages \n\\usepackage{footnote}\n\\usepackage{blindtext} \n\\usepackage{mathtools} \n\\usepackage{graphicx}\n\\usepackage[export]{adjustbox}\n\\graphicspath{{./}{figures/}}\n\\usepackage{amsmath} \n\\usepackage{amsfonts} \n\\usepackage{amssymb}\n\\usepackage{amstext} \n\\usepackage[english]{babel} \n\\usepackage{helvet}\n\\usepackage{microtype} \n\\usepackage[pdftex,hidelinks]{hyperref}\n\\hypersetup{\n    colorlinks=true,\n    linkcolor=blue,\n    filecolor=blue,\n    urlcolor=blue,\n    citecolor = blue,\n}\n\\usepackage{bbold} \n\\usepackage{mathrsfs} \n\\usepackage{makecell}\n\n\n\\DeclareMathOperator{\\Tr}{Tr}\n% Some new commands\n\\newcommand{\\rgeq}{\\stackrel{\\text{RG}}{=}}\n\\newcommand{\\defeq}{\\stackrel{\\text{def}}{=}}\n\\newcommand{\\svdeq}{\\stackrel{\\text{svd}}{=}}\n\\newcommand{\\rgapprox}{\\stackrel{\\text{RG}}{\\approx}}\n\\newcommand{\\ket}[1]{|#1\\rangle}\n\\newcommand{\\bra}[1]{\\langle#1|}\n\\newcommand{\\textapproxmy}[1]{\\stackrel{\\text{#1}}{\\approx}}\n\\newcommand{\\texteq}[1]{\\stackrel{\\text{#1}}{=}}\n\\newcommand{\\tTr}{\\mathrm{tTr}}\n\n% You should use BibTeX and apsrev.bst for references Choosing a journal\n% automatically selects the correct APS BibTeX style file (bst file), so\n% only uncomment the line below if necessary.\n%\\bibliographystyle{apsrev4-2}\n\n\\begin{document}\n%Title of paper\n\\title{Scaling dimensions from linearized tensor renormalization group transformations}\n\n%Authors\n\\author{Xinliang Lyu} \\email[]{lyu@issp.u-tokyo.ac.jp}\n%\\homepage[]{Your web page} \\thanks{} \\altaffiliation{}\n\\affiliation{Institute for Solid State Physics, The University of Tokyo,\nKashiwa, Chiba 277-8581, Japan} \\author{RuQing G. Xu}\n%\\email[]{r-xu@g.ecc.u-tokyo.ac.jp}\n\\affiliation{Department of Physics, The University of Tokyo, Tokyo\n    113-0033, Japan} \\author{Naoki Kawashima}\n    \\email[]{kawashima@issp.u-tokyo.ac.jp} \\affiliation{Institute for\n        Solid State Physics, The University of Tokyo, Kashiwa, Chiba\n    277-8581, Japan}\n\n\\date{\\today}\n\n\\begin{abstract} \n    We show a way to perform the canonical renormalization group (RG) prescription in tensor space: write down the tensor RG equation, linearize it around a fixed-point tensor, and diagonalize the resulting linearized RG equation to obtain scaling dimensions. \n    The tensor RG methods have had a great success in producing accurate free energy compared with the conventional real-space RG schemes.\n    However, the above-mentioned canonical procedure has not been implemented for general tensor-network-based RG schemes.\n    We extend the success of the tensor methods further to extraction of scaling dimensions through the canonical RG prescription, without explicitly using the conformal field theory.\n    This approach is benchmarked in the context of the Ising models in 1D and 2D.\n    Based on a pure RG argument, the proposed method has potential applications to 3D systems, where the existing bread-and-butter method is inapplicable.\n\\end{abstract}\n\n%\\maketitle must follow title, authors, abstract, and keywords\n\\maketitle\n\n% body of paper here - Use proper section commands References should be\n% done using the \\cite, \\ref, and \\label commands\n\\section{Introduction\\label{intro}}\nThe renormalization group (RG) is a powerful technique for studying physical systems where fluctuations in all scales of length are important~\\cite{wilsonNobel}; the most famous example in statistical mechanics is critical phenomena.\nThe main idea behind the RG is to study how a physical system changes as we go from one length scale to another.\nConventional RG schemes, such as $\\epsilon$-expansion~\\cite{wilson1972} and block-spin methods~\\cite{kadanoff1966,kadanoff1975,migdal,kadanoff1976,niemeijer1973}, aim at a map from the Hamiltonian of the short length scale to that of the longer one, such that the partition function is unchanged~\\cite{nonlinearRG}.\nThe map is known as an RG equation. \nA well-behaved RG equation exhibits fixed points, each corresponding to a conformal field theory (CFT)~\\cite{polchinski1988,nakayama2015}.\nA critical system is described by a fixed point.\nBy linearizing the RG equation around the critical fixed point, universal properties like scaling dimensions of the critical system can be extracted.\nThis canonical RG prescription also provides a theoretical framework to understand universality in critical phenomena.\nHowever, for a systematic study with high-precision, the Hamiltonian may not be the most efficient representation of the system.\n%\n\nRecently, ideas from quantum information have stimulated a novel type of RG methods in tensor space.\nThey are versatile numerical RG schemes whose approximations are controlled by an integer, $\\chi$, called the \\textit{bond dimension}.\nThe RG equation is a map from a tensor encapsulating the Boltzmann weights of local configurations at a short length scale to a new tensor at a longer one.\nThe first realization of this new paradigm is the tensor renormalization group (TRG)~\\cite{trg}, followed by many variations~\\cite{SRGa,SRGb,hotrg,atrg, triadtrg,morita2020global}.\nThese TRG-type techniques have excellent performance in calculations of free energy. \nFor example, the higher-order tensor renormalization group (HOTRG)~\\cite{hotrg} estimates the free energy of the 2D Ising model with error of order $10^{-7}$ within a few minutes in a desktop computer.\nThe estimation error decreases exponentially as $\\chi$ increases, while the computational costs only grow polynomially.\n%\n\nWith all of their success in calculations of free energy, however, the TRG-type techniques encounter obstacles in the canonical RG prescription. \nEarly attempts~\\cite{Berker2008,aoki2009,meurice2013,kadanoff2014} show that if the bond dimension $\\chi$ of the TRG is larger than 8, the tensor will \\textit{never} flow to the critical fixed point of the 2D Ising model; this imposes a very strong restriction on the bond dimension in the canonical RG prescription.\nFor $\\chi = 2, 3, 4$, either using the TRG or the HOTRG, the estimated scaling dimension of the energy density operator has accuracy similar to the old potential moving tricks~\\cite{Berker2008,aoki2009,meurice2013}, and that of the spin operator is more than a factor of 2 larger than the exact value~\\cite{kadanoff2014}.\n%\n\nFortunately, in recent ten years, people have developed many tricks to solve the problem of the unsatisfactory tensor RG flows.\nIn 2009, Gu and Wen~\\cite{GuWen2009} was the first to deal with this problem. \nThey followed Levin's suggestion~\\cite{trg,LevinTalk} and focused on a toy model called corner double-line (CDL) tensors, which represent systems with only local correlations. \nThey showed that the CDL tensors are fixed points of the TRG, indicating that the local correlations at the smaller length scales will be carried to the larger ones. \nA crude algorithm was proposed to filter out the CDL tensors and the problem of the tensor RG flows was partially solved, followed up by an improved algorithm in 2017~\\cite{looptnr}. \nFrom 2015 to 2017, several similar methods were proposed~\\cite{tnr,tnralgo,tnrplus}. \nAll of these advanced TRG-type techniques successfully produced critical fixed-point tensors. \n%\n\nWith a critical fixed-point tensor in hand, Gu and Wen~\\cite{GuWen2009} pointed out that the scaling dimensions can be extracted by diagonalizing a transfer matrix constructed from the fixed-point tensor according to a well-known 2D CFT theorem~\\cite{cardy1986}. \nGu and Wen's proposal gradually becomes the bread-and-butter method for TRG-type techniques to extract scaling dimensions of 2D systems. \nLater, Evenbly and Vidal used the tensor network renormalization (TNR)~\\cite{tnr,tnralgo} to implement local scale transformation that maps a plane to a cylinder~\\cite{EvenblyDilatationOp}; the spectrum of eigenvalues of a transfer matrix on the cylinder gives scaling dimensions.\nThese two methods have been applied to extract scaling dimensions from then on, while the canonical RG prescription in tensor space has never followed up.\n%\n% Figure: research background\n\\begin{figure}[tb]\n    \\includegraphics[width=1.0\\columnwidth,valign=c]{summaryintro.pdf}\n    \\caption{\\label{fig:researchBG}\n        Different ways to extract scaling dimensions using tensor RG methods.\n        The proposed method in this paper corresponds to the path indicated by the thick arrows.\n    }\n\\end{figure}\n% Figure end\n\nIn this paper, we provide the missing piece of carrying out, in the general prescription, the RG in tensor space at a general bond dimension (see Fig.~\\ref{fig:researchBG}).\nAfter laying down the general framework for the canonical RG prescription for the tensor RG methods in Sec.~\\ref{RGprescrip}, we point out two technical obstacles, local correlations and gauge redundancy, in Sec.~\\ref{sec:obstacles}.\nThe higher-order tensor renormalization group (HOTRG)~\\cite{hotrg} is combined with a recently-developed technique, graph-independent local truncation (GILT)~\\cite{gilts} in Sec.~\\ref{sec:gilthotrg}, to generate correct tensor RG flows that will go to a critical fixed point at a general bond dimension. \nIn Sec.~\\ref{sec:gaugefix}, we show that most gauge redundancy in the tensor description is automatically fixed in the proposed HOTRG-like scheme, leaving only tractable sign ambiguities.\nThe linearized RG equation of this HOTRG-like scheme is easy to implement and has a simple pictorial representation\\footnote{It should be noted that the linearized RG transformation looks similar to the local scale transformation of Ref.~\\cite{EvenblyDilatationOp}.\n        Since the canonical RG prescription here is applicable to any proper tensor RG methods, it is more general than the TNR local scale transformation.\n    }\n(see Fig.~\\ref{fig:linearedRGschem} and Eq.~\\eqref{eq:respMatGiltHOTRG}); in practice, it can be generated by automatic differentiation~\\cite{xiang2019adtrg} once the tensor RG equation is implemented.\nThe scaling dimensions can be extracted from this linearized RG equation.\nIn Sec.~\\ref{benchmark}, the canonical RG prescription in tensor space is benchmarked with the 1D and 2D classical Ising models.\nWe conclude in Sec.~\\ref{conclusion}.\n%\n% Figure: schematic figure of linearized RG\n\\begin{figure}[tb]\n    \\includegraphics[scale=0.9,valign=c]{linearedRGschem.pdf}\n    \\caption{\\label{fig:linearedRGschem}\n        Schematic diagram of the linearized tensor RG equation $\\mathcal{R}$. \n        It is a linear map from $\\delta A$ to $\\delta A_c$ and is determined by the fixed-point tensor $A^*$ and various related tensors shown explicitly in Eq.~\\eqref{eq:respMatGiltHOTRG}.\n        The computation costs of this linearized RG equation are $O(\\chi^7)$, the same as those of the tensor coarse graining, since the inner structure of $\\mathcal{R}$ resembles the tensor network in the coarse graining step in Eq.~\\eqref{def:RGeqGiltHOTRG}.\n    }\n\\end{figure}\n% Figure end\n\n\nThe proposed method fully exploits the RG interpretation of the TRG-type techniques and offers a better understanding of the nature of these tensor techniques as real-space RG transformations. \nSince the HOTRG can be viewed as a modern extension of the Migdal-Kadanoff RG~\\cite{migdal,kadanoff1976,meurice2013}, the canonical RG prescription based on the proposed HOTRG-like scheme develops the old Migdal-Kadanoff idea in tensor network language and makes it systematically improvable.\nMost notably, the method might be relevant in 3D, where Gu and Wen's method is inapplicable and Evenbly and Vidal's local-scaling-transformation idea is nontrivial to implement.\n%%%\n\n\\section{Renormalization group in tensor network language\\label{sec:RGtensorSpace}} \nTRG-type methods start with the fact that partition functions of all classical statistical models can be rewritten as tensor network models~\\cite{trg}.\nTake the square lattice 2D Ising model as a concrete example. The partition function is\n%\n\\begin{align}\\label{eq:2DIsingZ}\n    Z =\n\\sum_{\\{\\sigma(\\mathbf{r})\\}}e^{K\\sum_{\\langle i,j \\rangle}\\sigma_i \\sigma_j},\n\\end{align}\n%\nwhere $\\sigma_i$ is the shorthand for the spin variable $\\sigma(\\mathbf{r}_i)$ located at lattice point $\\mathbf{r}_i$ and can take values $\\pm 1$, and $K = J / k_B T$.\nIn this paper, we measure temperature in units of $J / k_B $ so it becomes a dimensionless number.\nThe partition function in Eq.~\\eqref{eq:2DIsingZ} can be rewritten as a tensor network by defining a tensor \n%\n\\begin{align}\\label{def:tensorA}\n    A_{\\sigma_i \\sigma_j \\sigma_k \\sigma_l}\n\\equiv e^{K(\\sigma_i\\sigma_j + \\sigma_j\\sigma_k + \\sigma_k\\sigma_l +\n\\sigma_l\\sigma_i)}\n= \\includegraphics[scale=0.8,valign=c]{defAtensor.pdf}\\text{ }.\n\\end{align}\n%\nEach index of this tensor can take two values $\\pm 1$ and we say the bond dimension of a leg of this tensor is $\\chi = 2$.\nIt is now possible to rewrite the partition function of the 2D Ising model in Eq.~\\eqref{eq:2DIsingZ} as the tensor product of $N$ copies of $A$, with all their indices summed over (Fig.~\\ref{fig:spin2tensor})\n%\n\\begin{align}\\label{eq:ZbeforeRG}\n    Z = \\sum_{\\{ \\sigma(\\mathbf{r}) \\}}\n    \\bigotimes^{N}_{x=1}A_{\\sigma_{i(x)} \\sigma_{j(x)} \\sigma_{k(x)} \\sigma_{l(x)}}\n    \\equiv \\tTr\\left(\\bigotimes_{x=1}^{N}A\\right),\n\\end{align}\n%\nwhere the last equal sign defines the $\\tTr$ symbol.\n%\n% Figure: mapping from spins on lattice to a tensor network\n\\begin{figure}[tb]\n    \\includegraphics[scale=0.8]{spin2tensor.pdf}\n    \\caption{\\label{fig:spin2tensor}\n        Representation of the local Boltzmann weight in terms of tensors.\n        The dots are where the spin variables locate.\n        They form a square lattice slanted by $45^\\circ$.\n        The larger circles are tensors $A$ encoding the Boltzmann weight of the configurations of the four surrounding spin variables.\n    The square lattice formed by $N$ copies of $A$ is the tensor network representation of the partition function in Eq.~\\eqref{eq:ZbeforeRG}.\n}\n\\end{figure}\n% Figure end\n\n\nThe coarse graining of the tensor network resembles the conventional block-spin methods.\nWe replace a patch of, say, four copies of the original tensor $A$ with one coarse-grained tensor $A_c$, such that the partition function is approximately described by a coarser tensor network made of $N/4$ copies of $A_c$\n%\n\\begin{align}\\label{eq:ZafterRG}\n    Z \\approx \\tTr\\left(\\bigotimes_{x=1}^{N/4}A_c\\right).\n\\end{align}\n%\nThe specific procedure for obtaining $A_c$ from $A$ will be discussed later in Sec.~\\ref{sec:gilthotrg}. The map, \n%\n\\begin{align}\\label{def:tensorRGeq}\n    A \\xrightarrow{\\text{RG}} A_c \\text{ or } A_c = \\mathcal{T}(A), \n\\end{align}\nis the tensor RG equation if the gauge redundancy of the tensor is properly fixed (see Sec.~\\ref{sec:obstacles} and Sec.~\\ref{sec:gaugefix} for detailed discussions about gauge redundancy in tensor network language and how it is fixed).\n%\n\n\\subsection{General framework\\label{RGprescrip}}\nWe first define the \\textit{canonical} RG prescription in tensor space.\nTo this end, it is helpful to start with a review of the old approach in Hamiltonian space (we follow the detailed review~\\cite{kadanoff2014} and textbook~\\cite{cardy_1996} closely).\n%\n\nIt will be convenient to explain in terms of a specific physical system, a classical system with spin variables $\\sigma \\in \\{+1, -1\\}$ on a lattice, with general short-ranged interactions.\nThe Hamiltonian (or energy) of the system can be parameterized by a set of coupling constants $\\mathbf{K} = \\{K_j\\}$, each of which couples to a possible short-ranged interaction term $s_j(\\mathbf{r})$,\n%\n\\begin{align}\\label{eq:generalspinHam}\n    \\mathcal{H} = \\sum_{\\mathbf{r}} \\sum_{j} K_j s_j(\\mathbf{r}).\n\\end{align}\n%\nFor example, if $K_1$ is the magnetic field, $s_1(\\mathbf{r}) = \\sigma(\\mathbf{r})$ is the spin variable at lattice point $\\mathbf{r}$; if $K_2$ is the nearest neighbor interaction along $x$ direction, $s_2(\\mathbf{r}) = \\sigma(\\mathbf{r})\\sigma(\\mathbf{r} + a\\hat{\\mathbf{e}}_x)$, where $\\hat{\\mathbf{e}}_x$ is the unit vector along $x$ direction and $a$ is the lattice constant. \nA conventional RG transformation maps the old Hamiltonian $\\mathcal{H}$ to a new one $\\mathcal{H}'$ \\textit{with the same form as} Eq.~\\eqref{eq:generalspinHam} but characterized by a set of new coupling constants $\\mathbf{K}' = \\{ K_j'\\}$. \nThe map from the old Hamiltonian to the new one $\\mathcal{H} \\xrightarrow{\\text{RG}} \\mathcal{H}'$ is then parametrized explicitly as the transformation from the old coupling constants to the new ones,\n%\n\\begin{align}\\label{eq:oldRGK}\n    \\mathbf{K}' = \\mathcal{T}^{\\text{old}}\\left(\\mathbf{K}\\right).\n\\end{align}\n%\nWe require that the RG transformation should preserve the partition function of the system and should exhibit a fixed-point Hamiltonian $\\mathcal{H}^{*}$ parameterized by coupling constants $\\mathbf{K}^{*}$, such that $\\mathbf{K}^{*}$ remains unchanged under the RG transformation,\n%\n\\begin{align}\\label{eq:oldRGKstar}\n    \\mathbf{K}^{*} =\n    \\mathcal{T}^{\\text{old}}\\left(\\mathbf{K}^{*}\\right).\n\\end{align}\n%\n\nThe linearized RG equation around $\\mathbf{K}^{*}$ is defined in the following way.\nWe perturb the coupling constants around the fixed point $\\mathbf{K} = \\mathbf{K}^{*} + \\delta \\mathbf{K}$ and perform the RG transformation defined in Eq.~\\eqref{eq:oldRGK}. \nThe new coupling constants $\\mathbf{K}'$ after the RG transformation should be close to $\\mathbf{K}^{*}$ by continuity, so $\\mathbf{K}' = \\mathbf{K}^{*} + \\delta \\mathbf{K}'$.\nThe linearized RG equation around $\\mathbf{K}^{*}$ is a matrix $\\mathcal{R}^{\\text{old}}$ telling us how $\\delta \\mathbf{K}'$ is related to $\\delta \\mathbf{K}$,\n%\n\\begin{align}\\label{eq:respMat}\n    \\delta K_i' = \\sum_j\\mathcal{R}^{\\text{old}}_{ij} \\delta K_j.\n\\end{align}\n%\nThe matrix $\\mathcal{R}^{\\text{old}}$ has right and left eigenvectors $\\{\\psi^{\\alpha}\\}, \\{\\phi^{\\alpha}\\}$ with the same set of eigenvalues $\\{\\lambda^{\\alpha}\\}$,\n%\n\\begin{align}\\label{eq:eigsofRespM}\n    \\sum_j \\mathcal{R}^{old}_{ij} \\psi^{\\alpha}_j = \\lambda^{\\alpha}\n    \\psi^{\\alpha}_i \\text{ and } \\sum_i \\phi^{\\alpha}_i\n    \\mathcal{R}^{old}_{ij} = \\lambda^{\\alpha} \\phi^{\\alpha}_j.\n\\end{align}\n%\nThe linear combinations of $\\delta K_i$ according to the components of the left eigenvector $\\phi^{\\alpha}$ are known as scaling fields\n%\n\\begin{align}\\label{def:scalingfields}\n    h^{\\alpha} = \\sum_i \\phi^{\\alpha}_i \\delta K_i,\n\\end{align}\n%\nwhile the linear combinations of interaction terms $s_j(\\mathbf{r})$ according to the components of the right eigenvector $\\psi^{\\alpha}$ are known as scaling operators\n%\n\\begin{align}\\label{def:scalingOpt}\n    o^{\\alpha}(\\mathbf{r}) = \\sum_j s_j(\\mathbf{r}) \\psi^{\\alpha}_j.\n\\end{align}\n%\nUnder the RG transformation with rescaling factor $b$ for a system in dimension $d$, the scaling fields and the scaling operators transform in a simpler way with \n%\n\\begin{align}\\label{eq:transfho}\n    \\left(h^{\\alpha} \\right)' = b^{d - x_{\\alpha}} h^{\\alpha} \\text{ and }\n    \\left(o^{\\alpha}\\right)' = b^{x_{\\alpha}} o^{\\alpha},\n\\end{align}\nwhere $x_{\\alpha}$ are the scaling dimensions of the scaling operators $o^{\\alpha}(\\mathbf{r})$. \nEquations~\\eqref{eq:respMat} to~\\eqref{def:scalingfields} and~\\eqref{eq:transfho} give the relation between the scaling dimensions $\\{x_{\\alpha}\\}$ and the eigenvalues $\\{\\lambda^{\\alpha}\\}$ of the linearized RG equation, \n%\n\\begin{align}\\label{eq:lambda2x}\n    b^{d-x_{\\alpha}} = \\lambda^{\\alpha}.\n\\end{align}\n%\n\nNext, we move on to the tensor approach of the canonical RG prescription.\nIn the tensor RG approach, we skip the Hamiltonian description of the system. \nInstead, we use a tensor network made of copies of tensor $A$ to represent the partition function $Z$ of the system. \nThe tensor RG equation is a map from the tensor $A$ to the coarser tensor $A_c$, as is shown in Eq.~\\eqref{def:tensorRGeq}.\nWe claim that the components of the tensor $A$ can be thought of as some proxies of the coupling constants $\\mathbf{K}$ (this claim was hinted in Ref.~\\cite{GuWen2009}).\n%\n\nTo see why this claim is reasonable, note that we can map the partition function of the system with Hamiltonian in Eq.~\\eqref{eq:generalspinHam} to a tensor network using the method introduced in Ref.~\\cite{trg}. \nEach component of the initial tensor $A$ is the Boltzmann weight of a given local configuration and depends on the coupling constants,\n%\n\\begin{align}\\label{eq:K2A}\n    A_{(i)} = f_{(i)}\\left(\\mathbf{K}\\right),\n\\end{align}\n%\nwhere we group all legs of $A$ to form a single index, $A_{(i)}\\equiv A_{i_1 i_2 i_3 i_4}$. \nAfter coarse graining, the components of $A_c$ are still functions of $\\mathbf{K}$ but\nwith different functional forms,\n%\n\\begin{align}\\label{eq:tensorEleRG}\n    \\left(A_c\\right)_{(i)} =\n\\left(f_c\\right)_{(i)}\\left(\\mathbf{K}\\right).\n\\end{align}\n%\nNow, we require that each component of the coarser tensor $A_c$ should have the same functional form as that of $A$, but with different coupling constants $\\mathbf{K}'$,\n%\n\\begin{align}\\label{eq:tensorK2Kp}\n    f_{(i)}\\left(\\mathbf{K}'\\right) =\n    \\left(f_c\\right)_{(i)}\\left(\\mathbf{K}\\right), \\forall (i).\n\\end{align}\n%\nIn the old Hamiltonian approach, we need to solve Eq.~\\eqref{eq:tensorK2Kp} for $\\mathbf{K}'$ in terms of $\\mathbf{K}$, which defines the RG equation from the old $\\mathbf{K}$ to the new $\\mathbf{K}'$. \nHowever, in the tensor approach, it is enough to know the existence of such $\\mathbf{K}'$. Combine Eq.~\\eqref{eq:tensorEleRG} and Eq.~\\eqref{eq:tensorK2Kp}, we have\n%\n\\begin{align}\\label{eq:Kp2A}\n    \\left(A_c\\right)_{(i)} = f_{(i)}\\left(\\mathbf{K}'\\right).\n\\end{align}\n%\nAt the fixed point, $\\mathbf{K} = \\mathbf{K}' = \\mathbf{K}^*$, equations~\\eqref{eq:K2A} and \\eqref{eq:Kp2A} give\n%\n\\begin{align}\\label{eq:tensorRGAstar}\n    A^* \\xrightarrow{\\text{RG}} A^* \\text{ or }A^* = \\mathcal{T}\\left(A^* \\right).\n\\end{align}\n%\nTake the total derivative of tensors $A$ and $A_c$ in Eqs.~\\eqref{eq:K2A} and \\eqref{eq:Kp2A} and set $\\mathbf{K} = \\mathbf{K}' = \\mathbf{K}^*$, \n%\n\\begin{align}\n    \\delta A_{(i)} = \\sum_n \\left(\\partial_{(n)}\n    f_{(i)}\\right)\\Bigr|_{\\mathbf{K} = \\mathbf{K}^*} \\delta K_n,\n    \\label{eq:deltaK2deltaA} \\\\\n    \\left(\\delta A_c \\right)_{(i)} = \\sum_n \\left(\\partial_{(n)}\n    f_{(i)}\\right)\\Bigr|_{\\mathbf{K}' = \\mathbf{K}^*} \\delta\n    K_n'.\\label{eq:deltaK2deltaAp}\n\\end{align}\n%\nEquations~\\eqref{eq:deltaK2deltaA} and \\eqref{eq:deltaK2deltaAp} give the transformation law between the coupling-constant description and tensor description of the canonical RG prescription, with $\\partial_{(n)}f_{(i)}$ evaluated at $\\mathbf{K}^*$ being the change of basis matrix.\nUnder this transformation, the linearized RG equation in Eq.~\\eqref{eq:respMat} becomes\n%\n\\begin{align}\\label{eq:respMatTen}\n    \\left(\\delta A_c\\right)_{(i)} = \\sum_j\n    \\mathcal{R}_{(i)(j)} \\delta A_{(j)},\n\\end{align}\n%\nwhich defines the linearized RG equation in tensor space.\nSince Eqs.~\\eqref{eq:respMat} and \\eqref{eq:respMatTen} are the same linear transformation in two different representations, we can equally well diagonalize the matrix $\\mathcal{R}_{(i)(j)}$ and find scaling dimensions according to Eq.~\\eqref{eq:lambda2x}. \n%\n\nIn Sec.~\\ref{benchmark:1DIsing}, we will use the 1D Ising model as a\nconcrete example to demonstrate the general argument above.\n%\n\n\\subsection{Technical obstacles\\label{sec:obstacles}}\nThere are two major obstacles for the canonical RG prescription in tensor space: the problem of local correlations and the gauge redundancy in tensor network language. \nThey prevent us from obtaining a fixed-point tensor satisfying Eq.~\\eqref{eq:tensorRGAstar}.\n%\n\nLevin and Nave anticipated the problem of local correlations when looking for fixed points of the RG equation of the TRG~\\cite{LevinTalk}.\nOne of the earliest numerical evidence for the peculiar tensor RG flows of the 2D Ising model was provided by Hinczewski and Berker~\\cite{Berker2008}. \nTheir results indicate that the TRG-type techniques have difficulty in integrating out all the local correlations at short distances, so physics at the original lattice scale is carried all the way to the physics at larger ones. \nThis shortcoming of the TRG-type techniques makes identification of both non-critical and critical fixed-point tensors very difficult.\n%\n\nTo understand how the problem of local correlations at the lattice scale arises in the TRG-type techniques, let us examine the physical picture of the tensor RG transformation.\nWe focus on a concrete example of a tensor network made of $4 \\times 4 = 16$ copies of tensor $A$ shown in Fig.~\\ref{fig:spin2tensor} with periodic boundary condition.\nThe general picture of a tensor RG transformation is similar to the conventional block-spin methods.\nFor example, we block a square of four tensors by contracting legs between them and group every two legs in the same side. Call the new tensor $A_c$,\n%\n\\begin{align}\\label{eq:ZunderRG} \n    Z_{4 \\times 4} = \n    \\includegraphics[scale=1.0,valign=c]{Z-TNblock.pdf}\n    \\rgeq \n    \\includegraphics[scale=0.8,valign=c]{Z-underRG.pdf},\n\\end{align}\nwhere \n%\n\\begin{align}\\label{eq:exactBlock}\n    \\includegraphics[scale=0.8,valign=c]{Ac-thickleg.pdf}\n    \\equiv \n    \\includegraphics[scale=0.8,valign=c]{block4As.pdf}.\n\\end{align}\n%\nIt is enlightening to put the original spin variables back into the tensor network to get a more physical picture of what is happening under such a block-tensor RG transformation. \nWe refrain from drawing legs of $A$ and the dashed lines of the spin lattice in Fig.~\\ref{fig:spin2tensor}, and surround copies of $A$ with squares on whose sides the spin variables sit. \nThe big picture for the block-tensor transformation in Eq.~\\eqref{eq:ZunderRG} is shown schematically in Fig.~\\ref{fig:rgschem}(a).\n%\n% RG directly in both tensor and original spin decimation language\n\\begin{figure}[t]\n    \\includegraphics[scale=0.9,valign=c]{rgschem.pdf}\n    \\caption{\\label{fig:rgschem}\n        The origin of the problem of local correlations.\n        (a) The block-tensor transformation $A\\rightarrow A_c$. \n        The spins shared by two tensors $A$ are summed over according to Eq.~\\eqref{eq:exactBlock}. \n        The squares are larger after the decimation.\n        (b) The origin of the\n        CDL tensors. When the black square becomes large enough, the\n        spins on one edge are far away from those on another, except for\n        the spins around the four corners. The correlations among the\ncorner spins give rise to the CDL tensors, containing physics at the\nlattice scale.\n} \n\\end{figure}\n%\nThe process is similar to the decimation in the conventional approaches.\nAfter the spin variables shared by every two $A$ tensors forming the same $A_c$ are summed over, we are left with four bigger squares, with two spin variables sitting on each side of each square.\nWhen the squares become large enough as the block-tensor transformation goes on, we expect that, roughly speaking, the spin variables on different edges are far away from each other and thus uncorrelated. \nThe only exception is for the spin variables around the four corners.\nWe can use a matrix $C$ in Fig.~\\ref{fig:rgschem}(b) to capture the correlations around the corners; the matrix $C$ must contain physics at the scale of the original lattice constant. \nSince the spin variables around different corners are far away from each other, the tensor $A^{\\text{CDL}}$ corresponding to this black square should factorize into the tensor product of four corner matrices $C$. \nA tensor with the structure of $A^{\\text{CDL}}$ is called a corner double-line (CDL) tensor.\n%\n\nThe CDL tensors are fixed points of the RG equations of the TRG~\\cite{LevinTalk,GuWen2009,tnr,gilts} and the HOTRG~\\cite{hotrgfixpoint}.\nThis shows that the TRG and the HOTRG have difficulty in integrating out the local interactions among the spin variables around the corners. \nIf we start with two temperatures $T_1 \\neq T_2$, both larger than the critical temperature $T_c$ of the 2D Ising model, either of these two methods will generate tensors flowing to two different CDL tensors $A^{\\text{CDL}}_1 \\neq A^{\\text{CDL}}_2$, as a natural consequence of the fact that these CDL tensors depend, directly, on the bare interaction constants. \nAt criticality, the previous numerical calculations indicate that we will never reach a critical fixed-point tensor~\\cite{Berker2008,tnr}.\nTheir calculations suggest tensor RG flows shown in Fig.~\\ref{fig:tensorRGflow}(b), where the low- and high-temperature fixed points turn into two fixed lines and the critical fixed point disappears. \nBy comparison, the correct RG flow is shown in Fig.~\\ref{fig:tensorRGflow}(a).\nWe will introduce a way to solve the problem of CDL tensors for the HOTRG in Sec.~\\ref{sec:gilthotrg}.\n%%% Figure: schematic RG flows\n\\begin{figure}[t]\n    \\includegraphics[scale=0.9,valign=c]{tensorRGflowSchem.pdf}\n    \\caption{\\label{fig:tensorRGflow}\n        Schematic RG flows of the 2D Ising model, without and with the problem of local correlations.\n        Each point on the dashed line represents the lattice model at a given temperature and is the starting point of an RG transformation.\n        The solid lines with arrows represent different RG flows.\n        (a) The correct RG flow. There are one $T=0$ fixed point, one $T=\\infty$ fixed point and one critical fixed point.\n        (b) The RG flows generated by the TRG and the HOTRG\\@.\n        Due to the problem of local correlations, the two trivial fixed points become two fixed lines, and the critical fixed point disappears.\n    }\n\\end{figure}\n%\n\nThe second obstacle that prevents us from achieving Eq.~\\eqref{eq:tensorRGAstar} is that the tensor network representation of the partition function in Fig.~\\ref{fig:spin2tensor} and Eq.~\\eqref{eq:ZbeforeRG} has gauge redundancy.\nIf two tensors $\\tilde{A}$ and $A$ are related through some invertible matrices $S_x,S_y$ by the gauge transformation\n%\n\\begin{subequations}\\label{def:gaugeTrans}\n    \\begin{align}\\label{def:gaugeTransMath}\n        \\tilde{A}_{ijkl} = \\sum_{\\substack{m,n\\\\p,q}} A_{mnpq} \\left(S_x\n        \\right)_{im} \\left(S_y \\right)_{jn} \\left(S_x^{-1}\\right)_{pk}\n        \\left(S_y^{-1}\\right)_{ql}, \n    \\end{align}\nor pictorially as\n    \\begin{align}\\label{def:gaugeTransPic}\n        \\includegraphics[scale=0.8,valign=c]{Atilde.pdf}\n    =\n        \\includegraphics[scale=0.8,valign=c]{AsimilarTrans.pdf},\n    \\end{align}\n\\end{subequations}\n%\nthe two tensor networks formed by $A$ and $\\tilde{A}$ represent the same partition function $Z$.\nEquation~\\eqref{def:gaugeTrans} is a equivalence relation that defines a equivalence class $[A]$.\n%\n\nThe gauge redundancy makes the canonical RG prescription in tensor space less straightforward than that in Hamiltonian space.\nEven if we have reached a representation tensor $A^*$ of the fixed-point equivalence class $[A^*]$, the coarse graining process could bring this tensor to another representation of $[A^*]$, \n%\n\\begin{align}\\label{eq:tensorRGAstarnotfix}\n    A^* \\xrightarrow[\\text{graining}]{\\text{coarse}} \\tilde{A}^*. \n    % \\text{ or } \n    %\\tilde{A}^* = \\mathcal{T}\\left(A^* \\right).\n\\end{align}\n%\nIn general, we must fix the gauge of the tensor during a tensor RG transformation by choosing a preferred set of basis, so that the fixed-point tensor is manifestly fixed, as is shown in Eq.~\\eqref{eq:tensorRGAstar}.\nWe will show how to fix the gauge in Sec.~\\ref{sec:gaugefix}.\n%\n\n\\subsection{Filtering out local correlations for the HOTRG\\label{sec:gilthotrg}}\nIn this subsection, we present an HOTRG-like scheme to solve the first technical obstacle, the problem of local correlations.\nCompared with the state-of-the-art TRG-type methods~\\cite{GuWen2009,tnr,tnralgo,tnrplus,looptnr,harada2018,fet,tns,tensor-ring,gilts} that are free of this problem, the proposed scheme can be most easily generalized to 3D and higher and is convenient for the subsequent gauge fixing and linearization procedure.\nSpecifically, the graph-independent local truncation (GILT)~\\cite{gilts} is performed to filter out the problematic local correlations before the coarse graining of the HOTRG\\@.\nWhile the GILT may not be the unique solution for removing the local correlations, we adopt it mainly for its conceptual simplicity and ease in adoption.\n%\n\nThe key feature of the GILT is that it is a stand-alone procedure to filter out the local correlations and does not change the geometry of a given tensor network, so it is very flexible.\nIt has been shown that the TRG combined with GILT is able to generate correct tensor RG flows for the 2D Ising model~\\cite{gilts} and the 2D $\\phi^4$ theory~\\cite{Delcamp2020}.\nFigure~\\ref{fig:gilt} summarizes the basic process of the GILT. \nThe loop containing four matrices $C$ inside the plaquette represents the local correlations (see Fig.~\\ref{fig:rgschem}(b) and imagine putting four CDL tensors together to form a plaquette). \nThe first step, which is the most crucial one, is to insert a low-rank matrix $Q$ into the leg we wish to truncate. \nThe tensor network after the insertion should give a good approximation of the initial one.\nThe remaining two steps are exact. We split $Q$ into two pieces using singular value decomposition and absorb the two pieces into the adjacent two $A$ tensors. \nThe bond dimension of the leg is smaller and the local correlations on this leg are filtered out. \n%\n\nNext, we move on to explain the HOTRG~\\cite{hotrg}.\nThe block-tensor transformation in Eqs.~\\eqref{eq:ZunderRG} and~\\eqref{eq:exactBlock} is exact but not practical, since the bond dimension grows exponentially in the original lattice size.\nThe HOTRG is an approximate tensor RG transformation, which can keep the bond dimension from growing.\nFor the HOTRG in the vertical direction, we aim at the following approximation of a local patch of two copies of $A$ put together vertically,\n%\n\\begin{align}\\label{eq:hotrgProjTrun}\n    \\includegraphics[scale=0.8,valign=c]{twoAProj.pdf}\n    \\approx \n    \\includegraphics[scale=0.8,valign=c]{twoA.pdf},\n\\end{align}\n%\nwhere $w$ is an isometric tensor to be determined and $w^{\\dagger}$ its hermitian conjugate.\nThe isometry $w$ is a linear mapping: $\\mathbb{V}_{\\tilde{\\chi}} \\rightarrow  \\mathbb{V}_{\\chi}\\otimes\\mathbb{V}_{\\chi}$, where $\\mathbb{V}_{\\chi}$ denotes a $\\chi$-dimensional vector space, and the isometry satisfies $w^{\\dagger}w = \\mathbb{1}$.\nWe will later see that the isometric condition of tensor $w$ makes the gauge fixing in the HOTRG easier.\nIt is shown in Ref.~\\cite{hotrg,tnralgo} that a good approximation can be achieved if the isometry $w$ is a collection of $\\tilde{\\chi}$ eigenvectors corresponding to the first $\\tilde{\\chi}$ largest eigenvalues of the $\\chi^2$-by-$\\chi^2$ positive semi-definite matrix $MM^{\\dagger}$, with the matrix $M$ defined as\n%\n\\begin{align}\\label{def:M-AA} \n    M = \n    \\includegraphics[scale=0.9,valign=c]{M-AA.pdf}\n    \\equiv \n    \\includegraphics[scale=0.8,valign=c]{twoA2M.pdf}.\n\\end{align}\n%\nWe use the approximation in Eq.~\\eqref{eq:hotrgProjTrun} to replace all pairs of $A$ tensors in the tensor network representation of the partition function $Z_{4\\times4}$ in Eq.~\\eqref{eq:ZunderRG} to get\n%\n\\begin{align}\\label{eq:Zapproxy} \n    Z_{4 \\times 4}\n&\\textapproxmy{\\eqref{eq:hotrgProjTrun}}\n    \\includegraphics[scale=1.0,valign=c]{Z-approy.pdf}\n    \\nonumber\\\\ &= \n    \\includegraphics[scale=1.0,valign=c]{Z-contry.pdf},\n\\end{align}\n%\nwhere in the second step, we contract two $A$ tensors and $w, w^{\\dagger}$ in the dashed circle to get a coarser tensor $A'$,\n%\n\\begin{align}\\label{def:Apycontr}\n    \\includegraphics[scale=1.0,valign=c]{Ap-ycontr.pdf}\n    \\equiv \n    \\includegraphics[scale=0.8,valign=c]{twoAcoarse.pdf}.\n\\end{align}\n%\nNotice in the approximation step in Eq.~\\eqref{eq:Zapproxy}, we move the two leftmost $w$ tensors to the right because we have a periodic boundary condition. \nEquation~\\eqref{def:Apycontr} defines the HOTRG coarse graining in the vertical direction.\nWe usually choose $\\tilde{\\chi} \\leq \\chi_{\\text{max}}$ in Eq.~\\eqref{eq:hotrgProjTrun} to prevent the bond dimension from growing.\n%\n\nIn Appendix~\\ref{append:gilthotrg}, we demonstrate how to choose the plaquettes and where to insert the low-rank matrices in the GILT to filter out the local correlations for the HOTRG\\@. \nThe resultant coarse graining in the vertical direction looks similar to Eq.~\\eqref{def:Apycontr}, only with a few more pieces of the low rank matrices from the GILT inserted into the bonds between the tensor $A$ and the isometric tensors $w, w^{\\dagger}$.\nThe two coarse-graining steps in both vertical and horizontal directions together define the RG equation of this HOTRG-like scheme (before the gauge fixing),\n%\n\\begin{align}\\label{def:RGeqGiltHOTRG}\n    \\includegraphics[scale=1.0,valign=c]{Ac-hotrg.pdf}\n    =\n    \\includegraphics[scale=0.8,valign=c]{rgEq4GiltHOTRG.pdf}.\n\\end{align}\n%\nThe computational costs of the determination of all the isometric tensors and low-rank matrices are $O(\\chi^6)$, while those of the contraction of the tensor network on the right hand side of Eq.~\\eqref{def:RGeqGiltHOTRG} are $O(\\chi^7)$.\nThe computation costs of this HOTRG-like coarse graining are thus $O(\\chi^7)$, the same as the original HOTRG\\@.\n%\n\nThe coarse graining defined in Eq.~\\eqref{def:RGeqGiltHOTRG} is able to simplify the $A^{\\text{CDL}}$ tensor in Fig.~\\ref{fig:rgschem}(b) to a single number, \n%\n\\begin{align}\\label{eq:CDL2number}\n    \\includegraphics[scale=1.0,valign=c]{singleCDL.pdf}\n    \\xrightarrow{\\text{Eq.~\\eqref{def:RGeqGiltHOTRG}}}\n    \\left(\n        \\includegraphics[scale=0.8,valign=c]{CDLnumber.pdf}\n    \\right)^4.\n\\end{align}\n%\nEquation~\\eqref{eq:CDL2number} shows that this HOTRG-like  scheme can successfully filter out the local correlations among the spin variables around the corners at the lattice scale (see Fig.~\\ref{fig:rgschem}(b)).\nSince the CDL tensors are no longer fixed points for the RG equation of this HOTRG-like scheme, the peculiar fixed lines in Fig.~\\ref{fig:tensorRGflow}(b) generated by the HOTRG will collapse to fixed points; we expect that Eq.~\\eqref{def:RGeqGiltHOTRG} is able to exhibit the critical fixed point tensor shown schematically in Fig.~\\ref{fig:tensorRGflow}(a).\n%\n%%% Figure: summary of the GILT\n\\begin{figure}[t]\n    \\includegraphics[scale=0.9,valign=c]{gilt.pdf}\n    \\caption{\\label{fig:gilt}\n        The process of the GILT. \n        Four copies of $C$ matrices are unknown inner structure of the adjacent 4-leg tensors.\n        They are drawn explicitly to make the demonstration clearer.\n        In the first step, a low-rank matrix $Q$ is inserted into a bond. Then we split $Q$ into two pieces using singular value decomposition. \n        The low-rank matrix $Q$ is constructed so that it cuts the legs of the corner matrices $C$ during the splitting. \n        Finally, the pieces of the matrix $Q$ are absorbed into the two neighboring tensors. \n        The original GILT paper~\\cite{gilts} presents a nice way to determine the low-rank matrix $Q$.\n        A brief introduction is provided in Appendix~\\ref{append:gilthotrg}.\n    }\n\\end{figure}\n%\n\n\\subsection{Gauge fixing and the linearized tensor renormalization group transformation\\label{sec:gaugefix}}\nWe show how the gauge is fixed and give the explicit expression of the linearized RG equation of the HOTRG-like scheme in this subsection.\n%\n\nPart of the gauge can be fixed if the physical model possesses a global internal symmetry.\nThe global symmetry can be incorporated into the tensor network representation of the model~\\cite{Singh2010SymTen,Singh2011U1Ten,Singh2012SU2Ten}; it is a generalization of Schur's lemma from matrices to general tensors.\nFor the 2D Ising model, $\\mathbb{Z}_2$ symmetry can be imposed.\nEach index of the tensor $A$ breaks into even and odd sectors.\nHalf of the gauge is fixed since $A$ is in the basis where the states in the even sector transform trivially and\nthe states in the odd sector is multiplied by $-1$ under the spin flip operation.\n%\n\nMost of the remaining gauge in the degenerate sectors of $A$ can be fixed by going to the diagonal basis of the tensor.\nWe show how the $S_x$ gauge redundancy in Eq.~\\eqref{def:gaugeTrans} is fixed. The $S_y$ one can be dealt with in the same way.\nGiven a tensor $A$, we first contract its two vertical legs to produce a transfer matrix $N_x$,\n%\n\\begin{align}\\label{def:Nx}\n    \\includegraphics[scale=0.8,valign=c]{Nx.pdf}\n    = \n    \\includegraphics[scale=0.8,valign=c]{AvertContr.pdf}.\n\\end{align}\n%\nWe then find the eigenvalue decomposition of this matrix,\n\\begin{align}\\label{eq:eigdcpNx}\n    \\includegraphics[scale=0.8,valign=c]{Nx.pdf}\n    = \n    \\includegraphics[scale=0.8,valign=c]{eigdcpNx.pdf}\\text{ },\n\\end{align}\n%\nwhere $\\lambda$ is the diagonal matrix encoding eigenvalues.\nThe gauge fixing transformation in the horizontal direction is defined by acting the invertible matrix $W_x$ and its inverse on the horizontal legs of the tensor $A$,\n%\n\\begin{align}\\label{def:gaugefixHori}\n    \\includegraphics[scale=0.8,valign=c]{Aold.pdf}\n    \\xrightarrow[\\text{gauge fixing}]{\\text{horizontal}} \n    \\includegraphics[scale=0.8,valign=c]{gaugefixAhori.pdf}.\n\\end{align}\n%\nIt is shown in Appendix~\\ref{append:proofgaugefix} that the above procedure fully fixes the gauge redundancy in two horizontal legs except the phase ambiguities if there is no degeneracy in the spectrum of $N_x$. \n%\n\nThe gauge fixing procedure described in Eqs.~\\eqref{def:Nx} to~\\eqref{def:gaugefixHori} is general for all TRG-type techniques.\nHowever, this procedure is not necessary for the HOTRG-like scheme applied to systems with spatial reflection symmetries like the 2D Ising model, since the RG equation in Eq.~\\eqref{def:RGeqGiltHOTRG} has a preferred set of basis.\nAs a result, the gauge redundancy in Eq.~\\eqref{def:gaugeTrans} collapses into phase ambiguities (or sign ambiguities for real tensors) in the HOTRG-like scheme\\@.\nTo make things as simple as possible, we focus on real tensors in the following discussions.\nThe generalization to complex tensors is straightforward.\n%\n\n% Write the tensor RG equation in Eq.~\\eqref{def:RGeqGiltHOTRG} schematically as $A_c = \\mathcal{T}\\left(A\\right)$.\nFor two real tensors $A, \\tilde{A}$ that are related by the gauge transformation defined in Eq.~\\eqref{def:gaugeTrans} where we further restrict $S_x,S_y$ to be orthogonal matrices, the new tensors generated by Eq.~\\eqref{def:RGeqGiltHOTRG}, $A_c$ and $ \\tilde{A}_c$, are equal up to sign ambiguities,\n%\n\\begin{align}\\label{eq:signAmbi}\n    \\left(\\tilde{A}_c \\right)_{ijkl} =\n    \\left(A_c\\right)_{ijkl}(d_x)_i (d_y)_j (d_x)_k (d_y)_l, \n\\end{align}\n%\nwhere $d_x,d_y$ are vectors with components $\\pm 1$. \nThe proof of the property of the HOTRG-like scheme in Eq.~\\eqref{eq:signAmbi} is provided in Appendix~\\ref{append:proofgaugefix}.\nImagine that we manage to fix the sign ambiguities, then we can write Eq.~\\eqref{def:RGeqGiltHOTRG} after the gauge fixing schematically as $A_c = \\mathcal{T}(A)$. The RG equation of the HOTRG-like scheme ensures\n%\n\\begin{align}\\label{eq:HOTRGgaugefix}\n    \\mathcal{T}(A) = \\mathcal{T}(\\tilde{A}).\n\\end{align}\n%\nSince the orthogonal matrices $S_x, S_y$ are arbitrary, equation~\\eqref{eq:HOTRGgaugefix} says that the whole equivalence class $[A]$ will be mapped into the same tensor $A_c$. \nThis means that the HOTRG-like scheme, after incorporating the sign fixing step, will choose a preferred set of basis. \nIt is worth to mention that the TRG has a similar property~\\cite{kadanoff2014}.\nFor a fixed-point tensor, equation~\\eqref{eq:HOTRGgaugefix} indicates that we can start with any representation $\\tilde{A}^*$ of the equivalence class $[A^*]$, and the HOTRG-like scheme will bring $\\tilde{A}^*$ to the proper basis; further coarse graining will satisfy Eq.~\\eqref{eq:tensorRGAstar},\n%\n\\begin{align}\\label{eq:GiltHOTRGfixT}\n    \\mathcal{T}(\\tilde{A}^*) =\n    \\mathcal{T}\\left(\\mathcal{T}(\\tilde{A}^*)  \\right) \\equiv A^*.\n\\end{align}\n%\n\nThe sign ambiguities $d_x,d_y$ in Eq.~\\eqref{eq:signAmbi} can be determined by comparing the sign of the components of $\\tilde{A}_c$ and $A_c$.\nFor example, upon making sure $(\\tilde{A}_c)_{1111}$ and $(A_c)_{1111}$ are both positive, set $j = k = l = 1$ in Eq.~\\eqref{eq:signAmbi} to have\n%\n\\begin{align}\\label{eq:finddx}\n    (\\tilde{A}_c)_{i111} =\n    (A_c)_{i111}(d_x)_i. \n\\end{align}\n%\nThe relative sign of $(\\tilde{A}_c)_{i111}$ and $(A_c)_{i111}$ determines $(d_x)_i$.\nHowever, this sign fixing method breaks down if both $(\\tilde{A}_c)_{i111}$ and $(A_c)_{i111}$ vanish, which occurs as long as there is a symmetry.\nThis is the reason why we first fix part of the gauge by exploiting the global internal symmetry of the physical model.\nThen, we can apply Eq.~\\eqref{eq:finddx} in each degenerate sector of the tensor.\nThe detailed implementation of the sign fixing procedure for $\\mathbb{Z}_2$ symmetric tensors can be found in the source code of this paper (see Appendix~\\ref{append:sc}).\n%\n\nAfter reaching the fixed-point tensor $A^*$ in Eq.~\\eqref{eq:GiltHOTRGfixT}, the next step is to linearize the tensor RG equation in Eq.~\\eqref{def:RGeqGiltHOTRG}.\nWe substitute $A = A^* + \\delta A$ into the right hand side of Eq.~\\eqref{def:RGeqGiltHOTRG} and collect terms that are first order in $\\delta A$ to get $\\delta A_c$,\n%\n\\begin{widetext}\n    \\begin{align}\\label{eq:respMatGiltHOTRG}\n    \\includegraphics[scale=1.0,valign=c]{deltaAc.pdf}\n    &=\n    \\includegraphics[scale=0.8,valign=c]{deltaA1.pdf}\n    +\n    \\includegraphics[scale=0.8,valign=c]{deltaA2.pdf}\n    + \\text{ two similar terms},\n    \\end{align}\n\\end{widetext}\n%\nwhere we refrain from drawing $d_x,d_y$ coming from the sign fixing procedure.\nThe result resembles the product rule for taking the differentials in calculus.\nEquation~\\eqref{eq:respMatGiltHOTRG} provides a simple pictorial representation of the linearized tensor RG equation $\\mathcal{R}$ in Fig.~\\ref{fig:linearedRGschem} and Eq.~\\eqref{eq:respMatTen} for the HOTRG-like scheme.\nThe computational costs of the contraction of the right hand side of Eq.~\\eqref{eq:respMatGiltHOTRG} are $O(\\chi^7)$, the same as those of the HOTRG-like coarse graining in Eq.~\\eqref{def:RGeqGiltHOTRG}.\nIn practice, after the fixed-point tensor $A^*$, the pieces of low-rank matrices $Q_A,Q_B$ and the isometric tensors $w, v$ in Eq.~\\eqref{def:RGeqGiltHOTRG} are determined, automatic differentiation can linearize Eq.~\\eqref{def:RGeqGiltHOTRG} around $A^*$ and generate Eq.~\\eqref{eq:respMatGiltHOTRG} for us.\nThere are many libraries that support automatic differentiation, including PyTorch~\\cite{pytorch} and JAX~\\cite{jax2018github}.\n%\n\n\\section{Examples\\label{benchmark}}\nWe use the classical Ising model in 1D and 2D to demonstrate how to carry out the canonical RG prescription in tensor space. \nThe Ising model in 1D serves as a concrete example to elucidate the general argument in Sec.~\\ref{RGprescrip}. \nThe Ising model in 2D provides more nontrivial benchmark results for our method.\n%\n\n\\subsection{The Ising Model in 1D\\label{benchmark:1DIsing}}\nThe Ising model in 1D has an exact real-space RG transformation realized via decimation. \nEven better, the decimation has a natural tensor network representation. \nThis makes the Ising model in 1D a nice example to see the relation between the old and the new approaches of the canonical RG prescription.\n%\n\nThe partition function is\n%\n\\begin{align}\\label{def:Z4Ising1D}\n    Z_{\\text{1D}} = \\sum_{\\{\\sigma_j \\} } \\exp{\\left[\\sum_{i=1}^N\n    \\mathscr{H}\\left(\\sigma_i,\\sigma_{i+1}\\right)  \\right]},\n\\end{align}\n%\nwhere the local interactions involve the nearest-neighbor term at most\n%\n\\begin{align}\\label{def:H4Ising1D}\n    \\mathscr{H}\\left(\\sigma_1, \\sigma_2\\right) = g +\n    \\frac{h}{2}\\left(\\sigma_1 + \\sigma_2\\right) + K\\sigma_1 \\sigma_2.\n\\end{align}\n%\nThe decimation process is shown in Fig.~\\ref{fig:Ising1D-decimation}.\nIt is realized by summing over all the even-numbered spins and then renumber the remaining odd-numbered spins. \n%\n%% Figure: decimation of the 1D Ising model\n\\begin{figure}[t]\n    \\includegraphics[width=0.9\\columnwidth,valign=c]{Ising1D-decimation.pdf}\n    \\caption{\\label{fig:Ising1D-decimation}\n        The decimation for the 1D Ising model. \n        The black dots are spin variables. \n        The spins on even sites $\\sigma_2,\\sigma_4,\\ldots$ are summed over and the remaining spins $\\sigma_1,\\sigma_3,\\ldots$ are renamed $\\sigma_1',\\sigma_2',\\ldots$ to become new spin variables. \n        In the tensor network language, this decimation is nothing but a matrix multiplication of two transfer matrices to form a coarse-grained matrix $A_c = AA$.\n    }\n\\end{figure}\n%\nWe denote $\\sigma_i'=\\sigma_{2i-1}, s_i = \\sigma_{2i}$ and sum over all $s$-spins in the partition function in Eq.~\\eqref{def:Z4Ising1D} to have\n%\n\\begin{align}\\label{eq:oldK2newKZ}\n    Z_{\\text{1D}} = \n    \\sum_{\\{\\sigma_j'\\}} \\sum_{\\{s_j \\}}\n    \\exp{\\left[ \\sum_i^{N/2} \\left[\\mathscr{H}\\left(\\sigma_i',s_i\\right)\n    + \\mathscr{H}\\left(s_i,\\sigma_{i+1}'\\right)\\right]\\right]},\n\\end{align}\n%\nfrom which we can define the effective local interaction $\\mathscr{H}'$ through\n%\n\\begin{align}\\label{eq:oldK2newK}\n    \\exp{\\left[\\mathscr{H}'\\left(\\sigma_1',\\sigma_2'\\right)\\right]} =\n    \\sum_{s=\\pm 1}\\exp{\\left[\\mathscr{H}\\left(\\sigma_1',s\\right) +\n        \\mathscr{H}\\left(s,\\sigma_2'\\right)\\right]},\n\\end{align}\n%\nwhere the effective local interaction has the same form as the old one in Eq.~\\eqref{def:H4Ising1D} but with new coupling constants $g',h',K'$,\n%\n\\begin{align}\\label{def:newH4Ising1D}\n    \\mathscr{H}'\\left(\\sigma_1,\\sigma_2\\right) = g' +\n    \\frac{h'}{2}\\left(\\sigma_1 + \\sigma_2\\right) + K' \\sigma_1 \\sigma_2.\n\\end{align}\n%\nThe partition function can be fully described by the new $\\sigma'$-spins,\n%\n\\begin{align}\\label{eq:Z2Ising1Dnew}\n    Z_{\\text{1D}} = \\sum_{\\{\\sigma_j'\\}}\n    \\exp{\\left[\\sum_{i=1}^{N/2}\\mathscr{H}'\\left(\\sigma_i',\\sigma_{i+1}'\\right)\\right]}.\n\\end{align}\n%\nEquations~\\eqref{def:H4Ising1D}, \\eqref{eq:oldK2newK} and~\\eqref{def:newH4Ising1D} together define the RG equation that maps the old coupling constants $(g,h,K)$ to the new coupling constants $(g',h',K')$. \nThe explicit expression of the RG equation can be found in Kardar's textbook~\\cite{kardar2007}. \nThe RG equation has two fixed points, one for high-temperature phase and the other for low-temperature phase. \nLet us focus on the high-temperature fixed point here, where the coupling constants are $g^* = \\log\\left(1/2\\right),h^*=0,K^*=0$. \nThe linearized RG equation around this fixed point gives $\\delta g' = 2\\delta g, \\delta h' = \\delta h, \\delta K' = 0\\times \\delta K$. \nThe matrix $\\mathcal{R}$ is in its diagonal form with eigenvalues $2,1,0$ for $\\delta g,\\delta h,\\delta K$ respectively.\n%\n\nNext, we translate the above decimation process into tensor network language. \nWe first define the tensor $A$ sitting on the bond connecting two spins shown in Fig.~\\ref{fig:Ising1D-decimation} as\n%\n\\begin{subequations}\\label{def:A4Ising1D}\n    \\begin{align}\\label{def:A4Ising1DCompo}\n    A_{\\sigma_1 \\sigma_2} =\n    \\exp{\\left[\\mathscr{H}\\left(\\sigma_1,\\sigma_2\\right)\\right]}.\n    \\end{align}\n    After using the expression for $\\mathscr{H}$ in\n    Eq.~\\eqref{def:H4Ising1D}, we have\n    \\begin{align}\\label{def:A4Ising1Depl}\n        A = \n    \\begin{pmatrix}\n    \\exp{\\left(g + h + K\\right)} & \\exp{\\left(g - K\\right)} \\\\\n    \\exp{\\left(g - K\\right)} & \\exp{\\left(g - h + K\\right)} \\\\\n    \\end{pmatrix},\n    \\end{align}\n\\end{subequations}\n%\nwhich is the familiar transfer matrix. Each component of the tensor $A$ is a function of coupling constants $g, h, K$, as is claimed in Eq.~\\eqref{eq:K2A}. \nThe partition function in Eq.~\\eqref{def:Z4Ising1D} can be rewritten as\n%\n\\begin{align}\\label{eq:Z4Ising1DbyA}\n    Z_{\\text{1D}} = \\sum_{\\{\\sigma_j\\}} \\bigotimes_{i=1}^N A_{\\sigma_i\n        \\sigma_{i+1}}.\n\\end{align}\n%\nThe decimation in the tensor network language is a multiplication of two old $A$ matrices to form a new $A_c$ matrix,\n%\n\\begin{align}\\label{def:Ising1DRGeqTen}\n    A_c = AA.\n\\end{align}\n%\nIn terms of the new $A_c$ matrix, the partition function is\n%\n\\begin{align}\\label{eq:Z4Ising1DbyAp}\n    Z_{\\text{1D}} = \\sum_{\\{\\sigma_j'\\}} \\bigotimes_{i=1}^{N/2}\n    (A_c)_{\\sigma_i' \\sigma_{i+1}'}.\n\\end{align}\n%\nEquation~\\eqref{def:Ising1DRGeqTen} is the RG equation in the tensor network language. \nNow, each component of $A_c$ is a function of coupling constants $g,h,K$ but with different functional form, as is claimed in Eq.~\\eqref{eq:tensorEleRG}. \nIf we further require that $A_c$ should have the same form as $A$ in Eq.~\\eqref{def:A4Ising1D} but with $\\mathscr{H}$ replaced by $\\mathscr{H}'$, new coupling constants $g',h',K'$ can be solved in terms of the old ones, which is what we do in the conventional approach. \nThe advantage of using the tensor network language is that the RG equation in Eq.~\\eqref{def:Ising1DRGeqTen} suffices for the canonical RG prescription in tensor space. \nFirst, let us set the coupling constants in Eq.~\\eqref{def:A4Ising1Depl} to be the high-temperature fixed point $g^* = \\log{\\left(1/2\\right)}, h^*=0, K^* = 0$ to get the fixed-point tensor,\n%\n\\begin{align}\\label{eq:fixedA4Ising1D}\n    A^* = \\frac{1}{2}\n\\begin{pmatrix}\n    1 & 1 \\\\\n    1 & 1 \\\\\n\\end{pmatrix}.\n\\end{align}\n%\nIt can be checked that $A^* A^* = A^*$. \nThe linearized version of Eq.~\\eqref{def:Ising1DRGeqTen} around this fixed-point tensor is\n%\n\\begin{align}\\label{eq:Ising1DRespEq}\n    \\delta A_c = \\delta A A^* + A^* \\delta A = I \\delta A A^* + A^*\n    \\delta A I,\n\\end{align}\n%\nwhere in the last equal sign, we add two identity matrices. \nWrite Eq.~\\eqref{eq:Ising1DRespEq} in its component form, we have $\\left(\\delta A_c\\right)_{ab} = \\sum_{\\alpha,\\beta}I_{a\\alpha}\\left(\\delta A\\right)_{\\alpha\\beta} \\left(A^*\\right)_{\\beta b} + \\left(A^*\\right)_{a\\alpha} \\left(\\delta A\\right)_{\\alpha \\beta} I_{\\beta b}$. \nWe can read off the matrix of the linearized RG equation as\n%\n\\begin{align}\\label{eq:Ising1DRespMat}\n    \\mathcal{R}_{(ab)(\\alpha \\beta)} = \\frac{\\left(\\delta\n    A_c\\right)_{ab}}{\\left(\\delta A\\right)_{\\alpha \\beta}} =\n    I_{a\\alpha}\\left(A^*\\right)_{\\beta b} + \\left(A^*\\right)_{a\\alpha}\n    I_{\\beta b},\n\\end{align}\n%\nwhere we group two indices $a,b$ as a single index $(ab)$, and $\\alpha,\\beta$ as $(\\alpha\\beta)$. \nIf we put the grouped index into the following order,\n%\n\\begin{align}\\label{def:orderConvention}\n    (11) \\rightarrow 1, (12) \\rightarrow 2, (21) \\rightarrow 3, (22)\n    \\rightarrow 4,\n\\end{align}\n%\nthe matrix takes the following value\n%\n\\begin{align}\\label{eq:Ising1DRespMatNum}\n    \\mathcal{R} = \n\\begin{pmatrix}\n    1 & 1/2 & 1/2 & 0 \\\\\n    1/2 & 1 & 0 & 1/2 \\\\\n    1/2 & 0 & 1 & 1/2 \\\\\n    0 & 1/2 & 1/2 & 1 \\\\\n\\end{pmatrix}.\n\\end{align}\n%\nThis matrix $\\mathcal{R}$ in Eq.~\\eqref{eq:Ising1DRespMatNum} is a symmetric, and we can find its eigenvalues and eigenvectors: $\\lambda_1 = 2,\\mathbf{v}_1 = (1,1,1,1)^T$; $\\lambda_2 = 1,\\mathbf{v}_2 = (1,0,0,-1)^T$; $\\lambda_3 =1, \\mathbf{v}_3 = (0,1,-1,0)^T$ and $\\lambda_4 = 0, \\mathbf{v}_4 = (1,-1,-1,1)^T$. \nThe eigenvalues are the same as what we get in the conventional method. \n%\n\nThe relation between the canonical RG prescription in tensor space and the Hamiltonian space can be clarified by noticing that the relation between the coupling constants and the tensor $A$ is given in Eq.~\\eqref{def:A4Ising1Depl}. \nWe perturb the coupling constants around the fixed point, $g_p = \\log{(1/2)} + \\delta g, h_p = \\delta h, K_p = \\delta K$, substitute them into the right hand side of Eq.~\\eqref{def:A4Ising1Depl} and Taylor expand to get the perturbed tensor,\n%\n\\begin{align}\\label{eq:Apert4Ising1D}\n    A_p &= A^* + \\frac{1}{2} \\delta g\n    \\begin{pmatrix}\n    1 & 1 \\\\\n    1 & 1 \\\\\n    \\end{pmatrix}\n    + \\frac{1}{2} \\delta h\n    \\begin{pmatrix}\n    1 & 0 \\\\\n    0 & -1 \\\\\n    \\end{pmatrix} \\nonumber\\\\\n    &+ \\frac{1}{2} \\delta K\n    \\begin{pmatrix}\n    1 & -1 \\\\\n    -1 & 1 \\\\\n    \\end{pmatrix}\n    + \\text{ higher-order terms }.\n\\end{align}\n%\nWe can read off $\\delta A = A_p - A^*$ as\n%\n\\begin{align}\\label{eq:deltaA4Ising1D}\n    \\delta A = \\frac{1}{2} \\delta g\n    \\begin{pmatrix}\n    1 & 1 \\\\\n    1 & 1 \\\\\n    \\end{pmatrix}\n    + \\frac{1}{2} \\delta h\n    \\begin{pmatrix}\n    1 & 0 \\\\\n    0 & -1 \\\\\n    \\end{pmatrix} \n    + \\frac{1}{2} \\delta K\n    \\begin{pmatrix}\n    1 & -1 \\\\\n    -1 & 1 \\\\\n    \\end{pmatrix},\n\\end{align}\n%\nwhich is Eq.~\\eqref{eq:deltaK2deltaA} in practice. \nRecall the order convention in Eq.~\\eqref{def:orderConvention}, we see the correspondence $\\mathbf{v}_1 \\leftrightarrow \\delta g$, $\\mathbf{v}_2 \\leftrightarrow \\delta h$ and $\\mathbf{v}_4 \\leftrightarrow \\delta K$.\n%\n\n\\subsection{The Ising Model in 2D\\label{benchmark:2DIsing}}\nThere is no exact RG transformation for the Ising model in 2D, so we will use the HOTRG-like scheme developed in Sec.~\\ref{sec:gilthotrg} to generate RG flows in tensor space. \nThe source code of the calculations in this subsection, including the implementations of the HOTRG-like scheme and its linearized version, can be found in Appendix~\\ref{append:sc}.\n%\n\nThe partition function is given in Eq.~\\eqref{eq:2DIsingZ} and we translate the partition function into a tensor network in Fig.~\\ref{fig:spin2tensor}. \nLet us denote the initial tensor in Eq.~\\eqref{def:tensorA} as $A^{(0)}$. \nTo prevent a rapid grow of the magnitude of the tensor during the RG transformation, we pull out the Frobenius norm of the tensor, $A^{(0)} = \\Vert A^{(0)}\\Vert \\mathcal{A}^{(0)}$, to define a normalized tensor $\\mathcal{A}^{(0)}$. \nThe normalized tensor $\\mathcal{A}^{(0)}$ will be fed into the RG equation of the HOTRG-like scheme in Eq.~\\eqref{def:RGeqGiltHOTRG} and we denote the output coarse-grained tensor as $A^{(1)}$, from which the norm $\\Vert A^{(1)}\\Vert$ is pulled out and the normalized tensor $\\mathcal{A}^{(1)}$ is defined the same way as the previous step. \nThe process can be repeated so we will have $A^{(n)} = \\Vert A^{(n)}\\Vert \\mathcal{A}^{(n)}$ at the $n$-th step. \nThe RG flow in tensor space can be conveniently visualized by examining the evolution of the norms $\\Vert A^{(n)}\\Vert$ as the RG step $n$ increases.\n%\n\n\nThe RG flows of the norms $\\Vert A^{(n)} \\Vert$ indicate the proposed HOTRG-like scheme is capable of generating a correct RG flow for the 2D Ising model in tensor space shown schematically in Fig.~\\ref{fig:tensorRGflow}(a). \nFor example, for bond dimension $\\chi = 30$ and the hyper-parameter of the GILT process $\\epsilon_{\\text{gilt}} = 6\\times 10^{-6}$, Fig.~\\ref{fig:flowAnorm}(a) shows several RG flows of the tensor norms $\\Vert A^{(n)} \\Vert$ at different temperatures. \nFor a given bond dimension $\\chi$, there is an estimated critical temperature $T_c^{[\\chi]}$ at which the tensor hits the critical surface and will flow to the critical fixed-point tensor $(A^{[\\chi]})^*_{\\text{cr}}$. \nThe $T_c^{[\\chi]}$ can be determined using the bisection method; for $\\chi = 30$, the difference between the estimated value $T_c^{[30]}$and the exact $T_c$, $|T_c^{[30]} - T_c|$, is of order $10^{-6}$. \nAt temperatures off by $\\Delta T = \\pm 10^{-3}$ from $T_c^{[30]}$, the tensor flows to the high- and low-temperature trivial fixed-point tensors respectively before it comes near to $(A^{[30]})^*_{\\text{cr}}$. \nAs $|\\Delta T|$ becomes smaller to order of $10^{-6}$, the tensor will stay in the vicinity of the critical fixed-point tensor $(A^{[30]})^*_{\\text{cr}}$ for a while and then flow away to one of the two trivial fixed-point tensors. \nIf $|\\Delta T|$ becomes smaller further to $10^{-10}$, the tensor will stay longer near $(A^{[30]})^*_{\\text{cr}}$. \nBy comparison, the RG flow of $\\Vert A^{(n)}\\Vert$ generated by the HOTRG with bond dimension $\\chi = 12$ is displayed in Fig.~\\ref{fig:flowAnorm}(b)\\footnote{\n    In principle, we can choose $\\chi = 30$ here. \n    In practice, however, our calculations show that the problem of local correlations in the HOTRG becomes worse at larger bond dimensions (see Ref.~\\cite{Berker2008} for a similar observation in the context of the TRG), and that $\\chi = 12$ is enough to demonstrate this problem.\n}. \nThe RG flow shows that the HOTRG has difficulty in exhibiting a critical fixed-point tensor or producing isolated trivial fixed-point tensors. \nIt is interesting to mention that the RG flow generated by the TRG has a similar behavior~\\cite{Berker2008} for bond dimensions $\\chi > 8$.\n%\n%%% Figure: the RG flows of the tensor norms\n\\begin{figure}[t]\n    \\includegraphics[width=\\columnwidth,valign=c]{AnormFlow-a.pdf}\n    \\includegraphics[width=\\columnwidth,valign=c]{AnormFlow-b.pdf}\n    \\caption{\\label{fig:flowAnorm}\n        The RG flows of the tensor norms $\\Vert A^{(n)} \\Vert$ at temperatures near the estimated critical temperature $T_c^{[\\chi]}$. \n        Different markers represent different deviations $| \\Delta T| $ from $T_c^{[\\chi]}$. Blue solid lines are for $\\Delta T<0$ and black dashed lines for $\\Delta T>0$. \n        (a) For the proposed HOTRG-like scheme with $\\chi = 30,\\epsilon_{\\text{gilt}} = 6\\times 10^{-6}$, two trivial fixed points are isolated and the critical fixed point can be reached. It corresponds to the schematic RG flows in Fig.~\\ref{fig:tensorRGflow}(a). \n        (b) For the plain HOTRG with $\\chi = 12$, we have fixed lines and there is no exhibition of a critical fixed point. \n        It corresponds to the schematic RG flows in Fig.~\\ref{fig:tensorRGflow}(b).\n    }\n\\end{figure}\n%\n\nTo make sure that the plateau in the RG flow of $\\Vert A^{(n)} \\Vert$ gives a critical fixed-point tensor $(A^{[30]})^*_{\\text{cr}}$ at the estimated critical temperature $T_c^{[30]}$, we plot the singular values $s^{(n)}$ of tensors $\\mathcal{A}^{(n)}$ defined as\n%\n\\begin{align}\\label{def:Asvd}\n    \\includegraphics[scale=1.0,valign=c]{Acaln.pdf}\n    \\svdeq\n    \\includegraphics[scale=1.0,valign=c]{Asvd.pdf}.\n\\end{align}\n%\nThe RG flow of the singular values in Fig.~\\ref{fig:flowA}(a) indicates that we indeed reach a non-trivial fixed-point tensor. \nThe fixed-point tensor is manifestly fixed after adding the sign-fixing step, which can be confirmed by plotting the Frobenius norm of the difference between the normalized tensors at successive RG steps $\\Vert \\mathcal{A}^{(n+1)} - \\mathcal{A}^{(n)}\\Vert$, see Fig.~\\ref{fig:flowA}(b). \nThe norm of the difference starts to decay systematically at RG step $n = 14$, goes all the way down to the order $\\sim 10^{-2}$ at $n = 23$ and then increases when the tensor begins to flow away from the critical fixed point.\nBy comparison, we show the RG flow of $\\Vert \\mathcal{A}^{(n+1)} - \\mathcal{A}^{(n)}\\Vert$ without sign fixing in Fig.~\\ref{fig:flowA}(c); the sign ambiguities in Eq.~\\eqref{eq:signAmbi} prevent us from achieving a manifestly-fixed-point tensor, except at RG step $n = 22$, where the tensor happens to have all signs correct by accident.\n%%% Figure: the RG flows of singular values of tensors\n\\begin{figure}[tb]\n    \\includegraphics[width=\\columnwidth]{flowA-singVal.pdf}\n    \\includegraphics[width=\\columnwidth]{flowA-diff-compare.pdf}\n    \\caption{\\label{fig:flowA}\n        The RG flows of (a) singular values defined in Eq.~\\eqref{def:Asvd} and (b) the difference between the normalized tensors, $\\Vert \\mathcal{A}^{(n+1)} - \\mathcal{A}^{(n)} \\Vert$ with sign fixing and (c) without, all at the estimated critical temperature $T_c^{[30]}$, generated by the proposed HOTRG-like scheme with $\\chi = 30, \\epsilon_{\\text{gilt}} = 6\\times 10^{-6}$.\n    }\n\\end{figure}\n% end Figure\n\nWe use the automatic differentiation implemented in JAX~\\cite{jax2018github} to generate the linearized tensor RG equation $\\mathcal{R}$ in Eq.~\\eqref{eq:respMatGiltHOTRG} at RG steps $n = 14,15,\\ldots, 28$, when the tensor is very close to the critical fixed-point tensor. \nThe scaling dimensions are extracted from the eigenvalues of the matrix $\\mathcal{R}$ according to Eq.~\\eqref{eq:lambda2x}, where $b = 2, d = 2$. \nIn Fig.~\\ref{fig:scDim}, we show the first few scaling dimensions. \nThe dashed lines are the exact values~\\cite{DiFrancesco1997}. \nFor $\\chi = 30$, the RG prescription in tensor space gives correct scaling dimensions up to $2.125$. \nThe results at RG step $n = 14 \\text{ and } 28$ are unreliable since $\\Vert \\mathcal{A}^{(n+1)} - \\mathcal{A}^{(n)}\\Vert$ is of order $1$ (see Fig.~\\ref{fig:flowA}(b)). \nThe results for $n = 15,16,\\ldots,27$ indicates that the scaling dimensions from the RG prescription in tensor space are reliable as long as the values of $\\Vert \\mathcal{A}^{(n+1)} - \\mathcal{A}^{(n)}\\Vert$ have order of or smaller than $10^{-1}$. \n%\n%%% Figure: scaling dimensions\n\\begin{figure}[tb]\n    \\includegraphics[width=\\columnwidth]{scDim.pdf}\n    \\caption{\\label{fig:scDim}\n        The scaling dimensions of the 2D Ising model from the canonical RG prescription using the proposed HOTRG-like scheme with $\\chi = 30, \\epsilon_{\\text{gilt}} = 6\\times 10^{-6}$.\n    Dashed lines are the exact values.}\n\\end{figure}\n%%% end figure\n\nIn Table~\\ref{table:scDim}, we show the scaling dimensions for all relevant and marginal operators at RG step $n = 22$ from the canonical RG prescription, compared with the results obtained by Gu and Wen's method~\\cite{GuWen2009}, where two copies of the fixed-point tensor are used to construct the transfer matrix. \nBoth methods have similar accuracy for scaling dimensions less than or equal to $1.125$.\nThe RG prescription in tensor space gives two out of total four scaling dimensions $2$ with three digits of accuracy, but the remaining two are overestimated and closer to $2.125$.\nGu and Wen's method estimates all of the four scaling dimensions $2$ correctly with two digits of accuracy.\n%\n%%% Table: scaling dimensions\n\\begin{table}[t]%[H] add [H] placement to break table across pages\n\\caption{The scaling dimensions for the relevant and marginal operators\n    of the 2D Ising model at criticality from the canonical RG prescription \n    and from the transfer matrix method \\`a la Gu and\n    Wen~\\cite{GuWen2009}, both using the proposed HOTRG-like scheme with $\\chi = 30, \\epsilon_{\\text{gilt}} =\n    6\\times 10^{-6}$ at RG step $n = 22$.\\label{table:scDim}} \n\\begin{ruledtabular}\n\\begin{tabular}{ c c c c c c c c c }\nExact      & 0.125 & 1 & 1.125 & 1.125 & 2 & 2 & 2 & 2 \\\\\n\\hline\n\\thead{RG\\\\ pres.} & 0.127 & 1.009 & 1.125 & 1.128 & 2.002 &\n2.004 & 2.068 & 2.073 \\\\\n\\thead{Trans.\\\\ mat.} & 0.125 & 1.002 & 1.128 & 1.128 & 2.014 &\n2.014 & 2.016 & 2.016\n\\end{tabular}\n\\end{ruledtabular}\n\\end{table}\n% end Table\n\nWe end this section with a few remarks on the above calculations. \nFirstly we impose the $\\mathbb{Z}_2$ symmetry of the tensors~\\cite{Singh2010SymTen, Singh2011U1Ten} when generating the RG flow in tensor space. \nThere are three reasons. \nOnly if the $\\mathbb{Z}_2$ symmetry of the tensor is imposed will the low-temperature fixed-point tensor be stable under the RG.  \nOtherwise, it will flow to the high-temperature fixed point eventually due to numerical errors, which will make the bisection search for the estimated critical temperature $T_c^{[\\chi]}$ less convenient. \nThe second merit of symmetric tensors is that half of the gauge redundancy can be automatically fixed (see Sec.~\\ref{sec:gaugefix}), making the sign-fixing procedure easier. \nThe third reason is to speed up the computations. \nHowever, we roll back to ordinary tensors when performing the RG prescription in tensor space, since the perturbations around the fixed-point tensor do not have to preserve $\\mathbb{Z}_2$ symmetry (for example, the spin operator)\\footnote{\n    The perturbations like the spin operator are not $\\mathbb{Z}_2$ invariant, but they are $\\mathbb{Z}_2$ covariant, with nonzero charge. \n    It should be possible to utilize this numerically to extract scaling dimensions of operators with different charges separately.\n    However, we did not proceed in this direction here.\n}. \n%\n\nThe second remark is about the improvement of the accuracy as the bond dimension $\\chi$ increases. \nThere are two sources of approximation errors in the above computations. \nOne comes from the truncations of the CDL tensors during the GILT that is necessary for producing the critical fixed point. \nThis error is controlled by the hyper-parameter $\\epsilon_{\\text{gilt}}$. \nThe other source is the leg squeezing step during the HOTRG to prevent the grow of the bond dimension.\nThis error can be reduced by increasing the bond dimension $\\chi$. \nIn general, for a given $\\chi$, the $\\epsilon_{\\text{gilt}}$ should be as small as possible provided that the proposed HOTRG-like scheme can exhibit a critical fixed-point tensor. \nIn practice, we tried $\\chi = 10, 20, 30$, and $\\epsilon_{\\text{gilt}}$ goes down from $6\\times 10^{-4}$ to $6\\times10^{-5}$ and further to $6\\times10^{-6}$. \nThe estimated scaling dimensions converge to the exact results in this process. \n%\n\nThe third remark is about the overall multiplication constant in front of the fixed-point tensor. \nAfter reaching the critical fixed point, the RG from $n$-th step to $(n+1)$-th step is the map $\\mathcal{A}^{*}\\rightarrow c^{*} \\mathcal{A}^{*}$, where $c^{*}$ is the magnitude of the coarser tensor. \nThe shape of $\\mathcal{A}^*$ is fixed but its magnitude is still changing under the RG transformation. \nIt has been shown in Ref.~\\cite{GuWen2009} that the fixed-point tensor with correct magnitude is simply given by $A^* = (c^*)^{-1/3} \\mathcal{A}^*$, and we will have $A^*\\rightarrow A^*$ under the RG transformation.\nOur numerical results have confirmed this statement.\n%\n\nThe final remark is that the problem of local correlations could be removed by other methods~\\cite{GuWen2009,tnr,tnralgo,tnrplus,looptnr,harada2018,fet,tns,tensor-ring} other than GILT.\nFor example, the TNR~\\cite{tnr,tnralgo} is known to be capable of exhibiting critical fixed-point tensors with its RG equation similar to that of the proposed HOTRG-like scheme in Eq.~\\eqref{def:RGeqGiltHOTRG}, and there is a method to fix its gauge~\\cite{tnralgo}. \nConsidering the unprecedented accuracy of the TNR, the estimation of the scaling dimensions might be much better.\nWe develop the canonical RG prescription in tensor space using the HOTRG-like scheme in this paper in order to prepare for the further applications to 3D systems.\n%\n\n\n\\section{Summary and discussions\\label{conclusion}}\nIn this paper, we show how to perform the canonical RG prescription in tensor space.\nThe general procedure is summarized as follows: reach a fixed-point tensor using a tensor RG equation free of the problem of local correlations, fix the gauge redundancy to make the fixed-point tensor manifestly fixed, linearize the RG equation around this fixed-point tensor and finally calculate the scaling dimensions from the eigenvalues of this linearized tensor RG equation.\nIn practice, we propose an HOTRG-like scheme to carry out this canonical RG prescription in tensor space.\nFor the estimates of the scaling dimensions, we had not expected the present scheme would yield better accuracy than the conventional way \\`a la Gu and Wen, and indeed it turned out not to be the case for the 2D classical Ising model.\nHowever, the important fact is that the present scheme works at least equally well, and it potentially has a broader range of applications.\n%\n\nThe success of the canonical RG prescription in tensor space offers a crucial missing piece of puzzle for understanding TRG-type techniques as real-space RG transformations.\nThe realization of the RG prescription based on the proposed HOTRG-like scheme extends the old Migdal-Kadanoff idea, and is systematically improvable.\nThe distinctive feature of the proposed method, compared with the two existing tensor-RG-based ones for extracting scaling dimensions~\\cite{GuWen2009,EvenblyDilatationOp}, is that it is from pure RG perspective and does not rely on any CFT arguments explicitly, making the method more promising in 3D.\nIn our future work, we will generalize the HOTRG-like scheme and apply the canonical tensor RG prescription to 3D systems, where there are few practical tensor-network-based methods\\footnote{\n    From the perspective of a real-space RG transformation for quantum systems~\\cite{ER2007}, the scale-invariant multiscale entanglement renormalization ansatz (MERA)~\\cite{MERA} can be used to build a scaling superoperator~\\cite{MERAsupop}. \n    The scaling dimensions are obtained from the eigenvalues of the scaling superoperator~\\cite{supop2scaleD}. \nHowever, the computation costs of the MERA for 2+1D quantum systems grow as $O(\\chi^{16})$~\\cite{MERA2p1}, much higher than $O(\\chi^{11})$ for the 3D HOTRG\\@.\n} \nto extract scaling dimensions efficiently. \n\n\n\n\n% If you have acknowledgments, this puts in the proper section head.\n\\begin{acknowledgments}\nWe thank Satoshi Morita, Shumpei Iino, Takuhiro Ogino, Yuan Yao and Takeo Kato for fruitful discussions and insightful suggestions, and Glen Evenbly and Guifre Vidal for explanations regarding the TNR and other tensor network methods. \nWe also thank Markus Hauru for clarifying the implementation of the GILT, and are very grateful to Antoine Tilloy and an anonymous referee for useful suggestions about this manuscript.\nX.L.\\ and R.G.X.\\ are grateful to the support of the Global Science Graduate Course (GSGC) program of the University of Tokyo. \nThis work is financially supported by MEXT Grant-in-Aid for Scientific Research (B) (19H01809).\nThe numerical computations were performed on computers at the Supercomputer Center, the Institute for Solid State Physics (ISSP), the University of Tokyo.\n\n\\end{acknowledgments}\n\n% Specify following sections are appendices. Use \\appendix* if there\n% appendices.\n\\appendix\n\\section{GILTs designed for the HOTRG\\label{append:gilthotrg}}\n%\n%% Gilt applied on plaquettes\n\\begin{figure*}[!t]\n\\includegraphics[scale=1.0,valign=c]{gilt4hotrg.pdf}\n\\caption{\\label{fig:gilt4hotrg}\n    The plaquettes and bonds where the GILT is applied to for the subsequent HOTRG coarse graining.\n    (a) Two copies of $A$ in the center will be coarse grained vertically. \n    The problematic loops of local correlations are drawn explicitly in the plaquettes to make the demonstration clearer.\n    They are unknown inner structure of the main tensor $A$.\n    (b) Copies of low-rank matrices $Q_A,Q_B$, determined by the GILT~\\cite{gilts}, are inserted into the bonds to catch the legs of the loops.\n    (c) $Q_A,Q_B$ are split using singular value decomposition. The GILT ensures the legs of the loops do not leak out.\n    (d) The pieces of $Q_A,Q_B$ matrices are absorbed into the copies of tensor $A$. The subsequent HOTRG will be applied on the patch of tensors in the dashed circle.\n}\n\\end{figure*}\n%\n\nIn this appendix, we first briefly introduce how the low rank matrix is determined in the GILT, and then move on to explain why the HOTRG has difficulty in filtering out the local correlations and how the GILT comes to help.\n%\n\nThe low-rank matrix $Q$ in Fig.~\\ref{fig:gilt} is determined by examining the environment $E$ of the bond and performing the singular value decomposition,\n%\n\\begin{align}\\label{eq:bondEnvSVD}\n    E \\equiv \n    \\includegraphics[scale=1.0,valign=c]{bondEnviro.pdf}\n    \\svdeq \n    \\includegraphics[scale=1.0,valign=c]{bondEnvSVD.pdf}\\text{ },\n\\end{align}\n%\nwhere we refrain from drawing the unknown $C$ matrices in the plaquette.\nThe environment $E$ of the bond should be thought of as a linear map from the vector space of all the legs with ingoing arrows to that of all the legs with outgoing arrows. \nWe can use the tensor $U$ and the diagonal matrix $s$ in Eq.~\\eqref{eq:bondEnvSVD} to construct the low-rank matrix $Q$. \nTo this end, we first define a vector $t$ by contracting two ingoing legs of the tensor $U$,\n%\n\\begin{align}\\label{def:tfromU}\n    \\includegraphics[scale=1.0,valign=c]{tvec.pdf}\n    \\equiv \n    \\includegraphics[scale=1.0,valign=c]{Ucontract.pdf}.\n\\end{align}\n%\nThen, we perform a soft truncation of the vector $t$ according to\n%\n\\begin{align}\\label{eq:tpfromt}\n    t'_i = t_i \\frac{s_i^2}{s_i^2 + \\epsilon_{\\text{gilt}}^2},\n\\end{align}\n%\nwhere $s_i$ are the singular values and $\\epsilon_{\\text{gilt}}$ is the hyper-parameter of the GILT.\nEquation~\\eqref{eq:tpfromt} says that the components of the vector $t$ will be set to very small values if the corresponding singular values $s_i$ are much smaller than $\\epsilon_{\\text{gilt}}$. \nThe justification for the truncation in Eq.~\\eqref{eq:tpfromt} can be found in Ref.~\\cite{gilts}. \nThe low-rank matrix $Q$ is constructed from the tensor $U^{\\dagger}$ and the truncated vector $t'$ as\n%\n\\begin{align}\\label{def:QfromUtp}\n    \\includegraphics[scale=1.0,valign=c]{Qmat.pdf}\n    \\equiv \n    \\includegraphics[scale=1.0,valign=c]{Utp2Q.pdf}\\text{ }.\n\\end{align}\n%\nIt is proved in Ref.~\\cite{gilts} that the matrix $Q$ determined in this\nway is able to filter out the loop of four $C$ matrices shown in Fig.~\\ref{fig:gilt}. \n%\n\nNext, we demonstrate how  to choose the plaquettes and where to insert the low-rank matrices to filter out the unwanted local correlations for the HOTRG.\nIt is shown in Ref.~\\cite{hotrgfixpoint} that the HOTRG in the vertical direction transforms the $A^{\\text{CDL}}$ in Fig.~\\ref{fig:rgschem}(b) in the following way,\n%\n\\begin{align}\\label{eq:cdlHOTRG}\n    \\includegraphics[scale=0.8,valign=c]{cdlHOTRG.pdf}\n    \\propto \n    \\includegraphics[scale=1.0,valign=c]{singleCDL.pdf},\n\\end{align}\n%\nwhich means that although the HOTRG can detect and project out four inner $C$ matrices, it can do nothing about the four outer $C$ matrices.\nTherefore, the GILT should be applied to filter out these four outer $C$ matrices before the HOTRG coarse graining. \nTo this end, we apply the GILT to the plaquettes where the loops of local correlations are drawn explicitly in Fig.~\\ref{fig:gilt4hotrg} and insert two low-rank matrices $Q_A,Q_B$ into the upper and lower bonds for each plaquette. \nThe legs of the unwanted $C$ matrices will be truncated after the splitting of $Q_A, Q_B$. \nFinally, we apply the ordinary HOTRG in the vertical direction to the local patch of tensors in the dashed circle in Fig.~\\ref{fig:gilt4hotrg} to get the coarser tensor $A'$\n%\n\\begin{align}\\label{def:ApycontrGilt}\n    \\includegraphics[scale=1.0,valign=c]{Ap-ycontr.pdf}\n    \\equiv\n    \\includegraphics[scale=0.8,valign=c]{twoAgiltcoarse.pdf}.\n\\end{align}\n%\nIn this way, we can remove all horizontal legs of $C$ matrices: a half of them by the GILT and the other half by contraction in the HOTRG\\@.\nWe repeat the similar GILT and the HOTRG on $A'$ in the horizontal direction.\nThe coarse-graining steps in two directions together define the tensor RG equation of the HOTRG-like scheme in Eq.~\\eqref{def:RGeqGiltHOTRG}.\n%\n\n\\section{Proof regarding gauge fixing\\label{append:proofgaugefix}}\nTo see why the gauge fixing procedure in Eqs.~\\eqref{def:Nx} to~\\eqref{def:gaugefixHori} defines a preferred set of basis, let us examine how the tensor $\\tilde{A}$ in Eq.~\\eqref{def:gaugeTrans} transforms under this gauge fixing procedure.\nThe contraction of two vertical legs of $\\tilde{A}$ annihilates $S_y$ and $S_y^{-1}$ on the right hand side of Eq.~\\eqref{def:gaugeTransPic}; the resultant $\\tilde{N}_x$ is related to $N_x$ through\n%\n\\begin{align}\\label{eq:simTransNx}\n    \\includegraphics[scale=0.8,valign=c]{Nxtilde.pdf}\n    = \n     \\includegraphics[scale=0.8,valign=c]{NxSimTrans.pdf}.\n\\end{align}\n%\nProvided that there is no degeneracy in the eigenvalue spectrum of $N_x$, the matrix $\\tilde{W}_x$ coming from eigenvalue decomposition of the matrix $\\tilde{N}_x$ is related to $W_x$ in Eq.~\\eqref{eq:eigdcpNx} through\n%\n\\begin{align}\\label{eq:Wxtransf}\n    \\includegraphics[scale=0.8,valign=c]{Wxtilde.pdf}\n    = \n    \\includegraphics[scale=0.8,valign=c]{WxSimtransf.pdf},\n\\end{align}\n%\nwhere $d_x$ is a diagonal matrix coming from phase ambiguities of eigenvectors, with its diagonal entries to be phases for general complex matrices. \nFor a real symmetric $N_x$, the diagonal entries of $d_x$ are $\\pm 1$.\nAfter the horizontal gauge fixing, the tensor $\\tilde{A}$ becomes\n%\n\\begin{align}\\label{eq:AtildegaugefixHori}\n    \\includegraphics[scale=0.8,valign=c]{Atilde.pdf}\n    \\xrightarrow[\\text{gauge fixing}]{\\text{horizontal}} \n    \\includegraphics[scale=0.8,valign=c]{gaugefixAtildeHori.pdf}.\n\\end{align}\n%\nCompare Eq.~\\eqref{def:gaugefixHori} with Eq.~\\eqref{eq:AtildegaugefixHori}, we see that the gauge redundancies in two horizontal legs are fixed except the phase ambiguities.\nFor 2D classical statistical models with spatial reflection symmetries, for example, the 2D Ising model, the real matrix $N_x$ can be made symmetric, so the phase ambiguities become sign ambiguities.\n%\n\nFinally, let us prove the property of the tensor RG equation of the HOTRG-like scheme in Eq.~\\eqref{eq:signAmbi}.\nWe focus on real tensors (the generalization to complex tensors is straightforward) and the equivalence relation defined by the gauge transformation,\n%\n\\begin{align}\\label{eq:simorth}\n    \\includegraphics[scale=0.8,valign=c]{Atilde.pdf}\n    = \n    \\includegraphics[scale=0.8,valign=c]{AsimOrth.pdf},\n\\end{align}\n%\nwhere $S_x,S_y$ are orthogonal matrices.\nIt is sufficient to consider such orthogonal changes of gauge if we restrict to the representations of the equivalence class $[A]$ with spatial reflection symmetries~\\cite{tnralgo},\n%\n\\begin{subequations}\\label{def:relsym}\n    \\begin{align}    A_{kjil}  = \\sum_{j'l'} (O_y)_{j j'} (O_y)_{l l'} A_{ij'kl'} \n    \\end{align}\nand\n    \\begin{align}        \n        A_{ilkj} = \\sum_{i'k'} (O_x)_{i i'} (O_x)_{k k'} A_{i'jk'l},\n    \\end{align} \n\\end{subequations}\n%\nwhere $O_x, O_y$ are orthogonal matrices, also with $O_x^2 = O_y^2 = \\mathbb{1}$, and the legs' order convention is as per Eq.~\\eqref{def:tensorA}.\nIt can be shown that, if we start with a tensor with the reflection symmetries, the tensor RG equation of the HOTRG-like scheme in Eq.~\\eqref{def:RGeqGiltHOTRG} will preserve the reflection symmetries\\footnote{This is because the pieces of low-rank matrices and the isometric tensors in the RG equation of the HOTRG-like scheme in Eq.~\\eqref{def:RGeqGiltHOTRG} will inherit the reflection symmetries of the input tensor $A$.\n}\nand will rotate the tensor into the set of basis where $O_x, O_y$ become diagonal, with their diagonal entries $\\pm 1$.\n%\n\nIt suffices to discuss the first half of the coarse graining defined in Eq.~\\eqref{def:ApycontrGilt}. \nWe want to show that if $\\tilde{A}$ is fed into the right hand side of Eq.~\\eqref{def:ApycontrGilt}, the $\\tilde{A}'$ we obtain on the left hand side is related with the original $A'$ by \n%\n\\begin{align}\\label{eq:Ap2Aptilde}\n    \\includegraphics[scale=0.8,valign=c]{Aptilde.pdf}\n    = \n    \\includegraphics[scale=0.8,valign=c]{ApsimOrth.pdf},\n\\end{align}\nwhere $d_x$ is a diagonal matrix with diagonal entries $\\pm 1$.\nEquation~\\eqref{eq:Ap2Aptilde} means that the gauge redundancy in the horizontal legs will be fixed with only sign ambiguities left during the first half of the coarse graining in the vertical direction.\nIt follows immediately that the full tensor RG equation in Eq.~\\eqref{def:RGeqGiltHOTRG} will give Eq.~\\eqref{eq:signAmbi}.\n%\n\nLet us first figure out the correct $\\tilde{Q}_A,\\tilde{Q}_B$ matrices in Fig.~\\ref{fig:gilt4hotrg}. \nThe environment in Eq.~\\eqref{eq:bondEnvSVD} is multiplied by several orthogonal matrices, which will not change the singular values, so $\\tilde{s}_i=s_i$. \nIt is easy to check that the tensor $U$ in the singular value decomposition becomes (the sign ambiguities coming from the singular value decomposition does not matter here)\n%\n\\begin{align}\\label{eq:Utilde}\n    \\includegraphics[scale=0.8,valign=c]{Utilde.pdf}\n    = \n    \\includegraphics[scale=0.8,valign=c]{U2Utilde.pdf}.\n\\end{align}\n%\nThe vector $\\tilde{t}$ is thus the same as the original $t$ by its definition in Eq.~\\eqref{def:tfromU}, which further gives $\\tilde{t}'_i= t'_i$ since the tilde version of the right hand side of Eq.~\\eqref{eq:tpfromt} is the same as the original version. \nFinally, equation~\\eqref{def:QfromUtp} gives\n%\n\\begin{align}\\label{eq:QAtilde}\n    \\includegraphics[scale=1.0,valign=c]{QAtildeMat.pdf}\n    \\texteq{\\eqref{def:QfromUtp}}\n    \\includegraphics[scale=1.0,valign=c]{Utp2QAtilde.pdf}\n    &= \n    \\includegraphics[scale=0.8,valign=c]{Utp2Qupdate.pdf}\n    \\nonumber\\\\ \n    &= \n    \\includegraphics[scale=1.0,valign=c]{QAMatUU.pdf}.\n\\end{align}\n%\nEquation~\\eqref{eq:QAtilde} means that the low rank matrix $Q_A$ transforms in a nice way when we perform a gauge transformation defined in Eq.~\\eqref{eq:simorth}. \nIf the singular values of $Q_A$ \\textit{do not have degeneracy}, after splitting of $Q_A$, we have $Q_{Ar},Q_{Al}$ transform like (the sign ambiguities coming from singular value decomposition of $Q_A$ and $\\tilde{Q}_A$ would kick in and contribute to $d_x$ in Eq.~\\eqref{eq:Ap2Aptilde}, but they are not drawn explicitly in the equation below)\n%\n\\begin{align}\\label{eq:QpieceTrans}\n    \\includegraphics[scale=1.0,valign=c]{QArTransf.pdf}\n    \\text{ and } \n    \\includegraphics[scale=1.0,valign=c]{QAlTransf.pdf}.\n\\end{align}\n% \nThe $S_x,S_x^T$ matrices that $Q_{Ar},Q_{Al}$ pick up will cancel those acting on the $A$ tensor when $\\tilde{Q}_{Ar},\\tilde{Q}_{Al}$ are contracted with the $\\tilde{A}$ tensor in Eq.~\\eqref{eq:simorth}.\nThe same argument works for $Q_B$. \nEquation~\\eqref{eq:QpieceTrans} indicates that all the $S_x,S_x^T$ matrices acting on the four horizontal legs of the local patch in Eq.~\\eqref{def:ApycontrGilt} will be canceled by the low-rank matrices used in the GILT process. \nThe above analysis shows that during the GILT process for the vertical coarse graining, the gauge in the horizontal legs will be fixed with only sign ambiguities left, since the GILT favors the basis chosen by the singular value decompositions of $Q_A, Q_B$.\n%\n\nHowever, there is one more twist. In practice, we observe that the low-rank matrices are projection operators, which are highly degenerated. \nAs a result, the gauge redundancy in the degenerate subspace will leak out, which will be seen by the subsequent HOTRG process. \nLuckily, the HOTRG has a similar feature as the GILT process.\nIt favors the basis where the positive semi-definite matrix $M M^{\\dagger}$ (see the definition of matrix $M$ in Eq.~\\eqref{def:M-AA}) is diagonal (the sign ambiguities coming from eigenvalue decomposition of $M M^{\\dagger}$ would similarly kick in here and contribute to $d_x$ in Eq.~\\eqref{eq:Ap2Aptilde}). \nIt is straightforward to see that the isometry $w$ will pick up the suitable $S_x,S_x^T$ matrices to cancel out the gauge transformation leaking out from the GILT process.\nThere are still concerns about whether degeneracy occurs in eigenvalues of $M M^{\\dagger}$. \nOur result in Fig.~\\ref{fig:flowA}(b) shows, a posteriori, that the potential degeneracy does not cause any problem for the 2D Ising model at criticality.\n%\n\n\\section{Source Code\\label{append:sc}}\nThe source code of this paper can be found at \\href{https://github.com/brucelyu/tensorRGflow}{github.com/brucelyu/tensorRGflow}.\nIt can be used to reproduce all the results in Sec.~\\ref{benchmark:2DIsing} for the 2D classical Ising model.\n\n% Create the reference section using BibTeX:\n\\bibliography{tensorRGflow}\n\n\\end{document}\n%\n% ****** End of file apstemplate.tex ******\n", "meta": {"hexsha": "28e0c1a9b1618eab2674a1f7569df38838f13529", "size": 87588, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tensorRGflow.tex", "max_stars_repo_name": "brucelyu/tensorRGflow", "max_stars_repo_head_hexsha": "e70edb2da11f0be4db2882ddd7a07a8a6e0d4f06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2021-03-06T10:06:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T14:20:28.000Z", "max_issues_repo_path": "tensorRGflow.tex", "max_issues_repo_name": "brucelyu/tensorRGflow", "max_issues_repo_head_hexsha": "e70edb2da11f0be4db2882ddd7a07a8a6e0d4f06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tensorRGflow.tex", "max_forks_repo_name": "brucelyu/tensorRGflow", "max_forks_repo_head_hexsha": "e70edb2da11f0be4db2882ddd7a07a8a6e0d4f06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 66.5056947608, "max_line_length": 424, "alphanum_fraction": 0.7400899667, "num_tokens": 25383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3258202154654124}}
{"text": "\\section*{Outline}\n\n\\begin{description}[leftmargin=!, labelwidth=0.7in]\n\\item[Chapter 1] Introduction\n\n\\item[Chapter 2] Background on Data Consistent Inversion:\n\\begin{description}[leftmargin=!, labelwidth=0.7in]\n\t\\item[Section 2.1] Notation, Terminology, and Assumptions\n\t\\item[Section 2.2] Set-Based Inversion for Measures\n\t\\item[Section 2.3] Sample-Based Inversion for Densities\n\t\\item[Section 2.4] Software Contributions (description of your updating of BET to Python 3 that you are doing for NSF goes here along with including the newer approach with densities that you are adding to BET, discuss testing, installation, etc. at a high level)\n\t\\item[Section 2.5] Illustrative Examples\n\\end{description}\n\n\\item[Chapter 3] Impact of Output Quantities on Accuracy\n\\begin{description}[leftmargin=!, labelwidth=0.7in]\n\\item[Section 3.1] Skewness and Information Content (this is a review section)\n\\item[Section 3.2] Skewness and Accuracy of Set-Based Inversion (this is a summary of your MS work updated for TV metric)\n\\item[Section 3.3] Skewness and Accuracy of Sample-Based Inversion (newer work that you were doing but hadn't written up yet, focus on linear problems and how KDEs deal with skewness on the data space)\n\\item[Section 3.4] Software contributions (adding the module to BET that computes the TV metric that is updated from your MS work, also discuss testing, and simple examples of usage that are disconnected from skewness, mostly high level)\n\\item[Section 3.5] Numerical results and analysis\n\\end{description}\n\n\\item[Chapter 4] Data-driven maps and Consistent Inversion\n\\begin{description}[leftmargin=!, labelwidth=0.7in]\n\\item[Section 4.1] A Generalized Stochastic Map Framework (material from the paper I am finishing up -- hopefully in the next two weeks for first draft -- goes here to set the stage)\n\\item[Section 4.2] Data-driven maps (also material from the paper including sensitivity analysis as the number of data points $M$ increases)\n\\item[Section 4.3] Software contributions (adding a module in BET to transform time series into QoI and do the data-consistent inversion)\n\\item[Section 4.4] Numerical Results and Analysis\n\\end{description}\n\n\\item[Chapter 5] Other Research from NSF project yet to be done/defined well enough to sketch out this chapter - perhaps functional assimilation discussion? Maybe no chapter 5 on this? We will see.\n \n\\item[Chapter 6] Summary, Conclusions and Future Research Directions\n\n\\item[Bibliography]\n\n\\end{description}", "meta": {"hexsha": "68526d5a9c8c2131fc02c823ae2dfa6718803f2e", "size": 2477, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "outline.tex", "max_stars_repo_name": "mathematicalmichael/thesis", "max_stars_repo_head_hexsha": "2906b10f94960c3e75bdb48e5b8b583f59b9441e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-04-24T08:05:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-28T20:34:29.000Z", "max_issues_repo_path": "outline.tex", "max_issues_repo_name": "mathematicalmichael/thesis", "max_issues_repo_head_hexsha": "2906b10f94960c3e75bdb48e5b8b583f59b9441e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 59, "max_issues_repo_issues_event_min_datetime": "2019-12-27T23:15:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T17:52:57.000Z", "max_forks_repo_path": "outline.tex", "max_forks_repo_name": "mathematicalmichael/thesis", "max_forks_repo_head_hexsha": "2906b10f94960c3e75bdb48e5b8b583f59b9441e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 65.1842105263, "max_line_length": 264, "alphanum_fraction": 0.7892612031, "num_tokens": 639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.3258078876680581}}
{"text": "\\section{Constraints}\nIn this section, the constraints we have taken into account in the project are introduced. A plausible set of constraints is fundamental in order to perform a realistic simulation, which is required in order to have reasonable simulation outcomes. \n\\subsection{Input constraints}\n\nThe vehicle model presented in Section \\ref{chap:Vehicle_model} assumes that the inputs $\\delta_f$ (front steering angle) and throttle (driving and braking) can be controlled\ndirectly. In practice, however, low-level controllers are used to transform the aforementioned\ncommands into physical control signals.\n\\subsubsection{Steering angle constraints}\nRegarding the steering angle control, we have supposed that our MPC directly affects the Electronic Power Steering (EPS) system by sending to it the target steering wheel position. Then, the EPS control unit calculates the optimal steering output based on the target steering wheel position received and sends the information to an electric motor in order to provide the necessary action on the wheels.\nFor the sake of this project, we have assumed this link to be ideal which implies that our MPC directly controls the angle of our front wheels. The values used are reported in the Table \\ref{tab:steering} and they have been chosen according to real data\\cite{forkenbrock2005assessment}.\n\n\\begin{table}[H]\n\\begin{center}\n\\begin{tabular}{lllll}\n\\cline{2-3}\n\\multicolumn{1}{l|}{}                         & \\multicolumn{1}{l|}{\\textbf{min}} & \\multicolumn{1}{l|}{\\textbf{max}} &  &  \\\\ \\cline{1-3}\n\\multicolumn{1}{|l|}{\\textbf{Steering angle}} & \\multicolumn{1}{l|}{-36 $deg$}      & \\multicolumn{1}{l|}{36 $deg$}      &  &  \\\\ \\cline{1-3}\n\\multicolumn{1}{|l|}{\\textbf{Steering rate}}  & \\multicolumn{1}{l|}{-60 $deg/s$}    & \\multicolumn{1}{l|}{60 $deg/s$}    &  &  \\\\ \\cline{1-3}\n\\end{tabular}\n\\caption{Steering constraints}\n\\label{tab:steering}\n\n\\end{center}\n\\end{table}\n\n\\subsubsection{Throttle constraints}\nAs stated in Section \\ref{chap:Vehicle_model}, the vehicle model used in our simulation is,  more or less, independent of the longitudinal dynamics of the vehicle. Moreover, the set of simulations we carry out are to be performed at constant speed, as close as possible to the target speed value. \nPhysical limits on the actuators and comfort requirements impose bounds on the throttle and its rate of change according to the Table \\ref{tab:throttle}.\n\n\\begin{table}[H]\n\\begin{center}\n\\begin{tabular}{lllll}\n\\cline{2-3}\n\\multicolumn{1}{l|}{} & \\multicolumn{1}{l|}{\\textbf{min}} & \\multicolumn{1}{l|}{\\textbf{max}} &  &  \\\\ \\cline{1-3}\n\\multicolumn{1}{|l|}{\\textbf{Throttle}} & \\multicolumn{1}{l|}{-7.85 $m/s^2$}  & \\multicolumn{1}{l|}{4 $m/s^2$} &  &  \\\\ \\cline{1-3}\n\\multicolumn{1}{|l|}{\\textbf{Throttle rate}} & \\multicolumn{1}{l|}{-20 $m/s^3$}    & \\multicolumn{1}{l|}{8 $m/s^3$} &  &  \\\\ \\cline{1-3}\n\\end{tabular}\n\\caption{Throttle constraints}\n\\label{tab:throttle}\n\\end{center}\n\\end{table}\n\n\\subsection{Output/State constraints}\n% - Output/State: Lane keeping and obstacle avoidance\nMPC algorithms allow to define a set of constraints on the States/Output variables of the model. In our project, this feature allows us to describe a forbidden zone nearby the obstacle when it is detected. In order to properly define this area, we refer to the art.148 and art.149 of the Italian reference legislation ``\\textit{Codice della Strada}\" which states that while traveling and overtaking, the vehicles must keep a safety distance from the vehicle in front of them.\n\n\n\\subsubsection{Safety distance}\n\\label{sec:Safety_distance}\n% The art. 149 of the Italian reference legislation ``\\textit{Codice della strada}\" states that ``while traveling, the vehicles must keep a safety distance from the vehicle in front of them such that timely stopping is guaranteed in any case and collisions with the vehicles in front are avoided\".\nIn order to estimate the optimal safety distance that each vehicle must keep from the preceding one, several factors must be taken into account:\n\\begin{itemize}\n    \\item the alertness of the driver's reflexes;\n    \\item the type and response of the vehicle;\n    \\item the vehicle speed;\n    \\item the visibility and weather conditions;\n    \\item the slope of the road and the characteristics and conditions of the road surface;\n    \\item the traffic.\n\\end{itemize}\nUnder the previous assumptions it's clear that it is impossible to exactly evaluate the safety distance because there are a multitude of factors that continuously change over time.\nAmong these, the most important one is the speed at which the vehicle is travelling. A common formula relates the safety distance to the square of the speed:\n\\begin{align}\n   SafetyDistance [m] = \\left(\\frac{v[\\sfrac{km}{h}]}{10}\\right)^2\n   \\label{eq:safetyDistance}\n\\end{align}\nMoreover the safety distance is strictly correlated to the stopping space that is the sum of the reaction space and braking space.\nThe former is the distance traveled by the vehicle in the reaction time (usually 1 second), the latter is proportional to the square of the speed and inversely proportional to the deceleration and the friction coefficient.\n\\begin{align}\n    BrakingSpace = v^2/(2a \\times \\mu)\n\\end{align} \nThe following table presents the value of the braking space associated to different speed and friction coefficient values:\n\\begin{table}[H]\n\\resizebox{\\textwidth}{!}{%\n\\begin{tabular}{|l|l|l|}\n\\hline\nVehicle speed & Braking space on dry asphalt ($\\mu=0,8$) & Braking space on wet asphalt($\\mu=0,4$)\\\\ \\hline\n20 km/h & 2.0 m & 3,9 m\\\\ \\hline\n40 km/h & 7,9 m & 15,7 m\\\\ \\hline\n60 km/h & 17,7 m & 35,4 m\\\\ \\hline\n80 km/h & 31,5 m & 62,9 m\\\\ \\hline\n100 km/h & 49,2 m & 98,3 m\\\\ \\hline\n120 km/h & 70,9 m & 141,7 m\\\\ \\hline\n\\end{tabular}%\n}\n\\caption{Braking distance with respect to vehicle speed and road condition}\n\\label{tab:braking}\n\\end{table}\n\\noindent\nIn our work we have decided to consider the \\textit{SafetyDistance} evaluated as in the Eq. \\ref{eq:safetyDistance} to define the aforementioned \\textit{``forbidden zone\"}.\n\n", "meta": {"hexsha": "3ebbc31163c4cb319b27777e5e226ca87d386879", "size": 6065, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Documentation/Report/Chapters/6-Constraints.tex", "max_stars_repo_name": "meltinglab/dynamic-obstacle-avoidance", "max_stars_repo_head_hexsha": "2290754436864a817851c71803d5275445cbcdb1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-05-24T07:00:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-19T16:44:04.000Z", "max_issues_repo_path": "Documentation/Report/Chapters/6-Constraints.tex", "max_issues_repo_name": "meltinglab/dynamic-obstacle-avoidance", "max_issues_repo_head_hexsha": "2290754436864a817851c71803d5275445cbcdb1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Documentation/Report/Chapters/6-Constraints.tex", "max_forks_repo_name": "meltinglab/dynamic-obstacle-avoidance", "max_forks_repo_head_hexsha": "2290754436864a817851c71803d5275445cbcdb1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-04-20T19:24:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T17:58:16.000Z", "avg_line_length": 66.6483516484, "max_line_length": 475, "alphanum_fraction": 0.7437757626, "num_tokens": 1675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.3258078803363456}}
{"text": "\\section{Architecture}\n\nIn this chapter will be discussed deeply the architecture of the three main parts of the \\textbf{Perceptron}. The general structure could be summarized by the following schema:\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=12cm]{img/architecture_general_schema.pdf}\n\t\\caption{General Schema}\n\\end{figure}\n\n\\subsection{Multiplication Circuit Architecture}\nThe Multiplication Circuit, as said before, will be implemented through a Parallel Multiplier. The inputs $b_{i}$ and $w_{i}$ are composed respectively by $b_{x} = 8$ bits and $b_{w} = 9$ bits. In order to compute the multiplication in the correct way, the inputs need to be translated in the \\textbf{unsigned form} and then is possible to perform the multiplication with the parallel multiplier.\nIn the following image is presented the general schema of the Parallel Multiplier:\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=\\textwidth]{img/architecture_general_parallel_multiplier.pdf}\n\t\\caption{Parallel Multiplier Architecture}\n\\end{figure}\nNotice that the \\textbf{sign} of the result will be computed by a simple \\textit{XOR} operation between the inputs signs. \nThe \\textbf{Unsigned Parallel Multiplier} architecture is the following:\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=13cm]{img/architecture_parallel_multiplier.pdf}\n\t\\caption{Unsigned Parallel Multiplier Architecture}\n\\end{figure}\nEach logic block is translated with a related logic block:\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.7\\textwidth]{img/architecture_parallel_multiplier_meaning.pdf}\n\t\\caption{Unsigned Parallel Multiplier Architecture}\n\\end{figure}\n\\subsection{Adder Circuit Architecture}\nIn order to compute the equation (1.1) different sums need to be computed. The building block of this part will be the \\textbf{Parallel Adder with Pipeline}: as said before, by adding some registers in between the Carry chains, the critical path impact can be reduced. Furthermore, by exploiting the parallel architecture, a single sum can be computed in a single clock cycle. In the next figure will be presented the Parallel Adder:\n \\begin{figure}[H]\n \t\\centering\n \t\\makebox[\\textwidth][c]{\\includegraphics[width=1.5\\textwidth]{img/architecture_full_adder_with_pipeline.pdf}}%\n \t\\caption{Parallel Adder Architecture}\n \\end{figure}\nIn order to obtain an output, after an input drive, there is a need to wait $\\floor*{\\frac{N}{N_{pipeline}}}$ clock cycles, where $N$ represent the number of bits of $a$ or $b$ and $N_{pipeline}$ represent the maximum number of consecutive FA without a register in between.\\\\\nTo implement the whole sum of 11 terms, \\textbf{in order to decrease the number of cycles needed} to compute the whole sum and to reduce the number of bits needed, a tree approach has been chosen. The schema of the tree parallel adder is the following:\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=\\textwidth]{img/architecture_adder_tree.pdf}\n\t\\caption{Parallel Multiplier Architecture}\n\\end{figure}\n\n\\textbf{Note some extension or left shifts (i.e. for b) were not represented.}\\\\\nSome register has been put in between the sum to limit the critical path impact on the performances and clock period limit. \nTo obtain a good output after an input drive there is a need to sum to 3 (the maximum number of consecutive register in the previous architecture) each Ripple Carry Adder contribution in terms of number of clock as seen before.\n\n\\subsection{Activation Function Circuit Architecture}\nAt the end of the computation of the latter phase the output is composed by $21$ bits. The computation of the sigmoid function will be done through a \\textbf{Look-Up-Table}, which will need \\textbf{$2^{21} = $ 2097152 entries} of different outputs with $16$ bits. In order to reduce the size of the Look-Up-Table a truncation is needed: from $21$ bits to $12$ bits. In this case the Look-Up Table will be composed by \\textbf{$2^{12} = $ 4096 entries}, but, by exploiting the \\textbf{odd symmetry} of the sigmoid, only \\textbf{$4096/2 = $ 2048 entries} are needed.\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.6\\textwidth]{img/architecture_lut_optimized.pdf}\n\t\\caption{Look-Up Table Architecture}\n\\end{figure}\n\nAll things considered, by performing the calculation showed before, there is a need of 26 \\textbf{clock cycles} to obtain a correct output after driving an input.\n ", "meta": {"hexsha": "8571fbff7bfe4b09d30b0b5c74fd16fe4a70055f", "size": 4381, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/chapters/architecture.tex", "max_stars_repo_name": "gerti98/Electronic-Systems-Project", "max_stars_repo_head_hexsha": "0691bbef06eb5a038c1324b3b8aa529d2346dbdc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/chapters/architecture.tex", "max_issues_repo_name": "gerti98/Electronic-Systems-Project", "max_issues_repo_head_hexsha": "0691bbef06eb5a038c1324b3b8aa529d2346dbdc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/chapters/architecture.tex", "max_forks_repo_name": "gerti98/Electronic-Systems-Project", "max_forks_repo_head_hexsha": "0691bbef06eb5a038c1324b3b8aa529d2346dbdc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 74.2542372881, "max_line_length": 563, "alphanum_fraction": 0.7874914403, "num_tokens": 1075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.3258078803363456}}
{"text": "\\documentclass{article}\n%\\documentclass[prl,amsmath,amssymb]{revtex4} % PRL\n\n% margins of 1 inch:\n\\setlength{\\topmargin}{-.5in}\n\\setlength{\\textheight}{9in}\n\\setlength{\\oddsidemargin}{0in}\n\\setlength{\\textwidth}{6.5in}\n\n\\usepackage[pdftex]{hyperref} % hyperlink equation and bibliographic citations\n\\usepackage[dvips]{graphicx,color}\n\\usepackage{amsmath} % advanced math\n\\usepackage{verbatim}\n\\usepackage{natbib} % bibilography \n\\usepackage{mciteplus} % collapse multiple citations in bibilography\n\\usepackage{multicol}\n\\usepackage[toc,page]{appendix} % http://tex.stackexchange.com/questions/49643/making-appendix-for-thesis\n\n\n% from http://www.flakery.org/search/show/569\n%\\newcommand{\\infint}{\\ensuremath{\\int_{-\\infty}^{\\infty}}}\n\\newcommand{\\cf}{\\textit{c.f.}} % \"compare\". In context the abbreviation advises readers to consult other material, drawing attention to related ideas that provide additional arguments or information.\n\\newcommand{\\ie}{\\textit{i.e.}} % i.e. is used to explain, clarify or rephrase a statement\n\\newcommand{\\eg}{\\textit{e.g.}} % “for the sake of example”. Used to introduce an example or list of examples to illustrate what is being discussed.\n\\newcommand{\\eqn}[1]{Eq.\\ (\\ref{#1})}\n\\newcommand{\\pfrac}[2]{\\ensuremath{\\frac{\\partial #1}{\\partial #2}}}\n\\newcommand{\\pdg}{Physics Derivation Graph}\n\n% http://tex.stackexchange.com/questions/59166/span-column-in-a-multicols-environment\n\\newcommand{\\multicolinterrupt}[1]{% Stuff to span both rows\n\\end{multicols}\n#1\n\\begin{multicols}{2}\n}\n\n\\begin{document}\n\\title{User Manual for the \\pdg}\n\n\\author{Ben Payne$^{1}$\\footnote{Corresponding author: ben.is.located@gmail.com}, Michael Goff$^{2}$\\\\\n{\\it $^{1}$Department of Fun, University Name \\& Town, city, State Zip}\\\\\n{\\it $^{2}$Department of , University of ,  }}\n\n\\date{\\today}\n\n\n\\maketitle % declares end of title page\n\\begin{abstract}\nOverview of current implementation. It is assumed here that the Introduction to the \\pdg\\ has been read. \n\\end{abstract}\n\n\\begin{multicols}{2}\n\n%\\tableofcontents\n\n%\\newpage\n\n\\section{Introduction}\n\n% relevant project background\nThe \\pdg\\ is a project designed to document mathematical physics knowledge. \nThe mathematics necessary to describe physics can be written down, in this case in the form of a graph. \nThe core of this project is a set of databases storing that content and an associated set of scripts for various manipulations of the content. \nThose scripts include the ability to generate visualizations of the graph, and to generate reports based on the graph content.\n\nSection~\\ref{sec:databases} describes the databases which store these values. \n\n\\section{Databases\\label{sec:databases}}\n\nThe content associated with physics knowledge takes the form of expressions (\\textit{equations and inequalities}), symbols, and inference rules. \n\\textit{An inference rule is an atomic transformation of one expression to another.} \nAn example is provided here. \n\nFrequency $f$ and period $T$ are related by\n\\begin{equation}\nT\\ f = 1\n\\label{eq:period_and_freq}\n\\end{equation}\nThus, frequency in terms of the period is\n\\begin{equation}\nf = 1/T\n\\label{eq:freq_is_inverse_period}\n\\end{equation}\nThe relation between \\eqn{eq:period_and_freq} and \\eqn{eq:freq_is_inverse_period} is that both sides of \\eqn{eq:period_and_freq} were divided by $T$. \n\nIn this example, there are two mathematical expressions: \\eqn{eq:period_and_freq} and \\eqn{eq:freq_is_inverse_period}. \nThese expressions are related by an inference rule: ``Divide both sides of first equation by a value to yield the second equation.'' \nThis inference rule takes an argument, referred to here as the ``feed'', which in this example is $T$. \nThis set of steps is shown graphically in~Fig.~\\ref{fig:freq_period}. \nThis simple step between two expressions is documented in five separate databases: expressions, symbols, feeds, inference rules, and connections. \n\nEach expression, symbol, and inference rule appears only once in the respective database. \nEach time an expression, symbol, or inference rule is used in a derivation, that unique instance is referenced. \nThis referencing of unique expressions, symbols, and inference rules is done using a numeric identifier (alphanumeric for inference rules).\n\nIn the expressions database, each expression has an associated 10 digit number in base 10. For example, \\eqn{eq:freq_is_inverse_period} is 2113211456 and \\eqn{eq:period_and_freq} is 2131616531. Similarly, the symbols have unique 15 digit numeric identfiers. Period $T$ is 192938440120938 and frequency $f$ is 102938475990112. The database of expressions references these symbol identifiers -- expression 2113211456 uses symbols 192938440120938 and 102938475990112. \n\nThe connections database is the set of derivations. A derivation involving \\eqn{eq:freq_is_inverse_period} refers to the expression identifier 2113211456 and relates it to 2131616531 by an inference rule which is identified by the alphanumeric string ``dividebothsidesby''. This inference rule takes an argument, referred to here as a ``feed.'' The feed database contains the value, in this example $T$ and a 7 digit identifier 8837284. Feeds are not unique, though the identifiers used are. The $T$ referred to for this use of the inference rule ``dividebothsidesby'' does not need to be associated with other instances of ``dividebothsidesby''. \n\nThe \\pdg\\ is designed to show one instance of each expression, but feeds and inference rules will have duplicates on the graph. To allow for this, the connections database has a unique 7 digit numeric identifier assocaited with each use of an inference rule. \n\n%transition paragraph\nThe databases supporting the \\pdg\\ are implemented using comma-separated (CSV) plain-text files with no headers. \n\n\\subsection{Implementation: Symbols\\label{sec:symbols}}\n\n\\begin{verbatim}\n<symbol>\n  <symbol_name></symbol_name>\n  <symbol_punid></symbol_punid>\n  <type></type>\n  <description></description>\n  <cas_sympy></cas_sympy>\n  <units></units>\n</symbol>\n\\end{verbatim}\n\n\\subsection{Implementation: Expressions\\label{sec:expressions}}\n\n\\begin{verbatim}\n3131111133,\"T=1/f\"\n\\end{verbatim}\n\n\\subsection{Implementation: Connections\\label{sec:connections}}\n\nIn the connections database, the \n\\end{multicols}\n\\begin{figure}\n\\begin{verbatim}\n\"frequency relations\",6, \"expression\",8482459,3131111133,\"infrule\",2939482,subRHSofExprXintoExprY\n\\end{verbatim}\n\\caption{Fig.~1: connections database content example.}\n\\end{figure}\n\\begin{multicols}{2}\n\\section{Database manipulation}\n\nThe databases are manipulated using software written in Python\\cite{2015_Python} version 2.7.6. \nEach script in the \\texttt{bin} directory performs a single task. \nCommon functions are stored in \\texttt{lib/lib\\_physics\\_graph.py}. \nThe scripts in \\texttt{bin} are described here in order of increasing complexity. \n\n\\subsection{Listing}\n\nThe two simplest scripts are for listing content from the connections and inference rules databases, respectively. \n\\begin{verbatim}\nbin/list_connection_sets.py\nbin/list_inference_rules.py\n\\end{verbatim}\n\nThe output of listing the connection sets are the derivations which are listed in the connections database.\n\\begin{verbatim}\nbin/list_connection_sets.py\n    frequency_relations\n    quadratic_equation_derivation\n    euler_equation_proof\n    euler_equation_trig_sqrt\n    example_of_Godel_problem\n    particle_in_a_1D_box\n    ...\n\\end{verbatim}\n\n\n\n\\subsection{Statistical Analysis}\nThere are three scripts which build on the listing functionality and count instances of inference rules, expressions, and symbols, respectively. \n\\begin{verbatim}\npopularity_of_inference_rules.py\npopularity_of_statements.py\npopularity_of_symbols.py\n\\end{verbatim}\n\n\\begin{verbatim}\nbin/popularity_of_statements.py\n    10 4938429483 \\exp(i\\ x) = \\cos(x)+...\n    6 3948574230 \\psi(\\vec{r},t) = ...\n    5 5727578862 \\frac{d^2}{dx^2} ...\n    ...\n\\end{verbatim}\nFor example, \\eqn{eq:freq_is_inverse_period} is referenced twice as of this writting. \n\n\\subsection{Utilities}\nThe utility scripts are meant for use by developers of the content. \n\\begin{verbatim}\ncreate_pdf_of_statements.py\ncreate_pictures_of_inference_rules.py\ncreate_pictures_of_statements_and_feeds.py\ngenerate_new_random_index.py\n\\end{verbatim}\nCreating a PDF of the expressions can be used to validate the \\LaTeX syntax of content in \\texttt{databases/expressions\\_database.csv}\n\n\\subsection{Primary functions}\n\n\\begin{verbatim}\ncheck_connections_using_CAS_sympy.py\nbuild_connection_set_pdf.py\nbuild_connections_graph.py\n\\end{verbatim}\n\nThe \\texttt{build\\_*.py} scripts are described in detail in sections \\ref{sec:reports} and \\ref{sec:visualization}, respectively. \n\nChecking the connections using SymPy is not fully supported. \n\n\\section{Report generation\\label{sec:reports}}\n\n\\LaTeX\\cite{1994_Latex} PDFs can be created by running \\texttt{bin/build\\_connection\\_set\\_pdf.py}\n\n\\section{Visualization of Graph\\label{sec:visualization}}\n\nDOT language\\cite{2015_Graphviz} \n\n\\texttt{bin/build\\_connections\\_graph.py}\n\n\\section{Creating a new Derivation\\label{sec:new_derivation}}\n\n\\subsection{New Symbol\\label{sec:new_symbol}}\n\nFirst, pick a symbol from your derivation.\n\nSecond, check whether that symbol exists in the symbol database. If it does, you are done.\n\nIf your symbol is not already in the symbol database, the third step is to get a new  random index (``available symbol numeric identifier''). \n\nCopy the symbol CSV fields to create a new entry\n\nPlace the symbol and new numeric identifier into the appropriate field\n\n\\subsection{New expression\\label{sec:new_expression}}\n\nFirst, pick the expression to be added.\n\nSecond, check whether that expression exists in the expression database. If it does, you are done\n\nIf your expression is not already in the expression database, the third step is to get a new random index (``available expression numeric identifier''). \n\nIn the expressions database, copy the expression CSV fields into the appropriate derivation. \n\nPlace the \\LaTeX expression and numeric identifier in the appropriate field. \n\nDetermine the SymPy equivalent. Include that in the CSV\n\nDetermine the symbols in the expression. See section~\\ref{sec:new_symbol}. Include the symbol numeric identifiers in the expression database.\n\n\\subsection{New Connection\\label{sec:new_connection}}\n\nAn inference rule connects expressions\n\n\\subsection{New Derivation\\label{sec:how_derivation}}\n\nA derivation is composed of a sequence of expressions connected by inference rules\n\n\\section{Summary}\n\n\\section{Bibliography}\n\n\\bibliographystyle{unsrt}\n\\bibliography{../bibliography} % external bibtex flat-file database\n\\end{multicols}\n\n\\newpage\n\\appendix\n%\\begin{appendices}\n%\\include{appendix_test_cases}\n%\\end{appendices}\n\n\n\\end{document}\n", "meta": {"hexsha": "5041d610aca8890ea9877534620ee637d1c892b4", "size": 10742, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "v3_CSV/doc/user_manual.tex", "max_stars_repo_name": "carlosal1015/proofofconcept", "max_stars_repo_head_hexsha": "579873aff082e6fa497a387e0d0a5f8e5ec3ecd2", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2015-01-02T19:39:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T06:08:10.000Z", "max_issues_repo_path": "v3_CSV/doc/user_manual.tex", "max_issues_repo_name": "carlosal1015/proofofconcept", "max_issues_repo_head_hexsha": "579873aff082e6fa497a387e0d0a5f8e5ec3ecd2", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 242, "max_issues_repo_issues_event_min_datetime": "2015-01-02T13:59:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T17:22:21.000Z", "max_forks_repo_path": "v3_CSV/doc/user_manual.tex", "max_forks_repo_name": "carlosal1015/proofofconcept", "max_forks_repo_head_hexsha": "579873aff082e6fa497a387e0d0a5f8e5ec3ecd2", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2015-02-13T16:00:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-05T17:51:26.000Z", "avg_line_length": 40.3834586466, "max_line_length": 647, "alphanum_fraction": 0.7863526345, "num_tokens": 2708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.3258078803363456}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% \tTemplate for seminar reports\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\documentclass[a4paper,pdftex]{scrartcl}\n\n\\usepackage[utf8]{inputenc}   \n\\usepackage{graphicx}\n\\usepackage{amstext}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{hyperref}\n\\usepackage{bm}\n\\usepackage{comment}\n\\usepackage{listings}\n\n% no page number on first page\n% \\pagestyle{empty}\n\\usepackage[colorinlistoftodos]{todonotes}\n\\usepackage{acronym}\n\n\\newcommand{\\dx}{\\text{d}x}\n\n\\begin{document}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% \tPaper title\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\title{Designing interactive webapplications for mathematical visualization}\n\\subtitle{}\n\n\\author{\nChristian Karpfinger, Benjamin Rüth\\\\\nTechnische Universit\\\"at M\\\"unchen\\\\\nEmail: benjamin.rueth@tum.de \n}\n\n\\maketitle\n\n%abstract\nWe developed a flexible open--source based workflow with the specific application of webdriven, platform independent, interactive applications for mathematical visualization in the context of university education. Our main goal is to realize mathematical visualization with no requirements of programming skills or program installation on the user--side. The Python plotting library Bokeh plays a crucial role in our approach.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% \tSections, Subsections,...\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Introduction}\nWe wanted to setup interactive webapplications for the visualization of math content, specially in the context of the math lecture for mechanical engineering students. The goal was to have an environment where as few user interaction as possible is necessary to get the application running and with as less visible code as possible. Both restrictions are in our opinion very important, because a non smooth start--up of the application often frustrates the user and especially undergraduate students often do not want or are not able to program (even few lines of code), sometimes even seeing code results in the user immediatelly leaving the webpage. Therefore we put up the following constraints to our application:\n\\begin{itemize}\n\\item no installation or log--in required\n\\item no visible code and no necessity to access or modify code \n\\item use of open source software\n\\item interactive modification of math visualizations\n\\item high flexibility with respect to plotting and interaction\n\\end{itemize}\nBefore starting this project we have used videos generated in MATLAB for visualizing mathematical content. At some point we found out that many topics cannot be visualized properly by creating a video. Often it has a much higher effect, if the user is able to play around with parameters and try out different combinations of parameters on ones own.\n\nOur MATLAB videos were --- obviously --- not able to fulfil our constraints. Also other environments like \"Wolfram CDF Player\" (huge installation, not open source), \"IPython Notebook\" (too much code interaction) or \"Geogebra\" (only basic scripting language, not flexible) do not fulfil our criteria and turned out to be not appropriate for that specific task.\n\nThe Python framework is in general very flexible, open--source and also extendible, since many scientific applications base on Python. After some research we discovered the plotting library Bokeh, which is similar to matplotlib, but also supports interactive manipulation of the plots with different kinds of widgets as well as running these interactive plots on a server. In the following we want to describe our workflow for setting up an interactive webapp using Bokeh as well as the other used tools. \n\n\\section{Installation}\nThe Framework \\href{}{Anaconda} turned out to be a good choice for the installation of all the necessary python modules. The installation of Anaconda is described at\n\\begin{center}\n\\href{http://continuum.io/downloads}{http://continuum.io/downloads}\n\\end{center}\n\nAfter the installation of Anaconda one can install Bokeh with the following commands:\n\\begin{verbatim}\n$ sudo conda install bokeh\n\\end{verbatim}\nIf installation fails due to access rights create environment.\n\\begin{verbatim}\n$ conda create -n my_root\n$ sudo activate my_root\n\\end{verbatim}\nExit environment with\n\\begin{verbatim}\n$ source deactivate\n\\end{verbatim}\nFor development one can use the IDE spyder. Running Spyder from \\verb!sudo! often causes problems, don't do this! If problems with the libraries occur run\n\\begin{verbatim}\n$ spyder --reset\n$ spyder\n\\end{verbatim}\n\n\\section{The idea}\nOur goal was to implement an interactive Fourier--Series app. The Fourier--Series of a $2\\pi$--periodic  function $f(x)$ is defined in the following way:\n\\begin{align*}\nf\\left(x \\right) = \\frac{a_0}{2}+\\sum\\limits_{k=1}^\\infty \\left[a_k \\cos\\left(kx \\right) + b_k \\sin\\left(kx\\right)\\right],\\\\\n\\intertext{with}\na_k = \\frac{1}{\\pi}\\int\\limits_{0}^{2\\pi} f\\left(x \\right)\\cos\\left(kx\\right)\\dx \\text{\\quad and\\quad }\nb_k = \\frac{1}{\\pi}\\int\\limits_{0}^{2\\pi} f\\left(x \\right)\\sin\\left(kx\\right)\\dx.\n\\end{align*}\nThis representation is exact, if one uses infinitely many coefficients $a_k,b_k$. If one truncuates the series after $n$ coefficients, such that we set $a_k,b_k = 0 \\forall k>n$ we do not get an exact representation of $f(x)$, but only an approximation:\n\\begin{align*}\nf\\left(x \\right) \\approx \\frac{a_0}{2}+\\sum\\limits_{k=1}^n \\left[a_k \\cos\\left(kx \\right) + b_k \\sin\\left(kx\\right)\\right].\n\\end{align*}\nWe now wanted to implement a app, where the user has the possibility to choose the value of $n$ and can therefore interactively control the accuracy of the approximation of $f(x)$. An additional goal is to visualize the analytical representation of the fourier series at the same time, such that the user can see different phenomena:\n\\begin{itemize}\n\\item The higher we choose $n$ the longer our analytical expression is.\n\\item Even functions (symmetrical to the y--axis) produce only $\\cos$ terms in the series expansion, odd functions (point--symmetrical to the origin) produce onyl $\\sin$ terms in the series expansion.\n\\item The coefficients are decreasing along the series.\n\\end{itemize}\nOf course one can also proof all these properties, but seeing them \"in action\" often has a bigger effect.\n\n\\section{Implementation}\nThe mathematical functionality has been implemented in the file \\verb!fourierFunctions.py!; these functions just supply us with some example functions $f(x)$ and functions for the calculation of the coefficients and the evaluation of the fourier series. We will not explain these in detail.\n\nThe dynamic generation of \\LaTeX\\ strings depending on the degree of the fourier series and $f(x)$ is done in \\verb!fourierTex.py!.\n\nThe most important part of our implementation is in \\verb!fourierApp.py!. This file sets up the web app and uses the previously mentioned files to correctly handle user input.\n\nThese functions are only able to publish our app directly on the Bokeh plotting server. For more elaborate functionality (like the dynamic update of \\LaTeX\\ strings) we feed the output of the Bokeh plotting server to a \\href{}{Flask} server(which is able to handle to \\LaTeX\\ strings sent via an request). The \\LaTeX\\ strings are finally embedded into the html file via \\href{https://www.mathjax.org/}{MathJax}.\nAll source files can be found in the appendix as well as on GitHub: \\href{}{}\n\n\\section{Running the App}\nFor running the app one firstly has to start the Bokeh plotting server via\n\\begin{verbatim}\n$ bokeh-server -m --backend=memory\n\\end{verbatim}\nThen one has to run the script starting the App on the plotting server\n\\begin{verbatim}\n$ python fourierApp.py\n\\end{verbatim}\nOne can now access the App at the plotting server. For enabling displaying of dynamically generatex \\LaTeX\\ strings one has to run\n\\begin{verbatim}\n$ python fourierFlask.py\n\\end{verbatim}\nfor starting the Flask server. The FourierApp can now be accessed from any Browser.\n\n\\section{Conclusions}\nWith Python and Bokeh we have the possibility to realize a large field of visualizations. Additionaly to sliders, Bokeh also supplies many other Widgets like buttons, checkboxes, dropdown--lists etc. as well as many different kinds of 2D plots.\nEmbedding These Bokeh plots in a Flask environment gives us additionaly the possibility to modify the html content directly from our app.\nCurrently we are working on running this app on a server as well as developing more interactive visualizations. Another already completed app is the visualization of different ODE solvers where the user is able to control parameters as step size and initial value.\n\n\\appendix\n\\section{Listings}\n\\subsection{fourierApp.py}\n\\lstinputlisting[basicstyle=\\scriptsize]{fourierApp.py}\n\\subsection{fourierFunctions.py}\n\\lstinputlisting[basicstyle=\\scriptsize]{fourierFunctions.py}\n\\subsection{fourierTex.py}\n\\lstinputlisting[basicstyle=\\scriptsize]{fourierTex.py}\n\\subsection{fourierFlask.py}\n\\lstinputlisting[basicstyle=\\scriptsize]{fourierFlask.py}\n\\end{document}\n\n\n\n", "meta": {"hexsha": "a2e1753627da4f5958886ce220984dd5985d0e98", "size": 9190, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Math_Apps/Fourier_series_approximation/Doc/fourierSpecification.tex", "max_stars_repo_name": "ChairOfStructuralMechanicsTUM/Mechanics_Apps", "max_stars_repo_head_hexsha": "b064a42d4df3fa9bde62a5cff9cb27ca61b0127c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2017-05-06T17:05:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T09:26:47.000Z", "max_issues_repo_path": "Math_Apps/Fourier_series_approximation/Doc/fourierSpecification.tex", "max_issues_repo_name": "ChairOfStructuralMechanicsTUM/Mechanics_Apps", "max_issues_repo_head_hexsha": "b064a42d4df3fa9bde62a5cff9cb27ca61b0127c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 49, "max_issues_repo_issues_event_min_datetime": "2017-04-20T11:26:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-29T13:18:06.000Z", "max_forks_repo_path": "Math_Apps/Fourier_series_approximation/Doc/fourierSpecification.tex", "max_forks_repo_name": "ChairOfStructuralMechanicsTUM/Mechanics_Apps", "max_forks_repo_head_hexsha": "b064a42d4df3fa9bde62a5cff9cb27ca61b0127c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-02-14T12:55:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T15:07:07.000Z", "avg_line_length": 60.4605263158, "max_line_length": 717, "alphanum_fraction": 0.7510337323, "num_tokens": 2099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.32580788033634556}}
{"text": "\n\\chapter{The Lambek bijection}\n\\label{chap:4}\n\\thispagestyle{empty}\nIn this chapter we raise bridges between Category Theory and simply typed $\\lambda$-calculus. The main sources for this chapter are \\cite{lambek1988introduction}, \\cite{lambek1985cartesian} and \\cite[Chapter 6]{selinger2008lecture}.\\\\\n\nIn this chapter we do an important work of unification and organization of the sources used. In general, whenever the connection of category theory and $\\lambda$-calculus is presented, these concepts are introduced in their most similar description. We consider that this approach, while requiring less work, loses in knowledge and intuition.\\\\\n\n\nAvoiding this work means that the bijection does not convey a fundamental idea. A closed Cartesian category naturally extracts the essence of programming. In particular, (following the notation of the definition), it is the adjoint $G_3$ and the unity of this adjoint what allows us to consider functions and application of functions as elements of the category, thus providing a computational system.\\\\\n\nIn this chapter we will begin by giving the anticipated definition of a deductive system, and from this we will be able to give an equational definition of closed Cartesian categories.  After this we will define the categories of the various $\\lambda$-calculi, and finally prove the existence of an adjoint equivalence between the two categories.\\\\\n\n\n\n\\section{Deduction systems}\nHaving introduced the notion $\\lambda$-calculus, category theory and propositional intuitionistic calculus, is time to to go a step back to get the full picture.\n\n\\begin{definition}\n  A \\emph{deductive system} $D$ is a graph  with identity and composition of arrows.\n\\end{definition}\n\nWe can reformulated the previous logic with this optic. Prior to that we will make an illustrative example on how is this made. All the properties aforementioned (and paired) show that the requirements of typing/intuitionistic calculus can be expressed in simple requirements for the arrows. Let us show some examples.\n\\begin{example}\n  \\begin{enumerate}\n  \\item Deduction rule $\\to_1$: There is an arrow $$\\varepsilon_{A,B}: [B\\land (B \\to A)] \\to A.$$\n  \\item From the deduction rule $\\to_2$ it can be deduced that, from the assumption $C \\land B \\to A$:\n    \\begin{align*}\n      \\Gamma,\\{\\} \\vdash & F= (C\\land B)\\to A;\\\\\n      \\Gamma, \\{(C\\land B)\\} \\vdash & A;\\\\\n      \\Gamma, \\{C, B\\} \\vdash & A;\\\\\n      \\Gamma, \\{C\\} \\vdash & B\\to A;\\\\\n      \\Gamma, \\{\\} \\vdash & F'=C \\to (B \\to A).\n    \\end{align*}\n    That is provided an arrow $h: C\\land B \\to A$ there is an induced arrow\n    $$h^*:C \\to [A\\to B].$$\n  \\end{enumerate}\n\\end{example}\n\nWe can check that the second example includes an idea about the relation between assumption and deduction systems. We can view each assumption of truth as a new deduction system. This also seems logical, since an assumption $\\Gamma = \\{A_i : i=1,...,n\\}$  with $A_i$ formulas can be seen as an existence of an arrow $g_i: \\top \\to A_i$.\\\\\n\n% We see that in our derivations we sometimes need to change the truth-assumption $\\Gamma$. This is not mandatory, but it is useful to avoid including a large number of rules. However we do that in a way such that we start from a given $\\Gamma$ and return to it at the end of the derivation. Thus knowing that if a $\\Gamma$ derives the formula $F$, then it also derives the formula $F'$ and therefore there is an arrow in our deductive system. Similar reflections can be made with the rest of the rules discussed in the previous sections, and of course with the simply typed $\\lambda$-calculus. \\\\\n\n\n\n\\subsection{Logical Systems as Deduction systems}\nIn  the fashion of the previous definitions we can reformulate logical systems as deduction systems.\n\\begin{definition}\n  A conjunction calculus is a deductive system $D$ where there is a specified object $\\top$ and an operation $\\land: Ob(D)\\times Ob(D) \\to Ob(D)$ such that:\n  \\begin{enumerate}\n  \\item For each $A\\in Ob(D)$ there exists an arrow $O_A:A\\to \\top$.\n  \\item For each $A_1,A_2\\in Ob(D)$ there exist arrows $\\pi_i^{A_1,A_2}: A_1 \\land A_2 \\to A_i$ for $i=1,2$.\n  \\item Let $f:C\\to A$ and $g:C\\to B$ be arrows of D . Then $\\langle f,g\\rangle : C\\to A\\land B$.\n  \\end{enumerate}\n\\end{definition}\n\nNote that $\\pi_i^{A_1,A_2}$ depends on both $A_1,A_2$. In the absence of ambiguity we will denote this arrow by $\\pi_i$.\n\n\\begin{definition} \\label{def:positivecalculus}\n  A positive intuitionistic calculus is a conjunction calculus $D$ where there is binary an operator $\\leadsto: Ob(D)\\times Ob(D) \\to Ob(D)$ such that:\n  \\begin{enumerate}\n  \\item For each $A,B \\in Ob(D)$, there is an arrow $\\varepsilon^{A,B}: [(B \\leadsto A) \\land B]\\to A$.\n  \\item For each $g:C\\land B \\to A$ then there is an arrow $g^*: C\\to [B\\leadsto A]$.\n  \\end{enumerate}\n\\end{definition}\n\\begin{remark}\n  In the future, in absence of ambiguity, we will use $\\to$ instead to $\\headsto$. We will also make use of $[]$ to avoid ambiguity whenever possible.\n\\end{remark}\nSimilarly to $\\pi_i$, we will usually denote just $\\varepsilon$. \n\\begin{definition}\\label{def:intuipropcalculus}\n  A \\emph{intuitionistic propositional calculus} is a positive intuitionistic calculus where there is a specified object $\\bot$ and an operation $\\lor: Ob(D)\\times Ob(D) \\to Ob(D)$ such that:\n  \\begin{enumerate}\n  \\item For each $A\\in Ob(D)$ there is an arrow $\\square_A: \\bot\\to A$.\n  \\item For each $A_1,A_2\\in Ob(D)$ there are arrows $\\iin_i: A_i\\to A_1 \\lor A_2 $.\n  \\item For each $A,B,C \\in Ob(D)$ there is an arrow $$h:[(B\\leadsto A)\\land (C\\leadsto A)] \\to [(C\\lor B)\\leadsto A].$$\n  \\end{enumerate}\n\\end{definition}\n\n\\begin{definition}\n  Given a conjunction calculus $D$, for every $f:A\\to B \\in D$ there exists an arrow $f^\\to: \\top \\to [A\\to B]$, defined as \n  $$f^\\to = \\left(f\\circ \\pi_2^{\\Top,A}\\right)^*.$$\n\\end{definition}\n\nThis last definition has an important meaning. It formalizes within our system the fact that if we have a proof that $A$ implies $B$, in the form of an arrow, it generates a proof that the statement \"$A$ implies $B$\", as an object, is also true (since it can be derived from truth value $\\top$). We finish this section with the definition of assumption and the deduction theorem.\\\\\n\nAs we have seen during the last part of the previous chapter, there is a constant work in the deduction system in changing each truth assumption. So the question is: how can we adapt this idea to a deduction system $D$? This is done by introducing \\emph{assumptions}.\n\n\\begin{definition}\\label{assumptions}\nThese assumptions are arrows $x^A: \\top \\to A$, which does not have to be in $Ar(D)$\\footnote{That is, an assumption can be considered as an extra edge in the graph created by the deduction system.}. These arrows allow us to consider new implications. Given $x^A$ we can consider proofs $\\varphi(x^A)$ by composition of arrows in $D$ with $x$.\n\\end{definition}\nThis derive lastly in  a proposition, widely known in the context of propositional logic:\n\n\\begin{theorem}[Deduction Theorem]\\label{deduction-theorem}\n  In a conjunction calculus $D$, a proof $\\varphi(x^A): B \\to C$ dependent on an assumption $x^A: \\top \\to A$ implies the existence of a proof $\\lambda x^A.\\varphi (x^A): A\\land B \\to C$ not dependent on $x^A$.\n\\end{theorem}\n\\begin{sproof}\n  As most proofs in the previous chapter, this proposition is proved by induction on the length on the proof, and studying the list of possible last steps taken. A full proof can be found in \\cite[proposition 2.1]{lambek1988introduction}.\n\\end{sproof}\n We are implicitly using the idea of the adjoint $f:A\\times B \\to C \\cong f: A \\to C^B$, although it is not needed for the formalism.\n\n\n\n\n\n\\subsection{Categorical systems as Deduction systems}\n\nWe have already noted that a category is a particular case of a deduction system. We can consider how are the logical systems, in the view of the Curry-Howard bijection, but we only focus on category systems.\n\n\\begin{remark}Now that  we see categories as deduction systems, we have a notation problems. We will identify $A\\land B$ with $A\\times B$. While in a deductive system we have defined $\\langle f_1,f_2\\rangle : C \\to A\\land B$ we have done the same in categories, meaning $$\\langle f_1,f_2\\rangle : C \\land C \\to A \\land B.$$  This was necessary in deduction system to not put a burden of having a diagonal arrow $C\\to C\\land C$. This make though some extra verbosity in functions like $\\langle h\\pi_1, \\pi_2\\rangle : C\\times B \\to A\\times B$, that would otherwise be the much more legible $\\langle h, 1_b\\rangle: C\\times B \\to A \\times B$. \n\\end{remark}\n\n\n\\begin{proposition}\\label{prop:CartCategory2}\n  A Cartesian category $\\mathcal{C}$ is a deduction system that is both a conjunction system and a category satifying:\n  \\begin{enumerate}\n  \\item If $f:A\\to T$ and $g:A\\to T$ then $f=g$.\n  \\item Given $\\langle f_1,f_2\\rangle: C\\to A\\land B$ then $\\pi_i \\circ \\langle f_1,f_2\\rangle = f_i$.\n  \\item Given $h:C\\to A\\land B$ we have that $\\langle \\pi_1 h, \\pi_2 h\\rangle = h$.\n  \\end{enumerate}\n\\end{proposition}\n\n\\begin{proof}\n\n  Lets begin by proving that a Cartesian category satisfy this conditions. It is clearly a category. Let us consider as terminal object $T=\\top$ and let us take as product $A\\times B = A\\land B$ for every $A,B \\in C$ along with the projections $pi_i$, the properties are satisfied.\\\\\n\n  Conversely, considering again $T= \\top$ we can check that it is a terminal object. Also, for every $h:C\\to A\\land B$ we can see that every $h$ derive the existence of unique $f_1,f_2$ such that:\n  \\[\n    \\begin{tikzcd}\n      {} & C \\arrow[bend right,swap,dashed]{dl}{f_1}\n      \\arrow[bend left,dashed]{dr}{f_2} \\arrow{d}[description]{h}& & \\\\\n      A  &A\\land B \\arrow{l}[swap]{\\pi_1} \\arrow{r}{\\pi_2} & \n      B \\\\\n    \\end{tikzcd}\n  \\]\n  And thus we have finite product.\n\\end{proof}\n\nThus, we can start seeing the kind of bijection already shown in the Curry Howard Isomorphism. Hitherto we can adopt the notation $A\\times B$ for the conjunction, in the context of Cartesian categories.\n\\begin{proposition}\\label{def2:CCC}\n  A closed Cartesian category $\\mathcal{C}$ is a deduction system that is a positive intuitionistic calculus and a category, and which satisfies:\n  \\begin{enumerate}\n  \\item   For all $h: c\\times b \\to a$ , we have that $\\varepsilon \\langle h^* \\pi_1, \\pi_2\\rangle = h$.\n  \\item   For all $k: c\\to [b \\to a]$ , we have that $(\\varepsilon \\langle k \\pi_1, \\pi_2\\rangle)^* = k$.\n  \\end{enumerate}\n\\end{proposition}\n\n\\begin{proof}\n  \n  Let us begin by checking that $\\mathcal{C}$ is a positive intuitionistic calculus and holds 1. and 2. As it is a Cartesian category, it is a conjunction calculus.\n  \\begin{itemize}\n  \\item We identify $a\\to b$ with the exponential object $b^a$. For every $b\\in Ob(C)$, following the notation from definition \\ref{def:CCC}, we have an adjoint $F_3^b\\dashv G_3^b = (F^b,G^b,\\varphi^b,\\eta^b,\\varepsilon^b)$. Then, we define the arrows from definition \\ref{def:positivecalculus} as\n    $$\\varepsilon^{a,b}: [(b \\to a) \\land b]\\to a = \\varepsilon^b(a), \\qquad g^* = \\varphi(g).$$\n  \\item Then, 1. is obtained by considering that, given a morphism $h: F_3^b c = c\\times b \\to a$, we have that, $\\varepsilon^b(a) \\circ F_3^b(\\varphi(h)) = h$, due to the fact that $$(\\varphi^b)^{-1}(h: d \\to Gc) = \\varepsilon^b(c)\\circ F_3^b(h).$$\n  \\item Conversely, if part 1. was the left part of the inverse definition, 2. is the right part.\n  \\end{itemize}\n\n  To prove that any intuitionistic calculus that is also a category is a closed Cartesian category, we just made the same pairing, $a\\times b = a\\land b$ and $a\\to b = b^a$ to define $F_b^3$ on both objects and arrows\\footnote{where $F_b^3(h:a\\to a') = \\langle h, 1_b\\rangle $} define $G_3^b$ on objects, and define $\\varepsilon^b(a)$ as $\\varepsilon^{a,b}$.\n\\end{proof}\n\n\n\n\n\n\n\n  % As it is a cartesian category, by it does satisfy the requirements for being a conjunction calculus. Pairing the exponential object $cA^B$ with the function object $B\\to A$. As in definition \\ref{def:CCC}, we have  3 adjoints, the first two of them are already considered as we have that $C$ is a cartesian category. We now study the third of them and remember that $F_3^B=F$ and $G_3^B=G$ are both adjoint, i.e.:\n  % $$\\hom_C(C \\times B, A) \\equiv \\hom(C, A^B)$$\n\n  % Therefore, we can check the second part in definition \\ref{def:positivecalculus}. Then, remembering proposition \\ref{prop:univAdjoint}, we can deduce the existence of a natural transformation  $\\varepsilon: FG \\to I_C$ i.e. $\\varepsilon: A^B\\times A = (B\\to A)\\land A \\to A$, having the first part in definition \\ref{def:positivecalculus}.\\\\\n\n  % The proof of 1. and 2. are conditions of universality. Lets unpack 1. as 2. is the same reasoning on the other side of the adjoint. We have (remember that, in the notation of part I: $\\langle h^*\\pi_1, \\pi_2\\rangle = \\langle h^*,1_B\\rangle$, and we used to note $h^*=\\varphi(h)$):\n  % \\[\n  %   \\begin{tikzcd}\n  %     C\\times B\\arrow{d}{h}&C\\arrow{d}{h^*} & C\\times B\\arrow{d}{\\langle h^*,1_B\\rangle} & A^B\\times B\\arrow{d}{\\varepsilon}\\\\\n  %     A & A^B = B\\to A & A^B\\times B & A \n  %   \\end{tikzcd}\n  % \\]\n\n  % therefore, putting it all together, and remembering the \\emph{evaluation} fashion of $\\varepsilon$ (i.e., we have that the following diagram commutes. The \n\n  % \\[\n  %   \\begin{tikzcd}\n  %     C\\times B\\arrow{d}{h} \\arrow{r}{\\langle h^*,1_B\\rangle}& A^B\\times B \\arrow[swap]{dl}{\\varepsilon}\\\\\n  %     A&\n  %   \\end{tikzcd}\n  % \\]\n\n  \n  % To do the converse, is enough to made the same pairings and apply the notions of universality of $\\varepsilon$ in  and apply \\ref{prop:equivdefinition} to check that such adjoints are define via $\\arepsilon$.\n\n\n\n\n\\begin{proposition} A \\emph{closed bi-Cartesian category} is a deduction system that is both a intuitionistic propositional calculus and a category, with the additional equations:\n  \\begin{enumerate}\n  \\item $f:\\bot \\to A \\implies f=\\square_A$.\n  \\item Given $[f_1,f_2] : A\\lor B \\to C$ then $ [f_1,f_2]\\circ \\iin_i  = f_i$.\n  \\item Given $h:A\\lor B\\to C$ we have that $[ h\\iin_1, h\\iin_2] = h$.\n  \\end{enumerate}\n\\end{proposition}\n\\begin{remark}\n  Is usual to denote $A\\lor B$ as $A+B$ or $A\\sqcup B$, as we are working with the coproduct.\n\\end{remark} \n\\begin{proof}\n  We have proved that it is already a closed Cartesian category. Extra considerations are dual to those already considered for a Cartesian category.\n\\end{proof}\n\\subsection{Polynomials in closed Cartesian categories}\n\nWe want now to introduce the concept of logical implications in the context of a closed Cartesian category $C$. For that, we can use the naive idea to consider the terminal object $\\top \\in C$, as a value of truth, and then deduce that any object $a\\in C$ such that there exists an arrow $f:\\top \\to a$, then $a$ is also true. In this idea, the natural progression is to consider a $a$ to be true by desire, so we add a new arrow $x:\\top \\to a$ to the category, and to complete the category so the axiom of metacategories are still satisfied. In this section we are going to formalize this idea.\n\\begin{definition}\n  Given a (Cartesian, closed Cartesian) category $C$, we say that an \\emph{indeterminate} arrow $x: a \\to b; a,b \\in C$ is an arrow $x:a \\to b$  not necessarily included in $Ar(C)$. \n\\end{definition}\n\\begin{remark}\\label{remark-indeterminates}\n  Whenever we talk about an indeterminate arrow, we just talk about an arrow with the special quality that it does not have to exist within our predefined set of arrows. The new emphasis is that we do not care what the arrow is exactly, in a similar way as it is usually do with numeric variables. \n\\end{remark}\n\\begin{remark}\n  Indeterminates $x: 1\\to a$ are assumptions, as in definition \\ref{assumptions}.\n\\end{remark}\n\n\\begin{definition}\\cite[Part I, Chapter 5]{lambek1988introduction}\n  Given a (Cartesian, closed Cartesian) category $C$, and a indeterminate $x: a \\to b$, we define the \\emph{category of $C$ based on the indeterminate $x:a\\to b$}, denoted by $C[x]$, as the category that has:\n  \\begin{enumerate}\n  \\item As objects the same object as in $C$.\n  \\item As arrows, we have $Ar(C[x])$ is the collection of words with alphabet $Ar(C) \\cup {x}$ quotiented by the equivalence relations:\n    \\begin{itemize}\n    \\item Preserve   $C$-equivalence: for all $g:b\\to c,f:a\\to b, h: a\\to c\\in C$,\n      \\begin{center}\n        $gf=h \\in C\\qquad $ implies $\\qquad gf \\cong h\\in C[x].$\n      \\end{center}\n\n    \\item Preserve composition: for all $f:a\\to b,f':a\\to b,g:b\\to c,g': b \\to c\\in Ar(C[x])$,\n      \\begin{center}\n        $f\\cong f', g\\cong g'\\qquad$ implies $\\qquad fg\\cong f'g'$.\n      \\end{center}\n      \n    \\item Preserve identity: for all $f:a\\to b\\in C[x]$ we have $f1_a\\cong f \\cong \\con 1_bf$.\n    \\item Associative: for all $f:a\\to b, g:b\\to c, h: c\\to d$ we have $(fg)h\\cong f(gh)$.\n    \\end{itemize}\n  \\end{enumerate}\n  Thus arrows are equivalence classes. Arrows in $C[x]$ are called \\emph{polynomials} in $x$.\n\\end{definition}\n\\begin{remark}\nWe have defined the equivalence on arrows $\\cong$ so that the inclusion $C\\hookrightarrow C[x]$ is a functor.\n\\end{remark}\n\\begin{definition}\n  Let $C$ be a (Cartesian, closed Cartesian) category and let $X=\\{x_1:a_1 \\to b_1, ... x_n:a_n \\to b_n\\}$ be a finite  set of indeterminates. We define the category $C[X]$, also denoted as $C[x_1,...,x_n]$, as $C[x_1][x_2]..[x_n]$.\n\\end{definition}\n\\begin{remark}\n  Note that for every permutation $\\sigma : \\{1,...,n\\}\\to \\{1,..,n\\}$, we have that $C[x_1]...[x_n]\\cong A[x_{\\sigma(1)}]...[x_{\\sigma(n)}]$. \n\\end{remark}\n\n% \\begin{remark}\n%   Note that the terms can be formed by the arrows $1\\to A\\in C$, the indeterminates $x^A: 1 \\to A$,  and the term forming operations:\n%   \\begin{align*}\n%     a,b,f,\\varphi(x^A) := \\langle a,b\\rangle: 1 \\to A\\times B \\ |\\ fa: 1 \\to B\\ |\\ \\lambda x^A. \\varphi(x^A): 1 \\to [A\\to B]\n%   \\end{align*}\n%   where we require $a: 1\\to A, & b: 1 \\to B,   f: A \\to B, \\varphi(x^a): 1 \\to B$\n% \\end{remark}\n\\begin{proposition}\\label{unique-polynomial-functor}Let $C,C'$ be (Cartesian, closed Cartesian) categories, let $F$ be a (Cartesian, closed Cartesian) functor, and $X=\\{x_1,...,x_n\\}, X'=\\{x_1',...,x_n'\\}$ be sets of assumptions for $C$ and $C'$ respectively. Then there is an unique (Cartesian, closed Cartesian) functor $F_{x_1,...,x_n}$ such that $F(x_i)=x_i'$ and the following diagram commutes. \n  \\[\n    \\begin{tikzcd}\n      C[X]\\arrow[dashed]{rr}{F_{X\\to X'}}&& C'[X]\\\\\n      C \\arrow{rr}{F}\\arrow[hookrightarrow]{u}{}&& C'\\arrow[hookrightarrow]{u}{}\n    \\end{tikzcd}\n  \\]\n\\end{proposition}\n\\begin{proof}\n  Immediate as $C[x_1,...,x_n]$ is the expansion of $C$ and ${x_1,...,x_n}$.\n\\end{proof}\n\nThis construction satisfies a nice property:\n\n\\begin{proposition}\\label{univ-polynomial}\n  Given a (resp. Cartesian, closed Cartesian) category $A$, an indeterminate $x:a_0\\to a$ over $A$, a functor $F:A\\to B$ and an arrow $ b:F(a_0) \\to F(a) \\in B$, there is a unique (Cartesian, closed Cartesian) functor $F': A[x]\\to B$ such that the following diagram commutes:\n  \\[\n    \\begin{tikzcd}\n      A\\arrow[hookrightarrow]{r}{} \\arrow[rd, \"F\", swap]      & A[x] \\arrow[d, \"F'\", dashed]& x:a_0\\to a\\arrow[d,\"f'\",dashed]\\\\\n      &B& b:F(a_0)\\to F(a) \n    \\end{tikzcd}\n  \\]\n\\end{proposition}\n\\begin{proof}\n  Observe that polynomials in closed Cartesian categories have to be defined inductively, with the following rules:\n  \\begin{enumerate}\n  \\item $x$ is a polynomial.\n  \\item Every arrow $f:a \\to b\\in A$ is a polynomial.\n  \\item The composition (resp.  [composition and product],  [composition, product and $*$-operation]) of every polynomial is a polynomial.\n  \\end{enumerate}\n  Thus, $F'$ is defined by the values on $x$ and $Ar(A)$, so it exists. As in this case we have both  $x$ and $Ar(A)$ fixed, $F'$ is unique. \n\\end{proof}\n\n\nWe finish this subsection presenting a refinement of the proposition \\ref{deduction-theorem}. This result is also proved by induction on the length of the proof.\n\n\\begin{proposition}[functional completeness]\n  For every polynomial $\\varphi(x^a): 1\\to C$ over a closed cartesian category $C[x^a]$ with an indeterminate $x:1\\to a$, there is an unique arrow $f$ such that $f\\circ x=\\varphi(x)$.\n\\end{proposition}\n\n\\section{Categorical understanding of simply typed $\\lambda$-calculus}\nAfter introducing the new optic explained in the previous section, we will use it to complete the Lambek equivalence. For this we will make a series of preparations. We first introduce the concept of natural numbers in categories and in $\\lambda$-typed calculations.\\\\\n\nThe introduction of the natural numbers in $\\lambda$-calculus has been delayed, because it is a construction that is inspired by our own construction for categories, and we believe that by explaining them straight away we can grasp the underlying idea of the natural numbers in a more efficient way.\\\\\n\nWe will proceed by introducing the basic $\\lambda$-calculus as a category, and explaining the categorical equivalence between it and the category of closed Cartesian categories.\n\n\\subsection{Natural Numbers}\n\n\nWe begin this section by motivating the introduction of natural numbers. The importance of this concept lies in the fact that we want a computation system. These systems, in a modern practical case, are actually intended to compute a function from the natural numbers to the natural numbers (either on a tape in a Turing machine, a recursion as in Gödel's computational system, or an abstract formalization in $\\lambda$-calculus).\\\\\n\nWe have already seen how natural numbers can be done in untyped calculus. However in this section we will approach the problem, formalizing the notion for typed calculus and introducing the concept of natural numbers in categories.\n\n\\subsubsection{Natural Numbers in Categories}\n\n\n\\begin{definition}\n  Given a closed Cartesian category $C$, a tuple  $(N,S:N\\to N)\\in Ob(C)\\times Ar(C)$ is said to be a \\emph{natural number system} when, for every $f:A\\to A\\in C$, there is an unique $h$ such that\n  \\[\n    \\begin{tikzcd}\n      1\\arrow{dr}{a}\\arrow{r}{0} & N\\arrow{r}{S}\\arrow[dashed]{d}{h} & N\\arrow[dashed]{d}{h}\\\\\n      & A\\arrow{r}{f} & A\n    \\end{tikzcd}\n  \\]\n  When $h$ exists but is not necessarily unique $(N,S)$ is said to be a \\emph{weak natural number system}.\n\\end{definition}\nEvery time natural numbers are mentioned, induction have to appear in some part. The intuition of the categorical concept is that we have a object $N$ that is the set of every natural, and a successor arrow $S$.\n\nWe can consider natural numbers systems as an initial object. Having a closed Cartesian category $C$, we can consider it as a marked category $C_*$, such as in $Set_*$, with the specified object being $\\top =1$. We can also consider the category $J$ provided by the diagram:\n\n\\[\n  \\begin{tikzcd}\n    1\\arrow{r}{0} & N\\arrow{r}{S} & N\n  \\end{tikzcd}\n\\]\nwith the specified point being $1$. Then considering the functor category $C_*^J$ we can see that every arrow has the form: \n\\[\n  \\begin{tikzcd}\n    1\\arrow{r}{0}\\arrow{d}{1_1} & N\\arrow{r}{S}\\arrow{d}{h} & N\\arrow{d}{g}\\\\\n    1\\arrow{r}{a} & A\\arrow{r}{f} & A\n  \\end{tikzcd}\n\\]\nand is denoted by $(1,h,g)$. Considering the category $(C_*^J)'$ with objects as in $C_*^J$ and arrows  $\\{(1,h,g)\\in C_*^J: h=g\\}$ we have that a natural number for $C$ is an initial object in $(C_*^J)'$. This observation allow us allows us to provide a simple proof of the following result a consequence of proposition \\ref{prop:initial}:\n\n\\begin{proposition}\n  Any two natural number objects are isomorphic.\n\\end{proposition}\n\n\n\n\\begin{definition}[Category of closed Cartesian categories]\n  The \\emph{category of closed Cartesian categories with natural numbers} $CCart_N$  is the category that has as objects all small closed Cartesian category with natural number systems, and as arrows all functors that preserve the structure of closed Cartesian categories and added natural numbers structure.\\\\\n\\end{definition}\n% {\\color{red} Maybe add the proposition and corollary 9.1 and 9.2 of Lambek.}\n\n\n\\subsubsection{Natural Numbers in simply typed $\\lambda$-calculus}\\label{section:natural-revisited}\n\nAs a consequence of the Curry-Howard isomorphism, we obtained an identification between logic and lambda-calculus. Afterwards, as we start considering different deduction system  (conjunction calculus, positive, intuitionistic) in logic. Analogously, we can consider different typed $\\lambda$-calculus (basic, standard, expanded), each one paired with a deduction system. Finally, we restricted these deduction systems to the world of categories which gave us also another set of paired categories (Cartesian, closed Cartesian, closed bi Cartesian). \\\\\n\n\n\nHaving laid the intuition of what a natural number is in category theory we can proceed to explain what a natural number is in simply yped $\\lambda$-calculus. Relating the notions of typed $\\lambda$-calculus shown in \\cite[Section 10]{lambek1988introduction}, \\cite[Section 6]{selinger2008lecture} and \\cite[Section 10]{cardone2006history}, we can see that it is opted by Lambek to  include, for simplicity, some structure over the basic type $\\iota$  to provide with a natural number type:\n\n\\begin{remark}\n  Remember that $\\iota$ was a basic type with no added structure.\n\\end{remark}\n\\begin{definition}[Lambek natural numbers]\n  \\emph{Natural number in simply typed lambda-calculus} is a simply typed $\\lambda$-calculus with the added structure for raw typed $\\lambda$-terms:\n  \\begin{align*}\n    A,B, C ::= ...\\ |\\ \\mathfrak{o}\\ |\\ S(A)\\ |\\ I_t(A,B,C);\n  \\end{align*}\n  for every type $t$, and the related typing rules:\n  \\begin{itemize}\n  \\item If $N$ is of type $\\iota$ so is $S(N)$:\n    $$  (S)\\qquad  {\\displaystyle\\Gamma \\vdash N:\\iota \\over \\Gamma \\vdash S(N):\\iota}.$$\n    In addition, $\\mathfrak{o}$ is of type $\\iota$:\n    $$  (\\mathfrak{o})\\qquad  {\\displaystyle\\over \\Gamma \\vdash \\mathfrak{o}:\\iota}.$$\n  \\item If $M: A$, $H: A\\to A$ and $N : \\iota$ then we can apply $H$ to $M$, $N$ times and get a result in $A$:\n    $$  (I)\\qquad  {\\displaystyle\\Gamma \\vdash N:\\iota, \\qquad \\Gamma \\vdash M:A,\\qquad \\Gamma \\vdash H:A\\to A \\over \\Gamma \\vdash I_A(M,H,N):\\iota}.$$\n  \\end{itemize}\n\\end{definition}\n\n\\begin{remark} \\label{remark-natural-numbers}\n  Natural number systems can be defined over any of the different typed $\\lambda$-calculus since we made the definition by simply adding structure to the term formation rules.\n\\end{remark}\n\nThis option has some positive notes:\n\\begin{enumerate}\n\\item We have, as in categories, an object $N$ that is a natural number.\n\\item It encapsulates in a formalism the properties of Church numerals used in untyped $\\lambda$-calculus.\n\\end{enumerate}\n\nNonetheless we have already carried out a construction over natural numbers in untyped $\\lambda$-calculus. That construction is replicable in the context of typed $\\lambda$-calculus.\n\n\\begin{definition}[Church numerals in typed $\\lambda$-calculi]\n We define the $n$-th Church numeral in typed $\\lambda$-calculi as, for a type $t$:\n  $$\\overline n^t = \\lambda f^{t \\to t}. \\lambda x^{t}. f^{n}(x).$$\n  \n\\end{definition}\n\n\\begin{remark}\n  $\\overline n^t$ is of type $(t\\to t)\\to(t\\to t)$.\n\\end{remark}\n\nAs a consequence of this proposition, we can consider a type $N^t: (t \\to t) -> (t \\to t)$ such that $\\overline n^t:N^t$ for every $n\\in\\mathbb{N}$ and every type $t$. Nonetheless:\n\\begin{enumerate}\n\n\\item To have a similar behaviour of multiple application of a function, the natural numbers are dependent on the type. In this setting, strictly speaking, there is a natural number family for each type $t$.\n\\item There is not a type exclusively for natural numbers, as not necessarily every element of $(t\\to t)\\to(t\\to t)$ is a natural number.\n\\end{enumerate}\nFrom this point on, we will use the Lambek description of natural numbers, letting Church numerals as a construction derived for untyped $\\lambda$-calculus.\\\\\n\n% Lastly, we can consider the effect of Lambek description in $\\beta$-reduction.\n\n\\subsection{The category of simply typed $\\lambda$-calculus}\n\nThe objective of this section is to finish forming an idea that has been present for some time in this work: the existence of several $\\lambda$-calculations. \\\\\n\nIn chapter 3, we have described how there exists different $\\lambda$-calculus, the same way that there exists multiple groups, as either $\\lambda$-calculus and a group is only a structure,. We may continue by defining the category of $\\lambda$-calculus. For that we first define the concept of morphism as a structure preserving mapping.\n\n\n\n\\begin{definition}[Morphisms of lambda-calculus]\n  Let $L, : '$ be minimal (resp. basic, expanded) $\\lambda$-calculus (resp. with natural numbers). A morphism $F: L \\to L '$ is a function that\n  \\begin{enumerate}\n  \\item Maps types in $ L$ to types in $L '$, Terms in $L$ to terms in $L '$ and if $a\\in L$ is a closed term, so is $F(a)$, and sends variables to variables. For example: $$F(1) = 1, \\qquad F(*) = * \\qquad or \\qquad F(A+B) =F(A)+F(B).$$\n    \n  \\item Preserves the structure of minimal (resp. basic, expanded) $\\lambda$-calculus (resp. with natural numbers) up to $\\alpha$-equivalence, $\\beta$-equivalence and $\\eta$-equivalence. \n\n  \\end{enumerate}\n\n  Morphisms of $\\lambda$-calculus will be also called $\\lambda$-morphism for short, in cases of ambiguity.\n\\end{definition}\n\n\n\\begin{definition}[Category of lambda-calculus]\n  We can define the category $\\LC$ of minimal simply typed $\\lambda$-calculus (resp. basic, expanded)  as the category that:\n  \\begin{itemize}\n  \\item Has as objects the different minimal (resp. basic, expanded) typed $\\lambda$-calculus.\n  \\item Has as arrow the $\\lambda$-calculus morphism.\n  \\end{itemize}\n  Similarly, we can define the category of $\\LC_N$ basic typed $\\lambda$-calculus with natural numbers as in remark \\ref{remark-natural-numbers}, adding that a morphism should also preserve natural numbers.\n\\end{definition}\n\n\\subsection{The internal language of a Closed Cartesian Category}\n\nUp to this moment, we have related that a closed Cartesian category is a positive intuitionistic calculus, which is equivalent to a typed $\\lambda$-calculus, with some extra structure.\\\\\n\nNow we have to consider the original ideas that were the precursor of categorical thinking: the Poincaré functor. This functor, in short,  sees how to consider a group within a topology, and see that we can infer group morphisms. This is the original idea behind the functors, and we will now provide an example that is similar in flavor to the Poincaré functor: we will generate a $\\lambda$-calculus from a closed Cartesian category.\\\\ \n\n\n\n\\begin{definition}\n  Let $C$ be a closed Cartesian category. Then its \\emph{internal language} $\\LL (C)$ is the basic $\\lambda$-calculus that:\n  \\begin{itemize}\n  \\item Has as types the objects of $C$, with function types given by exponential types, conjunction types by product types, and the 1 type by the terminal object $\\top \\in Ob(C)$.% \\begin{table}[!h]\n    % \\begin{center}\n    %   \\begin{tabular}{|l|c|c|}\n    %     \\hline\n    %     Typing name & Types  & Closed Cartesian categories  \\\\\n    %     \\hline\n    %     Minimal     & Function type $A\\to B$   &  Exponential object $B^A$  \\\\\n    %     \\hline \n    %     Basic      & Type 1 & Terminal object $\\top$ \\\\\n    %     & Product type $\\times$ & Product object $\\land$ \\\\\n    %     \\hline   \n    %   \\end{tabular}\n    %   \\caption*{\\label{tab:table-name} Pairing of Types and object in closed Cartesian categories.}\n    % \\end{center}\n    % \\end{table}A\n  \\item In $\\LL(A)$ a variable $x^{t_i}$ of type $t$ is just an indeterminate  $x:1 \\to t_i$, and terms of type $A$ are polynomial $\\varphi(x_1^{t_1},...,x_n^{t_n}):1 \\to A$, where each indeterminate $x_i: 1 \\to t_i,$ for $i$ in $1,...,n$ represents a free variable.\n  \\item We endow this set with the structure of a simply typed $\\lambda$ calculus as follows\\footnote{Instead of typing rules we provide equivalent term forming operations.}:\n    \\begin{itemize}\n    \\item For every to polynomials $\\varphi: 1 \\to A, \\psi: 1\\to B$ we have the term $\\langle \\varphi, \\psi \\rangle: 1 \\to A\\times B$ defined by the universal property of the product. Projections $\\pi_i$ in $\\lambda$-calculus are found by composition with the projection in the context of the category.\n    \\item Given $\\varphi(x^a):1 \\to B$ we want to find $\\lambda x^a.\\varphi(x^a): 1 \\to B^A$.  For that we first apply proposition \\ref{deduction-theorem} to found $k_{x^A}\\varphi(x^A): 1 \\land A \\to B$. After that, using the adjoint properties of the closed Cartesian category, we can find:\n      $$\\lambda x^A.\\varphi(x^A) := \\left( k_{x^A}\\varphi(x^A)\\right)^*: 1 \\to B^A.$$\n      % , i.e., is the unique arrow  such that:\n      % \\[\n      %   \\begin{tikzcd}\n      %     {} & C \\arrow[bend right,swap,dashed]{dl}{g}\n      %     \\arrow[bend left,dashed]{dr}{h} \\arrow{d}[description]{f}& & \\\\\n      %     A  &(A,B) \\arrow{l}[swap]{fst} \\arrow{r}{snd} & \n      %     B \\\\\n      %   \\end{tikzcd}\n      % \\]\n    \\item Application is defined by $\\epsilon$, the counit of the adjoint $F_3\\dashv G_3$.\n    \\end{itemize}\n  \\end{itemize}\n\n\\end{definition}\n\n\n\\begin{remark}\n  In any simply typed $\\lambda$-calculus, we consider raw terms and then we consider only those that are subject to be typable. This was later understood as that any term being a proof of veracity of a type, via the Curry-Howard isomorphism. So, to maintain this idea of the arrows of the language being proof of veracity, we see them as arrows $f:\\top \\to A$, that is, as deductions from truth. \\\\\n\\end{remark}\n\nNow, we have to define how the functor behave over morphisms.\n\n\\begin{definition}\n  Let $F:C\\to C'\\in CCart_N$. We define $\\LL (F)$ as theas the morphism of $\\lambda$-calculi given by:\n  \\begin{itemize}\n  \\item $\\LL (F) (a)= F(a)$ for every term $a$, that is, for every $a\\in Ob(C)$.\n  \\item $\\LL (x^a) = x^{F(a)}$ for every variables $x^a \\in\\LL(C)$, that is, for every assumption $x: 1 \\to A$ in $C$.\n  \\item Let $X= \\{x_1^{t_1},...,x_n^{t_n}\\}$ be a set of indeterminates. Then for ever polynomial $\\varphi$ over $X$ we have that\n    $$\\LL(F)(\\varphi(X):1 \\to A) = F_{X\\to \\LL(X)}(\\varphi(X):1 \\to A)$$  where $F_{X\\to \\LL(X)}$ is defined as in proposition \\ref{unique-polynomial-functor}.\n  \\end{itemize}\n\\end{definition}\n\n\\begin{remark}\n  Preservation of the structure of a $\\lambda$-calculus is derived directely from the preservation of the closed cartesian category structure of $F$.\n\\end{remark}\n\n\\begin{proposition}\\label{natural-numbers}\n  If $C$ has weak natural numbers, $\\LL (C)$ has natural numbers. \n\\end{proposition}\n\\begin{proof}\n  Let $(N,S)$ be a weak natural number in $C$. We remember that in $\\LL(C)$ a term of type $A$ corresponds to a polynomial $\\varphi(x): 1 \\to A$.We define a natural number system in $L(C)$ as follows:\n  \\begin{itemize}\n  \\item we identify the $\\iota$ type with the object $N$.\n  \\item we identify the $\\mathfrak{o}$ term with the arrow $0: 1 \\to N$, seen as a polynomial.\n  \\item given a term $\\varphi$ of type $N$, we define $S(N)$ as $S\\circ\\varphi$. Every term of type $N$ is of the form $S^n\\circ \\mathfrak o$\n  \\item given a term $a$ of type $A$, a term $f$ of type $A\\to A$, and a term $n$  of type $N$, remembering the identification in the category $C$ we have that $h$ exists,\n    \\[\n      \\begin{tikzcd}\n        1\\arrow{dr}{a}\\arrow{r}{0} & N\\arrow{r}{S}\\arrow[dashed]{d}{h} & N\\arrow[dashed]{d}{h}\\\\\n        & A\\arrow{r}{f} & A\n      \\end{tikzcd}\n    \\]\n  \\end{itemize}\n\n  Lastly, we idenfity $I_A(a,f,n)$ 1ith $h\\circ n: 1 \\to A$.\n  \n\\end{proof}\n\n\\begin{proposition}\n  If $F: C\\to C \\in CCart_N$ is an endofunctor of $CCart_N$, then $\\LL (F)$ maintains natural numbers.\n\\end{proposition}\n\n\\begin{proof}\n\n  The results directly follows from $F$ maintaining weak natural numbers. \n\\end{proof}\n\n\\subsection{The Cartesian Closed Category generated by a typed $\\lambda$-calculus}\n\nIn this section we are going to do the converse process of the previous one, i.e., given a typed $\\lambda$-calculus, we are going to construct a related closed Cartesian category.\n\n\\begin{definition}\n  Given a typed $\\lambda$-calculus $L$ we can construct the \\emph{generated closed Cartesian category}, denoted by $\\CC (L)$ as follow:\n  \\begin{itemize}\n  \\item As objects it has the types in $L$.\n  \\item As arrows $f:a\\to b$ it has the terms $\\lambda x^a. b(x)$ where $b(x)$ is a term that only has $x^a$ as a free variable. Arrows are considered as equivalence classes up to $\\alpha\\beta\\eta$-equivalence.\n  \\end{itemize}\n\\end{definition}\n\nThe following proposition is discussed in plenty of sources. We choose to adapt some ideas done by \\cite{seely1984locally} to dependent typing, instead of following directly the main source \\cite{lambek1985cartesian} as we consider that it has a more natural approach.\n\\begin{proposition}\n  $\\CC (L)$ is a closed Cartesian  category. \n\\end{proposition}\n\\begin{proof}\n  We start checking the category axioms:\n  \\begin{itemize}\n  \\item Identity is given by $\\lambda x^a.x$.\n  \\item Composition of $\\lambda x^a. f(x):  a\\to b$ and $\\lambda x^b. g(x^b): b \\to c$ is given by $\\lambda x^a. g(f(x)): a \\to c$.\n  \\item Associativity follows from $\\beta$-equivalence.\\\\\n  \\end{itemize}\n  To provide the terminal object:\n  \\begin{itemize}\n  \\item The type $1$ is the terminal object. By $\\eta_\\times$ equivalence\\footnote{as in definition \\ref{def:eta_x}.}, the only term of type $1$ is $*$ up to equivalence. Therefore, any arrow $t:a \\to 1$ must be equivalent to $\\lambda x^a. *$.\\\\\n  \\end{itemize}\n  To provide the product type for two types $a,b$.\n  \\begin{itemize}\n  \\item The type product is provided by $a \\times b$.\n  \\item The projections are provided by $\\beta_{x,i}$ with the projections $\\pi_1,\\pi_2$.\n  \\item Given three types $a,b,c$ and terms $\\lambda x^a. f(x) : a\\to b$, $\\lambda x^a. g(x) : a\\to c$ a term $\\lambda x^{a\\times b}.\\langle f(\\pi_1(x)),g(\\pi_2(x))\\rangle $.\n  \\item Properties 2. and 3. in proposition \\ref{prop:CartCategory2} comes directly from $\\eta_x$ and $\\beta_{x,i}$ equivalence rules.\\\\\n  \\end{itemize}\n  To provide the exponential type (and thus have a conjunction calculus):\n  \\begin{itemize}\n  \\item The exponential object $a^b$ comes from the type $b\\to a$.\n  \\item Given $h = \\lambda x^{a\\times b}. f(x): a\\times b \\to c$  we define $h^* = \\lambda x^a. \\lambda y^b. f(\\langle x,y\\rangle)$.\n  \\item There is an arrow $\\varepsilon^{a,b} = \\lambda y^{a\\to b \\times a}. (\\pi_1(y))(\\pi_2(y))$.\n  \\item Properties in proposition \\ref{def2:CCC} comes from extending the expresion by $\\beta$-equivalence and then simplifying with $\\eta$-equivalence.\n  \\end{itemize}\n\\end{proof}\n\n\\begin{proposition}\n  If $L$ has a natural numbers system, then $\\CC (L)$ has a natural number system.\n\\end{proposition}\n\\begin{proof}\n  Repeat the process of proposition \\ref{natural-numbers} in opposite direction.\n\\end{proof}\nNow we repeat the process as with $\\LL$ and define a functor $\\CC: \\LC \\to CCart$.\n\\begin{definition}\n  Let $L\\in Ob(\\LC)$, let $\\CC (L)$ be the generated closed Cartesian category of $L$ and let $F:L\\to L'\\in \\LC$.  We define the functor $\\CC (F)$:\n  \\begin{itemize}\n  \\item $\\CC (F) (a) = F(a)$ for every $a\\in Ob(C)$.\n  \\item $\\CC (F) (\\lambda x^a. b(x) :a \\to a') = \\CC (L') (\\lambda x^{F(a)}. F(b(x)))$.\n  \\end{itemize}\n\\end{definition}\n\\begin{remark}\n  Preservation of structures of closed cartesian structures derives directly from preservation of structures of $\\lambda$-calculus of $F$.\n\\end{remark}\n\nWe finally explain how to add an indeterminate to $\\CC(L)$, and how to characterize this construction.\n\n\\begin{definition}\n  Let $L$ be a simply typed $\\lambda$-calculus and let $x : a$ be a variable in $L$. We can generate the language $L(x)$ by adding the \\emph{parameter} $x$ that has the same types as $L$, and the same terms except that $x$ is no longer a variable. That is, now closed terms are terms that does not have any free variable other than $x$.\n\\end{definition}\n\n\n\n\\begin{proposition}\n  $\\CC(L)[x] \\cong \\CC(L(x)).$\n\\end{proposition}\n\\begin{proof}\n  We can define an equivalence between categories. Let us show that $\\CC(L(x))$ has the same property as $\\CC(L)[x]$, and thus there only exists two functors $F:\\CC(L(x))\\to \\CC(L)[x]$  and $G:\\CC(L)[x] \\to\\CC(L(x))$ that maps $x\\to x$ and thus they are inverses of each other.\n  \\[\n  \\begin{tikzcd}\n    \\CC(L)\\arrow[hookrightarrow]{r}{H} \\arrow[rd, \"F\", swap]      & \\CC(L(x)) \\arrow[d, \"F'\", dashed]& x:a_0\\to a\\arrow[d,\"f'\",dashed]\\\\\n    &B& z:F(a_0)\\to F(a) \n  \\end{tikzcd}\n\\]\nWe define $F'(a) = F(a)$ for every $b\\in Ob(\\CC(L))=Ob(\\CC(L(x)))$. Then, for every morphism $f \\in \\CC(L(x))$ has the form $f = \\lambda y^b. \\varphi(y^b, x)$ for some variable $y$ of type $b$ and some term with $y,x$ as free variables. It is easy to check that, $$\\varphi(y, x) = [\\lambda x. \\varphi(y,x ) ] x =^{1.} \\psi(y)x,$$ under $\\beta$-equivalence, where in 1. we define $\\psi (y)= \\lambda x. \\varphi(y,x)$. Finally, using that $\\lambda y^b. \\psi(y^b) \\in Ar(\\CC(L))$, we define $F'(f):= F(\\lambda y^b. \\psi(y^b)) z$.\n\\end{proof}\n\\subsection{Equivalence}\nTo finish this chapter, we prove that these two functors makes an adjoint equivalence. We adapted the proof from \\cite[Theorem 11.3]{lambek1988introduction}, using a more clear categorical language. \n\n\n\\begin{theorem}[Lambek Theorem]The categories $\\LC$ and $CCart$ are equivalent. \\end{theorem}\n\\begin{proof}\n  We will prove that $\\CC \\LL \\cong 1_{CCart_N}$ and  $ \\LL\\CC \\cong 1_{\\Lambda}$, to prove that $\\CC$ and $\\LL$ form an adjoint equivalence.\n\n  \\begin{enumerate}\n  \\item[\\fbox{$\\CC \\LL \\cong 1_{\\mathcal A}$}] To prove this, we have to define the counit $\\varepsilon$. Given a closed Cartesian category $\\mathcal A$ we define a functor  $\\varepsilon(\\mathcal A)$ such that\n    \\begin{itemize}\n    \\item $\\varepsilon(\\mathcal A)    (a) = a$ for every $a\\in Ob(\\mathcal A)$.\n    \\item An arrow in $f:a\\to b \\in \\CC \\LL(\\mathcal A)$ comes from a term of the form $\\lambda x^a. b(x^a)$ where $b(x^a)$ is a term in $\\LL (\\mathcal A)$ with the only free variable being $x^a$. Thus, f comes from a term $f$ has the form $\\lambda x^a. \\varphi(x^a)$ for some $\\varphi(x^a): 1 \\to b \\in \\mathcal A [x^a]$. Then, we define $\\varepsilon(\\mathcal A)(f) = \\varepsilon(\\mathcal A)(\\lambda x^a.\\varphi(x^a))$ as the unique arrow $g$ in $\\mathcal{A}$ such that $gx^a = \\varphi(x^a) \\in \\mathcal A[x^a]$ by functional completeness.\n    \\end{itemize}\n    It is easy to check that this is a closed Cartesian functor.  By the uniqueness of $g$ we infers that $$\\hhom_{\\CC\\LL(\\mathcal A)} (b,c)\\cong \\hhom_{\\mathcal A} (b,c).$$\n    We still have to check that $\\varepsilon (\\mathcal A)$ is a natural transformation, that is, or every to categories $B,C$ and  for every functor $F: C\\to B\\in CCart$ we have that\n    \\[\n      \\begin{tikzpicture}\n        \\node {\\begin{tikzcd}[column sep=20mm]\n            \\CC\\LL(B)\\ar[r,\"\\varepsilon(B)\"]\\ar[d,\"\\CC\\LL(F)\"] & B\\ar[d,\"F\"]\\\\\n            \\CC\\LL(C)\\ar[r,\"\\varepsilon(C)\"] & C.\n          \\end{tikzcd}};\n      \\end{tikzpicture}\n    \\]\n\n    Therefore, we have to check that $\\varepsilon(C)\\circ \\CC\\LL(F) = F \\circ \\varepsilon(B)$. This is trivially checked on objects. On arrows, we have to check that, for every $f = \\lambda x^a.\\varphi(x^a) \\in \\CC\\LL(F) $ we have that $\\varepsilon(C)\\circ \\CC\\LL(F) (f)= F \\circ \\varepsilon(B)(f)$.\n\n    \\begin{itemize}\n    \\item  $F \\circ \\varepsilon(B)(f) = F(g)$ where $g$ is the only function  such that$$gx^a = \\varphi(x^a) \\in \\mathcal B[x^a].$$\n    \\item $\\CC\\LL(F) = \\lambda x^{F(a)}.F_{x^a\\to F(x^a)} \\left ( \\varphi(x^a)\\right )$. Then we have that $\\varepsilon(C)\\circ \\CC\\LL(F) = h$ where $h$ is the only function such that $$h\\circ F(x^a) = F_{x^a\\to (x^{F(a)})}\\left ( \\varphi(x^a)\\right ).$$\n    \\end{itemize}\n    We finish by considering that $F(g)\\circ F(x^a) = F_{x^a\\to (x^{F(a)})}(g \\circ x^a) = F_{x^a\\to (x^{F(a)})}(\\varphi(x^a)) $, and therefore $\\varepsilon$ is natural.\\\\\n\n  \\item[\\fbox{$ 1_{\\mathcal A}\\cong \\LL \\CC $}] We start by studying the language $\\LL\\CC(L)$, given given a $\\lambda$-calculus $L$. Is easy to check that the types in both calculi are the same.\\\\\n\n    Remember that arrows $f:a\\to b$ in $\\CC(L)$ are closed terms $\\lambda x^a.f(x)$ of type $a\\to b$. On the other hand, every term $M$ of type $A$ in $\\LL\\CC(L)$ has the form $\\varphi(x_1,...,x_n): 1 \\to A$, where $\\varphi(x^{t_1},...,x^{t_n})$ is an arrow in $\\CC(L)$ dependent on some indeterminates. Thus $M =\\lambda z^1.m(x_1,...,x_n)$\\footnote{Here we are identifying $\\CC(L)[x_1,...,x_n]$ with $\\CC(L(x_1,...,x_n))$}, where $z^1$ is bounded variable of type of type 1.\\\\\n\n\n    We define the unit $\\eta$ of the adjoint equivalence similarly:\n    \\begin{itemize}\n    \\item For every $L\\in \\LC$ and every type $t$ of $L$ we have that $\\eta(L)(t) = t$.\n    \\item For every term $\\lambda z^1.\\varphi (x_1^{t_1},...,x_n^{t_n})$, were every $x_i^{t_i}$ represents a free variable, to $\\lambda z^1. \\varphi (x_1^{t_1},...,x_n^{t_n}).$\n    \\end{itemize}\n\n\n    It is easy to check that $\\eta(L)$ is a $\\lambda$-morphism. To check that it is an isomorphism on-home sets we can construct the inverse arrow $\\nu(L)$ given by:\n\n    \\begin{itemize}\n    \\item  $\\nu(L)(t) = t$ for every type $t \\in \\LL\\CC(L).$\n    \\item  Let $\\lambda z^1.\\varphi(x_1,...,x_n)$ be a term in $\\LL\\CC(L)$ with $x_1,...,x_n$ as free variables. We define $\\nu(L)(f)= f^* = \\varphi(x_1,...,x_n)$.  \n    \\end{itemize}\n\n    Naturality is checked as in the first part of the proof,expanding each equality term.\n  \\end{enumerate}\n\\end{proof}\n\n\n% \\subsubsection{Deduction Theorem}\n% We proceed with the tating that an arrow $f:\\top \\to A$ does exists in our deduction system. It can be deduced in both positive (without $\\lor$ and $\\bot$) an intuitionistic calculus that is $A \\land B\\vdash C$ then $A \\vdash C\\to B$. This theorem is more interesting to state in the new optics of deduction systems:\n% \\begin{theorem}[Proposition 2.1, \\cite{lambek1988introduction}]\n%   In a positive  calculus, if assuming the existence of an arrow $f:\\top \\to A$ implies the existence of an arrow $g: B\\to C$, then there exists an arrow $h: A\\land B\\to C$ that does not depend on $f$.\n% \\end{theorem}\n\n% \\begin{sproof}\n%   In a similar fashion of the Church-Rosser Theorem, it is solved by induction in the last rule used in the deduction.\n% \\end{sproof}\n\n\n% As we have seen, a category is a deductive system with added structure.\n\n\n", "meta": {"hexsha": "b8ab85695744a6d97bdad0938d1802cb085039a5", "size": 46536, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/Chapters/Chapter4.tex", "max_stars_repo_name": "pedrobn23/Master-thesis", "max_stars_repo_head_hexsha": "372fad59dfe8b96269d37d7a67767d633daef673", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-06-02T13:51:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-20T16:41:28.000Z", "max_issues_repo_path": "thesis/Chapters/Chapter4.tex", "max_issues_repo_name": "pedrobn23/Master-thesis", "max_issues_repo_head_hexsha": "372fad59dfe8b96269d37d7a67767d633daef673", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis/Chapters/Chapter4.tex", "max_forks_repo_name": "pedrobn23/Master-thesis", "max_forks_repo_head_hexsha": "372fad59dfe8b96269d37d7a67767d633daef673", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 66.7661406026, "max_line_length": 639, "alphanum_fraction": 0.6961492178, "num_tokens": 14226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593171945416, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.325807873004633}}
{"text": "\\chapter{Particles and Waves}\\label{c2}\nA particle is a material body whose dimensions are insignificant in comparison\nwith the typical dimensions of its motion. A pebble can be considered to be a\nparticle when one considers its projectile motion but not so when one considers\nits rotation. At a more extreme level, the earth is treated like a particle when\none studies it as a part of solar system but not when we study ocean currents.\nA wave, on the other hand, is a periodic disturbance. In the case of material\nwaves the disturbance is felt in properties of the materials. For example, the\npassage of a sound waves leads to periodic compressions and rarefactions in the\nmaterial. They are detected as changes in the pressure in the case of fluids and\ninternal stresses in the case of solids. Electromagnetic waves do not need \nmaterials for their propagation and their passage is manifested in the periodic\nvariations in electric and magnetic field intensities at a point. Although this\ndistinction between particles and waves seems quite natural it is not so when \none observes nature beyond the human senses. Newton considered light to be\nparticulate and it took more than two centuries to suspect that it is probably\na wave. The interference experiments of Young could be explained only by \ntreating light as a wave. Maxwell predicted the existence of electromagnetic\nwaves and Hertz confirmed their existence. Maxwell also derived the speed of\nelectromagnetic waves and it was the same as the speed of light. As a result,\nlight was suspected to be an electromagnetic wave and was indeed shown to be so.\nHowever, at the turn of the century other experiments were conducted whose \noutcome could not be explained by assuming that light is a wave. We will \ndescribe a few experiments in this chapter that demonstrate that what were\nthought to be waves also behave like particles and \\emph{vice versa}.\n\n\\section{Black body radiation}\\label{c2s1}\nMaterial bodies absorb and emit electromagnetic radiation. When they are in\nthermal equilibrium the net absorption of radiation matches the net emission.\nMost bodies do not absorb all radiation. They reflect or transmit it. Further,\ntheir absorption depends on the angle of incidence. A black body is the one \nthat absorbs all radiation irrespective of its wavelength and angle of \nincidence. If a blackbody is at thermal equilibrium then it should emit the\nenergy it absorbs. The emitted energy is called \\emph{black body radiation}.\nAn approximately black body is a large cavity enclosed in an opaque material \nand with a small hole for radiation to get in. It is only an approximation \nbecause waves with wavelength greater than the hole's diameter will be \npartially reflected. Further, a finite size cavity cannot hold radiation of all\nwavelengths.\n\nSince a black body absorbs radiation of all wavelengths it also emits radiation\nof all wavelengths. If $U_\\lambda$ is the amount of energy in the form of \nradiation of wavelength $\\lambda$ and if $V$ is it volume then \n\\begin{equation}\\label{c2s1e1}\nu_\\lambda = \\frac{U_\\lambda}{V}\n\\end{equation}\nis called the `spectral energy density'. The black body radiation experiment\nconsists in plotting $u_\\lambda$ against $\\lambda$. The results of the \nexperiment are shown in figure \\ref{c2f1}. \n\\begin{figure}\n\\begin{center}\n\\includegraphics[scale=0.20]{bb}\n\\caption{Blackbody spectrum credit: Encyclopedia Britannica,\\\\\nhttps://www.britannica.com/science/blackbody-radiation\\#/media/1/68456/1374}\n\\label{c2f1}\n\\end{center}\n\\end{figure}\n\nThe plot shows that as temperature\nrises the dominant wavelength decreases. It agrees with the observation that\nhot bodies successively appear redish to bluish to white as their temperature\nincreases. Lord Rayleigh and Sir James Jeans first tried to understand the\nblack body spectrum assuming that radiation is in the form of electromagnetic\nwaves. Radiation is trapped inside a black body in the form of standing waves.\nIf we the black body is in the form a cube of length $L$ then radiation of \nwavelength $\\lambda$ will stay as a standing wave only if an integral number of\nhalf wavelengths are accommodated in the extent $L$. If $n_x, n_y, n_z$ are the\nnumber of half-wavelengths along the $x, y, z$ axes then\n\\begin{eqnarray}\nn_x &=& \\frac{L}{\\lambda/2} = \\frac{2L}{\\lambda} \\\\\nn_y &=& \\frac{2L}{\\lambda} \\\\\nn_z &=& \\frac{2L}{\\lambda}\n\\end{eqnarray}\nFor a standing wave to form in an arbitrary direction we must have\n\\begin{equation}\\label{c2s1e5}\nn^2 = n_x^2 + n_y^2 + n_z^2 = \\left(\\frac{2L}{\\lambda}\\right)^2.\n\\end{equation}\nIn this equation we no longer require $n_x, n_y, n_z$ to be integers.\nThe number of waves with wavelengths between $\\lambda$ and $\\lambda + d\\lambda$\nis the number of points with positive coordinates $n_x, n_y, n_z$ in the region\nbetween the first octant of the spheres with radii $n$ and $n + dn$. This number\nis proportional to the volume of the region,\n\\[\n\\frac{1}{8} \\times 4\\pi n^2dn.\n\\]\nSince there are two polarisations for each mode, the number of standing waves is\n\\begin{equation}\\label{c2s1e6}\nG(n)dn = \\pi n^2 dn.\n\\end{equation}\nFrom equation \\eqref{c2s1e5} we have\n\\begin{equation}\\label{c2s1e7}\nn = \\frac{2L}{\\lambda} = \\frac{2L}{c}\\nu\n\\end{equation}\nso that equation \\eqref{c2s1e6} becomes\n\\begin{equation}\\label{c2s1e8}\nG(\\nu)d\\nu = \\pi \\cdot \\frac{8L^3}{c^3}\\nu^2d\\nu.\n\\end{equation}\nIf $g(\\nu)$ is the number of waves per unit volume, also called the density of\n`states', then\n\\begin{equation}\\label{c2s1e9}\ng(\\nu)d\\nu = \\frac{8\\pi}{c^3}\\nu^2 d\\nu.\n\\end{equation}\nFinally, in order to get the energy density, Rayleigh and Jeans used the \nclassical equipartition theorem that allocates an energy of $kT/2$ to each\ndegree of freedom. In the case of a single standing wave, there are two degrees\nof freedom so that the energy of each mode is\n\\begin{equation}\\label{c2s1e10}\nU = kT,\n\\end{equation}\nwhere $k = 1.38 \\times 10^{-23}$ JK${}^{-1}$ is the Boltzmann constant and $T$\nis the absolute temperature. The energy density is, therefore,\n\\begin{equation}\\label{c2s1e11}\nu(\\nu)d\\nu = \\frac{8\\pi kT}{c^3}\\nu^2 d\\nu.\n\\end{equation}\nOne can as well express the energy density $u$ as a function of wavelength and\nwrite\n\\begin{equation}\\label{c2s1e12}\nu(\\lambda)d\\lambda = \\frac{8\\pi kT}{\\lambda^4}d\\lambda,\n\\end{equation}\nwhere we have used the fact that $u(\\nu)d\\nu = -u(\\lambda)d\\lambda$ because of\nthe inverse relationship between $\\nu$ and $\\lambda$.\nThe experimentally observed energy density spectrum of a black body does not\nfollow these equations. In particular, when $\\lambda \\rightarrow 0$, or \nequivalently, $\\nu \\rightarrow \\infty$, $u$ blows up. This feature of the \nfunction $u$ defined in \\eqref{c2s1e10} and \\eqref{c2s1e11} is called the\n`ultraviolet catastrophe' and it was one of the first evidences to indicate \nthat certain experiments cannot be explained by classical physics.\n\nMax Planck's correction to this formula lay in replacing the energy given by\nequation \\eqref{c2s1e10} with\n\\begin{equation}\\label{c2s1e13}\nU = \\frac{h\\nu}{\\exp(\\frac{h\\nu}{kT}) - 1}\n\\end{equation}\nwhere $h = 6.626 \\times 10^{-34}$ Js is a universal constant, now called the\nPlanck's constant. The expression for energy density becomes\n\\begin{equation}\\label{c2s1e14}\nu(\\nu)d\\nu = \\frac{8\\pi h\\nu^3}{c^3}\\frac{d\\nu}{\\exp(\\frac{h\\nu}{kT}) - 1}.\n\\end{equation}\nThis is Planck's formula for black body radiation spectrum. \n\n\\subsection{Planck's expression for $U$}\nThere are many ways to derive Planck's expression in equation \\eqref{c2s1e13}\nfor the energy of radiation. We will follow the one used originally by Planck\n\\cite{planck1901law}. It assumes\n\\begin{enumerate}\n\\item The relation between entropy $S$ and internal energy $U$\n\\begin{equation}\\label{c2s1e15}\n\\left(\\frac{\\partial S}{\\partial U}\\right)_{V, N} = \\frac{1}{T}.\n\\end{equation}\nHere $T$ us the (absolute) temperature and $N$ is the number of particles.\n\\item The relation between entropy and the number of states in which a system\ncan be. If $\\Omega$ is the number of states then\n\\begin{equation}\\label{c2s1e16}\nS = k\\log\\Omega\n\\end{equation}\nwhere $k$ is Boltzmann constant.\n\\item Electromagnetic energy is transferred in the units of $h\\nu$, where $\\nu$\nis the frequency of the radiation and $h$ is another universal constant, now \nnamed after Planck. \n\\end{enumerate}\nOf these assumptions, the first one is a result in thermodynamics, known since \nthe 1850s. The second one was proposed by Ludwig Boltzmann in the 1870s when he\nlaid the foundations of statistical mechanics while the last one was Planck's \ncontribution for which he was to receive a Nobel prize in Physics in 1918.\n\nLet the black body cavity have an energy $U_0$ at the frequency $\\nu$. If there \nare $N$ modes of radiation, we want to find out the number of ways in which we \ncan  distribute the energy $U$ among them. The third assumption listed above \ntells  that the energy $U$ is available as $P=U_0/(h\\nu)$ packets, called quanta. \nTherefore, the problem of distribution of energy $U_0$ among the radiation modes\nis the same as counting the number of ways in which $P$ quanta can be \ndistributed among $N$ modes. This is an easy combinatorial problem whose \nsolution is\n\\begin{equation}\\label{c2s1e17}\n\\Omega = \\frac{(P + N - 1)!}{P!(N - 1)!}.\n\\end{equation}\nUsually, the number $N$ is so large that $(N - 1)! \\approx N!$ so that we can\nas well write \\eqref{c2s1e17} as\n\\begin{equation}\\label{c2e1e18}\n\\Omega = \\frac{(P + N)!}{P!N!}.\n\\end{equation}\nso that\n\\[\n\\log\\Omega = \\log[(P + N)!] - \\log P! - \\log N!.\n\\]\nWhen $n$ is large, we can approximate $\\log n! \\approx n\\log n$ (this is called\nStirling's approximation. It is quite accurate even for $n = 10$) to get\n\\[\n\\log\\Omega = (P + N)\\log(P + N) - P\\log P - N\\log N\n\\]\nso that the entropy of the electromagnetic radiation is\n\\begin{eqnarray*}\nS &=& k\\log\\Omega \\\\\n  &=& kN\\left\\{\\left(1 + \\frac{P}{N}\\right)\\log(P + N) - \\frac{P}{N}\n      \\log P - \\log N\\right\\} \\\\\n &=& kN\\left\\{\\left(1 + \\frac{P}{N}\\right)\\log(P+N) - \\frac{P}{N}\n     \\left(\\log\\frac{P}{N} + \\log N\\right) - \\log N\\right\\} \\\\\n &=& kN\\left\\{\\left(1 + \\frac{P}{N}\\right)\\left(\\log(P+N)-\\log N\\right)\n     - \\frac{P}{N}\\log\\frac{P}{N}\\right\\} \\\\\n &=& kN\\left\\{\\left(1 + \\frac{P}{N}\\right)\\log\\left(1+\\frac{P}{N}\\right)\n     - \\frac{P}{N}\\log\\frac{P}{N}\\right\\}\n\\end{eqnarray*}\nSince $P$ was defined as $U_0/(h\\nu)$, we can write\n\\[\n\\frac{U_0}{Nh\\nu} = \\frac{U}{h\\nu}\n\\]\nwhere\n\\begin{equation}\\label{c2s1e19}\nU = \\frac{U_0}{N}\n\\end{equation}\nis the average energy per mode. We now have\n\\begin{equation}\\label{c2s1e20}\nS = kN\\left\\{\\left(1 + \\frac{U}{h\\nu}\\right)\\log\\left(1+\\frac{U}{h\\nu}\\right)\n     - \\frac{U}{h\\nu}\\log\\frac{U}{h\\nu}\\right\\}.\n\\end{equation}     \nFrom equations \\eqref{c2s1e15} and \\eqref{c2s1e19} one can readily show that\n\\begin{equation}\\label{c2s1e21}\n\\frac{1}{T} = \\frac{k}{h\\nu}\\left(1 + \\frac{h\\nu}{U}\\right).\n\\end{equation}\nThis equation can be rearranged to get\n\\begin{equation}\\label{c2s1e22}\nU = \\frac{h\\nu}{\\exp\\left(\\frac{h\\nu}{kT}\\right) - 1}\n\\end{equation}\nwhich is identical with \\eqref{c2s1e13}.\n\n\\subsection{Additional notes on Planck's derivation}\nPlanck deduced the relation $E = h\\nu$ first on the basis of thermodynamic\narguments (section 2 of \\cite{planck1901law}). Later on (sixth lecture in \n\\cite{planck2012eight}) he gave an explanation using the mathematical \nproperties of electromagnetic radiation. Chang \\cite{chang2017physical} gives \nan account of Planck's theory in modern terms.\n\nEntropy is usually introduced as a quantity measuring the disorder in a system.\nThe molecules of a vapour have more freedom of movement than the molecules of a\nliquid. As a result we say the vapour has more entropy than a liquid. What could\nentropy mean in the case of radiation? Radiation is characterised by frequency \n(or wavelength), phase and amplitude. The entropy of radiation consists in \nrandom fluctuations of phase and amplitude.\n\nAlthough Planck introduced the idea of a quantum of energy he did not consider it\nas seriously as others like Einstein, Ehrenfest and Lorentz (preface of \n\\cite{planck2012eight}). In the remaining sections we will see how the idea \nturned out to have a profound and far-reaching impact on physics.\n\n\\subsection{Problem set 1}\n\\begin{enumerate}\n\\item Physics is an experimental science. We should supplement the theoretical\ndevelopment of black body radiation spectrum of \\eqref{c2s1e14} with an \nunderstanding of how it is measured. Refer to \n\\url{https://physicsopenlab.org/2015/12/04/black-body-emission/} for one way to\nmeasure the spectrum.\n\\item When the voltage drops an incandescent bulb gives a reddish glow. When the\nvoltage reaches its normal level the bulb glows bright. Can you explain the \nchange in appearance based on your understanding of \\eqref{c2s1e14}?\n\\item It is safer to use a touchless thermometer when a large number of people\nhave to be examined. Can you design a touchless thermometer using \n\\eqref{c2s1e14}?\n\\item Consider the function\n\\begin{equation}\\label{c2e1e23}\nB(\\nu, T) = \\frac{2h\\nu^3}{c^2}\\frac{1}{\\exp\\left(\\frac{h\\nu}{kT}\\right) - 1}.\n\\end{equation}\nShow that it reaches an extremum at a frequency $\\nu_0$ such that\n\\begin{equation}\\label{c2e1e24}\n3 + \\left(\\frac{h\\nu_0}{kT} - 3\\right)\\exp\\left(\\frac{h\\nu_0}{kT}\\right) = 0.\n\\end{equation}\nIf you measure the radiation spectrum of a body using the procedure outlined\nin the first problem and read the frequency $\\nu_0$ at which the spectral energy \ndensity peaks then you can use equation \\eqref{c2e1e24} to determine the \ntemperature.\n\\item If \n\\begin{equation}\\label{c2e1e25}\nx = \\frac{h\\nu_0}{kT}\n\\end{equation}\nthen equation \\eqref{c2e1e24} can be written as $3 + (x - 3)e^x = 0$. You can\nsolve this equation using Newton's method to get $x \\approx 2.821440$. Thus,\nthe relation between temperature of the black body and its peak frequency is\n\\begin{equation}\\label{c2s1e26}\n\\frac{h\\nu_0}{kT} \\approx 2.821440.\n\\end{equation}\nUsing equation \\eqref{c2s1e26} find the peak frequency when you measure the\nradiation spectrum of\n\\begin{enumerate}\n\\item Sun whose surface temperature is approximately $6000$ K?\n\\item human body with temperature of $310$K? (Do you now see the usefulness\nof infrared cameras?)\n\\end{enumerate}\nOn the other hand the peak frequency of the outer space is around $160$ GHz.\nWhat is the space's temperature? (The ambient radiation in the outer space \nis called the cosmic microwave background. Can you relate it to the relativistic\nDoppler effect you studied in the previous chapter?)\n\\end{enumerate}\n\n\\section{Photoelectric effect and X-ray generation}\\label{c2s2}\nWhen light of suitable frequency is shone on a clean metal surface, the metal\nemits electrons. This is called the photoelectric effect. Experiments reported\nthat\n\\begin{itemize}\n\\item The electrons are emitted only if the light exceeds a certain frequency\n, called the threshold frequency, which is characteristic of the metal.\n\\item As long as the light exceeds the threshold frequency the energy of the \nemitted electrons increases with frequency.\n\\item The number of electrons emitted is proportional to the intensity of light\nif its frequency exceeds the threshold. If its frequency is below the threshold\nthe increasing intensity of light does not result in emission of electrons.\n\\item There is no lag between turning on the light and the emission of electrons.\n\\end{itemize}\n\nNone of these observations could be satisfactorily explained if one assumes that\nlight is a classical electromagnetic wave. A classical wave can transfer energy\nto an electron in a continuous manner so that eventually the electron has enough\nenergy to free itself from the metal and escape.\n\nEinstein used Planck's idea of an energy quantum to explain the experimental \nfacts mentioned above (see section 8 of \\cite{einstein1905heuristic}). He \nproposed that an electron in a metal has to overcome a certain energy barrier,\ncalled the `work function' $\\phi$ of the metal, before it can escape it. The\nminimum frequency that the light must have for it to eject an electron is\n\\begin{equation}\\label{c2s2e1}\nh\\nu_0 = \\phi.\n\\end{equation}\nIf the light has a frequency $\\nu > \\nu_0$ then the energy $h\\nu - \\phi =\nh(\\nu - \\nu_0)$ beyond the metal's work function is transferred to the\nelectron as its kinetic energy.\n\n\\subsection{Problem set 2}\n\\begin{enumerate}\n\\item The (first) ionization energy of an atom is the energy needed to remove\nan electron from its outermost shell. Caesium atom has an ionization energy of\n$3.9$ eV. However the work function of Caesium metal is only $1.9$ eV. Why are\nthe two different? Why is the work function lower than the ionization energy?\n\\item Visible light's frequency ranges from $400$ to $800$ THz. If you want \nto build a device to detect visible light using photoelectric effect, which \nmetals would you use? You can consult the Wikipedia for values of work function\n(\\url{https://en.wikipedia.org/wiki/Work_function#Work_functions_of_elements})\nof common metals. Which metals can you use to detect red light? Which ones will\nsuffice if you are interested only in blue and violet?\n\\item You have probably studied thermionic emission in the context of vacuum\ntube diode. In thermionic emission electrons are ejected from a metal surface\nby heating the metal. Will the thermionic work function be different from the\nphotoelectric work function?\n\\end{enumerate}\n\nIn photoelectric effect, light transfers its energy to an electron giving it\nenough energy to escape from a metal. The inverse process in which a fast moving\nelectron is stopped by a solid releasing its energy as light is also possible.\nA sharp deceleration of an electron gives rise to `bremsstrahlung', the German\nword for radiation as a result of stopping (applying brakes) a charged particle.\nFigure \\ref{c2f1} shows the X-ray spectrum of Rhodium metal downloaded from\nWikipedia (\\url{https://commons.wikimedia.org/wiki/File:TubeSpectrum.jpg#/media/\nFile:TubeSpectrum.jpg}).The $x$-axis has the wavelength of X-rays in picometre\n($1$ pm = $10^{-12}$ m) while the $y$-axis has a quantity proportional to the\nintensity of the radiation. It is observed that the spectrum is largely smooth\nexcept for two sharp peaks and that it abruptly drops at a certain minimum\nwavelength. The smooth part of the spectrum is due to bremsstrahlung while the\nsharp peaks are because of transition of electrons in Rhodium atoms from higher \nenergy levels to lower ones. We will understand these transitions better when we\nstudy atomic structure in greater details in the chapters to follow.\n\\begin{figure}\n\\includegraphics[scale=0.5]{Tubespectrum}\n\\caption{X-ray spectrum of Rh downloaded from Wikipedia}\\label{c2f2}\n\\end{figure}\n\n\\subsection{Problem set 3}\n\\begin{enumerate}\n\\item Figure \\ref{c2f2} shows that there are no X-rays detected with a \nwavelength lesser than a certain cut-off. What does the cut-off depend on? Is \nit a characteristic of the metal or the fast moving electrons?\n\\item The cut-off wavelength is approximately $20$ pm. Can you estimate the \nenergy of the fast moving electrons?\n\\item How will the cut-off wavelength change when you use faster electrons?\n\\item When an electron is accelerated from rest by a potential difference \n$V$ then it acquires an energy $eV$, where $e$ is the charge on the electron.\nSuppose that this electron loses all its energy when it hits the metal in the\nform of light of frequency $\\nu_0$. Show that\n\\begin{equation}\\label{c2s2e2}\n\\nu_0 = \\frac{eV}{h}.\n\\end{equation}\nShow that the corresponding wavelength is\n\\begin{equation}\\label{c2s2e3}\n\\lambda_0 = \\frac{hc}{eV}.\n\\end{equation}\nThe quantities $h, c$ and $e$ on the right hand side of \\eqref{c2s2e3} are \nuniversal constants. Use their values in SI units to derive\n\\begin{equation}\\label{c2s2e4}\n\\lambda_0 = \\frac{1.2398 \\times 10^{-6}}{V}.\n\\end{equation}\nEquation \\eqref{c2s2e4} is called Duane-Hunt law. It was derived from empirical\ndata before the theory of X-ray production was understood.\n\nDoes \\eqref{c2s2e4} help you answer the previous two questions better?\n\\end{enumerate}\n\n\\section{Compton effect}\\label{c2s3}\nBlack body radiation spectrum and photoelectric effect can be explained by\nassuming that electromagnetic waves transfer energy in discrete quanta. That\nperhaps makes them strange kind of waves. But there is nothing in those \nexperiments to suggest that they are particles. Waves interfere, particles\ncollide and we can think of light as a stream of particles only when we can\nmake it collide with another particle. Compton's experiment involved the \ninteraction of light with an electron and its results can be explained by\ntreating light as a stream of particles, called photons. The particles have\nand energy \n\\begin{equation}\\label{c2s3e1}\nE = h\\nu,\n\\end{equation}\nand their momentum is given by equation \\eqref{c1s3e10} to be\n\\begin{equation}\\label{c2s3e2}\np = \\frac{E}{c}.\n\\end{equation}\nNote that we still associate the term `frequency' for photons alluding to the\nfact that they behave like particles and waves. Compton's experiment consisted\nof shining light on electrons. If light is considered to be an electromagnetic\nwave then the electron is exposed to an oscillating electric field as a result\nof which it starts oscillating with the same frequency. An oscillating charge\nalso emits radiation so that the radiation observed after interaction with the\nelectron consists of the incident radiation and the emitted radiation. The\nfrequency of both radiations is the same although the scattered radiation is\npolarised. Compton used radiation of a very high frequency in the form of X-rays\nand gamma rays. He observed that the scattered radiation had a lower frequency,\nor a higher wavelength. This observation could not be explained by the classical\ntheory. Compton, therefore, assumed that X-rays can be considered to be a \nstream of particles of energy and momentum given by equations \\eqref{c2s3e1}\nand \\eqref{c2s3e2}. He assumed that an electron at rest has zero momentum but\nit has an energy $E = m_ec^2$, $m_e$ being the mass of the electron. The\ncollision between the X-ray photon and a stationary electron results in the\nphoton getting scattered by an angle $\\theta$ and the electron recoiling at \nan angle $\\phi$ where the angles are measured with respect to the direction\nalong with the photons arrive. If we choose the $x$-axis to be along the\ndirection of the incident photons and if the origin is chosen to be the initial\nposition of the electron then $\\phi$ and $\\theta$ are the angles of the \nfinal momenta of the photon and electron with the positive $x$-axis.\n\nLet us put expressions for initial and final momenta of the electron and the\nphoton. The quantities after the collision are distingushed by a prime and those\nrelated to the electron have a subscript `e'. Thus, the initial energy and \nmomenta are\n\\begin{eqnarray}\nE &=& h\\nu \\label{c2s3e3} \\\\\n\\vec{p} &=& \\frac{h\\nu}{c}\\hat{i} \\label{c2s3e4} \\\\\nE_e &=& m_ec^2 \\label{c2s3e5} \\\\\n\\vec{p}_e &=& 0 \\label{c2s3e6}\n\\end{eqnarray}\nThe corresponding quantities for the photon after the collision are\n\\begin{eqnarray}\nE^\\prime &=& \\frac{h\\nu^\\prime}{c} \\label{c2s3e7} \\\\\n\\pvec{p}^\\prime &=& \\frac{h\\nu^\\prime}{c}\\cos\\phi\\hat{i} + \n                   \\frac{h\\nu^\\prime}{c}\\cos\\phi\\hat{j} \\label{c2s3e8}\n\\end{eqnarray}\nIf $p_e^\\prime$ is the magnitude of the electron's momentum after collision then\n\\begin{equation}\\label{c2s3e9}\n\\pvec{p}_e^\\prime = p_e^\\prime\\cos\\theta\\hat{i} + p_e^\\prime\\sin\\theta\\hat{j}\n\\end{equation}\nand\n\\begin{equation}\\label{c2s3e10}\nE_e^\\prime = \\sqrt{{p_e^\\prime}^2c^2 + m_e^2c^4}.\n\\end{equation}\n\nSince momentum is conserved,\n\\begin{eqnarray}\n\\frac{h\\nu}{c} &=& \\frac{h\\nu^\\prime}{c}\\cos\\phi + p_e^\\prime\\cos\\theta \n                   \\label{c2s3e11} \\\\\n0 &=& \\frac{h\\nu^\\prime}{c}\\sin\\phi - p_e^\\prime\\sin\\theta. \\label{c2s3e12}\n\\end{eqnarray}\nWe can rearrange these as\n\\begin{eqnarray}\np_e^\\prime c\\cos\\theta &=& h(\\nu - \\nu^\\prime\\cos\\phi) \\label{c2s3e13} \\\\\np_e^\\prime c\\sin\\theta &=& h\\nu^\\prime\\sin\\phi. \\label{c2s3e14}\n\\end{eqnarray}\nSquaring and summing these\n\\begin{equation}\\label{c2s3e15}\n{p_e^\\prime}^2c^2 = h^2(\\nu^2 + {\\nu^\\prime}^2 - \\nu\\nu^\\prime\\cos\\phi).\n\\end{equation}\nNow let us consider energy conservation. After the collision, the electron\nis no longer at rest. Let us assume that $T$ is its kinetic energy. It gets\nit from the photon. Therefore,\n\\begin{equation}\\label{c2s3e16}\nT = h\\nu - h\\nu^\\prime.\n\\end{equation}\nThe total energy of the electron after the collision is \n\\begin{equation}\\label{c2s3e17}\nE_e^\\prime =  T + m_ec^2.\n\\end{equation}\nFrom equations \\eqref{c2s3e10} and \\eqref{c2s3e17},\n\\[\nT^2 + 2m_ec^2T + m_e^2c^4 = {p_e^\\prime}^2c^2 + m_e^2c^4\n\\]\nso that\n\\begin{equation}\\label{c2s3e18}\n{p_e^\\prime}^2c^2 = T^2 + 2m_ec^2T.\n\\end{equation}\nSubstituting \\eqref{c2s3e16} in the above equation we get\n\\begin{equation}\\label{c2s3e19}\n{p_e^\\prime}^2c^2 = h^2(\\nu^2 + {\\nu^\\prime}^2 - 2\\nu\\nu^\\prime) + \n                    2m_ec^2h(\\nu - \\nu^\\prime).\n\\end{equation}\nFinally, from equations \\eqref{c2s3e15} and \\eqref{c2s3e19} one get\n\\begin{equation}\\label{c2s3e20}\n\\frac{m_e}{h}\\left(\\frac{c}{\\nu^\\prime} - \\frac{c}{\\nu}\\right) = 1-\\cos\\phi.\n\\end{equation}\nSince $c/\\nu = \\lambda$ and $c/\\nu^\\prime = \\lambda^\\prime$, we can as well\nwrite \\eqref{c2s3e20} as\n\\begin{equation}\\label{c2s3e21}\n\\lambda^\\prime - \\lambda = \\frac{h}{m_ec}(1 - \\cos\\phi).\n\\end{equation}\nThe expression on the right hand side of the above equation is called the\n`Compton shift'. Observe that it depends on $\\phi$ the angle at which one\nobserves the scattered photon.\n\n\\subsection{Problem set 4}\n\\begin{enumerate}\n\\item Mathematically it is clear that the Compton shift depends on the angle\nof observation. Can you explain it solely on physical grounds?\n\\item Compton shift depends only on the angle of observation of the scattered\nphoton. The other terms are universal constants. In particular, the Compton\nshift is independent of characteristics of the incident photon. Why did Compton\nuse X-rays when so many other choices of radiation were available?\n\\end{enumerate}\n\n\\subsection{About photons}\nWe used the term `photon' for the first time in this section. We used it to mean\na `light particle'. However, one should not imagine propagation of light as a\nstream of particles of finite extent. Although it might have been the original\nidea, the modern concept of photon is does not permit such a picture. A \npragmatic choice, at this stage, is just to assume that light can be associated\nwith an energy $E = h\\nu$ and a momentum $p = E/c$ and conceptally one can \ntreat it as if it were a particle. To know more about why the idea of photon is\nsubtle and how physicists sometime get it wrong, refer to Willis Lamb's article\n\\cite{lamb1995anti} or a more extensive set of articles in \n\\cite{roychoudhurioptics}. The same caution applies to the `phonons', the \nacoustic counterpart of photons, which we will study the specific heat of \nsolids.\n\n\\section{de Broglie waves}\\label{c2s4}\nExperimental evidence forced Max Planck, Albert Einstein and Arthur Compton to\npropose and accept that idea that electromagnetic waves show particle-like\nproperties. The proposal was tortuous and the acceptance reluctant. If\nwaves can behave like particle, might particles behave like waves? There was\nno experimental evidence to suspect this possibility in 1924 when the French\nphysicist Louis de Broglie proposed it. It was firmly in the realm of \nspeculation. However within a matter of three years the speculation was put to\nrest by an experiment that demonstrated that electrons do get diffracted. In\nthis section, we will review de Broglie's ideas and describe the experiments\nthat proved them right.\n\nWe learnt in chapter \\ref{c1} that photons of energy $E = h\\nu$ have a momentum\n\\begin{equation}\\label{c2s4e1}\np = \\frac{E}{c} = \\frac{h\\nu}{c} = \\frac{h}{\\lambda}.\n\\end{equation}\nde Broglie proposed that a particle with momentum $p$ has a wavelength\n\\begin{equation}\\label{c2s4e2}\n\\lambda = \\frac{h}{p}.\n\\end{equation}\nLet us understand the profound implications of this mathematically innocuous\nrearrangement of the terms of equation \\eqref{c2s4e1}. We know that the momentum\nof a particle of mass $m$ moving with a velocity $\\vec{v}$ is\n\\begin{equation}\\label{c2s4e3}\n\\vec{p} = \\gamma m\\vec{v},\n\\end{equation}\nwhere \n\\begin{eqnarray*}\n\\gamma &=& \\frac{1}{\\sqrt{1 - \\beta^2}} \\\\\n\\vec{\\beta} &=& \\frac{\\vec{v}}{c} \n\\end{eqnarray*}\nTherefore, the wavelength of the particle is\n\\begin{equation}\\label{c2s4e4}\n\\lambda = \\frac{h}{\\gamma mv}.\n\\end{equation}\nThe energy of a body is $E = \\gamma mc^2$. Therefore, its frequency is\n\\begin{equation}\\label{c2s4e5}\n\\nu = \\frac{E}{h} = \\frac{\\gamma mc^2}{h}\n\\end{equation}\nand the velocity of its wave is\n\\begin{equation}\\label{c2s4e6}\nv_p = \\nu\\lambda = \\frac{\\gamma mc^2}{h}\\frac{h}{\\gamma mv} = \\frac{c^2}{v}.\n\\end{equation}\nWe learnt in chapter \\ref{c1} that material bodies always travel slower than\nlight. That is $v < c$. As a result, from equation \\eqref{c2s4e6}, it is\nevident that\n\\begin{equation}\\label{c2s4e7}\nv_p > c.\n\\end{equation}\nThe theory of relativity proposed that no information can travel faster than\nlight. So what kind of information is contained in a wave whose speed is given\nby \\eqref{c2s4e6}? To understand that, we need a brief interlude to refresh\nour ideas about waves.\n\n\\subsection{The equation of a wave}\nAny wave can be expressed with the equation\n\\begin{equation}\\label{c2s4e8}\ny = A\\cos\\left(2\\pi\\left(\\frac{x}{\\lambda} - \\nu t\\right)\\right).\n\\end{equation}\nThe wave travels along the positive $x$ axis causing a displacement along the\n$y$ axis. Its crest, or trough, or any other point with a fixed phase, travels\nat a speed $v_p = \\nu\\lambda$. The subscript $p$ emphasizes that this is the\nvelocity of a point of a fixed phase. It is called the phase velocity. We saw\nin equation \\eqref{c2s4e7} that the phase velocity of de Broglie waves is\ngreater than the speed of light. Is there something else associated with a \nwave whose velocity matches the velocity of the particle?\n\nTo do that, we introduce the angular frequency\n\\begin{equation}\\label{c2s4e9}\n\\omega = 2\\pi\\nu\n\\end{equation}\nand the wave number\n\\begin{equation}\\label{c2s4e10}\nk = \\frac{2\\pi}{\\lambda}\n\\end{equation}\nto rewrite the equation of wave motion as\n\\begin{equation}\\label{c2s4e11} \ny = A\\cos(kx - \\omega t)\n\\end{equation}\nso that the phase velocity can also be written as\n\\begin{equation}\\label{c2s4e12}\nv_p = \\frac{\\omega}{k}.\n\\end{equation}\n\nNow consider a superposition of two waves\n\\begin{eqnarray}\ny_1 &=& A\\cos(kx - \\omega t) \\label{c2s4e13} \\\\ \ny_2 &=& A\\cos((k + \\delta k)x - (\\omega + \\delta\\omega)t). \\label{c2s4e14}\n\\end{eqnarray}\nThe net displacement of any point on the $x$ axis is\n\\begin{equation}\\label{c2s4e15}\ny = y_1 + y_2 = A\\left[\\cos(kx-\\omega t) + \n  \\cos((k + \\delta k)x - (\\omega + \\delta\\omega)t)\\right].\n\\end{equation}\nUsing standard trignometric identities, one can write the above equation as\n\\begin{equation}\\label{c2s4e16}\ny = 2A\\cos\\left[\\left(k+\\frac{\\delta k}{2}\\right)x - \\left(\\omega + \n\\frac{\\delta\\omega}{2}\\right)t\\right]\\cos\\left(\\frac{\\delta k}{2}x - \n\\frac{\\delta\\omega}{2} t\\right).\n\\end{equation}\nNow assume that $\\delta k \\ll k$ and $\\delta\\omega \\ll \\omega$ so that $k + \n\\delta k/2 \\approx k$ and $\\omega + \\delta\\omega/2 \\approx \\omega$ and hence\n\\begin{equation}\\label{c2s4e17}\ny = 2A\\cos\\left(\\frac{\\delta k}{2}x - \\frac{\\delta\\omega}{2}t\\right)\n    \\cos(kx - \\omega t)\n\\end{equation}\nThe superposition of the two waves \\eqref{c2s4e13} and \\eqref{c2s4e14} is thus\nanother wave with its amplitude modulated by the first cosine factor in\n\\eqref{c2s4e17}. The velocity of the modulation is\n\\begin{equation}\\label{c2s4e18}\nv_g = \\frac{\\delta\\omega}{\\delta k},\n\\end{equation}\nwhich in the limit $\\delta k \\rightarrow 0, \\delta\\omega \\rightarrow 0$ becomes\n\\begin{equation}\\label{c2s4e19}\nv_g = \\frac{d\\omega}{dk}.\n\\end{equation}\n$v_g$ is called the group velocity of thewave $y$.\n\n\\subsection{Group velocity of de Broglie waves}\nFrom equation \\eqref{c2s4e4}\n\\begin{equation}\\label{c2s4e20}\nk = \\frac{2\\pi}{\\lambda} = \\frac{2\\pi}{h}\\gamma mv\n\\end{equation}\nso that\n\\begin{equation}\\label{c2s4e21}\n\\frac{dk}{dv} = \\frac{2\\pi}{h}\\frac{m}{(1 - \\beta^2)^{3/2}}.\n\\end{equation}\nLikewise, from \\eqref{c2s4e5}\n\\begin{equation}\\label{c2s4e22}\n\\omega = 2\\pi\\nu = \\frac{2\\pi}{h}\\gamma mc^2\n\\end{equation}\nso that\n\\begin{equation}\\label{c2s4e23}\n\\frac{d\\omega}{dv} = \\frac{2\\pi}{h}\\frac{mv}{(1 - \\beta^2)^{3/2}}.\n\\end{equation}\nFrom equations \\eqref{c2s4e23} and \\eqref{c2s4e21} we readily get\n\\begin{equation}\\label{c2s4e24}\nv_g = \\frac{d\\omega}{dk} = \\frac{d\\omega/dv}{dk/dv} = v.\n\\end{equation}\nIt is not the phase velocity but the group velocity of the de Broglie waves\nthat is physically significant. In fact, the group velocity is \\emph{the}\nvelocity of the particle.\n\n\\subsection{Problem set 5}\n\\begin{enumerate}\n\\item Waves for which $\\omega$ and $k$ have are proportional are called\nnon-dispersive waves. Show that for non-dispersive waves the group velocity is\nidentical with the phase velocity.\n\\item Are electromagnetic waves in vacuum dispersive or non-dispersive?\n\\item Derive equations \\eqref{c2s4e21} and \\eqref{c2s4e23}.\n\\item Mention the word `wave' and most people think of waves on water. Waves\nin fluids are some of the most complicated waves one can come across. Read \nthe article \\url{https://en.wikipedia.org/wiki/Dispersion_(water_waves)} for a\nglimpse of their complexity and an understanding of what dispersion means.\n\\item The equation\n\\begin{equation}\\label{c2s4e25}\ny = A\\cos(kx + \\omega t)\n\\end{equation}\nalso represents a wave. What is the difference between the waves represented\nby \\eqref{c2s4e25} and \\eqref{c2s4e8}?\n\\end{enumerate}\n\n\\section{Davisson-Germer experiment}\\label{c2s5}\n`Light travels in a straight line' is what everyone learns first in optics. If\nthis were strictly true then all objects would cast a sharp shadow. If you hold\nyour hand in front of a light source and observe its shadow on a wall you will\nobserve that there is a central dark shadow of your palm is surrounded by a \nless darker outline of the palm. It happens because light rays bend as they go\npast your palm. This phenomenon in which waves past a sharp edge bend is called\ndiffraction. Diffraction is a characteristic of waves.\n\nDiffraction happens when light is made to pass through one or more narrow slits.\nA grating is an optical instrument with a very large number of slits. It is\nmade by etching corrugations on a glass plate. Any regular, periodic arrangement\nof a transparent material is a grating. \n\nVisible light is diffracted by grating made of glass. Electromagnetic waves of\nmuch shorter wavelengths like X-rays need gratings whose `slits' are far more\nclosely etched. It is hard to manufacture such grating but nature provides an\nalternative in the form of crystals. When X-rays are shone on a crystal the\ndiffracted rays form a series of intensity peaks which depend on the geometry\nand symmetry of the crystal. Observing a diffraction pattern of X-rays is not\nsurprising. Davisson and Germer observed a diffraction pattern when they\nreplaced X-rays with electrons giving the first evidence in support of de\nBroglie's speculation that particles have wave-like features.\n\nElectrons being charged particles interact strongly with the crystals. As a \nresult they undergo significant accelaration in the crystal. A change in their\nmomentum is accompanied with a change in their wavelength. It makes an analysis\nof electron diffraction rather challenging. In modern times neutrons are used\nin the place of electrons. They are neutral and do not interact with the crystal\nas much as electrons do. They too result in a diffraction pattern further\ncorroborating de Broglie's hypothesis.\n\n\\subsection{Problem set 6}\n\\begin{enumerate}\n\\item The molecular weight of N$_2$ gas is $28$ g per mole. That is, $N_A$ \nnumber of N$_2$ molecules weigh $28$ g, where $N_A$ is the Avogadro number.\n\\begin{enumerate}\n\\item Find the mass of one N$_2$ molecule.\n\\item The root mean square speed of a gas molecule of mass $m$ at temperature\n$T$ is\n\\begin{equation}\nu = \\sqrt{\\frac{3kT}{m}}.\n\\end{equation}\nFind the root mean square of a Nitrogen molecule at $300$ K. Hence compute its\nmometum.\n\\item What is the de Broglie wavelength of the Nitrogen molecule? Compare it \nwith the typical mean free path which is of the order of $10^{-6}$ m.\n\\end{enumerate}\n\n\\item A typical cricket ball weighs $160$ g and typical fast bowler gives it a\nspeed of $130$ kmph. What is the ball's de Broglie wavelength after it \nleaves the bowler.\n\\end{enumerate}\n\n\\section{Towards uncertainty relation}\\label{c2s6}\nWe understand what waves are physically. Water waves are undulations on the\nsurface of water, sound waves are a succession of rarefactions and compressions\nin air, electromagnetic waves are fluctuations of electric and magnetic fields\nat a point. What are electrons waves? What undulates when an electron wave \npasses by?\n\nElectron waves, or de Broglie waves in general, are represented mathematically\nby a wave function $\\Psi$. It is a function of position $\\vec{r}$ and time $t$.\nIn general, $\\Psi$ is a complex valued function. That is, for a given $\\vec{r}$\nand $t$, $\\Psi(\\vec{r}, t)$ is a complex number. The quantity $|\\Psi|^2 = \\Psi\n\\Psi^\\ast$ is a real quantity. It is proportional to the probability of finding\na particle at a point $\\vec{r}$ and time $t$. This statement is not accurate\nbecause the probability of finding a particle exactly at $\\vec{r}$ and exactly\nat time $t$ is always zero. The correct interpretation of $\\Psi^2$ is that\nit is the probability of finding the particle in a small volume $dV$ around\n$\\vec{r}$ between times $t$ and $t + dt$. \n\nde Broglie waves are thus waves of a function $\\Psi$ whose squared modulus has\nis the probability density function of finding the particle in a neighbourhood\nof a point and in an interval of time.\n\nA probabilistic interpretation of $|\\Psi|^2$ indicates that there is never a \ncertainty of finding a particle in a small enough region around a point \n$\\vec{r}$. The standard deviation of $|\\Psi|^2$ at $\\vec{r}$ is a measure of\nuncertainty of finding the particle in the neighbourhood. If we restrict \nourselves to one dimension, that is if $\\Psi$ is function of $x$ and $t$ then\nthe uncertainty of finding a particle in the neighbourhood of a point $x_0$ is\ndenoted by $\\Delta x$. \n\nArmed with this understanding of $\\Psi$ let us consider a wave whose wavelength\nis known precisely. If $\\lambda$ is known then so is $k = 2\\pi/\\lambda$. Such\na wave looks like the one in figure \\ref{c2f3}. Its squared modulus is shown in\nfigure \\ref{c2f4}. How can one tell where the particle is? It seems like the\nparticle can be just about anywhere where $|\\Psi|^2$ is not close to zero. The\nuncertainty of finding it is fairly large.\n\\begin{figure}\n\\begin{center}\n\\includegraphics[scale=0.5]{one-wave}\n\\caption{A wave with precise $k$.}\\label{c2f3}\n\\includegraphics[scale=0.5]{one-wave-sq}\n\\caption{Squared modulus of a wave with precise $k$.}\\label{c2f4}\n\\end{center}\n\\end{figure}\nFigures \\ref{c2f5} and \\ref{c2f6} show a plots for a wave formed by \nsuperposition of two sinusoidal waves. Now we do not know the precise $k$, for \nwe have mixed two of them, but we get a slightly improved localisation of the\nparticle.\n\\begin{figure}\n\\begin{center}\n\\includegraphics[scale=0.5]{two-waves}\n\\caption{Superposition of two cosine waves.}\\label{c2f5}\n\\includegraphics[scale=0.5]{two-waves-sq}\n\\caption{Squared modulus of superposition of waves.}\\label{c2f6}\n\\end{center}\n\\end{figure}\n\nIf we repeat the exercise by mixing ten sinusoidal waves, we get the pair of\nimages \\ref{c2f7} and \\ref{c2f8}. We observe a much better knowledge of the\nparticle's position at the cost of losing information of $k$. We can now say\nwith a great confidence that the particle is likely to be in a small \nneighbourhood of the origin. \n\\begin{figure}\n\\begin{center}\n\\includegraphics[scale=0.5]{ten-waves}\n\\caption{Superposition of ten cosine waves.}\\label{c2f7}\n\\includegraphics[scale=0.5]{ten-waves-sq}\n\\caption{Squared modulus of superposition of ten waves.}\\label{c2f8}\n\\end{center}\n\\end{figure}\n\nThese pictures indicate that there is always a trade-off in knowing $k$ and\nknowing $x$. If you think this is just the mathematical property of sinusoids\nyou are absolutely correct. It is indeed a mathematical property that\n\\begin{equation}\\label{c2s6e1}\n\\Delta x \\Delta k \\ge \\frac{1}{2}.\n\\end{equation}\nPhysics connects momentum with $k$ through the equation\n\\begin{equation}\\label{c2s6e2}\np = \\frac{h}{\\lambda} = \\frac{h}{2\\pi}k\n\\end{equation}\nso that we can write equation \\eqref{c2s6e1} as\n\\begin{equation}\\label{c2s6e3}\n\\Delta x \\Delta p \\ge \\frac{h}{4\\pi}.\n\\end{equation}\nThis is the celebrated `Heisenberg uncertainty relation'. It tells us that\nwe cannot \\emph{simultaneously} know the position and momentum of a particle.\nWe illustrate the uncertainty relation by considering a particle in one \ndimension. As a result, its position and momentum had just one component. \nHowever, in general, a particle will have three position components $(x, y, z)$\nand three momentum components $(p_x, p_y, p_z)$. The complete set of uncertainty\nrelations is\n\\begin{eqnarray}\n\\Delta x \\Delta p_x &\\ge& \\frac{h}{4\\pi} \\label{c2s6e4} \\\\\n\\Delta y \\Delta p_y &\\ge& \\frac{h}{4\\pi} \\label{c2s6e5} \\\\\n\\Delta z \\Delta p_z &\\ge& \\frac{h}{4\\pi}. \\label{c2s6e6}\n\\end{eqnarray}\nHowever,\n\\begin{eqnarray}\n\\Delta x \\Delta p_y &=& 0 \\label{c2s6e7} \\\\\n\\Delta x \\Delta p_z &=& 0 \\label{c2s6e8} \\\\\n\\Delta y \\Delta p_x &=& 0 \\label{c2s6e9} \\\\\n\\Delta y \\Delta p_z &=& 0 \\label{c2s6e10} \\\\\n\\Delta z \\Delta p_x &=& 0 \\label{c2s6e11} \\\\\n\\Delta z \\Delta p_y &=& 0 \\label{c2s6e12}\n\\end{eqnarray}\nEquations \\eqref{c2s6e7} to \\eqref{c2s6e12} guarantee that one can measure the\n$x$ component of a particle and $p_y$ or $p_z$ components of its momentum with\narbitrary precision. Why is $\\Delta x \\Delta p_x \\ge h/(4\\pi)$ but $\\Delta x\n\\Delta p_y = 0$? This question cannot be answered informally using the pictures\nof superposed waves and their square modulii. The answer will be partly clear\nwhen we study quantum mechanics later in this course.\n\n\\subsection{Problem set - 6}\n\\begin{enumerate}\n\\item An atom's size is of the order of $1$ A${}^\\circ$. It means that the \nuncertainty in the position of an electron in it is also of the same order.\nWhat is the minimum uncertainty in momentum? What is the minimum uncertainty in\nkinetic energy? (Assume that the electron moves at non-relativistic speed so\nthat its kinetic energy is $T = p^2/(2m_e)$, $m_e$ being the mass of the \nelectron.\n\\item Energy of nucleons (protons and neutrons) is of the order of $1$ MeV.\nCan you estimate the size of the nucleus using the uncertainty relation?\n\\end{enumerate}\n\n\n", "meta": {"hexsha": "4796bde271b3b4e9988abd7e21ac165f2ba92869", "size": 42838, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "qm/modern-physics/notes/c2.tex", "max_stars_repo_name": "drameyjoshi/physics", "max_stars_repo_head_hexsha": "9d3360258bdd12bc3d981ae08c8358dff4b777b3", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "qm/modern-physics/notes/c2.tex", "max_issues_repo_name": "drameyjoshi/physics", "max_issues_repo_head_hexsha": "9d3360258bdd12bc3d981ae08c8358dff4b777b3", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qm/modern-physics/notes/c2.tex", "max_forks_repo_name": "drameyjoshi/physics", "max_forks_repo_head_hexsha": "9d3360258bdd12bc3d981ae08c8358dff4b777b3", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.9577142857, "max_line_length": 82, "alphanum_fraction": 0.7550305803, "num_tokens": 12603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593171945416, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.325807873004633}}
{"text": "\\documentclass{article}\n\\usepackage{amsmath,amsthm,amsfonts,microtype,amssymb}\n\\usepackage{enumitem}\n\\usepackage{parskip}\n\\usepackage{mathpazo}\n\\usepackage{tikz-cd}\n\\usepackage{geometry}\n\\geometry{top=1in}\n\\usepackage{float}\n\\usepackage{graphicx}\n\n\\usepackage{hyperref}\n\\hypersetup{%\n  colorlinks=true,\n  linkcolor=blue,\n  filecolor=blue,\n  urlcolor=blue,\n  bookmarks=true,\n  pdfpagemode=FullScreen,\n}\n\n\n\\title{Homework 07 \\\\ Mayer--Vietoris Sequence}\n\\author{Algebraic Topology - Winter 2021}\n\\date{Due: \\textbf{March 25, 2021, 11:59 pm}}\n\n\\begin{document}\n\\pagenumbering{gobble}\n\\maketitle\n\nUsing the Mayer--Vietoris sequence compute the singular homology with integer coefficients of the following spaces:\n\\begin{enumerate}\n    \\item $SX$ where $X$ is a \\emph{path-connected} topological space,\n    \\item $S^1 \\vee S^1$,\n    \\item $S^1 \\times S^1$,\n    \\item $\\mathbb{RP}^2$.\n\\end{enumerate}\nYou cannot assume that $H_1$ is the abelianization of $\\pi_1$. You instead need to compute it explicitly using the long exact sequence.\n\n\\LaTeX ing long-exact sequences can get very tedious and time-consuming. Feel free to submit handwritten solutions for this homework.\n\n\\newpage\n\\section*{Suggested exercises for practice from Hatcher}\n\n\\begin{description}\n\\item[Pg. 157] 28, 29, 30, 31, 32, 35\n\\end{description}\n\n\\end{document}\n", "meta": {"hexsha": "bc39e0688db0c3a7a8fde09fcc0f128f081805e7", "size": 1326, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "HW07.tex", "max_stars_repo_name": "apurvnakade/uwo2021-algebraic-topology", "max_stars_repo_head_hexsha": "eea8ddd8328aba9126e7d7e73888338b5aa6bb51", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW07.tex", "max_issues_repo_name": "apurvnakade/uwo2021-algebraic-topology", "max_issues_repo_head_hexsha": "eea8ddd8328aba9126e7d7e73888338b5aa6bb51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW07.tex", "max_forks_repo_name": "apurvnakade/uwo2021-algebraic-topology", "max_forks_repo_head_hexsha": "eea8ddd8328aba9126e7d7e73888338b5aa6bb51", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.52, "max_line_length": 135, "alphanum_fraction": 0.7518853695, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.32580787108132936}}
{"text": "\r\n\r\nThe proposed autoscaling system scales a web application in response to change in throughput at fixed intervals, which we denote by reconfiguration intervals of 10 minutes. This system is able to provision the right amount and type of vm instances for minimizing the number of SLA violations while keeping the operational cost adapted to the customer requirements. Vertical and horizontal scaling actions can be applicable to satisfy the service demand. This architecture has the following key components:\r\n\r\n\\vspace{2mm}\r\n\r\n\\textbf{Predictor: } Inspired by~\\cite{wolski_network_1999}, the Predictor component takes the monitoring data as input and uses different time-series analysis techniques to predict the future service demand for the next time interval. To provide accurate forecasting measures, this component utilizes the technique that exhibited the lowest cumulative error measure during the previous monitoring window. By doing so, the Predictor is able to adapt the predictions to the current type of workload. This component supports five distinct statistical models that fits four types of workload: \\emph{(1)} \\emph{Linear Regression} for linear trends~\\cite{muppala_regression-based_2012}, \\emph{(2)} \\emph{Auto Regression Moving Average} (ARMA) for linear with small oscillations~\\cite{roy_efficient_2011},\\emph{(3)} \\emph{Exponential Smoothing} for daily and seasonal~\\cite{exponential_smoothing2010}, and \\emph{(4)} \\emph{Autoregression} and \\emph{Vector Autoregression} for correlated trends~\\cite{chandra_dynamic_2003,vector_autoregression_2006}. \r\n\r\n\\vspace{2mm}\r\n\r\n\\textbf{Profiler: } To choose a scaling plan, provisioning systems have to know the limitations of the different server configurations when running an application. The definition of profiles for each instance's type improves the accuracy of the scaling actions in heterogeneous cloud infrastructures. Thus, the Profiler component calculates the optimal throughput of each type of provisioned vm instance using profiling techniques.\r\n\r\n% without any server instrumentation.\r\n\r\n\\vspace{2mm}\r\n\r\n\\textbf{Dynamic load balancer: } In order to adapt our system to the heterogeneity of requests and cloud resources, this component dynamically assign weights to the backend servers to proportionally distribute the incoming traffic based on the performance characteristics of each backend. As an example, a server with four cores is able to process a higher number of requests so its weight has to a be greater than a server with only one core.\r\n\r\n\\vspace{2mm}\r\n\r\n\\textbf{Scaler:} This component contains the central intelligence of our autoscaling system. As illustrated in Figure~\\ref{autoScalingSys}, Scaler uses the Predictor and Profiler components to find the optimal provisioning strategy that fulfills a pre-established SLO (Service Level Objective). Furthermore, this component constantly analyzes the behavior of each provisioned vm triggering the Dynamic load balancer component when need it.\r\n\r\n\\begin{figure}[htb]\r\n  \\begin{center}\r\n    \\includegraphics[width=.85\\linewidth]{images/monitoringSchema}\r\n  \\end{center}\r\n\\vspace{-5mm}\r\n  \\caption{Autoscaling system.}\r\n  \\label{autoScalingSys}\r\n\\end{figure}\r\n\r\n%In the following we ..\r\n\r\n%\\subsection{Online profiling of allocated instances\\label{profiling}}\r\n\\subsection{Online instance profiling\\label{profiling}}\r\n\r\nRegarding the resource heterogeneity of cloud infrastructures, a sensitivity analysis of the allocated resources is crucial to provide accurate scaling decisions. Accordingly, online profiling-based techniques~\\cite{kaviani_profiling-as--service:_2011} have recently emerged as a solution to  estimate the resource's throughput under a certain workload. Traditionally, this technique replicates at runtime a server hosting an application, with a new server with profiling instrumentation that analyzes the performance behavior of a specific resource under a fixed percentage of the incoming traffic~\\cite{jiangThesis,dejavu2012}. The use of fixed workloads to calculate the maximum throughput of a resource do not necessary imply the definition of more accurate profiles. A reason seems to be the lack of ideal performance isolation in cloud infrastructures which affects to the precision of the definitions, and consequently reduces the accuracy of the decisions. Furthermore, setting a profiling environment, in a heterogeneous cloud infrastructure, requires as many additional resources as number of available server configurations. Even though the use of online-profiling techniques is still under study, the configuration of a parallel environment and the heterogeneity of the cloud resources are the major drawbacks for its adoption. These techniques increase the operational cost and do not necessarily improve the accuracy of the scaling decisions.\r\n\r\n%Even though the use of online-profiling techniques is still under study, the configuration of a parallel %environment and the limited accuracy of its scaling decisions are the major drawbacks for its %adoption.\r\n\r\nAs a consequence, we designed a novel online profiling technique that gives an estimation of the maximum throughput of each allocated instance's type without need for additional resources or parallel environments. To do that, the Profiler component use the provisioned resources for the analysis and estimation of the computing capacity of each available hardware configuration.\r\n\r\n\\begin{algorithm}\r\n{\\scriptsize\r\n\\SetAlgoLined\r\n\\SetInd{0mm}{2mm}\r\n\\KwData{ \\\\Service Level Objective, \\emph{slo} \\\\ List of allocated instance types, \\emph{inst\\_types} \\\\ Compute units per \\emph{inst\\_type}, \\emph{compute\\_units$_{inst}$}}\r\n\r\n\\KwResult{Instances performance classification}\r\n\r\n\\While{ allocated instances to profile}{\r\n\\BlankLine\r\nCollect profiling data of \\emph{inst\\_type}: \\emph{req\\_rate, cpu\\_usage and resp\\_time}\\;\r\n\r\n\\While{ profiling data to smooth}{  \\label{alg:smooth}\r\n//Perform smoothing percentiles technique \\;\r\n\\If{ \\emph{resp\\_time}$_i$ $>$ (slo * 0.25) and \\emph{resp\\_time}$_i$ $<=$ (slo * 0.75)}{ \r\n\t\\If{ \\emph{req\\_rate}$_i$ $>$ 0 and \\emph{cpu\\_usage}$_i$ $<$ 75}{ \r\n\t\t\\hspace{3mm} Add \\emph{cpu\\_usage$_i$} to cpu\\_usage\\_data\\;\r\n\t\t\\hspace{3mm} Add \\emph{req\\_rate$_i$} to req\\_rate\\_data\\;\r\n\t\t\\hspace{3mm} Add \\emph{resp\\_time$_i$} to resp\\_time\\_data\\;\r\n}\r\n}\r\n} \\label{alg:endSmooth}\r\n\\BlankLine\r\nInitialize instance capacity \\emph{CPU speed$_{inst}$} to 0 \\;\r\n\\uIf{ \\emph{resp\\_time\\_data}, \\emph{cpu\\_usage\\_data}, \\emph{req\\_rate\\_data}  \\textbf{not empty}}{\r\nCalculate average of \\emph{cpu\\_usage\\_data}, \\emph{CPU$_{inst}$} \\;\r\nCalculate average of \\emph{req\\_rate\\_data}, \\emph{Num\\_requests$_{inst}$} \\;\r\n\\BlankLine\r\n\\emph{CPU speed$_{inst}$} = $\\dfrac{\\emph{CPU$_{inst}$} } {\\emph{Num\\_requests$_{inst}$} }$  \\;\r\n\\BlankLine\r\nStore instance computing capacity, \\emph{CPU speed$_{inst}$} \\;\r\n}\r\n\\Else{ \r\n\tUse historic value of \\emph{CPU speed$_{inst}$} for \\emph{inst\\_type}\\;\r\n}\r\n\\BlankLine\r\nClassify \\emph{inst\\_type} based on its computing capacity \\;\r\n\\If{ CPU speed$_{inst}$ = 0 }{\r\nUse \\emph{compute\\_units$_{inst}$} of \\emph{inst\\_type} to rank \\emph{inst\\_type} \\;\r\n}\r\n\\Else{ \r\nUse new value of \\emph{CPU speed$_{inst}$} to rank \\emph{inst\\_type} \\;\r\n}\r\n}\r\n}\r\n\\caption{Instance profiling algorithm}\r\n\\label{profilingAlg}\r\n\\end{algorithm}\r\n\r\nAs detailed in Algorithm~\\ref{profilingAlg}, once the Scaler component decides to trigger a scaling action, the Profiler component estimates the throughput of the allocated instances according the following steps:\r\n\r\n\\begin{enumerate}\r\n\\item Collect the latest hour of monitoring data from each instance's type. This profiling data contains information about monitoring metrics such as the request rate, cpu usage and response time, which provide enough feedback for the definition of instance profiles. \r\n\r\n\\item Perform a smoothing technique over the profiling data of each instance to remove the noise generated by traffic spikes. As pointed out in~\\cite{gandhi_hybrid_2012}, when hosting web applications sudden changes in the workload, interference due to virtualization or OS activities may affect the precision of the profiling process. Hence, we decided to smooth the profiling data during the latest hour (or older if there is not enough data) to identify the performance capacity of one instance. In particular, the Profiler extracts the smoothed 75th and 25th percentiles from the response times below the SLO and 75th percentile from the cpu usage data-points. (See Lines \\ref{alg:smooth}-\\ref{alg:endSmooth}). This mechanism allows to identify the maximum ideal throughput of each instance while enforcing the performance requirements and avoiding CPU saturation. (based on the Amazon EC2 recommendation CPU usage < 75 )\r\n\r\nAs an example in Figure~\\ref{fig:vm_performance}, we show the profiling data and percentiles for one \"m1.small\" (left) and one \"c1.medium\" (right) EC2 instance types during one hour. The gray areas represent the ranges of response times and cpu usage comprised by the percentiles. Red circles contain all data points that will be used to calculate the maximum ideal throughput of one instance. As we mentioned above, some data points are excluded as they identify periods of time on which resources suffered from under-utilization or over-utilization (denoted by white areas). Furthermore, as shown in Figure~\\ref{fig:vm_performance} (left), a short number of data points are comprised between the percentiles for the \"m1.small\" instance. Its poor hardware configuration makes this type of instance more vulnerable to sudden changes in the workload.\r\n\r\n%and three red circles highlight several data-points on which the performance of the instance was optimal while enforcing the %SLO.\r\n\r\n%\\begin{figure*}[htb]\r\n%\t\\begin{minipage}[b]{0.5\\linewidth}\r\n%\t\t\\includegraphics[height=4.5cm]{images/vm_performance_resp_smallEC2Remark.pdf}\t\t%\\includegraphics[height=4.5cm]{images/vm_performance_cpu_smallEC2Remark.pdf}\r\n%\t\t\\vspace{-4mm}\r\n%\t\\end{minipage}\r\n%\t\\hfill\r\n%\t\\begin{minipage}[b]{0.5\\linewidth}\r\n%\t\t\\includegraphics[height=4.5cm]{images/vm_performance_resp_c1mediumRemark.pdf}\t\t%\\includegraphics[height=4.5cm]{images/vm_performance_cpu_c1mediumRemark.pdf}\r\n%\t\t\\vspace{-4mm}\r\n%\t\\end{minipage}\r\n%\\caption{Profiling data and percentiles of m1.small and c1.medium EC2 instances.}\r\n%\\label{fig:vm_performance}\r\n%\\end{figure*}\r\n\r\n\\begin{figure*}[htb]\r\n\t\\begin{minipage}[b]{0.45\\linewidth}\r\n\t\t\\includegraphics[height=8.5cm]{images/idealSmallRemark.pdf}\t\r\n\t\t\\vspace{-4mm}\r\n\t\\end{minipage}\r\n\t\\hfill\r\n\t\\begin{minipage}[b]{0.45\\linewidth}\r\n\t\t\\includegraphics[height=8cm]{images/idealc1MediumRemark.pdf}\r\n\t\t\\vspace{-4mm}\r\n\t\\end{minipage}\r\n\\caption{Profiling data and percentiles of m1.small and c1.medium EC2 instances.}\r\n\\label{fig:vm_performance}\r\n\\end{figure*}\r\n\r\n\\item Classify the different instance types depending on its computing capacity. Using the profiling smoothed data of each instance type, the Profiler computes a factor, named \\emph{CPU speed}, as the number of clocks required to process a request (clocks/request), where \\emph{CPU$_{inst}$} represents the average of cpu usage and \\emph{Num\\_requests$_{inst}$} the average of request rate, as illustrated in the next Equation~\\ref{cpu_speed}:\r\n\r\n\\begin{equation}\\label{cpu_speed}\r\n\\begin{split}\r\nCPU speed_{inst} = \\dfrac{  CPU_{inst} } {Num\\_requests_{inst} } \r\n\\end{split}\r\n\\end{equation}\r\n\r\n\r\nThe \\emph{CPU speed$_{inst}$} factor gives an estimation of the ideal performance capacity of one instance when processing the current workload. Based on the value of this factor per-instance, the \\emph{Profiler} classifies the different instances based on its computing capacity when running an application. The resulting classification gives an interesting feedback to the Scaler component, which is now able to identify the limitations of the instances, and consequently to choose an optimal scaling plan. Initially, there are not instance profiles due to the lack of monitoring data, thereby the Scaler uses the number of compute units per instance as a priori classification of their performance capacities. Note that, this work only consider the compute units, but memory or bandwidth can be also taken into account to classify the instances.\r\n\r\n\\end{enumerate}\r\n\r\nThis profiling process allows to define a profile per instance type, thus facilitating the selection of an appropriate scaling plan that satisfies the QoS requirements. As such, the accuracy of the scaling decisions can be improved independently of factors such as performance isolation in clouds or request heterogeneity.\r\n\r\n\r\n\\subsection{The scaling decision maker}\r\n\r\nThe Scaler component is the central governance of this autoscaling system, and thereby is the responsible of triggering any scaling decision.\r\n\r\n%% Threshold fixed by the user\r\n\r\n\\subsubsection{Time-series smoothing}\r\n\r\nWhen minimizing the SLA violations, a precise analysis of the monitoring data is crucial to improve the accuracy of the scaling decisions. It allows to identify the resource requirements from the current workload type. This analyisis has even more importance when hosting web applications (e.g. Wikipedia, Amazon) that need to provide high availability and performance to their clients. Moreover, the workload heterogeneity of this sites requires a meticulous analysis of every monitoring data-point to reduce at the maximum the number of SLO violations. \r\n\r\n\\begin{figure}[htb]\r\n\t\\begin{minipage}[b]{0.49\\linewidth}\r\n\t\t\\includegraphics[width=4cm,height=3cm]{images/data2007/proxy_outputAvg.pdf}\t\r\n\t\t\\vspace{-4mm}\r\n\t\\end{minipage}\r\n\t\\hfill\r\n\t\\begin{minipage}[b]{0.49\\linewidth}\r\n\t\t\\includegraphics[width=4cm,height=3cm]{images/data2007/proxy_outputWMA.pdf}\r\n\t\t\\vspace{-4mm}\r\n\t\\end{minipage}\r\n\\caption{Response times for a trace: Average vs extended WMA.}\r\n\\label{fig:data_analysis}\r\n\\end{figure}\r\n\r\nTo obtain precise information (response times) that reflects the performance behavior of an application, we decided to extend a known smoothing technique called \\emph{Weighted Moving Average} (WMA). This technique is widely used in resource provisioning systems instead of others such as the median, average or moving average. Using our extension of WMA, it first associated weights in an increasing order giving more importance to the latest monitoring data; and second it doubles the original weight value of each data-point that exceeds the performance requirements (response time). By doing so, the Scaler analyzes the monitoring data giving special importance to the data points on which SLO violations have occurred, and thereby being able to detect and avoid the maximum number of violations. As an example, Figure~\\ref{fig:data_analysis} shows how several SLO violantions are omitted when analyzing the monitoring data using an average analytical method (left) than when using our version of WMA (right).\r\n\r\n\\subsubsection{Definition of a reactive threshold}\r\n\r\n\\fixme{Perhaps, you may want to omit this subsection, as it is more related to When to provision than How to provision ?}\r\n\r\nInitially, the user defines several performance requirements that will be utilized by the Scaler to trigger scaling actions. As we mentioned, these QoS goals are previously specified in the Service Level Objective (SLO). In particual, when hosting web applications, these performance requirements are usually related to the maximum processing time needed to serve any request (response times). Regarding SLO fulfillment the majority of resource provisioning system aims to maintain the processing time as closer as possible to the performance requirements. However, this operation can become a problem, as provisioning systems are vulnerable to temporal traffic oscillations causing SLO violations.\r\n\r\nTherefore, and based on the requirements, the Scaler defines a reactive threshold that will enable in advance to react against any traffic oscillation minimizing the number of SLO violations or period of time under-utilization of the provisioned resources. As shown in Figure~\\ref{threshold}, this reactive threshold specifies one upper and lower boundaries creating two head-rooms between them and the performance requirements pre-defined by the user (for the response time). In the future, these two boundaries could be adjusted depending on the hardware configuration of each provisioned vm, as introduced in~\\cite{beloglazov_adaptive_2010}.  \r\n\r\n\r\n\\begin{figure}[htb]\r\n  \\begin{center}\r\n    \\includegraphics[width=.85\\linewidth]{images/thresholdGraphic.jpg}\r\n  \\end{center}\r\n\\vspace{-5mm}\r\n  \\caption{Reactive threshold.}\r\n  \\label{threshold}\r\n\\end{figure}\r\n\r\n\\subsubsection{Vertical and horizontal scaling}\r\n\r\nThe \\emph{Scaler} component supports two ways to add and remove resources to an application: vertical and horizontal scaling.\r\nHorizontal scaling enables to create a cluster of virtual machines associated to one application whose size is dynamically adapted to the workload variations by adding or removing vmes to the cluster. This scaling technique is commonly supported for the majority of resource provisioning systems. In our system, vertical scaling enables to add or remove resources with high or less CPU or memory using \\emph{service live migration}. Using this technique, the Scaler migrates the hosted service (web application) from one virtual machine to another with better hardware configuration. To reduce the degradations caused by this type of migration or by the booting time of the new machine, the Scaler checks the proper functioning of the new machine in order to release the older one.\r\n\r\nThus, the \\emph{Scaler} evaluates whether the current performance behavior requires to trigger any of the following scaling actions:\r\n\r\n\\begin{itemize}\r\n\r\n\\item \\textbf{Scale out or up:} Additional resources are provisioned if the performance behavior exceeds the upper boundary of the reactive threshold, and the \\emph{Predictor} confirms that such traffic changes will remain at least during the next monitoring window (in our experiments 5min). \r\n\r\n\\item \\textbf{Scale back or down:} Resources are released if the performance behavior exceeds the lower boundary of the reactive threshold, and the \\emph{Predictor} confirms that such traffic changes will remain at least during the next monitoring window.\r\n\r\n\\end{itemize}\r\n\r\nNote that, the \\emph{Predictor} component will trigger short-term forecasts operations to minimize at the maximum the number of SLA violations, as well as to keep a high level of efficiency in the predictions. \r\n\r\n\r\n\r\n%\\begin{figure*}[htb]\r\n%\t\\begin{minipage}[b]{0.3\\linewidth}\r\n%\t\t\\includegraphics[height=4.5cm]{images/prediction_conpaas_6min.eps}\r\n%\t\t\\vspace{-4mm}\r\n%\t\\end{minipage}\r\n%\t\\hfill\r\n%\t\\begin{minipage}[b]{0.3\\linewidth}\r\n%\t\t\\includegraphics[height=4.5cm]{images/prediction_conpaas_10min}\r\n%\t\t\\vspace{-4mm}\r\n%\t\\end{minipage}\r\n%\t\\hfill\r\n%\t\\begin{minipage}[b]{0.3\\linewidth}\r\n%\t\t\\includegraphics[height=4.5cm]{images/prediction_conpaas_30min}\r\n%\t\t\\vspace{-4mm}\r\n%\t\\end{minipage}\r\n%\\caption{ConPaaS Predictions, response times for 5min, 10min and 30min ahead.}\r\n%\\label{fig:vm_performance}\r\n%\\end{figure*}\r\n\r\n\\subsubsection{Scaling strategy decision-making}\r\nThe most important and challenging phase in a resource provisioning system is the selection of an appropriate scaling strategy (combination of resources) that satisfies the performance requirements with the lowest operational cost. This operation can become more laborious when running web applications, and therefore it has been barely addressed in the existing provisioning systems. Web applications are often a target of temporal traffic variations that may cause SLO violations having an impact in the user experience. Hence, the selection of an appropriate scaling plan becomes crucial to mitigate these penalties. \r\n\r\n\r\nTo overcome this challenging phase, the Scaler takes into consideration two aspects: resource heterogeneity and user experience. Cloud infrastructures are highly heterogeneous, offering a wide range of resource combinations. On the other hand, to boost the volume of customers, the user experience appears as a mandatory requirement in web applications contrary to budget cuts that may reduce the advantage over competitors.\r\nBased on that, the Scaler computes the cost of all the possible resource combinations how the cost incurred by its SLO fulfillment degree and the infrastructure cost. The SLO fulfillment degree indicates the vulnerability of a strategy to experience SLO violations. To refine this search process according to the final goal and adapted to the customer preferences (user experience), the Scaler provides three classes of SLA agreements in function of the type of customer. These three classes of customers namely, gold, silver and bronze minimize the SLA violations with a different infrastructure cost. Accordingly, a gold customer pays more in order to get the best service at the cost of some extra over-provisioning. A silver customer gets good availability while a bronze customer obtains a reduced, but acceptable, SLA fulfillment but with very little over-provisioning.\r\n\r\nPrior to any resource selection, the Scaler has to measure the requirements of the current workload. To do that, it has to compute its degree of complexity taken into account the total cpu usage and request rate served by the current scaling strategy. In Equation~\\ref{workload_complexity}, the \\emph{$Workload_{complex}$} factor represents the complexity of the incoming traffic and includes degradations caused by operative system activities, low network performance, vm sharing or request heterogeneity. These degradations are not detected by individually analyzing the request rate and cpu usage consumed by all the resources. Thus, the \\emph{$Workload_{complex}$} is computed by using the sum of the cpu usage (denoted by \\emph{$CPU\\_usage_{i}$}) and the performance capacity of each allocated resource. The performance capacity is calculated as the average of the request rate served by each resource (denoted by $Num\\_reqs_{i}$) and its ideal throughput (denoted by $CPU speed_{inst_{i}}$). By using the ideal throughput instead of calculating the current throughput, the Scaler is able to detect how much the current workload is affecting to the ideal performance of an instance.\r\n\r\n{\\scriptsize\r\n\\begin{equation}\\label{workload_complexity}\r\n\\begin{split}\r\nWorkload_{complex}  = \\dfrac{ \\sum_{i=1}^N CPU\\_usage_{i}  }  {  \\sum_{i=1}^N \\bigg(  Num\\_reqs_{i}  * CPU speed_{inst_{i}}   \\bigg)   }\r\n\\end{split}\r\n\\end{equation}\r\n}\r\n\r\nAdditionally, the total cpu usage ($\\sum_{i=1}^N CPU\\_usage_{i} $) and request rate ($\\sum_{i=1}^N  Num\\_reqs_{i}$) can be calculated by the Predictor component to estimate the future service demand for the next monitoring windows (in our experiments 30min). This enables to select in advance a scaling strategy that will handle future variations in the workload, and thereby reducing the operational cost. As an example in Figure~\\ref{fig:forecast}, the Predictor shows the forecast values for the resource requirements during the next 30min offering an acceptable level of accuracy. \r\n\r\n\\begin{figure}[htb]\r\n  \\begin{center}\r\n    \\includegraphics[height=5cm]{images/prediction_conpaas_30min}\r\n  \\end{center}\r\n\\vspace{-5mm}\r\n  \\caption{ConPaaS Predictor: prediction values for 30min ahead.}\r\n  \\label{fig:forecast}\r\n\\end{figure}\r\n\r\n\r\nTo decide which type of vm instances to release or add, the Scaler uses an optimal decision tree that calculates all the possible scaling strategies.  Figure~\\ref{fig:scalingTree} shows three examples of scaling actions that propose three different resource combinations using EC2 instances. In the scaling decision tree, each node represents each type of vm instance offered by the cloud infrastructure. The branches define all the possible combination of resources. While the links indicate the percentage of CPU usage consumed to process the current workload when using a specific combination. Note that, CPU values provides enough feedback about the performance capacity, as it is a function of the request complexity  and number of served requests. To calculate the CPU usage consumed by each scaling strategy to process the current workload, Scaler uses the following formula~\\ref{resource_combination}. \r\n\r\n\\begin{figure}[htb]\r\n  \\begin{center}\r\n    \\includegraphics[height=5cm]{images/scalingTree}\r\n  \\end{center}\r\n\\vspace{-5mm}\r\n  \\caption{Decision tree: scaling actions using EC2 instances.}\r\n  \\label{fig:scalingTree}\r\n\\end{figure}\r\n\r\n\r\n\r\n%To calculate the different combinations of VM instances that enforce the performance requirements, we used the next\r\n\r\n\r\n{\\scriptsize\r\n\\begin{equation}\\label{resource_combination}\r\n\\begin{split}\r\nCPU_{strategy} = \\dfrac{ \\sum_{i=1}^n \\bigg( \\bigg( \\dfrac{ Num\\_reqs_{total} * Workload_{complex} }  {N}  \\bigg) * CPU speed_{inst_{i}} \\bigg) }  {N} \\\\ \r\n\\\\ {\\small \\textit{ If } CPU_{strategy} \\leqslant CPU_{SLO} }\r\n\\end{split}\r\n\\end{equation}\r\n}\r\n\r\nEquation~\\ref{resource_combination} defines how the workload will be distributed across the different instances taken into account their performance capacities.  Thus, the Scaler selects a strategy that uses \\emph{N} resources to distribute the \\emph{$Num\\_reqs_{total}$} (total rate of served requests) with a complexity \\emph{$Workload_{complex}$} across \\emph{N} instances with an ideal throughput \\emph{$CPUspeed_{inst}$}. Note that, the search of an optimal scaling strategy can represent a NP hard problem, so that Scaler limits the number of possible strategies by filtering them using a maximum CPU usage consumed by a strategy, where \\emph{$CPU_{strategy} \\leq CPU_{SLO}$}. \\emph{$CPU_{SLO}$} can be calculated based on the Amazon EC2 recommendations with CPU values lower than 75\\%, or based on the CPU values at which the application starts to experience SLO violations (or performance degradations). This assumption avoids to trigger new scaling actions in the next time interval saving costs. With the Equation~\\ref{resource_combination} the Scaler is able to answer to the question \\emph{\"How many and which type of vm instances to provision?\"}.\r\n\r\n%is calculated using the Profiler component and will variate depending on the type of vm instance used in the strategy. \r\n\r\n\r\nOnce the Scaler obtains a list of filtered scaling strategies, they are classified based on their infrastructure cost and degree of SLO fulfillment, as defined in the Equation~\\ref{strategy_cost}. The infrastructure cost specifies the price required to provision extra cloud resources. While the SLO fulfillment (\\emph{slo\\_fulfillment} in the Equation~\\ref{strategy_cost}) represents its degree of vulnerability to violations. The \\emph{slo\\_fulfillment} cost is calculated given the percentage of \\emph{$CPU_{strategy}$} and the \\emph{$CPU_{SLO}$}, multiply by a SLO penalty (in \\$)which is pre-established between the customer and provider. Obviously, higher values in the percentage of \\emph{$CPU_{strategy}$} imply an increment in the probability of having SLO violations under traffic spikes, so the \\emph{slo\\_fulfillment} will increase as well. Therefore, according to the customer preferences, the Scaler will select one strategy with the lowest, highest or medium cost.\r\n\r\n{\\scriptsize\r\n\\begin{equation}\\label{strategy_cost}\r\n\\begin{split}\r\ninfra\\_cost = \\sum_{i=1}^N \\big( instance\\_price_{i} \\big) \\\\\r\nslo\\_fulfillment =  \\bigg( \\dfrac{ CPU_{strategy} } {CPU_{SLO}} \\bigg) * SLO penalty \\\\\r\ncost\\_strategy = \\dfrac{  slo\\_fulfillment  } {infra\\_cost}\r\n\\end{split}\r\n\\end{equation}\r\n}\r\n\r\nTo decide which type of instance to release, the Scaler uses a conservative algorithm that releases the resources with the lowest utilization by analyzing their monitoring data. Similarly, a cost policy was also included for avoiding to choose wasteful scaling decisions. Considering the pricing model of cloud providers that charges users on a per-hour basis, the Scaler includes a cost policy that rejects strategies releasing vm instances which have been recently started ( 5min < time to the end of its hour < 20). Scaler releases resources which are closed to the hour are free under the cloud pricing model, and there is no gain from terminating them before this hour price boundary.\r\n\r\n%A complete point of view of the whole scaling flow is shown in Figure~\\ref{autoScalingFlow}.\r\n\r\n%\\begin{figure}[htb]\r\n%  \\begin{center}\r\n %   \\includegraphics[width=\\linewidth]{images/NewAutoScalingFlow}\r\n%  \\end{center}\r\n%\\vspace{-5mm}\r\n%  \\caption{Auto scaling flow.}\r\n%  \\label{autoScalingFlow}\r\n%\\end{figure}\r\n\r\n\r\n\\subsection{Dynamic load balancing weights: } \r\n\r\nThe problem we consider here is again the heterogeneity of cloud platforms.\r\nIndependently of its instance type, different virtual machines from the same cloud might have different performance\r\ncharacteristics, even when their specifications from the cloud vendor are \r\nthe same~\\cite{ec2Performance}. This issue can be addressed through various \r\nload balancing techniques, like assigning weights to the backend servers or \r\ntaking into account the current number of connections that each server \r\nhandles. Furthermore, the performance behavior of the virtual servers may \r\nalso fluctuate, either due to changes in the application's usage \r\npatterns, or due to changes related to the hosting of the virtual servers \r\n(e.g., vm migration).\r\n\r\n\r\n\\begin{figure}[htb]\r\n  \\begin{center}\r\n    \\includegraphics[height=5cm]{images/load_balancing}\r\n  \\end{center}\r\n\\vspace{-5mm}\r\n  \\caption{Weighted load balancing flow.}\r\n  \\label{fig:load_balancing}\r\n\\end{figure}\r\n\r\n\r\nIn order to address these issues, the Scaler implemented a weighted \r\nload balancing system in which the weights of the servers are \r\nperiodically re-adjusted automatically, based on the monitoring data.  \r\nThis method assigns the same weight to each backend server at the \r\nbeginning of the process. As illustrated in Figure~\\ref{fig:load_balancing}, the weights are then periodically\r\nadjusted (in our experiments, using a monitoring window of $\\sim$ 15min) proportionally \r\nwith the difference among the average cpu usage and request rate of the servers \r\nduring this time interval. By adding this technique to our autoscaling system, \r\nthe workload can be dynamically and proportionally distributed across the provisioned instances\r\ndepending on their performance capacities.\r\n\r\n%we noticed a performance improvement when running the benchmarks, as discussed in the following.\r\n\r\n\r\n\r\n", "meta": {"hexsha": "517352c3c8195893efeaf2c195d74d82fdd28d33", "size": 30489, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/publications/paper-autoscaling-web/old/scaling_sysOld.tex", "max_stars_repo_name": "bopopescu/conpaas-1", "max_stars_repo_head_hexsha": "cea3c02f499a729464697de7cf98c2041febc0ab", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2016-02-24T14:44:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-29T19:18:40.000Z", "max_issues_repo_path": "doc/publications/paper-autoscaling-web/old/scaling_sysOld.tex", "max_issues_repo_name": "bopopescu/conpaas-1", "max_issues_repo_head_hexsha": "cea3c02f499a729464697de7cf98c2041febc0ab", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2015-03-23T16:05:19.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-13T17:22:22.000Z", "max_forks_repo_path": "doc/publications/paper-autoscaling-web/old/scaling_sysOld.tex", "max_forks_repo_name": "bopopescu/conpaas-1", "max_forks_repo_head_hexsha": "cea3c02f499a729464697de7cf98c2041febc0ab", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-09-14T16:54:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-26T03:14:56.000Z", "avg_line_length": 86.3711048159, "max_line_length": 1457, "alphanum_fraction": 0.7869067533, "num_tokens": 6976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.32579058625555624}}
{"text": "%!TEX root=../mythesis.tex\n% Chapter Template\n\n\\chapter{Late Interaction} % Main chapter title\n\\chaptermark{Late Interaction}  % replace the chapter name with its abbreviated form\n\\label{ch:late_interaction}\n\n\n\\section{Method}\n\\label{ch:late_interaction_method}\n%\nIn this chapter, we present our next contribution designed specifically to tackle the long-standing decomposability gap problem described in~\\sref{sec:open_book}.\n%\nRecall that in the original DPR architecture, the question $q$ and passage $p$ are encoded \\emph{independently} at run time (see~\\eqref{eq:dpr_encode}), which later gets multiplied to obtain the dot product as their similarity score.\n%\nBy doing so, we effectively decompose the task of reading both $q$ and $p$ together to the task of extracting important information from each $q$ and $p$ to embedding vectors and later comparing them.\n%\nOur goal is to minimize the information loss caused by the extraction step.\n\n\n\\begin{figure}[!htbp]\n\t\\centering\n\t\\includegraphics[width=1.0\\linewidth]{late_interaction/two_tower_late_interaction.pdf}\n\t\\caption[Two-tower architecture of DPR retriever with the late interaction mechanism.]{\n\t\t%\n\t\tThe two-tower architecture of the DPR retriever with the late interaction mechanism.\n\t\t%\n\t\tAfter the top-$n$ retrieval with the usual similarity scores $\\text{sim}(q, p)$, where $n > k$, embedding vectors are fed to the feed-forward interaction layer to obtain the late interaction similarity scores $\\text{sim}_L(q, p)$, after which the final set of ranked passages is returned.\n\t}\n\t\\label{fig:two_tower}\n\\end{figure}\n\n\n%\nIn this work, we propose to append a small parametric module after the information extraction step.\n%\nThis component is designed to \\emph{recover} necessary information from both the question and passage embeddings that will then be compared again for retrieval, thus called \\emph{late interaction}.\n%\n\\fref{fig:two_tower} presents an overview of our proposed method.\n%\nSpecifically, suppose we have a question embedding vector $\\mathbf{v}^{(q)}_{\\texttt{[CLS]}} \\in \\mathbb{R}^d$ and a passage embedding vector $\\mathbf{v}^{(p)}_{\\texttt{[CLS]}} \\in \\mathbb{R}^d$ obtained from the question encoder and passage encoder, respectively, using~\\eqref{eq:dpr_encode}.\n%\nWe then allows simple interactions between the two vectors\n%\n\\begin{equation}\n\\label{eq:late_concat}\n\\mathbf{v}^{(qp)}_{\\texttt{[CLS]}} = [\\mathbf{v}^{(q)}_{\\texttt{[CLS]}}; \\mathbf{v}^{(p)}_{\\texttt{[CLS]}}; \\mathbf{v}^{(q)}_{\\texttt{[CLS]}} \\odot \\mathbf{v}^{(p)}_{\\texttt{[CLS]}}; \\mathbf{v}^{(q)}_{\\texttt{[CLS]}} - \\mathbf{v}^{(p)}_{\\texttt{[CLS]}}] \\in \\mathbb{R}^{4d}\n\\end{equation}\nwhere $[\\cdot;\\cdot]$ denotes vector concatenation and $\\odot$ denotes the Hadamard product, which is a element-wise operation.\n%\nWe obtain $\\mathbf{v}^{(qp)}_{\\texttt{[CLS]}}$, a vector containing information when the question representation is allowed to interact with the passage representation on the feature level via element-wise arithmetic operations.\n%\nThis information-rich vector is then fed through a simple feed-forward (FFN) parametric module to obtain the final similarity score\n\\begin{equation}\n\\label{eq:late_sim}\n\\text{sim}_L(q, p) = \\mathbf{m}_L^\\intercal \\mathbf{v}^{(qp)}_{\\texttt{[CLS]}}  \\in \\mathbb{R}\n\\end{equation}\n%\nwhere $\\mathbf{m}_L \\in \\mathbb{R}^{4d}$ is the weight vector of the FFN.\n\nDuring training, we apply the same negative log-likehood objective function defined in Definition~\\ref{def:nll} to the novel late interaction similarity scores\n%\n\\begin{equation}\nL_L(q_i, p^{+}_i, p^{-}_{i, 1}, p^{-}_{i, 2}, \\ldots, p^{-}_{i, n}) = - \\log \\frac{e^{\\text{sim}_L(q_i, p^{+}_i)}}{e^{\\text{sim}_L(q_i, p^{+}_i)} + \\sum_{j = 1}^{n} e^{\\text{sim}_L(q_i, p^{-}_{i, j})}}\n\\end{equation}\n%\nThe final objective function is then taken as sum of the two individual losses\n\\begin{equation}\nL_{\\text{late\\_interaction}} = L(q_i, p^{+}_i, p^{-}_{i, 1}, p^{-}_{i, 2}, \\ldots, p^{-}_{i, n}) + \\lambda L_L(q_i, p^{+}_i, p^{-}_{i, 1}, p^{-}_{i, 2}, \\ldots, p^{-}_{i, n})\n\\end{equation}\n%\nwhere $\\lambda$ is the weight of the late interaction objective component.\n%\nIn other words, we train the retriever model to minimize the losses with respect to both the usual similarity scores and late-interaction similarity scores, which can also be viewed as a multi-task training paradigm.\n\n%\nAt test time, we use $\\text{sim}(q, p)$ for our retrieval method and $\\text{sim}_L(q, p)$ for our re-ranking method.\n%\nIn particular, given at input query $q$, we first retrieve a set $\\mathcal{C_F}\\prime$ of top-$n$ highest-scoring passages from a pre-built FAISS index as described in~\\sref{sec:dpr_training}, where $n > k$.\n%\nThis means that we retrieve more passages than we need.\n%\nAfterwards, we feed the question feature embeddings $\\mathbf{v}^{(q)}_{\\texttt{[CLS]}}$ as well as the embeddings of each passage in $\\mathcal{C_F}\\prime$ to the late interaction module via~\\eqref{eq:late_concat} and~\\eqref{eq:late_sim} to obtain the late-interaction similarity scores with minimal additional computational cost.\n%\nThese scores are then used to re-rank and filter the passages in $\\mathcal{C_F}\\prime$ to obtain the final set $\\mathcal{C_F}$ of $k$ most relevant passages.\n\n\n\\section{Experimental Results}\n\\label{ch:late_interaction_results}\n\n\n\\begin{table*}[t!]\n\t\\setlength\\tabcolsep{5pt}\n\t\\centering\n\t\\small\n\t\\begin{tabular}{ll|cccc}\n\t\t\\toprule\n\t\t\\textbf{Architecture} & \\textbf{Loss function}\n\t\t& Top-1 & Top-5 & Top-20 & Top-100 \\\\ \n\t\t\\midrule\n\t\t\\multirow{2}{*}{\\shortstack{DPR \\\\(shared encoders)}} &\n\t\tDPR loss & \\textbf{53.02} & \\textbf{71.30} & \\textbf{80.89} & \\textbf{86.93} \\\\\n\t\t& DPR loss + late interaction loss & 51.66 & 69.42 & 79.64 & 86.15 \\\\\n\t\t\\bottomrule\n\t\\end{tabular}\n\t\\caption[Top-$\\{1, 5, 20, 100\\}$ retrieval accuracy on the Natural Questions test set of the DPR retriever (shared encoders) with and without the late interaction module.]{\n\t\t%\n\t\tTop-$\\{1, 5, 20, 100\\}$ retrieval accuracy on the Natural Questions test set of the DPR retriever (shared encoders) with and without the late interaction module, calculated as the percentage of top-$k$ retrieved passages that contain the answer.\n\t\t%\n\t\tThe proposed interaction component degrades the baseline DPR model performance by a sizable margin.\n\t}\n\t\n\t\\label{tab:shared_encoders_results}\n\\end{table*}\n\n\n%\nWe conduct an experiment on NQ following the experimental settings described in~\\sref{sec:exp_setup} with a batch size of 24.\n%\nThe baseline model is taken as the DPR retriever with parameter sharing introduced in~\\cref{ch:shared_encoders}, and the hyperparameters are set to $\\{n, \\lambda\\} = \\{200, 1.0\\}$.\n%\n\\tref{tab:shared_encoders_results} presents the retrieval recall on the NQ test set.\n\n%\nWe observe that the late interaction component brings about a marginal performance loss to the DPR retriever.\n%\nWe believe there are several reasons that make designing a late interaction layer difficult.\n%\nFirst, the proposed interaction layer consists of a small parametric module with weights $\\mathbf{m}_L \\in \\mathbb{R}^{4d}$, which might not be sufficient to fully capture such complex natural language interactions.\n%\nSecond, our interaction layer makes use of only element-wise operations (\\eqref{eq:late_concat}), therefore is incapable of modeling the complex cross-feature interactions between the question embeddings and passage embeddings.\n%\nLastly, it is worth noting that we did not specifically tune the newly introduced hyperparameters $\\{n, \\lambda\\}$ which can have a huge impact on the final model performance.\n%\nNevertheless, a concurrent work of~\\citet{khattab2020colbert} that shares a very similar idea to our proposed late interaction has shown that this mechanism is a valuable addon to the existing retriever to combat the problem of decomposability gap.\n%\nTherefore, we refer interested readers to~\\cite{khattab2020colbert} for a complete work on this idea.\n", "meta": {"hexsha": "68a15c332ed37b559bcad977bf7d1c0c03487290", "size": 7911, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapters/late_interaction.tex", "max_stars_repo_name": "hnt4499/bachelor_thesis", "max_stars_repo_head_hexsha": "6332210e337677840e76dc7b2efbbf90cb5460ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapters/late_interaction.tex", "max_issues_repo_name": "hnt4499/bachelor_thesis", "max_issues_repo_head_hexsha": "6332210e337677840e76dc7b2efbbf90cb5460ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapters/late_interaction.tex", "max_forks_repo_name": "hnt4499/bachelor_thesis", "max_forks_repo_head_hexsha": "6332210e337677840e76dc7b2efbbf90cb5460ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 57.3260869565, "max_line_length": 329, "alphanum_fraction": 0.7416255846, "num_tokens": 2236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.5, "lm_q1q2_score": 0.32567743910088726}}
{"text": "%\\newpage\n\\subsubsection{\\stid{3.13} CLOVER Sub-project SLATE}\\label{subsubsect:slate}\n\n\\paragraph{Overview}\n\nSLATE (Software for Linear Algebra Targeting Exascale)\nprovides fundamental dense linear algebra capabilities\nto DOE and the HPC community at large.\nTo this end, SLATE provides\nparallel basic linear algebra subprograms (BLAS), norms,\nlinear systems solvers, least square solvers,\nsingular value and eigenvalue solvers.\n\nThe ultimate objective of SLATE is to replace the\nvenerable Scalable Linear Algebra PACKage (ScaLAPACK) library,\nwhich has become the industry standard for dense linear algebra operations\nin distributed-memory environments.\nAfter two decades of operation,\nScaLAPACK is past the end of its life cycle and overdue for a replacement,\nas it can hardly be retrofitted to support GPUs,\nwhich are an integral part of today's HPC hardware infrastructure.\n\nPrimarily, SLATE aims to extract the full performance potential and maximum\nscalability from modern HPC machines with large numbers nodes,\nlarge numbers of cores per node, and multiple GPUs per node.\nFor typical dense linear algebra workloads, this means getting close\nto the theoretical roofline peak performance and scaling to the full size of\nthe machine.\nThis is accomplished in a portable manner by relying on standards\nsuch as MPI and OpenMP.\n%\n% SLATE functionalities will first be delivered to the ECP applications\n% that most urgently require SLATE capabilities\n% (NWChem, GAMESS, EXAALT, QMCPACK, CANDLE, etc.)\n% and to other software libraries\n% that rely on underlying dense linear algebra services\n% (STRUMPACK, SuperLU, etc.).\nFigure~\\ref{fig:slate-architecture} shows the role of SLATE\nin the ECP software stack.\n\nWhile the initial objective of SLATE is to serve as a successful,\ndrop-in replacement for ScaLAPACK with support for GPU accelerators,\nthe ultimate goal of SLATE is to deliver dense linear algebra capabilities\nbeyond the capabilities of ScaLAPACK.\nThis includes new features such as communication-avoiding\nalgorithms and randomization algorithms, as well as the potential to\nsupport variable size tiles and block low-rank compressed tiles.\n\n\\begin{figure}[htb]\n    \\centering\n    \\includegraphics[width=0.75\\textwidth]{projects/2.3.3-MathLibs/2.3.3.13-CLOVER/SLATE-architecture.jpg}\n    \\caption{\\label{fig:slate-architecture}\n    SLATE in the ECP software stack.}\n\\end{figure}\n\n\\paragraph{Key  Challenges}\n\n\\begin{enumerate}\n\n\\item\n\\textbf{Designing from the ground up:}\nThe SLATE project's primary challenge stems from the need to design the package\nfrom the ground up, as no existing software package offers\na viable path forward for efficient support of GPUs\nin a distributed-memory environment.\n\n\\item\n\\textbf{Facing harsh hardware realities:}\nSLATE is being developed in a difficult hardware environment, where virtually\nall the processing power is on the GPU side.\nAchieving efficiency requires aggressive offload to GPU accelerators\nand careful optimization of multiple bottlenecks, including\ninterconnect technology lagging behind the computing\ncapabilities of the GPUs.\n\n\\item\n\\textbf{Facing harsh software realities:}\nSLATE is being developed using cutting-edge software technologies,\nand relies on modern C++ features and recent extensions\nto the OpenMP standard, many of which are not fully supported by compilers\nand their runtime environments.\nIn terms of GPU acceleration, standardized solutions are still in flux.\n% Also, while complete parallel programming frameworks exist, at this stage\n% they have to be considered research prototypes.\n\n\\end{enumerate}\n\n\\paragraph{Solution Strategy}\n\n\\begin{enumerate}\n\n\\item\n\\textbf{Evolving design:}\nDue to the inherent challenges of designing a software package\nfrom the ground up, the SLATE project started\nwith a careful analysis of the existing and emerging\nimplementation technologies~\\cite{abdelfattah2017roadmap},\nand followed with a phase\nof laying out the initial design~\\cite{kurzak2017designing}.\nSince then, the team has rolled out new computational routines\nand performance improvements quarterly.\nWhile we continue to refactor as needed to achieve high performance, the basic\ndesign has solidified and been published~\\cite{gates2019slate-design}.\n\n\\item\n\\textbf{Focus on GPUs:}\nEfficient GPU acceleration is the primary focus of performance\nengineering efforts in SLATE.\nWhere applicable, highly optimized vendor implementations of GPU operations\nare used, such as the batched \\texttt{gemm} routine.\nWhere necessary, custom GPU kernels are developed, as in the case of computing\nmatrix norms.\nCare is taken to hide communication by overlapping it with GPU computations.\n\n\\item\n\\textbf{Community engagement:}\nThe SLATE team interacts on a regular basis with the OpenMP community,\nrepresented in ECP by the SOLLVE project, and with the MPI community,\nrepresented in ECP by the OMPI-X project and the Exascale MPI project.\nThe SLATE team also engages the vendor community through our contacts\nat Cray, IBM, Intel, NVIDIA, AMD, and ARM.\n\n\\end{enumerate}\n\n\\paragraph{Recent Progress}\n\nDuring 2020, the SLATE team expanded the Hermitian eigenvalue solver to\nthe generalized Hermitian problem of the forms $Ax = \\lambda Bx$, $ABx =\n\\lambda x$, or $BAx = \\lambda x$. These are of strong interest in\nmechanics and chemistry applications, among others.\n%\nWe also implemented the polar decomposition with the QDWH algorithm,\n%\nwrote a Users' Guide and Developers' Guide to document the public and\ninternal APIs,\n%\nand added native C and Fortran 2003 APIs that access SLATE's native\nmatrix types from outside C++.\n%\nFurther work was done on performance enhancements, with notable gains\nfor BLAS (gemm, herk), norms, Cholesky and QR factorizations.\n%\nA new build system using CMake and Spack has been developed, in\ncollaboration with the NWChemEx project to help include BLAS++ and\nLAPACK++ in their project.\n%\nAll developments are documented in SLATE Working Notes\n\\footnote{\\url{http://www.icl.utk.edu/publications/series/swans}.}\n\n\\paragraph{Next Steps}\n\n\\begin{enumerate}\n\n\\item\n\\textbf{Port to AMD and Intel platforms:}\nOriginally, SLATE was developed using NVIDIA CUDA and cuBLAS. We are now\nabstracting the backend to run on AMD and Intel platforms. BLAS++ will\nserve as a portability layer, with calls to NVIDIA cuBLAS, AMD rocBLAS,\nor Intel oneMKL, as appropriate for the platform. CUDA kernels will be\nported to a combination of HIP, SYCL, and OpenMP offload.\n\n\\item\n\\textbf{Optimizing QR, eigenvalue, and singular value routines:}\nThese are fundamental routines used by many projects.\nWe have observed these routines that are not performing as well as expected.\nIn some cases, such as eigenvalues, we have already identified\nimprovements to be made to the algorithm, such as refactoring loops to improve\nparallelism. In other cases, we will analyze traces to identify and\ncorrect problems.\n\n\\item\n\\textbf{Implementing divide-and-conquer algorithm:}\nFor singular value and Hermitian eigenvalue problems, the divide-and-conquer\nalgorithm exhibits better performance and parallel scalability than the\ntraditional QR-iteration based algorithm currently used in SLATE.\n\n\\item\n\\textbf{Non-symmetric eigenvalue problem:}\nComputing the non-symmetric eigenvalue problem is significantly more\ncomputationally expensive than the Hermitian eigenvalue problem. Our\nimplementation will leverage the latest advances, such as aggressive early\ndeflation, to achieve high performance.\n\n\\end{enumerate}\n", "meta": {"hexsha": "2354026fae84e2abef52a138df0c549ff875221e", "size": 7460, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "projects/2.3.3-MathLibs/2.3.3.13-CLOVER/2.3.3.13-SLATE.tex", "max_stars_repo_name": "gardner48/ECP-ST-CAR-PUBLIC", "max_stars_repo_head_hexsha": "9bc73d1a568569b473063e50d0aca0dac5d410e5", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "projects/2.3.3-MathLibs/2.3.3.13-CLOVER/2.3.3.13-SLATE.tex", "max_issues_repo_name": "gardner48/ECP-ST-CAR-PUBLIC", "max_issues_repo_head_hexsha": "9bc73d1a568569b473063e50d0aca0dac5d410e5", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "projects/2.3.3-MathLibs/2.3.3.13-CLOVER/2.3.3.13-SLATE.tex", "max_forks_repo_name": "gardner48/ECP-ST-CAR-PUBLIC", "max_forks_repo_head_hexsha": "9bc73d1a568569b473063e50d0aca0dac5d410e5", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3243243243, "max_line_length": 106, "alphanum_fraction": 0.8079088472, "num_tokens": 1717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.5, "lm_q1q2_score": 0.32567743910088726}}
{"text": "\\documentclass{notes}\n\n\\title{Discretisation of position and momentum}\n\\author{}\n\n\\usepackage{amssymb}\n\\usepackage{hyperref}\n\\usepackage[\n    backend=biber,\n    sorting=none,\n    style=numeric-comp,\n    citestyle=numeric-comp\n]{biblatex}\n\\addbibresource{ref.bib}\n\n\\newcommand{\\FVM}{\\textsc{Fvm}}\n\\newcommand{\\nRE}{n_{\\rm RE}}\n\\newcommand{\\Vp}{\\mathcal{V}'}\n\\newcommand{\\Jac}{\\mathsf{J}}\n\n\\begin{document}\n    \\maketitle\n\n    \\noindent\n    This document describes the (spatial/momentum) discretisations used in \\DREAM.\n    The overarching scheme used for deriving discretisations is the so-called\n    finite-volume method (FVM).\n\n    \\tableofcontents\n\n    \\section{Grid definition}\n    The most general grid used in \\DREAM\\ consists of three coordinates: one\n    spatial coordinate $x$ and two momentum coordinates, $p_1$ and $p_2$. For\n    a general coordinate $z^{(\\alpha)}$, we introduce $N_\\alpha$ cell grid points and\n    $N_\\alpha+1$ flux grid points and impose the definitions\n    \\begin{equation}\n        \\begin{aligned}\n            \\text{Flux grid:} & \\qquad z^{(\\alpha)}_{\\rm min} = z^{(\\alpha)}_{1/2} < z^{(\\alpha)}_{3/2} < \\ldots < z^{(\\alpha)}_{N_\\alpha+1/2} = z^{(\\alpha)}_{\\rm max},\\\\\n            \\text{Cell grid:} & \\qquad z^{(\\alpha)}_i = \\frac{z^{(\\alpha)}_{i+1/2} + z^{(\\alpha)}_{i-1/2}}{2}, \\quad (1\\leq i \\leq N_\\alpha)\\\\\n            &\\qquad \\Delta z^{(\\alpha)}_i = z^{(\\alpha)}_{i+1/2} - z^{(\\alpha)}_{i-1/2}, \\quad (1\\leq i \\leq N_\\alpha)\\\\\n            &\\qquad \\Delta z^{(\\alpha)}_{i-1/2} = z^{(\\alpha)}_i - z^{(\\alpha)}_{i-1},\\quad (2\\leq i \\leq N_\\alpha).\n        \\end{aligned}\n    \\end{equation}\n\n    \\section{Boundary conditions}\n    This section describes the various boundary conditions used in the code.\n    In momentum space, the internal boundary conditions can be described from\n    the distribution function symmetry relations\n    \\begin{equation}\\label{eq:fsymmetry}\n        \\begin{aligned}\n            f(-p,\\theta) &= f(p,\\pi-\\theta),\\\\\n            f(p,-\\theta) &= f(p,\\theta).\n        \\end{aligned}\n    \\end{equation}\n\n    \\subsection{Boundary conditions on $p/\\xi$ grids}\n    From the first of the symmetry relations~\\eqref{eq:fsymmetry}, we find that\n    that the flux through $p=0$ along a given pitch direction must be equal on\n    both sides, implying that\n    \\begin{equation}\n        \\Phi^{(p)}\\left(p=0^+, \\xi\\right) = \\Phi^{(p)}\\left(p=0^-, -\\xi\\right).\n    \\end{equation}\n\n    From the second of the symmetry relations~\\eqref{eq:fsymmetry}, we\n    immediately find that the fluxes across the $\\xi=\\pm1$ boundaries vanish,\n    i.e.\\\n    \\begin{equation}\\label{eq:bc:xiInternal}\n        \\Phi^{(\\xi)}(p, \\xi=1) = \\Phi^{(\\xi)}(p, \\xi=-1) = 0.\n    \\end{equation}\n\n    For external boundary conditions, we need to consider two cases. In the\n    first case, the region above $p=p_{\\rm max}$ is modelled as a fluid, and we\n    thus only count the radial density $\\nRE$ of runaway electrons. This\n    means that we must count the flux through the $p=p_{\\rm max}$ boundary, so\n    that\n    \\begin{equation}\n        \\frac{\\partial \\nRE}{\\partial t} =\n        \\int_{-1}^1 \\Phi^{(p)}\\left(p_{\\rm max}, \\xi\\right)\\,\\frac{\\Vp(r,p_{\\rm max},\\xi)}{V'(r)}\\,\\dd\\xi.\n    \\end{equation}\n    To evaluate $\\Phi^{(p)}(p_{\\rm max},\\xi)$, which results from a combination\n    of advection and diffusion on the momentum grid, we generally need to know\n    the distribution function $f$ on both sides of $p=p_{\\rm max}$. Since we do\n    not keep track of $f$ above $p=p_{\\rm max}$, we will need handle this in a\n    special way. For the advection term, we simply set the interpolation\n    coefficient $\\delta_{N_p+1} = 0$, so that only the value of $f$ in\n    $p=p_{N_p-1/2}$ is used. This could potentially cause problems with\n    the preservation of positivity, and \\red{we might want to consider other\n    methods in the future.} For the diffusion term, however, no such simple fix\n    exists, and we instead choose to interpolate in the flux:\n    \\begin{equation}\n        \\begin{aligned}\n            \\Phi^{(p)}_{N_p-1/2} &= \\Phi^{(p)}_{N_p+1/2} - \\Delta p_{N_p}\\Phi^{\\prime(p)}_{N_p+1/2},\\\\\n            \\Phi^{(p)}_{N_p-3/2} &= \\Phi^{(p)}_{N_p+1/2} - (\\Delta p_{N_p}+\\Delta p_{N_p-1})\n            \\Phi^{\\prime(p)}_{N_p+1/2},\n        \\end{aligned}\n    \\end{equation}\n    where $\\Phi^{\\prime(p)} = \\partial\\Phi^{(p)}/\\partial p$. Solving for\n    $\\Phi^{(p)}_{N_p+1/2}$ we obtain\n    \\begin{equation}\n        \\Phi^{(p)}_{N_p+1/2} = \\Phi^{(p)}_{N_p-1/2} +\n        \\frac{\\Delta p_{N_p}}{\\Delta p_{N_p-1}} \\left( \\Phi^{(p)}_{N_p-1/2} - \\Phi^{(p)}_{N_p-3/2} \\right).\n    \\end{equation}\n\n    In the second case, when the runaway grid is enabled, we want the flux\n    across the hot-tail $p=p_{\\rm max}$ to enter (or leave) the runaway grid\n    seamlessly. If the hot-tail and runaway grids have the same $\\xi$ grids,\n    this is rather straightforward as we simply set \n    $\\Phi^{(p)}_{\\rm hot}(p_{\\rm max},\\xi) = \\Phi^{(p)}_{\\rm RE}(p_{1/2},\\xi)$.\n    However, in \\DREAM, we allow for the two grids to be different (we only\n    enforce $p^{\\rm RE}_{1/2} = p^{\\rm hot}_{\\rm max}$) and so we must connect\n    the two grids in some way. To conserve particles, we require that the\n\tnumber of particles added to the runaway (RE) grid are also removed from\n\tthe hot-tail grid. Specifically,\n\t\\begin{equation}\\label{eq:fluxCross_origin}\n\t\t\\begin{gathered}\n\t\t\t-\\int \\left[\\nabla\\cdot\\bb{\\Phi}\\right]^{\\rm RE}_{1,J}\\,\\Vp^{\\rm RE}_{1,J}\\dd p\\,\\dd\\xi =\n\t\t\t\\int \\left[\\nabla\\cdot\\bb{\\Phi}\\right]^{\\rm hot}_{N_p,j}\\,\\Vp^{\\rm hot}_{N_p,j}\\dd p\\,\\dd\\xi,\\\\\n\t\t\t\\implies\\\\\n\t\t\t%\n\t\t\t-\\sum\\frac{\\Vp^{\\rm RE}_{1/2,J}\\Phi^{\\rm RE}}{\\Vp^{\\rm RE}_{1,J}\\Delta p^{\\rm RE}_1}\\Vp^{\\rm RE}_{1,J}\\Delta p^{\\rm RE}_1 \\Delta\\xi^{\\rm RE}_J =\n\t\t\t\\sum_j\\frac{\\Vp^{\\rm hot}_{N_p+1/2,j}\\Phi^{\\rm hot}}{\\Vp^{\\rm hot}_{N_p,j}\\Delta p^{\\rm hot}_{N_p}}\\Vp^{\\rm hot}_{N_p,j}\\Delta p^{\\rm hot}_{N_p}\\Delta\\xi^{\\rm hot}_{j}, % \\overline{\\Delta\\xi}_{jJ},\n\t\t\\end{gathered}\n\t\\end{equation}\n    As we will see in section~\\ref{sec:discr:adv:bc}, in \\DREAM\\ we specify the\n    flux of particles on the hot-tail grid, and then enforce the flux on the\n    runaway grid by requiring that the flux into each cell is\n    \\begin{equation}\\label{eq:fluxCross}\n        \\Phi^{\\rm RE}(p_{1/2},\\xi_J) \\Vp^{\\rm RE}_{1/2,J} \\Delta\\xi^{\\rm RE}_J =\n        -\\sum_j \\Phi^{\\rm hot}\\left(p_{\\rm max},\\xi_j\\right) \\Vp^{\\rm hot}_{N_p+1/2,j} \\overline{\\Delta\\xi}_{jJ},\n    \\end{equation}\n\twhere $\\overline{\\Delta\\xi}_{jJ}$ is\n    \\begin{equation}\\label{eq:PhiPinterp}\n        \\overline{\\Delta\\xi}_{jJ} = \\min\\left(\\xi_{J+1/2,{\\rm hot}},\\xi_{j+1/2,{\\rm RE}}\\right) -\n        \\max\\left( \\xi_{J-1/2,{\\rm hot}}, \\xi_{j-1/2,{\\rm RE}} \\right),\n    \\end{equation}\n    so that $\\Delta\\xi_{j,\\rm RE} = \\sum\\overline{\\Delta\\xi}_{jJ}$, and\n\tthe sum is taken over all $j$ such that $\\xi_j\\in[\\xi_{J-1/2}, \\xi_{J+1/2}]$.\n\t%Simplifying equation~\\eqref{eq:fluxCross_origin} we obtain the relation\n    %\\begin{equation}\\label{eq:fluxCross}\n    %    -\\Phi^{\\rm RE}(p_{1/2},\\xi_J)\\Vp^{\\rm RE}_{1/2,J}\\Delta\\xi^{\\rm RE}_{J} =\n    %    \\sum_{j} \\Phi^{\\rm hot}(p_{\\rm max},\\xi_J) \\Vp^{\\rm hot}_{N_p+1/2,j} \\overline{\\Delta\\xi}_{jJ},\n    %\\end{equation}\n\t%which must be satisfied for the particle number to be conserved across the\n\t%two grids.\n\n    \\section{Spatial discretisations}\n    In this section we describe the various discretisations used in \\DREAM. We\n    however begin by describing the general approach taken to discretising\n    equations in the code.\n\n    \\subsection{Finite volume method}\n    In order to achieve mass conservation, we use the finite-volume method to\n    discretise our equations and consider the fluxes between cells on the\n    computational grid. For a general flux-conservative term\n    $\\nabla\\cdot\\bb{\\Phi}$, we take the matrix row corresponding to element\n    $i_1\\cdots i_D$ ($D$ being the problem dimensionality) of the unknown\n    quantity to be\n    \\begin{equation}\n        \\left[ \\nabla\\cdot\\bb{\\Phi} \\right]_{i_1\\cdots i_D}  =\n            \\frac{1}{\\Vp_{i_1\\cdots i_D}}\\sum_\\beta \\frac{\n                \\Phi^{(\\beta)}_{i_\\beta+1/2} \\Vp_{i_\\beta+1/2} -\n                \\Phi^{(\\beta)}_{i_\\beta-1/2} \\Vp_{i_\\beta-1/2}\n            }{\\Delta z^{(\\beta)}_{i_\\beta}},\n    \\end{equation}\n    where $\\Vp$ denotes the phase space Jacobian, Greek indices denote the\n    coordinate (i.e.\\ $z_\\alpha, z_\\beta, \\ldots$), Latin indices denote grid\n    points and the matrix indices which are not shifted have been suppressed for\n    clarity (i.e.\\\n    $\\Phi^{(\\beta)}_{i_\\beta+1/2}\\equiv\\Phi^{(\\beta)}_{i_1\\cdots i_\\beta+1/2\\cdots i_D}$).\n\n    \\subsection{Advection term}\\label{sec:advection}\n    A general advection term can be written on the form\n    \\begin{equation*}\n        \\nabla\\cdot\\left( \\bb{F} f \\right),\n    \\end{equation*}\n    with $\\bb{F} = \\zhat^{(\\alpha)}F^{(\\alpha)} + \\zhat^{(\\beta)}F^{(\\beta)}+\\ldots$\n    denoting the advection coefficient and $f$ the distribution function. For\n    momentum-space friction, we discretise such terms according to\n    \\begin{equation}\\label{eq:advection:discr}\n        \\left[\\nabla\\cdot\\left( \\bb{F}f \\right) \\right]_{i_1\\cdots i_D} =\n            \\frac{1}{\\Vp_{i_1\\cdots i_D}}\\sum_\\beta \\frac{\n                F^{(\\beta)}_{i_\\beta+1/2}f_{i_\\beta+1/2} \\Vp_{i_\\beta+1/2} -\n                F^{(\\beta)}_{i_\\beta-1/2}f_{i_\\beta-1/2} \\Vp_{i_\\beta-1/2}\n            }{\\Delta z^{(\\beta)}_{i_\\beta}},\n    \\end{equation}\n    Since the distribution function is only known on the cell grid, but is here\n    required on the flux grid, we must interpolate. We may interpolate linearly in\n    $f$ according to\n    \\begin{equation}\n        f_{i_\\beta-1/2} = \\delta^{(\\beta)}_{i_\\beta} f_{i_\\beta} + \\left( 1 - \\delta^{(\\beta)}_{i_\\beta} \\right) f_{i_\\beta-1},\n    \\end{equation}\n    where the interpolation coefficients $\\delta^{(\\beta)}_{i_\\beta}$ are\n    determined with the help of any of the methods described in\n    section~\\ref{sec:interp}. (Note that unnecessary indices have been\n    suppressed, so that really\n    $\\delta^{(\\beta)}_{i_\\beta} = \\delta^{(\\beta)}_{i_1\\cdots i_\\beta\\cdots i_D}$).\n    \n    DREAM more generally supports interpolation via a general 4-point stencil according to\n    \\begin{equation}\n        f_{i_\\beta-1/2} = \\sum_{k=0}^3 \\delta^{(\\beta)}_{i_\\beta,k} f_{i_\\beta-2+k}.\n    \\end{equation}\n    \n\n    \\subsubsection{Boundary conditions on $p/\\xi$ grid}\\label{sec:discr:adv:bc}\n    Internal boundary conditions at $p=p_{1/2}$ must be specified explicitly.\n    They must then be inserted appropriately into~\\eqref{eq:advection:discr} so\n    that\n    \\begin{equation}\n        \\left[ \\nabla\\cdot\\left( \\bb{F}f \\right) \\right]_{1,j} = \\frac{\n            \\Vp_{3/2} F_{3/2}^{(p)} f_{3/2} - \\Vp_{1/2}\\Phi^{(p)}_{1/2}\n        }{\\Delta p_{1}}\n    \\end{equation}\n    where $\\Phi_{1/2}^{(p)}$ is the phase space particle flux into or out of\n    the inner boundary. At $\\xi=\\xi_{1/2}$ and $\\xi=\\xi_{N_\\xi+1/2}$, however,\n    we use the result~\\eqref{eq:bc:xiInternal} and obtain (for the $\\xi$ term)\n    \\begin{equation}\n        \\begin{aligned}\n            \\left[ \\nabla\\cdot\\left( \\bb{F} f \\right) \\right]_{i,1} &=\n                \\frac{\\Vp_{3/2} F^{(\\xi)}_{i,3/2} f_{i,3/2}}{\\Delta\\xi_{1}},\\\\\n            %\n            \\left[ \\nabla\\cdot\\left( \\bb{F} f \\right) \\right]_{i,N_\\xi} &=\n                -\\frac{\\Vp_{N_\\xi-1/2} F^{(\\xi)}_{i,N_\\xi-1/2} f_{i,N_\\xi-1/2}}{\\Delta\\xi_{N_\\xi}}.\n        \\end{aligned}\n    \\end{equation}\n\n    \\paragraph{Combining kinetic grids}\n    When combining the hot-tail and runaway grids, we want the particles to flow\n    seamlessly from one grid to another across their shared boundary. This is\n    not automatically guaranteed, since the hot-tail and runaway grids need not\n    have the same resolutions and so cell may overlap arbitrarily. The only\n    property we can be certain that the grids satisfy is that\n    $p_{N_p+1/2}^{\\rm hot} = p_{1/2}^{\\rm RE}$. To achieve a seamless flow of\n    particles between the grids, we first write out the discretized forms of the\n    boundary fluxes on each grid:\n    \\begin{equation}\\label{eq:crossCondition}\n        \\begin{aligned}\n            \\left[ \\nabla\\cdot\\left( \\bb{F}f \\right)\\right]^{\\rm hot}_{N_p,j} &=\n                \\frac{\\Vp^{\\rm hot}_{N_p+1/2}\\Phi^{\\rm hot}_j - \\Vp_{N_p-1/2} F_{N_p-1/2}f_{N_p-1/2}}{\\Delta p^{\\rm hot}_{N_p}},\\\\\n            \\left[ \\nabla\\cdot\\left( \\bb{F}f \\right)\\right]^{\\rm RE}_{1,J} &=\n                \\frac{\\Vp^{\\rm RE}_{3/2} F^{(p)}_{3/2} f_{3/2,J} - \\Vp^{\\rm RE}_{1/2}\\Phi^{\\rm RE}_J}{\\Delta p^{\\rm RE}_1},\n        \\end{aligned}\n    \\end{equation}\n    where $\\Phi^{\\rm hot}$ and $\\Phi^{\\rm RE}$ denote the fluxes into the\n    hot-tail and runaway grids respectively. According to the usual recipe used\n    in a finite volume discretization, the hot-tail flux $\\Phi^{\\rm hot}_j$\n    should be given by\n    \\begin{equation}\n        \\Phi^{\\rm hot}_j = F_{N_p+1/2,j}^{\\rm hot} f_{N_p+1/2,j}^{\\rm hot}.\n    \\end{equation}\n    However, the hot-tail distribution is only known in integer grid points with\n    $i\\leq N_p$, and so to evaluate $f_{N_p+1/2,j}^{\\rm hot}$ we must\n    interpolate. In contrast to the usual situation, we however have two\n    different distribution functions on each side of the cell face on which the\n    flux is to be evaluated. We therefore write the flux grid distribution as\n    \\begin{equation}\n        f_{N_p+1/2,j}^{\\rm hot} = \\delta^{(1)}_{j}f_{N_p,j} +\n            \\left( 1-\\delta^{(1)}_{j} \\right) \\hat{f}^{\\rm RE}_j,\n    \\end{equation}\n    where $\\delta^{(1)}$ is an interpolation coefficient (to be determined)\n    and $\\hat{f}^{\\rm RE}_j$ is a function of the RE distribution function in\n    the cells adjacent to cell $j$ on the hot-tail grid. Various possibilities\n    for choosing $\\hat{f}^{\\rm RE}_j$ can be foreseen, but here we decide to\n    use the rather straightforward\n    \\begin{equation}\n        \\hat{f}^{\\rm RE}_j = \\delta^{(2)}_j f^{\\rm RE}_{J_j} +\n            \\left( 1 - \\delta^{(2)}_j \\right) f^{\\rm RE}_{J_j-1},\n    \\end{equation}\n    where $\\delta^{(2)}_j$ is an interpolation coefficient and $J_j$ is the\n    first $J$ such that $\\xi^{\\rm RE}_{J_j}\\geq\\xi^{\\rm hot}_j$ (if $J_j=1$,\n    (index 0 in C++) we set $\\delta^{(2)}_j = 1$). With this form for the\n    runaway distribution function, we obtain the flux grid distribution value\n    \\begin{equation}\n        f^{\\rm hot}_{N_p+1/2,j} = \\delta^{(1)}_j f_j^{\\rm hot} +\n            \\left( 1 - \\delta^{(1)}_j \\right)\\left[\n                \\delta^{(2)}_j f_{J_j}^{\\rm RE} +\n                \\left( 1-\\delta^{(2)}_{J_j} \\right) f_{J_j-1}^{\\rm RE}\n            \\right].\n    \\end{equation}\n    Next, we must choose the interpolation coefficients $\\delta^{(1)}_j$ and\n    $\\delta^{(2)}_j$. For any type of advection, a desirable property of the\n    interpolation coefficients is to preserve the monotonicity of the\n    distribution function. Unfortunately it would be rather difficult to use\n    the general flux limiter scheme otherwise available in \\DREAM, but to still\n    have some protection against oscillations we use an up-wind interpolation\n    scheme:\n    \\begin{equation}\n        \\delta^{(1)}_j = \\begin{cases}\n            1, \\quad&\\text{if } F_{N_p+1/2}^{\\rm hot} \\leq 0,\\\\\n            0, \\quad&\\text{otherwise}.\n        \\end{cases}\n    \\end{equation}\n    For the second interpolation coefficient, we use a linear interpolation in\n    $\\xi$. This is known to generally be prone to oscillations for pure\n    advection problems, but in our situation the problem may be significantly\n    helped by the pitch-angle diffusion present which can often be stronger\n    than the $\\xi$-component of the electric field in the region of interest\n    (near $\\xi\\sim1$):\n    \\begin{equation}\n        \\begin{gathered}\n            \\hat{f}^{\\rm RE}_j = f^{\\rm RE}_{J_j} +\n                \\left( \\xi^{\\rm hot}_j - \\xi^{\\rm RE}_{J_j-1} \\right)\n                \\frac{f_{J_j}^{\\rm RE} - f_{J_j-1}^{\\rm RE}}\n                {\\xi^{\\rm RE}_{J_j} - \\xi^{\\rm RE}_{J_j-1}} \\implies\\\\\n                %\n                \\delta^{(2)}_j = \\frac{\\xi^{\\rm hot}_j - \\xi^{\\rm RE}_{J_j-1}}\n                {\\xi^{\\rm RE}_{J_j} - \\xi^{\\rm RE}_{J_j-1}}.\n        \\end{gathered}\n    \\end{equation}\n    Again, when $J_j=1$ (index 0 in C++), we let $\\delta^{(2)}_j = 1$.\n\n    For the flux on the runaway grid, we use equation~\\eqref{eq:fluxCross}\n    directly to ensure the conservation of density.\n\n    \\subsubsection{Boundary conditions on $p_\\parallel / p_\\perp$ grid}\n    \\emph{To be written...}\n\n    \\subsection{Diffusion term}\\label{sec:diffusion}\n    A general diffusion term can be written on the form\n    \\begin{equation*}\n        \\nabla\\cdot\\left( \\mathbb{D}\\cdot\\nabla f \\right),\n    \\end{equation*}\n    where $\\mathbb{D}$ is the diffusion tensor\n    \\begin{equation*}\n        \\mathbb{D} = \\begin{pmatrix}\n            D_{rr} & D_{r1} & D_{r2} \\\\\n            D_{1r} & D_{11} & D_{12} \\\\\n            D_{2r} & D_{21} & D_{22}\n        \\end{pmatrix}.\n    \\end{equation*}\n    In \\DREAM, we neglect the radial cross-terms, i.e.\\\n    $D_{r1} = D_{1r} = D_{r2} = D_{2r} = 0$.\n\n    For the diffusion term, we will need to approximate derivatives of the\n    distribution function $f$. For the diagonal terms (i.e.\\ the $D_{rr}$,\n    $D_{11}$ and $D_{22}$ terms), this is straightforward: since the derivatives\n    should be evaluated on the flux grid, we can use a basic central difference\n    approximation:\n    \\begin{align}\n        \\left.\\frac{\\partial f}{\\partial r}\\right|_{k-1/2,i,j} &=\n            \\frac{f_{k,i,j} - f_{k-1,i,j}}{\\Delta r_{k-1/2}},\\\\\n        %\n        \\left.\\frac{\\partial f}{\\partial p_1}\\right|_{k,i-1/2,j} &=\n            \\frac{f_{k,i,j} - f_{k,i-1,j}}{\\Delta p_{1; i-1/2}},\\\\\n        %\n        \\left.\\frac{\\partial f}{\\partial p_2}\\right|_{k,i,j-1/2} &=\n            \\frac{f_{k,i,j} - f_{k,i,j-1}}{\\Delta p_{2; j-1/2}},\\\\\n    \\end{align}\n    Since no interpolation in $f$ is needed, these terms automatically preserve\n    the positivity of the solution.\n\n    The cross terms cause some problems with preservation of positivity.\n    Unfortunately we cannot use the same interpolation scheme as for the\n    advection term. To easily support the use of diffusion cross terms, we\n    therefore use simple cell averaging, which does \\emph{not} preserve\n    positivity. We write the derivatives as\n    \\begin{equation}\n        \\begin{aligned}\n            \\left.\\frac{\\partial f}{\\partial p_1}\\right|_{k,i,j-1/2} &=\n                \\frac{f_{i+1,j} + f_{i+1,j-1} - f_{i-1,j} - f_{i-1,j-1}}\n                {\\Delta p_{1;i+1/2} + \\Delta p_{1;i-1/2}},\\\\\n            %\n            \\left.\\frac{\\partial f}{\\partial p_2}\\right|_{k,i-1/2,j} &=\n                \\frac{f_{i,j+1} + f_{i-1,j+1} - f_{i,j-1} - f_{i-1,j-1}}\n                {\\Delta p_{2;j+1/2} + \\Delta p_{2;j-1/2}}.\n        \\end{aligned}\n    \\end{equation}\n    If we would like to also preserve positivity, we should instead use the\n    approach taken by refs.~\\cite{DuToit2018,Daniel2019}. They rewrite the\n    diffusion cross terms as advection terms, which allows us to use the same\n    methods as in section~\\ref{sec:advection}. The ``advection form'' for the\n    diffusion cross terms is\n    \\begin{equation}\n        \\begin{aligned}\n            \\left[ D_{12}\\frac{\\partial f}{\\partial p_2} \\right] &=\n                \\frac{\\partial (\\ln f)}{\\partial p_2}D_{12} f = \\tilde{D}_{12} f,\\\\\n            %\n            \\left[ D_{21}\\frac{\\partial f}{\\partial p_1} \\right] &=\n                \\frac{\\partial (\\ln f)}{\\partial p_1}D_{21} f = \\tilde{D}_{21} f,\n        \\end{aligned}\n    \\end{equation}\n    where we have introduced the modified diffusion coefficients\n    $\\tilde{D}_{12}\\equiv D_{12}\\partial(\\ln f)/\\partial p_2$ and\n    $\\tilde{D}_{21}\\equiv D_{21}\\partial(\\ln f)/\\partial p_1$. These modified\n    diffusion coefficients depend on (non-linearly) on the unknown, and hence\n    they require a non-linear solver. We choose not to implement this form of\n    the diffusion coefficients directly in the \\DREAM/\\FVM\\ library, but instead\n    refer to the physicist to rewriting her equations according to the above\n    and implement them using the advection term class instead.\n\n    \\paragraph{Full discretisation}\n    Within the framework of the finite-volume method, we discretise the general\n    diffusion term as\n    \\begin{equation}\n        \\begin{aligned}\n            \\left[ \\nabla\\cdot\\left( \\mathbb{D}\\cdot\\nabla f \\right) \\right]_{kij} &=\n                \\frac{1}{\\Vp_{i_1\\cdots i_D}}\\Bigg[\\\\\n                %\n                &\\frac{1}{\\Delta r_k}\\left(\n                    \\Vp_{k+1/2}D_{rr;k+1/2}\\frac{f_{k+1,i,j}-f_{k,i,j}}{\\Delta r_{k+1/2}} -\n                    \\Vp_{k-1/2}D_{rr;k-1/2}\\frac{f_{k,i,j}-f_{k-1,i,j}}{\\Delta r_{k-1/2}}\n                \\right) +\\\\\n                %\n                &+ \\frac{1}{\\Delta p_{1;i}} \\left(\n                    \\Vp_{i+1/2}D_{11;i+1/2}\\frac{f_{k,i+1,j} - f_{k,i,j}}{\\Delta p_{1;i+1/2}} -\n                    \\Vp_{i-1/2}D_{11;i-1/2}\\frac{f_{k,i,j} - f_{k,i-1,j}}{\\Delta p_{1;i-1/2}}\n                \\right) +\\\\\n                %\n                &+ \\frac{1}{\\Delta p_{2;i}} \\left(\n                    \\Vp_{j+1/2}D_{22;j+1/2}\\frac{f_{k,i,j+1} - f_{k,i,j}}{\\Delta p_{2;j+1/2}} -\n                    \\Vp_{j-1/2}D_{22;j-1/2}\\frac{f_{k,i,j} - f_{k,i,j-1}}{\\Delta p_{2;j-1/2}}\n                \\right) +\\\\\n                %\n                &+ \\Vp_{i+1/2}D_{12;i+1/2}\\frac{\n                    f_{k,i+1,j+1} + f_{k,i,j+1} - f_{k,i+1,j-1} - f_{k,i,j-1}\n                }{\\Delta p_{1;i}\\left(\\Delta p_{2;j+1/2} + \\Delta p_{2;j-1/2} \\right)} -\\\\\n                &- \\Vp_{i-1/2}D_{12;i-1/2}\\frac{\n                    f_{k,i,j+1} + f_{k,i-1,j+1} - f_{k,i,j-1} - f_{k,i-1,j-1}\n                }{\\Delta p_{1;i}\\left(\\Delta p_{2;j+1/2} + \\Delta p_{2;j-1/2} \\right)} +\\\\\n                %\n                &+ \\Vp_{j+1/2}D_{21;j+1/2}\\frac{\n                    f_{k,i+1,j+1} + f_{k,i+1,j} - f_{k,i-1,j+1} - f_{k,i-1,j}\n                }{\\Delta p_{2;j}\\left(\\Delta p_{1;i+1/2} + \\Delta p_{1;i-1/2} \\right)} -\\\\\n                &- \\Vp_{j-1/2}D_{21;j-1/2}\\frac{\n                    f_{k,i+1,j} + f_{k,i+1,j-1} - f_{k,i-1,j} - f_{k,i-1,j-1}\n                }{\\Delta p_{2;j}\\left(\\Delta p_{1;i+1/2} + \\Delta p_{1;i-1/2} \\right)}\\\\\n            &\\Bigg].\n        \\end{aligned}\n    \\end{equation}\n\n\t\\subsubsection{Boundary conditions on $p/\\xi$ grid}\n\n    \\paragraph{On combined kinetic grids}\n    When combining hot-tail and runaway grids, we use a similar discretization\n    for the diffusion flux as for the advection flux described above. With the\n    same choice for $\\hat{f}^{\\rm RE}_j$ as above we have\n    \\begin{equation}\n        \\left.\\frac{\\partial f^{\\rm hot}}{\\partial p}\\right|_{N_p+1/2,j} =\n            \\frac{f^{\\rm hot}_j - \\delta^{(2)}_j f_{J_j}^{\\rm RE} -\n            \\left( 1 - \\delta^{(2)}_j \\right) f^{\\rm RE}_{J_j-1}}\n            {p^{\\rm RE}_{1/2} - p^{\\rm hot}_{N_p+1/2}}.\n    \\end{equation}\n\n    \\subsection{Calculation of jacobian}\n    The jacobian matrix is used with Newton's method to solve a non-linear set\n    of equations. Each element of the matrix corresponds to a derivative of an\n    unknown quantity, with respect to another unknown quantity, and the matrix\n    has the structure\n    \\begin{equation}\n        \\Jac = \\frac{\\partial F_i}{\\partial x_j} = \\begin{pmatrix}\n            \\frac{\\partial F_1}{\\partial x_1} & \\frac{\\partial F_1}{\\partial x_2} & \\cdots & \\frac{\\partial F_1}{\\partial x_n}\\\\\n            \\frac{\\partial F_2}{\\partial x_1} & & \\cdots & \\\\\n            \\vdots & \\ddots & & \\frac{\\partial F_n}{\\partial x_n} \\\\\n        \\end{pmatrix},\n    \\end{equation}\n    where $x_i$ denotes an unknown quantity of the {\\em discretized} system of\n    equations and $F_i$ the non-linear function for which a zero is sought.\n\n    For the advection terms described above, we have\n    \\begin{equation}\\label{eq:advjac}\n        \\frac{\\partial}{\\partial x_i}\\left( \\left[ \\nabla\\cdot\\left(\\bb{F} f\\right) \\right] \\right) =\n        \\frac{1}{\\Vp_{i_1\\cdots i_D}}\\sum_\\beta \\frac{\\partial}{\\partial x_i}\\left(\\frac{\n            F^{(\\beta)}_{i_\\beta+1/2}f_{i_\\beta+1/2} \\Vp_{i_\\beta+1/2} -\n            F^{(\\beta)}_{i_\\beta-1/2}f_{i_\\beta-1/2} \\Vp_{i_\\beta-1/2}\n        }{\\Delta z^{(\\beta)}_{i_\\beta}}\\right).\n    \\end{equation}\n    Since the phase space jacobians $\\Vp$ and coordinates $z_{i_\\beta}$ are\n    independent of all unknowns $x_i$, the partial derivative will only affect\n    $f$ and the advection coefficient. For a single term, we have according to\n    the product rule\n    \\begin{equation}\\label{eq:advjacderiv}\n        \\frac{\\partial}{\\partial x_i}\\left( F^{(\\beta)}_{i_\\beta+1/2} f_{i_\\beta+1/2} \\right) =\n        F^{(\\beta)}_{i_\\beta+1/2}\\frac{\\partial f_{i_\\beta+1/2}}{\\partial x_i} +\n        \\frac{\\partial F^{(\\beta)}_{i_\\beta+1/2}}{\\partial x_i} f_{i_\\beta+1/2}.\n    \\end{equation}\n    Since we assume all unknown to be independent, the first term vanishes\n    identically for all $x_i\\neq f_{i_\\beta+1/2}$ and becomes unity otherwise,\n    while the second term appears as a new advective flow with coefficient\n    $\\partial_i F^{(\\beta)}_{i_\\beta+1/2}\\equiv \\partial F^{(\\beta)}_{i_\\beta+1/2}/\\partial x_i$.\n    In practice, this allows for a convenient way of setting elements of the\n    jacobian matrix, by reusing the code already written for setting elements of\n    the linear operator matrix and the residual vector.\n\n    The first term in~\\eqref{eq:advjacderiv} (which is $F^{(\\beta)}_{i_\\beta+1/2}$\n    for $x_i=f_{i_\\beta+1/2}$, and zero otherwise) will give rise to a block\n    along the main diagonal with exactly the same structure as in the linear\n    operator matrix. In fact, this block of the jacobian matrix will be\n    identical to the corresponding block of the linear operator matrix since\n    it represents the discretized advection operator {\\em without} the unknown\n    distribution function.\n\n    The second term has the structure of a regular advection term, but with\n    $\\partial_i F^{(\\beta)}_{i_\\beta+1/2}$ acting as the advection coefficient\n    instead. For a given element of the jacobian matrix, in the column\n    corresponding to a derivative with respect to $x_i$, we should therefore\n    evaluate the sum in~\\eqref{eq:advjac} with $\\partial_i F^{(\\beta)}_{i_\\beta+1/2}$\n    as the advection coefficient. But this is almost exactly what we do when\n    evaluating the residual, save for that we then use the regular advection\n    coefficients.\n\n    The jacobian matrix for an advection operator (and for a diffusion operator)\n    can therefore be built by first calling the \\texttt{SetMatrixElements()} on\n    the main diagonal block, and then iterating through all derivatives and\n    adding in the result of \\texttt{SetVectorElements()} in every column.\n\n    \\section{Interpolating in distribution function}\\label{sec:interp}\n    In advection terms, as well as diffusion cross terms, we must evaluate the\n    distribution function on the flux grid. Since the distribution function is\n    only explicitly computed on the cell grid, this means that we must\n    interpolate in the distribution function. A simple scheme is provided by \n    linear interpolation, for which one can generally write\n    \\begin{equation}\n        f_{i-1/2} = \\delta_{i} f_i + \\left( 1 - \\delta_i \\right) f_{i-1}.\n    \\end{equation}\n    In the simplest approach with uniform grids, we take $\\delta_i\\equiv 1/2$, making $f_{i-1/2}$\n    a simple average of the value of $f$ in the adjacent cells. While simple and\n    often accurate enough, other schemes for choosing $\\delta_i$ can provide\n    better stability and even desirable physical properties such as preservation\n    of positivity. These schemes are referred to as ``flux limiter schemes'',\n    and we also provide those in the code.\n    \n    For additional flexibility and accuracy, we consider general 4-point stencils of the form\n    \\begin{equation}\n    \tf_{i-1/2} = \\sum_{k=-2}^1 \\delta^{(i)}_k f_{i+k}.\n    \\end{equation}\n    In order to improve numerical stability and reduce oscillations, schemes with \n    upwind bias are advantageous where $\\delta_{1}$ vanishes for positive \n    advection coefficients, and $\\delta_{-2}$ for negative advection. In what follows,\n    we will assume a positive advection coeffient $A_{i-1/2}>0$. For the $A_{i-1/2}<0$ \n    case, all interpolation coefficients will be mirrored, and can be obtained with the \n    mapping $k \\mapsto -1 - k$.\n    \n    A general second-order accurate scheme can be generated from the so-called\n    $\\kappa$ schemes (given here for uniform grids, but are implemented more generally):\n    \\begin{align*}\n    \\delta_{-2} &= -\\frac{1-\\kappa}{4}, \\nonumber \\\\\n    \\delta_{-1} &= 1 - \\frac{\\kappa}{2}, \\nonumber \\\\\n    \\delta_0 &= \\frac{1+\\kappa}{4}, \\nonumber \\\\\n    \\delta_1 &= 0.\n    \\end{align*}\n    Here, $\\kappa = 1$ corresponds to the linear interpolation (central difference) \n    scheme described above; since it has no upwind bias, it is less stable than other \n    $\\kappa$ schemes. A common choice is $\\kappa=0.5$ which yields the QUICK \n    scheme (which is the only choice of $\\kappa$ that also gives third-order accuracy) \n    or $\\kappa=-1$ which yields a purely upwind linear-extrapolation scheme (Second-order upwind).\n\n    \\subsection{Flux limiter schemes}\n    The previous scheme, which is classified as linear since the interpolation \n    coefficients $\\delta_k$ are independent of the solution, can be generalised to a \n    useful class of non-linear \\emph{flux-limiter schemes}, which are given by\n    (again specialising to uniform grids for compactness)\n    \\begin{align}\n    \\delta^{(i)}_{-2} &= -\\frac{\\psi(r^{(i)})}{2}, \\nonumber \\\\\n    \\delta^{(i)}_{-1} &= 1 + \\frac{\\psi(r^{(i)})}{2}, \\nonumber \\\\\n    \\delta^{(i)}_{0} &= 0, \\nonumber \\\\\n    \\delta^{(i)}_{1} &= 0, \\nonumber \\\\\n    r^{(i)} &= \\frac{f_i - f_{i-1}}{f_{i-1}-f_{i-2}}.\n    \\end{align}\n    Via the function $\\psi(r)$, the interpolation coefficients depend non-linearly on \n    the distribution $f$. Although it is not explicitly written on that form, the linear $\\kappa$ schemes \n    are exactly retrieved with $\\psi(r) = (1+\\kappa)r/2 + (1-\\kappa)/2$ (by comparing the net $f_{i-1/2}$ \n    obtained after interpolating). It can be shown that positivity preservation (or the more strict condition \n    of \\emph{boundedness}, where $f_{i-1} \\leq f_{i-1/2} \\leq f_i$)\n    will be satisfied by letting $\\psi$ obey certain constraints.\n    \n    Three flux limiters that are implemented in DREAM are:\n    \\begin{align}\n    \\psi(r) &= \\text{max}(0,\\,\\text{min}(2r,\\,(1+3r)/4,\\,4)), && \\text{(SMART)} \\nonumber \\\\\n    \\psi(r) &= \\text{max}(0,\\,\\text{min}(2r,\\,(1+r)/2,\\,2)), && \\text{(MUSCL)} \\nonumber \\\\\n    \\psi(r) &= \\frac{3}{2}\\frac{r(1+r)}{r^2+r+1}. && \\text{(OSPRE)}\n    \\end{align}\n    For Dreicer generation, all three flux limiters give comparable accuracy, but OSPRE is the \n    more robust one thanks to its continuous form. \n    In some situations, convergence of the piece-wise flux limiters may be accelerated (or restored)\n    by under-relaxing the algorithm, which we do by updating\n    \\begin{align}\n    \\delta = \\delta_\\text{prev} + \\eta [\\delta_\\text{calc} - \\delta_\\text{prev}],\n    \\end{align}\n    where $\\eta \\in [0,1]$ is a damping factor, $\\delta_\\text{calc}$ the interpolation coefficient\n    according to the scheme chosen and $\\delta_\\text{prev}$ the coefficient in the previous iteration \n    of the non-linear solver. Sometimes a value of $\\eta \\approx 0.9$ is sufficient -- too low\n    values can prevent convergence altogether.\n    \n    The accuracy of the interpolation schemes are compared in figure \\ref{fig:advection interpolation convergence}.\n    The first-order upwind scheme is outside of view as it significantly overpredicts the generation. Computation times \n    are not indicated, but the linear 2-point stencils Centered and UPWIND are fastest, then the linear 3-point stencils \n    QUICK and second-order upwind (UPWIND-2), and finally the flux limiters which are all significantly slower since \n    they require the non-linear solver to be used.\n    \n    \\begin{figure}\n    \\begin{center}\n    \\includegraphics[width=1.0\\textwidth,trim=25mm 0 25mm 0]{advection_interpolation_convergence}\n    \\caption{\\label{fig:advection interpolation convergence} Runaway rate $\\partial n_\\mathrm{RE}/\\partial t$ in \n    a basic Dreicer runaway scenario with parameters: $n_e = 5\\times 10^{19}\\,$m$^{-3}$, $T_e = 100\\,$eV, $Z=1$, \n    $E=6.74546\\,$V/m, run for $t_\\mathrm{max}=1$\\,ms in 10 time steps, with a grid extending to \n    $p_\\mathrm{max} = 2m_e c$ with boundary condition $f(p_\\mathrm{max})=0$ .}\n    \\end{center}\n    \\end{figure}\n    \\section{Solution of non-linear system}\n    The set of equations we aim to solve can generally be formulated as the\n    root-finding problem,\n    \\begin{equation}\\label{eq:nonlinear}\n        \\bb{F}(\\bb{x}) = 0,\n    \\end{equation}\n    where $\\bb{F}$ represents the physical equations to solve. A number of\n    approaches could be imagined for solving this equation, and in this section\n    we will review those implemented in \\DREAM.\n\n    \\subsection{Linearly implicit solution}\n    The linearly implicit solution method relies on the slow time evolution of\n    the system in question. Let us assume that $\\bb{F}$ may be decomposed into\n    \\begin{equation}\n        \\bb{F}\\left( \\bb{x} \\right) = M\\left( \\bb{x} \\right) \\bb{x} + S\\left( \\bb{x} \\right)\n    \\end{equation}\n    where $M$ takes the form of a linear operator which may depend non-linearly\n    on $\\bb{x}$, and $S$ takes the form of a source term. In a linearly implicit\n    scheme, one assumes that $M$ and $S$ depend weakly on $\\bb{x}$, thus\n    justifying the approximation\n    \\begin{equation}\n        \\bb{F}\\left( \\bb{x}_{n+1} \\right)\\approx M\\left( \\bb{x}_n\\right) \\bb{x}_{n+1}\n        + S\\left( \\bb{x}_n \\right).\n    \\end{equation}\n    In this approximation, equation~\\eqref{eq:nonlinear} may be solved by\n    inverting the matrix $M$:\n    \\begin{equation}\n        \\bb{x}_{n+1} = M^{-1}\\left(\\bb{x}_n\\right) S\\left(\\bb{x}_n\\right).\n    \\end{equation}\n    In contrast to the more accurate Newton method, the linearly implicit scheme\n    requires no iteration, and thus only one matrix inversion. This can make the\n    scheme beneficial for evolving systems which vary slowly in time.\n    \n    \\subsection{Newton's method}\n    The more general \\emph{Newton's method} is obtained by Taylor expanding\n    equation~\\eqref{eq:nonlinear} around $\\bb{x}^{(k+1)} = \\bb{x}^{(k)} + \\Delta\\bb{x}$:\n    \\begin{equation}\n        \\bb{F}\\left( \\bb{x}^{(k+1)} \\right)\\approx \\bb{F}\\left(\\bb{x}^{(k)}\\right) +\n        \\Jac\\left(\\bb{x}^{(k)}\\right) \\left( \\bb{x}^{(k+1)} - \\bb{x}^{(k)} \\right) = 0.\n    \\end{equation}\n    Here, $\\Jac(\\bb{x}^{(k)}) = \\partial\\bb{F}(\\bb{x}^{(k)})/\\partial\\bb{x}$\n    denotes the Jacobian matrix of $\\bb{F}$. Solving for $\\bb{x}^{(k+1)}$, we\n    obtain the iterative scheme\n    \\begin{equation}\n        \\bb{x}^{(k+1)} = \\bb{x}^{(k)} - \\Jac^{-1}\\left( \\bb{x}^{(k)} \\right) \\bb{F}\\left( \\bb{x}^{(k)} \\right),\n    \\end{equation}\n    which hopefully converges to the true zero of $\\bb{F}$. Here, we thus rely\n    on a series of iterations to obtain the true solution in any given time\n    step.\n\n    The most difficult part of Newton's method is evaluating the Jacobian\n    $\\Jac$.\n\n    \\subsubsection{Acceleration of Newton solver: line search}\n    If the initial guess $\\bb{x}^{(0)}$ used is far from the true to solution,\n    the Newton solver may overshoot the true solution and first oscillate around\n    it, or even diverge completely. One method of accelerating convergence is\n    given in {\\em Numerical Recipes} and is based on the optimization of an\n    equivalent one-dimensional problem. The purpose of the method is to\n    determine the optimal damping factor $\\lambda$ such that the Newton update\n    \\begin{equation}\n        \\bb{x}^{(k+1)} = \\bb{x}^{(k)} + \\lambda\\delta\\bb{x},\n    \\end{equation}\n    with $\\delta\\bb{x}\\equiv\\Jac^{-1}\\bb{F}$, takes as close to the true\n    solution as possible. If we are sufficiently close to the true solution,\n    $\\lambda=1$ and no damping is needed.\n\n    First, let us introduce the proxy function\n    \\begin{equation}\n        f = \\frac{1}{2}\\bb{F}\\cdot\\bb{F}.\n    \\end{equation}\n    This function has a root wherever $\\bb{F}$ does, and is otherwise strictly\n    positive. It turns out that $\\delta\\bb{x}$ is a descent direction for $f$,\n    i.e.\\ a direction in which $f$ decreases, since\n    \\begin{equation}\n        \\nabla f\\cdot\\delta\\bb{x} = \\left( \\bb{F}\\cdot\\Jac \\right)\\cdot\n        \\left( -\\Jac^{-1}\\cdot\\bb{F} \\right) = -\\bb{F}\\cdot\\bb{F} < 0\n    \\end{equation}\n    Note, however, that we are only guaranteed that $\\delta\\bb{x}$ {\\em points}\n    in the descent direction from the previous guess $\\bb{x}^{(k)}$; the step\n    may however be too long and actually lead to an increase in $f$ is taken\n    fully. Thus, to prevent overshoot, we should verify that $f$ actually\n    decreases by taking the step $\\delta\\bb{x}$, and if not, backtrack along\n    $\\delta\\bb{x}$ until $f(\\bb{x}^{(k+1)}) < f(\\bb{x}^{(k)})$. In practice,\n    we impose the less strict condition\n    \\begin{equation}\\label{eq:newton:acc:cond}\n        f\\left(\\bb{x}^{(k+1)}\\right) \\leq f\\left(\\bb{x}^{(k)}\\right) +\n        \\alpha\\nabla f^{(0)}\\cdot\\delta\\bb{x},\n    \\end{equation}\n    where $\\alpha$ is an arbitrary coefficient satisfying $0<\\alpha<1$ (which\n    the authors of {\\em Numerical Recipes}---and we---set to $\\alpha=10^{-4}$)\n    and $\\nabla f^{(0)}$ denotes the gradient of $f$ at the initial guess\n    $\\bb{x}^{(0)}$. This condition prevents the algorithm from converging too\n    slowly, in case it successively jumps between $\\bb{x}$ values on different\n    sides of the root.\n\n    Having defined the target function $f$, we must now formulate the\n    optimization problem that will allow us to determine the damping factor\n    $\\lambda$. We do so by introducing the function\n    \\begin{equation}\n        g(\\lambda) = f\\left(\\bb{x}^{(k)} + \\lambda\\delta\\bb{x}\\right) = f\\left(\\bb{x}^{(k)}\\right).\n    \\end{equation}\n    This in turn implies that the derivative of this function is\n    \\begin{equation}\n        g'(\\lambda) = \\nabla f\\cdot\\delta\\bb{x}.\n    \\end{equation}\n    When starting the algorithm we have access to $g(0)$ and $g'(0)$. We then\n    take a Newton step with $\\lambda=1$ (assuming the true solution to be\n    nearby), thus obtaining information about $g(1)$ and $g'(1)$. If\n    $f(\\bb{x}^{(0)}+\\delta\\bb{x}^{(0)})$ does not\n    satisfy~\\eqref{eq:newton:acc:cond}, we can use the knowledge we have gained\n    about $g(\\lambda)$ to construct a better estimate for $\\lambda$. After this\n    first iteration, we assume that $g(\\lambda)$ depends quadratically on\n    $\\lambda$:\n    \\begin{equation}\n        g(\\lambda)\\approx \\left[ g(1)-g(0)-g'(0) \\right]\\lambda^2 +\n        g'(0)\\lambda + g(0).\n    \\end{equation}\n    This function has a minimum in\n    \\begin{equation}\n        \\lambda = -\\frac{g'(0)}{2\\left[ g(1)-g(0)-g'(0) \\right]}.\n    \\end{equation}\n    To prevent the algorithm from taking too small steps, we must ensure that\n    the obtained $\\lambda$ is greater than at least some minimum allowed value\n    $\\lambda_{\\rm min}$, which the authors of {\\em Numerical Recipes} (and\n    therefore also we) take to be $\\lambda_{\\rm min} = 0.1$.\n\n    In subsequent Newton iterations, if a step is rejected, we use a cubic\n    approximation for $g(\\lambda)$:\n    \\begin{equation}\\label{eq:newton:acc:cub}\n        g(\\lambda) = a\\lambda^3 + b\\lambda^2 + g'(0)\\lambda + g(0).\n    \\end{equation}\n    Here, the coefficients $a$ and $b$ are computed with the help of the initial\n    state $g(0)$ and $g'(0)$, as well as the function $g(\\lambda)$ evaluated in\n    the most recent and second most recent points $\\lambda=\\lambda_1$ and\n    $\\lambda=\\lambda_2$:\n    \\begin{equation}\n        \\begin{aligned}\n            a &= \\frac{\n                    \\lambda_2^2g\\left(\\lambda_1\\right) - \\lambda_1^2g\\left(\\lambda_2\\right)+\n                    \\lambda_1\\lambda_2\\left(\\lambda_1-\\lambda_2\\right)g'(0) +\n                    \\left(\\lambda_1^2 - \\lambda_2^2\\right)g(0)\n                }{\\lambda_1^2\\lambda_2^2\\left(\\lambda_1-\\lambda_2\\right)},\\\\\n            %\n            b &= \\frac{\n                    \\lambda_1^3g\\left(\\lambda_2\\right) - \\lambda_2^3g\\left(\\lambda_1\\right) +\n                    \\lambda_1\\lambda_2\\left(\\lambda_2^2-\\lambda_1^2\\right)g'(0) +\n                    \\left(\\lambda_2^3 - \\lambda_1^3\\right)g(0)\n                }{\\lambda_1^2\\lambda_2^2\\left(\\lambda_1-\\lambda_2\\right)}\n        \\end{aligned}\n    \\end{equation}\n    The minimum of~\\eqref{eq:newton:acc:cub} is\n    \\begin{equation}\n        \\lambda = \\frac{-b+\\sqrt{b^2-3ag'(0)}}{3a},\n    \\end{equation}\n    To prevent slow convergence, we require that\n    $0.1\\lambda_1\\leq\\lambda\\leq 0.5\\lambda_1$.\n\n    \\addcontentsline{toc}{section}{References}\n    \\printbibliography\n\n\\end{document}\n\n", "meta": {"hexsha": "93f0af5cccdcda49069a3bdd90e40948a91932ec", "size": 40895, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/notes/discretisation.tex", "max_stars_repo_name": "chalmersplasmatheory/DREAM", "max_stars_repo_head_hexsha": "715637ada94f5e35db16f23c2fd49bb7401f4a27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2020-09-07T11:19:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T17:40:19.000Z", "max_issues_repo_path": "doc/notes/discretisation.tex", "max_issues_repo_name": "chalmersplasmatheory/DREAM", "max_issues_repo_head_hexsha": "715637ada94f5e35db16f23c2fd49bb7401f4a27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 110, "max_issues_repo_issues_event_min_datetime": "2020-09-02T15:29:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T09:50:01.000Z", "max_forks_repo_path": "doc/notes/discretisation.tex", "max_forks_repo_name": "chalmersplasmatheory/DREAM", "max_forks_repo_head_hexsha": "715637ada94f5e35db16f23c2fd49bb7401f4a27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-05-21T13:24:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T14:43:12.000Z", "avg_line_length": 53.7385019711, "max_line_length": 200, "alphanum_fraction": 0.6256266047, "num_tokens": 13301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3256774323330271}}
{"text": "% !TeX root = ./ms.tex\n\\def\\LINENOS{1}\n\n\\ifdefined\\LINENOS\n    \\documentclass[modern,linenumbers]{aastex62}\n\\else\n    \\documentclass[modern]{aastex62}\n\\fi\n\n% Load the corTeX style definitions\n\\input{cortex}\n\n% Load custom style\n\\input{style}\n\n% Force line numbers in paragraphs containing equations\n\\ifdefined\\LINENOS\n    \\usepackage{lineno}\n    \\linenumbers\n    \\let\\oldalign\\align\n    \\let\\oldendalign\\endalign\n    \\renewenvironment{align}{%\n        \\linenomath%\n            \\oldalign%\n    }{%\n        \\endlinenomath%\n            \\oldendalign%\n    }\n\\fi\n\n% Bibliography\n\\bibliographystyle{aasjournal}\n\n% Begin!\n\\begin{document}\n\n% Title\n\\title{%\n    \\textbf{\n        Analytic Light Curves in Reflected Light:%\n        \\\\%\n        Phase Curves, Occultations, and Non-Lambertian Scattering for\n        Spherical Planets and Moons\n    }\n}\n\n% Author list\n\\author[0000-0002-0296-3826]{Rodrigo Luger}\\altaffiliation{Flatiron Fellow}\n\\email{rluger@flatironinstitute.org}\n\\affil{Center~for~Computational~Astrophysics, Flatiron~Institute, New~York, NY}\n\\affil{Virtual~Planetary~Laboratory, University~of~Washington, Seattle, WA}\n%\n\\author[0000-0002-0802-9145]{Eric Agol}\n\\affil{Department~of~Astronomy, University~of~Washington, Seattle, WA}\n\\affil{Virtual~Planetary~Laboratory, University~of~Washington, Seattle, WA}\n%\n\\author[0000-0001-8630-9794]{Fran Bartoli\\'c}\n\\affil{Centre for Exoplanet Science, University of St. Andrews, St. Andrews, UK}\n\\affil{Center~for~Computational~Astrophysics, Flatiron~Institute, New~York, NY}\n%\n\\author[0000-0002-9328-5652]{Daniel Foreman-Mackey}\n\\affil{Center~for~Computational~Astrophysics, Flatiron~Institute, New~York, NY}\n\n\\keywords{methods: analytic --- techniques: photometric}\n\n\\begin{abstract}\n    We derive efficient, closed form, differentiable, and numerically stable\n    solutions for the flux measured from a spherical planet or moon seen in reflected\n    light, either in or out of occultation.\n    %\n    Our expressions apply to the computation of scattered\n    light phase curves of exoplanets, secondary eclipse light curves in\n    the optical, or future measurements of planet-moon and planet-planet\n    occultations, as well as to photometry of solar system bodies.\n    %\n    We derive our solutions for Lambertian bodies illuminated by a point\n    source, but extend them to model illumination sources of finite\n    angular size and rough surfaces with phase-dependent scattering.\n    %\n    Our algorithm is implemented in \\Python within the open-source\n    \\starry mapping framework and is designed with efficient gradient-based\n    inference in mind.\n    %\n    The algorithm is ${\\sim}4-5$ orders of magnitude faster than direct\n    numerical evaluation methods and ${\\sim}10$ orders of magnitude more\n    precise.\n    %\n    We show how the techniques developed here may one day lead to the\n    construction of two-dimensional maps of terrestrial planet surfaces,\n    potentially enabling the detection of continents and oceans on\n    exoplanets in the habitable zone.\n    %\n    \\href{https://github.com/rodluger/starrynight}{\\color{linkcolor}\\faGithub}\n\\end{abstract}\n\n%\n\\section{Introduction}\n\\label{sec:intro}\n%\n\nDespite recent advances in instrumentation and the dawn of\nthirty meter-class telescopes and kilometer-wide interferomer arrays,\nextrasolar planets will remain unresolved point sources for decades\nto come. Nevertheless, modulations in the light received from these distant\nbodies due to their rotation, changing illumination, and eclipses\nby their host stars or other bodies in the system can be harnessed to\nreconstruct two-dimensional views of their surfaces.\nIn particular, next-generation space-based telescopes such as the\nLarge UV/Optical/IR Surveyor (LUVOIR) may enable us to measure\nvariations in the reflected light signature of terrestrial planets in\nthe habitable zone, which can be used to map their surfaces and\nindirectly infer the presence of clouds, continents, oceans, and perhaps\neven life.\n\nThere is an extensive literature on techniques for mapping exoplanet surfaces\nbased on their phase curves\n\\citep[e.g.,][]{Russell1906,Lacis1972,Knutson2007,Cowan2008,Oakley2009,Berdyugina2017,PaperI,PaperII,Heng2021}\nand occultation light curves\n\\citep[e.g.,][]{Williams2006,Rauscher2007,Majeau2012,deWit2012,Rauscher2018},\nboth in thermal and reflected (scattered) light.\nIn particular, much attention has been given to techniques for mapping\nEarth-like planets from visible-light reflected phase curves\n\\citep[e.g.,][]{Ford2001,Kawahara2010,Kawahara2011,Fujii2012,Kawahara2020,Aizawa2020}.\nUnlike thermal phase curves, which primarily encode (often degenerate)\ninformation about longitudinal surface brightness variations\n\\citep{Russell1906}, reflected light curves often contain information\nabout the full two-dimensional surface albedo distribution\n\\citep[e.g.,][]{Kawahara2010}.\n\nOccultation light curves in reflected light can encode even more information\nabout the surface. Thus far, these have been studied primarily within our\nsolar system. Mutual occultations among the Galilean moons of Jupiter\nhave been extensively studied to infer surface properties of the moons and to refine\ntheir ephemerides\n\\citep[e.g.,][]{Arlot1974,Aksnes1984,Arlot2014,deKleer2017,Saquet2018,Morgado2019,Bartolic2021}.\nFarther out in the solar system,\nmutual occultations of Pluto and Charon in the late 1980s\nwere used to confirm Charon's existence\n\\citep{Stern1992},\nestablish the sizes and orbital parameters of the two bodies\n\\citep{Tholen1990},\nand infer their surface properties\n\\citep{Marcialis1990}.\nIn particular, \\citet{Dunbar1986} developed an efficient analytic\nalgorithm to model Pluto-Charon occultation light curves in reflected light\nassuming uniform surfaces and used it to infer the two body's\naverage geometrical albedos. Later,\n\\citet{Buie1992} used a maximum entropy approach to reconstruct two-dimensional\nmaps of the two bodies and\n\\citet{Reinsch1994} analyzed\nthe complete mutual occultation dataset to infer longitudinal maps of Pluto's\nalbedo.\n\nMany studies have analyzed real Earth reflected light curves to\ninfer surface properties of our planet as an exercise in\nprepartion for the mapping of exoplanets.\n%\n\\citet{Cowan2009} and \\citet{Cowan2011b} analyzed visible-light disk-integrated light curves\nof the Earth taken by the Deep Impact spacecraft to produce\nlongitudinal maps of the surface, harnessing multi-band observations\nto disentangle static surface brightness features from temporally\nvariable clouds.  A transit of Earth by the Moon was observed\nas well \\citep{Livengood2011}, although this data has yet to be\nexploited for mapping purposes.\nMore recently, \\citet{Jiang2018} and \\citet{Fan2019}\nused data from the L1-stationed DSCOVR satellite to infer surface\nand cloud properties of the Earth, and \\citet{Luger2019b} analyzed\nbackground scattered light in TESS photometry to reconstruct a cloud\nmap of the Earth.\n\n\\textbf{%\nThere have also been many developments on the open-source software front.\nThese include \\textsf{ReflectDirect}, a reflected light curve analysis \nsuite \\citep{Schwartz2016};\n\\textsf{samurai}, a tool for rotational unmixing of reflected light curves\n\\citep{LustigYaeger2018};\n\\textsf{spiderman}, an efficient discretization scheme\non the sphere that enables fast computation of exoplanet\nphase curves and occultation light curves \\citep{Louden2018};\n\\textsf{exocartographer}, a Bayesian\nframework for doing inference on exoplanet phase curves based on\na HEALPix \\citep{healpix} discretization scheme \\citep{Farr2018};\nthe \\textsf{sot} package for spin-orbit tomography of exo-Earths \\citep{Kawahara2020,Kawahara2020b};\nand \n\\textsf{neural\\_exocartography}, a tool for mapping exoplanet surfaces with neural learned\nregularization \\citep{AsensioRamos2021}.\n%\nOf particular relevance to the present work,\n\\citet{Haggard2018} presented\n\\textsf{EARL} (Exoplanet Analytic Reflected Lightcurves),\na \\textsf{Mathematica} code to compute analytic, closed form\nsolutions for the phase curve of a Lambert sphere, i.e., one that\nscatters light isotropically, in the case that the surface albedo\ndistribution is characterized by either a sum of delta functions\nor a sum of spherical harmonics.\n%\nAnd finally, \\citet{Luger2019} introduced \\starry, a light curve\nmodeling package that computes thermal phase curves and occultation\nlight curves, as well as their derivatives, analytically from a spherical\nharmonic expansion of the surface brightness.\n}\n\nThe present paper is an extension to the \\starry algorithm,\nadapting it to model phase curves and occultation light curves\nin reflected light. The expressions\nwe derive are analytic: they may all be expressed in closed form\nin terms of algebraic operations involving trigonometric functions\nand (at times) elliptic integrals. We derive numerically\nstable recursion relations for the efficient evaluation of all\nexpressions and code them within an autodifferentiation framework\nto enable the computation of accurate derivatives for use in\ngradient-based inference and optimization schemes.\nOur code is fully\n\\href{https://github.com/rodluger/starry}{open-source},\ncomprehensively\n\\href{https://dev.azure.com/rodluger/starry/_test/analytics?definitionId=4}{unit-tested},\nand supplemented with an extensive\n\\href{https://starry.readthedocs.io}{API documentation}\nand suite of\n\\href{https://starry.readthedocs.io/en/latest/tutorials/}{tutorials}.\n%\nAs in all papers in the \\starry series, in the caption of each of the figures\nwe provide links \\codeicon\\ to the exact \\Python scripts that\ngenerated them. Next to many of the equations we also provide\nlinks \\prooficon\\ to \\textsf{Jupyter} notebooks containing\ndetailed derivations and/or validations.\n\n\\section{Overview}\n\\label{sec:overview}\n\nOur goal in this paper is to derive analytic expressions for the\nflux received by a distant observer from a sphere of non-uniform albedo\nilluminated by a monochromatic source that may or may not be\nocculted by a (possibly different) spherical body. This applies, for example,\nto the case of planetary phase curves, secondary\neclipse (occultation) light curves, and moon-moon, planet-moon, and\nplanet-planet occultations \\citep[in the Solar System or not; e.g.,][]{Cabrera2007,Luger2019b},\nall seen in reflected light. We derive all expressions in\nthe limit that the reflecting\nbody is Lambertian, i.e., it scatters light isotropically, but we relax\nthis assumption in later sections.\nWe model the general case of an\nintensity that varies across the surface of the body according to a\nspatially-dependent\nalbedo $A$. Throughout this paper, we will take $A$ to mean the \\emph{spherical}\nalbedo, the fraction of power incident on a body at a given wavelength\nthat is scattered back out to space (in all directions).\nNote that the spherical albedo\nis closely related to the Bond albedo: the Bond albedo is the stellar\nflux-weighted integral of $A(\\lambda)$ over all wavelengths $\\lambda$\n\\citep[see, e.g.,][]{Seager2010}.\n\nAs in \\citet{Luger2019}, we compute fluxes by first expanding the surface\nin terms of spherical harmonics.\nWhile in \\citet{Luger2019} we expanded the emissivity of the surface, here\nwe instead expand the spherical albedo $A$.\nSpecifically, if $\\bvec{y}$ is the vector\nof spherical harmonic coefficients describing the albedo anywhere on\nthe surface and\n$\\by$ is the spherical harmonics basis (Equation~\\ref{eq:by}),\nthe albedo $A$ at a point $(x, y)$ on the sky-projected disk of the body\nis given by the dot product\n%\n\\begin{align}\n    \\label{eq:albedo}\n    A(x, y) = \\by^\\top (x, y) \\, \\bvec{y}\n    \\quad.\n\\end{align}\n%\nThe flux measured from this body is proportional to the surface integral\nover the projected disk\nof the albedo $A$ times the illumination profile $\\mathcal{I}$ of the surface,\ngiven by Lambert's law as\n%\n\\begin{align}\n    \\label{eq:LambertsLaw}\n    \\mathcal{I}(\\vartheta_\\mathrm{i}) = \\mathcal{I}_0 \\, \\text{max}\\big( 0, \\cos\\vartheta_\\mathrm{i} \\big)\n    \\quad,\n\\end{align}\n%\nwhere $\\vartheta_\\mathrm{i}$ is the angle between the incident radiation and the surface\nnormal and $\\mathcal{I}_0$ is the peak illumination. We show in\nAppendix~\\ref{sec:adapting-starry} that in the case of, say, a planet\nilluminated by its host star,\n%\n\\begin{align}\n    \\mathcal{I}_0 = \\frac{f_s}{\\pi r_\\mathrm{s}^2}\n\\end{align}\n%\nwhere $r_\\mathrm{s}$ is the distance between the planet and the star (in units\nof the planet's radius) and $f_s$ is the stellar flux measured at the observer\n(in arbitrary units). Following the convention in \\citet{Luger2019}, we assume\nthroughout this paper that $f_s = 1$, so all fluxes are defined as a fraction of\nthe flux of the illumination source at the observer.\n\nThe piecewise nature of the illumination function at the day/night terminator\nmakes the problem of computing the visible flux particularly difficult; most\nstudies to date have tackled the problem numerically, either\nvia Monte Carlo integration \\citep[e.g.,][]{Ford2001} or by discretizing the surface\nand computing the relevant integrals by summing over the visible\npixels \\citep[e.g.,][]{Kawahara2010,Fujii2012}.\nRecently, \\citet{Haggard2018} developed an analytic\nframework for computing light curves of unocculted bodies illuminated\nby a point source. In this paper, we re-derive their solution under the\n\\starry framework and extend it for the first time to the case where\nthe body is occulted by another spherical body, which may or may not be the\nillumination source. We also extend the solution to the case of an extended\nillumination source and to non-Lambertian scattering.\n\nIn \\citet{Luger2019}, we reduced the problem of computing the flux from\nan occulted body in thermal (emitted) light to a series of efficient, analytical\noperations involving trigonometric functions of the position and size of the\noccultor and certain complete elliptic integrals. In the case of reflected\nlight, however, the change in the limits of integration due to the\nunilluminated night side breaks many of the symmetries that simplified\nthe flux calculation. In particular, the limits of integration now depend\non the solution to a quartic equation specifying the points of intersection\nbetween the occultor and the day/night terminator, and the solution to\nthose integrals is now a function of \\emph{incomplete} elliptic integrals.\nThe procedure for computing the flux is therefore significantly more complex.\n%\nWe therefore defer all calculations to the Appendix, and devote the body of\nthe paper to validating and demonstrating applications of our approach.\n\nThis paper is organized as follows.\nIn \\S\\ref{sec:validation} we present sample light curves computed\nusing our algorithm, validate it against numerical integration, and\ndiscuss its performance in terms of computational speed and precision.\nIn \\S\\ref{sec:extensions} we extend the model to apply to illumination\nsources of finite size and surfaces that scatter light anisotropically.\nWe discuss implications, applications, and limitations of our model in\n\\S\\ref{sec:discussion} and summarize our findings in \\S\\ref{sec:conclusions}.\nFor convenience, Tables~\\ref{tab:symbols}--\\ref{tab:matrices} at the end\nlist all symbols and variables used in the text, with descriptions and\nlinks to the equations in which they are defined.\n\n\\begin{figure}[t!]\n    \\begin{centering}\n        \\includegraphics[width=\\linewidth]{figures/earthphase.pdf}\n        \\oscaption{earthphase}{%\n            Mock reflected light phase curve of the cloudless Earth expanded\n            to spherical harmonic degree $l = 25$, viewed along the\n            ecliptic. The main plot shows the phase curve over the course of\n            one year.\n            The images at the top show the corresponding progression of\n            the phases of the Earth, from new phase to full phase and back\n            to new phase. Below each image we show a normalized 24-hour\n            segment of the light curve at that phase (blue).\n            Orange dots correspond\n            to the flux computed from brute force numerical integration on\n            a grid of\n            ${\\sim}10^5$ points.\n            \\label{fig:earthphase}\n        }\n    \\end{centering}\n\\end{figure}\n\n% HACK\n\\pagebreak\n\n\\section{Reflected light curves in starry}\n\\label{sec:validation}\n\n\\subsection{Sample light curves}\n\\label{sec:sample}\n\nFigure~\\ref{fig:earthphase} shows a sample application of the algorithm\ndeveloped in this paper: a reflected light phase curve of the\nEarth over the course of one year. The model is computed using the\nmethodology in Appendix~\\ref{sec:solution-no-occ} from an $l=25$\nspherical harmonic expansion of the cloudless Earth, where the oceans\nare given an albedo of zero and the continents an albedo of unity\n(note, however, that since the light curve is normalized, the model does\nnot depend on the value of the latter).\nThe Earth is assumed to be a perfect Lambertian scatterer,\nso effects like the phase dependence of Rayleigh scattering and\nspecular reflection (glint) from the oceans are neglected\n(but see \\S\\ref{sec:extensions} for an extension of the model to\nnon-Lambertian scatterers).\nThe observer is assumed to be along\nthe ecliptic, so the illumination source is along the $x-z$ plane of a\nright-handed Cartesian coordinate system, with $\\hat{z}$ pointing toward the\nobserver and $\\hat{x}$ pointing to the right on the sky. The axis of rotation\nof the Earth is therefore tilted clockwise away from\n$\\hat{y}$ by $23.5^\\circ$.\nThe images at the top show snapshots of the disk of the Earth throughout\nthe observation; below each one, we plot in blue the normalized phase curve\nat that phase over a single rotation. The orange dots correspond to a\nbrute force numerical solution, obtained by discretizing the disk\non a grid of ${\\sim}10^5$ points and summing over the dayside.\nThe models agree to within the\nnumerical precision of the brute force solution (about 100 ppm of the\nplanetary flux in this case).\n\nWhile the dominant signal in the phase curve is the sine-like envelope\ndue to the changing phases of the Earth, the local behavior of the light\ncurve at each phase is complex and varies significantly over the course\nof the year. Unlike phase curves in thermal light, which primarily encode\nlow-order spatial information (since the region of integration is always\nthe full disk), phase curves in reflected light encode information at\ndifferent scales depending on the phase. At crescent phase, the region of the\ndisk contributing to the total flux is a narrow lune; these measurements\ntherefore encode information primarily about high-$l$ modes. At full\nphase, the region of integration is the full disk, so these measurements\nencode information about low-$l$ modes. Furthermore, because of the obliquity\nof the Earth,\nthe orientation of the crescent lune changes relative to features on the\nsurface over the course of one orbit, changing the relative contribution of\ndifferent portions of the surface to the flux and increasing the\noverall information content of the observation.\nAs we will show in \\S\\ref{sec:information}, the information content of\nreflected light phase curves is overwhelmingly higher than that of\nphase curves in thermal light, particularly for planets with significant\nobliquity.\n\n%\n\n\\begin{figure}[t!]\n    \\begin{centering}\n        \\includegraphics[width=\\linewidth]{figures/earthmoon_emitted.pdf}\n        \\includegraphics[width=\\linewidth]{figures/earthmoon.pdf}\n        \\oscaption{earthmoon}{%\n            Mock light curves of the Moon occulting a rotating,\n            cloudless Earth expanded to spherical harmonic degree $l = 25$.\n            Black curves show the analytic solution; orange dots correspond\n            to brute force numerical integration on a grid of\n            ${\\sim}10^5$ points.\n            The top panel shows the light curve in emitted light and is\n            the same as in Figure~7 in \\citet{Luger2019}.\n            The bottom panel (this work) shows the same light curve in\n            reflected light during northern summer.\n            \\label{fig:earthmoon}\n        }\n    \\end{centering}\n\\end{figure}\n\nFigure~\\ref{fig:earthmoon} shows another light curve of the rotating\nEarth, but this time taken during an occultation by the Moon. The map\nof the Earth is the same as before, but the observer is now along the\nequatorial plane of the Earth.\nThe top panel is a reproduction of\nFigure~7 in \\citet{Luger2019} for the case of thermal light,\nwhere the Moon is seen to travel across the\ndisk of the Earth from southwest to northeast, progressively occulting\nSouth America (dip), the Atlantic (peak), and Africa (dip).\nAs before,\nthe blue curve is the analytic solution and the orange dots correspond\nto the numerical solution.\n\nThe bottom panel of the figure shows a light curve for the\nsame occultation geometry, but seen instead in reflected light, with the\nSun to the top left and slightly out of the page, corresponding to\nsome point during northern summer. Note the same dip-peak-dip pattern,\nalbeit with significantly different amplitudes. In particular, the\ntransit across South America is deeper, since it occurs close to local\nnoon, when the illumination is highest; conversely, the transit across\nAfrica occurs close to local dusk, when the illumination is close to zero.\nAs before, the light curves computed using \\starry agree to within the\nnumerical precision of the brute force solution.\n\n%\n\n\\begin{figure}[p!]\n    \\begin{centering}\n        \\includegraphics[width=\\linewidth]{figures/earthsun_emitted.pdf}\n        \\includegraphics[width=\\linewidth]{figures/earthsun.pdf}\n        \\includegraphics[width=\\linewidth]{figures/earthsun_diff.pdf}\n        \\oscaption{earthsun}{%\n            Mock secondary eclipse ingress light curves of the\n            cloudless Earth expanded to spherical harmonic degree $l = 25$,\n            viewed from an orientation where the Earth is occulted behind\n            a solar latitude of $30^\\circ$.\n            Black curves show the analytic solution; orange dots correspond\n            to brute force numerical integration on a grid of\n            ${\\sim}10^5$ points.\n            The top panel shows the light curve in emitted light and is\n            similar to Figure~13 in \\citet{Luger2019}.\n            The middle panel (this work) shows the same light curve in\n            reflected light.\n            The bottom panel shows the difference between the\n            normalized reflected and emitted light curves.\n            \\label{fig:earthsun}\n        }\n    \\end{centering}\n\\end{figure}\n\nOur last sample light curve is Figure~\\ref{fig:earthsun}, which shows\na secondary eclipse light curve of the Earth as it is occulted by the\nSun. The model for the Earth is the same as above, and the observer is\nnow close to the ecliptic, but slightly misaligned so that the\nEarth is occulted behind a solar latitude of $30^\\circ$ (i.e., at\na solar impact parameter of $0.5$). The observation takes place at the\nJune solstice, so the Earth is tilted by $23.5^\\circ$ out of the page.\nAs before, the top panel shows the light curve in thermal light; this\nis similar to the top panel of Figure~13 in \\citet{Luger2019}. The orange\ndots again correspond to the numerical solution.\n%\nThe center panel shows the same light curve in reflected light.\nBecause the observation occurs very close to full phase, the normalized\nlight curves look very similar to each other.\nThe bottom panel shows the difference between the two\n(reflected minus thermal), which is only on the order of a few percent.\n%\nIn fact, because\nthe illumination profile is proportional to the cosine of the viewing\nangle, $\\upmu$, and the reflection is assumed to be isotropic, the\n(normalized) secondary eclipse light curve in reflected light is to\ngood approximation equal\nto a limb-darkened thermal occultation light curve with\nlinear limb darkening coefficient $u_1 = 1$. As we will see later, for very\nclose-in planets this approximation breaks down, since the illumination\nphases at secondary eclipse ingress and egress are sufficiently different\nfrom full phase.\n\n%\n\n\\subsection{Performance}\n\\label{sec:performance}\n\nAs we discuss in the Appendix, the model for phase curves and\noccultation light curves in reflected light may be expressed\nanalytically in terms of purely algebraic and trigonometric functions\nand in some cases incomplete elliptic integrals of the first, second,\nand third kinds. We have derived efficient and numerically stable\nrecursion relations to compute the relevant expressions and their\nderivatives. At times, these involve the evaluation of certain\nexpressions numerically, especially when doing so\nleads to either a speed-up or a significant gain in numerical precision.\nIn particular, as we discuss in Appendix~\\ref{sec:which-case}, the\nintegration boundaries during an occultation sometimes depend on the\nsolution to a quartic equation. While this can be solved in closed form,\nthe analytic solution can often be very unstable. We therefore solve\nthe quartic numerically, attaining a precision for the roots within a\nfew orders of magnitude of machine (double) precision.\n\n\\begin{figure}[p!]\n    \\begin{centering}\n        \\includegraphics[width=\\linewidth]{figures/speed_no_occ.pdf}\n        \\oscaption{speed}{%\n            Evaluation time (vertical axis)\n            and numerical precision (point size)\n            for a single flux evaluation in the absence of an occultor\n            as a function of spherical\n            harmonic degree for different methods.\n            In purple we show results for the emitted light\n            \\starry algorithm from \\citet{Luger2019} (solid: no gradient,\n            dashed: with gradient), and in blue we show results for\n            the reflected\n            light algorithm from this paper (solid: no gradient,\n            dashed: with gradient). For comparison, in we also show\n            results for discrete integration on a grid (orange) and for\n            numerical integration using two-dimensional Gaussian\n            quadrature (red); neither of these include gradient\n            evaluations. The reflected light algorithm is\n            comparable in efficiency and precision to the emitted\n            light algorithm. It is ${\\sim}5$ orders of magnitude faster\n            and ${\\sim}10$ orders of magnitude more precise than numerical\n            integration.\n            \\label{fig:speed_no_occ}\n        }\n    \\end{centering}\n\\end{figure}\n\n\\begin{figure}[p!]\n    \\begin{centering}\n        \\includegraphics[width=\\linewidth]{figures/speed.pdf}\n        \\oscaption{speed}{%\n            Same as Figure~\\ref{fig:speed_no_occ}, but for an occultation\n            evaluation in which the occultor intersects the terminator\n            (case 6 in Appendix~\\ref{sec:solution-occ}).\n            The reflected light algorithm is around one\n            order of magnitude slower and comparably precise to the emitted\n            light algorithm. It is ${\\sim}4$ orders of magnitude faster\n            and ${\\sim}10$ orders of magnitude more precise than numerical\n            integration.\n            \\label{fig:speed}\n        }\n    \\end{centering}\n\\end{figure}\n\nFigures~\\ref{fig:speed_no_occ} and \\ref{fig:speed} summarize\nthe precision and computation time of the \\starry algorithm for\ntwo typical scenarios: a phase curve evaluation\n(Figure~\\ref{fig:speed_no_occ}) and an occultation evaluation\n(Figure~\\ref{fig:speed}).\nBlue points correspond to the reflected light algorithm developed\nin this paper, while purple points correspond to the thermal light\nalgorithm from \\citet{Luger2019} for the same occultation geometry,\nbut without an illumination source.\nSolid and dashed lines correspond to evaluations without and\nwith gradient propagation, respectively (see \\S\\ref{sec:usage}\nfor details).\nThe orange and red dots\ncorrespond to numerical evaluation of the flux:\nbrute force integration by summation on a grid of ${\\sim}10^6$ points\n(orange) and two-dimensional adaptive Gaussian quadrature using the\n\\textsf{dblquad} function in \\textsf{scipy} \\citep{scipy} with\nboth absolute and relative error tolerances set to $10^{-3}$ (red).\n%\nIn both figures, the vertical axis corresponds to the evaluation\ntime in seconds for a single flux computation, while the size of the\npoints is proportional to the base-10 log of the relative error. For the\n\\starry solutions, the latter is estimated as the max-min difference\nin the flux over one thousand evaluations in which the input parameters\nare perturbed within an order of magnitude of machine epsilon; this is\ntherefore a probe of the condition number of the starry algorithm and\ncaptures only error due to numerical instabilities.\nIt is worth emphasizing that this is a measurement of the precision of\nthe algorithm, rather than the accuracy, because it would be computationally\nintractable to compute a solution more accurate than this using a different\nalgorithm.\nWe argue that this measurement can be interpreted to mean that the algorithm\nis also accurate, but detailed quantification of this difference is beyond the\nscope of this paper.\nFor the numerical\nsolutions, the error is estimated as the difference between the numerical\nflux and the \\starry flux.\n\nFor both phase curves and occultations, the \\starry reflected\nlight algorithm is 1--2 orders of\nmagnitude slower than the emitted light algorithm, owing\nprimarily to the increased complexity of the reflected light model.\nFor phase curves (Figure~\\ref{fig:speed_no_occ}),\nthe thermal solution vector $\\rTe$ (Equation~\\ref{eq:rTA1Ry}) is a constant\nthat can be pre-computed, while the analogous vector in the reflected\nlight case, $\\rT$ (Equation~\\ref{eq:rTsoln}), must be evaluated\nrecursively each time. For occultations (Figure~\\ref{fig:speed}),\nthe slower evaluation in the reflected light case is primarily due to\nthe time spent solving the quartic equation for the points of intersection\nbetween the occultor and the day/night terminator of the illuminated\nbody (Appendix~\\ref{sec:solution-occ}). This contributes the\nsame overhead at all map degrees $l$, resulting in a gentler scaling\nin $l$ than for the thermal case; for large $l$, the evaluation time\nfor the two algorithms is within a factor of 2--3.\n%\nIn terms of precision, the algorithms are comparable, particularly\nfor occultations. For both phase curves and occultations, the numerical error up\nto $l=10$ is less than one part per trillion ($10^{-12}$) for both thermal\nand reflected light curves.\n\nCompared to either numerical evaluation method, the \\starry reflected light\nsolutions are\n\\textbf{4--5 orders of magnitude faster} and about\n\\textbf{10 orders of magnitude more precise}. While different\ngrid sizes and different error settings for the numerical integration change\nthe balance slightly between these numbers, the \\starry solution is always\nmany orders of magnitude faster and more precise than either method.\nIn particular, because of the complicated integration boundaries\n(see, for example, Figure~\\ref{fig:cases}), two-dimensional Gaussian quadrature\nstruggles to reach adequate accuracy in a reasonable amount of time,\nwhile integration on a grid fails to capture the curvature of the\nintegration boundaries. Moreover, neither method yields the gradient of the\nsolution with respect to the input parameters, which can be extremely useful\nfor optimization and inference problems (see \\S\\ref{sec:usage}) below.\n\nNote, importantly, that as we mentioned above, the reported error of the \\starry\nsolution is only the \\emph{numerical} error of the algorithm: it does not\ncapture any systematic error due to, say, an error in the derivation of\nthe method. To this end, we rely on the Jupyter notebooks containing\nderivations and validations of the main equations in the Appendix, whose\nlinks \\prooficon\\, appear next to the equation labels.\n%\nWe have also developed an extensive suite of\n\\href{https://github.com/rodluger/starry/tree/master/tests}{unit tests}\ncomparing the \\starry solution to the numerical solution over a large\ngrid of input parameter values, and verified that the solutions agree\nto within the precision of the numerical method.\n%\nThat said, there are specific cases in which the algorithm presented in the\nAppendix suffers from numerical instabilities. These generally happen due\nto division by small numbers or catastrophic cancellation in the recursion,\nand often occur near configurations involving grazing occultations,\nnear-total occultations, terminator semi-minor axis $b \\approx 0$ or\n$b \\approx 1$, etc. To mitigate these, we introduce various tolerance\nparameters in the code to either nudge the inputs away from these singular\npoints or switch to a different evaluation method. These parameters are\noutlined in Table~\\ref{tab:tolerance} at the end. In the vicinity of the cases\ndescribed in that table, the precision of the \\starry algorithm will be\nreduced to (roughly) the value of the tolerance parameter, which in\nextremely rare cases can be as high as $10^{-5}$.\n\n\\subsection{Implementation and usage}\n\\label{sec:usage}\n\nThe algorithm presented in this paper has been implemented in the \\Python\npackage \\starry, which can be installed from\n\\href{https://github.com/rodluger/starry}{GitHub} or via the Python package\nmanager \\textsf{pip}. The algorithm is coded in a mixture of \\textsf{C++}\nwith forward automatic differentiation using the \\textsf{Eigen} library\n\\citep{eigen} and \\Python with backward differentiation using\njust-in-time compiled \\textsf{theano}\noperations \\citep{theano}. The user interface, however, is purely in\n\\Python. The \\textsf{theano} backend facilitates integration with the\n\\textsf{exoplanet} modeling package \\citep{exoplanet} and in particular\nwith \\textsf{pymc3} \\citep{pymc3} for inference with gradient-based\nMarkov Chain Monte Carlo (MCMC) schemes\nsuch as Hamiltonian Monte Carlo \\citep[HMC;][]{Duane1987}\nand No-U-Turn Sampling \\citep[NUTS;][]{Hoffman2011}.\n%\nComplete \\href{https://starry.readthedocs.io}{documentation} and an\nextensive library of tutorials is available online.\nThe links next to each\nof the figures \\codeicon\\, point to the \\Python scripts used to generate\nthem and may also help in learning how to use \\starry.\n\n\\section{Extensions}\n\\label{sec:extensions}\n\nThe algorithm discussed above and derived in the Appendix computes light\ncurves in the limit that (1) the body is illuminated by a point source\nand (2) the body is an ideal Lambertian scatterer. Both of these\nassumptions can be relaxed within \\starry, and below we discuss modifications\nto the code to allow for this.\n\n% HACK\n\\pagebreak\n\n\\subsection{Extended illumination source}\n\\label{sec:extended}\n\nIn the limit that the angular size of the star as seen from the planet is\nsmall, the illumination profile on the surface of the planet will\ndecrease as the cosine of the angle between the surface normal and the star,\nreaching zero at the day/night terminator, an angle $\\nicefrac{\\pi}{2}$\naway from the sub-stellar point. However, if the star is sufficiently large\nand the planet is sufficiently close-in, rays originating from near the limb\nof the star will reach points on the planet surface beyond this angle.\nIf the stellar radius $R_\\star$\nis larger than the planet radius $R_\\mathrm{p}$, the angular extent of the true\nday/night terminator past $\\nicefrac{\\pi}{2}$ is given by\n%\n\\begin{proof}{tau}\n    \\label{eq:tau}\n    \\tau &= \\arcsin\\left( \\frac{1 - \\nicefrac{R_\\mathrm{p}}{R_\\star}}{\\nicefrac{a}{R_\\star}} \\right)\n\\end{proof}\n%\nwhere $a$ the semi-major axis of the orbit (where we implictly assume\nthe eccentricity is zero).\nFor planets like the Earth, this quantity is only about $0.26^\\circ$,\nresulting in a negligible effect on the planet's light curve. However,\nfor very close-in planets, the effect can be significant\n\\citep{Knuth2017,Carter2019}. For instance,\nthe hot Jupiter Kelt-9b has $\\nicefrac{R_\\mathrm{p}}{R_\\star} = 0.083$ and\n$\\nicefrac{a}{R_\\star} = 3.16$\nplanet \\citep{Wong2019}. Assuming zero eccentricity and ignoring any\nstellar oblateness\n\\citep[see][]{Ahlers2020},\nthe day/night terminator extends $\\tau \\approx 17^\\circ$ past the limb\nof that planet. Figure~\\ref{fig:extended} shows the illumination profile\nof this planet in a Mollweide projection, with the sub-stellar point at\nthe center, for the point source approximation (left) and accounting for\nthe finite size of the star (right). In addition to the\ndisplaced day/night terminator, the main difference between\nthe two profiles is the sub-stellar intensity, which is significantly higher\nin the extended source case. This is due to the simple fact that in the point\nsource case the illumination source is placed at the center of the star,\nwhich is one stellar radius farther from the planet than the point closest\nto the planet (the sub-planetary point) in the extended source case.\nOnce accounting for this difference, the fractional change in the intensity\non the planet away from the sub-stellar point is similar in both cases,\nand the intensity anywhere beyond $\\nicefrac{\\pi}{2}$ is less than one-tenth\nthe peak value.\n\n\\begin{figure}[t!]\n    \\begin{centering}\n        \\includegraphics[width=\\linewidth]{figures/extended.pdf}\n        \\oscaption{extended}{%\n            Normalized surface intensity on Kelt-9b viewed in a\n            Mollweide projection assuming a point illumination source\n            (left) and accounting for the finite extent of the star\n            (right). The day/night terminator extends about $17^\\circ$\n            past where it is in the point source case. The sub-stellar\n            intensity is higher in the extended source case because the\n            sub-planet point on the star is\n            closer to the planet than in the case where the star is a point\n            source located at the center of the star.\n            \\label{fig:extended}\n        }\n    \\end{centering}\n\\end{figure}\n\nThe illumination profile in the extended source case may be computed as the\ntwo-dimensional integral of the point source illumination profile over\nthe visible portion of the stellar disk. While this integral may in theory be\ncomputed analytically\n\\citep[see, for instance,][who derived series solutions to this problem]{Kopal1954},\nthe resulting profile on the planet surface\nwill not in general be exactly expressible in terms of spherical harmonics, a\nnecessary condition for the \\starry algorithm.\nFor simplicity, we therefore compute the illumination profile for\nextended sources by averaging the contribution of \\textsf{source\\_npts} point\nsources uniformly distributed across the projected disk corresponding to\nthe portion of the stellar surface\nvisible from the planet, where \\textsf{source\\_npts} is a user-supplied\nvalue. In the limit $R_\\mathrm{p} \\ll R_\\star$, this is a spherical cap centered at\nthe sub-planet point with radius $R_\\star \\cos\\tau$. In\nFigure~\\ref{fig:extended} we set\n\\textsf{source\\_npts} = 300, but in practice we find that ${\\sim}30$\npoints are sufficient for even the most extreme cases such as Kelt-9b.\n%\nNote, importantly, that while this method allows one to account for the\neffect of stellar limb darkening on the illumination profile of the planet,\nthis has not been implemented in \\starry.\n\n\\begin{figure}[p!]\n    \\begin{centering}\n        \\includegraphics[width=\\linewidth]{figures/kelt9b.pdf}\n        \\oscaption{kelt9b}{%\n            Reflected light phase curve model for Kelt-9b, assuming\n            a spherical albedo $A = 0.2$. The transit (phase zero)\n            is not included. Blue is the \\starry model\n            assuming a point source illumination; purple accounts for\n            the finite size of the star.\n            The left panel shows the two models in parts per million\n            of the stellar flux; the right panel shows the models\n            normalized so their maximum value is unity.\n            The primary effect of the extended source size is to\n            increase the planet flux near full phase, since the stellar\n            surface is on average slightly closer to the planet, and\n            to change the overall curvature of the phase curve.\n            The shape of secondary eclipse, however, is relatively\n            insensitive to the point source approximation\n            (see Figure~\\ref{fig:kelt9b_eclipse}).\n            \\label{fig:kelt9b}\n        }\n    \\end{centering}\n\\end{figure}\n%\n\\begin{figure}[p!]\n    \\begin{centering}\n        \\includegraphics[width=\\linewidth]{figures/kelt9b_eclipse.pdf}\n        \\oscaption{kelt9b}{%\n            Normalized reflected light secondary eclipse model for Kelt-9b,\n            assuming a spherical albedo $A = 0.2$. Blue is the \\starry model\n            assuming a point source illumination; purple accounts for\n            the finite size of the star. The orange curves show\n            approximate models computed using the \\citet{MandelAgol2002}\n            model: a sphere of uniform intensity (solid orange)\n            and a sphere whose intensity falls as the cosine of the\n            viewing angle from the center of the planet disk\n            (dashed orange).\n            Because Kelt-9b is so close to its host star, the illumination\n            phase changes significantly from ingress to egress, and neither\n            approximation accurately captures the behavior of the light curve.\n            On the other hand, the point source approximation agrees well with\n            the extended source solution, modulo the difference in\n            the depth (see Figure~\\ref{fig:kelt9b}).\n            \\label{fig:kelt9b_eclipse}\n        }\n    \\end{centering}\n\\end{figure}\n\nFigure~\\ref{fig:kelt9b} shows the practical implications of the finite\nstellar size for the phase curve of Kelt-9b. The left panel shows the\nreflected light phase curve of the planet in parts per million, assuming\na spherical albedo of 0.2, for the point source approximation\n(blue) and including the effect of the extended source with\n\\textsf{source\\_npts} = 300 (purple). The increased\nillumination at the sub-stellar point results in a ${\\sim}30$ ppm increase\nin the value of the phase curve close to full phase ($\\pm\\nicefrac{1}{2}$).\nClose to a phase of zero, the extended source results in decreased\nflux, since the portion of the star illuminating the planet (the region\nclose to the limb) is slightly\n\\emph{farther} away, by a factor of\n$\\sqrt{1 + (\\nicefrac{a}{R_\\star})^{-2}}$. This results in a steeper\nphase curve, which can be seen in the right panel, where the light curves\nhave been normalized to their maximum value.\n\nWhile modeling the extended size of the star is essential to\ngetting the shape of the phase curve correct, the same is not true\nfor secondary eclipse. Figure~\\ref{fig:kelt9b_eclipse} shows\nthe normalized secondary eclipse model for Kelt-9b under the point\nsource approximation (blue) and the extended source model (purple).\nNeglecting the fact that the \\emph{depth} of secondary eclipse is\nsignificantly different between the two models (see the left panel\nof Figure~\\ref{fig:kelt9b}), the difference in \\emph{shape} between\nthe two curves is almost negligible.\n%\nFor reference, the figure shows\ntwo additional models one might consider using to fit a secondary\neclipse light curve: a uniform (unilluminated) disk (solid orange)\nand a disk whose intensity falls as $\\upmu$, the cosine of the\nviewing angle (dashed orange). Both can be computed using the\nclassical \\citet{MandelAgol2002} transit model; the latter corresponds\nto a linearly limb-darkened sphere and is functionally equivalent to\na Lambertian sphere seen at full phase.\nHowever, neither approximation is particularly good, since Kelt-9b\nchanges illumination phase significantly from ingress to egress\nowing to its proximity to the star.\n\n% HACK\n\\pagebreak\n\n\\subsection{Non-Lambertian scatterers}\n\\label{sec:nonlambertian}\n\nThe second assumption we now seek to relax is that of Lambertian\nscattering. A perfect Lambert sphere reflects light isotropically, so\nthe measured intensity at a point on the surface is strictly\nproportional to the product of the cosine of the angle of incidence\nand the cosine of the viewing angle. While this is convenient\nfrom a modeling standpoint, it is hardly ever true in practice.\nFor planets and moons in particular, there is often a strong phase\ndependence in the scattering. Rayleigh scattering in planetary\natmospheres is preferentially in the forward/backward direction,\nwhile clouds and oceans can contribute strong specular reflection.\nMoreover, rough surfaces can have complex scattering behavior due\nto changes in the orientation of the surface normal on small scales\nand effects such as multiple reflections and self-shading.\n\n\\begin{figure}[t!]\n    \\begin{centering}\n        \\includegraphics[width=0.5\\linewidth]{figures/scattering.pdf}\n        \\oscaption{scattering}{%\n            Scattering geometry for non-Lambertian reflection. Based on\n            Figure~3 of \\citet{OrenNayar1994}. The incident radiation\n            is labeled $\\mathbf{s}$ and the outgoing radiation is\n            labeled $\\mathbf{v}$. The shaded region is a small patch\n            of surface, oriented so that the normal vector points along\n            $\\hat{z}$. The four angles relevant to the computation of\n            the emergent intensity are also indicated.\n            \\label{fig:scattering}\n        }\n    \\end{centering}\n\\end{figure}\n\nIn principle, any of these processes can be accounted for in\nthe \\starry algorithm by modifying the linear operator\n$\\mathbf{I}$ (Equation~\\ref{eq:Imat}), which in the Lambertian\ncase simply weights the spherical harmonic expansion of the albedo\nby the cosine-like illumination profile to obtain the observed\nintensity at a point on the surface\n(see Equations~\\ref{eq:sTA2IA1RRy} and \\ref{eq:rTIA1RRy}).\nFor non-Lambertian scattering, this matrix must also account for\nthe phase dependence of the reflection: in particular, it will depend\nnot only on the angle between the surface normal and the incident\nradiation, $\\vartheta_\\mathrm{i}$, but also on the angle between the surface\nnormal and the reflected radiation (i.e., the direction toward the\nobserver), $\\vartheta_\\mathrm{r}$. It may also depend on the azimuthal angles\nof the incident and reflected rays, $\\phi_\\mathrm{i}$ and $\\phi_\\mathrm{r}$, respectively.\nThese four angles are shown in Figure~\\ref{fig:scattering}, showing\nthe incoming radiation (source) vector $\\mathbf{s}$ and the outgoing\nradiation (viewer) vector $\\mathbf{v}$ in a frame in which the $z$-axis\npoints along the surface normal.\n\nTreatment of a generalized, flexible scattering model is beyond the scope\nof this paper; see \\citet{Heng2021} for recent results on this front.\nHowever, as an example of how a scattering model may be\nincorporated\ninto the \\starry algorithm, we consider in detail the case of the rough surface\nscattering model of \\citet{OrenNayar1994}, commonly used in computer\ngraphics applications and solar system body modeling\n\\citep[e.g.,][]{Morgado2019}. In this model, the surface is treated as a\ncollection of a large number of Lambertian facets oriented at random\nangles relative to the average surface normal, whose net contribution to\nthe total intensity can depart significantly from the Lambertian case.\nWhile the general model accounts for interreflections, shadowing, and\nan arbitrary distribution of facet orientations, in its simplest form\nthe intensity observed at a point $(x, y)$ on the (projected) surface of a\nbody of unit spherical albedo may be approximated as\n\\citep[c.f. Equation~30 in][]{OrenNayar1994}\n%\n\\begin{proof}{OrenNayar}\n    \\label{eq:OrenNayar}\n    \\mathcal{I} & =\n    \\mathcal{I}_\\text{Lamb}\n    \\bigg\\{ c_0 + c_1 \\, \\text{max}\\Big( 0, \\, \\cos(\\phi_\\mathrm{r} - \\phi_\\mathrm{i}) \\Big)\n    \\sin \\alpha \\tan \\beta\n    \\bigg\\}\n\\end{proof}\n%\nwhere%\n%\n\\\\\n\\begin{minipage}{.5\\linewidth}\n    \\begin{align}\n        c_0 & = 1 - 0.5 \\left(\\frac{\\sigma^2}{\\sigma^2 + 0.33}\\right)\n        \\nonumber                                                     \\\\\n        c_1 & = 0.45 \\left(\\frac{\\sigma^2}{\\sigma^2 + 0.09}\\right)\n        \\nonumber\n    \\end{align}\n\\end{minipage}%\n\\begin{minipage}{.49\\linewidth}\n    \\begin{proof}{OrenNayar}\n        \\alpha & = \\text{max}\\Big( \\vartheta_\\mathrm{r}, \\, \\vartheta_\\mathrm{i} \\Big)\n        \\nonumber                                                    \\\\\n        \\beta  & = \\text{min}\\Big( \\vartheta_\\mathrm{r}, \\, \\vartheta_\\mathrm{i} \\Big)\n    \\end{proof}\n\\end{minipage}\n\\\\[1em]\nand the angles $\\vartheta_\\mathrm{i}$, $\\vartheta_\\mathrm{r}$, $\\phi_\\mathrm{i}$, and $\\phi_\\mathrm{r}$ are all\nimplicit functions of $x$, $y$, and the illumination source position.\nThe term $\\mathcal{I}_\\text{Lamb}$ is the Lambertian illumination profile,\ngiven by Equation~(\\ref{eq:LambertsLaw}).\n%\nAt a given point on the surface, and for a given source position,\nthe intensity $\\mathcal{I}$ is therefore a function of a single\nparameter, $\\sigma$, defined as the standard deviation in radians of the\ndistribution of facet angles (which is assumed to be a zero-mean Gaussian).\n\n\\begin{figure}[t!]\n    \\begin{centering}\n        \\includegraphics[width=\\linewidth]{figures/oren_nayar.pdf}\n        \\oscaption{oren_nayar}{%\n            Intensity measured from a sphere at varying illumination\n            phase under the \\citet{OrenNayar1994} scattering model.\n            The top panel shows spheres rendered with different surface\n            roughness coefficients ranging from $\\sigma = 0^\\circ$\n            (the Lambertian case) to $\\sigma = 45^\\circ$. The bottom\n            panel shows the corresponding phase curves for a sphere\n            of unit spherical albedo illuminated by a point source, computed\n            analytically from a degree \\STARRYORENNAYARDEG expansion\n            of the scattering law. Dots\n            correspond to the intensity computed numerically directly\n            from Equation~(30) in \\citet{OrenNayar1994}.\n            \\label{fig:oren_nayar}\n        }\n    \\end{centering}\n\\end{figure}\n\nIn order to incorporate this scattering model into \\starry, we must weight\nthe spherical harmonic expansion of the albedo, $\\mathbf{y}$, by\nEquation~(\\ref{eq:OrenNayar}) instead of Equation~(\\ref{eq:LambertsLaw}).\nWeighting by Equation~(\\ref{eq:LambertsLaw}) is (relatively) straightforward,\nsince $\\mathcal{I}_\\text{Lamb}$ is a piecewise function of the $l=1$ spherical\nharmonics (see Appendix~\\ref{sec:adapting-starry}).\nThe function we must integrate when computing fluxes is therefore\nexactly expressible in terms of spherical harmonics and thus\n\\starry-integrable. However, Equation~(\\ref{eq:OrenNayar}) cannot be expressed\nexactly in terms of spherical harmonics, so we must instead approximate it.\nTo this end, we evaluate Equation~(\\ref{eq:OrenNayar}) on a\ngrid of $x$ and $y$ spanning the unit disk, as well as the illumination phase,\nparametrized by $b$, the semi-minor axis of the elliptical segment defining\nthe day/night terminator (see Appendix~\\ref{sec:adapting-starry}).\nWe then fit to this a polynomial of total degree \\STARRYORENNAYARDEG\nin $x$, $y$, and $z \\equiv \\sqrt{1 - x^2 - y^2}$ and degree\n\\STARRYORENNAYARNB in $b$ and degree \\STARRYORENNAYARNBC in\n$b_\\mathrm{c} \\equiv \\sqrt{1 - b^2}$.\n%\nThen, for a given value of $b$ and $b_\\mathrm{c}$, we construct the operator\n$\\mathbf{I}$ out of the polynomial coefficients in the same way as we\nconstructed the Lambertian operator in Appendix~\\ref{sec:adapting-starry}.\n%\nMore details about our approximation can be found in the Jupyter notebook\naccompanying Equation~(\\ref{eq:OrenNayar}).\n\nFigure~\\ref{fig:oren_nayar} shows spheres of unit albedo\nwith different surface roughness\ncoefficients $\\sigma$ and their corresponding phase curves.\nThe sphere in the top row is perfectly Lambertian; its phase curve (blue)\npeaks at a value of $\\nicefrac{2}{3}$, equal to the geometric albedo\nof a Lambert sphere. Increasing the surface roughness results in a greater\nrelative contribution of flux from the limb of the object near full\nphase, since there now exist facets reflecting light directly back toward the\nobserver (remaining rows and curves in the phase curve plot).\nConversely, less light is scattered\nback to the observer at the\nsub-illumination point. These competing effects lead to phase curves that\npeak at a super-Lambertian value for small roughness\ncoefficients ($\\sigma = 15^\\circ$, orange) and at a sub-Lambertian value for\nlarge roughness coefficients ($\\sigma = 45^\\circ$, red).\n%\nWe validate our calculations by computing the phase curves by numerically\nintegrating the \\citet{OrenNayar1994} model over the visible disk; these\nare shown as the small dots in the figure, which agree to within\n$350$ ppm of the body's flux for $\\sigma = 45^\\circ$.\n\n\\begin{figure}[t!]\n    \\begin{centering}\n        \\includegraphics[width=\\linewidth]{figures/io_europa.pdf}\n        \\oscaption{io_europa}{%\n            Visible-light occultation of Io by Europa observed\n            on 04 Dec 2009 by the PHEMU09 campaign \\citep{Arlot2014}.\n            The blue line is the \\starry model, based of an\n            $l=15$ spherical harmonic fit to the\n            Galileo global color mosaic of Io \\citep{Becker2005},\n            an $l=\\STARRYORENNAYARDEG$ expansion of the\n            \\citet{OrenNayar1994} scattering law, and orbital\n            information from the JPL Horizons database.\n            See text for details.\n            \\label{fig:io_europa}\n        }\n    \\end{centering}\n\\end{figure}\n\nOur implementation of the scattering model extends just as easily\nto occultations and to cases where the surface does not have uniform albedo.\nFigure~\\ref{fig:io_europa} shows a visible-light observation of the\noccultation of Io by Europa on 04 Dec 2009 taken by the PHEMU09\ncampaign \\citep{Arlot2014}. The trajectory of Europa relative to Io,\ncomputed from the \\href{https://ssd.jpl.nasa.gov/horizons.cgi}{JPL Horizons database}\nusing ephemerides from \\citet{Folkner2014}\nis shown at the top. We fit to this data a \\starry occultation model\nwith the scattering law discussed above.\nFor simplicity, we set the surface map equal too\nan $l=15$ spherical harmonic expansion of the Galileo global color mosaic\nof Io \\citep{Becker2005} and use ephemerides from the JPL Horizons\ndatabase, allowing for a small static $x-y$ offset between Europa and Io as\nin \\citep{Arlot2014} due to the uncertainty in the database. In total,\nwe fit for five parameters: the two Cartesian offset terms,\nthe flux contribution from Europa, the average\nalbedo of Io, and the average surface roughness of Io, $\\sigma$. The model\nis displayed in blue and closely matches the data.\n%\nNote, however, that this is meant simply as a demonstration of the \\starry\nalgorithm, as our model for the surface is approximate at best, given\ndifferences in the wavelength band between the Galileo observations and\nthose of the PHEMU09 campaign, changes in the albedo of Io since the Galileo\nmeasurements, and the fact that the orientation and extent of any shadows\ndue to volcanoes on the surface are likely different between the Galileo\nand PHEMU09 observations. Furthermore,\nproper modeling would entail the\njoint analysis of all light curves of Io taken in a given season, for which\nwe can afford to simultaneously fit for the surface map without risk of\noverfitting \\citep{Bartolic2021}.\n\n\\section{Discussion}\n\\label{sec:discussion}\n\n\\subsection{Linearity}\n\\label{sec:linearity}\n\nIn the Appendix we derive closed-form expressions for the flux\nas a function of the spherical harmonic expansion of the albedo,\n$\\mathbf{y}$: Equation~(\\ref{eq:sTA2IA1RRy}) for occultations and\nEquation~(\\ref{eq:rTA1Ry}) for phase curves. Inspection of those\nequations reveals that they are both \\emph{linear} in $\\mathbf{y}$:\nthe flux is simply the dot product of several matrices and the\nvector of spherical harmonic coefficients. We may therefore write\nboth expressions in the form\n%\n\\begin{align}\n    f = \\mathbf{x}^\\top \\mathbf{y}\n\\end{align}\n%\nwhere $f$ is a scalar representing the model for the flux at a particular\npoint in time and $\\mathbf{x}^\\top$ is a row vector equal to\n$\\sT\\mathbf{A_2}\\mathbf{I}\\mathbf{A_1}\\mathbf{R'}\\mathbf{R}$\n(in the case of an occultation)\nor\n$\\rT\\mathbf{I}\\mathbf{A_1}\\mathbf{R''}\\mathbf{R}$\n(in the case of a phase curve; see Appendix~\\ref{sec:adapting-starry}\nfor details on what each of the terms represent). Now, if we let $\\mathbf{f}$\nbe the vector of values of $f$ for each point in the timeseries and\nconstruct the matrix $\\mathbf{X}$ out of the stacked row vectors\n$\\mathbf{x}^\\top$, we may write our model for the entire timeseries as\nthe dot product\n%\n\\begin{align}\n    \\mathbf{f} = \\mathbf{X} \\mathbf{y}\n    \\quad.\n\\end{align}\n%\nThe linearity of the \\starry model is useful in several ways. For one,\nit can be exploited to cheaply compute the same model for different\ninput vectors $\\mathbf{y}$. This is useful for multi-band light curves,\nwhere the same matrix $\\mathbf{X}$ dots into several vectors $\\mathbf{y}$,\none for each observation band, or for time-dependent models, in which\nthe model for the flux might be the Taylor series\n%\n\\begin{align}\n    \\mathbf{f} =\n    \\mathbf{X}\n    \\bigg(\n    \\mathbf{y}(t)\\bigg|_{t=t_0} +\n    \\frac{\\dd\\mathbf{y'}(t)}{\\dd t}\\bigg|_{t=t_0} t +\n    \\frac{1}{2}\\frac{\\dd^2\\mathbf{y'}(t)}{\\dd t^2}\\bigg|_{t=t_0} t^2 +\n    \\cdots\n    \\bigg)\n    \\quad,\n\\end{align}\n%\nwhere $\\mathbf{y}(t)$ is a time-dependent representation of the surface\nmap, which we expand about $t=t_0$ \n\\citep{Luger2019b}; \\textbf{see also \\citealt{Kawahara2020b} for an alternative linear model for time-dependent maps}.\nBut perhaps even more importantly, linear\nmodels are particularly useful for inference, since under Gaussian\nnoise properties the posterior is analytic. In particular, if\nour light curve measurements are given by the data vector $\\mathbf{d}$\nwhose noise model is specified by the covariance matrix $\\pmb{\\Sigma}$,\nand we place a Gaussian prior on $\\mathbf{y}$ with mean $\\pmb{\\mu}$ and\ncovariance $\\pmb{\\Lambda}$, the posterior mean may be written\n%\n\\begin{align}\n    \\label{eq:posterior_mu}\n    \\hat{\\bvec{y}} & =\n    \\bvec{C}\n    \\left(\n    \\mathbf{X}^\\top\n    \\pmb{\\Sigma}^{-1}\n    \\bvec{d}\n    +\n    \\pmb{\\Lambda}^{-1}\n    \\pmb{\\mu}\n    \\right)\n    \\quad,\n\\end{align}\n%\nwhere $\\bvec{C}$ is the posterior covariance, given by\n%\n\\begin{align}\n    \\label{eq:posterior_cov}\n    \\bvec{C} & =\n    \\left(\n    \\mathbf{X}^\\top\n    \\pmb{\\Sigma}^{-1}\n    \\mathbf{X}\n    +\n    \\pmb{\\Lambda}^{-1}\n    \\right)^{-1}\n    \\quad.\n\\end{align}\n%\nBecause of this linearity, and the analyticity of the \\starry\nmodel, inference on datasets comprising thousands of points and\nspherical harmonic degree $l \\leq 20$ takes a\n\\emph{fraction of a second} on a typical computer.\n\\textbf{Full posterior inference with \\starry can thus be faster than\n    the numerical evaluation of a single forward model}\n(c.f. Figure~\\ref{fig:speed}).\n\nIt is important to note, however, that the \\starry model is linear\nonly in the map coefficients $\\mathbf{y}$. In any real application,\nthere will be uncertainty in the inputs of $\\mathbf{X}$, such\nas the orbital parameters, the occultor parameters, the scattering\nlaw, etc. These parameters must typically be sampled over, since the model\nis a nonlinear function of them. However, the analyticity---and in particular,\nthe differentiability---of the \\starry model makes sampling via\ngradient-based MCMC easy. Moreover, the linearity of the model\nwith respect to $\\mathbf{y}$ allows one to efficiently marginalize over\nthose parameters when sampling over the nonlinear parameters.\nTutorials on how to do this can be found in the\n\\starry \\href{https://starry.readthedocs.io}{documentation}.\n\n\\subsection{The information content of reflected light curves}\n\\label{sec:information}\n\nOne of the fundamental difficulties with the mapping problem is that\nthe process of inferring a two-dimensional map from a light curve\nis almost always ill-posed. This has been known since at least\nthe turn of the last century, when \\citet{Russell1906} discussed\nhow, because of symmetry,\nall odd harmonics above $l = 1$ are in the null space for thermal\nphase curves of spherical bodies, meaning those terms do not contribute\nat all to the disk-integrated flux. As discussed in \\citet{Luger2019}\nand \\citet{PaperI},\nthe problem is even more ill-posed than that: for any even\ndegree $l > 0$, there are $2l + 1$ modes on the \\emph{surface}\n(one for each value of $m$), but only $2$ Fourier modes in the\n\\emph{light curve} (i.e., a sine and a cosine). Thus, for every\nmode that can be constrained from the light curve, there are far\nmore modes that cannot, a problem that only gets worse as $l$\nincreases.\n\n\\begin{figure}[t!]\n    \\begin{centering}\n        \\includegraphics[width=\\linewidth]{figures/inference.pdf}\n        \\oscaption{inference}{%\n            Example of an inference problem for a thermal phase curve\n            (center left) and a reflected phase curve (center right).\n            In both cases,\n            a mock phase curve is generated from an $l=20$ expansion\n            of the cloudless Earth (top) with 1,000 evenly spaced points\n            over the course of one year and an extremely small\n            photometric uncertainty of 1 ppm. The observer sits along the\n            ecliptic and the obliquity of the Earth is set to $23.5^\\circ$.\n            Data is shown as the black points, and the maximum likelihood\n            \\starry model is shown in blue. While both models fit the\n            data equally well, the same is not true of the inferred\n            surface maps (bottom row): only in the reflected case are the\n            continental outlines recovered.\n            The thermal phase curve problem is\n            extremely ill-conditioned, but the analogous problem in reflected\n            light is much better posed.\n            \\label{fig:inference}\n        }\n    \\end{centering}\n\\end{figure}\n\nThe left panel of Figure~\\ref{fig:inference} shows this issue in practice.\nWe generate a mock thermal light curve (center left) from an $l = 20$\nexpansion of the Earth (top) with 1,000 points over the course of one year\nwith an exquisite photometric precision of 1 ppm. The Earth is given\nan obliquity of $23.5^\\circ$ on the plane of the sky but is viewed\nalong the ecliptic, rotating edge-on with an inclination of $90^\\circ$.\nThe data are shown in black, and in blue is the posterior mean model\n(Equation~\\ref{eq:posterior_mu}),\nin which we assume a prior variance of $10^{-3}$ for all spherical\nharmonic coefficients (and zero covariance).%\n\\footnote{%\n\\textbf{This choice is equivalent to assuming a flat prior on the power spectrum \nwith power $10^{-3}$ in each degree $l$ of the surface map.\nThis particular value is roughly the average power per degree in the input\nmap, although the results in the figure are not sensitive to this choice.\nFor a detailed discussion of how to set one's priors in a realistic setting in \nwhich the true map is not known, see \\citet{PaperIII}.}\n} \nThe corresponding surface\nmap is shown at the bottom. As expected, this looks nothing like the\ntrue map of the Earth. For a body seen rotating edge-on, the information\ncontent of the light curve is strictly longitudinal. While the\ninferred map captures the average brightness of the Earth at each\nlongitude fairly well, it is missing all latitudinal information.\nThis is independent of the signal-to-noise or the cadence of the\ndataset---it is a fundamental limitation of phase curves in thermal light.\n\nThe same is not true for the case of reflected light phase curves. In\nthe right panel of Figure~\\ref{fig:inference} we show the same\nmock light curve and perform the same inference step,\nbut this time for observations in reflected light; the light curve\nis similar to that in Figure~\\ref{fig:earthphase}. Because of the\npresence of a day-night terminator beyond which features on the surface\ncontribute zero flux, none of the symmetry arguments above apply. In\nparticular, the facts that (1) the Earth is seen at different phases and\n(2) the terminator is inclined relative to the rotational axis mean\nthat the region of the surface contributing to the phase curve is\nalways changing, resulting in a complex light curve that encodes\nsignificantly more information than its thermal counterpart.\n%\nThe result is an inferred map that is largely faithful to the\ntrue map (bottom). While the continental outlines are somewhat fuzzy and some\nartifacts are present at high latitudes, it is clear that the\ninference problem is much less ill-posed in this case.\n\nUnlike thermal light curves, reflected light phase curves have the\npotential to robustly constrain two-dimensional maps of exoplanets.\nThis result is\nnot new, and has been discussed at length in the literature\n\\citep[e.g.,][]{Fujii2012,Berdyugina2017,Luger2019b,Aizawa2020,Kawahara2020}.\nIn particular, \\citet{Kawahara2010} demonstrated the uniqueness of their\ninferred map from mock reflected light curves of the Earth. As we argued\nabove, for specific geometrical configurations, the mapping problem\nin reflected light can actually be well-posed, meaning it has no\nnull space up to a certain degree $l$. Reflected light phase curves of\nterrestrial planets with JWST and future direct imaging missions thus\nhave the potential to reveal detailed information about their surfaces.\n\n\\begin{figure}[p!]\n    \\begin{centering}\n        \\includegraphics[width=\\linewidth]{figures/inference_occ.pdf}\n        \\oscaption{inference_occ}{%\n            Similar to Figure~\\ref{fig:inference}, but for 500 high\n            signal to noise observations taken\n            over ten days near quadrature.\n            At the top we show the thermal and reflected\n            phase curves and the corresponding inferred maps.\n            At the bottom, we show the same light curves but this\n            time including 7 equatorial occultations by\n            a (very) short period moon one-quarter the size of the planet.\n            %\n            The presence of the occultations significantly increases the\n            fidelity of the recovered maps near the equator (the path\n            of the occultor). While in the thermal case there is significant\n            overfitting at high latitudes, in the reflected case the map\n            accurately recovers features across the entire planet.\n            \\label{fig:inference_occ}\n        }\n    \\end{centering}\n\\end{figure}\n\nNevertheless, at finite signal to noise and for limited observation\nduration or cadence, there may still be significant degeneracies in\nthe reflected phase curve problem. In \\citet{Luger2019} we argued that\noccultations can be used to break many of these degeneracies, since they\ndirectly probe the surface at scales inaccessible to phase curves.\nThe same is true in reflected light. Figure~\\ref{fig:inference_occ}\ndemonstrates this for mock observations of the same Earth-like\nplanet as in Figure~\\ref{fig:inference}, but this time taken\nover ten days near quadrature, when the disk of the planet is seen at\nhalf phase. The top rows show the thermal and reflected phase\ncurves and the inferred maps, which look similar to those in\nthe previous figure.\nAt the bottom we show the same light curve, but this time including\nseven equatorial occultations by a moon one-quarter the size of the planet.\nThe moon's period and occultation duration are unrealistically short, but\nthe inferred maps at the bottom show the exquisite constraining power of these\noccultations.\nIn the thermal case, the presence of the moon allows us to infer the\ntwo-dimensional distribution of surface features along its equatorial\noccultation path; however, there is little information\nin the light curve about features at higher latitudes, and the \\starry model\noverfits. Conversely, in the reflected light case, there is information\nabout all latitudes and longitudes, and the inferred map is\nlargely faithful to the true map.\n\nIt should be kept in mind that the kinds of observations\nmentioned above will be very challenging for exoplanets, even with\nnext-generation observatories such as HabEx or LUVOIR. Observations of\noccultations of planets by moons, in particular, are likely several decades\naway at least. There is some hope that planet-planet occultations may\nbe detectable in the near future for specific planetary\nsystems such as TRAPPIST-1\n\\citep{Luger2019b}, but at extremely limited signal-to-noise.\nEven phase curve observations will be difficult\nbecause of their limited signal-to-noise, and in practice many\ndegeneracies will likely remain. Several studies have found\nthat color information can greatly help in the interpretation of\nreflected phase curves \\citep{Cowan2009,Kawahara2011,LustigYaeger2018,Kawahara2020}, while others\nhave explored in detail the best kinds of priors to assume\n\\citep[e.g.,][]{Aizawa2020,AsensioRamos2021}. Future maps of exoplanets---particularly\nterrestrial ones in the habitable zone---will require every tool\nin the toolbox.\n\n\\subsection{Limitations}\n\\label{sec:limitations}\n\nThere are a few limitations to the \\starry model that are important\nto bear in mind. The primary limitation concerns the maximum spherical\nharmonic degree of the model. While the expressions derived here are\nvalid at arbitrary degree, we find that their numerical stability quickly\ndegrades above $l \\sim 20-25$ for occultations and $l \\sim 35-40$ for phase\ncurves. The same is true for the model in thermal light \\citep{Luger2019},\nand is due to (1) the large condition number of the change-of-basis matrix\nfrom spherical harmonics to polynomials and (2) instabilities in the\nmany recursion relations used to evaluate the solution vectors\n$\\sT$ and $\\rT$.\nIn principle, one could improve the numerical stability by evaluating\nall expressions at higher floating-point precision, but in practice\nthe computational cost of this becomes quickly prohibitive.\nHowever, it is important to keep in mind that our current best image\nof an exoplanet is the $l=1$ map of HD189733b\n\\citep{Knutson2007,Majeau2012,deWit2012}. Next-generation facilities\nsuch as JWST may allow us to probe surface modes as small as $l=5$\nfor some planets (Luger et al., \\emph{in prep}), but even with future\ntelescopes such as LUVOIR it is extremely unlikely we will do better than\n$l=20$. If cases arise requiring a resolution smaller than about\n$180^\\circ / 20 = 9^\\circ$ on the surface, the \\starry algorithm\nwill have to be revisited.\n\nThe second limitation concerns the flexibility of the \\starry model.\nWhile we presented ways to capture non-Lambertian scattering\nin \\starry (\\S\\ref{sec:nonlambertian}), there are certain aspects\nof light curves in reflected light that cannot be captured by the model.\nOne example of this is shadowing. Craters on the moon or\nvolcanoes on Io can cast large shadows visible from space, particularly\nif viewed near crescent phase. Unfortunately, there is no way to model\nthis within the \\starry framework. Another example is multiple scattering,\nas in optically thick atmospheres, for which a proper radiative transfer model\nmust be used. There is also the case of specular reflection,\nor ``glint'', which is a pronounced signal for the Earth due its\noceans \\citep{Robinson2014} and on Titan due to\nits hydrocarbon lakes \\citep{Barnes2011}. In principle, glint could be\nmodeled in the same way as non-Lambertian sccattering, by constructing the\nlinear operator $\\mathbf{I}$ in such a way as to downweight portions of the\nprojected disk where $\\vartheta_\\mathrm{i} \\neq \\vartheta_\\mathrm{r}$. In practice, however,\nif the size of the glint spot is small (which is typically the case),\nan expansion at extremely high $l$ ($l \\sim 360$ in the case of the Earth)\nwould be required, which would not work for the reasons above.\nInstead, it may be possible to combine the \\starry algorithm with the\nformalism of \\citet{Haggard2018}, who derived analytic expressions for\nphase curves of delta function maps ($\\delta$-map), to model glint.\nAs discussed in \\citet{LustigYaeger2018}, glint mapping is an extremely\npowerful way to not only map terrestrial planets but also to confirm\ntheir habitability via the presence of an ocean.  Lastly, the presence\nof time-variable features, such as clouds, dust storms, or seasonal\nvariations of vegetation are not accounted for in the model, although\nthe \\href{https://starry.readthedocs.io}{documentation} discusses\nhow one may approach the modeling of temporal features.\n\nWe would also like to emphasize that while spherical harmonics are\na convenient basis for the purpose of computing light curves, they\nhave a significant drawback when it comes to modeling real planetary\nsurfaces: it can be difficult to strictly enforce physical\nvalues of the albedo everywhere on the surface map when doing inference.\nThat is because there is no analytic way to determine whether a\nspherical harmonic representation is positive-valued\n(or restricted to a given range) everywhere on the sphere.\nInstead, this must be checked numerically, by evaluating the function on a\ndiscrete grid. This makes it somewhat cumbersome to implement positivity as a prior\nwhen doing inference; in particular, this prior cannot be expressed as\na Gaussian, so the analytic expression for the posterior\ndiscussed in \\S\\ref{sec:linearity} will generally have nonzero support for\nnegative albedo values. This is particularly problematic when the data is\nnot very constraining and the posterior is prior-dominated, as\npositivity can be an \\emph{extremely} informative prior\n\\citep[e.g.,][]{Fienup1978}.\nWe therefore recommend that in such cases\nusers of the \\starry algorithm use HMC/MCMC to do inference, either\n(1) sampling over the spherical\nharmonic coefficients $\\mathbf{y}$ and imposing a uniform prior in the range\n$[0, 1]$ on the albedo values $\\mathbf{a}$\nevaluated on a discrete grid on the sphere or\n(2) sampling over the albedo values $\\mathbf{a}$ with the same uniform prior,\nbut using $\\mathbf{y}$ to compute the actual light curve model\n\\citep{Bartolic2021}. In both\ncases, there exists a linear operator that transforms between\n$\\mathbf{y}$ and $\\mathbf{a}$:\n%\n\\begin{align}\n    \\label{eq:Py}\n    \\mathbf{a} = \\mathbf{P} \\mathbf{y}\n\\end{align}\n%\nand\n%\n\\begin{align}\n    \\label{eq:PInvy}\n    \\mathbf{y} = \\mathbf{P}^+ \\mathbf{a}\n    \\quad,\n\\end{align}\n%\nwhere\n%\n\\begin{align}\n    \\label{eq:PInv}\n    \\mathbf{P}^+ =\n    (\\mathbf{P}^\\top \\mathbf{P} + \\lambda \\boldsymbol{\\mathsf{I}})^{-1} \\mathbf{P}^\\top\n\\end{align}\n%\nis the pseudoinverse of $\\mathbf{P}$, with (small) regularization parameter\n$\\lambda$ and where $\\boldsymbol{\\mathsf{I}}$ is the identity matrix.\n%\nEach row of the matrix $\\mathbf{P}$ is constructed from the value\nof each of the spherical harmonics at the corresponding point on the\ngrid; both $\\mathbf{P}$ and its inverse may be pre-computed for\nefficiency. In both cases, the grid should be fine enough to ensure\npositivity over most of the sphere but not so fine as to throttle the\ncomputation; as a rule of thumb, we find that grids with ${\\sim}4$ times\nas many pixels\nas spherical harmonic coefficients are sufficient.\n%\nThe \\href{https://starry.readthedocs.io}{documentation}\nincludes tutorials on how to implement this in practice.\n\n%\n\nFinally, while the algorithm presented here can be used to model\nplanet-planet and planet-moon occultations in reflected light, we only\naccount for the physical blocking of light rays from the planet by the occultor;\nwe do not account for the attenuation of the reflected light due to the\n\\emph{shadow} of the occultor on the planet.\nThis can be an important effect at certain orbital phases\n\\citep[e.g.,][]{Cabrera2007}. However, since the shadow of the occultor is not necessarily\ncircular, it is significantly harder to model in closed form. A proper treatment\nof this and other effects, such as occultations and shadows due to rings\n\\citep[e.g.,][]{Arnold2004}, is deferred to future work.\n\n\n\\section{Conclusions}\n\\label{sec:conclusions}\n\nWe have presented an efficient, numerically stable,\nclosed-form algorithm for computing phase curves\nand occultation light curves of spherical bodies in reflected\n(scattered) light.\nThis algorithm is an extension of the algorithm presented\nin \\citet{Luger2019} for light curves in thermal light and\nis generally applicable to exoplanetary phase\ncurves, secondary eclipses, and occultations by moons and other planets,\nas well as to light curves of planets and moons in our solar system.\nWe derive the solution for the case of a Lambert sphere illuminated by a\npoint source, but extend it to the case of an extended illumination\nsource and non-Lambertian scattering parametrized by a surface roughness\ncoefficient.\n%\nThe algorithm is ${\\sim}4-5$ orders of magnitude faster\nand ${\\sim}10$ orders of magnitude more precise than other numerical\napproaches for computing these light curves. The algorithm is\nalso differentiable \\textbf{in all of the model parameters}, \nenabling inference with efficient gradient-based samplers\nsuch as Hamiltonian Monte Carlo (HMC), and linear in the spherical\nharmonic coefficients describing the surface albedo, enabling fast,\nclosed-form solutions for the albedo posterior distribution under a\nGaussian noise model.\n%\nWe implement the algorithm within the \\starry software, an open-source \\Python\npackage for inferring surface maps of unresolved celestial bodies. The\nalgorithm is coded in a combination of \\cpp and \\Python compiled using\nthe \\textsf{theano} package \\citep{theano}. The interface was designed specifically for\ncompatibility with the \\textsf{exoplanet} modeling package\n\\citep{exoplanet} and the \\textsf{pymc3} inference suite \\citep{pymc3}.\n\nUpcoming telescopes will enable measurements of exoplanet phase curves\nand secondary eclipses at unprecendented precision. While the\nJames Webb Space Telescope (JWST) will be primarily sensitive to thermal\nemission from exoplanets (which can currently be modeled with \\starry),\nnext-generation direct imaging facilities such as the\nLarge UV/Optical/IR Surveyor (LUVOIR)\nwill enable measurements in reflected light, in particular for terrestrial\nplanets in the habitable zone. Because of the changing illumination\npattern over the course of an orbit of the planet, phase curves and\noccultation light curves in reflected\nlight contain vastly more information about the two-dimension albedo\ndistribution of the body than their thermal counterparts.\nWith careful modeling, light curves in reflected light are likely to give us\nthe first images of potentially habitable exoplanets, enabling the\ndetection of clouds, continents, oceans, and perhaps even life.\n\n\\vspace{1em}\n\nThe software presented in this work is open source under the MIT License and\nis available at \\url{https://github.com/rodluger/starry}, with documentation\nand tutorials hosted at \\url{https://starry.readthedocs.io}.\nThe code used to generate the figures in this paper is hosted\nat \\url{https://github.com/rodluger/starrynight}.\n% --- TODO ---\n% with a permanent\n% version archived at \\url{https://doi.org/XX.YYYY/zenodo.ZZZZZZZ}.\n\n\\software{\n    astroquery \\citep{astroquery1,astroquery2},\n    Eigen v3 \\citep{eigen},\n    exoplanet \\citep{exoplanet},\n    pybind11 \\citep{pybind11},\n    pymc3 \\citep{pymc3},\n    scipy \\citep{scipy},\n    starry \\citep{starry},\n    theano \\citep{theano}.\n}\n\n\\vspace{1em}\n\nWe would like to thank Nicolas Cowan, Christina Hedges, and the\nAstronomical Data Group at the Center for Computational Astrophysics for\nmany thought-provoking discussions that helped shape this paper.\n\n% Bibliography\n\\bibliography{bib}\n\n\n% APPENDIX\n\\appendix\n\n%\n\n\\section{The Problem}\n\\label{sec:the-problem}\n%\nThis paper closely follows the\nnotation and formalism introduced in \\citet{Luger2019}. While we\ninclude all of the relevant equations and definitions below,\nthe reader is encouraged to\nreview \\citet{Luger2019} before proceeding.\nTo improve the readability of this paper,\nTables~\\ref{tab:symbols}--\\ref{tab:matrices} at the end list the principal\nsymbols and quantities used throughout the text, with links to the\nsections and equations in which they are defined.\nBecause of the large number of symbols used in this paper, we adopt\nthe following conventions: scalars are represented by regular lowercase or\noccasionally uppercase letters (i.e., $x$ or $X$), vectors are\nrepresented by boldface lowercase letters\n($\\mathbf{x}$), and matrices and other linear operators are represented\nby boldface capital letters ($\\mathbf{X}$).\nWith a few exceptions,\nGreek letters are reserved for angular quantities and may be either\nscalars ($\\alpha$) or vectors ($\\pmb{\\alpha}$).\nScript font is typically used to denote curves or frames of reference\n($\\mathcal{F}$). Primes are used to\ndistinguish between frames of reference ($x$ and $x'$ are used\nto denote the same quantity, but in frames $\\mathcal{F}$ and $\\mathcal{F}'$,\nrespectively). Tildes are used to denote basis vectors ($\\by$). Finally,\nblackboard vectors ($\\mathbbb{x}$) correspond to solutions\nto the various ``primitive'' integrals that arise in the occultation\nproblem.\n\n\\subsection{Review of the \\starry algorithm in emitted light}\n\\label{sec:starry-review}\n%\nWithout loss of generality, assume the body whose flux we wish to compute\nhas radius unity and sits at the origin of a right-handed Cartesian coordinate\nsystem in some frame $\\mathcal{F}_0$. In this frame,\nthe surface (emitted) intensity field of the body is described by a\nvector $\\mathbf{y}$ of coefficients in the spherical harmonic\nbasis $\\by$:\n%\n\\begin{align}\n    \\label{eq:by}\n    \\by(x, y) & =\n    \\begin{pmatrix}\n        Y_{0, 0}  &\n        Y_{1, -1} & Y_{1, 0}  & Y_{1, 1} &\n        Y_{2, -2} & Y_{2, -1} & Y_{2, 0} & Y_{2, 1} & Y_{2, 2} &\n        \\cdot\\cdot\\cdot\n    \\end{pmatrix}^\\top\n    \\quad,\n\\end{align}\n%\nwhere the component at index $n$ is the spherical harmonic $Y_{l,m}(x, y)$ with\n%\n\\begin{align}\n    \\label{eq:l-m}\n    l & = \\floor*{\\sqrt{n}}\n    \\nonumber               \\\\\n    m & = n - l^2 - l\n    \\quad.\n\\end{align}\n%\nThe spherical harmonics are traditionally expressed in spherical coordinates,\nbut for our purposes\nit is more conventient to express them in Cartesian coordinates on\nthe sky-projected disk, in which case they are simply polynomials in\n$x$, $y$, and $z$ \\citep[see Appendix~A in][]{Luger2019}.\n\nAn observer views the body from a large distance in the sky frame\n$\\mathcal{F}$, in which the $x$-axis points to the right,\nthe $y$-axis points up, and the $z$-axis points out of the sky\ntoward the observer. Following \\citet{Luger2019}, if\nan occultor of radius $r_\\mathrm{o}$ is located at sky position $(x_\\mathrm{o}, y_\\mathrm{o})$,\nwe compute the visible thermal flux $f_\\mathrm{T}$ from\n%\n\\begin{align}\n    \\label{eq:sTARRy}\n    f_\\mathrm{T} = \\sTe \\mathbf{A} \\mathbf{R}' \\mathbf{R} \\mathbf{y}\n    \\quad,\n\\end{align}\n%\nwhere, from right to left, $\\mathbf{R} = \\mathbf{R}(\\text{I}, \\Lambda, \\Theta)$\nis a Wigner rotation matrix that rotates $\\bvec{y}$ from $\\mathcal{F}_0$\nto the sky frame $\\mathcal{F}$\ngiven the body's inclination $\\text{I}$, obliquity\n$\\Lambda$, and rotational phase $\\Theta$\n\\citep[Appendix C in][]{Luger2019},\n%\n$\\mathbf{R}' = \\mathbf{R}'(x_\\mathrm{o}, y_\\mathrm{o})$ rotates the body on the plane\nof the sky into the integration frame $\\mathcal{F}'$, in which the\noccultor lies along the $+y'$-axis,\n%\n$\\mathbf{A}$\n\\citep[Equation~B13 in][]{Luger2019}\nis the change-of-basis matrix from $\\by$\nto the \\emph{Green's basis} $\\bg$ in which the integrals are computed,\nwhose component at index $n$ is\n%\n\\begin{align}\n    \\label{eq:bg}\n    \\tilde{g}_{n}(x, y) & =\n    \\begin{dcases}\n        %\n        \\frac{\\mu+2}{2}x^\\frac{\\mu}{2} y^\\frac{\\nu}{2}\n         & \\qquad \\mu, \\nu \\, \\text{even}\n        \\\\[1em]\n        %\n        z(x, y)\n         & \\qquad \\mu = \\nu = 1\n        \\\\[1em]\n        %\n        3x^{l-2}yz(x, y)\n         & \\qquad \\nu \\, \\text{odd}, \\,\n        \\mu = 1, \\,\n        \\frac{\\mu + \\nu}{2} \\, \\text{even}\n        \\\\[1em]\n        %\n        z(x, y)\n        \\bigg(\n        -x^{l-3} + x^{l-1} + 4x^{l-3}y^2\n        \\bigg)\n         & \\qquad \\nu \\, \\text{odd}, \\,\n        \\mu = 1, \\,\n        \\, \\text{odd}\n        \\\\[1em]\n        %\n        z(x, y)\n        \\bigg(\n        \\frac{\\mu-3}{2} x^\\frac{\\mu-5}{2} y^\\frac{\\nu-1}{2}\n        \\ - \\\n        \\frac{\\mu-3}{2} x^\\frac{\\mu-5}{2} y^\\frac{\\nu+3}{2}\n        \\\\\n        \\qquad\\qquad \\ - \\\n        \\frac{\\mu+3}{2} x^\\frac{\\mu-1}{2} y^\\frac{\\nu-1}{2}\n        \\bigg)\n         & \\qquad \\text{otherwise}\n        \\quad,\n    \\end{dcases}\n\\end{align}\n%\nwith\n%\n\\begin{align}\n    \\label{eq:mu-nu}\n    \\mu & \\equiv l - m\n    \\nonumber          \\\\\n    \\nu & \\equiv l + m\n\\end{align}\n%\nand\n%\n\\begin{align}\n    \\label{eq:z}\n    z(x, y) \\equiv \\sqrt{1 - x^2 - y^2}\n    \\quad,\n\\end{align}\n%\nand $\\sTe = \\sTe(b_\\mathrm{o}, r_\\mathrm{o})$ is the vector of solutions to the integral over\nthe projected visible disk of the body for each term in $\\bg$\n\\citep[Equation~26 in][]{Luger2019}, with $b_\\mathrm{o} = \\sqrt{x_\\mathrm{o}^2 + y_\\mathrm{o}^2}$.\n\nIf instead no occultor is present, we compute the total\nvisible thermal flux $f_\\mathrm{T_0}$ from this body as\n%\n\\begin{align}\n    \\label{eq:rTA1Ry}\n    f_\\mathrm{T_0} = \\rTe \\mathbf{A_1} \\mathbf{R}'' \\mathbf{R} \\mathbf{y}\n    \\quad,\n\\end{align}\n%\nwhere, as before, $\\mathbf{R} = \\mathbf{R}(\\text{I}, \\Lambda, \\Theta)$\nrotates the body from $\\mathcal{F}_0$\nto the sky frame $\\mathcal{F}$,\n%\n$\\mathbf{R}''$ rotates the body on the plane\nof the sky into the integration frame\n$\\mathcal{F}''$%\n\\footnote{%\n    In \\citet{Luger2019}, $\\mathcal{F}'' = \\mathcal{F}'$, so\n    this rotation is trivial: $\\mathbf{R}''$ is just the identity matrix.\n},\n%\n$\\mathbf{A_1}$\n\\citep[Equation~B11 in][]{Luger2019}\nis the change-of-basis matrix from the spherical harmonic\nbasis $\\by$ to the \\emph{polynomial basis} $\\bp$ in which the integrals\nare computed, whose component at index $n$ is\n%\n\\begin{align}\n    \\label{eq:bp}\n    \\tilde{p}_n(x, y) & =\n    \\begin{dcases}\n        x^\\frac{\\mu}{2} y^\\frac{\\nu}{2}\n         & \\qquad \\mu, \\nu \\, \\text{even}\n        \\\\[1em]\n        x^\\frac{\\mu-1}{2} y^\\frac{\\nu-1}{2} z(x, y)\n         & \\qquad \\text{otherwise}\n        \\quad,\n    \\end{dcases}\n\\end{align}\n%\nand $\\rTe$ is the vector of solutions to the integral over\nthe projected visible disk of the body for each term in $\\bp$\n\\citep[Equation~19 in][]{Luger2019}.\n\n\\subsection{Adapting the algorithm to the reflected light case}\n\\label{sec:adapting-starry}\n%\nIn order to compute light curves in reflected light, we must make two\nmodifications to the \\starry algorithm. First,\nthe expressions above assume that the coefficient vector\n$\\mathbf{y}$ describes the \\emph{emissivity} of the body, which (in the\nabsence of limb darkening) is assumed to be Lambertian, i.e., all points on the\nsurface emit equally in all directions.\nHere, we wish to derive the solution for the flux in the case of Lambertian\nreflectance, in which case the vector $\\mathbf{y}$ is taken to describe the\nspherical albedo of the surface, $A$.\n\nSecond, we must explicitly model the illumination of the body. We assume the\nbody is illuminated by a point-like source whose flux measured by the observer\nis unity. In this case, the observed intensity at any\npoint on the surface is proportional to the cosine of the angle $\\vartheta_\\mathrm{i}$ between\nthe incident light and the surface normal. Points for which\n$\\vartheta_\\mathrm{i} \\ge \\nicefrac{\\pi}{2}$ are unilluminated and\ntherefore have an intensity of zero.\n%\nIf the point-like illumination source is placed at sky coordinates\n$(x_\\mathrm{s}, y_\\mathrm{s}, z_\\mathrm{s})$ in units of the radius of the illuminated body,\nthe day/night terminator on the body is a half-ellipse\nof semi-major axis unity that is fully described by its (signed) semi-minor\naxis,\n%\n\\begin{proof}{illumination}\n    \\label{eq:b}\n    b = -\\frac{z_\\mathrm{s}}{r_\\mathrm{s}}\n    \\quad,\n\\end{proof}\n%\nwhere $r_\\mathrm{s} = \\sqrt{x_\\mathrm{s}^2 + y_\\mathrm{s}^2 + z_\\mathrm{s}^2}$ is the distance to the source,\n%\nand the angle by which its semi-major axis is rotated away from the\n$+x$-axis,\n%\n\\begin{proof}{illumination}\n    \\label{eq:theta}\n    \\theta = -\\atantwo(x_\\mathrm{s}, y_\\mathrm{s})\n    \\quad,\n\\end{proof}\n%\nwhere $\\atantwo(a, b)$ is the quadrant-aware arctangent of\n$\\nicefrac{a}{b}$.\nGiven this formulation, and assuming that\n$r_\\mathrm{s} \\gg 1$,\nit is straightforward to show that the illumination\n$\\mathcal{I}$ at a point $(x, y)$ on the projected disk of the body is given\nby the function\n%\n\\begin{proof}{illumination}\n    \\label{eq:illum}\n    \\mathcal{I}(b, \\theta, r_\\mathrm{s}; x, y)&=\n    \\text{max}\\bigg( 0, I(b, \\theta, r_\\mathrm{s}; x, y) \\bigg)\n\\end{proof}\n%\nwhere\n%\n\\begin{proof}{illumination}\n    \\label{eq:illum_poly}\n    I(b, \\theta, r_\\mathrm{s}; x, y) &=\n    \\frac{1}{\\pi r_\\mathrm{s}^2}\n    \\cos \\vartheta_\\mathrm{i}\n    \\nonumber \\\\\n    &= \\frac{1}{\\pi r_\\mathrm{s}^2}\n    \\bigg(\n    -b_\\mathrm{c}\\sin\\theta x + b_\\mathrm{c}\\cos\\theta y - bz(x, y)\n    \\bigg)\n\\end{proof}\n%\nwith $b_\\mathrm{c} \\equiv \\sqrt{1 - b^2}$ and $z(x, y) = \\sqrt{1 - x^2 - y^2}$.\nThe illumination $\\mathcal{I}$ is a unitless quantity, normalized such that\nthe integral of $A\\mathcal{I}$ over the unit\ndisk is equal to the flux measured\nby the observer as a fraction of the flux of the illumination source.\nIn particular, if we place the illumination source along the $+z$-axis at\n$(0, 0, 1)$, the body is seen at full phase, so $b = -1$, $b_\\mathrm{c} = 0$, and\n%\n\\begin{proof}{illumination}\n    \\mathcal{I}_\\text{full}(x, y) = \\frac{\\sqrt{1 - x^2 - y^2}}{\\pi}\n    \\quad.\n\\end{proof}\n%\nMultiplying this by the albedo and integrating over the unit disk,\nwe obtain the reflected flux measured\nby the observer in units of the flux of the illumination source:\n%\n\\begin{proof}{illumination}\n    f_\\text{full} &=\n    \\int_{-1}^{1}\n    \\int_{-\\sqrt{1 - x^2}}^{\\sqrt{1 - x^2}}\n    A\n    \\frac{\\sqrt{1 - x^2 - y^2}}{\\pi}\n    \\,\n    \\dd y\n    \\,\n    \\dd x\n    \\nonumber \\\\[0.5em]\n    &= \\frac{2}{3}A\n    \\quad,\n\\end{proof}\n%\nwhich is precisely the geometric albedo of a Lambert\nsphere of spherical albedo $A$ \\citep[see, e.g.][]{Seager2010}.\n%\\xxx{\\textbf{Eric:} Is this explanation sufficient? Why does it matter that this\n%    is the geometric albedo of a Lambert sphere?}\n\nIn principle, our task is now straightforward: weight each of the\nterms in the Green's basis (Equation~\\ref{eq:bg}) and integrate them\nover the visible portion of the body's disk to obtain the reflected\nlight solution vector, $\\sT$. Unfortunately, the piecewise nature\nof Equation~(\\ref{eq:illum}) makes direct evaluation of these integrals\nextremely difficult in practice.\n%\nWe find that it is more tractable to weight our basis terms by\nthe function $I$ (Equation~\\ref{eq:illum_poly}) and to modify the limits\nof integration to exclude the nightside of the body, where $I$ is\n(unphysically) negative.\n%\nIn particular, since $I$ is just a polynomial in $x$, $y$, and $z(x, y)$, we\ncan express it as a vector $\\mathbf{i}(b, \\theta)$ in the polynomial basis $\\bp$.\nRecalling the structure of the basis (Equation~\\ref{eq:bp}),\nwe may write\n%\n\\begin{proof}{illumination}\n    \\label{eq:ivec}\n    \\mathbf{i}(b, \\theta, r_\\mathrm{s}) & =\n    \\frac{1}{\\pi r_\\mathrm{s}^2}\n    \\begin{pmatrix}\n        0                       \\\\\n        -b_\\mathrm{c}\\sin\\theta \\\\\n        -b                      \\\\\n        b_\\mathrm{c}\\cos\\theta\n    \\end{pmatrix}\n    \\quad.\n\\end{proof}\n%\nThis fact allows us to construct a linear operator $\\mathbf{I}$ to weight a map\nvector in the polynomial basis by the illumination profile.\nIf we think about how each of the terms in $\\bp$ transforms under $\\mathbf{I}$,\n%\n\\\\[1em]\n%\n\\begin{minipage}{0.22\\linewidth}\n    \\begin{align}\n        \\begin{pmatrix}\n            1 \\\\\n            0 \\\\\n            0 \\\\\n            0\n        \\end{pmatrix}\n         & \\pmb{\\rightarrow}\n        \\begin{pmatrix}\n            \\bvec{i}_0 \\\\ %1\n            \\bvec{i}_1 \\\\ %x\n            \\bvec{i}_2 \\\\ %z\n            \\bvec{i}_3 \\\\ %y\n            0          \\\\ %x^2\n            0          \\\\ %xz\n            0          \\\\ %xy\n            0          \\\\ %yz\n            0             %y^2\n        \\end{pmatrix}\n        \\nonumber\n    \\end{align}\n\\end{minipage}\n%\n\\begin{minipage}{0.22\\linewidth}\n    \\begin{align}\n        \\begin{pmatrix}\n            0 \\\\\n            1 \\\\\n            0 \\\\\n            0\n        \\end{pmatrix}\n         & \\pmb{\\rightarrow}\n        \\begin{pmatrix}\n            0          \\\\ %1\n            \\bvec{i}_0 \\\\ %x\n            0          \\\\ %z\n            0          \\\\ %y\n            \\bvec{i}_1 \\\\ %x^2\n            \\bvec{i}_2 \\\\ %xz\n            \\bvec{i}_3 \\\\ %xy\n            0          \\\\ %yz\n            0    %y^2\n        \\end{pmatrix}\n        \\nonumber\n    \\end{align}\n\\end{minipage}\n%\n\\begin{minipage}{0.22\\linewidth}\n    \\begin{align}\n        \\begin{pmatrix}\n            0 \\\\\n            0 \\\\\n            1 \\\\\n            0\n        \\end{pmatrix}\n         & \\pmb{\\rightarrow}\n        \\begin{pmatrix}\n            \\bvec{i}_2  \\\\ %1\n            0           \\\\ %x\n            \\bvec{i}_0  \\\\ %z\n            0           \\\\ %y\n            -\\bvec{i}_2 \\\\ %x^2\n            \\bvec{i}_1  \\\\ %xz\n            0           \\\\ %xy\n            \\bvec{i}_3  \\\\ %yz\n            -\\bvec{i}_2    %y^2\n        \\end{pmatrix}\n        \\nonumber\n    \\end{align}\n\\end{minipage}\n%\n\\begin{minipage}{0.22\\linewidth}\n    \\begin{align}\n        \\begin{pmatrix}\n            0 \\\\\n            0 \\\\\n            0 \\\\\n            1\n        \\end{pmatrix}\n         & \\pmb{\\rightarrow}\n        \\begin{pmatrix}\n            0          \\\\ %1\n            0          \\\\ %x\n            0          \\\\ %z\n            \\bvec{i}_0 \\\\ %y\n            0          \\\\ %x^2\n            0          \\\\ %xz\n            \\bvec{i}_1 \\\\ %xy\n            \\bvec{i}_2 \\\\ %yz\n            \\bvec{i}_3    %y^2\n        \\end{pmatrix}\n        \\nonumber\n    \\end{align}\n\\end{minipage}\n\\begin{minipage}{0.05\\linewidth}\n    \\begin{align}\n    \\end{align}\n\\end{minipage}\n%\n\\\\[1em]\n%\nwe can compose $\\mathbf{I}$ out of these column vectors:\n%\n\\begin{proof}{illumination}\n    \\label{eq:Imat}\n    \\mathbf{I}(b, \\theta, r_\\mathrm{s}) & =\n    \\frac{1}{\\pi r_\\mathrm{s}^2}\n    \\begin{pmatrix}\n        0                       & 0                       & -b                      & 0                       & \\cdots \\\\\n        -b_\\mathrm{c}\\sin\\theta & 0                       & 0                       & 0                       & \\cdots \\\\\n        -b                      & 0                       & 0                       & 0                       & \\cdots \\\\\n        b_\\mathrm{c}\\cos\\theta  & 0                       & 0                       & 0                       & \\cdots \\\\\n        0                       & -b_\\mathrm{c}\\sin\\theta & b                       & 0                       & \\cdots \\\\\n        0                       & -b                      & -b_\\mathrm{c}\\sin\\theta & 0                       & \\cdots \\\\\n        0                       & b_\\mathrm{c}\\cos\\theta  & 0                       & -b_\\mathrm{c}\\sin\\theta & \\cdots \\\\\n        0                       & 0                       & b_\\mathrm{c}\\cos\\theta  & -b                      & \\cdots \\\\\n        0                       & 0                       & b                       & b_\\mathrm{c}\\cos\\theta  & \\cdots \\\\\n        \\vdots                  & \\vdots                  & \\vdots                  & \\vdots                  & \\ddots\n    \\end{pmatrix}\n\\end{proof}\n%\nwhere the dimensions of the matrix are $\\big((l + 2)^2, (l + 1)^2\\big)$, where\n$l$ is the spherical harmonic degree of the map (this operator raises the\ndegree of the map by one).\n%\nNote, again, that this weighting is valid only on the dayside\nhemisphere (see Equation~\\ref{eq:illum}), as the operator $\\mathbf{I}$ weights\npoints on the nightside by a \\emph{negative} amount, which is clearly\nunphysical. As we will see momentarily, we account for this by excluding the\nnightside from the integration region in our flux integrals.\n\n\\begin{figure}[t!]\n    \\begin{centering}\n        \\includegraphics[width=\\linewidth]{figures/frames.pdf}\n        \\oscaption{frames}{%\n            How \\starry computes the flux from a body in reflected light,\n            tracking each of the linear transformations from the input map\n            (far right) to the output (far left). The label below each map\n            denotes the reference frame, while the label above\n            each map denotes the basis in which the map is represented.\n            Arrows indicate linear operations and are labeled accordingly.\n            The upper branch corresponds to the occulted case\n            (Equation~\\ref{eq:sTA2IA1RRy}), while the\n            lower branch corresponds to the case where the body\n            is unocculted (Equation~\\ref{eq:rTIA1RRy}).\n            See text for details.\n            \\label{fig:frames}\n        }\n    \\end{centering}\n\\end{figure}\n\nWe may now re-write Equations~(\\ref{eq:sTARRy}) and (\\ref{eq:rTA1Ry}) to\naccount for this illumination transformation. The flux during an occultation\nis now given by\n%\n\\begin{align}\n    \\label{eq:sTA2IA1RRy}\n    f & =\n    \\sT(b, \\theta', b_\\mathrm{o}, r_\\mathrm{o})\n    \\mathbf{A_2}\n    \\mathbf{I}(b, \\theta', r_\\mathrm{s})\n    \\mathbf{A_1}\n    \\mathbf{R}'(x_\\mathrm{o}, y_\\mathrm{o})\n    \\mathbf{R}(\\text{I}, \\Lambda, \\Theta)\n    \\mathbf{y}\n    \\quad,\n\\end{align}\n%\nwhere\n%\n\\begin{align}\n    \\label{eq:theta'}\n    \\theta' = \\atantwo(x_\\mathrm{o}, y_\\mathrm{o}) - \\atantwo(x_\\mathrm{s}, y_\\mathrm{s})\n\\end{align}\n%\nis the angle of the terminator in the frame $\\mathcal{F}'$.\nNote that we made use of the fact that\n$\\mathbf{A} = \\mathbf{A_2} \\mathbf{A_1}$\n\\citep[Equation~14 in][]{Luger2019}, where $\\mathbf{A_1}$ transforms from\nthe spherical harmonic basis $\\by$ to the polynomial basis $\\bp$, and\n$\\mathbf{A_2}$ transforms from $\\bp$ to the Green's basis $\\bg$.\n\nSimilarly, the flux when there is no occultation is now given by\n%\n\\begin{align}\n    \\label{eq:rTIA1RRy}\n    f_0 & =\n    \\rT(b)\n    \\mathbf{I}(b, \\theta'', r_\\mathrm{s})\n    \\mathbf{A_1}\n    \\mathbf{R}''(x_\\mathrm{s}, y_\\mathrm{s})\n    \\mathbf{R}(\\text{I}, \\Lambda, \\Theta)\n    \\mathbf{y}\n    \\quad,\n\\end{align}\n%\nwhere\n%\n\\begin{align}\n    \\label{eq:theta''}\n    \\theta'' = 0\n\\end{align}\n%\nis the angle of the terminator in the frame $\\mathcal{F}''$, by\nconstruction. The transformation\n$\\mathbf{R}'' = \\mathbf{R}''(x_\\mathrm{s}, y_\\mathrm{s})$ rotates\nthe body\nthrough an angle $\\atantwo(x_\\mathrm{s}, y_\\mathrm{s})$\nso the semi-major axis of the terminator is aligned\nwith the $x''$-axis; as will become clear in \\S\\ref{sec:solution-no-occ} below,\nthis greatly simplifies the integration step.\n\nNote that in both equations we replaced the integral vectors\n$\\rTe$ and $\\sTe(b_\\mathrm{o}, r_\\mathrm{o})$\nwith the vectors\n$\\rT(b)$ and $\\sT(b, \\theta', b_\\mathrm{o}, r_\\mathrm{o})$,\nrespectively.\nAs we mentioned above, we must modify the integration limits to exclude the\nnightside, where the weighting by $\\mathbf{I}$ is unphysical.\nThe vectors $\\rT$ and $\\sT$ correspond to these\nmodified integrals, which we devote the rest of this paper to\ncomputing.\n\nFigure~\\ref{fig:frames} summarizes the transformations involved in the two\nequations above. Starting on the right with a map vector $\\mathbf{y}$ in\nthe spherical harmonic basis $\\by$, defined in some observer-independent frame\n$\\mathcal{F}_0$, we first rotate it via $\\mathbf{R}$ to the sky frame\n$\\mathcal{F}$, in which the body is viewed by the\nobserver. If an occultor is present (upper branch of the figure),\nwe rotate the map from $\\mathcal{F}$ via $\\mathbf{R}'$ to the frame\n$\\mathcal{F}'$, in which the occultor lies along the\n$+y'$-axis. We then apply $\\mathbf{A_1}$ to change basis to $\\bp$ and $\\mathbf{I}$\nto weight the map by the illumination. Finally, we change basis\nvia $\\mathbf{A_2}$ to the Green's basis, in which we compute and dot the\nintegrals $\\sT$.\nIf, on the other hand, there is no occultation (lower branch of the figure),\nwe instead rotate the map via $\\mathbf{R}''$ to the integration frame\n$\\mathcal{F}''$, in which the terminator is parallel to the\n$x''$-axis. We then apply $\\mathbf{A_1}$ to change basis to $\\bp$, apply the\nillumination transform $\\mathbf{I}$, and finally dot in the solutions to the\nsurface integrals $\\rT$.\n\n%\n\n\\section{The Solution: No Occultation}\n\\label{sec:solution-no-occ}\n%\nBefore we tackle configurations involving occultations, we must address the\nsimpler problem of computing the total visible flux from an unocculted\nbody in reflected light (Equation~\\ref{eq:rTIA1RRy}). This problem was\noriginally solved by \\citet{Haggard2018} and subsequently by\n\\citet{Luger2019b}, but for completeness we present the detailed\nderivation in the \\starry formalism here.\n\nAs we discussed above, we perform the integration in a frame\n$\\mathcal{F}''$\nin which the semi-major axis of the terminator is aligned with the\n$x''$-axis, with the illumination source at $y'' \\ge 0$.\nThe solution vector may then be computed from\n%\n\\begin{align}\n    \\label{eq:rT}\n    \\rT(b) & =\n    \\int_{-1}^{1}\n    \\int_{b\\sqrt{1 - x''^2}}^{\\sqrt{1 - x''^2}}\n    \\bp(x'', y'')\n    \\ \\dd y'' \\ \\dd x''\n    \\quad,\n\\end{align}\n%\nwhich is identical to Equation~(20) in \\citet{Luger2019} except for the\nlower integration limit of the inner integral. The lower limit is now\nthe equation describing the terminator, which ensures we always exclude the\nnightside from the integration region.\n%\nEquation~(\\ref{eq:rT}) may be solved analytically in terms of purely\ntrigonometric and algebraic functions of $b$.\nThe component of $\\rT$\nat index $n$ is given by\n%\n\\begin{proof}{PhaseCurve}\n    \\label{eq:rTsoln}\n    \\mathbb{r}_n(b) & =\n    \\begin{cases}\n        \\frac{\\left(1 - b^{\\frac{\\nu + 2}{2}}\\right)}{2}\n        \\mathbb{L}_{\\frac{\\mu}{2}, \\frac{\\nu}{2}}\n        %\n         &\n        %\n        \\qquad\n        \\frac{\\mu}{2} \\ \\text{even}\n        %\n        \\\\[1em]\n        %\n        \\mathbb{k}_{\\frac{\\nu - 1}{2}}(b) \\mathbb{M}_{\\frac{\\mu - 1}{2}, \\frac{\\nu - 1}{2}}\n        %\n         &\n        %\n        \\qquad\n        \\frac{\\mu - 1}{2} \\ \\text{even}\n        %\n        \\\\[1em]\n        %\n        0\n        %\n         &\n        %\n        \\qquad\n        \\text{otherwise}\n    \\end{cases}\n\\end{proof}\n%\nwhere the components of $\\mathbbb{k}$, $\\mathbbb{L}$, and $\\mathbbb{M}$\nare given by\n%\n\\begin{proof}{PhaseCurve}\n    \\label{eq:HJK}\n    \\mathbb{k}_{j}(b) &= \\int_b^1 a^j \\sqrt{1 - a^2} \\dd a\n    \\nonumber \\\\\n    %\n    \\mathbb{L}_{i,j} &=\n    \\frac{\n        \\Gamma\\left(\\frac{i + 1}{2}\\right)\n        \\Gamma\\left(\\frac{j + 1}{2}\\right)\n    }\n    {\n        \\Gamma\\left(\\frac{i + j + 4}{2}\\right)\n    }\n    %\n    \\nonumber \\\\\n    %\n    \\mathbb{M}_{i,j} &=\n    \\frac{\n        \\Gamma\\left(\\frac{i + 1}{2}\\right)\n        \\Gamma\\left(\\frac{j + 4}{2}\\right)\n    }\n    {\n        \\Gamma\\left(\\frac{i + j + 5}{2}\\right)\n    }\n    \\quad,\n\\end{proof}\n%\nwhere $\\Gamma$ is the gamma function.\n%\nGiven initial conditions\n%\n\\\\[1em]\n\\begin{minipage}{.33\\linewidth}\n    \\begin{align}\n        \\mathbb{k}_{0}(b) & = \\frac{\\arccos(b) - bb_c}{2}\n        %\n        \\nonumber                                         \\\\\n        %\n        \\mathbb{k}_{1}(b) & = \\frac{b_\\mathrm{c}^3}{3}\n        %\n        \\nonumber\n    \\end{align}\n\\end{minipage}%\n\\begin{minipage}{.32\\linewidth}\n    \\begin{align}\n        \\mathbb{L}_{0,0} & = \\pi\n        %\n        \\nonumber                        \\\\\n        %\n        \\mathbb{L}_{0,1} & = \\frac{4}{3}\n        %\n        \\nonumber\n    \\end{align}\n\\end{minipage}%\n\\begin{minipage}{.33\\linewidth}\n    \\begin{proof}{PhaseCurve}\n        \\label{eq:IJK0}\n        \\mathbb{M}_{0,0} &= \\frac{4}{3}\n        %\n        \\nonumber \\\\\n        \\mathbb{M}_{0,1} &= \\frac{3\\pi}{8}\n    \\end{proof}\n\\end{minipage}\n\\\\[1em]\n%\nwe may compute all the required higher order terms from the recurrence relations\n%\n\\begin{proof}{PhaseCurve}\n    \\label{eq:IJKrec}\n    \\mathbb{k}_{j}(b) &= \\frac{b^{j-1} b_\\mathrm{c}^3 + (j - 1) \\mathbb{k}_{j - 2}(b)}{j + 2}\n    %\n    \\nonumber \\\\\n    %\n    \\mathbb{L}_{0,j} &= \\left(\\frac{j - 1}{j + 2}\\right) \\mathbb{L}_{0,j-2}\n    %\n    \\nonumber \\\\\n    %\n    \\mathbb{M}_{0,j} &= \\left(\\frac{j + 2}{j + 3}\\right) \\mathbb{M}_{0,j-2}\n    %\n    \\nonumber \\\\\n    %\n    \\mathbb{L}_{i,j} &= \\left(\\frac{i - 1}{i + j + 2}\\right) \\mathbb{L}_{i-2,j}\n    %\n    \\nonumber \\\\\n    %\n    \\mathbb{M}_{i,j} &= \\left(\\frac{i - 1}{i + j + 3}\\right) \\mathbb{M}_{i-2,j}\n    \\quad.\n\\end{proof}\n%\nOnce $\\rT$ is known,\nthe observed total flux in reflected light\nis computed from (c.f. Equation~\\ref{eq:rTIA1RRy})\n%\n\\begin{align}\n    \\label{eq:f0}\n    f_0 & =\n    \\rT(b)\n    \\mathbf{I}(b, \\theta'', r_\\mathrm{s})\n    \\mathbf{A_1}\n    \\mathbf{R}''(x_\\mathrm{s}, y_\\mathrm{s})\n    \\mathbf{R}(\\text{I}, \\Lambda, \\Theta)\n    \\mathbf{y}\n    \\quad.\n\\end{align}\n%\nFinally, for future reference, we can also compute what we will call the\n\\emph{complement} of case 0:\n%\n\\begin{align}\n    \\label{eq:f0hat}\n    \\hat{f}_0 & =\n    \\Big(\n    \\mathbf{r}^\\top\n    -\n    \\rT(b)\n    \\Big)\n    \\mathbf{I}(b, \\theta'', r_\\mathrm{s})\n    \\mathbf{A_1}\n    \\mathbf{R}''(x_\\mathrm{s}, y_\\mathrm{s})\n    \\mathbf{R}(\\text{I}, \\Lambda, \\Theta)\n    \\mathbf{y}\n    \\quad.\n\\end{align}\n%\nThis is the flux contribution from the unphysical night side\n(if we were to integrate over it), where\nour polynomial illumination (Equation~\\ref{eq:illum_poly}) function\nyields \\emph{negative} intensities. This quantity\nwill be useful in negating the unphysical contribution\nin the integrals of the following section.\n\n\\section{The Solution: Occultation}\n\\label{sec:solution-occ}\n%\nThe integration in the unocculted case presented above is relatively\nstraightforward, since\nthe boundaries of integration are always the half-ellipse defining the\nterminator and the half-circle defining the upper limb of the body\n(Equation~\\ref{eq:rT}). When an occultor is present, however, the\nintegration boundaries are far less trivial, since they may or may not\ninclude sections of the terminator, sections of the limb of the body,\nand sections of the limb of the occultor. The integration regions may also\nbe disjoint; for instance, in case 7 of Figure~\\ref{fig:cases}, the\nportion of the dayside that is unocculted consists of two separate\nregions.\n\nWhereas in \\citet{Luger2019} we compute the observed flux by always\nintegrating over the unocculted portion of the disk, here we find that\nit is often easier and more computationally efficient to compute the\nintegral of the intensity over the\n\\emph{simplest} region -- meaning the one with the fewest boundaries --\nand combine it with the formalism from \\S\\ref{sec:solution-no-occ} to\ncompute the visible flux. These integrals may be over the unocculted dayside,\nthe occulted dayside, the unocculted nightside, or the occulted nightside;\nin the case of the latter three, a bit of algebra\n(\\S\\ref{sec:cases-hard}--\\S\\ref{sec:cases-pathological}) is needed\nto relate these to the observed flux. Additionally, in some cases we can\navoid computing new integrals entirely, as the solution can be obtained from\na combination of the classical \\starry solution vector $\\sT$ and the\nformalism from the unocculted case (\\S\\ref{sec:solution-no-occ}).\n\nAfter exhaustive experimentation, we identified in total 14 families of\ngeometrical configurations for the occultation problem,\neach defined by a distinct combination of integration\nboundaries; these are shown in Figures~\\ref{fig:cases} and\n\\ref{fig:pathological}.\nTogether, these cases encompass all possible\noccultation configurations, for any illumination angle, occultor size, and\noccultor position.\n\nBefore we discuss how to compute the occultation integrals, we must first\ndevelop a procedure to identify the relevant case given the occultor\nimpact parameter $b_\\mathrm{o} = \\sqrt{x_\\mathrm{o}^2 + y_\\mathrm{o}^2}$ and radius $r_\\mathrm{o}$ and\nthe terminator semi-minor\naxis $b$ and angle $\\theta'$ in the frame $\\mathcal{F}'$.\nThen, once the case is determined, we must\nidentify the relevant integration boundaries, which depend on the points\nof intersection between the limb of the body, the limb of the occultor, and\nthe terminator. We do so in the following sections.\n\n%\n\n\\subsection{Case determination}\n\\label{sec:which-case}\n\n\\begin{figure}[t!]\n    \\begin{centering}\n        \\includegraphics[width=\\linewidth]{figures/cases.pdf}\n        \\oscaption{cases}{%\n            The 10 principal families of cases of occultations in\n            reflected light.\n            In these figures, the body with the solid outline\n            is the one whose flux we are interested in, and the body with the\n            dashed outline is the occultor.\n            The nightside of the occulted body is colored\n            black (dark grey if occulted), and the dayside is colored blue\n            (bluish-grey if occulted).\n            Case 0 is the unocculted case (\\S\\ref{sec:solution-no-occ}),\n            while cases 1--5 involve\n            configurations in which the limb of the occultor does not intersect\n            with the terminator at any point, so the visible flux may be\n            computed in terms of classical \\starry integrals. The remaining\n            cases require integration along the orange boundary (the curves\n            $\\mathcal{P}$, $\\mathcal{T}$, and $\\mathcal{Q}$ of\n            \\S\\ref{sec:cases-hard}), which\n            include the terminator. These involve the evaluation of incomplete\n            elliptic integrals and are derived below.\n            %\n            Note, finally, that there are additional subcases not shown above.\n            For instance, cases 4, 5, 7, and 8 also encompass configurations\n            in which the occultor does not intersect the limb of the occulted\n            body. However, as this distinction does not affect the procedure\n            for computing the flux in these cases (see text), we omit these\n            subcases from the figure.\n            \\label{fig:cases}\n        }\n    \\end{centering}\n\\end{figure}\n\nThe key to identifying the case corresponding to a given configuration is\nto determine whether or not the limb of the occultor intersects the terminator\nof the body, and if so, the points of intersection.\nWhile we perform the integration in frame $\\mathcal{F}'$, finding the points\nof intersection with the terminator is easier if we temporarily switch to\nthe frame $\\mathcal{F}''$, in which the terminator\nis parallel to the $x''$-axis.\nIn this frame, the equations defining the terminator and the limb of the\noccultor are, respectively,\n%\n\\begin{proof}{quartic}\n    y''_1(x'') & = b \\sqrt{1 - x''^2}\n    \\nonumber                                               \\\\\n    y''_2(x'') & = y''_\\mathrm{o} \\pm \\sqrt{r_\\mathrm{o}^2 - (x'' - x''_\\mathrm{o})^2}\n\\end{proof}\n%\nwhere\n%\n\\begin{proof}{quartic}\n    x''_\\mathrm{o} = b_\\mathrm{o}\\sin\\theta'\n    \\nonumber \\\\\n    y''_\\mathrm{o} = b_\\mathrm{o}\\cos\\theta'\n\\end{proof}\n%\nare the coordinates of the occultor in $\\mathcal{F}''$.\n%\nWe wish to find the vector of $N$ points\n$\\mathbf{x''} = \\left(x_0, x_1, {\\cdot\\cdot\\cdot}, x_{N-1}\\right)^\\top$\nfor which\n$y''_1(x_n'') - y''_2(x_n'') = 0$. Following \\citet{Luger2017}, we may\nexpress this condition as the quartic equation\n%\n\\begin{proof}{quartic}\n    \\label{eq:quartic}\n    A {x''}^4 + B {x''}^3 + C {x''}^2 + D {x''} + E = 0\n\\end{proof}\n%\nwith coefficients\n%\n\\begin{proof}{quartic}\n    \\label{eq:quartic-coeffs}\n    A &= (1 - b^2)^2\n    \\nonumber \\\\\n    B &= -4 x''_\\mathrm{o} (1 - b^2)\n    \\nonumber \\\\\n    C &= -2 \\bigg(\n    b^4\n    + r_\\mathrm{o}^2\n    - 3 {x''_\\mathrm{o}}^2\n    - {y''_\\mathrm{o}}^2\n    - b^2 \\big(1 + r_\\mathrm{o}^2 - {x''_\\mathrm{o}}^2 + {y''_\\mathrm{o}}^2\\big)\n    \\bigg)\n    \\nonumber \\\\\n    D &= -4 x''_\\mathrm{o} (b^2 - r_\\mathrm{o}^2 + {x''_\\mathrm{o}}^2 + {y''_\\mathrm{o}}^2)\n    \\nonumber \\\\\n    E &=\n    b^4\n    - 2 b^2 \\big(r_\\mathrm{o}^2 - {x''_\\mathrm{o}}^2 + {y''_\\mathrm{o}}^2\\big)\n    + \\big(r_\\mathrm{o}^2 - {x''_\\mathrm{o}}^2 - {y''_\\mathrm{o}}^2\\big)^2\n    \\quad.\n\\end{proof}\n%\nAlthough closed-form solutions to quartic equations exist\n\\citep[see, e.g.,][who solve for the area of overlap between two ellipses\n    analytically]{Hughes2011}, they are prone to significant numerical\ninstabilities. Instead, we solve for the roots of the quartic\nnumerically by casting it\nas an eigenvalue problem \\citep[e.g.,][]{Edelman1995} and polish the\nresults with a few iterations of Newton's method. We find that this is\nreasonably computationally efficient and\nyields roots with precision within a couple orders of magnitude of machine\nepsilon (see \\S\\ref{sec:performance}).\n\nIn general, the quartic defined by Equation~(\\ref{eq:quartic}) has\n$N=4$ (potentially degenerate) roots, some of which may be complex, and some\nof which correspond to intersections with the wrong half of the\nterminator ellipse (i.e., the section of the terminator on the far side\nof the body). After excluding the unphysical solutions, we are still left with\nanywhere between zero and four roots.\n\nCases with zero roots (case 1 -- case 5) are treated in \\S\\ref{sec:cases-easy},\nwhile cases with one or two roots (case 6 -- case 10) are treated in\n\\S\\ref{sec:cases-hard}. Cases with three or four roots\n(case 11 -- case 14) are rarely encountered\nin practice, but are possible for some pathological configurations; these are\ntreated in \\S\\ref{sec:cases-pathological}.\n\n%\n\n\\subsection{Cases 1--5}\n\\label{sec:cases-easy}\n%\nCases 1--5 (see Figure~\\ref{fig:cases}) involve configurations in which the\noccultor does not intersect with\nthe terminator of the occulted body, and are therefore fairly\nstraightforward to solve. In particular, we can use the original emitted\nlight solution from \\citet{Luger2019}, provided we weight the map by our\npolynomial illumination function:\n%\n\\begin{align}\n    \\label{eq:fI}\n    f_\\mathrm{I} & =\n    \\sTe(b_\\mathrm{o}, r_\\mathrm{o})\n    \\mathbf{A_2}\n    \\mathbf{I}(b, \\theta', r_\\mathrm{s})\n    \\mathbf{A_1}\n    \\mathbf{R}'(x_\\mathrm{o}, y_\\mathrm{o})\n    \\mathbf{R}(\\text{I}, \\Lambda, \\Theta)\n    \\mathbf{y}\n    \\quad,\n\\end{align}\n%\nwhere $\\sTe(b_\\mathrm{o}, r_\\mathrm{o})$ is the emitted light solution vector\n\\citep[Equation~26 in][]{Luger2019}. The flux $f_\\mathrm{I}$ is the flux one would\nmeasure from a body whose surface map is weighted by the illumination function\n$\\mathbf{I}(b, \\theta', r_\\mathrm{s})$ during an occultation. Note that this is not\nnecessarily the \\emph{observed} flux, since this may include the unphysical\nnegative contribution from the nightside. We must compute the actual\nobserved flux on a case-by-case basis.\n\nCase 1 corresponds to any complete occultation of the body\n($b_\\mathrm{o} \\le r_\\mathrm{o} - 1$), so the solution for the flux is trivial:\n%\n\\begin{align}\n    \\label{eq:f1}\n    f_1 = 0\n    \\quad.\n\\end{align}\n%\nCase 2 corresponds to occultations in which the occultor blocks \\emph{all} of\nthe dayside of the body and \\emph{some} of the nightside. In this\nconfiguration, the unocculted part of the disk consists only of nightside, so\nthe solution is again trivial:\n%\n\\begin{align}{}\n    \\label{eq:f2}\n    f_2 = 0\n    \\quad.\n\\end{align}\n%\nConversely, case 3 corresponds to occultations in which the occultor blocks\n\\emph{all} of the nightside of the body and \\emph{some} of the dayside.\nSince the visible portion of the disk consists only of dayside, we can\nsimply use the weighted solution in emitted light\n(Equation~\\ref{eq:fI}):\n%\n\\begin{align}\n    \\label{eq:f3}\n    f_3 = f_\\mathrm{I}\n\\end{align}\n%\nCase 4 involves any occultation in which the occultor blocks \\emph{only} the\nnightside of the body (regardless of whether or not it intersects with the\nlimb of the body). Since the nightside intensity is zero everywhere, this case\nis also trivial, as the flux is equal to the flux in the no occultation case\n(Equation~\\ref{eq:f0}):\n%\n\\begin{align}\n    \\label{eq:f4}\n    f_4 = f_0\n    \\quad.\n\\end{align}\n%\nFinally, case 5 involves any occultation in which the occultor blocks\n\\emph{only} the dayside of the body (regardless of whether or not it\nintersects with the limb). We first compute the illumination-weighted flux\n$f_\\mathrm{I}$ as above, then negate the unphysical nightside contribution\nusing Equation~(\\ref{eq:f0hat}):\n%\n\\begin{align}\n    \\label{eq:f5}\n    f_5 = f_\\mathrm{I} - \\hat{f}_0\n    \\quad.\n\\end{align}\n\n%\n\n\\subsection{Cases 6--10}\n\\label{sec:cases-hard}\n%\n\n\\begin{figure}[t!]\n    \\begin{centering}\n        \\includegraphics[width=\\linewidth]{figures/geometry.pdf}\n        \\oscaption{geometry}{%\n            Geometry of an occultation in reflected light, corresponding\n            to case 6 in Figure~\\ref{fig:cases}. The surface integral over\n            the occulted portion of the dayside (bluish-grey region)\n            is computed from the line integrals of the antiderivatives of the\n            surface intensity map along the boundary curves\n            $\\mathcal{P}$, $\\mathcal{T}$, and $\\mathcal{Q}$. See text for details.\n            \\label{fig:geometry}\n        }\n    \\end{centering}\n\\end{figure}\n\nCases 6--10 (see Figure~\\ref{fig:cases}) correspond to configurations in which\nthe limb of the occultor intersects with the terminator at either one point\n(case 6) or two points (cases 7--10). Because of these intersections, we\ncannot simply re-weight the emitted light solution, as the integration\nboundaries are now different. In general, we may compute the flux by\nintegrating the components of the Green's basis $\\bg$\nover the region $S$ bounded by three curves, which we denote\n$\\mathcal{P}$, $\\mathcal{T}$, and $\\mathcal{Q}$. These are shown in orange\nin Figure~\\ref{fig:cases} and presented in more detail in\nFigure~\\ref{fig:geometry}.\nCurve $\\mathcal{P}$ is a segment of the limb of\nthe occultor, parametrized by the angle $\\phi \\in [\\phi_0, \\phi_1]$;\ncurve $\\mathcal{T}$ is a segment of the terminator,\nparametrized by the angle $\\xi \\in [\\xi_0, \\xi_1]$;\nand curve $\\mathcal{Q}$ is a segment of the limb of the occulted body,\nparametrized by the angle $\\lambda \\in [\\lambda_0, \\lambda_1]$.\nThe endpoints $\\phi_0, \\phi_1, \\xi_0, \\xi_1, \\lambda_0,$ and\n$\\lambda_1$ are functions of the solutions to the quartic from\n\\S\\ref{sec:which-case} and will be presented in \\S\\ref{sec:sT}.\n\nLet $\\sT$ be the integral of $\\bg^\\top$ over $S$:\n%\n\\begin{align}\n    \\label{eq:sTint}\n    \\sT(b, \\theta', b_\\mathrm{o}, r_\\mathrm{o}) & =\n    \\iint\\limits_{S(b, \\theta', b_\\mathrm{o}, r_\\mathrm{o})}\n    \\bg^\\top(x', y')\n    \\ \\dd x' \\ \\dd y'\n    \\quad,\n\\end{align}\n%\nWe defer the solution to Equation~(\\ref{eq:sTint}) to \\S\\ref{sec:sT} below,\nas it is quite lengthy. Given $\\sT$, the flux $f_\\mathrm{S}$ over the integration\nregion $S$ is computed from Equation~(\\ref{eq:sTA2IA1RRy}):\n%\n\\begin{align}\n    \\label{eq:fS}\n    f_\\mathrm{S} & =\n    \\sT(b, \\theta', b_\\mathrm{o}, r_\\mathrm{o})\n    \\mathbf{A_2}\n    \\mathbf{I}(b, \\theta', r_\\mathrm{s})\n    \\mathbf{A_1}\n    \\mathbf{R}'(x_\\mathrm{o}, y_\\mathrm{o})\n    \\mathbf{R}(\\text{I}, \\Lambda, \\Theta)\n    \\mathbf{y}\n    \\quad.\n\\end{align}\n%\nNote again that this is not necessarily the \\emph{observed} flux, which we must\ncompute on a case-by-case basis below.\n\nCase 6 corresponds to configurations in which the limb of the occultor\nintersects the terminator at a single point. The integration region\n(see Figures~\\ref{fig:cases} and \\ref{fig:geometry}) is the occulted\nportion of the dayside, which is bounded by all three curves $\\mathcal{P}$, $\\mathcal{Q}$, and $\\mathcal{T}$.\nThe total flux may\nbe computed by subtracting the occulted flux $f_\\mathrm{S}$ from the total dayside\nflux $f_0$:\n%\n\\begin{align}\n    \\label{eq:f6}\n    f_6 = f_0 - f_\\mathrm{S}\n    \\quad.\n\\end{align}\n%\nCases 7--10 involve two points of intersection between the occultor limb and\nthe terminator.\n%\nCases 7 and 8 correspond to occultors that block some of the\nnightside and some of the dayside, but \\emph{neither} of the extrema of the\nterminator ellipse. In case 7 a lens-shaped region is formed by the\nintersection of the occultor limb and the terminator on the\n\\emph{nightside}, while in case 8 this region is formed on the \\emph{dayside}.\n%\nIn case 7, we begin by computing the\nflux over the unocculted region, $f_\\mathrm{I}$, which includes the spurious\nnightside contribution. We then remove this contribution by noting that it\nis equal to the total nightside contribution, $\\hat{f}_0$, minus the\nocculted nightside flux, $f_\\mathrm{S}$:\n%\n\\begin{align}\n    \\label{eq:f7}\n    f_7 = f_\\mathrm{I} - (\\hat{f}_0 - f_\\mathrm{S})\n    \\quad.\n\\end{align}\n%\nCase 8, on the other hand, is equivalent to case 6, since\nthe integration region consists of occulted dayside:\n%\n\\begin{align}\n    \\label{eq:f8}\n    f_8 = f_0 - f_\\mathrm{S}\n    \\quad.\n\\end{align}\n%\nCases 9 and 10 correspond to occultors that also block some nightside and some\ndayside, along with \\emph{both} of the extrema of the ellipse; these are\ntherefore exclusively for large occultors ($r_\\mathrm{o} > 1$). Case 9\ninvolves occultations in which only a small lens-shaped region of the\nnightside is visible. The total flux is the visible dayside plus unphysical\nnightside contribution, $f_\\mathrm{I}$, minus the nightside contribution, which we\ncompute from Equation~(\\ref{eq:fS}):\n%\n\\begin{align}\n    \\label{eq:f9}\n    f_9 = f_\\mathrm{I} - f_\\mathrm{S}\n    \\quad.\n\\end{align}\n%\nConversely, case 10 involves occultations in which only a small lens-shaped\nregion of the dayside is visible. In this case, we may compute the observed\nflux from Equation~(\\ref{eq:fS}) directly:\n%\n\\begin{align}\n    \\label{eq:f10}\n    f_{10} = f_\\mathrm{S}\n    \\quad.\n\\end{align}\n%\n\n\\subsection{Cases 11--14}\n\\label{sec:cases-pathological}\n\n\\begin{figure}[t!]\n    \\begin{centering}\n        \\includegraphics[width=\\linewidth]{figures/pathological.pdf}\n        \\oscaption{pathological}{%\n            Four additional families of occultations in reflected light,\n            involving rare triple (cases 11 and 12, top) and quadruple\n            (cases 13 and 14, bottom) intersections between the limb of the\n            occultor and the terminator of the occulted body. All four cases\n            involve integration over two disjoint regions (bounded by\n            the orange curves in the figure). The insets next to each case\n            show a zoomed-in version of four such regions. See text for\n            more details.\n            \\label{fig:pathological}\n        }\n    \\end{centering}\n\\end{figure}\n\nCases 11--14 correspond to (rare) configurations involving three\nor four roots to Equation~(\\ref{eq:quartic}) and are\nillustrated in Figure~\\ref{fig:pathological}. All four involve integration over\ntwo disjoint regions (see the figure).\n%\nCases 11 and 12 involve three points of intersection between the terminator\nand the occultor limb. In case 11, the regions of integration $S_1$ and\n$S_2$ are the\nocculted portion of the dayside, so the solution is similar to\nthat of cases 6 and 8:\n%\n\\begin{align}\n    \\label{eq:f11}\n    f_{11} = f_0 - (f_{\\mathrm{S}_1} + f_{\\mathrm{S}_2})\n    \\quad,\n\\end{align}\n%\nwhere $f_{\\mathrm{S}_1}$ and $f_{\\mathrm{S}_2}$ are computed from Equation~(\\ref{eq:fS}) for\neach of the integration regions. Conversely, in case 12 the two regions\nare the occulted portion of the nightside, so the solution is similar to that\nof case 7:\n%\n\\begin{align}\n    \\label{eq:f12}\n    f_{12} = f_\\mathrm{I} - \\big(\\hat{f}_0 - (f_{\\mathrm{S}_1} + f_{\\mathrm{S}_2})\\big)\n    \\quad,\n\\end{align}\n%\nFinally, cases 13 and 14 involve four points of intersection between the\nterminator and the occultor limb. The regions of integration in case 13 are\nthe visible portion of the nightside, so this case is equivalent to case 9:\n%\n\\begin{align}\n    \\label{eq:f13}\n    f_{13} = f_\\mathrm{I} - (f_{\\mathrm{S}_1} + f_{\\mathrm{S}_2})\n    \\quad.\n\\end{align}\n%\nConversely, the regions of integration in case 14 are the\nvisible portion of the dayside, so this case is equivalent to case 10:\n%\n\\begin{align}\n    \\label{eq:f14}\n    f_{14} = f_{\\mathrm{S}_1} + f_{\\mathrm{S}_2}\n    \\quad.\n\\end{align}\n%\n\n\\subsection{Computing the integrals $\\sT$}\n\\label{sec:sT}\n%\nIn the previous sections, we discussed how to identify the case\ncorresponding to a specific configuration of the occultor and the\nillumination source. We showed how in some cases\n(1--5; \\S\\ref{sec:cases-easy}) the total flux may be\ncomputed by exploiting the classical \\starry integrals (Equation~\\ref{eq:fI}).\nIn all other cases (6--14; \\S\\ref{sec:cases-hard} and\n\\S\\ref{sec:cases-pathological}), however, the flux computation involves\nevaluation of\nEquation~(\\ref{eq:fS}), where the solution vector $\\sT$\nis the vector of integrals (in the frame $\\mathcal{F}'$)\nof each of the terms in the Green's basis $\\bg$\nover a region $S$ of the\nprojected disk of the occultor (Equation~\\ref{eq:sTint}).\n%\nAs in \\citet{Luger2019}, the approach to computing $\\sT$\nis to use Green's theorem to transform the surface integrals into line\nintegrals along the curves $\\mathcal{P}$, $\\mathcal{T}$, and $\\mathcal{Q}$\n(see Figure~\\ref{fig:geometry}). Specifically, we write%\n\\footnote{%\n    In this section, we deliberately drop the dependence of $\\sT$ and\n    the primitive\n    integrals on the geometrical parameters $b, \\theta', b_\\mathrm{o}, r_\\mathrm{o}$\n    for clarity.\n}\n%\n\\begin{align}\n    \\label{eq:greens}\n    \\sT\n     & =\n    \\iint\\limits_{S}\n    \\bg^\\top(x', y')\n    \\ \\dd x' \\ \\dd y'\n    \\nonumber \\\\[0.5em]\n     & =\n    \\oint \\bvec{G}^\\top (x', y') \\cdot\n    \\dd \\bvec{r} (x', y')\n    \\quad,\n\\end{align}\n%\nwhere $\\bvec{G} (x', y')$\nis a vector of two-dimensional Cartesian vectors chosen such that its\nexterior derivative is $\\bg$,\n%\n\\begin{align}\n    \\label{eq:DGg}\n    \\frac{\\dd \\bvec{G}_{y'}(x', y')}{\\dd x'}\n    - \\frac{\\dd \\bvec{G}_{x'}(x', y')}{\\dd y'} = \\bg(x', y')\n    \\quad,\n\\end{align}\n%\nand\n%\n\\begin{align}\n    \\dd \\mathbf{r} (x', y') & =\n    \\left(\\frac{\\dd x'}{\\dd \\varphi}\\right) \\dd \\varphi \\, \\xhat' +\n    \\left(\\frac{\\dd y'}{\\dd \\varphi}\\right) \\dd \\varphi \\, \\yhat'\n    \\quad,\n\\end{align}\n%\nwhere $\\varphi$ is the parametrized angle along the integration path\nand the integral is taken in a counter-clockwise direction relative to\nthe center of the integration region.\n%\n\\citet{Luger2019} showed that one possible solution to\nEquation~(\\ref{eq:DGg}) consists of the vector whose $n^\\text{th}$\ncomponent is given by\n%\n\\begin{align}\n    \\label{eq:G}\n    \\mathbf{G}_n (x', y') & =\n    \\begin{dcases}\n        %\n        x'^{\\frac{\\mu + 2}{2}}\n        y'^{\\frac{\\nu}{2}}\n        \\,\\yhat'\n         & \\qquad \\mu, \\nu \\, \\text{even}\n        \\\\[1em]\n        %\n        \\frac{1-z(x', y')^3}{3(1-z(x', y')^2)}\\bigg(-y' \\, \\xhat' + x' \\, \\yhat'\\bigg)\n         & \\qquad \\mu = \\nu = 1\n        \\\\[1em]\n        %\n        x'^{l-2}\n        z(x', y')^3\n        \\,\\xhat\n         & \\qquad \\nu \\, \\text{odd}, \\,\n        \\mu = 1, \\,\n        l \\, \\text{even}\n        \\\\[1em]\n        %\n        x'^{l-3}\n        y'\n        z(x', y')^3\n        \\,\\xhat\n         & \\qquad \\nu \\, \\text{odd}, \\,\n        \\mu = 1, \\,\n        l \\, \\text{odd}\n        \\\\[1em]\n        %\n        x'^{\\frac{\\mu-3}{2}}\n        y'^{\\frac{\\nu-1}{2}}\n        z(x', y')^3\n        \\,\\yhat\n         & \\qquad \\text{otherwise,}\n    \\end{dcases}\n\\end{align}\n%\nwhere the indices $l, m, \\mu, \\nu$ are given by\nEquations~(\\ref{eq:l-m}) and (\\ref{eq:mu-nu}).\n\nWe showed in the previous sections that there are at most three curves\n$\\mathcal{P}$, $\\mathcal{T}$, and $\\mathcal{Q}$ bounding a given closed surface of integration\n(see Figure~\\ref{fig:geometry}). We may therefore express\nEquation~(\\ref{eq:greens}) as\n%\n\\begin{proof}{Greens}\n    \\label{eq:sT}\n    \\sT & =\n    \\pT + \\tT + \\qT\n    \\quad,\n\\end{proof}\n%\nwhere we define the primitive integrals%\n\\footnote{%\n    The components of the vectors $\\pT$ and\n    $\\qT$ are analogous to the primitive integrals\n    $\\mathcal{P}$ and $\\mathcal{Q}$\n    defined in Equations~(30)--(32) in \\citet{Luger2019}, although the\n    integration limits of both and the sense of integration of $\\mathcal{P}$\n    are different.\n}\n%\n\\begin{proof}{Greens}\n    \\label{eq:pT}\n    \\pT\n    & =\n    \\int\\limits_{\\pmb{\\phi}}\n    \\mathbf{G}^\\top(x'_\\mathrm{p}, y'_\\mathrm{p})\n    \\cdot \\dd \\mathbf{r}(x'_\\mathrm{p}, y'_\\mathrm{p})\n    %\n    \\\\\n    %\n    \\label{eq:tT}\n    \\tT\n    & =\n    \\int\\limits_{\\pmb{\\xi}}\n    \\mathbf{G}^\\top(x'_\\mathrm{t}, y'_\\mathrm{t})\n    \\cdot \\dd \\mathbf{r}(x'_\\mathrm{t}, y'_\\mathrm{t})\n    %\n    \\\\\n    %\n    \\label{eq:qT}\n    \\qT\n    & =\n    \\int\\limits_{\\pmb{\\lambda}}\n    \\mathbf{G}^\\top(x'_\\mathrm{q}, y'_\\mathrm{q})\n    \\cdot \\dd \\mathbf{r}(x'_\\mathrm{q}, y'_\\mathrm{q})\n\\end{proof}\n%\nto be the line integrals of $\\mathbf{G}$ along each of the curves\n$\\mathcal{P}$, $\\mathcal{T}$, and $\\mathcal{Q}$, respectively, where the coordinates along each\ncurve are parametrized\nin terms of $\\varphi$ as follows:\n%\n\\\\[1em]\n%\n\\begin{minipage}{0.3\\linewidth}\n    \\begin{align}\n        x'_\\mathrm{p} & = r_\\mathrm{o} \\cos\\varphi\n        \\nonumber                                                 \\\\\n        y'_\\mathrm{p} & = b_\\mathrm{o} + r_\\mathrm{o} \\sin\\varphi\n        \\nonumber\n    \\end{align}\n\\end{minipage}\n%\n\\begin{minipage}{0.34\\linewidth}\n    \\begin{align}\n        x'_\\mathrm{t} & = \\cos\\theta' \\cos\\varphi - b \\sin\\theta' \\sin\\varphi\n        \\nonumber                                                             \\\\\n        y'_\\mathrm{t} & = \\sin\\theta' \\cos\\varphi + b \\cos\\theta' \\sin\\varphi\n        \\nonumber\n    \\end{align}\n\\end{minipage}\n%\n\\begin{minipage}{0.3\\linewidth}\n    \\begin{proof}{Greens}\n        \\label{eq:xy_pqt}\n        x'_\\mathrm{q} & =\\cos\\varphi\n        \\nonumber           \\\\\n        y'_\\mathrm{q} & = \\sin\\varphi\n        \\quad,\n    \\end{proof}\n\\end{minipage}\n%\n\\\\[1em]\n%\nand we define\n%\n\\begin{align}\n    \\label{eq:vint}\n    \\int\\limits_{\\pmb{\\varphi}} & \\equiv\n    %\n    \\int\\limits_{\\varphi_{0}}^{\\varphi_{1}}\n    +\n    \\int\\limits_{\\varphi_{2}}^{\\varphi_{3}}\n    +\n    \\cdots\n    +\n    \\int\\limits_{\\varphi_{N - 2}}^{\\varphi_{N - 1}}\n    %\n    \\nonumber                            \\\\\n                                & \\equiv\n    \\sum_{i = 0}^{\\frac{N}{2} - 1}\n    \\int\\limits_{\\varphi_{2i}}^{\\varphi_{2i+1}}\n\\end{align}\n%\nto be the sum of definite integrals between pairs of limits $\\varphi_i$\narranged in a vector $\\pmb{\\varphi}$ of length $N$.\n%\nFor future reference, it will also be useful to define the operator\n%\n\\begin{align}\n    \\label{eq:pairdiff}\n    \\Delta \\mathbf{x} \\equiv \\sum_{i=0}^{\\frac{N}{2} - 1}\n    \\left( x_{2i + 1} - x_{2i} \\right)\n    \\quad,\n\\end{align}\n%\nwhich sums the difference of successive pairs of values in\na vector\n$\\mathbf{x} = \\left( x_0, x_1, x_2, x_3, {\\cdot\\cdot\\cdot}, x_{N - 1} \\right)^\\top$.\nThis will come in handy when computing definite integrals. Specifically,\nif $g$ is the antiderivative of some function $f$, we may use the\nfundamental theorem of calculus to compute the integral of\n$f$ over the interval(s) given\nby the vector of limit pairs $\\pmb{\\varphi}$:\n%\n\\begin{align}\n    \\vint{\\pmb{\\varphi}}{f(\\varphi)}\n     & = \\int\\limits_{\\varphi_{0}}^{\\varphi_{1}} f(\\varphi) \\dd\\varphi\n    +\n    \\int\\limits_{\\varphi_{2}}^{\\varphi_{3}} f(\\varphi) \\dd\\varphi\n    +\n    {\\cdot\\cdot\\cdot}\n    +\n    \\int\\limits_{\\varphi_{N - 2}}^{\\varphi_{N - 1}} f(\\varphi) \\dd\\varphi\n    \\nonumber                                                          \\\\\n     & = \\Delta \\mathbf{g}(\\pmb{\\varphi})\n\\end{align}\n%\nwhere $\\mathbf{g}$ is the vector given by\n%\n\\begin{align}\n    \\mathbf{g}(\\pmb{\\varphi}) =\n    \\bigg( g(\\varphi_0), g(\\varphi_1), g(\\varphi_2), g(\\varphi_3),\n    {\\cdot\\cdot\\cdot}, g(\\varphi_{N - 2}), g(\\varphi_{N - 1}) \\bigg)^\\top\n    \\quad.\n\\end{align}\n%\nNote that most of the cases (1--10) involve integration over a single closed\nregion, so Equations~(\\ref{eq:vint}) and (\\ref{eq:pairdiff}) reduce to\n%\n\\begin{align}\n    \\int\\limits_{\\pmb{\\varphi}} & \\equiv\n    %\n    \\int\\limits_{\\varphi_{0}}^{\\varphi_{1}}\n\\end{align}\n%\nand\n%\n\\begin{align}\n    \\Delta \\mathbf{x} \\equiv x_1 - x_0\n    \\quad.\n\\end{align}\n%\nFor cases 11--14, we must integrate over two disjoint regions, so we\nsum over two pairs of limits.\n%\nIn the next three sections, we derive the solutions to each of the\nprimitive integrals $\\pT$, $\\tT$, and $\\qT$.\n\n\\subsection{The integral along the occultor limb, $\\pT$}\n\\label{sec:pT}\n%\nIn this section we present a solution to Equation~(\\ref{eq:pT}). The first\norder of business is to derive expressions for the integration limits\n$\\pmb{\\phi}$. Depending on the integration case, these limits will correspond\nto the point of intersection between the limb of the occultor and the\nlimb of the occulted body and/or the point of intersection between the limb\nof the occultor and the terminator of the occulted body.\nThe former is given by\n\\citep[c.f. Equation~24 in][]{Luger2019}\n%\n\\begin{proof}{pT}\n    \\phi_0 & =\n    \\frac{\\pi}{2} \\pm \\left(\\arcsin\\left(\\frac{1 - r_\\mathrm{o} ^ 2 - b_\\mathrm{o} ^ 2}{2 b_\\mathrm{o} r_\\mathrm{o}}\\right) - \\frac{\\pi}{2}\\right)\n    \\quad,\n\\end{proof}\n%\nwhere the sign is chosen such that the point\n$(r_\\mathrm{o}\\cos\\phi_0, b_\\mathrm{o} + r_\\mathrm{o}\\sin\\phi_0)$ is on the dayside of the occulted body,\nand the latter (of which there may be multiple) is given by\n%\n\\begin{proof}{pT}\n    \\pmb{\\phi_1} & =\n    \\theta' +\n    \\atantwo\n    \\left(b\\sqrt{1 - {\\mathbf{x''}}^2} - y''_\\mathrm{o}, \\mathbf{x''} - x''_\\mathrm{o}\\right)\n    \\quad\n\\end{proof}\n%\nwhere $\\mathbf{x''}$ are the roots of the quartic (Equation~\\ref{eq:quartic}).\nThese angles are then wrapped to the range $[0, 2\\pi)$\nand sorted into the vector $\\pmb{\\phi}$ such that\nthe integration is always performed in a counter-clockwise sense about\nthe center of the integration region.\n%\nThe left panel in Figure~\\ref{fig:geometry} shows a configuration in which\nthe lower integration limit $\\phi_0 = 158.2^\\circ$ corresponds to the\npoint of intersection between the limbs of the two bodies and the upper\nintegration limit $\\phi_1 = 223.3^\\circ$ corresponds to the\nlimb-terminator intersection. Both angles are measured counter-clockwise\nfrom the line $x' = b_\\mathrm{o}$.\n\nIn order to evaluate the integral in Equation~(\\ref{eq:pT}),\nwe follow the reparametrization tricks of \\S{D.2.3} in \\citet{Luger2019}.\nThe algebra is long and tedious, so we merely present the result\n(alongside the usual validation links). The $n^\\text{th}$ component\nof $\\pT$ is\n%\n\\begin{proof}{pT}\n    \\label{eq:pTsoln}\n    \\mathbb{p}_n & =\n    \\resizebox{.8\\hsize}{!}{$\n            \\begin{cases}\n                %\n                2(2r_\\mathrm{o})^{l+2}\n                %\n                \\begin{cases}\n                    %\n                    V\n                    \\left(\n                    \\frac{\\mu+4}{4},\n                    \\frac{\\nu}{2},\n                    0;\n                    \\viI\n                    \\right)\n                    %\n                     & \\qquad \\qquad \\qquad \\qquad \\qquad\n                    \\qquad \\qquad \\qquad \\quad\n                    \\frac{\\mu}{2} \\, \\text{even}\n                    \\\\[0.5em]\n                    %    \n                    V\n                    \\left(\n                    \\frac{\\mu + 2}{4},\n                    \\frac{\\nu}{2},\n                    0;\n                    \\viU\n                    \\right)\n                    %\n                     & \\qquad \\qquad \\qquad \\qquad \\qquad\n                    \\qquad \\qquad \\qquad \\quad\n                    \\frac{\\mu}{2} \\, \\text{odd}\n                    %\n                \\end{cases}\n                %\n                 & \\qquad\n                \\mu, \\nu \\, \\text{even}\n                %\n                \\\\[2em]\n                %\n                \\mathbb{p}_2\n                %\n                 & \\qquad\n                \\mu = \\nu = 1\n                %\n                \\\\[1.5em]\n                %\n                \\beta (2r_\\mathrm{o})^{l-1}\n                %\n                \\begin{cases}\n                    %\n                    \\begin{cases}\n                        %\n                        V\n                        \\left(\n                        \\frac{l-2}{2},\n                        0,\n                        0;\n                        \\viJ\n                        \\right) -\n                        2\n                        V\n                        \\left(\n                        \\frac{l-2}{2},\n                        0,\n                        1;\n                        \\viJ\n                        \\right)\n                        %\n                         & \\qquad \\quad  \\enspace\n                        l \\, \\text{even}\n                        %\n                        \\\\[1em]\n                        %\n                        V\n                        \\left(\n                        \\frac{l-3}{2},\n                        1,\n                        0;\n                        \\viJ\n                        \\right) -\n                        2V\n                        \\left(\n                        \\frac{l-3}{2},\n                        1,\n                        1;\n                        \\viJ\n                        \\right)\n                        %\n                         & \\qquad \\quad  \\enspace\n                        l \\, \\text{odd} \\ne 1\n                        %\n                    \\end{cases}\n                    %\n                     & \\qquad\n                    \\mu = 1\n                    %\n                    \\\\[3em]\n                    %\n                    \\begin{cases}\n                        %\n                        2\n                        V\n                        \\left(\n                        \\frac{\\mu-1}{4},\n                        \\frac{\\nu-1}{2},\n                        0;\n                        \\viJ\n                        \\right)\n                        %\n                         & \\qquad \\qquad \\qquad \\qquad\n                        \\frac{\\mu - 1}{2} \\, \\text{even}\n                        %\n                        \\\\[1em]\n                        %\n                        2\n                        V\n                        \\left(\n                        \\frac{\\mu-1}{4},\n                        \\frac{\\nu-1}{2},\n                        0;\n                        \\viW\n                        \\right)\n                        %\n                         & \\qquad \\qquad \\qquad \\qquad\n                        \\frac{\\mu - 1}{2} \\, \\text{odd}\n                        %\n                    \\end{cases}\n                    %\n                     & \\qquad\n                    \\mu > 1\n                    %\n                \\end{cases}\n                %\n                 & \\qquad\n                \\mu, \\nu \\, \\text{odd}\n                %\n            \\end{cases}\n        $}\n\\end{proof}\n%\nwhere $\\beta = \\left(1 - (b_\\mathrm{o} - r_\\mathrm{o})^2\\right)^\\frac{3}{2}$\nand we define the Vieta operator\n%\n\\begin{proof}{pT}\n    \\label{eq:V}\n    V\\left(u, v, w; \\mathbf{x}\\right) \\equiv\n    \\sum_{i=0}^{u + v}\n    \\mathcal{A}_{u, v, i}\n    x_{u + w + i}\n\\end{proof}\n%\nas the dot product of a vector $\\mathbf{x}$ and\nthe vector of Vieta's theorem coefficients, where\n\\citep[c.f. Equation~D34 in][]{Luger2019}\n%\n\\begin{proof}{pT}\n    \\label{eq:vieta}\n    \\mathcal{A}_{u,v,i} & =\n    \\sum_{j=\\text{max}(0,u-i)}^{\\text{min}(u+v-i,u)}\n    \\binom{u}{j}\n    \\binom{v}{u+v-i-j}\n    (-1)^{u+j}\\left(\\frac{b_\\mathrm{o}-r_\\mathrm{o}}{2r_\\mathrm{o}}\\right)^{u+v-i-j}\n    \\quad.\n\\end{proof}\n%\nThe vectors $\\viI$, $\\viJ$,\n$\\viU$, and $\\viW$ are solutions\nto specific integrals, which we compute recursively below. As in\n\\citet{Luger2019} the $n = 2$ term of $\\pT$, $\\mathbb{p}_2$,\nis handled separately; we also compute this below.\n\nNote that several of the cases in Equation~(\\ref{eq:pTsoln}) are\nidentical to those in Equation~(D35) of \\citet{Luger2019}, provided\nwe replace their integrals $\\mathcal{I}$ and $\\mathcal{J}$ with our\nintegrals $\\viI$ and $\\viJ$, respectively. The integrals themselves\nare similar, except for a change in the limits of integration, which\nare no longer symmetric about zero. As we will see, this leads to the\ndependence of these expressions on \\emph{incomplete} elliptic integrals.\nNote also that the integrals $\\viU$ and $\\viW$ are new, as certain\ncancellations in \\citet{Luger2019} resulted in the corresponding cases\ncontributing zero net flux \\citep[last case in Equation~D35 of][]{Luger2019}.\n\n%\n\n\\subsubsection{The vector $\\viI$}\n\\label{sec:I}\n%\nThe components of the vector $\\viI$ are given by the integral\n%\n\\begin{align}\n    \\label{eq:I}\n    \\iI_v(\\valpha) & =\n    \\vint{\\valpha}{\\sin^{2v}\\varphi}\n    \\quad,\n\\end{align}\n%\nfor $v \\in [0, \\vmax]$,\nwhere we define the helper angle\n%\n\\begin{align}\n    \\label{eq:alpha}\n    \\valpha \\equiv \\frac{\\pmb{\\phi}}{2} + \\frac{\\pi}{4}\n    \\quad.\n\\end{align}\n%\nThe integral in the expression above is the same as that in Equation (D38)\nof \\citet{Luger2019}, except for a change in the limits of integration.\nAs in \\citet{Luger2019}, we can compute the vector $\\viI$ recursively given\na trivial lower boundary condition:\n%\n\\begin{proof}{I}\n    \\label{eq:Irec}\n    \\iI_0(\\valpha) &=\n    \\Delta \\valpha\n    %\n    \\nonumber \\\\\n    %\n    \\iI_v(\\valpha) &=\n    \\frac{1}{2v}\n    \\bigg(\n    (2v - 1) \\iI_{v-1}(\\valpha) -\n    \\Delta \\left(\\sin^{2v - 1}\\valpha\\cos^{2v -1}\\valpha\\right)\n    \\bigg)\n\\end{proof}\n%\nwhere the last expression is valid for all $v > 0$. We find that this algorithm\nis generally stable, except when\n$\\sin\\valpha$ is small.\nIn that limit, we evaluate $\\iI_\\vmax(\\valpha)$\nby numerical integration of\nEquation~(\\ref{eq:I}) using Gauss-Legendre quadrature with \\STARRYQUADPOINTS\npoints. We then recurse downward by substituting $v \\rightarrow v + 1$ in\nEquation~(\\ref{eq:Irec}) and solving for $\\iI_v(\\valpha)$.\n\n%\n\n\\subsubsection{The vector $\\viJ$}\n\\label{sec:J}\n%\nThe components of the vector $\\viJ$ are given by the integral\n%\n\\begin{align}\n    \\label{eq:J}\n    \\iJ_v(k^2, \\valpha) =\n    \\vint{\\valpha}{\n        \\sin^{2v}\\varphi\n        \\left(1 - \\frac{\\sin^2\\varphi}{k^2}\\right)^\\frac{3}{2}\n    }\n    \\quad,\n\\end{align}\n%\nwhere\n%\n\\begin{align}\n    \\label{eq:k2}\n    k^2 & \\equiv \\frac{1 - r_\\mathrm{o}^2 - b_\\mathrm{o}^2 + 2 b_\\mathrm{o} r_\\mathrm{o}}{4 b_\\mathrm{o} r_\\mathrm{o}}\n    \\quad.\n\\end{align}\n%\nThe integral in this expression is again the same as that in Equation (D39)\nof \\citet{Luger2019}, except for a change in the limits of integration.\nIn that paper, we computed all terms\n$\\{ \\iJ_0, {\\cdot\\cdot\\cdot}, \\iJ_\\vmax \\}$ from a three-term\nrecurrence relation and two boundary conditions. In the case of upward\nrecursion, the boundary conditions $\\iJ_0$ and $\\iJ_1$ were\ncomputed analytically from the complete elliptic integrals $K(k^2)$\nand $E(k^2)$. In cases where upward recursion was not numerically stable, we\nevaluated $\\iJ_\\vmax$ and $\\iJ_{\\vmax-1}$\nvia a quickly convergent series expansion and recursed downward.\n\nIn order to solve Equation~(\\ref{eq:J}), it is possible to\nreplace the complete elliptic integrals $K(k^2)$ and $E(k^2)$ in the lower\nboundary conditions \\citep[Equation D46 in ][]{Luger2019} with the\nincomplete elliptic integrals\n%\n\\begin{align}\n    \\label{eq:F}\n    F(\\psi \\,|\\, m) & \\equiv \\int_0^{\\psi} \\frac{\\dd \\varphi}{\\sqrt{1 - m \\sin^2 \\varphi}}\n    \\\\\n    \\intertext{and}\n    \\label{eq:E}\n    E(\\psi \\,|\\, m) & \\equiv \\int_0^{\\psi} \\sqrt{1 - m \\sin^2 \\varphi} \\, \\dd \\varphi\n    \\quad,\n\\end{align}\n%\nwhich we compute from the $el\\mathit{2}$ parametrization of\n\\citet{Bulirsch1965},\n%\nthen use the same upward\nrecursion relation to obtain analytic solutions for all $\\iJ_v$:\n%\n\\begin{proof}{J}\n    \\label{eq:Jrec}\n    \\iJ_0(k^2, \\valpha) &=\n    \\frac{1}{3} \\bigg(\n    2 \\left(2 - \\frac{1}{k^2}\\right) \\DE +\n    \\left(\\frac{1}{k^2} - 1\\right) \\DF +\n    \\Delta \\mathbf{z}_0(k^2, \\valpha)\n    \\bigg)\n    %\n    \\nonumber \\\\\n    %\n    \\iJ_1(k^2, \\valpha) &=\n    \\frac{1}{15} \\bigg(\n    \\left(-3 k^2 + 13 - \\frac{8}{k^2}\\right) \\DE\n    \\nonumber \\\\\n    &\\qquad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\n    +\n    \\left(3 k^2 - 7 + \\frac{4}{k^2}\\right) \\DF +\n    \\Delta \\mathbf{z}_1(k^2, \\valpha)\n    \\bigg)\n    %\n    \\nonumber \\\\\n    %\n    \\iJ_v(k^2, \\valpha) &=\n    \\frac{1}{2v + 3}\n    \\bigg(\n    2 \\left( v + 1 + (v - 1) k^2 \\right) \\iJ_{v - 1}(k^2, \\valpha)\n    \\nonumber \\\\\n    &\\qquad\\qquad\\quad\\quad\\quad\\quad\n    -\n    (2v - 3) k^2 \\iJ_{v - 2}(k^2, \\valpha)\n    + \\Delta \\mathbf{z}_v(k^2, \\valpha)\n    \\bigg)\n\\end{proof}\n%\n%\nwhere the last expression is valid for all $v > 1$ and\n%\n\\begin{proof}{J}\n    \\label{eq:Jrec_z}\n    \\mathbf{z}_0(k^2, \\valpha) & =\n    \\frac{\n        \\sin\\valpha\n        \\cos\\valpha\n        \\,\n        \\mathbf{q}(k^2, \\valpha)\n    }{\n        k^2\n    }\n    %\n    \\nonumber\\\\\n    %\n    \\mathbf{z}_1(k^2, \\valpha) & =\n    \\left(3 \\sin^2\\valpha + 4 - 6k^2\\right)\n    \\mathbf{z}_0(k^2, \\valpha)\n    %\n    \\nonumber\\\\\n    %\n    \\mathbf{z}_v(k^2, \\valpha) & =\n    k^2\n    \\sin^{2v - 3}\\valpha\n    \\cos\\valpha\n    \\,\n    \\mathbf{q}(k^2, \\valpha)^5\n    \\quad,\n\\end{proof}\n%\nwith\n%\n\\begin{align}\n    \\label{eq:q}\n    \\mathbf{q}(k^2, \\valpha) = \\sqrt{1 - \\frac{\\sin^2\\valpha}{k^2}}\n    \\quad.\n\\end{align}\n%\nNote that when $k^2 < 1$ we use the reciprocal-modulus transformation\nto evaluate the elliptic integrals:\n%\n\\begin{align}\n    F\\left(\\psi \\,\\Big|\\, \\frac{1}{k^2}\\right) & =\n    k \\, F(\\beta \\,|\\, k^2)\n    \\nonumber                                                                               \\\\\n    E\\left(\\psi \\,\\Big|\\, \\frac{1}{k^2}\\right) & =\n    \\frac{E(\\beta \\,|\\, k^2) - (1 - k^2) F(\\beta \\,|\\, k^2)}{k}\n    \\\\\n    \\intertext{with}\n    \\beta                                      & = \\arcsin\\left( \\frac{\\sin\\psi}{k} \\right)\n    \\quad.\n\\end{align}\n%\n\nIn practice, however, we find that this procedure is even more numerically\nunstable than it was in \\citet{Luger2019}.\nTo address this, we express the recurrence structure of the problem as\na tridiagonal system with one lower boundary condition $\\iJ_0$\nand one upper boundary condition $\\iJ_\\vmax$:\n%\n\\begin{proof}{J}\n    \\label{eq:Jtri}\n    \\begin{pmatrix}\n        a_0 & 1   &     &        &         &         \\\\\n        b_1 & a_1 & 1   &        &         &         \\\\\n            & b_2 & a_2 & 1      &         &         \\\\\n            &     & b_0 & a_3    & 1       &         \\\\\n            &     &     & \\ddots & \\ddots  & \\ddots  \\\\\n            &     &     &        & b_\\vmax & a_\\vmax\n    \\end{pmatrix}\n    \\begin{pmatrix}\n        \\iJ_1           \\\\\n        \\iJ_2           \\\\\n        \\iJ_3           \\\\\n        \\iJ_4           \\\\\n        \\cdot\\cdot\\cdot \\\\\n        \\iJ_{\\vmax-1}\n    \\end{pmatrix}\n    =\n    \\begin{pmatrix}\n        c_0 - b_0 \\iJ_0 \\\\\n        c_1             \\\\\n        c_2             \\\\\n        c_3             \\\\\n        \\cdot\\cdot\\cdot \\\\\n        c_\\vmax - \\iJ_\\vmax\n    \\end{pmatrix}\n\\end{proof}\n%\nwhere the recursion coefficients are given by\n%\n\\begin{proof}{J}\n    \\label{eq:Jtri_coeffs}\n    a_v(k) &= -2\\frac{(v + 1) + (v - 1) k^2}{2v + 3} \\nonumber \\\\\n    b_v(k) &= \\frac{(2v - 3) k^2}{2v + 3} \\nonumber \\\\\n    c_v(k^2, \\valpha) &= \\Delta\n    \\bigg(\n    \\frac{\n            \\mathbf{z}_v(k^2, \\valpha)\n        }{\n            2v + 3\n        }\n    \\bigg)\n    \\quad.\n\\end{proof}\n%\nSolving this matrix system yields values for all\nintermediate $\\{ \\iJ_1, {\\cdot\\cdot\\cdot}, \\iJ_{\\vmax - 1} \\}$.\nWhile efficient algorithms exist for solving tridiagonal problems, we obtain\nfar better numerical stability by instead performing traditional LU\ndecomposition. We find that this algorithm is stable in all the regimes that we\ntested.\n\nWe evaluate the upper boundary condition $\\iJ_{\\vmax}$ by numerical\nintegration of Equation~(\\ref{eq:J}) via Gauss-Legendre quadrature with\n\\STARRYQUADPOINTS points. While the lower boundary condition may be computed\nanalytically from Equation~(\\ref{eq:Jrec}),\nin practice we achieve better precision via numerical\nintegration (as above), with negligible effects on computational performance.\n\n%\n\n\\subsubsection{The vector $\\viU$}\n\\label{sec:U}\n%\nThe components of the vector $\\viU$ are given by the integral\n%\n\\begin{align}\n    \\label{eq:U}\n    \\iU_v(\\valpha) =\n    \\vint{\\valpha}{\\cos\\varphi\\sin^{2v + 1}\\varphi}\n    \\quad.\n\\end{align}\n%\nThis integral has an analytic solution for all $v$:\n%\n\\begin{proof}{U}\n    \\label{eq:Usol}\n    \\iU_v(\\valpha) &= \\frac{\\Delta \\sin^{2v+2}\\valpha}{2v + 2}\n    \\quad.\n\\end{proof}\n%\n\n\\subsubsection{The vector $\\viW$}\n\\label{sec:W}\n%\nThe components of the vector $\\viW$ are given by the integral\n%\n\\begin{align}\n    \\label{eq:W}\n    \\iW_v(k^2, \\valpha) =\n    \\vint{\\valpha}{\n        \\cos\\varphi\\sin^{2v + 1}\\varphi\n        \\left(1 - \\frac{\\sin^2\\varphi}{k^2}\\right)^\\frac{3}{2}\n    }\n    \\quad.\n\\end{align}\n%\nWe may compute it by either upward or downward recursion. In both cases,\nwe compute each of the $\\iW_v$ from\n%\n\\begin{proof}{W}\n    \\iW_v(k^2, \\valpha) = \\Delta \\mathbf{b}_v(k^2, \\valpha)\n    \\quad.\n\\end{proof}\n%\nIn the upward case, we start with the lower boundary conditions\n%\n\\begin{proof}{W}\n    \\mathbf{b}_0(k^2, \\valpha) &=\n    \\frac{\\sin^2\\valpha}{5}\n    \\left(\n    \\frac{1 - \\mathbf{q}(k^2, \\valpha)^3}{1 - \\mathbf{q}(k^2, \\valpha)^2}\n    +\n    \\mathbf{q}(k^2, \\valpha)^3\n    \\right)\n    \\nonumber \\\\\n    \\mathbf{c}_0(k^2, \\valpha) & =\n    \\sin^4\\valpha \\,\n    \\frac{\\mathbf{q}(k^2, \\valpha)^5}{1 - \\mathbf{q}(k^2, \\valpha)^2}\n    \\quad,\n\\end{proof}\n%\nand recurse upward in $\\mathbf{b}$ and $\\mathbf{c}$ simultaneously:\n%\n\\begin{proof}{W}\n    \\mathbf{b}_v(k^2, \\valpha) & =\n    \\frac{1}{2v + 5}\n    \\left(\n    \\frac{2 v \\sin^2\\valpha}{1 - \\mathbf{q}(k^2, \\valpha)^2}\n    \\mathbf{b}_{v - 1}(k^2, \\valpha)\n    - \\mathbf{c}_{v - 1}(k^2, \\valpha)\n    \\right)\n    \\nonumber\n    \\\\\n    \\mathbf{c}_v(k^2, \\valpha) & =\n    \\sin^2\\valpha \\, \\mathbf{c}_{v - 1}(k^2, \\valpha)\n\\end{proof}\n%\nfor $v > 0$.\n%\nIn the case of downward recursion, we start with the upper boundary\nconditions\n%\n\\begin{proof}{W}\n    \\mathbf{b}_\\vmax &=\n    \\frac{\\sin^{2\\vmax + 2}\\valpha}{4\\vmax + 10}\n    \\left(\n    \\mathbf{f}_\\vmax(k^2, \\valpha)\n    + 2 \\mathbf{q}(k^2, \\valpha)^3\n    \\right)\n    \\nonumber \\\\\n    \\mathbf{c}_\\vmax &=\n    \\frac{1}{2}\n    \\mathbf{q}(k^2, \\valpha)^5\n    \\sin^{2\\vmax}\\valpha\n    \\quad,\n\\end{proof}\n%\nwhere\n%\n\\begin{proof}{W}\n    \\mathbf{f}_v(k^2, \\valpha)\n    &\\equiv\n    \\frac{3}{v+1}\n    \\,\n    {_2\\pmb{F}_1}\\left(\n    -\\frac{1}{2},\n    v + 1;\n    v + 2;\n    1 - \\mathbf{q}(k^2, \\valpha)^2\n    \\right)\n\\end{proof}\n%\nand ${_2\\pmb{F}_1}(a, b; c; \\mathbf{z})$ is the Gauss\nhypergeometric function, which we compute via its series\ndefinition.\n%\nWe recurse downward in $\\mathbf{b}$ and $\\mathbf{c}$ simultaneously:\n%\n\\begin{proof}{W}\n    \\mathbf{b}_v(k^2, \\valpha) & =\n    \\frac{1 - \\mathbf{q}(k^2, \\valpha)^2}{\\sin^2\\valpha}\n    \\left(1 + \\frac{5}{2v + 2}\\right)\n    \\mathbf{b}_{v + 1}(k^2, \\valpha) +\n    \\frac{\\mathbf{c}_{v + 1}(k^2, \\valpha)}{v + 1}\n    \\nonumber\n    \\\\\n    \\mathbf{c}_v(k^2, \\valpha) & =\n    \\frac{\\mathbf{c}_{v + 1}(k^2, \\valpha)}{\\sin^2\\valpha}\n    \\quad.\n\\end{proof}\n\n%\n\n\\subsection{The term $\\mathbb{p}_2$}\n\\label{sec:p2}\n%\nThe final integral we must solve is that corresponding to\n$\\mathbb{p}_2$ ($\\mu = \\nu = 1$). As in \\citet{Luger2019}, this is\nthe integral of the linear limb darkening term,\nwhose solution must be handled\nseparately due to the fact that the corresponding antiderivative\nin Equation~(\\ref{eq:G}) is not a polynomial in $x$, $y$, and $z(x, y)$;\nalso see \\citet{Agol2020}.\nThe integral we must solve is\n%\n\\begin{align}\n    \\label{eq:p2}\n    \\mathbb{p}_2 & =\n    \\vint{\\pmb{\\phi}}{\n        \\frac{1}{3}\n        \\left(\n        \\frac{\n            1 - z(r_\\mathrm{o}\\cos\\varphi, b_\\mathrm{o} + r_\\mathrm{o}\\sin\\varphi)^3\n        }{\n            1 - z(r_\\mathrm{o}\\cos\\varphi, b_\\mathrm{o} + r_\\mathrm{o}\\sin\\varphi)^2\n        }\n        \\right)\n        \\left(r_\\mathrm{o}^2 + b_\\mathrm{o} r_\\mathrm{o} \\sin\\varphi\\right)\n    }\n    \\quad,\n\\end{align}\n%\nwhere $z$ is the usual Cartesian coordinate (Equation~\\ref{eq:z}).\nThe solution is tricky, but fortunately a similar integral was solved in\nEquation~(34) of \\citet{Pal2012}. Adapting their solution to our formalism,\nwe obtain\n%\n\\begin{proof}{p2}\n    \\label{eq:p2_soln}\n    \\mathbb{p}_2 & =\n    \\frac{1}{3}\n    \\Big(\n    c_0 +\n    c_1 \\DF +\n    c_2 \\DE +\n    c_3 \\DPi\n    \\Big)\n\\end{proof}\n%\nwhere\n%\n\\begin{proof}{p2}\n    c_0 &=\n    \\Delta\n    \\Bigg\\{\n    -\\atantwo\\left(\n    -(b_\\mathrm{o} - r_\\mathrm{o}) \\cos\\valpha, (b_\\mathrm{o} + r_\\mathrm{o}) \\sin\\valpha\n    \\right)\n    + \\valpha\n    \\nonumber \\\\\n    &\\qquad\\enspace\\enspace\n    - \\frac{4}{3} b_\\mathrm{o} r_\\mathrm{o}\n    \\sin\\valpha \\cos\\valpha\n    \\sqrt{1 - (b_\\mathrm{o} - r_\\mathrm{o})^2 - 4 b_\\mathrm{o} r_\\mathrm{o} \\sin^2\\alpha}\n    \\nonumber \\\\\n    &\\qquad\\enspace\\enspace\n    + \\pmb{\\delta}(b_\\mathrm{o}, r_\\mathrm{o}, \\valpha)\n    \\Bigg\\}\n    \\nonumber \\\\[0.5em]\n    c_1 &=\n    \\frac{1 + b_\\mathrm{o}^4 - b_\\mathrm{o}^2(5 + 2 r_\\mathrm{o}^2) + r_\\mathrm{o}^4 + r_\\mathrm{o}^2}{3 \\sqrt{1 - (b_\\mathrm{o} - r_\\mathrm{o})^2}}\n    \\nonumber \\\\[0.5em]\n    c_2 &= \\frac{(b_\\mathrm{o}^2+7r_\\mathrm{o}^2-4)\\sqrt{1 - (b_\\mathrm{o} - r_\\mathrm{o})^2}}{3}\n    \\nonumber \\\\[0.5em]\n    c_3 &= \\frac{b_\\mathrm{o} + r_\\mathrm{o}}{(b_\\mathrm{o} - r_\\mathrm{o})\\sqrt{1 - (b_\\mathrm{o} - r_\\mathrm{o})^2}}\n    \\quad,\n    \\\\\n    \\intertext{and}\n    %\n    \\delta(b_\\mathrm{o}, r_\\mathrm{o}, \\alpha) &=\n    \\begin{cases}\n        -2\\pi\n         &\n        \\qquad\n        \\alpha > \\frac{3\\pi}{2} \\,\\, \\text{and} \\,\\, b_\\mathrm{o} > r_\\mathrm{o}\n        \\\\\n        +2\\pi\n         &\n        \\qquad\n        \\alpha > \\frac{3\\pi}{2} \\,\\, \\text{and} \\,\\, b_\\mathrm{o} < r_\\mathrm{o}\n        \\\\\n        0\n         &\n        \\qquad\n        \\text{otherwise}\n        \\quad.\n    \\end{cases}\n\\end{proof}\n%\nThe quantities $\\pmb{F}(\\valpha \\,|\\, \\nicefrac{1}{k^2})$ and\n$\\pmb{E}(\\valpha \\,|\\, \\nicefrac{1}{k^2})$\nare the same incomplete elliptic integrals as those in\n\\S\\ref{sec:J}, while\n%\n\\begin{align}\n    \\label{eq:Pi}\n    \\Pi(n; \\psi \\,|\\, m) & \\equiv\n    \\int_0^{\\psi}\n    \\frac{\\dd \\varphi}{(1 - n \\sin^2\\varphi)\\sqrt{1 - m \\sin^2 \\varphi}}\n\\end{align}\n%\nis the incomplete elliptic integral of the third\nkind, with\n%\n\\begin{proof}{p2}\n    \\label{eq:n}\n    n & = -\\frac{4 b_\\mathrm{o} r_\\mathrm{o}}{(r_\\mathrm{o} - b_\\mathrm{o})^2}\n    \\quad.\n\\end{proof}\n%\n\nWhile stable algorithms exist to evaluate $\\Pi(n; \\psi \\,|\\, m)$\n\\citep[e.g.][]{Bulirsch1969}, we find that the parametrization above has\npoor numerical stability, particularly in the vicinity of the singular\npoints $b_\\mathrm{o} = r_\\mathrm{o}$ and $b_\\mathrm{o} = 1 + r_\\mathrm{o}$. In practice, we find that\nnumerical evaluation of Equation~(\\ref{eq:p2}) via Gaussian quadrature\nis more numerically stable and just as computationally efficient as\nthe procedure outlined above.\n\n\\subsection{The integral along the terminator, $\\tT$}\n\\label{sec:tT}\n%\nIn this section we present a solution to Equation~(\\ref{eq:tT}), the\nline integral along the day/night terminator of the occulted body. As\nbefore, the first thing we must do is derive expressions for the integration\nlimits $\\pmb{\\xi}$.\n%\nDepending on the integration case, these limits\nwill corresponds to the point of intersection between the terminator and\nthe limb of the occultor and/or the point of intersection between the\nterminator and the limb of the occulted body. The former is given by\n%\n\\begin{proof}{tT}\n    \\pmb{\\xi_0} &=\n    \\atantwo\\left(\\sqrt{1 - {\\mathbf{x''}}^2}, \\mathbf{x''} \\right)\n\\end{proof}\n%\nwhere $\\mathbf{x''}$ are the roots of the quartic (Equation~\\ref{eq:quartic}).\nThe latter is given by\n%\n\\begin{proof}{tT}\n    \\xi_1 &=\n    \\begin{cases}\n        0   & \\qquad \\qquad (1 - x_\\mathrm{o}'')^2 + {y_\\mathrm{o}''}^2 < r_\\mathrm{o}^2\n        \\\\\n        \\pi & \\qquad \\qquad \\text{otherwise}\n        \\quad.\n    \\end{cases}\n\\end{proof}\n%\nAs before, these angles are then\nwrapped to the range $[0, 2\\pi)$ and\nsorted into the vector\n$\\pmb{\\xi}$ such that the integration is performed counter-clockwise\nabout the center of the integration region.\n%\nThe middle panel of Figure~\\ref{fig:geometry} shows a case where\n$\\xi_0 = 96.5^\\circ$ corresponds to the point of intersection between the occultor\nlimb and the terminator and $\\xi_1 = 0^\\circ$ corresponds to the\npoint where the terminator extends onto the backside of the body.\n%\nNote, importantly, that unlike $\\pmb{\\phi}$, the angle $\\pmb{\\xi}$ is not\nmeasured between the horizontal and a point on the curve of $\\mathcal{T}$.\nRecall that $\\pmb{\\xi}$ is an angular parameter of the ellipse, so it is\nmeasured in the same way as the eccentric anomaly in a Keplerian orbit:\nit is the\nangle between the semi-major axis of the ellipse and the perpendicular\nprojection of a point on the ellipse onto the unit circle\n(see Figure~\\ref{fig:geometry}).\n\nThe solution to Equation~(\\ref{eq:tT}) involves repeated application\nof the binomial theorem.\nIf we define the quantities\n%\n\\begin{proof}{tT}\n    \\label{eq:Zuvjk}\n    Z^{u,v}_{j,k}(b, \\theta') & =\n    \\binom{u}{j}\n    \\binom{v}{k}\n    (-1)^{v-k}\n    b^{u+v-j-k}\n    \\sin^{v+j-k}\\theta'\n    \\cos^{u-j+k}\\theta'\n    \\nonumber\n    \\\\\n    \\intertext{and}\n    %\n    \\delta(b, \\xi) & =\n    \\begin{cases}\n        0                        & \\qquad 0 \\leq \\xi < \\frac{\\pi}{2}     \\\\\n        \\pi                      & \\qquad \\frac{\\pi}{2} \\leq \\xi < \\pi   \\\\\n        2 |b| b_\\mathrm{c}       & \\qquad \\pi \\leq \\xi < \\frac{3\\pi}{2}  \\\\\n        \\pi + 2 |b| b_\\mathrm{c} & \\qquad \\frac{3\\pi}{2} \\leq \\xi < 2\\pi\n        \\quad,\n    \\end{cases}\n\\end{proof}\n%\nwe may express the solution to the $\\mathbb{t}_n$ integral as\n\n%\n\\clearpage\n%\n\n\\begin{proof}{tT}\n    \\label{eq:tn}\n    \\mathbb{t}_n & =\n    \\begin{cases}\n        %\n        %\n        b\\cos\\theta'\n        \\sum\\limits_{j=0}^{\\frac{\\nu}{2}}\n        \\sum\\limits_{k=0}^{\\frac{\\mu + 2}{2}}\n        Z^{\\frac{\\nu}{2}, \\frac{\\mu+2}{2}}_{j,k}\n        (b, \\theta') \\,\n        \\iH_{j + k + 1, l + 1 - j - k}(\\pmb{\\xi})\n        \\\\\n        \\quad\\quad\\quad\\quad\n        - \\, \\sin\\theta'\n        \\sum\\limits_{j=0}^{\\frac{\\nu}{2}}\n        \\sum\\limits_{k=0}^{\\frac{\\mu + 2}{2}}\n        Z^{\\frac{\\nu}{2}, \\frac{\\mu+2}{2}}_{j,k}\n        (b, \\theta') \\,\n        \\iH_{j + k, l + 2 - j - k}(\\pmb{\\xi})\n        %\n         & \\qquad\n        \\mathrel{\\raisebox{1.25em}{$\\mu, \\nu, \\, \\text{even}$}}\n        %\n        %\n        \\\\[3em]\n        %\n        %\n        \\frac{1}{3}\n        \\Delta\n        \\Big\\{\n        \\arctan\\left( \\frac{|b|\\sin\\vxi}{\\cos\\vxi} \\right)\n        \\\\\n        \\qquad\\quad\\quad\n        - \\, \\sgn\\left({\\sin\\vxi}\\right)\n        \\left(\n        \\arctan\n        \\left(\n            \\frac{\n                \\left(\\frac{\\sin\\vxi}{1 + \\cos\\vxi}\\right)^2 + 2 b^2 - 1\n            }{2 |b| b_\\mathrm{c}}\n            \\right)\n        + |b| b_\\mathrm{c} \\cos\\vxi\n        \\right)\n        %\n         & \\qquad \\mu = \\nu = 1\n        %\n        \\\\\n        \\qquad\\quad\\quad\n        + \\, \\pmb{\\delta}(b, \\vxi)\n        \\Big\\}\n        %\n        \\\\[3em]\n        %\n        %\n        -bb_c^3\\sin\\theta'\n        \\sum\\limits_{j=0}^{l-2}\n        Z^{0, l-2}_{0,j}\n        (b, \\theta') \\,\n        \\iH_{j + 1, l + 1 - j}(\\pmb{\\xi})\n        \\\\\n        \\quad\\quad\\quad\\quad\n        - \\, b_\\mathrm{c}^3\\cos\\theta'\n        \\sum\\limits_{j=0}^{l-2}\n        Z^{0, l-2}_{0,j}\n        (b, \\theta') \\,\n        \\iH_{j, l + 2 - j}(\\pmb{\\xi})\n        %\n         & \\qquad\n        \\mathrel{\\raisebox{1.25em}{$\\nu \\, \\text{odd}, \\mu = 1, l \\, \\text{even}$}}\n        %\n        %\n        \\\\[3em]\n        %\n        %\n        -bb_c^3\\sin^2\\theta'\n        \\sum\\limits_{j=0}^{l-3}\n        Z^{0, l-3}_{0,j}\n        (b, \\theta') \\,\n        \\iH_{j + 2, l - j}(\\pmb{\\xi})\n        \\\\\n        \\quad\\quad\\quad\\quad\n        - \\, b b_\\mathrm{c}^3\\cos^2\\theta'\n        \\sum\\limits_{j=0}^{l-3}\n        Z^{0, l-3}_{0,j}\n        (b, \\theta') \\,\n        \\iH_{j, l + 2 - j}(\\pmb{\\xi})\n        %\n        %\n         & \\qquad\n        \\mathrel{\\raisebox{0em}{$\\nu \\, \\text{odd}, \\mu = 1, l \\, \\text{odd}$}}\n        %\n        \\\\\n        \\quad\\quad\\quad\\quad\n        - \\, b_\\mathrm{c}^5\\sin\\theta'\\cos\\theta'\n        \\sum\\limits_{j=0}^{l-3}\n        Z^{0, l-3}_{0,k}\n        (b, \\theta') \\,\n        \\iH_{j + 1, l + 1 - j}(\\pmb{\\xi})\n        %\n        %\n        %\n        \\\\[3em]\n        bb_c^3\\cos\\theta'\n        \\sum\\limits_{j=0}^{\\frac{\\nu}{2}}\n        \\sum\\limits_{k=0}^{\\frac{\\mu + 2}{2}}\n        Z^{\\frac{\\nu-1}{2}, \\frac{\\mu - 3}{2}}_{j,k}\n        (b, \\theta') \\,\n        \\iH_{j + k + 1, l + 1 - j - k}(\\pmb{\\xi})\n        \\\\\n        \\quad\\quad\\quad\\quad\n        - \\, b_\\mathrm{c}^3\\sin\\theta'\n        \\sum\\limits_{j=0}^{\\frac{\\nu}{2}}\n        \\sum\\limits_{k=0}^{\\frac{\\mu + 2}{2}}\n        Z^{\\frac{\\nu-1}{2}, \\frac{\\mu - 3}{2}}_{j,k}\n        (b, \\theta') \\,\n        \\iH_{j + k, l + 2 - j - k}(\\pmb{\\xi})\n        %\n         & \\qquad\n        \\mathrel{\\raisebox{1.25em}{$\\text{otherwise}$}}\n        %\n        %\n    \\end{cases}\n\\end{proof}\n\n%\n\\vfill\n\\clearpage\n%\n\nThe solution to Equation~(\\ref{eq:tn}) depends on the matrix\n$\\viH$, whose components are given by the integral\n%\n\\begin{align}\n    \\label{eq:H}\n    \\iH_{u,v}(\\vxi) & =\n    \\vint{\\vxi}{\n        \\cos^u\\varphi\n        \\sin^v\\varphi\n    }\n    \\quad.\n\\end{align}\n%\nThe $\\viH$ integral is the same as that in Equation (D27)\nof \\citet{Luger2019}, except for a change in the limits of integration.\nWe can compute this integral recursively given four lower boundary conditions:\n%\n\\begin{proof}{H}\n    \\label{eq:Hlower}\n    \\iH_{0,0}(\\vxi) &= \\Delta \\vxi\n    %\n    \\nonumber \\\\\n    %\n    \\iH_{1,0}(\\vxi) &= \\Delta \\sin\\vxi\n    %\n    \\nonumber \\\\\n    %\n    \\iH_{0,1}(\\vxi) &= -\\Delta \\cos\\vxi\n    %\n    \\nonumber \\\\\n    %\n    \\iH_{1,1}(\\vxi) &= -\\frac{\\Delta\\cos^2\\vxi}{2}\n    %\n    \\quad.\n\\end{proof}\n%\nThe remaining terms may be computed by upward recursion using the\nrelations\n%\n\\begin{proof}{H}\n    \\label{eq:Hrec1}\n    \\iH_{u,v}(\\vxi) &=\n    \\frac{\n        -\\Delta \\left(\n        \\cos^{u + 1} \\vxi\n        \\sin^{v - 1} \\vxi\n        \\right)\n        +(v - 1)\\iH_{u,v - 2}(\\vxi)\n    }{u + v}\n\\end{proof}\n%\nfor $u < 2, v \\ge 2$ and\n%\n\\begin{proof}{H}\n    \\label{eq:Hrec2}\n    \\iH_{u,v}(\\vxi) &=\n    \\frac{\n        \\Delta \\left(\n        \\cos^{u - 1} \\vxi\n        \\sin^{v + 1} \\vxi\n        \\right)\n        + (u - 1)\\iH_{u - 2,v}(\\vxi)\n    }{u + v}\n\\end{proof}\n%\nfor all remaining terms.\n\n%\n\n\\subsection{The integral along the occulted body limb, $\\qT$}\n\\label{sec:qT}\n%\nThe final line integral we must solve is the integral along the boundary\nof the occulted body,  Equation~(\\ref{eq:qT}). Fortunately, this is\nalso the easiest of the three.\n%\nThe limits of integration $\\vlambda$\ncorrespond to the point at which the terminator crosses from the dayside\nto the night side,\n%\n\\begin{proof}{qT}\n    \\lambda_0 &=\n    \\begin{cases}\n        \\theta'        & \\qquad \\qquad \\cos^2\\theta' + (\\sin\\theta' - b_\\mathrm{o})^2 < r_\\mathrm{o}^2\n        \\\\\n        \\theta ' + \\pi & \\qquad \\qquad \\text{otherwise}\n        \\quad.\n    \\end{cases}\n\\end{proof}\n%\nand the point of intersection between the limb of the occultor\nand the limb of the occulted body,\n%\n\\begin{proof}{qT}\n    \\lambda_1 & =\n    \\frac{\\pi}{2} \\pm \\left(\\arcsin\\left(\\frac{1 - r_\\mathrm{o} ^ 2 + b_\\mathrm{o} ^ 2}{2 b_\\mathrm{o}}\\right) - \\frac{\\pi}{2}\\right)\n    \\quad,\n\\end{proof}\n%\nwhere the sign is chosen such that the point\n$(\\cos\\lambda_1, \\sin\\lambda_1)$ is on the dayside of the occulted body.\n%\nAs before, these angles are\nwrapped to the range $[0, 2\\pi)$ and\nplaced in the vector\n$\\lambda$ such that the line integral is taken in the counter-clockwise\ndirection about the center of the integration region. The right panel\nof Figure~\\ref{fig:geometry} shows a case where\n$\\lambda_0 = 75^\\circ$ and $\\lambda_1 = 130.5^\\circ$. Both angles are\nmeasured counter-clockwise from the $x'$-axis.\n\nGiven $\\vlambda$, the solution to Equation~(\\ref{eq:qT}) is straightforward:\n%\n\\begin{proof}{qT}\n    \\mathbb{q}_n &=\n    \\begin{cases}\n        \\iH_{\\frac{\\mu + 4}{2}, \\frac{\\nu}{2}}(\\vlambda)\n                                  & \\qquad \\mu, \\nu, \\, \\text{even}\n        \\\\[1em]\n        \\frac{1}{3}\\Delta\\vlambda & \\qquad \\mu = \\nu = 1\n        \\\\[1em]\n        0                         & \\qquad \\text{otherwise}\n        \\quad,\n    \\end{cases}\n\\end{proof}\n%\nwhere the matrix $\\viH$ is given by Equation~(\\ref{eq:H}).\n\n\n\\section{Caveats}\n\\label{sec:cases-missing}\n%\nThe \\starry code includes a large suite of unit tests that compare\nthe flux computations to numerical models and to various benchmarks\nfor a wide variety of inputs. While we have done our best to\ndevelop tests over the full range of occultation configurations,\nthere may be edge cases in which the \\starry algorithm fails and returns\nthe wrong flux. This could happen, for instance, if the quartic root\nsolver (\\S\\ref{sec:which-case}) fails to find the points of intersection\nbetween the occultor and the day/night terminator, leading to\nan incorrect case identification (Figure~\\ref{fig:cases}) and thus the\nwrong value for the flux. In the development of the algorithm, these cases\nwould occasionally show up as a single, obvious outlier in a light curve\nmodel. All such cases we encountered\nhave been fixed by adding consistency\nchecks in the root solver and switching to alternate evaluation methods\nnear known singularities. However, it is possible that there may still be\nrare cases in which this happens, in which case we ask that users\nraise an \\href{https://github.com/rodluger/starry/issues}{issue} on\nGitHub so that we can provide a fix.\n\n\n% TABLE\n\\vfill\n\\pagebreak\n\\input{table}\n\n\n\\end{document}\n", "meta": {"hexsha": "86864864fd6249f3f3247a6d3ed732ae3275864c", "size": 164958, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/ms.tex", "max_stars_repo_name": "rodluger/starrynight", "max_stars_repo_head_hexsha": "d3f015e466621189cb271d4d18b538430b14a557", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-05-20T09:30:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-27T14:17:33.000Z", "max_issues_repo_path": "tex/ms.tex", "max_issues_repo_name": "rodluger/starrynight", "max_issues_repo_head_hexsha": "d3f015e466621189cb271d4d18b538430b14a557", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-05-16T18:49:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-11T21:46:32.000Z", "max_forks_repo_path": "tex/ms.tex", "max_forks_repo_name": "rodluger/starrynight", "max_forks_repo_head_hexsha": "d3f015e466621189cb271d4d18b538430b14a557", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-05-19T17:11:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-19T17:11:57.000Z", "avg_line_length": 38.2466960352, "max_line_length": 148, "alphanum_fraction": 0.6718740528, "num_tokens": 47081, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3256774255651669}}
{"text": "\\documentclass{report}\n\\input{../preamble}\n\n\\begin{document}\n\n\\thispagestyle{FirstPage}\n\\begin{center}\n\\textbf{\\large Extra problems to save for review/backup}\n\\end{center}\n\\vspace{1cm}\n\n\n{\\huge More relevant}\n\n\\section*{Problem}\n\nA reactor is operating for a long time at some known power density $P_0$. Then, it instantaneously changes power to some power density $P_1$. One fission product of interest is $^{135}$Xe, though it has a neglible yield from the initial fission reaction. $^{135}$Xe precursors $^{135}$Te and $^{135}$I are produced with a combined yield of approximately 6\\%, before decaying via $\\beta^{-}$ decay to $^{135}$I and $^{135}$Xe respectively. Find the number density of $^{135}$Xe as a function of time after the power change. (Your solution may be left as variables)\n\n\\begin{table}[htbp]\n\t\\centering\n\t\\begin{tabular}{|c|c|c|}\n\t\t\t\\hline\n\t\t\tNucleus\t\t&\tHalf-life \t& Thermal $\\sigma_{\\text{a}}$ \\\\\n\t\t\t\\hline\n\t\t\t$^{135}$Te\t&  $19.0$ s \t& $\\sim 0$\\\\\n\t\t\t$^{135}$I\t&  $6.6$ hr \t& $\\sim 0$\\\\\n\t\t\t$^{135}$Xe\t&  $9.2$ hr \t& $2.6 \\times 10^6$ barns \\\\\n\t\t\t\\hline\n\t\\end{tabular}\n\t\\label{tab:design-specs}\n\\end{table}\n\n\n\\textbf{Walkthrough of neutron slowing down}\\\\\n(1) Generate a neutron from fission-neutron energy spectrum\\\\\n(2) Find cross section at that point\\\\\n(3) Determine if more likely to scatter/absorb; choose higher prob ((hopefully scatter))\\\\\n(4) Decrease by average energy loss\\\\\n(5) Repeat steps 2/3 until absorbed\\\\\nIdentify interaction points on fission cross section plot... show \"skipped resonances\"\n\n\\vspace{4cm}\n{\\huge Less relevant}\n\n\\section*{Problem}\n\nRecall from mechanics that centripetal force is $F_{\\text{cent}} = -\\frac{mv^2}{r}$ and recall from E\\&M that the Coulombic force is $F_{\\text{coul}} = -\\frac{Ze^2}{r^2}$. Solve for the Bohr radius of the orbit of an electron on hydrogen, assuming the angular momentum $L = mvr$ is quantized multiples of $\\hbar$ ($1\\hbar, \\; 2\\hbar,\\; 3\\hbar$, etc). Compare this to the measured value of $5.2917721067(12)\\times10^{11} \\text{\\AA}$ , the most probable distance between an electron in the ground state and the nucleus of a hydrogen atom.\n\n\n\n\n\n\n\\end{document}\n\n", "meta": {"hexsha": "0179aac2f2040e604340fd942cf8bd78126d7ec7", "size": 2150, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "exercises/drafts/extra_problems/extra_problems.tex", "max_stars_repo_name": "mitchnegus/NE150-discussion", "max_stars_repo_head_hexsha": "1d2afe0fc4830c3d13d491b9d6ccb7819083c5ad", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exercises/drafts/extra_problems/extra_problems.tex", "max_issues_repo_name": "mitchnegus/NE150-discussion", "max_issues_repo_head_hexsha": "1d2afe0fc4830c3d13d491b9d6ccb7819083c5ad", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercises/drafts/extra_problems/extra_problems.tex", "max_forks_repo_name": "mitchnegus/NE150-discussion", "max_forks_repo_head_hexsha": "1d2afe0fc4830c3d13d491b9d6ccb7819083c5ad", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3928571429, "max_line_length": 563, "alphanum_fraction": 0.7004651163, "num_tokens": 687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.325509124817436}}
{"text": "\\documentclass[11pt]{article}\n\n\\usepackage{alltt,fullpage,graphics,color,epsfig,amsmath, amssymb}\n\\usepackage{hyperref}\n\\usepackage{boxedminipage}\n\\usepackage[ruled,vlined]{algorithm2e}\n\\usepackage{amsmath}\n\\usepackage{commath}\n\\usepackage{graphicx}\n\\graphicspath{ {.} }\n\\newcommand{\\floor}[1]{\\lfloor #1 \\rfloor}\n\\newcommand{\\ceil}[1]{\\lceil #1 \\rceil}\n\n\\title{CS 512 Assignment 2}\n\\author{Daniel Campos}\n\\date{April 25th,2021}\n\\begin{document}\n\\maketitle\n\\section{Problem 1}\n\\subsection{Short Answers}\n\\subsubsection{What is overfitting? What are two techniques that can mitigate this issue and explain why they handle overfitting.}\nOver fitting is when a machine learn method trains to emulate the training data too closely. In other words the model has overfit its learned solution to the training data to such a degree where the performance seen on the training data is far beyond what is seen on a sample that has not been trained on. \\\\\nOne way to get around this is to always keep a portion of the dataset for validation and evaluation which you do not train on. The validation corpus can be used to tweak model performance and the evaluation portion is used as a final blind verification of model performance. This handles overfitting because it keeps a machine learning engineer honest. The validation provides a observable insight into how the model is performing on data that has not been trained on and the evaluation portion provides a complete blind evaluation which is an indication of how well this model might perform on a broader unseen data.\\\\\nAnother mechanism that can be used to mitigate overfitting is dropout. Dropout is a mechanism which each neuron in the network has some probability that it will be turned off in during the forward pass of training. This makes the network become an ensemble of sort with multiple networks working withing the larger neural network. This prevents overfitting because having ensembles of neural networks provide a broader estimation function for the training data and thus less likely to overfit. \n\\subsubsection{Compare LSTM and GRU, what do they have in common and what are their differences}\nLSTM's and GRU's are two different Recurrent Neural Network (RNN) architectures. RNNs are designed to process inputs in series (like time series or language data) and do so by passing a hidden state from one state to the next. GRU and LSTM have learned gates which allow them to learn what information should be encoded and what information should not be encoded in the hidden state. They are similar because they both provide methods of updating and modifying what is remembered at each iteration but they differ in their structure. GRU only feature update and reset gate while the LSTM features a update, forget and input gate. As a result LSTMs can perform better on more complicated inputs but are computationally more expensive to train/predict and they require more data to train. In general GRU's will train and infer quicker and out perform LSTM with small datasets but as the dataset grows LSTMs will outperform GRUs.\n\\subsection{Back Propagation}\n\\subsubsection{Prove the error equation for unit $U_6$ and the weight update function for the same neuron}\nTo calculate the degree which unit six effected the loss is equivalent to asking what effect did the output of unit 6 have on the loss. This in turn can be viewed as what effect did the out of unit 6 multiplied by its connections to units 8 and 9 and their in turn connection to unit 10, the output unit. Via the chain rule we have $\\frac{\\partial L}{\\partial_6} = \\sum_k (\\frac{\\partial L}{\\partial_k} * \\frac{\\partial_k}{\\partial a_6} * \\frac{\\partial a_6}{\\partial O_6} \\frac{\\partial O_6}{\\partial w_{i,j}})$ where $a_6$ is the output of unit six and $z_6$ is the input of unit six. Now, we address each term separately: \\\\\n$\\frac{\\partial L}{\\partial_k} = - \\partial_k$ via the definition of $\\partial$ \\\\\n$\\frac{\\partial_k}{\\partial a_6} = \\frac{\\partial}{\\partial a_6} (\\sum_s a_s w_{s,k}) = w_{j,k}$ as the only term in the sum that involves $a_6$ is $a_6 w_{j,k}$\\\\\n$\\frac{\\partial a_6}{\\partial z_6} = \\frac{\\partial}{\\partial O_6} g(O_6)= g'(0_6) = g(O_6)(1-g(0_6)) = 0_6(1-O_6)$ where g is the sigmoid function.\\\\\n$\\frac{\\partial O_6}{\\partial w_{6,j}} = a_j$ since the only term that involves $w_{6,j}$ is $a_i w_{i,j}$ \\\\ \\\\\nThus combining it all $\\frac{\\partial L}{\\partial_6} = \\sum_k (-\\partial_k w_{6,k} a(1-a_j) O_6)$\nwhich we simplify to $\\partial_6 = O-6(1-O_6)(\\sum_k (\\partial_k w_{6,k}))$ and since unit six is only connected to unit 8 and 9 we further simplify to $\\partial_6 = O-6(1-O_6)(\\partial_8 w_{6,8}) + \\partial_9 w_{6,9})$. \\\\ \nThe update is derived from $\\frac{\\partial L}{\\partial w_{i,j}} = -\\partial_j O_i$ which because of the gradient descent technique we add  the learning rate and get $\\delta w_{i,j} = n \\partial_j O_i$\n\\subsubsection{Derive the equation which computes the error for output unit $U_10$ for cross entropy function}\nDerive the equation which computes the error for the output unit $U_10$ \nFirst, We know that with the cross entropy error function where D is the sample being evaluated $L= -\\sum_k [t_k *log(o_k) + (1-t_k)log(1-o_k)]$. This becomes \\\\\n$\\frac{\\partial L}{\\partial O} = \\frac{\\partial}{\\partial O} \\sum_k [t_k log(O_k) + (1-t_k)log(1-o_k)$ . \\\\\n$\\frac{\\partial L}{\\partial O} = \\frac{\\partial}{\\partial O} t log(O) - \\frac{\\partial}{\\partial O} (1-t)log(1-O)$ . \\\\\n$\\frac{\\partial L}{\\partial O} = \\frac{t}{O} + \\frac{1-t}{1-O}$. \\\\\nThis means in turn that the $\\partial_{10} = (\\frac{t}{O} + \\frac{1-t}{1-O})$\n\\subsection{2D Convolution}\n\\subsubsection{Compute the feature maps by applying kernel $K_1$, $K_2$ (stride = 1)}\nFirst its important to note that because there is no specification about what form of padding to use I am not using any padding. This means that our 5x5 input becomes a 4x4 output. The feature map after applying $K_1$ can be found in table \\ref{tab:conv1-k1} and the feature map after applying $K_2$ can be found in table \\ref{tab:conv1-k2}. \n\\begin{table}[]\n\\begin{tabular}{|l|l|l|l|} \\hline\n2 & 0 & 0 & 2 \\\\ \\hline\n0 & 0 & 2 & 0 \\\\ \\hline\n1 & 1 & 0 & 2 \\\\ \\hline\n1 & 0 & 2 & 0 \\\\ \\hline\n\\end{tabular}\n\\caption{Resulting feature map after application of K1 on Input}\n\\label{tab:conv1-k1}\n\\end{table}\n\\begin{table}[]\n\\begin{tabular}{|l|l|l|l|} \\hline\n1 & 1 & 1 & 1 \\\\ \\hline\n1 & 1 & 1 & 2 \\\\ \\hline\n0 & 1 & 2 & 1 \\\\ \\hline\n1 & 1 & 1 & 2 \\\\ \\hline\n\\end{tabular}\n\\caption{Resulting feature map after application of K2 on Input}\n\\label{tab:conv1-k2}\n\\end{table}\n\\subsubsection{Compute the new feature map after we apply average pooling with 2x2 filter from previous work}\nAverage pooling for the feature map extracted by using kernel $K_1$ can be found in table \\ref{tab:conv-k1-average}, and table \\ref{tab:conv1-k2-average} for the average pooling on the feature map extracted by $K_2$.\n\\begin{table}[]\n\\begin{tabular}{|l|l|} \\hline\n0.5 & 1 \\\\ \\hline\n0.75 & 1 \\\\ \\hline\n\\end{tabular}\n\\caption{Average pooling for feature map using K1 on input}\n\\label{tab:conv-k1-average}\n\\end{table}\n\\begin{table}[]\n\\begin{tabular}{|l|l|} \\hline\n1 & 1.25 \\\\ \\hline\n0.75 & 1.5 \\\\ \\hline\n\\end{tabular}\n\\caption{Average pooling for feature map using K2 on input}\n\\label{tab:conv1-k2-average}\n\\end{table}\n\\subsection{Graph Convolutional Networks}\n\\subsubsection{Is this task inductive learning or transductive learning}\nThis is inductive learning because we only see a portion of the dataset while training (the train portion: 60\\%) and then we apply the learned model on dataset it has never seen before (validation/eval data portions)\nThe main difference is that during transductive learning, you have already encountered both the training and testing datasets when training the model. However, inductive learning encounters only the training data when training the model and applies the learned model on a dataset which it has never seen before.\n\\subsubsection{Implement this model and evaluate and report accuracy}\nFinal Loss on eval: 0.8361107707023621 and final accuracy:0.7458563535911602\n\\subsection{Vary the optimizer and learning rate strategies and report numbers}\nFirst, using ADAM I vary the learning rate and training length as seen in table \\ref{tab:1d}. Next, I vary the best LR (1e-1 ) and experiment with ADAM across SGD, and RMSProp finding ADAM to be the best as shown in table \\ref{tab:1de}\n\\begin{table}[]\n\\begin{tabular}{|l|l|l|l|} \\hline\nLearning Rate & Updates & Loss & Accuracy \\\\ \\hline\n1e-1 & 100  & 0.7455894351005554 & 0.7495395948434622 \\\\ \\hline\n1e-1 & 1000  & 0.6971593499183655 & 0.7569060773480664 \\\\ \\hline\n1e-1 & 10000  & \\textbf{0.6468987464904785} & \\textbf{0.7992633517495397}  \\\\ \\hline\n1e-2 & 100 & 1.1029239892959595 & 0.6611418047882136 \\\\ \\hline\n1e-2 & 1000  & 0.6627088189125061 & 0.7808471454880295 \\\\ \\hline\n1e-2 & 10000  & 0.6523106694221497 & 0.7974217311233887 \\\\ \\hline\n1e-3 & 100  & 1.832948923110962 & 0.3020257826887661 \\\\ \\hline\n1e-3 & 1000  & 1.0243993997573853 & 0.6758747697974218 \\\\ \\hline\n1e-3 & 10000  & 0.6788013577461243 & 0.7808471454880295 \\\\ \\hline\n1e-4 & 100  & 1.9703178405761719 & 0.0865561694290976 \\\\ \\hline\n1e-4 & 1000  & 1.8301498889923096 & 0.3020257826887661 \\\\ \\hline\n1e-4 & 10000  & 1.0697520971298218 & 0.6666666666666667 \\\\ \\hline\n1e-5 & 100  & 1.9364348649978638 & 0.18968692449355434 \\\\ \\hline\n1e-5 & 1000  & 1.9022825956344604 & 0.3001841620626151 \\\\ \\hline\n1e-5 & 10000  & 1.8908064365386963 & 0.27808471454880296 \\\\ \\hline\n\\end{tabular}\n\\caption{Effect of varying learning rate and training duration for GCN}\n\\label{tab:1d}\n\\end{table}\n\n\\begin{table}[]\n\\begin{tabular}{|l|l|l|l|} \\hline\nOptimizer & Updates & Loss & Accuracy \\\\ \\hline\nADAM & 100   & 0.7455894351005554 & 0.7495395948434622 \\\\ \\hline\nADAM & 1000   & 0.6971593499183655 & 0.7569060773480664 \\\\ \\hline\nADAM & 10000 & \\textbf{0.6468987464904785} & \\textbf{0.7992633517495397} \\\\ \\hline\nSGD & 100  & 1.822108507156372 & 0.3020257826887661 \\\\ \\hline\nSGD & 1000   & 1.05472731590271 & 0.6261510128913444 \\\\ \\hline\nSGD & 10000   & 0.8426060676574707 & 0.7679558011049724 \\\\ \\hline\nRMSProp & 100  & 1.5735245943069458 & 0.40699815837937386 \\\\ \\hline\nRMSProp & 1000  & 1.5078521966934204 & 0.3830570902394107 \\\\ \\hline\nRMSProp & 10000  & 1.0892350673675537 & 0.5948434622467772 \\\\ \\hline\n\\end{tabular}\n\\caption{Effect of varying optimizer and training duration for GCN}\n\\label{tab:1de}\n\\end{table}\n\\subsubsection{If the number of GCN layers increase how does the model performance change in terms of quality and efficiency}\nIf we increase the layers of the model we can model more complex data but do so with a computational overhead. In other words, a deeper network (more layers) is more computationally expensive to run and has a greater ability to fit the data. A deeper network can produce better accuracy but can also more easily overfit to the training data. When we add a third layer to our model our performance goes from 0.7569 to 0.784530 but the time to train goes from 1m13.765s to 1m38.955s and while the accuracy is higher for the deeper model its loss on eval is higher (0.7600502967834473 vs. 0.6616357564926147) indicating the model is overfitting.\n\\section{Outlier Detection}\n\\subsection{Short Answers}\n\\subsubsection{From the perspectives of outlier detection methods give two possible definitions of outliers}\nOne definition of an outlier would be a data point that differs so much from the expected data distribution as to make it clearly not part of the regular distribution. Another definition would be a data point which has a significant effect on the conditional probabilities learned while studying data as models will over compensate in order to fit this out of distribution sample. \n\\subsection{What is the disadvantage of describing outliers as any point that is larger than the majority of values? How do we modify our definition of outliers to avoid this problem? Use examples }\nThis method will miss any value that is an outlier on small scale (both close to 0 and negative) and also will fail to take into account natural distribution of large values. One way to avoid this problem is to build a notion of outliers based on the distribution of the data like Grubbs test. Instead of calling extremely large values outliers we refer to values which our outside of a Gaussian distribution as outliers. \n\\subsection{Implementation using $PyOD^3$}\nThe three methods I ran were KNN, PCA, and VAE results for runs on vowels.mat can be found in table \\ref{tab:vowels} and results for runs on satimage-2 can be found in table \\ref{tab:satimage}. At a broad level we see that more simple data like that of vowels, KNN performs best(and trained fastest) but as data gets harder Neural (VAE) and more complex methods (PCA) out perform. That being said neither PCA or VAE achieves the highest of scores on the satellite data as the feature space is small. \n\\begin{table}[]\n\\begin{tabular}{|l|l|l|l|} \\hline\nMetric        & KNN & PCA     & VAE  \\\\ \\hline\nPrecision @10 & 0.00/0.00       & 0.00/0.0    &  0.00/0.0   \\\\ \\hline\nPrecision @20 & 0.00/0.00       & 0.00/0.0    &  0.00/0.0     \\\\ \\hline\nPrecision @50 & \\textbf{0.4/0.3571}      & 0.1429/0.105 & 0.1538/0.1136 \\\\ \\hline\nPrecision @100 & \\textbf{0.4/0.3571}      & 0.1429/0.1053 & 0.1538/0.1136 \\\\ \\hline\nROC AUC Score & \\textbf{0.8868/0.8955}   & 0.6336/0.6267 & 0.6372/0.6625 \\\\ \\hline\nRecall Score  & \\textbf{0.8235/0.8333}   & 0.3529/0.3333 & 0.3529/0.4167 \\\\ \\hline\n\\end{tabular}\n\\caption{Model performance on vowel dataset vowels.mat}\n\\label{tab:vowels}\n\\end{table}\n\\begin{table}[]\n\\begin{tabular}{|l|l|l|l|}\\hline\nMetric        & KNN & PCA     & VAE  \\\\ \\hline\nPrecision @10 & 0.00/0.00       & 0.00/0.0     &  0.00/0.0   \\\\ \\hline\nPrecision @20 & 0.00/0.00       & 0.00/0.0     &  0.00/0.0   \\\\ \\hline\nPrecision @50 & 0.00/0.00       & 0.00/0.0     &  0.00/0.0   \\\\ \\hline\nPrecision @100 & 0.00/0.00      & 0.00/0.0     &  0.00/0.0   \\\\ \\hline\nPrecision @1000 & 0.0914/0.0983 & \\textbf{0.1024/0.1264} & 0.0994/0.1223  \\\\ \\hline\nROC AUC Score & 0.8666/0.8691   & 0.9331/0.9304& \\textbf{0.9546/0.9252} \\\\ \\hline\nRecall Score  & 0.8182/0.8421   & 0.9545/0.9474& \\textbf{1.0/0.9474} \\\\ \\hline\n\\end{tabular}\n\\caption{Model performance on Satellite images dataset satimage-2.mat}\n\\label{tab:satimage}\n\\end{table}\n\\section{Gaussian Mixture Model}\n\\subsection{Compared with K-Means, what are the advantages and disadvantages of Gaussian mixture model}\nThe advantages of GMM over KNN are related to how a Gaussian models a cluster. First off, since a GMM is a probability distribution we can get confidence scores for each of these clusters which can help us decide if a data point may belong to more than one cluster. Additionally GMM can outperform KNN as they can man model more oblong clusters of data while KNN is limited to modeling circular clusters while Gaussian can become oblong shapes. This works well for data that does not have a circular distribution.  \\\\\n\nThe disadvantages of GMM are mostly related to the model size. There are a lot of parameters to fit which means that there are many iterations and large data is required for training. If there are few samples in the train dataset KNN may still have good performance while GMM will likely not.\n\\subsection{E-Step:Prove that the posterior probability of the k-th component $\\gamma_{i,j}$}\nFirst from bayes theorem $p(z_i = K| x) = \\frac{p(z_i = k)p(x|z_i = k)}{\\sum_{j=1}^k p(z_j = k)p(x| z_j = k)}$. \\\\\nwhich since the prior probability $p(Z_i=k) = \\pi_k$ we can rewrite $\\gamma_{i,k} = p(z_i = K| x_i) = \\frac{\\pi_k  N(x_i | \\mu_k , \\sigma_k)}{\\sum_k N(x_i| \\mu_k, \\sigma_k)}$ \n\\subsection{M-Step:Prove that the new estimations of $\\mu_k$, $\\sigma_k$, $\\pi_k$}\nThe approach we use to prove all three estimates is the same: take the derivative with respect to the variable set to 0. \nFirst for $u_k$: $\\frac{\\partial}{\\partial \\mu_k}= \\sum_{i=1}^n \\frac{\\pi_k N(x_i| \\mu_k, \\sigma_k)}{\\sum_{k=1}^K \\pi_k N(x_i| \\mu_k, \\sigma_k)} \\frac{x_i - \\mu_k}{\\sigma_k^2} = 0$ which given the E step can be rewritten as $\\sum_{i=1}^n \\gamma_{i,k}\\frac{x_i - \\mu_k}{\\sigma_k^2} = 0 $ which can be simplified to $\\frac{\\sum_{i=1}^n \\gamma_{i,k}x_i}{\\sigma_k^2}  - \\frac{\\sum_{i=1}^n \\gamma_{i,k}\\mu_k}{\\sigma_k^2} = 0 $ which then becomes $\\frac{\\sum_{i=1}^n \\gamma_{i,k}x_i}{\\sigma_k^2}  = \\frac{\\sum_{i=1}^n \\gamma_{i,k}\\mu_k}{\\sigma_k^2}$, then $\\frac{\\sum_{i=1}^n \\gamma_{i,k}x_i}{1}  = \\frac{\\sum_{i=1}^n \\gamma_{i,k}\\mu_k}{1}$, $\\frac{\\sum_{i=1}^n \\gamma_{i,k}x_i}{\\sum_{i=1}^n \\gamma_{i,k}}  = \\mu_k$ which is our target. \\\\\\\\\nFollowing the same logic for $\\sigma_k^2$ we first take the derivative and set to 0 we get $\\frac{\\partial }{\\partial \\sigma_k} =  (\\sum_{n=1}^n \\gamma_{n,k}(x_n-u_k)(x_n-u_k)) - (\\sum_i \\gamma_{i,k} \\sigma_k^2)$ which leads to $(\\sum_{n=1}^n \\gamma_{n,k}(x_n-u_k)(x_n-u_k)) = (\\sum_i \\gamma_{i,k} \\sigma_k^2)$, then $\\frac{\\sum_{n=1}^n \\gamma_{n,k}(x_n-u_k)^2}{\\sum_i \\gamma_{i,k}} =  \\sigma_k^2$. \\\\\nFinally, to find the value of $\\pi_k$ we must take into account mixing coefficients must sum to one. We find the maximum by using the Lagrangian multiplier and taking its derivative and setting to one. this gives $\\ln p(x_i| \\pi_k, \\mu_k, \\sigmoid_k) + \\lambda (\\sum_k \\pi_k -1)$ which the derivative with respect to $\\pi_k$ is $\\frac{1}{N}*\\sum_i \\gamma_{i,k}$ which is our desired output\n\\section{Graph Connectivity and SIS model}\n\\subsection{Implement the Susceptible-Infected-Susceptible and graph number of people in each group}\nFor the initial implementation there are an average of 6876.03 infected nodes\nafter the convergence(200-300 iterations). The plot for susceptible and infected individuals can be found  in figure \\ref{fig:sis}.\n\\begin{figure}\n    \\centering\n    \\includegraphics{Assignments/Assignment2/sis.png}\n    \\caption{Effect of Random Vaccination in virus propagation}\n    \\label{fig:sis}\n\\end{figure}\n\\subsection{Vaccination}\nFor random vaccination of 200 nodes the average infected nodes after convergence is 6645.46 and the plot for susceptible and infected individuals can be found  in figure \\ref{fig:vacrand}.\nFor those with highest degree there is an average we achieve a slightly lower rate of 6215.99 and the plot for infection growth over time can be found in figure \\ref{fig:highdegree}.\n\\begin{figure}\n    \\centering\n    \\includegraphics{Assignments/Assignment2/random-vac.png}\n    \\caption{Effect of Random Vaccination in virus propagation}\n    \\label{fig:vacrand}\n\\end{figure}\n\\begin{figure}\n    \\centering\n    \\includegraphics{Assignments/Assignment2/high-degree.png}\n    \\caption{Effect of High Degree Vaccination in virus propagation}\n    \\label{fig:highdegree}\n\\end{figure}\n\\subsection{More Vaccination}\nI explore three strategies for vaccination: proximity to infected nodes at time step 0, highest connection via 2 hops, random walk. \\\\\nFor proximity to infected nodes I generate a ranking by how heavily nodes are connected to infected node. The 200 susceptible nodes with highest connection to infected nodes become vaccinated. This averages to 6342.96 infected individuals after convergence and results over time can be seen in figure \\ref{fig:infection}. This method is more effective than any random method but not as effective at vaccinating the highest degree nodes. \\\\\nFor highest connection via two hop we build on the notion of highest degree nodes but take the highest number of nodes available within 2 hops (Node-Edge-Node). This averages to 6335.06 infected individuals after convergence and results over time can be seen in figure \\ref{fig:2hop}. \\\\\nFor Random walk we start at an random node and vaccinate it and then walk to one of its edges and make that our new vaccination node. We continue this process until we have used all of our vaccination. This averages to 6620.56 infected individuals after convergence and results over time can be seen in figure \\ref{fig:randwalk}. We can see this method is more effective than random but not by much.\n\\begin{figure}\n    \\centering\n    \\includegraphics{Assignments/Assignment2/two_hop.png}\n    \\caption{Effect of Two Hop Vaccination in virus propagation}\n    \\label{fig:2hop}\n\\end{figure}\n\\begin{figure}\n    \\centering\n    \\includegraphics{Assignments/Assignment2/infection-proximity.png}\n    \\caption{Effect of Infection proximity Vaccination in virus propagation}\n    \\label{fig:infection}\n\\end{figure}\n\\begin{figure}\n    \\centering\n    \\includegraphics{Assignments/Assignment2/random-walk.png}\n    \\caption{Effect of Random Walk Vaccination in virus propagation}\n    \\label{fig:randwalk}\n\\end{figure}\n\\end{document}", "meta": {"hexsha": "d97c62ede0a8f849c6b98eec858fd55c7eb4666c", "size": 20633, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Assignments/Assignment2/main.tex", "max_stars_repo_name": "spacemanidol/CS512DM", "max_stars_repo_head_hexsha": "fa664ceb7526e27b9cccd372b65b15c587095c49", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assignments/Assignment2/main.tex", "max_issues_repo_name": "spacemanidol/CS512DM", "max_issues_repo_head_hexsha": "fa664ceb7526e27b9cccd372b65b15c587095c49", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assignments/Assignment2/main.tex", "max_forks_repo_name": "spacemanidol/CS512DM", "max_forks_repo_head_hexsha": "fa664ceb7526e27b9cccd372b65b15c587095c49", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 89.7086956522, "max_line_length": 926, "alphanum_fraction": 0.7407551011, "num_tokens": 6357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.32550912481743594}}
{"text": "\n\n\\documentclass[11pt]{article}\n\\date{}\n \n\\usepackage[margin=0.8in]{geometry} \n\\usepackage{amsmath,amsthm,amssymb,bm,graphicx,pdfpages,enumerate,enumitem,breqn,blkarray}\n\\newcommand*\\tageq{\\refstepcounter{equation}\\tag{\\theequation}}\n\\usepackage{graphicx, bbm, color, parskip}\n\\usepackage{multirow}\n\\newcommand{\\indep}{\\rotatebox[origin=c]{90}{$\\models$}}\n\\setcounter{MaxMatrixCols}{20}\n\n\\usepackage{physics}\n\\usepackage[makeroom]{cancel}\n\\usepackage{listings}\n\n\\newcommand{\\N}{\\mathbb{N}}\n\\newcommand{\\Z}{\\mathbb{Z}}\n\\newcommand{\\R}{\\mathbb{R}}\n\\allowdisplaybreaks\n\\makeatletter\n\\newcommand{\\colvect}{\\rcvector}\n\\newcommand{\\rowvect}{\\rcvector}\n\\newcommand{\\E}{\\textrm{E}}\n\\newcommand{\\Var}{\\textrm{Var}}\n\\newcommand{\\Cov}{\\textrm{Cov}}\n\\newcommand{\\Corr}{\\textrm{Corr}}\n\\newcommand{\\pf}{\\begin{flushright}$\\square$\\end{flushright}}\n\\newcommand{\\asreq}{\\begin{flushright}...as required\\end{flushright}}\n \n\\begin{document}\n\n\\title{\\vspace{-0.7cm}The \\texttt{stmpy} package}\n\\date{\\today}\n\\author{Hoffman lab} \n\\maketitle\n\n\n%----------------------------------------------------------\n\n\n\\section*{Methods in \\texttt{stmpy.tools}:}\n\nDescriptions are shown in the order functions appear in {\\tt stmpy.tools}, which is vaguely chronologically.\n\n\\begin{enumerate}\n\\item {\\tt saturate} - Designed to make it easy to set color limits on images. Adjusts color axis of current image handle by calculating a probability density function for the data in the current axis.  Uses upper and lower thresholds on the PDF to find sensible c-axis limits. \n\n\\item {\\tt azimuthalAverage} - Given a point $\\mathbf{p}=(x_0,y_0)$ in a 2D data set $F(x,y)$, computes the azimuthal average of the $F$ as a function of $r$ away from $\\mathbf{p}$. Uses 2D interpolation on $F$ to get evenly spaced $r$ values. \n\n\\item {\\tt azimuthalAverageRaw} - Computes a raw azimuthal average on 2D data $F(x,y)$.  This is similar to {\\tt \\small azimuthalAverage} but does not interpolate the data.  Instead the returned $r$ values are not linearly spaced, but follow the sequence: $1,\\sqrt{2}, 2, \\sqrt{5}...$\n\n\\item {\\tt binData} - Puts non-linearly sampled data into linear bins.\n\n\\item {\\tt linecut} - Simple algorithm for taking a line-cut on a 2D data set $F(x,y)$.  Uses interpolation to sample $F$ along a line from $(x_1,y_1)$ to $(x_2,y_2)$ with $n$ evenly spaced points.\n\n\\item {\\tt squareCrop} - Crops a 2D image to be $m\\times m$.\n\n\\item {\\tt lineCrop} - Takes 1D data $y(x)$ and removes arbitrarily many sections to return $y(x(t_0:t_1, t_2:t_3, ...))$.\n\n\\item {\\tt removePolynomial1d} - Removes an $n$ degree polynomial fit to 1D data $y(x)$. Optional: can specify the sections of $y(x)$ to use when fitting the background polynomial.\n\n\\item {\\tt lineSubtract} - Acts on 3D or 2D data $A(\\mathbf{r})$ to remove an $n$ degree polynomial from each line in $A(\\mathbf{r})$.  Specifically, it iterates over the first index of $A(\\mathbf{r})$ until to get 1D data $y(x)$  and implements {\\small \\tt removePolynomial1d} to remove the background.\n\n\\item {\\tt fitGaussian2d} - Fit a 2D gaussian of the form $$f(x,y) = A \\exp (-a(x-x_0)^2 +2b(x-x_0)(y-y_0) - c(y-y_0)^2 ) + B$$\nto 2D data $F(x,y)$ given specified initial parameters: $A, B, x_0, y_0, \\sigma_x,  \\sigma_y, \\theta.$\n\n\\item {\\tt findOtherBraggPeaks} - For a Fourier transformed lattice, the Bragg peaks come in pairs at $\\pm \\mathbf{Q}_{B}$, with harmonics at  $\\pm n\\mathbf{Q}_{B}$ with $n\\in \\mathbb{N}$.  This function takes on Bragg peak and returns the $2n-1$ other Bragg peak locations for 2D data $F(x,y)$.\n\n\\item {\\tt findPeaks} - Simple peak detection algorithm that returns the location of the $n$ highest peaks, $x^*$, in 1D data $y(x)$ by checking where the derivative crosses zeros, $y'(x^*)=0$.\n\n\\item {\\tt fitGaussian1d} - Fits $N$ gaussians to 1D data $y(x)$ of the form $$f(x) = \\sum_{n=0}^N A_n \\exp (-\\frac{(x-\\mu_n)^2}{2\\sigma_n^2}).$$\n\n\\item {\\tt foldLayerImage} - Takes 3D data $A(\\mathbf{r})$ and returns a $n$-fold symmetric 3D image $\\tilde{A}(\\mathbf{r})$, by iterating through the first index of $A(\\mathbf{r})$ and symmetrizing the $i^{th}$ 2D layer, $A(E_i,x,y)$, about a specified fold direction.  The intended use is to symmetrize an FT-DOS map along the direction of a Bragg peak. Currently implemented for $n=1,2,4$ and all but replaced by {\\tt \\small symmetrize}\n\n\\item {\\tt quickFT} - Computes a 2D Fourier transform of 2D or 3D data $A(\\mathbf{r})$, with the option to $n$-fold symmetrize the result.  If 3D data is used the 2D Fourier transforms will be computed by iterating along the first index.\n\n\\item {\\tt symmetrize} - Similar to {\\tt \\small foldLayerImage}, returns $n$-fold symmetric 2D or 3D data $\\tilde{A}(\\mathbf{r})$ by rotating clockwise and anti-clockwise by an angle $2\\pi/n$, then applying a mirror line.  Works on 2D and 3D data sets, in the case of 3D each layer is symmetrized.\n\n\\item {\\tt ngauss1d} - More general version of {\\tt fitGaussian1d}, which allows any fit parameter to be fixed. Also returns information about the quality of fit.\n\n\\item {\\tt track_peak} - Generalizes {\\tt \\small ngauss1d} to work on 2D data $F(x,y)$ by iterating the first index of $F(x,y)$. Only retains information about the position of the gaussian peaks, which track features that disperse in the $y$ direction.\n\n\\item {\\tt shearcorr} - ... to be updated to include local drift correction.\n\n\\item {\\tt planeSubtract} - Removes a 2D polynomial plane $P(x,y)$  from 2D data $F(x,y)$.  The polynomial is of the form:\n$$ P(x,y) = a_0 + \\sum_{k=1}^N a_{2k-1}\\ x^k + a_{2k}\\ y^k,$$\nwhere $a_0,a_1,a_2, ...$ are the polynomial coefficients. \n\n\\item {\\tt butter_lowpass_filter} - Implements a Butterworth filter for 1D data $y(x)$ or for each spectrum $g(E)$ in a 3D data set $g(E,x,y)$.\n\n\\item {\\tt gradfilter} -  Applies a minimum gradient filter to extract dispersive features in a 2D data set $F(x,y)$ (Ref: arXiv:1612.07880).  Returns filtered data with optional gradient components for pseudo-vector-field and gradient modulus maps.\n\n\\end{enumerate}\n\n\n\\end{document}\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ", "meta": {"hexsha": "767dfaf21a58c3f5770c02e61eb125950a9a1474", "size": 6064, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "stmpy/doc/tex/Documentation.tex", "max_stars_repo_name": "harrispirie/stmpy", "max_stars_repo_head_hexsha": "74c5142bd75af474241c131b817ba362dcac5b13", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2016-10-12T20:47:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-07T14:23:15.000Z", "max_issues_repo_path": "stmpy/doc/tex/Documentation.tex", "max_issues_repo_name": "harrispirie/stmpy", "max_issues_repo_head_hexsha": "74c5142bd75af474241c131b817ba362dcac5b13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-12-24T22:00:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-01T20:38:09.000Z", "max_forks_repo_path": "stmpy/doc/tex/Documentation.tex", "max_forks_repo_name": "harrispirie/stmpy", "max_forks_repo_head_hexsha": "74c5142bd75af474241c131b817ba362dcac5b13", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2016-07-30T01:18:30.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-16T15:44:25.000Z", "avg_line_length": 53.1929824561, "max_line_length": 439, "alphanum_fraction": 0.7064643799, "num_tokens": 1939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3255091171329785}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n%\n%\n%\t1. Motivation\n%\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Motivation}\n\\label{s:mot}\n\nThe \\textit{interwar period} in the United States (1919-1939) remains one of the most discussed topics in the field of quantitative economic history. Enormous volatility in currency exchange rates, hyperinflation in Germany and the failing gold standard constitute some characteristics of this turbulent period. This seminar paper analyzes the \\textit{interwar period} in the US using a dataset from \\cite{reichsamt}. The relative importance of supply and demand shocks are examined applying a Blanchard-Quah decomposition\\footnote{an application of a structural VAR model developped by \\cite{blanchard}}. Subsequently the paper features a review of the obtained results and tries to assess the Blanchard-Quah decomposition regarding its suitability for such analysis.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n%\n%\n%\t2. Data\n%\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Data}\n\\label{s:data}\n\nThe dataset includes monthly observations of Industrial Production (\\textit{IP}) and Consumer Price Inflation (\\textit{CPI}) figures for the years 1919-1939.\\footnote{The obtained time series stems from \\cite{reichsamt}.} Figure (\\ref{plot}) shows a plot of the series. Three distinct sub-samples are created two examine the properties for each economic cycle in the \\textit{Interwar Period} (\\cite{feinstein}). Sub-sample (1) aims to reflect the \\textit{Roaring Twenties} and includes observations from January 1920 until December 1928. Sub-sample (2) accounts for the \\textit{Great Depression} and features figures for the timespan between October 1929 and February 1933. Sub-sample (3) includes observations reflecting the \\textit{New Deal} programs in between April 1933 and June 1937.\n\n\\begin{figure}[ht]\n  \\setstretch{1.0} \n  \\footnotesize \n  \\centering\n  \t\t\\includegraphics[width=1\\textwidth]{../../out/figures/data_plot.pdf}\n  \\vspace{3mm}\n  \\caption[US Output Growth \\textit{(Industrial Production)} and Inflation \\textit{(Consumer Price Index)}]{\\textbf{US Output Growth \\textit{(Industrial Production)} and Inflation \\textit{(Consumer Price Index)}} (Log First Differences)}\n  \\label{plot}\n\\end{figure}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n%\n%\n%\t3. Methodology\n%\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\clearpage\n\\section{Methodology}\n\\label{s:methodology}\n\n\\subsection{Structural vector autoregression}\n\\label{s:structural}\n\nIn structural models (see equation (\\ref{e:var})) there often are no possibilities to observe shocks that are of structural nature. Autoregressive models (VAR) are then estimated as alternative (see equation (\\ref{eq:var2})).\n\\begin{equation}\n{\\bf Gx_t}={\\bf Dx_{t-1}}+{\\bf \\epsilon_t}\n\t\t\\label{e:var}\n\\end{equation}\nwhere $\n{\\bf x_t}\n=\n\\begin{bmatrix}\n\\Delta p_t \\\\\n\\Delta y_t \\\\\n\\end{bmatrix}\n,\n\\quad\n{\\bf x_{t-1}}\n=\n\\begin{bmatrix}\n\\Delta y_{t-1} \\\\\n\\Delta p_{t-1} \\\\\n\\end{bmatrix}\n\\quad\n\\textrm{and}\n\\quad\n{\\bf \\epsilon_t}\n=\n\\begin{bmatrix}\n\\epsilon_{y,t} \\\\\n\\epsilon_{p,t} \\\\\n\\end{bmatrix}\n$\n\n${\\bf x_t}$ is a 2$\\times$1 vector featuring output growth and inflation.\n\\begin{equation}\r\n\t{\\bf x_t} = {\\bf A(L)x_{t-1}} + {\\bf u_t}\r\n\\label{eq:var2}\r\n\\end{equation}\nwhere\n$\n{\\bf A(L)}\n=\n{\\bf G^{-1}D}\n\\quad\n\\textrm{and}\n\\quad\n{\\bf u_t}\n=\n{\\bf G^{-1}}\n{\\bf \\epsilon_t}\n$\n\nEstimates for ${\\bf A(L)}$, the residuals ${\\bf u_t}$ and the covariance matrix ${\\bf \\sum}$ are obtained by OLS. Equation (\\ref{eq:ma}) shows the $MA(\\infty)$ representation of such VAR model.\n\\begin{equation}\r\n{\\bf x_t}\n=\n{\\bf B(L)u_t}\n\\label{eq:ma}\n\\end{equation}\nRearranging equation (\\ref{eq:ma}) yields:\n\\begin{equation}\r\n{\\bf u_t}\n=\n{\\bf G^{-1}\\epsilon_t}\n=\n{\\bf S\\epsilon_t}\r\n\\label{eq:response}\r\n\\end{equation}\nEquation (\\ref{eq:res}) depicts the covariance matrix of ${\\bf u_t}$:\n\\begin{equation}\r\n{\\bf \\sum} = E \\big[ {\\bf u_t u'_t} \\big] = {\\bf S}E \\big[ {\\bf \\epsilon_t \\epsilon'_t} \\big] {\\bf S'} = {\\bf SS'}\r\n\\label{eq:res}\r\n\\end{equation}\n${\\bf \\epsilon_t}$ is assumed to be mutually uncorrelated with a normalized variance of 1. Therefore $var({\\bf \\epsilon_t})={\\bf I}$.\nResolving equation (\\ref{eq:res}) yields the identification matrix ${\\bf S}$ (impact matrix)\\footnote{The impact matrix maps structural shocks into residuals}. \n\n\\subsection{Blanchard-Quah decomposition}\n\\label{s:bq}\nImplications of the traditional AS-AD model (\\cite{favero}) assume supply shocks to have permanent and demand shocks to have temporary effects, on output whereas price effects are permanent for both, supply and demand shocks.\n\nBlanchard-Quah decomposition (\\cite{blanchard}) requires the implications of the traditional AS-AD model to be fulfilled (\\cite{favero}). These implications are then sufficient to compute the long-run structural coefficient matrix:\n\n\\begin{equation}\r\n\\begin{bmatrix}\n\\Delta p_t \\\\\n\\Delta y_t \\\\\n\\end{bmatrix}\n=\n\\begin{bmatrix}\n(+) & 0 \\\\\n(-) & (+) \\\\\n\\end{bmatrix}\n\\begin{bmatrix}\n\\epsilon^S  \\\\\n\\epsilon^S \\\\\n\\end{bmatrix}\n\\label{eq:lr}\n\\end{equation}\nwhere: $\n\\begin{bmatrix}\n(+) & 0 \\\\\n(-) & (+) \\\\\n\\end{bmatrix}\n=\n{\\bf C(1)}\n\\quad\n\\textrm{and}\n\\quad\n\\begin{bmatrix}\n\\epsilon^S  \\\\\n\\epsilon^S \\\\\n\\end{bmatrix}\n=\n{\\bf \\epsilon}$\n\n${\\bf C(1)}$ is lower triangular by restriction from the AS-AS model\\footnote{as demand shocks have no long-run effects on output}. The long-run multiplier of the reduced form is denoted by:\n\\begin{equation}\r\n{\\bf B(1)}={\\bf C(1)S^{-1}}\r\n\\label{eq:lrm}\r\n\\end{equation}\nCholeski decomposition of (\\ref{eq:chole}) leads to the long-run coefficient {\\bf C(1)} which in turn facilitates the calculation of the identification matrix ${\\bf S}={\\bf B(1)^{-1}C(1)}$ and the structural moving average representation ${\\bf x_t}={\\bf C(L)\\epsilon_t}={\\bf B(L)S\\epsilon_t}$.\n\n\\begin{equation}\n  \\begin{split}\n\t\t{\\bf B}(1)\\bs{\\Sigma}{\\bf B}(1)'=&{\\bf C}(1){\\bf S}^{-1}\\bs{\\Sigma}({\\bf S}')^{-1}{\\bf C}(1)'=\\\\=&{\\bf C}(1){\\bf S}^{-1}{\\bf S}{\\bf S}'({\\bf S}')^{-1}{\\bf C}(1)^\t\t{\\prime}=\\\\=&{\\bf C}(1){\\bf C}(1)'.\n   \\end{split}\n\\label{eq:chole}\t\t\t\n\\end{equation}\n\n\\clearpage\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n%\n%\n%\t4. Results\n%\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Results}\n\\subsection{Impulse response functions}\n\\label{s:ir}\nFigure (\\ref{irt}) shows the impulse response functions \\textit{(IR)} calculated on the basis off the entire dataset (years 1919-1939) . Figure (\\ref{irr}) features impulse response functions on the \\textit{Roaring Twenties} sub-sample (1920-1982). Figures (\\ref{irg}) and (\\ref{irn}) cover the \\textit{Great Depression} (1929-1933) and the \\textit{New Deal} era (1933-1937) respectively.\n\n\\begin{figure}[ht]\n  \\setstretch{1.0} \n  \\footnotesize \n  \\centering\n  \t\t\\includegraphics[width=1\\textwidth]{../../out/figures/impulse_response.pdf}\n  \\vspace{3mm}\n  \\caption[Impulse response functions - entire dataset]{\\textbf{Impulse response functions - entire dataset} (January 1919 - December 1939)}\n  \\label{irt}\n\\end{figure}\n\n\\begin{figure}[ht]\n  \\setstretch{1.0} \n  \\footnotesize \n  \\centering\n  \t\t\\includegraphics[width=1\\textwidth]{../../out/figures/impulse_response_RT.pdf}\n  \\vspace{3mm}\n  \\caption[Impulse response functions - Roaring Twenties]{\\textbf{Impulse response functions - Roaring Twenties} (January 1920 - December 1928)}\n  \\label{irr}\n\\end{figure}\n\n\\begin{figure}[ht]\n  \\setstretch{1.0} \n  \\footnotesize \n  \\centering\n  \t\t\\includegraphics[width=1\\textwidth]{../../out/figures/impulse_response_GD.pdf}\n  \\vspace{3mm}\n  \\caption[Impulse response functions - Great Depression]{\\textbf{Impulse response functions - Great Depression} (October 1929 - February 1933)}\n  \\label{irg}\n\\end{figure}\n\n\\begin{figure}[ht]\n  \\setstretch{1.0} \n  \\footnotesize \n  \\centering\n  \t\t\\includegraphics[width=1\\textwidth]{../../out/figures/impulse_response_ND.pdf}\n  \\vspace{3mm}\n  \\caption[Impulse response functions - New Deal]{\\textbf{Impulse response functions - New Deal} (April 1933 - June 1937)}\n  \\label{irn}\n\\end{figure}\n\nThe impulse response function indicate positive short-run output changes in response to a demand shock for the \\textit{Great Depression} and \\textit{New Deal} sub-samples. These reactions converge to zero in the long-run (which is in line with the restrictions imposed on the Blanchard-Quah decomposition (\\cite{blanchard}). Several dependencies in line with the traditional AS-AD model can be observed. Prices tend to increase after a positive demand shock, whereas output tends to rise after positive supply shocks. Figure (\\ref{irt}) shows negative short-run effects on output to positive demand shocks during the \\textit{Roaring Twenties}. This result collides with the relationship assumed by the traditional AS-AD model.\n\n\\clearpage\n\\subsection{Forecast Error Variance Decomposition}\nFigure (\\ref{ft}) shows the forecast error variance decompositions of the impulse response functions covering the entire dataset, whereas figures (\\ref{fr}), (\\ref{fg}), (\\ref{fg}) and (\\ref{fn}) show the forecast error variance decompositions for the \\textit{Roaring Twenties}, \\textit{Great Depression} and \\textit{New Deal} sub-sets respectively. The results indicate that variation in output is mainly driven by supply shocks whereas variation in prices is mainly driven by shocks in demand. As require by Blanchard-Quah specifications, long-run variation in output is entirely driven by supply shocks. In the short-run there seems to be no impact on output from demand shocks.\n\n\\begin{figure}[ht]\n  \\setstretch{1.0} \n  \\footnotesize \n  \\centering\n  \t\t\\includegraphics[width=1\\textwidth]{../../out/figures/fevd.pdf}\n  \\vspace{3mm}\n  \\caption[Forecast error variance decomposition - Full data]{\\textbf{Forecast error variance decomposition - entire dataset} (January 1919 - December 1939)}\n  \\label{ft}\n\\end{figure}\n\n\\begin{figure}[ht]\n  \\setstretch{1.0} \n  \\footnotesize \n  \\centering\n  \t\t\\includegraphics[width=1\\textwidth]{../../out/figures/fevd_RT.pdf}\n  \\vspace{3mm}\n  \\caption[Forecast error variance decomposition - Roaring Twenties]{\\textbf{Forecast error variance decomposition - Roaring Twenties} (January 1920 - December 1928)}\n  \\label{fr}\n\\end{figure}\n\n\\begin{figure}[ht]\n  \\setstretch{1.0} \n  \\footnotesize \n  \\centering\n  \t\t\\includegraphics[width=1\\textwidth]{../../out/figures/fevd_GD.pdf}\n  \\vspace{3mm}\n  \\caption[Forecast error variance decomposition - Great Depression]{\\textbf{Forecast error variance decomposition - Great Depression} (October 1929 - February 1933)}\n  \\label{fg}\n\\end{figure}\n\n\\begin{figure}[ht]\n  \\setstretch{1.0} \n  \\footnotesize \n  \\centering\n  \t\t\\includegraphics[width=1\\textwidth]{../../out/figures/fevd_ND.pdf}\n  \\vspace{3mm}\n  \\caption[Forecast error variance decomposition - New Deal]{\\textbf{Forecast error variance decomposition - New Deal} (April 1933 - June 1937)}\n  \\label{fn}\n\\end{figure}\n\n\\clearpage\n\n\\section{Conclusion}\nIn general Blanchard-Quah decompositions lead to results further in line with textbook macroeconomic models when applied to post-World War II data (see e.g. \\cite{blanchard2}). Applying Blanchard-Quah decomposition on the evaluated dataset may lead to several implications that seem counterfactual to the traditional AS-AD model (see section \\ref{s:ir}). Blanchard-Quah decompositions seem to be of limited power when modelling the effects of structural shocks that occurred in the \\textit{inter war} period (see e.g. \\cite{eggertson} who claim that monopoly protection and union support backed by \\textit{New Deal} policies were beneficial to output growth or \\cite{comm} who highlight the effects of commodity markets disintegration after 1929). \n\n\n", "meta": {"hexsha": "5780914e494b8110cea447833295a97f55ad6e74", "size": 12466, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/text/S_Term_Paper.tex", "max_stars_repo_name": "michaelkilchenmann/Quantitative_Economic_History", "max_stars_repo_head_hexsha": "c64b5ad877eb995629d4b31f8a8500e7565a953a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-05-15T19:20:55.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-04T18:38:20.000Z", "max_issues_repo_path": "src/text/S_Term_Paper.tex", "max_issues_repo_name": "michaelkilchenmann/Quantitative_Economic_History", "max_issues_repo_head_hexsha": "c64b5ad877eb995629d4b31f8a8500e7565a953a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/text/S_Term_Paper.tex", "max_forks_repo_name": "michaelkilchenmann/Quantitative_Economic_History", "max_forks_repo_head_hexsha": "c64b5ad877eb995629d4b31f8a8500e7565a953a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.4355400697, "max_line_length": 789, "alphanum_fraction": 0.6628429328, "num_tokens": 3323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.32532249473868396}}
{"text": "\\documentclass{elsart}  \n\\usepackage{epsfig,amssymb,amsmath}  \n\\begin{document}\n\n\n\\section{Drift velocity and gas gain}\n\nAs shown in the Langevin equation \\cite{blum}[p.49], the drift velocity is a function of the field (electric, magnetic) and the mobility. The mobility depends on the gas density which is a function of the environment variables as well as the gas composition which can change in time. \n\n$$v_d = v_d(E/N) = v_d(E,B,T,P,C_{CO_2},C_{N_2})$$\n\n$E$ and $B$ are the field values (electric, magnetic), $N$ is the gas density, $P$ is the atmospheric pressure, $T$ is the temperature inside of the TPC and $C_{CO_2}$ and $C_{N_2}$ are two concentration out of three components of the drift gras $Ne,CO_2,N_2$ (90/10/5) within the TPC. We suppose that these parameters, especially the environment variables, will vary in time within a reasonable range. However, according to performed \\textsl{Magboltz-2} \\cite{magboltz} simulations a first order Taylor expansion of the dependencies around the nominal values is sufficient. More details can be found in section \\ref{sec:magbolzSim}.\n\\begin{equation}\n\\Delta{v_d}=v_d-v_{d0}=\\frac{dv}{dE}\\Delta{E}+\\frac{dv}{dN}\\Delta{N(P,T)}+\\frac{dv}{dC_{CO_2}}\\Delta{C_{CO_2}}+\\frac{dv}{dC_{N_2}}\\Delta{C_{N_2}}\n\\label{equ:taylor}\n\\end{equation}\n\nWithin the TPC volume, the parameters in the expansion are changing with different time constant. A significant change of the drift velocity due to the gas composition changes has a time constant of days. On the other hand the changes due to the pressure and temperature variation have to be corrected on the level of minutes.\nIn the following we will focus on the influence of the changes of the gas density, temperature and pressure. \n\\begin{equation}\n\\frac{\\Delta{v_d}}{v_{d0}}= k_t(t)+k_{N}\\frac{\\Delta{N(P,T)}}{N_0(P,T)} \n\\end{equation}\n\\begin{equation}\n\\frac{\\Delta{v_d}}{v_{d0}}= k_t(t)+k_{P/T}\\frac{\\Delta{(P/T)}}{(P/T)_0} \n\\end{equation}\n\nThe factor of the time dependent offset $k_t(t)$ describes then the influence of the gas composition and possible changes within the field. \n\nThe correction factor $v_c=\\frac{\\Delta{v_d}}{v_{d0}}$ can be measured using different methods:\n\\begin{itemize}\n\\item Matching laser tracks with the surveyed mirror position\n\\item Matching with the ITS tracks\n\\item Matching of the TPC primary vertices from the two halves of the TPC\n\\item Using cosmic tracks - matching tracks from two halves of the TPC\n\\end{itemize}\n\nThe unknown parameters $k_t(t)$ and $k_N$ can be than fitted using the Kalman filter as is shown in section \\ref{sec:kalman}.\n\n\n\\section{Simulation of drift velocity dependencies }\n\\label{sec:magbolzSim}\n\nThe state-of-the-art program \\textsl{Magboltz-2} \\cite{magboltz} can be used to calculate different drift properties by means of MonteCarlo (MC) methods as for example the drift velocity within a certain gas mixtures, under certain environment conditions and with any choosen field. Since MC simulations itself are too time consuming, a first order tayler expansion was used in order to fit various simulated data points under different conditions. Upper and lower tresholds for the simulated points were choosen to be within a reasonable range of possible changes within the TPC as shown in table \\ref{tab:valRange}.  This approximation was implemented within the class \\textsl{AliTPCCalibVDrift}. It allows to estimate the drift velocity, as a function of field and gas properties changes, quickly and with sufficient accuracy, at least for a first order calibration.\\\\\n\n\\begin{table}[htbp]\n\\caption{Dependency range of simulated drift velocities}\n\\centering\n\\begin{tabular}{|l|r|r|r|}\n\\hline\n & \\multicolumn{1}{l|}{std.cond.} & \\multicolumn{1}{l|}{MIN} & \\multicolumn{1}{l|}{MAX}  \\\\ \\hline\nE [V/cm] & 400 & 395 & 405 \\\\ \\hline\nT [K]& 293 & 288 & 300  \\\\ \\hline\nP [TORR]& 744 & 719 & 759 \\\\ \\hline\nCo2 [\\%]& 9.52 & 9.02 & 10.02  \\\\ \\hline\nN2 [\\%]& 4.76 & 4.36 & 5.26  \\\\ \\hline\n\\end{tabular}\n\\label{tab:valRange}\n\\end{table}\n\n\nThe following dependencies were obtained through fitting the simulated $v_d$'s with a linear hyperplane which is equal to the first order taylor expansion from equation (\\ref{equ:taylor}). \n\n\\begin{eqnarray*}\n  \\frac{\\partial v_d}{\\partial E} & = & 0.24 \\; [cm/V\\mu s] \\\\\n  \\frac{\\partial v_d}{\\partial T} & = & 0.31 \\; [cm/K\\; \\mu s]\\\\\n  \\frac{\\partial v_d}{\\partial P} & = & -0.13 \\; [cm/Torr\\; \\mu s]\\\\\n  \\frac{\\partial v_d}{\\partial C_{CO_2}} & = & -6.60 \\; [cm/\\%\\; \\mu s]\\\\\n  \\frac{\\partial v_d}{\\partial C_{N_2}} & = & -1.73 \\;[cm/\\%\\; \\mu s]\n\\end{eqnarray*}\n\n\nTwo example plots are given in figure \\ref{figVDdepend} where the drift velocity change is plotted in dependency of pressure and temperature. A residual histogram of the complete taylor expansion with all dependencies is plotted in figure \\ref{figResHistoSim}. The sigma of the residual distribution is lower than the claimed relative precision of \\textsl{Magboltz-2}, which is 0.05\\%. This proves that the first order taylor approximation is valid within the chosen range of possible variations.\n\n\n\\begin{figure}[t]\n\\centering\n\\includegraphics[width=0.48\\textwidth]{picDCS/NeCO2N2_T-vd.epsi}\n\\includegraphics[width=0.48\\textwidth]{picDCS/NeCO2N2_P-vd.epsi}\n\\caption{\nChange of drift velocity in dependency of temperature (left) and pressure (right). } \n\\label{figVDdepend}\n\\end{figure}\n\n\\begin{figure}[t]\n\\centering\n\\includegraphics[width=90mm]{picDCS/resHist.eps}\n\\caption{\nFit residuals of drift velocity change in [\\%]. } \n\\label{figResHistoSim}\n\\end{figure}\n\n\n\n\\section{Kalman filter for time dependent variables}\n\\label{sec:kalman}\nThe drift velocity and the gas gain are changing in time.\nThe drift velocity and gas gain is a function of many parameters, but not all of \nthem are known. We assume that the most important parameters are pressure and temperature\nand the influence of other parameters (gas composition, and electric field) are only \nslowly varying in time and can be expressed by smooth function $x_{off}(t)$:\n\\begin{equation}\nx(t) = x_{off}(t)+k_N\\frac{\\Delta{P/T}}{P/T}\n\\label{eq:KalmanTime}\t\n\\end{equation}\nwhere x(t) is the parameter which we observe.\n\\begin{equation}\n\\begin{split}\nx(t)=\\frac{\\Delta{G}}{G_0}\t\\\\\nx(t)=\\frac{\\Delta{v_d}}{v_{d0}}\t\n\\end{split}\n\\end{equation}\n\nThe Kalman filter parameters are:\n\\begin{itemize}\n\\item State vector  ($x_{off}(t)$, $k_N$) at given time\n\\item Covariance matrix\n\\end{itemize}\n\nThe Kalman filter implement the following functions:\n\\begin{itemize}\n\\item Prediction - adding covariance element $\\sigma_{xoff}$\n\\item Update state vector with new measurement vector ($x_t,\\frac{\\Delta{P/T}}{P/T}$)\n\\end{itemize}\n\n\\begin{figure}[t]\n\\centering\n\\includegraphics[width=80mm]{picDCS/vdriftraw_time.eps}\n\\includegraphics[width=80mm]{picDCS/tpraw_tp.eps}\n\\caption{\n\tDrift velocity as function of time (upper plot) and as a function of $\\Delta(T/P)$ (lower plot)\n} \n\\label{figVDrift}\n\\end{figure}\n\n\\begin{figure}[t]\n\\centering\n\\includegraphics[width=80mm]{picDCS/vdriftptcorr_time.eps}\n\\includegraphics[width=80mm]{picDCS/vdriftfdrift_time.eps}\n\\caption{\n\tDrift velocity corrected for T/P variation as function of time (upper plot). \n\tIn the lower plot the correction for time dependent offset is  also applied ($x_{off}(t)$ in formula\\ref {eq:KalmanTime})\n} \n\\label{figVDriftCorrected}\n\\end{figure}\n\n\n\n\n\n\\section{Precision of the correction}\n\nThe precision of the drift velocity correction and gain correction is proportional\nto the  precision of the pressure and temperature measurement and to the length of the time\ninterval \n\\begin{eqnarray}\n    \\sigma^2_x=\\sigma^2_{xoff}\\Delta{t}+k^2_N\\sigma^2_{P/T}\n\\label{eq:sigmaX}\n\\end{eqnarray}\n\nThe typical relative resolution of the pressure and temperature measurement is on the level of $6\\times10^{-5}$ and\n$1\\times10^{-5}$ respectively (see picture \\ref{figDCSResol}). For cool gas the  coefficient $k_N$ is close to one. The contribution of the P/T correction to the drift velocity uncertainty is on the level of  $6.1\\times10^{-5}$ (150 microns for the full drift length of 250 cm)\n\nThe $\\sigma_{xoff}$ from equation \\ref{eq:sigmaX} was  estimated from plot \\ref{figVDriftCorrected} and is on the level of 0.001 in a four day period. This estimate was obtained for the period of largest change in the present data sample. Further investigations should be carried out for extended time periods.\n\nFor the TPC drift velocity determination, the requiered relative resolution is on the level of $6\\times10^{-5}$.\nEntering the observed sigmas into equation (\\ref{eq:sigmaX}) the minimal frequncy of the drift velocity updates were estimated (equation \\ref{eq:driftUpdateTime}) to be about 1 hour.  \n\\begin{eqnarray}\n    \\Delta{t}\\le\\frac{\\sigma^2_x}{\\sigma^2_{xoff}}\\approx\\left(\\frac{6\\times10^{-5}}{0.001/4days}\\right)^2=0.05 day.\n\\label{eq:driftUpdateTime}\n\\end{eqnarray}\n\n\n\\begin{figure}[t]\n\\centering\n\\includegraphics[width=80mm]{picDCS/deltaPoverP.eps}\n\\includegraphics[width=80mm]{picDCS/deltaToverT.eps}\n\\caption{\nThe relative resolution of the pressure and temperature  measurement.\n} \n\\label{figDCSResol}\n\\end{figure}\n\n\n\n\\section{ Alice TPC drift calibration using tracks}\n\nIn the first approximation there is a linear dependence of the z position on the drift time.\nIn the Alice TPC the expression on the A side and C side of the chambers have the same drift velocity part $v_d$ \nwith opposite sign. The full drift length $z_{0A}$ and $z_{0C}$ are different. We suppose that\nthe $t_0$ offset given by trigger arrival time is the same. In reality the $t_0$ equalization is applied before,\nusing the pad-by-pad calibration pulser measurement. We let the variable $s$ represent the sides A and C with, with respective values $s_A=-1$ and $s_C=+1$. \n\\begin{equation}\n\\begin{split}\nz_s = z_{s0}+sv_d(t-t_0)\n\\end{split}\n\\end{equation}\n\nLet the actual value of drift velocity $v_d$ and the time offset $t_0$ are shifted by some $\\Delta$ value.\nOur starting drift velocity values and time offset are $\\tilde{v}_d$ and $\\tilde{t}_0$\n\\begin{equation}\n\\begin{split}\nv_d=\\tilde{v}_d+\\Delta v_d \\\\\nt_0=\\tilde{t}_0+\\Delta t_0 \\\\\nv_c = \\frac{\\Delta{v_d}}{\\tilde{v}_d} \\\\\n\\Delta{z}_{t_0} = \\Delta{t}_0\\tilde{v}_d \\\\\n\\end{split}\n\\end{equation}\n\nThen the actual z position is expressed using the starting z position measurement $\\tilde{z}_s$. \n\\begin{equation}\n\\begin{split}\nz_s = \\tilde{z}_s-\\frac{\\Delta v_d}{v_d}(z_{s0}-\\tilde{z}_{s})-s\\Delta t_0 \\tilde{v}_d\\\\= \\tilde{z}_{s} -v_c(z_{s0}-\\tilde{z}_{s})+\\Delta{z}\\\\\n\\end{split}\n\\end{equation}\n\n\nIn previous expression  we neglected second order correction\n\\begin{equation}\n\\begin{split}\n\\Delta{v_d}\\Delta{t_0}\\ll\\frac{\\Delta v_d}{v_d}(z_{s0}-z_{s}) \\\\\n(t-t_0)\\approx \\frac{(z_{s0}-\\tilde{z}_{s})}{v_d}\n\\end{split}\n\\end{equation}\n\nCombining the z measurement the track parameters can be fitted. Let's assume linear track model:\n\\begin{equation}\n\\begin{split}\n\\tilde{z}_s =\\tilde{a}_s+\\tilde{b}_sx \\\\\nz_s = a_s+ b_sx \\\\\n\\end{split}\n\\end{equation}\n\nThe relation between starting  parameters $\\tilde{a}, \\tilde{b}$ and corrected parameters $a,b$ is linear.\n\\begin{equation}\n\\begin{split}\na_s=\\tilde{a}_s-v_c(z_{s0}-\\tilde{a}_s)-s\\Delta{z}\\\\\nb_s=\\tilde{b}_s(1+v_c)\\\\\n\\end{split}\n\\end{equation}\nThe inclination angle correction is the same on the A and C side.\n \nTracks crossing the central electrode, respectively primary tracks can be used to\nmonitor correction coefficients $\\Delta{z}$ and $v_c$. For tracks crossing the central electrode the a and b parameters at the crossing point fitted form A and C side are the same. In case of primary tracks, the z position at r-$\\phi$ DCA are also the same:\n\\begin{equation}\n\\begin{split}\na_A-a_C=0 \\\\\n\\Delta\\tilde{a}(1-v_c)+2\\Delta{z}-v_c(z_{0A}-z_{0C})=0 \\\\\n\\Delta\\tilde{a}=\\frac{v_c(z_{0A}-z_{0C})-2\\Delta{z}}{1-v_c}\t\n\\end{split}\n\\end{equation}\n\nCombining information from A and C side the correction parameters, drift correction $v_c$ and offset correction $\\Delta{z}$ can be fitted.\n\nIn case track crossed the central electrode the track parameters of the same track on A side and C side can be fitted.\nThe actual track parameters $a_A$ and $a_C$  respectivally $b_A$ and $b_C$ are the same.\n\n\n\n\\begin{thebibliography}{99}\n\n\\bibitem{Blum}\nW.Blum, W.Riegler, L.Luigi: Particle Detection with drift Chambers; 2nd ed.\n%@book{Blum,\n%      author       = \"Blum, Walter and Riegler, Werner and Rolandi, Luigi\",\n%      title        = \"Particle Detection with drift Chambers; 2nd ed.\",\n%}\n\n\\bibitem{magboltz}\nS.Biagi: Magboltz-2, transport of electrons in gas mixtures; http://consult.cern.ch/writeup/magboltz\n%@Misc{magboltz,\n%  author = {S. Biagi},\n%  title = {{Magboltz-2}, Transport of electrons in gas mixtures},\n%  year =  {2008},\n%  annote = {Version 8.3}\n\n\n\n \\end{thebibliography}\n\n\\end{document}\n", "meta": {"hexsha": "3e45d78337e0215b6d1e4fe79226c9166c62c16a", "size": 12739, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "TPC/doc/calib/DriftV/tpcDrift.tex", "max_stars_repo_name": "AllaMaevskaya/AliRoot", "max_stars_repo_head_hexsha": "c53712645bf1c7d5f565b0d3228e3a6b9b09011a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 52, "max_stars_repo_stars_event_min_datetime": "2016-12-11T13:04:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T11:49:35.000Z", "max_issues_repo_path": "TPC/doc/calib/DriftV/tpcDrift.tex", "max_issues_repo_name": "AllaMaevskaya/AliRoot", "max_issues_repo_head_hexsha": "c53712645bf1c7d5f565b0d3228e3a6b9b09011a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1388, "max_issues_repo_issues_event_min_datetime": "2016-11-01T10:27:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T15:26:09.000Z", "max_forks_repo_path": "TPC/doc/calib/DriftV/tpcDrift.tex", "max_forks_repo_name": "AllaMaevskaya/AliRoot", "max_forks_repo_head_hexsha": "c53712645bf1c7d5f565b0d3228e3a6b9b09011a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 275, "max_forks_repo_forks_event_min_datetime": "2016-06-21T20:24:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T13:06:19.000Z", "avg_line_length": 45.334519573, "max_line_length": 871, "alphanum_fraction": 0.7394614962, "num_tokens": 3877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358685621719, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3253224947386839}}
{"text": "                FUNCTION MINIMIZATION\n \n \n \n                      F. James\n%        Reprinted from the Proceedings of the\n%  1972 CERN Computing and Data Processing School,\n% Pertisau, Austria, 10-24 September, 1972 (CERN 72-21)\n\\documenstyle{report}\n\\begin{document}\n\\chapter{Introduction}\n\\section{The motivation}\nA large class of problems in many different fields of research can\nbe reduced to the problem of finding the smallest value taken on by a\nfunction of one or more variable parameters.  Examples come from fields\nas far apart as industrial processing (minimization of production costs\nand general relativity (determination of geodesics by minimizing the\npath length between two points in curved space-time).  But the classic\nexample which occurs so often in scientific research is the estimation of\nunknown parameters in a theory by minimizing the difference (chi-square)\nbetween theory and experimental data.  In all these examples, the function\nto be minimized is of course determined by considerations proper to\nthe particular field being investigated, which do not concern us here.\nOur aim is to study the mathematical problem of minimization.\n \n\\section{Minimization, maximization, and optimization}\n \nAlthough traditionally one speaks of function minimization, some\nauthors refer to maximization.  Of course the two are entirely equivalent\nsince one can be converted to the other by changing the sign of the function.\nThus the problems of minimizing chi-square, maximizing likelihood,\nminimizing cost, or maximizing efficiency can all be considered as\nminimization (or maximization).  To avoid committing oneself, it is\nfashionable to speak of optimization, to cover both cases.  This\nunfortunately causes confusion with optimization in control theory where\nthe principal techniques are analytical (calculus of variations) and\nhence bear little relationship to the numerical methods used in function\nminimization as treated here.\n \nTo add to the confusion there is the term \"programming\", which is\nalso used to mean minimization (usually specified as linear programming,\nnon-linear programming, or mathematical programming), a historical usage\ndating from the time when programmers in the modern sense did not exist,\nand computer users were not programming but coding.\n \nOther terms used for minimization are extremization and\nhill-climbing.  Since these can also be used to mean other things, the\ngeneral conclusion is that in this field you can not tell a book from\nits title.  While waiting for general agreement as to what the subject\nshould be called, we will stick to function minimization.\n \n\\section{Definition of the problem}\n \n      Given a function $F(x)$, the general problem is to find the value of\nthe variable or variables x for which the function $F(x)$ takes on its\nsmallest value.  [As pointed out above, this is entirely equivalent to\nfinding the x for which the function $-F (x)$ takes on its largest value,\nbut for consistency we will always consider only minimization.]  The\nrules of the game are the following:\n \n  i) The function $F(x)$is assumed not to be known analytically, but is\n     specified by giving its value at any point x.\n \n ii) The allowed values of the variable or variables x may be restricted\n     to a certain range, or to satisfy certain conditions,\n     in which case one speaks of constrained\n     minimization.  In these lectures we limit ourselves to the\n     unconstrained problem.\n \niii) In some cases additional information about the function F may be\n     available, such as the numerical values of the\n     first or second derivatives $$ at any point x.\n     Such knowledge cannot in general be assumed, but\n     should be used when possible.\n \n iv) The function $F(x)$ is repeatedly evaluated at different points x\n     until its minimum value is attained.\n \nThe method which finds the minimum (within a given tolerance) after the\nfewest function evaluations is the best.  Occasionally other considerations\nmay be important, such as the amount of storage required by the\nmethod  or the amount of computation required to implement the method,\nbut normally the dominating factor will be the time spent in evaluating\nthe function.\n \n \n\\section{Definition of a minimum}\n \n     The theorems of elementary calculus tell us that the function\nF(x) must take on its smallest value at a point where either:\n \n  i) all derivatives $aF/ax = O$ (a stationary point), or\n ii) some derivative $aF/ax$ does not exist (a cusp), or\niii) the point x is on the boundary of the allowed region (an edge point)\n \n     Although we will sometimes find it useful to consider points\nsatisfying the above properties, this approach of considering essentially\nthe analytic properties of the function is clearly not well adapted\nthe rules of the game as outlined above.  Indeed, when one considers that\nthere may be any number of stationary points, cusps, and edge points,\nall of which may be arbitrarily hard to find by simply sampling the\nfunction value, the whole problem begins to appear hopeless unless some\nsimplifying assumptions are made.\n \n     The usual simplification consists in abandoning the attempt to find\nthe global minimum and being satisfied with a local minimum.  A local\nminimum may be defined as a point xo, where for all points x in some\nneighbourhood around $xo$ we have $F(x) > F(xo)$.\n \n     Now the situation looks much brighter since the very definition\na local minimum suggests a general strategy for finding one:  we vary x\nby small steps in a direction which causes F to decrease, and continue\nuntil F increases in all allowed directions from some point $xo.$  This\ndoes not yet tell us how to vary x, but at least it suggests that a solution\ncan be found.\n \n \n\\section{The shape of the function -- Taylor's series}\n \n     With a view to making an intelligent minimizing method, it is of\ninterest to consider what we might reasonably expect about the behaviour\nof F.  If F represents a physically meaningful function, we would certainly\nexpect all the derivatives of F to exist everywhere in the region of\ninterest.  Under these conditions we can write down the Taylor series\nexpansion for F about some point $xl$, assuming for the moment that x\nrepresents just one variable:\n \n \n              $F(x) = F(xl) + aXl  (x-xl) + 2 |  (x-xl)  +\n                       Xl             Xl$\n \n \nAlthough we do not know anything a priori about the domain of convergence\nof this series, we do know that as the distance $(x -xl)$ becomes smaller,\nthe higher order terms become less important, so that we would expect\nthat predictions based on the low-order terms should not be very wrong,\nat least for small steps.  Before considering these terms in more detail\nlet us generalize the variable x to a vector of n variables $x$.  Then we\nhave\n \n          $F(x) = F(Xl) + T(x-xl) + 2 (x -xl)  |(x - xl) +$\n \n \n          where the matrix $G$ is defined by $Gij = a2F/axiaXi$ and\n          the gradient vector $g is gi = aF/axi$, all derivatives\n          being evaluated at $xl$.  The T denotes transposition\n          which turns a column vector into a row vector.  Note\n          the difference between $xi$ (the i$th$ variable) and $x$\n          (the position vector at the point i).\n \nNow the first term of the above series is constant, so it will not tell\nus much about where to look for a minimum.  The second term is\nproportional to the gradient  $ $\nand tells us in which direction the function is\ndecreasing the fastest, but since it is linear in $x$, it does not predict\na minimum and therefore does not tell us what step size to take.\nMoreover, as we approach the minimum $g ) O$ (if it exists)\nso we will have to\ngo further and consider the next term.  The third, or quadratic term\ndescribes a parabolic behaviour and is therefore the lowest term to\npredict a minimum.  Unlike $g$ we can expect G to be roughly constant over\nsmall regions, since it would be exactly constant if higher-order terms\nwere zero.\n \n     We mention, in passing, one class of problems in which the above\nanalysis would not hold at all.  This is in the field known as linear\nprogramming, which limits itself to minimizing functions which are linear\nin the parameters, subject to constraints which are also linear.  A\nlinear function can not have a minimum in the sense described above (a\nstationary point) but must take on its minimum at a constraint boundary\n(edge point).  For such problems the description of the constraints therefore\ntakes on greater importance than the analysis of the function\nitself, and will not be considered in these lectures.\n \n \n\\section{Non-existence of optimum in general}\n \n     Although we will be studying and comparing\ndifferent minimization algorithms (recipes), the reader should be warned\nat the outset that in the strict sense of the rules of the game as stated\nin Section 1.3 above, we will not be able to show any algorithm to be\nsuperior to any other for all functions.  In principle at least, no\nmatter how bad one algorithm is, or how good another, we can always find\na function which will be minimized faster by the bad method than by the\ngood one.  We should keep such essentially theoretical considerations in\nmind, but should not be overly discouraged by them.  In particular,\ncertain objective criteria will emerge for comparing methods even though\nthe principal criterion -- minimization speed -- depends on the function.\nIn the past there has in my opinion been an overemphasis on such objective\ncriteria in an attempt to find the ideal universal minimization\nalgorithm.  More recently, the tendency is to adapt the algorithm to\nthe function, even to the point of introducing a super-algorithm which\nwould\nchoose a sub-algorithm appropriate to the function at hand. Such questions\nof global strategy will be considered later.\n \n     The reader should also be warned that in presenting part|cular\nalgorithms I will often omit details which are unimportant to an\nunderstanding of the algorithm although they may be crucial in actually\nmaking it work.  The original references should therefore be consulted\nbefore programming such alorithms.\n \n \n\\section{The role of the computer}\n \n     While our subject is essentially a mathematical one, it has been so\nprofoundly influenced by the existence of high-speed electronic computers\nthat it would certainly be unfair  not to mention them here.  Indeed,\nreal progress in the solving of large-scale practical problems has come\nonly in the last fifteen years, although much of the basic theory dates\nback to Newton's time or even earlier.  This is, of course, because of\nthe renewed interest in numerical minimization techniques for use on\ncomputers.  As it is no longer even thinkable to use these techniques\nfor hand calculations, it is best to place ourselves immediately in the\ncomputer context and to conceive of our function F(x) rather as a\nsubroutine which returns a value of F (and perhaps some other information\nsuch as numerical values of derivatives) for given input values of the\narguments x.\n \n     One unpleasant consequence of the computer-oriented approach is that\nwe will sometimes have to worry about rounding-off errors in the\nfunction value due to the finite word length of digital\ncomputers.  This rounding\nerror is usually of the order\nof $10 8$ of the function value for computers\nwith 36-bit words in single precision, but the cumulative effects of\nrounding inside a complicated function subroutine may be much larger.\nIn addition there may be problems of overflow or underflow.\n \n \n\\chapter{ONE-DIMENSIONAL MINIMIZATION}\n_\n \n\\section{Usefulness in n-dimensional problems}\n     We will first consider functions of just one variable, since some\ngeneral problems can be seen more easily in this simplest case and also\nbecause some n-variable algorithms contain steps which require\none-dimensional minimization.  The one-variable problem is therefore both\ninstructive and useful even though our prime consideration will be that\nof more complex problems.\n \n \n\\section{Grid search}\n \n     The most elementary search technique consists in choosing k equally\nspaced points within the range of the parameter x, evaluating the\nfunction at each of the points, and retaining the lowest value found. If\nthe spacing between points is $x$, one of the points is sure to be\nwithin\n$x/2$ of the true minimum, although in principle it may not be the point\ncorresponding to the lowest value.  Still, if the function does not vary\ntoo wildly over the distances of the order of $x$, one generally assumes\nthat this method gives the minimum within a range of about $x.$\n \n     Of course the grid search method has some difficulties. It is not\ndirectly applicable to the usual case where the range of x is infinite\nBut in this case a simple remedy is to choose a reasonable range in the\nmiddle of the allowed range, and later to shift the sampling range if the\nminimum comes out at an end point.\n \n     The most serious objection to the grid method is its inefficiecy\nGiven the assumption that F does not vary too much over a distance\nof $ $\nmany of the function evaluations are certainly unnecessary, namely those\nthat are in regions where the function value is known to be large. In\nother words, the algorithm takes no account of what it has learned ;\nabout the function.  This inefficiency becomes more striking, in fact\n \nthe function.  This inefficiency becomes more striking, in fact\nprohibitive, when extended to many variables.\n \n     On the other hand, this method has the prized virtues of extreme\nsimplicity and absolute stability.  It always converges within the\ndesired tolerance in a known number of steps and is quite insensitive\nto the detailed behaviour of the function.\n \n     The efficiency of the grid method may be greatly improved by\nproceeding in several stages, using a smaller range and smaller step\nsize in each succeeding stage.  In this way each stage takes account of\nthe least value found in the preceding stage, and the method can be said\nto converge in the usual sense of increasing accuracy due to decreasing\nstep size.  In the next section we consider optimum ways to arrange\nstaging in order to obtain the fastest decrease in step size.\n \n \n\\section{Fibonacci and golden section searches}\n .\n \n     In order to optimize the grid search, we want to minimize the\nnumber of function evaluations per stage, compatible with maintaining\na constant reduction of a factor t in the step sizes at each stage.\nThis will yield the fastest reduction in step size.  One function evalution\ntells us nothing about the possible location of a minimum, but as\nlong as we restrict ourselves to local minima in a given range of x, two\npoints are sufficient as shown in the diagram below. If $F(xl) < F(x2)$,\n                                      then there must be at least one\n                                      local minimum somewhere in the\n                                      range $O < x < X2$. Now in this\n                                      new range, we already have one\nO          Xl     X2          l       point $(xl)$, so that a further\n                                      reduction in range is possible\n                                      with only one new function evaluation,\n and the procedure can now be continued with only one new evaluation\nper stage.  It remains to be shown that this can be continued indefinitelz\nwith a constant reduction in step size, and to calculate what that\nreductiontion will be. Clearly we would get the maximum reduction on the\nfirst step if $xl and x2$\nwere very close together, but we must not forget that\n$Xl (or X2)$will then be used for the next stage and should therefore be\nclose to the middle of this new interval as well.  The situation is\nillustrated in the diagram below, where the distances indicated are\nimposed by the symmetry of the intervals and the condition that the\nreduction in range must be a factor of t in each stage.  The new range\nafter evaluation of $F(x3)$will be $X3 < x < x2$and\nits length must be $t$\n \n \n \nO         Xl     X2        1        0     X3 Xl     X\n                                 q                  ,l _|2 _ q\n                                             2\n \n \nThis will be possible since there is a real root to the equation:\n                                  $t2 = 1- t\n                                  t  = g2 1  0.616 $.\n \n \nSince this ratio t is known as the goZden section, the minimization\ntechnique is called a golden section search.  If the number of stages\nto be taken is known in advance, it is possible to improve very slig\non this technique by using a Fibonacci seorch, as described for examF\nin Kowalik and Osbornel).  Although Fibonacci can be shown to be opti\n(in a sense described below), the slight improvement is probably not\nworth the added complication.  The golden section search is optimal\namong algorithms where the stopping point is not decided in advance.\n \n     The above techniques are optimal only in the minimox sense, that\nthey minimize the maximum number of function evaluations necessary to\nobtain a given accuracy.  It might be called the pessimists optimalit\nsince in game theory it is the best strategy against an intelligent\nopponent who is trying to make you lose.  It should therefore be\neffective\nin minimizing pathological functions, but in more normal cases we sha\nexpect other methods to be better.  Such methods are described in the\nfollowing sections.\n \n \n\\section{Quadratic interpolation and extrapolation}\n \n     A more optimistic approach consists in studying the expected\nbehaviour of the function and then hoping that the deviations of the\nreal function from this behaviour are not too great.  From the Taylor's\nseries analysis of Section 1.5, it would be reasonable to proceed by\nassuming that the function is nearly quadratic.\n \n     Since a parabola is determined by three points, this method requires\nthe function to have been evaluated for three different values $xl, x2$\nand $X3$. It then predicts the minimum to be at the minimum of the\nparabola passing through these points.  If the three function values are\n$Fl, F2, and F3$, the predicted minimum is at $X4$ given by\n \n \n                            - 10 -\n \n \n            $(X2 + x3)Fl      +     (Xl + x3)F2      +      (Xl + X2)F3\n  x4 =  (xl - x2)(xl - x)      (X2 - xl)(x2 - X3)      (X3 - Xl)(X3- X2)$\n \n              $2 r Fl         +          F2          +          F3\n        L(xl - X2)(Xl - X3)     (X2 - xl)(x2 - x3)     (x3 - xl)(x3 - X2)J$\n \n \nConsiderable simplification results when the three points are equally\nspaced, a distance d apart, in which case\n \n \n                    $x4   X2   2 (Fl + F3 - 2F2) $-\n \n \nThe function is then evaluated at X4 this point replaces one of the\nfirst three, and a new point is predicted, again by quadratic\ninterpolation using the new set of three points.\nThe method terminates when the\npredicted function value at some new point agrees with the actual value\nwithin a specified tolerance.\n \n     This algorithm usually performs quite well when applied to easy\n(nearly quadratic) functions, but suffers from a number of instabilities\nwhich can be quite serious, as follows:\n \n  i) At any step the three points may determine a parabola with a maximum\n     rather than a minimum, in which case the method diverges.\n \n ii) If the three points lie nearly in a straight line, the algorithm\n     takes an enormous step which may cause numerical difficulties as\n     well as diverging.\n \niii) After each step there is a choice of which two of the three previous\n     points to retain for the next step.  It is usually more convenient\n     and logical to retain the most recent points, but this may also lead\n     to instabilities by throwing away the best points.\n \n iv) Even without any of the above difficulties, the method may oscillate\n     about the minimum instead of converging toward it.\n \n     All the problems can be fixed by including checks and safeguards in\nthe algorithm, but the remedies always involve abandoning, at least\ntemporarily, the quadratic interpolation\n step.  The best remedy is probably\n \n \nto reserve the method for well-behaved functions and to abandon it\nentirely as soon as trouble arises.  It is most often used as the last\nstep in algorithms which depend principally on other methods, since\nphysical functions are usually quite parabolic in the immediate\nvicinity of the minimum.\n \n     When derivatives of the function are available, variations of\nquadratic interpolation are possible, using instead of three points to\ndetermine the parabola, either two function values and one first\nderivative, or the function value and the first two derivatives at one\npoint. These\nvariations tend to be even more unstable than the basic method, since\nthey use information from fewer points.\n \n \n\\section{The success-failure method}\n \n     A good compromise between the stability of the grid search and the\nrapid convergence of quadratic interpolation is found with the\nsuccess-failure\n technique of Rosenbrock2).  A start point $xO$ and initial step size\nd are required, and the function is evaluated at xO and xo + d.  Th\nstep is termed a success if $F(xO + d) ' F(xO)$, otherwise it is a failure\nIf it is a failure, d is replaced by $-d$ where  is a contraction factor\nless than one, and the test is repeated.  If it is a success, $xo$ is\nreplaced by $xO + d$, d is replaced by d, where  is an expansion factor\ngreater than one, and the test is repeated.  The process continues in\nthis way until the function values change by less than a specified amount,\nThe numerical values usually used for the expansion and contraction\nparameters are $ 3.0 and   0.4.$\n \n     An interesting feature of this method is that a local minimum is\nalways bracketed whenever a success is followed by a failure.  When this\nhappens, the middle one of the last three points is always lower than\nthe outer two, so that one is in a favourable position for trying a\nquadratic\ninterpolation step.  The success-failure method, with one quadratic\ninterpolation step each time a success is followed by a failure, is\nprobably\nthe most effective one-dimensional technique for use on general functions\nalthough in special cases other methods may be superior.\n \n \n                                     - 12 -\n \\chapter{STEPPING METHODS IN MANY VARIABLES}\n  \\section{Grid searches and random searches}\n        An excellent illustration of the enormous increase in complexity in\n   going to spaces of high dimensionality is afforded by the grid search\n   technique in many variables.  In order to localize a minimum to 1% of\n   the range of one variable by this technique requires 100 function\n   evaluations;  in ten variables the number of points required is $102$.\n   Clearly  we can forget about this method when more than one or two parameters are involved.\n \nIn fact it is a general rule in function minimization, as in\nfunction integration, that one should not expect good one-dimensional\ntechniques to be good when extended to higher dimensionality. Experience\nwith ntegration suggests that a Monte Carlo search is more efficient\nthan a grid search in many dimensions. The Monte Carlo technique\nconsists in\nchoosing points randomly according to some distribution\n   (usually uniform or normal).\n \n        But even when these methods are refined by using variable search\n   ranges, they prove far too slow for general use and we must turn to more\n   efficient techniques.\n \n \\section{Single-parameter variation}\n \n        Since the condition for a minimum which is a stationary point in\n   n variables $xi$ is the vanishing of all n first derivatives $aF/xi$\n it is\n   natural to try to make each derivative vanish separately, one after the\n   other.  This is the old method of single\n   parameter variation, where one seeks a\n   minimum with respect to one variable at a\n       /           time using one of the techniques described\n2 / /   MIN earlier.  Of course when you have finished\n                                  minimizing with respect to $X2$ you may no\n               -  / /            longer be at a minimum with respect to $xl$,\n                    / /           so you generally have to start all over\n       /                        again, but the process usually does\n  SAR                      converge, as illustrated for two variables in\n                           X l\n                                  this diagram. Here the curves represent\n \n                                - 13 -\n \n \ncontours of equal function value, and the straight lines show the steps\ntaken in minimizing F with respect to $xl, then X2, then xl$, etc.  In\nthis case the method converges nicely after only four single-parameter\nminimizations.\n \n     Consider now the function represented by the contours shown below\nHere the method proceeds much more slowly because of the narrow valley\n \n                     S T `. V                '\n                                              Xl\n \n \n \nSuch behaviour in many dimensions causes this method to be generally\nconsidered as unacceptably slow.\n \n     Two of the more successful improvements aimed at avoiding such\nbehaviour are due to Hooke and Jeeves3) and Rosenbrock2).  We discuss\nthe latter below.\n \n \n\\section{Rosenorock's method}\n \n     Rosenbrock's algorithm2) starts by performing single-parameter\nminimizations as above.  Then when one full cycle of all parameters has\nbeen completed, a new set of orthogonal axes is defined with one axis\ntaken as the vector from the start point to end point of the cycle.\nThis vector points in the direction of previous over-all improvement and\nis expected to be a good direction for future improvement  In the case\nof the narrow valley seen above, it should point more or less along the\nvalley and avoid the zig-zag behaviour.  The next cycle of single-variable\n minimizations is performed using multiples of the newly defin\naxes as variables.\n \n \n                                - 14 a\n \n \n \n     The Rosenbrock method generally performs well, being quite stable\nand capable of following narrow valleys, but as the number of variables\nincreases, the efficiency drops, probably because the new axis defined\nby past improvement is based on points so far apart that it no longer\npoints along a \"hyper-valley\" at the start point of the next cycle.\nAlso, its terminal convergence is slow compared with the more\n''quadratic\" methods described in Section 4.\n \n \n     Another technique, that of Davies, Swann, and Campey4) (unpublished,\nsee Ref. 4) is similar to Rosenbrock's and will not be described here\n \n \n\\section{The simplex method}\n \n     One of the most successful stepping methods in many variables is\nthat of Nelder and Meads), based on the simplex.  A simplex is an n-\ndimensional figure specified by giving its n + 1 vertices.  It is a\ntriangle in two dimensions, a tetrahedron in three, etc.  The algorithm\ntakes the name simplex because at each step the information it carries\nabout the function consists of its values at n + 1 points.  One can\neasily visualize how the method works by considering the\ntwo-dimensional\ncase as in the diagram below.  The three starting simplex points are\nsomehow  chosen (perhaps randomly) and the function is evaluated at each\npoint.  Let the point $PH$ be that at which the function value is highest\n(worst) and $PL$ that at which it is lowest. Let $P$ be the centre-of-mass\nof all points in the simplex except $PH$  that is:\n \n \n                                 -n+l\n                               n '   i    H' -\n \n \n \n                                                                P-\n \n \n \n                   2  P\n \n \n                             P1 =PL\n                   P3 Ph\n                                             xl\n \n \n                                 - 15 -\n \n \nFrom the original simplex, a new simplex is formed by replacing $PH$ by\na better point if possible.  The first attempt to find a better point is\nmade by reflecting $PH$ with respect to $P$, producing\n$P* = P + (P - PH)$.\nIf $F(P*) < F(PL)$, a new point is tried at $P   = P + 2(P - PH)$.  If\n$F(P*) > F(PH)$, a new point is tried at $P** = P - (P - PH)$.  The best of\nthe new points then replaces $PH$in the simplex for the next step, unless\nnone of them is better than $PH$. In the latter case, a whole new simplex\nis formed around $PL$, with dimensions reduced by a factor of 0.5.\n \n     Variations on the method are possible by using different contraction\nor expansion factors when searching along the line from $PH$ through $P$\n(dotted in diagram).  Another interesting possibility is to attempt a\nquadratic interpolation step along the dotted line whenever three points\nhave been determined $(PH, P*, P**)$.  However, one must be careful not to\naccept a point too close to $P$, for then the simplex collapses into a line\n(or in general a hyperplane of n- 1 dimensions) from which it can never\nrecover.\n \n     The simpl|x algorithm, being designed always to take as big steps\nas possible, is rather insensitive to shallow local minima or fine\nstructure in the function caused by rounding errors, statistical errors\n(lonte Carlo output), etc.  Another of its virtues is that of requiring\nfew function evaluations, usudlly one or two per iteration.  In addition,\neach search is in an \"intellient\" direction, pointing from the highest\nvalue to the average of the lowest values.  Com?are this with Rosenbrock's\nmethod, where really only the principal axis is an \"intelligent\" direction,\nand all other searches are for exploring along orthogonal axes to\ndetermine a new principal axis.\n \n     A convenient convergence criterion for the simplex method is based\non the difference F(PH) - F(PL).  The iterations are stopped when this\ndifference is less than a preset value.  As a final step, the function is\nevaluated at $P$, which is often slightly better than $F(PL)$.\n \n     In view of the danger mentioned above -- of the simplex collapsing\ninto a hyperplane of dimension $n      $ it has been suggested to use $n $\nor more points rather than n+ 1 at each step.  I have tested this idea,\nwhich is equivalent to introducing a dummy parameter of which the\nfunction is independent, and have always found the efficiency of the\nalgorithm to decrease under these conditions.\n \n                                 - 16 -\n\\chapter{GRADIENT METHODS}\n \n\\section{Calculating derivatives}\n \n     I will call a gradient method any technique which uses information\nfrom a very small range of the variables (i.e. essentially derivatives)\nto predict good trial points relatively far away. This does not necessarily\n mean that they follow the gradient, but only that the gradient, and\nperhaps higher derivatives, are used or estimated.\n \n     It is of course possible in most cases to calculate analytically the\nnumerical values of the derivatives of a function, just as it is possible\nto calculate the value of the function itseif.  However, it is often\ninconvenient and dangerous if the algebra is complicated, so that very\noften we are faced with minimizing a function for which no derivatives\nare provided. Since the most powerful algorithms discussed below require\nderivatives, a general minimization program must be able to estimate the\nderivatives of the function by finite differences.\n \n     A first derivative may be estimated from\n \n \n                      $aF      F(xo+ d) - F(xO)\n                        x              d\n \n                       x o$\n \n \nwhere d is a \"small\" displacement.  The error will be, to lowest order\nin the Taylor's expansion,\n \n                                $d   a2F$\n \n It is therefore advantageous to make d as small as possible, but still\nlarge enough so that the rounding error in the computation of F does not\nbecome larger than the error introduced by $o.$ Since the second derivatives may not be known, it may not be possible to find an optimum\nstep-size d, so we may just have to close our eyes and guess.\n \n     A much safer method would be to use points chosen symmetrically\neither side of $xo$giving\n \n \n                      $aF|     F(xo + d) - F(xo - d)$\n \n \nfor in this case the error  vanishes to second order and the lowest\norder term is proportional to the third derivative. A disadvantage of\nthis method is that it requires 2n function calls to estimate the n first\nderivatives, whereas the asymmetric steps require only n +l [or only\nF$(xo)$ has to be evaluated anyway].  An advantage of the symmetric steps\nmethod, however, is that it gives the second derivatives as a\nby-product [assuming F$(xo)$ known]:\n \n \n                 $a2F   F(xO - d) + F(xO+ d) - 2F(Xo)$\n                                      2\n \n \nand from the relationship for the error $$ in the asymmetric method,\nconservative upper limit of the uncertainty in the first derivative\nresults assuming at least that the symmetric formula gives a smaller\nerror than the asymmetric one.  A complete treatment of step sizes is\nbeyond the scope of these lectures but can be found in a paper by\nStewart6 ) .\n \n     The numerical evaluation of second derivatives is facilitated by\nthe fact that they should be approximately constant over small regions,\nso that symmetrical steps are usually not necessary.  Unfortunately,\nhowever, there are a lot of second derivatives to evaluate;  since they\nform a symmetric n x n matrix, there are n(n + 1)/2 independent\ncomponents, requiring at least n(n - 1)/2 points  in addition to those\n                                    required for the symmetric derivatives.\n                                    . For two parameters, a minimum\n                                     point pattern is shown in the\n                                    diagram at left. The odd point (for\n   $2                 c             the mixed second derivative) could\n                 O O dO$          have been chosen in any corner. The\n                                    two-dimensional diagram is somewhat\n                     |              misleading since for large n, the\n                                    number of \"odd points\" is n times\n                                    larger than the number of \"symmetric\" points.\n                  Seen Rejected  Percentage\n \n\\section{Steepest descent}\n \n     As soon as the function's first derivatives are known, it is natural\nto follow the direction of the negative gradient vector in seeking a\nminimum, since this is the direction in which the function is decreasing\nthe fastest.  Such a technique was used by Cauchy more than a century\nago, and is the basis of what is now known as the method of steepest\ndescent.\n \n     This method consists of a series of one dimensional minimizations,\neach one along the direction of local steepest descent (gradient) at the\npoint where each search begins.  Of course the direction of the gradient\nis not constant along a line even for a general quadratic function, so\nwe expect many iterations to be necessary, but the method can be shown\nto converge for a quadratic function.  Let us follow its progress\n                    / / / /  .-MIN  for a typical function whose contours are shown\n                                         in the diagram.\n                        / / /  / /  We immediately see an unfortunate\n                   STARI  / / / /  property of the successive search\n                        `J-' / /  directions: if each linear minimization is exact,\n                                      successive searches must be in orthogonal\n                                      directions.  In two dimensions,\n                                      this yields steps which look just\nlike the single parameter variation method with the axes rotated to\nline up with the gradient at the start point.  In many dimensions the\nsituation is not quite so bad, but successive directions are still\northogonal and the algorithm cannot be considered acceptable.\n \n     It is in fact easy to draw contours for a reasonably well-behaved\n                    \"'|           hypothetical function (as at left)\n             X2               / where the direction to the\n                             /  ) minimum is just perpendicular to the gradient.\n \n                            - 19 -\n \n \n\\section{Newton's method}\n \n     It is clear that since a general quadratic function is determined\nby specifying its value, first derivatives, and second derivatives at a.\npoint, it can be minimized in one step if and only if all this information\n(or its equivalent) is taken into account.  Let us write a\nquadratic function as\n \n              $$F( )   F(  ) +  T | (    ) + l (    )T G($$\n \nwhere the gradient $$ is evaluated at $xo$ and the second derivative\nmatirx $G$is a constant.  Then the minimum is given directly by\n \n                     $Xm = xO- G lg = xO_$,\n \nwhere the inverse of the second derivative matrix is the covorience\nmatrix $v$\n \n     This is then the many-dimensional equivalent of quadratic\ninterpolation\ndiscussed earlier, and it is subject to the same sort of difficulties\nwhen applied as an iterative technique to general non-quadratic functions.\nBut let us first point out its good features:\n \n  i) the step size is no longer arbitrary, but is prescribed precisely by\n     the method;\n \n ii) the step directions are no longer necessarily along the gradient\n     vector but take account of parameter correlations (narrow valleys\n     or ridges) through the mixed second derivative terms.\n \n     In practice, however, the method is unstable, essentially for the\nreasons given in Section 2.4.  In particular, it diverges whenever the\nmatrix G (or V) is not positive-definite (see next section).  In its\nunmodified form  the method is used only when the minimum is known to\nbe very close or when the function is known to be positive quadratic (for\nlinear least squares).  However, it is clearly a powerful technique\nand is worth studying in some detail since all the most successful\nalgorithms are based on ewton-Zike steps, as discussed below.\n \n                                   - 20 -\n \n\\section{Positive-definite quadratic forms}\n     We pause here briefly to consider the properties of quadratic forms\nuseful for understanding the more powerful gradient methods.  In one\ndimension the description is simple;  a general quadratic form can be\nwritten\n \n                         $F(x) z a + gx + 2 Gx2 $,\n \n \nwhere $g = aF/ax at x = 0$, and $G = a2F/ax2 also at x = .$ . This function\nhas a minimum if and only if G > 0.  If G = 0, the minimum is at infinity,\nThe minimum (if it exists) is at x = -g/G.  len using a quatratic\napproximation to minimize a general non-linear function, it makes sense to\ntake a step to $x = -g/G$ only if $G > O$ since otherwise we step to\na predicted maximum or to infinity.  A possible remedy if $G < O$ is to\ntake a\nstep $x = -g$;  that is, to set G arbitrarily equal to unity so that the\nstep will at least be in the right direction although it will now have\narbitrary length.  Consideration of the sketch below shows that this is\nthe only thing we can do unless more information is available, since the\nquadratic part of the function is not convex or positive-definite at\nthe point $xo$:\n \n \n          F t Gc O   G|\n \n \n                  l  I\n                      -g/G   I   \\\n \n                         -9 \\\n \n                       xo                       x\n \n      These arguments may now be extended to many dimensions where g\nbecomes the gradient vector , and G becomes the second terivative matrix\n$G . Then the Newton step to $x - -G lg$ makes sense only if $ (or | l)$ is\na positive-definite matrix, since only then does the quadratic form\n \n \n                                   T      1  T\n                        $F(x) = a + g | x + 2 x Gx$\n \n \nhave a minimum.  If G is singular, the predicted minimum (or maximum)\nis not unique.\n \n     Unfortunately there is no simple way of telling, in general, if a\nmatrix is positive-definite by inspecting individual components, but we\ncan at least state some of the many useful properties of such matrices.\nTwo necessary (but not sufficient) conditions for a (square, symmetric)\nmatrix to be positive-definite are:\n \n  i) the diagonal elements must be positive (this is in fact sufficient\n     for a 1 x 1 matrix);\n \n ii) the off-diagonal elements must obey $Gij < GiiGjj$\n \nProperties (i) and (ii) together are sufficient for a 2 x 2 matrix\nWhile the above conditions are easy to check, they are not in general\nsufficient.  Some necessary ond sufficient conditions are the following:\n \n iii) All the eigenvalues of the matrix are positive. This is generally\n      a rather difficult calculation and is usually approximate.\n \n iv) The determinants of all the upper left square submatrices (formed\n                                     as indicated in the diagram at left) are\n                                      positive.  This is probably the easiest method.\n \n  v) The scalar $eT|e$ is positive for all vectors $e$  This is usually\n     taken as the definition of a positive-definite matrix, and explains\n     why a positive-definite matrix yields a quadratic form with a\n     minimum:  the function increases in all directions from $e  0$.\n \n vi) The inverse $G 1 s V$ is positive-definite.\n \n     Now suppose that $G-l$ is calculated for a Newton  step and turns out\nto be non-positive-definite.  In analogy to the one dimen8ional case we\nwould simply take G - I, the unit matrix, and the Newton step would\nbecome a steepest-descent step of arbitrary length, which is probably\nnot so bad an idea and is in fact often don.  But we can do better by\n \n                                - 22 -\n \n \ntrying to make a positive-definite matrix which is as \"close\" as possible\no the unacceptable $G$  The ways in which this can be done depend on\nwhat is \"wrong\" with $G$.  For example:\n \n  i) If all the diagonal elements of $G$ are positive, the off-diagonal\n     elements can simply be set - 0.  The resulting matrix will be better\n     than the unit matrix, since it will at least produce a\n     scale-invariant step and non-arbitrary step length.\n \n ii) If the only thing \"wrong\" with G is that one or more off-diagonal\n     elements of G or G 1 do not satisfy condition (ii) above, just these\n     off-diagonal elements can be set to zero.\n \niii) The matrix $(G +I) 1$ can be used instead of $G 1$, where  is greater\n     than the largest negative eigenvalue of $G$  This requires a large\n     amount of calculation and so is not very convenient, but it is\n     quite appealing since it amounts to taking a step which is intermediate         between a Newton step and a steepest-descent step (for\n     large valueg of  the step becomes short and in the direction of\n     the gradient).\n \n iv) If one or more of the diagonal second derivatives are negative, the\n     non-positive-definiteness can be turned into an advantage, since it\n     indicates a direction (or directions) in which the negative first\n     derivative is increaing in magnitude rather than decreasing.  This\n     suggests an especially fruitful direction for a\nsingle-parameter-variation step which should not only lead to a good\ndecrease of the\n     function value but should also lead more quickly to a region of\n     positive-definiteness.\n \n     Minimization methods based on variations of Newton's method as\n8uggested by the above considerations are usually called quasi-Newton\nmethods.  Many such algorithms have been published and some are quite\n8ucce8sful, but the field is still open for new ideas.\n \n     The principal drawback of such techniques is the repeated evaluation\n and inversion of the second-derivative matrix.  The calculation of\nthe second derivatives usually requires a rather long time, proportional\nto $n2$, and the matrix inversion, although usually faster, increases with\nn like $n$.\n \n                                - 23 -\n \n \n     One of the most interesting results concerning quadratic forms is\nthe basis of a collection of related techniques described in the next\nsections, which do not require explicit repeated evaluations of $G$\n \n \n\\section{Conjugate directions}\n \n     The vectors $di$ and $d$ are said to be conJugate with respect to a\npositive-definite symmetric matrix $A$ if\n \n \n                        $d Ad. = O   for   i  j $.\n                            J\n \n \nIf A is the unit matrix $I$, the conjugate vectors d would be orthogonal\nso conjugacy can be thought of as a generalization of orthogonality. A\nset of n conjugate vectors span an n-dimensional space, and any point\nin the space can therefore be expressed as a linear combination of n\nconjugate vectors.\n \n     Although the matrix $A$ does not uniquely define a set of conjugate\nvectors, such a set can always be constructed by a procedure similar to\nthe Gram-Schmidt orthogonalization method.  Let us start for example\nwith an arbitrary vector $dl$.  Then the vector\n \n \n                                    d Ad\n                      $d2 = Adl -  T   1 d$\n \n                                    dlAdl\n \ncan be seen to be conjugate to $dl$ since the product $dlAd2$ vanishes\nidentically.  The process can then be continued in the same way to\nconstruct a $d3$which will be conjugate to both $dl$ and $d2$,\nand so forth up to $dn$.\n \n     Such vectors become interesting for minimization problems when they\nare conjugate with respect to the hessian (second derivative) matrix $G$\nIn this case a theorem of Fletcher and Reeves7) states that a sequence\nof linear minimizations in each of the n conjugate directions will\nminimize a general quadratic function of n variables.  That this is tr\ncan be seen quite easily as follows.  Let the quadratic function be\n \n \n                      $F(x) s F(O) + gTx + l XTG$\n \n                                 - 24 -\nand the n directions $di$ be conjugate with respect to |$$:\n$diGdj - O, i  j $.\nThen the vectors $x $and $$ can be expressed as linear combinations\n \n                              $g =  C$\nso that the general quadratic becomes\n \n      $F(x) = F(O) + (  cidTJ ( yjdj) + 2 ( yidTi)G ( yjdi)$.\n \nNow  if the last term above is regrouped as a double sum, the terms with\ni $$ j drop out because of the conjugacy condition, so that the whole\nexpression can be simplified as\n \n               $F(x) = F(O) +     Cididjyj + 2  yjdj|d$\n                       i j               i\n \n                $= F(O) +   (bjyi + b;yj2)$\n \nwhere\n                                     $bj =  cidid$\n \nand\n \n                               $bj   dTGd$\n \nare constants. By expressing the quadratic in terms of $y$ instead of $x$\nwe have separated it into a sum of independent one-parameter quadratic\nfunctions.  A minimization with respect to $yi$ (a linear minimization\nalong the direction $di$) will therefore be independent of the minimizations\nalong the other conjugate directions, which demonstrates the validity\nof the theorem.\n \n                                - 25 -\n \n \n     The above theorem tells us what is \"wrong\" with the\nsingle-parameter-variation method:  we should\nbe using conjugate directions rather than\nsimply orthogonal axes.  However, since the construction of conjugate\nvectors seems to require knowledge of the hessian $G$, this does not yet\nhelp very much in practice, for if we knew $$ (and $g$) we could minimize\na quadratic immediately by means of Newton's method, and would not need\nto use n linear minimizations.\n \n     The usefulness of conjugate directions comes from the fact that\nthere are ways of determining such directions implicitly, without firs\nevaluating the entire hessian matrix $$  Of course, by the time all n\nconjugate directions are determined, by whatever method, information\nequivalent to the matrix $G$ must have been determined.  However, by that\ntime considerable minimization may already have been performed, as in\nthe method implied by the following theorem.\n \n     If $xo$ and $xl$ are minimum points in two parallel subspaces, then the\n                                    direction $xl-xo$ is conjugate to any\n      X2                          vector which lies in either\n                 /                 subspace. This can easily be seen in\n              / / / /              two dimensions as illustrated\n                 W /                in the figure at left. Since $xo$\n                                    is a minimum along the direction $$\n                 dl                 the gradient of F at $xo$ must be\n          _                 | X     orthogonal to $dl$:\n \n                         $dlT(g + Gxo) = O$,\n \nwhere $g$ is the gradient at $x = 0$.  Similarly at $xl$:\n \n                          $dl (g + GXl) = | -$\n \nSubtracting the above equations, the first terms drop out and we have:\n \n                          $dlG(xl- xo) = O$,\n \nshowing that $(xl- xo)$ is conjugate to $dl$\n.\n     Unfortunately, extending this algorithm to three dimensions requires\nthree additional minimizations in order that the third direction be\nconjugate to both of the first two, so that convergence for a general\n \n                                - 26 -\n \n \nquadratic in n variables is obtained only after n iterations involving in\nall n(n+ 1)/2 linear minimizations.  Since this is just the number of\nindependent elements in the second derivative matrix, we would be better\noff for quadratic functions to calculate this matrix directly and avoid\nthe linear searches.  On the other hand, for non-quadratic functions the\nconjugate directions method should be much more stable since it proceeds\nby a series of linear searches in independent directions and still\nguarantees convergence in a finite number of steps once a quadratic\nregion is entered.  In addition, this method has the advantage of\nrequiring neither first nor second derivatives of the function.\n(Strictly speaking, then, it should have been discussed in Section 3\nrather than in this section.)\n \n      A disadvantage of the algorithm described above is that for each\niteration, n minimizations are performed in direction $dl$, whilst only\none is performed in direction dn.  This undesirable asymmetry is largely\navoided in a variation due to Powell).\n \n\\section{Conjugate gradients}\n \n      When the first derivatives of the function are calculated, a somewhat\nmore elegant method can be used, known as the method of conjugate\ngradients7). Suppose that the function and its gradient are evaluated\nat two points $xo$ and $xl$, giving differences:\n \n                                                         $x = Xl - XO$\n \n                            $g = gl - go$ .\n \nThen if the function were quadratic with hessian $$we would have\n \n                            $g = G x.$\n \nAny vector $dl$ orthogonal to $g$ would then be conjugate to $x$\n \n                         $dl g = dTlG x = O ,$\n \nwhich immediately suggests a method for obtaining conjugate directions\nwithout knowing $G$, based on the change in gradient along a previous\ndirection.\n \n                                  - 27\n \n \n     In the method of conjugate gradients, successive one-dimensional\nminimizations are performed along conjugate directions with each direction being used only once per iteration.  The first direction is taken\nas $do = -go$, the steepest descent vector at $xo$.  Let the minimum along\nthis direction be at xl where the gradient is $gl$.  Then the next  search\ndirection $dl$, which we want to be conjugate to $do$ must be a linear\ncombination of the only vectors we have at hand, namely:\n \n                             $dl = -gl + bdo $.\n \nThe conjugacy condition is\n \n                        $dlGdo = dTlG(xl - xo) = O$\nor\n                $(-gl + bd)Gdo = (-gTl - bgTo)(gl - go) = O $.\n \nSince $xl$ is a minimum along direction $do = -go$, the direction $go$ is\northogonal to the gradient at $xl$, so that $glgO = 0$.  We are then left\nwith\n \n                               $b =\n                                    gogo$\n \nso that the new conjugate direction is\n \n                      $dl = -gl + () do $.\n                                _ o _ o\n \nThis process can be continued to generate n directions, each one conjugate\nto all the others.  It turns out that the same simple formula holds\nfor all the successive conjugate directions\n \n                  $-i+l -i+l + (8i+l) di$ .\n \n                                 - 28 -\n \n\\section{Variahle metric methods (VMM)}\n \n     In analogy with the methods of differential geometry and general\nrelativity, it is convenient to consider the properties of the function\n$F(x)$as being in fact properties of the space of the variables $x$. We\nhave already made some rudimentary use of this idea when we generalized\nfrom the usual orthogonal coordinate axes to a system defined by axes\npointing in conjugate directions.  We now wish to go further and be able\nto express the properties of the function F geometrically as the properties of the non-Euclidean space of its variables $x.$\n \n     The fundamental invariant in a non-Euclidean space is the squared\ndistance element\n \n                               $d 2   d TAd$\n \nwhere $dx$ is a differential coordinate displacement and A is the\ncovariant\nmetric tensor which determines all the properties of the space under\nconsideration. When $A$is just the unit matrix $I$, the above formula for\n$ds2$ just expresses the Pythagorean theorem for an n-dimensional\nEuclidean\nspace. When off-diagonal elements of $A$ are non-zero and when the\nelements are allowed to vary as functions of $x$, a generalized\nnon-Euclidean space is generated.\n \n     It is easily verified that the second derivative (hessian) matrix $ $\nbehaves under coordinate transformations like a covariant tensor and\nwe will identify it with the metric tensor of our space.  The inverse\n$v = | 1$ is a contravariant tensor and becomes the contravariant metric\ntensor.  (For a discussion of covariant and contravariant tensors, see\nfor example chapter 10 of reference 9.)  This immediately enables us to\nconstruct two scalar (invariant under coordinate transformations)\nquantities:\n$a)    ds  = _d_x _Gd_x$_\n \nis the square of the generalized distance between the point $x$ and the\npoint $x + dx$.  When F is a chisquare function which is minimized to\ndetermine some best parameters x, then the physical meaning of the\ngeneralized distance ds is just the number of \"standard deviations\"\n$x + dx$ is away from $x$.  That is, the use of the metric tensor $G$\nenables\nus to scale the distance $dx$ so that it comes out as a physically (or\n \n \n                               - 29 -\n \n \nstatistically) meaningful invariant quantity instead of being expressed\nin arbitrary units (or a mixture of arbitrary units').\n \nAnd                       $b)    p = g Vg$\n \nis twice the difference between the function value at the point where $$\nand the gradient $g$ are calculated and the minimum of a quadratic form\nwith hessian matrix  $= V l$  That is, p/2 is the expected (vertica]\ndistance to the minimum if the function F were quadratic. This provides\nus with an important scale-free convergence criterion for any method\nwhich provides approximations to $V$and $g$.\n \n     When the function F is quadratic, $G$ is constant everywhere and, in\nthe sense outlined above, this is equivalent to working in a space with\na constant metric.  For real non-linear functions we expect higher-order\nterms to be small but not negligible, so that we can think of working in\na space with a slowly-varying metric tensor. Minimization methods based\non this approach are known as variable metric methods.  They differ from\nthe basic Newton-Raphson method in that the matrix $G$ is not\ncompletely\nre-evaluated at each iteration, but is assumed to be well approximated by\ntaking the $G$ of the previous iteration and applying a correction based on\nnew information from the current iteration.  This correction is known as\nthe matrix updating formula, which in general differs from method to\nmethod.\n \n     Variable metric methods therefore proceed generally by the following\nsteps:\n \n  i) A starting point $xo$ is given, the gradient go at that point is\n     calculated, and some approximation to  $1$, say $VO$, is constructed.\n     The starting $Vo$ may be only the unit matrix, or it may actually be\n     the inverse of the full second derivative matrix.\n \n ii) A step is taken to $xl = xo - Vogo$, which would be the minimum is F\n     were quadratic and if $Vo4 were the true covariance matrix.  Since $$\n     is not the position of the minimum in the general case, it is usual\n     to perform a linear search along this direction, finding the $a$\n     which minimizes $F(xO - aVgO)$.  In either case let the new point be\n     called $xl$ and let the gradient calculated at $xl$ be $gl$.\n \n                                 - 30 -\n \niii) The matrix $V$ is corrected using an updating formula of the form\n                       $Vl = Vo + f(voxoxlgogl) -$\n     Then go is replaced by $gl. xo$ by $xl$, and $VO by Vl$, and steps (ii)\n     and (iii) are repeated until some convergence criteria are satisfied.\n \n     The different methods differ chiefly in the choice of updating\nfunction f, as described in the following sections, and in the extent to\nwhich linear minimizations are necessary.  Less important variations\ninvolve the starting approximation VO and various safeguards against\n\"unreasonable\" steps and non-positive-definiteness as for the Newton\ntechniques.\n \n \n\\section{Davidon's rank-two formula}\n \n     Probably the first -- and perhaps still the best -- variable metric\nmethod was developed in 1959 by Davidon and later published in simplified\nform in 1963 by Fletcher and Powelll|).  Davidon's updating formula for\nthe covariance matrix is the following:\n \n                         $V 1 = V O +  T     T$\n                             y y Voy\n \nwhere the changes in position and gradient on the last step were\n \n \n                               $= Xl - Xo$\nand\n                                $y = gl - go.$\n \nand $Vo$was the previous estimate of the covariance matrix.  This is\ncalled a rank-two formula since the correction $Vl -Vo$ is a matrix of\nrank two in the space of $$ and $Voy$ as can be seen directly by inspection\nof the formula.\n \n     One fundamental requirement of an updating formula is that the new\nmatrix satisfies the relationship\n \n                           VlY  .\n \n \nsince y - G for a quadratic with hessian G.  It is easily seen that\nDavidon's formula satisfies this requirement:\n \n \n                                 - 30\n \n \niii) The matrix V is corrected using an updating formula of the fcrm\n                       Vl = Vo + f(voxoxlgogl) -\n     Then go is replaced by gl, xo by xl, and VO by Vl, and steps (ii\n     and (iii) are repeated until some convergence criteria are sati\n \n     The different methods differ chiefly in the choice of updating\nfunction f, as described in the following sections, and in the exten\nwhich linear minimizations are necessary.  Less important variations\ninvolve the starting approximation VO and various safeguards against\n\"unreasonable\" steps and non-positive-definiteness as for the Newton\ntechniques.\n \n \n4.8  Davidon's rank-two formula\n    _\n \n     Probably the first -- and perhaps still the best -- variable me\nmethod was developed in 1959 by Davidon and later published in simpl\nform in 1963 by Fletcher and Powelll|).  Davidon's updating formula\nthe covariance matrix is the following:\n \n \n                        Vl = V| +  T     T\n                              y y Voy\n \n \nwhere the changes in position and gradient on the last step were\n \n                               = Xl - Xo\nand\ny = gl - go.\n \nand Vo was the previous estimate of the covariance matrix.  This is\ncalled a rank-two formula since the correction Vl -Vo is a matrix o\nrank two in the space of  and Voy as can be seen directly by insp\ntion of the formula.\n \n     One fundamentat requirement of an updating formula is that the\nmatrix satisfies the relationship\n \n                              VlY_ ,\n \nsince y  G for a quadratic with hessian G.  It is easily seen tha\nDavidon's formula satisfies this requirement:\n \n \n$CVlY = [Vo    T$\n          j    V\n \n   $= Voy + -- Y _ oW o_y$\n \n                                     $y    _y V o _y$\n \n                       $= voy +  - voy =  -4\n \n \n \n     An unfortunate feature of the Davidon algorithm is the need to\nperform at each iteration a linear minimization along the direction\ngiven by a Newton step, $-Vg.$  This linear search step is, however,\nnecessary in order to assure convergence for general functions. Fletcher\nand Powell showl|) that if the starting approximation to $V$ is\npositive-definite, then\n$V$will remain positive-definite after all updatings, but\nthey have to use the fact that each iteration is a linear minimization,\nthat is\n                                              $glVogo = O $\n \n     It can be shown that this method is quadratically convergent, at\nmost n iterations (n linear searches and n gradient calculations) being\nrequired for an n-dimensional quadratic form.\n \n \n\\section{The rank-one formula}\n \n     In an effort to avoid the linear minimizations required by Davidon's\nalgorithm, several workers have independently developed an interesting\nupdating formula of rank one.  In this case Davidon in 1968 was the\nfirst\nto publish an algorithmll) based on the formula, and Powelll2) has\nsummarized the properties of this formula and of algorithms based on it\n \n     The rank-one updating is:\n \n                  $Vl  Vo + (- VoY      Voy)T4\n                                     y ( - VoY)\n \nIt can be shownl2) that this is the only formula of rank two (or less)\nfor which not only Vly =  but:\n                           $Vl-y$\n \n \n                                 - 32 -\n \n \nwhere $i$ and $Yi$are the step and gradient changes at any previous\niteration.  This is known as the hereditary property, since $Vl$ can be\nsaid to\ninherit the fundamental property $Vy =$  with respect to all previous\niterations (up to n).\n \n     The hereditary prcperty assures that after n iterations, $Vl$ will be\nthe true covariance matrix if F is quadratic, no matter what steps were\ntaken (almost), so that if Newton steps are taken, convergence for a\nquadratic function is assured after n iterations, without the need for\n.linear mlnlmlzations..\n \n     In addition, the rank-one formula is symmetric, in the sense that\nthe expression for $Vll$ in terms of $Vol$ is the same as that for $Vl$ in\nterms of $Vo$ provided $$ and $y$ are interchanged. The meaning of this\nsymmetry property will be discussed in the next section.\n \n     But, as nothing is perfect, so the elegance and mathematical beauty\nof the rank-one formula hide a number of numerical and practical difficulties which can make it highly unstable when applied to a general\nfunction.  In particular, if the vector $y$ happens to be orthogonal to the\nvector $(- VOy)$, the denominator goes to zero in the updating formula,\nand an unbounded correction is possible.  Since these vectors may be\northogonal, even for a quadratic function, the problem of numerical\ninstability is a serious one.\n \n     Moreover, the matrices $Vl$ do not really converge to the true covariance matrix in the usual meaning of the term convergence.  Although\nit is true that $Yl$ will be equal to the true covariance matrix at the\nn$th$ step for a quadratic function (barring numerical difficulties), the\nintermediate matrices $V$ may vary wildly from step to step, so that on\nany particular iteration $Vl$ may be a rather poor approximation.  This is\nespecially dangerous when the function is not quadratic, since the large\ncorrections necessary in later iterations will generally not compensate\nproperly the fluctuations in early steps.  Also, there is no guarantee\nthat intermediate matrices will remain positive-definite, and hence no\nguarantee of a reduction in the value of F at each step, even for a\nquadratic F.\n \n     All these difficulties can, of course, be overcome by programming\nenough safeguards into the algorithm, but this can only be done at the\n \n                                - 33 -\n \nexpense of efficiency and sometimes only by abandoning temporarily the\nupdating formula itself, which makes it lose some of its appeal.\nDifferent approaches are possible depending on whether it is considered\nimportant to maintain positive definiteness as in the Davidon\nalgorithmll), or important not to abandon the exact rank-one formula\nas in Powell's methodl2).\n \n \n\\section{Fletcher's unified approach to VMM}\n \n     The existence of two different updating formulas with very different\nproperties generated a lot of interest in variable metric methods (VMM)\nduring the years 1967-1971, since it showed VMM to be very promising\nand left many questions unanswered, such as:\n \n  i) How can it be that the rank-one and rank-two formulas have such\n     different properties?  What is the relationship between them?\n \n ii) Is there a way to combine the best properties of both formulas?\n \niii) Are there other good formulas?  Is it possible to define a class\n     of \"admissible\" formulas?\n \n     A certain understanding of the above problems has recently been\nmade possible by the work of a number of people. In particular, a recent\npaper by Fletcherl3) presents a unified approach to VMM, which will be\ngiven here.\n \n     Recall that the rank-one equation is symmetrical (in a sense defined\nin Section 4.9), but as we shall now see, the rank-two formula is not.\nIndeed the asymmetry suggests a way to construct a possible third\nformula\nby taking the \"mirror image\" of the rank-two formula.  The basic idea is\nthat a new formula should satisfy the fundamental relationship\n \n                           $VlY =  .$\n \nand therefore its inverse should satisfy\n \n                                $V$\n \nWe can indeed write down the updating formula for $ll$ which\ncorresponds to the rank-two formula for $Vl$:\n \n                 $V           Vnl rI |  + Y _ Y$\n \n \n                                 - 34 -\n \nThis matrix $Vll$ can now be thought of as a mapping from  $) y$ since\n$y = Vll$.  If we interchange $y $and $$ in the formula, it will then give\na mapping from $y  $, thereby producing a new updating formula where\n$Vly = $.  The new duaZ formuZa will be just\n \n \n                    $    '    yT`   '   yT   T\n                     V          T  Y| I    T      T\n                           Y   Y,  Y$\n \n \nIf we try this trick with the rank-one formula, we just get the same\nrank-one formula back again, since it is symmetric in this sense, or\ndual to itself.  But with the rank-two formula, the process of inverting\nand interchanging yields a new formula, also of rank-two, which is also\na valid updating forr__ula in the sense that it gives rise to a quadratically convergent VM1 algorithm.\n \n     Now we go further and consider the class of formulas which includes\nboth rank-two and dual formulas as special cases.  Let us introduce the\nnotation\n                   $Vl = T(Vo)$   for the rank-two formula ,\nand\n                   $Vl = D(Vo)$   for the dual formula ,\n \n \nand consider the class of updating expressions as introduced by\nFletcherl 3):\n \n                         $V,        ) T +  (D)$\n \n where  is some parameter which determines the exact formula.  Broydenl4\nusing a somewhat different notation, has also considered the same class\nof formulas.]\n \n     It then turns out that the rank-one formula is also in this class,\n with\n                                          Ty\n                      $ (rank-one)\n                               ( y y_ Voy-)$\n \n     Having now constructed a wide class of updating formulas, which in\nfact includes all formulas known to the author, it will prove interesting\nto consider their properties as a function of the generating parameter $$\nProbably the most important property, and the only one we will consider\nhere, is that of monotonic convergence of V toward the true covariance\n \n \nmatrix for a quadratic function.  [This is called Property 1 in Fletcher's\npaperl3) which should be consulted for details of the definition an for\ntheorems concerning it.]  The use of an updating formula with this\nproperty will guarantee an improvement in the approximation y at each\niteration (for a quadratic function).\n \n     Any formula V with  in the interval [0,1] possesses the monotonic\nconvergence property.  Such a formula is said to belong to the convex\nclass of formulas. For any $V$ with  outside the range [0,1], there\nexists some quadratic function for which V diverges from the true\ncovariance matrix.\n \n     From what we have already seen about the rank-one formula, it i\nnot surprising to find that it does not belong to the convex class.\nSince  $y > O$ for any step which is an improvement, and since $yTvoy$\nif $VO$is positive-definite, it can be seen immediately from inspection\nof the equation for (rank-one) that it must either be less than zero\nor greater than one.\n \n     Ihe aboe considerations lead Fletcher to propose a new algorithm13)\nwhich is probably the most elegant and powerful of any VMM algorithm\nBasically, he uses the genera] updating formula $V$, with the value $o$\nchosen according to the following scheme:  If ,(rank-one) $< 0$#, set $$\ncorresponding to the usual  rank-two formula.  If $$ (rank-one) > 1, set\n$= 1$, corresponding to the dual formula. In this way, one always uses\na formula in the convex class, and chooses that one which is \"closest\"\nto the rank-one formula.  It seems that the linear searches can then be\neliminated and replaced simply by Newton's steps, unless the function\nis highly non-quadratic.  The latter condition can easily be detected by\ncomparing the actual improvement with the expected improvement at\neach iteration.\n \n \n\\chapter{SPECIALIZED TECHNIQUES}\n \n          All the methods outlined so far in these lectures are of rathe\n     general applicability, the only assumption being -- for some methods--\n     a predominantly quadratic behaviour in the immediate vicinity of the\n     mihimum. In order to develop more powerful methods than those already\n     presented, we will have to give up some of this generality and exploit\n     particular features of the functions to be minimized. In this section\n \n                                 - 36 -\n \nwe discuss a few specialized techniques which are still of rather wide\napplicability in the sense that most functions of physical interest\nfall in one or more of these classes.\n \n]section{Chisquare minimization}\n \n     Probably the most common application of minimization in scientific\nresearch is in least squares fitting, where the function to be minimized\nis the sum of squares of deviations, between measured values and predictions of a model containing variable parameters:\n \n                          K           K   Yk - Tk(x) 2\n                $ F(_x) =   fk(_x) =$\n \n                     k=l         k=l `         '\n \nwhere $Yk$ and $k $are measured values and errors, and Tk(x) are the values\npredicted by the model, depending on some parameters $x$.  Minimizing F\nthen yields best values (estimates) of the n parameters $x$, based on K\nmeasurements $Y$ with random errors $$, where K must be greater than or\nequal to n, and is usually much greater than n.\n \n     Let us now consider the second derivative matrix for $F(x)$, expressed\nin terms of the individual $fk(x)$:\n \n             $   2F a a 2\n              ax ax  = axi ax   fl;$\n \n                                        $   a        afk\n                    = aX  2fk aX$\n \n                              k\n \n \n                  $=   2 aXk aXk +  2fk ax ax\n                           k      i       k        1  J$\n \n \nIn the above r.h.s., it is usual to make the approximation that the\nsecond sum, involving second derivatives, is small compared with the\nfirst term involving products of first derivatives.  This is called\nlinearization.  [Note that it is the mode1, T$(x)$ that is being linearized,\nnot the function F$(x).$]  In the important special case of linear least\nquare, the second sum is exactly zero, so that F $(x)$is quadratic, and\nthe whole minimization problem reduces to the inversion of the above\nmatrix $a2F/axjaxi$ (i.e. the taking of one Newton step).\n \n \n     In the more general case of non-Zinear Zeast squares, the\nlinearization approximation consists in taking\n \n                     $a2F        afk afk\n                     ax ax   ax ax -$\n \nThis has the advantage of being easy to calculate and, moreover, it is\nalways positive-definite (under rather weak conditions such as the\nexistence of the derivatives, and provided it is non-singular). In fact\nin many cases the use of the above approximation in computing Newton\nsteps is actually more effective than using the exact second derivative\nmatrix because of the positive defiteness.  Of course it must be\nremembered that the covariance matrix obtained by inverting this\napproximate\nmatrix does not in general converge to the true covariance matrix\neven though the minimization  based on it may converge to the true\nminlmum.\n \n\\section{Likelihood maximization}\n \n     An increasingly important alternative to the least squares method\nin data fitting is the method of maximum likelihood.  In this case the\nfunction to be minimized is of the form\n \n                         $ F(x) = -  ln fk(X) ,\n                                       kSl$\n \n \nthat is, a sum of logarithms.  Here again, an approximation for the\nsecond derivative matrix can be found which involves only products of\nfirst derivatives:\n \n \n                       $ S - axi ax   ln fk$\n \n                        $ a l k\n                        axi  f k axj$\n \n                            $1 k afk 1 a2fk\n                            k aXi axj     fk aXiaxi $ -\n \n                                 - 38 -\n \n \nAs with least squares, we can neglect the second sum, involving second\nderivatives.  In the case of the likelihood function, the second derivatives\nof f are never exactly zero over any finite range (exactly linear\nmaximum likelihood does not exist, essentially because the likelihood\nfunction must be normalized so that its integral over the space of\nmeasurements is independent of the parameters x).  However, the\napproximation\n \n                        $a2F        1 afk afk\n                         ax.ax.  k2 ax. ax.\n                                   k$\n \n \nhas the same advantages as in the non-linear least squares case, namely\nspeed of calculation and assured positive-definiteness.\n \n \n5.3  Models with separable computing\n \n     It often happens that the computation of the function value F can\nbe arranged so that large parts of the calculation depend on only a fe\nof the variable parameters x.  These parts will then remain unchanged\nthe corresponding parameters have not changed since the previous funct\nevaluation.  An important special case of this is when the calculation\ncan be separated into n pieces, each depending on only one parameter.\n \n     Whenever the computing is separable in the above sense, large por\ntions of the computation may be avoided by testing which parameters ha\nnot varied since the previous function call, and using the previous\nresults of the corresponding sub-calculation when appropriate.  The ov\nall saving in computer time will then depend, of course, on the minimi\ntion method used, and some otherwise inferior methods, such as single-parameter variation, may become relatively efficient because of the ti\nsaved in computing the function.\n \n     In particular, the cost of computing derivatives by finite differences will generally be much lower when the computing is separable,\nand in the extreme case of complete separability, all n first derivati\nmay be computed in a time comparable with that of one full function\nevaluation.\n \n                 Seen Rejected  Percentage\n \nCharacters       1559        4   99.74\n \n                                - 39 -\n \n \n5.4  Sets of related problems\n \n     Many applications involve a series of minimizations for which t\nfunctions involved are closely related.  For example, in determining\nconfidence intervals for a parameter y in a statistical problem inva\nadditional parameters x also to be estimated, one determines the cuc\np(y) traced by the minima of the chisquare function F with respect t\nfor different values of y:\np(y) = min F(x,y) .\n \n \nA series of points on this curve is then determined by fixing y at\nseveral different values, and for each of these, minimizing F as a f\ntion of x.  Clearly then, information from the first minimization ca\nused as a starting point for the second, and then extrapolated to gc\nstarting point for the third, and so on.  In particular, one does nc\nexpect the covariance matrix to vary considerably from point to poir\nso this is an especially valuable piece of information to carry ove\none problem to the next.\n \n     Similarly, if an experiment is repeated with new, independent,\nidentically distributed data, the minimizations involved in the datc\nanalysis can be speeded up by supplying covariance matrices from th\nanalysis of the first experiment.\n \n \n \n\\chapter{LOCAL AND GLOBAL MINIMA}\n\\section{The problem of multiple minima}\n     All the methods presented so far have been designed to find a local\nminimum, without any consideration of whether or not other local minima\nexist, or whether the minimum found is actually the global minimum.\nIf the function has more than one local minimum, there is not even any\nguarantee that these methods will find the minimum closest to the\nstarting point, let alone the global minimum.  In fact, it is usually\nassumed, when using these algorithms, that the function is unimodal\n(has one minimum) in the region of interest likely to be explored\nduring the minimization.\n \n \n                                 - 40 -\n \n \n     Whenever the function may have more than one local minimum, new\nproblems arise in addition to the problem  of local minimization. First\nof all, the user must decide what he wants to know about the function.\nThe following four possibilities are the most common and will be\ndiscussed here:\n \n  i) it is sufficient to know the location of any one local minimum;\n ii) only the global minimum is of interest;\n iii) only one minimum is of interest (the \"physical solution\"), but it\n need not be the global minimum; or\n iv) all local minima, including the global one, must be found and\n catalogued.\n \n     The first possibility, (i), is quite rare, but is easy to deal with,\nsince any local minimization routine is sufficient.\n \n     Possibility (ii) is much more common, particularly in system\noptimization where the cost must be the smallest possible, not just\nsmall compared with other near-by solutions.  Several methods exist for\nfinding global minima, of which two will be discussed in the next sections.\n All such methods suffer from the absence of a stopping rule:\neven if the global minimum is found there is no way of recognizing it\nunless the function is known to be bounded and has reached its lower\nbound.\n \n     Possibility (iii) often arises in scientific research where the\napproximate values of some parameters are known in advance and one seeks\na solution not too far from these values, corresponding to \"the right\nvalley\" where the function may have several faraway valleys which may\nbe deeper.  The usual technique for making sure of staying in the right\nvalley is first to fix the approximately known parameters at their\nassumed values and minimize with respect to all other variables, then\nstarting from this point minimize in the entire variable space.\n \n     Possibility (iv), of having to find and record all local minima,\nis the most difficult of all.  It arises, for example, in energy-dependent\nphase-shift analyses where all \"solutions\" are recorded at each energy,\nand a continuous set of solutions is sought, one at each energy, which\nhave a smooth energy dependence. Although the techniques described below\n \n \n \n \nmay help in this problem, no exhaustive method is known to the author\nexcept for the prohibitive one of using many starting points equally\nspaced on an n-dimensional grid.\n \n \n\\section{The Gelfand algorithm}\n \n      Relatively few minimization methods are specifically designed for\nnon-local search in many parameters. Probably the most successful of\nthe ad hoc stepping methods is that of Gelfandl S) . It is non-local\nbecause it provides a natural way to allow for function increases as\nwell as decreases in any one step, while tending generally to decrease\nthe function value .\n \n      The procedure is as follows. From the starting point $xo$, a local\nminimization is begun (for example along the gradient) until the function differences between steps become small (at the point $aO$). Then,\n \n                        X 1\n                          1      ?\n \n                  aO              a   X\n                                 _ 2     _3\n \n \n \ngoing back to the starting point, a \"long\" random step is taken to the\npoint $xl$, and another rough local minimization is performed to reach the\npoint $al$(see figure above). Then the so-called \"precipitous step\" is\ntaken along a line from $aO$ to $al$, some distance past $al$ to $x2$.\nThen from '$X2$ another rough local\nminimization is performed, yielding $a2$, and another\nprecipitous step is taken from $al$ past $a2$ to $X3$  and the search\ncontinues in this way.\n \n \n      The choice of the \"precipitous step\" length is important in determining whether the method will \"roll over small ridges, but skirt a high\nmountain\", as its authors say it should. But no precise way is given,\nexcept that \"the choice of the length of the precipitous step is carried\nout experimentally (by trials) and it constitutes an important\ncharactistic of the function\".\n \n \n \n                                - 42 -\n \n \n     Moreover, there is no stopping rule, since the method is essentially\nsearching rather than converging.  In practice one usually stops after\na given length of computer time, but one would also stop if the program\nwent around in circles repeating itself (which is very possible but not\nso easy to detect) or if a predetermined \"acceptably small\" function\nvalue was attained.  This problem of stopping seems to be common to all\nnon-local minimization methods.\n \n \n\\section{The Goldstein-Price method}\n .\n \n     Goldstein and Pricel6) have proposed an elegant yet simple method\nfor seeking other local minima after one local minimum has been found\nIt is based on a consideration of the analytic (Taylor series) properties\nof the function.  Let us assume that the function can be represented as\na Taylor series about a local minimum xl, where the first derivatives\nvanish:\n \n                $F(x) = F(xl) + 2 (x - xl) G(x -xl) + h.t.$ .\n \nNow the higher terms (h.t.), involving third and higher derivatives, are\nimportant since these are the terms that will give rise to other local\nminima.  In fact, we seek a way of transforming the function so that only\nthe higher terms remain.  Such a transformed function is $Fl$ such that:\n \n \n                           $2(F(x) - F(Xl))\n            Fl(xl,_x) =        T         = 1 + h.t. .\n                          (X -Xl) G(x - xl)$\n \n \nBy means of this transformation, we have \"removed\" the minimum at $xl$\nand the way is cleared to search for other minima generated by the higher\nterms of the expansion about xl.  The method therefore consists of\nseeking a local minimum of the function $Fl4  (It is required to know the\nsecond derivative matrix $G4at the local minimum $xl$.)  Since the\nquadratic form $(x -xl) G(x - xl)$\n is always positive for positive-definite $G$, th\nfunction $Fl$ will become negative as soon as an improvement on $xl4 is\nfound.  Then starting from this improved point, the original function F\ncan be minimized locally to yield a new, improved local minimum of F\n \n     If the minimum value found for Fl is positive, then it may correspond to a new local minimum of F, but not an improvement over $xl$.\n \n \n                               - 43 -\n \n \nIn this case the procedure may be continued from this new point, forming\na new function $F2$, related to $Fl4 just as $Fl$ was related to F. As usual,\nno stopping rule is given by the theory.\n \n     The method seems to work in practice, although experience with it\nis limited and no conditions are known under which it is guaranteed to\nwork.  It is appealing for reasons of its elegance and simplicity, and\ncould prove to be an important tool in global minimization.\n \n \n \n\\chapter{CONCLUSION}\n\\section{Global strategy}\n     After having studied the properties of many minimization methods,\nwe are finally faced with the problem of choosing one of them.  As we\nhave already stated, no one method can be optimum in the sense of being\nbest for all functions.  And even for one given function, it is unlikely\nto find a method which works well in all regions, far from the minimum\nas well as near.\n \n     All this suggests that we should try to tailor the programs to our\nfunction's needs.  If we expect to be doing a lot of minimization,\nseveral programs should be prepared, based on different methods with\nproperties suited to different kinds of functions.  Then a decision as\nto which method to use would depend on a consideration of the particular\nfunction to be minimized.  A decisio tree, enabling the user to choose\na method for his function, has been given in the review of Fletcher\nCertainly no two experts would agree on the details of such a logic\ndiagram, since everyone has his own personal preferences in this field,\nbut the general idea is a good one and indicates a way in which a\nroutine could be chosen.\n \n     In large problems, the properties of the function may change\ndrastically from one region to another, so that a good method far from\nthe minimum, for example, may converge very slowly in the vicinity of\nthe minimum.  In particular, the simplex and Rosenbrock methods are\nquite insensitive to the exact shape of the function, and so should\nwork as well in non-quadratic regions as in quadratic regions.\nHowever, once the region of the minimum is reached, the function should\n \n                               _ 44 _\n \n \nbe reasonably quadratic so that a method with quadratic convergence\nshould certainly be used.\n \n     With the present state of the art, the decision as to which method\nto use, or when to change methods if more than one is used, must be\nbased on a priori knowledge of the function.  Ultimately one could\nimagine designing a super-algorithm which could examine the function or\nfollow the progress of the minimization and choose the best method on\nthe basis of what it finds out, rejecting those whose progress is too\nslow in favour of more suitable techniques.  At present this is sometimes\ndone, but only in a most rudimentary way, in the sense that some\nalgorithms can tell when they are going astray and can signal this to a\nmain program which can then try a safer method.\n \n \n7.2  Computer programs\n \n     The purpose of this last section is not to suggest particular\nprograms which may be available for general use, but rather to indica\nin very general terms several ways in which such programs may be org2\nnized.  The implementation and use of the techniques described in thc\nlectures implies their being programmed for high-speed computers, wit\nthe program structure depending again on the nature of the problem tc\nsolved.\n \n     One traditional program structure is that of the Zarge autonomoz\nprogro which as far as possible takes care of all details of initia]\ntion, input-output formats, error returns, and other organizational\nThe function to be minimized is submitted by the user in the form of\nsubroutine which returns a function value F on each call, depending\nthe values of the formal parameters x.  Another formal parameter is\nflag informing the function subroutine when the first and last calls\nbeing made, so that the subroutine may do any private initialization\nprinting of final results if necessary.  The starting values and ste\nsizes of the function parameters are usually read in by the main pro\non data cards, and there may be more data cards specifying which of\nseveral options are requested if the main program is capable of perf\na variety of different tasks.  Programs organized in this way are po\nin laboratories where the principal task to be performed in a typica\n \n                 Seen Rejected  Percentage\n \nCharacters       1792        2   99.89\n \n \njob is a single large minimization problem, for then the main program\ncan easily contain logic permitting change-over from one algorithm to\nanother in case of failure to converge, and can contain many other\nfeatures which relieve the user of a large amount of trivial \"house-keeping\" work.\n \n     A different approach is that of the smaZZ minimizing subroutine,\ndesigned to save memory space and to allow the user maximum flexibili\nIn this case the user must write the main program which calls the\nminimizer, as well as the function subroutine called by the minimizer\nIn return for the extra work, he then has complete control over the\norganizational details, and the minimizer is more likely to be machin\nindependent when available in a higher-level language such as FORTRAX\nThis approach is especially adapted to jobs consisting of a series of\nmany related minimizations, or when the minimization is only a small\nintermediate step in a larger calculation.\n \n     A more recent development is that of interactive minimization,\nwhere the user can follow the progress of the search by means of a CF\nscreen or other output device, and modify the search procedure accordingly.  Although this appears a potentially powerful technique, i\nis rather expensive in terms of real-time computer resources, and I c\nskeptical about its ultimate efficiency for two reasons:\n \n  i) Computer output devices and human geometric insight are both\n     notoriously poor in spaces of high dimensionality, and cases of\n     many variables are usually the only ones difficult enough to\n     warrant the use of expensive computing techniques.\n \n ii) If a human is able to direct a many-dimensional search more\n     efficiently than a computer, it is probably a sign of deficienc\n     in the numerical methods used by the computer rather than brilli\n     insight on the part of the human.\n \n     However, interactive minimization is still relatively new, and\ncould prove very useful for some problems, including the development\nnew  algorithms for off-line minimization programs.\n \n                 Seen Rejected  Percentage\n \nCharacters       1676        1   99.94\n \n                           - 46 -\n                              \\chapter{REFERENCES}\n \n(References 18-31 are  not referred to specifically in the text, but are\nadded as usefuZ general  references.)\n \n \n l)  J. Kowalik and M.R. Osborne, Methods for unconstrained optimization\n        problems (American Elsevier Publishing Co., Inc., New York,\n        1968) .\n \n 2) H.H. Rosenbrock, An automatic method for finding the greatest or\n        least value of a function, Comput. J. 3, 175 (1960).\n \n 3)  R. Hooke and T.A. Jeeves, Direct search solution of numerical an\n        statistical problems, J. Assoc. Comput. Mach. 8, 212 (1961).\n \n 4)  L.C.W. Dixon, Non-linear optimization  (English Universities Press,\n        London, 1972) .\n \n S)  J.A. Nelder and R. Mead, A simplex method for function minimization,\n        Comput . J. 7, 308 (1965) .\n \n 6) G.W. Stewart, A modification of Davidon's method to accept difference approximations of derivatives, J. Assoc. Comput. Mach\n        14, 72 (1967).\n \n 7)  R. Fletcher and C.M. Reeves, Function minimization by conjugate\n        gradients, Comput . J . 7, 149 (1964) .\n \n 8) M.J.D. Powell, An efficient method for finding the minimum of a\n        function of several variables without calculating derivatives\n        Comput . J. 7, 155 (1964) .\n \n 9) L.D. Landau and E.M. Lifshitz, The classical theory of fields\n        (Addison-Wesley Publ. Co., Inc., Reading, Mass., 1951) .\n \n10)  R. Fletcher and M.J.D. Powell, A rapidly converging descent method\n        for minimization, Comput. J. 6, 163 (1963) .\n \n11)  W.C. Davidon, Variance algorithm for minimization, Comput. J. lC\n        406 (1968).\n \n12) M.J.D. Powell, Rank one methods for unconstrained optimization,\n        appearing in Integer and Non-linear Programming, J. Adabie\n        editor (North-Holland Publ. Co., Amsterdam, 1970) .\n \n13) R. Fletcher, A new approach to variable metric algorithms,\n        Comput. J. 13, 317 (1970).\n \n14) C.G. Broyden, Quasi-Newton methods and their application to function\n        minimization, Math. Comput. 21, 368 (1967) .\n \n15)  I.M. Gelfand and f.L. Tsetlin, The principle of non-local search\n        in automatic optimization systems, Soviet Phys . Dokl . 6, 192\n        (1961) .\n \n \n                              - 47 -\n \n \n16) A.A. Goldstein and J.F. Price, On descent from local minima, Math.\n        Comput . 25, 569 (1971) .\n \n17) R. Fletcher, Methods for the solution of optimization problems,\n        Comput. Phys. Commun. 3, 159 (1972).\n \n18)  M.J.D. Powell, Minimization of functions of several variables,\n        appearing in Numerical Analysis, an Introduction, J. Walsh\n        editor (Academic Press, Inc., New York, 1966) .\n \n19)  M.J. Box, D. Davies, and W.H. Swann, Non-linear optimization\n        techniques (Oliver and Boyd, Edinburgh, 1969).\n \n20) D.J. Wilde and C.S. Beightler, Foundations of optimization\n        (Prentice-Hall, Inc., Englewood Cliffs, N.J., 1967) .\n \n21) M.J. Box, A comparison of several current optimization methods\n        and the use of transformations in constrained problems, Comput. J.\n        9, 67 (1966) .\n \n22) R. Fletcher, Function minimization without evaluating derivatives\n        a review, Comput . J . 8, 33 (1965) .\n \n23) R. Fletcher (editor), Optimization - Symposium of the Institute of\n        Mathematics and its Applications  (Academic Press, Inc. ?\n        New York, 1969).\n \n24) H.A. Spang, A review of minimization techniques for non-linear\n        functions, SIAM Rev. 4, 343 (1962).\n \n25) M.J.D. Powell, A survey of numerical methods for unconstrained\n        optimization, SIAM Rev. 12, 79 (1970) .\n \n26) M.J.D. Powell, A method for minimizing a sum of squares of non-linear functions without calculating derivatives, Comput. J.\n        303 (1965).\n \n27) J. Greenstadt, On the relative efficiencies of gradient methods,\n        Math. Comput . 21, 360 (1967) .\n \n28) R.W.H. Sargent and B.A. Murtaugh, Computational experience with\n        quadratically convergent minimization methods, Comput. J. 13\n        185 (1970).\n \n29) J.D. Pearson, Variable metric methods of minimization, Comput. J.\n        12, 171 (1969).\n \n30) R. Bass, A rank two algorithm for unconstrained minimization,\n        Math . Comput . 26, 129 (1972) .\n \n31) A.A. Goldstein and J.F. Price, An effective algorithm for minimization,\n        Nurm.  . Math. 10, 184 (1967) .\n \n \n                                - 48 -\n \n \n\\chapter{APPENDIX}\n \n \n \\chapter{SOME SAMPLE PROBLEMS FOR MINIMIZATION ROUTINES}\n \n \n     We assemble here a collection of test problems which found to be\nuseful in verifying and comparing different minimization routines.\nMany of these are standard functions upon which it has become\nconventional to try all new methods, quoting the performance in the\npublication of the algorithm.\n \n \n\\chapter{Rosenbrock's curved valley}\n  .\n \n \n                  F(x,y)  lOO(y - x2)2 + (1 - x)2\n \nstart point:              F(-1.2,1.0) = 24.20\nminimum:                  F(l.O,l.O)  = O .\n     This narrow, parabolic valley is probably the best known of all test\ncases.  The floor of the valley follows approximately the parabola\ny = x2 + 1/200, indicated by the dashed line in the diagram.  In the\ncross-hatched area above the dashed line, the covariance matrix is not\npositive-definite.  On the dashed line it is singular.  Stepping methods\ntend to perform at least as well as gradient methods for this function.\n \n[Reference:  Comput. J. 3, 175 (1960).]\n \n \n \n                                 - 49 -\n \n \n\\section{Wood's function of four parameters}\n \n \n  $F(Wx,y,z) = lOO(x -w2)2 + (w _l)2 + 9o(    2)2\n               + (1- y)2 + lO.l[(x -1)2 + (z -1)2] + 19.8(x -l)(z - 1$\nstart point:            $F(-3,    3,-1) = 19192$\nminimum:                $F(l,l,l,l)     = O$.\n \n     This is a fourth-degree polynomial which is reasonably well-behaved\nnear the minimum, but in order to get there one must cross a rather flat,\nfour-dimensional \"plateau\" which often causes minimization algorithm to\nget \"stuck\" far from the minimum.  As such it is a particularly good\ntest of convergence criteria and simulates quite well a feature of many\nphysical problems in many variables where no good starting\napproximation is known.\n \n \n[Reference:  Unpublished.  See IBM Technical Report No. 320-2949.]\n \n \n\\section{Powell's quartic function}\n \n \n     $F(w,x,y,z) = (w + lOx)2 + S(y- Z)2 + (X - 2y)4 + lO(w -z)4$\nstart point:               $F(3,-1,0,1) = 215$\nminimum:                  $ F(O,O,O,O)  = O$ .\n \n     This function is difficult because its matrix of second derivatives\nbecomes singular at the minimum.  Near the minimum the function is given\nby $(w +lOx)2 + S(y _Z)2$ which does not determine the minimum uniquely.\n \n[Reference:  Comput. J. 5, 147 (1962).]\n \n\\section{Fletcher and Powell's helical valley}\n \n \n          $F(x,y,z) = lOOz -10(X,y)2 + (x2 + y2 _ l)2 + z2$\nwhere              $ 2(x,y) = arctan (y/x) for x > O$\n                       $=  + arctan (y/x) for x< O$\n \nstart point:               $F(-l,O,O) = 2500$\nminimum:                    $F(l,O,O) = O$ .\n \nF is defined only for -0.25 < $$ < 0.75.\n \n                                - so -\n \n \n     This is a curved valley problem, similar to Rosenbrock's, but in\nthree dimensions.\n \n[Reference:  Comput. J. 6, 163 (1963).]\n \n \n\\section{Goldstein and Price function with four minima}\n \n \n     $F(x,y) = (1 + (x + y + 1) 2 * (19-14x + 8x2 _ 14y + 6xy + 3y2)\n             * ( 30 + (2x _ 3y) 2 * (18-32x + 12x2 + 48y - 36xy + 27y2$\nlocal minima:         $F (1. 2, O . 8) = 840\n                       F(1.8,0.2)   = 84\n                       F(-0.6,-0.4) = 30$\nglobal minimum:        $F (O ,-1. 0) = 3$\n \n     This is an eighth-order polynomial in two variables which is well\nbehaved near each minimum, but has four local minima and is of course\nnon-positive-definite in many regions.  The saddle point between the two\nlowest minima occurs at F(-0.4,-0.6) = 35, making this an interesting\nstart point.\n \n[Reference:  Math. Comp. 25, 571 (1971).]\n \n \n \\section{Goldstein and Price function with many minima}\n \n \n    $F(x,y) = exp 2 (x2 + y2 _ 25)2 + sin4 (4x  3y)  +  1  (2     1  )2$\n \n \n gl obal minimum:             F ( 3, 4 )\n      This function has \"many\" local minima.\n[Reference:  Math. Comp. 25, 571 (1971).]\n \n \n\\section{Quadratic function in four parameters}\n \n \n \n        {F(x,y,z,w) = 7l (21x2 + 20y2 + 19z2 _ 14xz - 20yz) + w2}\n \n                                  - 51 -\n \nminimum:                    F(O,O,O,O) = O\n                            4 1 2\n                             1 5 3\ncovariance matrix:      $             6$\n \n \n                                O O O\n \n \n \n     Except for the reasonably strong parameter correlations, this function\nposes no special problem to any minimization routine.  But the\nauthor has found it useful in debugging programs based on quadratically\nconvergent methods, since these programs should minimize the function\nexactly in one iteration.  It is also used to check the calculation of\nthe covariance matrix.\n \n     A variation consists of adding |$x|$ - 1 whenever $|x| >$1, and\nsimilarly with the other variables.  This introduces in a reasonably\nsmooth way terms which alter the quadratic behaviour far from the\nminimum\nwhile leaving it unchanged inside the unit cube, thus providing a test\nfor those methods which are supposed to converge to the correct\ncovariance matrix by updating.\n \n \\section{Chebyquad}\n \n \n                $F(x) =    Ti(X ) dx          T (x )\n \n                      i=l O              =l$\n \n \nwhere $Ti(x)$ are shifted Chebyshev polynomials of degree i;\nstart point:                 $Xj = j/(n + l) $.\n     This function is designed to have a variable and possibly large\nnumber of parameters, and to resemble functions encountered in actual\npractice rather than being contrived to be especially difficult.  Each\nterm of F represents the squared difference between the true integral\nof a polynomial of degree i and the integral estimated by Chebyshev\n(equal-weight) quadrature on n points:\n \n \n                      $J P(x) dx | P(xj) .\n                    O                                   =l$\n \n \n                                - ;2 -\n \n \nThe starting values correspond to equally spaced points $Xj$ which is not\ntoo far away from the solution.  Fletcher gives a complete Algol-codec,\nprocedure for this function in the reference quoted below.\n \n[Reference:  Comput. J. 8, 33 (1965).]\n \n\\section{Trigonometric functions of Fletcher and Powell}\n                   $ n r n                                 -2\n                                  (Aij sin Xj + Bij cos Xj)\n                i=l  j=l$\n \nwhere\n \n \n                 $ E. = '  (A.. sin x . + B.. cos x .) $.\n                               0 1     0\n \n \n$B $ and $A$. are random matrices composed of integers between -100 and\n100;  for j = 1, ..., n:  $Xj$ are any random numbers, $- < Xoj < ;$\n \nstart point:         $xj = x j + O.l     n < j <$\nminimum:             $F(x = xO) = O $.\n \n     This is a set of functions of anv number of variables n, where the\nminimum is always known in advance, but where the problem can be changed\nby choosing different (random) values of the constants $Aij, Bij$, and .$$\nThe difficulty can be varied by choosing larger starting deviations  $$\nIn practice, most methods find the \"right\" minimum, corresponding to\nx = xo, but there are usually many subsidiary minima.\n \nReference:  Comput. J. , i63 (1963).\n \n", "meta": {"hexsha": "2a6de2c53de78f9f550c68a4f4c19eb7a0add08a", "size": 101877, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "minuit/minpart2.tex", "max_stars_repo_name": "berghaus/cernlib-docs", "max_stars_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-24T12:30:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-24T12:30:01.000Z", "max_issues_repo_path": "minuit/minpart2.tex", "max_issues_repo_name": "berghaus/cernlib-docs", "max_issues_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "minuit/minpart2.tex", "max_forks_repo_name": "berghaus/cernlib-docs", "max_forks_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.9503882657, "max_line_length": 143, "alphanum_fraction": 0.7018070811, "num_tokens": 23461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.3252848675087017}}
{"text": "\\documentclass[10pt,a4paper]{article}\n\\usepackage[latin1]{inputenc}\n\\usepackage{amsmath}\n\\usepackage{amsfonts}\n\\usepackage{amssymb}\n\\usepackage{graphicx}\n\\usepackage{float}\n\\usepackage{listings}\n\\author{Michele De Vita}\n\\title{Exercises week 5}\n\\begin{document}\n\t\\maketitle\n\t\\begin{enumerate}\n\t\t\\item  \n\t\t\\begin{align*}\n\t &i) \\,\\,\\, \\mathbf{C} = (0,  5, -7, 0), &d = -2  \\\\\n\t\t& ii) \\,\\,\\, \\mathbf{C} = \\left( \\begin{matrix}\n\t\t0 & 1 & -1 & 0 & 0 \\\\ \n\t\t0 & 0 & 1 & -1 & 0 \n\t\t\\end{matrix} \\right) ,  &d= \\left( \\begin{matrix}\n\t\t0 \\\\ \n\t\t0\n\t\t\\end{matrix} \\right)\n\t\t\\end{align*}\n\t\t\\item \n\t\tThis plot shows the SSE in function of $ \\beta $:\n\t\t\\begin{figure}[H]\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=0.7\\linewidth]{plot_ftest}\n\t\t\\end{figure}\n\t\tThe F-test score is $ \\dfrac{SSE_{H_0} - SSE}{SSE} $ where $ SSE = SSE(\\hat{\\beta}) $ that is the y in the plot where $ x = \\hat{\\beta} $ and $ SSE_{H_0} = SSE(\\beta = 1) $\\\\\n\t\tThe plot for the numerator of Wald test is the same of the previous because the numerator is the same except for a square difference instead of normal difference.\\\\\n\t\tThe main difference between F-test and Wald test is the denominator in the first is $ \\hat{\\theta} $ while in the second is $ var(\\hat{\\theta}) $. There is also a relation between test statistics $ F $ and $ W $: $ W = rF $\n\t\t\\item The confidence interval for $ \\mu_0  $ is $ \\mathbf{x}_0' \\hat{\\beta} \\pm t_{n-p}(1-\\alpha / 2) \\hat{\\sigma} (\\mathbf{x}_0' (\\mathbf{X'X})^{-1} x_0)^{1/2}$ while for prediction is $ \\mathbf{x}_0' \\hat{\\beta} \\pm t_{n-p}(1-\\alpha / 2) \\hat{\\sigma} (1 + \\mathbf{x}_0' (\\mathbf{X'X})^{-1} x_0)^{1/2}$. The difference between the two formulas is the \"$ 1\\,\\,+ $\" near $ x_0 $ that become from the fact that the estimation try to give an confidence interval of a parameter , so with no variance, while the prediction try to estimate a aleatory variable with a expected value and a variance.\n\t\t\\item $ f(x_0) = \\mathbf{x}_0' \\hat{\\beta} \\pm t_{n-2}(1-\\alpha / 2) \\hat{\\sigma} (1 + \\mathbf{x}_0' (\\mathbf{X'X})^{-1} x_0)^{1/2}$\n\t\twhere $ X = $\n\t\t$ \\left( \\begin{matrix}\n\t\t\t1 & x_{11} \\\\ \n\t\t\t\\vdots & \\vdots  \\\\ \n\t\t1 & x_{n1}\n\t\t\t\\end{matrix} \\right)$ and $ p = 2 $.\\\\\n\t\t\tThe length of interval is minimum when $ \\mathbf{x_0 = \\mu}  $ because we can write the product $ \\mathbf{x_0'(X'X)^{-1}x_0}  $ as $ \\dfrac{\\sum(x_i - x_0)^2}{dev(x)} $ then the numerator $  \\sum(x_i - x_0)^2 $ is minimized when $ x_0 = \\mu $\n\t\t\t\\item Increasing the number of parameters is not always a good idea: we can express the SPSE (expected squared prediction error as):\n\t\t\t$ \\underbrace{n\\sigma^2}_{irreducible\\,\\,  part} + \\underbrace{|M|\\sigma^2}_{Variance \\,\\, error} + \\underbrace{\\sum_{i=1}^{n} (u_{i M} - u_i)^2}_{BIAS^2} $\n\t\t\t\\item If we consider only $ \\mathbf{X_1} $ we have $ \\mathbf{X = X_1} $ then \n\t\t\t\\begin{align*}\n\t\t\t\tE\\left[ \\tilde{\\beta}_1 \\right]\t\t&= E \\left[ \\mathbf{(X_1'X_1)^{-1} X_1'y} \\right] \\\\\n\t\t\t\t&=  \\mathbf{(X_1'X_1)^{-1} X_1' } E \\left[ \\mathbf{y} \\right] \\\\\n\t\t\t\t&=  \\mathbf{(X_1'X_1)^{-1} X_1' (X_1 \\beta_1 + X_2 \\beta_2)} \\\\\n\t\t\t\t&= \\beta_1 +\\mathbf{(X_1'X_1)^{-1} X_1'  X_2 \\beta_2}\n\t\t\t\\end{align*}\n\t\t\tThe bias vanish if $ \\mathbf{X_1'  X_2  = 0} $ that in statical words mean that $ \\mathbf{X_1} \\text{ and } \\mathbf{X_2} $ are uncorrelated or when $ \\mathbf{\\beta_2}  $ is irrelevant\n\t\t\t\\item If we omit a relevant covariate, we can have a decrease the variance of model such that the increase of $ bias^2 $ is overall convenient\n\t\t\t\\item $ SPSE = \\sum (y_{n+i} - \\hat{y}_{iM}^2) $. See point 5\n\t\t\t\\item \n\t\t\t\\begin{align*}\n\t\t\tE\\left( SSE \\right) &= E\\left( \\sum \\left( y_i - \\hat{y}_{iM} \\right)^2 \\right)  \\\\\n\t\t\t&= E \\left( \\mathbf{\\varepsilon' \\varepsilon} \\right) \\\\\n\t\t\t&= (n-p) \\sigma^2 \\\\\n\t\t\t&= E(SPSE) - 2  |M|\\sigma^2 \\\\\n\t\t\t&= n \\sigma^2 + |M|\\sigma^2 -2 |M|\\sigma^2 \\\\\n\t\t\t&= n \\sigma^2 - |M|\\sigma^2 \\\\\n\t\t\t&= (n-p)\\sigma^2\n\t\t\t\\end{align*} \n\t\t\t$ SSE $  underestimate the $ SPSE $ because $ \\hat{SPSE} = \\hat{SSE} + 2  |M| \\hat{\\sigma}^2$ .\\\\\n\t\t\tThis bias is more severe for complex models because the bias is proportional to model complexity\n\t\t\t\\item $ AIC =n \\log(\\hat{\\sigma}^2) + 2 (|M| + 1) $\\\\\n\t\t\t$ BIC = n \\log(\\hat{\\sigma}^2) + \\log(n) (|M| + 1) $.\\\\\n\t\t\tSince $ SPSE  $ is not observable the two latter indicators are used to evaluate the fit of the model.\\\\\n\t\t\tThe difference between $ AIC \\text{ and } BIC $ is the term before $ (|M| + 1) $: in AIC is equal to 2 while in BIC is $ \\log(n) $. This mean that BIC have a major penalty when the model complexity increase in big dataset.\\\\\n\t\t\tNext we can see the tables with the results:\n\t\t\t\\begin{center}\n\t\t\t\\begin{tabular}{|c|c|c|}\n\t\t\t\t\\hline \n\t\t\t\tn = 100 & AIC & BIC \\\\ \n\t\t\t\t\\hline \n\t\t\t\t$ l = -300, |M| = 5 $ & 612 & 627.63 \\\\ \n\t\t\t\t\\hline \n\t\t\t\t$ l = -290, |M| = 9 $ & 600 & 626.05 \\\\ \n\t\t\t\t\\hline \n\t\t\t\\end{tabular} \\\\ \\medskip\n\t\t\t\\begin{tabular}{|c|c|c|}\n\t\t\t\t\\hline \n\t\t\t\tn = 200 & AIC & BIC \\\\ \n\t\t\t\t\\hline \n\t\t\t\t$ l = -300, |M| = 5 $ & 612 & 631.79 \\\\ \n\t\t\t\t\\hline \n\t\t\t\t$ l = -290, |M| = 9 $ & 600 & 632.98 \\\\ \n\t\t\t\t\\hline \n\t\t\t\\end{tabular} \\\\\n\t\t\\end{center}\n\t\t\tBetween $ n = 100 $ and $ n = 200 $ we can note the phenomenon described before with BIC, because with $ n = 100 $ there is a decrement of BIC between the two configurations while for $ n = 200 $ the BIC increase between the two configurations\n\n\t\t\t\\item $ VIF_j = \\dfrac{1}{1 - R_j^2} $.\\\\It measures the correlation between the covariate $ x_j $ with the other covariates. The greater is $ R^2_j \\in [0,1]$ the greater is $ VIF_j $. An empiric alert for variance is when $ VIF_j > 10 $\n\t\t\t\\item The ridge regression add a penalty term $ \\lambda $ to the linear regression. The $ \\mathbf{PLS(\\beta) = (y - X \\beta)'(y - X \\beta) + \\lambda \\beta' \\beta} $.\\\\The ridge regression is biased respect to linear regression:\\\\\n\t\t\t$ E_{LS}(\\hat{\\beta}) = \\mathbf{(X'X)^{-1} X'X \\beta = \\beta} $\\\\\n\t\t\t$   E_{PLS}(\\hat{\\beta}) = \\mathbf{(X'X + \\lambda X'X)^{-1} X'X \\beta} $   (when penalty = 0 $  E_{PLS}(\\hat{\\beta}) = E_{LS}(\\hat{\\beta})   $)\\\\\n\t\t\tWhen $ \\lambda $ increases the coefficients $\\beta $ tends to zero because $ \\mathbf{\\lambda K = (X'X + \\lambda K)- X'X} $. If we multiply two definite semipositive matrices $ \\mathbf{(X'X + \\lambda K)^{-1}} $ with $  \\mathbf{(X'X + \\lambda K)- X'X}  $ also the result is definite semipositive  that is $ \\mathbf{I_p - (X'X + \\lambda K)^{-1}X'X}  $. This imply that $ \\mathbf{(X'X + \\lambda K)^{-1}X'X}    $ have the diagonal elements between $[0,1] $ and this term appears when we express $ \\hat{\\beta}_{PLS} $ in function of $ \\hat{\\beta}_{LS} $:\\\\\n\t\t\t$ \\hat{\\beta}_{PLS} =  \\mathbf{(X'X + \\lambda K)^{-1}X'X \\beta_{LS}}   $\\\\\n\t\t\tThe covariance matrix of $ \\hat{\\beta}_{PLS} $ for the same reason is lower than variance of $ \\hat{\\beta}_{LS} $ so in some cases can be convenient use a ridge regression when the bias error is less relevant than variance error \n\t\\end{enumerate}\n\t\\subsection*{Stata code}\n\t\\lstinputlisting{stata_ex.do}\n\\end{document}", "meta": {"hexsha": "8baf457100c64784127b275572f9d71df6253007", "size": 6932, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "week_5/week5.tex", "max_stars_repo_name": "Michedev/MSA_Exercises", "max_stars_repo_head_hexsha": "d7faeaef14c1a8a939b3a3b613769845de6aa2fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "week_5/week5.tex", "max_issues_repo_name": "Michedev/MSA_Exercises", "max_issues_repo_head_hexsha": "d7faeaef14c1a8a939b3a3b613769845de6aa2fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week_5/week5.tex", "max_forks_repo_name": "Michedev/MSA_Exercises", "max_forks_repo_head_hexsha": "d7faeaef14c1a8a939b3a3b613769845de6aa2fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 66.6538461538, "max_line_length": 593, "alphanum_fraction": 0.6115118292, "num_tokens": 2666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.3252848602598147}}
{"text": "%!TEX TS-program = lualatex\n%!TEX encoding = UTF-8 Unicode\n\n\\documentclass[12pt]{exam}\n\n\n%\\printanswers\n\n\\usepackage{fontspec}\n\\setmainfont[Ligatures={TeX}, BoldFont={* Bold}, ItalicFont={* Italic}, BoldItalicFont={* BoldItalic}, Numbers={Monospaced, Lining}]{Linux Libertine O}\n\\setsansfont[Scale=MatchLowercase,Ligatures=TeX]{Linux Biolinum O}\n\\setmonofont[Scale=MatchLowercase]{Inconsolatazi4}\n\\newfontfamily{\\tablenumbers}[Numbers={Monospaced,Lining}]{Linux Libertine O}\n\\usepackage{microtype}\n\n\\usepackage{amsmath}\n\n\\usepackage{unicode-math}\n\\setmathfont[Scale=MatchLowercase]{TeX Gyre Termes Math}\n\n\\usepackage{geometry}\n\\geometry{letterpaper, left=1.5in, bottom=1in}                   \n%\\geometry{landscape}                % Activate for for rotated page geometry\n\\usepackage[parfill]{parskip}    % Activate to begin paragraphs with an empty line rather than an indent\n\n\\usepackage{longtable}\n\n%\\usepackage{siunitx}\n\\usepackage{booktabs}\n\\usepackage{array}\n\\newcolumntype{L}[1]{>{\\raggedright\\let\\newline\\\\\\arraybackslash\\hspace{0pt}}m{#1}}\n\\newcolumntype{C}[1]{>{\\centering\\let\\newline\\\\\\arraybackslash\\hspace{0pt}}m{#1}}\n\\newcolumntype{R}[1]{>{\\raggedleft\\let\\newline\\\\\\arraybackslash\\hspace{0pt}}m{#1}}\n\n\\usepackage{enumitem}\n\\setlist{leftmargin=*}\n\\setlist[1]{labelindent=\\parindent}\n\\setlist[enumerate]{label=\\textsc{\\alph*}.}\n\\setlist[itemize]{label=\\color{gray}\\textbullet}\n%\\usepackage{hyperref}\n%\\usepackage{placeins} %PRovides \\FloatBarrier to flush all floats before a certain point.\n%\\usepackage{hanging}\n\n\\usepackage[sc]{titlesec}\n\n%% Commands for Exam class\n\\renewcommand{\\solutiontitle}{\\noindent}\n\\unframedsolutions\n\\SolutionEmphasis{\\bfseries}\n\n\n\\pagestyle{headandfoot}\n\\firstpageheader{\\textsc{bi}\\,163 Evolution and Ecology}{}{\\ifprintanswers\\textbf{KEY}\\else Name: \\enspace \\makebox[2.5in]{\\hrulefill}\\fi}\n\\runningheader{}{}{\\footnotesize{pg. \\thepage}}\n\\footer{}{}{}\n\\runningheadrule\n\n\n\n\\begin{document}\n\n\\subsection*{Shannon-Wiener diversity practice problems}\n\n\n%The species diversity of a community can be estimated by random sampling of individuals from the community. You can calculate \\textit{species richness}, which is the total number of unique species in your sample. You can also calculate \\textit{relative abundance}, which the proportion of individuals for each species out of the total number of individuals in your sample.\n%\n%Species richness and relative abundance (also known as evenness) can be combined mathematically to represent the \\textit{species diversity} of a community with a single value (the diversity index). The number by itself does not tell you too much but communities with higher indices have higher diversity.\n\nSpecies diversity for a sample can be calculated with any of several different equations. The equation we will use is called the Shannon-Wiener diversity index, or Shannon index for short. The Shannon equation is\n\n\\[H^{\\prime} = -\\sum p_i \\ln p_i,\\] \n\nwhere $H^{\\prime}$ is the index, $p_i$ is the relative abundance of each species, $ln$ is the natural logarithm, and $\\sum$ indicating summing across all species. Notice the negative sign before the summation symbol. This will make the final index positive, as you will see below.\n\nHere is an example calculation with the number of individuals from each of 5 species.\n\n\\begin{tabular}{llllll}\nSpecies & A & B & C & D & E \\tabularnewline\nNumber & 11 & 23 & 17 & 24 & 28 \\tabularnewline\n\\end{tabular}\n\nThe calculations are summarized in the table at the end of the list.\n\n\\begin{enumerate}\n\\item Calculate the total number of individuals in the sample, $11 + 23 + 17 + 24 + 28 = 103.$\n\n\\item Calculate $p_i$ by dividing the number of individuals for each species by the total number of individuals, e.g., 11/103 = 0.107, etc.\n%\n%\\begin{tabular}{lrr}\n%Species & $n$ & $p_i$ \\tabularnewline\n%\\toprule\n%A & $11$ & $0.107$ \\tabularnewline\n%B & $23$ & $0.223$ \\tabularnewline\n%C & $17$ & $0.165$ \\tabularnewline\n%D & $24$ & $0.233$ \\tabularnewline\n%E & $28$ & $0.272$ \\tabularnewline\n%\\bottomrule\n%\\end{tabular}\n\n\\item Calculate the natural log of each $p_i$. This is the “ln” key on your calculator. If your calculator does not have a natural log key, use the “log” key for $\\log_{10}$. You will get a different result but that is OK. You are comparing numbers (larger = more diverse) so the actual values do not matter much. If your calculator does not have either key, get a better calculator! \n\n%\\begin{tabular}{lrrr}\n%Species & $n$ & $p_i$ & $\\ln p_i$\\tabularnewline\n%\\toprule\n%A & $11$ & $0.107$ & $-2.235$ \\tabularnewline\n%B & $23$ & $0.223$ & $-1.501$ \\tabularnewline\n%C & $17$ & $0.165$ & $-1.802$ \\tabularnewline\n%D & $24$ & $0.233$ & $-1.457$ \\tabularnewline\n%E & $28$ & $0.272$ & $-1.302$ \\tabularnewline\n%\\bottomrule\n%\\end{tabular}\n%\n\\item Multiply the two values together, e.g., $0.107 \\times -2.235 = -0.239$ and so on.\n\n%\\begin{tabular}{lrrrr}\n%Species & $n$ & $p_i$ & $\\ln p_i$ & $p_i \\ln p_i$ \\tabularnewline\n%\\toprule\n%A & $11$ & $0.107$ & $-2.235$ & $-0.239$ \\tabularnewline\n%B & $23$ & $0.223$ & $-1.501$ & $-0.335$ \\tabularnewline\n%C & $17$ & $0.165$ & $-1.802$ & $-0.297$ \\tabularnewline\n%D & $24$ & $0.233$ & $-1.457$ & $-0.339$ \\tabularnewline\n%E & $28$ & $0.272$ & $-1.302$ & $-0.354$ \\tabularnewline\n%\\bottomrule\n%\\end{tabular}\n\n\\item Sum together the values in the final column.\n\n\\item Notice the final sum is a negative value. That is why the negative sign appears before the summation symbol in the equation above. It turns the final value positive. \n\\end{enumerate}\n\n\\begin{tabular}{lrrrr}\nSpecies & $n$ & $p_i$ & $\\ln p_i$ & $p_i \\ln p_i$ \\tabularnewline\n\\toprule\nA & $11$ & $0.107$ & $-2.235$ & $-0.239$ \\tabularnewline\nB & $23$ & $0.223$ & $-1.501$ & $-0.335$ \\tabularnewline\nC & $17$ & $0.165$ & $-1.802$ & $-0.297$ \\tabularnewline\nD & $24$ & $0.233$ & $-1.457$ & $-0.339$ \\tabularnewline\nE & $28$ & $0.272$ & $-1.302$ & $-0.354$ \\tabularnewline\n\\midrule\n  &  $103$    &         & \\hfill $\\sum$ & $-1.564$\\tabularnewline\n\\bottomrule\n\\end{tabular}\n\nThe Shannon diversity for this sample is $H^{\\prime} = 1.564.$\n\n\\subsection*{Practice Problems}\n\nCalculate $H^{\\prime}$ for each community, then identify the most and least diversity communities.  The correct answers for $\\ln$ and $\\log_{10}$ are given for you to check your work. Be sure to compare values calculated by the same logarithm function (i.e., only $\\ln$ or only $\\log_{10}$). Your numbers may be off slightly due to rounding but you should not be off by more than 0.010 or so.\n\n\\begin{enumerate}[label=\\textsc{Community \\alph*:}]\n\n\\item 74 71 75 84 55 56 71 54\n\n Answer $\\ln: 2.067$\n \n Answer $\\log_{10}: 0.898$\n\n\\item 90 93 65 85 74 91 73 85\n\n Answer $\\ln: 2.072$\n \n Answer $\\log_{10}: 0.900$\n\n\\item 65 65 90 51 83 99 50 52\n\n Answer $\\ln: 2.047$\n \n Answer $\\log_{10}: 0.889$\n\n\\item 80 43 37 77 94 10 67 63\n\n Answer $\\ln: 1.965$\n \n Answer $\\log_{10}: 0.854$\n\n\\item 80 82 66 50 38 87 31 38\n\n Answer $\\ln: 2.014$\n \n Answer $\\log_{10}: 0.875$\n\n\\end{enumerate}\n\nCommunity B is the most diverse. Community D is the least diverse.\n\n\\end{document}  ", "meta": {"hexsha": "b7d853df79dc11f767c12c79cef5cacdd13d7caa", "size": 7058, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "activities/diversity_practice.tex", "max_stars_repo_name": "mtaylor-semo/163", "max_stars_repo_head_hexsha": "670db734c68195edb7af76a2feee7bcb166fdffc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "activities/diversity_practice.tex", "max_issues_repo_name": "mtaylor-semo/163", "max_issues_repo_head_hexsha": "670db734c68195edb7af76a2feee7bcb166fdffc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "activities/diversity_practice.tex", "max_forks_repo_name": "mtaylor-semo/163", "max_forks_repo_head_hexsha": "670db734c68195edb7af76a2feee7bcb166fdffc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9462365591, "max_line_length": 392, "alphanum_fraction": 0.7047322188, "num_tokens": 2307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521307073646, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.32528485094405934}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%\n%\n%   Thesis template by Youssif Al-Nashif\n%\n%   May 2020\n%\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Introduction}\n\n\n\n\\subsection{ Skip-grams}\n\\hspace*{0.3cm} As an alternative to natural language processing (NLP) methods, which are reliant on ``bag-of-words\" methods, the methods used here utilize a graph representation of the text. Consider a bigram, a pair of two words\\textemdash like ``hot dog\" or ``peanut butter\", these bigrams can be constructed for a text document where every pair or adjacent words is a bigram. The bigrams can then be used to make a graph, where each word is a vertex, and each bigram is an edge. This graph representation holds more context than the bag-of-words methods; for example seeing the words ``cake\" and ``carrot\" in a bag of words may not show that ``carrot cake\" was the real intent of the text. This is an important concept for modeling text, as we should strive to achieve a representation of the text that makes for effective modeling that will capture the true meaning of the text in question. Keeping this in mind, with the example of ``carrot cake\", what about the idiom ``beating a dead horse\"? Each word individually may mean something other than the idiom. Even the bigrams ``beating dead\" and ``dead horse\" do not capture what the idiom means. We can expand the number of words in the n-gram to be 3 or 4 words, or alternatively, we can make more ``edges\" or connect more words. We can connect words that are not immediately adjacent but perhaps within $k$ words away. These bigrams that appear within $k$ words of each other are called ``skip-grams\". The skip-gram allows to capture context of larger sequences of words since the graph representation will show how the $k$ wide neighborhood of words was connected. In the idiom example, using skip-grams with window width $k = 2$, and removing common words (e.g. ``a\", ``at\", ``the\"), will produce a graph like: \n\n$$\nE(G) = \\{\n\\text{beat}  \\longleftrightarrow \\text{dead}, \n\\text{dead}  \\longleftrightarrow \\text{horse}, \n\\text{horse}  \\longleftrightarrow \\text{beat} \\}\n$$\n\nThis graph representation contains a cycle, of length 3, where most native english speakers will identify the meaning behind the graph representation. As ideas, idioms, figures of speech, and other concepts (that may be explained in a non-literal fashion) grow in size as they include more words, it becomes more difficult to capture the meaning behind the text. However, leveraging the concept of a skip gram can produce such a rich graph representation of the text that the original meaning is more likely to be preserved. Other research has shown that use of skip-grams for text modeling leads to less data sparsity and mitigates issues of variety in large corpuses through modeling text in this way. The skip-grams are shown to preserve more context than traditional bag-of-words methods that use words as the token of choice \\cite{guthrie2006closer}.\\\\\n\n\\subsection{ Graph Kernels}\n\\hspace*{0.3cm} The next natural question is, ``how can we compare these graph representations?\", and we address this with graph kernel methods. These methods are generally used to compare the similarity of graphs. These use of a graph kernel to compare graphs was first published in 2003, and since then various applications and adaptations have been made to the methods. In the case of text mining, the graph kernel must assess vertex labels \\textemdash if one intends to map words to vertices, otherwise they will be assessing the topology alone. In this study, the Edge-Histogram kernel is the kernel used to compute similarity. This kernel was chosen as it uses labels on the graph structure, and is not as computationally intensive as other methods \\cite{sugiyama2015halting}. In the specific implementation used for these studies, the computation time was the shortest when compared with other kernel methods like: graphlet, random walk, and Weisfeiler-Lehman kernel \\cite{sugiyama2015halting}. Since the data sets of concern in the studies feature either large graphs or a large number of graphs, the kernel had to be cheap computationally.\\\\\n\nTo compute and edge histogram kernel on two graphs, $G_1$ and $G_2$, first define the set of edges $E_i =\\{ (u_1,v_1), (u_2,v_2), ... , (u_n,v_n) \\}$ where $(u_n,v_n)$ is the $n$-th edge connecting $u_n$ to $v_n$. Then the edge label histogram is defined to be $\\vec{g} = \\{ g_1, g_2, ... , g_s\\}$, so that $g$ contains the number of times each edge label appeared. In the case of graphical representations of text, the number of times a skip-gram appears is not considered; it either appeared or did not. For this reason, a Manhattan distance is chosen, as opposed to a euclidean or similar distance metric, since the Manhattan distance measures distance along a grid\\textemdash like Manhattan city blocks from point A to point B. Since the data are all on a grid in essence, due to the binary nature of either having a label or not, the Manhattan distance is a natural fit here. The kernel is then the sum or the product of each element in the $g$ vectors for each $G_1$ and $G_2$ in the case of a linear kernel \\cite{sugiyama2015halting}.\n\n\n\n%https://papers.nips.cc/paper/2015/file/31b3b31a1c2f8a370206f111127c0dbd-Paper.pdf\n\n\\subsection{Using Kernel for Clustering}\n\n\\hspace*{0.3cm} The output of the kernel is useful for a variety of tasks. Some other popular applications have included classification with support vector machines, which are popular with other kernel methods. In this case, the kernel is used for unsupervised clustering. Within the kernel matrix, $K$, the entry $k_{i,j}$ represents the similarity between graphs $i$ and $j$. This matrix which contains measures of similarity between points can be used as a distance matrix for hierarchical clustering. Before using the graph kernel as a distance matrix, normalization or standardization takes place, and principal component analysis may be used. The end result is each row is a single graph-document being described by its similarity to all the other graphs, which are the column values. Once the values are transformed or rotated by preprocessing methods, the points are just represented by their similarity to one another, but in a transformed space. Various hyper parameters can be tuned for successful clustering; the graph kernel has a parameter that can be tuned, and the hierarchical clustering can be tried with differing types of linkage.\n\n\n%\\subsection{Kernel Density Estimation Clustering for Linear Kernel}\n\n%In addition to hierarchical clustering, a method was developed to find potential clusters based on the kernel similarity measure, but while measuring similarity to a single graph. For example, we can compare how similar graphs $B$ and $C$ without computing their similarity, by comparing how similar they are to graph $A$; this extension of transitive property logic allows for focusing on the similarity of the graph list as it relates to just one graph. \n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "87cadc87480438c8278bffe6d1caa3b876c100af", "size": 6997, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Thesis_Tex/Content/02_Chapters/Chapter 03/Sections/00_Introduction.tex", "max_stars_repo_name": "Levi-Nicklas/GraphDocNLP", "max_stars_repo_head_hexsha": "dec1acb24a2ab42b46d161c92b69ad3a55fcc5ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-27T02:08:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-27T02:08:34.000Z", "max_issues_repo_path": "Thesis_Tex/Content/02_Chapters/Chapter 03/Sections/00_Introduction.tex", "max_issues_repo_name": "Levi-Nicklas/GraphDocNLP", "max_issues_repo_head_hexsha": "dec1acb24a2ab42b46d161c92b69ad3a55fcc5ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2021-02-18T16:07:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-25T14:18:51.000Z", "max_forks_repo_path": "Thesis_Tex/Content/02_Chapters/Chapter 03/Sections/00_Introduction.tex", "max_forks_repo_name": "Levi-Nicklas/GraphDocNLP", "max_forks_repo_head_hexsha": "dec1acb24a2ab42b46d161c92b69ad3a55fcc5ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 134.5576923077, "max_line_length": 1771, "alphanum_fraction": 0.7776189796, "num_tokens": 1597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.32515961632211404}}
{"text": "\\hypertarget{haskell-types}{%\n\\section{Haskell Types}\\label{haskell-types}}\n\n\\hypertarget{types-of-lists-and-tuples}{%\n\\subsection{Types of Lists and Tuples}\\label{types-of-lists-and-tuples}}\n\nAfter declare x = `x':\n\n\\begin{lstlisting}[language=Haskell]\nx ==> Char\n'x' ==> Char\n\"x\" ==> [Char]\n['x'] ==> [Char]\n[x, 'x'] ==> [Char]\n[x, x, x, x] ==> [Char]\n['x', \"x\"] ==> error\n[x, True] ==> error\n[x == 'x', True] ==> [Bool]\n[[\"True\"]] ==> [[[Char]]]\n[[ True, False], True] ==> error\n[[ True, False], []] ==> [[Bool]]\n('x') ==> Char\n(x , 'x') ==> (Char, Char)\n(x ,x, x, x) ==> (Char, Char, Char, Char)\n('x', \"x\") ==> (Char, [Char])\n(x , True) ==> (Char, Bool)\n(x == 'x' ,True) ==> (Bool, Bool)\n((\"True\")) ==> [Char]\n((True ,False) ,True) ==> ((Bool, Bool), Bool)\n((True, False), ()) ==> ((Bool, Bool), ())\n\\end{lstlisting}\n\n\\hypertarget{types-of-lists}{%\n\\subsection{Types of Lists}\\label{types-of-lists}}\n\n\\begin{lstlisting}[language=Haskell]\nAfter declare a = [True]:\n\na ==> [Bool]\na ++ a ++ [True] ==> [Bool]\na ++ [] ==> [Bool]\nhead a ==> Bool\ntail a (*) ==> error\nhead 'x' ==> error\nhead \"x\" ==> Char\ntail \"x\" (*) ==> error\n\"dimdi\" !! 2 ==> Char (Gibt den dritten Buchstaben aus (0 indexiert))\n\"dimdi\" ++ \"ding\" ==> [Char]\n\\end{lstlisting}\n\n\\hypertarget{types-of-functions-and-lists}{%\n\\subsection{Types of Functions and\nLists}\\label{types-of-functions-and-lists}}\n\n\\begin{lstlisting}[language=Haskell]\nf1 :: Int -> Int\nf1 x = x^2 + x + 1\nf2 :: Int -> Int\nf2 x = 2 * x + 1\n\nf1 ==> Int -> Int\nf1 5 ==> Int\nf1 f2 ==> error\nf1 (f2 5) ==> Int\n[f1 5, f2 6, 5, 6] ==> [Int]\n[f1, f2, f1] ==> [Int -> Int]\n[f1 5, f2] ==> error\n(f1 5, f2) ==> (Int, Int -> Int)\n([f1, f2, f1] !! 1) 3 ==> Int\n([f1, f2, f1] !! 5) 3 (*) ==> error\n\\end{lstlisting}\n\n\\hypertarget{types-of-functions-with-currying}{%\n\\subsection{Types of Functions with\nCurrying}\\label{types-of-functions-with-currying}}\n\n\\begin{lstlisting}[language=Haskell]\ng1 :: Int -> Int -> Int -> Int\ng1 x y z = x^2 + y^2 + z^2\ng2 :: Int -> Int -> Int\ng2 x y = 2*x + 2*y\n\ng1  ==> Int -> Int -> Int -> Int\ng1 2 ==> Int -> Int -> Int\ng1 2 3 ==> Int -> Int\ng1 2 3 4 ==> Int\ng1 2 3 4 5 ==> eroor\n(g1, g2) ==> (Int -> Int -> Int -> Int, Int -> Int -> Int)\n(g1 2, g2) ==> (Int -> Int -> Int, Int -> Int -> Int)\n(g1 2 3, g2 4) ==> (Int -> Int, Int -> Int)\n(g1 2 3 4, g2 4 5) ==> (Int, Int)\n[g1, g2] ==> error\n[g1 2, g2] ==> [Int -> Int -> Int]\n[g1 2 3, g2 4] ==> [Int -> Int]\n[g1 2 3 4, g2 4 5] ==> [Int]\n\\end{lstlisting}\n\n\\clearpage", "meta": {"hexsha": "8056824032e36f57901ae17f8842b6ac7bdee3f9", "size": 2468, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "TSM_AdvPrPa/Excercises/Haskell/01_TypeExercise.tex", "max_stars_repo_name": "nortismo/mse-documentations", "max_stars_repo_head_hexsha": "cc67637785237d630f077a863edcd5f49aa52b59", "max_stars_repo_licenses": ["Beerware"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TSM_AdvPrPa/Excercises/Haskell/01_TypeExercise.tex", "max_issues_repo_name": "nortismo/mse-documentations", "max_issues_repo_head_hexsha": "cc67637785237d630f077a863edcd5f49aa52b59", "max_issues_repo_licenses": ["Beerware"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TSM_AdvPrPa/Excercises/Haskell/01_TypeExercise.tex", "max_forks_repo_name": "nortismo/mse-documentations", "max_forks_repo_head_hexsha": "cc67637785237d630f077a863edcd5f49aa52b59", "max_forks_repo_licenses": ["Beerware"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-15T07:10:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-15T07:10:24.000Z", "avg_line_length": 25.1836734694, "max_line_length": 72, "alphanum_fraction": 0.5429497569, "num_tokens": 966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.3251596073118461}}
{"text": "\\documentclass[12pt,letterpaper]{article}\n\n\\usepackage{amsmath, amsthm, amsfonts, amssymb}\n\\usepackage{microtype, parskip, graphicx}\n\\usepackage{multirow, morefloats, rotating}\n\\usepackage{caption, subcaption}\n\\usepackage{lineno}\n\\usepackage{afterpage}\n\\usepackage{hyperref}\n\n\\title{Report on Fossil/Not Fossil}\n\n\n\\begin{document}\n\\maketitle\n\n\\section{Set-Up}\n\nWe want to predict the expected diversity of a Macrostrat geological unit. We are focused on the diversity of individual biological classes. Geological units are described in terms of their lithological descriptions, areal extent, location, ``connectedness'' (units above/below), and other values. Lithological description is a compositional variable and thus has annoying properties which can prove difficult to interpret. \n\nThe dataset is split into two sets: the late Ordovician (460.4--445.6) and the Hirnantian (445.6--443.8); the former is the training dataset while the latter is the testing dataset.\n\n\n\\section{Model}\n\nThe basics of the models used in this analysis is a hurdle model which is a mixture of a Bernoulli distribution and either a Poisson or Negative-Binomial distribution. The Bernoulli aspect describes the probability of observing 0 species in a geological unit, while the Poisson or Negative-Binomial describes the expected number of species present in that geological unit if there are more than 0.\n\nBoth parts of the mixture are modeled as regressions with all of the geological unit covariates as predictors.\n\nThe models are fit to the training dataset and the results of which are used to predict the diversity of the Hirnantian geological units. The approximate expected out-of-sample predictions were evaluated through 5 rounds of 5-fold cross-validation.\n\nThe models are fit in a fully Bayesian context using the Stan probabilistic programming language. Model fit for the complete training dataset is evaluated through a series of posterior predictive checks. Additionally, models are compared using WAIC and LOOIC which are estimates of comparative out-of-sample predictive performance.\n\n\n\\section{Results}\n\n\\subsection{Full data posterior predictive checks}\nfigures \\ref{fig:ppc_mean}, \\ref{fig:ppc_sd}, \\ref{fig:ppc_ecdf}, \\ref{fig:ppc_root}, \\ref{fig:ppc_avgerr}. waic \\ref{tab:waic} and looic \\ref{tab:loo}.\n\n\\afterpage{\\clearpage}\n\\begin{figure}[h]\n  \\centering\n  \\includegraphics[width=\\textwidth,height=0.8\\textheight,keepaspectratio=true]{figure/ppc_mean}\n  \\caption{Mean of unit diversity. Distribution is estimated from posterior, vertical line is observed. Columns are by model type, rows are by taxonomic group.}\n  \\label{fig:ppc_mean}\n\\end{figure}\n\n\\afterpage{\\clearpage}\n\\begin{figure}[h]\n  \\centering\n  \\includegraphics[width=\\textwidth,height=0.8\\textheight,keepaspectratio=true]{figure/ppc_sd}\n  \\caption{Standard deviation of unit diversity. Distribution is estimated from posterior, vertical line is observed. Columns are by model type, rows are by taxonomic group.}\n  \\label{fig:ppc_sd}\n\\end{figure}\n\n\\afterpage{\\clearpage}\n\\begin{figure}[h]\n  \\centering\n  \\includegraphics[width=\\textwidth,height=0.8\\textheight,keepaspectratio=true]{figure/ppc_ecdf}\n  \\caption{Empirical cumulative distribution function of unit diversity; that is, rank order proportional accumulation. Distribution is estimated from posterior, dark line is observed. Columns are by model type, rows are by taxonomic group.}\n  \\label{fig:ppc_ecdf}\n\\end{figure}\n\n\\afterpage{\\clearpage}\n\\begin{figure}[h]\n  \\centering\n  \\includegraphics[width=\\textwidth,height=0.8\\textheight,keepaspectratio=true]{figure/ppc_root}\n  \\caption{Rootogram of unit diversity. Distribution is estimated from posterior, hanging histogram is is observed. If histogram is above x-axis, overestimate; if histogram is below x-axis, underestimate. Columns are by model type, rows are by taxonomic group.}\n  \\label{fig:ppc_root}\n\\end{figure}\n\n\\afterpage{\\clearpage}\n\\begin{figure}[h]\n  \\centering\n  \\includegraphics[width=\\textwidth,height=0.8\\textheight,keepaspectratio=true]{figure/ppc_avgerr}\n  \\caption{Average error of estimated unit diversity. Comparison is between observed diversity and estimated diversity. Columns are by model type, rows are by taxonomic group.}\n  \\label{fig:ppc_avgerr}\n\\end{figure}\n\n\\begin{sidewaystable}\n  \\centering\n  \\caption{}\n  \\label{tab:waic}\n  \\begin{tabular}{r|llll}\n    \\hline\n    Taxonomic group & Poisson model WAIC & Poisson model SE WAIC & NegBin model WAIC & NegBin model SE WAIC \\\\ \n    \\hline\n    Bivalvia & 1485.42 & 124.66 & 1317.38 & 102.66 \\\\ \n    Brachiopoda & 2602.90 & 179.58 & 2134.50 & 123.81 \\\\ \n    Gastropoda & 2089.17 & 176.01 & 1636.84 & 114.12 \\\\ \n    Trilobita & 1828.36 & 139.25 & 1585.80 & 105.04 \\\\ \n    \\hline\n  \\end{tabular}\n\\end{sidewaystable}\n\n\\begin{sidewaystable}\n  \\centering\n  \\caption{}\n  \\label{tab:loo}\n  \\begin{tabular}{r|llll}\n    \\hline\n    Taxonomic group & Poisson model LOOIC & Poisson model SE LOOIC & NegBin model LOOIC & NegBin model SE LOOIC \\\\ \n    \\hline\n    Bivalvia & 1485.45 & 124.66 & 1319.02 & 102.88 \\\\ \n    Brachiopoda & 2602.95 & 179.58 & 2135.65 & 123.91 \\\\ \n    Gastropoda & 2089.20 & 176.01 & 1639.43 & 114.45 \\\\ \n    Trilobita & 1828.38 & 139.25 & 1586.98 & 105.18 \\\\ \n    \\hline\n  \\end{tabular}\n\\end{sidewaystable}\n\n\n\n\\subsection{K-fold cross-validation results}\nfigures \\ref{fig:cv_rmse}. CV RMSE estimates \\ref{tab:cv_rmse}.\n\n\\afterpage{\\clearpage}\n\\begin{figure}[h]\n  \\centering\n  \\includegraphics[width=\\textwidth,height=0.8\\textheight,keepaspectratio=true]{figure/cv_rmse}\n  \\caption{Posterior estimates of the expected out-of-sample error based on 5 rounds of 5-fold cross-validation. Columns are by model type, rows are by taxonomic group.}\n  \\label{fig:cv_rmse}\n\\end{figure}\n\n\\begin{sidewaystable}\n  \\centering\n  \\caption{}\n  \\label{tab:cv_rmse}\n  \\begin{tabular}{rllll}\n    \\hline\n    Taxonomic group & Poisson Model Mean CV RMSE & Poisson Model SD CV RMSE & NegBin Model Mean CV RMSE & NegBin Model SD CV RMSE \\\\ \n    \\hline\n    Bivalvia & 3.51 & 0.13 & 4.18 & 0.08 \\\\ \n    Brachiopoda & 7.07 & 0.13 & 7.47 & 0.07 \\\\ \n    Gastropoda & 5.23 & 0.15 & 6.37 & 0.17 \\\\ \n    Trilobita & 3.52 & 0.07 & 4.36 & 0.05 \\\\ \n    \\hline\n  \\end{tabular}\n\\end{sidewaystable}\n\n\\subsection{Regression coefficients}\nfigures \\ref{fig:arth_coefs}, \\ref{fig:brach_coefs}, \\ref{fig:mol_coefs}.\n\n\\afterpage{\\clearpage}\n\\begin{figure}[h]\n  \\centering\n  \\includegraphics[width=\\textwidth,height=0.8\\textheight,keepaspectratio=true]{figure/arth_coefs}\n  \\caption{left: coefficients from the arthropod analysis. right: regression coefs for compositional variables back-transformed into composition units. theta is for binomial part (i.e. zeroes), lambda is for poisson or negative binomial part (i.e. non-zeroes)}\n  \\label{fig:arth_coefs}\n\\end{figure}\n\n\\afterpage{\\clearpage}\n\\begin{figure}[h]\n  \\centering\n  \\includegraphics[width=\\textwidth,height=0.8\\textheight,keepaspectratio=true]{figure/brach_coefs}\n  \\caption{left: coefficients from the brachiopod analysis. right: regression coefs for compositional variables back-transformed into composition units. theta is for binomial part (i.e. zeroes), lambda is for poisson or negative binomial part (i.e. non-zeroes)}\n  \\label{fig:brach_coefs}\n\\end{figure}\n\n\\afterpage{\\clearpage}\n\\begin{figure}[h]\n  \\centering\n  \\includegraphics[width=\\textwidth,height=0.8\\textheight,keepaspectratio=true]{figure/mol_coefs}\n  \\caption{left: coefficients from the mollusc analysis. right: regression coefs for compositional variables back-transformed into composition units. theta is for binomial part (i.e. zeroes), lambda is for poisson or negative binomial part (i.e. non-zeroes)}\n  \\label{fig:mol_coefs}\n\\end{figure}\n\n\n\\subsection{Predictive results}\nfigures \\ref{fig:pred_mean}, \\ref{fig:pred_sd}, \\ref{fig:pred_ecdf}, \\ref{fig:pred_root}, \\ref{fig:pred_avgerr}. rmse from prediction table \\ref{tab:test_rmse}.\n\n\\afterpage{\\clearpage}\n\\begin{figure}[h]\n  \\centering\n  \\includegraphics[width=\\textwidth,height=0.8\\textheight,keepaspectratio=true]{figure/pred_mean}\n  \\caption{Mean of unit diversity for testing dataset. Distribution is estimated from posterior, vertical line is observed. Columns are by model type, rows are by taxonomic group.}\n  \\label{fig:pred_mean}\n\\end{figure}\n\n\\begin{figure}[h]\n  \\afterpage{\\clearpage}\n  \\centering\n  \\includegraphics[width=\\textwidth,height=0.8\\textheight,keepaspectratio=true]{figure/pred_sd}\n  \\caption{Standard deviation of unit diversity for testing dataset. Distribution is estimated from posterior, vertical line is observed. Columns are by model type, rows are by taxonomic group.}\n  \\label{fig:pred_sd}\n\\end{figure}\n\n\\afterpage{\\clearpage}\n\\begin{figure}[h]\n  \\centering\n  \\includegraphics[width=\\textwidth,height=0.8\\textheight,keepaspectratio=true]{figure/pred_ecdf}\n  \\caption{Empirical cumulative distribution function of unit diversity for testing dataset; that is, rank order proportional accumulation. Distribution is estimated from posterior, dark line is observed. Columns are by model type, rows are by taxonomic group.}\n  \\label{fig:pred_ecdf}\n\\end{figure}\n\n\\afterpage{\\clearpage}\n\\begin{figure}[h]\n  \\centering\n  \\includegraphics[width=\\textwidth,height=0.8\\textheight,keepaspectratio=true]{figure/pred_root}\n  \\caption{Rootogram of unit diversity for testing dataset. Distribution is estimated from posterior, hanging histogram is is observed. If histogram is above x-axis, overestimate; if histogram is below x-axis, underestimate. Columns are by model type, rows are by taxonomic group.}\n  \\label{fig:pred_root}\n\\end{figure}\n\n\\afterpage{\\clearpage}\n\\begin{figure}[h]\n  \\centering\n  \\includegraphics[width=\\textwidth,height=0.8\\textheight,keepaspectratio=true]{figure/pred_avgerr}\n  \\caption{Average error of estimated unit diversity for testing dataset. Comparison is between observed diversity and estimated diversity. Columns are by model type, rows are by taxonomic group.}\n  \\label{fig:pred_avgerr}\n\\end{figure}\n\n\n\\begin{sidewaystable}\n  \\centering\n  \\caption{}\n  \\label{tab:test_rmse}\n  \\begin{tabular}{r|llll}\n    \\hline\n    Taxonomic group & Poisson model Mean CV RMSE & Poisson model SD CV RMSE & NegBin model Mean CV RMSE & NegBin model SD CV RMSE \\\\ \n    \\hline\n    Bivalvia & 2.21 & 1.30 & 5.11 & 2.89 \\\\ \n    Brachiopoda & 5.05 & 3.14 & 7.81 & 6.18 \\\\ \n    Gastropoda & 3.24 & 0.89 & 6.37 & 2.20 \\\\ \n    Trilobita & 1.81 & 0.99 & 4.18 & 1.07 \\\\ \n    \\hline\n  \\end{tabular}\n\\end{sidewaystable}\n\n\n\\end{document}\n", "meta": {"hexsha": "7ca9e264f513103873fadca029cf0126e7daf3a4", "size": 10461, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "analysis/doc/report.tex", "max_stars_repo_name": "psmits/not_fossil", "max_stars_repo_head_hexsha": "1fa6639757da9521731f36f0617ca44b3e7a3ec3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-20T19:44:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-20T19:44:52.000Z", "max_issues_repo_path": "analysis/doc/report.tex", "max_issues_repo_name": "psmits/notfossil", "max_issues_repo_head_hexsha": "1fa6639757da9521731f36f0617ca44b3e7a3ec3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "analysis/doc/report.tex", "max_forks_repo_name": "psmits/notfossil", "max_forks_repo_head_hexsha": "1fa6639757da9521731f36f0617ca44b3e7a3ec3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.2857142857, "max_line_length": 424, "alphanum_fraction": 0.7562374534, "num_tokens": 3059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.32515959830157803}}
{"text": "\\section{Proving Techniques}\n\nThe properties that have been proven can be divided into three types: Preconditions, Invariants and Post-conditions \\cite{meyer_1992}. Preconditions are properties that must be true before a function is called, post-conditions must be true after a function is called, and invariants are properties that must be true for all values of a certain type. In this section it will be shown that these three types of properties each have their own way to be proven in Agda.\n\n\\subsection{Finding properties to prove}\\label{finding_props_to_prove}\n\\cite{BREITNER2021} presents multiple techniques to find properties to prove from Haskell code. A few of those techniques have been selected that were deemed useful for this paper:\n\\begin{enumerate}\n\t\\item Define an invariant property when there are types whose correctness depend on invariants\n\t\t\\cite[p. 7]{BREITNER2021}\n\t\\item Define a post-condition property by deriving a definition directly from the test suite\n\t\t\\cite[p. 9]{BREITNER2021}\n\t\\item Define a precondition when there is a risk of numeric overflow, or switch to using unbounded integers instead. \n\t\t\\cite[p. 9]{BREITNER2021}\n\t\\item Define a post-condition when there are type classes which come with laws that all instances of the type class should satisfy\n\t\t\\cite[p. 10]{BREITNER2021}\n\\end{enumerate}\nFinally, one technique that was not mentioned in \\cite{BREITNER2021} was used:\n\\begin{enumerate}\n\t\\setcounter{enumi}{4}\n\t\\item Define a precondition if it is required to make the function total, as was described in section \\ref{total-functions}\n\\end{enumerate}\n\n\n\\subsection{Properties to prove}\\label{props_to_prove}\n\nInstead of defining a precondition when there is a risk of numeric overflow as described in technique 3, we switch to using unbounded integers in this papers' implementation of the QuadTree library. This is the same decision that \\cite{BREITNER2021} made. Furthermore, the test suite of the QuadTree library consists only of tests that test the type class laws, so no additional properties could be derived from technique 2. Using technique 1, 4, and 5, the following properties of the QuadTree library were derived: \n\n\\setlength{\\parindent}{0pt} \\setlength{\\parskip}{5pt}\n\\textbf{Invariants of a QuadTree:}\n\\begin{itemize}\n    \\item Depth invariant: The depth of a QuadTree must be less than or equal to \\linebreak $\\left \\lceil{log_{2}( max(width, height))}\\right \\rceil$. This is to ensure that there is exactly one value at each location. (Technique 1)\n    \\item Compression invariant: No node can have four leaves that are identical. These need to be fused into a single leaf quadrant. This is needed to keep the QuadTree fast and space efficient. (Technique 1)\n\\end{itemize} \n\\textbf{Preconditions of a QuadTree:}\n\\begin{itemize}\n    \\item When calling \\verb|atLocation|, \\verb|getLocation|, \\verb|setLocation| or \\verb|mapLocation|, the location must be inside of the QuadTree. (Technique 5)\n    \\item When calling \\verb|lensLeaf|, the quadrant needs to have a depth of zero (i.e.  it must be a leaf) (Technique 5)\n    \\item When calling \\verb|lensA/B/C/D|, the quadrant needs to have a depth that is greater than zero (i.e.  it must not be a leaf) (Technique 5)\n\\end{itemize} \n\\textbf{Post-conditions of a QuadTree:}\n\\begin{itemize}\n    \\item The lenses returned by all the lens functions satisfy the lens laws: \\cite{lens} (Technique 4)\n        \\begin{itemize}\n            \\item \\verb|view l (set l v s) = v| (Setting and then getting returns the value)\n            \\item \\verb|set l (view l s) s = s| (Setting the value to what it already was doesn't change anything)\n            \\item \\verb|set l v2 (set l v1 s) = set l v2 s| (Setting a value twice is the same as setting it once to the second value)\n        \\end{itemize}\n    \\item The functor implementations for Quadrant and QuadTree satisfy the functor laws (Technique 4)\n        \\begin{itemize}\n            \\item \\verb|fmap id = id| (Identity law)\n            \\item \\verb|fmap (f . g) == fmap f . fmap g| (Composition law)\n        \\end{itemize}\n    \\item The foldable implementation returns an output of the correct length (Technique 4)\n        \\begin{itemize}\n            \\item \\verb|length quadtreeFoldable vqt = width * height|\n        \\end{itemize}\n    \\item The foldable implementation satisfies the foldable-functor law (Technique 4)\n        \\begin{itemize}\n            \\item \\verb|foldMap f = fold . fmap f|\n        \\end{itemize}\n\\end{itemize}\n\t\n\\setlength{\\parindent}{15pt} \\setlength{\\parskip}{0pt}\n\\subsection{Techniques to prove invariants} \\label{prove_invariants}\nInvariants are proven by creating a new datatype with one constructor, which takes the original datatype and a proof for all the invariants. As a simple example, this datatype represents a natural number with the invariant that it is greater than 5.\n\\begin{minted}{agda}\ndata GreaterThanFive : Set where\n  CGreaterThanFive : (n : Nat) -> { .( IsTrue (n > 5) ) } -> GreaterThanFive\n\\end{minted}\nThe proof is marked as implicit \\{\\} so that it is removed when compiled to Haskell, and it is marked as as irrelevant .() so that will not interfere when proving post-conditions later. An irrelevant value means that the actual value of the proof does not matter, only its existence does.\n\nUsing this technique, the datatype for a compressed quadrant with a certain maximum depth is: \n\\begin{minted}{agda}\ndata VQuadrant (t : Set) {depth : Nat} : Set where\n  CVQuadrant : (qd : Quadrant t) \n            -> {.(IsTrue (depth qd <= depth && isCompressed qd))} \n            -> VQuadrant t {depth}\n\\end{minted}\nThe datatype for a valid QuadTree is defined very similarly. Agda2hs flawlessly compiles this to the following Haskell code, where the proof is erased:\n\\begin{minted}{haskell}\ndata VQuadrant t = CVQuadrant (Quadrant t)\n\\end{minted}\n\nThe advantage of making a new wrapper datatype over adding the proofs to the original datatype is that if the original datatype has multiple constructors, functions that use the proof do not need to be split into multiple cases (one for each constructor). The disadvantage is that this additional wrapper type is visible when compiled to Haskell. To avoid this, it is possible to create an additional function for all public functions. This function then takes the invariance proof as a precondition, and calls the original function with the wrapper type. \n\n\\subsection{Techniques to prove preconditions}\nIn this section, two techniques to prove preconditions are presented.\n\n\\subsubsection{Using an implicit argument} \\label{using_implicit}\nWhen using the implicit argument technique, preconditions are proven by adding the proofs as implicit arguments to the function.\nAs a simple example, this function takes a natural number that must be greater than 5.\n\\begin{minted}{agda}\ntakesGtFive : (n : Nat) -> { .( IsTrue (n > 5) ) } -> ?\n\\end{minted}\nAs with invariants, the proof is marked as implicit and irrelevant. \n\nUsing this technique, a precondition can be used to ensure that the location given to the \\verb|getLocation| function must be inside the QuadTree:\n\\begin{minted}{agda}\n-- Function that checks if a location is inside a given QuadTree\nisInsideQuadTree : (Nat × Nat) -> QuadTree t -> Bool\nisInsideQuadTree (x , y) (Wrapper (w , h) _) = x < w && y < h\n\ngetLocation : (loc : Nat × Nat) -> (qt : QuadTree t) \n    -> {.( IsTrue (isInsideQuadTree loc qt) )} -> t\n\\end{minted}\nAfter being compiled with Agda2hs, the precondition is removed from the function, just like with invariants.\n\\begin{minted}{haskell}\ngetLocation :: (Nat, Nat) -> QuadTree t -> t\n\\end{minted}\n\n\\subsubsection{Using a datatype with invariants}\nAnother technique to prove preconditions is by passing in a datatype with an invariant, as was used in section \\ref{prove_invariants}. The simple example from \\ref{using_implicit} would then be written like this, using the type defined in section \\ref{prove_invariants}:\n\\begin{minted}{agda}\ntakesGtFive : (n : GreaterThanFive) -> ?\n\\end{minted}\n\nFor the QuadTree verification, this technique was used to encode the maximum depth properties of the lens functions, using the same datatype that was defined for the invariants.\n\\begin{minted}{agda}\nlensLeaf : Lens (VQuadrant t {0}) t\nlensA : {dep : Nat} \n    -> Lens (VQuadrant t {S dep}) (VQuadrant t {dep})\n\\end{minted}\n\n\\subsubsection{Comparison}\nThe advantages of using implicit arguments is that it is not necessary to define a separate datatype, and that the precondition can be dependent on more than one parameter of the function. On the other hand, the advantages of using a datatype with an invariant is that the defined function are cleaner and more compact. It is then also possible to use the type as a parameter for another type, like it is used in \\verb|lensLeaf| and \\verb|lensA|. It also allows for cleaner reuse of the property, as it does not need to be repeated each time it is used.\n\n\\subsection{Techniques to prove post-conditions}\nPost-conditions are proven as separate functions. As a simple example, this is a proof that this function returns a number greater than 5.\n\\begin{minted}{agda}\ngt5 : Bool -> Nat\ngt5 _ = 42\n\ngt5-is-gt5 : (b : Bool) -> IsTrue (gt5 b > 5)\ngt5-is-gt5 b = IsTrue.itsTrue\n\\end{minted}\n\nFor the QuadTree verification, this technique was used to verify the lens laws of all the lenses defined in the implementation. For example, this is the proof that the ViewSet law holds for \\verb|lensLeaf|.\n\\begin{minted}{agda}\nValidLens-Leaf-ViewSet : \n    -> (v : t) (s : VQuadrant t {0}) \n    -> view (lensLeaf {t}) (set (lensLeaf {t}) v s) ≡ v\nValidLens-Leaf-ViewSet v (CVQuadrant (Leaf x)) = refl\n\\end{minted}\n\nWhen proving preconditions and invariants, these properties have to be marked as irrelevant. This is to ensure that when proving that two function calls are equal, one does not need to show that the proofs of the preconditions and invariants are equal, since the actual value of the proofs is irrelevant.\n\n\\subsection{Results} \\label{results}\nAll of the properties mentioned in section \\ref{props_to_prove} have been successfully proven. Most of these proofs have not been shown in the paper, since they are available in the source code. The amount of lines of code that this took is shown in figure \\ref{division}.  This counts all non-empty lines. The verification took about 3 times more lines of code than the implementation. While this comparison is an indication, this should not be taken to mean that the verification took 3 times as much effort, as the information density of the implementation and proofs is different.\n\nIn reality, the implementation took approximately one full-time week, while the verification took approximately five full-time weeks. This too should not be taken to mean the verification took 5 times as much effort, as this number may be biased by the fact that the implementation was just a translation from Haskell.\n\nDuring the verification phase, one bug was found in this papers implementation of QuadTree that was accidentally introduced during the translation to Agda. This was not caught by the tests, though this may be because the tests on the foldable implementation are very limited.\n\nWhether the verification is worth the time spent, depends on the situation. For example, in a situation where even one small error could bring down an airplane, this is clearly worth it. However, in many common situations, this verification may not be worth it.\n\n\\begin{figure}[H]\n\t\\begin{tikzpicture}[scale=0.8]\n\t\t\\pie[sum=auto]\n\t\t{757/Implementation,\n\t\t\t545/General Proofs,\n\t\t\t789/Foldable Proofs,\n\t\t\t809/Lens Proofs,\n\t\t\t215/Functor Proofs}\n\t\\end{tikzpicture}\n\t\\caption{Division of lines of code}\n\t\\label{division}\n\\end{figure}", "meta": {"hexsha": "aac40da8da9195f25d13603bd01f04791bb1ed8c", "size": 11713, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/sections/4_proving.tex", "max_stars_repo_name": "JonathanBrouwer/research-project", "max_stars_repo_head_hexsha": "4959a3c9cd8563a1726e0e968e6a179008cd4d9f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-25T09:10:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-25T09:10:20.000Z", "max_issues_repo_path": "paper/sections/4_proving.tex", "max_issues_repo_name": "JonathanBrouwer/research-project", "max_issues_repo_head_hexsha": "4959a3c9cd8563a1726e0e968e6a179008cd4d9f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/sections/4_proving.tex", "max_forks_repo_name": "JonathanBrouwer/research-project", "max_forks_repo_head_hexsha": "4959a3c9cd8563a1726e0e968e6a179008cd4d9f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 70.1377245509, "max_line_length": 584, "alphanum_fraction": 0.7565098608, "num_tokens": 2972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.32515959830157803}}
{"text": "\\chapter{Conclusions}\\label{concl}\n\\thispagestyle{plain}\n\nIn this thesis three machine learning algorithms have been used to create models aimed at predicting glaciers ice thickness.\n\nIn order to do so, the GlaThiDa, a database containing ice thickness observations of glaciers all over the world has been linked to the RGI, a database of glaciers outlines which include over 215,000 glaciers and represents all glaciers and ice caps in the globe. Of all the observations in GlaThiDa, 96.6\\% have been associated with glaciers in the RGI, summing up to a total of only 771 glaciers worldwide with ice thickness observations. In many glaciers only few observations have been reported in the GlaThiDa, and some regions completely lack ice thickness measurements.\n\nIn order to create a data set to train the machine learning models, the Open Global Glacier Model has been used. This model provided the tools to merge together the relevant digital elevation models for each glacier, and compute gridded geometrical features such as: the topography, the distance from the border of the glacier, the slope angle and the altitude dependent linear mass balance.\n\nWith this data three different machine learning models, linear regression, random forest regression and support vector regression, have been trained using only observations available for the alpine region. To avoid over-fitting the models, and to be able to assess their performances, each model has been trained with 20 different sub-samples, each containing 75\\% of data points available. The $R^2$ coefficient, also called score, calculated over the resulting 25\\% of the data, has been chosen as a value to assess the performances of each model. The best performing model on average was the support vector regression with an average $R^2 = 0.55$. The spread of the score between the models trained with the different sub-samples has been found particularly high with much lower scores for some specific sub-samples. This is true for the three different machine learning algorithms used, as all of them showed drops in score for samples 5, 14 and 19. This behavior could be explained by the fact that the sub-sample left out for training in these 3 cases was particularly hard to predict but might also be a sign of over-fitting.\nThe model achieving the highest score when training them over the whole sample has been the random forest regression with a score of 0.57.\n\nAfter the models have been trained the relevance of each feature in the models predictions has been analyzed. The mass balance was the most relevant feature for both the random forest and support vector regression, but for the linear regression it was the slope angle. Those two features however proved to be relevant for the predictions of all the models. Altitude and distance from the border seem to be much less important for the predictions of both the random forest and the linear regression model, while still being relevant for the support vector regression. The importance of mass balance and slope angle in determining the ice thickness of glaciers, is in accordance with the general theory of ice dynamics in glaciers.  \n\nThe trained machine learning models have been used to estimate the ice thickness of each of the glaciers in the Alps. The results have been compared to those obtained by \\citet{Farinotti2019} (F19). All the machine learning models have been found to predict very different volumes compared to the ones predicted in the \\citet{Farinotti2019}. The linear regression is the only model which predicted a total ice volume larger than the one from F19 by over 9\\%. The random forest and support vector machine predicted a total volume respectively 22\\% and 25\\% lower than F19. These two models in fact seem to underestimate the ice thickness for large glaciers, leading to low volume values for those glaciers and hence for the whole region. Larger glaciers are essential in estimating the total volume of ice but are also outliers in the per-volume distribution of glaciers in the alps. The machine learning algorithms seem then unfit to make predictions about these larger glaciers. This could be explained by the fact that the models were not able to learn the patterns of these large glaciers, due to the fact that they had no information about them in the training data-set. \n\nWhen comparing the performances of the machine learning models to those of the single models used by \\citet{Farinotti2019}, using the observations as reference, the tendency of the machine learning models to underestimate ice thickness has been furthered confirmed. In contrast two physical models showed an opposite trend predicting larger values more often than lower ones and the other two seem to have low bias in the predictions, predicting equally lower or higher ice thickness values compared to the observations. The reason for the machine learning models underestimating the ice thickness of glaciers is probably related to the training data-set being skewed towards the presence of low ice thickness values. \n\nIn conclusion, the machine learning algorithms have not been very accurate in estimating the ice thickness for Alpine glaciers, using the features chosen as input values. This applies particularly to large glaciers, for which the models seem unable to replicate accurate ice thicknesses.\n\nA lot could be done to improve the machine learning models performances. \nOne of the first thing to try could be the usage of different machine learning algorithms to train the model. An example could be the use of artificial neural networks as in the work of \\citet{Clarke2009}, which was however not based on real glacier data but on artificially grown ones. Artificial neural networks have in fact shown a lot of real life applications in the last years due to their accurate performances, and seeing how they would perform on the problem of estimating glacier ice thickness could be very interesting.\n  \nUsing more and different features could also be a very interesting possibility. Adding the mass balance based on the catchment basins could already be a big improvement on the mass balance used. A smoothed version of this would be ideal but even the non-smoothed one could be beneficial. Even if the ice thickness distribution would look unrealistic, it could still lead to better estimates for glacier volumes. Climate data like precipitation and temperature could also be used as they could be helpful in recognizing differences between glaciers.\n\nIncreasing the grid resolution could also improve the models performances. Many measurements have been in fact agglomerated into single ones, due to the fact that they were all falling inside the same grid cell. Having more measurements could give the machine learning algorithms more room to learn. This could however also skew the predictions of the algorithms, as glaciers with many more observations could have a much higher influence in the training process than those with few ones. \n \nFurther research could also look into the data from other regions included in the GlaThiDa database.  This thing in particular could lead to models able to predict glaciers ice thickness for those regions, better than the models trained in this thesis. In fact, if the observations for those regions were covering a wider spectrum of ice thickness and feature values, the models could be trained with data better representing the whole distribution of glaciers for the inspected region. As machine learning models can only learn from the data fed to them, those data are in fact extremely important for thje outcome of the prediction.\n \nFinally, the importance of collecting measurements for a wide spectrum of values, is something to be taken into account for the future. A data-set covering the distribution of glaciers as well as possible, is in fact very important for statistical glacier models, but also for the validation of the physically based ones. The importance of this problem could then be taken into consideration, when choosing where to lead future campaigns to collect ice thickness measurements.\n", "meta": {"hexsha": "2db30e85b6c2978b70ca31f989a7452d73e3f494", "size": 8111, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "conclusion.tex", "max_stars_repo_name": "MatCast/master-thesis", "max_stars_repo_head_hexsha": "57ab7ea67d1dfc059aa78ffb6de6ad89989cfa70", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "conclusion.tex", "max_issues_repo_name": "MatCast/master-thesis", "max_issues_repo_head_hexsha": "57ab7ea67d1dfc059aa78ffb6de6ad89989cfa70", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "conclusion.tex", "max_forks_repo_name": "MatCast/master-thesis", "max_forks_repo_head_hexsha": "57ab7ea67d1dfc059aa78ffb6de6ad89989cfa70", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 261.6451612903, "max_line_length": 1175, "alphanum_fraction": 0.8172851683, "num_tokens": 1555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.324908933370279}}
{"text": "\\chapter{Colour spaces and systems}\n\\label{s:spaces}\n\\ohead{Appendix: Colour spaces and systems}\n\nThe colour information used in this book is reported in a wide\nvariety of colour spaces. The main colour space used in my own\nexperiments is CIE 1967 $L^*a^*b^*$, but data reported in incorporated\nstudies are often reported in other colour systems. Some studies\n\\citep[e.g.][]{lillo07locating} used the CIE 1967 $L^*u^*v^*$ colour\nspace whereas others \\citep[e.g.][]{sturges95location} used the\nMunsell colour system to report their results. The vision system of\nthe Sony humanoid robots uses the YCbCr colour model to encode the\ncolour information of the objects they perceive.\n\nThis chapter introduces the different colour spaces and systems and\nthe functions that are used to convert this data from one colour\nsystem into another, as shown in \\figref{f:conversions}. Some\nconversions are impossible to compute in one step and hence require\nsome intermediary steps. Most of these functions are based on Bruce\nLindblooms's website.\\footnote{\\url{http://www.brucelindbloom.com}}\n\n\\begin{figure}[htb]\n\\begin{center}\n\\includegraphics[width=.8\\textwidth]{./spaces/figures/conversions.pdf}\n\\caption[Conversion diagram between different colour models and\nspaces]{A diagram representing the conversions between the different\n  colour models and spaces. To convert colour information from the\n  YCbCr colour model to the CIE 1967 $L^*a^*b^*$ colour space for\n  example, it first needs to be converted to RGB which can be\n  converted to CIE 1931 XYZ which can finally be converted to CIE 1967\n  $L^*a^*b^*$.}\n\\label{f:conversions}\n\\end{center}\n\\end{figure}\n\n\\section{CIE 1931 XYZ colour space}\n\\label{s:xyz}\n\\is{colour space!CIE 1931 XYZ}\n\\is{CIE 1931 XYZ|see{colour space}}\n\nCentral to the conversion diagram (\\figref{f:conversions}) is the\nXYZ colour space. The XYZ colour space was established by the\nCommission Internationale de l'Eclairage (CIE) in 1931. It standardised\nthe colour-matching functions which describe how to combine the\ndifferent amounts of primaries into unique colours and how to establish\nthe primaries themselves. It was based on two experiments\n\\citep{wright28, guild31} which independently estimated the\ncolour-matching functions for humans with normal colour vision, based\non the principles of trichromacy and Grassmann's laws of additive\ncolour mixture. The experiments matched to such a level of degree that\nthe CIE decided to put them forward as the standard set of\ncolour-matching functions.\n\nAlthough the XYZ primaries are based on studies of human subjects,\nthey are imaginary and do not map directly on the primaries\nestablished by the studies. This is mainly done to eliminate some\nmathematical properties of the original colour-matching functions and\nto incorporate the results into the previously established system of\nphotometry. More exactly, the primaries for X and Z are imaginary as\nthey do not produce any luminance response, whereas the primary for Y\nis the luminance response \\citep{fairchild98color}.\n\n\\subsection{Illuminants and chromatic adaptation}\n\nAs the appearances of colours change under different light sources,\nthese sources are also incorporated in the model as idealised\nilluminants which reflect their spectral power distribution. These\ndistributions determine how much each wavelength contributes to the\ntotal illumination. Some of them, such as illuminant A, try to model a\ntypical domestic lighting, whereas others, such as illuminants C and\nD65, try to reconstruct natural daylight conditions. In all reported\nexperiments, D65 is used as standard illuminant. For each illuminant a\nreference white can be defined which represents the colour white\nunder such illuminant. The reference whites for some illuminants are\nshown in \\tabref{t:reference-whites}.\n\n\\begin{table}\n\\begin{center}\n\\begin{tabular}{cd{7}d{7}d{7}}\n\\lsptoprule\nIlluminant & \\multicolumn{1}{c}{X} & \\multicolumn{1}{c}{Y} & \\multicolumn{1}{c}{Z} \\\\\n\\midrule\nA & 1.09850 & 1.00000 & 0.35585 \\\\\nC & 0.98074 & 1.00000 & 1.18232 \\\\\nD65 & 0.95047 & 1.00000 & 1.08883 \\\\\n\\lspbottomrule\n\\end{tabular}\n\\end{center}\n\\caption{Reference white tristimulus values for illuminants A, C and D65}\n\\label{t:reference-whites}\n\\end{table}\n\nTo adapt $XYZ$ values from one illuminant to another, several\nchromatic adaptation algorithms have been proposed. All these\nalgorithms first transform the $XYZ$ values into the cone response\ndomain before scaling the actual values depending on the source and\ntarget illuminant. The algorithms differ in how they do the\ntransformation to the cone response domain. The Bradford method is\nconsidered to be the best one.\n\nAll steps of this transformation can be compiled into one matrix\nmultiplication. To convert from illuminant C to illuminant D65,\nEquation \\ref{e:c-to-d65} was used.\\footnote{More chromatic\n  transformations can be found on Bruce Lindbloom's website:\\\\\n  \\url{http://www.brucelindbloom.com/Eqn_ChromAdapt.html}.}\n\n\\begin{equation}\n\\begin{bmatrix}\n  X_{D65} \\\\ Y_{D65} \\\\ Z_{D65}\n\\end{bmatrix}\n= \\left[\n\\setlength{\\arraycolsep}{5pt} \\sisetup{group-digits = false}\n\\begin{array}{S[table-format=2.7] S[table-format=2.7] S[table-format=2.7]}\n 0.9904476 & -0.0071683 & -0.0116156 \\\\\n-0.0123712 & 1.0155950 & -0.0029282 \\\\\n-0.0035635  & 0.0067697 & 0.9181569\n\\end{array}\n\\right]\n\\begin{bmatrix}\n  X_{C} \\\\ Y_{C} \\\\ Z_{C}\n\\end{bmatrix}\n\\label{e:c-to-d65}\n\\end{equation}\n\n\\subsection{Chromaticity diagrams and CIE xyY colour space}\n\\is{colour space!CIE xyY}\n\\is{CIE xyY|see{colour space}}\n\nChromaticity diagrams were developed to provide a convenient\ntwo-dimensional representation of colour which removes the luminance\ninformation. This is a\\-chieved by means of a one-point perspective\nprojection onto the unit plane of the XYZ colour space. The\ntransformation from the $XYZ$ coordinates to the $xy$ plane can be\ncomputed using Equations in \\ref{e:xyz-to-xyy}.\n\n\\begin{equation}\nx = \\frac{X}{X + Y + Z} \\qquad\ny = \\frac{Y}{X + Y + Z} \\qquad\nz = \\frac{Z}{X + Y + Z}\n\\label{e:xyz-to-xyy}\n\\end{equation}\n\nGiven the nature of the projection the third chromaticity coordinate\n$z$ can always be computed from the other two because the three sum\nto unity. $z$ can also be computed using Equation \\ref{e:xy-to-z}.\n\n\\begin{equation}\nz = 1.0 - x - y\n\\label{e:xy-to-z}\n\\end{equation}\n\nThe inverse transformation from chromaticy coordinates $x$ and $y$ can\nonly be computed when one of the original tristimulus values is\ngiven. In most cases this is the luminance value $Y$. The inverse\ntransformation from xyY to XYZ is computed using Equations\n\\ref{e:xyy-to-xyz}\n\n\\begin{equation}\nX = \\frac{xY}{y} \\qquad\nZ = \\frac{zY}{y} =  \\frac{(1.0-x-y)Y}{y}\n\\label{e:xyy-to-xyz}\n\\end{equation}\n\n\\section{CIE 1976 L*a*b*}\n\\label{s:lab}\n\\is{colour space!CIE 1976 \\emph{L*a*b*}}\n\\is{CIE 1976 \\emph{L*a*b*}|see{colour space}}\n\n\nThe CIE 1976 \\emph{L*u*v*} and \\emph{L*a*b*} (CIELUV and CIELAB for\nshort) colour spaces were designed to provide uniform practices for\nthe measurement of colour differences. To determine the colour\ndifference ($\\Delta E^*_{ab}$ or $\\Delta E^*_{uv}$) it suffices to use\nthe Euclidean distances between two colours represented in these\nspaces. To achieve this goal, the colour spaces are extended with\ndimensions that correlate to lightness, chroma and hue. These spaces\nalso incorporate features to account for chromatic adaptation and\nnonlinear visual responses.\n\nIn the CIELAB space, the \\emph{L*} dimension represents lightness, the\n\\emph{a*} dimension approximately redness-greenness and the \\emph{b*}\ndimension approximately yellow\\-ness-blueness. Chroma ($C^*_{ab}$) and\nhue ($h_{ab}$) can be computed by the Equations in\n\\ref{e:lab-chroma-hue}. The value for \\emph{L*} ranges from 0 (black)\nto 100 (white). The values for \\emph{a*} and \\emph{b*} can be both\npositive and negative and are only limited by the physical properties\nof materials.  $h_{ab}$ is expressed as an angle in degrees. The\n\\emph{L*}, $C^*_{ab}$ and $h_{ab}$ form a cylindrical representation\nof the same space.\n\n\\begin{equation}\nC^*_{ab} = \\sqrt{\\left(a^{*^2} + b^{*^2} \\right)} \\qquad h_{ab} = \\tan^{-1} \\frac{b^*}{a^*}\n\\label{e:lab-chroma-hue}\n\\end{equation}\n\n\\subsection*{Conversion}\n\nThe equations to convert CIE 1931 XYZ coordinates to CIE 1976\n\\emph{L*a*b*} coordinates are shown in Equations\n\\ref{e:xyz-to-lab-first}-\\ref{e:xyz-to-lab-last}, where $\\epsilon$ and\n$\\kappa$ have identical values as defined in Equations \\ref{e:epsilon}\nand \\ref{e:kappa}. This conversion requires a reference white\n$\\begin{bmatrix}X_r & Y_r & Z_r\\end{bmatrix}$ which for my experiments\nis chosen based on illuminant D65 (see \\tabref{t:reference-whites}).\n\n\\begin{align}\nL^{*}& = 116f_y - 16\n\\label{e:xyz-to-lab-first} \\\\\na^{*}& = 500(f_x - f_y) \\\\\nb^{*}& = 200(f_x - f_y) \\\\\nf_x& = \\left\\{\n\\begin{aligned}\n&\\sqrt[\\leftroot{-1}\\uproot{2}3]{x_r} & \\quad x_r > \\epsilon \\\\\n&\\frac{\\kappa x_r + 16}{116} & \\quad x_r \\leq \\epsilon\n\\end{aligned}\n\\right. \\\\\nf_y& = \\left\\{\n\\begin{aligned}\n&\\sqrt[\\leftroot{-1}\\uproot{2}3]{y_r} & \\quad y_r > \\epsilon \\\\\n&\\frac{\\kappa y_r + 16}{116} & \\quad y_r \\leq \\epsilon\n\\end{aligned}\n\\right. \\\\\nf_z& = \\left\\{\n\\begin{aligned}\n&\\sqrt[\\leftroot{-1}\\uproot{2}3]{z_r} & \\quad z_r > \\epsilon \\\\\n&\\frac{\\kappa z_r + 16}{116} & \\quad z_r \\leq \\epsilon\n\\end{aligned}\n\\right. \\\\\nx_r& = \\frac{X}{X_r} \\\\\ny_r& = \\frac{Y}{Y_r} \\\\\nZ_r& = \\frac{Z}{Z_r}\n\\label{e:xyz-to-lab-last}\n\\end{align}\n\n\\section{CIE 1976 L*u*v*}\n\\label{s:luv}\n\\is{colour space!CIE 1976 \\emph{L*u*v*}}\n\\is{CIE 1976 \\emph{L*u*v*}|see{colour space}}\n\nThe CIELUV space is very similar to the CIELAB space: \\emph{L*}\nrepresents lightness, \\emph{u*} redness-greenness, \\emph{v*}\nyellowness-blueness. Chroma $C^*_{uv}$ and hue $h_{uv}$ values can be\ncomputed using the Equations in \\ref{e:luv-chroma-hue}.\n\n\\begin{equation}\nC^*_{uv} = \\sqrt{\\left(u^{*^2} + v^{*^2} \\right)} \\qquad h_{uv} = \\tan^{-1} \\frac{v^*}{u^*}\n\\label{e:luv-chroma-hue}\n\\end{equation}\n\n\\subsection*{Conversion}\n\nThe equations to convert CIELUV coordinates to CIE 1931 XYZ\ncoordinates are shown in Equations\n\\ref{e:luv-to-xyz-first}-\\ref{e:kappa}. This conversion requires a\nreference white based on an illuminant $\\begin{bmatrix}X_r & Y_r &\n  Z_r\\end{bmatrix}$ which for my experiments is chosen to be\nilluminant D65 (see \\tabref{t:reference-whites}).\n\n\\begin{align}\nX& = \\frac{d - b}{a - c} \n\\label{e:luv-to-xyz-first} \\\\\nY& = \n\\left\\{\n\\begin{aligned}\n&\\left(\\frac{(L + 16)}{116}\\right)^3& \\quad L > \\kappa\\epsilon \\\\\n&\\frac{L}{\\kappa}& \\quad L \\leq \\kappa\\epsilon\n\\end{aligned} \n\\right. \\\\\nZ& = Xa + b \\\\\na& = \\frac{1}{3}\\left(\\frac{52L^{*}}{u^{*}13Lu_0}-1\\right) \\\\\nb& = -5Y  \\\\\nc& = -\\frac{1}{3} \\\\\nd& = Y \\left(\\frac{39L^{*}}{v^{*}+13Lv_0} - 5\\right) \\\\\nu_0& = \\frac{4X_r}{X_r + 15Y_r + 3 Z_r}  \\\\\nv_0& = \\frac{9Y_r}{X_r + 15Y_r + 3 Z_r}  \\\\\n\\epsilon& = \\frac{216}{24389} \n\\label{e:epsilon} \\\\\n\\kappa& = \\frac{24389}{27}\n\\label{e:kappa}\n\\end{align}\n\n\\section{Munsell colour system}\n\\label{s:munsell}\n\\is{colour system!Munsell}\n\\is{Munsell colour system|see{colour system}}\n\nIn the Munsell colour system, a colour is defined based on three\ndimensions: hue, value (or lightness) and chroma (or purity). The hue\ndimension is divided in 5 principal colours: red, yellow, green, blue\nand purple, and a number of intermediate hues as shown in \\figref{f:munsell-colour-wheel}. Value, or lightness, is divided in 10\nsteps ranging from black (value 0) to white (value 10). Chroma\nrepresents the purity of a colour and the maximal possible chroma is\ndependent on the values of the hue-value pair. The three dimensions\nare shown in a diagram in \\figref{f:munsell-diagram}.\n\n\\begin{figure}[htbp]\n\\centering\n\\subfigure[]{\n  \\includegraphics[height=5cm]{./spaces/figures/munsell-colour-wheel.pdf}\n  \\label{f:munsell-colour-wheel}\n}\n\\subfigure[]{\n  \\includegraphics[height=5cm]{./spaces/figures/Munsell-system-Jacob-Rus.pdf}\n  \\label{f:munsell-diagram}\n}\n\\caption[The Munsell colour system]{\\subref{f:munsell-colour-wheel}: a colour wheel representing different hue values in the Munsell colour system; \\subref{f:munsell-diagram}: a diagram representing the three dimensions of the Munsell colour system: hue, value and chroma. (CC-BY-SA Jacob Rus)}\n\\end{figure}\n\n\\subsection{Development}\n\nThe original goals of Albert H. Munsell were to develop a system that\nis both psychophysically equidistant, meaning that it faithfully\nrepresents the differences between different colours as experienced by\nhuman subjects, and precisely applicable.\n\nThe development of the Munsell hue and chroma scales, which lead to\npublication of the first \\textit{Book of Color} in 1929, is poorly documented\n\\citep{berns82development}. Only the research leading to the scale for\nvalue has been properly documented but was based on the judgment of a\nlow number of human subjects (six to fourteen). A projection of the\ncolour samples in the Book of Color of 1929 on the \\emph{a*b*} plane\nof the CIE \\emph{L*a*b*} colour space is shown in \\figref{f:book-of-color-1929}.\n\n\\begin{figure}[htbp]\n\\begin{center}\n\\includegraphics[width=.8\\textwidth]{./spaces/figures/book-of-color-1929.pdf}\n\\caption[Colour samples of The Munsell Book of Color of 1929]{A projection of the colour samples that appear in the Munsell \\textit{Book of Color} of 1929 on the \\emph{a*b*} plane of the CIE \\emph{L*a*b*} colour space.}\n\\label{f:book-of-color-1929}\n\\end{center}\n\\end{figure}\n\nMost of the shortcomings have been addressed in a follow-up study\n\\citep{newhall42final}, which critically reviewed and extensively\nrevised all three dimensions based on the judgment of fourty\nparticipants and on more recent psychophysical findings. This study\nalso enlarged the Munsell solid to incorporate all colours within the\nMacAdam limits, which is the theoretical maximum visual reflectance\nfactor for specified chromaticities \\citep{macadam35maximum}. A\nprojection of the resulting colour samples on the \\emph{a*b*} plane of\nthe CIE \\emph{L*a*b*} colour space is shown in \\figref{f:munsell}. These colour samples clearly cover a wider range of \\enlargethispage{\\baselineskip}\npossible colours when compared to those of the Book of Color in \\figref{f:book-of-color-1929}.\n\n\\begin{figure}[htbp]\n\\begin{center}\n\\includegraphics[width=.8\\textwidth]{./spaces/figures/real.pdf}\n\\caption[Colour samples resulting from a study by\n\\citeauthor{newhall42final}]{A projection of the colour samples\n  resulting from the study by \\citeauthor{newhall42final} on the\n  \\emph{a*b*} plane of the CIE \\emph{L*a*b*} colour space.}\n\\label{f:munsell}\n\\end{center}\n\\end{figure}\n\n\\subsection{Conversion}\n\nThe Munsell Color Science Laboratory, a research laboratory supported\nby the Munsell Color Foundation at the Rochester Institute of\nTechnology, released three datafiles\\footnote{Publicly available at\n  \\url{http://www.cis.rit.edu/mcsl/online/munsell.php}.} which map\ncolour chips from the Munsell colour system to corresponding CIE $xyY$\ncoordinates. One of these datafiles lists all Munsell colour chips\nwithin the MacAdam limits as reported by \\citet{newhall42final}. The\ncoordinates of most of these colours chips are only approximations\nwhich are extrapolated or interpolated from a set of measurements of a\nsmall subset of chips.\n\nAll coordinates stored in these datafiles use illuminant C. Care has\nbeen taken to convert them to illuminant D65, using Equation\n\\ref{e:c-to-d65}, as this is the illuminant assumed in all experiments\nreported in this book.\n\n\\section{Natural Color System}\n\\label{s:NCS}\n\\is{colour system!Natural}\n\\is{NCS|see{Natural Color System}}\n\\is{Natural Color System|see{colour system}}\n\nThe Natural Color System (NCS) is a proprietary colour system is based on \nHering's opponent-colour theory. A colour is defined by three attributes:\n\\emph{blackness} (s), \\emph{chromaticness} (c) and \\emph{hue}\n($\\varphi$). A yellow colour for example can be described as 0580-Y10R,\nwhere 05 corresponds to 5\\% blackness, 80 to 80\\% chromaticness and\nY10R to a hue of 90\\% yellow and 10\\% red.\n\nConverting colours reported in the Natural Color System can be done\nmost precisely using a lookup table (SIS SS 19104), which describes\ntristimulus values for NCS coordinates and can be obtained from national\nstandardization offices. \\cite{derefeldt86transformation} report on an\napproximative method to transform NCS coordinates to the CIE\n$L^*a^*b^*$ colour space. In this book, I use the NCS navigator \nsoftware\\footnote{Available online at \\url{http://www.ncscolour.com}.}\nto compute the same conversion. This software is more precise \nthan the method suggested by \\cite{derefeldt86transformation}, but returns \nonly integer values in the CIE $L^*a^*b^*$ colour space. Moreover, not all\ncolour samples are present in the software. Whenever a colour sample\\enlargethispage{\\baselineskip}\nwas missing in the software, it was approximated using the nearest\ncolour sample that was available in the software.\n\n\\section{RGB}\n\\label{s:RGB}\n\\is{colour model!RGB}\n\\is{RGB|see{colour model}}\n\nRGB is a technical colour model that is used in a wide range of\ndevices, such as in television sets and computer screens, to reproduce\ncolours. It is highly device-dependent as each RGB device comes with\nits own colour profile and needs to be approached with considerable\ncare when used in colour research. Efforts have been made to define a\ncommon colour profile that could be supported by any RGB device, but\nthese can at best be simulated on RGB devices that are commonly used\nas they are not natively supported.\n\nAnother important aspect of the RGB colour model is the gamma\ncorrection, which is used to counter the non-linearity between the\nvoltage applied to electrons and the resulting brightness on a\nscreen. This correction can be approximated by raising the values by a\npower of gamma, which for most devices has a value of 2.2. Before RGB\nvalues are transmitted to a screen, they can be gamma compressed by\nraising to the power of the inverse of gamma.\n\nOn a final note, RGB devices are not capable of reproducing all\ncolours of the complete colour gamut, but of reproducing rather a\n(small) subset of it. For example, both the Adobe RGB (1998) and\nPAL/SECAM colour profile encode only half of the complete gamut. This\nis the reason why some of the colour chips that are known to be foci\nof basic colour categories, such as orange, can not be reproduced on\nan everyday colour device.\n\nThe equations to convert any XYZ value using the D65 reference white,\nto an RGB value for a device that is using the Adobe RGB (1998) colour\nprofile and a gamma correction of $\\gamma$ is shown in Equations\n\\ref{e:xyz-rgb-first} and \\ref{e:xyz-rgb-last}. When the values for\n$R_t$, $G_t$ or $B_t$ are not within the range between 0 and 1, they\nare not reproducable using this colour profile.\n\n\\begin{equation}\n\\begin{bmatrix}\n  R_t \\\\ G_t \\\\ B_t\n\\end{bmatrix}\n= \\left[\n\\setlength{\\arraycolsep}{10pt} \\sisetup{group-digits = false}\n\\begin{array}{S[table-format=1.7] S[table-format=1.7] S[table-format=1.6]}\n 2.04148 & -0.0564977 & -0.344713 \\\\\n-0.969258 & 1.87599& 0.0415557 \\\\\n0.0134455  &  -0.118373 & 1.01527\n\\end{array}\n\\right]\n\\begin{bmatrix}\n  X \\\\ Y \\\\ Z\n\\end{bmatrix}\n\\label{e:xyz-rgb-first}\n\\end{equation}\n\n\\begin{equation}\nR = R_t^{1/\\gamma} \\quad G = G_t^{1/\\gamma} \\quad B = B_t^{1/\\gamma}\n\\label{e:xyz-rgb-last}\n\\end{equation}\n\n\\section{YCbCr}\n\\label{s:ycbcr}\n\\is{colour model!YCbCr}\n\\is{YCbCr|see{colour model}}\n\nRobotic vision data is typically delivered by one of the cameras in\nthe head or body of the robot. The colour information that is recorded\nby these cameras can be stored in a wide variety of encodings. The\nrobots that have been used in my experiments deploy the YCbCr colour\nmodel. In order to utilise this information, it needs to be converted\nto the XYZ colour space, which happens in two steps. First it needs to\nbe converted to a RGB colour model using the Equations\n\\ref{e:ycbcr-rgb-first}--\\ref{e:ycbcr-rgb-last}. Finally, these\ncoordinates can be converted to the XYZ using Equations\n\\ref{e:secam-rgb-xyz-first} and \\ref{e:secam-rgb-xyz-last} which\nassumes the SECAM/PAL colour profile.\n\n\\begin{align}\nR& = (Y + 1.402 (C_r - 128) \\label{e:ycbcr-rgb-first}) / 255 \\\\\nG& = (Y - 0.34414 (C_b - 128) - 0.71414 (C_r - 128)) / 255 \\\\\nB& = (Y + 1.772 (C_b - 128)) / 255\\label{e:ycbcr-rgb-last}\n\\end{align}\n\n\\begin{equation}\nR_t = R^\\gamma \\quad G_t = G^\\gamma \\quad B_t = B^\\gamma\n\\label{e:secam-rgb-xyz-first}\n\\end{equation}\n\n\\begin{equation}\n\\begin{bmatrix}\n  X \\\\ Y \\\\ Z\n\\end{bmatrix}\n= \\left[\n\\setlength{\\arraycolsep}{5pt} \\sisetup{group-digits = false}\n\\begin{array}{S[table-format=1.7]S[table-format=1.7]S[table-format=1.7]}\n 0.4306190 & 0.3415419 & 0.1783091 \\\\\n 0.2220379 & 0.7066384 & 0.0713236 \\\\\n 0.201853  &  0.1295504 & 0.9390944\n\\end{array}\\right]\n\\begin{bmatrix}\n  R_t \\\\ G_t \\\\ B_t\n\\end{bmatrix}\n\\label{e:secam-rgb-xyz-last}\n\\end{equation}", "meta": {"hexsha": "5cb762c1c85a383660f945c486ab93a495cb82a5", "size": 20854, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "spaces/spaces.tex", "max_stars_repo_name": "langsci/Bleys", "max_stars_repo_head_hexsha": "d33df4fe062e27bded56495a16922228ef834602", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "spaces/spaces.tex", "max_issues_repo_name": "langsci/Bleys", "max_issues_repo_head_hexsha": "d33df4fe062e27bded56495a16922228ef834602", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spaces/spaces.tex", "max_forks_repo_name": "langsci/Bleys", "max_forks_repo_head_hexsha": "d33df4fe062e27bded56495a16922228ef834602", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-04-01T06:50:23.000Z", "max_forks_repo_forks_event_max_datetime": "2017-04-01T06:50:23.000Z", "avg_line_length": 41.5418326693, "max_line_length": 294, "alphanum_fraction": 0.7498321665, "num_tokens": 6346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.3249089268905928}}
{"text": "\n\\chapter{Basis sets}\\label{chap:basisets}\n\n%\\section{Introduction}\n\\abstract{Numerical integration and differentiation\nare some of the most frequently needed methods in computational\nphysics. Quite often we are confronted with the need of evaluating\neither the derivative $f'$ or an integral  $\\int f(x)dx$.  \nThe aim of this chapter is to introduce some of these methods\nwith a critical eye on numerical accuracy, following the discussion\nin the previous chapter. \n The next section deals essentially with topics from numerical differentiation.\nThere we present also the most commonly used formulae for computing\nfirst and second derivatives, formulae which in turn find their most important\napplications in the numerical solution of ordinary and partial \ndifferential equations. We discuss also selected methods for numerical \ninterpolation. \nThis  chapter serves also the scope of introducing\nsome more advanced C++ programming concepts, such as call\nby reference and value, reading and writing to a file and the use\nof dynamic memory allocation.  We will also discuss several object-oriented features of C++,\nending the chapter with an analogous discussion of Fortran features.}\n\n\nIn the previous chapter the general Hartree-Fock equations, which is a set of\nintegro-differential equations, were converted to a set of algebraic equations (the Roothaan\nequations in the restricted case and the Pople-Nesbet equations in the unrestricted case) by\nexpanding the unknown orbitals in a known set of basis functions. The Fock operator was then\nreduced to a matrix, the elements of which are integrals involving the chosen basis functions.\n\nWe start this chapter by discussing two popular types of basis functions, namely the \nSlater-type orbtials (STOs) and the Gaussian-type orbitals (GTOs). The latter is more suited for\nmolecular calculations and is the one we will use in this thesis. Thereafter we derive the\nintegration scheme for the Gaussian type orbitals.\n\n\n\n\\section{Basis functions}\nFor a molecular system, the eigenfunctions of the Hartree-Fock equations are called\n\\emph{molecular orbitals} (MOs). As discussed earlier, it is important to distinguish these\nfrom the perhaps more familiar \\emph{atomic orbitals}, and it is erroneous to\nthink that the electrons of molecular systems are occupying atomic orbitals.\nConsider for example the $H_2$-molecule.\nIn the ground state the electrons are not occupying the 1$s$-orbitals of atomic hydrogen. The\nmolecular system is entirely different from the atomic one, with an entirely different Hamiltonian,\nand the eigenstates of the Hartree-Fock equations will therefore also be different.\n\nIn order to solve the Hartree-Fock equations, we need to expand the molecular orbitals in a known\nset of basis functions\n\\begin{equation}\n \\phi_k(\\vec r) = \\sum_{\\mu=1}^M\\chi_{\\mu k}(\\vec r).\n\\end{equation}\nThe importance of choosing suitable basis functions can hardly be overemphasised; it completely determines\nthe accuracy of the results as well as the computational cost of the calculations. In choosing basis functions,\nthe following criteria should be met:\n\\begin{enumerate}\n \\item The functions must be physically reasonable, i.e., they should have large probability where\n      the electrons are likely to be and small probability elsewhere.\n \\item It should be possible to integrate the functions efficiently.\n \\item The solution of the Hartree-Fock equations must converge towards the Hartree-Fock limit (see chapter \\ref{chapter:electron_correlation})\n       as the number of basis functions increases.\n\\end{enumerate}\nThe first point suggests that we choose atomic orbitals as basis functions,  which is often\nreferred to as ``linear combination of atomic orbitals'' (LCAO). In this thesis we will let the\natomic orbitals be centered at the nuclei. However, this is not strictly required since the\natomic orbitals are merely being used as basis functions, and they are not to be thought of\nas orbitals occupied by electrons. In the following two subsections, we\ndiscuss two common types of atomic orbitals, namely the Slater type orbitals (STOs) and\nGaussian type orbitals (GTOs), respectively. Only the GTOs will be applied to the \ncalculations in this thesis.\n\n\n\\subsection{Slater-type orbitals (STOs)}\nThe Slater type orbitals are defined as \\cite{Cramer}\n\\begin{equation}\n \\chi^{STO}(r,\\theta,\\phi,n,l,m) = \\frac{(2a)^{n+1/2}}{[(2n)!]^{1/2}}r^{n-1}\\exp(-a r) Y^m_l(\\theta,\\phi),\n\\end{equation}\nwhere $n$ is the principal quantum number, $l$ and $m$ are the angular momentum quantum numbers,\n$Y^m_l(\\theta,\\phi)$ are the spherical harmonics familiar from the solution of the Schrödinger\nequation for the hydrogen atom, and $a$ is an exponent which determines the radial decay of the\nfunction. The main attractive features of the STOs are that they have the correct exponential decay with\nincreasing $r$ and that the angular components are hydrogenic. For this reason, they are often\nused in atomic Hartree-Fock calculations. When doing molecular calculations, however, they have the\ndisadvantage that the two-particle integrals $\\bra{\\mu\\sigma}g\\ket{\\nu\\lambda}$ occuring in the\nFock matrix $F_{\\mu\\nu}$ have no known analytical expression. This is because integrals of products\nof exponentials centered on different nuclei are difficult to handle. They can of course be calculated\nnumerically, but for large molecules this is very time consuming.\n\n\\subsection{Gaussian-type orbitals (GTOs)}\nA clever trick which makes multiple center integrals easier to handle is to replace the exponential\nterm $\\exp(-a r)$ with $\\exp(-a r^2)$, i.e., to use Gaussian functions. This greatly simplifies the\nintegrals because the product of two Gaussians centered on nuclei with positions\n$\\vec A$ and $\\vec B$ is equal to \\emph{one} Gaussian centered on some point $\\vec P$ on\nthe line between them:\n\\begin{equation}\n\\label{eq:gaussian_product}\n \\exp(-a|\\vec r - \\vec A|^2)\\cdot \\exp(-b|\\vec r - \\vec B|^2) = K_{AB}\\,\\exp(-p|\\vec r - \\vec P|^2),\n\\end{equation}\nwhere\n\\begin{eqnarray}\n K_{AB} & = & \\exp\\Big(-\\frac{ab}{a + b}|\\vec A - \\vec B|^2\\Big), \\\\\n \\vec P & = & \\frac{a \\vec A + b \\vec B}{a + b}, \\\\\n p & = & a + b.\n\\end{eqnarray}\nThis is the so-called \\emph{Gaussian product theorem}. It is illustrated in the one-dimensional case in figure \\ref{fig:Gaussians}.\n\\begin{figure}\n \\begin{center}\n  \\includegraphics[scale=0.5]{basis_functions_and_integral_evaluation/figures/Gaussians.pdf}\n  \\caption{Illustration of the Gaussian product theorem which says that the product of two Gaussians with centers at points A and B is another Gaussian\n           with center somewhere between A and B.}\n  \\label{fig:Gaussians}\n \\end{center}\n\\end{figure}\n\n\nThe general functional form of a normalised Gaussian type orbital \ncentered at $\\vec A$ is given by \\cite{Cramer}\n\\begin{equation}\n\\label{eq:gaussian_primitive}\n G_{ijk}(a, \\vec r_A) = \\Big(\\frac{2a}{\\pi}\\Big)^{3/4}\\Big[\\frac{(8a)^{i+j+k}\\,i!\\,j!\\,k!}{(2i)!\\,(2j)!\\,(2k)!}\\Big]x_A^i\\,y_A^j\\,z_A^k\\,\\exp(-a r_A^2),\n\\end{equation}\nwhere $\\vec r_A = \\vec r - \\vec A$ and the integers $i$, $j$, $k$ determine the angular momentum quantum number $l=i+j+k$. \n\n\\subsection{Contracted GTOs}\n\\label{subsec:contracted_gtos}\nThe greatest drawback with Gaussians is that they do not have the proper exponential radial decay. This can be remedied by forming linear combinations of GTOs\nto resemble the STOs\n\\begin{equation}\n \\chi^{CGTO}(\\vec r_A,i,j,k) = \\sum_{p=1}^L d_p G_{ijk}(a_p, \\vec r_A).\n\\end{equation}\nThese are called STO-LG basis functions, where L refers to the number of Gaussians used in the linear combination. Hehre, Stewart and Pople \\cite{pople}\nwere the first to systematically calculate optimal coefficients $d_p$ and exponentials $a_p$, and today the STO-LG basis sets are available\nfor most atoms.\nThe individual Gaussians are called \\emph{primitive} basis functions and the linear combinations are called \\emph{contracted} basis functions, hence the label\nCGTO (Contracted Gaussian Type Orbital). In this thesis we will only consider CGTOs, and whenever the symbol $\\chi$ appears without any label,\nwe will always mean CGTO. \n\nA very common choice for the STO-LG basis sets is $L=3$. Figure \\ref{fig:STOvsSTO3G} shows how the 1$s$ STO for hydrogen is approximated by 3 GTOs.\nThe exponents $a_p$ and coefficients $d_p$ have been set so that the contracted basis function lies as close to the STO as possible, see\ntable \\ref{tab:STO3G}. It is important to note that the parameters $(a_p,d_p)$ are static and that the linear combination of Gaussians constitute \\emph{one single}\nbasis function. Throughout this text the phrase ``basis function'' will always refer to a contracted basis function.\n\n\n\n\\begin{figure}\n \\begin{center}\n  \\includegraphics[scale=0.7]{basis_functions_and_integral_evaluation/figures/STO3G.pdf}\n  \\caption{The whole line shows the 1s STO basis function, while the broken line shows a linear combination of three Gaussians.}\n  \\label{fig:STOvsSTO3G}\n \\end{center}\n\\end{figure}\n\n% Note that the GTOs and STOs do not have any radial nodes as the hydrogenic functions do. This means that no single GTO or STO can mimic the 2$s$ hydrogenic orbital for example. With contractions, however,\n% this problem is eliminated; nodes can be introduced by using a combination of positive and negative coefficients $d_p$.\n\nThe STO-LG basis sets belong to the family of \\emph{minimal basis sets}.\nIt means that there is one and only one basis function per atomic orbital.\nThe STO-LG basis sets for the hydrogen and helium atoms, for example, contain only one basis\nfunction for the 1$s$ atomic orbital. This basis function is, as explained above, composed of\na linear combination of L primitives. For the atoms lithium through neon the STO-LG basis\nsets contain 5 basis functions; one for each of the atomic orbitals\n$1s$, $2s$, $2p_x$, $2p_y$ and $2p_z$.\n\n\\begin{table}\n \\begin{center}\n \\caption{Coefficients and exponents used in the STO-3G basis shown in figure \\ref{fig:STOvsSTO3G}.}\n \\label{tab:STO3G}\n  \\begin{tabular}{|c|c|c|c|}\\hline\n   $p$        &  1  &  2  &   3 \\\\ \\hline\n   $d_p$      &  0.1543   & 0.5353    & 0.4446  \\\\ \\hline\n   $a_p$ &  3.4252   & 0.6239    & 0.1688  \\\\ \\hline\n  \\end{tabular}\n \\end{center}\n\\end{table}\n\nThe reader might be asking herself why the coefficients $d_p$ in the linear combination of the STO-LGs are static. Shouldn't the accuracy of our results\nactually improve if we let the coefficients vary? The answer to this is yes. However, the linear system to be solved (the Hartree-Fock equations) will then\nbe larger. Thus there is a trade off between accuracy and computational efficiency which must be considered.\n\nHowever, basis sets where the STO-LG sets have been ``decontracted'' as described above have actually been used. They belong to the family of $\\zeta$-basis sets.\nThe double-$\\zeta$ and triple-$\\zeta$ basis sets have two and three basis functions, respectively, for each atomic orbital. As an example, we could\ncreate a double-$\\zeta$ basis set from the STO-3G basis set by contracting the two first primitives and leave the third as a normalised primitive. Similarly, we could\ncounstruct a triple-$\\zeta$ basis set by treating each primitive as a basis function.\n\nLet us for a moment assume that we use a triple-$\\zeta$ basis set constructed from the STO-3G to do Hartree-Fock calculations on atomic oxygen.\nWhat will the resulting orbitals look like? The lowest orbital will be very close to the definition of the 1$s$ orbital of the STO-3G set.\nThis is to be expected since the STO-3G basis functions are constructed to resemble the STO atomic orbitals.\n\nWhat if we now apply the same triple-$\\zeta$ basis to calculations on the CO molecule, say? In this case we would probably also find an orbital which resembles the 1$s$\norbital of the STO-3G basis for oxygen. This is because it is mostly the valence electrons which contribute in the bonding between atoms, and the core electrons are more or less unaffected.\nThus decontracting basis functions corresponding to the core atomic orbitals will generally not pay off, but will merely increase the computational load. Therefore, basis\nsets have been constructed where only the functions corresponding to the valence atomic orbitals are decontracted. These are the so-called \\emph{split-valence} basis sets. \nAn example of a split-valence basis set is the 3-21G. The number before the hyphen (in this case 3) is the number of primitives per core atomic orbital. The fact that there are\ntwo numbers after the hyphen signifies that there are two basis functions for each valence atomic orbital. The numbers themselves (in this case 2 and 1) indicate how many primitives\nthe first and second of these are composed of. As an example, the 3-21G basis set for the oxygen atom has one single\nbasis function for the 1$s$ orbital (since this is the core orbital), and this basis function consists of three primitives. Furthermore, it has two basis functions for the 2$s$,\n2$p_x$, 2$p_y$ and 2$p_z$ atomic orbitals (since these are the valence orbitals). The first consists of two primitives, and the second consists of only one\nprimitive. In sum the oxygen atom thus has 9 basis functions which are built up from a total of 15 primitives.\nOther examples of split-valence basis sets are 4-31G, 6-31G and 6-311G \\cite{Cramer}.\n\nIn many molecular calculations, the split-valence basis sets mentioned thus far do not provide enough flexibility to describe the chemistry appropriately.\nThis is often fixed by adding functions\ncorresponding to atomic orbitals with angular momentum $l_{max}+1$, where $l_{max}$ is the highest angular momentum of the atom. \nSuch functions are called \\emph{polarisation functions}. For example, the polarisation functions for the Oxygen atom are the $d$-functions. Asterisks (*) are added to the name of the basis set to indicate that polarisation\nfunctions are included. One asterisk (as in 6-31G*) indicates that $d$-functions are added to polarise the $p$-functions of first row atoms (Li-Ne). Two asterisks (as in 6-31G**)\nmean that $p$-functions are added to polarise the $s$-functions of hydrogen and helium as well.\n\n% Note that the 3-21G basis set for Oxygen contains basis functions for each atomic orbital up to the $p$-orbital. Similarly, all the split-valence basis sets mentioned above\n% contain basis functions for each atomic orbital up to the the highest present in the atom which is considered. However, in many molecular calculations this does not provide enough flexibility to\n% describe the chemistry correctly. One way to increase the flexibility is to include basis functions for the orbital \\emph{above} the highest present in the atom. These functions\n% are called \\emph{polarization functions}. The polarization functions for the Oxygen atom are the $d$-orbitals. An asterix (*) is added to the name of the basis set to indicate that polarization\n% functions are included. One asterisk (as in 3-21G*, for example) indicate that $d$-functions are added to polarize the $p$-functions. Two asterisks (as in 3-21G**, for example)\n% are added to show that also the $s$-functions of Hydrogen and helium are polarized by $p$-functions.\n\nIt should be noted that the list of basis sets mentioned here is in no way exhaustive. There is a flora of basis sets out there, see for example\nCramer \\cite{Cramer} or Helgaker \\emph{et al} \\cite{Helgaker}.\n\n\n\n\n\\section{Integral evaluation}\nAs discussed in the previous section, using Gaussian basis functions significantly improves the speed of the integrations which must be done when setting up the Fock matrix.\nThis section discusses the details of how the integration is performed.\n\nWe start by summarising the most important properties of the Cartesian Gaussians. Thereafter, we\nchange basis to the so-called Hermite Gaussians, as proposed by \\v{Z}ivkovi\\'{c} and Maksi\\'{c} \\cite{zivkovic_maksic}.\nThen, following the work of McMurchie and Davidson \\cite{mcmurchie_davidson}, we show how the one- and two-particle integrals can be expressed compactly in\nterms of some auxiliary functions. The auxiliary functions are computed via a set of recurrence relations.\n\nA thorough review of the techniques presented can be found in Helgaker \\emph{et al} \\cite{Helgaker}.\n\n\\subsection{Cartesian Gaussians}\nThe Cartesian Gaussian functions centered at $\\vec A$ are given by\n\\begin{equation}\n G_{ijk}(a, \\vec r_A) = x^i_A\\,y^j_A\\,z^k_A\\,\\exp(-a r^2_A),\n\\end{equation}\nwhere $\\vec r_A = \\vec r - \\vec A$. These will be our primitive basis functions. They factorise in the Cartesian components\n\\begin{equation}\n G_{ijk}(a, \\vec r_A) = G_i(a, x_A)\\,G_j(a, y_A)\\,G_k(a, z_A),\n\\end{equation}\nwhere\n\\begin{equation}\n G_i(a, x_A) = x^i_A\\,\\exp(-a x^2_A),\n\\end{equation}\nand the other factors are defined similarly. Each of the components obey the simple recurrence relation\n\\begin{equation}\n x_A\\,G_i = G_{i+1}.\n\\end{equation}\n\n\n\\subsection{Gaussian overlap distribution}\nWe introduce the following shorthand notation\n\\begin{align}\n  G_a(\\vec r) & = G_{ikm}(a, \\vec r_A), \\label{eq:Ga}\\\\\n  G_b(\\vec r) & = G_{jln}(b, \\vec r_B), \\label{eq:Gb}\n\\end{align}\nand define the overlap distribution\n\\begin{equation}\n \\Omega_{ab}(\\vec r) = G_a(\\vec r)\\,G_b(\\vec r).\n\\end{equation}\nUsing the Gaussian product theorem (\\ref{eq:gaussian_product}) this can be written as\n\\begin{equation}\n \\Omega_{ab}(\\vec r) = K_{AB}\\,x^i_A\\,x^j_B\\,y^k_A\\,y^l_B\\,z^m_A\\,z^n_B\\,\\exp(-p\\,r^2_P),\n\\end{equation}\nwhere\n\\begin{equation}\n\\label{eq:gaussian_product_defs}\n \\begin{split}\n  K_{AB} & = \\exp\\Big(-\\frac{ab}{a + b}R^2_{AB}\\Big) \\\\\n  \\vec R_{AB} & =  \\vec A - \\vec B \\\\\n  p & = a + b\\\\\n  \\vec r_P & = \\vec r - \\vec P \\\\\n  \\vec P & = \\frac{a\\vec A + b\\vec B}{a + b}.\n \\end{split}\n\\end{equation}\nBecause the Gaussians $G_a$ and $G_b$ factorise in their Cartesian components, so does the overlap distribution\n\\begin{equation}\n \\Omega_{ab}(\\vec r) = \\Omega_{ij}(x)\\,\\Omega_{kl}(y)\\,\\Omega_{mn}(z),\n\\end{equation}\nwhere\n\\begin{equation}\n \\Omega_{ij} = K^x_{AB}\\,x^i_A\\,x^j_B\\,\\exp(-px^2_P)\n\\end{equation}\nand\n\\begin{equation}\n\\begin{split}\n K^x_{AB} = & \\exp\\Big(-\\frac{ab}{a + b}X^2_{AB}\\Big) \\\\\n   X_{AB} = & A_x - B_x.\n\\end{split}\n\\end{equation}\nThe distributions $\\Omega_{kl}(y)$ and $\\Omega_{mn}(z)$ are defined similarly.\n\n\n\n\n\\subsection{Hermite Gaussians}\nLater we will expand the Cartesian Gaussians in terms of the so-called Hermite Gaussians.\nThis will simplify the integrations significantly. The Hermite Gaussians centered at $\\vec P$ are defined by\n\\begin{equation}\n \\Lambda_{tuv}(p, \\vec r_p) = \\Big(\\frac{\\partial}{\\partial P_x}\\Big)^t \\Big(\\frac{\\partial}{\\partial P_y}\\Big)^u \\Big(\\frac{\\partial}{\\partial P_z}\\Big)^v \\exp(-p\\, r^2_P),\n\\end{equation}\nwhere $\\vec r_p = \\vec r - \\vec P$. They factorise in the same way as the Cartesian Gaussians do:\n\\begin{equation}\n \\Lambda_{tuv}(p, \\vec r_P) = \\Lambda_t(p,x_P)\\,\\Lambda_u(p,y_P)\\,\\Lambda_v(p,z_P),\n\\end{equation}\nwhere\n\\begin{equation}\n\\label{eq:HermiteGaussian_x}\n \\Lambda_t(p,x_P) = \\Big(\\frac{\\partial}{\\partial P_x}\\Big)^t \\exp(-p\\,x^2_P),\n\\end{equation}\nand the other factors are defined similarly. However, their recurrence relation is quite different from that of the Cartesian Gaussians:\n\\begin{equation}\n\\begin{split}\n \\Lambda_{t+1}(p,x_P) & = \\Big(\\frac{\\partial}{\\partial P_x}\\Big)^t \\frac{\\partial}{\\partial P_x}\\exp(-px^2_P) \\\\\n                      & = \\Big(\\frac{\\partial}{\\partial P_x}\\Big)^t 2px_P \\exp(-px^2_P)  \\\\\n                      & = 2p[-t\\Big(\\frac{\\partial}{\\partial P_x}\\Big)^{t-1} + x_P \\Big(\\frac{\\partial}{\\partial P_x}\\Big)^t] \\exp(-px^2_P) \\\\\n                      & = 2p[-t\\Lambda_{t-1} + x_P \\Lambda_t],\n\\end{split}\n\\end{equation}\nwhere we have used that\n\\begin{equation}\n\\label{eq:derivation_rule}\n \\Big(\\frac{\\partial}{\\partial x}\\Big)^t x f(x) = t\\Big(\\frac{\\partial}{\\partial x}\\Big)^{t-1}f(x) + x\\Big(\\frac{\\partial}{\\partial x}\\Big)^t f(x).\n\\end{equation}\nThus the recurrence relation reads\n\\begin{equation}\n\\label{eq:hermite_gaussian_recurrence}\n x_P \\Lambda_t = \\frac{1}{2p}\\Lambda_{t+1} + t\\Lambda_{t-1}.\n\\end{equation}\n\n\n\n\n\\subsection{Overlap integral $S_{ab}$}\nOur goal is to compute the overlap integral\n\\begin{equation}\nS_{ab}  = \\langle G_a|G_b\\rangle = \\int d\\vec r \\,\\Omega_{ab}(\\vec r)\n\\end{equation}\nbetween two Gaussians centered at the points $\\vec A$ and $\\vec B$.\nNote that since the overlap distribution $\\Omega_{ab}$ factorise in the Cartesian components, the integrals over $x$, $y$ and $z$ can be calculated independently of each other:\n\\begin{equation}\n\\begin{split}\n S_{ab} = & \\langle G_i|G_j\\rangle \\langle G_k|G_l\\rangle \\langle G_m|G_n\\rangle \\\\\n        = & S_{ij}\\,S_{kl}\\,S_{mn}.\n\\end{split}\n\\end{equation}\nThe $x$ component of the overlap integral, for example, is given by\n\\begin{equation}\n\\label{eq:intG_ij}\n\\begin{split}\n S_{ij} = & \\int dx \\,\\Omega_{ij}(x) \\\\\n        = & K_{AB}^x\\int dx \\,x_A^ix_B^j\\exp(-px_P^2).\n\\end{split}\n\\end{equation}\nIn equation (\\ref{eq:intG_ij}) the two-center Gaussians have been reduced to a one-center Gaussian.\nHowever, the integral is still not straightforward to calculate because of the powers $x_A^i$ and $x_B^j$. A smart way to deal with this is to express the Cartesian Gaussian\nin terms of the Hermite Gaussians. Note that (\\ref{eq:HermiteGaussian_x}) is a polynomial of order $t$ in $x$ multiplied by the exponential function. In equation (\\ref{eq:intG_ij}) the polynomial\nis of order $i+j$. This means that we can express the overlap distribution $\\Omega_{ij}(x)$ in equation (\\ref{eq:intG_ij}) in terms of the Hermite Gaussians in (\\ref{eq:HermiteGaussian_x}) in the following way:\n\\begin{equation}\n\\label{eq:LinCombOfHermGauss}\n \\Omega_{ij}(x) = \\sum_{t=0}^{i+j} E^{ij}_t \\Lambda_t(p, x_P),\n\\end{equation}\nwhere $E^{ij}_t$ are constants.\nNote that the sum is over $t$ only. The indices $i$ and $j$ are static and are determined from the powers of $x$ in $G_i$ and $G_j$.\nWe use them as labels on the coefficients $E^{ij}_t$ because different sets of indices will lead to different sets of coefficients.\n\nTo get the overlap integral in the $x$-direction we integrate (\\ref{eq:LinCombOfHermGauss}) over $\\mathbb{R}$, which now turns out to be extremely easy;\nthe only term that survives the integration is the term for $t=0$:\n\\begin{eqnarray}\n \\int dx\\,\\Lambda_t(p,x_P) & = & \\int dx\\,\\Big(\\frac{\\partial}{\\partial P_x}\\Big)^t\\exp(-p\\,x^2_P), \\\\\n                           & = & \\Big(\\frac{\\partial}{\\partial P_x}\\Big)^t \\int dx\\,\\exp(-p\\,x^2_P), \\\\\n                           & = & \\sqrt{\\frac{\\pi}{p}}\\,\\delta_{t0}.\n\\end{eqnarray}\nWe have used Leibniz' rule, which says that the differentiation of an integrand with respect to a variable which is not an integration variable can\nbe moved outside the integral. Thus the integral in (\\ref{eq:intG_ij}) is simply\n\\begin{equation}\n S_{ij} = E^{ij}_0\\,\\sqrt{\\frac{\\pi}{p}}.\n\\end{equation}\nThe exact same procedure can be used for the integrals with respect to $y$ and $z$, which means that the total overlap integral is\n\\begin{equation}\n\\label{eq:S_ab}\n S_{ab} = E^{ij}_0\\,E^{kl}_0\\,E^{mn}_0\\,\\Big(\\frac{\\pi}{p}\\Big)^{3/2}.\n\\end{equation}\nSo far nothing has been said about how we actually determine the coefficients $E^{ij}_t$. First observe that when $i=j=0$ in equation (\\ref{eq:LinCombOfHermGauss})\nwe obtain\n\\begin{equation}\n E^{0,0}_0 = K_{AB}^x.\n\\end{equation}\nThe other coefficients are found via the following recurrence relations\n\\begin{equation}\n\\label{eq:E_recurrence}\n\\begin{split}\n E^{i+1,j}_t & = \\frac{1}{2p}E^{ij}_{t-1} + X_{PA}E^{ij}_t + (t+1)E^{ij}_{t+1} \\\\\n E^{i,j+1}_t & = \\frac{1}{2p}E^{ij}_{t-1} + X_{PB}E^{ij}_t + (t+1)E^{ij}_{t+1}.\n\\end{split}\n\\end{equation}\nAnalogous expressions hold for the coefficients $E^{kl}_u$ and $E^{mn}_v$. The first equation in (\\ref{eq:E_recurrence}) can be derived by comparing two equivalent ways of expanding the product $G_{i+1}G_j$\nin Hermite Gaussians. The first way is\n\\begin{equation}\n G_{i+1}\\,G_j= \\sum_{t=0}^{i+j+1}E^{i+1,j}_t \\Lambda_t,\n\\end{equation}\nand the second way is\n\\begin{equation}\n\\label{eq:derivation_E_coeffs}\n\\begin{split}\n G_{i+1}\\,G_j & = x_A G_i\\,G_j \\\\\n              & = [(x - P_x) + (P_x - A_x)]\\sum_{t=0}^{i+j} E^{ij}_t \\Lambda_t\\\\\n              & = \\sum_{t=0}^{i+j}[x_P + X_{PA}] E^{ij}_t \\Lambda_t \\\\\n              & = \\sum_{t=0}^{i+j}[\\frac{1}{2p}\\Lambda_{t+1} + t\\Lambda_{t-1} + X_{PA}\\Lambda_t]E^{ij}_t \\\\\n              & = \\sum_{t=0}^{i+j+1}[\\frac{1}{2p}E^{ij}_{t-1} + X_{PA}E^{ij}_t + (t+1)E^{ij}_{t+1}] \\Lambda_t,\n\\end{split}\n\\end{equation}\nwhere we have used the recurrence relation (\\ref{eq:hermite_gaussian_recurrence}) on the fourth line and changed the summation indices on the fifth line. Comparing the two expressions gives the\ndesired result.\n\nNote that the change in summation indices in equation (\\ref{eq:derivation_E_coeffs}) implies that we must define\n\\begin{equation}\n E^{ij}_t = 0, \\qquad \\text{if }t<0\\text{ or }t > i + j.\n\\end{equation}\n\n\n\n\\subsection{Kinetic integral $T_{ij}$}\nNext we turn to the evaluation of the kinetic integral:\n\\begin{equation}\n\\begin{split}\nT_{ab} & = -\\frac{1}{2}\\bra{G_a}\\nabla^2\\ket{G_b} \\\\\n       & = -\\frac{1}{2}\\bra{G_{ikm}(a, \\vec r_A)}\\nabla^2\\ket{G_{jln}(b, \\vec r_B)} \\\\\n       & = -\\frac{1}{2}(T_{ij}\\,S_{kl}\\,S_{mn} + S_{ij}\\,T_{kl}\\,S_{mn} + S_{ij}\\,S_{kl}\\,T_{mn}),\n\\end{split}\n\\end{equation}\nwhere\n\\begin{equation}\n T_{ij} = \\int dx \\,G_i(a,x_A)\\frac{\\partial^2}{\\partial x^2}G_j(b,x_B),\n\\end{equation}\nand the other factors are defined in the same way. Performing the differentiation yields\n\\begin{equation}\n T_{ij} = 4b^2\\,S_{i,j+2} - 2b(2j + 1)S_{i,j} + j(j-1)S_{i,j-2}.\n\\end{equation}\nThus we see that the kinetic integrals are calculated easily as products of the overlap integrals.\n\n\n\\subsection{Coulomb integral $V_{ab}$}\n\\label{sec:V_ab}\nWe now turn to the Coulomb integral due to the interaction between the electrons and the nuclei\n\\begin{equation}\n V_{ab} = \\bra{G_a}\\frac{1}{r_C}\\ket{G_b},\n\\end{equation}\nwhere $r_C = |\\vec r - \\vec C|$. As before, the overlap distribution is expanded in the Hermite Gaussians:\n\\begin{equation}\n\\begin{split}\n V_{ab} & = \\int d\\vec r \\,\\frac{\\Omega_{ab}(\\vec r)}{r_C} \\\\\n        & = \\sum_{tuv}E^{ij}_t E^{kl}_u E^{mn}_v\\int d\\vec r \\, \\frac{\\Lambda_{tuv}(p,\\vec r_P)}{r_C} \\\\\n        & = \\sum_{tuv}E^{ab}_{tuv}\\int d\\vec r \\, \\frac{\\Lambda_{tuv}(p,\\vec r_P)}{r_C}. \\\\\n\\end{split}\n\\end{equation}\nHere we have used the shorthand notation\n\\begin{equation}\n E^{ab}_{tuv} = E^{ij}_t E^{kl}_u E^{mn}_v.\n\\end{equation}\nIn this integral other terms besides $\\Lambda_{000}$ will survive due to the factor $1/r_C$. Let us nonetheless start by evaluating this term\n\\begin{equation}\n V_p = \\int d\\vec r \\, \\frac{\\Lambda_{000}(p,\\vec r_P)}{r_C} = \\int d\\vec r\\, \\frac{\\exp(-p\\,r_P^2)}{r_C}.\n\\end{equation}\nWe will show that this three-dimensional integral can actually be converted to a one-dimensional one. The trick is to observe that the factor $1/r_C$ can be replaced by the integral\n\\begin{equation}\n \\frac{1}{r_C} = \\frac{1}{\\sqrt{\\pi}}\\int_{-\\infty}^\\infty dt\\,\\exp(-r^2_C\\,t^2).\n\\end{equation}\nInserting this into $V_p$ and using the Gaussian product theorem gives\n\\begin{eqnarray}\n V_p & = & \\int \\exp(-p\\,r_P^2)\\Big(\\frac{1}{\\sqrt{\\pi}}\\int_{-\\infty}^\\infty\\exp(-r^2_C\\,t^2)\\,dt\\Big)\\,d\\vec r \\\\\n     & = & \\frac{1}{\\sqrt{\\pi}}\\int_{-\\infty}^\\infty\\int\\exp\\Big(-\\frac{pt^2}{p + t^2}R^2_{PC}\\Big)\\,\\exp[-(p + t^2)r^2_S] d\\vec r\\, dt,\n\\end{eqnarray}\nwhere $\\vec R_{PC} = \\vec P - \\vec C$ and $\\vec r_S = \\vec r - \\vec S$ for some point $\\vec S$. Doing the integral over the spatial coordinates reveals that the specific value of $\\vec S$ is immaterial:\n\\begin{eqnarray}\n V_p & = & \\frac{1}{\\sqrt{\\pi}}\\int_{-\\infty}^\\infty\\exp\\Big(-\\frac{pt^2}{p + t^2}R^2_{PC}\\Big)\\Big(\\frac{\\pi}{p + t^2}\\Big)^{3/2}\\,dt \\\\\n     & = & 2\\pi\\int_0^\\infty\\exp\\Big(-\\frac{pt^2}{p + t^2}R^2_{PC}\\Big)\\frac{dt}{(p + t^2)^{3/2}}.\n\\end{eqnarray}\nNext we change integration variable from $t$ to $u$ by defining\n\\begin{equation}\n u^2 = \\frac{t^2}{p + t^2}.\n\\end{equation}\nThis will change the range of integration from $[0,\\infty\\rangle$ to $[0,1]$. This is beneficial because the final integral at which we arrive will be calculated numerically.\nThe change of variables leads to\n\\begin{align}\n\\label{eq:V_p}\n V_p & = \\frac{2\\pi}{p}\\int_0^1\\exp(-p\\,R^2_{PC}\\,u^2)\\,du \\\\\n     & = \\frac{2\\pi}{p}F_0(p\\,R^2_{PC}),\n\\end{align}\nwhere $F_0(x)$ is a special instance of the Boys function $F_n(x)$ which is defined as\n\\begin{equation}\n F_n(x) = \\int_0^1\\exp(-xt^2)\\,t^{2n}\\,dt.\n\\end{equation}\nHow to actually evaluate the Boys function will be discussed in section \\ref{section:Boys}.\n\nWe have now a tremendously simplified way of calculating the integral of $\\Lambda_{000}/r_C$. However, we need to integrate $\\Lambda_{tuv}/r_C$ for general values of $t$, $u$ and $v$.\nThese integrals are actually not that hard to do once the Boys function is calculated:\n\\begin{align}\n V_{ab} & = \\sum_{tuv}E^{ab}_{tuv}\\int d\\vec r \\, \\frac{\\Lambda_{tuv}(p,\\vec r_p)}{r_C} \\\\\n        & = \\frac{2\\pi}{p}\\sum_{tuv}E^{ab}_{tuv} \\frac{\\partial^{t+u+v} F_0(p R^2_{PC})}{\\partial P_x^t \\partial P_y^u \\partial P_z^v} \\\\\n        & = \\frac{2\\pi}{p}\\sum_{tuv}E^{ab}_{tuv} R_{tuv}(p,\\vec R_{PC}), \\label{eq:V_ab}\n\\end{align}\nwhere we have defined\n\\begin{equation}\n R_{tuv}(a,\\vec A) = \\frac{\\partial^{t+u+v} F_0(a A^2)}{\\partial A_x^t \\partial A_y^u \\partial A_z^v}.\n\\end{equation}\nSo we need to know how to calculate derivatives of the function $F_0$. Note first that\n\\begin{equation}\n \\frac{d}{dx}F_n(x) = -F_{n+1}(x).\n\\end{equation}\nThis means that it is possible to derive analytical expressions for the Coulomb term $V_{ab}$. However, in practice they are calculated recursively in a manner similar to the way we calculate\nthe coefficients $E^{ij}_t$. Before presenting the recursion relations, we introduce the so-called auxiliary Hermite integrals\n\\begin{equation}\n R^n_{tuv}(a,\\vec A) = (-2a)^n\\,\\frac{\\partial^{t+u+v} F_n(a A^2)}{\\partial A_x^t \\partial A_y^u \\partial A_z^v}.\n\\end{equation}\nBy starting with the source terms $R^n_{000}(a,\\vec A) = (-2a)^n\\,F_n(a A^2)$ we can reach the targets $R^0_{tuv}(a,\\vec A) = R_{tuv}(a,\\vec A)$ through the following\nrecurrence relations\n\\begin{equation}\n\\label{eq:R_recurrence}\n \\begin{split}\n  R^n_{t+1,u,v} & = tR^{n+1}_{t-1,u,v} + A_x R^{n+1}_{tuv} \\\\\n  R^n_{t,u+1,v} & = uR^{n+1}_{t,u-1,v} + A_y R^{n+1}_{tuv} \\\\\n  R^n_{t,u,v+1} & = vR^{n+1}_{t,u,v-1} + A_z R^{n+1}_{tuv}.\n \\end{split}\n\\end{equation}\nThe first of these are derived as follows\n\\begin{align}\n R^{n}_{t+1,u,v} & = (-2a)^n\\frac{\\partial^{t+u+v}}{\\partial A_x^t \\partial A_y^u \\partial A_z^v} [2aA_xF'_n(aA^2)] \\\\\n                 & = (-2a)^{n+1}\\frac{\\partial^{t+u+v}}{\\partial A_x^t\\partial A_y^u \\partial A_z^v}\\Big[A_xF_{n+1}(aA^2)\\Big] \\\\\n                 & = (-2a)^{n+1}\\frac{\\partial^{u+v}}{\\partial A_y^u \\partial A_z^v}\\Big[t\\frac{\\partial^{t-1}}{\\partial A_x^{t-1}} + A_x\\frac{\\partial^t}{\\partial A_x^t}\\Big]F_{n+1}(aA^2) \\\\\n                 & = tR^{n+1}_{t-1,u,v} + A_xR^{n+1}_{tuv},\n\\end{align}\nwhere we have used equation (\\ref{eq:derivation_rule}) and the fact that $F'_n(x) = -F_{n+1}(x)$.\n% From these relations it is clear that in order to calculate the values of $R_{tuv}(p,\\vec R_{PC})$ needed in (\\ref{eq:V_ab}), the Boys function $F_n(p, R^2_{PC})$ has to be\n% evaluated for $n\\in\\{0,\\dots,\\mathrm{max}(t_{max}, u_{max}, v_{max})\\}$.\n\n\n\\subsection{Coulomb integral $g_{acbd}$}\n\\label{sec:g_abcd}\nFinally we show how to calculate the Coulomb integral due to the interaction between the electrons. It is given by\\footnote{Here $G_a$ is combined with $G_b$ and $G_c$ combined with\n$G_d$ using the Gaussian product rule. In many books on quantum chemistry this is written as \\newline\n$\\left(G_a(1) G_b(1)|r^{-1}_{12}|G_c(2) G_d(2)\\right) =\\int\\int d\\vec r_1 d\\vec r_2 G_a(\\vec r_1) G_b(\\vec r_1) r^{-1}_{12} G_c(\\vec r_2) G_d(\\vec r_2)$. However, since this\ndeparts from the usual notation of quantum physics, it will not be used in this thesis.}\n\\begin{equation}\n\\begin{split}\n  g_{acbd} & = \\bra{G_a G_c}\\frac{1}{r_{12}}\\ket{G_b G_d} \\\\\n           & = \\int\\int \\frac{\\Omega_{ab}(\\vec r_1)\\Omega_{cd}(\\vec r_2)}{r_{12}} d\\vec r_1 d\\vec r_2 \\\\\n           & = \\sum_{tuv}\\sum_{\\tau\\nu\\phi}E^{ab}_{tuv}E^{cd}_{\\tau\\nu\\phi}\\int\\int\\frac{\\Lambda_{tuv}(p,\\vec r_{1P})\\Lambda_{\\tau\\nu\\phi}(q,\\vec r_{2Q})}{r_{12}}d \\vec r_1 d\\vec r_2 \\\\\n           & = \\sum_{tuv}\\sum_{\\tau\\nu\\phi}E^{ab}_{tuv}E^{cd}_{\\tau\\nu\\phi}\\frac{\\partial^{t+u+v}}{\\partial P_x^t \\partial P_y^u \\partial P_z^v}\n                \\frac{\\partial^{\\tau+\\nu+\\phi}}{\\partial Q_x^\\tau \\partial Q_y^\\nu \\partial Q_z^\\phi} \\\\\n           &    \\hspace{30mm} \\int\\int\\frac{\\exp(-pr^2_{1P})\\exp(-qr^2_{2Q})}{r_{12}}d \\vec r_1 d\\vec r_2,\n\\end{split}\n\\end{equation}\nwhere, analogous to $p$ and $\\vec r_{1P}$, we have defined \n\\begin{equation}\n \\begin{split}\n    q = & c + d\\\\\n  \\vec r_{2Q} = & \\vec r_2 - \\vec Q \\\\\n  \\vec Q = & \\frac{c\\,\\vec C + d\\,\\vec D}{c + d}.\n \\end{split}\n\\end{equation}\nThus we need to evaluate the integral\n\\begin{equation}\n V_{pq} = \\int\\int\\frac{\\exp(-pr^2_{1P})\\exp(-qr^2_{2Q})}{r_{12}}d \\vec r_1 d\\vec r_2.\n\\end{equation}\nBy first integrating over $\\vec r_1$ and using equation (\\ref{eq:V_p}) this can be written as\n\\begin{equation}\n V_{pq} = \\int\\Big(\\frac{2\\pi}{p}\\int_0^1\\exp(-p\\,r^2_{2P}\\,u^2)\\,du\\Big)\\exp(-qr^2_{2Q}) d \\vec r_2.\n\\end{equation}\nNext we change the order of integration and use the Gaussian product theorem to get\n\\begin{equation}\n\\begin{split}\n V_{pq} & = \\frac{2\\pi}{p}\\int_0^1\\int\\exp(-\\frac{pqu^2}{pu^2+q}R^2_{PQ})\\exp[-(pu^2+q)r_{2S}^2] d\\vec r_2 du \\\\\n        & = \\frac{2\\pi}{p}\\int_0^1\\exp(-\\frac{pqu^2}{pu^2+q}R^2_{PQ})\\Big(\\frac{\\pi}{pu^2+q}\\Big)^{3/2} du,\n\\end{split}\n\\end{equation}\nwhere $\\vec R_{PQ} = \\vec P - \\vec Q$ and $\\vec r_{2S} = \\vec r_2 - \\vec S$ for some point $\\vec S$. Again, the actual coordinates of \n$\\vec S$ are immaterial. If we now make the change of variable\n\\begin{equation}\n \\frac{v^2}{p+q} = \\frac{u^2}{pu^2+q},\n\\end{equation}\nwe get the result\n\\begin{equation}\n V_{pq} = \\frac{2\\pi^{5/2}}{pq\\sqrt{p+q}}F_0\\Big(\\frac{pq}{p+q}R^2_{PQ}\\Big).\n\\end{equation}\nFrom this we get the final answer\n\\begin{equation}\n\\begin{split}\n g_{acbd} & = \\frac{2\\pi^{5/2}}{pq\\sqrt{p+q}}\\sum_{tuv}\\sum_{\\tau\\nu\\phi}(-1)^{\\tau+\\nu+\\phi}E^{ab}_{tuv}E^{cd}_{\\tau\\nu\\phi} \\\\\n          & \\hspace{40mm} \\frac{\\partial^{t+u+v+\\tau+\\nu+\\phi}}{\\partial P_x^{t+\\tau} \\partial P_y^{u+\\nu} \\partial P_z^{v+\\phi}}F_0\\Big(\\frac{pq}{p+q}R^2_{PQ}\\Big) \\\\\n          & = \\frac{2\\pi^{5/2}}{pq\\sqrt{p+q}}\\sum_{tuv}\\sum_{\\tau\\nu\\phi}(-1)^{\\tau+\\nu+\\phi}E^{ab}_{tuv}E^{cd}_{\\tau\\nu\\phi}R_{t+\\tau,u+\\nu,v+\\phi}(\\alpha,\\vec R_{PQ}),\n\\end{split}\n\\end{equation}\nwhere $\\alpha = pq/(p+q)$. The term $(-)^{\\tau+\\nu+\\phi}$ arises due to the fact that\n\\begin{equation}\n\\frac{\\partial}{\\partial Q_x} F_0\\Big(\\frac{pq}{p+q}R^2_{PQ}\\Big) = - \\frac{\\partial}{\\partial P_x} F_0\\Big(\\frac{pq}{p+q}R^2_{PQ}\\Big).\n\\end{equation}\n\n\n\n\n\\section{The Boys function}\n\\label{section:Boys}\n\nAs shown in the previous section, calculating the Coulomb integrals boils down to evaluating the Boys function\n\\begin{equation}\n\\label{eq:boys}\n F_n(x) = \\int_0^1\\exp(-xt^2)\\,t^{2n}\\,dt.\n\\end{equation}\nDoing this by standard numerical procedures is compuationally\nexpensive and should therefore be avoided. This section describes one possible way to calculate the Boys function efficiently.\n\nFirst note that if $x$ is very large, the function value will hardly be affected by changing the upper limit of the integral from $1$ to $\\infty$. Doing this is beneficial\nbecause then the integral can be calculated exactly. Thus, we have the following approximation for the Boys function for large $x$:\n\\begin{equation}\n F_n(x) \\approx \\frac{(2n-1)!!}{2^{n+1}}\\sqrt{\\frac{\\pi}{x^{2n+1}}}. \\hspace{15mm} (x\\hspace{2mm}\\mathrm{large})\n\\end{equation}\nFor small values of $x$ there seems to be no escape from numerical calculation. However, instead of doing the integral at the time of computation, \nit can be tabulated once and for all at regular values of $x$. For values between the tabulated ones, the function can be calculated by a Taylor expansion centered at the nearest tabulated point $x_t$:\n\\begin{equation}\n F_n(x_t+\\Delta x) = \\sum_{k=0}^\\infty\\frac{F_{n+k}(x_t) (-\\Delta x)^k}{k!}. \\hspace{15mm} (x\\hspace{2mm}\\mathrm{small})\n\\end{equation}\nComputational cost can be reduced even further by calculating the Boys function according to the description above only for the highest values of $n$ needed; for lower values of $n$ the function\ncan be found via the recursion relation\n\\begin{equation}\n F_n(x) = \\frac{2xF_{n+1}(x)+e^{-x}}{2n+1},\n\\end{equation}\nwhich can be shown by integrating the function by parts.\n\n\n\\section{Summary of the integration scheme}\nIn the previous sections the integration scheme for GTOs has been derived. We summarise the results in this section. Some of the results are only elaborated fully for the $x$-component as\nthe others components are defined similarly.\n\n\\subsection*{Gaussian functions}\nThe Gaussian functions are given by\n\\begin{equation}\n \\begin{split}\n  G_a(\\vec r) & = G_{ikm}(a, \\vec r_A) = x^i_A\\,y^k_A\\,z^m_A\\exp(-a r^2_A), \\\\\n  G_b(\\vec r) & = G_{jln}(b, \\vec r_B) = x^j_B\\,y^l_B\\,z^n_B\\exp(-b r^2_B),\n \\end{split}\n\\end{equation}\nwhere $\\vec r_A = \\vec r - \\vec A$ and $\\vec r_B = \\vec r - \\vec B$. We further define\n\\begin{equation}\n\\begin{split}\n  p & = a + b, \\\\\n \\vec P & = \\frac{a\\vec A + b\\vec B}{a + b}.\n\\end{split}\n\\end{equation}\n\n\n\\subsection*{Overlap integral $S_{ab}$}\nThe overlap integral\n\\begin{equation}\n S_{ab} = \\langle G_a|G_b\\rangle\n\\end{equation}\nis calculated as\n\\begin{equation}\n\\label{eq:Sab_compute}\n S_{ab} = E^{ij}_0\\,E^{kl}_0\\,E^{mn}_0\\,\\Big(\\frac{\\pi}{p}\\Big)^{3/2},\n\\end{equation}\nwhere\n\\begin{equation}\n E^{i=0,j=0}_0 = \\exp(-\\frac{ab}{a+b}X_{AB}^2),\n\\end{equation}\nand the desired coefficients are found via\n\\begin{equation}\n\\begin{split}\n E^{i+1,j}_t & = \\frac{1}{2p}E^{ij}_{t-1} + X_{PA}E^{ij}_t + (t+1)E^{ij}_{t+1}, \\\\\n E^{i,j+1}_t & = \\frac{1}{2p}E^{ij}_{t-1} + X_{PB}E^{ij}_t + (t+1)E^{ij}_{t+1}.\n\\end{split}\n\\end{equation}\n\n\n\n\\subsection*{Kinetic integral $T_{ab}$}\nThe kinetic integral is calculated as\n\\begin{equation}\n\\label{eq:Tab_compute}\n T_{ab} = -\\frac{1}{2}(T_{ij}\\,S_{kl}\\,S_{mn} + S_{ij}\\,T_{kl}\\,S_{mn} + S_{ij}\\,S_{kl}\\,T_{mn}),\n\\end{equation}\nwhere\n\\begin{equation}\n T_{ij} = 4b^2\\,S_{i,j+2} - 2b(2j + 1)S_{i,j} + j(j-1)S_{i,j-2}.\n\\end{equation}\n\n\\subsection*{Coulomb integral $V_{ab}$}\nThe Coulomb integral\n\\begin{equation}\n V_{ab} = \\bra{G_a}\\frac{1}{r_C}\\ket{G_b}\n\\end{equation}\nis calculated as\n\\begin{equation}\n\\label{eq:Vab_compute}\n V_{ab} = \\frac{2\\pi}{p}\\sum_{tuv}E^{ab}_{tuv} R_{tuv}(p,\\vec R_{PC}),\n\\end{equation}\nwhere\n\\begin{equation}\n E^{ab}_{tuv} = E^{ij}_t\\,E^{kl}_u\\,E^{mn}_v,\n\\end{equation}\nand $R_{tuv}(a,\\vec A)$ is found by first calculating the source term\n\\begin{equation}\n R^n_{000}(a,\\vec A) = (-2a)^n\\,F_n(a A^2)\n\\end{equation}\nand then iterating towards the target $R^0_{tuv}(a,\\vec A) = R_{tuv}(a,\\vec A)$ via the recurrence relations\n\\begin{equation}\n \\begin{split}\n  R^n_{t+1,u,v} & = tR^{n+1}_{t-1,u,v} + A_x R^{n+1}_{tuv}, \\\\\n  R^n_{t,u+1,v} & = uR^{n+1}_{t,u-1,v} + A_y R^{n+1}_{tuv}, \\\\\n  R^n_{t,u,v+1} & = vR^{n+1}_{t,u,v-1} + A_z R^{n+1}_{tuv}.\n \\end{split}\n\\end{equation}\n\n\n\\subsection*{Coulomb integral $g_{acbd}$}\nThe Coulomb integral\n\\begin{equation}\n g_{acbd} = \\bra{G_a G_c}\\frac{1}{r_{12}}\\ket{G_b G_d}\n\\end{equation}\nis calculated as\n\\begin{equation}\n\\label{eq:gabcd_compute}\n g_{acbd} = \\frac{2\\pi^{5/2}}{pq\\sqrt{p+q}}\\sum_{tuv}\\sum_{\\tau\\nu\\phi}(-1)^{\\tau+\\nu+\\phi}E^{ab}_{tuv}E^{cd}_{\\tau\\nu\\phi}R_{t+\\tau,u+\\nu,v+\\phi}(\\alpha,\\vec R_{PQ}),\n\\end{equation}\nwhere\n\\begin{equation}\n  \\alpha = \\frac{pq}{p + q}.\n\\end{equation}\n\n\n", "meta": {"hexsha": "1716eb8affc5992681127c6607f7ab2071d43411", "size": 39768, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/src/chapters/chapter3.tex", "max_stars_repo_name": "ManyBodyPhysics/CQMech", "max_stars_repo_head_hexsha": "8395f082392844a0e2831649aab4108324c86312", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2016-06-18T14:34:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T14:44:41.000Z", "max_issues_repo_path": "doc/src/chapters/chapter3.tex", "max_issues_repo_name": "ManyBodyPhysics/CQMech", "max_issues_repo_head_hexsha": "8395f082392844a0e2831649aab4108324c86312", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/src/chapters/chapter3.tex", "max_forks_repo_name": "ManyBodyPhysics/CQMech", "max_forks_repo_head_hexsha": "8395f082392844a0e2831649aab4108324c86312", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-02-18T15:21:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-18T15:21:45.000Z", "avg_line_length": 54.4021887825, "max_line_length": 222, "alphanum_fraction": 0.7072772078, "num_tokens": 12988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.32477183492559664}}
{"text": "%!TEX root = ../../dissertacao.tex\nThis chapter~\\label{chap:inductive} shows a brief introduction on formal verification and a more detailed explanation on the selected approach to be used in this work: the Inductive Method. The concepts will be restricted to the necessary elements needed for comprehension of the proposed problem.\n\n\n\n\n\n\\section{Formal Verification}\nUsing the previous definitions for security protocols, we note that one can reason about protocol rules, \\textit{verifying} if they are correct with respect to the protocol's goals.\n\nInformal reasoning on verifying protocols was the first attempt to guarantee their correctness, succeeding in recognizing some flaws and weaknesses quickly and providing a good understanding about protocols design~\\cite{Bella2007}. However, not finding an error does not mean that a certain model does not hold one, since informal methods may fail to identify critical flaws in major security protocols.\n\nA classical example is the Needham-Schröeder protocol~\\cite{NeedhamSchroeder78}. Despite the authors efforts on its specification and informal verification, security flaws were found using formal techniques based on Lowe's work~\\cite{Lowe96}. This was an optimal context for the rise of formal methods for verifying security protocols~\\cite{Meadows96, Meadows94, Kemmerer94, Burrows90}, providing a mathematical approach for reasoning about abstract protocols models.\n\nFormal verification requires the definition of such protocols in a proper language, suitable for the application of specific methods and, hopefully, the use of automated reasoning tools, improving proof methodology. Also, formal methods can be divided in two major categories, according to~\\cite{BoydMathuria2008}:\n\n\\begin{itemize}\n  \\item \\textbf{Model checking}: protocol behavior can be modeled as a finite set of states. Such proposal is suitable for checking if a given configuration satisfy a set of correctness conditions and analyze a certain past configuration, searching for attacks attempts. This approach is more appropriate for finding inconsistencies and attacks in the protocol rather than proving some of its correctness properties;\n\n  \\item \\textbf{Theorem proving}: the protocol can described as a model, where \\textit{all} possible behavior are considered. Thus, any wanted property must be described as a theorems and proved using the axioms stated by the model. This method is more suitable for proving the correctness and properties of the protocol rather than finding possible attacks on them.\n\\end{itemize}\n\n\n\n\\section{Method Introduction}\\label{sec:inductive-method}\nThe Inductive Method is a proof theory for modeling and reasoning about security protocol, which aims for both the formalization and the verification of such protocols, using model checking and structural induction. First, the intended protocol \\(\\mathcal{P}\\) must be defined as an inductively constructed model \\(P\\), composed by rules describing the real world steps of \\(\\mathcal{P}\\).\n\nAn infinitely countable set of agents is considered, who can fire events accordingly with the model \\(P\\), in any desired order or regularity. Agents can interleave between protocol sessions with their actions indefinitely. Among the agents, we stress a special one, the Spy, who has control over the network and compromised agents, it is used to model the threat scenario.\n\nAt a second stage, the model is verified towards proposed properties, reasoning along technical and theoretical traits. Here, structural induction takes a crucial role. If a security property must hold for the protocol, it must hold for all possible traces derived from the formal model \\(P\\), hence induction over the set of possible network traces is the main proof tool used in this phase.\n\nInduction has been previously used for the formalization of protocol, for example in the NRL Protocol Analyzar by C.~Meadows~\\cite{Meadows96}, and the Inductive Method has similarities with other model checking theories, like CSP~\\cite{RyanSchneider2010}. It comprehends a strong threat model and concurrency among peers, however it does not check liveness properties. Moreover, the framework on which it is built provides easy ways for extension, allowing steady formalizations of atypical systems, a feature which interests us.\n\nThe method was first proposed by L.~Paulson~\\cite{Paulson98} and extended by G.~Bella~\\cite{Bella2007}. It has been used for the verification of many deployed and significant protocols~\\cite{Paulson99, BellaPaulson2006, Bella2003}.\n\n\n\n\\subsection{Isabelle}\nGiven the considerably great number of possible agents and possible traces which can be derived from a model, correctness proofs can take a substantial amount of work. As a result, the use of an automatic theorem prover is desirable. Isabelle~\\cite{isabelle} is one of such systems, where the theory framework is built on, providing machine verifiable and maintainable proofs scripts.\n\nIsabelle is a generic theorem prover, which can reason over several formal systems, in an interactive way. Hence, proofs are not entirely automatic, requiring certain user guidance. It combines high order logic, typed formalism and quantifiers for functions, predicates and sets. Also, the system has a good range of proof tools: simplifiers, induction-oriented commands and access to some automatic provers and state-of-the-art theories.\n\nLemmas and theorems are stated as goals, to which the user must apply proof tactics, being able to use previously proved lemmas. Such process may derive subgoals, which also need to be dealt with. Hence, the proof process is arduous and must be done with care. If an user fails to find a proof for a certain property, this may not be a certification of the nonexistence of a proof. At the same time, the proof or some of its aspects may be built on top of wrong formalizations, meaning the user is not skilled enough.\n\nEach formalized theory in Isabelle is contained in a proof script. Also, each Isabelle distribution comes with a library of such formalizations. The Inductive Method framework is defined in the \\textit{Auth} library~\\cite{isabelle-hol-auth}, comprised in three files: \\texttt{Message.thy}, \\texttt{Event.thy} and \\texttt{Public.thy}. The content of those files will be depicted over the rest of this chapter, where some of Isabelle syntax will be presented, when convenient.\n\n\n\n\\subsection{Agents}\nAgents are described in the \\texttt{Message.thy} file, being the basic type for specifying participants in a protocol session. Three main entities are defined as free types: legal agents (Friends ), the Spy and the Server. In the definition below, the \\( \\triangleq \\) symbol reads as a definition equality operator for a keyword and the \\(|\\) symbol is the disjunction operator, separating the possible types for the \\texttt{agent} datatype.\n\n\\begin{center}\n  {\\ttfamily datatype agent \\( \\triangleq \\) Server | Spy | Friend \\(nat\\)}\n\\end{center}\n\nThe set of legal agents has a correspondence with the set of natural numbers. Thus, we have both an easy mapping for each participant of a protocol session and removal of limitations of its population size, providing the ability to reason over protocols with an indefinite and infinite number of peers.\n\nThe nullary constructor \\texttt{Server} defines the trusted third part entity, presented in many protocols. It is considered uncompromisable and holds the long-term secrets (keys) of all agents. The Spy is the malicious agent, but who can also act as a legal one. She has access to the secrets of all compromised agents and her own secrets.\n\n\n\n\\subsection{Cryptographic Keys}\nAlso defined in \\texttt{Message.thy}, cryptographic keys are bounded to the natural numbers, but constrained within a proper set. Later, each type of key is normally defined as a relation between the sets of agents and keys. For instance, the habitual specification of shared keys is defined as follows, where the \\( \\longrightarrow \\) symbol defines the relation between the type sets.\n\n\\begin{center}\n  {\\ttfamily \\(shrK\\): agent \\( \\longrightarrow \\) key}\n\\end{center}\n\nThe description of public and private keys structures uses a similar construction. The set \\texttt{symKeys} helps in the distinction between of long-term keys and session keys. Both types are considered shared keys, but the latter is commonly a fresh entity generated at protocol runtime and distributed among peers. Below, \\texttt{range} is a function which gives us the image of a given function.\n\n\\begin{center}\n  {\\ttfamily \\(K \\in \\) symKeys} and {\\ttfamily \\(K \\notin \\) range \\(shrK\\)}\n\\end{center}\n\nFinally, the function \\(invKey\\) receives a key and returns its inverse key, which can decipher any cipher created by the former. If it is applied to a symmetric key, it return the same key, while for asymmetric keys, the respective half is returned. Any other kind of keys not mentioned here must be manually defined.\n\n\n\n\\subsection{Messages}\nA message is any kind of information that can be transmitted during the execution of a protocol. This includes agents names, keys, nonces, timestamps, and so on. Therefore, its constructor accepts many kinds of formats, as stated below:\n\n\\begin{equation*}\n  \\begin{split}\n    \\texttt{datatype} \\triangleq\\\n    & \\texttt{\\textbf{Agent} agent} | \\\\\n    & \\texttt{\\textbf{Nonce} nat} | \\\\\n    & \\texttt{\\textbf{Key} key} | \\\\\n    & \\texttt{\\textbf{Mpair} msg msg} | \\\\\n    & \\texttt{\\textbf{Hash} msg} | \\\\\n    & \\texttt{\\textbf{Crypt} key msg}\n  \\end{split}\n\\end{equation*}\n\nSome of the accepted datatypes are constructors and others are simply natural numbers. If any other datatype is needed, the definition of this scope must be extended.\n\nAnother important concept is the \\texttt{Crypt} directive. It receives a message \\(M\\) and a key \\(K\\) and produces the corresponding cipher, i.e.\\ \\texttt{Crypt} \\(M\\ K\\). In this model, encryption is perfect and collision-free, so a message is only accessible within a cipher by a peer if she has the proper key.\n\nSome protocol formalizations demand new types of message, since security protocols often resort on numeric entities for soundness of some properties. Significant ones are described below:\n\n\\begin{description}\n  \\item[Nonces] are big random natural numbers which are unguessable to any agent, including the Spy.\n\n  \\item[Guessable numbers] are natural numbers, often used to model message option fields, time properties and similar concepts. As a result, they are always known by the Spy.\n\n  \\item[Timestamps] are defined on top of the length of a trace, instead of relying on classical time units. Its definition and properties will be further explored in the sections below.\n\\end{description}\n\n\n\n\\subsection{Events}\nEvents, defined in the theory \\texttt{Event.thy}, are the basic units that compose network traces. There are three main events, which are suitable for the analyzed protocol in this work, although there are more available for others protocols:\n\n\\begin{equation*}\n  \\begin{split}\n    \\texttt{datatype} \\triangleq\\\n    & \\texttt{\\textbf{Says} agent agent msg} \\\\\n    & \\texttt{\\textbf{Notes} agent msg} \\\\\n    & \\texttt{\\textbf{Gets} agent msg}\n  \\end{split}\n\\end{equation*}\n\nThe action of \\texttt{Says} is straightforward and it follows easily from its syntax: the first agent is the sender, the second is the intended receiver and the third parameter is the message which will be sent.\n\nBoth events \\texttt{Notes} and \\texttt{Gets} are related to information acquisition by an agent. The former is the literal action of an agent obtaining and storing a given message, enabling them to explore messages contents, deriving new information, and the Spy on collecting data from the network. The latter event denotes message reception by an agent, but without enrichment of agent's knowledge. It was a late extension of the Inductive Method~\\cite[Ch. 8]{Bella2007}, in order to explore an agents' knowledge set of messages. Without this, agents' knowledge would be constrained to past events only. Additionally, the creation of such event, introduces the concept of \\textit{reception invariant}, demanding that \\texttt{Gets} events are preceded by a \\texttt{Says} event. This guarantee must be enforced by the protocol model.\n\nA \\textit{trace} can now be defined: a list of network events occurring while an unbounded population of agents are running the protocol. Specifically, the trace is a list of such events, disposed in reverse chronological order, since events are added at the list head. Hence, traces may have many configurations, but must stay faithful to the protocol model. The set of possible traces of a given protocol characterizes its formal model.\n\nWe can now recall some aspects concerning timestamps. In the Inductive Method, a timestamp describes the moment where an event happened in a trace, using the trace length as the measure. Therefore, for generating a timestamp, the following function is used:\n\n\\begin{center}\n  {\\ttfamily CT\\@: event list \\(\\longrightarrow \\) nat}\n\\end{center}\n\nThus, the function receives a trace and returns a natural number, which will be the length of that trace, leading to the following definition, where \\texttt{length} trivially denotes the function that returns the length of a trace.\n\n\\begin{center}\n  {\\ttfamily CT \\(evs \\triangleq \\) length \\(evs\\)}\n\\end{center}\n\nPrecisely, the timestamp for a trace which has \\(n\\) events will be \\(n\\) and, consequently, an event happening at that moment will receive a timestamp value of \\(n\\). Note that such definition does not allow that two distinct events have the same timestamp, eliminating concurrency among events in the same trace. Further, this concept is properly guaranteed by the existence of two distinct traces, where such two events happens at switched positions, defining two corresponding sequential approximations.\n\n\n\\subsection{Threat Model}\\label{ssec:threat-model}\nThe standard thread model used in the Inductive Method is based upon the Dolev-Yao~\\cite{DolevYao81} approach, introducing three main characteristics concerning the Spy:\n\n\\begin{enumerate}\n  \\item \\textit{The Spy is a legitimate agent:} since she can act as a legal agent, she has their same features, such as shared keys with the Server, public asymmetric keys, etc.;\n\n  \\item \\textit{The Spy controls the network traffic:} this copes with the capability of the Spy on monitoring and obtaining messages sent on network channel and  preventing the delivery or redirecting messages;\n\n  \\item \\textit{The Spy can perform any message operation, except cryptanalysis:} with this abilities, the Spy can break, compose and modify messages on-the-fly, being able to alter legal messages or create fake ones. There is only one exception, she must hold the correspondent key to a cipher in order to obtain the plain text, which guarantees that any encryption is perfect.\n\\end{enumerate}\n\nThe Inductive Method implements all of these three aspects. The first one is already assured by the definitions of agents and cryptographic keys. Moreover, the protocols models should enable the Spy to participate as a legal action along their runs.\n\nThe set \\texttt{bad} contains all agents which are compromised by the Spy. These agents disclose all their secrets to the malicious peer, both prior and during the protocol run. The Spy herself is also included in this set. Secrets are contained in the agent's knowledge set, which is a crucial concept for meeting the second requirement of the threat model.\n\nFunction \\textit{initState} describes the peer knowledge set prior to any protocol interaction, defined as follows.\n\n\\begin{center}\n  {\\ttfamily \\(initState\\): agent \\(\\longrightarrow \\) msg set}\n\\end{center}\n\n\\begin{enumerate}\n  \\item The Server initially knows all shared and public keys and its own private keys;\n  %\n  \\begin{equation*}\n    \\begin{split}\n      initState\\ \\texttt{Server} \\triangleq\\\n      & (\\texttt{Key range}\\ shrK) \\cup (\\texttt{Key range}\\ pubK)\\ \\cup \\\\\n      & \\{\\texttt{Key}\\ (priK\\ \\texttt{Server})\\}\n    \\end{split}\n  \\end{equation*}\n  %\n  \\item Each legitimate agent initially knows its own shared and private keys and all public keys;\n  %\n  \\begin{equation*}\n    \\begin{split}\n      initState (\\texttt{Friend}\\ \\textit{i}) \\triangleq\\\n      & \\{ \\texttt{Key}\\ (shrK\\ (\\texttt{Friend}\\ i))\\}\\ \\cup \\\\\n      & \\{ \\texttt{Key}\\ (priK\\ (\\texttt{Friend}\\ i))\\}\\ \\cup \\\\\n      & (\\texttt{Key range}\\ pubK)\n    \\end{split}\n  \\end{equation*}\n  %\n  \\item The Spy knows all secrets from a compromised agent, which includes herself. Additionally, she also knows all public keys.\n  %\n  \\begin{center}\n    \\[\n      initState\\ \\texttt{Spy} \\triangleq (\\texttt{Key}\\ shrK\\ \\texttt{bad}) \\cup (\\texttt{Key}\\ priK\\ \\texttt{bad}) \\cup (\\texttt{Key range}\\ pubK)\n    \\]\n  \\end{center}\n\\end{enumerate}\n\nFunction \\textit{knows} defined how the agents' dynamic knowledge is built during the protocol run. Its definition is presented below, where the symbol \\#  denotes the concatenation of an element at the head of a list.\n%\n\\begin{center}\n  \\(knows\\): [\\texttt{agent, event list}] \\(\\longrightarrow \\) \\texttt{msg set}\n\\end{center}\n%\n\\begin{enumerate}\n  \\item An agent knows her initial state\n  %\n  \\begin{center}\n    \\(knows\\ A\\ [] \\triangleq\\ initState\\ A\\)\n  \\end{center}\n  %\n  \\item An agent knows what she sends to anyone in a trace and the Spy knows all messages ever sent over it.\n  %\n  \\begin{center}\n    \\(knows\\ A\\) ((\\texttt{Says} \\(A'\\ B \\ X\\)) \\# \\(evs\\)) \\(\\triangleq \\)\n    \\(\\left \\{\n      \\begin{array}{@{}ll@{}}\n        {X} \\cup knows\\ A\\ evs, & \\text{if } A \\in \\texttt{bad} \\\\\n        knows\\ A\\ evs, & \\text{otherwise}\n      \\end{array} \\right.\\)\n  \\end{center}\n  %\n  \\item An agent knows what she notes in a trace, while the Spy also knows the compromised agents' notes\n  %\n  \\begin{center}\n    \\(knows\\ A\\) ((\\texttt{Notes} \\(A'\\ X\\)) \\# \\(evs\\)) \\(\\triangleq \\)\n    \\(\\left \\{\n      \\begin{array}{@{}ll@{}}\n        {X} \\cup knows\\ A\\ evs, & \\text{if } A = A' \\text{ or } \\\\ & (A = \\texttt{Spy} \\text{ and } A' \\in \\texttt{bad}) \\\\\n        knows\\ A\\ evs, & \\text{otherwise}\n      \\end{array} \\right.\\)\n  \\end{center}\n  %\n  \\item An agent, except the Spy, knows what she receives in a trace. The Spy knowledge is not enriched here since she already knows by case 2 and by the reception invariant.\n  %\n  \\begin{center}\n    \\(knows\\ A\\) ((\\texttt{Gets} \\(A'\\ X\\)) \\# \\(evs\\)) \\(\\triangleq \\)\n    \\(\\left \\{\n      \\begin{array}{@{}ll@{}}\n        {X} \\cup knows\\ A\\ evs, & \\text{if } A = A' \\text{ and } A \\neq \\texttt{Spy} \\\\\n        knows\\ A\\ evs, & \\text{otherwise}\n      \\end{array} \\right.\\)\n  \\end{center}\n\\end{enumerate}\n\nIt is important to note that the expression \\(knows\\) \\texttt{Spy} \\(evs\\) expresses the entire network traffic occurred to the point registered in \\(evs\\). With these formalizations, the attacker's omnipotence requirement for the threat model is fulfilled. For the third one, the definition of message operations will be necessary, as given in the next section.\n\n\n\n\\subsection{Operators}\\label{ssec:operators}\nOperators are functions for reasoning about message sets. They translate the act of exploring and producing messages, being defined as follows.\n\n\\begin{center}\n  \\texttt{analz, synth, parts: msg set \\(\\longrightarrow \\) msg set}\n\\end{center}\n\nIn this section, some new symbols are introduced. The symbol \\(\\Longrightarrow \\) denotes a sequent, where \\(\\Gamma \\Longrightarrow \\Delta \\) reads as {\\em if \\(\\Gamma \\) holds, then so does \\(\\Delta \\)}. Also, the \\(\\lBrack \\) and \\(\\rBrack \\) symbols are a shorthand syntax for the \\texttt{Mpair} constructor, denoting concatenation of messages, while \\(\\lBrace \\) and \\(\\rBrace \\) are concatenation of clauses in a list.\n\nThe \\texttt{analz} operator denotes the act of inspecting the components of a message, breaking it up. Therefore, considering the message set \\(H\\), the set \\texttt{analz} \\(H\\) uses the following rules below.\n\n\\begin{enumerate}\n  \\item Any element of a message set \\(H\\) can be analyzed from it;\n  \\begin{center}\n    \\(X \\in H \\Longrightarrow X \\in \\) \\texttt{analz} \\(H\\)\n  \\end{center}\n\n  \\item Any element in a given concatenation of messages, that could be analyzed from its message set, can also be analyzed from it;\n  \\begin{center}\n    \\(\\Bracks{X,Y} \\in \\texttt{analz} H \\Longrightarrow X \\in \\) \\texttt{analz} \\(H\\) \\\\\n    \\(\\Bracks{X,Y} \\in \\texttt{analz} H \\Longrightarrow Y \\in \\) \\texttt{analz} \\(H\\)\n  \\end{center}\n\n  \\item The contents of an analyzed cyphertext can only properly be analyzed and further retrieved in possession of its decryption key.\n  \\begin{center}\n    \\(\\Braces{\\texttt{Crypt}\\ K\\ X \\in \\texttt{analz}\\ H; \\texttt{Key}\\ (invKey\\ K) \\in \\texttt{analz}\\ H} \\Longrightarrow X \\in \\texttt{analz}\\ H\\)\n  \\end{center}\n\\end{enumerate}\n\nThe set \\texttt{analz (spies) \\textit{evs}} holds all data that the Spy can gather from the network in the trace \\textit{evs}, either by decomposition or decryption of ciphers. Thus, saying a set of message \\(X\\) does not belong to this set is equivalent to state the confidentiality of \\(X\\) in such trace.\n\nThe second operator is the \\texttt{synth}, which basically denotes the action of composing messages from given components. Its rules are the following:\n\n\\begin{enumerate}\n  \\item Any element or agent name can be synthesized from a message set;\n  \\begin{center}\n    \\(X \\in H \\Longrightarrow X \\in \\texttt{synth}\\ H\\) \\\\\n    \\(\\texttt{Agent}\\ A \\in \\texttt{synth}\\ H\\)\n  \\end{center}\n\n  \\item If a message can be synthesized from a message set, then so it can its hash;\n  \\begin{center}\n    \\(X \\in \\texttt{synth}\\ H \\Longrightarrow \\texttt{Hash}\\ X \\in \\texttt{synth}\\ H\\)\n  \\end{center}\n\n  \\item If two messages can be synthesized from a message set, then so it can its concatenation;\n  \\begin{center}\n    \\(\\Braces{X \\in \\texttt{synth}\\ H; Y \\in \\texttt{synth}\\ H} \\Longrightarrow \\Bracks{X,Y} \\in \\texttt{synth}\\ H\\)\n  \\end{center}\n\n  \\item If a key belongs to a message set and a message can be synthesized from it as well, then so the encryption of the message with the given key.\n  \\begin{center}\n    \\(\\Braces{\\texttt{Key}\\ K \\in H; X \\in \\texttt{synth } H} \\Longrightarrow \\texttt{Crypt}\\ K\\ X \\in \\texttt{synth}\\ H\\)\n  \\end{center}\n\\end{enumerate}\n\nFinally, the last operator \\texttt{parts} is very similar to the \\texttt{analz} operator, hence its rules are similar to the latter, except the one concerning encryption:\n\n\\begin{enumerate} \\setcounter{enumi}{3}\n  \\item The contents of any cyphertext can be obtained.\n  %\n  \\begin{center}\n    \\(\\texttt{Crypt}\\ K\\ X \\in \\texttt{parts}\\ H \\Longrightarrow X \\in \\texttt{parts}\\ H\\)\n  \\end{center}\n\\end{enumerate}\n\nThereby, the extraction of messages from ciphers does not require a key in this operator, simulating unbounded computational power. This operator is mainly used in analysis of agents' knowledge sets along proofs and not used to give an agent unlimited power over sets of messages. Additionally, the following relation can be derived concerning the last two operators:\n\n\\begin{center}\n  \\texttt{analz} \\(\\subseteq \\) \\texttt{parts}\n\\end{center}\n\nFinally, \\textit{freshness} can be defined. Normally, nonces and session keys demand to be freshly generated in order to increase security. To analyze this properties for a given message the following function is defined, which receives a trace and return the messages used in that trace:\n\n\\begin{center}\n  \\(used\\): \\texttt{event list} \\(\\longrightarrow \\) \\texttt{msg set}\n\\end{center}\n\n\\begin{enumerate}\n  \\item All components of any agent's initial state are used in a trace, including the empty one\n  %\n  \\begin{center}\n    \\(used\\ [] \\triangleq \\bigcup A\\). \\texttt{parts}\\( (initState\\ A)\\)\n  \\end{center}\n  %\n  \\item All components of messages sent in a trace are used in that trace\n  %\n  \\begin{center}\n    \\(used\\ A\\) ((\\texttt{Says} \\(A\\ B\\ X\\)) \\# \\(evs\\)) \\(\\triangleq \\) \\texttt{parts} \\( \\{X\\} \\cup used\\ evs\\)\n  \\end{center}\n  \\item All components of messages noted in a trace are used in that trace\n  %\n  \\begin{center}\n    \\(used\\ A\\) ((\\texttt{Notes} \\(A\\ X\\)) \\# \\(evs\\)) \\(\\triangleq \\) \\texttt{parts} \\( \\{X\\} \\cup used\\ evs\\)\n  \\end{center}\n  \\item All components of messages received in a trace do not count as used, due to reception invariant and hence, they are already considered as used.\n  %\n  \\begin{center}\n    \\(used\\ A\\) ((\\texttt{Gets} \\(A\\ X\\)) \\# \\(evs\\)) \\(\\triangleq \\) \\texttt{parts} \\( \\{X\\} \\cup used\\ evs\\)\n  \\end{center}\n\\end{enumerate}\n\nHence, it is said to a component to be fresh in a given protocol execution when such component was not used prior to that execution.\n\n\n\\subsection{Protocol Model}\nOnce all elements are properly defined, we are able to formally define the protocol model. As previously stated, the model will be structured as a set of unlimited traces, representing all possible network histories induced by the protocol. Here, we use the protocol in Figure~\\ref{prt:notation-example} as the basis for our example. The corresponding model is presented in Figure~\\ref{fig:notation-example-model}.\n\nThe model rules are composed by two parts. The first part are the preconditions, a list of clauses that need to be true in order to fire the correspondent event. The latter are the postconditions, which states which events will be added to the head of the trace, composing the network history.\n\nRule \\texttt{Nil} is the base case, where the empty trace is a valid trace in a protocol session. Rules \\texttt{DSP1} and \\texttt{DSP2} emulate the protocol steps, hence if a protocol has \\(n\\) parts, the model should contain at least \\(n\\) rules. A regular precondition among rules are that the trace must be faithful to the model, thus, considering a trace \\(evs\\), then \\(evs\\) should belong to the model. In rule \\texttt{DP2}, we see that the preconditions contains a \\texttt{Gets} event resembling rule \\texttt{DP1}, showing a common formalization of how rules demand previous ones.\n\nThe rule \\texttt{Fake} aides the formalization of the threat context, where the Spy can fake a message \\(X\\) once she has the necessary knowledge, i.e.\\ message \\(X\\) belongs to the set of data which can be constructed based on her knowledge set. The rule \\texttt{Oops} abstracts the loss of a session key to the Spy by accident. This local security breach is used to model specific situations where a lost session key could affect future protocol sessions. Thus, this rule only concerns protocol involving this kind of keys.\n\nFinally, the rule \\texttt{Rcpt} is meant to fulfill the \\textit{reception invariant}, i.e.\\ a message can only be received if it was previously sent. Note that it does not guarantee that sent messages will ever be received, but only enforces that traces with \\texttt{Gets} events must have a matching \\texttt{Says} event.\n\n\\begin{figure}\\label{fig:notation-example-model}\n  \\centering\n  \\includegraphics[width=0.8\\textwidth]{img/prt-example-model}\n  \\caption{Formal model for the protocol displayed in Figure~\\ref{prt:notation-example}}\n\\end{figure}\n\n\n\n\n\n\\section{Goals Verification}\nSecurity protocols have technical properties that are inherent to its system, outlining how peers should communicate and the protocol proceed. Meanwhile, other important security aspects, introduced in Chapter~\\ref{chap:sec-protocols}, are another kind of features that should be part of such specifications, being them another crucial role.\n\nWhen the protocol formal model is defined, its underlying characteristics are not explicit. We need to present them, precisely stating its form, and proving that they are valid in the model, i.e.\\ they hold in all conceivable trace. This is the \\textit{goal verification} stage, where each desired protocol feature is modeled as a goal and formal proofs build their validation to the model. Goals are divided in types, concerning the protocol property scope.\n\nAt the end, we also try to show that \\textit{goal availability} is present in the model. This property provides formal guarantees to the agents that a given goal is present in that model, even under a threat model. Hence, these agents are assured that the protocol is reliably faithful to what it intends to offer.\n\n\n\n\\subsection{Reliability}\nReliability relates to how close a model is to the system it is representing. Note that such crucial property may not be really related to the security protocol goals but to the system goals itself. As a result, the number of reliability theorems may vary from a protocol to another.\n\nHowever, some basic properties, which are common for many protocols, are already defined and likely to be used in new formalizations. Some of them may seem obvious, but are important for formal systems. As examples, we can cite the idempotence of \\texttt{analz} operator, fresh keys and session keys proper distinction, and the certainty of messages composition correctness.\n\nThe theorems of this class are easy to prove. They mainly use induction and simplification as its main proof strategy. Providing such goals gives us assurance that our model is reliable to the real world.\n\n\n\n\\subsection{Regularity}\nThe regularity lemmas are facts that can be proved from any message that appears in the traffic. Such properties may be applied to specific protocol goals, but some other broader properties can be guaranteed using them.\n\nFor example, regularity lemmas hold for long-term keys which can never be sent through the channel, since they are never meant to be used over the network, just in a agent local context. Therefore, if such agent key is seen in the traffic it is easy to derive that this agent is compromised, as stated below.\n\n\\begin{center}\n  \\texttt{Key} (\\(shrK\\ A\\)) \\(\\in \\) \\texttt{parts} (\\(knows\\) \\texttt{Spy} \\textit{evs}) if and only if \\(A \\in bad\\)\n\\end{center}\n\n\n\n\\subsection{Confidentiality}\nHolding confidentiality in a protocol can be simply translated as to preventing the disclosure of certain messages to the Spy, that is, a message \\(X\\) cannot belong to the Spy knowledge set. Since messages are usually protected by encryption, this property is highly related to the use of cryptographic keys.\n\nPrecisely, the confidentiality of such keys is a major issue for the protocol confidentiality, specially session keys, because if the Spy obtains them, all messages encrypted under these keys could be easily acquired and altered by her. Hence, given a key \\(K\\), we have to be certain that at the end of all traces the key does not belong to the Spy knowledge set, as defined below.\n\n\\begin{center}\n  \\(\\texttt{Key}\\ K \\notin \\texttt{analz}\\ (knows\\ \\texttt{Spy}\\ evs)\\)\n\\end{center}\n\nNote that if \\(K\\) is encrypted with some other private key of an agent, the latter cannot be part of the compromised agents set. Otherwise, the Spy could easily retrieve the key from the compromised agent, obtaining the session key and further messages. Confidentiality is also interesting for nonces, which are commonly used for assuring authenticity, computing checksum and other operations.\n\n\n\n\\subsection{Unicity}\nThe creation of fresh components in protocol is vastly used. It is seen in the production of session keys, nonces and other entities and they are mostly used for a single session, identifying it. Therefore, providing freshness in a protocol resembles unicity, a concept that establishes bounds between a message and its fresh components.\n\nMore precisely, if two events contain the same fresh message component, then they must be identical. Further, events containing fresh message components cannot occur more than once, otherwise they violate the unicity concept. Such lemmas are deeply explored when protocols apply the use of nonces and timestamps.\n\nA formalization for this definition prompted the creation of a new predicate in Isabelle/HOL \\textit{Auth} library, the \\texttt{Unique} predicate. It takes an event and a trace as parameters, holding if the given event is unique in the given trace. Such formalization is crucial for detecting replay attacks over traces.\n\n\n\n\\subsection{Authenticity}\nThis property can also be read as legitimacy. In the method, the guarantee of a message's authorship is presented as synonym of integrity, since if the message is unaltered (integrity), then the authorship must be preserved. Even if the Spy intercepts the message and them relays it to the recipient, if integrity is preserved, then legitimacy is still preserved, since the Spy acted as a channel relay.\n\nAs a result, it is important that the message's author does not belong to the compromised agent set. Otherwise, any messages sent by him would be compromised as well and authenticity would not hold. Such concept may seem obvious for integrity matters, but it is important to enforce the authorship interest. Therefore, both properties are attached during our verification.\n\n\n\n\\subsection{Authentication}\nAs discussed in Section~\\ref{sec:protocols:auth}, authentication may assume many properties. Suppose an initiator \\(A\\), who completes a protocol session with a responder \\(B\\). In this run, authentication may be translated as:\n\n\\begin{enumerate}\n  \\item \\textbf{Aliveness of B}, meaning that \\(B\\) has been running the protocol;\n  \\item \\textbf{Weak agreement of \\(B\\) with \\(A\\)}, meaning that \\(B\\) has been running the protocol with \\(A\\);\n  \\item \\textbf{Non-injective agreement of \\(B\\) with \\(A\\) on \\(H\\)}, meaning a weak agreement of \\(B\\) with \\(A\\), considering the set \\(H\\) of message components;\n  \\item \\textbf{Injective agreement of \\(B\\) with \\(A\\) on \\(H\\)}, meaning the non-injective agreement of \\(B\\) with \\(A\\), using the set \\(H\\) of message components, where \\(B\\) did not respond more than once on each session with \\(A\\).\n\\end{enumerate}\n\nThe Inductive Method does not provide formalisms to reason about the fourth point. Although, it is claimed on~\\cite{Bella2007} that such formalization can be easily constructed by simple verification of repetition of a given event \\textit{ev} in the analyzed trace, restraining the agents to single responses. However, the method mainly tries to provide models that are more permissive as possible, stating that any message could be repeated over traces with no harm to model.\n\nSpecifically, non-injective agreements have a wider focus. Regarding key distribution protocols, such property applied to session keys establishes a trust relation between the two agents, with a given key as a validation of such relationship, since both agents are uncompromised.\n\nEventually, \\textbf{key distribution} becomes a major goal to be checked. Since this concept is related to the agreement of two agents in a mutual secret, it is stated in~\\cite{BellareRogaway93} that this property is, indeed, stronger than authentication and thus, authentication itself relies on key distribution. Additionally, the authors of the Inductive Method prove that if authentication holds, so does key distribution, specifically non-injective agreement on a session key.\n\n\n\n\\subsection{Goal Availability}\nThe concept of goal availability is one of the main contributions in the work of G.~Bella~\\cite{Bella2007}. In summary, it establishes a formal guarantee that the protocol model could meet a given goal and, once this is true, the validity of such goal can be applied to all peers within their assumptions. If such property holds in the model, but cannot be checked by the peers, it is argued that this goal is not available and thus, not fully assured.\n\nAlso, goal availability is closely related to the threat model considered by the protocol and its peers minimal trust. Considering the former, our adopted model is the Dolev-Yao, faithfully implemented by the Inductive Method using abstractions described in Sections~\\ref{ssec:threat-model} and~\\ref{ssec:operators}. If a different threat model is considered, important aspects of the model context are also altered, which may change the validity of previous goals.\n\n\\textit{Minimal trust} concerns facts that agents must assume true, due to inability to verify them, in order to check a protocol guarantee from their point of view. Precisely, agents can only verify what they send and receive from the network, having no guarantees at all about other peers. Likewise, agents cannot state if they are compromised. Therefore, they must take such facts as true, in order to establish a suitable set of clauses to attest some goal. We formally define minimal trust below.\n\n\\begin{definition}\n  Let \\(\\mathcal{P}\\) be a security protocol, \\(P\\) be a formal model for \\(\\mathcal{P}\\), and \\(A\\) be an agent's name. The \\textit{minimal trust} of \\(A\\) is the set of environmental facts formalized in \\(P\\) whose truth values \\(A\\) needs to know but can never verify.\n\\end{definition}\n\nHaving the notion of what agents can verify, an \\textit{applicable guarantee} can be defined.\n\n\\begin{definition}\n  Let \\(\\mathcal{P}\\) be a security protocol, \\(P\\) be a formal model for \\(\\mathcal{P}\\), and \\(A\\) be an agent's name. A formal guarantee in \\(P\\) is \\textit{applicable} by \\(A\\) if it is established on the basis of assumptions that \\(A\\) is able to verify in \\(P\\) within her minimal trust.\n\\end{definition}\n\nIn these previous definitions, it is clear that guarantees that are applicable by an honest agent \\(A\\) are not necessarily applicable by another honest agent \\(B\\). Hence, this strengthens the argument that only proved assumptions concerning protocol messages, specially the ones related to the agent, are the valid formal guarantees for a given protocol goal.\n\nFinally, the definition of available goal can be made. The principle should be used to guide the formal proofs about goals. As a result, whenever a goal is not available to some peer, it is not guaranteed at that model and so, it does not hold for the given protocol.\n\n\\begin{definition}\n  Let \\(\\mathcal{P}\\) be a security protocol, \\(P\\) be a formal model for \\(\\mathcal{P}\\), \\(g\\) be a goal for \\(\\mathcal{P}\\), and \\(A\\) be an agent's name. The goal \\(g\\) is \\textit{available} to \\(A\\) in \\(P\\) if there exists a formal guarantee in \\(P\\) that confirms \\(g\\) and that is applicable by \\(A\\) in \\(P\\).\n\\end{definition}\n", "meta": {"hexsha": "8f02a3a86545abe6df150e189918bc8ea23143e8", "size": 38147, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/src/chaps/3.inductive.tex", "max_stars_repo_name": "rodopoulos/dap-verification", "max_stars_repo_head_hexsha": "bcc17195754594a5c102719f2a486fa9a0564010", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/src/chaps/3.inductive.tex", "max_issues_repo_name": "rodopoulos/dap-verification", "max_issues_repo_head_hexsha": "bcc17195754594a5c102719f2a486fa9a0564010", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/src/chaps/3.inductive.tex", "max_forks_repo_name": "rodopoulos/dap-verification", "max_forks_repo_head_hexsha": "bcc17195754594a5c102719f2a486fa9a0564010", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 80.8199152542, "max_line_length": 833, "alphanum_fraction": 0.7598238394, "num_tokens": 9093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3247718349255966}}
{"text": "\\chapter{Classification and Prediction}\r\n\r\nThus far in the book, the term \\emph{information}\r\nhas been used sparingly and when\r\nit has been used, we have purposely been imprecise as to its meaning.\r\nAlthough, everyone  has an intuitive feeling for what information is,\r\nit is difficult to attach\r\na meaningful quantitative definition to the term. In the context of\r\ncommunication systems, Claude Shannon was able to do exactly this,\r\nand as a result, opened up an entirely new view of communication systems\r\nanalysis and design \\cite[p.~123]{Albano1991}.\r\nThe principal contribution of Shannon's information theory to date has been\r\nto allow communication theorists to establish absolute\r\nbounds on communication systems performance that cannot be exceeded no matter\r\nhow ingeniously designed or complex our communication systems are.\r\nFundamental physical limitations on communication systems performance is\r\nanother topic that has been largely ignored in the preceding chapters,\r\nbut it is a subject of exceptional practical importance.\r\nFor example, for any of the numerous communication systems developed\r\nthus far in the book, we could decide to design\r\na new system that would outperform the accepted standard for a particular\r\napplication. The first question that we should ask is: how close is the\r\npresent system to achieving theoretically optimum performance?\r\nIf the existing communication system operates at or near the fundamental\r\nphysical limit on performance, our task may be difficult or impossible.\r\nHowever, if the existing system is far away from the absolute\r\nperformance bound, this might be an area for fruitful work.\r\n\r\n\\section{What is Classification? What is Prediction?}\r\n\\label{ch01.sec11.1}\r\n\r\nOf course, in specifying the particular communication system under\r\ninvestigation, we must know the important physical parameters,\r\nsuch as transmitted\r\npower, bandwidth, type(s) of noise present, and so on,\r\nand information theory allows these constraints to be incorporated.\r\nHowever, information theory does not provide a way for communication system\r\ncomplexity to be explicitly included.\r\nAlthough, this is something of a drawback, information theory itself provides\r\na way around this difficulty, since it is generally true that as we approach\r\nthe fundamental limit on the performance of a communication system,\r\nthe system complexity increases, sometimes quite drastically.\r\nTherefore, for a simple communication system operating far\r\nfrom its performance bound, we may be able to improve the performance\r\nwith a relatively modest increase in complexity.\r\nOn the other hand, if we have a rather complicated communication system\r\noperating near its fundamental limit, any performance improvement may\r\nbe possible only with an extremely complicated system.\r\n\r\nIn this chapter we are concerned with the rather general block diagram\r\nshown in Figure~\\ref{ch01.fig11.1.1}. Most of the early work by\r\nShannon and others ignored the source  encoder/decoder blocks and\r\nconcentrated  on bounding the performance of the channel\r\nencoder/decoder pair. Subsequently, the source  encoder/decoder blocks\r\nhave attracted much research attention.  In this chapter we consider\r\nboth topics and expose the reader to the nomenclature used in the\r\ninformation theory literature.\r\nQuantitative definitions of information are presented in\r\nSec.~\\ref{ch01.sec11.2} that lay the foundation for the remaining\r\nsections. In Secs.~\\ref{ch01.sec11.2} and~\\ref{ch01.sec11.2} we present\r\nthe fundamental source and channel coding theorems, give some examples,\r\nand state the implications of these theorems.\r\nSection~\\ref{ch01.sec11.2} contains a brief development of rate\r\ndistortion theory,\r\nwhich is the mathematical basis for data compression.\r\nA few applications of the theory in this chapter are presented\r\nin Sec.~\\ref{ch01.sec11.2}, and a technique for variable-length\r\nsource coding is given in Sec.~\\ref{ch01.sec11.2}.\r\n\\begin{equation}\r\nx = a + b - \\sqrt{q}\r\n\\end{equation}\r\nOf course, in specifying the particular communication system under\r\ninvestigation, we must know the important physical parameters,\r\nsuch as transmitted\r\npower, bandwidth, type(s) of noise present, and so on,\r\nand information theory allows these constraints to be incorporated.\r\nHowever, information theory does not provide a way for communication system\r\ncomplexity to be explicitly included.\r\nAlthough, this is something of a drawback, information theory itself provides\r\na way around this difficulty, since it is generally true that as we approach\r\nthe fundamental limit on the performance of a communication system,\r\nthe system complexity increases, sometimes quite drastically.\r\nTherefore, for a simple communication system operating far\r\nfrom its performance bound, we may be able to improve the performance\r\nwith a relatively modest increase in complexity.\r\nOn the other hand, if we have a rather complicated communication system\r\noperating near its fundamental limit, any performance improvement may\r\nbe possible only with an extremely complicated system.\r\n\r\n\\subsection{And Yet More of the Same}\r\n\r\n\\noindent In this chapter we are concerned with the rather general block diagram\r\nshown in Figure~\\ref{ch01.fig11.1.1}. Most of the early work by\r\nShannon and others ignored the source  encoder/decoder blocks and\r\nconcentrated  on bounding the performance of the channel\r\nencoder/decoder pair. Subsequently, the source  encoder/decoder blocks\r\nhave attracted much research attention.  In this chapter we consider\r\nboth topics and expose the reader to the nomenclature used in the\r\ninformation theory literature.\r\nQuantitative definitions of information are presented in\r\nSec.~\\ref{ch01.sec11.2} that lay the foundation for the remaining\r\nsections. In Secs.~\\ref{ch01.sec11.2} and~\\ref{ch01.sec11.2} we present\r\nthe fundamental source and channel coding theorems, give some examples,\r\nand state the implications of these theorems.\r\nSection~\\ref{ch01.sec11.2} contains a brief development of rate\r\ndistortion theory,\r\nwhich is the mathematical basis for data compression.\r\nA few applications of the theory in this chapter are presented\r\nin Sec.~\\ref{ch01.sec11.2}, and a technique for variable-length\r\nsource coding is given in Sec.~\\ref{ch01.sec11.2}.\r\n\\begin{itemize}\r\n\\item This is a bullet list with a short item.\r\n\\item And another item that is much longer so that we can make sure it is\r\nformatted correctly and so forth and so on.\r\n\\item And a final short item.\r\n\\end{itemize}\r\n\r\n\\begin{figure}\r\n\\includegraphics[width=24pc]{sample-figure}\r\n\\caption{This is a caption for this figure. It is fairly long so we can make\r\nsure it looks good when occupying more than one line. Here is one more\r\nsentence to make it longer.}\r\n\\label{ch01.fig11.1.1}\r\n\\label{fig:query-specification}\r\n\\end{figure}\r\n\r\nIn this chapter we are concerned with the rather general block diagram\r\nshown in Figure~\\ref{ch01.fig11.1.1}. Most of the early work by\r\nShannon and others ignored the source  encoder/decoder blocks and\r\nconcentrated  on bounding the performance of the channel\r\nencoder/decoder pair. Subsequently, the source  encoder/decoder blocks\r\nhave attracted much research attention.  In this chapter we consider\r\nboth topics and expose the reader to the nomenclature used in the\r\ninformation theory literature.\r\n\\begin{align}\r\na& = b + c\\\\\r\nx&= \\frac{1}{2} a\r\n\\end{align}\r\nQuantitative definitions of information are presented in\r\nSec.~\\ref{ch01.sec11.2} that lay the foundation for the remaining\r\nsections. In Secs.~\\ref{ch01.sec11.2} and~\\ref{ch01.sec11.2} we present\r\nthe fundamental source and channel coding theorems, give some examples,\r\nand state the implications of these theorems.\r\nSection~\\ref{ch01.sec11.1} contains a brief development of rate\r\ndistortion theory,\r\nwhich is the mathematical basis for data compression.\r\nA few applications of the theory in this chapter are presented\r\nin Sec.~\\ref{ch01.sec11.2}, and a technique for variable-length\r\nsource coding is given in Sec.~\\ref{ch01.sec11.2}.\r\n\r\nOnly the binary Huffman procedure has been described here,\r\nbut nonbinary codes can be designed using the Huffman method.\r\nThe details are somewhat more complicated and nonbinary codes\r\nare less commonly encountered than binary ones,\r\nso further discussion is left to the problems and the literature.\r\n\r\n\\section{Case Study}\r\n\\label{sec:case-study}\r\n\r\nIn this section, we exemplify how the 5S extensions for content-based image retrieval can be explored to define an image search service in the context of the CTRnet project.\r\nThe Crisis, Tragedy, and Recovery Network (CTRnet)~\\cite{Balzer2007} objectives include to develop better\r\napproaches toward making technology useful for archiving information about such events, and to support\r\nanalysis of rescue, relief, and recovery, from a digital library  perspective. CTRnet has\r\nseveral modules, including crawling, filtering, a Facebook application, visualization, metadata\r\nsearch, and Content-Based Image Retrieval (CBIR).\r\n\r\nThe CBIR module\r\nbuilds upon the EVA tool for evaluating image descriptors for content-based image retrieval \\cite{Bierman2005}. Eva integrates the most common stages of an image retrieval process and provides functionalities to facilitate the comparison of image descriptors in the context of content-based image retrieval.\r\n\r\nIn this case study, we consider the scenario in which a user is interested in finding images in the CTRnet collection that are similar to a particular photo provided as example. The objective is to identify images that could be used in a report on damages caused by an earthquake.\r\nIn this example, the query specification $q$ would be a tuple $q = (H_q, Contents_q, P_q)$, where $q$ is an image (see Figure~\\ref{fig:query-specification})\r\n Thus, $q =\r\n((V_q, E_q), L_q, F_q), Contents_q, P_q)$, where $V_q = {v_1}$; $E_q =\\emptyset$; $L_q={' Cathedral\\_P\\_A\\_P.jpg'}$; $F_q: V_q\\cup E_q\r\n\\rightarrow L_q$, $Contents_q$ is the stream of the query image; and $P_q: V_q\r\n\\rightarrow Contents_q$.\r\n\r\n\\begin{table}\r\n\\caption{This is a little table here.}\r\n\\label{tab:coordinates}\r\n\\begin{tabular}{ccccc}\r\n\\hline\r\nFoo& Bar& Zoo& Snork& Quux\\\\\r\n\\hline\r\n 0 & 0 & 1 & 2 & 4\\\\\r\n 0 & 0 & 3 & 2 & 4\\\\\r\n 3 & 3 & 1 & 0 & 1\\\\\r\n 3 & 1 & 4 & 2 & 1\\\\\r\n 3 & 4 & 4 & 2 & 2\\\\\r\n\\end{tabular}\r\n\\end{table}\r\n\r\nIn this chapter we are concerned with the rather general block diagram\r\nshown in Figure~\\ref{ch01.fig11.1.1}. Most of the early work by\r\nShannon and others ignored the source  encoder/decoder blocks and\r\nconcentrated  on bounding the performance of the channel\r\nencoder/decoder pair. Subsequently, the source  encoder/decoder blocks\r\nhave attracted much research attention.  In this chapter we consider\r\nboth topics and expose the reader to the nomenclature used in the\r\ninformation theory literature.\r\n\r\n\\section{Entropy and Average Mutual Information}\r\n\\label{ch01.sec11.2}\r\n\r\nConsider a discrete random variable $U$ that takes on\r\nthe values $\\{u_1, u_2, \\dots, u_M\\}$, where the set of possible\r\nvalues of $U$ is often called the \\textit{alphabet} and the elements\r\nof the set are called \\textit{letters} of the alphabet. Let $P_U(u)$\r\ndenote the probability  assignment  over the alphabet, then we can\r\ndefine the \\textit{self-information} of the event $ u = u_j $ by\r\n\\begin{equation}\r\n  I_U \\left( u_j \\right) = \\log \\frac{1}{P_U (u_j)} = - \\log P_U\r\n    \\left( u_j \\right)~.\r\n\\label{ch01.eq11.2.1}\r\n\\end{equation}\r\nThe quantity $I_U (u_j) $ is a measure  of the information  contained\r\nin the event $ u = u_j$. Note that the base of the logarithm in\r\nEq.~\\eqref{ch01.eq11.2.1} is unspecified. It is common\r\nto use base $e$, in which case $I_U (\\cdot) $ is in natural units (nats),\r\nor base 2,  in which case $I_U(\\cdot)$ is in binary units (bits).\r\nEither base is acceptable since the difference in the two bases is just a\r\nscaling operation. We will use base 2 in all of our work,\r\nand hence $I_U(\\cdot)$ and related quantities will be in bits.\r\nThe average or expected value of the self-information is called the\r\n\\textit{entropy,} also discrete entropy or absolute entropy, and is given by\r\n\\begin{equation}\r\n \\displaystyle H(U) = - \\sum^M_{j=1} P_U \\left(u_j\\right)\r\n    \\log P_U \\left(u_j \\right)~.\r\n\\label{ch01.eq11.2.2}\r\n\\end{equation}\r\nThe following example illustrates the calculation of entropy and how it is\r\naffected by probability assignments.\r\n\r\n\\section{Exercises and Projects}\r\n\\label{cbir:exercises}\r\n\r\n\\begin{enumerate}\r\n\\item\r\nHow might CBIR be applied so teachers with a computer and connected camera can be reminded of the names of students in their class?\r\n\r\n\\item Consider the two colourful images (Image A and Image B) showed below, represented in the RGB color space. Suppose that the intensity values of each pixel in all bands (R, G, and B) are the same. Furthermore, each $(R,G,B)$ triplet is represented by a single intensity value. For example the triplet $(R,G,B)= (2,2,2)$ is represented by the intensity value $2$.\r\n\r\nSuppose also that the colour space was quantized in five colors with intensity values 0, 1, 2, 3, and 4.\r\n\r\n\\item Compute the $L_1$ between the {\\em Color Histograms} (5\r\n  bins) of the two images. The $L_1$ distance between two color histograms $H_A$ and $H_B$ is computed as follows: $L_1(H_A, H_B) = \\sum_{i=1}^{K}|H_A[i]- H_B[i]|$, where $K$ is the size of both histograms (5, in the case).\r\n\r\n\r\n\\item By considering both the feature vector extraction function and the distance function defined of the descriptor {\\em Color Coherence Vector -- CCV}~\\cite{Burns2006}, compute the distance\r\n  $\\delta_{CCV}(A,B)$ between the two images.\r\n\r\n\\item Consider the existence of two classes ({\\em class 1} and {\\em\r\nclass 2}) composed of five images each. Consider the existence of three different descriptors ({\\em descriptor 1}, {\\em descriptor 2}, and {\\em descriptor 3}), whose feature vector extraction functions extract vectors belonging to the $R^2$ space.\r\nTable~\\ref{tab:coordinates} shows the coordinate of each image of each class, considering the three descriptors.\r\n\\end{enumerate}\r\n", "meta": {"hexsha": "b876df4d7456a744a9bcf24fc70a93f92e8df0fe", "size": 14042, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "official/acmbook/chap01.tex", "max_stars_repo_name": "gmarciani/templatex", "max_stars_repo_head_hexsha": "f226a7aaab7d6bd1b8752345c1a9a525af5501af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2016-10-06T08:09:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T05:15:26.000Z", "max_issues_repo_path": "official/acmbook/chap01.tex", "max_issues_repo_name": "gmarciani/templatex", "max_issues_repo_head_hexsha": "f226a7aaab7d6bd1b8752345c1a9a525af5501af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "official/acmbook/chap01.tex", "max_forks_repo_name": "gmarciani/templatex", "max_forks_repo_head_hexsha": "f226a7aaab7d6bd1b8752345c1a9a525af5501af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-09T13:19:17.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-09T13:19:17.000Z", "avg_line_length": 55.0666666667, "max_line_length": 367, "alphanum_fraction": 0.7715425153, "num_tokens": 3382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.3247718349255965}}
{"text": "\\chapter{Illumination optics}\\label{chap:Illumination optics}\nThis chapter provides some concepts of illumination optics used in this thesis. We start explaining the difference between radiometry and photometry.\nIn particular, we focus on the photometric variables, defining them both in three and two dimensions. The reflection and refraction laws and the phenomenon of total internal reflection are explained next. The last paragraph of the chapter gives a brief introduction to Fresnel reflection. \n\\section{Radiometric and photometric variables}\\label{sec:photometry}\nRadiometry concerns with the measurement of electromagnetic radiation across the entire electromagnetic spectrum. Photometry is the sub-field of radiometry that takes into account only part of the electromagnetic spectrum corresponding to the visible light \\cite{zalewski1995radiometry}. Radiometry deals with radiometric quantities. An important radiometric quantity  is the radiant flux $\\Phi_{\\textrm{r}}$ (unit watt \\textrm{W}) which is the total energy emitted from a source or received by a target per unit time:\n\\begin{equation}\n\\Phi_{\\textrm{r}} = \\frac{\\textrm{d}Q}{\\textrm{d}\\mytime}\\,,\n\\end{equation}\nwhere $Q$ is the energy and $\\mytime$ the time.\\\\\n\\indent In illumination optics the measurement of light is given in terms of the impression that it gives on the human eye. Therefore, illumination optics deals with photometric variables rather than with radiometric variables. The most important photometric variables are defined in the following using the notation adopted by Chaves in \\cite{chaves2015introduction}. The luminous flux $\\Phi$ (unit lumen, \\textrm{lm}) is defined as the \\textit{perceived} power of light by the human eye.\n The radiant and the luminous flux are related by the luminous efficacy function $y$ (unit \\textrm{lm}/\\textrm{W}) which defines how many lumen correspond to one Watt of power at a given wavelength.\n The luminous efficacy function reaches its maximum  at a wavelength of $555$ $\\textrm{nm}$ where it is equal to $683$ $\\textrm{lm}/\\textrm{W}$.\n  We may normalize the luminous efficacy function with its maximum value of $683$.\n  The normalized function $\\bar{y}(\\lambda)$ is the luminosity function shown in Figure $\\ref{fig:luminosityfunction}$ where $\\lambda$ is the wavelength. It is a \\textit{dimensionless} quantity with a range between $0$ and $1$ \\cite{schubert2005light}.\n\\begin{figure}[t]\n%\\label{fig:luminousfunction}  \n  \\begin{center}\n  \\includegraphics[width=7cm]{CIELuminosity}\n  \\end{center}\n  \\caption{\\textbf{Luminosity function $\\bar{y}(\\lambda)$}. Relation between the eye's sensitivity and the wavelength of light. The luminosity function is dimensionless  \\cite{wiki}.}\n  \\label{fig:luminosityfunction}\n  \\end{figure}\n\\\\ \\indent The luminous flux corresponding to one Watt of radiation power at any wavelength is given by the product of $683$ $\\textrm{lm/W}$ and the luminosity function at the same wavelength,\ni.e., $683 \\, \\bar{y}(\\lambda)$. Hence, the total luminous flux $\\Phi$ is defined as:\n\\begin{equation}\\label{eq:luminous_flux}\n\\Phi = 683 \\int_0^\\infty \\Psi_\\textrm{r}(\\lambda) \\bar{y}(\\lambda)\\textrm{d}\\lambda,\n\\end{equation}\nwhere $\\Psi_\\textrm{r}(\\lambda)$ is the spectral radiant flux, i.e., the power (in Watt) per unit wavelength (unit \\textrm{W}/\\textrm{m}). The corresponding photometric variable is the spectral luminous flux $\\Psi(\\lambda)$ (unit \\textrm{lm}/\\textrm{m}), i.e., the flux as perceived by the human eye as a function of the wavelength. \nUsing the following relation between $\\Psi_\\textrm{r}$ and $\\Psi$:\n\\begin{equation}\n683 \\bar{y}(\\lambda) = \\frac{\\Psi(\\lambda)}{\\Psi_\\textrm{r}(\\lambda)}, \n\\end{equation}\n(\\ref{eq:luminous_flux}) can be written as:\n\\begin{equation}\n\\Phi = \\int_0^\\infty \\Psi(\\lambda)\\textrm{d}\\lambda.\n\\end{equation}\n%% Explain while integrals between 0 and infinity\n%The luminous emittance $M = M(\\vect{x}, \\myangle)$ is the total flux emitted in all direction from a unit area. It is measured in lumens pr square meters (\\textrm{lm}/$\\textrm{m}^2$).\n\\\\ \\indent Geometric optics describes a beam of light as a collection of parallel light rays, where a light ray can be interpreted as a line or curve along which the electromagnetic energy travels. A ray is always direct perpendicular to the light's wavefront.  \nThe infinitesimal luminous flux $\\textrm{d}\\Phi$ incident on an infinitesimal surface $\\textrm{d}A$ is called illuminance $E$ (unit $\\textrm{lm}/\\textrm{m}^2$)\nand is defined as:\n\\begin{equation}\n E=E(\\vect{x}) = \\frac{\\textrm{d}\\Phi}{\\textrm{d}A}\\;.\n \\end{equation}\nThe corresponding radiometric variable is called \\textit{irradiance}, we indicate it with $P$. The density of light emitted by a point source in a given direction depends on the solid angle.\\\\ \\indent\nThe solid angle in a given direction is expressed by a cone of rays emitted in that particular direction by a point source located at the center of the unit sphere \\cite{koshel2012illumination}. Let us now consider a finite source $\\textrm{d}A$ and let $\\textrm{d}S$ be the area on the unit sphere subtended by the cone,\nthe infinitesimal solid angle $\\textrm{d}\\Omega$ is given by:\n\\begin{equation}\\label{solid_angle}\n\\textrm{d}\\Omega = \\textrm{d}S= \\sin(\\theta)\\textrm{d}\\theta \\textrm{d}\\varphi,\n\\end{equation}\n where $\\myangle$ and $\\varphi$ are the polar and the azimuthal angle, respectively, which the normal $\\boldsymbol{\\nu}$ to the infinitesimal area $\\textrm{d}A$ makes with the direction of the central line of $\\textrm{d}\\Omega$ (see Figure \\ref{fig:rad}).\nThe solid angle on the entire unit sphere is $\\Omega = 4\\pi$ and its unit is steradian ($\\textrm{sr}$) \\cite{arecchi2007field}.\nThe luminous intensity $I$ (unit candela, $\\textrm{cd}=\\textrm{lm}/\\textrm{sr}$) is defined as the luminous flux $\\textrm{d}\\Phi$ per solid angle\n$\\textrm{d}\\Omega$ and is given by:\n\\begin{equation}\\label{intensity}\nI = I(\\myangle, \\varphi) = \\frac{\\textrm{d}\\Phi}{\\textrm{d}\\Omega}\\;.\n\\end{equation}\n \\begin{figure}[t]\n%\\label{fig:cup}\n  \\begin{center}\n  \\includegraphics[width=6 cm]{SolidAngle}\n  \\end{center}\n  \\caption{\\textbf{Solid angle}. $\\textrm{d}\\Omega$ is in a given direction $\\myangle$ and $\\varphi$.}\n  \\label{fig:rad}\n  \\end{figure}\n\\\\ \\indent \nThe luminance $L = L(\\vect{x}, \\myangle, \\varphi)$ (unit $\\textrm{cd} / \\textrm{m}^2$) depends both on the position and the direction, it is the luminous flux per unit solid angle $\\textrm{d}\\Omega$ and  per unit projected area $\\cos\\myangle \\textrm{d}A$.  $L$  is given by:\n\\begin{equation}\\label{luminance1}\n  L=L(\\vect{x}, \\myangle, \\varphi) = \\frac{\\textrm{d}\\Phi}{\\cos\\myangle\\textrm{d}A\\textrm{d}\\Omega}\\,.\n\\end{equation}\n\\noindent Note that from ($\\ref{intensity}$) and ($\\ref{luminance1}$) we can derive a relation between the intensity and the luminance. \nThe intensity $I$ emitted by the infinitesimal area $\\textrm{d}A$ is given by:\n\\begin{equation}\\label{eq:int_lum}\nI = \\frac{\\textrm{d}\\Phi}{\\textrm{d}\\Omega}= L(\\vect{x},\\myangle, \\varphi)\\cos\\myangle\\textrm{d}A \\,.\n\\end{equation}\nWhen the luminance is uniform over a finite area $A$, the luminous intensity emitted in the direction $\\myangle$ and $\\varphi$ is:\n\\begin{equation}\nI(\\myangle, \\varphi) = L(\\myangle, \\varphi) A \\cos\\myangle\\,.\n\\end{equation}\nFurther, when $L(\\vect{x},\\myangle, \\varphi)$ does not depend on the position and the direction (i.e. $L(\\vect{x},\\myangle, \\varphi)=L$), we obtain Lambert's cosine law:\n\\begin{equation}\nI(\\myangle) = I_0\\cos\\myangle ,\n\\end{equation}\nwhere $I_0 = I(\\myangle = 0) = LA$. Light sources emitting light with a constant luminance are called \\textit{Lambertian} sources.\\\\\n\\indent Finally, we give a definition of the \\'{e}tendue $U$ (unit $\\textrm{m}^2\\textrm{sr}$).\n\\'{E}tendue is a french word that means extent or spread. In geometric optics, it is a quantity to describe how light is spread out in terms of area and solid angle \\cite{lerner2006etendue, zhu2011etendue}.\nThe quantity $ \\textrm{d}U $ of a source $\\textrm{d}A$ is defined as:\n\\begin{equation}\\label{etendue}\n\\textrm{d}U = n^2  \\frac{1}{L}\\textrm{d}\\Phi = n^2 \\cos\\myangle\\textrm{d}A\\textrm{d}\\Omega,\n\\end{equation}\nwhere $n$ is the index of refraction of the medium in which $\\textrm{d}A$ is immersed. In phase space optics the \\'{e}tendue is considered to be a volume in phase space (or an area for two-dimensional systems). This concept will be clarified in Chapter \\ref{chap:PS} in which we treat the phase space in more detail.\nAn important property is conservation of \\'{e}tendue within an optical system in the absence of absorption. \nIn the following we show, using the approach of Chaves in \\cite{chaves2015introduction}, \nhow conservation of \\'{e}tendue in a lossless system can be derived. \n%For the optical systems we will consider in this work, the source and the target are located in the same medium (air) with $n=1$, so the luminance $L$ equals the basic luminance $L^* = L/n^2$ at the source and the target of the system. \nConsider a light ray emitted from an infinitesimal area $\\textrm{d}A_1$ to the area $\\textrm{d}A_2$. Suppose that the centers of $\\textrm{d}A_1$ and $\\textrm{d}A_2$ \nare located at a distance \\variabile{d} from each other and that both the surfaces are located in the same medium, see Figure \\ref{fig:etendue_conservation}.\n\\begin{figure}[t]\n \\label{fig:etendue_conservation}\n     \\begin{center}\n     \\includegraphics[width=10cm]{areas.pdf}\n     \\end{center}\n     \\caption{\\textbf{Transfer of flux from the source $\\textrm{d}A_1$ to the target $\\textrm{d}A_2$.} $\\textrm{d}A_1$ and $\\textrm{d}A_2$ are two surfaces with normals $\\nu_1$ and $\\nu_2$, respectively. Their centers are located at a distance \\variabile{d}.\n$\\myangle_1$ and $\\myangle_2$ are the angles made by the central ray with the normals $\\nu_1$ and $\\nu_2$, respectively.}\n\\label{fig:etendue_conservation}\n \\end{figure}\nWe derive \\'{e}tendue conservation for the case in which $\\textrm{d}A_1$ and $\\textrm{d}A_2$ are located in the same medium (see \\cite{chaves2015introduction, koshel2012illumination} for the general case).\nWe indicate with $\\boldsymbol{\\nu}_1$ and $\\boldsymbol{\\nu}_2$ the normals on the surfaces $\\textrm{d}A_1$ and $\\textrm{d}A_2$, and with $\\myangle_1$ and $\\myangle_2$ the angles that the ray connecting the centers of $\\textrm{d}A_1$ and $\\textrm{d}A_2$ forms with $\\boldsymbol{\\nu}_1$ and $\\boldsymbol{\\nu}_2$. The infinitesimal solid angle $\\textrm{d}\\Omega_1$ subtended by $\\textrm{d}A_2$ at the center of $\\textrm{d}A_1$ and the flux $\\textrm{d}\\Phi_1$ passing through $\\textrm{d}A_2$ emitted from $\\textrm{d}A_1$ are defined as:\n\\begin{subequations}\n\\begin{align}\n\\label{eq:omega1}\n\\textrm{d}\\Omega_1 &= \\frac{\\textrm{d}A_2\\cos(\\myangle_2)}{\\variabile{d}^2}\\,,\\\\\n\\textrm{d}\\Phi_1 &= L_1 \\cos\\myangle_1 \\textrm{d}A_1 \\textrm{d}\\Omega_1. \\label{eq:phi1}\n\\end{align}\n\\end{subequations}\nSimilarly, the infinitesimal solid angle $\\textrm{d}\\Omega_2$ subtended by $\\textrm{d}A_1$ at the center of $\\textrm{d}A_2$ and the flux $\\textrm{d}\\Phi_2$ passing through $\\textrm{d}A_1$ emitted from $\\textrm{d}A_2$ are equal to:\n\\begin{subequations}\\begin{align}\\label{eq:omega2}\n\\textrm{d}\\Omega_2 &= \\frac{\\textrm{d}A_1\\cos\\myangle_1}{\\variabile{d}^2}\\,,\\\\\n\\textrm{d}\\Phi_2 &= L_2 \\cos\\myangle_2 \\textrm{d}A_2 \\textrm{d}\\Omega_2.\\label{eq:phi2}\n\\end{align}\n\\end{subequations}\nThen from (\\ref{etendue}) we obtain the following relations: \n\\begin{subequations}\n\\begin{align}\n\\textrm{d}U_1 &= n^2\\cos\\myangle_1 \\textrm{d}A_1\\textrm{d}\\Omega_1= \\frac{n^2\\cos\\myangle_1 \\textrm{d}A_1\\textrm{d}A_2\\cos\\myangle_2}{\\variabile{d}^2},\\\\\n\\textrm{d}U_2 &= n^2 \\cos\\myangle_2\\textrm{d}A_2\\textrm{d}\\Omega_2= \\frac{ n^2 \\cos\\myangle_2\\textrm{d}A_2\\textrm{d}A_1\\cos\\myangle_1}{\\variabile{d}^2}, \\label{eq:dU2}\n%\\end{split}\n\\end{align}\n\\end{subequations}\nfor $\\textrm{d}A_1$ and $\\textrm{d}A_2$, respectively.\n%From equation ($\\ref{etendue1}$) and ($\\ref{etendue2}$) \nFrom the previous equations we can conclude that $\\textrm{d}U_1=\\textrm{d}U_2$ and therefore the \\'{e}tendue is conserved along a beam of light. \nSince the system is a lossless system, energy is conserved from the source to the target ($\\textrm{d}\\Phi_1= \\textrm{d}\\Phi_2$), therefore the \\'{e}tendue conservation implies:\n\\begin{equation}\\label{basicluminance}\nL_1 = n^2 \\frac{\\textrm{d}\\Phi_1}{\\textrm{d}U_1} = n^2 \\frac{\\textrm{d}\\Phi_2}{\\textrm{d}U_2} = L_2\\,,\n\\end{equation}\nwhere the first equality comes from (\\ref{luminance1}) combined with (\\ref{etendue}).\n\\\\ \\indent In this thesis we consider two-dimensional optical systems. \n Hence, the definitions of the photometric parameters have to be adapted to two-dimensions. An infinitesimal line segment of length $\\textrm{d}\\variabile{a}$ emitting a ray that makes an angle $\\myangle$ with the normal $\\boldsymbol{\\nu}$ are considered, see Figure \\ref{fig:2Dsolidangle}. \n\\begin{figure}[t]\n \\label{fig:2Dsolidangle}\n     \\begin{center}\n     \\includegraphics[width=7cm]{solidangle2D.pdf}\n     \\end{center}\n     \\caption{\\textbf{Ray emitted by an infinitesimal line segment.} $\\textrm{d}a$ makes an angle $\\myangle$ with respect to the line normal $\\boldsymbol{\\nu}$.}\n\\label{fig:2Dsolidangle}\n \\end{figure}\nThe two-dimensional illuminance (unit $\\textrm{lm}/\\textrm{m}$) denotes the luminous flux received by an infinitesimal line segment of length $\\textrm{d}\\variabile{a}$ \nand it is given by:\n \\begin{equation}\n E=\\frac{\\textrm{d}\\Phi}{\\textrm{d}\\variabile{a}}\\;.\n \\end{equation}\n%The luminous emittance $M = M(\\variabile{x}, \\myangle)$ is the total flux emitted in all direction from a line segment.\nThe luminous intensity \\big(unit $\\big[\\textrm{lm}/\\textrm{rad}\\big]$\\big) is the luminous flux per angle $\\textrm{d}\\myangle$:\n \\begin{equation}\n I=\\frac{\\textrm{d}\\Phi}{\\textrm{d}\\myangle}\\;.\n \\end{equation}\n The two-dimensional luminance (unit $\\textrm{lm}/(\\textrm{rad}\\,\\textrm{m})$) is given by:\n \\begin{equation}\n L= \\frac{\\textrm {d}\\Phi}{\\cos\\myangle\\,\\textrm{d}\\variabile{a} \\,\\textrm{d}\\myangle}.\n \\end{equation}\n Thus the following relation holds:\n \\begin{equation}\n I = L(x, \\myangle)\\cos\\myangle\\,\\textrm{d}\\variabile{a},\n \\end{equation}\nwhere $x$ is a certain position at the light source $\\textrm{d}\\variabile{a}$. \n Finally, the \\'{e}tendue $\\textrm{d}U $ (unit $\\textrm{m}\\;\\textrm{rad}$) in two-dimensions is given by:\n\\begin{equation}\\label{etendue2d}\n\\textrm{d}U = \\n\\cos\\myangle\\textrm{d}\\variabile{a}\\,\\textrm{d}\\myangle.\n\\end{equation}\nAn overview of the photometric variables used in this thesis is given in Table \\ref{tab:photometric_variables}\n\\begin{table}[t] \n\\centering\n\\caption{\\bf Photometric variables}\n\\begin{tabular}{lllll}\n \\hline   \\\\\nName  & Symbol & Unit ($3D$) & Unit ($2D$) \\\\\n  \\hline \nLuminous flux & $\\Phi$   & $\\textrm{lm}$   &  $\\textrm{lm}$ \\\\\n%Spectral luminous flux & $\\Phi_\\lambda$   & $$   &  $1.75\\cdot10^{-4}$ \\\\\nIlluminance/emittance  & $E$    & $\\textrm{lm}/{\\textrm{m}^2} $ & $\\textrm{lm}/{\\textrm{m}}$  \\\\\nIntensity  & $I$    & $\\textrm{lm}/{\\textrm{sr}} = \\textrm{cd}$  & $\\textrm{lm}/\\textrm{rad}$ \\\\\nLuminance  & $L$  & $ \\textrm{cd}/{\\textrm{m}^2}$   & $\\textrm{lm}/(\\textrm{rad} \\,\\textrm{m})$ \\\\\n\\'{E}tendue & $U$  & $\\textrm{m}^2\\, \\textrm{sr}$   & $\\textrm{m}\\, \\textrm{rad}$ \\\\\n \\hline\n \\end{tabular}\n\\label{tab:photometric_variables}\n \\end{table}\n\\\\ \\indent In order to determine the light distribution on a surface and to compute the photometric variables on that surface, we need to understand how the light emitted from a source propagates. In the field of geometric optics the light propagation is described by light rays.\nThe propagation of a light ray traveling through different media is determined by the reflection and refraction law.\nIn the following we introduce these two laws and we explain the total internal reflection phenomenon.\n\\section{Reflection and refraction law}\\label{sec:reflection}\nA light ray is described by a position vector \\vect{x} on a surface and a direction vector \\vect{t} and can be parametrized by the arc length \\variabile{s}.\nLight rays travel in a homogeneous medium along straight lines, once they hit a reflective surface their direction changes.\n Denoting with $\\vect{t}_\\textrm{i}$ the direction of the incident ray and with $\\boldsymbol{\\nu}$ the unit normal to the surface at the location of incidence, the direction $\\vect{t}_\\textrm{r}$ of the reflected ray is given by:\n \\begin{equation}\\label{Reflection}\n  \\vect{t}_\\textrm{r} = \\vect{t}_\\textrm{i}-2 (\\vect{t}_\\textrm{i}\\boldsymbol{\\cdot}\\boldsymbol{\\nu})\\boldsymbol{\\nu},\n\\end{equation}\nwhere the vectors $\\vect{t}_\\textrm{i}$ and $\\boldsymbol{\\nu}$ are unit vectors and $\\vect{t}_\\textrm{i}\\boldsymbol{\\cdot}\\boldsymbol{\\nu}$ indicates the scalar product of\n$\\vect{t}_\\textrm{i}$ and $\\boldsymbol{\\nu}$. \nFrom the previous equation it follows that the vector  $\\vect{t}_\\textrm{r}$ is a unit vector too, indeed considering the scalar product $\\vect{t}_\\textrm{r}\\boldsymbol{\\cdot}\\vect{t}_\\textrm{r}$ we conclude:\n\\begin{equation}\\label{unit_vector}\n\\vect{t}_\\textrm{r}\\boldsymbol{\\cdot}\\vect{t}_\\textrm{r} = \\vect{t}_\\textrm{i}\\boldsymbol{\\cdot}\\vect{t}_\\textrm{i} \n- 4(\\vect{t}_\\textrm{i}\\boldsymbol{\\cdot}\\boldsymbol{\\nu})(\\vect{t}_\\textrm{i}\\boldsymbol{\\cdot}\\boldsymbol{\\nu})+\n4(\\vect{t}_\\textrm{i}\\boldsymbol{\\cdot}\\boldsymbol{\\nu})^2(\\boldsymbol{\\nu}\\boldsymbol{\\cdot}\\boldsymbol{\\nu})=1 .\n\\end{equation} \nNote from (\\ref{Reflection}) that the vectors $\\vect{t}_\\textrm{i}$, $\\vect{t}_\\textrm{r}$ and $\\boldsymbol{\\nu}$ are coplanar.\nIndicating with $\\myangle_\\textrm{i}$ the incident angle and with $\\myangle_\\textrm{r}$ the reflective angle such that $\\myangle_\\textrm{i}$, $\\myangle_\\textrm{r} \\in[0, \\pi/2)$,\nthe reflection law states that $\\myangle_\\textrm{i}=\\myangle_\\textrm{r}$, see Figure \\ref{fig:Snell}.\n\\begin{figure}[t]\n \\label{fig:Snell}\n     \\begin{center}\n     \\includegraphics[width=8cm]{reflection}\n     \\end{center}\n     \\caption{\\textbf{Propagation of a ray.} The ray travels through two materials with index of refraction $\\n_\\textrm{i}$ and $\\n_\\textrm{t}$.}% \\bolsymbol{$\\nu$} is the normal to the surface $A$ that the incident ray hits.\n%$\\vect{t}_i$, $\\vect{t}_r$ and $\\vect{t}_t$ are the direction vectors of the incident, reflected and refracted (or transmitted) ray, respectively. }}\n%\\myangle$_{i}$, \\myangle$_{r}$ and \\myangle$_{t}$ are the angles between \\bolsymbol{$\\nu$} and the incident, reflected and transmitted ray, respectively.}}\n\\label{fig:Snell}\n \\end{figure}\n\\\\ \\indent When a ray propagates through two different media, its direction changes according to the law of refraction. \nIndicating with $n_\\textrm{i}$ the index of refraction of the medium in which the incident ray travels and with \n$n_\\textrm{t}$ the index of refraction of the medium of the transmitted ray, the direction of the transmitted ray is given by:\n\\begin{equation}\\label{Refraction}\n\\vect{t}_\\textrm{t} = n_{\\textrm{i},\\textrm{t}}\\,\\vect{t}_\\textrm{i}-\n\\Big[\\sqrt{1-n_{\\textrm{i},\\textrm{t}}^2+\nn_{\\textrm{i},\\textrm{t}}^2(\\boldsymbol{\\nu}\\boldsymbol{\\cdot}\\vect{t}_\\textrm{i})^2}\n+n_{\\textrm{i},\\textrm{t}}(\\boldsymbol{\\nu}\\boldsymbol{\\cdot}\\vect{t}_\\textrm{i}) \\Big]\\boldsymbol{\\nu}\\,,\n\\end{equation}\nwhere $n_{\\textrm{i},\\textrm{t}}=\\n_\\textrm{i}/\\n_\\textrm{t}$ \\cite{chaves2015introduction}.\nWhile the direction of the normal $\\boldsymbol{\\nu}$ to the surface is not relevant for the computation of the direction of the reflected ray, in fact:\n\\begin{equation}\n\\vect{t}_\\textrm{r} = \\vect{t}_\\textrm{i}-2(\\vect{t}_\\textrm{i}\\boldsymbol{\\cdot}\\boldsymbol{\\nu})\\boldsymbol{\\nu}= \\vect{t}_\\textrm{i}-2(\\vect{t}_\\textrm{i}\\boldsymbol{\\cdot}(-\\boldsymbol{\\nu}))(-\\boldsymbol{\\nu}), \n\\end{equation}\nfor computing the direction of the refracted ray, we need to specify the direction of $\\boldsymbol{\\nu}$ which is usually chosen so that the scalar product between the incident ray and the normal is negative $\\vect{t}_{\\textrm{i}}\\boldsymbol{\\cdot}\\boldsymbol{\\nu}<0$. \nConsidering the cross product of both the terms in Equation (\\ref{Refraction}) with the normal $\\boldsymbol{\\nu}$ of the incident surface we obtain:\n\\begin{equation}\n\\vect{t}_\\textrm{t}\\times\\boldsymbol{\\nu} = n_{\\textrm{i},\\textrm{t}}(\\vect{t}_\\textrm{i}\\times\\boldsymbol{\\nu}),\n\\end{equation}\nwhich leads to the Snell's law:\n\\begin{equation}\\label{eq:snell}\nn_\\textrm{t}\\sin(\\myangle_\\textrm{t}) = \\n_\\textrm{i}\\sin(\\myangle_\\textrm{i}).\n\\end{equation}\nNote that (\\ref{Refraction}) is only valid for \n\\begin{equation}\\label{tir}\n1-\\n_{\\textrm{i},\\textrm{t}}^2+\\n_{\\textrm{i},\\textrm{t}}^2(\\boldsymbol{\\nu}\\boldsymbol{\\cdot}\\vect{t}_\\textrm{i})^2\\geq 0,\n\\end{equation} which implies that\n\\begin{equation}\n\\frac{\\n_\\textrm{t}}{\\n_\\textrm{i}}\\geq \\sqrt{1-(\\boldsymbol{\\nu}\\boldsymbol{\\cdot}\\vect{t}_\\textrm{i})^2},\n\\end{equation}\nfrom which we obtain:\n\\begin{equation}\n %n_\\textrm{t}\\geq n_\\textrm{i}\\sqrt{1-\\cos^2\\myangle_\\textrm{i}}= \n n_\\textrm{t}\\geq \\n_\\textrm{i} \\sin\\myangle_\\textrm{i}\\,.\n\\end{equation}\n The angle $\\myangle_{\\textrm{c}}$ for which the equality holds is\n\\begin{equation}\\label{critical}\n\\myangle_{\\textrm{c}} = \\arcsin\\Big(\\frac{n_\\textrm{t}}{\\n_\\textrm{i}}\\Big),\n\\end{equation} and it is called the critical angle \\cite{chaves2015introduction}.\n%Note that the condition $\\frac{n_t}{n_i}<1$ is verified as in this case $\\sin(\\myangle_\\textrm{i})<1$.\nWhen the incident angle $\\myangle_{\\textrm{i}}$ is exactly equal to the critical angle $\\myangle_{\\textrm{c}}$, the square root in (\\ref{Refraction}) is zero and $\\vect{t}_\\textrm{t}\\boldsymbol{\\cdot}\\boldsymbol{\\nu}=0$, hence the transmitted ray propagates parallel to the refractive surface. \nWhen $\\myangle_{\\textrm{i}}>\\myangle_{\\textrm{c}}$ the light ray is no longer refracted but is only reflected by the surface. This phenomenon is called total internal reflection (TIR). When TIR occurs, $100\\%$ of the incident light is reflected and there is no refraction. Therefore, optical systems designed such that rays are reflected by TIR are very efficient. \\\\ \\indent \nIn general, light that hits an ordinary refractive surface can be both reflected and refracted. Every incident ray generates two rays when interacting with a surface. Each of them carries a fraction of the total energy of the incident ray. Obviously, the sum of the reflected and transmitted energy equals the incident power.\nThe amount of energy transported by the reflected and the refracted ray is determined by the Fresnel equations. In the next paragraph an overview of the Fresnel coefficients is given based on the theory in \\cite{hecht1998hecht} (Section $4.6$).\n\\section{Fresnel's coefficients for reflection and refraction}\\label{sec:fresnel}\nIn order to derive Fresnel's equations we need to describe light as an electromagnetic wave. \nIt is therefore useful to study light propagation from the perspective of electromagnetic theory which gives information about the incident, reflected and transmitted radiant flux density, denoted with $P_\\textrm{i}$, $P_\\textrm{r}$ and $P_\\textrm{t}$, respectively.  \nThe electric field $\\boldsymbol{\\mathcal{E}}$ can be written as: \n\\begin{equation}\n\\boldsymbol{\\mathcal{E}}(\\vect{x}, \\mytime) = \\boldsymbol{\\mathcal{E}}_0(\\vect{x} )e^{i( \\vect{k}\\boldsymbol{\\cdot}\\vect{x}-\\omega \\mytime)},\n\\end{equation}\nwhere \\vect{k} is the vector in the direction of the field propagation with modulus \n$|\\vect{k}| = k$, \\vect{x} is the position vector and $\\mytime$ is the time. The amplitude $\\boldsymbol{\\mathcal{E}}_0(\\vect{x})$ is constant in time and $\\omega = c\\,k/ \\n$ is the value of the angular frequency with $c$ the velocity of light in vacuum and $\\n$ the index of refraction in which the wave is traveling. We recall that $\\n = c/v$ with $v$ the speed of light in the material. Note that the angular frequency can be also written as $\\omega = v\\,k$ (in vacuum $\\n=1$ and $\\omega=c\\,k$). The parameter\n$k =2\\,\\pi/\\lambda$ is the wave number in vacuum, with $\\lambda$ the wavelength. \\\\ \\indent Similarly, the magnetic field has the form:\n\\begin{equation}\n\\boldsymbol{\\mathcal{B}}(\\vect{x}, \\mytime) = \\boldsymbol{\\mathcal{B}}_0(\\vect{x}) e^{i( \\vect{k}\\boldsymbol{\\cdot} \\vect{x}-\\omega \\mytime )},\n\\end{equation}\nwhere $\\boldsymbol{\\mathcal{B}}_0(\\vect{x})$ is the amplitude of the magnetic field.\nThe electric and magnetic fields satisfy the following relations:\n\\begin{subequations}\\label{eq:electric_magnetic}\n\\begin{align}\n\\frac{\\vect{k}}{k} \\boldsymbol{\\times} \\boldsymbol{\\mathcal{E}} & = v \\, \\boldsymbol{\\mathcal{B}}, \\\\\n\\frac{\\vect{k}}{k} \\boldsymbol{\\cdot}\\boldsymbol{\\mathcal{E}} &=0.\n\\end{align}\n\\end{subequations}\n% Say right hand system\n\\\\ \\indent Light can be considered as an electromagnetic wave, consisting of an electric field $\\boldsymbol{\\mathcal{E}}$ and a magnetic field $\\boldsymbol{\\mathcal{B}}$, which propagates always perpendicular to $\\boldsymbol{\\mathcal{E}}$ and $\\boldsymbol{\\mathcal{B}}$ (see Equations (\\ref{eq:electric_magnetic})). By convention, the direction of the electric field $\\boldsymbol{\\mathcal{E}}$ with respect to the incident plane defines the \\textit{polarization} of an electromagnetic wave \\cite{feynman1964feynman} (see Figure \\ref{fig:planeofincidence}). \\\\\n%The direction of $\\boldsymbol{\\mathcal{E}}$ is given by the incident and reflected rays as is shown in Figure \\ref{fig:planeofincidence}. \\\\\n\\indent Fresnel's equations were introduced to describe the effect of an incident wave when encountering an interface located between two media having different indexes of refraction. In particular, the Fresnel coefficients determine the fractions of transmitted and reflected energy.  \nIn the following we provide the Fresnel coefficients and we briefly explain their physical interpretation. \nWe refer the reader to \\cite{hecht1998hecht, feynman2011feynman, born2013principles} for more details. To derive Fresnel's equations the polarization of light must be taken into account.\n\\\\ \\indent Light is said to be \\textit{polarized} if the electric field oscillates in a single plane. Light is \\textit{unpolarized} when the direction of this electric field changes randomly in time.\n\\begin{figure}[t]\n \\label{fig:planeofincidence}\n     \\begin{center}\n     \\includegraphics[width=10cm]{plane_of_incidence1}\n     \\end{center}\n     \\caption{\\textbf{Light ray that hits a mirror located on the reflecting plane.} The incident and the reflected ray are coplanar with the normal to the mirror. The plane of incidence is spanned by the reflected and the refracted rays. The plane of interface is perpendicular to the plane of incidence.}\n\\label{fig:planeofincidence}\n \\end{figure}\nThe light polarization can be classified into three different kinds of polarization:\n\\begin{itemize}\n\\item \\textit{Linear polarization}: The electric filed is confined to a single plane perpendicular to the direction of propagation;\n\\item \\textit{Circular polarization}: The electric field describes a circle around the direction of propagation;\n\\item \\textit{Elliptic polarization}: The electric field describes an ellipse around the direction of propagation.\n\\end{itemize}\nAny form of light can be defined by two orthogonal linear polarizations.\nHence, the following two cases of light polarization are considered: \n\\begin{enumerate}\n\\item $\\boldsymbol{\\mathcal{E}}$ is perpendicular to the plane of incidence, and therefore $\\boldsymbol{\\mathcal{B}}$ is parallel to it (see Figure \\ref{fig:electric_field}). In this case light is said to be \\textit{s-polarized} (from the German word \\textit{senkrecht}).\n\\item $\\boldsymbol{\\mathcal{E}}$ is parallel to the plane of incidence and, therefore $\\boldsymbol{\\mathcal{B}}$ is perpendicular to it (see Figure \\ref{fig:electric_field_p}). In this case light is said to be \\textit{p-polarized} (from the German word \\textit{parallel}).\n\\end{enumerate}\n\\begin{figure}[t]\n \\label{fig:electric_field}\n     \\begin{center}\n     \\includegraphics[width=8cm]{electric_field}\n     \\end{center}\n     \\caption{\\textbf{Propagation of an electromagnetic wave for s-polarized light.} The components of $\\boldsymbol{\\mathcal{E}}$ are indicated with the green circles.\nThe components of $\\boldsymbol{\\mathcal{B}}$ are indicated with red arrows.}\n\\label{fig:electric_field}\n \\end{figure}\n\\begin{figure}[t]\n \\label{fig:electric_field_p}\n     \\begin{center}\n     \\includegraphics[width=8cm]{electric_field_p}\n     \\end{center}\n \\caption{\\textbf{Propagation of an electromagnetic wave for p-polarized light.} The components of $\\boldsymbol{\\mathcal{B}}$ are indicated with the red circle.\n%, they are in the $(\\variabile{x},\\variabile{z})$ plane and they are oriented in the positive direction of $\\variabile{z}$. \nThe components of $\\boldsymbol{\\mathcal{E}}$ are indicated with green arrows.}\n%and they are located in the $(\\variabile{x}, \\variabile{z})$ plane.}\n\\label{fig:electric_field_p}\n \\end{figure}\nThe amplitude Fresnel coefficient $r$ is defined by the ratio between the amplitudes of the reflected and the incident electric field. Similarly, $t$ is the ratio between the amplitudes of the transmitted and the incident electric field. They are defined by:\n\\begin{equation}\n\\begin{split}\nr & =\\frac{|\\boldsymbol{\\mathcal{E}}_{0 \\textrm{r}}|}{|\\boldsymbol{\\mathcal{E}}_{0\\textrm{i}}|}, \\\\\nt & =\\frac{|\\boldsymbol{\\mathcal{E}}_{0 \\textrm{t}}|}{|\\boldsymbol{\\mathcal{E}}_{0\\textrm{i}}|}.\n\\end{split}\n\\end{equation}\nThe Fresnel equations provide the perpendicular $r_\\textrm{s}$ and $t_\\textrm{s}$ and parallel $r_\\textrm{p}$ and $t_\\textrm{p}$ versions of $r$ and $t$, respectively.\nEnergy conservation gives the boundary conditions of the electromagnetic field at the plane of the interface (perpendicular to the incident plane), from which the Fresnel coefficients are derived. They are defined in both case $1$ and case $2$. Since the mathematical formulation is similar for the two cases, in the following we explain in detail the computation of the Fresnel coefficients only for s-polarized light (case $1$).\\\\ \n\\indent For s-polarized light, the component tangential to the interface of $\\boldsymbol{\\mathcal{E}}$ and $\\boldsymbol{\\mathcal{B}}/\\mu$ are continuous across the boundary between the two different media, where $\\mu$ is the permeability of the material in which the electromagnetic field is located. From now on, all quantities defined in the medium of the incident, reflective and transmitted light are indicated with the subscripts \\textrm{i}, \\textrm{r} and \\textrm{t}, respectively. The continuity of the tangential component of $\\boldsymbol{\\mathcal{E}}$ leads to:\n\\begin{equation}\\label{Econservation}\n|\\boldsymbol{\\mathcal{E}}_{0\\textrm{i}}|+|\\boldsymbol{\\mathcal{E}}_{0\\textrm{r}}|= |\\boldsymbol{\\mathcal{E}}_{0\\textrm{t}}|,\n\\end{equation} \n%where we have indicated with $\\mathcal{E}_{0\\textrm{i}}$, $\\mathcal{E}_{0\\textrm{r}}$ and $\\mathcal{E}_{0\\textrm{t}}$\n%the magnitudes of $\\boldsymbol{\\mathcal{E}}_{0\\textrm{i}}$, $\\boldsymbol{\\mathcal{E}}_{0\\textrm{r}}$ and $\\boldsymbol{\\mathcal{E}}_{0\\textrm{t}}$, respectively.\nwhile the continuity of the tangential component of $\\boldsymbol{\\mathcal{B}}/\\mu$ gives:\n\\begin{equation}\\label{Bconservation}\n-\\frac{|\\boldsymbol{\\mathcal{B}}_{0\\textrm{i}}|}{\\mu_\\textrm{i}}\\cos\\myangle_{\\textrm{i}}+\\frac{|\\boldsymbol{\\mathcal{B}}_{0\\textrm{r}}|}{\\mu_\\textrm{r}}\\cos\\myangle_{\\textrm{r}} = \n-\\frac{|\\boldsymbol{\\mathcal{B}}_{0\\textrm{t}}|}{\\mu_\\textrm{t}}\\cos\\myangle_{\\textrm{t}},\n\\end{equation}\nwhere the sign convention is chosen as illustrated in Figure \\ref{fig:electric_field}.\n%where we have indicated with $\\mathcal{B}_{\\textrm{i}}$, $\\mathcal{B}_{\\textrm{r}}$ and $\\mathcal{B}_{\\textrm{t}}$\n%the absolute values of $\\boldsymbol{\\mathcal{B}}_{\\textrm{i}}$,$\\boldsymbol{\\mathcal{B}}_{\\textrm{r}}$ and $\\boldsymbol{\\mathcal{B}}_{\\textrm{t}}$, respectively.\nSince $|\\boldsymbol{\\mathcal{B}}| = |\\boldsymbol{\\mathcal{E}}|/v$, (\\ref{Bconservation}) can be written as \n\\begin{equation}\n\\frac{1}{\\mu_{\\textrm{i}}v_{\\textrm{i}}}(|\\boldsymbol{\\mathcal{E}}_{0\\textrm{i}}|-|\\boldsymbol{\\mathcal{E}}_{0\\textrm{r}}|)\\cos\\myangle_{\\textrm{i}} = \\frac{1}{\\mu_{\\textrm{t}}v_{\\textrm{t}}}|\\boldsymbol{\\mathcal{E}}_{0\\textrm{t}}|\\cos\\myangle_{\\textrm{t}},\n\\end{equation}\nwhere we employed the fact that $v_{\\textrm{i}}= v_{\\textrm{r}}$, and $\\myangle_{\\textrm{i}}= \\myangle_{\\textrm{r}}$. \nSince $n = c/v$, the previous equation becomes:\n\\begin{equation}\n\\frac{n_{\\textrm{i}}}{\\mu_{\\textrm{i}}}(|\\boldsymbol{\\mathcal{E}}_{0\\textrm{i}}|-|\\boldsymbol{\\mathcal{E}}_{0\\textrm{r}}|)\\cos\\myangle_{\\textrm{i}} = \\frac{n_{\\textrm{t}}}{\\mu_{\\textrm{i}}}|\\boldsymbol{\\mathcal{E}}_{0\\textrm{t}}|\\cos\\myangle_{\\textrm{t}}.\n\\end{equation}\nMost often used optical materials are non-magnetic, hence we assume $\\mu_{\\textrm{i}}=\\mu_{\\textrm{t}}=\\mu_{0}$ \\cite{lvovsky2013fresnel}. Employing (\\ref{Econservation}) we arriving at the Fresnel coefficients for s-polarized light:\n\\begin{equation} \\label{Fresnel_perpendicular}\n\\begin{split}\nr_{\\textrm{s}} & =\\frac{|\\boldsymbol{\\mathcal{E}}_{0 \\textrm{r}}|_{\\textrm{s}}}{|\\boldsymbol{\\mathcal{E}}_{0\\textrm{i}}|_\\textrm{s}} = \n\\frac{n_\\textrm{i}\\cos\\myangle_\\textrm{i}-n_\\textrm{t} \\cos\\myangle_\\textrm{t}}{n_\\textrm{i}\n\\cos\\myangle_\\textrm{i}+n_\\textrm{t}\\cos\\myangle_\\textrm{t}},\\\\\nt_{\\textrm{s}} & = \\frac{|\\boldsymbol{\\mathcal{E}}_{0 \\textrm{t}}|_\\textrm{s}}{|\\boldsymbol{\\mathcal{E}}_{0\\textrm{i}}|_\\textrm{s}} \n=\\frac{2\\n_\\textrm{i}\\cos\\myangle_\\textrm{i}}{n_\\textrm{i}\\cos\\myangle_\\textrm{i}+\\n_\\textrm{t}\\cos\\myangle_\\textrm{t}},\\\\\n\\end{split}\n\\end{equation}\nwhere the subscript $\\textrm{s}$ is used to remind the reader that we are considering s-polarized light. \nUsing Snell's law (Equation (\\ref{eq:snell})) the first pair of the Fresnel equations restricted to the case $\\myangle_\\textrm{i}\\leq\\myangle_\\textrm{c}$ becomes:\n\\begin{equation}\n\\fbox{\\begin{minipage}{18em}\n\\begin{equation*} \\label{simple_Fresnel}\n\\begin{split}\nr_{\\textrm{s}} & = -\\frac{\\sin(\\myangle_\\textrm{i}-\\myangle_\\textrm{t})}{\\sin(\\myangle_\\textrm{i}+\\myangle_\\textrm{t})}\\\\\nt_{\\textrm{s}} & = \\frac{2\\sin \\myangle_\\textrm{t} \\cos \\myangle_\\textrm{i}}{\\sin(\\myangle_\\textrm{i}+\\myangle_\\textrm{t})}\n\\end{split}\n\\end{equation*}\n\\end{minipage}}\n\\end{equation}\n\nA similar argument for p-polarized light leads to the calculation of the parallel versions $r_\\textrm{p}$ and $t_\\textrm{p}$ of $r$ and $t$. \nThe boundary conditions for the electric and magnetic field read:\n\\begin{subequations}\n\\begin{align}\n|\\boldsymbol{\\mathcal{E}}_{0 \\textrm{i}}|\\cos\\myangle_{\\textrm{i}} - |\\boldsymbol{\\mathcal{E}}_{0 \\textrm{r}}|\\cos\\myangle_{\\textrm{r}} &= \n|\\boldsymbol{\\mathcal{E}}_{0 \\textrm{t}}|\\cos\\myangle_{\\textrm{t}}\\\\\n|\\boldsymbol{\\mathcal{B}}_{0 \\textrm{i}}| + \n|\\boldsymbol{\\mathcal{B}}_{0 \\textrm{r}}| &= \n|\\boldsymbol{\\mathcal{B}}_{0 \\textrm{t}}|,\n\\end{align}\n\\end{subequations}\nleading to the second pair of Fresnel's equations:\n\\begin{equation}\\label{Fresnel_parallel}\n\\begin{split}\nr_{\\textrm{p}} & = \\frac{|\\boldsymbol{\\mathcal{E}}_{0 \\textrm{r}}|_{\\textrm{p}}}{|\\boldsymbol{\\mathcal{E}}_{0\\textrm{i}}|_\\textrm{p}} = \\frac{\\n_\\textrm{t}\\cos\\myangle_\\textrm{i}-n_\\textrm{i} \\cos\\myangle_\\textrm{t}}{n_\\textrm{i} \\cos\\myangle_\\textrm{t}+n_\\textrm{t}\\cos\\myangle_\\textrm{i}},\\\\\nt_{\\textrm{p}} & =\\frac{|\\boldsymbol{\\mathcal{E}}_{0 \\textrm{t}}|_{\\textrm{p}}}{|\\boldsymbol{\\mathcal{E}}_{0\\textrm{i}}|_\\textrm{p}} =  \\frac{2\\n_\\textrm{i}\\cos\\myangle_\\textrm{i}}{n_\\textrm{i}\\cos\\myangle_\\textrm{t}+n_\\textrm{t}\\cos\\myangle_\\textrm{i}}.\n\\end{split}\n\\end{equation}\n%where $\\myangle_\\textrm{i}\\leq\\myangle_\\textrm{c}$. \nSimilarly to the $s$-polarized case, using Snell's law, the previous equations when $\\myangle_\\textrm{i}\\leq\\myangle_\\textrm{c}$ reduce to:\n\\begin{equation}\n\\fbox{\\begin{minipage}{18em}\n\\begin{equation*} \\label{simple_Fresnel_p}\n\\begin{split}\nr_{\\textrm{p}} & =  \\frac{\\tan(\\myangle_\\textrm{i}-\\myangle_\\textrm{t})}{\\tan(\\myangle_\\textrm{i}+\\myangle_\\textrm{t})}\\\\\nt_{\\textrm{p}} & = \\frac{2\\sin \\myangle_\\textrm{t} \\cos \\myangle_\\textrm{i}}{\\sin(\\myangle_\\textrm{i}+\\myangle_\\textrm{t})\\cos(\\myangle_\\textrm{i}- \\myangle_\\textrm{t})}\n\\end{split}\n\\end{equation*}\n\\end{minipage}}\n\\end{equation}\nFurthermore, it can be checked that\n \\begin{equation}\nt_\\textrm{s}-r_\\textrm{s} = 1\n\\end{equation}\nholds for every $\\myangle_{\\textrm{i}}$, while \n\\begin{equation}\nt_\\textrm{p}+r_\\textrm{p} =  1\n\\end{equation}\nis valid only at normal incidence ($\\myangle_{\\textrm{i}} = 0$).\n\\\\ \\indent The amplitude coefficients are shown in Figure \\ref{fig:coefficients} for the case in which light travels from a less dense to a more dense medium, i.e., $\\n_\\textrm{i}<n_\\textrm{t}$ where $\\n_{\\textrm{i}}= 1$ and $\\n_{\\textrm{t}}=1.5$, thus $\\myangle_\\textrm{i}>\\myangle_\\textrm{t}$. \nIn Figure \\ref{fig:coefficients2} the amplitude coefficients are shown for the case in which $\\n_\\textrm{i}>n_\\textrm{t}$ with $\\n_{\\textrm{i}}= 1.5$ and $\\n_{\\textrm{t}}=1$ ($\\myangle_\\textrm{i}<\\myangle_\\textrm{t}$). Note from Figure \\ref{fig:coefficients} that $r_\\textrm{p}$ approaches $0$ when $\\myangle_\\textrm{i}$ approaches $\\myangle_\\textrm{p}$ and it gradually decreases, reaching $-1$ for an incident angle $\\myangle_\\textrm{i}=90^\\circ$. The angle $\\myangle_\\textrm{p}$ is called \\textit{Brewster's angle} or polarization angle as only the component perpendicular to the incident plane is reflected at that angle and therefore light is perfectly polarized. Similarly, Figure \\ref{fig:coefficients2} shows that $r_\\textrm{p}=0$ for $\\myangle_\\textrm{i}= \\myangle_{\\textrm{p}\\prime}$. It can be show that $\\myangle_\\textrm{p}+ \\myangle_{\\textrm{p}\\prime}= 90^\\circ$. Both $r_\\textrm{p}$ and $r_\\textrm{s}$ reach $1$ when $\\myangle_\\textrm{i}~=~\\myangle_\\textrm{c}$. $\\myangle_\\textrm{c}$ is called the critical angle. Light that hits the incident plane with an incident angle equal to or greater than $\\myangle_{\\textrm{c}}$ is totally reflected back and no transmitted light is observed. This phenomenon is called total internal reflection. \n\\begin{figure}[t]\n  \\begin{minipage}[h]{0.48\\textwidth}\n    \\includegraphics[width=\\textwidth]{amplitude_coefficients}\n    \\caption{\\textbf{Amplitude coefficients of reflection and transmission.} $n_\\textrm{i}<n_\\textrm{t}$\n($n_\\textrm{i} = 1$ and $\\n_\\textrm{t}=1.5$). $\\myangle_\\textrm{p} ~=~ 56.3^\\circ$ is the polarization angle.}\n    \\label{fig:coefficients}\n  \\end{minipage}\\hfill\n  \\begin{minipage}[h]{0.48\\textwidth}\n    \\includegraphics[width=\\textwidth]{amplitude_coefficients3}\n    \\caption{\\textbf{Amplitude coefficients.} $n_\\textrm{i}>n_\\textrm{t}$\n($n_\\textrm{i} = 1.5$ and $n_\\textrm{t}=1$). $\\myangle_{p\\prime}~=~ 33.7^\\circ$ is the polarization angle and $\\myangle_\\textrm{c}= 41.8^\\circ$ is the critical angle.}\n   \\label{fig:coefficients2}\n \\end{minipage}\n\\end{figure}\\\\\n%\\indent The  we introduce the Poynting vector \\vect{P} that defines the energy flux of an electromagnetic field. \n%It is measured in $[\\textrm{W}/\\textrm{m}^2]$, and it is given by:\n%\\begin{equation}\n%\\vect{P} = \\frac{1}{\\mu}\\Big(\\boldsymbol{\\mathcal{E}}\\boldsymbol{\\times} \\boldsymbol{\\mathcal{B}}\\Big),\n%\\end{equation}\n%where $\\mu = \\frac{1}{\\varepsilon v^2}$ is the permeability and $\\varepsilon$ the permittivity of the medium.\n% In the following, the parameters for vacuum are indicated with the subscript $0$. Optical rays are perpendicular to the wave front of an electromagnetic wave and parallel to the Poynting vector \\cite{jones2015optical}.\n\\indent To calculate the amount of energy reflected and transmitted, it is necessary to define the reflection and transmission coefficients in terms of the irradiance (or radiant flux density) $P$ rather than in terms of amplitudes of the electric field. For a wave of amplitude $|\\boldsymbol{\\mathcal{E}}_0|$ propagating in a non-magnetic medium with a refractive index $n$, the energy flux $P$ is given by:\n%Therefore, defining the average of the vector \\vect{P} over the time as:\n%\\begin{equation}\n%\\langle \\vect{P} \\rangle_T = \\frac{1}{T}\\int_0^T \\vect{P}\\textrm{d}T\n%\\end{equation}\n%we can write the irradiance $E$ as:\n\\begin{equation}\nP = \\frac{c\\, n \\, \\varepsilon_0}{2}|\\boldsymbol{\\mathcal{E}}_0|^2,\n\\end{equation}\n\\cite{hecht1998hecht}. For a beam of light that hits a surface such that an area $A$ is illuminated,\n$P$ is the average energy that crosses in unit time a unit area $A$ perpendicular to the direction of the energy flow.\nWe indicate with $P_{\\textrm{i}}$, $P_{\\textrm{r}}$ and $P_{\\textrm{t}}$ the incident, reflected and transmitted flux densities, respectively.\nThe energy per unit time for the incident, reflected and transmitted beams are \n$P_\\textrm{\ni} A\\cos\\myangle_\\textrm{i}$, $P_\\textrm{r} A\\cos\\myangle_\\textrm{r}$, and \n$P_\\textrm{t} A\\cos\\myangle_\\textrm{t}$, respectively. % as is shown in Figure \\ref{}\nThe reflectance $\\mathcal{R}$ is the ratio of the reflected power to the incident power:\n\\begin{equation}\\label{reflectance}\n\\mathcal{R} = \\frac{P_\\textrm{r}\\cos\\myangle_\\textrm{r}}{P_\\textrm{i}\\cos\\myangle_\\textrm{i}} = \\frac{|\\boldsymbol{\\mathcal{E}}_{0 \\textrm{r}}|^2}{|\\boldsymbol{\\mathcal{E}}_{0 \\textrm{i}}|^2} = r^2,\n\\end{equation}\nwhere the second equality holds because $\\n_{\\textrm{i}}= \\n_{\\textrm{r}}$, $\\varepsilon_{\\textrm{i}} = \\varepsilon_{\\textrm{r}}$ and $\\myangle_{\\textrm{i}} = \\myangle_{\\textrm{r}}$.\nSimilarly, the transmittance $\\mathcal{T}$ is the ratio between the transmitted to the incident power:\n\\begin{equation}\\label{transmittance}\n\\mathcal{T} = \\frac{P_\\textrm{t} \\cos\\myangle_\\textrm{t}}{P_\\textrm{i}\\cos\\myangle_\\textrm{i}} = \\frac{n_\\textrm{t} \\cos\\myangle_\\textrm{t}}{n_\\textrm{i} \\cos\\myangle_\\textrm{i}}\\frac{|\\boldsymbol{\\mathcal{E}}_{0 \\textrm{t}}|^2}{\\boldsymbol{|\\mathcal{E}}_{0 \\textrm{i}}|^2} = \\frac{n_\\textrm{t} \\cos\\myangle_\\textrm{t}}{n_\\textrm{i} \\cos\\myangle_\\textrm{i}} t^2\\,.\n\\end{equation}\nEmploying total energy conservation, that is:\n\\begin{equation}\nP_\\textrm{i} A\\cos\\myangle_\\textrm{i} = P_\\textrm{r} A\\cos\\myangle_\\textrm{r}+P_\\textrm{t} A\\cos\\myangle_\\textrm{t},\n\\end{equation}\nwe can easily prove that:\n\\begin{equation}\n\\fbox{\\begin{minipage}{10em}\n\\begin{equation*}\n\\mathcal{R}+\\mathcal{T}=1\\,.\n\\end{equation*}\n\\end{minipage}}\n\\end{equation}\n The perpendicular and parallel versions of $\\mathcal{R}$ and $\\mathcal{T}$ are given by:\n\\begin{equation}\n\\fbox{\\begin{minipage}{15em}\n\\begin{equation*}\\label{Fresnel_pands}\n\\begin{split}\n\\mathcal{R}_\\textrm{s} &=  r_\\textrm{s}^2\\\\\n\\mathcal{T}_\\textrm{s} &= \\frac{n_\\textrm{t} \\cos\\myangle_\\textrm{t}}{n_\\textrm{i} \\cos\\myangle_\\textrm{i}}t_\\textrm{s}^2\\\\\n\\mathcal{R}_\\textrm{p}& =  {r_\\textrm{p}^2}\\\\\n\\mathcal{T}_\\textrm{p} &=  \\frac{n_\\textrm{t} \\cos\\myangle_\\textrm{t}}{n_\\textrm{i} \\cos\\myangle_\\textrm{i}}t_\\textrm{p}^2\\\\\n\\end{split}\n\\end{equation*}\n\\end{minipage}}\n\\end{equation}\nIt can be shown that \n%\\begin{equation}\n%\\fbox{\\begin{minipage}{15em}\n\\begin{equation}\n\\begin{split}\n\\mathcal{R}_\\textrm{s}+\\mathcal{T}_\\textrm{s} &= 1,\\\\\n\\mathcal{R}_\\textrm{p}+\\mathcal{T}_\\textrm{p} &=1\\,.\n\\end{split}\n\\end{equation}\n%\\end{minipage}}\n%\\end{equation}\nFor normal incidence, i.e., $\\myangle_\\textrm{i} = 0$, the incident plane is not defined and there is no distinction between the perpendicular and the parallel versions of $\\mathcal{R}$ and $\\mathcal{T}$. As a consequence, (\\ref{Fresnel_pands}) combined with (\\ref{Fresnel_perpendicular}) and (\\ref{Fresnel_parallel}) leads to:\n\\begin{equation}\\label{eq:fresnel_pands2}\n\\begin{split}\n\\mathcal{R} &= \\mathcal{R}_\\textrm{p} = \\mathcal{R}_\\textrm{s} = \\Bigg(\\frac{n_\\textrm{i}-n_\\textrm{t}}{n_\\textrm{t}+n_\\textrm{i}}\\Bigg)^2, \\\\\n\\mathcal{T} &= \\mathcal{T}_\\textrm{p} = \\mathcal{T}_\\textrm{s} = \\frac{4n_\\textrm{i} n_\\textrm{t}}{(n_\\textrm{t}+n_\\textrm{i})^2}\\,.\n\\end{split}\n\\end{equation}\n%In two dimensions light hits lines instead of surfaces. Therefore only the plane of incidence is defined and it has no sense to consider separately the parallel and the perpendicular polarization. \n%If $\\mathcal{R}_\\textrm{p} = \\mathcal{R}_\\textrm{s}$ and $\\mathcal{T}_\\textrm{p} = \\mathcal{T}_\\textrm{s}$, then the amount of energy in both polarization states is the same \\cite{hecht1998hecht}.\\\\ \\indent\n\nMany common light sources such as the sun, halogen lighting, LED spotlights, and incandescent bulbs produce unpolarized light. \nIn this case, light can be represented by the sum of two orthogonal states. For unpolarized light, the convention is to take as reflectance and transmittance the averages:\n\\begin{equation}\n\\fbox{\\begin{minipage}{15em}\n\\begin{equation*}\\begin{split}\n\\mathcal{R} &= \\frac{\\mathcal{R}_\\textrm{p}+ \\mathcal{R}_\\textrm{s}}{2}\\\\\n\\mathcal{T} &= \\frac{\\mathcal{T}_\\textrm{p}+ \\mathcal{T}_\\textrm{s}}{2}\n\\end{split}\n\\label{eq:RandTin2D}\n\\end{equation*}\n\\end{minipage}}\n\\end{equation}\nwhere $\\mathcal{R}_\\textrm{p}$, $\\mathcal{R}_\\textrm{s}$, $\\mathcal{T}_\\textrm{p}$ and $\\mathcal{T}_\\textrm{s}$ are obtained from (\\ref{Fresnel_pands}). The reflectance $\\mathcal{R}$ and the transmittance $\\mathcal{T}$ give the fraction of the power of energy reflected and transmitted at every interaction of a light ray with a Fresnel surface.\n\nWith this overview we conclude this chapter. The notions given in Section \\ref{sec:photometry} will be used in the entire thesis as our goal is to study the distribution of light at the target of some optical systems. In particular, we will focus on the computation of the output intensity distribution. The reflection and refraction laws explained in Section \\ref{sec:reflection} are needed to determine how the optical system changes the ray's direction every time that it hits a surface (or a line in the two-dimensional case). In Chapters \\ref{chap:raytracing}-\\ref{chap:raymapping2} we restrict ourselves to pure reflection and refraction; the Fresnel reflection and refraction are ignored. Systems with Fresnel reflection is postponed until Chapter \\ref{chap:fresnel}. The amount of reflected and transmitted light is calculated using (\\ref{eq:RandTin2D}) and (\\ref{Fresnel_pands}) where $r_\\textrm{s}$ and $t_\\textrm{s}$ are obtained from (\\ref{Fresnel_perpendicular}) and $r_\\textrm{p}$ and $t_\\textrm{p}$ from (\\ref{Fresnel_parallel}). In our simulations we consider the general case of unpolarized light. \n", "meta": {"hexsha": "52c13db55d8372d5bc4a72e726404760a8106112", "size": 46080, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/Non_imaging_optics.tex", "max_stars_repo_name": "melaniafilosa/ps_raytracing", "max_stars_repo_head_hexsha": "8f9111ea4ec3ac125b593f41b3ac6fe302ea6632", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/Non_imaging_optics.tex", "max_issues_repo_name": "melaniafilosa/ps_raytracing", "max_issues_repo_head_hexsha": "8f9111ea4ec3ac125b593f41b3ac6fe302ea6632", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/Non_imaging_optics.tex", "max_forks_repo_name": "melaniafilosa/ps_raytracing", "max_forks_repo_head_hexsha": "8f9111ea4ec3ac125b593f41b3ac6fe302ea6632", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 86.1308411215, "max_line_length": 1252, "alphanum_fraction": 0.7313802083, "num_tokens": 15249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3247718274027638}}
{"text": "\\chapter{\\proj Object Detection}\n\\label{ch_mvm}\n\\index{detection}\n\n\\markright{Object detection}\n\n\n\\section{Multiscale Vision Model}\n\\label{sect_detect}\n\\subsection{Introduction}\nAfter applying the wavelet transform on the image, we have to \ndetect, to extract, to measure and to recognize the significant \nstructures. The wavelet space of a 2D direct space \nis a 3D one. An object has to be defined in \nthis space.  A general idea for object definition lies in the connectivity \nproperty. An object occupies a physical region, and in this region we \ncan join any pixel to other ones. The connectivity in the direct space \nhas to be transported to the wavelet transform space (WTS). In order to \ndefine the objects we have to identify the WTS pixels we can attribute to \nthe objects.\n\n\\begin{figure}[htb]\n\\centerline{\n\\hbox{ \n\\psfig{figure=fig_detect.ps,bbllx=4cm,bblly=4cm,bburx=18cm,bbury=21.cm,width=12cm,height=12cm}\n}}\n\\label{fig_detect_graph}\n\\caption{Example of connectivity in the wavelet space: contiguous significant wavelet \ncoefficients\nform a structure, and following an interscale relation, a set of structures form\nan object. Two structures $S_{j},S_{j+1}$ at two successive scales  \nbelong to the same object if the position pixel of the maximum wavelet\ncoefficient value of $S_j$ is  included in $S_{j+1}$.}\n\\end{figure}\n\nFigure~\\ref{fig_detect_graph} shows an example of connectivity between \ndetected structures at different scales.\n\n\\subsection{Definition}\n\nThe Multiscale Vision Model (MVM) \\cite{ima:bijaoui95,ima:rue97} \ndescribed  an object as a hierarchical set of structures.\nIt uses the following definitions:\n\\begin{itemize}\n\\item {\\bf Structure}: a structure ${\\cal S}_j$ is a set of significant\n connected wavelet coefficients at the same scale $j$. \\\\\n\\item {\\bf object}: an object is a set of structures.\\\\\n\\item {\\bf object scale}: the scale of an object is given by the scale of the\nmaximum of its wavelet coefficients.\\\\\n\\item {\\bf interscale-relation}: the rule which  \nallows us to connect two structures into a single object\nis called ``interscale relation''. Let us consider two structures at two \nsuccessive scales, $S^1_j$ and  $S^2_{j+1}$. Each\nstructure is located in one of the individual images of the\ndecomposition and corresponds to a region in this image where the\nsignal is significant. Noting $p_m$ the pixel position of the maximum\nwavelet coefficient value of $S^1_j$, $S^1_j$ is said to be connected to\n$S^2_{j+1}$ if $S^2_{j+1}$ contains the pixel position $p_m$ (i.e. the maximum\nposition of the structure $S^1_j$ must also be contained in the structure \n$S^2_{j+1}$). Several structures\nappearing in successive wavelet coefficient images can be connected in\nsuch a way, which we call an object in the interscale connectivity\ngraph.\n\\item {\\bf sub-object}: a sub-object is a part of an object. It appears when\nan object has a local wavelet maximum. Hence, an object can be composed of\nseveral sub-objects. Each sub-object can also be analysed.\n\\end{itemize}\n\n\\subsection{Reconstruction}\nThe problem of reconstruction \\cite{ima:bijaoui95,ima:rue97} \nconsists of searching for a signal $O$ such that\nits wavelet coefficients are the same as those of the detected\nstructures. If $\\cal T$ describes the wavelet transform operator, and $P_w$ the\nprojection operator in the subspace of the detected coefficients\n(i.e.\\ all coefficients set to zero at scales and positions where\nnothing was detected), the solution is found by minimization of\n\\begin{eqnarray*}\nJ(O) = \\parallel W - (P_w \\circ {\\cal T}) O  \\parallel\n\\end{eqnarray*}\nwhere $W$ represents the detected wavelet coefficients of the data.\n\nThe MVM presents many advantages compared to the standard approach:\n\\begin{itemize}\n\\item faint extended objects can be detected as well as point sources,\n\\item the analysis does not require background estimation,\n\\item the Point Spread Function (PSF) is not needed.\n\\end{itemize}\nThe second point is relatively important. Indeed, if the background varies\nspatially, its estimation becomes a non-trivial task, and may produce \nlarge errors in the object photometry.\n\nThe last point is an advantage when the PSF is unknown, or difficult to \nestimate, which occurs relatively often when it is space variant.\nHowever, when the PSF is well determined, it becomes a drawback because\nknown information is not used for the object reconstruction. \nSuch a situation leads to\nsystematic errors in the photometry, which depends on PSF and on the source \nsignal to noise ratio.\nIn order to correct this error, a kind of calibration must be performed using\nsimulations \\cite{starck:sta99_4}. The \nnext section shows how the PSF can be used\nin the MVM, leading to a deconvolution.\n\n\\section{Detection and Deconvolution}\n\\subsection{Object reconstruction using the PSF}\nA reconstructed and deconvolved object can be obtained\nby searching for a signal $O$ such that\nthe wavelet coefficients of $P*O$ are the same as those of the detected\nstructures. If $\\cal T$ describes the wavelet transform operator, \nand $P_w$ the projection operator in the subspace of the detected coefficients,\n the solution is found by minimization of\n\\begin{eqnarray}\nJ(O) = \\parallel W - (P_w \\circ {\\cal T}) P * O  \\parallel\n\\end{eqnarray}\nwhere $W$ represents the detected wavelet coefficients of the data, and \n$P$ is the point spread function. By this approach, each object is deconvolved\nseparately. The flux related to the ring of the PSF will be taken into \naccount. For a point source, the solution will be close to that obtained by\nPSF fitting. This problem is different from global deconvolution \nin the sense that it is well-constrained. Exept for the \npositivity of the solution\nwhich is always true and must be used, no other constraint needs to\nbe introduced. This is due to the fact that the reconstruction is performed\nfrom a small set of wavelet coefficients (those above a detection limit).\nThe number of objects are the same as those obtained by the MVM, but\nthe photometry and the morphology are different. The position may also change\na little.\n\n\\subsection{The algorithm}\nAny minimizing method can be used to obtain the solution $O$. As we did not\nmeet any problem of convergence, noise amplification, or ringing effect, \nwe choose the Van Cittert method, which is certainly the simplest one.\nFor each detected object, we apply the following algorithm:\n\n\\begin{eqnarray}\nO^{n+1} = O^{n} + {\\cal T}^{-1}(W - (P_w \\circ {\\cal T}) P * O^{n})\n\\end{eqnarray}\nwhere ${\\cal T}^{-1}$ is the inverse wavelet transform.\n\n\\begin{enumerate}\n\\item Set $n$ to $0$.  \n\\item Find the initial estimation $O^{n}$ by applying an inverse\nwavelet transform to the set $W$ corresponding to the detected wavelet\ncoefficients in the data.\n\\item Convolve $O^{n}$ with the PSF $P$: $I^n = P*O^{n}$.\n\\item Determine the wavelet transform $W(I^n)$ of $I^n$.\n\\item Threshold all wavelet coefficients in $W(I^n)$ at position \nand scales where nothing has been detected (i.e. $P_w$ operator). We get\n$W_t(I^n)$.\n\\item Determine the residual $W(R) = W -  W_t(I^n)$.\n\\item Reconstruct the residual image $R^n$ applying an inverse wavelet\n transform.\n\\item Add the residual to the solution: $O^{n+1} = O^{n} + R^n$.\n\\item Threshold negative values in $O^{n+1}$.\n\\item if $\\sigma(R^n) / \\sigma(O^0) < \\epsilon$ then $n = n + 1$ and goto step 3.\n\\item $O^{n+1}$ contains the deconvolved reconstructed object. \n\\end{enumerate}\nIn practice, the convergence is very fast (less than 20 iterations).\nThe reconstructed image (not deconvolved) can also be obtained, just by\nreconvolving the solution with the PSF.\n\n\\clearpage\n\\newpage\n\n\\section{Object Detection:  mr\\_detect}\n\\index{mr\\_detect}\nProgram {\\em mr\\_detect} detects all objects present in \nan image \\cite{ima:bijaoui95,ima:rue97}.\nSeveral output files are created:\n\\begin{itemize}\n\\item name\\_out.tex: LaTeX file which contains a table describing all detected\nobjects. Values given in the \ntable are respectively the object number, the coordinates in pixel units, \nthe standard deviation in $x$ and $y$, the orientation, the maximum value, \nthe flux and the signal to noise ratio of\n the maximum wavelet coefficient of the object. This file\ncan be compiled by the LaTeX command. The pixel coordinates are given\nusing the first pixel of the image as the reference pixel (0,0).\nThe rotation angle gives the angle between the main axis of the object\nand the x-axis following the trigonometric convention. The object number is\ndefined by numbers: the scale number which indicates at which  scale\nthe object is detected, and a number which indicates the object number\nat this scale.\n\\item name\\_out\\_obj.ps: a Postscript file giving the position\nof all objects in the image.\n\\item name\\_out.fits: this image contains the sum of all objects. It looks\nlike a filtered image, without any background.\n\\item name\\_out.mes: ASCII file describing all detected objects. Each object\nis described by five lines: \n\\begin{itemize}\n\\item the first line contains the scale where the maximum of the object has\nbeen detected, and the object number at this scale.\n\\item the second line contains respectively the coordinates \nin pixel units ($x$ and $y$), and the standard deviation in $x$ and $y$.\n\\item the third line contains the orientation, the maximum value, the flux,\nand the magnitude.\n\\item the fourth line contains the flux error, the signal to noise \nratio (SNR) of the\nmaximum of the wavelet coefficient, and the SNR of the object.\nThe SNR of the wavelet coefficient gives the ratio between the maximum \nof the wavelet coefficients belonging to the object, and the standard deviation\nof the noise at the scale of this maximum. The SNR of the object is obtained\nby calculating the standard deviation in a box containing 90\\% of the flux of\nthe object in the reconstructed image, and by taking the  ratio between \nthis standard deviation and \nthe noise standard deviation. In the case of Poisson\nnoise with few events, the SNR of the wavelet coefficient is not calculated,\nbut instead the probability that the wavelet coefficient is not due to noise\n(i.e.\\ due to signal), and the SNR of the object, is calculated by\ntaking the ratio between  90\\% of the flux of the source and the square\nroot of the flux contained in the same box in the original data.\n\\item the last line contains the position of the maximum wavelet coefficient.\n\\end{itemize}\n\\end{itemize}\nFurthermore, if the option ``-w 1'' is set, an image is created for each \nobject individually.\nFor a FITS image, if the ``-C'' option is set, another TeX table is created\ncontaining the object coordinates (RA, Dec), the flux and the SNR.\n\nIf the Point Spread Function (PSF) is available, it can be given to the\nprogram using the ``-P'' option. It generally improves the object photometry.\nFurthermore an object deconvolution can be performed using the \n``-D'' option. In\nthis case, each object is also deconvolved. \n\nThe photometry is by default estimated by integrating the flux in the\nreconstructed object. An alternative is to use an \naperture photometry (``-a'' option). In this case, a background image is needed.\nIt can be:\n\\begin{itemize}\n\\item automatically calculated using pyramidal transform (PMT) (``-a 1'').\nIt is found by interpolating\n the last scale of the PMT  to the input image size. \n The number of scales is derived from the\n input image size and the number of pixels in the last scale (default is 16, \n and can be changed with the ``-b'' option).\n The background image size must be large enough to take into account \n background variations, and small enough to no take into account the \n information relative to the significant signal.\n\\item  a flat image (``-a 3''), with a value equal to\n{\\em BgrValue}.\n\\item an image given by the user (``-a 2'' + ``-B'' option).\n\\end{itemize}\nAn object is characterized by its second order moments $\\sigma_x,\\sigma_y$ in\nthe two principal directions. The aperture photometry is done in a box\nof size $k MAX(\\sigma_x,\\sigma_y)$, where k is defaulted to 3. $k$ can\nbe modified by the ``-l'' option.\n\n{\\bf\n\\begin{center}\n USAGE: mr\\_detect option image\\_in name\\_out\n\\end{center}}\n{\\bf image\\_in} is the input image and {\\bf name\\_out} the name which will\nbe used for the output files. This name must not contain any suffix.\n\\\\\nOptions are:\n\\begin{itemize}\n\\baselineskip=0.4truecm\n\\itemsep=0.1truecm\n\\item {\\bf [-t type\\_of\\_multiresolution\\_transform ]}\n\\begin{enumerate}\n\\baselineskip=0.4truecm\n\\itemsep=0.1truecm\n\\item B-spline wavelet transform: \\`a trous algorithm\n\\item Half-pyramidal transform\n\\item Pyramidal B-spline wavelet transform\n\\item Mixed WT and PMT method (WT-PMT)\n\\item Mixed Half-pyramidal WT and Median method (WT-HPMT) \n\\end{enumerate}\nDefault is 1.\n\\item {\\bf [-V Multiscale\\_Vision\\_Model]}\n\\begin{enumerate}\n\\baselineskip=0.4truecm\n\\itemsep=0.1truecm\n\\item No vision model.\n\\item Blinded Objects. \n\\item Rue-Bijaoui Vision Model for blinded + embedded Objects. \n\\end{enumerate}\nDefault is Rue-Bijaoui Vision Model for blinded + embedded Objects.\n\\item {\\bf [-n number\\_of\\_scales]} \\\\\nNumber of scales used in the multiresolution transform. Default is 5.\n\\item {\\bf [-m type\\_of\\_noise]} \\\\\nDescription in section~\\ref{sect_filter}.\n\\item {\\bf [-g SigmaNoise]} \\\\\nSigmaNoise = noise standard deviation. Default is automatically estimated.\n\\item {\\bf [-c gain,sigma,mean]} \\\\\nDescription in section~\\ref{sect_support}.\n\\item {\\bf [-s NSigma]} \\\\\nThresholding at Nsigma * SigmaNoise. Default is 3.\n\\item {\\bf [-E Epsilon]} \\\\\nEpsilon = precision for computing thresholds. (Only used in the case of \nPoisson noise with few events). Default is 1e-03.\n\\item {\\bf [-e minimum\\_of\\_events ]} \\\\\nMinimum number of events for a detection. Default is 4. \\\\\nFor Poisson noise with few events only (-m 9).\n\\item {\\bf [-S SizeBlock]} \\\\\nSize of the  blocks used for local variance estimation. Default is 7.\n\\item {\\bf [-N NiterSigmaClip]} \\\\\nIteration number used for local variance estimation. Default is 1.\n\\item {\\bf [-F first\\_detection\\_scale]} \\\\\nFirst scale used for the detection. Default is 1.\n\\item {\\bf [-R RMS\\_Map\\_File\\_Name]} \\\\\nRMS Map.  If this option is set, the noise model is automatically fixed to:\\\\\nNon-stationary additive noise\n\\item {\\bf [-L last\\_detection\\_scale]} \\\\\nLast scale used for the detection.\n\\item {\\bf [-i number\\_of\\_iterations]} \\\\\nIteration number per object reconstruction. Default is 10.\n\\item {\\bf [-u object\\_reconstruction\\_error]} \\\\\nDefault is 1e-5.\n\\item {\\bf [-k]} \\\\\nKeep isolated objects. Default is no.\n\\item {\\bf [-K]} \\\\\nKeep objects which touch the border. Default is no.\n\\item {\\bf [-A FluxMult]} \\\\\n Flux in TeX tables are multiplied by {\\em FluxMul}. Default is 1.   \n\\item {\\bf [-w writing\\_parameter]}\n\\begin{enumerate}\n\\baselineskip=0.4truecm\n\\itemsep=0.1truecm\n\\item  Write each object separately in an image. \\\\\nThe image file name of the object will be:\n\\begin{center}\n                      ima\\_obj\\_xx\\_yy.fits \n\\end{center}\n\\item  Two synthetic images \\\\\nxx\\_ellips.fits: an ellipse is drawn around each object \\\\\nxx\\_simu.fits: image created only from the morphological parameters \n\\item  equivalent to 1 and 2 together \n\\end{enumerate}\n\\item {\\bf [-U]} \\\\\nSub-segmentation. If two objects are close, and detected as a single object,\nsub-segmentation will try to separate them (deblending) into two objects.\n\\item {\\bf [-p]} \\\\\nDetect also negative structures. Default is no.\n\\item {\\bf [-q]} \\\\\nDefine the root of an object from the maximum position and its value.\n\\item {\\bf [-d DistMax]} \\\\\nMaximum distance between two max positions \nof the same object at two successive scales. \\\\\nDefault is 1.\n\\item {\\bf [-o Sub-object analysis]} \\\\\nIf set, sub-objects are also analysed. Several files are created:\n\\begin{itemize}\n\\baselineskip=0.4truecm\n\\item name\\_out\\_sub\\_obj.ps: a Postscript file giving the position\nof all sub-objects in the image.\n\\item name\\_out\\_sub.mes: ASCII file describing all detected sub-objects. \nThe syntax is the same as for the object ASCII file.\n\\item name\\_out\\_sub.tex: LaTeX file which contains a table describing all detected\nsub-objects.  The syntax is the same as for the object TeX file.\n\\item name\\_out\\_subobj\\_radec: sub-object coordinates (only \nif ``-C'' option is set).\n\\end{itemize}\n\\item {\\bf [-D]} \\\\\nPerform a deconvolution. Default is no.\n\\item {\\bf [-P PsfFileName]} \\\\\nPSF file name.\n\\item {\\bf [-f Fwhm]} \\\\\nFull Width at Half Maximum.\n\\item {\\bf [-O PSF\\_Sampling]} \\\\\nPSF over-sampling value.\n\\item {\\bf [-a BgrMethod] } \\\\\n Aperture photometry:\n\\begin{enumerate}\n\\baselineskip=0.4truecm\n\\itemsep=0.1truecm\n\\item Aperture photometry using a background image model \n\\item Aperture photometry using an estimated background image \n\\item Aperture photometry using a constant background \n\\end{enumerate}\nDefault is no aperture photometry.\n\\item {\\bf [-B BgrFileName]  } \\\\\nBackground image file name.\n\\item {\\bf [-G BgrValue] } \\\\\nConstant background value. Default is: 0.\n\\item {\\bf  [-b BGR\\_Size] } \\\\\nBackground image size for automatic background estimation.\nDefault is 16.\n\\item {\\bf [-l KSigmaAperture]  } \\\\\nAperture photometry size parameter. Default is 3.\n\\item {\\bf [-M object\\_reconstruction\\_method]}\n\\begin{enumerate}\n\\baselineskip=0.4truecm\n\\itemsep=0.1truecm\n\\item reconstruction from the fixed step gradient method \n\\item reconstruction from the optimum step gradient method \n\\item reconstruction from the conjugate gradient method \n\\item reconstruction using the PSF\n\\end{enumerate}\nDefault is: reconstruction from the conjugate gradient method\n\\item {\\bf [-C RADEC\\_Table\\_Order]}\n\\begin{enumerate}\n\\baselineskip=0.4truecm\n\\itemsep=0.1truecm\n  \\item TeX table ordered by object number.\n  \\item TeX table ordered by the right ascension.\n  \\item TeX table ordered by object SNR.\n\\end{enumerate}\nA TeX table of name {\\bf name\\_out\\_radec.tex} is created, which contains\nthe object number, the right ascension (in degrees and in HH MN SEC), the\ndeclination in degrees and in DEG MN SEC), the flux, and the SNR. The object \norder depends on the {\\em RADEC\\_Table\\_Order} parameter.\n\\item {\\bf [-v]} \\\\\nVerbose. Default is no.\n\\end{itemize}\n\n\\section{Examples and Strategies}\n\n\\begin{figure}[htb]\n\\centerline{\n\\vbox{\n\\hbox{\n\\psfig{figure=fig_bert_org.ps,bbllx=1.9cm,bblly=12.6cm,bburx=14.6cm,bbury=25.4cm,width=8cm,height=8cm,clip=}\n\\psfig{figure=fig_bert_imag.ps,bbllx=1.9cm,bblly=12.6cm,bburx=14.6cm,bbury=25.4cm,width=8cm,height=8cm,clip=}}\n\\hbox{\n\\psfig{figure=fig_bert_detect.ps,bbllx=1.9cm,bblly=12.6cm,bburx=14.6cm,bbury=25.4cm,width=8cm,height=8cm,clip=}\n\\psfig{figure=fig_bert_ellips.ps,bbllx=1.9cm,bblly=12.6cm,bburx=14.6cm,bbury=25.4cm,width=8cm,height=8cm,clip=}}\n}}\n\\caption{Top left, original simulated image (stars + galaxies). Top right,\nsame image plus Gaussian noise. Bottom left, output image produced by\n{\\em mr\\_detect}. Bottom right, noise image, and ellipses overplotted.}\n\\label{fig_bert}\n\\end{figure}\n\n\\begin{itemize}\n\\item  mr\\_detect -v -w 2 field\\_g10.fits detect\\_field \\\\\nFigure~\\ref{fig_bert} presents the result of applying such a treatment.\nThe input image (top right)  has been obtained by adding \nGaussian noise to a simulated image (top left). The output image shows\nthat all objects (even very faint objects) have been detected.\nThe file ``detect\\_field.tex'' contains Table~\\ref{tabdetect}, and\ncan be compiled by the simple command ``latex detect\\_field''.\n\\item mr\\_detect -P PsfFileName field\\_g10.fits detect\\_field \\\\\nApply the detection with the same parameters, but using the PSF.\n\\item mr\\_detect -D -P PsfFileName field\\_g10.fits detect\\_field \\\\\nThis time, a deconvolution is performed on each extracted object. \n\\item mr\\_detect -D -P -u 0 -i 20 PsfFileName field\\_g10.fits detect\\_field \\\\\nForce the number of iterations for each object reconstruction to be equal to 20.\n\\item  mr\\_detect -v -m 2 -n 7 field\\_g10.fits detect\\_field \\\\\nAssume Poisson noise, and use more wavelet scales.\n\\item  mr\\_detect -t 5 -q field\\_g10.fits detect\\_field \\\\\nThe fifth transform type is used. \nThis means that the reconstruction is not iterative\n(it runs faster). When two objects are blended, \nit may not reconstruct them as\nwell as with other transforms.\nThe Postscript file ``detect\\_field\\_obj.ps'' (see Figure \\ref{fig_ima_obj}) \nshows the position of each object in the map.\n\n\\end{itemize}\n\n\\subsection{Choice of multiscale transform}\n\\subsubsection*{Linear versus nonlinear transform}\nFive multiscale transforms are available. The first three are wavelet \ntransforms, while the last two are nonlinear transform. Wavelet transforms\nshould normally be preferred to nonlinear transforms, but in some cases, \nnon-linear transforms can be useful. The main difference between the two\ntypes of transform  is that nonlinear transforms allow us to have very\nfast object reconstruction, without iterating. But the separation between\ntwo blended objects is better when we iterate. \nThe PSF can also not be used when\nusing nonlinear methods, and the consequence is that the photometry may \nbe systematically underestimated. \n\n\\subsubsection*{Decimation or not?}\nThe default transform (transform 1) produces cubes, while transforms \n2 and 5 produce half pyramidal data structures, and 3 and 4 pyramidal \ndata structures. It is clear that in using pyramidal transforms we save\ncomputation time and memory space, but the quality is less good than with\nthe two other sets of transforms. Half pyramidal transforms may be\na good compromise between quality and both computation time and memory.\n\n\\subsubsection*{Photometry}\nBy default, {mr\\_detect} estimates the object photometry without any\ninformation about the Point Spread Function (PSF). If the PSF presents\na tail, it may not be detected in the wavelet space and the photometry\nmay have a systematic error which depends on the PSF and \non the flux of the source. If objects are sparse, an aperture photometry\nwill resolve this problem (``-a'' option). In the case\nwhere the PSF is known, a more accuracy photometry \ncan also be obtained using the ``-P'' option. The PSF knowledge can be used\nfor the object reconstruction, and the tail arround the objects is correctly\nrestored. This approach produces normally goor results, even for crowded\nfields, where an aperture photometry produces poor results.\n\n\\begin{table}[h]\n\\begin{center}\n\\begin{tabular}{||c||c|c|c|c|c|c|c|c||}\n\\hline\nObject & x & y & $\\sigma_x$ & $\\sigma_y$ & $\\theta$ &\n\t$I_{max} $ & Flux & SNR\\_WaveCoef\\\\\n\\hline\n\\hline\n3-1 & 166.78 & 171.85 & 3.90 & 3.54 & 6.4 & 64.62 & 3155.54  & 26.88\\\\\n\\hline\n3-2 & 167.23 & 47.96 & 2.16 & 1.59 & 23.1 & 26.30 & 533.53  & 24.34  \\\\\n\\hline\n3-3 & 230.21 & 83.97 & 4.34 & 4.78 & -14.6 & 84.77 & 6107.79 & 10.59  \\\\\n\\hline\n3-4 & 129.85 & 88.28 & 4.47 & 6.89 & 15.0 & 81.99 & 8839.90 & 22.36 \\\\\n\\hline\n3-5 & 63.78 & 185.28 & 5.49 & 2.85 & 2.4 & 91.62 & 6830.69 & 32.21 \\\\\n\\hline\n2-1 & 119.96 & 17.71 & 1.93 & 3.12 & -18.0 & 85.43 & 2910.22 & 14.89 \\\\\n\\hline\n2-2 & 129.27 & 29.65 & 4.54 & 2.33 & -5.5 & 398.30 & 16277.82  & 60.05 \\\\\n\\hline\n2-3 & 154.99 & 145.35 & 2.66 & 2.91 & -35.5 & 181.33 & 6070.46 & 31.37  \\\\\n\\hline\n2-4 & 16.67 & 160.69 & 2.78 & 2.40 & -11.6 & 55.63 & 1562.33 & 8.37 \\\\\n\\hline\n2-5 & 103.16 & 75.34 & 2.98 & 2.12 & -11.6 & 47.76 & 1368.29 & 12.32 \\\\\n\\hline\n2-6 & 114.21 & 231.37 & 2.35 & 3.13 & -41.1 & 72.64 & 2538.67 & 12.43 \\\\\n\\hline\n2-7 & 233.17 & 101.44 & 2.91 & 3.02 & 0.5 & 79.43 & 3552.28  & 8.54 \\\\\n\\hline\n2-8 & 101.13 & 98.60 & 2.80 & 3.51 & 42.9 & 79.17 & 3228.94 & 9.36 \\\\\n\\hline\n2-9 & 231.91 & 127.28 & 3.15 & 2.74 & 5.7 & 56.52 & 2015.41 & 8.71 \\\\\n\\hline\n2-10 & 36.05 & 153.08 & 2.33 & 3.03 & -39.5 & 32.58 & 1162.67  & 15.26 \\\\\n\\hline\n2-11 & 227.54 & 207.51 & 3.36 & 2.98 & -0.8 & 54.97 & 2549.64 & 12.13 \\\\\n\\hline\n2-12 & 152.97 & 209.01 & 3.54 & 3.09 & 35.1 & 95.40 & 4358.75  & 10.36 \\\\\n\\hline\n1-1 & 176.37 & 131.80 & 1.48 & 1.37 & 2.4 & 133.07 & 1653.93 & 5.66 \\\\\n\\hline\n1-2 & 154.00 & 146.00 & 1.01 & 1.01 & 0.0 & 122.96 & 1004.52 & 13.05 \\\\\n\\hline\n1-3 & 13.92 & 145.08 & 1.38 & 1.42 & -9.0 & 299.54 & 3488.15 & 5.54  \\\\\n\\hline\n\\end{tabular}\n\\label{tabdetect}\n\\caption{Detection table.}\n\\end{center}\n\\end{table}\n\n\\begin{figure}[htb]\n\\centerline{\n\\hbox{\n\\psfig{figure=fig_bert_obj.ps,bbllx=2cm,bblly=6cm,bburx=19cm,bbury=23.5cm,height=14cm,width=14cm,clip=}\n}}\n\\caption{Position of each object in the image.}\n\\label{fig_ima_obj}\n\\end{figure}\n\n\\clearpage\n\n", "meta": {"hexsha": "42719a6a3b48ca8728a5d29e6a512b047057863c", "size": 24371, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/doc/doc_mra/doc_mr1/ch_detect.tex", "max_stars_repo_name": "sfarrens/cosmostat", "max_stars_repo_head_hexsha": "a475315cda06dca346095a1e83cb6ad23979acae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/doc/doc_mra/doc_mr1/ch_detect.tex", "max_issues_repo_name": "sfarrens/cosmostat", "max_issues_repo_head_hexsha": "a475315cda06dca346095a1e83cb6ad23979acae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/doc/doc_mra/doc_mr1/ch_detect.tex", "max_forks_repo_name": "sfarrens/cosmostat", "max_forks_repo_head_hexsha": "a475315cda06dca346095a1e83cb6ad23979acae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.1503623188, "max_line_length": 112, "alphanum_fraction": 0.7440400476, "num_tokens": 7068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.3247320526494783}}
{"text": "\\section{Method}\\label{sec:yourmethod}\nWe present our two different approaches to parallelize the algorithm and their major optimizations. Our implementations use MPI (``Message Passing Interface''). We also discuss a vectorization optimization that can be applied to both versions. Our source code and test cases are publicly available \\cite{our_source}.\n\n\n% Now comes the ``beef'' of the report, where you explain what you did. \n% Again, organize it in paragraphs with titles. As in every section\n% you start with a very brief overview of the section.\n% In this section, structure is very important so one can follow the technical content.\n% Mention and cite any external resources that you used including libraries or other code.\n\n\\mypar{Row-wise algorithm}\nThe design of our algorithm is intentionally simple. We divide each row of our pyramid-shaped DP table into evenly spaced contiguous segments and assign exactly one to each worker. As the number of cells in each row is increased by one we increase the size of a segment by one. To ensure a balanced workload we increase each segment size in a round robin fashion.\n\nEach worker calculates the cells in its segment from left to right. But in order to calculate the leftmost element the worker may depend on the rightmost element of the previous row from the left neighboring worker. Thus a worker has to wait for the neighboring worker to complete its segment in the previous row before the worker can start the next row. This can lead to an imbalance. In order to overcome this issue we prioritize the leftmost and rightmost elements and calculate them first and send them right away before calculating any other elements. This ensures that the waiting time is minimal.\n    \nThe number of messages sent in each row is constant in the number of workers (up to two receives and one send per worker) independent of the size of the rows. This means that with a small work size per worker we get a significant communication overhead. We solve this by first increasing the segment of a worker until it reaches a certain threshold before assigning any work to the next worker. In experiments we found that a threshold of $200$ cells works well.\n\nWe can calculate the edit script in a similar fashion as a sequential algorithm would. But due to the quadratic memory consumption we did not benchmark this.\n\n\\mypar{Dynamic priority algorithm}\nIn our row-wise algorithm a worker will not calculate any elements of the next row until it receives all required elements of the previous row. This blocking wait is usually not necessary - it is possible to calculate some elements of the next rows without waiting for other workers. We designed the dynamic priority algorithm to always perform some calculation instead of a blocking wait if possible. Additionally, the algorithm prioritizes calculations that will be sent to other workers, so that they are quickly unblocked.\n\n\\begin{figure}[hbt]\\centering\n  \\includegraphics[width=0.85\\linewidth]{images/dphpc-dynamic-priority-diagram.pdf}\n  \\caption{Visualization of the internal state of the dynamic priority algorithm. The circles are cells in the DP table (colored by worker). There are two workers (red and green). The state is from the perspective of the red worker. The arrows represent (past or future) sends and receives. Every cell on or above the \\emph{frontier} is known to have been calculated by some worker. Every cell on or below the \\emph{limiting line} cannot be calculated by the red worker at the moment.}\n  \\label{priority_state}\n\\end{figure}\n\nIn order to perform calculations whenever possible, it is necessary to determine which calculations are possible in a given state. Figure \\ref{priority_state} shows the internal state that our algorithm keeps for this purpose. Every cell on the solid jagged line (\\emph{frontier}) has been calculated by some worker, and every cell on or below the dotted line (\\emph{limiting line}) can not be calculated at the moment. This means that all cells below the frontier and above the limiting line can be calculated without receiving any further messages from other workers. The frontier and the limiting lines fully determine the currently possible calculations (darker red).\n\nThe shape of the frontier is a direct consequence of the dependencies in our DP table. Before a DP cell can be calculated, the cells above it (left and right) must be calculated (see arrows in figure \\ref{dp_table}). Because of transitivity, this means that all DP cells in the ``upside down pyramid'' ending in a cell must have been calculated before it. The frontier is the boundary of a union of such pyramids. Whenever a worker learns that a cell was calculated (because it calculated the value itself or received it from another worker) it extends its frontier by union with the pyramid ending in that cell.\n\nEvery worker has up to 2 limiting lines at any given time. These diagonal lines go through the next cell that the worker expects to receive. The worker shouldn't calculate any cells on or below a limiting line, since these cells will either be calculated by another worker (e.g. the cell that it expects to receive) or depend on values in such cells.\n\nOnce it is clear which cells are possible to calculate, it is necessary to choose a calculation order. One interesting case is outlined with a red circle in figure \\ref{priority_state}. This cell has not been calculated yet, and another worker expects to receive its value. To prevent other workers from being blocked, such cells (and their dependencies) will be calculated before cells that do not result in a send. If there are no such cells to prioritize, cells near the middle of the DP pyramid are calculated first, since this order results in a frontier with few bends, which makes planning calculations faster.\n\n\\mypar{SIMD Optimization}\nThe amount of work needed per DP cell dynamically depends on the input, since the number of loop iterations in the while-loop is determined by the number of equal elements after a change. Therefore, the workload per worker might be imbalanced. %, especially for inputs with high similarity. \nTo mitigate these imbalances and hence, reduce the time workers are waiting, we use x86's SIMD\\footnote{``Single instruction stream, multiple data streams'' by Flynn's Taxonomy \\cite{flynns_taxonomy}} vector extensions to compare multiple elements at once.\n\nIn many cases we need to compare only one value, because the first value is already unequal. In these cases we would not benefit from using SIMD instructions, they might even be more expensive. Therefore, we have a preliminary scalar check for inequality of the first element. Only if this check fails, we will use SIMD instructions.\n\n%To force the compiler to use SIMD instructions we use the vector intrinsics from the \\texttt{immintrin.h} %TODO: ref needed?) -> Intel intrinsics guide as footnote?\n%header.\n%If there are at least eight elements left in both input sequences, we will use the AVX\\footnote{Advanced Vector Extensions and} instructions which operate on 8-way vectors of 32-bit integers. For the case, in which less than eight elements but at least four are left, we make use of SSE\\footnote{Streaming SIMD Extensions are extensions to the x86 instruction set architecture} instructions once to compare 4-way vectors.\n\nFor the vectorized comparison we first load unaligned 8-way or 4-way vectors from both input sequences (the loads need to be unaligned, since we do not know the position in the vector in advance and we compare the input sequences at different offsets). Then we use a \\texttt{cmpeq} intrinsic to compare the two vectors for equality. The result is then checked for an unequal element by using the negation of the \\texttt{testc} intrinsic. If there is no inequality, the next vector will be checked. Otherwise, the exact location of the inequality is determined by a scalar loop over the last up to eight elements using the same loop as in the original algorithm.", "meta": {"hexsha": "d5a38860a7d36a1d88cb2d2d3f3d22444ed96ad7", "size": 7989, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report_src/sections/03-method.tex", "max_stars_repo_name": "tehwalris/mpi-myers-diff", "max_stars_repo_head_hexsha": "9d6dafc9dc16dcf97b4c712dbb8c6dace25eeee5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-11-09T11:30:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T17:47:49.000Z", "max_issues_repo_path": "report_src/sections/03-method.tex", "max_issues_repo_name": "tehwalris/mpi-myers-diff", "max_issues_repo_head_hexsha": "9d6dafc9dc16dcf97b4c712dbb8c6dace25eeee5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report_src/sections/03-method.tex", "max_forks_repo_name": "tehwalris/mpi-myers-diff", "max_forks_repo_head_hexsha": "9d6dafc9dc16dcf97b4c712dbb8c6dace25eeee5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 169.9787234043, "max_line_length": 671, "alphanum_fraction": 0.8018525473, "num_tokens": 1637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.32473205264947824}}
{"text": "\\documentclass[]{article}\n\\usepackage[margin=1.0in]{geometry}\n\\usepackage{amssymb}\n\n%title material\n\\title{Astronomy 400B Lecture 5: Stellar Orbits}\n\\author{Brant Robertson}\n\\date{February, 2015}\n\n\n%include latex definitions\n\\input{astro400B_definitions.tex}\n\n%begin the document\n\\begin{document}\n\n%make the title, goes after document begins\n\\maketitle\n\n%first section\n\\section{Motion Under Gravity}\n\nNewton's Law of Gravity point mass $M$ attracts another mass $m$ separated by \ndistance $\\vr$, causing a change in momentum $m\\vv$ of:\n\n\\begin{equation}\n\\frac{d}{dt}(m\\vv) = -\\frac{GmM}{r^{3}} \\vr\n\\end{equation}\n\\noindent\nwhere $G$ is Newton's gravitational constant. For an $N$-body system, we have\n\\begin{equation}\n\\frac{d}{dt}(m_{i}\\vv_{i}) = -\\sum_{j\\ne i}\\frac{G m_{i} m_{j}}{|\\vx_i - \\vx_j|^{3}} (\\vx_i - \\vx_j)\n\\end{equation}\n\\noindent\nThis equation can be re-written as\n\\begin{equation}\n\\frac{d}{dt}(m \\vv_i) = - m \\nabla\\Phi(\\vx_i)\n\\end{equation}\n\\noindent\nwhere\n\\begin{equation}\n\\Phi(\\vx_i) = - \\sum_{i\\ne j} \\frac{G m_j}{|\\vx_i - \\vx_j|}\n\\end{equation}\n\\noindent\nis the gravitational potential supplied by the point mass distribution at positions $\\vx_i$.\nNote we have chosen to define the potential such that $\\Phi(x)\\to0$ as $x\\to\\infty$ but\nthis is arbitrary. Note that\n\\begin{equation}\n\\nabla = \\left[\\frac{\\partial}{\\partial x},\\frac{\\partial}{\\partial y},\\frac{\\partial}{\\partial x}\\right]\n\\end{equation}\n\n\\subsection{Continuous Matter Distributions}\nNow consider a continuous distribution of matter density $\\rho(\\vx)$.  The\npotential generated by $\\rho(\\vx)$ is given by\n\\begin{equation}\n\\label{eqn:potential}\n\\Phi(\\vx) = - \\int \\frac{G\\rho(\\vx')}{|\\vx - \\vx'|}d^{3}\\vx'\n\\end{equation}\n\\noindent\nNote that the integral is performed over $\\vx'$.  The force $\\vF$ per unit mass\nis\n\\begin{equation}\n\\vF(\\vx) = - \\nabla \\Phi(\\vx) = - \\int \\frac{G\\rho(\\vx')(\\vx-\\vx')}{|\\vx-\\vx'|^{3}}d^{3}\\vx'\n\\end{equation}\n\n\\subsection{Poisson's Equation}\n\nTake Equation \\ref{eqn:potential} and apply the Laplacian operator \n\\begin{equation}\n\\nabla^{2} \\equiv \\nabla \\cdot \\nabla = \\left[\\frac{\\partial^{2}}{\\partial x^{2}}+\\frac{\\partial^{2}}{\\partial y^{2}}+\\frac{\\partial^{2}}{\\partial z^{2}}\\right]\n\\end{equation}\n\\noindent\nto both sides.  Remembering that the operator acts on $\\vx$ and not $\\vx'$, we have\n\\begin{equation}\n\\label{eqn:pois_init}\n\\nabla^{2} \\Phi(\\vx) = - \\int G \\rho(\\vx') \\nabla^{2} \\left(\\frac{1}{|\\vx-\\vx'|}\\right)d^{3}\\vx'.\n\\end{equation}\n\\noindent\nWe can evaluate this by noting that\n\\begin{equation}\n\\label{eqn:nabla}\n\\nabla\\left(\\frac{1}{|\\vx - \\vx'|}\\right) = -\\frac{\\vx-\\vx'}{|\\vx-\\vx'|^3}, \\nabla^{2}\\left(\\frac{1}{|\\vx - \\vx'|}\\right) = 0.\n\\end{equation}\n\\noindent\nSo we conclude that outside of a very small region around $\\vx$, $\\nabla^{2}\\Phi(\\vx)=0$.\nLet's take a spherical region $S(\\epsilon)$ of radius $\\epsilon$ centered on $\\vx$. In proceeding, let's \nnote that \n\\begin{equation}\n\\nabla^{2} f(|\\vx-\\vx'|) = \\nabla_{\\vx'}^{2} f(|\\vx-\\vx'|)\n\\end{equation}\n\\noindent\nfor any function $f(|\\vx - \\vx'|)$. If we take $\\epsilon$ to be small enough such \nthat $\\rho(\\vx)\\approx$ a constant, then we can write\n\\begin{eqnarray}\n\\label{eqn:pois_med}\n\\nabla^{2}\\Phi(\\vx) &\\approx& - G\\rho(\\vx) \\int_{S(\\epsilon)} \\nabla^2 \\left( \\frac{1}{|\\vx - \\vx'|} \\right)d^{3}\\vx' \\nonumber \\\\\n&=& - G \\rho(\\vx)  \\int_{S(\\epsilon)} \\nabla_{\\vx'}^2 \\left( \\frac{1}{|\\vx - \\vx'|} \\right)d V'.\n\\end{eqnarray}\n\\noindent\nNow we get to use the {\\it divergence} theorem\n\\begin{equation}\n\\int \\nabla^{2} f dV = \\oint \\nabla f \\cdot dS,\n\\end{equation}\n\\noindent\nwhich allows us to write Equation \\ref{eqn:pois_med} as\n\\begin{equation}\n- G \\rho(\\vx)  \\int_{S(\\epsilon)} \\nabla_{\\vx'}^2 \\left( \\frac{1}{|\\vx - \\vx'|} \\right)d V' = - G \\rho(\\vx) \\oint_{S(\\epsilon)} \\nabla_{\\vx'}\\left(\\frac{1}{|\\vx-\\vx'|}\\right) \\cdot d\\vS'\n\\end{equation}\n\\noindent\nBy applying Equation \\ref{eqn:nabla} and the identity $\\nabla_{\\vx'} f = -\\nabla f$, we have\n\\begin{eqnarray}\n- G \\rho(\\vx) \\oint_{S(\\epsilon)} \\nabla_{\\vx'}\\left(\\frac{1}{|\\vx-\\vx'|}\\right) \\cdot d\\vS' &=&\n-G \\rho(\\vx) \\oint_{S(\\epsilon)} \\left(\\frac{\\vx-\\vx'}{|\\vx-\\vx'|^{3}}\\right) \\cdot d\\vS' \\nonumber \\\\\n&=& 4 \\pi G \\rho(\\vx)\n\\end{eqnarray}\n\n\n\\subsection{Inside a Uniform Shell}\n\nThe gravitational force inside a spherical shell of uniform density is zero.  The potential is a\nconstant.\n\n{\\bf See Figure 3.1 of Sparke and Gallagher.}\n\nThe opening angle OA is the same as OB, so the ratio of the enclosed mass is (SA/SB)$^{2}$.  Since\nthe ratio of the forces scale like the inverse of this ratio (from the inverse square law), the\nforce contributions of the A and B patches are equal and opposite.\n\n\\subsection{Gravitational Potential Outside a Uniform Spherical Shell}\n\n{\\bf See Figure 3.2 of Sparke and Gallagher}\n\nWe are calculating the potential a uniform spherical shell of mass $M$ and radius $a$.  \nConsider a point $P$ a distance $r$. The contribution of a narrow cone of opening\nsolid angle $\\Delta\\Omega$ around another point $Q'$ is\n\\begin{equation}\n\\Delta\\Phi[\\vx(P)] = -\\frac{GM}{|\\vx(P) - \\vx(Q')|} \\frac{\\Delta\\Omega}{4\\pi}\n\\end{equation}\n\\noindent\nNow consider the potential $\\Phi'$ at point $P'$ at a radius $a$ away from the\ncenter of a shell of the same mass $M$ but with a radius $r$.\nThe contribution $\\Delta\\Phi'$ from the material in the same cone of solid\nangle $\\Delta\\Omega$ but at point $Q$ a distance $r$ away is\n\\begin{equation}\n\\Delta\\Phi'[\\vx(P')] = - \\frac{GM}{|\\vx(P') - \\vx(Q)|}\\frac{\\Delta\\Omega}{4\\pi}\n\\end{equation}\n\\noindent\nbut since $PQ'=P'Q$, $\\Delta\\Phi[\\vx(P)] = \\Delta\\Phi'[\\vx(P')]$.\nWhen we integrate over $4\\pi$, we have\n\\begin{equation}\n\\Phi[\\vx(P)] = \\Phi'[\\vx(P')]= \\Phi'[\\vx=0] = -\\frac{GM}{r}\n\\end{equation}\n\\noindent\nThe force associated with this spherical shell is just $F(r) = \\nabla \\Phi[\\vx(P)] = -\\frac{GMm}{r}$.\nSo the force outside the shell is the same as for a point mass at distance $r$.\n\nInside a spherical mass distribution $\\rho(r)$, the \ncentripetal acceleration that allows for a circular \norbit must be the radial gravitational force inwards.\nOn a circular orbit, in terms of the circular velocity\n$V$ this acceleration is just\n\\begin{equation}\na = \\frac{V^{2}(r)}{r} = -F(r) = \\frac{GM(<r)}{r^2}.\n\\end{equation}\n\\noindent\nFor a point mass, $V(r)\\propto r^{-1/2}$.  No extended\ndistribution can have a circular velocity curve that\ndeclines more rapidly than $\\propto r^{-1/2}$.\n\nNote that the potential of a distributed mass density $\\rho(\\vx)$\nis not the same as for a point mass.  Instead, we have\n\\begin{equation}\n\\Phi(r) = - \\left[ \\frac{GM(<r)}{r} + 4 \\pi G \\int_{r}^{\\infty} \\rho(r') r' dr'\\right].\n\\end{equation}\n\\noindent\nBut as long as the spherical mass distribution has a finite size, eventually we \nwill have\n\\begin{equation}\n\\Phi(\\vx) \\to - \\frac{G M_{\\mathrm{tot}}}{|\\vx|}\n\\end{equation}\n\\noindent\nat large enough radius.\n\n\n\\subsection{Moving Through a Potential}\n\nIf we are moving through a background potential $\\Phi(\\vx)$ with\nvelocity $\\vx$, the potential we experience changes\nwith time according to $d\\Phi/dt = \\vv\\cdot\\nabla\\Phi(\\vx)$.\nWe can re-write Newton's equation as\n\\begin{equation}\n\\vv \\cdot \\frac{d}{dt} ( m\\vv) + m \\vv\\cdot\\nabla \\Phi(\\vx) = 0 = \\frac{d}{dt}\\left[\\frac{1}{2}m\\vv^{2} + m \\Phi(\\vx)\\right]\n\\end{equation}\n\\noindent\nTherefore, the total energy\n\\begin{equation}\n\\label{eqn:total_energy}\nE \\equiv \\frac{1}{2} m\\vv^{2} + m\\Phi(\\vx) =~\\mathrm{const}\n\\end{equation}\n\\noindent.\nWe can write of course that $E = KE + PE$, where $KE = \\frac{1}{2}m\\vv^{2}$ and $PE = m\\Phi(\\vx)$.\nThe kinetic energy cannot be negative, and we adopt $\\Phi(\\vx)\\to0$ as $\\vx\\to\\infty$.  At position\n$\\vx$, an orbit is unbound only if the total energy $E>0$. The speed at this place in the\norbit must exceed the escape speed, which is found by setting Equation \\ref{eqn:total_energy} to zero.\nWe then have\n\\begin{equation}\nv_{e}^{2} = - 2 \\Phi(\\vx).\n\\end{equation}\n\n\\subsection{Angular Momentum}\n\nThe angular momentum of an orbit is $L = \\vx \\times m\\vv$. The time rate of change is\n\\begin{equation}\n\\frac{dL}{dt} = \\vx \\times \\frac{d}{dt} (m \\vv) = -m\\vx \\times \\nabla \\Phi.\n\\end{equation}\n\\noindent\nFor a spherically symmetric distribution, the force is central and $dL/dt = 0$ (angular\nmomentum is conserved).\nIn an axisymmetric distribution, on the component of $L$ parallel to the symmetry\naxis is conserved.\n\n\\subsection{Individual Energy is Not Conserved in a Time-Dependent Potential}\n\nIn a many-body system, the total energy of each star is not individually conserved.\nThe time derivative of the kinetic energy of star $i$ is\n\\begin{equation}\n\\sum_{i} \\vv_i \\cdot \\frac{d}{dt} (m_i \\vv_i) = \\frac{d}{dt} KE = -\\sum_{i,j;i\\ne j} \\frac{Gm_i m_j}{|\\vx_i - \\vx_j|^{3}}(\\vx_i - \\vx_j) \\cdot \\vv_i\n\\end{equation}\n\\noindent\nDoing the same calculation on star $j$ and taking the dot product with $\\vv_j$ gives\n\\begin{equation}\n\\frac{1}{2}\\sum_{j} \\frac{d}{dt} (m_j \\vv_j \\cdot \\vv_j) = - \\sum_{i,j; i\\ne j}\\frac{Gm_i m_j}{|\\vx_i - \\vx_j|^{3}}(\\vx_j - \\vx_i)\\cdot \\vv_j\n\\end{equation}\n\\noindent\nAdding the RHS of these two equations gives\n\\begin{equation}\n- \\sum_{i,j; i\\ne j}\\frac{Gm_i m_j}{|\\vx_i - \\vx_j|^{3}}(\\vx_i - \\vx_j)\\cdot(\\vv_i - \\vv_j) = \\sum_{i,j;i\\ne j}\\frac{d}{dt}\\left(\\frac{Gm_i m_j}{|\\vx_i - \\vx_j|}\\right).\n\\end{equation}\nThe potential energy $PE$ is a sum of pairs of potentials from individual objects\n\\begin{equation}\nPE = -\\frac{1}{2} \\sum_{i,j;i\\ne j}\\frac{Gm_i m_j}{|\\vx_i - \\vx_j|} = \\frac{1}{2} \\sum_i m_i \\Phi(\\vx_i) = \\frac{1}{2} \\int \\rho(\\vx)\\Phi(\\vx)dV.\n\\end{equation}\n\\noindent\nWe divided by two so every object contributes only once.\n\nWe can now see that, for the whole collection of objects \n\\begin{equation}\n2 \\frac{d}{dt} \\left[ KE - \\frac{1}{2} \\sum_{i,j;i\\ne j} \\frac{G m_i m_j}{|\\vx_i - \\vx_j|}\\right] = 0.\n\\end{equation}\n\\noindent\nThis means the total energy of the system is conserved.\n\n\\subsection{External Forces}\n\nConsider the total force on an object $i$ in \na many body system under the influence of an external force $\\vF_{\\mathrm{ext}}$.\n\\begin{equation}\n\\sum_i \\frac{d}{dt} (m_i \\vv_i) \\cdot \\vx_i = -\\sum_{i,j; i\\ne j} \\frac{Gm_i m_j}{|\\vx_i - \\vx_j|^{3}} (\\vx_i - \\vx_j) \\cdot \\vx_i + \\sum_i \\vF_{\\mathrm{ext}}^{i} \\cdot \\vx_i.\n\\end{equation}\n\\noindent\nThe force on the $j$th object is\n\\begin{equation}\n\\sum_j \\frac{d}{dt} (m_j \\vv_j) \\cdot \\vx_j = - \\sum_{i,j;i\\ne j }\\frac{G m_i m_j}{|\\vx_i - \\vx_j|^{3}}(\\vx_j - \\vx_i)\\cdot\\vx_j + \\sum_j \\vF_{\\mathrm{ext}}^{j} \\cdot \\vx_j\n\\end{equation}\n\\noindent\nThe left hand sides of these equations are equal, and are equal to\n\\begin{equation}\n\\frac{1}{2} \\sum_i \\frac{d^2}{dt^2}(m_i\\vx_i \\cdot \\vx_i) - \\sum_i m_i \\vv_i \\cdot \\vv_i = \\frac{1}{2} \\frac{d^2I}{dt^2} -2 KE\n\\end{equation}\n\\noindent\nwhere the moment of inertia $I$ is\n\\begin{equation}\nI \\equiv \\sum_i m_i \\vx_i \\cdot \\vx_i.\n\\end{equation}\n\\noindent\nBy averaging the force on $i$ and $j$, we find\n\\begin{equation}\n\\frac{1}{2} \\frac{d^2 I}{dt^2} - 2 KE = PE + \\sum_i \\vF_{\\mathrm{ext}}^{i} \\cdot \\vx_i\n\\end{equation}\n\\noindent\nand averaging this over a short time interval $0<t<\\tau$ gives\n\\begin{equation}\n\\frac{1}{2\\tau}\\left[ \\frac{dI}{dt}(\\tau) - \\frac{dI}{dt}(0)\\right] = 2 \\ave{KE} + \\ave{PE} + \\sum_i \\ave{\\vF_{\\mathrm{ext}}^{i} \\cdot \\vx_i}\n\\end{equation}\n\\noindent\nIf all objects in the system are bound, then $|\\vx_i \\cdot \\vv_i|$ and $dI/dt$ will be finite.  As $\\tau\\to\\infty$, the LHS goes to zero.  Then we have\n\\begin{equation}\n2\\ave{KE} + \\ave{PE} + \\sum_i \\ave{\\vF_{\\mathrm{ext}}^{i} \\cdot \\vx_i} = 0\n\\end{equation}\n\n\\section{Two-Body Relaxation}\n\nA potential can be thought of as a combination of a smooth and steep potential wells.\nWe can calculate the average time between strong encounters with the steep\npotential wells supplied near individual stars. Suppose that the\nstars have mass $m$ and typical velocities $V$. If two stars come\nwithin $r$ of one another, their kinetic energies increase to balance the\nchange in potential energy.  We say there is a {\\it strong encounter}\nif the change in potential energy is comparable to their starting\nkinetic energy.  In other words\n\\begin{equation}\n\\frac{Gm^{2}}{r} \\gtrsim \\frac{mV^{2}}{2}\n\\end{equation}\n\\noindent\nand the radius must be smaller than\n\\begin{equation}\nr \\lesssim r_{s} \\equiv \\frac{2Gm}{V^2}.\n\\end{equation}\n\\noindent\nIn the solar neighborhood, $V\\approx30~\\km~s^{-1}$, and taking $m\\sim0.5\\Msun$ we have $r_s \\approx 1~$AU.\nFor the Sun, there has been no strong encounter for $\\sim4.5~\\Gyr$. Over a time $t$, the Sun\nhas an encounter with all stars in a cylinder with volume $\\pi r_s^2 V t$. If there is a number\ndensity of $n$, then we are interested in the time when $n\\pi r_s^2 V t = 1$.  This time is\n\\begin{equation}\nt_s = \\frac{V^3}{4\\pi G^2 m^3 n} \\approx 4 \\times 10^{12}~\\yr~\\left(\\frac{V}{10~\\km~s^{-1}}\\right)^3\\left(\\frac{m}{\\Msun}\\right)^{-2}\\left(\\frac{n}{1~\\pc^{-3}}\\right)^{-1}.\n\\end{equation}\n\\noindent\nFor $n\\approx0.1~\\pc^{-3}$, then $t_s\\sim10^{15}~\\yr$.\n\n\n\\subsection{Weak Encounters}\n\nInstead of strong encounters, we need to calculate the effects of weaker encounters\non indivudal stars.  We do this via the impulse approximation, that tells us how to\napproximate the change in velocity from a weak encounter.  As one object passes\nanother, the perpendicular force between them is\n\\begin{equation}\n\\vF_{\\perp} = \\frac{GmMb}{(b^2 + V^2t^2)^{3/2}} = M \\frac{dV_{\\perp}}{dt}.\n\\end{equation}\n\\noindent\nIntegrating over time, we find that\n\\begin{equation}\n\\Delta V_{\\perp} = \\frac{1}{M} \\int_{-\\infty}^{\\infty} \\vF_{\\perp}(t) dt =\\frac{2 G m}{bV}.\n\\end{equation}\nSlower approaches result in larger perpendicular velocity changes. The\npath of $M$ is bent via\n\\begin{equation}\n\\alpha = \\frac{\\Delta V_{\\perp}}{V} = \\frac{2Gm}{bV^2}.\n\\end{equation}\n\\noindent\nA weak encounter requires $b$ to be larger than $r_s$.\n\nThe number of stars with mass $m$ passing $M$ with\nseparations between $b$ and $b+\\Delta b$ is the product of\nthe number density $n$ and the volume $V t \\cdot 2 \\pi b\\Delta b$.\nWe multiply by $\\Delta V_{\\perp}^{2}$ and integrate over $b$ to find\n\\begin{equation}\n\\ave{\\Delta V_{\\perp}^{2}} = \\int_{b_{min}}^{b_{max}} n V t\\left(\\frac{2Gm}{bV}\\right)^2 2 \\pi b db = \\frac{8 \\pi G^2 m^2 nt}{V} \\ln \\left(\\frac{b_{max}}{b_{min}}\\right).\n\\end{equation}\n\\noindent\nAfter a time $t_{\\mathrm{relax}}$ such that $\\ave{\\Delta V_{\\perp}^2} = V^2$, the expected perpendicular \nvelocity becomes about equal to its original forward speed.  The initial path is forgotten!\nDefining $\\Lambda\\equiv (b_{max}/b_{min})$, we find the relaxation time is much shorter than\nthe strong interaction time as\n\\begin{equation}\nt_{\\mathrm{relax}} = \\frac{V^3}{8\\pi G^2 m^2 n \\ln \\Lambda} = \\frac{t_s}{2 \\ln \\Lambda}\n\\end{equation}\n\\begin{equation}\nt_{\\mathrm{relax}} \\approx \\frac{2\\times10^9~\\yr}{\\ln \\Lambda}\\left(\\frac{V}{10~\\km~s^{-1}}\\right)^3\\left(\\frac{m}{\\Msun}\\right)^{-2}\\left(\\frac{n}{10~\\pc^{-3}}\\right)^{-1}.\n\\end{equation}\n\\noindent\nSo what is $\\Lambda$?  Well, if $b<r_s$ the method can't be correct and we usually take $b_{min} = r_s$.  We\ncan then take $b_{max}$ to be the size of the whole system.  For the Sun, $r_s = 1$~AU.  If we \ntake $300~\\pc \\leq b_{max} \\leq 30~\\kpc$, then $\\Lambda\\approx18-22$.  So the exact value of\n$\\Lambda$ doesn't matter, as $t_{\\mathrm{relax}}\\approx10^{13}~\\yr$.\n\nIn a cluster consisting of $N$ stars with mass $m$ and typical $V$, the average separation is about\nhalf the size of the system $R$.  We have\n\\begin{equation}\n\\frac{1}{2}NmV^2 \\sim \\frac{G(Nm)^2}{2R},~\\Lambda = \\frac{R}{r_s} \\sim \\frac{GmN}{V^2} \\cdot \\frac{V^2}{2Gm}\\sim\\frac{N}{2}.\n\\end{equation}\nThe crossing time of the system is $t_{cross} \\sim R/V$.  Since $N=4n\\pi R^3 /3$, we have\n\\begin{equation}\n\\frac{t_{relax}}{t_{cross}} \\sim \\frac{V^4 R^2}{6 N G^2 m^2 \\ln \\Lambda} \\sim \\frac{N}{6 \\ln (N/2)}.\n\\end{equation}\n\\noindent\nFor $N\\sim10^{11}$ stars, the relaxation will take $10^9$ crossing times.  For globulars with $10^6$ stars,\nthe relaxation time for the whole system is $t_{\\mathrm{relax}} \\sim 10^4 t_{cross}$.\n\n\\subsection{Effects of Two-Body Relaxation}\n\nConsider a cluster of stars, each with mass $m$.\nThe {\\it Maxwellian} distribution gives the fraction $f$ of stars with \nvelocities between $v$ and $v+\\Delta v$ as\n\\begin{equation}\n4\\pi f_M(E) v^{2} \\Delta v \n\\end{equation}\n\\noindent\nwhere\n\\begin{equation}\nf_M(E)\\propto \\exp\\left(-\\frac{E}{kT} \\right) = \\exp \\left\\{ -\\left[ m\\Phi(\\vx) + \\frac{mv^{2}}{2} \\right]\n \\Big/ kT \\right\\}.\n\\end{equation}\nThe temperature is related to the average kinetic energy as\n\\begin{equation}\n\\frac{1}{2}m\\ave{\\vv^{2}(\\vx)} = \\frac{3}{2}kT.\n\\end{equation}\n\\noindent\nBut there are stars at large energies, and these will evaporate. The kinetic\nenergy of stars that escape will typically be\n\\begin{equation}\n\\left\\langle \\frac{1}{2} m v_2^2(\\vx) \\right\\rangle = - \\frac{1}{N} \\sum_i m_i \\Phi(\\vx_i) = -\\frac{2}{N} PE = \\frac{4}{N} KE = 6 kT\n\\end{equation}\nThe fraction of stars that escape will be\n\\begin{equation}\n\\int_{\\sqrt{12kT/m}}^{\\infty} f(E) v^2 dv \\Big/ \\int_0^{\\infty} f(E) v^2 dv = 0.0074 \\approx \\frac{1}{136}\n\\end{equation}\n\\noindent\nThe evaporation time will be $t_{evap} \\sim 136 t_{relax}$.  For globulars this is longer than\nthe age of the universe, but for open clusters it is a few gigayears.\n\n\\section{Orbits of Disk Stars and Epicycles}\n\nNow we will treat orbits in axisymmetric potentials, and we will use cylindrical polar\ncoordinates $(R,\\phi,z)$. In an axisymmetric potential, $\\partial\\Phi/\\partial\\phi = 0$, and\nangular momentum about the $z$-axis is conserved.  We adopt $l_z$ at the angular\nmomentum per unit mass, we can write\n\\begin{equation}\n\\frac{d}{dt}(R^2 \\dot{\\phi}) = 0;~l_z \\equiv R^2 \\dot{\\phi} =~\\mathrm{constant}.\n\\end{equation}\n\\noindent\nThe radial equation of motion is\n\\begin{equation}\n\\label{eqn:radial_motion}\n\\ddot{R} = R \\dot{\\phi}^2 - \\frac{\\partial \\Phi}{\\partial R} = - \\frac{\\partial \\Phi_{\\mathrm{eff}}}{\\partial R}\n\\end{equation}\n\\noindent\n\\begin{equation}\n\\Phieff \\equiv \\Phi(R,z) + \\frac{l_z^2}{2R^2}.\n\\end{equation}\nMultiplying \\ref{eqn:radial_motion} by $\\dot{R}$ and integrating informs us that\nfor a star in the midplane $z=0$\n\\begin{equation}\n\\frac{1}{2}\\dot{R}^2 + \\Phieff(R,z=0;l_z) = ~\\mathrm{constant}.\n\\end{equation}\n\\noindent\nIf $l_z\\ne0$, then there is an angular momentum barrier at the center of the galaxy that\nlimits $R$ to some minimum value.\n\nThe vertical equation of motion is\n\\begin{equation}\n\\ddot{z} = -\\frac{\\partial \\Phi}{\\partial z} (R,z) = -\\frac{\\partial \\Phieff}{\\partial z} (R,z)\n\\end{equation}\n\\noindent\nIf the potential is an even function about $z=0$ there is no vertical force in the midplane.\n\nLet's expand the potential about the average radius $R_g$ of a star in a Taylor series and\ntruncate at the first term\n\\begin{equation}\n\\ddot{z} = -z \\left[ \\frac{\\partial^2 \\Phi}{\\partial z^2}(R_g, z)\\right]_{z=0} \\equiv - \\nu^2(R_g) z\n\\end{equation}\n\\noindent\nwhere $\\nu$ is an angular frequency.  The solution to this equation is\na harmonic oscillator\n\\begin{equation}\nz(t) = Z \\cos (\\nu t + \\theta)\n\\end{equation}\n\\noindent\nwhere $Z$ and $\\theta$ are constants.\n\nCircular orbits with $\\dot{R} = 0$ are only possible at a radius $R_g$ where $\\Phieff =~\\mathrm{constant}$.\nAt this radius\n\\begin{equation}\n\\frac{\\partial \\Phi}{\\partial R}(R_g,z=0) = \\frac{l_z^2}{R_g^3} = R_g \\Omega^{2}(R_g)\n\\end{equation}\n\\noindent\nwhere $\\Omega(R)$ is the angular speed of a circular orbit in the disk plane.  If $\\Phieff$ has a\nminimum at $R_g$, then the circular orbit will have the lowest $l_z$.  Any larger $l_z$\nwill oscillate about the circular orbit, in an {\\it epicycle} about a point that\nmoves with $\\Omega(R_g)$ in a circular orbit of radius $R_g$.\n\nLet's set $R = R_g+x$ in Equation \\ref{eqn:radial_motion}, assume that $x\\ll R$, and expand to\nfirst order in $x/R$ and $z/R$.  We find that\n\\begin{equation}\n\\ddot{x} \\approx - x\\left[\\frac{\\partial^2 \\Phieff}{\\partial R^2}\\right]_{R_g}\\equiv - \\kappa^2(R_g)x\n\\end{equation}\n\\noindent\nand\n\\begin{equation}\nx(t) \\approx X \\cos(\\kappa t + \\psi).\n\\end{equation}\n\\noindent\nThe constant $\\kappa$ is called the epicyclic frequency when $\\kappa^2>0$.  If $\\kappa^2<0$,\nthe orbit is unstable.\n\nRecalling that in a circular orbit\n\\begin{equation}\nR \\Omega^2(R) = \\frac{\\partial \\Phi(R,z=0)}{\\partial R}\n\\end{equation}\n\\noindent\nwe can write\n\\begin{equation}\n\\kappa^2(R) = \\frac{d}{dR}[R\\Omega^2(R)] + \\frac{3 l_z^2}{R^4} = \\frac{1}{R^3}\\frac{d}{dR}[(R^2\\Omega)^2] = -4B\\Omega\n\\end{equation}\n\\noindent\nwhere $B$ is Oort's constant.  In the solar neighborhood $B<0$ and $\\kappa^2$ is positive and the Solar\norbit is stable.  If $R^2\\Omega(R)$, the angular momentum of a circular orbit, increases with $R$ then\nall larger circular orbits are stable.  Near a black hole this isn't the case, and the inner\nmost circular orbit is at $R=6GM/c^2$.\n\n\\subsection{Azimuthal Motion in Epicycles}\n\nSince $R$ changes in an epicyclical orbit, the azimuthal velocity must change to\ncompensate to keep $l_z$ constant.  This means that\n\\begin{equation}\n\\dot(\\phi) = \\frac{l_z}{R^2} = \\frac{\\Omega(R_g)R_g^2}{(R_g + x)^2} \\approx \\Omega(R_g)\\left(1 - \\frac{2x}{R_g}\\right).\n\\end{equation}\n\\noindent\nWe can integrate this equation to find that the azimuthal position with time varies as\n\\begin{equation}\n\\phi(t) = \\phi_0  + \\Omega(R_g)t - \\frac{1}{R_g}\\frac{2\\Omega}{\\kappa}X \\sin(\\kappa t + \\psi)\n\\end{equation}\n\\noindent\nThe first two terms are circular motion starting from $\\phi_0$ with constant angular\nfrequency $\\Omega(R_g)$.  The third term is a harmonic oscillation with the same\nfrequency $\\kappa$ as the $x$ motion but $\\pi/2$ out of phase, and\nlarger by a factor $2\\Omega/\\kappa$.\nThe motion is also retrograde!\n\n\\subsection{$\\kappa$ vs. $\\Omega$}\n\nFor a point mass $\\kappa = \\Omega$.  For a uniform sphere $\\kappa = 2\\Omega$.\nThe galaxy has $\\Omega < \\kappa < 2\\Omega$, and near the sun $\\kappa \\approx 1.4 \\Omega$.\n\n\\subsection{Relative Speed of Nearby Stars}\n\nThe relative speeds of stars with $R_g > R_0$ are\n\\begin{equation}\nv_y = R_0[\\dot{\\phi} - \\Omega(R_0)]\\approx R_0 \\left[ \\Omega(R_g) - 2x \\frac{\\Omega(R_g)}{R_g} - \\Omega(R_0)\\right]\n\\end{equation}\n\\noindent\nbut since $R_0 = R_g + x$ and dropping terms in $x^2$ we have\n\\begin{equation}\nv_y \\approx -x\\left[ 2\\Omega(R_0) + R_0\\left(\\frac{d\\Omega}{dR}\\right)_{R_0}\\right] = -\\frac{\\kappa^2 x}{2\\Omega} = 2Bx\n\\end{equation}\n\\noindent\nTaking the average of stars we can measure, we find\n\\begin{equation}\n\\ave{v_y^2} = \\left(\\frac{\\kappa^2}{2\\Omega}\\right)^2\\ave{x^2} = \\frac{\\kappa^2}{4\\Omega^2}\\ave{v_x^2}\n\\end{equation}\n\\noindent\nand since $\\kappa<2\\Omega$, $\\ave{v_y^2}<\\ave{v_x^2}$.  For the thin disk, we find that $2\\lesssim\\ave{v_x^2}/\\ave{v_y^2}\\lesssim3$.\n\n\\end{document}\n", "meta": {"hexsha": "40773b9e88209c2e3bd03b828cb313f7616ba7f9", "size": 22709, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "astro400B_lecture_5.tex", "max_stars_repo_name": "brantr/astro400B", "max_stars_repo_head_hexsha": "95cd675c23b9c44242f428516ed3e0fca54d3b4f", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-05-03T23:30:58.000Z", "max_stars_repo_stars_event_max_datetime": "2015-05-03T23:30:58.000Z", "max_issues_repo_path": "astro400B_lecture_5.tex", "max_issues_repo_name": "brantr/astro400B", "max_issues_repo_head_hexsha": "95cd675c23b9c44242f428516ed3e0fca54d3b4f", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "astro400B_lecture_5.tex", "max_forks_repo_name": "brantr/astro400B", "max_forks_repo_head_hexsha": "95cd675c23b9c44242f428516ed3e0fca54d3b4f", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.6678899083, "max_line_length": 186, "alphanum_fraction": 0.6862917786, "num_tokens": 8174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3247320443237449}}
{"text": "\\subsection{Demand Forecasting with Classical Forecasting Methods}\n\\label{class_methods}\n\nForecasting became a formal discipline starting in the 1950s and has its\n    origins in the broader field of statistics.\n\\cite{hyndman2018} provide a thorough overview of the concepts and methods\n    established, and \\cite{ord2017} indicate business-related applications\n    such as demand forecasting.\nThese \"classical\" forecasting methods share the characteristic that they are\n    trained over the entire $Y$ first.\nThen, for prediction, the forecaster specifies the number of time steps for\n    which he wants to generate forecasts.\nThat is different for ML models.\n", "meta": {"hexsha": "e2961605de9d2654aa59dfdeb9c08620de9cb432", "size": 660, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/2_lit/2_class/1_intro.tex", "max_stars_repo_name": "webartifex/urban-meal-delivery-paper-demand-forecasting", "max_stars_repo_head_hexsha": "9ee3396a24ce20c9886b4cde5cfe2665fd5a8102", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-25T19:40:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T19:40:56.000Z", "max_issues_repo_path": "tex/2_lit/2_class/1_intro.tex", "max_issues_repo_name": "webartifex/urban-meal-delivery-demand-forecasting", "max_issues_repo_head_hexsha": "9ee3396a24ce20c9886b4cde5cfe2665fd5a8102", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/2_lit/2_class/1_intro.tex", "max_forks_repo_name": "webartifex/urban-meal-delivery-demand-forecasting", "max_forks_repo_head_hexsha": "9ee3396a24ce20c9886b4cde5cfe2665fd5a8102", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.1428571429, "max_line_length": 76, "alphanum_fraction": 0.8, "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3247320359980114}}
{"text": "\\documentclass[10pt]{article}\n\\usepackage[a4paper, margin=1in]{geometry}\n\\usepackage{hyperref}\n\\usepackage{setspace}\n\\usepackage[style=iso]{datetime2}\n\\usepackage{amsmath}\n\\usepackage{eufrak}\n\\usepackage{amssymb}\n\\usepackage{mathtools}\n\n\\newcommand{\\defeq}{\\vcentcolon=}\n\n\\title{Automatic Differentiation Variational Inference \\\\ Mean Field Simplification and Constraint Scalar}\n\\author{Harshad Deo \\\\ \n  \\href{mailto:harshad@moreficent.com}{harshad@moreficent.com} \\\\ \n  \\href{mailto:harshad@simianquant.com}{harshad@simianquant.com}\n}\n\\date{}\n\n\\setlength{\\parindent}{0cm}\n\n\\hypersetup{\n  colorlinks,\n  citecolor=blue,\n  filecolor=blue,\n  linkcolor=blue,\n  urlcolor=blue\n}\n  \n\\setlength{\\parskip}{\\baselineskip}%\n  \n\\begin{document}\n  \n\\maketitle\n\nThis monograph is a follow up to the article introducing Auto Differentiation Variational Inference and develops simplifying\nassumptions that allow the technique to be used to train large, complex models over large datasets, for example for Bayesian \nDeep Learning.\n\n\\section*{Decoupling The Latent Space}\n\nThe full rank approximation, developed in the previous monograph, allows all the latent variables ($\\theta$) to be coupled\nwith each other through the correlation matrix of the variational approximation. As a result, the number of parameters\ngrows quadratically with the size of the latent space. This makes it intractable for \nuse in all but the simplest problems, say with a few thousand latent variables. \n\nThe mean field approximation assumes that all the latent variables are independent. This makes it practical to scale the \nmodels, as the number of parameters grows linearly with the size of the latent space. Formally,\n\n\\begin{align*}\n  q(\\zeta, \\phi) \\defeq& \\mathcal{N}\\big(\\zeta; \\mu, \\text{diag}(\\exp(\\omega) ^2)\\big) \\\\\n  =& \\prod_{k=1}^K \\mathcal{N}(\\zeta_k; \\mu_k, \\exp(\\omega_k)^2)\n\\end{align*}\n\nWith this parameterization, the space of the variational parameters is given by:\n\n\\begin{equation*}\n  \\Phi = \\{\\mu_1, \\ldots, \\mu_k, \\omega_1, \\ldots, \\omega_k\\} = \\mathbb{R}^{2K}\n\\end{equation*}\n\nAnd the elliptical standardization is given by:\n\n\\begin{equation*}\n  \\eta_k = S_{\\phi}(\\zeta) = \\frac{\\zeta_k - \\mu_k}{\\exp \\omega_k}\n\\end{equation*}\n\nCorrelation between the latent variables, if required, now needs to be modelled in explicitly as a function of the \nlatent variables. For example, the Lewandowski-Kurowicka-Joe transform \\footnote{Lewandowski, D., Kurowicka, D., \\& Joe, H. (2009). Generating random correlation matrices based on vines and extended onion method. Journal of multivariate analysis, 100(9), 1989-2001.} \ncan be used to explicitly model a correlation matrix for a subset of the latent variables. This transformation, as well as several \nother useful ones, ship with the library. \n\n\\section*{Entropy Simplification}\n\nThe contribution of the entropy of the variational approximation to the ELBO can be simplified as:\n\n\\begin{align*}\n  \\frac{1}{2}\\ln| \\det \\Sigma ^ 2| &= \\frac{1}{2}\\ln |\\det \\big(\\text{diag}(\\exp(\\omega) ^ 2)\\big)|  \\\\\n  &= \\frac{1}{2}\\ln \\prod_{k=1}^{K}\\big(\\exp(\\omega_k)^2\\big) \\\\\n  &= \\ln \\prod_{k=1}^{K}\\exp \\omega_k \\\\\n  &= \\sum_{k=1}^{K}\\omega_k\n\\end{align*}\n\nTherefore the optimization objective can be simplified to:\n\n\\begin{equation*}\n  \\phi^* = \\underset{\\phi}{\\text{argmax}} \\, \\mathbb{E}_{\\mathcal{N}(\\eta; 0, 1)}\\big[\\log p(x, T^{-1}(S_\\phi^{-1}(\\eta))) + \\log |\\det J_{T^{-1}}(S_\\phi^{-1}(\\eta))|\\big] + \\sum_{k=1}^{K}\\omega_k\n\\end{equation*}\n\n\\section*{Joint Probability Simplification}\n\nThe joint probability of the data and the parameters, $p\\big(x, T^{-1}(S_\\phi^{-1}(\\eta))\\big)$ can be factorized as the product \nof the probability of the data given the parameters, and the prior probability of the parameters. The objective can thus be \nreexpressed as:\n\n\\begin{equation*}\n  \\phi^* = \\underset{\\phi}{\\text{argmax}} \\, \\mathbb{E}_{\\mathcal{N}(\\eta; 0, 1)}\\big[\\log p(x | T^{-1}(S_\\phi^{-1}(\\eta))) + \\log p(T^{-1}(S_\\phi^{-1}(\\eta))) + \\log |\\det J_{T^{-1}}(S_\\phi^{-1}(\\eta))|\\big] + \\sum_{k=1}^{K}\\omega_k\n\\end{equation*}\n\n\nIt is observed that the prior probability acts as a regularizing term on the distribution of the latent space. This gives \na clear and simple interpretation to standard regularization techniques like $L_1$ and $L_2$ regularization as being equivalent to \nassigning Laplace and Gaussian priors respectively, with some fixed scale parameters. \n\n\\section*{Graph Simplification}\n\nTo simplify the expression further, the computational graph is assumed to be directed and acyclic, and the family of \nconstraint relaxation functions, $T(\\theta)$, is restricted to that for which the Jacobian of the inverse transform is \na triangular matrix. In practice, this is a benign assumption as it is true for practically all models and all commonly used \ntransformations. Since the Jacobian of a triangular matrix is the product of its diagonal elements, \nthe computational graph can be factorized into mutually exclusive subgraphs $U_1 \\ldots U_M, M \\leq K$ such that \n$U_m, 1 < m \\leq M$ is only dependent on $U_1 \\ldots U_{m - 1}$. Let\n\n\\begin{align*}\n  K_m \\defeq&\\quad \\text{Indices of the latent space for the m-th subgraph} \\\\\n  \\tau_m \\defeq&\\quad \\text{The contribution of the m-th subgraph to the jacobian of the inverse constraint transform} \\\\\n  z_m \\defeq&\\quad \\text{The sampled outputs of the m-th subgraph, implicitly being functions of $\\phi$} \\\\\n  \\rho_m \\defeq&\\quad \\text{The averaged log prior probability of the m-th subgraph} \\\\\n  \\mathcal{P}(\\cdot) \\defeq&\\quad \\text{The averaged log probability of the arguments}\n\\end{align*}\n\n$\\tau_m$ is equal to the sum of the diagonal elements in rows $K_m$ of the jacobian of the inverse constraint transform matrix. The optimization \nobjective can be reexpressed as:\n\n\\begin{equation*}\n  \\phi^* = \\underset{\\phi}{\\text{argmax}} \\, \\mathcal{P}(x | z_M) + \\sum_{m=1}^{M}\\Big(\\rho_m(z_1, \\ldots, z_m ) + \\tau_m + \\sum_{j \\in K_m}\\omega_j \\Big)\n\\end{equation*}\n\nThe first term can be interpreted as the log probability of the output given the input and the model. Each of the summands of the\nsecond term can be interpreted as a \\textit{constraint scalar} that ensures that the latent variables for the subgraph satisfy their \ndomain constraint and are regularized by their priors. Let $\\mathcal{C}_m$ denote the constraint scalar for subgraph $m$. The optimization\nobjective can be reexpressed as:\n\n\\begin{equation*}\n  \\phi^* = \\underset{\\phi}{\\text{argmax}} \\, \\mathcal{P}(x | z_M) + \\sum_{m=1}^{M}\\mathcal{C}_m(z_1, \\ldots, z_m )\n\\end{equation*}\n\nThis can be interpreted by analogy with the architecture of modern deep learning libraries, like TensorFlow and PyTorch:\n\n\\begin{enumerate}\n  \\item $P$ is equivalent to the cost function. For example, if the output is normally distributed with a fixed variance, the optimization objective is mathematically identical to a Mean Square Error loss.\n  \\item Instead of a single tensor, each subgraph outputs a tuple. The first is a sample tensor of the output and the second is a scalar constraint term. \n  \\item All of the constraint scalars are summed and added to the loss given by the cost function.\n\\end{enumerate}\n\nThese parallels motivate the abstractions of the library. \n\n\\end{document}\n", "meta": {"hexsha": "8fb39f9132b4b84ef4a670dda262bf110c7a63a1", "size": 7245, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "theory/meanfieldsimpl.tex", "max_stars_repo_name": "Moreficent/xvi", "max_stars_repo_head_hexsha": "fb9d4cf15638104480a4f1666d77644fe7ecc760", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "theory/meanfieldsimpl.tex", "max_issues_repo_name": "Moreficent/xvi", "max_issues_repo_head_hexsha": "fb9d4cf15638104480a4f1666d77644fe7ecc760", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "theory/meanfieldsimpl.tex", "max_forks_repo_name": "Moreficent/xvi", "max_forks_repo_head_hexsha": "fb9d4cf15638104480a4f1666d77644fe7ecc760", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.9527027027, "max_line_length": 267, "alphanum_fraction": 0.7378881988, "num_tokens": 2110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.32472433357722963}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% \\input{./Ressources/Presentation/Preamble4to3.tex} % Layout 4:3\n\\input{./Ressources/Presentation/Preamble16to9.tex} % Layout 16:9\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\input{./_Config.tex}                    \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\newcommand{\\Rplus}{\\protect\\hspace{-.1em}\\protect\\raisebox{.35ex}{\\smaller{\\smaller\\textbf{+}}}}\n\\newcommand{\\Cpp}{\\mbox{C\\Rplus\\Rplus}\\xspace}\n\\newcommand{\\CppTw}{\\mbox{C\\Rplus\\Rplus 20}\\xspace}\n\n\\newcommand{\\Datum}{\\today}\n\n\\renewcommand{\\PraesentationFusszeileZusatz}{| Amortized Time Complexity of Union-Find in Isabelle/HOL}\n\n\\title{Amortized Time Complexity of Union-Find in Isabelle/HOL \\newline \\newline {\\Large Colloquium to the Bachelor's Thesis \\newline}}\n\\author{\\PersonTitel{} \\PersonVorname{} \\PersonNachname}\n\\institute[]{\\UniversitaetName \\\\ \\FakultaetName \\\\ \\LehrstuhlName {\\newline}\nSupervisor: Prof. Tobias Nipkow, Ph.D. {\\newline} Advisor: Maximilian P.L. Haslbeck, M.Sc.}\n\\date[\\Datum]{\\PersonStadt, October 16, 2019}\n\\subject{Amortized Time Complexity of Union-Find in Isabelle/HOL}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\input{./Ressources/Presentation/Beginning.tex} \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% FOLIENSTIL: Standard\n% !!!ÄNDERUNG HIER:!!!\n\\PraesentationMasterStandard\n%\\PraesentationMasterKopfzeileDreizeiler\n%\\PraesentationMasterWeissBlau\n\n%\\PraesentationStartseiteFlaggen\n\\PraesentationStartseiteUhrenturm\n\\PraesentationTitelseite % Fügt die Startseite ein\n\n\\begin{frame}\n\t\\frametitle{Overview}\n\t\\vspace{1cm}\n\t\\begin{minipage}[s]{\\textwidth}\n\t\\tableofcontents\n\t\\end{minipage}\n\\end{frame}\n\n\\section{Union-Find}\n\\begin{frame}\n\\frametitle{Union-Find}\n\\begin{itemize}\n\t\\item Models a partial equivalence relation\nover a finite domain\n\t\\item Implemented by disjoint set forests\n\\item The graph structure is represented by an array\n\t\\item Supports \\textbf{Union} and \\textbf{Find} operations\n\\end{itemize}\n\\vspace{-2cm}\n\\begin{figure}\n\t\\centering\n\t\\begin{minipage}{5cm}\n\t\t\\caption{Two equivalence classes}\\end{minipage}\n\t\\begin{minipage}{8cm}\\includegraphics[scale=1.0]{UnionFindFigure}\\end{minipage}\n\\end{figure}\n\\end{frame}\n\n\\subsection{Path Compression and Union by Rank}\n\\begin{frame}\n\\frametitle{Path Compression and Union by Rank}\n\\begin{itemize}\n\t\\item As with many tree-based data structures, trees should be kept flat\n\t\\item This is done in two ways: \n\t\\begin{enumerate}\n\t\t\\item \\textbf{Path Compression}\n\t\t\\item \\textbf{Union by Rank}\n\t\\end{enumerate}\n\\end{itemize}\t\n\\begin{figure}\n\t\\centering\n\t\\begin{minipage}{5cm}\n\t\t\\caption{Illustration of Path Compression}\\end{minipage}\n\t\\begin{minipage}{8cm}\\includegraphics[scale=0.8]{PathCompressionFigure}\\end{minipage}\n\\end{figure}\n\\end{frame}\n\n\\subsection{Design Choices}\n\\begin{frame}\n\t\\frametitle{Design Choices}\n\t\\begin{itemize}\n\t\t\\item Done in Imperative/HOL, which can then be exported to several languages\n\t\t\\item The arrays used and therefore the domain are static\n\t\t\\item We define the operations in Imperative/HOL:\n\t\t\\begin{itemize}\n\t\t\t\\item \\includegraphics{RepofDef}\n\t\t\t\\item \\includegraphics{CompressDef}\n\t\t\t\\item \\includegraphics{RepofcDef}\n\t\t\t\\item \\includegraphics{CmpDef}\n\t\t\t\\item \\includegraphics{UnionBigDef.png}\n\t\t\\end{itemize}\n\t\\end{itemize}\n\\end{frame}\n\n\\section{History of the Proof}\n\\begin{frame}\n\t\\frametitle{History of the Proof}\n\t\\begin{itemize}\n\t\t\\item Several, slightly different results about the amortized time complexity of the operations of Union-Find\n\t\t\\item The first result involving $\\alpha$ by Tarjan in 1975. The proof was simplified until the version in CLRS\n\t\t\\item In 1989 Fredman and Saks prove (in some sense) the optimality of the result\n\t\t\\item The latest result by Alstrup et al. in 2014 tightens the bound\n\t\t\\item In 2017, Charguéraud and Pottier formalize the result in Coq\n\t\t\\item Now, we present this formalization in Isabelle/HOL\n\t\t\\item In all these proofs, but especially since Alstrup et al., most work is needed for the abstract analysis\n\t\\end{itemize}\n\\end{frame}\n\n\\section{Timeline of the Project}\n\\begin{frame}\n\t\\frametitle{Timeline of the Project}\n\t\\vspace{-0.7cm}\n\t\\begin{table}\n\t\t\\centering\n\t\t\\begin{minipage}[t]{\\linewidth}\n\t\t\t\\color{gray}\n\t\t\t\\ytl{May}{Background work: Familiarisation with Sepreftime and the paper by Charguéraud and Pottier}\n\t\t\t\\vspace{-0.1cm}\n\t\t\t\\ytl{May 15th}{Official thesis registration}\n\t\t\t\\vspace{-0.1cm}\n\t\t\t\\ytl{June}{Cleanup of the previous work by Lammich and Haslbeck}\n\t\t\t\\vspace{-0.1cm}\n\t\t\t\\ytl{June 5th}{Armaël Guéneau visits TUM}\n\t\t\t\\vspace{-0.1cm}\n\t\t\t\\ytl{June}{\\textbf{Bottom-up}: Ackermann and InverseNatNat theories and important definitions}\n\t\t\t\\vspace{-0.1cm}\n\t\t\t\\ytl{July}{First abstract proofs: rank, level, index}\n\t\t\t\\vspace{-0.1cm}\n\t\t\t\\ytl{July 16th}{\\textbf{Top-down}: Sanity check of definitions done, skipping the rest and proof of the Hoare-Triples}\n\t\t\t\\vspace{-0.1cm}\n\t\t\t\\ytl{August}{Exam phase}\n\t\t\t\\vspace{-0.1cm}\n\t\t\t\\ytl{September}{Parallel writing of the thesis, proof gap-filling and correction of definitions}\n\t\t\t\\vspace{-0.1cm}\n\t\t\t\\ytl{September 8th}{Complete sound theory}\n\t\t\t\\vspace{-0.1cm}\n\t\t\t\\ytl{Semptember 13th}{Submission of the thesis}\n\t\t\t\\vspace{-0.1cm}\n\t\t\t\\bigskip\n\t\t\\end{minipage}%\n\t\\end{table}\n\\end{frame}\n\n\\section{Overview of the Isabelle Proof}\n\\begin{frame}\n\t\\frametitle{Overview}\n\t\\vspace{-2.5cm}\n\t\\begin{figure}\n\t\t\\includegraphics[scale=0.8]{OverviewFigure}\n\t\\end{figure}\n\\end{frame}\n\n\\section{Inverses of Functions $f: \\mathbb{N} \\rightarrow \\mathbb{N}$}\n\\begin{frame}\n\t\\frametitle{Inverses of Functions $f: \\mathbb{N} \\rightarrow \\mathbb{N}$}\n\t\\begin{minipage}[t]{0.55\\linewidth}\n\t\t\\vspace{-4cm}\n\t\\begin{itemize}\n\t\t\\item Defined in InverseNatNat.thy\n\t\t\\item Upper inverse $\\alpha_f$ and Lower inverse $\\beta_f$\n\t\t\\item Lemmas to change the proof obligations between inverses and the original function\n\t\t\\item Used for Inverse Ackermann Function, but also the ``index'' of a node\n\t\\end{itemize}\n\t\\end{minipage}\n\\begin{minipage}[c]{0.4\\linewidth}\n\\includegraphics[scale=0.7]{InverseNatNatFigure}\n\\end{minipage}\n\\end{frame}\n\n\\section{The Ackermann Function and its Inverse}\n\\begin{frame}\n\t\\frametitle{The Ackermann Function and its Inverse}\n\t\\begin{itemize}\n\t\t\\item There is no single Ackermann Function ``$A$'' or inverse Ackermann Function ``$\\alpha$''\n\t\t\\item All definitions share the property of growing faster than any primitive recursive function\n\t\t\\item $\\alpha$ grows \\textbf{very} slowly\n\t\t\\item We use the definition of $A$ and $\\alpha$ by Tarjan:\n\t\\end{itemize}\n\\begin{minipage}{0.45\\linewidth}\n\\begin{dfn} Ackermann Function\n\t\\begin{align*}\n\tA \\, 0 \\, x &= x + 1  \\\\\n\tA \\, (k + 1)\\, x &= (A\\, k)^{(x + 1)}\\, x \n\t\\end{align*}\n\\end{dfn}\n\\end{minipage}\n\\begin{minipage}{0.45\\linewidth}\n\\begin{dfn} Inverse Ackermann Function\n\t\\begin{align*}\n\t\\alpha \\, n &= \\min \\{ k \\,\\mid\\, A\\, k\\, 1 \\geq n \\}\\\\\n\t\\alpha_r \\, n &= 1 + \\min\\{ k \\,\\mid\\, A\\, k\\, r \\geq (n + 1) \\}\n\t\\end{align*}\n\\end{dfn}\n\\end{minipage}\n\n\\begin{itemize}\n\t\\item In Isabelle/HOL, the definitions are expressed slightly differently and make use of InverseNatNat.thy\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}\n\t\\frametitle{The Ackermann Function and its Inverse}\n\t\\vspace{0.6cm}\n\t\\begin{lma}{observable\\_universe\\_$\\alpha$}\n\t\t\\newline\n\t\t\\textbf{Assume:} $n \\leq 10^{80} $\n\t\t\\begin{equation}\n\t\t\\alpha \\, n \\leq 4 \\label{universealpha}\n\t\t\\end{equation}\n\t\\end{lma}\t\n\\begin{itemize}\n\t\\item $10^{80}$ is an estimate of the number of atoms in the universe\n\\end{itemize}\n\n\\begin{lma}{$\\alpha$\\_n\\_0\\_$\\alpha$\\_logn}\n\t\\newline\n\t\\textbf{Assume:} $16 \\leq n$\n\t\\begin{equation}\n\t\\alpha \\, n \\leq 1 + (\\alpha \\, (\\log{n}))\n\t\\end{equation}\n\\end{lma}\n\\begin{itemize}\n\t\\item $\\alpha$ and $\\alpha(\\log\\, n)$ are asymptotically equivalent\n\t\\item True for every primitive recursive strictly monotonic function\n\\end{itemize}\n\\end{frame}\n\n\\section{Separation Logic with Time Credits}\n\\begin{frame}\n\t\\frametitle{Separation Logic with Time Credits}\n\t\\begin{itemize}\n\t\t\\item Logic to reason about mutable resources in a heap. Enables Hoare-Triple definition\n\t\t\\item It also allows for ``pure'' assertions, predicates independent of the heap content\n\t\t\\item Time Credits can also appear in assertions and are required to execute atomic operations\n\t\t\\item The components of the logic are: \\begin{itemize}\n\t\t\t\\item $\\uparrow(P)$ \n\t\t\t\\item true and false \n\t\t\t\\item $p \\mapsto_a xs$ \n\t\t\t\\item $P_1 * P_2$ \n\t\t\t\\item $\\exists_A x.\\, P$ \n\t\t\\end{itemize}\n\t\\item The Framework by Haslbeck implementing this for Isabelle/HOL, as well as this thesis as a usage example will be published in the AFP.\n\t\\end{itemize}\n\\end{frame}\n\n\\subsection{Amortized Analysis with Time Credits}\n\\begin{frame}\n\t\\frametitle{Amortized Analysis with Time Credits}\n\t\\begin{itemize}\n\t\t\\item We define a potential function $\\Phi$ that measures the ``entropy'' of the data structure\n\t\t\\item The idea is to ``hide'' $\\Phi$ credits in the assertion defining the data structure\n\t\t\\item If we are able to prove a Hoare-Triple of the form:\n\t\t\\begin{equation*}\n\t\t\\langle \\mathrm{invar}(\\mathcal{D}) * \\$(\\Phi(\\mathcal{D})) * \\underbrace{\\$(f(\\mathcal{D}))}_{\\text{Advertised Cost}} \\rangle \n\t\t\\quad \\mathtt{op}(\\mathcal{D}) \\quad \n\t\t\\langle \\mathrm{invar}(\\mathcal{D'}) * \\$(\\Phi(\\mathcal{D}')) \\rangle\n\t\t\\end{equation*}\n\t\tfor any $\\Phi$ and $f \\in \\mathcal{O}(g)$, we can conclude that the operation \\texttt{op} has an amortized cost in $\\mathcal{O}(g)$\n\t\t\\item Remaining questions: \\begin{itemize}\n\t\t\t\\item What $\\Phi$ do you choose? How does $\\Phi$ evolve?\n\t\t\t\\item How do you prove the functional correctness? \\newline\n\t\t\t$\\Longrightarrow$ Mathematical analysis of the data structure\n\t\t\\end{itemize}\n\t\\end{itemize}\n\\end{frame}\n\n\n\\section{The Potential Function $\\Phi$}\n\\begin{frame}\n\t\\frametitle{The Potential Function $\\Phi$}\t\n\t\\vspace{0.6cm}\n\t\\begin{definition}{Potential for a single node}\n\t\t\\begin{equation*}\n\t\t\\philr i :=\n\t\t\\begin{cases}\n\t\t\\alpha_r\\, (\\RR_r\\, i) \\cdot (1 + (\\RR_r\\, i)) & \\mathrm{if}\\, \\LL!i=i \\,   \\\\\n\t\t(\\alpha_r\\, (\\RR_r\\, i) - \\level i) \\cdot \\RR_r\\, i - \\iindex i + 1  &\\mathrm{if}\\, \\alpha_r\\, (\\RR_r\\, i) = \\alpha_r\\, (\\RR_r\\, (\\LL!i))\\\\\n\t\t0 & \\mathrm{otherwise}\n\t\t\\end{cases}\n\t\t\\end{equation*}\n\t\\end{definition}\n\n\\begin{definition}{Potential of the data structure}\n\t\\begin{equation}\n\t\\Philr :=  \\sum_{i = 0}^{|\\LL| - 1}{\\philr i}\n\t\\end{equation}\n\\end{definition}\n\n\\begin{itemize}\n\t\\item $\\{0,\\dots, |\\LL|-1\\}$ is in this case the domain of our equivalence relation\n\\end{itemize}\n\n\t\n\\end{frame}\n\n\n\\section{Results of the Thesis}\n\\begin{frame}\n\t\\frametitle{Results of the Thesis}\n\tThe $\\,\\,\\mathrm{is\\_uf}$ Assertion takes a relation and two arrays as arguments and ensures:\\begin{itemize}\n\t\t\\item The well-formedness of the disjoint set forest and the ranks\n\t\t\\item That the relation modeled by the array is the one given\n\t\t\\item That the necessary potential is stored as Time Credits\n\t\\end{itemize}\n\t\\vspace{0.6cm}\n\t\\begin{dfn}\n\t\\begin{align}\n\t\\begin{split}\n\t\\mathrm{is\\_uf}\\, \\mathcal{X} \\, (s,p) := \n\t&\\exists_A \\LL\\, \\RR.\\, p \\mapsto_a \\LL * s \\mapsto_a \\RR\\, * \\\\\n\t&\\uparrow (\\ufaalpha = \\mathcal{X} \\land \\mathrm{invar\\_rank}\\, \\LL \\, \\RR)\\, * \\\\\n\t&\\$(4\\cdot\\Philr)\n\t\\end{split}\n\t\\end{align}\n\t\\end{dfn}\n\\vspace{-0.5cm}\n\\end{frame}\n\n\\begin{frame}\n\t\\frametitle{Results of the Thesis}\n\t\\vspace{0.6cm}\n\t\\begin{minipage}{0.48\\linewidth}\n\\begin{lma}\n\t\\begin{equation*}\n\t\\mathrm{uf\\_cmp\\_time}\\, \\in \\mathcal{O}(\\alpha_r\\,n)\n\t\\end{equation*}\n\\end{lma}\n\n\\begin{thm}\n\t\\,\\newline\n\t\\begin{align*}\n\t\\begin{split}\n\t\\langle \\mathrm{is\\_uf}\\, \\mathcal{X}\\, u\\, * &\\$(\\mathrm{uf\\_cmp\\_time}\\, |\\mathrm{Dom}\\, \\mathcal{X}|)\\rangle \\quad \\\\ \n\t&\\mathtt{uf\\_cmp}\\, u\\, i\\, j\\\\\n\t&\\langle \\mathrm{is\\_uf}\\, \\mathcal{X}\\, u\\, * \\uparrow(r \\leftrightarrow (i,j)\\in\\mathcal{X}) \\rangle_t\n\t\\end{split}\n\t\\end{align*}\n\\end{thm}\n\t\\end{minipage}\n\t\\begin{minipage}{0.40\\linewidth}\n\\begin{lma}\n\t\\begin{equation*}\n\t\\mathrm{uf\\_union\\_time}\\, \\in \\mathcal{O}(\\alpha_r\\,n)\n\t\\end{equation*}\n\\end{lma}\n\\begin{thm}\\,\\newline\n\t\\textbf{Assumes: } $i,j \\in \\mathrm{Dom}\\, \\mathcal{R}$\n\t\\begin{align*}\n\t\\begin{split}\n\t\\langle \\mathrm{is\\_uf}\\, \\mathcal{X}\\, u\\, * &\\$(\\mathrm{uf\\_union\\_time}\\, |\\mathrm{Dom}\\, \\mathcal{X}|)\\rangle \\quad \\\\\n\t&\\mathtt{uf\\_union}\\, u\\, i\\, j\\\\\n\t&\\langle \\mathrm{is\\_uf}\\, (\\mathrm{per\\_union}\\, \\mathcal{X}\\, i\\, j)\\rangle_t\n\t\\end{split}\n\t\\end{align*}\n\\end{thm}\n\\end{minipage}\n\\vspace{-0.4cm}\n\\begin{itemize}\n\t\\item \\texttt{uf\\_union} corresponds to the \\textbf{Union} and \\texttt{uf\\_cmp} to the \\textbf{Find} operation\n\t\\item These theorems follow from abstract results about disjoint set forests\n\t\\item The whole proof is about 5KLoc long in Isabelle/HOL\n\\end{itemize}\n\\end{frame}\n\n\\section{Conclusions}\n\\begin{frame}\n\t\\frametitle{Conclusions}\n\t\\begin{itemize}\n\t\t\\item Formalization of the state-of-the-art result about Union-Find\n\t\t\\item Comprehensive theory about Ackermann, including quantitative and asymptotic results\n\t\t\\item The proofs of the imperative programs are still too long:\n\t\t \\begin{itemize}\n\t\t\t\\item The automation does not deal well with arithmetic\n\t\t\t\\item It also instantiates existentials too aggressively\n\t\t\t\\item Repetitive proofs generated by branching $\\Longrightarrow$ optimization possible\n\t\t\\end{itemize}\n\t\t\\item Formal verification of non-trivial results about runtime, not only correctness are possible \n\t\t\\item Some overhead, but this helps to reveal hidden assumptions \n\t\\end{itemize}\n\\end{frame}\n\n%\\PraesentationMasterKopfzeileDreizeiler\n\\begin{frame}\n\\frametitle{\\,}\n\\Huge Thank You for listening! \\newline\n\\Huge Any questions?\n\\end{frame}\n\n\\begin{frame}\n\t\\frametitle{Important Definitions}\n\t\\vspace{1cm}\n\t\\begin{definition}{invar\\_rank}\n\t\t\\begin{align}\n\t\t\\mathrm{invar\\_rank}\\, \\LL \\, \\RR := \n\t\t&\\mathrm{ufa\\_invar} \\, \\LL \\, \\land \\\\\n\t\t&|\\LL| = |\\RR| \\, \\land \\\\\n\t\t&(\\forall (i,j) \\in \\ufabstart. \\, \\RR!i < \\RR!j) \\\\\n\t\t&(\\forall i < |\\LL|.\\, \\LL!i = i \\longrightarrow 2^{\\RR!i} \\leq |\\mathrm{descendants}_\\LL \\, i|)\n\t\t\\end{align}\n\t\\end{definition}\n\t\\begin{definition}{ufa\\_invar}\n\t\\begin{equation}\n\t\\mathrm{ufa\\_invar} \\, \\LL \\, := \\forall i < |\\LL|.\\, i \\in \\mathrm{Dom}\\, \\repof \\land \\LL!i < |\\LL|\n\t\\end{equation}\n\t\\end{definition}\n\n\\begin{definition}{ufa\\_$\\beta$\\_start}\n\\begin{equation}\n\\ufabstart := \\{(x,y) \\,\\mid\\, x<|\\LL| \\land y<|\\LL| \\land x \\neq y \\land \\LL!x = y \\}\n\\end{equation}\n\\end{definition}\n\n\\end{frame}\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\end{document} % !!! NICHT ENTFERNEN !!!\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n", "meta": {"hexsha": "515d146cc6234585cea23d3058c8cf9147aeeb5e", "size": 14897, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Colloquium/Colloquium.tex", "max_stars_repo_name": "adrilow/Proof-of-the-amortized-time-complexity-of-the-Union-Find-data-structure-in-Isabelle-HOL", "max_stars_repo_head_hexsha": "293b12752261dac7f741483b62b27891bf4be1cc", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Colloquium/Colloquium.tex", "max_issues_repo_name": "adrilow/Proof-of-the-amortized-time-complexity-of-the-Union-Find-data-structure-in-Isabelle-HOL", "max_issues_repo_head_hexsha": "293b12752261dac7f741483b62b27891bf4be1cc", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Colloquium/Colloquium.tex", "max_forks_repo_name": "adrilow/Proof-of-the-amortized-time-complexity-of-the-Union-Find-data-structure-in-Isabelle-HOL", "max_forks_repo_head_hexsha": "293b12752261dac7f741483b62b27891bf4be1cc", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-05T10:54:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-05T10:54:16.000Z", "avg_line_length": 34.4837962963, "max_line_length": 141, "alphanum_fraction": 0.6705376922, "num_tokens": 4981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.3247243335772296}}
{"text": "%-------------------------------------------------------------------------------\n\\FloatBarrier\\section{Static model of educational choice}\n%-------------------------------------------------------------------------------\nConsider the framework of the generalized Roy model presented in class for the static analysis of educational choice.\n\n\\begin{boenumerate}\n\n\\item Write down and briefly describe the key equations of the model.\n\n\\item Formally define the conventional average treatment effects and describe their limited policy relevance. What is potentially lost by focusing on average effects instead of looking at the whole distribution of individual benefits?\n\n\\item Define and describe the concept of essential heterogeneity. How does its presence and absence affect the relationship between the conventional average treatment effect parameters. Please integrate the conventional average treatment effects in the absence of essential heterogeneity into Figure \\ref{Distribution of effects} which already shows a hypothetical distribution of individual-specific benefits.\n\n\\begin{figure}[htp]\\centering\n\\caption{Distribution of effects}\\label{Distribution of effects}\\scalebox{0.35}\n{\\includegraphics{fig-static-model-distribution-canvas}}\n\\end{figure}\n\n\\item Define and describe the marginal benefit of treatment. What exactly is the conditioning set? Complete the empty canvas below by sketching the marginal benefit of treatment in the presence and absence of essential heterogeneity. Ensure that both axes are properly labeled.\n\n\\begin{figure}[htp]\\centering\n\\caption{Marginal benefit of treatment}\\scalebox{0.35}\n{\\includegraphics{fig-static-model-marginal-benefit-canvas}}\n\\end{figure}\n\n\\item What are the main findings in \\cite{Carneiro.2011} on the marginal benefit of a college education?\n\n\\item Briefly outline the shortcomings of a static model of educational choice compared to a dynamic model.\n\\end{boenumerate}\n\nConsider the following parameterization of the generalized Roy model presented in class for the static analysis of educational choice.\n\n\\begin{align*}\nY_1 & = 0.25     & D = \\mathbbm{1}[\\,0.50 > U\\,] \\\\\nY_0 & = U &\n\\end{align*}\n\nAssume that $U$ is unobservable and follows a uniform distribution between zero and one. Please be careful about correctly labeling all graphs that you decide to include in your answers.\n\n\\begin{boenumerate}\n\n\\item Define the individual effect of treatment. What are the sources of heterogeneity in the model. What fraction of individuals have a positive benefit of treatment?  How many do select into treatment?\n\n\\item Formally define the conventional average treatment effects and describe their limited policy relevance. How does the distribution of benefits for the model above look like? What is its exact range? Please mark the part of the distribution conditional on treatment status. Calculate the conventional effects of treatment.\n\n\\item Define and describe the concept of essential heterogeneity. Does the parameterized model exhibit essential heterogeneity? Please explain your answer.\n\n\\item Define and describe the marginal benefit of treatment $B^{MTE}$. How exactly does the $B^{MTE}$ for the parameterized model above look like?\n\n\\end{boenumerate}\n", "meta": {"hexsha": "e1ebb8e72d6ea0552307f7cc4b4c9e1584253d83", "size": 3226, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "lectures/99-tutorial/files/s-static-model.tex", "max_stars_repo_name": "HumanCapitalAnalysis/labor-economics", "max_stars_repo_head_hexsha": "14f6cf83b2f29eb22236af4acd6c5e24779fa62d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2020-06-05T02:38:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-26T12:17:01.000Z", "max_issues_repo_path": "lectures/99-tutorial/files/s-static-model.tex", "max_issues_repo_name": "peppegrass/labor-economics", "max_issues_repo_head_hexsha": "d8fe99db8fb93b43ca53514d1fc048bb7b0efec7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lectures/99-tutorial/files/s-static-model.tex", "max_forks_repo_name": "peppegrass/labor-economics", "max_forks_repo_head_hexsha": "d8fe99db8fb93b43ca53514d1fc048bb7b0efec7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-03-31T19:50:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T02:12:27.000Z", "avg_line_length": 63.2549019608, "max_line_length": 410, "alphanum_fraction": 0.7684438934, "num_tokens": 630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3247126118599018}}
{"text": "\\documentclass[inequalities.tex]{subfile}\n\n\\begin{document}\n\t\\section{Smoothing and Isolated Fudging}\\label{sec:smoothfudging}\n\tIn many inequalities of the form\n\t\t\\begin{align*}\n\t\t\tf(x_{1},\\ldots,x_{n})\n\t\t\t\t& \\geq a\n\t\t\\end{align*}\n\tfor some real number $a$, we may be able to establish the property that $f$ assumes smaller values when the difference between two variables $x_{i}$ and $x_{j}$ decreases. In such cases, we can use the fact that $f$ assumes the smallest value when $x_{1}=\\ldots=x_{n}$. This is known as the \\textit{smoothing principle}. Recall that we used a similar argument for arithmetic-geometric mean inequality when we replaced the product $a_{1}a_{2}$ by $\\bar{a}(\\bar{a}+k-h)$ where $a_{1}=\\bar{a}-h$ and $a_{2}=\\bar{a}+k$.\n\t\t\\begin{problem}[USA $1996$]\\label{prob:usa1996-3}\n\t\t\tLet $a_{0},\\ldots,a_{n}$ be real numbers in the interval $\\left(0,\\frac{\\pi}{2}\\right)$. If\n\t\t\t\t\\begin{align*}\n\t\t\t\t\t\\tan\\left(a_{0}-\\dfrac{\\pi}{4}\\right)+\\ldots+\\tan\\left(a_{n}-\\dfrac{\\pi}{4}\\right)\n\t\t\t\t\t\t& \\geq n-1\n\t\t\t\t\\end{align*}\n\t\t\tprove that\n\t\t\t\t\\begin{align*}\n\t\t\t\t\t\\tan{a_{0}}\\cdots\\tan{a_{n}}\n\t\t\t\t\t\t& \\geq n^{n+1}\n\t\t\t\t\\end{align*}\n\n\t\t\t\t\\begin{solution}\n\t\t\t\t\tIf $x_{i}=\\tan\\left(a_{i}-\\frac{\\pi}{4}\\right)$ so $-1<x_{i}<1$ and\n\t\t\t\t\t\t\\begin{align*}\n\t\t\t\t\t\t\tx_{i}\n\t\t\t\t\t\t\t\t& = \\dfrac{\\tan{a_{i}}-1}{1+\\tan{a_{i}}}\\\\\n\t\t\t\t\t\t\t\t& = \\dfrac{y_{i}-1}{1+y_{i}}\n\t\t\t\t\t\t\\end{align*}\n\t\t\t\t\twhere $y_{i}=\\tan{a_{i}}$. Then\n\t\t\t\t\t\t\\begin{align*}\n\t\t\t\t\t\t\ty_{i}\n\t\t\t\t\t\t\t\t& = \\dfrac{1+x_{i}}{1-x_{i}}\n\t\t\t\t\t\t\\end{align*}\n\t\t\t\t\\end{solution}\n\t\t\\end{problem}\n\\end{document}", "meta": {"hexsha": "639c1cb36a7975ed94f72b97fcdbaa37827779fc", "size": 1553, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "smoothfudging.tex", "max_stars_repo_name": "ineq-tech/inequality", "max_stars_repo_head_hexsha": "ebf89351c843b6a7516e10e2ebf0d64e3f1f3f83", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-06T08:29:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T08:29:30.000Z", "max_issues_repo_path": "smoothfudging.tex", "max_issues_repo_name": "ineq-tech/inequality", "max_issues_repo_head_hexsha": "ebf89351c843b6a7516e10e2ebf0d64e3f1f3f83", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "smoothfudging.tex", "max_forks_repo_name": "ineq-tech/inequality", "max_forks_repo_head_hexsha": "ebf89351c843b6a7516e10e2ebf0d64e3f1f3f83", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.972972973, "max_line_length": 516, "alphanum_fraction": 0.607211848, "num_tokens": 601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.3247126118599018}}
{"text": "\\documentclass[english]{../thermomemo/thermomemo}\n\\pdfminorversion=4\n\\usepackage[utf8]{inputenc}\n\n\\usepackage{amsmath}\n%\\input{mathdef}\n\\usepackage[per-mode=symbol]{siunitx}\n\\usepackage[numbers]{natbib}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{array}% improves tabular environment.\n\\usepackage{dcolumn}% also improves tabular environment, with decimal centring.\n\n\\usepackage{booktabs}\n\\usepackage{a4wide}\n\\usepackage{xspace}\n\\usepackage{todonotes}\n\\presetkeys{todonotes}{inline}{}\n\\usepackage{subcaption,caption}\n\\usepackage{tikz}\n\\usetikzlibrary{arrows}\n\\usetikzlibrary{snakes}\n\\usepackage{verbatim}\n\\usepackage{hyperref}\n\\hypersetup{\n  colorlinks=true,\n  linkcolor=blue,\n  urlcolor=blue,\n  citecolor=blue\n}\n%\n% Egendefinerte\n%\n% Kolonnetyper for array.sty:\n\\newcolumntype{C}{>{$}c<{$}}% for å slippe å taste inn disse $\n\\newcolumntype{L}{>{$}l<{$}}% for å slippe å taste inn disse $\n%\n\\newcommand*{\\unit}[1]{\\ensuremath{\\,\\mathrm{#1}}}\n\\newcommand*{\\uunit}[1]{\\ensuremath{\\mathrm{#1}}}\n%\\newcommand*{\\od}[3][]{\\frac{\\mathrm{d}^{#1}#2}{\\mathrm{d}{#3}^{#1}}}% ordinary derivative\n\\newcommand*{\\od}[3][]{\\frac{\\dif^{#1}#2}{\\dif{#3}^{#1}}}% ordinary derivative\n\\newcommand*{\\pd}[3][]{\\frac{\\partial^{#1}#2}{\\partial{#3}^{#1}}}% partial derivative\n\\newcommand*{\\pdc}[3]{\\frac{\\partial^{2}#1}{\\partial{#2}\\partial{#3}}}% partial derivative\n\\newcommand*{\\pdt}[3][]{{\\partial^{#1}#2}/{\\partial{#3}^{#1}}}% partial\n                                % derivative for inline use.\n\\newcommand{\\pone}[3]{\\frac{\\partial #1}{\\partial #2}_{#3}}% partial\n                                % derivative with information of\n                                % constant variables\n\\newcommand{\\ponel}[3]{\\frac{\\partial #1}{\\partial #2}\\bigg|_{#3}} % partial derivative with informatio of constant variable. A line is added.\n\\newcommand{\\ptwo}[3]{\\frac{\\partial^{2} #1}{\\partial #2 \\partial\n    #3}} % partial differential in two different variables\n\\newcommand{\\pdn}[3]{\\frac{\\partial^{#1}#2}{\\partial{#3}^{#1}}}% partial derivative\n\n% Total derivative:\n\\newcommand*{\\ttd}[2]{\\frac{\\mathrm{D} #1}{\\mathrm{D} #2}}\n\\newcommand*{\\td}[2]{\\frac{\\mathrm{d} #1}{\\mathrm{d} #2}}\n\\newcommand*{\\ddt}{\\frac{\\partial}{\\partial t}}\n\\newcommand*{\\ddx}{\\frac{\\partial}{\\partial x}}\n% Vectors etc:\n% For Computer Modern:\n\n\\DeclareMathAlphabet{\\mathsfsl}{OT1}{cmss}{m}{sl}\n\\renewcommand*{\\vec}[1]{\\boldsymbol{#1}}%\n\\newcommand*{\\vektor}[1]{\\boldsymbol{#1}}%\n\\newcommand*{\\tensor}[1]{\\mathsfsl{#1}}% 2. order tensor\n\\newcommand*{\\matr}[1]{\\tensor{#1}}% matrix\n\\renewcommand*{\\div}{\\boldsymbol{\\nabla\\cdot}}% divergence\n\\newcommand*{\\grad}{\\boldsymbol{\\nabla}}% gradient\n% fancy differential from Claudio Beccari, TUGboat:\n% adjusts spacing automatically\n\\makeatletter\n\\newcommand*{\\dif}{\\@ifnextchar^{\\DIfF}{\\DIfF^{}}}\n\\def\\DIfF^#1{\\mathop{\\mathrm{\\mathstrut d}}\\nolimits^{#1}\\gobblesp@ce}\n\\def\\gobblesp@ce{\\futurelet\\diffarg\\opsp@ce}\n\\def\\opsp@ce{%\n  \\let\\DiffSpace\\!%\n  \\ifx\\diffarg(%\n    \\let\\DiffSpace\\relax\n  \\else\n    \\ifx\\diffarg[%\n      \\let\\DiffSpace\\relax\n    \\else\n      \\ifx\\diffarg\\{%\n        \\let\\DiffSpace\\relax\n      \\fi\\fi\\fi\\DiffSpace}\n\\makeatother\n%\n\\newcommand*{\\me}{\\mathrm{e}}% e is not a variable (2.718281828...)\n%\\newcommand*{\\mi}{\\mathrm{i}}%  nor i (\\sqrt{-1})\n\\newcommand*{\\mpi}{\\uppi}% nor pi (3.141592...) (works for for Lucida)\n%\n% lav tekst-indeks/subscript/pedex\n\\newcommand*{\\ped}[1]{\\ensuremath{_{\\text{#1}}}}\n% høy tekst-indeks/superscript/apex\n\\newcommand*{\\ap}[1]{\\ensuremath{^{\\text{#1}}}}\n\\newcommand*{\\apr}[1]{\\ensuremath{^{\\mathrm{#1}}}}\n\\newcommand*{\\pedr}[1]{\\ensuremath{_{\\mathrm{#1}}}}\n%\n\\newcommand*{\\volfrac}{\\alpha}% volume fraction\n\\newcommand*{\\surften}{\\sigma}% coeff. of surface tension\n\\newcommand*{\\curv}{\\kappa}% curvature\n\\newcommand*{\\ls}{\\phi}% level-set function\n\\newcommand*{\\ep}{\\Phi}% electric potential\n\\newcommand*{\\perm}{\\varepsilon}% electric permittivity\n\\newcommand*{\\visc}{\\mu}% molecular (dymamic) viscosity\n\\newcommand*{\\kvisc}{\\nu}% kinematic viscosity\n\\newcommand*{\\cfl}{C}% CFL number\n\n\\newcommand*{\\cons}{\\vec U}\n\\newcommand*{\\flux}{\\vec F}\n\\newcommand*{\\dens}{\\rho}\n\\newcommand*{\\svol}{\\ensuremath v}\n\\newcommand*{\\temp}{\\ensuremath T}\n\\newcommand*{\\vel}{\\ensuremath u}\n\\newcommand*{\\mom}{\\dens\\vel}\n\\newcommand*{\\toten}{\\ensuremath E}\n\\newcommand*{\\inten}{\\ensuremath e}\n\\newcommand*{\\press}{\\ensuremath p}\n\\renewcommand*{\\ss}{\\ensuremath a}\n\\newcommand*{\\jac}{\\matr A}\n%\n\\newcommand*{\\abs}[1]{\\lvert#1\\rvert}\n\\newcommand*{\\bigabs}[1]{\\bigl\\lvert#1\\bigr\\rvert}\n\\newcommand*{\\biggabs}[1]{\\biggl\\lvert#1\\biggr\\rvert}\n\\newcommand*{\\norm}[1]{\\lVert#1\\rVert}\n%\n\\newcommand*{\\e}[1]{\\times 10^{#1}}\n\\newcommand*{\\ex}[1]{\\times 10^{#1}}%shorthand -- for use e.g. in tables\n\\newcommand*{\\exi}[1]{10^{#1}}%shorthand -- for use e.g. in tables\n\\newcommand*{\\nondim}[1]{\\ensuremath{\\mathit{#1}}}% italic iflg. ISO. (???)\n\\newcommand*{\\rey}{\\nondim{Re}}\n\\newcommand*{\\acro}[1]{\\textsc{\\MakeLowercase{#1}}}%acronyms etc.\n\n\\newcommand{\\nto}{\\ensuremath{\\mbox{N}_{\\mbox{\\scriptsize 2}}}}\n\\newcommand{\\chfire}{\\ensuremath{\\mbox{CH}_{\\mbox{\\scriptsize 4}}}}\n%\\newcommand*{\\checked}{\\ding{51}}\n\\newcommand{\\coto}{\\ensuremath{\\text{CO}_{\\text{\\scriptsize 2}}}}\n\\newcommand{\\celsius}{\\ensuremath{^\\circ\\text{C}}}\n\\newcommand{\\clap}{Clapeyron~}\n\\newcommand{\\subl}{\\ensuremath{\\text{sub}}}\n\\newcommand{\\spec}{\\text{spec}}\n\\newcommand{\\sat}{\\text{sat}}\n\\newcommand{\\sol}{\\text{sol}}\n\\newcommand{\\liq}{\\text{liq}}\n\\newcommand{\\vap}{\\text{vap}}\n\\newcommand{\\amb}{\\text{amb}}\n\\newcommand{\\tr}{\\text{tr}}\n\\newcommand{\\crit}{\\text{crit}}\n\\newcommand{\\entr}{\\ensuremath{\\text{s}}}\n\\newcommand{\\fus}{\\text{fus}}\n\\newcommand{\\flash}[1]{\\ensuremath{#1\\text{-flash}}}\n\\newcommand{\\spce}[2]{\\ensuremath{#1\\, #2\\text{ space}}}\n\\newcommand{\\spanwagner}{\\text{Span--Wagner}}\n\\newcommand{\\triplepoint}{\\text{TP triple point}}\n\\newcommand{\\wrpt}{\\text{with respect to~}}\n\\newcommand{\\tpd}{\\ensuremath{\\text{tpd}}\\xspace}\n\\newcommand{\\TPD}{\\ensuremath{\\text{TPD}}\\xspace}\n\n\\title{Stability and critical points of mixtures}\n\\author{Morten Hammer}\n\n\\graphicspath{{gfx/}}\n\n\\begin{document}\n\\frontmatter\n\\tableofcontents\n\\section{Introduction}\nThis memo is to present methods for calculating stability and critical points of\nmixture. Background information on stability of mixtures and the calculation of\ncritical points is found in \\citet{Reid1977}, \\citet{Heidemann1980},\n\\citet{Michelsen1984} and \\citet[Chap. 9]{Michelsen2007}.\n\\section{Limit of stability formulated in temperature and pressure}\n\\label{sec:tp_fomulation}\nThe stability criterion for a mixture with composition $z$, formulated\nin temperature and pressure, is given by\n\\begin{equation}\n  \\label{eq:TPDorg}\n  \\TPD(\\vektor{w}) = \\underset{i}{\\sum}w_i\\left(\\mu_i(\\vektor{w})-\\mu_i(\\vektor{z})\\right),\n\\end{equation}\nwhere \\TPD is the tangent plane distance function, and $\\mu$ is the\nchemical potential. If looking at global stability, $\\vektor{w}$ is any\ncomposition. In the case of local stability, $\\vektor{w}$ is any perturbation\nof $\\vektor{z}$. If \\TPD is non-negative the mixture $\\vektor{z}$ is stable.\n\nA modified stability condition for a reduced tangent plane\ndistance \\tpd, is given in Equation \\ref{eq:tpd}. \\tpd is evaluated\nusing composition variables treated as mole numbers, $\\vektor{Y}$, instead of\ncomposition, and have better properties and are easier to solve\nnumerically that the $TPD$ formulation.\n\\begin{equation}\n  \\tpd(\\vektor{Y}) = 1.0 + \\underset{i}{\\sum}Y_i\\left(\\ln Y_i + \\ln \\varphi_i(\\vektor{Y})-\\ln z_i - \\ln \\varphi_i(\\vektor{z})\\right).\n  \\label{eq:tpd}\n\\end{equation}\nHere $\\varphi$ is the fugacity.\n\nDifferentiating Equation \\ref{eq:tpd}, we get\n\\begin{align}\n  \\vektor{g} &= \\pd{\\tpd}{\\vektor{Y}} = \\ln Y_i + \\ln \\varphi_i(\\vektor{Y})-\\ln z_i - \\ln \\varphi_i(\\vektor{z}),\\\\\n  H_{ij} &= \\frac{\\partial^2\\tpd}{\\partial Y_i \\partial Y_j} = \\frac{\\delta_{ij}}{Y_i} + \\frac{\\partial \\ln \\varphi_i(\\vektor{Y})}{Y_j}.\n  \\label{eq:dtpd}\n\\end{align}\n\nLooking at local stability of a mixture phase with composition $\\vektor{z}$, a\nperturbation of $\\vektor{z}$, $\\vektor{Y} = \\vektor{z} + \\vektor{e}$, for small $\\vektor{e}$ must give a positive\n\\tpd. A Taylor series expansion from $\\vektor{Y}=\\vektor{z}$ yields,\n\\begin{align}\n  \\tpd(\\vektor{Y}) =& \\tpd(\\vektor{z}) + \\left(\\pd{\\tpd}{\\vektor{z}}\\right)^\\intercal\\vektor{e} + \\frac{1}{2}\\vektor{e}^\\intercal\\left(\\pd[2]{\\tpd}{\\vektor{z}}\\right)\\vektor{e} + \\dots \\\\\n  =& \\tpd + \\vektor{g}^\\intercal \\vektor{e} + \\frac{1}{2}\\vektor{e}^\\intercal\\vektor{H}\\vektor{e} + \\dots.\n  \\label{eq:tpdTaylor}\n\\end{align}\nSince $\\tpd(\\vektor{z}) = 0$ and $\\vektor{g}(\\vektor{z}) = 0$, the local stability limit therefore become,\n\\begin{equation}\n  \\text{det}\\left(H\\right) = 0,\n  \\label{eq:detM}\n\\end{equation}\nor equivalent $\\lambda_{\\text{min}} = 0$, where $\\lambda_{\\text{min}}$\nis the minimum eigenvalue of $\\vektor{H}$.\n\nTo improve the scaling and the numerical properties of the problem,\n\\citet{Michelsen1984} introduces a scaling of the composition\nvariables,\n\\begin{equation}\n  \\label{eq:X}\n  X_i = \\frac{Y_i-z_i}{\\sqrt{z_i}}.\n\\end{equation}\nFurther $X_i = s u_i$, where $\\vektor{u}$ is a normalized vector,\n$\\vektor{u}^\\intercal\\vektor{u} = 1$. The perturbed composition then becomes,\n\\begin{equation}\n  \\label{eq:Y}\n  Y_i = z_i + s u_i\\sqrt{z_i}.\n\\end{equation}\nDifferentiating Equation \\ref{eq:tpd} \\wrpt $X_i$ we get,\n\\begin{align}\n  \\pd{\\tpd}{X_i} = \\sqrt{z_i}g_i,\\\\\n  \\frac{\\partial^2\\tpd}{\\partial X_i \\partial X_j} = B_{ij} &=  \\sqrt{z_i}\\sqrt{z_j}H_{ij}.\n  \\label{eq:dtpdX}\n\\end{align}\n\nFurther, if we let $\\vektor{u}$ be the eigenvector corresponding to the smallest\neigenvalue, $\\lambda_{\\text{min}}$, of $\\vektor{B}$, we have\n\\begin{equation}\n  \\label{eq:b}\n  b = \\frac{1}{2}\\vektor{u}^{\\top}\\vektor{B}\\vektor{u} = \\frac{1}{2} \\lambda_{\\text{min}}.\n\\end{equation}\n\n\\subsection{Numerical solver}\nSolving for $b = 0$ in Equation \\ref{eq:b}, for a specified pressure\nor temperature is complicated. The solution value ($T$ ot $p$) will\nlie near the value ($T$ ot $p$) where the underlying equation of state\nloses a density root (phase). A discontinuity will therefore be\nlocated close to the solution, excluding the possibility of using a\nbracketing solver, unless the position where the phase root disappears\nis know. If we are dealing with a cubic equation of state, the\nposition where the model looses a density root can easily be\ndetermine, otherwise not. See Figure \\ref{fig:meta_init}.\n\\begin{figure}[h]\n  \\centering\n  \\includegraphics[width=0.6\\textwidth]{meta_init}\n  \\caption{Minimum eigenvalue plotted as a function of $T$ for given\n    pressure, $P$ and for given specific volume, $V$. The\n    meta-stable limit is located at $T=\\SI{181.65}{\\kelvin}$. The $TP$\n    line have a discontinuity (phase disappear) located close to the\n    meta-stable limit, while the $TV$ line is monotonous. The plot is\n    generated for a mixture of \\SI{90}{\\percent} methane and\n    \\SI{10}{\\percent} ethane.}\n  \\label{fig:meta_init}\n\\end{figure}\n\nSpecifying a pressure and solving for a temperature at the meta-stable\nlimit, has been found possible for low pressures. The saturation\ntemperature, when treating the fluid as a pure fluid, at low\npressures, can be used as initial value of the search for a\nmeta-stable limit of a gas/liquid. We then know that the solution will\nlie below (gas) and above (liquid) the initial guess. Using a\nNewton-Raphson (NR) solver we will take steps in a direction towards\nthe solution, but with the possibility of overshooting the\nsolution. Since the eigenvalue of the stability matrix, $\\vektor{B}$,\nchanges abruptly when a phase disappears, and another phase is selected\nby the EOS density solver, a line search is used to back track if the\nsearch step becomes to large.\n\nThe NR solver must use numerical differentials since analytical\ndifferentials are difficult to derive in the general case.\n\nFor larger pressures, where the metastable limits of the gas and the\nliquid come close together, it has proven difficult to guaranty\nsolution to the correct meta-stable limit. To overcome this problem,\nan alternative formulation is needed.\n\n\\section{Alternative formulation}\nMichelsen and Heidemann \\cite{Heidemann1980} suggest that a\nformulation in the variables $T$ and $v$ is more robust than the $P$\nand $T$ formulation. One reason for this is that following the meta\nstable limit, the volume will be monotonous.\n\nThe Heidemann tangent plane distance for $T$ and $v$ are given as,\n\\begin{equation}\n  \\label{eq:tpd_TV}\n  \\TPD\\left(T,V,\\mathbf{Y}\\right) =\n A\\left(T,V,\\mathbf{Y}\\right) - A\\left(T,V_0,\\mathbf{z}\\right) +\n P\\left(T,V_0,\\mathbf{z}\\right)\\left(V - V_0\\right) -\n \\underset{j}{\\sum}\\mu\\left(T,V_0,\\mathbf{z}\\right)\\left(Y_j - z_j\\right)\n .\n\\end{equation}\n\nThe Michelsen \\citet[Chap. 9]{Michelsen2007} reduced tangent plane distance for $T$ and $v$ are given as,\n\\begin{equation}\n  \\label{eq:tpd_TV_M}\n  \\tpd(T,V,\\mathbf{Y}) =\n  \\underset{j}{\\sum}Y_j\\left[\\ln f_j \\left(T,V,\\mathbf{Y}\\right) -\n    \\ln f_j\\left(T,V_0,\\mathbf{z}\\right)\\right] -\n  \\left[P\\left(T,V,\\mathbf{Y}\\right) - P_0\\right]\\frac{V}{RT}\n  .\n\\end{equation}\n\nThe Helmholtz energy can be written as follows,\n\\begin{equation}\n  \\label{eq:A}\n A\\left(T,V,\\mathbf{Y}\\right) = - P\\left(T,V,\\mathbf{Y}\\right)V +\n \\underset{j}{\\sum}Y_j\\mu\\left(T,V,\\mathbf{Y}\\right)\n .\n\\end{equation}\n\nThe fugacity coefficient definition\n\\begin{equation}\n  \\label{eq:fugacity}\n  R T \\ln f_j\\left(T,V,\\mathbf{Y}\\right) =\n  \\pd{A\\left(T,V,\\mathbf{Y}\\right)}{Y_j} = \\mu_j \\left(T,V,\\mathbf{Y}\\right).\n\\end{equation}\ngive the following relation:\n\\begin{equation}\n  \\label{eq:A2}\n A\\left(T,V,\\mathbf{Y}\\right) = - P\\left(T,V,\\mathbf{Y}\\right)V +\n \\underset{j}{\\sum}Y_j\\ln f_j\\left(T,V,\\mathbf{Y}\\right).\n\\end{equation}\n\nNote that we are not working with the reduced Helmholtz energy, but\nthe real Helmholtz energy.\n\nUsing Equations \\ref{eq:A}, \\ref{eq:fugacity} and \\ref{eq:A2}, and\n$V=V_0$ it is seen that Equation \\ref{eq:tpd_TV} and Equation\n\\ref{eq:tpd_TV_M} represent the same stability criteria:\n\\begin{align}\n  \\label{eq:tpd_TV_M2}\n  tpd(T,V,\\mathbf{Y}) =&\n  \\underset{j}{\\sum}Y_j\\left[\\ln f_j \\left(T,V,\\mathbf{Y}\\right) -\n    \\ln f_j\\left(T,V_0,\\mathbf{z}\\right)\\right] -\n  \\left[P\\left(T,V,\\mathbf{Y}\\right) - P_0\\right]\\frac{V}{RT},\\\\\n  =& \\frac{1}{RT}\\left(-P\\left(T,V,\\mathbf{Y}\\right) V +\n     \\underset{j}{\\sum}Y_j\\mu_j \\left(T,V,\\mathbf{Y}\\right) \\right)\\\\\n  & - \\frac{1}{RT}\\left( - P_0V_0 + P_0\\left(V_0-V\\right)\n    -\\underset{j}{\\sum}\\left(Y_j - z_j + z_j\\right)\\mu_j\\left(T,V_0,\\mathbf{z}\\right)\n  \\right)\n  ,\\\\\n  =& \\frac{1}{RT}\\left( A\\left(T,V,\\mathbf{Y}\\right) -\n     A\\left(T,V_0,\\mathbf{z}\\right) + P_0\\left(V_0-V\\right) - \\underset{j}{\\sum}\\left(Y_j - z_j\\right)\\mu_j\\left(T,V_0,\\mathbf{z}\\right)\\right),\n\\end{align}\n\nDifferentiating Equation \\ref{eq:tpd_TV_M} w.r.t. $n_i$, and using $V=V_0$ we\nget\n\\begin{equation}\n  \\label{eq:tpd_TV_n}\n  g_i =\n \\ln f_i\\left(T,V_0,\\mathbf{Y}\\right) +\n \\ln f_i\\left(T,V_0,\\mathbf{z}\\right),\n\\end{equation}\nand\n\\begin{equation}\n  \\label{eq:tpd_TV_h}\n  h_{ij} =\n \\ln f_{ij}\\left(T,V,\\mathbf{Y}\\right) .\n\\end{equation}\n\nThe same variable scaling is used for this formulation, as in the\nprevious section (Equation \\ref{eq:X}). Using the temperature-pressure\nformulation to calculate an initial point, Section\n\\ref{sec:tp_fomulation}, for a low pressure, the entire meta-stable\nlimit can be mapped using steps in the volume variable. Stepping with\nfixed increments in $\\ln v$ was found optimal considering resolution of\nthe line.\n\nAn example, plotting the meta-stable limit together with the phase\nenvelope for a mixture of \\SI{90}{\\percent} methane and\n\\SI{10}{\\percent} ethane, is plotted in Figure \\ref{fig:meta}.\n\\begin{figure}[h]\n  \\centering\n  \\includegraphics[width=0.6\\textwidth]{meta}\n  \\caption{Phase envelope and meta-stable limit plotted for a mixture\n    of \\SI{90}{\\percent} methane and \\SI{10}{\\percent} ethane. The\n    critical point is plotted using a black dot.}\n  \\label{fig:meta}\n\\end{figure}\n\n\n\\subsection{Single component}\nThe pure fluid stability limit is the well-known,\n\\begin{equation}\n  \\label{eq:dpdv_t}\n  \\left(\\pd{p}{v}\\right)_T = 0.\n\\end{equation}\n\nThe mapping of the meta-stable limit for pure fluids currently use a\nsolver for Equation \\ref{eq:dpdv_t}. For robust and fast mapping,\nextrapolation of volume is performed between each step in temperature.\n\n%\\todo{Investigate if multi-component approach can be used for single components as well.}\n\nAn example, plotting the meta-stable limit together with the\nsaturation line for pure \\coto, is plotted in Figure\n\\ref{fig:singleMeta}.\n\\begin{figure}[h]\n  \\centering\n  \\includegraphics[width=0.6\\textwidth]{singleMeta}\n  \\caption{Saturation line and meta-stable limit plotted for pure\n    \\coto. Peng-Robinson equation of state with van der Waals mixing\n    rules are applied.}\n  \\label{fig:singleMeta}\n\\end{figure}\n\n\\section{Critical point}\n``A critical point is a stable point which lies on the stability\nlimit.'' - \\citet{Heidemann1980}. The implications from this is that,\nif \\tpd is Taylor expanded, the cubic form must vanish. See\n\\cite{Heidemann1980} for more details.\n\n% The critical will lie on the meta-stable line and also satisfying,\n% \\begin{equation}\n%   q_{ijk} = \\left(\\frac{\\partial^3\\tpd}{\\partial z_i \\partial z_j \\partial z_k}\\right)_{T,V\\text{ or }P} % \\Delta z_i \\Delta z_j \\Delta z_k.\n%   \\label{eq:q}\n% \\end{equation}\n\n\\subsection{Critical point solver}\nSince the third order differentials of \\tpd typically is difficult and\ntime consuming to construct analytically, \\citet{Michelsen1984}\ndeveloped an approach to solve for a critical point numerically\nwithout calculating these differentials. The main components of this\nalgorithm is given below for the formulation in temperature an volume.\nUsing $F = \\tpd$, and Taylor expanding in $s$, we get\n\\begin{align}\nF(\\mathbf{X} = s\\mathbf{u}) = F_1(s) = \\overset{\\infty}{\\underset{m=0}{\\sum}}\\left(\\frac{s^m}{m!}\\right)\\left(\\frac{\\partial^m F_1}{\\partial s^m}\\right)_{s=0} = as + bs^2 + cs^3 + ds^4 + \\mathcal{O}(s^5),\n\\label{eq:sTaylor}\n\\end{align}\nsince $F_1(s=0) = 0$. Further,\n$a = \\left(\\partial F_1/\\partial s\\right)_{s=0} =\n\\underset{i}{\\sum}\\sqrt{z_i}u_ig_i(s=0)=0$. For $b$ we have,\n\\begin{equation}\nb = \\frac{1}{2}{\\underset{i,j}{\\sum}}B_{ij}u_iu_j = \\frac{1}{2}\\mathbf{u}^\\intercal \\mathbf{B} \\mathbf{u},\n\\label{eq:bdef}\n\\end{equation}\nidentical to the definition in Equation \\ref{eq:b}. The smallest value\nof $b$ is found by choosing $\\mathbf{u}$ to be the eigenvector\ncorresponding to the minimum eigenvalue of $\\mathbf{B}$. We then get,\n\\begin{equation}\n\\mathbf{B} \\mathbf{u} = \\lambda_{\\text{min}} \\mathbf{u}, \\mathbf{u}^\\intercal\\mathbf{u} = 1\n\\label{eq:brelation}\n\\end{equation}\n\nFor $c$ we have,\n\\begin{equation}\n  c = \\frac{1}{6}{\\underset{i,j,k}{\\sum}}q_{ijk}u_iu_ju_k.\n\\label{eq:cdef}\n\\end{equation}\n\nDifferentiating Equation \\ref{eq:sTaylor} \\wrpt $s$, we get,\n\\begin{align}\n\\pd{F_1}{s} =  2bs + 3cs^2 + 4ds^3 + \\mathcal{O}(s^4),\n\\label{eq:sTaylords}\n\\end{align}\nand this equals\n\\begin{align}\n\\pd{F_1}{s} = \\underset{i}{\\sum}\\pd{F}{Y_i}\\pd{Y_i}{s} = \\underset{i}{\\sum}\\sqrt{z_i}u_ig_i.\n\\label{eq:dfds}\n\\end{align}\nEvaluating at $s=\\epsilon$ and $s=-\\epsilon$, we get\n\\begin{align}\n\\left(\\pd{F_1}{s}\\right)_{\\epsilon} &= 2b\\epsilon + 3c\\epsilon^2 + 4d\\epsilon^3 + \\mathcal{O}(\\epsilon^4),\\\\\n\\left(\\pd{F_1}{s}\\right)_{-\\epsilon} &= -2b\\epsilon + 3c\\epsilon^2 - 4d\\epsilon^3 + \\mathcal{O}(\\epsilon^4).\\\\\n\\label{eq:dfdseps}\n\\end{align}\nAdding the Equations above we get a Equation for $c$,\n\\begin{align}\nc = \\frac{1}{6\\epsilon^2}\\left(\\left(\\pd{F_1}{s}\\right)_{\\epsilon} + \\left(\\pd{F_1}{s}\\right)_{-\\epsilon}\\right) + \\mathcal{O}(\\epsilon^2).\n\\label{eq:c}\n\\end{align}\n\\subsubsection{Critical point solver Jacobean}\nIn order to construct a Newton-Raphson solver differentials for the Jaocobian is\nrequired.  Differentiating Equation \\ref{eq:brelation} \\wrpt temperature, we get\nthe relation,\n\\begin{equation}\n\\mathbf{B}_T \\mathbf{u} + \\mathbf{B} \\mathbf{u}_T = \\lambda_{T} \\mathbf{u} + \\lambda_{\\text{min}} \\mathbf{u}_T, \\mathbf{u}^\\intercal\\mathbf{u}_T = 0\n\\label{eq:breldiffT}\n\\end{equation}\nMultiplying with $\\mathbf{u}^\\intercal$, and simplifying we get,\n\\begin{align}\n\\mathbf{u}^\\intercal \\mathbf{B}_T \\mathbf{u} + \\mathbf{u}^\\intercal\\mathbf{B} \\mathbf{u}_T &= \\lambda_{T} \\mathbf{u}^\\intercal\\mathbf{u} + \\lambda_{\\text{min}} \\mathbf{u}^\\intercal\\mathbf{u}_T,\\\\\n\\mathbf{u}^\\intercal \\mathbf{B}_T \\mathbf{u}  &= \\lambda_{T}.\n\\label{eq:breldiffTuT}\n\\end{align}\nRearranging Equation \\ref{eq:breldiffT}, we get\n\\begin{equation}\n\\left(\\mathbf{B} - \\lambda_{\\text{min}}I\\right) \\mathbf{u}_T = \\lambda_{T} \\mathbf{u}  - \\mathbf{B}_T \\mathbf{u}.\n\\label{eq:breldiffTR}\n\\end{equation}\nWe see that if $\\mathbf{B}_T \\mathbf{u}$ is known, it is possible to\nfind $\\mathbf{u}_T$. The elements of $\\mathbf{B}_T \\mathbf{u}$, is\n\\begin{align}\n\\label{eq:Btu}\n  \\left(\\mathbf{B}_T \\mathbf{u}\\right)_i &= \\sqrt{z_i}\\underset{j}{\\sum}\\sqrt{z_j}u_j \\pd{\\ln f_{ij}}{T} = \\sqrt{z_i} \\pd{}{s}\\left(\\pd{\\ln f_{i}}{T}\\right)_{s=0} \\\\ \n                                         &\\approx \\sqrt{z_i} \\left(\\frac{1}{2\\epsilon}\\right)\\left[\\left(\\pd{\\ln f_{i}}{T}\\right)_{s=\\epsilon} - \\left(\\pd{\\ln f_{i}}{T}\\right)_{s=-\\epsilon} \\right].\n\\end{align}\nUsing $\\mathbf{B}_T \\mathbf{u}$, $\\lambda_T$ is determined, and further $b_T = \\lambda_T/2$. To determine $c_T$, Equation \\ref{eq:sTaylor} is used,\n\\begin{align}\n\\pd{F_1}{T} = b_Ts^2 + c_Ts^3 + d_Ts^4 + \\mathcal{O}(s^5).\n\\label{eq:dF1dT_Taylor}\n\\end{align}\nFurther differentiating Equation \\ref{eq:tpd_TV_M}, we get\n\\begin{align}\n\\label{eq:dF1dT}\n\\pd{F_1}{T} &= \\pd{\\tpd}{T} +\n  \\underset{j}{\\sum}\\pd{\\tpd}{Y_j}\\pd{Y_j}{T},\\\\\n\\pd{\\tpd}{T} &= \\underset{j}{\\sum}Y_j\\left[\\ln f_{jT} \\left(\\mathbf{Y}\\right) -\n     \\ln f_{jT}\\left(\\mathbf{z}\\right)\\right] -\n   \\left[P_T\\left(\\mathbf{Y}\\right) -\n               P_T\\left(\\mathbf{z}\\right)\\right]\\frac{V}{RT} \\\\ \n            &+\\left[P\\left(\\mathbf{Y}\\right) - P\\left(\\mathbf{z}\\right)\\right]\\frac{V}{RT^2}\\\\\n\\pd{\\tpd}{Y_j}\\pd{Y_j}{T} &=g_j\\sqrt{z_j}s(\\mathbf{u}_T)_j\n\\end{align}\nEvaluating equations \\ref{eq:dF1dT} and \\ref{eq:dF1dT_Taylor} at $\\epsilon$ and $-\\epsilon$ and combining, we get,\n\\begin{align}\nc_T = \\frac{1}{2\\epsilon^3}\\left(\\left(\\pd{F_1}{T}\\right)_{\\epsilon} - \\left(\\pd{F_1}{T}\\right)_{-\\epsilon}\\right) + \\mathcal{O}(\\epsilon^2).\n\\label{eq:cT}\n\\end{align}\nThe differentials \\wrpt volume can be determined in the same manner.\n\n% \\ref{eq:A}\n% \\begin{align}\n%   \\label{eq:dA}\n%  \\pd{A}{n_i} &= - P_iV + \\mu_i\n%  \\underset{j}{\\sum}n_j\\pd{\\mu}{n_i} = \\mu_i \\\\ \n%  P_iV &= \\underset{j}{\\sum}n_j\\pd{\\mu}{n_i} \\\\\n% F_1(T,V,n(T,V)) &=\n%   \\underset{j}{\\sum}n_j\\left[\\ln f_j \\left(T,V,\\mathbf{n}\\right) -\n%     \\ln f_j\\left(T,V_0,\\mathbf{z}\\right)\\right] -\n%   \\left[P\\left(T,V,\\mathbf{n}\\right) - P_0\\right]\\frac{V}{RT}\\\\\n%   \\pd{F_1}{n_i} &= \\ln f_i \\left(T,V,\\mathbf{n}\\right) + \\ln\n%                   f_i\\left(T,V_0,\\mathbf{z}\\right) + \\underset{j}{\\sum}n_j\\left[\\ln f_{ji} \\left(T,V,\\mathbf{n}\\right) -\n%     \\ln f_{ji}\\left(T,V_0,\\mathbf{z}\\right)\\right] -\n%    \\left[P_i\\left(T,V,\\mathbf{n}\\right) - P_{0,i}\\right]\\frac{V}{RT}\\\\\n% \\left[P\\left(T,V,\\mathbf{n}\\right) - P_0\\right]\\frac{V}{RT}\n% \\end{align}\n\\clearpage\n\\bibliographystyle{plainnat}\n\\bibliography{../thermopack}\n\n\\end{document}\n", "meta": {"hexsha": "6f945a9797273ef955ed01613dbdd0d34472ec64", "size": 23327, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/memo/critical/critical.tex", "max_stars_repo_name": "SINTEF/Thermopack", "max_stars_repo_head_hexsha": "63c0dc82fe6f88dd5612c53a35f7fbf405b4f3f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2020-10-14T07:51:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T04:59:23.000Z", "max_issues_repo_path": "doc/memo/critical/critical.tex", "max_issues_repo_name": "SINTEF/Thermopack", "max_issues_repo_head_hexsha": "63c0dc82fe6f88dd5612c53a35f7fbf405b4f3f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2020-10-26T11:43:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T22:06:30.000Z", "max_forks_repo_path": "doc/memo/critical/critical.tex", "max_forks_repo_name": "SINTEF/Thermopack", "max_forks_repo_head_hexsha": "63c0dc82fe6f88dd5612c53a35f7fbf405b4f3f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2020-10-27T13:04:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T04:59:24.000Z", "avg_line_length": 41.9550359712, "max_line_length": 204, "alphanum_fraction": 0.6895871737, "num_tokens": 8415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.32471261185990175}}
{"text": "\\documentclass[times, utf8, diplomski, numeric, english]{fer}\n\n\\usepackage{booktabs}\n\\usepackage{amsmath}\n\\usepackage{nccmath}\n%\\usepackage{hyperref}\n\\usepackage[section]{placeins}\n\n\\usepackage{footnote}\n\\usepackage{graphicx}\n\\usepackage{float}\n\\usepackage{mathtools}\n\\usepackage{makecell}\n\\usepackage[hidelinks]{hyperref}\n\n\\renewcommand\\theadalign{cb}\n\\renewcommand\\theadfont{\\bfseries}\n\\renewcommand\\theadgape{\\Gape[4pt]}\n\\renewcommand\\cellgape{\\Gape[4pt]}\n\n\\DeclarePairedDelimiter\\ceil{\\lceil}{\\rceil}\n\\DeclarePairedDelimiter\\floor{\\lfloor}{\\rfloor}\n\n\\DeclareMathOperator*{\\argmin}{\\arg\\!\\min}\n\\DeclareMathOperator*{\\argmax}{\\arg\\!\\max}\n\\begin{document}\n\n\n\\thesisnumber{1417}\n\\title{Deep Learning Model for Base Calling of MinION Nanopore Reads}\n\\author{Marko Ratković}\n\n\\maketitle\n\n% Ispis stranice s napomenom o umetanju izvornika rada. Uklonite naredbu \\izvornik ako želite izbaciti tu stranicu.\n\\izvornik\n\n% Dodavanje zahvale ili prazne stranice. Ako ne želite dodati zahvalu, naredbu ostavite radi prazne stranice.\n\\zahvala{I would like to thank my mentor, Mile Šikić, for his patient guidance, encouragement\n\tand advice provided over the years.\n\t\nI would also like to thank my family and friends for their\n\tcontinuous support.\n\t\nIn the end, honorable mentions go to Neven Miculinić for his help with this thesis.\n\t\n}\n\n\\tableofcontents\n\\listoffigures\n\\listoftables\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% CHAPTER\n\\chapter{Introduction}\n\nIn recent years,  deep learning methods significantly improved the state-of-the-art in multiple domains such as computer vision, speech recognition, and natural language processing \\cite{LeCun:1998:CNI:303568.303704}\\cite{NIPS2012_4824}. \nIn this thesis, we present application of deep learning in the field of  Bioinformatics for analysis of DNA sequencing data. \n\nDNA is a molecule that makes up the genetic material of a cell, and it is responsible for carrying the information needed for survival, growth, and reproduction of an organism. \nDNA is a long polymer of simple blocks called nucleotides connected together forming two spiraling strands to a structure called a double helix.  Possible nucleotide bases of a DNA strand are adenine, cytosine, guanine, thymine usually represented with letters A, C, G, and T. The order of these bases is what defines genetic code.\n\nDNA sequencing is the process of determining this sequence of nucleotides. Originally sequencing was an expensive process, but during the last couple of decades, the price of sequencing has drastically decreased.  A significant breakthrough occurred in May 2015 with the release of MinION sequencer by Oxford Nanopore making DNA sequencing inexpensive and more available, even for small research teams. \n\nBase calling is a process assigning sequence of nucleotides (letters) to the raw data generated by the sequencing device. Simply put, it is a process of decoding the output from the sequencer.\n\n\n\\section{Objectives}\nThe goal of this thesis is to show that the accuracy of sequencing data is not only limited by sequencing technology, but also by the underlying software used for base calling and can be further improved using different machine learning concepts. A novel approach for base calling of raw data using convolutional neural networks is introduced.\n\n\\section{Organization}\n\\indent Chapter 2 gives more detailed explanation of the problem, background on nanopore sequencing and overview of state-of-the-art basecallers.\n\nChapter 3 describes in detail deep learning concepts used in later chapters.\n\nChapter 4 goes into implementation details, preprocessing methods and training of the deep learning model. \n\nChapter 5 explains the methodology used to evaluate obtained results and the results of testing performed on different datasets as well as comparison with state-of-the-art basecallers.\n\nIn the end, Chapter 6 gives a brief conclusion and possible future work and improvements of the developed basecaller.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% CHAPTER\n\\chapter{Background}\n\n\\section{Sequencing}\n\nAll sequencing technologies to date have constraints on the length of the strand they can process, which are much smaller than the genome for a majority of organisms, making sequencing the entire genome of an organism a difficult problem. To resolve this problem whole genome shotgun sequencing approach is used, in which multiple copies of the genome are broken randomly into numerous small fragments that can be processed by the sequencer. Sequenced fragments are called reads.\n\nGenome assembly is the process of reconstructing the original genome from reads and usually starts with finding overlaps between reads.\nThe quality of reconstruction heavily depends on the length and the quality (accuracy) of the reads produced by the sequencer.\n\nFigure \\ref{fg:sequencing} depicts process of sequencing.\n\n\\begin{figure}[!ht]\n\t\\begin{center}\n\t\t\\includegraphics[width=0.6\\textwidth]{./imgs/sequencing.png}\n\t\t\\caption{Depiction of the sequencing process}\n\t\t\\label{fg:sequencing}\n\t\\end{center}\n\\end{figure}\n\n\nDevelopment of sequencing started with work of Frederick Sanger \\cite{mile} \\cite{Pettersson2009}. In 1977, he developed the first sequencing method which allowed \nread lengths up to 1000 bases with very high accuracy (99.9\\%) at the cost of 1\\$ per 1000 bases.\nSecond generation sequencing (IAN Torrent and Illumina devices) reduced the price of sequencing while maintaining high accuracy. Mayor disadvantage of these devices is read length of only a few hundred base pairs. Short reads make resolving repetitive regions practically impossible.\n\nThe need for technology able of producing longer reads led to the development of so-called third generation sequencing technologies.\nPacBio developed sequencing method that allowed read lengths up to several thousand bases but at the cost of smaller accuracy. Error Rates of PacBio devices are \\textasciitilde10-15\\%. \n\nCost makes the biggest obstacle stopping widespread genome sequencing. The release of, previously mentioned, MinION sequencer made sequencing less expensive and even portable.\n\n\n\n\\section{Oxford Nanopore MinION}\n\nThe MinION device by Oxford Nanopore Technologies is the first portable DNA sequencing device. Its small weight, low cost, and long read length combined with decent accuracy yield promising results in various applications including full human genome assembly \\cite{human_seq} what could potentially lead to personalized genomic medicine.\n\n\\subsection{Technology}\nAs its name says, nanoscaled pores are used to sequence DNA. An electrical potential is applied over a membrane in which a  pore is inserted. \nAs the DNA passes through the pore, the sensor detects changes in ionic current caused by different nucleotides present in the pore. Figure \\ref{fg:nanopore} shows the change of ionic current as DNA strain is pulled through a nanopore.\n\n\\begin{figure}[!ht]\n\t\\begin{center}\n\t\t\\includegraphics[width=0.7\\textwidth]{./imgs/nanopore.png}\n\t\t\n\t\t\\caption[DNA strain being pulled through a nanopore]{DNA strain being pulled through a nanopore \\protect\\footnotemark}\n\t\t\\label{fg:nanopore}\n\t\\end{center}\n\\end{figure}\n\\footnotetext{Figure adapted from https://nanoporetech.com/how-it-works}\n\n\nOfficial software called MinKNOW outputs sequencing data in FAST5 (a variant of the HDF5 standard) file format. It is a hierarchical file format with data arranged in a tree-structure of groups. Metadata are stored in group and dataset attributes. The same file format is during used different stages of analyses and groups, datasets and attributes are added incrementally. Figure \\ref{fg:fast5} shows raw signal being present in the FAST5 file.\n\\begin{figure}[!ht]\n\t\\begin{center}\n\t\t\\includegraphics[width=0.6\\textwidth]{./imgs/fast5.png}\n\t\t\\caption[Structure of FAST5 file and raw signal plot show in \\textit{HDFView}]{Structure of FAST5 file and raw signal line plot show in \\textit{HDFView} \\protect\\footnotemark}\n\t\t\\label{fg:fast5}\n\t\\end{center}\n\\end{figure}\n\\footnotetext{https://support.hdfgroup.org/products/java/hdfview/}\n\nMinion offers the possibility of sequencing one or both strands of DNA. Sequencing both strands and combining information results in reads of higher quality. Those reads are called 2D (two-dimensional) reads. Otherwise, if the only single strand is sequenced 1D (one-dimensional) reads are produced.\n\nMinION devices can produce long reads, usually tens of thousand base pairs (with reported reads lengths of 100 thousand \\cite{loman1-100k} and even recently above 800 thousand base pairs \\cite{loman2-800k}), but with high sequencing error than older generations of sequencing technologies.\nSwitch from older R7.3 to  R9 chemistry in 2016 increased accuracy of produced data. With this change, the accuracy of 1D data increased from 70\\% to 85\\% and the accuracy of 2D reads from 88\\% to 94\\% \\cite{nanopore_video}.  This increase of accuracy makes 1D reads usable for analysis with benefits over 2D reads being faster sample preparation and faster sequencing. Developed tool in this thesis focuses on base calling 1D reads.\n\n\n  \n\\section{Existing basecallers}\n\n\\subsection{Official}\nOxford Nanopore has, with the R9 version of the platform, introduced a variety of base calling options. Some of those are production ready and some experimental. The majority of information regarding differences, specifications and similar is only available through Nanoporetech Community \\footnote{https://community.nanoporetech.com/}.\n\n\n\\textit{Metrichor} is an Oxford Nanopore company that offers cloud-based platform \\textit{EPI2ME} for analysis of nanopore data. \nInitially, base calling was only available by uploading data to the platform - that being the reason why this basecaller is often called Metrichor even though it is a name of the company.\n\nThe older version of Metrichor relied on \\textit{hidden Markov models} (HMM) to find the biological sequence corresponding to the signal. Preprocess included segmentation of the signal into smaller chunks called events defined by start location of the chunk, length, mean value and variance of the signal in the chunk. Metrichor than assumed that each event usually corresponds to a context of 6 bases being present in the pore and that the context is typically shifted by one base in each step. \nThe states of HMM are modeled as a context present in the pore and transition correspond to change of bases in the pore. During the transition from one state to another, an event is emitted. Base calling is performed using the Viterbi algorithm which determines the most likely sequence of states for the observed sequence of events. This approach showed poor results when calling long homopolymer stretches as the context in the pore remains the same \\cite{homopolymers}\\cite{homopolimeri_analiza}.\n\nWith the release of R9 chemistry, this model was replaced by a more accurate recurrent neural network (RNN) implementation. Currently, Oxford Nanopore offers several RNN-based local basecaller versions under different names: Albacore, Nanonet and basecaller integrated into MinKNOW \\cite{ont-basecallers}.   \n\n\\textit{Albacore} is basecaller by Oxford Nanopore Technologies ready for production and actively supported.\nIt is available to the Nanopore Community served as a binary. The source code of Albacore was not provided and is only available through the ONT Developer Channel. Tool supports only R9.4 and future R9.5 version of the chemistry.\n\n\\textit{Nanonet}\\footnote{\\url{https://github.com/nanoporetech/nanonet/}} uses the same neural network that is used in Albacore but it is continually under development and does contain features such as error handling or logging needed for production use. It uses \\textit{CURRENNT} library for running neural networks. It supportes basecalling of both R9 and R9.4 chemistry versions.\n\n\n\\textit{Scrappie}\\footnote{\\url{https://github.com/nanoporetech/scrappie}} is another basecaller by Oxford Nanopore Technologies. Similar to Nanonet, it is the platform for ongoing development. Scrappie is reported to be the first basecaller  that specifically address homopolymer base calling. It became publicly available just recently in June, 2017 and supports R9.4 and future R9.5 data.\n\n\\pagebreak\n\\subsection{Third-party basecallers}\n\n\\textit{Nanocall} \\cite{David046086} was the first third-party open source basecaller for nanopore data. It uses HMM approach like the original R7 Metrichor. Nanocall does not support newer chemistries after R7.3.\n\n\n\\textit{DeepNano} \\cite{Boza2017}  was the first open-source basecaller based on neural networks. It uses bidirectional recurrent neural networks implemented in Python, using the Theano library. When released, originally only supported R7 chemistry, but support for R9 and R9.4 was added recently.\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% CHAPTER\n\\chapter{Methods}\nThe process of base calling can be represented as the problem of machine translation where a sentence is translated from one language to another. For base calling, the sequence of events or current measurements is \\textit{translated} to the sequence of nucleotides (letters A, C, T, and G).\n\nThis section explains some key  deep learning concepts needed to understand the final model. It gives general idea behind recurrent neural networks used in a majority of existing basecallers and possible problems that serve as motivation for the different approach - usage of convolutional neural networks. \n\n\\section{Architecture}\n\n\\subsection{RNN}\n\\textit{Recurrent neural networks} can be viewed as a simple feed-forward network with the difference that the current output does not only depend on the current input but previous inputs as well. RNNs store that information in their hidden state which is updated in each step. The figure shows simple RNN and the same RNN unfolded in time.  Unrolling is a way of showing how network processes each input in the sequence and updates its hidden state (show in figure  \\ref{fg:rnn}).\n\\begin{figure}[!ht]\n\t\\begin{center}\n\t\t\\includegraphics[width=0.8\\textwidth]{./imgs/rnn.png}\n\t\t\\caption{An unrolled recurrent neural network}\n\t\t\\label{fg:rnn}\n\t\\end{center}\n\\end{figure}\n\nThese networks are trained using a variant of backpropagation called backpropagation through time which is essentially the same as classical backpropagation on an unfolded network. The gradient is propagated through the entire recurrence relation, and the gradient is multiplied in each step with the factor, depending on a scale it can make gradient vanish (drop to 0) or exponentially grow each step and explode. Detailed explanation can be found \\cite{rnn-blog}. These issues are called the vanishing and exploding gradient and are generally resolved by a variant of RNN called \\textit{LSTM} \\cite{hochreiter1997long}. \n\nBidirectional Recurrent Neural (BiRNN) networks are used when the current output not only depends on the previous elements in the sequence but also future elements. The idea is to combine two RNN (one in the positive direction, one in negative time direction) and have an output of the current state expressed as a function of hidden states of both RNNs and current input. This is the approach used in DeepNano \\cite{Boza2017}. \n\n\nOne of the major drawbacks of all recurrent networks is computation time. RNNs operate sequentially as the output for the second step depends on the first step and so on, which makes parallelization capabilities of RNNs quite limited. This especially is the case for Bidirectional RNNs.\n\n\\subsection{CNN}\n\n\\textit{Convolutional Neural Networks }(CNNs) were responsible for major breakthroughs in Image Classification and are the core of most Computer Vision systems today. More recently CNNs are applied being to problems in Natural Language Processing and show promising results \\cite{BYTENET}\\cite{facebook}.\n\nConvolution can be easily explained as a sliding window function applied to a matrix or in the case of base calling, signal. The sliding window is called a kernel or a filter. Figure \\ref{fg:convolution} shows an example of convolution with kernel size 3 and how output is calculated as a sum of element-wise multiplication of kernel elements and input vector. Stride defines by how much filter is shifted at each step. Usually, to preserve the same dimension, padding with zeros is added to the borders. \n\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\includegraphics[width=0.5\\textwidth]{./imgs/convolution.png}\n\t\t\\caption{Convolution layer, kernel size 3 with stride 1.}\n\t\t\\label{fg:convolution}\n\t\\end{center}\n\\end{figure}\n\n\n\\subsubsection{Activations}\nAfter each convolution layer, usually nonlinear layer (know as activation layer) is applied. The purpose of this layer is to introduce nonlinearity to a system which consists of only linear operations as convolution layers are nothing more than just element-wise multiplications and summations. In classical neural networks, nonlinear functions like $ tanh $ and $ sigmoid $ were often used, but because of the undesirable property of saturation (at either end of 0 or 1 for $ sigmoid $, -1 or 1 for $ tanh $), other activations are more often used today with CNNs. \n\n\\textit{The Rectified Linear Unit }(ReLU) has become very popular in the last few years. It is shown in \\cite{NIPS2012_4824} that usage of ReLU greatly accelerates the convergence of stochastic gradient descent compared to the sigmoid or tanh activations. Calculation of ReLU is much also more efficient as it is is simply thresholding at zero. \n\n\\begin{equation}\nReLU(x) =\n\\begin{cases}\nx, & \\text{if}\\ x>0 \\\\\n0, & \\text{otherwise}\n\\end{cases} \\\\\n\\end{equation}\n\n\nThe downside of ReLU is still saturation to the 0 on one side. Once in this state, the neuron is unlikely to recover because the function gradient at 0 is also 0, so gradient descent learning will not alter the weights. This is the problem known as \\textit{dying ReLU}.\nDifferent variants of ReLU, \\textit{PrRelu}, and \\textit{ELU} are often used to resolve this problem \\cite{prelu}\\cite{elu}.  \n\n\\begin{equation}    \nPrELU(x)=\n\\begin{cases}\nx, & \\text{if}\\ x>0 \\\\\n\\alpha x, & \\text{otherwise}\n\\end{cases}\\\\\n\\end{equation}\n\\begin{equation}\nELU(x)=\n\\begin{cases}\nx, & \\text{if}\\ x>0 \\\\\n\\alpha (exp(x) - 1), & \\text{otherwise}\n\\end{cases}    \\\\\n\\end{equation}\n\nFigure \\ref{fg:activations} shows different activation functions.\n\\begin{figure}[!htb]\n\t\\begin{center}\n\t\t\\includegraphics[width=0.5\\textwidth]{./imgs/activations.png}\n\t\t\\caption{Activation functions}\n\t\t\\label{fg:activations}\n\t\\end{center}\n\\end{figure}\n\n\\subsubsection{Pooling}\n\nThe pooling layer is usually placed after the convolutional layer. Its primary utility lies in reducing the spatial dimensions of the input for the next convolution layer while preserving the most salient information. Pooling also provides basic invariance to translation.\n\nSimilar to the convolution layer described previously, the pooling layer also uses sliding window or a certain size that is moved across the input transforming the values. Usually, larger strides are used then in the convolution layers, as the purpose of this layer is subsampling. Most ofter, maximum value operation on the values in the window (max pooling) is used, but other transformations are possible (average pooling, L2-norm, or stochastic pooling).\nFigure \\ref{fg:pooling} show dimensionality reduction by factor 2 using pooling with kernel size 2 with stride 2.\n\\begin{figure}[!htb]\n\t\\begin{center}\n\t\t\\includegraphics[width=0.5\\textwidth]{./imgs/pooling.png}\n\t\t\\caption{Dimensionality reduction by pooling (kernel size 2, stride 2)}\n\t\t\\label{fg:pooling}\n\t\\end{center}\n\\end{figure}\n\n\n\n\n  \n\\subsubsection{Comparision with RNN}\n\n\nDuring calculation, each \\textit{patch} a convolutional kernel operates on is independent of the other, meaning that the entire input layer can be processed concurrently making CNNs usually more efficient than RNNs. \n\nWhen compared with RNN in which output can depend on the entire sequence,  in convolution layer, single output \\textit{sees} only limited window in the previous layer defined by kernel size. This is called the receptive field of the convolution. \nFigure \\ref{fg:receptive field} shows each new layers depends on larger portion of the input ($z_i$ \\textit{sees} 5 elements of input). \nLower layers see limited spatial information and are able to detect simple features like edges but through a series of convolutional layers, later layers can detect more abstract concepts using intermediate features detected from the whole input, or the signal in our case. This is the motivation behind deep convolution neural networks and why they are so popular in the field of image processing.\n\n\\begin{figure}[!ht]\n\t\\begin{center}\n\t\t\\includegraphics[width=0.5\\textwidth]{./imgs/receptive_field.png}\n\t\t\\caption{Receptive field after 2 layers of convolutions with kernel size 3}\n\t\t\\label{fg:receptive field}\n\t\\end{center}\n\\end{figure}\nStacking layers increases computational time as the input signal has to pass through the entire network but calculations at each layer can happen concurrently and each individual computation is small.\nIn practice, even deep CNNs still have a big speed up over RNNS.\n\nDuring the forward pass, input flows and is transformed, hopefully becoming a representation that is more suitable for the task. During the back phase, the gradient is propagated back through the network. Just like in RNNs, this signal gets multiplied and depending on the scales it can vanish resulting in no gradient flow to lower layers and no parameter upgrades. This limits the depth of the network. Resnet arhitecture \\cite{resnet} with its residual layers address this issue and allows deep architectures with steady gradient flow.\n\n\n\n\n\\subsection{Residual Networks}\nA Residual Network or ResNet is a neural network architecture which solves the problem of vanishing gradients using a simple trick.  \nFigure \\ref{fg:resnet_block}  shows on the left classical CNN that takes input and transforms it using convolution layers and activations.  This can be represented as some nonlinear function $ H(x) $. $ H(x) $ can be written as a sum of some other nonlinear function $F(X)$ and linear member $x$. $F(X) $ is called the residual. Detailed explanation and comparisons are included in the original paper.\n\n\\begin{figure}[!ht]\n\t\\begin{center}\n\t\t\\includegraphics[width=0.7\\textwidth]{./imgs/resnet_block.png}\n\t\t\\caption[Comparison between classical CNN and CNN with the residual connection ]{Comparison between classical CNN and CNN with the residual connection \\protect\\footnotemark}\n\t\t\\label{fg:resnet_block}\n\t\\end{center}\n\\end{figure}\n\\footnotetext{Figure adapted from the original paper \\cite{resnet}}\nInstead of learning $H(X)$, network learns residual and at the output $x$ is simply summed up to the $F(x)$ as shown in the figure.  By stacking these layers, the gradient could theoretically \\textit{skip} over all the intermediate nonlinear layers and reach the bottom without vanishing.\n\n\n\n\n\\section{CTC Loss}\n\nAs mentioned previously, the goal of this thesis is to design model which can convert from a sequence of current measurements into a sequence of base pairs.\n\nSuppose that we have an input sequence $X$ (signal data) and the desired output sequence $Y$ (nucleotides). $X$ and $Y$ will be of different lengths as the sequence of base pairs is always shorter than the length of the signal.\n\nInstead of having a variable size of the output from the neural network, we can limit it to the length $m$ and have sequences of variable length \\textit{decoded} from those outputs. The neural network can be considered to be simply a function that takes in some input sequence $X$ (of length $n$) and generates sequence $O$ (of length $m$). Output sequence of variable length $Y$ is later \\textit{decoded} from $O$.\n\n\\subsection{Definition}\nThey key idea behind Connectionist Temporal Classification(CTC) \\cite{Graves:2006:CTC:1143844.1143891} is that instead of directly generating output sequence $Y$ as output from the neural network, we  generate a probability distribution at every output length (from $t$=1 to $t$=$m$) that after \\textit{decoding} gives maximum likelihood output sequence $Y$. \nFinally, the network is trained using training dataset $D = \\{(X_i, Y_i)\\}$ by creating an objective function that restricts the maximum likelihood decoding for a given sequence $X_i$ to correspond to our desired target sequence $Y_i$.\n\nGiven an input sequence $X$ of length $n$, the network generates probabilities over all possible labels (A, C, T, and G) with an extra symbol \"-\" representing a \\textit{blank} at each timestep. \n\\begin{equation}\n\\begin{gathered}\n\\Sigma = \\{A, C, T, G\\} \\cup \\{-\\}\n\\end{gathered}\n\\end{equation}\n\n\nPossible output generated by the network is called \\textit{path}. Path is defined by the sequence of its elements $\\pi = (\\pi_1, \\pi_2, ..., \\pi_m)$ where $\\pi_i$ is from $\\Sigma$.\nThe probability of a given path $\\pi$, given input sequence $X$, can then be expressed as the product of probabilities for each of its forming elements.\n\n\\begin{equation}\n\\begin{gathered}\nP(\\pi | X) = \\prod_{t=1}^{m} o_t(\\pi_t), \\\\\n\\text{where $o_t(\\pi_t)$ is probability of element $\\pi_t$ being $t^{th}$ element on path $\\pi$}\n\\end{gathered}\n\\end{equation}\n\n\nReal output sequence, for given path, is obtained by traversing the path and removing all blanks and duplicate letters. Let $ decode(\\pi) $ be the output sequence corresponding to a path $\\pi$. As seen\nin expression \\ref{eq:multiple} multiple path correspond to the same sequence $Y=\"ACT\"$.\n\\begin{equation}\n\\begin{gathered}\n\\label{eq:multiple}\nACT = \\begin{cases}\ndecode(A, A, A, C, T) \\\\\ndecode(A, A, C, -, T) \\\\\ndecode(-, A, C, T, T)  \\\\\ndecode(-, -, A, C, T)  \\\\\ndecode(A, C, C, C, T)  \\\\\n\\vdots \\\\\ndecode(A, C, T, -, -) \n\\end{cases}\n\\end{gathered}\n\\end{equation}\n\nThe probability of output sequence $Y$ is then the sum of probabilities of all paths that decode to $Y$:\n\\begin{equation}\n\\begin{gathered}\nP(Y | X) = \\sum_{\\pi \\in decode^{-1}(Y)}^{} P(\\pi | X)\n\\end{gathered}\n\\end{equation}\n\\subsection{Objective}\nGiven the dataset $D = \\{(X_i, Y_i)\\}$, training objective is the maximization of the likelihood of each training sample  which is the same as the minimization of negative log likelihood:\n\n\\begin{equation}\n\\begin{gathered}\nL(D) = - \\sum_{(X,Y)\\in D}^{} ln P(Y | X)\n\\end{gathered}\n\\end{equation}\n\n\n\\subsection{Output decoding}\nGiven the probability distribution $P(Y | X)$ and given input sequence $X$, most likely $Y^{*}$ can be computed.\n\\begin{equation}\n\\begin{gathered}\nY^{*} = \\argmax_{Y \\in L^m} P(Y|X) = \\argmax_{Y \\in L^m} \\sum_{\\pi \\in decode^{-1}(Y)}^{} P(\\pi | X),\\\\\n\\text{~where $L^m$ set of all possible sequences over alphabet $L$ }\\\\\n\\text{with length less than or equals to $m$}\n\\end{gathered}\n\\end{equation}\n\nThe probability of a single output sequence $Y$ is the sum of probabilities of all paths that decode to $Y$ and the most probable sequence is selected as the output.\nCalculation of all possible sequences is computationally intractable but exist several algorithms that approximate this decoding. \n\nThe naive possibility is to take the most probable path and say that output sequence corresponds to that path.\nThis is not necessarily correct.  For example, suppose we have one path with probability $0.1$ corresponding to sequence $A$, and ten paths with probabilities  $0.05$ each corresponding to sequence $B$. Label $B$ is preferable one since it has an overall probability of $0.5$; however, this naive best path decoding would select label $A$, whose single path has higher probability the those for label $B$. This method is called \\textit{best path decoding}.\n\nBetter approximations can be calculated using \\textit{beam search decoding} proposed in paper \\cite{graves_decode}.  \nThe idea is an incremental construction of the most probable sequences in step $t$ using $N$ most probable sequences from the previous step. Parameter $N$ is called beam width. \n\n\n\n\nProbability of $Y$ being extended with character $c$ in step $t$ is expressed like:\n\\begin{equation}\n\\begin{gathered}\nP(c, Y, t) = P(Y, t-1) * p(c, t|X), \\\\\\text{~where $p(c, t|X)$ is probability of $c$ being t-th output from the network in t-th step}.\n\\end{gathered}\n\\end{equation}\n\nLets label  with $\\hat{Y}$ prefix of $Y$ without last symbol and $Y^e$ as last symbol in $Y$.\n\\begin{equation}\n\\begin{gathered}\nY = \\hat{Y} + Y^e, \\text{~where $+$ is concatanation operator}\n\\end{gathered}\n\\end{equation}\n\n\nWe can get $Y$ by having $\\hat{Y}$ in previous step and network output $Y^e$ or simply by\nalready having $Y$ in previous step and network output blank($-$) or $Y^e$ as blanks and repeats are merged during decoding.\n\\begin{equation}\n\\begin{gathered}\n\\label{eq:rec_step}\nP(Y, t) = P(Y, t-1) p(-, t|X) +  P(Y, t-1)  p(Y^e, t|X) +  P(\\hat{Y}, t-1)  p(Y^e, Y, t) \n\\end{gathered}\n\\end{equation}\nUsing this expression, using dynamic programing can efficiently be determine probability of some sequence $Y$.\n\nBeam search decoder keeps set $B$ of $N$ most probable sequences. $B$ is initially a set consisting of a single blank. In each time step $t$ (from $t$=1 to $t$=$m$) all sequences from $B$ are expanded and probabilities of new sequences are calculated using recursive relation \\ref{eq:rec_step}. Expanded sequences are placed in the new set $B'$. At the end of each step, $B$ is replaced by $B'$ and truncated by keeping $N$ most probable sequences. \nAfter last time step, the sequence in $B$ with the highest probability is chosen as the final output.\nFull pseudocode can be found in original paper \\cite{graves_decode}. \nDetailed explanation and calculation of gradient can be found in original CTC paper \\cite{Graves:2006:CTC:1143844.1143891}, or this very detailed blog post \\cite{ctc-blog}.\n\n\n\\section{Batch normalization}\nBatch normalization is method proposed in paper \\cite{BNORM} that accelerates learning process. \nDuring training, parameters are updated, and distribution of outputs of each layer keep changing. A small change in the distribution of outputs in early layers can cause a drastic change in later layers, and those layers need to adapt to the new scale of their inputs. This change of distribution is called the internal covariate shift and results in slows learning.\nThis is solved by centering each output from activations of the training batch to zero-mean and unit variance. After that learned scale and offset are applied. This process is called batch normalization. \nAfter training, mean and variance for each activation are computed on the whole training dataset rather than on mini-batches during training. \n\nBatch normalization offers several advantages other than reducing internal covariant shift including more robust learning process by reducing reliance on the scale of the parameters and their initial values allowing the usage of larger learning rates and faster learning altogether. It is shown in the original paper that batch normalization also regularizes the model that could potentially improve the performance of the model.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% CHAPTER\n\\chapter{Implementation}\n\n\n\\section{Data}\n\nBoth used datasets show in table \\ref{tbl:datasets} be previously have passed through MinKNOW and had been basecalled by Metrichor. As 1D read analysis was the focus of this thesis, only those reads were used.\n\\begin{savenotes}\n\t\\begin{table}[htb]\n\t\t\\caption{Used datasets}\n\t\t\\label{tbl:datasets}\n\t\t\\centering\n\t\t\n\t\t\\begin{tabular}{lcc| c}\n\t\t\t\\toprule\n\t\t\t{} &  \\thead{Number of reads} &   \\thead{Total bases \\lbrack bp\\rbrack\\footnote{Total number of bases calle by Metrichor}} &    \\thead{Whole genome size \\lbrack bp\\rbrack} \\\\\n\t\t\t\\midrule\n\t\t\t\\textit{{E. Coli}}\\footnote{R9 sequencing data from \\url{http://lab.loman.net/2016/07/30/nanopore-r9-data-release/}, reference taken from \\url{https://www.ncbi.nlm.nih.gov/nuccore/48994873}} & 164471 & 1 481 687 490 & 4 639 675\\\\\n\t\t\t\\textit{lambda}\\footnote{Internal dataset, reference taken from \\url{https://www.ncbi.nlm.nih.gov/nuccore/NC_001416.1}}   & 86 &  466 465 & 48 502  \\\\\n\t\t\t\n\t\t\t\\bottomrule\n\t\t\\end{tabular}\n\t\\end{table}\n\\end{savenotes}\n\n\nFigure \\ref{fg:events} shows data present inside FAST5 file after being base calling by Metrichor. For each basecalled event, $model\\_state$ field contains the most likely sequence of bases in the pore. How many bases have passed through the pore between two consecutive events is defined by the $move$ field. \n\n\n\\begin{figure}[!ht]\n\t\\begin{center}\n\t\t\\includegraphics[width=1\\textwidth]{./imgs/basecall_events.png}\n\t\t\\caption{Basecall information produced by Metrichor show in HDFView}\n\t\t\\label{fg:events}\n\t\\end{center}\n\\end{figure}\n\n\n\n\\subsection{File formats}\nDescriptions of various file formats used later in descriptions of preprocessing of training data and evaluation are given in this section.\n\\subsubsection{FASTA}\n\n\nFASTA is widely used file format for reference sequences. Usual file extensions are \\textit{.fasta} or \\textit{.fa}).\nSequence representation consists of header line containing description starting with character $ > $, followed by line(s) of sequence data represented by letters. Full file specification can be found at \\textit{NCBI} site\\footnote{\\url{http://www.ncbi.nlm.nih.gov/BLAST/blastcgihelp.shtml}}.\nFigure \\ref{fg:fsta} shows example of sequence stored in FASTA file format.\n\\begin{figure}[!ht]\n\t\\begin{center}\n\t\t\\includegraphics[width=0.8\\textwidth]{./imgs/fasta.png}\n\t\t\\caption{Example of FASTA file}\n\t\t\\label{fg:fsta}\n\t\\end{center}\n\\end{figure} \n\n\\subsubsection{FASTQ format}\nReads are usually stored in FASTQ file format. Each read in the file is stored in following way:\n\\begin{enumerate}\n\t\\item character \"$@$\" followed  by a sequence identifier and an optional description \n\t\\item sequence\n\t\\item character \"$+$\" character and is optionally followed by the same sequence identifier and description.\n\t\\item quality score for each base\n\\end{enumerate}\nQuality is represented by ASCII printable characters where\nthe character \"$!$\" represents the lowest quality while \"\\textasciitilde\" is the highest. Figure \\ref{fg:fq} shows example of read stored in FASTQ file format.\n\\begin{figure}[!ht]\n\t\\begin{center}\n\t\t\\includegraphics[width=0.6\\textwidth]{./imgs/fq.png}\n\t\t\\caption{Example of FASTQ file}\n\t\t\\label{fg:fq}\n\t\\end{center}\n\\end{figure} \n\n\\subsubsection{SAM format}\nThe Sequence Alignment/Map (SAM) format is a generic format for storing reads alignments against the reference sequences. It is a TAB-delimited text format consisting\nof header section and an alignments section. Detailed information about SAM specification can be found on \\textit{SAMTools} website\\footnote{\\url{https://samtools.github.io/hts-specs/SAMv1.pdf}}.\nAmong other information, alignment start position is included, flag stating if read aligned as the template of as the reverse complement and CIGAR string describing the alignment.\nFigure \\ref{fg:align} shows simple alignment and CIGAR string. \nThere are several possible letters that can appear in CIGAR string but most importantly matches, mismatches, insertions and deletions are represented by letters \"=\", \"X\", \"I\" and \"D\".\n\n\n\\begin{figure}[!ht]\n\t\\begin{center}\n\t\t\\includegraphics[width=0.6\\textwidth]{./imgs/alignment.png}\n\t\t\\caption{Example of simple alignment and CIGAR string}\n\t\t\\label{fg:align}\n\t\\end{center}\n\\end{figure} \n\n\n\\section{Data preprocess}\n\nTo help training process, the raw signal is split into smaller blocks that are used as inputs. For each Metrichor basecalled event is easy to determine the block it falls into using $start$ field. Using this information output given by Metrichor can be determined for each block. \nTo correct errors produced by Metrichor and possibly increase the quality of data, each read is aligned to the reference. This is done using aligner GraphMap \\cite{sovic} that returns the best position in the genome, hopefully, the part of the genome from which read came from.\nAlignment part in the genome is used as a target. Using CIGAR string returned by aligner we can correct Metrichor data and get target output for each block. This process is shown in figure \\ref{fg:data_correction}.\n\n\\begin{figure}[!ht]\n\t\\begin{center}\n\t\t\\includegraphics[width=1\\textwidth]{./imgs/train_data_correction.png}\n\t\t\\caption{Dataset preparation}\n\t\t\\label{fg:data_correction}\n\t\\end{center}\n\\end{figure}\n\n\nTo eliminate the possibility of overfitting to the known reference, the model is trained and tested on reads from different organisms. Due to limited amount of public available raw nanopore sequence data, ecoli was \\textit{divided} into two regions.\nReads were split into train and test portions, depending on which region of ecoli they align. \nIf read aligns inside first 70\\% of the ecoli, it is placed into train set, and if it aligns to the second portion, it is placed into test set. Reads whose alignment overlaps train and test region are not used. Important to note that ecoli genome, and genomes of the majority of other bacteria, is cyclical, so reads with alignments that wrap over edges are also discarded. Total train set consist of over 110 thousand reads.\nOverview of the entire learning pipeline is shown in figure \\ref{fg:train_pipe}.\n\\begin{figure}[!ht]\n\t\\begin{center}\n\t\t\\includegraphics[width=0.7\\textwidth]{./imgs/train_pipeline.png}\n\t\t\\caption{Overview of training pipeline}\n\t\t\\label{fg:train_pipe}\n\t\\end{center}\n\\end{figure}\n\n\\section{Deep Learning model}\n\nThe final model is a residual neural network consisting of 72 residual blocks that are depicted in figure \\ref{fg:model_block}. The used model is a variant of architecture proposed in paper \\cite{identitet} with the difference of ELU being used as activation instead of ReLU as it is reported \\cite{resnet-elu} to speeds up the learning process and improve accuracy as the depth increase.\n\\begin{figure}[!ht]\n\t\\begin{center}\n\t\t\\includegraphics[width=0.2\\textwidth]{./imgs/model.png}\n\t\t\\caption{Used residual block}\n\t\t\\label{fg:model_block}\n\t\\end{center}\n\\end{figure} \n\nEach residual block contains two convolution layers making a total number of convolutions 144. Each convolutional layer in this models uses 64 kernels of 3. Because sequenced read is always shorter than the raw signal, pooling with kernel size two is used every 48 layers resulting in a reduction of dimensionality by factor 8. This is used reduce computation effort and to help training by reducing the number of required blank labels outputed by the network. This network has two million parameters that are learned during training. \n\nTraining the model is the minimization of previously described CTC loss. It was done using Adam \\cite{adam}, stochastic gradient descent algorithm based on an estimation of first and second-order moments.\nIt is often used as it offers fast and stable convergence. Default parameters of Adam were used (\n$\\beta_1=0.9$ and $\\beta_2=0.999$). Initial learning rate was set to 1e-3 with exponential decay. Batch size was set to 8 mostly due to limited hardware resources. As noisy batches could potentially cause gradients to explode, gradient clipped to a range [-2, 2] was used.\nLearning curve is show on figure \\ref{fg:learn}. Occasional spikes of training loss are explained by small batch size and presence of noise in the signal. Learning curve shows no sign of overfitting as modes shows similar performance on both train and validation sets.\n\n\\begin{figure}[!ht]\n\t\\begin{center}\n\t\t\\includegraphics[width=0.6\\textwidth]{./imgs/train_tb.png}\n\t\t\\caption{Learning curve in TensorBoard}\n\t\t\\label{fg:learn}\n\t\\end{center}\n\\end{figure}\n\nTraining process is implemented as \\textit{producers/consumer} pattern with communication done using FIFO\\footnote{FIFO is an acronym for first in, first out} queue. Multiple producer threads, running on the CPU, load FAST5 and alimnment batch data, preprocess it and convert to required objects, while single GPU worker takes batch from the queue and computes forwards and backward passes on the network. This is done to reduce time between batches and maximize GPU utilization during training. \n\n\n\\section{Technologies}\n\\label{sec:tech}\nOverall solution was implemented in Python programing language. Described model is implemented using TensorFlow. It is an open source software library for numerical computation using data flow graphs developed by Google. TensorFlow, even though is considered low-level framework, offers implementations of many higher level concepts (layers, losses, and optimizers) which makes it great for prototyping while keeping it modular and extensible for highly specific tasks as well.\n\nTensorFlow offers efficient GPU implementations of various layers and losses but as of version 1.2 still lacks GPU implementation of used CTC loss, so WARP-CTC\\footnote{\\url{https://github.com/baidu-research/warp-ctc}} was used. It offers both GPU and CPU implementations as well as bindings for TensorFlow.\n\nFor alignment tasks, developed tool offers support for GraphMap and BWA but can easily be extended with support any other aligner that outputs results in SAM file format.\n\nSAMTools\\footnote{\\url{http://www.htslib.org/}} and Python bindings PySam\\footnote{\\url{https://github.com/pysam-developers/pysam}} were used for conversions between various file formats used in Bioinformatics.\n\nDocker was used for automating the deployment on different machines. It helps to resolve problem know as \\textit{dependency hell}\\footnote{\\url{https://en.wikipedia.org/wiki/Dependency_hell}}  keeping all dependencies in single container thus eliminating possible conflict between packages on host OS.\nNvidia Docker\\footnote{\\url{https://github.com/NVIDIA/nvidia-docker}} was used for GPU support inside docker containers.\n\n\nTraining and all evaluations were done on the server with  \\textit{Intel(R) Xeon(R) E5-2640 CPU}, 600 GB of RAM and \\textit{NVIDIA TITAN X Black} with 6GB of GDDR5 memory and 2880 CUDA cores.\n\nAll developed and used code, including utility scripts is publicly available on \\textit{GitHub}\\footnote{\\url{https://github.com/mratkovic/masters-thesis}} under the \\textit{MIT Licence}.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% CHAPTER\n\\chapter{Results}\nDeveloped tool was compared with other available basecallers that support R9 chemistry. This includes third-party basically DeepNano and official basecallers by Oxford Nanopore (cloud-based Metrichor and Nanonet).\nThe fact that ground truth is not known makes evaluation difficult. \nDifferent methods for evaluation were used to get clearer information about each basecaller.\nIn all tables and figures, developed model is addressed as \\textit{resdeep} simply due to the fact it is a deep residual neural network.\n\n\n\n\\section{Error rates per read}\n\nBasecalled reads are aligned to the reference using GraphMap and alignments are analyzed. If the whole sequencing is done correctly and quality basecaller is used, all reads should align to the reference. Mismatches, insertions, and deletions, in that case, should be due to limitations of sequencing technology and noise in the signal.\n\nA portion of the read length that aligns as correctly is called match\\_rate. Same goes for mismatches and insertions. \nSum of all matches, mismatches, and insertions is equal to the reads length \\ref{eq:read_len}. \n\n\\begin{equation}\n\\begin{gathered}\n\\label{eq:read_len}\nread\\_len =  n\\_matches + n\\_mismatches + n\\_insertions \n\\end{gathered}\n\\end{equation}\n\\begin{equation}\n\\begin{gathered}\nmatch\\_rate = \\dfrac{n\\_matches}{read\\_length}\n\\end{gathered}\n\\end{equation}\n\\begin{equation}\n\\begin{gathered}\nmissmatch\\_rate = \\dfrac{n\\_mismatches}{read\\_length}\n\\end{gathered}\n\\end{equation}\n\\begin{equation}\n\\begin{gathered}\ninsertion\\_rate = \\dfrac{n\\_insertions}{read\\_length}\n\\end{gathered}\n\\end{equation}\n\n\\begin{equation}\n\\begin{gathered}\nmatch\\_rate  + snp\\_rate + insertion\\_rate = 1\n\\end{gathered}\n\\end{equation}\n\nDeletion rate is defined as a total number of deletions in the alignment over the length of the aligned read. \n\n\\begin{equation}\n\\begin{gathered}\ndeletion\\_rate = \\dfrac{n\\_deletion}{read\\_length}\n\\end{gathered}\n\\end{equation}\n\n\nTo get reliable results, this is done on both ecoli test dataset and lambda dataset. \nFor each basecaller, median, mean and variance of all aligned reads are calculated. To summarize the results, the median is used as a single value as it is robust and even more informative in the case of skewed distributions like these.  Results expressed as percentages are shown in the table \\ref{tbl:ecoli_rates} for ecoli and table \\ref{tbl:lambda_rates} for lambda dataset. \n\nDeveloped tool shows promising results by having better match rate and smaller mismatch rate than the others. \nBoth datasets show all basecallers being biased towards deletions than insertions but this possibly is the bias of the used aligner. To eliminate that possibility, tests were repeated using \\textit{BWA mem} aligner\\footnote{https://github.com/lh3/bwa} with almost identical results. Results using BWA aligner are shown in tables\n\\ref{tbl:ecoli_rates_bwa} and \\ref{tbl:lambda_rates_bwa}. Results are consistent on both datasets using both aligners.\n\n\n\n\\begin{table}[htb]\n\t\\caption{Alignment specifications of Ecoli R9 basecalled reads using GraphMap}\n\t\\label{tbl:ecoli_rates}\n\t\\centering\n\t\\begin{tabular}{lcccc}\n\t\t\\toprule\n\t\t{} &  \\thead{Match \\% \\\\(median)} &  \\thead{Mismatch \\% \\\\(median)} &  \\thead{Insertion \\% \\\\(median)} &  \\thead{Deletion \\% \\\\(median)} \\\\\n\t\t\\midrule\n\t\t\n\t\tDeepNano   &                  90.254762 &                      6.452852 &                       \\textbf{3.274420} &                     11.829965 \\\\\n\t\tMetrichor  &                  90.560455 &                      5.688105 &                       3.660381 &                      8.328271 \\\\\n\t\tNanonet    &                  90.607674 &                      5.608912 &                       3.652791 &                      8.299046 \\\\\n\t\tresdeep    &                  \\textbf{91.408591} &                     \\textbf{ 5.019141} &                       3.477739 &                      \\textbf{7.471608 }\\\\\n\t\t\\bottomrule\n\t\\end{tabular}\n\\end{table}\n\n\\begin{table}[htb]\n\t\\caption{Alignment specifications of Ecoli R9 basecalled reads using BWA mem}\n\t\\label{tbl:ecoli_rates_bwa}\n\t\\centering\n\t\\begin{tabular}{lcccc}\n\t\t\\toprule\n\t\t{} &  \\thead{Match \\% \\\\(median)} &  \\thead{Mismatch \\% \\\\(median)} &  \\thead{Insertion \\% \\\\(median)} &  \\thead{Deletion \\% \\\\(median)} \\\\\n\t\t\\midrule\n\t\tDeepNano   &                  90.254762 &                      6.452852 &                       3.274420 &                     11.829965 \\\\\n\t\tMetrichor  &                  90.595441 &                      6.869543 &                       2.531646 &                      7.567381 \\\\\n\t\tNanonet    &                  90.988989 &                      6.674760 &                     \\textbf{  2.348552} &                      7.698530 \\\\\n\t\tresdeep    &                 \\textbf{ 91.470588} &                      \\textbf{5.929204 }&                       2.477283 &                     \\textbf{ 6.970362} \\\\\n\t\t\\bottomrule\n\t\\end{tabular}\n\t\n\\end{table}\n\\begin{table}[htb]\n\t\\caption{Alignment specifications of Ecoli R9 basecalled reads using GraphMap}\n\t\\label{tbl:lambda_rates}\n\t\\centering\n\t\\begin{tabular}{lcccc}\n\t\t\\toprule\n\t\t{} &  \\thead{Match \\% \\\\(median)} &  \\thead{Mismatch \\% \\\\(median)} &  \\thead{Insertion \\% \\\\(median)} &  \\thead{Deletion \\% \\\\(median)} \\\\\n\t\t\\midrule\n\t\tDeepNano   &                  86.997687 &                      9.623494 &                       3.442490 &                     16.052830 \\\\\n\t\tMetrichor  &                  87.714988 &                      7.835052 &                       4.093851 &                     \\textbf{10.757491} \\\\\n\t\tNanonet    &                  88.415611 &                      8.178372 &                       3.629653 &                     11.793022 \\\\\n\t\tresdeep    &                 \\textbf{ 89.694482} &                     \\textbf{ 7.238095} &                       \\textbf{3.078796} &                     13.450292 \\\\\n\t\t\\bottomrule\n\t\\end{tabular}\n\t\n\t\n\t\n\t\n\\end{table}\n\\begin{table}[H]\n\t\\caption{Alignment specifications of lambda R9 basecalled reads using BWA mem}\n\t\\label{tbl:lambda_rates_bwa}\n\t\\centering\n\t\\begin{tabular}{lcccc}\n\t\t\\toprule\n\t\t{} &  \\thead{Match \\% \\\\(median)} &  \\thead{Mismatch \\% \\\\(median)} &  \\thead{Insertion \\% \\\\(median)} &  \\thead{Deletion \\% \\\\(median)} \\\\\n\t\t\\midrule\n\t\t\n\t\tDeepNano   &                  86.625973 &                     11.288361 &                       2.098225 &                     14.648308 \\\\\n\t\tMetrichor  &                  87.294093 &                     10.109186 &                       2.376476 &                      \\textbf{9.645323 }\\\\\n\t\tNanonet    &                  87.767037 &                     10.017598 &                       2.354248 &                     10.597232 \\\\\n\t\tresdeep    &                 \\textbf{ 89.049870} &                     \\textbf{ 9.480883} &                       \\textbf{1.615188 }&                     12.962441 \\\\\n\t\t\\bottomrule\n\t\\end{tabular}\n\t\n\\end{table}\n\n\nDistribution of these percentages per reads are shown using  histogram plot on figure \\ref{fg:hist} and the KDE (\\textit{kernel density estimate}) plot on igures \\ref{fg:ecoli_kde} and \\ref{fg:lambda_kde}. Like the histogram, the KDE plot encodes the density of observations, but curve approximation is used instead of bins resulting in less cluttered comparison. \nIt is important to note that lambda is small dataset and more samples are needed to get a better approximation of distribution.\n\n\\begin{figure}[!htb]\n\t\\begin{center}\n\t\t\\includegraphics[width=0.8\\textwidth]{./imgs/results/ecoli/hist_20.png}\n\t\t\\caption{Histogram showing distribution of percentage of alimnment operations for ecoli}\n\t\t\\label{fg:hist}\n\t\\end{center}\n\\end{figure}\n\n\\begin{figure}[!htb]\n\t\\begin{center}\n\t\t\\includegraphics[width=0.8\\textwidth]{./imgs/results/ecoli/kde_cigar.png}\n\t\t\\caption{KDE plot for distribution of percentage of alimnment operations for ecoli}\n\t\t\\label{fg:ecoli_kde}\n\t\\end{center}\n\\end{figure}\n\n\\begin{figure}[!htb]\n\t\\begin{center}\n\t\t\\includegraphics[width=0.8\\textwidth]{./imgs/results/lambda/hist_20.png}\n\t\t\\caption{Histogram showing distribution of percentage of alimnment operations for lambda}\n\t\t\\label{fg:hist}\n\t\\end{center}\n\\end{figure}\n\n\\begin{figure}[!htb]\n\t\\begin{center}\n\t\t\\includegraphics[width=0.8\\textwidth]{./imgs/results/lambda/kde_cigar_lines.png}\n\t\t\\caption{KDE plot for distribution of percentage of alimnment operations for lambda}\n\t\t\\label{fg:lambda_kde}\n\t\\end{center}\n\\end{figure}\n\\FloatBarrier\n\nThe histogram on figure \\ref{fg:cigar_op_dist} shows how matches, mismatches, insertions, and deletions are distributed across the read. It is shown that mismatches and insertion occur more frequently at the beginnings and the ends of the reads. This is not only the case for the developed basecaller, but all other show the same property. This could be due to lack of context information from both sides when edges are base called.\n\n\\begin{figure}[!ht]\n\t\\begin{center}\n\t\t\\includegraphics[width=1\\textwidth]{./imgs/operation_distributed_r9.png}\n\t\t\\caption{Histogram of alignment operations over relative position inside of read}\n\t\t\\label{fg:cigar_op_dist}\n\t\\end{center}\n\\end{figure}\n\n\n\n\n\n\\section{Consensus}\nDescribed error rates and match rates calculated from alignments of individual reads to the reference could be misleading as it is simple to produce a naive model that obtains excellent results. Let us consider a model that basecalls single base \"A\" for every input signal. Aligning \"A\" to the reference (supposing that the aligner does not discard short and highly ambiguous reads) will always return perfect alignment as nucleotide \"A\" is certainly present in the reference. This model would have a perfect match rate with non-existent mismatches, insertions, and deletions. Two other approaches are used, in addition to the first, to give a more rigorous comparison.\n\nThe idea behind other approaches is checking if the reconstruction of the reference is possible from the basecalled reads and closely does it match the original reference.\n\n\\subsection{Consensus from pileup}\n Instead of going through the whole assembly process, as we know the reference genome of the data used in these tests, we simply align all the reads to the genome, stack them on top of each other forming pileup of read bases. Using majority vote, dominant bases are called on each position. The resulting sequence is called consensus. When calling consensus for deletions,  there has to be a majority of deletions of the same length. Calling insertions has the additional condition,  the majority has to agree on both length and the bases of insertion. Figure \\ref{fg:consensus} shows how consensus is called from pileup created from aligned reads. Pileup is stored in mpileup format.  \n\n\n\\begin{figure}[!ht]\n\t\\begin{center}\n\t\t\\includegraphics[width=0.8\\textwidth]{./imgs/consnesus.png}\n\t\t\\caption{Consensus from pileup}\n\t\t\\label{fg:consensus}\n\t\\end{center}\n\\end{figure}\n\n\nSimilarly, as before, match rate, mismatch rate, insertion and deletion rates are calculated but this time for whole consensus sequence. In this context, mismatches are called \\textit{single nucleotide polymorphisms} (snp).\n\n\n\n\\begin{equation}\n\\begin{gathered}\nmatch\\_rate = \\dfrac{n\\_correct\\_bases}{consensus\\_length}\n\\end{gathered}\n\\end{equation}\n\\begin{equation}\n\\begin{gathered}\nsnp\\_rate = \\dfrac{n\\_snp}{consensus\\_length}\n\\end{gathered}\n\\end{equation}\n\\begin{equation}\n\\begin{gathered}\ninsertion\\_rate = \\dfrac{n\\_insertions}{consensus\\_length}\n\\end{gathered}\n\\end{equation}\n\n\\begin{equation}\n\\begin{gathered}\nmatch\\_rate  + snp\\_rate + insertion\\_rate = 1\n\\end{gathered}\n\\end{equation}\n\n\n\\begin{equation}\n\\begin{gathered}\ndeletion\\_rate = \\dfrac{n\\_deletion}{consensus\\_length}\n\\end{gathered}\n\\end{equation}\n\nResults are shown in the tables \\ref{tbl:spec_ecoli}  for ecoli and \\ref{tbl:spec_lambda} for lambda. \nDeveloped model shows results comparable with Metrichor in all aspects (matches, mismatches, insertions, deletions and the total length of the consensus sequence) for lambda and show even better results from ecoli. \n\n\\begin{table}[htb]\n\t\\caption{Consensus specifications of Ecoli R9 basecalled reads}\n\t\\label{tbl:spec_ecoli}\n\t\\centering\n\t\n\t\\begin{tabular}{lcccccc}\n\t\t\\toprule\n\t\t{} &  \\thead{Total called\\\\\\lbrack bp\\rbrack} &  \\thead{Correctly called\\\\\\lbrack bp\\rbrack} &  \\thead{Match\\\\\\%} &  \\thead{Snp\\\\\\%} &  \\thead{Insertion\\\\\\%} &  \\thead{Deletion\\\\\\%} \\\\\n\t\t\\midrule\n\t\tDeepNano  &                  1510244.0 &                      1493242.0 &          98.8742 &         1.0044 &               0.1214 &              0.9041 \\\\\n\t\tMetrichor &                  1515893.0 &                      1502588.0 &          99.1223 &         0.7464 &               0.1313 &              0.6300 \\\\\n\t\tNanonet   &                  1414237.0 &                      1385515.0 &          97.9691 &         1.5700 &               0.4609 &              1.5158 \\\\\n\t\tresdeep   &                  1517828.0 &                      1506233.0 &          \\textbf{99.2361} &         \\textbf{0.6474} &               \\textbf{0.1165} &             \\textbf{ 0.5510 }\\\\\n\t\t\\bottomrule\n\t\\end{tabular}\n\t\n\\end{table}\n\n\\begin{table}[htb]\n\t\\caption{Consensus specifications of lambda R9 basecalled reads}\n\t\\label{tbl:spec_lambda}\n\t\\centering\n\t\n\t\\begin{tabular}{lcccccc}\n\t\t\\toprule\n\t\t{} &  \\thead{Total called\\\\\\lbrack bp\\rbrack} &  \\thead{Correctly called\\\\\\lbrack bp\\rbrack} &  \\thead{Match\\\\\\%} &  \\thead{Snp\\\\\\%} &  \\thead{Insertion\\\\\\%} &  \\thead{Deletion\\\\\\%} \\\\\n\t\t\\midrule\n\t\tDeepNano  &                    48342.0 &                        48025.0 &          99.3443 &         0.6433 &               \\textbf{0.0124} &              0.2648 \\\\\n\t\tMetrichor &                    48469.0 &                        48257.0 &          \\textbf{99.5626} &         \\textbf{0.4188} &               0.0186 &              \\textbf{0.1465} \\\\\n\t\tNanonet   &                    48438.0 &                        48168.0 &          99.4426 &         0.5409 &               0.0165 &              0.1961 \\\\\n\t\tresdeep   &                    48385.0 &                        48163.0 &          99.5412 &         0.4402 &               0.0186 &              0.1976 \\\\\n\t\t\\bottomrule\n\t\\end{tabular}\n\\end{table}\n\nAll models show a slight bias towards deletions than insertions, but this may be the limitation of technology as it has been reported that deletion and mismatch rates for nanopore data are ordinarily higher than insertion rates \\cite{sovic}.\n\n\\subsection{Assembly}\nIn this evaluation method, consensus sequence is not calculated from pileup, but by \\textit{de novo} genome assembly. For this task, fast and accurate \\textit{de novo} genome assembler \\textit{ra}\\footnote{\\url{https://github.com/rvaser/ra}} \\cite{vaser} was used and obtained consensus sequence is compared to the reference using \\textit{dnadiff} present in the \\textit{Mumer}\\footnote{\\url{https://github.com/garviz/MUMmer}}. \nThe length of the reference, consensus sequence, number of contigs and percentages of aligned bases from the reference to the query and vice versa are shown in the table \\ref{tbl:assembly}. Average identity summarizes how closely does the assembled sequence match the reference. This is run on full ecoli sequence run for 1D template reads (\\textasciitilde 160k reads), for both developed tools, Nanonet and Metrichor. Developed tool has shown a small increase in quality of the assembled sequence over Metrichor by offering longer consensus, higher identity percentage, and overall smaller edit distance\\footnote{Calculated using \\url{https://github.com/isovic/racon/blob/master/scripts/edcontigs.py}}.\n\n\n\\begin{table}[htb]\n\t\\caption{Assembly and consensus results for ecoli}\n\t\\label{tbl:assembly}\n\t\\centering\n\n\\begin{tabular}{lccc}\n\\toprule\n&         Metrichor &           resdeep &          Nanonet \\\\\n\\midrule\n\\thead{Ref. genome size (bp)} &           4639675 &           4639675 &            4639675 \\\\\n\\thead{Total bases (bp)}      &           4604806 &           \\textbf{4614354} &          4600056 \\\\\n\\thead{Contigs [\\#]}           &                 1 &                 1 &                1 \\\\\n\\thead{Aln. bases ref. (bp)}  &  4639641(100.00\\%) &  4639612(100.00\\%) &  4639031(99.99\\%) \\\\\n\\thead{Aln. bases query (bp)} &  4604787(100.00\\%) &  4614351(100.00\\%) &  4599745(99.99\\%) \\\\\n\\thead{Avg. Identity}         &             98.76 &             \\textbf{99.06} &            98.47 \\\\\n\\thead{Edit distance}         &             60418 &             \\textbf{46686 }&            74341 \\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n\n\n\\section{Read lengths}\nThe lengths of basecalled reads for each tool are interesting to analyze. Developed tool output reads of lengths similar to Metrichor while other tools, such as Nanonet, for instance, basecall reads that are significantly shorter. Detailed analysis of read length distributions is shown using KDE plots on figure \\ref{fg:r_lens} for both lambda and ecoli.\n\n\n\\begin{table}[htb]\n\t\\caption{Ecoli R9 basecalled read lengths in base pairs}\n\t\\label{tbl:ecoli_lens}\n\t\\centering\n\t\n\t\\begin{tabular}{lccc}\n\t\t\\toprule\n\t\t{} &  \\thead{median} &   \\thead{mean} &    \\thead{std} \\\\\n\t\t\\midrule\n\t\tDeepNano   &        5526.5 &  8126.694000 &  7406.554786 \\\\\n\t\tMetrichor  &        5809.5 &  8933.275000 &  9189.709720 \\\\\n\t\tNanonet    &        3286.5 &  4874.406582 &  4803.182344 \\\\\n\t\tresdeep    &        5784.0 &  8990.988989 &  9297.972688 \\\\\n\t\t\\bottomrule\n\t\\end{tabular}\n\\end{table}\n\n\n\\begin{table}[htb]\n\t\\caption{Lambda R9 basecalled read lengths in base pairs}\n\t\\label{tbl:ecoli_lens}\n\t\\centering\n\t\n\t\\begin{tabular}{lccc}\n\t\t\\toprule\n\t\t{} &  \\thead{median} &    \\thead{mean} &    \\thead{std} \\\\\n\t\t\\midrule\n\t\tDeepNano   &        4740.0 &   4664.750000 &  2628.512543 \\\\\n\t\tMetrichor  &        5491.0 &   5482.952941 &  2748.446253 \\\\\n\t\tNanonet    &        4931.5 &   4925.804878 &  2739.987512 \\\\\n\t\tresdeep    &        5229.0 &   5138.764706 &  2605.958080 \\\\\n\t\t\\bottomrule\n\t\\end{tabular}\n\\end{table}\n\n\\begin{figure}[!ht]\n\t\\begin{center}\n\t\t\\includegraphics[width=1\\textwidth]{./imgs/lens_lines.png}\n\t\t\\caption{Overview of evaluation pipeline}\n\t\t\\label{fg:r_lens}\n\t\\end{center}\n\\end{figure}\n\n\\section{Base calling speeds}\nTable \\ref{tbl:speeds} shows base calling speeds of all tools. Metrichor is present in the table as it is cloud-based service and real execution time is unknown. Tests for all other basecallers were run under same conditions on hardware described in section \\ref{sec:tech}. All tested tools offer parallelized base calling so a number of jobs(threads) during testing was set to 32. Both the developed model and Nanonet provide GPU support for base calling, while DeepNano is limited for CPU only.\n\nDeveloped tool has shown faster base calling times in both CPU and GPU group even though it is very deep network of 144 layers. This shows efficiency of CNNs compared with RNNs. Differences in base calling speeds for ecoli and lambda datasets do exist, but they are not substantial and may be contributed to the different length of the reads and the different total number of reads in datasets. \n\n\\begin{table}[htb]\n\t\\caption{Base calling speeds measured in \\textit{base pairs per second}}\n\t\\label{tbl:speeds}\n\t\\centering\n\t\n\t\\begin{tabular}{lcc}\n\t\t\\toprule\n\t\t{} &  \\thead{ecoli (bp/s)} &  \\thead{lambda (bp/s)} \\\\ \n\t\t\\midrule\n\t\tresdeep (CPU)  &               \\textbf{1174.28} &              \\textbf{ 1363.340 }\\\\\n\t\tNanonet (CPU)  &                856.01 &                897.499 \\\\\n\t\tDeepNano (CPU) &                626.99 &                692.370 \\\\\n\t\t\\midrule\n\t\tresdeep (GPU)  &              \\textbf{ 6571.76 }&              \\textbf{ 6140.300} \\\\\n\t\tNanonet (GPU)  &               3828.39 &               3787.510 \\\\\n\t\t\\bottomrule\n\t\\end{tabular}\n\t\n\\end{table}\n\n\\section{Evaluation pipeline}\nEntire evaluation pipeline is shown in figure \\ref{fg:eval_pipe}.  GraphMap was used for alignment purposes and SAMTools for conversion between SAM and its binary variant BAM as well as a generation of mpileup.\n\n\\begin{figure}[!ht]\n\t\\begin{center}\n\t\t\\includegraphics[width=0.7\\textwidth]{./imgs/evaluation_pipeline.png}\n\t\t\\caption{Overview of evaluation pipeline}\n\t\t\\label{fg:eval_pipe}\n\t\\end{center}\n\\end{figure}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% CHAPTER\n\\chapter{Conclusion}\n\n\n\nThe goal of this thesis was to show that usage of convolution neural networks can potentially replace RNNs in the analysis of sequencing data by offering better results as well as faster execution times.\n\nOn all tests, proposed model has shown improvement in the accuracy of basecalled data as well as faster basecalling speeds of over both official (Matrichor and experimental Nanonet) and  third-party DeepNano while having. \nTo provide definite proof of this claim, the model needs to be tested on larger datasets from different sequencing runs for multiple organisms.\n\nAll test are done on data for R9 chemistry, but the developed code could easily be adjusted and trained on R9.4 and newest R9.5 data when it becomes publicly available.\nIt would be interesting to see how well this approach works compare to basecaller Scrappie by Oxford Nanopore that addresses detection of homopolymers.\n\nCurrently, without support for newer sequencing data, this model has limited application. \nIt can be used as a demonstration of a different approach to base calling which yields promising results.  As newer versions of basecallers by Oxford Nanopore do not offer any support for data sequenced with previous version of chemistries, this tool can be used to re-basecall that data and improvement of the quality of reads.\n\nFuture work includes experiments with recently proposed \\textit{scaled exponential linear units} (SELU) \\cite{selu} that eliminates the need for normalization techniques such as used batch normalization. Possible improvements of the model include the combination of convolutions and attention mechanism proposed just recently in the paper \\cite{facebook} showing excellent results in both speed and accuracy, for tasks of language translation. \n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% DONE\n\\bibliography{references}\n\\bibliographystyle{unsrtnat}\n\\begin{abstract}\n\n\nMinION by Oxford Nanopore Technologie is affordable and portable sequencing device suitable for various applications. The device produces very long reads, however, it suffers from high sequencing error rate. \nThe goal of this thesis is to show that the reported accuracy of the sequencing data is not only limited by sequencing technology, but also by the current software tools used for base calling and can be further improved by using different deep learning concepts.\nApproach for base calling of raw data using convolutional neural networks is proposed as an alternative to recurrent neural networks used by other basecallers offering improvements both in  speed and accuracy. A detailed comparison of the developed tool with the existing tools for base calling R9 data is given.\n\n\\keywords{base calling, Oxford Nanopore Technologies, MinION, deep learning, seq2seq, convolutional neural network, residual network, CTC loss}\n\\end{abstract}\n\n\\hrtitle{Model dubokog učenja za određivanje očitanih baza dobivenih uređajem za sekvenciranje MinION}\n\\begin{sazetak}\n\n\nUređaji za sekvenciranje MinION tvrtke Oxford Nanopore Technologies su pristupačni i prenosivi što ih čini pogodnim za razne primjene. \nUređaj omogućuje sekvenciranje očitanja velikih duljina ali većeg postotka greške u odnosu na prethodne tehnologije.\nCilj ovog diplomskog rada je pokazati da trenutna pogreška nije uzrokovana isključivo metodom sekvenciranja, već i programskim alatima koji se koriste za očitavanje baza te je pogrešku moguće smanjiti korištenjem metoda dubokog učenja.\n\nPredstavljen je novi alat za očitavanje baza temeljen na konvolucijskim neuronski mrežama koji pruža napredak u preciznosti i brzini u odnosu na trenutno korištene rekurzivne neuronske mrežama. U radu je dana detaljna analiza razvijenog alata i usporedba s postojećim rješenjima za određivanje očitanih baza.\n\n\\kljucnerijeci{određivanje baza, Oxford Nanopore Technologies, MinION, duboko učenje, prevođenje, konvolucijske neuronske mreže, rezidualne mreže, CTC gubitak}\n\\end{sazetak}\n\n\\end{document}\n", "meta": {"hexsha": "bc23232ba0242b431444db5dfe7977f5d12e9519", "size": 66572, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/diplomski_en.tex", "max_stars_repo_name": "mratkovic/masters-thesis", "max_stars_repo_head_hexsha": "a73e1ccc27f600b7c73bb876e5977a5a92366c72", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-08-05T15:27:58.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-13T20:38:53.000Z", "max_issues_repo_path": "tex/diplomski_en.tex", "max_issues_repo_name": "mratkovic/masters-thesis", "max_issues_repo_head_hexsha": "a73e1ccc27f600b7c73bb876e5977a5a92366c72", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/diplomski_en.tex", "max_forks_repo_name": "mratkovic/masters-thesis", "max_forks_repo_head_hexsha": "a73e1ccc27f600b7c73bb876e5977a5a92366c72", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-03-24T22:40:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-01T09:06:47.000Z", "avg_line_length": 63.5835721108, "max_line_length": 703, "alphanum_fraction": 0.7382533197, "num_tokens": 16947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.32471261185990175}}
{"text": "% This is based on the LLNCS.DEM the demonstration file of % the LaTeX macro\n% package from Springer-Verlag % for Lecture Notes in Computer Science, version\n% 2.4 for LaTeX2e as of 16. April 2010\n%\n% See http://www.springer.com/computer/lncs/lncs+authors?SGWID=0-40209-0-0-0\n% for the full guidelines.\n\\documentclass{llncs}\n\n \\addtolength{\\oddsidemargin}{-.875in}\n \\addtolength{\\evensidemargin}{-.875in}\n \\addtolength{\\textwidth}{1.75in}\n\n \\addtolength{\\topmargin}{-.875in}\n \\addtolength{\\textheight}{1.75in}\n\n\\usepackage{graphicx}\n\\graphicspath{ {./assets/} }\n\n\\usepackage{enumitem}\n\\setlist[enumerate]{itemsep=2mm}\n\n\\usepackage{dirtytalk}\n\\usepackage{minted}\n%\\usepackage{amsmath}\n\\usepackage{mathtools}\n\\usepackage{amsfonts}\n\\usepackage{extarrows}\n\\usepackage{pdflscape}\n\\usepackage[pass]{geometry}\n\n%\n% Tables\n% --------\n\\usepackage[table]{xcolor}\n\\usepackage{hhline}\n\\usepackage{booktabs} % much better tables\n\\usepackage{multirow} % allows to fuse rows\n\\usepackage{array}    % manipulate array\n\\usepackage{tabularx} % better tables\n\n% Define new tabularx column types:\n%  - R: stretched right aligned\n%  - C: stretched centered\n%  - N: left aligned, specified space\n\\newcolumntype{R}{>{\\raggedleft\\arraybackslash}X}\n\\newcolumntype{C}{>{\\centering\\arraybackslash}X}\n\\newcolumntype{N}[1]{>{\\raggedleft\\arraybackslash}p{#1}}\n\\newcolumntype{S}{>{\\hsize=.5\\hsize}C}\n\n% Set row height multiplier to provide more breathing space\n\\renewcommand{\\arraystretch}{1.5}\n\n\\usepackage[backend=biber]{biblatex}\n\\addbibresource{bibliography.bib}\n\n\\pagestyle{plain}\n\\setcounter{page}{1}\n\\pagenumbering{arabic}\n\n%\\usepackage{pgfplots}\n%\\pgfplotsset{width=6cm}\n\\usepackage{float}\n\\usepackage[caption = false]{subfig}\n\n\\newcommand{\\BTX}{\\texttt{BTX}}\n\\newcommand{\\XTX}{\\texttt{XTX}}\n\n\\newcommand{\\Enc}{\\textsf{Enc}}\n\\newcommand{\\EncGen}{\\textsf{EncGen}}\n\\newcommand{\\EncSign}{\\textsf{EncSign}}\n\\newcommand{\\EncVer}{\\textsf{EncVrfy}}\n\n\\newcommand{\\DecSig}{\\textsf{DecSig}}\n\\newcommand{\\KeyGen}{\\textsf{Gen}}\n\\newcommand{\\Sign}{\\textsf{Sign}}\n\\newcommand{\\Verify}{\\textsf{Vrfy}}\n\\newcommand{\\Rec}{\\textsf{Rec}}\n\\newcommand{\\RecKey}{\\textsf{RecKey}}\n\\newcommand{\\hatsigma}{\\hat{\\sigma}}\n\n\\newcommand{\\DLGen}{\\textsf{DLGen}}\n\\newcommand{\\DLProve}{\\textsf{DLProve}}\n\\newcommand{\\DLVrfy}{\\textsf{DLVrfy}}\n\n\\newcommand{\\InitTx}{\\textsf{InitTx}}\n\\newcommand{\\SignTx}{\\textsf{SignTx}}\n\\newcommand{\\VrfyTx}{\\textsf{VrfyTx}}\n\\newcommand{\\PubTx}{\\textsf{PubTx}}\n\\newcommand{\\WatchTx}{\\textsf{WatchTx}}\n\\newcommand{\\RecSig}{\\textsf{RecSig}}\n\n\\newcommand{\\skSign}{sk_S}\n\\newcommand{\\pkSign}{pk_S}\n\\newcommand{\\kSign}{(\\skSign,\\pkSign)}\n\\newcommand{\\skEnc}{sk_E}\n\\newcommand{\\pkEnc}{pk_E}\n\\newcommand{\\kEnc}{(\\skEnc, \\pkEnc)}\n\\newcommand{\\rec}{\\delta}\n\n\\newcommand{\\bin}{\\{0,1\\}}\n\n\\newcommand{\\GG}{\\mathbb{G}}\n\\newcommand{\\HH}{\\mathbb{H}}\n\n\\begin{document}\n\n\\title{Bitcoin--Monero Cross-chain Atomic Swap}\n\\author{Jo\\\"el Gugger}\n\n\\authorrunning{Jo\\\"el Gugger et al.}\n\\tocauthor{Jo\\\"el Gugger}\n\\institute{\\email{h4sh3d@protonmail.com}}\n\n\\maketitle\n\n\\begin{abstract}\n    In blockchains where hashed timelock contracts are possible atomic swaps are already deployed, but when one of the blockchains doesn't have this capability it becomes a challenge. This protocol describes how to achieve atomic swaps between Bitcoin and Monero with two transactions per chain without trusting any central authority, servers, nor the other swap participant.\n    We propose a swap between two participants, one holding bitcoin and the other monero, in which when both follow the protocol their funds are not at risk at any moment. The protocol does not require timelocks on the Monero side nor script capabilities but does require two proofs of knowledge of equal discrete logarithm across  the \\texttt{edward25519} and the \\texttt{secp256k1} groups and \\texttt{ECDSA} one-time VES.\n    \\keywords{Blockchain, Atomic Swap, Cross-Chain Transactions, Bitcoin, Monero}\n\\end{abstract}\n\n\\section{Introduction}\nWe describe a protocol for an on-chain atomic swap between Monero and Bitcoin, but the protocol can be generalized for any cryptocurrency that fulfills the same requirements as Monero to any other cryptocurrency that fulfills the same requirements as Bitcoin. For an exhaustive list of prerequisites, see chapter \\ref{prerequisites}.\n\nParticipants send funds into a specific address generated during the process (the lock) on each chain (cross-chain) where each party can take control of the funds on the other chain (swap) atomically (i.e. claiming of funds on either chain is mutually exclusive from the ability to claim funds from the other chain.)\n\nDuring this process participants do not expose their funds if they follow the protocol accordingly, meaning that the swap is trustless and does not require any sort of collateral, allowing two strangers to trade without risks nor the help of a third-party.\n\n\\section{Scenario}\nWe describe the participants and their incentives. Alice, who owns monero (XMR), and Bob, who owns bitcoin (BTC), want to swap funds. We assume that they already have negotiated the price in advance (i.e. amount of bitcoin for amount of monero to swap.) This negotiation can also be integrated into the protocol, for example by swap services who provide a price to their customers.\n\nBoth participants wish to only have two possible execution paths (which are mutually exclusive to each other) when executing the protocol: (1) the protocol succeeds and Alice gets bitcoin, Bob gets monero, or (2) the protocol fails and both keep their original funds minus the minimum transaction fees possible.\n\n\\subsection{Successful swap}\nIf both participants follow the protocol there will be four transactions broadcast in total---only three if the Monero are not moved directly after completion, which is not a problem---, two on the Bitcoin blockchain and two on the Monero blockchain. The first ones on each chain lock the funds and make them ready for the trade on each chain. The second ones unlock the funds for one participant only and give knowledge to the other participant who takes control of the output on the other chain.\n\nThis is the optimal execution of the protocol, requiring no timelocks, the minimum number of transactions and only locking funds for the minimum confirmation on each chain depending on the level of security expected by each participant, i.e. how many confirmations each expects for the funding transaction to be considered final and continue to the following step of the protocol.\n\n\\subsection{Swap correctly aborted}\nWhen locking the bitcoin, after a timelock, Alice or Bob can start the process of refunding the locked funds. At that moment the monero might not be locked yet. If no monero are locked, the refund process will just refund the bitcoin; otherwise Alice will learn enough information to refund her monero too.\n\nWhen the refund transaction is broadcast Bob must spend the refund before some timelock, otherwise he might end up loosing his bitcoin without getting any monero.  We can describe this as an interactive protocol from Bob's perspective, i.e. Bob cannot go offline -- he must react to such a situation during the swap. Alice, on the other hand, can remain offline.\n\n\\subsection{Worst case scenario}\nIf the swap is cancelled with the refund process and Bob does not spend his refund before the timelock, Alice can claim the refund without revealing the knowledge needed for Bob to claim on the other chain. Thus one participant, Bob, ends up disadvantaged and three Bitcoin transactions are needed instead of two.\n\n\\subsubsection{Rationale}\n\\label{worstCaseRationale}\nThis choice is made to avoid the following case: if the monero are locked, Alice will be able to refund them if and only if Bob refunds his bitcoin first. We need an incentive mechanism to force Bob to spend his refund to prevent a deadlock in the refund process or compensate Alice if Bob does not follow the protocol correctly.\n\nOtherwise Bob, with all the information already learned, can go offline and move his bitcoin a year after the swap, forcing Alice to consistently monitor the chain until she sees Bob's transaction and learns the last piece of knowledge she needs to unlock her monero.\n\n\\section{Prerequisites}\n\\label{prerequisites}\nAs previously described, conditional execution must be possible in order to achieve a swap with atomicity. Bitcoin has a simple stack-based script language that allows for conditional execution and timelocks. On the other hand, at the moment, Monero's privacy oriented RingCT design provides only signatures to unlock UTXOs. Control of UTXOs is only related to who controls the associated private keys. The challenge is then to move control of funds only with knowledge of some private keys.\n\nIn this chapter we discuss all the required pieces needed on both chains and off-chain to achieve an atomic swap under the previously exposed scenario.\n\n\\subsection{Monero}\nMonero does not require any particular on-chain primitives (hashlocks, timelocks), all building blocks are off-chain primitives. Thus we need to provide proofs of the correct initialization of the protocol such as described in chapter \\ref{eqDiscreteLog}: those proofs will ensure the swap atomicity for each participant.\n\n\\subsubsection{Secret shares,}\nto enable a basic two-path execution in Monero. The Monero private spend key is split into two secret shares $k^s_a$ and $k^s_b$. Participants will not use any multi-signature protocol; instead, the private spend key shares are distributed during initialization of the swap process where one participant will gain knowledge of the full key $k^s \\equiv k^s_a + k^s_b \\pmod l$ at the end of the protocol execution, either for a completed swap or for an aborted swap.\n\n\\subsection{Bitcoin}\n\\label{bitcoinPrerequisites}\nThe bitcoin transactions in this protocol require the fix for transaction malleability provided by the \\texttt{SegWit} upgrade.  This allows us to chain transactions without necessarily broadcasting them. This protocol is only compatible with cryptocurrencies which use a bitcoin style \\texttt{UTXO} model and have an equivalent malleability fix such as Litecoin (i.e. Bitcoin Cash is not compatible.)\n\n\\subsubsection{Timelock,}\nto enable new execution paths after some predefined amount of time, e.g. start the refund process after having locked funds on-chain without creating a race condition. It is worth noting that we do not require timelocks for the other chain.\n\n\\subsubsection{Hashlock,}\nto syncronize both chains before allowing one to start the swap.\n\n\\subsubsection{2-of-2 multisig,}\nto create a common path accessible only by the two participants if both agree. In this protocol we use the on-chain option in the context of Bitcoin, but off-chain multi-signature schemes are more efficient and should be preferred in other setups.\n\n\\subsubsection{Semi-Scriptless protocol,}\nto reveal a secret and allow the protocol to continue execution without requiring complex scripting capabilities. We use ECDSA one-time VES such as described in \\ref{oneTimeEcdsaVES}. It is worth noting that full scriptless script \\cite{poelstra-adaptor} protocol should be able to achieve the same results with better efficiency.\n\n\\subsection{Equal discrete logarithm across groups zero-knowledge proof of knowledge}\nEqual discrete logarithm across groups zero-knowledge proof of knowledge, as described in technical note \\cite{MRL0010}, allow the verification of a common discrete logarithm $\\alpha$ given two groups with fixed generators $G \\in \\GG$ and $H \\in \\HH$, where $\\alpha \\leq min(|G|,|H|)$, such that given $xG$ and $yH$: $x=y=\\alpha$.\n\nIn this context we focus on groups \\texttt{edward25519} with $|G| = l$ and \\texttt{secp256k1} with $|H| = n$.\n\n\\begin{definition}[Equal discrete logarithm across groups scheme]\n    An equal discrete logarithm across groups scheme is defined with two algorithms under the parameter tuple $(\\GG,\\HH,G,G',H,H')$:\n\\begin{itemize}\n    \\item $\\DLProve(\\alpha) \\rightarrow (\\phi,A,B)$: A probabilistic proving algorithm which on input of a discrete logarithm $\\alpha$ outputs a proof $\\phi$, a point $A \\in \\GG$, and a point $B \\in \\HH$.\n    \\item $\\DLVrfy(\\phi,A,B) \\rightarrow \\{0,1\\}$: A deterministic proof verification algorithm which on input of a proof $\\phi$, a point $A \\in \\GG$, and a point $B \\in \\HH$ outputs 1 if and only if $(A,B)$ share a common discrete logarithm across their respective groups.\n\\end{itemize}\n\\end{definition}\n\n\\subsubsection{Curve parameters}\n\\label{curveParams}\nBitcoin and Monero do not use the same elliptic curves. Bitcoin uses the \\texttt{secp256k1} curve as defined in \\textit{Standards for Efficient Cryptography (SEC)} with the \\texttt{ECDSA} algorithm. Monero, based on the second version of CryptoNote \\cite{van2013cryptonote}, uses \\texttt{curve25519}, hereinafter also \\texttt{edward25519}, from Daniel J. Bernstein \\cite{CerRes10}.\n\nWe denote curve parameters for\n\n\\subsubsection{\\texttt{edward25519}} as\n\\begin{equation}\n\\begin{split}\n    q&: \\text{a prime number;}\\ q = 2^{255} - 19 \\\\\n    d&: \\text{an element of } \\mathbb{F}_q;\\ d = - 121665/121666 \\\\\n    \\mathcal{E}&: \\text{an elliptic curve equation};\\ -x^2 + y^2 = 1 + dx^2y^2 \\\\\n    G&: \\text{a base point};\\ G = (x, -4/5) \\\\\n    l&: \\text{the base point order};\\ l = 2^{252} + \\text{\\scriptsize27742317777372353535851937790883648493} \\\\\n\\end{split}\n\\end{equation}\n\n\\subsubsection{\\texttt{secp256k1}} as\n\\begin{equation}\n\\begin{split}\n    p&: \\text{a prime number;}\\ p = 2^{256} - 2^{32} - 977 \\\\\n    a&: \\text{an element of } \\mathbb{F}_p;\\ a = 0 \\\\\n    b&: \\text{an element of } \\mathbb{F}_p;\\ b = 7 \\\\\n    \\mathcal{E}'&: \\text{an elliptic curve equation};\\ y^2 = x^3 + ax + b \\\\\n    H&: \\text{a base point};\\ H = \\\\ (&\\texttt{\\scriptsize0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798},\\\\ &\\texttt{\\scriptsize0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8}) \\\\\n    n&: \\text{the base point order};\\ n = 2^{256} - \\text{\\scriptsize{432420386565659656852420866394968145599}} \\\\\n\\end{split}\n\\end{equation}\n\n\\subsection{\\texttt{ECDSA} one-time VES}\n\\label{oneTimeEcdsaVES}\n\\texttt{ECDSA} one-time VES are introduced by Fournier et al. in \\cite{oneTimeVES} as a generalization of the concept of adaptor signatures under \\texttt{Schnorr} \\cite{Schnorr:1989:EIS:646754.705037} and \\texttt{ECDSA}. One-time Verifiably Encrypted Signatures, hereinafter one-time VES, are VES constructed such that with knowledge of the ciphertext and the plaintext, it is possible to recover the encrypting key.\n\nWe recall some of the algorithms defined in \\cite{oneTimeVES} as:\n\n\\begin{definition}[\\texttt{ECDSA} one-time VES]\n    An \\texttt{ECDSA} one-time VES scheme contains:\n\\begin{itemize}\n    \\item $\\EncSign(\\skSign, \\pkEnc, m) \\hskip2.3pt{\\mbox{\\tiny${\\$}$\\normalsize}}\\!\\!\\rightarrow \\hatsigma$: A possibly probabilistic encrypted signing algorithm, which on input of a secret signing key $\\skSign$, a public encryption key $\\pkEnc$, and a message $m$, outputs a ciphertext $\\hatsigma$.\n    \\item $\\EncVer(\\pkSign, \\pkEnc, m, \\hatsigma) \\rightarrow \\bin$: A deterministic encrypted signature verification algorithm which --- on input of a public signing key $\\pkSign$, a public encryption key $\\pkEnc$, a message $m$ and a ciphertext $\\hatsigma$ --- outputs 1 if and only if $\\hatsigma$ is a valid encryption of a signature on $m$ for $\\pkSign$ under $\\pkEnc$.\n    \\item $\\DecSig(\\skEnc, \\hatsigma) \\rightarrow \\sigma$: A (usually) deterministic signature decryption algorithm which --- on input of a decryption key $\\skEnc$ and a valid ciphertext $\\hatsigma$ under that encryption key --- outputs a valid signature $\\sigma$.\n    \\item $\\RecKey(\\pkEnc, \\hatsigma) \\rightarrow \\delta$: A deterministic recovery key extraction algorithm which extracts a recovery key $\\delta$ from the ciphertext $\\hatsigma$ and the public encryption key $\\pkEnc$.\n    \\item $\\Rec(\\sigma,\\rec) \\rightarrow \\skEnc$: A deterministic decryption key recovery algorithm which --- when given a decrypted signature $\\sigma$ and the recovery key $\\rec$ associated with the original ciphertext --- returns the secret decryption key $\\skEnc$.\n\\end{itemize}\n\\end{definition}\n\n\\subsection{Generalization}\nAs shown in the Monero section, there are no on-chain requirements. We only make use of private key generation and addresses, meaning that this scheme can be generalized to any pair of cryptocurrencies where one fulfills the bitcoin prerequisites, making this scheme very chain agnostic, like \\cite{succinct-atomic-swap} (under the assumption of the above cryptographic primitives existence for the underlying chains' parameters). However, it is worth noting that other schemes are simpler and more efficient when, in the pair, both\nchains have on-chain capabilities, but such schemes are generally already deployed \\cite{atomic-swap, scriptless-atomic-swap, btcGrinSwap}.\n\n\\section{Protocol}\nThe overall protocol is as follows: Alice moves the monero into an address where each participant controls half of the private spend key (later referred to as key ``shares''). The Bitcoin scripting language is then used with semi-scriptless protocols to reveal one of the halves of the private spend key, depending on which participant claims the bitcoin. Depending on who reveals their half of the private spend key, the locked monero change ownership. Bitcoin transactions are designed in such a way\nthat if a participant follows the protocol, they can't terminate with a loss.\n\nIf the deal goes through, Alice spends the bitcoin by revealing her private key share, thus allowing Bob to spend the locked monero. If the deal is cancelled, Bob spends the bitcoin after the first timelock by revealing his private key share thus allowing Alice to spend the monero, in both cases minus transaction fees.\n\nKey exchange is performed with \\texttt{ECDSA} one-time VES---also adaptor signatures---, and equal discrete logarithm across groups zero-knowledge proofs of knowledge. One-time VES are constructed such that given the ciphertext and the decrypted signature, the decryption key is easily recoverable.\nBy setting the private key share---one half of the Monero full private spend key---as the decryption key we have a way to atomically sell the private key share to the other participant. Thus, because Bitcoin and Monero use different curves, we need to prove the relation between points on \\texttt{edward25519} and \\texttt{secp256k1} to ensure protocol trustlessness.\n\n\\subsection{Non-interactive refund}\nIf Alice and or Bob locked their funds but one of them aborts the swap, or stop communicating at some point, the protocol must not require interactivity to complete the refund procedure for both participants. Otherwise Alice can keep Bob hostage by not responding and wait for the second timelock to get free bitcoin. In a gracefully aborted swap, Bob should reveal his Monero private key share, allowing Alice to get her monero back through one one-time VES.\n\n\\texttt{ECDSA} one-time VES are interactive: one has to provide the encrypted signature, and if the verification succeeds, the counterparty provides a valid signature for the 2-of-2 Bitcoin multisig back---a.k.a semi-scriptless scripts---, thus allowing the former to decrypt and publish two valid signatures for the 2-of-2 multisig and the latter to learn---on-chain---the decrypted signature and recover the decryption key.\n\nAs mentioned before, the refund process must be non-interactive: The protocol is designed in such a way that Alice learns Bob's refund encrypted signature and provides to Bob a valid refund 2-of-2 multisig signature before locking the funds. Bob can, in the case of a refund, decrypt and publish the signature without Alice's cooperation.\n\n\\subsection{Monero private keys}\nMonero private keys are pairs of \\texttt{edward25519} scalars: One is the private view key and the other is the private spend key. We use small letters to denote private keys and capital letters for public keys such that\n$$X = xG$$\nwhere $G$ is the generator element of the group $\\GG$. We denote\n\\begin{enumerate}[label=(\\roman*)]\n    \\item the private key $k^v$ as the full private view key,\n    \\item $K^v$ as the full public view key,\n    \\item $k^v_a$ as the private view key share of Alice and $k^v_b$ of Bob,\n    \\item the private key $k^s$ as the full private spend key,\n    \\item $K^s$ as the full public spend key,\n    \\item and $k^s_a$ as the private spend key share of Alice and $k^s_b$ of Bob.\n\\end{enumerate}\n\n\\subsubsection{Partial keys}\nWe denote private key shares as $k^s_a$ and $k^s_b$ such that\n$$k^s_a + k^s_b \\equiv k^s \\pmod l$$\n\nAnd then\n\\begin{equation}\n\\begin{split}\n    k^s_aG &= K^s_a \\\\\n    k^s_bG &= K^s_b \\\\\n    K^s_a + K^s_b = (k^s_a + k^s_b)G = k^sG &= K^s\n\\end{split}\n\\end{equation}\n\nThe same holds for $k^v$ with $k^v_a$ and $k^v_b$.\n\n\\subsection{Zero-Knowledge proofs}\n\\label{eqDiscreteLog}\nZero-knowledge proofs are required at the beginning to make the protocol trustless. The protocol uses one-time VES to reveal private key shares, but we cannot check the discrete logarithm equality between the Monero public key share and Bitcoin public decryption key of the other participant before it goes on-chain. Thus we need to provide a proof that the discrete logarithm is the same across the two groups $\\GG$ and $\\HH$.\n\n\\subsubsection{Equal discrete logarithm across groups}\nAlice and Bob must prove to each other with\n\\begin{equation}\n\\begin{split}\n    k^s_i &\\leftarrow \\text{scalars on \\texttt{edward25519} and \\texttt{secp256k1} with an equivalent bit representation} \\\\\n    K^s_i &= k^s_iG \\in \\GG \\\\\n    B^s_i &= k^s_iH \\in \\HH \\\\\n\\end{split}\n\\end{equation}\n\nfor $i \\in \\{a, b\\}$, given $K^s_i$ and $B^s_i$ that\n\\begin{equation}\n\\begin{split}\n    \\exists k^s_i \\mid K^s_i = k^s_iG \\land B^s_i = k^s_iH \\land k^s_i < \\textsf{min}(l,n)\n\\end{split}\n\\end{equation}\n\n\\subsection{Time parameters}\nTwo timelocks $t_0, t_1$ are defined during the initialization phase. $t_0$ sets the time window during which it is safe to execute the trade: after $t_0$, the refund process may start, making the trade unsafe to complete due to a potential race condition (even if it is hard to exploit in reality). $t_1$ sets the response time during which Bob is required to react, reveal his private Monero share to get his bitcoin back, and allow Alice to redeem her monero (if monero have been locked). After $t_1$, Alice is able to claim the bitcoin unilaterally.\n\n\\subsection{Bitcoin scripts}\nTwo scripts are needed on the bitcoin side: the first is used to complete the swap or start the refund process---a.k.a \\texttt{SWAPLOCK}---, the second is used to complete the refund process---a.k.a \\texttt{REFUND}---. In a successful swap, the second script does not go on-chain and is not used. Each script defines two possible paths, and we consequently explain the four possible ways (\\textit{buy}, \\textit{refund}, \\textit{spend}, and \\textit{claim}) of spending the two \\texttt{UTXOs}.\n\n\\subsubsection{\\texttt{SWAPLOCK}}\nis a script used to lock funds and defines the two base execution paths: (1) swap execution---success---and (2) refund execution---fail---. We define the \\texttt{SWAPLOCK} script as:\n\n\\begin{minted}[escapeinside=||,mathescape=true]{text}\nOP_IF\n    OP_SHA256 <|$h_s$|> OP_EQUALVERIFY\n    2 <|$B_a$|> <|$B_b$|> 2 OP_CHECKMULTISIG\nOP_ELSE\n    <|$t_0$|> OP_CHECKSEQUENCEVERIFY OP_DROP\n    2 <|$B^r_a$|> <|$B^r_b$|> 2 OP_CHECKMULTISIG\nOP_ENDIF\n\\end{minted}\n\n\\subsubsection{Buy \\texttt{SWAPLOCK},}\nAlice takes control of the bitcoin and reveals her Monero key share to Bob with $\\sigma_1$ --- a one-time VES leaking $k^s_a$ --- thus allowing Bob to take control of the monero. $\\BTX_\\textit{buy}$ redeems the \\texttt{SWAPLOCK} with:\n\n\\begin{minted}[escapeinside=||,mathescape=true]{text}\nOP_0 <|$\\sigma_1$|> <|$\\sigma_2$|> <|$s$|> OP_TRUE <|\\texttt{SWAPLOCK} script|>\n\\end{minted}\n\n\\subsubsection{Refund \\texttt{SWAPLOCK},}\nsigned by both participants, and moves the funds into the \\texttt{REFUND} script. $\\BTX_\\textit{refund}$ redeems the \\texttt{SWAPLOCK} with:\n\n\\begin{minted}[escapeinside=||,mathescape=true]{text}\nOP_0 <|$\\sigma_r'$|> <|$\\sigma_r''$|> OP_FALSE <|\\texttt{SWAPLOCK} script|>\n\\end{minted}\n\n\\subsubsection{\\texttt{REFUND}}\nis a script used in case the swap already started on-chain but is cancelled. This refund script is used to move the funds out of the \\texttt{SWAPLOCK} script with the 2-of-2 timelocked multisig. We define the \\texttt{REFUND} script as:\n\n\\begin{minted}[escapeinside=||,mathescape=true]{text}\nOP_IF\n    2 <|$B^r_a$|> <|$B^r_b$|> 2 OP_CHECKMULTISIG\nOP_ELSE\n    <|$t_1$|> OP_CHECKSEQUENCEVERIFY OP_DROP\n    <|$B_a$|> OP_CHECKSIG\nOP_ENDIF\n\\end{minted}\n\n\\subsubsection{Spend \\texttt{REFUND},}\nBob cancels the swap and reveals his Monero private share with $\\sigma_1'$ --- a one-time VES leaking $k^s_b$ --- thus allowing Alice to regain control over her Monero. $\\BTX_\\textit{spend}$ redeem the \\texttt{REFUND} with:\n\n\\begin{minted}[escapeinside=||,mathescape=true]{text}\nOP_0 <|$\\sigma_1'$|> <|$\\sigma_2'$|> OP_TRUE <|\\texttt{REFUND} script|>\n\\end{minted}\n\n\\subsubsection{Claim \\texttt{REFUND},}\nAlice takes control of the bitcoin after both timelocks without revealing her Monero key share, resulting in Bob losing money for not following the protocol. $\\BTX_\\textit{claim}$ redeems the \\texttt{REFUND} with:\n\n\\begin{minted}[escapeinside=||,mathescape=true]{text}\n<|$sig_a$|> OP_FALSE <|\\texttt{REFUND} script|>\n\\end{minted}\n\n\\subsection{Transactions}\nWe describe and name the Bitcoin and Monero transactions that are needed for the entire protocol.\n\n\\subsubsection{$\\BTX_\\textit{lock}$,}\na Bitcoin transaction with $\\geq 1$ inputs from Bob and the first output (vout: 0) to the \\texttt{SWAPLOCK} script and optional change outputs.\n\n\\subsubsection{$\\BTX_\\textit{buy}$,}\na Bitcoin transaction with 1 input consuming the \\texttt{SWAPLOCK} script ($\\BTX_\\textit{lock}$, vout: 0) with the 2-of-2 semi-scriptless multisig and $\\geq 1$ outputs.\n\n\\subsubsection{$\\BTX_\\textit{refund}$,}\na Bitcoin transaction with 1 input consuming the \\texttt{SWAPLOCK} script ($\\BTX_\\textit{lock}$, vout: 0) with the 2-of-2 timelocked multisig and exactly one output to the \\texttt{REFUND} script.\n\n\\subsubsection{$\\BTX_\\textit{spend}$,}\na Bitcoin transaction with 1 input consuming the \\texttt{REFUND} script ($\\BTX_\\textit{refund}$, vout: 0) with the 2-of-2 semi-scriptless multisig and $\\geq 1$ outputs.\n\n\\subsubsection{$\\BTX_\\textit{claim}$,}\na Bitcoin transaction with 1 input consuming the \\texttt{REFUND} script ($\\BTX_\\textit{refund}$, vout: 0) with Alice signature and $\\geq 1$ outputs.\n\n\\subsubsection{$\\XTX_\\textit{lock}$,}\na Monero transaction that sends funds to the address $(K^v,K^s)$.\n\n\\subsubsection{$\\XTX_\\textit{buy}$,}\na Monero transaction that spend funds from the address $(K^v,K^s)$.\n\n\\subsection{Full protocol sequence}\nWe describe the full protocol execution to successfully complete a swap, while computing and sharing all necessary knowledge in case any participant stops responding at any time or any participant starts the refund process actively.\n\nDuring the first communication round, since both share parameters used to initialize the protocol, we might avoid schemes such as commit-reveal even with $K^s = K^s_a + K^s_b$: thanks to the equal discrete logarithm zero-knowledge proofs, one cannot arbitrarily choose $K^s$ and compute a valid proof $z_i$. However, to ensure getting a random view key for each execution, a commit-reveal must be added on $k^v_i$. Thus, without adding another round of communication, a commit-reveal might be added on $k^s_i$ also.\n\nWe define some utility algorithms to initialize, sign, and verify Bitcoin and Monero transactions.\n\n\\begin{itemize}\n    \\item $\\InitTx()$: A generic and deterministic algorithm which --- on input of a set of parameters --- outputs a valid initialized transaction.\n    \\item $\\Sign()$: A generic and probabilistic algorithm for siging a transaction which --- on input of a private key and an initialized transaction --- outputs a valid signature for the transaction.\n    \\item $\\VrfyTx()$: A generic and deterministic algorithm which --- on input of a set of transactions and parameters --- outputs 1 if and only if the transactions are valid under the protocol rules and blockchain consensus.\n    \\item $\\Verify()$: A generic and deterministic algorithm which --- on input of a public key, a transactions and a signature --- outputs 1 if and only if the signature is valid for transactions given the public key.\n    \\item $\\PubTx()$: A generic algorithm for publishing a transactions over the network.\n    \\item $\\WatchTx()$: A generic algorithm for waiting on a transaction to confirm.\n    \\item $\\RecSig()$: A generic algorithm for extracting transaction's signatures.\n\\end{itemize}\n\n\\newpage\n\n\\begin{figure}[H]\n    \\begin{table}[H]\n        \\centering\n      {\\renewcommand{\\arraystretch}{1.1}%\n      \\begin{tabular}{ | l c l | }\n        \\hline\n          \\multicolumn{1}{|c}{Alice (XMR$\\rightarrow$BTC)} &  & \\multicolumn{1}{c|}{Bob (BTC$\\rightarrow$XMR)} \\\\\n          $k^v_a, k^s_a \\xleftarrow{R} [1, l-1]$ & & $k^v_b, k^s_b \\xleftarrow{R} [1, l-1]$ \\\\\n          %$K^s_a \\leftarrow k^s_aG$ & & $K^s_b \\leftarrow k^s_bG$ \\\\\n          %$B^s_a \\leftarrow k^s_aH$ & & $B^s_b \\leftarrow k^s_bH$ \\\\\n          $b_a,b^r_a \\xleftarrow{R} [1, n-1]$ & & $b_b,b^r_b \\xleftarrow{R} [1, n-1]$ \\\\\n          $B_a \\leftarrow b_aH$ & & $B_b \\leftarrow b_bH$ \\\\\n          $B^r_a \\leftarrow b^r_aH$ & & $B^r_b \\leftarrow b^r_bH$ \\\\\n          $(z_a, K^s_a, B^s_a) \\leftarrow \\DLProve(k^s_a)$ & & $(z_b, K^s_b, B^s_b) \\leftarrow \\DLProve(k^s_b)$ \\\\\n          & & $s \\xleftarrow{R} [0, 2^{256}]$ \\\\\n          & & $h_s \\gets \\texttt{SHA256}(s)$ \\\\\n           & & \\\\\n\n          \\multicolumn{3}{|c|}{$\\xlongleftrightarrow{\\langle k^v_i, K^s_i, B_i, B^s_i, B^r_i, z_i, h_s \\rangle \\  \\forall i \\in \\{a, b\\}}$} \\\\\n\n          & $k^v \\equiv k^v_a + k^v_b \\pmod l$ & \\\\\n          & $K^v = k^vG$, \\ $K^s = K^s_a + K^s_b$ & \\\\\n\n          \\DLVrfy$(K^s_b, B^s_b, z_b) \\stackrel{?}{=} 1$ & & \\DLVrfy$(K^s_a, B^s_a, z_a) \\stackrel{?}{=} 1$ \\\\\n          & & $(\\BTX_\\textit{lock}$, $\\BTX_\\textit{refund}) \\gets$ \\InitTx$(B_a, B_b, B^r_a, B^r_b)$ \\\\\n          & & $\\sigma_r' \\gets$ \\Sign$(b^r_b, \\BTX_\\textit{refund})$ \\\\\n\n          \\multicolumn{3}{|c|}{$\\xleftarrow{\\langle \\BTX_\\textit{lock}, \\BTX_\\textit{refund}, \\BTX_\\textit{spend}, \\sigma_r' \\rangle}$} \\\\\n\n          \\VrfyTx$(\\BTX_\\textit{lock}$, $\\BTX_\\textit{refund}, B_a, B_b, B^r_a, B^r_b, h_s) \\stackrel{?}{=} 1$ & & \\\\\n          \\Verify$(B^r_b, \\BTX_\\textit{refund}, \\sigma_r') \\stackrel{?}{=} 1$ & & \\\\\n          $\\hatsigma_1' \\gets \\EncSign(b^r_a, B^s_b, \\BTX_\\textit{spend})$ & & \\\\\n          $\\delta' \\gets \\RecKey(B^s_b, \\hatsigma_1')$ & & \\\\\n          $\\sigma_r'' \\gets$ \\Sign$(b^r_a, \\BTX_\\textit{refund})$ & & \\\\\n\n          \\multicolumn{3}{|c|}{$\\xrightarrow{\\langle \\sigma_r'', \\hatsigma_1' \\rangle}$} \\\\\n\n          & & $\\EncVer(B^r_a, B^s_b, \\BTX_\\textit{spend}, \\hatsigma_1') \\stackrel{?}{=} 1$ \\\\\n          & & \\Verify$(B^r_a, \\BTX_\\textit{refund}, \\sigma_r'') \\stackrel{?}{=} 1$ \\\\\n          %& & \\Verify$(B^r_a, \\BTX_\\textit{spend}, \\sigma_2') \\stackrel{?}{=} 1$ \\\\\n          & & $\\BTX_\\textit{buy} \\gets$ \\InitTx$(\\BTX_\\textit{lock})$ \\\\\n          & & $\\hatsigma_1 \\gets \\EncSign(b_b, B^s_a, \\BTX_\\textit{buy})$ \\\\\n          & & $\\delta \\gets \\RecKey(B^s_a, \\hatsigma_1)$ \\\\\n          & & \\PubTx$(\\BTX_\\textit{lock})$ \\\\\n\n          \\multicolumn{3}{|c|}{$\\xleftarrow{\\langle \\BTX_\\textit{buy}, \\hatsigma_1 \\rangle}$} \\\\\n\n          $\\EncVer(B_b, B^s_a, \\BTX_\\textit{buy}, \\hatsigma_1) \\stackrel{?}{=} 1$ & & \\\\\n          \\WatchTx$(\\BTX_\\textit{lock}) \\stackrel{?}{=} 1$ & & \\\\\n          \\multicolumn{3}{|c|}{$\\dots$} \\\\\n\n          $\\XTX_\\textit{lock} \\gets$ \\InitTx$(K^v, K^s)$ & & \\\\\n          \\PubTx$(\\XTX_\\textit{lock})$ & & \\\\\n\n          \\multicolumn{3}{|c|}{$\\dots$} \\\\\n          & & \\WatchTx$(K^v, K^s)$ w/ $(k^v, K^s) \\stackrel{?}{=} 1$ \\\\\n\n          \\multicolumn{3}{|c|}{$\\xleftarrow{\\langle s \\rangle}$} \\\\\n\n          $\\sigma_1 \\gets \\DecSig(k^s_a, \\hatsigma_1)$ & & \\\\\n          $\\sigma_2 \\gets \\Sign(b_a, \\BTX_\\textit{buy})$ & & \\\\\n          $\\sigma := (\\sigma_1, \\sigma_2)$ & & \\\\\n          \\PubTx$(\\BTX_\\textit{buy}, \\sigma, s)$ & & \\\\\n\n          & & \\WatchTx$(\\BTX_\\textit{buy}) \\stackrel{?}{=} 1$ \\\\\n          \\multicolumn{3}{|c|}{$\\dots$} \\\\\n\n          & & $(\\sigma_1, \\sigma_2) \\gets \\RecSig(\\BTX_\\textit{buy})$ \\\\\n          & & $k^s_a \\gets \\Rec(\\sigma_1, \\delta)$ \\\\\n          & & $k^s \\equiv k^s_a + k^s_b \\pmod l$ \\\\\n          & & $\\langle k^v, k^s \\rangle$ \\\\\n        \\hline\n      \\end{tabular}}\n    \\end{table}\n  \\caption{Protocol execution between Alice and Bob for a successful swap}\n  \\label{fig:protocol}\n\\end{figure}\n\nDots represent synchronization timing during which one or more participants must check for transaction confirmations before continuing the protocol execution. The level of security --- i.e. the number of confirmations required by each participants --- is a local parameter, but must be set according to the timing parameters --- which are global to both participants --- to avoid the case where the timing is less or equal to the security parameter.\n\n\\section{Further research}\nThis protocol is implementable with today's state of Bitcoin and Monero, but further research is required to use \\texttt{Schnorr} capabilities and simplicity to create a more efficient protocol with lighter on-chain footprints. This would improve anonymization of atomic swaps with respect to chain-analysis.\n\nAs discussed, this protocol can be adapted to other cryptocurrencies. Some of them might not have atomic swaps yet, and extending to other pairs might improve decentralization. Extending this protocol to privacy preserving cryptocurrency pairs only --- like Monero with Mimblewimble --- is the next challenge in atomic swaps.\n\nIntegration with services or decentralized exchanges would help democratizing trading without trusted institutions and might increase the market liquidity. Since the design presented here is asymmetric, building services might not be straightforward.\n\n\\subsection{Known limitations}\nTo provide liveness (if at least one participant is still online) we allow for the worst case scenario in which a participant may end up losing funds (by not being able to claim on the other chain). This can happen in the case where they do not follow the protocol, e.g. remaining online during pending swap or claiming funds in time. The rationale behind this design is explained in \\ref{worstCaseRationale}.\n\nFees are different from one chain to the other partly because of internal blockchain parameters \\& transaction complexity, and also due to external factors such as demand for blockspace. Note that within this protocol, the Bitcoin blockchain is used as a decision engine, where we use scripting features of bitcoin---although we try to put as much logic as we can off-chain---, which causes bigger transactions on the bitcoin side. These two factors combined make the Bitcoin transactions more expensive in general than those on the Monero chain.\n\nInstant user feedback in a cross-chain atomic swap is hard to achieve.  The slowest chain and the number of confirmations required for transaction finality dictate the speed of the protocol, allowing front running in some cases. The protocol can be extended to prevent front running within certain setups however. It is worth noting that front running cannot be enforced by one participant on the other, thus making the worst case scenario the loss of transaction fees on each of the participants' respective blockchains.\n\n\\section{Acknowledgement}\nThe Monero Research Lab and Sarang Noether are acknowledged for their helpful comments during the completion of this work. This work has been supported and partially funded by the Monero Community --- we extend a special thanks to all donators. Finally, thanks to TrueLevel SA collaborators for the initial funding and their helpful contribution and comments.\n\n%\n% ---- Bibliography ----\n%\n\\printbibliography\n\n\\end{document}\n", "meta": {"hexsha": "83aa33247ee1d3c8d7086f2b9e6ee03adcc9f2cb", "size": 36142, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "whitepaper/xmr-btc.tex", "max_stars_repo_name": "h4sh3d/XMR-BTC-atomic", "max_stars_repo_head_hexsha": "07b7ee306c1f0c96e7f5cda92616da0df780cc00", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 57, "max_stars_repo_stars_event_min_datetime": "2019-03-29T13:18:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-26T07:23:59.000Z", "max_issues_repo_path": "whitepaper/xmr-btc.tex", "max_issues_repo_name": "h4sh3d/XMR-BTC-atomic", "max_issues_repo_head_hexsha": "07b7ee306c1f0c96e7f5cda92616da0df780cc00", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-03-25T14:44:57.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-24T10:56:30.000Z", "max_forks_repo_path": "whitepaper/xmr-btc.tex", "max_forks_repo_name": "h4sh3d/XMR-BTC-atomic", "max_forks_repo_head_hexsha": "07b7ee306c1f0c96e7f5cda92616da0df780cc00", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-04-21T18:46:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T21:59:46.000Z", "avg_line_length": 70.3151750973, "max_line_length": 553, "alphanum_fraction": 0.73911239, "num_tokens": 9990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.32471261185990175}}
{"text": "\\documentclass[aps,preprint]{revtex4-1}\n\\usepackage{graphicx}\n\\usepackage{amsmath}\n\\usepackage{makeidx}\n\\usepackage{amsfonts}\n\\usepackage{amssymb}\n\\usepackage{mathtools}\n\\usepackage{xcolor}\n\n\\begin{document}\n\n\n\\title{Efficiency and entropy production of selfish drivers}\n\n\n\n\\date{\\today}\n\n\\begin{abstract}\nCharacterizing transport processes in a city system is important to have a better picture of efficiency and sustainability in such a complex system. In this study, we consider the process of movements of selfish drivers from their homes (origins) to work places (destinations) to see how interactions and randomness in the movements affect a measure of efficiency and entropy production in this process. Interactions are modelled by the effect of the flows on the local travel times, and by exploiting the travel information from the previous days. Here, the efficiency is computed by comparing the total travel time with the number of travels along the links. And, the entropy production is obtained by comparing the time intervals of leaving the origins and arriving at the destinations. We use  realistic models of population distributions and mobility laws for simulation of the movement process where at each step a driver moves to a neighbouring site which is closer to the destination or which is chosen randomly. We observe that interactions and a naive way of using the travel information without any coordination reduce the efficiency and increase the entropy production of the process. Moreover, the larger systems display smaller efficiencies for the same model parameters like the population density which limits the size of an efficient city. On the other hand, randomness in the movements can help to enhance the efficiency when the strength of interactions is large and congestion is high. We also find that the entropy production is a good order parameter to distinguish the low- and high-congestion phases. In the former phase, the entropy production grows monotonically with the probability of random moves whereas it displays a minimum in the congested phase; that is randomness in the movements can reduce the uncertainty in the destination time intervals. \n\\end{abstract}\n\n\n%\\pacs{} \n\n\\maketitle\n\n\\section{Introduction}\\label{S0}\n\n\\begin{itemize}\n\n\\item interactions $(g,\\lambda)$ increase the travel time, reduce the efficiency, and increase the entropy production.\n\n\n\\item $\\lambda=0$: \n\n- we observe a change in behaviour of the entropy production $\\Delta S_D$ vs the disorder parameter $\\alpha$ as the interaction strength $g$ increases.  For sufficiently large $g$, a bit of disorder can reduce the entropy production. \n\n\n\\item $\\lambda=0.5$: \n\n- we observe a change in the complexity of the time series in days as the interaction strength $g$ increases.\n\n- the efficiency and velocity display a (nontrivial) maximum for some disorder $\\alpha^*(g)$ depending on the parameter $g$.  \n\n- mutual information between $(t_O,t_D)$ increases whereas that of $(\\Delta x_{OD},\\Delta t_{OD})$ decreases by introducing $\\lambda$. \n\n\n\n\\end{itemize}\n\n\n\\section{Models and Settings}\\label{S1}\nIn this section, we present the main definitions and methods which are used to model the network flow dynamics.   \nConsider a city of $N$ sites with local populations $\\{m_a:a=1,\\dots,N\\}$ and total population $M=\\sum_a m_a$. The connectivity graph of the city is given by $G(V,E)$ where $V$ is the set of sites and $E$ is the set of directed edges $(ab)$. Here we take a two dimensional square lattice of size $N=L\\times L$, where all edges have the same length and the same free travel times. We use the simple growth model introduced in Ref. \\cite{Li-nc-2017} to produce reasonable population distributions for the model cities. The population density is fixed to $M/N=10^3$ in the following.\n\nGiven the population distribution $m_a$, we use the following mobility law to construct the flux of movements $m_{a\\to b}$ from origins $a$ to destinations $b$, \n\\begin{align}\\label{mab}\nm_{a\\to b}=m_ap_{a\\to b}=m_a\\frac{m_b/M(r_{ab})}{\\sum_{c\\neq a} m_c/M(r_{ac})},\n\\end{align}\nwhere $M(r_{ab})$ is the population in the circle of radius $r_{ab}$ centred at site $b$. The ratio $m_b/M(r_{ab})$ can be interpreted as the attractiveness of site $b$ for an individual at site $a$. \n\nFinally, the flows of movements on edges $(ab)\\in E$ are determined by a flux distribution problem that satisfies the system constraints and preferences, as follows. \n \n\n\\subsection{The movement process}\\label{S11}\nHere is the process of moving from the origins to destinations in a single day:\n\n\\begin{itemize}\n\n\\item The starting times of the OD trips are distributed uniformly in the origin time interval $\\Delta T_O$. We assume that $\\Delta T_O$ is the same for all origins. In each time step, the time increases by $\\Delta t=1$. Driver $i$ starts its trip and becomes active at time $t_O(i) \\in \\Delta T_O$. The trip will become inactive when the driver reaches its destination at time $t_D(i) \\in \\Delta T_D$. The destination time interval $\\Delta T_D$ is determined by the system structure and dynamics (see Fig. \\ref{Tday}). \nThe arrival times of the drivers to destination site $a$ determine the destination time interval $\\Delta T_D(a)$ of that site. \nThe travel time from origin to destination for driver $i$ is denoted by $\\Delta t_{OD}(i)=t_D(i)-t_O(i)$. \n\n\\item An active driver $i$ at site $a$ chooses the next site as follows: with probability $\\alpha$ the next site is chosen randomly and uniformly from the set of neighbouring sites. With probability $1-\\alpha$ the neighbour that minimizes the expected travel time to the destination $D(i)$ is selected. The expected travel time on edge $(ab)$ is denoted by $\\tilde{t}_{ab}$. The expected travel times in day $d$ are estimated by using the actual travel times $t_{ab}$ from the previous day:\n\\begin{align}\\label{tab0}\n\\tilde{t}_{ab}(d)=\\lambda t_{ab}(d-1)+(1-\\lambda) \\tilde{t}_{ab}(d-1).\n\\end{align}\nFor the initial day $\\tilde{t}_{ab}(0)=t_{ab}(0)$, where the $t_{ab}(0)$ are the travel times for free lines. \n\n\\item Let flow $F_{ab}(t)$ be the number of people that enter edge $(ab)$ at time step $t$. Given the input flows, then the actual travel times are obtained from \n\\begin{align}\\label{tab}\nt_{ab}(F_{ab})=t_{ab}(0)\\left(1+g(\\frac{F_{ab}}{F_{ab}^*})^{\\mu}\\right),\n\\end{align}\nwith $g (F_{ab}/F_{ab}^*)^{\\mu}$ to model the influence of flows on the travel times \\cite{BPR-1964,lc-trans-1976,lc-trans-2011}. Here $F_{ab}^*$ is a measure of the line capacity. For simplicity, we assume that $t_{ba}(0)=t_{ab}(0)$ and $F_{ba}^*= F_{ab}^*$.\nIn the following we take $\\mu=3$, $t_{ab}(0)=1$, and $F_{ab}^*=M/|E|$ in all simulations.\n\n\\end{itemize}\n\nThe actual travel time $t_{ab}$ determines the time that a person spends on edge $(ab)$. The total number of persons on edge $(ab)$ at time step $t$ is denoted by the flow density $\\rho_{ab}(t)$. \n\n\n\\section{Results}\\label{S2}\nLet us start with the effects of interactions on the cumulative distribution of the travel times $P(\\Delta t_{OD}>T)$ in the absence of any randomness in the movements ($\\alpha=0$). As Fig. \\ref{Ti} shows, the travel times increase by introducing the interactions either by considering the effects of flows on the trips (with $g$) or by knowing the travel information from the previous days (with $\\lambda$). The latter says that a selfish way of using the information without any coordination could result to a chaotic situation \\cite{Apps-ieee-2019}. We know that interacting systems can display complex behaviours and interactions may reduce the system predictability \\cite{watts-sci-2006}. In the following, we see how the interplay of the above interactions with disorder in the movements affects a measure of complexity and predictability of the movement process. In addition, we follow the changes in the efficiency and a measure of entropy production in the system to see how the relation between these qualities depend on the macroscopic state (phase) of the system \\cite{efc-srep-2020}.  \n                    \n\n\\subsection{Complexity and predictability}\\label{S21}\nA measure of predictability for two stochastic variables $x,x'$ is provided by the mutual information of the two variables,\n\\begin{align}\n\\mathrm{MI}(x,x')=\\sum_{x,x'}P(x,x')\\log\\frac{P(x,x')}{P(x)P(x')},\n\\end{align}\nwhere $P(x,x'), P(x)$ and $P(x')$ are the joint and marginalized probability distributions of the variables.\n\nLet us define the mutual information between the destination and origin times\n\\begin{align}\n\\Pi_{t,t}=\\mathrm{MI}(t_O,t_D),\n\\end{align}\nand the mutual information between the travel time and the geometrical distance, \n\\begin{align}\n\\Pi_{x,t}=\\mathrm{MI}(\\Delta x_{OD},\\Delta t_{OD}).\n\\end{align}\nFigure \\ref{Pi} shows the results of numerical simulations for these quantities in a square lattice of linear size $L=20$.\nAs expected, the above measures of predictability diminish with increasing $g$ or $\\alpha$, except the small jump that is observed \nfor $\\lambda=0.5$ when $\\alpha$ changes from zero.  On the other hand, we observe that $\\Pi_{t,t}$ increases but $\\Pi_{x,t}$ decreases after using the travel times from the previous days (i.e., for $\\lambda=0.5$). Note that when $\\lambda=0$ all edges have the same estimated travel times $\\tilde{t}_{ab}(d)=t_{ab}(0)=1$ where the shortest path is strongly correlated with the geometrical distance $\\Delta x_{OD}$. On the other side, when $\\lambda=0.5$ there are some edges with small travel times in the previous day and all drivers are aware of this information which in turn determines the shortest path to their destinations. Therefore, one expects to observe less correlations here between the geometrical distance and the actual travel times. However, the same global information now makes the arrival times to the destinations more dependent on the departure times from the origins and results to larger mutual information between the two time variables. \n\n\nTo address the complexity of the process, we check the presence of long range correlations in the time evolution of the system. \nConsider a stationary time series $\\{\\cdots,x_{n-1},x_n,x_{n+1},\\cdots\\}$ and a string of data points which is divided into two equal data sets $\\mathbf{x}_{past}$ and $\\mathbf{x}_{future}$ of length $l$. A measure of complexity can be defined by the scaling of the mutual information $\\mathrm{MI}(\\mathbf{x}_{past},\\mathbf{x}_{future})$ with $l$. This information could be independent of the size or increase logarithmically or even sub-linearly with $l$ \\cite{bialek-nc-2001}. In the following, however, we study a computationally more efficient but approximate way of detecting a time series complexity, which is based on an estimation of information rate (sample entropy) in different time scales \\cite{samp-ajp-2000,costa-prl-2002}. \n\nConsider the coarse grained time series $\\{\\cdots,y_{n-1},y_n,y_{n+1},\\cdots\\}$ obtained by averaging the original time series within a window of size $w$, i.e., $y_n=(\\sum_{n'=(n-1)w+1}^{nw}x_{n'})/w$. Let $\\mathbf{y}_n(l)$ be a sequence of length $l$ starting at $n$. We define $p(l:r,w)$ as the probability that two such sequences are within distance $r$ of each other, i.e., $d(\\mathbf{y}_n(l),\\mathbf{y}_{n'}(l))<r \\times std(x)$. Here $d(\\mathbf{y}_{n_1}(l),\\mathbf{y}_{n_2}(l))=\\max_{0\\le n'<l}|y_{n_1+n'}-y_{n_2+n'}|$ and $std(x)$ denotes the standard deviation of the original time series. Then the sample entropy at scale factor $w$ is given by $SampEn(l,r,w)=-\\log (p(l+1:r,w)/p(l:r,w))$. The ratio of the two probabilities is indeed the conditional probability that two sequences of size $l$ which are within distance $r$ of each other are still close when the size increases to $l+1$. Here we take $l=2$ and $r=0.2$. A large value of the above sample entropy for large scale factors indicates on the presence of long range correlations in the system. It also means that still distinct sequence patterns appear when the series is looked at larger time scales.\n \n         \nNow let us define the average flow density, using the local flow densities $\\rho_{ab}(t)$,\n\\begin{align}\n\\rho(t)=\\frac{1}{|E|}\\sum_{(ab)}\\rho_{ab}(t).\n\\end{align}\nTo study the day to day correlations we take the maximum flow density $\\rho^*=\\max_{t}{\\rho(t)}$ and the associated time series $\\{\\cdots,\\rho^*_{d-1},\\rho^*_d,\\rho^*_{d+1},\\cdots\\}$ in a sequence of days indexed by $d$. Figure \\ref{Sw} displays the sample entropy in terms of the scale factor $w$ for single instances of the above time series. We observe that the sample entropy decays very slowly around $g=2$ signalling the presence of long range correlations in the system. In the following we see how this change in the complexity affects the qualitative behaviour of other interesting quantities in the system.              \n\n\n\\subsection{Efficiency and entropy production}\\label{S22}\nThe average travel time in the process is given by\n\\begin{align}\n\\tau_{OD}=\\frac{1}{M}\\sum_{i} \\Delta t_{OD}(i).\n\\end{align}\nThe average number of travels per person in a day is obtained from the sum of all the input flows $F_{ab}(t)$ for different edges and times, \n\\begin{align}\n\\sigma_{OD}=\\frac{1}{M}\\sum_{t} \\sum_{(ab)} F_{ab}(t).\n\\end{align}\nA measure of efficiency is defined by ratio of the two\n\\begin{align}\n\\eta_{OD}=\\frac{1/\\tau_{OD}}{\\sigma_{OD}}.\n\\end{align}\n \nFor each person we can also define the velocity $v_{OD}(i)=\\Delta x_{OD}(i)/\\Delta t_{OD}(i)$, given the geometrical origin to destination distances $\\Delta x_{OD}(i)$. Then the average velocity is\n\\begin{align}\nv_{OD}=\\frac{1}{M}\\sum_{i} v_{OD}(i).\n\\end{align}\n\n\nA measure of increase in the system disorder or uncertainty (entropy production) is provided by the distribution of the destination time intervals  \n\\begin{align}\n\\Delta S_D=\\langle \\log \\Delta T_D \\rangle-\\langle \\log \\Delta T_O \\rangle=\\frac{1}{N}\\sum_a \\log \\Delta T_D(a)-\\log \\Delta T_O.\n\\end{align}\nAs mentioned above, $\\Delta T_O$ is the same for all the sites $a$.\n\n\n\n\n\n\\section{Conclusion}\\label{S3}\nIn summary, numerical simulations of the movement process shows that in general interactions $(g,\\lambda)$ increase the travel time, reduce the efficiency, and increase the entropy production. A selfish usage of information from the previous days results to smaller efficiency and velocity but at the same time enhance the mutual information between the origin and destination times of the trips. This enhancement in the mutual information probably is the only good point of such a movement process. Moreover, the efficiency and velocity display a (nontrivial) maximum for some randomness probability $\\alpha^*$ depending on the strength of interactions. We also observed a qualitative change in the behaviour of the entropy production $\\Delta S_D$ with the randomness parameter $\\alpha$ as the parameter $g$ increases. In fact, for sufficiently large $g$, one can reduce the uncertainty in the destination times by introducing randomness in the movements. In other words, the response of $\\Delta S_D$ to the randomness $\\alpha$ can be used to discriminate the ordered and disordered phases of the flows in the system.\n\nAn interesting observation is that the efficiency and velocity are significantly reduced by increasing the system linear size $L$ when the other model parameters are fixed even for the same density $M/N$ and $L/\\Delta T_O$.  For instance here the efficiency and velocity scale roughly as $L^{-2.3}$ and $L^{-0.3}$, respectively. This means that under the above conditions the city size is limited by the efficiency or velocity of the movement process. An important quantity here is the link capacity $F^*_{ab}$, which controls the travel times for a give flow in link $(ab)$. In the numerical simulation, we set $F^*_{ab}=M/|E|$ independent of the link position in the lattice, whereas the population is not distributed homogeneously. The question then is how we should adjust the local capacities such that the efficiency approaches a desirable limit by increasing the size of the system.  \n\n\n\n\\begin{thebibliography}{prsty}\n\n%\\bibitem{Lavenda-book-1978} Lavenda, B. H. Thermodynamics of irreversible processes. (London: Macmillan, 1978).\n%\n%\n%\n%\\bibitem{B-book-2012} Bialek, W. Biophysics: searching for principles. (Princeton University Press, 2012).\n%\n%\n%\n%\\bibitem{Emarket-jfe-1998} Fama, E. F. Market efficiency, long-term returns, and behavioral finance. {\\it Journal of financial economics} {\\bf 49}(3), 283-306 (1998).\n%\n%\\bibitem{Emarket-jep-2003} Shiller, R. J. From efficient markets theory to behavioral finance. {\\it Journal of economic perspectives} {\\bf 17}(1), 83-104 (2003).\n%\n%\\bibitem{Emarket-jpm-2004} Lo, A. W. The adaptive markets hypothesis. {\\it The Journal of Portfolio Management}, {\\bf 30}(5), 15-29 (2004).\n%\n%\n%\\bibitem{ut-nat-2010} Bettencourt, L. M. A. \\& West, G. B. A unified theory of urban living. {\\it Nature}\n%{\\bf 467}, 912–913 (2010).\n%\n%\\bibitem{Batty-book-2013} Batty, M. The new science of cities. (MIT press, 2013).\n%\n%\\bibitem{B-book-2016} Barthelemy, M. The Structure and Dynamics of Cities\n%(Cambridge University Press, Cambridge, 2016).\n%\n%\\bibitem{B-nr-2019} Barthelemy, M. The statistical physics of cities. {\\it Nature Reviews Physics}  {\\bf 1}, 406–415 (2019).\n%\n%\n%\n%\n%\\bibitem{cp-sci-2011} Glaeser, E. Cities, productivity, and quality of life. {\\it Science} {\\bf 333}, 592–594 (2011).\n%\n%\n%\\bibitem{neq-ac-2006} Pulselli, R. M., Ciampalini, F., Galli, A., \\& Pulselli, F. M. Non equilibrium thermodynamics and the city: A new approach to urban studies. {\\it Annali di chimica}, {\\bf 96}(9‐10), 543-552 (2006).\n%\n%\\bibitem{Batty-sci-2008} Batty, M. The size, scale, and shape of cities. {\\it Science} {\\bf 319}, 769–771 (2008).\n%\n%\\bibitem{tc-spr-2009} Wilson, A. The “thermodynamics” of the city. In Complexity and Spatial Networks,  11-31 (Springer, Berlin, Heidelberg, 2009).\n%\n%\\bibitem{cg-jie-2015} Bristow, D., \\& Kennedy, C. Why do cities grow? Insights from nonequilibrium thermodynamics at the urban and global scales. {\\it Journal of Industrial Ecology}, {\\bf 19}(2), 211-221 (2015).\n%\n%\n%\n%\n%\\bibitem{scaling-sci-2013} Bettencourt, L. M. A. The origins of scaling in cities.{\\it  Science} {\\bf 340}, 1438–1441 (2013).\n%\n%\\bibitem{scaling-plos-2014} Louf, R., Roth, C., \\& Barthelemy, M.  Scaling in transportation networks. {\\it PLoS One}, {\\bf 9}(7) (2014).\n%\n%\n%\n\\bibitem{Li-nc-2017} Li, R., Dong, L., Zhang, J., Wang, X., Wang, W. X., Di, Z., \\& Stanley, H. E.  Simple spatial scaling rules behind complex cities. {\\it Nature communications}, {\\bf 8}(1), 1-7 (2017).\n%\n%\n%\\bibitem{mt-book-2011} Ortuzar, J. \\& Willumsen, L. Modelling Transport. (John Wiley \\& Sons., New York, 2011)\n%\n%\n%\n%\\bibitem{sf-nature-1999} Banavar, J. R., Maritan, A., \\& Rinaldo, A. Size and form in efficient transportation networks. {\\it Nature}, {\\bf 399}(6732), 130-132 (1999).\n%\n%\\bibitem{sus-book-2005} Banister, D. Unsustainable transport: city transport in the new century (Taylor \\& Francis, 2005).\n%\n%\n%\n%\n%\\bibitem{C-pre-1999} Crooks, G. E. Entropy production fluctuation theorem and the nonequilibrium work relation for free energy differences. {\\it Physical Review E} {\\bf 60}(3), 2721 (1999).\n%\n%\\bibitem{J-cm-2011} Jarzynski, C. Equalities and inequalities: Irreversibility and the second law of thermodynamics at the nanoscale. {\\it Annu. Rev. Condens. Matter Phys.} {\\bf 2}(1), 329-351 (2011).\n%\n%\\bibitem{st-rpp-2012} Seifert, U. Stochastic thermodynamics, fluctuation theorems and molecular machines. {\\it Reports on progress in physics} {\\bf 75}(12), 126001 (2012).\n%\n%\n%\n%\\bibitem{E-njp-2003} Kolbl, R., \\& Helbing, D.  Energy laws in human travel behaviour. {\\it New Journal of Physics}, {\\bf 5}(1), 48 (2003).\n%\n%\n%\n%\n%\\bibitem{rad-nature-2012} Simini, F., Gonzalez, M. C., Maritan, A., \\& Barabasi, A. L.  A universal model for mobility and migration patterns. {\\it Nature}, {\\bf 484}(7392), 96-100 (2012).\n%\n%\\bibitem{Hasan-jsp-2013} Hasan, S., Schneider, C. M., Ukkusuri, S. V., \\& Gonzalez, M. C.  Spatiotemporal patterns of urban human mobility. {\\it Journal of Statistical Physics}, {\\bf 151}(1-2), 304-318 (2013).\n%\n\\bibitem{Yan-intf-2014} Yan, X. Y., Zhao, C., Fan, Y., Di, Z., \\& Wang, W. X.  Universal predictability of mobility patterns in cities. {\\it Journal of The Royal Society Interface}, {\\bf 11}(100), 20140834 (2014).\n%\n%\\bibitem{Ren-nc-2014} Ren, Y., Ercsey-Ravasz, M., Wang, P., Gonzalez, M. C., \\& Toroczkai, Z.  Predicting commuter flows in spatial networks using a radiation model based on temporal ranges. {\\it Nature communications}, {\\bf 5}(1), 1-9 (2014).\n%\n%\\bibitem{mob-plos-2015} Kang, C., Liu, Y., Guo, D., \\& Qin, K.  A generalized radiation model for human mobility: spatial scale, searching direction and trip constraint. {\\it PloS one}, {\\bf 10}(11) (2015).\n%\n%\n%\n%\\bibitem{lo-plos-2015} Mastroianni, P., Monechi, B., Liberto, C., Valenti, G., Servedio, V. D., \\& Loreto, V.  Local optimization strategies in urban vehicular mobility. {\\it PloS one}, {\\bf 10}(12), (2015).\n%\n%\\bibitem{Serdar-nc-2016} Colak, S., Lima, A., \\& Gonzalez, M. C.  Understanding congested travel in urban areas. {\\it Nature communications}, {\\bf 7}(1), 1-8 (2016).\n%\n%\n%\n%\n%\\bibitem{horner-epa-2002} Horner, M. W. Extensions to the concept of excess commuting. {\\it Environ. Plann. A} {\\bf 34}, 543–566 (2002).\n%\n%\\bibitem{newman-jstst-2006} Gastner, M. T. \\& Newman, M. E. Shape and efficiency in spatial distribution networks. {\\it J. Stat. Mech-Theory E.} P01015 (2006).\n%\n%\\bibitem{EC-trans-2015} Kanaroglou, P. S., Higgins, C. D. \\& Chowdhury, T. A. Excess commuting: a critical review and comparative analysis of concepts, indices, and policy implications. {\\it J. Transp. Geogr.} {\\bf 44}, 13–23 (2015).\n%\n%\\bibitem{ceff-srep-2016}Dong, L., Li, R., Zhang, J., \\& Di, Z.  Population-weighted efficiency in transportation networks. {\\it Scientific reports}, {\\bf 6}, 26377 (2016).\n%\n\\bibitem{indaco-arx-2018} Biazzo, I., Monechi, B., \\& Loreto, V.  General scores for accessibility and inequality measures in urban areas. {\\it Royal Society open science}, {\\bf 6}(8), 190979 (2019).\n%\n%\n%\\bibitem{hmobility-nph-2010} Song, C., Koren, T., Wang, P., \\& Barabasi, A. L.  Modelling the scaling properties of human mobility. {\\it Nature Physics}, {\\bf 6}(10), 818-823 (2010).\n%\n%\\bibitem{sp-mpc-2012} Riccardo, G., Armando, B., \\& Sandro, R.  Towards a statistical physics of human mobility. {\\it International Journal of Modern Physics C}, {\\bf 23}(09), 1250061 (2012).\n%\n%\\bibitem{motif-rci-2013} Schneider, C. M., Belik, V., Couronné, T., Smoreda, Z., \\& Gonzalez, M. C.  Unravelling daily human mobility motifs. {\\it Journal of The Royal Society Interface}, {\\bf 10}(84), 20130246 (2013).\n%\n%\\bibitem{motif-nc-2017} Yan, X. Y., Wang, W. X., Gao, Z. Y., \\& Lai, Y. C.  Universal model of individual and population mobility on diverse spatial scales. {\\it Nature communications}, {\\bf 8}(1), 1-9 (2017).\n%\n%\n%\n\n\n\n\\bibitem{BPR-1964} US Bureau of Public Roads. Office of Planning. Urban Planning Division. Traffic Assignment Manual for Application with a Large, High Speed Computer. US Department of Commerce; 1964.\n\n\n\\bibitem{lc-trans-1976} Branston D. Link capacity functions: A review. Transportation research. 1976 Aug 1;10(4):223-36.\n\n\\bibitem{lc-trans-2011} Huntsinger, L. \\& Rouphail, N. Bottleneck and queuing analysis: calibrating volume–delay functions of travel demand models. {\\it Transp. Res. Rec.} {\\bf 2255}, 117–124 (2011).\n\n%\n%\n%\n%\\bibitem{popGridEurostat}\n%Eurostat population grid;\n%\\newblock \\textit{Available at}\n%\\url{http://ec.europa.eu/eurostat/web/gisco/geodata/reference-data/population-distribution-demography/geostat}.\n%\n%\\bibitem{sedacV4}\n%Center for International Earth Science Information Network CIESIN Columbia~University\n%C. {Gridded Population of the World, Version 4 (GPWv4): Population Count}.\n%\\newblock Palisades, NY: NASA Socioeconomic Data and Applications Center (SEDAC); 2016.\n%\\newblock Available from: \\url{http://dx.doi.org/10.7927/H4X63JVC}.\n%\n%\n%\n%\\bibitem{critical-dd-1999} Batty, M., \\& Yichun X. Self-organized criticality and urban development. {\\it Discrete Dynamics in Nature and Society} {\\bf 3}(2-3), 109-124 (1999).\n%\n%\\bibitem{predict-sci-2010} Song, C., Qu, Z., Blumm, N., \\& Barabasi, A. L.  Limits of predictability in human mobility. {\\it Science}, {\\bf 327}(5968), 1018-1021 (2010).\n%\n%\\bibitem{predict-jsta-2013} Gallotti, R., Bazzani, A., Degli Esposti, M., \\& Rambaldi, S.  Entropic measures of individual mobility patterns. {\\it Journal of Statistical Mechanics: Theory and Experiment}, {\\bf 2013}(10), P10022 (2013).\n%\n\n\n\n\\bibitem{watts-sci-2006} Salganik MJ, Dodds PS, Watts DJ. Experimental study of inequality and unpredictability in an artificial cultural market. science. 2006 Feb 10;311(5762):854-6.\n\n\\bibitem{Apps-ieee-2019} Macfarlane J. When apps rule the road: The proliferation of navigation apps is causing traffic chaos. It's time to restore order. IEEE Spectrum. 2019 Sep 24;56(10):22-7.\n\n\\bibitem{efc-srep-2020} Biazzo I, Ramezanpour A. Efficiency and irreversibility of movements in a city. Scientific reports. 2020 Mar 9;10(1):1-8.\n\n\\bibitem{bialek-nc-2001} Bialek W, Nemenman I, Tishby N. Predictability, complexity, and learning. Neural computation. 2001 Nov 1;13(11):2409-63.\n\n\n\\bibitem{samp-ajp-2000} Richman JS, Moorman JR. Physiological time-series analysis using approximate entropy and sample entropy. American Journal of Physiology-Heart and Circulatory Physiology. 2000 Jun 1;278(6):H2039-49.\n\n\\bibitem{costa-prl-2002} Costa M, Goldberger AL, Peng CK. Multiscale entropy analysis of complex physiologic time series. Physical review letters. 2002 Jul 19;89(6):068102.\n\n\n\n\n\\bibitem{saad1-arxiv-2020} Po HF, Yeung CH, Saad D. The Futility of Being Selfish--The Impact of Selfish Routing on Uncoordinated and Optimized Transportation Networks. arXiv preprint arXiv:2003.06833. 2020 Mar 15.\n\n\\bibitem{saad2-arxiv-2020} Li B, Lokhov AY, Saad D. Reducing Urban Traffic Congestion Due To Localized Routing Decisions. arXiv preprint arXiv:2002.10298. 2020 Feb 24.\n\n\n%\\bibitem{glaw-japp-1936} Greenshields BD. Studying traffic capacity by new methods. J. Appl. Psychol. 1936;20(3):353-8.\n\n\n\n\\end{thebibliography}\n\n\n\\begin{figure}\n\\includegraphics[width=12cm]{Tday.eps} \n\\caption{Illustration of the origin to destination trips. (a) In each day, the trips are started from the origins in the time interval $\\Delta T_O$ and reach the destinations in the time interval $\\Delta T_D(a)$ with travel times $T_{OD}(i)$. (b) The travel times of day $d-1$ are used to find the shortest-time paths in the next day (see the main text).}\\label{Tday}\n\\end{figure}\n\n\n\\begin{figure}\n\\includegraphics[width=12cm]{Ti.eps} \n\\caption{Cumulative probability distribution of the travel times $\\Delta t_{OD}$ in the $M=1.6\\times 10^5$ trips. The lattice size is $L=40$ and $\\alpha=0$ here.}\\label{Ti}\n\\end{figure}\n\n\n\\begin{figure}\n\\includegraphics[width=12cm]{Pi.eps} \n\\caption{Mutual information of origin times with destination times $\\Pi_{t,t}$ and geometrical distances with travel times $\\Pi_{x,t}$. The lattice size is $L=20$, and $\\Delta T_O=16$ here. The data are averaged over $1000$ independnet realizations of the population distribution and the movement process.}\\label{Pi}\n\\end{figure}\n\n\n\\begin{figure}\n\\includegraphics[width=12cm]{Rmax_loglog.png} \n\\caption{Sample entropy vs the scale factor $w$. The lattice size is $L=20$, $\\Delta T_O=16$, and $\\alpha=0$ here. The data are for a single realization of the population distribution and the movement process.}\\label{Sw}\n\\end{figure}\n\n\n\\begin{figure}\n\\includegraphics[width=12cm]{Ef.eps} \n\\caption{The efficiency $\\eta_{OD}$ vs the disorder parameter $\\alpha$. The lattice size is $L=20$, and $\\Delta T_O=16$ here. The data are averaged over $1000$ independnet realizations of the population distribution and the movement process. }\\label{Ef}\n\\end{figure}\n\n\n\\begin{figure}\n\\includegraphics[width=12cm]{v.eps} \n\\caption{The velocity $v_{OD}$ vs the disorder parameter $\\alpha$. The lattice size is $L=20$, and $\\Delta T_O=16$ here. The data are averaged over $1000$ independnet realizations of the population distribution and the movement process.}\\label{v}\n\\end{figure}\n\n\n\n\\begin{figure}\n\\includegraphics[width=12cm]{dS.eps} \n\\caption{The relative entropy $\\Delta S_D$ vs the disorder parameter $\\alpha$. The lattice size is $L=20$, and $\\Delta T_O=16$ here. The data are averaged over $1000$ independnet realizations of the population distribution and the movement process.}\\label{dS}\n\\end{figure}\n\n\n\n\\begin{figure}\n\\includegraphics[width=12cm]{Lg.eps} \n\\caption{Size effects with the interaction parameter $g$ for $\\lambda=0$. Here $\\Delta T_O=16, 24, 32$ for $L=20, 30, 40$, respectively to have the ratio $L/\\Delta T_O$ fixed. Also the population density is fixed to $M/N=10^3$. The data are averaged over $1000$ (for $L=20,30$) or $500$ (for $L=40$) independnet realizations of the population distribution and the movement process.}\\label{Lg}\n\\end{figure}\n\n\n\\begin{figure}\n\\includegraphics[width=12cm]{La.eps} \n\\caption{Size effects with the disorder parameter $\\alpha$ for $\\lambda=0$. Here $\\Delta T_O=16, 24, 32$ for $L=20, 30, 40$, respectively to have the ratio $L/\\Delta T_O$ fixed. Also the population density is fixed to $M/N=10^3$. The data are averaged over $1000$ (for $L=20,30$) or $500$ (for $L=40$) independnet realizations of the population distribution and the movement process.}\\label{La}\n\\end{figure}\n\n\n\\begin{figure}\n\\includegraphics[width=12cm]{L4.eps} \n\\caption{Behaviour in a larger range of the disorder parameter $\\alpha$ for $\\lambda=0$. The lattice size is $L=40$, and $\\Delta T_O=32$ here. The data are averaged over $500$ independnet realizations of the population distribution and the movement process.}\\label{L4}\n\\end{figure}\n\n\n\n\n\\end{document}\n\n\n", "meta": {"hexsha": "6e842a30e7c1910cf832933d8ca86dbde16d11b3", "size": 29816, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "EE-0.tex", "max_stars_repo_name": "ocadni/city_entropy_efficiency", "max_stars_repo_head_hexsha": "a08cf4386185ed44e5ac2ebd1fbfaa0f96457498", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "EE-0.tex", "max_issues_repo_name": "ocadni/city_entropy_efficiency", "max_issues_repo_head_hexsha": "a08cf4386185ed44e5ac2ebd1fbfaa0f96457498", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EE-0.tex", "max_forks_repo_name": "ocadni/city_entropy_efficiency", "max_forks_repo_head_hexsha": "a08cf4386185ed44e5ac2ebd1fbfaa0f96457498", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 72.0193236715, "max_line_length": 1878, "alphanum_fraction": 0.7378253287, "num_tokens": 8449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.3247126034604596}}
{"text": "\\subsection{Atom Transition Moments}\\index{Transition!dipole moments}\\index{Polarizability!atomic transition}\r\n\\index{Dipole!transition}\\index{Exponents!transition dipole}\r\n\\index{Polarizability}\\label{oscil}\r\n\\index{Oscillator}\r\nA system can go from the ground state to an excited  state as the result of the\r\nabsorption of a photon.  The probability of this happening, $\\kappa$, is\r\ngiven\\footnote{\\samepage Wilson Decius and Cross,  ``Molecular Vibrations'', p\r\n163, McGraw-Hill (1955)} in terms of the  oscillator integral:\r\n\\begin{eqnarray}\r\n<\\!\\Psi_{0}|\\stackrel{\\rightharpoonup}{r}|\\Psi_{*}\\!> \\label{os1},\r\n\\end{eqnarray}\r\nby\r\n$$\r\n\\kappa = \\frac{8\\pi^3}{3ch}\\nu_{n'n''}(N_{n'}-N_{n''})\r\n<\\!\\Psi_{0}|\\stackrel{\\rightharpoonup}{r}|\\Psi_{*}\\!>^2 .\r\n$$\r\nFor electronic photoexcitations, $\\Psi_A$ are state functions:\r\n$$\r\n\\Psi_A = \\sum_ic_i\\Psi_i,\r\n$$\r\nand the $\\Psi_i$ are microstates; see p.~\\pageref{sd} for a\r\ndefinition of microstates.\r\n\\subsubsection*{Some Mathematical tools}\r\nIn order to evaluate \\ref{os1}, a property of integrals of the type:\r\n$$\r\n<\\!\\psi_{i}|\\stackrel{\\rightharpoonup}{r}|\\psi_{j}\\!>\r\n$$\r\nwill be used several times.  This property is:\r\n$$\r\n<\\!\\psi_{i}|\\stackrel{\\rightharpoonup}{r}|\\psi_{i}\\!> = 0.\r\n$$\r\nFrom this, it follows that, if\r\n$$\r\n<\\!\\psi_{j}|\\stackrel{\\rightharpoonup}{r}|\\psi_{i}\\!> \\neq 0,\r\n$$\r\nthen\r\n$$\r\n<\\!\\psi_{i}|\\stackrel{\\rightharpoonup}{r}|\\psi_{j}\\!> =\r\n-<\\!\\psi_{j}|\\stackrel{\\rightharpoonup}{r}|\\psi_{i}\\!> .\r\n$$\r\nTo prove this relationship, consider the integral\r\n$$\r\n<\\!(\\psi_i+\\psi_j)|\\stackrel{\\rightharpoonup}{r}|(\\psi_i+\\psi_j)\\!>.\r\n$$\r\nObviously, this integral has a value of zero, therefore\r\n$$\r\n<\\!\\psi_i|\\stackrel{\\rightharpoonup}{r}|\\psi_i\\!>  +\r\n<\\!\\psi_j|\\stackrel{\\rightharpoonup}{r}|\\psi_i\\!>  +\r\n<\\!\\psi_i|\\stackrel{\\rightharpoonup}{r}|\\psi_j\\!>  +\r\n<\\!\\psi_j|\\stackrel{\\rightharpoonup}{r}|\\psi_j\\!>  =0.\r\n$$\r\nIn this expression, the first and fourth terms are obviously zero, therefore\r\n$$\r\n<\\!\\psi_j|\\stackrel{\\rightharpoonup}{r}|\\psi_i\\!>  =\r\n-<\\!\\psi_i|\\stackrel{\\rightharpoonup}{r}|\\psi_j\\!> .\r\n$$\r\n\r\n\\subsubsection{Evaluation of Transition Dipole}\r\n\r\n\\begin{table}\r\n\\caption{\\label{transx} ``$x$\" Transition Integrals}\r\n\\begin{center}\r\n\\begin{tabular}{l|ccccccccc} \\hline\r\n& $s$  &  $p_x$  &  $p_y$  &  $p_z$  &  $d_{x^2-y^2}$  & $d_{xz}$  &\r\n$d_{z^2}$  &  $d_{yz}$  &  $d_{xy}$ \\\\ \\hline\r\n$s$ & X$_A$\\\\\r\n$p_x$ & sp & X$_A$\\\\\r\n$p_y$  & 0 & 0 & X$_A$ \\\\\r\n$p_z$  & 0 & 0 & 0 & X$_A$\\\\\r\n$d_{x^2-y^2}$ & 0 & pd & 0 & 0 & X$_A$\\\\\r\n$d_{xz}$      & 0 & 0 & 0 & pd & 0 & X$_A$\\\\\r\n$d_{z^2}$     & 0 & -$\\frac{1}{\\sqrt{3}}$pd & 0 & 0 & 0 & 0 & X$_A$\\\\\r\n$d_{yz}$      & 0 & 0 & 0 & 0 & 0 & 0 & 0 & X$_A$\\\\\r\n$d_{xy}$      & 0 & 0 & pd & 0 & 0 & 0 & 0 & 0 & X$_A$\\\\  \\hline\r\n\r\n\r\n\\end{tabular}\\\\\r\n\\hspace{-0.3in}Note: X$_A$ = $<\\! \\phi_{\\lambda}|\\stackrel{\\rightharpoonup}{x}|\\phi_{\\lambda}\\! >$;\r\nsp = $<\\! ns|\\stackrel{\\rightharpoonup}{r}|np\\! >$; pd = $<\\! np|\\stackrel{\\rightharpoonup}{r}|nd\\! >$ (see below).\r\n\\end{center}\r\n\\end{table}\r\n\r\nThe probability, $B_{0\\rightarrow *}$, that a photon will be absorbed by a system that has a\r\nground state $\\Psi_0$ and an excited state $\\Psi_*$ separated by an energy $\\epsilon$ when\r\nirradiated by an energy density $\\rho_{\\epsilon}$\r\nis given by\r\n$$\r\nB_{0\\rightarrow *} = \\frac{2\\pi}{3\\hbar^2}|R_{0*}|^2\\rho_{\\epsilon},\r\n$$\r\nin which\r\n$$\r\n|R_{0*}|^2 = |X_{0*}|^2 + |Y_{0*}|^2 + |Z_{0*}|^2.\r\n$$\r\n\r\n$X_{0*}$ is the matrix element for the $x$ component of the dipole moment:\r\n$$\r\nX_{0*} = \\int \\Psi_0|e\\sum_j \\stackrel{\\rightharpoonup}{x_j} |\\Psi_* d\\tau.\r\n$$\r\n\r\nEvaluation of this integral requires evaluating the effect of the operators  $\\stackrel{\\rightharpoonup}{x_j}$,\r\n$\\stackrel{\\rightharpoonup}{y_j}$, and $\\stackrel{\\rightharpoonup}{z_j}$\r\nacting on an atomic orbital.  Tables \\ref{transx}, \\ref{transy}, and \\ref{transz} show\r\nthe integrals of the type $<\\! \\phi_{\\lambda}\r\n |\\stackrel{\\rightharpoonup}{r_j}|\\phi_{\\sigma}\\!>$, where $\\phi_{\\lambda}$ and $\\phi_{\\sigma}$ are\r\n pairs of atomic orbitals.\r\n\r\n\r\nThe integral\r\n $<\\! \\phi_{\\lambda}|\\stackrel{\\rightharpoonup}{r}|\\phi_{\\lambda}\\! >$ is simply the appropriate Cartesian coordinate,\r\nthat is, the $x$, $y$, or $z$ coordinate of the atom that $\\phi_{\\lambda}$ is on.\r\n\r\n\\begin{table}\r\n\\caption{\\label{transy} ``$y$\" Transition Integrals}\r\n\\begin{center}\r\n\\begin{tabular}{l|ccccccccc} \\hline\r\n& $s$  &  $p_x$  &  $p_y$  &  $p_z$  &  $d_{x^2-y^2}$  & $d_{xz}$  &\r\n$d_{z^2}$  &  $d_{yz}$  &  $d_{xy}$ \\\\ \\hline\r\n$s$ & Y$_A$\\\\\r\n$p_x$ & 0 & Y$_A$\\\\\r\n$p_y$  & sp & 0 & Y$_A$ \\\\\r\n$p_z$  & 0 & 0 & 0 & Y$_A$\\\\\r\n$d_{x^2-y^2}$ & 0 & 0 & -pd & 0 & Y$_A$\\\\\r\n$d_{xz}$      & 0 & 0 & 0 & 0 & 0 & Y$_A$\\\\\r\n$d_{z^2}$     & 0 & 0 & -$\\frac{1}{\\sqrt{3}}$pd & 0 & 0 & 0 & Y$_A$\\\\\r\n$d_{yz}$      & 0 & 0 & 0 & pd & 0 & 0 & 0 & Y$_A$\\\\\r\n$d_{xy}$      & 0 & pd & 0 & 0 & 0 & 0 & 0 & 0 & Y$_A$\\\\  \\hline\r\n\r\n\r\n\\end{tabular}\\\\\r\n\\end{center}\r\n\\end{table}\r\n\r\n\r\n $<\\! ns|\\stackrel{\\rightharpoonup}{r}|np\\! >$\r\n and  $<\\! np|\\stackrel{\\rightharpoonup}{r}|nd\\! >$\r\n can be evaluated using the following expressions:\r\n\r\n$$\r\n<\\! ns|\\stackrel{\\rightharpoonup}{r}|np\\! > = a_0\\frac{(2n+1).2^{2n+1}.(\\xi_s\\xi_p)^{n+1/2}}{\\sqrt{3}(\\xi_s+\\xi_p)^{2n+2}}\r\n$$\r\n\r\n$$\r\n<np|\\stackrel{\\rightharpoonup}{r}|nd>=a_0\\frac{(n_p+n_d+1)!.2^{n_p+n_d+1}.\\xi_p^{n_p+1/2}.\\xi_d^{n_d+1/2}}\r\n{\\sqrt{5}(\\xi_p+\\xi_d)^{n_p+n_d+2}.\\sqrt{(2n_p)!(2n_d)!}},\r\n$$\r\nwhere $ns$, $np$, and $nd$ are $s$, $p$, and $d$ quantum numbers, respectively.\r\nFor the $sp$ transition, $n=ns=np$.\r\nThe Slater orbital exponents, $\\xi_s$, $\\xi_p$, and $\\xi_d$, are usually\r\ngiven in atomic units, that is, in\r\ninverse Bohr, therefore they must converted to \\AA ngstroms before use, hence the\r\npresence of the $a_0=0.529$ in these expressions.\r\n\r\nAll integrals of the type used here are in \\AA ngstroms, therefore the units of the integral\r\nof the dipole operator on a M.O. is also in \\AA ngstroms:\r\n$$\r\n<\\! \\psi_i|\\stackrel{\\rightharpoonup}{r}|\\psi_j\\! > =\\sum_{\\lambda}\\sum_{\\sigma}c_{\\lambda i}c_{\\sigma j}\r\n<\\! \\phi_{\\lambda}\\stackrel{\\rightharpoonup}{r}\\phi_{\\sigma} \\!>,\r\n$$\r\n Once the value of the integral is known,\r\nthe phase to be used must be determined. The simplest way to achieve this\r\nis to reverse the sign of the oscillator whenever the second M.O.\\ has a\r\nhigher index than the first.\r\n\r\n\\begin{table}\r\n\\caption{\\label{transz} ``$z$\" Transition Integrals}\r\n\\begin{center}\r\n\r\n\\begin{tabular}{l|ccccccccc} \\hline\r\n& $s$  &  $p_x$  &  $p_y$  &  $p_z$  &  $d_{x^2-y^2}$  & $d_{xz}$  &\r\n$d_{z^2}$  &  $d_{yz}$  &  $d_{xy}$ \\\\ \\hline\r\n$s$ & Z$_A$\\\\\r\n$p_x$ & 0 & Z$_A$\\\\\r\n$p_y$  & 0 & 0 & Z$_A$ \\\\\r\n$p_z$  & sp & 0 & 0 & Z$_A$\\\\\r\n$d_{x^2-y^2}$ & 0 & 0 & 0 & 0 & Z$_A$\\\\\r\n$d_{xz}$      & 0 & pd & 0 & 0 & 0 & Z$_A$\\\\\r\n$d_{z^2}$     & 0 & 0 & 0 & $\\frac{2}{\\sqrt{3}}$pd & 0 & 0 & Z$_A$\\\\\r\n$d_{yz}$      & 0 & 0 & pd & 0 & 0 & 0 & 0 & Z$_A$\\\\\r\n$d_{xy}$      & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & Z$_A$\\\\  \\hline\r\n\\end{tabular}\\\\\r\n\\end{center}\r\n\\end{table}\r\n\r\n\r\n  Evaluation of the integrals over microstates is straightforward,\r\nin that all integrals are zero, unless the number of differences between the microstates is exactly two,\r\nin which case the integral is equal to that of the two M.O.s involved, times a phase factor.  That is,\r\nfor each pair of microstates that are identical, except for $\\psi_i$\r\nin $\\Psi_a$ and  $\\psi_j$ in $\\Psi_b$, the integral is:.\r\n\r\n$$\r\n<\\! \\Psi_a|\\stackrel{\\rightharpoonup}{r}|\\Psi_b\\! > =<\\! \\psi_i|\\stackrel{\\rightharpoonup}{r}|\\psi_j\\! >*(-1)^n,\r\n$$\r\nwhere $n$ is the number of permutations necessary to move $\\psi_i$ in microstate $\\Psi_a$ to the position\r\noccupied by $\\psi_j$ in microstate $\\Psi_b$. This is\r\nsimilar to the `b' option on page~\\pageref{b}.  As with\r\nthe molecular orbitals, the oscillators for microstates change sign\r\nwhen the order of the microstates is reversed.  The simplest way to\r\nachieve this is to use the same device that was used with the M.O.s;\r\nthat is, to reverse the sign of the oscillator whenever the second\r\nmicrostate has a higher index than the first.\r\n\r\n\r\nFor completeness, the sign of $R_{0*}$ should be reversed if $k>l$, but\r\nsince only the modulus is used, this operation does not need to be done.\r\n\r\n\r\nFinally, the state transition dipole can be calculated from:\r\n$$\r\n<\\! \\Psi_A|\\stackrel{\\rightharpoonup}{r}|\\Psi_B\\! > =\\sum_a\\sum_bc_{A a}c_{B b}<\\! \\Psi_a\\stackrel{\\rightharpoonup}{r}\\Psi_b \\!>,\r\n$$\r\n\r\nAlthough the transition dipole is normally regarded as involving the ground and an excited state, it is\r\npossible to calculate the transition between two excited states.  The initial state is, by default, the\r\nground state, however if \\comp{ROOT=n} $n\\neq 1$, or any other keyword that specifies\r\na state other than the ground state, then the initial state will be an excited state.\r\n\r\nFor degenerate states, the transition dipole is the sum over all states involved.\r\n", "meta": {"hexsha": "a647a3239125cc7cd1f1d3d1efd1590cbdb048c0", "size": 8853, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "manuals/MOPAC2000_manual/t_oscillator.tex", "max_stars_repo_name": "openmopac/MOPAC-archive", "max_stars_repo_head_hexsha": "01510e44246de34a991529297a10bcf831336038", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-16T20:53:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T20:54:11.000Z", "max_issues_repo_path": "manuals/MOPAC2000_manual/t_oscillator.tex", "max_issues_repo_name": "openmopac/MOPAC-archive", "max_issues_repo_head_hexsha": "01510e44246de34a991529297a10bcf831336038", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "manuals/MOPAC2000_manual/t_oscillator.tex", "max_forks_repo_name": "openmopac/MOPAC-archive", "max_forks_repo_head_hexsha": "01510e44246de34a991529297a10bcf831336038", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.4246575342, "max_line_length": 130, "alphanum_fraction": 0.6188862532, "num_tokens": 3391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.32465432367792585}}
{"text": "% !TEX root=/home/tavant/these/manuscript/src/manuscript.tex\n\n\\section{Axial convection of the particles}\n  \\label{sec-reinjectionnoise}\n\n  As introduced in the previous section, the \\ac{2D} radial-azimuthal simulation does not model the axial convection of the particles.\n  This results in an ever increasing particle energy \\citep{lafleur2016a,heron2013}.\n  We present in this section an algorithm to model the convection of the particle.\n  Its drawbacks are discussed, and we propose a way to reduce them.\n  \n  \\subsection{Lafleur's model of convection}\n\n    \\citet{lafleur2016a} proposed a way to model the axial convection of the particles in \\ac{1D} purely azimuthal simulation.\n    \\Cref{fig-Fake_1d_1} shows a schematic illustration of the model.\n    The principle is as follows\n    \\begin{itemize}\n      \\item We set a finite axial length, noted $L_z$ in \\cref{fig-Fake_1d_1}.\n      \\item We follow the positions of the particle in the axial direction $z$\n      \\item When a particle crosses the boundary, it is removed.\n      \\item A new particle is created\n      \\begin{itemize}\n        \\item at $z=0$ for the ions\n        \\item  at $z=L_z$ for the electrons\n      \\end{itemize}\n    \\end{itemize}\n\n    We create a new particle in order to conserve the charge in the simulation.\n    The new particle has a random velocity following a Maxwellian flux distribution function of a given temperature.\n    The azimuthal position of the particle is chosen uniformly at random.\n\n    The Maxwellian flux distribution is the velocity distribution of the particles crossing a surface if the particles follow a Maxwellian distribution function. Thus we have\n    \\begin{equation} \\label{eq-Maxwflux} \n      f_{\\rm flux}(\\vect{v}) = \\vect{v} \\cdot \\vect{n} f_{\\rm M}(\\vect{v}),\n    \\end{equation}\n    with $f_{\\rm M}$ the Maxwellian distribution function defined in \\cref{eq-Maxwellian} and $\\vect{n}$ the vector normal to the surface.\n\n    \\begin{figure}[hbt]\n      \\centering\n      \\includegraphics[width=\\defaultwidth]{Fake_1d_2}\n      \\caption{Schematic representation of Lafleur's convection model \\citep{lafleur2016a}. The red particle is removed of the simulation, and the green particle is created. In this illustration, the particle is an ion, and the reinjection is at $z=0$. The x direction corresponds to the azimuthal direction.}\n      \\label{fig-Fake_1d_1}\n    \\end{figure}\n\n    Lafleur's model of convection has been adopted in \\ac{2D} by \\citet{croes2017a}.\n    The principle is exactly similar.\n    The particles are followed in the three directions, and a finite length is used to close the axial direction.\n    It is important to note that even if the particles are followed in the three directions, the meshed domain is only \\ac{2D}.\n    The simulation is not \\ac{3D}-\\ac{3V}, but only \\ac{2D}-\\ac{3V}.\n\n    In \\citet{croes2017a}, the authors have observed that if the newly created particle has a radial position chosen uniformly at random, it will affect the sheath.\n    Hence, they decided to use the same radial position as the removed particle.\n    \\Cref{fig-Fake_2d} presents a schematic representation of the convection model in \\ac{2D}.\n\n    \\begin{figure}[hbt]\n      \\centering\n      \\includegraphics[width=\\defaultwidth]{2_5D_dielectric_PPS_small}\n      \\caption{Schematic representation of the Lafleur's convection model adapted in \\acs{2D}. The new particle radial position corresponds to the removed particle, but its azimuthal position is chosen uniformly at random. }\n      \\label{fig-Fake_2d}\n    \\end{figure}\n\n    \\Cref{fig-energy_convection} shows the evolution as a function of time of the electron mean energy in a typical \\ac{2D} radial-azimuthal simulation, adapted from \\citet{croes2017}.\n    We can see that without the convection, the mean energy quickly rises to unphysical values.\n    When the convection is modeled, using an axial length of $L_z=1$ cm, the energy reaches a steady-state.\n    \\nomenclature[Q]{\\ensuremath{ L_z}}{ Axial length}\n    \\begin{figure}[hbt]\n      \\centering\n      \\includegraphics[width=\\defaultwidth]{energy}\n      \\caption{Time evolution of the electron mean energy when the convection is not modeled ($L_z \\rightarrow \\infty$) and with Lafleur's convection model used, $L_z = 1$ cm. Adapted from \\citet{croes2017}.}\n      \\label{fig-energy_convection}\n    \\end{figure}\n\n\n\n  \\subsection{Numerical artifacts}\n    \\citet{lafleur2016a} studied the impact of the convection model on the simulation results.\n    The authors observed in particular that changing the azimuthal length of the simulation domain could affect the simulation results.\n\n    \\Cref{fig-convection_numerical} shows the time evolution of the azimuthal electric field $E_{\\theta}$ from the \\ac{1D} simulation \\citep{lafleur2016a}.\n    \\nomenclature[Q]{\\ensuremath{ E_{\\theta}}}{ Azimuthal electric field}\n\n    On the first row (\\cref{fig-convection_numerical}.{\\bf a} and {\\bf b}), the length of the periodic azimuthal direction is $L_{\\theta}=0.5$~cm.\n    \\cref{fig-convection_numerical}.{\\bf a} corresponds to the case without axial convection.\n    We see that the \\ac{ECDI} rises and does not saturate.\n    The wavelength is short, of the order of $\\lambda = 1.5$~mm.\n    \\nomenclature[Q]{\\ensuremath{ \\lambda}}{ Wave length}\n    \\cref{fig-convection_numerical}.{\\bf b} corresponds to the same case as \\cref{fig-convection_numerical}.{\\bf a} but this time with the axial convection modeled.\n    We observe this time a saturation of the oscillation's amplitude, and the wavelength is close to $\\lambda \\simeq 1.5$~mm.\n\n    On the second row (\\cref{fig-convection_numerical}.{\\bf c} and {\\bf d}), the length of the periodic azimuthal direction is $L_{\\theta}=1$~cm.\n    \\cref{fig-convection_numerical}.{\\bf c} corresponds to the case without axial convection, and \\cref{fig-convection_numerical}.{\\bf d} corresponds to the same case but with the axial convection modeled.\n    In \\cref{fig-convection_numerical}.{\\bf c}, we can see that increasing the azimuthal length compared to \\cref{fig-convection_numerical}.{\\bf a} did not affect the \\ac{ECDI}, as expected.\n    However, in  \\cref{fig-convection_numerical}.{\\bf d}, the instability is clearly affected.\n    A single oscillation is observed, corresponding to $\\lambda=10$~mm, which seems almost undoubtedly unphysical.\n\n    \\begin{figure}[hbt]\n      \\centering\n\n      \\begin{tabular}{@{} cc @{}}\n        \\subfigure{Lafleur_NoLz_1}{a}{20, 20}  &\n        \\subfigure{Lafleur_Lz_1}{b}{20, 20} \\\\\n        \\subfigure{Lafleur_NoLz_2}{c}{20, 20} &\n        \\subfigure{Lafleur_Lz_2}{d}{20, 20} \\\\\n      \\end{tabular}\n      \\caption{Effects of Lafleur's convection model for two different azimuthal lengths on the azimuthal electric field. ({\\bf a}) No convection, $L_x=0.5$~cm,  ({\\bf b}) convection modeled, $L_x=0.5$~cm,  ({\\bf c}) No convection, $L_x=1$~cm,  ({\\bf d}) convection modeled, $L_x=1$~cm. The color of each plot is normalized to the maximum amplitude. Adapted from \\citep{lafleur2016a}. }\n      \\label{fig-convection_numerical}\n    \\end{figure}\n    \\FloatBarrier\n    \\citet{croes2017} observed similar behavior with the bidimensional  simulation.\n    The author investigated the values of the azimuthal length, which presented physical and unphysical results\n    for different values of the axial length.\n    \\Cref{fig-couplesCroes} shows the results obtained (adapted from \\citep{croes2017}).\n    We can see that for a given value of the axial length, the azimuthal length must be less than a specific value to present physical results.\n    However, the value of this upper limit depends on the axial length, such that if the axial length decreases, the upper limit of the azimuthal length decreases as well.\n    The dotted gray line is a rough representation of the limit between the physical and unphysical results. \n\n    \\begin{figure}[hbt]\n      \\centering\n      \\includegraphics[width=\\defaultwidth]{2D_couples.pdf}\n      \\caption{For 2D PIC simulations\\string: values of the azimuthal length and the axial length for which the simulation result is physical (similar to \\cref{fig-convection_numerical}.{\\bf b}) or unphysical  (similar to \\cref{fig-convection_numerical}.{\\bf d}). The dotted gray line is an approximation of the limit between the domains.}\n      \\label{fig-couplesCroes}\n    \\end{figure}\n\n    In the next section, we develop a theory that could explain the observation, and a new convection model for the simulation is proposed.\n\n  \\subsection{Numerical noise of Lafleur's convection model}\n\n    Let us consider Lafleur's convection model in \\ac{1D} on the charge density.\n    When computing the charge density on the mesh vertices, the axial position is not taken into account.\n    Consequently, the convection process illustrated in \\cref{fig-Fake_1d_1} is similar to moving a particle arbitrarily (read randomly).\n    Seen by the charge density, this is similar to Poisson noise, also named shot noise, on the charge density.\\footnote{In fact, this noise is the combination of Poisson noise with a uniform noise as we use a cloud in cell method. In addition it is happening twice for every particle convection, once with a positive charge and once with a negative charge. But the result is not affected by this simplification due to the central limit theorem.}\n\n    After a certain number of particles removed and created, the Poisson noise is similar to a Gaussian noise, also named thermal noise, following a normal distribution $\\N$. \n    \\nomenclature[Q]{\\ensuremath{ \\N }}{ Normal distribution.}\n    Hence, the charge density becomes \\footnote{One can note that the mean noise is strictly zero (with probability 1), as the charge density is conserved.}\n    \\begin{equation} \\label{eq-rhonoise}\n      \\rho = \\rho_0 + \\N(0, \\stdconv),\n    \\end{equation}\n    with $\\rho$ the charge density, $\\rho_0$ the charge density without the convection process, and $\\stdconv$ the standard deviation of the distribution of the noise associated with the convection model.\n    \\nomenclature[Q]{\\ensuremath{ \\rho}}{ Charge density}\n    \\nomenclature[Q]{\\ensuremath{ \\stdconv}}{ Standard deviation of the distribution of the noise associated with the convection model}\n    Surprisingly, the noise due to the convection model is similar to the numerical noise induced by the decomposition of the plasma into particles $\\N(0, \\sigma_{\\rm stat})$.\n    However, the amplitude of this statistical noise decreases with the number of particles per cell used\n    \\begin{equation*} \\label{eq-statistical}\n     \\sigma_{\\rm stat} \\propto \\frac{1}{\\sqrt{N_{pc}}}.\n    \\end{equation*}\n\n    On the other hand, the amplitude of the noise induced by the convection model depends on the plasma density $n$, the axis velocity of the particles $v_z$ and the axial length $L_z$\n    \\begin{equation} \\label{eq-convstd}\n     \\stdconv \\propto \\frac{n}{L_z} v_z.\n    \\end{equation}\n\n    We can see in \\cref{eq-convstd} that the amplitude of the convection induced noise on the charge density is proportional to the inverse of the axial length $L_z$.\n    This could explain the observation of \\cref{fig-couplesCroes} when using a smaller $L_z$.\n    However, it does not explain the effects of the azimuthal length observed in \\cref{fig-couplesCroes,fig-convection_numerical}.\n\n  \\subsection{Effect of the noise on the electric field}\n    \\label{sec-mathnoise}\n    In order to explain the impact of the azimuthal length on the instability, we can study the azimuthal electric field $\\aziE$ resulting of the charge density $\\rho$.\n    As the Poisson equation is linear, we have\n    \\begin{align}\n      \\aziE(\\theta) &= C + \\frac{1}{\\epsilon_0} \\int_0^{\\theta} \\rho(s) ds\\\\\n                    &= C + \\frac{1}{\\epsilon_0} \\int_0^{\\theta} (\\rho_0(s) + \\N(0, \\stdconv) ) ds \\\\ \n                    &= C + \\aziE_{, 0} + \\aziE_{, 1}\n    \\end{align}\n    with $C$ a constant that ensures that the periodical \\ac{BC} are respected.\n    The part of the electric field $\\aziE_{, 0}$ corresponds to the unperturbed charge density $\\rho_0$ and $\\aziE_{, 1}$  corresponds to the noisy charge density $\\N(0, \\sigma_{\\rm stat})$.\n    Hence, let us focus now on $\\aziE_{, 1}$.\n    We can study $\\aziE_{, 1}$ using two equivalent means\\string: the \\ac{FT} and the Brownian bridge.\n    \n    \\paragraph{Fourier Transform \\\\}\n      Applying the \\ac{FT} on the equation\n      \\begin{equation} \\label{eq-aziE1}\n        \\aziE_{, 1} = \\frac{1}{\\epsilon_0} \\int_0^{\\theta}  \\N(0, \\stdconv) ds\n      \\end{equation}\n      gives    \n      \\begin{align}\n        \\FFT \\lp \\aziE_{, 1} \\rp (k) &= \\frac{1}{\\epsilon_0} \\FFT \\lp \\int_0^{\\theta}  \\N(0, \\stdconv) ds \\rp \\\\\n                                     &= \\frac{1}{\\epsilon_0} \\frac{ \\N(\\mu_{\\rm FT}, \\sigma_{\\rm FT})}{k} \\label{eq-fft}\n      \\end{align}\n      \n      \\Cref{eq-fft} shows that $\\aziE_{, 1}$ also follows a Gaussian distribution, but with a non-zero mean value.\n      It is also inversely proportional to the wave number $k$.\n      Hence, when we increase the azimuthal length, which means that small wave numbers can exist in the simulation domain, the amplitude of $\\aziE_{, 1}$ increases as well.\n      \n    \\paragraph{Brownian Bridge\\\\}\n      \\Cref{eq-aziE1}, combined with the \\ac{BC}, is the definition of the a Brownian bridge.\n      \n      A Brownian bridge is a particular Brownian motion that reaches at a given distance the same value as the initial value.\n      Hence, we have \\citep{ibe2013}\n      \\begin{align*}\n        \\mathbb{E}(\\aziE_{, 1}) &= 0,  \\\\\n        {\\rm var}(\\aziE_{, 1}) &= \\stdconv^2 \\frac{L_{\\theta}^2}{4}\n      \\end{align*}\n    \n      Hence, the increase of the azimuthal length increases the amplitude of $\\aziE_{, 1}$.\n      \n    \n    We believe that when the amplitude of $\\aziE_{, 1}$ is too large, it can trigger an unphysical oscillation.\n    The next section uses this conclusion in order to adapt the convection model.\n    \n    \\subsection{Noiseless convection model}\n      \\label{sec-noiselessresults}\n      In the previous section, we have shown that the convection model induces a noise in the charge density, that produces an azimuthal electric field which amplitude depends on the azimuthal length.\n      \n      We propose here a modified version of Lafleur's convection model in order to remove the noise in the charge density.\n      The noiseless convection model follows the same algorithm as before, but the azimuthal position of the particle created is not chosen uniformly as random, but instead the new particle has the same position as the removed particle.\n      \\Cref{fig-fakez3} shows a schematic illustration of the noiseless convection algorithm applied on a particle.\n      \n      \\begin{figure}[hbt]\n        \\centering\n        \\includegraphics[width=\\defaultwidth]{Fake_1d_3}\n        \\caption{Illustration of the noiseless convection model}\n        \\label{fig-fakez3}\n      \\end{figure}\n      \n      We have implemented this modified convection model in the \\ac{2D} radial and azimuthal simulation.\n      \\Cref{fig-newconv_noconv} shows the time  evolution of the azimuthal electric field at the center of the radial dimension with and without the noiseless convection model.\n      It presents the same conditions as in \\cref{fig-convection_numerical}.{\\bf a} and {\\bf b}. \n      As previously, the convection stabilizes the growth of the instability to a steady-state, but it does not affect the physics.\n       \n      \n      \\begin{figure}[hbt]\n        \\centering\n        \\includegraphics[width=0.95\\textwidth]{Compare_no_new_Reinj_Oz}\n        \\caption{Time evolution of the azimuthal electric field at the center of the radial dimension with and without the noiseless convection model. }\n        \\label{fig-newconv_noconv}\n      \\end{figure}\n      \n      \n      \\Cref{fig-oldeconv_newconv} shows the time  evolution of the azimuthal electric field at the center of the radial dimension  with the convection modeled using Lafleur's model and the noiseless model with a small azimuthal length.\n      We can see that the two models give almost exactly the same results.\n      \n      \\begin{figure}[hbt]\n        \\centering\n        \\includegraphics[width=0.95\\textwidth]{Compare_old_new_Reinj_Oz}\n        \\caption{Time evolution of the azimuthal electric field at the center of the radial dimension with the convection modeled using (left) Lafleur's model and (right) the noiseless model with a small azimuthal length (0.325cm).}\n        \\label{fig-oldeconv_newconv}\n      \\end{figure}\n      \n      \n      \\Cref{fig-oldeconv_newconv_longLZ} shows the  time  evolution of the azimuthal electric field at the center of the radial dimension  with the convection modeled using Lafleur's model and the noiseless model but using a longer azimuthal length than \\cref{fig-oldeconv_newconv}.\n      In this case, we can see that Lafleur's convection model induces oscillations that are not observed with the noiseless model.\n      \n      \\begin{figure}[!hbt]\n        \\centering\n        \\includegraphics[width=0.95\\textwidth]{Compare_old_new_Reinj_Oz_LongLx}\n        \\caption{Time evolution of the azimuthal electric field at the center of the radial dimension with the convection modeled using (left) Lafleur's model and (right) the noiseless model with a longer azimuthal length (0.65cm).}\n        \\label{fig-oldeconv_newconv_longLZ}\n      \\end{figure}\n\n\n      These observations have shown that Lafleur's convection model induces a noise on the charge density, that does not affect the simulation when the domain size is small, but can rise numerical artifacts when the domain size is larger.\n      We have seen that minor modifications on the model do not affect the simulation results on a small domain, and allows us to use a larger simulation domain without any numerical artifact.\n      \n      \n          \n    \\subsection{Effects on a \\acs{2D} simulation domain}\n      \n      The mathematical development of \\cref{sec-mathnoise} has been done in \\ac{1D}.\n      We can legitimately wonder if the results  can be extended directly to a \\ac{2D} domain.\n      A mathematical definition of $\\aziE_{, 1}$ in \\ac{2D} is more difficult, as we have, neglecting the dielectric layers,\n      \\begin{equation} \\label{eq-aziE}\n        \\aziE_{, 1} = -\\partial_{\\theta} \\phi_1 \\text{ such that } \\grad \\cdot \\grad \\phi_1 = - \\frac { \\N(0, \\stdconv)}{\\epsilon_0} \\text{ following the \\ac{BC}}.\n      \\end{equation}\n      The \\ac{BC}s are\n      \\begin{itemize}\n        \\item periodic \\ac{BC} in the azimuthal direction,\n        \\item Dirichlet \\ac{BC} in the radial direction, modeling grounded walls,\n      \\end{itemize}\n      which translate as\n      \\begin{align}\n        &\\phi = 0 \\text{ for } r=0 \\text{ and } r=L_r, &\\forall \\theta \\label{eq-BC1} \\\\\n        &\\phi(\\theta = 0)= \\phi(\\theta = L_{\\theta}) , &\\forall r \\label{eq-BC2}\n      \\end{align}\n      \n      Solving \\cref{eq-aziE} with the conditions \\cref{eq-BC1,eq-BC2} analytically is much more difficult that the \\ac{1D} development, because of the Dirichlet \\ac{BC}.\n      \\nomenclature[N]{Dirichlet boundary condition\\string:}{ a type of boundary conditions for which the field is fixed. For instance for grounded electrodes on the plasma potential\\string: $\\phi = 0$}\n      \\nomenclature[N]{Neumann boundary condition\\string:}{ a type of boundary conditions for which the first derivative of the field field is fixed. For instance for a surface with surface charges on the plasma potential\\string: $\\deriv{\\phi}{x} = \\sigma$}\n      However, we can investigate it numerically, by solving \\cref{eq-aziE} for a given random source term.\n      Using a Monte Carlo approach, we average the results  200 times to better observe the mean behavior with respect to the noise (i.e. increasing signal to noise ratio).\n      For each computation, a normalized source term $\\rho_1 = \\N(0, 1)$ is generated over a \\ac{2D} domain, then the \\ac{2D} Poisson equation is solved numerically\\footnote{The SOR algorithm is used in this MC calculation. The iterations are stopped using a relative tolerance of $\\sn{2}{-6}$ on the mean square error.} to obtain $\\phi_1$, and the azimuthal electric field $\\aziE_{, 1} =- \\partial_{\\theta} \\phi_1 $ is computed.\n    \n      \\begin{figure}[!hbt]\n        \\centering\n        \\includegraphics[width=\\textwidth]{2D_MC_noise.png}\n        \\caption{Results for one case used in the Monte Carlo calculation with 100 cells in radial direction and 500 cells in the azimuthal direction, with (left) the normalized source term $\\rho = \\N(0, 1)$, (center) the azimuthal electric field, and (right) the plasma potential. }\n        \\label{fig-one}\n      \\end{figure}\n      \n      One typical result is shown in \\cref{fig-one}.\n      We can see the impact of the radial Dirichlet boundary conditions, \\cref{eq-BC1}, on the potential $\\phi_1$ induced by the noise.\n      The potential mostly oscillates in the azimuthal direction, and its amplitude is larger on the centerline between the walls.\n      A similar behavior is observed for the azimuthal electric field.      \n      \n      \\Cref{fig-dftLr} shows the \\ac{DFT} of the source term $\\rho_1$, the resulting azimuthal electric field $\\aziE_{, 1}$ and plasma potential $\\phi_1$ computed on the centerline of the simulation domain, for three different radial lengths expressed in number of cells in the radial direction $N_x$.\n      Is also shown the \"equivalent\" source term $\\rho_{\\rm eq}$, which is the source term that would give the frequency spectra of $\\aziE_{, 1}$ observed in a \\ac{1D} domain\n      \n      \\begin{equation} \\label{eq-equirho}\n        \\rho_{\\rm eq} = \\epsilon_0 \\partial_\\theta \\aziE_{, 1}.\n      \\end{equation}\n      The results are given for different radial lengths $N_x=15,50 \\text{ and } 200$, while the azimuthal length $N_y=200$ is kept constant.\n      We can see that the plasma potential and the electric field show larger amplitudes for small wave numbers (large wavelength) compared to large wave numbers in the three cases.\n      However, the amplitude of the smallest wave numbers is affected.\n      In the cases of small radial length ($N_x=15 \\text{ and } 50$), the spectra of the electric field is not monotonic.\n      This can be explained by the Dirichlet \\ac{BC}s that {\\it pins down} the fluctuation of the plasma potential.\n      \n      To compare the results to the purely azimuthal \\ac{1D} case, \\cref{fig-dftLr} shows the frequency spectra of the equivalent source term $\\rho_{\\rm eq}$.\n      We see that $\\rho_{\\rm eq}$ is always smaller than $\\rho_1$, and is significantly reduced in the small and large wavenumber.\n      However, even though the amplitude is reduced in \\ac{2D} with small radial direction compared to a \\ac{1D} model, we still observe large amplitude of small wave number oscillations in both the electric field and the plasma potential.\n      It means that the \\ac{2D} domain does not change significantly the effect of the numerical noise $\\rho_1$.\n      Hence, the conclusions of  \\cref{sec-mathnoise} derived in \\ac{1D} can be legitimately used for \\ac{2D} domains.\n      \n      \\begin{figure}[!hbt]\n        \\centering\n        \\includegraphics[width=\\textwidth]{effect_Lr_noEq1D.pdf}\n        \\caption{ DFT of the source term $\\rho_1 = \\N(0, \\stdconv)$, the resulting azimuthal electric field $\\aziE_{, 1}$ and plasma potential $\\phi$ computed on the centerline of a radial-azimuthal simulation, and the Equivalent \\acs{1D} source term defined by \\cref{eq-equirho}. The azimuthal length is $L_{\\theta}=50$ cm. The \\acs{DFT} are averaged 200 times  }\n        \\label{fig-dftLr}\n        \n      \\end{figure}\n\n\n\n\n", "meta": {"hexsha": "60b900a5ffa81ee59e408622dd8a19e02e68bd59", "size": 23563, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/Chapitre1/14_convection.tex", "max_stars_repo_name": "antoinetavant/PhD_thesis_manuscript", "max_stars_repo_head_hexsha": "1fdaf99356f75abc488edf1f30b5dd65f22bcdca", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Chapitre1/14_convection.tex", "max_issues_repo_name": "antoinetavant/PhD_thesis_manuscript", "max_issues_repo_head_hexsha": "1fdaf99356f75abc488edf1f30b5dd65f22bcdca", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Chapitre1/14_convection.tex", "max_forks_repo_name": "antoinetavant/PhD_thesis_manuscript", "max_forks_repo_head_hexsha": "1fdaf99356f75abc488edf1f30b5dd65f22bcdca", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 72.725308642, "max_line_length": 446, "alphanum_fraction": 0.7159529771, "num_tokens": 6257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3246543236779258}}
{"text": "\\chapter{Simulation}\n% put these two lines after every \\chapter{} command\n\\vspace{-2em}\n\\minitoc\nTo implement and research various FDIR systems on satellites an simulation of satellite dynamics and kinematics is developed. The focus of this thesis is on small satellites and more specifically cubesats. For the simulation of the ADCS of the satellite \\cite{auret2012design, JansevanVuuren2015, Jordaan2016} were referenced during the development of the satellite simulation. The simulation was developed in Python to simulate the dynamics and kinematics during a satellite orbit. The faults for the subsystems are also developed within the simulation and will be discussed within this chapter.\n\n\\section{Attitude Determination and Control System}\n\nFor the mission of the specific satellite in this document the main operational goal of the Attitude Determination and Control System (ADCS) on this specific satellite mission is to control the payload to point towards the centre of the earth. \n\n\\subsection{Coordinate Frames}\nThe coordinate frames in aerospace is a fundamental part of the ADCS. To determine the orientation and position of an object, it should be relative to a fixed frame. Consequently, the Earth inertial coordinate (EIC) frame is the fixed frame from which every other frame is relative to.\n\nA coordinate frame consists of three orthogonal vectors which is commonly referred to as x, y, and z. The axis of the coordinate frame is appropriately named as X-axis, Y-axis and Z-axis as seen in Figure... A vector (r) within the current coordinate frame can thus be expressed as \n\\begin{equation}\n\\overrightarrow{r} = x\\overrightarrow{i} + y\\overrightarrow{j} + z\\overrightarrow{k}\n\\end{equation}\nwhere the magnitude of $\\overrightarrow{r}$ is denoted as $|\\overrightarrow{r}|$ and is equal to \n\\begin{equation}\n|\\overrightarrow{r}| = \\sqrt{x^2 + y^2 + z^2}.\n\\end{equation}\n\nThe Earth-centered coordinate frames are dived into two, namely the EIC and earth fixed coordinate (EFC) frame. EFC is fixed to the earth and rotates with it. This frame is important with respect to where the satellite position is with regards to position's on earth, such as the ground station. It is also import for the modelling of the geomagnetic fields. \n\n% Insert a figure of the earth coordinate frames here\n\nThe EIC is defined as the Z-axis pointing towards the north pole, the X-axis pointing towards the Vernal Equinox, $\\Upsilon$, and the Y-axis completing the orthogonal set. The EFC is a copy of the EIC, with the Z-axis being identical, however the EFC rotates with the earth. The EFC in relation to the EIC can be expressed by a single angle of rotation, which is the Greenwich Hour Angle (GHA), $\\alpha_G$. With the knowledge of $t$ --- the elapsed time since $t_0$, $w_E$ --- the angular rate of the earth, and $\\alpha_{G,0}$ --- the GHA at $t = t_0$, $\\alpha_G$ can be calculated as \n\\begin{equation}\n\\alpha_G = w_Et + \\alpha_{G,0}\n\\end{equation}\nTo transform a vector from one coordinate frame to another, a transformation matrix, $\\boldsymbol{A}$, is required. For example vector $\\overrightarrow{r}_{EFC}$ can be transformed to $\\overrightarrow{r}_{EIC}$ with \n\\begin{equation}\n\\overrightarrow{r}_{EIC} = \\boldsymbol{A}^{EIC}_{EFC}\\overrightarrow{r}_{EFC}\n\\end{equation}\nwith $\\boldsymbol{A}^{EIC}_{EFC}$ being the EFC-to-EIC transformation matrix. Due to the definition of both coordinate frames, $\\boldsymbol{A}^{EIC}_{EFC}$ can be defined .\n\n\\begin{equation}\n\\boldsymbol{A}^{EIC}_{EFC} = \n\\begin{bmatrix}\n\tcos(\\alpha_G) & -sin(\\alpha_G) & 0\\\\\n\tsin(\\alpha_G) & cos(\\alpha_G) & 0 \\\\\n\t0 & 0 & 1\n\\end{bmatrix}\n\\end{equation}\n\nTo determine the satellite position, satellite coordinate frames must be used. Three satellite-centred coordinate frames are used, namely the inertial-reference coordinate frame (the satellite does not rotate), the orbit-referenced coordinate (ORC) frame and the satellite body coordinate (SBC) frame. The IRC frame is only acknowledged, since it is the frame that is fixed (as it does not rotate around the centre of the satellite), however it changes position with the orbit of the satellite. This frame is not used to determine the position of the satellite and will not be referenced for the remainder of this document.\n\nThe ORC frame changes location as the satellite moves, however the Z-axis is always pointing towards the centre of the earth, with the Y-axis being the anti-normal and the X-axis completing the orthogonal set. To transform a vector from the EIC frame to the ORC frame the unit position vector, $\\overrightarrow{r}_{sat}$ and the unit velocity vector, $\\overrightarrow{v}_{sat}$ in EIC \\cite{Chen_ground-target}.\n\n\\begin{equation}\n\t\\boldsymbol{A}^{ORC}_{EIC} = \n\t\\begin{bmatrix}\n\t\t\\hat{u} & \\hat{v} & \\hat{w}\\\\\n\t\\end{bmatrix}^T\n\\end{equation}\nwhere\n\\begin{equation}\n\\hat{w} = -\\frac{r_{sat}}{||r_{sat}||}\n\\end{equation}\n\\begin{equation}\n\\hat{v} = -\\frac{r_{sat} \\times v_{sat}}{||r_{sat} \\times v_{sat}||}\n\\end{equation}\n\\begin{equation}\n\\hat{u} = \\hat{v} \\times \\hat{w}\n\\end{equation}\n\nThe SBC frame is the frame fixed to the satellite and it is the relative rotation of the satellite in relation to the ORC. Thus for the mission of this satellite it is required that the SBC and ORC frames coincide. For the transformation of a vector from the ORC to SBC frame, the direct cosine matrix (DCM) also referred to as $\\boldsymbol{A}$ or $\\boldsymbol{A}^{SBC}_{ORC}$ is used. For the remainder of the document the DCM will be referred to as $\\boldsymbol{A}^{SBC}_{ORC}$ to avoid any confusion. The calculation of this transformation matrix will be discussed in $\\S$\\ref{subsection_quaternions}.\n\n% Insert a figure of the satellite coordinate frames here\n\n\\subsection{Attitude}\n\\label{subsection_quaternions}\nTo determine the attitude of an object, a model must be used to determine the rotation of an object in three dimensions. For this the visual and intuitive example of the Euler angles exist. Euler angles are the rotation of an object around three orthogonal axis, that change orientation with the rotation of the object. The three axes, denoted by X, Y and Z rotate with the object as depicted in Figure~\\ref{Figure-Euler_angles}.\n\n\\begin{figure}[h!tb]\n\\label{Figure-Euler_angles}\n\\begin{tikzpicture}[scale=2.5,tdplot_main_coords]\n\t%\\tdplotsetmaincoords{70}{110}\n\t% Set origin of main (body) coordinate system\n\t\\coordinate (O) at (0,0,0);\n\t\n\t% Draw main coordinate system\n\t\\draw[red, ,->] (0,0,0) -- (1,0,0) node[anchor=north east]{$x_{\\mathcal{I}}$};\n\t\\draw[red, ,->] (0,0,0) -- (0,1,0) node[anchor=north west]{$y_{\\mathcal{I}}$};\n\t\\draw[red, ,->] (0,0,0) -- (0,0,1) node[anchor=south]{$z_{\\mathcal{I}}$};\n\t\n\t\n\t\n\t% Intermediate frame 1\n\t\\tdplotsetrotatedcoords{-60}{0}{0}\n\t\\draw[tdplot_rotated_coords,->, blue] (0,0,0) -- (1,0,0) node[anchor=north east]{$x'$};\n\t\\draw[tdplot_rotated_coords,->, blue] (0,0,0) -- (0,1,0) node[anchor=west]{$y'$};\n\t\\draw[tdplot_rotated_coords,->, blue] (0,0,0) -- (0,0,1) node[anchor=west]{$z'$};\n\t\n\t\\tdplotsetrotatedthetaplanecoords{90}\n\t%draw theta arc and label\n\t%\\tdplotdrawarc[tdplot_rotated_coords,->,color=blue]{(0,0,0)}{0.5}{0}{350}{anchor=south west,color=gray}{$\\alpha$}\n\t\\tdplotdrawarc[tdplot_rotated_coords,->,color=gray]{(0,0,0)}{0.5}{80}{90}{anchor=south west,color=gray}{$\\alpha$}\n\t\\tdplotdrawarc[tdplot_rotated_coords,->,color=gray]{(0,0,0)}{0.5}{170}{180}{anchor=south west,color=gray,  yshift = -15 pt}{$\\alpha$}\n\t\n\t%% Intermediate frame 2\n\t\\tdplotsetrotatedcoords{-60}{15}{0}\n\t\\draw[,tdplot_rotated_coords,->, green] (0,0,0) -- (1,0,0) node[anchor=\n\tnorth]{};\n\t\\draw[,tdplot_rotated_coords,->, green] (0,0,0) -- (0,1,0)\n\tnode[anchor=west]{$y''$};\n\t\\draw[,tdplot_rotated_coords,->, green] (0,0,0) -- (0,0,1)\n\tnode[anchor=south]{$z''$};\n\t\\tdplotsetrotatedthetaplanecoords{60}\n\t%draw theta arc and label\n\t%\\tdplotdrawarc[tdplot_rotated_coords,->,color=green]{(0,0,0)}{0.5}{0}{350}{anchor=north,color=gray}{$\\beta$}\n\t\\tdplotdrawarc[tdplot_rotated_coords,->,color=gray]{(0,0,0)}{0.5}{80}{90}{anchor=north,color=gray}{$\\beta$}\n\t\\tdplotdrawarc[tdplot_rotated_coords,->,color=gray]{(0,0,0)}{0.5}{310}{320}{anchor=south west,color=gray}{$\\beta$}\n\t% \n\t% Rotate to final frame\n\t\\tdplotsetrotatedcoords{-60}{15}{45}\n\t\\draw[thick,tdplot_rotated_coords,->, cyan] (0,0,0) -- (1,0,0)\n\tnode[anchor=west]{$x_{\\mathcal{B}}$, \\textcolor{green}{$x''$}};\n\t\\draw[thick,tdplot_rotated_coords,->, cyan] (0,0,0) -- (0,1,0) node[anchor=west]{$y_{\\mathcal{B}}$};\n\t\\draw[thick,tdplot_rotated_coords,->, cyan] (0,0,0) -- (0,0,1) node[anchor=south]{$z_{\\mathcal{B}}$};\n\t\n\t\\tdplotsetrotatedthetaplanecoords{30}\n\t%draw theta arc and label\n\t%\\tdplotdrawarc[tdplot_rotated_coords,->,color=cyan]{(0,0,0)}{0.5}{0}{350}{anchor=north,color=gray}{$\\gamma$}\n\t\\tdplotdrawarc[tdplot_rotated_coords,->,color=gray]{(0,0,0)}{0.5}{215}{225}{anchor=north,color=gray, yshift = 15pt}{$\\gamma$}\n\t\\tdplotdrawarc[tdplot_rotated_coords,->,color=gray]{(0,0,0)}{0.5}{328}{338}{anchor=south west,color=gray}{$\\gamma$}\n\t\n\\end{tikzpicture}\n\\end{figure}\n\n\nEuler angles and DCM will be acknowledged and explained why they are not applicable.\nIn some literature the first and last quaternion are swapped.\n\n\\subsection{Satellite Kinematics and Dynamics}\n\n\\subsection{Rungka-kutta}\n\n\\section{Environment}\n\\subsection{Earth Orbit}\nEarth orbit according to sgp4 and also the placement of the earth sensor.\n\nShow plot of 3D earth orbit...\n\n\\subsection{Sun}\nThe calculations for the sun position and also the placement of the coarse and fine sun sensor.\n\nShow graph of sun plot...\n\n\\subsection{Geomagnetic field}\n\n\\begin{equation}\n\\label{Eq-Geomagnetic_field}\nV(r_s,\\theta, \\lambda) = R_E \\sum_{n=1}^{k}\\left(\\frac{R_E}{r_s}^{n+1}\\right)\\sum_{m=0}^{n}\\left(g_n^mcos(m\\lambda) + h_n^msin(m\\lambda)\\right)P_n^m(\\theta)\n\\end{equation}\n\nShow graph of geomagnetic plot...\n\n\\section{Sensor models}\n\\subsection{Position of Sensors and Field of View}\n\n\\subsection{Noise}\n\n\\section{Disturbance models}\n\\subsection{Gravity Gradient}\n\n\\subsection{Aerodynamic Disturbance}\n\\cite{Steyn2014}\n\n\\subsection{Wheel Imbalance}\n\n\\section{Attitude Determination}\nIn this section discuss the Kalman filter.\n\n\\subsection{Kalman Filter}\n\\cite{Jones2017}\n\n\\section{Attitude Control}\nMagnetic control during detumbling\nReaction wheel control during normal operation\n\n\\section{Constellations}\nExplain the design of the satellite constellations and the algorithms to run communicate between satellites.\n\n\\begin{algorithm}\n\t\n\t\\SetKwInOut{Input}{Input}\n\t\\SetKwInOut{Output}{Output}\n\t\n\t\\SetKwData{Left}{left}\n\t\\SetKwData{This}{this}\n\t\\SetKwData{Up}{up}\n\t\\SetKwFunction{Union}{Union}\n\t\\SetKwFunction{FindCompress}{FindCompress}\n\t\n\t\\Indm\n\t\\Input{Description of the input to the algorithm.}\n\t\\Output{Description of the output from the algorithm.}\n\t\\Indp\n\t\n\t\\BlankLine\n\t\n\t\\emph{Initialize hyperparameters}\\;\n\tGet initial data from satellite\\\\\n\tUpdate positions of each satellite\\\\\n\t\\For{$i\\leftarrow 1$ \\KwTo $N$}{\n\t\tDetermine $k$-nearest satellites to $satellite_i$ from the positions\\\\\n\t\tSelect data from nearest satellites\\\\\n\t\tSend nearest satellites predictions and data to $satellite_i$\\\\\n\t\tRetrieve data from $satellite_i$ and fault predictions of $k$-nearest satellites\\\\\n\t}\n\tUpdate position of $satellite_i$\\\\\n\tUpdate data of $satellite_i$\n\t\n\t\\caption[Do not end short caption with full-stop]{Algorithm example}\n\t\\label{alg}\n\t\n\\end{algorithm}\n\n\n\\section{Typical Faults}\nFor the simulation of the satellite and the induced faults to train and test various anomaly detection methodologies a database of typical faults is required. \\textcite{tafazoli2009study} made a study of the percentage of failure per subsystem. \n\n\\subsection{Probability of Fault Occurence}\nThe occurrence of a fault depends on the reliability of that equipment. \\textcite{Guo2014} studied the reliability of small satellites and calculated the parameters for the Weibull distribution based on real data. To model the probability of a fault to occur the probability density function is used \\cite{Jones2017}.\n\nThis probability however is small and for the training of the system the data is too sparse for the computational abilities of any regular PC. Thus the probability of a failure during training is fixed to $1/1000000$ to produce the data required for the anomaly detection with a million test samples.\n\n\\subsection{Set of faults}\nA set of typical faults for the ADCS is shown in Table~\\ref{ADCS fault table}. \n\n\\newpage\n\\begin{sidewaystable}[]\n\t\\label{ADCS fault table}\n\t\\begin{tabular}{|l|c|l|l|l|l|}\n\t\t\\hline\n\t\t\\multicolumn{6}{|c|}{\\textbf{Internal Faults}} \\\\ \\hline\n\t\t\\textbf{Fault classes} &\n\t\t\\multicolumn{1}{l|}{\\textbf{\\begin{tabular}[c]{@{}l@{}}Failure rate \\\\ per hour\\end{tabular}}} &\n\t\t\\textbf{Fault causes} &\n\t\t\\textbf{References} &\n\t\t\\textbf{Possible effect} &\n\t\t\\textbf{Possible permutations} \\\\ \\hline\n\t\t\\multirow{4}{*}{Reaction wheels} &\n\t\t\\multicolumn{1}{l|}{\\multirow{4}{*}{2.5E-7 \\cite{Spilhaus1987}}} &\n\t\t\\begin{tabular}[c]{@{}l@{}}Reaction wheel electronics \\\\ fail\\end{tabular} &\n\t\t\\cite{allen2012satellite} \\cite{Jacklin2019} &\n\t\t\\begin{tabular}[c]{@{}l@{}}Does not respond \\\\ to control inputs\\end{tabular} &\n\t\t\\begin{tabular}[c]{@{}l@{}}Momentum remains the same \\\\ or decreases slightly due to \\\\ friction\\end{tabular} \\\\ \\cline{3-6} \n\t\t&\n\t\t\\multicolumn{1}{l|}{} &\n\t\tOverheated reaction wheel &\n\t\t\\cite{Wintoft} &\n\t\tDecrease in speed &\n\t\t1\\% of initial speed per second \\\\ \\cline{3-6} \n\t\t&\n\t\t\\multicolumn{1}{l|}{} &\n\t\t\\begin{tabular}[c]{@{}l@{}}Catastrophic failure (cause \\\\ unknown)\\end{tabular} &\n\t\t\\cite{Choi2011} &\n\t\tStops rotating &\n\t\t0 \\\\ \\cline{3-6} \n\t\t&\n\t\t\\multicolumn{1}{l|}{} &\n\t\t\\begin{tabular}[c]{@{}l@{}}Increase in rotation speed \\\\ (Unknown cause)\\end{tabular} &\n\t\t\\begin{tabular}[c]{@{}l@{}}Gerhard Janse \\\\ van Vuuren\\end{tabular} &\n\t\t\\begin{tabular}[c]{@{}l@{}}Wheel speed \\\\ increases\\end{tabular} &\n\t\t\\begin{tabular}[c]{@{}l@{}}Between 90-100\\% of maximum \\\\ wheel speed\\end{tabular} \\\\ \\hline\n\t\tMagnetorquers &\n\t\t\\multicolumn{1}{l|}{ADCS fault table8.15E-9 \\cite{Spilhaus1987}} &\n\t\tPolarities are inverted &\n\t\t\\cite{Crowell2011} &\n\t\tIncorrect rotation &\n\t\t\\\\ \\hline\n\t\t\\multirow{2}{*}{Magnetometers} &\n\t\t\\multicolumn{1}{l|}{\\multirow{2}{*}{8.15E-9 \\cite{Spilhaus1987}}} &\n\t\tUnknown &\n\t\t\\begin{tabular}[c]{@{}l@{}}Gerhard Janse \\\\ van Vuuren\\end{tabular} &\n\t\tStops reacting &\n\t\t\\begin{tabular}[c]{@{}l@{}}Provides no feedback or the \\\\ output remains constant\\end{tabular} \\\\ \\cline{3-6} \n\t\t&\n\t\t\\multicolumn{1}{l|}{} &\n\t\t\\begin{tabular}[c]{@{}l@{}}Magnetometers and magne-\\\\ torquers interfered with \\\\ each other\\end{tabular} &\n\t\t\\cite{Jacklin2019} &\n\t\t\\begin{tabular}[c]{@{}l@{}}Noise on magneto-\\\\ meters and noise \\\\ on control of mag-\\\\ netorquers\\end{tabular} &\n\t\t\\begin{tabular}[c]{@{}l@{}}Between x3 and x5 times the \\\\ normal noise magnitude \\\\ Guassian distribution\\end{tabular} \\\\ \\hline\n\t\tEarth Sensor &\n\t\t- &\n\t\tUnknown &\n\t\t\\cite{Robertson2019} &\n\t\t\\begin{tabular}[c]{@{}l@{}}Noisy Earth Sensor \\\\ effected pointing \\\\ accuracy\\end{tabular} &\n\t\t\\begin{tabular}[c]{@{}l@{}}Between x5 and x10 times the \\\\ normal sensor noise based on \\\\ Guassian distribution\\end{tabular} \\\\ \\hline\n\t\t\\multirow{2}{*}{Sun sensor} &\n\t\t\\multirow{2}{*}{-} &\n\t\t\\begin{tabular}[c]{@{}l@{}}Cross-wired during instal-\\\\ lation\\end{tabular} &\n\t\t\\cite{Crowell2011} &\n\t\t\\begin{tabular}[c]{@{}l@{}}Erroneous \\\\ measurements\\end{tabular} &\n\t\tUniform random values \\\\ \\cline{3-6} \n\t\t&\n\t\t&\n\t\tUnknown &\n\t\t\\cite{Jacklin2019} &\n\t\tSun sensor fails &\n\t\toutput is 0 \\\\ \\hline\n\t\tStar tracker &\n\t\t- &\n\t\t\\begin{tabular}[c]{@{}l@{}}Shutter on star tracker is \\\\ closed\\end{tabular} &\n\t\t\\cite{Crowell2011} &\n\t\tStar tracker fails &\n\t\toutput is 0 \\\\ \\hline\n\t\tOverall control &\n\t\t- &\n\t\t\\begin{tabular}[c]{@{}l@{}}Incorrect control law or \\\\ variation \\\\ thereof\\end{tabular} &\n\t\t\\begin{tabular}[c]{@{}l@{}}Gerhard Janse \\\\ van Vuuren\\end{tabular} &\n\t\t\\begin{tabular}[c]{@{}l@{}}Angular velocity \\\\ suddenly increases \\\\ or decreases or \\\\ oscillation results\\end{tabular} &\n\t\t\\begin{tabular}[c]{@{}l@{}}Increase to 75 - 100\\% \\\\ Decrease to 0 - 25\\%\\\\ Oscillates\\end{tabular} \\\\ \\hline\n\t\t\\multirow{3}{*}{\\begin{tabular}[c]{@{}l@{}}Common data \\\\ transmission errors\\end{tabular}} &\n\t\t\\multirow{3}{*}{-} &\n\t\tSign flip &\n\t\t\\cite{Crowell2011} &\n\t\tProcessor-based &\n\t\t\\begin{tabular}[c]{@{}l@{}}Processor outputs and/or \\\\ inputs experience a sign flip\\end{tabular} \\\\ \\cline{3-6} \n\t\t&\n\t\t&\n\t\tBit flip &\n\t\tN/A &\n\t\t&\n\t\t\\begin{tabular}[c]{@{}l@{}}Processor outputs and/or \\\\ inputs experience a bit flip flip\\end{tabular} \\\\ \\cline{3-6} \n\t\t&\n\t\t&\n\t\tInsertion of zeros &\n\t\t\\cite{Jacklin2019} &\n\t\t&\n\t\t\\begin{tabular}[c]{@{}l@{}}Processor outputs and/or inputs \\\\ experience an insertion of a zero\\end{tabular} \\\\ \\hline\n\t\t\\begin{tabular}[c]{@{}l@{}}Possible sensors \\\\ errors\\end{tabular} &\n\t\t- &\n\t\tUnknown &\n\t\tN/A &\n\t\tHigh sensor noise &\n\t\t\\begin{tabular}[c]{@{}l@{}}Between x5 and x10 times the \\\\ normal sensor noise based on \\\\ Guassian distribution\\end{tabular} \\\\ \\hline\n\t\\end{tabular}\n\\end{sidewaystable}\n\n\\newpage", "meta": {"hexsha": "9cbdb33f3a18711c1ff8dcf14b492388acc6c9cd", "size": 17021, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapter/Simulation.tex", "max_stars_repo_name": "UlrichLouw/Masters_Latex", "max_stars_repo_head_hexsha": "92d341948a6c9dea47d987c9b9e7f55421960694", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapter/Simulation.tex", "max_issues_repo_name": "UlrichLouw/Masters_Latex", "max_issues_repo_head_hexsha": "92d341948a6c9dea47d987c9b9e7f55421960694", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter/Simulation.tex", "max_forks_repo_name": "UlrichLouw/Masters_Latex", "max_forks_repo_head_hexsha": "92d341948a6c9dea47d987c9b9e7f55421960694", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.6239067055, "max_line_length": 623, "alphanum_fraction": 0.7188766817, "num_tokens": 5448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251201477015, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.32462901325226506}}
{"text": "\\section{Scannerless parsing of streams}\n\nIn this section, we present a technique to write\ndescent\\hyp{}recursive parsers based on \\emph{streams}, a lazy data\nstructure available to \\OCaml by means of \\CamlpF, which is\ndistributed separately. We will not explain how to install \\CamlpF and\nwe refer the reader to any textbook on compilers for the basics on\ncontext\\hyp{}free grammars and, in particular, LL($k$) grammars.\n\nOur technique assumes that we already have an LL(1) grammar, and we\nwish to implement a parser to recognise the language it generates. In\npassing, it enables also a style called \\emph{scannerless parsing},\nmeaning that both the lexer, also called scanner, and the parser can\nbe expressed with the same feature, namely streams.\n\nWe will use the following formalism to express context\\hyp{}free\ngrammars. A grammar is a set of production rules, each one associating\na non\\hyp{}terminal symbol to a possibly empty sequence of terminals\nand non\\hyp{}terminals. These rules can be conceived as rewrite rules\nwhereby the non\\hyp{}terminal symbol, on the left\\hyp{}hand side, is\nrewritten into a series of symbols in the right\\hyp{}hand side, and\nthat is why we separate both sides with a rightwards\narrow. Non\\hyp{}terminals are names whose first letter is capitalised,\nwhereas terminals are named whose first letter is in lowercase. A word\nis a sequence of non\\hyp{}terminals. To avoid leaving blanks on the\npage, we will note~\\(\\varepsilon\\) the empty word. A Greek letter in\nlowercase represents a possibly empty concatenation of terminals and\nnon\\hyp{}terminals, in general, which means that the series may, in\nparticular, be a word. We will write \\(A \\stackrel{*}{\\Rightarrow}\n\\alpha\\) the relationship `$A$~derives~$\\alpha$'. Consider for example\nthe following ambiguous, context\\hyp{}free grammar for Boolean\nexpressions:\n\\begin{equation*}\nB \\rightarrow B \\, \\textsf{||} \\, B \\; \\mid \\; B \\, \\textsf{\\&\\&} \\, B\n\\; \\mid \\; \\textsf{!}B \\; \\mid \\; \\textsf{(}B\\textsf{)}\n\\; \\mid \\; \\textsf{true} \\; \\mid \\; \\textsf{false}\n\\end{equation*}\nWe will augment the formalism with rational operators, in order to\nhave a more compact notation: \\(\\alpha^*\\), \\(\\alpha^+\\),\n\\([\\alpha]\\), \\(\\{ A \\, a \\dots \\}^*\\) and \\(\\{ A \\, a \\dots\n\\}^+\\). Each occurrence of these operators can always be replaced by a\nnon\\hyp{}terminal whose defining rule is shown in\n\\fig~\\vref{fig:bnf_rel_op}.\n\\begin{figure}\n\\centering\n\\(\n\\begin{array}{llc}\n\\toprule\n  \\multicolumn{1}{c}{\\text{Notation}}\n& \\multicolumn{1}{c}{\\text{Definition}}\n& \\multicolumn{1}{c}{\\text{Constraint}}\\\\\n\\midrule\n  X \\rightarrow \\alpha^* \n& X \\rightarrow \\alpha X \\mid \\varepsilon\n& \\neg(\\alpha \\stackrel{*}{\\Rightarrow} \\varepsilon)\\\\\n  X \\rightarrow \\alpha^+ \n& X \\rightarrow \\alpha \\alpha^*\n& \\neg(\\alpha \\stackrel{*}{\\Rightarrow} \\varepsilon)\\\\\n  X \\rightarrow [\\alpha]\n& X \\rightarrow \\alpha \\mid \\varepsilon\n& \\neg(\\alpha \\stackrel{*}{\\Rightarrow} \\varepsilon)\\\\\n  X \\rightarrow \\{A \\, a \\ldots\\}^*\n& X \\rightarrow \\varepsilon \\mid A \\, (a A)^*\n& \\neg(A \\stackrel{*}{\\Rightarrow} \\varepsilon)\\\\\n  X \\rightarrow \\{A \\, a \\ldots\\}^+\n& X \\rightarrow A \\, (a A)^*\n& \\neg(A \\stackrel{*}{\\Rightarrow} \\varepsilon)\\\\\n\\bottomrule\n\\end{array}\\)\n\\caption{Rational operators for context\\hyp{}free grammars\n\\label{fig:bnf_rel_op}}\n\\end{figure}\nThese rules are LL(1) and it is suitable now that we define that\nproperty. LL(1) grammars are context\\hyp{}free grammars which can be\nused to recognise languages in a top\\hyp{}down way, with one token of\nlook\\hyp{}ahead. By `top\\hyp{}down', we actually mean rightwards in\nthe sense of the rules: Left to right scanning of the input, building\na Leftmost derivation (according to the production rules) with One\ntoken of look\\hyp{}ahead. In order to define them formally, we need\nfirst to define a couple of functions. Let us note~\\(\\mathcal{N}\\) the\nset of the non\\hyp{}terminals and~\\(\\Sigma\\) the set of the terminal\nsymbols.\n\n\\paragraph{The function \\emph{First}}\n\nThe function `First', noted~\\(\\mathcal{P}\\), maps each\nnon\\hyp{}terminal to the set of terminals that start any derivation\nfrom it. We have, for all non\\hyp{}terminal~\\(A\\),\n\\begin{equation*}\n\\first{A} := \\{ x \\in \\Sigma \\mid A \\stackrel{*}{\\Rightarrow} x\n\\alpha\\}.\n\\end{equation*}\n\n\\paragraph{The function \\emph{Follow}}\n\nThe function `Follow', noted~\\(\\mathcal{S}\\), maps each\nnon\\hyp{}terminal to the set of terminals that may follow each\noccurrences of the non\\hyp{}terminal. Formally, for all\nnon\\hyp{}terminal~\\(A\\),\n\\begin{equation*}\n\\follow{A} := \\{x \\in \\Sigma \\mid \\exists B \\in \\mathcal{N}.B\n\\stackrel{*}{\\Rightarrow} \\alpha A x \\beta\\}.\n\\end{equation*}\n\n\\paragraph{The LL(1) property}\n\nWe can now formally define LL(1) grammars as a set of production rules\n\\(A \\rightarrow \\alpha_1 \\mid \\alpha_2 \\mid \\ldots \\mid \\alpha_n\\)\nsatisfying\n\\begin{gather}\n\\neg(A \\stackrel{*}{\\Rightarrow} A \\alpha);\\label{P1}\\\\\n\\bigcap_{i=1}^{n} \\first{\\alpha_i} = \\varnothing;\\label{P2}\\\\\n\\alpha_i \\stackrel{*}{\\Rightarrow} \\varepsilon \\quad \\text{implies} \\quad\n\\first{\\alpha_j} \\cap \\follow{A} = \\varnothing, \\quad \\text{for all}\n\\; j.\\label{P3}\n\\end{gather}\nThe first constraint states that no rule can be left\\hyp{}recursive,\nneither directly, nor indirectly; the second affirms that no two words\nproduced by the same non\\hyp{}terminal can start with the same\nterminal; the third and last states that, if a word produced by a\nnon\\hyp{}terminal~\\(A\\) derives the empty word (it might derive\nnon\\hyp{}empty words as well), then the words derived from~\\(A\\)\nshould not start with a terminal following~\\(A\\) in the grammar.\n\nThese constraints can be extended to the rational operators we\nintroduced in \\fig~\\vref{fig:bnf_rel_op}, and the whole new definition\ncan be given an algorithmic style in \\fig~\\vref{fig:first_ext}.\n\\begin{figure}[!t]\n\\centering\n\\begin{framed}\n\\begin{align*}\n\\first{\\varepsilon} &= \\{\\varepsilon\\},\\\\\n\\first{x \\gamma} &= \\{x\\},\\\\\n\\first{B \\gamma} &= \\first{B},\\\\\n\\first{[\\beta] \\gamma} &= \\first{\\beta} \\cup \\first{\\gamma},\\\\\n\\first{\\{B \\; b \\ldots\\}^* \\gamma} &= \\first{B} \\cup \\first{\\gamma},\\\\\n\\first{\\{B \\; b \\ldots\\}^+ \\gamma} &= \\first{B},\\\\\n\\first{\\beta^*\\gamma} &= \\first{\\beta} \\cup \\first{\\gamma},\\\\\n\\first{\\beta^+\\gamma} &= \\first{\\beta},\\\\\n\\first{A} &= \\cup_{i=1}^{n}\\first{\\alpha_i}, \\quad \\text{if} \\; A\n\\rightarrow \\alpha_1 \\mid \\alpha_2 \\mid \\ldots \\mid \\alpha_n.\n\\end{align*}\n\\end{framed}\n\\caption{Extended definition of function First\\label{fig:first_ext}}\n\\end{figure}\nNote that we extended the definition of~\\(\\mathcal{P}\\)\nto~\\(\\varepsilon\\), even though it is not a non\\hyp{}terminal,\nand~\\(\\gamma\\) may derive~\\(\\varepsilon\\) (it is \\emph{nullable}). As\nfor~\\(\\mathcal{S}\\), the redefinition is seen in\n\\fig~\\vref{fig:follow_ext}.\n\\begin{figure}\n\\centering\n\\(\\begin{array}{@{}ll@{}}\n\\toprule\n\\multicolumn{1}{c}{\\text{Rule}} & \\multicolumn{1}{c}{\\text{Constraint}}\\\\\n\\midrule\n  X \\rightarrow \\ldots \\mid \\alpha A B \\beta\n& \\first{B} \\subseteq \\follow{A};\\\\\n  X \\rightarrow \\ldots \\mid \\alpha A \\{B \\; b \\dots\\}^+ \\beta\n& \\first{B} \\subseteq \\follow{A};\\\\\n  X \\rightarrow \\ldots \\mid \\alpha A [\\beta] \\gamma\n& \\first{\\beta} \\cup (\\first{\\gamma} \\setminus\n  \\{\\varepsilon\\}) \\cup \\follow{X} \\subseteq \\follow{A},\\\\\n& \\text{if} \\; \\gamma \\stackrel{*}{\\Rightarrow} \\varepsilon, \\;\n  \\text{else} \\; \\first{\\beta} \\cup \\first{\\gamma} \\subseteq \\follow{A};\\\\\n  X \\rightarrow \\ldots \\mid \\alpha A \\beta^* \\gamma\n& \\first{\\beta} \\cup (\\first{\\gamma} \\setminus\n  \\{\\varepsilon\\}) \\cup \\follow{X} \\subseteq \\follow{A},\\\\\n& \\text{if} \\; \\gamma \\stackrel{*}{\\Rightarrow} \\varepsilon, \\;\n  \\text{else} \\; \\first{\\beta} \\cup \\first{\\gamma} \\subseteq \\follow{A};\\\\\n  X \\rightarrow \\ldots \\mid \\alpha A\n& \\follow{X} \\subseteq \\follow{A};\\\\\n  X \\rightarrow \\ldots \\mid \\alpha A x \\beta\n& x \\in \\follow{A};\\\\\n  X \\rightarrow \\ldots \\mid \\alpha A \\beta^+ \\gamma\n& \\first{\\beta} \\subseteq \\follow{A};\\\\\n  X \\rightarrow \\ldots \\mid \\alpha A \\{B \\; b \\ldots \\}^* \\beta\n& \\first{B} \\cup (\\first{\\beta} \\setminus \\{\\varepsilon\\}) \\cup\n  \\follow{X} \\subseteq \\follow{A},\\\\\n& \\text{if} \\; \\beta \\stackrel{*}{\\Rightarrow} \\varepsilon,\n  \\text{else} \\; \\first{B} \\cup \\first{\\beta} \\subseteq \\follow{A};\\\\\n  X \\rightarrow \\ldots \\mid \\alpha \\{A \\; a \\dots\\}^* \\beta\n& \\{a\\} \\cup (\\first{\\beta} \\setminus \\{\\varepsilon\\}) \\cup \\follow{X}\n  \\subseteq \\follow{A},\\\\\n& \\text{if} \\; \\beta \\stackrel{*}{\\Rightarrow} \\varepsilon,\n  \\text{else} \\; \\{a\\} \\cup \\first{\\beta} \\subseteq \\follow{A};\\\\\n  X \\rightarrow \\ldots \\mid \\alpha \\{A \\; a \\dots\\}^+ \\beta\n& \\{a\\} \\cup (\\first{\\beta} \\setminus \\{\\varepsilon\\}) \\cup \\follow{X}\n  \\subseteq \\follow{A},\\\\\n& \\text{if} \\; \\beta \\stackrel{*}{\\Rightarrow} \\varepsilon,\n  \\text{else} \\; \\{a\\} \\cup \\first{\\beta} \\subseteq \\follow{A}.\\\\\n\\bottomrule\n\\end{array}\\)\n\\caption{Extended definition of function Follow\\label{fig:follow_ext}}\n\\end{figure}\nAny place where it is possible, we replace~\\(A\\) by \\([A]\\), \\(A^*\\)\nor~\\(A^+\\) --~the first replacement is mandatory for the\nimplementation technique we propose. Notice as well that the\nalgorithmic definition of~\\(\\mathcal{S}\\) consists in a collection of\ninclusion constraints \\(\\ldots \\subseteq \\follow{A}\\), whose smallest\nsolution is then~\\(\\follow{A}\\). (Contrast this with the definition\nof~\\(\\mathcal{P}\\).)\n\nFor reasons that will become apparent later, we will impose that our\ngrammars do not contain explicitly the empty word, therefore, in the\ncase of the rational expressions, the LL(1) property~\\vref{P3} takes\nthe shape\n\\begin{equation*}\n\\begin{array}{ll}\n\\toprule\n\\multicolumn{1}{c}{\\text{Rule}} & \\multicolumn{1}{c}{\\text{Constraint}}\\\\\n\\midrule\n  X \\rightarrow \\alpha^*\n& \\first{\\alpha} \\cup \\follow{X} = \\varnothing\\\\\n  X \\rightarrow \\alpha^+\n& \\first{\\alpha} \\cup \\follow{X} = \\varnothing\\\\\n  X \\rightarrow [\\alpha]\n& \\first{\\alpha} \\cup \\follow{X} = \\varnothing\\\\\n  X \\rightarrow \\{A \\; a \\ldots\\}^*\n& (\\first{A} \\cup \\{a\\}) \\cap \\follow{X} = \\varnothing\\\\\n  X \\rightarrow \\{A \\; a \\ldots\\}^+\n& \\{a\\} \\cap \\follow{X} = \\varnothing\\\\\n\\bottomrule\n\\end{array}\n\\end{equation*}\n\n\\paragraph{Stream constraints}\n\nThe method we propose in this section relies on LL(1) grammars with\nadditional constraints due to the semantics of streams; it will allow\nus to specify error messages only in the rules that may fail to parse\nthe input, so they can be tailored, without knowledge of the lexical\ncontext. Higher\\hyp{}order parser will be used to implement rational\noperators, so the functions matching stream patterns will be\nisomorphic to the constrained grammar, greatly improving the\nmaintenance of the program.\n\nLet us begin by the sort of constraints arising from the use of\nstreams for parsing. Simply put, we cannot implement as is the\nproduction rules which are left\\hyp{}recursive:\n\\begin{equation*}\nA \\rightarrow X \\, B \\mid C, \\quad \\text{where} \\; X\n\\stackrel{*}{\\Rightarrow} A.\n\\end{equation*}\nIndeed, since each non\\hyp{}terminal will be transformed into a\nfunction matching a stream, the parser for~\\(A\\) will try to match a\nlexeme by calling itself, recursively, which yields\nnon\\hyp{}termination. Another issue arises in the case\n\\begin{equation*}\nA \\rightarrow X \\, B \\mid C, \\quad \\text{where} \\; X\n\\stackrel{*}{\\Rightarrow} \\varepsilon.\n\\end{equation*}\nIf~\\(B\\) fails, the exception \\texttt{Stream.Failure} raised by the\nparser associated with~\\(B\\) becomes an exception\n\\texttt{Stream.Error} in the parser associated with~\\(A\\)\nbecause~\\(B\\) is not at the head of a rule, which interrupts the\nsyntax analysis, event though~\\(C\\) might have succeeded. It is clear\nthat there was never any danger in pursuing the analysis since no\nlexeme had been consumed from the stream by~\\(X\\). This limitation is\njustified by a simpler semantics for streams and can be overcome by\nrewriting the LL(1) grammar. Therefore, after making sure that the\ngrammar is not left\\hyp{}recursive, we must transform it according to\nthe following table:\n\\begin{equation*}\n\\begin{array}{@{}lcl@{}}\n\\toprule\n  X \\rightarrow [\\alpha] \\beta\n& \\textit{becomes} \n& X \\rightarrow \\alpha \\beta \\mid \\beta\\\\\n  X \\rightarrow \\alpha^* \\beta\n& \\textit{becomes}\n& X \\rightarrow \\alpha^+ \\beta \\mid \\beta\\\\\n  X \\rightarrow \\{A \\; a \\ldots\\}^* \\beta\n& \\textit{becomes}\n& X \\rightarrow \\{A \\; a \\ldots\\}^+ \\beta \\mid \\beta\\\\\n\\bottomrule\n\\end{array}\n\\end{equation*}\nNote that we assume that the language does not contain the empty word.\n\nThese constraints are relevant to our analysis method and it is\nperhaps suitable now to explain why parsers on streams are good tools\nin general, despite the constraints we just have mentioned. First, it\nis wrong to believe that these allow us to only analyse LL(1)\ngrammars. Let us consider the famous case of the `dangling else'. Let\nthe grammar\n\\begin{equation*}\n\\begin{array}{@{}ccl@{}}\nS & \\rightarrow & \\textsf{if} \\; \\textit{BoolExpr} \\;\n                  \\textsf{then} \\; S \\, S'\n                  \\mid \\textit{OtherInstr}\\\\\nS' & \\rightarrow & \\textsf{else} \\; S \\mid \\varepsilon\n\\end{array}\n\\end{equation*}\nThis grammar defines a conditional construct and it yields a\nshift/reduce conflict in parsers generated by tools like \\textsc{Yacc}\nwhen the lexical right\\hyp{}context is \\textsf{else}. That conflict\nboils down to decide whether a \\textsf{else} clause should be\nassociated to the last \\textsf{if} or not, as in the sentence\n\\begin{equation*}\n\\textsf{if} \\; b_1 \\; \\textsf{then} \\; \\textsf{if} \\; b_2 \\;\n\\textsf{then} \\; i_1 \\; \\textsf{else} \\; i_2.\n\\end{equation*}\nThe usual way to resolve this matter is to systematically associate a\n\\textsf{else} to the last \\textsf{if} encountered, from left to\nright. In \\OCaml with parsers on streams, the same effect is simply\nachieved by writing the pattern matching corresponding to\n\\(\\textsf{else} \\; S\\) first, so it is tried before~\\(\\varepsilon\\).\n\nIn fact, \\OCaml with parsers on streams can recognise contextual\nlanguages, thanks to higher\\hyp{}order functions. Let us consider the\nlanguage \\(\\{wcw \\,\\mid\\, w \\in (a+b)^*\\}\\), where \\(a\\), \\(b\\)\nand~\\(c\\) are terminal symbols. This is a contextual language because,\nin order to recognise the second occurrence of~\\(w\\), we need to\nsomehow `remember' (here goes the context) the first occurrence. In\n\\OCaml, we recognise the prefix~\\(w\\), then we dynamically build a\nparser for it, then, after reading~\\(c\\), we apply this previously\nconstructed parser to the stream to find the suffix~\\(w\\). First, let\nus write the parser for~\\(w\\):\n\\begin{alltt}\n\\textbf{let} \\textbf{rec} wd = \\textbf{parser}\n  [< ''a'; w=wd >] \\(\\rightarrow\\) (\\textbf{parser} [< ''a' >] \\(\\rightarrow\\) \"a\")::w\n| [< ''b'; w=wd >] \\(\\rightarrow\\) (\\textbf{parser} [< ''b' >] \\(\\rightarrow\\) \"b\")::w\n|             [<>] \\(\\rightarrow\\) []\n\\end{alltt}\nThe type of \\texttt{wd} is \\topout{char stream $\\rightarrow$ (char\n  Stream.t $\\rightarrow$ string) list}. The higher\\hyp{}order parser,\nwhich takes as an argument the list of parsers generated by\n\\texttt{wd}, and applies them to the current stream is defined as\nfollows:\n\\begin{alltt}\n\\textbf{let} \\textbf{rec} wu = \\textbf{function}\n  p::pl \\(\\rightarrow\\) (\\textbf{parser} [< x=p; w=wu pl >] \\(\\rightarrow\\) x^w)\n|    [] \\(\\rightarrow\\) (\\textbf{parser} [<>] \\(\\rightarrow\\) \"\")\n\\end{alltt}\nwhose type is \\topout{($\\alpha$ Stream.t $\\rightarrow$ string) list\n  $\\rightarrow$ $\\alpha$ Stream.t $\\rightarrow$ string}. Finally, the\nparser for our toy language is\n\\begin{alltt}\n\\textbf{let} wcw = \\textbf{parser} [< pl=wd; ''c'; w=wu pl >] \\(\\rightarrow\\) w\n\\end{alltt}\nwhose type is \\topout{char Stream.t $\\rightarrow$ string}. Then, we\ncan use it as follows:\n\n\\bigskip\n\n\\noindent\\topin{wcw (Stream.of\\_string \"abaacabaa\")}\n\n\\noindent\\topout{-~:~string = \"abaa\"}\n\n\n\\paragraph{Error handling}\n\nSince we rewrite any given LL(1) grammar so that the empty word does\nnot occur, we can use the stream pattern \\texttt{[<>]} or \\texttt{[< s\n    >]} to detect failures, but, first, let us define a type with two\nconstant constructors which are passed to all parsers, denoting, in\ncase of failure, whether the analysis should stop with an error\nmessage (abort), or resume (fail):\n\\begin{alltt}\n\\textbf{type} mode = Abort | Fail\n\\end{alltt}\nTo allow for the partial application of the parsers, we put the\nargument of type \\texttt{mode} in first position, and the general\nshape of the parsers is\n\\begin{alltt}\n\\textbf{let} my\\_parser mode = \\textbf{parser}\n  [< ... >] \\(\\rightarrow\\) ...\n| ...\n| [< ... >] \\(\\rightarrow\\) ...\n|   [< s >] \\(\\rightarrow\\) \\textbf{match} mode \\textbf{with}\n                 Fail  \\(\\rightarrow\\) raise Stream.Failure\n               | Abort \\(\\rightarrow\\) syntax\\_error \\emph{message} s\n\\end{alltt}\nwhere \\texttt{syntax\\_error} is a function which prints the error\nmessage about the first lexeme at the head of the stream~\\texttt{s}\nand stops the execution, for example by raising the predefined\nexception \\texttt{(Stream.Error s)}. We call \\texttt{(my\\_parser\n  Fail)} in head of a stream pattern, and \\texttt{(my\\_parser Abort)}\nin tail of a stream pattern. We will later see how to optimise this\ngeneral pattern, for instance, in case we know that\n\\texttt{my\\_parser} can never stop the parsing because it never occurs\nin tail of a stream pattern. We understand now why we take care of\nrewriting the grammar so it does not produce the empty word: the\nstream pattern \\texttt{[< s >]} can then be used for error handling.\n\n\\paragraph{Parser combinators}\n\nThe rational operators we have seen above are implemented by means of\nhigher\\hyp{}order parsers: their first parameter is the parser to\napply, the second is the parsing mode (of type \\texttt{mode} above)\nand the last is the stream to parse. This order makes it possible to\npartially evaluate a rational operator on its first argument and use\nthe resulting first\\hyp{}order parser as an argument to another\nhigher\\hyp{}order parser, giving rise to \\emph{parser combinators}.\n\\begin{itemize}\n\n  \\item \\(X \\rightarrow \\alpha^*\\)\\\\ The definition of~\\(\\alpha^*\\),\n    called the \\emph{Kleene star}, is \\(X \\rightarrow \\alpha X \\mid\n    \\varepsilon\\). Its \\OCaml implementation will evaluate in the list\n    of the parsed lexemes. As seen earlier, for the LL(1) property to\n    hold, the lexeme following \\(\\alpha^*\\) in the grammar must not be\n    recognisable by~\\(\\alpha\\). Moreover, we impose that~\\(\\alpha\\)\n    does not derive the empty word~\\(\\varepsilon\\). The general shape\n    of the implementation is then:\n\\begin{alltt}\n\\textbf{let rec} star p m = \\textbf{parser} [< x=p Fail; y=star p m >] \\!\\(\\rightarrow\\)\\! x::y\n                        |                       [<>] \\!\\(\\rightarrow\\) \\![]\n\\end{alltt}\n    Note that the mode~\\texttt{m} is not used because the call\n    to~\\texttt{p} must always be allowed to fail, with possibility to\n    resume parsing.\n\n  \\item \\(X \\rightarrow \\alpha^+\\)\\\\\n     The definition of this operator is \\(X \\rightarrow \\alpha\n     \\alpha^*\\). Its \\OCaml implementation relies on \\texttt{star} and\n     evaluates in the list of the parsed lexemes:\n\\begin{alltt}\n\\textbf{let} plus p m = \\textbf{parser} [< x=p m; y=star p m >] \\(\\rightarrow\\) x::y\n\\end{alltt}\n     Recall that the mode~\\texttt{m} in \\texttt{star} is not used\n     because \\texttt{p} is called there with \\texttt{Fail}. This\n     entails that, in general, the call \\texttt{(plus p Abort)} implies\n     the calls \\texttt{(p Abort)} and \\texttt{(p Fail)}.\n\n  \\item \\(X \\rightarrow [\\alpha]\\)\\\\\n    The definition of this operator is \\(X \\rightarrow \\alpha \\mid\n    \\varepsilon\\). We have the following straightforward\n    implementation:\n\\begin{alltt}\n\\textbf{let} opt p m = \\textbf{parser} [< x=p Fail >] \\(\\rightarrow\\) [x] | [<>] \\(\\rightarrow\\) []\n\\end{alltt}\n    Just as with the operator~\\(\\alpha^*\\), the parser~\\texttt{p} must\n    always be allowed to fail, hence the mode~\\texttt{m} is\n    useless. An alternative implementation could evaluate in a value\n    of the predefined type \\texttt{option}:\n\\begin{alltt}\n\\textbf{let} opt p m = \\textbf{parser} [< x=p Fail >] \\!\\(\\rightarrow\\)\\! Some x | [<>] \\!\\(\\rightarrow\\)\\! None\n\\end{alltt}\n\n  \\item \\(X \\rightarrow \\{A \\; a \\ldots\\}^+\\)\\\\\n    The definition of this operator is \\(X \\rightarrow A \\, (a\n    A)^*\\). If~\\texttt{p} is the parser for~\\(A\\) and~\\texttt{a}\n    denotes~\\(a\\), the implementation is as follows:\n\\begin{alltt}\n\\textbf{let} list\\_plus p a m =\n  \\textbf{let} aux m = \\textbf{parser} [< 'b \\textbf{when} a=b; c=p Abort >] \\(\\rightarrow\\) a::c\n\\textbf{in parser} [< x=p m; y=star aux m >] \\(\\rightarrow\\) x::y\n\\end{alltt}\n    Note that the call \\texttt{(list\\_plus p a Fail)} entails the\n    calls \\texttt{(p Fail)} and \\texttt{(p Abort)}.\n\n  \\item \\(X \\rightarrow \\{A \\; a \\ldots\\}^*\\)\\\\\n    The definition of this\n    operator is \\(X \\rightarrow \\varepsilon \\mid A \\, (a A)^*\\), hence\n\\begin{alltt}\n\\textbf{let} list\\_star p a m =\n  \\textbf{let} aux m = \\textbf{parser} [< 'b \\textbf{when} a=b; c=p Abort >] \\(\\rightarrow\\) a::c\n\\textbf{in parser} [< x=p Fail; y=star aux m >] \\(\\rightarrow\\) x::y | [<>] \\(\\rightarrow\\) []\n\\end{alltt}\n    Note the two calls \\texttt{(p Fail)} and \\texttt{(p Abort)} and\n    how the mode~\\texttt{m} is useless.\n\n\\end{itemize}\n\n\n\\paragraph{Optimisation}\n\nAll parsers have the same type, in particular they all take a mode as\nan argument. This mode can sometimes be useless when the parser in\nquestion is always at the head of a stream pattern or always in the\ntail: if the former, this is equivalent to always have the\n\\texttt{Fail} mode, whereas, in the latter, it is always\n\\texttt{Abort}. We can partially evaluate these parsers accordingly\nand we can do the same with the parser combinators implementing the\nrational operators. The pros are twofold: we create fewer closures at\nrun\\hyp{}time and we eliminate useless code; the cons are also\ntwofold: we need another analysis of the grammar and we lose the\npossibility to combine arbitrarily our parsers because their types may\nvary. The parser combinators are modified as follows.\n\\begin{itemize}\n\n  \\item \\(X \\rightarrow \\alpha^*\\)\\\\ We have seen above that the\n    parsing mode is irrelevant, so we can remove it and assume that,\n    if no lexeme can be recognised, the parser~\\texttt{p} may fail by\n    raising \\texttt{Stream.Failure}, but not abort by raising\n    \\texttt{Stream.Error} or an exception defined by the\n    programmer. We have the new definition\n\\begin{alltt}\n\\textbf{let rec} star p = \\textbf{parser} [< x=p; y=star p >] \\(\\rightarrow\\) x::y\n                      |                [<>] \\(\\rightarrow\\) []\n\\end{alltt}\n\n  \\item \\(X \\rightarrow \\alpha^+\\)\\\\ We must retain the parsing mode\n    for~\\texttt{plus} because it needs to be passed along to the\n    parser~\\texttt{p}. According to the optimisation of~\\(\\alpha^*\\)\n    above, we evaluate partially now~\\texttt{p} with the\n    mode~\\texttt{Fail}:\n\\begin{alltt}\n\\textbf{let} plus p m = \\textbf{parser} [< x=p m; y=star (p Fail) >] \\(\\rightarrow\\) x::y\n\\end{alltt}\n\n  \\item \\(X \\rightarrow [\\alpha]\\)\\\\\n    We remove the parsing mode, as with~\\texttt{star} above:\n\\begin{alltt}\n\\textbf{let} opt p = \\textbf{parser} [< x=p >] \\(\\rightarrow\\) [x] | [<>] \\(\\rightarrow\\) []\n\\end{alltt}\n\n  \\item \\(X \\rightarrow \\{A \\; a \\ldots\\}^+\\)\\\\ We keep the parsing\n    mode, as with~\\texttt{plus} above:\n\\begin{alltt}\n\\textbf{let} list\\_plus p a m =\n  \\textbf{let} aux = \\textbf{parser} [< 'b \\textbf{when} a=b; c=p Abort >] \\(\\rightarrow\\) a::c\n\\textbf{in parser} [< x=p m; y=star aux >] \\(\\rightarrow\\) x::y\n\\end{alltt}\n\n  \\item \\(X \\rightarrow \\{A \\; a \\ldots\\}^*\\)\\\\ We remove the parsing\n    mode, as with~\\texttt{star} above:\n\\begin{alltt}\n\\textbf{let} list\\_star p a =\n  \\textbf{let} aux = \\textbf{parser} [< 'b \\textbf{when} a=b; c=p Abort >] \\(\\rightarrow\\) a::c\n\\textbf{in parser} [< x=p Fail; y=star aux >] \\(\\rightarrow\\) x::y | [<>] \\(\\rightarrow\\) []\n\\end{alltt}\n\n\\end{itemize}\nThese optimisations give rise to three kinds of parsers:\n\\begin{enumerate*}\n\n  \\item \\emph{passing parsers}, which may fail by raising\n    \\texttt{Stream.Failure};\n\n  \\item \\emph{blocking parsers}, which may stop parsing, for example\n    by raising \\texttt{Stream.Error};\n\n  \\item \\emph{mixed parsers}, which may or may not stop parsing,\n    depending on the call context.\n\n\\end{enumerate*}\nThe grammar must be analysed to categorise all the non\\hyp{}terminals\nwith respect to these three kinds. First, we ignore the rational\noperators. If a non\\hyp{}terminal always appear at the start of a\nproduction, the corresponding parser is passing; if it always occur\ninside a production, the parser is blocking; otherwise, it is\nmixed. Second, we assume that the non\\hyp{}terminals appearing only\ninside rational operators are passing. Third, we consider the rational\noperators:\n\\begin{itemize}\n\n  \\item \\(\\alpha^*\\)\\\\ We distinguish the first word of~\\(\\alpha\\):\n    it is a non\\hyp{}terminal whose parser was deemed blocking, then\n    it becomes mixed. For each following non\\hyp{}terminal, if their\n    parser was passing, it becomes mixed.\n\n  \\item \\(\\alpha^+\\)\\\\ Let us leave aside the first word\n    of~\\(\\alpha\\). For each subsequent non\\hyp{}terminal, if the\n    corresponding parser was passing, it becomes mixed. We now\n    distinguish depending on the position of~\\(\\alpha^+\\) in the\n    grammar. If it occurs at the start of a production and if the\n    parser of the first word of~\\(\\alpha\\) was blocking, then it\n    becomes mixed. If~\\(\\alpha^+\\) does not occur at the start of a\n    production and if the parser of the first word of~\\(\\alpha\\)\n    was passing, then it becomes mixed.\n\n  \\item \\([\\alpha]\\)\\\\ Same as~\\(\\alpha^*\\).\n\n  \\item \\(\\{A \\; a \\ldots\\}^*\\)\\\\ The parser of~\\(A\\) becomes (or\n    remains) mixed.\n\n  \\item \\(\\{A \\; a \\ldots\\}^+\\)\\\\ Same as~\\(\\alpha^+\\).\n\n\\end{itemize}\nAll mixed parsers require a parameter for the parsing mode. Some\npassing or blocking parsers may also require such a parameter only for\ntyping reasons, for example if it is passed itself as an argument to\nthe parser combinators \\texttt{plus} or \\texttt{list\\_plus}. The\nblocking parsers have the shape\n\\begin{alltt}\n\\textbf{let} my\\_parser \\emph{mode\\(\\sp{\\text{opt}}\\)} = \\textbf{parser}\n  [< ... >] \\(\\rightarrow\\) ...\n| ...\n| [< ... >] \\(\\rightarrow\\) ...\n|   [< s >] \\(\\rightarrow\\) syntax\\_error \\emph{message} s\n\\end{alltt}\nNote that \\texttt{\\emph{mode\\(^{\\text{opt}}\\)}} means that the\nparameter \\texttt{mode} may be required for typing reasons. The\npassing parsers have the shape\n\\begin{alltt}\n\\textbf{let} my\\_parser \\emph{mode\\(\\sp{\\text{opt}}\\)} = \\textbf{parser}\n  [< ... >] \\(\\rightarrow\\) ...\n| ...\n| [< ... >] \\(\\rightarrow\\) ...\n\\end{alltt}\nNote that there is no pattern \\texttt{[<>]} or \\texttt{[< s >]}\nbecause the semantics of stream matching would naturally see an\nexception \\texttt{Stream.Failure} raised if the first lexeme in the\nstream matches no pattern. The mixed parsers have the shape we gave\nearlier, before considering any optimisations.\n\n\\paragraph{An example}\n\nLet us consider an example based on a real formal language called\n\\emph{Abstract Syntax Notation One} (ASN.1)~\\citep{Larmouth_1999,\n  Dubuisson_2001}, notoriously difficult to\nparse~\\citep{Rinderknecht_1995}. To keep things simple, we will only\nparse the header of a module, not the assignments it contains.\n\nThe name of the scanned file containing the module is set in a global\nreference:\n\\begin{alltt}\n\\textbf{let} file = ref \"\"\n\\end{alltt}\nand a location in that file is a pair of integer coordinates (line,\ncolumn):\n\\begin{alltt}\n\\textbf{type} loc = int \\(\\times\\) int\n\\end{alltt}\nThe keywords here are a small subset of all ASN.1 keywords:\n\\begin{alltt}\n\\textbf{type} kwd = ALL | AUTOMATIC | BEGIN | DEFINITIONS\n| END | EXPLICIT | EXPORTS | EXTENSIBILITY | FROM\n| IMPLICIT | IMPLIED | IMPORTS | TAGS\n\\end{alltt}\nSymbols are also in small number in our presentation:\n\\begin{alltt}\n\\textbf{type} sym =\n  Assign | Lbrace | Rbrace | Comma | Lparen | Rparen | SemiColon\n\\end{alltt}\nTo understand what these data constructors stand for, here is the\nfunction that provides their concrete syntax:\n\\begin{alltt}\n\\textbf{let} string\\_of\\_sym = \\textbf{function}\n  Assign \\(\\rightarrow\\) \"::=\" | Lbrace \\(\\rightarrow\\) \"{\" | Rbrace \\(\\rightarrow\\) \"}\" | Comma \\(\\rightarrow\\) \",\"\n| Lparen \\(\\rightarrow\\) \"(\" | Rparen \\(\\rightarrow\\) \")\" | SemiColon \\(\\rightarrow\\) \";\"\n\\end{alltt}\nThe concrete syntax of keywords is obvious, but we need a function\nnonetheless:\n\\begin{alltt}\n\\textbf{let} string\\_of\\_kwd = \\textbf{function}\n  ALL \\(\\rightarrow\\) \"ALL\" | AUTOMATIC \\(\\rightarrow\\) \"AUTOMATIC\" | BEGIN \\(\\rightarrow\\) \"BEGIN\"\n| DEFINITIONS \\(\\rightarrow\\) \"DEFINITIONS\" | END \\(\\rightarrow\\) \"END\" | TAGS \\(\\rightarrow\\) \"TAGS\"\n| EXPLICIT \\(\\rightarrow\\) \"EXPLICIT\" | EXPORTS \\(\\rightarrow\\) \"EXPORTS\" | FROM \\(\\rightarrow\\) \"FROM\" \n| EXTENSIBILITY \\(\\rightarrow\\) \"EXTENSIBILITY\" | IMPLICIT \\(\\rightarrow\\) \"IMPLICIT\"\n| IMPLIED \\(\\rightarrow\\) \"IMPLIED\" | IMPORTS \\(\\rightarrow\\) \"IMPORTS\"\n\\end{alltt}\nThe type for the tokens is\n\\begin{alltt}\n\\textbf{type} token =\n  Low    \\textbf{of} (loc \\(\\times\\) string)  (* Lowercase-starting identifier *)\n| Up     \\textbf{of} (loc \\(\\times\\) string)  (* Uppercase-starting identifier *)\n| ModRef \\textbf{of} (loc \\(\\times\\) string)  (* Module reference *)\n| Nat    \\textbf{of} (loc \\(\\times\\) string)  (* Natural number *)\n| Str    \\textbf{of} (loc \\(\\times\\) string)  (* String *)\n| Kwd    \\textbf{of} (loc \\(\\times\\) kwd)     (* Keyword *)\n| Sym    \\textbf{of} (loc \\(\\times\\) sym)     (* Symbol *)\n| EOF    \\textbf{of} loc              (* End of file (virtual token) *)\n\\end{alltt}\nThe only parser combinator we need are the following:\n\\begin{alltt}\n\\textbf{let} opt p = \\textbf{parser} [< x=p >] \\(\\rightarrow\\) Some x | [<>] \\(\\rightarrow\\) None\n\n\\textbf{let rec} star p = \\textbf{parser} [< x=p; y=star p >] \\(\\rightarrow\\) x::y\n                      |                [<>] \\(\\rightarrow\\) []\n\\end{alltt}\nNote that the constraints and optimisations above apply. We also need\n\\texttt{plus}, which requires parsing modes:\n\\begin{alltt}\n\\textbf{type} mode = Fail | Abort\n\n\\textbf{let} plus p m = \\textbf{parser} [< x=p m; y=star (p Fail) >] \\(\\rightarrow\\) x::y \n\\end{alltt}\nAt the head of a stream pattern, we shall use \\texttt{(plus p Fail)},\notherwise \\texttt{(plus p Abort)}. We need an exception to signal\nsyntax errors, and a way to print them:\n\\begin{alltt}\n\\textbf{exception} Error \\textbf{of} (loc \\(\\times\\) string)\n\n\\textbf{let} get\\_loc = \\textbf{function}\n  Low a | Up a | ModRef a | Str a | Nat a -> fst a\n| Sym (loc,\\_) | Kwd (loc,\\_) | EOF loc \\(\\rightarrow\\) loc\n\n\\textbf{let} stop token msg = raise (Error (get\\_loc token, msg))\n\n\\textbf{let} check msg = \\textbf{function}\n   Fail \\(\\rightarrow\\) raise Stream.Failure\n| Abort \\(\\rightarrow\\) \\textbf{parser} [< 't >] \\(\\rightarrow\\) stop t msg\n\\end{alltt}\nThe function \\texttt{check} performs the action corresponding to the\nparsing mode. We continue with the definitions of auxiliary parsers\ndedicated to tokens to be recognised in pattern tails, so we must stop\nparsing if they are not found:\n\\begin{alltt}\n\\textbf{let} modref = \\textbf{parser}\n  [< 'ModRef \\_ >] \\(\\rightarrow\\) ()\n| [< 't >] \\(\\rightarrow\\) stop t \"Module reference expected.\"\n\n\\textbf{let} kwd k = \\textbf{parser}\n  [< 'Kwd (\\_,k') \\textbf{when} k=k' >] \\(\\rightarrow\\) ()\n| [< 't >] \\(\\rightarrow\\) stop t (\"Keyword \"^ string\\_of\\_kwd k ^ \" expected.\")\n\n\\textbf{let} sym s = \\textbf{parser}\n  [< 'Sym (\\_,s') \\textbf{when} s=s' >] \\(\\rightarrow\\) ()\n| [< 't >] \\(\\rightarrow\\) stop t (\"Symbol \" ^ string\\_of\\_sym s ^ \" expected.\")\n\n\\textbf{let} nat = \\textbf{parser} [< 'Nat \\_ >] \\(\\rightarrow\\) ()\n               | [< 't >] \\(\\rightarrow\\) stop t \"Natural number expected.\"\n\\end{alltt}\nFinally, we can define the parser for ASN.1 modules:\n\\begin{alltt}\n\\textbf{let rec} moduleDefinition = \\textbf{parser}\n  [< \\_=moduleIdentifier;\n     ()=kwd DEFINITIONS;\n     \\_=opt tagDefault;\n     \\_=opt extensionDefault;\n     ()=sym Assign;\n     ()=kwd BEGIN;\n     s=moduleSuffix >] \\(\\rightarrow\\) s\n\n\\textbf{and} moduleIdentifier = \\textbf{parser}\n  [< 'ModRef \\_; \\_=opt definitiveIdentification >] \\(\\rightarrow\\) ()\n| [< 't >] \\(\\rightarrow\\) stop t \"Module identifier expected\"\n\n\\textbf{and} definitiveIdentification = \\textbf{parser}\n  [< 'Sym (\\_,Lbrace); \\_=plus definitiveObjIdComponent Abort;\n     ()=sym Rbrace; \\_=opt iriValue >] \\(\\rightarrow\\) ()\n\n\\textbf{and} iriValue = \\textbf{parser} [< 'Str \\_ >] \\(\\rightarrow\\) ()\n\n\\textbf{and} definitiveObjIdComponent mode = \\textbf{parser}\n  [< 'Nat \\_ >] \\(\\rightarrow\\) ()\n| [< 'Low \\_; \\_=opt num >] \\(\\rightarrow\\) ()\n| [< s >] \\(\\rightarrow\\) check \"OID component expected.\" mode s\n\n\\textbf{and} num = \\textbf{parser}\n  [< 'Sym (\\_,Lparen); ()=nat; ()=sym Rparen >] \\(\\rightarrow\\) ()\n\n\\textbf{and} tagDefault = \\textbf{parser}\n  [< 'Kwd (\\_,EXPLICIT);  ()=kwd TAGS >] \\(\\rightarrow\\) ()\n| [< 'Kwd (\\_,IMPLICIT);  ()=kwd TAGS >] \\(\\rightarrow\\) ()\n| [< 'Kwd (\\_,AUTOMATIC); ()=kwd TAGS >] \\(\\rightarrow\\) ()\n\n\\textbf{and} extensionDefault = \\textbf{parser}\n  [< 'Kwd (\\_,EXTENSIBILITY); ()=kwd IMPLIED >] \\(\\rightarrow\\) ()\n\n\\textbf{and} moduleSuffix = \\textbf{parser}\n  [< 'Kwd (\\_,EXPORTS); \\_=opt exports; ()=sym SemiColon;\n     \\_=opt imports; a=assignmentList >] \\(\\rightarrow\\) a\n|     [< \\_=imports; a=assignmentList >] \\(\\rightarrow\\) a\n|                [< a=assignmentList >] \\(\\rightarrow\\) a\n\n\\textbf{and} exports = \\textbf{parser} [< \\_=symbolList Fail >] \\(\\rightarrow\\) ()\n                   |      [< 'Kwd (\\_,ALL) >] \\(\\rightarrow\\) ()\n\n\\textbf{and} imports = \\textbf{parser}\n  [< 'Kwd (\\_,IMPORTS); \\_=opt imp1; ()=sym SemiColon >] \\(\\rightarrow\\) ()\n\n\\textbf{and} imp1 = \\textbf{parser} [< \\_=symbolList Fail; \\_=from >] \\(\\rightarrow\\) ()\n\n\\textbf{and} from = \\textbf{parser} [< ()=kwd FROM; \\_=modref; \\_=opt imp2 >] \\(\\rightarrow\\) ()\n\n\\textbf{and} imp2 = \\textbf{parser}\n  [< \\_=obj; \\_=opt imp1 >] \\(\\rightarrow\\) ()\n| [< 'Up \\_; \\_=opt braces; \\_=opt moreSymbols; \\_=from >] \\(\\rightarrow\\) ()\n| [< 'Low \\_; \\_=opt imp3 >] \\(\\rightarrow\\) ()\n\n\\textbf{and} obj = \\textbf{parser}\n  [< 'Sym (\\_,Lbrace); \\_=plus objIdComponents Abort;\n     ()=sym Rbrace >] \\(\\rightarrow\\) ()\n\n\\textbf{and} braces = \\textbf{parser} [< 'Sym (\\_,Lbrace); ()=sym Rbrace >] \\(\\rightarrow\\) ()\n\n\\textbf{and} moreSymbols = \\textbf{parser}\n  [< 'Sym (\\_,Comma); \\_=symbolList Abort >] \\(\\rightarrow\\) ()\n\n\\textbf{and} imp3 = \\textbf{parser}\n  [< \\_=braces; \\_=opt moreSymbols; \\_=from >] \\(\\rightarrow\\) ()\n|               [< \\_=moreSymbols; \\_=from >] \\(\\rightarrow\\) ()\n| [< 'Kwd (\\_,FROM); \\_=modref; \\_=opt imp2 >] \\(\\rightarrow\\) ()\n|                              [< \\_=imp1 >] \\(\\rightarrow\\) ()\n\n\\textbf{and} objIdComponents mode = \\textbf{parser}\n                            [< \\_=obj >] \\(\\rightarrow\\) ()\n| [< \\_=definitiveObjIdComponent Fail >] \\(\\rightarrow\\) ()\n| [< s >] \\(\\rightarrow\\) check \"OID component expected.\" mode s\n\n\\textbf{and} symbolList mode = \\textbf{parser}\n  [< \\_=symbol; \\_=opt moreSymbols >] \\(\\rightarrow\\) ()\n| [< s >] \\(\\rightarrow\\) check \"Reference expected.\" mode s\n\n\\textbf{and} symbol = \\textbf{parser} [< \\_=reference; \\_=opt braces >] \\(\\rightarrow\\) ()\n\n\\textbf{and} reference = \\textbf{parser} [< 'Up \\_ >] \\(\\rightarrow\\) () | [< 'Low \\_ >] \\(\\rightarrow\\) ()\n\n\\textbf{and} assignmentList = \\textbf{parser}\n  [< 'Kwd(\\_,END); s >] \\(\\rightarrow\\) after\\_END s\n|  [< 'EOF \\_ \\textbf{as} eof >] \\(\\rightarrow\\) stop eof \"Keyword END expected.\"\n|          [< 't; s >] \\(\\rightarrow\\) [< 't; assignmentList s >]\n\n\\textbf{and} after\\_END = \\textbf{parser}\n  [< 'EOF \\_ \\textbf{as} eof >] \\(\\rightarrow\\) [< 'eof >]\n|            [< 't >] \\(\\rightarrow\\) stop t \"End of file expected.\"\n\\end{alltt}\nNote that \\texttt{objIdComponents} and \\texttt{symbolList} retained\ntheir parsing mode parameter because the former is used as an argument\nto the parser combinator \\texttt{plus}, and the latter is used both at\nthe head (passing parser) and in the tail (blocking parser) of stream\npatterns. As explained earlier, the parsers have been derived from the\nstandard grammar, which has been transformed into LL(1) form first,\nthen the restrictions for streams were applied, for instance, not\nhaving a parser combinator for the empty word at the head of a\npattern.\n\nThe next step would be building up symbol tables for imported and\nexported definitions in the semantic actions, that is, on the\nright\\hyp{}hand side of the arrows in parsers, and then write another\nparser to recognise the tokens currently passed along by\n\\texttt{assignmentList} (third pattern), that is, the actual contents\nof the ASN.1 modules.\n", "meta": {"hexsha": "c85f70d143179832a4ded5ecf77130037fb2c03a", "size": 36570, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "streams.tex", "max_stars_repo_name": "rinderknecht/Book", "max_stars_repo_head_hexsha": "6f302ab1319c8ae9b3ea690c45fdb3d2b6fbca16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "streams.tex", "max_issues_repo_name": "rinderknecht/Book", "max_issues_repo_head_hexsha": "6f302ab1319c8ae9b3ea690c45fdb3d2b6fbca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "streams.tex", "max_forks_repo_name": "rinderknecht/Book", "max_forks_repo_head_hexsha": "6f302ab1319c8ae9b3ea690c45fdb3d2b6fbca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.706601467, "max_line_length": 116, "alphanum_fraction": 0.6761553186, "num_tokens": 11371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.3246290029262209}}
{"text": "%----------------------------------------------------------------------------------------\n%\tPACKAGES AND OTHER DOCUMENT CONFIGURATIONS\n%----------------------------------------------------------------------------------------\n\n\\documentclass[11pt]{article}\n\\usepackage{hyperref}\n\\input{structure.tex} % Include the file specifying the document structure and custom commands\n\n%----------------------------------------------------------------------------------------\n%\tASSIGNMENT INFORMATION\n%----------------------------------------------------------------------------------------\n\n% Required\n\\newcommand{\\assignmentQuestionName}{} % The word to be used as a prefix to question numbers; example alternatives: Problem, Exercise\n\\newcommand{\\assignmentClass}{Zero to ASIC} % Course/class\n\\newcommand{\\assignmentTitle}{Analogue Design} % Assignment title or name\n\\newcommand{\\assignmentAuthorName}{Thomas Parry} % Student name\n\n\n\n\n\n% Optional (comment lines to remove)\n%\\newcommand{\\assignmentClassInstructor}{Jones 10:30am} % Intructor name/time/description\n%\\newcommand{\\assignmentDueDate}{Monday,\\ January\\ 24,\\ 2019} % Due date\n\n%----------------------------------------------------------------------------------------\n\n\\begin{document}\n\n%----------------------------------------------------------------------------------------\n%\tTITLE PAGE\n%----------------------------------------------------------------------------------------\n\n\\maketitle % Print the title page\n\n\\thispagestyle{empty} % Suppress headers and footers on the title page\n\n\\newpage\n\n\n\\section{Fundamentals of the MOSFET}\n\nThe MOSFET (Metal-Oxide Semiconductor Field Effect Transistor) is the fundamental building block of modern IC design.\n\n\\begin{figure}[h]\n\\centering{\n\\includegraphics[scale=1.00]{diagrams/nmos.pdf}\n}\n\\end{figure}\n\nThe MOSFET is a \\textit{transconductance} device which translates a voltage between it's gate and source terminals to a current between the drain and source - assuming the device is biased correctly.\n\n\\subsection{The Saturation Region}\n\nMost devices in a circuit will be operating in saturation where the following description of the current is given for a square-law device:\n\n\\begin{equation}\nI_D = \\frac{1}{2} \\mu_n C_{ox} \\frac{W}{L} {\\left( V_{GS} - V_{TH} \\right)}^2\n\\end{equation}\n\nThis can be simplified to:\n\n\\begin{equation}\nI_D = K_n \\frac{W}{L} {V_{OD}}^2\n\\end{equation}\n\n\\begin{equation}\ngiven \\; that: \\;\\;\\; V_{DS} > V_{OD}\n\\end{equation}\n\nThe condition is very important, if you want your FET to work as expected you must ensure you have sufficient $V_{DS}$ headroom.  The value $V_{OD}$ is also more commonly called $V_{D_{SAT}}$ and is defined as the minimum drain voltage required to keep the device in saturation. Note that in sub-micron processes (like Skywater 130 nm) the statement that $V_{D_{SAT}} = V_{OD}$ is not fully accurate due to second order effects from device scaling.\n\n\n\\subsection{The Triode Region}\n\nWhen there is insufficient drain-source voltage (by design or error) the device will work in the triode region where it approximates a voltage controlled resistor:\n\n\\begin{equation}\nI_D = \\mu_n C_{ox} \\frac{W}{L} \\left( (V_{GS} - V_{TH}) V_{DS} - \\frac{V_{DS}^2}{2} \\right)\n\\end{equation}\n\n\\subsection{The Cutoff Region}\n\nWhen there is insufficient voltage across the gate-source terminals the device is 'off':\n\n\\begin{equation}\nI_D = 0 \\;\\;\\;\\; given \\; that: \\;\\; V_{GS} << V_{TH}\n\\end{equation}\n\n\n\\answer{Always know the region you expect your FET to operate and check that you have it correctly biased or all other assumptions are broken.}\n\n\\section{Basics of Transconductance Efficiency}\n\nThe transconductance is the amount of current in the drain per gate-source voltage.\n\n\\begin{equation}\ni_d = g_m \\cdot v_{gs}\n\\end{equation}\n\nThis simple diagram shows the most important concept of the FET: a voltage at the input is converted to an output current. This output current will later be converted by an impedance to another voltage.\n\n\\begin{figure}[h]\n\\centering{\n\\includegraphics[scale=1.00]{diagrams/nmos_smallsignal.pdf}\n}\n\\end{figure}\n\n\nThe transconductance can be expressed as a function of the bias current, giving the $g_m / I_d $ value. This value is related to how inverted the channel of the FET is - a measure of how 'turned on' the FET is. The measure of channel inversion is how many minority charge carriers have been attracted to the conductive channel between the source and drain.\n\n\\subsection{Transconductance Efficiency and Overdrive Voltage}\n\nThere is a relation to the overdrive voltage mentioned above, $V_{OD}$. The higher the $V_{OD}$, the more the FET is 'turned on', and therefore the more the FET channel is inverted, which leads to a \\textit{lower} $g_m / I_d$. Conversly, a lower $V_{OD}$ turns on the FET less, and therefore the FET channel is less inverted, which leads to a \\textit{higher} $g_m / I_d$.\n\n\\subsection{Realistic Values of Transconductance Efficiency}\n\nThere is a range of transconductance efficiencies that can be obtained in standard CMOS processes. It is reasonable to assume a maximum transconductance efficiency of 20 in design equations, although in some specific cases values of 25 can be reached. Typically a device will not be used below a transconductance efficiency of 4.\n\n\\subsection{Why Use Transconductance Efficiency?}\n\nWhile transconductance efficiency, $g_m/I_d$, feels very abstract at first, its use lies in two factors.\n\n\\begin{enumerate}\n  \\item It gives a strong indication of the channel inversion.\n  \\item It allows quick calculation of circuit currents and other conditions.\n\\end{enumerate}\n\nFor example, if I have determined I will use a FET in weak inversion and I need $1 \\; mS$ of transconductance, then I very simply know the required current of $50 \\; \\mu A$.\n\n\\answer{But how do we know what transconductance we should use for a given FET? We'll discuss this in the next section where I will talk about the relation of matching and noise to transconductance.}\n\n\\textbf{Further Reading (clickable)}\n\n\\hspace{1cm} \\href{http://web02.gonzaga.edu/faculty/talarico/EE406/documents/gmid.pdf}{gm/ID - Based Design}\n\n\\hspace{1cm} \\href{http://web.eecs.utk.edu/~bblalock/ece532/ece532_pres_ekv_bsim.pdf}{An Introduction to the EKV Model and a comparison of EKV to BSIM}\n\n\\end{document}\n", "meta": {"hexsha": "b6c42b122c5a1d0903ee1af6924f2d350b7192c9", "size": 6295, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/notes/analogue_notes.tex", "max_stars_repo_name": "markus-zzz/analogue_ic_template", "max_stars_repo_head_hexsha": "0a198e4820b681a79757a352863c5284652723c6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/notes/analogue_notes.tex", "max_issues_repo_name": "markus-zzz/analogue_ic_template", "max_issues_repo_head_hexsha": "0a198e4820b681a79757a352863c5284652723c6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/notes/analogue_notes.tex", "max_forks_repo_name": "markus-zzz/analogue_ic_template", "max_forks_repo_head_hexsha": "0a198e4820b681a79757a352863c5284652723c6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.6453900709, "max_line_length": 448, "alphanum_fraction": 0.6900714853, "num_tokens": 1503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3245571988530871}}
{"text": "% !TEX root = ../main.tex\n\\chapter{Sentiment Analysis}\n\\label{ch:sentimentAnalysis}\n\nSemantic orientation describes the strength and polarity of words and phrases used in text.\nExtraction of subjectivity and polarity of the text from the semantic orientation of its words and phrases is called sentiment analysis.\nThe huge volume of text-based interactions on social media makes it difficult\nto read and organize them, and manually analyze their sentiment.\nFocusing on single instances of interaction also makes it difficult to extract the overall sentiment,\nnecessitating a solution that performs and summarizes the analysis automatically, fast, and gives human-comprehensible results~\\cite{Sarlan2014}.\n\n\\section{Methods}\n\\label{sec:methods_sa}\n\nThe informal language used in statuses on Twitter, and the limited length, poses an additional difficulty\nto analyzing their sentiment.\nPrevious research showed supervised approaches to be superior to lexicon-based approaches~\\cite{Sarlan2014}.\nSince labeled data is available from the Sanders dataset~\\cref{sec:theSandersDataset},\nthis thesis will focus on supervised approaches.\nThe dataset was preprocessed using the preprocessing and tokenization functions introduced in~\\cref{sec:preprocessingAndTokenization} (without stopwords removal),\nand the following methods evaluated.\n\n\\subsection{Naive Bayes}\n\\label{subsec:naivebayes}\n\nThe naive Bayes algorithm works by first expressing the probability of a label given the features,\nin this case the sentiment given the bag of words that is the status, with Bayes rule:\n\n\\begin{equation}\n    P(label|features) = \\frac{P(label)*P(features|label)}{P(features)}\n\\end{equation}\n\nThe algorithm then naively assumes that all features are independent, giving:\n\n\\begin{equation}\n    P(label|features) = \\frac{P(label)*P(feature 1|label)*...*P(feature n|label)}{P(features)}\n\\end{equation}\n\n\nThe denominator $P(features)$ is not explicitly calculated.\nInstead, all numerators are calculated and the denominator is chosen such that all $P(label|features)$ sum to 1~\\cite{nltkDocs}.\n\\\\\nThe features of each status are extracted as a vector of every distinct word in the dataset,\ntogether with $True$ if the word can be found in the status, or $False$ if not.\nThe Python-code achieving this encoding can be seen in~\\cref{code:extract_features}.\n\n\\begin{figure}\n    \\caption{Encoding a status as a vector}\n    \\label{code:extract_features}\n    % @formatter:off\n    \\begin{minted}{python}\n        # Contains every word in the dictionary and whether the status contains it.\n        features = {}\n        # Using the previously created dictionary\n        for word in dictionary:\n            features['contains(\\%s)' \\% word] = (word in document_words)\n    \\end{minted}\n    % @formatter:on\n\\end{figure}\n\nNLTK's implementation of this algorithm is used~\\cite{nltkDocs}.\nThis implementation assumes the distribution of each feature $P(feature_i|label)$ to be multinomial,\nmaking it a multinomial naive Bayes, which has shown the best performance in previous work~\\cite{Go2009}.\nThe data from the Sanders dataset created in~\\cref{sec:theSandersDataset} was shuffled and split into 10\\% test data and 90\\% training data,\nwhich still gives accurate test results without removing too much from the little available training data.\nThis classifier achieved an accuracy of 75\\%.\nIn addition to accuracy, the performance measures precision, recall and F-measure, were computed for this classifier.\nLet $p_t$ be the number of statuses from a class that were actually labeled as being in that class,\nand $p_f$ be the number of statuses from other classes that were falsely labeled as being in that class.\nSimilarly, let $n_t$ be the number of statuses that were correctly labeled as $not$ being in that class,\nand $n_f$ be the number of statuses were labeled as not being in that class although they are.\nThe definitions for precision, recall and F-measure are then defined as follows:\n\n\\begin{equation}\n    Precision = \\frac{p_t}{p_t + p_f}\n\\end{equation}\n\\begin{equation}\n    Recall = \\frac{p_t}{p_t + n_f}\n\\end{equation}\n\\begin{equation}\n    F-Measure = \\frac{2 \\times Precision \\times Recall}{Precision + Recall}\n\\end{equation}\n\nIntuitively, precision and recall can be understood as the percentage of positives that are real positives,\nand the percentage of real positives that were labeled as positives, respectively.\nThe F-measure is their harmonic mean.\nThese measures, for each sentiment-class, can be seen in~\\cref{tab:mnb_results}.\nClass distribution and absolute counts for each class can be seen in~\\cref{tab:naive_bayes_results}.\n\n\\begin{table}\n    \\centering\n    \\fontsize{8.5}{9}\\selectfont\n    \\caption{Sentiment classification results using multinomial naive Bayes}\n    \\label{fig:sentiment_results}\n    \\begin{subtable}{.48\\textwidth}\n        \\caption{Absolute counts and percentages}\n        \\label{tab:naive_bayes_results}\n        \\centering\n        \\begin{tabular}{lllll} %\n            \\toprule\n            & \\multicolumn{2}{c}{Test Data} & \\multicolumn{2}{c}{Classification Result}\\\\\n            \\cmidrule{2-3}\n            \\cmidrule{4-5}\n            Sentiment\n            & Count\n            & Percentage\n            & Count\n            & Percentage\n            \\\\\\midrule\n            neutral & 206 & 47\\%  & 266 & 61\\%\n            \\\\\\midrule\n            irrelevant & 146 & 33\\%  & 124 & 28\\%\n            \\\\\\midrule\n            negative & 42 & 9\\%   & 30 & 6\\%\n            \\\\\\midrule\n            positive & 41 & 9\\%   & 15 & 3\\%\n            \\\\\\bottomrule\n        \\end{tabular}\n    \\end{subtable}%\n    \\hfill\n    \\begin{subtable}{.48\\textwidth}\n        \\caption{F-measure, precision and recall}\n        \\label{tab:mnb_results}\n        \\centering\n        \\begin{tabular}{llll} %\n            \\toprule\n            & \\multicolumn{3}{c}{Measure}\\\\\n            \\cmidrule{2-4}\n            Sentiment\n            & F-measure\n            & Precision\n            & Recall\n            \\\\\\midrule\n            neutral & 0.769 & 0.747 & 0.792\n            \\\\\\midrule\n            irrelevant & 0.896 & 0.902 & 0.890\n            \\\\\\midrule\n            negative & 0.504 & 0.464 & 0.553\n            \\\\\\midrule\n            positive & 0.318 & 0.440 & 0.250\n            \\\\\\bottomrule\n        \\end{tabular}\n    \\end{subtable}\n\\end{table}\n\nWhen the dictionary created from the sample stream was used to extract the features as shown in~\\cref{code:extract_features},\nthe accuracy dropped to 62\\%, indicating that the Sanders dataset, and the dictionary created from it, is highly topical.\nHowever, the dictionary created from the Sanders dataset will be used in this thesis.\n\n\\subsection{NLTK Sentiment Analyzer}\n\\label{subsec:nltksentimentanalyzer}\n\nThe NLTK sentiment analyzer package provides a framework for building classification-pipelines with easily interchangeable components\n(like choosing which methods to use for training, or which feature extractors to use).\nIt also builds its own dictionary, which means the dictionary created in~\\cref{sec:preprocessingAndTokenization} doesn't need to be used.\n\nFirst, the previous approach was reconstructed in this framework, and successfully validated to give the same accuracy.\nThen, it was expanded by marking all negated words as negated using the \\texttt{mark\\_negation} utility function of the NLTK.\nThey were then added to the dictionary in their negated form.\n\\\\\nThis yielded no performance increase: again, an accuracy of 75\\% was achieved.\n\\\\\nInspection revealed that only 22 words were added to the dictionary in negated form.\nSince the tokenization function described in~\\cref{sec:preprocessingAndTokenization} filters tokens of length shorter then 3,\nthereby also filtering, for example, the word \"no\", another test was conducted with a modified tokenization function that doesn't filter out short words.\n\\\\\nThis also yielded no performance increase.\n\\\\\nOnly two more distinct words were found in their negated form and added to the dictionary,\nincreasing the dictionary size of the modified tokenization function by 24, from 4132 to 4156.\n\\\\\nWhile recognizing contextual polarity has shown improvements in accuracy in a more general case~\\cite{Hoffmann2005},\nthese results indicate that marking negated words does not have the same positive effect on the special case presented by Twitter statuses.\n\n\\subsection{VADER}\n\\label{subsec:vader}\n\nVADER (\\textbf{V}alence \\textbf{A}ware \\textbf{D}ictionary for s\\textbf{E}ntiment \\textbf{R}easoning)\nis a gold standard of lexical features together with five general rules embodying grammatical and syntactical conventions\nthat were devised in a human-centered approach.\nIt is specifically designed for micro-blog-like environments such as Twitter~\\cite{Hutto2014}.\n\nNLTK's implementation of VADER returns scores between 0 and 1 for positivity, negativity and neutrality,\nas well as a compound score between -1 and 1, where the direction represents polarity and the magnitude represents subjectivity.\nA test was conducted involving only the statuses labeled \"positive\", \"negative\" or \"neutral\",\nto avoid the ambiguity of the \"irrelevant\"-label.\nThe optimal threshold for which a status will be classified as neutral was found\nat an absolute value for the compound score of 0.8, giving an accuracy of 68\\%.\n\n\\begin{equation}\n    class(x) =\n    \\begin{cases}\n        neutral & \\text{for } |compound\\_sentiment(x)| < 0.8 \\\\\n        positive & \\text{for } compound\\_sentiment(x) \\geq 0.8 \\\\\n        negative & \\text{for } compound\\_sentiment(x) \\leq -0.8 \\\\\n    \\end{cases}\n\\end{equation}\n\nStill, this accuracy remained below that of the naive Bayes approach at 74\\% when using the same filtered subset of statuses.\nDetailed results can be seem in~\\cref{tab:vader_results}.\n\n\\begin{table}[t]\n    \\begin{minipage}[t]{.4\\textwidth }\n        \\caption{F-measure, precision and recall of VADER}\n        \\label{tab:vader_results}\n        \\vspace{1.5mm} % Lining up the tables to make it bit prettier\n        \\resizebox{\\textwidth}{!}{%\n        \\begin{tabular}{llll} %\n            \\toprule\n            Sentiment\n            & F-measure\n            & Precision\n            & Recall\n            \\\\\\midrule\n            neutral & 0.806 & 0.689 & 0.971\n            \\\\\\midrule\n            negative & 0.098 & 0.742 & 0.052\n            \\\\\\midrule\n            positive & 0.171 & 0.448 & 0.105\n            \\\\\\bottomrule\n        \\end{tabular}}\n    \\end{minipage}%\n    \\hfill\n    \\begin{minipage}[t]{.55\\textwidth}\n        \\captionof{figure}{NLTK's VADER demonstration}\n        \\label{code:vader_demo}\n        % @formatter:off\n        \\begin{minted}{python}\n            import nltk.sentiment.util\n            nltk.sentiment.util.demo_vader_tweets()\n\n            Loaded 1 tweets\n            (...)\n            Loaded 5000 tweets\n\n            Accuracy: 0.861\n            F-measure [neg]: 0.8524416135881105\n            F-measure [pos]: 0.8686200378071833\n            Precision [neg]: 0.9083710407239819\n            Precision [pos]: 0.8234767025089605\n            Recall [neg]: 0.803\n            Recall [pos]: 0.919\n        \\end{minted}\n        % @formatter:on\n    \\end{minipage}\n\\end{table}\n\nThe NLTK also provides a function that demonstrates the use of VADER on the dataset provided by the NLTK.\nInterestingly, as seen in~\\cref{code:vader_demo}, the performance on that dataset is better than on the Sanders-dataset.\nHowever, as described in~\\cref{sec:theSandersDataset}, it is not known how the sample dataset in the NLTK was collected and labeled,\nwhich is why these results are disregarded.\n\n\\subsection{TextBlob}\n\\label{subsec:textblob}\n\nTextBlob is a simple text-processing library written in Python.\nIt provides similar functionality than the NLTK described in~\\cref{subsec:nltk},\nbut is simpler and less extensive.\nAmong other, it offers sentiment analysis~\\cite{textblobDocs}.\nTextBlob returns a polarity score between -1 and 1 as well as a subjectivity score between 0 and 1.\nAs in the previous subsection, the Sanders dataset is used for evaluation, disregarding statuses labeled as irrelevant.\nA scatter plot of the polarity and subjectivity score on the axes and label represented as the color can be seen in~\\cref{fig:textblob}.\nThe plot clearly shows the algorithms incapability of distinguishing subjective from neutral statuses,\nwhich is why a quantitative accuracy test was conducted using only tweets labeled as negative or positive.\n\n\\begin{equation}\n    class(x) =\n    \\begin{cases}\n        positive & \\text{for } compound\\_sentiment(x) \\geq 0 \\\\\n        negative & \\text{for } compound\\_sentiment(x) < 0\\\\\n    \\end{cases}\n\\end{equation}\n\nThe TextBlob's sentiment analysis algorithm achieved an accuracy of 64\\% on this filtered dataset,\nwhereas the current front-runner, the multinomial naive bayes approach,\nachieved an accuracy of 72\\% on the same filtered subset of statuses.\n\n\\subsection{Google Cloud Platform}\n\\label{subsec:googlecloud}\n\nThe natural language API by the Google Cloud Platform offers sentiment analysis as a service.\nFor any document, provided in a supported language, the API returns a magnitude starting from 0, with an undocumented upper bound\n(although the highest observed was 4.1) and a score between -1 and 1.\nMagnitude and subjectivity as well as score and polarity are similarly described in the their respective documentations~\\cite{gcloudDocs}\\cite{textblobDocs},\nwhich is why they are assumed have the same meaning.\n\nThe API is billed on a per-request basis, so all statuses from the Sanders dataset were classified once and persisted in a CSV-file.\nAgain, statuses labeled as irrelevant were filtered out to avoid ambiguity.\nA scatter plot of the score and magnitude on the axes and label represented as the color can be seen in~\\cref{fig:gcloud}.\n\n\\begin{figure}\n    \\centering\n    \\caption{Sentiment classification results on a scatter plot}\n    \\label{fig:sentiment_results_scatter}\n    \\begin{subfigure}{.5\\textwidth}\n        \\centering\n        \\caption{TextBlob}\n        \\label{fig:textblob}\n        \\includegraphics[width=\\textwidth]{../figures/textblob.pdf}\n    \\end{subfigure}%\n    \\begin{subfigure}{.5\\textwidth}\n        \\centering\n        \\caption{Google Cloud natural language API}\n        \\label{fig:gcloud}\n        \\includegraphics[width=\\textwidth]{../figures/gcloud.pdf}\n    \\end{subfigure}\n\\end{figure}\n\nAs for the VADER-classifier in~\\cref{subsec:vader}, these values are mapped to the labels from the dataset by\nchoosing an optimal threshold for which a status will be classified as neutral.\nStatuses labeled as irrelevant were, again, discarded.\nThe optimal magnitude-threshold was found at a magnitude of 0.9, giving an accuracy of 49\\%,\nwhich is just marginally better than guessing neutral, with 47\\% of statuses being labeled neutral.\n\n\\begin{equation}\n    class(x) =\n    \\begin{cases}\n        neutral & \\text{for } |compound\\_sentiment(x)| < 0.9 \\\\\n        positive & \\text{for } compound\\_sentiment(x) \\geq 0.9 \\\\\n        negative & \\text{for } compound\\_sentiment(x) \\leq -0.9 \\\\\n    \\end{cases}\n\\end{equation}\n\n\\section{Comparison and Conclusion}\n\\label{sec:comparison}\n\nWhen comparing the results of the different methods presented, it is surprising to see the simplest,\na multinomial naive Bayes, turned out to be the most accurate.\nThe summarized accuracy results can be seen in~\\cref{tab:sa_results}.\n\n\nThis indicates that short text statuses on micro-blogs like Twitter present a special challenge to sentiment analysis\nthat cannot be solved with current approaches.\nAdditions to existing algorithms, like marking negated words, that showed improved results with regular texts,\nshowed no improvement to the multinomial naive Bayes classifier when working with Twitter statuses.\nFurthermore, even methods specifically designed for this special challenge, like VADER,\nwere outperformed by a multinomial naive Bayes classifier.\n\nHowever, the results of these tests need to be handled carefully.\nAs explained in~\\cref{sec:theSandersDataset},\nand also indicated by the performance discrepancies between different dictionaries in~\\cref{subsec:naivebayes},\nthe dataset used is highly topical.\n\nThe sample stream dataset introduced in~\\cref{sec:streamingSampleDataset} was then classified using the multinomial naive bayes classifier from~\\cref{subsec:naivebayes}.\nWhen comparing the sentiment distribution of this dataset, seen in~\\cref{fig:sample_sentiment},\nto that of the Sanders dataset, seen in~\\cref{fig:sanders_sentiment},\none can see that it seems to be more opinionated,\ncontaining fewer statuses labeled as \"irrelevant\" in favor of positive and negative tweets.\n\nThis indicates that the dataset is not only highly topical, but also not perfectly representative in terms of sentiment.\nStill, the multinomial naive Bayes classifier was saved and will be used in the upcoming chapters.\n\n\\begin{table}[t]\n    \\begin{minipage}[t]{.5\\textwidth }\n        \\captionof{table}{Sentiment classification accuracy comparison}\n        \\label{tab:sa_results}\n        \\centering\n        \\resizebox{\\textwidth}{!}{%\n        \\begin{tabular}{lll} %\n            \\toprule\n            Method\n            & Statuses used\n            & Accuracy\n            \\\\\\midrule\n            & \\textit{all} & 75\\%\n            \\\\\\cmidrule{2-3}\n            Naive Bayes & positive, negative, neutral & 74\\%\n            \\\\\\cmidrule{2-3}\n            & positive, negative & 72\\%\n            \\\\\\midrule\n            NLTK Sentiment Analyzer & \\textit{all} & 75\\%\n            \\\\\\midrule\n            VADER & positive, negative, neutral & 68\\%\n            \\\\\\midrule\n            TextBlob & positive, negative & 64\\%\n            \\\\\\midrule\n            Google Cloud Platform & positive, negative, neutral & 49\\%\n            \\\\\\bottomrule\n        \\end{tabular}}\n    \\end{minipage}%\n    \\hfill\n    \\begin{minipage}[t]{.46\\textwidth}\n        \\centering\n        \\captionof{figure}{Sample stream dataset label distribution}\n        \\label{fig:sample_sentiment}\n        \\includegraphics[width=\\textwidth]{../figures/sample_sentiment.pdf}\n    \\end{minipage}\n\\end{table}", "meta": {"hexsha": "4b4f3a00b00d9e8dd4109cfb6f7631641d0b03b5", "size": 18047, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "reports/thesis/chapters/07_SentimentAnalysis.tex", "max_stars_repo_name": "ClaasM/streamed-sentiment-topic-intent", "max_stars_repo_head_hexsha": "76f6e8686ab629391fd714228547ed1de097466c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "reports/thesis/chapters/07_SentimentAnalysis.tex", "max_issues_repo_name": "ClaasM/streamed-sentiment-topic-intent", "max_issues_repo_head_hexsha": "76f6e8686ab629391fd714228547ed1de097466c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-03-24T15:33:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T23:16:16.000Z", "max_forks_repo_path": "reports/thesis/chapters/07_SentimentAnalysis.tex", "max_forks_repo_name": "ClaasM/streamed-sentiment-topic-intent", "max_forks_repo_head_hexsha": "76f6e8686ab629391fd714228547ed1de097466c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.5128865979, "max_line_length": 169, "alphanum_fraction": 0.715575996, "num_tokens": 4451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011686727232, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.32442131704285426}}
{"text": "\\section{Muth--Lucas--Pischke and \\cite{reis:inattentive}} \\label{sec:Comparisons}\n\nNow that our calibrations and results have been presented, we are in position to make some quantitative comparisons of our model to two principal alternatives to habit formation (or our model) for explaining excess smoothness in consumption growth, by Pischke and by Reis.\n\n\\subsection{Muth--Lucas--Pischke}\nThe longest-standing rival to habit formation as an explanation of consumption sluggishness is what we will call the Muth--Lucas--Pischke (henceforth, MLP) framework.  The idea is not that agents are inattentive, but instead that they have imperfect information on which they perform an optimal signal extraction problem.\n\n\\cite{muthOptimal}'s agents could observe only the level of their income, but not the split between its permanent and transitory components.  He derived the optimal (mean-squared-error-minimizing) method for estimating the level of permanent income from the observed signal about the level of actual income.  \\cite{lucas:imperfectInfo} applied the same mathematical toolkit to solve a model in which firms are assumed to be unable to distinguish idiosyncratic from aggregate shocks.  \\cite{pischkeMicroMacro} combines the ideas of Muth and Lucas and applies the result to micro consumption data: His consumers have no ability at all to perceive whether income shocks that hit them are aggregate or idiosyncratic, transitory or permanent.  They see only their income, and perform signal extraction on it.\n\nPischke calibrates his model with micro data in which he calculates that transitory shocks vastly outweigh permanent shocks.\\footnote{Pischke's estimates constructed from the {\\it Survey of Income and Program Participation} are rather different from the magnitudes of transitory and permanent shocks estimated in the extensive literature---mostly subsequent to Pischke's paper---cited in our calibration section above.}  So, when a shock arrives, consumers always interpret it as being almost entirely transitory and change their consumption by little.  However, macroeconometricians have long known that {\\it aggregate} income shocks are close to permanent.  When an aggregate permanent shock comes along, Pischkian consumers spend very little of it, confounding the aggregate permanent shock's effect on their income with the mainly transitory idiosyncratic shocks that account for most of the total variation in their income.  This misperception causes sluggishness in {\\it aggregate} consumption dynamics in response to aggregate shocks.\n\nIn its assumption that consumers fail to perceive aggregate shocks immediately and fully, Pischke's model resembles ours.  However, few papers in the subsequent literature have followed Pischke in making the assumption that households have no idea, when an idiosyncratic income shock occurs, whether it is transitory or permanent.  Especially in the last decade or so, the literature instead has almost always assumed that consumers can perfectly perceive the transitory and permanent components of their income; \\hyperlink{Why-Consumers-See-Individual-Shocks}{see our defense of this assumption above}.\n\nGranting our choice to assume that consumers correctly perceive the events that are idiosyncratic to them (job changes, lottery winnings, etc), there is still a potential role for application of the MLP framework:  Instead of assuming sticky expectations, we could instead have assumed that consumers perform a signal extraction exercise on \\textit{only} the aggregate component of their income, because they cannot perceive the transitory/permanent split for the (tiny) part of their income change that reflects aggregate macroeconomic developments.\n\nIn principle, such confusion could generate excess smoothness; for a detailed description of the mechanism, \\hyperlink{MuthLucasPischke}{see} online Appendix~\\ref{appendix:Muth}.  But, defining the signal-to-noise ratio $\\varphi=\\sigma^2_{\\Psi}/\\sigma^2_{\\Theta}$, Muth's derivations imply that the optimal updating coefficient is:\n \\input{/Volumes/Data/Papers/cAndCwithStickyE/cAndCwithStickyE-AEJM/Equations/muthOptimal.tex}\n\\newcommand{\\PischkePi}{0.83}\n\\newcommand{\\PischkePiCancel}{0.17}\n \\newcommand{\\fromFile}{false}\n \\newcommand{\\FileOrNot}{\\ifthenelse{\\boolean{\\fromFile}}}\nPlugging our calibrations of $\\sigma^2_{\\Psi}$ and $\\sigma^2_{\\Theta}$ from section \\ref{sec:calibration} into \\eqref{eq:muthOptimal}, the model yields a predicted value of \\FileOrNot{$1-\\Pi \\approx \\PischkePiCancel$}{$(1-\\Pi) \\approx \\PischkePiCancel $}---very far below the approximately $0.6$ estimate from \\cite{hrsHabit} and even farther below our estimate of roughly $0.7$--$0.8$ for U.S.\\ data.  This reflects the well-known fact that aggregate income is hard to distinguish from a random walk; if it were perceived to be a perfect random walk with no transitory component at all, the serial correlation in its growth would be zero.  So, in practice, allowing signal extraction with respect to the aggregate data is not a path to explaining excess smoothness.\n\n\\subsection{\\cite{reis:inattentive}}\n\nLeaving aside our earlier criticisms of its fidelity to microeconomic evidence, the model of \\cite{reis:inattentive} has a further disadvantage relative to any of the other three stories (habits, MLP, or our model) with respect to aggregate dynamics. In Reis's model consumers update their information on a regular schedule---under a plausible calibration of the model, once a year. One implication of the model is that the change in consumption at the next reset is unpredictable; this implies that aggregate consumption growth would be unpredictable at any horizon beyond, say, a year.\\footnote{In contrast, our model exhibits significant predictability beyond one year. The value of $\\chi$ in the `horse-race' regression for the SOE economy is 0.66 when the right hand side is lagged by one quarter (see Table~\\ref{tPESOEsim}). Adding an extra one and two years' lag to the right hand side sees $\\chi$ decline approximately as an AR(1), to 0.20 and 0.06 respectively.}  But, macroeconomists felt compelled to incorporate sluggishness into macroeconomic models in large part to explain the fact that consumption growth is forecastable over extended periods---empirical impulse response functions indicate that a macroeconomically substantial component of the adjustment to shocks takes place well beyond the one year horizon.  A calibration of the Reis model in which consumers update once a year therefore fails to solve a large part of the original problem (of medium-term predictability).\n\n", "meta": {"hexsha": "f7ee3d0e2c1f22d90b09c1a261a154e45a30dede", "size": 6604, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Highlighted/MuthLucasPischke.tex", "max_stars_repo_name": "llorracc/cAndCwithStickyE-AEJM", "max_stars_repo_head_hexsha": "c053da06e88dd8c36319ac5976efa89d5d69c8f5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Highlighted/MuthLucasPischke.tex", "max_issues_repo_name": "llorracc/cAndCwithStickyE-AEJM", "max_issues_repo_head_hexsha": "c053da06e88dd8c36319ac5976efa89d5d69c8f5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Highlighted/MuthLucasPischke.tex", "max_forks_repo_name": "llorracc/cAndCwithStickyE-AEJM", "max_forks_repo_head_hexsha": "c053da06e88dd8c36319ac5976efa89d5d69c8f5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-08-05T07:51:31.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-05T07:51:31.000Z", "avg_line_length": 235.8571428571, "max_line_length": 1493, "alphanum_fraction": 0.8099636584, "num_tokens": 1473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.32442130901994826}}
{"text": "\\section{Implementation}\nOur implementation was done in Matlab code. The structure of the Warm Chorus algorithm is quite modular; figure~\\ref{fig:struct}, which details the structure of the algortihm, shows that there are at least six distinct processing blocks.\n\\begin{figure}[ht]\n\\centering\n\\includegraphics[width= 9cm]{Structure.png}\n\\caption{Block diagram of the warm chorus algorithm. \\cite{dudas}}\n\\label{fig:struct}\n\\end{figure}\n\nThe flow of the algorithm begins with a multi-tap delay line, which divides the input signal into eight differently delayed paths. The first path is not delayed, as it corresponds to the lead player in the orchestra section. There is also an uneffected path on the left side of the structure, which is only used in the frequency domain processing for some minor corrections.\n\nThese eight paths then process the signal with harmonising structures, filters and other common digital signal processing tools. The most important processing block is the harmoniser, which will be explained separately, followed by brief explanations of the other processing blocks. \n", "meta": {"hexsha": "87de7250a8afc85bcb131a32264505f5703cd56b", "size": 1097, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/implementation.tex", "max_stars_repo_name": "Gastron/WarmChorus", "max_stars_repo_head_hexsha": "cfa716c633150949fa115a15d7e29fdf1fbd06e1", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-21T17:07:29.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-21T17:07:29.000Z", "max_issues_repo_path": "report/implementation.tex", "max_issues_repo_name": "Gastron/WarmChorus", "max_issues_repo_head_hexsha": "cfa716c633150949fa115a15d7e29fdf1fbd06e1", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/implementation.tex", "max_forks_repo_name": "Gastron/WarmChorus", "max_forks_repo_head_hexsha": "cfa716c633150949fa115a15d7e29fdf1fbd06e1", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 84.3846153846, "max_line_length": 374, "alphanum_fraction": 0.8094804011, "num_tokens": 231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.32434608626452854}}
{"text": "\\title{(An introduction to )MultiSymplectic Geometry and Classical Field systems}\n\\author{\n\tInternational Ph.D. Program in \"Science\" \\\\\n\t\"Differential geometry and applications to modern physics\" \\\\\n\t%\n\t\\begin{minipage}[c]{0.5\\textwidth}\n\t\t\\vspace{2em}\n\t\t\\centering\n\t\tDepartment of Mathematics and Physics\\\\\n\t\tUniversit\\'a Cattolica del Sacro Cuore\\\\\n\t\tvia Musei 41, 25121 Brescia, \\underline{Italy}\n\t\\end{minipage}\n\t\\hfill\n\t\\begin{minipage}[c]{0.5\\textwidth}\n\t\t\\vspace{2em}\n\t\t\\centering\n\t\tDepartment of Mathematics\\\\\n\t\tKU Leuven\\\\\n\t\tCelestijnenlaan 200B, 3001 Leuven, \\underline{Belgium}\n\t\\end{minipage}\n}\n\n\\documentclass[a4paper,12pt,fleqn]{article}  %Per La Stampa\n\\usepackage[a4paper, margin=3cm]{geometry}\n\n\\usepackage{amsmath}\n\\usepackage{amsfonts}\n%\\usepackage[multisym, geomec, basic, diffgeo]{./Math-Symbols-List/toninus-math-symbols}\n\\usepackage[subpreambles=true]{standalone}\n\\usepackage{commath}\n\n\\usepackage[italian,english]{babel}\n\\usepackage[utf8]{inputenc}\n\n\\usepackage{graphicx}\n\\usepackage{hyperref}\n\\usepackage{tabularx}\n\n\\usepackage{Latex-Theorem/theoremtemplate}\n\n\\providecommand{\\oast}{\\ensuremath{\\:\\!%\n {\\raisebox{0.1ex}{$\\scriptscriptstyle \\bigcirc$} \\hspace{-0.5em} \\ast}}}\n\\providecommand{\\ostar}{\\ensuremath{\\:\\!%\n {\\raisebox{0.05ex}{$\\scriptscriptstyle \\bigcirc$} \\hspace{-0.5em} \\star}}}\n\\providecommand{\\smoast}{\\ensuremath{%\n {\\raisebox{-0.25ex}{$\\textstyle \\circ$} \\hspace{-0.42em}\n {\\scriptscriptstyle \\ast}}}}\n\\providecommand{\\smostar}{\\ensuremath{%\n {\\raisebox{-0.25ex}{$\\textstyle \\circ$} \\hspace{-0.42em}\n  \\raisebox{0.05ex}{$\\scriptscriptstyle \\star$}}}}\n\n\\begin{document}\n\\maketitle\n\n$$\n\\ast \n\\star \n\\oast \n\\ostar\n\\smoast\n\\smostar\nJ^\\smostar\nJ^\\smoast\n%J^\\ostar\n$$\n\n\n\\begin{abstract}\n$n$-plectic structures (also called \\emph{multisymplectic}) are a rather straightforward generalization of symplectic ones where closed non-degenerate $n+1$-forms take the place of  $2$-forms.\n\\\\\nJust as one can associate a symplectic manifold to an ordinary classical mechanical system (e.g. a single point-like particle constrained to some manifold), it is possible to associate a multisymplectic manifold to any classical field systems (e.g. a continuous medium like a filament or a membrane).\n\\\\\nThe aim of this talk is to give an account on the multisymplectic framework for (I-order) classical fields theories trying to comparing it with another object that plays a significant role in the mathematical description of classical fields called \\emph{Covariant phase space}.\n\\\\\nBeing the latter a sort of \"$\\infty$-dimensional manifold\" (namely a mapping space), we will draw from this picture the idea that multisymplectic geometry could be seen as a tool that allows us to treat such formal object in a finite-dimensional setting.\n\n\n\\end{abstract}\n\n\n\\section{Preliminiaries}\n\n%What's geometric Mechanics\n\\subsection{A glance at the geometric approach to classical mechanics}\nThe context in which we are going to work is \\emph{Geometric Mechanics}.\n\\\\\nRoughly speaking, geometric mechanics is a branch of (applied) mathematics that employs differential geometry to the description of physical systems. Unlike analytical mechanics, the focus is on encoding the mechanical properties of a physical system regardless of the reference frame (coordinate system).\n\\\\\nLet us briefly recall what are the most important ingredients of an ordinary classical\\footnote{Here \"ordinary\" stands for finite degrees of freedom and \"classical\" stands for non-quantum and non-relativistic.} system.\n\n\\begin{center}\n  %\\includestandalone{Pictures/Figure_ordinary_landscape}\n\\end{center}\n\n\\begin{itemize}\n\t\\item The starting point is the \\emph{Configuration space}, that is a smooth manifolds $Q$ containing all possible spatial displacements of a system.\\\\\n\tE.g. for the simple planar pendulum $Q= S^1$, for a double pendulum $Q =\\mathbb{T}^2$\n\t\\item A point in $Q$ is a statical configuration, that is opposed to the elements of the \\emph{space of kinematics configuration}\n\t$$ \\mathcal{C} = C^\\infty(\\mathbb{R},Q)$$\n\twhich is the collection of all trajectories admitted by the constraints.\n\t\\item The tangent bundle $TQ$ takes the name of \\emph{space of generalized velocities}\n\t\\item The cotangent bundle $T^\\ast Q$ is called \\emph{phase space}. Such space carries a natural symplectic form $\\omega$ (\\emph{Poincare\\'} 2-form) defined in term of the tautological 1-form $$\\omega= \\text{d} \\theta$$\n\\end{itemize}\n%\nAll of this encode the geometry of the kinematics. Fixing a point in the previous two spaces is tantamount to give a complete set of initial data determining unambiguously the evolution of the system. \n\\\\\nSuch point carries more information that the simple spatial displacement and are interpreted as the \\emph{physical state} of the system.\n%\n\\begin{itemize}\n\\item Dynamics is encoded by two smooth functions:\n\t\\\\ \n\t$L:TQ\\rightarrow \\mathbb{R}$ in the \\emph{Lagrangian} framework\n\t\\\\\n\t$H:T^\\ast Q \\rightarrow \\mathbb{R}$ in the \\emph{Hamiltonian} framework\n\t\\\\\n\tGenerally the two framework are not equivalent.\n\\item From the Lagrangian $L$ or the Hamiltonian $H$ one can obtain the so-called \\emph{Action functional} $S:\\mathcal{C}\\rightarrow \\mathbb{R}$ which yields the equation of motion through the d'Alambert principle.\n\\end{itemize}\n%\nThe goal of this talk is to describe the analogue of this framework in the case of classical field systems.\n\n%What's a Classical Field\n\\subsection{Modelling a classical field theory}\nA classical field theory is a physical theory that predicts how \"physical fields\" evolves according to their interaction with the matter and themselves.\n\\\\\nThe term \"classical\" is commonly reserved to theories treating electro-magnetism and gravitation. Here it is meant as non-quantum mechanics of physical fields or continuous systems.\n\nRoughly, a physical field can be thought as the assignment of a physical quantity at each point of space and time.\n\n\nClassicamente: DOF come numero di misure necessarie per fissare univocamente una configurazione.\n\n\\begin{tabularx}{\\textwidth}{c X c c}\n\tSystem & Prototype & DoF & Configuration space (locally)\\\\\n\tOrdinary classical mech system & point-particle on a  $q$-dim manifold &\n\t$q$ finite (discrete) & $\\mathbb{R}^n = Hom_{set}(\\{1,\\ldots n\\}, \\mathbb{R})$ \\\\\n\t1-dim. field & collection of points on a line each one parametrized by a point on the manifold $Q$ & $q$ for each point on the continuous line (infinite and continuous) &\n\t...\n%\t\\\\\n%\tn dimensional field & $(\\mathbb{R}^m)^{\\mathbb{R}^n} = C^\\infty (\\mathbb{R}^n, \\mathbb{R}^m)$ & ...\n\\end{tabularx}\n\n\nA questo punto si dovrebbe Essere chiaro il punto di partenza:\n\\\\\n\n\\subsection{Multisymplectic geometry}\n\n\n\\section{Multymplectic approach to classical field theories}\nTabella -Dictionary\n\n\n\\subsection{From the configuration Space to the configuration Bundle}\nRecall that a physical field has to be thought as the assignment of a quantity to every point of a base manifold (a \"spacetime\" most of the time).\n\\\\\nIt is reasonable that the object needed to encode the kinematics of our field system ougth to be a smooth bundle, that would be the proper language in order to formulate the notion of smooth physical quantity.\n\\\\\n\\begin{definition}[Configuration bundle] \n \t\\begin{displaymath}\n \t\tE = \\left( \\pi_{M,E} : E\\rightarrow M \\right)\n \t\\end{displaymath}\nSmooth fiber bundle $E\\sim(x^\\mu,q^A)$ with typical fiber $Q\\sim(q^A)$ over a smooth, oriented and connected base manifold $M\\sim(x^\\mu)$.\n\\end{definition}\nThis definition may seem a bit too bare, but has to be kept in mind that we are describing a structure suitable for many different models.\n\\\\\nThe collection $\\Gamma(E)$ of all smooth sections has to be understood as the set of kinematics configurations of the system and the typical fiber $Q$ can be tought as the configuration space of possible values of the field in a fixed point.\n\n\\subsection{From the space of generalized velocities to the I Jet bundle}\nThe collection of all field configurations together with their partial derivatives up to $r$-th order can be represented by the space of the sections of the $r$-th jet bundle.\n\\\\\nIn what follows we shall only need the first order Jet bundle. This restriction reflect the fact that almost all known examples of field theories are governed by second order PDE and derived from Lagrangian depending only on first order partial derivative.\nAlso, it is also reasonable to develop the theory starting from this point directly extending the ordinary geometric mechanics theory.\n\n\\begin{definition}[I Jet bundle]\nAffine bundle $J^1 E \\rightarrow E$, with fibers over a point $y\\in E$ given by\n\\begin{displaymath}\n\t\\left( J^1 E\\right)_y = \\left\\lbrace \\gamma \\in \\text{L}(T_{\\pi(y)}M, T_y E) \\; \\vert \\: T\\pi \\circ \\gamma = \\text{id}_{T_{\\pi(x)} M} \\right\\rbrace\n\\end{displaymath}\nwhere $T$ is the tangent functor, $L$ is the space of linear maps and $\\pi$ is the bundle projection of $E$ over $M$.\n\\\\\nThis fiber is an affine subspace of $\\text{L}(T_{\\pi(y)}M, T_y E)$ modelled on the following (difference) vector space:\n\\begin{displaymath}\n\t\\vec{\\left( J^1 E\\right)_y} = \\left\\lbrace z \\in \\text{L}(T_{\\pi(y)}M, T_y E) \\; \\vert \\: T\\pi \\circ z = 0 \\right\\rbrace\n\t\\cong \\text{L}(T_{\\pi(y)}M, T_y E)\n\t\\cong T_x^\\ast M \\otimes V_y E\n\\end{displaymath}\n\\end{definition}\n\n\n\n\\subsection{Dualization of Jet bundles}\n\n\\subsection{Lagrangian Dynamics}\n\n\\subsection{Hamiltonian Dynamics}\n\n\\subsection{Legendre transformation}\n\n\\subsection{examples}\n\n\\section{Spunti}\n\n\\subsection{Link to the Covariant Approach}\n\n\\subsection{Open problems?}\n\\begin{itemize}\n\t\\item We have a momap on ms mfd and a momap on mapping space (as diffeological space) does the two match?\n\t\\item We have a canonical m-s structure on J.. and a canonical poisson structure con cov phase space (Peierls bracket) does the two match? \\\\\n\t\tYes! this is actually the result of \\cite{forgeromero}. At pages 396-397 they show how to transgress the multisymplectic form to a symplectic form on Sol.\\\\\n\t\tIn theorem 4 pag 403 they show that this form coincide with the one by Peierls constructed a' la Dewitt.\n\n\t\\item there are other notion of moment map on the multisymplectic setting. For instance how the definition in section 4 of \\cite{Gotay1998a} is related to the one in \\cite{Ryvkin2018}?\n\nMarco ha fatto un'osservazione interessante: la densità hamiltoniana come definita da Forger-Romero non sembra a priori collegata a nessun elemento delle \"L-infty algebra\" usata nei suoi lavori. Questo e' in contrasto con il parallelismo che si vorrebbe fare tra algebra di poisson per i sistemi tipo di particella e L-infity algebra per i sistemi tipo campo.\n\nAnche Forger e Romero indicano come che uno dei grandi difetti del formalismo multi-simplettico il fatto che non sia chiaro quale sia la corretta struttura algebrica degli osservabili. Questo problema non è di poco conto visto che la maggior parte degli schemi di quantizzazione partono dal quantizzare l'algebra degli osservabili.\n\nMarco ha parlato con Gotay: dice che la forma ms per i campi è molto particolare (esatta e definita su un particolare fibrato) e che lo studio della geo multisymp a livello molto generale potrebbe alla fine non essere centrale o utile per quanto riguarda la meccanica.\t\n\t\n\n\\end{itemize}\n\n\n%------------------------------------------------------------------------------------------------\n% Bibliography (BibTex)\n% https://arxiv.org/hypertex/bibstyles/\n%------------------------------------------------------------------------------------------------\n\t\t\t\\nocite{*}\n\t\t\t\\bibliographystyle{ieeetr}\n\t\t\t\\bibliography{biblio}\n%------------------------------------------------------------------------------------------------\n\n\n\n\n\\end{document}\n", "meta": {"hexsha": "2617c703bf0d25f380773a9a9eb3b5b17b22679a", "size": 11703, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ms-mechanics.tex", "max_stars_repo_name": "MasterToninus/multisymplectic", "max_stars_repo_head_hexsha": "14398a92b05678804b97111035f40a216529e5c6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ms-mechanics.tex", "max_issues_repo_name": "MasterToninus/multisymplectic", "max_issues_repo_head_hexsha": "14398a92b05678804b97111035f40a216529e5c6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ms-mechanics.tex", "max_forks_repo_name": "MasterToninus/multisymplectic", "max_forks_repo_head_hexsha": "14398a92b05678804b97111035f40a216529e5c6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.1722689076, "max_line_length": 359, "alphanum_fraction": 0.7434845766, "num_tokens": 3170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3243459969850503}}
{"text": "\\documentclass[review]{elsarticle}\n\n\\usepackage{amsmath}\n\\usepackage{booktabs}\n\\usepackage[makeroom]{cancel}\n\\usepackage[section]{placeins}\n\\usepackage{subcaption}\n\\usepackage{tabularx}\n\\usepackage{nicefrac}\n\\usepackage[usenames]{xcolor}\n\\usepackage{lineno,hyperref}\n\\modulolinenumbers[5]\n\n\\journal{Computer Methods in Applied Mechanics and Engineering}\n\n%%%%%%%%%%%%%%%%%%%%%%%\n%% Elsevier bibliography styles\n%%%%%%%%%%%%%%%%%%%%%%%\n%% To change the style, put a % in front of the second line of the current style and\n%% remove the % from the second line of the style you would like to use.\n%%%%%%%%%%%%%%%%%%%%%%%\n\n%% Numbered\n%\\bibliographystyle{model1-num-names}\n\n%% Numbered without titles\n%\\bibliographystyle{model1a-num-names}\n\n%% Harvard\n%\\bibliographystyle{model2-names.bst}\\biboptions{authoryear}\n\n%% Vancouver numbered\n%\\usepackage{numcompress}\\bibliographystyle{model3-num-names}\n\n%% Vancouver name/year\n%\\usepackage{numcompress}\\bibliographystyle{model4-names}\\biboptions{authoryear}\n\n%% APA style\n%\\bibliographystyle{model5-names}\\biboptions{authoryear}\n\n%% AMA style\n%\\usepackage{numcompress}\\bibliographystyle{model6-num-names}\n\n%% `Elsevier LaTeX' style\n\\bibliographystyle{elsarticle-num}\n%%%%%%%%%%%%%%%%%%%%%%%\n\n\\begin{document}\n\n\\begin{frontmatter}\n\n\\title{Curvilinear Finite Difference (C-FD) solution of the fiber/matrix interface problem}\n%\\tnotetext[mytitlenote]{Fully documented templates are available in the elsarticle package on \\href{http://www.ctan.org/tex-archive/macros/latex/contrib/elsarticle}{CTAN}.}\n\n%% Group authors per affiliation:\n%\\author{Luca Di Stasio\\fnref{myfootnote}}\n%\\address{Radarweg 29, Amsterdam}\n%\\fntext[myfootnote]{Since 1880.}\n\n%% or include affiliations in footnotes:\n\\author[lulea]{Luca Di Stasio}\n%\\author[lulea]{Janis Varna}\n%\\author[nancy]{Zoubir Ayadi}\n%\\ead[url]{www.elsevier.com}\n\n%\\author[mysecondaryaddress]{Global Customer Service\\corref{mycorrespondingauthor}}\n%\\cortext[mycorrespondingauthor]{Corresponding author}\n%\\ead{support@elsevier.com}\n\n\\address[lulea]{Lule\\aa\\ University of Technology, University Campus, SE-97187 Lule\\aa, Sweden}\n%\\address[nancy]{Universit\\'e de Lorraine, EEIGM, IJL, 6 Rue Bastien Lepage, F-54010 Nancy, France}\n\n\\begin{abstract}\n\\noindent\n\n\\end{abstract}\n\n\\begin{keyword}\nFiber/matrix interface crack\\sep Bi-material interface arc crack\\sep Linear Elastic Fracture Mechanics (LEFM)\\sep Virtual Crack Closure Technique (VCCT) \\sep Finite Difference (FD)\\sep Curvilinear coordinates\n\\end{keyword}\n\n\\end{frontmatter}\n\n\\linenumbers\n\n\\section{Introduction}\\label{sec:intro}\n\n\n\n\\section{Analytical formulation}\n\n\\begin{equation*}\n\\begin{aligned}\n&\\text{in }\\Omega_{f}, \\Omega_{m}:\\\\\n&\\frac{\\partial^{2}\\varepsilon_{xx}}{\\partial y^{2}}+\\frac{\\partial^{2}\\varepsilon_{yy}}{\\partial x^{2}}=\\frac{\\partial^{2}\\gamma_{xy}}{\\partial x\\partial y}\\\\\n&\\varepsilon_{z}=\\gamma_{zx}=\\gamma_{yz}=0\\\\\n&\\frac{\\partial\\sigma_{xx}}{\\partial x}+\\frac{\\partial\\tau_{xy}}{\\partial y} = 0\\\\\n&\\frac{\\partial\\tau_{xy}}{\\partial x}+\\frac{\\partial\\sigma_{yy}}{\\partial y} = 0\\\\\n&\\sigma_{zz}=\\nu\\left(\\sigma_{xx}+\\sigma_{yy}\\right)\\\\\n&\\text{for } 0^{\\circ}\\leq\\alpha\\leq\\Delta\\theta:\\\\\n&\\left(\\overrightarrow{u}_{m}\\left(R_{f},\\alpha\\right)-\\overrightarrow{u}_{f}\\left(R_{f},\\alpha\\right)\\right)\\cdot\\overrightarrow{n}_{\\alpha}\\geq 0\\\\\n&\\text{for } \\Delta\\theta\\leq\\alpha\\leq 180^{\\circ}:\\\\\n&\\overrightarrow{u}_{m}\\left(R_{f},\\alpha\\right)-\\overrightarrow{u}_{f}\\left(R_{f},\\alpha\\right)=0\\\\\n&\\sigma_{ij}=E_{ijkl}\\varepsilon_{kl}\\\\\n&+BC\n\\end{aligned}\n\\end{equation*}\n\n\\section{Curvilinear Finite Difference (C-FD) discretization}\n\n\\section{Conclusions \\& Outlook}\n\n\n\n\\FloatBarrier\n\n\\section*{Acknowledgements}\n\n\n\n\\bibliography{refs}\n\n\n\n\\end{document}\n", "meta": {"hexsha": "cdb9322b4435d1abab816d7201bba16b5bc57539", "size": 3718, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/04_Preprints/15_FD-interface-crack/FD-interface-crack.tex", "max_stars_repo_name": "LucaDiStasio/thinPlyMechanics", "max_stars_repo_head_hexsha": "813bdeef7e07db6b7830d41fcca198f8dd2eb3cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2018-06-04T10:15:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-04T03:53:54.000Z", "max_issues_repo_path": "tex/04_Preprints/15_FD-interface-crack/FD-interface-crack.tex", "max_issues_repo_name": "LucaDiStasio/thinPlyMechanics", "max_issues_repo_head_hexsha": "813bdeef7e07db6b7830d41fcca198f8dd2eb3cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 123, "max_issues_repo_issues_event_min_datetime": "2017-09-07T14:05:04.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-21T12:01:30.000Z", "max_forks_repo_path": "tex/04_Preprints/15_FD-interface-crack/FD-interface-crack.tex", "max_forks_repo_name": "LucaDiStasio/thinPlyMechanics", "max_forks_repo_head_hexsha": "813bdeef7e07db6b7830d41fcca198f8dd2eb3cf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-08-09T19:20:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T20:55:44.000Z", "avg_line_length": 29.5079365079, "max_line_length": 208, "alphanum_fraction": 0.7321140398, "num_tokens": 1151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.5273165233795672, "lm_q1q2_score": 0.32434598954372573}}
{"text": "% ==============================================================================\n%\n%                           V E R I F I C A T I O N\n%\n% ==============================================================================\n% ==============================================================================\n%\n%                               O V E R V I E W\n%\n% ==============================================================================\n\\chapter{Verification} % <<< ------------------------------------------------- %\n\\label{ch:verification}\n% ---------------------------------------------------------------------------- %\n\nDesigning filters  in Matlab  and running  FPGA simulations  in Vivado  is all\nnice  and well,  but  in the  end,  what  counts is  how  the system  performs\nin  practice. This chapter  outlines  which sorts  of  measurements have  been\nperformed, the rationale behind them, and summarizes the results.\n\nAll  the metrics  presented in  this  chapter are  based  on the  same set  of\nmeasurements, unless  otherwise mentioned. For  each filter  chain, \\num{2000}\nmeasurements have  been made, each  with a size  of \\num{8192} samples  in the\ntime domain at one frequency. Between each of the \\num{2000} runs for a single\nchain, the signal frequency increases equidistantly from \\num{0} to five times\nthe  filter's  outgoing  sampling frequency. Covering  \\num{2000}  frequencies\nallows to  cover the  passband ripple  and the  transition band  in sufficient\nresolution to detect possible issues.\n\nFor the  filter chains  with $R=5$  decimators at their  ends (the  chains for\ndecimation factors by \\num{5}, \\num{25},  \\num{125} and \\num{625}), this means\nthat the output filter's passband is first traversed, and then its stopband up\nuntil half its incoming sampling rate. This enables us to measure the passband\nand  stopband magnitude  response. Furthermore, by  performing an  FFT of  the\nfilter chain's output at specific frequencies,  we can verify how strongly the\nstopband aliases back into the passband. This is the problem illustrated in\nFigures~\\ref{fig:aliasing:iirCopies},\n\\ref{fig:cic:freq_responses:passband:aliasing},\nand~\\ref{fig:stl125:moving_averager}.\n\nFor the filter chains with half-band filters as their final stages (\\num{1250}\nand \\num{2500}),  this frequency range is  actually too large, since  we would\nonly need to measure up to twice  the outgoing sampling rate in order to cover\nthe final filter's  magnitude response range.  However, there is  no real harm\nin going higher (a bit of resolution is lost), and it simplifies the measuring\nprocess, so no particular distinction is made here.\n\nNote that it is generally not necessary to measure at even higher frequencies.\nAs can be seen in Section~\\ref{sec:multi_stage_filter_designs} and some of the\nfrequency responses  for the filter  cascades which  are being used  (e.g. the\nchain for  $R=25$, see page~\\pageref{sec:filter_frequency_responses:chain25}),\nit  is   the  final  filter  in   a  cascade  which  determines   the  chain's\noverall   behavior   in  the   relevant   frequency   regions  (assuming   the\nindividual   filters  in   the   chains  have   been   sensibly  designed   to\nmatch   each  other's   characteristics,   also  explained   in  the   section\n\\emph{\\nameref{sec:multi_stage_filter_designs}}).    Increasing    the   input\nfrequency  further simply  moves into  regions  which are  ever more  strongly\nattenuated,  so unless  serious issues  are encountered,  the higher  spectral\nranges are not of interest  in verifying the filter chain's functionality. The\nmeasurements for the  \\num{1250} and \\num{2500} chains, which  do indeed cover\nmore than the necessary frequency range, confirm this.\n\nAll   measurements   are   adjusted   to   have   the   right   scaling   with\nEquation~\\ref{eqn:verification:transform}  where $x_\\mathrm{unsigned}$  is the\nmeasured sample.\n\\begin{align}\n    \\label{eqn:verification:transform}\n    x_{i,\\mathrm{signed}} &= \\left(x_{i,\\mathrm{unsigned}} - 2^{15}\\right) \\cdot 2^{-15} \\\\\n    x_{i,\\mathrm{V}}      &= x_{i,\\mathrm{signed}} \\cdot \\SI{1.1}{\\V}\n\\end{align}\n\n% >>>\n% ==============================================================================\n%\n%                R M S   F R E Q U E N C Y   R E S P O N S E\n%\n% ==============================================================================\n\\section{RMS Frequency Response} % <<< --------------------------------------- %\n\\label{sec:verification:rms}\n% ---------------------------------------------------------------------------- %\n\nTo verify  that the  filters perform as  expected, the RMS  of all  samples is\ncalculated and  plotted against their  respective input frequency, as  seen in\nFigure~\\ref{fig:verification:rmsAll}.  The RMS looks  good and the passband is\npractically flat. Two things stand out as not too positive:\n\\begin{itemize}\\tightlist\n    \\item \n        The passband frequency  response has a slight slope  upwards. It is at\n        no  point  higher  than  \\SI{20}{\\mV},  effectively  having  an  error\n        below  \\SI{2}{\\percent}  in  all  of  the  filter  chains  except  the\n        $R=5$  chain.  \n        This is  mostly in  line with  the case in  the filter  performance as\n        predicted  by  Matlab; a  ripple  in  the cascade's  passband  between\n        \\SI{0.67}{\\percent} and \\SI{2.8}{\\percent} is predicted.\n        What is  peculiar is that  the overall  shape of the  passband doesn't\n        quite  align  with  Matlab's  designs. No  behavior  occurs  which  we\n        consider to be deal-breaking though.\n    \\item \n        The passband of $R=5$ chain looks deformed, on the other hand, and not\n        at all what  is expected. Something has gone  horribly wrong here. The\n        previous statements do not apply for this case.\n\\end{itemize}\nOn the other hand, these results are as expected:\n\\begin{itemize}\n    \\item \n        The  Passband has  a  slight ripple  of  $\\pm\\SI{1}{\\percent}$ in  all\n        filter chains.  This is well within the filter design specification in\n        theory.  Matlab predicts a  ripple in the cascade's passband between\n        \\SI{0.67}{\\percent} and \\SI{2.8}{\\percent}, depending on the chain.\n    \\item \n        The  passband   shows  a   gain  loss. If  the   optimum  case   of  a\n        \\SI{2}{\\bit}  win   were  achieved,   all  of  the   amplitudes  would\n        be   at  $\\frac{1}{\\sqrt{2}}   =  \\SI{0.707}{\\V}$   (since  input   is\n        \\SI{2}{V_{\\mathrm{PP}}}).    Since   not   all   filter   chains   win\n        the   same   amount  of   bits,   this   sadly   is  not   the   case.\n        Table~\\ref{tab:verification:results} lists  the actual number  of bits\n        won, along with  correction factors which need to be  applied to scale\n        the output correctly.\n\\end{itemize}\nOverall,  these  results  are  mostly acceptable  in  our  view,  particularly\nconsidering that  this system is  in essence a  first prototype which  has not\ngone through any performance tuning  yet. However, there is certainly room for\nfurther investigation and improvement.\n\n\\begin{figure}\n    \\centering\n    \\input{images/verification/rmsAll.tikz}\n    \\caption[RMS at Filter Chain Output]{%\n        RMS  at   the  output   of  each   filter  chain   over  a   range  of\n        frequencies. Input is a sine wave with $\\SI{2}{V_{\\mathrm{PP}}}$.%\n    }\n    \\label{fig:verification:rmsAll}\n\\end{figure}\n\n\n% >>>\n% ==============================================================================\n%\n%                M E A N   F R E Q U E N C Y   R E S P O N S E\n%\n% ==============================================================================\n\\section{Mean Frequency Response} % <<< -------------------------------------- %\n\\label{sec:verification:mean}\n% ---------------------------------------------------------------------------- %\n\nBecause it  became apparent during tests  that the device has  an offset (even\nwithout filters!), the  mean of each sample has been  calculated too such that\nat later stages  the offset can be calibrated out  in the scoping application.\nThe results are shown in Figure~\\ref{fig:verification:meanAll}.\n\n\\begin{figure}\n    \\centering\n    \\input{images/verification/meanAll.tikz}\n    \\caption[Mean at Filter Outputs]{%\n        The  mean  at  the  output  of  each filter  stage  over  a  range  of\n        frequencies.  Since the  input signal is a sine wave  and the function\n        generator which provides it has  been verified to have no (meaningful)\n        offset, these lines should be located at zero volts.%\n    }\n    \\label{fig:verification:meanAll}\n\\end{figure}\n%>>>\n% ==============================================================================\n%\n%                S N R   F R E Q U E N C Y   R E S P O N S E\n%\n% ==============================================================================\n\\clearpage\n\\section{SNR Frequency Response}% <<< ---------------------------------------- %\n\\label{sec:verification:snr}\n% ---------------------------------------------------------------------------- %\n\nTwo  series  of  measurements  are  used  for  SNR: An  automated  one  by  us\nwhich  is  evaluated  with  Matlab's SNR  algorithms. Its  results  are  shown\nin  Figure~\\ref{fig:verification:snrAll}. SNR for  a signal  is determined  by\nseparating signal and  noise components, calculating the  respective power and\nthe ratio of signal power to noise power components\\footnote{%\n    This is similar to what our scope does.%\n}.\nThis series of measurements  allows us to get a good idea of  the shape of the\nsystem's overall frequency response for the SNR.\n\nHowever, Matlab's SNR algorithms are  not perfect; the automated separation of\nsignal from  noise components  is prone  to errors. Consequently,  the results\nachieved by  this method are  below the system's true  capabilities. To assess\nactual  system performance,  SNR  measurements referenced  against a  measured\nnoise floor have also been performed  by Mr. Gut. For this, the noise floor is\nmeasured by terminating  the device with a \\SI{50}{\\ohm}  resistor, instead of\nextracting it from  a signal. Afterwards, a signal is put  through the system,\nthe  power  in  the  signal  is  measured,  and  its  power  compared  to  the\nmeasured noise floor. This  method is more precise than  the automated method,\nand  also  happens to  give  better  results. Its findings are  summarized  in\nTable~\\ref{tab:verification:fifty_ohms}.\n\nWhen comparing our new system against  the measurements of the STEMlab's stock\nconfiguration by our predecessors\\footnote{%\n    Those  measurements  are also  referenced  against  a \\SI{50}{\\ohm}  noise\n    floor.%\n}, our system achieves an SNR of \\SI{84}{\\dB} for an input frequency of \\SI{3}{\\kHz}\nat a sampling rate of \\SI{50}{\\kHz}! The stock configuration needs to downsample\nby a factor of \\num{65536} (corresponding to a sampling frequency of \\SI{1.9}{\\kHz}\nin order to achieve an SNR of \\SI{83.5}{\\dB}\\footnote{%\n    The higher the downsampling ratio, the  better the achievable SNR tends to\n    be.%\n}.\n\n\\begin{figure}\n    \\centering\n    \\input{images/verification/snrAll.tikz}\n    \\caption[SNR at Filter Outputs]{%\n        The  SNR  at  the  output  of  each  filter  stage  over  a  range  of\n        frequencies.   Note the  downward  spikes in  the passband. These  are\n        caused by  Matlab's algorithms during  post-processing and are  not an\n        actual system issue.%\n    }\n    \\label{fig:verification:snrAll}\n\\end{figure}\n\n\\begin{table}\n    \\centering\n    \\caption[SNR Referenced Against \\SI{50}{\\ohm}]{%\n        SNR  measurements  referenced  against   a  true  \\SI{50}{\\ohm}  noise\n        floor,  measured  by  Mr. Gut. The results  constitute  a  significant\n        improvement   over   the   stock  system's   SNR   capabilities   (see\n        Table~\\ref{tab:stl125:measurements_bucher_kuery}). Only the  chain for\n        $f_\\mathrm{s}  = \\SI{25}{\\MHz}$  lies  outside  the expected  pattern;\n        this  has already  been seen  in its  magnitude frequency  response in\n        Section~\\ref{sec:verification:rms}.%\n    }\n    \\label{tab:verification:fifty_ohms}\n    \\begin{tabular}{SSSSSS}\n        \\toprule\n        {\\parbox[t]{10mm}{\\raggedleft $f_\\mathrm{s}$                       \\\\(\\si{\\kHz})}          } &\n        {\\parbox[t]{10mm}{\\raggedleft $f_\\mathrm{signal}$                  \\\\(\\si{\\kHz})}          } &\n        {\\parbox[t]{10mm}{\\raggedleft $V_\\mathrm{sine,RMS}$                \\\\(\\si{\\milli\\volt})}   } &\n        {\\parbox[t]{15mm}{\\raggedleft $V_\\mathrm{noise,RMS}$               \\\\(\\si{\\milli\\volt})}   } &\n        {\\parbox[t]{15mm}{\\raggedleft $\\mathrm{SNR}_\\mathrm{\\SI{50}{\\ohm}}$\\\\(\\si{\\dB})}           } &\n        {\\parbox[t]{10mm}{\\raggedleft $\\mathrm{SNR}_\\mathrm{autom.}$       \\\\(\\si{\\dB})}           } \\\\\n        \\midrule\n           50 &    1 & 707 & 40e-6  & 84   & 71 \\\\\n          100 &   25 & 707 & 55e-6  & 82   & 71 \\\\\n          200 &   50 & 708 & 59e-6  & 81.5 & 69 \\\\\n         1000 &  250 & 708 & 75e-6  & 79.5 & 69 \\\\\n         5000 & 1250 & 707 & 130e-3 & 79.5 & 69 \\\\\n        25000 & 6250 & 707 & 260e-6 & 62   & 69 \\\\\n        \\bottomrule\n    \\end{tabular}\n\\end{table}\n\n% >>>\n% ==============================================================================\n%\n%                   S T O P B A N D   A T T E N U A T I O N\n%\n% ==============================================================================\n\\section{Stopband Attenuation} % <<< ----------------------------------------- %\n\\label{sec:verification:snr}\n% ---------------------------------------------------------------------------- %\n\nMeasuring stopband attenuation  is relevant in order to verify  whether or not\nthe aliasing effect  of the stopband into the passband  during downsampling is\nattenuated to the specified degree of \\SI{60}{\\dB}. See\nFigures~\\ref{fig:aliasing:iirCopies},\n\\ref{fig:cic:freq_responses:passband:aliasing}\nand~\\ref{fig:stl125:moving_averager} for illustrations of the phenomenon.\n\nFor this purpose,  the power density spectrum is plotted\nproperly scaled and adjusted  as seen in Equation~\\ref{eqn:verification:power}\nthrough~\\ref{eqn:verification:power_density}:\n\\begin{align}\n    x_{i,\\mathrm{corrected}} &= x_{i,\\mathrm{V}} \\cdot \\sqrt{\\frac{1}{2f_s N}} \\label{eqn:verification:power} \\\\\n    X                        &= FFT\\left(x_{i,\\mathrm{corrected}}\\right)       \\\\\n    X_{i,\\mathrm{one}}       &= X_i \\cdot 2, i < \\frac{N}{2}+1                 \\\\\n    X_{i,\\mathrm{abs}}       &= |X_{i,\\mathrm{one}}|                           \\\\\n    S_{\\si{\\dB}}             &= 10\\log_{10}(X_{i,\\mathrm{abs}}^2)              \\label{eqn:verification:power_density}\n\\end{align}\n\nFigures~\\ref{fig:verification:fB5}    through    \\ref{fig:verification:fB2500}\ndepict  the results. Each  plot contains  one frequency  which falls  into the\npassband, one which falls into the filter's edge, and one which falls into the\nstopband.   The passband  and edge  frequency  components are  expected to  be\nrelatively high (depending on where exactly  in the edge the measurement point\nfalls). The measurement point in the stopband should be \\SI{60}{\\dB} below the\npassband measurement  point. Most satisfactorily,  this is  the case,  and the\nmeasurement results line up very nicely with the specifications.\n\n\\begin{figure}\n    \\centering\n    \\input{images/verification/foldingBack5.tikz}\n    \\caption[Attenuation in Passband, Edge and Stopband for $R=5$]{%\n        Attenuation in passband, edge and stopband for $R=5$.\n        $f_\\mathrm{s}$ is the sampling rate at the chain's output.%\n    }\n    \\label{fig:verification:fB5}\n\\end{figure}\n\n\\begin{figure}\n    \\centering\n    \\input{images/verification/foldingBack25.tikz}\n    \\caption[Attenuation in Passband, Edge and Stopband for $R=25$]{%\n        Attenuation in passband, edge and stopband for $R=25$.\n        $f_\\mathrm{s}$ is the sampling rate at the chain's output.%\n    }\n    \\label{fig:verification:fB25}\n\\end{figure}\n\n\\begin{figure}\n    \\centering\n    \\input{images/verification/foldingBack125.tikz}\n    \\caption[Attenuation in Passband, Edge and Stopband for $R=125$]{%\n        Attenuation in passband, edge and stopband for $R=125$.\n        $f_\\mathrm{s}$ is the sampling rate at the chain's output.%\n    }\n    \\label{fig:verification:fB125}\n\\end{figure}\n\n\\begin{figure}\n    \\centering\n    \\input{images/verification/foldingBack625.tikz}\n    \\caption[Attenuation in Passband, Edge and Stopband for $R=625$]{%\n        Attenuation in passband, edge and stopband for $R=625$.\n        $f_\\mathrm{s}$ is the sampling rate at the chain's output.%\n    }\n    \\label{fig:verification:fB625}\n\\end{figure}\n\n\\begin{figure}\n    \\centering\n    \\input{images/verification/foldingBack1250.tikz}\n    \\caption[Attenuation in Passband, Edge and Stopband for $R=1250$]{%\n        Attenuation in passband, edge and stopband for $R=1250$.\n        $f_\\mathrm{s}$ is the sampling rate at the chain's output.%\n    }\n    \\label{fig:verification:fB1250}\n\\end{figure}\n\n\\begin{figure}\n    \\centering\n    \\input{images/verification/foldingBack2500.tikz}\n    \\caption[Attenuation in Passband, Edge and Stopband for $R=2500$]{%\n        Attenuation   in   passband,   edge   and   stopband   for   $R=2500$.\n        $f_\\mathrm{s}$ is the sampling rate at the chain's output.%\n    }\n    \\label{fig:verification:fB2500}\n\\end{figure}\n\n% >>>\n% ==============================================================================\n%\n%                                S U M M A R Y\n%\n% ==============================================================================\n\\clearpage\n\\section{Summary} % <<< ------------------------------------------------------ %\n\\label{sec:verification:summary}\n% ---------------------------------------------------------------------------- %\n\nIn  conclusion, the  filter  chains  perform their  task  mostly according  to\nspecifications. The main point  of concern is the stark passband  droop in the\nchain for $R=5$ chain. More investigating is  needed to determine the cause of\nthis behavior. But overall, we consider it to be a success.\n\nTable~\\ref{tab:verification:results}  lists  the  resulting  mean  values  for\ncomparison  against each  other. \\emph{SNR  won} is  the theoretical  SNR gain\ncaused by the bits which are gained  along the processing chain. It is not the\nactually achieved  improvement in SNR  as other factors  play a role  as well.\n\\emph{Correction} is the correction factor which  needs to be applied in order\nto achieve the proper gain (\\SI{0.707}{\\volt} RMS for a \\SI{2}{\\V_\\mathrm{PP}}\nsignal, see Section~\\ref{sec:verification:rms}).\n\n\\vfill\n\\begin{table}[h]\n    \\centering\n    \\caption[Mean Metrics for All Filter Chains]{Mean metrics for all filter chains}\n    \\label{tab:verification:results}\n    \\begin{tabular}{rrrrrrr}\n        \\toprule\n        {\\scshape $R$                 }& \n        {\\scshape $V_\\mathrm{RMS}$ (\\si{V})  }& \n        {\\scshape $V_\\mathrm{Mean}$ (\\si{V}) }& \n        {\\scshape $S_\\mathrm{SNR}$ (\\si{dB}) }&  % TODO: unit correct?\n        {\\parbox[t]{16mm}{\\raggedleft\\scshape Corr.\\\\(\\si{1})}}& \n        {\\parbox[t]{16mm}{\\raggedleft\\scshape Bits\\\\won (\\si{1})}}& \n        {\\parbox[t]{16mm}{\\raggedleft\\scshape SNR\\\\won (\\si{dB})}}\\\\\n        \\midrule\n        5           & 0.6203   & -0.1800   & 79.0054   & 1.1398   & 1.8113   & 10.9038\\\\\n        25          & 0.6329   & -0.1690   & 76.9049   & 1.1171   & 1.8403   & 11.0784\\\\\n        125         & 0.5643   & -0.0159   & 73.6582   & 1.2529   & 1.6748   & 10.0820\\\\\n        625         & 0.5529   & -0.0155   & 71.8813   & 1.2787   & 1.6453   & 9.9048\\\\\n        1250        & 0.4576   & -0.0130   & 69.7006   & 1.5450   & 1.3724   & 8.2617\\\\\n        2500        & 0.4092   & -0.0127   & 63.5121   & 1.7278   & 1.2111   & 7.2908\\\\\n        \\bottomrule\n    \\end{tabular}\n\\end{table}\n\\vfill\n\n% >>>\n\n%^^A vim: foldenable foldcolumn=4 foldmethod=marker foldmarker=<<<,>>>\n", "meta": {"hexsha": "7e592453d508c8213ad149eceb5dbf51aa65001f", "size": 19872, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/report/chunks/verification.tex", "max_stars_repo_name": "alpenwasser/pitaya", "max_stars_repo_head_hexsha": "a6ced99408171ffcd96c9444adfe30d2ba699f48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-03-22T15:26:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-15T20:19:03.000Z", "max_issues_repo_path": "doc/report/chunks/verification.tex", "max_issues_repo_name": "alpenwasser/pitaya", "max_issues_repo_head_hexsha": "a6ced99408171ffcd96c9444adfe30d2ba699f48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/report/chunks/verification.tex", "max_forks_repo_name": "alpenwasser/pitaya", "max_forks_repo_head_hexsha": "a6ced99408171ffcd96c9444adfe30d2ba699f48", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.8045112782, "max_line_length": 117, "alphanum_fraction": 0.5995873591, "num_tokens": 5471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.3243459895437257}}
{"text": "Motion planning is needed for tensegrity robots to perform complex\ntasks, such as goal-directed locomotion over uneven terrains.  Early\nmethods defined the desired trajectory for the structure's center of\nmass \\cite{Pinaud2003Path-Planning-f} or for some of its nodes\n\\cite{Wijdeven:2005dz} in the workspace.  Then, they divided the\ntrajectory into small segments, and for each of them, a stable\nstructure configuration was found using optimization.  But collisions\nwere not considered, which motivated approaches for (self-)collision\navoidance \\cite{Xu2013Collision-free-, hernandez2009reconfigurable},\nwhile keeping the structure stable. Recent path planning approaches\ntake collisions into account, but the control process is assumed slow\nenough to eliminate any dynamic effects \\cite{Xu2013Collision-free-,\nPorta:2015aa}. This quasistatic assumption is often used in\ntensegrity-based civil structures \\cite{Rhode-Barbarigos:2012fv} but\nis not easily justifiable in robotic applications.\n\n\\subsection{Efficient Kinodynamic Planning for Tensegrity Robots}\n\nA tensegrity planner should be able to select a reconfiguration that\ntakes advantage of nonlinear dynamics to emulate behaviors, such as\nrunning, jumping, and climbing, instead of limiting the structure to\nslow reconfigurations. At the same time it should deal with the\nhigh-dimensionality of a tensegrity robot's state space. Various\nalternatives can be considered, as long as they can deal with\nsignificant dynamics and complex contacts.\n\nTrajectory planning can be formulated as a non-convex constraint\noptimization, where a trajectory cost function must be minimized given\nconstraints arising from collision avoidance and actuator limits.  One\nway to solve this problem is sequential convex optimization, where a\nconvex approximation around a trajectory is computed in an iterative\nmanner \\cite{Schulman:2014aa}. This framework has shown promise in\ndynamical systems \\cite{Schulman:2014aa} and recently in soft\nmanipulators \\cite{Marchese:2016aa}. At the same time, it does not\nprovide performance guarantees, as it may get stuck in local minima\nwhere constraints are violated. Approaches, such as {\\tt\nCHOMP} \\cite{Zucker:2013aa}, introduce a Monte Carlo process to\nachieve probabilistic completeness. Nevertheless, there are many\nimplementation aspects that need to be addressed for such methods: a)\nsimplifications, such as approximating the robot geometry with spheres\nmay not be appropriate for tensegrities, b) and it may not be easy to\ndefine certain primitives, such as Jacobians, or formulating complex\nconstraints.\n\nAn alternative that provides probabilistic completeness is founded on\nsampling-based motion planning~\\cite{Kavraki1996Probabilistic-R},\nwhich finds valid robot configurations and connects them with locally\nvalid paths. Tree-based variants, such as {\\tt\nRRT}~\\cite{LaValle2001}, can deal with significant dynamics as they\nonly need a forward propagation model, such as a physics engine, to\nsimulate the progression of a system's state.  Recently the conditions\nunder which these methods achieve asymptotic optimality have been\nidentified for kinematic systems\n\\cite{Karaman:2011aa}. Two recent developments also bring the hope\nthat sampling-based methods can provide global trajectories for\ntensegrity robots in a computationally efficient manner, while\nconsidering complex physical interactions:\n\\begin{myitem}\n  \\item[a)] efficient physics-based simulation for tensegrity robots,\n    which are verified in hardware, are now available\n    \\cite{Caluwaerts2013rsif};\n  \\item[b)] asymptotically optimal and computationally efficient\n    sampling-based planners have been developed for highly nonlinear,\n    underactuated dynamics \\cite{Li2015Sparse-Methods-}.\n\\end{myitem}\n\nFig.~\\ref{fig:tens_example} illustrates a trajectory computed by such\na method \\cite{Li2015Sparse-Methods-} for a simulated SUPERball\nrobot~\\cite{SunSpiralSoftware}. The method provides anytime\nproperties, i.e., it returns trajectories of increasing quality as\ncomputation time increases. The implementation behind\nFig.~\\ref{fig:tens_example} randomly samples controls for the robot\nand then optimizes over the resulting trajectories.\n\nWhile promising, the above implementation is not taking advantage of\nmorphological computation as the planner reasons about the underlying\nrobot at its full complexity. One way to improve performance is the\nintegration of such high-level dynamical planners with lower-level\ncontrollers, such as {\\tt CPGs} \\cite{Ijspeert2008,\nBliss2013Central-Pattern,MirletzSoftRobotics}. The latter take\nadvantage of morphological computation and provide identifiable motion\nbehaviors adaptable to different terrains. In such an integration, the\nhigh-level planner can explore the space by sampling from a library of\nmaneuvers/behaviors by invoking different low-level controllers. This\ncan potentially provide a general framework for goal-directed\nmulti-modal locomotion of tensegrity structures that takes advantage\nof morphological computation \\cite{Nurzaman:2015aa,\nKhazanov:2014aa}. It is useful to consider whether probabilistic\ncompleteness and asymptotic optimality can still be provided for the\nintegrated framework.\n\n\\subsection{Re-Planning in Belief Space with Complex Dynamics}\n\nDespite the progress in tensegrity modeling and even if dynamics are\nreasonably taken into account, modeling errors and noise will result\nin inaccurate execution of trajectories. One way to deal with this\nissue is to represent uncertainty about the robot state as a\nprobability distribution, and plan in the set of distributions over\nstates, called the belief space. In this context, the planner aims to\ncompute the trajectory that maximizes the probability of success in\nreaching a desired target. This challenge corresponds to a Partially\nObservable Markov Decision Process ({\\tt POMDP})\n\\cite{Kaebling:1998aa}. Planning in the belief space is challenging:\n\\begin{myitem}\n\\item[a)] A policy needs to be computed, where an action must be mapped\n  to every possible belief distribution, which is a large, continuous\n  space.\n\\item[b)] The resulting belief state dynamics are highly nonlinear\n  and underactuated.\n\\end{myitem}\nNevertheless, recent advances have shown that motion planning in\nbelief space is becoming practical for many medium size problems by\nemploying reasonable approximations and efficient algorithmic tools\n\\cite{Platt:2010aa,Bai:2012aa}, bringing the\nhope of potentially addressing more complex problems.\n\n\\begin{figure}[h!]\n  \\vspace{-.1in}\n  \\centering\n\\includegraphics[width=.48\\textwidth]{figures/belief_replanning.png}\n\\vspace{-0.3in}\n\\caption{Replanning in belief space, where the first action of a plan\n  is executed and the planner is called again given an updated\n  belief. This allows the use of conformant planning, which operates\n  in the belief space but does not compute a policy. Instead it\n  returns the most robust trajectory.}\\vspace{-0.1in}\n\\label{fig:belief_replanning}\n\\end{figure}\n\nFor instance, one way to reduce the complexity of the first challenge\nabove is to follow a replanning approach in belief space\n\\cite{Platt:2010aa}, similar to model predictive control, as\nillustrated in Fig.~\\ref{fig:belief_replanning}. In this case, only\nthe first action of the plan is executed and after the belief state is\nupdated, the planner is called again. This means that the planner does\nnot need to map actions to every possible belief but instead only\ncompute the most robust trajectory given the current initial belief,\nthe probabilistic transition model, and with no online observations.\nThis type of conformant planning, or a Non-Observable Markov Decision\nProcess, is easier than computing a general {\\tt POMDP} policy.\n\nEven after the consideration of a replanning approach, the second\nchallenge remains, i.e., the conformant planner needs to optimize the\nrobustness of trajectories in a highly nonlinear and underactuated\nstate space. Nevertheless, the recent sampling-based motion planners\nfor computing asymptotically optimal trajectories for complex\ndynamical systems can now address such problems\n\\cite{Li2015Sparse-Methods-}. Recent work has shown that these methods\ncan be used for belief space conformant planning, where the objective\nis to compute control inputs for high-dimensional, nonlinear and\nunderactuated systems that safely drive them to a goal region with a\nprobability above a given threshold \\cite{Littlefield:2015aa}.\n\nThe representation of the underlying belief plays a critical role. The\nhigh-dimensionality of tensegrities, the multi-modality from the\npresence of contacts, and the highly nonlinear nature of the dynamics\npose significant challenges to both parametric representations, such\nas Gaussian beliefs, and non-parametric ones, such as particle\nfilters. The highlighted recent work has followed a particle\nrepresentation, which can deal with multi-modality but is\ncomputationally expensive. Figure \\ref{fig:particles} shows the\npropagation of multiple particles for the SUPERball given the same\ncontrol under the presence of noise.  It is interesting to consider\nhow to achieve effective belief space conformant replanning in the\ncase of tensegrity robots and focus on the proper modeling and fast\ncomputation of the resulting uncertainty.\n\n\\begin{figure}[t]\n\\centering\n\\includegraphics[width=.48\\textwidth]{figures/particles.png}\n\\vspace{-0.3in}\n\\caption{A trajectory for the SUPERBall in belief space, where the\n  application of controls can result in different outcomes due to noise.\n  For the same control sequence a belief distribution over possible\n  future states arises. A particle representation is followed for the\n  belief \\cite{Littlefield:2015aa}, which is illustrated as\n  transparent versions of the robot.}  \\vspace{-0.25in}\n\\label{fig:particles}\n\\end{figure}\n\n\\subsection {Model-based feedback motion planning}\n\nAnother avenue for dealing with noise and uncertainty involves the use\nof feedback-based controllers, which aim to stabilize the robot at a\ntarget state or trajectory, despite disturbances. For global motion\nplanning, this requires composing a sequence of low-level feedback\ncontrollers, as shown in Fig.~\\ref{fig:funnelcake}.\nwhich \\emph{funnel} the system toward a desired target in a way that\nlocal minima are avoided~\\cite{Burridge:1999aa, Conner:2006aa}.\n\nOne way to implement this principle is through the framework of\nwhole-body control via an operational space formulation\n\\cite{Khatib:1987aa,Sentis2005}. This involves the definition of\nartificial potential fields for different tasks and their\nprioritization, so that lower priority tasks are allowed to influence\nthe robot given only access to the null-space of higher priority\nprimitives. Tasks can include the avoidance of self-collisions,\nreaching a desired configuration, and maintaining a desired posture.\nThe formulation of an Elastic Roadmap over operational spaces is done\nby tiling the underlying state space with different, locally valid\ncontrollers and specifying the transitions between them, while also\nallowing for fast responses to sensory input \\cite{Yang2010}. A\nchallenge for tensegrity robots is defining the artificial potential\nfields in a way that they are valid for significant subsets of the\nstate space. Related to the challenge of defining proper Jacobians for\nthese systems, defining effective potential fields is not trivial.\nMuch like trajectory optimization methods, it is typically difficult\nto argue about the properties and quality of paths generated from such\nfeedback controllers.\n\n\\begin{wrapfigure}{r}{0.2\\textwidth}\n  \\centering\n  \\vspace{-.15in}\n\\includegraphics[width=.2\\textwidth]{figures/Funnel.png}\n\\vspace{-0.2in}\n\n\\caption{The basic principle in feedback-based planning. The resulting\n  state of a controller should be in the region of attraction of\n  another.  The union of these regions should cover the state space so\n  that the composition of controllers leads to the goal from any\n  initial state.\\vspace{-0.1in}}\n\\label{fig:funnelcake}\n\\end{wrapfigure}\n\nAn alternative methodology aims to provide probabilistic completeness\nfor feedback-based planning by composing multiple Linearized Quadratic\nRegulators ({\\tt LQR}), where each regulator stabilizes the system\naround an individual trajectory. The composition can result in a\ntree-like structure that allows for global planning\n\\cite{Tedrake2010}, where the {\\tt LQR}-trees incrementally cover the\nstate space with their regions of attraction. A region of attraction\nis the subset of the state space where the application of an {\\tt LQR}\ncontroller allows the stabilization of the system to a desired\ntrajectory.  Recent progress has allowed the conservative computation\nof such areas for certain systems with dynamics.  A simulation-based\nmethodology has also been proposed that aims to approximate these\nregions given access only to a simulator for the underlying system\n\\cite{Reist2010}. Applying this line of work on tensegrity robots can\npotentially result in feedback solutions that can provide a certificate\nof completeness.  It requires the formulation\nof locally valid {\\tt LQR} controllers for tensegrity robots with\ncomputable regions of attractions, even if approximate. Such\ncontrollers and regions of attractions should be generated quickly\ngiven new sensor data.\n\nThe application of effective artificial potential fields or {\\tt LQR}\ncontrollers on tensegrity robots may prove difficult due to challenges in modeling  \ncomplex dynamic interactions with the environment.  As pointed out in Section\n\\ref{sec:control}, however, effective low-level and model-free\nlocomotion controllers have already been defined for tensegrity\nstructures, such as those based on {\\tt\nCPG}s \\cite{MirletzSoftRobotics, Caluwaerts2013rsif,\nBliss2013Central-Pattern}.  It is interesting to explore the\ncomposition of such controllers in a way that global feedback-based\nmotion planning can be achieved. This will require exploration of the\nconditions under which they work and how transitioning between\ndifferent controllers can be achieved, thereby synthesizing\ncertificates for whether a particular controller can achieve a desired\nresult. This direction also indicates one way that model-based\nplanning principles can be integrated with developments in the\nmodel-free low-level controller domain.\n\n\\begin{comment}\n\\komment{\n\nGiven the development of effective controllers specifically for\ntensegrity structures, such as {\\tt CPG}s, one can focus on integrating\nthese controllers so as to solve more complex planning problems, while\nproviding feedback solutions with guarantees. This would require that\nthese controllers are able to provide some form of certificates about\ntheir effectiveness, i.e., the conditions under which they work,\nregion of attraction, etc..}\n\n\\komment{Nice visuals can be generated for many of the principles\nfor the above set of methods.}\n\\end{comment}\n", "meta": {"hexsha": "9f42ede711687cba115b2e8036485cef28617373", "size": 14913, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Dissertation/tex/reviewPaper/04_planning.tex", "max_stars_repo_name": "JEB12345/Advancement_UCSC", "max_stars_repo_head_hexsha": "92c7f0bdaecde6bce2c6ee47d401e0335e449d6b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Dissertation/tex/reviewPaper/04_planning.tex", "max_issues_repo_name": "JEB12345/Advancement_UCSC", "max_issues_repo_head_hexsha": "92c7f0bdaecde6bce2c6ee47d401e0335e449d6b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Dissertation/tex/reviewPaper/04_planning.tex", "max_forks_repo_name": "JEB12345/Advancement_UCSC", "max_forks_repo_head_hexsha": "92c7f0bdaecde6bce2c6ee47d401e0335e449d6b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.8375451264, "max_line_length": 84, "alphanum_fraction": 0.8198216321, "num_tokens": 3286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.32424670082979257}}
{"text": "\\section{Updates: 08/13/2020}%\n\\label{sec:updates_2020_08_13}\n\\subsection{HMC Results}\n%\nFor a fixed value of \\(\\beta\\), we are interested in finding the values of\n\\(N_\\mathrm{LF}, \\varepsilon\\) that give the optimal tunneling rate, \\(\\delta\nQ\\).\n%\n% +--------------+\n% |   beta = 1   |\n% +--------------+\n\\begin{figure}[htpb]\n  \\centering\n  \\begin{subfigure}[htpb]{0.40\\textwidth}\n    \\includegraphics[width=\\textwidth]{updates_2020_08_13/dq_b1.png}\n    \\caption{\\(\\delta Q\\) vs. \\(N_{\\mathrm{LF}}, \\varepsilon\\) at \\(\\beta =\n    1\\)}%\n  \\end{subfigure}\n  \\begin{subfigure}[htpb]{0.40\\textwidth}\n    \\includegraphics[width=\\textwidth]{updates_2020_08_13/dq_sin_b1.png}\n    \\caption{\\(\\delta Q_{\\sin}\\) vs. \\(N_{\\mathrm{LF}}, \\varepsilon\\)\n    at \\(\\beta = 1\\)}%\n  \\end{subfigure}\n\\end{figure}\n%\n% +--------------+\n% |   beta = 2   |\n% +--------------+\n\\begin{figure}[h!]\n  \\centering\n  \\begin{subfigure}[htpb]{0.40\\textwidth}\n    \\includegraphics[width=\\textwidth]{updates_2020_08_13/dq_b2.png}\n    \\caption{\\(\\delta Q\\) vs. \\(N_{\\mathrm{LF}}, \\varepsilon\\) at \\(\\beta =\n    2\\)}%\n  \\end{subfigure}\n  \\begin{subfigure}[htpb]{0.40\\textwidth}\n    \\includegraphics[width=\\textwidth]{updates_2020_08_13/dq_sin_b2.png}\n    \\caption{\\(\\delta Q_{\\sin}\\) vs. \\(N_{\\mathrm{LF}}, \\varepsilon\\)\n    at \\(\\beta = 2\\)}%\n  \\end{subfigure}\n\\end{figure}\n%\n% +--------------+\n% |   beta = 3   |\n% +--------------+\n\\begin{figure}[h!]\n  \\centering\n  \\begin{subfigure}[htpb]{0.40\\textwidth}\n    \\includegraphics[width=\\textwidth]{updates_2020_08_13/dq_b3.png}\n    \\caption{\\(\\delta Q\\) vs. \\(N_{\\mathrm{LF}}, \\varepsilon\\) at \\(\\beta =\n    3\\)}%\n  \\end{subfigure}\n  \\begin{subfigure}[htpb]{0.40\\textwidth}\n    \\includegraphics[width=\\textwidth]{updates_2020_08_13/dq_sin_b3.png}\n    \\caption{\\(\\delta Q_{\\sin}\\) vs. \\(N_{\\mathrm{LF}}, \\varepsilon\\)\n    at \\(\\beta = 3\\)}%\n  \\end{subfigure}\n\\end{figure}\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% +--------------+\n% |   beta = 1   |\n% +--------------+\n\\clearpage\n% \\subsubsection{\\(\\beta = 1\\)}%\n% \\label{subsubsec:hmc_beta1_lineplots}\n\\begin{figure}[h!]\n  \\centering\n  \\begin{subfigure}[htpb]{0.4725\\textwidth}\n    \\includegraphics[width=\\textwidth]{updates_2020_08_13/lines/dq_ns_b1}\n    \\caption{\\(\\delta Q\\) vs. \\(N_{\\mathrm{LF}}\\) at \\(\\beta = 1\\)}%\n  \\end{subfigure}\n  \\begin{subfigure}[htpb]{0.4725\\textwidth}\n    \\includegraphics[width=\\textwidth]{updates_2020_08_13/lines/dqs_ns_b1}\n    \\caption{\\(\\delta Q_{\\sin}\\) vs. \\(N_{\\mathrm{LF}}\\) at \\(\\beta = 1\\)}%\n  \\end{subfigure}\n\\end{figure}\n%\n\\begin{figure}[h!]\n  \\centering\n  \\begin{subfigure}[htpb]{0.4725\\textwidth}\n    \\includegraphics[width=\\textwidth]{updates_2020_08_13/lines/dq_eps_b1}\n    \\caption{\\(\\delta Q\\) vs. \\(\\varepsilon\\) at \\(\\beta = 1\\)}%\n  \\end{subfigure}\n  \\begin{subfigure}[htpb]{0.4725\\textwidth}\n    \\includegraphics[width=\\textwidth]{updates_2020_08_13/lines/dqs_eps_b1}\n    % \\caption{\\(\\delta Q\\) vs. \\(\\varepsilon\\) at \\(\\beta = 1\\)}%\n    \\caption{\\(\\delta Q_{\\sin}\\) vs. \\(\\varepsilon\\) at \\(\\beta = 1\\)}%\n  \\end{subfigure}\n\\end{figure}\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% +--------------+\n% |   beta = 2   |\n% +--------------+\n\\clearpage\n% \\subsubsection{\\(\\beta = 2\\)}%\n% \\label{subsubsec:hmc_beta2_lineplots}\n\\begin{figure}[h!]\n  \\centering\n  \\begin{subfigure}[htpb]{0.4725\\textwidth}\n    \\includegraphics[width=\\textwidth]{updates_2020_08_13/lines/dq_ns_b2}\n    \\caption{\\(\\delta Q\\) vs. \\(N_{\\mathrm{LF}}\\) at \\(\\beta = 2\\)}%\n  \\end{subfigure}\n  \\begin{subfigure}[htpb]{0.4725\\textwidth}\n    \\includegraphics[width=\\textwidth]{updates_2020_08_13/lines/dqs_ns_b2}\n    \\caption{\\(\\delta Q_{\\sin}\\) vs. \\(N_{\\mathrm{LF}}\\) at \\(\\beta = 2\\)}%\n  \\end{subfigure}\n\\end{figure}\n%\n\\begin{figure}[h!]\n  \\centering\n  \\begin{subfigure}[htpb]{0.4725\\textwidth}\n    \\includegraphics[width=\\textwidth]{updates_2020_08_13/lines/dq_eps_b2}\n    \\caption{\\(\\delta Q\\) vs. \\(\\varepsilon\\) at \\(\\beta = 2\\)}%\n  \\end{subfigure}\n  \\begin{subfigure}[htpb]{0.4725\\textwidth}\n    \\includegraphics[width=\\textwidth]{updates_2020_08_13/lines/dqs_eps_b2}\n    \\caption{\\(\\delta Q_{\\sin}\\) vs. \\(\\varepsilon\\) at \\(\\beta = 2\\)}%\n  \\end{subfigure}\n\\end{figure}\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% +--------------+\n% |   beta = 3   |\n% +--------------+\n\\clearpage\n% \\subsubsection{\\(\\beta = 3\\)}%\n% \\label{subsubsec:hmc_beta3_lineplots}\n\\begin{figure}[h!]\n  \\centering\n  \\begin{subfigure}[htpb]{0.4725\\textwidth}\n    \\includegraphics[width=\\textwidth]{updates_2020_08_13/lines/dq_ns_b3}\n    \\caption{\\(\\delta Q\\) vs. \\(N_{\\mathrm{LF}}\\) at \\(\\beta = 3\\)}%\n  \\end{subfigure}\n  \\begin{subfigure}[htpb]{0.4725\\textwidth}\n    \\includegraphics[width=\\textwidth]{updates_2020_08_13/lines/dqs_ns_b3}\n    \\caption{\\(\\delta Q_{\\sin}\\) vs. \\(N_{\\mathrm{LF}}\\) at \\(\\beta = 3\\)}%\n  \\end{subfigure}\n\\end{figure}\n%\n\\begin{figure}[h!]\n  \\centering\n  \\begin{subfigure}[htpb]{0.4725\\textwidth}\n    \\includegraphics[width=\\textwidth]{updates_2020_08_13/lines/dq_eps_b3}\n    \\caption{\\(\\delta Q\\) vs. \\(\\varepsilon\\) at \\(\\beta = 3\\)}%\n  \\end{subfigure}\n  \\begin{subfigure}[htpb]{0.4725\\textwidth}\n    \\includegraphics[width=\\textwidth]{updates_2020_08_13/lines/dqs_eps_b3}\n    \\caption{\\(\\delta Q_{\\sin}\\) vs. \\(\\varepsilon\\) at \\(\\beta = 3\\)}%\n  \\end{subfigure}\n\\end{figure}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\clearpage\n\\subsection{Training results}%\n\\label{subsec:2020_08_13_training_results}\n% +--------------+\n% |   beta = 1   |\n% +--------------+\n\\begin{figure}[htpb]\n  \\centering\n  \\begin{subfigure}[htpb]{0.375\\textwidth}\n    \\includegraphics[width=\\textwidth]{updates_2020_08_13/training_lf10_beta1/dq_avg.png}\n    \\caption{\\(\\langle\\delta Q\\rangle\\) vs training step at \\(\\beta = 1\\)}%\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[htpb]{0.375\\textwidth}\n    \\includegraphics[width=\\textwidth]{updates_2020_08_13/training_lf10_beta1/dq_sin_avg.png}\n    \\caption{\\(\\langle\\delta Q_{\\sin}\\rangle\\) vs training step at \\(\\beta = 1\\)}%\n  \\end{subfigure}\n\\end{figure}\n\n% +--------------+\n% |   beta = 2   |\n% +--------------+\n\\begin{figure}[htpb]\n  \\centering\n  \\begin{subfigure}[htpb]{0.375\\textwidth}\n    \\includegraphics[width=\\textwidth]{updates_2020_08_13/training_lf10_beta2/dq_avg.png}\n    \\caption{\\(\\langle\\delta Q\\rangle\\) vs training step at \\(\\beta = 2\\)}%\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[htpb]{0.375\\textwidth}\n    \\includegraphics[width=\\textwidth]{updates_2020_08_13/training_lf10_beta2/dq_sin_avg.png}\n    \\caption{\\(\\langle\\delta Q_{\\sin}\\rangle\\) vs training step at \\(\\beta = 2\\)}%\n  \\end{subfigure}\n\\end{figure}\n\n% +--------------+\n% |   beta = 3   |\n% +--------------+\n\\begin{figure}[htpb]\n  \\centering\n  \\begin{subfigure}[htpb]{0.375\\textwidth}\n    \\includegraphics[width=\\textwidth]{updates_2020_08_13/training_lf10_beta3/dq_avg.png}\n    \\caption{\\(\\langle\\delta Q\\rangle\\) vs training step at \\(\\beta = 3\\)}%\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[htpb]{0.375\\textwidth}\n    \\includegraphics[width=\\textwidth]{updates_2020_08_13/training_lf10_beta3/dq_sin_avg.png}\n    \\caption{\\(\\langle\\delta Q_{\\sin}\\rangle\\) vs training step at \\(\\beta = 2\\)}%\n  \\end{subfigure}\n\\end{figure}\n", "meta": {"hexsha": "32be591378318aa5776a252b59c79a47c5a9e2c4", "size": 7181, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/updates/updates_2020_08_13.tex", "max_stars_repo_name": "saforem2/l2hmc-qcd", "max_stars_repo_head_hexsha": "b5fe06243fae663607b6c88e71373b68b19558fc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2019-04-18T18:50:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T18:30:48.000Z", "max_issues_repo_path": "doc/updates/updates_2020_08_13.tex", "max_issues_repo_name": "saforem2/l2hmc-qcd", "max_issues_repo_head_hexsha": "b5fe06243fae663607b6c88e71373b68b19558fc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2019-09-09T21:10:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T17:43:51.000Z", "max_forks_repo_path": "doc/updates/updates_2020_08_13.tex", "max_forks_repo_name": "saforem2/l2hmc-qcd", "max_forks_repo_head_hexsha": "b5fe06243fae663607b6c88e71373b68b19558fc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-10-31T02:25:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-25T00:49:14.000Z", "avg_line_length": 34.5240384615, "max_line_length": 93, "alphanum_fraction": 0.6169057234, "num_tokens": 2597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891307678319, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3242466928844136}}
{"text": "\\section{Introduction}\n\nFormal verification is a subject that constantly attracts attention of the research community. Static type systems are considered to be a lightweight verification method but they can be very powerful and precise as well. Dependent type systems in languages like Agda~\\cite{Nor07}, Idris~\\cite{Bra13} or Coq~\\cite{coq} can be successfully applied in practical verification tasks but they are not yet as widely used as they could potentially be. This paper contributes to changing that.\n\n\\subsection{Motivation}\n\nTwo things have motivated me to write this paper. Firstly, while there are many tutorials on dependently typed programming and basics of verification, I could find little material demonstrating how to put verification to practical use. A must-read introductory paper ``Why Dependent Types Matter'' by Altenkirch, McKinna and McBride \\cite{AltMcBMcK05}, which demonstrates how to use dependent types to prove correctness of merge sort algorithm, actually elides many proof details that are required in a real-world application. I want to fill in that missing gap by writing a tutorial that picks up where other tutorials have ended.\n\nMy second motivation comes from reading Okasaki's classical ``Purely Functional Data Structures''~\\cite{Oka99}. Despite book's title many presented implementations are not purely functional as they make use of impure exceptions to handle corner cases (eg. taking head of an empty list). I realised that using dependent types allows to do better and it is instructive to build a provably correct purely functional data structure on top of Okasaki's presentation.\n\nIn the end this paper is both a tutorial and a case study of weight biased leftist heap implemented in dependently typed setting. My goal is to teach the reader how to build complex proofs from simple ones. As a result the reader will be able to verify that operations on a data structure maintain required invariants. Acquired knowledge will allow to understand more advanced verification techniques, eg. equational reasoning provided by Agda's standard library or tactics system found in Idris \\cite{Bra13} and Coq \\cite{coq}.\n\n\\subsection{Companion code}\n\nThis tutorial comes with a standalone companion code written in Agda 2.3.4\\footnote{\\url{http://ics.p.lodz.pl/~stolarek/_media/pl:research:dep-typed-wbl-heaps.tar.gz}}\\footnote{NOTE TO THE REVIEWER: Agda 2.3.4 is planned to be released sometime in February or March. Companion code was created using latest development version of Agda. This notice will be removed from final version of the paper.}. I assume the reader is reading companion code along with the paper. Due to space limitations I elide some proofs that are detailed in the code using Notes convention adapted from GHC project~\\cite{MarPey12}.\n\n``Living'' version of companion code is available at GitHub\\footnote{\\url{https://github.com/jstolarek/dep-typed-wbl-heaps}} and it may receive updates after the paper is published.\n\n\\subsection{Assumptions}\n\nI assume that reader has basic understanding of Agda, some elementary definitions and proofs. In particular I assume the reader is familiar with definition of natural numbers (\\texttt{Nat}s) and their addition (\\texttt{+}) as well as proofs of basic properties of addition like associativity, commutativity or 0 as right identity ($a + 0 ≡ a$). Reader should also understand \\texttt{refl} with its basic properties (symmetry, congruence, transitivity and substitution), know the concept of ``data as evidence'' and other ideas presented in ``Why Dependent Types Matter'' \\cite{AltMcBMcK05} as I will build upon them. All of these are implemented in the \\texttt{Basics} module in the companion code. Module \\texttt{Basics.Reasoning} reviews in detail the above-mentioned proofs.\n\n\\subsection{Notation and conventions}\n\nIn the rest of the paper I will denote heaps using \\texttt{typewriter font} and their ranks using an \\textit{italic type}. The description of merge algorithm will mention heaps \\texttt{h1} and \\texttt{h2} with ranks \\textit{h1} and \\textit{h2} respectively, their left children (\\texttt{l1} in \\texttt{h1} and \\texttt{l2} in \\texttt{h2}) and right children (\\texttt{r1} in \\texttt{h1} and \\texttt{r2} in \\texttt{h2}) with \\texttt{p1} and \\texttt{p2} as the priorities of root elements in \\texttt{h1} and \\texttt{h2} respectively. In the text I will use $\\oplus$ to denote heap merging operation. So \\texttt{h1}$\\oplus$\\texttt{h2} will be a heap created by merging \\texttt{h1} with \\texttt{h2}, while \\textit{h1}$\\oplus$\\textit{h2} will be the rank of the merged heap.\n\nI will represent priority using natural numbers with lower number meaning higher priority. This means that 0 will be the highest priority, while the lowest priority will be unbounded. This also means that if \\texttt{p1 > p2} holds as a relation on natural numbers then \\texttt{p2} is higher priority than \\texttt{p1}.\n\nIn the text I will use numerals to represent \\texttt{Nat}s but the code uses encoding based on \\texttt{zero} and \\texttt{suc}. Thus 2 in the text will correspond to \\texttt{suc (suc zero)} in the source code.\n\nI will use \\texttt{\\hilight{\\{ \\}?}} in code listings to represent Agda holes.\n\nRemember that any sequence of Unicode characters is a valid identifier in Agda. Thus \\texttt{l≥r} is an identifier, while \\texttt{l ≥ r} is application of \\texttt{≥} operator to \\texttt{l} and \\texttt{r} operands.\n\n\\subsection{Contributions}\n\nThis paper contributes the following:\n\n\\begin{itemize}\n \\item Section~\\ref{sec:no-proofs} presents unverified implementation and the problem of partiality of functions operating on a weight biased leftist heap. While the problem in general is well-known the solution to this particular case can be combined with verification of one of data structure's invariants. This is done in Section~\\ref{sec:rank-property}.\n \\item Section~\\ref{sec:eq-proofs-using-trans} outlines a technique for constructing equality proofs using transitivity of propositional equality. This simple, standalone technique provides ground for understanding verification mechanisms used in Agda's standard library.\n \\item Section~\\ref{sec:single-pass-merge-proof-by-comp} uses the technique introduced in Section~\\ref{sec:eq-proofs-using-trans} to prove code obtained by inlining one function into another. This shows how programs created from small, verified components can be proved correct by composing proofs of these components.\n \\item Section~\\ref{sec:priority-invariant} contains a case study of how a proof of data structure invariant influences the design of an API. This is demonstrated on the example of priority invariant proof and its influence on designing insertion of a new element into a heap.\n\\end{itemize}\n", "meta": {"hexsha": "177565621bf74769d3345b2bdf8a1d8ad376cbc8", "size": 6741, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/1-introduction.tex", "max_stars_repo_name": "jstolarek/dep-typed-wbl-heaps", "max_stars_repo_head_hexsha": "57db566cb840dc70331c29eb7bf3a0c849f8b27e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-05-02T21:48:43.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-02T21:48:43.000Z", "max_issues_repo_path": "paper/1-introduction.tex", "max_issues_repo_name": "jstolarek/dep-typed-wbl-heaps", "max_issues_repo_head_hexsha": "57db566cb840dc70331c29eb7bf3a0c849f8b27e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/1-introduction.tex", "max_forks_repo_name": "jstolarek/dep-typed-wbl-heaps", "max_forks_repo_head_hexsha": "57db566cb840dc70331c29eb7bf3a0c849f8b27e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 149.8, "max_line_length": 777, "alphanum_fraction": 0.7949859071, "num_tokens": 1595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3242466928844136}}
{"text": "\\documentclass{llncs}\n\\newcommand{\\X}{{\\bf X}}\n\\newcommand{\\x}{{\\bf x}}\n\\newcommand{\\Y}{{\\bf Y}}\n\\newcommand{\\y}{{\\bf y}}\n\\newcommand{\\Z}{{\\bf Z}}\n\\newcommand{\\z}{{\\bf z}}\n\\newcommand{\\bs}{\\boldsymbol}\n\\newcommand{\\bSigma}{\\boldsymbol \\Sigma}\n\\usepackage{amsmath,amssymb,algorithm,algorithmic}\n\\usepackage{times}\n\\usepackage{setspace,verbatim}\n\\usepackage{epsfig,url,subfigure}\n\n\\begin{document}\n\\title{Partial sparse canonical correlation analysis (PSCCA) for population\n  studies in medical imaging}\n\\author{Anonymous}\n\\institute{Anonymous}\n\\maketitle              \n\\begin{abstract}\nWe propose a new multivariate method, partial sparse canonical\ncorrelation analysis (PSCCA), for computing the statistical\ncomparisons needed by population studies in medical imaging.  PSCCA is a\nmultivariate generalization of linear regression that allows one to statistically parameterize imaging studies in terms of\nmultiple views of the population (e.g., the full collection of\nmeasurements taken from an image set along with batteries of cognitive\nor genetic data) while controlling for nuisance variables.  This paper\ndevelops the theory of PSCCA, provides an algorithm and illustrates\nPSCCA performance on both simulated and real datasets.  We show, as a\nfirst application and evaluation of this new methodology, that\nPSCCA can improve detection power over mass univariate approaches\nwhile retaining the interpretability and biological plausibility of\nthe estimated effects.  We also discuss the strengths, limitations and\nfuture potential of this methodology.\n\\end{abstract}\n\\section{Introduction}\n% pubmed references to MRI :  \n% 2000-2001 --- 25561\n% 2001-2002 --- 27053\n% 2003-2004 --- 31708\n% 2005-2006 --- 38620\n% 2008-2009 --- 49288\n% 2009-2010 --- 49323\n% pubmed references to MRI brain :  \n% 2000-2001 --- 9938\n% 2001-2002 --- \n% 2003-2004 --- 12655\n% 2005-2006 --- \n% 2008-2009 --- \n% 2009-2010 --- 19676 ------  \n% MRI brain statistical parametric mapping 783 results ,\n% MRI brain gives \nThe number of neuroimaging studies published annually has doubled from\n9,938 in 2000-2001 to 19,676 in 2009-2010\n(\\url{http://www.ncbi.nlm.nih.gov/pubmed/}).  This growth has been\naccompanied by increasing diversity in the types of data being\ncollected; Imaging studies now often include not only various\nstructural and functional modalities but also neurocognitive\nbatteries, genetics, and environmental measurements.  However, the\nstatistical methods have changed relatively little over the past\ntwenty years -- until very recently (e.g., \\cite{Tosun2010a}).  The\nincreasing size of imaging datasets and the concomitant desire for\nperforming integrative studies across modalities points to the need\nfor new multivariate statistical methods that elegantly handle large,\nmulti-view datasets.  These methods should retain or even improve\ndetection power over traditional mass-univariate (MU) models such as\nstatistical parametric mapping (SPM) which uses the univariate form of\nthe general linear model (GLM).  Repeatedly applying the univariate GLM (or\nlinear regression) at each voxel leads to loss of detection power due\nto the well-known multiple comparisons problem.\n\nCanonical Correlation Analysis (CCA)~\\cite{hotellingcca} is a\ntraditional multivariate generalization of standard linear regression\n\\cite{kshirsagar}.  CCA inherently avoids the multiple-comparisons penalty\nassociated with MU methods by symmetrically maximizing the correlation\nbetween the full matrices representing two views of the data (here\ndenoted $\\Y$ and $\\X$).  The matrix {$\\X$} might represent a\ntabulation of all demographic data, including genetics, diagnosis,\nbehavioral measures, age, etc. while $\\Y$ may be a matrix of all the\nimaging measurements.  In contrast, traditional univariate models only\nenable the predicted value to be a vector while the predictors may be\na matrix.  Thus, linear regression is a special case of CCA.  In both\ntraditional regression and CCA, the number of predictors, $p$, must be\nfewer than the number of observations, $n$ (subjects in our\nneuroimaging study).  For CCA (or multivariate regression), this\nrestriction holds for both sets of predictors $p$, $q$, contained in\n$\\X, \\Y$.\n\nRecently, sparse (or penalized) canonical covariance analyses (SCCovA)\n~\\cite{parkhomenko,witten,lykou} have been proposed as an\napproximation to CCA specifically for the high dimensional ($p\\gg n$)\nsetting.\\footnote{SCCovA substitutes the identity matrix for\nwithin-view covariance matrices and thus analyze cross-covariance\nstructure, not correlation structure \\cite{cherry}.  Thus, SCCA\n(versus SCCovA) does not depend on how the observations are scaled.}\nThe {\\em sparseness} in penalized methods improves interpretability by\nincluding in the model only the most important variables from the\nlarge set of $p$ (and/or $q$) predictors.  From a medical imaging\nresearcher's perspective, the benefit is that only the most predictive\nvariables (e.g. parts of the brain) will emerge in the results\nprovided by a penalized statistical tool.  Hence, brain regions are\nhighlighted in a way that is similar to SPM.  Furthermore, regions\nselected by SCCovA (or similarly sparse canonical correlation analysis\n(SCCA)) are treated statistically as a collective (or `network') as\nopposed to MU methods which treat each predictor as an independent\nvariable.\n\nDespite prior studies using SCCovA~\\cite{parkhomenko,witten,lykou,Avants2010b}, we are unaware of\nprevious work that studies factoring (``partialling'') out nuisance\nvariables within the penalized CCA framework.  While this problem is\naddressed in the $p < n$ setting by partial canonical correlation\nanalysis (PCCA)\\cite{timm}, no penalized formulation has yet been\nproposed.\n\nThis paper contributes the theory of Partial Sparse CCA (PSCCA) along\nwith a novel and efficient iterative algorithm for PSCCA.  PSCCA (like\nCCA) performs a global multivariate test of the association between\ntwo modalities that quantify a study's subjects while accounting for a\nthird set of nuisance variables.  It generalizes linear regression and\nis inherently, sparsely multivariate in multiple views of the data\nunlike MU and standard support vector machines (SVM).\n\nThe general PSCCA formulation has many applications.  PSCCA may be\napplied to almost any statistical scenario in medical imaging studies\ntraditionally handled by SPM.  PSCCA is able to identify the subset of\nthe brain most correlated with non-imaging variable(s) of interest\n(for instance, a cognitive battery) while factoring out confounding\neffects (age, gender).  Alternatively, we may apply PSCCA to the case\nwhere both views of the data are high-dimensional, for instance, to\nidentify correlations between different imaging modalities\nindependently from covariates such as scanner, gender, etc.  PSCCA\nthus enables complex studies of multiple view data that contains many\nmore variables than observations.\n\nThe rest of the paper is organized as follows: in the next section we\nprovide a brief review of CCA and Sparse CCA. In Section 3, we present\nthe theory behind our novel Partial Sparse CCA (PSCCA) framework and\ndescribe the iterative algorithm for performing PSCCA. In Section 4,\nwe provide experimental results on synthetic and real world\nneuroimaging datasets and we conclude with a brief summary in Section\n5.\n\n\nNeuropsychological measures detect high-level cognitive function that\nemerges from complex, large-scale neural\nnetworks that include multiple gray matter (GM) regions integrated by\nwhite matter (WM) projections. The clinically-validated Philadelphia\nBrief Assessment of Cognition (PBAC) \\cite{Libon2007} examines several\ncognitive domains, including executive functioning/working memory\n(exe), language (lang), visuospatial skills (vs), visual/verbal\nepisodic memory (mem) and social comportment/behavior (behav). We use\nthe open-source sparse canonical correlation analysis for neuroimaging\n(SCCAN) software to {\\bf cross-validate} putative relationships\nbetween the neural substrate and cognition.   We thus relate three quantitative measures: the PBAC, GM density (GMD) derived from T1 MRI, and the fractional anisotropy (FA) of WM derived from DTI.\n\n%What we are doing here ( a few sentences )\n\n%This paper will detail and illustrate our approach to performing\n%neuroimaging studies in the style of traditional formulations but\n%using a new, powerful multivariate pscca.  We highlight in both\n%simulated and real data the advantages and disadvantages of this\n%method.\n\n\n\\section{Brief review: CCA and sparse CCA (SCCA)}\n\\begin{comment}{\nConsider a standard neuroimaging population study with both male and\nfemale subjects between 20 and 40 years of age each of which measured\nvia a series of MRI scans.  Each subject is also designated either\npatient or control.  A standard regression analysis will treat the\nquantitative imaging measurement as the dependent variable ($\\y$) and\nage, gender and diagnosis group as covariates $({\\X})$ where each test\nis performed independently at each voxel.  Detection power is\ncompromised by the multiple-comparisons problem incurred by the number\nof imaging measurements (millions) as well as the confounding\nvariables (age, gender).   It is compromised because one must perform\nadditional statistical corrections to the $p$-values output by MU\nstatistics. If we are using MU models and\nwant to test the whole brain for effects, then\nwe can not do much about the first problem.  For the second problem,\nwe can factor out the effects of these unwanted (confounding)\nvariables by regressing on the residuals ($\\y -\\X\\beta$).\n}\n\\end{comment}\n\n% CCA~\\cite{hotellingcca} is the analog to Principal Component Analysis\n% (PCA) for pairs of matrices. PCA computes the directions of maximum\n% covariance between elements in a single matrix, whereas CCA computes\n% the directions of maximal correlation between a pair of matrices.\n% See~\\cite{taylor:cca} for a general review of CCA along with some\n% representative applications. Unlike PCA, CCA does not depend on how the observations are scaled.\n\nMore specifically, given a set of $n$ paired observation vectors\n$\\{(y_1,x_1),...,(y_n,x_n)\\}$--in our case the two matrices are the\nquantitative imaging measurement ({\\Y}) and age, gender, diagnosis ({\\X}) matrices --we would like to simultaneously find the directions\n${\\bs{\\bs\\phi_{\\Y}}}$ and\n${\\bs{\\bs\\phi_{\\X}}}$ that maximize the correlation of\nthe projections of ${\\Y}$ onto ${\\bs{\\bs\\phi_{\\Y}}}$\nwith the projections of ${\\X}$ onto\n${\\bs{\\bs\\phi_{\\X}}}$. This is expressed as\n\n\\begin{equation}\n\\label{cca1}\n\\rho=\\max_{{\\bs\\phi_Y}, {\\bs\\phi_X}}\n\\frac{{\\bs\\phi_{\\X}^T\\bs\\Sigma_{\\X\\Y}}\\bs\\phi_{\\Y}}{\\sqrt{\\bs\\phi_{\\X}^T\\bs\\Sigma_{\\X\\X}\\bs\\phi_{\\X}}\\sqrt{\\bs\\phi_{\\Y}^T\\bs\\Sigma_{\\Y\\Y}\\bs\\phi_{\\Y}}}\n\\end{equation}\nwhere ${\\bs\\Sigma_{\\X\\X}}$, ${\\bs\\Sigma_{\\Y\\Y}}$ and ${\\bs\\Sigma_{\\X\\Y}}$ are the auto and cross covariance matrices i.e. $\\X^T\\X$, $\\Y^T\\Y$ and $\\X^T\\Y$, respectively. The above objective can also be thought of as maximizing the numerator $\\bs\\phi_{\\X}^T\\bs\\Sigma_{\\X\\Y}\\bs\\phi_{\\Y}$ subject to $\\bs\\phi_{\\X}^T\\bs\\Sigma_{\\X\\X}\\bs\\phi_{\\X} =1$ and $\\bs\\phi_{\\Y}^T\\bs\\Sigma_{\\Y\\Y}\\bs\\phi_{\\Y}=1$\n\nNow, define change of basis as:\n\n\\begin{equation}\n\\label{basisChange}\n\\bs\\psi_{\\X} = \\bs\\Sigma_{\\X\\X}^{1/2}\\bs\\phi_{\\X}, \\;\\;\\;\\;\\;\\;   \\bs\\psi_{\\Y} = \\bs\\Sigma_{\\Y\\Y}^{1/2}\\bs\\phi_{\\Y} \n\\end{equation}\n\nThen, substituting~(\\ref{basisChange}) in~(\\ref{cca1}) we get \n\n\\begin{equation}\n\\label{subs}\n\\rho= \\max_{{\\bs\\psi_{\\Y}}, {\\bs\\psi_{\\X}}} \\frac{\\bs\\psi_{\\X}^T \\bs\\Sigma_{\\X\\X}^{-1/2}\\bs\\Sigma_{\\X\\Y}\\bs\\Sigma_{\\Y\\Y}^{-1/2}\\bs\\psi_Y}{\\|\\bs\\psi_{\\X}\\| \\|\\bs\\psi_{\\Y}\\|}\n\\end{equation}\n\nThe whitening transform is used to convert covariances to correlations\nand also to de-correlate auto-correlation matrices.  In CCA, this\nnormalizes the data such that the optimization can maximize the\ncross-correlation.  The standard whitening transform is defined as\n$\\X_w= \\X\\bs\\Sigma_{\\X\\X}^{-1/2}$ and $\\Y_w=\n\\Y\\bs\\Sigma_{\\Y\\Y}^{-1/2}$.  Applying the whitening transform\nto~(\\ref{subs})\n\n\\begin{equation}\n\\label{simplifiedcca}\nCorr(\\X_w\\bs\\psi_{\\X},\\Y_w\\bs\\psi_{\\Y})=\\rho=\\max_{{\\bs\\psi_{\\Y}}, {\\bs\\psi_{\\X}}} \\frac{\\bs\\psi_{\\X}^T \\bs\\Sigma_{\\X_w\\Y_w}\\bs\\psi_Y}{\\|\\bs\\psi_{\\X}\\| \\|\\bs\\psi_{\\Y}\\|}\n\\end{equation}\nwhere $\\bs\\Sigma_{\\X_w\\Y_w} = \\X_w^T\\Y_w$. \n\nAs mentioned earlier, CCA results in vectors $\\bs\\psi_{\\X}$,\n$\\bs\\psi_{\\Y}$ that are not sparse, and these vectors are not unique\nif $p > n$. In most biomedical imaging applications, $p$ is\nlarge and, one needs to find a linear combination of the\nvariables in $\\X_w$ and $\\Y_w$ that has large correlation but is also\nsparse in the variables that enter the model.  \n\n\\begin{comment}\nSeveral researchers propose sparse formulations of canonical\ncovariance analysis: Witten et al.~\\cite{witten} use penalized matrix\ndecomposition to enforce sparsity; Parkhomenko et\nal.~\\cite{parkhomenko} use soft-max thresholding in an iterative\nalgorithm.  Both papers assume that within-view covariance matrices\nare well-approximated by the identity.  Finally, Lykou and\nWhittaker~\\cite{lykou} propose a LARS~\\cite{lars} style algorithm for\nobtaining sparsity in the loadings.\n\\end{comment}\n\nWhile several researchers propose sparse formulations of canonical\ncovariance analysis \\cite{parkhomenko,witten,lykou}, none of the these\nmethods handle confounding variables---a highly desirable modeling\nproperty for many biomedical and neuroimaging applications.  In the\nnext section, we detail the PSCCA solution to this problem.\n\n\\begin{comment}\nWe formulate a sparse canonical correlation analysis optimization\nwith an embedded step that factors out the effect of nuisance\nvariables.  We also provide an efficient power iteration based\nalgorithm to compute the directions of maximum partial\ncorrelation. Our approach incorporates the normalization constraints\nrequired for correlation (versus covariance) analysis; We call it\nPartial Sparse CCA (PSCCA).\n\\end{comment}\n\n\\section{PSCCA (Partial Sparse Canonical Correlation Analysis)}\nAs described earlier, let $\\X$ be the matrix with columns containing voxels from one set of\nimages of $n$ subjects; $\\Y$ is the matrix with columns containing\nthe second set of measurements from the same $n$ subjects and further\nlet $\\Z$ be the matrix of confounding variables (age, gender, etc.) for\nour neuroimaging problem.  The second set of measurements may be\nvoxels from another imaging modality, scores from a battery of\nneuropsychological tests or a much simpler feature such as a binary\ndiagnosis variable.  Also, let $\\lambda_{\\X}$ and $\\lambda_{\\Y}$ ($\\in\n[0,1]$) (where higher values indicate more sparsity) be the user defined \nparameters which control the sparsity for either set of the canonical\nvariates.  The sparseness parameters can, alternatively, be chosen automatically \nfrom the data so as to maximize the correlation (or likelihood) between the canonical variates.\n\nPCCA~\\cite{timm} finds the correlation between $\\X$ and $\\Y$ after removing (``partialling out'') the linear effect of the confounding variables $\\Z$. \nWe denote the $\\X$ and $\\Y$ matrices with effect of $\\Z$ ``partialled'' out as $\\X^{\\backslash\\Z}$ and $\\Y^{\\backslash\\Z}$. Regressing $\\X$ against $\\Z$, using standard least squares ($\\|\\X -\\Z\\bs\\beta\\|^2$) gives $\\bs\\beta=  \\bs\\Sigma_{\\Z\\Z}^{-1}\\Z^T\\X$. \nThus, the residual\\footnote{Note that $\\X^{\\backslash\\Z}$ is actually what is called the residual $\\X-\\Z\\bs\\beta$ in a least squares regression problem.} can be written as  $\\X^{\\backslash\\Z}=\\X - \\Z\\bs\\Sigma_{\\Z\\Z}^{-1}\\Z^T\\X$. Applying the whitening transform to $\\Z$  as $\\Z_w =\\Z \\Sigma_{\\Z\\Z}^{-1/2}$, we get $\\X^{\\backslash\\Z}=\\X - \\Z_w\\Z_w^T\\X$.\nWe can write similar equations for the residual when $\\Y$ is regressed against $\\Z$.\n \nNow, we can write the complete variance-covariance matrix of the residuals as:\n\n\\begin{eqnarray}\n\\label{matrices}\n\\begin{bmatrix}\n \\bs\\Sigma_{\\X\\X}^{\\backslash \\Z} & \\bs\\Sigma_{\\X\\Y}^{\\backslash \\Z} \\\\\n  \\bs\\Sigma_{\\Y\\X}^{\\backslash \\Z} & \\bs\\Sigma_{\\Y\\Y}^{\\backslash \\Z} \n\\end{bmatrix}\n&=&\n\\begin{bmatrix}\n  \\X^T\\X -\\X^T \\Z_w\\Z_w^T\\X &\\;\\;\\;\\;   \\X^T\\Y -\\X^T \\Z_w\\Z_w^T\\Y\\\\\n  \\Y^T\\X -\\Y^T \\Z_w\\Z_w^T\\X &\\;\\;\\;\\;   \\Y^T\\Y -\\Y^T \\Z_w\\Z_w^T\\Y\n\\end{bmatrix}\n.\n\\end{eqnarray}\n\n\n%The matrices $\\bSigma_{X_wX_w\\backslash Z_w}$ etc. are the variance-covariance matrices of the residual vectors $\\bs r_X$ and $\\bs r_Y$ and are defined as:\n\n%\\begin{eqnarray}\n%\\label{matrices}\n%\\begin{bmatrix}\n% \\bSigma_{11\\backslash 3} & \\bSigma_{12\\backslash 3} \\\\\n%  \\bSigma_{21\\backslash 3} & \\bSigma_{22\\backslash 3} \n%\\end{bmatrix}\n%&=&\n%\\begin{bmatrix}\n% \\bSigma_{11} -\\bSigma_{13}\\bSigma_{33}^{-1}\\bSigma_{31} &\\;\\;\\;\\; \\bSigma_{12} -\\bSigma_{13}\\bSigma_{33}^{-1}\\bSigma_{32}\\\\\n%  \\bSigma_{21} -\\bSigma_{23}\\bSigma_{33}^{-1}\\bSigma_{31} &\\;\\;\\;\\; \\bSigma_{22} -\\bSigma_{23}\\bSigma_{33}^{-1}\\bSigma_{33}\n%\\end{bmatrix}\n%\\end{eqnarray}\n%where we denote $\\X_w \\rightarrow 1$, $\\Y_w \\rightarrow 2$ and $\\Z_w \\rightarrow 3$ as shorthand.\n\n% Equation~(\\ref{matrices}) can easily be extended to handle more than two matrices and also to ``partial'' out the effect of more than one confounding covariate matrices.\n\n\nThe PCCA problem can therefore be written as:\n\n\\begin{equation}\n\\label{pscca}\n\\rho_{PCCA}=\\max_{{\\bs\\phi_{\\Y}}, {\\bs\\phi_{\\X}}} \\frac{\\bs\\phi_{\\X}^T \\bs\\Sigma_{\\X\\Y}^{\\backslash \\Z}\\bs\\phi_Y}{\\sqrt{\\bs\\phi_{\\X}^T\\bs\\Sigma_{\\X\\X}^{\\backslash \\Z}\\bs\\phi_{\\X}}\\sqrt{\\bs\\phi_{\\Y}^T\\bs\\Sigma_{\\Y\\Y}^{\\backslash \\Z}\\bs\\phi_{\\Y}}}\n\\end{equation}\n\n\nChanging the basis as for simple CCA, we get\n\n\\begin{equation}\n\\label{basisChangePSCCA}\n\\bs\\psi_{\\X} = (\\bs\\Sigma_{\\X\\X}^{\\backslash \\Z})^{1/2}\\bs\\phi_{\\X}, \\;\\;\\;\\;\\;\\;   \\bs\\psi_{\\Y} = (\\bs\\Sigma_{\\Y\\Y}^{\\backslash \\Z})^{1/2}\\bs\\phi_{\\Y} \n\\end{equation}\n\nand substituting~(\\ref{basisChangePSCCA}) in~(\\ref{pscca}) gives\n\n\\begin{equation}\n\\label{subsPSCCA}\n\\rho_{PCCA}= \\max_{{\\bs\\psi_{\\Y}}, {\\bs\\psi_{\\X}}} \\frac{\\bs\\psi_{\\X}^T (\\bs\\Sigma_{\\X\\X}^{\\backslash \\Z})^{-1/2}\\bs\\Sigma_{\\X\\Y}(\\bs\\Sigma_{\\Y\\Y}^{\\backslash \\Z})^{-1/2}\\bs\\psi_{\\Y}}{\\|\\bs\\psi_{\\X}\\| \\|\\bs\\psi_{\\Y}\\|} .\n\\end{equation}\n\nAfter some algebraic manipulation we can write the PCCA objective compactly as\n\n\\begin{equation}\n\\label{psccacompact}\n\\rho_{PCCA}=\\max_{{\\bs\\psi_{\\Y}}, {\\bs\\psi_{\\X}}} \\frac{\\bs\\psi_{\\X}^T \\bs\\Sigma_{\\X_w\\Y_w}^{\\backslash \\Z}\\bs\\psi_{\\Y}}{\\|\\bs\\psi_{\\X}\\| \\|\\bs\\psi_{\\Y}\\|}\n\\end{equation}\nwhere $\\X_w=\\X(\\bs\\Sigma_{\\X\\X}^{\\backslash \\Z})^{-1/2}$ and\n$\\Y_w=\\Y(\\bs\\Sigma_{\\Y\\Y}^{\\backslash \\Z})^{-1/2}$. Note the\ndifference in the whitening transform from the one used in simple CCA;\nhere we are using the covariance matrix with $\\Z$ partialled out\nto whiten $\\X$ and $\\Y$.\n\n\nFinally, the above objective after incorporating the user specified $\\ell_1$ sparsity penalties ($\\lambda_{\\X}$ and $\\lambda_{\\Y}$) and under the constraints $\\bs\\psi_{\\X}^T\\bs\\psi_{\\X}=\\bs\\psi_{\\Y}^T\\bs\\psi_{\\Y}=1$ can be written as:\n\n\\begin{equation}\n\\label{psccaSparseConst}\n\\rho_{PSCCA}=\\max_{{\\bs\\psi_{\\Y}}, {\\bs\\psi_{\\X}}} \\{ \\bs\\psi_{\\X}^T \\bs\\Sigma_{\\X_w\\Y_w}^{\\backslash \\Z}\\bs\\psi_{\\Y} - \\lambda_{\\X}\\|\\bs\\psi_{\\X}\\|_1 - \\lambda_{\\Y}\\|\\bs\\psi_{\\Y}\\|_1\\}\n\\end{equation}\nOur optimization strategy for (\\ref{psccaSparseConst}) combines power\niteration and soft thresholding to compute the canonical vectors while\nsatisfying  the sparsity constraints.  The approach, described in the next\nsection, uses an alternating least squares method\n\\cite{golub} extended to include sparsity constraints\n\\cite{cichocki}. \n\n\n\n%\\caption{\\baselineskip 12pt \\small Cartoons illustrating (a) SCCA ;\n%  (b) partial SCCA ; (c) part SCCA.  }\n%\\label{fig:cartoon}\n%\\end{figure}\n\n\\subsection{PSCCA Algorithm}\nFollowing \\cite{golub}, we propose a power iteration based algorithm\nfor PSCCA for the general problem of finding principal eigenvectors of\nthe matrices.  This numerical approach does not require one to ever\nexplicitly form the full $\\X_{w}^T \\Y_{w}$ matrix and is therefore\nappropriate for large datasets where the number of columns in both views may\ncount in the millions or more.  In all steps below, we employ the\npseudoinverse when needed.  In addition, the function $(x)_+$ is equal to $x$ is $x \\geq 0$ and $0$ is $x <0$ and \n \\begin{equation}\nSign(x)= \\begin{cases} -1, & \\mbox{if } x<0 \\\\0, & \\mbox{if } x=0 \\\\1, & \\mbox{if } x>0 \\end{cases}\n\\end{equation}\nNote that positivity or negativity constraints on the\n$\\bs\\psi_{\\X}, \\bs\\psi_{\\Y}$ may be trivially included with a minor\nmodification to Algorithm \\ref{partial-mic}.\n\\vspace{-0.1in}\n\\begin{algorithm}[htdp]\n\\small \\caption{\\bf Computing principal eigenvectors for PSCCA}\n\\label{partial-mic}\n\\begin{algorithmic}[1]\n\\STATE Apply the whitening transformation to {\\Z} to get $\\Z_{w}$.\n\\STATE Compute $\\X^{\\backslash \\Z}$ and $\\Y^{\\backslash \\Z}$ and the whitened matrices $\\X_{w}$ and $\\Y_{w}$. \n\\STATE Select the (fractional) sparsity parameters $\\lambda_{\\X}$ and $\\lambda_{\\Y}$\n\\STATE Randomly initialize $\\bs \\psi_{\\X}^0$ and $\\bs \\psi_{\\Y}^0$ ($\\sim \\mathcal{N}(0,1)$) and set $k=0$.\n\n\\WHILE {$\\Delta$ Corr($\\bs X_w \\bs \\psi_{\\X}^{k+1}$, $\\bs Y_w \\bs \\psi_{\\Y}^{k+1}$) $<$ $\\epsilon$}\n\\STATE Compute  $\\bs \\psi_{\\X}^{k+1}= {\\X_w}^T {\\Y_w} \\bs \\psi_{\\Y}^{k} -  {\\X_w}^T  {\\Z_w} {\\Z_w}^T {\\Y_w} \\bs \\psi_{\\Y}^{k}$\n\\STATE Soft-Max Sparseness:  $\\bs \\psi_{\\X}^{k+1} \\leftarrow (\\|\\bs \\psi_{\\X}^{k+1}\\|  - max(\\bs \\psi_{\\X}^{k+1})*\\lambda_{\\X})_+ Sign(\\bs \\psi_{\\X}^{k+1})$\n\\STATE Normalize: $\\bs \\psi_{\\X}^{k+1} \\leftarrow \\frac{\\bs \\psi_{\\X}^{k+1}}{\\|\\bs \\psi_{\\X}^{k+1}\\|}$\\\\\n//Repeat Same Procedure for $\\bs \\psi_{\\Y}$ \\\\\n\\STATE Compute  $\\bs \\psi_{\\Y}^{k+1}= {\\Y_w}^T {\\X_w} \\bs \\psi_{\\X}^{k+1} -  {\\Y_w}^T  {\\Z_w} {\\Z_w}^T {\\X_w} \\bs \\psi_{\\X}^{k+1}$\n\\STATE Soft-Max Sparseness: $\\bs \\psi_{\\Y}^{k+1} \\leftarrow (\\|\\bs \\psi_{\\Y}^{k+1}\\|  - max(\\bs \\psi_{\\Y}^{k+1})*\\lambda_{\\Y})_+ Sign(\\bs \\psi_{\\Y}^{k+1})$\n\\STATE Normalize: $\\bs \\psi_{\\Y}^{k+1} \\leftarrow \\frac{\\bs \\psi_{\\Y}^{k+1}}{\\|\\bs \\psi_{\\Y}^{k+1}\\|}$\n\\STATE k $\\leftarrow$ k+1\n\\ENDWHILE\n\\end{algorithmic}\n\\end{algorithm}\nWe use permutation testing on $\\X$, $\\Y$ to assess significance where\nthe test statistic is the partial correlation between the two main views.\n\n%\\noindent{}\n%\\begin{description}\n%\\item [Whiten:]Apply the whitening transformation to {\\X}, {\\Y}, {\\Z}.\n%    VectorType temp=q*w_q;\n%    wpnew=p.transpose()*( temp - this->m_MatrixRRt*temp ); \n%\\item [Begin Loop:]for power iteration. \n%\\item [~~View 1:]Compute  $\\x= {\\X}^T {\\Y} \\y -  {\\X}^T  {\\Z} {\\Z}^T {\\Y} \\y$.\n%\\item [~~Soft-Max Sparseness \\& Normalization $\\x$:] Enforce $\\x$\n%  sparseness and set $\\x \\leftarrow \\frac{\\x}{\\|\\x\\|}$.\n%\\item [~~View 2:]Compute  $\\y= {\\Y}^T {\\X} \\x -  {\\Y}^T  {\\Z} {\\Z}^T\n%  {\\X} \\x$\n%\\item [~~Soft-Max Sparseness \\& Normalization $\\y$:] As in $\\x$ step.\n%\\item [~~CC:]Compute $Corr( {\\X} \\x ,  {\\Y} \\y )$.\n%\\item [End loop:]Check the correlation and stop when converged.\n%\\end{description}\n \n%For multiple eigenvectors, use the Lanczos algorithm.\n\\begin{comment}\n\\subsection{Assessing significance}\nA well-known difficulty with neuroimaging studies, particularly when\nsample sizes are small, is the potential for the methods to find biologically implausible structure in the data.  While the\npotential for this problem can never be fully eliminated, we seek to\nminimize the confound by using an empirical approach to significance\ntesting based on permutations:\n\\begin{enumerate}\n\\item Compute the true PSCCA correlation~$t=$PSCCA$(\\X,\\Y,\\Z)$.  \n\\item Initialize $p=0$. \n\\item {\\bf For} $N$ simulations {\\bf do }\n\\item ~~~Permute the rows of $\\X$, $\\Y$ to get $\\X_p, \\Y_p$.\n\\item ~~~Compute $t_p=$ PSCCA$(\\X_p,\\Y_p,\\Z)$.\n\\item ~~~if $t_p > t , ~~p=p+1$.\n\\item {\\bf done }\n\\item {\\bf Return} the p-value, $p/N$. \n\\end{enumerate}\nThe number of simulations should be selected to provide a reasonable\nsampling of the permutation space.  \n\\end{comment}\n\n\\section{Results}\nThe code for the PSCCAN implementation, the simulation study and the\nneuroimaging study will be made available at publication time. \n\\subsection{Simulations} Define a ``true'' linear signal vector with\n$n$ entries, ${\\bs v}$, such that the value of each entry is ${\\bs\nv}_i=i/n$ where $i$ indexes the vector.  A second signal is a vector drawn from a zero mean unit\nvariance Gaussian distribution, ${\\bs g_x}$ with $p$ entries.  The\nfirst view is then $\\X ={\\bs v}^T {\\bs g_x}$ and we similarly generate\n$\\Y $ with $n \\times q$ entries.  We optionally add noise to both\nviews.  In 100 low-noise simulations, SCCA produces a significant\nassociation.  However, when we use $\\Z = {\\bs v} + $ {\\em noise} as a\ncovariate in PSCCA on $\\X$ and $\\Y$, then no significant association\nexists.  Both results are as expected and provide a sanity check on\nour theory and implementation.  The second experimental validation of\nour implementation and theory generates $\\X$ and $\\Y$ where the first\n$p/2, q/2$ columns are derived from ${\\bs v}$.  The second $p/2, q/2$\ncolumns in $\\X, \\Y$ are derived from a different ``true'' signal (${\\bs v}_2$) with\na less strong linear relationship than in the first half of the\nmatrices.  Thus, when we use SCCA with sparseness\n$\\lambda_{\\X}=\\lambda_{\\Y}=0.25$, the first half of the matrix is\nselected.  PSCCA selects the second half of the matrix when $\\Z$ is\nused as confounding covariate.  Both are significant across permutations.  Due to\nnoise, in some simulations, a few entries from the first half of the\nmatrix may enter the model with low weight.  If we add a column containing signal derived from ${\\bs\n  v}_2$ to $\\Z$ then, as predicted, PSCCA results become insignificant. Figure~\\ref{fig:sim}\nshows the vectors $\\bs\\phi_{\\X}$ selected by SCCA and PSCCA on the\nsame input data where PSCCA uses $\\Z$ (derived from ${\\bs v}$ alone)\nas confounding covariate. \n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=120mm]{simulation_result_mix.pdf} \n\\end{center}\n\\vspace{-0.2in}\n\\caption{The black hollow circles show the non-zero entries in\n  $\\bs\\phi_{\\X}$ that are selected by SCCA, that is, the value of the vector\n  $\\bs\\phi_{\\X}$.  The red full circles show the non-zero entries in\n  the vector $\\bs\\phi_{\\X}$ that are selected by PSCCA.  The $\\Z$ signal factors\n  out the confounding signal in the first half of the matrix leaving\n  the second signal of interest in the second half to be the source of\nthe significant association.}\n\\label{fig:sim}\n\\end{figure}\n% This analysis can be achieved by simulating imaging data and two other\n% views (age, cognition) in such a way that the age is the true hidden variable that\n% generates both cognition and imaging measurements.  PSCCA should then\n% detect an insignificant association between cognition and imaging when\n% age is used as the confounding variable.  Similarly, PSCCA should\n% detect a significant association between age and imaging when\n% cognition is a confounding variable.   \n\\subsection{Comparison of regression and PSCCA on OASIS data}\nOur first evaluation on real data employs PSCCA as a form of\nmultivariate regression between imaging, diagnosis and nuisance variables.  \nWe employ a subset of the freely available OASIS dataset to compare\nPSCCA to mass-univariate linear regression.  This subset of the OASIS\ndata contains elderly subjects (n=38) in addition to subjects with\nAlzheimer's disease (n=31) of both genders (39 F, 30 M) and with ages\nthat range between 62 and 98 years.  Our evaluation criterion compares\nboth methods' power to detect the known anatomical distribution of\nAD-related atrophy in gray matter (hippocampus, cuneus, temporal lobe)\n\\cite{Avants2010b} where gray matter was segmented and normalized by using standard\nopen source software.  We use the whole brain, in template space, as region of interest in order to\nchallenge the power of the MU method relative to the\nsingle test performed by multivariate PSCCA.  We assume that the\nresearcher has pre-selected the sparseness parameter for the study.\nWe choose $\\lambda$ (sparsity parameter) for the gray matter voxels such that 10\\% of the\nROI (contained in the $\\X$ matrix) will be selected by PSCCA.  The\n$\\Y$ matrix, in this case, is the diagnosis vector that defines\nwhether a subject is control or patient.  The nuisance matrix $\\Z$\ncontains age and gender variables.  We run both the MU\nstatistics (via the {\\bf R} program) and our own independently\ndeveloped PSCCA implementation (C++ based, BSD license, open-source)\non identical input data.  Using false discovery rate (FDR) correction\non the regression-based p-values for diagnosis, we find that the\nminimum q-value is 0.183, thus insignificant after correction.  In\ncontrast, PSCCA shows significant effects at the $p=0.041$ level,\n10000 permutations.  We visualize the regions that emerge from PSCCA\nby overlaying the first canonical vector $\\bs \\psi_{\\X}$ on the brain.\nFigure~\\ref{fig:comp} compares the PSCCA output with the regression\nresults overlaid on the brain at the level of $p=0.01$ uncorrected.\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=120mm]{figs/MUvPSCCAN.pdf} \n% \\includegraphics[width=50mm]{Pvalue_f_of_sparsenss_and_corr.pdf} \n\\end{center}\n\\vspace{-0.1in}\n\\caption{PSCCAN (right) versus mass-univariate uncorrected statistics\n(left).  Both methods reveal similar areas of the brain.  However, the\nmass-univariate results cannot be considered significant (after FDR\ncorrection) due to the multiple comparisons problem.  It is possible\nthat another correction method would retain some of the mass-univariate\neffects but we choose FDR because it is standard and only moderately\nconservative.  We show, at right, the relationship of estimated\nsignificance to variations in the sparseness parameter (for the image\nvoxel matrix $\\X$) and PSCCA correlation.  The significant region is\noutlined in a dashed box.  In a real study, one would only use the\npre-selected sparseness parameter.}\n\\label{fig:comp}\n\\end{figure}\n\\subsection{PBAC}\n\\paragraph{Description of cohort: }\n104 subjects had complete cognitive evaluations as well as Siemens\n3.0T T1 and DTI collected at the University of Pennsylvania. The\ncohort contained subjects diagnosed with Alzheimer's disease (AD;\nn=23), behavioral- variant frontotemporal degeneration (bvFTD; n=31),\nprimary progressive aphasia (PPA) variants of FTD (n=24), 17 with\nextrapyramidal motor disorders, and 9 elderly controls. We use\nmultiple different disorders only to obtain variance in cognition but\ndo not include clinical diagnosis in subsequent analyses. We\nnormalized and segmented \\cite{Avants2011a} the DT and T1 images using\nthe ITK-based open-source ANTs \\cite{Avants2011} and Pipedream software.\n\n\\paragraph{Part 1-imaging \\& cognition:} SCCAN identifies, for each PBAC domain, uniquely related WM regions. We perform the same type of study, independently, using GMD. The output from each run of SCCAN is the subset of WM / GM voxels that (as a set) relate most significantly to the cognitive domain of interest (e.g. language).\n\\newline\n\\newline\n We found significant associations between GM and each domain of\ncognition consistent with putative neuroanatomical substrates at the\np<0.001 level. FA in WM was related to exec, soc, vs (p<0.05), weakly\nrelated to memory (p<0.072) and unrelated to lang (p<0.89).\n\\newline\n\\paragraph{Part 2:}~We directly tested relationships between\n cognition-specific GMD and FA voxels derived from Part A. For\n example, we test if language-defined GMD voxels relate significantly\n to language-defined FA voxels, where SCCAN treats the voxels as a\n set.\n\\newline\n\\newline\n FA regions and GM regions were strongly related within each cognitive\ndomain (p<0.001) except for language where the relation was modest\n(p<0.05). Fig 1 and 2 show the anatomic distribution of the\ncognition-specific regions for both WM and GM for each cognitive\ndomain. Fig 3 shows the behav-based GMD and FA scatterplot.\n\\newline\n\\paragraph{Highlights:} Behav relates strongly to medial orbitofrontal cortex GM and genu in WM. Vs to occipital GM (cuneus) and occipital projections. Exec to insula, dorsolateral prefrontal, lateral orbitofrontal, and bilateral hippocampus GM regions and WM projections in the superior frontal lobe and the anterior callosum. Mem to GM insula, cuneus and posterior superior temporal gyrus, and WM fornix and superior longitudinal fasciculus.\n\n\\begin{figure}\n\\centering\n\\mbox{\\subfigure{\n    \\includegraphics[height=1.5in]{figs/gm}\n}\n\\quad\n\\subfigure{\n    \\includegraphics[height=1.5in]{figs/gm}\n}\n}\n\\caption{In this figure, we illustrate two dimensionality-reduction applications of the same\n  class of the multivariate correlation-based method, sparse canonical\n  correlation analysis (SCCA).  At left, {\\bf we use SCCA as a direct tool for quantifying significant\n  associations between cortical thickness and five neuropsychological\n  batteries}: social behavior (apathy/disinhibition), executive\n  function, language skill, visuospatial skill and memory.  SCCA draws out a network of\n  voxels that, as a set, correlates optimally with each domain and\n  the location of these networks  largely confirm putative brain-behavior\n  relationships.  In a second study, right, {\\bf we used SCCA as a feature\n  selection tool to identify diagnosis-relevant imaging signatures of ADHD} from a large dataset of\n  structural and resting state fMRI taken from ADHD and control\n  subjects. The figure at right shows the features from the rsf MRI that are most relevant to ADHD-control classification and\nimprove performance by a factor of almost 10\\% over using clinical variables\nalone.  Lateral inferior prefrontal cortex, middle frontal gyrus and thalamus\nconnectivity with anterior cingulate were most important.} \\label{fig:fig3}\n\\end{figure}\n\n\\section{Discussion and Conclusion}\nIn this paper we proposed a new statistical tool that is\nideal for multivariate imaging studies. \n% We presented the theory behind\n% PSCCA and also provided a highly efficient algorithm for solving the\n% optimization problem. Our formulation also has two user defined\n% sparsity parameters $\\lambda_{\\X}$ and $\\lambda_{\\Y}$ which the\n% researcher can chose based on domain knowledge or select automatically\n% by optimizing on a held out development set. \nResults on synthetic and\nreal world data (OASIS) further corroborate our hypothesis that PSCCA\nis able to increase detection power in the presence of covariates and\nextract biologically plausible, multivariate patterns from neuroimaging\ndata.  Specifically, PSCCA reveals significant patterns of difference\nbetween elderly and AD subjects that are within brain regions known to\nbe affected by Alzheimer's tauopathy.  Although the MU model fails to reveal\nsignificant effects, there is notable similarity between regions selected by PSCCA and\nthose voxels in the brain that had uncorrected $p$-value $< 0.01$.  %This study has limitations.   \nIn our experiments we only use the\nprimary eigenvector from PSCCA;\nFuture work will analyze the effect of including additional\neigenvectors and will seek to further investigate alternatives for\nassessing PSCCA significance in interpretable ways. Finally, as in standard correlation, one should take care to visualize PSCCA results to investigate the potential impact of outliers. \n\n% {\\bf FINISH}\n% despite the fact that we show similar biologically plausible patterns to univariate\n% regression, though with greater power, \n% difficulty of interpretation remains ....  \n\n\n {\\bf Our results confirm putative brain-behavior associations.}  At\n the least, they suggest unique relationships between cognitive variation\n and large-scale GM-WM networks that vary uniquely with cognitive domain. Furthermore,\n these results suggest that SCCAN may enhance detection power over\n traditional univariate approaches.  In particular, the significance\n of GM and cognition relationships ($\\approx$  p<0.001) far exceeds those of the FA\n cognition relationships ($\\approx$ p<0.05).  Despite this, there is\n significant association between FA-cognition identified voxels and GM-cognition\n identified voxels ($\\approx$  p<0.001).  \n\n\n%\\noindent{\\bf Acknowledgment}\n% This work is supported by Grant XXX \n% 1R01EB006266-01 \n% from the ...\n%National Institute Of Biomedical Imaging and Bioengineering and administered through the UCLA Center for Computational Biology.\n\\bibliographystyle{IEEEbib}\n\\bibliography{./cca}\n\n\\end{document}\n\n\n\\text{argmax}( \\x,\\y) :\n~\\text{Corr}~( \\X \\x , \\Y \\y) - \\lambda_\\x \\| \\x \\|_1 - \\lambda_\\y \\|  \\y  \\|_1 , \n\\end{equation} \nwhere $\\X$ is a matrix with columns containing voxels from one set of\nimages of $n$ subjects, \nand $\\Y$ is a matrix with columns containing voxels from the second\nset of images from the same $n$ subjects. \nCorr computes Pearson correlation and the\n$\\lambda$ are inversely related to the sparseness costs, $C$.  %\\vspace{-0.2in}\n\nThe covariance formulation of SCCA .... \n\nLet's compute the canonical correlation between two matrices where we\nassume the matrices have been normalized and, as such, CCA computes\n$$ \\rho = \\frac{ x \\X^T \\Y y  }{ \\sqrt{x  \\X^T \\X x}\\sqrt{x  \\Y^T \\Y y}  } $$.  Now, we change bases by\nusing the whitening transform.  \nRedefine $\\x =  ... $ Then, $\\X \\leftarrow \\X \\Sigma^{-1/2}_{XX}$ (same for $\\Y$) and\n$$ \\rho = \\frac{ x \\X_w^T \\Y_w \\y  }{ ||x|| || y||} $$.\n$$\\rho = \\frac{c^T \\Sigma^{-1/2}_{XX} \\Sigma_{XY}\n  \\Sigma^{-1/2}_{YY}}{\\sqrt{c^Tc}\\sqrt{d^Td}}$$\n\nif matrices are whitened, then $\\X \\leftarrow \\X \\Sigma^{-1/2}_{XX}$\n$$ \\rho = \\frac{c^T \\Sigma_{XY}  d }{\\sqrt{c^Tc}\\sqrt{d^Td}}$$\n\nThe partial SCCA formulation will maximize \n\n\nGenerally, SCCA depends upon univariate models to\nfactor out the effects of confounding variables.  In this paper we present a\nnovel algorithm for computing partial sparse canonical correlation\nanalysis (PSCCA) and factor (``partial'') out the effect of unwanted covariates. \n\nSparse canonical correlation analysis (SCCA) is a powerful,\nmultivariate statistical tool for making unbiased inferences about the\nrelationship between different types of measurements taken on the same\npopulation.\n", "meta": {"hexsha": "c23e42cfdf8849cc5a688f2a049114aad68466a1", "size": 37979, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/psccan.tex", "max_stars_repo_name": "stnava/sccan", "max_stars_repo_head_hexsha": "2e9241b13c319a3adbbeab5b61e7ddfbf228bd5a", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2015-08-06T03:40:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-11T11:48:20.000Z", "max_issues_repo_path": "doc/psccan.tex", "max_issues_repo_name": "stnava/sccan", "max_issues_repo_head_hexsha": "2e9241b13c319a3adbbeab5b61e7ddfbf228bd5a", "max_issues_repo_licenses": ["FSFAP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/psccan.tex", "max_forks_repo_name": "stnava/sccan", "max_forks_repo_head_hexsha": "2e9241b13c319a3adbbeab5b61e7ddfbf228bd5a", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-01-22T18:49:53.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-03T09:31:01.000Z", "avg_line_length": 53.6426553672, "max_line_length": 443, "alphanum_fraction": 0.7454382685, "num_tokens": 10970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073507867328, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.32424668419917785}}
{"text": "% Created 2015-06-13 Sat 17:49\n\\documentclass[integrals, nointegrals, article, 12pt, a4paper]{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage[T1]{fontenc}\n\\usepackage{fixltx2e}\n\\usepackage{wrapfig}\n\\usepackage{soul}\n\\usepackage{textcomp}\n\\usepackage{marvosym}\n\\usepackage{wasysym}\n\\usepackage{latexsym}\n\\usepackage{amssymb}\n\\usepackage{hyperref}\n\\usepackage{graphicx}\n\\usepackage{longtable}\n\\usepackage{float}\n\\usepackage{geometry}\n\\usepackage{amsmath}\n\\usepackage{clrscode3e}\n\\usepackage{palatino}\n\\usepackage{euler}\n\\setcounter{secnumdepth}{2}\n\\geometry{a4paper, textwidth=6.5in, textheight=10in, marginparsep=7pt, marginparwidth=.6in}\n\\usepackage{amsthm}\n\\newtheorem{theorem}{Theorem}[section]\n\\newtheorem{lemma}[theorem]{Lemma}\n\\date{}\n\\title{Cache Optimized error correction.}\n\\hypersetup{\n  pdfkeywords={},\n  pdfsubject={},\n  pdfcreator={Emacs 24.5.1 (Org mode 8.2.8)}}\n\\begin{document}\n\n\\maketitle\n\n\\section{Algorithm}\n\\label{sec-1}\nWe assume that the index of array and the level number starts with\n$0$.  We say a search tree \\emph{complete}, if at every level $i$ of the\ntree has exactly $m(m+1)^{i}$ elements. We also assume $n$ is a\nmultiple of $m$ and $m \\geq 3$.\n\n\\begin{codebox}\n\\Procname{$\\proc{Cache-Aware-Search-Tree}(X, m)$}\n\\zi \\kw{Input : } List of Elements, $X$ ; No. of Elements in a cache line, $m$\n\\zi \\kw{Output : } Cache-Aware Search Tree of the list $X$ of size $n$, $CT$\n\\li $l \\gets \\lceil \\log_{m+1} (n+1) \\rceil$\n\\li $\\proc{Init-Global}(m, l)$\n\\li Initialize $CT$ as a vector of size $n$.\n\\li $i \\gets 0$; $CT[0] \\gets 0$; $CT[1] \\gets l$; $CT[m - 1] \\gets n - 1$\n\\li $l_{ptr} \\gets 0$ \\Comment Pointer to the last inserted node\n\\li $c_{ptr} \\gets 0$ \\Comment Pointer to the current node\n\\li \\While $i < n$\n    \\Do\n\\zi      \\Comment $[x,y]$ range of indices covered by this subtree.\n\\li      $x \\gets CT[c_{ptr}]$\n\\li      $y \\gets CT[c_{ptr} + m - 1]$\n\\zi      \\Comment $k$ is no. levels of current subtree including root.\n\\li      $k \\gets CT[c_{ptr} + 1]$\n\\li      $d \\gets y - x + 1$\n\\li      \\If $d == m$\n         \\Then\n\\li\n\\li      $ST \\gets \\proc{Subtree-Size}(y - x + 1, k)$\n\\li      $y \\gets x$\n\\li      \\For $j \\gets 0 \\To m - 1$ \\Comment Update entries for current node.\n         \\Do\n\\li           $y \\gets y + ST[j]$\n\\li           $CT[c_{ptr} + j] \\gets y$\n         \\End\n\\li      \\For $j \\gets 0 \\To m$ \\Comment Insert indices for sub-trees.\n         \\Do\n\\li           \\If $ST[j] > 0$\n              \\Do\n\\li               $y \\gets x + ST[j]$\n\\li               $l_{ptr} \\gets l_{ptr} + m$\n\\li               $CT[l_{ptr}] \\gets x$\n\\li               $CT[l_{ptr} + 1] \\gets k - 1$\n\\li               $CT[l_{ptr} + m - 1] \\gets y - 1$\n\\li               $x \\gets y + 1$\n              \\End\n        \\End\n\\li     $i = i + m$; $c_{ptr} = c_{ptr} + m$\n    \\End\n\\li \\Return $CT$\n\\end{codebox}\n\n\\begin{codebox}\n\\Procname{$\\proc{Init-Global}(m, l)$}\n\\zi $A_1, A_2$ are global arrays of size $l$ each.\n\\li Initialize $A_1$ with $A_1[i] = m(m+1)^{i}$.\n\\zi \\quad $A_1[i]$ is the number of elements at level $i$ of a\n    complete $m$-ary search tree.\n\\li Initialize $A_2$ with $A_2[i] = \\sum_{j = 0}^i A_1[j]$.\n\\zi \\quad $A_2[i]$ is the total number of elements at upto\n    level $i$ of a complete $m$-ary search tree.\n\\end{codebox}\n\n\\begin{codebox}\n\\Procname{$\\proc{Subtree-Size}(d,k)$}\n\\zi \\kw{Input : } No. of elements with in this subtree, $d$\n\\zi \\kw{Input : } No. of Levels in the current subtree incl. root, $k$\n\\zi \\kw{Output : } Size of each of the $m+1$ subtree sizes, $ST$\n\\li \\If $d == m$ \\Comment Last row : All zeroes\n\\li \\Do Initialize $ST$ to $m+1$ zeros.\n\\li     \\Return $ST$ \\End\n\\li $d_k \\gets d - A_2[k - 2]$ \\Comment No. of elements in the last level\n\\li $q = d_k / A_1[k - 2]$\n\\li $r = d_k \\% A_1[k - 2]$\n\\zi \\Comment $LS$, No. elements in last row of $m+1$ sub-trees.\n\\li \\For $j \\gets 0 \\To m$\n\\li \\Do \\If $j < q$\n\\li        \\Then $LS[j] \\gets A_1[k - 2]$\n\\li      \\ElseIf $j > q$\n\\li        \\Then $LS[j] \\gets 0$\n\\li      \\Else\n\\li         $LS[j] \\gets r$ \\End\n    \\End\n\\zi \\Comment $ST$, Size of $m+1$ sub-trees\n\\li \\For $j \\gets 0 \\To m$\n\\li \\Do $ST[j] = LS[j] + A_2[k-2]$ \\End\n\\li \\Return $ST$\n\\end{codebox}\n\n\n\\section{Experimental Results}\n\\label{sec-2}\n\nIn order to demonstate how the layout datastructures behave with real\ndatasets, we used the datasets listed in table\n\\ref{tab:datasets}. Datasets are the same as that one used in (TODO: Refer\nparallel error correction paper) and are available from the NCBI Short\nRead Archive.\n\n\\begin{table}[htb]\n\\caption{\\label{tab:datasets}Datasets for experimental validation}\n\\centering\n\\begin{tabular}{llrrr}\n\\hline\nDataset & Genome & No. of Reads & Read Length & Coverage\\\\\n &  & (millions) & (base pairs) & \\\\\n\\hline\nD2 & \\emph{E.Coli} & 8.9 & 101 & 193x\\\\\nD3A & \\emph{Droso. M} & 37.9 & 95 & 30x\\\\\nD3B & \\emph{Droso. M} & 41.5 & 35 & 12x\\\\\nD3C & \\emph{Droso. M} & 18.8 & 75 & 12x\\\\\n\\hline\n\\end{tabular}\n\\end{table}\n\n\nDatasets D3A (SRX023452), D3B (SRX001651) and D3C(SRX001652) are\ncombined into a single dataset D3, having 98.2 million\nreads. D2(SRR034501$\\backslash$$_{\\text{1}}$) and D3 are used in all our experiments. Since we\nuse the same parameters as used in (TODO: refer to the error correction\npaper), we don't evaluate the quality of error correction. We only\nevaluate the runtime performace for error correction runs of the\ndatasets D2 and D3 with the three different -- sorted order layout,\ncache aware layout and cache oblivious layout.\n\n\n\n\\section{Results}\n\\label{sec-3}\n\\subsection{Kmer Table Sizes}\n\\label{sec-3-1}\n\n\\begin{table}[htb]\n\\caption{\\label{tab:spectrum}$k$-mer spectrum and tile spectrum size}\n\\centering\n\\begin{tabular}{lrr}\n\\hline\nDataset & Kmer Table Size & Tile Table Size\\\\\n\\hline\nD2 & 1699218 & 8830856\\\\\nD3 & 6092949 & 240045877\\\\\n\\hline\n\\end{tabular}\n\\end{table}\n\n\n\\subsection{Dataset D2 (Hamming Distance 1)}\n\\label{sec-3-2}\n\\subsubsection{Summary}\n\\label{sec-3-2-1}\n\n\\begin{table}[htb]\n\\caption{\\label{tab:d2h1run}Results for dataset $D2$ with $h = 1$}\n\\centering\n\\begin{tabular}{rrrrrrr}\n\\hline\n & k-Spectrum & Error & Cache Aware &  & Cache Oblivious & \\\\\nProcs & Construction & Correction & Error Correction & Speedup & Error Correction & Speedup\\\\\n & Time (seconds) & Time (seconds) & Time (seconds) &  & Time (seconds) & \\\\\n\\hline\n2 & 74.94 & 1326.61 & 739.76 & 1.79x & 858.30 & 1.54x\\\\\n4 & 42.61 & 761.65 & 451.68 & 1.68x & 475.62 & 1.60x\\\\\n8 & 22.66 & 335.53 & 244.57 & 1.37x & 249.76 & 1.34x\\\\\n16 & 13.12 & 189.28 & 133.60 & 1.41x & 130.01 & 1.44x\\\\\n32 & 7.71 & 98.92 & 71.72 & 1.38x & 69.10 & 1.43x\\\\\n64 & 4.90 & 52.46 & 36.42 & 1.46x & 35.79 & 1.46x\\\\\n128 & 4.24 & 28.02 & 19.71 & 1.42x & 19.23 & 1.45x\\\\\n256 & 5.90 & 14.25 & 10.40 & 1.37x & 10.06 & 1.42x\\\\\n512 & 13.72 & 7.65 & 5.60 & 1.37x & 5.54 & 1.38x\\\\\n\\hline\n\\end{tabular}\n\\end{table}\n\n\n\n\\subsubsection{Default run results}\n\\label{sec-3-2-2}\n\n\\begin{center}\n\\begin{tabular}{rrrr}\n\\hline\nProcs & Construction & Error Correction & Total\\\\\n & Time (seconds) & Time (seconds) & Time (seconds)\\\\\n\\hline\n2 & 74.94 & 1326.61 & 1406.62\\\\\n4 & 42.61 & 761.65 & 808.91\\\\\n8 & 22.66 & 335.53 & 359.56\\\\\n16 & 13.12 & 189.28 & 203.14\\\\\n32 & 7.71 & 98.92 & 107.12\\\\\n64 & 4.90 & 52.46 & 57.59\\\\\n128 & 4.24 & 28.02 & 32.40\\\\\n256 & 5.90 & 14.25 & 20.37\\\\\n512 & 13.72 & 7.65 & 22.10\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\n\n\\subsubsection{Cache Aware results}\n\\label{sec-3-2-3}\n\n\\begin{center}\n\\begin{tabular}{rrrr}\n\\hline\nProcs & Construction & Error Correction & Total\\\\\n & Time (seconds) & Time (seconds) & Time (seconds)\\\\\n\\hline\n2 & 68.32 & 739.76 & 813.68\\\\\n4 & 37.69 & 451.68 & 491.88\\\\\n8 & 22.65 & 244.57 & 268.59\\\\\n16 & 12.12 & 133.60 & 147.47\\\\\n32 & 7.60 & 71.72 & 80.82\\\\\n64 & 4.90 & 36.42 & 41.51\\\\\n128 & 4.10 & 19.71 & 24.77\\\\\n256 & 5.80 & 10.40 & 16.80\\\\\n512 & 13.10 & 5.60 & 19.52\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\n\\subsubsection{Cache Oblivious results}\n\\label{sec-3-2-4}\n\n\\begin{center}\n\\begin{tabular}{rrrr}\n\\hline\nProcs & Construction & Error Correction & Total\\\\\n & Time (seconds) & Time (seconds) & Time (seconds)\\\\\n\\hline\n2 & 75.24 & 858.30 & 948.21\\\\\n4 & 42.07 & 475.62 & 520.45\\\\\n8 & 23.65 & 249.76 & 274.82\\\\\n16 & 13.14 & 130.01 & 147.21\\\\\n32 & 7.65 & 69.10 & 77.21\\\\\n64 & 4.72 & 35.79 & 40.83\\\\\n128 & 4.38 & 19.23 & 23.14\\\\\n256 & 6.36 & 10.06 & 16.49\\\\\n512 & 13.34 & 5.54 & 19.61\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\n\\subsection{Dataset D2 (Hamming Distance = 2)}\n\\label{sec-3-3}\n\n\\subsubsection{Summary}\n\\label{sec-3-3-1}\n\n\\begin{table}[htb]\n\\caption{\\label{tab:d2h1run}Results for dataset $D2$ with $h = 1$}\n\\centering\n\\begin{tabular}{rrrrrrr}\n\\hline\n & k-Spectrum & Error & Cache Aware &  & Cache Oblivious & \\\\\nProcs & Construction & Correction & Error Correction & Speedup & Error Correction & Speedup\\\\\n & Time (seconds) & Time (seconds) & Time (seconds) &  & Time (seconds) & \\\\\n\\hline\n64 & 4.79 & 5820.63 & 2430.41 & 2.39 & 3430.27 & 1.69\\\\\n128 & 4.06 & 2868.85 & 1315.91 & 2.18 & 1819.92 & 1.57\\\\\n256 & 6.19 & 1627.04 & 740.60 & 2.19 & 1042.59 & 1.56\\\\\n512 & 13.06 & 835.94 & 380.16 & 2.19 & 537.66 & 1.55\\\\\n\\hline\n\\end{tabular}\n\\end{table}\n\n\\subsubsection{Default run results}\n\\label{sec-3-3-2}\n\n\\begin{center}\n\\begin{tabular}{rrrr}\n\\hline\nProcs & Construction & Error Correction & Total\\\\\n & Time (seconds) & Time (seconds) & Time (seconds)\\\\\n\\hline\n64 & 4.79 & 5820.63 & 5287.87\\\\\n128 & 4.06 & 2868.85 & 2874.39\\\\\n256 & 6.19 & 1627.04 & 1693.27\\\\\n512 & 13.06 & 835.94 & 908.36\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\n\\subsubsection{Cache Aware results}\n\\label{sec-3-3-3}\n\n\\begin{center}\n\\begin{tabular}{rrrr}\n\\hline\nProcs & Construction & Error Correction & Total\\\\\n & Time (seconds) & Time (seconds) & Time (seconds)\\\\\n\\hline\n64 & 4.83 & 2430.41 & 2495.45\\\\\n128 & 4.10 & 1315.91 & 1321.59\\\\\n256 & 5.86 & 740.60 & 747.63\\\\\n512 & 14.1 & 380.16 & 394.61\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\n\\subsubsection{Cache Oblivious results}\n\\label{sec-3-3-4}\n\n\\begin{center}\n\\begin{tabular}{rrrr}\n\\hline\nProcs & Construction & Error Correction & Total\\\\\n & Time (seconds) & Time (seconds) & Time (seconds)\\\\\n\\hline\n64 & 4.80 & 3430.27 & 3435.68\\\\\n128 & 4.07 & 1819.92 & 1825.67\\\\\n256 & 6.83 & 1042.59 & 1050.28\\\\\n512 & 13.01 & 537.66 & 551.67\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\n\\subsection{Dataset D3 (Hamming Distance 1)}\n\\label{sec-3-4}\n\\subsubsection{Default run results}\n\\label{sec-3-4-1}\n\n\\begin{center}\n\\begin{tabular}{rrrr}\n\\hline\nProcs & Construction & Error Correction & Total\\\\\n & Time (seconds) & Time (seconds) & Time (seconds)\\\\\n\\hline\n8 & 742.81 & 1393.49 & 2161.24\\\\\n16 & 301.14 & 909.75 & 1242.94\\\\\n32 & 95.42 & 521.19 & 622.65\\\\\n64 & 56.96 & 268.58 & 328.34\\\\\n128 & 36.03 & 139.88 & 177.49\\\\\n256 & 27.98 & 89.03 & 117.85\\\\\n512 & 32.55 & 53.81 & 87.44\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\n\\subsubsection{Cache Aware results}\n\\label{sec-3-4-2}\n\n\\begin{center}\n\\begin{tabular}{rrrr}\n\\hline\nProcs & Construction & Error Correction & Total\\\\\n & Time (seconds) & Time (seconds) & Time (seconds)\\\\\n\\hline\n8 &  &  & \\\\\n16 & 325.56 & 597.92 & 959.25\\\\\n32 & 95.07 & 339.56 & 440.89\\\\\n64 & 56.71 & 177.45 & 237.06\\\\\n128 & 36.47 & 95.91 & 133.95\\\\\n256 & 27.65 & 57.54 & 85.99\\\\\n512 & 31.31 & 36.12 & 68.50\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\n\\subsubsection{Cache Oblivious results}\n\\label{sec-3-4-3}\n\n\\begin{center}\n\\begin{tabular}{rrrr}\n\\hline\nProcs & Construction & Error Correction & Total\\\\\n & Time (seconds) & Time (seconds) & Time (seconds)\\\\\n\\hline\n8 &  &  & \\\\\n16 & 277.21 & 591.01 & 895.64\\\\\n32 & 95.85 & 343.65 & 442.24\\\\\n64 & 56.62 & 175.89 & 241.81\\\\\n128 & 36.34 & 93.65 & 135.92\\\\\n256 & 28.24 & 60.75 & 89.78\\\\\n512 & 31.28 & 47.29 & 81.26\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\n\\subsection{Dataset D3 (Hamming Distance = 2)}\n\\label{sec-3-5}\n\\subsubsection{Summary}\n\\label{sec-3-5-1}\n\\begin{table}[htb]\n\\caption{\\label{tab:d3h2run}Results for dataset $D3$ with $h = 2$}\n\\centering\n\\begin{tabular}{rrrrrrr}\n\\hline\n & k-Spectrum & Error & Cache Aware &  & Cache Oblivious & \\\\\nProcs & Construction & Correction & Error Correction & Speedup & Error Correction & Speedup\\\\\n & Time (seconds) & Time (seconds) & Time (seconds) &  & Time (seconds) & \\\\\n\\hline\n256 & 27.49 & 5816.80 & 2633.96 & 2.21 & 3600.86 & 1.61\\\\\n512 & 33.04 & 3503.59 & 1611.09 & 2.17 & 2184.29 & 1.60\\\\\n1024 & 53.40 & 2156.35 & 1071.46 & 2.01 & 1313.32 & 1.64\\\\\n\\hline\n\\end{tabular}\n\\end{table}\n\n\\subsubsection{Default run results}\n\\label{sec-3-5-2}\n\n\\begin{center}\n\\begin{tabular}{rrrr}\n\\hline\nProcs & Construction & Error Correction & Total\\\\\n & Time (seconds) & Time (seconds) & Time (seconds)\\\\\n\\hline\n256 & 27.49 & 5816.80 & 5865.32\\\\\n512 & 33.04 & 3503.59 & 3544.15\\\\\n1024 & 53.40 & 2156.35 & 2215.19\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\n\\subsubsection{Cache Aware run results}\n\\label{sec-3-5-3}\n\n\\begin{center}\n\\begin{tabular}{rrrr}\n\\hline\nProcs & Construction & Error Correction & Total\\\\\n & Time (seconds) & Time (seconds) & Time (seconds)\\\\\n\\hline\n256 & 27.64 & 2633.96 & 2682.89\\\\\n512 & 31.87 & 1611.09 & 1644.02\\\\\n1024 & 53.62 & 1071.46 & 1130.10\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\n\\subsubsection{Cache Oblivious run results}\n\\label{sec-3-5-4}\n\n\\begin{center}\n\\begin{tabular}{rrrr}\n\\hline\nProcs & Construction & Error Correction & Total\\\\\n & Time (seconds) & Time (seconds) & Time (seconds)\\\\\n\\hline\n256 & 28.27 & 3600.86 & 3649.69\\\\\n512 & 32.67 & 2184.29 & 2224.49\\\\\n1024 & 56.61 & 1313.32 & 1373.40\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\n\\section{Work Distribution Notes}\n\\label{sec-4}\n\nWe will use a master-slave pattern to dynamically distribute\nwork. Suppose, we use p processes for the error correction, and each\nprocess uses k + 1 shared memory threads.  In each process, we allocate\none thread completely dedicated to handle all the inter-process\ncommunincations and work assignment. I call this thread 'the\nco-ordination thread'. This thread doesn't do any error correction (EC)\nwork. The rest of the k worker threads will only do the EC work. In our\nimplementation, we will use the the root process for the master process.\n\nIn the mater process, the following are the reponsibilities of a\nco-ordination thread:\n\\begin{enumerate}\n\\item Assign work to k local worker threads.\n\\item Poll for any work request from slave process. If any slave process\nasks for work, assign work for them.\n\\item When there is no more work to assign, notify every one.\n\\end{enumerate}\n\nIn the slave process, a co-ordination thread's responsibilities are as\nfollows:\n\\begin{enumerate}\n\\item If we are running low on work assignment, ask work from master\nprocess.\n\\item Recieve work from master process and distribute it to the local\nworker threads.\n\\end{enumerate}\n\nAn EC work-item is represented by an offset in the input file. This is\nposition starting from which a worker thread starts reading and\ncontinues to do error correction for a predifined chunk. Communication\nbetween the co-ordination thread and the worker threads with in a\nprocess is accomplished via a shared queue. The co-ordination thread\nloads the work-item to queue, from which the worker threads pops the\nitem and proceeds to do the error correction. When the queue size is\nbelow a given threshold, the co-ordination threads pre-emptively\nrequests work from the master process. The master process always sends k\nwork-items. Right now the threshold is kept as 2k, and hence the work\nqueue size is always bounded by 3k work items.\n\nWorker thread is dumb in the sense that it goes on an infinite loop : it\ndoes error correction, looks at the work queue for the next chunk and so\non. Worker processes break out of the loop, when a shared boolean\nvariable is set to true.\n\nThe state transitions of the co-ordination thread is as follows:\nInitially, the co-ordination thread is at \"ASSIGN$_{\\text{WORK}}$\" state. In this\nstate this thread in a slave process monitors the work queue, and if its\nsize falls below 2k, it requests work-items from the master\nprocess. After receiving the work items, it pushes them into the work\nqueue. In the master process, this thread fulfills the slaves' requests,\nand performs work-item assignment for local worker threads. When there\nis no more work available for assignment, we move to the next state :\n\"PENDING$_{\\text{WORK}}$\". This state represents the situation that there is no\nmore work to assign, but the work-queue is not empty i.e., there are\nstill work-items left to be claimed by the dumb workers. In this state,\nthe co-ord thread in a slave process will just monitor the work queue\nand wait for it to become empty. In the master process, the co-ord\nthread at this state will poll for any slave requests, while monitoring\nthe work queue. This thread also sends the \"No more work is available to\nassign\" signal by sending assigning 'zero work'. This thread can move to\nnext state only if it has sent 'zero work' signal to all the slave\nprocesses. The next state is 'FINISHED$_{\\text{WORK'}}$. At this state, there is\nnothing more to do for the co-ord threads. It sets the shared boolean\nvariable to true and waits for the worker threads to finish the last\nerror correction work items.\n\n\n\n\nPage 3:\nAdd SRX027713 and SRX027583 as the references for the human dataset.\n\nPage 4: (right column: 2nd paragraph)\n\\begin{itemize}\n\\item The work-queue can hold up to 3 × M chunks at any given time.\n\\end{itemize}\nPage 4: (right column: 4th paragraph)\n\\begin{itemize}\n\\item Each local-master is responsible for maintaining a work-queue of size\n3 x M chunks.\n\\end{itemize}\n\nComment: We maintain only 2 x M work-chunks in the queue at a\ntime. However, the initial queue size is 3 x M work-chunks because we\nwant to avoid work requests from local masters as soon as the error\ncorrection is started. Suppose if the initial queue size is less than 3\nx M, which implies that after M work-chunks are taken up by the worker\nthreads, we will have less than 2 x M left in the queue. This\nimmediately causes the local master to request the global master for\nwork. By keeping the initial queue size 3 x M, we avoid the initial\nflood of requests.\n\nPage 4: (right column: 3rd paragraph)\n\\begin{itemize}\n\\item After communicating the no−more−work message to all the local-masters,\n\\end{itemize}\nthe global master waits for all the local-masters to complete the work\npreviously requested by them.\n\nComment : No, global-master doesn't wait for the local-master. It waits\nto make sure only two things:\n\\begin{enumerate}\n\\item All local-masters have recieved the \"no-more-work\" message. This is\ndone by counting how many times \"no-more-work\" message has been sent.\n\\item global-masters' own local workers have completed their work.\n\\end{enumerate}\nIf the above two are done, global-master just go ahead and does\nMPI$_{\\text{finalize}}$. Here, also it doesn't wait for local-masters -- only that\nit announces that there is nothing more to do.\n\n\nPage 5:(left column: 1st paragraph)\n\\begin{itemize}\n\\item The local-master then sends a pending − work − done message to the\nglobal-master and exits.\n\\end{itemize}\n\nComment : No, the local-master doesn't send any message to global\nmaster. The \"pending-work\" is just a state maintained by local masters\nto no longer request work from the master and just wait until every\nlocal worker is done error correction.\n\nPage 5:(right column: 1st paragraph)\n\\begin{itemize}\n\\item By taking the network-latency of our cluster into account, a choice of\n500 reads for the chunk size achieves a good trade-off between the two\nconflicting requirements.\n\\end{itemize}\n\nComment: Also, note that it also depends on the dataset on how much work\n500 reads consume.\n\nPage 7:(results)\n\nComment: Do we have to mention that we don't use the parallel\ncache-aware construction algorithm in our experiments ?\n% Emacs 24.5.1 (Org mode 8.2.8)\n\\end{document}", "meta": {"hexsha": "7f909f5e48b2ea3d8bd4f70922d4c99ca6ccd659", "size": 19640, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "notes/notes.tex", "max_stars_repo_name": "ParBLiSS/cao-reptile", "max_stars_repo_head_hexsha": "bb807b0578396f3ffe156a95e612ef16d5da167c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notes/notes.tex", "max_issues_repo_name": "ParBLiSS/cao-reptile", "max_issues_repo_head_hexsha": "bb807b0578396f3ffe156a95e612ef16d5da167c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notes/notes.tex", "max_forks_repo_name": "ParBLiSS/cao-reptile", "max_forks_repo_head_hexsha": "bb807b0578396f3ffe156a95e612ef16d5da167c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5248796148, "max_line_length": 94, "alphanum_fraction": 0.6782586558, "num_tokens": 7057, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073507867328, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.32424668419917785}}
{"text": "\\newtheorem{cscexample}{Example}\n\n\\achapter{\\protect{Generalized rewriting}}\n\\aauthor{Matthieu Sozeau}\n\\label{setoids}\n\nThis chapter presents the extension of several equality related tactics\nto work over user-defined structures (called setoids) that are equipped\nwith ad-hoc equivalence relations meant to behave as equalities.\nActually, the tactics have also been generalized to relations weaker\nthen equivalences (e.g. rewriting systems). The toolbox also extends the\nautomatic rewriting capabilities of the system, allowing the specification of\ncustom strategies for rewriting.\n\nThis documentation is adapted from the previous setoid documentation by\nClaudio Sacerdoti Coen (based on previous work by Cl\\'ement Renard).\nThe new implementation is a drop-in replacement for the old one,\\footnote{Nicolas\nTabareau helped with the gluing.} hence most of the documentation still applies.\n\nThe work is a complete rewrite of the previous implementation, based on\nthe type class infrastructure. It also improves on and generalizes\nthe previous implementation in several ways:\n\\begin{itemize}\n\\item User-extensible algorithm. The algorithm is separated in two\n  parts: generations of the rewriting constraints (done in ML) and\n  solving of these constraints using type class resolution. As type\n  class resolution is extensible using tactics, this allows users to define\n  general ways to solve morphism constraints.\n\\item Sub-relations. An example extension to the base algorithm is the\n  ability to define one relation as a subrelation of another so that\n  morphism declarations on one relation can be used automatically for\n  the other. This is done purely using tactics and type class search.\n\\item Rewriting under binders. It is possible to rewrite under binders\n  in the new implementation, if one provides the proper\n  morphisms. Again, most of the work is handled in the tactics.\n\\item First-class morphisms and signatures. Signatures and morphisms are\n  ordinary Coq terms, hence they can be manipulated inside Coq, put\n  inside structures and lemmas about them can be proved inside the\n  system. Higher-order morphisms are also allowed.\n\\item Performance. The implementation is based on a depth-first search for the first\n  solution to a set of constraints which can be as fast as linear in the\n  size of the term, and the size of the proof term is linear\n  in the size of the original term. Besides, the extensibility allows the\n  user to customize the proof search if necessary.\n\\end{itemize}\n\n\\asection{Introduction to generalized rewriting}\n\n\\subsection{Relations and morphisms}\n\nA parametric \\emph{relation} \\texttt{R} is any term of type\n\\texttt{forall ($x_1$:$T_1$) \\ldots ($x_n$:$T_n$), relation $A$}. The\nexpression $A$, which depends on $x_1$ \\ldots $x_n$, is called the\n\\emph{carrier} of the relation and \\texttt{R} is\nsaid to be a relation over \\texttt{A}; the list $x_1,\\ldots,x_n$\nis the (possibly empty) list of parameters of the relation.\n\n\\firstexample\n\\begin{cscexample}[Parametric relation]\nIt is possible to implement finite sets of elements of type \\texttt{A}\nas unordered list of elements of type \\texttt{A}. The function\n\\texttt{set\\_eq: forall (A: Type), relation (list A)} satisfied by two lists\nwith the same elements is a parametric relation over \\texttt{(list A)} with\none parameter \\texttt{A}. The type of \\texttt{set\\_eq} is convertible with\n\\texttt{forall (A: Type), list A -> list A -> Prop}.\n\\end{cscexample}\n\nAn \\emph{instance} of a parametric relation \\texttt{R} with $n$ parameters\nis any term \\texttt{(R $t_1$ \\ldots $t_n$)}.\n\nLet \\texttt{R} be a relation over \\texttt{A} with $n$ parameters.\nA term is a parametric proof of reflexivity for \\texttt{R} if it has type\n\\texttt{forall ($x_1$:$T_1$) \\ldots ($x_n$:$T_n$),\n reflexive (R $x_1$ \\ldots $x_n$)}. Similar definitions are given for\nparametric proofs of symmetry and transitivity.\n\n\\begin{cscexample}[Parametric relation (cont.)]\nThe \\texttt{set\\_eq} relation of the previous example can be proved to be\nreflexive, symmetric and transitive.\n\\end{cscexample}\n\nA parametric unary function $f$ of type\n\\texttt{forall ($x_1$:$T_1$) \\ldots ($x_n$:$T_n$), $A_1$ -> $A_2$}\ncovariantly respects two parametric relation instances $R_1$ and $R_2$ if,\nwhenever $x, y$ satisfy $R_1~x~y$, their images $(f~x)$ and $(f~y)$ \nsatisfy $R_2~(f~x)~(f~y)$ . An $f$ that respects its input and output relations\nwill be called a unary covariant \\emph{morphism}. We can also say that $f$ is\na monotone function with respect to $R_1$ and $R_2$. \nThe sequence $x_1,\\ldots x_n$ represents the parameters of the morphism.\n\nLet $R_1$ and $R_2$ be two parametric relations.\nThe \\emph{signature} of a parametric morphism of type\n\\texttt{forall ($x_1$:$T_1$) \\ldots ($x_n$:$T_n$), $A_1$ -> $A_2$} that\ncovariantly respects two instances $I_{R_1}$ and $I_{R_2}$ of $R_1$ and $R_2$ is written $I_{R_1} \\texttt{++>} I_{R_2}$.\nNotice that the special arrow \\texttt{++>}, which reminds the reader\nof covariance, is placed between the two relation instances, not\nbetween the two carriers. The signature relation instances and morphism will\nbe typed in a context introducing variables for the parameters.\n\nThe previous definitions are extended straightforwardly to $n$-ary morphisms,\nthat are required to be simultaneously monotone on every argument.\n\nMorphisms can also be contravariant in one or more of their arguments.\nA morphism is contravariant on an argument associated to the relation instance\n$R$ if it is covariant on the same argument when the inverse relation\n$R^{-1}$ (\\texttt{inverse R} in Coq) is considered. \nThe special arrow \\texttt{-{}->} is used in signatures\nfor contravariant morphisms.\n\nFunctions having arguments related by symmetric relations instances are both\ncovariant and contravariant in those arguments. The special arrow\n\\texttt{==>} is used in signatures for morphisms that are both covariant\nand contravariant.\n\nAn instance of a parametric morphism $f$ with $n$ parameters is any term\n\\texttt{f $t_1$ \\ldots $t_n$}.\n\n\\begin{cscexample}[Morphisms]\nContinuing the previous example, let\n\\texttt{union: forall (A: Type), list A -> list A -> list A} perform the union\nof two sets by appending one list to the other. \\texttt{union} is a binary\nmorphism parametric over \\texttt{A} that respects the relation instance\n\\texttt{(set\\_eq A)}. The latter condition is proved by showing\n\\texttt{forall (A: Type) (S1 S1' S2 S2': list A), set\\_eq A S1 S1' ->\n set\\_eq A S2 S2' -> set\\_eq A (union A S1 S2) (union A S1' S2')}.\n\nThe signature of the function \\texttt{union A} is\n\\texttt{set\\_eq A ==> set\\_eq A ==> set\\_eq A} for all \\texttt{A}.\n\\end{cscexample}\n\n\\begin{cscexample}[Contravariant morphism]\nThe division function \\texttt{Rdiv: R -> R -> R} is a morphism of\nsignature \\texttt{le ++> le -{}-> le} where \\texttt{le} is\nthe usual order relation over real numbers. Notice that division is\ncovariant in its first argument and contravariant in its second\nargument.\n\\end{cscexample}\n\nLeibniz equality is a relation and every function is a\nmorphism that respects Leibniz equality. Unfortunately, Leibniz equality\nis not always the intended equality for a given structure.\n\nIn the next section we will describe the commands to register terms as\nparametric relations and morphisms. Several tactics that deal with equality\nin \\Coq\\ can also work with the registered relations.\nThe exact list of tactic will be given in Sect.~\\ref{setoidtactics}.\nFor instance, the\ntactic \\texttt{reflexivity} can be used to close a goal $R~n~n$ whenever\n$R$ is an instance of a registered reflexive relation. However, the tactics\nthat replace in a context $C[]$ one term with another one related by $R$\nmust verify that $C[]$ is a morphism that respects the intended relation.\nCurrently the verification consists in checking whether $C[]$ is a syntactic\ncomposition of morphism instances that respects some obvious\ncompatibility constraints.\n\n\\begin{cscexample}[Rewriting]\nContinuing the previous examples, suppose that the user must prove\n\\texttt{set\\_eq int (union int (union int S1 S2) S2) (f S1 S2)} under the\nhypothesis \\texttt{H: set\\_eq int S2 (nil int)}. It is possible to\nuse the \\texttt{rewrite} tactic to replace the first two occurrences of\n\\texttt{S2} with \\texttt{nil int} in the goal since the context\n\\texttt{set\\_eq int (union int (union int S1 nil) nil) (f S1 S2)}, being\na composition of morphisms instances, is a morphism. However the tactic\nwill fail replacing the third occurrence of \\texttt{S2} unless \\texttt{f}\nhas also been declared as a morphism.\n\\end{cscexample}\n\n\\subsection{Adding new relations and morphisms}\nA parametric relation\n\\textit{Aeq}\\texttt{: forall ($y_1 : \\beta_!$ \\ldots $y_m : \\beta_m$), relation (A $t_1$ \\ldots $t_n$)} over\n\\textit{(A : $\\alpha_i$ -> \\ldots $\\alpha_n$ -> }\\texttt{Type})\ncan be declared with the following command:\n\n\\comindex{Add Parametric Relation}\n\\begin{quote}\n  \\texttt{Add Parametric Relation} ($x_1 : T_1$) \\ldots ($x_n : T_k$) :\n  \\textit{(A $t_1$ \\ldots $t_n$) (Aeq $t'_1$ \\ldots $t'_m$)}\\\\\n  ~\\zeroone{\\texttt{reflexivity proved by} \\textit{refl}}\\\\\n  ~\\zeroone{\\texttt{symmetry proved by} \\textit{sym}}\\\\\n  ~\\zeroone{\\texttt{transitivity proved by} \\textit{trans}}\\\\\n  \\texttt{~as} \\textit{id}.\n\\end{quote}\nafter having required the \\texttt{Setoid} module with the\n\\texttt{Require Setoid} command.\n\nThe identifier \\textit{id} gives a unique name to the morphism and it is\nused by the command to generate fresh names for automatically provided lemmas\nused internally.\n\nNotice that the carrier and relation parameters may refer to the context \nof variables introduced at the beginning of the declaration, but the\ninstances need not be made only of variables.\nAlso notice that \\textit{A} is \\emph{not} required to be a term\nhaving the same parameters as \\textit{Aeq}, although that is often the\ncase in practice (this departs from the previous implementation).\n\n\\comindex{Add Relation}\nIn case the carrier and relations are not parametric, one can use the\ncommand \\texttt{Add Relation} instead, whose syntax is the same except\nthere is no local context.\n\nThe proofs of reflexivity, symmetry and transitivity can be omitted if the\nrelation is not an equivalence relation. The proofs must be instances of the\ncorresponding relation definitions: e.g. the proof of reflexivity must\nhave a type convertible to \\texttt{reflexive (A $t_1$ \\ldots $t_n$) (Aeq $t'_1$ \\ldots\n  $t'_n$)}. Each proof may refer to the introduced variables as well. \n\n\\begin{cscexample}[Parametric relation]\nFor Leibniz equality, we may declare:\n\\texttt{Add Parametric Relation (A : Type) :} \\texttt{A (@eq A)}\\\\\n~\\zeroone{\\texttt{reflexivity proved by} \\texttt{@refl\\_equal A}}\\\\\n\\ldots\n\\end{cscexample}\n\nSome tactics\n(\\texttt{reflexivity}, \\texttt{symmetry}, \\texttt{transitivity}) work only\non relations that respect the expected properties. The remaining tactics\n(\\texttt{replace}, \\texttt{rewrite} and derived tactics such as\n\\texttt{autorewrite}) do not require any properties over the relation.\nHowever, they are able to replace terms with related ones only in contexts\nthat are syntactic compositions of parametric morphism instances declared with\nthe following command.\n\n\\comindex{Add Parametric Morphism}\n\\begin{quote}\n  \\texttt{Add Parametric Morphism} ($x_1 : \\T_!$) \\ldots ($x_k : \\T_k$)\\\\\n  (\\textit{f $t_1$ \\ldots $t_n$})\\\\\n  \\texttt{~with signature} \\textit{sig}\\\\\n  \\texttt{~as id}.\\\\\n  \\texttt{Proof}\\\\\n  ~\\ldots\\\\\n  \\texttt{Qed}\n\\end{quote}\n\nThe command declares \\textit{f} as a parametric morphism of signature\n\\textit{sig}. The identifier \\textit{id} gives a unique name to the morphism\nand it is used as the base name of the type class instance definition \nand as the name of the lemma that proves the well-definedness of the morphism.\nThe parameters of the morphism as well as the signature may refer to the\ncontext of variables.\nThe command asks the user to prove interactively that \\textit{f} respects\nthe relations identified from the signature.\n\n\\begin{cscexample}\nWe start the example by assuming a small theory over homogeneous sets and\nwe declare set equality as a parametric equivalence relation and\nunion of two sets as a parametric morphism.\n\\begin{coq_example*}\nRequire Export Setoid.\nRequire Export Relation_Definitions.\nSet Implicit Arguments.\nParameter set: Type -> Type.\nParameter empty: forall A, set A.\nParameter eq_set: forall A, set A -> set A -> Prop.\nParameter union: forall A, set A -> set A -> set A.\nAxiom eq_set_refl: forall A, reflexive _ (eq_set (A:=A)).\nAxiom eq_set_sym: forall A, symmetric _ (eq_set (A:=A)).\nAxiom eq_set_trans: forall A, transitive _ (eq_set (A:=A)).\nAxiom empty_neutral: forall A (S: set A), eq_set (union S (empty A)) S.\nAxiom union_compat:\n forall (A : Type),\n  forall x x' : set A, eq_set x x' ->\n  forall y y' : set A, eq_set y y' ->\n   eq_set (union x y) (union x' y').\nAdd Parametric Relation A : (set A) (@eq_set A)\n reflexivity proved by (eq_set_refl (A:=A))\n symmetry proved by (eq_set_sym (A:=A))\n transitivity proved by (eq_set_trans (A:=A))\n as eq_set_rel.\nAdd Parametric Morphism A : (@union A) with \nsignature (@eq_set A) ==> (@eq_set A) ==> (@eq_set A) as union_mor.\nProof. exact (@union_compat A). Qed.\n\\end{coq_example*}\n\n\\end{cscexample}\n\nIt is possible to reduce the burden of specifying parameters using\n(maximally inserted) implicit arguments. If \\texttt{A} is always set as\nmaximally implicit in the previous example, one can write:\n\n\\begin{coq_eval}\nReset Initial.\nRequire Export Setoid.\nRequire Export Relation_Definitions.\nParameter set: Type -> Type.\nParameter empty: forall {A}, set A.\nParameter eq_set: forall {A}, set A -> set A -> Prop.\nParameter union: forall {A}, set A -> set A -> set A.\nAxiom eq_set_refl: forall {A}, reflexive (set A) eq_set.\nAxiom eq_set_sym: forall {A}, symmetric (set A) eq_set.\nAxiom eq_set_trans: forall {A}, transitive (set A) eq_set.\nAxiom empty_neutral: forall A (S: set A), eq_set (union S empty) S.\nAxiom union_compat:\n forall (A : Type),\n  forall x x' : set A, eq_set x x' ->\n  forall y y' : set A, eq_set y y' ->\n   eq_set (union x y) (union x' y').\n\\end{coq_eval}\n\n\\begin{coq_example*} \nAdd Parametric Relation A : (set A) eq_set\n reflexivity proved by eq_set_refl\n symmetry proved by eq_set_sym\n transitivity proved by eq_set_trans\n as eq_set_rel.\nAdd Parametric Morphism A : (@union A) with\n  signature eq_set ==> eq_set ==> eq_set as union_mor.\nProof. exact (@union_compat A). Qed.\n\\end{coq_example*}\n\nWe proceed now by proving a simple lemma performing a rewrite step\nand then applying reflexivity, as we would do working with Leibniz\nequality. Both tactic applications are accepted\nsince the required properties over \\texttt{eq\\_set} and\n\\texttt{union} can be established from the two declarations above.\n\n\\begin{coq_example*}\nGoal forall (S: set nat),\n eq_set (union (union S empty) S) (union S S).\nProof. intros. rewrite empty_neutral. reflexivity. Qed.\n\\end{coq_example*}\n\nThe tables of relations and morphisms are managed by the type class\ninstance mechanism. The behavior on section close is to generalize\nthe instances by the variables of the section (and possibly hypotheses\nused in the proofs of instance declarations) but not to export them in\nthe rest of the development for proof search. One can use the\n\\texttt{Existing Instance} command to do so outside the section,\nusing the name of the declared morphism suffixed by \\texttt{\\_Morphism}, \nor use the \\texttt{Global} modifier for the corresponding class instance\ndeclaration (see \\S\\ref{setoid:first-class}) at definition time.\nWhen loading a compiled file or importing a module,\nall the declarations of this module will be loaded.\n\n\\subsection{Rewriting and non reflexive relations}\nTo replace only one argument of an n-ary morphism it is necessary to prove\nthat all the other arguments are related to themselves by the respective\nrelation instances.\n\n\\begin{cscexample}\nTo replace \\texttt{(union S empty)} with \\texttt{S} in\n\\texttt{(union (union S empty) S) (union S S)} the rewrite tactic must\nexploit the monotony of \\texttt{union} (axiom \\texttt{union\\_compat} in\nthe previous example). Applying \\texttt{union\\_compat} by hand we are left\nwith the goal \\texttt{eq\\_set (union S S) (union S S)}.\n\\end{cscexample}\n\nWhen the relations associated to some arguments are not reflexive, the tactic\ncannot automatically prove the reflexivity goals, that are left to the user.\n\nSetoids whose relation are partial equivalence relations (PER)\nare useful to deal with partial functions. Let \\texttt{R} be a PER. We say\nthat an element \\texttt{x} is defined if \\texttt{R x x}. A partial function\nwhose domain comprises all the defined elements only is declared as a\nmorphism that respects \\texttt{R}. Every time a rewriting step is performed\nthe user must prove that the argument of the morphism is defined.\n\n\\begin{cscexample}\nLet \\texttt{eqO} be \\texttt{fun x y => x = y $\\land$ ~x$\\neq$ 0} (the smaller PER over\nnon zero elements). Division can be declared as a morphism of signature\n\\texttt{eq ==> eq0 ==> eq}. Replace \\texttt{x} with \\texttt{y} in\n\\texttt{div x n = div y n} opens the additional goal \\texttt{eq0 n n} that\nis equivalent to \\texttt{n=n $\\land$ n$\\neq$0}.\n\\end{cscexample}\n\n\\subsection{Rewriting and non symmetric relations}\nWhen the user works up to relations that are not symmetric, it is no longer\nthe case that any covariant morphism argument is also contravariant. As a\nresult it is no longer possible to replace a term with a related one in\nevery context, since the obtained goal implies the previous one if and\nonly if the replacement has been performed in a contravariant position.\nIn a similar way, replacement in an hypothesis can be performed only if\nthe replaced term occurs in a covariant position.\n\n\\begin{cscexample}[Covariance and contravariance]\nSuppose that division over real numbers has been defined as a\nmorphism of signature \\texttt{Z.div: Z.lt ++> Z.lt -{}-> Z.lt} (i.e.\n\\texttt{Z.div} is increasing in its first argument, but decreasing on the\nsecond one). Let \\texttt{<} denotes \\texttt{Z.lt}.\nUnder the hypothesis \\texttt{H: x < y} we have\n\\texttt{k < x / y -> k < x / x}, but not\n\\texttt{k < y / x -> k < x / x}.\nDually, under the same hypothesis \\texttt{k < x / y -> k < y / y} holds,\nbut \\texttt{k < y / x -> k < y / y} does not.\nThus, if the current goal is \\texttt{k < x / x}, it is possible to replace\nonly the second occurrence of \\texttt{x} (in contravariant position)\nwith \\texttt{y} since the obtained goal must imply the current one.\nOn the contrary, if \\texttt{k < x / x} is\nan hypothesis, it is possible to replace only the first occurrence of\n\\texttt{x} (in covariant position) with \\texttt{y} since\nthe current hypothesis must imply the obtained one.\n\\end{cscexample}\n\nContrary to the previous implementation, no specific error message will\nbe raised when trying to replace a term that occurs in the wrong\nposition. It will only fail because the rewriting constraints are not\nsatisfiable. However it is possible to use the \\texttt{at} modifier to\nspecify which occurrences should be rewritten.\n\nAs expected, composing morphisms together propagates the variance annotations by\nswitching the variance every time a contravariant position is traversed.\n\\begin{cscexample}\nLet us continue the previous example and let us consider the goal\n\\texttt{x / (x / x) < k}. The first and third occurrences of \\texttt{x} are\nin a contravariant position, while the second one is in covariant position.\nMore in detail, the second occurrence of \\texttt{x} occurs\ncovariantly in \\texttt{(x / x)} (since division is covariant in its first\nargument), and thus contravariantly in \\texttt{x / (x / x)} (since division\nis contravariant in its second argument), and finally covariantly in\n\\texttt{x / (x / x) < k} (since \\texttt{<}, as every transitive relation,\nis contravariant in its first argument with respect to the relation itself).\n\\end{cscexample}\n\n\\subsection{Rewriting in ambiguous setoid contexts}\nOne function can respect several different relations and thus it can be\ndeclared as a morphism having multiple signatures.\n\n\\begin{cscexample}\nUnion over homogeneous lists can be given all the following signatures:\n\\texttt{eq ==> eq ==> eq} (\\texttt{eq} being the equality over ordered lists)\n\\texttt{set\\_eq ==> set\\_eq ==> set\\_eq} (\\texttt{set\\_eq} being the equality\nover unordered lists up to duplicates),\n\\texttt{multiset\\_eq ==> multiset\\_eq ==> multiset\\_eq} (\\texttt{multiset\\_eq}\nbeing the equality over unordered lists).\n\\end{cscexample}\n\nTo declare multiple signatures for a morphism, repeat the \\texttt{Add Morphism}\ncommand.\n\nWhen morphisms have multiple signatures it can be the case that a rewrite\nrequest is ambiguous, since it is unclear what relations should be used to\nperform the rewriting. Contrary to the previous implementation, the\ntactic will always choose the first possible solution to the set of\nconstraints generated by a rewrite and will not try to find \\emph{all}\npossible solutions to warn the user about.\n\n\\asection{Commands and tactics}\n\\subsection{First class setoids and morphisms}\n\\label{setoid:first-class}\n\nThe implementation is based on a first-class representation of\nproperties of relations and morphisms as type classes. That is, \nthe various combinations of properties on relations and morphisms \nare represented as records and instances of theses classes are put\nin a hint database.\nFor example, the declaration:\n\n\\begin{quote}\n  \\texttt{Add Parametric Relation} ($x_1 : T_1$) \\ldots ($x_n : T_k$) :\n  \\textit{(A $t_1$ \\ldots $t_n$) (Aeq $t'_1$ \\ldots $t'_m$)}\\\\\n  ~\\zeroone{\\texttt{reflexivity proved by} \\textit{refl}}\\\\\n  ~\\zeroone{\\texttt{symmetry proved by} \\textit{sym}}\\\\\n  ~\\zeroone{\\texttt{transitivity proved by} \\textit{trans}}\\\\\n  \\texttt{~as} \\textit{id}.\n\\end{quote}\n\nis equivalent to an instance declaration:\n\n\\begin{quote}\n  \\texttt{Instance} ($x_1 : T_1$) \\ldots ($x_n : T_k$) \\texttt{=>}\n  \\textit{id} : \\texttt{@Equivalence} \\textit{(A $t_1$ \\ldots $t_n$) (Aeq\n    $t'_1$ \\ldots $t'_m$)} :=\\\\\n  ~\\zeroone{\\texttt{Equivalence\\_Reflexive :=} \\textit{refl}}\\\\\n  ~\\zeroone{\\texttt{Equivalence\\_Symmetric :=} \\textit{sym}}\\\\\n  ~\\zeroone{\\texttt{Equivalence\\_Transitive :=} \\textit{trans}}.\n\\end{quote}\n\nThe declaration itself amounts to the definition of an object of the\nrecord type \\texttt{Coq.Classes.RelationClasses.Equivalence} and a\nhint added to the \\texttt{typeclass\\_instances} hint database. \nMorphism declarations are also instances of a type class defined in\n\\texttt{Classes.Morphisms}.\nSee the documentation on type classes \\ref{typeclasses} and \nthe theories files in \\texttt{Classes} for further explanations. \n\nOne can inform the rewrite tactic about morphisms and relations just by\nusing the typeclass mechanism to declare them using \\texttt{Instance}\nand \\texttt{Context} vernacular commands.\nAny object of type \\texttt{Proper} (the type of morphism declarations)\nin the local context will also be automatically used by the rewriting \ntactic to solve constraints.\n\nOther representations of first class setoids and morphisms can also\nbe handled by encoding them as records. In the following example,\nthe projections of the setoid relation and of the morphism function \ncan be registered as parametric relations and morphisms.\n\\begin{cscexample}[First class setoids]\n\n\\begin{coq_example*}\nRequire Import Relation_Definitions Setoid.\nRecord Setoid: Type :=\n{ car:Type;\n  eq:car->car->Prop;\n  refl: reflexive _ eq;\n  sym: symmetric _ eq;\n  trans: transitive _ eq\n}.\nAdd Parametric Relation (s : Setoid) : (@car s) (@eq s)\n reflexivity proved by (refl s)\n symmetry proved by (sym s)\n transitivity proved by (trans s) as eq_rel.\nRecord Morphism (S1 S2:Setoid): Type :=\n{ f:car S1 ->car S2;\n  compat: forall (x1 x2: car S1), eq S1 x1 x2 -> eq S2 (f x1) (f x2) }.\nAdd Parametric Morphism (S1 S2 : Setoid) (M : Morphism S1 S2) :\n (@f S1 S2 M) with signature (@eq S1 ==> @eq S2) as apply_mor.\nProof. apply (compat S1 S2 M). Qed.\nLemma test: forall (S1 S2:Setoid) (m: Morphism S1 S2)\n (x y: car S1), eq S1 x y -> eq S2 (f _ _ m x) (f _ _ m y).\nProof. intros. rewrite H. reflexivity. Qed.\n\\end{coq_example*}\n\\end{cscexample}\n\n\\subsection{Tactics enabled on user provided relations}\n\\label{setoidtactics}\nThe following tactics, all prefixed by \\texttt{setoid\\_}, \ndeal with arbitrary\nregistered relations and morphisms. Moreover, all the corresponding unprefixed\ntactics (i.e. \\texttt{reflexivity}, \\texttt{symmetry}, \\texttt{transitivity},\n\\texttt{replace}, \\texttt{rewrite})\nhave been extended to fall back to their prefixed counterparts when\nthe relation involved is not Leibniz equality. Notice, however, that using\nthe prefixed tactics it is possible to pass additional arguments such as\n\\texttt{using relation}.\n\\medskip\n\n\\tacindex{setoid\\_reflexivity}\n\\texttt{setoid\\_reflexivity}\n\n\\tacindex{setoid\\_symmetry}\n\\texttt{setoid\\_symmetry} \\zeroone{\\texttt{in} \\textit{ident}}\n\n\\tacindex{setoid\\_transitivity}\n\\texttt{setoid\\_transitivity}\n\n\\tacindex{setoid\\_rewrite}\n\\texttt{setoid\\_rewrite} \\zeroone{\\textit{orientation}} \\textit{term}\n~\\zeroone{\\texttt{at} \\textit{occs}} ~\\zeroone{\\texttt{in} \\textit{ident}}\n\n\\tacindex{setoid\\_replace}\n\\texttt{setoid\\_replace} \\textit{term} \\texttt{with} \\textit{term}\n~\\zeroone{\\texttt{in} \\textit{ident}}\n~\\zeroone{\\texttt{using relation} \\textit{term}}\n~\\zeroone{\\texttt{by} \\textit{tactic}}\n\\medskip\n\nThe \\texttt{using relation}\narguments cannot be passed to the unprefixed form. The latter argument\ntells the tactic what parametric relation should be used to replace\nthe first tactic argument with the second one. If omitted, it defaults\nto the \\texttt{DefaultRelation} instance on the type of the objects.\nBy default, it means the most recent \\texttt{Equivalence} instance in\nthe environment, but it can be customized by declaring new\n\\texttt{DefaultRelation} instances. As Leibniz equality is a declared\nequivalence, it will fall back to it if no other relation is declared on\na given type.\n\nEvery derived tactic that is based on the unprefixed forms of the tactics\nconsidered above will also work up to user defined relations. For instance,\nit is possible to register hints for \\texttt{autorewrite} that are\nnot proof of Leibniz equalities. In particular it is possible to exploit\n\\texttt{autorewrite} to simulate normalization in a term rewriting system\nup to user defined equalities.\n\n\\subsection{Printing relations and morphisms}\nThe \\texttt{Print Instances} command can be used to show the list of\ncurrently registered \\texttt{Reflexive} (using \\texttt{Print Instances Reflexive}),\n\\texttt{Symmetric} or \\texttt{Transitive} relations,\n\\texttt{Equivalence}s, \\texttt{PreOrder}s, \\texttt{PER}s, and\nMorphisms (implemented as \\texttt{Proper} instances). When\n the rewriting tactics refuse to replace a term in a context\nbecause the latter is not a composition of morphisms, the \\texttt{Print Instances}\ncommands can be useful to understand what additional morphisms should be\nregistered.\n\n\\subsection{Deprecated syntax and backward incompatibilities}\nDue to backward compatibility reasons, the following syntax for the\ndeclaration of setoids and morphisms is also accepted.\n\n\\comindex{Add Setoid}\n\\begin{quote}\n  \\texttt{Add Setoid} \\textit{A Aeq ST} \\texttt{as} \\textit{ident}\n\\end{quote}\nwhere \\textit{Aeq} is a congruence relation without parameters,\n\\textit{A} is its carrier and \\textit{ST} is an object of type\n\\texttt{(Setoid\\_Theory A Aeq)} (i.e. a record packing together the reflexivity,\nsymmetry and transitivity lemmas). Notice that the syntax is not completely\nbackward compatible since the identifier was not required.\n\n\\comindex{Add Morphism}\n\\begin{quote}\n  \\texttt{Add Morphism} \\textit{f}:\\textit{ident}.\\\\\n  Proof.\\\\\n  \\ldots\\\\\n  Qed.\n\\end{quote}\n\nThe latter command also is restricted to the declaration of morphisms without\nparameters. It is not fully backward compatible since the property the user\nis asked to prove is slightly different: for $n$-ary morphisms the hypotheses\nof the property are permuted; moreover, when the morphism returns a\nproposition, the property is now stated using a bi-implication in place of\na simple implication. In practice, porting an old development to the new\nsemantics is usually quite simple.\n\nNotice that several limitations of the old implementation have been lifted.\nIn particular, it is now possible to declare several relations with the\nsame carrier and several signatures for the same morphism. Moreover, it is\nnow also possible to declare several morphisms having the same signature.\nFinally, the replace and rewrite tactics can be used to replace terms in\ncontexts that were refused by the old implementation. As discussed in\nthe next section, the semantics of the new \\texttt{setoid\\_rewrite}\ncommand differs slightly from the old one and \\texttt{rewrite}.\n\n\\asection{Extensions}\n\\subsection{Rewriting under binders}\n\n\\textbf{Warning}: Due to compatibility issues, this feature is enabled only when calling \nthe \\texttt{setoid\\_rewrite} tactics directly and not \\texttt{rewrite}.\n\nTo be able to rewrite under binding constructs, one must declare\nmorphisms with respect to pointwise (setoid) equivalence of functions. \nExample of such morphisms are the standard \\texttt{all} and \\texttt{ex}\ncombinators for universal and existential quantification respectively. \nThey are declared as morphisms in the \\texttt{Classes.Morphisms\\_Prop}\nmodule. For example, to declare that universal quantification is a\nmorphism for logical equivalence:\n\n\\begin{coq_eval}\nReset Initial.\nRequire Import Setoid Morphisms.\n\\end{coq_eval}\n\\begin{coq_example}\nInstance all_iff_morphism (A : Type) :\n  Proper (pointwise_relation A iff ==> iff) (@all A).\nProof. simpl_relation. \n\\end{coq_example}\n\\begin{coq_eval}\nAdmitted.\n\\end{coq_eval}\n\nOne then has to show that if two predicates are equivalent at every\npoint, their universal quantifications are equivalent. Once we have\ndeclared such a morphism, it will be used by the setoid rewriting tactic\neach time we try to rewrite under an \\texttt{all} application (products\nin \\Prop{} are implicitly translated to such applications).\n\nIndeed, when rewriting under a lambda, binding variable $x$, say from\n$P~x$ to $Q~x$ using the relation \\texttt{iff}, the tactic will generate\na proof of \\texttt{pointwise\\_relation A iff (fun x => P x) (fun x => Q\nx)} from the proof of \\texttt{iff (P x) (Q x)} and a constraint of the\nform \\texttt{Proper (pointwise\\_relation A iff ==> ?) m} will be\ngenerated for the surrounding morphism \\texttt{m}.\n\nHence, one can add higher-order combinators as morphisms by providing\nsignatures using pointwise extension for the relations on the functional\narguments (or whatever subrelation of the pointwise extension).\nFor example, one could declare the \\texttt{map} combinator on lists as \na morphism:\n\\begin{coq_eval}\nRequire Import List Setoid Morphisms.\nSet Implicit Arguments.\nInductive list_equiv {A:Type} (eqA : relation A) : relation (list A) :=\n| eq_nil : list_equiv eqA nil nil\n| eq_cons : forall x y, eqA x y ->\n  forall l l', list_equiv eqA l l' -> list_equiv eqA (x :: l) (y :: l').\nGeneralizable All Variables.\n\\end{coq_eval}\n\\begin{coq_example*}\nInstance map_morphism `{Equivalence A eqA, Equivalence B eqB} :\n  Proper ((eqA ==> eqB) ==> list_equiv eqA ==> list_equiv eqB) (@map A B).\n\\end{coq_example*}\n\nwhere \\texttt{list\\_equiv} implements an equivalence on lists\nparameterized by an equivalence on the elements.\n\nNote that when one does rewriting with a lemma under a binder\nusing \\texttt{setoid\\_rewrite}, the application of the lemma may capture\nthe bound variable, as the semantics are different from rewrite where\nthe lemma is first matched on the whole term. With the new\n\\texttt{setoid\\_rewrite}, matching is done on each subterm separately\nand in its local environment, and all matches are rewritten\n\\emph{simultaneously} by default. The semantics of the previous\n\\texttt{setoid\\_rewrite} implementation can almost be recovered using\nthe \\texttt{at 1} modifier.\n\n\\subsection{Sub-relations}\n\nSub-relations can be used to specify that one relation is included in\nanother, so that morphisms signatures for one can be used for the other.\nIf a signature mentions a relation $R$ on the left of an arrow\n\\texttt{==>}, then the signature also applies for any relation $S$ that\nis smaller than $R$, and the inverse applies on the right of an arrow. \nOne can then declare only a few morphisms instances that generate the complete set\nof signatures for a particular constant. By default, the only declared\nsubrelation is \\texttt{iff}, which is a subrelation of \\texttt{impl}\nand \\texttt{inverse impl} (the dual of implication). That's why we can\ndeclare only two morphisms for conjunction:\n\\texttt{Proper (impl ==> impl ==> impl) and} and \n\\texttt{Proper (iff ==> iff ==> iff) and}. This is sufficient to satisfy\nany rewriting constraints arising from a rewrite using \\texttt{iff},\n\\texttt{impl} or \\texttt{inverse impl} through \\texttt{and}.\n\nSub-relations are implemented in \\texttt{Classes.Morphisms} and are a \nprime example of a mostly user-space extension of the algorithm.\n\n\\subsection{Constant unfolding}\n\nThe resolution tactic is based on type classes and hence regards user-defined \nconstants as transparent by default. This may slow down the resolution\ndue to a lot of unifications (all the declared \\texttt{Proper}\ninstances are tried at each node of the search tree).\nTo speed it up, declare your constant as rigid for proof search\nusing the command \\texttt{Typeclasses Opaque} (see \\S\n\\ref{TypeclassesTransparency}).\n\n\\asection{Strategies for rewriting}\n\n\\subsection{Definitions}\nThe generalized rewriting tactic is based on a set of strategies that\ncan be combined to obtain custom rewriting procedures. Its set of\nstrategies is based on Elan's rewriting strategies\n\\cite{Luttik97specificationof}. Rewriting strategies are applied using\nthe tactic \\texttt{rewrite\\_strat $s$} where $s$ is a strategy\nexpression. Strategies are defined inductively as described by the\nfollowing grammar:\n\n\\def\\str#1{\\texttt{#1}}\n\n\\def\\strline#1#2{& \\vert & #1 & \\text{#2}}\n\\def\\strlinea#1#2#3{& \\vert & \\str{#1}~#2 & \\text{#3}}\n\n\\[\\begin{array}{lcll}\n  s, t, u & ::= & ( s ) & \\text{strategy} \\\\\n  \\strline{c}{lemma} \\\\\n  \\strline{\\str{<-}~c}{lemma, right-to-left} \\\\\n\n  \\strline{\\str{fail}}{failure} \\\\\n  \\strline{\\str{id}}{identity} \\\\\n  \\strline{\\str{refl}}{reflexivity} \\\\\n  \\strlinea{progress}{s}{progress} \\\\\n  \\strlinea{try}{s}{failure catch} \\\\\n\n  \\strline{s~\\str{;}~u}{composition} \\\\\n  \\strline{\\str{choice}~s~t}{left-biased choice} \\\\\n\n  \\strlinea{repeat}{s}{iteration (+)} \\\\\n  \\strlinea{any}{s}{iteration (*)} \\\\\n  \n  \\strlinea{subterm}{s}{one subterm} \\\\\n  \\strlinea{subterms}{s}{all subterms} \\\\\n  \\strlinea{innermost}{s}{innermost first} \\\\\n  \\strlinea{outermost}{s}{outermost first}\\\\\n  \\strlinea{bottomup}{s}{bottom-up} \\\\\n  \\strlinea{topdown}{s}{top-down} \\\\\n\n  \\strlinea{hints}{hintdb}{apply hint} \\\\\n  \\strlinea{terms}{c \\ldots c}{any of the terms}\\\\\n  \\strlinea{eval}{redexpr}{apply reduction}\\\\\n  \\strlinea{fold}{c}{fold expression}\n\\end{array}\\]\n\nActually a few of these are defined in term of the others using\na primitive fixpoint operator:\n\n\\[\\begin{array}{lcl}\n  \\str{try}~s & = & \\str{choice}~s~\\str{id} \\\\\n  \\str{any}~s & = & \\str{fix}~u. \\str{try}~(s~\\str{;}~u) \\\\\n  \\str{repeat}~s & = & s~\\str{;}~\\str{any}~s \\\\\n  \\str{bottomup}~s & = &\n  \\str{fix}~bu. (\\str{choice}~(\\str{progress}~(\\str{subterms}~bu))~s)~\\str{;}~\\str{try}~bu \\\\\n  \\str{topdown}~s & = &\n  \\str{fix}~td. (\\str{choice}~s~(\\str{progress}~(\\str{subterms}~td)))~\\str{;}~\\str{try}~td \\\\\n  \\str{innermost}~s & = &  \\str{fix}~i. (\\str{choice}~(\\str{subterm}~i)~s) \\\\\n  \\str{outermost}~s & = &\n  \\str{fix}~o. (\\str{choice}~s~(\\str{subterm}~o))\n\\end{array}\\]\n\nThe basic control strategy semantics are straightforward: strategies are\napplied to subterms of the term to rewrite, starting from the root of\nthe term. The lemma strategies unify the left-hand-side of the\nlemma with the current subterm and on success rewrite it to the\nright-hand-side. Composition can be used to continue rewriting on the\ncurrent subterm. The fail strategy always fails while the identity\nstrategy succeeds without making progress. The reflexivity strategy\nsucceeds, making progress using a reflexivity proof of\nrewriting. Progress tests progress of the argument strategy and fails if\nno progress was made, while \\str{try} always succeeds, catching\nfailures. Choice is left-biased: it will launch the first strategy and\nfall back on the second one in case of failure. One can iterate a\nstrategy at least 1 time using \\str{repeat} and at least 0 times using\n\\str{any}.\n\nThe \\str{subterm} and \\str{subterms} strategies apply their argument\nstrategy $s$ to respectively one or all subterms of the current term\nunder consideration, left-to-right. \\str{subterm} stops at the first\nsubterm for which $s$ made progress. The composite strategies\n\\str{innermost} and \\str{outermost} perform a single innermost our outermost\nrewrite using their argument strategy. Their counterparts\n\\str{bottomup} and \\str{topdown} perform as many rewritings as possible,\nstarting from the bottom or the top of the term. \n\nHint databases created for \\texttt{autorewrite} can also be used by\n\\texttt{rewrite\\_strat} using the \\str{hints} strategy that applies any\nof the lemmas at the current subterm. The \\str{terms} strategy takes the\nlemma names directly as arguments. The \\str{eval} strategy expects a\nreduction expression (see \\S\\ref{Conversion-tactics}) and succeeds if it\nreduces the subterm under consideration. The \\str{fold} strategy takes a\nterm $c$ and tries to \\emph{unify} it to the current subterm, converting\nit to $c$ on success, it is stronger than the tactic \\texttt{fold}. \n\n\n\\subsection{Usage}\n\\tacindex{rewrite\\_strat}\n\n\\texttt{rewrite\\_strat}~\\textit{s}~\\zeroone{\\texttt{in} \\textit{ident}}: \n\n  Rewrite using the strategy \\textit{s} in hypothesis \\textit{ident}\n  or the conclusion.\n\n  \\begin{ErrMsgs}\n  \\item  \\errindex{Nothing to rewrite}. If the strategy failed. \n  \\item  \\errindex{No progress made}. If the strategy succeeded but\n    made no progress.\n  \\item  \\errindex{Unable to satisfy the rewriting constraints}. \n    If the strategy succeeded and made progress but the corresponding\n    rewriting constraints are not satisfied.\n  \\end{ErrMsgs}\n  \n\nThe \\texttt{setoid\\_rewrite}~c tactic is basically equivalent to \n\\texttt{rewrite\\_strat}~(\\str{outermost}~c).\n\n\n\n\n\n%%% Local Variables: \n%%% mode: latex\n%%% TeX-master: \"Reference-Manual\"\n%%% End: \n", "meta": {"hexsha": "2c9602a2297caf59b5b8b47f199252b92d3d3722", "size": 38510, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "presentations/coq-workshop-2014-coq/doc/refman/Setoid.tex", "max_stars_repo_name": "JasonGross/test-broken-tar", "max_stars_repo_head_hexsha": "6b52b8532879df53386b0f5413485888a1aa886a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "presentations/coq-workshop-2014-coq/doc/refman/Setoid.tex", "max_issues_repo_name": "JasonGross/test-broken-tar", "max_issues_repo_head_hexsha": "6b52b8532879df53386b0f5413485888a1aa886a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "presentations/coq-workshop-2014-coq/doc/refman/Setoid.tex", "max_forks_repo_name": "JasonGross/test-broken-tar", "max_forks_repo_head_hexsha": "6b52b8532879df53386b0f5413485888a1aa886a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.7363420428, "max_line_length": 120, "alphanum_fraction": 0.7574655934, "num_tokens": 10703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073507867328, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.32424668419917785}}
{"text": "\\vsssub\n\\subsubsection{~Second-order spectrum and free infragravity waves} \\label{sec:IG1}\n\\vsssub\n\n\\opthead{IG1}{\\ws}{F. Ardhuin}\n\n\\noindent \nWARNING: {\\it A bug has been identified with IG wave sources in unstructured grids. \nA model patch using an older version of the code will be provided shortly.}\n\nThe linear dispersion relation used in section \\ref{sec:intro} is a good\napproximation for most of the wave energy but a significant part of the\nspectrum at high frequencies, with typical frequencies above three times the\nwindsea wave peak \\citep[e.g.][]{rep:Lec13}.  In shallow water, another\nstrongly nonlinear part of the spectrum is found at very low frequencies,\nwhich are called infragravity waves.\n\nIn the case of horizontally homogeneous conditions over a flat bottom, both\nlow and high frequency non-linear components can be estimated from the linear\nwave spectrum, using perturbation theory \\citep[e.g.][]{art:Has62}. Also, the\nnon-linear evolution of a homogeneous wave field is better described in terms\nof this `linearized spectrum'. It is thus practical to work with this\n`linearized spectrum' and convert to the observable spectrum that contains\nnon-linear components when post-processing the model results. One method to\nperform this transformation is a canonical transformation proposed by\n\\cite{art:Kra94}. The properties of this transformation were further explored\nby \\cite{art:Jan09} and implemented for post-processing in the ECMWF version\nof the WAM model.\n\nThe code for the canonical transform written by P. Janssen was interfaced with\n\\ws.  Using the {\\code IG1} switch and setting the parameter {\\code IGADDOUTP\n= 2} in the {\\F SIG1} namelist, this canonical transformed, which conserves\nenergy, will be used for the output point spectra.  If {\\code IGADDOUTP = 1},\nthen the second-order spectrum is added on top of the model spectrum using the\ntheory \\citep[e.g.][]{art:Has62}. That option does not conserve energy and\nis not consistent at high frequency because the quasi-linear term in the\nsecond-order spectrum are ignored \\citep{art:Jan09}.\n\nHowever, when comparing to measurements, one should be aware that different\nmeasuring devices have different responses to the nonlinear part of the\nspectrum. In particular, surface-following buoys also linearize the spectrum,\nand the second-order pressure field is not related to the second-order\nelevation via the relations used for linear waves. The canonical transform is\nthus only applicable for wave gauges that measure elevation at a fixed\nlocation.\n\nWhen the wave field is not homogeneous, the nonlinear properties of the waves\nlead to an exchange of energy between different modes. In shallow water this\nusually results in the transfer of energy to infragravity waves, that are\nreleased along shorelines and travel as free waves. The {\\code IG1} switch\nallows the parameterization of that effect with several methods.  These are\nvery crude parameterizations compared to the full hydrodynamic solution that\nwould require solving the bispectral evolution across the surf zone at a very\nhigh spatial resolution \\citep[e.g.][]{art:HB97}. The default namelist settings\ncorrespond to the parameterization presented by \\cite{art:Aea14}, with minor adjustments in version 6.06. \nThe power in the definition of $\\widehat{E}_{IG}(f)$ was changed from $f^{1.5}$ to $f^{1.0}$, with \nan associated adjuspent of the constant fro 0.015 to 0.013. \n\n In practice the free infragravity wave energy is\nadded via the $S_{ref}$ source term, by setting the {\\code SIG1} namelist\n{\\code IGSOURCE} to 1 or 2.\n\nIn the first method, activated with {\\code IGSOURCE =1}, the second-order\nspectrum is computed using either the Hasselmann perturbation ({\\code IGMETHOD\n= 1}) or the canonical transform (any other value of {\\code IGMETHOD}) as described \nin \\cite{art:Jan09}. This\napproach may lead to better directional distribution of IG wave energy but it\nis still being tested.  The second method, activated with {\\code IGSOURCE =\n2}, and the free IG spectrum is given by the following expressions,\n\n\\begin{eqnarray}\n A_{IG} & =&    H_s T_{m0,-2}^2\\label{eq:IGfit0}, \\\\\n\\widehat{E}_{IG}(f)& = & 1.2 \\alpha_1^2 \\frac{k g^2}{c_g 2 \\pi f} \\frac{(A_{IG}/4)^2}{\\Delta_f}  \n\\left[\\min( 1., 0.013\\mathrm{Hz}/ f)\\right]^{1.0}, \\label{eq:IGfit1} \\\\\n \\widehat{E}_{IG}(f,\\theta) & = & \\widehat{E}_{IG}(f) / (2 \\pi ),\n\\label{eq:fit2} \n\\end{eqnarray}\n\n\\noindent\nwhere the mean period is defined as $ T_{m0,-2} =\\sqrt{m_{-2}/m_{0}}$ with the\nmoments\n\n\\begin{equation}\n m_n= \\int_{f_{min}~\\mathrm{Hz}}^{0.5~\\mathrm{Hz}} E(f) f^n {\\mathrm d}f,\\label{eq:mn}\n\\end{equation}\n\n\\noindent\nand the empirical coefficient $\\alpha_1$ is of the order of\n$10^{-3}$~s$^{-1}$, and is set by the {\\code SIG1} namelist parameter {\\code\nIGEMPIRICAL}. The minimum frequency $f_{min}$ used to define $ T_{m0,-2}$ is\nset by the namelist parameter {\\code IGMAXFREQ} and it is also the maximum\nfrequency of the IG band over which this source of energy is applied.  Also,\nin this band the IG energy at the coast can be added on top of pre-existing\nenergy, or the pre-existing energy can be reset to zero. That latter behavior\nis the default and controlled by {\\code IGBCOVERWRITE = 1}. For other choices,\n({\\code IGBCOVERWRITE = 0}), the results are very sensitive to the maximum\nshoreline reflection coefficient allowed ({\\code REFRMAX} parameter in\nnamelist {\\F REF1}).\n\nFinally, IG energy can also be added for frequencies beyond $f_{min}$, this is the default behavior \nand it is activated by setting {\\code IGSWELLMAX = TRUE}.  For that part of the IG wave\nfield, the IG wave source is now reduced by a factor 4 which is now hard-coded\nin {\\file w3ref1md.ftn}. This should be adjusted together with the maximum reflection \nwhich is defined by the {\\F REF1} namelist parameter {\\code\nREFRMAX}. In the present version, the option {\\code IGSWELLMAX = TRUE} does \nnot work well with unstructured grids. We thus advise to use \n{\\code IGSWELLMAX = FALSE} for these grids, this will unfortunately lead \nto a spectral gap between the IG band and the swell-windsea band. \n\n\n\n\n", "meta": {"hexsha": "75c4c958c95830157e3db53da14e048c63f0d5f8", "size": 6092, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "WW3/manual/eqs/IG1.tex", "max_stars_repo_name": "minsukji/ci-debug", "max_stars_repo_head_hexsha": "3e8bbbe6652b702b61d2896612f6aa8e4aa6c803", "max_stars_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WW3/manual/eqs/IG1.tex", "max_issues_repo_name": "minsukji/ci-debug", "max_issues_repo_head_hexsha": "3e8bbbe6652b702b61d2896612f6aa8e4aa6c803", "max_issues_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-05-31T15:49:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-04T14:17:45.000Z", "max_forks_repo_path": "WW3/manual/eqs/IG1.tex", "max_forks_repo_name": "minsukji/ci-debug", "max_forks_repo_head_hexsha": "3e8bbbe6652b702b61d2896612f6aa8e4aa6c803", "max_forks_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-01T09:29:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T09:29:46.000Z", "avg_line_length": 53.9115044248, "max_line_length": 106, "alphanum_fraction": 0.7649376231, "num_tokens": 1611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.32423697317916367}}
{"text": "\\subsection{Gaussian basis sets}\n\\label{sec:gaussianbasis}\n\nIn this section we describe the use of localized basis sets to expand the \\texttt{sposet}. The general form of a single particle orbital in this case is given by:\n\\begin{equation}\n\\phi_i(\\vec{r}) = \\sum_k C_{i,k} \\ \\eta_k(\\vec{r}),\n\\end{equation}\nwhere $\\{\\eta_k(\\vec{r})\\}$ is a set of M atom-centered basis\nfunctions and $C_{i,k}$ is a coefficient matrix. This \\texttt{sposet}\nshould be used in calculations of finite systems employing an\natom-centered basis set and is typically generated by the\n\\textit{convert4qmc} converter.  Examples include calculations of\nmolecules using gaussian basis sets or slater-type basis\nfunctions. Initial support for periodic systems is described in Sec.\n\\ref{chap:LCAO}. Even though this section is called \"Gaussian basis\nsets\" (by far the most common atom-centered basis set), QMCPACK works\nwith any atom-centered basis set built based on either spherical\nharmonic angular functions or cartesian angular expansions. The radial\nfunctions in the basis set can be expanded in either gaussian\nfunctions, slater-type functions or numerical radial functions.\n\nIn this section we describe the input sections for the atom-centered basis set and the \\texttt{sposet} for a single slater determinant trial wavefunction. The input sections for multideterminant trial wavefunctions are described in section \\ref{sec:multideterminants}. The basic structure for the input block of a single slater determinant is given in Listing \\ref{listing:lcaosposet}.\nA list of options for \\texttt{determinantset} associated with this \\texttt{sposet} is given in Table \\ref{table:determinantset}.\n\n\\begin{minipage}{\\linewidth}\n\\begin{lstlisting}[style=XML,caption=Basic input block for a single determinant trial wavefunction using a sposet expanded on an atom-centered basis set. \\label{listing:lcaosposet}]\n<wavefunction id=\"psi0\" target=\"e\">\n    <determinantset>\n      <basisset>\n        ...\n      </basisset>\n      <slaterdeterminant>\n        ...\n      </slaterdeterminant>\n    </determinantset>    \n</wavefunction>\n\\end{lstlisting}\n\\end{minipage}\n\n\\begin{table}[h]\n\\begin{center}\n\\begin{tabularx}{\\textwidth}{l l l l l l }\n\\hline\n\\multicolumn{6}{l}{\\texttt{determinantset} element} \\\\\n\\hline\n\\multicolumn{2}{l}{parent elements:} & \\multicolumn{4}{l}{\\texttt{wavefunction}}\\\\\n\\multicolumn{2}{l}{child  elements:} & \\multicolumn{4}{l}{\\texttt{basisset,slaterdeterminant,sposet,multideterminant}}\\\\\n\\multicolumn{2}{l}{attribute      :} & \\multicolumn{4}{l}{}\\\\\n   &   \\bfseries name              & \\bfseries datatype & \\bfseries values & \\bfseries default   & \\bfseries description \\\\\n   &   \\texttt{name}/\\texttt{id}   &  text              &  \\textit{any}    &  \"\"             & Name of determinant set. \\\\\n   &   \\texttt{type}                    &  text               &   see below   &   \"\"            &  Type of \\texttt{sposet}. \\\\\n   &   \\texttt{keyword}             &  text               &   NMO,GTO,STO   &  NMO        & Type of orbital set generated. \\\\  \n   &   \\texttt{transform}           &  text               &   yes/no          &  yes         &  Transform to numerical radial functions?  \\\\\n   &   \\texttt{source}               &  text               &   \\textit{any}    &  ion0        & Particle set with the position of atom centers. \\\\\n   &   \\texttt{cuspCorrection}  &  text               &   yes/no          &  no         & Apply cusp correction scheme to \\texttt{sposet}? \\\\\n%   &   \\texttt{cuspInfo}               &  text               &   \\textit{any}    &  \"\"             & File with saved cusp data. \\\\       \n  \\hline\n\\end{tabularx}\n\\end{center}\n\\caption{Options for the \\texttt{determinantset} xml-block associated with atom-centered single particle orbital sets.}\n\\label{table:determinantset}\n\\end{table}\n\nThe definition of the set of atom-centered basis functions is given by the \\texttt{basisset} block, while the sposet is defined within \\texttt{slaterdeterminant}. The basisset input block is composed from a collection of \\texttt{atomicBasisSet} input blocks, one for each atomic species in the simulation where basis functions are centered. The general structure for \\texttt{basisset} and \\texttt{atomicBasisSet} are given in Listing \\ref{listing:basisset}, while the corresponding lists of options are given in Tables \\ref{table:basisset} and \\ref{table:atomicBasisSet}.\n\n\\begin{minipage}{\\linewidth}\n\\begin{lstlisting}[style=XML,caption=Basic input block for \\texttt{basisset}.\\label{listing:basisset}]\n      <basisset name=\"LCAOBSet\">\n        <atomicBasisSet name=\"Gaussian-G2\" angular=\"cartesian\" elementType=\"C\" normalized=\"no\">\n          <grid type=\"log\" ri=\"1.e-6\" rf=\"1.e2\" npts=\"1001\"/>\n          <basisGroup rid=\"C00\" n=\"0\" l=\"0\" type=\"Gaussian\">\n            <radfunc exponent=\"5.134400000000e-02\" contraction=\"1.399098787100e-02\"/>\n            ...\n          </basisGroup>\n          ...              \n        </atomicBasisSet>\n        <atomicBasisSet name=\"Gaussian-G2\" angular=\"cartesian\" type=\"Gaussian\" elementType=\"C\" normalized=\"no\">\n          ...              \n        </atomicBasisSet>\n        ...\n      </basisset>\n\\end{lstlisting}\n\\end{minipage}\n\n\\begin{table}[h]\n\\begin{center}\n\\begin{tabularx}{\\textwidth}{l l l l l l }\n\\hline\n\\multicolumn{6}{l}{\\texttt{basisset} element} \\\\\n\\hline\n\\multicolumn{2}{l}{parent elements:} & \\multicolumn{4}{l}{\\texttt{determinantset}}\\\\\n\\multicolumn{2}{l}{child  elements:} & \\multicolumn{4}{l}{\\texttt{atomicBasisSet}}\\\\\n\\multicolumn{2}{l}{attribute      :} & \\multicolumn{4}{l}{}\\\\\n   &   \\bfseries name              & \\bfseries datatype & \\bfseries values & \\bfseries default   & \\bfseries description \\\\\n   &   \\texttt{name}/\\texttt{id}   &  text              &  \\textit{any}    &  \"\"                & Name of atom-centered basis set. \\\\\n  \\hline\n\\end{tabularx}\n\\end{center}\n\\caption{Options for the \\texttt{basisset} xml-block associated with atom-centered single particle orbital sets.}\n\\label{table:basisset}\n\\end{table}\n\n\\begin{table}[h]\n\\begin{center}\n\\begin{tabularx}{\\textwidth}{l l l l l l }\n\\hline\n\\multicolumn{6}{l}{\\texttt{atomicBasisSet} element} \\\\\n\\hline\n\\multicolumn{2}{l}{parent elements:} & \\multicolumn{4}{l}{\\texttt{basisset}}\\\\\n\\multicolumn{2}{l}{child  elements:} & \\multicolumn{4}{l}{\\texttt{grid,basisGroup}}\\\\\n\\multicolumn{2}{l}{attribute      :} & \\multicolumn{4}{l}{}\\\\\n   &   \\bfseries name              & \\bfseries datatype & \\bfseries values & \\bfseries default   & \\bfseries description \\\\\n   &   \\texttt{name}/\\texttt{id}   &  text              &  \\textit{any}    &  \"\"                & Name of atomic basis set. \\\\\n   &   \\texttt{angular}               &  text              &  see below    &  default       & Type of angular functions.  \\\\\n%   &   \\texttt{type}                    &  text              &  see below    &  \"\"                &  Type of input radial function. \\\\\n   &   \\texttt{expandYlm}         &  text              &  see below   &  yes                &  Expand Ylm shells? \\\\  \n   &   \\texttt{expM}                  &  text              &  see below   &  yes                &  Add sign for $(-1)^{m}$? \\\\  \n   &   \\texttt{elementType/species}   &  text  &  \\textit{any}    &  e                &  Atomic species where functions are centered. \\\\\n   &   \\texttt{normalized}         &  text              &  yes/no   &  yes                &  Are single particle functions normalized? \\\\   \n  \\hline\n\\end{tabularx}\n\\end{center}\n\\caption{Options for the \\texttt{atomicBasisSet} xml-block.}\n\\label{table:atomicBasisSet}\n\\end{table}\n\n\\begin{table}[h]\n\\begin{center}\n\\begin{tabularx}{\\textwidth}{l l l l l l }\n\\hline\n\\multicolumn{6}{l}{\\texttt{basisGroup} element} \\\\\n\\hline\n\\multicolumn{2}{l}{parent elements:} & \\multicolumn{4}{l}{\\texttt{atomicBasisSet}}\\\\\n\\multicolumn{2}{l}{child  elements:} & \\multicolumn{4}{l}{\\texttt{radfunc}}\\\\\n\\multicolumn{2}{l}{attribute      :} & \\multicolumn{4}{l}{}\\\\\n   &   \\bfseries name              & \\bfseries datatype & \\bfseries values & \\bfseries default   & \\bfseries description \\\\\n   &   \\texttt{rid}/\\texttt{id}   &  text              &  \\textit{any}    &  \"\"                & Name of the basisGroup. \\\\\n   &   \\texttt{type}                    &  text            &  \\textit{any}    &  \"\"                & Type of basisGroup. \\\\\n   &   \\texttt{n/l/m/s}                 &  integer           &  \\textit{any}    &  0                & Quantum numbers of basisGroup. \\\\\n  \\hline\n\\end{tabularx}\n\\end{center}\n\\caption{Options for the \\texttt{basisGroup} xml-block.}\n\\label{table:basisGroup}\n\\end{table}\n\n\\begin{minipage}{\\linewidth}\n\\begin{lstlisting}[style=XML,caption=Basic input block for \\texttt{slaterdeterminant} with an atom-centered \\texttt{sposet}.\\label{listing:slaterdeterminant}]\n      <slaterdeterminant>\n      </slaterdeterminant>\n\\end{lstlisting}\n\\end{minipage}\n\n\\begin{table}[h]\n\\begin{center}\n\\begin{tabularx}{\\textwidth}{l l l l l l }\n\\hline\n\\multicolumn{6}{l}{\\texttt{} element} \\\\\n\\hline\n\\multicolumn{2}{l}{parent elements:} & \\multicolumn{4}{l}{\\texttt{}}\\\\\n\\multicolumn{2}{l}{child  elements:} & \\multicolumn{4}{l}{\\texttt{}}\\\\\n\\multicolumn{2}{l}{attribute      :} & \\multicolumn{4}{l}{}\\\\\n   &   \\bfseries name              & \\bfseries datatype & \\bfseries values & \\bfseries default   & \\bfseries description \\\\\n   &   \\texttt{name}/\\texttt{id}   &  text              &  \\textit{any}    &  \"\"                & Name of determinant set \\\\\n   &   \\texttt{}                    &  text              &  \\textit{any}    &  \"\"                &  \\\\\n  \\hline\n\\end{tabularx}\n\\end{center}\n\\end{table}\n\n\\subsubsection{Detailed description of attributes:}\n\nIn the following, we give a more detailed description of all the options presented in the various xml-blocks described in this section. Only non-trivial attributes are described below. Those with simple yes/no options and whose description above is enough to explain the intended behavior are not included. \n\n\\hspace{1mm} \\\\\n\n\\texttt{determinantset} attributes:\n\n\\begin{itemize}\n\\item \\texttt{type} \\\\\nType of sposet. For atom-centered based sposets, use type=\"MolecularOrbital\" or type=\"MO\". Other options describe elsewhere in this manual are \"spline\", \"composite\", \"pw\", \"heg\", \"linearopt\", etc.\n\\item \\texttt{keyword}/\\texttt{key} \\\\\nType of basis set generated, which doesn't necessarily match the type of the basis set on the input block. The three possible options are: NMO (numerical molecular orbitals), GTO (gaussian-type orbitals), STO (slater-type orbitals). The default option is NMO. By default, QMCPACK will generate numerical orbitals from both GTO and STO types and use cubic or quintic spline interpolation to evaluate the radial functions. This is typically more efficient than evaluating the radial functions in the native basis (gaussians or exponents) and allows for arbitrarily large contractions without any additional cost. To force the use of the native expansion (not recommended), use GTO or STO for each type of input basis set.\n\\item \\texttt{transform}\\\\\nRequest (or avoid) a transformation of the radial functions to NMO type. The default and recommended behavior is to transform to numerical radial functions. If \\texttt{transform} is set to \\textit{\"yes\"}, the option \\texttt{keyword} is ignored.  \n\\item \\texttt{cuspCorrection}\\\\\nEnable (disable) the use of the cusp correction algorithm (CASINO REFERENCE) for a \\texttt{basisset} built with GTO functions. The algorithm is implemented as described in (CASINO REFERENCE) and only works with transform=\"yes\" and an input GTO basis set. No further input is needed. \n\\end{itemize}\n\n\\texttt{atomicBasisSet} attributes:\n\n\\begin{itemize}\n\\item \\texttt{name/id}\\\\\nName of the basis set. Names should be unique.\n\\item \\texttt{angular}\\\\\nType of angular functions used in the expansion. In general, two angular basis functions are allowed: \"spherical\" (for spherical Ylm functions) and \"cartesian\" (for functions of the type $x^{n}y^{m}z^{l}$).  \n%\\item \\texttt{type}\\\\ Type of input radial functions. Options are: \"Numerical\" (for radial functions on a numerical radial grid), \"Gaussian\" (for an expansion in gaussian functions) and \"\" \n\\item \\texttt{expandYlm}\\\\\nDetermines whether each basis group is expanded across the corresponding shell of m values (for spherical type) or consistent powers (for cartesian functions). Options:\n\\begin{itemize}\n\\item \"No\": Do not expand angular functions across corresponding angular shell.\n\\item \"Gaussian\": Expand according to Gaussian03 format. This function is only compatible with angular=\"spherical\". For a given input (l,m), the resulting order of the angular functions becomes: (1,-1,0) for l=1 and (0,1,-1,2,-2,...,l,-l) for general l.\n\\item \"Natural\": Expand angular functions according to (-l,-l+1,...,l-1,l). \n\\item \"Gamess\": Expand according to Gamess' format for cartesian functions. Notice that this option is only compatible with angular=\"cartesian\". If angular=\"cartesian\" is used, this option is not necessary.\n\\end{itemize}\n\\item \\texttt{expM}\\\\ \nDetermines whether the sign of the spherical Ylm function associated with m ($-1^{m}$) is included in the coefficient matrix or not.\n\\item \\texttt{elementType/species}\\\\\nName of the species where basis functions are centered. Only one atomicBasisSet block is allowed per species. Additional blocks are ignored. The corresponding species must exist in the \\texttt{particleset} given as the \\texttt{source} option to \\texttt{determinantset}. Basis functions for all the atoms of the corresponding species are included in the basis set, based on the order of atoms in the \\texttt{particleset}.\n\\end{itemize}\n\n\\texttt{basisGroup} attributes:\n\n\\begin{itemize}\n\\item \\texttt{type}\\\\\n  Type of input basis radial function. Notice that this refers to the type of radial function in the input xml-block, which might not match the radial function generated internally and used in the calculation (if \\texttt{transform} is set to \"yes\"). Also notice that different \\texttt{basisGroup} blocks within a given \\texttt{atomicBasisSet} can have different \\texttt{type}.\n\\item \\texttt{n/l/m/s}\\\\\n  Quantum numbers of the basis function. Notice that if \\texttt{expandYlm} is set to \\textit{\"yes\"} in \\texttt{atomicBasisSet}, a full shell of basis functions with the appropriate values of \\textit{\"m\"} will be defined for the corresponding value of \\textit{\"l\"}. Otherwise a single basis function will be given for the specific combination of \\textit{\"(l,m)\"}. \n\\end{itemize}\n\n\\texttt{radfunc} attributes for \\texttt{type}=\\textit{\"Gaussian\"}:\n\n\\begin{itemize}\n\\item \\texttt{}\\\\\n\\end{itemize}\n\n\\texttt{slaterdeterminant} attributes:\n\n\\begin{itemize}\n\\item \\texttt{}\\\\\n\\end{itemize}\n\n\n\n", "meta": {"hexsha": "fac9048322632845d0f5732e78f3d268714e0f85", "size": 14647, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "manual/spo_gaussian.tex", "max_stars_repo_name": "bwvdg/qmcpack", "max_stars_repo_head_hexsha": "cd09fc54b36de2579c9802f5e64b7ec15506f3c3", "max_stars_repo_licenses": ["NCSA"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "manual/spo_gaussian.tex", "max_issues_repo_name": "bwvdg/qmcpack", "max_issues_repo_head_hexsha": "cd09fc54b36de2579c9802f5e64b7ec15506f3c3", "max_issues_repo_licenses": ["NCSA"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-10T15:33:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-10T15:35:59.000Z", "max_forks_repo_path": "manual/spo_gaussian.tex", "max_forks_repo_name": "bwvdg/qmcpack", "max_forks_repo_head_hexsha": "cd09fc54b36de2579c9802f5e64b7ec15506f3c3", "max_forks_repo_licenses": ["NCSA"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 62.3276595745, "max_line_length": 719, "alphanum_fraction": 0.6756332355, "num_tokens": 4141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3241265495139945}}
{"text": "\\section{Configuration file}\n\\label{S:CFGFile}\nThe configuration file is a \\MATLAB{} script utilized for initializing the project (see Figure \\ref{fig:cfgfile}).\nThe name of a configuration file can be given as an input to the function   \\lstinline[basicstyle = \\mlttfamily \\small ]!OpenBLDM_main.m!, as mentionned in Section~\\ref{SS:OpenBDLMinput}.\nThe configuration file must follow a specific structures, which includes 6 sections: Project name, Data, Model structure, Model parameters, Initial states values and Options.\nThe first three sections are mandatory, while the last three sections are optional.\n\\begin{figure}[h!]\n\\centering\n\\includegraphics[width=140mm]{docfigs/Example_DISPSIM/listing/config_file_1.pdf}\n\\caption{Exemple of configuration file}\n\\label{fig:cfgfile}\n\\end{figure}\n\n\\subsection{Project name}\nThis section of the configuration file defines the name of the project as a vector of characters stored in the field \\lstinline[basicstyle = \\mlttfamily \\small ]!ProjectName! of the \\MATLAB{} variable \\lstinline[basicstyle = \\mlttfamily \\small ]!misc!.\n\n\\subsection{Data}\n\nThis section of the configuration file defines information required for loading the data from a \\lstinline[basicstyle = \\mlttfamily \\small ]!DATA_! file located in ``/data/mat'' subfolder.\nThe file must follow the format described in Section~\\ref{SS:MATInput}.\nThe timestamp values, the amplitude values and the label values must be stored in the fields \\lstinline[basicstyle = \\mlttfamily \\small]!timestamps!, \\lstinline[basicstyle = \\mlttfamily \\small]!values!, and \\lstinline[basicstyle = \\mlttfamily \\small]!labels! of the \\MATLAB{} structure named \\lstinline[basicstyle = \\mlttfamily \\small]!data!.\n\n\\subsection{Model structure}\n\\label{SS:ModelComponents}\nThis part of the configuration file defines the model in a \\MATLAB{} structure named \\lstinline[basicstyle = \\mlttfamily \\small]!model.component!.\nThe structure \\lstinline[basicstyle = \\mlttfamily \\small]!model.component! must have three fields, named \\lstinline[basicstyle = \\mlttfamily \\small]!model.component.block!, \\lstinline[basicstyle = \\mlttfamily \\small]!model.component.ic!, and \\lstinline[basicstyle = \\mlttfamily \\small]!model.component.const!.\n\n\\begin{itemize}\n\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!model.component.block!: it defines the block components associated with each time series.\nThe field \\lstinline[basicstyle = \\mlttfamily \\small ]!block! stores $1\\times \\mathtt{S}$ cell array, where $\\mathtt{S} = \\{1,2 \\}$ is the number of model classes.\nEach cell array is a $1\\times \\mathtt{D}$ cell array of matrice, where $\\mathtt{D}$ is the number of time series.\nEach block component is associated with a reference number:\n\\begin{itemize}\n\\item 11: Local level \n\\item 12: Local trend\n\\item 13: Local acceleration\n\\item 21: Local level compatible with local trend\n\\item 22: Local level compatible with local acceleration\n\\item 23: Local trend compatible with local acceleration\n\\item 31: Periodic\n\\item 41: First-order autoregressive\n\\item 51: Kernel regression\n\\item 61: Level intervention\n\\end{itemize}\n\n\\item  \\lstinline[basicstyle = \\mlttfamily \\small ]!model.component.const!: it constrains model parameters between the block components from different model classes.\nThe field \\lstinline[basicstyle = \\mlttfamily \\small ]!const! stores a $1\\times \\mathtt{S}$ cell array, where $\\mathtt{S} = \\{1, 2 \\}$ is the total number of model classes.\nIt is defined only if $\\mathtt{S} = 2$.\nThe first cell is empty, and the second cell is a $1\\times \\mathtt{D}$ cell array of array, where $\\mathtt{D}$ is the number of time series.\nThe array contains $0$ and $1$ to indicate which block components of the second model class has the same model parameters than the corresponding component of the first model class. \nA value of $1$ indicates that the model parameters are constrained between the block components of the two model classes, $0$ otherwise.\n\n\\item  \\lstinline[basicstyle = \\mlttfamily \\small ]!model.component.ic!:  it defines the dependencies among the time series.\nThe field \\lstinline[basicstyle = \\mlttfamily \\small ]!ic! stores a $1\\times \\mathtt{D}$ cell array of $1\\times (\\mathtt{D}-1)$ matrix, where $\\mathtt{D}$ is the number of time series.\nEach time series depend on the time series corresponding to the indexes given in the $\\mathtt{D}$ arrays.\nIf the array is empty, the time series are considered independent by default.\n\n\\end{itemize}\n\n\n\\subsection{Model parameters}\n\\label{SS:ModelParamProperties}\nThis part of the configuration file aims at defining the model parameter properties which are stored in the field named \\lstinline[basicstyle = \\mlttfamily \\small ]!model.param_properties! of the \\MATLAB{} structure \\lstinline[basicstyle = \\mlttfamily \\small ]!model!.\nThe field \\lstinline[basicstyle = \\mlttfamily \\small ]!model.param_properties! stores $\\mathtt{K} \\times 10$ cell array, where $\\mathtt{K}$ is the total number of model parameters.\n\\begin{itemize}\n\\item column 1 must be a character vector that gives the name of the model parameters (e.g.  \\lstinline[basicstyle = \\mlttfamily \\small ]!sigma_w!). \n\\item column 2 must be a character vector that gives the reference name of the block associated with the parameter (e.g \\lstinline[basicstyle = \\mlttfamily \\small ]!LL!, see Section~\\ref{SS:BlockComponent}).\n\\item column 3 must be a character vector that gives the index corresponding to the model class associated with the parameter (e.g  either \\lstinline[basicstyle = \\mlttfamily \\small ]!1! or \\lstinline[basicstyle = \\mlttfamily \\small ]!2!) (see~\\ref{SS:THSKF}).\n\\item column 4 must be a character vector that gives the index corresponding to the observation associated with the parameter (e.g \\lstinline[basicstyle = \\mlttfamily \\small ]!3!).\n\\item column 5 must be a $1\\times2$ array that gives the bound of the parameter (e.g \\lstinline[basicstyle = \\mlttfamily \\small ]![NaN, NaN]!,  \\lstinline[basicstyle = \\mlttfamily \\small ]![0, Inf]!, \\lstinline[basicstyle = \\mlttfamily \\small ]![0, 1]!). \nThe bounds are used to transform (if necessary) model parameters from a bounded to  an unbounded space during the optimization process (see Sections~\\ref{S:PARAMESTIMATION} and~\\ref{SS:THModelParameterEstimation}).\n\\item column 6 must be a character vector that gives the type of the prior used during the optimization process (e.g  either \\lstinline[basicstyle = \\mlttfamily \\small ]!N/A! or \\lstinline[basicstyle = \\mlttfamily \\small ]!normal!). \n\\lstinline[basicstyle = \\mlttfamily \\small ]!N/A! indicates that no prior is used (see Sections~\\ref{S:PARAMESTIMATION} and~\\ref{SS:THModelParameterEstimation}).\n\\item column 7 must be a real number that gives the mean of the prior when a prior of type \\lstinline[basicstyle = \\mlttfamily \\small ]!normal! is used, otherwise it must be set to \\lstinline[basicstyle = \\mlttfamily \\small ]!NaN! (see Sections~\\ref{S:PARAMESTIMATION} and~\\ref{SS:THModelParameterEstimation}).\n\\item column 8 must be a real number that gives the standard deviation of the prior when a prior of type \\lstinline[basicstyle = \\mlttfamily \\small ]!normal! is used, otherwise it must be set to \\lstinline[basicstyle = \\mlttfamily \\small ]!NaN! (see Sections~\\ref{S:PARAMESTIMATION} and~\\ref{SS:THModelParameterEstimation}).\n\\item column 9 must be a real number that gives the value of the model parameters.\n\\item column 10 must be an integer that gives the reference number of the model parameters. The model parameters which share the same reference number are constrained to each other.\n\\end{itemize}\n\n\\subsection{Initial states values}\n\\label{SS:InitialHS}\nThis part of the configuration file defines the initial states values (at time $t=0$).\nThe initial mean and covariance hidden states values are stored in the \\lstinline[basicstyle = \\mlttfamily \\small ]!model.initX! and \\lstinline[basicstyle = \\mlttfamily \\small ]!model.initV! fields.\nThe initial probability for the model class is stored in the field \\lstinline[basicstyle = \\mlttfamily \\small ]!model.initS!.\n\n\\begin{itemize}\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!model.initX!: $1\\times \\mathtt{S}$ cell array of array, where $\\mathtt{S} \\in \\{1, 2 \\}$ is the total number of model classes.\nEach array is $\\mathtt{L}\\times1$ array of real number that stores the initial mean values associated with each hidden states variables, where $\\mathtt{L}$ is the total number of hidden states variables associated with the model.\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!model.initV!: $1\\times \\mathtt{S}$ cell array of array, where $\\mathtt{S} \\in \\{1, 2 \\}$ is the total number of model classes.\nEach array is $\\mathtt{L}\\times\\mathtt{L}$ array of real number that stores the initial variance and covariances values associated with each hidden states variables.\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!model.initS!: $1\\times \\mathtt{S}$ cell array of array, where $\\mathtt{S} \\in \\{1, 2 \\}$ is the total number of model classes. \nEach array is $1\\times1$ array of real number that gives the initial probability for the model class.\n\\end{itemize}\n\n\\subsection{Options}\n\\label{SS:options}\nThis part of the configuration file defines the options that control different aspect of the software regarding the data pre-processing, optimization, hidden states estimation, and aspects related to graphical outputs.\nThe options are stored in the field named \\text{options} of the \\MATLAB{} variable \\lstinline[basicstyle = \\mlttfamily \\small ]!misc!.\n\\begin{itemize}\n\n\\item Options for the data pre-processing\n\n\\begin{itemize}\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.NaNThreshold!: real number that gives, in percent, the amount of missing data allowed at each time slice.\\\\Default: \\lstinline[basicstyle = \\mlttfamily \\small ]!100!.\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.Tolerance!: real number that gives the duration (in number of days) after which two timestamps are not considered equal. \\\\Default: $10^{-6}$.\n\n\\end{itemize}\n\n\n\\item Options for the model parameters estimation\n\n\\begin{itemize}\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.trainingPeriod!:  $1\\times2$ array of real number that defines the training period, given in number of days since the first timestamp. \\\\Default: \\lstinline[basicstyle = \\mlttfamily \\small ]![1 Inf]!. \n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.isParallel!: logical that triggers or not the parallel computation for approximating the gradient in the optimization procedure. Note that parallel computation requires the \\MATLAB{} \\emph{Parallel Computing Toolbox}. \\\\Default: \\lstinline[basicstyle = \\mlttfamily \\small ]!true!.\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.maxIterations!: integer that gives the maximum number of iterations for the optimization procedure. Newton-Raphson only. \\\\Default: \\lstinline[basicstyle = \\mlttfamily \\small ]!100!.\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.maxTime!: real number that gives, in minutes, the maximum amount of  time to spend for the optimization procedure. \\\\Default: \\lstinline[basicstyle = \\mlttfamily \\small ]!60!.\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.isMAP!: logical that triggers or not the Maximum A Posteriori (MAP) estimation of the model parameters during the optimization procedure. MAP estimation includes prior information about the model parameters. \\\\Default: \\lstinline[basicstyle = \\mlttfamily \\small ]!false!.\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.isPredCap!: logical so that if \\lstinline[basicstyle = \\mlttfamily \\small ]!isPredCap=true!, the Prediction Capacity (i.e. the log-likelihood over a test dataset) is used to drive the optimization process, otherwise the log-likelihood over the full dataset is used. This option is used only for Stochastic Gradient optimization. \\\\Default: \\lstinline[basicstyle = \\mlttfamily \\small ]!false!.\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.isLaplaceApprox!: logical so that if \\lstinline[basicstyle = \\mlttfamily \\small ]!isLaplaceApprox=true! the posterior covariance matrix is estimated using Laplace approximation around the optimized model parameters values. This option is used only for Newton-Raphson optimization. \\\\Default: \\lstinline[basicstyle = \\mlttfamily \\small ]!false!.\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.NRTerminationTolerance!: real value determining the termination tolerance for the Newton-Raphson algorithm. \\\\Default: $10^{-7}$.\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.NRLevelsLambdaRef!: integer that controls the number of trial loop for a parameter being optimized for theNewton-Raphson algorithm. \\\\Default: $4$.\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.isMute!: logical so that if \\lstinline[basicstyle = \\mlttfamily \\small ]!isMute=true!, no message are displayed on screen during the optimization procedure. \\\\Default: \\lstinline[basicstyle = \\mlttfamily \\small ]!false!.\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.maxEpochs!: integer that gives the maximum number of epochs the optimization procedure. This option is used only for Stochastic Gradient optimization. \\\\Default: \\lstinline[basicstyle = \\mlttfamily \\small ]!50!.\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.Optimizer!: vector of character that defines the optimizer for Stochastic Gradient algorithm. It must be either \\lstinline[basicstyle = \\mlttfamily \\small ]!'MMT'!, \\lstinline[basicstyle = \\mlttfamily \\small ]!'ADAM'!, \\lstinline[basicstyle = \\mlttfamily \\small ]!'MMTbeta'!, \\lstinline[basicstyle = \\mlttfamily \\small ]!'ADAMbeta'!. This option is used only for Stochastic Gradient optimization. \\\\Default: \\lstinline[basicstyle = \\mlttfamily \\small ]!'MMT'!.\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.SplitPercent!: real number that defines defines in percent the portion of the training data used for validation. \\\\Default: \\lstinline[basicstyle = \\mlttfamily \\small ]!30!.\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.MiniBatchSizePercent!: real number that defines defines the size of mini-batch, in percent of the training data. \\\\Default: \\lstinline[basicstyle = \\mlttfamily \\small ]!20!.\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.SGTerminationTolerance!: termination tolerance for the Stochastic gradient algorithm. This option is used only for Stochastic Gradient optimization. \\\\Default: \\lstinline[basicstyle = \\mlttfamily \\small ]!0.95!.\n\\end{itemize}\n\n\\item Options for the estimation\n\n\\begin{itemize}\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.MaxSizeEstimation!: real number that gives the maximum size, in Mb, for which the hidden states estimations are saved in the \\lstinline[basicstyle = \\mlttfamily \\small ]!PROJ_! file at the end of the analysis. \\\\Default: \\lstinline[basicstyle = \\mlttfamily \\small ]!100!.\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.MethodStateEstimation!: vector of character. It must be either \\lstinline[basicstyle = \\mlttfamily \\small ]!'kalman'! or \\lstinline[basicstyle = \\mlttfamily \\small ]!'UD'!. it gives the method used for the estimation of the hidden states. \\\\Default: \\lstinline[basicstyle = \\mlttfamily \\small ]!'kalman'!.\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.DataPercent!: real number that gives in percent the amount of data, starting at $t=1$ used for the estimation of the initial hidden states. \\\\Default: \\lstinline[basicstyle = \\mlttfamily \\small ]!100!.\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.KRNumberControlPoints!: integer that gives the number of control points used for the periodic kernel regression component (see Section~\\ref{SS:BlockComponent}). \\\\Default: \\lstinline[basicstyle = \\mlttfamily \\small ]!100!.\n\\end{itemize}\n\n\n\\item Options for the synthetic data creation\n\n\\begin{itemize}\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.Seed!: integer that controls the random number generation used to create synthetic data. Synthetic data created with the same seed are identical (useful to replicate results). If  \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.Seed=[]!, the seed is based on current time and therefore, a different sequence of random number  is generated at each run. \\\\Default: \\lstinline[basicstyle = \\mlttfamily \\small ]!12345!.\n\\end{itemize}\n\n\\item Options for the graphical outputs\n\n\\begin{itemize}\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.isPlotEstimations!: logical. if \\lstinline[basicstyle = \\mlttfamily \\small ]!isPlotEstimations=true!, figures plotting the estimation results popup on screen each time the hidden states are estimated. \\\\Default: \\lstinline[basicstyle = \\mlttfamily \\small ]!true!.\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.FigurePosition!: $1\\times4$ array of real number that gives the location and size of the drawable area, specified as a vector of the form [left bottom width height] in the current units of \\MATLAB{}. \\\\Default: \\lstinline[basicstyle = \\mlttfamily \\small ]![100, 100, 1300, 270]!\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.isSecondaryPlot!: logical. if \\lstinline[basicstyle = \\mlttfamily \\small ]!isSecondaryPlot=true!, a closeup over two weeks is plotted at the right of each figure. \\\\Default: \\lstinline[basicstyle = \\mlttfamily \\small ]!false!.\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.Subsample!: integer that controls the number of points that are displayed in the plots. The number of points to plot is divided by a factor given by the values of \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.Subsample!. \\\\Default: \\lstinline[basicstyle = \\mlttfamily \\small ]!1!.\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.Linewidth!: real number that controls the width of the line plotted in the figure. \\\\Default: \\lstinline[basicstyle = \\mlttfamily \\small ]!1!.\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.ndivx!: integer that controls the number of labels for abscissa x-axis in each figure. \\\\Default: \\lstinline[basicstyle = \\mlttfamily \\small ]!4!.\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.ndivy!: integer that controls the number of labels for ordinate y-axis in each figure. \\\\Default: \\lstinline[basicstyle = \\mlttfamily \\small ]!3!.\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.Xaxis_lag!: real number that gives in number of days the amount of time by which the x-axis is shifted on each figure. \\\\Default: \\lstinline[basicstyle = \\mlttfamily \\small ]!0!. \n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.isExportTEX!: logical so that if \\lstinline[basicstyle = \\mlttfamily \\small ]!isExportTEX=true!, figures are exported in \\LaTeX{} format. \\\\Default: \\lstinline[basicstyle = \\mlttfamily \\small ]!false!.\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.isExportPNG!: logical so that if \\lstinline[basicstyle = \\mlttfamily \\small ]!isExportPNG=true!,  figures are exported in PNG format. \\\\Default: \\lstinline[basicstyle = \\mlttfamily \\small ]!false!.\n\\item \\lstinline[basicstyle = \\mlttfamily \\small ]!misc.options.isExportPDF!: logical so that if \\lstinline[basicstyle = \\mlttfamily \\small ]!isExportPDF=true!,  figures are exported in PDF format. \\\\Default: \\lstinline[basicstyle = \\mlttfamily \\small ]!false!.\n\\end{itemize}\n\\end{itemize}", "meta": {"hexsha": "89df026766d9048357cdaa58611ea1b9d8c315c2", "size": 19595, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/pdf_doc/section/OpenBDLMConfigurationFile.tex", "max_stars_repo_name": "CivML-PolyMtl/OpenBDLM", "max_stars_repo_head_hexsha": "af395cea6d394b0d1fb91ce76ddda9d97c02318f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-05-19T23:42:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T17:32:11.000Z", "max_issues_repo_path": "doc/pdf_doc/section/OpenBDLMConfigurationFile.tex", "max_issues_repo_name": "bhargobdeka/OpenBDLM", "max_issues_repo_head_hexsha": "af395cea6d394b0d1fb91ce76ddda9d97c02318f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/pdf_doc/section/OpenBDLMConfigurationFile.tex", "max_forks_repo_name": "bhargobdeka/OpenBDLM", "max_forks_repo_head_hexsha": "af395cea6d394b0d1fb91ce76ddda9d97c02318f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-10-18T07:18:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T02:26:06.000Z", "avg_line_length": 120.9567901235, "max_line_length": 524, "alphanum_fraction": 0.7713192141, "num_tokens": 5213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926666143434, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3240334494690883}}
{"text": "\\documentclass[twoside]{article}\n\n\\usepackage{epsfig}\n\\usepackage{amssymb}\n\\usepackage{amsmath}\n\n\\setlength{\\oddsidemargin}{0.25 in}\n\\setlength{\\evensidemargin}{-0.25 in}\n\\setlength{\\topmargin}{-0.6 in}\n\\setlength{\\textwidth}{6.5 in}\n\\setlength{\\textheight}{8.5 in}\n\\setlength{\\headsep}{0.75 in}\n\\setlength{\\parindent}{0 in}\n\\setlength{\\parskip}{0.1 in}\n\n\\newtheorem{thm}{Theorem}[section]\n\\newtheorem{Defn}{Definition}[section]\n\n\\newcommand{\\lecture}[3]{\n   \\pagestyle{myheadings}\n   \\thispagestyle{plain}\n   \\newpage\n   \\setcounter{page}{1}\n   \\noindent\n   \\begin{center}\n   \\framebox{\n      \\vbox{\\vspace{2mm}\n    \\hbox to 6.28in { {\\bf  ~Probabilistic Graphical Models 10-708 Notes with Koller and Friedman Textbook\\hfill} }\n       \\vspace{6mm}\n       \\hbox to 6.28in { {\\Large \\hfill #1  \\hfill} }\n       \\vspace{6mm}\n       \\hbox to 6.28in { {\\it Lecturer: #2 \\hfill Scribes: #3} }\n      \\vspace{2mm}}\n   }\n   \\end{center}\n   \\markboth{#1}{#1}\n   \\vspace*{4mm}\n}\n\n\\begin{document}\n\n\\lecture{2 : Directed GMs: Bayesian Networks}{Eric P. Xing}{Xing JunJie} % Lecture name, Lecturer, Scribes\n\n\\section{Introduction}\n\nThe goal of establishing GMs (Graphical Models) is to represent a joint distribution \\(P\\) over some set of random variables \\(\\mathbf{\\chi} = \\{X_1,\\ldots,X_n\\}\\). Consider the simplest case where each variable is binary-valued, a joint distribution requires total \\(2^n - 1\\) numbers (minus 1 comes from sum-to-one constraint).This explicit representation of the joint distribution is unmanageable from every perspective\\footnote{The following mainly quotes from Koller andFriedman Textbook Ch.3}.\n\n\\begin{itemize}\n\\item \\textbf{Computationally}, it's very expensive to manipulate and too large to store in memory.\n\\item \\textbf{Cognitively}, it is impossible to acquire so many numbers from a human expert, and the numbers are very small and do not correspond to events that people can reasonably contemplate.\n\\item \\textbf{Statistically}, if we want to learn the distribution from date, we would need ridiculously large amounts of data to estimate this many parameters robustly.\n\\end{itemize}\n\nHowever, \\textbf{Bayesian Networks} are able to represent compact representations by exploiting \\textbf{Independence Properties}. \n\n\\section{The \\emph{student} Example}\n\nWe'll introduce perhaps the simplest example to see how \\textbf{independence assumptions} produce a very compact representation of a high-dimensional distribution.\n\nWe now assume that a company would like to hire some graduates. The company's goal is to hire intelligent employees, but there is no way to test intelligence directly. However, the company have access to student's SAT scores and course grades. Thus, our probability space is induced by three relevant random variables \\(I, S\\) and \\(G\\). Assuming that \\(G\\) takes on three values \\(g^1,g^2,g^3\\), representing grades \\(A, B\\) and \\(C\\), \\(I\\) takes on two values \\(i^0\\)(low intelligence), \\(i^1\\)(high intelligence), \\(S\\) takes on two values \\(s^0\\)(low score) and \\(s^1\\)(high score).\n\nWe can get some intuitive independences in this example. The student's intelligence is clearly correlated both with his SAT score and grade. The SAT score and grade are also not independent.If we on the fact that the student received a high score on his SAT, the chances that he gets a high grade in his class are also likely to increase. Thus, we assume that, for our distribution \\(P\\),\\[P(g^1\\ |\\ s^1) > P(g^1\\ |\\ s^0)\\]\n\nHowever, it's quite plausible that our distribution \\(P\\) satisfies a \\textbf{conditional independence property}. If we know that the student has high intelligence, a high grade on the SAT no longer gives us information about the student’s performance in the class. That is:\n\\[P(g\\ |\\ i^1,s^1) = P(g\\ |\\ i^1)\\]\nGenerally, we may assume that \\[P\\models(S\\perp{G\\ |\\ I)}\\]\n\nNote that this independence holds only if we assume that student's intelligence is the only reason why his grade and SAT score might be correlated, which means that it assumes that there is no correlations due to other factors. These assumptions are also not ``True'' in any formal sense of word, and they are often only approximations of our true beliefs.\n\\begin{figure}\n\\centering\n\\includegraphics[width=0.3\\textwidth]{assets/student_nb.png}\n\\caption{\\label{fig:student_nb}Simple Bayesian networks for the \\emph{student} example}\n\\end{figure}\n\nAs in the case of marginal independence, conditional independences allows us to provide a compact specification of the joint distribution. The compact representation is based on a very natural alternative parameterization. By simple probabilistic reasoning, we have that \n\n\\(P(I,S,G) = P(S,G \\ |\\ I)P(I).\\)\n\nBut now, the \\textbf{conditional independence assumption} implies \n\n\\(P(S,G\\ |\\ I) = P(S\\ |\\ I)P(G\\ |\\ I).\\)\n\nHence, we have that \n\n\\(P(I,S,G) = P(S\\ |\\ I)P(G\\ |\\ I)P(I)\\)\n\nThus, we have factorized the joint distribution \\(P(I,G,G)\\) as a product of three conditional probability distributions (CPDs). This factorization immediately leads us to the desired alternative parameterization. Together with \\(P(I), P(S\\ |\\ I), P(G\\ |\\ I)\\), we can specify the joint distribution. For example, \\(P(i^1,s^1,g^2) = P(i^1)P(s^1\\ |\\ i^1)P(g^2\\ |\\ i^1)\\).\n\nWe note that this probabilistic model would be represented using the Bayesian network shown in Figure \\ref{fig:student_nb}.\n\nIn this case, the alternative parameterization is more compact than the joint. We now have three binomial distributions --- \\(P(I)\\), \\(P(S\\ |\\ i^1)\\) and \\(P(S\\ |\\ i^0)\\), and two three-valued multinomial distributions --- \\(P(G\\ |\\ i^1)\\) and \\(P(G\\ |\\ i^0)\\). Each of the binomials requires one independent parameter, and each three-valued multinomial requires two independent parameters, for a total of \\textbf{seven} (\\(3 * (2 - 1) + 2 * (3 - 1)\\)).By contract, our joint distribution has twelve entries, so that \\textbf{eleven} independent parameters.\n\n\\section{Bayesian Networks}\n\nBayesian networks build on the intuition as the naive Bayes model by exploiting conditional independence properties in order to allow a compact and natural representation.However, they are not restricted to the strong independence assumptions naive Bayes model makes.\n\nThe core of the Bayesian network representation is a directed acyclic graph (DAG), whose nodes are the random variables in our domain and whose edges correspond, intuitively, to direct influence of one node on another.\n\nWe can view  the graph in two ways:\n\\begin{itemize}\n\\item a data structure that provides the skeleton for representing \\textbf{a joint distribution} compactly in a \\emph{factorized} way.\n\\item a compact representation for \\textbf{a set of conditional independence assumptions} about a distribution.\n\\end{itemize}\n\n\\subsection{Factorization Theorem}\n\nGiven a DAG, the most general form of the probability distribution that is \\textbf{consistent} with the graph factors according to ``\\textbf{node given its parents}'':\\[P(X) = \\prod_{1=1:d}{P(X_i\\ |\\ X_{\\pi_i})}\\] where \\(X_{\\pi_i}\\)is the set of parent node of \\(x_i\\), and \\(d\\) is the number of nodes.See Figure \\ref{fig:factorize_example} for an example.\nThis graph can be factorized and represented as follows: \n\\[\n\\begin{split}\n&P(X_1,X_2,X_3,X_4,X_5,X_6,X_7,X_8) = \\\\ \n&P(X_1)P(X_2)P(X_3\\ |\\ X_1)P(X_4\\ |\\ X_2)P(X_5\\ |\\ X_2)P(X_6\\ |\\ X_3, X_4)P(X_7\\ |\\ X_6)P(X_8\\ |\\ X_5, X_6)\n\\end{split}\n\\]\n\n\\begin{figure}\n\\centering\n\\includegraphics[width=0.6\\textwidth]{assets/factorize_example.png}\n\\caption{\\label{fig:factorize_example}Factorize example graph}\n\\end{figure}\n\n\\subsection{Local Structures and Independences}\n\nGraphical models have three fundamental local structures that composes bigger structures.\n\n\\begin{itemize}\n\\item \\textbf{Common parent} Fixing \\(B\\) decouples \\(A\\) and \\(C\\). When two variables \\(A\\) and \\(C\\) have a common parent \\(B\\), conditional independence \\(A\\perp C\\ |\\ B\\) holds.\n\\item \\textbf{Cascade} Knowing \\(B\\) decouples \\(A\\) and \\(C\\). When a middle node in a cascaded three random variables is known, a conditional independence \\(A\\perp C\\ |\\ B\\) holds.\n\\item \\textbf{V-structure} If \\(C\\) is not observed, then \\(A\\) and \\(B\\) are independent. However, if it is given, then the independence is lost. (\\(A\\) and \\(B\\) are not independent given \\(C\\)). In this case, \\(A\\) and \\(B\\) are \\emph{marginally independent}.\n\\end{itemize} \n\nThe unintuitive V-structure can be described by a simple example. Suppose \\(A = \\) clock on tower, \\(B = \\) traffic jam on Eric's way to campus, and \\(C = \\) Eric on time for class. If Eric is not on time and the clock is on time, then our belief that \\(B\\) occurred is higher.\n\n\\section{I-maps}\n\n\\begin{Defn}\nLet \\(P\\) be a distribution over \\(X\\). We define \\(I(P)\\) to be the set of independence assertions of the form \\((X \\perp Y\\ |\\ Z)\\) that hold in P.\n\\end{Defn}\n\\begin{Defn}\nLet \\(K\\) be an any graph object associated with a set of independences \\(I(K)\\). Then \\(K\\) is an \\(I-map\\) for a set of independences \\(I\\) if \\(I(K) \\subseteq I\\)\n\\end{Defn}\n\nFor example, if a graph \\(K\\) is totally connected, then every pair of variables are dependent, more formally, \\(I(K) = \\emptyset \\subset P\\). A complete graph is ``useless'', since it does not give any knowledge about the structural.\n\n\\subsection{Facts about I-maps}\nFor \\(G\\) to be an I-map of \\(P\\), it is necessary that \\(G\\) does not mislead us regarding independences in \\(P\\). In other words, any independence that \\(G\\) asserts must also hold in \\(P\\), but conversely, \\(P\\) may have additional independences that are not reflected in \\(G\\).\n\n\\begin{figure}[!bph]\n\\centering\n\\includegraphics[width=0.4\\textwidth]{assets/imap_example.png}\n\\caption{\\label{fig:imap_example}} I-map example\n\\end{figure}\n\nExample:\n\nConsider a joint probability space over two independent random variables \\(X\\) and \\(Y\\) . There are three possible graphs (as shown in Figure \\ref{fig:imap_example}) over these two nodes: \\(G_\\emptyset\\), which is a disconnected pair \\(X\\) \\(Y\\) ; \\(G_{X\\rightarrow Y}\\) , which has the edge \\(X\\rightarrow Y\\) ; and \\(G_{X\\rightarrow Y}\\) , which contains \\(Y\\rightarrow X\\). The graph \\(G_\\emptyset\\) encodes the assumption that \\((X \\perp Y )\\). The latter two encode no independence assumptions.\n\nConsider following two distributions:\n\n\\begin{table}[!htbp]\n\\parbox{.3\\linewidth}{\n\\begin{tabular}{cc|c}\n\\(X\\) & \\(Y\\) & \\(P(X, Y)\\)\\\\ \\hline\n\\(x^0\\) & \\(y^0\\) & \\(0.08\\)\\\\\n\\(x^0\\) & \\(y^1\\) & \\(0.32\\)\\\\\n\\(x^1\\) & \\(y^0\\) & \\(0.12\\)\\\\\n\\(x^1\\) & \\(y^1\\) & \\(0.48\\)\\\\\n\\end{tabular}\n\\hfill\\hfill\n\\parbox{.3\\linewidth}{\n\\begin{tabular}{cc|c}\n\\(X\\) & \\(Y\\) & \\(P(X, Y)\\)\\\\ \\hline\n\\(x^0\\) & \\(y^0\\) & \\(0.4\\)\\\\\n\\(x^0\\) & \\(y^1\\) & \\(0.3\\)\\\\\n\\(x^1\\) & \\(y^0\\) & \\(0.2\\)\\\\\n\\(x^1\\) & \\(y^1\\) & \\(0.1\\)\\\\\n\\end{tabular}\n}\n}\n\\end{table}\n\nIn the example on the left, \\(X\\) and \\(Y\\) are independent in \\(P\\); for example, \\(P(x^1) = 0.48 + 0.12 = 0.6\\), \\(P(y^1) = 0.8\\), and \\(P(x^1, y^1) = 0.48 = 0.6 · 0.8\\). Thus, \\((X \\perp Y ) \\in I(P)\\), and we have that \\(G_\\emptyset\\) is an I-map of \\(P\\). In fact, all three graphs are I-maps of \\(P\\): \\(I(G_{X\\rightarrow Y})\\) is empty, so that trivially \\(P\\) satisfies all the independences in it (similarly for \\(G_{Y\\rightarrow X}\\) ). In the example on the right, \\((X \\perp Y) \\not\\in I(P)\\), so that \\(G_\\emptyset\\) is not an I-map of \\(P\\). Both other graphs are I-maps of \\(P\\).\n\n\\subsection{Local independences}\n\n\\begin{Defn}\nA Bayesian network structure \\(G\\) is a directed acyclic graph whose nodes represent random variables \\(X_1,\\ldots,X_n\\) . Let \\(Pa_{X_i}\\) denote the parents of \\(X_i\\) in \\(G\\), and \\(NonDescendants_{X_i}\\) denote the variables in the graph that are not descendants of \\( X_i\\) . Then \\(G\\) encodes the following set of \\textbf{local conditional independence assumptions} \\(I_l (G)\\):\n\\[For\\ each\\ variable\\ X_i: (X_i \\perp NonDescendant_{X_i} | Pa_{x_i}).\\]\n\\end{Defn}\n\nIn other words, a node \\(X_i\\) is independent of any non descendants given its parents.\n\n\\section{D-separation}\n\n\\textbf{Direct connection}\\quad The simple case is that \\(X\\) and \\(Y\\) are directly connected via an edge, say \\(X \\rightarrow Y\\). For any network structure \\(G\\) that contains the edge \\(X \\rightarrow Y\\) , it is possible to construct a distribution where \\(X\\) and \\(Y\\) are correlated regardless of any evidence about any of the other variables in the network. In other words, if \\(X\\) and \\(Y\\) are directly connected, we can always get examples where they influence each other, regardless of \\(Z\\).\n\n\\begin{figure}[!bth]\n\\centering\n\\includegraphics[width=.6\\linewidth]{assets/xyz_trail.png}\n\\caption{\\label{fig:xyz_trail} The four possible two-edge trails from \\(X\\) to \\(Y\\) via \\(Z\\)}\n\\end{figure}\n\n\\textbf{Indirect connection}\\quad Now consider the more complicated case when X and Y are not directly connected, but there is a trail between them in the graph. We begin by considering the simplest such case: a three-node network, where X and Y are not directly connected, but where there is a trail between them via Z. It is clear that there are four cases where X and Y are connected via Z, as shown in Figure \\ref{fig:xyz_trail}.\n\n\\begin{itemize}\n\\item Causal trail \\(X \\rightarrow Y \\rightarrow Z\\), and evidential trail \\(X \\leftarrow Y \\leftarrow Z\\): active iff \\(Z\\)is not observed. These two is shown in Figure \\ref{fig:xyz_trail} (a),(b)\n\\item Common cause \\(X \\leftarrow Z \\rightarrow Y\\) : active iff \\(Z\\) is not observed.\n\\item Common effect \\(X \\rightarrow Z \\leftarrow Y\\) : active iff \\(Z\\) or one of its descendants is observed.\n\\end{itemize}\n\n\\begin{Defn}\nLet \\(\\mathbf{X}\\), \\(\\mathbf{Y}\\) , \\(\\mathbf{Z}\\) be three sets of nodes in \\(G\\). We say that \\(\\mathbf{X}\\) and \\(\\mathbf{Y}\\) are d\\textrm{-}separated given \\(\\mathbf{Z}\\), denoted \\(d-sep_G(\\mathbf{X} ; \\mathbf{Y} \\ |\\ \\mathbf{Z})\\), if there is no active trail between any node \\(X \\in \\mathbf{X}\\) and \\(Y \\in \\mathbf{Y}\\) given \\(\\mathbf{Z}\\). We use \\(I(G)\\) to denote the set of independences that correspond to d-separation:\n\\[I(G) = \\{(\\mathbf{X}\\perp{\\mathbf{Y}}\\ |\\ \\mathbf{Z})\\ :\\ d\\textrm{-}sep_G(\\mathbf{X} ; \\mathbf{Y} \\ |\\ \\mathbf{Z})\\}.\\]\nThis set is also called the set of \\textbf{global Markov independences}.\n\\end{Defn}\n\n\\section{Soundness and completeness}\n\n\\textbf{Soundness}\\quad If a distribution \\(P\\) factorizes according to a graph \\(G\\), then \\(I(G) \\subseteq I(P\\)).\n\n\\textbf{Completeness}\\quad d-separation detects all possible independences.\n\nHowever, it is important to note that if \\(X\\) and \\(Y\\) are not d-separated given \\(G\\), then it is not the case that \\(X\\) and \\(Y\\) are dependent given \\(Z\\) in all distributions that factorize over \\(G\\). For example, consider the graph \\(A \\rightarrow B\\). Clearly, \\(A\\) and \\(B\\) are dependent. Note that every distribution over \\(A\\) and \\(B\\) factorizes according to this graph, since it is always true that \\(P(A, B) = P(A)P(B\\ |\\ A)\\). But if we consider the specific distribution give in Table 1, then \\(A \\perp B\\). However, we can assert that if \\(X\\) and \\(Y\\) are not d-separated given \\(Z\\), then there is at least one distribution which factorizes according to the graph, and where \\(X\\) is not independent of \\(Y\\) given \\(Z\\). Combining this with the above theorems gives us an important result.\n\n\\begin{table}[!hbt]\n\\centering\n\\begin{tabular}{c|cc}\n & \\(b^0\\) & \\(b^1\\)\\\\ \\hline\n\\(a^0\\) & 0.4 & 0.6\\\\\n\\(a^1\\) & 0.4 & 0.6\\\\\n\\end{tabular}\n\\caption{\\label{table:completeness} The distribution specified in this table factorizes according to the graph \\(A \\rightarrow B\\) but \\(A\\) is independent of \\(B\\).}\n\\end{table}\n\n\\section{Uniqueness of BN}\nVery different BN graphs can actually be equivalent, in that they encode precisely the same set of conditional independence assertions.For example, the three networks in figure \\ref{fig:xyz_trail}(a),(b),(c) encode precisely the same independence assumption: \\(X\\perp Y\\ |\\ Z\\). Note that the v-structure network in figure \\ref{fig:xyz_trail}(d) induces a very different set of d-separation assertions, and hence it does not fall into the same I-equivalence class as the first three.\n\n\\begin{Defn}\nTwo graph structures \\(K^1\\) and \\(K^2\\) over X are I-equivalent if \\(I(K^1) = I(K^2)\\). The set of all graphs over \\(X\\) is partitioned into a set of mutually exclusive and exhaustive I-equivalence classes, which are the set of equivalence classes induced by the I-equivalence relation.\\(\\)\n\\end{Defn}\n\n\\begin{Defn}\nThe skeleton of a Bayesian network graph \\(\\mathcal{G}\\) over \\(X\\) is an undirected graph over \\(X\\) that contains an edge \\(\\{X, Y\\}\\) for every edge \\((X, Y)\\) in \\(\\mathcal{G}\\).\n\\end{Defn}\n\n\\begin{thm}\nLet \\(\\mathcal{G}^1\\) and \\(\\mathcal{G}^2\\) be two graphs over \\(X\\). If \\(\\mathcal{G}^1\\) and \\(\\mathcal{G}^2\\) have the same skeleton and the same set of v-structures then they are I-equivalent.\n\\end{thm}\n\n\\section{Minimum I-Map}\n\nComplete graph is a trivial I-map for any distribution over all variables, since it does not reveal any of the independence structure in the distribution.\n\n\\begin{Defn}\nA graph \\(\\mathcal{K}\\) is a minimal I-map for a set of independences \\(\\mathcal{I}\\) if it is an I-map for \\(\\mathcal{I}\\), and if the removal of even a single edge from \\(\\mathcal{K}\\) renders it not an I-map.\n\\end{Defn}\n\n\\section{Perfect Maps}\n\n\\begin{Defn}\nWe say that a graph \\(\\mathcal{K}\\) is a perfect map (P-map) for a set of independences \\(I\\) if we have that \\(I(\\mathcal{K}) = I\\). We say that \\(\\mathcal{K}\\) is a perfect map for \\(P\\) if \\(I(\\mathcal{K}) = I(P)\\).\n\\end{Defn}\n\nNote that not every distribution has a perfect map.\n\n\\section{Summary}\n\\begin{itemize}\n\\item \\begin{Defn}\n\\(A\\) Bayesian network is a pair \\(B = (G, P)\\) where \\(P\\) factorizes over \\(G\\), and where \\(P\\) is specified as a set of CPDs associated with \\(G’s\\) nodes. The distribution \\(P\\) is often annotated \\(P_B\\).\n\\end{Defn}\n\\item BN utilizes local and global independences to give a compact representation of the joint distribution.\n\\item Joint likelihood is computed by multiplying CPDs.\n\\item Local and global independences are identifiable via d-separation.\n\\end{itemize}\n\n\\end{document}\n\n\n", "meta": {"hexsha": "777655a051b59efeaaad6a61e426db10fb1bc95d", "size": 18140, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "assets/pgm/lecture2/lecture2.tex", "max_stars_repo_name": "GavinXing/blog", "max_stars_repo_head_hexsha": "59cf8ac227974a17178a28176469adbfc8bacbdf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assets/pgm/lecture2/lecture2.tex", "max_issues_repo_name": "GavinXing/blog", "max_issues_repo_head_hexsha": "59cf8ac227974a17178a28176469adbfc8bacbdf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-01-31T02:21:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T03:34:38.000Z", "max_forks_repo_path": "assets/pgm/lecture2/lecture2.tex", "max_forks_repo_name": "GavinXing/blog", "max_forks_repo_head_hexsha": "59cf8ac227974a17178a28176469adbfc8bacbdf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 65.017921147, "max_line_length": 815, "alphanum_fraction": 0.7054575524, "num_tokens": 5309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.32403344160189246}}
{"text": "%------------------------------------------------------------------------------\n\\section{Computing Tree Edit Distance}\n%------------------------------------------------------------------------------\n\nTree edit distance is formally defined as the minimum total cost of the steps needed to change from a source tree to a destination tree \\cite{bille2005survey}. A \\textquote{step} can either be inserting a node, deleting a node, or renaming a node. Clearly the trivial solution is to simply delete every node in the source tree and insert a copy of every node from the destination tree. The goal, however, is to find the sequence of steps that minimizes the total cost.\n\nAfter preprocessing the ASTs, we are now ready to compute the tree edit distance between the student solution's AST and the reference solution's AST. However before we can proceed, we first need to choose a starting point for the root of our trees. In the context of assignment marking, there are two potential candidates for the tree roots.\n\nThe first choice is to root our trees at the file level. In this case, we treat the entire solution file as a single tree; functions and global variables are the immediate children of the root. The advantage of this approach is that we only need to compute the tree edit distance once. However, the disadvantage is that it is easy for logically trivial changes, such as different function orderings or function names, to significantly impact the final edit distance value.\n\nThe second choice is to root our trees at the function level. In this case, we need to compute a different tree edit distance for each matching function between the student and reference solution. For example, we would have to compute the edit distance between the tree corresponding to \\texttt{main()} in the student solution to the tree corresponding to \\texttt{main()} in the reference solution. We then repeat this process for each pair of matching functions between the student and reference solution.\n\nBetween these two choices, we decided the function-level approach is less prone to miscalculating tree edit distances between logically similar solutions. Since the tree edit distance algorithm library we are using does not have a \\textquote{reorder} operation, we want to avoid the case where the students' functions are in a different order than the reference solution.\n\n%------------------------------------------------------------------------------\n\\subsection{Inlining Unexpected Functions}\n%------------------------------------------------------------------------------\n\nBefore we pass the ASTs to our tree edit distance algorithm, we need to consider the potential case of unexpected helper functions created by the students. In programming assignments, some students may create helper functions to avoid duplicating code. This is problematic because the edit distance algorithm does not take the context of the nodes to edit into account.\n\nResearch in static analysis and automated marking generally focuses on single functions because inter-procedural analysis is exponentially more complex and time consuming. Luckily in our course, students historically do not use helper functions; of those that do, they mainly use \\textquote{pure functions}, i.e. functions that do not have any side effects and only have one return statement. In addition, emperical evidence indicate that student helper functions are rarely recursive and do not include complex logic. From this observation, we devised a simple technique (Figure~\\ref{fig:cam-inlining}) to inline these helper functions' ASTs into the caller's AST prior to computing edit distances. Should a student solution contain a more complicated helper function, their solution will be designated for manual marking.\n\n\\begin{figure}\n\\begin{minipage}{.45\\textwidth}\n\\lstinputlisting[language=C]{../media/code/inlining-before.c}\n\\end{minipage}\n\\hfill\n\\begin{minipage}{.45\\textwidth}\n\\lstinputlisting[language=C]{../media/code/inlining-after.c}\n\\end{minipage}\n\\caption[Inlining Unexpected Student Functions]{Our inliner first deletes the parameter list in the function root. It then replaces every reference to the parameters with the respective argument from the caller. Finally, it replaces the original function call with the child of the return statement.}\n\\label{fig:cam-inlining}\n\\end{figure}\n\n%------------------------------------------------------------------------------\n\\subsection{Cost Model for Comparing ASTs}\n\\label{sec:cam-cost-model}\n%------------------------------------------------------------------------------\n\nThe last component to consider before we pass the ASTs to our tree edit distance algorithm is the cost function or model that determines the actual cost of each edit step. A cost model, given an input node, returns the \\textquote{cost} to insert a copy of it into the source tree, delete it from the source tree, or rename it to a second input node.\n\nBy default, every node has an edit distance of one. Clearly, this is not ideal because some nodes should more important than others. For example, if a student forgot to call \\texttt{free()} at the end of their program, they should lose a few marks (small insertion cost) whereas if they forgot to call \\texttt{curl\\_multi\\_perform()}, they should lose a lot of marks (high insertion cost). Furthermore, inconsequential node differences such as parentheses should be penalized less, if at all. Therefore, we have added additional analysis to our cost model to ensure similar nodes and structures have reduced edit costs and key function calls have heavier penalties.\n\n\\subsubsection{Variables}\n\\label{sec:cam-ted-declref}\n\nThere are two types of variables to consider in our ASTs: external and internal variables.\n\nExternal variables are variables defined outside the student or reference solution files. These are usually library constants. For example, students may choose to use \\texttt{CURLE\\_OK} from the cURL library instead of its hard-coded value of 0 for code readability. To determine if two external variables are \\textquote{equivalent}, we check their types and names. We do not check for literal value because we want to encourage good coding practices such as using library defined constants. Furthermore, we do not need to worry about naming conflicts because the Clang frontend will catch them beforehand.\n\nInternal variables are variables defined inside the student or reference solution files. These include global variables as well as scope-level variables such as loop counters and function parameters. Recall from Section~\\ref{sec:cam-simplify-var-usage} that variables are defined to be the set of functions that read and write to them. When comparing internal variables, we consider them to be \\textquote{equivalent} and thus have zero edit cost if the intersections of their reader or writer sets are not empty.\n\n\\subsubsection{Conditions}\n\nThere are often many ways to write the same or similar behaving conditions for if-statements and loops. Without relying on SAT solvers, it is difficult to know whether two condition nodes are logically similar. For the purpose of marking, we noticed that simply comparing the set of variables and function calls between two different conditions is sufficient for determining logically similar code.\n\nWe define the edit cost between two conditions to be zero if they share at least one \\textquote{equivalent} variable (described in Section~\\ref{sec:cam-ted-declref}). If one condition has a function call to $f$, then the other condition must either contain a function call to $f$ or a variable that has been written to by $f$.\n\n\\subsubsection{Weighting Key Function Usage}\n\nConceptually, the key aspects to look for when marking should be how students make their function calls to the assignment's corresponding libraries. As a result, we want to penalize improper usage, i.e. increase the cost to insert the missing call statement to the student's AST such that it matches the reference AST.\n\nWe assign each \\textquote{key function} a weight on a per-assignment basis. Anywhere that requires a call to one of these key functions will use the associated weight---generally magnitudes higher than other edit costs.\n", "meta": {"hexsha": "15d8627928d3402fe9a809dac023e116d11b89d1", "size": 8207, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/thesis/body/clangautomarker/computing-ted.tex", "max_stars_repo_name": "Trinovantes/Masters", "max_stars_repo_head_hexsha": "a7f036a08cda7e508b0c51fefa6ac150555ec2ee", "max_stars_repo_licenses": ["BSD-Source-Code"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thesis/thesis/body/clangautomarker/computing-ted.tex", "max_issues_repo_name": "Trinovantes/Masters", "max_issues_repo_head_hexsha": "a7f036a08cda7e508b0c51fefa6ac150555ec2ee", "max_issues_repo_licenses": ["BSD-Source-Code"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis/thesis/body/clangautomarker/computing-ted.tex", "max_forks_repo_name": "Trinovantes/Masters", "max_forks_repo_head_hexsha": "a7f036a08cda7e508b0c51fefa6ac150555ec2ee", "max_forks_repo_licenses": ["BSD-Source-Code"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 128.234375, "max_line_length": 823, "alphanum_fraction": 0.7605702449, "num_tokens": 1595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6187804478040617, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.32388227790457685}}
{"text": "\\documentclass[apjl]{emulateapj}\n%\\documentclass[letterpaper,12pt,preprint]{aastex}\n\n% packages\n\\usepackage{amssymb,amsmath,amsbsy}\n\\usepackage{booktabs}\n\\usepackage{multirow}\n\\usepackage{url}\n\n% commands\n\\newcommand{\\given}{\\,|\\,}\n\\newcommand{\\dd}{\\mathrm{d}}\n\\newcommand{\\transpose}[1]{{#1}^{\\mathsf{T}}}\n\\newcommand{\\inverse}[1]{{#1}^{-1}}\n\\newcommand{\\Msun}{\\ifmmode {{\\rm M}_{\\odot}}\\else M$_{\\odot}$\\fi}\n\\newcommand{\\bs}[1]{\\boldsymbol{#1}}\n\\newcommand{\\degree}{^{\\circ}}\n\\newcommand{\\eqn}{Equation~}\n\n% Symbols\n\\newcommand{\\period}{T}\n\\newcommand{\\mf}{m_f}\n\\newcommand{\\wdupper}{1.44}\n\n\\begin{document}\n\n\\title{The mass distribution of companions to low-mass white dwarfs}\n\\author{Jeff J.~Andrews\\altaffilmark{\\colum}, Adrian M.~Price-Whelan\\altaffilmark{\\colum}, Marcel A.~Ag\\\"ueros\\altaffilmark{\\colum}}\n\n% Affiliations\n\\newcommand{\\colum}{1}\n\\altaffiltext{\\colum}{Department of Astronomy, \n\t\t              Columbia University, \n\t\t              550 W 120th St., \n\t\t              New York, NY 10027, USA}\n\n\n\\begin{abstract}\nMeasuring the masses of companions to single-line spectroscopic binary stars is (in general) not possible because of the unknown orbital plane inclination.  Even when the mass of the visible star can be measured, only a lower limit can be placed on the mass of the unseen companion. However, since these inclination angles should be isotropically distributed, for a large enough, unbiased sample, the  companion mass distribution can be deconvolved from the distribution of observables. In this work, we construct a hierarchical probabilistic model to infer properties of unseen companion stars given observations of the orbital period and projected radial velocity of the primary star. We apply this model to three mock samples of low-mass white dwarfs (LMWDs, $M\\lesssim0.45~\\Msun$) and a sample of post-common-envelope binaries. We use a mixture of two Gaussians to model the WD and neutron star (NS) companion mass distributions. Our model successfully recovers the initial parameters of these test data sets. We then apply our model to 55 WDs in the extremely low-mass (ELM) WD Survey. Our maximum a posteriori model for the WD companion population has a mean mass $\\mu_{\\rm WD} = 0.74~\\Msun$, with a standard deviation $\\sigma_{\\rm WD} = 0.24~\\Msun$. Our model constrains the NS companion fraction $f_{\\rm NS}$ to be $<$16\\% at 68\\% confidence. We make samples from the posterior distribution publicly available so that future observational efforts may compute the NS probability for newly discovered LMWDs.\n\\end{abstract}\n\n\\keywords{binaries: general --- binaries: spectroscopic --- methods: statistical --- white dwarfs} \n\n\\section{Introduction}\nExcept in cases of extreme metallicity \\citep{kilic07}, the Galaxy is not old enough to produce low-mass white dwarfs (LMWDs) through single-star evolution. Instead, LMWDs are expected to form through interactions with another star \\citep{han98,nelemans00,nelemans01,vdSluys06,woods12}. Indeed, with few exceptions, follow-up observations consistently find companions to LMWDs \\citep{marsh95,maxted00,nelemans05,rebassa11}. Recently, the ELM WD Survey has identified 61 extremely LMWDs ($M\\lesssim0.3~ \\Msun$) in the Sloan Digital Sky Survey \\citep[SDSS;][]{york00} and elsewhere \\citep{ELMI,ELMII, ELMIII, ELMIV, ELMV}. We refer to the 55 WDs found by these authors that have a measured radial velocity (RV) and orbital period ($\\period$) as the ELM sample.\n\nThese RV and $\\period$ measurements indicate that the LMWDs companions are most likely WDs. However, since the inclination angle $i$ is unknown, LMWDs could have neutron star (NS) companions. Indeed, LMWDs are known companions to millisecond pulsars, although these WDs are generally too faint for spectroscopy \\citep{vKerkwijk96,callanan98,bassa06,antoniadis12}. Finding even one NS companion to a spectroscopically characterized LMWD would be very valuable, since this system could constrain the NS mass. To date, unfortunately, radio and X-ray searches for NS companions to LMWDs have been unsuccessful \\citep{vLeeuwen07,agueros09b,agueros09a,kilic13}. \n\nFor each LMWD in the ELM sample, spectroscopy provides $\\period$, the primary WD mass $M_1$, and the projected orbital velocity $K=v \\sin i$. Assuming circular orbits, we can write:\n\\begin{equation}\n\t\\frac{(M_2 \\sin i)^3}{\\left(M_1+M_2\\right)^2} = \\frac{\\period}{2\\pi G} K^3, \\label{eq:massfunc}\n\\end{equation}\nwhere the right side is the mass function $\\mf$. The companion mass, $M_2$, is minimized for an edge-on orbit ($i = 90\\degree$). Because of this dependence on $i$, the nature of the companion cannot usually be determined based on $\\mf$ alone. Figure~\\ref{fig:Porb-M1} shows that the population of LMWDs with pulsar companions occupies the same region in $M_1 - \\period$ space as those with WD companions. Therefore, barring rare circumstances such as eclipsing systems, individual LMWDs with NS companions cannot be identified from optical observations alone.\n\nThe ELM sample is now large enough that the $M_2$ distribution and NS companion fraction can be constrained statistically. %These constraints provide important tests for population synthesis models. \nWe have developed a probabilistic model to infer parameters of an assumed form for the $M_2$ distribution. Our method is similar to that employed by \\citet{ozel12} and \\citet{kiziltan13} to describe the mass distribution of NSs in binaries using post-Keplerian parameters. We focus on the following questions: Can the companion population be modeled using a simple description of $M_2$? How does the $M_2$ distribution compare to predictions from population synthesis simulations?  What is the rate of LMWD-NS binaries implied by our model? What are the resulting distributions of NS probabilities for individual systems in the ELM sample? \n\nTo answer these questions, we build the mathematical framework (Section 2), then test our resulting model (Section 3). We apply our model to the ELM sample (Section 4) before concluding (Section 5).\n\n\\begin{figure}[h!]\n\\begin{center}\n\\includegraphics[angle=90,width=0.95\\columnwidth]{f1.eps}\n\\caption{The $M_1$ - $\\period$ distribution of the ELM sample (circles) and the known WD-NS binaries (triangles). The three eclipsing systems in the ELM sample with known $M_2$ are shown as filled circles, and the masses of the ELM WDs without detected RV variations are shown by the arrows. From $M_1$ and $\\period$ alone, the two populations are indistinguishable.}\n\\label{fig:Porb-M1}\n\\end{center}\n\\end{figure}\n\n\\section{Building our model}\nWe construct a statistical model to constrain a parametric model for the distribution of LMWD companion masses, $p(M_2 \\given \\bs{\\theta})$.\\footnote{We represent vectors or sets of parameters or quantities by bold symbols.} For each system, we assume we have $K$, $T$, and $M_1$, and therefore know $\\mf$. We wish to derive posterior constraints on the model parameters, $\\bs{\\theta}$, which describe the distribution of companion masses, $p(M_2\\given \\bs{\\theta})$, given the set of observed mass functions, $\\bs{m_f}$, by deconvolving the $\\mf$ distribution from the unobserved inclinations. Using Bayes' rule,\n\\begin{equation}\n    p(\\bs{\\theta} \\given \\bs{\\mf}) = \\frac{1}{\\mathcal{Z}}~p(\\bs{\\mf} \\given \\bs{\\theta})~p(\\bs{\\theta}),\n\\end{equation}\nwhere $p(\\bs{\\mf} \\given \\bs{\\theta})$ is the likelihood, $p(\\bs{\\theta})$ is the prior on parameters $\\bs{\\theta}$, and the evidence integral, $\\mathcal{Z}$, is a constant that depends only on the data. The likelihood, $p(\\bs{\\mf} \\given \\bs{\\theta})$, can be split into a product over the likelihoods of individual systems:\n\\begin{equation}\np(\\bs{\\mf} \\given \\bs{\\theta}) = \\prod_j p(\\mf \\given \\bs{\\theta}),\n\\end{equation}\nwhere the product is over each of the $j$ systems.  This marginal likelihood involves integrals over the unobserved quantities $i$ and $M_2$,\n\\begin{align}\n    p(\\mf \\given \\bs{\\theta}) &= \\int_0^\\infty dM_2 \\int_0^{\\pi/2} di  \\nonumber \\\\\n      & \\qquad {} \\times p(\\mf \\given M_1, M_2, i)~p(M_2 \\given \\bs{\\theta})~p(i).\n\\end{align}\nWe neglect observational uncertainties in $\\mf$ and $M_1$,\\footnote{The fractional uncertainties in these quantities are small, $\\sigma_x / x \\sim 0.05-0.1$ \\citep{gianninas14}.} and assume the inclination angles are isotropically distributed:\n\\begin{equation}\n\tp(\\mf \\given M_1, M_2, i) = \\delta \\left[\\mf - f(M_1, M_2, i) \\right],\n\\end{equation}\nwhere\n\\begin{equation}\n\tf(M_1, M_2, i) = \\frac{(M_2 \\sin i)^3}{(M_1 + M_2)^2}\n\\end{equation}\nand\n\\begin{equation}\np(i) = \\sin i.\n\\end{equation}\nFor now, we do not specify a parametric form for the companion mass distribution, $p(M_2 \\given \\bs{\\theta})$. With the above assumptions, the marginal likelihood integral is:\n\\begin{align}\n    p(\\mf \\given \\bs{\\theta}) &= \\int_{0}^\\infty dM_2 ~p(M_2 \\given \\bs{\\theta})  \\nonumber \\\\\n    & \\qquad {} \\times \\int_0^{\\pi/2} di ~\\sin i ~ \\delta \\left[g(M_1,M_2,i) \\right]\\label{eq:delta},\n\\end{align}\nwhere\n\\begin{equation}\n\tg(M_1,M_2,i) = \\mf - \\frac{M_2^3}{(M_1+M_2)^2}\\sin^3 i.\n\\end{equation}\nThe inner integral (over $i$) has the form:\n\\begin{equation}\n    \\int dx~F(x)~\\delta \\left[ G(x) \\right] = \\sum_j \\frac{F(x^*_j)}{|G'(x^*_j)|},\n\\end{equation}\nwhere the sum is over the roots, $x^*_j$, of the function $G(x)$. The root, $i^*$, and derivative of the argument of the delta function in \\eqn\\ref{eq:delta} are: \n\\begin{align}\n\t\\sin i^* &= \\frac{ \\left[\\mf(M_1+M_2)^2 \\right]^{1/3}}{M_2}, \\\\\n\t\\frac{\\partial g}{\\partial i}\\bigg\\rvert_{i^*} &= \\frac{3M_2^3}{(M_1+M_2)^2} \\sin^2 i^* \\sqrt{1 - \\sin^2 i^*}.\n\\end{align}\nWe may rewrite the marginal likelihood as:\n\\begin{align}\n\tp(\\mf \\given \\bs{\\theta}) &= \\int_{0}^\\infty dM_2~p(M_2 \\given \\bs{\\theta})~\\sin i^* \\left(\\frac{\\partial g}{\\partial i}\\bigg\\rvert_{i^*}\\right)^{-1}\\\\\n\t&= \\int_{M_{2,{\\rm min}}}^\\infty dM_2~p(M_2 \\given \\bs{\\theta})~h(M_2, \\mf, M_1). \\label{eq:fullm2}\n\\end{align}\nThe bottom bound in the integral in \\eqn\\ref{eq:fullm2} is set by the minimum companion mass for which the integrand is real, $M_{2,{\\rm min}}$, determined by setting $i=90\\degree$ in \\eqn\\ref{eq:massfunc} and solving for $M_2$, and\n\n\\begin{equation}\nh(M_2, \\mf, M_1) = \\frac{(M_1+M_2)^{4/3}}{3\\ \\mf^{1/3}M_2\\sqrt{M_2^2 - \\left[ \\mf(M_1+M_2)^2 \\right]^{2/3}}}.\n\\end{equation}\n\n\\subsection{Our Model} \\label{sec:experiments}\nWe must now choose a functional form for the companion mass distribution, $p(M_2\\given \\bs{\\theta})$. We use a two-component Gaussian mixture model. We truncate the distributions using physically motivated bounds: the WD component is restricted to $M_2\\in [0.2,\\wdupper]~\\Msun$ and the NS component is restricted to $M_2\\in [1.3,2.0]~\\Msun$. We then have:\n\\begin{align}\n\tp(M_2 \\given \\bs{\\theta}) &= \\left[ (1-f_{\\rm NS})~p_{\\rm WD} + f_{\\rm NS}~p_{\\rm NS} \\right], \n\\end{align}\nwhere $f_{\\rm NS}$ is the NS fraction and\n\\begin{align}\n\tp_{\\rm WD} &= \\mathcal{N}(M_2 \\given \\mu_{\\rm WD}, \\sigma^2_{\\rm WD}); ~0.2 < \\frac{M_2}{\\Msun} < \\wdupper, \\\\\n\tp_{\\rm NS} &= \\mathcal{N}(M_2 \\given \\mu_{\\rm NS}, \\sigma^2_{\\rm NS}); ~1.3 < \\frac{M_2}{\\Msun} < 2.\n\\end{align}\n$\\mathcal{N}$ is the (truncated, but properly normalized) normal distribution with mean $\\mu$, variance $\\sigma^2$; the distributions are limited to the ranges specified. To reduce the number of parameters in our model we fix $\\mu_{\\rm NS}$ and $\\sigma_{\\rm NS}$\n%$\\mu_{\\rm NS} = 1.4~\\Msun$ and $\\sigma_{\\rm NS} = 0.05~\\Msun$, \nto:\n\\begin{align}\n\t\\mu_{\\rm NS} &= 1.4~\\Msun, \\\\\n\t\\sigma_{\\rm NS} &= 0.05~\\Msun,\n\\end{align}\nas some NSs in binaries may be somewhat more massive than the canonical NS mass of 1.35 \\Msun~\\citep{kiziltan13,smedley14}.\n\nThe probability of any particular WD having a NS companion, $P_{\\rm NS}$, can be computed for a given set of parameters for the $M_2$ distribution:\n\\begin{equation}\nP_{\\rm NS} = \\frac{\\int_{M_{2,{\\rm min}}}^{\\infty} dM_2~ f_{\\rm NS}~ p_{\\rm NS}~ h(M_2, \\mf, M_1)}{p(\\mf \\given \\bs{\\theta})}. \\label{eq:P_NS}\n\\end{equation}\n\nOur companion mass model parameters are then $\\bs{\\theta} = (\\mu_{\\rm WD}, \\sigma_{\\rm WD}, f_{\\rm NS})$. For $\\mu_{\\rm WD}$, we use a uniform prior from $0.2-1.0~\\Msun$; for $\\sigma_{\\rm WD}$, we use a logarithmic (scale-invariant) prior over the range $0.02-2.0~\\Msun$. Finally, we use a uniform prior over the dimensionless $f_{\\rm NS}$ from $0-1$. The model parameters are summarized in Table~\\ref{tbl:parameters}.\n\n\\renewcommand{\\arraystretch}{1.405}\n\\begin{deluxetable}{ccccc}\n\t\\tablecaption{Model Results \\label{tbl:parameters}}\n\n\t\\tablehead{\n\t\t\\multicolumn{2}{c}{} &\n\t\t\\colhead{$\\mu_{\\rm WD}$} & \n\t\t\\colhead{$\\sigma_{\\rm WD}$} &\n\t\t\\colhead{$f_{\\rm NS}$} \\\\\n\t\t\\colhead{} &\n\t\t\\colhead{} &\n\t\t\\colhead{[\\Msun]} &\n\t\t\\colhead{[\\Msun]} &\n\t\t\\colhead{}\n\t}\n\n\t\\startdata\n\t\t\\multicolumn{2}{c}{\\multirow{2}{*}{Priors}} & $\\mathcal{U}(0.2, 1)$ & $\\propto \\sigma^{-1}$  & $\\mathcal{U}(0, 1)$ \\\\\n\t\t\\multicolumn{2}{c}{} & & $(0.02 < \\sigma/\\Msun < 2.0)$ & \\\\\n\t\t\\cutinhead{Test Cases}\n\t\t\\multirow{2}{*}{Test 1} & True & 0.7 & 0.2 & 0 \\\\\n\t\t & MAP & 0.72 & 0.20 & 0.0 \\\\\n\t\t \\hline\n\t\t\\multirow{2}{*}{Test 2} & True & 0.7 & 0.2 & 0.10 \\\\\n\t\t & MAP & 0.74 & 0.19 & 0.11 \\\\\n\t\t \\hline\n\t\t\\multirow{2}{*}{Test 3} & True & \\nodata & \\nodata & 0.10 \\\\\n\t\t & MAP & 0.63 & 0.52 & 0.14 \\\\\n\t\t \\hline\n\t\t\\multirow{2}{*}{PCEB} & True & \\nodata & \\nodata & 0 \\\\\n\t\t & MAP & 0.58 & 0.16 & 0.0 \\\\\n\t\t \\cutinhead{ELM Sample}\n\t\t & MAP & 0.74 & 0.24 & 0.0\n\t\\enddata\n\n\t\\tablecomments{Parameter information for the form of the $M_2$ distribution used in the tests described in Section~\\ref{sec:tests}. $\\mathcal{U}$ is the uniform distribution. We additionally fix the NS mass distribution: $\\mu_{\\rm NS} = 1.4~\\Msun$ and $\\sigma_{\\rm NS} = 0.05~\\Msun.$}\\\n\n\\end{deluxetable}\n\nWe use a Markov Chain Monte Carlo algorithm \\citep{goodman10} to draw samples from the posterior distribution, $p(\\mu_{\\rm WD}, \\sigma_{\\rm WD}, f_{\\rm NS} \\given \\bs{m}_f, \\bs{M}_1)$.\\footnote{Our model uses {\\tt emcee}, implemented in \\texttt{Python} \\citep{foremanmackey13}.} The algorithm uses an ensemble of individual ``walkers'' to naturally adapt to the geometry of the parameter-space being explored. We run the walkers for a burn-in period of 500 steps starting from randomly drawn initial conditions (sampled from the priors in Table~\\ref{tbl:parameters}). We then re-initialize the walkers from their positions at the end of this run and run again for 1000 steps. We remove the burn-in samples to eliminate any effects due to our choice of initial conditions. \n\n\\section{Testing Our Model} \\label{sec:tests}\nWe test the performance of this Gaussian mixture model on four separate data sets: three mock data sets and a sample of SDSS post-common-envelope binaries \\citep[PCEBs;][]{nebot11}. \nEach of the 100 systems in our three mock data sets is generated by computing a $\\mf$ from a random $M_1$ (drawn from a uniform distribution, $\\mathcal{U}(0.2,0.4)~\\Msun$), $M_2$ (from the distributions described below), and $i$ (from an isotropic distribution). \n%the companion mass from the particular distributions described below, then using a randomly drawn $i$ and $M_1$ to compute $\\mf$. We draw $M_1$ from a uniform distribution, $\\mathcal{U}(0.2,0.4)~\\Msun$. \nWe apply the same Gaussian mixture model to all four tests to infer the parameters of the WD mixture component and $f_{\\rm NS}$.\n\n\\begin{figure*}[h!]\n\\begin{center}\n\\includegraphics[width=0.95\\textwidth]{f2.pdf}\n\\caption{Results from testing the first two mock data sets described in Section~\\ref{sec:tests}. The left-most panels show the companion masses (gray histogram) randomly drawn from each of our test distributions and our MAP models (black line). Panels in the second and third columns show samples from the posterior distributions of $\\mu_{\\rm WD}$ and $\\sigma_{\\rm WD}$ and $f_{\\rm NS}$. Contours designate the 68\\% and 95\\% confidence levels. Dashed lines in these panels show the true values from which the sample systems were drawn. The fourth panel shows individual mock LMWD systems (ordered by increasing $\\mf$) and their corresponding $P_{\\rm NS}$ distribution. Tick marks along the bottom indicate inputed LMWD-NS systems.}\n\\label{fig:tests_1_2}\n\\end{center}\n\\end{figure*}\n\n\\subsection{Test 1: Single Gaussian (WD)} \\label{sec:exp1}\nWe first generate companion masses by drawing from a single, truncated Gaussian with the parameters given in Table~\\ref{tbl:parameters}. This mock sample contains no NSs. In the top row of Figure~\\ref{fig:tests_1_2}, the left-most panel shows that our model finds a maximum a posteriori (MAP) $M_2$ distribution (black line) that qualitatively matches the input distribution (gray histogram). The second and third panels show samples from the posterior distributions and contours containing 68\\% and 95\\% of the samples for our three model parameters. The input values (dashed lines) lie cleanly within the inner contour in both panels, although $f_{\\rm NS}$ has a tail up to $\\approx$10\\%.\n\n%The second panel shows samples from the posterior distribution and contours containing 68\\% and 95\\% of the samples. The input values lie cleanly within the inner contour in both projections of the posterior. \n%the model preference toward higher masses and smaller standard deviations is due to statistical noise from our randomly generated mock sample. \n%The third panel shows that, although the posterior $f_{\\rm NS}$ distribution is consistent with 0\\%, there is a tail up to $\\approx$10\\%. \n\nEquation~\\ref{eq:P_NS} gives the probability of an individual system hosting a NS. Using posterior samples, we can determine the distribution of $P_{\\rm NS}$ for each system. The right-most panel in Figure~\\ref{fig:tests_1_2} includes all the individual systems, ordered by $\\mf$, and shows the distributions of $P_{\\rm NS}$ for each. For most systems, there is negligible probability above $P_{\\rm NS}\\sim 5\\%$.\n\n\\subsection{Test 2: Two Gaussians (WD + NS)} \\label{sec:exp2}\nWe use the same Gaussian distribution to generate companion masses for the WDs but add a NS component with $f_{\\rm NS} = 10\\%$. The bottom row of Figure~\\ref{fig:tests_1_2} shows that our model again recovers the input values for $\\mu_{\\rm WD}$ and $\\sigma_{\\rm WD}$. \n%As in Test 1, the model preference for higher $\\mu_{\\rm WD}$ and lower $\\sigma_{\\rm WD}$ is due to our randomly generated mass distribution. \nImportantly, the third panel shows that our model also recovers $f_{\\rm NS}$, although the posterior shows a substantial tail toward higher $f_{\\rm NS}$. Tick marks in the right-most panel of Figure~\\ref{fig:tests_1_2} indicate ``true\" NSs in our mock data. Our model correctly assigns high $P_{\\rm NS}$ to roughly half of these. However, many systems with NS companions have inclinations too low to be statistically differentiated from those with WD companions.\n\n\\subsection{Test 3: Uniform (WD) + Gaussian (NS)} \\label{sec:exp3}\nWe generate companion masses for the WDs by sampling from a uniform distribution over $[0.2,1.2]~\\Msun$, again with $f_{\\rm NS}=$10\\%. The top row of Figure~\\ref{fig:tests_3_4} shows the results. The posterior distribution in the second panel indicates that $\\mu_{\\rm WD}$ and $\\sigma_{\\rm WD}$ are not well constrained. The preference for larger $\\sigma_{\\rm WD}$ is expected, as the model flattens the Gaussian model distribution to match it with the input uniform distribution. Interestingly, the third panel shows that despite having a non-Gaussian input distribution for $M_2$, and a poorly constrained $\\sigma_{\\rm WD}$, our model still recovers $f_{\\rm NS}$ approximately as accurately as in Test 2. Furthermore, the fourth panel of Figure~\\ref{fig:tests_3_4} demonstrates that our model effectively identifies which LMWDs host NS companions.\n\n\\subsection{Test 4: PCEBs} \\label{sec:PCEB}\nPCEBs are composed of WDs in close orbits with main-sequence companions. The \\citet{nebot11} sample of 54 SDSS PCEBs, which have precisely determined $K$, $\\period$, and masses for the main-sequence companions, are an ideal test sample for our model. Our model uses these parameters to try and recover the PCEBs WD mass distribution, which we can then compare to the spectroscopically determined WD masses.\n%Our model is ignorant of the spectroscopically measured WD masses and attempts to fit the WD mass distribution based on the measured main sequence mass, $K$, and $\\period$. We use a sample of 54 SDSS PCEBs with spectroscopically derived $K$, $\\period$, and main sequence masses \\citep{nebot11}. \nOur MAP distribution (black line) is shown in the left-most panel in the bottom row of Figure~\\ref{fig:tests_3_4}. Our model qualitatively recovers the true $M_{\\rm WD}$ distribution (gray histogram). The third panel shows that the posterior $f_{\\rm NS}$ distribution is very low, as expected since there are no NS companions in the PCEB sample. This is further illustrated in the right-most panel, where every PCEB in the sample has low $P_{\\rm NS}$ values.\n\n\\begin{figure*}[h!]\n\\begin{center}\n\\includegraphics[width=0.95\\textwidth]{f3.pdf}\n\\caption{ The results of our model when applied to our third mock data set and the SDSS PCEB sample. The panels are same as those in Figure~\\ref{fig:tests_1_2}.}\n\\label{fig:tests_3_4}\n\\end{center}\n\\end{figure*}\n\n\\section{Applying our model}\n\\subsection{The ELM Sample}\nThe ELM WD Survey is based on the Hypervelocity Star Survey \\citep{brown06}, and includes previously identified SDSS LMWDs \\citep{eisenstein06,liebert04}. Objects are chosen for spectroscopic follow-up based on their $ugr$ colors, and this choice is independent of the mass and nature of any putative companions. Therefore, at least with regard to $i$ and $M_2$, the population is unbiased.\n\nThe ELM WD sample includes 55 systems with RV variations fit to orbital solutions, which provide precise measurements of $\\period$ and $K$. WD masses in these systems are derived from fits to spectroscopic templates, which are generally precise to $\\approx$10\\% \\citep{gianninas14}. The masses of cool LMWDs may suffer somewhat from inaccuracies in the one-dimensional WD atmospheric models \\citep{tremblay13}. However, since this should only affect the coolest WDs in the ELM sample, we expect any impact on our results to be minor.\n\nThree systems are eclipsing binaries, with known companion masses: NLTT 11748 \\citep[$M_2=0.72~\\Msun$;][]{kaplan14}, SDSS J065133.3$+$284423.3 \\citep[$M_2=0.50~\\Msun$;][]{brown11b}, and SDSS J075141.2$-$014120.9 \\citep[$M_2=0.97~\\Msun$;][]{kilic14}. For these systems, the likelihood reduces to:\n\\begin{equation}\np(\\mf \\given \\theta) = (1-f_{\\rm NS}) \\mathcal{N}(M_2^* \\given \\mu_{\\rm WD}, \\sigma^2_{\\rm WD}),\n\\end{equation}\nwhere $M_2^*$ is the mass of the WD companion. \n\nThe other six ELM systems show no evidence of orbital motion, with RV upper limits of $\\approx$20-50 km s$^{-1}$. Some of these systems may be in low $i$ binaries with RVs below the detection limit, or may have $\\period\\approx24$ hr, which is difficult to measure \\citep{ELMV}. These LMWDs could also have companions at systematically longer $\\period$, resulting in orbital velocities below the detection limit. We do not include these systems in our analysis.\n% TO ADD?: They could also not have companions at all - reference goes here\n\n\\begin{figure*}[h!]\n\\begin{center}\n\\includegraphics[width=0.95\\textwidth]{f4.pdf}\n\\caption{Results from applying our model to the ELM WDs. \nThe panels are the same as in Figures~\\ref{fig:tests_1_2} and \\ref{fig:tests_3_4}. \n%The leftmost panel of the top row shows that the MAP model $M_{\\rm WD}$ distribution matches the histogram of true masses in the PCEB sample. \n%The second and third panels show the posterior distributions for our model parameters, while the fourth panel shows the $P_{\\rm NS}$ values for each of the PCEBs (ordered by increasing $\\mf$). \nThe left-most panel shows both the MAP $M_2$ distribution (solid black) and random samples from the posterior (gray lines). \n%The second panel shows that the MAP Gaussian model has $\\mu_{\\rm WD}= 0.71~\\Msun$ and $\\sigma_{\\rm WD}= 0.26~\\Msun$. The third panel shows posterior samples of $\\mu$ and $f_{\\rm NS}$. The last panel indicates that several LMWDs in the ELM sample have high $P_{\\rm NS}$. \nThe three systems in the right-most panel with all $P_{\\rm NS} = 0\\%$ are the eclipsing systems with measured $M_2$.\n}\n\\label{fig:ELM_post}\n\\end{center}\n\\end{figure*}\n\n\\subsection{Results and Discussion}\nThe results from applying our model to the ELM sample are shown in Figure~\\ref{fig:ELM_post}. The MAP model gives $\\mu_{\\rm WD} = 0.74~\\Msun$, $\\sigma_{\\rm WD} = 0.24~\\Msun$, and $f_{\\rm NS} = 0\\%$. The marginal posterior over $\\mu_{\\rm WD}$ and $\\sigma_{\\rm WD}$ has a tail toward larger $\\sigma_{\\rm WD}$, which could indicate that the true WD distribution may not be exactly Gaussian.\n\nIt is interesting that the best-fit Gaussian for the companions to the ELM WDs is similar to that of the population of single hydrogen-atmosphere WDs in SDSS, with a mean of 0.6 $\\Msun$ \\citep{kleinman13}. Our distribution is significantly wider: $\\sigma \\approx 0.26~\\Msun$, compared to $\\sigma \\approx 0.1~\\Msun$, possibly due to past mass transfer phases increasing the masses of the unseen primary WDs.\n\nThe low combined mass in these systems indicates that, although several of them will merge within a Hubble time \\citep{ELMV}, the majority of the ELM systems are unlikely to be type Ia SN progenitors. However, we cannot rule out the possibility that some individual LMWD binaries may be massive enough to produce type Ia SNe \\citep{justham09}.\n%Several of these systems will merge within a Hubble time \\citep{ELMV}, but their sub-Chandrasekhar combined mass would suggest that they are more likely to be underluminous type .Ia, rather than Ia, supernova progenitors. \n%Our results are independent of astrophysical expectations, as they do not include informative priors on $\\mu_{\\rm WD}$ and $\\sigma_{\\rm WD}$, apart from limits for $M_2$ of 0.2 \\Msun\\,(based on observations of LMWDs) and \\wdupper~\\Msun\\,(based on the Chandrasekhar mass). In principle, priors could be added based on \n\nOur posterior distributions further suggest that the companions to LMWDs have predominantly CO cores. This is in contrast to population synthesis models, which suggest that LMWDs should predominantly have He-core WD companions \\citep{toonen12}. With a larger sample, a more sophisticated LMWD companion model could place quantitative constraints on population synthesis predictions.\n\nThe third panel in Figure~\\ref{fig:ELM_post} shows a $f_{\\rm NS}$ strongly peaked toward 0\\%. However, there is a significant tail toward higher NS probabilities. Our model indicates $f_{\\rm NS} <16\\%$ at the 68\\% confidence level, in agreement with independent constraints from \\citet[][$f_{\\rm NS}<18\\pm5$\\%]{vLeeuwen07} and \\citet[][$f_{\\rm NS}<10\\substack{+4 \\\\ -2}~\\%$]{agueros09b}, both based on radio non-detections of LMWD companions.\n\nThe right-most panel in Figure~\\ref{fig:ELM_post} indicates there are two LMWDs with substantial $P_{\\rm NS}$: SDSS J081133.6$+$022556.8 and J174140.5$+$652638.7. However, the X-ray non-detection of SDSS J174140.5$+$652638.7 suggests its companion is unlikely to be a NS \\citep{kilic14}. Searches for radio and X-ray emission from SDSS J081133.6$+$022556.8 are on-going. We note that the $P_{\\rm NS}$ distributions in each of our samples show a trend such that systems with higher $\\mf$ have higher $P_{\\rm NS}$ values. These high $\\mf$ systems are therefore ideal targets to search for NS companions to LMWDs.\n\n\\section{Conclusions}\nWe have developed a statistical model to infer the companion mass distribution for a sample of single-line, spectroscopic binaries. This model can be applied to any such sample with measured $M_1$ and $\\mf$. When tested on three separate mock data sets with unseen WD and NS companions to LMWDs, our model recovers the input parameters. Even when the companion mass distribution is not drawn from a Gaussian distribution, our model still infers the input NS fraction to within a few percent. We further apply our model to the SDSS PCEBs \\citep{nebot11}, and our model qualitatively recovers the independent, spectroscopically measured $M_{\\rm WD}$ distribution. \n\nWe applied our model to the set of LMWDs from the ELM WD survey. The resulting posterior distribution is qualitatively similar to our two-component Gaussian test case, suggesting that the companion mass distribution to the LMWDs in the ELM sample is well-described by our model. Our model returns a MAP $\\mu_{\\rm WD} = 0.74\\pm0.24\\ \\Msun$, suggesting that a majority of ELM WDs have CO-core WD companions. This is in contrast to predictions from population synthesis models, which find that the dominant companion population should be He-core WDs \\citep[e.g.,][]{toonen12}. Our model further indicates that the fraction of ELM WDs with NS companions is consistent with 0\\%, but could be as high as $\\approx$16\\% (within 1-$\\sigma$). Finally, our model identifies the LMWD SDSS J081133.6$+$022556.8 as having the highest median probability of hosting a NS companion.\n\nTo determine the probability of any particular LMWD hosting a NS, we make our model posteriors publicly available on fig{\\bf share}.\\footnote{\\url{http://dx.doi.org/10.6084/m9.figshare.1206621}} We further provide a {\\tt Python} script that calculates $P_{\\rm NS}$ and the mass distribution for a WD companion for any LMWD with a measured $M_1$ and $\\mf$. This script can be applied to newly discovered LMWDs as well as those already in the ELM sample.\n\nThere are several ways in which our model can be expanded. By modeling photometric variability, \\citet{hermes14} recently constrained the inclination of 20 LMWDs in the ELM sample; we could include these constraints. Furthermore, our model can place tighter constraints on $f_{\\rm NS}$ by factoring in radio and X-ray non-detections. We plan to develop our method to quantitatively compare our model to the results of population synthesis codes, potentially constraining the formation of LMWDs.\n\n\\acknowledgements\nThe authors thank David Hogg, DJ D'Orazio, and Josh Peek for useful discussions, and the organizers of the \\emph{AstroData Hack Week} (2014). We are grateful to the anonymous referees for comments that helped improve this paper. MAA acknowledges support provided by the NSF through grant AST-1255419. APW is supported by a NSF Graduate Research Fellowship under grant No.\\ 11-44155. This research made use of Astropy, a community-developed core \\texttt{Python} package for Astronomy \\citep{astropy13}. \\\\\n\n\\bibliographystyle{apj}\n\n\n\\begin{thebibliography}{43}\n\\expandafter\\ifx\\csname natexlab\\endcsname\\relax\\def\\natexlab#1{#1}\\fi\n\n\\bibitem[{{Ag{\\\"u}eros} {et~al.}(2009{\\natexlab{a}}){Ag{\\\"u}eros}, {Camilo},\n  {Silvestri}, {Kleinman}, {Anderson}, \\& {Liebert}}]{agueros09b}\n{Ag{\\\"u}eros}, M.~A., {Camilo}, F., {Silvestri}, N.~M., {Kleinman}, S.~J.,\n  {Anderson}, S.~F., \\& {Liebert}, J.~W. 2009{\\natexlab{a}}, \\apj, 697, 283\n\n\\bibitem[{{Ag{\\\"u}eros} {et~al.}(2009{\\natexlab{b}}){Ag{\\\"u}eros}, {Heinke},\n  {Camilo}, {Kilic}, {Anderson}, {Freire}, {Kleinman}, {Liebert}, \\&\n  {Silvestri}}]{agueros09a}\n{Ag{\\\"u}eros}, M.~A. {et~al.} 2009{\\natexlab{b}}, \\apjl, 700, L123\n\n\\bibitem[{{Antoniadis} {et~al.}(2012){Antoniadis}, {van Kerkwijk}, {Koester},\n  {Freire}, {Wex}, {Tauris}, {Kramer}, \\& {Bassa}}]{antoniadis12}\n{Antoniadis}, J., {van Kerkwijk}, M.~H., {Koester}, D., {Freire}, P.~C.~C.,\n  {Wex}, N., {Tauris}, T.~M., {Kramer}, M., \\& {Bassa}, C.~G. 2012, \\mnras,\n  423, 3316\n\n\\bibitem[{{Astropy Collaboration} {et~al.}(2013){Astropy Collaboration},\n  {Robitaille}, {Tollerud}, {Greenfield}, {Droettboom}, {Bray}, {Aldcroft},\n  {Davis}, {Ginsburg}, {Price-Whelan}, {Kerzendorf}, {Conley}, {Crighton},\n  {Barbary}, {Muna}, {Ferguson}, {Grollier}, {Parikh}, {Nair}, {Unther},\n  {Deil}, {Woillez}, {Conseil}, {Kramer}, {Turner}, {Singer}, {Fox}, {Weaver},\n  {Zabalza}, {Edwards}, {Azalee Bostroem}, {Burke}, {Casey}, {Crawford},\n  {Dencheva}, {Ely}, {Jenness}, {Labrie}, {Lim}, {Pierfederici}, {Pontzen},\n  {Ptak}, {Refsdal}, {Servillat}, \\& {Streicher}}]{astropy13}\n{Astropy Collaboration} {et~al.} 2013, \\aap, 558, A33\n\n\\bibitem[{{Bassa} {et~al.}(2006){Bassa}, {van Kerkwijk}, {Koester}, \\&\n  {Verbunt}}]{bassa06}\n{Bassa}, C.~G., {van Kerkwijk}, M.~H., {Koester}, D., \\& {Verbunt}, F. 2006,\n  \\aap, 456, 295\n\n\\bibitem[{{Brown} {et~al.}(2006){Brown}, {Geller}, {Kenyon}, \\&\n  {Kurtz}}]{brown06}\n{Brown}, W.~R., {Geller}, M.~J., {Kenyon}, S.~J., \\& {Kurtz}, M.~J. 2006, \\apj,\n  647, 303\n\n\\bibitem[{{Brown} {et~al.}(2013){Brown}, {Kilic}, {Allende Prieto},\n  {Gianninas}, \\& {Kenyon}}]{ELMV}\n{Brown}, W.~R., {Kilic}, M., {Allende Prieto}, C., {Gianninas}, A., \\&\n  {Kenyon}, S.~J. 2013, \\apj, 769, 66\n\n\\bibitem[{{Brown} {et~al.}(2010){Brown}, {Kilic}, {Allende Prieto}, \\&\n  {Kenyon}}]{ELMI}\n{Brown}, W.~R., {Kilic}, M., {Allende Prieto}, C., \\& {Kenyon}, S.~J. 2010,\n  \\apj, 723, 1072\n\n\\bibitem[{{Brown} {et~al.}(2012){Brown}, {Kilic}, {Allende Prieto}, \\&\n  {Kenyon}}]{ELMIII}\n---. 2012, \\apj, 744, 142\n\n\\bibitem[{{Brown} {et~al.}(2011){Brown}, {Kilic}, {Hermes}, {Allende Prieto},\n  {Kenyon}, \\& {Winget}}]{brown11b}\n{Brown}, W.~R., {Kilic}, M., {Hermes}, J.~J., {Allende Prieto}, C., {Kenyon},\n  S.~J., \\& {Winget}, D.~E. 2011, \\apjl, 737, L23\n\n\\bibitem[{{Callanan} {et~al.}(1998){Callanan}, {Garnavich}, \\&\n  {Koester}}]{callanan98}\n{Callanan}, P.~J., {Garnavich}, P.~M., \\& {Koester}, D. 1998, \\mnras, 298, 207\n\n\\bibitem[{{Eisenstein} {et~al.}(2006){Eisenstein}, {Liebert}, {Harris},\n  {Kleinman}, {Nitta}, {Silvestri}, {Anderson}, {Barentine}, {Brewington},\n  {Brinkmann}, {Harvanek}, {Krzesi{\\'n}ski}, {Neilsen}, {Long}, {Schneider}, \\&\n  {Snedden}}]{eisenstein06}\n{Eisenstein}, D.~J. {et~al.} 2006, \\apjs, 167, 40\n\n\\bibitem[{{Foreman-Mackey} {et~al.}(2013){Foreman-Mackey}, {Hogg}, {Lang}, \\&\n  {Goodman}}]{foremanmackey13}\n{Foreman-Mackey}, D., {Hogg}, D.~W., {Lang}, D., \\& {Goodman}, J. 2013, \\pasp,\n  125, 306\n\n\\bibitem[{{Gianninas} {et~al.}(2014){Gianninas}, {Dufour}, {Kilic}, {Brown},\n  {Bergeron}, \\& {Hermes}}]{gianninas14}\n{Gianninas}, A., {Dufour}, P., {Kilic}, M., {Brown}, W.~R., {Bergeron}, P., \\&\n  {Hermes}, J.~J. 2014, \\apj, 794, 35\n\n\\bibitem[Goodman~\\&\\ Weare(2010)]{goodman10}\nGoodman,~J. \\& Weare,\\ J.\n2010, Comm.\\ App.\\ Math.\\ Comp.\\ Sci., 5, 65\n\n\\bibitem[{{Han}(1998)}]{han98}\n{Han}, Z. 1998, \\mnras, 296, 1019\n\n\\bibitem[{{Hermes} {et~al.}(2014){Hermes}, {Brown}, {Kilic}, {Gianninas},\n  {Chote}, {Sullivan}, {Winget}, {Bell}, {Falcon}, {Winget}, {Mason},\n  {Harrold}, \\& {Montgomery}}]{hermes14}\n{Hermes}, J.~J. {et~al.} 2014, \\apj, 792, 39\n\n\\bibitem[{{Justham} {et~al.}(2009){Justham}, {Wolf}, {Podsiadlowski}, \\&\n  {Han}}]{justham09}\n{Justham}, S., {Wolf}, C., {Podsiadlowski}, P., \\& {Han}, Z. 2009, \\aap, 493,\n  1081\n\n\\bibitem[{{Kaplan} {et~al.}(2014){Kaplan}, {Marsh}, {Walker}, {Bildsten},\n  {Bours}, {Breedt}, {Copperwheat}, {Dhillon}, {Howell}, {Littlefair},\n  {Shporer}, \\& {Steinfadt}}]{kaplan14}\n{Kaplan}, D.~L. {et~al.} 2014, \\apj, 780, 167\n\n\\bibitem[{{Kilic} {et~al.}(2011){Kilic}, {Brown}, {Allende Prieto},\n  {Ag{\\\"u}eros}, {Heinke}, \\& {Kenyon}}]{ELMII}\n{Kilic}, M., {Brown}, W.~R., {Allende Prieto}, C., {Ag{\\\"u}eros}, M.~A.,\n  {Heinke}, C., \\& {Kenyon}, S.~J. 2011, \\apj, 727, 3\n\n\\bibitem[{{Kilic} {et~al.}(2012){Kilic}, {Brown}, {Allende Prieto}, {Kenyon},\n  {Heinke}, {Ag{\\\"u}eros}, \\& {Kleinman}}]{ELMIV}\n{Kilic}, M., {Brown}, W.~R., {Allende Prieto}, C., {Kenyon}, S.~J., {Heinke},\n  C.~O., {Ag{\\\"u}eros}, M.~A., \\& {Kleinman}, S.~J. 2012, \\apj, 751, 141\n\n\\bibitem[{{Kilic} {et~al.}(2013){Kilic}, {Gianninas}, {Brown}, {Harris},\n  {Dahn}, {Ag{\\\"u}eros}, {Heinke}, {Kenyon}, {Panei}, \\& {Camilo}}]{kilic13}\n{Kilic}, M. {et~al.} 2013, \\mnras, 434, 3582\n\n\\bibitem[{{Kilic} {et~al.}(2014){Kilic}, {Hermes}, {Gianninas}, {Brown},\n  {Heinke}, {Ag{\\\"u}eros}, {Chote}, {Sullivan}, {Bell}, \\& {Harrold}}]{kilic14}\n---. 2014, \\mnras, 438, L26\n\n\\bibitem[{{Kilic} {et~al.}(2007){Kilic}, {Stanek}, \\& {Pinsonneault}}]{kilic07}\n{Kilic}, M., {Stanek}, K.~Z., \\& {Pinsonneault}, M.~H. 2007, \\apj, 671, 761\n\n\\bibitem[{{Kiziltan} {et~al.}(2013){Kiziltan}, {Kottas}, {De Yoreo}, \\&\n  {Thorsett}}]{kiziltan13}\n{Kiziltan}, B., {Kottas}, A., {De Yoreo}, M., \\& {Thorsett}, S.~E. 2013, \\apj,\n  778, 66\n\n\\bibitem[{{Kleinman} {et~al.}(2013){Kleinman}, {Kepler}, {Koester}, {Pelisoli},\n  {Pe{\\c c}anha}, {Nitta}, {Costa}, {Krzesinski}, {Dufour}, {Lachapelle},\n  {Bergeron}, {Yip}, {Harris}, {Eisenstein}, {Althaus}, \\&\n  {C{\\'o}rsico}}]{kleinman13}\n{Kleinman}, S.~J. {et~al.} 2013, \\apjs, 204, 5\n\n\\bibitem[{{Liebert} {et~al.}(2004){Liebert}, {Bergeron}, {Eisenstein},\n  {Harris}, {Kleinman}, {Nitta}, \\& {Krzesinski}}]{liebert04}\n{Liebert}, J., {Bergeron}, P., {Eisenstein}, D., {Harris}, H.~C., {Kleinman},\n  S.~J., {Nitta}, A., \\& {Krzesinski}, J. 2004, \\apjl, 606, L147\n\n\\bibitem[{{Marsh} {et~al.}(1995){Marsh}, {Dhillon}, \\& {Duck}}]{marsh95}\n{Marsh}, T.~R., {Dhillon}, V.~S., \\& {Duck}, S.~R. 1995, \\mnras, 275, 828\n\n\\bibitem[{{Maxted} {et~al.}(2000){Maxted}, {Marsh}, \\& {Moran}}]{maxted00}\n{Maxted}, P.~F.~L., {Marsh}, T.~R., \\& {Moran}, C.~K.~J. 2000, \\mnras, 319, 305\n\n\\bibitem[{{Nebot G{\\'o}mez-Mor{\\'a}n} {et~al.}(2011){Nebot\n  G{\\'o}mez-Mor{\\'a}n}, {G{\\\"a}nsicke}, {Schreiber}, {Rebassa-Mansergas},\n  {Schwope}, {Southworth}, {Aungwerojwit}, {Bothe}, {Davis}, {Kolb},\n  {M{\\\"u}ller}, {Papadaki}, {Pyrzas}, {Rabitz}, {Rodr{\\'{\\i}}guez-Gil},\n  {Schmidtobreick}, {Schwarz}, {Tappert}, {Toloza}, {Vogel}, \\&\n  {Zorotovic}}]{nebot11}\n{Nebot G{\\'o}mez-Mor{\\'a}n}, A. {et~al.} 2011, \\aap, 536, A43\n\n\\bibitem[{{Nelemans} {et~al.}(2005){Nelemans}, {Napiwotzki}, {Karl}, {Marsh},\n  {Voss}, {Roelofs}, {Izzard}, {Montgomery}, {Reerink}, {Christlieb}, \\&\n  {Reimers}}]{nelemans05}\n{Nelemans}, G. {et~al.} 2005, \\aap, 440, 1087\n\n\\bibitem[{{Nelemans} {et~al.}(2000){Nelemans}, {Verbunt}, {Yungelson}, \\&\n  {Portegies Zwart}}]{nelemans00}\n{Nelemans}, G., {Verbunt}, F., {Yungelson}, L.~R., \\& {Portegies Zwart}, S.~F.\n  2000, \\aap, 360, 1011\n\n\\bibitem[{{Nelemans} {et~al.}(2001){Nelemans}, {Yungelson}, {Portegies Zwart},\n  \\& {Verbunt}}]{nelemans01}\n{Nelemans}, G., {Yungelson}, L.~R., {Portegies Zwart}, S.~F., \\& {Verbunt}, F.\n  2001, \\aap, 365, 491\n\n\\bibitem[{{{\\\"O}zel} {et~al.}(2012){{\\\"O}zel}, {Psaltis}, {Narayan}, \\& {Santos\n  Villarreal}}]{ozel12}\n{{\\\"O}zel}, F., {Psaltis}, D., {Narayan}, R., \\& {Santos Villarreal}, A. 2012,\n  \\apj, 757, 55\n\n\\bibitem[{{Rebassa-Mansergas} {et~al.}(2011){Rebassa-Mansergas}, {Nebot\n  G{\\'o}mez-Mor{\\'a}n}, {Schreiber}, {Girven}, \\& {G{\\\"a}nsicke}}]{rebassa11}\n{Rebassa-Mansergas}, A., {Nebot G{\\'o}mez-Mor{\\'a}n}, A., {Schreiber}, M.~R.,\n  {Girven}, J., \\& {G{\\\"a}nsicke}, B.~T. 2011, \\mnras, 413, 1121\n\n\\bibitem[{{Smedley} {et~al.}(2014){Smedley}, {Tout}, {Ferrario}, \\&\n  {Wickramasinghe}}]{smedley14}\n{Smedley}, S.~L., {Tout}, C.~A., {Ferrario}, L., \\& {Wickramasinghe}, D.~T.\n  2014, \\mnras, 437, 2217\n\n\\bibitem[{{Toonen} {et~al.}(2012){Toonen}, {Nelemans}, \\& {Portegies\n  Zwart}}]{toonen12}\n{Toonen}, S., {Nelemans}, G., \\& {Portegies Zwart}, S. 2012, \\aap, 546, A70\n\n\\bibitem[{{Tremblay} {et~al.}(2013){Tremblay}, {Ludwig}, {Steffen}, \\&\n  {Freytag}}]{tremblay13}\n{Tremblay}, P.-E., {Ludwig}, H.-G., {Steffen}, M., \\& {Freytag}, B. 2013, \\aap,\n  559, A104\n\n\\bibitem[{{van der Sluys} {et~al.}(2006){van der Sluys}, {Verbunt}, \\&\n  {Pols}}]{vdSluys06}\n{van der Sluys}, M.~V., {Verbunt}, F., \\& {Pols}, O.~R. 2006, \\aap, 460, 209\n\n\\bibitem[{{van Kerkwijk} {et~al.}(1996){van Kerkwijk}, {Bergeron}, \\&\n  {Kulkarni}}]{vKerkwijk96}\n{van Kerkwijk}, M.~H., {Bergeron}, P., \\& {Kulkarni}, S.~R. 1996, \\apjl, 467,\n  L89\n\n\\bibitem[{{van Leeuwen} {et~al.}(2007){van Leeuwen}, {Ferdman}, {Meyer}, \\&\n  {Stairs}}]{vLeeuwen07}\n{van Leeuwen}, J., {Ferdman}, R.~D., {Meyer}, S., \\& {Stairs}, I. 2007, \\mnras,\n  374, 1437\n\n\\bibitem[{{Woods} {et~al.}(2012){Woods}, {Ivanova}, {van der Sluys}, \\&\n  {Chaichenets}}]{woods12}\n{Woods}, T.~E., {Ivanova}, N., {van der Sluys}, M.~V., \\& {Chaichenets}, S.\n  2012, \\apj, 744, 12\n\n\\bibitem[{{York} {et~al.}(2000){York}, {Adelman}, {Anderson}, {Anderson},\n  {Annis}, {Bahcall}, {Bakken}, {Barkhouser}, {Bastian}, {Berman}, {Boroski},\n  {Bracker}, {Briegel}, {Briggs}, {Brinkmann}, {Brunner}, {Burles}, {Carey},\n  {Carr}, {Castander}, {Chen}, {Colestock}, {Connolly}, {Crocker}, {Csabai},\n  {Czarapata}, {Davis}, {Doi}, {Dombeck}, {Eisenstein}, {Ellman}, {Elms},\n  {Evans}, {Fan}, {Federwitz}, {Fiscelli}, {Friedman}, {Frieman}, {Fukugita},\n  {Gillespie}, {Gunn}, {Gurbani}, {de Haas}, {Haldeman}, {Harris}, {Hayes},\n  {Heckman}, {Hennessy}, {Hindsley}, {Holm}, {Holmgren}, {Huang}, {Hull},\n  {Husby}, {Ichikawa}, {Ichikawa}, {Ivezi{\\'c}}, {Kent}, {Kim}, {Kinney},\n  {Klaene}, {Kleinman}, {Kleinman}, {Knapp}, {Korienek}, {Kron}, {Kunszt},\n  {Lamb}, {Lee}, {Leger}, {Limmongkol}, {Lindenmeyer}, {Long}, {Loomis},\n  {Loveday}, {Lucinio}, {Lupton}, {MacKinnon}, {Mannery}, {Mantsch}, {Margon},\n  {McGehee}, {McKay}, {Meiksin}, {Merelli}, {Monet}, {Munn}, {Narayanan},\n  {Nash}, {Neilsen}, {Neswold}, {Newberg}, {Nichol}, {Nicinski}, {Nonino},\n  {Okada}, {Okamura}, {Ostriker}, {Owen}, {Pauls}, {Peoples}, {Peterson},\n  {Petravick}, {Pier}, {Pope}, {Pordes}, {Prosapio}, {Rechenmacher}, {Quinn},\n  {Richards}, {Richmond}, {Rivetta}, {Rockosi}, {Ruthmansdorfer}, {Sandford},\n  {Schlegel}, {Schneider}, {Sekiguchi}, {Sergey}, {Shimasaku}, {Siegmund},\n  {Smee}, {Smith}, {Snedden}, {Stone}, {Stoughton}, {Strauss}, {Stubbs},\n  {SubbaRao}, {Szalay}, {Szapudi}, {Szokoly}, {Thakar}, {Tremonti}, {Tucker},\n  {Uomoto}, {Vanden Berk}, {Vogeley}, {Waddell}, {Wang}, {Watanabe},\n  {Weinberg}, {Yanny}, {Yasuda}, \\& {SDSS Collaboration}}]{york00}\n{York}, D.~G. {et~al.} 2000, \\aj, 120, 1579\n\n\\end{thebibliography}\n\n\n\n%\\bibliography{refs}\n  \n%\\bibitem[Goodman~\\&\\ Weare(2010)]{goodman10}\n%Goodman,~J. \\& Weare,\\ J.\n%2010, Comm.\\ App.\\ Math.\\ Comp.\\ Sci., 5, 65\n\n\n\\end{document}\n\n", "meta": {"hexsha": "7a16821f98c668dcbc30168aaeeca02d8a7886e6", "size": 41842, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "documents/letter/ms.tex", "max_stars_repo_name": "adrn/tilt-shift", "max_stars_repo_head_hexsha": "23d1a024bcec4061de09df834ad7cbe97b9f37ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "documents/letter/ms.tex", "max_issues_repo_name": "adrn/tilt-shift", "max_issues_repo_head_hexsha": "23d1a024bcec4061de09df834ad7cbe97b9f37ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "documents/letter/ms.tex", "max_forks_repo_name": "adrn/tilt-shift", "max_forks_repo_head_hexsha": "23d1a024bcec4061de09df834ad7cbe97b9f37ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 77.4851851852, "max_line_length": 1513, "alphanum_fraction": 0.7009464175, "num_tokens": 14249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3238822779045768}}
{"text": "\\section{Particle representation}\n\\label{sect:amplitudes}\n\\index{amplitude}\n\\index{spin}\n\\index{representation}\n\\index{scalar particle}\n\\index{vector particle}\n\\index{tensor particle}\n\\index{spin 1/2 particle}\n\\index{photon}\n\\index{neutrino}\n\nParticles with spin up to spin 2, with the exception of spin 3/2,\nare handled by classes within the framework of EvtGen.\\footnote{\nOther particles will be added as need arises.\n}\nThis\nsection will describe how spin degrees of freedom are\nrepresented, and will introduce the classes that represent\nparticles in EvtGen.  Table~\\ref{tab:reps} summarizes the different\ntypes of particles currently implemented.\n\n\\begin{table}[htbp]\n\\begin{center}\n\\begin{tabular}{ccccl} \\hline\nClass name     &  Rep. &  J   &  States   & Example \\\\ \\hline\nEvtScalarParticle   &  1    &   0  &    1      &  $\\pi$, $B^0$ \\\\\nEvtDiracParticle    & $u_{\\alpha}$& 1/2 & 2       &  $e$, $\\tau$ \\\\\nEvtNeutrinoParticle & $u_{\\alpha}$& 1/2 & 1       &  $\\nu_e$ \\\\\nEvtVectorParticle   & $\\epsilon^{\\mu}$ & 1 & 3&  $\\rho$, $J/\\Psi$ \\\\\nEvtPhotonParticle   & $\\epsilon^{\\mu}$ & 1 & 2&  $\\gamma$ \\\\\nEvtTensorParticle   & $T^{\\mu\\nu}$ & 2 & 5 &   $D^*_2$, $f_2$ \\\\ \\hline\n\\end{tabular}\n\\caption{The different types of particles that supported by EvtGen.\nThe spin 3/2, Rarita-Schwinger, representation has not yet been\nimplemented.\n\\label{tab:reps}}\n\\end{center}\n\\end{table}\n\nIn Table~\\ref{tab:reps}, $u_{\\alpha}$ \nrepresents a four component Dirac spinor,\ndefined in the Pauli-Dirac convention for the\ngamma matrices, as discussed in Section~\\ref{sect:diracspinor}.\nThe {\\tt EvtDiracParticle} class represents\nmassive spin 1/2 particles that have\ntwo spin degrees of freedom. Neutrinos are also represented\nwith a 4-component Dirac spinor by the {\\tt EvtNeutrinoParticle}\nclass.  Neutrinos are assumed to\nbe massless and only left handed neutrinos and \nright handed anti-neutrinos\nare considered. \n\nThe complex 4-vector\n$\\epsilon^{\\mu}$ is used to represent \nthe spin degrees of freedom for\nspin 1 particles.  Massive spin 1 particles, represented\nby the {\\tt EvtVectorParticle} class,\nhave three degrees of freedom.  The\n{\\tt EvtPhotonParticle} class represents massless\nspin 1 particles, which have only two (longitudinal) \ndegrees of freedom.\n\nMassive spin 2 particles are represented \nwith a complex symmetric rank 2 tensor and are\nimplemented in the {\\tt EvtTensorParticle}\nclass. \n\nFor each particle initialized in EvtGen, a set of\nbasis states is created, where the number of basis states is\nthe same as the number of spin degrees of freedom.\nThese basis states can be accessed \nthrough the {\\tt EvtParticle} class \nin either the particle's rest frame or in\nthe parent's rest frame. For massless particles, only states\nin the parent's rest frame are available.\nAs an example, consider the basis\nfor a massive spin 1 particle in it's own rest frame\n\\begin{eqnarray}\n\\epsilon^{\\mu}_1&=&(0,1,0,0),\\\\\n\\epsilon^{\\mu}_2&=&(0,0,1,0),\\\\\n\\epsilon^{\\mu}_3&=&(0,0,0,1).\n\\end{eqnarray}\nNote that these basis vectors are mutually orthogonal, and\nnormalized. That is,\n\\begin{equation}\ng_{\\mu\\nu}\\epsilon^{*\\mu}_i\\epsilon^{\\nu}_j=\\delta_{ij}.\n\\end{equation}\nFurther, they form a complete set \n\\begin{equation}\n\\sum_i\\epsilon^{*\\mu}_i\\epsilon^{\\nu}_i=g^{\\mu\\nu}-p^{\\mu}p^{\\nu}/m^2,\n\\end{equation}\nwhere $g^{\\mu\\nu}-p^{\\mu}p^{\\nu}/m^2$\nis the propagator for an on-shell spin 1 particle.\n\nIn order to write a new decay model, there\nis no reason to need to know the exact choice of\nthese basis states.  The code needed to describe the amplitude\nfor a decay process is independent of these states, as\nlong as they are complete, orthogonal and normalized.\n\n\n\n", "meta": {"hexsha": "055f50b0ea316ccaf7fcfc8362d22f8ab63772ae", "size": 3651, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "EvtGen1_06_00/doc/evt_particlerep.tex", "max_stars_repo_name": "klendathu2k/StarGenerator", "max_stars_repo_head_hexsha": "7dd407c41d4eea059ca96ded80d30bda0bc014a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-12-24T19:37:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T06:57:20.000Z", "max_issues_repo_path": "EvtGen1_06_00/doc/evt_particlerep.tex", "max_issues_repo_name": "klendathu2k/StarGenerator", "max_issues_repo_head_hexsha": "7dd407c41d4eea059ca96ded80d30bda0bc014a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EvtGen1_06_00/doc/evt_particlerep.tex", "max_forks_repo_name": "klendathu2k/StarGenerator", "max_forks_repo_head_hexsha": "7dd407c41d4eea059ca96ded80d30bda0bc014a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1057692308, "max_line_length": 71, "alphanum_fraction": 0.7310325938, "num_tokens": 1104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.32388227054517593}}
{"text": "\\chapter{Theory}\n\\label{sec:theory}\n\n\n\\section{Design Load Cases (DLCs)}\nThe user must specify the metocean conditions that drive the wind and\nwave loads upon the floating substructure.  \\textit{FloatingSE}\ncurrently only uses the single load case of maximum thrust coincident\nwith maximum wave loading to drive the substructure design. The\nassumption is that this load case would be the driver for substructure\nsizing and stability.  Ideally, multiple DLCs and metocean conditions\nwould be used for design optimization.  The capability to optimize over\nmultiple DLCs will be added to future versions of the model.  By not\ncurrently including a formal set of IEC DLCs, the conceptual designs\nderived in this work should be considered preliminary and subject to\nextensive revision once other load cases, and higher-fidelity analysis,\nis brought to bear.\n\n\\section{Load Path}\nAs with other WISDEM models, the primary simplification in\n\\textit{FloatingSE} is the treatment of all loads as pseudo-static. This\napproximation significantly reduces computational time and resources,\nsince an accurate calculation of dynamic loads requires more\nsophisticated numerical tools and simulations.  However, dynamic effects\ncan still dominate drive component sizing for floating platforms, thus\nthe static loading assumption gives a rough approximation of the total\nloading.  Furthermore, fatigue effects and structural lifetime estimates\nare also excluded for now, but could be incorporated in future\ndevelopments.\n\nA floating wind turbine undergoes loading from a number of sources.  The\nprimary loading source for the tower comes from the aerodynamic loads\ninduced by the rotor. The substructure must resist the combination of\nboth rotor loads and hydrodynamics loads, with the latter becoming more\nand more important as water depth and wave heights increase.\n\\textit{FloatingSE}, together with other WISDEM modules, accounts for\nthese two dominant load sources, as well as the self-loading of gravity\nloads.  Other sources of loading, such as installation loads, accidental\nloads, vortex-induced vibrations, ice, and seismic loads are ignored.\n\n\\subsection{Wind and Wave Loads}\nWind drag loads are applied to the tower body and the upper part of the\nsubstructure that extends above the waterline.  They are not applied to\nconnecting truss members that may be part of the substructure geometry.\nThese drag loads are computed assuming the tower and columns are smooth\ncircular cross-sections and that the drag coefficient can be selected as\na function of the flow Reynolds number \\citep{Roshko}.  The aerodynamic\ndrag force is a function of height, since the wind profile and\ncross-sectional geometry varies along that dimension.  For the wind\nprofile, the standard power-law scaling is used,\n\\begin{equation}\n  U_a(z) = U_{ref}\\left(\\frac{z}{z_{ref}}\\right)^{\\alpha}\\quad,\n\\end{equation}\nwhere $U_a(z)$ is the wind velocity as a function of height, $U_{ref}$ is a\nreference wind speed measured at a reference height, $z_{ref}$, and\n$\\alpha$ is the shear exponent used in the power-law approximation of\nwind profiles.  The wind profile then feeds the aerodynamic drag,\nReynolds number, and drag coefficient,\n\\begin{equation} \\label{eqn:drag}\n  dF(z) = \\frac{1}{2} \\rho_a U_a^2(z) d(z) c_d(Re) dz;\\qquad\n  Re_d = \\frac{\\rho_a U_a(z) d(z)}{\\mu_a}\\quad,\n\\end{equation}\nwhere $Re_d$ is the Reynolds number based on diameter, $\\rho_a$ and\n$\\mu_a$ are the density and viscosity of air, $d(z)$ is the diameter of\nthe column as a function of height, $c_d$ is the 2-D drag coefficient, and\n$dF(z)$ is the force per unit length in the z-direction.\n\nWave drag loads arise from similar processes, but are computed using\nMorison's equation, a semi-empirical expression that predicts the total\nhydrodynamic loads.  It is comprised of two components, one for viscous\ndrag contributions and another for inertial effects (which includes\nincident, diffracted, and radiated wave effects).  For flow past\nstructures with circular cross sections, Morison's equation for force\nper unit length ($dF(z)$) takes the form,\n\\begin{equation} \\label{eqn:morison}\n  dF(z) = \\frac{\\pi d^2(z)}{4} \\rho_w C_m \\dot{U}_w(z)dz + \\frac{1}{2} \\rho_w U_w^2(z) d(z) c_d(Re)dz\\quad,\n\\end{equation}\nwhere $C_m$ is the added mass coefficient (assumed to be $C_m=2$),\n$U_w(z)$ is the current speed as a function of height, $\\dot{U}_w(z)$ is\nthe acceleration as a function of height, and the Reynolds number is\ncomputed by substituting in the appropriate properties for water,\n\\begin{equation}\nRe_d = \\frac{\\rho_w U_w(z) d(z)}{\\mu_w}\\quad.\n\\end{equation}\n\nTo compute Morison's equation, expressions for local fluid velocity and\nacceleration are required.  Wave particle velocity (not the same as the bulk\nvelocity of the wave) is assumed to follow linear (Airy) wave theory\n\\begin{equation} \\label{eqn:Uwave}\nU_w(z) = a\\omega\\frac{\\cosh\\left[\\kappa\\left(z + D \\right)\\right]}{\\sinh\\left(\\kappa D\\right)}\\cosh\\left(\\kappa x -\n  \\omega t\\right);\n\\qquad \\omega=\\frac{2\\pi}{T} = \\sqrt{ g \\kappa \\tanh\\left(\\kappa\n    D\\right) } \\quad,\n\\end{equation}\nwhere $\\omega$ is the circular frequency, $T$ is the wave period, $a$ is\nthe wave amplitude (half of the significant wave height), $D$ is the\ntotal water depth, $g$ is the acceleration of gravity, and $\\kappa$ is\nthe wave number numerically computed from the dispersion relationship\ngiven as the last expression in Equation \\ref{eqn:Uwave}.  Note that the\nhorizontal particle velocity varies in time and space (by the\n$\\kappa x - \\omega t$) term.  Thus, the individual particles in the wave\nare also accelerating at different rates,\n\\begin{equation} \\label{eqn:Awave}\n\\dot{U}_w(z) = a\\omega^2\\frac{\\cosh\\left[\\kappa\\left(z + D \\right)\\right]}{\\sinh\\left(\\kappa D\\right)}\\sinh\\left(\\kappa x -\n  \\omega t\\right)\\quad.\n\\end{equation}\nFor\nsimplicity, \\textit{FloatingSE} only considers the maximum velocity and\nacceleration at a given height, and makes a conservative assumption that\nthey are concurrent in time and space.  This essentially means ignoring the\n$\\kappa x - \\omega t$ term, since the maximum of any hyperbolic sine or cosine\nterm is one.\n\n\n\\subsection{Rotor Nacelle Assembly (RNA) Loads}\nFrom a quasi-steady-state point of view, the RNA loads reduce to three\nforces and three moments along the main coordinate axes\n\\citep{JacketSE}. The thrust is the biggest force responsible for the\nbending moment distribution along the tower and loads on the\nsubstructure.  There is the additional effect of the gravitational load\ncaused by the offset of the RNA center of mass from the tower\ncenterline.  This effect is more pronounced for downwind turbines than\nupwind turbines, but is included regardless.  \\textit{FloatingSE} does\nnot compute the force and moment components directly, but rather accepts\nthem as inputs from other WISDEM modules or from the user directly.\n\n\n\\section{Structural Analysis}\nThe analysis tool, Frame3DD, is an open-source tool for static and\ndynamic structural analysis of 2-D and 3-D frames and trusses with\nelastic and geometric stiffness. It computes the static deflections,\nreactions, internal element forces, natural frequencies, and modal\nshapes using direct stiffness and mass assembly \\citep{frame3dd}.  The\nWISDEM toolkit developed a python interface, \\textit{pyFrame3DD}, to\navoid the use of intermediate input and output text files.  The\nintegration of all loads happens within Frame3DD, where the whole floating\nturbine load path, from the rotor to the keel of the substructure, is\nmodeled with Timoshenko frame elements \\citep{timoshenko}.\n\n\\subsection{Discretization}\nFor the finite element structural analysis of the substructure, the\ndiscretization of the main columns into a handful of sections is still\ntoo coarse to capture the appropriate physics. Long slender components,\nsuch as the tower and substructure columns, are broken up into a\nthree-times finer discretization than the physical cans that they are\nactually made of.  The sectional and nodal variables are re-sampled at\nthis finer spacing.  These additional discretization points give greater\nresolution of internal forces and natural frequencies.  Substructure\npontoons are represented as single frame elements.  Frame elements are\ndescribed by their cross sectional properties (area, moments of inertia,\nmodulus of elasticity, and mass density) and starting and ending nodes.\nFor simple geometries, such as pontoons with tubular cross sections,\nthese properties are straightforward calculations.  For the turbine\ntower, tubular cross section properties are also used, albeit at a finer\ndiscretization.  For substructure columns, it is assumed that the\npermanent or variable ballast and bulkheads are not load-bearing, so\ntubular cross section properties are also used to represent the column\nshell.  However, the material mass density of the frame element is\nscaled to reflect the true mass of the whole section, including ballast,\nto ensure that gravity loads are captured correctly.\n\nFor the tubular cross sections, the critical properties needed by\nFrame3DD given user inputs of diameter, $d$, and tube (or wall)\nthickness, $t$, are,\n\\begin{align*}\n  \\textrm{Outer radius, } r_o &= d/2\\\\\n  \\textrm{Inner radius, } r_i &= r_o - t\\\\\n  \\textrm{Material area, } A &= \\pi \\left( r_o^2 - r_i^2 \\right)\\\\\n  \\textrm{Bending second moment of area, } I_{xx} &= I_{yy} = \\frac{\\pi}{4}\\left( r_o^4 - r_i^4 \\right)\\\\\n  \\textrm{Torsion second moment of area, } I_{zz} &= J_0 = I_{xx} + I_{yy}\\\\\n  \\textrm{Shear area, } A_{s} &= A / \\left[ 1.124235 + 0.055610\\left(\\frac{r_i}{r_o}\\right) +\n           1.097134\\left(\\frac{r_i}{r_o}\\right)^2 - 0.630057\\left(\\frac{r_i}{r_o}\\right)^3 \\right]\\\\\n  \\textrm{Bending modulus, } S &= I_{xx} / r_o \\\\\n  \\textrm{Torsion modulus (shear constant), } C &= I_{zz} / r_o\n\\end{align*}\nNote that the shear area expression is an empirical relationship as\nopposed to an analytical expression.\n\n\\begin{figure}[htb]\n  \\begin{center}\n    \\includegraphics[width=2in]{figs/frameCS.pdf}\n    \\caption{Coordinate system for frame element forces.}\n    \\label{fig:frameCS}\n  \\end{center}\n\\end{figure}\n\n\\subsection{Loads}\nAll of the loads described above are integrated together within\nFrame3DD.  These loads include,\n\\begin{itemize}\n\\item Rotor-nacelle-assembly loads (thrust, moments, etc)\n\\item Mooring line force\n\\item Wind and wave loading\n\\item Gravity loads (weight distribution)\n\\item Hydrostatic pressure loads, including buoyancy\n\\end{itemize}\n\nThe forces, moments, and mass properties of the rotor-nacelle assembly\n(RNA) are inputs to \\textit{FloatingSE} (mass properties are assumed to\nbe relative to the tower top position).  It assumed that the RNA is a\nrigid body with respect to the tower modes and the mass properties,\nforces, and moments, are applied to the corresponding node in the model.\nThe forces along each mooring line are applied to the connection\npoint nodes on the structure.  The wind and wave forces per unit length\nin Equations \\ref{eqn:drag} and \\ref{eqn:morison} are applied as\ntrapezoidally varying loads along the column elements.  Other loads\napplied to the structure include the gravity loads, and the buoyancy\nacting on the submerged elements.\n\n\\subsection{Boundary Conditions}\nMultiple boundary conditions are applied to the structure.  The mooring\nsystem stiffness matrix (linearized about the neutral position) is\napplied at the mooring connection nodes.  However, even with the mooring\nstiffness, the finite element analysis would otherwise still regard the\nstructure as unrestrained and incapable of supporting any static loads.\nThus, in order to successfully compute stress and buckling limits in a\nwell-posed problem, an additional rigid boundary condition (in all 6\nDOF) is imposed at the bottom node of the main column.\n\n\\subsection{Outputs}\nStructural analysis outputs include mass properties of the structure,\nmember stresses, and summary forces and moments on the body.  Mass\nproperties include the total mass of the floating turbine and the mass\nof the substructure itself.  The calculations also allow for easy\ncomputation of the center of mass of the structure (not accounting for\nvariable ballast) and the center of buoyancy (centroid of the submerged\nvolume).  The first two natural frequencies of the structure are also\ncomputed to compare against the range of standard wave frequencies and\nrotor passing frequencies (1P and 3P).  Next, the reaction forces and\nmoments at the boundary node at the keel are taken as the total loading\non the structure.  These are used later in the static stability\ncalculations to ensure that the mooring lines provide adequate restoring\nforce and moment.  Finally, the axial and shear forces within each frame\nelement are extracted and converted to stresses using cross-sectional\nproperties. These element member follow the sign convention in Figure\n\\ref{fig:frameCS},\n\\begin{align*}\n  \\sigma_z &= \\frac{N_z}{A} - \\frac{\\sqrt{M_x^2 + M_y^2}}{S}\\\\\n  \\tau_{z\\theta} &= \\frac{T_z}{C} + \\frac{\\sqrt{V_x^2 + V_y^2}}{A_s}\n\\end{align*}\nwhere $N$ is the axial force (tension or compression), $T$ is the\ntorsional moment, $V$ is the shear force, $M$ is the bending moment,\n$\\sigma_z$ is the axial stress, and $\\tau_{z\\theta}$ is the shear\nstress across axial and hoop principle directions.\n\nHoop stress of the tower is estimated from the dynamic pressure of the\nwind loads using the Eurocode method \\citep{Eurocode}.  Hoop stress of the submerged\ncolumns is determined using the dynamic and static pressure heads of the\nwater.\n\\begin{align}\n  \\sigma_{\\theta,Euro} &= k_w q_{max} \\frac{d-t}{2t};\\qquad q_{max} =\n                         \\frac{1}{2}\\rho_a U_a^2\\\\\n  \\sigma_{\\theta,hydro} &= \\left(q_{max}+p_{hydro}\\right) \\frac{d-t}{2t};\\qquad q_{max} =\n                          \\frac{1}{2}\\rho_w U_w^2\\\\\n  p_{hydro} &= \\rho_w g \\left( a\\frac{\\cosh\\left[\\kappa\\left(z + D \\right)\\right]}{\\cosh\\left(\\kappa D\\right)} - z\\right)\n\\end{align}\nwhere $\\sigma_{\\theta}$ is the hoop stress, $q_{max}$ is the maximum\ndynamic pressure on a cross-section, and $p_{hydro}$ is the hydrostatic\npressure with contributions from wave motion and the static head.  In\nthe Eurocode method, $k_w$ is the dynamic pressure factor for hoop\nstress calculation using cylinder dimensions and an external pressure\nbuckling factor.  Note that the argument, $(z)$, was dropped from many\nof the terms without losing generality.\n\n\n\n\\subsection{Code Compliance as Utilizations}\nOnce the stress components of all structural members are computed, they\nare compared against design code standards for compliance, and serve as\ndesign constraints when conducting optimization.  Multiple code\nstandards are used across all components.  For all columns, the tower,\nand substructure pontoons, stress components (axial, shear, and hoop)\nare combined into a von Mises, equivalent, stress,\n\\begin{equation}\n  \\sigma_{vm} = \\sqrt{\\sigma_a^2 + \\sigma_{\\theta}^2 -\n    \\sigma_a\\sigma_{\\theta} + 3\\tau_{a\\theta}^2}\n\\end{equation}\nwhere $\\sigma_{vm}$ is the von Mises stress, $\\sigma_a$ is the axial\nstress, $\\tau_{a\\theta}$ is the shear stress across axial and hoop\nprinciple directions.  and $\\sigma_{\\theta}$ is chosen as the relevant\nhoop stress.  The von Mises stress is compared against the yield stress,\n$\\sigma_y$, and a safety factor as a utilization criterion.\n\nMain column, offset column, and tower segment stresses and geometry are\nalso evaluated against a shell buckling criterion published by\n\\citet{Eurocode} and a global buckling criterion published by\n\\citet{Germanischer}.  Note that the implementation of the Eurocode\nbuckling is modified slightly so as to produce continuously\ndifferentiable output.  See \\citet{JacketSE} for a more detailed\nexposition.\n\nFor submerged columns, additional code standard utilization ratios are\ntaken from the \\citet{api2U}, Bulletin 2U (specifically the procedure\noutlined in Appendix B).  These standards also apply shell and general\nbuckling criterion with a margin of safety in a manner that accounts for\nstiffeners and the common buckling modes of submerged structures.\nFuture efforts will also apply Bulletin 2V, the standards for plates, to\nthe legs that support taut mooring lines.\n\n\n\\section{Mooring Lines}\nThe quasi-steady mooring system analysis is handled by the external\nMooring Analysis Program (MAP++) library \\citep{MAP}, which has\nconvenient Python bindings to access the simulation output, bundled into\nthe WISDEM \\textit{pyMAP} module. MAP++ is designed to model the\nsteady-state forces on a Multi-Segmented, Quasi-Static (MSQS) mooring\nline. Seabed contact, seabed friction, and multi-element mooring lines\nwith arbitrary connection configurations can be analyzed.  MAP++ inputs\ninclude sea depth, geometry descriptions of the mooring line\nconnections, and material properties of the lines.  For chain and\nrope-based cables, these material properties are not easily derived and\nwould be typically provided by a manufacturer.  We borrow from the\napproach of the popular Orcina OrcaFlex software \\citep{orca} and use\nthe following expressions,\n\\begin{align*}\nMBL &= 2.74\\times 10^7  d^2 \\left(44 - 80d\\right) \\,[\\unit{N}] \\\\\nmass &= 19.9\\times 10^3 d^2 \\,[\\unit{kg/m}]\\\\\nA &= 2\\left(\\pi d^2 / 4 \\right)\\,[\\unit{m^2}]\\\\\nEA &= 8.54\\times 10^{10} d^2\\,[\\unit{N}]\\\\\ncost &= 3.415\\times 10^4 d^2 \\,[\\unit{USD}]\n\\end{align*}\nwhere $MBL$ is minimum breaking load, $d$ is the diameter of a single\nhalf-chain link, $A$ is the chain cross-sectional area, $E$ is the\nYoung's modulus, $EA$ is the axial stiffness.  When conducting\noptimization, the expression for $MBL$ is poorly posed due to its limited\nrange of diameter applicability, so a linear fit is used instead,\n\\begin{equation}\nMBL = 1000 \\max\\left(1.0, -5445.3 + 176972.7 d\\right)\n\\end{equation}  \n\n\n\\section{Hydrostatic Stability}\n\\label{sec:static}\n\\subsection{Neutral Buoyancy}\nAny floating body requires enough water displacement to create\nsufficient buoyancy force such that the body stays afloat in the most\nextreme loading and environmental conditions.  This level of\ndisplacement would otherwise be overkill for more benign loading\nconditions.  Since a floating turbine is designed for a constant hub\nheight, variable amounts of ballast are required to maintain a neutrally\nbuoyant system for all operating conditions.  The variable ballast is\nsimply ocean water that is pulled in or pumped out of holding areas\nwithin the substructure columns.\n\nIn \\textit{FloatingSE}, the variable ballast water mass is calculated as\nthe difference between the total mass of displaced water and the total\nmass of the floating turbine.  This mass is then divided by the water\ndensity to obtain the variable ballast volume, which is then compared to\nthe frustum shell cross section profile above the permanent ballast to\ndetermine the height of the water ballast within the column.  Once this\nis determined, the final center of mass of the system can be determined.\n\n\\subsection{Surge/Sway Stability}\nSurge and sway stability is not actively tracked over the coarse of a\nload case.  Instead the total surge force on the structure is calculated\nat the initial conditions and compared to the restoring force of the\nmooring system at the maximum allowable surge offset, which is specified\nby the user.\n\nThe surge direction is assumed to be aligned with the wind vector, which\nis aligned with the $x$-axis.  Since the rotor yaw is assumed to be\n$0^{\\circ}$, the surge forces on the turbine include the rotor thrust\nand the wind and wave drag on the tower and substructure.  The final\nsurge force over the whole structure is taken from the $x$-direction\nreaction force of the reaction node in Frame3DD.\n\nThe restoring force is calculated as the smallest possible restoring\nforce after a displacement in any angular direction in the mooring\nmodel.  Since the alignment of the mooring lines relative to the\nincoming wind direction is arbitrary, a maximum offset is simulated at\n$2^{\\circ}$ increments around the unit circle. Also recorded in this\nsurvey is the maximum mooring line tension in any\nline, in any direction, for comparison against the minimum breaking load\nvalue,\n\\begin{equation}\n  F_{x,restore} = \\min_{i\\in a} F_{x,i}\\quad \\mbb{T}_{moor} = \\max_{l\\in L,i\\in a} \\mbb{T}_{l,i}\\,;\n\\qquad L=\\left\\{1,2\\ldots nlines\\right\\}, \\, a= \\left\\{0^{\\circ}, 2^{\\circ}\\ldots 360^{\\circ}\\right\\}\n\\end{equation}\nwhere $F_x$ is the surge force and $\\mbb{T}$ is the tension.  If\nrestoring force at this maximum offset is greater than the surge force\napplied, then the system is considered stable in surge.  Since the wind\nand wave profiles are essentially 2-D in the $x-z$ plane, the sway\nstability is given the same status as surge stability.\n\n\n\\subsection{Pitch Stability}\nThe approach to pitch stability determination is similar to that of\nsurge stability.  The total pitching moment on the floating turbine is\ncalculated and compared to the restoring moment at the maximum allowable\nangle of heel.  If the restoring moment at this max heel angle is\ngreater than the pitching moment applied, the system is said to be\nstatically stable in pitch.\n\nSimilar to the surge force calculation, the total pitching moment is\ndetermined from the reaction moment at the boundary condition\nin the Frame3DD analysis.  The pitching moment has contributions from\nthe wind and wave loads on the structure, the rotor forces and torques,\nthe buoyancy forces on the submerged substructure, and the off-center\nweight of components (e.g. the RNA).\n\nThe restoring pitching moment has two primary contributions.  The first\nis from the mooring lines.  Similar to the surge force calculation, here\nthe floating turbine is deflected in pitch by the maximum allowable heel\nangle and the mooring forces are recorded.  The restoring moment\ncontribution from the mooring system is computed as,\n\\begin{equation}\n  \\mbf{M_{moor}} = \\sum_i \\mbf{r_{cm-l}} \\times \\mbf{F_l}\n\\end{equation}\nwhere $r_{cm-l}$ is the vector from the center of mass to the mooring\nconnection, and $F_l$ is the force applied by the $l$-\\th\\~mooring\nline.  As above, $F_l$ is taken as the minimum set over the possible\norientations of the mooring lines relative to the direction.\n\n\\begin{figure}[htb]\n  \\begin{subfigure}[b]{0.49\\linewidth}\n    \\centering \\includegraphics[height=3.5in]{figs/metacenterA.pdf}\n    \\caption{}\n  \\end{subfigure}\n  \\begin{subfigure}[b]{0.49\\linewidth}\n    \\centering \\includegraphics[height=3.5in]{figs/metacenterB.pdf}\n    \\caption{}\n  \\end{subfigure}\\\\\n  \\caption{Static stability of floating offshore wind turbines.}\n  \\label{fig:metacenter}\n\\end{figure}\n\nThe second contributing restoring moment comes from the motion of the\ncenter of buoyancy away from alignment with the center of mass.  This is\na standard calculation in naval architecture \\citep{thiagarajan2014} and is\ndiagrammed in Figure \\ref{fig:metacenter}.  In this diagram, the center\nof mass is denoted, $G$, the center of buoyancy is $B$, and the\nmetacenter is $M$.  In neutral conditions (Figure \\ref{fig:metacenter}a),\nall of these points are vertically aligned.\n\nAs the structure lists or heels, the center of buoyancy shifts toward\nthe side of the structure that is more submerged (from $B$ to $B'$) and\nthe buoyancy force no longer passes through the center of mass.\nInstead, the buoyancy force passes through the metacenter with an\neffective moment arm of $GZ$ from the center of mass (Figure\n\\ref{fig:metacenter}b).  The metacenter is defined as the common point\nthrough which the buoyancy force acts as it pitches through small\ndisplacements, for bodies with sufficient freeboard margin.\n\nThe metacenteric height, $GM$ is most easily calculated as an offset from the\ncenter of buoyancy ($BM$) by,\n\\begin{equation}\n  h_{meta} = M - G = GM = BM + BG;\\quad BM = \\frac{I_w}{V}\n\\end{equation}\nwhere $BG$, the distance between the centers of buoyancy and gravity is\neasily calculated, $I_w$ is the second moment of area of the substructure waterplane\n(with units of \\unit{$m^4$}) and $V$ is the total volume of displacement\n(with units of \\unit{$m^3$}).  Note that for semisubmersible type\ngeometries, $I_w$ is calculated with the parallel axis theorem for all\nof the columns at the waterplane,\n\\begin{equation}\n  I_w = \\sum_i \\left( I_{w,i} + S_ir_i^2 \\right)\n\\end{equation}\nwhere $S_i$ is the waterplane cross sectional area of the $i$-\\th column and $r_i$\nis the distance from the waterplane centroid to the $i$-\\th column centroid.\n\nThe restoring moment is then the buoyancy force acting through the\nrestoring arm, $GZ$,\n\\begin{equation}\n  M_{meta} = F_B GZ = F_B GM \\sin \\varphi\n\\end{equation}\nwhere $\\varphi$ is the angle of heel.\n\nFor this reason, the metacenter must be located above the center of mass\nfor static stability.  This condition is imposed on the design as a\nconstraint.  Note that the total volume of displacement, and the\nsubsequent buoyancy force, is not recalculated in the perturbed\nconfiguration.  It is assumed that the angles of deflection are small\nand that there is sufficient freeboard and design symmetry such that the\ntotal displacement is constant.\n\nThe total restoring pitching moment is then the sum of two\ncontributions,\n\\begin{equation}\n  M_{y,restore} = M_{y,moor} + M_{meta}\n\\end{equation}\n\n\\section{Hydrodynamic Stability}\nFloating bodies are typically modeled, for small motions and linearized\nbehavior, as a second-order differential system with mass, damping, and\nspring stiffness terms,\n\\begin{equation}\n  \\left(\\mbf{M} + \\mbf{A}\\right)\\ddot{\\mbf{x}} + \\mbf{C}\\dot{\\mbf{x}} +\n  \\mbf{K} = \\mbf{F}\\left( t \\right)\n\\end{equation}\nwhere $\\mbf{x}\\in\\mbb{R}^6$ is the six-degree of freedom vector\n(commonly ordered as 1-surge, 2-sway, 3-heave, 4-roll, 5-pitch,\n6-yaw), $\\mbf{M}$ is the mass matrix, $\\mbf{A}$ is the added mass\nmatrix, $\\mbf{C}$ is the damping matrix, and $\\mbf{K}$ is the stiffness\nmatrix.  The right-hand side of the equation captures the time-dependent\nsummation of all forces.\n\nAs a low-fidelity, quasi-static sizing and cost module,\n\\textit{FloatingSE} does not attempt to capture all of the matrix\nentries or forcing terms of the hydrodynamics.  A more sophisticated\ntime- or frequency-domain solver, where these quantities are calculated,\nmay be linked or included into \\textit{FloatingSE} in the future.\nNevertheless, it does attempt to compute the diagonal entries of the\nmass and stiffness matrices in order to derive the rigid body natural\nfrequencies of the system,\n\\begin{equation}\n  f_i = \\frac{\\omega_i}{2\\pi} =\n  \\frac{1}{2\\pi}\\sqrt{\\frac{K_{ii}}{M_{ii}+A_{ii}}}, \\quad \\forall i \\in\n  \\left[1\\ldots6\\right]\n\\end{equation}\nwhere $f_i$ are the frequencies of the eigenmodes and $\\omega_i$ is the\ncircular frequency.  The mass matrix diagonal entries, $M_{ii}$, are simply the mass and\nmoments of inertia of the whole system,\n\\begin{equation}\n  M_{11} = M_{22} = M_{33} = m_{sys};\\quad M_{44} = I_{xx,sys};\\quad M_{55} = I_{yy,sys};\\quad M_{66} = I_{zz,sys};\n\\end{equation}\nWhere the coordinate system notation is consistent with that of Figure\n\\ref{fig:diagram}.\n\nThe added mass matrix diagonal entries are evaluated via standard strip\ntheory for the tapered vertical columns.  The added mass for the system is a\nsummation over the columns, using the parallel axis theorem for the\nrotational degrees of freedom.  Pontoon contributions to system added\nmass are currently ignored.  The column quantities are calculated as,\n\\begin{equation}\n  A_{11} = A_{22} = \\rho V;\\quad A_{33} = \n  \\left(\\frac{1}{2}\\right)\\frac{8}{3} \\rho \\max \\left[ R^3(z)\\right] ; \\quad A_{44} =\n  A_{55} = \\pi\\rho\\int\\left(z-z_{cb}\\right)R^2(z)dz;\\quad A_{66} = 0.0;\n\\end{equation}\nwhere $\\rho$ is the water density, $R(z)$ is the column radius along its\naxis, and $V$ is the submerged volume.  The extra factor of $1/2$ in\n$A_{33}$ is included to account for the fact that the top of the column\nextends above the waterline.  Also, the integral in $A_{55}$ is only evaluated\nalong the submerged portion of the column.\n\nThe stiffness matrix is comprised of contributions from the mooring\nand hydrostatic stiffness.  The mooring linearized stiffness matrix is output\ndirectly from MAP++ and needs no additional processing within\n\\textit{FloatingSE}.  The hydrostatic stiffness, for a vertical column, is derived from the same\nprincipals described above regarding the metacentric height,\n\\begin{equation}\n  K_{ii} = K_{ii}^{moor} + K_{ii}^{hydro};\\quad K_{33}^{hydro} = \\rho g\n  S_{sys};\\quad K_{44}^{hydro} =  K_{55}^{hydro} = \\rho g V h_{meta}\n\\end{equation}\nwhere $S_{sys}$ is the waterplane area of the system.\n\nOnce the rigid body natural frequencies (eigenmodes) of the system are\ncalculated, they are compared against the standard wave frequencies\nrange, \\unit[0.5--5]{Hz}, and expressed as a design constraint (with a\npartial safety factor).\n\n", "meta": {"hexsha": "082bbab01ecbdc53da1c02259c10e1c83496dfe9", "size": 28766, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/latex-doc/theory.tex", "max_stars_repo_name": "mattEhall/FloatingSE", "max_stars_repo_head_hexsha": "f13e0f38a7742ea00a8f446a9ebf505dcf7acd42", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-27T15:09:02.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-27T15:09:02.000Z", "max_issues_repo_path": "docs/latex-doc/theory.tex", "max_issues_repo_name": "mattEhall/FloatingSE", "max_issues_repo_head_hexsha": "f13e0f38a7742ea00a8f446a9ebf505dcf7acd42", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-05-17T14:57:05.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-17T14:57:05.000Z", "max_forks_repo_path": "docs/latex-doc/theory.tex", "max_forks_repo_name": "mattEhall/FloatingSE", "max_forks_repo_head_hexsha": "f13e0f38a7742ea00a8f446a9ebf505dcf7acd42", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2015-12-26T01:06:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-08T20:19:57.000Z", "avg_line_length": 52.2068965517, "max_line_length": 123, "alphanum_fraction": 0.769032886, "num_tokens": 7601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.32387814443043395}}
{"text": "\\documentclass{bioinfo}\n\\copyrightyear{2017}\n\\pubyear{2017}\n\n\\usepackage{hyperref}\n\\usepackage{amsmath}\n\\usepackage[ruled,vlined]{algorithm2e}\n\\newcommand\\mycommfont[1]{\\footnotesize\\rmfamily{\\it #1}}\n\\SetCommentSty{mycommfont}\n\\SetKwComment{Comment}{$\\triangleright$\\ }{}\n\n\\usepackage{natbib}\n\\bibliographystyle{apalike}\n\n\\begin{document}\n\\firstpage{1}\n\n\\title[Pairwise alignment with DP]{On pairwise alignment with dynamic programming}\n\\author[Li]{Heng Li}\n\\address{Broad Institute, 415 Main Street, Cambridge, MA 02142, USA}\n\n\\maketitle\n\n\\begin{abstract}\nThis \\emph{informal} note introduces important literatures on pairwise\nbiological sequence alignment with dynamic programming (DP), disambiguates a\nfew different formulations, investigates the choice of gap cost function and\ndiscusses the implementation of DP-based alignment with a focus on practical\napplications. It targets developers who are interested in the history of\nDP-based alignment and want to understand it in depth.  Importantly, this note\nis not a general tutorial. Audience should be familiar with the basis of\npairwise alignment before reading the note.\n\\end{abstract}\n\n\\begin{methods}\n\\section{Alignment with dynamic programming}\n\nLet $T$ be the \\emph{target} sequence or the \\emph{reference} sequence of\nlength $n=|T|$ and $Q$ be the \\emph{query} sequence of length $m=|Q|$. Gaps on\nthe target sequence are \\emph{deletions}; gaps on the query sequence are\n\\emph{insertions}. Function $s(i,j)$, $0\\le i<n$ and $0\\le j<m$, gives the\nscore between the $T[i]$ and $Q[j]$. We will focus on global alignment\nalgorithms because it is usually more complex than local alignment due to\nnon-trivial initial conditions.\n\n\\subsection{Levenshtein distance}\n\n\\emph{Levenshtein distance}~\\citep{Levenshtein:1966aa} is the minimum sum of\nsubstitutions, insertions and deletions among all possible alignments between\ntwo sequences. The author proposed the measurement but did not provide an\nalgorithm to compute the distance. Levenshtein distance is the most common\nmeasure of edit distance. Other variants of edit distances may include fewer\n(e.g. no substitutions) or more types of primitive edit operations (e.g.\ntranspositions).\n\nLevenshtein distance can be computed with dynamic programming (DP). Let\n$H_{ij}$ be the distance between prefixes $T[0..i]$ and $Q[0..j]$. The distance\nbetween the full sequences will be $H_{n-1,m-1}$, which can be recursively\ncomputed with\n\\begin{equation}\\label{eq:ed}\nH_{ij}=\\min\\{H_{i-1,j-1}+1-\\delta_{T[i],Q[j]}, H_{i-1,j}+1, H_{i,j-1}+1\\}\n\\end{equation}\nwhere $\\delta_{ab}$ is the Kronecker delta function, which equals 1 if $a=b$ or\n0 otherwise. The initial conditions are: $H_{-1,j}=j+1$ and $H_{i,-1}=i+1$.\nThis is an $O(mn)$ algorithm.\n\nPractically faster algorithms exist. \\citet{Landau:1986aa} found an $O(kn)$\nalgorithm that guarantees to find the optimal solution if the edit distance is\nno larger than $k$. It is particularly fast if the distance is\nsmall~\\citep{Sosic:2015aa}.\n\nFollowing the idea behind the 4-Russian problem~\\citep{Arlazarov:1970aa},\n\\citet{Wu:1996aa} made an important observation that the differences\nbetween adjacent cells\n\\[\\left\\{\\begin{array}{l}\nu_{ij}\\triangleq H_{ij}-H_{i-1,j}\\\\\nv_{ij}\\triangleq H_{ij}-H_{i,j-1}\n\\end{array}\\right.\\]\nonly take values $-1$, $0$ or $1$. They transformed Eq.~(\\ref{eq:ed}) to\n\\begin{equation}\n\\left\\{\\begin{array}{l}\nz_{ij}=\\min\\{1-\\delta_{T[i],Q[j]},v_{i-1,j}+1,u_{i,j-1}+1\\}\\\\\nu_{ij}=z_{ij}-v_{i-1,j}\\\\\nv_{ij}=z_{ij}-u_{i,j-1}\n\\end{array}\\right.\n\\end{equation}\nand used a lookup table to speed up the computation. \\citet{Myers:1999aa}\nfurthered this idea with bit-level parallelization, resulting in an $O(mn/w)$\nalgorithm where $w$ is the size of a machine word in bits. Combined with\nbounding~\\citep{Ukkonen:1985aa}, Myers' algorithm is significantly faster than\nEq.~(\\ref{eq:ed}) for long sequences.  Edlib~\\citep{Sosic:2017aa} provides an\nefficient implementation of this algorithm with added functionality.\n\n\\subsection{Linear gap cost}\n\nWhen \\citet{Needleman:1970aa} first proposed to align a pair of biological\nsequences with DP, they focused on a linear gap cost function\n$\\gamma_0(k;e)=k\\cdot e$, $e>0$. Let the optimal score up to cell $(i,j)$ be\n$H_{ij}$. It can be computed with\n\\begin{equation}\\label{eq:linear}\nH_{ij}=\\max\\{H_{i-1,j-1}+s(i,j), H_{i-1,j}-e, H_{i,j-1}-e\\}\n\\end{equation}\nThis equation is a generalization of Eq.~(\\ref{eq:ed}). It gives matches,\nmismatches and gaps different weights. Typically, we require $2e$ to be larger\nthan the mismatch cost; otherwise the alignment would always prefer two gaps\nover a mismatch -- the final alignment would not contain any mismatches.\n\nThe Needleman-Wunsch algorithm has a history of multiple inventions in\ndifferent fields. Readers are referred to \\citet{Navarro:2001aa} for a more\ncomplete survey.\n\nIt is also possible to apply Myer's bit-parallelis to the linear gap cost\nif $s(i,j)$ and $e$ are small integers~\\citep{Loving:2014aa}.\n\n\\subsection{Classical formulation of affine gap cost}\n\nWith a linear cost function, a long gap is considered to arise from a series of\nsmall gaps independently. In evolution, however, a long gap at times results\nfrom one event (e.g. a transposon insertion). A linear gap cost often breaks a\nlong gap into small pieces and complicates the interpretation of alignment.\nTherefore, it is discouraged to use a linear cost to produce alignment for\nevolutionarily related sequences.\n\nThe limitation of linear cost motivated \\citet{Waterman:1976aa} to use a more\ngeneral cost function. This work was later folded to \\citet{Smith:1981aa},\n\\emph{the} Smith-Waterman paper. With a general cost, the time complexity to\nfind the optimal alignment is $O(mn\\max\\{m,n\\})$. \\citet{Gotoh:1982aa} showed\nthat when the cost function takes a form $\\gamma_1(k;q,e)=q+k\\cdot e$, which is\ncalled \\emph{affine gap cost}, it is possible to solve the alignment problem in\n$O(mn)$ time. \\citet{Altschul:1986aa} fixed an issue in the original Gotoh's\nalgorithm and introduced the formulation we commonly use today.\n\n\\subsubsection{Durbin's formulation}\n\nTo give alignment a probablitistic interpretation, \\citet{Durbin:1998uq} \nintroduced\n\\begin{equation}\\label{eq:durbin}\n\\left\\{\\begin{array}{l}\nM_{ij}=\\max\\{M_{i-1,j-1}, E_{i-1,j-1}, F_{i-1,j-1}\\} + s(i,j)\\\\\nE_{ij}=\\max\\{M_{i-1,j}-q, E_{i-1,j}\\} - e\\\\\nF_{ij}=\\max\\{M_{i,j-1}-q, F_{i,j-1}\\} - e\n\\end{array}\\right.\n\\end{equation}\nThis formulation has a natural connection to pair-HMM with each state having a\nclear meaning in alignment. It, however, has one problem: it disallows\ntransitions between $E$ and $F$ states and thus forbids insertions immediately\nfollowed by deletions (and vice versa). When the gap extension cost $e$ is\nsmaller than the half of a mismatch cost, transitions between $E$ and $F$ may\nyield a better alignment score. It is possible to add transitions between $E$\nand $F$ in Eq.~(\\ref{eq:durbin}), but in practice, AE86's\nformulation~\\citep{Altschul:1986aa} will be simpler and faster to implement.\n\n\\subsubsection{AE86's formulation}\n\nIn Eq.~(\\ref{eq:durbin}), if we let:\n\\[H_{ij}\\triangleq\\max\\{M_{ij},E_{ij},F_{ij}\\}\\]\nDurbin's formulation allowing $E$--$F$ transitions becomes\n\\begin{equation}\\label{eq:ae86-ori}\n\\left\\{\\begin{array}{l}\nE_{ij}=\\max\\{H_{i-1,j}-q, E_{i-1,j}\\} - e \\\\\nF_{ij}=\\max\\{H_{i,j-1}-q, F_{i,j-1}\\} - e \\\\\nH_{ij}=\\max\\{H_{i-1,j-1}+s(i,j), E_{ij}, F_{ij}\\}\n\\end{array}\\right.\n\\end{equation}\nThis is AE86's formulation. In practice, we sometimes compute the cells in the\nfollowing order\n\\begin{equation}\\label{eq:ae86}\n\\left\\{\\begin{array}{l}\nH_{ij}=\\max\\{H_{i-1,j-1}+s(i,j), E_{ij}, F_{ij}\\}\\\\\nE_{i+1,j}=\\max\\{H_{ij}-q, E_{ij}\\} - e \\\\\nF_{i,j+1}=\\max\\{H_{ij}-q, F_{ij}\\} - e\n\\end{array}\\right.\n\\end{equation}\nwith initial conditions\n\\begin{equation}\n\\left\\{\\begin{array}{ll}\nH_{-1,-1}=0\\\\\nH_{-1,j}=-q-e-j\\cdot e & (0\\le j<m)\\\\\nH_{i,-1}=-q-e-i\\cdot e & (0\\le i<n)\\\\\nE_{0j}=-2q-2e-j\\cdot e & (0\\le j<m)\\\\\nF_{i0}=-2q-2e-i\\cdot e & (0\\le i<n)\n\\end{array}\\right.\n\\end{equation}\nWe don't need $E_{-1,\\cdot}$ or $F_{\\cdot,-1}$ because Eq.~(\\ref{eq:ae86})\ndoes not start with these initial values.\n\nAE86 can be impelmented in different ways depending on the order of computation\nand how row scores are stored. Algorithm~\\ref{algo:ae86} gives one\nimplementation. At the beginning of each iteration at line 2, $f=F_{ij}$,\n$h=H_{i,j-1}$, $H[j]=H_{i-1,j-1}$ and $E[j]=E_{ij}$. The loop computes\n$H$ in cell $(i,j)$, $E$ in the next row and $F$ in the next column.\nThis algorithm uses a query profile at line 1. It is a common techique\nto accelerate the inner loop.\n\n\\begin{algorithm}[tb]\n\\DontPrintSemicolon\n\\footnotesize\n\\KwIn{Target sequence $T$ and query $Q$; scoring matrix $S(\\cdot,\\cdot)$ and\naffine gap cost $\\gamma_1(k;q,e)=q+k\\cdot e$}\n\\KwOut{Best alignment score between $T$ and $Q$}\n\\BlankLine\n\\textbf{Function} {\\sc AlignScore}$(T,Q,q,e)$\n\\Begin {\n\t\\nl\\For (\\Comment*[f]{Generate query profile}) {$a\\in\\Sigma$} {\n\t\t\\For{$j\\gets0$ \\KwTo $|Q|-1$} {\n\t\t\t$P[a][j]\\gets S(Q[j],a)$\\;\n\t\t}\n\t}\n\t\\For{$j\\gets0$ \\KwTo $|Q|-1$} {\n\t\t$H[j]\\gets-q-j\\cdot e$\\Comment*[r]{$H[j]=H_{-1,j-1}$}\n\t\t$E[j]\\gets-2q-2e-j\\cdot e$\\Comment*[r]{$E[j]=E_{0j}$}\n\t}\n\t$H[j]\\gets 0$\\Comment*[r]{$H_{-1,-1}=0$}\n\t\\For{$i\\gets0$ \\KwTo $|T|-1$} {\n\t\t$f\\gets-2q-2e-i\\cdot e$\\Comment*[r]{$f=F_{i0}$}\n\t\t$h\\gets-q-e-i\\cdot e$\\Comment*[r]{$h=H_{i,-1}$}\n\t\t$p\\gets P[T[i]]$\\;\n\t\t\\For{$j\\gets0$ \\KwTo $|Q|-1$} {\n\t\t\t\\nl$s\\gets p[j]$\\Comment*[r]{$s=S(Q[j],T[i])$}\n\t\t\t$h'\\gets\\max\\{H[j]+s,E[j],f\\}$\\;\n\t\t\t$H[j]\\gets h$\\Comment*[r]{$H[j]=H_{i,j-1}$}\n\t\t\t$h\\gets h'$\\Comment*[r]{$h=H_{ij}$}\n\t\t\t$E[j]\\gets\\max\\{h-q,E[j]\\}-e$\\Comment*[r]{$E[j]=E_{i+1,j}$}\n\t\t\t$f\\gets\\max\\{h-q,f\\}-e$\\Comment*[r]{$f=F_{i,j+1}$}\n\t\t}\n\t\t$H[|Q|]\\gets h$\\;\n\t}\n\t\\Return $H[|Q|]$\\;\n}\n\\caption{AE86's formulation with affine gap cost}\\label{algo:ae86}\n\\end{algorithm}\n\n\\subsubsection{Effect of affine gap cost}\\label{sec:affine-eff}\n\nFor simplicity, we use one score $a>0$ for all types of matches and one cost\n$b>0$ for all types of mismatches. Ignore gaps for now. If the identity between\n$T$ and $Q$ is below $1-a/(a+b)$, $T$ and $Q$ will get a negative alignment\nscore. The $b:a$ ratio sets the minimum identity. Now suppose we have a long\ndeletion. If $\\lceil q/(a+b)\\rceil$ or more residues on the query adjacent to\nthe gap are mismatches but have a perfect match to a subsequence in the gap,\nthe perfect match will yield a higher alignment score and split the long gap in\ntwo. Gap open cost $q$ determines how easily a long gap to be split into two or\nmore smaller gaps. Gap extension $e$ is directly related to $E$--$F$\ntransitions: if $b>2e$, there may be insertions immediately followed by\ndeletions. $q$ and $e$ together control the total number of gaps. Suppose in a\nsmall region there are $x$ mismatches and one gap. We may achieve a better\nscore by opening a new gap and add $2y$ gap extensions if $x\\cdot b>q+2y\\cdot\ne$, approximately. We also note that scoring must satisfy $2(q+e)>b$; otherwise\nthe alignment would not contain any mismatches.\n\n\\subsection{Affine gap cost: SIMD acceleration}\n\nSIMD CPU instructions perform one action on a vector of data at the same time.\nFor example, with SSE2, a type of SIMD, we can compute the sum of two vectors\nof sixteen 8-bit integers with one CPU instruction. This is much faster than\nsumming with sixteen standard instructions. How many data can be processed with\none SIMD instruction depends on the number of bits in the vector and the max\nvalue of each element in the vector. For example, SSE instructions operate on\n128-bit vectors. We can process four 32-bit integers or eight 16-bit integers\nat the same time. AVX instructions operate on 256-bit vectors. It doubles the\nbandwidth of SSE.\n\nSIMD has been used to speed up DP-based pairwise alignment. There are two\ngeneral classes of SIMD algorithms: inter-sequence and intra-sequence.\nInter-sequence algorithms~\\citep{Rognes:2011aa} align multiple pairs of\nsequences at the same time. It is conceptually easier to implement and faster\nto run but it is tricky to use with other alignment routines. Intra-sequence\nalgorithms align one sequence at a time. There are several ways to implement\nintra-sequence pairwise alignment, depending on how to organize multiple data\ninto one vector.\n\nFor simplicity, we assume each vector consists of four elements.\n\\citet{Wozniak:1997aa} put $(H_{ij},H_{i+1,j-1},H_{i+2,j-2},H_{i+3,j-3})$\ninto a vector and fills the DP matrix along its diagonal.\n\\citet{Rognes:2000aa} took a block of column cells into a vector\n$(H_{ij},H_{i,j+1},H_{i,j+2},H_{i,j+3})$. \\citet{Farrar:2007hs} interleaved columns\ninto $(H_{ij},H_{i,t+j},H_{i,2t+j},H_{i,3t+j})$ in a striped manner, where\n$t=\\lfloor(m+3)/4\\rfloor$ -- the algorithm collates cells distant apart. In\npractice, Farrar's striped algorithm is the fastest and most often\nused~\\citep{Szalkowski:2008aa,Zhao:2013aa}. \\citet{Daily:2016aa} developed a\nprogramming library that implements all three intra-sequence algorithms.\n\n\\subsection{Affine gap cost: Suzuki's formulation}\n\nWhen working with long sequences that yield large alignment scores,\nwe may need to use 32-bit integers to hold the score arrays. With SSE, we can\nonly process four cells at a time. Inspired by \\citet{Myers:1999aa} and\n\\citet{Loving:2014aa}, \\href{https://github.com/ocxtal}{Hajime Suzuki} proposed\nto rewrite Eq.~(\\ref{eq:ae86}) with differences between cells:\n\\begin{equation}\n\\left\\{\\begin{array}{l}\nu_{ij}\\triangleq H_{ij}-H_{i-1,j}\\\\\nv_{ij}\\triangleq H_{ij}-H_{i,j-1}\\\\\nx_{ij}\\triangleq E_{i+1,j}-H_{ij}\\\\\ny_{ij}\\triangleq F_{i,j+1}-H_{ij}\n\\end{array}\\right.\n\\end{equation}\nas\n\\begin{equation}\\label{eq:suzuki}\n\\left\\{\\begin{array}{l}\nz_{ij}=\\max\\{s(i,j),x_{i-1,j}+v_{i-1,j},y_{i,j-1}+u_{i,j-1}\\}\\\\\nu_{ij}=z_{ij}-v_{i-1,j}\\\\\nv_{ij}=z_{ij}-u_{i,j-1}\\\\\nx_{ij}=\\max\\{0,x_{i-1,j}+v_{i-1,j}-z_{ij}+q\\}-q-e\\\\\ny_{ij}=\\max\\{0,y_{i,j-1}+u_{i,j-1}-z_{ij}+q\\}-q-e\n\\end{array}\\right.\n\\end{equation}\nwhere $z_{ij}$ is a temporary variable that does not need to be stored.  We can\nprove that all variables in these equations are bounded by gap costs and the\nextreme match and mismatch scores, but not by the sequence lengths or the peak\nalignment score. For small scores, we can encode 16 cells in one SSE vector.\n\nIn practice, Suzuki's formulation is about twice as slow as Algorithm~1 without\nSSE vectorization, because it involves more computation and cannot use\na query profile. For long sequences when the peak score does not fit 16-bit\nintegers, 16-way vectorized Suzuki's formulation is twice as fast as striped\n4-way vectorization~\\citep{Farrar:2007hs}. Another advantage of Suzuki's\nalgorithm is that it can be adapted for banded alignment.\n\n\\subsection{Piece-wise affine gap cost}\n\nAffine gap cost still has issues with long gaps. Recall that an exact match of\nlength $\\lceil q/(a+b)\\rceil$ in the middle of a long gap splits the gap into\ntwo if moving this exact match to either edge of the gap leads to mismatches\n(Section~\\ref{sec:affine-eff}). For noisy reads, it is not infrequent for a\nlong gap to be split by incidental sequencing errors. We would prefer to\nincrease the gap open cost $q$ to avoid such a split, but this would contradict\nthe high INDEL error rate of some sequencing data.\n\nThe root cause of this dilemma is that gaps are caused by two different\nmechanisms: evolution which may create a long gap with one event, and\nsequencing errors which generate gaps as relatively independent events. A\nbetter gap cost should be concave, such that $\\gamma(k+1)-\\gamma(k)$ is smaller\nwith larger $k$.\n\n\\citet{Miller:1988aa} found an $O(mn\\log\\max\\{m,n\\})$ algorithm for a concave\ngap cost function $\\gamma(k)$. When $\\gamma(k)$ is a piece-wise affine cost\ncomposed of $p$ affine cost functions, their algorithm finds the optimal\nalignment in $O(mn\\log p)$ time. \\citet{Gotoh:1990aa} proposed an $O(mn\\cdot\np)$ algorithm, which is simpler and probably faster for small $p$ in practice.\n\nWhen $p=2$, the two-piece affine cost takes the form\n\\[\n\\gamma_2(k;q,e,\\tilde{q},\\tilde{e})=\\min\\{q+k\\cdot e,\\tilde{q}+k\\cdot\\tilde{e}\\}\n\\]\nIt is concave on the condition that $q+e<\\tilde{q}+\\tilde{e}$ and\n$e>\\tilde{e}$. Effectively, this cost function applies $\\gamma_1(k;q,e)$ to\ngaps shorter than $\\lceil(\\tilde{q}-q)/(e-\\tilde{e})\\rceil$ and applies\n$\\gamma_1(k;\\tilde{q},\\tilde{e})$ to longer gaps. We can compute the maximal\nalignment score under $\\gamma_2(k)$ with\n\\begin{equation}\\label{eq:affine2}\n\\left\\{\\begin{array}{l}\nH_{ij} = \\max\\{H_{i-1,j-1}+s(i,j),E_{ij},F_{ij},\\tilde{E}_{ij},\\tilde{F}_{ij}\\}\\\\\nE_{i+1,j}= \\max\\{H_{ij}-q,E_{ij}\\}-e\\\\\nF_{i,j+1}= \\max\\{H_{ij}-q,F_{ij}\\}-e\\\\\n\\tilde{E}_{i+1,j}= \\max\\{H_{ij}-\\tilde{q},\\tilde{E}_{ij}\\}-\\tilde{e}\\\\\n\\tilde{F}_{i,j+1}= \\max\\{H_{ij}-\\tilde{q},\\tilde{F}_{ij}\\}-\\tilde{e}\n\\end{array}\\right.\n\\end{equation}\nEq.~(\\ref{eq:suzuki}) can be extended to work with piece-wise affine cost in a\nsimilar manner.\n\n\\end{methods}\n\n\\bibliography{aln-dp}\n\\end{document}\n", "meta": {"hexsha": "4b2aea20996a6896dd6b5c4095b113785d541e28", "size": 16936, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "implementations/guidi2020/benchmark/tools/ksw2/tex/aln-dp.tex", "max_stars_repo_name": "r-barnes/sw_comparison", "max_stars_repo_head_hexsha": "1ac2c9cc10a32badd6b8fb1e96516c97f7800176", "max_stars_repo_licenses": ["BSD-Source-Code"], "max_stars_count": 108, "max_stars_repo_stars_event_min_datetime": "2017-06-22T16:49:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T22:55:14.000Z", "max_issues_repo_path": "implementations/guidi2020/benchmark/tools/ksw2/tex/aln-dp.tex", "max_issues_repo_name": "r-barnes/sw_comparison", "max_issues_repo_head_hexsha": "1ac2c9cc10a32badd6b8fb1e96516c97f7800176", "max_issues_repo_licenses": ["BSD-Source-Code"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2017-07-06T14:59:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T03:22:55.000Z", "max_forks_repo_path": "implementations/guidi2020/benchmark/tools/ksw2/tex/aln-dp.tex", "max_forks_repo_name": "r-barnes/sw_comparison", "max_forks_repo_head_hexsha": "1ac2c9cc10a32badd6b8fb1e96516c97f7800176", "max_forks_repo_licenses": ["BSD-Source-Code"], "max_forks_count": 22, "max_forks_repo_forks_event_min_datetime": "2017-06-23T05:33:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T16:46:12.000Z", "avg_line_length": 46.1471389646, "max_line_length": 83, "alphanum_fraction": 0.7243150685, "num_tokens": 5574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.32387813868788323}}
{"text": "\\section{Backend} \\label{back}\nIn this section we illustrate the design and implementation of the backend of compiler of $\\lambda_Q$.\nThe backend consists of four parts: lexer, parser, qubit allocation and optimization.\n\\subsection{Lexer \\& Parser}\nWe use Lex/Yacc to implement the lexer and parser of a modified version of OpenQasm2.0 in backend.\n\nSubcircuit definition is not available in our OpenQasm2.0. Besides $\\{U3,CX\\}$ that are available in the original OpenQasm2.0, we add $\\{H,X,Y,Z\\}$ to the built-in gate set.\n\nThis part consists of 600 lines of C code formatted in Lex/Yacc file's syntax.\nReaders can refer to \\textit{lex.l} and \\textit{parser.y} to get more detailed information.\n\n\\subsection{Qubit Allocation}\nIn recent years, some companies like IBM have made quantum computers available to wide community.\nUsers can build their experiments based on a circuit representation on the cloud platform. However, today's quantum computer prototypes have tight resources constraints.\nFor instance, you can only apply two qubits operations to a subset of qubit pairs which is specificed by a partial network.\n\nIn \\textit{qubit\\_allocation.cpp}, we implement a heuristic algorithm  to allocate physical qubits to logic qubits.\n\n\\subsubsection{Problem Definition}\nThe most basic form of Qubit Allocation Problem is: given a quantum circuit and an architecture, we want to know if it is possible to map logic qubits in the former to physical qubits in the latter.\nNotice that even this basic problem is NP-hard.\n\nIn some cases, the constraints of the architecture is impossible to satisfy, and we need some circuit transformation to relax these constraints.\n\nThere are three kinds of transformations we can apply:\n\\begin{itemize}\n    \\item[Reversal] Apply $CX$ to $(p,q)$ when $(q,p)$ is available in the architecture.\n    \\item[Bridge] Apply $CX$ to $(p,q)$ when $(p,s)$ and $(s, q)$ is available.\n    \\item[Swap] Swap the state of $p$ and $q$ when $(p,q)$ or $(q,p)$ is available.\n\\end{itemize}\n\nAll these transformation need extra gates to implement, so we need to find a qubit mapping and circuit transformations to satisfy the constraints with minimum number of extra gates involved.\n\n\\subsubsection{Algorithm}\n\nOur algorithm~\\cite{qa} has two stages:\n\n\\textbf{First stage}: Find an intial mapping\n\nWe first sort the logic qubits in descending order of their occurrence counts.\n\nThen, for each logic qubit $q$ in order, we allocate $q$ to a physical qubit with the nearest out-degree(both the quantum circuit and the architecture can be regarded as a directed graph whose vertex is qubit)\n\nAfter $q$ is allocated to $p$, for each edge $(q,q')$, we try to allocate $q'$ to some $p'$ with edge $(p,p')$ and has the nearest out-degree.\n\nRepeat the above process for $q'$ if it is successfully allocated.\n\nAfter this BFS-like allocation we allocate the rest unallocated logic qubit to a free physical qubit.\n\n\\textbf{Second stage}: Adjust the mapping and apply circuit transformation\n\nThe mapping $l$ in the output of the first stage may not satisfy all constraints, so we need to adjust it and apply circuit transformations to the quantum circuit.\n\nFor any two qubits operation on $(p,q)$, if $(l(p),l(q))$ can't be implemented in current mapping, then:\n\\begin{itemize}\n    \\item[1.] if $(p,q)$ appears more than once in the circuit, we use a Swap transformation to move $q$ closer to $p$ (Here we can use BFS to find the shortest path to $p$) and then re-evaluate these four cases.\n    \\item[2.] else if $(l(q), l(p))$ can be implemented, then we use a Reversal transformation to $l(q)$ and $l(p)$.\n    \\item[3.] else if $\\exists s$ s.t. $(l(p),s)$ and $(s, l(q))$ are both available, we can use a Bridge transformation to $l(p), s, l(q)$.\n    \\item[4.] else use Swap transformation like case 1.\n\\end{itemize}\n\\subsection{Optimization}\n\nOptimization \\cite{Nam_2018} for arbitary unitary gates is sophisticated, so we only consider cases when gates are chosen from a discrete set.\n\nIn this section, we implement two basic optimization method for gate set $\\{H, RZ, CX, X\\}$\n\nOur work in this section can be divided into four parts: graph conversion, gate decomposition, Hardmard reduction and gate cancellation.\n\nReaders can refer to \\textit{generator.cpp, optimization.cpp, graph.h} for detailed information.\n\\subsubsection{Graph Conversion}\n\nAt first, we only store quantum circuit in the AST constructed by yacc and write \\textit{generator.cpp} for code generation from AST (It retains this function in the final version)\n\nHowever, tree structure is not suitable for gate optimization, since we often access the adjacent gate of a given gate, and they can be distant in AST.\n\nTherefore, in \\textit{generator.cpp}, we construct a graph from AST whose edge connects gates that are adjacent in the circuit.\n\nIn \\textit{graph.h}, we implement function $Graph::toposort$ to generate code from a given graph.\n\n\\subsubsection{Gate Decomposition}\nSince available gate set in our modified OpenQasm2.0 is different from the gate set on which we implement gate optimization, we should first decompose the given circuit in the new basis gate set.\n\nNotice that $HXH = Z, ZX = iY, U(\\theta, \\phi, \\lambda) = R_z(\\phi)R_x(-\\frac{\\pi}{2})R_z(\\theta)R_x(\\frac{\\pi}{2})R_z(\\lambda)\\\\$ and $HR_x(\\theta)H = R_z(\\theta)$, it is easy to implement this decomposition.\n\n    \\subsubsection{Hardmard Reduction}\n    In this section, we implement Hardmard Reduction to reduce the number of Hardmard gate.\n\n    It is a simple pattern (\\ref{pattern}) matching algorithm. We can traverse the graph, find serveral subcircuit pattern and replace it with a simplfied equivalent subcircuit.\n\n\n    \\begin{center}\n        \\begin{figure}\n            \\label{pattern}\n            \\centering\n            \\includegraphics[width=0.9\\linewidth]{images/hardmard_reduction.png}\n            \\caption{Subcircuit patterns in Hardmard Reduction}\n        \\end{figure}\n    \\end{center}\n\n    \\subsubsection{Gate Cancellation}\n    When a pair of conjugate transpose gates are adjacent, they can both be cancelled.\n\n    In this section, we implement gate cancellation for $RZ$ gate, we traverse all $RZ$ gates and try to move it by swapping with adjacent commutative subcircuit if posible (we only consider serveral  built-in commutation rules (\\ref{commutation}) since it is hard to determine whether two gates are commutative) until encountering its conjugate transpose or reaching endpoints of the circuit.\n\n\\begin{center}\n    \\begin{figure}\n        \\label{commutation}\n        \\centering\n        \\includegraphics[width=0.9\\linewidth]{images/gate_cancellation.png}\n        \\caption{Commutation rules for RZ gate}\n    \\end{figure}\n\\end{center}\n\n", "meta": {"hexsha": "8453d17dd3e1e3d063bc8407082cd8a91fe49af5", "size": 6704, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/backend.tex", "max_stars_repo_name": "thwfhk/lambdaQ", "max_stars_repo_head_hexsha": "834c0a42e234f486ac0f7b55f76e096d70cf7262", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-04-10T08:42:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-09T07:09:53.000Z", "max_issues_repo_path": "report/backend.tex", "max_issues_repo_name": "thwfhk/lambdaQ", "max_issues_repo_head_hexsha": "834c0a42e234f486ac0f7b55f76e096d70cf7262", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/backend.tex", "max_forks_repo_name": "thwfhk/lambdaQ", "max_forks_repo_head_hexsha": "834c0a42e234f486ac0f7b55f76e096d70cf7262", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-09T06:13:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-09T06:13:15.000Z", "avg_line_length": 58.8070175439, "max_line_length": 393, "alphanum_fraction": 0.7508949881, "num_tokens": 1634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.32378166376251405}}
{"text": "% --- [ Conservativeness ] -----------------------------------------------------\n\n\\subsection{Conservativeness}\n\nReports whether the source type exists within the type range (lower and upper bound) of the recovered type.\n\nThe distance measurement as defined by TIE did not distinguish between multi-level pointers (e.g. \\texttt{int*} and \\texttt{int**} are equivalent, i.e. on the same level in the type lattice). Thus SecondWrite proposed a refinement to measure the ratio between the recovered pointer level and the source pointer level \\cite{second_write_scalable_type_detection}.\n", "meta": {"hexsha": "42f17b0fe95bf6e0b131d03d2f3ce17b06293588", "size": 584, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/type_analysis/sections/5_evaluation_metrics/2_conservativeness.tex", "max_stars_repo_name": "decomp/doc", "max_stars_repo_head_hexsha": "fb82b6a5074aa8721afb24a5537bf1964ed20467", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2016-05-27T10:16:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T08:14:04.000Z", "max_issues_repo_path": "report/type_analysis/sections/5_evaluation_metrics/2_conservativeness.tex", "max_issues_repo_name": "decomp/doc", "max_issues_repo_head_hexsha": "fb82b6a5074aa8721afb24a5537bf1964ed20467", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 48, "max_issues_repo_issues_event_min_datetime": "2019-01-30T19:08:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-29T19:17:53.000Z", "max_forks_repo_path": "report/type_analysis/sections/5_evaluation_metrics/2_conservativeness.tex", "max_forks_repo_name": "decomp/doc", "max_forks_repo_head_hexsha": "fb82b6a5074aa8721afb24a5537bf1964ed20467", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-05-25T21:15:26.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-09T07:36:14.000Z", "avg_line_length": 73.0, "max_line_length": 361, "alphanum_fraction": 0.720890411, "num_tokens": 117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3237816559741216}}
{"text": "%!TEX root = Lefley - Mesh to voxel transformations for optimised physics-based interactions.tex\n\\chapter{Implementation}\n\nThis chapter will discuss the stages of development. The starting point, implementation and result of each pipeline stage will be detailed as well as any difficulties faced.\n\n\\section{Process}\n\nThe process for development was iterative, implementing each pipeline stage in order. This was because each stage required the output of the previous stage to function and, while mock results could have been generated and forwarded, often the easiest way to input interesting data was to generate it from the previous stage because of the size of the data structures being used.\n\nStages were kept as encapsulated as possible so that any changes that had to be made would not cascade through later stages or require changes to those previous.\n\nTesting and debugging were done on each stage as it was completed to test the performance of that particular implementation and gauge whether changes or a new algorithm were needed. This also improved the ease of finding bugs in comparison with debugging at the end of the pipeline.\n\n\\section{Preprocessing}\n\n\\label{sect:pre}\n\nThe simplest way to satisfy the requirement of applying the correct resultant movement vector to each fragment is to perform the fragmentation before the collision takes place. This allows the Unity3D physics engine to properly apply force to each fragment when the incoming particle makes contact.\n\nIt is therefore necessary to predict and extrapolate possible collisions before they occur. This was achieved by adding a bounding sphere to destructible objects and using Algorithm~\\ref{alg:extrap}.\n\n\\begin{algorithm}[H]\n \\KwData{Object to be destroyed: d, Bounding sphere: s, Incoming object: p}\n \\KwResult{Force magnitude exerted on each object: f, Collision point on d: c}\n Ray r = cast ray from p along p.velocity\\;\n \\If{r intersects d}{\n \tPoint c = intersection point\\;\n \tVector n = c.normal\\;\n \tn = n*2\\;\n\n \tDouble md = d.mass\\;\n \tDouble mp = p.mass\\;\n\n \tVector vd = d.velocity\\;\n \tVector vp = p.velocity\\;\n\n \tDouble t = Physics.timestep\\;\n\n \tf = Dot(n, (mpvd - mdvp))\\;\n \tf = f / (md+mp)\\;\n }\n \\caption{Collision extrapolation}\n \\label{alg:extrap}\n\\end{algorithm}\n\nThis algorithm relies on the following equations which approximately calculate the magnitude of the force which will be exerted on each object\\footnote{Dylan Kennedy, personal communication, January 14, 2015}:\n\n\\begin{equation}\nF = {\\beta \\over t} \\quad \\text{$t$ = time objects are in contact for}\n\\end{equation}\n\n\\begin{equation}\n\\beta = {2\\mathbf{\\hat{N_1}}\\cdot (m_{2}\\mathbf{v_1}-m_{1}\\mathbf{v_2}) \\over m_{1}+m_{2}}\n\\end{equation}\n\nAs the colliding objects are rigid we take the time that they will be in contact for to be one time-step of the Unity3D physics engine.\n\n\\subsection{Assumptions}\n\nAs we are extrapolating the collision data at the point when they enter the bounding sphere, some assumptions are made.\n\n\\begin{itemize}\n\\item{The velocity of the two objects involved will not change between this point and any collision}\n\\item{A third object will not move to obstruct any collision after this point}\n\\item{The rotation of either object will not change the result of any collision}\n\\end{itemize}\n\nBy tightening the bounding sphere around our destructible object we can take these assumptions to hold for simplicity.\n\n\\section{Voxelisation}\n\nOriginally it was planned for only a portion of the destructible object to be voxelised, depending on the physical forces involved. However it was found that the computational complexity of determining which mesh triangles fell within this portion was equal to that of voxelising these triangles. Therefore, for simplicity, the whole mesh is voxelised.\n\nThe solution for voxelisation used is based on an implementation of the Schwartz method found in GPU Pro 3\\cite{Schwarz:2010:Vox}\\cite{Engel:2012:GPA:2331213}.\n\nThis method is made up of two phases, a triangle phase and a propagation phase. Both of these are separate shaders run on the GPU to allow for parallel processing within the phases.\n\n\\subsection{Data structures}\n\nThe data structures used in this stage of the pipeline are primarily buffers as these can be passed to and from the GPU shaders as input and output.\n\nThe inputs to the first shader are the triangles defining the object's mesh. These are stored in two buffers. A `vertex' buffer stores a list of floating point numbers, each one being an x, y or z coordinate in a triangle's vertex, relative to the position of the object\\footnote{Therefore the world position is not factored into the vertices.}. These values are always grouped such that for each vertex the x, y and z coordinates are adjacent and in sequence. There is no further ordering imposed. A second `index' buffer stores an integer list of indices into the vertex buffer. This buffer is ordered such that, when divided into strides of three, each index within that triplet refers to the point of a triangle when used with the vertex buffer. This is shown in Figure~\\ref{fig:3.1}.\n\n\\begin{figure}\n\\centerline{\\includegraphics[scale=0.5]{buffers13.pdf}}\n\\caption{The triangle (c) is represented by three consecutive indices, one for each vertex, in (b) which each point to the beginning of three consecutive floats which define that vertex in (a).}\n\\label{fig:3.1}\n\\end{figure}\n\nThe output from both shaders and input to the second is a three dimensional array of bits defining which voxels exist. This is stored as a single integer buffer, with each integer encoding 32 voxels. The three dimensional array is flattened, first along the $Z$ direction, then $X$, then $Y$. The $Z$ direction is padded such that all of the voxels in a integer will have the same $X$ and $Y$ coordinates. On being outputted from the second shader this flattened array is wrapped in a helper class which allows easy lookup into the array as if it were three dimensional as well as helper functions such as getting the array's size in any of the three dimensions represented.\n\n%Figure?\n\n\\subsection{Triangle Phase}\n\nDuring this phase, each triangle in the object to be voxelised is processed in its own GPU thread. First the triangle is translated and scaled by a pair of matrices defined by the object's bounding box and the requested voxel resolution\\footnote{The $X$, $Y$ and $Z$ dimensions of the voxel grid.}. This transforms object relative world coordinates into `voxel coordinates'. \n\nThe object relative coordinates are defined by taking a tight bounding box around the object, the centre of the box is $(0,0,0)$ and the box extends to $0.5$ in each dimension. Voxel coordinates define $(0,0,0)$ to be a corner of the bounding box and each axis extends to a defined magnitude depending on the voxel resolution desired. This is shown in Figure~\\ref{fig:3.2}.\n\n\\begin{figure}\n\\centerline{\\includegraphics[scale=0.5]{coordinates13.pdf}}\n\\caption{The box (a) represents a voxel space of resolution $7\\times9\\times7$. (b) shows the same box in object relative coordinates.}\n\\label{fig:3.2}\n\\end{figure}\n\nTriangles are then projected onto the $XZ$ plane and all of the intersecting voxel columns are found\\footnote{Voxel columns extending along the $Y$ axis.}. This is shown in Figure~\\ref{fig:3.2.1}. For all of these columns the first voxel below the triangle, in the $Y$ direction, is set.\n\n\\begin{figure}\n\\centerline{\\includegraphics[scale=0.5]{projection13.pdf}}\n\\caption{The red triangle has been projected onto the $XZ$ plane and the intersecting voxel columns marked in green.}\n\\label{fig:3.2.1}\n\\end{figure}\n\n\\subsection{Propagation Phase}\n\nIn the propagation phase we move up the $Y$ axis, XORing each voxel with the one below in the $Y$ direction. This allows us to fill in the solid volume. As we move up, when the first set voxel is met all those above will then become set until we reach another that had been set by the triangle phase. Each $Y$ column is processed in parallel, with 32 columns being processed in parallel on the same thread as we are XORing integers which are encoding 32 voxels.\n\n\\subsection{Progress}\n\n\\label{sect:voxprog}\n\nBoth shaders were taken from the GPU Pro 3 library mostly unaltered\\footnote{There were methods in the first shader for other, unneeded, forms of voxelisation which were removed.}. The {\\sc{C++}} driver found in the library was used to gain insight on interfacing with the shaders when writing the {\\sc{C\\#}} driver used. The completed driver and wrapper for the voxel grid output were heavily inspired by a {\\sc{Javascript}} CPU implementation of voxelisation in Unity3D\\cite{CPUVoxel}.\n\nAchieving binary solid voxelisation on the GPU was the first major milestone completed. Several other libraries and methods were tried and tested before a suitable one was found. It also took much more time than anticipated to complete integration of the library which was used.\n\nA scene was constructed where several objects differing in triangle resolution and shape were used for debugging the implementation. Figure~\\ref{fig:3.3} demonstrates the output with the voxel structure being displayed for debugging.\n\n\\begin{figure}[b!]\n\\centerline{\\includegraphics[scale=0.6]{Stanford_Bunny_Voxelised.png}}\n\\caption{Voxelisation of the `Stanford Bunny' model, composed of 69,666 triangles. The voxelisation shown is lower resolution than that which is typically used in the final implementation resulting in 1,723 voxels shown in red.}\n\\label{fig:3.3}\n\\end{figure}\n\n\\section{Physical Destruction}\n\n\\label{sect:destr}\n\nThe process of physically destroying an object involves partitioning its volume into fragments. This is done by assigning each voxel to a fragment, which will be referred to as `colouring'.\n\nThe method used is based on Voronoi diagrams as these are commonly used for achieving visually realistic fracturing effects\\cite{Muller:2013:RTD:2461912.2461934}. This choice was made because of time restrictions and the encapsulated pipeline nature of Dynamic Volumetric Fragmentation would allow a more physically accurate algorithm to easily take its place.\n\n\\subsection{Data structures}\n\nThis pipeline stage takes the voxel grid from the voxelisation stage as an input and outputs a list of `fragment' classes and an altered voxel grid.\n\nThe fragment class stores:\n\n\\begin{itemize}\n\\item{An integer `colour' for that fragment, which acts as an identifier.}\n\\item{A list of points that make up the volume for that fragment.}\n\\item{A minimum and maximum $X$, $Y$ and $Z$ coordinate which define the bounding box for that fragment in voxel space.}\n\\end{itemize}\n\nThe altered voxel grid is a three dimensional array of integer values with each one corresponding to the colouring of the voxel in that position.\n\nDuplicate information is returned here as different algorithms further down in the pipeline, primarily the meshing phase, require different input data structures. Some work on the point cloud provided by the fragment objects while others work optimally on the grid where neighbours can be found in constant time.\n\n\\subsection{Finding Generating Points}\n\nTo fragment the object using a Voronoi diagram, a series of generating points have to be found.\n\nFirstly, the collision point from the preprocessing stage of the pipeline is transformed into voxel space. A number of vectors are then generated from this point with their magnitudes normally distributed within a given radius. The number of points and radius are calculated from both user defined physical properties of the object such as `brittleness' and `strength' as well as the collision force. This ensures that the fragmentation is different depending on the physical characteristics of the collision and therefore more accurate.\n\nThe vectors have normally distributed magnitudes so that there are more generating points closer to the collision point. This results in many smaller fragments about the point of impact as you would expect. \n\n\\subsection{Partitioning}\n\nGiven the generating points $P_i$, a Voronoi diagram is a partitioning of space such that a cell contains all points in space which are closer to $P_i$ than any $P_j$. This is formally defined by equation~\\ref{eq:3.1} and shown in Figure~\\ref{fig:3.4}.\n\n\\begin{equation}\n\\text{Given a set } S=\\{p_1, p_2\\dotsc p_n\\} \\quad \\text{A Cell } C(S,p_i)=\\{p\\in R^d\\mid |p-p_i|<|p-p_j|, i\\neq j\\}\n\\label{eq:3.1}\n\\end{equation}\n\n\\begin{figure}\n\\centerline{\\includegraphics[scale=0.25]{VoronoiEx.png}}\n\\caption{A Voronoi diagram\\cite{voronoipict}.}\n\\label{fig:3.4}\n\\end{figure}\n\nA fragment object is made for each generating point and all voxels are looped over. For each voxel, all generating points are checked and the closest found. That voxel is then added to the corresponding fragment object, also updating the minimum and maximum coordinates for that fragment, and the voxel is given the correct integer colouring in the new grid.\n\n\\subsection{Finding Islands}\n\n\\label{sect:islands}\n\nA Voronoi partitioning is always guaranteed to produce convex solids when applied to a convex solid. However, as Dynamic Volumetric Fragmentation works on concave models this cannot be relied on. If a partitioning spans a concavity then it may produce unconnected islands as shown in Figure~\\ref{fig:3.5}. Meshing such a partition into a rigid solid would result in floating areas as the physics engine cannot reason within a mesh as seen in Figure~\\ref{fig:3.5.1}.\n\n\\begin{figure}\n\\centerline{\\includegraphics[scale=0.5]{island13.pdf}}\n\\caption{The blue Voronoi cell creates two unconnected partitions of the concave object.}\n\\label{fig:3.5}\n\\end{figure}\n\n\\begin{figure}\n\\centerline{\\includegraphics[scale=0.5]{islands.png}}\n\\caption{If the unconnected ears and body are a single mesh then the physics engine cannot act on the ears causing them to fall.}\n\\label{fig:3.5.1}\n\\end{figure}\n\nTo find and remove any islands a flood fill algorithm is used. Algorithms \\ref{alg:flinit} and \\ref{alg:flood} demonstrate how this works.\n\n\\begin{algorithm}[]\n \\KwData{Dictionary of fragments indexed by colour: d, Greatest fragment colour: c, Coloured grid with islands: g}\n \\KwResult{Dictionary of new fragments with no islands: o, Coloured grid with no islands: g}\n Dictionary$<$integer, fragment$>$ o\\;\n \\For{Each fragment f in d}{\n \t\\For{Each voxel v in f}{\n \t\t\\If{g[v.x,v.y,v.z] == f.colour}{\n \t\t\tFragment r\\;\n \t\t\tr.colour = ++c\\;\n \t\t\to.Store(r.colour, r)\\;\n \t\t\tFlood(v.x, v.y, v.z, f.colour, r.colour, r, o)\\;\n \t\t}\n \t}\n }\n \\caption{Flood initiation}\n \\label{alg:flinit}\n\\end{algorithm}\n\n\\begin{algorithm}[]\n \\KwData{Vector to flood from: v, Old colouring: f, New colouring: r, Dictionary of fragments indexed by colour: o, Coloured grid with islands: g}\n \\KwResult{Dictionary of new fragments with no islands: o, Coloured grid with no islands: g}\n Queue$<$Vector$>$ neighbours\\;\n HashSet$<$Vector$>$ visited\\;\n neighbours.Enqueue(v)\\;\n visited.Add(v)\\;\n \\While{neighbours is nonempty}{\n \tVector deq = neighbours.Dequeue()\\;\n\n    int x = deq.x\\;\n    int y = deq.y\\;\n    int z = deq.z\\;\n\n    g[x, y, z] = r\\;\n\n    colouring.Add(v)\\;\n\n    \\For{i from -1 to 1} {\n        \\For{j from -1 to 1} {\n            \\For{k from -1 to 1} {\n                int xi = x + i\\;\n                int yj = y + j\\;\n                int zk = z + k\\;\n\n                \\If{i == 0 AND j == 0 AND k == 0}{continue\\;}\n                \\If{xi out of bounds in g OR yj out of bounds in g OR zk out of bounds in g}{continue\\;}\n\n                \\If {g[xi, yj, zk] == f}{\n                    \\If{!(visited.Contains(xi, yj, zk))}{\n                        neighbours.Enqueue(xi, yj, zk)\\;\n                        visited.Add(xi, yj, zk)\\;\n                    }\n                }\n            }\n        }\n    }\n }\n \\caption{Flooding}\n \\label{alg:flood}\n\\end{algorithm}\n\nFor every voxel in every fragment, if that voxel is still coloured with the same value as that fragment then it has not been reached by a previous flood for that fragment. Therefore it is not connected to the already flooded portion of that fragment and should instead be part of a new fragment. As should all connected voxels found by flooding from the voxel.\n\n\\subsection{Progress}\n\nAll of the code for this stage of the pipeline was written from scratch. Most time was spent optimising for both time and space complexity once the algorithms used had been implemented.\n\nDebugging was done by partitioning the voxel structure of a cube and colouring the voxels according to their fragments. The generating points were also visualised. This is shown in Figure~\\ref{fig:3.6}.\n\n\\begin{figure}[b!]\n\\centerline{\\includegraphics[scale=1]{Voronoi.png}}\n\\caption{A visualisation of the Voronoi partitioning of the voxel structure of a cube.}\n\\label{fig:3.6}\n\\end{figure}\n\n\\subsection{Advantages}\n\nAs discussed, while the partitioning here is done using a Voronoi method which is common when working with surface representations, having a volumetric representation of an object could allow more complex and physically accurate algorithms. For example, the grid of voxels could be taken to represent the crystalline structure of some solids with the `bonds' between neighbouring voxels acting as they would in a real collision.\n\nAlso, the method works on both convex and concave models equally which is uncommon in other approaches as discussed in Section~\\ref{sect:prob}.\n\n\\section{Intermediate Processing}\n\nBefore the partitioned voxels can become rigid meshes, preprocessing is needed. This is in order to prepare the data for the different algorithms used.\n\n\\subsection{Separating Border Voxels}\n\nFor the chosen meshing processes, the voxel grid is trimmed so that only interior border voxels remain, as shown in Figure~\\ref{fig:3.7}. The reason for this is that both meshing processes require only the surface of the fragments defined by the voxels and not the solid volume. Separation is done by checking for every voxel whether it has a neighbouring voxel with a different colouring and keeping only those that do.\n\n\\begin{figure}[b!]\n\\centerline{\\includegraphics[scale=0.9]{border213.pdf}}\n\\caption{A fragmented voxelised rectangle. The interior border voxels are green and the exterior voxels are blue. The unneeded interior voxels are red.}\n\\label{fig:3.7}\n\\end{figure}\n\nVoxels on the surface of the object, with a non-existent neighbour, are recorded for entry into a k-d~tree.\n\nA k-d tree is a binary tree based data structure which features an average $\\mathcal{O}(n\\log{}n)$ lookup for the nearest vector in the tree to a given vector in space.\n\nAn implementation of k-d trees in {\\sc{C\\#}} for Unity3D was found and used as there was little point reimplementing a well used data structure\\cite{kdtree}.\n\nVoxels both on the surface and on the interior borders with other fragments are also stored in the fragment they belong to.\n\n\\section{Mesh Generation}\n\nOnce the solid volume for each fragment has been found, it needs to be transformed into a rigid mesh for use in the physics engine. These meshes are constructed via two processes. The first splits the original object mesh and the second forms new meshes around the solid voxel structures.\n\n\\subsection{Data Structures}\n\nThe mesh partitioning procedure takes as an input the k-d tree of surface voxels from the intermediate processing stage as well as the original object mesh. The output is a list of fragment submeshes and for each one, a k-d tree of the vertices which make up the border of that submesh. These meshes will be referred to as the external meshes. This is shown in Figure~\\ref{fig:3.8}.\n\n\\begin{figure}[b!]\n\\centerline{\\includegraphics[scale=0.35]{mesh_border.png}}\n\\caption{A partitioning of the Stanford Bunny mesh. The vertices which make up the border of the green submesh are highlighted in red. The gap between partitions is caused by the loss of triangles which have vertices in different partitions.}\n\\label{fig:3.8}\n\\end{figure}\n\nThe marching tetrahedra algorithm runs for each fragment and takes as an input the grid of coloured border voxels from the intermediate processing stage as well as the k-d tree of the vertices which make up the fragment's external mesh border as outputted by the mesh partitioning procedure above. The algorithm outputs a mesh which represent the surface defined by the voxels (referred to as the solid mesh), and surface mesh, for that fragment.\n\n\\subsection{Mesh Partitioning}\n\n\\label{sect:part}\n\nIn order to preserve the original surface of the object the correct sections of the original mesh need to be mapped onto the computed fragments.\n\nTo do this the original object mesh is partitioned according to the colouring of the nearest voxel for every vertex.\n\nThis is the purpose of having all of the surface voxels in a k-d tree. There is no need to have the internal voxels as there will always be a surface voxel which is closer.\n\nThe process loops over all triangles and each vertex in that triangle. If all of the vertices have a nearest voxel of the same colouring then that triangle is added to the mesh for the fragment of that colouring. If the nearest voxel colours differ then the triangle is discarded and the vertices are added to the boundary k-d tree for their fragments.\n\nThe result of this process is demonstrated in Figure ~\\ref{fig:3.8}. \n\n\\subsection{Marching Tetrahedra}\n\n\\subsubsection{Marching Cubes}\n\nMarching cubes is an algorithm used to extract a polygonal mesh of an implicit surface from a three-dimensional discrete scalar field\\cite{Lorensen:1987:MCH:37401.37422}. The binary field of voxels\\footnote{The colouring of the voxels is for identifying which fragment they belong to, they are still treated as binary present or not present for meshing purposes.} representing the solid volume of an object in this case is such an example.\n\nThe algorithm proceeds through the scalar field, taking a `cube' of eight adjacent locations at a time. The polygon(s) needed to represent the part of the implicit surface that passes through this cube are determined by creating an index into a pre-calculated array of 256 configurations from the eight scalar values.\n\nOrdinarily each vertex of the generated polygons would be placed on the appropriate position along the cube's edge by linearly interpolating the two scalar values that are connected by that edge. However, in this case the scalar values only have two possibilities and so interpolating between them always results in a placement of the vertices half way between the voxels. This leads to a meshed surface which reveals the blocky voxel structure as opposed to a smoother surface which would be extracted if dealing with a field of actual scalars. This is shown in Figures \\ref{fig:3.9} and \\ref{fig:3.10}.\n\n\\begin{figure}[b!]\n\\centerline{\\includegraphics[scale=8]{marchingtetrahedrons.jpg}}\n\\caption{Marching tetrahedra applied to a scalar field generated from perlin noise\\cite{ScrawkMarching}.}\n\\label{fig:3.9}\n\\end{figure}\n\\begin{figure}\n\\centerline{\\includegraphics[scale=0.75]{Marching.png}}\n\\caption{Marching tetrahedra applied to the voxel grid of a fragmented Stanford Bunny.}\n\\label{fig:3.10}\n\\end{figure}\n\nAmbiguous cases are present in the polygonisation where there exist at least two correct interpretations of the implicit surface. This is shown in two dimensions\\footnote{These ambiguities would therefore be for the marching squares algorithm but the premise is the same.} in Figure~\\ref{fig:3.11}.\n\n\\begin{figure}\n\\centerline{\\includegraphics[scale=0.5]{ambiguous.png}}\n\\caption{The two possible surfaces for the imaginary square shown with dashed lines with two points inside the surface and two outside.}\n\\label{fig:3.11}\n\\end{figure}\n\n\\clearpage\n\\subsubsection{Marching Tetrahedra}\n\nMarching tetrahedra is an algorithm based on marching cubes which solves these ambiguities as well as producing a surface which matches the voxel data more closely at the cost of generating more vertices\\cite{Tetrahedra}.\n\nIn marching tetrahedra, each cube is split into six irregular tetrahedra by cutting the cube in half diagonally three times as shown in Figure~\\ref{fig:3.12}. These tetrahedra are then used to find the implicit surface in much the same way as marching cubes however there are now nineteen edge intersections per cube instead of twelve.\n\n\\begin{figure}[b!]\n\\centerline{\\includegraphics[scale=0.8]{Marching_tetrahedrons.png}}\n\\caption{A cube split into six irregular tetrahedra\\cite{marchingpict}.}\n\\label{fig:3.12}\n\\end{figure}\n\n\\clearpage\n\\subsubsection{Modification}\n\nAs two separate meshes are being produced in this stage, a section of the original mesh and a surface representing the solid volume, the two need to be combined and joined.\n\nThe marching tetrahedra library used was modified to take the grid of coloured border voxels as well as the set of voxels lying both on the exterior and on the fragment border. The k-d tree of the vertices which make up the fragment's external mesh border is also used. These border voxels are meshed using marching tetrahedra. However, when a voxel also lying on the exterior is found, the calculated vertices are discarded and instead their nearest neighbours in the k-d tree are used. This process knits the gap that would have otherwise existed between the two generated meshes, the external mesh and the solid mesh. A small amount of random noise is also applied to the rest of the vertices in an effort to disguise some of the blocky underlying structure. The results of this can be seen in Figure~\\ref{fig:3.13}.\n\n\\begin{figure}\n\\centerline{\\includegraphics[scale=0.75]{collision.png}}\n\\caption{The Stanford Bunny after the entire pipeline has completed.}\n\\label{fig:3.13}\n\\end{figure}\n\n\\subsection{Progress}\n\nThis stage of the pipeline took the longest to complete and was the final milestone when done. The stage went through several iterations of varying success before the above method was devised.\n\nOriginally the fragment meshes were to be only generated using marching tetrahedra with no splitting or use of the original external mesh. This resulted in an important detail loss as seen in Figure~\\ref{fig:3.10} and was not viable for use. Increasing the voxel resolution improved this but added too much of a computational overhead.\n\nA second method involved only splitting the original external mesh and not using marching tetrahedra at all. The resultant fragment meshes were duplicated and had their normals flipped before being combined. This gave results that resembled hollow porcelain objects as seen in Figure~\\ref{fig:3.14}. This could not be used as it did not satisfy the requirement of modelling the internal structure.\n\n\\begin{figure}\n\\centerline{\\includegraphics[scale=1]{Porcelain2.png}}\n\\caption{The Stanford Bunny fractured as if it were a hollow object.}\n\\label{fig:3.14}\n\\end{figure}\n\nProducing the final method, involved modifying the marching cubes library found to stitch the external and solid meshes together as discussed. The algorithm found in the library was also optimised. Originally the algorithm would produce duplicate vertices for triangles which should share a vertex. This was solved by using a dictionary of vertices and indices into the vertex list. All vertices required by a triangle are checked in the dictionary, if they exist as a key then the index stored is used else the vertex is added to the vertex list and a new index stored in the dictionary with that vertex and used in the triangle. This dramatically reduced vertex counts in the meshes produced which is necessary as Unity3D imposes a limit of 65,534 vertices for any mesh.\n\n\\section{Post-processing}\n\nAfter the fragment meshes have been generated, some post processing must take place in order for the meshes to be used in the physics simulation.\n\n\\subsection{Physics}\n\n\\label{sect:postphysics}\n\nOne advantage of fragmenting a voxel structure is that the mass of each fragment, $m_f$, can be calculated using Equation~\\ref{eq:mass}.\n\n\\begin{equation}\n\\begin{split}\nm_f=m_o\\times v_f/v_o \\quad \\text{$v$ is the number of voxels}\n\\label{eq:mass}\n\\end{split}\n\\end{equation}\n\n\\subsection{Game-object Generation}\n\nFinally, the fragment meshes and masses are passed to Unity3D so that they can be instantiated into the simulated world. Depending on the number of vertices in each mesh this can add a large time overhead which will be discussed in Section~\\ref{sect:over}. This overhead is a limitation of Unity3D and not Dynamic Volumetric Fragmentation.\n\n\\section{Result}\n\n\\label{sect:result}\n\nThe result is a library which can be used to fragment objects on collision based on the physical attributes of the object and of the collision.\n\nThe library produced requires that two scripts be attached to the destructible object, one as a driver for the destruction process and the other to allow the physical properties of the object to be defined. A Unity3D object with a `sphere collider' must also be attached with a script which triggers the destruction process as detailed in Section~\\ref{sect:pre}. All of these elements are added to an existing object and none require any existing features of the object to be changed.\n\nWhen an object is given the above attributes and a projectile fired at it, the object is broken into fragments and these fragments then receive force from the projectile causing them to explode out as would be expected. This is shown in Figure~\\ref{fig:3.15}.\n\nA video demonstrating the results can be found at \\url{https://www.screenr.com/NRQN}.\n\n\\begin{figure}\n\\centerline{\\includegraphics[scale=0.7]{voxel_exploded.png}\\includegraphics[scale=0.686]{voxel_exploded2.png}}\n\\caption{Fragments exploding out of the Stanford Bunny after a cubic projectile, shown in red, has been fired at it.}\n\\label{fig:3.15}\n\\end{figure}\n\nThe nature of the fragmentation differs depending on the forces involved as shown in Figure~\\ref{fig:3.16}.\n\n\\begin{figure}\n\\centerline{\\includegraphics[scale=0.85]{voxel_forces.png}}\n\\caption{The biggest fragments after three Stanford Bunnies have been fragmented. Compared to the middle, the right was given a higher strength while the left was hit with a faster projectile.}\n\\label{fig:3.16}\n\\end{figure}\n\n\\section{Conclusion}\n\nIn order for the proposed solution to be realised, four stages of implementation had to take place:\n\n\\begin{enumerate}\n\\item{Preprocessing}\n\\label{point:pre}\n\\item{Voxelisation}\n\\label{point:vox}\n\\item{Meshing}\n\\label{point:mesh}\n\\item{Postprocessing}\n\\label{point:post}\n\\end{enumerate}\n\nIntermediate stages were also completed to process data passed between the above sections.\n\nPoints \\ref{point:vox} and \\ref{point:mesh} required adapting existing implementations of the algorithms used whereas the remaining sections were developed from scratch.", "meta": {"hexsha": "54cc965aea2df489ad56aa19a6ae7955de75a52e", "size": 30694, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Tex/Implementation.tex", "max_stars_repo_name": "TomLefley/Dissertation", "max_stars_repo_head_hexsha": "5aed9f2c32aa2ec94d066638d88af6cd838b7ed0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tex/Implementation.tex", "max_issues_repo_name": "TomLefley/Dissertation", "max_issues_repo_head_hexsha": "5aed9f2c32aa2ec94d066638d88af6cd838b7ed0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tex/Implementation.tex", "max_forks_repo_name": "TomLefley/Dissertation", "max_forks_repo_head_hexsha": "5aed9f2c32aa2ec94d066638d88af6cd838b7ed0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 65.3063829787, "max_line_length": 819, "alphanum_fraction": 0.7794357203, "num_tokens": 7158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3237816559741216}}
{"text": "\\documentclass{article}\n\n\\usepackage{listings}\n\\usepackage{amsmath}\n\\usepackage{graphicx}\n\\usepackage{url}\n\\usepackage{authblk}\n\\usepackage{array} \\setlength{\\extrarowheight}{1.5pt}\n\n\n\\begin{document}\n\n\\lstset{\n%language=C++, % choose the language of the code\nbasicstyle=\\footnotesize, % code font size\nnumbers=left, % where to put the line-numbers\nnumberstyle=\\footnotesize, % line number font size\nstepnumber=1, % the step between two line-numbers.\n%backgroundcolor=\\color{white}, % choose the background color\nframe=single,\nframerule=1pt,\ncaptionpos=b, % t or b\nshowstringspaces=false, % underline spaces within strings\nshowspaces=false, % show spaces within strings with underscores\nshowtabs=false, % show tabs within strings with underscores\nbreaklines=true % Break long lines of code\n}\n\n\\def\\CRC{{\\rm CRC}_u}\n\\def\\SCRC{{\\rm CRC}_0}\n\\def\\BYTE{{\\rm BYTE}}\n\\def\\LCD{{\\rm LCD}}\n\\def\\CrcWord{{\\rm CrcWord}}\n\n\\def\\remove#1{}\n\n% -----------------------------------------\n\\title{Everything we know about CRC but afraid to forget}\n\\author[1]{Andrew Kadatch}\n\\affil[1]{Google Inc.}\n\\author[2]{Bob Jenkins}\n\\affil[2]{Microsoft Corporation}\n\\maketitle\n\n\\begin{abstract}\n  This paper describes a novel interleaved, parallelizeable word-by-word\n  CRC computation algorithm which computes $N$-bit CRC ($N \\leq 64$) on\n  modern Intel and AMD processors in 1.2 CPU cycles per byte, improving\n  state of the art over word-by-word 32-bit and 64-bit CRCs (2.1 CPU\n  cycles/byte) and classic byte-by-byte CRC computation (6-7 CPU cycles/byte).\n  It computes 128-bit CRC in 1.7 CPU cycles/byte.\n\n  CRC implementations are heavily optimized and hard to understand. This\n  paper describes CRC algorithms as they evolved over time, splitting\n  complex optimizations into a sequence of natural improvements.\n\n  This paper also presents a collection of CRC ``tricks\" that we found\n  handy on many occassions.\n\\end{abstract}\n\n\\tableofcontents\n\n\n% -----------------------------------------\n\\section{Definition of CRC}\n\nCyclic Redundancy Check (CRC) is a well-known technique that allows the\nrecipient of a message transmitted over a noisy channel to detect whether\nthe message has been corrupted.\n\nA message $M = m_0 \\dots m_{N-1}$ comprised of $N=|M|$ bits ($m_k \\in \\{0,\n1\\}$) may be viewed either as a numeric value\n  \\begin{align*}\n    M = \\sum_{k=0}^{N-1} m_k 2^{N-1-k}\n  \\end{align*}\nor as a polynomial of a single variable of degree $(N-1)$\n  \\begin{align*}\n    M(x) = \\sum_{k=0}^{N-1} m_k x^{N-1-k}\n  \\end{align*}\nwhere $m_k \\in GF(2) = \\{0, 1\\}$ and all arithmetic operations on\ncoefficients are performed modulo 2. For example,\n  \\begin{align*}\n    & \\mbox{Addition: }\n        (x^3+x^2+x+1) + (x^2+x+1) = x^3+2x^2+2x+2 = x^3, \\\\\n    & \\mbox{Subtraction: }\n        (x^3+x+1) - (x^2+x) = x^3-x^2+1 = x^3+x^2+1, \\\\\n    & \\mbox{Multiplication: }\n        (x+1)(x+1) = x^2 + 2x + 1 = x^2 + 1.\n  \\end{align*}\n\nFor a given polynomial $P(x)$ of degree $D=\\deg\\bigl(P(x)\\bigr)$,\n$\\CRC\\bigl(M(x),v(x)\\bigr)$ is the reminder from division of $\\left(M(x)\n\\cdot x^D\\right)$ by $P(x)$. In practice, a more complex formula is used:\n  \\begin{align}\n    \\label{e:crcdefinition}\n    \\CRC\\bigl(M(x), v(x)\\bigr)\n      = \\Bigl(\\bigl(v(x)-u(x)\\bigr) \\cdot x^{|M|} + M(x) \\cdot x^D + u(x)\\Bigr)\n        \\bmod P(x),\n  \\end{align}\nwhere polynomial $P(x)$ of degree $D$ and polynomial $u(x)$ of degree less\nthan $D$ are fixed.\n\nThe use of the non-zero value of $u(x)$ guarantees that the CRC of a sequence\nof zeroes is different from zero. That allows detection of insertion of\nzeroes in the beginning of a message and replacement of both content of the\nmessage and its CRC value with zeroes. Typically,\n  \\begin{align}\n    \\label{e:constdefinition}\n    u(x) &= \\sum_{k=0}^{D-1} x^k.\n  \\end{align}\n\nThe use of auxilary parameter $v(x)$ allows incremental CRC computation\nas shown in section \\ref{s:incrementalcrc}.\n\n% -----------------------------------------\n\\section{Related work}\n\nCyclic Redundancy Checks (CRCs) were proposed by Peterson and Brown\n\\cite{Peterson61} in 1961. An efficient table-driven software\nimplementation which reads and processes data byte by byte was described by\nHill \\cite{Hill79} in 1979, Perez \\cite{Perez83} in 1983. The ``classic\"\nbyte-by-byte CRC algorithm described in section \\ref{s:crcbyte} was\npublished by Sarwate \\cite{DBLP:journals/cacm/Sarwate88} in 1988.\n\nIn 1993, Black \\cite{Black93} published a method that reads data by words\n(described in section \\ref{s:crcbyteword}); however, it still computes the\nCRC byte by byte in strong sequential order.\n\nIn 2001, Braun and Waldvogel \\cite{\\remove{%braun01fast,\n}braun01fast-techreport} briefly outlined a specialized variant of a CRC\nthat could read input data by words and process them byte by byte -- but,\nthanks to the use of multiple tables, different bytes from the input word\ncould be processed in parallel. In 2002, Ji and Killian \\cite{JiKillian02}\nprovided detailed description and analysis of a nearly identical scheme.\nBoth solutions were targeted for hardware implementation. In 2005, Kouvanis\nand Berry \\cite{Kounavis2005\\remove{, DBLP:conf/iscc/KounavisB05,\nDBLP:journals/tc/KounavisB08}} demonstrated clear performance benefits of\nthis scheme even when it is implemented in software. A generalized version\nof this approach is described in section \\ref{s:crcword}.\n\nSurprisingly, until \\cite{Gopal2010} we have not seen prior art describing\nor utilizing a method of computing a CRC by processing in parallel (in an\ninterleaved manner to utilize multiple ALUs) multiple input streams\nbelonging to non-overlapping sections of input data, desribed in section\n\\ref{s:blockword}.\n\nA novel method of CRC computation that processes in parallel multiple words\nbelonging to overlapping sections of input data is described in section\n\\ref{s:multiword}. A special case restricted to the use of 64-bit tables,\n64-bit reads, and 32 or 64-bit generating polynomials was implemented by\nthe authors in February-March 2007 and was used by a couple of Microsoft\nproducts. In 2009, the algorithm was generalized and these limitations were\nremoved.\n\nThe fact that the CRC of a message followed by its CRC is a constant value\nwhich does not depend on the message, described in section\n\\ref{s:storingcrcafter}, is well known and has been widely used in the\ntelecommunication industry for long time.\n\nA method of storing a carefully chosen sequence of bits after a message so\nthat the CRC of a message and the sequence of bits appended to the message\nproduces predefined result, described in \\ref{s:storingcrcafter}, was\nimplemented in 1990 by Zemtsov \\cite{Zemtsov90}.\n\nA method for recomputing a known CRC using a new initial CRC value,\ndescribed in section \\ref{s:changinginitialvalue}, and the method of\ncomputing a CRC of the concatenation of messages having known CRC values\nwithout touching the actual data, described in section\n\\ref{s:concatenation}, were implemented by one of the authors in 2005 but\nwere not published.\n\n\n% -----------------------------------------\n\\section{CRC tricks and tips}\n\n\n% -----------------------------------------\n\\subsection{Incremental CRC computation} \\label{s:incrementalcrc}\n\nThe use of an arbitrary initial CRC value $v(x)$ allows computation of a CRC\nincrementally. If a message\n  $M(x) = M_1(x) \\cdot x^{|M_2|} + M_2(x)$\nis a concatenation of messages $M_1$ and $M_2$, its CRC may be computed\npiece by piece because\n  \\begin{align}\n    \\label{e:incremental}\n    \\CRC\\bigl(M(x), v(x)\\bigr)\n      &= \\CRC\\Bigl(M_2(x), \\CRC\\bigl(M_1(x), v(x)\\bigr)\\Bigr).\n  \\end{align}\n\nIndeed,\n  \\begin{align*}\n    \\CRC(M, v)\n      &= \\bigl((v-u) x^{|M|} + M x^D + u\\bigr) \\bmod P = \\\\\n      &= \\bigl((v-u) x^{|M_1|+|M_2|} + (M_1 x^{|M_2|} + M_2) x^D + u\\bigr) \\bmod P = \\\\\n      &= \\Bigl(\\bigl((v-u) x^{|M_1|} + M_1 x^D \\bigr) x^{|M_2|} + M_2 x^D + u\\Bigr) \\bmod P = \\\\\n      &= \\bigl(\\CRC(M_1, v) x^{|M_2|} + M_2 x^D + u\\bigr) \\bmod P = \\\\\n      &= \\CRC\\bigl(M_2, \\CRC(M_1, v)\\bigr)\n  \\end{align*}\n\n\n% -----------------------------------------\n\\subsection{Changing initial CRC value} \\label{s:changinginitialvalue}\n\nIf\n  $\\CRC\\bigl(M(x), v(x)\\bigr)$\nfor some initial value $v(x)$ is known, it is possible to compute\n  $\\CRC\\bigl(M(x), v'(x)\\bigr)$\nfor different initial value $v'(x)$ without touching the value of $M(x)$:\n  \\begin{align}\n    \\CRC(M, v')\n      &= \\CRC(M,v) + \\Bigl((v'-v) x^{|M|}\\Bigr) \\bmod P.\n  \\label{e:fixv}\n  \\end{align}\n\nProof:\n  \\begin{align*}\n    \\CRC(M, v')\n      &= \\bigl((v'-u) x^{|M|} + M x^D + u\\bigr) \\bmod P = \\\\\n      &= \\Bigl(\\bigl((v'-u)+(v-v)\\bigr) x^{|M|} + M x^D + u\\Bigr) \\bmod P = \\\\\n      &= \\Bigl(\\bigl((v-u)+(v'-v)\\bigr) x^{|M|} + M x^D + u\\Bigr) \\bmod P = \\\\\n      &= \\Bigl(\\bigl((v-u) x^{|M|} + M x^D + u\\bigr) + (v'-v) x^{|M|}\\Bigr) \\bmod P = \\\\\n      &= \\CRC(M,v) + \\Bigl((v'-v) x^{|M|} \\bmod P \\Bigr).\n  \\end{align*}\n\n\n% -----------------------------------------\n\\subsection{Concatenation of CRCs} \\label{s:concatenation}\n\nIf a message\n  $M(x) = M_1(x) \\cdot x^{|M_2|} + M_2(x)$\nis a concatenation of messages $M_1$ and $M_2$, and CRCs of $M_1$, $M_2$\n(computed with some initial values $v_1(x)$, $v_2(x)$ respectively) are\nknown,\n $\\CRC\\bigl(M(x),v(x)\\bigr)$\nmay be computed without touching contents of the message $M$:\n\\begin{enumerate}\n\\item\n  Using formula (\\ref{e:fixv}), the value of $v'_1 = \\CRC(M_1,v)$ may\n  be computed from the known $\\CRC(M_1,v_1)$ without touching the contents of $M_1$.\n\\item\n  Then, $v'_2 = \\CRC(M_2, v'_1)$ may be computed from known $\\CRC(M_2,v_2)$\n  without touching the contents of $M_2$.\n\\end{enumerate}\nAccording to (\\ref{e:incremental}), $\\CRC(M,v) = v'_2$.\n\n\n\n% -----------------------------------------\n\\subsection{In-place modification of CRC-ed message} \\label{s:replacement}\n\nSometimes it is necessary to replace a part of message $M(x)$ in-place and\nrecompute CRC of modified message $M(x)$ efficiently.\n\nIf a message $M=ABC$ is a concatenation of messages $A$, $B$, and $C$, and\n$B'(x)$ is new message of the same length as $B(x)$, $\\CRC(M')$ of message\n$M'=AB'C$ may be computed from known $\\CRC(M)$. Indeed,\n  \\begin{align*}\n    M(x)  &= A(x) \\cdot x^{|B| + |C|} + B(x) \\cdot x^{|C|} + C(x), \\\\\n    M'(x) &= A(x) \\cdot x^{|B| + |C|} + B'(x) \\cdot x^{|C|} + C(x) = \\\\\n          &= M(x) + \\bigl(B'(x) - B(x)\\bigr) \\cdot x^{|C|},\n  \\end{align*}\ntherefore\n  \\begin{align*}\n    &  \\CRC\\bigl(M'(x),v(x)\\bigr) = \\\\\n    &= \\CRC\\Bigl(M(x) +\\bigl(B'(x) - B(x)\\bigr) \\cdot x^{|C|}\\Bigr) = \\\\\n    &= \\Bigl(\\bigl(v(x)-u(x)\\bigr) x^{|M|} + M(x) x^D + \\bigl(B'(x) - B(x)\\bigr) x^{|C| + D} + u(x)\\Bigr) \\bmod P(x) \\\\\n    &= \\Bigl(\\CRC\\bigl(M(x),v(x)\\bigr) + \\bigl(B'(x) - B(x)\\bigr) x^{|C| + D}\\Bigr) \\bmod P(x) = \\\\\n    &= \\CRC\\bigl(M(x),v(x)\\bigr) + \\Bigl(\\bigl(B'(x) - B(x)\\bigr) x^{|C| + D} \\bmod P(x)\\Bigr).\n  \\end{align*}\n\nIt is easy to see that\n  \\begin{align*}\n    &  \\CRC\\bigl(B'(x),v(x)\\bigr) - \\CRC\\bigl(B(x),v(x)\\bigr) = \\\\\n    &= \\bigl(B'(x) - B(x)\\bigr) x^{D} \\bmod P(x),\n  \\end{align*}\nso\n  \\begin{align*}\n    & \\CRC\\bigl(M'(x),v(x)\\bigr) = \\CRC\\bigl(M(x),v(x)\\bigr) + \\Delta \\\\\n  \\end{align*}\nwhere\n  \\begin{align*}\n    & \\Delta = \\Bigl(\\CRC\\bigl(B'(x),v(x)\\bigr) - \\CRC\\bigl(B(x),v(x)\\bigr) \\Bigr) x^{|C|} \\bmod P(x).\n  \\end{align*}\n\n% -----------------------------------------\n\\subsection{Storing CRC value after the message} \\label{s:storingcrcafter}\n\nOften $Q(x) = \\CRC\\bigl(M(x),v(x)\\bigr)$ is padded with zero bits until the\nnearest byte or word boundary and is transmitted as a sequence of $W$ bits\n($W \\geq D$) right after the message $M(x)$. This way, the transmitted\nmessage $T(x)$ is the concatenation of $M(x)$ and $Q(x)$ followed by\n$(W-D)$ zeroes, and is equal to\n  \\begin{align*}\n    T(x) = M(x) \\cdot x^W + Q(x) \\cdot x^{W-D}.\n  \\end{align*}\n\nAccording to (\\ref{e:crcdefinition}), (\\ref{e:incremental}) and taking into\naccount that $Q(x)+Q(x) = 0$ since polynomial coefficient are from $GF(2)$,\n$\\CRC\\bigl(T(x), v(x)\\bigr)$ is a constant value which does not depend on\nthe contents of the message and is equal to\n  \\begin{align*}\n    & \\CRC\\bigl(T(x), v(x)\\bigr) = \\\\\n    & = \\CRC\\Bigl(Q(x) \\cdot x^{W-D}, CRC\\bigl(M(x), v(x)\\bigr)\\Bigr) = \\\\\n    & = \\CRC\\bigl(Q(x) \\cdot x^{W-D}, Q(x)\\bigr) = \\\\\n    & = \\Bigl(\\bigl(Q(x)-u(x)\\bigr) \\cdot x^W + Q(x)\\cdot x^{W-D} \\cdot x^D + u(x)\\Bigr)\n        \\bmod P(x) = \\\\\n    & = \\Bigl(u(x)\\left(1 - x^W\\right)\\Bigr) \\bmod P(x).\n  \\end{align*}\n\nA more generic solution is to store a $W$-bit long value after the message\nsuch that the CRC of the transmitted message is equal to a predefined value\n$R(x)$ (typically $R(x)=0$). The $D$-bit value followed by $(W-D)$ zero\nbits that should be stored after $M(x)$ is\n  \\begin{align*}\n    \\hat{q}\\bigl(Q(x)\\bigr) = \\Bigl(\\bigl(R(x) - u(x)\\bigr) x^{-W} - \\bigl(Q(x) - u(x)\\bigr)\\Bigr) \\bmod P(x)\n  \\end{align*}\nwhere $x^{-W}$ is the multiplicative inverse of $x^W \\bmod P(x)$ which\nexists if $P(x)$ is not divisble by $x$ and may be found by the extended\nEuclidean algorithm \\cite{Hasan01}:\n  \\begin{align*}\n    & \\CRC\\Bigl(\\hat{q}\\bigl(Q(x)\\bigr)x^{W-D}, CRC\\bigl(M(x), v(x)\\bigr)\\Bigr) = \\\\\n    & = \\CRC\\Bigl(\\hat{q}\\bigl(Q(x)\\bigr)x^{W-D}, Q(x)\\Bigr) = \\\\\n    & = \\Bigl(\\bigl(Q(x)-u(x)\\bigr) \\cdot x^W + \\hat{q}\\bigl(Q(x)\\bigr) \\cdot x^{W-D} \\cdot x^D + u(x)\\Bigr)\n          \\bmod P(x) = \\\\\n    & = R(x).\n  \\end{align*}\n\n\n% -----------------------------------------\n\\section{Efficient software implementation}\n\n% -----------------------------------------\n\\subsection{Mapping bitstreams to hardware registers}\n\nFor little-endian machines (assumed from now on), the result of loading of\na $D$-bit word from memory into hardware register matches the expectations:\nthe 0-th bit of the 0-th byte becomes the 0-th (least significant) bit of\nthe word corresponding to $x^{(D-1)}$.\n\nFor example, the 32-bit sequence of 4 bytes 0x01, 0x02, 0x03, 0x04\n(0x04030201 when loaded into a 32-bit hardware register) corresponds to the\npolynomial\n  \\begin{align*}\n    \\left(x^{31} + x^{22} + x^{15} + x^{14} + x^{5}\\right).\n  \\end{align*}\n\nAddition and subtraction of polymonials with coefficients from $GF(2)$ is\nthe bitwise XOR of their coefficients. Multiplication of a polynomial by\n$x$ is achieved by logical right shift of register contents by 1 bit. If a\nshift operation causes a carryover, the resulting polynomial has degree\n$D$.\n\nPolynomials of degree less than $D$ whose coefficients are recorded using\nexactly $D$ bits irrespective of actual degree of the polynomial will be\ncalled {\\it $D$-normalized}.\n\nWhenever possible -- and unless mentioned explicitly -- all polynomials\nwill be represented in $D$-normalized form.\n\nSince the generating polynomial $P(x)$ is of degree $D$ and has $(D+1)$\ncoefficients, it does not fit into the $D$-bit register. However, its most\nsignificant coefficient is guaranteed to be 1 and may be implied\nimplicitly.\n\n% -----------------------------------------\n\\subsection{Multiplication of $D$-normalized polynomials} \\label{s:shiftandadd}\n\nMultiplication of two $D$-normalized polynomials may be accomplished by\ntraditional bit-by-bit, shift-and-add multiplication. This is adequate if\nperformance is not a concern. Sample code is given in listing\n\\ref{l:MulNormalizedPoly}.\n\n\\begin{figure}\n\\begin{lstlisting}[caption={Multiplication of normalized polynomials},label={l:MulNormalizedPoly}]\n// \"a\" and \"b\" occupy D least significant bits.\nCrc Multiply(Crc a, Crc b) {\n  Crc product = 0;\n  Crc bPowX[D];  // bPowX[k] = (b * x**k) mod P\n  bPowX[0] = b;\n  for (int k = 0; k < D; ++k) {\n    // If \"a\" has non-zero coefficient at x**k,\n    // add ((b * x**k) mod P) to the result.\n    if (((a & (1 << (D-k)) != 0) product ^= bPowX[k];\n\n    // Compute bPowX[k+1] = (b ** x**(k+1)) mod P.\n    if (bPowX[k] & 1) {\n      // If degree of (bPowX[k] * x) is D, then\n      // degree of (bPowX[k] * x - P) is less than D.\n      bPowX[k+1] = (bPowX[k] >> 1) ^ P;\n    } else {\n      bPowX[k+1] = bPowX[k] >> 1;\n    }\n  }\n  return product;\n}\n\\end{lstlisting}\n\\end{figure}\n\n% -----------------------------------------\n\\subsection{Multiplication of unnormalized polynomial}\n\nDuring initialization of CRC tables it may be necessary to multiply\n$d$-normalized polynomial $v(x)$ of a degree $d \\neq D$ by a $D$-normalized\npolynomial. It may be accomplished by representing the operand as a sum of\nweighted polynomials of degree of no more than $(D-1)$, then calling\n$Multiply()$ function repeatedly as shown in listing\n\\ref{l:MulUnnormalizedPoly}.\n\n\\begin{figure}\n\\begin{lstlisting}[caption={Multiplication of unnormalized polynomial},label={l:MulUnnormalizedPoly}]\n// \"v\" occupies \"d\" least signficant bits.\n// \"m\" occupies D least significant bits.\nCrc MultiplyUnnormalized(Crc v, int d, Crc m) {\n  Crc result = 0;\n  while (d > D) {\n    Crc temp = v & ((1 << D) - 1);\n    v >>= D;\n    d -= D;\n    // XpowN returns (x**N mod P(x)).\n    result ^= Multiply(temp, Multiply(m, XpowN(d)));\n  }\n  result ^= Multiply(v << (D - d), m);\n  return result;\n}\n\\end{lstlisting}\n\\end{figure}\n\n\n% -----------------------------------------\n\\subsection{Computing powers of $x$} \\label{s:mulpown}\n\nOften (see sections \\ref{s:changinginitialvalue}, \\ref{s:concatenation},\n\\ref{s:storingcrcafter}) it is necessary to compute $x^N \\bmod P(x)$ for\nvery large values of $N$. This may be accomplished in\n$O\\bigl(\\log(N)\\bigr)$ time.\n\nConsider the binary representation of $N$:\n  \\begin{align*}\n    N = \\sum_{k=0}^K n_k 2^k\n  \\end{align*}\nwhere $n_k \\in \\{0, 1\\}$. Then\n  \\begin{align}\n    x^N &= x^{\\sum n_k 2^k}\n         = \\prod_{k=0}^K x^{n_k 2^k}\n         = \\prod_{n_k != 0} x^{2^k} \\label{e:pow2k}\n  \\end{align}\nand may be computed using no more than\n    $\\left(\\left\\lfloor \\log_2(N) \\right\\rfloor + 1\\right)$\nmultiplications of polynomials of degree less than $D$ provided known\nvalues of\n  \\begin{align}\n    Pow2k(k) = x^{2^k} \\bmod P(x).\n  \\end{align}\n\nValues of $Pow2k(k)$ may be computed iteratively using one multiplication\n$\\bmod P(x)$ per iteration:\n  \\begin{align*}\n    Pow2k(0) &= 0, \\\\\n    Pow2k(k + 1)\n      &= x^{2^{k+1}} \\bmod P(x) = \\\\\n      &= x^{2 \\cdot 2^k} \\bmod P(x) = \\\\\n      &= \\left(x^{2^k}\\right)^2 \\bmod P(x) = \\\\\n      &= \\Bigl(Pow2k(k-1)\\Bigr)^2 \\bmod P(x).\n  \\end{align*}\n\n% -----------------------------------------\n\\subsection{Simplified CRC}\n\nIt is sufficient to be able to compute\n  \\begin{align}\n    \\SCRC\\bigl(M(x), v(x)\\bigr)\n      &= \\Bigl(v(x) \\cdot x^{|M|} + M(x) \\cdot x^D\\Bigr)\n        \\bmod P(x), \\label{e:simplifiedcrc}\n  \\end{align}\nsince\n  \\begin{align*}\n    \\CRC\\bigl(M(x),v(x)\\bigr) &= \\SCRC\\bigl(M(x), v(x) - u(x)\\bigr) + u(x),\n  \\end{align*}\n$\\CRC\\bigl(M(x),v(x)\\bigr)$ of message $M = M_1 \\ldots M_K$ may be computed\nincrementally using $\\SCRC$ instead of $\\CRC$:\n  \\begin{align*}\n    v_0(x) &= v(x) - u(x), \\\\\n    v_k(x) &= \\SCRC\\bigl(M_k(x),v_{k-1}(x)\\bigr), \\\\\n    \\CRC(M(x), v(x)) &= v_K + u(x).\n  \\end{align*}\n\n\n% -----------------------------------------\n\\subsection{Computing a CRC byte by byte} \\label{s:crcbyte}\n\nIf $M(x)$ is $W$-bit value (typically, $W=8$) and\n$\\deg\\bigl(v(x)\\bigr) < D$, by definition (\\ref{e:simplifiedcrc})\n  \\begin{align*}\n    \\SCRC\\bigl(M(x), v(x)\\bigr)\n      = \\Bigl(v(x) \\cdot x^W + M(x) \\cdot x^D\\Bigr) \\bmod P(x).\n  \\end{align*}\n\nWhen $D \\leq W$,\n\\begin{align}\n  \\SCRC\\bigl(M(x), v(x)\\bigr)\n    &= \\Bigl(v(x) \\cdot x^W + M(x) \\cdot x^D\\Bigr) \\bmod P(x) = \\nonumber \\\\\n    &= \\Bigl(\\bigl(v(x) \\cdot x^{W-D} + M(x)\\bigr) \\cdot x^D\\Bigr) \\bmod P(x), \\label{e:crcbytetable2}\n\\end{align}\nwhich may be obtained via single lookup into precomputed table $T$ of size\n$2^W$ such that $T[i] = \\bigl(i(x) \\cdot x^D)\\bigr) \\bmod P(x)$ since\n$\\deg\\bigl(v(x) \\cdot x^{W-D} + M(x)\\bigr) < W$.\n\n$D$-normalized representation of $v(x)$ occupies $D$ least significant bits\nand is equal to $\\left(v(x) \\cdot x^{W-D}\\right)$ when viewed as\n$W$-normalized representation which is required to form $W$-bit index into\na table of $2^W$ entries. Therefore, explicit multiplication of $v(x)$ by\n$x^{W-D}$ in formula (\\ref{e:crcbytetable2}) is not required.\n\nWhen $D \\geq W$, $v(x)$ may be represented as\n  \\begin{align*}\n    v(x) = v_L(x) + v_H(x) \\cdot x^{D-W}\n  \\end{align*}\nwhere\n  \\begin{align*}\n    v_H(x) &= \\left\\lfloor\\frac{v(x)}{x^{D-W}}\\right\\rfloor,\n        &\\deg\\bigl(v_H(x)\\bigr) &< W, \\\\\n    v_L(x) &= v(x) \\bmod x^{D-W},\n        &\\deg\\bigl(v_L(x)\\bigr) &< D-W.\n  \\end{align*}\n\nSince $\\deg\\bigl(v_L(x) \\cdot x^W \\bigr) < D$, $\\Bigl(v_L(x) \\cdot\nx^W\\Bigr) \\bmod P(x) = v_L(x) \\cdot x^W$. Therefore,\n  \\begin{align}\n    & \\SCRC\\bigl(M(x), v(x)\\bigr) = \\nonumber \\\\\n      &= \\Bigl(v(x) \\cdot x^W + M(x) \\cdot x^D\\Bigr) \\bmod P(x) = \\nonumber \\\\\n      &= \\Bigl(\\bigl(v_L(x) + v_H(x) \\cdot x^{D-W}\\bigr)\\cdot x^W + M(x) \\cdot x^D\\Bigr) \\bmod P(x) = \\nonumber \\\\\n      &= \\Bigl(v_L(x) \\cdot x^W + \\bigl(v_H(x) + M(x)\\bigr) \\cdot x^D\\Bigr) \\bmod P(x) = \\nonumber \\\\\n      &= \\Bigl(v_L(x) \\cdot x^W + \\bigl(v_H(x) + M(x)\\bigr) \\cdot x^D\\Bigr) \\bmod P(x) = \\nonumber \\\\\n      &= \\Bigl(v_L(x) \\cdot x^W\\Bigr) \\bmod P(x) + \\Bigl(\\bigl(v_H(x) + M(x)\\bigr) \\cdot x^D \\Bigr) \\bmod P(x) = \\nonumber \\\\\n      &= \\Bigl(v_L(x) \\cdot x^W\\Bigr) + \\mbox{MulByXpowD}\\bigl(v_H(x) + M(x)\\bigr), \\label{e:crcbyte}\n  \\end{align}\nwhere\n  \\begin{align}\n    \\mbox{MulByXpowD}\\bigl(a(x)\\bigr) = \\bigl(a(x) \\cdot x^D \\bigr) \\bmod P(x). \\label{e:crcbytetable}\n  \\end{align}\n\nThe value of $\\bigl(v_L(x) \\cdot x^W\\bigr)$ may be computed by shifting\n$v(x)$ by $W$ bits and discarding $W$ carry-over zero bits.\n\nSince $\\deg\\bigl(v_H(x) + M(x)\\bigr) < W$, the value of\n$\\mbox{MulByXpowD}\\bigl(v_H(x) + M(x)\\bigr)$ may be obtained using\nprecomputed table containing $2^W$ entries.\n\nThe classic table-driven, byte-by-byte CRC computation \\cite{Perez83,\nDBLP:journals/cacm/Sarwate88} implementing formulas\n(\\ref{e:crcdefinition}), (\\ref{e:incremental}), (\\ref{e:crcbytetable2}),\n(\\ref{e:crcbyte}), and (\\ref{e:crcbytetable}) for $W=8$ is given in listing\n\\ref{l:CrcByte}.\n\n\\begin{figure}\n\\begin{lstlisting}[caption={Computing CRC byte by byte},label={l:CrcByte}]\nCrc CrcByte(Byte value) {\n  return MulByXpowD[value];\n}\nCrc CrcByteByByte(Byte *data, int n, Crc v, Crc u) {\n  Crc crc = v ^ u;\n  for (int i = 0; i < n; ++i) {\n    Crc ByteCrc = CrcByte(crc ^ data[i]);\n    crc >>= 8;\n    crc ^= ByteCrc;\n  }\n  return (crc ^ u);\n}\nvoid InitByteTable() {\n  for (int i = 0; i < 256; ++i) {\n    MulByXPowD[i] = MultiplyUnnormalized(i, 8, XpowN(D));\n  }\n}\n\\end{lstlisting}\n\\end{figure}\n\nExperience shows that computing CRC byte by byte is rather slow and,\ndepending on a compiler and input data size, takes $6-8$ CPU cycles per\nbyte on modern 64-bit CPU for $D <= 64$. There are two reasons for it:\n\n\\begin{enumerate}\n\\item\n  Reading data 8 bits at a time is not the most efficient data access\n  method on 64-bit CPU.\n\\item\n  Modern CPUs have multiple ALUs and may execute 3-4 instructions per CPU\n  cycles provided the instructions handle independent data flows. However,\n  byte-by-byte CRC contains only one data flow. Futhermore, most\n  instructions use the result from the previous instruction, leading to CPU\n  stalls because of result propagation delays.\n\\end{enumerate}\n\n\n% -----------------------------------------\n\\subsection{Rolling CRC} \\label{s:rollingcrc}\n\nGiven a set of messages $M_k=m_{k} \\ldots m_{k+N-1}$ where $m_k$ are\n$W$-bit symbols and $N$ is fixed (i.e. each next message is obtained by\nremoving first symbol and appending new one), $C_{k+1} = \\CRC(M_{k+1}, v)$\nmay be obtained from known $C_k = \\CRC(M_k, v)$ and symbols $m_k$ and\n$m_{k+N}$ only, without the need to compute CRC of entire message\n$M_{k+1}$. This property may be utilized to efficiently compute a set of\nrolling Rabin fingerpints.\n\nSince $M_{k+1}(x) = M_k(x) x^W - m_{k}(x) x^{NW} + m_{k+N}(x)$,\n  \\begin{align*}\n    & C_{k+1}(x) = \\CRC\\bigl(M_{k+1}(x), v(x)\\bigr) = \\\\\n    &= \\left(\\bigl(v(x)-u(x)\\bigr) x^{NW} + u(x) + \\sum_{n=0}^{N-1} m_{k+1+n}(x) x^{D+W(N-1-n)} \\right) \\bmod P(x) = \\\\\n    &= F\\bigl(C_k(x), m_{k+N}(x)\\bigr) + G\\bigl(m_k(x)\\bigr),\n  \\end{align*}\nwhere\n  \\begin{align*}\n    & F\\bigl(C_k(x), m_{k+N}(x)\\bigr) = \\Bigl(C_k(x) x^W + m_{k+N}(x) x^D\\Bigr) \\bmod P, \\\\\n    & G\\bigl(m_k(x)\\bigr) = \\Bigl(\\bigl(\\bigl(v(x)-u(x)\\bigr) x^{NW} + u\\bigr) (1 - x^W) - m_k(x) x^{D+NW} \\Bigr) \\bmod P\n  \\end{align*}\nare polynomials of degree less than $D$.\n\n$G\\bigl(m_{k-1}(x)\\bigr)$ may be computed easily via a single lookup\nin a table of $2^W$ entries indexed by $m_k$.\n\nComputation of $F\\bigl(C_k(x), m_{k+N}(x)\\bigr)$ may be implemented as\ndescribed in section \\ref{s:crcbyte} and requires one bitwise shift, one\nbitwise XOR, and one lookup into a precomputed table containing $2^W$\nentries.\n\n\n% -----------------------------------------\n\\subsection{Reading multiple bytes at a time} \\label{s:crcbyteword}\n\nOne straightforward way to speed up byte-by-byte CRC computation is to read\n$W > 8$ bits at once. Unfortunately, this is the path of very rapidly\ndiminishing return as the size of the MulByPowD table increases with $W$\nexponentially. From practical perspective, it is extremely desirable to\nensure that the MulByPowD table fits into the L1 cache (32-64KB), otherwise\ntable entry access latency sharply increases from 3-4 CPU cycles (L1 cache)\nto 15-20 CPU (L2 cache).\n\nThe value of $\\mbox{MulByXpowD}\\bigl(v(x)\\bigr)$ may be computed\niteratively using a smaller table because\n  \\begin{align}\n    \\mbox{MulByXpowD}\\bigl(v(x)\\bigr)\n      = v(x) \\cdot x^D \\bmod P(x)\n      = \\SCRC\\bigl(v(x), 0\\bigr) \\label{e:readwordatonce}\n  \\end{align}\nand therefore may be computed using formulas (\\ref{e:incremental}) and\n(\\ref{e:crcbyte}) for smaller values of $W'$.\n\n\\cite{Black93} provided the implementation for $W=32$ and $W'=8$. Our more\ngeneral implementation was faster than byte-by-byte CRC but not\nsubstentially: the improvement was in 20-25\\% range. However, the result is\nstill important -- it demonstrates that reading input data per se is not a\nbottleneck.\n\n\n% -----------------------------------------\n\\subsection{Computing a CRC word by word} \\label{s:crcword}\n\nThe value of $\\mbox{MulByXpowD}\\bigl(v(x)\\bigr)$ may be computed using\nmultiple smaller tables instead of one table. Given that\n$\\deg\\bigl(v(x)\\bigr) < W$, $v(x)$ may be represented as a weighted\nsum of polynomials $v_k(x)$ such that $\\deg\\bigl(v_k(x)\\bigr) < B$:\n  \\begin{align*}\n    v(x) = \\sum_{k=0}^{K-1} v_k(x) \\cdot x^{(K-1-k)B},\n  \\end{align*}\nwhere $K = \\lceil W/B \\rceil$ and\n  \\begin{align*}\n    v_k(x) = \\left\\lfloor \\frac{v(x)}{x^{(K-1-k)B}} \\right\\rfloor \\bmod x^B.\n  \\end{align*}\n\nConsequently,\n  \\begin{align}\n    \\mbox{MulByXpowD}\\bigl(v(x)\\bigr)\n      &= v(x) \\cdot x^D \\bmod P(x) = \\nonumber \\\\\n      &= \\left(\\sum_{k=0}^{K-1} v_k(x) \\cdot x^{(K-1-k)B}\\right) \\cdot x^D \\bmod P(x) = \\nonumber \\\\\n      &= \\sum_{k=0}^{K-1} \\left(v_k(x) \\cdot x^{(K-1-k)B+D} \\bmod P(x)\\right) = \\nonumber \\\\\n      &= \\sum_{k=0}^{K-1} \\mbox{MulWordByXpowD}\\bigl(k, v_k(x)\\bigr), \\label{e:crcword}\n  \\end{align}\nwhere the values of\n  \\begin{align}\n    \\mbox{MulWordByXpowD}\\bigl(k, v_k(x))\\bigr) = v_k(x) \\cdot x^{(K-1-k)B+D} \\bmod P(x) \\label{e:crcwordtable}\n  \\end{align}\nmay be obtained using $K$ precomputed tables. Given that\n$\\deg\\bigl(v_k(x)\\bigr) < B$, each table should contain $2^B$\nentries.\n\nA sample implementation of formulas (\\ref{e:crcdefinition}),\n(\\ref{e:incremental}), (\\ref{e:crcword}), and (\\ref{e:crcwordtable}) is\ngiven in listing \\ref{l:CrcWord} using $B=8$ and assuming that $W$ is a\nmultiple of 8.\n\n\\begin{figure}\n\\begin{lstlisting}[caption={Computing CRC word by word},label={l:CrcWord}]\nCrc CrcWord(Word value) {\n  Crc result = 0;\n  // Unroll this loop or let compiler do it.\n  for (int byte = 0; byte < sizeof(Word) / 8; ++byte) {\n    result ^= MulWordByXpowD[byte][(Byte) value];\n    value >>= 8;\n  }\n  return result;\n}\nCrc CrcWordByWord(Word *data, int n, Crc v, Crc u)\n  Crc crc = v ^ u;\n  for (int i = 0; i < n; ++i) {\n    Crc WordCrc = CrcWord(crc ^ data[i]);\n    if (sizeof(Crc) <= sizeof(Word)) {\n      crc = WordCrc;\n    } else {\n      crc >>= 8;\n      crc ^= WordCrc;\n    }\n  }\n  return (crc ^ u);\n}\nvoid InitWordTables() {\n  for (int byte = 0; byte < sizeof(Word) / 8; ++byte) {\n    // (K-1-k)*B + D = (W/8-1-byte)*8 + D = D - 8 + W - 8*byte.\n    Crc m = XpowN(D - 8 + sizeof(Word)*8 - 8*byte);\n    for (int i = 0; i < 256; ++i) {\n      MulWordByXpowD[byte][i] =MultiplyUnnormalized(i, 8, m);\n    }\n  }\n}\n\\end{lstlisting}\n\\end{figure}\n\nCrcWordByWord\\footnote{The variant presented in this paper is more general\nthan ``slicing\" described in \\cite{Kounavis2005\\remove{,\nDBLP:conf/iscc/KounavisB05, DBLP:journals/tc/KounavisB08}}. Sample\nimplementation given in listing \\ref{l:CrcWord} does not include one subtle\noptimization implemented in \\cite{Kounavis2005\\remove{,\nDBLP:conf/iscc/KounavisB05, DBLP:journals/tc/KounavisB08}} as it was found\nto be counter-productive.} with $W=64$ uses only 2.1-2.2 CPU cycles/byte on\nmodern 64-bit CPUs (our implementation is somewhat faster than the one\ndescribed in \\cite{Kounavis2005\\remove{, DBLP:conf/iscc/KounavisB05,\nDBLP:journals/tc/KounavisB08}}). It solves the problem with data access\nand, to lesser degree, allows instruction level parallelism: in the middle\nof the unrolled main loop of CrcOfWord function the CPU may process\nmultiple bytes in parallel.\n\nHowever, this solution is still imperfect -- the beginning of computation\ncontends for a single source of data (variable $value$), and the end of\ncomputation contends for a single destination (variable $result$). Further\nimprovement requires processing of multiple independent data streams in\ninterleaved manner so that when computation of one data flow path is\nstalled the CPU may proceed with another one.\n\n% -----------------------------------------\n\\subsection{Processing non-overlapping blocks in parallel} \\label{s:blockword}\n\nStraighforward pipepiling may be achieved by spliting the input message\n$M(x)=M_0(x) \\ldots M_{N-1}(x)$ into $N$ blocks $M_k(x)$ of approximately\nthe same size and computing CRC of each block in an interleaved manner,\nconcatenating CRCs of individual blocks in the end. A sample implementation\nis given in listing \\ref{l:CrcWordBlock}.\n\n\\begin{figure}\n\\begin{lstlisting}[caption={Processing non-overlapping blocks in parallel},label={l:CrcWordBlock}]\n// Processes N stripes of StripeWidth words each\n// word by word, in an interleaved manner.\nCrc CrcWordByWordBlocks(Word *data, Crc v, Crc u) {\n  assert(n % (N * StripeWidth) == 0);\n  // Use N local variables instead of the array.\n  Crc crc[N];\n  // Initialize the CRC value for each stripe.\n  crc[0] = v ^ u;\n  for (int stripe = 1; stripe < N; ++stripe)\n    crc[i] = 0 ^ u;\n  // Compute each stripe's CRC.\n  for (int i = 0; i < StripeWidth; ++i) {\n    // Compute multiple CRCs in interleaved manner.\n    Word buf[N];\n    for (int stripe = 0; stripe < N; ++stripe) {\n      buf[i] =\n        crc[stripe] ^ data[i + stripe * StripeWidth];\n      if (D > sizeof(Word) * 8) {\n        crc[stripe] >>= D - sizeof(Word) * 8;\n      } else {\n        crc[stripe] = 0;\n      }\n    }\n    for (int byte = 0; byte < sizeof(Word) / 8; ++byte) {\n      for (int stripe = 0; stripe < N; ++stripe) {\n        crc[stripe] ^=\n          MulWordByXpowD[byte][(Byte) buf[stripe]];\n        buf[stripe] >>= 8;\n      }\n    }\n  }\n  // Combine stripe CRCs.\n  for (int stripe = 1; stripe < N; ++stripe) {\n    crc[0] = ChangeStartingValue(\n                crc[stripe], StripeWidth, 0, crc[0]);\n  }\n  return (crc[0] ^ u);\n}\n\\end{lstlisting}\n\\end{figure}\n\nA tuned implementation of $CrcWordByWordBlocks$ is capable of processing\ndata at 1.3-1.4 CPU cycles/byte on sufficiently large (64KB and more)\ninputs, which is noticeably better that 2.1-2.2 CPU cycles/byte delivered\nby word by word CRC computation. It is a good sign that it is a move in\nright direction.\n\nThe drawbacks of this approach are obvious: it does not work well with\nsmall inputs -- the cost of CRC concatentation becomes a bottleneck, -- and\nit may be susceptible to false cache collisions caused by cache line\naliasing.\n\nIf the cost of CRC concatenation was not a problem, cache pressure could be\nmitigated with the use of very narrow stripes. The code in question, lines\n33-37 of listing \\ref{l:CrcWordBlock} which combine CRCs of individual\nstripes, iteratively computes\n  \\begin{align*}\n    \\mbox{crc}_0(x) = \\mbox{crc}_k(x) + \\Bigl(\\mbox{crc}_0 \\cdot x^{8S} \\bmod P(x)\\Bigr)\n  \\end{align*}\nfor $k = 1, \\ldots, N-1$ where $N$ and $S$ are the number and the width of\nthe stripes respectively. It may be rearranged as\n  \\begin{align*}\n    \\mbox{crc}_0(x) = \\sum_{k = 0}^{N-1} \\Bigl(\\mbox{crc}_{K-1-k} \\cdot x^{8kS} \\bmod P(x)\\Bigr).\n  \\end{align*}\n\nExplicit multiplication by $x^{8kS}$ may be avoided by moving it into preset\ntables\n  \\begin{align*}\n    \\mbox{MulWordByXPowD}_k(n) = \\mbox{MulWordByXPowD}(n) \\cdot x^{kS} \\bmod P(x).\n  \\end{align*}\nthat are used to compute $crc'_k(x) = \\mbox{crc}_k(x) \\cdot x^{8kS}$, so that\n  \\begin{align*}\n    \\mbox{crc}_0(x) = \\sum_{k = 0}^{N-1} crc'_k.\n  \\end{align*}\n\nUnfortunately, this approach alone does not help because\n\\begin{enumerate}\n\\item\n  It increases the memory footprint of MulWordByXPowD by factor of $N$.\n  Once the cumulative size of $\\mbox{MulWordByXPowD}_k$ tables exceeds the\n  size of L1 cache (32-64KB), the cost of memory access to multiplication\n  table data increases from 3-4 CPU cycles to 15-20, eliminating all\n  performance gains achieved by reducing the number of table operations.\n\\item\n  It is still necessary to combine all $N$ values of $\\mbox{crc}_k$ into\n  $\\mbox{crc}_0$ at the end of the CRC computation.\n\\end{enumerate}\n\n\n% -----------------------------------------\n\\subsection{Interleaved word-by-word CRC} \\label{s:multiword}\n\n% -----------------------------------------\n\\subsubsection{Parallelizing CRC computation} \\label{s:parallelizing}\n\nAssume that input message $M$ is the concatenation of $K$ groups $g_k$, and\neach group $g_k$ is concatenation of $N$ $W$-bit long words:\n  \\begin{align*}\n    M(x) &= \\sum_{k=0}^{K-1} g_k(x) \\cdot x^{(K-1-k)NW}, \\\\\n    g_k(x) &= \\sum_{n=0}^{N-1} m_{k, n} \\cdot x^{(N-1-n)W}.\n  \\end{align*}\n\nInput message $M(x)$ may be represented as\n  \\begin{align}\n    M(x)\n      &= \\sum_{k=0}^{K-1} g_k(x) \\cdot x^{(K-1-k)NW} = \\nonumber \\\\\n      &= \\sum_{k=0}^{K-1} \\left(\\sum_{n=0}^{N-1} m_{k, n} \\cdot x^{(N-1-n)W} \\right) \\cdot x^{(K-1-k)NW} = \\nonumber \\\\\n      &= \\sum_{n=0}^{N-1} \\left(\\sum_{k=0}^{K-1} m_{k, n} \\cdot x^{(K-1-k)NW}\\right) \\cdot x^{(N-1-n)W} = \\nonumber \\\\\n      &= \\sum_{n=0}^{N-1} M_n(x) \\cdot x^{(N-1-n)W} \\label{e:splitbyword}\n  \\end{align}\nwhere\n  \\begin{align*}\n    M_n(x)\n      &= \\sum_{k=0}^{K-1} m_{k, n} \\cdot x^{(K-1-k)NW}.\n  \\end{align*}\n\nIn other words, $M_n$ is concatenation of $n$-th $W$-bit word from $g_0$\nfollowed by $(N-1)W$ zero bits, then $n$-th word from $g_1$ followed by\n$(N-1)W$ zero bits, etc., ending up with $n$-th word from last group\n$g_{K-1}$.\n\nAppending $(N-1)W$ zero bits to $M_n$ yields $M'_n(x) = M_n(x) \\cdot\nx^{(N-1)W} $ which may be viewed as the concatenation of $K$ $NW$-bit\ngroups $f_{k}$:\n  \\begin{align*}\n    M'_n(x)\n      &= M_n(x) \\cdot x^{(N-1)W}\n      = \\sum_{k=0}^{K-1} f_{k, n} \\cdot x^{(K-1-k)NW}, \\\\\n    f_{k, n}(x) &= m_{k, n}(x) \\cdot x^{(N-1)W}, \\\\\n  \\end{align*}\nso\n  \\begin{align}\n    M(x)\n      &= \\sum_{n=0}^{N-1} M_n(x) \\cdot x^{(N-1-n)W} \\nonumber \\\\\n      &= \\sum_{n=0}^{N-1} M'_n(x) \\cdot x^{-(N-1)W} \\cdot x^{(N-1-n)W} \\nonumber \\\\\n      &= \\sum_{n=0}^{N-1} M'_n(x) \\cdot x^{-nW}. \\label{e:mdash}\n  \\end{align}\n\nAccording to (\\ref{e:incremental}),\n  $v_{K, n}(x) = \\SCRC\\bigl(M'_n(x), v_{0, n}(x)\\bigr)$\nmay be computed incrementally:\n  \\begin{align}\n    v_{k+1, n}(x)\n      &= \\SCRC\\bigl(f_{k, n}(x), v_{k, n}(x)\\bigr) = \\nonumber \\\\\n      &= \\SCRC\\bigl(m_{k, n}(x) \\cdot x^{(N-1)W}, v_{k, n}(x)\\bigr) = \\nonumber \\\\\n      &= \\Bigl(v_{k, n}(x) \\cdot x^{NW} + m_{k, n}(x) \\cdot x^{(N-1)W} \\cdot x^D \\Bigr) \\bmod P(x) = \\nonumber \\\\\n      &= \\Bigl(v_{k, n}(x) \\cdot x^W + m_{k, n}(x) \\cdot x^D \\Bigr) \\cdot x^{(N-1)W} \\bmod P(x) = \\label{e:crcwordnmultiply} \\\\\n      &= \\mbox{CrcWordN}\\bigl(m_{k, n}(x), v_{k, n}(x)\\bigr). \\label{e:crcwordn}\n  \\end{align}\n\nThis approach:\n\\begin{enumerate}\n\\item\n  Creates $N$ independent data flows: computation of $v_{k, 0}, \\ldots,\n  v_{k, N-1}$ may be performed truly in parallel. There are no contentions\n  on a single data source or destination like those the word-by-word CRC\n  computation described in section \\ref{s:crcword} suffered from.\n\\item\n  Input data is accessed sequentially. Therefore, the load on cache\n  subsystem and false cache collisions are  minimal. Thus, the performance\n  bottlenecks of approach described in \\ref{s:blockword} are eliminated.\n\\end{enumerate}\n\n\n% -----------------------------------------\n\\subsubsection{Combining individual CRCs} \\label{s:combine}\n\nOnce $v_{K, n}(x) = \\SCRC\\bigl(M'_n(x), v_{0, n}(x)\\bigr)$ are computed starting with\n  \\begin{align*}\n    v_{0, 0} &= v(x), \\\\\n    v_{0, n} &= 0, n \\geq 1,\n  \\end{align*}\nby definition (\\ref{e:simplifiedcrc}) of $\\SCRC$ and relationship (\\ref{e:mdash}),\n  \\begin{align}\n    \\SCRC\\bigl(M(x), v(x)\\bigr)\n      &= \\SCRC\\left(\\sum_{n=0}^{N-1} M'_n(x) \\cdot x^{-nW}, v(x)\\right) = \\nonumber \\\\\n      &= \\sum_{n=0}^{N-1} \\SCRC\\bigl(M'_n(x) \\cdot x^{-nW}, v_{0, n}(x) \\bigr) = \\nonumber \\\\\n      &= \\sum_{n=0}^{N-1} \\SCRC\\bigl(M'_n(x), v_{0, n}(x) \\bigr) \\cdot x^{-nW} = \\nonumber \\\\\n      &= \\sum_{n=0}^{N-1} v_{K, n}(x) \\cdot x^{-nW}. \\label{e:multiwordcrc1}\n  \\end{align}\n\nEven though this step is performed only once per input message, it still\nrequires $(N-1)$ non-trivial multiplications modulo $P(x)$ negatively\naffecting the performance on small input messages. Also,\n(\\ref{e:multiwordcrc1}) uses the multiplicative inverse of $x^{nW}$ modulo\n$P(x)$ which does not exists when $P(x) \\bmod x = 0$.\n\nThere is more efficient and elegant solution. Assume that $M(x)$ is\nfollowed by one more group $g_K(x)$. Then\n  \\begin{align}\n    & \\SCRC\\bigl(M(x) \\cdot x^{NW} + g_K(x), v(x)\\bigr) = \\nonumber \\\\\n    & = \\SCRC\\Bigl(g_K(x), \\SCRC\\bigl(M(x), v(x)\\bigr)\\Bigr) = \\nonumber \\\\\n    & = \\Bigl(\\SCRC\\bigl(M(x), v(x)\\bigr) \\cdot x^{NW} + g_K(x) \\cdot x^D \\Bigr) \\bmod P(x) = \\nonumber \\\\\n    & = \\left(x^{NW} \\sum_{n=0}^{N-1} v_{K, n}(x) \\cdot x^{-nW} + x^D \\sum_{n=0}^{N-1} m_{K, n}(x) \\cdot x^{(N-1-n)W} \\right) \\bmod P(x) = \\nonumber \\\\\n    & = \\left(x^{W} \\sum_{n=0}^{N-1} v_{K, n}(x) \\cdot x^{(N-1-n)W} + x^D \\sum_{n=0}^{N-1} m_{K, n}(x) \\cdot x^{(N-1-n)W} \\right) \\bmod P(x) \\nonumber \\\\\n    & = \\sum_{n=0}^{N-1} \\Bigl( v_{K, n}(x) \\cdot x^{W} + m_{K, n}(x) \\cdot x^D\\Bigr) \\cdot x^{(N-1-n)W} \\bmod P(x) = \\label{e:additionalmultiply} \\\\\n    & = \\sum_{n=0}^{N-1} \\SCRC\\bigl(m_{K, n}(x), v_{K, n}(x)\\bigr) \\cdot x^{(N-1-n)W} \\bmod P(x). \\label{e:additionalmultiply2}\n  \\end{align}\n\n(\\ref{e:additionalmultiply2}) may be implemented using formula\n(\\ref{e:crcwordtable}) by setting $v'_0 = 0$, and then for $n = 0, \\ldots,\nN-1$ computing\n  \\begin{align*}\n    v'_{n+1}(x)\n      &= \\Bigl(\\bigl(v'_n(x) + v_{K, n}\\bigr) \\cdot x^W + m_{K, n} \\cdot x^D\\Bigr) \\bmod P(x) \\\\\n      &= \\SCRC\\bigl(m_{K,n}, v'_n(x) + v_{K, n} \\bigr).\n  \\end{align*}\n\nAlternatively, this step may be performed using the less efficient\ntechnique described in section \\ref{s:crcbyteword}.\n\n\n% -----------------------------------------\n\\subsubsection{Efficient computation of individual CRCs} \\label{s:compute}\n\nGiven $v(x)$, $\\deg\\bigl(v(x)\\bigr) < D$ and $m(x)$, $\\deg\\bigl(m(x)\\bigr) < W$,\n\\begin{align*}\n    \\mbox{CrcWordN}\\bigl(m(x), v(x)\\bigr)\n    &= \\Bigl(v(x) \\cdot x^W + m(x) \\cdot x^D \\Bigr) \\cdot x^{(N-1)W} \\bmod P(x)\n\\end{align*}\nmay be implemented efficiently utilizing the techniques described in\nsections \\ref{s:crcbyte}, \\ref{s:crcbyteword}, and \\ref{s:crcword}. When $D\n\\leq W$,\n  \\begin{align*}\n    \\mbox{CrcWordN}\\bigl(m(x), v(x)\\bigr)\n    &= \\Bigl(v(x) \\cdot x^W + m(x) \\cdot x^D \\Bigr) \\cdot x^{(N-1)W} \\bmod P(x) = \\\\\n    &= \\Bigl(v(x) \\cdot x^{W-D} + m(x) \\Bigr) \\cdot x^{(N-1)W + D} \\bmod P(x),\n  \\end{align*}\nand may be implemented using the table-driven multiplication as described\nin (\\ref{e:crcwordtable}) except that the operand is multiplied by\n$x^{(N-1)W+D}$ instead of $x^D$. Like in (\\ref{e:crcbytetable2}), explicit\nmultiplication of $v(x)$ by $x^{W-D}$ is not required since $D$-normalized\nrepresentation of $v(x)$, viewed as a $W$-normalized representation, is\nequal to $\\left(v(x) \\cdot x^{W-D}\\right)$.\n\nUsing the same technique as in formula (\\ref{e:crcbyte}), for $D \\geq W$\nlet\n  \\begin{align*}\n    v_H(x) &= \\left\\lfloor\\frac{v(x)}{x^{D-W}}\\right\\rfloor,\n        & \\deg\\bigl(v_H(x)\\bigr) &< W, \\\\\n    v_L(x) &= v(x) \\bmod x^{D-W},\n        & \\deg\\bigl(v_L(x)\\bigr) &< D-W,\n  \\end{align*}\nso that $v(x) = v_L(x) + v_H(x) \\cdot x^{D-W}$. Then,\n  \\begin{align}\n    & \\mbox{CrcWordN}\\bigl(m(x), v(x)\\bigr) = \\nonumber \\\\\n    & = \\Bigl(v(x) \\cdot x^W + m(x) \\cdot x^D \\Bigr) \\cdot x^{(N-1)W} \\bmod P(x) = \\nonumber \\\\\n    & = \\Bigl(\\bigl(v_L(x) + v_H(x) \\cdot x^{D-W}\\bigr) \\cdot x^W + m(x) \\cdot x^D \\Bigr) \\cdot x^{(N-1)W} \\bmod P(x) = \\nonumber \\\\\n    & = \\Bigl(v_L(x) \\cdot x^W + \\bigl(v_H(x) + m(x)\\bigr) \\cdot x^D \\Bigr) \\cdot x^{(N-1)W} \\bmod P(x) = \\nonumber \\\\\n    & = \\Bigl(\\bigl(v_H(x) + m(x)\\bigr) \\cdot x^{(N-1)W + D} \\bmod P(x)\\Bigr) + \\nonumber \\\\\n    &   + \\Bigl(\\bigl(v_L(x) \\cdot x^W \\bigr) \\cdot x^{(N-1)W} \\bmod P(x)\\Bigr). \\label{e:crcwordinterleaved}\n  \\end{align}\n\nSince $\\deg\\bigl(v_H(x)+m(x)\\bigr) < W$, the first summand of\n  $\\mbox{CrcWordN}\\bigl(m(x), v(x)\\bigr)$,\n\\begin{align*}\n  \\Bigl(\\bigl(v_H(x) + m(x)\\bigr) \\cdot x^{(N-1)W + D} \\bmod P(x)\\Bigr),\n\\end{align*}\nmay be computed using the table-driven multiplication technique described\nin (\\ref{e:crcwordtable}) except that the operand is multiplied by\n$x^{D+(N-1)W}$ instead of $x^D$.\n\nComputation of the second summand of $\\mbox{CrcWordN}\\bigl(m(x), v(x)\\bigr)$,\n  \\begin{align*}\n    \\Bigl(\\bigl(v_L(x) \\cdot x^W \\bigr) \\cdot x^{(N-1)W} \\bmod P(x)\\Bigr),\n  \\end{align*}\nis somewhat less intuitive. Since $\\deg\\bigl(v_L(x)\\bigr) < D-W$,\n  \\begin{align*}\n    \\left(v_L(x) \\cdot x^W\\right) \\bmod P(x) = \\left(v_L(x) \\cdot x^W\\right),\n  \\end{align*}\nand may be computed by shifting $v_L(x)$ by $W$ bits. Additional\nmultiplication by $x^{(N-1)W}$ is accomplished by adding $\\bigl(v_L(x)\n\\cdot x^W\\bigr)$, produced at step $n < N-1$ of the algorithm described by\nformula (\\ref{e:crcwordn}), to the value of $v_{k, n+1}(x)$ which will be\nadditionally multiplied by $x^{(N-1)W}$ as shown in formula\n(\\ref{e:crcwordnmultiply}).\n\nFor $n=N-1$, the value of $\\bigl(v_L(x) \\cdot x^W\\bigr)$ should be added to\nthe value of $v_{k+1, n'}(x)$ where $n' = 0$. For $k < K$, it will be\nmultiplied by $x^{(N-1)W}$ during next round of parallel computation as\nshown in (\\ref{e:crcwordnmultiply}). For $k = K$, $v_{k+1, n'}(x)$ will be\nmultiplied by $x^{(N-1)W}$ during CRC concatenation as shown in\n(\\ref{e:additionalmultiply}) since $n'=0$.\n\n\\begin{figure}\n\\begin{lstlisting}[caption={Interleaved, word by word CRC computation},label={l:CrcMultiword}]\nCrc CrcInterleavedWordByWord(\n    Word *data, int blocks, Crc v, Crc u) {\n  Crc crc[N+1] = {0};\n  crc[0] = v ^ u;\n  for (int i = 0; i < N*(blocks - 1); i += N) {\n    Word buffer[N];\n    // Load next N words and move overflow\n    // bits into \"next\" word.\n    for (int n = 0; n < N; ++n) {\n      buffer[N] = crc[n] ^ data[i + n];\n      if (D > sizeof(Word) * 8)\n        crc[n+1] ^= crc[n] >> (sizeof(Word) * 8);\n      crc[n] = 0;\n    }\n    // Compute interleaved word-by-word CRC.\n    for (int byte = 0; byte < sizeof(Word); ++byte) {\n      for (int n = 0; n < N; ++n) {\n        crc[n] ^=\n            MulInterleavedWordByXpowD[byte][(Byte) buffer[n]];\n        buffer[n] >>= 8;\n      }\n    }\n    // Combine crc[0] with delayed overflow bits.\n    crc[0] ^= crc[N];\n    crc[N] = 0;\n  }\n  // Process the last N bytes and combine CRCs.\n  for (int n = 0; n < N; ++n) {\n    if (n != 0) crc[0] ^= crc[n];\n    Crc WordCrc = CrcOfWord(crc[0] ^ data[i + n]);\n    if (D > sizeof(Word) * 8) {\n      crc[0] >>= D - sizeof(Word) * 8;\n      crc[0] ^= WordCrc;\n    } else {\n      crc[0] = WordCrc;\n    }\n  }\n  return (crc[0] ^ u);\n}\nvoid InitInterleavedWordTables(void) {\n  for (int byte = 0; byte < sizeof(Word); ++byte) {\n    Crc m = XpowN(D - 8 + N*sizeof(Word)*8 - 8*byte);\n    for (int i = 0; i < 256; ++i) {\n      MulInterleavedWordByXpowD[byte][i] =\n          MultiplyUnnormalized(i, 8, m);\n    }\n  }\n}\n\\end{lstlisting}\n\\end{figure}\n\n\n% -----------------------------------------\n\\section{Experimental results}\n\nThe tests were performed using Intel Q9650 3.0GHz CPU, DDR2-800 memory with\n4-4-4-12 timing, and a motherboard with an Intel P45 chipset.\n\n\n% -----------------------------------------\n\\subsection{Testing methology}\n\nAll tests were performed using random input data over various block sizes.\nThe code for all evaluated algorithms was heavily optimized. Tests were\nperformed on both aligned and non-aligned input data to ensure that\nmisaligned inputs do not carry performance penalty. CRC tables were aligned\non 256-byte boundary.\n\nTests were performed with warm data and warm CRC tables: as shown in\n\\cite{Kounavis2005\\remove{, DBLP:conf/iscc/KounavisB05,\nDBLP:journals/tc/KounavisB08}}, the footprint of CRC tables -- as long as\nthey fit into L1 cache -- is not a major contributor to the performance.\n\nPerformance was measured in number of CPU cycles per byte of input data:\napparently, performance of CRC computation is bounded by performance of CPU\nand its L1 cache latency. Spot testing of few other Intel and AMD CPU\nmodels showed little variation in performance measured in CPU cycles per\nbyte despite substential differences in CPU clock frequencies.\n\nTo minimize performance variations caused by interference with OS and other\napplications (context switches, CPU migrations, CPU cache flushes, memory\nbus interference from other processes, etc.), the test applications were\nrun at high priority, each test was executed multiple times, and the\nminimum time was measured. That allowed the tests to achieve repeatability\nwithin $\\pm 1\\%$.\n\n\n% -----------------------------------------\n\\subsection{Compiler comparison}\n\nDespite CRC code being rather straightforward, there were surprises (see\ntables \\ref{t:CompilerComparison128} and \\ref{t:CompilerComparison64}).\n\nOn 64-bit AMD64 platform, Microsoft CL compiler (version 15.00.30729)\nconsistently and noticeably generated the fastest code using\ngeneral-purpose integer arithmetics (64-bit and smaller CRCs) -- 1.23 times\nfaster than the code generated by Intel's ICL 11.10.051 and 1.49 times\nfaster than the code generated by GCC 4.5.0. A tuned, hand-written inline\nassembler code for CRC-32 and CRC-64 for GCC was as fast as the code\ngenerated by CL.\n\nWhen it comes to arithmetics with the use of SSE2 intrinsic functions on\n64-bit AMD64 platform for 128-bit CRC, the code generated by GCC 4.5.0\nconsistenly outperformed the code generated by Microsoft and Intel\ncompilers -- by a factor of 1.21 and 1.33 respectively. However, earlier\nversions of GCC did not produce efficient SSE2 code either. For that\nreason, pre-4.5.0 versions of GCC use hand-written inline assember code\nwhich was as fast as the code generated by GCC 4.5.0.\n\nNeither compiler was able to generate efficient code on 32-bit bit I386\nplatform. Performance of the code that used MMX intrinsic functions was\nbetter but still not as good as hand-written assember, which was provided\nfor all compilers.\n\nThe fastest code for 128-bit CRC on I386 platform was generated by GCC\n4.5.0.\n\n\n% -----------------------------------------\n\\subsection{Choice of interleave level}\n\nNumber of data streams processed by interleaved, word-by-word CRC\ncomputation described in section \\ref{s:multiword} should matter. Too few\nmeans underutilization of available ALUs. Too many will increase the length\nof the main loop and stress instruction decoders, and may cause splilling\nof registers containing hot data (interleaved processing of $N$ words of\ndata uses at least $(2N+2)$ registers).\n\nAs table \\ref{t:MultiwordPerfByStripe} shows, the optimal number of\ninterleaved data streams on modern Intel and AMD CPUs for integer\narithmetics is either 3 or 4 (likely because they all have exactly 3 ALUs).\nHowever, for SSE2 arithmetics on AMD64 platform the optimal number of\nstreams is 6 (3 on I386), which is quite counter-intuitive result as it does\nnot correlate with the number of available ALUs. Good old performance\nmantra \"you need to measure\" still applies.\n\n\n% -----------------------------------------\n\\subsection{Performance of CRC algorithms}\n\nAverage performance of best variants of CRC algorithms for 64-bit AMD64 and\n32-bit I386 platforms processing 1KB, 2KB, \\ldots, 1MB inputs is given in\ntables \\ref{t:AveragePerformance64} and \\ref{t:AveragePerformance64}\nrespectively. Proposed interleaved multiword CRC algorithm is 1.7-2.0 times\nfaster that current state of the art ``slicing''.\n\nAs demonstrated in tables \\ref{t:CRC64Perf} and \\ref{t:CRC32Perf},\ninterleaved word-by-word CRC described in section \\ref{s:multiword},\nrunning at 1.2 CPU cycles/byte, is 1.8 times faster than 2.1 CPU\ncycles/byte achieved by current state of the art word-by-word CRC algorithm\n(``slicing\") described in \\cite{Kounavis2005\\remove{,\nDBLP:conf/iscc/KounavisB05, DBLP:journals/tc/KounavisB08}}.\n\nOn 64-bit AMD64 platform, the best performance was achieved using 64-bit\nreads and 64-bit tables for all variants of $N$-bit CRC for $N \\leq 64$. In\nparticular, tables \\ref{t:CRC64Perf} and \\ref{t:CRC32Perf} clearly show\nthat performance of 32-bit and 64-bit CRCs is nearly identical.\nConsequently, there is no reason to favor CRC-32 over CRC-64 for\nperformance reasons.\n\nThe use of MMX on the 32-bit I386 platform allowed to utilize 64-bit tables\nand 64-bit reads achieving 1.3 CPU cyles/byte. Neither compiler generated\nefficient code using MMX intrinsic functions, so inline assembler was used.\n\nWith the use of SSE2 intrinsics on AMD64 architecture, 128-bit CRC may be\ncomputed takes at 1.7 CPU cycles/byte using the new algorithm (see\ntable \\ref{t:CRC128PerfMultiword}), compared with 2.9 CPU cycles/byte\nachieved by word-by-word CRC computation (see table\n\\ref{t:CRC128PerfSlicing}). On the 32-bit I386 architecture, the use of SSE2\nintrinsics and GCC 4.5.0 allowed the computation of 128-bit CRC at 2.1 CPU\ncycles/byte, compared with 4.2 CPU cycles/byte delivered by\nword-by-word algorithm.\n\nGiven that MD5 computation takes 6.8-7.1 CPU cycles/byte and SHA-1 takes\n7.6-7.9 CPU cycles per byte, CRCs are still the algorithm of choice for\ndata corruption detection.\n\n\n\n% -----------------------------------------\n\\bibliographystyle{alpha}\n\\bibliography{crc}\n\n% -----------------------------------------\n\\appendix\n\\cleardoublepage\n\n\n\n% -----------------------------------------\n\\begin{table}\n\\begin{center}\n\n\\caption{CRC performance, AMD64 platform} \\label{t:AveragePerformance64}\n\\begin{tabular}{| l | c | c | c |}\n  \\hline\nMethod               & Slicing$^1$ & Multiword$^2$ & Improvement \\\\\n  \\hline\n              CRC-32 &  $2.08^3$   &  $1.16^{4,5}$ & 1.79    \\\\\n              CRC-64 &  $2.09^3$   &  $1.16^{4,5}$ & 1.79    \\\\\n             CRC-128 &  $2.91^4$   &  $1.68^{4,6}$ & 1.73    \\\\\n  \\hline\n\\end{tabular}\n{}\n\n\\caption{CRC performance, I386 platform} \\label{t:AveragePerformance32}\n\\begin{tabular}{| l | c | c | c |}\n  \\hline\nMethod               & Slicing$^1$ & Multiword$^2$ & Improvement \\\\\n  \\hline\n              CRC-32 &  $2.52^3$   &  $1.29^{3,7}$ & 1.96   \\\\\n              CRC-64 &  $3.28^3$   &  $1.29^{3,7}$ & 2.55   \\\\\n             CRC-128 &  $4.17^4$   &  $2.10^{4,8}$ & 1.98   \\\\\n  \\hline\n\\end{tabular}\n{}\n\\end{center}\n\n\n\nThe best average number of CPU cycles per byte processing 1KB-1MB inputs.\nWarm data, warm tables.\n\n$^1$ {\\it``Slicing\"} implements the algorithm described in section\n\\ref{s:crcword}.\n\n$^2$ {\\it``Multiword/$N$\"} implements algorithm described in section\n\\ref{s:multiword} processing $N$ data streams in parallel in interleaved\nmanner.\n\n$^3$ Microsoft CL 15.00.30729 compiler, ``-O2\" flag.\n\n$^4$ GCC 4.5.0 compiler, ``-O3\" flag.\n\n$^5$ Multiword/$N=4$, hand-written inline assembler.\n\n$^6$ Multiword/$N=6$, C++.\n\n$^7$ Multiword/$N=4$, hand-written MMX inline assember.\n\n$^8$ Multiword/$N=3$, C++.\n\n\\end{table}\n\n\n\n% --------------------------------------\n\\begin{table}\n\\begin{center}\n\\caption{Interleaved multiword CRC: choosing the number of stripes $N$}\n\n\\label{t:MultiwordPerfByStripe}\n\\begin{tabular}{| l | l | c | c | c | c | c | c | c |}\n  \\hline\n    CRC             & Platform & N=2   & N=3   & N=4   & N=5   & N=6   & N=7   & N=8      \\\\\n  \\hline\n            CRC-64$^9$ & AMD64 &  1.42 &  1.23 &  {\\bf 1.17} &  1.46 &  2.08 &  2.59 &  2.73    \\\\\n        CRC-128$^{10}$ & AMD64 &  2.07 &  1.84 &  1.76 &  1.70 &  {\\bf 1.68} &  1.75 &  1.79    \\\\\n        CRC-128$^{10}$ &  I386 &  2.56 &  {\\bf 2.10} &  2.46 &  2.61 &  2.52 &  2.62 &  2.57    \\\\\n  \\hline\n\\end{tabular}\n\\end{center}\n{}\n\nAverage number of CPU cycles per byte processing 1KB, 2KB, \\ldots, 1MB\ninputs. Interleaved word-by-word CRC computation as described in section\n\\ref{s:multiword}. Warm data, warm tables.\n\n$^9$ Microsoft CL 15.00.30729 compiler, AMD64 platform, C++ code.\n\n$^{10}$ GCC 4.5.0 compiler, AMD64 platform, C++ code.\n\n\\end{table}\n\n\n\n% -----------------------------------------\n\\begin{table}\n\\begin{center}\n\n\\caption{Compiler comparison: Multiword/N, 64-bit CRC} \\label{t:CompilerComparison64}\n\\begin{tabular}{| l | c | c | c | c | c | c | c | c | c |}\n  \\hline\nInput size        & N & 64   & 256   & 1K    & 4K    & 16K   & 64K   & 256K  & 1M       \\\\\n  \\hline\n          GCC/C++ & 3 & 2.11 &  1.84 &  1.76 &  1.74 &  1.75 &  1.75 &  1.75 &  1.76    \\\\\n              ICL & 3 & 2.35 &  1.65 &  1.48 &  1.44 &  1.44 &  1.45 &  1.45 &  1.45    \\\\\n               CL & 4 & 1.75 &  1.29 &  1.18 &  1.15 &  1.17 &  1.18 &  1.18 &  1.18    \\\\\n          GCC/ASM & 4 & 1.65 &  1.26 &  1.17 &  1.15 &  1.16 &  1.17 &  1.17 &  1.17    \\\\\n  \\hline\n\\end{tabular}\n{}\n\n\\caption{Compiler comparison: Multiword/N, 128-bit CRC} \\label{t:CompilerComparison128}\n\\begin{tabular}{| l | c | c | c | c | c | c | c | c | c |}\n  \\hline\nInput size       & N & 64    & 256   & 1K    & 4K    & 16K   & 64K   & 256K  & 1M       \\\\\n  \\hline\n              CL & 5 &  4.08 &  2.56 &  2.43 &  2.25 &  2.20 &  2.19 &  2.18 &  2.20    \\\\\n             ICL & 5 &  3.52 &  2.33 &  2.23 &  2.05 &  2.00 &  1.99 &  1.99 &  2.01    \\\\\n             GCC & 6 &  2.90 &  1.93 &  1.85 &  1.72 &  1.65 &  1.63 &  1.63 &  1.63    \\\\\n  \\hline\n\\end{tabular}\n{}\n\\end{center}\n\nNumber of CPU cycles per byte, best code for given compiler and CRC.\n\n64-bit CRC (CRC-64-ECMA-182 polynomial) and 128-bit CRC (CRC-128/IEEE\npolynomial) respectively. 64-bit platform, 64-bit reads. Warm data, warm\ntables.\n\nMicrosoft CL 15.00.30729 compiler was used with ``-O2\" flag. Intel ICL\n11.10.051 and GCC 4.5.0 were used with ``-O3\" flag.\n\n\\begin{center}\n\\includegraphics[trim=14.25mm 50mm 16.75mm 50mm, width=0.99\\textwidth]{CompilerComparison.pdf} \\label{f:CompilerComparison}\n\\end{center}\n\n{\\it``Multiword/$N$\"} implements algorithm described in section\n\\ref{s:multiword} processing $N$ data streams in parallel in interleaved\nmanner.\n\n\n\\end{table}\n\n\n% --------------------------------------\n\\begin{table}\n\\begin{center}\n\n\\caption{CRC-32 performance} \\label{t:CRC32Perf}\n\\begin{tabular}{| l | c | c | c | c | c | c | c | c |}\n  \\hline\nInput size           & 64    & 256   & 1K    & 4K    & 16K   & 64K   & 256K  & 1M       \\\\\n  \\hline\n             Sarwate &  6.61 &  6.62 &  6.70 &  6.68 &  6.67 &  6.66 &  6.67 &  6.75    \\\\\n               Black &  5.44 &  5.46 &  5.47 &  5.48 &  5.47 &  5.46 &  5.47 &  5.53    \\\\\n             Slicing &  2.15 &  2.10 &  2.09 &  2.09 &  2.08 &  2.08 &  2.08 &  2.10    \\\\\n         Blockword/3 &  2.27 &  2.14 &  2.15 &  2.13 &  2.13 &  1.55 &  1.39 &  1.31    \\\\\n         Multiword/4 &  1.75 &  1.29 &  1.18 &  1.16 &  1.17 &  1.18 &  1.18 &  1.18    \\\\\n  \\hline\n\\end{tabular}\n\\end{center}\n\nNumber of CPU cycles per byte. 32-bit CRC (CRC-32C polynomial), 64-bit\nplatform, 64-bit tables, 64-bit reads (except Sarwate). Microsoft CL\n15.00.30729 compiler. Warm data, warm tables.\n\n\\begin{center}\n\\includegraphics[trim=14.25mm 50mm 16.75mm 50mm, width=0.99\\textwidth]{CRC32-full.pdf} \\label{f:CRC32Perf}\n\\end{center}\n\n{\\it``Sarwate\"} implements the algorithm described in section\n\\ref{s:crcbyte}.\n\n{\\it``Black\"} implements the algorithm described in section\n\\ref{s:crcbyteword}.\n\n{\\it``Slicing\"} implements the algorithm described in section\n\\ref{s:crcword}.\n\n{\\it``Blockword/3\"} implements the algorithm described in section\n\\ref{s:blockword} with 3 stripes of 15,376 bytes each.\n\n{\\it``Multiword/4\"} implements the algorithm described in section\n\\ref{s:multiword} processing 4 data streams in parallel in interleaved\nmanner.\n\n\n\\end{table}\n\n\n% --------------------------------------\n\\begin{table}\n\\begin{center}\n\n\\caption{CRC-64 performance} \\label{t:CRC64Perf}\n\\begin{tabular}{| l | c | c | c | c | c | c | c | c |}\n  \\hline\nInput size           & 64    & 256   & 1K    & 4K    & 16K   & 64K   & 256K  & 1M       \\\\\n  \\hline\n             Sarwate &  6.61 &  6.62 &  6.70 &  6.68 &  6.67 &  6.65 &  6.66 &  6.75    \\\\\n               Black &  5.44 &  5.46 &  5.47 &  5.47 &  5.47 &  5.47 &  5.47 &  5.53    \\\\\n             Slicing &  2.16 &  2.08 &  2.09 &  2.10 &  2.08 &  2.08 &  2.08 &  2.09    \\\\\n         Blockword/3 &  2.27 &  2.14 &  2.15 &  2.13 &  2.13 &  1.59 &  1.41 &  1.33    \\\\\n         Multiword/4 &  1.75 &  1.29 &  1.18 &  1.15 &  1.17 &  1.18 &  1.18 &  1.18    \\\\\n  \\hline\n\\end{tabular}\n\\end{center}\n\nNumber of CPU cycles per byte. 64-bit CRC (CRC-64-ECMA-182 polynomial),\n64-bit platform, 64-bit tables, 64-bit reads (except Sarwate). Microsoft CL\n15.00.30729 compiler. Warm data, warm tables.\n\n\\begin{center}\n\\includegraphics[trim=14.25mm 50mm 16.75mm 50mm, width=0.99\\textwidth]{CRC64-small.pdf} \\label{f:CRC64Perf}\n\\end{center}\n\n{\\it``Sarwate\"} implements the algorithm described in section\n\\ref{s:crcbyte}.\n\n{\\it``Black\"} implements the algorithm described in section\n\\ref{s:crcbyteword}.\n\n{\\it``Slicing\"} implements the algorithm described in section\n\\ref{s:crcword}.\n\n{\\it``Blockword/3\"} implements the algorithm described in section\n\\ref{s:blockword} with 3 stripes of 15,376 bytes each.\n\n{\\it``Multiword/4\"} implements the algorithm described in section\n\\ref{s:multiword} processing 4 data streams in parallel in interleaved\nmanner.\n\n\n\\end{table}\n\n% --------------------------------------\n\\begin{table}\n\\begin{center}\n\n\n\\caption{CRC-128 performance: Slicing CRC} \\label{t:CRC128PerfSlicing}\n\\begin{tabular}{| l | c | c | c | c | c | c | c | c |}\n  \\hline\nInput size   & 64    & 256   & 1K    & 4K    & 16K   & 64K   & 256K  & 1M       \\\\\n  \\hline\n     CL/SSE2 &  4.02 &  3.81 &  4.01 &  4.05 &  4.13 &  4.18 &  4.20 &  4.24    \\\\\n    ICL/SSE2 &  3.40 &  3.24 &  3.57 &  3.59 &  3.68 &  3.72 &  3.75 &  3.81    \\\\\n    GCC/UINT &  3.45 &  3.24 &  3.36 &  3.48 &  3.61 &  3.64 &  3.67 &  3.72    \\\\\n    GCC/SSE2 &  2.67 &  2.48 &  2.63 &  2.79 &  2.97 &  2.99 &  2.99 &  3.03    \\\\\n  \\hline\n\\end{tabular}\n\n\n\\caption{CRC-128 performance: Multiword CRC} \\label{t:CRC128PerfMultiword}\n\\begin{tabular}{| l | c | c | c | c | c | c | c | c |}\n  \\hline\nInput size & 64    & 256   & 1K    & 4K    & 16K   & 64K   & 256K  & 1M       \\\\\n  \\hline\nGCC/UINT/3 &  3.83 &  3.02 &  3.04 &  3.01 &  3.00 &  2.98 &  2.98 &  3.00    \\\\\n CL/SSE2/5 &  4.08 &  2.56 &  2.43 &  2.25 &  2.20 &  2.19 &  2.18 &  2.20    \\\\\nICL/SSE2/5 &  3.52 &  2.33 &  2.23 &  2.05 &  2.00 &  1.99 &  1.99 &  2.01    \\\\\nGCC/SSE2/6 &  2.90 &  1.93 &  1.85 &  1.72 &  1.65 &  1.63 &  1.63 &  1.63    \\\\\n  \\hline\n\\end{tabular}\n\\end{center}\n\nNumber of CPU cycles per byte. 128-bit CRC (CRC-128/IEEE polynomial),\n64-bit platform, 128-bit tables, 64-bit reads. Warm data, warm tables.\n\nAll compilers were tested using SSE2 intrinsics (/SSE2 variants). GCC was\nalso tested using 128-bit integers provided by the compiler (GCC/UINT).\n\n\\begin{center}\n\\includegraphics[trim=14.25mm 50mm 16.75mm 50mm, width=0.99\\textwidth]{CRC128-full.pdf} \\label{f:CRC128Perf}\n\\end{center}\n\n{\\it``Slicing\"} implements algorithm described in section \\ref{s:crcword}.\n\n{\\it``Multiword/$N$\"} implements algorithm described in section\n\\ref{s:multiword} processing $N$ data streams in parallel in interleaved\nmanner. The optimal (for given compiler) value of $N$ was used.\n\n\\end{table}\n\n\\end{document}\n", "meta": {"hexsha": "96becb9ca9c4ba5768f5c27610a0645f50d57715", "size": 60372, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/text/crc.tex", "max_stars_repo_name": "koolhazz/crcutil", "max_stars_repo_head_hexsha": "b560cd2cbcc8e3cea01f2e545411c1bf1626cb55", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-05-23T22:38:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T09:10:42.000Z", "max_issues_repo_path": "doc/text/crc.tex", "max_issues_repo_name": "koolhazz/crcutil", "max_issues_repo_head_hexsha": "b560cd2cbcc8e3cea01f2e545411c1bf1626cb55", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-21T01:05:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-21T01:05:10.000Z", "max_forks_repo_path": "doc/text/crc.tex", "max_forks_repo_name": "koolhazz/crcutil", "max_forks_repo_head_hexsha": "b560cd2cbcc8e3cea01f2e545411c1bf1626cb55", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-01-05T13:35:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-24T06:44:33.000Z", "avg_line_length": 39.8758256275, "max_line_length": 153, "alphanum_fraction": 0.6288179951, "num_tokens": 21375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.32378165597412156}}
{"text": "% LaTeX2e Template by Stephen Iota (https://stepheniota.com/)\n% last updated: Jan. 2019\n\n% for papers\n%\\documentclass[aps,onecolumn,superscriptaddress]{revtex4-1}\n% https://www-d0.fnal.gov/Run2Physics/WWW/templates/revtex4.pdf\n% https://cdn.journals.aps.org/files/revtex/auguide4-1.pdf\n% for revTeX4-1 class options\n\n% for other\n\\documentclass[12pt]{article}\n\\usepackage[margin=2cm]{geometry}\n\n%%%%%%%%%%%%%%%%\n%%% Packages %%%\n%%%%%%%%%%%%%%%%\n\n\\usepackage[utf8]{inputenc}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{amsfonts} % to remove math font when typesetting equations\n\\usepackage[thinc]{esdiff} \n\\usepackage{graphicx}\n\\usepackage[shortlabels]{enumitem} % to change labels in enum/item\n\\usepackage[dvipsnames]{xcolor} % for colored links\n\n% always put this at the end\n\\usepackage[\n\tcolorlinks=true,\n\tcitecolor=green!50!black,\n\tlinkcolor=NavyBlue!75!black,\n\turlcolor=green!50!black,\n\thypertexnames=false]{hyperref} \n\n \n %%%%%%%%%%%%%%%%%%\n %% New Commands %%\n %%%%%%%%%%%%%%%%%%\n \n\\newcommand{\\email}[1]{\\texttt{\\href{mailto:#1}{#1}}}\n\n\\newcommand{\\hint}[1]{\\color{Blue}{#1}}\n \n%----------------------------------------------------\n%%%%%%%%%%%%%%%%%%\n%% Front Matter %%\n%%%%%%%%%%%%%%%%%%\n\n\\pagenumbering{gobble} % no page numbers\n\\graphicspath{{figures/}} % set directory for figures\n%\\usepackage{wrapfig}\n\\setcounter{section}{-1} % start with section 0\n\n%%%%%%%%%%%%%\n%%% Title %%%\n%%%%%%%%%%%%%\n\\begin{document}\n\n\\begin{center}\n\n\\Large{\\textsc{Problem Set 2}: \\textbf{Acceleration}}\n\n\\end{center}\n\n\\vspace{.5mm}\n\n\n%%%%%%%%%%\n%% INFO %%\n%%%%%%%%%%\n\n\\begin{tabular}{rl}\n\\textsc{SI Leader}:\n&\nStephen Iota (\\email{siota001@ucr.edu})\n\\\\\n\\textsc{Course}:\n&\nPhysics 40A (Winter 2019), Prof.~John Ellison\n\\\\\n\\textsc{Date}:\n&\n14 -- 16 January 2019\n\\end{tabular}\n\n%%%%%%%%%%%%%%\n%% PROBLEMS %%\n%%%%%%%%%%%%%%\n\n\n\\section{Quiz}\n\n\\subsection{Monday}\n\\begin{enumerate}[(a)]\n\t\\item What is the acceleration of free fall objects close to the earth's surface?\n\t\\vspace{-1mm}\n\t\\item You throw a rock straight down at the water from a bridge. It takes you 1.5 s to accelerate the rock to 25 m/s from rest, then it takes the rock 6 s to reach the water. Sketch a plot of the acceleration v time graph\n\t\\vspace{-1mm}\n\t\\item You are riding a bicycle heading due east. Can your acceleration vector ever point west? Explain why or why not.\n\t\\vspace{-1mm}\n\\end{enumerate}\n\n\n\\subsection{Wednesday}\n\n\\begin{enumerate}[(a)]\n\t\\item A hockey puck is traveling on a frictionless surface in the North-East direction. Assume the x-axis is pointing North. It's velocity is $v_0$. Write down it's velocity in component form.\n\t\\vspace{-1mm}\n\t\\item A car's velocity is given by the following function\n\t \t\t$$ v(t) = x^2 + 3 $$\n          Find the car's average velocity after 5 seconds.  \n          \n\\end{enumerate}\n\n\n\\section{Rocket Launch}\n\nA rocket is launched straight up with constant acceleration. Four seconds after liftoff, a bolt falls off the side of the rocket. The bolt hits the ground 6.0 s later. \nWhat was the rocket's acceleration?\n\n\\section{Water Drops}\n\nWater drops fall from the edge of a roof at a steady rate. A fifth drop starts to fall just as the first drop hits the ground. At this instant, the second and third drops are exactly at the bottom and top edges of a 1.00 m tall window. How high is the edge of the roof?\n\n\n\\section{Olympic Sprinters}\n\nA quite realistic model of Olympic sprinter's velocity in the 100 meter dash is given by \n$$ v_x = b(1-e^{-ct}) $$\nwhere $b$ and $c$ are constants characteristic of the sprinter. We model Usain Bolt with $b$ = 11 m/s and $c$ = .6 s$^{-1}$.\n\n\\begin{enumerate}[(a)]\n\t\\item What was Bolt's acceleration at $t$ = 0 s, 2 s, and 4 s?\n\t\\vspace{-1mm}\n\t\\item Find the expression for the distance traveled at time $t$.\n\t\\vspace{-1mm}\n\t\\item Your expression from part b is a transcendental equation, meaning you can't solve for $t$. However, it's not hard to use trial and error to find time needed to travel a specific distance. To the nearest 0.01 s, find the time Bolt needed to sprint 100.0 m. \n\\end{enumerate}\n\n\n\\section{Challenge Problem}\n\nA rubber ball is shot straight up from the ground with speed $v_0$. Simultaneously, a second rubber ball at height $h$ directly above the first ball is dropped from rest. \n\n\\begin{enumerate}[(a)]\n\t\\item At what height above the ground do the balls collide?\n\t\\vspace{-1mm}\n\t\\item What is the max value of $h$ for which a collision occurs before the first ball falls back to the ground?\n\t\\vspace{-1mm}\n\t\\item For what value of $h$ does the collision occur at the instant when the first ball is at its highest point? \n\\end{enumerate}\n\n\n\\end{document}\n", "meta": {"hexsha": "399a8b8a89f13b005549edfec1510f0baa3feb0f", "size": 4638, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "problem-sets/P40A_W19_PS2.tex", "max_stars_repo_name": "stepheniota/physics-40a-w19", "max_stars_repo_head_hexsha": "caf0b5b049d6f8f06f66b7c12ee4fa87f1309fca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problem-sets/P40A_W19_PS2.tex", "max_issues_repo_name": "stepheniota/physics-40a-w19", "max_issues_repo_head_hexsha": "caf0b5b049d6f8f06f66b7c12ee4fa87f1309fca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problem-sets/P40A_W19_PS2.tex", "max_forks_repo_name": "stepheniota/physics-40a-w19", "max_forks_repo_head_hexsha": "caf0b5b049d6f8f06f66b7c12ee4fa87f1309fca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9225806452, "max_line_length": 269, "alphanum_fraction": 0.6901681759, "num_tokens": 1304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.32378165597412156}}
{"text": "\\documentclass[10pt,tgadventor, onlymath]{beamer}\n\n\\usepackage{graphicx,amsmath,amssymb,tikz,psfrag,neuralnetwork, stackengine,array, multirow, fontawesome}\n\n\\input defs.tex\n\\graphicspath{ {./figures/} }\n\n%% formatting\n\n\\mode<presentation>\n{\n\\usetheme{default}\n\\usecolortheme{seahorse}\n}\n\\setbeamertemplate{navigation symbols}{}\n\\usecolortheme[rgb={0.03,0.28,0.59}]{structure}\n\\setbeamertemplate{itemize subitem}{--}\n\\setbeamertemplate{frametitle} {\n\t\\begin{center}\n\t  {\\large\\bf \\insertframetitle}\n\t\\end{center}\n}\n\n\n\\usetikzlibrary{shapes,arrows}\n\\usetikzlibrary{positioning}\n\\tikzstyle{block} = [rectangle, draw, fill=blue!20, \n    text width=5em, text centered, rounded corners, minimum height=4em]\n\\tikzstyle{line} = [draw, -latex']\n\n%% begin presentation\n\n\\title{\\large \\bfseries Power Allocation in Heterogeneous Networks for Base Stations with Multiple Antennas}\n\n\\author{Peter Hartig \\\\ \\and Supervisor: Prof. Laura  Cottatellucci\n}\n\n\\date{\\today}\n\n\\begin{document}\n\n\\frame{\n\\thispagestyle{empty}\n\\titlepage\n}\n\n\\section{Project Goals}\n\n\\begin{frame}\n\\frametitle{Objectives}\n\\begin{enumerate}\n\\setlength\\itemsep{2em}\n\\item Find a Nash Equilibrium between all players.\n\\begin{itemize}\n\\item Preferably a \"social optimal\" Nash Equilibrium.\n\\end{itemize}\n\\item Minimize the resources required to reach Nash Equilibrium.\n\\end{enumerate}\n%\\pause\n\\begin{center}\n\t\t\\includegraphics[scale=.2]{het_net}\n\\end{center}\n\\end{frame}\n\\begin{frame}\n\\frametitle{Key Tools}\n\\begin{enumerate}\n\\setlength\\itemsep{2em}\n\n\\item \nPotential Games \n\\begin{itemize}\n\\item\nGames with many players becomes a central optimization problem\n\\end{itemize}\n\\item \nN-Person Concave Games\n\\begin{itemize}\n\\item\nEnsures solution is optimal\n\\item\nSolve the game using convex optimization\n\\end{itemize}\n\\item \nDistributed Optimization\n\\begin{itemize}\n\\item\nReducing the network overhead needed to reach a solution\n\\end{itemize}\n\\end{enumerate}\n\\end{frame}\n\n\\begin{frame}\n  \\centering \\Large\n  \\emph{Thank You.}\n  \\\\\n\t\\bigskip\n    \\centering \\Large\n  \\emph{Questions or Comments?}\n\\end{frame}\n\n\\end{document}\n", "meta": {"hexsha": "a31d1b634f801f99a6368838b6d879661d91539f", "size": 2075, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "documentation/presentations/Pitch Presentation/pitch_presenation.tex", "max_stars_repo_name": "pghartig/Power-Control", "max_stars_repo_head_hexsha": "c23613b74c9fe1a1ecd6d415f5bf0cb625920661", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-04-19T01:58:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T02:24:23.000Z", "max_issues_repo_path": "documentation/presentations/Pitch Presentation/pitch_presenation.tex", "max_issues_repo_name": "pghartig/Power-Control", "max_issues_repo_head_hexsha": "c23613b74c9fe1a1ecd6d415f5bf0cb625920661", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "documentation/presentations/Pitch Presentation/pitch_presenation.tex", "max_forks_repo_name": "pghartig/Power-Control", "max_forks_repo_head_hexsha": "c23613b74c9fe1a1ecd6d415f5bf0cb625920661", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-03-21T12:34:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-15T17:23:48.000Z", "avg_line_length": 20.3431372549, "max_line_length": 108, "alphanum_fraction": 0.76, "num_tokens": 639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.32378164715189006}}
{"text": "\\begin{frame}{Two Primary Questions}\n  \\onslide<+->{Previous work focused on two primary questions.  These form the basis of this work.}\n  \\vfill\n    \\begin{itemize}[<+->]\n      \\setlength\\itemsep{15pt}\n      \\item How can we produce \\textit{strong} adversarial examples that fool the model with high confidence while requiring only a small perturbation?\n\n      \\item How can we train a model so there are no \\only<+->{(\\textit{easily found}) }adversarial examples?\n    \\end{itemize}\n  \\vfill\n  \\onslide<+->{We will tackle these two questions separately with the first one being much more interesting}\n\\end{frame}\n\n\\section{Producing Strong Adversarial Examples}\n\\transitionFrame{Producing Strong Adversarial Examples}\n\n\\begin{frame}{Adversarial Examples should be Intractable}\n\n  \\onslide<+->{\\textbf{\\green{Inner Maximization}}: Adversarial example generation problem:\n      \\begin{equation}\\label{eq:InnerMaximization}\n        \\max_{\\delta \\in \\sPerturb} \\loss (\\X + \\perturb, \\y ; \\params)\n      \\end{equation}\n\n    \\vspace{-3pt}\n    is a highly non-concave function.  Potentially large number of local maxima making this problem \\textit{seem} intractable.\n  }\n\n  \\vfill\n  \\begin{itemize}[<+->]\n    \\setlength{\\itemsep}{8pt}\n    \\item \\textbf{\\red{Previous Work}}: Fast Gradient Sign Method (FGSM)\n  \\end{itemize}\n\\end{frame}\n\n\n\\begin{frame}{Previous Work: Fast Gradient Sign Method}\n  \\onslide<+->{%\n    \\begin{definition}\n      \\textbf{\\blue{Fast Gradient Sign Method}} (FGSM) linearizes the inner maximization s.t.:\n\n      \\begin{equation}\\label{eq:FGSM}\n        \\xadv = \\X + \\varepsilon \\sgn\\left(\\nabla_{\\X} \\loss(\\X, \\y ; \\params) \\right)\n      \\end{equation}\n    \\end{definition}\n  }\n\n  \\begin{itemize}[<+->]\n    \\setlength\\itemsep{8pt}\n    \\item \\textbf{Summary}: Simple ``single-step-size'' approach\n    \\item Enhanced versions of FGSM (e.g., multi-step, randomized) that are beyond the scope of this talk\n  \\end{itemize}\n\n  \\vspace{3pt}\n  \\onslide<+->{\\textbf{\\red{Major Issue}}: FGSM provides no security guarantee}\n  \\begin{itemize}[<+->]\n    \\setlength\\itemsep{8pt}\n    \\item \\textbf{Why?} \\onslide<+->{Not selecting the \\textit{worst-case} perturbation}\n    \\item Easy to find ``nearby'' perturbations with significantly higher loss\n  \\end{itemize}\n  \\vfill\n  \\onslide<+->{\\textbf{\\madry's Solution}: \\blue{\\textbf{Projected Gradient Descent}} (PGD)}\n\\end{frame}\n\n\n\\begin{frame}{Projected Gradient Descent (PGD)}\n  \\onslide<+->{\\textbf{Question}: What is PGD?}\n\n  \\vspace{4pt}\n  \\onslide<+->{\\textbf{Answer}: Form of \\green{\\textit{constrained optimization}} where the constraint is a \\blue{\\textbf{projection}}}\n\n  \\vfill\n  \\onslide<+->{\n    \\begin{definition}\n      A \\textbf{\\blue{projection}} of a point~$z$ onto a set~$\\mathcal{X}$ is defined as:\n\n      \\[ \\Pi_{\\sPerturb}(z) = \\argmin_{s \\in \\sPerturb} \\norm{s-z}_{p}\\text{.}  \\]\n    \\end{definition}\n  }\n\n  \\vfill\n  \\begin{itemize}[<+->]\n    \\item $\\Pi_{\\sPerturb}$ is the projection operator\n  \\end{itemize}\n\\end{frame}\n\n\n\\begin{frame}{Projected Gradient Descent --- The Algorithm}\n  \\begin{columns}\n    \\begin{column}{0.5\\textwidth}\n      \\textbf{Procedure}:\n      \\begin{enumerate}[<+->]\n        \\setlength{\\itemsep}{12pt}\n        \\item For any ${\\X \\in \\mathcal{X}}$, define ${\\X^{(0)} = \\X + \\perturb}$ where ${\\perturb \\sim \\mathcal{U}\\left( \\sPerturb \\right)}$\n        \\item At each time $t$, define:\n          \\begin{equation}\\label{eq:PGD:GradUpdate}\n            z^{(t+1)} = \\X^{(t)} \\textcolor<6->{red}{-} \\alpha \\nabla_{\\X} \\loss(\\X^{(t)}, \\y) \\text{.}\n          \\end{equation}\n        \\item Enforce the constraint where:\n          \\begin{equation}\\label{eq:PGD:NextX}\n            \\X^{(t+1)} = \\Pi_{\\sPerturb}(z^{(t+1)}) \\text{.}\n          \\end{equation}\n\n        \\item Repeat steps~\\#2 and~\\#3 until convergence\n      \\end{enumerate}\n    \\end{column}\n    \\begin{column}{0.45\\textwidth}\n      \\begin{center}\n        \\onslide<+->{\\includegraphics[scale=0.65]{pgd}~\\cite{Srebro}}\n      \\end{center}\n    \\end{column}\n  \\end{columns}\n\\end{frame}\n\n\\subsection{\\texorpdfstring{$\\ell_{p}$}{Lp}-Balls}\n\n\\begin{frame}{What is our constraint set~$\\sPerturb$?}\n  \\begin{itemize}[<+->]\n    \\setlength{\\itemsep}{20pt}\n    \\item By definition, PGD requires a constraint set,~$\\sPerturb$\n\n    \\item Recall that in adversarial training,~$\\sPerturb$, is the set of allowed perturbations\n\n    \\item In this paper, $\\sPerturb$ is an $\\ell_{p}$-ball\n      \\begin{itemize}\n        \\item Let's define what those are\\ldots\n      \\end{itemize}\n  \\end{itemize}\n\\end{frame}\n\n\n\\begin{frame}{$\\ell_{p}$-Balls --- Norms First}\n  \\onslide<+->{For ${x \\in \\mathbb{R}^d}$, the $L_{p}$ norm is:}\n\n  \\onslide<+->{%\n    \\begin{equation}\\label{eq:LpNorm}\n      \\norm{x}_{p} = \\left( \\sum_{i=1} x_{i}^{p}  \\right)^{\\frac{1}{p}}\n    \\end{equation}\n  }\n\n  \\onslide<+->{$L_{\\infty}$ norm is a special case:}\n\n  \\onslide<+->{%\n    \\begin{equation}\\label{eq:LinftyNorm}\n      \\norm{x}_{\\infty} = \\sup_{i} \\abs{x_i}\n    \\end{equation}\n  }\n\n  \\onslide<+->{%\n    \\begin{center}\n      \\textbf{Note}: ``$\\sup$'' equals the ``$\\max$'' for a finite set\n    \\end{center}\n  }\n\\end{frame}\n\n\\begin{frame}{$\\ell_{p}$-Balls --- Formally}\n  \\begin{definition}\n    Given scalar ${\\varepsilon > 0}$, the $\\ell_{p}$~ball of a point ${x \\in \\mathbb{R}^{d}}$ is the set:\n\n    \\begin{equation}\\label{eq:LpBall}\n      \\ell_{p}(x) = \\setbuild{x + \\delta}{\\norm{\\delta}_{p} \\leq \\varepsilon}\\text{.}\n    \\end{equation}\n  \\end{definition}\n\n  \\begin{columns}\n    \\begin{column}{0.5\\textwidth}\n      \\onslide<2->{Let's visualize $\\ell_{p}$ for different values of $p$}\n\n      \\vspace{15pt}\n      \\onslide<4->{\\blue{\\textbf{Question}}: What is the value of $\\varepsilon$?}\n\n      \\vspace{4pt}\n      \\onslide<5->{\\textbf{Answer}: $\\varepsilon = 1$}\n\n      \\vspace{15pt}\n      \\onslide<6->{\\green{\\textbf{Key Takeaway}}: $\\ell_{\\infty}$~ball is a superset of all other $\\ell_{p}$~balls for fixed $\\varepsilon$}\n    \\end{column}\n    \\begin{column}{0.45\\textwidth}\n      \\onslide<3->{\n        \\begin{center}\n          \\includegraphics[scale=0.28]{img/lpballs.pdf}~\\cite{wiki:Lp_space}\n        \\end{center}\n      }\n    \\end{column}\n  \\end{columns}\n\\end{frame}\n\n\n\\subsection{\\texorpdfstring{$\\ell_{\\infty}$}{L-infinity}~Ball \\& PGD}\n\n\\begin{frame}{Connecting $\\ell_{\\infty}$ \\& PGD}\n  \\begin{itemize}[<+->]\n    \\setlength{\\itemsep}{20pt}\n    \\item Since ${\\forall_{p \\in \\mathbb{R}} \\hspace{3pt} \\ell_p \\subset \\ell_{\\infty}}$, providing an adversarial guarantee over $\\ell_{\\infty}$ guarantees that for any other $p$, the maximum loss will be the same or smaller.\n\n    \\item Uses complete first-order information, i.e.,~not only the gradient's information\n\n    \\item \\textbf{Summary}: Training a network robust to PGD~adversaries makes it robust against a wide range of other attacks as well\n  \\end{itemize}\n\\end{frame}\n\n\\begin{frame}{PGD \\& Adversarial Tractability}\n  \\onslide<+->{\\textbf{\\blue{Question}}: Is PGD + $\\ell_{\\infty}$\\-/balls guaranteed to eliminate \\textit{all} adversarial examples within (Minkowski) distance~$\\varepsilon$ of $\\X$?}\n\n  \\vspace{3pt}\n  \\onslide<3->{\\textbf{Answer}: No.} \\only<4-5>{Why?}\n  \\begin{itemize}\n    \\item \\onslide<5->{PGD is only a \\textbf{first-order adversary}.}\n  \\end{itemize}\n\n  \\vfill\n  \\onslide<6->{\n    \\begin{definition}\n      \\blue{\\textbf{First-order adversary}} is the strongest attack utilizing only \\textit{first-order} (e.g.,~gradient) information about network\n    \\end{definition}\n  }\n\n  \\vfill\n  \\onslide<7->{An attacker using higher order information (e.g.,~Hessian) may tractably find adversarial examples.} \\onslide<8->{They may even find them \\textit{easily}.}\n  \\begin{itemize}\n    \\item \\onslide<9->{Similar to \\textit{polynomially-bounded} adversary that is cornerstone of cryptography}\n  \\end{itemize}\n\\end{frame}\n\n\\subsection{Zero-Order Adversaries}\n\\begin{frame}{Zero-Order Adversaries}\n  \\begin{itemize}[<+->]\n    \\setlength{\\itemsep}{20pt}\n    \\item A \\blue{\\textbf{zero-order adversary}} has no direct access to the classifier and is only able to evaluate the classifier based on chosen examples\n      \\begin{itemize}\n        \\setlength{\\itemsep}{8pt}\n        \\item ``Zero-order'' means no access to ``first-order'' information\n        \\item \\textit{Translation}: \\red{No gradient feedback}\n      \\end{itemize}\n\n    \\item \\textit{Example}: Black-box attack\n\n    \\item Much more challenging that first-order attack\n  \\end{itemize}\n\\end{frame}\n", "meta": {"hexsha": "d65891752ca76117e341922b08573ae203bb6761", "size": 8430, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/produce_good_adv_examples.tex", "max_stars_repo_name": "ZaydH/towards_adversarial_robustness", "max_stars_repo_head_hexsha": "c03c7948a7b8a8efefb7f7aa1d420b05c1eaee2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/produce_good_adv_examples.tex", "max_issues_repo_name": "ZaydH/towards_adversarial_robustness", "max_issues_repo_head_hexsha": "c03c7948a7b8a8efefb7f7aa1d420b05c1eaee2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/produce_good_adv_examples.tex", "max_forks_repo_name": "ZaydH/towards_adversarial_robustness", "max_forks_repo_head_hexsha": "c03c7948a7b8a8efefb7f7aa1d420b05c1eaee2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.125, "max_line_length": 226, "alphanum_fraction": 0.6481613286, "num_tokens": 2784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.3234917883497141}}
{"text": "\\documentclass[a4paper]{article}\n\n% Language and Font Encoding\n\\usepackage[english]{babel}\n%\\usepackage[utf8x]{inputenc}\n\\usepackage[T1]{fontenc}\n\\usepackage{listings}\n\\usepackage{float}\n\\usepackage{caption}         % For captions\n\\usepackage{fancyhdr}        % For header and footer\n\\usepackage{rotating}\n\\usepackage{amssymb}\n%\\usepackage{varwidth}\n\\usepackage[colorlinks=true, allcolors=blue]{hyperref}\n\n% Page size and margins\n\\usepackage[a4paper,top=3cm,bottom=2cm,left=2cm,right=2cm,marginparwidth=1.75cm]{geometry}\n\n% Useful Packages\n\\usepackage{amsmath}\n\\usepackage{graphicx}\n\\usepackage{amsthm}\n%\\usepackage{bbm}\n\\usepackage{siunitx}\n\\usepackage{cite}\n\\DeclareMathOperator*{\\argmax}{argmax}\n\\DeclareMathOperator*{\\argmin}{argmin}\n\\DeclareMathOperator*{\\softmax}{softmax}\n\n\\newcommand{\\squeezeup}{\\vspace{-2.5mm}}\n\\newcommand{\\norm}[1]{\\left\\lVert#1\\right\\rVert}\n\n\n\\pagestyle{fancy}\n\\lhead{Optimization On Manifolds: 1}\n\\rhead{}\n\n\\begin{document}\n\n\\title{Notes: Optimization on Manifolds, Ch. 1}\n\\author{Ibrahim Akbar}\n\\maketitle\n\n%--------Introduction---------------\n\\section{Introduction}\n\n%-----------Objective---------------\n\\subsection{Objective}\n\\begin{enumerate}\n     \\item Generalize a given optimization algorithm on an abstract manifold.\n     \\item Modify the algorithm to be an efficient numberical procedure that either invalidates or justifies the 1\\textsuperscript{st} step.\n\\end{enumerate}\n\n%-----------Information------------\n\\subsection{Information}\n\\begin{itemize}\n\\item This book is about the design of numerical algorithms for computational problems on smooth search spaces.\n\\item \\textbf{Example}: The eigenvalue problem: Given a linear transformation $\\mathcal{T}:\\mathcal{U}\\rightarrow\\mathcal{U}$ with eigenvector $\\mathbf{v}$.\n\n\\begin{itemize}\n\\item Eigenvectors span an invariant subspace under the transformation $\\mathcal{T}$.\n\\item A subset, $\\mathcal{S}\\subset\\mathcal{U}$, is an invariant subset under a transformation,$A$, if $\\mathbf{x}\\in\\mathcal{S}\\Rightarrow A\\mathbf{x}\\in\\mathcal{S}$.\n\\item Thus eigenvectors are not isolated in the search space and it is preferable for computation that points are isolated in the search space. (\\textit{Definition of isolation?})\n\\item Solutions to this are to impose a norm equality constraint (\\textit{Why}?) or factor the space by a scale-invariant operator such that any subspace reduces to a point.\n\\item These produce the \\textit{embedded submanifold} and \\textit{quotient manifold}, respectively and are the proto-type structures.\n\\end{itemize}\n\n\\item Scale invariance property is one of several symmetries that may be exploited in order to reformulate the optimization problem as nondegenerative on an embedded or quotient manifold associated with the original search space.\n\\item Such sets carry the structure of nonlinear matrix manifolds and this book provides the tools to exploit such structures to develop efficient algorithms.\n\\item A challenge is that classically, optimization algorithms rely on the assumptions of a Euclidean vector space structure, but in order for these to be well-defined on a manifold this must be reformulated in the differential geometry sense.\n\\item This book makes sure to equally consider the practical implementation and the geometric formulation.\n\n\\begin{itemize}\n\\item Concepts such as \\textit{retraction} and \\textit{vector transport} aid in the formalization of concrete aspects of algorithm design. (These are relaxations of classical geometric concepts of motion along geodesics and parallel transport).\n\\end{itemize}\n\n\\item This book is an extension of Absil's PhD Thesis which relies heavily on Mahony's Thesis.\n\\end{itemize}\n\n% ----------Layout---------------\n\\subsection{Layout}\n\\begin{itemize}\n\\item \\textbf{Chapter 2}\n\n\\begin{itemize}\n\\item Detailed Discription of the invariant subspace problem.\n\\item Other applications that can be re-formulized as problems of the same nature.\n\\end{itemize}\n\n\\item \\textbf{Chapter 3}\n\n\\begin{itemize}\n\\item Riemannian Manifold\n\\item Tangent Spaces\n\\end{itemize}\n\n\\item \\textbf{Chapter 4}\n\n\\begin{itemize}\n\\item Gradient-descent line-search algorithms\n\\item Retraction\n\\end{itemize}\n\n\\item \\textbf{Chapter 5}\n\n\\begin{itemize}\n\\item Advanced material needed to define higher-order derivatives on manifolds.\n\\item Advanced material beeded to build analogous first- and second-order local models required in most optimization problem.\n\\item This book does not provide a complete introduction to classical differential geometry. (See References)\n\\end{itemize}\n\n\\item \\textbf{Chapter 6}\n\n\\begin{itemize}\n\\item Newton-based Methods\n\\end{itemize}\n\n\\item \\textbf{Chapter 7}\n\n\\begin{itemize}\n\\item Trust-region Methods\n\\end{itemize}\n\n\\item \\textbf{Chapter 8}\n\n\\begin{itemize}\n\\item Vector Transport\n\\item Survey of other superlinear methods (e.g. conjugate gradient)\n\\end{itemize}\n\n\\end{itemize}\n\\end{document}\n\n", "meta": {"hexsha": "da8dd08204132b70bff56e2855245cbc0e07f55e", "size": 4875, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "files/notes/tex/opti-manifold/opti-manifold-1.tex", "max_stars_repo_name": "ibrahimkakbar/ibrahimkakbar.github.io", "max_stars_repo_head_hexsha": "5e6b0ea67f5e5f8f3a7bb4394095ea7f7992673a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "files/notes/tex/opti-manifold/opti-manifold-1.tex", "max_issues_repo_name": "ibrahimkakbar/ibrahimkakbar.github.io", "max_issues_repo_head_hexsha": "5e6b0ea67f5e5f8f3a7bb4394095ea7f7992673a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "files/notes/tex/opti-manifold/opti-manifold-1.tex", "max_forks_repo_name": "ibrahimkakbar/ibrahimkakbar.github.io", "max_forks_repo_head_hexsha": "5e6b0ea67f5e5f8f3a7bb4394095ea7f7992673a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3805970149, "max_line_length": 244, "alphanum_fraction": 0.7718974359, "num_tokens": 1240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.32349145489332204}}
{"text": "\\documentclass[12pt]{amsproc}\n\n\\usepackage{amsmath, amsthm, ulem, graphicx, marvosym, fancyhdr, amscd, amssymb, enumitem, mathrsfs, multicol, setspace}\n\\usepackage{enumitem}\n\\usepackage{url}\n\n\n\\usepackage{listings, color}\n\\definecolor{codegreen}{rgb}{0,0.6,0}\n\\definecolor{codegray}{rgb}{0.5,0.5,0.5}\n\\definecolor{codepurple}{rgb}{0.58,0,0.82}\n\\definecolor{backcolour}{rgb}{0.95,0.95,0.92}\n\n\\lstdefinestyle{mystyle}{\n\tbackgroundcolor=\\color{backcolour},   \n\tcommentstyle=\\color{codegreen},\n\tkeywordstyle=\\color{magenta},\n\tnumberstyle=\\tiny\\color{codegray},\n\tstringstyle=\\color{codepurple},\n\tbasicstyle=\\footnotesize,\n\tbreakatwhitespace=false,         \n\tbreaklines=true,                 \n\tcaptionpos=b,                    \n\tkeepspaces=true,                 \n\tnumbers=left,                    \n\tnumbersep=5pt,                  \n\tshowspaces=false,                \n\tshowstringspaces=false,\n\tshowtabs=false,                  \n\ttabsize=2\n}\n\n\\lstset{style=mystyle}\n\n\n\\newcommand\\Z{{\\mathbb Z}}\n\\newcommand\\F{{\\mathbb F}}\n\\newcommand\\N{{\\mathbb N}}\n\\newcommand\\A{{\\mathbf A}}\n\\newcommand\\p{{\\mathscr P}}\n\\newcommand\\R{{\\mathbb R}}\n\\newcommand\\Q{{\\mathbb Q}}\n\\newcommand\\C{{\\mathbb C}}\n\\newcommand\\bfx{{\\mathbf x}}\n\\newcommand\\bfv{{\\mathbf v}}\n\\newcommand\\bfy{{\\mathbf y}}\n\\newcommand\\bfw{{\\mathbf w}}\n\n%\\usepackage{graphics}\n\n\\topmargin -.7in\n\\evensidemargin-0in\n\\oddsidemargin0in\n\\textheight 9.5in\n\\textwidth 6.5in\n\n\\newtheorem{theorem}{Theorem}\n\\newtheorem{lemma}{Lemma}\n\\newtheorem{prop}{Proposition}\n\\newtheorem{cor}{Corollary}\n\\theoremstyle{definition}\n\\newtheorem{defi}{Definition}\n\\newtheorem{definition}{Definition}\n\\newtheorem{example}{Example}\n\\newtheorem{rmk}{Remark}\n\\newtheorem{interpret}{Interpretation}\n%\\theoremstyle{test}\n\\newtheorem{test}{Test}\n\n\\everymath={\\displaystyle}\n\n\\pagestyle{empty}\n\\onehalfspacing\n\n\\title{Proposal: Surviving the Titanic}\n\n\\author{\n\tPacific Lutheran University  \\\\\n\tMiguel Amezola,\n\tNicholas Glover,\n\t\\and Quinton Teas\n}\n%\tPacific Lutheran University  \\\\\n%\t%\t\\and\n%\t%\tYour friend who worked with you \\\\\n%\t%\tHis/her Major / University \\\\\n%}\n\n\\date{\\today}\n\n\\begin{document}\n\t\n\t\\maketitle\n\t\t\n\t\\begin{abstract}\n\tWe will use passenger data from the sinking of the RMS Titanic to predict survival. Creating a feature space we give us the opportunity to experiment with feature generation. Implementing C4.5, a decision tree algorithm for continuous features and binary classification, will deepen our understanding of machine learning models. Benchmarking with a bagging meta-estimator from scikit-learn will not only allow us to compare our implementation with another, but also give us the opportunity to familiarize ourself with a robust machine learning library\n\t\\end{abstract}\n\t\n\t\\section{Introduction}\\label{intro}\n\tThe RMS Titanic sank on 15 April 1912, after colliding with an iceberg during its maiden voyage from Southampton to New York. Out of 2224 passengers and crew, 1502 lost their lives. Interestingly, some groups of people were more likely to survive, such as women, children, and the upper class. We would like to identify more factors that improved the likelihood of survival. Furthermore, we will map these factors to an appropriate feature space. And finally, we will implement and train a Decision Tree to analyze what sorts of people were likely to survive and compare its accuracy with that of a bagging-meta estimator from sciki-learn.\n\t\n\t\\section{Implementation}\\label{implementation}\n\t\n\tFor the passengers on the Titanic, there were only two outcomes, namely survive and not survive. Thus, they can be grouped into two disjoint sets or classes. We will use a decision tree to predict the class two which each passenger belongs.\n\t\n\t\\subsection{C4.5 Algorithm}\\label{C4.5 Algorithm}\n\tWe will generate the decision tree using the C4.5 algorithm --- an ID3 extension developed by Ross Quinton.\n\tLike its predecessor, C4.5 uses information entropy to perform recursive binary partitioning of a given feature space. \n\t\t\n%\t\\begin{definition}[Entropy]\n%\t\tSuppose a set of possible events have probabilities of occurrence $p_1, p_2, \\ldots, p_n$.\n%\t\tWe define $p_i \\log_2 p_i := 0$ if $p_i = 0$.\n%\t\tThen \\textbf{entropy} is the function $H:p_1,p_2,\\ldots,p_n \\to \\R$ defined by \n%\t\t$$H(p_1,p_2,\\ldots,p_n) := -K\\sum_{i=1}^n p_i \\log_2 p_i,$$\n%\t\twhere $K$ is a positive constant.\n%\t\\end{definition}\n\n\t\\begin{definition}[Entropy \\cite{shannon}]\n\t\tLet $S$ be a dataset, let $X$ be the set of classes in $S$, and let $p(x)$ be the proportion of the number of elements in class $x \\in X$ to the number of elements in $S$. We define $p(x) \\log_2 p(x) := 0$ if $p(x) = 0$. Then \\textbf{entropy} is the function $H:S \\to \\R$ defined by \n\t\t$$H := -\\sum_{x \\in X} p(x) \\log_2 p(x).$$\n\t\\end{definition}\n\t\n\t\\begin{definition}[Information gain]\n\t\tLet $H(S)$ be the entropy of set $S$, let $T$ be a collection of subsets created by partitioning $S$ by feature $F$ such that $S = \\bigcup_{t \\in T}t$, let $p(t)$ be the proportion of the number of elements in class $t \\in T$ to the number of elements in $S$, and let $H(t)$ be the entropy of $t$. \n\t\tThen \\textbf{information gain} is the function $IG: F \\times S \\to \\R$ defined by \n\t\t$$IG(F, S) := H(S) - \\sum_{t \\in T} p(t) H(t).$$\n\t\\end{definition}\n\t\n\tC4.5 uses a set of training data, a set of classified samples $S = s_1,s_2,\\ldots$, to build decision trees. Each sample $s_i \\in \\R^n$, $s_i = (x_1,x_2,\\ldots,s_{n-1}, y)$, where each $x_i$ represents a feature of $s_i$ and $y$ represents the class label for $s_i$ \n\t\n\tAt each node of the tree, C4.5 chooses the feature that most effectively partitions $S$ into subsets $S_1, S_2, \\ldots S_m \\subset S$. This is done using the concept of information gain; that is, the attribute with the largest normalized information gain is used to partition $S$. This is done recursively until for each subset $S_i$ of $S$, $$s_1, s_2 \\in S_i \\wedge s_1 \\neq s_2 \\implies y_1 = y_2$$\n\twhere $y_1$ is the $y$ entry in $s_1$ and $y_2$ is the $y$ entry in $s_2$.\n\n\t\\subsection{Learning Model}\\label{implementation:learning model}\n\t\n\tThere are many decision-tree algorithms. Notable ones include ID3 (Iterative Dichotomiser 3) and C4.5 (successor to ID3) \\cite{wikipedia:decision_tree}. \n\tSince C4.5 made a number of important improvements to ID3, like the ability to handle both discreet and continuous attributes and allowing attributes to be marked ? for missing, we choose this algorithm.\n\t\n\t\\subsection{Work Allocation}\n\t\n\tThis implementation will require several subtasks, namely\n\t\n\t\\begin{enumerate}\n\t\t\\item creating data structures for representing datasets and feature spaces,\n\t\t\\item implementing the C4.5 algorithm, and\n\t\t\\item training/testing the bagging meta-estimator. \n\t\\end{enumerate}\n\t\n\tEach task is assigned to a different group member: (1) Miguel, (2) Nicholas, and (3) Quinton. \n\n\n\t\\begin{table}[h!]\n\t\t\\centering\n\t\t\\caption{Tentative Schedule}\n\t\t\\label{Tentative Schedule}\n\t\t\\begin{tabular}{lll}\n\t\t\t\\textbf{Start Date} & \\textbf{Duration} & \\textbf{Task} \\\\\n\t\t\tApril 10 or April 12 & N/A & Project Proposal Presentation \\\\\n\t\t\tApril 3 & 1 week & Generate features \\\\\n\t\t\tApril 10 & 2 week & Implement model \\\\\n\t\t\tApril 24 & 1 week & Train/Test \\\\\n\t\t\tMay 1 & 1 week & Predict \\\\\n\t\t\tMay 8 & 1 week & Prepare final presentation \\\\\n\t\t\tMay 8 & 2 weeks & Prepare report \\\\\n\t\t\tMay 15, 17, or 19 & N/A & Final project presentation \\\\\n\t\t\tMay 24 & N/A & Report due\n\t\t\\end{tabular}\n\t\\end{table}\n\t\n\t\n\t\\section{Method}\\label{method}\n\t\n\t\\subsection{Data}\\label{method:data}\n\tThe data have been partitioned into two disjoint subsets, $E$ and $F$, such that the cardinality of $F$ is about one half of the cardinality of $E$; that is, $|F| \\approx \\frac{1}{2} |E|$. As demonstrated in Table \\ref{table:data dictionary}, the data have ten variables for each passenger. Note that \\textbf{pclass} is a proxy for the socio-economic status of the passenger. Also, \\textbf{age} is fractional if less than one, or in the form of $xx.5$ if the age was estimated. For \\textbf{sibsp}, a sibling is defined as a brother, sister, stepbrother, stepsister, and a spouse is defined as a husband, wife (mistresses and fianc\\'{e}s were ignored). Similarly for \\textbf{parch}, a parent is a mother or father and a child is a daughter, son, stepdaughter, or stepson. If children traveled with a nanny, then parch = 0 for them \\cite{kaggle}.\n\t \n\n\t\\begin{table}[h]\n\t\t\\centering\n\t\t\\caption{Data Dictionary}\n\t\t\\label{table:data dictionary}\n\t\t\\begin{tabular}{ll}\n\t\t\t\\textbf{Variable} & \\textbf{Definition} \\\\\n\t\t\tsurvival & Survival \\\\\n\t\t\tpclass & Ticket class \\\\\n\t\t\tsex & Sex \\\\\n\t\t\tage & Age in years \\\\\n\t\t\tsibsp & number of siblings or spouses aboard the Titanic \\\\\n\t\t\tparch & number of parents or children aboard the Titanic \\\\\n\t\t\tticket & Ticket number \\\\\n\t\t\tfare & Passenger fare \\\\\n\t\t\tcabin & Cabin number \\\\\n\t\t\tembarked & Port of Embarkation\n\t\t\\end{tabular}\n\t\\end{table}\n\t\n\t\n\t\\subsection{Train}\\label{method:train}\n\tThe larger subset of data $E$ will be used to build the machine learning model. We will also fit this training set to the bagging meta-estimator from scikit-learn. This bagging classifier in turn fits an ensemble of classification trees, each on random subsets of the original set. Such an estimator should reduce the variance that plagues decision trees, thereby outperforming our implementation of the C4.5 algorithm.\n\t\n\t\\subsection{Test}\\label{method:test}\n\tWe will use dataset $F$ to see how well the model performs on unseen data. As with training, we will also test the bagging estimator with this dataset.\n\t\n\t\\subsection{Predict}\\label{method:predict}\n\t\n%\t\\subsubsection{Goal}\\label{method:predict:goal}\n%\tWe will predict whether or not a passenger survived the sinking of the Titanic. \n\n\tPredictions from our C4.5 implementation and the bagging meta-estimator will be recorded in distinct .csv files. Each file will have exactly 418 entries and a header row, as in Listing 1.  Each file will have exactly 2 columns:\n\t\\begin{itemize}\n\t\t\\item PassengerId (sorted in any order), and\n\t\t\\item Survived (contains binary predictions: 1 for survived, 0 for deceased).\n\t\\end{itemize}\n\t\n\t\\begin{lstlisting}[language=Python, caption=Prediction example]\n\t\tPassengerId,Survived\n\t\t892,0\n\t\t893,1\n\t\t894,0\n\t\tEtc.\\end{lstlisting}\n\t\t\n\tWe will use the following metric to see how well our implementation of the C4.5 algorithm performs.\n\n\t\\begin{definition}[Accuracy]\\label{definition:accuracy}\n\t\tLet $c,i \\in \\N$ such that $c + i \\neq 0$ with $c$ equal to the number of correct predictions and $i$ equal to the number of incorrect predictions, and let $f: \\N \\to [0,1] \\cap \\R$ be the function defined by   \n\t\t$$f(c,i) := \\frac{c}{c + i}.$$\n\t\tThis function is the statistical measure commonly known as accuracy. \n\t\\end{definition}\n\t\n\tAs for the bagging meta-estimator, scikit-learn provides a method for computing the mean accuracy on the given test data and labels. \n\t\n\t\\section{Conclusion}\\label{conclusions}\n\tNot only is the sinking of the RMS Titanic an interesting historical event, but an opportunity to design a machine learning model and test its performance. Since we are familiar with ID3, implementing its successor C4.5 will allow us to build on previous knowledge. The hands-on experience stemming from making our own implementation will deepen our understanding of machine learning models.\n\n\t\t\n\t\\bibliographystyle{plain}\n\t\\bibliography{refs.bib}\n\t\n\t\n\n\\end{document}", "meta": {"hexsha": "a7f1be0316667fe97618475922e521fb6e1fdb9f", "size": 11393, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "proposal/project-proposal.tex", "max_stars_repo_name": "aM3z/titanic", "max_stars_repo_head_hexsha": "d8ebb53bcde879b336a266245f2744d81d3fda45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "proposal/project-proposal.tex", "max_issues_repo_name": "aM3z/titanic", "max_issues_repo_head_hexsha": "d8ebb53bcde879b336a266245f2744d81d3fda45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "proposal/project-proposal.tex", "max_forks_repo_name": "aM3z/titanic", "max_forks_repo_head_hexsha": "d8ebb53bcde879b336a266245f2744d81d3fda45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.4708333333, "max_line_length": 845, "alphanum_fraction": 0.7293074695, "num_tokens": 3271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.3233808946074032}}
{"text": "\\subsubsection{Diamond}\\index{Diamond}\\index{Data!Diamond!construction of}\\index{Solid state!data sets}\r\n\r\nThe unit cell of diamond consists of two carbon atoms. If symmetry operations were allowed,\r\n only one atom would be needed, but only translation operations are allowed, so two atoms\r\n must be used.\r\n\r\nEach carbon atom forms four single bonds with other carbon atoms. \r\nThis can be used in defining the translation vectors: the effect \r\nof a translation vector acting on atom 1 would be to move it to \r\none of the atoms attached to atom 2. \r\n Using this fact, the data set can easily be made:\r\n\r\nFirst attempt at a data set for MAKPOL. \\begin{verbatim}\r\nMERS=(4,4,4)  Diamond\r\nC\r\nC  1.545 1 0 0 0 0 1\r\nTv 2.523 1 35.26439 10 0 1 2\r\nTv 2.523 1 35.26439 1 120 1 1 2 3\r\nTv 2.523 1 35.26439 1 240 1 1 2 3\r\n\\end{verbatim}\r\n\r\nIn this description, the number of unit cells to be used is too\r\nsmall: 4 by 4 by 4.  Ideally, at least a 6 by 6 by 6 system\r\n should be use. The smaller number is used here purely for the\r\n purposes of illustration.\r\n\r\n\r\n\r\nThis data set is, however, not ideal, for the following reasons:\r\n\r\nThe angle between the translation vectors is 60 degrees. This \r\nmeans that the unit cell must be very large in order for the \r\ndistance between opposite faces to be at least 10 \\AA ngstroms. \r\nDiamond is a Body-Centered-Cubic lattice. This means that every \r\nodd cell (e.g. 001,111,012, etc.) is missing. By specifying BCC, \r\nthe angle between the translation vectors can be increased to 90 \r\ndegrees. This is the ideal angle to maximize the distance between \r\nfaces. The system has a lot of symmetry. By adding ``SYMMETRY\" two \r\nobjectives can be met: First, symmetry can be used in defining the \r\nTv. This is not very important in this unit cell, but does make it \r\neasier to change the bond-length of atom 2, in that any change in \r\nthis distance is automatically made in the Tv. Second, if SYMMETRY \r\nis present, MAKPOL will automatically add symmetry to the data \r\nset.\r\n\r\n\\begin{verbatim}\r\nData set for MAKPOL. File name: Make_diamond.dat\r\n SYMMETRY MERS=(4,4,4) BCC\r\n Diamond, 64 atoms \r\nC \r\nC 1.545 1 0 0 0 0 1 \r\nTv 1.784 0 54.73561 0 0 0 1 2 \r\nTv 1.784 0 54.73561 0 120 0 1 2 3 \r\nTv 1.784 0 54.73561 0 240 0 1 2 3 \r\n\r\n2 19 1.1547005 3 4 5 \r\n\\end{verbatim}\r\n\r\nWhen this data set is run using MAKPOL, the following data set is \r\ngenerated: \r\n\\begin{verbatim}\r\nSYMMETRY MERS=(4,4,4) BCC \r\nDiamond, 64 atoms \r\n\r\nC  0.000000 0   0.000000 0    0.000000 0 \r\nC  1.545000 1   0.000000 0    0.000000 0 1 \r\nC  3.568025 1  54.735610 1    0.000000 0 1 2 \r\nC  1.545000 0 125.264390 1    0.000000 1 3 1 2 \r\nC  2.522974 1  35.264390 1   60.000000 1 1 2 3 \r\nC  1.545000 0 144.735610 1    0.000000 0 5 1 2 \r\nC  2.522974 0 135.000000 1   45.000000 1 3 1 2 \r\nC  1.545000 0 144.735610 0  -90.000000 1 7 3 1 \r\nC  2.522974 0  90.000000 1   90.000000 0 5 1 2 \r\nC  1.545000 0  90.000000 0 -144.735610 1 9 5 1  \r\n\r\n(many lines deleted) \r\n\r\nC  1.545000 0  90.000000 0  160.528779 1 61 57 41 \r\nC  2.522974 0  60.000000 0  -35.264390 0 59 43 26\r\nC  1.545000 0  90.000000 0  160.528779 0 63 59 43 \r\nXX 2.522974 0  90.000000 0  180.000000 0 7   3 1 \r\nXX 2.522974 0  90.000000 0 -125.264390 0 29  9 5 \r\nXX 2.522974 0 180.000000 0    0.000000 0 53 41 42 \r\nTv 7.136049 1   0.000000 0    0.000000 0 1  65 2 \r\nTv 7.136049 0   0.000000 0    0.000000 0 1  66 2 \r\nTv 7.136049 0   0.000000 0    0.000000 0 1  67 2 \r\n\r\n2 1 4 6 8 10 12 14 16 18 20 22\r\n2 1 24 26 28 30 32 34 36 38 40 42\r\n2 1 44 46 48 50 52 54 56 58 60 62\r\n2 1 64\r\n4 3 6 11 12 15 16 18 33 34 35 36\r\n4 3 39 40 43 44 45 51 52 53 54 55\r\n4 3 56 59 60 67\r\n5 1 7 9 11 13 15 17 19 21 23 25\r\n5 1 27 29 31 33 35 37 39 41 43 45\r\n5 1 47 49 51 53 55 57 59 61 63 65\r\n5 1 66 67\r\n5 2 17\r\n5 14 17\r\n\r\n(many lines deleted) \r\n\r\n\\end{verbatim}\r\nBefore running this data set, more symmetry can be added \r\n``by hand.\" Every angle is symmetry defined, and does not need to \r\nbe optimized, therefore every angle and dihedral optimization flag \r\ncan be set to zero. Every angle and dihedral symmetry relation \r\ndefined at the end of the data set can also be deleted. These are \r\nthe lines that start with a number followed by a 2, a 3, or a 14. \r\nEvery distance can be related to the bond-length of atom 2. The \r\nposition of atoms 3 and 5, and the length of the translation \r\nvector Tv can be defined by distances that are exactly Sqrt(16/3). \r\nSqrt(8/3) and Sqrt(64/3) times the C$_2$-C$_1$ \r\ndistance, respectively. These symmetry relations can be defined \r\nusing MOPAC symmetry function 19. This has the form: Defining-atom \r\n19 multiplier dependent atom(s) When these changes are made to the \r\ndata set, the final data set is produced. This is: \r\n\\begin{verbatim}\r\n SYMMETRY MERS=(4,4,4) BCC \r\n Diamond, 64 atoms\r\n\r\n  C    0.000000  0   0.000000  0    0.000000  0\r\n  C    1.545000  1   0.000000  0    0.000000  0     1\r\n  C    3.568025  0  54.735610  0    0.000000  0     1     2\r\n  C    1.545000  0 125.264390  0    0.000000  0     3     1     2\r\n  C    2.522974  0  35.264390  0   60.000000  0     1     2     3\r\n  C    1.545000  0 144.735610  0    0.000000  0     5     1     2\r\n  C    2.522974  0 135.000000  0   45.000000  0     3     1     2\r\n  \r\n  (many lines deleted) \r\n \r\n  C    1.545000  0  90.000000  0  160.528779  0    61    57    41\r\n  C    2.522974  0  60.000000  0  -35.264390  0    59    43    26\r\n  C    1.545000  0  90.000000  0  160.528779  0    63    59    43\r\n XX    2.522974  0  90.000000  0  180.000000  0     7     3     1\r\n XX    2.522974  0  90.000000  0 -125.264390  0    29     9     5\r\n XX    2.522974  0 180.000000  0    0.000000  0    53    41    42\r\n Tv    7.136049  0   0.000000  0    0.000000  0     1    65     2\r\n Tv    7.136049  0   0.000000  0    0.000000  0     1    66     2\r\n Tv    7.136049  0   0.000000  0    0.000000  0     1    67     2\r\n\r\n   2 19 2.3094  3\r\n   2 19 1.6330  5\r\n   2 19 4.6188 68\r\n   2  1    4    6    8   10   12   14   16   18   20   22\r\n   2  1   24   26   28   30   32   34   36   38   40   42\r\n   2  1   44   46   48   50   52   54   56   58   60   62\r\n   2  1   64\r\n   5  1    7    9   11   13   15   17   19   21   23   25\r\n   5  1   27   29   31   33   35   37   39   41   43   45\r\n   5  1   47   49   51   53   55   57   59   61   63   65\r\n   5  1   66   67\r\n  68  1   69   70\r\n\\end{verbatim} \r\n\r\nIs the use of symmetry worth all this effort? Most \r\ndefinitely! If symmetry is NOT used, then for this small system of \r\n64 atoms, 195 parameters would need to be optimized. That is, \r\n3*64-6 for the 64 atoms plus 9 parameters for the three \r\ntranslation vectors. Optimization of a system with 195 unknowns \r\nwould take much longer than for a system with precisely one \r\nunknown. For a more realistic system, involving 6 by 6 by 6 \r\nprimitive unit cells, symmetry would lower the complexity of the \r\ncalculation from 651 unknowns to precisely 1. \r\n", "meta": {"hexsha": "143e4ceabe3a29046be062cb93e69c9e54cda286", "size": 6847, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "manuals/MOPAC2000_manual/diamond.tex", "max_stars_repo_name": "openmopac/MOPAC-archive", "max_stars_repo_head_hexsha": "01510e44246de34a991529297a10bcf831336038", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-16T20:53:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T20:54:11.000Z", "max_issues_repo_path": "manuals/MOPAC2000_manual/diamond.tex", "max_issues_repo_name": "openmopac/MOPAC-archive", "max_issues_repo_head_hexsha": "01510e44246de34a991529297a10bcf831336038", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "manuals/MOPAC2000_manual/diamond.tex", "max_forks_repo_name": "openmopac/MOPAC-archive", "max_forks_repo_head_hexsha": "01510e44246de34a991529297a10bcf831336038", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.2469879518, "max_line_length": 104, "alphanum_fraction": 0.6488973273, "num_tokens": 2874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3233808946074032}}
{"text": "%!TEX root = ../chapter1.tex\n% ******************************* Thesis Appendix A ****************************\n\\chapter{}\n\n\\begin{table}[H]\n\\footnotesize\n    \\caption{Summary Statistics - Year 2004}\n          \\begin{tabularx}{\\linewidth}{X H H H H}\n    \\hline\n    \\hline\n      Variable  & Mean & St. Dev. & Min. & \\centering\\arraybackslash Max.\\\\\n    \\hline\n    Deforestation   &  53.342 & 107.654 & 0.1 & 1082.5 \\\\\n    Fines &    0.082 &    0.307 &           0&    4.290 \\\\\n    Protected Areas  & 1.501 &    3.428 &      0&    36.930\\\\\n    Rural Credits   &  0.264 &   0.830 &           0&   9.649\\\\\n    Environmental Law  &  0.339&    0.473 &     0&           1 \\\\\n    Environmental Office  & 0.479&     0.500 &      0&     1\\\\\n    Housing Projects   &   0.728 &    0.444&   0&           1 \\\\\n    Settlements  &  2.570 &    4.652 &           0&          65 \\\\\n    Settlements Density  & 0.016&    0.048&        0&    1.016\\\\\n    GDP  &    0.014&     0.082&    0.001&    1.659\\\\\n    Beef Price   &  2.409&    0.035&    2.286&     2.419\\\\\n    Soy Price   &   0.703&    0.138&    0.272&    1.034\\\\\n    Wood Price   &   0.074&    0.049&    0.002&    0.401 \\\\\n    Roads &      0.018 &    0.029 &           0.001&    0.081\\\\\n    Clouds &      0.284&    1.459&           0&    18.557\\\\\n    No obs &     0.260&      2.333&    0&    49.530\\\\\n    Mayor Political Party (pro-farmer)   & 0.809&    0.393&   0&   1 \\\\\n    Mayor Gender (Male)   & 0.923&    0.265 &  0& 1\\\\\n    Mayor Age (\\% above 50) &   0.357&    0.479&  0& 1\\\\\n    Mayor Education &    0.347&    0.476& 0& 1\\\\\n    Corruption &     0.007&    0.007&           0&    0.056\\\\\n    Re-election &    0 & 0 & 0  &   0\\\\\n    \\hline\n    \\hline\n    \\multicolumn{5}{l}{\\footnotesize  Note: Statistics refer to N=6178 observations for 562 municipalities.}\n    \\end{tabularx}\n  \\label{tab:summary2004}\n\\end{table}\n\n\n\\begin{table}[H]\n\\footnotesize\n    \\caption{Summary Statistics - Year 2015}\n          \\begin{tabularx}{\\linewidth}{X H H H H}\n     \\hline\n      \\hline\n      Variable  & Mean & St. Dev. & Min. & \\centering\\arraybackslash Max.\\\\\n     \\hline\n    Deforestation   &  11.449 & 31.028  &0.1 &\t308.6 \\\\\n    Fines &     0.342&    1.642&           0&    24.227 \\\\\n    Protected Areas  &  23.134&    57.679&     0&    448.777\\\\\n    Rural Credits   &   0.919&    0.364&           0&   3.281\\\\\n    Environmental Law  &   0.696&    0.460&  0& 1\\\\\n    Environmental Office  &  0.942&    0.232& 0 & 1\\\\\n    Housing Projects   &     0.822&    0.382& 0& 1\\\\\n    Settlements  &   4.239&    6.460&           0&          76\\\\\n    Settlements Density  &   0.018&     0.027& 0& 0.277\\\\\n    GDP  &    0.110&    0.530&    0.002&    9.850\\\\\n    Beef Price   &    0.877&    0.006&    0.866&     0.889\\\\\n    Soy Price   &   0.722&    0.060&    0.540&    0.899\\\\\n    Wood Price   &   0.105&    0.087&    0.005&    0.649 \\\\\n    Roads &     0.206 &    0.028&           0.001&   0.083\\\\\n    Clouds &     9.019&    35.686&           0&   488.1\\\\\n    No obs &     0&     0&           0&     0\\\\\n    Mayor Political Party (pro-farmer)   &  0.944&    0.229&  0&  1\\\\\n    Mayor Gender (Male)   & 0.866&    0.340&  0& 1\\\\\n    Mayor Age (\\% above 50) &     0.368&    0.482&         0& 1\\\\\n    Mayor Education &    0.505&    0.500&         0&1\\\\\n    Corruption &       0.042&    0.539&           0&    12.534\\\\\n     Re-election &    0.194 & 0.396 & 0  &   1\\\\\n    \\hline\n    \\hline\n    \\multicolumn{5}{l}{\\footnotesize  Note: Statistics refer to N=6178 observations for 562 municipalities.}\n    \\end{tabularx}\n  \\label{tab:summary2015}\n\\end{table}\n\n\\begin{table}[H]\n\\scriptsize\n    \\caption{Data Description - Scope and Sources}\n       \\begin{tabularx}{\\linewidth}{l ccc}\n     \\hline\n     \\hline\n       Variable & \\centering Level & Source & \\centering\\arraybackslash Scale\\\\\n     \\hline\n    Deforestation & Municipality & INPE & ln(square km)\\\\\n    Fines & Municipality & IBAMA & in \\$10,000,000 BRL \\\\\n    Conservation Units & Municipality & MMA/IBAMA & in 10,000 sq km \\\\\n    Indigenous Land   & Municipality & FUNAI & in 10,000 sq km \\\\\n    Rural Credits Grants & Municipality & BASA, BNB, BACEN & in \\$10,000,000,000 BRL \\\\\n    Environment Law & Municipality & IBGE & Indicator of environmental law\\\\\n    Environmental Agency   & Municipality & IBGE & Indicator of environmental office \\\\\n    Housing Projects   & Municipality & IBGE & Indicator of housing project \\\\\n    Settlements  & Municipality & INCRA & Number of settlements \\\\\n    Settlements Density & Municipality & INCRA & Ratio of families per settlement \\\\\n    GDP   & Municipality & IBGE & in \\$100,000,000 BRL\\\\\n    Beef Price   & State & CEPEA & per 15kg, \\$100 BRL\\\\\n    Soy Price  & Municipality & IBGE & per 60kg, BRL \\\\\n    Wood Price  & Municipality & IBGE & per cubic m, BRL\\\\\n    Roads & State & DNIT & Number of `new` paved kms averaged by state size\\\\\n    Mayor Political Party   & Municipality & IBGE & Dummy if \"pro-farmer\" party\\\\\n    Mayor Education   & Municipality & IBGE & Dummy  if mayor has tertiary education  \\\\\n    Mayor Age  & Municipality & IBGE & Dummy if age is higher than the average of 50\\\\\n    Clouds  & Municipality & INPE & in 52 weeks\\\\\n    No Obs & Municipality & INPE & Area not observed per year\\\\\n    Corruption   & Municipality & IBGE & Number of Commissioned Workers per City Hall averaged by population \\\\\n    Re-election & Municipality & TSE & Dummy if mayor is running for re-election in election years\\\\\n    \\hline\n    \\hline\n    \\multicolumn{4}{l}{\\footnotesize Note: All prices and economic values are expressed in constant 2010 Brazil Reais (BRL).} \\\\\n    \\multicolumn{4}{l}{\\footnotesize Exchange Rate 1.00 BRL to 0.602 US Dollar.} \\\\\n    \\end{tabularx}%\n \\label{tab:sources}%\n\\end{table}%\n\n\n    \\begin{table}[htp!]\n\\caption{LM Tests}\n\\footnotesize\n       \\begin{tabularx}{\\columnwidth}{X H H}\n     \\hline\n     \\hline\n     & \\multicolumn{2}{c}{W1} \\\\\n      \\cline{2-3}\n    \\multicolumn{3}{l}{\\textbf{Elhorst}} \\\\\n    LM test no spatial lag, probability         &   0.0000 &  1.000  \\\\\n    robust LM test no spatial lag, probability   & 314.0441 &  0.000 \\\\\n    LM test no spatial error, probability        &  288.3646 & 0.000 \\\\\n    robust LM test no spatial error, probability &  602.4087 & 0.000 \\\\\n    \\multicolumn{3}{l}{\\textbf{Lacombe}} \\\\\n    LM lag test for omitted spatial lag in panel data  &     111.2545  &       0.000 \\\\\n    LM error test for spatial errors in panel data &  103.5038 & 0.000 \\\\\n    Robust LM lag test for omitted spatial lag in panel data & 10.1198 & 0.001 \\\\\n    Robust LM error test for spatial errors in panel data & 2.3692 & 0.123 \\\\\n    \\hline\n     & \\multicolumn{2}{c}{W2} \\\\\n      \\cline{2-3}\n     \\multicolumn{3}{l}{\\textbf{Elhorst}} \\\\\n    LM test no spatial lag, probability         &  0.0000 &   1.000   \\\\\n    robust LM test no spatial lag, probability   & 314.3242 &  0.000 \\\\\n    LM test no spatial error, probability        &  288.6314 & 0.000 \\\\\n    robust LM test no spatial error, probability &  602.9555 & 0.000 \\\\\n    \\multicolumn{3}{l}{\\textbf{Lacombe}} \\\\\n    LM lag test for omitted spatial lag in panel data  &    111.2895  &       0.000 \\\\\n    LM error test for spatial errors in panel data &  104.1005 & 0.000 \\\\\n    Robust LM lag test for omitted spatial lag in panel data & 9.7553 & 0.001 \\\\\n    Robust LM error test for spatial errors in panel data & 2.5663 & 0.109 \\\\\n    \\hline\n     & \\multicolumn{2}{c}{W3} \\\\\n      \\cline{2-3}\n     \\multicolumn{3}{l}{\\textbf{Elhorst}} \\\\\n    LM test no spatial lag, probability         &   0.0000 &  1.000  \\\\\n    robust LM test no spatial lag, probability   & 921.5621 &  0.000 \\\\\n    LM test no spatial error, probability        &  1370.3817 & 0.000 \\\\\n    robust LM test no spatial error, probability & 2291.9439 & 0.000 \\\\\n    \\multicolumn{3}{l}{\\textbf{Lacombe}} \\\\\n    LM lag test for omitted spatial lag in panel data  &    326.6028  &       0.000 \\\\\n    LM error test for spatial errors in panel data &  334.1047 & 0.000 \\\\\n    Robust LM lag test for omitted spatial lag in panel data &  21.3014 & 0.000 \\\\\n    Robust LM error test for spatial errors in panel data & 28.8033 & 0.000 \\\\\n      \\hline\n \\hline\n    \\multicolumn{3}{l}{Note that the results satisfy the condition tha LM spatial Lag + Robust LM spatial error}\\\\\n    \\multicolumn{3}{l}{= LM spatial error + robust LM spatial lag \\citep{ANSELIN}.}\n    \\end{tabularx}%\n  \\label{tab:LMtests}%\n\\end{table}%\n\n\n\n", "meta": {"hexsha": "61e672b594777866c01731adbcd380cfc18996b8", "size": 8404, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapter1/AppendixA1.tex", "max_stars_repo_name": "vgs549/phd-thesis-vilane", "max_stars_repo_head_hexsha": "85755a8608514a7b4c8fc53c8b449027dfc896c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter1/AppendixA1.tex", "max_issues_repo_name": "vgs549/phd-thesis-vilane", "max_issues_repo_head_hexsha": "85755a8608514a7b4c8fc53c8b449027dfc896c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1/AppendixA1.tex", "max_forks_repo_name": "vgs549/phd-thesis-vilane", "max_forks_repo_head_hexsha": "85755a8608514a7b4c8fc53c8b449027dfc896c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.5780346821, "max_line_length": 128, "alphanum_fraction": 0.5669919086, "num_tokens": 3005, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3233808946074032}}
{"text": "\\documentclass{artikel3}\n\n\\usepackage{pslatex,graphicx,amsmath,amssymb}\n\\usepackage{pdflatex}\n\n\\newtheorem{theorem}{Theorem}\n\n\\newcounter{excounter}\n\\newenvironment{exercise}\n  {\\refstepcounter{excounter}\n   \\begin{quotation}\\textbf{Exercise \\arabic{excounter}.} }\n  {\\end{quotation}}\n\n\\begin{document}\n\\title{SSC 335: demo}\n\\author{Victor Eijkhout}\n\\date{today}\n\\maketitle\n\n\\section{This is a section}\n\\label{sec:intro}\n\nThis is a test document, used in~\\cite{latexdemo}. It contains a\ndiscussion in section~\\ref{sec:discussion}.\n\n\\begin{exercise}\\label{easy-ex}\n  Left to the reader.\n\\end{exercise}\n\\begin{exercise}\n  Also left to the reader, just like in exercise~\\ref{easy-ex}\n\\end{exercise}\n\n\\begin{theorem}\n  This is cool.\n\\end{theorem}\nThis is a formula: $a\\Leftarrow b$.\n\\begin{equation}\n  \\label{eq:one}\n    x_i\\leftarrow y_{ij}\\cdot x^{(k)}_j\n\\end{equation}\nText: $\\int_0^1 \\sqrt x\\,dx$\n\\[\n  \\int_0^1 \\sqrt x\\,dx\n\\]\n\\section{This is another section}\n\\label{sec:discussion}\n\n\\begin{table}[ht]\n  \\centering\n  \\begin{tabular}{|rl|}\n    \\hline one&value \\\\ \\hline another&values \\\\ \\hline\n  \\end{tabular}\n  \\caption{This is the only table in my demo}\n  \\label{tab:thetable}\n\\end{table}\n\\begin{figure}[ht]\n  \\centering\n  \\includegraphics{graphics/caches}\n  \\caption{this is the only figure}\n  \\label{fig:thefigure}\n\\end{figure}\nAs I showed in the introductory section~\\ref{sec:intro}, in the\npaper~\\cite{AdJo:colorblind}, it was shown that\nequation~\\eqref{eq:one}\n\\begin{itemize}\n\\item There is an item.\n\\item There is another item\n  \\begin{itemize}\n  \\item sub one\n  \\item sub two\n  \\end{itemize}\n\\end{itemize}\n\\begin{enumerate}\n\\item item one\n\\item item two\n  \\begin{enumerate}\n  \\item sub one\n  \\item sub two\n  \\end{enumerate}\n\\end{enumerate}\n\n\\tableofcontents\n\\listoffigures\n\n\\bibliography{math}\n\\bibliographystyle{plain}\n\n\\end{document}\n", "meta": {"hexsha": "4a365967f9dc738e2f122ca4153492b0eaf2340c", "size": 1847, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "booksources/tutorials/latexdemo/demo.tex", "max_stars_repo_name": "oabushama/HPC", "max_stars_repo_head_hexsha": "7f66d951a690e3e5e33da19aaabaffbc058797f2", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "booksources/tutorials/latexdemo/demo.tex", "max_issues_repo_name": "oabushama/HPC", "max_issues_repo_head_hexsha": "7f66d951a690e3e5e33da19aaabaffbc058797f2", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "booksources/tutorials/latexdemo/demo.tex", "max_forks_repo_name": "oabushama/HPC", "max_forks_repo_head_hexsha": "7f66d951a690e3e5e33da19aaabaffbc058797f2", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7528089888, "max_line_length": 64, "alphanum_fraction": 0.722252301, "num_tokens": 629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.6224593241981982, "lm_q1q2_score": 0.32338089096885436}}
{"text": "% -------------------------------------------------------------------------\n% ------ nuweb macros (redefine as desired, or omit with \"nuweb -p\") ------\n% -------------------------------------------------------------------------\n\\providecommand{\\NWtxtMacroDefBy}{Macro defined by}\n\\providecommand{\\NWtxtMacroRefIn}{Macro referenced in}\n\\providecommand{\\NWtxtMacroNoRef}{Macro never referenced}\n\\providecommand{\\NWtxtDefBy}{Defined by}\n\\providecommand{\\NWtxtRefIn}{Referenced in}\n\\providecommand{\\NWtxtNoRef}{Not referenced}\n\\providecommand{\\NWtxtFileDefBy}{File defined by}\n\\providecommand{\\NWsep}{${\\diamond}$}\n\\providecommand{\\NWlink}[2]{\\hyperlink{#1}{#2}}\n\\providecommand{\\NWtarget}[2]{% move baseline up by \\baselineskip \n  \\raisebox{\\baselineskip}[1.5ex][0ex]{%\n    \\mbox{%\n      \\hypertarget{#1}{%\n        \\raisebox{-1\\baselineskip}[0ex][0ex]{%\n          \\mbox{#2}%\n}}}}}\n% -------------------------------------------------------------------------\n\n\\documentclass[11pt,oneside]{article}\t%use\"amsart\"insteadof\"article\"forAMSLaTeXformat\n\\usepackage{geometry}\t\t%Seegeometry.pdftolearnthelayoutoptions.Therearelots.\n\\geometry{letterpaper}\t\t%...ora4paperora5paperor...\n%\\geometry{landscape}\t\t%Activateforforrotatedpagegeometry\n%\\usepackage[parfill]{parskip}\t\t%Activatetobeginparagraphswithanemptylineratherthananindent\n\\usepackage{graphicx}\t\t\t\t%Usepdf,png,jpg,orepsßwithpdflatex;useepsinDVImode\n\t\t\t\t\t\t\t\t%TeXwillautomaticallyconverteps-->pdfinpdflatex\t\t\n\\usepackage{amssymb}\n\\usepackage[colorlinks]{hyperref}\n\n\\usepackage{framed}\n\\usepackage{amsthm}\n\\newtheorem{remark}{Remark}\n\\newtheorem{definition}{Definition}\n\n%----macros begin---------------------------------------------------------------\n\\usepackage{color}\n\\usepackage{amsthm}\n\n\\def\\conv{\\mbox{\\textrm{conv}\\,}}\n\\def\\aff{\\mbox{\\textrm{aff}\\,}}\n\\def\\E{\\mathbb{E}}\n\\def\\R{\\mathbb{R}}\n\\def\\Z{\\mathbb{Z}}\n\\def\\tex{\\TeX}\n\\def\\latex{\\LaTeX}\n\\def\\v#1{{\\bf #1}}\n\\def\\p#1{{\\bf #1}}\n\\def\\T#1{{\\bf #1}}\n\n\\def\\vet#1{{\\left(\\begin{array}{cccccccccccccccccccc}#1\\end{array}\\right)}}\n\\def\\mat#1{{\\left(\\begin{array}{cccccccccccccccccccc}#1\\end{array}\\right)}}\n\n\\def\\lin{\\mbox{\\rm lin}\\,}\n\\def\\aff{\\mbox{\\rm aff}\\,}\n\\def\\pos{\\mbox{\\rm pos}\\,}\n\\def\\cone{\\mbox{\\rm cone}\\,}\n\\def\\conv{\\mbox{\\rm conv}\\,}\n\\newcommand{\\homog}[0]{\\mbox{\\rm homog}\\,}\n\\newcommand{\\relint}[0]{\\mbox{\\rm relint}\\,}\n\n%----macros end-----------------------------------------------------------------\n\n\\title{Imaging Morphology with LAR\n\\footnote{This document is part of the \\emph{Linear Algebraic Representation with CoChains} (LAR-CC) framework~\\cite{cclar-proj:2013:00}. \\today}\n}\n\\author{Alberto Paoluzzi}\n%\\date{}\t\t\t\t\t\t\t%Activatetodisplayagivendateornodate\n\n\\begin{document}\n\\maketitle\n\\nonstopmode\n\n\\begin{abstract}\nIn this module we aim to implement the four operators of mathematical morphology, i.e.~the \\emph{dilation}, \\emph{erosion}, \\emph{opening} and \\emph{closing} operators, by the way of matrix operations representing the linear operators---\\emph{boundary} and \\emph{coboundary}---over LAR. \nAccording to the multidimensional character of LAR, our implementation is dimension-independent.\nIn few words, it works as follows: (a)  the input is (the coordinate representation of) a $d$-chain $\\gamma$; (b) compute its boundary $\\partial_d(\\gamma)$; (c) extract the maximal $(d-2)$-chain $\\epsilon \\subset \\partial_d(\\gamma)$; (d) consider the $(d-1)$-chain returned from its coboundary $\\delta_{d-2}(\\epsilon)$; (e) compute the $d$-chain $\\eta := \\delta_{d-1}(\\delta_{d-2}(\\epsilon)) \\subset C_d$ \\emph{without} performing the  $\\mbox{mod\\ 2}$ final transformation on the resulting coordinate vector, that would provide a zero result, according to the standard algebraic constraint $\\delta\\circ\\delta=0$. It is easy to show that $\\eta \\equiv (\\oplus \\gamma) - (\\ominus \\gamma)$ provides the \\emph{morphological gradient} operator. The four standard morphological operators are therefore  consequently computable.\n\\end{abstract}\n\n\\tableofcontents\n\n\\section{Test image generation}\n\nVarious methods for the input or the generation of a test image  are developed in the subsections of this section. The aim is to prepare a set of controlled test beds, used to check both the implementation and the working properties of our topological implementation of morphological operators. \n\n\n\\subsection{Random binary multidimensional image}\n\nA multidimensional binary image is generated here by using a random approach, both for the bulk structure and the small artefacts of the image.  \n\n\n%-------------------------------------------------------------------------------\n\\begin{flushleft} \\small\n\\begin{minipage}{\\linewidth} \\label{scrap1}\n\\protect\\makebox[0ex][r]{\\NWtarget{nuweb2a}{\\rule{0ex}{0ex}}\\hspace{1em}}$\\langle\\,$Generation of random image\\nobreak\\ {\\footnotesize 2a}$\\,\\rangle\\equiv$\n\\vspace{-1ex}\n\\begin{list}{}{} \\item\n\\mbox{}\\verb@@\\\\\n\\mbox{}\\verb@def randomImage(shape, structure, noiseFraction=0.0):@\\\\\n\\mbox{}\\verb@   \"\"\" Generation of random image of given shape and structure. @\\\\\n\\mbox{}\\verb@      Return scipy.ndarray(shape)@\\\\\n\\mbox{}\\verb@   \"\"\"@\\\\\n\\mbox{}\\verb@   print \"noiseFraction =\",noiseFraction@\\\\\n\\mbox{}\\verb@   @\\hbox{$\\langle\\,$Generation of bulk array structure\\nobreak\\ {\\footnotesize \\NWlink{nuweb2b}{2b}}$\\,\\rangle$}\\verb@@\\\\\n\\mbox{}\\verb@   @\\hbox{$\\langle\\,$Generation of random artifacts\\nobreak\\ {\\footnotesize \\NWlink{nuweb3a}{3a}}$\\,\\rangle$}\\verb@@\\\\\n\\mbox{}\\verb@   return image_array@\\\\\n\\mbox{}\\verb@@{\\NWsep}\n\\end{list}\n\\vspace{-1ex}\n\\footnotesize\\addtolength{\\baselineskip}{-1ex}\n\\begin{list}{}{\\setlength{\\itemsep}{-\\parsep}\\setlength{\\itemindent}{-\\leftmargin}}\n\\item \\NWtxtMacroRefIn\\ \\NWlink{nuweb14e}{14e}.\n\\end{list}\n\\end{minipage}\\\\[4ex]\n\\end{flushleft}\n%-------------------------------------------------------------------------------\n\n\n\\paragraph{Generation of the gross image}\nFirst we generate a 2D grid of squares by Cartesian product, and produce the bulk of the random image then used to test our approach to morphological operators via topological ones.\n\n\n%import scipy\n%scipy.misc.imsave('outfile.jpg', image_array)\n%\n%scipy.ndimage.imread(fname, flatten=False, mode=None)[source]\n%\n%rand(10, 10)\n%\n\t\n%-------------------------------------------------------------------------------\n\\begin{flushleft} \\small\n\\begin{minipage}{\\linewidth} \\label{scrap2}\n\\protect\\makebox[0ex][r]{\\NWtarget{nuweb2b}{\\rule{0ex}{0ex}}\\hspace{1em}}$\\langle\\,$Generation of bulk array structure\\nobreak\\ {\\footnotesize 2b}$\\,\\rangle\\equiv$\n\\vspace{-1ex}\n\\begin{list}{}{} \\item\n\\mbox{}\\verb@ranges = [shape[k]/structure[k] for k in range(len(shape))]@\\\\\n\\mbox{}\\verb@random_array = randint(0, 255, size=structure)@\\\\\n\\mbox{}\\verb@image_array = numpy.zeros(shape)@\\\\\n\\mbox{}\\verb@for index in scipy.array(CART(AA(range)(shape))):@\\\\\n\\mbox{}\\verb@   block = index/ranges@\\\\\n\\mbox{}\\verb@   if random_array[tuple(block)] < 127:@\\\\\n\\mbox{}\\verb@      image_array[tuple(index)] = 0 @\\\\\n\\mbox{}\\verb@   else: @\\\\\n\\mbox{}\\verb@      image_array[tuple(index)] = 255@\\\\\n\\mbox{}\\verb@@{\\NWsep}\n\\end{list}\n\\vspace{-1ex}\n\\footnotesize\\addtolength{\\baselineskip}{-1ex}\n\\begin{list}{}{\\setlength{\\itemsep}{-\\parsep}\\setlength{\\itemindent}{-\\leftmargin}}\n\\item \\NWtxtMacroRefIn\\ \\NWlink{nuweb2a}{2a}.\n\\end{list}\n\\end{minipage}\\\\[4ex]\n\\end{flushleft}\n%-------------------------------------------------------------------------------\n\n\n\n\\paragraph{Generation of random artefacts upon the image}\n\nThen random noise is added to the previously generated image, in order to produce artifacts at the pixel scale. \n\n%-------------------------------------------------------------------------------\n\\begin{flushleft} \\small\n\\begin{minipage}{\\linewidth} \\label{scrap3}\n\\protect\\makebox[0ex][r]{\\NWtarget{nuweb3a}{\\rule{0ex}{0ex}}\\hspace{1em}}$\\langle\\,$Generation of random artifacts\\nobreak\\ {\\footnotesize 3a}$\\,\\rangle\\equiv$\n\\vspace{-1ex}\n\\begin{list}{}{} \\item\n\\mbox{}\\verb@noiseQuantity = PROD(list(shape))*noiseFraction@\\\\\n\\mbox{}\\verb@k = 0@\\\\\n\\mbox{}\\verb@while k < noiseQuantity:@\\\\\n\\mbox{}\\verb@   index = tuple(AA(randint)(list(shape)))@\\\\\n\\mbox{}\\verb@   if image_array[index] == 0: image_array[index] = 255@\\\\\n\\mbox{}\\verb@   else: image_array[index] = 0@\\\\\n\\mbox{}\\verb@   k += 1@\\\\\n\\mbox{}\\verb@if len(shape)==3:@\\\\\n\\mbox{}\\verb@   for k in range(shape[0]):@\\\\\n\\mbox{}\\verb@      scipy.misc.imsave('tmp/outfile'+str(k).zfill(3)+'.png', image_array[k])@\\\\\n\\mbox{}\\verb@else:@\\\\\n\\mbox{}\\verb@   scipy.misc.imsave('tmp/outfile'+str(k).zfill(3)+'.png', image_array)@\\\\\n\\mbox{}\\verb@@{\\NWsep}\n\\end{list}\n\\vspace{-1ex}\n\\footnotesize\\addtolength{\\baselineskip}{-1ex}\n\\begin{list}{}{\\setlength{\\itemsep}{-\\parsep}\\setlength{\\itemindent}{-\\leftmargin}}\n\\item \\NWtxtMacroRefIn\\ \\NWlink{nuweb2a}{2a}.\n\\end{list}\n\\end{minipage}\\\\[4ex]\n\\end{flushleft}\n%-------------------------------------------------------------------------------\n\n\n\\section{Selection of an image segment}\n\nIn this section we implement several methods for image segmentation and segment selection. \n\n\\subsection{Selection of a test chain}\n\nThe first and simplest method is the selection of the portion of a binary image contained within a masking window.\nHere we select the (white) sub-image contained in a given window, and compute the coordinate representation of the (chain) sub-image.\n\n\\paragraph{Mask definition}\n\nA \\emph{window} within a $d$-image is defined by $2\\times d$ integer numbers (2 multi-indices), corresponding to the window  \\texttt{minPoint} (minimum indices) and to the window \\texttt{maxPoint} (maximum indices). A list of multi-index tuples, contained in the \\texttt{window} variable, is generated by the function \\texttt{setMaskWindow} below.\n\n%-------------------------------------------------------------------------------\n\\begin{flushleft} \\small\n\\begin{minipage}{\\linewidth} \\label{scrap4}\n\\protect\\makebox[0ex][r]{\\NWtarget{nuweb3b}{\\rule{0ex}{0ex}}\\hspace{1em}}$\\langle\\,$Generation of a masking window\\nobreak\\ {\\footnotesize 3b}$\\,\\rangle\\equiv$\n\\vspace{-1ex}\n\\begin{list}{}{} \\item\n\\mbox{}\\verb@def setMaskWindow(window,image_array):@\\\\\n\\mbox{}\\verb@   minPoint, maxPoint = window@\\\\\n\\mbox{}\\verb@   imageShape = list(image_array.shape)@\\\\\n\\mbox{}\\verb@   @\\hbox{$\\langle\\,$Generation of multi-index window\\nobreak\\ {\\footnotesize \\NWlink{nuweb4}{4}}$\\,\\rangle$}\\verb@@\\\\\n\\mbox{}\\verb@   @\\hbox{$\\langle\\,$Window-to-chain mapping\\nobreak\\ {\\footnotesize \\NWlink{nuweb5b}{5b}}$\\,\\rangle$}\\verb@@\\\\\n\\mbox{}\\verb@   @\\hbox{$\\langle\\,$Change chain color to grey\\nobreak\\ {\\footnotesize \\NWlink{nuweb5c}{5c}}$\\,\\rangle$}\\verb@@\\\\\n\\mbox{}\\verb@   return segmentChain@\\\\\n\\mbox{}\\verb@@{\\NWsep}\n\\end{list}\n\\vspace{-1ex}\n\\footnotesize\\addtolength{\\baselineskip}{-1ex}\n\\begin{list}{}{\\setlength{\\itemsep}{-\\parsep}\\setlength{\\itemindent}{-\\leftmargin}}\n\\item \\NWtxtMacroRefIn\\ \\NWlink{nuweb14e}{14e}.\n\\end{list}\n\\end{minipage}\\\\[4ex]\n\\end{flushleft}\n%-------------------------------------------------------------------------------\n\nThe set of tuples of indices contained in a (multidimensional) window is given below.\n \n%-------------------------------------------------------------------------------\n\\begin{flushleft} \\small\n\\begin{minipage}{\\linewidth} \\label{scrap5}\n\\protect\\makebox[0ex][r]{\\NWtarget{nuweb4}{\\rule{0ex}{0ex}}\\hspace{1em}}$\\langle\\,$Generation of multi-index window\\nobreak\\ {\\footnotesize 4}$\\,\\rangle\\equiv$\n\\vspace{-1ex}\n\\begin{list}{}{} \\item\n\\mbox{}\\verb@indexRanges = zip(minPoint,maxPoint)@\\\\\n\\mbox{}\\verb@tuples = CART([range(min,max) for min,max in indexRanges])@\\\\\n\\mbox{}\\verb@@{\\NWsep}\n\\end{list}\n\\vspace{-1ex}\n\\footnotesize\\addtolength{\\baselineskip}{-1ex}\n\\begin{list}{}{\\setlength{\\itemsep}{-\\parsep}\\setlength{\\itemindent}{-\\leftmargin}}\n\\item \\NWtxtMacroRefIn\\ \\NWlink{nuweb3b}{3b}.\n\\end{list}\n\\end{minipage}\\\\[4ex]\n\\end{flushleft}\n%-------------------------------------------------------------------------------\n\n\n\n\\subsection{Mapping of integer tuples to integers}\n\nIn order to produce the coordinate representation of a chain in a multidimensional image (or $d$-image) we need: (a) to choose a basis of image elements, i.e.~of $d$-cells, and in particular to fix an ordering of them; (b) to map the multidimensional index, selecting a single $d$-cell of the image, to a single integer mapping the cell to its linear position within the chosen basis ordering. \n\n\n\\paragraph{Grid of hyper-cubes of unit size}\nLet $S_i=(0,1,...,n_i-1)$ be ordered integer sets with $n_i$ elements, and \n\\[\nS= S_0 \\times S_1 \\times \\cdots \\times S_{d-1}\n\\] \nthe set of indices of elements of a $d$-image.\n\n\\begin{definition}[$d$-image shape]\nThe \\emph{shape} of a $d$-image with $n_0\\times n_1 \\times\\cdots\\times n_{d-1}$ elements (here called \\emph{voxels}) is the ordered set $(n_0, n_1, \\ldots, n_{d-1})$.\n\\end{definition}\n\n\n\\paragraph{$d$-dimensional row-major order}\n\nGiven a $d$-image with shape $S=(n_0,n_1,...,n_{d-1})$ and number of elements $n=\\prod n_i$, \nthe mapping  \n\\[\nS_0 \\times S_1 \\times \\cdots \\times S_{d-1} \\to \\{ 0, 1, \\ldots, n-1\\}\n\\]\n is a {linear combination} with integer {weights}  $(w_0,w_1,...,w_{d-2},1)$, such that:\n\\[\n(i_0,i_1,...,i_{d-1}) \\mapsto i_0 w_0 +i_1 w_1 +\\cdots +i_{d-1} w_{d-1},\n\\]\nwhere \n\\[\nw_k = n_{k+1}  n_{k+2} \\cdots  n_{d-1}, \\qquad 0\\leq k\\leq d-2.\n\\]\n\n\\paragraph{Implementation}\nA functional implementation of the \\emph{Tuples to integers mapping} is given by the second-order  \\texttt{mapTupleToInt} function, that  accepts in a first application the \\texttt{shape} of the image (to compute the tuple space of indices of $d$-cells), and then takes a single tuple in the second application. Of course, the function  returns the cell address in the linear address space associated to the given \\texttt{shape}.\n\n%-------------------------------------------------------------------------------\n\\begin{flushleft} \\small\n\\begin{minipage}{\\linewidth} \\label{scrap6}\n\\protect\\makebox[0ex][r]{\\NWtarget{nuweb5a}{\\rule{0ex}{0ex}}\\hspace{1em}}$\\langle\\,$Tuples to integers mapping\\nobreak\\ {\\footnotesize 5a}$\\,\\rangle\\equiv$\n\\vspace{-1ex}\n\\begin{list}{}{} \\item\n\\mbox{}\\verb@def mapTupleToInt(shape):@\\\\\n\\mbox{}\\verb@   d = len(shape)@\\\\\n\\mbox{}\\verb@   weights = [PROD(shape[(k+1):]) for k in range(d-1)]+[1]@\\\\\n\\mbox{}\\verb@   @\\\\\n\\mbox{}\\verb@   def mapTupleToInt0(tuple):@\\\\\n\\mbox{}\\verb@      return INNERPROD([tuple,weights])@\\\\\n\\mbox{}\\verb@   return mapTupleToInt0@\\\\\n\\mbox{}\\verb@@{\\NWsep}\n\\end{list}\n\\vspace{-1ex}\n\\footnotesize\\addtolength{\\baselineskip}{-1ex}\n\\begin{list}{}{\\setlength{\\itemsep}{-\\parsep}\\setlength{\\itemindent}{-\\leftmargin}}\n\\item \\NWtxtMacroRefIn\\ \\NWlink{nuweb14e}{14e}.\n\\end{list}\n\\end{minipage}\\\\[4ex]\n\\end{flushleft}\n%-------------------------------------------------------------------------------\n\n\n\\paragraph{From tuples multi-indices to chain coordinates}\n\nThe set of address \\texttt{tuples} of $d-cells$ ($d$-dimensional image elements) within the \\emph{mask} is here mapped to the corresponding set of (single) integers associated to the low-level image elements (pixels or voxels, depending on the image dimension and shape), denoted \\texttt{windowChain}. Such total chain of the mask \\texttt{window} is then filtered to contain the only coordinates of \\emph{white} image elements within the window, and returned as the set of integer cell indices \\texttt{segmentChain}.\n\n\n%-------------------------------------------------------------------------------\n\\begin{flushleft} \\small\n\\begin{minipage}{\\linewidth} \\label{scrap7}\n\\protect\\makebox[0ex][r]{\\NWtarget{nuweb5b}{\\rule{0ex}{0ex}}\\hspace{1em}}$\\langle\\,$Window-to-chain mapping\\nobreak\\ {\\footnotesize 5b}$\\,\\rangle\\equiv$\n\\vspace{-1ex}\n\\begin{list}{}{} \\item\n\\mbox{}\\verb@imageCochain = image_array.reshape(PROD(imageShape))@\\\\\n\\mbox{}\\verb@mapping = mapTupleToInt(imageShape)@\\\\\n\\mbox{}\\verb@windowChain = [mapping(tuple) for tuple in tuples]@\\\\\n\\mbox{}\\verb@segmentChain = [cell for cell in windowChain if imageCochain[cell]==255]@\\\\\n\\mbox{}\\verb@@{\\NWsep}\n\\end{list}\n\\vspace{-1ex}\n\\footnotesize\\addtolength{\\baselineskip}{-1ex}\n\\begin{list}{}{\\setlength{\\itemsep}{-\\parsep}\\setlength{\\itemindent}{-\\leftmargin}}\n\\item \\NWtxtMacroRefIn\\ \\NWlink{nuweb3b}{3b}.\n\\end{list}\n\\end{minipage}\\\\[4ex]\n\\end{flushleft}\n%-------------------------------------------------------------------------------\n\n\\subsection{Show segment chain on binary image}\n\nNow we need to show visually the selected \\texttt{segmentChain}, by change the color of its cells from white (255) to middle grey (127). Just remember that \\texttt{imageCochain} is the linear representation of the image, with number of cells equal to \\texttt{PROD(imageShape)}. Then the modified image is restored within \\texttt{image\\_array}, and is finally exported to a \\texttt{.png} image file.\n\n%-------------------------------------------------------------------------------\n\\begin{flushleft} \\small\n\\begin{minipage}{\\linewidth} \\label{scrap8}\n\\protect\\makebox[0ex][r]{\\NWtarget{nuweb5c}{\\rule{0ex}{0ex}}\\hspace{1em}}$\\langle\\,$Change chain color to grey\\nobreak\\ {\\footnotesize 5c}$\\,\\rangle\\equiv$\n\\vspace{-1ex}\n\\begin{list}{}{} \\item\n\\mbox{}\\verb@for cell in segmentChain: imageCochain[cell] = 127@\\\\\n\\mbox{}\\verb@image_array = imageCochain.reshape(imageShape)@\\\\\n\\mbox{}\\verb@#for k in range(shape[0]):@\\\\\n\\mbox{}\\verb@#  scipy.misc.imsave('tmp/outfile'+str(k).zfill(3)+'.png', image_array[k])@\\\\\n\\mbox{}\\verb@@{\\NWsep}\n\\end{list}\n\\vspace{-1ex}\n\\footnotesize\\addtolength{\\baselineskip}{-1ex}\n\\begin{list}{}{\\setlength{\\itemsep}{-\\parsep}\\setlength{\\itemindent}{-\\leftmargin}}\n\\item \\NWtxtMacroRefIn\\ \\NWlink{nuweb3b}{3b}.\n\\end{list}\n\\end{minipage}\\\\[4ex]\n\\end{flushleft}\n%-------------------------------------------------------------------------------\n\n\n\\section{Construction of (co)boundary operators}\n\nA $d$-image is a \\emph{cellular $d$-complex} where cells are $k$-cuboids ($0\\leq k\\leq d$), i.e.~Cartesian products of a number $k$ of 1D intervals, embedded in $d$-dimensional Euclidean space. \n\n\n\\subsection{Reading and writing LAR of image from disk}\nSince the construction of the \\emph{chain complex} supported by a cellular complex with $O(n^d)$ $d$-cells---and $n=O(10^3)$---may be really time-consuming, it is unquestionably useful to store on disk, once and for all, the topological model of a multidimensional image, i.e.~the LAR of its chain complex,  and just restore it (or the needed part of it --- TODO) when necessary, since \\emph{it only depends on the \\texttt{shape} of a $d$-image}, i.e.~from the array arrangement of its $d$-cells (``hypervoxels'').\n\n%-------------------------------------------------------------------------------\n\\begin{flushleft} \\small\n\\begin{minipage}{\\linewidth} \\label{scrap9}\n\\protect\\makebox[0ex][r]{\\NWtarget{nuweb6}{\\rule{0ex}{0ex}}\\hspace{1em}}$\\langle\\,$Save and restore data object from file\\nobreak\\ {\\footnotesize 6}$\\,\\rangle\\equiv$\n\\vspace{-1ex}\n\\begin{list}{}{} \\item\n\\mbox{}\\verb@def dump(object,filename):@\\\\\n\\mbox{}\\verb@   with open(filename, 'wb') as f:@\\\\\n\\mbox{}\\verb@       pickle.dump(object, f)@\\\\\n\\mbox{}\\verb@       @\\\\\n\\mbox{}\\verb@def load(filename):@\\\\\n\\mbox{}\\verb@   with open(filename, 'rb') as f:@\\\\\n\\mbox{}\\verb@       object = pickle.load(f)@\\\\\n\\mbox{}\\verb@   return object@\\\\\n\\mbox{}\\verb@@{\\NWsep}\n\\end{list}\n\\vspace{-1ex}\n\\footnotesize\\addtolength{\\baselineskip}{-1ex}\n\\begin{list}{}{\\setlength{\\itemsep}{-\\parsep}\\setlength{\\itemindent}{-\\leftmargin}}\n\\item \\NWtxtMacroRefIn\\ \\NWlink{nuweb14e}{14e}.\n\\end{list}\n\\end{minipage}\\\\[4ex]\n\\end{flushleft}\n%-------------------------------------------------------------------------------\n\n\n%-------------------------------------------------------------------------------\n\\begin{flushleft} \\small\n\\begin{minipage}{\\linewidth} \\label{scrap10}\n\\protect\\makebox[0ex][r]{\\NWtarget{nuweb7a}{\\rule{0ex}{0ex}}\\hspace{1em}}$\\langle\\,$Save or restore the chain complex of multidimensional image\\nobreak\\ {\\footnotesize 7a}$\\,\\rangle\\equiv$\n\\vspace{-1ex}\n\\begin{list}{}{} \\item\n\\mbox{}\\verb@def imageChainComplex (shape):@\\\\\n\\mbox{}\\verb@   tokens = str(shape)[1:-1].split(',')@\\\\\n\\mbox{}\\verb@   tokens = [token.strip() for token in tokens]@\\\\\n\\mbox{}\\verb@   filename = \"tmp/larimage-\" + \"-\".join(tokens) + \".pickle\"@\\\\\n\\mbox{}\\verb@   @\\\\\n\\mbox{}\\verb@   if os.path.isfile(filename):@\\\\\n\\mbox{}\\verb@      shape, skeletons, operators = loadImageLAR(filename)@\\\\\n\\mbox{}\\verb@   else:@\\\\\n\\mbox{}\\verb@      skeletons = gridSkeletons(list(shape))@\\\\\n\\mbox{}\\verb@      operators = boundaryOps(skeletons)@\\\\\n\\mbox{}\\verb@      imageLAR = (shape, skeletons, operators)@\\\\\n\\mbox{}\\verb@      dump(imageLAR,filename)@\\\\\n\\mbox{}\\verb@      print \"filename =\",filename@\\\\\n\\mbox{}\\verb@   return shape, skeletons, operators@\\\\\n\\mbox{}\\verb@   @\\\\\n\\mbox{}\\verb@def loadImageLAR(filename):@\\\\\n\\mbox{}\\verb@   object = load(filename)@\\\\\n\\mbox{}\\verb@   shape, skeletons, operators = object@\\\\\n\\mbox{}\\verb@   return shape, skeletons, operators@\\\\\n\\mbox{}\\verb@@{\\NWsep}\n\\end{list}\n\\vspace{-1ex}\n\\footnotesize\\addtolength{\\baselineskip}{-1ex}\n\\begin{list}{}{\\setlength{\\itemsep}{-\\parsep}\\setlength{\\itemindent}{-\\leftmargin}}\n\\item \\NWtxtMacroRefIn\\ \\NWlink{nuweb14e}{14e}.\n\\end{list}\n\\end{minipage}\\\\[4ex]\n\\end{flushleft}\n%-------------------------------------------------------------------------------\n\t\n\n\n\n\\subsection{LAR chain complex construction}\n\nIn our first multidimensional implementation of morphological operators through algebraic topology of the image seen as a cellular complex, we compute the whole sequence of characteristic matrices $M_k$ ($0\\leq k \\leq d$) in \\texttt{BRC} form, and the whole sequence of matrices $[\\partial_k]$ ($0\\leq k \\leq d$) in \\texttt{CSR} form.\n\n\\begin{figure}[htbp] %  figure placement: here, top, bottom, or page\n   \\centering\n   \\includegraphics[width=0.7\\linewidth]{images/larcomplex} \n   \\caption{The LAR definition of  a chain complex: a sequence of characteristic matrices \\emph{and} a sequence of boundary operators.}\n   \\label{fig:example}\n\\end{figure}\n\n\\paragraph{Array of characteristic matrices}\n\nA direct construction of cuboidal complexes is offered, within the \\texttt{larcc} package, by the \\texttt{largrid.larCuboids} function. \n\n%-------------------------------------------------------------------------------\n\\begin{flushleft} \\small\n\\begin{minipage}{\\linewidth} \\label{scrap11}\n\\protect\\makebox[0ex][r]{\\NWtarget{nuweb7b}{\\rule{0ex}{0ex}}\\hspace{1em}}$\\langle\\,$Characteristic matrices of multidimensional image\\nobreak\\ {\\footnotesize 7b}$\\,\\rangle\\equiv$\n\\vspace{-1ex}\n\\begin{list}{}{} \\item\n\\mbox{}\\verb@def larImage(shape):@\\\\\n\\mbox{}\\verb@   \"\"\" Compute vertices and skeletons of an image of given shape \"\"\"@\\\\\n\\mbox{}\\verb@   imageVerts = larImageVerts(shape)@\\\\\n\\mbox{}\\verb@   skeletons = gridSkeletons(list(shape))@\\\\\n\\mbox{}\\verb@   return imageVerts, skeletons@\\\\\n\\mbox{}\\verb@@{\\NWsep}\n\\end{list}\n\\vspace{-1ex}\n\\footnotesize\\addtolength{\\baselineskip}{-1ex}\n\\begin{list}{}{\\setlength{\\itemsep}{-\\parsep}\\setlength{\\itemindent}{-\\leftmargin}}\n\\item \\NWtxtMacroRefIn\\ \\NWlink{nuweb14e}{14e}.\n\\end{list}\n\\end{minipage}\\\\[4ex]\n\\end{flushleft}\n%-------------------------------------------------------------------------------\n\n\\paragraph{Example}\nConsider a (very!) small 3D image of \\texttt{shape=(2,2,2)}. The data structures returned by the \\texttt{larImage} function are shown below, where \\texttt{imageVerts} gives the integer coordinates of vertices of the 3D (image) complex, and \\texttt{skeletons} is the list of characteristic matrices $M_k$ ($0\\leq k\\leq d$) in \\texttt{BRC} form.\n\n%-------------------------------------------------------------------------------\n\\begin{flushleft} \\small \\label{scrap12}\n\\protect\\makebox[0ex][r]{\\NWtarget{nuweb8}{\\rule{0ex}{0ex}}\\hspace{1em}}$\\langle\\,$Example of characteristic matrices (and vertices) of multidimensional image\\nobreak\\ {\\footnotesize 8}$\\,\\rangle\\equiv$\n\\vspace{-1ex}\n\\begin{list}{}{} \\item\n\\mbox{}\\verb@imageVerts, skeletons = larImage((2,2,2))@\\\\\n\\mbox{}\\verb@@\\\\\n\\mbox{}\\verb@print imageVerts,@\\\\\n\\mbox{}\\verb@>>> [[0,0,0],[0,0,1],[0,0,2],[0,1,0],[0,1,1],[0,1,2],[0,2,0],[0,2,1],[0,2,2],@\\\\\n\\mbox{}\\verb@[1,0,0],[1,0,1],[1,0,2],[1,1,0],[1,1,1],[1,1,2],[1,2,0],[1,2,1],[1,2,2],[2,0,@\\\\\n\\mbox{}\\verb@0],[2,0,1],[2,0,2],[2,1,0],[2,1,1],[2,1,2],[2,2,0],[2,2,1],[2,2,2]]@\\\\\n\\mbox{}\\verb@@\\\\\n\\mbox{}\\verb@print skeletons[1:],@\\\\\n\\mbox{}\\verb@>>> [@\\\\\n\\mbox{}\\verb@[[0,1],[1,2],[3,4],[4,5],[6,7],[7,8],[9,10],[10,11],[12,13],[13,14],[15,@\\\\\n\\mbox{}\\verb@16],[16,17],[18,19],[19,20],[21,22],[22,23],[24,25],[25,26],[0,3],[1,4],[2,@\\\\\n\\mbox{}\\verb@5],[3,6],[4,7],[5,8],[9,12],[10,13],[11,14],[12,15],[13,16],[14,17],[18,21],@\\\\\n\\mbox{}\\verb@[19,22],[20,23],[21,24],[22,25],[23,26],[0,9],[1,10],[2,11],[3,12],[4,13],[5,@\\\\\n\\mbox{}\\verb@14],[6,15],[7,16],[8,17],[9,18],[10,19],[11,20],[12,21],[13,22],[14,23],[15,@\\\\\n\\mbox{}\\verb@24],[16,25],[17,26]],@\\\\\n\\mbox{}\\verb@[[0,1,3,4],[1,2,4,5],[3,4,6,7],[4,5,7,8],[9,10,12,13],[10,11,13,14],[12,13,15,@\\\\\n\\mbox{}\\verb@16],[13,14,16,17],[18,19,21,22],[19,20,22,23],[21,22,24,25],[22,23,25,26],[0,@\\\\\n\\mbox{}\\verb@1,9,10],[1,2,10,11],[3,4,12,13],[4,5,13,14],[6,7,15,16],[7,8,16,17],[9,10,18,@\\\\\n\\mbox{}\\verb@19],[10,11,19,20],[12,13,21,22],[13,14,22,23],[15,16,24,25],[16,17,25,26],[0,@\\\\\n\\mbox{}\\verb@3,9,12],[1,4,10,13],[2,5,11,14],[3,6,12,15],[4,7,13,16],[5,8,14,17],[9,12,18,@\\\\\n\\mbox{}\\verb@21],[10,13,19,22],[11,14,20,23],[12,15,21,24],[13,16,22,25],[14,17,23,26]],@\\\\\n\\mbox{}\\verb@[[0,1,3,4,9,10,12,13],[1,2,4,5,10,11,13,14],[3,4,6,7,12,13,15,16],[4,5,7,8,13,@\\\\\n\\mbox{}\\verb@14,16,17],[9,10,12,13,18,19,21,22],[10,11,13,14,19,20,22,23],[12,13,15,16,21,@\\\\\n\\mbox{}\\verb@22,24,25],[13,14,16,17,22,23,25,26]]@\\\\\n\\mbox{}\\verb@]@\\\\\n\\mbox{}\\verb@@{\\NWsep}\n\\end{list}\n\\vspace{-1ex}\n\\footnotesize\\addtolength{\\baselineskip}{-1ex}\n\\begin{list}{}{\\setlength{\\itemsep}{-\\parsep}\\setlength{\\itemindent}{-\\leftmargin}}\n\\item {\\NWtxtMacroNoRef}.\n\\end{list}\n\\end{flushleft}\n%-------------------------------------------------------------------------------\n\n\n\\paragraph{Array of matrices of boundary operators}\n\nThe function \\texttt{boundaryOps} takes the array of \\texttt{BRC} reprs of characteristic matrices, and returns the array of \\texttt{CSR} matrix reprs of boundary operators $\\partial_k$ ($1\\leq k\\leq d$).\n\n%-------------------------------------------------------------------------------\n\\begin{flushleft} \\small\n\\begin{minipage}{\\linewidth} \\label{scrap13}\n\\protect\\makebox[0ex][r]{\\NWtarget{nuweb9a}{\\rule{0ex}{0ex}}\\hspace{1em}}$\\langle\\,$CSR matrices of boundary operators\\nobreak\\ {\\footnotesize 9a}$\\,\\rangle\\equiv$\n\\vspace{-1ex}\n\\begin{list}{}{} \\item\n\\mbox{}\\verb@def boundaryOps(skeletons):@\\\\\n\\mbox{}\\verb@   \"\"\" CSR matrices of boundary operators from list of skeletons \"\"\"@\\\\\n\\mbox{}\\verb@   return [larBoundary(skeletons[k+1],faces) @\\\\\n\\mbox{}\\verb@      for k,faces in enumerate(skeletons[:-1])]@\\\\\n\\mbox{}\\verb@@{\\NWsep}\n\\end{list}\n\\vspace{-1ex}\n\\footnotesize\\addtolength{\\baselineskip}{-1ex}\n\\begin{list}{}{\\setlength{\\itemsep}{-\\parsep}\\setlength{\\itemindent}{-\\leftmargin}}\n\\item \\NWtxtMacroRefIn\\ \\NWlink{nuweb14e}{14e}.\n\\end{list}\n\\end{minipage}\\\\[4ex]\n\\end{flushleft}\n%-------------------------------------------------------------------------------\n\n\n\\paragraph{Boundary chain of a $k$-chain of a $d$-image}\n\n%-------------------------------------------------------------------------------\n\\begin{flushleft} \\small\n\\begin{minipage}{\\linewidth} \\label{scrap14}\n\\protect\\makebox[0ex][r]{\\NWtarget{nuweb9b}{\\rule{0ex}{0ex}}\\hspace{1em}}$\\langle\\,$Boundary of image chain computation\\nobreak\\ {\\footnotesize 9b}$\\,\\rangle\\equiv$\n\\vspace{-1ex}\n\\begin{list}{}{} \\item\n\\mbox{}\\verb@def imageChainBoundary(shape, operators):@\\\\\n\\mbox{}\\verb@   imageVerts, skeletons = larImage(shape)@\\\\\n\\mbox{}\\verb@   # operators = boundaryOps(skeletons)@\\\\\n\\mbox{}\\verb@   cellNumber = PROD(list(shape))@\\\\\n\\mbox{}\\verb@   @\\\\\n\\mbox{}\\verb@   def imageChainBoundary0(k):@\\\\\n\\mbox{}\\verb@      csrBoundaryMat = operators[-1]@\\\\\n\\mbox{}\\verb@      facets = skeletons[k-1]@\\\\\n\\mbox{}\\verb@      @\\\\\n\\mbox{}\\verb@      def imageChainBoundary1(chain):@\\\\\n\\mbox{}\\verb@         @\\hbox{$\\langle\\,$Boundary*chain product and interpretation\\nobreak\\ {\\footnotesize \\NWlink{nuweb10a}{10a}}$\\,\\rangle$}\\verb@@\\\\\n\\mbox{}\\verb@         boundaryChainModel = imageVerts, [facets[h] for h in boundaryChain]     @\\\\\n\\mbox{}\\verb@         return boundaryChainModel,boundaryChain@\\\\\n\\mbox{}\\verb@      @\\\\\n\\mbox{}\\verb@      return imageChainBoundary1@\\\\\n\\mbox{}\\verb@   return imageChainBoundary0@\\\\\n\\mbox{}\\verb@@{\\NWsep}\n\\end{list}\n\\vspace{-1ex}\n\\footnotesize\\addtolength{\\baselineskip}{-1ex}\n\\begin{list}{}{\\setlength{\\itemsep}{-\\parsep}\\setlength{\\itemindent}{-\\leftmargin}}\n\\item \\NWtxtMacroRefIn\\ \\NWlink{nuweb14e}{14e}.\n\\end{list}\n\\end{minipage}\\\\[4ex]\n\\end{flushleft}\n%-------------------------------------------------------------------------------\n\n\\paragraph{Low-level SpMSpV matrix-chain product}\n\nA low-level implementation of the product of boundary matrix times the coordinate representation of the image chain under consideration is given below. It was enveloped and protected in this macro because it is strongly dependent on the CSR structures and tools provided by the sparse matrix module of the \\texttt{scipy} library.\t\n\n%-------------------------------------------------------------------------------\n\\begin{flushleft} \\small\n\\begin{minipage}{\\linewidth} \\label{scrap15}\n\\protect\\makebox[0ex][r]{\\NWtarget{nuweb10a}{\\rule{0ex}{0ex}}\\hspace{1em}}$\\langle\\,$Boundary*chain product and interpretation\\nobreak\\ {\\footnotesize 10a}$\\,\\rangle\\equiv$\n\\vspace{-1ex}\n\\begin{list}{}{} \\item\n\\mbox{}\\verb@csrChain = scipy.sparse.csr_matrix((cellNumber,1))@\\\\\n\\mbox{}\\verb@for h in chain: csrChain[h,0] = 1@\\\\\n\\mbox{}\\verb@csrBoundaryChain = matrixProduct(csrBoundaryMat, csrChain)@\\\\\n\\mbox{}\\verb@for h,value in enumerate(csrBoundaryChain.data):@\\\\\n\\mbox{}\\verb@   if MOD([value,2]) == 0: csrBoundaryChain.data[h] = 0@\\\\\n\\mbox{}\\verb@cooBoundaryChain = csrBoundaryChain.tocoo()@\\\\\n\\mbox{}\\verb@boundaryChain = [cooBoundaryChain.row[h] @\\\\\n\\mbox{}\\verb@   for h,val in enumerate(cooBoundaryChain.data) if val == 1]@\\\\\n\\mbox{}\\verb@@{\\NWsep}\n\\end{list}\n\\vspace{-1ex}\n\\footnotesize\\addtolength{\\baselineskip}{-1ex}\n\\begin{list}{}{\\setlength{\\itemsep}{-\\parsep}\\setlength{\\itemindent}{-\\leftmargin}}\n\\item \\NWtxtMacroRefIn\\ \\NWlink{nuweb9b}{9b}.\n\\end{list}\n\\end{minipage}\\\\[4ex]\n\\end{flushleft}\n%-------------------------------------------------------------------------------\n\n\n\\subsection{Visualisation of an image chain and its boundary}\n\n\n\\paragraph{$d$-Chain visualisation}\n\nThe \\texttt{visImageChain} function given by the macro \\emph{Visualisation of an image chain} below. \n\n%-------------------------------------------------------------------------------\n\\begin{flushleft} \\small\n\\begin{minipage}{\\linewidth} \\label{scrap16}\n\\protect\\makebox[0ex][r]{\\NWtarget{nuweb10b}{\\rule{0ex}{0ex}}\\hspace{1em}}$\\langle\\,$Pyplasm visualisation of an image chain\\nobreak\\ {\\footnotesize 10b}$\\,\\rangle\\equiv$\n\\vspace{-1ex}\n\\begin{list}{}{} \\item\n\\mbox{}\\verb@def visImageChain (shape,chain, imageVerts, skeletons):@\\\\\n\\mbox{}\\verb@   # imageVerts, skeletons = larImage(shape)@\\\\\n\\mbox{}\\verb@   chainLAR = [cell for k,cell in enumerate(skeletons[-1]) if k in chain]@\\\\\n\\mbox{}\\verb@   return imageVerts,chainLAR@\\\\\n\\mbox{}\\verb@@{\\NWsep}\n\\end{list}\n\\vspace{-1ex}\n\\footnotesize\\addtolength{\\baselineskip}{-1ex}\n\\begin{list}{}{\\setlength{\\itemsep}{-\\parsep}\\setlength{\\itemindent}{-\\leftmargin}}\n\\item \\NWtxtMacroRefIn\\ \\NWlink{nuweb14e}{14e}.\n\\end{list}\n\\end{minipage}\\\\[4ex]\n\\end{flushleft}\n%-------------------------------------------------------------------------------\n\n\n\\begin{figure}[htbp] %  figure placement: here, top, bottom, or page\n   \\centering\n   \\includegraphics[height=0.3\\linewidth,width=0.16\\linewidth]{images/morph-chain2D1} \n   \\includegraphics[height=0.3\\linewidth,width=0.16\\linewidth]{images/morph-chain1D1} \n   \\includegraphics[height=0.3\\linewidth,width=0.16\\linewidth]{images/morph-chain2D2} \n   \\includegraphics[height=0.3\\linewidth,width=0.16\\linewidth]{images/morph-chain1D2} \n   \\includegraphics[height=0.3\\linewidth,width=0.16\\linewidth]{images/morph-chain2D3} \n   \\includegraphics[height=0.3\\linewidth,width=0.16\\linewidth]{images/morph-chain1D3} \n   \\caption{example caption}\n   \\label{fig:morph}\n\\end{figure}\n\n\n\\section{The bulk of morphological imaging}\n\nThe main part of the implementation of our algebraic construction of morphological operators on $d$-images is given in this section. First we introduce two generalized incidence operators, respectively named \\emph{$\\mathcal{U}_d$}, which stands for \\emph{Upper}, and \\emph{$\\mathcal{L}_d$}, which stands for \\emph{Lower}. Then we implement the standard morphological operators of Dilation (\\emph{$\\mathcal{D}_d$}), Erosion (\\emph{$\\mathcal{E}_d$}), Opening (\\emph{$\\mathcal{O}_d$}), and Closing (\\emph{$\\mathcal{C}_d$}).\n\n\\subsection{``Down'' and ``Up'' operators on Chains}\n\nThe Up and Down incidence operators are defined as mapping $d$-cells to $(d+1)$- and $(d+1)$-cells that, respectively, share vertices with them:\n\\[\n\\mathcal{U}_d : C_d \\to C_{d+1}, \\qquad \\mathcal{D}_d : C_d \\to C_{d-1}.\n\\]\n\nRemembering that the characteristic matrix $M_d$ corresponds to the mapping from vertices to $d$-cells, we have\n\\[\n[\\mathcal{U}_d] = M_{d+1}\\,M_d^t, \\qquad [\\mathcal{D}_d] = M_{d-1}\\,M_d^t.\n\\]\n\n\\paragraph{Down and Up operators} Just consider that the characteristic matrices $M_{d-1},M_{d},M_{d+1}$,  stored in position $d-1$, $d$, and $d+1$ of the \\texttt{skeletons} array, respectively provide the subsets of vertices of proper dimensions incising on each cell. They are used to compute the topological incidence operators, according to the paper~\\cite{Dicarlo:2014:TNL:2543138.2543294}.\n\n%-------------------------------------------------------------------------------\n\\begin{flushleft} \\small\n\\begin{minipage}{\\linewidth} \\label{scrap17}\n\\protect\\makebox[0ex][r]{\\NWtarget{nuweb11}{\\rule{0ex}{0ex}}\\hspace{1em}}$\\langle\\,$Down and Up operators\\nobreak\\ {\\footnotesize 11}$\\,\\rangle\\equiv$\n\\vspace{-1ex}\n\\begin{list}{}{} \\item\n\\mbox{}\\verb@def larDown(skeletons,d):@\\\\\n\\mbox{}\\verb@   \"\"\" Down operator, to multiply a d-chain and return the incident (d-1)-chain \"\"\"@\\\\\n\\mbox{}\\verb@   csrMd = csrCreate(skeletons[d])@\\\\\n\\mbox{}\\verb@   csrMinus = csrCreate(skeletons[d-1])@\\\\\n\\mbox{}\\verb@   csrDown = matrixProduct(csrMinus,csrTranspose(csrMd))@\\\\\n\\mbox{}\\verb@   return csrDown@\\\\\n\\mbox{}\\verb@   @\\\\\n\\mbox{}\\verb@def larUp(skeletons,d):@\\\\\n\\mbox{}\\verb@   \"\"\" Up operator, to multiply a d-chain and return the incident (d+1)-chain \"\"\"@\\\\\n\\mbox{}\\verb@   csrMd = csrCreate(skeletons[d])@\\\\\n\\mbox{}\\verb@   csrPlus = csrCreate(skeletons[d+1])@\\\\\n\\mbox{}\\verb@   csrUp = matrixProduct(csrPlus,csrTranspose(csrMd))@\\\\\n\\mbox{}\\verb@   return csrUp   @\\\\\n\\mbox{}\\verb@@{\\NWsep}\n\\end{list}\n\\vspace{-1ex}\n\\footnotesize\\addtolength{\\baselineskip}{-1ex}\n\\begin{list}{}{\\setlength{\\itemsep}{-\\parsep}\\setlength{\\itemindent}{-\\leftmargin}}\n\\item \\NWtxtMacroRefIn\\ \\NWlink{nuweb14e}{14e}.\n\\end{list}\n\\end{minipage}\\\\[4ex]\n\\end{flushleft}\n%-------------------------------------------------------------------------------\n\n\\paragraph{The $\\mathcal{UUD}$ operator}\nA generic $\\mathcal{UUD}: C_{d-1} \\to C_{d}$ operator is given to be associated with the boundary $\\partial_2$, in order to return the $\\mathcal{ERO}\\cup\\mathcal{DIL}$ (TODO:correct) of a $d$-chain.\n\n%-------------------------------------------------------------------------------\n\\begin{flushleft} \\small\n\\begin{minipage}{\\linewidth} \\label{scrap18}\n\\protect\\makebox[0ex][r]{\\NWtarget{nuweb12a}{\\rule{0ex}{0ex}}\\hspace{1em}}$\\langle\\,$UUD operator: maps Down-UP-UP its input chains\\nobreak\\ {\\footnotesize 12a}$\\,\\rangle\\equiv$\n\\vspace{-1ex}\n\\begin{list}{}{} \\item\n\\mbox{}\\verb@def UUD(skeletons,d):@\\\\\n\\mbox{}\\verb@   \"\"\" Compute the morphological operator UUP.@\\\\\n\\mbox{}\\verb@      Return a CSR matrix to be applied to the coordinate representation of a chain@\\\\\n\\mbox{}\\verb@   \"\"\" @\\\\\n\\mbox{}\\verb@   D = larDown(skeletons,d)@\\\\\n\\mbox{}\\verb@   U1 = larUp(skeletons,d-1)@\\\\\n\\mbox{}\\verb@   U2 = larUp(skeletons,d)@\\\\\n\\mbox{}\\verb@   UUDout = matrixProduct(U2,matrixProduct(U1,D))@\\\\\n\\mbox{}\\verb@   return D,U1,U2,UUDout@\\\\\n\\mbox{}\\verb@@{\\NWsep}\n\\end{list}\n\\vspace{-1ex}\n\\footnotesize\\addtolength{\\baselineskip}{-1ex}\n\\begin{list}{}{\\setlength{\\itemsep}{-\\parsep}\\setlength{\\itemindent}{-\\leftmargin}}\n\\item \\NWtxtMacroRefIn\\ \\NWlink{nuweb14e}{14e}.\n\\end{list}\n\\end{minipage}\\\\[4ex]\n\\end{flushleft}\n%-------------------------------------------------------------------------------\n\nA pair of similar function \\texttt{testAlgebraicMorphology} and \\texttt{testAlgebraicMorphologyStepByStep} are given here, both accepting the same (redundant) inputs, in order to test our algebraic approach to mathematical morphology. In particular: \n\n%\\item\n%\\texttt{solid} is the LAR model (i.e.~the pair (\\texttt{V},\\texttt{CV})) of the original image;\n%\\item\n%\\texttt{b_rep} is the LAR model of its boundary (\\texttt{V},\\texttt{BV});\n%\\item\n%\\texttt{chain} is the $d$-chain of the image, given as the list of indices of $(d-1)$-cells within the boundary's $(d-1)$-chain;\n%\\item\n%\\texttt{imageVerts} \n%\\item\n%\\texttt{skeletons} \n\n%-------------------------------------------------------------------------------\n\\begin{flushleft} \\small\n\\begin{minipage}{\\linewidth} \\label{scrap19}\n\\protect\\makebox[0ex][r]{\\NWtarget{nuweb12b}{\\rule{0ex}{0ex}}\\hspace{1em}}$\\langle\\,$Testing the algebraic morphology\\nobreak\\ {\\footnotesize 12b}$\\,\\rangle\\equiv$\n\\vspace{-1ex}\n\\begin{list}{}{} \\item\n\\mbox{}\\verb@def testAlgebraicMorphology (solid, b_rep, chain, imageVerts, skeletons):@\\\\\n\\mbox{}\\verb@   d = len(skeletons)-1@\\\\\n\\mbox{}\\verb@   D,U1,U2,csrMorphOp = UUD(skeletons,d-1)@\\\\\n\\mbox{}\\verb@   outputChain = chainTransform(skeletons,1,chain,csrMorphOp,d)@\\\\\n\\mbox{}\\verb@   chainLAR = [cell for k,cell in enumerate(skeletons[d]) if k in outputChain]@\\\\\n\\mbox{}\\verb@   model2 = (imageVerts,chainLAR)@\\\\\n\\mbox{}\\verb@   return imageVerts,chainLAR@\\\\\n\\mbox{}\\verb@@{\\NWsep}\n\\end{list}\n\\vspace{-1ex}\n\\footnotesize\\addtolength{\\baselineskip}{-1ex}\n\\begin{list}{}{\\setlength{\\itemsep}{-\\parsep}\\setlength{\\itemindent}{-\\leftmargin}}\n\\item \\NWtxtMacroRefIn\\ \\NWlink{nuweb14e}{14e}.\n\\end{list}\n\\end{minipage}\\\\[4ex]\n\\end{flushleft}\n%-------------------------------------------------------------------------------\n\n%-------------------------------------------------------------------------------\n\\begin{flushleft} \\small\n\\begin{minipage}{\\linewidth} \\label{scrap20}\n\\protect\\makebox[0ex][r]{\\NWtarget{nuweb13a}{\\rule{0ex}{0ex}}\\hspace{1em}}$\\langle\\,$Testing the algebraic morphology method step-by-step\\nobreak\\ {\\footnotesize 13a}$\\,\\rangle\\equiv$\n\\vspace{-1ex}\n\\begin{list}{}{} \\item\n\\mbox{}\\verb@def testAlgebraicMorphologyStepByStep (solid, b_rep, chain, imageVerts, skeletons):@\\\\\n\\mbox{}\\verb@   d = len(skeletons)-1@\\\\\n\\mbox{}\\verb@   D,U1,U2,csrMorphOp = UUD(skeletons,d-1)@\\\\\n\\mbox{}\\verb@   @\\\\\n\\mbox{}\\verb@   VIEW(EXPLODE(1.5,1.5,1)(MKPOLS(solid)))@\\\\\n\\mbox{}\\verb@   VIEW(COLOR(MAGENTA)(STRUCT(MKPOLS(b_rep))))@\\\\\n\\mbox{}\\verb@   @\\\\\n\\mbox{}\\verb@   outputChain = chainTransform(skeletons,d-1,chain,D,d-1)@\\\\\n\\mbox{}\\verb@   chainLAR = [cell for k,cell in enumerate(skeletons[0]) if k in outputChain]@\\\\\n\\mbox{}\\verb@   model0 = (imageVerts,chainLAR)@\\\\\n\\mbox{}\\verb@   VIEW(COLOR(RED)(STRUCT(MKPOLS(model0))))@\\\\\n\\mbox{}\\verb@   @\\\\\n\\mbox{}\\verb@   M2 = csrCreate(skeletons[d])@\\\\\n\\mbox{}\\verb@   @\\\\\n\\mbox{}\\verb@   outputChain = chainTransform(skeletons,0,outputChain,M2,d)@\\\\\n\\mbox{}\\verb@   chainLAR = [cell for k,cell in enumerate(skeletons[d]) if k in outputChain]@\\\\\n\\mbox{}\\verb@   model2 = (imageVerts,chainLAR)@\\\\\n\\mbox{}\\verb@   VIEW(COLOR(YELLOW)(STRUCT(MKPOLS(model2))))@\\\\\n\\mbox{}\\verb@   @\\\\\n\\mbox{}\\verb@   return imageVerts,chainLAR@\\\\\n\\mbox{}\\verb@@{\\NWsep}\n\\end{list}\n\\vspace{-1ex}\n\\footnotesize\\addtolength{\\baselineskip}{-1ex}\n\\begin{list}{}{\\setlength{\\itemsep}{-\\parsep}\\setlength{\\itemindent}{-\\leftmargin}}\n\\item \\NWtxtMacroRefIn\\ \\NWlink{nuweb14e}{14e}.\n\\end{list}\n\\end{minipage}\\\\[4ex]\n\\end{flushleft}\n%-------------------------------------------------------------------------------\n\n\\paragraph{Boundary chain mapping}\nThe function \\texttt{chainTransform} takes as input a \\texttt{chain} of dimension \\texttt{d} (actually the boundary of a chain of dimension $d+1$), the \\texttt{skeletons} array of \\texttt{BRC} representations of matrices $M_k$ ($0\\leq k\\leq d+1$), and the number $n$ that $(d+1)$-cells resulting by multiplication with the operator's matrix \\texttt{csrMatrix} must ahare with they incident $d$-cells in order to be included in the output of the considered algebraic morphology operator.\n\n%-------------------------------------------------------------------------------\n\\begin{flushleft} \\small\n\\begin{minipage}{\\linewidth} \\label{scrap21}\n\\protect\\makebox[0ex][r]{\\NWtarget{nuweb13b}{\\rule{0ex}{0ex}}\\hspace{1em}}$\\langle\\,$csrMatrix*chain product and interpretation\\nobreak\\ {\\footnotesize 13b}$\\,\\rangle\\equiv$\n\\vspace{-1ex}\n\\begin{list}{}{} \\item\n\\mbox{}\\verb@@\\\\\n\\mbox{}\\verb@def chainTransform(skeletons,d,chain,csrMatrix,n):@\\\\\n\\mbox{}\\verb@   # n: number of vertices shared in the incidence relation@\\\\\n\\mbox{}\\verb@   cellNumber = len(skeletons[d])@\\\\\n\\mbox{}\\verb@   csrChain = scipy.sparse.csr_matrix((cellNumber,1))@\\\\\n\\mbox{}\\verb@   for h in chain: csrChain[h,0] = 1@\\\\\n\\mbox{}\\verb@   cooOutChain = matrixProduct(csrMatrix, csrChain).tocoo()@\\\\\n\\mbox{}\\verb@   outChain = [cooOutChain.row[h]@\\\\\n\\mbox{}\\verb@      for h,val in enumerate(cooOutChain.data) if int(val) >= n]@\\\\\n\\mbox{}\\verb@   return outChain @\\\\\n\\mbox{}\\verb@@{\\NWsep}\n\\end{list}\n\\vspace{-1ex}\n\\footnotesize\\addtolength{\\baselineskip}{-1ex}\n\\begin{list}{}{\\setlength{\\itemsep}{-\\parsep}\\setlength{\\itemindent}{-\\leftmargin}}\n\\item \\NWtxtMacroRefIn\\ \\NWlink{nuweb14e}{14e}.\n\\end{list}\n\\end{minipage}\\\\[4ex]\n\\end{flushleft}\n%-------------------------------------------------------------------------------\n\n\n\\paragraph{Example}\n\n%-------------------------------------------------------------------------------\n\\begin{flushleft} \\small\n\\begin{minipage}{\\linewidth} \\label{scrap22}\n\\protect\\makebox[0ex][r]{\\NWtarget{nuweb14a}{\\rule{0ex}{0ex}}\\hspace{1em}}$\\langle\\,$Algebraic dilation minus erosion\\nobreak\\ {\\footnotesize 14a}$\\,\\rangle\\equiv$\n\\vspace{-1ex}\n\\begin{list}{}{} \\item\n\\mbox{}\\verb@D1 = larDown(skeletons,1)@\\\\\n\\mbox{}\\verb@U0 = larUp(skeletons,0)@\\\\\n\\mbox{}\\verb@U1 = larUp(skeletons,1)@\\\\\n\\mbox{}\\verb@UUD1 = UUD(skeletons,1)@\\\\\n\\mbox{}\\verb@@{\\NWsep}\n\\end{list}\n\\vspace{-1ex}\n\\footnotesize\\addtolength{\\baselineskip}{-1ex}\n\\begin{list}{}{\\setlength{\\itemsep}{-\\parsep}\\setlength{\\itemindent}{-\\leftmargin}}\n\\item {\\NWtxtMacroNoRef}.\n\\end{list}\n\\end{minipage}\\\\[4ex]\n\\end{flushleft}\n%-------------------------------------------------------------------------------\n\n\n\n\\subsection{Maximal ($d-2$)-chain extraction}\n\n\n%-------------------------------------------------------------------------------\n\\begin{flushleft} \\small\n\\begin{minipage}{\\linewidth} \\label{scrap23}\n\\protect\\makebox[0ex][r]{\\NWtarget{nuweb14b}{\\rule{0ex}{0ex}}\\hspace{1em}}$\\langle\\,$Extract the maximal ($d-2$)-chain from a ($d-1$)-chain\\nobreak\\ {\\footnotesize 14b}$\\,\\rangle\\equiv$\n\\vspace{-1ex}\n\\begin{list}{}{} \\item\n\\mbox{}\\verb@@\\\\\n\\mbox{}\\verb@@\\\\\n\\mbox{}\\verb@@{\\NWsep}\n\\end{list}\n\\vspace{-1ex}\n\\footnotesize\\addtolength{\\baselineskip}{-1ex}\n\\begin{list}{}{\\setlength{\\itemsep}{-\\parsep}\\setlength{\\itemindent}{-\\leftmargin}}\n\\item {\\NWtxtMacroNoRef}.\n\\end{list}\n\\end{minipage}\\\\[4ex]\n\\end{flushleft}\n%-------------------------------------------------------------------------------\n\n\\subsection{($d-1$)-Star of a ($d-2$)-chain computation}\n\n%-------------------------------------------------------------------------------\n\\begin{flushleft} \\small\n\\begin{minipage}{\\linewidth} \\label{scrap24}\n\\protect\\makebox[0ex][r]{\\NWtarget{nuweb14c}{\\rule{0ex}{0ex}}\\hspace{1em}}$\\langle\\,$Compute the ($d-1$)-star of a ($d-2$)-chain\\nobreak\\ {\\footnotesize 14c}$\\,\\rangle\\equiv$\n\\vspace{-1ex}\n\\begin{list}{}{} \\item\n\\mbox{}\\verb@@\\\\\n\\mbox{}\\verb@@\\\\\n\\mbox{}\\verb@@{\\NWsep}\n\\end{list}\n\\vspace{-1ex}\n\\footnotesize\\addtolength{\\baselineskip}{-1ex}\n\\begin{list}{}{\\setlength{\\itemsep}{-\\parsep}\\setlength{\\itemindent}{-\\leftmargin}}\n\\item {\\NWtxtMacroNoRef}.\n\\end{list}\n\\end{minipage}\\\\[4ex]\n\\end{flushleft}\n%-------------------------------------------------------------------------------\n\n\n\\subsection{$d$-Star of a $(d-1)$-chain computation}\n\n%-------------------------------------------------------------------------------\n\\begin{flushleft} \\small\n\\begin{minipage}{\\linewidth} \\label{scrap25}\n\\protect\\makebox[0ex][r]{\\NWtarget{nuweb14d}{\\rule{0ex}{0ex}}\\hspace{1em}}$\\langle\\,$Compute the d-star of a ($d-1$)-chain\\nobreak\\ {\\footnotesize 14d}$\\,\\rangle\\equiv$\n\\vspace{-1ex}\n\\begin{list}{}{} \\item\n\\mbox{}\\verb@@\\\\\n\\mbox{}\\verb@@\\\\\n\\mbox{}\\verb@@{\\NWsep}\n\\end{list}\n\\vspace{-1ex}\n\\footnotesize\\addtolength{\\baselineskip}{-1ex}\n\\begin{list}{}{\\setlength{\\itemsep}{-\\parsep}\\setlength{\\itemindent}{-\\leftmargin}}\n\\item {\\NWtxtMacroNoRef}.\n\\end{list}\n\\end{minipage}\\\\[4ex]\n\\end{flushleft}\n%-------------------------------------------------------------------------------\n\n\n\\subsection{Dilation and erosion computation}\n\n\n\n\\subsection{Opening and closing computation}\n\n\n\n\n\\section{Exporting the \\texttt{morph} module}\n\n\\paragraph{Exporting the morph module}\n%-------------------------------------------------------------------------------\n\\begin{flushleft} \\small \\label{scrap26}\n\\protect\\makebox[0ex][r]{\\NWtarget{nuweb14e}{\\rule{0ex}{0ex}}\\hspace{1em}}\\verb@\"larlib/larlib/morph.py\"@\\nobreak\\ {\\footnotesize 14e }$\\equiv$\n\\vspace{-1ex}\n\\begin{list}{}{} \\item\n\\mbox{}\\verb@\"\"\" LAR implementation of morphological operators on multidimensional images.\"\"\"@\\\\\n\\mbox{}\\verb@@\\hbox{$\\langle\\,$Initial import of modules\\nobreak\\ {\\footnotesize \\NWlink{nuweb15}{15}}$\\,\\rangle$}\\verb@@\\\\\n\\mbox{}\\verb@@\\hbox{$\\langle\\,$Generation of random image\\nobreak\\ {\\footnotesize \\NWlink{nuweb2a}{2a}}$\\,\\rangle$}\\verb@@\\\\\n\\mbox{}\\verb@@\\hbox{$\\langle\\,$Save and restore data object from file\\nobreak\\ {\\footnotesize \\NWlink{nuweb6}{6}}$\\,\\rangle$}\\verb@@\\\\\n\\mbox{}\\verb@@\\hbox{$\\langle\\,$Save or restore the chain complex of multidimensional image\\nobreak\\ {\\footnotesize \\NWlink{nuweb7a}{7a}}$\\,\\rangle$}\\verb@@\\\\\n\\mbox{}\\verb@@\\hbox{$\\langle\\,$Tuples to integers mapping\\nobreak\\ {\\footnotesize \\NWlink{nuweb5a}{5a}}$\\,\\rangle$}\\verb@@\\\\\n\\mbox{}\\verb@@\\hbox{$\\langle\\,$Generation of a masking window\\nobreak\\ {\\footnotesize \\NWlink{nuweb3b}{3b}}$\\,\\rangle$}\\verb@@\\\\\n\\mbox{}\\verb@@\\hbox{$\\langle\\,$Characteristic matrices of multidimensional image\\nobreak\\ {\\footnotesize \\NWlink{nuweb7b}{7b}}$\\,\\rangle$}\\verb@@\\\\\n\\mbox{}\\verb@@\\hbox{$\\langle\\,$CSR matrices of boundary operators\\nobreak\\ {\\footnotesize \\NWlink{nuweb9a}{9a}}$\\,\\rangle$}\\verb@@\\\\\n\\mbox{}\\verb@@\\hbox{$\\langle\\,$csrMatrix*chain product and interpretation\\nobreak\\ {\\footnotesize \\NWlink{nuweb13b}{13b}}$\\,\\rangle$}\\verb@@\\\\\n\\mbox{}\\verb@@\\hbox{$\\langle\\,$Pyplasm visualisation of an image chain\\nobreak\\ {\\footnotesize \\NWlink{nuweb10b}{10b}}$\\,\\rangle$}\\verb@@\\\\\n\\mbox{}\\verb@@\\hbox{$\\langle\\,$Boundary of image chain computation\\nobreak\\ {\\footnotesize \\NWlink{nuweb9b}{9b}}$\\,\\rangle$}\\verb@@\\\\\n\\mbox{}\\verb@@\\hbox{$\\langle\\,$Down and Up operators\\nobreak\\ {\\footnotesize \\NWlink{nuweb11}{11}}$\\,\\rangle$}\\verb@@\\\\\n\\mbox{}\\verb@@\\hbox{$\\langle\\,$UUD operator: maps Down-UP-UP its input chains\\nobreak\\ {\\footnotesize \\NWlink{nuweb12a}{12a}}$\\,\\rangle$}\\verb@@\\\\\n\\mbox{}\\verb@@\\hbox{$\\langle\\,$Testing the algebraic morphology method step-by-step\\nobreak\\ {\\footnotesize \\NWlink{nuweb13a}{13a}}$\\,\\rangle$}\\verb@ @\\\\\n\\mbox{}\\verb@@\\hbox{$\\langle\\,$Testing the algebraic morphology\\nobreak\\ {\\footnotesize \\NWlink{nuweb12b}{12b}}$\\,\\rangle$}\\verb@ @\\\\\n\\mbox{}\\verb@@{\\NWsep}\n\\end{list}\n\\vspace{-2ex}\n\\end{flushleft}\n%-------------------------------------------------------------------------------\n\nThe set of importing commends needed by test files in this module is given in the macro below.\n\n%-------------------------------------------------------------------------------\n\\begin{flushleft} \\small\n\\begin{minipage}{\\linewidth} \\label{scrap27}\n\\protect\\makebox[0ex][r]{\\NWtarget{nuweb15}{\\rule{0ex}{0ex}}\\hspace{1em}}$\\langle\\,$Initial import of modules\\nobreak\\ {\\footnotesize 15}$\\,\\rangle\\equiv$\n\\vspace{-1ex}\n\\begin{list}{}{} \\item\n\\mbox{}\\verb@\"\"\" Initial import of modules \"\"\"@\\\\\n\\mbox{}\\verb@from larlib import *@\\\\\n\\mbox{}\\verb@import scipy.misc, numpy, pickle@\\\\\n\\mbox{}\\verb@from numpy.random import randint@\\\\\n\\mbox{}\\verb@@{\\NWsep}\n\\end{list}\n\\vspace{-1ex}\n\\footnotesize\\addtolength{\\baselineskip}{-1ex}\n\\begin{list}{}{\\setlength{\\itemsep}{-\\parsep}\\setlength{\\itemindent}{-\\leftmargin}}\n\\item \\NWtxtMacroRefIn\\ \\NWlink{nuweb14e}{14e}\\NWlink{nuweb16}{, 16}.\n\\end{list}\n\\end{minipage}\\\\[4ex]\n\\end{flushleft}\n%-------------------------------------------------------------------------------\n\n\n\\section{Morphological operations examples}\n\n\\subsection{2D image masking and boundary computation}\n\n\\paragraph{Test example}\n\nThe \\texttt{larcc.morph} API is used here to generate a random black and white image, with an \\emph{image segment} selected and extracted by masking, then colored in middle grey, and exported to an image file.  \nThe \\texttt{shape} and \\texttt{structure} variables must contain two tuples, of equal \\texttt{len}, of powers of 2, used toy define the size of random blocks in the generated image. The \\texttt{window} variable is used to define the portion of the image where the \\emph{segmentChain} of white pixels (or voxels, for 3-images) is computed.\n\n%------------------------------------------------------------------\n\\begin{flushleft} \\small\n\\begin{minipage}{\\linewidth} \\label{scrap28}\n\\protect\\makebox[0ex][r]{\\NWtarget{nuweb16}{\\rule{0ex}{0ex}}\\hspace{1em}}\\verb@\"test/py/morph/test01.py\"@\\nobreak\\ {\\footnotesize 16 }$\\equiv$\n\\vspace{-1ex}\n\\begin{list}{}{} \\item\n\\mbox{}\\verb@@\\\\\n\\mbox{}\\verb@@\\hbox{$\\langle\\,$Initial import of modules\\nobreak\\ {\\footnotesize \\NWlink{nuweb15}{15}}$\\,\\rangle$}\\verb@@\\\\\n\\mbox{}\\verb@@\\\\\n\\mbox{}\\verb@shape = 64,64@\\\\\n\\mbox{}\\verb@structure = 8,8@\\\\\n\\mbox{}\\verb@assert len(shape) == len(structure)@\\\\\n\\mbox{}\\verb@imageVerts = larImageVerts(shape)@\\\\\n\\mbox{}\\verb@_, skeletons, operators = imageChainComplex (shape)@\\\\\n\\mbox{}\\verb@image_array = randomImage(shape, structure, 0.05)@\\\\\n\\mbox{}\\verb@minPoint, maxPoint = (0,0), (64,64)@\\\\\n\\mbox{}\\verb@window = minPoint, maxPoint@\\\\\n\\mbox{}\\verb@segmentChain = setMaskWindow(window,image_array)@\\\\\n\\mbox{}\\verb@   @\\\\\n\\mbox{}\\verb@solid = visImageChain (shape,segmentChain, imageVerts, skeletons)@\\\\\n\\mbox{}\\verb@b_rep,boundaryChain = imageChainBoundary(shape, operators)(2)(segmentChain)@\\\\\n\\mbox{}\\verb@@\\\\\n\\mbox{}\\verb@stepwiseTest = True@\\\\\n\\mbox{}\\verb@if stepwiseTest:@\\\\\n\\mbox{}\\verb@   model = testAlgebraicMorphologyStepByStep(solid, b_rep, @\\\\\n\\mbox{}\\verb@            boundaryChain, imageVerts, skeletons)@\\\\\n\\mbox{}\\verb@else:@\\\\\n\\mbox{}\\verb@   model = testAlgebraicMorphology(solid, b_rep, @\\\\\n\\mbox{}\\verb@            boundaryChain, imageVerts, skeletons)@\\\\\n\\mbox{}\\verb@VIEW(STRUCT(MKPOLS(model)))@\\\\\n\\mbox{}\\verb@@\\\\\n\\mbox{}\\verb@V = model[0]@\\\\\n\\mbox{}\\verb@M = AA(tuple)(model[1])@\\\\\n\\mbox{}\\verb@S = AA(tuple)(solid[1])@\\\\\n\\mbox{}\\verb@B = AA(tuple)(b_rep[1])@\\\\\n\\mbox{}\\verb@D = list(set(S).union(M))@\\\\\n\\mbox{}\\verb@E = list(set(S).difference(M))@\\\\\n\\mbox{}\\verb@M,S,B,D,E = (AA(AA(list)))([M,S,B,D,E])@\\\\\n\\mbox{}\\verb@M2 = STRUCT(MKPOLS((V,M)))@\\\\\n\\mbox{}\\verb@S2 = STRUCT(MKPOLS((V,S)))@\\\\\n\\mbox{}\\verb@@\\\\\n\\mbox{}\\verb@S2 = COLOR(CYAN)(STRUCT(MKPOLS((V,S))))@\\\\\n\\mbox{}\\verb@B1 = COLOR(MAGENTA)(STRUCT(MKPOLS((V,B))))@\\\\\n\\mbox{}\\verb@D2 = COLOR(YELLOW)(STRUCT(MKPOLS((V,D))))@\\\\\n\\mbox{}\\verb@E2 = COLOR(WHITE)(STRUCT(MKPOLS((V,E))))@\\\\\n\\mbox{}\\verb@VIEW(STRUCT([D2,S2,E2,B1]))@\\\\\n\\mbox{}\\verb@@\\\\\n\\mbox{}\\verb@VIEW(STRUCT([D2,S2,B1]))@\\\\\n\\mbox{}\\verb@VIEW(STRUCT([S2,E2,B1]))@\\\\\n\\mbox{}\\verb@@\\\\\n\\mbox{}\\verb@@{\\NWsep}\n\\end{list}\n\\vspace{-2ex}\n\\end{minipage}\\\\[4ex]\n\\end{flushleft}\n%------------------------------------------------------------------\n\n%A0 = matrix([\n%[0,2,0],\n%[4,0,0],\n%[0,0,2],\n%])\n%B0 = matrix([\n%[0,1,0],\n%[1,0,0],\n%[0,0,1],\n%])\n%A1 = matrix([\n%[0,10,0],\n%[0,11,0],\n%[5,0,12],\n%])\n%B1 = matrix([\n%[0,1,0],\n%[0,1,0],\n%[1,0,1],\n%])\n\n\n%===============================================================================\n\\appendix\n\\section{Utilities}\n\n\\subsection{Importing a generic module}\nFirst we define a parametric macro to allow the importing of \\texttt{larcc} modules from the project repository \\texttt{lib/py/}. When the user needs to import some project's module, she may call this macro as done in Section~\\ref{sec:lar2psm}.\n%------------------------------------------------------------------\n\\begin{flushleft} \\small\n\\begin{minipage}{\\linewidth} \\label{scrap29}\n\\protect\\makebox[0ex][r]{\\NWtarget{nuweb17a}{\\rule{0ex}{0ex}}\\hspace{1em}}$\\langle\\,$Import the module\\nobreak\\ {\\footnotesize 17a}$\\,\\rangle\\equiv$\n\\vspace{-1ex}\n\\begin{list}{}{} \\item\n\\mbox{}\\verb@import @@1\\verb@@\\\\\n\\mbox{}\\verb@from @@1\\verb@ import *@\\\\\n\\mbox{}\\verb@@{\\NWsep}\n\\end{list}\n\\vspace{-1ex}\n\\footnotesize\\addtolength{\\baselineskip}{-1ex}\n\\begin{list}{}{\\setlength{\\itemsep}{-\\parsep}\\setlength{\\itemindent}{-\\leftmargin}}\n\\item \\NWtxtMacroRefIn\\ \\NWlink{nuweb17b}{17b}.\n\\end{list}\n\\end{minipage}\\\\[4ex]\n\\end{flushleft}\n%------------------------------------------------------------------\n\n\\paragraph{Importing a module} A function used to import a generic \\texttt{lacccc} module within the current environment is also useful.\n%------------------------------------------------------------------\n\\begin{flushleft} \\small\n\\begin{minipage}{\\linewidth} \\label{scrap30}\n\\protect\\makebox[0ex][r]{\\NWtarget{nuweb17b}{\\rule{0ex}{0ex}}\\hspace{1em}}$\\langle\\,$Function to import a generic module\\nobreak\\ {\\footnotesize 17b}$\\,\\rangle\\equiv$\n\\vspace{-1ex}\n\\begin{list}{}{} \\item\n\\mbox{}\\verb@def importModule(moduleName):@\\\\\n\\mbox{}\\verb@   @\\hbox{$\\langle\\,$Import the module\\nobreak\\ ({\\footnotesize \\NWtarget{nuweb17c}{17c}\\label{scrap31}\n }\\mbox{}\\verb@moduleName@ ) {\\footnotesize \\NWlink{nuweb17a}{17a}}$\\,\\rangle$}\\verb@@\\\\\n\\mbox{}\\verb@@{\\NWsep}\n\\end{list}\n\\vspace{-1ex}\n\\footnotesize\\addtolength{\\baselineskip}{-1ex}\n\\begin{list}{}{\\setlength{\\itemsep}{-\\parsep}\\setlength{\\itemindent}{-\\leftmargin}}\n\\item {\\NWtxtMacroNoRef}.\n\\end{list}\n\\end{minipage}\\\\[4ex]\n\\end{flushleft}\n%------------------------------------------------------------------\n\n\n\\bibliographystyle{amsalpha}\n\\bibliography{morph}\n\n\\end{document}\n", "meta": {"hexsha": "92c6c844dc386d6b406754c3cc15af9afbecc385", "size": 54734, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/tex/morph.tex", "max_stars_repo_name": "Ahdhn/lar-cc", "max_stars_repo_head_hexsha": "7092965acf7c0c78a5fab4348cf2c2aa01c4b130", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-10T02:06:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T02:06:27.000Z", "max_issues_repo_path": "doc/tex/morph.tex", "max_issues_repo_name": "Ahdhn/lar-cc", "max_issues_repo_head_hexsha": "7092965acf7c0c78a5fab4348cf2c2aa01c4b130", "max_issues_repo_licenses": ["MIT", "Unlicense"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-02-20T21:57:07.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-21T07:18:11.000Z", "max_forks_repo_path": "doc/tex/morph.tex", "max_forks_repo_name": "Ahdhn/lar-cc", "max_forks_repo_head_hexsha": "7092965acf7c0c78a5fab4348cf2c2aa01c4b130", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2016-11-04T10:47:42.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-10T17:32:50.000Z", "avg_line_length": 48.4800708592, "max_line_length": 820, "alphanum_fraction": 0.6300654072, "num_tokens": 17856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.32316297522434834}}
{"text": "\\chapter{Depth Map Prediction using Machine Learning}\n\nThinking about the original inspiration of our project, human can easily estimate the distance between the scenery and themselves, we believe that is based on binocular vision. However, after thinking over, we may find we are not so sure about this hypothesis, because when we close one eye, we can still see the world and we can still estimate the depth of the scenery, maybe a little harder. \n\nOn the other hand, we did plenty of calculations in our projects, including building calibration model, image comparison, to get the depth information. But do we really do this kind of calculations in our brain all the time? Do we estimate depth information simply based on the two images of left and right view? We may find the answer is no, because so many other cues are used when we estimate the distance of one object. For example, we know that one building should far larger than a person and when a building and a person project to our retina with the same size, we should know the build is far and the person is near to us. \n\nActually, our brain do so many amazing things, the brain can learn to process images, sounds, it can learn to process our sense of touch. It seems like if we want to mimic the brain, we have to write lots of different pieces of software and programs. But instead, the way the brain does it is just worth a single learning algorithms, this is a hypothesis and widely accepted by scientists now. This magical algorithm is neural network algorithm. \n\nMachine learning is a field of computer science that often uses statistical techniques to give computers the ability to \"learn\" In this chapter, we want to make a machine learn to predict the depth information using neural network.\n\n\\section{Convolutional Neural Network}\n\nConvolutional neural networks (CNNs) are the current state-of-the-art model architecture for image classification tasks and other image processing tasks. CNNs apply a series of filters to the raw pixel data of an image to extract and learn higher-level features. This model can be used  to classification and other image processing tasks.\n\nIn this section. We build a model to classify the images of hand write number, as shown in Figure \\ref{fig:number}. Through studying amount of features, the classifier can label a new image with the number on it, the accuracy can reach 0.99.\n\n\\begin{figure}[h!]\n\t\\centering\n\t\\includegraphics[width=0.8\\linewidth]{figures/part3/number}\n\t\\caption{Hand write numbers}\n\t\\label{fig:number}\n\\end{figure} \n\nUsually, CNNs contains three components:\n\\begin{itemize}\n\t\\item Convolutional layers, which apply a specified number of convolution filters to the image. For each subregion, the layer performs a set of mathematical operations to produce a single value in the output feature map.\n\t\\item Pooling layers, which downsample the image data extracted by the convolutional layers to reduce the dimensionality of the feature map in order to decrease processing time. A commonly used pooling algorithm is max pooling, which extracts subregions of the feature map (e.g., 2x2-pixel tiles), keeps their maximum value, and discards all other values.\n\t\\item Dense (fully connected) layers, which perform classification on the features extracted by the convolutional layers and downsampled by the pooling layers. In a dense layer, every node in the layer is connected to every node in the preceding layer.\n\\end{itemize}\n\nIn our model, we define a deep neural network which contains one input layer, three convolution layers, two pooling layers and a output layer. The result shows deep networks performs better than shallow networks. Figure \\ref{fig:train} shows the training progress of our model. From the figure we can easily find the accuracy of classify become higher and higher as the training epoch increase. \n\n\\begin{figure}[h!]\n\t\\centering\n\t\\includegraphics[width=0.9\\linewidth]{figures/part3/train}\n\t\\caption{Training process}\n\t\\label{fig:train}\n\\end{figure} \n\nSource code for hand write image classifier is in Appendix \\ref{code:3.1}.\n\n\\section{Stereo Convolutional Neural Network}\n\nThis section introduce a stereo convolution neural network. The network is fully convolutional, and takes a couple of grayscale stereoscopic images concatenated along the channel axis, and outputs a single image representing the depth map. A series of convolutional and maxpooling layers followed by a series of upscalling and deconvolutional layers allow the network to extract image disparity features at the smaller scale (object edges), and generate a smooth estimate of the depth map at the larger scale (full object). \n\nFigure \\ref{fig:stereo_connet} show the depth map prediction of Stereo ConvNet. The training/validation sets are created using the random virtual 3d scene generator \\footnote{https://github.com/LouisFoucard/DepthMap\\_dataset}.\n\n\\begin{figure}[h!]\n\t\\centering\n\t\\includegraphics[width=0.8\\linewidth]{figures/part3/stereo_connet.pdf}\n\t\\caption{Stereo ConvNet results}\n\t\\label{fig:stereo_connet}\n\\end{figure} \n\n There are many related works about Stereo ConvNet, basic architecture contains 4 convolution layers, 3 maxpool layers and 4 deconvolution layers\\footnote{https://github.com/LouisFoucard/StereoConvNet}. To achieve better performance Deeper Stereo ConvNet Architecture \\cite{Dosovitskiy2015FlowNet} and  Patched Deeper Stereo ConvNet Architecture \\cite{7298715}\\cite{Lecun2015Stereo} are proposed.\n", "meta": {"hexsha": "952c22dadb6ad03d3e3c838300e199c69779f365", "size": 5454, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "The_Art_Of_Scientific_Computation/report/part3.tex", "max_stars_repo_name": "infinityglow/Unimelb-CS-Subjects", "max_stars_repo_head_hexsha": "07bdb49fd4c50035b7f2e80ca218ac2b620098e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-14T16:31:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T16:31:07.000Z", "max_issues_repo_path": "The_Art_Of_Scientific_Computation/report/part3.tex", "max_issues_repo_name": "hidara2000/Unimelb-CS-Subjects", "max_issues_repo_head_hexsha": "07bdb49fd4c50035b7f2e80ca218ac2b620098e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "The_Art_Of_Scientific_Computation/report/part3.tex", "max_forks_repo_name": "hidara2000/Unimelb-CS-Subjects", "max_forks_repo_head_hexsha": "07bdb49fd4c50035b7f2e80ca218ac2b620098e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-14T11:59:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-14T11:59:13.000Z", "avg_line_length": 97.3928571429, "max_line_length": 632, "alphanum_fraction": 0.8032636597, "num_tokens": 1205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.32316297522434834}}
{"text": "\\documentclass[acmsmall,nonacm]{acmart}\n\n\\bibliographystyle{ACM-Reference-Format}\n\\citestyle{acmauthoryear}\n\n\\RequirePackage{tikz}\n\\RequirePackage{scalerel}\n\\RequirePackage{xparse}\n\\RequirePackage{xifthen}\n\n\\usepackage{mathpartir}\n\n\\usetikzlibrary{shapes}\n\\usetikzlibrary{arrows}\n\\usetikzlibrary{calc}\n\\usetikzlibrary{arrows.meta}\n\n\n\n%% Invariants and Ghost ownership\n% PDS: Was 0pt inner, 2pt outer.\n% \\boxedassert [tikzoptions] contents [name]\n\\tikzstyle{boxedassert_border} = [sharp corners,line width=0.2pt]\n\\NewDocumentCommand \\boxedassert {O{} m o}{%\n\t\\tikz[baseline=(m.base)]{\n\t\t%\t  \\node[rectangle, draw,inner sep=0.8pt,anchor=base,#1] (m) {${#2}\\mathstrut$};\n\t\t\\node[rectangle,inner sep=0.8pt,outer sep=0.2pt,anchor=base] (m) {${\\,#2\\,}\\mathstrut$};\n\t\t\\draw[#1,boxedassert_border] ($(m.south west) + (0,0.65pt)$) rectangle ($(m.north east) + (0, 0.7pt)$);\n\t}\\IfNoValueF{#3}{^{\\,#3}}%\n}\n\\DeclareMathOperator*{\\Sep}{\\scalerel*{\\ast}{\\sum}}\n\\newcommand*{\\ghost}[1]{\\boxedassert[densely dashed]{#1}}\n\\newcommand*{\\N}{\\mathbb{N}}\n\\newcommand*{\\Z}{\\mathbb{Z}}\n\\newcommand{\\wand}{\\mathrel{-\\!\\!\\ast}}\n\\newcommand{\\core}[1]{\\left| #1 \\right|}\n\\newcommand{\\proves}{\\vdash}\n\\newcommand{\\makes}{\\dashv}\n\\newcommand{\\constep}{\\Rightarrow}\n\\newcommand{\\makesto}{\\dashv\\!\\constep}\n\\newcommand{\\judgment}[2][]{\\noindent\\\\\\textbf{#1}\\hspace{\\stretch{1}}\\fbox{$#2$}\\nopagebreak}\n\\newcommand{\\judgmentB}[3][]{\\noindent\\\\\\textbf{#1}\\hspace{\\stretch{1}}\\fbox{$#2$}\\ \\ \\fbox{$#3$}\\nopagebreak}\n\\newcommand*{\\axiom}[2][]{\\infer[#1]{}{#2}}\n\n\\begin{document}\n\n\\title{Metamath C technical appendix}\n\n%% Author with single affiliation.\n\\author{Mario Carneiro}\n\\affiliation{\n  \\institution{Carnegie Mellon University}\n}\n\n% \\begin{abstract}\n% Text of abstract \\ldots.\n% \\end{abstract}\n\n\\maketitle\n\n\n\\section{Introduction}\n\nThis is an informal development of the theory behind the Metamath C language: the syntax and separation logic, as well as the lowering map to x86. For now, this is just a set of notes for the actual compiler. (Informal is a relative word, of course, and this is quite formally precise from a mathematician's point of view. But it is not mechanized.)\n\n\\section{Syntax}\n\nThe syntax of MMC programs, after type inference, is given by the following (incomplete) grammar:\n\n\\begin{align*}\n  \\alpha,x,h,k\\in \\mathrm{Ident} ::={}& \\mathrm{identifiers}\\\\\n  s \\in \\mathrm{Size} ::={}& 8\\mid 16\\mid 32\\mid 64\\mid \\infty&&\\mbox{integer bit size}\\\\\n  t \\in \\mathrm{TuplePattern} ::={}& \\_\\mid x\\mid \\ghost{x}&&\\mbox{ignored, variable, ghost variable}\\\\\n    \\mid{}&t:\\tau \\mid \\langle \\overline{t}\\rangle&&\\mbox{type ascription, tuple}\\\\\n  R \\in \\mathrm{Arg} ::={}& x:\\tau\\mid \\ghost{x}:\\tau\\mid h:A&&\\mbox{regular/ghost/proof argument}\\\\\n  \\tau\\in\\mathrm{Type} ::={}& \\alpha&&\\mbox{type variable reference}\\\\\n    \\mid{}& \\core\\alpha&&\\mbox{moved type variable}\\\\\n    \\mid{}&\\mathbf{0}\\mid \\mathbf{1}\\mid \\mathsf{bool}&&\\mbox{void, unit, booleans}\\\\\n    \\mid{}&\\N_s\\mid \\Z_s&&\\mbox{unsigned and signed integers of different sizes}\\\\\n    \\mid{}&\\textstyle\\bigcap\\overline{\\tau} \\mid \\textstyle\\bigcup \\overline{\\tau}&&\\mbox{intersection type, (undiscriminated) union type}\\\\\n    \\mid{}&\\textstyle\\Sep\\overline{\\tau} \\mid \\textstyle\\sum\\overline{R}&&\\mbox{tuple type, structure (dependent tuple) type}\\\\\n    \\mid{}&S(\\overline{\\tau},\\overline{pe})&&\\mbox{user-defined type}\\\\\n\\end{align*}\n\\begin{align*}\n  A\\in\\mathrm{Prop} ::={}& pe&&\\mbox{assert that a boolean value is true}\\\\\n    \\mid{}&\\top\\mid \\bot\\mid \\mathsf{emp}&&\\mbox{true, false, empty heap}\\\\\n    \\mid{}&\\forall x:\\tau,\\;A\\mid \\exists x:\\tau,\\;A&&\\mbox{universal, existential quantification}\\\\\n    \\mid{}&A_1\\to A_2\\mid \\neg A&&\\mbox{implication, negation}\\\\\n    \\mid{}&A_1\\land A_2\\mid A_1\\lor A_2&&\\mbox{conjunction, disjunction}\\\\\n    \\mid{}&A_1\\ast A_2\\mid A_1 \\wand A_2&&\\mbox{separating conjunction and implication}\\\\\n    \\mid{}&pe\\mapsto pe'&&\\mbox{points-to assertion}\\\\\n    \\mid{}&\\boxed{x:\\tau}&&\\mbox{typing assertion}\\\\\n\\end{align*}\n\\begin{align*}\n  pe\\in \\mathrm{PureExpr} ::={}&\\mbox{(the first half of Expr below)}&&\\mbox{pure expressions}\\\\\n  e \\in \\mathrm{Expr} ::={}& x&&\\mbox{variable reference}\\\\\n    \\mid{}&()\\mid \\mathsf{true}\\mid \\mathsf{false}\\mid n&&\\mbox{constants}\\\\\n    \\mid{}&e_1 \\land e_2\\mid e_1 \\lor e_2\\mid \\neg e&&\\mbox{logical AND, OR, NOT}\\\\\n    \\mid{}&e_1 \\mathbin\\texttt{\\&} e_2\\mid e_1 \\mathbin\\texttt{|} e_2\\mid \\texttt{!}_s\\; e&&\\mbox{bitwise AND, OR, NOT}\\\\\n    \\mid{}&e_1 + e_2\\mid e_1 * e_2\\mid -e&&\\mbox{addition, multiplication, negation}\\\\\n    \\mid{}&e_1 < e_2\\mid e_1 \\le e_2\\mid e_1 = e_2&&\\mbox{equalities and inequalities}\\\\\n    \\mid{}&\\mathsf{if}\\;h^? : e_1\\;\\mathsf{then}\\;e_2\\;\\mathsf{else}\\;e_3&&\\mbox{conditionals}\\\\\n    \\mid{}&\\langle\\overline{e}\\rangle&&\\mbox{tuple}\\\\\n    \\mid{}&f(\\overline{e})&&\\mbox{(pure) function call}\\\\[2mm]\n%\n    \\mid{}&\\mathsf{let}\\ h^? := t := e_1\\;\\mathsf{in}\\; e_2 &&\\mbox{assignment to a regular variable}\\\\\n    \\mid{}& \\mathsf{let}\\ t := p\\;\\mathsf{in}\\; e&&\\mbox{assignment to a hypothesis}\\\\\n    \\mid{}& \\eta \\gets pe;\\ e&&\\mbox{move assignment}\\\\\n    \\mid{}&F(\\overline{e})&&\\mbox{procedure call}\\\\\n    \\mid{}&\\mathsf{unreachable}\\;p&&\\mbox{unreachable statement}\\\\\n    \\mid{}&\\mathsf{return}\\; \\overline{e}&&\\mbox{procedure return}\\\\\n    \\mid{}&\\mathsf{label}\\;\\overline{k(\\overline{R}):=e}\\;\\mathsf{in}\\;e'&&\\mbox{local mutual tail recursion}\\\\\n    \\mid{}&\\mathsf{goto}\\;k(\\overline{e})&&\\mbox{local tail call}\\\\\n  \\eta \\in \\mathrm{Place} ::={}& x&&\\mbox{variable reference}\\\\\n\\end{align*}\n\\begin{align*}\n  p \\in \\mathrm{Proof} ::={}&\\mathsf{entail}\\;\\overline{p}\\;q&&\\mbox{entailment proof}\\\\\n    \\mid{}&\\mathsf{assert}\\;pe&&\\mbox{assertion}\\\\\n    \\mid{}&\\mathsf{typeof}\\;pe&&\\mbox{take the type of a variable}\\\\\n  q \\in \\mathrm{PureProof} ::={}&\\dots&&\\mbox{MM0 proofs}\\\\\n  it \\in \\mathrm{Item} ::={}&\\mathsf{type}\\;S(\\overline{\\alpha}, \\overline{R}):=\\tau&&\\mbox{type declaration}\\\\\n    \\mid{}&\\mathsf{const}\\;t:=e&&\\mbox{constant declaration}\\\\\n    \\mid{}&\\mathsf{global}\\;t:=e&&\\mbox{global variable declaration}\\\\\n    \\mid{}&\\mathsf{func}\\;f(\\overline{R}):\\overline{R}:=e&&\\mbox{function declaration}\\\\\n    \\mid{}&\\mathsf{proc}\\;f(\\overline{R}):\\overline{R}:=e&&\\mbox{procedure declaration}\\\\\n\\end{align*}\n\nMissing elements of the grammar include:\n\\begin{itemize}\n  \\item Switch statements, which are desugared to if statements.\n  \\item Raw MM0 formulas can be lifted to the `Prop' type.\n  \\item Raw MM0 values can be lifted into $\\N_\\infty$ and $\\Z_\\infty$.\n  \\item There are more operations for working with pointers and arrays. These are discussed in section \\ref{sec:pointers}.\n  \\item There are operations for moving between typed values and hypotheses, which will be discussed later.\n  \\item There are also \\textsf{while} loops and \\textsf{for} loops, but we will focus on the general control flow of \\textsf{label} and \\textsf{goto}.\n\\end{itemize}\n\nLanguage items that are considered but not present (yet) in the language include:\n\\begin{itemize}\n  \\item Functions and procedures cannot be generic over type and propositional variables. (In fact there are no propositional variables in the language, only the type Prop of propositional expressions.) A generic propositional variable is used internally to model the frame rule but it is not available to user code.\n  \\item Recursive and mutually recursive function support is currently very limited.\n\\end{itemize}\nMost of the constructs are likely familiar from other languages. We will call some attention to the more unusual features:\n\\begin{itemize}\n  \\item Ghost variables $\\ghost x$ are used to represent computationally irrelevant data. They can be manipulated just like regular variables, but they must not appear on the data path during code generation. We will use $x^\\gamma$ to generalize over ghost and non-ghost variables, where $\\gamma=\\bot$ means this is a ghost variable and $\\gamma=\\top$ means it is not. We use $\\gamma'\\le \\gamma$ to mean that $\\gamma$ is ``more computationally relevant'' than $\\gamma'$, i.e. if $x^\\gamma$ is ghost then $x^{\\gamma'}$ is too.\n\n  \\item The $\\texttt{!}_s\\; n$ operation performs the mathematical function $2^s-n-1$, taking $2^\\infty=0$ so that $\\texttt{!}_\\infty\\; n=-n-1$. $\\texttt{!}_s\\; n$ is used for bitwise negation of unsigned integers, and $\\texttt{!}_\\infty\\; n$ is used for bitwise negation of signed integers (even those of finite width).\n  \\item The assignment operator $\\mathsf{let}\\ h^? := t := e_1\\;\\mathsf{in}\\; e_2$ assigns the variables of $t$ to the result of $e_1$, but here it should be understood as a new binding, or shadowing declaration, rather than a reassignment to an existing variable. Even array assignments will be desugared into pure-functional update operations.\n\n  Here $h^?$ denotes that the hypothesis binding $h$ is optional; we will write the version with no hypothesis binding as $\\mathsf{let}\\ t := e_1\\;\\mathsf{in}\\; e_2$. The version that has a hypothesis binding requires that $e_1$ is pure.\n\n  The concrete version of the assignment operator also contains a ``$\\mathsf{with}\\ x\\to y$'' clause, but this only renames variables in the source (which is to say, it changes the mapping of source names to internal names) and so is not relevant for the theoretical presentation here.\n\n  \\item The operator $x\\gets pe;\\ e$ is the primitive for mutation of the variables in the context. Intuitively, it can be thought as moving $pe$ into $x$, but it has no effect on the type context, and is only used to coordinate data flow. In the grammar the left hand side is generalized to a type of ``places'' (a.k.a lvalues), but for now these can only be variable references. For example,\n  \\begin{align*}\n    &\\qquad\\mbox{this:}\n      &&\\!\\!\\!\\!\\!\\!\\mbox{has the same effect as:}\n        &&\\!\\!\\!\\!\\!\\!\\mbox{which we can $\\alpha$-rename to:}\\\\\n    &\\mathsf{let}\\ x := 1\\;\\mathsf{in}\n      &&\\mathsf{let}\\ x := 1\\;\\mathsf{in}\n        &&\\mathsf{let}\\ x := 1\\;\\mathsf{in}\\\\\n    &\\mathsf{let}\\ y :=\n      &&\\mathsf{let}\\ \\langle x,y\\rangle :=\n        &&\\mathsf{let}\\ \\langle x',y\\rangle :=\\\\\n    &\\quad x \\gets x+1;\n      &&\\quad \\mathsf{let}\\ x := x+1\\;\\mathsf{in}\\;\n        &&\\quad \\mathsf{let}\\ x' := x+1\\;\\mathsf{in}\\;\\\\\n    &\\quad {-x}\\;\\mathsf{in}\n      &&\\quad \\langle x,-x\\rangle\\;\\mathsf{in}\n        &&\\quad \\langle x',-x'\\rangle\\;\\mathsf{in}\\\\\n    &e(x,y)\n      &&e(x,y)\n        &&e(x',y)\n  \\end{align*}\n\n  The surface syntax uses a combination of $\\mathsf{mut}$ declarations and shadowing let bindings to signal that a move assignment is desired; $\\mathsf{move}$ is the desugared form.\n  One can view this as one part of a phi expression in SSA form.\n\n  \\item The expression $\\mathsf{label}\\;\\overline{k(\\overline{R}):=e}\\;\\mathsf{in}\\;e'$ is similar in behavior to a recursive let binding such as those found in functional languages, but the $\\overline{k}$ are all continuations, which is to say they do not return to the caller when using $\\mathsf{goto}\\;l(\\overline{e})$, which is how we ensure that they can be compiled to plain $\\mathsf{label}$ and $\\mathsf{goto}$ at the machine code level.\n\n  \\item The $\\mathsf{typeof}\\;pe$ operator ``moves'' a value $x:\\tau$ and returns a fact $\\boxed{x:\\tau}$ that asserts ownership of the resources of $x$. See \\ref{sec:moving}.\n\\end{itemize}\n\n\\section{Typing}\n\n\\subsection{Overview}\n\nThe main typing judgments are:\n\n\\begin{itemize}\n  \\item $\\Gamma \\proves t:\\tau \\Rightarrow \\overline{R}$ and $\\Gamma \\proves t:A\\Rightarrow \\overline{R}$\\\\ type a tuple pattern against a value of type $\\tau$ or $A$, producing additional hypotheses $\\overline{R}$ that will enter the context\n  \\item $\\Gamma \\proves \\tau\\;\\mathsf{type}$\\\\ determines that a type $\\tau$ is a valid type in the current context\n  \\item $\\Gamma \\proves A\\;\\mathsf{prop}$\\\\ determines that $A$ is a valid separating proposition in the current context\n  \\item $\\Gamma \\proves R\\;\\mathsf{arg}$\\\\ determines that $R$ is a valid argument extending the current context\n  \\item $\\Gamma \\proves e:\\tau \\makes\\Gamma'$\\\\ determines that $e$ is a valid expression of type $\\tau$, which modifies the context to $\\Gamma'$. In the special case where $\\Gamma'=\\Gamma$, we will write $\\Gamma \\proves e:\\tau$ instead.\n  \\item $\\Gamma \\proves pe:\\tau$\\\\ This is only a specialization of the $\\Gamma \\proves e:\\tau$ judgment, because pure expressions do not change the context.\n  \\item $\\Gamma \\proves p:A \\makes\\Gamma'$\\\\ determines that $p$ is a proof of $A$, which modifies the context to $\\Gamma'$. In the special case where $\\Gamma'=\\Gamma$, we will write $\\Gamma \\proves p:A$ instead.\n  \\item $\\Gamma \\constep \\Gamma'$\\\\ an auxiliary judgment for applying pending mutations to the context.\n  \\item $\\Gamma \\proves e:\\tau\\makesto\\Gamma'$ is defined to mean $\\Gamma \\proves e:\\tau\\makes\\Gamma_1\\ \\wedge\\ \\Gamma_1\\constep\\Gamma'$ for some $\\Gamma_1$.\n  \\item $\\Gamma\\proves it\\;\\mathsf{ok}$\\\\ The top level item typing judgment\n\\end{itemize}\n\nCentral to all of these judgments is the context $\\Gamma$, which consists of:\n\\begin{itemize}\n  \\item The global environment of previously declared items, including in particular a record $\\mathsf{self}(\\bar R):\\bar S$ recording the type of the function being typechecked (if a function/procedure is being checked). This doesn't change during expression typing.\n  \\item A list of type variables $\\overline{\\alpha}$. This is only nonempty when type checking a type declaration.\n  \\item A list of declared jump targets $\\overline{k(\\bar{R})}$, including a special jump target $\\mathsf{return}(\\bar{R})$ where $\\bar{R}$ is the declared return type.\n  \\item A list of regular variables, ghost variables, and hypotheses $\\overline{R}$ with their types.\n  \\item (Used only in non-pure expression and proofs:) An unordered map of mutation records of the form $x\\gets pe:\\tau$ where $x$ is already in the context and $\\Gamma\\proves pe:\\tau$. These represent mutations to elements of the context that need to be propagated forward along the control flow.\n\\end{itemize}\nThe type variables don't depend on anything and cannot be introduced in the middle of an item, so these can be assumed to come first, but jump targets can depend on regular variables. We use the notation $\\Gamma,\\overline{k(\\bar{R})}$ and $\\Gamma,\\overline{R}$ to denote extension of the context with a list of jump targets or variables, respectively, and $\\Gamma,x\\gets pe:\\tau$ to denote the insertion of $x\\gets pe:\\tau$ into the list of mutations, replacing $x\\gets pe':\\tau'$ if it is present.\n\n\\subsection{Moving types}\\label{sec:moving}\n\nThe last essential element to understand the typing rules is the ``moved'' modality on types and propositions, denoted $\\core\\tau$ or $\\core A$. For separating propositions this is also known as the persistence modality, and it represents what is left of a proposition after all the ``ownership'' is removed from it. We use moved types to represent a value that has been accessed. This satisfies the axioms $\\core{\\core\\tau}=\\core\\tau$ and $A\\Leftrightarrow A\\ast\\core A$. We extend this to arbitrary arguments and contexts $\\core R$ and $\\core\\Gamma$ by applying the modality to all contained types and propositions.\n\nA type/proposition is called ``$\\mathsf{copy}$'' or persistent if $\\core\\tau=\\tau$, and is denoted $\\tau\\;\\mathsf{copy}$.\n\nThe moved modality is defined like so:\n\\begin{align*}\n  \\core\\alpha,\\mathbf{0}, \\mathbf{1}, \\mathsf{bool},\\N_s, \\Z_s&\\;\\mathsf{copy}\\\\\n  \\core\\alpha={}&\\core\\alpha\\qquad\\mbox{(that is, $\\alpha$ maps to $\\core\\alpha$)}\\\\\n  \\core{\\textstyle\\bigcap\\overline{\\tau}}={}&\\textstyle\\bigcap\\overline{\\core\\tau}\\\\\n  \\core{\\textstyle\\bigcup\\overline{\\tau}}={}&\\textstyle\\bigcup\\overline{\\core\\tau}\\\\\n  \\core{\\textstyle\\Sep\\overline{\\tau}}={}&\\textstyle\\Sep\\overline{\\core\\tau}\\\\\n  \\core{\\textstyle\\sum\\overline{\\tau}}={}&\\textstyle\\sum\\overline{\\core\\tau}\\\\\n  \\core{S(\\overline{\\tau},\\overline{pe})}={}&[S](\\overline{\\tau},\\overline{pe})\\qquad\\mbox{(that is, the effect of moving $S$ is precalculated)}\n\\end{align*}\nThere are no interesting cases among the types presented here. When we get to pointer types in section \\ref{sec:pointers} we will see that $\\core{\\&^\\mathbf{own}\\tau}=\\core{\\&^\\mathbf{mut}\\tau}=\\N_{64}$, so pointers become ``mere integers'' after they are moved away. (Note, however, that they actually retain their original types for type inference purposes; that is, the typechecker remembers that they have type $\\core{\\&^\\mathbf{own}\\tau}$ in order to determine the type that would result from dereferencing the pointer, if it were still valid.)\n\nFor propositions, the effect is more dramatic:\n\\begin{align*}\n  pe,\\top,\\bot,\\mathsf{emp}&\\;\\mathsf{copy}\\\\\n  \\core{\\forall x:\\tau,\\;A}={}& \\begin{cases}\n    \\forall x:\\tau,\\;\\core A&\\mbox{if $\\tau\\;\\mathsf{copy}$}\\\\\n    \\mathsf{emp}&o.w.\\\\\n  \\end{cases}\\\\\n  \\core{\\exists x:\\tau,\\;A}={}&\\exists x:\\core\\tau,\\;\\core A\\\\\n  \\core{A_1\\land A_2}={}&\\core{A_1}\\land \\core{A_2}\\\\\n  \\core{A_1\\lor A_2}={}&\\core{A_1}\\lor \\core{A_2}\\\\\n  \\core{A\\to A'}={}& \\begin{cases}\n    A\\to \\core{A'}&\\mbox{if $A\\;\\mathsf{copy}$}\\\\\n    \\mathsf{emp}&o.w.\\\\\n  \\end{cases}\\\\\n  \\core{\\neg A}={}& \\begin{cases}\n    A&\\mbox{if $A\\;\\mathsf{copy}$}\\\\\n    \\mathsf{emp}&o.w.\\\\\n  \\end{cases}\\\\\n\\end{align*}\n\\begin{align*}\n  \\core{A_1\\ast A_2}={}&\\core{A_1}\\ast \\core{A_2}\\\\\n  \\core{A\\wand A'}={}& \\begin{cases}\n    A\\wand \\core{A'}&\\mbox{if $A\\;\\mathsf{copy}$}\\\\\n    \\mathsf{emp}&o.w.\\\\\n  \\end{cases}\\\\\n  \\core{pe\\mapsto pe'}={}&\\mathsf{emp}\\\\\n  \\core{\\boxed{x:A}}={}&\\boxed{x:\\core{A}}\\\\\n\\end{align*}\nBecause moving is monotonic, that is $A\\to \\core A$ but not the other way around, negative uses of a non-persistent proposition cause it to completely collapse to \\textsf{emp} when moved.\n\n\\subsection{The Typing Rules}\n\nWe now give the main typing rules for the logic. This corresponds roughly to the \\texttt{typeck} phase of the compiler. Note that ghost variable markings are ignored during this phase; they will come back during the layout phase.\n\n\\judgmentB[Tuple pattern typing]{\\Gamma \\proves t:\\tau \\Rightarrow \\overline{R}}{\\Gamma \\proves t:A \\Rightarrow \\overline{R}}\n\\begin{mathparpagebreakable}\n  \\axiom[tpt-ignore]{\\Gamma \\proves \\_:\\tau\\Rightarrow \\cdot}\\and\n  \\axiom[tpp-ignore]{\\Gamma \\proves \\_:A\\Rightarrow \\cdot}\\and\n  \\axiom[tpt-var]{\\Gamma \\proves x^\\gamma:\\tau\\Rightarrow x^\\gamma:\\tau}\\and\n  \\axiom[tpp-var]{\\Gamma \\proves h:A\\Rightarrow h:A}\\and\n  \\infer[tpt-typed]\n    {\\Gamma \\proves t:\\tau\\Rightarrow \\overline{R}}\n    {\\Gamma \\proves (t:\\tau):\\tau\\Rightarrow \\overline{R}}\\and\n  \\infer[tpp-typed]\n    {\\Gamma \\proves t:A\\Rightarrow \\overline{R}}\n    {\\Gamma \\proves (t:A):A\\Rightarrow \\overline{R}}\\and\n  \\infer[tpt-sum]\n    {\\Gamma \\proves t:\\textstyle \\tau\\Rightarrow \\bar{S}\\quad\n      \\Gamma,\\bar{S} \\proves \\langle \\overline{t'}\\rangle:\\textstyle \\overline{R}[t/x]\\Rightarrow \\bar{S}'}\n    {\\Gamma \\proves \\langle t,\\overline{t'}\\rangle:\\textstyle\\sum x:\\tau,\\overline{R}\\Rightarrow \\bar{S},\\bar{S}'}\\and\n  \\infer[tpp-ex]\n    {\\Gamma \\proves t:\\textstyle \\tau\\Rightarrow \\bar{S}\\quad\n      \\Gamma,\\bar{S} \\proves \\langle \\overline{t'}\\rangle:\\textstyle \\overline{R}[t/x]\\Rightarrow \\bar{S}'}\n    {\\Gamma,\\bar{S} \\proves \\langle t,\\overline{t'}\\rangle:\\textstyle\\exists x:\\tau,\\overline{R}\\Rightarrow \\bar{S},\\bar{S}'}\\and\n  \\infer[tpt-list]\n    {\\forall i,\\ \\ \\Gamma \\proves t_i:\\tau_i\\Rightarrow(\\bar{R})_i}\n    {\\Gamma \\proves \\langle \\overline{t}\\rangle:\\textstyle\\Sep\\overline{\\tau}\\Rightarrow \\overline{\\bar{R}}}\\and\n  \\infer[tpt-and]\n    {\\forall i,\\ \\tau_i\\;\\mathsf{copy}\\quad\n      \\forall i,\\ \\Gamma \\proves t_i:\\tau_i\\Rightarrow(\\bar{R})_i}\n    {\\Gamma \\proves \\langle \\overline{t}\\rangle:\\textstyle\\bigwedge\\overline{\\tau}\\Rightarrow \\overline{\\bar{R}}}\\and\n  \\infer[tpp-sep]\n    {\\Gamma \\proves t:\\textstyle A\\Rightarrow \\bar{R}\\quad\n      \\Gamma \\proves t':\\textstyle A'\\Rightarrow \\bar{R}'}\n    {\\Gamma \\proves \\langle t,t'\\rangle:A\\ast A'\\Rightarrow \\bar{R},\\bar{R}'}\\and\n  \\infer[tpp-and]\n    {\\Gamma \\proves t:\\textstyle A\\Rightarrow \\bar{R}\\quad\n      \\Gamma \\proves t':\\textstyle \\core{A'}\\Rightarrow \\bar{R}'}\n    {\\Gamma \\proves \\langle t,t'\\rangle:A\\land A'\\Rightarrow \\bar{R},\\bar{R}'}\\and\n\\end{mathparpagebreakable}\n\nThe only really relevant rules here for expressiveness are the \\textsc{tpt-var} and \\textsc{tpp-var} rules; the rest are convenience rules for being able to destructure a type or proposition into components using the tuple pattern. For notational simplicity we show the \\textsc{tpt-sum} rule in iterative form, but it actually matches an $n$-ary tuple against an $n$-ary struct type in one go.\n\nIn the \\textsc{tpt-sum} and \\textsc{tpp-ex} rules, we use $\\overline{R}[t/x]$ to denote the result of substituting $t$ for $x$ in $R$. For this to work, $t$ must be reified as a tuple of variables rather than simply a destructuring pattern, which in particular means that `$\\_$' ignore patterns are interpreted as inserting internal variables with no user-specified name rather than being omitted from the context entirely as the \\textsc{tpt-ignore} rule would suggest.\n\n\n\\judgment[Argument typing]{\\Gamma \\proves R\\;\\mathsf{arg}}\n\\begin{mathparpagebreakable}\n  \\infer[arg-type]\n    {\\Gamma \\proves \\tau\\;\\mathsf{type}}\n    {\\Gamma \\proves x^\\gamma:\\tau\\;\\mathsf{arg}}\\and\n  \\infer[arg-prop]\n    {\\Gamma \\proves A\\;\\mathsf{prop}}\n    {\\Gamma \\proves h:A\\;\\mathsf{arg}}\\and\n\\end{mathparpagebreakable}\nThis one is simple so we get it out of the way first. We will avoid dealing with variable shadowing rules here; suffice it to say that variables in the context must always be distinct, and we will perform renaming from the surface syntax to ensure this property when necessary. Also remember that $x^\\gamma$ represents either $x$ or $\\ghost x$ in this rule.\n\n\n\\judgment[Type validity]{\\Gamma \\proves \\tau\\;\\mathsf{type}}\n\\begin{mathparpagebreakable}\n  \\axiom[ty-void]{\\Gamma \\proves \\mathbf{0}\\;\\mathsf{type}}\\and\n  \\axiom[ty-unit]{\\Gamma \\proves \\mathbf{1}\\;\\mathsf{type}}\\and\n  \\axiom[ty-bool]{\\Gamma \\proves \\mathsf{bool}\\;\\mathsf{type}}\\and\n  \\axiom[ty-nat]{\\Gamma \\proves \\N_s\\;\\mathsf{type}}\\and\n  \\axiom[ty-int]{\\Gamma \\proves \\Z_s\\;\\mathsf{type}}\\\\\n  \\infer[ty-var]\n    {\\alpha\\in\\Gamma}\n    {\\Gamma \\proves \\alpha\\;\\mathsf{type}}\\and\n  \\infer[ty-core-var]\n    {\\alpha\\in\\Gamma}\n    {\\Gamma \\proves \\core\\alpha\\;\\mathsf{type}}\\and\n  \\infer[ty-inter]\n    {\\forall i,\\ \\ \\Gamma \\proves \\tau_i\\;\\mathsf{type}}\n    {\\Gamma \\proves \\textstyle\\bigcap\\tau\\;\\mathsf{type}}\\and\n  \\infer[ty-union]\n    {\\forall i,\\ \\ \\Gamma \\proves \\tau_i\\;\\mathsf{type}}\n    {\\Gamma \\proves \\textstyle\\bigcup\\tau\\;\\mathsf{type}}\\and\n  \\infer[ty-list]\n    {\\forall i,\\ \\ \\Gamma \\proves \\tau_i\\;\\mathsf{type}}\n    {\\Gamma \\proves \\textstyle\\Sep\\tau\\;\\mathsf{type}}\\and\n  \\infer[ty-struct-1]\n    {\\Gamma \\proves R_0\\;\\mathsf{arg}}\n    {\\Gamma \\proves \\textstyle\\sum R_0\\;\\mathsf{type}}\\and\n  \\infer[ty-struct-2]\n    {\\Gamma \\proves R_0\\;\\mathsf{arg}\\quad\n      \\Gamma, R_0 \\proves \\textstyle\\sum\\overline{R}\\;\\mathsf{type}}\n    {\\Gamma \\proves \\textstyle\\sum R_0,\\overline{R}\\;\\mathsf{type}}\\and\n  \\infer[ty-user]\n    {\\mathsf{type}\\;S(\\overline{\\alpha}, \\overline{R})\\quad\n      \\forall i,\\ \\Gamma \\proves \\tau_i\\;\\mathsf{type}\\quad\n      \\Gamma \\proves \\langle \\overline{pe}\\rangle:\\textstyle\\sum\\overline{R}[\\overline{\\tau}/\\overline{\\alpha}]}\n    {\\Gamma \\proves S(\\overline{\\tau},\\overline{pe})\\;\\mathsf{type}}\\and\n\\end{mathparpagebreakable}\n\nType validity is also relatively straightforward. Type variables are looked up in the context, and structs can have dependent types, but the only way dependencies can appear is through \\textsc{ty-array}, which can have a natural number size bound, and in hypotheses that appear in struct declarations.\n\n\\judgment[Proposition validity]{\\Gamma \\proves A\\;\\mathsf{prop}}\n\\begin{mathparpagebreakable}\n  \\axiom[typ-true]{\\Gamma \\proves \\top\\;\\mathsf{prop}}\\and\n  \\axiom[typ-false]{\\Gamma \\proves \\bot\\;\\mathsf{prop}}\\and\n  \\axiom[typ-emp]{\\Gamma \\proves \\mathsf{emp}\\;\\mathsf{prop}}\\and\n  \\infer[typ-bool]\n    {\\Gamma \\proves pe:\\mathsf{bool}}\n    {\\Gamma \\proves pe\\;\\mathsf{prop}}\\and\n  \\infer[typ-not]\n    {\\Gamma \\proves A\\;\\mathsf{prop}}\n    {\\Gamma \\proves \\neg A\\;\\mathsf{prop}}\\and\n  \\infer[typ-and]\n    {\\Gamma \\proves A\\;\\mathsf{prop}\\and\n      \\Gamma \\proves B\\;\\mathsf{prop}}\n    {\\Gamma \\proves A\\land B\\;\\mathsf{prop}}\\and\n  \\infer[typ-or]\n    {\\Gamma \\proves A\\;\\mathsf{prop}\\and\n      \\Gamma \\proves B\\;\\mathsf{prop}}\n    {\\Gamma \\proves A\\lor B\\;\\mathsf{prop}}\\and\n  \\infer[typ-sep]\n    {\\Gamma \\proves A\\;\\mathsf{prop}\\and\n      \\Gamma \\proves B\\;\\mathsf{prop}}\n    {\\Gamma \\proves A\\ast B\\;\\mathsf{prop}}\\and\n  \\infer[typ-wand]\n    {\\Gamma \\proves A\\;\\mathsf{prop}\\and\n      \\Gamma \\proves B\\;\\mathsf{prop}}\n    {\\Gamma \\proves A\\wand B\\;\\mathsf{prop}}\\and\n  \\infer[typ-forall]\n    {\\Gamma \\proves \\tau\\;\\mathsf{type}\\quad\n      \\Gamma,x:\\core\\tau \\proves A\\;\\mathsf{prop}}\n    {\\Gamma \\proves \\forall x:\\tau,\\;A\\;\\mathsf{prop}}\\and\n  \\infer[typ-exists]\n    {\\Gamma \\proves \\tau\\;\\mathsf{type}\\quad\n      \\Gamma,x:\\core\\tau \\proves A\\;\\mathsf{prop}}\n    {\\Gamma \\proves \\exists x:\\tau,\\;A\\;\\mathsf{prop}}\\and\n  \\infer[typ-points-to]\n    {\\Gamma \\proves \\ell:\\mathsf{\\N_{64}}\\quad\n      \\Gamma \\proves v:\\mathsf{\\core\\tau}}\n    {\\Gamma \\proves \\ell\\mapsto v\\;\\mathsf{prop}}\\and\n  \\infer[typ-typing]\n    {\\Gamma \\proves x:\\core\\tau\\quad\n      \\Gamma \\proves \\tau\\;\\mathsf{type}}\n    {\\Gamma \\proves \\boxed{x:\\tau}\\;\\mathsf{prop}}\\and\n\\end{mathparpagebreakable}\n\nThere is nothing non-standard in these rules, except perhaps the requirement in the \\textsc{typ-forall} and \\textsc{typ-exists} rules that the types are moved (needed because the assertion language itself should not be able to take ownership of variables used in the assertions).\n\nThe most interesting rule is \\textsc{typ-typing}, which describes the typing assertion $\\boxed{x:\\tau}$. One should think of $x:\\tau$ in the context as a separating conjunction of $x:\\core\\tau$ (which asserts, roughly, that $x$ is a reference to some data in the stack frame that is a valid bit-pattern for type $\\tau$), plus the ``fact'' $h:\\boxed{x:\\tau}$, which represents ownership of all the resources that $x$ may point to. For example, if $x:\\&^\\mathbf{own}\\tau$, then $x$ is itself just a number, but $\\boxed{x:\\&^\\mathbf{own}\\tau}$ is equal to $\\exists v:\\tau,\\ x\\mapsto v$, saying that $x$ points to some data $v$, and $v:\\tau$ may itself own some portion of the heap.\n\n\\subsection{Expression typing}\n\nThe typing rules for expressions make use of the following operators on contexts:\n\n\\begin{itemize}\n  \\item $\\Gamma_{\\core x}$ ``moves'' $x$ out of the context, by replacing $x:\\tau$ with $x:\\core\\tau$ or $x:A$ with $x:\\core A$. This does not invalidate the well formedness of any type, proposition, or pure expression.\n\\end{itemize}\n\nThe rules for pure expression typing are the same as for regular expression typing, although since all the pure expression constructors do not change the context, they are all of the form $\\Gamma\\vdash pe:\\tau\\makes \\Gamma$, which we abbreviate as $\\Gamma\\vdash pe:\\tau$.\n\nNote that the \\textsc{tye-var-ref} rule ignores the effect of mutations. This is necessary so that new mutations do not cause the context to become ill-typed. Instead, mutations are applied in the translation from surface syntax, so that ``$x\\gets 1;\\ x+x$'' is elaborated into ``$\\mathsf{move}\\;x\\gets 1\\;\\mathsf{in}\\;1+1$''.\n\n\\judgment[Expression validity (pure expressions)]{\\Gamma \\proves e:\\tau\\makes\\Gamma'}\n\\begin{mathparpagebreakable}\n  \\infer[tye-var-ref]\n    {(x^\\gamma:\\tau)\\in\\Gamma}\n    {\\Gamma \\proves x:\\core\\tau}\\and\n  \\axiom[tye-unit]{\\Gamma \\proves ():\\mathbf{1}}\\and\n  \\axiom[tye-true]{\\Gamma \\proves \\mathsf{true}:\\mathsf{bool}}\\and\n  \\axiom[tye-false]{\\Gamma \\proves \\mathsf{false}:\\mathsf{bool}}\\and\n  \\infer[tye-nat]\n    {0\\le n\\quad s<\\infty\\to n<2^s}\n    {\\Gamma \\proves n:\\N_s}\\and\n  \\infer[tye-int]\n    {s<\\infty\\to -2^{s-1}\\le n<2^{s-1}}\n    {\\Gamma \\proves n:\\Z_s}\\and\n  \\infer[tye-tuple]\n    {\\forall i<n,\\ \\ \\Gamma_i \\proves e_i:\\tau\\makes\\Gamma_{i+1}}\n    {\\Gamma_0 \\proves \\langle\\overline{e}\\rangle:\\textstyle\\Sep\\tau\\makes\\Gamma_n}\\and\n  \\infer[tye-not]\n    {\\Gamma \\proves e:\\mathsf{bool}\\makes\\Gamma'}\n    {\\Gamma \\proves \\neg e:\\mathsf{bool}\\makes\\Gamma'}\\and\n  \\infer[tye-and, tye-or]\n    {\\Gamma \\proves e_1:\\mathsf{bool}\\makes\\Gamma_1\\quad\n      \\Gamma_1 \\proves e_2:\\mathsf{bool}\\makes\\Gamma_2}\n    {\\Gamma \\proves e_1\\land e_2:\\mathsf{bool}\\makes\\Gamma_2 \\quad\n      \\Gamma \\proves e_1\\lor e_2:\\mathsf{bool}\\makes\\Gamma_2}\\and\n  \\infer[tye-band, tye-bor]\n    {\\tau\\in\\{\\N_s,\\Z_s\\}\\quad\n      \\Gamma \\proves e_1:\\tau\\makes\\Gamma_1\\quad\n      \\Gamma_1 \\proves e_2:\\tau\\makes\\Gamma_2}\n    {\\Gamma \\proves e_1\\mathrel{\\texttt{\\&}} e_2:\\tau\\makes\\Gamma_2 \\quad\n      \\Gamma \\proves e_1\\mathrel{\\texttt{|}} e_2:\\tau\\makes\\Gamma_2}\\and\n  \\infer[tye-bnot]\n    {\\tau=\\N_s\\lor (\\tau=\\Z_{s'}\\land s=\\infty)\\quad\n      \\Gamma \\proves e:\\tau\\makes\\Gamma'}\n    {\\Gamma \\proves \\texttt{!}_s\\;e:\\tau\\makes\\Gamma'}\\and\n  \\infer[tye-lt, tye-le, tye-eq]\n    {\\tau,\\tau'\\in\\{\\N_s,\\Z_s\\}\\qquad\n      \\Gamma \\proves e_1:\\tau\\makes\\Gamma_1\\qquad\n      \\Gamma_1 \\proves e_2:\\tau'\\makes\\Gamma_2}\n    {\\Gamma \\proves e_1< e_2:\\mathsf{bool}\\makes\\Gamma_2\\quad\n      \\Gamma \\proves e_1\\le e_2:\\mathsf{bool}\\makes\\Gamma_2\\quad\n      \\Gamma \\proves e_1= e_2:\\mathsf{bool}\\makes\\Gamma_2}\\and\n  \\infer[tye-dep-if]\n    {c\\ \\mbox{pure}\\quad \\Gamma \\proves c:\\mathsf{bool}\\quad\n      \\Gamma,h:c \\proves e_1:\\tau\\makesto\\Gamma',h:c\\quad\n      \\Gamma,h:\\neg c \\proves e_2:\\tau\\makesto\\Gamma',h:\\neg c}\n    {\\Gamma \\proves (\\mathsf{if}\\;h : c\\;\\mathsf{then}\\;e_1\\;\\mathsf{else}\\;e_2):\\tau\\makes\\Gamma'}\\and\n  \\infer[tye-if]\n    {\\Gamma \\proves c:\\mathsf{bool}\\makes\\Gamma'\\quad\n      \\Gamma' \\proves e_1:\\tau\\makesto\\Gamma''\\quad\n      \\Gamma' \\proves e_2:\\tau\\makesto\\Gamma''}\n    {\\Gamma \\proves (\\mathsf{if}\\;c\\;\\mathsf{then}\\;e_1\\;\\mathsf{else}\\;e_2):\\tau\\makes\\Gamma''}\\and\n  \\infer[tye-struct-var\\footnotemark]\n    {\\Gamma_0 \\proves e:\\tau\\makes\\Gamma_1\\quad\n      \\Gamma_1 \\proves \\langle \\overline{e}\\rangle:\\textstyle\\sum \\bar R[e/x]\\makes\\Gamma_n}\n    {\\Gamma_0 \\proves \\langle e,\\overline{e}\\rangle:\\textstyle\\sum x^\\gamma:\\tau,\\bar R\\makes\\Gamma_n}\\and\n  \\footnotetext{In \\textsc{tye-struct-var}, $e$ must be pure or $x\\notin\\mathrm{Var}(\\bar R)$, so that $\\bar R[e/x]$ is well defined.}\n  \\infer[tye-struct-prop]\n    {\\Gamma_0 \\proves p:A\\makes\\Gamma_1\\quad\n      \\Gamma_1\\proves \\langle \\overline{e}\\rangle:\\textstyle\\sum \\bar R\\makes\\Gamma_n}\n    {\\Gamma_0 \\proves \\langle p,\\overline{e}\\rangle:\\textstyle\\sum h:A,\\bar R\\makes\\Gamma_n}\\and\n  \\infer[tye-func-call]\n    {\\mathsf{func}\\;f(\\overline{R}):\\overline{S}\\quad\n      \\Gamma \\proves \\langle\\overline{e}\\rangle:\\textstyle\\sum\\bar R\\makes\\Gamma'}\n    {\\Gamma \\proves f(\\overline{e}):\\textstyle\\sum\\bar S\\makes\\Gamma'}\\and\n\\end{mathparpagebreakable}\n\nThe rules above are the only ones that apply to pure expressions. General expressions have additional typing rules for the other constructions, continued below.\n\nFor general expressions, we must worry about the following additional effects:\n\\begin{itemize}\n  \\item Variables in the context can be moved by their being referenced (in the \\textsc{tye-var-move} rule).\n  \\item Variables can be mutated, resulting in contexts with unapplied mutations. We will return to this in section \\ref{sec:mutapp}.\n\\end{itemize}\n\n\\judgment[Expression validity]{\\Gamma \\proves e:\\tau\\makes\\Gamma'}\n\\begin{mathparpagebreakable}\n  \\infer[tye-var-move]\n    {(x^\\gamma:\\tau)\\in\\Gamma}\n    {\\Gamma \\proves x:\\tau\\makes\\Gamma_{|x|}}\\and\n  \\infer[tye-mut]\n    {\\!\\:{\\Gamma \\proves pe:\\tau\\makes\\Gamma'\\qquad\n      (x^\\gamma:\\tau'')\\in\\Gamma'\\atop\n      \\Gamma',x\\gets pe:\\tau\\proves e:\\tau'\\makes\\Gamma''}}\n    {\\Gamma \\proves (x\\gets pe;\\ e):\\tau'\\makes\\Gamma''}\\and\n  \\infer[tye-mut-pr]\n    {\\!\\:{\\Gamma \\proves p:A\\makes\\Gamma'\\qquad\n      (h:A')\\in\\Gamma'\\atop\n      \\Gamma',h\\gets p:A\\proves e:\\tau\\makes\\Gamma''}}\n    {\\Gamma \\proves (h\\gets p;\\ e):\\tau\\makes\\Gamma''}\\and\n  \\infer[tye-let-hyp\\footnotemark]\n    {\\!\\:{\\Gamma \\proves pe:\\tau\\qquad\n      \\Gamma \\proves t:\\tau\\Rightarrow \\overline{R}\\qquad\n      \\Gamma' \\proves \\tau'\\;\\mathsf{type}\\atop\n      \\Gamma,\\overline{R},h:t=pe \\proves e:\\tau'\\makesto\\Gamma',\\overline{R},h:t=pe}}\n    {\\Gamma \\proves (\\mathsf{let}\\ h := t := pe\\;\\mathsf{in}\\; e):\\tau'\\makes\\Gamma'}\\and\n  \\footnotetext{In \\textsc{tye-let-hyp}, $t$ must not contain ignore patterns so that $t$ is a pure expression and $t=pe$ is well defined.}\n  \\infer[tye-unreachable]\n    {\\Gamma \\proves p:\\bot\\makes\\Gamma'}\n    {\\Gamma \\proves \\mathsf{unreachable}\\;p:\\tau}\\and\n  \\infer[tye-let]\n    {\\!\\:{\\Gamma \\proves e_1:\\tau\\makes \\Gamma'\\quad\n      \\Gamma' \\proves t:\\tau\\Rightarrow \\overline{R}\\quad\n      \\Gamma'' \\proves \\tau'\\;\\mathsf{type}\\atop\n      \\Gamma',\\overline{R} \\proves e_2:\\tau'\\makesto\\Gamma'',\\overline{R}}}\n    {\\Gamma \\proves (\\mathsf{let}\\ t := e_1\\;\\mathsf{in}\\; e_2):\\tau'\\makes\\Gamma''}\\and\n  \\infer[tye-proc-call]\n    {\\mathsf{proc}\\;F(\\overline{R}):\\overline{S}\\quad\n      \\Gamma \\proves \\langle\\overline{e}\\rangle:\\textstyle\\sum\\bar R\\makes\\Gamma'}\n    {\\Gamma \\proves F(\\overline{e}):\\textstyle\\sum\\bar S\\makes\\Gamma'}\\and\n  \\infer[tye-let-pr]\n    {\\!\\:{\\Gamma \\proves p:A\\makes \\Gamma'\\quad\n      \\Gamma' \\proves t:A\\Rightarrow \\overline{R}\\quad\n      \\Gamma'' \\proves t:\\tau\\;\\mathsf{type}\\atop\n      \\Gamma',\\overline{R} \\proves e:\\tau\\makesto\\Gamma'',\\overline{R}}}\n    {\\Gamma \\proves (\\mathsf{let}\\ t := p\\;\\mathsf{in}\\; e):\\tau\\makes\\Gamma''}\\and\n  \\infer[tye-return]\n    {\\mathsf{self}(\\bar R):\\bar S\\quad\n      \\Gamma \\proves \\langle\\overline{e}\\rangle:\\textstyle\\sum\\bar S\\makesto \\core{\\bar R}}\n    {\\Gamma \\proves \\mathsf{return}\\;\\overline{e}:\\tau}\\and\n  \\infer[tye-label]\n    {\\forall i,\\ \\core{\\Gamma},\\overline{k(\\bar{R})},(\\bar{R})_i \\proves e_i:\\mathbf{0}\\makes\\Gamma''_i\\quad\n      \\Gamma,\\overline{k(\\bar{R})}\\proves e':\\tau\\makes\\Gamma'}\n    {\\Gamma \\proves (\\mathsf{label}\\;\\overline{k(\\bar{R}):=e}\\;\\mathsf{in}\\;e'):\\tau\\makes\\Gamma'}\\and\n  \\infer[tye-goto]\n    {\\Gamma \\proves \\langle\\overline{e}\\rangle:\\textstyle\\sum(\\bar R)_i\\makesto \\Gamma',\\overline{k(\\bar{R})}}\n    {\\Gamma \\proves \\mathsf{goto}\\;k_i(\\overline{e}):\\tau}\\and\n\\end{mathparpagebreakable}\n\nNote that the \\textsf{unreachable}, \\textsf{return}, \\textsf{goto} functions do not return to the calling context, so they return an arbitrary type $\\tau$, and also roll back the context to the initial state $\\Gamma$. A more complex model here would allow the final context to be a special context $\\Gamma_\\bot$, which can step to any context with the same variables as $\\Gamma$.\n\nProofs are essentially (effectful) expressions with proposition type, so the rules look much the same. Pure proofs are simply imported from the MM0 logical enironment so we do not discuss them here. The main job of metamath C is to make sure that these pure proofs have simple types, not using the entire context, since the user will be directly interacting with them.\n\n\\judgment[Proof validity]{\\Gamma \\proves p:A\\makes\\Gamma'}\n\\begin{mathparpagebreakable}\n  \\infer[tpr-assert]\n    {\\Gamma \\proves pe:\\mathsf{bool} \\makes \\Gamma'}\n    {\\Gamma \\proves \\mathsf{assert}\\;pe:pe\\makes\\Gamma'}\\and\n  \\infer[tpr-typeof]\n    {\\Gamma \\proves pe:\\tau \\makes \\Gamma'}\n    {\\Gamma \\proves \\mathsf{typeof}\\;pe:\\boxed{pe:\\tau}\\makes\\Gamma'}\\and\n  \\infer[tpr-entail]\n    {\\Gamma \\proves \\langle\\overline{p}\\rangle:\\textstyle\\Sep\\overline{A} \\makes \\Gamma'\\quad\n      \\vdash q:\\textstyle\\Sep\\overline{A}\\wand B}\n    {\\Gamma \\proves \\mathsf{entail}\\;\\overline{p}\\;q:B\\makes\\Gamma'}\\and\n\\end{mathparpagebreakable}\n\n\\subsection{Mutation application}\\label{sec:mutapp}\n\nThe role of the $\\Gamma\\proves e:\\tau\\makesto\\Gamma'$ judgment is to clean up the context at the terminator of a basic block in the control flow graph: after the branches of an \\textsf{if} statement, and at a \\textsf{return} and \\textsf{goto}. It is also used whenever the context has to drop a variable, such as after a $\\mathsf{let}$ expression completes.\n\nRecall that $\\Gamma\\proves e:\\tau\\makesto\\Gamma'$ means $\\Gamma\\proves e:\\tau\\makes\\Gamma_1$ and $\\Gamma_1\\constep\\Gamma'$ for some $\\Gamma_1$. The reason we can't just use $\\Gamma_1$ directly is because there may be pending mutations, whose values depend on variables we are about to drop. But mutations to variables are not required to be well typed at the target variable at the time of mutation, because for example structs may be written incrementally, with the half written structs being ill-typed. Instead, we delay committing these values as long as possible, even across CFG edges if we can. However, the rules given below are not deterministic, because \\textsc{cs-mut} steps can choose to apply any subset of outstanding mutations that are collectively well typed.\n\n\\judgment[Mutation application]{\\Gamma \\constep\\Gamma'}\n\\begin{mathparpagebreakable}\n  \\axiom[cs-refl]{\\Gamma \\constep \\Gamma}\\and\n  \\infer[cs-trans]\n    {\\Gamma_1 \\constep \\Gamma_2 \\quad \\Gamma_2 \\constep \\Gamma_3}\n    {\\Gamma_1 \\constep \\Gamma_3}\\and\n  \\infer[cs-drop]\n    {\\mbox{for all $S$, if $(x\\gets S)\\in\\Gamma$ then $\\Gamma\\vdash S$}}\n    {\\Gamma,\\overline{R}\\constep\\Gamma}\\and\n  \\axiom[cs-drop-label]{\\Gamma,\\overline{k(\\bar R)}\\constep\\Gamma}\\and\n  \\infer[cs-move]\n    {R\\in \\Gamma}\n    {\\Gamma \\constep\\Gamma_{|R|}}\\and\n  \\infer[cs-mut]\n    {\\Gamma \\proves \\langle \\overline{x}\\rangle:\\textstyle\\sum\\core{\\overline{R}}\\quad\n      \\Gamma \\proves \\langle \\overline{e}\\rangle:\\textstyle\\sum\\overline{R}}\n    {\\Gamma,\\overline{x\\gets e} \\constep\\Gamma_{\\overline{R}}}\\and\n\\end{mathparpagebreakable}\nHere $\\Gamma_{|R|}$ is the context in which $R$ has been moved away to nowhere (i.e. the memory is released), and $\\Gamma_{\\bar R}$ is the context which restores each variable in $\\bar R$ to the specified status, reflecting that they are no longer moved away after the resource is transferred into the context.\n\nTo see how this plays out, recall the \\textsc{tye-return} rule:\n\n$$\\infer[tye-return]\n    {\\mathsf{self}(\\bar R):\\bar S\\quad\n      \\Gamma \\proves \\langle\\overline{e}\\rangle:\\textstyle\\sum\\bar S\\makesto \\core{\\bar R}}\n    {\\Gamma \\proves \\mathsf{return}\\;\\overline{e}:\\tau}$$\n\nAfter executing $\\langle\\overline{e}\\rangle$, we obtain the return value $\\sum\\bar S$ in some context $\\Gamma'$. This context contains the same variables as $\\Gamma$, but we are executing a return statement somewere deep in the function, so $\\Gamma$ will typically contain many variables that were not parameters to the function (the list $\\bar R$), and these variables may appear in uncommitted mutations that are still in $\\Gamma$, so to ensure consistency of the state at the return of the function, we have to commit all outstanding mutations, expressed here by saying that the final state is simply $\\core{\\bar R}$, the moved-out version of the original context, with all extra variables and labels dropped, and no active mutations.\n\n\\subsection{Top level typing}\n\nThe full program consists of a list of top level items, which are typechecked incrementally:\n\n\\judgment[AST typing]{\\Gamma\\proves \\overline{it}\\makes \\Gamma'}\n\\begin{mathparpagebreakable}\n  \\axiom[ok-zero]{\\Gamma\\proves \\cdot\\makes \\Gamma}\\and\n  \\infer[ok-append]\n    {\\Gamma\\proves \\overline{it}\\makes \\Gamma'\\quad\n      \\Gamma'\\vdash it\\makes \\Gamma''}\n    {\\Gamma\\proves \\overline{it},it'\\makes \\Gamma''}\\and\n\\end{mathparpagebreakable}\nIndividual items are typed as follows:\n% it \\in \\mathrm{Item} ::={}&\\mathsf{type}\\;S(\\overline{\\alpha}, \\overline{R}):=\\tau&&\\mbox{type declaration}\\\\\n% \\mid{}&\\mathsf{const}\\;t:=e&&\\mbox{constant declaration}\\\\\n% \\mid{}&\\mathsf{global}\\;t:=e&&\\mbox{global variable declaration}\\\\\n% \\mid{}&\\mathsf{func}\\;f(\\overline{R}):\\overline{R}:=e&&\\mbox{function declaration}\\\\\n% \\mid{}&\\mathsf{proc}\\;f(\\overline{R}):\\overline{R}:=e&&\\mbox{procedure declaration}\\\\\n\n\\judgment[Item typing]{\\Gamma \\proves it\\makes \\Gamma'}\n\\begin{mathparpagebreakable}\n  \\infer[ok-type]\n    {\\Gamma,\\overline{\\alpha} \\proves \\textstyle\\sum\\overline{R}\\;\\mathsf{type}\\quad\n      \\Gamma,\\overline{\\alpha},\\overline{R}\\proves\\tau\\;\\mathsf{type}}\n    {\\Gamma \\proves \\mathsf{type}\\;S(\\overline{\\alpha}, \\overline{R}):=\\tau\\makes \\Gamma,\\ \\mathsf{type}\\;S(\\overline{\\alpha}, \\overline{R}):=\\tau}\\and\n  \\infer[ok-const]\n    {\\Gamma\\proves pe:\\tau\\quad\n     \\Gamma\\proves t:\\tau\\Rightarrow \\bar R}\n    {\\Gamma \\proves \\mathsf{const}\\;t:=pe\\makes \\Gamma,\\bar R}\\and\n  \\infer[ok-global]\n    {\\Gamma\\proves e:\\tau\\makes \\Gamma'\\quad\n     \\Gamma'\\proves t:\\tau\\Rightarrow \\bar R}\n    {\\Gamma \\proves \\mathsf{global}\\;t:=e\\makes \\Gamma',\\bar R}\\and\n  \\infer[ok-func, ok-proc]\n    {\\mathbf{kw}\\in\\{\\mathsf{func},\\mathsf{proc}\\}\\quad \\Gamma\\proves \\textstyle\\sum\\overline{R}\\;\\mathsf{type}\\quad\n      \\Gamma,\\overline{R} \\proves\\textstyle\\sum\\overline{S}\\;\\mathsf{type}\\quad\n      \\Gamma,(\\mathsf{self}(\\overline{R}):\\overline{S}),\\overline{R} \\proves e:\\mathbf{0}\\makesto \\core{\\bar R}}\n    {\\Gamma \\proves \\mathbf{kw}\\;f(\\overline{R}):\\overline{S}:=e\\makes \\Gamma',\\ \\mathbf{kw}\\;f(\\overline{R}):\\overline{S}}\\and\n\\end{mathparpagebreakable}\n\n\\subsection{Uninitialized data}\n\nThe approach for handling mutation also cleanly supports uninitialized data. We extend the language as follows:\n\n\\begin{mathparpagebreakable}\n  \\mathrm{Type}::=\\dots\\mid \\tau^?\\and\n  \\mathrm{Expr}::=\\dots\\mid \\mathsf{uninit}\\and\n  \\core{\\tau^?}=\\core\\tau^?\\and\n  \\boxed{x:\\tau^?}=\\top\\\\\n  \\infer[ty-maybe]\n    {\\Gamma \\proves \\tau\\;\\mathsf{type}}\n    {\\Gamma \\proves \\tau^?\\;\\mathsf{type}}\\and\n  \\infer[tye-uninit]\n    {\\Gamma \\proves \\tau\\;\\mathsf{type}}\n    {\\Gamma \\proves \\mathsf{uninit}:\\tau^?}\\and\n\\end{mathparpagebreakable}\nWe also modify the \\textsc{cs-mut} rule:\n$$\\infer[cs-mut]\n    {\\Gamma \\proves \\langle \\overline{x}\\rangle:\\textstyle\\sum\\core{\\overline{R^?}}\\quad\n      \\Gamma \\proves \\langle \\overline{e}\\rangle:\\textstyle\\sum\\overline{R}}\n    {\\Gamma,\\overline{x\\gets e} \\constep\\Gamma_{\\overline{R}}}$$\nsuch that the variables $x$ are allowed to be potentially uninitialized versions of the types in $e$, meaning that a variable $x:\\tau^?$ can change to $x:\\tau$ as the result of a mutation.\n\n\\subsection{Pointers}\\label{sec:pointers}\n\nThus far the rules have only talked about local variables and mutation of local variables, that we think of as being on the stack frame of the function. To understand the representation of pointers in the type system, it will help to understand the way contexts are modeled as separating propositions. The context is a large separating conjunction of $\\boxed{x:\\tau}$ assertions for every $(x^\\gamma:\\tau)\\in\\Gamma$ and $A$ for every $h:A$, plus additional ``layout'' information about the relation of non-ghost variables to the stack frame that will be calculated in the layout pass (see section \\ref{sec:layout}).\n\n\\subsubsection{Singleton pointers}\n\nThe simplest pointer type is $\\&^\\mathbf{sn}(\\eta:\\tau)$. $x:\\&^\\mathbf{sn}(\\eta:\\tau)$ simply means that $x$ is a pointer that points to $\\eta$, which is a ``place'', a writable location. $\\core{\\&^\\mathbf{sn}\\eta}=\\N_{64}$ and $\\boxed{x:\\&^\\mathbf{sn}\\eta}=x\\mapsto \\eta$. Supporting these requires no significant extensions to the language. We add the following:\n\n\\begin{mathparpagebreakable}\n  \\mathrm{Type}::=\\dots\\mid \\&^\\mathbf{sn}(\\eta:\\tau)\\and\n  \\mathrm{Expr}::=\\dots\\mid {}^\\ast e\\mid \\& e\\\\\n  \\core{\\&^\\mathbf{sn}(\\eta:\\tau)}=\\N_{64}\\and\n  \\boxed{x:\\&^\\mathbf{sn}(\\eta:\\tau)}=x\\mapsto \\eta\\\\\n  \\infer[ty-snp]\n    {\\Gamma \\proves \\tau\\;\\mathsf{type}\\quad\n      \\Gamma \\proves \\eta:\\core\\tau}\n    {\\Gamma \\proves \\&^\\mathbf{sn}(\\eta:\\tau)\\;\\mathsf{type}}\\and\n  \\infer[tye-deref]\n    {\\Gamma \\proves e:\\&^\\mathbf{sn}(\\eta:\\tau)\\makes\\Gamma'\\quad\n      \\Gamma' \\proves \\eta:\\tau\\makes\\Gamma''}\n    {\\Gamma \\proves {}^* e:\\tau\\makes\\Gamma''}\\and\n  \\infer[tye-ref]\n    {\\Gamma \\proves \\eta:\\core\\tau}\n    {\\Gamma \\proves \\&\\eta:\\&^\\mathbf{sn}(\\eta:\\tau)}\\and\n\\end{mathparpagebreakable}\nTo allow for mutation, we must also extend the $x\\gets pe;\\ e$ form to allow a pointer on the left:\n\n\\begin{mathparpagebreakable}\n  \\mathrm{Place}::=\\dots\\mid {}^\\ast e\\and\n  \\infer[tye-mut-deref]\n    {\\Gamma \\proves e_1:\\&^\\mathbf{sn}(\\eta:\\tau)\\makes\\Gamma'\\quad\n      \\Gamma' \\proves (\\eta\\gets pe;\\ e_2):\\tau'\\makes\\Gamma''}\n    {\\Gamma \\proves ({}^\\ast e_1\\gets pe;\\ e_2):\\tau'\\makes\\Gamma''}\\and\n\\end{mathparpagebreakable}\n\n\\subsubsection{Owned pointers}\n\nAn owned pointer is also fairly simple. We define $\\boxed{x:\\&^\\mathbf{own}\\tau}$ as $\\exists v:\\tau,\\ x\\mapsto v$, but we can't directly dereference an owned pointer as we must first have access to the variable $v$, so we require that it first be destructured to be used.\n\n\\begin{mathparpagebreakable}\n  \\mathrm{Type}::=\\dots\\mid \\&^\\mathbf{own}\\tau\\and\n  \\core{\\&^\\mathbf{own}\\tau}=\\N_{64}\\and\n  \\boxed{x:\\&^\\mathbf{own}\\tau}=\\exists v:\\tau,x\\mapsto v\\\\\n  \\infer[ty-own]\n    {\\Gamma \\proves \\tau\\;\\mathsf{type}}\n    {\\Gamma \\proves \\&^\\mathbf{own}\\tau\\;\\mathsf{type}}\\and\n  \\infer[tpt-own]\n    {\\Gamma \\proves t:\\textstyle \\tau\\Rightarrow \\bar{S}\\quad\n      \\Gamma,\\bar{S} \\proves t':\\textstyle \\&^\\mathbf{sn}t\\Rightarrow \\bar{S}'}\n    {\\Gamma \\proves \\langle t,t'\\rangle:\\&^\\mathbf{own}\\tau\\Rightarrow \\bar{S},\\bar{S}'}\\and\n\\end{mathparpagebreakable}\n\n\\subsubsection{Mutable pointers}\nThe type $\\&^\\mathbf{mut}\\tau$ is not a true type, but is allowed in function signatures to indicate a $\\&^\\mathbf{sn}(\\eta:\\tau)$ value where $\\eta$ is external to the function. To support this we have to rewrite the provided function signature to include these $\\eta$ ghost values and then match them with provided expressions.\n\n\\begin{align*}\n  \\rho\\in\\mathrm{FArg}::={}&R\\mid x:\\&^\\mathbf{mut}\\tau\\\\\n  \\mathrm{Item}::={}&\\dots\\mid\\mathsf{func}\\;f(\\overline{\\rho}):\\overline{R}:=e\\mid\\mathsf{proc}\\;f(\\overline{\\rho}):\\overline{R}:=e\n\\end{align*}\nWe have to modify \\textsf{ok-proc} to accomodate the new arguments:\n\\begin{mathparpagebreakable}\n  \\infer[ok-func, ok-proc]\n    {\\mathbf{kw}\\in\\{\\mathsf{func},\\mathsf{proc}\\}\\quad \\Gamma\\proves \\overline{\\rho}\\;\\mathsf{args}\\Rightarrow\\overline R\\quad\n      \\Gamma,\\overline{R} \\proves\\textstyle\\sum\\overline{S}\\;\\mathsf{type}\\quad\n      \\Gamma,(\\mathsf{self}(\\overline{\\rho}):\\overline{S}),\\overline{R} \\proves e:\\textstyle\\sum\\overline{S}\\makesto \\core{\\bar \\rho}}\n    {\\Gamma \\proves \\mathbf{kw}\\;f(\\overline{\\rho}):\\overline{S}:=e\\makes \\Gamma',\\ \\mathbf{kw}\\;f(\\overline{\\rho}):\\overline{S}}\\and\n\\end{mathparpagebreakable}\nwhere we have a new judgment for elaborating function arguments, whose only interesting case elaborates $x:\\&^\\mathbf{mut}\\tau$ to $\\ghost v:\\tau,x:\\&^\\mathbf{sn}v$:\n\n\\judgment[Argument elaboration]{\\Gamma\\proves \\overline{\\rho}\\;\\mathsf{args}\\Rightarrow\\overline R}\n\\begin{mathparpagebreakable}\n  \\axiom[args-zero]{\\Gamma\\proves \\cdot\\Rightarrow\\cdot}\\and\n  \\infer[args-arg]\n    {\\Gamma\\proves \\overline{\\rho}\\Rightarrow \\bar R}\n    {\\Gamma\\proves \\overline{\\rho},R'\\Rightarrow R,R'}\\and\n  \\infer[args-mut]\n    {\\Gamma\\proves \\overline{\\rho}\\Rightarrow \\bar R\\quad\n      \\Gamma,\\bar R\\proves \\tau\\;\\mathsf{type}}\n    {\\Gamma\\proves \\overline{\\rho},x:\\&^\\mathbf{mut}\\tau\\Rightarrow \\bar R,\\ghost v:\\tau,x:\\&^\\mathbf{sn}v}\\and\n\\end{mathparpagebreakable}\n\nThe $\\core{\\bar \\rho}$ that appears in \\textsc{ok-proc} denotes a final function context that moves all regular function arguments, but the $\\ghost v:\\tau$ variables generated by $x:\\&^\\mathbf{mut}\\tau$ elaboration are not moved. This ensures that they are still valid at function return.\n\nFinally, we have to describe how a function is called. In short, $e$ matches an argument of type $x:\\&^\\mathbf{mut}\\tau$ if $e:\\&^\\mathbf{sn}\\eta$ for some $\\eta$, which is ``captured'' by the function and modified, generating a fresh $v':\\tau$ and a mutation record $\\eta\\gets v'$.\n\n\\subsubsection{Shared pointers}\n\nShared pointers are the most complex, because they cannot be modeled by separating conjunctions, at least without techniques such as fractional ownership. This is not a problem until we get to the underlying separation logic. Here we only need to mark work that will be perfomed later on.\n\nWe introduce a new kind of variable modifier, a heap variable. $\\hat x:\\tau$ means that $x:\\tau$, but $x$ is not owned by the current context. Heap variables can overlap each other, but not other regular variables in the context.\n\nHeap variables resemble shared references from Rust, and in particular they are annotated with a ``lifetime''. The difference is that the pointer-ness is separated out; a heap variable directly has the type of the pointee, and the pointer is just a $\\&^\\mathbf{sn}\\eta$ where $\\eta$ is a heap variable.\n\n\\begin{mathparpagebreakable}\n  a\\in\\mathrm{Lft}::=\\mathsf{extern}\\mid x\\and\n  \\mathrm{Arg}::=\\dots\\mid \\mathsf{ref}^a\\;x:\\tau\\and\n  \\mathrm{FArg}::=\\dots\\mid \\mathsf{ref}\\;x\\and\n  \\mathrm{TuplePattern}::=\\dots\\mid \\mathsf{ref}^a\\;x\\and\n  \\axiom[tpt-ref]{\\Gamma \\proves \\mathsf{ref}^a\\;x:\\tau\\Rightarrow \\mathsf{ref}^a\\;x:\\tau}\\and\n  \\infer[arg-ref]\n    {\\mathrm{Var}(a)\\subseteq \\Gamma\\quad\n      \\Gamma \\proves \\tau\\;\\mathsf{type}}\n    {\\Gamma \\proves \\mathsf{ref}^a\\; x:\\tau\\;\\mathsf{arg}}\\and\n  \\infer[args-ref]\n    {\\Gamma\\proves \\overline{\\rho}\\Rightarrow \\bar R\\quad\n      \\Gamma,\\bar R\\proves \\tau\\;\\mathsf{type}}\n    {\\Gamma\\proves \\overline{\\rho},\\mathsf{ref}\\;x:\\tau\\Rightarrow \\bar R,\\mathsf{ref}^\\mathsf{extern}\\;x:\\tau}\\and\n  \\infer[tye-struct-ref]\n    {\\Gamma \\proves \\eta:\\core\\tau\\quad\n      \\Gamma \\proves \\langle \\overline{e}\\rangle:\\textstyle\\sum \\bar R[\\eta/x]\\makes\\Gamma'}\n    {\\Gamma \\proves \\langle \\eta,\\overline{e}\\rangle: \\textstyle\\sum \\mathsf{ref}^{\\mathrm{Lft}(\\eta)}\\;x:\\tau,\\bar R\\makes\\Gamma'}\\and\n  {\\mathrm{Lft}(x)=x\\atop\n    \\mathrm{Lft}(\\eta[pe])=\\mathrm{Lft}(\\eta)}\n\\end{mathparpagebreakable}\n\nUsing heap variables, we can desugar shared references similarly to owned pointers:\n\n\\begin{mathparpagebreakable}\n  \\mathrm{Type}::=\\dots\\mid \\&^a\\tau\\and\n  \\core{\\&^a\\tau}=\\N_{64}\\and\n  \\boxed{x:\\&^a\\tau}=\\exists v:\\mathsf{ref}^a\\;\\tau,x\\mapsto v\\\\\n  \\infer[ty-shr]\n    {\\mathrm{Var}(a)\\subseteq \\Gamma\\quad\n      \\Gamma \\proves \\tau\\;\\mathsf{type}}\n    {\\Gamma \\proves \\&^a\\tau\\;\\mathsf{type}}\\and\n  \\infer[tpt-shr]\n    {\\Gamma \\proves \\mathsf{ref}^a\\; t:\\textstyle \\tau\\Rightarrow \\bar{S}\\quad\n      \\Gamma,\\bar{S} \\proves t':\\textstyle \\&^\\mathbf{sn}t\\Rightarrow \\bar{S}'}\n    {\\Gamma \\proves \\langle t,t'\\rangle:\\&^a\\tau\\Rightarrow \\bar{S},\\bar{S}'}\\and\n\\end{mathparpagebreakable}\n\n\\subsection{Arrays}\\label{sec:arrays}\n\nArrays here are fixed length, depending on another variable in the context.\n\n\\begin{mathparpagebreakable}\n  \\mathrm{Type}::=\\dots\\mid \\mathsf{array}\\;\\tau\\;pe\\and\n  \\core{\\mathsf{array}\\;\\tau\\;n}=\\mathsf{array}\\;\\core\\tau\\;n\\and\n  \\boxed{x:\\mathsf{array}\\;\\tau\\;n}=(x:n\\to\\core\\tau)\\ast\\textstyle\\Sep_{i<n}\\boxed{x[i]:\\tau}\\\\\n  \\infer[ty-array]\n    {\\Gamma \\proves \\tau\\;\\mathsf{type}\\quad\n      \\Gamma \\proves n:\\N_s}\n    {\\Gamma \\proves \\mathsf{array}\\;\\tau\\;n\\;\\mathsf{type}}\\and\n\\end{mathparpagebreakable}\n\nTODO\n\n\\section{The Layout pass}\\label{sec:layout}\n\nThe layout pass is responsible for assigning concrete memory locations to variables in the code. In particular, multiple variables may overlap the same memory location if they are never \\emph{live} at the same time, which is to say, the last use of one variable comes before the definition of the second. The analysis pass that determines these relations is considered part of the ``nondeterministic'' part of the compiler, meaning that it requires no proof. Instead, the analysis pass produces a satisfying layout, and the typing relation will validate that a layout puts variables in disjoint locations if they are live at the same time.\n\nTo that end, we introduce another syntactic category not present in the source language, a \\emph{machine place}, or M-place for short.\n\n$$\\mu::=\\mathsf{Reg}\\;r\\mid \\mathsf{Stack}\\;s$$\n\nThe registers $r$ correspond to the registers on the machine, so there is one for every general-purpose register. (On x86-64 there are 16 general purpose registers, but RSP is the stack pointer, and one register is reserved by the compiler for spilling, so there are 14 registers available for use.)\n\nThe stack locations $s$ correspond to an abstraction of the stack frame, optimized for disjointness proofs. A stack frame has a series-parallel layout:\n$$\\phi ::= \\phi_0\\ast\\phi_1\\mid \\phi_0\\cup \\phi_1\\mid |\\tau|$$\nand $s$ is a path into the stack frame:\n$$s ::= \\mathsf{id}\\mid s.0\\mid s.1 \\mid s.l \\mid s.r$$\nwith the following typing rules:\n\n\\judgment[Stack variable typing]{\\phi\\proves s:\\phi'}\n\\begin{mathparpagebreakable}\n  \\axiom[stk-id]{\\phi\\proves \\mathsf{id}:\\phi}\\and\n  \\infer[stk-fst]\n    {\\phi\\proves s:\\phi_1\\ast \\phi_2}\n    {\\phi\\proves s.0:\\phi_1}\\and\n  \\infer[stk-snd]\n    {\\phi\\proves s:\\phi_1\\ast \\phi_2}\n    {\\phi\\proves s.1:\\phi_2}\\and\n  \\infer[stk-left]\n    {\\phi\\proves s:\\phi_1\\cup \\phi_2}\n    {\\phi\\proves s.l:\\phi_1}\\and\n  \\infer[stk-right]\n    {\\phi\\proves s:\\phi_1\\cup \\phi_2}\n    {\\phi\\proves s.r:\\phi_2}\n\\end{mathparpagebreakable}\n\nIntuitively, $\\phi_1\\ast\\phi_2$ is the stack layout consisting of the layout $\\phi_1$ followed by $\\phi_2$ in the bytes immediately after, while $\\phi_1\\cup\\phi_2$ consists of $\\phi_1$ and $\\phi_2$ superimposed on the same bytes (taking up size equal to the larger of the two).\n\nAt a given point in execution, each of the unions has one of its members ``active'' and the other ``inactive'', and a variable can only be accessed if it is active in all parent unions.\nA ghost variable is never assigned any stack location and hence it can never be accessed. More formally, we say that two stack paths are \\emph{incompatible}, written $s_1\\perp s_2$, if there exists $s$ such that $s_1$ extends $s.l$ and $s_2$ extends $s.r$, or vice versa. We will maintain the invariant that if two variables in the context are represented by stack paths $s_1$ and $s_2$ then they are compatible.\n\n\\end{document}\n", "meta": {"hexsha": "8bc7437bdb3487908fd4da44b175a07abc4fe9ee", "size": 54030, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "mm0-rs/theory/separation_logic.tex", "max_stars_repo_name": "david-a-wheeler/mm0", "max_stars_repo_head_hexsha": "97e6bb4da8a880f9f38df8ba3a9412ec5be1c017", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mm0-rs/theory/separation_logic.tex", "max_issues_repo_name": "david-a-wheeler/mm0", "max_issues_repo_head_hexsha": "97e6bb4da8a880f9f38df8ba3a9412ec5be1c017", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mm0-rs/theory/separation_logic.tex", "max_forks_repo_name": "david-a-wheeler/mm0", "max_forks_repo_head_hexsha": "97e6bb4da8a880f9f38df8ba3a9412ec5be1c017", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 63.6395759717, "max_line_length": 774, "alphanum_fraction": 0.6920784749, "num_tokens": 17776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3231629675952776}}
{"text": "\\documentclass[a4paper]{article}\n\n\\input{temp}\n\n\\setcounter{section}{-1}\n\n\\begin{document}\n\n\\title{Representation Theory}\n\n\\maketitle\n\n\\newpage\n\n\\tableofcontents\n\n\\newpage\n\n\\section{Introduction}\nRepresentaiton theory is the theory of how \\emph{groups} act as groups of linear transformations on \\emph{vector spaces}. \n\nHere the groups are either \\emph{finite}, or \\emph{compact topological groups} (infinite), for example, $SU(n)$ and $O(n)$. The vector spaces we conside are finite dimensional, and usually over $\\C$. Actions are \\emph{linear} (see below).\n\nSome books: James-Liebeck (CUP); Alperin-Bell (Springer); Charles Thomas, \\emph{Representations of finite and Lie groups}; Onlne notes: SM, Teleman; P.Webb \\emph{A course in finite group representation theory} (CUP); Charlie Curtis, \\emph{Pioneers of representation theory} (history).\n\n\\newpage\n\n\\section{Group actions}\n\nThroughout this course, if not specified otherwise:\\\\\n$\\bullet$ $F$ is a field, usually $\\C$, $\\R$ or $\\Q$. When the field is one of these, we are discussing \\emph{ordinary representation theory}. Sometimes $F=F_p$ or $\\bar{F}_p$ (algebraic closure, see Galois Theory), in which case the theory is called \\emph{modular representation theory};\\\\\n$\\bullet$ $V$ is a vector space over $F$, always finite dimensional;\\\\\n$GL(V) =\\{\\theta : V \\to V, \\theta$ linear, invertible$\\}$, i.e. $\\det \\theta \\neq 0$.\n\nRecall from Linear Algebra:\\\\\nIf $\\dim_F V = n < \\infty$, choose basis $e_1,...,e_n$ over $F$, so we can identify it with $F^n$. Then $\\theta \\in GL(V)$ corresponds to an $n \\times n$ matrix $A_\\theta = (a_{ij})$, where $\\theta(e_j) = \\sum_i a_{ij} e_i$. In fact, we have $A_\\theta \\in GL_n(F)$, the general linear group.\n\n(1.1) $GL(V) \\cong GL_n(F)$ as groups by $\\theta \\to A_\\theta$ ($A_{\\theta_1 \\theta_2} = A_{\\theta_1} A_{\\theta_2}$ and bijection).\\\\\nChoosing different basis gives different isomorphism to $GL_n(F)$, but:\n\n(1.2) Matrices $A_1,A_2$ represent the same element of $GL(V)$ w.r.t different bases iff they are conjugate (similar), i.e. $\\exists X \\in GL_n(F)$ s.t. $A_2 =XA_1 X^{-1}$.\n\nRecall that $\\tr(A) = \\sum_i a_{ii}$ where $A = (a_{ij})$, the \\emph{trace} of $A$.\n\n(1.3) $\\tr(XAX^{-1}) = \\tr(A)$, hence we can define $\\tr(\\theta) = \\tr(A_{\\theta_1})$ independent of basis.\n\n(1.4) Let $\\alpha \\in GL(V)$ where $V$ in f.d. over $\\C$, with $\\alpha^m = \\iota$ for some $m$ (here $\\iota$ is the identity map). Then $\\alpha$ is diagonalisable.\n\nRecall $EndV$ is the set of all ilnear maps $V \\to V$, e.g. $End(F^n) =M_n(F)$ some $n \\times n$ matrices.\n\n(1.5) \\emph{Proposition.} Take $V$ f.d. over $\\C$, $\\alpha \\in End(V)$. Then $\\alpha$ is diagonalisable iff there exists a polynomial $f$ with distinct linear factors with $f(\\alpha) = 0$. For example, in (1.4), where $\\alpha^m = \\iota$, we take $f = X^m - 1 = \\prod_{j=0}^{m-1} (X-\\omega^j)$ where $\\omega = e^{2\\pi i/m}$ is the ($m^{th}$) root of unity. In fact we have:\n\n(1.4)* A finite family of commuting separately diagonalisable automorphisms of a $\\C$-vector space can be simultaneously diagonalised (useful in abelian groups).\n\nRecall from Group Theory:\\\\\n(1.6) The symmetric group, $S_n = Sym(X)$ on the set $X = \\{1,...,n\\}$ is the set of all permutations of $X$. $|S_n| = n!$. The alternating group $A_n$ on $X$ is the set of products of an even number of transpositions (2-cycles). $|A_n| = \\frac{n!}{2}$.\n\n(1.7) Cyclic groups of order $m$: $C_m = <x:x^m = 1>$. For example, $(\\Z/m\\Z, +)$; also, the group of $m^{th}$ roots of unity in $\\C$ (inside $GL_1(\\C)$ = $\\C^*$, the multiplicative group of $\\C$). We also have the group of rotations, centre $O$ of regular $m-$gon in $\\R^2$ (inside $GL_2(\\R)$).\n\n(1.8) Dihedral groups $D_{2m}$ of order $2m = <x,y: x^m = y^2 = 1, yxy^{-1} = x^{-1}>$. Think of this as the set of rotations and reflections preserving a regular $m$-gon.\n\n(1.9) Quaternion group, $Q_8 = <x,y|x^4 = 1, y^2 = x^2, yxy^{-1} = x^{-1}>$ of order $8$. For example, in $GL_2(\\C)$, put $i={{i\\ 0} \\choose {0 \\ i}}, j = {{0 \\ 1} \\choose {-1 \\ 0}}, k = {{0 \\ i} \\choose {i \\ 0}}$, then $Q_8 = \\{\\pm I_2, \\pm i, \\pm j, \\pm k\\}$.\n\n(1.10) The conjugacy class (ccls) of $g \\in G$ is $\\mathcal{C}_G(g) = \\{xgx^{-1} : x \\in G\\}$. Then $|\\mathcal{C}_G (g) | = |G:C_G(g)|$, where $C_G(g) = \\{x \\in G : xg = gx\\}$, the centraliser of $g \\in G$.\n\n(1.11) Let $G$ be a group, $X$ be a set. $G$ acts on $X$ if there exists a map $\\cdot: G \\times X \\to X$ by $(g,x) \\to g\\cdot x$ for $g \\in G$, $x \\in X$, s.t. $1 \\cdot x = x$ for all $x \\in X$, $(gh) \\cdot x = g \\cdot (h\\cdot x)$ for all $g,h \\in G, x \\in X$.\n\n(1.12) Given an action of $G$ on $X$, we obtain a homomorphism $\\theta: G \\to Sym(X)$, called the \\emph{permutation representation} of $G$.\n\\begin{proof}\nFor $g \\in G$, the function $\\theta_g: X \\to X$ by $x \\to gx$ is a permutation on $X$, with inverse $\\theta_{g^{-1}}$. Moreover, $\\forall g_1,g_2 \\in G$, $\\theta_{g_1 g_2} = \\theta_{g_1} \\theta_{g_2}$ since $(g_1g_2) x = g_1(g_2 x)$ for $x \\in X$.\n\\end{proof}\n\n\\newpage\n\n\\section{Basic Definitions}\n\\subsection{Representations}\n\nLet $G$ be finite, $F$ be a field, usually $\\C$.\n\\begin{defi} (2.1)\\\\\nLet $V$ be a f.d. vector space over $F$. A (linear, in some books) \\emph{representation} of $G$ on $V$ is a group homomorphism \n\\begin{equation*}\n\\begin{aligned}\n\\rho = \\rho_V: & G &\\to GL(V)\n\\end{aligned}\n\\end{equation*}\nWrite $\\rho_g$ for the image $\\rho_V(g)$; so for each $g \\in G$, $\\rho_g \\in GL(V)$, and $\\rho_{g_1 g_2} = \\rho_{g_1} \\rho_{g_2}$, and $(\\rho_g)^{-1} = \\rho_{g^{-1}}$.\\\\\nThe \\emph{dimension} (or \\emph{degree}) of $\\rho$ is $\\dim_F V$.\n\\end{defi}\n\n(2.2) Recall $\\ker \\rho \\triangleleft G$ (kernel is a normal subgroup), and $G/\\ker \\rho \\cong \\rho(G) \\leq GL(V)$ (1st isomorphism theorem). We say $\\rho$ is \\emph{faithful} if $\\ker \\rho = 1$.\n\nAn alternative (and equivalent) approach is to observe that a representation of $G$ on $V$ is \"the same as\" a \\emph{linear action} of $G$:\n\n\\begin{defi} (2.3)\\\\\n$G$ \\emph{acts linearly} on $V$ if there exists a \\emph{linear action}\n\\begin{equation*}\n\\begin{aligned}\nG \\times V &\\to V\\\\\n(g,v) &\\to gv\n\\end{aligned}\n\\end{equation*}\nBy linear action we mean: (action) $(g_1 g_2) v = g_1(g_2 v)$, $1v=v$ $\\forall g_1,g_2 \\in G, v \\in V$, and (linear) $g(v_1+v_2) = gv_1+gv_2$, $g(\\lambda v) = \\lambda gv$ $\\forall g \\in G, v_1,v_2 \\in V, \\lambda \\in F$.\\\\\nNow if $G$ acts linearly on $V$, the map\n\\begin{equation*}\n\\begin{aligned}\nG &\\to GL(V)\\\\\ng &\\to \\rho_g\n\\end{aligned}\n\\end{equation*}\nwith $\\rho_g:v \\to gv$ is a representation of $G$. Conversely, given a representation $\\rho: G \\to GL(V)$, we have a linear action of $G$ on $V$ via $g \\cdot v := \\rho(g) v$ $\\forall v \\in V, g \\in G$.\n\\end{defi}\n\n(2.4) In (2.3) we also say that $V$ is a $G$-space or that $V$ is a $G$-module. In fact if we define the \\emph{group algebra} $FG$, or $F[G]$, to be $\\{ \\sum \\alpha_j g: \\alpha_j \\in F\\}$ with natural addition and multiplication, then $V$ is actually a $FG$-module (in the sense from GRM).\n\n(2.5) $R$ is a \\emph{matrix representation} of $G$ of degree $n$ if $R$ is a homomorphism $G \\to GL_n (F)$. Given representation $\\rho:G \\to GL(V)$ with $\\dim_F V=n$, fix basis $B$; we get matrix representation\n\\begin{equation*}\n\\begin{aligned}\nG &\\to GL_n(F)\\\\\ng &\\to [\\rho(g)]_B\n\\end{aligned}\n\\end{equation*}\nConversely, given matrix representation $R:G \\to GL_n(F)$, we get representation\n\\begin{equation*}\n\\begin{aligned}\n\\rho: G &\\to GL(F^n)\\\\\ng &\\to \\rho_g\n\\end{aligned}\n\\end{equation*}\nvia $\\rho_g(v) = R_g v$ where $R_g$ is the matrix of $g$.\n\n\\begin{eg} (2.6)\\\\\nGiven any group $G$, take $V=F$ the 1-dimensional space, and \n\\begin{equation*}\n\\begin{aligned}\n\\rho:G &\\to GL(F)\\\\\ng &\\to (id: F \\to F)\n\\end{aligned}\n\\end{equation*}\nis known as the trivial representation of $G$. So $\\deg \\rho = 1$ ($\\dim_F F = 1$).\n\\end{eg}\n\n\\begin{eg} (2.7)\\\\\nLet $G=C_4 = <x:x^4=1>$. Let $n=2$, and $F=\\C$. Note that any $R:x \\to X$ will determine $x^j \\to X^j$ as it is a homomorphism, and also we need $X^4 = I$. So we can take $X$ to be diagonal matrix -- any such with diagonal entries a root to $x^4=1$, i.e. $\\{\\pm 1,\\pm i\\}$, or if $X$ is not diagonal then it will be similar to a diagonal matrix by (1.4) ($X^4=I$).\n\\end{eg}\n\n\\subsection{Equivalent representations}\n\n\\begin{defi} (2.8)\\\\\nFix $G,F$. Let $V,V'$ be $F$-spaces, and $\\rho:G \\to GL(V)$, $\\rho': G \\to GL(V')$ which are representations of $G$. The linear map $\\phi: V \\to V'$ is a $G$-homomorphism if $$\\phi\\rho(g) = \\rho'(g)\\phi \\forall g \\in G (*)$$ We can understand this more by the following diagram:\n\n\\includegraphics[scale=0.5]{image/Rep_01.png}\n\nWe say $\\phi$ \\emph{intertwines} $\\rho,\\rho'$. Write $Hom_G(V,V')$ for the $F$-space of all these.\\\\\n$\\phi$ is a $G$-isomorphism if it is also bijective; if such $\\phi$ exists, $\\rho,\\rho'$ are isomorphic/equivalent representations. If $\\phi$ is a $G$-isomorphism, we can write $(*)$ as $\\rho' = \\phi\\rho\\phi^{-1}$.\n\\end{defi}\n\n\\begin{lemma} (2.9)\\\\\nThe relation \"being isomorphic\" is an equivalent relation on the set of all representations of $G$ (over $F$).\n\\end{lemma}\n\n\\begin{rem} (2.10)\\\\\nIf $\\rho,\\rho'$ are isomorphic representations, they have the same dimension.\n\nThe converse may be false: $C_4$ has four non-isomorphic 1-dimensional representations: if $\\omega = e^{2\\pi i/4}$ then they are $\\rho_j(x^i) = \\omega^{ij}$ ($0 \\leq i \\leq 3$).\n\\end{rem}\n\n\\begin{rem} (2.11)\\\\\nGiven $G$, $V$ over $F$ of dimension $n$ and $\\rho:G \\to GL(V)$. Fix basis $B$ for $V$: we get a linear isomorphism \n\\begin{equation*}\n\\begin{aligned}\n\\phi:V &\\to F^n\\\\\nv &\\to [v]_B\n\\end{aligned}\n\\end{equation*}\nand we get a representation $\\rho': G \\to GL(F^n)$ isomorphic to $\\rho$:\n\n\\includegraphics[scale=0.5]{image/Rep_02.png}\n\\end{rem}\n\n(2.12) In terms of matrix representations, we have\n\\begin{equation*}\n\\begin{aligned}\nR: G &\\to GL_n(F),\\\\\nR':G &\\to GL_n(F)\n\\end{aligned}\n\\end{equation*}\nare ($G$)-isomorphic or equivalent if there exists a nonsingular matrix $X \\in GL_n(F)$ with $R'(g) = XR(g)X^{-1}$ $\\forall g \\in G$.\n\nIn terms of linear $G$-actions, the actions of $G$ on $V$,$V'$ are $G$-isomorphic if there exists isomorphisms $\\phi:V \\to V'$ such that $g:\\phi(v) = \\phi(gv)$ $\\forall v \\in V,g \\in G$.\n\n\\subsection{Subrepresentations}\n\\begin{defi} (2.13)\\\\\nLet $\\rho:G \\to GL(V)$ be a representation of $G$. We say $W \\leq V$ is a $G$-subspace if it's a subspace and it is $\\rho(G)$-invariant, i.e. $\\rho_g(W) \\leq W \\forall g \\in G$. Obviously $\\{0\\}$ and $V$ are $G$-subspaces, however.\\\\\n$\\rho$ is \\emph{irreducible/simple} representation if there are no proper $G$-subspaces.\n\\end{defi}\n\n\\begin{eg} (2.14)\\\\\nAny $1$-dimensional representation of $G$ is irreducible, but not conversely, e.g. $D_8$ has $2$-dimensional $\\C$-irreducible representation.\n\\end{eg}\n\n(2.15) In definition (2.13), if $W$ is a $G$-subspace, then the corresponding map\n\\begin{equation*}\n\\begin{aligned}\nG &\\to GL(W)\\\\\ng &\\to \\rho(g)|_W\n\\end{aligned}\n\\end{equation*}\nis a representation of $G$, a \\emph{subrepresentation} of $\\rho$.\n\n\\begin{lemma} (2.16)\\\\\nIn definition (2.13), given $\\rho:G \\to GL(V)$, if $W$ is a $G$-subspace of $V$ and if $B=\\{v_1,...,v_n\\}$ is a basis containing basis $B_1 = \\{v_1,...,v_m\\}$ of $W$ ($0<m<n$) then the matrix of $\\rho(g)$ w.r.t. $B$ has block upper triangular form as the graph below, for each $g \\in G$.\n\\includegraphics[scale=0.5]{image/Rep_03.png}\n\\end{lemma}\n\n\\begin{eg} (2.17)\\\\\n(i) The irreducible representations of $C_4=\\bra x:x^4=1\\ket$ are all $1$-dimensional and four of these are $x\\to i,x \\to -1, x \\to -i, x \\to 1$. In general, $C_m=\\bra x:x^m=1\\ket$ has precisely $m$ irreducible complex representations, all of dimension 1. In fact, all complex irreducible representations of a finite abelian group are $1$-dimensional (use (1.4)* or see (4.4) below).\\\\\n(ii) $G=D_6$: any irreducible $C$-representation has dimension $\\leq 2$.\\\\\nLet $\\rho:G \\to GL(V)$ be irreducible $G$-representation. Let $r,s$ be rotation and reflection in $D_6$ respectively. Let $V$ be eigenvector of $\\rho(r)$. So $\\rho(r) v = \\lambda v$ for some $\\lambda \\neq 0$. Let $W=span\\{v,\\rho(s)v\\} \\leq V$. Since $\\rho(s)\\rho(s)v = v$ and $\\rho(r)\\rho(s) v = \\rho(s)\\rho(r)^{-1} v = \\lambda^{-1} \\rho(s) v$, both of which are in $W$; so $W$ is $G$-invariant, i.e. a $G$-subspace. Since $V$ is irreducible, $W=V$.\n\\end{eg}\n\n\\begin{defi} (2.18)\\\\\nWe say at $\\rho:G \\to GL(V)$ is \\emph{decomposable} if there are proper $G$-invariant subspaces $U,W$ with $V = U \\oplus W$. Say $\\rho$ is direct sum $\\rho_U \\oplus \\rho_W$. If no such decomposition exists, we say that $\\rho$ is \\emph{indecomposable}.\n\\end{defi}\n\n\\begin{lemma} (2.19)\\\\\nSuppose $\\rho:G \\to GL(V)$ is decomposable with $G$-invariant decomposition $V=U \\oplus W$. If $B$ is a basis $\\{\\underbrace{u_1,...,u_k}_{B_1}, \\underbrace{w_1,...,w_l}_{B_2}\\}$ of $V$ consisting of basis of $U$ and basis of $W$, then w.r.t. $B$, $\\rho(g)_B$ is a block diagonal matrix $\\forall g\\in G$ as \n\\begin{equation*}\n\\begin{aligned}\n\\rho(g)_B = \\begin{pmatrix}\n[\\rho_W(g)]_{B_1} & 0\\\\\n0 & [\\rho_W(g)]_{B_2}\n\\end{pmatrix}\n\\end{aligned}\n\\end{equation*}\n\\end{lemma}\n\n\\begin{defi} (2.20)\\\\\nIf $\\rho:G \\to GL(V)$, $\\rho':G \\to GL(V')$, the \\emph{direct sum} of $\\rho,\\rho'$ is $$\\rho \\oplus \\rho':G \\to GL(V \\oplus V')$$ where $\\rho \\oplus \\rho'(g) (v_1+v_2) = \\rho(g)v_1 + \\rho'(g) v_2$, a \\emph{block diagonal action}. For matrix representations $R:G \\to GL_n(F)$, $R':G \\to GL_{n'} (F)$, define $R \\oplus R': G \\to GL_{n+n'}(F)$:\n\\begin{equation*}\n\\begin{aligned}\ng \\to \\begin{pmatrix}\nR(g) & 0\\\\\n0 & R'(g)\n\\end{pmatrix}\n\\end{aligned}\n\\end{equation*}\n\\end{defi}\n\n\\newpage\n\\section{Complete reducibility and Maschke's theorem}\n\\begin{defi} (3.1)\\\\\nA representation $\\rho:G \\to GL(V)$ is \\emph{completely reducible}, or \\emph{semisimple}, if it is a direct sum of irreducible representations. Evidently, irreducible implies completely reducible (lol).\n\\end{defi}\n\n\\begin{rem} (3.2)\\\\\n(1) The converse is false;\\\\\n(2) See sheet 1 Q3: $\\C$-representation of $\\Z$ is not completely reducible and also representation of $C_p$ over $\\F_p$ is not c.r..\n\nFron now on, take $G$ finite and $char\\ F =0$.\n\\end{rem}\n\n\\begin{thm} (3.3)\\\\\nEvery f.d. representation $V$ of a finite group over a field of char $0$ is completely reducible, i.e. $$V \\cong V_1 \\oplus ... \\oplus V_r$$is a direct sum of representations, each $V_i$ irreducible.\n\\end{thm}\n\nIt is enough to prove:\n\n\\begin{thm} (3.4 Maschke's theorem, 1899)\\\\\nLet $G$ be finite, $\\rho:G \\to GL(V)$ a f.d. representation, $char\\ F = 0$. If $W$ is a $G$-subspace of $V$, then there exists a $G$-subspace $U$ of $V$ s.t. $V = W \\oplus U$, a direct sum of $G$-subspaces.\n\\begin{proof} (1)\\\\\nLet $W'$ be any \\emph{vector subspace} complement of $W$ in $V$, i.e. $V=W \\oplus W'$ as vector spaces, and $W \\cap W'=0$. Let $q:V \\to W$ be th projection of $V$ onto $W$ along $W'$ ($\\ker q = W'$), i.e. if $v=w+w'$ then $q(v) = w$. Define $$\\bar{q} : v \\to \\frac{1}{|G|} \\sum_{g \\in G} g q(g^{-1}v)$$the 'average' of $q$ over $G$. Note that in order for $\\frac{1}{|G|}$ to exists, we need $char\\ F = 0$. It still works if $char\\ F \\nmid |G|$.\\\\\nClaim (1): $\\bar{q}:V \\to W$: For $v \\in V$, $g(q^{-1}v) \\in W$ and $gW \\leq W$;\\\\\nClaim (2): $\\bar{q}(w) = w$ for $w \\in W$: $$\\bar{q}(w) = \\frac{1}{|G|} \\sum_{g \\in G} gq(g^{-1}w) = \\frac{1}{|G|} \\sum g(g^{-1}w) = \\frac{1}{|G|} \\sum w = w$$\nSo these two claims imply that $\\bar{q}$ projects $V$ onto $W$.\\\\\nClaim (3) If $h \\in G$ then $h\\bar{q}(v) = \\bar{q}(hv)$ ($v \\in V$):\n\\begin{equation*}\n\\begin{aligned}\nh\\bar{q}(v) &= h\\frac{1}{|G|} \\sum_g g \\cdot q(g^{-1} v)\\\\\n&= \\frac{1}{|G|} \\sum_g hgq(g^{-1} v)\\\\\n&= \\frac{1}{|G|} \\sum (hg) q((hg)^{-1} hv)\\\\\n&= \\frac{1}{|G|} \\sum_g gq(g^{-1}(hv))\\\\\n&= \\bar{q}(hv\\\\\n&= \\bar{q}(hv))\n\\end{aligned}\n\\end{equation*}\nWe'll then show that the kernel of this map is $G$-invariant, so this gives a $G$-summand on Thursday.\n\nLet's now show $\\ker \\bar{q}$ is $G$-invariant. If $v \\in \\ker \\bar{q}$, then $h\\bar{q}(v) = 0 = \\bar{q}(hv)$, so $hv \\in \\ker \\bar{q}$. Thus $V = im \\bar{q} \\oplus \\ker \\bar{q} = W \\oplus \\ker \\bar{q}$ is a $G$-subspace decomposition.\n\nWe can deduce (3.3) from (3.4) by induction on $\\dim V$. If $\\dim V = 0$ or $V$ is irreducible, then result is clear. Otherwise, $V$ has non-trivial $G$-invariant subspace, $W$. Then by (3.4), there exists $G$-invariant complement $U$ s.t. $V = U \\oplus W$ as representations of $G$. But $\\dim U, \\dim W < \\dim V$. So by induction they can be broken up into direct sum of irreducible subrepresentations.\n\\end{proof}\n\nThe second proof uses inner products, hence we need to take $F = \\C$ and can be generalised to compact groups in section 15.\\\\\nRecall, for $V$ a $\\C$-space, $\\bra,\\ket$ is a \\emph{Hermitian inner product} if\\\\\n(a) $\\bra w,v\\ket =\\overline{\\bra v,w\\ket}$ $\\forall v,w$ (Hermitian);\\\\\n(b) linear in RHS (sesquilinear);\\\\\n(c) $\\bra v,v\\ket > 0$ iff $v \\neq 0$ (positvie definite).\n\nAdditionally, $\\bra,\\ket$ is \\emph{G-invariant} if \\\\\n(d) $\\bra gv,gw\\ket = \\bra v,w\\ket$ $\\forall v,w \\in V, g \\in G$.\n\nNote if $W$ is $G$-invariant subspace of $V$, with $G$-invariant inner product, then $W^\\perp$ is also $G$-invariant, and $V \\oplus W^\\perp$. For all $v \\in W^\\perp$, $g \\in G$, we have to show that $gv \\in W^\\perp$. But $v \\in W^\\perp \\iff \\bra v,w\\ket = 0 \\forall w \\in W$. Thus by (d), $\\bra gv,gw\\ket = 0$ $\\forall g \\in G \\forall w \\in W$. Hence $\\bra gv,w'\\ket = 0$ $\\forall w' \\in W$. Since we can choose $w=g^{-1}w' \\in W$ by $G$-invariance of $W$. Thus $gv \\in W^\\perp$ since $g$ was arbitrary.\n\nHence if there is a $G$-invariant inner product on any $G$-space, we get another proof of Maschke's theorem:\n\n(3.4*) (Weyl's unitary trick)\\\\\nLet $\\rho$ be a complex representation of the finite group $G$ on the $\\C$-space $V$. Then there is a $G$-invariant Hermitian inner product on $V$.\n\\begin{rem}\nRecall the \\emph{unitary group} $U(V)$ on $V$: $\\{f \\in GL(V): (fu,fv) = (u,v) \\forall u,v \\in V\\} = \\{A \\in GL_n(\\C) : A \\bar{A}^T = I\\} (= U(n))$ by choosing orthonormal basis.\\\\\nSheet 1 Q.12: any finite subgroup of $GL_n(\\C)$ is conjugate to a subgroup of $U(n)$.\n\\end{rem}\n\n\\begin{proof} (2)\\\\\nThere exist an inner product on $V$: take basis $e_1,...,e_n$ and define $(e_i,e_j) = \\delta_{ij}$, extended sesquilinearly. Now\n\\begin{equation*}\n\\begin{aligned}\n\\bra v,w\\ket := \\frac{1}{|G|} \\sum_{g \\in G} (gv,gw)\n\\end{aligned}\n\\end{equation*}\nwe claim that $\\bra,\\ket$ is sesquilinear, positive definite and $G$-invariant: if $h \\in G$, then\n\\begin{equation*}\n\\begin{aligned}\n\\bra hv,hw\\ket = \\frac{1}{|G|} \\sum_{g \\in G} ((gh)v,(gh)w)\\\\\n&= \\frac{1}{|G|} \\sum_{g' \\in G} (g'v, g'w)\\\\\n&= \\bra v,w\\ket\n\\end{aligned}\n\\end{equation*}\nfor all $v,w \\in V$.\n\\end{proof}\n\\end{thm}\n\n\\begin{defi} (3.5, the regular representation)\\\\\nRecall \\emph{group algebra} of $G$ is $F$-space $FG = span\\{e_g:g \\in G\\}$. There is a linear $G$-action\n\\begin{equation*}\n\\begin{aligned}\nh \\in G, h \\sum_{g \\in G} a_g e_g = \\sum_{g \\in G} a_g e_{hg} (=\\sum_{g' \\in G} a_{h^{-1} g'} e_{g'})\n\\end{aligned}\n\\end{equation*}\n$\\rho_{reg}$ is the corresponding representation, the \\emph{regular representation} of $G$. This is faithful of $\\dim |G|$. $FG$ is the \\emph{regular module}.\n\\end{defi}\n\n\\begin{prop}\nLet $\\rho$ be an irreducible representation of $G$ over a field of characteristic 0. Then $\\rho$ is isomorphic to a subrepresentation of $\\rho_{reg}$.\n\\begin{proof}\nTake $\\rho: G \\in GL(V)$ irreducible and let $0 \\neq v \\in V$. Let $\\theta : FG \\to V$ by $\\sum a_g e_g \\to \\sum a_g gv$. Check this is a $G$-homomorphism. Now $V$ is irreducible so $im\\theta = V$ (since $im\\theta$ is a $G$-subspace).\n\nAlso $\\ker\\theta$ is $G$-subspace of $FG$. Let $W$ be $G$-complement of $\\ker \\theta$ in $FG$ (Maschke), so that $W < FG$ is $G$-subspace and $FG = \\ker\\theta \\oplus W$. Thus $W \\cong FG/\\ker \\theta \\cong(G-isomorphism) im\\theta \\cong V$.\n\\end{proof}\n\\end{prop}\n\nMore generally,\n\\begin{defi} (3.7)\\\\\nLet $F$ be a field. Let $G$ act on set $X$. Let $FX = span\\{e_x:x \\in X\\}$ with $G$-action\n\\begin{equation*}\n\\begin{aligned}\ng(\\sum a_x e_x) = \\sum a_x e_{gx}\n\\end{aligned}\n\\end{equation*}\n\\end{defi}\n\nThe representation $G \\to GL(V)$ where $V=FX$ is the corresponding \\emph{permutation representation}. See section 7.\n\n\\newpage\n\n\\section{Schur's lemma}\nIt's really unfair that such an important result is only remembered by a lemma, so we shall call it a theorem.\n\\begin{thm} (4.1, Schur)\\\\\n(a) Assume $V,W$ are irreducible $G$-spaces over field $F$. Then any $G$-homomorphism $\\theta:V \\to W$ is either $0$ or an isomorphism.\\\\\n(b) Assume $F$ is \\emph{algebraically closed}, and let $V$ be an irreducible $G$-space. Then any $G$-endomorphism $V \\to V$ is a scalar multiple of the identity map $\\iota_V$.\n\\begin{proof}\n(a) Let $\\theta:V \\to W$ be a $G$-homomorphism. Then $\\ker$ $\\theta$ is $G$ subspace of $V$ and, since $V$ is irreducible, we get $\\ker\\theta = 0$ or $\\ker\\theta = V$.\\\\\nAnd $im\\theta$ is $G$-subspace of $W$, so as $W$ is irreducible, $im\\theta$ is either $0$ or $W$. Hence, either $\\theta=0$ or $\\theta$ is injective and surjective, hence isomorphism.\\\\\n(b) Since $F$ is algebraically closed, $\\theta$ has an eigenvalue, $\\lambda$. Then $\\theta-\\lambda \\iota$ is singular $G$-endomorphism of $V$, but it cannot be an isomorphism, so it is $0$ (by (a)). So $\\theta = \\lambda \\iota_V$.\n\\end{proof}\n\\end{thm}\n\nRecall from (2.8), the $F$-space $Hom_G(V,W)$ of all $G$-homomorphisms $V \\to W$. Write $End_G(V)$ for the $G$-endomorphisms of $V$.\n\n\\begin{coro} (4.2)\\\\\nIf $V,W$ are irreducible complex $G$-spaces, then\n\\begin{equation*}\n\\begin{aligned}\n\\dim_\\C Hom_G (V,W) = \\left\\{\\begin{array}{ll}\n1 & \\text{ if } V,W \\text{ are } G- \\text{ isomorphic}\\\\\n0 & \\text{ otherwise}\n\\end{array}\n\\right.\n\\end{aligned}\n\\end{equation*}\n\\begin{proof}\nIf $V,W$ are not $G$-isomorphic then the only $G$-homomorphism $V\\to W$ is $0$ by (4.1). Assume $v \\cong_G W$ and $\\theta_1,\\theta-2 \\in Hom_G (V,W)$, both non-zero. Then $\\theta_2$ is invertible by (4.1), and $\\theta_2^{-1} \\theta_1 \\in End_G(V)$, and non-zero, so $\\theta_2^{-1} \\theta_1 = \\lambda\\iota_V$ for some $\\lambda \\in \\C$. Hence $\\theta_1 = \\lambda\\theta_2$.\n\\end{proof}\n\\end{coro}\n\n\\begin{coro} (4.3)\\\\\nIf finite group $G$ has a faithful complex irreducible representation, then $Z(G)$, the centre of the group, is cyclic.\\\\\nNote that the converse is false (Sheet 1, Q10).\n\\begin{proof}\nLet $\\rho:G \\to GL(V)$ be faithful irreducible complex representation. Let $z \\in Z(G)$, so $zg = gz$ $\\forall g \\in G$, hence the map $\\phi_z: v \\to z(v)$ ($v \\in V$) is $G$-endomorphism of $V$, hence is multiplication by scalar $\\mu_z$, say.\\\\\nBy Schur's lemma, $z(v) = \\mu_z v$ $\\forall v$. Then the map \n\\begin{equation*}\n\\begin{aligned}\nZ(G) &\\to \\C^* \\ (\\text{multiplicative group})\\\\\nz &\\to \\mu_z\n\\end{aligned}\n\\end{equation*}\nis a representation of $Z$ and is faithful, since $\\rho$ is. Thus $Z(G)$ is isomorphic to some finite subgroup of $\\C^*$, so is cyclic.\n\\end{proof}\n\\end{coro}\n\nLet's now consider representation of finite abelian groups.\n\n\\begin{coro} (4.4)\\\\\nThe irreducible $\\C$-representations of a finite abelian group are all $1$-dimensional.\n\\begin{proof}\n\\emph{Either}: use (1.4)* to invoke simultaneous diagonalisation: if $v$ is an eigenvector for each $g \\in G$, and if $V$ is irreducible, then $V=\\bra v\\ket$.\\\\\n\\emph{Or}: Let $V$ be an irreducible $\\C$-representation. For $g \\in G$, the map\n\\begin{equation*}\n\\begin{aligned}\n\\theta_g: &V &\\to v\\\\\n&v &\\to gv\n\\end{aligned}\n\\end{equation*}\nis a $G$-endomorphism of $V$, and as $V$ irreducible, $\\theta_g = \\lambda_g \\iota_V$ for some $\\lambda_g \\in \\C$. Thus $gv = \\lambda_g v$ for any $g \\in G$ (so $\\bra v\\ket$ is a $G$-subspace of $V$). Thus as $0 \\neq V$ is irreducible, $V = \\bra v\\ket$, which is $1$-dimensional.\n\\end{proof}\n\\end{coro}\n\n\\begin{rem}\nSchur's lemma fails over non-algebraically closed field, in particular, over $\\R$. For example, let's consider the cyclic group $C_3$. It has 2 irreducible $\\R$-representations, one of dimension 1 (maps everything to 1) and one of dimension 2(imo consider $\\C$ as a dimension 2 space over $\\R$, then map the generator to the 3rd root of unity?) (so 'contradicting' with Schur's lemma via the corollary above).\\\\\nRecall that every finite abelian group $G$ is isomorphic to a product of cyclic groups (see GRM). For example, $C_6 = C_2 \\times C_3$. In fact, it can be written as a product of $C_{p^\\alpha}$ for various primes $p$ and $\\alpha \\geq 1$, and the factors are uniquely determined up to reordering.\n\\end{rem}\n\n\\begin{prop} (4.5)\\\\\nThe finite abelian group $G=C_{n_1} \\times ... \\times C_{n_r}$ has precisely $|G|$ irreducible $\\C$-representations, as described below:\n\\begin{proof}\nWrite $G = \\bra x_1\\ket \\times ... \\bra x_r\\ket$ where $|x_j| = n_j$. Suppose $\\rho$ is irreducible, so by (4.4), it's $1$-dimensional: $\\rho:G \\to \\C^*$.\\\\\nLet $\\rho(1,...,x_j,...,1)$ (all $1$ apart from the $j^{th}$ entry) be $\\lambda_j$. Then $\\lambda_j^{n_j} = 1$, so $\\lambda_j$ is a $n_j$-th root of unity. Now, the values $(\\lambda_1,...,\\lambda_r)$ determine $\\rho$: $$\\rho(x_1^{j_1}, ..., x_r^{j_r}) = \\lambda_1^{j_1}...\\lambda_r^{j_r}$$\nthus $\\rho \\leftrightarrow (\\lambda_1,...,\\lambda_r)$ with $\\lambda_j^{n_j} =1 $ $\\forall j$; we have $n_1...n_r$ such $r$-tuples, each giving $1$-dimensional representation.\n\\end{proof}\n\\end{prop}\n\n\\begin{eg} (4.6)\\\\\nConsider $G=C_4 = \\bra x\\ket$. We could have $\\rho_1(x) = 1,\\rho_2(x) = i,\\rho_3(x)=-1,\\rho_4(x)=-i$.\n\\end{eg}\n\nWarning: There is no \"natural\" 1-1 correspondence between the elements of $G$ and the representations of $G$ ($G$-finite abelian). If you choose an isomorphism $G \\cong C_{a_1} \\times ... \\times C_{a_r}$, then we can identify the two sets (elements of groups and representations of $G$), but it depends on the choice of isomorphism.\n\nIsotypical decomposition:\n\nRecall any diagonalisable endomorphism $\\alpha:V \\to V$ gives eigenspace decomposition of $V \\cong \\oplus_\\lambda V(\\lambda)$, where $V(\\lambda) = \\{v:\\alpha v = \\lambda v\\}$. This is \\emph{caconical} (one of the three useless words: \\emph{arbitrary}(anything), \\emph{canonical}(only one choice), \\emph{uniform}(you can choose, but it doesn't really matter)), in the sense that it depends on $\\alpha$ alone (and nothing else).\\\\\nThere is no canonical eigenbasis of $V$: must choose basis in each $V(\\lambda)$.\n\nWe know that in $char\\ 0$ every representation $V$ decomposes as $\\oplus n_i V_i$, $V_i$ irreducible, $n_i \\geq 0$. How unique is this?\n\nWe have this wishlist (4.7):\\\\\n(a) Uniqueness: for each $V$ there is only one way to decompose $V$ as above. However, this doesn't work obviously.\\\\\n(b) Isotypes: for each $V$, there exists a unique collection of subrepresentations $U_1,...,U_k$ s.t. $V=\\oplus U_i$ and, if $V_i \\subseteq U_i$ and $V'_j \\subseteq U_j$ are irreducible subrepresentations, then $V_i \\cong V'_j$ iff $i = j$.\\\\\n(c) Uniqueness of factors: If $\\oplus_{i=1}^k V_i \\cong \\oplus_{i=1}^k V'_i$ with $V_i,V'_i$ irreducible, then $k=k'$, and $\\exists \\pi \\in S_k$ such that $V'_{\\pi(i)} \\cong V_i$ (Krull-Schimdt theorem).\\\nFor (b),(c) see Teleman section 5.\n\n\\begin{lemma} (4.8)\\\\\nLet $V,V_1,V_2$ be $G-$spaces over $F$.\\\\\n(i) $Hom_G(V,V_1 \\oplus V_2) \\cong Hom_G (V,V_1) \\oplus Hom_G(V,V_2)$;\\\\\n(ii) $Hom_G(V_1\\oplus V_2, V) \\cong Hom_G(V_1,V) \\oplus Hom_G(V_2,V)$;\\\\\n\\begin{proof}\n(i) Let $\\pi_i: V_1 \\oplus V_2 \\to V_i$ be $G$-linear projections onto $V_i$, with kernel $V_{3-i}$ ($i=1,2$).\\\\\nConsider \n\\begin{equation*}\n\\begin{aligned}\nHom_G (V,V_1 \\oplus V_2) &\\to Hom_G (V,V_1) \\oplus Hom_G (V,V_2)\\\\\n\\phi &\\to (\\pi_1 \\phi, \\pi_2 \\phi)\n\\end{aligned}\n\\end{equation*}\nThis map has inverse $(\\psi_1,\\psi_2) \\to \\psi_1+\\psi_2)$. Check details.\\\\\n(ii) The map $\\phi \\to (\\phi|_{V_1},\\phi|_{V_2})$ has inverse $(\\psi_1,\\psi_2) \\to \\psi_1\\pi_1+\\psi_2\\pi_2$.\n\\end{proof}\n\\end{lemma}\n\n\\begin{lemma}\nLet $F$ be algebraically closed, $V=\\oplus_1^n V_i$ a decomposition of $G$-space into irreducible summands. Then, for each irreducible representation $S$ of $G$,\n\\begin{equation*}\n\\begin{aligned}\n\\#\\{j:V_j \\cong S\\} = \\dim Hom_G(S,V)\n\\end{aligned}\n\\end{equation*}\nwhere $\\#$ means 'number of times'. This is called the \\emph{multiplicity} of $S$ in $V$.\n\\begin{proof}\nIndunction on $n$. $n=0,1$ are trivial.\\\\\nIf $n>1$, $V=\\oplus_1^{n-1} V_i \\oplus V_n$. By (4.8) we have\n\\begin{equation*}\n\\begin{aligned}\n\\dim Hom_G (S,\\oplus_1^{n-1} V_i \\oplus V_n) = \\dim Hom(S,\\oplus_1^{n-1} V_i) + \\underbrace{\\dim Hom_G (S,V_n)}_{\\text{Schur's lemma}}\n\\end{aligned}\n\\end{equation*}\n\\end{proof}\n\\end{lemma}\n\n\\begin{defi} (4.10)\\\\\nA decomposition of $V$ as $\\oplus W_j$ where each $W_j \\cong n_j$ copies of irreducible representations $S_j$ (each non-isomorphic for each $j$) is the \\emph{canonical decomposition} or the decomposition into \\emph{isotypical components} $W_j$. For $F$ algebraically closed, $n_j=\\dim Hom_G(S_j,V)$.\n\\end{defi}\n\n\\newpage\n\n\\section{Character theory}\n\nWe want to attach invariants to representation $\\rho$ of a finite group $G$ on $V$. Matrix coefficients of $\\rho(g)$ are basis dependent, so not true invariants.\\\\\nLet's take $F=\\C$, $G$ finite, $\\rho=\\rho_V: G \\to GL(V)$ be a representation of $G$.\n\n\\begin{defi} (5.1)\\\\\nThe \\emph{character} $\\chi_\\rho = \\chi_V = \\chi$ is defined as $\\chi(g) = \\tr \\rho(g) = \\tr R(g)$ where $R(g)$ is any matrix representation of $\\rho(g)$ w.r.t. any basis.\\\\\nThe degree of $\\chi_V$ is $\\dim_\\C V$.\\\\\nThus $\\chi$ is a function $G \\to \\C$. $\\chi$ is \\emph{linear} (not a universal name) if $\\dim V=1$, in which case $\\chi$ is a homomorphism $G \\to \\C^*$ ($=GL_1(\\C)$).\\\\\n$\\chi$ is irreducible if $\\rho$ is; $\\chi$ is faithful if $\\rho$ is; and, $\\chi$ is trivial, or principal, if $\\rho$ is the trivial representation (2.6). We write $\\chi = 1_G$ in that case.\\\\\n$\\chi$ is a complete invariant in the sense that it determines $\\rho$ up to isomorphism -- see (5.7).\n\\end{defi}\n\n\\begin{thm} (5.2, first properties)\\\\\n(i) $\\chi_V(1) = \\dim_\\C V$; (clear: $\\tr I_n = n$)\\\\\n(ii) $\\chi_V$ is a \\emph{class function}, via it is conjugation-invariant: $$\\chi_V (hgh^{-1}) = \\chi_V(g) \\forall g,h \\in G$$\nThus $\\chi_V$ is constant on conjugacy classes.\\\\\n(iii) $\\chi_V(g^{-1}) = \\overline{\\chi_V(g)}$, the complex conjugate;\\\\\n(iv) For two representations $V,W$, $\\chi_{V \\oplus W} = \\chi_V + \\chi_W$.\n\\begin{proof}\n(ii) $\\chi(hgh^{-1}) = \\tr (R_h R_g R^{-1}_h) = \\tr (R_g) = \\chi(g)$.\\\\\n(iii) Recall $g \\in G$ has finite order, so we can assume $\\rho(g)$ is represented by a diagonal matrix $Diag(\\lambda_1,...,\\lambda_n)$. Then $\\chi(g) = \\sum \\lambda_i$. Now $g^{-1}$ is represented by the matrix $Diag(\\lambda_1^{-1},...\\lambda_n^{-1})$, and hence $\\chi(g^{-1}) = \\sum \\lambda_i^{-1} = \\sum \\bar{\\lambda_i} = \\overline{\\chi(g)}$ (since $\\lambda_i$'s are roots of unity -- since $g^k = 1$ for some $k$!(I mean an exclamation mark here to express surprise) and by homomorphism we know that).\\\\\n(iv) Suppose $V = V_1 \\oplus V_2$, $\\rho_i : G \\to GL(V_i)$, $\\rho:G \\to GL(V)$. Take basis $B = B_1 \\cup B_2$ of $V$ w.r.t $B$, $\\rho(g)$ has matrix of block form $Diag([\\rho_1(g)]_{B_1},[\\rho_2(g)]_{B_2})$ and as $\\chi(g)$ is the trace of the above matrix, it is equal ot $\\tr \\rho_1(g)+ \\tr\\rho_2(g) = \\chi_{\\rho_1} (g) + \\chi_{\\rho_2}(g)$.\n\\end{proof}\n\\end{thm}\n\n\\begin{rem}\nWe see later that $\\chi_1,\\chi_2$ character of $G$ implies that $\\chi_1\\chi_2$ is also a character of $G$: uses tensor products, see (9.6).\n\\end{rem}\n\n\\begin{lemma} (5.3)\\\\\nLet $\\rho:G \\to GL(V)$ be a copmlex representation \\emph{affording} the character $\\chi$ (i.e. $\\chi$ is a character of $\\rho$). Then $|\\chi(g)| \\leq \\chi(1)$, with equality iff $\\rho(g) = \\lambda_I$ for some $\\lambda \\in \\C$, a root of unity. Moreover, $\\chi(g) = \\chi(1)$ iff $g \\in \\ker \\rho$.\n\\begin{proof}\nFix $g$. W.r.t. basis of $V$ of eigenvalues $\\rho(g)$, the matrix of $\\rho(g)$ is $Diag(\\lambda_1,...,\\lambda_n)$. Hence $|\\chi(g)| = |\\sum \\lambda_j| \\leq \\sum |\\lambda_j|= \\sum 1 = \\dim V = \\chi(1)$. Equality holds iff all $\\lambda_j$ are equal (to $\\lambda$, say).\\\\\nIf $\\chi(g) = \\chi(1)$, then $\\rho(g) = \\lambda \\iota$ has $\\chi(g) = \\lambda \\chi(1)$.\n\\end{proof}\n\\end{lemma}\n\n\\begin{lemma} (5.4)\\\\\n(a) If $\\chi$ is a complex irreducible character of $G$, so is $\\bar{\\chi}$;\\\\\n(b) Under the same assumption, so is $\\varepsilon\\chi$ for any linear character $\\varepsilon$ of $G$.\\\n\\begin{proof}\nIf $R:G \\to GL_n (\\C)$ is a complex irreducible representation then so is $\\bar{R}: G \\to GL_n (\\C)$ by $g \\to \\bar{R}(g)$. Similarly for $R': g \\to \\varepsilon(g) R(g)$ for $g \\in G$. Check the details.\n\\end{proof}\n\\end{lemma}\n\n\\begin{defi} (5.5)\\\\\n$\\mathcal{C}(G) = \\{f: G \\to \\C: f(hgh^{-1}) = f(g) \\forall h,g \\in G\\}$, the $\\C$-space of class functions (we call it a space since $f_1+f_2: g \\to f_1(g)+f_2(g)$, $\\lambda f: g \\to \\lambda f(g)$ are still in $\\mathcal{C}(G)$), so this is a vector space.\\\\\nLet $k = k(G)$ be the number of ccls of $G$. List the ccls $\\mathcal{C}_1,...,\\mathcal{C}_k$. Conventionally we choose $g_1 = 1, g_2,...,g_k$, representatives of the ccls (hence $\\mathcal{C}_1 = \\{1\\}$). Note that $\\dim_\\C \\mathcal{C}(G) = k$ (the characteristic functions $\\delta_j$ of each ccl which maps any element in the ccl to 1 and others to 0 form a basis).\\\\\nWe define Hermitian inner product on $\\mathcal{C}(G)$:\n\\begin{equation*}\n\\begin{aligned}\n\\bra f,f' \\ket &= \\frac{1}{|G|} \\sum_{g \\in G} \\overline{f(G)} f'(g)\\\\\n&= \\frac{1}{|G|} \\sum_{j=1}^k |\\mathcal{C}_j| \\overline{f(g_j)} f'(g_j)\\\\\n&= \\sum_{j=1}^k \\frac{1}{|C_G(g_j)} \\overline{f(g_j)} f'(g_j)\n\\end{aligned}\n\\end{equation*}\nusing $|\\mathcal{C}_x| =  |G:C_g(x)|$, where $\\mathcal{C}_x$ is the ccl of $x$, $C_G(x)$ is the centraliser of $x$.\\\\\nFor characters\n\\begin{equation*}\n\\begin{aligned}\n\\bra \\chi,\\chi' \\ket &= \\sum \\frac{1}{|C_G(g_j)|} \\chi(g_j^{-1}) \\chi'(g_j)\n\\end{aligned}\n\\end{equation*}\nis a real symmetric form (in fact, $\\bra \\chi,\\chi'\\ket \\in \\Z$ -- see later).\n\\end{defi}\n\n\\begin{thm} (5.6)\\\\\nThe $\\C$-irreducible characters of $G$ form an orthonormal basis of $\\mathcal{C}(G)$. Moreover,\\\\\n(a) If $\\rho:G \\to GL(V), \\rho': G \\to GL(V')$ are irreducible representations of $G$ affording characters $\\chi,\\chi'$ respecitvely, then\n\\begin{equation*}\n\\begin{aligned}\n\\bra \\chi,\\chi' \\ket = \\left\\{\\begin{array}{ll}\n1 & \\rho,\\rho' \\text{ are isomorphic representations}\\\\\n0 & \\text{ otherwise}\n\\end{array}\n\\right.\n\\end{aligned}\n\\end{equation*}\nwe call this 'row orthogonality'.\\\\\n(b) Each class function of $G$ can be expressed as a linear combination of $G$.\\\\\nThis will be proved later in section 6.\n\\end{thm}\n\n\\begin{coro} (5.7)\\\\\nComplex representations of \\emph{finite} groups are characterised by their characters.\\\\\nWe emphasise on finiteness here: for example, $G=\\Z$, consider $1 \\to I_2$, $1 \\to {{1\\ 1} \\choose {0\\ 1}}$ are non-isomorphic but have same character.\n\\begin{proof}\nLet $\\rho:G \\to GL(V)$ be representation affording $\\chi$ ($G$ finite over $\\C$). (3.3) says \n\\begin{equation*}\n\\begin{aligned}\n\\rho = m_1 \\rho_1 \\oplus ... \\oplus m_k \\rho_k\n\\end{aligned}\n\\end{equation*}\nwhere $\\rho_1,...,\\rho_k$ are irreducible, and $m_j \\geq 0$. Then $m_j = \\bra \\chi,\\chi_j\\ket$ where $\\chi_j$ is afforded by $\\rho_j$: we have $\\chi = m_1\\chi_1 + ... + m_k \\chi_k$, but the $\\rho_i$'s are orthonormal.\n\\end{proof}\n\\end{coro}\n\n\\begin{coro} (5.8, irreduciblility criterion)\\\\\nIf $\\rho$ is $\\C$-representation of $G$ affording $\\chi$, then $\\rho$ irreducible $\\iff$ $\\bra \\chi,\\chi \\ket = 1$.\n\\begin{proof}\nForward is just the statement of orthonormality. Conversely, assume $bra \\chi,\\chi\\ket = 1$. Now take a (complete) decomposition of $\\rho$ and take characters of it we get $\\chi = \\sum m_j \\chi_j$ with $\\chi_j$ irreducible and $m_j \\geq 0$. Then $\\sum m^2_j = 1$. Hence $\\chi = \\chi_j$ for some $j$ (since the $m_j$'s are obviously integers), so is irreducible.\n\\end{proof}\n\\end{coro}\n\n\\begin{coro} (5.9)\\\\\nIf the irreducible $\\C$-representations of $G$ are $\\rho_1,...,\\rho_k$ have dimensions $n_1,...,n_k$, then \n\\begin{equation*}\n\\begin{aligned}\n|G| = \\sum_{i=1}^k n_i^2\n\\end{aligned}\n\\end{equation*}\n\\begin{proof}\nRecall from (3.5), $\\rho_{reg}; G \\to GL(\\C G)$, the regular representation $G$ of dimension $|G|$ (where $\\C G$ is just a $G$-space with basis $\\{e_g: g \\in G\\}$ and any $h \\in G$ permutes the $e_g$: $e_g \\to e_{hg}$).\\\\\nLet $\\pi_{reg}$ be its charcter, the \\emph{regular character} of $G$.\\\\\nClaim 1: $\\pi_{reg}(1) = |G|$, $\\pi_{reg}(h) = 0$ if $h \\neq 1$.\\\\\nThis is clear: take $h \\in G, h \\neq 1$, then we always have $0$ down the diagonal since $h$ permutes things around, so the trace is 0; if $h=1$ then we have an identity matrix so trace is $\\dim \\rho = |G|$.\\\\\nClaim 2: $\\pi_{reg} = \\sum n_j \\chi_j$ with $n_j = \\chi_j(1)$.\\\\\nThis is because\n\\begin{equation*}\n\\begin{aligned}\nn_j &= \\bra \\pi_{reg}, \\chi_j\\ket\\\\\n&= \\frac{1}{|G|} \\sum_{g \\in G} \\overline{\\pi_{reg}(g)} \\chi_j(g)\\\\\n&= \\frac{1}{|G|} \\cdot |G| \\chi_j(1) = \\chi_j(1)\n\\end{aligned}\n\\end{equation*}\n(all the other $\\pi_{reg}(g)$ are zero by claim 1).\\\\\nOur corollary is then obvious by just calculating $|G| = \\pi_{reg}(1)$.\n\\end{proof}\n\\end{coro}\n\n\\begin{coro} (5.10)\\\\\nNumber of irreducible characters of $G$ (up to equivalence) = $k$ (=number of ccls).\n\\end{coro}\n\n\\begin{coro} (5.11)\\\\\nElements $g_1,g_2 \\in G$ are conjugate iff $\\chi(g_1) = \\chi(g_2)$ for all irreducible characters of $G$.\n\\begin{proof}\nForward: characters are class functions;\\\\\nBackward: Let $\\delta$ be the characteristic function of the class of $g_1$. In particular, $\\delta$ is a class function, so can be written as a linear combination of the irreducible characters of $G$. Hence $\\delta(g_2) = \\delta(g_1) = 1$, so $g_2 \\in \\mathcal{C}_G (g_1)$.\n\\end{proof}\n\\end{coro}\n\nIn the end let's introduce a good friend which will be around for the next few lectures:\\\\\nRecall from (5.5), the inner product on $\\mathcal{C}(G)$ and the real symmetric form $\\bra,\\ket$ on characters:\n\\begin{defi}\nThe \\emph{character table} of $G$ is the $k \\times k$ matrix (where $k$ is the number of ccls) $X = [\\chi_i (g_j)]$, the $i^{th}$ character on the $j^{th}$ class, where we let $\\chi_1 =1_G, \\chi_2,...,\\chi_k$ are the irreducible characters of $G$, and $\\mathcal{C}_1 =\\{1\\},...,\\mathcal{C}_k$ are the ccls with $g_j \\in \\mathcal{C}_j$ (as we defined in 5.5).\\\\\nSo the $(i,j)^{th}$ entry of $X$ is just $\\chi_i (g_j)$.\n\\end{defi}\n\n\\begin{eg} (5.13)\\\\\n(a) $C_3 = \\bra x:x^3=1\\ket$. The character table is\n\\begin{equation*}\n\\begin{aligned}\n\\begin{matrix}\n & 1 & x & x^2\\\\\n\\chi_1 & 1 & 1 & 1\\\\\n\\chi_2 & 1 & \\omega & \\omega^2\\\\\n\\chi_3 & 1 & \\omega^2 & \\omega\n\\end{matrix}\n\\end{aligned}\n\\end{equation*}\nwhere $\\omega = e^{2\\pi i/3}$.\\\\\n(b) $G=D_6 \\cong S_3 = \\bra r,s:r^3=s^2=1,sr^{-1} = r^{-1}\\ket$.\\\\\nccls of $G$: $\\mathcal{C}_1 = \\{1\\}$, $\\mathcal{C}_2 = \\{r,r^{-1}$, $\\mathcal{C}_3 =\\{s,sr,sr^2\\}$. We have 3 irreducible representations over $\\C$: $1_G$ (trivial); $\\mathcal{S}$ (sign): $x \\to 1$ for $x$ even, $x \\to -1$ for $x$ odd; and $W$ (2-dimensional): $sr^i$ acts by matrix with eigenvalues $\\pm 1$; $r^k$ acts by the matrix\n\\begin{equation*}\n\\begin{aligned}\n\\begin{matrix}\n\\cos 2k\\pi/3 & -\\sin 2k\\pi/3\\\\\n\\sin 2k\\pi/3 & \\cos 2k\\pi/3\n\\end{matrix}\n\\end{aligned}\n\\end{equation*}\nso $\\chi_w(sr^i) = 0$ $\\forall j$, $\\chi_w (r^k) = 2\\cos 2k\\pi/3 = -1$ $\\forall k$. So the charactable is:\n\\begin{equation*}\n\\begin{aligned}\n\\begin{matrix}\n & \\mathcal{C}_1 & \\mathcal{C}_2 & \\mathcal{C}_3\\\\\n 1_G & 1 & 1 & 1\\\\\n \\chi_s & 1 & -1 & 1\\\\\n \\chi_w & 2 & 0 & -1\n\\end{matrix}\n\\end{aligned}\n\\end{equation*}\n\\end{eg}\n\n\\newpage\n\n\\section{Proofs and orthogonality}\n\nWe want to prove(5.6): irreducible characters form orthonormal basis for the space of $\\C$-class functions.\n\n\\begin{proof} (of 5.6 (a))\\\\\nFix bases of $V$ and $V'$. Write $R(g)$, $R'(g)$ for matrices of $\\rho(g),\\rho'(g)$ w.r.t. these bases, respectively. Then\n\\begin{equation*}\n\\begin{aligned}\n\\bra \\chi',\\chi \\ket &= \\frac{1}{|G|} \\chi'(g^{-1}) \\chi(g) \\\\\n&= \\frac{1}{|G|} \\sum_{g \\in G, i,j\\ s.t. 1 \\leq i \\leq n', 1 \\leq j \\leq n} R'(g^{-1})_{ii} R(g)_{jj}\n\\end{aligned}\n\\end{equation*}\nthe trick is to define something that annhilates almost the whole thing. Let $\\phi:V \\to V'$ be linear and define \n\\begin{equation*}\n\\begin{aligned}\n\\tilde{\\phi}: V &\\to &V'\\\\\nv &\\to &\\frac{1}{|G|} \\sum_{g \\in G} \\rho'(g^{-1}) \\phi \\rho(g) v\n\\end{aligned}\n\\end{equation*}\nWe claim that this is a $G$-homomorphism: if $h \\in G$, let's calculate\n\\begin{equation*}\n\\begin{aligned}\n\\rho'(h^{-1}) \\tilde{\\phi} \\rho(h) (v) &= \\frac{1}{|G|} \\sum_{g \\in G} \\rho' (gh)^{-1} \\phi \\rho(gh) (v)\\\\\n&= \\frac{1}{|G|} \\sum_{g' \\in G} \\rho'(g'^{-1}) \\phi \\rho(g') (v)\\\\\n&= \\tilde{\\phi} (v)\n\\end{aligned}\n\\end{equation*}\n(when $g$ runs through $G$, $gh$ runs through $G$ as well). So (2.8) is satisfied, i.e. $\\phi$ is a $G$-homomorphism.\n\nCase 1: $\\rho,\\rho'$ are not isomorphic. Schur's lemma says $\\tilde{\\phi} = 0$ for any given linear $\\phi:V \\to V'$. Take $\\phi - \\varepsilon_{\\alpha\\beta}$, having matrix $E_{\\alpha\\beta}$ (w.r.t our basis). This is $0$ everywhere except $1$ in the $(\\alpha,\\beta)$-position. Then $\\tilde{\\varepsilon_{\\alpha\\beta}} = 0$. So $\\frac{1}{|G|} \\sum_{g \\in G} (R'(g^{-1}) E_{\\alpha\\beta} R(g))_{ij} = 0$. So $\\frac{1}{|G|} \\sum R'(G^{-1})_{i\\alpha} R(g)_{\\beta j} =0 $ $\\forall i,j$, with $\\alpha = i, \\beta = j$. Now $\\frac{1}{|G|} \\sum_{g \\in G} R'(g^{-1})_{ii} R(g)_{jj} = 0$ sum over $i,j$. Then $\\bra \\chi',\\chi\\ket = 0$.\\\\\nCase 2: $\\rho,\\rho'$ isomorphic. So $\\chi = \\chi'$; take $V=V'$, $\\rho = \\rho'$. If $\\phi:V \\to V$ is linear endomorphism, we claim $\\tr \\phi = \\tr \\tilde{\\phi}$:\n\\begin{equation*}\n\\begin{aligned}\n\\tr \\tilde{\\phi} = \\frac{1}{|G|} \\sum_{g \\in G} \\tr(\\rho(g)^{-1} \\phi \\rho(g)) = \\frac{1}{|G|} \\sum_{g \\in G} \\tr \\phi = \\tr \\phi\n\\end{aligned}\n\\end{equation*}\nBy Schur's lemma, $\\tilde{\\phi} = \\lambda\\iota_V$ for some $\\lambda \\in \\C$ (depending on $\\phi$). Then $\\lambda = \\frac{1}{n} \\tr\\phi$. Let $\\phi = \\varepsilon_{\\alpha\\beta}$. So $\\tr \\phi = \\delta_{\\alpha\\beta}$. Hence $\\tilde{\\varepsilon_{\\alpha\\beta}} = \\frac{1}{n} \\delta_{\\alpha\\beta}\\iota_v = \\frac{1}{|G|} \\sum_{g \\in G} \\rho(g^{-1}) \\varepsilon_{\\alpha\\beta} \\rho(g)$. In terms of matrices, take $(i,j)$-entry: $\\frac{1}{|G|} \\sum_j R(g^{-1})_{i \\alpha} R(g)_{\\beta j} = \\frac{1}{n} \\delta_{\\alpha\\beta}\\delta_{ij}$ $\\forall i,j$. Put $\\alpha = i,\\beta =j $ to get $\\frac{1}{|G|} \\sum_g R(g^{-1})_{ii} R(g)_{jj} = \\frac{1}{n} \\delta_{ij}$. Finally sum over $i,j$ to get $\\bra \\chi,\\chi \\ket = 1$.\n\\end{proof}\n\nBefore proving (b), let's prove column orthogonality:\n\n\\begin{thm} (6.1, column orthogonality relations)\\\\\n\\begin{equation*}\n\\begin{aligned}\n\\sum_{i=1}^k \\overline{\\chi_i(g_j)} \\chi_i (g_l) = \\delta_{jl} |C_G(g_j)|\n\\end{aligned}\n\\end{equation*}\n\\end{thm}\nhaving an easy corollary\n\\begin{coro} (6.2)\\\\\n$|G| =\\sum_{i=1}^k \\chi_i^2(1)$.\n\\end{coro}\n\n\\begin{proof} (of (6.1))\\\\\n$\\delta_{ij} = \\bra \\chi_i,\\chi_j\\ket = \\sum \\overline{\\chi_i (g_l)} \\chi_j (g_l) / |C_G(g_l)|$. Consider the character table $X = (\\chi_i(g_j))$. Then $\\bar{X} D^{-1} X^T = I_{k \\times k}$ where $D = Diag(|C_G(g_1)|,...,|C_G(g_k)|)$.\\\\\nSince $X$ is quare, it follows that $d6{-1} \\bar{X}^T$ is the inverse of $X$, so $\\bar{X}^T X = D$.\n\\end{proof}\n\n\\begin{proof} (of (5.6(b)))\\\\\nThe $\\chi_i$ generate $\\mathcal{C}_G$. Let all the irreducible characters $\\chi_1,...,\\chi_l$ of $G$: claim these generate $\\mathcal{C}_G$, the $\\C$-space of class functions on $G$. It's enough to show that the orthogonal complement to $span\\{\\chi_1,...,\\chi_l\\}$ in $\\mathcal{C}_G$ is $\\{0\\}$. To see this, assume $f \\in \\mathcal{C}_G$ with $\\bra f,\\chi_j\\ket = 0 \\forall j$. Let $\\rho:G \\to GL(V)$ be irreducible representation affording $\\chi \\in \\{\\chi_1,...,\\chi_l\\}$. Then $\\bra f,\\chi\\ket = 0$.\\\\\nConsider\n\\begin{equation*}\n\\begin{aligned}\n\\frac{1}{|G|} \\sum_G \\overline{f(g)} \\rho(g): V \\to V\n\\end{aligned}\n\\end{equation*}\nThis is a $G$-homomorphism, so as $\\rho$ is irreducible, it must be $\\lambda_\\iota$ for some $\\lambda \\in \\C$. Now \n\\begin{equation*}\n\\begin{aligned}\nn\\lambda &= \\tr \\frac{1}{|G|} \\sum_g \\overline{f(g)} \\rho(g)\\\\\n&= \\frac{1}{|G|} \\sum_g \\overline{f(g)} \\chi(g) = 0 = \\bra f,\\chi\\ket\n\\end{aligned}\n\\end{equation*}\nSo $\\lambda = 0$. Hence $\\sum \\overline{f(g)} \\rho(g) = 0$, the zero endomorphism on $V$ for all representations $\\rho$ (complete reducibility).\n\nTake $\\rho = \\rho_{reg}$ where $\\rho_{reg}(g): e_1 \\to e_g$ ($g \\in G$). So\n\\begin{equation*}\n\\begin{aligned}\n\\sum_g \\overline{f(g)} \\rho_{reg}(g): e_1 \\to \\sum_g \\overline{f(g)} e_g\n\\end{aligned}\n\\end{equation*}\nSo it follows $\\sum_g \\overline{f(g)} e_g = 0$. So $\\overline{f(g)} = 0 \\forall g \\in G$, so $f \\equiv 0$.\n\\end{proof}\n\nVariuous corollaries now follow:\\\\\n$\\bullet$ The number of irreducible representations of $G$ = number of ccls; (5.10)\\\\\n$\\bullet$ Column orthogonality (6.1);\\\\\n$\\bullet$ $|G| = \\sum n_i^2$ (6.2);\\\\\n$\\bullet$ $g_1 \\stackrel{\\sim}{G} g_2 \\iff \\chi(g_1) = \\chi(g_2)$ for all irreducible $\\chi$ (5.11);\\\\\n$\\bullet$ If $g \\in G$, $g \\stackrel{\\sim}{G} g^{-1} \\iff \\chi(g) \\in \\R$ for all irreducible $\\chi$.\n\n\\newpage\n\n\\section{Permutation representations}\nPreview was given in (3.7). Recall:\n$\\bullet$ $G$ finite group acting on finite set $X = \\{x_1,...,x_n\\}$;\\\\\n$\\bullet$ $\\C X$ = $\\C$-space, with basis $\\{e_{x_1},...,e_{x_n}\\}$ of dimension $|X|$, so is $\\{\\sum_j a_j e_{x_j}: a_j \\in \\C\\}$;\\\\\n$\\bullet$ corresponding permutation representation $\\rho_X:G \\to GL(\\C X)$ by $g \\to \\rho(g)$, where $\\rho(g)$ sends $e_{x_j} \\to e_{gx_j}$, extending linearly.\\\\\n$\\bullet$ $\\rho_X$ is the \\emph{permutation representation} corresponding to the action of $G$ on $X$.\\\\\n$\\bullet$ matrices representing $\\rho_X(g)$ w.r.t. basis $\\{e_x\\}_{x \\in X}$ are permutation matrices: 0 except for one 1 in each row and column, and $(\\rho(g))_{ij} = 1$ iff $gx_j = x_i$. Consider its character:\n\n(7.1) Permutation character, $\\pi_X$, is\n\\begin{equation*}\n\\begin{aligned}\n\\pi_X(g) = |Fix_X(g)| =|\\{x \\in X:gx = x\\}|.\n\\end{aligned}\n\\end{equation*}\n\n(7.2) $\\rho_X$ always contains $1_G$: $span \\{e_{x_1}+...+e_{x_n}\\}$ is a trivial $G$-subspace of $\\C X$ with $G$-invariant complement $span\\{\\sum a_x e_x: \\sum a_x = 0\\}$.\n\n\\begin{lemma} (7.3, Burnside's lemma, after Cauchy, Frobenius)\n$\\bra \\pi_X, 1\\ket = $ number of orbits of $G$ on $X$.\n\\begin{proof}\nIf $X = X_1 \\cup ... \\cup X_l$ disjoint union of orbits, then $\\pi_X = \\pi_{X_1}+...+\\pi_{X_l}$, with $\\pi_{X_j}$ permutation character of $G$ on $X_j$, so to prove the claim it's enough to show that if $G$ is transitive on $X$ then $\\bra \\pi_X,1\\ket = 1$. Assume $G$ is transitive on $X$. Now\n\\begin{equation*}\n\\begin{aligned}\n\\bra \\pi_X,1\\ket &= \\frac{1}{|G|} \\sum_g \\pi_X(g) = \\frac{1}{|G} |\\{(g,x) \\in G \\times X: gx = x\\}|\\\\\n&= \\frac{1}{|G|} \\sum_{x \\in X} |G_x|=\\frac{1}{|G|}|X||G_x| = \\frac{1}{|G|}|G| = 1\n\\end{aligned}\n\\end{equation*}\n(Note the use of orbit-stabilizer theorem).\n\\end{proof}\n\\end{lemma}\n\n\\begin{lemma} (7.4)\\\\\nLet $G$ act on the sets $X_1,X_2$. Then $G$ acts on $X_1 \\times X_2$ via $g(x_1,x_2) = (gx_1,gx_2)$. The character $\\pi_{X_1 \\times X_2} = \\pi_{X_1} \\pi_{X_2}$ and so $\\bra \\pi_{X_1} ,\\pi_{X_2}\\ket =$ number of orbits of $G$ on $X_1 \\times X_2$.\n\\begin{proof}\nIf $g \\in G$ then $\\pi_{X_1 \\times X_2} (g) = \\pi_{X_1} (g) \\pi_{X_2}(g)$. And we have\n\\begin{equation*}\n\\begin{aligned}\n\\bra \\pi_{X_1},\\pi_{X_2} \\ket = \\bra \\pi_{X_1}\\pi_{X_2},1\\ket = \\bra \\pi_{X_1 \\times X_2} ,1\\ket = (7.3) \\text{ number of orbits of G on } X_1 \\times X_2.\n\\end{aligned}\n\\end{equation*}\n\\end{proof}\n\\end{lemma}\n\n\\begin{defi} (7.5)\\\\\nLet $G$ act on $X$, $|X| > 2$. Then $G$ is \\emph{2-transitive} on $X$ if $G$ has precisely two orbits on $X \\times X: \\{(x,x):x \\in X\\}$ and $\\{x_1,x_2) : x_i \\in X,x_1 \\neq x_2\\}$.\n\\end{defi}\n\n\\begin{lemma} (7.6)\\\\\nLet $G$ act on $X$, $|X|>2$. Then $\\pi_X = 1+\\chi$ with $\\chi$ irreducible $\\iff$ $G$ is 2-transitive on $X$.\n\\begin{proof}\n$\\pi_X = m_1 1 + m_2 \\chi_2 + ... + m_l \\chi_l$ with $1,\\chi_2,...,\\chi_l$ distinct irreducible characters and $m_i \\in \\N$. Then\n\\begin{equation*}\n\\begin{aligned}\n\\bra \\pi_X,\\pi_X\\ket = \\sum_{i=1}^l m_i^2\n\\end{aligned}\n\\end{equation*}\nhence $G$ is 2-transitive on $X$ $\\iff$ $l=2,m_1=m_2=1$.\n\\end{proof}\n\\end{lemma}\n\n\\begin{eg} (7.7)\\\\\nConsider $S_n$ acting on $X=\\{1,...,n\\}$ which is $2$-transitive. Hence $\\pi_X =1+\\chi$ with $\\chi$ irreducible of degree $n-1$. Similarly for $A_n$ ($n>3$).\n\\end{eg}\n\n\\begin{eg} (7.8)\\\\\nConsider $G=S_4$.\\\\\n\\includegraphics[scale=0.6]{image/Rep_04.png}\n\\end{eg}\n\nLast lecture we were talking about using column orthogonality to find $\\chi_5$. Indeed we have \n\\begin{equation*}\n\\begin{aligned}\n\\chi_{reg} = \\chi_1+\\chi_2+3\\chi_3+3\\chi_4+2\\chi_5\n\\end{aligned}\n\\end{equation*}\nSo we can use this to find $\\chi_5$. Also, $S_4 / V_4 \\cong S_3$ by 'lifting' -- see next chapter.\n\n\n\\subsection{Alternating groups}\nSuppose $g \\in A_n$. In 1A we've known that $|\\mathcal{C}_{S_n} (g)| = |S_n:C_{S_n}(g)|$ and $|\\mathcal{C}_{A_n}(g)| = |A_n : C_{A_n}(g)|$.\n\nThese are not necessarily equal. For example, $\\sigma=(123) \\in A_3$, $\\mathcal{A}_3 (\\sigma) =\\{\\sigma\\}$, but $\\mathcal{S_3}(\\sigma) = \\{\\sigma,\\sigma^{-1}\\}$.\n\n\\begin{lemma} (7.9)\\\\\nLet $g \\in A_n$. Then if $g$ commutes with some odd permutation in $S_n$ then $\\mathcal{C}_{S_n} (g) = \\mathcal{C}_{A_n}(g)$; otherwise $\\mathcal{C}_{S_n}(g)$ splits into two ccls in $A_n$ of equal size.\n\\end{lemma}\n\nFor example, consider $G=A_4$, so $|G| = 12$.\n\n\\includegraphics[scale=0.6]{image/Rep_05.png}\n\nNote that if we ignore the second row and first column, the table becomes identical to that of $C_3 \\cong G/V_4$. This is not a coincident, and is actually called \\emph{lifting}.\n\n\\newpage\n\n\\section{Normal subgroups and lifting characters}\n\\begin{lemma} (8.1)\\\\\nLet $N \\triangleleft G$. Let $\\tilde{\\rho} : G/N \\to GL(V)$ be a representation of $G/N$. Then\n\\begin{equation*}\n\\begin{aligned}\n\\rho:G &\\xrightarrow{canonical} G/N &\\xrightarrow{\\tilde{\\rho}} GL(V)\\\\\ng & \\to & \\tilde{\\rho}(gN)\n\\end{aligned}\n\\end{equation*}\nis a representation of $G$, where $\\rho(g) := \\tilde{\\rho}(gN)$. Moreover, $\\rho$ is irreducible iff $\\tilde{\\rho}$ is irreducible.\n\nThe corresponding characters satisfy $\\chi(g) =\\tilde{\\chi} (gN)$. We say that $\\tilde{\\chi}$ \\emph{lifts} to $\\chi$. The lifting $\\tilde{\\chi} \\to \\chi$ is a bijection between irreducible representations of $G/N$ and irreducible representations of $G$ with $N$ in $\\ker$.\n\nWell this looks like Q4/Q12 in the first example sheet.\n\n\\begin{proof}\nNote $\\chi(g) = \\tr(\\rho(g)) = \\tr(\\tilde{\\rho}(gN)) = \\tilde{\\chi}(gN) \\forall g$, and $\\chi(1) = \\tilde{\\chi}(N)$. SO have some degree (?).\n\nBijection: if $\\tilde{\\chi}$ is a charcter of $G/N$-representation and $\\chi$ is its lift to $G$, then $\\chi(N) = \\chi(1)$. Also, if $k \\in N$ then \n\\begin{equation*}\n\\begin{aligned}\n\\chi(k) = \\tilde{\\chi} (kN) = \\tilde{\\chi}(N) = \\chi(1)\n\\end{aligned}\n\\end{equation*}\nSo $N \\leq \\ker\\chi$.\n\nNow let $\\chi$ be character of $G$ with $N \\leq \\ker\\chi$. Suppose $\\rho:G \\to GL(V)$ affords $\\chi$. Define\n\\begin{equation*}\n\\begin{aligned}\n\\tilde{\\rho}: & G/N &\\to GL(V)\\\\\n&gN &\\to \\rho(g)\n\\end{aligned}\n\\end{equation*}\nCheck this is well-defined (uses $N \\leq \\ker\\chi$) and $\\tilde{\\rho}$ is homomorphism, hence gives representation of $G/N$. If $\\tilde{\\chi}$ is the character of $\\tilde{\\rho}$ then $\\tilde{\\chi}(gN) = \\chi(g)$ $\\forall g\\in G$. So $\\tilde{\\chi}$ lifts to $\\chi$.\\\\\nCheck irreducibility.\n\\end{proof}\n\\end{lemma}\n\n\\begin{lemma} (8.2)\\\\\nThe derived subgroup, $G' = \\bra[a,b],a,b \\in G \\ket$ of $G$ is the unique minimal normal subgroup of $G$ s.t. $G/G'$ is abelian, i.e. $G/N$ is abelian $\\implies G' \\leq N$ and $G^{ab}=G/G'$ is abelian, where $G^{ab}$ is the \\emph{abelianisation} of $G$.\\\\\n$G$ has precisely $l=|G/G'|$ representations of $\\dim 1$, all with kernel containing $G'$ and obtained by lifting from $G/G'$. In particular, $l | |G|$.\n\\begin{proof}\n$G'\\triangleleft G$ is an easy exercise.\n\nLet $N \\triangleleft G$. Let $h,g \\in G$, so \n\\begin{equation*}\n\\begin{aligned}\n&g^{-1}h^{-1}gh \\in N \\iff &(gh)N = (hg)N\\\\\n&[g,h] \\iff (gN)(hN) = (hN)(gN)\n\\end{aligned}\n\\end{equation*}\nSo $G' \\leq N \\iff G/N$ is abelian. Since $G' \\triangleleft G$ we deduce $G/G'$ is abelian.\n\nBy (4.5), $G/G'$ has exactly $l$ irreducible characters $\\tilde{\\chi}_1,...,\\tilde{\\chi}_l$ all of degree 1. The lifts of these to $G$ also have degree 1 and by (8.1) these are precisely the irreducible characters $\\chi_i$ of $G$ s.t. $G' \\leq \\ker \\chi_i$. But any linear character of $G$ is a homomorphism $\\chi:G \\to \\C^*$, hence $G' \\leq \\ker \\chi$ ($\\chi(ghg^{-1}h^{-1}) = \\chi(g)\\chi(h)\\chi(g^{-1} \\chi(h)^{-1} = 1$), so the $\\chi_1,...,\\chi_l$ are all the linear characters of $G$.\n\\end{proof}\n\\end{lemma}\n\nExamples:\\\\\n(a) If $G=S_n$, show $s'_n = A_n$. Thus since $G/G' \\cong C_2$, $S_n$ must have exactly two linear characters.\\\\\n(b) Consider $G=A_4$. We've seen previously that this can be lifted from $C_3$ using (8.1),(8.2).\n\n\\begin{lemma} (8.4)\\\\\n$G$ is not simple iff $\\chi(g) = \\chi(1)$ for some irreducible character $\\chi \\neq 1_G$ and some $1 \\neq g \\in G$.\\\\\nAny normal subgroup of $G$ is the intersection of the kernels of some of the irreducible characters of $G$:\n\\begin{equation*}\n\\begin{aligned}\nN =\\bigcap_i \\ker \\chi_i\n\\end{aligned}\n\\end{equation*}\n\\begin{proof}\nIf $\\chi(g) = \\chi(1)$ for some non-trivial irreducible character $\\chi$ (afforded by $\\rho$, say). Then $g \\in \\ker\\rho$ (5.3), so if $g \\neq 1$, then $1 \\neq \\ker \\rho \\stackrel{\\triangleleft}{\\neq} G$.\\\\\nIf $1 \\neq N \\stackrel{\\triangleleft}{\\neq} G$, take irreducible $\\tilde{\\chi}$ of $G/N$, $\\tilde{\\chi}$ non-trivial. Lift to get an irreducible $\\chi$, afforded by $\\rho$ of $G$, then $N \\leq \\ker \\rho \\triangleleft G$. So $\\chi(g) \\ chi(1)$ for $g \\in N$.\\\\\nWe claim that, if $1 \\neq N \\triangleleft G$, then $N$ is the intersection of the kernels of the lifts of all the irreducibles of $G/N$.\\\\\n$\\leq$ is clear from (8.1). If $g \\in G \\setminus N$, then $gN \\neq N$. so $\\tilde{\\chi} (gN) \\neq \\tilde{\\chi}(N)$ for some irreducible $\\tilde{\\chi}$ of $G/N$. Lifting $\\tilde{\\chi}$ to $\\chi$, we have $\\chi(g) \\neq \\chi(1)$.\n\\end{proof}\n\\end{lemma}\nRecall $\\ker \\chi = \\{g \\in G: \\chi(g) = \\chi(1)\\}$. (5.3) : $g \\in \\ker\\chi \\iff g \\in \\ker\\rho$.\n\n\\newpage\n\\section{Dual spaces and tensor products of representations}\n\nRecall (5.5):\\\\\n$\\bullet$ $\\mathcal{C}(G)$ is $\\C$-space of class functions on $G$;\\\\\n$\\bullet$ endowed with irreducible product, $\\dim \\mathcal{C}(G) = k$, orthonormal basis of irreducible characters of $G$ (5.6)l\\\\\n$\\bullet$ there exists an involution (ring homomorphism of order 2): $f \\to f^*$ where $f^*(g) = f(g^{-1})$.\n\n\\begin{lemma} (9.1)\\\\\nLet $\\rho:G \\to GL(V)$, representation over $F$, and let $V^* = Hom_F (V,F)$, dual space of $V$. Then $V^*$ is a $G$-space under \n\\begin{equation*}\n\\begin{aligned}\n(\\rho^*(g)\\phi)(v) = \\phi(\\rho(g^{-1})v)\n\\end{aligned}\n\\end{equation*}\ncalled the \\emph{dual representation} to $\\rho$. Its charcater is $\\chi_{\\rho^*}(g) = \\chi_\\rho (g^{-1})$.\n\\begin{proof}\n\\begin{equation*}\n\\begin{aligned}\n\\rho^*(g_1) (\\rho^*(g_2)\\phi)(v) &= (\\rho^*(g_2)\\phi)(\\rho(g_1^{-1})(v))\\\\\n&= \\phi(\\rho(g_2^{-1}) \\rho(g_1^{-1}) v)\\\\\n&= \\phi(\\rho(g_1g_2)^{-1}(v))\\\\\n&= (\\rho^*(g_1g_2)\\phi)(v)\n\\end{aligned}\n\\end{equation*}\nSo this is a representation. For its character, fix $g \\in G$ and let $e_1,...,e_n$ be basis of $V$ of eigenvectors of $\\rho(g)$, say $\\rho(g) e_j = \\lambda_j e_j$. Let $\\varepsilon_1,...,\\varepsilon_n$ be dual basis. We claim that $\\rho^*(g) \\varepsilon_j =\\lambda^{-1}_j \\varepsilon_j$:\n\\begin{equation*}\n\\begin{aligned}\n(\\rho^*(g)\\varepsilon_j)(e_i) = \\varepsilon_j(\\rho(g^{-1})e_i) = \\varepsilon_j\\lambda_i^{-1}e_i = \\lambda_j^{-1} \\varepsilon_j e_i \\forall i\n\\end{aligned}\n\\end{equation*}\nSo $\\chi_{\\rho^*}(g) = \\sum \\lambda_j^{-1}  = \\chi_\\rho(g^{-1})$.\n\\end{proof}\n\\end{lemma}\n\n\\begin{defi} (9.2)\\\\\n$\\rho:G \\to GL(V)$ is \\emph{self-dual} if $V \\cong V^*$ (as $G$-spaces). Over $\\C$, this holds iff $\\chi_\\rho(g) = \\chi_\\rho(g^{-1})$ ($=\\overline{\\chi_\\rho(g)}$) $\\forall g$, iff $\\chi_\\rho(g) \\in \\R$ for all $g$.\n\\end{defi}\n\nExercise: all irreducible representations of $S_n$ are self-dual (the ccls are determined by cycle type, so $g,g^{-1}$ are always $S_n$-conjugate. Not always true for $A_n$.\n\n\\subsection{tensor products}\nLet $V,W$ be $F-$spaces, $\\dim V = m$, $\\dim W = n$. Fix bases $v_1,...,v_m$ and $w_1,...,w_n$ of $V,W$ respectively. The \\emph{tensor product space} $V \\otimes_F W$ is an $nm$-dimensional $F$-space with basis $\\{v_i \\otimes w_j: 1 \\leq i \\leq m, 1 \\leq j \\leq n\\}$. Thus\\\\\n(a) $V \\otimes W = \\{\\sum_{i,j} \\lambda_{ij} v_i \\otimes w_j: \\lambda_{ij} \\in F\\}$ with 'obvious' addition and scalar multiplication;\\\\\n(b) If $v = \\sum_{i} \\alpha_iv_i \\in V$, $w = \\sum_j \\beta_j w_j \\in W$, define $v\\otimes w:=\\sum_{i,j} \\alpha_i\\beta_j (v_i\\otimes w_j)$.\n\n\\begin{rem}\nNot all elements of $V \\otimes W$ are of this form: some are combinations, e.g. $v_1 \\otimes w_1 + v_2 \\times w-2$, which can't be further simplified. (like entangled)\n\\end{rem}\n\n\\begin{lemma} (9.3)\\\\\n(i) For $v \\in V$, $w \\in W$, $\\lambda \\in F$, $(\\lambda v) \\otimes w = \\lambda (v\\otimes w) = v \\otimes (\\lambda w)$;\\\\\n(i) If $x_1,x_2,x \\in V$, $y_1,y_2,y \\in W$, then \n\\begin{equation*}\n\\begin{aligned}\n(x_1+x_2) \\otimes y = (x_1 \\otimes y) + (x_2 \\otimes y),\\\\\nx \\otimes (y_1+y_2) = (x \\otimes y_1) + (x \\otimes y_2)\n\\end{aligned}\n\\end{equation*}\n\\begin{proof}\n(i) $v = \\sum \\alpha_i v_i$, $w = \\sum \\beta_j w_j$. Then just multiply out everything we get the desired equality. (ii) is similar.\n\\end{proof}\n\\end{lemma}\n\n\\begin{lemma} (9.4)\\\\\nIf $\\{e_1,...,e_m\\}$ is a basis of $V$, $\\{f_1,...,f_n\\}$ is a basis of $W$, then $\\{e_i \\otimes f_j: 1 \\leq i \\leq m,1 \\leq j \\leq n\\}$ is a basis of $V \\otimes W$.\n\\begin{proof}\nWriting $v_k = \\sum_i \\alpha_{ik} e_i$, $w_l = \\sum_j \\beta_{jl} f_j$, we have\n\\begin{equation*}\n\\begin{aligned}\nv_k \\otimes w_l = \\sum \\alpha_{ik} \\beta_{jl} e_i \\otimes f_j\n\\end{aligned}\n\\end{equation*}\nHence $\\{e_i \\otimes f_j\\}$ spans $V \\otimes W$ and, since we have $nm$ of them, they form a basis.\n\\end{proof}\n\\end{lemma}\n\n\\begin{rem}\nOne can define $V \\otimes W$ in a basis-independent way in the first place, see Teleman chapter 6.\n\\end{rem}\n\n\\begin{prop} (9.5)\\\\\nLet $\\rho: G \\to GL(V)$, $\\rho': G \\to GL(V')$ be representations of $G$. Define $\\rho \\otimes \\rho': G \\to GL(V \\otimes V')$ by\n\\begin{equation*}\n\\begin{aligned}\n(\\rho \\otimes \\rho') (g) : \\sum \\lambda_{ij} v_i \\otimes w_j \\to \\sum \\lambda_{ij} \\rho(g) v_i \\otimes \\rho'(g) w_j\n\\end{aligned}\n\\end{equation*}\nThen $\\rho \\otimes \\rho'$ is a representation of $G$ with character\n\\begin{equation*}\n\\begin{aligned}\n\\chi_{\\rho \\otimes \\rho'} (g) = \\chi_\\rho(g) \\chi_{\\rho'} (g) \\forall g \\in G\n\\end{aligned}\n\\end{equation*}\nHence product of two characters of $G$ is still a character of $G$.\n\\begin{proof}\nOn Tuesday.\n\\end{proof}\n\\end{prop}\n\n(After lecture 11: this is the first notes to get beyond 1000 lines!)\n\n\\begin{rem} (9.6)\\\\\nSheet 1, Q2 says $\\rho$ irreducible, $\\rho'$ of degree 1, then $\\rho \\otimes \\rho'$ irreducible; if $\\rho'$ is not of $\\deg$ 1 this is usually false.\n\\end{rem}\n\n\\begin{proof} (of 9.5)\\\\\nIt's clear that $(\\rho \\otimes \\rho') (g) \\in GL(V \\otimes V')$ $\\forall g \\in G$ and so $\\rho \\otimes \\rho'$ is a homomorphism $G \\to GL(V \\otimes V')$. Let $g \\in G$. Let $V_1,...,v_m$ be basis of $V$ of eigenvectors of $\\rho(g)$; let $w_1,...,w_n$ be a basis of $V'$. Say: \n\\begin{equation*}\n\\begin{aligned}\n\\rho(g) v_j = \\lambda_j v_j, \\rho'(g) w_j = \\mu_j w_j\n\\end{aligned}\n\\end{equation*}\nThen \n\\begin{equation*}\n\\begin{aligned}\n(\\rho \\otimes \\rho') (g) (v_i \\otimes w_j) &= \\rho(g) v_i \\otimes \\rho'(g) w_j\\\\\n&= \\lambda_i v_i \\otimes \\mu_j w_j\\\\\n&= (\\lambda_i \\mu_j) (v_i \\otimes w_j)\n\\end{aligned}\n\\end{equation*}\nSo $\\chi_{\\rho \\otimes \\rho'}(g) = \\sum_{i,j} \\lambda_i \\mu_j = (\\sum \\lambda_i)(\\sum\\lambda_j) = \\chi_\\rho(g)\\chi_{\\rho'}(g)$\n\\end{proof}\n\nNow work over $\\C$. Take $V=V'$ and define $V^{\\otimes 2} = V \\otimes V$.\\\\\nLet\n\\begin{equation*}\n\\begin{aligned}\n\\tau: \\sum \\lambda_{ij} v_i \\otimes v_j \\to \\sum \\lambda_{ij} \\lambda_j \\otimes v_i\n\\end{aligned}\n\\end{equation*}\nwhich is a linear $G$-endomorphism of $V^{\\otimes 2}$, s.t. $\\tau^2 =1$ (so eigenvalues $\\pm 1$).\n\n\\begin{defi} (9.7)\\\\\n\\begin{equation*}\n\\begin{aligned}\nS^2 V = \\{v \\in V^{\\otimes 2}: \\tau(x) = x\\},\\\\\n\\wedge^2 V = \\{x \\in V^{\\otimes 2}: \\tau(x) = -x\\}\n\\end{aligned}\n\\end{equation*}\nknown as the \\emph{symmetric square} of $V$ and \\emph{exterior square} of $V$ respectively.\n\\end{defi}\n\n\\begin{lemma} (9.8)\\\\\n$S^2 V$ and $\\wedge^2 V$ are $G$-subspaces of $V^{\\otimes 2}$ and $V^{\\otimes 2} \\cong S^2 V \\otimes \\wedge^2 V$. $S^2 V$ has basis $\\{v_iv_j := v_i \\otimes v_j + v_j \\otimes v_i: 1 \\leq i \\leq j \\leq n\\}$, and $\\wedge^2 V$ has basis $\\{v_i \\wedge v_j:=v_i \\otimes v_j - v_j \\otimes v_i: 1 \\leq i < j \\leq n\\}$. Hence we have $\\dim S^2 V = \\frac{1}{2}n(n+1)$ and $\\dim \\wedge^2 V = \\frac{1}{2} n(n-1)$.\n\\begin{proof}\nExercise in linear algebra.\\\\\nTo show $V^{\\otimes 2}$ is reducible, write $x \\in V^{\\otimes 2}$ as $x=\\frac{1}{2} (x+\\tau(x)) + \\frac{1}{2} (x-\\tau(x))$, which is in $S^2 V$ and $\\wedge^2 V$ respectively.\n\\end{proof}\n\\end{lemma}\n\nIn fact, $V^{\\otimes 2}$, $V^{\\otimes 3} = V \\otimes V \\otimes V$, ...,etc. are never irreducible if $\\dim V > 1$.\n\n\\begin{lemma} (9.9)\\\\\nIf $\\rho:G \\to GL(V)$ is a representation affording character $\\chi$, then $\\chi^2 = \\chi_S + \\chi_\\wedge$ where $\\chi_s$ ($=S^2 \\chi$) is the character of $G$ in the subrepresentation $S^2 V$, and $\\chi_\\wedge$ ($=\\wedge^2 \\chi)$ is the character of $G$ in the subrepresentation $\\wedge^2 V$. Moreover, for $g \\in G$,\n\\begin{equation*}\n\\begin{aligned}\n\\chi_s(g) = \\frac{1}{2} (chi^2(g) + \\chi(g^2)),\n\\chi_\\wedge(g) = \\frac{1}{2} (\\chi^2(g) - \\chi(g^2)).\n\\end{aligned}\n\\end{equation*}\n\\begin{proof}\nLet's compute the characters $\\chi_s,\\chi_\\wedge$. Fix $g \\in G$. Let $v_1,...,v_n$ be a basis of eigenvectors of $\\rho(g)$, say $\\rho(g)v_i = \\lambda_i v_i$ (we drop the $\\rho$ to write $g v_i = \\lambda_i v_i$ for simplicity below). Then\n\\begin{equation*}\n\\begin{aligned}\ng v_i v_j = \\lambda_i \\lambda_j v_i v_j\\\\\ng v_i \\wedge v_j = \\lambda_i \\lambda_j v_i \\wedge v_j\n\\end{aligned}\n\\end{equation*}\nHence $\\chi_s(g) = \\sum_{1 \\leq i \\leq j \\leq n} \\lambda_i\\lambda_j$ and $\\chi_\\wedge(g) = \\sum_{1 \\leq i < j \\leq n} \\lambda_i \\lambda_j$. Now,\n\\begin{equation*}\n\\begin{aligned}\n(\\chi(g))^2 &= (\\sum \\lambda_i)^2\\\\\n&= \\sum \\lambda_i^2 + 2\\sum_{i < j} \\lambda_i \\lambda_j\\\\\n&= \\chi(g^2) + 2\\sum_{i < j} \\lambda_i \\lambda_j\\\\\n&= \\chi(g^2) + 2 \\chi_\\wedge (g)\n\\end{aligned}\n\\end{equation*}\nSo $\\chi_\\wedge (g) = \\frac{1}{2} (\\chi^2 (g) - \\chi(g^2))$. But $\\chi^2 = \\chi_s + \\chi_\\wedge$ so we get the expression for $\\chi_s(g)$.\n\\end{proof}\n\\end{lemma}\n\n\\begin{eg} (9.10)\\\\\nConsider our usual example $G=S_4$ (see 7.8).\n\n\\includegraphics[scale=0.5]{image/Rep_06.png}\n\n\\includegraphics[scale=0.5]{image/Rep_07.png}\n\nNotice that $\\wedge^2 \\chi_3 = \\bar{\\chi}_3$ (irreducible since $\\bra \\chi_\\wedge,\\chi_\\wedge\\ket = 1$),\\\\\n$S^2 \\chi_3 = 1+\\chi_3+\\chi5$: The inner product is 3 and it contains $1$ ,$\\chi_3$, so the one left is $\\chi_5$.\n\\end{eg}\n\nCharacters of $G \\times H$ (seen in (4.5) for abelian groups):\\\\\n\\begin{prop} (9.11)\\\\\nIf $G,H$ are finite groups with irreducible characters $\\chi_1,...,\\chi_k$ and $\\psi_1,...,\\psi_r$ respectively, then the irreducible characters of the direct product $G \\times H$ are precisely $\\{\\chi_i \\psi_j:1 \\leq i \\leq k, 1 \\leq j \\leq r\\}$, where $\\chi_i \\psi_j (g,h) = \\chi_i*g( \\psi_j(h)$.\n\\begin{proof}\nIf $\\rho:G \\to GL(V)$, $\\rho':H \\to GL(W)$ affording $\\chi$ and $\\psi$ respectively, then\n\\begin{equation*}\n\\begin{aligned}\n\\rho \\otimes \\rho': &G \\times H \\to &GL(V \\otimes W)\\\\\n&(g,h) \\to &\\rho(g) \\otimes \\rho'(h)\n& &v_i \\otimes w_j \\to \\rho(g) v_i \\otimes \\rho'(h) w_j\n\\end{aligned}\n\\end{equation*}\nis a representation of $G \\times H$ on $V \\otimes W$ by (9.5), and $\\chi_{\\rho \\otimes \\rho'} = \\chi\\psi$, again by (9.5).\\\\\nWe claim that $\\chi_i \\psi_j$ are distinct and irreducible:\n\\begin{equation*}\n\\begin{aligned}\n\\bra \\chi_i \\psi_j,\\chi_r\\psi_s \\ket_{G \\times H} &= \\frac{1}{|G \\times H|} \\sum_{(g,h)} \\overline{\\chi_i\\psi_j (g,h)} \\chi_r \\psi_s (g,h)\\\\\n&= (\\frac{1}{|G|} \\overline{\\chi_i(g)} \\chi_r(g)) (\\frac{1}{|H|} \\sum_h \\overline{\\psi_j(h)} \\psi_s(h))\\\\\n&= \\delta_{ir} \\delta_{js}\n\\end{aligned}\n\\end{equation*}\n...tbc.\\\\\nLet's complete on $\\chi_i\\psi_j$ being distinct and irreducible:\\\\\nComplete set: $\\sum_{i,j} (\\chi_i\\psi_j)(1)^2 = \\sum_i \\chi_i(1)^2 \\sum_j \\psi_j(1)^2 = |G| |H| = |G \\times H|$\n\\end{proof}\n\\end{prop}\n\n\\subsection{Symmetric and extreior powers}\nLet $V$ be a vector space, $\\dim_F V = d$, with basis $\\{v_1,...,v_d\\}$. Let $V^{\\otimes n} = V \\otimes ... \\otimes V$, with basis $\\{v_{i_1} \\otimes ... \\otimes v_{i_n} : (i_1,...,i_n) \\in \\{1,...,d\\}^n\\}$, so $\\dim V^{\\otimes n} = d^n$.\n\n$S_n$-action: for any $\\sigma \\in S_n$, we can define linear map\n\\begin{equation*}\n\\begin{aligned}\n\\sigma: &V^{\\otimes n} \\to &V^{\\otimes n}\\\\\nv_1 \\otimes ... \\otimes v_n \\to &v_{\\sigma^{-1}(1)} \\otimes ... \\otimes v_{\\sigma^{-1}(n)}\n\\end{aligned}\n\\end{equation*}\nfor $v_1,...,v_n \\in V$, permuting posutums of vectors in a tensor.\n\nFor example, $(12)(v_1\\otimes v_2 \\otimes v_3) = v_2 \\otimes v_1 \\otimes v_3$, $(13)(v_2 \\otimes v_1 \\otimes v_3) = v_3 \\otimes v_1 \\otimes v_2$.\n\nCheck that this defines a representation of $S_n$ on $V^{\\otimes n}$ (extended linearly).\n\n$G$-action: given representation $\\rho:G \\to GL(V)$, then the action of $G$ on $V^{\\otimes n}$ is\n\\begin{equation*}\n\\begin{aligned}\n\\rho^{\\otimes n} (g) : v_1 \\otimes ... \\otimes v_n = \\rho(g) v_1 \\otimes ... \\otimes \\rho(g) v_n\n\\end{aligned}\n\\end{equation*}\nextended linearly, and this commutes with the $S_n$-action. We can decompose $V^{\\otimes n}$ as $S_n$-module, and each isotypical component (4.?) is $G$-invariant subspace of $V^{\\otimes n}$. In particular:\n\n\\begin{defi} (9.12)\\\\\nFor $G$-space $V$, define\\\\\n(i) the $n$th symmetric power of $V$, $S^n V = \\{x \\in V^{\\otimes n}: \\sigma(x) = x \\forall \\sigma \\in S_n\\}$;\\\\\n(ii) the $n$th exterior power of $V$, $\\wedge^n V = \\{x \\in V^{\\otimes n}: \\sigma(x) = sign(\\sigma)x \\forall \\sigma \\in S_n\\}$.\\\\\nBoth are $G$-subspaces of $V^{\\otimes n}$, but for $n>2$, $S^n V \\oplus \\wedge^n V \\lneq V^{\\otimes n}$, so in general there are lots of others for the $S_n$-action.\n\\end{defi}\n\n(9.13) See Sheet 3 Q7 for bases of $S^n V$, $\\wedge^n V$ and their characters.\n\n\\subsection{Tensor algebra}\nTake $char F = 0$.\n\n\\begin{defi} (9.14)\\\\\nLet $T^n V = V^{\\otimes n}$. The tensor algebra of $V$ is $TV := \\oplus_{n \\geq 0} T^n V$, $T^0 V = F$.\\\\\nThis is $F$-space and is a (non-commutative) graded ring with product $x \\in T^n V$, $y \\in T^m V$ , $x \\cdot y = x \\otimes y \\in T^{n+m} V$.\\\\\nThere are two graded quotient rings\n\\begin{equation*}\n\\begin{aligned}\nSV = TV /(\\text{ideal generated by all } U \\otimes V - V \\otimes U)\\\\\n\\wedge V = TV / \\text{ ideal generated by all }V \\otimes V\n\\end{aligned}\n\\end{equation*}\ncalled the symmetric algebra and exterior algebra respectively.\n\\end{defi}\n\n\\begin{defi} (9.15)\\\\\nThe $2$-submodule of $\\mathcal{C}(G)$ spanned by irreducible characters of $G$ is the character ring of $G$, $R(G)$. Elements of $R(G)$ are called generalised/virtual characters if $\\psi = \\sum n_\\chi \\chi$, $n_\\chi \\in \\Z$ correspondingly.\\\\\n$\\bullet$ $R(G)$ is a commutative ring and any generalised character is a difference of two characters, $\\psi = \\alpha - \\beta$:\\\\\n$\\alpha = \\sum_{n_\\chi \\geq 0} n_\\chi \\chi, \\beta = -\\sum_{n_\\chi < 0} n_\\chi \\chi$.\\\\\nThe $\\{\\chi_i\\}$ form a $\\Z$-basis for $R(G)$ as a free $\\Z$-module.\\\\\n$\\bullet$ Suppose $\\psi$ is virtual character and $\\bra\\psi,\\psi\\ket = 1$ and $\\psi(1) > 0$. Then $\\psi$ is actually the character of an irreducible representation of $G$.\\\\\nList irreducible characters of $G$: $\\chi_1,...,\\chi_k$, $\\psi = \\sum n_i \\chi_i$; orthonormality says $\\bra\\psi,\\psi\\ket = \\sum n_i^2$, so $\\sum n_i^2 = 1$, meaning $n_i = \\pm 1$ for exactly one $i$ and $n_j = 0$ for $j \\neq i$. Since $\\psi(1)>0$, we must have $n_i = +1$.\\\\\n$\\bullet$ Henceforth we don't distinguish between a character and its negative and we often study generalised characters of norm 1 rather than irreducible characters.\n\\end{defi}\n\n\\newpage\n\\section{Restriction and induction}\nThroughout we set $H \\leq G$, $F = \\C$.\n\n\\begin{defi} (10.1, restriction)\\\\\nLet $\\rho:G \\to GL(V)$ be representation affording $\\chi$. We can think of $V$ as a $H$-space by restricting attention to $h \\in H$. We then get\n\\begin{equation*}\n\\begin{aligned}\nRes_H^G \\rho : &H \\to &GL(V)\n\\end{aligned}\n\\end{equation*}\nThis is sometimes written as $\\rho_H$ or $\\rho\\downarrow_H$, the restriction of $\\rho$ to $H$. It affords the character $Res_H^G \\chi = \\chi_H = \\chi \\downarrow_H$.\n\\end{defi}\n\n\\begin{lemma} (10.2)\\\\\nIf $\\psi$ is any non-zero character of $H \\leq G$, then there exists irreducible charcater $\\chi$ of $G$ s.t. $\\bra Res_H^G \\chi, \\psi \\ket_H \\neq 0$. We say $\\psi$ is a constituent of $Res_H^G \\chi$.\n\\begin{proof}\n\\begin{equation*}\n\\begin{aligned}\n0 \\neq \\frac{|G|}{|H|} \\psi(1) = \\bra \\pi_{reg} \\downarrow_H ,\\psi\\ket = \\sum_1^k \\deg \\chi_i \\bra \\chi_i \\downarrow_H ,\\psi\\ket\n\\end{aligned}\n\\end{equation*}\nwhere $\\psi_i$ are irreducible characters of $G$.\n\\end{proof}\n\\end{lemma}\n\n\\begin{lemma} (10.3)\\\\\nLet $\\chi$ be irreducible character of $G$, and let $Res_H^G \\chi = \\sum c_I \\chi_i$ with $\\chi_i$ irreducible characters of $H$, $c_i \\in \\Z_{\\geq 0}$. Then\n\\begin{equation*}\n\\begin{aligned}\n\\sum c_I^2 \\leq |G:H|\n\\end{aligned}\n\\end{equation*}\nwith equality iff $\\chi(g) = 0$ $\\forall g \\in G \\setminus H$.\n\\begin{proof}\n\\begin{equation*}\n\\begin{aligned}\n\\sum c_i^2 = \\bra Res_H^G \\chi,Res_H^G \\chi \\ket_H = \\frac{1}{|H|} \\sum_{h \\in H} |\\chi(h)|^2\n\\end{aligned}\n\\end{equation*}\nBut \n\\begin{equation*}\n\\begin{aligned}\n1 = \\bra \\chi,\\chi\\ket G &= \\frac{1}{|G|} \\sum_{g \\in G} |\\chi(g)|^2\\\\\n&= \\frac{1}{|G|} (\\sum_{h \\in H} |\\chi(h)|^2 + \\sum_{g \\in G \\setminus H} |\\chi(g)|^2)\\\\\n&= \\frac{|H|}{|G|} \\sum c_i^2 + \\underbrace{\\frac{1}{|G|} \\sum_{g \\in G \\setminus H} |\\chi(g)|^2}_{\\geq 0}\n\\end{aligned}\n\\end{equation*}\nSo $\\sum c_i^2 \\leq |G:H|$, with equality holds iff $\\chi(g) = 0$. $\\forall g \\in G\\setminus H$.\n\\end{proof}\n\\end{lemma}\n\n\\begin{eg}\nLet $G=S_5$, $H=A_5$. This has 7 representations of degree $1,1,4,4,5,5,6$ respectively, where if we restrict to $H$, the two representations of degree $1,4,5$ combines into one of the same degree respectively; however, the degree $6$ representation splits into two irreducible representations of degree 3. In the first case we have $\\chi(g) \\neq 0$ somewhere outside $H$; for the degree $6$ representation, $\\chi(g) = 0$ $\\forall g \\in S_5 \\setminus A_5$. All restrictions are irreducible if $|G:H|=2$ which is the case here. Fact: $\\chi \\downarrow_H$ all constituents have same degree if $H \\triangleleft G$ (Janes-Liebeck, chapter 20).\n\\end{eg}\n\nLet's talk about induced characters.\n\n\\begin{defi} (10.4)\\\\\nIf $\\psi \\in \\mathcal{C}(H)$, define $Ind_H^G \\psi(g) = \\frac{1}{|G|} \\sum_{\\chi \\in G} \\mathring{\\psi} (x^{-1} gx)$, where\n\\begin{equation*}\n\\begin{aligned}\n\\mathring{\\psi(g)} = \\left\\{\\begin{array}{ll}\n\\psi(g) & g \\in H\\\\\n0 & g \\not\\in H\n\\end{array}\n\\right.\n\\end{aligned}\n\\end{equation*}\nWe also write $Ind_H^G \\psi (g)$ as $\\psi \\uparrow^G = \\psi^G$.\n\\end{defi}\n\n\\begin{lemma} (10.5)\\\\\nIf $\\psi \\in \\mathcal{C}(H)$ then $Ind_H^G \\psi \\in \\mathcal{C}(G)$ and $Ind_H^G \\psi(1) = |G:H|\\psi(1)$.\n\\begin{proof}\nThis is clear, noting that $Ind_H^G \\psi(1) = \\frac{1}{H} \\sum \\mathring{\\psi}(1) = |G:H| \\psi(1)$.\n\\end{proof}\n\\end{lemma}\n\nLet $n = |G:H|$. Let $1=t_1,t_2,...,t_n$ be a \\emph{left transversal} of $H$ in $G$ (complete set of coset representatives), so that $t_1H = H$, $t_2H,...,t_nH$ are precisely the $n$ left cosets of $H$ in $G$.\n\n\\begin{lemma} (10.6)\\\\\nGiven left transversal as above,\n\\begin{equation*}\n\\begin{aligned}\nInd_H^G \\psi(g) = \\sum_{i=1}^n \\mathring{\\psi} (t_i^{-1} gt_i)\n\\end{aligned}\n\\end{equation*}\n\\begin{proof}\nFor $h \\in H$, $\\mathring{\\psi}((t_i h)^{-1} g(t_ih)) = \\mathring{\\psi} (t_i^{-1} g t_i)$ as $\\psi$ is a class function on $H$.\n\\end{proof}\n\\end{lemma}\n\n\\begin{thm} (10.7, Frobenius reciprocity)\\\\\n$H \\leq G$. $\\psi$ is a class function for $H$, $\\phi$ is a class function for $G$. Then\n\\begin{equation*}\n\\begin{aligned}\n\\bra \\underbrace{Res_H^G \\phi}_{in\\ \\mathcal{C}(H)} , \\psi\\ket_H = \\bra\\phi,\\underbrace{Ind_H^G \\psi}_{in\\ \\mathcal{C}(G)}\\ket_G\n\\end{aligned}\n\\end{equation*}\n\\begin{proof}\nWe want to show $\\bra \\phi_H,\\psi\\ket_H =\\bra \\phi,\\psi^G \\ket_G$:\n\\begin{equation*}\n\\begin{aligned}\n\\bra \\phi,\\psi^G \\ket = \\frac{1}{|G|} \\sum_{g \\in G} \\overline{\\phi(g)} \\psi^G (g) =\\frac{1}{|G||H|} \\sum_{g,x \\in G} \\overline{\\phi(g)} \\mathring{\\psi} (x^{-1}gx)\n\\end{aligned}\n\\end{equation*}\nPut $y=x^{-1}gx$. The above then equals\n\\begin{equation*}\n\\begin{aligned}\n\\frac{1}{|G||H|} \\sum_{x,y \\in G} \\overline{\\phi(y)} \\mathring{\\psi}(y) = \\frac{1}{|H|} \\sum_{y \\in G} \\overline{\\phi(y)} \\mathring{\\psi}(y)\n\\end{aligned}\n\\end{equation*}\nwhich is independent of $x$, and then equals\n\\begin{equation*}\n\\begin{aligned}\n\\frac{1}{|H|} \\sum_{y \\in H} \\overline{\\phi(y)} \\psi(y) = \\bra \\phi_H,\\psi\\ket_H\n\\end{aligned}\n\\end{equation*}\n\\end{proof}\n\\end{thm}\n\n\\begin{coro} (10.8)\\\\\nIf $\\psi$ is a character of $H$, then $Ind_H^G \\psi$ is a character of $G$.\n\\begin{proof}\nLet $\\chi$ be an irreducible character of $G$. Then\n\\begin{equation*}\n\\begin{aligned}\n\\bra Ind_H^G \\psi,\\chi\\ket = \\bra \\psi,Res_H^G \\chi\\ket \\in \\Z_{\\geq 0}\n\\end{aligned}\n\\end{equation*}\nsince $\\psi$ and $Res_H^G \\chi$ are characters. Hence $Ind_H^G \\psi$ is a linear combination of irreducible charcaters with non-negative coefficients, hence a character.\n\\end{proof}\n\\end{coro}\n\n\\begin{lemma} (10.9)\\\\\nLet $\\psi$ be a character of $H \\leq G$, and let $g \\in G$. Let \n\\begin{equation*}\n\\begin{aligned}\n\\mathcal{C}_G(g) \\cup H = \\bigcup_{i=1}^m \\mathcal{C}_H (x_i)\n\\end{aligned}\n\\end{equation*}\n(disjoint union), where the $x_i$ are representatives of the $H$-ccls of elements of $H$ conjugate to $g$.\\\\\nIf $m =0$, then $Ind_H^G \\psi(g) = 0$. Otherwise\n\\begin{equation*}\n\\begin{aligned}\nInd_H^G \\psi(g) = |C_G(g)| \\cdot \\sum_{i=1}^m \\frac{\\psi(x_i)}{|C_H(x_i)|}\n\\end{aligned}\n\\end{equation*}\n\\begin{proof}\nAssume $m>0$. Let $X_i = \\{x \\in G: x^{-1} g x \\in H$ and is conjugate in $H$ to $x_i\\}$ $\\forall 1 \\leq i \\leq m$.\nThe $X_i$ are pairwise disjoint, and their union is $\\{x \\in G: x^{-1} gx \\in H\\}$. By definition,\n\\begin{equation*}\n\\begin{aligned}\nInd_H^G \\psi(g) &= \\frac{1}{|H|} \\sum_{\\alpha \\in G} \\mathring{\\psi}(x^{-1}gx)\\\\\n&= \\frac{1}{|H|} \\sum_{i=1}^m \\sum_{x \\in X_i} \\psi (x^{-1}gx)\\\\\n&= \\frac{1}{|H|} \\sum_{i=1}^m \\sum_{x \\in X_i} \\psi(x_i)\\\\\n&= \\sum_{i=1}^m \\frac{|X_i|}{|H|} \\psi(x_i)\n\\end{aligned}\n\\end{equation*}\nand evaluate $\\frac{|X_i|}{|H|}$ to get what we want... although a bit tedious: Fix $1 \\leq i \\leq m$ and choose some $g_i \\in G$ s.t. $g_i^{-1} gg_i = x_i$ so $\\forall c \\in C_G (g)$ and $h \\in H$,\n\\begin{equation*}\n\\begin{aligned}\n(cg_i h)^{-1} g(cg_ih) &= h^{-1}g_i^{-1}c^{-1}gcg_i h\\\\\n&= h^{-1}g_i^{-1} c^{-1}cgg_i h\\\\\n&=h^{-1} g_i^{-1} g g_i h\\\\\n&= h^{-1} x_i h \\in H\n\\end{aligned}\n\\end{equation*}\ni.e. $cg_i h \\in X_i$, hence $C_G(g) g_i H \\subseteq X_i$;\n\nConvserly, if $x\\in X_i$ then $x^{-1} gx = h^{-1} x_i h = h^{-1} (g_i^{-1} gg_i)h$ for some $h \\in H$; thus $xh^{-1} g_i^{-1} \\in C_G(g)$. So $x \\in C_G(g) g_i h \\subseteq C_G(g) g_i H$. Conclude $X_i = C_G (g) g_i H$, thus \n\\begin{equation*}\n\\begin{aligned}\n|X_i| = |C_G(g) g_i H| = \\frac{|C_G(g)||H|}{|H \\cap g_i^{-1} C_G (g) g_i}\n\\end{aligned}\n\\end{equation*}\n(see notes at end). Finally $g_i^{-1} C_G(g) g_i = C_G(g_i^{-1} gg_i) = C_G(x_i)$. Thus\n\\begin{equation*}\n\\begin{aligned}\n|X_i| &= |H:H \\cup C_G(x_i)||C_G(g)|\\\\\n&=|H:C_H(x_i)||C_G(g)|\n\\end{aligned}\n\\end{equation*}\nThus, \n\\begin{equation*}\n\\begin{aligned}\n\\frac{|X_i|}{|H|} &= \\frac{|H:C_H(x_i)||C_G(g)|}{|H|}\\\\\n&= \\frac{|C_G(g)|}{|C_H(x_i)|}\n\\end{aligned}\n\\end{equation*}\nfor each $1 \\leq i \\leq m$.\n\\end{proof}\n\\end{lemma}\n\nNote: if $H,K \\leq G$, a double coset of $H$ and $K$ in $G$ is a set $HgK = \\{hgk:h \\in H,k \\in K\\}$ for some $g \\in G$.\n\nFacts:\\\\\n$\\bullet$ two double cosets are either disjoint or equal;\\\\\n$\\bullet$ $|HgK| = \\frac{|H||K|}{|H \\cap gKg^{-1}} = \\frac{|H||K|}{|g^{-1} Hg\\cap K|}$ (prove this: it's a bit like $|HK|$).\n\n\\begin{eg}\nConsider $H = C_4 = \\bra (1234 \\ket \\leq G = S_4$, of index 6. Char of induced representation $Ind_H^G(\\alpha)$ wher $|alpha$ is faithful 1-dim representation of $C_4$. If $\\alpha((1234)) = i$, then char of $\\alpha$ is $(1\\ i\\ -1\\ i)$ for $(1),(1234),(13)(24),(1432)$. The induced representation of $S_4$, we know $Ind_{C_4}^{S_4} \\chi_\\alpha$ evaluates to 6 at $(1)$ (by (10.5)) and to $0$ at $(12)$ and $(123)$.\\\\\nFor $(12)(34)$ only one of the three elements of $S_4$ it's conjugate to, lies in $H$, namely $(13)(24)$. So $Ind_H^G \\chi_\\alpha((12)(34)) = 8(-1/4) = -2$.\\\\\nFor $(1234)$, it is conjugate to $6$ elements of $S_4$ of which two are in $C_4$, namely $(1234)$ and $(1432)$. So $Ind_H^G \\chi_\\alpha (1234) = 4(\\frac{i}{4} - \\frac{i}{4}) = 0$.\n\\end{eg}\n\n\\subsection{Induced representations}\nLet $H \\leq G$, of index $n$. Let $1=t_1,t_2,...,t_n$ transversal, i.e. $H,t_2H,...,t_n H$ are left cosets of $H$. Let $W$ be a $H$-space.\n\n\\begin{lemma} (10.10)\\\\\n$Ind_{\\{1\\}}^G 1= \\rho_{reg}$.\n\\end{lemma}\n\n\\begin{defi} (10.11)\nLet $V:=W \\oplus t_2\\otimes W \\oplus ... \\oplus t_n \\otimes W = \\bigoplus_{t_i} t_i \\otimes W$, where $t_i \\otimes W = \\{t_i \\otimes w: w \\in W\\}$. So $\\dim V = n\\dim W$. We write $V = Ind_H^G W$.\n\\end{defi}\n\n\\emph{$G$-action}: Let $g \\in G$. $\\forall i \\exists $ unique $j$ with $t_j^{-1} g t_i \\in H$ (namely $t_j H$ is the coset containing $gt_i$). You got to understand where did this $g$ come from, otherwise you can't make progress. Define\n\\begin{equation*}\n\\begin{aligned}\ng(t_i \\otimes W) = t_j \\otimes ((t_j^{-1} gt_i) w)\n\\end{aligned}\n\\end{equation*}\nWe drop $\\otimes$ from now. Check this is a $G$-action. Then\n\\begin{equation*}\n\\begin{aligned}\ng_1(g_2 t_i w) &= g_1(t_j(t_j^{-1} g_2t_i)w)\\\\\n&= t_l((t_l^{-1}g_1t_j)(t_j^{-1}g_2 t_i)w)\\\\\n&= t_l (t_l^{-1} (g_1g_2) t_i)w = (g_1)(g_2) (t_i w)\n\\end{aligned}\n\\end{equation*}\nwhere $j$ and $l$ are the unique ones such that $g_2 t_iH = t_jH$ and $g_1 t_j H = t_l H$.\n\nIt has the 'right' character: $g:t_i w \\to t_j \\underbrace{(t_j^{-1} gt_i})_{ \\in H} w$, so the contribution to the character is $0$ unless $j=i$, i.e. if $t_i^{-1} gt_i \\in H$, in which case it contributes $\\psi(t_i^{-1} gt_i)$. So\n\\begin{equation*}\n\\begin{aligned}\nInd_H^G \\psi_(g) = \\sum_1^m \\mathring{\\psi} (t_i^{-1} gt_i)\\ (10.6)\n\\end{aligned}\n\\end{equation*}\n\n\\begin{rem} (10.12)\\\\\nThere is Frobenius Reciprocity,\n\\begin{equation*}\n\\begin{aligned}\nHom_H(W,Res_H^G V) \\cong Hom_G (Ind_H^G W,V)\n\\end{aligned}\n\\end{equation*}\n\\end{rem}\nnaturally as vector spaces ($W$ is a $H$-space, $V$ is a $G$-space).\n\n\\begin{lemma} (10.13)\\\\\n(i) $Ind_H^G(W_1 \\oplus W_2) \\cong Ind_H^G W_1 \\otimes Ind_H^G W_2$;\\\\\n(ii) $\\dim Ind_H^G W = |G:H|\\dim W$.\\\\\n(iii) If $H \\leq K \\leq G$, then $Ind_K^G Ind_H^K W \\cong Ind_H^G W$.\\\\\n(lecture had (10.10) here because he missed it previously, and labelled (iii) as (iv) while (10.10) as (iii)).\\\\\n\\begin{proof}\n(10.10):\n\\begin{equation*}\n\\begin{aligned}\nInd_H^G \\psi(g) &= \\sum_{i=1}^n \\mathring{\\psi}(t_i^{-1} gt_i)\\\\\n&= \\sum_1^n \\mathring{1}_H (e_i^{-1} gt_i)\\\\\n&= |\\{ i: t_i^{-1} gt_i \\in H\\}|\\\\\n&= |\\{i : g \\in t_i H t_i^{-1}\\}| = |fix_X (g)| = \\pi_X\n\\end{aligned}\n\\end{equation*}\n\\end{proof}\n\\end{lemma}\n\n\\begin{rem}\n$\\bra \\psi_X,1_G\\ket_G = \\bra Ind_H^G 1_H, 1_G\\ket_G = \\bra 1_H,1_H\\ket = 1$ as predicted in chapter 7.\n\\end{rem}\n\n\\newpage\n\\section{Frobenius groups}\n\n\\begin{thm} (11.1, Frobenius theorem, 1891)\\\\\nLet $G$ be a transitive permutation group on a finite $X$, say $|X|=n$. Assume that each non-identity element of $G$ fixes at most one element of $X$. Then\n\\begin{equation*}\n\\begin{aligned}\nK =  \\{1\\} \\cup \\{g \\in G: g \\alpha \\neq \\alpha \\forall \\alpha \\in X\\}\n\\end{aligned}\n\\end{equation*}\nis a normal subgroup of $G$ of order $n$.\\\\\nNote that $G$ is necessarily finite, being isomorphic to a subgroup of $S_X$.\n\\begin{proof}\n(method of exceptional characters, due to M. Isaacs - chapter 7 books)\\\\\nWe have to show $K \\triangleleft G$. Let $H = G_\\alpha$ the stabiliser of $\\alpha \\in X$ for some $\\alpha \\in X$, i.e. $g G_\\alpha g^{-1} = G_{g\\alpha}$. Conjugates of $H$ are stabiliers of single elements of $X$. No two conjugates can share a non-identity elment (by hypothesis), so $H$ has $n$ distinct conjugate, and $G$ itself has $n(|H|-1)$ elements that fix exactly one element of $X$. But $|G| = |X||H = n|H|$ ($X$ and $G/H$ are isomorphic (because transitive action) as $G$-sets). Hence $|K| = |G| -n(|H|-1) = n$. Let $1 \\neq h \\in H$. Suppose $h = ghg^{-1}$ for some $g \\in G, h' \\in H$. Then $h$ lies in both $H = G_\\alpha$ and $gHg^{-1} = G_{g\\alpha}$; by hypothesis $g\\alpha = \\alpha$, hence $g \\in H$. Therefore, the ccls in $G$ of $h$ is precisely the ccls in $H$. Similarly oif $g \\in C_G(h)$, then $h=ghg^{-1} \\in G_{g\\alpha}$ and hence $g \\in H$. We conclude $C_G(h) = C_H(h)$ ($1 \\neq h \\in H$). Every element of $G$ either belongs to $K$ or lies in one of the $n$ stabilisers, each of which is conjugate to $H$. So evergy element of $G \\setminus K$ is conjugate with a non-identity element of $H$.\\\\\nSo $\\{1,h_2,...,h_t,y_1,...,y_u\\}$ (the representations of $H$-ccls and representations of ccls of $G$ which comprise $K \\setminus \\{1\\}$ respectively) is a set of ccls reps for $G$.\n\nTake $\\theta_1 = 1_G$. $\\{1_H = \\psi_1,...,\\psi_t\\}$ be irreducible characters of $H$. Fix $1 \\leq i \\leq t$. Then, if $g \\in G$, we know\n\\begin{equation*}\n\\begin{aligned}\nInd_H^G \\psi_i (g) = \\left\\{\\begin{array}{ll}\n|G:H| \\psi_i(1) = n\\psi_i(1) & g=1\\\\\n\\psi_i (h_j) & g=h_j (2 \\leq j \\leq t)\\\\\n0 & g=y_k (1 \\leq k \\leq u)\n\\end{array}\n\\right.\n\\end{aligned}\n\\end{equation*}\nwhere in the second case we appeal to $C_G(h_j) = C_H(h_j)$ and (10.9). Now fix some $2 \\leq i \\leq t$ and put $\\theta_i = \\psi_i^G - \\psi_i(1) \\psi_1^G + \\psi_i(1) \\theta_1 \\in R(G)$ by (9.15). Values for $2 \\leq j \\leq t$, $1 \\leq k\\ leq u$:\n\n\\includegraphics[scale=0.5]{image/Rep_08.png}\n\nNow calculate\n\\begin{equation*}\n\\begin{aligned}\n\\bra \\theta_i ,\\theta_i \\ket &= \\frac{1}{|G|} \\sum_{g \\in G} |\\theta_i(g)|^2\\\\\n&= \\frac{1}{|G|} \\left(\\sum_{g \\in K} |\\theta_i(g)|^2 + \\sum_{\\alpha \\in X} \\sum_{1 \\neq g \\in G_\\alpha} |\\theta_i(g)|^2\\right)\\\\\n&= \\frac{1}{|G|} (n\\psi_i^2 (1) + n \\sum_{1 \\neq h \\in H} |\\theta_i (h)|)^2\\\\\n&= \\frac{1}{|H|} \\sum_{h \\in H} |\\psi_i(h)|^2\\\\\n&= \\bra \\psi_i,\\psi_i\\ket\\\\\n&= 1\n\\end{aligned}\n\\end{equation*}\nAs $\\psi_i$ is irreducible. So (by (9.15)), either $\\theta_i$ or $-\\theta_i$ is a character. Since $\\theta_i(1) > 0$, it's $+\\theta_i$, an actual character. Let $\\theta = \\sum_{i=1}^t \\theta_i(1) \\theta_i$. Column orthogonality gives $\\theta(h) = \\sum_{i=1}^t \\psi_i(1) \\psi_i(h) = 0$ ($1 \\neq h \\in H$), and for any $y \\in K$, $\\theta(y) = \\sum_{i=1}^t \\psi_i^2 (1) = |H|$. Hence\n\\begin{equation*}\n\\begin{aligned}\n\\theta(g) = \\left\\{\\begin{array}{ll}\n|H| & g \\in K\\\\\n0 & g \\not\\in K\n\\end{array}\n\\right.\n\\end{aligned}\n\\end{equation*}\nSo $K = \\{g \\in G : \\theta(g) = \\theta(1) \\} \\triangleleft G$.\n\\end{proof}\n\\end{thm}\n\n\\begin{defi} (11.2)\\\\\nA Frobenius group is a group $G$ having subgroup $H$ s.t. $H \\cap gHg^{-1} = 1$ $\\forall g \\not\\in H$.\\\\\n$H$ is the Frobenius complement of $G$.\n\\end{defi}\n\n\\begin{prop} (11.3)\\\\\nAny finite Frobenius group satisfies the hypothesis of (11.1). The normal subgroup $K$ is a Frobenius Kernel of $G$.\n\\begin{proof}\nLet $G$ be Frobenius, with complement $H$. Then action of $G$ on $G/H$ is transitive and faithful. Furthermore, if $1 \\neq g \\in G$ fixes both $xH$ and $yH$, then $g \\in xHx^{-1} \\cap yhy^{-1}$ $\\implies$ $H \\cap (y^{-1} x) H (y^{-1}x)^{-1} \\neq 1$ $\\implies xH = yH$.\n\\end{proof}\n\\end{prop}\n\nExample: If $p,q$ distinct primes, $p \\equiv 1 \\pmod q$, the unique non-abelian group of order $pq$ is a Frobenius group (see James-Liebeck chapter 25 or Teleman chapter 11).\n\nRemarks:\\\\\n$\\bullet$ Thompson (thesis, 1959) proved any finite group having fixed point free automorphism of prime power order is nilpotent. This implied that in finite Frobenius group, $K$ is nilpotent (iff $K$ is a direct product of its sylow subgroups).\\\\\n$\\bullet$ There is no profo of (11.1) known in which character theory is not required.\n\n\\newpage\n\\section{The missing lecutre: Mackey Theory}\nLet's work over $\\C$. Mackey Theory describes restriction to a subgroup $K \\leq G$ of an irreducible representation $Ind_H^G W$. Here $K,H$ are unrelated, but usually we take $K=H$, in which case we can characterise when $Ind_H^G W$ is irreducible. (?)\n\nSpecial case: $W=1_H$ (trivial $H$-space of dimension 1). Then $Ind_H^G W$ is the permutation representation of $G$ on $G/H$ (by 10.10, action on left cosets of $H$ in $G$).\n\nRecall: if $G$ is transitive on a set $X$ and $H=G_\\alpha$ for some $\\alpha \\in X$, then the action of $G$ on $X$ is isomorphic to the action of $G$ on $G/H$, namely\n\\begin{equation*}\n\\begin{aligned}\ng \\cdot \\alpha & \\leftrightarrow &gH \\ (12.1)\\\\\n\\in X & & \\in G/H\n\\end{aligned}\n\\end{equation*}\nis a well-defined bijection and commutes with $G$-actions ($x(g\\alpha) = (xg)\\alpha \\leftrightarrow x(gH) = (xg)H$).\n\nConsider the action of $G$ on $G/H$ and let $K \\leq G$. $G/H$ splits into $K$-orbits: these correspond to \\emph{double cosets} $KgH = \\{KgH : k \\in K, h \\in H\\}$, namely the $K$-orbit containing $gH$ contains precisely all $kgH$ with $k \\in K$ (bunches of some $gH$ cosets together).\n\n\\begin{notation} (12.2)\\\\\n$K\\backslash G/H$ is the set of $(K,H)$-double cosets; they partition $G$. Note that $|K\\backslash G/H| = \\bra \\pi G/K,\\pi G/H\\ket$ as in (7.4). Let $S$ be the set of representations.\n\\end{notation}\n\nClearly $G_{gH} = gHg^{-1}$, so $K_{gH} = gHg^{-1} \\cap K = Hg$.\n\nSo by (12.1), the action of $K$ on the orbit containing $gH$ is isomorphic to the action of $K$ on $K/Hg$. From this, using $Ind_H^G 1_H = \\C(G/H)$ and, if $X = \\cup X_i$ a decomposition into orbits, then $\\C X = \\oplus_i \\C X_i$, we get\n\n\\begin{prop} (12.3)\\\\\n$G$ is a finite group, $H,K \\leq G$. Then\n\\begin{equation*}\n\\begin{aligned}\nRes_K^G Ind_H^G 1 \\cong \\oplus_{g \\in S} Ind_{gHg^{-1}}^K 1\n\\end{aligned}\n\\end{equation*}\nI think this is some application:\\\\\nLet $S = \\{g_1=1,g_2,...,g_r\\}$ be s.t. $G = \\cup_i Kg_i H$. Write $H_g = gHg^{-1} \\cap K$ ($\\leq K$). $(\\rho,W)$ is representation of $H$. For $g \\in G$, define $(\\rho_g,W_g)$ to be the representation of $Hg$ with the same underlying vector space $W$, but now the $Hg$-action is $\\rho_g(x) = \\rho(h)$, where $x \\in gHg^{-1}$. Since $H_g \\leq K$, we obtain an induced represntation $Ind_{H_g}^G W_g$ from this.\n\\end{prop}\n\n\\begin{thm} (12.4) (Mackey's restriction formula)\\\\\n$G$ finite, $H,K \\leq G$ and $W$ $H$-space. Then\n\\begin{equation*}\n\\begin{aligned}\nRes_K^G Ind_H^G W = \\oplus_{g\\in S} Ind_{H_g}^K W_g\n\\end{aligned}\n\\end{equation*}\nas $K$-modules.\\\\\nWe'll prove this later.\n\\end{thm}\n\n\\begin{coro} (12.5, character version of (12.4))\\\\\nIf $\\psi$ is a character of a representation of $H$, then\n\\begin{equation*}\n\\begin{aligned}\nes_K^G Ind_H^G \\psi = \\sum_{g \\ni S} Ind_{H_g}^K \\psi_g\n\\end{aligned}\n\\end{equation*}\nwhere $\\psi_g$ is the character of $H_g$ given as $\\psi_g(x) = \\psi(g^{-1} xg)$.\n\\end{coro}\n\n\\begin{coro} (12.6, Mackey's irreducibility criterion)\\\\\nLet $H \\leq G$, $W$ be a $H$-vector space. Then $V = Ind_H^G W$ is irreducible iff\\\\\n(i) $W$ is irreducible;\\\\\n(ii) for each $g \\in S\\setminus H$, the two $Hg$- spaces $Wg$ and $Res_{H_g}^H W$ have no irreducible consitutnets in common (they're 'disjoint' representations).\n\\begin{proof}\nLet $W$ afford character $\\psi$. Recall $W$ irreducible $\\iff \\bra \\psi,\\psi \\ket = 1$. Take $K=H$ in (12.4), so $Hg = gHg^{-1} \\cap H$. Then\n\\begin{equation*}\n\\begin{aligned}\n\\bra Ind_H^G \\psi,Ind_H^G \\psi\\ket_G = \\bra \\psi,Res_H^G Ind_H^G \\psi\\ket_H\n\\end{aligned}\n\\end{equation*}\nby (10.7), then by (12.5) is equal to\n\\begin{equation*}\n\\begin{aligned}\n\\sum_{g \\in S} \\bra \\psi Ind_{H_g}^H \\psi_g\\ket_H &= \\sum_{g \\in S} \\bra Res_{H_g}^H \\psi, \\psi_g\\ket_{H_g}\\\\\n&= \\bra \\psi,\\psi\\ket_H + \\sum_{g \\in S, g \\not\\in H} d_g\n\\end{aligned}\n\\end{equation*}\nwhere $d_g = \\bra Res_{H_g}^H \\psi,\\psi_g \\ket$ ($g \\neq 1$).\n\\end{proof}\n\\end{coro}\n\nFor $g=1$ we have $H_g =H$, hence we get a sum of non-negative integers which is $\\geq 1$. So $Ind_H^ \\psi$ is irreducible iff $\\bra\\psi,\\psi\\ket = 1$ and all the other terms in the sum are 0. In other words, $W$ is irreducible representation of $H$ and $\\forall g \\not\\in H$, $W$ and $W_g$ are disjoint representations of $H \\cap gHg^{-1}$.\n\n\\begin{rem}\nSet $S$ of representations was arbitrary, so could demand $g \\in G \\setminus H$ in (ii) but in fact suffices to check for $g \\in S \\setminus H$.\n\\end{rem}\n\n\\begin{coro} (12.7)\\\\\nIf $H \\triangleleft G$, assume $\\psi$ is an irreducible character of $H$. Then $Ind_H^G \\psi$ is irreducible $\\iff \\psi$ is distinct from all its conjugates $\\psi_g$ for all $g \\in G\\setminus H$ ($\\psi_g(h) = \\psi(ghg^{-1})$).\n\\begin{proof}\nAgain take $K=H$, noting double cosets $\\equiv$ left cosets. Also, $Hg = H$ $\\forall g$ (as $H \\triangleleft G$). Moreover, $Wg$ is irreducible since $W$ is irreducible. So by (12.6), $Ind_H^G W$ is irreducible precisely when $W \\not\\cong Wg$ $\\forall g \\in G \\setminus H$. This is equivalent to $\\psi \\neq \\psi g$.\n\\end{proof}\n\\end{coro}\n\n\\begin{rem}\nAgain could check conditions on a set of representatives.\n\\end{rem}\n\n\\begin{proof} (of 12.4)\\\\\nWrite $V = Ind_H^G W$. Fix $g \\in G$. Now $V$ is a direct sum of $x \\oplus W$ with $x$ running through representations of left cosets of $H$ in $G$ (10.11). $V = \\oplus_{x \\in J} x \\otimes W$.\\\\\nConsider a particular coset $KgH = K\\backslash G/H$. The terms\n\\begin{equation*}\n\\begin{aligned}\nV(g) = \\oplus_{x\\text{ rep of H in } G, x \\in KgH} x \\otimes W\n\\end{aligned}\n\\end{equation*}\nforms a subspace invariant under the action of $K$ (it's a direct sum of an orbit of subspaces permuted by $K$). Now viewing $V$ as a $K$-space (forget $G$-structure), $Res_K^G V = \\oplus_{g \\in S} V(g)$, so we need to show $V(g) = Ind_{H_g}^K W_g$ as $K$-spaces for each $g \\in S$.\n\nNow, $Stab_K (g \\otimes W) = \\{k \\in K: kg \\otimes W = g \\otimes W\\} = \\{k \\in K: g^{-1} kg \\in Stab_G (1 \\otimes W) = H\\} = K \\cap gHg^{-1}$ ($=Hg$). This implies if $x = kgh, x' =k'gh'$, then $x \\otimes W = x' \\otimes W$ iff $k,k'$ lie in same coset in $K/Hg$, hence $V(g)$ is direct sum $\\oplus_{k \\in K/Hg} k \\otimes (g \\otimes W)$. Therefore, as a representation of $K$, this subspace is\n\\begin{equation*}\n\\begin{aligned}\nV(g) \\cong Ind_{H_g}^K (g \\otimes W)\n\\end{aligned}\n\\end{equation*}\n\\end{proof}\nBut $g \\otimes W \\cong Wg$ as a representaiton of $Hg$ ($w \\to g \\otimes W$ is an isomorphism). Putting everything together we are done.\n\n\\newpage\n\\section{Integrality in the group algebra}\n\n\\begin{defi} (13.1)\\\\\n$a \\in \\C$ is an algebraic integer if: $a$ is a root of a monic polynomial in $\\Z[x]$. Equivalently, the subring of $\\C$ generated by $\\Z[a] = \\{f(a): f(x) \\in \\Z[x]\\}$ is a finitely generated $\\Z$-module.\n\\end{defi}\n\nFact 1: The algebraic integers form a subring of $\\C$ (see number fields);\\\\\nFact 2: If $a \\in \\C$ is both an algebraic integer and a rational number, then it's an integer (see number fields);\\\\\nFact 3: Any subring of $\\C$ which is a finitely-generated $\\Z$-module consists of algebraic integers.\n\n\\begin{prop} (13.2)\\\\\nIf $\\chi$ is character of $G$ and $g \\in G$, then $\\chi(g)$ is an algebraic integer.\n\\begin{proof}\n$\\chi(g)$ is a sum of $n$th roots of unity ($n=|g|$). Each root of unity is an algebraic integer, and any sum of algebraic integers is an algebraic integer by fact 1.\n\\end{proof}\n\\end{prop}\n\n\\begin{coro}\nThere are no entries in the chracter rables of any finite group which are rational but not integers, by Fact 2.\n\\end{coro}\n\n\\subsection{The centre of $\\C G$}\nRecall from (2.4), the group algebra $\\C G =\\{ \\sum \\alpha_g g: \\alpha_g \\in \\C\\}$ of finite group, the $\\C$-space with basis $G$. Also a ring, hence a finite-dimensional $\\C$-algebra.\n\nList $\\{1\\} = \\mathcal{C}_1,...,\\mathcal{C}_k$ the $G$-ccls. Define the class sums:\n\\begin{equation*}\n\\begin{aligned}\nC_j = \\sum_{g \\in \\mathcal{C}_j} g \\in \\C G\n\\end{aligned}\n\\end{equation*}\nClaim, each $C_j \\in Z(\\C G)$, the centre of $\\C G$ (Note: this is not the same as $\\C(Z(G))$!).\n\n\\begin{prop} (13.3)\\\\\n$C_1,...,C_k$ is a basis of $Z(\\C G)$. There exist non-negative integers $a_{ijl}$ ($1 \\leq i,j,l \\leq k$) with \n\\begin{equation*}\n\\begin{aligned}\nC_i C_j = \\sum_l a_{ijl} C_l\n\\end{aligned}\n\\end{equation*}\nThese are called the class algebra constants for $Z(\\C G)$.\n\\end{prop}\n\nRemember last time we had $C_j = \\sum_{g \\in \\mathcal{C}_j} g$ ($=\\sum_{k=1}^r x_k^{-1} g_j x_k$). We claimed that $c_1,...,c_k$ are basis for $Z(\\C G)$. Let's now prove it.\n\\begin{proof}\nCheck that $g C_j g^{-1} = C_j$ $\\forall g \\in G$. So $C_j \\in Z(\\C G)$. Clear that the $C_j$ are linearly independent (because the $\\mathcal{C}_J$ are pairwise disjoint). Now suppose $z \\in Z(\\C G)$, $z = \\sum_{g \\in G} \\alpha_g g$. Then $\\forall h \\in G$ we have $\\alpha_{h^{-1}gh} = \\alpha_g$. So the function $g \\to \\alpha_g$ is constant on $G$-conjugacy classes. Wrigting $\\alpha_g = \\alpha_j$ for $g \\in \\mathcal{C}_j$, then $z = \\sum_1^k \\alpha_j C_j$. Finally, $Z(\\C G)$ is a $\\C$-algebra, so $C_i C_j = \\sum_{l=1}^k \\underbrace{a_{ijl}}_{\\in \\C} C_l$, as the $C_l$ span. We claim $a_{ijl} \\in \\Z_{\\geq 0}$ $\\forall i,j,l$: Fix $g_l \\in \\mathcal{C}_l$. Then\n\\begin{equation*}\n\\begin{aligned}\na_{ijl} = \\text{number of} \\{(x,y\\in\\mathcal{C}_i \\times \\mathcal{C}_j:xy = g_l\\} \\in \\Z_{\\geq 0}\n\\end{aligned}\n\\end{equation*}\n\\end{proof}\n\n\\begin{defi} (13.4)\\\\\nLet $\\rho:G \\to GL(V)$ be an irreducible representation over $\\C$, affording character $\\chi$. Extend by linearity to $\\rho:A = \\C G \\to End_\\C V$, an algebra homomorphism. Any homomorphism of algebras $A \\to End V$ is called a representation of $A$. A \\emph{central character} of $A$ is a ring homomorphism $Z(A) \\to \\C$. Let $z \\in Z(\\C G)$. Then $\\rho(z)$ commutes with all $|rho(g)$ ($g \\in \\C G$), so by Schur's lemma, $\\rho(z) = \\lambda_z I$ for some $\\lambda_z \\in \\C$. Now consider the algebra homomorphism $\\omega_\\chi =\\omega: Z(\\C G) \\to \\C$ by $z \\to \\lambda_z$. Now $\\rho(C_i) = \\omega(C_i) I$, so, taking traces,\n\\begin{equation*}\n\\begin{aligned}\n\\chi(1) \\omega(C_i) = \\sum_{g \\in \\mathcal{C}_i} \\chi(g) = |\\mathcal{C}_i| \\chi(g_i)\n\\end{aligned}\n\\end{equation*}\nwhere $g_i$ is a representation of $\\mathcal{C}_i$. So $\\omega(C_i) = \\frac{\\chi(g_i)}{\\chi(1)} |\\mathcal{C}_i|$.\n\\end{defi}\n\n\\begin{lemma} (13.5)\\\\\nThe values $\\omega(C_i) = \\frac{\\chi(g)}{\\chi(1)} |\\mathcal{C}_i|$ are algebraic integers.\n\\begin{proof}\nSince $\\omega$ is an algebra homomorphism and using (13.3),\n\\begin{equation*}\n\\begin{aligned}\n\\omega(C_i) \\omega(C_j) = \\sum_{l=1}^k a_{ijl} \\omega(C_l)\n\\end{aligned}\n\\end{equation*}\nwhere $a_{ijl} \\in \\Z_{\\geq 0}$. Thus the span $\\{\\omega(C_l): 1 \\leq l \\leq k\\}$ is a subring of $\\C$ and is a finitely-generated abelian group, so by Fact 3, consists of algebraic integers.\\\\\n$[$A bit of explanations:\n\\begin{equation*}\n\\begin{aligned}\n\\omega(C_i) \\omega(C_j) = \\sum a_{ijl} \\omega(C_l)\\\\\n\\omega(C_i) \\begin{pmatrix}\n\\omega(C_1)\\\\\n...\\\\\n\\omega(C_k)\n\\end{pmatrix} = (a_{ijk}) \\begin{pmatrix}\n\\omega(C_1)\\\\\n...\\\\\n\\omega(C_k)\n\\end{pmatrix}\n\\end{aligned}\n\\end{equation*}\n$\\omega(C_i)$ is eigenvalue of the integer matrix $(a_{ijl})$ so an algebraic integer by definition.$]$\n\\end{proof}\n\\end{lemma}\n\nExercise (Burnside, 1911):\\\\\nShow that $a_{ijl}$ can be obtained from the charcater table. In fact, $\\forall i,j,l$,\n\\begin{equation*}\n\\begin{aligned}\na_{ijl} = \\frac{|G|}{|C_G(g_i)| |C_G(g_j)|} \\sum_{s=1}^k \\frac{\\chi_s (g_i) \\chi_s(g_j) \\chi_s(g_l^{-1})}{\\chi_s(1)}\n\\end{aligned}\n\\end{equation*}\nfor $g_i \\in \\mathcal{C}_i$, $1 \\leq i \\leq l$.\\\\\n(proof uses column orthogonality, JL 30.4).\n\n\\begin{thm} (13.6)\\\\\nThe degree of any irreducible charcaters of $G$ divides $|G|$.\n\\begin{proof}\nGiven irreducible charcater $\\chi$, apply orthogonality,\n\\begin{equation*}\n\\begin{aligned}\n\\frac{|G|}{\\chi(1)} &= \\frac{1}{\\chi(1)} \\sum_{g \\in G} \\chi(g) \\chi(g^{-1})\\\\\n&= \\frac{1}{\\chi(1)} \\sum_{i=1}^k |\\mathcal{C}_i| \\chi(g_i) \\chi(g_i^{-1})\\\\\n&= \\sum_{i=1}^k \\frac{|\\mathcal{C}_i \\chi(g_i)}{\\chi(1)} \\chi(g_i^{-1})\n\\end{aligned}\n\\end{equation*}\nwhere in the last summand, the first fraction is an algebraic integer by (13.5), and $\\chi(g_i^{-1})$ is sum of roots of unity so an algebraic integer. LHS is clearly also rational, so it's an integer.\n\\end{proof}\n\\end{thm}\n\n\\begin{eg} (13.7)\\\\\n(a) If $G$ is a $p$-group, then $\\chi(1)$ is a $p$-power ($\\chi$ irreducible). In particualr, if $|G| = p^2$, then $\\chi(1) = 1$ (since we already have a trivial character -- the idea is actually similar to the proof in Groups 1A), hence $G$ abelian.\\\\\n(b) If $G = S_n$ then every prime dividing the degree of an irreducible charcater of $G$ also divides $n!$.\n\\end{eg}\n\n\\begin{thm} (13.8, Burnside, 1904)\\\\\nIf $\\chi$ is irreducible, then $\\chi(1) | \\frac{|G|}{|Z|}$.\\\\\nThe proof is left as an exercise. As a hint, it uses tensor products.\n\\end{thm}\n\n\\newpage\n\\section{Burnside's theorem}\n\n\\begin{thm} (14.1)\\\\\nLet $p,q$ be primes, let $|G| = p^a q^b$, where $a,b \\in \\Z_{\\geq 0}$, with $a+b \\geq 2$. Then $G$ is not simple.\n\\begin{proof}\nThe theorem gollows from 2 lemmas. We will prove this on Saturday.\n\\end{proof}\n\\end{thm}\n\n\\begin{rem}\n(1) In fact, even more is true: $G$ is soluble.\\\\\n(2) Result is best possible, in the sense that $|A_5| = 60 = 2^2 \\cdot 3 \\cdot 5$ has 3 prime factors, and is simple (actually there are 8 non-soluble groups of order $p^aq^br^c$ for $p,q,r$ primes).\\\\\n(3) If either $a$ or $b$ is 0 then $G$ is a $p$ group, so is nilpotent, so soluble.\\\\\n(4) In 1963, Feit and Thompson proved that every group of odd order was soluble.\n\\end{rem}\n\n\\iffalse\n\\begin{equation*}\n\\begin{aligned}\n\n\\end{aligned}\n\\end{equation*}\n\\fi\n\n\\end{document}\n", "meta": {"hexsha": "346d6ab0ff736aed47610d55880bbb15c9f2f2b6", "size": 98190, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Notes/Representation.tex", "max_stars_repo_name": "raoxiaojia/raoxiaojia.github.io", "max_stars_repo_head_hexsha": "d20c23a64794b500f2e0356fd01017ee31830fa2", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-25T17:34:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-25T17:34:25.000Z", "max_issues_repo_path": "Notes/Representation.tex", "max_issues_repo_name": "raoxiaojia/raoxiaojia.github.io", "max_issues_repo_head_hexsha": "d20c23a64794b500f2e0356fd01017ee31830fa2", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Notes/Representation.tex", "max_forks_repo_name": "raoxiaojia/raoxiaojia.github.io", "max_forks_repo_head_hexsha": "d20c23a64794b500f2e0356fd01017ee31830fa2", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.9897463573, "max_line_length": 1118, "alphanum_fraction": 0.6375394643, "num_tokens": 38555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984137988773, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.3231629662694076}}
{"text": "\\chapter{fMRI model specification \\label{Chap:fmri_spec}}\n\nStatistical analysis of fMRI data uses a mass-univariate approach based on General Linear Models (GLMs). It comprises the following steps (1) specification of the GLM design matrix, fMRI data files and filtering (2) estimation of GLM parameters using classical or Bayesian approaches and (3) interrogation of results using contrast vectors to produce Statistical Parametric Maps (SPMs) or Posterior Probability Maps (PPMs).\n\nThe design matrix defines the experimental design and the nature of hypothesis testing to be implemented.  The design matrix has one row for each scan and one column for each effect or explanatory variable. (eg. regressor or stimulus function). You can build design matrices with separable session-specific partitions.  Each partition may be the same (in which case it is only necessary to specify it once) or different.\n\nResponses can be either event- or epoch related, the only distinction is the duration of the underlying input or stimulus function. Mathematically they are both modeled by convolving a series of delta (stick) or box functions (u), indicating the onset of an event or epoch with a set of basis functions.  These basis functions model the hemodynamic convolution, applied by the brain, to the inputs.  This convolution can be first-order or a generalized convolution modeled to second order (if you specify the Volterra option). The same inputs are used by the Hemodynamic model or Dynamic Causal Models which model the convolution explicitly in terms of hidden state variables.\n\nEvent-related designs may be stochastic or deterministic.  Stochastic designs involve one of a number of trial-types occurring with a specified probability at successive intervals in time.  These probabilities can be fixed (stationary designs) or time-dependent (modulated or non-stationary designs).  The most efficient designs obtain when the probabilities of every trial type are equal. A critical issue in stochastic designs is whether to include null events. If you wish to estimate the evoked response to a specific event type (as opposed to differential responses) then a null event must be included (even if it is not modeled explicitly).\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=100mm]{fmri_spec/fmri_model}\n\\end{center}\n\\caption{\\em After starting SPM in fMRI mode and pressing the ``Specify 1st-level'' button, the SPM batch editor window should appear as above. The options for ``fMRI model specification'' can be examined by clicking on them. A single click will bring up some help text in the lower subwindow (not shown in the above graphic). Options highlighted with a ``$<$-X'' are mandatory and must be filled in by the user. Each of the options shown above is described in this chapter. \\label{spec}}\n\\end{figure}\n\nIn SPM, analysis of data from multiple subjects typically proceeds in two stages using models at two ``levels''. The ``first level'' models are used to implement a within-subject analysis. Typically there will be as many first level models as there are subjects. Analysis proceeds as described using the ``Specify first level'' and ``Estimate'' options. The results of these analyses can then be presented as ``case studies''. More often, however, one wishes to make inferences about the population from which the subjects were drawn. This is an example of a ``Random-Effects (RFX) analysis'' (or, more properly, a mixed-effects analysis). In SPM, RFX analysis is implemented using the ``summary-statistic'' approach where contrast images from each subject are used as summary measures of subject responses. These are then entered as data into a ``second level'' model.\n\nFigure~\\ref{spec} shows how the SPM graphics window appears during fMRI model specification.\n\n\\section{Timing parameters}\n\nSpecify various timing parameters needed to construct the design matrix. This includes the units of the design specification and the interscan interval.\n\nAlso, with long TRs you may want to shift the regressors so that they are aligned to a particular slice.  This is effected by changing the microtime resolution and onset.\n\n\\subsection{Units for design}\n\nThe onsets of events or blocks can be specified in either scans or seconds.\n\n\\subsection{Interscan interval}\n\nInterscan interval, TR, (specified in seconds).  This is the time between acquiring a plane of one volume and the same plane in the next volume.  It is assumed to be constant throughout.\n\n\\subsection{Microtime resolution}\n\nIn Echo-Planar Imaging (EPI), data is acquired a plane at a time. To acquire a whole volume of data takes at least a second or two.\n\nIt is possible, however, that experimental events may occur between scan (volume) acquisition times. This can be specified when building your design matrix either by (i) specifying your design in scans and using non-integer values  or (ii) specifying your design in seconds at a resolution greater than the TR.\n\nSPM takes these timing specifications and builds its regressors using a `microtime' time-scale. The microtime resolution, t, is the number of time-bins per scan.\n\nDo not change this parameter unless you have a long TR and wish to shift regressors so that they are aligned to a particular slice.\n\n\\subsection{Microtime onset}\n\nThe microtime onset, t0, is the first time-bin at which the regressors are resampled to coincide with data acquisition.  If t0 = 1 then the regressors will be appropriate for the first slice.  If you want to temporally realign the regressors so that they match responses in the middle slice then make t0 = t/2 (assuming there is a negligible gap between volume acquisitions).\n\nDo not change the default setting unless you have a long TR. \n\nA typical use of the t and t0 parameters is to set them to correspond to the results of any slice timing correction you have made eg. if you have 24 slices and have made slice 12 the reference slice you would set t=24, t0=12. \n\n\\section{Data \\& Design}\n\nThe design matrix defines the experimental design and the nature of hypothesis testing to be implemented.  The design matrix has one row for each scan and one column for each effect or explanatory variable. (e.g. regressor or stimulus function).  Figure~\\ref{design} shows an example of a design matrix.\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=100mm]{fmri_spec/design}\n\\end{center}\n\\caption{\\em Design matrix for fMRI data from two sessions. There are 24 experimental conditions for each session. The last two columns model the average activity in each session, giving a total of 50 regressors. There are 191 fMRI scans for each session. The overall design matrix therefore has 382 rows and 50 columns. \\label{design}}\n\\end{figure}\n\nYou can build design matrices with separable session-specific partitions.  Each partition may be the same (in which case it is only necessary to specify it once) or different.  Responses can be either event- or epoch related, where the latter model involves prolonged and possibly time-varying responses to state-related changes in experimental conditions.  Event-related response are modelled in terms of responses to instantaneous events.  Mathematically they are both modelled by convolving a series of delta (stick) or box-car functions, encoding the input or stimulus function. with a set of hemodynamic basis functions.\n\n\\subsection{Subject/Session}\n\nThe design matrix for fMRI data consists of one or more separable, session-specific partitions.  These partitions are usually either one per subject, or one per fMRI scanning session for that subject.\n\n\\subsubsection{Scans}\n\nSelect the fMRI scans for this session.  They must all have the same image dimensions, orientation, voxel size etc. This is implemented using SPM's file selector.\n\n\\subsubsection{Conditions}\n\nYou are allowed to combine both event- and epoch-related responses in the same model and/or regressor. Any number of condition (event or epoch) types can be specified.  Epoch and event-related responses are modeled in exactly the same way by specifying their onsets [in terms of onset times] and their durations.  Events are specified with a duration of 0.  If you enter a single number for the durations it will be assumed that all trials conform to this duration.For factorial designs, one can later associate these experimental conditions with the appropriate levels of experimental factors. \n\n\\paragraph{Condition}\n\nAn array of input functions is constructed, specifying occurrence events or epochs (or both). These are convolved with a basis set at a later stage to give regressors that enter into the design matrix. Interactions of evoked responses with some parameter (time or a specified variate) enter at this stage as additional columns in the design matrix with each trial multiplied by the [expansion of the] trial-specific parameter. The 0th order expansion is simply the main effect in the first column.\n\n\\subparagraph{Name}\n\nCondition Name\n\n\\subparagraph{Onsets}\n\nSpecify a vector of onset times for this condition type. This can be entered using the keyboard eg. typing in ``100 300'' and then hitting return or ``100;300'' or ``[100,300]'' or ``[100,300]''.\n\nMore usually, however, this specification takes place using variables that have been created before and loaded into matlab. For example, an \\verb!my_onsets! cell array\\footnote{Cell arrays are usually used in preference to matrices as different event types can then have different numbers of events.} might exist in a file you created earlier called \\verb!my_design.mat!. You would then type \\verb!load my_design! at the matlab command prompt before pressing the `Specify 1st-level' button. \n\nYou could then specify the onsets for condition 2 by typing in eg. \\verb!my_onsets{2}! instead of entering the numbers via the keyboard.\n\n\n\\subparagraph{Durations}\n\nSpecify the event durations. Epoch and event-related responses are modeled in exactly the same way but by specifying their different durations.  Events are specified with a duration of 0.  If you enter a single number for the durations it will be assumed that all trials conform to this duration. If you have multiple different durations, then the number must match the number of onset times.\n\n\\subparagraph{Time Modulation}\n\nThis option allows for the characterisation of nonstationary responses. Specifically, you can model either linear or nonlinear time effects. For example, 1st order modulation would model the stick functions and a linear change of the stick function heights over time. Higher order modulation will introduce further columns that contain the stick functions scaled by time squared, time cubed etc.\n\n\\subparagraph{Parametric Modulations}\n\nThe stick function itself can be modulated by some parametric variate (this can be time or some trial-specific variate like reaction time) modeling the interaction between the trial and the variate. The events can be modulated by zero or more parameters.\n\nSee \\cite{parametric_pet,parametric_fmri} for further details of parametric modulations.\n\n\\subsubsection{Multiple conditions}\n\nIf you have multiple conditions then entering the details a condition at a time is very inefficient. This option can be used to load all the required information in one go. \n\nYou will need to create a \\verb!*.mat! file containing the relevant information. This \\verb!*.mat! file must include the following cell arrays: names, onsets and durations eg. \\verb!names{2}='SSent-DSpeak'!, \\verb!onsets{2}=[3 5 19 222]!, \\verb!durations{2}=[0 0 0 0]! contain the required details of the second condition. These cell arrays may be made available by your stimulus delivery program eg. COGENT. The duration vectors can contain a single entry if the durations are identical for all events. \n\nYou then need to use SPM's file selector to select this \\verb!*.mat! file.\n\n\\subsubsection{Regressors}\n\nRegressors are additional columns included in the design matrix, which may model effects that would not be convolved with the haemodynamic response.  One such example would be the estimated movement parameters, which may confound the data.\n\n\\paragraph{Regressor}\n\n\\subparagraph{Name}\n\nEnter name of regressor eg. First movement parameter\n\n\\subparagraph{Value}\n\nEnter the values that the regressor takes. This could also be, for example, the name of a variable in MATLAB's work space that you have previously loaded in from a file. This might be a subjects movement parameters or reaction times.\n\n\\subsubsection{Multiple regressors}\n\nIf you have mutliple regressors eg. realignment parameters, then entering the details a regressor at a time is very inefficient. This option can be used to load all the required information in one go. \n\nYou will first need to create a \\verb!*.mat! file containing a matrix R. Each column of R will contain a different regressor. When SPM creates the design matrix the regressors will be named R1, R2, R3, ..etc.\n\nYou then need to use SPM's file selector to select this \\verb!*.mat! file.\n\n\\subsubsection{High-pass filter}\n\nThe default high-pass filter cutoff is 128 seconds. Slow signal drifts with a period longer than this will be removed. Use ``Explore design'' to ensure this cut-off is not removing too much experimental variance. This is described later in section~\\ref{explore}. High-pass filtering is implemented using a residual forming matrix (i.e. it is not a convolution) and is simply a way to remove confounds without estimating their parameters explicitly.  The constant term is also incorporated into this filter matrix.\n\n\\section{Factorial design}\n\nIf you have a factorial design then SPM can automatically generate the contrasts necessary to test for the main effects and interactions.\n\nThis includes the F-contrasts necessary to test for these effects at the within-subject level (first level) and the simple contrasts necessary to generate the contrast images for a between-subject (second-level) analysis.\n\nTo use this option, create as many factors as you need and provide a name and number of levels for each.  SPM assumes that the condition numbers of the first factor change slowest, the second factor next slowest etc. It is best to write down the contingency table for your design to ensure this condition is met. This table relates the levels of each factor to the conditions.\n\nFor example, if you have 2-by-3 design  your contingency table has two rows and three columns where the the first factor spans the rows, and the second factor the columns. The numbers of the conditions are 1,2,3 for the first row and 4,5,6 for the second.\n\nSee \\cite{rnah_anova} for more information on SPM and factorial designs.\n\n\\subsection{Factor}\n\nAdd a new factor to your experimental design.\n\n\\subsubsection{Name}\n\nName of factor, eg. 'Repetition' \n\n\\subsubsection{Levels}\n\nEnter number of levels for this factor, eg. 2\n\n\\section{Basis Functions}\n\nSPM uses basis functions to model the hemodynamic response. This could be a single basis function or a set of functions. The most common choice is the `Canonical HRF' with or without time and dispersion derivatives. \n\n\\subsection{Canonical HRF}\n\nCanonical Hemodynamic Response Function (HRF). This is the default option. Contrasts of these effects have a physical interpretation and represent a parsimonious way of characterising event-related responses. This option is also useful if you wish to look separately at activations and deactivations. This is implemented using a t-contrast with a +1 or -1 entry over the canonical regressor. \n\n\\subsubsection{Model derivatives}\n\nModel HRF Derivatives. The canonical HRF combined with time and dispersion derivatives comprise an `informed' basis set, as the shape of the canonical response conforms to the hemodynamic response that is commonly observed. The incorporation of the derivative terms allow for variations in subject-to-subject and voxel-to-voxel responses. The time derivative allows the peak response to vary by plus or minus a second and the dispersion derivative allows the width of the response to vary by a similar amount. \n\nA positive estimate of the time-derivative regression coefficient implies that the peak hemodynamic response occurs earlier than usual ie. than would be expected using just the canonical regressor. A positive estimate for the dispersion derivative implies a less dispersed response than usual.\n\nThe informed basis set requires an SPM{F} for inference. T-contrasts over just the canonical are perfectly valid but assume constant delay/dispersion. The informed basis set compares favourably with eg. FIR bases on many data sets \\cite{rnah_basis}.\n\n\\subsection{Other basis sets}\n\nThe other basis sets supported by SPM are\n\n\\begin{enumerate}\n\\item{Fourier Set}\n\\item{Fourier Set (Hanning)}\n\\item{Gamma Functions}\n\\item{Finite Impulse Response (FIR)}\n\\end{enumerate}\n\nFor each of these options you must also specify the {\\bf window length} which is the length in seconds of the post-stimulus time window that the basis functions span. You must also specify the {\\bf order}, that is, how many basis functions to use.\n\nUsually, an informed basis set should be sufficient for most data sets. If this does not provide a good fit to the data it may be worthwhile re-considering how the neuronal events are modelled ie. is the timing correct ? should events be split into subsets ? \n\nAlternatively, the gamma basis functions are an interesting choice as a particular linear combination of them is actually used to specify the canonical HRF. The FIR approach is of interest as it is equivalent to the method of `selective averaging'. See \\cite{rnah_conv} for further details. \n\n\\section{Model Interactions (Volterra)}\n\nGeneralized convolution of inputs, $U$, with basis set, $bf$.\n\nFor first order expansions the causes are simply convolved (e.g. stick functions) in $U$ by the basis functions in $bf$ to create a design matrix $X$.  For second order expansions new entries appear that correspond to the interaction among the original causes. The basis functions for these effects are two dimensional and are used to assemble the second order kernel. \n\nInteractions or response modulations can enter at two levels.  Firstly the stick function itself can be modulated by some parametric variate. This can be time or some trial-specific variate like reaction time modeling the interaction between the trial and the variate. Secondly interactions among the trials themselves can be modeled using a Volterra series formulation that accommodates interactions over time (and therefore within and between trial types). \n\nThis last option is useful for accommodating nonlinearities in the hemodynamic response. For example, if two events occur within a second or so of each other then the hemodynamic response to the pair may be less than the sum of the responses to each event when occuring in isolation. This type of `sub-linear' response can be modelled using Volterra kernels. See \\cite{balloon} for further details.\n\n\\section{Directory}\n\nSelect a directory where the SPM.mat file containing the specified design matrix will be written. If this directory already contains an SPM.mat file then SPM will warn you of this before overwriting it, when the specification job is run.\n\n\\section{Global normalisation}\n\nSPM can normalise fMRI data in one of two ways. These are selected using the options `None' (the default) and `Scaling'.\n\nBoth methods are based on first estimating the average within-brain fMRI signal, $g_{ns}$, where $n$ denotes scan and $s$ denotes session. If you select `Scaling', SPM will multiply each fMRI value in scan $n$ and session $s$ by $100/g_{ns}$.\n\nIf you select ``None'' then SPM computes the grand mean value, $g_s=\\frac{\\sum_{n=1}^N g_{ns}}{N}$ where N is the number of scans in that session. This is the fMRI signal averaged over all voxels within the brain and all time points within session $s$. SPM then implements ``Session-specific grand mean scaling'' by multiplying each fMRI data point in session $s$ by $100/g_s$.\n\nSee \\cite{ja_global} for further discussion of this issue.\n\n\\section{Explicit mask}\n\nSpecify an image for explicitly masking the analysis. A sensible option here is to use a segmentation of structural images to specify a within-brain mask. If you select that image as an explicit mask then only those voxels in the brain will be analysed. This both speeds the estimation and restricts SPMs/PPMs to within-brain voxels. Alternatively, if such structural images are unavailable or no masking is required, then leave this field empty.\n\n\\section{Serial correlations}\n\nSerial correlations in fMRI time series due to aliased biorhythms and unmodelled neuronal activity can be accounted for using an autoregressive AR(1) model during Classical (ReML) parameter estimation.  \n\nThis estimate assumes the same correlation structure for each voxel, within each session.  ReML estimates are then used to correct for non-sphericity during inference by adjusting the statistics and degrees of freedom appropriately. The discrepancy between estimated and actual correlations are greatest at low frequencies.  Therefore specification of the high-pass filter is particularly important.\n\nSerial correlation can be ignored if you choose the ``none'' option. Note that the above options only apply if you later specify that your model will be estimated using the Classical (ReML) approach. If you choose Bayesian estimation these options will be ignored. For Bayesian estimation, the choice of noise model (AR model order) is made under the estimation options. See \\cite{peb1,vb_fmri_ar} for further discussion of these issues.\n\n\\section{Reviewing your design \\label{explore}}\n\nAfter you have completed the SPM ``job'' file for specifying your fMRI design, and have run it, you will then be able to review your design by pressing the ``Review'' button in SPM's button window (the top-left window). This is particularly useful, for example, for checking that your experimental variance has not been removed by high-pass filtering, as shown in Figure~\\ref{rev4}.\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=100mm]{fmri_spec/reg4}\n\\end{center}\n\\caption{\\em After pressing ``Review'', selecting the pull-down `Design' menu, Explore-$>$Session, and selecting the regressor you wish to look at, you should get a plot similar to the one above. The top row shows time and frequency domain plots of the time-series corresponding to this regressor. In this particular case we have four events. Each event or ``stick function'' has been convolved with the hemodynamic response function shown in the bottom panel. The frequency domain graph is useful for checking that experimental variance is not removed by high-pass filtering. The grayed out section of the frequency plot shows those frequencies which are removed. For this regressor we have plenty of remaining experimental variance (see the peak at about 0.04Hz). \\label{rev4}}\n\\end{figure}\n", "meta": {"hexsha": "18b3c02207dc5443b8ed090443947153e8c66f82", "size": 22907, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "spm8/man/fmri_spec/fmri_spec.tex", "max_stars_repo_name": "Hexans/spm_linux", "max_stars_repo_head_hexsha": "0d817a8478de736cd91946efa2a71c8dae7ec08a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2018-02-17T14:01:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T20:28:03.000Z", "max_issues_repo_path": "spm8/man/fmri_spec/fmri_spec.tex", "max_issues_repo_name": "Hexans/spm_linux", "max_issues_repo_head_hexsha": "0d817a8478de736cd91946efa2a71c8dae7ec08a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-09-27T20:50:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-24T20:06:01.000Z", "max_forks_repo_path": "spm8/man/fmri_spec/fmri_spec.tex", "max_forks_repo_name": "Hexans/spm_linux", "max_forks_repo_head_hexsha": "0d817a8478de736cd91946efa2a71c8dae7ec08a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-02-05T22:13:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-02T05:12:25.000Z", "avg_line_length": 92.7408906883, "max_line_length": 869, "alphanum_fraction": 0.7984022351, "num_tokens": 4902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.3231400120298387}}
{"text": "%\\documentclass [12pt]{article}\n%\\usepackage{amssymb}\n\\documentclass[twocolumn,showpacs,preprintnumbers,amsmath,amssymb]{revtex4}\n\\usepackage{dcolumn}\n\\usepackage{bm}\n\n\\usepackage{gb4e} % added by ES\n\n\\begin {document}\n\n\n\n\\title {The strong superadditivity conjecture holds for the quantum depolarizing channel in any dimension}\n\n\\author {Grigori G. Amosov}\n\n\\email {gramos@mail.ru}\n\n\n\\affiliation {Department of Higher Mathematics\\\\\nMoscow Institute of Physics and Technology\\\\ Dolgoprudny\n141700\\\\RUSSIA}\n\n\n\\date{\\today}\n\n\n\\begin {abstract}\nGiven a quantum channel $\\Phi $ in a Hilbert space $H$ put $\\hat\nH_{\\Phi}(\\rho)=\\min \\limits _{\\rho _{av}=\\rho }\\Sigma\n_{j=1}^{k}\\pi _{j}S(\\Phi (\\rho _{j}))$, where $\\rho _{av}=\\Sigma\n_{j=1}^{k}\\pi _{j}\\rho _{j}$, the minimum is taken over all\nprobability distributions $\\pi =\\{\\pi _{j}\\}$ and states $\\rho\n_{j}$ in $H$, $S(\\rho)=-Tr\\rho\\log\\rho$ is the von Neumann\nentropy of a state $\\rho$. The strong superadditivity conjecture\nstates that $\\hat H_{\\Phi \\otimes \\Psi}(\\rho)\\ge \\hat\nH_{\\Phi}(Tr_{K}(\\rho))+\\hat H_{\\Psi}(Tr_{H}(\\rho))$ for two\nchannels $\\Phi $ and $\\Psi $ in Hilbert spaces $H$ and $K$,\nrespectively. We have proved the strong superadditivity\nconjecture for the quantum depolarizing channel in any dimensions.\n\n\n\\end {abstract}\n\n\\pacs {03.67.-a, 03.67.Hk}\n\n\\maketitle\n\n\\section {Introduction}\n\nA linear trace-preserving map $\\Phi $ on the set of states\n(positive unit-trace operators) $\\mathfrak{S}(H)$ in a Hilbert\nspace $H$ is said to be a quantum channel if $\\Phi ^{*}$ is\ncompletely positive (\\cite {Hol}). The channel $\\Phi $ is called\nbistochastic if $\\Phi (\\frac {1}{d}I_{H})=\\frac {1}{d}I_{H}$.\nHere and in the following we denote by $d$ and $I_{H}$ the\ndimension of $H,\\ dimH=d<+\\infty ,$ and the identity operator in\n$H$, respectively.\n\n\nGiven a quantum channel $\\Phi $ in a Hilbert space $H$ put (\\cite\n{Sh})\n\\begin {equation}\\label {quant}\n\\hat H_{\\Phi}(\\rho)=\\min \\limits _{\\rho _{av}=\\rho}\\sum \\limits\n_{j=1}^{k}\\pi _{j}S(\\Phi (\\rho _{j})),\n\\end {equation}\nwhere $\\rho _{av}=\\sum \\limits _{j=1}^{k}\\pi _{j}\\rho _{j}$ and\nthe minimum is taken over all probability distributions $\\pi\n=\\{\\pi _{j}\\}$ and states $\\rho _{j}\\in \\mathfrak{S}(H)$. Here\nand in the following $S(\\rho)=-Tr(\\rho\\log \\rho)$ is the von\nNeumann entropy of a state $\\rho $. The strong superadditivity\nconjecture states that\n\\begin {equation}\\label {strong}\n\\hat H_{\\Phi \\otimes \\Psi}(\\rho)\\ge \\hat\nH_{\\Phi}(Tr_{K}(\\rho))+\\hat H_{\\Psi}(Tr_{H}(\\rho)),\n\\end {equation}\n$\\rho \\in \\mathfrak{S}(H\\otimes K)$ for two channels $\\Phi $ and\n$\\Psi $ in Hilbert spaces $H$ and $K$, respectively. Start-ex.\n\n%%%%%%%%%%%%%%%%%INSERT HERE\n\n\n\\ea\\label{ex:culo:24}\n  \\ea \n\\textit{Aber Sie wissen nichts. \\textup{(GO\\_FICTION\\_007)}}\\\\\n  \\ex \n\\textit{But you don't know anything. \\textup{(ETrans\\_FICTION\\_007)}}\n  \\z\n\\z \n\n\n\\ea \\label{ex:culo:25}\n  \\ea \n\\textit{Die Frauen hat das nicht gerade zimperlich gemacht. \\textup{(GO\\_FICTION\\_007)}}\\\\\n   \\ex \\textit{The women weren't exactly prudes. \\textup{(ETrans\\_FICTION\\_007)}}\n   \\z\n\\z\n\n\n\\ea \\label{ex:culo:26}\n   \\ea\n\\textit{Wenn wir also in diesem Sinne unseren Interessen und Werten dienen wollen, dann   muss Europa erstens wachsam gegenüber den neuen Bedrohungen sein, denen die   freien und offenen Gesellschaften ausgesetzt sind. \\textup{(GO\\_SPEECH\\_010)}}\\\\\n   \\ex \n   \\textit{So if we want to serve our interests and values in line with this definition, Europe must:   firstly, be vigilant to the new threats to which the free and open societies are exposed.   \\textup{(ETrans\\_SPEECH\\_010)}}\n   \\z\n\\z\n\n\n\n\n\\ea \\label{ex:culo:27}\n     \\ea \\textit{Every country has its own political issues and this makes resolution of our disputes increasingly difficult.} (EO\\_SPEECH\\_009)\\\\\n      \\ex \\textit{Jedes Land hat seine eigenen politischen Anliegen, wodurch die Streitschlichtung zunehmend erschwert wird.} (GTrans\\_SPEECH\\_009) \n      \\z\n\\z\n\n\n\n\\ea \\label{ex:culo:28}\n   \\ea \\textit{And if the EU does as it has in the past, and provides financing to Airbus at below-  market rates of return, we could be facing a very large and highly contentious fight in the WTO.} (EO\\_SPEECH\\_009)\\\\\n    \\ex \\textit{Und wenn die EU sich wie in der Vergangenheit verhält und dem Airbus Finanzierung zu Zinssätzen unter den auf dem Markt gültigen bietet, könnte uns ein großer und sehr kontroverser Kampf in der WTO bevorstehen.} (GTrans\\_SPEECH\\_009) \n    \\z\n\\z\n\n\n\n%%%%%%%%%%%%END INSERT\n\n\n\n\nThe infimum of the output entropy of a quantum channel $\\Phi $ is\ndefined by the formula\n\\begin {equation}\\label {addit}\nS_{min}(\\Phi)=\\inf \\limits _{\\rho\\in \\mathfrak{S}(H)}S(\\Phi\n(\\rho)).\n\\end {equation}\nThe additivity conjecture for the quantity $S_{min} (\\Phi)$ states\n(\\cite {Hol2})\n\\begin {equation}\\label {conj}\nS_{min} (\\Phi\\otimes \\Psi)=S_{min} (\\Phi)+S_{min} (\\Psi)\n\\end {equation}\nfor an arbitrary quantum channel $\\Psi $. It was shown in (\\cite\n{Sh}) that if the strong superadditivity conjecture holds, then\nthe additivity conjecture for the quantity $S_{min}$ holds too.\nNevertheless the conjecture (\\ref {strong}) is stronger than\n(\\ref {addit}).\n\nIn the present paper we shall prove the strong superadditivity\nconjecture for the quantum depolarizing channel for all dimensions\nof $H$.\n\n\n\\section {The estimation of the output entropy}\n\n\nOur approach is based upon the estimate of the output entropy\nproved in \\cite {C02}. Combining formulae (111) and (112) in\n\\cite {C02} we get the lemma formulated below.\n\n{\\bf Lemma.}{\\it Let $\\Phi _{dep}(\\rho)=(1-p)\\rho+\\frac\n{p}{d}I_{H},\\ \\rho\\in \\mathfrak{S} (H),\\ 0\\le p\\le \\frac\n{d^{2}}{d^{2}-1},$ be the quantum depolarizing channel in the\nHilbert space $H$ of the dimension $d$. Then, for any quantum\nchannel $\\Psi $ there exist the orthonormal basis $\\{e_{s},\\ 1\\le\ns\\le d\\}$ in $H$ and $d$ states $\\rho_{s}\\in \\mathfrak {S}(K),\\\n1\\le s\\le d,$ such that\n\\begin {equation}\\label {XJ}\nS((\\Phi _{dep}\\otimes \\Psi)(\\rho))\\ge -(1-\\frac {d-1}{d}p)\\log\n(1-\\frac {d-1}{d}p)-\n\\end {equation}\n$$\n\\frac {d-1}{d}p\\log \\frac {p}{d}+ \\frac {1}{d}\\sum \\limits\n_{s=1}^{d}S(\\Psi (\\rho_{s}))\n$$\nand\n$$\n\\frac {1}{d}\\sum \\limits _{s=1}^{d}\\rho _{s}=Tr_{H}(\\rho ),\n$$\nwhere $\\rho\\in \\mathfrak{S} (H\\otimes K),\\\n\\rho_{s}=dTr_{H}((|e_{s}><e_{s}|\\otimes I_{K})\\rho)\\in \\mathfrak\n{S} (K),\\ 1\\le s\\le d$. }\n\n\n\n\nIn the present paper our goal is to prove the following theorem.\n\n\n{\\bf Theorem.}{\\it Let $\\Phi _{dep}$ be the quantum depolarizing\nchannel in the Hilbert space of the dimension $d$. Then, for an\narbitrary quantum channel $\\Psi $ in a Hilbert space $K$ the\nstrong superadditivity conjecture holds, i.e.\n\\begin {equation}\\label {theorem}\n\\hat H_{\\Phi _{dep}\\otimes \\Psi}(\\rho)\\ge \\hat H_{\\Phi\n_{dep}}(Tr_{K}(\\rho))+\\hat H_{\\Psi}(Tr_{H}(\\rho)).\n\\end {equation}\n}\n\n\nProof.\n\n\n\nSuppose that\n\\begin {equation}\\label {avr}\n\\rho =\\sum \\limits _{j=1}^{k}\\pi _{j}\\rho _{j}\n\\end {equation}\nand the states $\\rho _{j},\\ 1\\le j\\le k,$ form the optimal\nensemble for (\\ref {quant}) in the sense that\n\\begin {equation}\\label {avr2}\n\\hat H_{\\Phi _{dep}\\otimes \\Psi}(\\rho)=\\sum \\limits _{j} \\pi\n_{j}S((\\Phi _{dep}\\otimes \\Psi)(\\rho _{j}))\n\\end {equation}\nApplying (\\ref {XJ}) to each element of the sum in (\\ref {avr2})\nwe get\n\\begin {equation}\\label {A1}\n\\hat H_{\\Phi _{dep}\\otimes \\Psi}(\\rho)\\ge -(1-\\frac\n{d-1}{d}p)\\log (1-\\frac {d-1}{d}p)-\n\\end {equation}\n$$\n\\frac {d-1}{d}p\\log \\frac {p}{d}+\\frac {1}{d}\\sum \\limits\n_{j=1}^{k}\\pi _{j}\\sum \\limits _{s=1}^{d}S(\\Psi (\\rho_{js})),\n$$\nwhere $\\rho_{js}=dTr_{H}((|e_{js}><e_{js}|\\otimes I_{K})\\rho\n_{j})\\in \\mathfrak {S} (K),\\ 1\\le j\\le d$, and each the set\n$\\{e_{js},\\ 1\\le s\\le d\\}$ forms the orthonormal basis of $H$ for\n$1\\le j\\le k$.\n\n\n\nIt follows from Lemma that\n\\begin {equation}\\label {Sup1}\n\\frac {1}{d}\\sum \\limits _{j=1}^{k}\\pi _{j}\\sum \\limits\n_{s=1}^{d}\\Psi (\\rho_{js})=\\sum \\limits _{j=1}^{k}\\pi _{j}\\Psi (\nTr_{H}(\\rho _{j}))=\\Psi (Tr_{H}(\\rho)).\n\\end {equation}\nThe equality (\\ref {Sup1}) results in\n\\begin {equation}\\label {E2}\n\\frac {1}{d}\\sum \\limits _{j=1}^{k}\\pi _{j}\\sum \\limits\n_{s=1}^{d}S(\\Psi (\\rho_{js}))\\ge \\hat H_{\\Psi}(Tr_{H}(\\rho)).\n\\end {equation}\nNotice that the quantity (\\ref {quant}) is always bounded from\nbelow by the quantity (\\ref {addit}). For the quantum\ndepolarizing channel $\\Phi _{dep}$ (\\ref {quant}) coincides with\n(\\ref {addit}) for any state because (\\ref {addit}) is achieved on\nany pure input state due to the covariance property of $\\Phi\n_{dep}$. Thus, we get\n\\begin {equation}\\label {E3}\n\\hat H_{\\Phi _{dep}}(\\rho)=-(1-\\frac {d-1}{d}p)\\log (1-\\frac\n{d-1}{d}p)-\n\\end {equation}\n$$\n\\frac {d-1}{d}p\\log \\frac {p}{d}=S_{min} (\\Phi _{dep})\n$$\nfor any state $\\rho \\in \\mathfrak {S}(H)$. Taking into account\n(\\ref {A1}),(\\ref {E2}) and (\\ref {E3}) we get\n$$\n\\hat H_{\\Phi _{dep}\\otimes \\Psi}(\\rho)\\ge \\hat H_{\\Phi _{dep}\n}(Tr_{K}(\\rho))+\\hat H_{\\Psi}(Tr_{H}(\\rho)),\n$$\n$\\rho \\in \\mathfrak{S}(H\\otimes K).$ Thus, the strong\nsuperadditivity conjecture for the quantum depolarizing channel\nis proved.\n\n\n\n$\\Box $\n\n\\section {Conclusion}\n\nAt the first time the additivity conjecture (\\ref {conj}) for the\nquantum depolarizing channel was proved in \\cite {C02}. The method\nwas based upon the estimation of $l_{p}$-norms of the channel. On\nthe other hand in the papers \\cite {Amo, Amo1, Amo2} it was shown\nthat the decreasing property of the relative entropy also can be\nused to prove the additivity conjecture for some partial cases at\nleast. In the present paper we have proved that the estimation of\nthe output entropy obtained in \\cite {C02} allows to prove the\nstrong superadditivity conjecture (\\ref {strong}) for the quantum\ndepolarizing channel. One of a possible basis for considering the\nstrong superadditivity conjecture can be drawn from the paper\n\\cite {Sh}. There was presented the proof of the global\nequivalence of the additivity conjecture for the constrained\nchannels and the strong superadditivity conjecture.\n\n\n\\section*{Acknowledgments}\n\nThe author is grateful to M.E. Shirokov for an inspiration of this\nwork and many fruitful discussions. The work is partially\nsupported by intas grant Ref. Nr. 06-1000014-6077.\n\n\n\\begin {thebibliography}{99}\n\n\\bibitem {Amo} Amosov G.G. Remark on the additivity conjecture for\nthe depolarizing quantum channel. Probl. Inf. Transm. 42 (2006)\n3-11; e-print quant-ph/0408004.\n\n\\bibitem {Amo1} Amosov G.G. On the Weyl  channels being covariant\nwith respect to the maximum commutative group of unitaries. J.\nMath. Phys. 48 (2007); e-print quant-ph/0605177 v.3.\n\n\n\\bibitem {Amo2} Amosov G.G. On the additivity conjecture for the\nWeyl channels being covariant with respect to the maximum\ncommutative group of unitaries. e-print quant-ph/0606040 v.3.\n\n\n\\bibitem {AHW} Amosov G.G., Holevo A.S., Werner R.F. On some additivity problems in\nquantum information theory.  Probl. Inf. Transm. 2000. V. 36. N 4.\nP. 24-34; e-print quant-ph/0003002.\n\n\\bibitem {Ruskai} Datta N, Ruskai M.B. Maximal output purity and capacity for asymmetric unital qudit channels\nJ. Physics A: Mathematical and General 38 (2005) 9785-9802.\ne-print quant-ph/0505048.\n\n\\bibitem {Fukuda} Fukuda M., Holevo A.S. On Weyl-covariant\nchannels. e-print quant-ph/0510148.\n\n\n\\bibitem {Hol} Holevo A.S. On the mathematical theory of quantum communication\nchannels. Probl. Inf. Transm. 8 (1972) 62 - 71.\n\n\\bibitem {Hol1} Holevo A.S. Some estimates for the amount of information\ntransmittable by a quantum communications channel. (Russian)\nProbl. Inf. Transm. 9 (1973) 3 - 11.\n\n\\bibitem {Hol2} Holevo A.S. Quantum coding theorems. Russ.\nMath. Surveys 53 (1998) 1295-1331; e-print quant-ph/9808023.\n\n\n\\bibitem {Sh} Holevo A.S., Shirokov M.E. On Shor's channel\nextension and constrained channels. Commun. Math. Phys. 249\n(2004) 417-436.\n\n\\bibitem {Ivan} Ivanovich I.D. Geometrical description of quantum state\ndetermination. J. Physics A 14 (1981) 3241-3245.\n\n\n\\bibitem {Cerf} Karpov E., Daems D., Cerf N.J. Entanglement\nenhanced classical capacity of quantum communication channels\nwith correlated noise in arbitrary dimensions. e-print\nquant-ph/0603286.\n\n\n\\bibitem{C02} King C. The capacity of the quantum depolarizing\nchannel // IEEE Trans. Inform. Theory. - 2003. - V. 49, N 1. - P.\n221-229; e-print quant-ph/0204172.\n\n\n\n\n\\end {thebibliography}\n\n\\end {document}\n", "meta": {"hexsha": "8061e10282b5e9175f956228f6eeff29f00f116f", "size": 12240, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "benchmark/src/with-lang/working/0707.1097-ger-ex.tex", "max_stars_repo_name": "e-sim/pdf-text-extraction-benchmark", "max_stars_repo_head_hexsha": "42eede9867e5795a6fc040b0a7ce92da3ddd3120", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-08-23T19:07:01.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-23T19:07:01.000Z", "max_issues_repo_path": "benchmark/src/with-lang/working/0707.1097-ger-ex.tex", "max_issues_repo_name": "e-sim/pdf-text-extraction-benchmark", "max_issues_repo_head_hexsha": "42eede9867e5795a6fc040b0a7ce92da3ddd3120", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmark/src/with-lang/working/0707.1097-ger-ex.tex", "max_forks_repo_name": "e-sim/pdf-text-extraction-benchmark", "max_forks_repo_head_hexsha": "42eede9867e5795a6fc040b0a7ce92da3ddd3120", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1899441341, "max_line_length": 250, "alphanum_fraction": 0.6954248366, "num_tokens": 4200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3231331358716827}}
{"text": "%\n% set up at March 31th, 2009\n%\n%\n%\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\chapter{Perturbation treatment for the time-dependent systems}\n\\label{perturbation_in_time}\n%\n%  what's the perturbation treatment for the time-dependent system?\n%  quantum transition is mostly important\n%  zero order and first order expression\n%\nIn quantum mechanics, the study related to the quantum states can be\ndivided into two groups:\n\\begin{itemize}\n  \\item the possible states for describing the system\n  \\item the quantum system evolves with time\n\\end{itemize}\n\nIn the first case, all the study concentrate on the eigen states and\neigen values. For the specific system, we choose its CSCCO and\nevaluate the corresponding eigen states. By using such eigen states,\nwe can figure out any physical quantity, obviously such physical\nquantity should be time independent; such as the dipole moments for\nthe molecule.\n\nFor the second case, nearly all the study concentrate on the\nperturbation treatment for the time dependent system. In practice,\nit's usually impossible to derive the general form for the evolution\nof wave functions as time varies. Instead, to determine the quantum\ntransition probabilities is much more important in practical\napplication. For example, in the photochemistry to determine the\nexcitation energy level due to some perturbed radiation, or in the\nUV spectrum to determine the ultraviolet spectrum intensity. they\nare all related to the transition probability between two quantum\nstates. therefore, we usually express the time dependent part as\nsome ``perturbed'' operator:\n\\begin{equation}\\label{}\n\\hat{H} = \\hat{H}_{0} + \\hat{H}^{'}(t)\n\\end{equation}\nSo we calculate the response of the wave functions to this perturbed\noperator by progressively expanding it as:\n\\begin{align}\\label{}\n\\hat{H} &= \\hat{H}_{0} + \\lambda\\hat{H}^{'}(t) \\nonumber \\\\\n\\Psi(r,t) &= \\Psi^{(0)}(r) + \\lambda\\Psi^{(1)}(r,t) +\n\\lambda^{2}\\Psi^{(2)}(r,t) + \\cdots\n\\end{align}\n\nFor the $\\hat{H}_{0}$, we can calculate its eigen states. Suggest\nthat such eigen states for the $\\hat{H}_{0}$ are labeled as\n$\\psi_{i}(r)$ ($i=1,2,\\cdots$) so that for the zero order\napproximation, an arbitrary state of $\\Psi^{(0)}(r)$ can be\nexpressed as:\n\\begin{equation}\\label{}\n\\Psi^{(0)}(r) = \\sum_{i}a_{i}^{(0)}\\psi_{i}(r)\n\\end{equation}\nHere the $\\Psi^{(0)}(r)$ can be any states for the $\\hat{H}_{0}$.\nHowever, in practical application the system usually resides in the\nground state for the $\\hat{H}_{0}$; so here we can extent this\ncondition by requiring that:\n\\begin{equation}\\label{}\n\\Psi^{(0)}(r) = \\psi_{k}(r)\n\\end{equation}\nSo the initial state for the system is assumed in $\\ket{k}$ state.\nTherefore, for the zero order approximation we have:\n\\begin{equation}\\label{PTFTDSeq:4}\na_{i}^{(0)} = \\delta_{ik}\n\\end{equation}\n\nAs the perturbation of $\\hat{H}^{'}(t)$ is switched on at $t > 0$,\nthe original eigen states will be broken down; instead the new\nstates will be the linear combination of the original states (see\nthe discussion in \\ref{SE:5}):\n\\begin{equation}\\label{PTFTDSeq:1}\n\\Psi(r,t) = \\sum_{i}a_{i}(t)\\psi_{i}(r)e^{-iE_{i}t/\\hbar}\n\\end{equation}\nHere the coefficients of $a_{i}$ should be time dependent.\nFurthermore, in (\\ref{PTFTDSeq:1}) the wave function is no longer\nthe eigen states for Hamiltonian anymore, the new state will be\npartially in state $\\psi_{i}$ or partially in state $\\psi_{j}$,\nwhich is decided by the coefficient of $a_{i}$, it is in turn\ninfluenced by the time of $t$.\n\nIn perturbation treatment, now we can expand the $\\Psi(r,t)$ as well\nas the coefficients of $a_{i}(t)$ in order of $\\lambda$. however,\nlet's firstly bring the (\\ref{PTFTDSeq:1}) into the Schrodinger\nequation to see the general form:\n\\begin{equation}\\label{}\ni \\hbar \\frac{\\partial \\Psi(r,t)}{\\partial t} = (\\hat{H}_{0} +\n\\hat{H}^{'}(t))\\Psi(r,t)\n\\end{equation}\nWhich it yields:\n\\begin{multline}\\label{}\n\\sum_{i}i\\hbar \\psi_{i}(r)e^{-iE_{i}t/\\hbar}\\frac{\\partial\na_{i}(t)}{\\partial t} +\n\\sum_{i}a_{i}(t)E_{i}\\psi_{i}(r)e^{-iE_{i}t/\\hbar} = \\\\\n\\sum_{i}a_{i}(t)E_{i}\\psi_{i}(r)e^{-iE_{i}t/\\hbar} +\n\\sum_{i}a_{i}(t)e^{-iE_{i}t/\\hbar}\\hat{H}^{'}(t)\\psi_{i}(r)\n\\end{multline}\n\nThen we can drop the some terms in the above equation to make it to\nbe:\n\\begin{equation}\\label{}\n\\sum_{i}i\\hbar \\psi_{i}(r)e^{-iE_{i}t/\\hbar}\\dot{a}_{i}(t) =\n\\sum_{i}a_{i}(t)e^{-iE_{i}t/\\hbar}\\hat{H}^{'}(t)\\psi_{i}(r)\n\\end{equation}\nBy using the orthogonal condition (whatever we can always get some\northogonal sets) for the $\\psi_{i}(r)$, we can multiply both side of\nthe equation with $\\bra{\\psi_{j}(r)}$:\n\\begin{align}\\label{PTFTDSeq:2}\ni\\hbar e^{-iE_{j}t/\\hbar}\\dot{a}_{j}(t) &=\n\\sum_{i}a_{i}(t)e^{-iE_{i}t/\\hbar}\\hat{H}^{'}_{ji}\n \\quad \\underrightarrow{e^{iE_{j}t/\\hbar}}\\nonumber \\\\\ni\\hbar \\dot{a}_{j}(t) &= \\sum_{i}a_{i}(t)e^{-i\\omega_{ij}\nt}\\hat{H}^{'}_{ji}\n\\end{align}\nHere we have $\\omega_{ij}$ as:\n\\begin{equation}\\label{}\n\\omega_{ij} = \\frac{E_{i} - E_{j}}{\\hbar}\n\\end{equation}\n\nFor the first order perturbation, where we can express the first\norder correlated wave function as:\n\\begin{equation}\\label{}\n\\Psi^{(1)}(r,t) =\n\\sum_{i}a^{(1)}_{i}(t)\\psi_{i}(r)e^{-iE_{i}t/\\hbar}\n\\end{equation}\nSo now it's easy to transform the (\\ref{PTFTDSeq:2}) into the first\norder equation:\n\\begin{equation}\\label{PTFTDSeq:3}\ni\\hbar \\dot{a}^{(1)}_{j}(t) = \\sum_{i}a^{(0)}_{i}(t)e^{-i\\omega_{ij}\nt}\\hat{H}^{'}_{ji}\n\\end{equation}\nHere it's worthy to note that the $\\hat{H}^{'}$ already has the\norder of $\\lambda$ so that the coefficients of $a_{i}(t)$ should be\nin zero order on the right side of (\\ref{PTFTDSeq:3}). Furthermore,\nby using the relation in the (\\ref{PTFTDSeq:4}) where $a_{i}^{(0)} =\n\\delta_{ik}$; we can finally get:\n\\begin{equation}\\label{PTFTDSeq:5}\ni\\hbar \\dot{a}^{(1)}_{j}(t) = e^{-i\\omega_{kj} t}\\hat{H}^{'}_{jk}\n\\end{equation}\nHere the label of $k$ indicates that the system is originally in the\n$\\ket{k}$ state. by integrating the (\\ref{PTFTDSeq:5}), it gives:\n\\begin{equation}\\label{}\na^{(1)}_{j}(t) = -\\frac{i}{\\hbar}\\int_{0}^{t}\n\\hat{H}^{'}_{jk}e^{-i\\omega_{kj} t}dt\n\\end{equation}\n\nFor the (\\ref{PTFTDSeq:6}), now in this equation we have two index:\n$j$ and $k$. $k$ indicates the original state, while $j$ stands for\nthe component for $\\ket{j}$ in the first order correlated wave\nfunctions. Hence it's better to express the $a^{(1)}_{j}(t)$ as two\nindices $a^{(1)}_{kj}(t)$:\n\\begin{equation}\\label{PTFTDSeq:6}\na^{(1)}_{kj}(t) = -\\frac{i}{\\hbar}\\int_{0}^{t}\n\\hat{H}^{'}_{jk}e^{-i\\omega_{kj} t}dt\n\\end{equation}\nThis equation fixes the first order approximated wave function.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Periodic situation}\n%\n%\n%\nNow let's analyze some important situation where the perturbation\noperator can be expressed as periodic function of time\\cite{Landau}.\n\nIn this case, $\\hat{H}^{'}$ is:\n\\begin{equation}\\label{}\n\\hat{H}^{'}(t) = \\hat{F}e^{-i\\omega t} + \\hat{G}e^{i\\omega t}\n\\end{equation}\ntherefore we have $\\hat{H}^{'}(t) = \\hat{H}^{'}(t +\n\\frac{2k\\pi}{\\omega})$.\n\nHere the operator of $\\hat{F}$ and $\\hat{G}$ are time independent.\nSince that the $\\hat{H}^{'}$ is required to be some physical\nquantity, thus it's some hermite operator:\n\\begin{equation}\\label{}\n\\hat{F}e^{-i\\omega t} + \\hat{G}e^{i\\omega t} = \\hat{F}^{+}e^{i\\omega\nt} + \\hat{G}^{+}e^{-i\\omega t} \\Rightarrow \\hat{F} = \\hat{G}^{+}\n\\end{equation}\nThen for the $H^{'}_{jk}$, we have:\n\\begin{align}\\label{}\na^{(1)}_{kj}(t) &= -\\frac{i}{\\hbar}\\int_{0}^{t}\n\\left\\{\\hat{F}_{jk}e^{-i(\\omega_{kj}+\\omega) t} +\n\\hat{F}^{*}_{kj}e^{-i(\\omega_{kj}-\\omega) t}\\right\\}dt \\nonumber\n\\\\\n&=-\\frac{1}{\\hbar}\\bigg\\{\n\\frac{\\hat{F}_{jk}e^{-i(\\omega_{kj}+\\omega)t}} {\\omega_{kj}+\\omega}\n+ \\frac{\\hat{F}^{*}_{kj}e^{-i(\\omega_{kj}-\\omega)t}}\n{\\omega_{kj}-\\omega}\\bigg\\}\n\\end{align}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%%% Local Variables: \n%%% mode: latex\n%%% TeX-master: \"../../main\"\n%%% End: \n", "meta": {"hexsha": "f5cfbd7891e412ab22a1420996853ea3726432fa", "size": 8010, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "theory/physics/time_dependent.tex", "max_stars_repo_name": "murfreesboro/fenglai-note", "max_stars_repo_head_hexsha": "7bdf943f681e54948cd68775a31e4c93a53a13f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-16T07:23:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T07:23:48.000Z", "max_issues_repo_path": "theory/physics/time_dependent.tex", "max_issues_repo_name": "murfreesboro/fenglai-note", "max_issues_repo_head_hexsha": "7bdf943f681e54948cd68775a31e4c93a53a13f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "theory/physics/time_dependent.tex", "max_forks_repo_name": "murfreesboro/fenglai-note", "max_forks_repo_head_hexsha": "7bdf943f681e54948cd68775a31e4c93a53a13f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2647058824, "max_line_length": 94, "alphanum_fraction": 0.6558052434, "num_tokens": 2711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.32284210268905095}}
{"text": "\\section{Conclusion}\n\n\tFrom the results contains in this report:\n\t\n\t\\paragraph{} The \\textbf{Exact Method} (EM) for instance less or equal to 100 nodes remain the best choice. We get the optimal solution guaranteed in a reasonable amount of time. Anyway it's interesting to note that Exact Method with emulated real instances (\\verb|fb| instances) it takes more time to compute the solution. Finally in the real instances tested the use of this method require a large investment of resources (hardware, people and time).\n\t\n\t\\paragraph{} The \\textbf{Local Search} (LS) is extremely fast and its best use cases are in the real-time contexts. Also for small instances of nodes the LS isn't able to reach the optimum. Instead the \\textbf{Tabu Search} (TS) is a good trade-off, for small instances it found the optimal solution and also in instance with about 500 nodes it performs well, in my opinion time limits parameter is a nice feature. TS limitation starts when we use it on real instances. Here the calibration require more effort, code optimizations are needed and a higher maximum time need to be set. Both LS and TS could use the parallel computation in order to reduce the times.\n\t\n\t\\paragraph{Domain considerations} About the possible domains I think that EM could be used only if the build of the board are huge and the production of the same board last for month or year. In this case an optimal solution guarantees a big saving. Otherwise in the context where the production of boards are limited in time and in quantity the EM is not the best choice, in my opinion here a Tabu Search is the best choice.\n\t\n\tAnother example where meta heuristics methods are a better choice is for test board, still in developing phase. In this case the production is limited to some prototype and also a Local Search is sufficient. \n\t\n\tAnother important factor is that for the use EM it is needed an expensive license for CPLEX. It is a remarkable disadvantage, mostly for small companies.\n\t\n\t\\paragraph{} Finally I want to do a last consideration a bit out of the assignment, I want to thank my colleagues that gives me useful tools, advices and discussions. I believe that the collaboration is another essential \"feature\" in order to tackle these problems.\n\n\t\t\n\t", "meta": {"hexsha": "2dc8ad92dbe4e4ddb2e853409cd91e4023264725", "size": 2259, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "sections/conclusion.tex", "max_stars_repo_name": "EduBic/TSP-MetaheuristicSolvers-Documentation", "max_stars_repo_head_hexsha": "2c6952f5ad5afbd5469b4223311be5781073c953", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-02-15T13:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-12T14:10:08.000Z", "max_issues_repo_path": "sections/conclusion.tex", "max_issues_repo_name": "EduBic/TSP-MetaheuristicSolvers-Documentation", "max_issues_repo_head_hexsha": "2c6952f5ad5afbd5469b4223311be5781073c953", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sections/conclusion.tex", "max_forks_repo_name": "EduBic/TSP-MetaheuristicSolvers-Documentation", "max_forks_repo_head_hexsha": "2c6952f5ad5afbd5469b4223311be5781073c953", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 125.5, "max_line_length": 663, "alphanum_fraction": 0.789729969, "num_tokens": 477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199306096344, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.32284209762102123}}
{"text": "\\documentclass[bigger]{beamer}\n\n\\input{header-beam} % change to header-handout for handouts\n\n% ====================\n\\title[Lecture 4]{Logic I F13 Lecture 4}\n\\date{September 19, 2013}\n% ====================\n\n\\include{header}\n\n\\section[Boolean Connectives]{The Boolean Connectives}\n\n\\subsec{The Boolean Connectives}{\n\n\\bit\n\\item Negation (``not''): $\\lnot$\n\\item Conjunction (``and''): $\\land$\n\\item Disjunction (inclusive ``or''): $\\lor$\n\\eit\n\n}\n\n\\subsec{Sentences of FOL}{\n\n\\bit\n\\item Every atomic sentence is a sentence (duh!)\n\\item If $P$ is a sentence, then $\\lnot P$ is a sentence as well.\n\\bit\n\\item Note: no parentheses\n\\item Instead of $\\lnot a = b$ we write $a \\neq b$\n\\eit\n\\item If $P$ and $Q$ are sentences, then so are\\\\\n$(P \\land Q)$ and $(P \\lor Q)$\n\\bit\n\\item Note parentheses\n\\item But: we will leave off the outermost parentheses\n\\eit\n\\eit\n}\n\n\\subsec{Constructing Sentences}{\n\n\\bits\n\\item $\\sf Large(a)$, $\\sf Cube(a)$, $\\sf a = b$\n\\item $\\sf \\lnot Large(a)$, $\\sf \\lnot Cube(a)$, $\\sf a \\neq b$\n\\item $\\sf \\lnot\\lnot Large(a)$, $\\sf \\lnot\\lnot\\lnot Large(a)$, \\dots\n\\item $\\sf (Cube(a) \\land \\lnot Large(a))$\n\\item $\\sf ((Cube(a) \\lor Tet(a)) \\land \\lnot(Large(a) \\lor Medium(a)))$\\\\\n\\dots\n\\eit\n}\n\n\\subsec{Ill-formed Expressions}{\n\nExamples of expressions that are \\emph{not} sentences:\n\\bit\n\\item $\\sf \\lnot (a = b)$\n\\item $\\sf Cube(a \\land b)$\n\\item $\\sf Cube(\\lnot a)$\n\\item $\\sf Large(Cube(a))$\n\\item $\\sf Cube(a) \\lor Small(a) \\land LeftOf(a, c)$\n\\item $\\sf (Large \\land Cube)(a)$\n\\item \n\\eit\n\n}\n\n\\subsec{Semantics of the Boolean Connectives}{\n\n\\bit\n\\item Atomic sentences $P(a)$ are true or false according to whether the object named by $a$ has the determinate property assigned to $P$\n\\item Non-atomic sentences are true or false according to \n\\bit\n\\item what the \\emph{main connective} is (*)\n\\item the truth values of the \\emph{immediate subsentences} ($P$, $Q$)\n\\item the \\emph{truth table} for the main connective\n\\eit\n\\eit\n\\begin{align*}\n\\underbrace{(Cube(a) \\lor Tet(a))}_P \\underbrace{\\land}_\\text{*} \\underbrace{\\lnot(Large(a) \\lor Medium(a))}_Q \\\\\n\\underbrace{\\lnot}_*\\underbrace{(Large(a) \\lor Medium(a))}_P\n\\end{align*}\n\n}\n\n\\subsec{Truth Tables for the Boolean Connectives}{\n\n\\[\n\\begin{array}{c|c}\nP & \\lnot P\\\\\n\\hline\n\\T & \\F \\\\\n\\F & \\T\n\\end{array}\n\\qquad\n\\begin{array}{cc|c}\nP & Q & (P \\land Q)\\\\\n\\hline\n\\T & \\T & \\T\\\\\n\\T & \\F & \\F\\\\\n\\F & \\T & \\F\\\\\n\\F & \\F & \\F\n\\end{array}\n\\qquad\n\\begin{array}{cc|c}\nP & Q & (P \\lor Q)\\\\\n\\hline\n\\T & \\T & \\T\\\\\n\\T & \\F & \\T\\\\\n\\F & \\T & \\T\\\\\n\\F & \\F & \\F\n\\end{array}\n\\]\n\n}\n\n\\subsec{Truth Conditions of Sentences}{\n\n\\bit\n\\item $\\lnot P$ is \n\\bit \n\\item true iff $P$ is false\n\\item false iff $P$ is true\n\\eit\n\\item $P \\land Q$ is \n\\bit\n\\item true iff $P$ and $Q$ are both true\n\\item false iff at least one of $P$, $Q$ is false\n\\eit\n\\item $P \\lor Q$ is \n\\bit\n\\item true iff at least one of $P$, $Q$ is true\n\\item false iff $P$ and $Q$ are both false\n\\eit\n\\eit\n}\n\n\\section{English and FOL}\n\n\\subsec{Negation}{\n\n\\bit\n\\item To negate a sentence, you use ``isn't'' or ``doesn't'':\n\\bit\n\\item b is a cube --- b \\emph{isn't} a cube\n\\item a adjoins b --- a \\emph{doesn't} adjoin b\n\\eit\n\\item You can prefix a sentence by ``it isn't the case that'':\n\\bit\n\\item a adjoins b --- \\emph{it isn't the case that} a adjoins b\n\\eit\n\\item ``neither \\dots nor \\dots''\n\\bit\n\\item \\emph{Neither a nor b} is a cube.\n\\eit\n\\eit\n}\n\n\\subsec{Coordination}{\n\n\\bit\n\\item Can combine names, verbs, adjectives, nouns, even whole clauses using ``conjunctions'' (and, or, yet, but, neither, \\dots)\n\\bit\n\\item \\emph{a and b} are cubes.\n\\item a \\emph{equals and adjoins} b.\n\\item a is \\emph{large or small}.\n\\item a is a \\emph{tetrahedron or dodecahedron}.\n\\item a is a cube \\emph{and} b is a tetrahedron.\n\\item a and b are left of c and d, but e is not left of c or not left of d.\n\\item a and b are large cubes both of which adjoin c.\n\\eit\n\\eit\n\n}\n\n\n\\subsec{English into FOL}{\n\n\\bit\n\\item a adjoins b --- a \\emph{doesn't} adjoin b\\\\\n$\\sf Adjoins(a, b)$ --- $\\sf\\lnot Adjoins(a, b)$\n\\item \\emph{a and b} are cubes.\\\\\n$\\sf Cube(a) \\land Cube(b)$\n\\item a \\emph{is left of and adjoins} b.\\\\\n$\\sf LeftOf(a, b) \\land Adjoins(a, b)$ \n\\item a is \\emph{large or small}.\\\\\n$\\sf Large(a) \\lor Small(a)$\n\\item a is a \\emph{tetrahedron or dodecahedron}.\\\\\n$\\sf Tet(a) \\lor Dodec(a)$\n\\item a is a cube \\emph{but} b is a tetrahedron.\\\\\n$\\sf Cube(a) \\land Tet(b)$\n\\eit\n}\n\n\n\n\\section[Expressive Power]{Expressive Power of the Boolean Connectives}\n\n\\subsec{Neither \\dots nor \\dots}{\n\n\\bits\n\\item Neither a nor b is a cube\n\\item $\\sf \\lnot Cube(a) \\land \\lnot Cube(b)$\n\\item $\\sf \\lnot (Cube(a) \\lor Cube(b))$\n\\eit\n\n}\n\n\\subsec{Not Both}{\n\n\\bits\n\\item a and b are not both large\n\\item $\\sf \\lnot(Large(a) \\land Large(b))$\n\\item $\\sf \\lnot Large(a) \\lor \\lnot Large(b)$\n\\eit\n\n}\n\n\\subsec{Exclusive ``Or''}{\n\n\\bits\n\\item a or b is a cube (but not both)\n\\item $\\sf (Cube(a) \\lor Cube(b)) \\land \\lnot(Cube(a) \\land Cube(b))$\n\\item $\\sf (Cube(a) \\land \\lnot Cube(b)) \\lor (\\lnot Cube(a) \\land Cube(b))$\n\\eit\n}\n\n\\subsec{At Least One Of}{\n\n\\bits\n\\item At least one of a, b, and c is small\n\\item $\\sf Small(a) \\lor Small(b) \\lor Small(c)$\n\\eit \n\n}\n\n\\subsec{At Least One Of}{\n\n\\bits\n\\item At least two of a, b, and c are small\n\\item $\\sf (Small(a) \\land Small(b)) \\lor (Small(a) \\land Small(c)) \\lor (Small(b) \\land Small(c))$\n\\eit \n\n}\n\n\\subsec{At Least As Large As and $\\le$}{\n\n\\bits\n\\item a is at least as large as b\n\\item $\\sf Larger(a, b) \\lor SameSize(a, b)$\n\\item $\\sf \\lnot Smaller(a, b)$, $\\sf\\lnot Larger(b, a)$\n\\item $2 \\le 3$\n\\item $(1+1) < (1+(1+1)) \\lor (1+1) = (1+(1+1))$\n\\item $\\lnot (1 + (1+1)) < (1+1)$ \n\\eit\n\n}\n\n\\end{document} %got to here\n\n\\section{Step-by-Step Translations}\n\n\\subsec{Step-by-Step Method of Translation}{\n\n\\bit\n\\item a and b are left of c or right of d, \\emph{but}\\\\ e is neither left of c nor right of d.\n\\bit\n\\item a and b are left of c or right of d\n\\item but\n\\item e is neither left of c nor right of d\n\\eit\\eit\n}\n\n\\subsec{Step-by-Step Method of Translation}{\n\n\\bits\n\\item a \\emph{and} b are left of c or right of d\n\\bit\n\\item a is left of c \\emph{or} right of d\n\\bit\n\\item a is left of c or a is right of d\\\\\n$\\sf LeftOf(a, c) \\lor RightOf(a, d)$\n\\eit\n\\item b is left of c \\emph{or} right of d\n\\bit\n\\item b is left of c or b is right of d\\\\\n$\\sf LeftOf(b, c) \\lor RightOf(b, d)$\n\\eit\n\\eit\n\\eit\n\\begin{align*}\n(LeftOf(a, c) \\lor {} & RightOf(a, d)) \\land {}\\\\\n(LeftOf(b, c) \\lor {} & RightOf(b, d))\n\\end{align*}\n\n}\n\n\\subsec{Step-by-Step Method of Translation}{\n\n\\bits\n\\item e is neither left of c nor right of d\n\\[\\sf \\lnot(LeftOf(e, c) \\lor RightOf(e, d))\\]\n\\eit\n}\n\n\\subsec{Step-by-Step Method of Translation}{\n\n\\bit\n\\item a and b are left of c or right of d, but\\\\ e is neither left of c nor right of d.\n\\bit\n\\item a and b are left of c or right of d\n\\begin{align*}\n(LeftOf(a, c) \\lor {} & RightOf(a, d)) \\land {}\\\\\n(LeftOf(b, c) \\lor {} & RightOf(b, d))\n\\end{align*}\n\\item but\n$\\land$\n\\item e is neither left of c nor right of d\n\\[\\sf \\lnot(LeftOf(e, c) \\lor RightOf(e, d))\\]\n\\eit\\eit\n\\begin{multline*}\n((LeftOf(a, c) \\lor RightOf(a, d)) \\land {} \\\\\n(LeftOf(b, c) \\lor RightOf(b, d))) \\land {}\\\\\n\\lnot(LeftOf(e, c) \\lor RightOf(e, d))\n\\end{multline*}\n\n}\n\n\n\n\\section{Ambiguity}\n\n\\subsec{Ambiguity in English}{\n\n\\bit\n\\item Lexical ambiguity: one word---many meanings \\\\\ne.g., ``bank'', ``crane''\n\\item Syntactic ambiguity: one sentence---many readings\\\\\ne.g., ``Flying planes can be dangerous''\n\\eit\n\n}\n\n\\subsec{Connectives and Ambiguity}{\n\n\\bits\n\\item a adjoins b and c or d\n\\item a adjoins [[b and c] or d]\\\\\n$\\sf (Adjoins(a, b) \\land Adjoins(a, c)) \\lor Adjoins(a, d)$\n\\item a adjoins [b and [c or d]]\\\\\n$\\sf Adjoins(a, b) \\land (Adjoins(a, c) \\lor Adjoins(a, d))$\n\\eit\n\n}\n\n\\subsec{The Man Who Was Hanged by a Comma}{\n\n\\bit\n\\item Sir Roger Casement (1864--1916)\n\\item British consul to Congo and Peru\n\\item Tried to recruit Irish revolutionaries in Germany during WWI\n\\item Tried for treason\n\\eit\n\n}\n\n\\subsec{Treason Act of 1351}{\n\n\\small \nITEM, Whereas divers Opinions have been before this Time in what Case\nTreason shall be said, and in what not; the King, at the Request of\nthe Lords and of the Commons, hath made a Declaration in the Manner as\nhereafter followeth, that is to say; When a Man doth compass or\nimagine the Death of our Lord the King, or of our Lady his Queen or of\ntheir eldest Son and Heir; or if a Man do violate the King’s\nCompanion, or the King’s eldest Daughter unmarried, or the Wife of the\nKing’s eldest Son and Heir; or \\textbf{if a Man do levy War against our Lord\nthe King in his Realm, or be adherent to the King’s Enemies in his\nRealm, giving to them Aid and Comfort in the Realm, or elsewhere}, and\nthereof be probably attainted of open Deed by the People of their\nCondition: \\dots And it is to be\nunderstood, that in the Cases above rehearsed, that ought to be judged\nTreason which extends to our Lord the King, and his Royal Majesty:\n\\dots\n\n}\n\n\\subsec{R v. Casement in the Blocks Language}{\n\n\\bits\n\\item a is a cube in front of b, or a tetrahedron in front of b[,] or in back of b.\n\n\\item Without comma:\n\\begin{align*}\n(Cube(a) \\land {} & FrontOf(a, b)) \\lor {}\\\\\n(Tet(a) \\land {} & (FrontOf(a,\nb) \\lor BackOf(a, b)))\n\\end{align*}\n\\item With comma:\n\\begin{align*}\n(Cube(a) \\land {} & (FrontOf(a, b) \\lor BackOf(a, b))) \\lor {}\\\\\n(Tet(a) \\land {} & (FrontOf(a, b) \\lor BackOf(a, b))\n\\end{align*}\n\\eit\n}\n\n\n\n\n\\end{document}\n", "meta": {"hexsha": "daf09d53a65d3a3ead6f5744b47fb8d416193304", "size": 9403, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "279-lec04.tex", "max_stars_repo_name": "rzach/phil279", "max_stars_repo_head_hexsha": "722ec82ae7a4593d40c72083d830c4e3e4864dc0", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2015-09-23T13:42:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-21T10:48:55.000Z", "max_issues_repo_path": "279-lec04.tex", "max_issues_repo_name": "rzach/phil279", "max_issues_repo_head_hexsha": "722ec82ae7a4593d40c72083d830c4e3e4864dc0", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "279-lec04.tex", "max_forks_repo_name": "rzach/phil279", "max_forks_repo_head_hexsha": "722ec82ae7a4593d40c72083d830c4e3e4864dc0", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.822815534, "max_line_length": 137, "alphanum_fraction": 0.6490481761, "num_tokens": 3419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.3228420954946003}}
{"text": "%%\\documentclass[handout]{beamer}\n%\\documentclass[aspectratio=169,13pt]{beamer}\n\n%\\input{./preamble}\n\n\\subtitle{Numerical Integration and Differentiation}\n\n\\date{}\n\\begin{document}\n\n\\begin{frame}\n  \\titlepage\n\\end{frame}\n\n\\section{Introduction to Numerical Integration}\n\n\\begin{frame}{Integrability and Sensitivity}\n\n\\begin{itemize}\n\n\\item Seek to compute $\\mathcal{I}(f)=\\int_{a}^b f(x) dx$:\n\n\\mdcond{\n\\begin{itemize}\n\\item $f$ is integrable if continuous and bounded.\n\\mitem Finite number of discontinuities is also often permissible.\n\\end{itemize}\n}\n\n\\item The condition number of integration is bounded by the distance $b-a$:\n\n\\lgcond{\nSuppose the input function is perturbed $\\hat{f}=f+ \\delta f$, then\n\\begin{align*}\n\\delta I &=  |\\mathcal{I}(\\hat{f}) - \\mathcal{I}(f)| \\\\\n               &\\leq |\\mathcal{I}(\\delta f)| \\\\\n               &\\leq (b-a) ||\\delta f||_\\infty, \\quad \\text{where} \\quad |f||_\\infty = \\max_{x\\in[a,b]} | f(x)|.\n%\\left|\\int_{a}^b \\hat{f}(x) dx - \\int^b_a f(x) dx\\right| \\\\\n%               &\\leq |\\int_{a}^b \\underbrace{|\\hat{f}(x) dx - \\int^b_a f(x)|}_{\\leq||\\hat{f}-f||_\\infty = \\delta f}dx \\\\\n%               &\\leq (b-a) \\delta f\n\\end{align*}\nNote that this result {\\it does not depend on the magnitude of $f$ or its derivatives}, which means integration is generally very well-conditioned, which makes sense since integration corresponds to averaging.\n}\n\n\\end{itemize}\n\n\\end{frame}\n\n\\section{Quadrature Rules}\n\n\\begin{frame}{Quadrature Rules}\n\n\\begin{itemize}\n\n\\item Approximate the integral $\\mathcal{I}(f)$ by a weighted sum of function values:\n\\lgcond{\n\\[\\mathcal{I}(f) \\approx Q_n(f)= \\sum_{i=1}^n w_i f(x_i)\\]\n\\begin{itemize}\n\\item $\\{x_i\\}_{i=1}^n$ are quadrature \\coloremph{nodes} or \\coloremph{abscissas},\n%\\item\n $\\{w_i\\}_{i=1}^n$ are quadrature \\coloremph{weights}.\n\\mitem Quadrature rule %defined by $(\\{x_i\\}_{i=1}^n,\\{w_i\\}_{i=1}^n)$ \nis \\coloremph{closed} if $x_1=a,x_n=b$ and \\coloremph{open} otherwise.\n\\mitem Rule is \\coloremph{progressive} if nodes of $Q_n$ are a subset of those of $Q_{n+1}$.\n\\end{itemize}\n}\n\n\\sitem For a fixed set of $n$ nodes, polynomial interpolation followed by integration give \\coloremph{$(n-1)$-degree quadrature rule}:\n\n\\lgcond{\n\\begin{itemize}\n\\item Accuracy depends on interpolant, is exact for all $(n-1)$-degree polynomials.\n\\mitem Can obtain weights by expressing the unique $(n-1)$-degree polynomial interpolant in the Lagrange basis \n$p(x)=\\sum_{i=1}^{n} \\phi_i(x)f(x_i)$, so that\n%, the coefficients are then % of $f$ is given by the Vandermonde system,\n%\\[\\B y = \\B y, \\quad \\text{where} \\quad y_i= f(x_i) \\quad \\text{and} \\quad d_{ii}=\\phi_i(x_i).\\] \n%The quadrature rule is defined by \n\\[Q_n(f)=\\mathcal{I}(p)= \\sum_{i=1}^{n} \\underbrace{\\mathcal{I}(\\phi_i)}_{w_i}f(x_i).\\]\n\\end{itemize}\n}\n\n\\end{itemize}\n\n\\end{frame}\n\n\\begin{frame}{Determining Weights in a General Basis}\n\n\\begin{itemize}\n\\item A quadrature rule provides $\\B x$ and $\\B w$ so as to approximate \n\\lgcond{\n  \\[\\mathcal{I}(f)\\approx Q_n(f)=\\langle \\B w, \\B y \\rangle, \\quad \\text{where} \\quad y_i=f(x_i)\\]\n$Q_n$ is the integral of the polynomial interpolant $p$ of $(x_1,y_1),\\ldots,(x_n,y_n)$.\n%\\begin{itemize}\n%\\item \n%\\end{itemize}\n}\n\\item \\coloremph{Method of undetermined coefficients} obtains $\\B y$ from \\coloremph{moment equations} based on Vandermonde system:\n\\lgcond{\n\\[ \n\\mathcal{I}(p) = \\mathcal{I}(\\langle \\{\\phi_i(x)\\}_{i=1}^n, \\underbrace{\\B V(\\B x, \\{\\phi_i\\}_{i=1}^n)^{-1} \\B y}_\\text{interpolant coefficients}\\rangle) =\n \\langle \\underbrace{\\B V(\\B x, \\{\\phi_i\\}_{i=1}^n)^{-T}\\{\\mathcal{I}(\\phi_i(x))\\}_{i=1}^n}_{\\B w}, \\B y\\rangle\\]\n%\\begin{bmatrix} \\int_a^b \\phi_1(x) dx & \\cdots &\\int_a^b \\phi_n(x)dx \\end{bmatrix} \\B V(\\B x, \\{\\phi_i\\}_{i=1}^n)^{-1} \\B y.\\]\n%\\begin{bmatrix} \\int_a^b \\phi_1(x) dx & \\cdots &\\int_a^b \\phi_n(x)dx \\end{bmatrix} \\B V(\\B x, \\{\\phi_i\\}_{i=1}^n)^{-1} \\B y.\\]\n\\begin{itemize}\n\\item Thus to obtain $\\B w$, we need to solve the linear system,\n\\[\\B V(\\B x, \\{\\phi_i\\}_{i=1}^n)^T\\B w = \\begin{bmatrix} \\int_a^b \\phi_1(x) dx & \\cdots &\\int_a^b \\phi_n(x)dx \\end{bmatrix}^T,\\]\n\\item Note that the weights $\\B w$ are \\coloremph{independent} of the function values $\\B y$.\n\\end{itemize}\n}\n\\end{itemize}\n\n\\end{frame}\n\n\\begin{frame}{Newton-Cotes Quadrature}\n\\urcornerlinkdemo{08-quadrature-and-differentiation}{Newton-Cotes weight finder}\n\n\\begin{itemize}\n\\item \\coloremph{Newton-Cotes} quadrature rules are defined by equispaced nodes on $[a,b]$:\n\n\\mdcond{\nopen: $x_i=a+i(b-a)/(n+1)$, closed: $x_i=a+(i-1)(b-a)/(n-1)$.\n}\n\n\\item The \\coloremph{midpoint rule} is the $n=1$ open Newton-Cotes rule:\n\n\\mdcond{\n\\[M(f) = (b-a)f\\left(\\frac{a+b}{2}\\right)\\]\n}\n\n\\item The \\coloremph{trapezoid rule} is the $n=2$ closed Newton-Cotes rule:\n\n\\mdcond{\n\\[T(f) = \\frac{(b-a)}{2}(f(a) + f(b))\\]\n}\n\n\\item \\coloremph{Simpson's rule} is the $n=3$ closed Newton-Cotes rule:\n\n\\mdcond{\n\\[S(f)=\\frac{b-a}{6}\\left(f(a) + 4f\\left(\\frac{a+b}{2}\\right) + f(b)\\right)\\]\n}\n\n\\end{itemize}\n\n\\end{frame}\n\n\n\\subsection{Error and Conditioning of Quadrature Rules}\n\\begin{frame}[fragile]{Error in Newton-Cotes Quadrature}\n\\urcornerlinkdemo{08-quadrature-and-differentiation}{Accuracy of Newton-Cotes}\n\n\\begin{itemize}\n\\item Consider the Taylor expansion of $f$ about the midpoint of the integration interval $m=(a+b)/2$:\n\\mdcond{\n\\[f(x) = f(m) + f'(m)(x-m) + \\frac{f''(m)}{2}(x-m)^2 +\\ldots\\]\n}\n\nIntegrating the Taylor approximation of $f$, we note that the odd terms drop: \n\\lgcond{\n\\[\\mathcal{I}(f) = \\underbrace{f(m)(b-a)}_{M(f)} + \\underbrace{\\frac{f''(m)}{24}(b-a)^3}_{E(f)} + O((b-a)^5)\\]\nConsequently, the midpoint rule is third-order accurate (first degree).\n}\n\\end{itemize}\n\n\\end{frame}\n\n\n\\begin{frame}{Error Estimation}\n\n\\begin{itemize}\n\n%\\item Quadrature weights can be alternatively determined for a rule by solving the moment equations:\n%\\lgcond{\n%\\begin{align*}\n%\\B V(\\B x, \\{\\phi_i\\}_{i=1}^n) \\B w = \\B y(\\{\\phi_i\\}_{i=1}^n), \\quad \\text{where} \\quad y_i = \\mathcal{I}(\\phi_i)\n%\\end{align*}\n%}\n\\item The trapezoid rule is also first degree, despite using higher-degree polynomial interpolant approximation, since \n\\lgcond{\n\\begin{align*}\nf(m) = \\frac{1}{2}\\bigg(&f(a) - f'(m)(a-m) - \\frac{f''(m)}{2}(a-m)^2 +\\ldots \\\\\n+&f(b) - f'(m)(b-m) - \\frac{f''(m)}{2}(b-m)^2 +\\ldots \\bigg) \\\\\n\\mathcal{I}(f)= T(f)  -& \\underbrace{\\frac{f''(m)}{12}(b-a)^3}_{2E(f)} - O((b-a)^5)\n\\end{align*}\n}\n\\item The above derivation allows us to obtain an error approximation via a difference of midpoint and trapezoidal rules:\n\\lgcond{\n\\[T(f)-M(f)\\approx 3E(f).\\]\nThis approximation rapidly becomes accurate as $b-a$ decreases.\n}\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Error in Polynomial Quadrature Rules}\n\n\\begin{itemize}\n\n\n\\item We can bound the error for a an arbitrary polynomial quadrature rule by\n\\lgcond{\n\\begin{align*}\n|\\mathcal{I}(f)-Q_n(f)| &= |\\mathcal{I}(f-p)| \\\\\n              &\\leq (b-a) || f-p||_\\infty \\\\\n              &\\leq \\frac{b-a}{4n}h^n || f^{(n)}||_\\infty \n\\end{align*}\nwhere $h=\\max_i(x_{i+1}-x_i)$.\n}\n\\lgcond{\n}\n\n\\end{itemize}\n\n\\end{frame}\n\n\\begin{frame}{Conditioning of Newton-Cotes Quadrature}\n\n\\begin{itemize}\n\\item We can ascertain stability of quadrature rules, by considering the amplification of a perturbation $\\hat{f} = f+ \\delta f$:\n\\lgcond {\n\\begin{align*}\n|Q_n(\\hat{f})-Q_n(f)| &= |Q_n(\\delta f)| \\\\\n                      &= \\sum_{i=1}^n w_i \\delta f(x_i) \\\\\n                      &\\leq ||\\B w||_1 ||\\delta f||_\\infty.\n\\end{align*}\nNote that we always have $\\sum_i w_i=b-a$, since the quadrature rule must be correct for a constant function.\nSo if $\\B w$ is positive $||\\B w||_1=b-a$, the quadrature rule is stable, i.e. it matches the conditioning of the problem.\n}\n\\item Newton-Cotes quadrature rules have at least one negative weight for any $n\\geq 11$:\n\\lgcond{\nMore generally, $||\\B w||_1\\to \\infty$ as $n \\to \\infty$ for fixed $b-a$. This means that the Newton-Cotes rules can be ill-conditioned.\n}\n\\end{itemize}\n\n\\end{frame}\n\n\\subsection{Chebyshev Quadrature}\n\n\\begin{frame}{Clenshaw-Curtis Quadrature}\n\n\\begin{itemize}\n\\item To obtain a more stable quadrature rule, we need to ensure the integrated interpolant is well-behaved as $n$ increases:\n\n\\lgcond{\n\\begin{itemize}\n\\mitem Chebyshev quadrature nodes ensure that interpolant polynomial has bounded coefficients so long as $f$ is bounded, since the Vandermonde system defining its coefficients is well-conditioned.\n\\mitem Formally, it can be shown that $w_i>0$ for the Chebyshev-node ({\\color{red} Clenshaw-Curtis}) quadrature.\n\\mitem The weights for Clenshaw-Curtis quadrature rules can be obtained by solutions to Vandermonde systems on $[-1,1]$ with Chebyshev-spaced nodes, then translating to a desired integration interval.\n\\end{itemize}\n}\n\\end{itemize}\n\n\\end{frame}\n\n%\\begin{frame}{Gaussian Quadrature}\n%\n%\\begin{itemize}\n%\\item So far, we have only considered quadrature rules based on a fixed set of nodes, but we can also choose a set of nodes to improve accuracy:\n%\n%\\lgcond{\n%Choice of nodes gives additional $n$ parameters for a total of $2n$ degrees of freedom, permitting representation of polynomials of degree $2n-1$.\n%}\n%\\item The \\coloremph{unique} $n$-point \\coloremph{Gaussian quadrature rule} is defined by the solution of the nonlinear form of the moment equations in terms of \\textit{both} $\\B x$ and $\\B w$:\n%\\lgcond{\n%Given any complete basis, we seek to solve the nonlinear equations,\n%\\[\\B V(\\B x, \\{\\phi_i\\}_{i=1}^{2n+1}) \\B w = \\B y(\\{\\phi_i\\}_{i=1}^{2n+1}), \\quad \\text{where} \\quad y_i = \\mathcal{I}(\\phi_i)\\]\n%For fixed $\\B x$, we have an overdetermined system of linear equations for $\\B w$.\n%}\n%%To obtain a more stable quadrature rule, we need to ensure the integrated interpolant is well-behaved as $n$ increases:\n%%\n%%\\lgcond {\n%%Chebyshev quadrature nodes ensure that interpolant polynomial has bounded coefficients so long as $f$ is bounded, since the Vandermonde system defining its coefficients is well-conditioned.\n%%\n%%Formally, it can be shown that $w_i>0$ for Chebyshev-node (Clenshaw-Curtis) quadrature.\n%%}\n%\\end{itemize}\n%\n%\\end{frame}\n%\n%\\begin{frame}{Using Gaussian Quadrature Rules}\n%\n%\\begin{itemize}\n%\\item Gaussian quadrature rules are hard to determine and usually, but can be enumerated for a fixed interval, e.g. $a=0,b=1$, so it suffices to transform the integral to $[0,1]$\n%\n%\\lgcond{\n%We have that \n%\\[\\mathcal{I}(f) = \\int_{a}^b f(x)dx = \\int_0^1 g(t) dt \\quad \\text{where} \\quad g(x) = f(t), t=\\frac{x+b-a}{b-a}\\]\n%\n%Choice of nodes gives additional $n$ parameters for a total of $2n$ degrees od freedom, permitting representation of polynomials of degree $2n-1$.\n%}\n%\\item The \\coloremph{unique} $n$-point \\coloremph{Gaussian quadrature rule} is defined by the solution of the nonlinear form of the moment equations in terms of \\textit{both} $\\B x$ and $\\B w$:\n%\\lgcond{\n%Given any complete basis, we seek to solve the nonlinear equations,\n%\\[\\B V(\\B x, \\{\\phi_i\\}_{i=1}^{2n+1}) \\B w = \\B y(\\{\\phi_i\\}_{i=1}^{2n+1}), \\quad \\text{where} \\quad y_i = \\mathcal{I}(\\phi_i)\\]\n%For fixed $\\B x$, we have an overdetermined system of linear equations for $\\B w$.\n%}\n%%To obtain a more stable quadrature rule, we need to ensure the integrated interpolant is well-behaved as $n$ increases:\n%%\n%%\\lgcond {\n%%Chebyshev quadrature nodes ensure that interpolant polynomial has bounded coefficients so long as $f$ is bounded, since the Vandermonde system defining its coefficients is well-conditioned.\n%%\n%%Formally, it can be shown that $w_i>0$ for Chebyshev-node (Clenshaw-Curtis) quadrature.\n%%}\n%\\end{itemize}\n%\n%\\end{frame}\n%\n%\\begin{frame}{Improvements to Gaussian Quadrature}\n%\n%\\begin{itemize}\n%\\item Gaussian quadrature rules are are accurate and stable but not progressive (nodes cannot be reused to obtain higher-degree approximation):\n%\n%\\mdcond{}\n%\n%\\item \\coloremph{Kronod} quadrature rules construct $(2n+1)$-point quadrature $K_{2n+1}$ that is progressive w.r.t. Gaussian quadrature rule $G_n$\n%\n%\\mdcond{}\n%\n%\\item Gaussian quadrature rules are in general open, but Gauss-Radau and Gauss-Lobatto rules permit including end-points:\n%\n%\\mdcond{\n%Gauss-Radau uses one of two end-points as a node, while Gauss-Lobatto quadrature uses both.\n%}\n%\n%\\end{itemize}\n%\n%\n%\\end{frame}\n%\n%\n%\\begin{frame}{Composite and Adaptive Quadrature}\n%\n%\\begin{itemize}\n%\\item Composite quadrature rules are obtained by integrating a piecewise interpolant of $f$:\n%\n%\\lgcond{}\n%\n%\\item Adaptive quadrature corresponds to using composite quadrature with adaptive refinement:\n%\n%\\lgcond{\n%Introduce new nodes where error estimate is large. \n%Error estimate can be obtained by e.g. comparing trapezoid and midpoint rules, but can be completely wrong if function is insufficiently smooth.\n%}\n%\n%\\end{itemize}\n%\n%\n%\\end{frame}\n\n\n\n\n\n\n\n\n%\\end{document}\n\n\\subsection{Gaussian Quadrature}\n\n\\begin{frame}{Gaussian Quadrature}\n\\urcornerlinkdemo{08-quadrature-and-differentiation}{Gaussian quadrature weight finder}\n\n\\begin{itemize}\n\\item So far, we have only considered quadrature rules based on a fixed set of nodes, but we may also be able to choose nodes to maximize accuracy:\n\n\\lgcond{\n\\begin{itemize}\n\\item Choice of nodes gives additional $n$ parameters for total $2n$ degrees of freedom.\n\\mitem Permits exact integration of degree-$(2n-1)$ polynomials and corresponding general accuracy.\n\\end{itemize}\n}\n\\item The \\coloremph{unique} $n$-point \\coloremph{Gaussian quadrature rule} is defined by the solution of the nonlinear form of the moment equations in terms of \\textit{both} $\\B x$ and $\\B w$:\n\n\\lgcond{\nGiven any complete basis, we seek to solve the nonlinear equations for $\\B x,\\B w$,\n\\[\\B V(\\B x, \\{\\phi_i\\}_{i=1}^{2n+1})^T \\B w = \\B y, \\quad \\text{where} \\quad y_i = \\mathcal{I}(\\phi_i).\\]\n\\begin{itemize}\n\\item These nonlinear equations generally have a unique solution $(\\B x^*, \\B w^*)$.\n\\mitem For fixed $\\B x$, we have an overdetermined system of linear equations for $\\B w$.\n\\end{itemize}\n}\n%To obtain a more stable quadrature rule, we need to ensure the integrated interpolant is well-behaved as $n$ increases:\n%\n%\\lgcond {\n%Chebyshev quadrature nodes ensure that interpolant polynomial has bounded coefficients so long as $f$ is bounded, since the Vandermonde system defining its coefficients is well-conditioned.\n%\n%Formally, it can be shown that $w_i>0$ for Chebyshev-node (Clenshaw-Curtis) quadrature.\n%}\n\\end{itemize}\n\n\\end{frame}\n\n\\begin{frame}{Using Gaussian Quadrature Rules}\n\n\\begin{itemize}\n\\item Gaussian quadrature rules are hard to compute, but can be enumerated for a fixed interval, e.g. $a=0,b=1$, so it suffices to transform the integral to $[0,1]$\n\n\\lgcond{\n\\begin{itemize}\n\\item We can transform a given integral using variable substitution $t=\\frac{x-a}{b-a}$,\n\\[\\mathcal{I}(f) = \\int_{a}^b f(x)dx = (b-a)\\int_0^1 g(t) dt \\quad \\text{where} \\quad g(t) = f(t(b-a)+a)).\\]\n\\item For quadrature rules defined on $[-1,1]$, we can transform via the substitution $t=2\\frac{x-a}{b-a}-1$,\n\\[\\mathcal{I}(f) = \\int_{a}^b f(x)dx = \\frac{b-a}{2}\\int_{-1}^1 g(t) dt \\quad \\text{where} \\quad g(t) = f((t+1)(b-a)/2+a).\\]\n\\end{itemize}\n}\n\n\\item Gaussian quadrature rules are accurate and stable but not progressive (nodes cannot be reused to obtain higher-degree approximation):\n\n\\mdcond{\n\\begin{itemize}\n\\item maximal degree is obtained\n\\sitem weights are always positive (perfect conditioning)\n\\end{itemize}\n}\n\n\n\\end{itemize}\n\n\\end{frame}\n\n\\begin{frame}{Progressive Gaussian-like Quadrature Rules}\n\n\\begin{itemize}\n\\item \\coloremph{Kronod} quadrature rules construct $(2n+1)$-point $(3n+1)$-degree quadrature $K_{2n+1}$ that is progressive with respect to Gaussian quadrature rule $G_n$:\n\n\\lgcond{\n\\begin{itemize}\n\\item Gaussian quadrature rule $G_{2n+1}$ would use same number of points and have degree $4n+1$.\n\\mitem Kronod rule points are optimal chosen to reuse all points of $G_n$, so $n+1$ rather than $2n+1$ new evaluations are necessary.\n\\end{itemize}\n}\n\\item \\coloremph{Patterson} quadrature rules use $2n+2$ more points to extend $(2n+1)$-point Kronod rule  to degree $6n+4$, while reusing all $2n+1$ points.\n\n\\item Gaussian quadrature rules are in general open, but \\coloremph{Gauss-Radau} and \\coloremph{Gauss-Lobatto} rules permit including end-points:\n\n\\lgcond{\nGauss-Radau uses one of two end-points as a node, while Gauss-Lobatto quadrature uses both.\n}\n\n\\end{itemize}\n\n\n\\end{frame}\n\n\n\\begin{frame}{Composite and Adaptive Quadrature}\n\n\\begin{itemize}\n\\item \\coloremph{Composite quadrature rules} are obtained by integrating a piecewise interpolant of $f$:\n\n\\lgcond{\nFor example, we can derive simple composite Newton-Cotes rules by partitioning the domain into sub-intervals $[x_i,x_{i+1}]$:\n\\begin{itemize}\n\\sitem composite midpoint rule \n  \\[\\mathcal{I}(f) = \\sum_{i=1}^{n-1} \\int_{x_i}^{x_{i+1}} f(x)dx \\approx \\sum_{i=1}^{n-1} (x_{i+1}-x_i)f((x_{i+1}+x_i)/2)\\]\n\\item composite trapezoid rule\n  \\[\\mathcal{I}(f) = \\sum_{i=1}^{n-1} \\int_{x_i}^{x_{i+1}} f(x)dx \\approx \\sum_{i=1}^{n-1} \\frac{(x_{i+1}-x_i)}2 (f(x_{i+1})+f(x_i))\\]\n\\end{itemize}\n}\n\n\\item Composite quadrature can be done with adaptive refinement:\n\n\\lgcond{\nIntroduce new nodes where error estimate is large. \nError estimate can be obtained by e.g. comparing trapezoid and midpoint rules, but can be completely wrong if function is insufficiently smooth.\n}\n\n\\end{itemize}\n\n\n\\end{frame}\n\n\\begin{frame}{More Complicated Integration Problems}\n\n\\begin{itemize}\n\\item To handle improper integrals can either transform integral to get rid of infinite limit or use appropriate open quadrature rules.\n\n\\mdcond{}\n\n\\item Double integrals can simply be computed by successive 1-D integration.\n\n\\mdcond{\nComposite multidimensional rules are also possible by partitioning the domain into chunks.\n}\n\n\\item High-dimensional integration is often effectively done by \\coloremph{Monte Carlo}:\n\n\\lgcond{\n\\[\\int_\\Omega f(\\B x) d\\B x = E[Y], \\quad Y = \\frac{|\\Omega|}{N} \\sum_{i=1}^N Y_i, \\quad Y_i = f(\\B x_i), \\quad \\B x_i \\ \\  \\text{chosen randomly from $\\Omega$}.\\]\n\\begin{itemize}\n\\item Convergence rate is independent of function (effective polynomial degree approximation) or dimension of integration domain.\n\\mitem Instead, it depends on number of samples ($N$), with error scaling as $O(1/\\sqrt{N})$.\n\\end{itemize}\n}\n\n\n\\end{itemize}\n\n\n\\end{frame}\n\n\n\\begin{frame}{Integral Equations}\n\n\\begin{itemize}\n\\item Rather than evaluating an integral, in solving an \\coloremph{integral equation} we seek to compute the integrand. A typical linear integral equation has the form\n\\[\\int_a^b K(s,t)u(t) dt = f(s), \\quad \\text{where} \\quad K \\quad \\text{and} \\quad f \\quad \\text{are known}.\\]\n\\lgcond{\n\\begin{itemize}\n\\item Useful for recovering signal $u$ given response function with kernel $K$ and measurements of $f$.\n\\mitem Also arise from solve equations arising from Green's function methods for PDEs.\n\\end{itemize}\n}\n\\item Using a quadrature rule with weights $w_1,\\ldots, w_n$ and nodes $t_1,\\ldots, t_n$ obtain\n\\lgcond{\n\\[\\sum_{j=1}^n w_jK(s,t_j)u(t_j) = f(s).\\]\nDiscrete sample of $f$ on $s_1,\\ldots, s_n$ yields a linear system of equations,\n\\[\\sum_{j=1}^n w_jK(s_i,t_j)u(t_j) = f(s_i).\\]\n%The resulting matrix $\\B A$ can be ill-conditioned for many kernels $K$.\n}\n\\end{itemize}\n\n\n\\end{frame}\n\n\n%\\begin{frame}{Challenges in Solving Integral Equations}\n%\n%\\begin{itemize}\n%\\item Integral equations based on response functions tend to be ill-conditioned, which is resolved using\n%\n%\\begin{itemize}\n%\\item truncated singular value decomposition of $\\B A$, where $a_{ij}=w_jK(s_i,t_j)$\n%\n%\\mdcond{}\n%\n%\\item replacing the linear system with a regularized linear least squares problem,\n%\n%\\mdcond{}\n%\n%\\item expressing the solution using a basis\n%\n%\\mdcond{Let $u(t)\\approx \\sum_{j=1}^n c_j \\phi_j(t)$ and derive equations for the coefficients.}\n%\n%\\end{itemize}\n%\\end{itemize}\n%\n%\n%\\end{frame}\n\n\n\\begin{frame}{Numerical Differentiation}\n\\urcornerlinkdemo{08-quadrature-and-differentiation}{Taking Derivatives with Vandermonde Matrices}\n\n\\begin{itemize}\n\\item Automatic (symbolic) differentiation is a surprisingly viable option:\n\\lgcond{\n\\begin{itemize}\n\\item Any computer program is differentiable, since it is an assembly of basic arithmetic operations.\n\\item Existing software packages can automatically differentiate whole programs.\n\\end{itemize}\n}\n\\item Numerical differentiation can be done by interpolation or finite differencing:\n\n\\lgcond{\n\\begin{itemize}\n\\item Given polynomial interpolant, its derivative is easy to obtain by differentiating the basis in which it is expressed,\n\\[f'(x)\\approx p'(x) = \\begin{bmatrix} \\phi'_1(x) & \\cdots &\\phi'_n(x) \\end{bmatrix}^T\\B V(\\B t, \\{\\phi_i\\}_{i=1}^n)^{-1} \\B y, \\ \\text{where} \\ y_i=f(t_i).\\]\n\\item Obtaining the values of the derivative at the interpolation nodes, can be done via\n\\[\\underbrace{\\B V(\\B t, \\{\\phi_i'\\}_{i=1}^n)\\B V(\\B t, \\{\\phi_i\\}_{i=1}^n)^{-1}}_\\text{Differentiation matrix} \\B y, \\ \\text{where} \\ y_i=f(t_i).\\]\n\\item Finite-differencing formulas effectively use linear interpolant.\n\\end{itemize}\n}\n\n\\end{itemize}\n\n\\end{frame}\n\n\\begin{frame}{Accuracy of Finite Differences}\n\n\\dblurcornerlinkdemo{08-quadrature-and-differentiation}{Finite Differences vs Noise}{08-quadrature-and-differentiation}{Floating point vs Finite Differences}\n\n\\begin{itemize}\n\\item \\coloremph{Forward and backward differencing} provide first-order accuracy:\n\n\\lgcond{\nThese can be derived, respectively from forward and backward Taylor expansions of $f$ about $x$,\n\\begin{align*}\nf(x+h) &= f(x) + f'(x)h + f''(x) h^2 /2 + \\ldots \\\\\nf(x-h) &= f(x) - f'(x)h + f''(x) h^2 /2 - \\ldots \n\\end{align*}\nFor forward differencing, we obtain an approximation from the first equation,\n\\[f'(x) = \\frac{f(x+h)- f(x)}h + f''(x) h /2 + \\ldots.\\]\n}\n\\item \\coloremph{Centered differencing} provides second-order accuracy.\n\\lgcond{\nSubtracting the backward Taylor expansion from the forward, we obtain centered differencing,\n\\[f'(x) = \\frac{f(x+h)- f(x-h)}{2h} + O(h^2).\\]\nSecond order accuracy is due to cancellation of odd terms like $f''(x)h/2$.\n}\n\n\\end{itemize}\n\n\\end{frame}\n\n\\begin{frame}{Extrapolation Techniques}\n\n\\urcornerlinkdemoinclass{08-quadrature-and-differentiation}{Richardson with Finite Differences}{inclass-richardson}{Richardson Extrapolation}\n\n\\begin{itemize}\n\\item Given a series of approximate solutions produced by an iterative procedure, a more accurate approximation may be obtained by \\coloremph{extrapolating} this series.\n\n\\lgcond{\nFor example, as we lower the step size $h$ in a finite-difference formula, we can try to extrapolate the series to $h=0$, if we know that \n\\[F(h)=a_0 + a_1h^p + O(h^r) \\ \\text{as} \\ h\\to 0 \\ \\text{and seek to determine $F(0)=a_0$},\\]\nfor example in centered differences $p=2$ and $r=4$.\n}\n\\item In particular, given two guesses, \\coloremph{Richardson extrapolation} eliminates the leading order error term.\n\n\\lgcond{\nSeek to eliminate $a_1h^p$ term in  $F(h)$, $F(h/2)$ to improve approximation of $a_0$,\n\\begin{align*}\nF(h) &= a_0 + a_1h^p + O(h^r), \\\\\nF(h/2) &= a_0 + a_1h^p/2^p + O(h^r), \\\\\na_0 &= F(h) - \\frac{F(h)-F(h/2)}{1-1/2^{p}} + O(h^r).\n\\end{align*}\n}\n\n\\end{itemize}\n\n\\end{frame}\n\n\\begin{frame}{High-Order Extrapolation}\n\n\\begin{itemize}\n\\item Given a series of $k$ approximations, \\coloremph{Romberg integration} applies $(k-1)$-levels of Richardson extrapolation.\n\n\\lgcond{\nCan apply Richardson extrapolation to each of $k-1$ pairs of consecutive nodes, then proceed recursively on the $k-1$ resulting approximations.\n}\n\n\\item Extrapolation can be used within an iterative procedure at each step:\n\n\\lgcond{\nFor example, Steffensen's method for finding roots of nonlinear equations,\n\\[x_{n+1} = x_n + \\frac{f(x_n)}{1-f(x_n+f(x_n))/f(x_n)},\\]\nderived from Aitken's delta-squared extrapolation process:\n\\begin{itemize}\n\\item achieves quadratic convergence,\n\\sitem requires no derivative,\n\\sitem competes with the Secant method (quadratic versus superlinear convergence, but an extra function evaluation necessary).\n\\end{itemize}\n}\n\n\\end{itemize}\n\n\\end{frame}\n\n\n\n\n\n\n\n\n\n\n\n\n\n%\\end{document}\n", "meta": {"hexsha": "b2f6f2007be657cebe42a86ce7a3f7a49afa9930", "size": 23953, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "08-body.tex", "max_stars_repo_name": "solomonik/cs450-notes", "max_stars_repo_head_hexsha": "7f4d18705dac5730b7e40e588acf55030c9d823a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "08-body.tex", "max_issues_repo_name": "solomonik/cs450-notes", "max_issues_repo_head_hexsha": "7f4d18705dac5730b7e40e588acf55030c9d823a", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "08-body.tex", "max_forks_repo_name": "solomonik/cs450-notes", "max_forks_repo_head_hexsha": "7f4d18705dac5730b7e40e588acf55030c9d823a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.697466468, "max_line_length": 209, "alphanum_fraction": 0.7053813719, "num_tokens": 7674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.3228203637733662}}
{"text": "\\documentclass{article}\n\n\\usepackage{url}\n\\usepackage{proof}\n\\usepackage{amssymb}\n\\usepackage{stmaryrd}\n\\usepackage{listings}\n\\usepackage{graphicx}\n\\usepackage{multicol}\n\n\\newcommand{\\todo}[1]{\\textbf{TODO: #1}}\n\n\\setlength{\\parskip}{0pt}\n\n\n%subcode-inline{bnf-inline} name langRev\n%! swap+ = \\mathit{swap}^+\n%! swap* = \\mathit{swap}^*\n%! dagger =  ^{\\dagger}\n%! assocl+ = \\mathit{assocl}^+\n%! assocr+ = \\mathit{assocr}^+\n%! assocl* = \\mathit{assocl}^*\n%! assocr* = \\mathit{assocr}^*\n%! identr* = \\mathit{uniti}\n%! identl* = \\mathit{unite}\n%! dist = \\mathit{distrib}\n%! factor = \\mathit{factor}\n%! (o) = \\fatsemi\n%! (;) = \\fatsemi\n%! (*) = \\times\n%! (+) = +\n\n%subcode-inline{bnf-inline} regex \\{\\{(((\\}[^\\}])|[^\\}])*)\\}\\} name main include langRev\n%! [^ = \\ulcorner\n%! ^] = \\urcorner\n%! [v = \\llcorner\n%! v] = \\lrcorner\n%! |-->* = \\mapsto^{*}\n%! |-->> = \\mapsto_{\\ggg}\n%! |-->let = \\mapsto_{let}\n%! |--> = \\mapsto\n%! <--| = \\mapsfrom\n%! |- = \\vdash\n%! in = \\!\\!\\in\\!\\!\n%! <=> = \\Longleftrightarrow\n%! <-> = \\leftrightarrow\n%! ~> = \\leadsto\n%! ::= = ::=\n%! /= = \\neq\n%! vi = v_i\n%! di = d_i\n%! si = s_i\n%! sj = s_j\n%! F = \\texttt{F}\n%! T = \\texttt{T}\n%! forall = \\forall\n%! exists = \\exists\n%! empty = \\emptyset\n%! eta = \\eta\n%! where = \\textbf{where}\n%! epsilon = \\varepsilon\n%! least = \\phi\n%! trace+ = trace\n%! trace* = trace_{\\times}\n%! loop+ = loop_{+}\n%! loop* = loop_{\\times}\n%! CatC = {\\mathcal C}\n%! CatA = {\\mathcal A}\n%! gamma = \\gamma\n%! {[ = \\{\n%! ]} = \\}\n%! elem = \\in\n%! dagger = ^\\dagger\n%! alpha = \\alpha\n%! beta = \\beta\n%! rho = \\rho\n%! < = \\langle\n%! > = \\rangle\n%! @@~ = \\tilde{\\mu}\n%! @@ = \\mu\n%! @ = \\,@\\,\n%! * = \\times\n%! FC = \\mathcal{C}\n%! langRev = \\Pi\n%! langRevT = \\Pi^{o}\n%! langRevEE = \\Pi^{\\eta\\epsilon}_{+}\n%! bullet = \\bullet\n\n\\urldef{\\mails}\\path|{rpjames, sabry}@indiana.edu|\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\begin{document}\n\\title{ Logic of {{langRevEE}} } \n% \\titlerunning{On the construction of Isomorphic Interpreters} \n% \\author{Roshan P. James \\and Amr Sabry}\n%\\institute{School of Informatics and Computing, Indiana University\\\\\n% \\mails}\n\\maketitle\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{abstract}\n\\end{abstract}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Logic} \n\nBy Curry-Howard of the presentataion of {{langRevEE}}, we simply erase\nthe terms to reveal the underlying logic. Sequents have the form\n{{b1~|-~b2}} with just one formula on the left and right of the sequent. \n\n\n%subcode{proof} include main\n%@ ~\n%@@  0 + b |- b \n%\n%@ ~\n%@@  b1 + b2 |- b2 + b1 \n%\n%@ ~\n%@@  b1 + (b2 + b3) |- (b1 + b2) + b3 \n%---\n%@ ~\n%@@  1 * b |- b \n%\n%@ ~\n%@@  b1 * b2 |- b2 * b1 \n%\n%@ ~\n%@@  b1 * (b2 * b3) |- (b1 * b2) * b3 \n%---\n%@ ~\n%@@ 0 * b |- 0 \n%\n%@ ~\n%@@ (b1 + b2) * b3 |- (b1 * b3) + (b2 * b3)\n%---\n%@ ~\n%@@ 0 |- (-b) + b\n%\n%@ ~\n%@@ 1 |- (1/b) * b\n%\n\n\n%subcode{proof} include main\n%@  ~\n%@@ b |- b \n%\n%@ b1 |- b2\n%@@ b2 |- b1\n%\n%@ b1 |- b2\n%@ b2 |- b3\n%@@ b1 |- b3\n%---\n%@ b1 |- b3\n%@ b2 |- b4\n%@@ b1 + b2 |- b3 + b4\n%\n%@ b1 |- b3\n%@ b2 |- b4\n%@@ b1 * b2 |- b3 * b4\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\begin{scriptsize}\n\\bibliographystyle{splncs03} \n\\bibliography{cites}  \n\\end{scriptsize}\n\\end{document}\n\n", "meta": {"hexsha": "5cae729c401f97bff2e4e745452e125ae963d6e3", "size": 3325, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "mu-mu-tilde/logic.tex", "max_stars_repo_name": "JacquesCarette/pi-dual", "max_stars_repo_head_hexsha": "003835484facfde0b770bc2b3d781b42b76184c1", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2015-08-18T21:40:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T01:07:57.000Z", "max_issues_repo_path": "mu-mu-tilde/logic.tex", "max_issues_repo_name": "JacquesCarette/pi-dual", "max_issues_repo_head_hexsha": "003835484facfde0b770bc2b3d781b42b76184c1", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-06-07T16:27:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-29T20:41:23.000Z", "max_forks_repo_path": "mu-mu-tilde/logic.tex", "max_forks_repo_name": "JacquesCarette/pi-dual", "max_forks_repo_head_hexsha": "003835484facfde0b770bc2b3d781b42b76184c1", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-05-29T01:56:33.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-10T09:47:13.000Z", "avg_line_length": 18.7853107345, "max_line_length": 88, "alphanum_fraction": 0.4806015038, "num_tokens": 1250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.5039061705290806, "lm_q1q2_score": 0.322820360315997}}
{"text": "\\newpage\r\n\\section{High Energy Physics}\r\n\r\n\\begin{Introduction}{HEPHYS}\r\nThe High-energy Physics package is historic for REDUCE, since REDUCE\r\noriginated as a program to aid in computations with Dirac expressions.\r\nThe commutation algebra of the gamma matrices is independent of their\r\nrepresentation, and is a natural subject for symbolic mathematics.  Dirac\r\ntheory is applied to \\IFTEX{$\\beta$}{beta} decay and the computation of\r\ncross-sections and scattering.  The high-energy physics operators are\r\navailable in the REDUCE main program, rather than as a module which must\r\nbe loaded.\r\n\\end{Introduction}\r\n\r\n\\begin{Operator}[HE-dot]{.}\r\nThe . operator is used to denote the scalar product of two Lorentz\r\nfour-vectors.\r\n\\begin{Syntax}\r\n\\meta{vector} \\name{.} \\meta{vector}\r\n\\end{Syntax}\r\n\r\n\\meta{vector} must be an identifier declared to be of type \\name{vector} to have\r\nthe scalar product definition.  When applied to arguments that are not\r\nvectors, the \\nameref{cons} operator is used,\r\nwhose symbol is also ``dot.''\r\n\r\n\\begin{Examples}\r\nvector aa,bb,cc; \\\\\r\nlet aa.bb = 0; \\\\\r\naa.bb;                               &     0 \\\\\r\naa.cc;                               &     AA.CC \\\\\r\nq := aa.cc;                          &     Q := AA.CC \\\\\r\nq;                                   &     AA.CC\r\n\\end{Examples}\r\n\r\n\\begin{Comments}\r\nSince vectors are special high-energy physics entities that do not contain\r\nvalues, the . product will not return a true scalar product.  You can\r\nassign a scalar identifier to the result of a . operation, or assign a .\r\noperation to have the value of the scalar you supply, as shown above.  Note\r\nthat the result of a . operation is a scalar, not a vector.\r\n\r\nThe metric tensor g(u,v) can be represented by \\name{u.v}.  If contraction\r\nover the indices is required, \\name{u} and \\name{v} should be declared to\r\nbe of type \\nameref{index}.\r\n\r\nThe dot operator has the highest precedence of the infix operators, so\r\nexpressions involving . and other operators have the scalar product\r\nevaluated first before other operations are done.\r\n\\end{Comments}\r\n\\end{Operator}\r\n\r\n\r\n\\begin{Operator}{EPS}\r\nThe \\name{eps} operator denotes the completely antisymmetric tensor of\r\norder 4 and its contraction with Lorentz four-vectors, as used in\r\nhigh-energy physics calculations.\r\n\\begin{Syntax}\r\n\\name{eps}\\(\\meta{vector-expr},\\meta{vector-expr},\\meta{vector-expr},\r\n\\meta{vector-expr}\\)\r\n\\end{Syntax}\r\n\r\n\\meta{vector-expr} must be a valid vector expression, and may be an index.\r\n\r\n\\begin{Examples}\r\nvector g0,g1,g2,g3; \\\\\r\neps(g1,g0,g2,g3);               &      - EPS(G0,G1,G2,G3); \\\\\r\neps(g1,g2,g0,g3);               &      EPS(G0,G1,G2,G3); \\\\\r\neps(g1,g2,g3,g1);               &      0\r\n\\end{Examples}\r\n\r\n\\begin{Comments}\r\nVector identifiers are ordered alphabetically by REDUCE.  When an odd number\r\nof transpositions is required to restore the canonical order to the four\r\narguments of \\name{eps}, the term is ordered and carries a minus sign.  When an\r\neven number of transpositions is required, the term is returned ordered and\r\npositive.  When one of the arguments is repeated, the value 0 is returned.\r\nA contraction of the form\r\n\\IFTEX{$\\epsilon_{ij\\mu\\nu}p_{\\mu}q_{\\nu}$}{eps(_i j mu nu p_mu q_nu)}\r\nis represented by \\name{eps(i,j,p,q)} when \\name{i} and \\name{j} have been\r\ndeclared to be of type \\nameref{index}.\r\n\\end{Comments}\r\n\\end{Operator}\r\n\r\n\r\n\\begin{Operator}{G}\r\n\\name{g} is an n-ary operator used to denote a product of gamma matrices\r\ncontracted with Lorentz four-vectors, in high-energy physics.\r\n\\begin{Syntax}\r\n\\name{g}\\(\\meta{identifier},\\meta{vector-expr}\r\n\\{,\\meta{vector-expr}\\}\\optional\\)\r\n\\end{Syntax}\r\n\r\n\\meta{identifier} is a scalar identifier representing a fermion line\r\nidentifier, \\meta{vector-expr} can be any valid vector expression,\r\nrepresenting a vector or a gamma matrix.\r\n\r\n\\begin{Examples}\r\nvector aa,bb,cc; \\\\\r\nvector a; \\\\\r\ng(line1,aa,bb);                 &     AA.BB \\\\\r\ng(line2,aa,a);                  &     0 \\\\\r\ng(id,aa,bb,cc);                 &     0 \\\\\r\ng(li1,aa,bb) + k;               &     AA.BB + K \\\\\r\nlet aa.bb = m*k; \\\\\r\ng(ln1,aa)*g(ln1,bb);            &     K*M \\\\\r\ng(ln1,aa)*g(ln2,bb);            &     0\r\n\\end{Examples}\r\n\\begin{Comments}\r\nThe vector \\name{A} is reserved in arguments of \\name{g} to denote the\r\nspecial gamma matrix \\IFTEX{$\\gamma_{5}$}{gamma_5}.  It must be declared to\r\nbe a vector before you use it.\r\n\r\nGamma matrix expressions are associated with fermion lines in a Feynman\r\ndiagram.  If more than one line occurs in an expression, the gamma\r\nmatrices involved are separate (operating in independent spin space), as\r\nshown in the last two example lines above.  A product of gamma matrices\r\nassociated with a single line can be entered either as a single \\name{g}\r\ncommand with several vector arguments, or as products of separate \\name{g}\r\ncommands each with a single argument.\r\n\r\nWhile the product of vectors is not defined, the product, sum and\r\ndifference of several gamma expressions are defined, as is the product of\r\na gamma expression with a scalar.  If an expression involving gamma\r\nmatrices includes a scalar, the scalar is treated as if it were the\r\nproduct of itself with a unit \\IFTEX{$4 \\times 4$}{4 x 4} matrix.\r\n\r\nDirac expressions are evaluated by computing the trace of the expression\r\nusing the commutation algebra of gamma matrices.  The algorithms used are\r\ndescribed in articles by J. S. R. Chisholm in \\meta{Il Nuovo Cimento X,} Vol.\r\n30, p. 426, 1963, and J. Kahane, \\meta{Journal of Mathematical Physics},\r\nVol. 9, p. 1732, 1968.  The trace is then divided by 4 to distinguish\r\nbetween the trace of a scalar and the trace of an expression that is the\r\nproduct of a scalar with a unit \\IFTEX{$4 \\times 4$}{4 x 4} matrix.\r\n\r\nTrace calculations may be prevented over any line identifier by declaring it\r\nto be \\nameref{nospur}.   If it is later desired to evaluate these traces,\r\nthe declaration can be undone with the \\nameref{spur} declaration.\r\n\r\nThe notation of Bjorken and Drell, \\meta{Relativistic Quantum Mechanics,}\r\n1964, is assumed in all operations involving gamma matrices.  For an\r\nexample of the use of \\name{g} in a calculation, see the \\meta{REDUCE\r\nUser's Manual}.\r\n\\end{Comments}\r\n\\end{Operator}\r\n\r\n\r\n\\begin{Declaration}{INDEX}\r\nThe declaration \\name{index} flags a four-vector as an index for subsequent\r\nhigh-energy physics calculations.\r\n\\begin{Syntax}\r\n\\name{index} \\meta{vector-id}\\{,\\meta{vector-id}\\}\\optional\r\n\\end{Syntax}\r\n\r\n\\meta{vector-id} must have been declared of type \\name{vector}.\r\n\r\n\\begin{Examples}\r\nvector aa,bb,cc; \\\\\r\nindex uu; \\\\\r\nlet aa.bb = 0; \\\\\r\n(aa.uu)*(bb.uu);                  &      0 \\\\\r\n(aa.uu)*(cc.uu);                  &      AA.CC\r\n\\end{Examples}\r\n\r\n\\begin{Comments}\r\nIndex variables are used to represent contraction over components of\r\nvectors when scalar products are taken by the . operator, as well as\r\nindicating contraction for the \\nameref{eps} operator or metric tensor.\r\n\r\nThe special status of a vector as an index can be revoked with the\r\ndeclaration \\nameref{remind}.  The object remains a vector, however.\r\n\\end{Comments}\r\n\\end{Declaration}\r\n\r\n\r\n\\begin{Command}{MASS}\r\nThe \\name{mass} command associates a scalar variable as a mass with\r\nthe corresponding vector variable, in high-energy physics calculations.\r\n\\begin{Syntax}\r\n\\name{mass} \\meta{vector-var}\\name{=}\\meta{scalar-var}\r\n\\{,\\meta{vector-var}\\name{=}\\meta{scalar-var}\\}\\optional\r\n\\end{Syntax}\r\n\r\n\\meta{vector-var} can be a declared vector variable;  \\name{mass} will declare\r\nit to be of type \\name{vector} if it is not.  This may override an existing\r\nmatrix variable by that name.  \\meta{scalar-var} must be a scalar variable.\r\n\r\n\\begin{Examples}\r\nvector bb,cc; \\\\\r\nmass cc=m; \\\\\r\nmshell cc; \\\\\r\ncc.cc;                            &         M^{2}\r\n\\end{Examples}\r\n\r\n\\begin{Comments}\r\nOnce a mass has been attached to a vector with a \\name{mass} declaration,\r\nthe \\nameref{mshell} declaration puts the associated particle ``on the mass\r\nshell.''  Subsequent scalar (.) products of the vector with itself will be\r\nreplaced by the square of the mass expression.\r\n\\end{Comments}\r\n\\end{Command}\r\n\r\n\r\n\\begin{Command}{MSHELL}\r\nThe \\name{mshell} command puts particles on the mass shell in high-energy\r\nphysics calculations.\r\n\\begin{Syntax}\r\n\\name{mshell} \\meta{vector-var}\\{,\\meta{vector-var}\\}\\optional\r\n\\end{Syntax}\r\n\r\n\\meta{vector-var} must have had a mass attached to it by a \\nameref{mass}\r\ndeclaration.\r\n\r\n\\begin{Examples}\r\nvector v1,v2; \\\\\r\nmass v1=m,v2=q; \\\\\r\nmshell v1; \\\\\r\nv1.v1;                       &            M^{2} \\\\\r\nv2.v2;                       &            V2.V2 \\\\\r\nmshell v2; \\\\\r\nv1.v1*v2.v2;                 &            M^{2}*Q^{2}\r\n\\end{Examples}\r\n\r\n\\begin{Comments}\r\nEven though a mass is attached to a vector variable representing a\r\nparticle, the replacement does not take place until the \\name{mshell}\r\ndeclaration is given for that vector variable.\r\n\\end{Comments}\r\n\\end{Command}\r\n\r\n\r\n\\begin{Declaration}{NOSPUR}\r\nThe \\name{nospur} declaration prevents the trace calculation over the given\r\nline identifiers in high-energy physics calculations.\r\n\\begin{Syntax}\r\n\\name{nospur} \\meta{line-id}\\{,\\meta{line-id}\\}\\optional\r\n\\end{Syntax}\r\n\r\n\r\n\\meta{line-id} is a scalar identifier that will be used as a line identifier.\r\n\r\n\\begin{Examples}\r\nvector a1,b1,c1; \\\\\r\ng(line1,a1,b1)*g(line2,b1,c1);      &     A1.B1*B1.C1 \\\\\r\nnospur line2; \\\\\r\ng(line1,a1,b1)*g(line2,b1,c1);      &     A1.B1*G(LINE2,B1,C1)\r\n\\end{Examples}\r\n\r\n\\begin{Comments}\r\nNospur declarations can be removed by making the declaration \\nameref{spur}.\r\n\\end{Comments}\r\n\\end{Declaration}\r\n\r\n\r\n\\begin{Declaration}{REMIND}\r\nThe \\name{remind} declaration removes the special status of its arguments\r\nas indices, which was set in the \\nameref{index} declaration, in\r\nhigh-energy physics calculations.\r\n\\begin{Syntax}\r\n\\name{remind} \\meta{identifier}\\{,\\meta{identifier}\\}\\optional\r\n\\end{Syntax}\r\n\r\n\\meta{identifier} must have been declared to be of type \\nameref{index}.\r\n\\end{Declaration}\r\n\r\n\r\n\\begin{Declaration}{SPUR}\r\nThe \\name{spur} declaration removes the special exemption from trace\r\ncalculations that was declared by \\nameref{nospur}, in high-energy physics\r\ncalculations.\r\n\\begin{Syntax}\r\n\\name{spur} \\meta{line-id}\\{,\\meta{line-id}\\}\\optional\r\n\\end{Syntax}\r\n\r\n\\meta{line-id} must be a line-identifier that has previously been declared\r\n\\name{nospur}.\r\n\\end{Declaration}\r\n\r\n\r\n\\begin{Command}{VECDIM}\r\nThe command \\name{vecdim} changes the vector dimension from 4 to an arbitrary\r\ninteger or symbol.  Used in high-energy physics calculations.\r\n\\begin{Syntax}\r\n\\name{vecdim} \\meta{dimension}\r\n\\end{Syntax}\r\n\r\n\r\n\\meta{dimension} must be either an integer or a valid scalar identifier that\r\ndoes not have a floating-point value.\r\n\r\n\\begin{Comments}\r\nThe \\nameref{eps} operator and the \\IFTEX{$\\gamma_{5}$}{gamma_5}\r\nsymbol (\\name{A}) are not properly defined in anything except four\r\ndimensions and will print an error message if you use them that way.  The\r\nother high-energy physics operators should work without problem.\r\n\\end{Comments}\r\n\\end{Command}\r\n\r\n\r\n\\begin{Declaration}{VECTOR}\r\nThe \\name{vector} declaration declares that its arguments are of type \\name{vector}.\r\n\\begin{Syntax}\r\n\\name{vector} \\meta{identifier}\\{,\\meta{identifier}\\}\\optional\r\n\\end{Syntax}\r\n\r\n\\meta{identifier} must be a valid REDUCE identifier.  It may have already been\r\nused for a matrix, array, operator or scalar variable.  After an identifier\r\nhas been declared to be a vector, it may not be used as a scalar variable.\r\n\r\n\\begin{Comments}\r\nVectors are special entities for high-energy physics calculations.  You\r\ncannot put values into their coordinates; they do not have coordinates.\r\nThey are legal arguments for the high-energy physics operators\r\n\\nameref{eps}, \\nameref{g} and \\name{.} (dot).  Vector variables are\r\nused to represent gamma matrices and gamma matrices contracted with Lorentz\r\n4-vectors, since there are no Dirac variables per se in the system.\r\nVectors do follow the usual vector rules for arithmetic operations:\r\n\\name{+} and \\name{-} operate upon two or more vectors, producing a\r\nvector; \\name{*} and \\name{/} cannot be used between vectors; the\r\nscalar product is represented by the . operator; and the product of a\r\nscalar and vector expression is well defined, and is a vector.\r\n\r\nYou can represent components of vectors by including representations of unit\r\nvectors in your system.  For instance, letting \\name{E0} represent the unit\r\nvector (1,0,0,0), the command\r\n\r\n\\name{V1.E0 := 0;}\r\n\r\nwould set up the substitution of zero for the first component of the vector\r\n\\name{V1}.\r\n\r\nIdentifiers that are declared by the \\name{index} and \\name{mass} declarations are\r\nautomatically declared to be vectors.\r\n\r\nThe following errors can occur in calculations using the high energy\r\nphysics package:\r\n\r\n\\name{A represents only gamma5 in vector expressions}\r\n\\begin{quote}\r\nYou have tried to use A in some way other than gamma5 in a\r\nhigh-energy physics expression.\r\n\\end{quote}\r\n\r\n\\name{Gamma5 not allowed unless vecdim is 4}\r\n\\begin{quote}\r\nYou have used \\IFTEX{$\\gamma_{5}$}{gamma_5} in a high-energy physics\r\ncomputation involving a vector dimension other than 4.\r\n\\end{quote}\r\n\r\n\\meta{ID} \\name{has no mass}\r\n\\begin{quote}\r\nOne of the arguments to \\nameref{mshell} has had no mass assigned to it, in\r\nhigh-energy physics calculations.\r\n\\end{quote}\r\n\r\n\\name{Missing arguments for G operator}\r\n\\begin{quote}\r\nA line symbol is missing in a gamma matrix expression in high-energy physics\r\ncalculations.\r\n\\end{quote}\r\n\r\n\\name{Unmatched index} \\meta{list}\r\n\\begin{quote}\r\nThe parser has found unmatched indices during the evaluation of a\r\ngamma matrix expression in high-energy physics calculations.\r\n\\end{quote}\r\n\\end{Comments}\r\n\\end{Declaration}\r\n\r\n", "meta": {"hexsha": "796a5e846db7b05f6b4ace3543d9543195569eea", "size": 13795, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "hephys.tex", "max_stars_repo_name": "nilqed/REDHELP", "max_stars_repo_head_hexsha": "0c98a32bf21fa060ccd67ce82f638d6a1bc47a52", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hephys.tex", "max_issues_repo_name": "nilqed/REDHELP", "max_issues_repo_head_hexsha": "0c98a32bf21fa060ccd67ce82f638d6a1bc47a52", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hephys.tex", "max_forks_repo_name": "nilqed/REDHELP", "max_forks_repo_head_hexsha": "0c98a32bf21fa060ccd67ce82f638d6a1bc47a52", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2837837838, "max_line_length": 85, "alphanum_fraction": 0.7068503081, "num_tokens": 3612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3228203603159969}}
{"text": "\\title{Tendon Robot Statics}\n\\author{John Till}\n\\date{}\n\n\\documentclass[12pt]{article}\n\n\\usepackage[a4paper, margin=0.75in]{geometry}\n\\usepackage[colorlinks=true,urlcolor=blue]{hyperref}\n\\usepackage{amsmath,amssymb}\n\\usepackage{graphicx}\n\n\\usepackage{xcolor}\n\\definecolor{OffWhite}{rgb}{0.93,0.93,0.93}\n\\definecolor{QtCommentColor}{rgb}{0,0.5,0}\n\\definecolor{QtKeywordColor}{rgb}{0.5,0.5,0}\n\\definecolor{QtPurpleColor}{rgb}{0.5,0,0.5}\n\\definecolor{QtGlobal}{rgb}{0.808,0.361,0}\n\\definecolor{QtFunctionColor}{rgb}{0,0.404,0.486}\n\\definecolor{BlenderPythonString}{rgb}{0.392,0,0}\n\\definecolor{BlenderPythonKeyword}{rgb}{0.502,0,0.314}\n\\definecolor{BlenderPythonGold}{rgb}{0.373,0.373,0}\n\\definecolor{BlenderPythonLiteral}{rgb}{0,0,0.784}\n\\definecolor{BlenderPythonBackground}{rgb}{0.6,0.6,0.6}\n\n\\usepackage[T1]{fontenc} %for upquotes in listings\n\\usepackage{textcomp} %for upquotes in listings\n\\usepackage{listings}\n\\lstset{\n\t\tlanguage=C++,\n\t\tescapeinside={!-}{-!},\n\t\tupquote=true,\n\t\t%\n\t\totherkeywords={Vector3d, DiagonalMatrix, VectorXd, Matrix3d, Map, MatrixXd, Vector6d, Vector4d,\n\t\t              Matrix6d, Eigen, Upper, std, fstream, Matrix3Xd,\n\t\t\t\t\t\t\t\t\tUnitX, pow, inverse, transpose, segment, data, UnitZ, cross, hat_squared,\n\t\t\t\t\t\t\t\t\that_postmultiply, hat_premultiply,\n\t\t\t\t\t\t\t\t\tZero, Identity, UnitY, cosseratTendonRobotOde, ode4, cols, row, main, shootingFunction,\n\t\t\t\t\t\t\t\t\tblock, rotation_error, solveLevenbergMarquardt, toDenseMatrix,\n\t\t\t\t\t\t\t\t\tselfadjointView, llt, close, kirchhoffTendonRobotOde, cwiseProduct, cwiseMin,\n\t\t\t\t\t\t\t\t\tcwiseMax, getRouting, normalized},\n    morekeywords=[2]{Vector3d, DiagonalMatrix, VectorXd, Matrix3d, Map, MatrixXd, Vector6d, Vector4d,\n\t\t                 Matrix6d, Eigen, Upper, std, fstream, Matrix3Xd},\n\t\tmorekeywords=[3]{UnitX, UnitZ, pow, inverse, transpose, segment, data, cross, hat_squared,\n\t\t                 hat_postmultiply, hat_premultiply,\n\t\t                 Zero, Identity, UnitY, cosseratTendonRobotOde, ode4, cols, row, main, shootingFunction,\n\t\t\t\t\t\t\t\t\t\t block, rotation_error, solveLevenbergMarquardt, toDenseMatrix,\n\t\t\t\t\t\t\t\t\t\t selfadjointView, llt, close, kirchhoffTendonRobotOde, cwiseProduct, cwiseMin,\n\t\t\t\t\t\t\t\t\t\t cwiseMax, getRouting, normalized},\n    %\n\t\tframe = single,\n\t\trulecolor=\\color{black},\n    tabsize=4, % tab space width\n    showstringspaces=false, % don't mark spaces in strings\n\t\t%\n\t\tbasicstyle=\\footnotesize,%\\color{QtIdentifier},\n\t\tbackgroundcolor=\\color{OffWhite},\n    commentstyle=\\color{QtCommentColor}, % comment color\n    keywordstyle=\\color{QtKeywordColor}, % keyword color\n\t\tkeywordstyle=[2]{\\color{QtPurpleColor}},\n\t\tkeywordstyle=[3]{\\color{QtFunctionColor}},\n    stringstyle=\\color{QtCommentColor} % string color\n}\n\n\\begin{document}\n\n\\makeatletter\n\\renewcommand{\\@maketitle}{\n\\newpage\n\\null\n\\vskip 2em\n\\begin{center}\n{\\LARGE \\@title \\par}\n\\end{center}\n\\par\n} \\makeatother\n\n\\maketitle\n\n\\section{Tendon Robot Model in C++}\n\nThis example shows how to implement the tendon robot model from the paper \\href{https://ieeexplore.ieee.org/document/5957337}{``Statics and Dynamics of Continuum Robots With General Tendon Routing and External Loading''}, which is also described in Chapter 4 of the dissertation \\href{https://etd.library.vanderbilt.edu//available/etd-10042011-115347/}{``The Mechanics of Continuum Robots: Model-based Sensing and Control''}.\n\nAt the top of the C++ script, we start with the simple independent parameters:\n\\begin{lstlisting}\n//Independent Parameters\nconst double E = 200e9;\nconst double G = 80e9;\nconst double rad = 0.001;\nconst double rho = 8000;\nconst Vector3d g = 9.81*Vector3d::UnitX();\nconst double L = 0.5;\nconst int num_tendons = 4;\n\\end{lstlisting}\nThese are straightforward. However, the independent parameters also include the tendon routing paths. The journal paper considers general routing paths with offsets given by the functions $\\boldsymbol{r}_i(s)$ for $1 \\leq i \\leq$ num\\_tendons, as well as derivatives $\\dot{\\boldsymbol{r}}_i(s)$ and $\\ddot{\\boldsymbol{r}}_i(s)$. Tendons are often routed parallel to the backbone, and simulations involving functions as design parameters tend to be a bit complicated, so for now we'll assume there is no dependence on $s$ so that $\\boldsymbol{r}_i$ is constant. We implement this in C++ for four tendons spaced $90^\\circ$ apart:\n\\begin{lstlisting}\nconst double tendon_offset = 0.01506;\n#define R(theta) (tendon_offset*Vector3d(!-\\textcolor{QtFunctionColor}{cos}-!(theta), !-\\textcolor{QtFunctionColor}{sin}-!(theta), 0))\nconst Vector3d r[num_tendons] = {R(0), R(pi/2), R(pi), R(pi*3/2)};\n#undef R\n\\end{lstlisting}\nWe define a macro function ``R'' which makes it easier to initialize the array ``r'' with vectors spaced $90^\\circ$ apart. We immediately undefine the macro so that we can use the symbol ``R'' in the future without accidently invoking the macro. Now there is just one more independent parameter; the input to the forward kinematics problem is the tension in each tendon:\n\\begin{lstlisting}\nconst VectorXd tau = Vector4d(15,0,0,0);\n\\end{lstlisting}\nWe set $\\tau_1 = 15$N and $\\tau_2 = \\tau_3 = \\tau_4 = 0$N.\nWith the independent parameters set, there are several dependent parameter calculations:\n\\begin{lstlisting}\n//Dependent parameter calculations\nconst double area = pi*pow(rad,2);\nconst double I = pi*pow(rad,4)/4;\nconst double J = 2*I;\nconst DiagonalMatrix<double, 3> Kse (G*area,G*area,E*area);\nconst DiagonalMatrix<double, 3> Kbt (E*I,E*I,G*J);\nconst Matrix3d Kse_dense = Kse.toDenseMatrix();\nconst Matrix3d Kbt_dense = Kbt.toDenseMatrix();\n\\end{lstlisting}\nThere is some redundancy in the stiffness matrices; we have both dense and diagonal data structures so that we can use either representation without making a conversion.\n\nThe core of the model is the ODE function. The state variables are $\\boldsymbol{p}$, $\\boldsymbol{R}$, $\\boldsymbol{v}$, and $\\boldsymbol{u}$. At the start of the ODE function we unpack the state vector:\n\\newpage\n\\begin{lstlisting}\nvoid cosseratTendonRobotOde(VectorXd& y_s_out, VectorXd& y){\n    //Unpack state vector\n    Matrix3d R = Map<Matrix3d>(&y[3]);\n    Vector3d v = Map<Vector3d>(&y[12]);\n    Vector3d u = Map<Vector3d>(&y[15]);\n\\end{lstlisting}\nThe paper describes how one must solve a linear system to find $\\dot{\\boldsymbol{v}}$ and $\\dot{\\boldsymbol{u}}$. We declare the variables to setup this system:\n\\begin{lstlisting}\nVector3d a = Vector3d::Zero();\nVector3d b = Vector3d::Zero();\nMatrix3d A_plus_Kse = Kse_dense; = Kse_dense;\nMatrix3d G = Matrix3d::Zero();\nMatrix3d H_plus_Kbt = Kbt_dense;\n\\end{lstlisting}\nIn Equation (16) of the paper, the left-hand side coefficient matrix is given by\n\\begin{align*}\n\\begin{bmatrix}\n\\boldsymbol{K}_{se} + \\boldsymbol{A} & \\boldsymbol{G} \\\\ \\boldsymbol{G}^T & \\boldsymbol{K}_{bt} + \\boldsymbol{H}\n\\end{bmatrix}.\n\\end{align*}\nFor the program, it makes sense to roll $\\boldsymbol{K}_{se} + \\boldsymbol{A}$ into a single variable, and likewise for $\\boldsymbol{K}_{bt} + \\boldsymbol{H}$. Then we sum the variables as described just before Equation (15):\n\\begin{lstlisting}\nfor(int i = 0; i < num_tendons; i++){\n    Vector3d pb_si = u.cross(r[i]) + v;\n    double pb_s_norm = pb_si.!-\\textcolor{QtFunctionColor}{norm}-!();\n    Matrix3d A_i = -hat_squared(pb_si)*(tau(i)/pow(pb_s_norm,3));\n    Matrix3d G_i = -hat_postmultiply(A_i,r[i]);\n    Vector3d a_i = A_i*(u.cross(pb_si));\n\n    a += a_i;\n    b += r[i].cross(a_i);\n    A_plus_Kse += A_i;\n    G += G_i;\n    H_plus_Kbt += hat_premultiply(r[i],G_i);\n}\n\\end{lstlisting}\nAfter the summation in this loop, the variables will have the correct values. The smaller components are combined to setup the linear system coefficient matrix:\n\\begin{lstlisting}\nMatrix6d K;\nK << A_plus_Kse, G, G.transpose(), H_plus_Kbt;\n\\end{lstlisting}\nThe right-hand side ``rhs'' is given just before Equation (16), and we construct the vector:\n\\begin{lstlisting}\nVector3d nb = Kse*(v - Vector3d::UnitZ());\nVector3d mb = Kbt*u;\n\nVector6d rhs;\nrhs << -u.cross(nb) - !-\\textcolor{QtFunctionColor}{transposeMultiply}-!(R,rho*area*g) - a,\n       -u.cross(mb) - v.cross(nb) - b;\n\\end{lstlisting}\nWe solve for the body frame internal force and moment as intermediate variables before setting the right-hand side values. This is partially to recognize physically relevant terms, but also to avoid repeated calculations of ``nb''.\n\n\\newpage \\noindent\nWith the linear system setup, we are positioned to complete the ODE function by solving for the derivatives:\n\\begin{lstlisting}\n    //Pack state vector derivative\n    Map<Vector3d> p_s(&y_s_out[0]);\n    Map<Matrix3d> R_s(&y_s_out[3]);\n    Map<Vector6d> vs_and_us(&y_s_out[12]);\n\n    //ODEs\n    p_s = R*v;\n    R_s = hat_postmultiply(R,u);\n    vs_and_us = K.selfadjointView<Eigen::Upper>().llt().!-\\textcolor{QtFunctionColor}{solve}-!(rhs);\n}\n\\end{lstlisting}\nOne of Eigen's linear solvers is used to solve the 6x6 linear system. The ``selfadjointView'' takes advantage of the symmetry of ``K''.\n\nAfter the ODE function, we move on to the shooting method's objective function. At the top of the function we unpack the guess:\n\\begin{lstlisting}\nstatic MatrixXd Y; //Declare Y global to save results\nVectorXd shootingFunction(VectorXd guess){\n    Vector3d n0 = guess.segment<3>(0);\n    Vector3d v0 = Kse.inverse()*n0 + Vector3d::UnitZ();\n    Vector3d u0 = guess.segment<3>(3);\n\\end{lstlisting}\nOne of the unknown state variables is $\\boldsymbol{v}(0)$, but we guess $\\boldsymbol{n}(0)$ and solve for $\\boldsymbol{v}(0)$ since I suspect this will lead to better \\emph{numerical conditioning} of the objective function. Next we integrate the tendon robot ODE:\n\\begin{lstlisting}\nVectorXd y0(18);\ny0 << p0, Map<VectorXd>(Matrix3d(R0).data(), 9), v0, u0;\n\n//Numerically integrate the Cosserat rod equations\nY = ode4<cosseratTendonRobotOde>(y0, L);\n\\end{lstlisting}\nOnce the integration is done, we can find the violation of the static equilibrium equations. There are forces acting on the final disk from the backbone and tendon attachment points. We extract the internal force in the backbone:\n\\begin{lstlisting}\n//Find the internal forces in the backbone prior to the final plate\nVector3d vL = Y.block<3,1>(12,Y.cols()-1);\nVector3d uL = Y.block<3,1>(15,Y.cols()-1);\n\nVector3d nb = Kse*(vL - Vector3d::UnitZ());\nVector3d mb = Kbt*uL;\n\\end{lstlisting}\nThen we sum the forces and moments acting on the plate, starting with the backbone, then looping over the tendons:\n\\begin{lstlisting}\n//Find the equilibrium error at the tip, considering tendon forces\nVector3d force_error = -nb;\nVector3d moment_error = -mb;\nfor(int i = 0; i < num_tendons; i++){\n    Vector3d pb_si = uL.cross(r[i]) + vL;\n    Vector3d Fb_i = -tau(i)*pb_si.normalized();\n    force_error += Fb_i;\n    moment_error += r[i].cross(Fb_i);\n}\n\\end{lstlisting}\nThe tendon loading terms are given by Equations (18), (19), and (20). Finally we complete the objective function by returning a single error vector:\n\\begin{lstlisting}\n    Vector6d distal_error;\n    distal_error << force_error, moment_error;\n\n    return distal_error;\n}\n\\end{lstlisting}\n\nWith the objective function complete, we are finally ready to write the simulation driver. Over in the main function, the problem is solved in just a few lines:\n\\begin{lstlisting}\nint main(int, char**){\n    Vector6d init_guess = Vector6d::Zero(); //nb and u\n\n    //Solve with shooting method\n    VectorXd wrench_soln = solveLevenbergMarquardt<shootingFunction>\n                               (init_guess, 1e-12, 500, 1e-2, 0.5, 1e-7, 1e-9);\n\\end{lstlisting}\nThe solver uses finite differences to build the Jacobian, and the default finite difference increments are too small. Thus we specify all the parameters for the ``solveLevenbergMarquardt'' function to use larger increments. With the problem solved, the results should be visualized. I think it can be difficult to understand tendon robot behavior from simple line plots, so we'll generate a render of the robot instead. The backbone curve, tendon curves, and full pose at nine points along the backbone are saved to text files:\n\\begin{lstlisting}\n    //Save results for Blender visualization\n    std::fstream file(\"centerline.dat\", std::fstream::out);\n    file << Y.block(0,0,3,Y.cols());\n    file.close();\n\n    MatrixXd tendonlines(3*num_tendons, Y.cols());\n    for(int i = 0; i < Y.cols(); i++){\n        Vector3d p = Y.block<3,1>(0,i);\n        Matrix3d R = Map<Matrix3d>(&Y(3,i));\n        for(int j = 0; j < num_tendons; j++)\n            tendonlines.block<3,1>(3*j,i) = p + R*r[j];\n    }\n    file = std::fstream(\"tendonlines.dat\", std::fstream::out);\n    file << tendonlines;\n    file.close();\n\t\t\n    const int num_disks = 9;\n    Matrix3Xd disks(3,4*num_disks);\n    for(int i = 1; i <= num_disks; i++){\n        int j = ((Y.cols()-1) * i) / num_disks;\n        Vector3d p = Y.block<3,1>(0,j);\n        Matrix3d R = Map<Matrix3d>(&Y(3,j));\n        disks.block<3,3>(0,4*(i-1)) = R;\n        disks.block<3,1>(0,4*(i-1)+3) = p;\n    }\n    file = std::fstream(\"disks.dat\", std::fstream::out);\n    file << disks;\n    file.close();\n\n    return 0;\n}\n\\end{lstlisting}\nRunning the C++ script should produce three files ``centerline.dat'', ``tendonlines.dat'', and ``disk.dat''. These files will be located in the active directory the program is run from, which by default is a build folder when using Qt.\n\n\\section{Visualization with Blender}\n\nOne of the nice features of Blender is that in addition to using the user interface, you can also perform modeling tasks using Python scripts. This is perfect for generating 3d models from simulation results.\n\nThe output text files should be moved to the Blender subfolder. The Python script to render the tendon robot is contained in ``Tendon\\_Robot\\_Render.blend''. Upon opening the file with Blender, the Python scripting pane will be in the upper left. There is a ``Run Script'' button on the bottom right of the pane as shown below:\n\\begin{figure}[h]\n\t\\centering\n\t\t\\includegraphics[width=0.95\\textwidth]{fig/ScriptingPane.jpg}\n\t\\label{fig:Pane}\n\\end{figure}\n\n\\noindent\nRunning this script with the text files present will cause a render of the robot to be saved to the ``output'' subfolder:\n\\begin{figure}[h]\n\t\\centering\n\t\t\\includegraphics[width=0.8\\textwidth]{fig/TendonRobotRender.jpg}\n\\end{figure}\n\n\\noindent Applying a tension on the first tendon has caused the backbone to bend, exactly as we would expect. Since the distributed weight of the backbone is not very large, the backbone curve nearly has a constant curvature.\n\n\\lstset{\n\t\tlanguage=Python,\n\t\tescapeinside={!-}{-!},\n\t\t%\n\t\tdeletekeywords={def, type, object, range, len, int},\n\t\totherkeywords={def, True, False, type, object, range, len},\n\t\tmorekeywords=[2]{def},\n\t\tmorekeywords=[3]{True, False, type, object, range, len},\n\t\t%\n\t\tframe = single,\n\t\trulecolor=\\color{black},\n    tabsize=4, % tab space width\n    showstringspaces=false, % don't mark spaces in strings\n\t\t%\n\t\tbasicstyle=\\footnotesize,%\\color{QtIdentifier},\n\t\t%backgroundcolor=\\color{BlenderPythonBackground},\n    %commentstyle=\\color{QtCommentColor}, % comment color\n    keywordstyle=\\color{BlenderPythonKeyword}, % keyword color\n\t\tkeywordstyle=[2]{\\color{BlenderPythonGold}},\n\t\tkeywordstyle=[3]{\\color{BlenderPythonLiteral}},\n    stringstyle=\\color{BlenderPythonString}, % string color\n\t\tliterate={0}{{\\textcolor{BlenderPythonLiteral}{0}}}{1}%\n             {1}{{\\textcolor{BlenderPythonLiteral}{1}}}{1}%\n             {2}{{\\textcolor{BlenderPythonLiteral}{2}}}{1}%\n             {3}{{\\textcolor{BlenderPythonLiteral}{3}}}{1}%\n             {4}{{\\textcolor{BlenderPythonLiteral}{4}}}{1}%\n             {5}{{\\textcolor{BlenderPythonLiteral}{5}}}{1}%\n             {6}{{\\textcolor{BlenderPythonLiteral}{6}}}{1}%\n             {7}{{\\textcolor{BlenderPythonLiteral}{7}}}{1}%\n             {8}{{\\textcolor{BlenderPythonLiteral}{8}}}{1}%\n             {9}{{\\textcolor{BlenderPythonLiteral}{9}}}{1}%\n             {.0}{{\\textcolor{BlenderPythonLiteral}{.0}}}{2}% Following is to ensure that only periods\n             {.1}{{\\textcolor{BlenderPythonLiteral}{.1}}}{2}% followed by a digit are changed.\n             {.2}{{\\textcolor{BlenderPythonLiteral}{.2}}}{2}%\n             {.3}{{\\textcolor{BlenderPythonLiteral}{.3}}}{2}%\n             {.4}{{\\textcolor{BlenderPythonLiteral}{.4}}}{2}%\n             {.5}{{\\textcolor{BlenderPythonLiteral}{.5}}}{2}%\n             {.6}{{\\textcolor{BlenderPythonLiteral}{.6}}}{2}%\n             {.7}{{\\textcolor{BlenderPythonLiteral}{.7}}}{2}%\n             {.8}{{\\textcolor{BlenderPythonLiteral}{.8}}}{2}%\n             {.9}{{\\textcolor{BlenderPythonLiteral}{.9}}}{2}%\n\t\t\t\t\t\t {type}{type}{4}%\n\t\t\t\t\t\t {object}{object}{6}%\n\t\t\t\t\t\t {range}{range}{5}%\n\t\t\t\t\t\t {len}{len}{3}%\n\t\t\t\t\t\t {int}{int}{3}%\n\t\t\t\t\t\t {format}{format}{6}%\n}\n\nWe won't get into the details of the different parts of the Blender Python script here. The script is given in whole below to close out the example:\n\\begin{lstlisting}\nimport bpy\nfrom bpy import context\nimport numpy as np\nimport mathutils\nfrom mathutils import Matrix, Vector\nimport os\n\ndef drawDisk(p,R):\n    rotm = Matrix(R)\n    (x_base, y_base, z_base) = Vector(p) + rotm * Vector((0, 0, -0.001/2))\n    (x_top, y_top, z_top) = Vector(p) + rotm * Vector((0, 0, 0.001/2))\n    \t\n    #Curve settings\n    curveData = bpy.data.curves.new('myCurve', type='CURVE')\n    curveData.dimensions = '!-\\textcolor{BlenderPythonString}{3D}-!'\n    curveData.resolution_u = 2\n    polyline = curveData.splines.new('POLY')\n    polyline.points.add(1)\n    polyline.points[0].co = (x_base, y_base, z_base, 1)\n    polyline.points[1].co = (x_top, y_top, z_top, 1)\n\n    cross_section = bpy.ops.curve.primitive_bezier_circle_add(radius=0.017)\n    ob = bpy.context.object\n    ob.name = 'cross_section_disk'\n\n    curveOB = bpy.data.objects.new('myCurve', curveData)\n    scn = bpy.context.scene\n    scn.objects.link(curveOB)\n    scn.objects.active = curveOB\n    curveOB.select = True\n    curveOB.data.bevel_object = bpy.data.objects['cross_section_disk']\n    curveOB.data.use_fill_caps = True\n    \n    mat = bpy.data.materials.new(\"RGBA\")\n    mat.use_transparency = True;\n    mat.diffuse_color = (79/255.0, 41/255.0, 132/255.0)\n    mat.alpha = 1;\n    curveOB.active_material = mat\n\ndef drawRod(p):\n    (rows,cols) = p.shape\n\n    #Curve settings\n    curveData = bpy.data.curves.new('tCurve', type='CURVE')\n    curveData.dimensions = '!-\\textcolor{BlenderPythonString}{3D}-!'\n    curveData.resolution_u = 2\n    polyline = curveData.splines.new('POLY')\n    polyline.points.add(cols-1)\n        \n    cross_section = bpy.ops.curve.primitive_bezier_circle_add(radius=0.001)\n    ob = bpy.context.object\n    ob.name = 'tcross_section'\n\n    #Loop through spatial steps\n    for i in range(0,cols):\n    \tx,y,z = p[0,i], p[1,i], p[2,i]\n    \tpolyline.points[i].co = (x, y, z, 1)\n            \n    curveOB = bpy.data.objects.new('myCurve', curveData)\n    scn = bpy.context.scene\n    scn.objects.link(curveOB)\n    scn.objects.active = curveOB\n    curveOB.select = True\n    curveOB.data.bevel_object = bpy.data.objects['tcross_section']\n    curveOB.data.use_fill_caps = True\n    \ndef drawTendon(p):\n    (rows,cols) = p.shape\n\n    #Curve settings\n    curveData = bpy.data.curves.new('tCurve', type='CURVE')\n    curveData.dimensions = '!-\\textcolor{BlenderPythonString}{3D}-!'\n    curveData.resolution_u = 2\n    polyline = curveData.splines.new('POLY')\n    polyline.points.add(cols-1)\n        \n    cross_section = bpy.ops.curve.primitive_bezier_circle_add(radius=0.0003)\n    ob = bpy.context.object\n    ob.name = 'tcross_section_tendon'\n\n    #Loop through spatial steps\n    for i in range(0,cols):\n    \tx,y,z = p[0,i], p[1,i], p[2,i]\n    \tpolyline.points[i].co = (x, y, z, 1)\n            \n    curveOB = bpy.data.objects.new('myCurve', curveData)\n    scn = bpy.context.scene\n    scn.objects.link(curveOB)\n    scn.objects.active = curveOB\n    curveOB.select = True\n    curveOB.data.bevel_object = bpy.data.objects['tcross_section_tendon']\n    curveOB.data.use_fill_caps = True\n    \n    mat = bpy.data.materials.new(\"RGBA\")\n    mat.use_transparency = True;\n    mat.diffuse_color = (255/255.0, 221/255.0, 0)\n    mat.alpha = 1;\n    curveOB.active_material = mat\n    \n### MAIN ###\nscript_dir = os.getcwd() #<-- absolute path of dir the script is in\nbpy.context.scene.world.horizon_color = (1,1,1) #white background\nscene = bpy.data.scenes[\"Scene\"]\nscene.render.resolution_x = 1280*2\nscene.render.resolution_y = 720*2\n\n#Load data\ncenterline = np.loadtxt( os.path.join(script_dir, 'centerline.dat'))\ntendonlines = np.loadtxt( os.path.join(script_dir, 'tendonlines.dat'))\ndisks = np.loadtxt( os.path.join(script_dir, 'disks.dat'))\nnum_disks = int(disks.shape[1]/4);\nnum_tendons = int(tendonlines.shape[0]/3);\n\n#Delete objects already in the scene\nfor item in bpy.data.objects:\n    if item.type == 'MESH' or item.type=='CURVE':\n        item.select = True\n        bpy.ops.object.delete()\n\n#Create the render\ndrawRod(centerline)\nfor i in range(0,num_tendons):\n    drawTendon(tendonlines[3*i:3*(i+1), 0:tendonlines.shape[1]])\nfor i in range(0,num_disks):\n    drawDisk(disks[0:3,4*i+3], disks[0:3,4*i:4*i+3])\n\nrel_path = 'output/TendonRobotRender.jpg'\nabs_file_path = os.path.join(script_dir, rel_path)\nbpy.data.scenes[\"Scene\"].render.filepath = abs_file_path\nbpy.ops.render.render( animation=False, write_still=True )\n\\end{lstlisting}\n\n\\end{document}", "meta": {"hexsha": "573020b4eb02c592fb375121125ba90f9d23092c", "size": 21266, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "01_Statics/05_Tendon_Robot/LaTeX/TendonRobotStatics.tex", "max_stars_repo_name": "matthiastummers/ContinuumRobotExamples", "max_stars_repo_head_hexsha": "2575fa71075c8867f7be78c112695de2f9b6c403", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 73, "max_stars_repo_stars_event_min_datetime": "2019-03-21T04:59:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T18:44:50.000Z", "max_issues_repo_path": "01_Statics/05_Tendon_Robot/LaTeX/TendonRobotStatics.tex", "max_issues_repo_name": "matthiastummers/ContinuumRobotExamples", "max_issues_repo_head_hexsha": "2575fa71075c8867f7be78c112695de2f9b6c403", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2019-04-23T18:22:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T07:05:29.000Z", "max_forks_repo_path": "01_Statics/05_Tendon_Robot/LaTeX/TendonRobotStatics.tex", "max_forks_repo_name": "matthiastummers/ContinuumRobotExamples", "max_forks_repo_head_hexsha": "2575fa71075c8867f7be78c112695de2f9b6c403", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28, "max_forks_repo_forks_event_min_datetime": "2019-04-02T04:01:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T06:59:02.000Z", "avg_line_length": 43.9380165289, "max_line_length": 627, "alphanum_fraction": 0.7005078529, "num_tokens": 6240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.32279637166924086}}
{"text": "%\n%\n%  This file is inserted in the file Segmentation.tex\n%\n%\n\n\\subsection{Overview}\n\\label{sec:AboutWatersheds}\n\\index{Watersheds}\n\\index{Watersheds!Overview}\nWatershed segmentation classifies pixels into regions using gradient descent on\nimage features and analysis of weak points along region boundaries.  Imagine\nwater raining onto a landscape topology and flowing with gravity to collect in\nlow basins.  The size of those basins will grow with increasing amounts of\nprecipitation until they spill into one another, causing small basins to merge\ntogether into larger basins.  Regions (catchment basins) are formed by using\nlocal geometric structure to associate points in the image domain with local\nextrema in some feature measurement such as curvature or gradient magnitude.\nThis technique is less sensitive to user-defined thresholds than classic\nregion-growing methods, and may be better suited for fusing different types of\nfeatures from different data sets.  The watersheds technique is also more\nflexible in that it does not produce a single image segmentation, but rather a\nhierarchy of segmentations from which a single region or set of regions can be\nextracted a-priori, using a threshold, or interactively, with the help of a\ngraphical user interface\n\\cite{Yoo1992,Yoo1991}.\n\nThe strategy of watershed segmentation is to treat an image $f$ as a height\nfunction, i.e.,  the surface formed by graphing $f$ as a function of its\nindependent parameters, $\\vec{x} \\in U$.  The image $f$ is often not the\noriginal input data, but is derived from that data through some filtering,\ngraded (or fuzzy) feature extraction, or fusion of feature maps from different\nsources.  The assumption is that higher values of $f$ (or $-f$) indicate the\npresence of boundaries in the original data.  Watersheds may therefore be\nconsidered as a final or intermediate step in a hybrid segmentation method,\nwhere the initial segmentation is the generation of the edge feature map.\n\nGradient descent associates regions with local minima of $f$ (clearly interior\npoints) using the watersheds of the graph of $f$, as in\nFigure~\\ref{fig:segment}.\n\\begin{figure}\n\\centering\n\\includegraphics[width=0.9\\textwidth]{WatershedCatchmentBasins.eps}\n\\itkcaption[Watershed Catchment Basins]{A fuzzy-valued boundary map, from an image\n  or set of images, is segmented using local minima and catchment basins.}\n\\protect\\label{fig:segment}\n\\end{figure}\nThat is, a segment consists of all points in $U$ whose paths of steepest\ndescent on the graph of $f$ terminate at the same minimum in $f$.  Thus, there\nare as many segments in an image as there are minima in $f$.  The segment\nboundaries are ``ridges'' \\cite{Koenderink1979,Koenderink1993,Eberly1996} in\nthe graph of $f$.  In the 1D case ($U \\subset \\Re$), the watershed boundaries\nare the local maxima of $f$, and the results of the watershed segmentation is\ntrivial.  For higher-dimensional image domains, the watershed boundaries are\nnot simply local phenomena; they depend on the shape of the entire watershed.\n\nThe drawback of watershed segmentation is that it produces a region for each\nlocal minimum---in practice too many regions---and an over segmentation\nresults.  To alleviate this, we can establish a minimum watershed depth.  The\nwatershed depth is the difference in height between the watershed minimum and\nthe lowest boundary point.  In other words, it is the maximum depth of water\na region could hold without flowing into any of its neighbors.  Thus, a\nwatershed segmentation algorithm can sequentially combine watersheds whose\ndepths fall below the minimum until all of the watersheds are of sufficient\ndepth.  This depth measurement can be combined with other saliency\nmeasurements, such as size.  The result is a segmentation containing regions\nwhose boundaries and size are significant.  Because the merging process is\nsequential, it produces a hierarchy of regions, as shown in\nFigure~\\ref{fig:watersheds}.\n\\begin{figure}\n\\centering\n\\includegraphics[width=0.9\\textwidth]{WatershedsHierarchy.eps}\n\\itkcaption[Watersheds Hierarchy of Regions]{A watershed segmentation combined\nwith a saliency measure (watershed depth) produces a hierarchy of regions.\nStructures can be derived from images by either thresholding the saliency\nmeasure or combining subtrees within the hierarchy.}\n\\protect\\label{fig:watersheds}\n\\end{figure}\nPrevious work has shown the benefit of a user-assisted approach that provides\na graphical interface to this hierarchy, so that a technician can quickly move\nfrom the small regions that lie within an area of interest to the union of\nregions that correspond to the anatomical structure \\cite{Yoo1991}.\n\nThere are two different algorithms commonly used to implement watersheds:\ntop-down and bottom-up.  The top-down, gradient descent strategy was chosen for\nITK because we want to consider the output of multi-scale differential\noperators, and the $f$ in question will therefore have floating point\nvalues. The bottom-up strategy starts with seeds at the local minima in the\nimage and grows regions outward and upward at discrete intensity levels\n(equivalent to a sequence of morphological operations and sometimes called {\\em\nmorphological watersheds} \\cite{Serra1982}.) This limits the accuracy by\nenforcing a set of discrete gray levels on the image.\n\n\\begin{figure}\n\\centering\n\\includegraphics[width=0.9\\textwidth]{WatershedImageFilter.eps}\n\\itkcaption[Watersheds filter composition]{The construction\nof the Insight watersheds filter.}\n\\protect\\label{fig:constructionWatersheds}\n\\end{figure}\n\nFigure~\\ref{fig:constructionWatersheds} shows how the ITK image-to-image\nwatersheds filter is constructed.  The filter is actually a collection of\nsmaller filters that modularize the several steps of the algorithm in a\nmini-pipeline.  The segmenter object creates the initial segmentation via\nsteepest descent from each pixel to local minima. Shallow background regions\nare removed (flattened) before segmentation using a simple minimum value\nthreshold (this helps to minimize oversegmentation of the image).  The\ninitial segmentation is passed to a second sub-filter that generates a\nhierarchy of basins to a user-specified maximum watershed depth.  The\nrelabeler object at the end of the mini-pipeline uses the hierarchy and the\ninitial segmentation to produce an output image at any scale {\\em below} the\nuser-specified maximum.  Data objects are cached in the mini-pipeline so that\nchanging watershed depths only requires a (fast) relabeling of the basic\nsegmentation.  The three parameters that control the filter are shown in\nFigure~\\ref{fig:constructionWatersheds} connected to their relevant\nprocessing stages.\n\n\\subsection{Using the ITK Watershed Filter}\n\\label{sec:UsingWatersheds}\n\\index{Watersheds!ImageFilter}\n\\input{WatershedSegmentation.tex}\n\n%\\subsection{Interpreting the Results}\n%\\label{sec:VisualizingWatersheds}\n%\\index{Watersheds!Visualization}\n%In order to interpret the output of the Insight watersheds algorithm, it is\n%important to understand what the output represents and how it is formatted. The\n%itk::WatershedImageFilter produces an image of unsigned long integers.  Each\n%integer number is a label for a unique segmented region (catchment basin) from\n%the original input.  The output is the same size and dimensionality of the\n%input.\n\n%Because the segmented image may have potentially many thousands of labels, some\n%care must be taken when visualizing the data or information may be lost.  One\n%effective way to visualize the output is to map the integer labels into\n%distinct RGB colors.  Because labels close in value tend to also be close\n%spatially in the image, it is helpful to spread sequential label values far\n%apart in the RGB range.  A hashing scheme that puts more weight on the\n%least-significant integer bits is a good way to accomplish this.\n%Figure~\\ref{fig:colorVisWatersheds} shows a slice taken from a segmentation of\n%a section of abdomen from the Visible Female Cryosection data.  The unsigned\n%long label values of the output have been hashed into RGB colors.\n\n%\\begin{figure}\n%\\centering\n%\\includegraphics[width=.95\\textwidth]{WatershedAbdomenSegmentation.eps}\n%\\itkcaption[Watershed segmentation of visible woman data]{A slice from a\n%segmentation of Visible Female cryosection data.\n%The original is shown at the left and the segmented image is shown to the\n%right. Colored regions in the segmented image correspond to structures in the\n%original data. }\n%\\protect\\label{fig:colorVisWatersheds}\n%\\end{figure}\n\n%For volumetric data, it is often interesting to create a surface rendering of\n%one or more regions in the output.  This can be done by thresholding the\n%region(s) of interest from the output image and exporting the result to a\n%visualization package capable of isosurface rendering.  Thresholding can be\n%done either by explicit manipulation of the image values through an ITK image\n%iterator, or using one of the several Insight image thresholding filters.\n\n%Figure~\\ref{fig:surfaceRenderingWatersheds} is a surface rendering of the right\n%eye, the optic nerve and chiasm, the lens of the eye, and the right lateral\n%rectus muscle.  A slice from the original Visible Female head and neck\n%cryosection data from which the segmentations were created is shown at the\n%left.  This image was created as described above by thresholding isovalues in a\n%watershed segmentation output and then rendered using third-party visualization\n%software.\n\n%\\begin{figure}\n%\\centering\n%\\includegraphics[width=0.95\\textwidth]{WatershedRendering.eps}\n%\\itkcaption[Watershed segmenation visualization]{A surface rendering (right)\n%of four anatomical structures in the Visible\n%Female head and neck. A slice of the data from which the segmentation was\n%created is shown at the left.  The right and left optic nerves and chiasm are\n%shown in yellow.  The right eye is in transparent purple.  The lens is dark\n%purple.  The structure in red is the lateral rectus muscle.}\n%\\protect\\label{fig:surfaceRenderingWatersheds}\n%\\end{figure}\n\n", "meta": {"hexsha": "a877b7b02fc9670e438421541d2b6c6b9da06de1", "size": 10039, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Documentation/SoftwareGuide/Latex/Watersheds.tex", "max_stars_repo_name": "xcorail/OTB", "max_stars_repo_head_hexsha": "092a93654c3b5d009e420f450fe9b675f737cdca", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-02-13T14:48:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-03T02:54:28.000Z", "max_issues_repo_path": "Documentation/SoftwareGuide/Latex/Watersheds.tex", "max_issues_repo_name": "xcorail/OTB", "max_issues_repo_head_hexsha": "092a93654c3b5d009e420f450fe9b675f737cdca", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2015-10-14T10:11:38.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-15T08:26:23.000Z", "max_forks_repo_path": "Documentation/SoftwareGuide/Latex/Watersheds.tex", "max_forks_repo_name": "xcorail/OTB", "max_forks_repo_head_hexsha": "092a93654c3b5d009e420f450fe9b675f737cdca", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2015-10-08T12:04:06.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-19T08:00:47.000Z", "avg_line_length": 54.8579234973, "max_line_length": 82, "alphanum_fraction": 0.8064548262, "num_tokens": 2381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.3227963716692408}}
{"text": "\n\n\n% ====================================================================\n\\chapter{Introduction}\n\\label{sec:Introduction}\n\n% --------------------------------------------------------------------\n\\section{Purpose}\n\\label{sec:Purpose}\n\nDescribe the purpose for this algorithm.\n\n% ====================================================================\n\\chapter{Algorithm Details}\n\\label{sec:AlgorithmDetails}\n\n% --------------------------------------------------------------------\n\\section{Algorithm Overview}\n\\label{sec:AlgorithmOverview}\n\nInclude an overview of the algorithm from a black box level.\nDescribe how the algorithm is related to other algorithms.\n\n% --------------------------------------------------------------------\n\\subsection{Algorithm Inputs}\n\\label{sec:AlgorithmInputs}\n\nDescribe any inputs that the algorithm uses to make\ncalculations from. Inputs are summarized in \\autoref{tab:CCddd-input}.\n\n\\begin{table}\n  \\centering\n  \\caption{Input information for CCddd.}\n  \\label{tab:CCddd-input}\n  \\begin{CCInOutTable}\n    % Five (5) columns\n    % symbol & description & unit & range & notes \\\\\n    $m$ % mathematical symbol\n    & mass % short description\n    & \\si{\\kilo\\gram} % dimension of quantity\n    & $\\mathbb{R} \\in (-\\infty, \\infty)$ % math-valid range\n    & {}\\footnote{Technically this is the \\emph{intertial} mass as opposed to gravitational mass.}\\footnote{Negative mass is allowed by the mathematics so it is not an error. However, since negative inertial mass often yields physical paradoxes it is worth a warning.} % notes\n    \\\\%\n    $\\vec{a}$ % mathematical symbol\n    & acceleration\\footnote{One-dimensional vector, direction indicated by sign.} % short description\n    & \\si{\\meter\\per\\second\\squared} % dimension of quantity\n    & $\\mathbb{R} \\in (-\\infty, \\infty)$ % math-valid range\n    \\\\%\n  \\end{CCInOutTable}\n\\end{table}\n\n\n% --------------------------------------------------------------------\n\\subsection{Algorithm Outputs}\n\\label{sec:AlgorithmOutputs}\n\nDescribe the outputs from the algorithm. Outputs are summarized in \\autoref{tab:CCddd-output}.\n\n\\begin{table}\n  \\centering\n  \\caption{Output information for CCddd.}\n  \\label{tab:CCddd-output}\n  \\begin{CCInOutTable}\n    % Five (5) columns\n    % symbol & description & unit & range & notes \\\\\n    $\\vec{F}$ % mathematical symbol\n    & force % short description\n    & \\si{\\newton} % dimension of quantity\n    & $\\mathbb{R} \\in (-\\infty, \\infty)$ % math-valid range\n    & % notes\n    \\\\%\n  \\end{CCInOutTable}\n\\end{table}\n\n% --------------------------------------------------------------------\n\\section{Algorithm Description}\n\\label{sec:AlgorithmDescription}\n\nDetailed description of the algorithm with sufficient fidelity\nto allow independent implementation.\n\n% --------------------------------------------------------------------\n\\subsection{Assumptions / Limitations}\n\\label{sec:AssumptionsLimitations}\n\nDescribe any known limitations or assumptions that went into\nthe design.  \n\n%-%% ====================================================================\n%-%\\chapter{Trade Studies}\n%-%\\label{sec:TradeStudies}\n%-%\n%-%Provide details and results of any trade studies used in the\n%-%design of this algorithm.  Should include any optimization studies\n%-%used to determine parameter values.  This may just be a summary with\n%-%reference to other documents.\n\n% ====================================================================\n\\chapter{Algorithm Verification}\n\\label{sec:AlgorithmVerification}\n\nProvide test cases and associated metrics / tolerances to be\nused to test that any implementation of the algorithm is correct. Refer to \\autoref{tab:CCddd-verification} for a summary of tests.\n\n\\begin{table}\n  \\centering\n  \\caption{Verification test cases for CCddd.}\n  \\label{tab:CCddd-verification}\n  % These lengths are necessary to avoid white space from the \\{top,mid,bottom}rule lines\n  \\setlength{\\aboverulesep}{0pt}\n  \\setlength{\\belowrulesep}{0pt}\n  \\setlength{\\extrarowheight}{.75ex}\n  \\begin{tabular}{lll>{\\columncolor{green}}l}\n    \\toprule%\n    \\multicolumn{1}{c}{\\bfseries ID}%\n    &\\multicolumn{1}{c}{\\bfseries $m$}%\n    &\\multicolumn{1}{c}{\\bfseries $\\vec{a}$}%\n    &\\multicolumn{1}{>{\\columncolor{green}}c}{\\bfseries $\\vec{F}$}%\n    \\\\%\n    \\midrule%\n    1 & 1 & 1 & 1%\n    \\\\%\n    2 & 3.300 & -9.800 & -32.34%\n    \\\\%\n    \\bottomrule\n  \\end{tabular}\n\\end{table}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "0abbbdc83dc91cc846357f2591777d088bba8e33", "size": 4377, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/templates/kert/kert_unit_Concept-Calculation.tex", "max_stars_repo_name": "tcburt/kert", "max_stars_repo_head_hexsha": "10df0bb3b6c2e401bb2e1e37a3a7acefcc76996e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-16T15:16:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-16T15:16:05.000Z", "max_issues_repo_path": "src/templates/kert/kert_unit_Concept-Calculation.tex", "max_issues_repo_name": "tcburt/kert", "max_issues_repo_head_hexsha": "10df0bb3b6c2e401bb2e1e37a3a7acefcc76996e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-08-08T23:35:46.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-15T14:40:21.000Z", "max_forks_repo_path": "src/templates/kert/kert_unit_Concept-Calculation.tex", "max_forks_repo_name": "tcburt/kert", "max_forks_repo_head_hexsha": "10df0bb3b6c2e401bb2e1e37a3a7acefcc76996e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7755102041, "max_line_length": 276, "alphanum_fraction": 0.5953849669, "num_tokens": 1060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.32279637166924074}}
{"text": "\\documentclass[10pt,a4paper]{article}\n\\usepackage[textwidth=16cm,textheight=23cm]{geometry}\n\\usepackage[utf8]{inputenc}\n\\usepackage[T1]{fontenc}\n\\usepackage{amsmath}\n\\usepackage{amsfonts}\n\\usepackage{amssymb}\n\\usepackage{graphicx}\n%\\usepackage{url}\n\\usepackage{hyperref}\n\\usepackage{bm}\n\n\n\\newcommand{\\Trans}{\\mathcal{T}}\n\\newcommand{\\filterationF}{\\mathcal{F}}\n\\newcommand{\\mkt}{\\mathrm{mkt}}\n\\newcommand{\\ytw}{\\mathrm{ytw}}\n\\newcommand{\\dd}{\\mathrm{d}}\n\\newcommand{\\CRdelta}{\\mathrm{CR01}}\n\n\\newcommand{\\inVaR}{{\\mathrm{iv}}}\n\\newcommand{\\notInVaR}{{\\mathrm{niv}}}\n\n\n\\usepackage{tcolorbox}\n\\tcbuselibrary{theorems}\n\n\\newtcbtheorem[number within=section]{MyRemark}{Remark}%\n{colback=green!5,colframe=green!35!black,fonttitle=\\bfseries}{th}\n\n\n\\parindent=0pt\n\\parskip=1.5ex\n\n\n\\begin{document}\n\n\\title{Note on Deal Contingent Trades}\n\\author{Youngsuk Lee}\n\\date{26 July 2020}\n\\maketitle\n\n\\section{Structure}\n\nThe firm enters a derivative trade such as FX forwards or FX options with a counterparty where the trade is contingent on an agreed deal such as merger, regulatory approval, etc. \n\nConsider such a deal-contingent trade (DCT) and its hedge trade, both of which are booked in the trading book. Figure \n\\ref{fig:dct-illustration} illustrates two situations:\n\\begin{itemize}\n\t\\item Deal succeeds where DCT is well hedged throughout its life.  \n\t\\item Deal fails where there is a potential sudden P\\&L due to (i) the mark-to-market is {\\em released} from DCT and \n\tthe PV changes from the {\\em naked} hedge. \n\\end{itemize}\n\n\\begin{figure}[h!]\n\t\\begin{center}\n\t\t\\includegraphics[width=16cm]{figs/dct-illustration.png}\n\t\\end{center}\n\t\\caption{If we put them into the reg VaR and realise the P\\&Ls. \n%\t\tleft: The deal succeeds. right: The deal fails tomorrow. There are two sources of P\\&Ls: (i) blue bar with '+': The mark-to-market of DCT drops to zero.\n%\t\t(ii) orange bar with '/': The mark-to-market of the hedge trade moves. \n\t}\n\t\\label{fig:dct-illustration}\t\n\t\\hrule\n\\end{figure}\n\n\\begin{figure}[h!]\n\t\\begin{center}\n\t\t\\includegraphics[width=16cm]{figs/dct-illustration-held.png}\n\t\\end{center}\n\t\\caption{\nIf we put them outside the reg VaR and hold the P\\&Ls.. \n\t}\n\t\\label{fig:dct-illustration-held}\t\n\t\\hrule\n\\end{figure}\n\n\\section{Risk-Not-In-VaR}\n\n\\subsection{Risk-Not-In-VaR P\\&L}\n\nFor typical VaR models, it is not easy to incorporate the risk of deal failures. \n\nTo express the P\\&L of this missing risk, let\n\\begin{itemize}\n\t\\item $V$: mark-to-market of DCT\n\t\\item $\\bar{V}$: today's mark-to-market\n\t\\item $\\Delta V$: random variable to represent the total P\\&L in $V$\n\t\\item $\\Delta V^\\inVaR$: the part of $\\Delta V$ included in VaR. \n\t\n\tFor example, if DCT is a simple FX forward on the spot rate $z$, \n\t\\begin{equation}\n\t\\Delta V^\\inVaR = \\delta_z \\cdot \\Delta Z\n\t\\label{eqn:pnl-in-var-example}\n\t\\end{equation}\n\twhere $\\delta_z$ is the first-order sensitivity and $\\Delta Z$ is the random variable representing the change in $z$. \n\t\\item $\\Delta V^\\notInVaR$: the part of $\\Delta V$ not included in VaR \n\t\\item $F$ is the random variable indicating the deal failure:\n\t\\begin{equation}\n\tF = \\left\\{ \n\t\\begin{array}{cl}\n\t\t1, & \\textrm{if the deal has failed.}\\\\\n\t\t\\\\\n\t\t0, & \\textrm{otherwise}\n\t\\end{array}\n\t\\right.\n\t\\end{equation}\n\\end{itemize}\nThen, we have\n\\begin{equation}\n\\Delta V = -\\bar{V} \\cdot F + \\Delta V^\\inVaR \\cdot (1 - F)\n\\end{equation}\nand\n\\begin{eqnarray}\n\\Delta V^\\notInVaR &=& \\Delta V - \\Delta V^\\inVaR\\\\\n& = & -\\bar{V} \\cdot F - \\Delta V^\\inVaR  \\cdot F \n\\end{eqnarray}\n\nWith multiple deals, each of which denoted by $i$, \n\\begin{equation}\n\\Delta V^\\notInVaR = \\sum_{i=1}^{I}\\left[ - \\bar{V}_i \\cdot F_i\n- \\Delta V_i^\\inVaR \\cdot F_i \\right]\n\\label{eqn:missing-pnl}\n\\end{equation}\n\n\\subsection{Model}\n\nTo move Eq (\\ref{eqn:missing-pnl}), we use a simple multi-variate normal distribution.\n\n\\subsubsection{Failure Indicator}\nTo model $F_i$, we can use a standard framework used for credit default modelling. \n\nLet $P_i$ be the probability of the deal failure. To simulate the deal failure events, let $X_i$ be an $N(0,1)$ random variable, indicating the deal quality and set\n\\begin{equation}\nF_i := \\left\\{\n\\begin{array}{cl}\n1, & \\textrm{if}\\quad \\Phi(X_i) < P_i,\\\\\n\\\\\n0, & \\textrm{otherwise} \n\\end{array}\n\\right.\n\\end{equation}\n\nFor joint simulations of $\\{F_i\\}_{i=1}^{I}$, the correlation should be specified:\n\\begin{equation} \n\\rho^F_{i,j} := \\mathrm{corr}(F_i, F_j).\n\\end{equation}\n\n\n\n\\subsubsection{VaR P\\&Ls}\n\nTo model $\\Delta V_i^\\inVaR$, without loss of generality, assume that it can be written as a function of $\\Delta \\bm{Z}$, the return distribution of a set of risk factors $\\bm{z} = [z_1, \\cdots, z_K]$ included in VaR:\n\\begin{equation}\n\\Delta V_i^\\inVaR := \\Delta V_i^\\inVaR(\\Delta \\bm{Z})\n\\end{equation}\nAs an example, see Eq (\\ref{eqn:pnl-in-var-example}). \n\n\\begin{MyRemark}{VaR P\\&L functions}{}\n$\\Delta V_i^\\inVaR$ is the same P\\&L (approximation) function used in VaR.\n\\end{MyRemark}\n\nWe assume that $\\Delta Z$ follows a multi-variate normal distribution with\n\\begin{equation}\n\\Delta Z_k \\sim N(\\mu_k, \\sigma_k^2) \\quad \\textrm{and} \\quad \\mathrm{corr}(\\Delta Z_k, \\Delta Z_l) = \\rho_{k,l}^{Z}.\n\\end{equation}\n\n\\subsubsection{Correlation: Deal Failures and Risk Factors}\n\nFinally, the correlations among deal quality indices $X_i$'s and VaR risk factors $Z_k$'s should be specified:\n\\begin{equation}\n\\rho_{i,k}^{F,Z} = \\mathrm{corr}(X_i, Z_k)\n\\end{equation}\n\n\n\n\\subsection{Model Parameter Estimations}\n\n{\\bf Postulations}: The following parameters are postulated by appropriate {\\em experts}:\n\\begin{itemize}\n\t\\item Failure Probability and Correlations: \t$\\{P_i\\}$ and $\\{\\rho^F_{i,j}\\}$ where $i, j = 1, \\cdots, I$\n\t\\item Deal vs market correlations: $\\{ \\rho_{i,k}^{F,Z}\\}$ for $i = 1, \\cdots, I$ and $k = 1, \\cdots, K$. \n\t\n\tDue to the nature of typical deal contingent trades, they would be set to zero. \n\t\n\\end{itemize}\n\n\n{\\bf Calibrations}: The following risk factor model parameters \n\\begin{center}\n\t$\\{\\mu_k\\}$, $\\{\\sigma_k\\}$ and $\\{\\rho_{k,l}^Z\\}$ where $k, l = 1, \\cdots, I$: \n\\end{center}\nwould be calibrated to simulated returns of the relevant historical VaR models. \n\n\\subsection{Quantification}\n\n\\begin{enumerate}\n\t\\item Run standard Monte Carlo simulations on \n\t\\begin{equation}\n\t\\{X_i\\}_{i=1}^{I}\\quad\\textrm{and}\\quad\\{Z_k\\}_{k=1}^{K}.\n\t\\end{equation}\n\t\\item Generate scenarios of the risk-not-in-VaR P\\&L $\\Delta V^\\notInVaR$ using Eq (\\ref{eqn:missing-pnl}).\n\t\\item Calculate the 99th tail measure.\n\\end{enumerate}\n\n\\end{document}", "meta": {"hexsha": "4d334fac40c2df42159236c1388008e5b644b9bf", "size": 6502, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "notebook/deal_contingent/doc/DCT.tex", "max_stars_repo_name": "xyise/xyise", "max_stars_repo_head_hexsha": "e2bc1c2e824da4fc5cd1d81aaef76a1ad147fb01", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebook/deal_contingent/doc/DCT.tex", "max_issues_repo_name": "xyise/xyise", "max_issues_repo_head_hexsha": "e2bc1c2e824da4fc5cd1d81aaef76a1ad147fb01", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebook/deal_contingent/doc/DCT.tex", "max_forks_repo_name": "xyise/xyise", "max_forks_repo_head_hexsha": "e2bc1c2e824da4fc5cd1d81aaef76a1ad147fb01", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5631067961, "max_line_length": 217, "alphanum_fraction": 0.707628422, "num_tokens": 2179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.3227963626496327}}
{"text": "\\documentclass[12pt]{article}\n\\usepackage{SteveStyle}\n\n\\begin{document}\n\n\\title{\\texttt{Math 470 - Summary Report}}\n\\author{Stephen Fay 260844060, under Prof. Gantumur Tsogtgerel}\n\\date{May 1st to August 31st}\n\\maketitle\n\n\\begin{abstract}\nIn this project we explore geometric properties of numerical integrators applied to Hamiltonian ordinary differential equations; we study the n-body problem, chosen for it's wealth of symmetries and chaotic behavior. We combine symplectic numerical schemes \\cite{Numerical} with projections onto invariant manifolds, which we obtain with well known symmetry methods for dimensionality reduction \\cite{Symmetry-methods}. Using backward error analysis we show that the projections violate symplecticity; postulating that projection methods may give rise to an attractor - a subset of the preserved manifold, we investigate the Lyapunov spectrum of our modified equations but find evidence that for $n\\geq 3$ the projection methods make the equations \\textit{more} chaotic. \n\\end{abstract}\n\n\\section{Symmetry methods}\nWe look at lie groups, their algebras and their applications to differential equations. We study Noether's theorem at different levels of generality and abstraction; in the language of Lagrangian formalism invariant physical quantities such as energy and total angular momentum are found with Noether's theorem with respect to the kepler problem and the n-body problem. \n\nWe look at Pointcar\\'e cuts of the Heinon-Heiles system, there appears to exist a first integral but at a critical energy bifurcation occurs and the conserved manifold becomes strange. \n\n\\section{Numerical Integration of Hamiltonian ODEs}\nSome classical integration schemes are surveyed with an eye kept on applications to Hamiltonian systems: euler methods, midpoint rule, Str\\\"omer Verlet and Runge-Kutta symplectic methods. After a brief venture into symplectic geometry we discuss the advantages of using symplectic integrators, proving relevant theorems along the way. \n\nProjections onto invariant manifolds are introduced, various algorithms (some of my own inventions) are discussed and compared first with computational experiments, and later analytically. Certain other methods for preserving first integrals which where not implemented, such as solving equations in local coordinates, are also presented. \n\nWe apply the methods of backward error analysis to numerical integration schemes and compare the modified vector fields with the exact vector fields / one-forms; we determine second and third order modified terms to add to the modified equations based off of the projections to see if they improve the accuracy of the numerical flows. It is clear from these equations that the projected flows are no longer symplectic, this prompts further investigation of the flows.\n\nWe suspect from the experiments that the numerical integrators with projection create an attractor in the two body problem; the experiments showed that if the orbit of the reduced mass starts off with small eccentricity, that the orbit would be attracted to circular motion. Also, numerical simulations of the two and many body problem showed that the projection methods tended to select for trajectories which maximized the angles between first integrals. From these two observations we postulate that the projection methods may give rise to an attractor. By taking the logarithm of the eigenvectors of the eigenvalues of the jacobian, we can estimate the lyapunov spectrum; apply this method to a symplectic integrator for which both the theory and the experiment yield pairs of Lyapunov exponents - each positive exponent has an equal in magnitude corresponding negative exponent (a theorem derived rigorously). If the hypothesis had been correct, we would have gotten that the sum of the spectrum of the projected equations would be negative, instead we found for three and four bodies, that the sum of the eigenvalues was positive, which is evidence for the opposite - that the introduction of projections makes the equations more chaotic rather than giving rise to an attractor. \n\n\n\\section{Conclusions}\nSomething I found particularly satisfying about working on this project is that the theory and computational experiments complemented each other: the theory was driving the experiments, and the experiments where confirming the theory and driving me in new directions; for instance I would never have (alas, wrongly) suspected the existence of an attractor had I not seen some suspicion in the graphical behavior of numerical solutions to the kepler problem.\n\nReading literature and diving into textbooks was a fascinating and informative experiance, this has prepared and motivated me to think more ambitiously and I feel I have gained some insight into how research in applied math is conducted.\n\nI was drawn to the kepler problem because I have been wrestling with it's quantum analogue for the last 4 months (Hydrogen atom), and with Noether's theorem in quantum mechanics for the past 11 months. \n\nMany thanks to Prof. Gantumur Tsogtgerel for supporting and inspiring me along the way; and to my peers Selim Amar and Noah Nicodemo for staying in tune with my project and asking pertinant questions. \n\n\\bibliographystyle{plain}\n\\bibliography{MyBibliography}\n\n\\end{document}", "meta": {"hexsha": "2204e676ab31d1ce9b157462616f9ed41dad3401", "size": 5298, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/summary_report.tex", "max_stars_repo_name": "dcxSt/numerical_integrators", "max_stars_repo_head_hexsha": "7b7e2fbfa7c4df981e86934446d87272965baf28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tex/summary_report.tex", "max_issues_repo_name": "dcxSt/numerical_integrators", "max_issues_repo_head_hexsha": "7b7e2fbfa7c4df981e86934446d87272965baf28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-06T19:32:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-06T19:32:38.000Z", "max_forks_repo_path": "tex/summary_report.tex", "max_forks_repo_name": "dcxSt/numerical_integrators", "max_forks_repo_head_hexsha": "7b7e2fbfa7c4df981e86934446d87272965baf28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 126.1428571429, "max_line_length": 1285, "alphanum_fraction": 0.822385806, "num_tokens": 1080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3225471713744836}}
{"text": "\\chapter{Epilogue}\nIn this thesis, we have presented a detailed study of bendotaxis -- a new mechanism by which a droplet squeezes itself out of an elastic channel: the capillary pressure of the droplet bends the channel walls confining the droplet in such a way that causes the droplet to move spontaneously.  We have focussed on questions pertinent to the possible application of bendotaxis to self cleaning surfaces, which has motivated consideration of the time scale of motion, physical effects that might impede droplet transport, the influence of channel geometry, and the collaborative effects that arise between neighbouring channels. In this chapter we summarize our results and suggest some ideas for further work.\n\n\\section{Summary of the thesis}\nWe began in Chapter 1 with a discussion of the mechanism of bendotaxis: the Laplace pressure within a droplet induces a tapering of the confining channel that drives it towards the free end. By considering this mechanism, we predicted that the direction of motion is universal -- droplets should be transported to the free end, regardless of whether they wet the channel or not -- and verified this with a proof-of-concept experiment.\n\nHaving shown that the direction of bendotaxis is universal, we turned in Chapter~2 to develop a two-dimensional dynamic model of bendotaxis. The physical processes represented by our model were motivated by the proof of concept experiment of Chapter~1; in particular, we exploited the small aspect ratio of the droplet and the slenderness of the channel walls to reduce the dimensionality of the problem. The resulting spatially one-dimensional system of PDEs that describe this model were solved numerically; using these solutions, we verified that wettability independent droplet transport is a feature that is reproduced by our model and identified three key characteristic features of the dynamics of bendotaxis in two-dimensional channels: Firstly, motion occurs on two time scales: a short time scale on which the channel walls respond to a torque imbalance by bending rapidly (causing the droplet to spread), and a longer time scale on which droplets translate to the free end. Secondly, even in the absence of inertia, droplets accelerate along the channel, in contrast to bendo-capillary imbibition from a fixed bath of liquid, for which the leading meniscus decelerates throughout the motion. Finally,  when surface tension is sufficiently strong, the channel walls touch before the droplet reaches the free end. We made analytic progress in understanding the first two of these observations by assuming small channel wall deflections;  this asymptotic analysis suggested that the time scale of bendotaxis is inversely proportional to the product of the channel bendability $\\nu$ and the droplet volume $V$, as a scaling argument valid for small droplets also suggested. The mathematical model provides some insight that could inform the design of superhydrophobic surfaces  that exploit bendotaxis for anti-fogging. In particular, we noted that more compliant channels will transport droplets faster (it would be desirable to remove droplets from such a surface as quickly as possible), but this faster transport must be balanced with the increased risk of trapping the droplets within the channel, thereby compromising the surface’s performance. \n\nIn Chapter 3, we presented an experimental study of bendotaxis. The experimental setup was similar to that in the proof of concept experiments of Chapter 1, except that the parameters of the system (specifically the channel geometry, droplet viscosity, and channel wall stiffness) were systematically varied to present a robust test of the mathematical model developed in Chapter 2. The experimental droplet trajectories have a similar shape and time scale of motion to those predicted by the analysis of our model (both from scaling, asymptotics, and numerics). Nevertheless, the experimentally observed motion was systematically slower than predicted -- a discrepancy that is consistent with the two-dimensional nature of our theory and the  associated overestimation of the relative droplet volume. To facilitate comparison of a much larger data set and reduce dependence on initial conditions, we introduced the time taken to traverse a section of the channel as a proxy for the full dynamics represented by the trajectories. Analysis of the experimental data showed that the small volume result of Chapter 2 describes the dynamics reasonably well, even when the droplet has finite volume. Moreover, this analysis showed that deviations from the small volume result -- the non-linearity associated with larger channel deflections, and the finite drop size effects predicted by the model -- are represented in the experimental data in a way that is consistent with the model predictions. \n\nIn Chapter 4, we considered two mechanisms by which droplets might become trapped in channels whilst undergoing bendotaxis. The first of these was geometric trapping, which describes the scenario first encountered in Chapter~2 in which the channel walls touch before the droplet reaches the free end. We built upon the ideas of Chapter~2, where we saw that the channel bendability for which droplet trapping occurs is reasonably insensitive to the droplet volume and initial position, provided that the droplet starts reasonably far from the free end of the channel. In particular, we extended our model of bendotaxis to describe the behaviour beyond the point of wall contact, and identified two post contact  scenarios -- channel walls touching at a single point, and channel walls making contact along a portion of their length, the latter occuring only when the channel bendability $\\nu$ is very large. Numerical solutions of the model equations display complex dynamics that result from the strong squeezing at early times that is associated with large channel bendability, as well as from the competition between two diverging quantities (the meniscus pressure and viscous dissipation) as the droplet advances into a channel of vanishing thickness. \n%If, on the one hand, the meniscus approaches the end of the channel while the walls are simply touching, it appears to reach the end in finite time with asymptotic behaviour faster than the corresponding rigid case. On the other hand, if the meniscus approaches the end of a channel whose walls are in contact along a portion of their length (making a cusp at the contact point), the meniscus appears to take an infinite amount of time to reach the cusp.\n\nIn the second half of Chapter 4, we considered when droplets may be trapped as a result of contact angle hysteresis. We extended the model to encode the idea of a non-unique contact angle at a stationary interface and supplemented this with the simplest possible contact angle dynamics.  In numerical solutions, we saw that droplets may be trapped (reach equilibria) part way along the channel, but this depends critically on whether the contact angle asymmetry across the droplet that is allowed by the given contact angle hysteresis is sufficient to permit an equilibrium. We mapped out the conditions under which such an equilibrium is possible and found, in particular, that for a given droplet, it may `escape' the channel provided that it starts close enough to the free end. Further, we found that droplets are more likely to be trapped in channels with higher contact angle hysteresis, confirming the need to minimize hysteresis in any superhydrophobic surface that seeks to exploit bendotaxis for anti-fogging. We also verified that the trapped states are indeed equilibria, that they are linearly stable, and that droplets will never translate to equilibrium -- heuristically, once droplets `get going' they will not be stopped.\n\nIn Chapter 5, we sought to understand the weaving instability that is observed in experiments of condensation of droplets into deformable microchannels~\\citep{Seemann2011JPhysCondMat}. In doing so, we identified a novel bendo-capillary instability that is reminiscient of the Rayleigh-Plateau instability (in that it relies on a competition between the principal interfacial curvatures) and the instability described by~\\cite{AlHousseiny2012NaturePhysics} (in that it is mediated by the channel that confines the liquid). Unlike the rigid (Al-Housseiny) case, however, the channel tapering in the bendo-capillary case is set by the liquid pressure meaning that both wetting and non-wetting liquids may, in theory, experience instability in the same channel. To study this bendo-capillary instability, we developed a mathematical model of a three-dimensional system and again exploited linear beam theory and lubrication theory to reduce its dimensionality. We focussed first on the no condensation case, where equilibria are possible. A linear stability analysis revealed that these equilibria are unstable to perturbations of a sufficiently small wavenumber and that the corresponding growth rates are highly sensitive to the amount of liquid in the channel, which is parametrized by the cross-sectional volume $V$. We then considered the effect of a non-zero condensation rate, which changed the picture in two important ways: (i) the cross-sectional volume $V$ becomes time-dependent, and (ii) condensation may drive dynamic effects in the (now time-dependent) base state. We saw that when the condensation rate is small, condensation enters only through the instantaneous value of $V$ and the instantaneous growth rate of a perturbation is given by the corresponding zero-condensation result; as a consequence of the sensitivity of the zero-condensation results to $V$, we saw how modes that grow slowly at first are able to catch up with, and overtake, those that grow faster initially. We speculated that these later modes reach the non-linear regime sooner. Numerical solutions of the linearized equations revealed that this mechanism is also present for condensation rates of any size, but interacts with the condensation driven dynamics. This tends to enhance the instantaneous growth rate and lengthen the band of unstable modes (compared to the quasistatic case) with longer wavelength modes being enhanced preferentially. Despite the simplicity of our model, its predictions agree in their order of magnitude with the condensation experiments of~\\cite{Seemann2011JPhysCondMat}.\n\nIn Chapter 6, we sought to understand how multiple droplets in neighbouring channels might affect each other's bendotaxis -- a question relevant not only for self cleaning surfaces (which naturally have many channels) but also for the condensation experiments in which the weaving instability occurs simultaneously in neighbouring channels. We developed a mathematical model of this `multi-body’ bendotaxis in which, for simplicity, we assumed that the channel walls are rigid, and are tethered at their base by torsional elastic springs. As part of the model development, we identified the importance of a parameter $\\Gamma$  that encodes the ability of the individual droplets to deform the channel that confines them, and is analogous to the bendability $\\nu$ used throughout Chapters 2--5. Importantly, this torsional spring model is also able to describe wettability-independent droplet transport in a single channel. Modelling with torsional springs (rather than the potentially more realistic beam theory applied elsewhere in this thesis) simplifies the model equations to a system of ODEs which have an equilibrium corresponding to equal volume droplets in un-deformed channels. A linear stability analysis revealed that this equilibrium is always unstable and we do not, therefore, expect to see it in practice. Moreover, the linear stability analysis suggested that a pairwise mode is always the fastest growing. However, numerical solutions of the governing ODEs with an initial condition close to the equilibrium displayed a range of cluster sizes. For small $\\Gamma$, the system almost always selects the pairwise mode (in accord with the linear stability analysis) because the angle of the channel walls (and thus direction of droplet motion) is set simply by the difference in position of droplets across them. We rationalized this result with an analysis that considers the governing ODEs in the case of small deflections that are associated with small $\\Gamma$. For large $\\Gamma$, however, a distribution of cluster sizes were observed, with a maximal size that scales with $\\Gamma^{1/2}$. By using a discrete-to-continuum approximation of the ODEs, we suggested that this appears to be the result of the propagation of fronts through the system which `lock in' clusters of this set size; with a random initial condition, these fronts interact with one another to `smooth out' the cluster sizes between the pairwise mode preferred by the linear stability analysis and the maximal cluster size set by the front propagation. We also considered the implications of this model for self-cleaning surfaces exploiting bendotaxis; the key result is that for larger $\\Gamma$, a greater proportion of droplets reach the free end, but they do so in channels that are almost closed at the free end, and thus potentially difficult for droplets to be removed from.\n\n\n\n\\section{Future work}\nIn this section, we provide a brief overview of how the work presented in this thesis might be extended.\n\nWe hypothesized in Chapter 3 that some of the discrepancies between experimental data and the predictions of the model of Chapter 2 are a result of  the two-dimensional nature of the model, which does not account for the fact that the length of the droplet (and interfacial curvature) vary in the third dimension in the experiments. It would be useful to quantify these effects and thereby assess the validity of this hypothesis. We anticipate that to do so, the mathematical model of Chapter 2 could be extended to describe variations of a finite extent in the third spatial direction (similar to the model of Chapter 5, although there the liquid had infinite extent in the third direction). With geometric extensions to the model of Chapter 2 in mind, one might also consider how the shape of the channel walls influences the dynamics of bendotaxis; in particular, one might take further inspiration from the setae of the water strider, which played an important role in the problem that provided our original motivation for studying bendotaxis. The setae are conically shaped, and they should, therefore, have a lower resistance to deformation at their tip than at their base; this should, in turn, exacerbate the relative `softness' of the free end of the channel, potentially increasing the speed of motion of droplet transport, but increasing the risk of trapping. A first step towards modelling this softening might be to consider the two-dimensional configuration of Chapter 2 with a variable bending stiffness $B = B(x)$. (Indeed, with a variable bending stiffness, many more possibilities open up, such as bendotaxis in tubes, which could be useful for micro-fluidic applications.)\n\nIn Chapter 4, we observed numerically that a droplet approaching the end of a channel whose walls are in contact at a single point appear to be able to reach this contact point in finite time (approaching with power law behaviour), but a droplet approaching the end of a channel whose walls are in contact over a portion of their length appear to take an infinite time to do so. It would be good to confirm and rationalize this behaviour, perhaps using an asymptotic approximation of the solution as the droplet approaches the contact point.\n\nWe focussed in Chapter 4 on identifying when droplets are trapped with a view to preventing this from happening, but, in other situations, this behaviour could perhaps be turned to our advantage. Indeed,  the trapping of droplets in tapered channels that results from contact angle hysteresis is believed to be part of a wider `capillary ratchet' mechanism that is exploited by feeding shorebirds~\\citep{Prakash2008Science}. Furthermore, with modifications to the channel set-up, additional possibilities for droplet control might open up; for example, by controlling tapering angle of the channel walls at the clamped end, we can imagine a scenario in which only droplets with a sufficiently large surface tension are transported to the free end, whilst others are trapped, and others still (of the same wettability) are transported to the clamped end of the channel.\n\nThe natural extension to our study of the bendo-capillary instability in Chapter 5 is to solve the corresponding non-linear equations numerically. This would allow us to assess how the linearly unstable modes interact with one another as well as to predict which mode will ultimately be observed at late times, once the linearized analysis is no longer valid. We stress, however, that this is not a simple task for myriad reasons. For example, care is required in discretizing the biharmonic operator in the beam equation on a moving domain, fluid and solid deformations must be solved for simultaneously (leading to a large number of degrees of freedom), and the free surface must be appropriately parametrized.\n\nIt would also be interesting to study how the mobility of the liquid affects the bendo-capillary instability; we assumed for simplicity that the liquid is sat at the base of the channel but a similar instability should occur if there is a second meniscus closer to the clamped end (a scenario that would be more appropriate for bendotaxis). In that case, there are potentially two modes of instability, depending on whether the protrusions of the perturbation to the leading meniscus are in phase or out of phase with those at the trailing meniscus (sinusoidal or varicose modes). \n\nThere are several ways in which the study of multi-body bendotaxis in Chapter 6 could be extended. Most pressingly, we assumed that the droplets have a constant volume, and focussed primarily on the case when each droplet has the same volume. This is often not the case in experiments of bendo-capillary clustering (for example, in the condensation experiments which provide motivation). In addition, a recent study by~\\cite{Hadjittofis2016JFM} identified how mass changes in a similar system can exert a strong influence on the dynamic behaviour, both suppressing or enhancing clustering depending on how quickly it occurs. One might extend this work further to imagine a scenario in which droplets nearer to the free end are evaporated preferentially; this may exert a stabilizing control on our system, which is always unstable when droplet volumes are constant. \n\nWith respect to self cleaning surfaces that could exploit bendotaxis, it would be useful to consider boundary conditions other than periodic in the $y$ direction because, after all, a real surface would have finite extent. Beyond the channel geometry considered here, one might extend our model to include two dimensional arrays of pillars; key difficulties with this would be that surface tension forces require a more careful calculation (because of the three-dimensional menisci), and resistive forces from the lubricating flow might be reduced because the liquid can flow in two directions.\n\nFinally, we note that in the second part of this thesis, we took much inspiration from the condensation experiments of~\\cite{Seemann2011JPhysCondMat}, but made progress towards understanding the observations by decoupling the behaviour into the weaving instability in a single channel and the interaction between bendotaxis in neighbouring two-dimensional channels. For a model that is more faithful to the experiments, one would have to couple these two together (i.e. Chapters 5 and 6), as well as account for droplets and contact angle hysteresis (Chapter 4), all of which would pose a significant modelling challenge.", "meta": {"hexsha": "2705804b18ac7b33ffcf04cc1a839fc01e3f7d3c", "size": 19880, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Sections/Chapter7_conclusion/Conclusion.tex", "max_stars_repo_name": "alextbradley/Thesis_final", "max_stars_repo_head_hexsha": "69d441a579a9e42a5e80838d2d5c5281e15695a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sections/Chapter7_conclusion/Conclusion.tex", "max_issues_repo_name": "alextbradley/Thesis_final", "max_issues_repo_head_hexsha": "69d441a579a9e42a5e80838d2d5c5281e15695a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sections/Chapter7_conclusion/Conclusion.tex", "max_forks_repo_name": "alextbradley/Thesis_final", "max_forks_repo_head_hexsha": "69d441a579a9e42a5e80838d2d5c5281e15695a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 509.7435897436, "max_line_length": 2868, "alphanum_fraction": 0.8191146881, "num_tokens": 3954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526660244837, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3225471713007715}}
{"text": "Since the corrections are directly effectued on the \\textit{primitive symbols} the choice that seemed to be the simplest was to use the top-down parser as basis for the implementation of the error correction parser.\n\n\\section{Implementation of the character replacement}\n\nThe first step was to implement the character replacement, this is a modified version of the previous code of the top-down parser:\n\n\\FloatBarrier\n\\begin{algorithm}\n    \\caption{Top-down parser character modification}\n    \\label{parse}\n    \\begin{algorithmic}[1]\n        \\State $table$ is a 3d array of 0\n        \\State $s \\gets input\\_string$\n        \\Procedure{parse}{$var, i, j$} \\Comment{Recursive parser function}\n            \\If{$table[var, i, j] != 0$}\n                \\State \\textbf{return} $(table[var, i, j] == 1)$\n            \\EndIf\n            \\If{$i == j - 1$}\n                \\ForAll{$t \\in terminal\\_rule[var]$}\n                    \\If{$t == s[i]$}\n                        \\State $table[var, i, j] \\gets \\textcolor{red}{1}$\n                        \\State \\textbf{return} \\textcolor{red}{$table[var, i, j]$}\n                    \\EndIf\n                \\EndFor\n                \\textcolor{red}{\\If{$terminal\\_rule[var].size() > 0$}\n                    \\State $table[var, i, j] \\gets 2$\n                    \\State \\textbf{return} $table[var, i, j]$\n                \\EndIf}\n            \\Else\n                \\State \\textcolor{red}{$min \\gets INT\\_MAX$}\n                \\ForAll{$nt \\in non\\_terminal\\_rules[var]$}\n                    \\For{$k \\gets i + 1; k < j$}\n                        \\State \\textcolor{red}{$declare \\text{ } res\\_1 \\text{ } and \\text{ } res\\_2$}\n                        \\textcolor{red}{\\If{$(res\\_1 \\gets parse(nt[0], i, k)) < INT\\_MAX \\text{ } \\land \\text{ } (res\\_2 \\gets parse(nt[1], k, j)) < INT\\_MAX$}\n                            \\If{$res\\_1 + res\\_2 - 1 < min$}\n                                \\State $min \\gets res\\_1 + res\\_2 - 1$\n                            \\EndIf\n                        \\EndIf}\n                    \\EndFor\n                \\EndFor\n                \\State \\textcolor{red}{$table[var, i, j] \\gets min$}\n                \\State \\textcolor{red}{\\textbf{return} $table[var, i, j]$}\n            \\EndIf\n            \\State $table[var, i, j] \\gets \\textcolor{red}{INT\\_MAX}$\n            \\State \\textbf{return} \\textcolor{red}{$table[var, i, j]$}\n        \\EndProcedure\n    \\end{algorithmic}\n\\end{algorithm}\n\\FloatBarrier\n\nAll the differences with the initial top-down parser are in red on this pseudo-code.\n\nWith those modifications the top-down parser now returns an integer when it parses a string:\n\\begin{itemize}\n    \\item[$-$] If the value is 1 it means that the string can be parsed without any modifications.\n    \\item[$-$] If the value is $x > 1$ it means that the string can be parsed with $x - 1$ modifications.\n    \\item[$-$] If the value is $INT\\_MAX$, the maximum value of an integer, it means that the string cannot be parsed, no matter how much modifications could be made.\n\\end{itemize}\n\n\\section{Implementation of the character deletion}\n\nOnce the character modification is done the next step is to implement character deletion.\n\n\\FloatBarrier\n\\begin{algorithm}\n    \\caption{Top-down parser character deletion}\n    \\label{parse}\n    \\begin{algorithmic}[1]\n        \\State $table$ is a 3d array of 0\n        \\State $s \\gets input\\_string$\n        \\Procedure{parse}{$var, i, j$} \\Comment{Recursive parser function}\n            \\If{$table[var, i, j] != 0$}\n                \\State \\textbf{return} $(table[var, i, j] == 1)$\n            \\EndIf\n            \\If{$i == j - 1$}\n                \\ForAll{$t \\in terminal\\_rule[var]$}\n                    \\If{$t == s[i]$}\n                        \\State $table[var, i, j] \\gets 1$\n                        \\State \\textbf{return} $table[var, i, j]$\n                    \\EndIf\n                \\EndFor\n                \\If{$terminal\\_rule[var].size() > 0$}\n                    \\State $table[var, i, j] \\gets 2$\n                    \\State \\textbf{return} $table[var, i, j]$\n                \\EndIf\n            \\Else\n                \\State $min \\gets INT\\_MAX$\n                \\State \\textcolor{red}{$del\\_1 \\gets parse(var, i + 1, j)$}\n                \\State \\textcolor{red}{$del\\_2 \\gets parse(var, i, j - 1)$}\n                \\ForAll{$nt \\in non\\_terminal\\_rules[var]$}\n                    \\For{$k \\gets i + 1; k < j$}\n                        \\State $declare \\text{ } res\\_1 \\text{ } and \\text{ } res\\_2$\n                        \\If{\\begin{varwidth}[t]{\\linewidth}$(res\\_1 \\gets parse(nt[0], i, k)) < INT\\_MAX \\text{ } \\land \\text{ } (res\\_2 \\gets parse(nt[1], k, j)) < INT\\_MAX$}\\end{varwidth}\n                            \\If{$res\\_1 + res\\_2 - 1 < min$}\n                                \\State $min \\gets res\\_1 + res\\_2 - 1$\n                            \\EndIf\n                        \\EndIf\n                    \\EndFor\n                \\EndFor\n                \\textcolor{red}{\\If{$del\\_2 < del\\_1$}\n                    \\State $del\\_1 \\gets del\\_2$\n                \\EndIf\n                \\If{$del\\_1 < min$}\n                    \\State $min \\gets del\\_1$\n                \\EndIf}\n                \\State $table[var, i, j] \\gets min$\n                \\State \\textbf{return} $table[var, i, j]$\n            \\EndIf\n            \\State $table[var, i, j] \\gets INT\\_MAX$\n            \\State \\textbf{return} $table[var, i, j]$\n        \\EndProcedure\n    \\end{algorithmic}\n\\end{algorithm}\n\\FloatBarrier\n\nThat algorithm returns the number of modifications plus deletions, the next step is to be able to return the corrected version of the input string.\nOnce such corrected string can be generated it will be trivial to know how much deletions and modifications were both needed.\n\n\\section{Recuperation of the corrected string}\n\nIn order to proceed to the recuperation of the corrected string a structure is used to contain the result of the parse function plus the corresponding corrected string.\nThe memoization table of the top-down parser will now contains datas of this structure.\nThe parse function will also now return a $parse\\_result$ structure, it will also take the corrected string at its actual state as parameter.\n\nThis is is the pseudo-code with the modifications needed to be able to retrieve the corrected string.\n\n\\FloatBarrier\n\\begin{algorithm}\n    \\caption{Top-down parser correction and string recuperation}\n    \\label{parse}\n    \\begin{algorithmic}[1]\n        \\State $table$ is a 3d array of $parse\\_result$\n        \\State $s \\gets input\\_string$\n        \\Procedure{parse}{$var, i, j, \\textcolor{red}{sc}$} \\Comment{Recursive parser function}\n            \\If{$table[var, i, j] != 0$}\n                \\State \\textbf{return} $(table[var, i, j] == 1)$\n            \\EndIf\n            \\If{$i == j - 1$}\n                \\ForAll{$t \\in terminal\\_rule[var]$}\n                    \\If{$t == s[i]$}\n                        \\State \\textcolor{red}{$table[var, i, j].result \\gets 1$}\n                        \\State \\textcolor{red}{$table[var, i, j].string \\gets sc$}\n                        \\State \\textbf{return} $table[var, i, j]$\n                    \\EndIf\n                \\EndFor\n                \\If{$terminal\\_rule[var].size() > 0$}\n                    \\State \\textcolor{red}{$table[var, i, j].result \\gets 2$}\n                    \\State \\textcolor{red}{$table[var, i, j].string \\gets terminal\\_rule[var][0]$}\n                    \\State \\textbf{return} $table[var, i, j]$\n                \\EndIf\n            \\Else\n                \\State $min \\gets INT\\_MAX$\n                \\State \\textcolor{red}{$new\\_s \\gets \"\"$}\n                \\State \\textcolor{red}{$del\\_1 \\gets parse(var, i + 1, j, sc.substr(1, sc.size() - 1))$}\n                \\State \\textcolor{red}{$del\\_2 \\gets parse(var, i, j - 1, sc.substr(0, sc.size() - 1))$}\n                \\ForAll{$nt \\in non\\_terminal\\_rules[var]$}\n                    \\For{$k \\gets i + 1; k < j$}\n                        \\State $res\\_1 \\gets parse(nt[0], i, k, \\textcolor{red}{sc.substr(0, k - i)})$\n                        \\If{$res\\_1\\textcolor{red}{.result} < INT\\_MAX$}\n                            \\State $res\\_2 \\gets parse(nt[1], k, j, \\textcolor{red}{sc.substr(k - i, j - k)})$\n                            \\If{$res\\_2\\textcolor{red}{.result} < INT\\_MAX$}\n                                \\If{$res\\_1\\textcolor{red}{.result} + res\\_2\\textcolor{red}{.result} - 1 < min$}\n                                    \\State $min \\gets res\\_1\\textcolor{red}{.result} + res\\_2\\textcolor{red}{.result} - 1$\n                                    \\State \\textcolor{red}{$new\\_s \\gets res\\_1.string + res\\_2.string$}\n                                \\EndIf\n                            \\EndIf\n                        \\EndIf\n                    \\EndFor\n                \\EndFor\n                \\State $table[var, i, j] \\gets \\textcolor{red}{min\\_parse\\_result(del\\_1, del\\_2, min, new\\_string)}$\n                \\State \\textbf{return} $table[var, i, j]$\n            \\EndIf\n            \\State \\textcolor{red}{$table[var, i, j].result \\gets INT\\_MAX$}\n            \\State \\textcolor{red}{$table[var, i, j].string \\gets sc$}\n            \\State \\textbf{return} $table[var, i, j]$\n        \\EndProcedure\n    \\end{algorithmic}\n\\end{algorithm}\n\\FloatBarrier\n\nSuch an algorithm will end by returning the corrected string plus the sum of all needed corrections and deletions to arrive to this result.\nIt is then trivial to separate the number of needed deletions from the number of modifications, just by comparing the size from the initial string to the size of the corrected string.\n\nThe running time of this algorithm will always be longer than for the top-down parser since the algorithm has to test the two possible deletions before entering the main loop, which the top-down parser does not do.\nHowever the complexity of this algorithm remains the same as for the top-down parser, $O(n^3)$.\n\n\\section{Obtained results}\n\n\\subsection{Well balanced parenthesis}\n\nThe goal of the new parser is to correct an input string to make it match the given grammar if it is possible, the first experimentation is realised on the well balanced parenthesis.\n\nInitially it was planned to check the parser's performances on the following cases:\n\n\\begin{itemize}\n    \\item[$-$] Strings in which the parser must modify half of the characters, that case corresponds to whatever pattern gives a string that does not contain any substring that would match the grammar, for example `$)\\string^ n$', or `$(\\string^ n$', or `$)\\string^ n / 2 \\text{ } (\\string^ n / 2$'.\n    \\item[$-$] Strings that match the grammar, then the parser does not have to modify the input string.\n    \\item[$-$] Strings that match the grammar or not, containing an odd number of characters so the parser needs to delete one.\n\\end{itemize}\n\nIt was interesting to notice that the correction top-down parser followed exactly the same behaviour no matter what pattern the given string follows.\n\n\\FloatBarrier\n\\begin{figure}[h]\n\\begin{tikzpicture}\n\\begin{groupplot}[group style={group size=2 by 1},height=0.5\\textwidth,width=0.5\\textwidth]\n    \\nextgroupplot[title=Number of recursive calls, xlabel=string size, ylabel=recursive calls, legend pos=north west]\n    \\addplot coordinates {\n        (50, 171256)\n        (100, 1352506)\n        (200, 10745006)\n        (300, 36177506)\n        (400, 85650006)\n        (500, 167162506)};\n    \\nextgroupplot[title=Running time, xlabel=string size, ylabel=seconds, legend pos=north west]\n    \\addplot coordinates {\n        (50, 0.009821)\n        (100, 0.084296)\n        (200, 0.705466)\n        (300, 2.82136)\n        (400, 7.1228)\n        (500, 14.8394)};\n\\end{groupplot}\n\\end{tikzpicture}\n\\end{figure}\n\\FloatBarrier\n\nThe running time plot follows exactly the same curve as the number of recursive calls, which was expected.\n\nHere is the verification of the complexity of the correction parser.\n\n\\begin{align*}\n    &y = 1.187152 \\cdot 10^{-7} \\cdot x^3\n\\end{align*}\n\n\\FloatBarrier\n\\begin{figure}[h]\n\\centering\n\\begin{tikzpicture}\n\\begin{groupplot}[group style={group size=1 by 1},height=0.5\\textwidth,width=0.5\\textwidth]\n    \\nextgroupplot[title=correction parser, xlabel=string size, ylabel=seconds, legend pos=north west]\n    \\addplot[domain=0:500, samples=100, line width=1.5pt, green] {1.187152*(10^(-7))*(x^3)};\n    \\addlegendentry{Theory}\n    \\addplot[only marks, mark=*, mark size=2pt] coordinates {\n        (50, 0.009821)\n        (100, 0.084296)\n        (200, 0.705466)\n        (300, 2.82136)\n        (400, 7.1228)\n        (500, 14.8394)};\n    \\addlegendentry{Real}\n\\end{groupplot}\n\\end{tikzpicture}\n\\caption{Checking theorical fit, correction parser}\n\\end{figure}\n\\FloatBarrier\n\nThe running time behaviour of the correction parser follows exactly the theorical fit, which proves that its complexity is $O(n^3)$.\n\n\\subsection{Strings starting with an `a'}\n\nThe next expimentation is on the grammar that matches strings that start with an `a'.\nWith that grammar the parser follows exactly the same behaviour as before, it always need the same amount of recursive calls for a string of size $n$, no matter the pattern.\n\n\\FloatBarrier\n\\begin{figure}[h]\n\\begin{tikzpicture}\n\\begin{groupplot}[group style={group size=2 by 1},height=0.5\\textwidth,width=0.5\\textwidth]\n    \\nextgroupplot[title=Number of recursive calls, xlabel=string size, ylabel=recursive calls, legend pos=north west]\n    \\addplot coordinates {\n        (50, 88005)\n        (100, 686005)\n        (200, 5412005)\n        (300, 18178005)\n        (400, 42984005)\n        (500, 83830005)};\n    \\nextgroupplot[title=Running time, xlabel=string size, ylabel=seconds, legend pos=north west]\n    \\addplot coordinates {\n        (50, 0.004987)\n        (100, 0.04377)\n        (200, 0.420274)\n        (300, 1.56265)\n        (400, 3.8529)\n        (500, 8.30812)};\n\\end{groupplot}\n\\end{tikzpicture}\n\\end{figure}\n\\FloatBarrier\n\nHere the parser does not need as much recursive calls as with the previous grammar but it still follows exactly the same behaviour.\n\nThe number of solved subproblems solved for this grammar follows the next sequence, with $n$ the size of the input string.\n\n$$\n1 + \\dfrac{(n - 1) \\cdot (3 \\cdot (n - 1) + 1)}{2} + (n - 1) \\cdot 2\n$$\n\nIt has no use to keep going with the experimentation since no matter the grammar or the given string this parser always follows the same behaviour.\n", "meta": {"hexsha": "e335924f6a6cbc6b2a0bfd8a823f6e2d62d3fe11", "size": 14320, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/sections/chapter_5.tex", "max_stars_repo_name": "ThomasRanvier/cyk_algorithm_analysis", "max_stars_repo_head_hexsha": "f6d7fbf95533461b58b0a9937530f1e4d8bc2e29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "report/sections/chapter_5.tex", "max_issues_repo_name": "ThomasRanvier/cyk_algorithm_analysis", "max_issues_repo_head_hexsha": "f6d7fbf95533461b58b0a9937530f1e4d8bc2e29", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/sections/chapter_5.tex", "max_forks_repo_name": "ThomasRanvier/cyk_algorithm_analysis", "max_forks_repo_head_hexsha": "f6d7fbf95533461b58b0a9937530f1e4d8bc2e29", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-09-13T17:38:35.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-13T17:38:35.000Z", "avg_line_length": 47.8929765886, "max_line_length": 299, "alphanum_fraction": 0.5886173184, "num_tokens": 3920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3225471630310558}}
{"text": "%\n% API Documentation for QSTK\n% Module QSTK.qstklearn.hmm\n%\n% Generated by epydoc 3.0.1\n% [Mon Mar  5 00:49:20 2012]\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%                          Module Description                           %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n    \\index{QSTK \\textit{(package)}!QSTK.qstklearn \\textit{(package)}!QSTK.qstklearn.hmm \\textit{(module)}|(}\n\\section{Module QSTK.qstklearn.hmm}\n\n    \\label{QSTK:qstklearn:hmm}\nThis package includes code for representing and learning HMM's.\n\nMost of the code in this package was derived from the descriptions provided\nin 'A Tutorial on Hidden Markov Models and Selected Applications in Speach \nRecognition' by Lawence Rabiner.\n\nConventions: The keyword argument elem\\_size will be passed in when \ncreating numpy array objects.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%                               Functions                               %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n  \\subsection{Functions}\n\n    \\label{QSTK:qstklearn:hmm:calcalpha}\n    \\index{QSTK \\textit{(package)}!QSTK.qstklearn \\textit{(package)}!QSTK.qstklearn.hmm \\textit{(module)}!QSTK.qstklearn.hmm.calcalpha \\textit{(function)}}\n\n    \\vspace{0.5ex}\n\n\\hspace{.8\\funcindent}\\begin{boxedminipage}{\\funcwidth}\n\n    \\raggedright \\textbf{calcalpha}(\\textit{stateprior}, \\textit{transition}, \\textit{emission}, \\textit{observations}, \\textit{numstates}, \\textit{elem\\_size}={\\tt {\\textless}type 'numpy.float128'{\\textgreater}})\n\n    \\vspace{-1.5ex}\n\n    \\rule{\\textwidth}{0.5\\fboxrule}\n\\setlength{\\parskip}{2ex}\n    Calculates 'alpha' the forward variable.\n\n    The alpha variable is a numpy array indexed by time, then state (TxN). \n    alpha[t][i] = the probability of being in state 'i' after observing the\n    first t symbols.\n\n\\setlength{\\parskip}{1ex}\n    \\end{boxedminipage}\n\n    \\label{QSTK:qstklearn:hmm:forwardbackward}\n    \\index{QSTK \\textit{(package)}!QSTK.qstklearn \\textit{(package)}!QSTK.qstklearn.hmm \\textit{(module)}!QSTK.qstklearn.hmm.forwardbackward \\textit{(function)}}\n\n    \\vspace{0.5ex}\n\n\\hspace{.8\\funcindent}\\begin{boxedminipage}{\\funcwidth}\n\n    \\raggedright \\textbf{forwardbackward}(\\textit{stateprior}, \\textit{transition}, \\textit{emission}, \\textit{observations}, \\textit{numstates}, \\textit{elem\\_size}={\\tt {\\textless}type 'numpy.float128'{\\textgreater}})\n\n    \\vspace{-1.5ex}\n\n    \\rule{\\textwidth}{0.5\\fboxrule}\n\\setlength{\\parskip}{2ex}\n    Calculates the probability of a sequence given the HMM.\n\n\\setlength{\\parskip}{1ex}\n    \\end{boxedminipage}\n\n    \\label{QSTK:qstklearn:hmm:calcbeta}\n    \\index{QSTK \\textit{(package)}!QSTK.qstklearn \\textit{(package)}!QSTK.qstklearn.hmm \\textit{(module)}!QSTK.qstklearn.hmm.calcbeta \\textit{(function)}}\n\n    \\vspace{0.5ex}\n\n\\hspace{.8\\funcindent}\\begin{boxedminipage}{\\funcwidth}\n\n    \\raggedright \\textbf{calcbeta}(\\textit{transition}, \\textit{emission}, \\textit{observations}, \\textit{numstates}, \\textit{elem\\_size}={\\tt {\\textless}type 'numpy.float128'{\\textgreater}})\n\n    \\vspace{-1.5ex}\n\n    \\rule{\\textwidth}{0.5\\fboxrule}\n\\setlength{\\parskip}{2ex}\n    Calculates 'beta' the backward variable.\n\n    The beta variable is a numpy array indexed by time, then state (TxN). \n    beta[t][i] = the probability of being in state 'i' and then observing \n    the symbols from t+1 to the end (T).\n\n\\setlength{\\parskip}{1ex}\n    \\end{boxedminipage}\n\n    \\label{QSTK:qstklearn:hmm:calcxi}\n    \\index{QSTK \\textit{(package)}!QSTK.qstklearn \\textit{(package)}!QSTK.qstklearn.hmm \\textit{(module)}!QSTK.qstklearn.hmm.calcxi \\textit{(function)}}\n\n    \\vspace{0.5ex}\n\n\\hspace{.8\\funcindent}\\begin{boxedminipage}{\\funcwidth}\n\n    \\raggedright \\textbf{calcxi}(\\textit{stateprior}, \\textit{transition}, \\textit{emission}, \\textit{observations}, \\textit{numstates}, \\textit{alpha}={\\tt None}, \\textit{beta}={\\tt None}, \\textit{elem\\_size}={\\tt {\\textless}type 'numpy.float128'{\\textgreater}})\n\n    \\vspace{-1.5ex}\n\n    \\rule{\\textwidth}{0.5\\fboxrule}\n\\setlength{\\parskip}{2ex}\n    Calculates 'xi', a joint probability from the 'alpha' and 'beta' \n    variables.\n\n    The xi variable is a numpy array indexed by time, state, and state \n    (TxNxN). xi[t][i][j] = the probability of being in state 'i' at time \n    't', and 'j' at time 't+1' given the entire observation sequence.\n\n\\setlength{\\parskip}{1ex}\n    \\end{boxedminipage}\n\n    \\label{QSTK:qstklearn:hmm:calcgamma}\n    \\index{QSTK \\textit{(package)}!QSTK.qstklearn \\textit{(package)}!QSTK.qstklearn.hmm \\textit{(module)}!QSTK.qstklearn.hmm.calcgamma \\textit{(function)}}\n\n    \\vspace{0.5ex}\n\n\\hspace{.8\\funcindent}\\begin{boxedminipage}{\\funcwidth}\n\n    \\raggedright \\textbf{calcgamma}(\\textit{xi}, \\textit{seqlen}, \\textit{numstates}, \\textit{elem\\_size}={\\tt {\\textless}type 'numpy.float128'{\\textgreater}})\n\n    \\vspace{-1.5ex}\n\n    \\rule{\\textwidth}{0.5\\fboxrule}\n\\setlength{\\parskip}{2ex}\n    Calculates 'gamma' from xi.\n\n    Gamma is a (TxN) numpy array, where gamma[t][i] = the probability of \n    being in state 'i' at time 't' given the full observation sequence.\n\n\\setlength{\\parskip}{1ex}\n    \\end{boxedminipage}\n\n    \\label{QSTK:qstklearn:hmm:baumwelchstep}\n    \\index{QSTK \\textit{(package)}!QSTK.qstklearn \\textit{(package)}!QSTK.qstklearn.hmm \\textit{(module)}!QSTK.qstklearn.hmm.baumwelchstep \\textit{(function)}}\n\n    \\vspace{0.5ex}\n\n\\hspace{.8\\funcindent}\\begin{boxedminipage}{\\funcwidth}\n\n    \\raggedright \\textbf{baumwelchstep}(\\textit{stateprior}, \\textit{transition}, \\textit{emission}, \\textit{observations}, \\textit{numstates}, \\textit{numsym}, \\textit{elem\\_size}={\\tt {\\textless}type 'numpy.float128'{\\textgreater}})\n\n    \\vspace{-1.5ex}\n\n    \\rule{\\textwidth}{0.5\\fboxrule}\n\\setlength{\\parskip}{2ex}\n    Given an HMM model and a sequence of observations, computes the \n    Baum-Welch update to the parameters using gamma and xi.\n\n\\setlength{\\parskip}{1ex}\n    \\end{boxedminipage}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%                               Variables                               %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n  \\subsection{Variables}\n\n    \\vspace{-1cm}\n\\hspace{\\varindent}\\begin{longtable}{|p{\\varnamewidth}|p{\\vardescrwidth}|l}\n\\cline{1-2}\n\\cline{1-2} \\centering \\textbf{Name} & \\centering \\textbf{Description}& \\\\\n\\cline{1-2}\n\\endhead\\cline{1-2}\\multicolumn{3}{r}{\\small\\textit{continued on next page}}\\\\\\endfoot\\cline{1-2}\n\\endlastfoot\\raggedright \\_\\-\\_\\-p\\-a\\-c\\-k\\-a\\-g\\-e\\-\\_\\-\\_\\- & \\raggedright \\textbf{Value:} \n{\\tt \\texttt{'}\\texttt{QSTK.qstklearn}\\texttt{'}}&\\\\\n\\cline{1-2}\n\\end{longtable}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%                           Class Description                           %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n    \\index{QSTK \\textit{(package)}!QSTK.qstklearn \\textit{(package)}!QSTK.qstklearn.hmm \\textit{(module)}!QSTK.qstklearn.hmm.HMMLearner \\textit{(class)}|(}\n\\subsection{Class HMMLearner}\n\n    \\label{QSTK:qstklearn:hmm:HMMLearner}\n\\begin{alltt}\n\nA class for modeling and learning HMMs.\n\nThis class conveniently wraps the module level functions. Class objects hold 6\ndata members:\n- num\\_states                    number of hidden states in the HMM\n- num\\_symbols                   number of possible symbols in the observation \n                                sequence\n- precision                     precision of the numpy.array elements (defaults to\n                                longdouble)\n- prior                         The prior probability of starting in each state\n                                (Nx1 array)\n- transition\\_matrix             The probability of transitioning between each state\n                                (NxN matrix)\n- emission\\_matrix               The probability of each symbol in each state\n                                (NxO matrix)\nYou can set the 3 matrix parameters as you wish, but make sure the shape of\nthe arrays matches num\\_states and num\\_symbols, as these are used internally\n\nTypical usage of this class is to create an HMM with a set number of states\nand external symbols, train the HMM using addEvidence(...), and then use\nthe sequenceProb(...) method to see how well a specific sequence matches\nthe trained HMM.\n\\end{alltt}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%                                Methods                                %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n  \\subsubsection{Methods}\n\n    \\label{QSTK:qstklearn:hmm:HMMLearner:__init__}\n    \\index{QSTK \\textit{(package)}!QSTK.qstklearn \\textit{(package)}!QSTK.qstklearn.hmm \\textit{(module)}!QSTK.qstklearn.hmm.HMMLearner \\textit{(class)}!QSTK.qstklearn.hmm.HMMLearner.\\_\\_init\\_\\_ \\textit{(method)}}\n\n    \\vspace{0.5ex}\n\n\\hspace{.8\\funcindent}\\begin{boxedminipage}{\\funcwidth}\n\n    \\raggedright \\textbf{\\_\\_init\\_\\_}(\\textit{self}, \\textit{num\\_states}, \\textit{num\\_symbols}, \\textit{init\\_type}={\\tt \\texttt{'}\\texttt{uniform}\\texttt{'}}, \\textit{precision}={\\tt {\\textless}type 'numpy.float128'{\\textgreater}})\n\n    \\vspace{-1.5ex}\n\n    \\rule{\\textwidth}{0.5\\fboxrule}\n\\setlength{\\parskip}{2ex}\n    Creates a new HMMLearner object with the given number of internal \n    states, and external symbols.\n\n    calls self.reset(init\\_type=init\\_type)\n\n\\setlength{\\parskip}{1ex}\n    \\end{boxedminipage}\n\n    \\label{QSTK:qstklearn:hmm:HMMLearner:reset}\n    \\index{QSTK \\textit{(package)}!QSTK.qstklearn \\textit{(package)}!QSTK.qstklearn.hmm \\textit{(module)}!QSTK.qstklearn.hmm.HMMLearner \\textit{(class)}!QSTK.qstklearn.hmm.HMMLearner.reset \\textit{(method)}}\n\n    \\vspace{0.5ex}\n\n\\hspace{.8\\funcindent}\\begin{boxedminipage}{\\funcwidth}\n\n    \\raggedright \\textbf{reset}(\\textit{self}, \\textit{init\\_type}={\\tt \\texttt{'}\\texttt{uniform}\\texttt{'}})\n\n    \\vspace{-1.5ex}\n\n    \\rule{\\textwidth}{0.5\\fboxrule}\n\\setlength{\\parskip}{2ex}\n\\begin{alltt}\n\nResets the 3 arrays using the given initialization method.\n\nWipes out the old arrays. You can use this method to change the shape\nof the arrays by first changing num\\_states and/or num\\_symbols, and then\ncalling this method.\n\nCurrently supported initialization methods:\nuniform         prior, transition, and emission probabilities are all \n                        uniform (default)\n\\end{alltt}\n\n\\setlength{\\parskip}{1ex}\n    \\end{boxedminipage}\n\n    \\label{QSTK:qstklearn:hmm:HMMLearner:sequenceProb}\n    \\index{QSTK \\textit{(package)}!QSTK.qstklearn \\textit{(package)}!QSTK.qstklearn.hmm \\textit{(module)}!QSTK.qstklearn.hmm.HMMLearner \\textit{(class)}!QSTK.qstklearn.hmm.HMMLearner.sequenceProb \\textit{(method)}}\n\n    \\vspace{0.5ex}\n\n\\hspace{.8\\funcindent}\\begin{boxedminipage}{\\funcwidth}\n\n    \\raggedright \\textbf{sequenceProb}(\\textit{self}, \\textit{newData})\n\n    \\vspace{-1.5ex}\n\n    \\rule{\\textwidth}{0.5\\fboxrule}\n\\setlength{\\parskip}{2ex}\n    Returns the probability that this HMM generated the given sequence.\n\n    Uses the forward-backward algorithm.  If given an array of sequences, \n    returns a 1D array of probabilities.\n\n\\setlength{\\parskip}{1ex}\n    \\end{boxedminipage}\n\n    \\label{QSTK:qstklearn:hmm:HMMLearner:addEvidence}\n    \\index{QSTK \\textit{(package)}!QSTK.qstklearn \\textit{(package)}!QSTK.qstklearn.hmm \\textit{(module)}!QSTK.qstklearn.hmm.HMMLearner \\textit{(class)}!QSTK.qstklearn.hmm.HMMLearner.addEvidence \\textit{(method)}}\n\n    \\vspace{0.5ex}\n\n\\hspace{.8\\funcindent}\\begin{boxedminipage}{\\funcwidth}\n\n    \\raggedright \\textbf{addEvidence}(\\textit{self}, \\textit{newData}, \\textit{iterations}={\\tt 1}, \\textit{epsilon}={\\tt 0.0})\n\n    \\vspace{-1.5ex}\n\n    \\rule{\\textwidth}{0.5\\fboxrule}\n\\setlength{\\parskip}{2ex}\n    Updates this HMMs parameters given a new set of observed sequences \n    using the Baum-Welch algorithm.\n\n    newData can either be a single (1D) array of observed symbols, or a 2D \n    matrix, each row of which is a seperate sequence. The Baum-Welch update\n    is repeated 'iterations' times, or until the sum absolute change in \n    each matrix is less than the given epsilon.  If given multiple \n    sequences, each sequence is used to update the parameters in order, and\n    the sum absolute change is calculated once after all the sequences are \n    processed.\n\n\\setlength{\\parskip}{1ex}\n    \\end{boxedminipage}\n\n    \\index{QSTK \\textit{(package)}!QSTK.qstklearn \\textit{(package)}!QSTK.qstklearn.hmm \\textit{(module)}!QSTK.qstklearn.hmm.HMMLearner \\textit{(class)}|)}\n    \\index{QSTK \\textit{(package)}!QSTK.qstklearn \\textit{(package)}!QSTK.qstklearn.hmm \\textit{(module)}|)}\n", "meta": {"hexsha": "29e4c4125d59b4f3a19c3fbff601c94d710695a4", "size": 12758, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Docs/pdf/QSTK.qstklearn.hmm-module.tex", "max_stars_repo_name": "elxavicio/QSTK", "max_stars_repo_head_hexsha": "4981506c37227a72404229d5e1e0887f797a5d57", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 339, "max_stars_repo_stars_event_min_datetime": "2015-01-01T10:06:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T23:32:24.000Z", "max_issues_repo_path": "Legacy/Docs/pdf/QSTK.qstklearn.hmm-module.tex", "max_issues_repo_name": "jenniyanjie/QuantSoftwareToolkit", "max_issues_repo_head_hexsha": "0eb2c7a776c259a087fdcac1d3ff883eb0b5516c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2015-01-04T13:12:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-19T11:13:47.000Z", "max_forks_repo_path": "Legacy/Docs/pdf/QSTK.qstklearn.hmm-module.tex", "max_forks_repo_name": "jenniyanjie/QuantSoftwareToolkit", "max_forks_repo_head_hexsha": "0eb2c7a776c259a087fdcac1d3ff883eb0b5516c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 154, "max_forks_repo_forks_event_min_datetime": "2015-01-30T09:41:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T02:27:59.000Z", "avg_line_length": 40.1194968553, "max_line_length": 263, "alphanum_fraction": 0.6443799969, "num_tokens": 3867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3225471630310558}}
{"text": "%!TEX root = morusAC.tex\n\n\\section{Analysis on Initialization and Finalization of Reduced \\texorpdfstring{\\MORUS}{MORUS}}\n\\label{sec/IniFin}\n\nThe bias in the previous sections analysed the encryption part of the \\MORUS. In this section, for comprehensive security analysis of \\MORUS, we provide new attacks on reduced version of the initialization and the finalization. We emphasize that the results in this section do not threaten any security claim by the designers. However, we believe that investigating all parts of the design with different approaches from the existing work on \\MORUS provides a better understanding and will be useful especially when the design will be tweaked in future.\n\n\\subsection{Forgery with Reduced Finalization}\n\\label{subsec/Fin}\nWe present forgery attacks on 3 out of 10 steps of \\MORUS[1280] that claims 128-bit security for integrity. The attack only works for a limited number of steps, while it works in the nonce-respecting setting. As far as we know, this is the first attempt to evaluate integrity of \\MORUS in the nonce-respecting setting.\n\n\\subsubsection{Overview.}\nA general strategy for forgery attacks in the nonce-respecting setting is to inject some difference in a message block and propagate it so that it can be canceled by a difference in another message block. However this approach does not work well against \\MORUS due to its large state size which prevents an attacker from easily controlling the differences in different registers. \n\nHere we focus on the property that the padding for an associated data $A$ and a message $M$ is the zero-padding, hence $A$ and $A'=A\\|0^*$ and $M$ and $M'=M\\|0$ result in identical states after the associated data processing and the encryption parts, as long as $A,A'$ and $M,M'$ fit in the same number of blocks. During the finalization, since $A,A'$ (resp. $M,M'$) have different lengths, the corresponding 64-bit values $\\adlen$ (resp. $\\msglen$) are different, which appears as $\\Delta \\adlen$ (resp. $\\Delta \\msglen$) during the finalization, and is injected through the message input interface. Our strategy is to propagate this difference to the 128-bit tags $T$ and $T'$ such that their difference $\\Delta T$ appears with higher probability than $2^{-128}$. All in all, the forgery succeeds as long as the desired $\\Delta T$ is obtained or in other words, the attacker does not have to cancel the state difference, which is the main advantage of attacking the finalization part of the scheme. \n\nNote that if the attacker uses different messages $M,M'$, not only the new tag $T'$ but also new ciphertext $C'$ must be guessed correctly. Because the encryption of \\MORUS is a simple XOR of the key stream, $C'$ can be easily guessed. For this purpose, the attacker should first query a longer message $M'=M\\|0^*$ to obtain $C'$. Then, $C$ can be obtained by truncating $C'$.\n\n\\subsubsection{Differential Trails.}\nRecall that the message input during the finalization of \\MORUS[1280] is $\\adlen\\mathrel\\|\\msglen\\mathrel\\|0^{128}$ where $\\adlen$ and $\\msglen$ are 64-bit strings. We set $\\Delta \\adlen$ to be of low Hamming weight, e.g.,~{\\tt 0x0000000000000001}. \n%Hereafter, we use {\\tt typefont} denote hexadecimal numbers.\nThis difference propagates through 3 steps as specified in \\Cref{Tbl:fin_diff}.\n\nRecall that each step consists of 5 rounds and the input message is absorbed to the state in rounds 2 to 5. The trail in \\Cref{Tbl:fin_diff} initially does not have any difference and the same continues even after round 1. Differences start to appear from round 2 and they will go through the bitwise-AND operation from round 4. We need to pay 1 bit to control each active AND gate. The probability evaluation for round 15 can be ignored since in this round only $S_4$ is non-linearly updated, while $S_4$ is never used for computing the tag. Finally, bitwise-AND in the tag computation is taken into account. Note that the tag is only 128 LSBs, thus the number of active AND gates should be counted only for those bits. As shown in \\Cref{Tbl:fin_diff}, we can have a particular tag difference $\\Delta T$ with probability $2^{-88}$. Thus after observing $A$ and corresponding $T$, $A\\|0$ and $(T \\oplus \\Delta T)$ is a valid pair with probability $2^{-88}$.\n\n\\begin{table}[!tb]\n\\begin{center}\n\\caption{Differential propagation through 3 Steps. Five lines for round $i$ denote the difference of $S_0, \\cdots, S_4$ after the round $i$ transformation.} %Weight is a Hamming weight of the state difference and accumulated probability is a probability to satisfy the trail from the beginning.}\n\\label{Tbl:fin_diff}\n{%\n\\iflncsmargins\n\\tiny\n\\else\n\\scriptsize\n\\renewcommand{\\arraystretch}{0.9}\n\\fi\n\\begin{tabular}{ccccccc} \\hline\nRound & \\multicolumn{4}{c}{State difference} & Weight & Accumulated probability \\\\ \\hline\n%      & & & &                                &        & \n      & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 0  & \\\\\n      & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 0  & \\\\\nIni   & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 0  & $-$ \\\\\n      & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 0  & \\\\\n      & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 0  & \\\\ \\hline\n\n      & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 0  & \\\\\n      & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 0  & \\\\\n1     & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 0  & $1$\\\\\n      & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 0  & \\\\\n      & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 0  & \\\\ \\hline\n\n      & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 0  & \\\\\n      & {\\tt 0000400000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 1  & \\\\\n2     & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 0  & $1$\\\\\n      & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 0  & \\\\\n      & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 0  & \\\\ \\hline\n\n      & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 0  & \\\\\n      & {\\tt 0000400000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 1  & \\\\\n3     & {\\tt 0000004000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 1  & $1$\\\\\n      & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 0  & \\\\\n      & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 0  & \\\\ \\hline\n\n      & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 0  & \\\\\n      & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000400000000000} & {\\tt 0000000000000000} & 1  & \\\\\n4     & {\\tt 0000004000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 1  & $1$\\\\\n      & {\\tt 0020000000000080} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 2  & \\\\\n      & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 0  & \\\\ \\hline\n\n      & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 0  & \\\\\n      & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000400000000000} & {\\tt 0000000000000000} & 1  & \\multirow{3}{*}{$2^{-1}$}\\\\\n5     & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000004000000000} & 1  & \\\\\n      & {\\tt 0020000000000080} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 2  & \\\\\n      & {\\tt 0000040000000010} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 2  & \\\\ \\hline\n\n      & {\\tt 0000000000100004} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 2  & \\\\\n      & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000400000000000} & {\\tt 0000000000000000} & 1  & \\multirow{3}{*}{$2^{-3}$}\\\\\n6     & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000004000000000} & 1 & \\\\\n      & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0020000000000080} & 2  & \\\\\n      & {\\tt 0000040000000010} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 2  & \\\\ \\hline\n\n      & {\\tt 0000000000100004} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 2  & \\\\\n      & {\\tt 0004400001000000} & {\\tt 0000000000000000} & {\\tt 0000000010000000} & {\\tt 0000000000000000} & 4  & \\multirow{3}{*}{$2^{-6}$}\\\\\n7     & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000004000000000} & 1  & \\\\\n      & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0020000000000080} & 2  & \\\\\n      & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000040000000010} & {\\tt 0000000000000000} & 2  & \\\\ \\hline\n\n      & {\\tt 0000000000000000} & {\\tt 0000000000100004} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 2  & \\\\\n      & {\\tt 0004400001000000} & {\\tt 0000000000000000} & {\\tt 0000000010000000} & {\\tt 0000000000000000} & 4  & \\multirow{3}{*}{$2^{-10}$}\\\\\n8     & {\\tt 0400014000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000001000} & 4  & \\\\\n      & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0020000000000080} & 2  & \\\\\n      & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000040000000010} & {\\tt 0000000000000000} & 2  & \\\\ \\hline\n\n      & {\\tt 0000000000000000} & {\\tt 0000000000100004} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 2  & \\\\\n      & {\\tt 0000000010000000} & {\\tt 0000000000000000} & {\\tt 0004400001000000} & {\\tt 0000000000000000} & 4  & \\multirow{3}{*}{$2^{-14}$}\\\\\n9     & {\\tt 0400014000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000001000} & 4  & \\\\\n      & {\\tt 0220000080000080} & {\\tt 0000000000000000} & {\\tt 0000000800000000} & {\\tt 1000000000004000} & 7  & \\\\\n      & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000040000000010} & {\\tt 0000000000000000} & 2  & \\\\ \\hline\n\n      & {\\tt 0000000000000000} & {\\tt 0000000000100004} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & 2  & \\\\\n      & {\\tt 0000000010000000} & {\\tt 0000000000000000} & {\\tt 0004400001000000} & {\\tt 0000000000000000} & 4  & \\multirow{3}{*}{$2^{-20}$}\\\\\n10    & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000001000} & {\\tt 0400014000000000} & 4  & \\\\\n      & {\\tt 0220000080000080} & {\\tt 0000000000000000} & {\\tt 0000000800000000} & {\\tt 1000000000004000} & 7  & \\\\\n      & {\\tt 4000140000000010} & {\\tt 0000000000000000} & {\\tt 0000400000000100} & {\\tt 0000000000010000} & 7  & \\\\ \\hline\n\n      & {\\tt 0000100000100044} & {\\tt 0000000200008000} & {\\tt 0001000000000000} & {\\tt 0000000008000200} & 9  & \\\\\n      & {\\tt 0000000010000000} & {\\tt 0000000000000000} & {\\tt 0004400001000000} & {\\tt 0000000000000000} & 4  &\\multirow{3}{*}{$2^{-28}$} \\\\\n11    & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000001000} & {\\tt 0400014000000000} & 4  & \\\\\n      & {\\tt 0000000000000000} & {\\tt 0000000800000000} & {\\tt 1000000000004000} & {\\tt 0220000080000080} & 7  & \\\\\n      & {\\tt 4000140000000010} & {\\tt 0000000000000000} & {\\tt 0000400000000100} & {\\tt 0000000000010000} & 7  & \\\\ \\hline\n\n      & {\\tt 0000100000100044} & {\\tt 0000000200008000} & {\\tt 0001000000000000} & {\\tt 0000000008000200} & 9  & \\\\\n      & {\\tt 0004500005000400} & {\\tt 0000000000000000} & {\\tt 0040000100000040} & {\\tt 4000000000000000} & 10 & \\multirow{3}{*}{$2^{-39}$}\\\\\n12    & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000001000} & {\\tt 0400014000000000} & 4  & \\\\\n      & {\\tt 0000000000000000} & {\\tt 0000000800000000} & {\\tt 1000000000004000} & {\\tt 0220000080000080} & 7  & \\\\\n      & {\\tt 0000400000000100} & {\\tt 0000000000010000} & {\\tt 4000140000000010} & {\\tt 0000000000000000} & 7  & \\\\ \\hline\n\n      & {\\tt 0000000008000200} & {\\tt 0000100000100044} & {\\tt 0000000200008000} & {\\tt 0001000000000000} & 9  & \\\\\n      & {\\tt 0004500005000400} & {\\tt 0000000000000000} & {\\tt 0040000100000040} & {\\tt 4000000000000000} & 10 & \\multirow{3}{*}{$2^{-53}$}\\\\\n13    & {\\tt 0400114000040000} & {\\tt 0020000000000080} & {\\tt 0004000000400000} & {\\tt 0000800100005002} & 14 &\\\\\n      & {\\tt 0000000000000000} & {\\tt 0000000800000000} & {\\tt 1000000000004000} & {\\tt 0220000080000080} & 7  & \\\\\n      & {\\tt 0000400000000100} & {\\tt 0000000000010000} & {\\tt 4000140000000010} & {\\tt 0000000000000000} & 7  & \\\\ \\hline\n\n      & {\\tt 0000000008000200} & {\\tt 0000100000100044} & {\\tt 0000000200008000} & {\\tt 0001000000000000} & 9  & \\\\\n      & {\\tt 0040000100000040} & {\\tt 4000000000000000} & {\\tt 0004500005000400} & {\\tt 0000000000000000} & 10 & \\multirow{3}{*}{$2^{-69}$}\\\\\n14    & {\\tt 0400114000040000} & {\\tt 0020000000000080} & {\\tt 0004000000400000} & {\\tt 0000800100005002} & 14 & \\\\\n      & {\\tt 0228000280020080} & {\\tt 0000040000000000} & {\\tt 2000008000202008} & {\\tt 1000004000004021} & 18 & \\\\\n      & {\\tt 0000400000000100} & {\\tt 0000000000010000} & {\\tt 4000140000000010} & {\\tt 0000000000000000} & 7  & \\\\ \\hline\n\n%Weight: 69\n      & {\\tt 0000000008000200} & {\\tt 0000100000100044} & {\\tt 0000000200008000} & {\\tt 0001000000000000} & 9  & \\\\\n      & {\\tt 0040000100000040} & {\\tt 4000000000000000} & {\\tt 0004500005000400} & {\\tt 0000000000000000} & 10 & \\\\\n15    & {\\tt 0020000000000080} & {\\tt 0004000000400000} & {\\tt 0000800100005002} & {\\tt 0400114000040000} & 14 & $-$\\\\\n      & {\\tt 0228000280020080} & {\\tt 0000040000000000} & {\\tt 2000008000202008} & {\\tt 1000004000004021} & 18 & \\\\\n      & {\\tt 0000400000000100} & {\\tt 0000000000010000} & {\\tt 4000140000000010} & {\\tt 0000000000000000} & 7  & \\\\ \\hline\n\n$\\Delta T$ &                   &                        & {\\tt 600080830020f00a} & {\\tt 1405414005044421} & & $2^{-88}$ \\\\ \\hline\n\\end{tabular}\n}\n\\end{center}\n\\end{table}\n\n\\subsubsection{Remarks.} The fact that the $S_4$ is updated in the last round but is not used in the tag generation implies that the \\MORUS finalization generally includes unnecessary computations with respect to security. It may be interesting to tweak the design such that the tag can also depend on $S_4$. Indeed in \\Cref{Tbl:fin_diff}, we can observe some jump-up of the probability in the tag computation. This is because the non-linearly involved terms are $S_2 \\cdot S_3$, and $S_3$ that was updated 2 rounds before has a high Hamming weight. In this sense, involving $S_4$ in non-linear terms of the tag computation imposes more difficulties for the attacker.\n\n\n\n\n\\subsection{Extending State Recovery to Key Recovery}\n\\label{subsec/Ini}\nKales et al.~\\cite{cryptoeprint:2017:1137} showed that the internal state of \\MORUS[640] can be recovered under the nonce-misuse scenario using $2^5$ plaintext-ciphertext pairs. As claimed by \\cite{cryptoeprint:2017:1137} the attack is naturally extended to \\MORUS[1280] though Kales et al. \\cite{cryptoeprint:2017:1137} did not demonstrate specific attacks. The recovered state allows the attacker to mount a universal forgery attack under the same nonce. However, the key still cannot be recovered because the key is used both at the beginning and end of the initialization, which prevents the attacker from backtracking the state value to the initial state. In this section, we show that meet-in-the-middle attacks allow the attacker to recover the key faster than exhaustive search for a relatively large number of steps, i.e., 10 out of 16 steps in \\MORUS[1280]. \n\n\\subsubsection{Overview.}\nWe divide the 10 steps of the initialization computation into two subsequent parts $F_0$ and $F_1$. (We later set that $F_0$ is the first 4 steps and $F_1$ is the last 6 steps.) Let $S^{-10}$ be the initial state value before setting the key, i.e., $S^{-10} = (\\IV\\mathrel\\|0^{128},0^{256},1^{256},0^{256},\\const_0\\mathrel\\|\\const_1)$. Also let $S^0$ be 1280-bit state value after the initialization, which is now assumed to be recovered with the nonce-misuse analysis~\\cite{cryptoeprint:2017:1137}. We then have the following relation.\n\\begin{align*}\n%F_1 \\circ F_0 \\bigl(S^{-10} \\oplus (0, K\\|K, 0, 0, 0)\\bigr) \\oplus (0,K\\|K,0,0,0) = S^0.\nF_1 \\circ F_0 \\bigl(S^{-10} \\oplus (0, K, 0, 0, 0)\\bigr) \\oplus (0,K,0,0,0) = S^0.\n\\end{align*}\nWe target the variant \\MORUS[1280-128], where $K = K_{128} \\mathrel\\| K_{128}$.\n\nHere, our strategy is to recover $K_{128}$ by independently processing $F_0$ and $F_1^{-1}$ to find the following match.\n\\begin{align*}\n  F_0 (S^{-10} \\oplus (0, K_{128}\\|K_{128}, 0, 0, 0)) \\stackrel{?}{=} F_1^{-1} (S^0 \\oplus (0,K_{128}\\|K_{128},0,0,0)).\n\\end{align*}\n\nTo evaluate the attack complexity, we consider the following parameters.\n\\begin{itemize}\n\\item $G_0$: a set of bits of $K_{128}$ that are guessed for computing $F_0$.\n\\item $G_1$: a set of bits of $K_{128}$ that are guessed for computing $F_1^{-1}$.\n\\item $G_2$: a set of bits in the intersection of $G_0$ and $G_1$.\n\\item $x$ bits can match after processing $F_0$ and $F_1^{-1}$.\n\\end{itemize}\nSuppose that the union of $G_0$ and $G_1$ covers all the bits of $K_{128}$. The attack exhaustively guesses $G_2$ and performs the following procedure for each guess.\n\\begin{enumerate}\n\\item $F_0$ is computed $2^{|G_0|-|G_2|}$ times and the results are stored in a table $T$. (Because $|G_1|-|G_2|$ bits are unknown, only a part of the state is computed.)\n\\item $F_1^{-1}$ is computed $2^{|G_1|-|G_2|}$ times and for each result we check the match with any entry in $T$.\n\\item The number of possible combinations is $2^{|G_0|-|G_2| + |G_1|-|G_2|}$, and the number of valid matches reduces to $2^{|G_0|-|G_2| + |G_1|-|G_2| - x}$ after matching the $x$ bits.\n\\item Check the correctness of the guess by using one plaintext-ciphertext pair.\n\\end{enumerate}\n\nIn the end,\n$F_0$ is computed $2^{|G_2|} \\cdot 2^{|G_0|-|G_2|} = 2^{|G_0|}$ times.\nSimilarly, $F_1^{-1}$ is computed $2^{|G_1|}$ times. The number of the total candidates after the $x$-bit match is $2^{|G_2|} \\cdot 2^{|G_0|-|G_2| + |G_1|-|G_2| - x} = 2^{|G_0| + |G_1| - |G_2| - x}$. Hence, the key $K_{128}$ is recovered with complexity $$\\max( 2^{|G_0|}, 2^{|G_1|}, 2^{|G_0| + |G_1| - |G_2| - x}).$$\nSuppose that we choose $|G_0|$ and $|G_1|$ to be balanced i.e., $|G_0|=|G_1|$. Then, the complexity is $$\\max( 2^{|G_0|}, 2^{2|G_0| - |G_2| - x}).$$\nTwo terms are balanced when $x = |G_0| - |G_2|$. Hence, the number of matched bits in the middle of two functions must be greater than or equal to the number of independently guessed bits to compute $F_0$ and $F_1^{-1}$.\n\nIn the attack below, we choose $|G_0|=|G_1|=127$ and $|G_2|=126$ (equivalently $|G_2|-|G_0| = |G_2|-|G_1| = 1$) in order to aim $x=1$-bit match in the middle, which maximizes the number of attacked rounds.\n\n\\begin{table}\n\\caption{Analysis of the diffusion and matching bits over 10 steps. `0' and `1' denote that the state bit can and cannot be computed from a partial knowledge of $K_{128}$, respectively. After the partial computations from each direction, 4 bits of $S^{-6}$ can match.} \n\\label{Tbl:ini_diffuse}\n\\centering\n{\n\\iflncsmargins\n\\tiny\n\\else\n\\footnotesize\n\\renewcommand{\\arraystretch}{0.9}\n\\fi\n\\begin{tabular}{ccccc} \\hline\nRound & \\multicolumn{4}{c}{State Difference}\\\\ \\hline\n                         & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} \\\\\n\\multirow{3}{*}{$S^{-10}\\oplus K_{128}$} & {\\tt 0000000000000000} & {\\tt 0000000000000001} & {\\tt 0000000000000000} & {\\tt 0000000000000001} \\\\\n  & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} \\\\\n                         & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} \\\\\n                         & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} \\\\ \\hline\n\n      & {\\tt 0000000000002000} & {\\tt 0000000000000000} & {\\tt 0000000000002000} & {\\tt 0000000000000000} \\\\\n      & {\\tt 0000000000000000} & {\\tt 0000400000000000} & {\\tt 0000000000000000} & {\\tt 0000400000000000} \\\\\n1     & {\\tt 0008000000000000} & {\\tt 0000000000000000} & {\\tt 0008000000000000} & {\\tt 0000000000000000} \\\\\n      & {\\tt 0000000000100000} & {\\tt 0020000000000000} & {\\tt 0000000000100000} & {\\tt 0020000000000000} \\\\\n      & {\\tt 0000000000020000} & {\\tt 0084000000000000} & {\\tt 0000000000020000} & {\\tt 0084000000000000} \\\\ \\hline\n\n      & {\\tt 0800000000000004} & {\\tt 0000000204000001} & {\\tt 0800000000000004} & {\\tt 0000000204000001} \\\\\n      & {\\tt 8000000a00000000} & {\\tt 0000002110000004} & {\\tt 8000000a00000000} & {\\tt 0000002110000004} \\\\\n2     & {\\tt 0400010221000000} & {\\tt 008000400a000081} & {\\tt 0400010221000000} & {\\tt 008000400a000081} \\\\\n      & {\\tt 1000050001000244} & {\\tt 4200118a08000280} & {\\tt 1000050001000244} & {\\tt 4200118a08000280} \\\\\n      & {\\tt 880004a0a0200858} & {\\tt 4840123350000050} & {\\tt 880004a0a0200858} & {\\tt 4840123350000050} \\\\ \\hline\n\n      & {\\tt 023d63c00050a850} & {\\tt 00a1442000489380} & {\\tt 023d63c00050a850} & {\\tt 00a1442000489380} \\\\\n      & {\\tt 02b63380056aaa48} & {\\tt 00b5563005dcd6c0} & {\\tt 02b63380056aaa48} & {\\tt 00b5563005dcd6c0} \\\\\n3     & {\\tt d42ab556bf5dfcd6} & {\\tt 5a26f633a8556aaa} & {\\tt d42ab556bf5dfcd6} & {\\tt 5a26f633a8556aaa} \\\\\n      & {\\tt 5fbbf556bd556c65} & {\\tt 7aab99aaee6bea2c} & {\\tt 5fbbf556bd556c65} & {\\tt 7aab99aaee6bea2c} \\\\\n      & {\\tt abff7f3ad7feafad} & {\\tt cfff777ffddffd6d} & {\\tt abff7f3ad7feafad} & {\\tt cfff777ffddffd6d} \\\\ \\hline\n\n      & {\\tt fff77dfffffdcf57} & {\\tt fefad7efffdffbf7} & {\\tt fff77dfffffdcf57} & {\\tt fefad7efffdffbf7} \\\\\n      & {\\tt ffffffffffffbfff} & {\\tt fffbf7fffddfff77} & {\\tt ffffffffffffbfff} & {\\tt fffbf7fffddfff77} \\\\\n4     & {\\tt ffffffffffffffff} & {\\tt ffffffffffffffff} & {\\tt ffffffffffffffff} & {\\tt ffffffffffffffff} \\\\\n      & {\\tt ffffffffffffffff} & {\\tt fffbffffefffffff} & {\\tt ffffffffffffffff} & {\\tt fffbffffefffffff} \\\\\n      & {\\tt ffffffffffffffff} & {\\tt ffffffffffffffff} & {\\tt ffffffffffffffff} & {\\tt ffffffffffffffff} \\\\ \\hline \n%\n%      \n      &                        & 2-bits match           & {\\tt                 } & 2-bits match            \\\\ \\hline\n%\n%\n      & {\\tt ffffffffffffffff} & {\\tt ffffffffffffffff} & {\\tt ffffffffffffffff} & {\\tt ffffffffffffffff} \\\\\n      & {\\tt ffffffffffffffff} & {\\tt ffffffffffffffff} & {\\tt ffffffffffffffff} & {\\tt ffffffffffffffff} \\\\\n5     & {\\tt ffffffffffffffff} & {\\tt ffffffffffffffff} & {\\tt ffffffffffffffff} & {\\tt ffffffffffffffff} \\\\\n      & {\\tt fffff7ffedfffff7} & {\\tt ffffffffedffffff} & {\\tt fffff7ffedfffff7} & {\\tt ffffffffedffffff} \\\\\n      & {\\tt ffffffffedffffff} & {\\tt fffff7ffedfffff7} & {\\tt ffffffffedffffff} & {\\tt fffff7ffedfffff7} \\\\ \\hline\n      \n      & {\\tt ffffffffedffffff} & {\\tt fffff7ffedfffff7} & {\\tt ffffffffedffffff} & {\\tt fffff7ffedfffff7} \\\\\n      & {\\tt fffbf5e7cdfffbf7} & {\\tt fffff7bfcdfff757} & {\\tt fffbf5e7cdfffbf7} & {\\tt fffff7bfcdfff757} \\\\\n6     & {\\tt fffbf5e7cdfffbf7} & {\\tt fffff7bfcdfff757} & {\\tt fffbf5e7cdfffbf7} & {\\tt fffff7bfcdfff757} \\\\\n      & {\\tt 7ffd75b6cdfff357} & {\\tt fffbf5a6ccfcfb73} & {\\tt 7ffd75b6cdfff357} & {\\tt fffbf5a6ccfcfb73} \\\\\n      & {\\tt 7ffbf5a6ccfcf373} & {\\tt 7ff975b6ccfff353} & {\\tt 7ffbf5a6ccfcf373} & {\\tt 7ff975b6ccfff353} \\\\ \\hline\n\n      & {\\tt 7efbf5a6cc7cf353} & {\\tt 7fd975a6cceff353} & {\\tt 7efbf5a6cc7cf353} & {\\tt 7fd975a6cceff353} \\\\\n      & {\\tt 7eb950a4cc78e353} & {\\tt 7dd07184cced7153} & {\\tt 7eb950a4cc78e353} & {\\tt 7dd07184cced7153} \\\\\n7     & {\\tt 7eb950a4cc78e353} & {\\tt 7dd07184ccec7153} & {\\tt 7eb950a4cc78e353} & {\\tt 7dd07184ccec7153} \\\\\n      & {\\tt 7cd051044c6c3153} & {\\tt 3e985024cc48a313} & {\\tt 7cd051044c6c3153} & {\\tt 3e985024cc48a313} \\\\\n      & {\\tt 3c905004cc482313} & {\\tt 7c9051044c6c2113} & {\\tt 3c905004cc482313} & {\\tt 7c9051044c6c2113} \\\\ \\hline\n\n      & {\\tt 2c905004c4482113} & {\\tt 7c9050040c682113} & {\\tt 2c905004c4482113} & {\\tt 7c9050040c682113} \\\\\n      & {\\tt 2810100444082112} & {\\tt 5c1010040c402113} & {\\tt 2810100444082112} & {\\tt 5c1010040c402113} \\\\\n8     & {\\tt 2810100444082112} & {\\tt 1c1010040c402113} & {\\tt 2810100444082112} & {\\tt 1c1010040c402113} \\\\\n      & {\\tt 0c00100404400113} & {\\tt 2800000404082112} & {\\tt 0c00100404400113} & {\\tt 2800000404082112} \\\\\n      & {\\tt 0800000404002112} & {\\tt 0800100404400113} & {\\tt 0800000404002112} & {\\tt 0800100404400113} \\\\ \\hline\n\n      & {\\tt 0800000404002112} & {\\tt 0800100004000112} & {\\tt 0800000404002112} & {\\tt 0800100004000112} \\\\\n      & {\\tt 0000000404000102} & {\\tt 0000100004000110} & {\\tt 0000000404000102} & {\\tt 0000100004000110} \\\\\n9     & {\\tt 0000000404000102} & {\\tt 0000000004000110} & {\\tt 0000000404000102} & {\\tt 0000000004000110} \\\\\n      & {\\tt 0000000004000110} & {\\tt 0000000000000102} & {\\tt 0000000004000110} & {\\tt 0000000000000102} \\\\\n      & {\\tt 0000000000000100} & {\\tt 0000000004000110} & {\\tt 0000000000000100} & {\\tt 0000000004000110} \\\\ \\hline\n\n      & {\\tt 0000000000000100} & {\\tt 0000000004000100} & {\\tt 0000000000000100} & {\\tt 0000000004000100} \\\\\n      & {\\tt 0000000000000000} & {\\tt 0000000004000100} & {\\tt 0000000000000000} & {\\tt 0000000004000100} \\\\\n10    & {\\tt 0000000000000000} & {\\tt 0000000000000100} & {\\tt 0000000000000000} & {\\tt 0000000000000100} \\\\\n      & {\\tt 0000000000000100} & {\\tt 0000000000000000} & {\\tt 0000000000000100} & {\\tt 0000000000000000} \\\\\n      & {\\tt 0000000000000000} & {\\tt 0000000000000100} & {\\tt 0000000000000000} & {\\tt 0000000000000100} \\\\ \\hline\n\n                     & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} \\\\\n\\multirow{3}{*}{$S^0\\oplus K_{128} $} & {\\tt 0000000000000000} & {\\tt 0000000000000100} & {\\tt 0000000000000000} & {\\tt 0000000000000100} \\\\\n                     & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} \\\\\n                     & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} \\\\\n                     & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} & {\\tt 0000000000000000} \\\\ \\hline\n\n\\end{tabular}\n}\n\\end{table}\n\n\\subsubsection{Full Diffusion Rounds.}\nWe found that {\\tt StepUpdate} was designed to have good diffusion in the forward direction. Thus, once the state is recovered, the attacker can perform the partial computation in the backward direction longer than the forward direction. We set $G_0$ and $G_1$ as follows.\n\\begin{align*}\nG_0 &= \\{1, 2, \\cdots, 127\\} & \\textrm {Bit position 0 is unknown.}\\\\\nG_1 &= \\{0, 1, \\cdots, 7, 9, 10, \\cdots, 127\\} & \\textrm {Bit position 8 is unknown.}\n\\end{align*}\nThose will lead to 4 matching bits after the 4-step forward computation and the 6-step backward computation. The analysis of the diffusion is given in \\Cref{Tbl:ini_diffuse}. In the end, $K_{128}$ can be recovered faster than the exhaustive search by 1 bit, i.e., with complexity $2^{127}$.\n\n\\subsubsection{Remarks.}\nThe matching state does not have to be a border of a step. It can be defined on a border of a round, or even in some more complicated way. We did not find the extension of the number of attacked steps even with this way. \n\nAs can be seen in \\Cref{Tbl:ini_diffuse}, the updated register in step $i$ is independent of the update function in step $i+1$ in the forward direction, and starts to impact from step $i+2$. By modifying this point, the diffusion speed can increase faster, which makes this attack harder.\n", "meta": {"hexsha": "9afaebd8cc20e2c9543568b40041c0d72e1a598a", "size": 28388, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "AC2018_camera_ready/morusAC_07_IniFin.tex", "max_stars_repo_name": "ildyria/MiniMorus", "max_stars_repo_head_hexsha": "168b27e059a46714bfe86af0cead20b4f6a51fcb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AC2018_camera_ready/morusAC_07_IniFin.tex", "max_issues_repo_name": "ildyria/MiniMorus", "max_issues_repo_head_hexsha": "168b27e059a46714bfe86af0cead20b4f6a51fcb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AC2018_camera_ready/morusAC_07_IniFin.tex", "max_forks_repo_name": "ildyria/MiniMorus", "max_forks_repo_head_hexsha": "168b27e059a46714bfe86af0cead20b4f6a51fcb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 96.8873720137, "max_line_length": 1001, "alphanum_fraction": 0.6742285473, "num_tokens": 10727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3225471630310558}}
{"text": "\\chapter{Time-Frequency Masking}\\label{ch:tf_mask_ch}\n\\section{Introduction}\nSpeech separation, in similarity to other \nprevalent enhancement applications, such as the \nComputational Auditory Scene Analysis (CASA)\\cite{BROWN1994297}\nand Blind Speech Separation (BSS)\\cite{6709849},\nmakes use of various\nalgorithms in order to distinguish in one way or another\nbetween desired speech and interferences.\nThe advantages of precise distinction \nbetween speech and interference include, among others,\nthe ability to apply speech enhancements, \nnoise cancelation or reduction, speech corrections, and more.\nWith ASR systems, these abilities are expressed in \nimproved performance of precisely detecting words\nwith higher detection rates.\n\nA typical algorithm in CASA applications is the \nTime-Frequency Masking (T-F Masking). \nSince speech signals vary with time, \nas described in chapter \\;\\ref{ch:features}, \nthey are not considered stationary. \nHence, a unique representation is required \nfor conducting an accurate analysis of such signals. \n\nA T-F representation means presenting a speech \nsignal in time-frequency composition, \nwhere each T-F unit contains the \nspeech's spectral elements at a certain time window bin. \nAs described in chapter\\;\\ref{ch:features}, \nthe T-F presentation of a signal \narrives by using the STFT or auditory filtering\\cite{Xia2017UsingOR}.\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=\\linewidth]{Features/images/noisy_specgram}\n    \\caption{Noisy mixture spectrogram}\\label{fig:noisy_specgram}\n\\end{figure}\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=\\linewidth]{Features/images/clean_specgram}\n    \\caption{Reference clean speech spectrogram}\\label{fig:clean_specgram}\n\\end{figure}\n\nExamination of the T-F units provides a \npossibility to classify an entire unit\nor parts of a unit \nas a speech-centric bin or, on the contrary, \nas interference (mainly noise). \nBased on this classification, \nappropriate weights are associated with each segment bin.\nIn that way, speech elements can be extracted \nby separating of the classified speech \nout of the mixture, or alternatively, \nthe attenuation of non-speech elements \nin certain activity areas \nalong the length of the audio signal.\nIn general, the association of weights for classifying different\nelements in a signal is called T-F masking. \nThis process of T-F masking takes a \nsignificant role in CASA and BSS applications, \nand in recent years, they proved to be \nvery useful in E2E-ASR systems.\n\nAdditional use of T-F masking \nis to tie it as input to a beamformer that\nin turn, filters interferences based \non the classification received \nby the masking operation.\n\n\\section{IBM --- Ideal Binary Mask}\nAssuming that a voice activity detection algorithm\ncan separate speech from noise effectively,\nthe IBM technique is based on power differences.\nWhenever the speech's power \nspectral density (PSD) is higher \nthan any of the interferences PSD, \nthe speech is masked binarily to ``1''.\n\\begin{align}\\label{eq:ibm_mask}\n    \\mathbf{M}_{s}(j\\omega, t) & = \n        \\begin{cases}\n            1, & if\\;|\\mathbf{S}(t,j\\omega)|^2 - |\\mathbf{N}(t,j\\omega)|^2 > \\epsilon \\\\\n            0, & otherwise\n        \\end{cases}\n\\end{align}\nWhere \\(\\epsilon\\) marks a changeable threshold value \nfor the speech activity detection over the noise.\n\nEquation~\\ref{eq:ibm_mask} indicates that as a result of \napplying the IBM masks, the speech and interference separated\nsources become complementary in such a way that\n\\[\\mathbf{M}_{n} = 1 - \\mathbf{M}_{s} \\] and thus:\n\\begin{align}\n    y(t) &= \\begin{cases}\n        \\hat{x_{s}}, &if\\;\\;\\mathbf{M}_{s} = 1 \\\\\n        \\hat{x_{n}}, &if\\;\\;\\mathbf{M}_{s} = 0\n    \\end{cases}\n\\end{align}\n\n\\section{IRM --- Ideal Ratio Mask}\n% \\begin{align}\n%     \\mathrm{IRM}(f;t) = \\left( \\frac{ || }{  } \\right)\n% \\end{align}\nUnlike IBM, where hard decisions in terms of \nboolean values are made,\nthat is, marking speech or noise \nelements with ``true'' or ``false'', the Ideal Ratio Mask (IRM) provides a soft decision\nmechanism with values in the range of \\([0,1]\\)\\cite{Jiang2018RobustBF}.\nThe IRMs at any T-F unit of the clean speech and noise artifacts,\n\\(\\mathbf{M}_{s}(j\\omega, t)\\) and \\(\\mathbf{M}_{n}(j\\omega, t)\\),\nare given in \nEquations\\;\\ref{eq:irm_speech} and \\ref{eq:irm_noise}, respectively.\n\n\\begin{align}\n    \\label{eq:irm_speech}\\mathbf{M}_{s}(j\\omega, t) & = {\\left( \\frac{|\\mathbf{S}(t,j\\omega)|^2}{|\\mathbf{S}(t,j\\omega)|^2 + |\\mathbf{N}(t,j\\omega)|^2} \\right)}^{\\beta} \\\\\n    \\label{eq:irm_noise}\\mathbf{M}_{n}(j\\omega, t) & = {\\left( \\frac{|\\mathbf{N}(t,j\\omega)|^2}{|\\mathbf{S}(t,j\\omega)|^2 + |\\mathbf{N}(t,j\\omega)|^2} \\right)}^{\\beta}\n\\end{align}\n \nWhere \\(\\beta \\) is a tunable parameter that \ncontrols the strength of the mask estimations. \nA value of 0.5 is used \nfor a fair trade-off between speech and noise mask estimations.\n%\n\\begin{align}\n    \\mathbf{M}_{s}(j\\omega, t) & = \\sqrt{\\left( \\frac{|\\mathbf{S}(t,j\\omega)|^2}{|\\mathbf{S}(t,j\\omega)|^2 + |\\mathbf{N}(t,j\\omega)|^2} \\right)} \\\\\n    \\mathbf{M}_{n}(j\\omega, t) & \\approx 1 - \\mathbf{M}_{s}\n\\end{align}\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=\\linewidth]{Features/images/irm_mask}\n    \\caption{IRM Speech Mask \\(\\mathbf{M}_{s}(j\\omega, t)\\)}\\label{fig:irm_mask}\n\\end{figure}\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=\\linewidth]{Features/images/irm_mask_noise}\n    \\caption{IRM Noise Mask \\(\\mathbf{M}_{n}(j\\omega, t)\\)}\\label{fig:irm_mask_noise}\n\\end{figure}\n\n%\nThus, the covariance matrices are extracted by:\n\\begin{align}\n    \\mathbf{R}_{NN}(j\\omega) & = \\frac{1}{\\sum\\limits_{t=1}^{T}\\mathbf{M}_{n_{(jw, t)}}}\\sum_{t=1}^{T}\\mathbf{M}_{n_{(jw, t)}}|\\mathbf{R}_{x_{(jw, t)}}|^2\\\\\n    \\mathbf{R}_{SS}(j\\omega) & = \\frac{1}{\\sum\\limits_{t=1}^{T}\\mathbf{M}_{s_{(jw, t)}}}\\sum_{t=1}^{T}\\mathbf{M}_{s_{(jw, t)}}|\\mathbf{R}_{x_{(jw, t)}}|^2\n\\end{align}\n\n\\subsection{Masks Estimations}\nThe IRM masks, \\(\\mathbf{M}_{s}(j\\omega, t)\\), \\(\\mathbf{M}_{n}(j\\omega, t)\\)\ngiven in Equations\\;\\ref{eq:irm_speech}, \\ref{eq:irm_noise} are bounded\nin the range of [0, 1]. \nSince both the speech and noise masks are bounded in that range, it is easier\nto use a Sigmoid activation function\nas the output layer, \nthus ensuring the output indeed remains in this range.\n\nA simple neural network of six to eight fully-connected (FC) layers,\nas seen in Figure\\;\\ref{fig:irm_dnn}, is proposed for\nclassifying the input features to the desired IRM masks.\nThe network's input features are the MFCCs of the microphone-array.\nEach input signal is framed into \\(25ms\\) lasting frames with a\nhopping length of \\(6.25ms\\). With a sampling frequency of \\(16KHz\\), \nthe framing settings are 400 samples per frame and \na total of 300 overlapping samples. \n\nA BLSTM (Bidirectional Long Short-Term Memory)\nlayer is placed as the first block in the network,\ngiving weight to the temporal context as well.\nIn that way, three additional adjacent feature maps \nare concatenated from both sides of the currently \nprocessed T-F unit feature map.\nThe BLSTM is then followed \nby several fully connected (FC) layers \nholding in between the ReLU activation functions.\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=0.95\\linewidth]{Features/images/irm_dnn}\n    \\caption{IRM estimation DNN blocks diagram}\\label{fig:irm_dnn}\n\\end{figure}\n\nProduction of both the speech and noise estimations co-occurs. \nConsequently, the cost function should \nconsider the two masks in the \nminimization process of the error term.\nTo that end, the cost function is defined as:\n\\begin{align}\n    \\ell(\\mathbf{\\widehat{M}}_{j\\omega, t},\\;\\mathbf{M}_{j\\omega, t}) & = \n        \\frac{1}{2N}\\sum_{j\\omega, t}\n        \\left[ \n            \\beta\\!\\left( \n                \\mathbf{\\widehat{M}}^{(s)}_{j\\omega, t} - \n                \\mathbf{M}^{(s)}_{j\\omega, t} \n            \\right)^{2} \n            + \\left( 1- \\beta \\right)\\!\n            \\left(\n                \\mathbf{\\widehat{M}}^{(n)}_{j\\omega, t} - \n                \\mathbf{M}^{(n)}_{j\\omega, t} \n            \\right)^{2} \n        \\right]\n\\end{align}\nHere, \\(\\beta\\) denotes the weighing factor.\nFor a fair and evenly consideration between the masks, \\(\\beta \\)\nis set to 0.5.\n\nThe proposed IRM estimation network blocks diagram is shown in \nFigure\\;\\ref{fig:irm_nn}.\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=0.75\\linewidth]{Beamformers/images/irm_nn}\n    \\caption{Proposed DNN for IRM T-F masking estimations}\\label{fig:irm_nn}\n\\end{figure}\n\n\n\\begin{figure}[H]\n    \\centering\n    \\subfloat[\\label{irm_s_ref}]{%\n       \\includegraphics[width=0.45\\linewidth]{Beamformers/images/irm_s_ref}}\n    \\hspace{0.1cm}\n    \\subfloat[\\label{irm_s_nn}]{%\n        \\includegraphics[width=0.45\\linewidth]{Beamformers/images/irm_s_nn}}\n    \\vspace{-0.35cm}\n    \\subfloat[\\label{irm_n_ref}]{%\n        \\includegraphics[width=0.45\\linewidth]{Beamformers/images/irm_n_ref}}\n    \\hspace{0.1cm}\n    \\subfloat[\\label{irm_n_nn}]{%\n        \\includegraphics[width=0.45\\linewidth]{Beamformers/images/irm_n_nn}}\n        \\caption{(a) and (b) are the ``IRM'' \n        reference vs. estimation masks of the speech.\n        \\(\\mathbf{\\widehat{M}}^{(s)}_{j\\omega, t}\\), \\(\\mathbf{M}^{(s)}_{j\\omega, t}\\);\\;\\;\n        (c) and (d) are the ``IRM'' reference vs. estimation masks \n        of the noise \\(\\mathbf{\\widehat{M}}^{(n)}_{j\\omega, t}\\), \\(\\mathbf{M}^{(n)}_{j\\omega, t}\\).}\\label{fig:irm_ref_s_n} \n\\end{figure}\n\n\n\\subsection{Measurements}\n\\subsubsection{SNR}\n\\begin{figure}[H]\n    \\centering\n    \\subfloat[\\label{irm_enh_snr}]{%\n       \\includegraphics[width=0.5\\linewidth]{Features/images/irm_enh_snr}}\n    % \\hspace{0.1cm}\n    \\subfloat[\\label{irm_noisy_snr}]{%\n        \\includegraphics[width=0.5\\linewidth]{Features/images/irm_noisy_snr}}\n    \\caption{(a) ``IRM'' enhanced SNR \\& Segmental-SNR degradation\n        with respect to the clean reference speech;\\;\\;\n        (b) The SNR \\& Segmental-SNR ratios between the\n        clean reference speech and the noisy mixture.}\\label{fig:irm_enh_noisy_snr} \n\\end{figure}\n\nFigure\\;\\ref{fig:irm_enh_noisy_snr} shows two measurements of the SNR \\&\nSegmental-SNR metrics for two subject signals, \nan ``IRM'' enhanced beamformed\nversion of the noisy mixture and the noisy mixture itself\nwith respect to the clean reference speech.\nThe overall improvements in SNR and Segmental-SNR \nare the ratios between the enhanced beamformed signal\nand the noisy mixture. Thus, from Figure\\;\\ref{fig:irm_enh_noisy_snr}\nthe accumulated improvement in SNR is:\n\\[|SNR_{noisy}| - |SNR_{enh}| = 5.1725\\;[dB]\\]\nLikewise, the improvement in Segmental-SNR is \\(9.2675\\;[dB]\\).\nIt is important to note that the enhanced beamformed signal\ndoes not align in time with the clean speech reference. \nIn a worst-case scenario, we measured a delay of \\(-0.0014\\;[s]\\),\nwhich equals approximately \\(22\\) samples. \nA perfectly aligned comparison considers being more \naccurate, but since the frame lengths' (400 samples)\nare much larger than the worst measured delay, \nthe impact of this time misalignment is less acute.\nThe Segmental-SNR calculation involves \na VAD (voice activity detection) algorithm\nfor dropping segments where the detected speech activity is negligible.\nThese dropped segments are red colored in Figure\\;\\ref{fig:irm_enh_noisy_snr}.\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=\\linewidth]{Experiments/images/irm_pesq_mosq}\n    \\caption{IRM beamformer PESQ vs. MOSLQ}\\label{fig:irm_pesq_mosq}\n\\end{figure}\n\nIn Figure\\;\\ref{fig:irm_pesq_mosq} presented the ``PESQ'' and ``MOSLQ'' \nmetrics for the IRM beamformer. The results are shown in a pair-plot\ndiagram, where the correlations between each pair of metrics are plotted.\nOn the diagonal, the distributions of the measured values are shown.\nOn top of the plots also shown are the mean values for both \nthe ``PESQ'' and ``MOSLQ'' under the test cases of the real and \nsimulation datasets from the ``CHiME4'' dataset. ``et'' stands for\nthe evaluation subset and ``dt'' marks the development subset.\nMore details about the datasets are provided in Chapter\\;\\ref{ch:datasets}.\n\nA strong correlation between the ``PESQ'' and ``MOSLQ'' is seen in the\nplot, and this behavior is both understandable and desirable since\nthe ``MOSLQ'' metric is based on the ``PESQ'' measurement.\n\nAnother pair-plot for the SNR, ``Segmental-SNR'', ``SI-SNR'' and ``STOI''\nmetrics is shown in Figure\\;\\ref{fig:irm_snr_stoi}.\nThe ``simulation'' subset yields better results in terms of\nperformance. It is important to note that faulty microphones\nin the ``real'' subset are dropped prior to taking the measurements.\nNevertheless, the ambient noise absorbed is characterized by\na real scenario and a non-artificial room impulse response. On the other hand,\nthe ``simulation'' subset is composed of a recording taken in a relatively\nclean environment (recording booth) and an artificial mixture of\nthe recorded background noises.\n\nBecause the SNR and Segmental-SNR are measured as the improvement\ncompared to the noisy mixture, \nand since the background noises are truncated \nto match the booth recorded speech for the ``simulation'' subset, \nthe results for those metrics are more sparsely distributed \ncompared to the ``real'' subset measurements. \nWith the ``SI-SNR'', \nthe measurements are taken regardless of the noisy mixture. \nHence, the ``simulation'' results are far better \nand more spatially dense \nin contrast to the ``real'' subset ``SI-SNR'' results.\n\nLikewise, in the same manner, \nthe ``STOI'' is measured regardless of the noisy mixture\nbut relatively to the clean speech. \nTherefore, the ``simulation'' \nsubset distribution is narrower with lower variance.\n\n% The results are summarized in Table\\;\\ref{tbl:irm_snr_stoi},\n% side by side with the ideal masks and the improvement ratios.\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=\\linewidth]{Features/images/irm_snr_stoi}\n    \\caption{IRM beamformer SNR vs. Segmental-SNR vs. STOI vs. SI-SNR}\\label{fig:irm_snr_stoi}\n\\end{figure}\n\nIn order to evaluate the generalization of the prediction model,\nthe DNN estimations are compared to the ideal mask enhancement.\nIn Figure\\;\\ref{fig:irm_ideal_snr}, shown is the measurements of \nthe SNR and ``Segmental-SNR'' for an ideal IRM mask.\nSNR measurement.\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=\\linewidth]{Features/images/irm_ideal_snr}\n    \\caption{Ideal IRM beamformer enhancement SNR \\& Segmental-SNR.}\\label{fig:irm_ideal_snr}\n\\end{figure}\n\n\n\n\\section{cIRM --- Complex Ideal Ratio Mask}\\label{ssec:cirm}\nBoth IBM and IRM utilize the noise and speech magnitudes only\nwhile completely neglecting the phase arguments.\nThe outcome of the STFT operation is a complex pair\nrepresentation of each T-F unit. Recent studies\nshowed the importance of \nthe phase element in \nspeech seperation\\cite{7364200,Xia2017UsingOR}.\n\nIn that manner, further extension of the IRM mask \nto include the imaginary part \naltogether with the magnitudes forms the cIRM. \nThus, instead of having a magnitude only based mask matrix, a complex\npair of masking matrices that make use of the phase element too is given.\n\nThe mixture \\(y(t)\\) after being processed by\nthe STFT operation can be described as a complex sum\nwhether in polar coordinates as seen in Equation\\ref{eq:ystft_polar}\nor in the general form as in Equation\\ref{eq:ystft_general}.\n\\begin{align}\\label{eq:ystft_polar}\n    \\mathbf{Y}(j\\omega, t)  & = \\mathcal{STFT} \\{ y(t) \\} := \\mathbf{Y}_{j\\omega, t} \\nonumber \\\\\n                            & = |\\mathbf{A}_{_{\\mathbf{Y}}}|\\cos(\\bm{\\theta}_{_{\\mathbf{Y}}}) \n                            + j|\\mathbf{A}_{_{\\mathbf{Y}}}|\\sin(\\bm{\\theta}_{_{\\mathbf{Y}}}) \\\\\n\\label{eq:ystft_general}      & = \\mathbf{Y}_{r} + j\\mathbf{Y}_{i}\n\\end{align}\n\nThe real and imaginary parts can be summarized as:\n\\begin{align}\n    \\mathbf{Y}_{r} & := \\mathfrak{R}_{_{\\mathfrak{C}}} \\{\\mathbf{Y}_{j\\omega, t}\\} \n                            = |\\mathbf{A}_{_{\\mathbf{Y}}}|\\cos(\\bm{\\theta}_{_{\\mathbf{Y}}})  \\\\\n    \\mathbf{Y}_{i} & := \\mathfrak{T}_{_{\\mathfrak{M}}} \\{\\mathbf{Y}_{j\\omega, t}\\} \n                            = |\\mathbf{A}_{_{\\mathbf{Y}}}|\\sin(\\bm{\\theta}_{_{\\mathbf{Y}}})\n\\end{align}\nExtraction of the magnitude and phase from the complex representation \nis accomplished by the following set of \nEquations\\ref{eq:complex_mag},\\ref{eq:complex_phase}:\n\\begin{align}\\label{eq:complex_mag}\n    |\\mathbf{A}_{_{\\mathbf{Y}}}|    & = \\sqrt{ \\mathfrak{R}_{_{\\mathfrak{C}}} \\{\\mathbf{Y}_{j\\omega, t}\\}^{2}\n                                            + \\mathfrak{T}_{_{\\mathfrak{M}}} \\{\\mathbf{Y}_{j\\omega, t}\\}^{2} } \\\\\n    \\label{eq:complex_phase}\\bm{\\theta}_{_{\\mathbf{Y}}}     & = \\tan^{-1} \\Bigg\\{ \\frac{ \\mathfrak{T}_{_{\\mathfrak{M}}} \\{\\mathbf{Y}(j\\omega, t)\\} }\n                                            {\\mathfrak{R}_{_{\\mathfrak{C}}} \\{\\mathbf{Y}(j\\omega, t)\\}} \\Bigg\\}\n\\end{align}\nRearranging the equations above, \nwe can write the cIRM mask's real and \nimaginary parts as:\n\\begin{align}\n    \\mathbf{M}_{r} & = \\frac{\\mathbf{Y}_{r}\\mathbf{S}_{r} + \\mathbf{Y}_{i}\\mathbf{S}_{i}}\n                            { \\mathbf{Y}_{r}^{2} + \\mathbf{Y}_{i}^{2}} \\\\\n    \\mathbf{M}_{i} & = \\frac{\\mathbf{Y}_{r}\\mathbf{S}_{i} - \\mathbf{Y}_{i}\\mathbf{S}_{r}}\n                            { \\mathbf{Y}_{i}^{2} + \\mathbf{S}_{r}^{2}}\n\\end{align}\nThus, the complex masks for the speech and noise are: \n\\begin{align}\n    \\mathbf{M}^{(s)}_{j\\omega, t} & = \\mathbf{M}^{(s)}_{r} + j\\mathbf{M}^{(s)}_{i} \\nonumber \\\\\n            & = \\frac{\\mathbf{Y}_{r}\\mathbf{S}_{r} + \\mathbf{Y}_{i}\\mathbf{S}_{i}}\n            { \\mathbf{Y}_{r}^{2} + \\mathbf{Y}_{i}^{2}} \n            + j \\frac{\\mathbf{Y}_{r}\\mathbf{S}_{i} - \\mathbf{Y}_{i}\\mathbf{S}_{r}}\n            { \\mathbf{Y}_{i}^{2} + \\mathbf{S}_{r}^{2}} \\label{eq:cirmr_mask} \\\\\n    \\mathbf{M}^{(n)}_{j\\omega, t} & = \\mathbf{M}^{(N)}_{r} + j\\mathbf{M}^{(N)}_{i} \\nonumber \\\\\n    & = \\frac{\\mathbf{Y}_{r}\\mathbf{N}_{r} + \\mathbf{Y}_{i}\\mathbf{N}_{i}}\n    { \\mathbf{Y}_{r}^{2} + \\mathbf{Y}_{i}^{2}} \n    + j \\frac{\\mathbf{Y}_{r}\\mathbf{N}_{i} - \\mathbf{Y}_{i}\\mathbf{N}_{r}}\n    { \\mathbf{Y}_{i}^{2} + \\mathbf{N}_{r}^{2}} \\label{eq:cirmi_mask}\n\\end{align}\nTherefore, applying a cIRM T-F masking requires a complex multiplication\nfor separation as opposed to the more basic IBM and IRM \nwhere magnitudes multiplications are taken in the real domain only.\n\nThe reference compressed cIRM masks are \nshown in Figure\\;\\ref{fig:cirm_ref_s_n};\n\n\\begin{figure}[H]\n    \\centering\n    \\subfloat[\\label{cIRM_real_mask}]{%\n       \\includegraphics[width=0.45\\linewidth]{Features/images/cIRM_real_mask}}\n    \\subfloat[\\label{cIRM_imag_mask}]{%\n        \\includegraphics[width=0.45\\linewidth]{Features/images/cIRM_imag_mask}}\n    \\vspace{-0.35cm}\n    \\subfloat[\\label{cIRM_real_noise_mask}]{%\n        \\includegraphics[width=0.45\\linewidth]{Features/images/cIRM_real_noise_mask}}\n    \\subfloat[\\label{cIRM_imag_noise_mask}]{%\n        \\includegraphics[width=0.45\\linewidth]{Features/images/cIRM_imag_noise_mask}}\n        \\caption{(a) and (b) are the cIRM\n        real and imaginary references of the speech \n        \\(\\mathbf{M}^{(s)}_{r}\\), \\(\\mathbf{M}^{(s)}_{i}\\);\\;\\;\n        (c) and (d) are the cIRM real and imaginary references \n        of the noise \\(\\mathbf{M}^{(n)}_{r}\\), \\(\\mathbf{M}^{(n)}_{i}\\).}\\label{fig:cirm_ref_s_n} \n\\end{figure}\n\n\\subsection{Masks Estimations}\nIn Section~\\ref{ssec:cirm}, \nthe \\(cIRM\\) masks are described in \nEquations~\\ref{eq:cirmr_mask},~\\ref{eq:cirmi_mask}.\nIn contrast to the \\(IRM\\) masks which are bounded in the range \\([0, 1]\\),\nthe \\(cIRM\\) masks are unbounded, and have the range \\((-\\infty, \\infty)\\).\n\nA neural network cannot train for unbounded values. \nHence, an alternative presentation to the mask values is needed.\nOne possibility is to compress the real and imaginary masks\nwith a hyperbolic tangent as suggested in \\cite{7364200}: \n\\begin{align}\\label{eq:cirm_compress}\n    cIRM_{x} &= K \\frac{1-e^{-C\\cdot M_{x}}}{1+e^{-C\\cdot M_{x}}}\n\\end{align}\nWhere \\(x\\) stands for the real or the imaginary parts of the mask.\nBy applying this compression, the mask values are bounded in\nthe range \\([-K, K]\\), while \\(C\\) controls the steepness.\nFor that purpose, we replaced the \nsimpler IRM DNN sigmoid layers placed at the output \nwith linear layers.\n\nThen, the cost function is defined to include both real and imaginary parts\nof both the noise and speech masks. \n\\begin{align}\n    \\ell(\\mathbf{\\widehat{M}}^{(x)}_{j\\omega, t},\\;\\mathbf{M}^{(x)}_{j\\omega, t}) & = \n        \\frac{1}{2N}\\sum_{j\\omega, t}\n        \\left[ \n            \\beta\\!\\left( \n                \\mathbf{\\widehat{M}}^{(s \\in \\mathbb{C})}_{j\\omega, t} - \n                \\mathbf{M}^{(s \\in \\mathbb{C})}_{j\\omega, t} \n            \\right)^{2} \n            + \\left( 1- \\beta \\right)\\!\n            \\left(\n                \\mathbf{\\widehat{M}}^{(n \\in \\mathbb{C})}_{j\\omega, t} - \n                \\mathbf{M}^{(n \\in \\mathbb{C})}_{j\\omega, t} \n            \\right)^{2} \n        \\right]\n\\end{align}\n\nThe proposed cIRM estimation network blocks \ndiagram is shown in Figure\\;\\ref{fig:cirm_nn}.\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=0.75\\linewidth]{Beamformers/images/cirm_nn}\n    \\caption{Proposed DNN for cIRM T-F masking estimations}\\label{fig:cirm_nn}\n\\end{figure}\n\n\n\\begin{figure}[H]\n    \\centering\n    \\subfloat[\\label{mel_fb_ref}]{%\n       \\includegraphics[width=0.45\\linewidth]{Beamformers/images/cirm_r_s_ref}}\n    \\hspace{0.1cm}\n    \\subfloat[\\label{mel_fbfcc_ref}]{%\n        \\includegraphics[width=0.444\\linewidth]{Beamformers/images/cirm_r_s_nn}}\n    \\caption{(a) Reference cIRM\n        real speech mask \\(\\mathbf{M}^{(s)}_{r}\\);\\;\\;\n        (b) The estimated cIRM\n        real speech \\(\\mathbf{\\widehat{M}}^{(s)}_{r}\\).}\\label{fig:cirm_nn_vs_ref} \n\\end{figure}\n\nFigure\\;\\ref{fig:cirm_nn_vs_ref} shows the reference real speech cIRM mask\ncompared to the estimated real speech mask predicted by the DNN model.\nLooking at the figure, one can conclude that the model generalized correctly\nas the estimated mask resembles the reference to a great extent.\nCompared to the ``IRM'' DNN performance, the cIRM model \nwith a compression in the range of \\([-10, 10]\\) performs better.\n\n\\subsection{Measurements}\nDue to the complexity of the cIRM DNN model, \nit did not generalize properly for the evaluation dataset\nwith a number of epochs settings set to 50.\nThe results hence, are not accurate as a reference nor for comparison,\nunless a retraining process is initialized with a sufficient number of epochs\nto let the model generalize.\n\nDue to the uncertainty of the impact the low number of epochs have\non the model performance, and the lack of time for a re-evaluation of the\nDNN mask estimation, we decide to skip the results and \nto drop the cIRM measurements.\n\n% \\begin{figure}[H]\n%     \\centering\n%     \\includegraphics[width=\\linewidth]{Experiments/images/irm_pesq_mosq}\n%     \\caption{IRM beamformer PESQ vs. MOSLQ}\\label{fig:irm_pesq_mosq}\n% \\end{figure}\n\n\\section{PSM --- Phase Sensitive Mask}\nThe PSM T-F masking makes use of the magnitude ratios and phase differences\nrather than requiring a complex multiplication.\nIn that way, the multiplication is taken in the real domain only,\nwhile utilizing the phase contribution directly.\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=\\linewidth]{Features/images/psm_mask}\n    \\caption{PSM Speech Mask \\(\\mathbf{M}_{s}(j\\omega, t)\\)}\\label{fig:psm_mask}\n\\end{figure}\n\\vspace{-0.5cm}\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=\\linewidth]{Features/images/psm_mask_noise}\n    \\caption{PSM Noise Mask \\(\\mathbf{M}_{n}(j\\omega, t)\\)}\\label{fig:psm_mask_noise}\n\\end{figure}\nThe following equations give the PSM masks for the reference speech and noise,\n\\(\\mathbf{M}^{(s)}_{j\\omega, t}\\) and \\(\\mathbf{M}^{(n)}_{j\\omega, t}\\):\n\\begin{align}\n    \\mathbf{M}^{(s)}_{j\\omega, t} & = \\frac{|\\mathbf{S}(t,j\\omega)|}{|\\mathbf{Y}(t,j\\omega)|} \\cos(\\bm{\\theta}_{_{\\mathbf{S}}} - \\bm{\\theta}_{_{\\mathbf{Y}}}) \\\\\n    \\mathbf{M}^{(n)}_{j\\omega, t} & = \\frac{|\\mathbf{N}(t,j\\omega)|}{|\\mathbf{Y}(t,j\\omega)|} \\cos(\\bm{\\theta}_{_{\\mathbf{N}}} - \\bm{\\theta}_{_{\\mathbf{Y}}})\n\\end{align}\n\n\\subsection{Masks Estimations}\nUnlike the cIRM complex masks, the PSM masks are real valued.\nHowever, the masks are not bounded similarly to the cIRM masks.\nTherefore, the proposed model for the cIRM masks can be reused\nwith a slight difference in implementation. \nNow, only two outputs are created \ninstead of branching to four outputs at the final layer.\nOne output for the speech mask and the other for the noise mask. \nThe same as we did for the ``IRM'' but without the Sigmoids.\nIn addition, to deal with the unbounded range of values, \nwe also apply apply a compression algorithm to the reference masks as well.\nThe compression mechanism is the same as \ndescribed in Equation\\;\\ref{eq:cirm_compress}.\n\nFollowing this architecture, the cost function can be set\nto take two masks in the calculation of the error term,\nlike with the ``IRM'' masks:\n\\begin{align}\\label{eq:psm_costf}\n    \\ell(\\mathbf{\\widehat{M}}_{j\\omega, t},\\;\\mathbf{M}_{j\\omega, t}) & = \n        \\frac{1}{2N}\\sum_{j\\omega, t}\n        \\left[ \n            \\beta\\!\\left( \n                \\mathbf{\\widehat{M}}^{(s)}_{j\\omega, t} - \n                \\mathbf{M}^{(s)}_{j\\omega, t} \n            \\right)^{2} \n            + \\left( 1- \\beta \\right)\\!\n            \\left(\n                \\mathbf{\\widehat{M}}^{(n)}_{j\\omega, t} - \n                \\mathbf{M}^{(n)}_{j\\omega, t} \n            \\right)^{2} \n        \\right]\n\\end{align}\n\nThe proposed PSM estimation network blocks diagram is shown in \nFigure\\;\\ref{fig:psm_nn}.\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=0.75\\linewidth]{Beamformers/images/psm_nn}\n    \\caption{Proposed DNN for PSM T-F masking estimations.}\\label{fig:psm_nn}\n\\end{figure}\n\n\\subsection{Measurements}\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=\\linewidth]{Features/images/psm_snr_stoi}\n    \\caption{PSM beamformer SNR vs. Segmental-SNR vs. STOI vs. SI-SNR.}\\label{fig:psm_snr_stoi}\n\\end{figure}\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=\\linewidth]{Features/images/psm_ideal_snr}\n    \\caption{Ideal PSM beamformer enhancement SNR \\& Segmental-SNR.}\\label{fig:psm_ideal_snr}\n\\end{figure}\n\n\n\n\\section{ORM --- Optimal Ratio Mask}\nThe realization of the phase component importance along with \nthe desire to keep the masking as simple as possible in terms of number \nof matrices and the simplicity of multiplication for separation,\nthe IRM masking is further developed.\n\nTrying to minimize the general MSE loss function for T-F masking,\nsame as with the ``Weiner filter'' that the IRM masking approximates, we get:\n\\begin{align}\n    \\mathbf{M}^{(s)}_{j\\omega, t} & = \\frac{\n        |\\mathbf{S}(t,j\\omega)|^{2}\n        + \\mathfrak{R}_{e}\\{ \\mathbf{S}(t,j\\omega) \\cdot {\\mathbf{N}}^{*}(t,j\\omega) \\}\n        }{\n            |\\mathbf{S}(t,j\\omega)|^{2} \n            + |\\mathbf{N}(t,j\\omega)|^{2}\n            + 2 \\mathfrak{R}_{e}\\{ \\mathbf{S}(t,j\\omega) \\cdot {\\mathbf{N}}^{*}(t,j\\omega) \\} \n        } \\\\\n    \\mathbf{M}^{(n)}_{j\\omega, t} & = \\frac{\n        |\\mathbf{N}(t,j\\omega)|^{2}\n        + \\mathfrak{R}_{e}\\{ \\mathbf{N}(t,j\\omega) \\cdot {\\mathbf{S}}^{*}(t,j\\omega) \\}\n        }{\n            |\\mathbf{S}(t,j\\omega)|^{2} \n            + |\\mathbf{N}(t,j\\omega)|^{2}\n            + 2 \\mathfrak{R}_{e}\\{ \\mathbf{N}(t,j\\omega) \\cdot {\\mathbf{S}}^{*}(t,j\\omega) \\} \n        }\n\\end{align}\n\nLooking at the equation above, \nit resembles the IRM form but also introduces\nthe real part of the multiplication between the speech spectrum\nand the conjugate noise spectrum.\n\n\\subsection{Masks Estimations}\nThe ORM masking in terms of the estimation process resembles the\nPSM completely. Therefore, the same compression and \nDNN architecture are used to estimate the ORM masks.\n\nThe proposed DNN model blocks diagram is shown in Figure\\;\\ref{fig:psm_nn},\nand the cost function is given in Equation\\;\\ref{eq:psm_costf}.\n\n\\subsection{Measurements}\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=\\linewidth]{Features/images/orm_snr_stoi}\n    \\caption{ORM beamformer SNR vs. Segmental-SNR vs. STOI vs. SI-SNR.}\\label{fig:orm_snr_stoi}\n\\end{figure}\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=\\linewidth]{Features/images/orm_ideal_snr}\n    \\caption{Ideal ORM beamformer enhancement SNR \\& Segmental-SNR.}\\label{fig:orm_ideal_snr}\n\\end{figure}\n\n% \\section{Masks Estimations}\n% \\subsection{IRM}\n\n% \\begin{align}\n%     \\ell(\\mathbf{\\widehat{M}}_{j\\omega, t},\\;\\mathbf{M}_{j\\omega, t}) & = \n%         \\frac{1}{2N}\\sum_{j\\omega, t}\n%         \\left[ \n%             \\beta\\!\\left( \n%                 \\mathbf{\\widehat{M}}^{(s)}_{j\\omega, t} - \n%                 \\mathbf{M}^{(s)}_{j\\omega, t} \n%             \\right)^{2} \n%             + \\left( 1- \\beta \\right)\\!\n%             \\left(\n%                 \\mathbf{\\widehat{M}}^{(n)}_{j\\omega, t} - \n%                 \\mathbf{M}^{(n)}_{j\\omega, t} \n%             \\right)^{2} \n%         \\right]\n% \\end{align}\n\n% \\begin{figure}[H]\n%     \\centering\n%     \\includegraphics[width=0.75\\linewidth]{Beamformers/images/irm_nn}\n%     \\caption{Proposed DNN for IRM T-F masking estimations}\\label{fig:irm_nn}\n% \\end{figure}\n\n% \\subsection{cIRM}\n% In Section~\\ref{ssec:cirm}, \n% the \\(cIRM\\) masks are described in \n% Equations~\\ref{eq:cirmr_mask},~\\ref{eq:cirmi_mask}.\n% In contrast to the \\(IRM\\) masks which are bounded in the range \\([0, 1]\\),\n% the \\(cIRM\\) masks are unbounded, and have the range \\((-\\infty, \\infty)\\).\n\n% A neural network cannot train for unbounded values. \n% Hence, an alternative presentation to the mask values is needed.\n% One possibility is to compress the real and imaginary masks\n% with a hyperbolic tangent as suggested in \\cite{}: \n% \\begin{align}\n%     cIRM_{x} &= K \\frac{1-e^{-C\\cdot M_{x}}}{1+e^{-C\\cdot M_{x}}}\n% \\end{align}\n\n% Where \\(x\\), stands for the real or the imaginary parts of the mask.\n% By applying this compression, the mask values are bounded in\n% the range \\([-K, K]\\), while \\(C\\) controls the steepness.\n% In that way, a linear layer at the output is placed\n% in favor of the sigmoid layers used in the simpler IRM DNN.\n\n% Then, the cost function is defined to include both real and imaginary parts\n% of both the noise and speech masks. \n% \\begin{align}\n%     \\ell(\\mathbf{\\widehat{M}}^{(x)}_{j\\omega, t},\\;\\mathbf{M}^{(x)}_{j\\omega, t}) & = \n%         \\frac{1}{2N}\\sum_{j\\omega, t}\n%         \\left[ \n%             \\beta\\!\\left( \n%                 \\mathbf{\\widehat{M}}^{(s \\in \\mathbb{C})}_{j\\omega, t} - \n%                 \\mathbf{M}^{(s \\in \\mathbb{C})}_{j\\omega, t} \n%             \\right)^{2} \n%             + \\left( 1- \\beta \\right)\\!\n%             \\left(\n%                 \\mathbf{\\widehat{M}}^{(n \\in \\mathbb{C})}_{j\\omega, t} - \n%                 \\mathbf{M}^{(n \\in \\mathbb{C})}_{j\\omega, t} \n%             \\right)^{2} \n%         \\right]\n% \\end{align}\n\n% \\begin{figure}[H]\n%     \\centering\n%     \\includegraphics[width=0.75\\linewidth]{Beamformers/images/cirm_nn}\n%     \\caption{Proposed DNN for cIRM T-F masking estimations}\\label{fig:cirm_nn}\n% \\end{figure}\n\n\n% \\subsection{PSM}\n\n% \\subsection{ORM}\n\n\\section{Conclusions}\nIn Table\\;\\ref{tbl:masks_l_params} are presented\nthe model's sizes in terms of memory requirement\nand the number of learnable parameters.\nThe model's parameters were quantized\nto the form of signed 16 bits. \nThe MSB (most significant bit) is for the sign,\nthe following four bits are set for the integer part,\nand the other eleven bits present the fractional part.\nAll of the tested models were trained with and without\nthe \\(\\Delta, \\Delta\\Delta\\) features.\nUsage of the additional \\(\\Delta, \\Delta\\Delta\\) features\nenlarges the input size of the model and thus\nleading to a larger number of learnable parameters, resulting\nin a bigger model. Bigger models take a longer time to train\nand are more complex to fit in limited resources hardware \ndevices. A trade-off decision can be made with respect to\nthe memory size and desired performance in the design phase\nof T-F masks based applications. Although presenting\nbetter results in audio metrics, the PSM and ORM\nmasks require \\(\\sim 43\\%\\) larger memory space\ncompared to the IRM masks, \nwhen the feature set does not include\nthe \\(\\Delta, \\Delta\\Delta\\) features.\nA less severe increase of \\(\\sim 22\\%\\) in memory \nsize requirement has been observed \nwhen the \\(\\Delta, \\Delta\\Delta\\) features\nwere not excluded from the feature set.\n\n\n\n\n\\begin{table}[H]\n    % for more info see: https://www.overleaf.com/learn/latex/tables\n    \\centering\n    % \\hspace*{-2.8cm}\n    \\arrayrulecolor{mtblborder}\n\\begin{tabular}{ !{\\color{mtblborder}\\vrule}c!{\\color{mtblborder}\\vrule}cc|||cc| } \n    \\hline\n\n    \\hline\n    \\rowcolor{mtblcaption}\n    & \\multicolumn{2}{c}{\\color{white}\\bf{Learnable Parameters} [Mil]}\n    & \\multicolumn{2}{c}{\\color{white}\\bf{Quant. (S16.11) Mem } [Mb]}\\\\         \n    % \\cline{2-8}\n    \n    \\multirow{-2}{*}{\\cellcolor{mtblcaption}\\color{white}\\bf{Targets} }\n    & \\cellcolor{mtbl} \\color{black}{W/o (\\(\\Delta\\),\\(\\Delta\\Delta\\))} \n    & \\cellcolor{mtbl} \\color{black}{W/ (\\(\\Delta\\),\\(\\Delta\\Delta\\))}\n    & \\cellcolor{mtbl} \\color{black}{W/o (\\(\\Delta\\),\\(\\Delta\\Delta\\))} \n    & \\cellcolor{mtbl} \\color{black}{W/ (\\(\\Delta\\),\\(\\Delta\\Delta\\))} \\\\\n    % & \\color{white}\\bf{ORM} \n    % & \\color{white}\\bf{Clean} \\\\\n    \\hline\n\n    \\hline\n    \\rowcolor{mtblA} IRM  \n        & 2.44 \n        & 4.67\n        & 39.0\n        & 74.8 \\\\\n    \\hline\n    \n    \\hline\n    \\rowcolor{mtbl} cIRM  \n        & 3.76\n        & 5.99\n        & 60.1\n        & 95.9 \\\\\n    \\hline\n\n    \\hline\n    \\rowcolor{mtblA} PSM  \n        & 3.49\n        & 5.73\n        & 55.9\n        & 91.7 \\\\\n    \\hline\n\n    \\hline\n    \\rowcolor{mtbl} ORM  \n        & 3.50\n        & 5.74\n        & 56.0\n        & 91.8 \\\\\n    \\hline\n    \n    \\hline\n\\end{tabular}\n\\arrayrulecolor{black}\n\\caption{T-F Masks models learnable parameters vs. Required memory size}\n\\label{tbl:masks_l_params}\n\\end{table}", "meta": {"hexsha": "a4e1340b50924d1331008cc1ffd1674d45bb53f0", "size": 34079, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Dissertation/Features/time_freq_masking.tex", "max_stars_repo_name": "aviadb/research", "max_stars_repo_head_hexsha": "d710d21cd18a5f5c01acf65d85c8ef364a3ca219", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Dissertation/Features/time_freq_masking.tex", "max_issues_repo_name": "aviadb/research", "max_issues_repo_head_hexsha": "d710d21cd18a5f5c01acf65d85c8ef364a3ca219", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Dissertation/Features/time_freq_masking.tex", "max_forks_repo_name": "aviadb/research", "max_forks_repo_head_hexsha": "d710d21cd18a5f5c01acf65d85c8ef364a3ca219", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.2578692494, "max_line_length": 171, "alphanum_fraction": 0.671909387, "num_tokens": 10494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.322508519735389}}
{"text": "%!TEX root = /home/renaud/Documents/EPL/tfe/latex/tfe.tex\n\\addcontentsline{toc}{chapter}{Introduction}\n\\chapter*{Introduction}\nThe understanding of geophysical and environmental fluid flows has shown an increasing interest over the past decades. Climate change, and the related issue of pollution have raised the need for accurate simulations allowing to understand and predict the time-space evolution of the concentration of pollutants in the environment. In this regard, the fate of constituents dissolved in a fluid mixture is commonly modelled by means of reactive-transport equations. Those are coupled partial differential equations taking into account the influence of \\textit{reactions} as well as of the advective and diffusive \\textit{transport phenomena} on the concentration of the constituent in the mixture. Accurate algorithms have been developed by engineers to numerically solve such equations. Finite differences, finite volume and finite elements methods are amongst the most commonly used discretization methods. However, they rely on grids containing thousands and in some instances millions of grid points so that CPU time can become prohibitive in cases where long time simulations are needed. Furthermore, although those methods provide pretty accurate results, these often suffer from a lack of \\textit{interpretation}. This raises the need for simpler models with a few number of variables that would allow for an easier interpretation of the results as well as for fast long time simulations. Obviously, one cannot expect such models to provide results that would be as accurate as the ones furnished by the previously mentioned methods. Hence, both approaches are complementary. \n\nOne way to build such coarser models is to partition the domain of interest into a relatively small number of subdomains, called \\textit{compartments} or \\textit{boxes} over which the state variables are assumed \\textit{homogeneous}. The fluxes between the compartments are then expressed by simple laws, leading to models that are relatively easy to interpret. This procedure leads to models called \\textit{compartment models} or equivalently \\textit{box models}. The number of subdomains and their shapes vary widely from one problem to another. Some schematic representations of compartment models found in the literature are shown in figure~\\ref{fig:intro:boxmodels}.\n\nBox models have been widely used in studies involving marine systems as well at local scale \\cite{deleersnijder1998two,maderich2014regional,soetaert1995estimating} as at global scale \\cite{kohler2005quantitative,munhoven1996glacial}. The choice of the subdomains and the specification of the fluxes exchanged between them rely on ad-hoc or empirical methods, based on the known hydrodynamics over the domain considered. It seems that no automatic procedure exists to define a relevant partitioning of the domain. The goal of this work is thus to fill that gap by proposing a method based on the tools of \\textit{network science} to automatically delineate relevant compartments.\n\nNetwork science may be defined as the study of graphs (or networks) and their use to model various (real-life or not) problems. Informally, a graph is a mathematical representation of a set of objects (the \\textit{nodes} or \\textit{vertices} of the graph), and the links between pairs of them (the \\textit{edges} of the graph). The field of application of network science is extremely large, as illustrated by this quote from Newman \\cite{newman2010networks}: \"\\textit{Many objects of interest in the physical, biological, and social sciences can be thought of as networks and [...] thinking of them in this way can often lead to new and useful insights}.\"\n\nOften, graphs exhibit a \\textit{community structure}: it is the case if the vertices can be organized into groups such that there are many interactions between the nodes within a group, and few interaction between the nodes of different groups. Such groups of vertices are called \\textit{communities} or \\textit{clusters}. An example of a three communities partitioning of a simple graph is shown in figure~\\ref{fiug:intro:communities}. The art of revealing the community structure of a graph has a long history in network science, and a variety of \\textit{community detection algorithms} and \\textit{heuristics} has been developed, see \\cite{fortunato2010community} for a 2010 survey. Clustering methods have shown to be useful for a wide applications such as social and biological networks \\cite{girvan2002community}, biochemical networks \\cite{holme2003subnetwork,guimera2005functional,palla2005uncovering}, or informations networks such as the world wide web \\cite{flake2002self}. What makes communities particularly appealing is that they often correspond to \\textit{functional units} such as cycles or pathways in metabolic networks \\cite{guimera2005functional,palla2005uncovering,huss2007currency} or collections of pages on a single topic on the web \\cite{flake2002self}. In the context of geophysical modeling, clustering methods have been used in works providing suggestions for the optimal placement of marine protected areas \\cite{thomas2014numerical,jacobi2012identification,rossi2014hydrodynamic}. In this work, we aim to show that communities may correspond to relevant compartments in the case of advection-diffusion flow networks. To this end, we focus on one relatively recent method for community detection based on the \\textit{stability} measure \\cite{delvenne2010stability,delvenne2013stability,lambiotte2009laplacian}.\n\nA complete procedure is proposed to build a compartment model from any problem whose velocity field and diffusivity tensor are known. First, the Lagrangian equations describing individual particles trajectories are derived from the transport model, and consistent numerical methods are proposed. This allows to compute the transition probability matrix at the desired times, which is the information needed to apply the stability clustering method. Finally, subdomains are delineated from the communities found by the clustering algorithm, and the exchange coefficients between the compartments are estimated numerically, completing the construction of the box model. This approach may be viewed\tas a special application of the theory of model order reduction~\\cite{deleersnijder2009reduction}. The whole procedure is applied on a simple, two dimensional test problem, and the resulting box model is assessed.  \n\nThe first part of the work gathers all the theoretical tools needed for that procedure. Chapter~\\ref{chap:clustering} is devoted to community detection and in particular to the \\textit{stability} measure and the related clustering algorithm. The reactive transport equation and the study of its properties is the topic of chapter~\\ref{chap:transportmodel}, whereas compartment models and their properties are studied in chapter~\\ref{chap:compartment}. Then, the link between the transport model and the Lagrangian equations describing the position of an individual particle is shown in chapter~\\ref{chap:numerical}, leading to the theory of stochastic differential equations and of the consistent numerical methods to solve them. The second part of this work consists in applying the procedure on a simple problem. An idealized, two-dimensional overturning circulation model is presented in~\\ref{chap:overturnercirculation} and is then used the build the test problem in chapter~\\ref{chap:bioverturner}. The complete procedure is applied on that test problem and assessed in the same chapter. \n\n\n\\begin{figure}[!htp]\n\t\\begin{subfigure}[t]{.47\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width=\\textwidth]{fig/intro/boxmodel_KohlerEtAl.png}\n\t\t\\caption{Geometry of the box model of the isotopic carbon cycle (BICYCLE), where the arrows represent carbon fluxes between the compartments. This is figure 1 of \\cite{kohler2005quantitative}.}\n\t\\end{subfigure}\n\t\t\\begin{subfigure}[t]{.51\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width=\\textwidth]{fig/intro/boxmodel_SoetaertHerman.png}\n\t\t\\caption{Representation of a subdomain decomposition of the Westerschelde. This is figure 1 of \\cite{soetaert1995estimating}.}\n\t\\end{subfigure}\n\t\\begin{subfigure}[b]{\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width=\\textwidth]{fig/intro/boxmodel_Munhoven.png}\n\t\t\\caption{Geometry and water fluxes of a compartmental model for the World Ocean. The fluxes are expressed in sverdrups ($1$ Sv = $10^6$ $\\rm{m^3/s}$). This is figure 3 of \\cite{munhoven1996glacial}.}\n\t\\end{subfigure}%\n\\caption{Schematic representations of different compartment models.}\\label{fig:intro:boxmodels}\n\\end{figure}\n\\begin{figure}[!htp]\n\t\\centering\n\t\\includegraphics[width=.4\\textwidth]{fig/intro/communities_example.png}\n\t\\caption{Example of a three-communities partitioning on a simple network.} \\label{fiug:intro:communities}\n\\end{figure}", "meta": {"hexsha": "c1c8d1073feb44e7cd5a717bf6ef16314e3e114e", "size": 8872, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "inputs/intro/intro.tex", "max_stars_repo_name": "dufaysr/tfe", "max_stars_repo_head_hexsha": "75c6191e1533da84233d4a38dea3cc3f3884a286", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inputs/intro/intro.tex", "max_issues_repo_name": "dufaysr/tfe", "max_issues_repo_head_hexsha": "75c6191e1533da84233d4a38dea3cc3f3884a286", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inputs/intro/intro.tex", "max_forks_repo_name": "dufaysr/tfe", "max_forks_repo_head_hexsha": "75c6191e1533da84233d4a38dea3cc3f3884a286", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 216.3902439024, "max_line_length": 1840, "alphanum_fraction": 0.8180793508, "num_tokens": 1983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.32243125960666685}}
{"text": "\\section{Results and interpretation}\r\n\\label{sec:results}\r\nTrying different network structures and extensive hyperparameter tuning results in a network which achieves an accuracy of $\\SI{84.4}{\\percent}$ on the validation set by using the\r\nhyperparameter values shown in \\autoref{tab:hyperparameters}.\r\nAn overview of the final network can be seen in \\autoref{fig:best_model}.\r\n\\begin{table}\r\n    \\centering\r\n    \\caption{A CNN using these hyperparameters can solve our problem the best. *= In the first convolutional layer and doubling from layer to layer afterwards.}\r\n    \\label{tab:hyperparameters}\r\n    \\begin{tabular}{c c c c c c c}\r\n        \\toprule\r\n        $N_\\text{conv. layers}$ & ${\\text{num}_\\text{kernels}}^*$ & $N_\\text{kernel}$ & $N_\\text{dense layers}$ & $N_\\text{dense nodes}$ & $r_\\text{L2}$ & $r_\\text{dropout}$ \\\\\r\n        \\midrule\r\n        5 & 48 & 4 & 1 & 128 & \\num{1e-5} & 0.3\\\\\r\n        \\bottomrule\r\n    \\end{tabular}\r\n\\end{table}\r\n\r\nThe final step of every machine-learing based work is the performance evaluation on data that was not used at any point in the work before.\r\nAfter the preprocessing we split $\\SI{15}{\\percent}$ of our data into a test set for this purpose.\r\nUsing our best performing model we achieve\r\n\\begin{align}\r\n    \\text{accuracy}_\\text{test} = \\SI{79.9}{\\percent}.\r\n\\end{align}\r\nThe significant gap between validation accuracy and test accuracy ($\\SI{4.5}{\\percent}$) might be due to the extensive hyperparameter tuning, while the validation and test datasets are quite small \r\n(50 images of each flower species).\r\nThis might lead to manual overfitting on the validation set during hyperparameter tuning.\r\n\r\nIt is also helpful to examine the distribution of the predicted probability for a single species, while distinguishing between the images which truly show a flower(s) of this species and\r\nall other images.\r\nThis is done in \\autoref{fig:hist} for \\enquote{Marguerite Daisy}.\r\nAnother import graphic for evaluating a classification is the \\textit{confusion matrix} which can be seen in \\autoref{fig:matrix}.\r\n\\begin{figure}\r\n    \\centering    \r\n    \\begin{subfigure}{0.49\\textwidth}\r\n        \\centering\r\n        \\includegraphics[width=0.99\\textwidth]{../data/eval_plots_test/One_vs_all_histogram.pdf}\r\n        \\caption{Probability distribution for \\enquote{Marguerite Daisy}.}\r\n        \\label{fig:hist}\r\n    \\end{subfigure}\r\n    \\hfill\r\n    \\begin{subfigure}{0.49\\textwidth}\r\n        \\centering\r\n        \\includegraphics[width=0.99\\textwidth]{../data/eval_plots_test/confusion_matrix.pdf}\r\n        \\caption{Confusion matrix.}\r\n        \\label{fig:matrix}\r\n    \\end{subfigure}\r\n    \\caption{The predicted probabilities for the class \\enquote{Marguerite Daisy} and the confusion matrix based on the test data set help to illustrate the performance of our classification model.}\r\n\\end{figure}\r\nThe probability distribution shows that out network is generally pretty certain of its classification of Marguerite Daisies, as most images (regardless if correctly classified or not) \r\nare in the highest or lowest bin.\r\n\r\nIf we look at both plots, we can see, that \\enquote{Marguerite Daisy} is the class which gets misclassified the most as only 31 of 50 images of Marguerite Daisies in the test set get \r\nclassified as such.\r\nThey get confused with Waterlilies the most, which, looking at \\autoref{fig:images}, might be caused by similarities in color and petal shape.\r\nHowever, there are also images of Waterlilies with different colors in our dataset\r\nSo it might be the case, that Waterlilies are the species which is hard to correctly classify and the (weak) classification criteria for Waterlilies just happen to also apply to Marguerite Daisies\r\nquite often.\r\nAnother interesting observation in \\autoref{fig:matrix} is, that Butterfly Bushs get confused with Bee Balm flowers and Grape Hyacinths a lot.\r\nBee Balm flowers come in very similar colors to Butterfly Bushes and the tattered-looking blossoms of Bee Balm flowers can look very similar to Butterfly Bushs which have already lost some of their \r\nblossoms.\r\nThe purple color and general shape of the flower head of Grape Hyacinths can make them look very much like Butterfly Bushs on images.\r\nIn reality the size of the flower head is very different, but this is not an information which our network has access to.\r\nHowever, real images of Grape Hyacinths do not get misclassified at all within our test set.\r\nThis can be caused by the very distinctive ball-like petal-shape (see \\autoref{fig:images}) which our network can probably detect very reliably in real images of Grape Hyacinths.\r\nMore interpretations like these for the other flower species are possible.\r\n\r\n\\begin{wrapfigure}{R}{0.75\\textwidth}\r\n    \\centering\r\n    \\includegraphics[width=0.75\\textwidth]{../data/eval_plots_test/biggest_errors.pdf}\r\n    \\caption{These six images get misclassified with the highest certainty in the wrong prediction.}\r\n    \\label{fig:errors}\r\n\\end{wrapfigure}\r\nThe six images which the network misclassifies with the highest certainty in its wrong prediction are shown in \\autoref{fig:errors}.\r\nThe image in the top left looks very similar to a Blanket Flower (like the one in the top middle) and the bottom left, bottom middle and top right image are drawings and have\r\na white/ white-grey background which probably makes it harder for the network due to a lack of contrast.\r\nThe Waterlilies on the bottom right image are very small and its color is very similar to a Grape Hyacinth, so this misclassification is understandable.\r\nThe only strange misclassification is the image in the top middle.\r\nA possible explanation is the network detecting something in the background of the image as resembling a Butterfly Bush.\r\n\r\n\r\n\\subsection{Alternative method}\r\nIn order to get a reference to compare the performance of our network to, we also try a different approach to the classification based on the eleven flower species.\r\nWe choose a \\textit{k-Nearest Neighbor} Algorithm (kNN) for this task, because it is one of the simplest machine-learning algorithms (\\textit{lazy learner}). \r\nSuitable input data for the kNN is generated by looking at a histogram of the color intensity of all three RGB colors (red, green, blue) for all pixels in an image.\r\nAn example of this can be seen in \\autoref{fig:kNN_hist}.\r\nThen the mean and the standart deviation for each color channel are calculated and used as input data for the kNN.\r\nThis results in an reduction of $200\\cdot 200 \\cdot 3 = 120.000$ parameters for each image to only $6$ parameters for each image.\r\n\r\nThe main hyperparameters of the kNN algorithm is the number of neighbors $k$ to consider for the classification of a new datapoint, as well as the distance metric used to decide which points are \r\nthe nearest ones.\r\nWe use the implementation of a kNN classifier in \\texttt{scikit-learn} \\cite{scikit-learn} with its default \\textit{Euclidean distance} as distance metric.\r\nWe then search for the optimal $k$ by looking at the accuracy the algorithm achieves on the validation data set for $k \\in [1, 300]$ which can be seen in \\autoref{fig:kNN_acc}.\r\n\\begin{wrapfigure}{r}{0.55\\textwidth}\r\n    \\centering\r\n    \\includegraphics[width=0.55\\textwidth]{../data/alternative_approach/accuracy_knn_threshold_300.pdf}\r\n    \\caption{The validation accuracy of the kNN algorithm for different $k$.}\r\n    \\label{fig:kNN_acc}\r\n\\end{wrapfigure}\r\nWe discard $k = 1, 2$, because there are images which are almost identical between the train and test set which distort the results for $k = 1, 2$.\r\nTherefore, $k = 82$ results in the best validation accuracy of $\\SI{39.0}{\\percent}$.\r\nApplying this kNN model on the test set achieves a classification accuracy of \r\n\\begin{align}\r\n    \\text{accuracy}_\\text{test, kNN} = \\SI{37.0}{\\percent}.\r\n\\end{align}\r\nConsidering the simplicity of the approach, this result is within an expected margin.\r\n", "meta": {"hexsha": "211822357077bf23f931e97097a31c480def8692", "size": 7889, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report_lukas/content/04_results.tex", "max_stars_repo_name": "LukasBeiske/project_Flowers-299", "max_stars_repo_head_hexsha": "c2315f8ad8e197c49622649d469e2dab802d8305", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "report_lukas/content/04_results.tex", "max_issues_repo_name": "LukasBeiske/project_Flowers-299", "max_issues_repo_head_hexsha": "c2315f8ad8e197c49622649d469e2dab802d8305", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report_lukas/content/04_results.tex", "max_forks_repo_name": "LukasBeiske/project_Flowers-299", "max_forks_repo_head_hexsha": "c2315f8ad8e197c49622649d469e2dab802d8305", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 73.7289719626, "max_line_length": 199, "alphanum_fraction": 0.7589048042, "num_tokens": 1915, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.3224312514868037}}
{"text": "\\documentclass{article}\n\n\\usepackage[utf8]{inputenc}\n\\usepackage[T1]{fontenc}\n\n\\begin{document}\n\n\\section*{Powers and indices}\n\n\\[x^2\\]\n\n\\[x_2\\]\n\n\\[^tM^{2}_{1}\\]\n\n% The command \\! removes a \"loose\" space for matrix transpose\n\\[^{t\\!}M^{2}_{1}\\]\n\n\\end{document}", "meta": {"hexsha": "77c881fbac78c389103011204f3e96f8a7055bf7", "size": 260, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "compendium/mathematics/powers-and-indices.tex", "max_stars_repo_name": "ZenLulz/LatexCompendium", "max_stars_repo_head_hexsha": "cc623a88ab05ca90430338333003293baea00f8c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-07-30T21:43:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-23T20:16:19.000Z", "max_issues_repo_path": "compendium/mathematics/powers-and-indices.tex", "max_issues_repo_name": "ZenLulz/LatexCompendium", "max_issues_repo_head_hexsha": "cc623a88ab05ca90430338333003293baea00f8c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "compendium/mathematics/powers-and-indices.tex", "max_forks_repo_name": "ZenLulz/LatexCompendium", "max_forks_repo_head_hexsha": "cc623a88ab05ca90430338333003293baea00f8c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.6842105263, "max_line_length": 61, "alphanum_fraction": 0.65, "num_tokens": 96, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.3224312514868036}}
{"text": "%!TEX root = ../OGUSAdoc.tex\n\nIn \\ogindia, the government enters by levying taxes on households, providing transfers to households, levying taxes on firms, spending resources on public goods, and making rule-based adjustments to stabilize the economy in the long-run. It is this last activity that is the focus of this chapter.\n\n\n\\section{Government Tax Revenue}\\label{SecUnbalGBCrev}\n\n  We see from the household's budget constraint that taxes $T_{s,t}$ and transfers $TR_{t}$ enter into the household's decision,\n  \\begin{equation}\\tag{\\ref{EqHHBC}}\n    \\begin{split}\n      c_{j,s,t} + b_{j,s+1,t+1} &= (1 + r_{t})b_{j,s,t} + w_t e_{j,s} n_{j,s,t} + \\zeta_{j,s}\\frac{BQ_t}{\\lambda_j\\omega_{s,t}} + \\eta_{j,s,t}\\frac{TR_{t}}{\\lambda_j\\omega_{s,t}} - T_{s,t}  \\\\\n      &\\quad\\forall j,t\\quad\\text{and}\\quad s\\geq E+1 \\quad\\text{where}\\quad b_{j,E+1,t}=0\\quad\\forall j,t\n    \\end{split}\n  \\end{equation}\n  where we defined the tax liability function $T_{s,t}$ in \\eqref{EqTaxCalcLiabETR} as an effective tax rate times total income and the transfer distribution function $\\eta_{j,s,t}$ is uniform across all households as in \\eqref{EqTaxCalcEtajs}. And government revenue from the corporate income tax rate $\\tau^{corp}$ and the tax on depreciation expensing $\\tau^\\delta$ enters the firms' profit function.\n  \\begin{equation}\\tag{\\ref{EqFirmsProfit}}\n    PR_t = (1 - \\tau^{corp})\\bigl(Y_t - w_t L_t\\bigr) - \\bigl(r_t + \\delta\\bigr)K_t + \\tau^{corp}\\delta^\\tau K_t \\quad\\forall t\n  \\end{equation}\n  We define total government revenue from taxes as the following.\n  \\begin{equation}\\label{EqUnbalGBCgovRev}\n    Rev_t = \\underbrace{\\tau^{corp}\\bigl[Y_t - w_t L_t\\bigr] - \\tau^{corp}\\delta^\\tau K_t}_{\\text{corporate tax revenue}} + \\underbrace{\\sum_{s=E+1}^{E+S}\\sum_{j=1}^J\\lambda_j\\omega_{s,t}\\tau^{etr}_{s,t}\\left(x_{j,s,t},y_{j,s,t}\\right)\\bigl(x_{j,s,t} + y_{j,s,t}\\bigr)}_{\\text{household tax revenue}} \\quad\\forall t\n  \\end{equation}\n\n\n\\section{Government Budget Constraint}\\label{SecUnbalGBCbudgConstr}\n\n  Let the level of government debt in period $t$ be given by $D_t$. The government budget constraint requires that government revenue $Rev_t$ plus the budget deficit ($D_{t+1} - D_t$) equal expenditures on interest of the debt, government spending on public goods $G_t$, and total transfer payments to households $TR_t$ every period $t$.\n  \\begin{equation}\\label{EqUnbalGBCbudgConstr}\n    D_{t+1} + Rev_t = (1 + r_t)D_t + G_t + TR_t \\quad\\forall t\n  \\end{equation}\n\n  We assume that total government transfers to households are a fixed fraction $\\alpha_{tr}$ of GDP each period.\n  \\begin{equation}\\label{EqUnbalGBCtfer}\n    TR_t = g_{tr,t}\\:\\alpha_{tr}\\: Y_t \\quad\\forall t\n  \\end{equation}\n  The time dependent multiplier $g_{tr,t}$ in front of the right-hand-side of \\eqref{EqUnbalGBCtfer} will equal 1 in most initial periods. It will potentially deviate from 1 in some future periods in order to provide a closure rule that ensures a stable long-run debt-to-GDP ratio. We will discuss the closure rule in Section \\ref{SecUnbalGBCcloseRule}.\n\n  We also assume that government spending on public goods is a fixed fraction of GDP each period in the initial periods.\n  \\begin{equation}\\label{EqUnbalGBC_Gt}\n    G_t = g_{g,t}\\:\\alpha_{g}\\: Y_t\n  \\end{equation}\n  Similar to transfers $TR_t$, the time dependent multiplier $g_{g,t}$ in front of the right-hand-side of \\eqref{EqUnbalGBC_Gt} will equal 1 in most initial periods. It will potentially deviate from 1 in some future periods in order to provide a closure rule that ensures a stable long-run debt-to-GDP ratio. We make this more specific in the next section.\n\n\n\\section{Interest Rate on Government Debt}\\label{SecRateWedge}\n\nDespite the model having no aggregate risk, it may be helpful to build in an interest rate differential between the rate of return on private capital and the interest rate on government debt.  Doing so helps to add realism by including a risk premium.  \\ogindia allows users to set an exogenous wedge between these two rates.  The interest rate on government debt,\n\n\\begin{equation}\\label{EqUnbalGBC_rate_wedge}\n  r_{gov, t} = (1 - \\tau_{d, t})r_{t} - \\mu_{d}\n\\end{equation}\n\nThe two parameters, $\\tau_{d,t}$ and $\\mu_{d,t}$ can be used to allow for a government interest rate that is a percentage hair cut from the market rate or a government interest rate with a constant risk premia.\n\nIn the cases where there is a differential ($\\tau_{d,t}$ or $\\mu_{d,t} \\neq 0$), then we need to be careful to specify how the household chooses government debt and private capital in its portfolio of asset holdings.  We make the assumption that under the exogenous interest rate wedge, the household is indifferent between holding its assets as debt and private capital. This amounts to an assumption that these two assets are perfect substitutes given the exogenous wedge in interest rates.  Given the indifference between government debt and private capital at these two interest rates, we assume that the household holds debt and capital in the same ratio that debt and capital are demanded by the government and private firms, respectively. The interest rate on the household portfolio of asset is thus given by:\n\n\\begin{equation}\\label{EqUnbalGBC_rate_wedge}\n  r_{hh,t} = \\frac{r_{gov,t}D_{t} + r_{t}K_{t}}{D_{t} + K_{t}}\n\\end{equation}\n\n\n\n\\section{Budget Closure Rule}\\label{SecUnbalGBCcloseRule}\n\n  If total government transfers to households $TR_t$ and government spending on public goods $G_t$ are both fixed fractions of GDP, one can imagine corporate and household tax structures that cause the debt level of the government to either tend toward infinity or to negative infinity, depending on whether too little revenue or too much revenue is raised, respectively.\n\n  A virtue of dynamic general equilibrium models is that the model must be stationary in order to solve it. That is, no variables can be indefinitely growing as time moves forward. The labor augmenting productivity growth $g_y$ from Chapter \\ref{Chap_Firms} and the potential population growth $\\tilde{g}_{n,t}$ from Chapter \\ref{Chap_Demog} render the model nonstationary. But we show how to stationarize the model against those two sources of growth in Chapter \\ref{Chap_Stnrz}. However, even after stationarizing the effects of productivity and population growth, the model could be rendered nonstationary and, therefore, not solvable if government debt were becoming too positive or too negative too quickly.\n\n  The \\ogindia model offers three different options for budget closure rules. Each rule uses some combination of changes in government spending on public goods $G_t$ and government transfers to households $TR_t$ to stabilize the debt-to-GDP ratio in the long-run.\n  \\begin{enumerate}\n    \\item Change only government spending on public goods $G_t$.\n    \\item Change only government transfers to households $TR_t$.\n    \\item Change both government spending $G_t$ and transfers $TR_t$ by the same percentage.\n  \\end{enumerate}\n\n\n  \\subsection{Change government spending only}\\label{SecUnbalGBC_chgGt}\n\n    We specify a closure rule that is automatically implemented after some period $T_{G1}$ to stabilize government debt as a percent of GDP (debt-to-GDP ratio). Let $\\alpha_D$ represent the long-run debt-to-GDP ratio at which we want the economy to eventually settle.\n    \\begin{equation}\\label{EqUnbalGBCclosure_Gt}\n      \\begin{split}\n        &G_t = g_{g,t}\\:\\alpha_{g}\\: Y_t \\\\\n        &\\text{where}\\quad g_{g,t} =\n          \\begin{cases}\n            1 \\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\:\\:\\:\\,\\text{if}\\quad t < T_{G1} \\\\\n            \\frac{\\left[\\rho_{d}\\alpha_{D}Y_{t} + (1-\\rho_{d})D_{t}\\right] - (1+r_{t})D_{t} - TR_{t} + Rev_{t}}{\\alpha_g Y_t} \\quad\\text{if}\\quad T_{G1}\\leq t<T_{G2} \\\\\n            \\frac{\\alpha_{D}Y_{t} - (1+r_{t})D_{t} - TR_{t} + Rev_{t}}{\\alpha_g Y_t} \\qquad\\qquad\\quad\\:\\:\\:\\,\\text{if}\\quad t \\geq T_{G2}\n          \\end{cases} \\\\\n        &\\quad\\text{and}\\quad g_{tr,t} = 1 \\quad\\forall t\n      \\end{split}\n    \\end{equation}\n    The first case in \\eqref{EqUnbalGBCclosure_Gt} says that government spending $G_t$ will be a fixed fraction $\\alpha_g$ of GDP $Y_t$ for every period before $T_{G1}$. The second case specifies that, starting in period $T_{G1}$ and continuing until before period $T_{G2}$, government spending be adjusted to set tomorrow's debt $D_{t+1}$ to be a convex combination between $\\alpha_D Y_t$ and the current debt level $D_t$, where $\\alpha_D$ is a target debt-to-GDP ratio and $\\rho_d\\in(0,1]$ is the percent of the way to jump toward the target $\\alpha_D Y_t$ from the current debt level $D_t$. The last case specifies that, for every period after $T_{G2}$, government spending $G_t$ is set such that the next-period debt be a fixed target percentage $\\alpha_D$ of GDP.\n\n\n  \\subsection{Change government transfers only}\\label{SecUnbalGBC_chgTRt}\n\n    If government transfers to households are specified by \\eqref{EqUnbalGBCtfer} and the long-run debt-to-GDP ratio can only be stabilized by changing transfers, then the budget closure rule must be the following.\n    \\begin{equation}\\label{EqUnbalGBCclosure_TRt}\n      \\begin{split}\n        &TR_t = g_{tr,t}\\:\\alpha_{tr}\\: Y_t \\\\\n        &\\text{where}\\quad g_{tr,t} =\n          \\begin{cases}\n            1 \\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\:\\text{if}\\quad t < T_{G1} \\\\\n            \\frac{\\left[\\rho_{d}\\alpha_{D}Y_{t} + (1-\\rho_{d})D_{t}\\right] - (1+r_{t})D_{t} - G_{t} + Rev_{t}}{\\alpha_{tr} Y_t} \\quad\\text{if}\\quad T_{G1}\\leq t<T_{G2} \\\\\n            \\frac{\\alpha_{D}Y_{t} - (1+r_{t})D_{t} - G_{t} + Rev_{t}}{\\alpha_{tr} Y_t} \\qquad\\qquad\\quad\\:\\:\\:\\:\\text{if}\\quad t \\geq T_{G2}\n          \\end{cases} \\\\\n        &\\quad\\text{and}\\quad g_{g,t} = 1 \\quad\\forall t\n      \\end{split}\n    \\end{equation}\n    The first case in \\eqref{EqUnbalGBCclosure_TRt} says that government transfers $TR_t$ will be a fixed fraction $\\alpha_{tr}$ of GDP $Y_t$ for every period before $T_{G1}$. The second case specifies that, starting in period $T_{G1}$ and continuing until before period $T_{G2}$, government transfers be adjusted to set tomorrow's debt $D_{t+1}$ to be a convex combination between $\\alpha_D Y_t$ and the current debt level $D_t$. The last case specifies that, for every period after $T_{G2}$, government transfers $TR_t$ are set such that the next-period debt be a fixed target percentage $\\alpha_D$ of GDP.\n\n\n  \\subsection{Change both government spending and transfers}\\label{SecUnbalGBC_chgGtTRt}\n\n    In some cases, changing only government spending $G_t$ or only government transfers $TR_t$ will not be enough. That is, there exist policies for which a decrease in government spending to zero after period $T_{G1}$ will not stabilize the debt-to-GDP ratio. And negative government spending on public goods does not make sense.\\footnote{Negative values for government spending on public goods would mean that revenues are coming into the country from some outside source, which revenues are triggered by government deficits being too high in an arbitrary future period $T_{G2}$.} On the other hand, negative transfers do make sense. Notwithstanding, one might want the added stabilization ability of changing both government spending $G_t$ and transfers $TR_t$ to stabilize the long-run debt-to-GDP ratio.\n\n    In our specific form of this joint option, we assume that the factor by which we scale government spending and transfers is the same $g_{g,t} = g_{tr,t}$ for all $t$. We label this single scaling factor $g_{trg,t}$.\n    \\begin{equation}\\label{EqUnbalGBCclosure_gTRGt}\n      g_{trg,t}\\equiv g_{g,t} = g_{tr,t} \\quad\\forall t\n    \\end{equation}\n    If government spending on public goods is specified by \\eqref{EqUnbalGBC_Gt} and government transfers to households are specified by \\eqref{EqUnbalGBCtfer} and the long-run debt-to-GDP ratio can only be stabilized by changing both spending and transfers, then the budget closure rule must be the following.\n    \\begin{equation}\\label{EqUnbalGBCclosure_TRGt}\n      \\begin{split}\n        &G_t + TR_t = g_{trg,t}\\left(\\alpha_g + \\alpha_{tr}\\right)Y_t \\quad\\Rightarrow\\quad G_t = g_{trg,t}\\:\\alpha_g\\: Y_t \\quad\\text{and}\\quad TR_t = g_{trg,t}\\:\\alpha_{tr}\\:Y_t \\\\\n        &\\text{where}\\quad g_{trg,t} =\n          \\begin{cases}\n            1 \\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\:\\:\\:\\,\\text{if}\\quad t < T_{G1} \\\\\n            \\frac{\\left[\\rho_{d}\\alpha_{D}Y_{t} + (1-\\rho_{d})D_{t}\\right] - (1+r_{t})D_{t} + Rev_{t}}{\\left(\\alpha_g + \\alpha_{tr}\\right)Y_t} \\quad\\text{if}\\quad T_{G1}\\leq t<T_{G2} \\\\\n            \\frac{\\alpha_{D}Y_{t} - (1+r_{t})D_{t} + Rev_{t}}{\\left(\\alpha_g + \\alpha_{tr}\\right)Y_t} \\qquad\\qquad\\quad\\:\\:\\:\\:\\text{if}\\quad t \\geq T_{G2}\n          \\end{cases}\n      \\end{split}\n    \\end{equation}\n    The first case in \\eqref{EqUnbalGBCclosure_TRGt} says that government spending and government transfers $Tr_t$ will their respective fixed fractions $\\alpha_g$ and $\\alpha_{tr}$ of GDP $Y_t$ for every period before $T_{G1}$. The second case specifies that, starting in period $T_{G1}$ and continuing until before period $T_{G2}$, government spending and transfers be adjusted by the same rate to set tomorrow's debt $D_{t+1}$ to be a convex combination between $\\alpha_D Y_t$ and the current debt level $D_t$. The last case specifies that, for every period after $T_{G2}$, government spending and transfers are set such that the next-period debt be a fixed target percentage $\\alpha_D$ of GDP.\n\n    Each of these budget closure rules \\eqref{EqUnbalGBCclosure_Gt}, \\eqref{EqUnbalGBCclosure_TRt}, and \\eqref{EqUnbalGBCclosure_TRGt} allows the government to run increasing deficits or surpluses in the short run (before period $T_{G1}$). But then the adjustment rule is implemented gradually beginning in period $t=T_{G1}$ to return the debt-to-GDP ratio back to its long-run target of $\\alpha_D$. Then the rule is implemented exactly in period $T_{G2}$ by adjusting some combination of government spending $G_t$ and transfers $TR_t$ to set the debt $D_{t+1}$ such that it is exactly $\\alpha_D$ proportion of GDP $Y_t$.\n\n\n\\section{Some Caveats and Alternatives}\\label{SecUnbalGBCcaveat}\n\n  \\ogindia adjusts some combination of government spending $G_t$ and government transfers $TR_t$ as its closure rule instrument because of its simplicity and lack of distortionary effects. Since government spending does not enter into the household's utility function, its level does not affect the solution of the household problem. In contrast, government transfers do appear in the household budget constraint. However, household decisions do not individually affect the amount of transfers, thereby rendering government transfers as exogenous from the household's perspective. As an alternative, one could choose to adjust taxes to close the budget (or a combination of all of the government fiscal policy levers).\n\n  There is no guarantee that any of our stated closure rules \\eqref{EqUnbalGBCclosure_Gt}, \\eqref{EqUnbalGBCclosure_TRt}, or \\eqref{EqUnbalGBCclosure_TRGt} is sufficient to stabilize the debt-to-GDP ratio in the long run. For large and growing deficits, the convex combination parameter $\\rho_d$ might be too gradual, or the budget closure initial period $T_{G1}$ might be too far in the future, or the target debt-to-GDP ratio $\\alpha_D$ might be too high. The existence of any of these problems might be manifest in the steady state computation stage. However, it is possible for the steady-state to exist, but for the time path to never reach it. These problems can be avoided by choosing conservative values for $T_{G1}$, $\\rho_d$, and $\\alpha_D$ that close the budget quickly.\n\n  And finally, in closure rules \\eqref{EqUnbalGBCclosure_Gt} and \\eqref{EqUnbalGBCclosure_TRGt} in which government spending is used to stabilize the long-run budget, it is also possible that government spending is forced to be less than zero to make this happen. This would be the case if tax revenues bring in less than is needed to financed transfers and interest payments on the national debt. None of the equations we've specified above preclude that result, but it does raise conceptual difficulties. Namely, what does it mean for government spending to be negative? Is the government selling off pubic assets? We caution those using this budget closure rule to consider carefully how the budget is closed in the long run given their parameterization. We also note that such difficulties present themselves across all budget closure rules when analyzing tax or spending proposals that induce structural budget deficits. In particular, one probably needs a different closure instrument if government spending must be negative in the steady-state to hit your long-term debt-to-GDP target.\n", "meta": {"hexsha": "877126403494479a3bea74c977987954595fa838", "size": 16752, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/LaTeXsource/Chapters/Chap_UnbalGBC.tex", "max_stars_repo_name": "keshavchoudhary87/OG-India", "max_stars_repo_head_hexsha": "269ee172b837882c826ee7f99507d93f9643128e", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-08-17T19:49:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-17T19:49:22.000Z", "max_issues_repo_path": "docs/LaTeXsource/Chapters/Chap_UnbalGBC.tex", "max_issues_repo_name": "keshavchoudhary87/OG-India", "max_issues_repo_head_hexsha": "269ee172b837882c826ee7f99507d93f9643128e", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2019-08-16T15:40:52.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-16T07:07:15.000Z", "max_forks_repo_path": "docs/LaTeXsource/Chapters/Chap_UnbalGBC.tex", "max_forks_repo_name": "keshavchoudhary87/OG-India", "max_forks_repo_head_hexsha": "269ee172b837882c826ee7f99507d93f9643128e", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 44, "max_forks_repo_forks_event_min_datetime": "2019-08-16T15:10:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-08T07:03:26.000Z", "avg_line_length": 115.5310344828, "max_line_length": 1092, "alphanum_fraction": 0.7422994269, "num_tokens": 4606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.32239181661441113}}
{"text": "\\documentclass[11pt]{article}\n\\usepackage{amsfonts,amssymb,amsthm,eucal,amsmath}\n\\usepackage{graphicx}\n\\usepackage[T1]{fontenc}\n\\usepackage{latexsym,url}\n\\usepackage{array}\n\\usepackage{subfig}\n\\usepackage{comment}\n\\usepackage{color}\n\\usepackage{tikz}\n\\usepackage{fancyvrb}\n\\usepackage{hyperref}\n\\usepackage[nameinlink,noabbrev]{cleveref}\n\n\\hypersetup{colorlinks=true,linkcolor=blue}\n\\newcommand{\\myspace}{\\vspace{.1in}\\noindent}\n\\newcommand{\\mymyspace}{\\vspace{.1in}}\n\\usepackage[inner=30mm, outer=30mm, textheight=225mm]{geometry}\n\\creflabelformat{equation}{#2(#1)#3}\n\\crefname{equation}{}{}\n\\Crefname{equation}{}{}\n\n\\newtheorem{theorem}{Theorem}[section]\n\\newtheorem{prop}[theorem]{Proposition}\n\\newtheorem{corollary}[theorem]{Corollary}\n\\newtheorem{defn}[theorem]{Definition}\n\\newtheorem{notn}[theorem]{Notation}\n\\newtheorem{cond}[theorem]{Condition}\n\\newtheorem{ex}[theorem]{Example}\n\\newtheorem{rmk}[theorem]{Remark}\n\n\\newcommand{\\TODO}{{\\color{red} TODO}}\n\n% Code and primitives\n\\newcommand{\\cc}[1]{\\texttt{#1}}\n\\newcommand{\\Env}{\\cc{Env}}\n\\newcommand{\\Known}{\\cc{Known}}\n%\\newcommand{\\a}{\\&\\&}\n%\\newcommand{\\c}[1]{\\operatorname{#1}}\n\\newcommand{\\Set}{\\operatorname{Set}}\n\\newcommand{\\empty}{\\operatorname{empty}}\n\n% Fix weird spacing issue in \\cc.  For details, see\n% https://tex.stackexchange.com/questions/118455/why-is-there-extra-space-after-in-texttt\n%\\makeatletter\n%\\let\\ttfamily\\relax % avoid a spurious warning\n%\\DeclareRobustCommand\\ttfamily{\\not@math@alphabet\\ttfamily\\mathtt\\fontfamily\\ttdefault\\selectfont\\frenchspacing}\n%\\makeatother\n\n\\title{A logic for computation}\n\\author{Geoffrey Irving\\thanks{Email: irving@otherlab.com, Otherlab, San Francisco, CA, United States}}\n\\date{Version 1, \\today}\n\n\\begin{document}\n\\maketitle\n\nWe want a logic that mixes computational objects with noncomputational objects, combining the\nexpressiveness of ZFC with programming.  We'll start by completely ignoring issues of soundness\nand universes, then attempt to fix this later.  We will also ignore issues of size (sizeof),\nby assuming that all computational types are word sized as in ocaml.  I believe that fixing\nthese issues will be relatively easy.\n\nMore importantly, we start out assuming a purely functional universe.  This assumption is much\nharder to eliminate, but we have to start somewhere.\n\nWe use ASCII notation where possible to make it easy to translate into code.  In particular,\nwe use \\cc{(:)} in place of $(\\in)$ for set membership, \\cc{<:} in place of $(\\subset)$ for subset,\n\\cc{->} for function types, and \\cc{x => ...} for anonymous functions.\n\n\\section{Primitives}\n\nWe have two universes \\cc{Set} and \\cc{Any}, where \\cc{Set <: Any}.  \\cc{Any} contains both sets\nand immutable computational objects (booleans, lists, functions, etc.).  \\cc{Set} is the ZFC\nuniverse with individuals, where individuals include at least the computational objects.  We do\nnot assume the individuals include \\emph{only} the computational objects, although that would\nbe a harmless assumption.\n\nAside: although \\cc{Set} lives in some sense outside the computational universe, we allow\npointers to point directly to sets.  At machine runtime the logic will enforce that such a\npointer is used solely for pointer equality comparison.\n\nThe notion of a function is a bit slippery, since we want both the nice properties of ZFC\nfunctions (concrete domain, concrete range, extensionality), and first class support for\npartial vs. total and computable vs. noncomputable.  I believe we need two notions; since\nthe ZFC notion is emergent from sets in ZFC, only the second notion is necessary as a\nseparate primitive.  We'll curry, so actually what we want is not a notion of function, but\nof value.  Since we allow pointers to reference sets, and general values have no properties\nthat sets don't, this second notion is actually just \\cc{Any}.\n\nThe primitives in our logic are\n\n\\begin{enumerate}\n\\item $\\empty : \\Set$: The empty set: \\cc{all Any (x => !(x : empty))}\n\\item \\cc{Bool : Set}: The set of booleans\n\\item \\cc{false,true : Bool}: The boolean individuals\n\\item \\cc{(:) : Any}: The set membership function\n\\item \\cc{(==) : Any}: Perfect structural equality over \\cc{Any}\n\\item \\cc{(!) : Any}: Boolean not: if \\cc{b : Bool}, \\cc{!b : Bool} is the other boolean\n\\item \\cc{(\\&\\&) : Any}: Boolean and\n\\item \\cc{all : Any}: Universal quantification over a set: if \\cc{a : Set, f : a -> Bool}, \\cc{all f a : Bool}\n\\item \\cc{subsets : Any}: Power set: if \\cc{a : Set}, \\cc{subsets a : Set}\n\\item \\cc{safe : Any}: Function safety at an argument: if \\cc{f : Any, x : Any}, \\cc{safe f x : Bool}\n\\item \\cc{filter : Any}: Subset extraction: if \\cc{a : Set, f : a -> Bool}, \\cc{filter f a : Set}\n\\item \\cc{choice : Any}: Global choice: if \\cc{a : Set} is nonempty, \\cc{choice a : a}\n\\end{enumerate}\n\nImportant: for now, we explicitly leave out a primitive notion of whether a function is ``computational''\nat a value (whether it terminates).  This is because termination is not required for the logic to be\nsound, and on a physical machine termination by itself is a useless construct.  Soundness matters, and\nefficient execution matters, but little in between.  As with Milawa, we bail at runtime\nif the system attempts to run a noncomputational function.\n\nBased on these primitives, we define several derived notions:\n\n\\begin{enumerate}\n\\item Boolean or: \\cc{a || b = !(!a \\&\\& !b)}\n\\item Function types: \\cc{(a -> b) = filter (f => all (x => safe f x \\&\\& f x : b) a) Any}\n\\item Existential quantification: \\cc{any f a = !(all (x => !(f x)) a)}\n\\item Function composition: \\cc{f . g = (x => f (g x))}\n\\end{enumerate}\n\n\\section{Environments and knowledge}\n\nA proposition is simply a boolean value, together with its definition as code.  Code is an\nalgebraic datatype\n\\begin{verbatim}\ndata Code =\n    Var Name\n  | Value Any\n  | Lambda Name Code\n  | Apply Code Code\n\\end{verbatim}\nThat's not going to be enough (a bare \\cc{Any} is essentially useless, and we've left out\nboth conditionals and macros), but we'll add further features as necessary.\n\nAn environment is a (finite) map from names to values and optionally definitions.  That is\n\\begin{verbatim}\ntype Env = Map Name (Any,Maybe Code)\n\\end{verbatim}\nOur knowledge is a set of names that we have proven are true:\n\\begin{verbatim}\ntype Known = Set Name\n\\end{verbatim}\n\nFrequently, we'll have a function in \\cc{Env} like \\cc{refl = x => x == x}, together with a theorem\nof the form \\cc{reflAll = all refl Any} which will appear in \\cc{Env} and \\cc{Known}.  That is, the\ntheorem fills in all the missing universal quantification in the function.\n\n\\section{Definitions and proofs}\n\nAt a given point in the code, we have a number of definitions in \\Env, some of which are \\Known.\nWe would like to know how to define new things, and how to prove that some of these are true.\n\n\\end{document}\n", "meta": {"hexsha": "3141252e7bf828b00309a982f9e6b3f471a3461b", "size": 6836, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "logic.tex", "max_stars_repo_name": "girving/meme", "max_stars_repo_head_hexsha": "45474d1d99d0e7ba81bc37ae0e9eb0d302ef470c", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "logic.tex", "max_issues_repo_name": "girving/meme", "max_issues_repo_head_hexsha": "45474d1d99d0e7ba81bc37ae0e9eb0d302ef470c", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "logic.tex", "max_forks_repo_name": "girving/meme", "max_forks_repo_head_hexsha": "45474d1d99d0e7ba81bc37ae0e9eb0d302ef470c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.1032258065, "max_line_length": 113, "alphanum_fraction": 0.7396138092, "num_tokens": 1928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.32239181661441113}}
{"text": "\\documentclass[12pt]{article}\n\n\\usepackage{setspace}\n\n\\usepackage{graphicx, color, fancyhdr, tikz-cd, enumitem, framed, adjustbox, bbm, upgreek, xcolor, manfnt}\n\\usepackage[framed,thmmarks]{ntheorem}\n\\usepackage[framemethod=tikz]{mdframed}\n\\usepackage{hyperref}\n\n\\hypersetup{\n\tcolorlinks = true,\n\tlinkcolor = [rgb]{0,0,0.5},\n\tcitecolor = [rgb]{0.6,0,0},\n\turlcolor = [rgb]{0,0,0.5}\n}\n\\usepackage[style=alphabetic, bibencoding=utf8]{biblatex}\n%Set the bibliography file\n\\bibliography{sources}\n\n%lots of font stuff\n\\usepackage[T1]{fontenc}\n\\usepackage[urw-garamond]{mathdesign}\n\\usepackage{garamondx}\n\\let\\mathcal\\undefined\n\\newcommand{\\mathcal}[1]{\\text{\\usefont{OMS}{cmsy}{m}{n}#1}}\n\n%Document-Specific includes\n\\usepackage{ytableau}\n\\usepackage{mathtools}\n\\usepackage{scalerel}\n\n%Replacement for the old geometry package\n\\usepackage{fullpage}\n\\usepackage{amsmath}\n\n%Input my definitions\n\\input{./mydefs.tex}\n\n%Shade definitions\n\\theoremindent0cm\n\\theoremheaderfont{\\normalfont\\bfseries} \n\\def\\theoremframecommand{\\colorbox[rgb]{0.9,1,.8}}\n\\newshadedtheorem{defn}[thm]{Definition}\n\n%Set apart my theorems and lemmas and such\n\\surroundwithmdframed[outerlinewidth=0.4pt,\n  innerlinewidth=0pt,\n  middlelinewidth=1pt,\n  middlelinecolor=white,\n  topline=false,bottomline=false,rightline=false,leftmargin=2em]{thm}\n\\surroundwithmdframed[outerlinewidth=0.4pt,\n  innerlinewidth=0pt,\n  middlelinewidth=1pt,\n  middlelinecolor=white,\n  topline=false,bottomline=false,rightline=false,leftmargin=2em]{lem}\n\\surroundwithmdframed[outerlinewidth=0.4pt,\n  innerlinewidth=0pt,\n  middlelinewidth=1pt,\n  middlelinecolor=white,\n  topline=false,bottomline=false,rightline=false,leftmargin=2em]{cor}\n  \\surroundwithmdframed[outerlinewidth=0.4pt,\n  innerlinewidth=0pt,\n  middlelinewidth=1pt,\n  middlelinecolor=white,\n  topline=false,bottomline=false,rightline=false,leftmargin=2em]{prop}\n  \\surroundwithmdframed[outerlinewidth=0.4pt,\n  innerlinewidth=0,\n  middlelinewidth=1pt,\n  middlelinecolor=white,\n  topline=false,bottomline=false,rightline=false,leftmargin=2em]{rmk}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%% Customize Below %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%header stuff\n\\setlength{\\headsep}{24pt}  % space between header and text\n\\pagestyle{fancy}     % set pagestyle for document\n\\lhead{General Exam Paper} % put text in header (left side)\n\\rhead{Nico Courts} % put text in header (right side)\n\\cfoot{\\itshape p. \\thepage}\n\\setlength{\\headheight}{15pt}\n%\\allowdisplaybreaks\n\n% Document-Specific Macros\n\\newcommand*{\\ttc}{{\\large $\\triangle$}\\kern-0.86em\\raisebox{0.3ex}{$\\scaleobj{0.78}\\otimes$}\\hspace{1ex}}\n\\DeclareMathOperator{\\Spc}{Spc}\n\\DeclareMathOperator{\\Pol}{Pol}\n\n\\begin{document}\n%make the title page\n\\title{Schur Duality and Strict Polynomial Functors\\\\\\vspace{1ex} \\normalsize General Exam Paper}\n\\author{Nico Courts\\footnote{University of Washington, Seattle. Email: ncourts@uw.edu}}\n\\date{Exam Presentation: March 10th, 2020, 10:15am, DEN 213}\n\\maketitle\n\n\\begin{abstract}\n\tWe begin by going through a considerable amount of domain knowledge concerning representations of $\\GL_n$,\n\trepresentations of $\\frakS_n$, tracing the development from the classical study of group representations by Schur\n\tand Weyl and the transformation of this theory in the more robust language of affine group schemes. From there,\n\tthe story takes on a more categorical flavor as we discuss different manifestations of polynomial representations of $\\GL_n$, \n\tfollowing the work of Friedlander and Suslin as well as Krause, Aquilino, and Reischuk. In the latter case, \n\twe show how they determined that the Schur-Weyl functor is monoidal, opening up the theory to the machinery of \n\tmonoidal categories. We take some time to develop the theory of tensor triangulated geometry from Balmer as well \n\tas discuss some standard constructions necessary for the theory. We end our paper by talking about how all of this work \n\tcomes together to elucidate some problems at the boundaries of modern representation theory as well as techniques with \n\twhich we can solve them.\\vspace{0.5in}\n\n\t{\\begin{center}\n\t\t\\footnotesize The most up-to-date version of this paper can be downloaded at the following link:\\\\\n\t\t\\url{https://github.com/NicoCourts/General-Exam-Paper/raw/master/General-Paper.pdf}\n\t\\end{center}}\n\\end{abstract}\n\n\\newpage\n%\\setcounter{tocdepth}{3}\n\\tableofcontents\n\n\\newpage\n\\section{Introduction}\n\\subsection{Issai Schur and polynomial representations}\nThe story of this project (more-or-less) begins with Schur's doctoral thesis \\cite{schur-thesis} in which he defines\nthe polynomial representations of the group $\\GL_n(k)$---a theory which he developed more completely in his later paper \\textit{\\\"Uber die \nrationalen Darstellungen der allgemeinen linearen Gruppe}\\footnote{English: \\textit{On the rational representations of the general linear group}}\n\\cite{schur-rational}. In these papers, Schur develops the idea of a \\textbf{polynomial representation of $\\GL_n(k)$},\nmeaning a (finite dimensional) representation where the coefficient functions of the representing map \n\\[\\rho:\\GL_n(k)\\to \\GL_m(k)\\]\nis polynomial in each coordinate. For example, the map sending \n\\[A=\\begin{pmatrix}\n\ta&b\\\\\n\tc&d\n\\end{pmatrix}\\mapsto \\begin{pmatrix}\n\ta^2d-abc & acd-c^2b & 0\\\\\n\tabd-b^2c & ad^2-bcd & 0\\\\\n\t0 & 0 & ad-bc\n\\end{pmatrix}=\\rho(A)\\]\nis a three-dimensional polynomial representation of $\\GL_2(\\bbR)$.\n\nThe block-diagonal form above demonstrates a direct sum decomposition of our representation into two parts: one two-dimensional homogeneous degree 3\nand one one-dimensional homogeneous degree 2 (in the entries of $A$). A result in \\cite{schur-thesis} tells us that, in fact, this can always be done: \nif $V$ is a polynomial representation of $\\GL_n(k)$,\nthen $V$ decomposes as a direct sum of representations \n\\[V=\\bigoplus_\\delta V_\\delta\\]\nwhere each $V_\\delta$ is a polynomial representation where the coefficient functions are \\textit{homogeneous degree $\\delta$}. \nThis allows us to focus our attention to the structure of these $V_\\delta$ as the fundamental building blocks of the theory.\n\nThe key insight made in this theory comes from the observation that the vector space \n\\[E^{\\otimes d}\\eqdef (k^n)^{\\otimes d}\\]\ncan made into a $(\\GL_n(k),\\frakS_d)$-bimodule in a very natural way, and that this bimodule gives us a way to relate \n$\\rmod {\\frakS_d}$ with $\\lmod {\\GL_n(k)}$ via the so-called \\textbf{Schur-Weyl functor.}\n\n\\subsection{A more modern treatment: affine group schemes}\nSchur's discovery, while already interesting enough by itself, takes on a new level of depth when one puts \nthings in the right context. More modern mathematicians realized that this phenomenon is best stated as a property of \\textit{affine group schemes}, rather than as groups. \n\nWhen put into this context, the classification of rational representations (group scheme morphisms into $\\GL(V)$) comes as given and the classification comes as a very \nnatural condition put on the corresponding map between coordinate algebras. This better motivates many of the constructions \nthat Schur made and opens up his theory to analysis using the tools of category theory and algebraic geometry.\n\n\\subsection{The Schur-Weyl functor}\nClearly a connection between representations of two groups that are so ubiquitous in group theory and math in general \nis a stunning observation, and much effort has been expended since the late 20th century to study this functor and its \nproperties---especially in how it relates the representation theory of these two groups. \n\nFor instance, Friedlander and Suslin \\cite{friedlander-suslin}\noriginally discussed the idea of \\textbf{strict polynomial functors} and showed that the category of repesentations \nof the Schur algebra $S(n,d)$ was equivalent to the category $\\calP_d$ of homogeneous degree $d$ strict polynomial functors.\n\nIn later work, Krause \\cite{krause-strict-poly-func} used an alternative construction of $\\calP_d$ as the category of\nof reprsentations of the $d$-divided powers of the category of finitely generated projective $k$-modules. This category is \ndenoted $\\Gamma^d P_k$ (or $\\Gamma^d_k$ for short) and his version of strict polynomial functors is $\\Rep \\Gamma^d_k$. The upshot of this defintion is that \nthe polynomial structure we desire is better encapsulated in the domain category, rather than placing awkward conditions on the functors themselves.\nThis also enables Krause to define monoidal structure on $\\Rep \\Gamma^d_k$ using the fact that presheaves are canonical limits of representable presheaves. \n\nKrause's students Aquilino and Reischuk, in their paper \\cite{aquilino-reischuk}, prove, among other facts, that \nunder these natural monoidal structures the Schur-Weyl functor is in fact monoidal. This puts the theory of representations \nof these groups and algebras firmly in the realm of monoidal categories, opening up the area to new questions using \ntools from category theory.\n\n\\subsection{Tools and further directions}\nSections 5,6, and 7 are devoted to reproducing the core aspects of some tools that can be used in solving problems in representation theory\nincluding methods from homological algebra (the derived category) and triangulated categories (the Balmer spectrum). In fact, these two \ntools coalesce to give a way to analyze otherwise the (sometimes unweildy) categories $\\Rep S(n,r)$. We finish our discussion with some ideas \nof how to proceed from this knowledge to solving new problems.\n\n\\subsection{Notation and conventions}\\label{subsec:notation}\nThroughout this paper we will define $k$ to be an infinite field (not necessarily of characteristic zero or algebraically closed unless otherwise noted).\nd%Let $\\Alg_k$ be the category of $k$-algebras and $\\Grp$ denote the category of groups with homorphisms.\n\nWe will use $\\Gamma=\\GL_n$ to denote the affine group scheme $\\Hom_{\\Algk}(k[x_{ij}|1\\le i,j\\le n]_{\\det},-)$ and $\\GL_n(k)$ to denote either the $k$-points of $\\GL_n$\nor the abstract group, depending on which viewpoint best suits the discussion.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\newpage\n\\section{The classical theory: Representations of \\texorpdfstring{$\\GL_n$}{GLn} and of \\texorpdfstring{$\\frakS_n$}{Sn}}\nWe begin by detailing the theory behind the (polynomial) representations of $\\GL_n$ as well as the representations of $\\frakS_n$ to \nfamiliarize ourselves with the classical representation theory associated to these groups.\n\n\\subsection{Representations of \\texorpdfstring{$\\frakS_n$}{Sn}}\nThe representation theory for $\\frakS_n$ over the complex numbers is a subject that has been widely studied by representation theorists \nand combinatorialists alike for over a century. Before we dive into specifics, we write down the idea originally worked out by Frobenius \\cite{frobenius-charaktere}\nin his work in 1900 on the characters of $\\frakS_n$:\n\\begin{thm}\\label{thm:frob-conj}\n\tThe conjugacy classes (and thus isomorphism classes of irreducible representations over $\\bbC$) of $\\frakS_n$\n\tare in bijection with partitions of $n$.\n\\end{thm}\n\n\\begin{rmk}\n\tIn what follows we attempt to give a tangible, minimalistic overview of the nicest case of representations of $\\frakS_n$.\n\tSome of the arguments below appeal more to intuition and examples than rigor, but we feel this better prepares the reader \n\tfor computations in $\\frakS_n$ without being weighed down by unnecessary details. This can all be made rigorous, of course, \n\tat the expense of some clarity and conciseness. \n\\end{rmk}\nLet's get some sense first about how we can relate these two ideas by recalling some easy lemmas from \ngroup theory. Recall that each element of $\\frakS_n$ can be written \nas a product of disjoint cycles and that this representation is unique up to reordering the cycles. We can make this \nrepresentation unique by writing each cycle as one starting at its least element and then ordering the cycles by these least elements. \nFor instance, the permutation (in two-line notation)\n\\[\\sigma=\\begin{pmatrix}1&2&3&4&5&6&7&8\\\\ 2&1&7&5&3&8&4&6\\end{pmatrix}\\in\\frakS_8\\]\nis represented uniquely in this way as the product of cycles:\n\\[\\sigma=(1\\,2)(3\\,7\\,4\\,5)(6\\,8).\\]\n\nThe next observation to recover: if $\\tau,\\eta\\in\\frakS_n$ and $\\tau=(\\tau_1\\,\\tau_2\\,\\cdots\\,\\tau_k)$ is a cycle, \n\\[\\eta^{-1}\\tau\\eta=(\\eta(\\tau_1)\\,\\eta(\\tau_2)\\,\\cdots\\,\\eta(\\tau_k)).\\]\nWe can see this demonstrated in the computation\n\\begin{align*}\n\t(1\\,3\\,5)\\sigma(1\\,3\\,5)^{-1}&=(1\\,3\\,5)(1\\,2)(1\\,5\\,3)(1\\,3\\,5)(3\\,7\\,4\\,5)(1\\,5\\,3)(1\\,3\\,5)(6\\,8)(1\\,5\\,3)\\\\\n\t&=(3\\,2)(5\\,7\\,4\\,1)(6\\,8)\\\\\n\t&=(1\\,5\\,7\\,4)(2\\,3)(6\\,8)\n\\end{align*}\nThe important observation here is that the ``shape'' (the lengths of the cycles when written as a product of disjoint cycles) is preserved under conjugation.\nIn fact,\n\\begin{lem}\\label{lem:conj-classes}\n\tThe conjugacy classes of $\\frakS_n$ are in one-to-one correspondence with the partitions of $n$.\n\\end{lem}\n\\begin{prf}\n\tLet $\\scrP_n$ denote the partitions of $n$ and let $C_n$ denote the conjugacy classes in $\\frakS_n$.\n\tWe construct the set map \n\t\\[\\varphi:C_n\\to \\scrP_n\\]\n\tby sending a conjugacy class to the weakly-decreasing list of cycle lengths (including trivial cycles, if necessary). For instance in $\\frakS_8$,\n\t\\[(1\\,5\\,3)(2\\,7)\\qquad\\text{cooresponds to}\\qquad (3,2,1,1,1).\\]\n\n\tThe results cited and demonstrated above shows that this map is well defined---conjugation preserves the cycle length in \n\tthe disjoint cycle representation of an element. Furthermore if $p\\in \\scrP_n$ is a partition, the adjoint action of $\\frakS_n$ on $\\varphi^{-1}(p)$\n\tis transitive, since if two elements have the same cycle lengths when written as disjoint cycles, we can line \n\tthe cycles up according to length and act by the permutation that ``puts labels in the right place''. If we look at $\\sigma$ and the \n\telement we found by conjugation above, we have \n\t\\begin{align*}\n\t\t(1\\,2)(3\\,7\\,4\\,5)(6\\,8)\\\\\n\t\t(3\\,2)(5\\,7\\,4\\,1)(6\\,8)\n\t\\end{align*}\n\twhere we notice that $1\\mapsto 3$, $3\\mapsto 5$, and $5\\mapsto 1$, meaning that the cycle that takes the top element to the \n\tbottom is $(1\\,3\\,5)$---although of course we already knew that. Another example are the elements $(1\\,4\\,5)$ and $(3\\,2\\,1)$. Here we want $1\\mapsto 3$, $4\\mapsto 2$ and $5\\mapsto 1$.\n\tThus one element that takes the first to the second is $(5\\,1\\,3)(2\\,4)$. This demonstrates that the action is not faithful since we could also act by $(5\\,1\\,3\\,7)(2\\,4)(6\\,8)$ and get the same element. \n\tthe important fact here is that $\\frakS_n$ acts transitively on the elements of $1,\\dots,n$, so there is always such an element.\n\n\tThe surjectivity of this map is clear since we can write from any partition of $n$ a product of disjoint cycles corresponding to \n\tthis partition (which then must map to it) and injectivity is clear since the disjoint cycle representation is unique (up to reordering cycles, which doesn't affect the image $\\varphi(x)$).\n\tThis proves the lemma.\n\\end{prf}\n\nFrom here, the standard result that (again, over $\\bbC$) the conjugacy classes of a group are in bijection with the irreducible representations finishes demonstrating how \ntheorem \\ref{thm:frob-conj} is true. But a simple set bijection belies the depth of the connection here. \n\n\\subsubsection{Construction of the irreducible representations}\nIt is possible, through the idea of a Young symmetrizer, to directly link a Young diagram to the corresponding \nirreducible representation. Throughout this subsection, we will be relying on facts developed in \\cite{fulton-harris}, \nalthough there is also a more complete combinatorial picture painted in Fulton's book \\textit{Young Tableaux} \\cite{fulton-tableaux}. \n\nTo begin our discussion, consider the trivial representation within the left regular representation $\\bbC\\frakS_n$: \nit is a one-dimensional subspace spanned by the element \n\\[x_1=\\sum_{\\sigma\\in\\frakS_n}\\sigma\\]\nwhere you can see that this element is fixed by left multiplication, demonstrating that it has the trivial $\\frakS_n$ action.\nThe subspace spanned by the element \n\\[x_{-1}=\\sum_{\\sigma\\in\\frakS_n}(-1)^{\\operatorname{sign}(\\sigma)}\\sigma\\]\nis the sign representation, where an element with sign 1 acts by -1. This is because\n\\[\\operatorname{sign}(\\tau\\sigma)=\\operatorname{sign}(\\tau)+\\operatorname{sign}(\\sigma)\\pmod{2}.\\]\n\nIt ends up that these two representations form the two ``endpoints'' of the representation theory of $\\frakS_n$. The exact sense in which this is \ntrue is captured through Young diagrams! For the purposes of illustration, let us return to our example above of $\\frakS_8$. Here the trivial and sign representations \ncorrespond (repsectively) to the tableaux\n\\[\\ytableausetup{smalltableaux,centertableaux}\\ydiagram{8}\\qquad\\text{and}\\qquad\\ydiagram{1,1,1,1,1,1,1,1}\\]\nwhich, in turn, correspond to partitions $(8)$ and $(1,1,1,1,1,1,1,1)$ of $8$. The way to make this connection is through the definition \nof a \\textit{Young symmetrizer:}\n\\begin{defn}\n\tFix an $n\\ge 1$ and let $\\lambda$ be a partition of $n$. Then define two elements of $\\bbC\\frakS_n$, $a_\\lambda$ and $b_\\lambda$ in the following way:\n\t\\[a_\\lambda=\\sum_{\\sigma\\in R(T_\\lambda)}\\sigma\\qquad\\text{and}\\qquad b_\\lambda=\\sum_{\\sigma\\in C(T_\\lambda)}(-1)^{\\operatorname{sign}(\\sigma)}\\sigma\\]\n\twhere $T_\\lambda$ is the Young diagram corresponding to $\\lambda$ and given some labeling (say the canonical one that labels boxes left-to-right and top-to-bottom)\n\t$R(T_\\lambda)$ (resp. $C(T_\\lambda)$) denote the subgroups of $\\frakS_n$ stabilizing the rows (resp. columns) of $T_\\lambda$ under the action of $\\frakS_n$ on the labels.\n\n\tThen the \\textbf{Young centralizer} of $\\lambda$ is \n\t\\[c_\\lambda=a_\\lambda b_\\lambda\\in\\bbC\\frakS_n.\\]\n\\end{defn}\n\nThe canonical fillings of the diagrams above are\\footnote{Here you can see yet another connection to disjoint cycle representations. Notice, under the map \ndefined in lem.~\\ref{lem:conj-classes}, that the conjugacy class corresponding to the trivial representation is the one consisting of ``long'' (length $n$) cycles. Using the \nunique ordering on products of disjoint cycles described after the statement of thm.~\\ref{thm:frob-conj}, we can identify fillings with long cycles and we see \nthat the cycle $(1\\,2\\,3\\,4\\,5\\,6\\,7\\,8)$ is the only one in ``standard form'' in that it gives us a standard Young tableau. The complexity of the Young diagram (meaning how many \ndifferent standard fillings it admits) gives us some information about the dimensionality of the corresponding irreducible representation, as we will see later.}\n\\[\\ytableaushort{12345678}\\qquad\\text{and}\\qquad\\ytableaushort{1,2,3,4,5,6,7,8}\\]\nand so since the column stabilizer of the first diagram is trivial and the row stablizer is everything,\n\\[c_{(8)}=\\left(\\sum_{\\sigma\\in R(T_{(8)})}\\sigma\\right)\\left(\\sum_{\\sigma\\in C(T_{(8)})}(-1)^{\\operatorname{sign}(\\sigma)}\\sigma\\right)=\\sum_{\\sigma\\in\\frakS_n}\\sigma=x_1\\]\nand since the roles of the column and row stabilizing elements are reversed for the sign representation, we get \n\\[c_{(1,1,1,1,1,1,1,1)}=\\left(\\sum_{\\sigma\\in R(T_{(1,1,1,1,1,1,1,1)})}\\sigma\\right)\\left(\\sum_{\\sigma\\in C(T_{(1,1,1,1,1,1,1,1)})}(-1)^{\\operatorname{sign}(\\sigma)}\\sigma\\right)=\\sum_{\\sigma\\in\\frakS_n}(-1)^{\\operatorname{sign}(\\sigma)}\\sigma=x_{-1}.\\]\n\nThat the Young symmetrizers correspond with the elements spanning the corresponding representations of is no coincidence! \n\\begin{defn}\n\tThe module $V_\\lambda$ is a $\\bbC\\frakS_n$-module generated by the Young symmetrizer $c_\\lambda$.\n\\end{defn}\nNotice that the dimension of each $V_\\lambda$ is determined by number of linearly-independent elements that lie in the orbit of $c_\\lambda$. We compute another example that \ngives a general pattern:\n\\begin{ex}\n\tLet $\\lambda=(2,1,1)$ be the partition of $5$, so \n\t\\[T_\\lambda=\\ydiagram{2,1,1}.\\]\n\tGiven the canonical filling of $T_\\lambda$,\n\t\\[\\ytableaushort{12,3,4},\\]\n\twe have \n\t\\[a_\\lambda=e+(1\\,2)\\qquad\\text{and}\\qquad b_\\lambda=e-(1\\,3)-(1\\,4)-(3\\,4)+(1\\,3\\,4)+(1\\,4\\,3)\\]\n\tand so we can compute that the Young symmetrizer for this partition is \n\t\\[c_\\lambda=e-(1\\,3)-(1\\,4)-(3\\,4)+(1\\,2)+(1\\,3\\,4)+(1\\,4\\,3)-(2\\,1\\,4)-(1\\,2)(3\\,4)+(1\\,3\\,4\\,2)+(1\\,4\\,3\\,2)\\]\n\tand one can show (c.f. \\cite[48]{fulton-harris}) that this is the representation $V\\wedge V$ where $V$ is the standard representation \n\t(the complement of copy of the trivial representation spanned by the vector $(1,1,1,1)\\in\\bbC^4$ under the usual embedding of \n\t$\\frakS_4$ in $\\GL_4$ as permutation matrices).\n\\end{ex}\n\nThis completes the description of the representations of $\\frakS_n$ over $\\bbC$, but in fact everything we have done here holds over the splitting field \nof $\\frakS_n$, that is, the minimal field such that representations don't split further under field extension. We haven't proved here that\n\\begin{enumerate}\n\t\\item the $V_\\lambda$ are irreducible; or \n\t\\item the $V_\\lambda$ are pairwise nonisomorphic,\n\\end{enumerate}\nbut one can look up any of the standard texts (including the ones cited in this section) for more rigorous and thorough treatments of these facts.\n\n\\subsection{Polynomial representations of \\texorpdfstring{$\\Gamma$}{Gamma}}\nLet $k$ be an infinite field\\footnote{In some cases we will be able to allow $k$ to be a ring, but we will still need that $k$ be infinite so that \npolynomials over it are determined by their values.} and $\\Gamma$ be the affine group scheme $\\GL_n$. This can be thought of as the functor \n\\[\\Gamma:\\Alg_k\\to \\Grp\\quad\\text{sending}\\quad A\\mapsto \\GL_n(A).\\]\nThen \n\\begin{defn}\n\tA (finite dimensional) \\textbf{representation} of $\\Gamma$ is a (finite dimensional) vector space $V$ along with a group scheme homomorphism\n\t\\[\\rho:\\Gamma\\to \\GL(V)\\eqdef \\Aut(V\\otimes_k -)\\]\n\\end{defn}\n\\begin{rmk}\n\tRepresentations of (the group, which can be thought of as the $k$ points of the $k$-scheme) $\\GL_n(k)$ can be, in general, ``analytic.'' One can check that the map \n\t\\[\\rho:k^\\times=\\GL_1(k)\\to \\GL(k^2)\\qquad\\text{via}\\qquad x\\mapsto\\begin{pmatrix}\n\t\t1 & \\ln |x|\\\\ 0 & 1\n\t\\end{pmatrix}\\]\n\tgives a group homomorphism (and thus representation) between these two groups, but the logarithm makes this representation decidedly \\textit{not algebraic.}\n\n\tThis leads to slightly more awkward definitions in more classical treatments of the theory (e.g. \\cite{green}), where one has to \n\tspecifically rule these out. The upshot to using a more algebro-geometric approach is that we start off in the world of rational maps where \n\tsuch a representation doesn't make sense.\n\\end{rmk}\nRecall that the affine group scheme $\\GL_n$ is represented by the algebra \n\\[k[x_{ij}]_{\\det}\\]\nwhere $1\\le i,j\\le n$ and $\\det$ is the polynomial corresponding to the determinant of the matrix $A=(x_{ij})$. Since $\\GL_n$ is an affine scheme,\nwe know that the global functions are \n\\[k[\\Gamma]=k^\\Gamma\\cong k[x_{ij}]_{\\det}\\]\nwhere we will (for clarity) use the notation $c_{ij}:\\Gamma\\to k$ to denote the function corresponding to $x_{ij}$.\n\n\\begin{defn}\\label{def:poly-rep}\n\tA \\textbf{polynomial representation} of $\\Gamma$ is a representation $\\rho:\\Gamma\\to \\GL(V)$ (where $\\dim_k V=m$) such that (on points) the structure maps (\\ref{rmk:structure-maps}) of \n\t\\[\\rho_A:\\Gamma(A)\\to \\GL(V)(A)\\cong\\GL_m(A)\\] \n\tare polynomials in the functions $c_{ij}:\\Gamma(A)\\to A$ that extract the $(i,j)^{th}$ entry.\n\n\tIf all the structure maps are homogeneous of degree $r$ for some fixed $r$, we say that $\\gamma$ is a \\textbf{homogeneous degree $r$\n\tpolynomial representation of $\\Gamma$.}\n\\end{defn}\n\\begin{rmk}\\label{rmk:structure-maps}\n\tRecall (or learn for the first time!) that the \\textit{structure maps} of a representation $(\\rho,V)$ are a collection \n\tof maps $r_{ij}$ for $1\\le i,j,\\le n$ from $\\Gamma$ to $k$ such that for all $g\\in \\Gamma$:\n\t\\[g\\cdot v_i=\\sum_{j=1}^n r_{ij}(g)v_j\\]\n\twhere we have picked a basis $\\{v_1,\\dots,v_n\\}$ for $V$. Of course changing basis may change our \n\t$r_{ij}$, but their \\textbf{span} $\\langle r_{ij}\\rangle$ is an invariant of the representation.\n\\end{rmk}\n\\begin{defn}\\label{def:Mnr}\n\tLet $\\Pol_k(n)=\\Pol(n)$ be the collection of all polynomial representations of $\\GL_n$ and let $\\Pol_k(n,r)=\\Pol(n,r)$ \n\tbe the collection of all homogeneous degree $r$ polynomial representations of $\\GL_n$.\n\\end{defn}\nIt is the \\textit{polynomial} representations that we will concern ourselves with in the following sections. \n\n\\subsubsection{Reducing scope}\nIn what follows we (temporarily) restrict to the case of considering the $R$-points of the scheme, where $R\\in\\Alg_k$. \nUsing some of our familiar friends from representation theory (as well as some clever twists), \nwe can simplify this picture considerably by proving the following structural result:\n\\begin{thm}[{\\cite[pp.7-10]{schur-thesis}}]\\label{thm:decomp}\n\tEvery polynomial representation $V$ of the group $\\GL_n(R)$ (where $R$ is an algebra over an infinite field $k$) decomposes as a direct sum \n\t\\[V\\cong\\bigoplus_{\\delta\\in\\bbN}V_\\delta\\]\n\twhere $V_\\delta$ is a \\textit{homogeneous} polynomial representation of degree $\\delta.$\n\\end{thm}\nClearly, then, it suffices to understand the \\textit{homogeneous degree $r$} polynomial representations of $\\Gamma(A)$ if we are looking\nto understand the larger structure.\n\nWe begin with a useful lemma extracted from a proof in \\cite{schur-thesis} echoing the general theory of \northogonal decomposition of Artinian algebras.\n\\begin{lem}\\label{lem:orth-decomp}\n\tLet $C_0,\\dots,C_m\\in M_n(R)$ be mutually orthogonal idempotent matrices that sum to the identity. That is, \n\t\\[I_n=\\sum_i C_i\\quad\\text{and}\\quad C_iC_j=\\delta_{ij}C_i\\]\n\tfor all $0\\le i,j\\le m$. Then there exists an invertible matrix $P$ such that for some positive integers $d_0,\\dots,d_m$ with $\\sum_k d_k=n$ and for all $i$,\n\t\\[P^{-1}C_iP=\\begin{pmatrix}\n\t\t\\mathbf{0}_{N_i} & &\\\\\n\t\t& I_{d_i} & \\\\\n\t\t& & \\mathbf{0}_{M_i}\n\t\\end{pmatrix}\\]\n\tWhere $N_i=\\sum_{0\\le j<i}d_j$ and $M_i=n-d_i-N_i$\n\\end{lem}\n\\begin{prf}[of lem~\\ref{lem:orth-decomp}]\n\tWe set $S_k=\\{C_0,C_1,\\dots,C_k\\}$ and we proceed by induction on $k$. When $k=0$, $S_k=\\{C_0\\}$. Now since \n\t$C_0^2=C_0$, we get that 1 and 0 are the only eigenvalues of $C_0$, so there is an $r\\times r$ matrix $P_0$ \n\tand a positive integer $d_0$ such that\n\t\\[P_0^{-1}C_0P_0=\\begin{pmatrix}\n\t\tI_{d_0} & \\\\\n\t\t\t& \\mathbf{0}_{n-d_0}\n\t\\end{pmatrix}.\\]\n\twhich establishes the base case.\n\n\tNow assume that we have a matrix $P_{k-1}$ such that this property holds for all elements of $S_{k-1}$.\n\tDefine, for each $0\\le i\\le k$, \n\t\\[C_i'\\eqdef P^{-1}_{k-1}C_iP_{k-1}\\]\n\tand since the $C_k$ is assumed to be orthogonal to all other $C_i$,\n\t\\[C_k'=\\begin{pmatrix}\n\t\t\\mathbf{0}_{N_k} & \\\\\n\t\t& D_k\n\t\\end{pmatrix}\\]\n\tfor some $D_k$.\n\n\tNow by properties of block diagonal matrices, we have \n\t\\[D_k^2=D_k\\]\n\tso the eigenvalues of $D_k$ are again one and zero. Thus there is an invertible $Q\\in \\GL_{n-N_k}$ such that \n\t\\[Q^{-1}D_kQ=\\begin{pmatrix}I_{d_k} &\\\\ & \\mathbf{0}_{M_k}\\end{pmatrix}\\]\n\tand so by setting\n\t\\[P_k\\eqdef P_{k-1}\\begin{pmatrix}I_{N_k} &\\\\ & Q\\end{pmatrix}\\]\n\twe can define\n\t\\[C''_i\\eqdef P_k^{-1}C_i P_k=\\begin{pmatrix}I_{N_k} &\\\\ & Q\\end{pmatrix}^{-1}C'\\begin{pmatrix}I_{N_k} &\\\\ & Q\\end{pmatrix}\\]\n\tfor $0\\le i\\le k$, we see immediately that $C_i'=C_i''$ for $0\\le i<k$ and furthermore \n\t\\[C_k''=\\begin{pmatrix}\n\t\t\\mathbf{0}_{N_k} & \\\\\n\t\t& Q^{-1}D_kQ\n\t\\end{pmatrix}=\\begin{pmatrix}\n\t\t\\mathbf{0}_{N_k} & &\\\\\n\t\t& I_{d_k} & \\\\\n\t\t& & \\mathbf{0}_{M_k}\n\t\\end{pmatrix}\\]\n\tcompleting the inductive step. This this result holds for all $S_i$ and in particular for $S_m$, so the result is proven.\n\\end{prf}\nAs well as another result on a special class of commuting block diagonal matrices:\n\\begin{lem}\\label{lem:block-diag}\n\tLet $R\\in\\Alg_k$ ($k$ be an infinite field) and let $A$ be a block diagonal matrix over $k$ of the form\n\t\\[A=\\operatorname{diag}(x^mI_{d_m},x^{m-1}I_{d_{m-1}},\\dots,I_{d_0})\\]\n\twhere $d_i$ is (clearly) the dimension of the $(m-i)^{th}$ block and let $B$ be any matrix that commutes with $A$\n\tfor every choice of $x\\in k$. Then $B$ is block diagonal of the same shape as $A$. \n\\end{lem}\n\\begin{prf}[of lem~\\ref{lem:block-diag}]\n\tWe proceed by comparing the entries in $AB$ and $BA$: notice that \n\t\\[(AB)_{ij}=\\sum_k A_{ik}B_{kj}=A_{ii}B_{ij}=x^aB_{ij}\\]\n\tand \n\t\\[(BA)_{ij}=\\sum_k B_{ik}A_{kj}=B_{ij}A_{jj}=x^bB_{ij}.\\]\n\tWe will show that if the $(i,j)^{th}$ postion is not in one of the blocks of $A$, then it is zero.\n\n\tBut if $(i,j)$ is not in one of the blocks of $A$, then the nonzero element in the $i^{th}$ row and the nonzero element in \n\tthe $j^{th}$ column ($x^a$ and $x^b$ in the above equations) are not the same! Since $x$ is arbitrary, this forces $B_{ij}=0$,\n\tso $B$ is block diagonal with blocks the same as $A$.\n\\end{prf}\n\\begin{rmk}\n\tNotice that in the above proof we used implicitly that there is an $x\\in R$ such that for all $a,b$\n\t\\[x^a=x^b\\quad\\Rightarrow\\quad a=b\\]\n\twhich is true since $k$ is infinite. This can cause a problem for finite fields since, for instance, every element in $\\bbF_p$ satisfies $x^p=x$.\n\\end{rmk}\n\nAnd finally using these two lemmas allows us to prove our main result:\n\\begin{prf}[of thm~\\ref{thm:decomp}]\n\tWe recreate the argument in Schur's thesis, translated from German and reinterpreted in more modern parlance. \n\t\n\tLet $(\\rho,V)$ be a polynomial representation of $\\GL_n(R)$ with $\\dim_k V=r$. Then let $x\\in R^\\times$ be arbitrary (thought of as an indeterminate)\n\tand consider the matrix $xI_n\\in\\Gamma$. The image of this matrix under $\\rho$ is a matrix \n\t\\[\\rho(A)=\\begin{pmatrix}\n\t\tp_{11}(x) & \\cdots & p_{1r}(x)\\\\\n\t\t\\vdots & \\ddots & \\vdots\\\\\n\t\tp_{r1}(x) & \\cdots & p_{rr}(x)\n\t\\end{pmatrix}\\]\n\twhere each $p_{ij}$ is a polynomial in $x$. Let $m=\\max_{i,j}\\deg p_{ij}$, and this gives us a decomposition \n\t\\[\\rho(A)=x^m C_0+x^{m-1}C_1+\\cdots+ xC_{m-1}+C_m\\]\n\twhere each $C_i$ is an $r\\times r$ matrix.\n\n\tLet $y$ be another indeterminate and $B=yI_n$. By virtue of being a representation of $\\GL_n(R)$, we get \n\t\\[\\rho(A)\\rho(B)=\\rho(xI_n)\\rho(yI_n)=\\rho(xyI_n)=\\rho(AB)\\]\n\tand using this setup we prove the following result: \n\t\\[\\text{For all $0\\le i,j\\le m$, with the $C_l$ as above,}\\quad C_iC_j=\\delta_{ij}C_i\\]\n\tThat this is true can be established by comparing coefficients in the equation\n\t\\begin{align*}\n\t\t\\rho(AB)&=\\rho(A)\\rho(B)\\\\\n\t\tC_0(xy)^m+\\cdots+C_i(xy)^{m-i}+\\cdots+C_m&=C_0^2x^my^m+\\cdots+C_iC_jx^{m-i}y^{m-j}+\\cdots+C_m^2\n\t\\end{align*}\n\tIndeed, we immediately get that $C_i=C_i^2$ and furthermore the coefficients on $x^iy^j$ when $i\\ne j$ give us\n\t\\[0=C_{m-i}C_{m-j}.\\]\n\t\n\tThus we have shown that the $C_i$ form a set of orthogonal idempotent matrices and evaluating our original equation at $x=1$,\n\twe get (since $\\rho$ is a homomorphism)\n\t\\[I_r=1C_0+\\cdots+1C_m=\\sum C_i\\]\n\tso the result from lemma~\\ref{lem:orth-decomp} applies: we get a matrix $P$ such that \n\t\\[P^{-1}\\rho(xI_n)P=\\begin{pmatrix}\n\t\tx^mI_{d_0} & & & &\\\\\n\t\t& x^{m-1}I_{d_1} & & &\\\\\n\t\t& & \\ddots & &\\\\\n\t\t& & & xI_{d_{m-1}} & \\\\\n\t\t& & & & I_{d_m}\n\t\\end{pmatrix}\\]\n\tNow let $\\rho'(g)=P^{-1}\\rho (g)P$ for all $g\\in\\GL_n(R)$. This is a representation of $\\Gamma$ since it it differs from $\\rho$ by \n\tan automorphism of $\\GL(V)$. Since matrix multiplication is an algebraic operation, $\\rho'$ is still a polynomial representation of $\\GL_n(R)$. \n\tBut notice that for all $g\\in\\GL_n(R)$\n\t\\[\\rho'(g)\\rho'(xI_n)=\\rho'(xg)=\\rho'(xI_n)\\rho'(g)\\]\n\tThen lemma \\ref{lem:orth-decomp} gives us that $\\rho'(g)$ decomposes in the same way for all $g\\in \\GL_n(R)$, so \n\twe know that $\\rho'$ decomposes as a direct sum of representations \n\t\\[\\rho'=\\sum_{i=0}^m \\rho'_i\\]\n\twhere for each $i$ and $\\lambda\\in k$,\n\t\\[\\rho'_i(\\lambda g)=\\rho_i'(\\lambda I_{d_i})\\rho_i'(g)=\\lambda^i\\rho'_i(g)\\]\n\tso each $\\rho_i'$ is a homogeneous degree $i$ polynomial representation of $\\Gamma$.\n\n\tBut of course the decomposition of a representation is independent of choice of basis,\n\tso we get a decomposition of $\\rho$ into homogenous pieces, as desired.\n\\end{prf}\n\nThis is wonderful if one is just interested in the representation theory of $\\GL_n(A)$ for a specific $A$, but \nhere we are interested in group \\textit{scheme} representations. The result above effectively tells us how the scheme splits \nup on points, but how about the global structure?\n\nWhat we need is that this splitting is functorial. That is, if $\\rho:\\Gamma\\to\\GL(V)$ is a polynomial representation, there is a subscheme $\\rho_r$\nthat, for all $A$, $(\\rho_r)_A$ is the homogeneous degree $r$ part of $\\rho_A$. Let $\\rho_r$ be such a map and let $\\varphi:A\\to B$ be an \nalgebra morphism. Then we want that this induces a map\n\\[\\hat\\varphi:(\\rho_r)_A\\to (\\rho_r)_B.\\]\nFix a basis $v_1,\\dots,v_n$ for $V$ and let $g\\in \\Gamma(A)$. Then since $(\\rho_r)_A$ is homogeneous degree $r$, for all $v_i$,\n\\[g\\cdot_A v_i=\\sum_j f_{ij}(g)v_i\\]\nwhere the $f_{ij}$ is a homogeneous degree $r$ polynomial in the $c_{ij}$. Now if we write $(\\rho_r)_A(g)=M_{g,A}=(m_{ij})_{i,j}$, this means that \nif $\\lambda\\in k$,\n\\[M_{\\lambda g, A}=(\\lambda^rm_{ij})_{i,j}=\\lambda^rM_{g,A}\\]\n\nThe map $\\hat \\varphi$ is such that \n\\[\\hat\\varphi(M_{g,A})=(\\varphi(m_{ij}))_{i,j}=M_{g,B}\\]\nand so\n\\[M_{\\lambda g,B}=\\hat\\varphi(M_{\\lambda g,A})=(\\varphi(\\lambda^r m_{ij}))_{i,j}=(\\lambda^r \\varphi(m_{ij}))_{i,j}=\\lambda^rM_{g,B}\\]\nwhich tells us that the map $\\rho_r$ is indeed a functor $\\Gamma\\to\\GL(V)$, so is a subgroup scheme of $\\rho$.\nThus the pointwise splitting shown above lifts to a splitting of the entire representation $\\rho$.\n\n\\subsubsection{Monomials and multi-indices}\\label{subsubsec:indices}\nAll of the discussion up to this point has revolved around polynomials in $n^2$ variables, which quickly gets unwieldy unless one \nuses some better notation. To that end, \n\\begin{defn}\n\tAn $(n,r)$-\\textbf{multi-index} $i$ is an $r$-tuple $(i_1,\\dots,i_r)$ where each $i_j\\in\\underline n\\eqdef\\{1,\\dots,n\\}$.\n\tThe collection of all $(n,r)$-multi-indices is denoted $I(n,r)$.\n\\end{defn}\n\\begin{rmk}\n\tOne can also think of an element $i\\in I(n,r)$ as a (set) map \n\t\\[i:\\underline r\\to\\underline n.\\]\n\\end{rmk}\nThe idea here is to associate to each monomial in a polynomial ring in many variables a tuple indicating its multidegree. That is we think of \n\\[(i_1,\\dots,i_r)\\quad\\leftrightsquigarrow\\quad x_{i_1}\\cdots x_{i_r}\\]\nas corresponding to the same object. Which is wonderful except for one small flaw: polynomials are commutative \nand multi-indices (as we have defined them) aren't! For example, in $I(3,4)$,\n\\[(2,2,1,3)\\quad\\leftrightsquigarrow\\quad x_1x_2^2x_3\\quad\\leftrightsquigarrow\\quad (3,2,1,2).\\]\n\nTo handle this disparity, we define an equivalence relation on $I(n,r)$ where we say that $i\\sim j$ if they are in the \nsame orbit under the natural $\\frakS_r$ action. That is, if there exists $\\sigma\\in\\frakS_r$ such that\n\\[(i_1,\\dots,i_r)=(j_{\\sigma(1)},\\dots,j_{\\sigma(r)})\\]\n\nIn the context of polynomial representations of $\\Gamma$, we want to consider polynomials in the coordinate functions $c_{ij}$,\nso as a matter of notation if $i,j\\in I(n,r)$, let $c_{i,j}$ denote the monomial \n\\[c_{i,j}=c_{i_1j_1}\\cdots c_{i_rj_r}.\\]\nAgain, we want to take into account that we can permute the order on the right hand side, but now we need that $i_k$ and $j_k$ \nremain linked to the same function. To deal with this, we define an equivalence relation $\\sim$ on $I(n,r)\\times I(n,r)$ such that \n\\[(a,c)\\sim (b,d)\\]\nif there exists a $\\sigma\\in\\frakS_r$ such that \n\\[(a_1,\\dots,a_r)=(b_{\\sigma(1)},\\dots,b_{\\sigma(r)})\\quad\\text{and}\\quad(c_1,\\dots,c_r)=(d_{\\sigma(1)},\\dots,d_{\\sigma(r)}).\\]\nThe upshot of this work is that it gives us a bijection between (total) degree $r$ monomials in the $c_{ij}$ and the set\n\\[I(n,r)\\times I(n,r)/\\sim\\]\n\n\\subsubsection{\\texorpdfstring{$A_k(n,r)$}{Ak(n,r)}}\nNotice that if $V\\in \\Pol(n,r)$, each of its structure maps are homogeneous degree $r$ polynomials. As the first object of study, consider \n\\begin{defn}\n\tLet $A_k(n,r)=A(n.r)$ denote the collection of all homogeneous degree $r$ polynomials in the \n\tcoordinate functions $c_{ij}:\\Gamma\\to k$.\n\\end{defn}\nIt is not too hard to see that \n\\begin{prop}\n\t$A_k(n,r)$ is spanned by the elements \n\t\\[\\{c_{i,j}|(i,j)\\in I(n,r)\\times I(n,r)\\}\\]\n\\end{prop}\nhowever it takes a short argument to see \n\\begin{lem}\n\tThe dimension of $A_k(n,r)$ over $k$ is $\\binom{n^2+r-1}{n^2-1}=\\binom{n^2+r-1}{r}$.\n\\end{lem}\n\\begin{prf}\n\tThe following is a ``stars and bars'' argument that is pervasive in combinatorics. See for example \\cite{stanley} if unfamiliar with these techniques.\n\t\n\tFix an ordering of the $c_{ij}$ (say the dictionary order)\n\tand relabel them $\\{\\gamma_1,\\dots,\\gamma_{m}\\}$ (here $m=n^2$) according to this order. Then the degree $r$ monomials are in bijection with $m$-tuples $(a_1,\\dots,a_{m})\\in\\bbN^m$ such that $\\sum_i a_i=r$ via the map which sends \n\t\\[(a_1,\\dots,a_{m})\\mapsto \\gamma_1^{a_1}\\cdots\\gamma_{m}^{a_{m}}.\\]\n\n\tBut choosing such an element is the same as inserting $m-1$ bars into a line of $r$ stars (that is an ordered partition of $r$ into $m$ parts, \n\twhere parts are allowed to be zero). But this is equivalent to choosing $m-1$ bars in a field of $m+r-1$ symbols. This is just \n\t\\[\\binom{m+r-1}{m-1}\\]\n\tand a well-known identity for binomial coefficients gets us the final equality.\n\\end{prf}\n\\begin{ex}\n\tIn case the reader is unfamiliar with this kind of reasoning, consider the case when $n=5$ and $r=4$. Then the composition $(1,0,0,2,1)$ corresponding to \n\t$\\gamma_1\\gamma_4^2\\gamma_5$ corresponds to the stars-and-bars diagram \n\t\\begin{center}\n\t\t$\\ast|||\\ast\\ast|\\ast$\n\t\\end{center}\n\twhere there are $m+r-1=8$ symbols, $r=4$ of which are stars.\n\\end{ex}\n\n\\subsubsection{Hopf algebras and group schemes}\n$A(n,r)$ lies within $k^\\Gamma=k[\\Gamma]$, which has the structure of a Hopf algebra induced from the group \nstructure on $\\Gamma$. More precisely, the functor $\\Gamma:\\Alg_k\\to \\Grp$ that assigns to every $k$-algebra $A$ the group $\\GL_n(A)$ is representable. In other words, \n\\[\\GL_n(-)\\simeq \\Hom_{\\Alg_k}(R,-)\\]\nwhere $R=k[\\Gamma]$.\n\nThe anti-equivalence of the categories of affine group schemes over $k$ and finite dimensional commutative $k$-Hopf algebras (of which this is a particular instance) follows from Yoneda lemma \n(c.f. \\cite[chp. 1]{waterhouse}). The resulting Hopf algebra will be (as an algebra) $R$, and along with a coalgebra structure induced the group structure on $\\Gamma$: \nwe have maps $\\mu,\\epsilon$, the multiplication and unit maps on $\\Gamma$ satisfying the diagrams \n\\begin{center}\n\t\\begin{tikzcd}\n\t\t\\Gamma\\times\\Gamma\\times\\Gamma\\ar[r,\"\\mu\\times\\id\"]\\ar[d,\"\\id\\times\\mu\"] & \\Gamma\\times\\Gamma\\ar[d,\"\\mu\"]\\\\\n\t\t\\Gamma\\times\\Gamma\\ar[r,\"\\mu\"] & \\Gamma\n\t\\end{tikzcd}\n\t\\quad \\begin{tikzcd}\n\t\t\\ast\\times G\\ar[r,\"\\epsilon\\times\\id\"] &G\\times G\\ar[d,\"\\mu\"]& G\\times \\ast\\ar[l,\"\\id\\times\\epsilon\",swap]\\\\\n\t\t& G\\ar[ur,leftrightarrow,\"\\sim\"]\\ar[swap,ul,leftrightarrow,\"\\sim\"] &\n\t\\end{tikzcd}\n\\end{center}\n(where $\\ast$ is the trivial group and initial object in the category of group schemes) giving us associativity and identity. Yoneda tells us that the maps between schemes\n\\[\\mu:\\Gamma\\times\\Gamma\\to \\Gamma\\quad\\text{and}\\quad \\epsilon:\\ast\\to\\Gamma\\]\ngive rise to maps in $\\Alg_k$:\n\\[\\Delta\\eqdef\\mu^\\ast:R\\to R\\otimes_k R\\quad\\text{and}\\quad \\varepsilon\\eqdef\\epsilon^\\ast: R\\to k\\]\nsatisfying diagrams \n\\begin{center}\n\t\\begin{tikzcd}\n\t\tR\\otimes R\\otimes R & R\\otimes R\\ar[l,\"\\Delta\\otimes\\id\",swap]\\\\\n\t\tR\\otimes R\\ar[u,\"\\id\\otimes \\Delta\"] & R\\ar[u,\"\\Delta\"]\\ar[l,\"\\Delta\"]\n\t\\end{tikzcd}\n\t\\quad\\begin{tikzcd}\n\t\tk\\otimes R\\ar[dr,\"\\sim\",leftrightarrow,swap] & R\\otimes R\\ar[l,\"\\varepsilon\\otimes \\id\",swap]\\ar[r,\"\\id\\otimes\\varepsilon\"] & R\\otimes k\\ar[dl,\"\\sim\",leftrightarrow]\\\\\n\t\t& R\\ar[u,\"\\Delta\"] &\n\t\\end{tikzcd}\n\\end{center}\n\\begin{prop}\n\tThe maps $\\Delta$ and $\\varepsilon$ which, in coordinates, for $1\\le i,j\\le n$, are\n\t\\[\\Delta(c_{ij})=\\sum_k c_{ik}\\otimes c_{kj}\\quad\\text{and}\\quad \\varepsilon(c_{ij})=\\delta_{ij}\\]\n\tgive a coalgebra structure on $R$\n\\end{prop}\n\nThat these maps satisfy the diagrams above is a straightforward computation. That, furthermore, these maps make $R$ into a bialgebra amounts \nto checking that $\\Delta$ and $\\varepsilon$ are algebra morphisms.\nBut what is not immediately obvious is why \\textit{these particular maps} are the ones we use on $R$. To \nsee this, one must dig into the Yoneda correspondence a bit to see what happens to the multiplication and unit morphisms.\n\nIn service of this, let's translate matrix multiplication into a statement about representable functors. We want to define $m$ as a map \n\\[m:\\Hom(R,-)\\times\\Hom(R,-)\\to \\Hom(R,-)\\]\nand to see what $m$ should do in this context, we evaluate at a $k$-algebra \n\\[m_A:\\Hom(R,A)\\times\\Hom(R,A)\\to \\Hom(R,A)\\]\nwhere we interpret each map $f:R\\to A$ as a matrix with entries in $A$ by saying $f$ corresponds to a matrix $A_f$ such that \n\\[(A_f)_{ij}=f(c_{ij}).\\]\n\nThen if $(f,g)\\in \\Hom(R,A)\\times\\Hom(R,A)$, we want that the algebra structure is the usual matrix multiplication, so\n\\[m_A(f,g)=A_fA_g\\]\nand by computing the $(i,j)^{th}$ entry everywhere, we get \n\\[m_A(f,g)(c_{ij})=(A_fA_g)_{ij}=\\sum_{k=1}^n(A_f)_{ik}(A_g)_{kj}=\\sum_k f(c_{ik})g(c_{kj}).\\]\n\nThis gives us the values of our component maps everywhere, so this defines the natural transformation $m$. Then (the proof of)\nYoneda tells us that we can compute the corresponding algebra morphism as \n\\[\\mu(c_{ij})=m_{R\\otimes R}(\\iota_l\\otimes\\iota_r)(c_{ij})=\\sum_k \\iota_l(c_{ik})\\iota_r(c_{kj})=\\sum_k c_{ij}\\otimes c_{kj}.\\]\nAbove we call $\\iota_l$ (resp. $\\iota_r$) to be the map $R\\to R\\otimes R$ which embeds $R$ into the left (resp. right) tensor factor. Notice \nthat $\\iota_l\\otimes\\iota_r=\\id_{R\\otimes R}$.\n\nUsing the same identification between maps and matrices over $A$, let $\\ast:k\\to A$ be the unique map sending $1_k\\mapsto 1_A$. Then we want\n\\[u_A(\\ast)=f:R\\to A\\]\ncorresponding to the identity $(n\\times n)$ matrix over $A$. So \n\\[u_A(\\ast)(c_{ij})=f(c_{ij})=(I_n)_{ij}=\\delta_{ij}\\cdot 1_A.\\]\nAgain applying Yoneda, we have \n\\[\\varepsilon(c_{ij})=u_k(\\id_k)(c_{ij})=\\delta_{ij}1_k\\]\nand we have our counit map.\n\nIn fact, as mentioned before, $R$ becomes a bialgebra (a Hopf algebra even, although we won't need the antipode here). This means that \n$\\Delta$ and $\\varepsilon$ are algebra morphisms for the natural algebra structure given by multiplication $m$ on $R$. In diagrams:\n\\begin{center}\n\t\\begin{tikzcd}\n\t\tR^{\\otimes 4}\\ar[r,\"\\id\\otimes\\tau\\otimes 1\"] & R^{\\otimes4}\\ar[r,\"m\\otimes m\"]  & R\\otimes R\\\\\n\t\tR\\otimes R\\ar[u,\"\\Delta\\otimes \\Delta\"]\\ar[rr,\"m\"] & & R\\ar[u,\"\\Delta\"]\n\t\\end{tikzcd}\n\t\\quad\\begin{tikzcd}\n\t\tR\\otimes R\\ar[r,\"m\"]\\ar[d,\"\\varepsilon\\otimes\\varepsilon\"] & R\\ar[d,\"\\varepsilon\"]\\\\\n\t\tk\\otimes k\\ar[r,\"m\"] & k\n\t\\end{tikzcd}\n\\end{center}\nwhere $\\tau:R\\otimes R\\to R\\otimes R$ is the twist map $a\\otimes b\\mapsto b\\otimes a$. \nChasing an element through the diagram on the left, we get\n\\[\\tilde m\\circ (\\Delta\\otimes \\Delta)(c_{ij}\\otimes c_{ab})=\\sum_{1\\le k,l\\le n}c_{ik}c_{al}\\otimes c_{kj}c_{lb}=\\Delta(c_{ij}{c_{ab}})\\]\nor using our multi-index notation,\n\\[\\Delta(c_{(i,a),(j,b)})=\\sum_{(k,l)\\in I(n,2)}c_{(i,a),(k,l)}\\otimes c_{(k,l),(j,b)}.\\]\n\nWritten more simply, the fact that $\\Delta$ is an algebra morphism can be written \n\\[\\Delta(a\\cdot b)=\\Delta(a)\\ast\\Delta(b)\\]\nunder suitable definitions of $\\cdot$ and $\\ast$. In a way that can be made precise, this means in particular that \n\\[\\Delta(a\\cdot b\\cdot c)=\\Delta(a)\\ast\\Delta(b\\cdot c)=\\Delta(a)\\ast\\Delta(b)\\ast\\Delta(c)\\]\nand so on (since multiplication everywhere is associative) and therefore we can define this for arbitrary monomials and extend $k$-linearly: \n\\begin{prop}\n\tIf $i,j\\in A(n,r)$, then \n\t\\[\\Delta(c_{i,j})=\\sum_{k\\in I(n,r)}c_{i,k}\\otimes c_{k,j}\\quad\\text{and}\\quad \\varepsilon(c_{i.j})=\\delta_{i,j}\\]\n\\end{prop}\nOne can easily see that degree is preserved by $\\Delta$, meaning that \n\\begin{prop}\n\t$\\Delta$ and $\\varepsilon$ descend to a coalgebra structure on $A(n,r)$. That is, $A(n,r)$ is a ($k$-)coalgebra.\n\\end{prop}\n\n\\subsubsection{The structure maps of \\texorpdfstring{$\\rho$}{rho}}\nThis context empowers us to better understand what is meant by the structure maps of a representation. At the moment, we \ndefine a homogeneous polynomial representation by how it looks on points and simply use the fact it coalesces to a functor. \nA natural question to ask is how the structure morphisms relate to the entries of the matrices $\\rho_A(g)=M_{g,A}$.\n\nTo understand the answer to this question, we need to uncover how the entries of a matrix come about. We have been thinking of an element of \n$\\Gamma(A)$ as a matrix, but what it actually is is a morphism \n\\[k[x_{ij}]_{\\det}\\to A\\]\nand then thinking of $\\Aut(V\\otimes A)\\cong\\GL_m(A)$ in the same way, we interpret a representation \nas a map \n\\[\\rho:\\Hom(k[x_{ij}]_{\\det},-)\\to \\Hom(k[y_{kl}]_{\\det},-)\\]\nwhere $i$ and $j$ run from 1 to $n$ and $k$ and $l$ run from 1 to $m$. \n\nThen Yoneda lemma tells us that $\\rho$ corresponds to an algebra map\n\\[\\rho^\\ast:k[y_{lk}]_{\\det}\\to k[x_{ij}]_{\\det}\\]\nThis map is the one such that if $f\\in\\Hom(k[x_{ij}]_{\\det},A)$,\n\\[\\rho_A(f)=f\\circ\\rho^\\ast:k[y_{lk}]_{\\det}\\to k[x_{ij}]_{\\det}\\to A.\\]\n\nWhat are the structure maps for this representation? We can compute for any $g\\in \\GL_n(A)$ (which we, though a mild\nabuse of notation, think of as a map $g:k[x_{ij}]_{\\det}\\to A$ where $g(x_{ij})=g_{ij}$)\n\\[\\rho_A(g)\\cdot v_i=\\rho_A(g(x_{ij}))_{i,j}v_i=((g\\circ\\rho^\\ast)(y_{ij}))_{i,j}v_i=\\sum_j g(\\rho^\\ast(y_{ij}))v_j=\\sum_j\\rho^\\ast(y_{ij})(g)v_j\\]\nfrom which we can see\n\\begin{lem}\n\tLet $\\rho:\\Gamma\\to \\GL(V)$ be a polynomial representation. Then for any $A\\in\\Alg_k$, the structure maps $f_{ij}$ \n\tof the group representation $\\rho_A:\\GL_n(A)\\to \\GL_m(A)$ are precisely the $\\rho^\\ast(y_{ij})$.\n\\end{lem}\n\nThis enables us to re-define polynomial representations \nin the following way (compare with definition \\ref{def:poly-rep}):\n\\begin{defn}\\label{def:poly-rep-new}\n\tA finite dimensional \\textbf{polynomial representation of $\\Gamma$ of degree $r$} is a finite dimensional vector space $V$ \n\tover $k$ along with a scheme map $\\rho:\\Gamma\\to \\GL(V)$ such that the associated algebra map $\\rho^\\ast:k[\\GL(V)]\\to k[\\Gamma]\\cong k[x_{ij}]_{\\det}$ is homogeneous \n\tdegree $r$. In other words, the image of $\\rho^\\ast$ is entirely contained within the degree $r$ graded piece of $k[x_{ij}]\\subseteq k[\\Gamma]$.\n\\end{defn}\n\n\\begin{rmk}\n\tIn the following section, we freely identify $k[x_{ij}]_{\\det}$ with the ring of functions on $\\Gamma$, and $k[y_{lk}]_{\\det}$ with \n\tthe ring of functions on $\\GL(V)$ (where $m=\\dim V$).\n\\end{rmk}\n\n\\subsubsection{Comodules}\nIn this section let $A=A(n,r)$, which we have just established is a coalgebra with $\\Delta$ and $\\varepsilon$ defined above.\n\\begin{defn}\n\tA (left) \\textbf{$A$-comodule} is a vector space $V$ over $k$ along with a (left) \\textbf{$A$-coaction} given by a ($k$-)morphism \n\t\\[\\phi:V\\to A\\otimes_k V\\]\n\tthat is both \\textbf{coassociative and counital} in the sense that the diagrams in Figure~\\ref{fig:comodule} commute.\n\\end{defn}\n\\begin{figure}\n\t\\centering\n\t\\begin{tikzcd}\n\t\tV\\ar[r,\"\\phi\"]\\ar[d,\"\\phi\"] & A\\otimes V\\ar[d,\"\\id\\otimes\\phi\"]\\\\\n\t\tA\\otimes V\\ar[r,\"\\Delta\\otimes \\id\",swap] & A\\otimes A\\otimes V\n\t\\end{tikzcd}\\qquad \n\t\\begin{tikzcd}\n\t\tV\\ar[r,\"\\phi\"]\\ar[rd,\"\\sim\",swap] & A\\otimes V\\ar[d,\"\\varepsilon\\otimes\\id\"]\\\\\n\t\t& k\\otimes V\n\t\\end{tikzcd}\n\t\\caption{The coassociative and counital axioms}\n\t\\label{fig:comodule}\n\\end{figure}\n\nGiven two $A$-comodules $V$ and $W$, a comodule morphism $\\varphi:V\\to W$ is one that preserves the coaction. That is \n\\[(\\id\\otimes\\varphi)\\phi_V(v)=\\phi_W(\\varphi(v))\\]\nfor all $v\\in V$.\n\n\\begin{defn}\n\tLet $A$ be any coalgebra. Then $\\lcomod A$ denote the category of (finite-dimensional, left) $A$-comodules along with comodule morphisms.\n\\end{defn}\n\nSometimes a more useful way to think of polynomial representations is as comodules. That idea is made more formal\nin the following theorem:\n\\begin{lem}\\label{lem:comod-map}\n\tEvery homogeneous degree $r$ polynomial representation of $\\GL_n$ gives rise to an $A(n,r)$-comodule\n\tin the following way: the underlying vector space is the same and the $A(n,r)$ coaction is given by \n\t\\[\\phi(v_i)=\\sum_j\\rho^\\ast(y_{ij})\\otimes v_j\\]\n\twhere in the above we identify the algebra $k[y_{ij}]_{\\det}$ with the ring of functions on $\\GL(V)$. As a matter of notation, \n\twe call this map \n\t\\[\\Psi:\\Pol(n,r)\\to \\lcomod{A(n,r)}.\\]\n\\end{lem}\n\\begin{prf}\n\tBy definition this gives us a map into $\\lcomod{k[\\Gamma]}$, but we can see that the image is entirely contained within \n\t$\\lcomod{A(n,r)}$ since, in light of definition \\ref{def:poly-rep-new}, $\\rho^\\ast(y_{ij})$ is homogeneous degree $r$.\n\tThen it remains to show that the given map is legitimately a coaction. We can compute (identifing the map $\\varepsilon:k[\\Gamma]\\to k$ as the matrix $I_n$ over $k$)\n\t\\[(\\varepsilon\\otimes\\id)\\circ\\phi(v_i)=\\sum_j \\varepsilon(\\rho^\\ast(y_{ij}))\\otimes v_j=\\sum_j(\\varepsilon\\circ\\rho^\\ast)(y_{ij})\\otimes v_j=\\sum_j\\rho_k(I_n)_{ij}\\otimes v_j=1_k\\otimes v_i\\]\n\tso $\\phi$ satisfies the counit identity. For coassociativity, identify the morphism $k[\\Gamma]\\to k[\\Gamma]\\otimes k[\\Gamma]$ with the matrix $D$ whose entries are $\\Delta(x_{ij})$. Then\n\t\\begin{align*}\n\t\t(\\Delta\\otimes\\id)\\circ\\phi(v_i)&=\\sum_j\\Delta(\\rho^\\ast(y_{ij}))\\otimes v_j\\\\\n\t\t&=\\sum_j\\rho(D)_{ij}\\otimes v_j\\\\\n\t\t&=\\sum_j \\left(\\sum_k \\rho^\\ast(y_{ik})\\otimes\\rho^\\ast(y_{kj})\\right)\\otimes v_j\\\\\n\t\t&=\\sum_k \\rho^\\ast(y_{ik})\\otimes\\left(\\sum_j \\rho^\\ast(y_{kj})\\otimes v_j\\right)\\\\\n\t\t&=(\\id\\otimes\\phi)\\sum_k\\rho^\\ast(y_{ik})\\otimes v_k\\\\\n\t\t&=(\\id\\otimes\\phi)\\circ\\phi(v_i)\n\t\\end{align*}\n\twhich shows that $\\phi$ gives a $A(n,r)$-comodule structure on the underlying vector space of a representation $\\rho$ of $\\Gamma.$\n\\end{prf}\n\\begin{rmk}\n\tAbove we used the fact that, for all $g\\in\\GL_n(A)$, \n\t\\[\\Delta(\\rho^\\ast(y_{ij}))(g)=\\sum_k\\rho^\\ast(y_{ik})\\otimes\\rho^\\ast(y_{kj})\\]\n\twhich is true since the map\n\t\\[\\Delta\\circ\\rho^\\ast:k[\\GL(V)]\\to k[\\Gamma]\\otimes k[\\Gamma]\\]\n\tcorresponds to the map \n\t\\[\\rho\\circ m:\\Gamma\\times\\Gamma\\to \\GL(V)\\]\n\twhere, after evaluating at $A\\in\\Alg_k$,\n\t\\[(\\rho\\circ m)(M,N)=\\rho(MN)=\\rho(M)\\rho_A(N)=m\\circ(\\rho\\times\\rho)(M, N)\\]\n\twhich implies we have the equation\n\t\\[\\Delta\\circ \\rho^\\ast=(\\rho^\\ast\\otimes \\rho^\\ast)\\circ \\Delta\\]\n\tand the equality follows.\n\\end{rmk}\nThe preceeding lemma is in service of reframing the problem in terms of the comodules of a nicely-behaved (e.g. finite dimensional!) coalgebra:\n\\begin{lem}\n\tThe map $\\Psi$ defined in lemma~\\ref{lem:comod-map} is a functor.\n\\end{lem}\n\\begin{prf}\n\tLet $f:(V,\\rho)\\to (W,\\eta)$ be a map of homogeneous degree $r$ polynomial representations of $\\Gamma$. This is a linear map $f:V\\to W$ \n\tsatisfying the usual property that for any $A\\in\\Alg_k$, $a\\in V\\otimes A$ and $g_A\\in \\Gamma(A)$,\n\t\\[f(\\rho(g_A)a)=\\eta(g_A)f(a).\\]\n\t%This corresponds to a diagram\n\t%\\begin{center}\n%\t\t\\begin{tikzcd}[column sep=large]\n%\t\t\t\\Gamma\\times V\\ar[r,\"{(g,v)\\mapsto \\rho(g)v}\"]\\ar[d,\"\\id\\times f\",swap] & V\\ar[d,\"f\"]\\\\\n%\t\t\t\\Gamma\\times W\\ar[r,\"{(g,w)\\mapsto \\eta(g)w}\",swap] & W\n%\t\t\\end{tikzcd}\n%\t\\end{center}\n%\tand upon evaluating at $k[\\Gamma]$ the action gives us a coaction defined by (for all $v\\in V$)\n%\t\\[\\phi_\\rho(v)=\\rho_{k[\\Gamma]}(\\id_{k[\\Gamma]})(1_{k[\\Gamma]}\\otimes v)\\in k[\\Gamma]\\otimes V\\]\n\n\tWe want to show that $f$ is a map of $A(n,r)$-comodules. Let $v_i\\in V$ be a basis element as we have used before. Then if $f(v_i)=\\sum_k a_{ik}w_{k}$ where $W=\\langle w_k\\rangle$,\n\t\\[\\phi_W\\circ f(v_i)=\\phi_W\\left(\\sum_ka_{ik}w_k\\right)=\\sum_ka_{ik}\\phi_W(w_k)=\\sum_ka_{ik}\\left(\\sum_j \\eta^\\ast(y_{kj})\\otimes w_j\\right)\\]\n\tand on the other hand \n\t\\[(\\id\\otimes f)\\circ\\phi(v_i)=(\\id\\otimes f)\\left(\\sum_j\\rho^\\ast(y_{ij})\\otimes v_j\\right)=\\sum_j\\rho^\\ast(y_{ij})\\otimes f(v_i)=\\sum_j\\rho^\\ast(y_{ij})\\otimes\\left(\\sum _ka_{jk}w_k\\right)\\]\n\tand using the identification of \n\t\\[k[\\Gamma]\\otimes W\\cong \\Hom_k(\\Gamma,W)\\]\n\twe see the first line corresponds to the map \n\t\\[g\\mapsto \\sum_ka_{ik}\\sum_j\\eta(g)_{kj}w_j=\\sum_ka_{ik}\\eta(g)w_k=\\eta(g)f(v_i)\\]\n\tand the bottom line corresponds to \n\t\\[g\\mapsto \\sum_j\\rho(g)_{ij}f(v_j)=f\\left(\\sum_j\\rho(g)_{ij}v_j\\right)=f(\\rho(g)v_i)\\]\n\tand these two values are equal by virtue of of $f$ being a $G$-module morphism.\n\\end{prf}\nFinally we prove that these are the same category!\n\\begin{thm}\n\tThe map\n\t\\[\\Psi:\\Pol(n,r)\\to \\lcomod{A(n,r)}\\]\n\tis an equivalence of categories.\n\\end{thm}\n\\begin{prf}\n\tTo prove essential surjectivity, let $V$ be an $A(n,r)$ comodule with coaction $\\phi:V\\to A(n,r)\\otimes V$.\n\tWe define from this an object in $\\Pol(n,r)$ via the action \n\t\\[g\\cdot v=(e_g\\overline\\otimes \\id)\\circ\\phi(v)\\]\n\twhere $e_g:k[\\Gamma]\\to k$ is evaluation at $g\\in \\Gamma$ and \n\t\\[e_g\\overline\\otimes\\id (f\\otimes v)=f(g)v.\\]\n\tThis defines the map \n\t\\[\\rho:\\Gamma\\to \\GL(V)\\quad\\text{via}\\quad g\\mapsto (e_g\\overline\\otimes \\id)\\circ\\phi\\]\n\twhich is a representation of $\\Gamma$. To check that this is homogeneous degree $r$, we just compute (where here we write $\\phi(v)=\\sum_i f_i\\otimes v_i$)\n\t\\[\\rho(\\lambda g)(v)=(e_{\\lambda g}\\overline\\otimes\\id)\\circ\\left(\\sum f_i\\otimes v_i\\right)=\\sum f_i(\\lambda g)v_i=\\lambda^r\\sum f_i(g)v_i=\\lambda^r\\rho(g)(v)\\]\n\twhere we used that the $f_i$ are homogeneous degree $r$ maps.\n\n\tOur category is concrete (we have a faithful functor to $\\Set$) and therefore the comodule map $\\Psi(f)$\n\tis completely determined by its underlying map on sets. But $\\Psi(f)(v)=f(v)$ after passing to sets for all $v\\in V$,\n\tso $\\Psi$ is automatically fully faithful. \n\n\tThus $\\Psi$ is an equivalence of categories, as desired.\n\\end{prf}\n\\begin{rmk}\n\tActually, the above proof can be modified slightly to show that $\\Psi$ has a functorial inverse--that is, $\\Psi$ is an \\textit{isomorphism of categories}.\n\tSince we are only interested in representations up to isomorphism, however, equivalence is all we need.\n\\end{rmk}\n\n\\subsubsection{The Schur algebra}\nFinally we get to the actual object of study:\n\\begin{defn}\\label{def:schur-alg}\n\tA \\textbf{Schur algebra} is an element of the two-parameter family $\\{S(n,r)\\}=\\{S_k(n,r)\\}$ where $n$ and $r$ are any positive integers.\n\tAs a set, $S(n,r)$ is the linear dual of $A(n,r)$:\n\t\\[S(n,r)=A(n,r)^\\ast=\\Hom_k(A(n,r),k)\\] \n\n\tLet $\\xi_{i,j}$ denote the element dual to $c_{i.j}\\in A(n,r)$. In other words:\n\t\\[\\xi_{(a,b)}(c_{i,j})=\\begin{cases}\n\t\t1, & (a,b)\\sim(i,j)\\\\\n\t\t0, & \\text{otherwise}\n\t\\end{cases}\\]\n\\end{defn}\n\n\\begin{lem}\n\tThe coalgebra structure $(\\Delta,\\varepsilon)$ on $A(n,r)$ defines an algebra structure on $S(n,r)$.\n\\end{lem}\n\\begin{prf}\n\tSince $k$ is an initial object in $\\Alg_k$, there is a unique map $u:k\\hookrightarrow S(n,r)$ sending $1$ to the unit function $\\1$, which is given by \n\t\\[\\1(c_{i,j})=c_{i,j}(I_n)=\\delta_{i,j}\\]\n\tDefine multiplication $(\\cdot)$ in $S(n,r)$ as follows: if $f,g\\in S(n,r)$ then for any $x\\in A(n,r)$ define \n\t\\[(f\\cdot g)(x)=m_k\\circ (f\\otimes g)\\circ \\Delta(x)=\\sum f(x_{(1)})g(x_{(2)})\\]\n\twhere $m_k:k\\otimes k\\to k$ denotes multiplication in $k$ and $\\Delta(x)=\\sum x_{(1)}\\otimes x_{(2)}$ in Sweedler notation.\n\n\tThen we must just confirm that these maps satisfy the properties of a $k$-algebra. $(\\cdot)$ is $k$-bilinear because (for instance)\n\t\\begin{align*}\n\t\t((af+bg)\\cdot h)(x)&=\\sum (af+bg)(x_{(1)})\\otimes h(x_{(2)})\\\\\n\t\t&=\\sum a(f(x_{(1)})\\otimes h(x_{(2)}))+b(g(x_{(1)})\\otimes h(x_{(2)}))\\\\\n\t\t&= a\\sum f(x_{(1)})\\otimes h(x_{(2)})+ b\\sum g(x_{(1)})\\otimes h(x_{(2)})\\\\\n\t\t&=(a(f\\cdot h)+b(g\\cdot h))(x).\n\t\\end{align*}\n\t\n\tBy $k$-linearity, it suffices to show that the unit $\\1$ acts as it should on the spanning set $\\xi_{i,j}$ for a basis element $c_{a,b}$:\n\t\\[(\\1\\cdot \\xi_{i,j})(c_{a,b})=\\sum_{k=1}^n \\1(c_{a,k})\\cdot\\xi_{i,j}=\\1(c_{a,a})\\cdot\\xi_{i,j}(c_{a,b})=\\xi_{i,j}(c_{a,b})\\]\n\tand a similar identity holds on the right.\n\n\tThen it remains to show that this multiplication is associative. Again by linearity it suffices to check that this works on the spanning set $\\{c_{i,j}\\}$:\n\t\\begin{align*}\n\t\t((\\alpha\\cdot \\beta)\\cdot\\gamma)(c_{i,j})&=\\sum_{k\\in I(n,r)}(\\alpha\\cdot\\beta)(c_{i,k})\\gamma(c_{k,j})\\\\\n\t\t&=\\sum_k\\left(\\sum_{l\\in I(n,r)}\\alpha(c_{i,l})\\beta(c_{l,k})\\right)\\gamma(c_{k,j})\\\\\n\t\t&=\\sum_l\\alpha(c_{i,l})\\left(\\sum_k \\beta(c_{l,k})\\gamma(c_{k,j})\\right)\\\\\n\t\t&=\\sum_l\\alpha(c_{i,l})(\\beta\\cdot\\gamma)(c_{l,j})\\\\\n\t\t&=(\\alpha\\cdot(\\beta\\cdot\\gamma))(c_{i,j}).\n\t\\end{align*}\n\n\tThus since we have $k$-linear maps $\\1$ and $m=(\\cdot)$ satisfying the usual identity and associativity diagrams, $S(n,k)$ is a $k$-algebra \n\twith $\\1$ and $m$ as its unit and multiplication.\n\\end{prf}\n\n\nThere is a standard result that says \n\\begin{prop}\n\tThe finite dimensional left comodules of a coalgebra $\\Lambda$ are the same as finite dimensional right modules \n\tover $\\Lambda^\\vee=\\Hom(\\Lambda, k)$.\n\\end{prop}\n\\begin{prf}[sketch]\n\tThe key idea here is as follows: an right comodule over $\\Lambda^\\vee$ is, equivalently, a $k$-linear map \n\t\\[V\\otimes \\Lambda^\\vee\\to V\\]\n\tsatisfying the usual associativity and identity axioms.\tBut notice that \n\t\\[\\Hom(V\\otimes \\Lambda^\\vee,V)\\cong\\Hom(V,\\Hom(\\Lambda^\\vee,V))\\subseteq\\Hom(V,\\Lambda\\otimes V)\\]\n\twhich, in turn, correspond to $\\Lambda$ comodules. It remains to show that the associativity and unit axioms restrict \n\tthe collection on the left in the right way to give us a map satisfying the coassociativity and counit axioms on the right.\n\\end{prf}\n\nSince $S(n,r)$ is commutative ($A(n,r)$ is cocommutative), this tells us that there is an equivalence between $\\lcomod{A(n,r)}$ and $\\rmod{S(n,r)}\\cong\\lmod{S(n,r)}$, and so \n\\begin{cor}\n\tThe categories $\\Pol(n,r)$ and $\\lmod{S(n,r)}$ are equivalent.\n\\end{cor}\n\\begin{rmk}\n\tUsing this equivalence, we identify $\\lmod{S(n,r)}$ with $\\Pol(n,r)$ whenever it suits us.\n\\end{rmk}\n\nThe following result has been proven in many different contexts, but one source is a paper of Doty and Nakano which completely \ncategorized the semisimple Schur algebras.\n\\begin{cor}[{\\cite[Thm. 2]{doty-nakano}}]\\label{cor:semisimple}\n\tIf $\\ch k=p$, the algebra $S_k(n,r)$ is semisimple if and only if one of the following hold:\n\t\\begin{itemize}\n\t\t\\item $p=0$\n\t\t\\item $p>r$\n\t\t\\item $p=n=2$ and $r=3$\n\t\\end{itemize}\n\\end{cor}\n\n\\subsubsection{Weights and characters}\nThe discussion in section~\\ref{subsubsec:indices} highlights an important idea: while we care about the \\textit{quantities} in which each $c_{ij}$ occurs \nin a monomial, we are not particularly interested in the \\textit{order}. Sometimes it is easier, then, to simply regard these as weak compositions:\n\\begin{defn}\n\tLet $n$ and $r$ be integers as usual. Then denote by $[a_1,\\dots,a_n]$ the \\textbf{weight} corresponding to \n\t$(i_1,\\dots,i_r)\\in I(n,r)$ where for each $i$,\n\t\\[a_i=\\#\\{k\\in\\underline r| i_k=i\\}\\]\n\tDenote by $\\Lambda(n,r)$ the collection of all weights. \n\\end{defn}\n\\begin{rmk}\n\tAnother way to realize $\\Lambda(n,r)$ is in the presentation \n\t\\[\\Lambda(n,r)=\\left\\{[a_1,\\dots,a_n]\\left|\\sum_i a_i=r\\right.\\right\\},\\]\n\tor as the set of compositions of $r$ into $n$ parts (allowing zeros).\n\t\n\tYet another is to think of $\\Lambda(n,r)$ as the set of $\\frakS_r$ orbits in $I(n,r)$ (where now two objects \n\tare distinguished only if their ``contents'' vary).\n\\end{rmk}\nRecall (c.f. \\ref{def:schur-alg}) that we had that $\\xi_{i,j}(c_{a,b})=1$ if and only if $(i,j)\\sim(a,b)$. Because of this, it makes sense (if $\\alpha$ is the \nweight of $i$) to write \n\\[\\xi_{\\alpha}\\eqdef \\xi_{\\alpha,\\alpha}\\eqdef \\xi_{i,i}\\]\nsince the action is the same irrespective of the choice of representative $i$ of $\\alpha.$\n\nNotice that the weights admit a $\\frakS_n$ action \n\\[\\sigma\\cdot [a_1,\\dots,a_n]=[a_{\\sigma(1)},\\dots,a_{\\sigma(n)}]\\]\nthen \n\\begin{defn}\n\t$\\Lambda_+(n,r)$ is the orbit space of $\\Lambda(n,r)$ under the above $\\frakS(n)$ action.\n\\end{defn}\n\\begin{rmk}\n\tThe above are called the \\textbf{dominant weights} in $\\Pol(n,r)$. Since each orbit $\\alpha$ contains an element $[a_1,\\dots,a_n]\\in\\alpha$ such that \n\t\\[a_1\\ge a_2\\ge\\cdots\\ge a_n\\]\n\twe will often identify weights with their weakly-decreasing representative.\n\n\tSometimes we will refer to the dominant weight representing the orbit of $i\\in I(n,r)$ as the \\textbf{shape of $i$.}\n\\end{rmk}\n\nThe theory of weights in representations of $\\Gamma$ closely mirrors similar decompositions in other \nArtinian algebras: first we identify a family of (mutually orthogonal) idempotents:\n\\begin{lem}\n\tFor $\\alpha\\in\\Lambda(n,r)$ and $i,j\\in I(n,r)$,\n\t\\[\\xi_\\alpha\\xi_{i,j}=\\begin{cases}\n\t\t\\xi_{i,j}, & i\\in\\alpha\\\\\n\t\t0, &\\text{otherwise}\n\t\\end{cases}\\quad\\text{and}\\quad\\xi_{i,j}\\xi_\\alpha=\\begin{cases}\n\t\t\\xi_{i,j}, & j\\in\\alpha\\\\\n\t\t0, &\\text{otherwise}\n\t\\end{cases}\\]\n\\end{lem}\n\\begin{prf}\n\tWe can compute the image of these on the $c_{a,b}\\in A(n,r)$:\n\t\\begin{align*}\n\t\t\\xi_\\alpha\\cdot \\xi_{i,j}(c_{a,b})&=\\sum_k \\xi_\\alpha(c_{a,k})\\xi_{i,j}(c_{k,b})\\\\\n\t\t&= \\xi_\\alpha(c_{a,a})\\xi_{i,j}(c_{a,b})\n\t\\end{align*}\n\twhere above we used that $\\xi_{\\alpha}(c_{i,j})=0$ unless $i=j$. But \n\t\\[\\xi_\\alpha(c_{a,a})=\\begin{cases}\n\t\t1, & a\\in\\alpha\\\\ 0, & \\text{otherwise}\n\t\\end{cases}\\]\n\tso \n\t\\[\\xi_\\alpha\\cdot \\xi_{i,j}(c_{a,b})=\\begin{cases}\n\t\t\\xi_{i,j}(c_{a,b}),& a\\in\\alpha\\\\ 0,& \\text{otherwise}\n\t\\end{cases}\\]\n\tbut in the case where $a\\in\\alpha$ and $\\xi_{i,j}(c_{a,b})\\ne 0$, this implies that $i\\sim a$, so $i\\in \\alpha$. So finally,\n\t\\[\\xi_\\alpha\\cdot \\xi_{i,j}(c_{a,b})=\\begin{cases}\n\t\t\\xi_{i,j}(c_{a,b}),& i\\in\\alpha\\\\ 0,& \\text{otherwise}\n\t\\end{cases}\\]\n\tand since this holds for any $c_{a,b}$, the left-hand side is proven. A symmetric argument goes through for the right-hand side.\n\\end{prf}\n\nFor the next step, we decompose the identity into a sum of these idempotents:\n\\begin{lem}\\label{lem:decomp-one}\n\tWe have the decomposition \n\t\\[\\1 = \\sum_{\\alpha\\in\\lambda(n,r)} \\xi_\\alpha.\\]\n\\end{lem}\n\\begin{prf}\n\tOn the one hand, for any $c_{a,b}\\in A(n,r)$, $\\1(c_{a,b})=\\delta_{a,b}$. On the other hand, for any $\\alpha$,\n\t\\[\\xi_\\alpha(c_{a,b})=0\\]\n\twhen $a\\ne b$ \\textit{or when $a\\notin \\alpha$}. \n\t\n\tTherefore when $a=b$, there is precisely one $\\alpha$ (the orbit of $a=b$)\n\tsuch that $\\xi_\\alpha(c_{a,b})=1$, so putting this all together,\n\t\\[\\sum_{\\alpha\\in\\Lambda(n,r)}\\xi_\\alpha(c_{a,b})=\\delta_{a,b}\\]\n\twhence these two functions are equal.\n\\end{prf}\n\\begin{rmk}\\label{rmk-weight-spaces}\nUsing lemma~\\ref{lem:decomp-one}, we can then decompose any $V\\in \\Pol(n,r)$ into weight spaces:\n\\[V=\\1\\cdot V=\\sum_{\\alpha\\in\\Lambda(n,r)}\\xi_\\alpha V\\]\nwhich we will denote \n\\[\\xi_\\alpha V=V^\\alpha.\\]\n\\end{rmk}\n\n\\begin{defn}\\label{defn:character}\n\tThe \\textbf{formal character} of a representation $V\\in \\Pol(n,r)$ is a polynomial \n\t\\[\\Phi_V(X_1,\\dots,X_n)=\\sum_{\\alpha\\in\\Lambda(n,r)}(\\dim V^\\alpha)X_1^{\\alpha_1}\\cdots X_n^{\\alpha_n}=\\sum_{\\alpha\\in\\Lambda_+(n,r)}(\\dim V^\\alpha)m_\\alpha(X_1,\\dots,X_n)\\]\n\twhere $m_\\alpha$ is the \\textit{monomial symmetric polynomial}\n\t\\[m_\\alpha(X_1,\\dots,X_n)=\\sum_{\\sigma\\in\\frakS_n}X_{\\sigma(1)}^{\\alpha_1}\\cdots X_{\\sigma(n)}^{\\alpha_n}.\\]\n\\end{defn}\n\n\\subsubsection{Irreducible representations}\nThe irreducible representations in $\\Pol(n,r)$ are given by a couple of results by some of the big names in representation theory: the original proof for $k=\\bbC$ was proven in \\cite[p.37]{schur-thesis} and then \ngeneralized in a later paper by Weyl \\cite{weyl} and in work by Chevalley\\footnote{Green \\cite{green} mentions a paper by Serre: \\textit{Groupes de Grothendieck des Sch\\'emas en Groupes R\\'eductifs D\\'eploy\\'es} \\cite{serre-chevalley}, which \nmakes mention to Chevalley's contributions in proving the existence of modules with prescribed characters. This author was unable to find Chevalley's work.}:\n\\begin{thm}\\label{thm:irreps}\n\tFix the usual lexicographical ordering on monomials in $k[X_1,\\dots,X_n]$. Let $n$ and $r$ be given integers with $n\\ge 1$ and $r\\ge 0$ Let $k$ be an infinite field. Then \n\t\\begin{enumerate}\n\t\t\\item For each $\\lambda\\in\\Lambda_+(n,r)$, there exists an (absolutely) irreducible module $F_{\\lambda,k}$\n\t\tin $\\Pol(n,r)$ whose character $\\Phi_{\\lambda,k}$ has leading term $X_1^{\\lambda_1}\\cdots X_n^{\\lambda_n}$.\n\t\t\\item Every irreducible $V\\in \\Pol(n,r)$ is isomorphic to $F_{\\lambda,k}$ for exactly one $\\lambda\\in \\Lambda_+(n,r)$.\n\t\\end{enumerate}\n\\end{thm}\nSo then the problem of classifying the simple modules (the ``basic building blocks'' in the semisimple case) is completely solved for infinite fields.\nIt remains to demonstrate a way to construct $F_{\\lambda,k}$.\n\\begin{defn}\n\tFix some $\\lambda\\in \\Lambda_+(n,r)$. Notice that this corresponds to a Young diagram with $r$ boxes. Fix any labeling $1,\\dots,r$ of the boxes in the \n\tYoung diagram corresponding to $\\lambda$. Let $T$ denote the diagram for $\\lambda$ along with this labeling.\n\t\n\tLet $i:\\underline r\\to\\underline n$ be any map. Then denote by $T_i$ the \\textbf{$\\lambda$-tableau}, which is $T$ with the $k^{th}$ entry consisting of $i(k)\\in\\underline r$.\n\\end{defn}\n\\begin{rmk}\n\tThis notation varies slightly (but not in spirit) from the notation in Green's book. He denotes the Young diagram by $[\\lambda]$ and lets $T^\\lambda$ be \n\tthe labelling of the boxes in $[\\lambda]$--a bijection $[\\lambda]\\to\\underline r$.\n\\end{rmk}\n\\begin{ex}\n\tLet $\\lambda=(3,1,1)\\in\\Lambda_+(3,5)$. Thus $T$ is of shape \n\t\\[\\ydiagram{3,1,1}\\]\n\tThen if we fix the left-to-right/top-to-bottom ordering of the boxes in $T$ and let $i:\\{1,2,3,4,5\\}\\to\\{1,2,3\\}$\n\tbe given by $(2,1,3,3,2)$, we get the $\\lambda$-tableau \n\t\\[T_i=\\ytableaushort{2 1 3, 3, 2}\\]\n\\end{ex}\n\nThe core tool in constructing (a basis for) the irreducible modules is in the following definiton:\n\\begin{defn}\n\tLet $\\lambda\\in\\Lambda_+(n,r)$ be some shape with a fixed labeling and let $i,j:\\underline r\\to\\underline n$. Then the \\textbf{bideterminant of $T_i$ and $T_j$}\n\tis \n\t\\[(T_i:T_j)=\\sum_{\\sigma\\in C(T)}\\operatorname{sgn}(\\sigma)c_{i,j\\sigma}\\in A_k(n,r)\\]\n\twhere $C(T)$ is the column stabilizer of $T$.\n\\end{defn}\nThis definition can be a bit difficult to unpack, so we give some examples:\n\\begin{ex}\n\t\\begin{enumerate}\n\t\t\\item $\\lambda=(2,1,0)\\in \\Lambda_+(3,3)$\\[\\ytableausetup{nosmalltableaux}\\left(\\ytableaushort{1 2,3}:\\ytableaushort{3 1,2}\\right)=\\left|\\begin{array}{cc}\n\t\t\tc_{13} & c_{12}\\\\ c_{33} & c_{32}\n\t\t\\end{array}\\right|c_{21}=(c_{13}c_{32}-c_{12}c_{33})c_{2,1}=c_{(1,2,3),(3,1,2)}-c_{(1,2,3),(2,1,3)}\\]\n\t\t\\item $\\lambda=(n,0,\\dots,0)\\in\\Lambda_+(m,n)$\\[\\left(\\begin{ytableau} a_1& a_2& a_3&\\none[\\dots] &a_n\\end{ytableau}:\n\t\t\\begin{ytableau} b_1& b_2& b_3&\\none[\\dots]&b_n\\end{ytableau}\\right)=c_{a_1b_1}\\cdots c_{a_nb_n}\\]\n\t\t\\item $\\lambda=(1,\\dots,1,0,\\dots)\\in\\Lambda_+(m,n)$ where $n\\ge m$ \\[\\left(\\begin{ytableau}a_1\\\\ a_2\\\\\\none[\\vdots]\\\\a_n\\end{ytableau}:\\begin{ytableau}b_1\\\\ b_2\\\\\\none[\\vdots]\\\\b_n\\end{ytableau}\\right)=\n\t\t\t\\left|\\begin{array}{ccc}c_{a_1b_1} & \\cdots & c_{a_1b_n}\\\\\n\t\t\t\\vdots & \\ddots & \\vdots\\\\\n\t\t\tc_{a_nb_1} & \\cdots & c_{a_nb_n}\n\t\t\t\\end{array}\\right|\\]\n\t\\end{enumerate}\n\\end{ex}\n\nIn the following, let $l:\\underline r\\to\\underline n$ be $(1,\\dots,1,2,\\dots,2,3,\\dots)$ such that for any shape $\\lambda$ the \n$\\lambda$-tableau $T_l$ is \n\\[\\begin{ytableau}\n\t1 & 1 &\\none[\\dots] &\\none[\\dots] &1\\\\\n\t2 & 2 &\\none[\\dots] &2\\\\\n\t\\none[\\vdots]\\\\\n\tk\n\\end{ytableau}\\ytableausetup{smalltableaux}\\]\nwith $i$ in every box on the $i^{th}$ row from the top.\n\n\\begin{defn}\n\tDefine, for every shape $\\lambda\\in\\Lambda_+(n,r)$, the module\n\t\\[D_{\\lambda,k}=\\langle(T_l:T_i)\\rangle_{i\\in I(n,r)}\\]\n\twhere $l$ is the filling defined above.\n\\end{defn}\nAccording to \\cite{green}, these modules were originally called ``Weyl modules'', while he (and we)\nreserve this name for the contravariant dual of these objects. To construct them, define the map \n\\begin{equation}\\label{eqn:pimap}\n\t\\pi:E^{\\otimes r}\\to D_{\\lambda, k},\n\\end{equation}\nand we get objects originally defined in Carter and Lusztig's treatment of modular representations of $\\GL_n$ \\cite{carter-lusztig}\nand tweaked by Green in \\cite{green}:\n\\begin{defn}\n\tGiven a shape $\\lambda$, the \\textbf{Weyl module of shape $\\lambda$ over $k$} is \n\t$V_{\\lambda, k}\\eqdef N^\\perp$ where \n\t\\[N\\eqdef\\ker\\pi\\hookrightarrow E^{\\otimes r}\\to D_{\\lambda,k}\\]\n\tand the orthogonal complement of $N$ is taken with respect to the canonical contravariant form on $E^{\\otimes r}$ that has the property $\\langle e_i,e_j\\rangle=\\delta_{ij}$.\n\\end{defn}\n\nIn their original paper \\cite[p.218]{carter-lusztig}, Carter and Lusztig showed that these modules are, in fact, generated as $S(n,r)$-modules by a single element:\n\\begin{thm}\\label{thm:weyl-basis}\n\tLet $\\lambda\\in\\Lambda_+(n,r)$ and $T$ the Young diagram corresponding to $\\lambda$. Let $l$ be the labelling above. Then \n\tthe element \n\t\\[f_l=e_l\\cdot\\sum_{g\\in C(T)\\subset\\frakS_n}\\operatorname{sign}(\\sigma)\\sigma\\]\n\tgenerates $V_{\\lambda,k}$ as a $S(n,r)$-module.\n\\end{thm}\n\\begin{prf}[sketch.]\n\tWe refer the reader to Green's \\cite[p.46]{green} proof for the details, but the idea is as follows: he relies on an earlier result \n\tthat the modules $D_{\\lambda,k}$ have a basis consisting of the bideterminants \n\t\\[(T_l:T_i)\\]\n\tsuch that $T_i$ is in ``standard form'' (meaning that it forms a valid Young tableau). One can define a nondegenerate contravariant form \n\t\\[(\\cdot,\\cdot):V_{\\lambda,l}\\times D_{\\lambda,k}\\to k\\]\n\tby pulling back any element in $D_{\\lambda,k}$ to a representative in $E^{\\otimes r}$ under the map $\\pi:E^{\\otimes r}\\to D_{\\lambda,k}$.\n\n\tRecall that $V_{\\lambda,k}$ is defined as the orthogonal complement (under the canonical form $\\langle\\cdot,\\cdot\\rangle$ on $E^{\\otimes r}$) of $\\ker\\pi.$\n\tThis gives us that $(\\cdot,\\cdot)$ is indeed well-defined. From there, Green does some computation to show that one can bootstrap the \n\tindependence of the $(T_l:T_i)$ to prove that of the set\n\t\\[\\{\\xi_{jl}f_l|j\\in I(n,r), T_j\\text{ standard}\\}\\]\n\tforms a $(k-)$basis for $V_{\\lambda,k}$, and therefore $f_l$ generates the entire module under the $S(n,r)$ action.\n\\end{prf}\n\\begin{lem}\\label{lem:unique-maximal-submod}\n\tThe modules $V_{\\lambda,k}$ have a unique maximal submodule $V_{\\lambda,k}^{\\text{max}}$\n\\end{lem}\n\\begin{prf}[{\\cite[p.47]{green}}]\n\tBegin by noticing that the weight space $V_{\\lambda,k}^\\lambda$ is spanned by the single element $f_l$. This is because\n\t\\[\\xi_l\\cdot\\xi_{il}f_l=\\delta_{il}f_l\\]\n\tso the only nonzero basis vector from the proof of thm.~\\ref{thm:weyl-basis} is $f_l$ itself. Since $f_l$ generates \n\tall of $V_{\\lambda,k}$ as an $S(n,r)$-module, however, any proper submodule $M$ of $V_{\\lambda,k}$ must be contained in the \n\tcomplement of $V_{\\lambda,k}^\\lambda.$ Thus the sum of all proper submodules is contained in the complement of this \n\tweight space, and is therefore proper! This sum is our $V_{\\lambda,k}^\\text{max}$\n\\end{prf}\n\nWe are finally in good shape to compute the irreducible modules promised to us in thm.~\\ref{thm:irreps}. We define \n\\[F_{\\lambda, k}=V_{\\lambda,k}/V_{\\lambda,k}^\\text{max}\\]\nwhere $V_{\\lambda,k}^\\text{max}$ is the unique maximal submodule guaranteed to us by lemma~\\ref{lem:unique-maximal-submod}. It remains to show \nthat the $F_{\\lambda,k}$ have the requisite characters $\\Phi_{\\lambda,k}$. But notice that $V^\\lambda_{\\lambda,k}$ is one-dimensional, so \nthe character (c.f. definition \\ref{defn:character}) of $V_{\\lambda, k}$ is of the form \n\\[m_\\lambda(X_1,\\dots,X_n)+\\sum_{\\lambda\\ne\\alpha\\in\\Lambda_+(n,r)} \\dim V_{\\lambda,l}^\\alpha m_\\alpha(X_1,\\dots,X_n)\\]\nbut since each $V_{\\lambda,k}^\\alpha$ is contained in $V_{\\lambda,k}^\\text{max}$, it occurs as a weight space of this maximal submodule with the \nsame multiplicity. Therefore the character of $V_{\\lambda,k}^\\text{max}$ is \n\\[\\sum_{\\lambda\\ne\\alpha\\in\\Lambda_+(n,r)} \\dim V_{\\lambda,l}^\\alpha m_\\alpha(X_1,\\dots,X_n)\\]\nso we can conclude that \n\\[\\Phi_{V_{\\lambda,k}}(X_1,\\dots,X_n)=m_\\lambda(X_1,\\dots,X_n)=X_1^{\\lambda_1}\\cdots X_n^{\\lambda_n}+\\cdots\\]\nwhich has leading term (under the lexicographic ordering) precisely what we wanted.\n\n\n\\subsection{Explicit examples for comparison}\nTo demonstrate the theory developed above, we begin a computation (in a simple case) of the isomorphism classes of irreducible \nrepresentations of both $S_\\bbC(2,2)$ and $\\frakS_2$.\n\n\\subsubsection{The symmetric group on two letters}\nThe representation theory (over $k=\\bbC$) of $\\frakS_2$ is as simple as it comes: of course $\\frakS_2\\cong \\bbZ/2\\bbZ$ and we know that \nthere are $|G|$ nonisomorphic irreducible representations of an abelian group $G$ over $\\bbC$. Since we are talking about a symmetric group, \nwe can realize these as the trivial and sign representations, represented by the Young diagrams:\n\\[\\ydiagram{2}\\quad\\text{and}\\quad\\ydiagram{1,1}\\]\n\nAs submodules of the regular representation $k\\frakS_2= k e\\oplus k(1\\,2)$, we can construct these as $\\langle e+(1\\, 2)\\rangle$ (trivial representation) and $\\langle e-(1\\,2)\\rangle$ (sign representation).\n\n\\subsubsection{The Schur algebra \\texorpdfstring{$S_\\bbC(2,2)$}{S(2,2)}}\nSince $\\ch\\bbC=0$, corollary~\\ref{cor:semisimple} implies that $S_\\bbC(2,2)$ is semisimple, so it suffices to identify the irreducible submodules therein.\nWe know \n\\[S=S_\\bbC(2,2)\\cong \\bbC^2\\otimes\\bbC^2\\]\nso $\\dim_\\bbC S=4.$ The theory outlined above gives us that isomorphism types of irreducible modules are in bijection with compositions of 2 of length 2, meaning \nwe have two isomorphism types: one corresponding to $\\lambda_1=(1,1)$ and one corresponding to $\\lambda_2=(2,1)$. \n\nUsing the construction of $D_{\\lambda,\\bbC}$ from above, we can compute these two irreducible modules explicitly:\n\n\\begin{ex}[$\\mathbf{\\lambda_1=(1,1)}$]\n In this case our shape is $(1,1)$, corresponding to the Young diagram \n\\[\\ydiagram{1,1}\\]\nand then $D_{\\lambda_1,\\bbC}$ is spanned by the element\n\\[(T_l:T_{(2,1)})=\\left(\\ytableaushort{1,2}:\\ytableaushort{2,1}\\right)=c_{12}c_{21}-c_{11}c_{22}=c_{(1,2),(2,1)}-c_{(1,2),(1,2)}\\in A_\\bbC(2,2)\\]\nsince all other bideterminants of this shape are zero or linearly dependent. Thus this is a one-dimensional irreducible representation.\n\\end{ex}\n\\begin{ex}[$\\mathbf{\\lambda_2=(2,0)}$]\nNow our shape is $(2,0)$, corresponding to the diagram\n\\[\\ydiagram{2}.\\]\nThe bideterminants here are \n\\begin{align*}\n\t(T_l:T_{(1,1)})=\\big(\\ytableaushort{1 1}:\\ytableaushort{1 1}\\big)=c_{11}^2\\\\\n\t(T_l:T_{(1,2)})=(T_l:T_{(2,1)})=c_{11}c_{12}\\\\\n\t(T_l:T_{(2,2)})=c_{12}^2\n\\end{align*}\nSo we have a three-dimensional irreducible representation spanned by $\\langle c_{11}^2,c_{11}c_{12},c_{12}^2\\rangle$.\n\\end{ex}\nSince these are the only two Young diagrams of size two, these examples form a complete list of isomorphism classes of irreducible representations of $S_\\bbC(2,2)$.\n\nIf we prefer instead to recognize our irreducibles as submodules of $E^{\\otimes 2}=(k e_1\\oplus k e_2)^{\\otimes 2}$ (giving us a more obvious action by our algebras), \nwe can use the short exact sequence \n\\[0\\to N\\hookrightarrow E^{\\otimes 2}\\twoheadrightarrow D_{\\lambda,\\bbC}\\to 0\\]\nto define the $N=\\ker\\pi$, where $\\pi$ is the map defined in equation (\\ref{eqn:pimap}) above.\nThen we can compute the orthogonal complement to $N$ to get $V_{\\lambda,\\bbC}$.\nWe can compute:\n\\[V_{\\lambda_1,\\bbC}=\\langle e_1\\otimes e_2-e_2\\otimes e_1\\rangle\\]\nand\n\\[V_{\\lambda_2,\\bbC}=\\langle e_1\\otimes e_1, \\,e_1\\otimes e_2+e_2\\otimes e_1, \\,e_2\\otimes e_2\\rangle.\\]\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\newpage\n\\section{The Schur-Weyl Functor}\nFrom the discussion in the last section it is evident that the combinatorics behind the representation theory of $S(n,r)$ and $\\frakS_r$ have some intersections\nin their use of Young tableaux and this connection is more than superficial. In fact, there is a functor relating the representations\nof these two objects in the following way:\n\\subsection{Construction of the Schur-Weyl functor \\texorpdfstring{$\\calF$}{F}}\n\nLet $V\\in \\Pol(n,r)$ be a $S(n,r)$-representation and select any weight $\\alpha\\in\\Lambda(n,r)$. Then the weight space (cf. rmk~\\ref{rmk-weight-spaces})\n\\[V^\\alpha=\\xi_\\alpha V\\]\nbecomes a $S(\\alpha)\\eqdef\\xi_\\alpha S(n,r)\\xi_\\alpha$-module using the action from $S(n,r)$. Now if we allow $r\\le n$ and let\n\\[\\omega=(1,\\dots,1,0,\\dots,0)\\in\\Lambda(n,r)\\]\nnotice that $S(\\omega)$ is spanned by the elements\n\\[\\xi_\\omega\\xi_{i,j}\\xi_\\omega,\\quad i,j\\in I(n,r)\\]\nbut by the multiplication rules established in the definition of $S(n,r)$, these are nonzero precisely when \n$i$ and $j$ are both of shape $\\omega$. So then since $\\xi_{i,j}=\\xi_{i\\sigma,j\\sigma}$ for all $\\sigma\\in\\frakS_r$, we can take as\na basis of $S(\\omega)$ the set \n\\[\\{\\xi_{u\\pi,u}|\\pi\\in\\frakS_r\\}\\]\nwhere $u=(1,2,\\cdots,r)\\in I(n,r)$.\n\nTo prove the next statement we require a computational result.\n\\begin{lem}\\label{lem:somega-mult}\n\tIf $u=(1,2,\\dots,r)\\in I(n,r)$, then for all $\\pi,\\sigma\\in\\frakS_r$,\n\t\\[\\xi_{u\\pi,u}\\cdot \\xi_{u\\sigma,u}=\\xi_{u\\pi\\sigma,u}.\\]\n\\end{lem}\n\\begin{prf}\n\tUsing the formulas for multiplication in $S(n,r)$, recall that \n\t\\begin{equation}\n\t\t\\xi_{u\\pi,u}\\cdot\\xi_{u\\sigma,u}=\\sum Z_{i,j} \\xi_{i,j}\\label{eq:1}\n\t\\end{equation}\n\twhere \n\t\\[Z_{i,j}=\\#\\{s\\in I(n,r)|(u\\pi,u)\\sim(i,s)\\text{ and }(u\\sigma,u)\\sim (s,j)\\}.\\]\n\tThen for each $i,j$, since $u=(1,2,\\dots,r)$ has no stabilizer in $\\frakS_r$, there is a unique \n\t$g$ such that $u\\pi g=i$, meaning that $s=ug$. \n\n\tBut then this fixes (again a unique) $h\\in\\frakS_r$ such that $u\\sigma h=s=u g$ whence $\\sigma h= g$. \n\tOne computes that \n\t\\[u\\pi\\sigma h = u\\pi g=i\\quad\\text{and}\\quad uh = j\\]\n\ttherefore since in the above computation $s$ was completely determined by $i$, we have\n\t\\[Z_{i,j}=\\left\\{\\begin{array}{lr}\n\t\t1, &  (i,j)\\sim(u\\pi\\sigma,u)\\\\\n\t\t0, & \\text{otherwise}\n\t\\end{array}\\right.\\]\n\tand the result follows.\n\\end{prf}\nUsing this result, we prove a more obviously useful statement:\n\n\\begin{lem}\n\t$S(\\omega)\\cong k\\frakS(r)$.\n\\end{lem}\n\\begin{prf}\n\tDefine the map $\\varphi:S(\\omega)\\to k\\frakS_r$ on the basis above to be \n\t\\[\\varphi (\\xi_{u\\pi,u})=\\pi\\]\n\tand extending $k$-linearly.\n\n\tThis is a homomorphism since \n\t\\[\\varphi(\\xi_{u\\pi,u}\\xi_{u\\sigma,u})=\\varphi(\\xi_{u\\pi\\sigma,u})=\\pi\\sigma=\\varphi(\\xi_{u\\pi,u})\\varphi(\\xi_{u\\sigma,u})\\]\n\tand it is bijective since it is bijective on the respective bases and is thus bijective as a linear map.\n\\end{prf}\nThe upshot of these lemmas is that one can define the \\textbf{Schur-Weyl functor} \n\\[\\calF:\\Pol(n,r)\\to \\Rep(\\frakS_r)\\]\nvia the map that sends any representation $V$ to its $\\omega$ weight space $V^\\omega\\in \\lmod {S(\\omega)}\\simeq \\Rep(\\frakS_r)$.\n\n\\subsecti on{The general theory}\nThe idea of the Schur functor fits into a larger context: Let $S$ be a $k$-algebra and let $M\\in\\lmod S$. Furthermore, let $e\\in S$ be a (nonzero)\nidempotent. Then one can define a functor \n\\[\\calF:\\lmod S\\to\\lmod {eSe}\\quad\\text{via}\\quad V\\mapsto eV.\\]\nAn important property of this functor is \n\\begin{prop}\\label{prop:F-irred}\n\tThe image of an irreducible $S$ module under the functor $\\calF$ above is zero or irreducible.\n\\end{prop}\n\\begin{prf}\n\tLet $e\\in S$ be the idempotent in the discussion above and let $W\\subseteq eV$ be any nonzero $eSe$-submodule.\n\tThen notice that $eW$ is a nonzero $S$-module contained in $e^2V=eV$, so $eW=eV$.\n\tBut since $eW\\subseteq W$, this forces $W=eV$, so $\\calF(V)$ is irreducible.\n\\end{prf}\n\nNext, a discussion in Green \\cite[p. 56]{green} gives us a natural thought process to follow in constructing a partial inverse to this functor. \nLet $\\calG:\\lmod{eSe}\\to\\lmod S$ be an extension of scalars: specifically, if $M\\in\\lmod{eSe}$, then \n\\[\\tilde\\calG(M)=Se\\otimes_{eSe}M.\\]\nThis is clearly functorial and furthermore satisfies the property that \n\\[\\calF\\circ\\tilde\\calG(M)=\\calF(Se\\otimes_{eSe}M)=e(Se\\otimes_{eSe}M)=eSe\\otimes_{eSe} M\\cong e\\otimes_{eSe}M\\cong M\\]\nso it is a right inverse (up to isomorphism) to $\\calF$---a good candidate for our purposes. \n\\begin{rmk}\n\tIt is easy to prove the fact, which I glossed over above, that $M\\cong e\\otimes M$ via the $eSe$-isomorphism $m\\mapsto e\\otimes m$.\n\\end{rmk}\n\nWhat we are really looking for, however, is a functor that sends irreducible modules to irreducibles. It can be shown that $\\tilde G$ \n\\textit{does not} satisfy this property, so we define \n\\begin{defn}\n\tIf $M\\in\\lmod S$ and $e\\in S$ is an idempotent, denote by $M_{(e)}$ the largest $S$-submodule of $(1-e)M$.\n\\end{defn}\n\\noindent which enables us to define the functor \n\\[\\calG:\\lmod{eSe}\\to \\lmod S\\quad\\text{via}\\quad M\\mapsto \\tilde\\calG(M)/\\tilde\\calG(M)_{(e)}.\\]\nThis leads to the result:\n\\begin{prop}\n\tIf $M\\in \\lmod{eSe}$ is irreducible, then so is $\\calG(M)$.\n\\end{prop}\n\\begin{prf}\n\tLet $W$ be an $S$-module such that \n\t\\[\\tilde\\calG(M)_{(e)}\\subseteq W\\subseteq \\tilde\\calG(M)\\]\n\tThen consider multiplying by $e$ in the above inculsions:\n\twe get\n\t\\[0=e\\tilde\\calG(M)_{(e)}\\subseteq eW\\subseteq e\\tilde \\calG(M)=\\calF\\circ\\tilde\\calG(M)\\simeq M\\]\n\twhich, by the irreducibility of $M$, forces either $eW=0$ (in which case $W\\subseteq\\tilde\\calG(M)_{(e)}$ and we are done)\n\tor else $eW=e\\tilde\\calG(M)$.\n\n\tIn this latter case, we find \n\t\\[\\tilde\\calG(M)= Se\\otimes M\\simeq Se\\otimes eSeM=S(eSe\\otimes M)=S(e\\tilde\\calG(M))=SeW\\subseteq W\\]\n\tThus we can conclude that $W=\\tilde\\calG(M)$, so $\\calG(M)$ has no nontrivial proper submodules, so it is simple.\n\\end{prf}\n\n\\subsection{Properties of \\texorpdfstring{$\\calF$ and $\\calG$}{F and G}}\nReturning to the specific case of $S=S(n,r)$ and $eSe\\cong\\frakS_r$, the theory developed in the last part\ngives us a pair of functors\n\\[\\calF:\\Pol(n,r)\\to \\lmod{\\frakS_r},\\qquad \\calG:\\lmod{\\frakS_r}\\to \\Pol(n,r),\\]\neach of which preserve irreducibility. We also have that\n\\begin{prop}\n\tIf $M\\in \\Pol(n,r)$ is irredicible and if $eM\\ne 0$, then $\\calG\\circ\\calF(M)=\\calG(eM)\\cong M.$\n\\end{prop}\n\\begin{prf}\n\tNotice by prop.~\\ref{prop:F-irred} and the following discussion that $eM$ is irreducible and (by assumption) nonzero, so\n\t\\[\\calF\\circ\\calG(eM)\\cong eM\\]\n\tand since \n\t\\[0\\ne eM\\subseteq M\\]\n\tand $M$ is irreducible, $eM=M$.\n\\end{prf}\n\n\\subsection{In positive characteristic}\nSchur's classical work dealt only with the case when $k$ is a field of characteristic zero. In Aquilino and Reischuk's paper \\cite{aquilino-reischuk} \non the monoidal structure of $\\lmod{S(n,d)}$, the authors mention that (in general),\n\\[\\lmod{S(n,d)}\\not\\cong\\lmod{\\frakS_d}.\\]\n\nTo fix this problem, the authors restrict attention to the ``nicely behaved ones''. Let $M^\\lambda$ denote \nthe $\\lambda\\in\\Lambda(n,d)$ weight space of $E^{\\otimes d}=(k^n)^{\\times d}$. Then one can define \n\\begin{defn}\n\tLet $M=\\{M^\\lambda|\\lambda\\in\\Lambda(n,d)\\}$ and let the category $\\mathbf{add}(M)$ be the full subcategory of $\\lmod{\\frakS_d}$ consisting \n\tof modules that are summands of finite direct sums of weight modules $M^\\lambda\\in M$.\n\\end{defn}\nOne can define an analogous subcategory $\\mathbf{add}(S(n,d))$, and the usual Schur-Weyl functor \n\\[\\calF(M)=\\xi_\\omega M=M^\\omega\\]\nrestricts to an equivalence between the categories $\\mathbf{add}(M)$ and $\\mathbf{add}(S(n,d)).$\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\newpage\n\\section{Strict polynomial functors}\nThe theory of strict polynomial functors has its genesis in the idea of \\textit{polynomial maps between vector spaces},\nor equivalently the rational maps between the schemes they represent. The category of vector spaces with these polynomial maps---and \nmore specifically, the representaion category associated to it---gives the category $\\Rep \\Gamma^d_k$ of strict polynomial functors. \n\nOriginally definied by Friedlander and Suslin in \\cite{friedlander-suslin}, the authors there showed that \nthe category $\\lmod{S(n,r)}$ is equivalent to this category, introducing the language of polynomial functors as \na way to understand the structure of representations of the Schur algebras. \n\nThis process was carried out by Krause \\cite{krause-strict-poly-func} and his students Aquilino and Reischuk \\cite{aquilino-reischuk}.\nIn the former, Krause identifies projective generators $\\Gamma^{d,V}$ for $\\Rep\\Gamma^d_k$ and defines the tensor product \nby defining it for projectives and taking the appropriate colimits. In the latter paper, the construction \nis further elucidated and it is proven that the Schur-Weyl functor $\\calF$ is monoidal.\n\n\\subsection{Polynomial maps}\nLet $V,W$ be vector spaces over a field $k$. There are many equivalent formulations of polynomial maps between such spaces, \nbut one that this author of this paper finds particulaly motivating is the scheme-theoretic one:\n\\begin{defn}\\label{defn:poly-maps}\n\tLet $V,W$ be as above. Then the set of \\textbf{polynomial maps from $V$ to $W$} is defined to be \n\t\\[\\Hom_\\text{Pol}(V,W)\\eqdef \\Hom_{\\Sch/k}(V,W).\\]\n\\end{defn}\n\nTo make sense of this definition, one recalls that every $V\\in\\Vectk$ corresponds to an affine $k$-scheme \n$\\Spec S^\\ast(V^\\vee)=V\\otimes_k-$ (which we, through an abuse of notation, again denote $V$) represented by the symmetric algebra of the dual of $V$. Thus the polynomial maps\nare precisely the rational maps one considers between these objects in their algebro-geometric realizations.\n\nFor reasons that will become apparent shortly, it is easier to identify the polynomial maps with elements of a vector space in the following way:\n\\begin{defn}\n\tIf $V,W\\in\\Vectk$ are finite dimensional, a \\textbf{polynomial map $f:V\\to W$} can be alternatively defined as an element \n\t\\[f\\in W\\otimes S^\\ast(V^\\vee)\\cong\\Hom_{\\Sch/k}(V,W)\\]\n\tthrough the identifications above.\n\\end{defn}\n\\begin{rmk}\n\tIn Friedlander and Suslin's original paper, they take this to be the first definition of a polynomial map. That this \n\tagrees with the geometric definition (assuming that $V$ and $W$ are finite dimensional) follows from the following series of isomorphisms:\n\t\\begin{align*}\n\t\t\\Hom_\\text{Pol}(V,W)&\\eqdef\\Hom_{\\Sch/k}(V,W)\\\\\n\t\t&\\simeq\\Hom_{\\Alg_k}(S^\\ast(W^\\vee),S^\\ast(V^\\vee))\\\\\n\t\t&\\simeq\\Hom_{k}(W^\\vee,S^\\ast(V^\\vee))\\\\\n\t\t&\\simeq W\\otimes S^\\ast(V^\\vee)\n\t\\end{align*}\n\twhere we used above properties of affine schemes and standard facts of the linear algebra of finite dimensional vector spaces as well as the fact that \n\ta map from $S^\\ast(V)$ is determined uniquely by its images on $V$.\n\\end{rmk}\n\nThe upshot to this seemingly more \\textit{ad hoc} definition is that, while it introduces the restriction of finite dimensionality (which will suffice for our \ndefinitions anyways), it enables us to make more simple the following idea:\n\\begin{defn}\\label{def:homog-poly-map}\n\tLet $V$ and $W$ be vector spaces. Then a map $f\\in \\Hom_\\text{Pol}(V,W)$ is called \\textbf{homogeneous degree $d$} if \n\tit corresponds (under the isomorphisms above) to an element \n\t\\[f\\in W\\otimes S^d(V^\\vee).\\]\n\\end{defn}\nThis is clearly a tangible and sensible way to define a degree $d$ map and it is less obvious how to define a property \non the map of corresponding varieties that achieves the same goal. We will see in the next subsection other ways to define this \nnotion that may appeal more to representation theorists.\n\\begin{ex}\n\tHere are some examples of polynomial maps:\n\t\\begin{itemize}\n\t\t\\item The identity (scheme) map $\\id:V\\to V$ is a (homogeneous degree 1) polynomial map. This corresponds to the element \n\t\t\\[\\sum_{i=1}^n v_i\\otimes v_i^\\vee\\in V\\otimes S^\\ast(V^\\vee)\\]\n\t\twhere $v_1,\\dots,v_n$ is a basis for $V$.\n\t\t\\item If $V=\\langle v_1,\\dots,v_n\\rangle$ and $W=\\langle w_1,\\dots,w_m\\rangle$, the element\n\t\t\\[\\sum_1^m w_i\\otimes (v_i^\\vee\\otimes v_i^\\vee)\\]\n\t\tgives rise to a map of algebras that sends basis element\n\t\t\\[\\sum_{\\sigma\\in\\frakS_k}w_{i_{\\sigma(1)}}^\\vee\\otimes \\cdots\\otimes w_{i_{\\sigma(k)}}^\\vee\\mapsto \\sum_{\\sigma\\in\\frakS_k}v_{i_{\\sigma(1)}}^\\vee\\otimes v_{i_{\\sigma(1)}}^\\vee\\otimes \\cdots\\otimes v_{i_{\\sigma(k)}}^\\vee\\otimes v_{i_{\\sigma(k)}}^\\vee\\]\n\t\twhich corresponds to a homogeneous degree 2 polynomial (scheme) map $V\\to W$.\n\t\\end{itemize}\n\\end{ex}\n\n\\subsection{The category \\texorpdfstring{$\\calP_k$}{Pk} of strict polynomial functors}\nBefore we define these categories we should describe the objects in question!\n\\begin{defn}\n\tA \\textbf{strict polynomial functor} is a functor $T:\\Vect_k\\to \\Vect_k$ such that for any $V,W\\in\\Vect_k$,\n\tthe map on $\\Hom$s\n\t\\[T_{V,W}:\\Hom_k(V,W)\\to \\Hom_k(T(V),T(W))\\]\n\tis a polynomial map. That is,\n\t\\[T_{V,W}\\in\\Hom_\\text{Pol}\\big(\\Hom_k(V,W), \\Hom_k(T(V),T(W))\\big)\\]\n\\end{defn}\n\nEarlier I promised that we would have a more representation-theoretic interpretation of the homogeneous degree \nof a strict polynomial functor. I am nothing if I am not true to my word:\n\\begin{lem}[Lem. 2.2 in \\cite{friedlander-suslin}]\n\tLet $T$ be a strict polynomial functor and let $n\\ge 0$ be an integer. Then the following conditions are equivalent:\n\t\\begin{enumerate}\n\t\t\\item For any $V\\in\\Vectk$, any field extension $k'/k$ and any $0\\ne\\lambda\\in k'$, the $k'$-linear \n\t\tmap $T_{k'}(\\lambda\\cdot 1_{V_{k'}})\\in\\End_{k'}(T(V)_{k'})$ coincides with $\\lambda^n1_{T(V)_{k'}}$.\n\t\t\\item For any $V\\in\\Vectk$, $n$ is the only weight of the representation of the algebraic group $\\Gm$ in $T(V)$\n\t\tobtained by applying $T$ to the evident representation of $\\Gm$ in $V$.\n\t\t\\item For any $V,W\\in\\Vectk$, the polynomial map \n\t\t\\[T_{V,W}:\\Hom_k(V,W)\\to \\Hom_k(T(V),T(W))\\] \n\t\tis homogeneous of degree $n$ (in the sense of \\ref{def:homog-poly-map}).\n\t\\end{enumerate}\n\\end{lem}\n%\\begin{prf}\n%\t\\color{red} sketch out ideas here. Maybe just important ones.\n%\\end{prf}\n\n\\begin{defn}\n\tThe category $\\calP_d$ is the full subcategory \n\t\\[\\calP_d\\subset\\Func(\\Vectk,\\Vectk)\\]\n\twhose objects are the \\textbf{strict polynomial functors of degree $d$.}\n\\end{defn}\n\nWe refer the reader to \\cite[Thm. 3.2]{friedlander-suslin} for a proof of the following fact:\n\\begin{thm}\\label{thm:FS-equiv}\n\tLet $n\\ge d$. Then the map\n\t\\[\\Psi:\\calP_d\\to \\lmod {S(n,d)}\\]\n\tgiven by evaluation at $k^n$:\n\t\\[T\\mapsto T(k^n)\\]\n\tis an equivalence of categories with quasi-inverse \n\t\\[M\\mapsto\\Gamma^{d,n}\\otimes_{S(n,d)}M\\]\n\twhere $\\Gamma^{d,n}=\\Gamma^d\\circ\\Hom_k(k^n,-)$ (c.f. \\ref{defn:div-powers} below).\n\\end{thm}\n\nThe important idea in this proof is that, for any polynomial functor $T$ and any finite-dimensional $V,W\\in\\Vectk$,\nwe get \n\\begin{align*}T_{VW}&\\in\\Hom(T(V),T(W))\\otimes S^d(\\Hom(V,W)^\\vee)\\\\\n\t&\\cong\\Hom(S^d(\\Hom(V,W)^\\vee)^\\vee,\\Hom(T(V),T(W)))\\\\\n\t&\\cong\\Hom(S^d(\\Hom(V,W)^\\vee)^\\vee\\otimes T(V),T(W))\n\\end{align*}\nand by using that $\\Gamma^d(X)\\cong S^d(X^\\vee)^\\vee\\eqdef (S^d)^\\sharp(X)$ and letting $V=W=k^n$, we can identify a canonical map \n\\[T_{k^n\\,k^n}:\\Gamma^d(\\End(k^n))\\otimes T(k^n)\\to T(k^n)\\]\nwhich gives us an action of $\\Gamma^d(\\End(k^n))$ on $T(k^n)$ and one can see without too much trouble that \n\\[\\Gamma^d(\\End(k^n))\\cong S(n,d).\\]\nThe rest of the proof is showing that these maps do what we want them to do.\n\n\\subsection{Strict polynomial functors... again}\nJust when you thought you had enough categories to consider, Krause developed a new category that more succinctly captures\nthe stucture of homogeneous degree $d$ polynomial maps: there the author changes the domain of these functors \nto encode the desired properties into the functors, rather than take a subcategory of objects satisfying a condition (which \nis inherently more difficult to work with).\n\\begin{defn}\\label{defn:div-powers}\n\tWhen $k$ is any commutative ring, one can define the category $P_k\\subseteq \\lmod{k}$ as the full subcategory of finitely-generated projective $k$-modules.\n\tIn this paper, we require that $k$ is an infinite field. In this case, $P_k=\\Vect_k$, but we use the former notation so that \n\tit aligns more closely with Krause's work.\n\n\tDefine $\\Gamma^d P_k$ to be the category of \\textbf{divided powers}---the objects are the same as those of $P_k$, but such that \n\t\\[\\Hom_{\\Gamma^dP_k}(V,W)=\\Gamma^d\\Hom_{P_k}(V,W)\\]\n\twhere $\\Gamma^d X=(X^{\\otimes d})^{\\frakS_d}$ denotes the \\textbf{$d^{\\text{th}}$} divided powers of the vector space $X$.\n\n\tFinally, as a matter of notation, let \n\t\\[\\Rep\\Gamma^d_k=\\Rep\\Gamma^dP_k=\\Func(\\Gamma^dP_k,\\lmod k)\\]\n\twhich we (suggestively) call the \\textbf{category of homogeneous degree $d$ strict polynomial functors.}\n\\end{defn}\n\\begin{rmk}\\label{rmk:action}\n\tOf course since $P_k=\\Vectk$, an element\n\t\\[T\\in\\Rep\\Gamma^d_k=\\Func(\\Gamma^d\\Vectk,\\Vectk),\\]\n\tis a functor that, on objects, is a map $\\Vectk\\to \\Vectk$ and on morphisms is of the form \n\t\\[T_{VW}:\\Hom_{\\Gamma^d\\Vectk}(V,W)=\\Gamma^d\\Hom_k(V,W)\\to \\Hom_k(T(V),T(W))\\]\n\twhich, leveraging $\\otimes$-$\\Hom$ adjunction, gives us a map \n\t\\[\\Gamma^d(V,W)\\otimes T(V)\\to T(W)\\]\n\tjust as we got in the discussion following thm.~\\ref{thm:FS-equiv}.\n\\end{rmk}\nUsing the idea in the last remark, Krause proves that there is another equivalence of categories:\n\\begin{thm}[{\\cite[Thm. 2.10]{krause-strict-poly-func}}]\n\tLet $d,n$ be positive integers. Then evaluation at $k^n$ induces a functor \n\t\\[\\Rep\\Gamma^d_k\\to \\lmod{S(n,d)}\\]\n\twhich is an equivalence of categories when $n\\ge d$.\n\\end{thm}\nThe key idea of this proof is to restrict attention to small projective generators of $\\Rep\\Gamma^d_k$. A class of these \nare the weight spaces $\\Gamma^\\lambda$ of the object $\\Gamma^{d,k^n}$. Then it just remains to see that \n\\[\\End_{\\Gamma^d_k}(\\Gamma^{d,k^n})\\cong S_k(n,d)\\]\nand the result follows.\t\n\\subsection{The monoidal structure on \\texorpdfstring{$\\Rep\\Gamma^d_k$}{Rep Gdk}}\nOne of the upshots of Krause's reformulation of strict polynomial functors is that it admits a more obvious monoidal \nstructure. His construction of the tensor product on $\\Rep\\Gamma_k^d$ takes the following tack: notice that the Yoneda embedding \nis a map \n\\[y:(\\Gamma^dP_k)\\op\\to \\Rep\\Gamma^d_k\\]\nsending each object $V\\mapsto \\Hom_{\\Gamma^dP_k}(V,-)$. Furthermore, the embedding $y$ is dense!\n\\begin{lem}\\label{lem:yoneda-dense}\n\tGiven a small category $\\calC$, let $y$ be the Yoneda embedding \n\t\\[y:(\\calC)\\to \\Func(\\calC\\op,\\Set)=\\PreSh(\\calC).\\]\n\tThen every element in $\\PreSh(\\calC)$ is (in a canonical way) a colimit of elements in the image of $y$. That is, for some collection of $C_i\\in \\calC$,\n\t\\[X=\\colim_{\\longrightarrow i}y(C_i)\\]\n\\end{lem}\nTo prove this lemma, let us remind you of the construction called the \\textbf{category of elements} of a functor $\\calF:\\calC\\op\\to \\Set$. It elements are \npairs $(C,x)$ where $C\\in\\calC$ and $x\\in \\calF(C)$ is a point. \n\nMorphisms between two objects\n\\[f:(C,x)\\to (C',y)\\]\nare honest morphisms $f:C\\to C'$ in $\\calC$ such that the set morphism\n\\[\\calF(f):\\calF(C')\\to \\calF(C)\\]\nhas the property that \n\\[\\calF(f)(y)=x.\\]\nThis category gives us a way to work with elements of a category ``locally'' even if the category $\\calC$ \nis not concrete.\n\n\\begin{prf}[of \\ref{lem:yoneda-dense}]\n\tThe setup (but not the details) for following proof comes from one in \\textit{Sheaves in Geometry and Logic} \\cite[41-43]{maclane-moerdijk}. \n\t\n\tDefine the functor\n\t\\[R:\\PreSh(\\calC)\\to \\PreSh(\\calC)\\quad\\text{via}\\quad E\\mapsto \\Hom_{\\hat\\calC}(y(-),E).\\]\n\tDefine also the opposing functor \n\t\\[L:\\PreSh(\\calC)\\to \\PreSh(\\calC)\\quad\\text{via}\\quad F\\mapsto \\colim \\calD_F\\]\n\twhere $\\calD_F$ is the diagram  \n\t\\[\\int_\\calC F\\xrightarrow{\\pi_\\calC}\\calC\\xrightarrow{y}\\hat\\calC\\]\n\t(this is makes sense since $\\Set$ is cocomplete).\n\n\tNow we claim that $L\\ladjointto R$ are a pair of adjoint functors. To prove this, it suffices to show that\n\t\\[\\Hom_{\\PreSh(\\calC)}(F,R(E))\\cong \\Hom_{\\PreSh(\\calC)}(L(F),E)\\]\n\tfor all $F,E\\in\\PreSh(\\calC)$.\n\n\tBut notice that maps from the colimit of a diagram to $E$ are in bijection with cones under the diagram (i.e. cocones)\n\twith nadir $E$ by the universal property of colimits! So \n\t\\[\\Hom(L(F),E)=\\Hom(\\colim\\calD_F,E)=\\operatorname{cocone}(\\calD_F,E)\\]\n\twhere an element of $\\operatorname{cocone}(\\calD_F,E)$ is a collection of maps $(\\varphi_{(C,x)})_{(C,x)\\in\\int_\\calC F}$\n\tsuch that for all morphisms $\\alpha:(C',x')\\to (C,x)$ in $\\int_\\calC F$, the following diagram commutes \n\t\\begin{center}\n\t\t\\begin{tikzcd}\n\t\t\t\\calD_F(C,x)\\ar[rr,\"\\calD_F(\\alpha)\"]\\ar[swap,dr,\"\\varphi_{(C,x)}\"] & &\\calD_F(C',y)\\ar[dl,\"\\varphi_{(C',y)}\"]\\\\\n\t\t\t& E &\n\t\t\\end{tikzcd}\n\t\\end{center}\n\tUsing these maps, we can construct a natural transformation $\\eta:F\\to \\Hom(y(-),E)$\n\tin the following way: for each $C\\in\\calC$, let \n\t\\[\\eta_C:F(C)\\to \\Hom(y(C),E)\\quad\\text{such that}\\quad \\eta_C(x)=\\varphi_{(C,x)}\\in\\Hom(y(C),E).\\]\n\tThis assembles to an honest natural transformation since for each $C,C'\\in\\calC$, and morphism $f:C\\to C'$, we have a diagram\n\t\\begin{center}\n\t\t\\begin{tikzcd}\n\t\t\tF(C)\\ar[r,\"x\\mapsto \\varphi_{(C,x)}\"] & \\Hom(y(C),E)\\\\\n\t\t\tF(C')\\ar[u,\"F(f)\"]\\ar[r,\"x'\\mapsto \\varphi_{(C',x')}\",swap] & \\Hom(y(C'),E)\\ar[u,\"{\\Hom(y(f),E)}\",swap]\n\t\t\\end{tikzcd}\n\t\\end{center}\n\twhich commutes since (by the commutativity of the colimit diagram above),\n\t\\[\\varphi_{(C,x)}=\\varphi_{(C',x')}\\circ\\Hom(-,\\alpha|_C)\\]\n\twhere $\\alpha|_C:C\\to C'$ denotes the underlying map in $\\calC$ (instead of in $\\int_\\calC F$). Then fixing\n\t$x'\\in F(C')$---and therefore $x=F(f)(x')\\in F(C)$---we can see that naturality of $\\eta$ means that \n\t\\[\\Hom(y(f),E)\\circ\\eta_{C'}(x')=\\Hom(y(f),E)(\\varphi_{(C',x')})=\\varphi_{(C',x')}\\circ y(f)\\]\n\tand (continuing in the other direction)\n\t\\[\\eta_C\\circ F(f)(x')=\\varphi_{(C,x)}\\]\n\tmust be the same. But in this case the map $f:C\\to C'$ lifts to a map $\\hat f:(C',x')\\to (C,x)$ in $\\int_\\calC F$,\n\tand $\\hat f|_{C}=f$ we get that the equality of these two expressions is precisely the compatibility condition of the \n\tstructural morphisms of the cocone.\n\n\tThus we have showed that there is a well-defined map\n\t\\[\\Psi_{E,F}:\\operatorname{cocone}(\\calD_F,E)\\to\\Hom(F,R(E))\\]\n\tsince a natural transformation is defined by its structural maps and a cocone by its legs, this map is injective.\n\tIt is surjective because for every $\\eta:F\\to R(E)$, we can define legs for a cocone:\n\t\\[\\varphi_{(C,x)}=\\eta_C(x)\\in\\Hom(y(C),E)=\\Hom(\\calD_F(C,x),E).\\]\n\t\n\tNext, we aim to show is natural in $F$ and $E$. If $\\epsilon:E\\to E'$ is a morphism, we have the diagram\n\t\\begin{center}\n\t\t\\begin{tikzcd}\n\t\t\t\\operatorname{cocone}(\\calD_F,E)\\ar[d,swap,\"(\\varphi_a)\\mapsto(\\epsilon\\circ\\varphi_a)\"]\\ar[r,\"\\Psi_{E.F}\"] &\\Hom(F,R(E))\\ar[d,\"{\\Hom(F,R(\\epsilon))}\"] \\\\\n\t\t\t\\operatorname{cocone}(\\calD_F,E')\\ar[r,swap,\"\\Psi_{E',F}\"] & \\Hom(F,R(E'))\n\t\t\\end{tikzcd}\n\t\\end{center}\n\tBut tracing along the bottom left, a cocone $(\\varphi_a)_a$ under $\\calD_F$ with nadir $E$ maps to the cocone $(\\epsilon\\circ\\varphi_a)_a$\n\twith nadir $E'$. Under the map $\\Psi_{E',F}$ just defined, this has as its image the natural transformation \n\t\\[\\eta:F\\to \\Hom(-,E')\\quad\\text{via}\\quad \\eta_{C}(x)=\\varphi_{(C,x)}\\circ\\epsilon\\in\\Hom(C,E')\\]\n\n\tProceeding along the top right, the same cocone with nadir $E$ is mapped to the natural transformation \n\t\\[\\hat\\eta:F\\to \\Hom(-,E)\\quad\\text{via}\\quad \\hat\\eta_{C}(x)=\\varphi_{(C,x)}\\in\\Hom(C,E)\\]\n\twhich is then mapped to $\\varphi_{(C,x)}\\circ\\epsilon\\in\\Hom(C,E')$. This gives us naturality in $E$.\n\n\tTo show naturality in $F$, let $\\beta:F\\to F'$ be a natural map between presheaves. Then this induces a map \n\t\\[\\int_\\calC\\beta:\\int_\\calC F\\to\\int_\\calC F'\\quad\\text{via}\\quad (C,x)\\mapsto (C,\\beta_C(x))\\]\n\twhich, in turn, induces a map between diagrams \n\t\\[\\calD_\\beta:\\calD_{F'}\\to \\calD_{F}\\]\n\twhere, on points, this is the map (if $x\\in F(C)$)\n\t\\[\\left(\\calD_\\beta(\\calD_{F'})\\right)_C(C,x)=(\\calD_{F'})_C(C,\\beta_C(x))\\]\n\twhich, in turn, induces the map \n\t\\[\\hat\\beta:\\operatorname{cocone}(\\calD_{F'},E)\\to \\operatorname{cocone}(\\calD_{F},E)\\]\n\tsuch that, if $(\\varphi_{(C,x)})_{\\int_\\calC F'}$ is a cone under $\\calD_{F'}$ with nadir $E$, \n\tthe image $\\rho=\\hat\\beta(\\varphi_{(C,x)})$ is such that \n\t\\[\\rho_{(C,x)}=\\varphi_{(C,\\beta_C(x))}.\\]\n\n\tSo naturality in $F$ is equivalent to the commutivity of \n\t\\begin{center}\n\t\t\\begin{tikzcd}\n\t\t\t\\operatorname{cocone}(\\calD_F,E)\\ar[r,\"\\Psi_{E,F}\"] & \\Hom(F, R(E))\\\\\n\t\t\t\\operatorname{cocone}(\\calD_{F'},E)\\ar[u,\"\\hat\\beta\"]\\ar[swap,r,\"\\Psi_{E,F'}\"] & \\Hom(F',R(E))\\ar[u,\"{\\Hom(\\beta,R(E))}\",swap]\n\t\t\\end{tikzcd}\n\t\\end{center}\n\twhich follows from the statement that the two natural transformations below take the same values:\n\t\\[\\left(\\Psi_{E,F}\\circ\\hat\\beta(\\varphi_{\\alpha})\\right)_C(x)=\\varphi_{(C,\\beta_C(x))}\\]\n\tand\n\t\\[\\left(\\Hom(\\beta,R(E))\\circ\\Psi_{E,F'}(\\varphi_{\\alpha})\\right)_C(x)=(\\Psi_{E,F'}(\\varphi_{\\alpha})\\circ\\beta)_C(x)=(\\Psi_{E,F'}(\\varphi_{(C,x)}))_C(\\beta_C(x))=\\varphi_{(C,\\beta_C(x))}\\]\n\tThis completes the proof that $L\\ladjointto R$.\n\n\tBut by the Yoneda lemma, we know that \n\t\\[R(E)(C)=\\Hom(y(C),E)\\cong E(C)\\]\n\twhich implies that $R$ is naturally isomorphic to $\\id_{\\PreSh(\\calC)}$. But adjoints, when they exist, \n\tare unique! Therefore $L\\simeq\\id_{\\PreSh(\\calC)}$, or in other words for all $F\\in\\PreSh(\\calC)$,\n\t\\[F=\\id_{\\PreSh(\\calC)}(F)\\simeq L(F)=\\colim D_F=\\colim_i \\Hom(-,C_i)\\]\n\tproving the result.\n\\end{prf}\n\nNotice that since \n\\[\\Hom_\\calC(-,X)=\\Hom_{\\calC\\op}(X,-)\\]\nwe can replace $\\calC$ with $\\calC\\op$ in the above argument and get that any functor in $\\Func(\\calC,\\Set)$ is a colimit \nof (covariant) representable functors of the form $\\Hom(C_i,-)$.\nThus \\textbf{all} the elements in our category $\\Rep \\Gamma^d_k$ can be written as a colimit of \nelements of the form \n\\[\\Gamma^{d,V}\\eqdef\\Hom_{\\Gamma^dP_k}(V,-)\\]\n\nLet $0\\to X\\to Y\\to Z\\to 0$ be an exact sequence of elements in $\\Rep\\Gamma^d_k$. Then by applying $\\Gamma^{d,V}$ and \napplying the Yoneda isomorphism $\\Hom(\\Gamma^{d,V},X)\\simeq X(V)$, we get that \n\\[0\\to X(V)\\to Y(V)\\to Z(V)\\to 0\\]\nis exact whence \n\\[0\\to \\Hom(\\Gamma^{d,V},X)\\to \\Hom(\\Gamma^{d,V},Y)\\to\\Hom(\\Gamma^{d,V},Z)\\to 0\\]\nis. This proves the fact that \n\\begin{lem}\n\tFor all $V\\in\\Gamma^dP_k$, $\\Gamma^{d,V}$ is a projective object.\n\\end{lem}\n\nFrom these reasonably simple objects, one defines (letting $\\Gamma^d_k=\\Rep\\Gamma^d_k$ in what follows)\n\\[\\Gamma^{d,V}\\otimes_{\\Gamma^d_k}\\Gamma^{d,W}\\eqdef\\Gamma^{d,V\\otimes W}\\]\nand leveraging the facts above, for each $Y\\in\\Gamma^dP_k$,\n\\[\\Gamma^{d,V}\\otimes_{\\Gamma^d_k} Y\\eqdef\\colim_{\\Gamma^{d,W}\\to Y}\\Gamma^{d,V\\otimes W}\\]\nand finally for each $X\\in \\Gamma^dP_k$,\n\\[X\\otimes_{\\Gamma^d_k} Y\\eqdef\\colim_{\\Gamma^{d,V}\\to X}\\Gamma^{d,V}\\otimes Y.\\]\n\nOne can similarly define internal hom:\n\\[\\iHom_{\\Gamma^d_k}(X,Y)\\eqdef \\lim_{\\Gamma^{d,V}\\to X}\\colim_{\\Gamma^{d,W}\\to Y}\\Gamma^{d,\\Hom(V,W)}\\]\nwhich in \\cite[prop 2.4]{krause-strict-poly-func} is shown to satisfy the usual adjunction:\n\\begin{prop}[Krause]\n\tIf $X,Y,Z\\in\\Gamma^dP_k$, \n\t\\[\\Hom_{\\Gamma^d_k}(X\\otimes_{\\Gamma^d_k} Y,Z)\\cong\\Hom_{\\Gamma^d_k}(X,\\iHom_{\\Gamma^d_k}(Y,Z))\\]\n\\end{prop}\n\\subsection{Monoidicity of the Schur-Weyl functor \\texorpdfstring{$\\calF$}{F}}\nIn \\cite{aquilino-reischuk}, the authors show that this is the ``correct'' monoidal structure. This is summed up \nin the primary result of their paper:\n\\begin{thm}[{\\cite[thm. 4.4]{aquilino-reischuk}}]\n\tThe functor \n\t\\[\\calF=\\Hom(\\Gamma^\\omega,-):\\Rep\\Gamma^d_k\\to \\lmod{k\\frakS_d}\\]\n\tpreserves the monoidal structure defined on strict polynomial functors, i.e.\n\t\\[\\calF(X\\otimes_{\\Gamma_k^d}Y)\\cong\\calF(X)\\otimes_k\\calF(Y)\\]\n\tfor all $X$ and $Y$ and if $\\1$ is the tensor unit, \n\t\\[\\calF(\\1_{\\Rep\\Gamma^d_k})=\\1_{k\\frakS_d}.\\]\n\\end{thm}\n\nThe key observation in their proof of this result is that strict polynomial functors can be computed \nas limits of representable presheaves where the representing objects are \\textit{free}. This is believable enough \nif we (as they do) allow $k$ to be any commutative ring. Since we are only interested in the case when $k$ is a field, however,\nwe have to make no such reduction.\n\nThen a combinatorial argument connecting weights in $\\Lambda(mn,d)$ to the collection of all matrices $A^\\lambda_\\mu$ with $\\lambda\\in\\Lambda(n,d)$ and $\\mu\\in\\Lambda(m,d)$ such that the $i^{th}$ column sums to $\\lambda_i$ and the \n$j^{th}$ row sums to $\\mu_j$. Then we observe that\n\\[\\Hom(\\Gamma^\\omega,\\Gamma^{d,n}\\otimes\\Gamma^{d_m})\\cong\\bigoplus_{\\lambda\\in\\Lambda(n,d),\\,\\mu\\in\\Lambda(m,d)}\\bigoplus_{A\\in A^\\lambda_\\mu}\\Hom(\\Gamma^\\omega,\\Gamma^A)=\\bigoplus_{\\lambda,\\mu}\\bigoplus_A{^\\lambda M}\\]\nand by a decomposition result (their lemma 3.1), then have that \n\\[\\bigoplus_A {^\\lambda M}\\cong{^\\lambda M}\\otimes_k{^\\mu M}\\]\nwhich is the crucial step in separating into a tensor product of $\\frakS_d$ modules.\n\n%I like this idea. I will try to do it, if time allows.\n%\\subsection{A dictionary}\n%{\\color{red} Spell out how one can translate between the three different categories: irreducibles and tensor structure.}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\newpage\n\\section{Tensor products in the derived category \\texorpdfstring{$\\Db(S(n,r))$}{DbS(n,r)}}\n(Co)homology is a powerful tool in analyzing the composition of objects and their actions. This is evidenced \nby the sheer number of cohomology theories that are in use across many different fields. Homological computations are, \nin their nature, lossy---one is reducing the object to its signature and then we play the game of gleaning what we can \nfrom the structure that remains. \n\nIt is a well-known fact of homological algebra that the cohomology of an $R$-module is independent of \nresolution by projective objects. Because of this fact, if we are interested in the homological properties of modules over a ring $R$,\nit isn't useful to look at the (abelian) category $\\lmod R$, but rather its ``homologically-distilled'' analog,\n$\\D(R)$. Throughout this section we will be relying on Weibel \\cite{weibel} and his discussion on chain, homotopy, and derived categories.\n\n\\subsection{Derived categories}\nIn what follows, let $\\calA$ denote any abelian category. If it helps, the reader can relatively safely assume that $\\calA$ is $\\lmod R$, the category \nof (left) $R$-modules.\\footnote{That one can do this is the subject of the \\textit{Freyd-Mitchell embedding theorem}, which tells us that any small Abelian category\ncan be embedded faithfully in $\\lmod R$ for some ring $R$. Even if $\\calA$ isn't small (a set), one can study it via this embedding by \nrestricting attention to small abelian subcategories.} Denote by $\\Ch(\\calA)$ (or $\\Ch(R)$ when $\\calA=\\lmod R$) the category of chain complexes $(C_\\bullet,\\partial)$\nsuch that each $C_i\\in\\calA$ and $\\partial\\circ\\partial=0$. Let $\\Chb(\\calA)$ denote the full subcategory of $\\Ch(\\calA)$ consisting of the \ncomplexes that are bounded---that is, $C_i=0$ for all $i>N$ and $i<M$ for some $N,M$.\n\nRecall that a chain complex morphism\\footnote{A morphism that commutes with the differential.} $f_\\bullet:C_\\bullet\\to D_\\bullet$ is a \\textbf{chain nullhomotopic} in $\\Ch(\\calA)$ if\nthere exist maps $\\sigma_i:C_i\\to D_{i+1}$ such that we have following (non-commuting) diagram:\n\\begin{figure}[h]\n\t\\centering\n\t\\begin{tikzcd}\n\t\t\\cdots\\ar[r,\"\\partial\"] &C_{n+1}\\ar[d,\"f_{n+1}\",swap]\\ar[r,\"\\partial\"] & C_n\\ar[dl,\"\\sigma_n\"]\\ar[r,\"\\partial\"]\\ar[d,\"f_n\"] & C_{n-1}\\ar[dl,\"\\sigma_{n-1}\"]\\ar[d,\"f_{n-1}\"]\\ar[r,\"\\partial\"] & \\cdots\\\\\n\t\t\\cdots\\ar[r,\"\\partial\",swap] &D_{n+1}\\ar[r,\"\\partial\",swap] & D_n\\ar[r,\"\\partial\",swap] & D_{n-1}\\ar[r,\"\\partial\",swap] & \\cdots\n\t\\end{tikzcd}\n\\end{figure}\n\n\\noindent with the condition that (for all $n$)\n\\[f_n=\\partial\\circ\\sigma_n+\\sigma_{n-1}\\circ \\partial.\\]\n\\begin{defn}\n\tTwo chain maps $f,g:C_\\bullet\\to D_\\bullet$ in $\\Ch(\\calA)$ are said to be \\textbf{chain homotopic} if their difference is chain nullhomotopic. That is, if \n\tthere exists maps $\\sigma_i:C_i\\to D_{i+1}$ such that \n\t\\[f_n-g_n=\\partial\\circ\\sigma_n+\\sigma_{n-1}\\circ\\partial.\\]\n\\end{defn}\n\nA well-known lemma is the following:\n\\begin{lem}\n\tIf $f$ and $g$ are chain homotopic maps, then they induce the same maps on (co)homology.\n\\end{lem}\n\nChain homotopies play the role of \\textbf{homotopy equivalences} (keeping in mind the example of topological spaces with simplicial homology for intuition) and \nthe fact we have nontrivial homotopy equivalences is the first indication that we aren't in the right category to study homology. A natural thing to do, then, is to \nattempt to pass to a category where we identify equivalent morphisms.\n\n\\begin{defn}\n\tGiven the category $\\Ch(\\calA)$, we define the \\textbf{homotopy category} $\\K(\\calA)$ to be the category whose objects are the \n\tsame as those in $\\Ch(\\calA)$ and whose morphisms between any two chains $C_\\bullet$ and $D_\\bullet$ are \n\t\\[\\Hom_{\\K(\\calA)}(C_\\bullet,D_\\bullet)\\eqdef \\Hom_{\\Ch(\\calA)}(C_\\bullet,D_\\bullet)/H\\]\n\twhere $H$ consists of all chain nullhomotopic maps from $C_\\bullet$ to $D_\\bullet$.\n\\end{defn}\n\n\\begin{rmk}\n\tWe can analogously define the category $\\K^\\text{b}(\\calA)$ that is formed through the \n\tsame process after first restricting to the subcategory $\\Chb(\\calA)$ of bounded chain complexes.\n\\end{rmk}\n\nThe upshot here is that we are now closer to our (until now only implicit) goal: to find a category that captures the information \nin $\\Ch(\\calA)$ \\textit{up to quasi-isomorphism.} One can show that, however, that in general there are quasi-isomoprhisms that are not \nhomotopic to the identity map! So our job is only partially complete. \n\nA result of great importance to reaching our goal is that $\\K(\\calA)$ is \\textit{triangulated} with distinguished triangles given by the mapping cones \n\\[A\\xrightarrow{u} B\\to \\cone(u)\\to A[1]\\]\nand all triangles equivalent to them\\footnote{We say a triangle $X\\to Y\\to Z\\to X[1]$ is equivalent to a mapping cone if $X,Y,Z\\in\\K(\\calA)$ and there exists isomorphisms (equivalently, homotopy equivalences when considered as maps in $\\Ch(\\calA)$)\n$f,g,h$ such that the diagram in fig.~\\ref{fig:tri-equiv} commutes (for some $A,B$ and $u$):\n}\n\\begin{figure}\n\t\\centering\n\t\\begin{tikzcd}\n\t\tX\\ar[r]\\ar[d,\"f\"] & Y\\ar[r]\\ar[d,\"g\"] & Z\\ar[r]\\ar[d,\"h\"] & X[1]\\ar[d,\"{f[1]}\"]\\\\\n\t\tA\\ar[r,\"u\"] & B\\ar[r] & \\cone(u)\\ar[r] & A[1]\n\t\\end{tikzcd}\n\t\\caption{Equivalence of triangles in $\\K(\\calA)$}\n\t\\label{fig:tri-equiv}\n\\end{figure}\n\nThe importance of triangluated categories cannot be understated (it is critical, e.g. in the construction of the Balmer spectrum in sec.~\\ref{sec:ttc}). Many people, including \nVerdier (\\cite{verdier-thesis}), and Neeman (\\cite{neeman-duality}, \\cite{neeman-book}) have put considerable time and effort into developing a \nframework within the context of triangulated categories to enable examination and manipulation. One of the tools \nthat we will now use is \\textit{Verdier localization}. It closesly mirrors the idea of localization of a ring at a multiplicative \nsubset (a parallel that will be extended further in the following section).\n\n\\begin{defn}\n\tGiven a triangulated category $\\calT$, a \\textbf{multiplicative system} $S$ in $\\calT$ is a collection of morphisms \n\tin $\\calT$ satisfying the following properties:\n\t\\begin{itemize}\n\t\t\\item If $s,s'\\in S$, so are $s\\circ s'$ and $s'\\circ s$ (whenever either of these make sense).\n\t\t\\item $\\id_X\\in S$ for all $X\\in\\calT$\n\t\t\\item (\\textbf{Ore condition}) If $t\\in S$ with $t:Z\\to Y$ then for every $g:X\\to Y$ there are maps $f$ and $s$ (with $s\\in S$) such that the diagram in figure \\ref{fig:fractions} commutes. The symmetric statement also holds.\n\t\t\\item (\\textbf{Cancellation}) If $f,g:X\\to Y$ are two morphisms, then there is an $s\\in S$ with $sf=sg$ if and only if there is a $t\\in S$ with $ft=gt$.\n\t\\end{itemize}\n\\end{defn}\n\\begin{figure}\n\t\\centering\n\t\\begin{tikzcd}\n\t\tW\\ar[d,\"s\"]\\ar[r,\"f\"] & Z\\ar[d,\"t\"]\\\\\n\t\tX\\ar[r,\"g\"] & Y\n\t\\end{tikzcd}\n\t\\caption{Ore condition in a multiplicative system}\n\t\\label{fig:fractions}\n\\end{figure}\n\\begin{rmk}\n\tUnder the foresight we will eventually be inverting the elements in $S$, the Ore condition translates into the following idea: for all $g:X\\to Y$ and $t:Z\\to Y$ in $S$,\n\t\\[t^{-1}g=fs^{-1}\\]\n\tfor some maps $s\\in S$ and $f$. This fixes the inherent noncommutativity of function composition.\n\\end{rmk}\n\\subsubsection{The calculus of fractions}\nWe can finally construct the Verdier localization of $\\K(\\calA)$ using a generalization of the calculus of \nfractions in localization of a ring. We will call a diagram of the form \n\\[fs^{-1}:X\\xleftarrow{s} X_1\\xrightarrow{f} Y\\]\nwhere $s\\in S$ a \\textbf{fraction} and say that two fractions $fs^{-1}$ and $gt^{-1}$ are equivalent if there exists an element $X_3$ fitting \ninto the commutative diagram below:\n\\begin{center}\n\t\\begin{tikzcd}\n\t\t& X_1\\ar[dl,swap,\"s\"]\\ar[dr,\"f\"] &\\\\\n\t\tX & X_3\\ar[u]\\ar[l]\\ar[r]\\ar[d] & Y\\\\\n\t\t& X_2\\ar[ul,\"t\"]\\ar[ur,\"g\",swap] &\n\t\\end{tikzcd}\n\\end{center}\n\nThen from this we can define\n\\begin{defn}\n\tLet $\\calT$ be a triangulated category and $S$ be a multiplicative system for $\\calT$. Then the \\textbf{Verdier localization of $\\calT$ at $S$}, \n\t$\\calT[S^{-1}]$ is a category whose objects are the same as those of $\\calT$ and whose morphisms are equivalence classes of \n\tfractions of maps, as defined above.\n\\end{defn}\n\nFrom this more general framework, we can very simply define the \\textbf{derived category of an abelian category $\\calA$}\nto be \n\\[\\D(\\calA)=\\K(\\calA)[W^{-1}]\\]\nwhere $W$ is the collection of weak homotopy equivalences (quasi-isomorphisms). For our purposes, it will suffice \nto restrict to the full triangulated subcategory $\\K^\\text{b}(\\calA)$, giving us the \\textbf{bounded derived category}\n\\[\\Db(\\calA)=\\K^\\text{b}(\\calA)[W^{-1}].\\]\n\n\\subsubsection{Tensor products in \\texorpdfstring{$\\Db(R)$}{Db(R)}}\nIn the context of $R$ (where $R$ is a $k$ algebra) modules, there is a tensor bifunctor \n\\[-\\otimes_R-:\\rmod R\\times\\lmod R\\to \\Vectk\\]\nand since it is right exact, but not exact, we can take the left derived functor\n\\[-\\otimes_R^\\mathbf{L}-\\eqdef \\L(-\\otimes_R-):\\D(\\rmod R)\\times\\D(\\lmod R)\\to\\D(\\Vectk)\\]\nwhich we call \\textbf{the derived tensor product}. This can defined via a Kan extension:\n\\begin{defn}\n\tLet $\\calF:\\calA\\to \\calB$ be an additive functor between abelian categories. Then since $\\calF$ preserves \n\tchain homotopies, it descends to a functor $\\K\\calF:\\K(\\calA)\\to \\K(\\calB)$. \n\t\n\tWe define the \\textbf{right derived functor} (if it exists) to be a functor $\\R\\calF:\\D(\\calA)\\to\\D(\\calB)$ along with a natural transformation $\\xi:q\\circ\\K\\calF\\to \\R\\calF\\circ q$ such that\n\tfor any $\\calG:\\D(\\calA)\\to \\D(\\calB)$ and $\\zeta:q\\circ\\K\\calF\\Rightarrow \\calG\\circ q$\n\tfitting into the diagram \n\t\\begin{center}\n\t\t\\begin{tikzcd}[row sep=large]\n\t\t\t\\K(\\calA)\\ar[r,\"\\K\\calF\"]\\ar[dr,\"q\",swap] & \\K(\\calB)\\ar[r,\"q\"]\\ar[d,\"\\zeta\",Rightarrow] & \\D(\\calB)\\\\\n\t\t\t& \\D(\\calA)\\ar[ur,bend right=45,\"\\R\\calF\",swap]\\ar[phantom,bend right=45,ur,\"\"{name=RF}]\\ar[ur,\"\\calG\"]\\ar[phantom,ur,\"\"{name=G,below}] & \\arrow[from=RF,to=G,Rightarrow,\"\\eta\"]\n\t\t\\end{tikzcd}\n\t\\end{center}\n\tthere exists \n\ta unique $\\eta:\\R\\calF\\Rightarrow \\calG$ such that $\\eta q\\circ \\xi=\\zeta$.\n\tIn other words, \n\t\n\t\\begin{center}\n\t\t$\\R\\calF$ is the \\textit{right Kan extension of $q\\circ\\K\\calF$ along the localization map $q$.}\n\t\\end{center}\n\tSimilarly, the left derived functor $\\L\\calF$ can be defined as the left Kan extension of $q\\circ\\K\\calF$ along $q$,\n\tsatisfying the same universal property with the natural transformations reversed.\n\\end{defn}\n\nThis gives us a property characterizing the functor, but in practice one usually computes this via resolutions. In the simplest case, let $M,N\\in\\calA$ for some abelian monoidal category $\\calA$. Then \n\\[M[0]\\otimes^\\mathbf{L}_R N[0]=F_\\bullet\\otimes G_\\bullet\\]\nwhere $F_\\bullet$ and $G_\\bullet$ are chain complexes quasi-isomorphic to $M[0]$ and $N[0]$, respectively (e.g. flat resolutions).\n\n%\\subsection{Compatibility of monoidal structures}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\newpage\n\\section{The (Balmer) spectrum of a tensor triangulated category}\\label{sec:ttc}\nIn Paul Balmer's 2005 paper \\cite{balmer-spc}, he developed a general framework for understanding the structure of certain \nkinds of categories that arose from the original constructions in algebraic geometry. Serving as a source of inspiration for Balmer, in \\cite{friedlander-pevtsova-pi} Friedlander and Pevtsova proved\nthat the projective geometry of the cohomology ring of a finite group scheme can be recovered by looking at ``ideals'' in the category $\\stmod G$ \nof stable $G$ modules.\n\nUsing this as a springboard, Balmer ported the definitions of ideals and prime ideals to tensor-triangulated categories (see below)\nand proved a broader result that gives some tools for better analyzing familes of representaitons of finite groups (among other things).\n\\subsection{Some motivation and a definition}\nLet $\\calC$ be a symmetric monoidal (i.e. tensor) category with tensor product $\\otimes$ and unit object $\\1$. After giving some \nthought to the matter, one realizes that a ring is given by putting a ``compatible'' monoidal structure on top of an abelian group,\nand to that end, one may consider the case when $\\calC$ is also additive. \n\nThis perspective gives us an interesting analogy between (unital, commutative) rings in algebra and category theory. Since every \ntriangulated category is also additive, we can further specify that $\\calC$ be triangulated:\n\\begin{defn}\n\tA \\textbf{tensor-triangulated} category $\\calC$ is both a symmetric moniodal category and a triangulated category such that \n\tthe monoidal structure preserves the triangluated structure. \n\n\tAs a reminder, such a category is equipped with a tensor product $-\\otimes -:\\calC\\times\\calC\\to \\calC$ and unit object $\\1$, along with\n\ta collecton distinguished triangles $\\calT$ comprised of objects in $\\calC$ and shift functor (an auto-equivalence) $(-)[1]:\\calC\\to \\calC$ such that:\n\t$-\\otimes-$ is a triangulated (or exact) functor in each entry (it takes $\\calT$ to itself).\n\\end{defn}\n\n\\subsubsection{Aside: Why triangulation?}\nIn the construction of the spectrum, we will see that the triangulated structure isn't explicitly necessary. It appears that \none only needs a symmetric (or not!) monoidal category with all sums (at least if we are just relying on analogy to rings). A question, \nwhich may not have an answer yet (fully or in part) is whether changing these requirements significantly changes things. For instance, \nwhat happens when one tries to compute the spectrum of the abelian (symmetric monoidal) category $\\Rep G$?\n\n\\subsection{Construction of the spectrum}\nOnce the appropriate context is identified (which is the real ingenuity of Balmer's paper), the construction \nvery closely mirrors the construction seen in elementary algebraic geometry:\n\\begin{defn}\n\tLet $\\calC$ be a tensor-triangulated category (TTC). Then a \\textbf{(thick tensor) ideal} $I\\subseteq \\calC$ is a full triangulated subcategory \n\twith the following conditons:\n\t\\begin{itemize}\n\t\t\\item \\textit{(2-of-3 rule/Triangulation)} If $A,B,$ and $C\\in\\calC$ are objects that fit into a distinguished triangle\n\t\t\\[A\\to B\\to C\\to A[1]\\]\n\t\tin $\\calC$, and if any two of the three are objects in $I$, then so is the third.\n\t\t\\item \\textit{(Thickness)} If $A\\in I$ is an object that splits as $A\\cong B\\oplus C$ in $\\calC$, then both $B$ and $C$ belong to $I$.\n\t\t\\item \\textit{(Tensor Ideal)} If $A\\in I$ and $B\\in \\calC$ then $A\\otimes B=B\\otimes A\\in I$.\n\t\\end{itemize}\n\\end{defn}\n\n\\begin{rmk}\n\tThe first condition just ensures that our ideals respect the triangulated structure (and thus stability) in the parent category $\\calC$. \n\tThe final condition is the most direct analog of an ideal and is central in the analogy between this theory and classical AG.\n\\end{rmk}\nFrom here the rest of the picture is relatively straightforward:\n\\begin{defn}\n\tLet $\\calC$ be a TTC as before. Then an ideal $I\\subseteq\\calC$ is called a \\textbf{prime ideal}\n\tif, whenever $A\\otimes B\\in I$ for some $A,B\\in \\calC$, either $A$ or $B$ is in $I$.\n\n\tWe call the collection of all primes the \\textbf{spectrum} of $\\calC$ and write \n\t$\\operatorname{Spc}(\\calC)$.\n\\end{defn}\n\nHere the construction varies slightly from the traditional construction of $\\Spec$: we define \n\\[Z(S)\\eqdef\\{\\calP\\in\\Spc(\\calC)|S\\cap\\calP=\\varnothing\\}\\]\nand define sets (for any $S\\subseteq\\calC$ and $A\\in \\calC$):\n\\[U(S)\\eqdef \\Spc(\\calC)\\setminus Z(S)=\\{\\calP\\in\\Spc(\\calC)|S\\cap \\calP\\ne\\varnothing\\}\\]\nand\n\\[\\supp(A)\\eqdef Z(\\{A\\})=\\{\\calP\\in\\Spc\\calC|A\\notin \\calP\\}\\]\n\nA routine check of the axioms shows us\n\\begin{lem}[2.6 of \\cite{balmer-spc}]\n\tThe sets $U(S)$ for all $S\\subseteq\\calC$ form a basis for a topology on $\\Spc\\calC$.\n\\end{lem}\nwhich we call the \\textbf{Zariski topology}, giving $\\Spc\\calC$ the structure of a topological space.\n\n\\subsection{As a locally-ringed space}\nThe above discussion mentions how we can construct a topological space from the set of prime thick tensor ideals \nin a TTC, but there is even more we can get: the structure of a locally-ringed space. \n\nTo get this, we need to define the structure sheaf:\n\\begin{defn}\n\tLet $\\calC$ be a tensor-triangulated category and let $\\Spc\\calC$ be the construction discussed above. Then the structure sheaf on $\\Spc\\calC$ is given by the \n\tsheafification $\\O_\\calC$ of the presheaf \n\t\\[\\tilde\\O_\\calC:\\operatorname{Open}(\\Spc\\calC)\\op\\to \\Ring\\]\n\tgiven by \n\t\\[\\tilde\\O_\\calC(U)\\eqdef \\End_{\\calC/\\calC_Z}(\\1_U)\\]\n\twhere $U\\subseteq\\Spc\\calC$ is an open set and $\\calC_Z$ is the thick tensor ideal in $\\calC$ supported \n\ton $Z=\\Spc\\calC\\setminus U$. The ringed space $(\\Spc \\calC,\\O_\\calC)$ is denoted $\\Spec_\\text{Bal} \\calC$.\n\\end{defn}\n\n\\begin{rmk}\n\tThat $\\calC_Z$ is a thick tensor ideal requires some work, but it follows from work that Balmer does to \n\tdefine a support data $(X,\\sigma)$ on a tensor-triangulated category and showing that for any subset $Y\\subset X$ of \n\tits associated topological space, the following set \n\t\\[\\{A\\in\\calC|\\sigma(A)\\subseteq Y\\}\\]\n\tis a thick tensor ideal of $\\calC$ (c.f. lem.~3.4).\n\\end{rmk}\n\nBalmer emphasizes that this is the ``correct'' ringed space structure to put on $\\Spc\\calC$. To do so, one defines an abstract support datum:\n\\begin{defn}\n\tA \\textbf{support datum} for a TTC $\\calC$ is a pair \n\t\\[(X,\\sigma)\\]\n\twhere $X$ is a topological space and $\\sigma:\\calC\\to \\operatorname{closed}(X)$ is a map sending $a\\mapsto\\sigma_a$ such that \n\t\\begin{enumerate}\n\t\t\\item $\\sigma(0)=\\varnothing$ and $\\sigma(1)=X$,\n\t\t\\item $\\sigma(a\\oplus b)=\\sigma(a)\\cup\\sigma(b)$,\n\t\t\\item $\\sigma (a[1])=\\sigma(a)$,\n\t\t\\item $\\sigma(a)\\subseteq \\sigma(b)\\cup\\sigma(c)$ for any triangle $a\\to b\\to c\\to a[1]$,\n\t\t\\item $\\sigma(a\\otimes b)=\\sigma(a)\\cap\\sigma(b).$\n\t\\end{enumerate}\n\\end{defn}\nUsing this definition, Balmer shows \n\\begin{thm}[{\\cite[thm. 3.2]{balmer-spc}}]\n\t$(\\Spc\\calC,\\supp)$ is a support datum for $\\calC$ and furthermore this support datum is terminal in the category of \n\tsupport data for $\\calC$. That is, for any other $(X,\\sigma)$, there exists a unique continuous map $f:X\\to \\Spc\\calC$ such that \n\t\\[\\sigma(a)=f^{-1}(\\supp(a)).\\]\n\\end{thm}\n\nTo finish up the discussion of tensor-triangulated geometry, we state a couple of results originally proven in different contexts but used \nby Balmer to motivate the utility of this construction. In \\cite{thomason}, the author classifies the triangulated tensor subcategories \nof $\\Dperf(X)$, thereby defining the set $\\Spc\\Dperf(X)$. Applying Balmer's language and structure, he proved that \n\\begin{thm}[{\\cite[thm. 6.3(a)]{balmer-spc}}]\n\tIf $X$ is a topologically Noetherian scheme, then (as ringed spaces)\n\t\\[\\Spec_\\text{Bal}\\Dperf(X)\\simeq X.\\]\n\\end{thm}\n\nFurthermore another result from Friedlander and Pevtsova \\cite{friedlander-pevtsova-pi} showed (again using \nthe language of $\\Spec_\\text{Bal}$):\n\\begin{thm}[{\\cite[thm. 3.6]{friedlander-pevtsova-pi},\\cite[thm. 6.3(b)]{balmer-spc}}]\n\tLet $G$ be a finite group scheme over a field $k$. Then \n\t\\[\\Spec_\\text{Bal}(\\stmod(kG))\\simeq\\Proj(H^\\bullet(G,k))\\]\n\twhere, $\\stmod(kG)$ is the full subcategory of the stable module category consisting of the finitely generated modules and $H^\\bullet(G,k)=\\Ext_G^\\bullet(k,k)$ is the cohomology ring of $G$.\n\\end{thm}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\newpage\n\\section{Questions and extensions}\nThe following are some rough outlines of research programs that we can look into moving forward. They vary in depth and difficulty and the questions \nasked herein may not end up being the ones that are most interesting in these different areas. These do, however, provide a good starting place as we transition \ninto tackling new problems.\n\n\\subsection{Computing the spectrum of \\texorpdfstring{$\\Db(S(n,r))$}{DbS(n,r)}}\nWhen one is interested in understanding the representation theory of an object, one often runs into  the problem \nof algebras of ``wild'' representation type. These are the algebras whose isomorphism types of indecomposables are in \nbijection with those of $k\\langle x,y\\rangle$. It has been shown (accurding to \\cite{bensonI}) that the representation \ntheory of algebras $\\Lambda$ of wild type is \\textit{undecideable} in that there exists no algorithm for a Turing machine that can \ndecide the truth or falsehood of a statement about $\\Lambda$ modules. \n\nWhile that may seem like a dismal prospect, the (Balmer) spectrum of the derived category of Schur algebras \ngives us a little more hope. Recall that the spectrum is comprised of prime thick tensor ideals in $\\Db(S(n,r))$,\nwhich are triangulated subcategories that, among other properties, are closed under summands and extensions. This gives us a coarser \ngrouping of chains of $\\Lambda$-modules to work with, and (hopefully!) gives us a better chance at being able to understand \nthings better.\n\nA first step would be to compute $\\Db(S(n,r))$ in the ``nice'' case where our field is characteristic zero. From there, there are interesting computations to be done \nfor Schur algebras over fields of characteristic $p>0$ which could yield interesting results.\n\n\\subsection{The representation theory of \\texorpdfstring{$S(n,r)$}{S(n,r)} in positive characteristic}\nWhen we are working over an infinite field of characteristic zero, the theory of Schur algebra representations affords a relatively \nnice, clean description. However, as is pointed out in \\cite{erdmann}, the representation theory of Schur algebras in positive characteristic \ncan be fraught with troubles. For instance, $S(3,10)$ over a field of characteristic 5 has wild representation type.\n\nThat such troublesome algebras exist and are so readily accessible (the above example is spanned by 66 elements) indicates that there are\nan endless supply of computational examples that one could try to understand and that could eventually lead to questions and conjectures concerning \nthe nature of the representations of algebras of wild type.\n\n\\subsection{Representation theory of the \\texorpdfstring{$q$}{q}-Schur algebra}\nRecall a motiviating example (c.f. \\cite{majid}) of a quantum group: $\\operatorname{SL}_q(2)$, so named because it is a ``$q$-analog'' of the algebra\n$\\operatorname{SL}_2$. Fix some $q\\in k^\\times$. Then it is defined (as an algebra) as a quotient \n\\[k\\langle a,b,c,d\\rangle/R\\]\nwhere $R$ is the ideal generated by the following relations:\n\\[\\begin{array}{ccc}\n\tca=qac & ba=qab & db=qdb\\\\\n\tdc=qcd & bc=cb & da-ad=(q-q^{-1})bc\n\\end{array}\\]\nalong with the ``$q$-determinant relation''\n\\[ad-q^{-1}bc=1.\\]\nNotice that setting $q=1$ makes $a,b,c,$ and $d$ commute, so we are left with the usual special linear group.\n\nQuantum groups and, more generally, quantum deformations of objects in commutative algebra, give mathematicians \na way to carefully perturb objects to open up areas of research in noncommutative algebra to the the same (or similar) techniques \nused by commutative algebraists and algebraic geometers.\\footnote{See, for instance Taft and Towber's \\textit{Quantum deformation of flag schemes and Grassmann schemes. I. A q-deformation of the shape-algebra for GL(n)}\nor the second half of my notes on the Grassmannian at \\href{https://github.com/NicoCourts/Grassmannian-Notes/}{https://github.com/NicoCourts/Grassmannian-Notes/} where I summarize this paper.} \n\nThe $q$-Schur algebras were developed by Dipper and James and eventually summarized very nicely in \\cite{donkin-q-schur} in a manner that\nreflects the character of \\cite{green} and re-derives the classical results as a degenerate case of a more complex and \ninteresting interplay between quantum $\\GL_n$ and Iwahori-Hecke algebras.\n\nThese algebras (and even further generalizations) are still an area of active research. The question of identifying representation \ntypes of $q$-Schur algebras has been completed already by Erdmann and Nakano in \\cite{erdmann-nakano}, \nbut the other questions persist. In particular, one can ask questions like:\n\\begin{itemize}\n\t\\item What are explicit indecomposable representations and (in the finite and tame cases) how can we classify the families of indecomposable representations of these algebras?\n\t\\item How can we generalize the idea of Schur duality to even broader families of noncommutative quasihereditary algebras?\n\\end{itemize}\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\newpage\n\\section*{Acknowledgements}\n\\label{sec:ack}\n\\addcontentsline{toc}{section}{\\nameref{sec:ack}}\nI extend my most heartfelt thanks to my advisor, Julia Pevtsova, who not only helped me immensely in setting a target \nfor this project, but also introduced me to many of the classical ideas found in this paper (some times more than once). \nHer knowledge and understanding while I learned this subject has been absolutely invaluable to me.\n\nMy thanks also to my loving partner Allison, who stands beside me in good times and in bad and always patiently humors me when \nI need someone to listen to my inane ramblings.\n\nFinally, thank you to my friends and colleagues in the University of Washington math department for many fruitful conversations \nand inspiration for ideas to investigate along the way. In particular I am indebted to (in no particular order) Thomas Carr, Sean Griffin, Sam Roven, and Cody Tipton\nfor all their help and support.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%  Bibliography %%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\newpage\n\n\\printbibliography\n\\addcontentsline{toc}{section}{References}\n\n\\end{document}", "meta": {"hexsha": "567be8fcec6cbbdd55779679788afe15d4bb1157", "size": 131436, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "General-Paper.tex", "max_stars_repo_name": "NicoCourts/General-Exam-Paper", "max_stars_repo_head_hexsha": "bba03156740b61d1e3e9bcc9fdae6d2328863218", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "General-Paper.tex", "max_issues_repo_name": "NicoCourts/General-Exam-Paper", "max_issues_repo_head_hexsha": "bba03156740b61d1e3e9bcc9fdae6d2328863218", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "General-Paper.tex", "max_forks_repo_name": "NicoCourts/General-Exam-Paper", "max_forks_repo_head_hexsha": "bba03156740b61d1e3e9bcc9fdae6d2328863218", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 60.6814404432, "max_line_length": 254, "alphanum_fraction": 0.701048419, "num_tokens": 42608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.3223918075313019}}
{"text": "\\chapter{Theory}\n\nIn the following sections, examples of a figure, an equation, a table, a chemical structure, a list, a listing and a to-do note are shown.\nThese examples are not particularly well-made\\dots%\n\\footnote{Here is another footnote to illustrate cross-chapter numbering.}\n\n\\section{Figure}\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=0.45\\linewidth, trim=3cm 11cm 3cm 11cm]{chapters/theory/X.pdf}\n    \\includegraphics[width=0.45\\linewidth, trim=3cm 11cm 3cm 11cm]{chapters/theory/Y.pdf}\n    \\caption{Surface and contour plots showing the two dimensional function $z(x,y)=\\sin(x+y)\\cos(2x)$.}\n\\end{figure}\n\n\\section{Equation}\n\\begin{equation}\n    f(t)=\\left\\{%\n    \\begin{array}{ll}\n        1,\\qquad & t< 1 \\\\\n        t^2 & t\\geq 1\n    \\end{array}\\right.\n\\end{equation}\n\n\\section{Table}\n\\begin{table}[H]\n    \\centering\n    \\caption[This (instead of the potentially long caption) appears in the list of tables.]{Values of $f(t)$ for $t=0,1,\\dots 5$.}\n    \\begin{tabular}{lllllll}\n        \\toprule\n        $t$ & 0 & 1 & 2 & 3 & 4 & 5 \\\\ \\midrule\n        $f(t)$ & 1 & 1 & 4 & 9 & 16 & 25 \\\\ \\bottomrule\n    \\end{tabular}\n\\end{table}\n\n\\section{Chemical structure}\n\\begin{center}\n    \\chemfig{X*5(-E-T-A-L-)}\n\\end{center}\n\n\\section{List}\n\\begin{enumerate}\n    \\item The first item\n    \\begin{enumerate}\n        \\item Nested item 1\n        \\item Nested item 2\n    \\end{enumerate}\n    \\item The second item\n    \\item The third item\n    \\item \\dots\n\\end{enumerate}\n\n\\section{Source code listing}\nAn example of a source code listing.\nThe output can be drastically improved with the optional settings.\n\\lstset{language=Matlab}\n\\begin{lstlisting}[frame=single]\n% Generate x- and y-nodes\nx = linspace(0, 1);\ny = linspace(0, 1);\n\n% Calculate z = f(x, y)\nfor i = 1:length(x)\n    for j = 1:length(y)\n        z(i, j) = x(i) + 2*y(j);\n    end\nend\n\\end{lstlisting}\n\n\\section{To-do note}\nThe \\texttt{todo} package enables to-do notes to be added in the page margin. This can be a very convenient way of making notes in the document during the process of writing. All notes can be hidden by using the option \\emph{disable} when loading the package in the settings. \\todo{Example of a to-do note.}\n", "meta": {"hexsha": "6593f83555b23fea3b30193bbcc07948779679fe", "size": 2204, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/theory.tex", "max_stars_repo_name": "kajoel/master_thesis_template", "max_stars_repo_head_hexsha": "d64376911dde9d53e2ff1d8abecd037d82e768ce", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-01-22T10:16:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T10:48:59.000Z", "max_issues_repo_path": "chapters/theory.tex", "max_issues_repo_name": "kajoel/master_thesis_template", "max_issues_repo_head_hexsha": "d64376911dde9d53e2ff1d8abecd037d82e768ce", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-01-23T15:03:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-23T18:39:56.000Z", "max_forks_repo_path": "chapters/theory.tex", "max_forks_repo_name": "kajoel/master_thesis_template", "max_forks_repo_head_hexsha": "d64376911dde9d53e2ff1d8abecd037d82e768ce", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-02-04T08:28:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-02T15:09:58.000Z", "avg_line_length": 31.0422535211, "max_line_length": 307, "alphanum_fraction": 0.6728675136, "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.32239180753130187}}
{"text": "\\documentclass[10pt,conference,compsocconf,a4paper]{IEEEtran}\n\n\\usepackage{graphicx}\n\\usepackage{amsmath, amssymb}\n\\usepackage{commath}\n\\usepackage{booktabs}\n\\usepackage{siunitx}\n\\usepackage[labelformat=simple, labelfont=normalfont]{subcaption}  % Side-by-side figures\n\\usepackage[labelfont=sc]{caption}  % Using captionof outside of figure environment\n\\usepackage[colorlinks, bookmarks=false, citecolor=black, linkcolor=black, urlcolor=blue]{hyperref}  % Cite colors + autoref\n\\usepackage{xurl}  % hypen breaks in urls\n\n\\newcommand{\\G}{\\mathcal{G}}\n\\renewcommand{\\vec}[1]{\\boldsymbol{#1}}\n\\newcommand{\\unit}[1]{\\ [\\si{#1}]}\n\\newcommand{\\nunit}[1]{\\ \\si{#1}}\n\\newcommand{\\avg}[1]{\\langle{#1}\\rangle}\n\n% braces around equation number in referencing\n\\makeatletter\n\\let\\oldtheequation\\theequation\n\\renewcommand\\tagform@[1]{\\maketag@@@{\\ignorespaces#1\\unskip\\@@italiccorr}}\n\\renewcommand\\theequation{(\\oldtheequation)}\n\\makeatother\n\n% Prevent latex from streching out paragraph spacings\n\\raggedbottom\n\n% braces around subfig number\n\\renewcommand\\thesubfigure{\\,(\\alph{subfigure})}\n\n% Smallcaps short autoref\n\\newcommand*{\\shortautoref}[1]{%\n\t\\begingroup\n\t\\def\\equationautorefname{\\textsc{Eq.}}%\n\t\\def\\tableautorefname{\\textsc{Tab.}}%\n\t\\def\\figureautorefname{\\textsc{Fig.}}%\n\t\\autoref{#1}%\n\t\\endgroup\n}\n\n% Itemize spacing\n\\let\\olditemize=\\itemize\n\\let\\endolditemize=\\enditemize\n\\renewenvironment{itemize}{\\olditemize \\itemsep0em}{\\endolditemize}\n\n% subfigure spacing\n\\captionsetup[subfigure]{aboveskip=1pt}\n\n\\begin{document}\n\\title{CS-433 -- Project 2\\\\Convolutional graph neural networks for tracking yeast cells}\n\n\\author{\n\tGreta Brenna, Fanny Massard, Niels Vadot\\\\\n\t\\textit{EPFL, Switzerland}\n}\n\n\\maketitle\n\n\\begin{abstract}\n\tWe present a graph-based machine learning method that is able to track yeast cells throughout a movie, after having segmented the frames (here, this is done with YeaZ \\cite{dietler_convolutional_2020}). The method achieves better accuracy than the Hungarian algorithm implemented in YeaZ, thanks to the context-awareness of the graph structure. The method relies on translating the tracking problem to a binary node classification problem, and should generalize to any tracking problem where segmentations are available. The source code, as well as explicative Python notebooks, are available at \\cite{vadot_cs-433_2021}.\n\\end{abstract}\n\n\n\\section{Context}\n\n\tThe tracking problem emerges when addressing a more specific problem, that of lineage determination of budding yeast : for each new bud, the parent cell needs to be determined. This is made difficult in densely packed environments, but budneck markers can be used to manually determine the parent of each bud. However, it might not always be convenient to use such markers, and the question arises if lineage determination is possible with only a phase contrast image. Buds are most visible when they grow, so a machine learning algorithm might be able to pick up on spatio-temporal correlations in the segmentations to determine the parent. However, feeding a machine learning algorithm coherent temporal information requires a consistent tracking of the cells, which is the main problem this report addresses.\n\n\tThe classical approach to tracking is to extract some features from the segmentation geometry (YeaZ uses cell surface area and center of mass), and minimize the pairwise euclidean distance in the feature space using the Hungarian algorithm. The problem with this method is that it starts to break down for large colonies, since in that regime many cells have similar geometry and entire sections of the colony might drift away. Then, it would be interesting to look at pairwise relationships between cells and their nearest neighbors to track the cells, similarly to how puzzle pieces fall into place given the right context.\n\n\tA graph-based approach arises, which can naturally encode cells as nodes with certain features, and nearest-neighbor relationships are edge features. The recent development of graph neural networks (GNN) \\cite{zhou_graph_2021} and growing open-source codebase \\cite{paszke_pytorch_2019, fey_fast_2019} makes it possible to easily implement machine learning methods that are able to learn on graphs.\n\n\n\\section{Prior work}\n\n\tThe problem of tracking arises in other domains, such as reconstruction of particle trajectory in detectors \\cite{dezoort_charged_2021}. In this approach, timestamped detection events in cylindrical coordinates are represented as nodes, and edge features are constructed by considering geometrical differences of the two detection events it connects. Features are then encoded with an MLP, and an edge-classification task is performed in order to attribute multiple detection events to the same particle. In our context, cells are not moving in a highly correlated manner like a particle through a detector, but the idea of encoding geometrical features can be repurposed.\n\n\tTracking nodes, as they evolve in time-dependent graphs, can be reformulated as the problem of graph matching. \\cite{kipf_semi-supervised_2017} considers the problem of finding a subgraph in a larger graph. It does this by applying graph convolutions, embedding the nodes in a high-dimensional space, and minimizing the total cost of pairwise euclidean distance to match nodes from the two graphs. We try to reformulate the tracking problem as a graph matching problem, and use a similar idea by maximizing a score to assign nodes between two graphs.\n\n\t% Other papers \\cite{cordonnier_extrapolating_2019} propose a graph neural network-based approach to predict trajectories, however they assume highly correlated motion or decision agents responsible for the motion, which is not applicable here. Furthermore, the task here is to reconstruct trajectories, not to predict them.\n\n\n\\section{Data preprocessing} \\label{sec:data_preprocessing}\n\n\t\\subsection{Feature extraction and cell graph generation}\n\n\t\tThe full data preprocessing pipeline is schematized in \\shortautoref{fig:pipeline}. The data used here consists of 5 colonies of budding yeast, with phase contrast images taken at 5 minute intervals, for a total of 180 images (15 hours of growth time) per colony. The first 4 colonies (in the data, named \\texttt{colony00[0123]}) are used for generating training (and validation) datasets, and the last colony (named \\texttt{colony007}) is kept as a final testing set. On average, the colonies started with 2 cells and had 110 cells at the end.\n\n\t\tThe movies were segmented and tracked semi-automatically using YeaZ \\cite{dietler_convolutional_2020}. From the segmentation masks, simple geometrical features were extracted from the cells : surface area $A$, radius $r$ and eccentricity $e$. To do this, an ellipse was fitted to the cell by using PCA analysis on the cell mask coordinates, which can then be used to obtain the semi-major and minor axes $a$ and $b$ respectively. Then we compute $e=\\sqrt{1-(\\frac{a}{b})^2}$, and the radius of the circle with the same area as the ellipse $r=\\sqrt{ab}$. \\shortautoref{fig:hist_x} shows the distribution of the node features. The distributions are strongly peaked around their mean, respectively $\\avg{A} \\approx 21 \\pm 14 \\nunit{\\micro \\meter \\squared}$, $\\avg{r} \\approx 2.5 \\pm 0.8 \\nunit{\\micro \\meter}$ and $\\avg{e} \\approx 0.52 \\pm 0.14$. Notice the distribution for $r$ has a few outliers corresponding to very large cells, and these outliers are even more visible for $A$, explained by the scaling law $A \\sim r^2$. It however doesn't make sense to remove these outliers, since that would have the same effect as removing the cell from the colony, impacting its direct neighbors.\n\n\t\tNearest neighbor features were extracted by considering the contour of each cell mask, and placing an edge between cells if the minimum distance between their contours is below $1.3 \\nunit{\\micro \\meter}$ (this threshold is arbitrary, and can be changed as needed when calling \\texttt{bread\\_nn.graph.build\\_cellgraph}). Extracted features are $\\rho$, the center of mass (CM) to CM distance between the neighboring cells, $\\theta$, the angle of the CM to CM vector with respect to the horizontal axis, and $\\ell$, the minimal distance between the contours. \\shortautoref{fig:hist_e} shows the distribution of these features. $\\rho$ shows a distribution peaked around $\\avg{\\rho} \\approx 5.4 \\pm 1.2$, which makes sense, as on average cell has a radius of $r \\approx 2.5 \\nunit{\\micro \\meter}$, meaning two average cells would be separated by approximately $2r \\approx 5.0 \\nunit{\\micro \\meter}$. $\\theta$ shows a near-uniform distribution, with mean and standard deviation $\\avg{\\theta} \\approx 0 \\pm 1.8$. Again, this is intuitive, since we don't expect cells to be preferentially aligned in one direction. Note that we allow $\\theta$ to take values in $[-\\pi, \\pi]$ instead of $[0, \\pi]$, because edges are not stored bidirectionally (to save memory), so the sign of $\\theta$ encodes directionality of the edge. $\\ell$ is strongly peaked around $\\avg{\\ell} \\approx 0.34 \\pm 0.22 \\nunit{\\micro \\meter}$. Physically, $\\ell$ is not that representative since membranes are supposed to be in contact, and the mean being slightly offset is an artifact from the segmentation process. Nevertheless, $\\ell$ can be a good distance metric between cells, since it is independent of their sizes.\n\n\t\tIn total, 720 cell graphs we constructed, for a total of 25510 nodes and 48018 edges (note : edges are considered bidirectional, but are stored as one-directional to save memory). The Python notebook used for this process can be found under \\texttt{experiment\\_gnn/build\\_cellgraphs.ipynb}.\n\n\t\\subsection{Assignment graph generation}\n\n\t\tWe formulate the tracking problem as a graph matching problem. Suppose we have generated two graphs $\\G^{(1)}$ and $\\G^{(2)}$ storing extracted features from two segmentations, and we want to track cells from segmentation (1) to segmentation (2). For this, we construct an assignment graph $\\G^{(a;x,e)}$. Let $\\vec{v_i^{(1)}}, \\vec{e_{i,j}^{(1)}}$ (resp. $\\vec{v_a^{(2)}}, \\vec{e_{a,b}^{(1)}}$) encode the nodes and edges of $\\G^{(1)}$ (resp. $\\G^{(2)}$). Nodes $\\vec{v_{ia}^{(a)}}$ of $\\G^{(a;x,e)}$ are obtained by concatenating features from $\\vec{v_i^{(1)}}$ and $\\vec{v_a^{(2)}}$. Edges $\\vec{e_{ia,jb}^{(a)}}$ of $\\G^{(a)}$ link nodes $\\vec{v_{ia}^{(a)}}$ and $\\vec{v_{jb}^{(a)}}$ if $\\vec{e_{i,j}^{(1)}}$ and $\\vec{e_{a,b}^{(2)}}$ exist in $\\G^{(1)}$ and $\\G^{(2)}$ respectively, in which case edge features are similarly obtained by concatenation.\n\n\t\tFinally, we similarly build the corresponding target graph $\\G^{(a;y)}$, where the node features are simply 2-dimensional one-hot encoder vectors, indicating whether a node $\\vec{v_{ia}^{(a)}}$ corresponds to a correct tracking. Note that at this point, there is no trace left of the cell ids that were used to differentiate cells in the segmentations.\n\n\t\tConcretely, the assignment graph dataset was obtained by considering all pairs of segmentations separated by at most 20 frames (1h40), constructing the assignment graphs, and repeating this for each colony. The Python notebook used for this process can be found under \\texttt{experiment\\_gnn/build\\_assgraphs.ipynb}.\n\n\t\t\\begin{figure*}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{figures/pipeline.pdf}\n\t\t\t% TODO : elliptical fits line colors\n\t\t\t\\caption{Data preprocessing pipeline. A movie of a budding yeast colony is taken (in phase contrast, as is the case here), then YeaZ \\cite{dietler_convolutional_2020} is used to segment individual frames, and semi-automatically track cells. Manual corrections to segmentation and tracking are applied as required. From the segmentations, geometric features are extracted, as well as features describing the neighborhood of each cell. This is stored in a graph structure $\\G^{(1)}$ and $\\G^{(2)}$, from which an assignment graph $\\G^{(a;x,e)}$ is built. A ground truth assignment graph $\\G^{(a;y)}$ is also built. Both assignment graphs are then used by the GNN for training.}\n\t\t\t\\label{fig:pipeline}\n\t\t\\end{figure*}\n\n\n\\section{Methods}\n\n\t\\subsection{GNN structure}\n\n\t\tThe GNN structure is summarized in \\shortautoref{fig:nn}. Node and edge features of $\\G^{(a;x,e)}$ are embedded by two MLPs with ReLU activation. The resulting embedded graph is then convolved by multiple DeepGCN layers \\cite{li_deepergcn_2020}. One DeepGCN layer consists of a batch normalization layer (LayerNorm), an activation function (ReLU), one dropout layer, one GENConv layer, then finally a residual connection layer. In particular, the GENConv layer constructs messages $\\vec{x_i}'$ from node and edge features $\\vec{x_i}, \\vec{e_{i,j}}$ as\n\t\t$$\n\t\t\t\\vec{x_i}' = \\textrm{MLP}(\\vec{x_i}' + \\textrm{AGG}(\\{\\textrm{ReLU}(\\vec{x_i} + \\vec{e_{i,j}}) + \\epsilon \\;|\\; i \\in \\mathcal{N}(j)\\})),\n\t\t$$\n\t\twhere $\\mathcal{N}(j)$ denotes indices of the nodes connected to node $j$, $\\textrm{AGG}$ is a permutation-invariant aggregation function (in this case, a softmax), and $\\epsilon$ is a small learnable constant. The $\\textrm{MLP}$ has 2 layers, and preserves the number of channels of the input.\n\n\t\tThe final linear layer maps the embedded node channels to two channels, and the resulting graph $\\G^{(a;\\hat y)}$ is then passed to CrossEntropyLoss along with the ground truth $\\G^{(a;y)}$ for backpropagation.\n\n\t\\subsection{Making predictions} \\label{sec:methods:pred}\n\n\t\tLet $n_1$ and $n_2$ be the number of cells in the first and second images respectively. We define an assignment matrix $A$ with components $A_{i,j} = 1$ if cell $i$ in the first image is the same as cell $j$ in the second image, else $A_{i,j} = 0$. For the example in \\shortautoref{fig:pipeline}, the assignment matrix is\n\t\t$$\n\t\t\tA = \\begin{pmatrix}\n\t\t\t\t1 & 0 & 0 & 0 & 0 & 0 & 0 \\\\\n\t\t\t\t0 & 1 & 0 & 0 & 0 & 0 & 0 \\\\\n\t\t\t\t0 & 0 & 1 & 0 & 0 & 0 & 0 \\\\\n\t\t\t\t0 & 0 & 0 & 1 & 0 & 0 & 0 \\\\\n\t\t\t\t0 & 0 & 0 & 0 & 1 & 0 & 0\n\t\t\t\\end{pmatrix}.\n\t\t$$\n\n\t\tFrom the predicted graph $\\G^{(a;\\hat y)}$, we can construct an assignment matrix by reshaping the node features into a matrix $Z$ of shape ($n_1$, $n_2$, $2$), where the last dimension stores weights for the classification decision. There are multiple ways of transforming $Z$ into $A$, but we describe only the method that empirically worked the best (other methods are presented and discussed in \\texttt{experiment\\_gnn/pipeline.ipynb}).\n\n\t\tBy taking differences along the last axis of $Z$, we obtain a score matrix $S$ of shape ($n_1$, $n_2$), where each entry's magnitude can be interpreted as the confidence of the GNN of the assignment. The goal is then to find $A^\\star$ as such to maximize the assignment score, mathematically\n\t\t$$\n\t\t\tA^\\star = \\arg \\max_{A \\in \\{0, 1\\}^{n_1 \\times n_2}} \\sum_{i,j} S_{i,j} A_{i,j}.\n\t\t$$\n\t\tThis linear sum assignment (linsum) is easily solved by using \\texttt{scipy.optimize.linear\\_sum\\_assignment} from the Scipy package \\cite{2020SciPy-NMeth}.\n\n\t\t\\begin{figure*}\n\t\t\t\\centering\n\t\t\t\\includegraphics[width=\\linewidth]{figures/nn.pdf}\n\t\t\t\\caption{The GNN structure. For a given input graph, the node and edge features are encoded by MLPs. The resulting graph is then convolved multiple times following DeepGCN \\cite{li_deepergcn_2020}. A final linear layer maps the encoded node features down to two, and CrossEntropyLoss is computed for backpropagation. For evaluation, the node features of $\\G^{(a;\\hat y)}$ can be reduced and reshaped to build an assignment matrix.}\n\t\t\t\\label{fig:nn}\n\t\t\\end{figure*}\n\n\n\\section{Results}\n\n\tThis section discusses performance on the models trained with the constructed graphs, as described in \\shortautoref{sec:data_preprocessing}. All models are trained with the Adam optimizer with varible exponentially decaying learning rate, adjusted manually depending on the batch size used. Unless specified otherwise, all layers use dropout (if it applies) during training with probability parameter $0.1$. The random seed is fixed at the start of each training session. Training and validation datasets are shuffled at each epoch, and make up $80\\%$ and $20\\%$ of the total dataset respectively.\n\n\tFor evaluation, models predicting assignment matrix $\\hat A$ are compared to the ground truth $A$ using the accuracy metric defined as\n\t$$\n\t\t\\textrm{acc}(\\hat A, A) = \\frac{1}{n_1 n_2} \\sum_{i,j} \\delta_{A_{i,j}, \\hat{A}_{i,j}}.\n\t$$\n\n\t\\subsection{MLP baseline}\n\n\t\tAs a baseline for the GNN, we train a MLP on the node features $\\vec{X}$ of $G^{(a;x,e)}$ to evaluate if the graph structure (that is, addition of edge features) really adds valuable information for learning.\n\n\t\tFor this, we need to equilibrate the labels $\\vec{y}$, because asymptotically the number of nodes in the assignment graph grows as $n_1 n_2$, but the number of assignments where $y=1$ grows as $n_1$. Therefore, labels $y=1$ are underrepresented in large graphs, and equilibration is done by removing samples where $y=0$ from the training batch, until both classes are equally represented.\n\n\t\tFurthermore, batch normalization is applied before the MLP in order to improve training, as described in \\cite{ioffe_batch_2015}.\n\n\t\tA hyperparameter scan was performed on the number of MLP layers and hidden channels, and found that the best performing MLP obtained an accuracy of approximately $0.88$. More layers and hidden channels were found to marginally improve the accuracy, before it started to drop due to overfitting.\n\n\t\\subsection{GNN performance}\n\n\t\tWe perform a scan on the following hyperparameters : $N_\\textrm{enc}$ number of layers in both encoder MLPs, $N_\\textrm{conv}$ number of DeepGCN layers, and $N_\\textrm{dim}$ the number of hidden channels. Other hyperparameters, such as dropout, learning rate, exponential learning rate decay and training batch size were found to not significatively improve final performance, but can decrease training time if correctly chosen (here they were set to $0.1$, $\\sim 10^{-4}$, $\\sim 0.98$, $\\sim 32$ respectively). For the study, we chose $N_\\textrm{enc} \\in \\{1,2,3,4,5\\}$, $N_\\textrm{conv} \\in \\{1,2,3,4,5,8,11\\}$ and $N_\\textrm{dim} \\in \\{30, 60, 90, 120\\}$. \\shortautoref{fig:hparams} plots the results of the hyperparameter scan in parallel coordinates.\n\n\t\tModels with less than $0.99$ accuracy are obtained with few parameters overall, $N_\\textrm{enc} \\in \\{1,2,3\\}$, $N_\\textrm{conv} \\in \\{1,2,3,4\\}$ and $N_\\textrm{dim} \\in \\{30, 60\\}$. For better accuracy, it was found most effective to increase the number of encoder layers $N_\\textrm{enc} \\in \\{2,3\\}$, which systematically drove up the accuracy up to $0.999$. Following this, increasing $N_\\textrm{enc}$ only marginally improved accuracy, but allowing up to 5 convolution layers gave models obtaining accuracy of up to $0.9999$. In this regime, the graph neural network is able to capture most of the complexity of the problem, but still struggles with edge cases (for instance, a cell moving a large amount). Further increasing the number of parameters (via $N_\\textrm{conv}$ or $N_\\textrm{dim}$, they seem to compensate each other) results in even better accuracy, where edge cases are now correctly handled. The best models obtained an accuracy of $0.99997$, and utilized $N_\\textrm{enc} \\geq 3$, $N_\\textrm{conv} \\geq 8$ and $N_\\textrm{dim} \\geq 80$.\n\n\t\tIntuitively, the performance gain of increasing $N_\\textrm{enc}$ eventually caps off, because each cell graph node or edge is decribed with only 3 features, and the MLP can only transform information it is given. Increasing $N_\\textrm{conv}$ intuitively can be seen as increasing the ``communication distance'' between cells, meaning each node has a ``better view'' of the whole graph structure. This of course comes with the cost of requiring more dimensions to store the information in, explaining the need to increase $N_\\textrm{dim}$, and how both compensate each other. It is not useful to be able to ``see'' further in the graph ($N_\\textrm{conv}$ large) if you cannot ``store'' the information ($N_\\textrm{dim}$ small), and vice-versa.\n\n\t\tWe now compare the performance of the best GNN model ($N_\\textrm{enc}=5$, $N_\\textrm{conv}=11$, $N_\\textrm{dim}=120$) against the built-in tracking system of YeaZ, using the test dataset. From the 180 frames in the dataset, 885 pairs are tested, corresponding to frames separated by 5 to 25 minutes. Numerical results are presented in \\shortautoref{tab:test_acc}. The linear sum assignment method works the best, and performs better than YeaZ, especially for pairs of frames separated by a long time difference, and in situations where cells move around a lot (specific examples are shown in \\shortautoref{fig:mistracks}). The dataset's frames were separated by 5 minutes here, however one should expect approximately 15 minutes of frame separation in real applications, in which case this method has been shown to be performant.\n\n\t\t% Out of the 180 interframes of the testing set, YeaZ's tracker made at least one mistake on 3 of them, while our model made none. This seems plausible, as this test evaluates performance on only one frame difference (5 minutes), but the GNN has been trained on frames separated by at most  Accuracies for different methods of generating assignment matrice from the model's output are reported in \\shortautoref{tab:test_acc}. This of course is not enough testing data to definitely conclude\n\n\t\t% Note that experimentally, better tracking performance has been observed when using values larger than this threshold, around $2 \\nunit{\\micro \\meter}$. This of course depends on the exact colony morphology\n\n\t\t\\begin{table}\n\t\t\t\\centering\n\t\t\t% \\begin{tabular}{l||rrrrr|r}\n\t\t\t% \t\\toprule\n\t\t\t% \t{} &       naive &     fw &    bw &  bw+corr &      linsum &        yeaz \\\\\n\t\t\t% \t\\midrule\n\t\t\t% \tmean  &    0.98698 &    0.99834 &    0.98689 &       0.99534 &    \\textbf{0.99991} &    0.99420 \\\\\n\t\t\t% \tstd   &    0.04319 &    0.01482 &    0.04011 &       0.01767 &    0.00064 &    0.05908 \\\\\n\t\t\t% \tmin   &    0.77777 &    0.77777 &    0.75000 &       0.77777 &    0.99259 &    0.33333 \\\\\n\t\t\t% \t25\\%   &    0.99725 &    1.00000 &    0.99359 &       1.00000 &    1.00000 &    1.00000 \\\\\n\t\t\t% \t50\\%   &    1.00000 &    1.00000 &    1.00000 &       1.00000 &    1.00000 &    1.00000 \\\\\n\t\t\t% \t75\\%   &    1.00000 &    1.00000 &    1.00000 &       1.00000 &    1.00000 &    1.00000 \\\\\n\t\t\t% \tmax   &    1.00000 &    1.00000 &    1.00000 &       1.00000 &    1.00000 &    1.00000 \\\\\n\t\t\t% \t\\bottomrule\n\t\t\t% \\end{tabular}\n\t\t\t\\begin{tabular}{lrrrrrrrr}\n\t\t\t\\toprule\n\t\t\t{} &             mean &       std &      25\\% &  50\\% &  75\\% \\\\\n\t\t\t\\midrule\n\t\t\tnaive         &  0.986984 &  0.043199 &  0.997253 &  1.0 &  1.0 \\\\\n\t\t\tfw            &  0.998341 &  0.014823 &  1.000000 &  1.0 &  1.0 \\\\\n\t\t\tbw            &  0.986895 &  0.040118 &  0.993590 &  1.0 &  1.0 \\\\\n\t\t\tbw+corr       &  0.995342 &  0.017675 &  1.000000 &  1.0 &  1.0 \\\\\n\t\t\tlinsum        &  \\textbf{0.999913} &  0.000645 &  1.000000 &  1.0 &  1.0 \\\\\n\t\t\t\\midrule\n\t\t\tyeaz          &  0.994201 &  0.059083 &  1.000000 &  1.0 &  1.0 \\\\\n\t\t\t\\bottomrule\n\t\t\t\\end{tabular}\n\t\t\t\\caption{Test accuracy of different methods of generating the assignment matrices from the GNN's output. The testing set (\\texttt{colony007}) was split into pairs of 885 interframes, separated in real time by 5 to 25 minutes. ``naive'' refers to classifying each node simply based on the weights for each class. ``fw'' refers to the forward method, which forces each cell in the first frame to match one in the second frame. ``bw'' refers to the backwards method, which forces each cell in the second frame to match one in the first frame. ``bw+corr'' is a corrected version of the backward method, which accounts for buds. ``linsum'' uses the linear sum optimization method, as presented in \\shortautoref{sec:methods:pred}. ``yeaz'' is the baseline tracking method. See \\texttt{experiment\\_gnn/pipeline.ipynb} for more information.}\n\t\t\t\\label{tab:test_acc}\n\t\t\\end{table}\n\n\n\\section{Conclusion}\n\n\tWe have shown that this graph neural network model is able to learn the structure of a yeast cell colony, and is able to reliably track cells from frame to frame. It has been shown that the model exceeds YeaZ's integrated tracker performance, using a relatively small training dataset of only 4 colonies growing over 15 hours and imaged every 5 minutes. If implemented in YeaZ's GUI, tracking tasks will become easier and significantly less time-consuming, especially for large colonies.\n\n\tOne of the limitations of this model is the need to have segmented the images and verified the segmentations. We however argue that thanks to advancements in this domain \\cite{dietler_convolutional_2020,stringer_cellpose_2020}, this has become a trivial task. Nevertheless, it is a good practice to verify the segmentations manually, and correct as needed.\n\n\tThe model presented in this report essentially only uses two graphs as an input, and could benefit from having a ``longer history'' of the colony in order to make better tracking predictions. Multiple papers \\cite{singer_node_2019,jin_recurrent_2020,rossi_temporal_2020} address the problem of temporal graphs, and it might be worth investigating to further the research. In summary, using temporal graph networks are a promising approach to constructing lineages from only phase contrast (or bright field) microscopy movies. This would likely have to be coupled to an attention system, for which literature and implementations for graph neural networks already exist \\cite{velickovic_graph_2018,brody_how_2021}.\n\n\t% Rome wasn't built in a day, and graph neural networks aren't mastered in a month.\n\n\\newpage\n\\bibliographystyle{IEEEtran}\n\\bibliography{literature}\n\n\\newpage\n\\appendix\n\n\t\\begin{figure}[h!]\n\t\t\\centering\n\t\t\\includegraphics[width=\\linewidth]{figures/mistracks.pdf}\n\t\t\\caption{Segmentations from \\texttt{colony007} highlighting moving cells. Out of the 179 interframes, YeaZ makes 3 tracking mistakes. On frame 115, cells 9 and 14 move together towards cell 5, and YeaZ tracks cell 9 to cell 16 and cell 14 to cell 9. On frame 163, cell 22 moves around the top of the colony, and YeaZ tracks cell 10 to 22, cell 10 to 29, cell 29 to cell 25 and cell 25 to 34. On frame 171, cells 22 and 34 move together around the top while swapping places, and YeaZ tracks cell 22 to 34 and vice-versa.}\n\t\t\\label{fig:mistracks}\n\t\\end{figure}\n\n\t\\begin{figure}\n\t\t\\centering\n\t\t\\includegraphics[width=\\linewidth]{figures/hist_x.pdf}\n\t\t\\captionof{figure}{Distribution of node features.}\n\t\t\\label{fig:hist_x}\n\t\\end{figure}\n\n\t\\begin{figure}\n\t\t\\centering\n\t\t\\includegraphics[width=\\linewidth]{figures/hist_e.pdf}\n\t\t\\captionof{figure}{Distribution of edge features.}\n\t\t\\label{fig:hist_e}\n\t\\end{figure}\n\n\t\\begin{figure}\n\t\t\\centering\n\t\t\\includegraphics[width=\\linewidth]{figures/hparams.pdf}\n\t\t\\caption{Parallel coordinates plot of the hyperparameter scan. The best performing model uses $N_\\textrm{enc}=5$, $N_\\textrm{conv}=11$, $N_\\textrm{dim}=120$, but a very similar performance can be achieved for less parameters, $N_\\textrm{enc} \\geq 3$, $N_\\textrm{conv} \\geq 8$ and $N_\\textrm{dim} \\geq 80$.}\n\t\t\\label{fig:hparams}\n\t\\end{figure}\n\n\\end{document}\n", "meta": {"hexsha": "81d3c32a9ce213b2f0642caa5fb9a5828d992e42", "size": 27118, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/report_gnn/report.tex", "max_stars_repo_name": "ninivert/bread", "max_stars_repo_head_hexsha": "9f8502574312d702fee9910130cffe3d876efced", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paper/report_gnn/report.tex", "max_issues_repo_name": "ninivert/bread", "max_issues_repo_head_hexsha": "9f8502574312d702fee9910130cffe3d876efced", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/report_gnn/report.tex", "max_forks_repo_name": "ninivert/bread", "max_forks_repo_head_hexsha": "9f8502574312d702fee9910130cffe3d876efced", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 102.3320754717, "max_line_length": 1686, "alphanum_fraction": 0.7457408363, "num_tokens": 7475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704796847395, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.322315403511774}}
{"text": "\\chapter{Introduction}\n\\section{first section}\nThis is the introduction Figure \\ref{fig:my_label}.\n\nNow reference an eqn about linear algebra: \\eqref{eq:Linear Algebra}.\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=\\linewidth]{figures/StabilityMargin.pdf}\n    \\caption{Caption}\n    \\label{fig:my_label}\n\\end{figure}\n\\begin{equation} \\label{eq:Linear Algebra}\n\\underline{A}\\vec{x}=\\underline{B}\n\\end{equation}\n\\lstinputlisting[language=Matlab]{code/Add.m}\n% Matlab Figure%%%%%%%%%%%%%%%%%%%%%%\n\\begin{figure}\n\t\n\t\\tikzset{every picture/.style={scale=.8}}%\n\t\\centering\n\t\\import{figures/}{test1.tex}\n\t\\caption{Free body diagram of a beam section in planar bending.}\n\t\\label{fig:test1}\n\\end{figure}\n% Inkscape Figure%%%%%%%%%%%%%%%%%%%%%\n\\begin{figure}\n\t\\centering\n\t\\def\\svgwidth{400pt}\n\t\\import{figures/}{BeamElement.pdf_tex}\n\t\\caption{Beam Element with nodal displacements.}\n\t\\label{fig:BeamElem}\n\\end{figure}", "meta": {"hexsha": "8b6ae742b089b077624aaa813990ad63c617a7c4", "size": 918, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/testing.tex", "max_stars_repo_name": "cameron1320/Cameron", "max_stars_repo_head_hexsha": "276144ab299ab00f102f3f3cc0869261a13e0059", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/testing.tex", "max_issues_repo_name": "cameron1320/Cameron", "max_issues_repo_head_hexsha": "276144ab299ab00f102f3f3cc0869261a13e0059", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/testing.tex", "max_forks_repo_name": "cameron1320/Cameron", "max_forks_repo_head_hexsha": "276144ab299ab00f102f3f3cc0869261a13e0059", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6875, "max_line_length": 69, "alphanum_fraction": 0.7124183007, "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704796847395, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.322315403511774}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\section{Gauge conditions}\n\n\\marginpar{Tuesday\\\\ 2021-6-22, \\\\ compiled \\\\ \\today}\n\nSo far we have only discussed maximal slicing, \\(k = - \\nabla_a n^a = 0\\). \n\nNow let us see Schwarzschild foliations: in \\((t, R)\\) Schwarzschild coordinates we can consider \\(t= \\const\\) hypersurfaces. \n\nFor \\(R > 2M\\) time \\(t\\) is a temporal coordinate. Here, these constant-\\(t\\) hypersurfaces satisfy \\(k_{ab} = 0\\), so we also have \\(k=0\\). \n\nIf we draw a Kruskal \\(U\\), \\(V\\) diagram the horizon \\(R = 2M\\) is a diagonal line \\(U=V\\), while the singularity is a hyperbola. \n\nThis slicing is therefore \\emph{maximal}, and \\emph{not horizon penetrating}. \n\nIf we use the isotropic radius \\(r\\) as a coordinate, the lapse reads \n%\n\\begin{align}\n\\alpha = \\qty(1 - \\frac{M}{2r}) \\qty(1 + \\frac{M}{2r})^{-1}\n\\,.\n\\end{align}\n\n\\(\\alpha \\) is antisymetric, and negative in the III Kruskal region. \n\nIn the region \\(R < 2M\\), the foliation is given by \\(R = \\const\\) because there \\(R\\) is a timelike coordinate. \n\nNow, \\(\\alpha = (2M / R - 1)^{-1}\\), while the metric determinant  is \n%\n\\begin{align}\n\\gamma = R^{4} \\sin^2 \\theta \\qty( \\frac{2M}{R } - 1)\n\\,,\n\\end{align}\n%\nand we can use \n%\n\\begin{align}\nk = - \\frac{1}{\\alpha } \\mathscr{L}_m \\log \\sqrt{ \\gamma } \n= \\frac{3M - 2R}{R^2 \\qty( 2M / R - 1)^{1/2}}\n\\,,\n\\end{align}\n%\ntherefore the \\(R = 3M/2\\) slice is maximal. \n\nIt can be proven that this is a limit slice of a certain maximal foliation of stuff which looks like hyperbolas in a Kruskal diagram, which is maximal and symmetric with respect to \\(R = 2M\\). \n\nThese correspond to solutions of the maximal equation the lapse: \n%\n\\begin{align}\nD_i D^{i}  \\alpha - \\alpha \\qty()\\dots = 0\n\\,\n\\end{align}\n%\nwith boundary conditions such that \\(\\alpha \\to 1\\) at \\(\\iota_0 \\), and \\(\\alpha (2M) = 0\\) (case 1, a Dirichlet boundary condition) or \\(\\partial_{R} \\alpha (3M/2) = 0\\) (case 2, a Neumann boundary condition). \n\nDifferent inner BCs determine different foliations and different properties. \nBoth of the foliations we discussed are singularity-avoiding. \n\nIn Eddington-Finkelstein (Kerr-Schild) coordinates, we can set \n%\n\\begin{align}\nt_{KS} = t + 2M \\log \\qty( \\frac{r}{2M} - 1)\n\\,,\n\\end{align}\n%\nwhich yields a non-singularity avoiding foliation. \nHow do we construct, in general, maximal foliations of Schwarzschild?\n\nWe consider the transformation \n%\n\\begin{align}\nt \\to \\widetilde{t} = t + h( R)\n\\,,\n\\end{align}\n%\nwhere \\(h(R)\\) is a \\emph{height function}, which (because of \\(0 = k\\)) satisfies the equation \n%\n\\begin{align}\nh'(R) = \\frac{c^2}{A^2(R) \\qty[ A(R) R^{4} + c^2s]}\n\\,,\n\\end{align}\n%\nwhere \\(A(R) = (1- 2M /R)\\) and \\(c\\) is a constant of integration. \n\nThe metric is given in terms of \n%\n\\begin{align}\n\\alpha = f(R) &= 1 + \\frac{2M}{R} + \\frac{c^2}{R^{4}}\n\\,,\n\\end{align}\n%\nwhile the shift is \n%\n\\begin{align}\n\\beta^{r} = \\frac{c}{R^2} \\sqrt{f(R)} \n\\,,\n\\end{align}\n%\nand \n%\n\\begin{align}\n\\gamma_{ij} \\dd{x^{i}} \\dd{x^{j}} = f^{-1} (R) \\dd{R^2} + R^2 \\dd{\\Omega }\n\\,,\n\\end{align}\n%\nwhich yields a family of foliations for different choices of \\(c\\): \\(c=0\\) is standard Schwarszchild spacetime, but other choices are possible, and \\(c = (3/4) \\sqrt{3} M^2\\).\n\nThe main property of maximal slicing, which is quite general, is that the lapse \\(\\alpha \\) goes to zero in the regions of highest curvature. \n\nThis is called ``lapse freezing'' or ``lapse collapse'', and it is a generic property indicating the fact that the gauge is singularity-avoiding. \n\nThis is defined by \\(\\square x^{\\mu }=  0\\) (Harmonic  gauge), so for \\(\\mu = 0\\) we have \\(\\square t = 0\\). \n\nThis means \n%\n\\begin{align}\n0 = \\square t = \\sqrt{-g} \\partial_{\\mu } \\qty(\\sqrt{-g} g^{\\mu \\nu } \\partial_{\\nu } t) = \\sqrt{-g} \\partial_{\\mu } \\qty(\\sqrt{-g} g^{\\mu 0})\n\\,.\n\\end{align}\n%\n\nThis means that \n%\n\\begin{align}\n0 = \\partial_{t} \\qty(\\alpha \\sqrt{\\gamma } g^{00}) + \\partial_{i} \\qty(\\alpha \\sqrt{\\gamma } g^{0i})\n\\,,\n\\end{align}\n%\nbut \\(g^{00} = \\alpha^{-2}\\) and \\(g^{0i}= \\beta^{i} / \\alpha^2 \\). \n\nThe equation then reads \n%\n\\begin{align}\n0 = \\partial_{t} \\alpha - \\beta^{i} \\partial_{i} \\alpha  - \\alpha \n\\underbrace{\\qty[ \\frac{1}{\\sqrt{\\gamma }} \\partial_{t} \\sqrt{\\gamma } - \\frac{1}{\\sqrt{\\gamma }} \\partial_{i} \\qty(\\sqrt{\\gamma } \\beta^{i})]}_{- \\alpha k}\n\\,,\n\\end{align}\n%\nso the equation for \\(\\alpha \\) reads \\(\\mathscr{L}_m \\alpha = - \\alpha^2 k\\).\n\nIf we set \\(\\beta^{i} = 0\\), we get \\(\\alpha = C(x^{i}) \\sqrt{\\gamma }\\).\nIn the case of Schwarzschild, we have \\(\\partial_{t} \\alpha = 0\\), \\(\\beta^{i} = 0\\) and \\(k = 0\\). \n\nConstant-\\(t\\) slices of Schwarzschild are harmonic slices. \n\nThe Bona-Masso family, also known as \\(1 + \\log\\) slicing, is determined by \n%\n\\begin{align}\n\\mathscr{L}_m \\alpha = - \\alpha^2 f(\\alpha ) k\n\\,.\n\\end{align}\n\nWe can fall back to geodesic slicing with \\(f(\\alpha ) = 0\\), or harmonic slicing with \\(f(\\alpha ) = 1\\), or we can set \\(f(\\alpha )= 2/\\alpha \\): this is \\(1+ \\log\\) slicing. \n\nIf we set \\(\\beta^{i} = 0\\), we have \\(\\partial_{t} \\alpha = \\partial_{t}  \\log \\gamma \\), a solution to which is  \\(\\alpha = 1 + \\log \\gamma \\).\n\nFor Schwarzschild, this is the Height function method: \n%\n\\begin{align}\n\\alpha^2 = 1 - \\frac{2M}{R} + \\frac{c^2}{R^{4} } e^{\\alpha }\n\\,,\n\\end{align}\n%\nwhich is very close to maximal slicing; however this is now an implicit equation with this new exponential term. \n\nThese are called ``trumpet slices'': in an embedding diagram they look like a wormhole, however they end at \\(R = 3M/2\\). \n\nThis \\(1 + \\log\\) slicing is what is typically used today to evolve astrophysical black holes. \n\nWhat about spatial gauge and the choice of shift \\(\\beta^{i}\\)? \n\nOne item in our wishlist was ``minimal distortion'': we can quantify it through a distortion tensor, \n%\n\\begin{align}\nQ_{ij} = \\partial_{t} \\gamma_{ij} = - 2 \\alpha k_{ij} + \\mathscr{L}_\\beta \\gamma_{ij}\n\\,.\n\\end{align}\n\nFrom this tensor we can consider \n%\n\\begin{align}\n\\Sigma_{ij} = Q_{ij} - \\frac{1}{3} Q \\gamma_{ij} = \\dots = - 2 \\alpha A_{ij} + (L \\beta )_{ij} = \\psi^{4} \\partial_{t} \\widetilde{\\gamma}_{ij}\n\\,.\n\\end{align}\n\nWe can use this to define a functional: \n%\n\\begin{align}\nI[\\beta^{i}] &= \\int_{\\Sigma _t} \\Sigma_{ij} \\Sigma^{ij} \\sqrt{\\gamma } \\dd[3]{x} =  \\\\\n&= \\int_{\\Sigma _t} \\qty[ 4 \\alpha^2 A_{ij}A^{ij} - 4 \\alpha A_{ij} (L \\beta )^{ij} + (L \\beta )_{ij} (L \\beta )^{ij} ] \\sqrt{\\gamma } \\dd[3]{x}\n\\,,\n\\end{align}\n%\nwhich we can extremize: we set \\(0 = \\delta I [\\beta^{i}]\\), which yields \n%\n\\begin{align}\n\\delta I [\\beta^{i}] &= \\int_{\\Sigma _t} 2 \\delta \\qty[ \\Sigma_{ij} (L \\beta )^{ij}] \\sqrt{\\gamma } \\dd[3]{x}  \\\\\n&= 2 \\int_{\\Sigma _t} \\Sigma_{ij} \\qty(D^{i} \\delta \\beta^{j} + D^{j} \\delta \\beta^{i} - \\underbrace{\\frac{2}{3} D_k \\delta \\beta^{k} \\gamma^{ij}}_{\\Sigma = 0}) \\sqrt{\\gamma } \\dd[3]{x}  \\\\\n&= 4 \\int_{\\Sigma _t} \\Sigma_{ij} D^{i} \\delta \\beta^{j} \\sqrt{\\gamma } \\dd[3]{x}  \\\\\n&= 4 \\int_{\\Sigma _t} \\qty[ D^{i} \\qty(\\Sigma_{ij} \\delta \\beta^{j}) - D^{i} \\Sigma_{ij} \\delta \\beta^{j} ] \\sqrt{\\gamma } \\dd[3]{x}  \\\\\n&= \\underbrace{4 \\int_{\\partial \\Sigma _t} \\Sigma_{ij} \\delta \\beta^{j} \\sqrt{\\gamma } \\dd[3]{x} }_{= 0, \\eval{\\delta \\beta^{j}}_{ \\partial} = 0} - 4 \n\\int_{\\Sigma _t} D^{i} \\Sigma_{ij} \\delta \\beta^{j} \\sqrt{\\gamma } \\dd[3]{x} = 0 \n\\,,\n\\end{align}\n%\ntherefore our condition, by the usual lemma of funcitonal variational calculus, is \\(D^{i} \\Sigma_{ij} = 0\\). \nIn terms of \\(\\beta^{i}\\), this defines what is knowns as \\emph{minimal distortion shift}: \n%\n\\begin{align}\n\\triangle_L \\beta^{i} = 2 D_j \\qty(\\alpha A^{ij}) - 16 \\pi \\alpha P^{i } + \\frac{4}{3} \\alpha D^{i } k + 2 A^{ij} D_j \\alpha \n\\,.\n\\end{align}\n\nThis gauge, as written, is not really used, however it is the starting point for other ones which better achieve the distortion minimization. \n\nAn observation: both \\(Q_{ij} \\) and \\(\\Sigma_{ij}\\) are 0 if \\(\\partial_{t}\\) is a Killing vector, so in that case minimal distortion is satisfied automatically for stationary spacetimes in adapted coordinates.\n\nHow do we use this then? \nWe can use approximate minimal distortion equations: \n%\n\\begin{align}\n0 = D^{i} \\Sigma_{ij} = D^{i} \\qty(\\psi^{4} \\partial_{t} \\widetilde{\\gamma}_{ij}) \\approx \\widetilde{D}^{i} \\qty(\\partial_{t} \\widetilde{\\gamma}_{ij})\n\\,.\n\\end{align}\n%\nthis elliptic equation for \\(\\beta^{i}\\) is easier to implement numerically. \n\nThis is called \\(\\Gamma \\) freezing: we can write the equation as \n%\n\\begin{align}\n0 = D_j \\dot{\\widetilde{\\gamma}} = \\partial_{t} D_j  \\widetilde{\\gamma}_{ij} = \\dots = - \\partial_{t} \\widetilde{\\Gamma}^{i}\n\\,,\n\\end{align}\n%\n(see equation 9.32 in the notes), where \n%\n\\begin{align}\n\\widetilde{\\Gamma}^{i} = - D_j \\widetilde{\\Gamma}^{ij} = \\qty(\\widetilde{\\Gamma}^{i}_{jk} - F^{i}_{jk}) \\widetilde{\\gamma}^{jk}\n\\,.\n\\end{align}\n\nWe get an elliptic equation for \\(\\beta^{i}\\), which is written as \n%\n\\begin{align}\n\\widetilde{\\gamma}^{jk} D_j D_k \\beta^{i} + \\dots = 0\n\\,,\n\\end{align}\n%\nwhich is nice because it is written in terms of partial derivatives.\n\nAlcubierre and colleagues have proposed a \\textbf{parabolic \\(\\Gamma \\) driver}: the idea is to write \\emph{evolution} equations for \\(\\beta^{i}\\), such that the solutions ``asymptote'' to the ``equilibrium'' solution of the \\(\\Gamma \\)-freezing.\n\nThis equation will look like  \n%\n\\begin{align}\n\\partial_{t} \\beta^{i} = k \\partial_{t} \\widetilde{\\Gamma}^{i} \\approx k \\qty( \\widetilde{\\gamma}^{jk} D_j D_k \\beta^{i} + \\dots)\n\\,,\n\\end{align}\n%\na parabolic equation. \n\nFor \\(t \\to \\infty \\) this asymptotes to the \\(\\Gamma \\)-freezing solution, however parabolic PDEs are known to be \\emph{stiff}, which severely constrains the number of timesteps which can be taken. \n\nTherefore, people have also considered \\emph{hyperbolic drivers}: \n%\n\\begin{align}\n\\partial_{tt} \\beta^{i} &= k \\partial_{t} \\widetilde{\\Gamma}^{i} - \\qty(\\eta \\partial_{t} \\log k) \\partial_{t} \\beta^{i}   \\\\\n&= k \\qty(\\widetilde{\\gamma}^{jk} \\partial_{j} \\partial_{k} \\beta^{i} + \\dots ) - \\qty(\\eta - \\partial_{t} \\log k) \\partial_{t} \\beta^{i}\n\\,,\n\\end{align}\n%\nand we can discard some term to get a damped wave equation:\n%\n\\begin{align}\n\\partial_{tt} \\beta^{i} = k \\widetilde{\\gamma}^{ij} \\partial_{j} \\partial_{k} \\beta^{i} - \\eta \\partial_{t} \\beta^{i} \n\\,.\n\\end{align}\n\nThis equation transports things and damps them. \n\nA simpler first-order version is written as an advection-like equation:\n%\n\\begin{align}\n\\partial_{t} \\beta^{i} = \\mu _s \\widetilde{\\Gamma}^{i} - \\eta \\beta^{i} + \\beta^{j} \\partial_{j} \\beta^{i}\n\\,,\n\\end{align}\n%\nwhich has speed \\(\\mu _s\\) (which can be chosen freely) and a damping term \\(\\eta > 0\\), which can be also chosen. \n\nThese equations should be compared to the hyperbolic \\(\\Gamma \\)-driver with the harmonic shift equation. \n\nIn summary: \nwe have seen, for \\(\\alpha \\):\n\\begin{enumerate}\n    \\item geodesic gauge \\(\\alpha = 1\\), \\(\\beta^{i} = 0\\);\n    \\item maximal slicing \\(k = 0\\);\n    \\item harmonic slicing \\(\\square t = 0\\);\n    \\item the Bona-Masso family, which includes harmonic slicing as well as \\(1+ \\log\\) slicing;\n\\end{enumerate}\n\nand for spatial slicing \n\\begin{enumerate}\n    \\item minimal distortion;\n    \\item \\(\\Gamma \\)-drivers.\n\\end{enumerate}\n\nIn geodesic gauge, the simulation crashes at \\(t = \\pi \\) for \\(M = 1\\): this is because that is the point at which the observer falls into the singularity. \n\nWith \\(1 + \\log\\) slicing as well as a \\(\\Gamma \\) driver we reach a sort of stationary configuration and the simulation does not crash. \n\n\\end{document}\n", "meta": {"hexsha": "3f90ef6070f1190299fec2892a57e1d2bc2358f2", "size": 11491, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "phd_courses/numerical_relativity/jun22.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "phd_courses/numerical_relativity/jun22.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phd_courses/numerical_relativity/jun22.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 36.7124600639, "max_line_length": 246, "alphanum_fraction": 0.6411974589, "num_tokens": 4039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.32231540299627925}}
{"text": "\\documentclass{article}\n\\usepackage{amssymb}\n\\usepackage{amsmath}\n\\usepackage{url}\n\\usepackage{comment}\n\\usepackage[dvipdfm]{graphicx}\n\\usepackage[dvipdfm,truedimen,margin=25mm, nohead]{geometry}\n%\\usepackage{color}\n%\\usepackage[bottom]{footmisc}\n\n%\\newtheorem{theorem}{Theorem}[section]\n%\\newtheorem{conjecture}[theorem]{Conjecture}\n%\\newtheorem{corollary}[theorem]{Corollary}\n%\\newtheorem{proposition}[theorem]{Proposition}\n%\\newtheorem{lemma}[theorem]{Lemma}\n%\\newdef{definition}[theorem]{Definition}\n%\\newdef{remark}[theorem]{Remark}\n\n\\def\\F2{{\\mathbb F}_2}\n%\\def\\wt{{\\rm wt}}\n%\\def\\wo{{\\rm wt}_o}\n%\\def\\wf{{\\rm wt}_f}\n%\\def\\UL{{\\rm ul}}\n%\\def\\bx{{{\\mathbf x}}}\n%\\def\\by{{{\\mathbf y}}}\n%\\def\\bz{{{\\mathbf z}}}\n%\\def\\bw{{{\\mathbf w}}}\n%\\def\\bu{{{\\mathbf u}}}\n\n%\\def\\im{{\\mathrm{Im}}}\n%\\def\\ker{{\\mathrm{Ker}}}\n%\\def\\id{{\\mathrm{Id}}}\n%\\def\\tr{{\\mathrm{tr}}}\n\n\\title{Technical Report: Dynamic Creator of 64-bit Mersenne Twister}\n\\author{Mutsuo Saito \\and Makoto Matsumoto}\n\\date{2019-8-3}\n\n\\begin{document}\n\n\\maketitle\n\n\\begin{abstract}\n  On this report, we describe a dynamic creation program for 64-bit\n  Mersenne Twister.\n\\end{abstract}\n\n%\\keywords{\n%Mersenne Twister; Dynamic Creation; Pseudorandom Number; Parallel Computing\n%}\n\n%\\category{G.3}{Mathematics of Computing}{PROBABILITY AND STATISTICS}[Random number generation]\n\n\\subsection*{Improvement}\n\nDynamic Creation of Pserudorandom Number Generators (DC)~\\cite{DC} was\nproposed by Matsumoto and Nishimura and a program for 32-bit Mersenne\nTwister (MT)~\\cite{MT} written in C is published on web page\n\\url{http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/DC/dc.html} and\nGit Hub \\url{https://github.com/MersenneTwister-Lab/dcmt}.  64-bit\nMersenne Twister (MT64)~\\cite{MT64} was proposed by Nishimura,\nbut　dynamic creation program for MT64 has not been supported.\n\nThere was a difficulty in calculating tempering parameter of MT64.\nTwo tempering parameter sizes of MT are 25 and 17 bits, on the other\nhand, those of MT64 are 47 and 27 bits.  Increased sizes of tempering\nparameters made dynamic creation very slow and impractical. To solve\nthis difficulty, now, we adopt ``Partial Bit Pattern'' algorithm,\nwhich is the algorithm used in Mersenne Twister of Graphic Processors\n(MTGP)~\\cite{MTGP}.  The algorithm separates tempering parameters some\nbit blocks and selects a bit pattern which gives the best $k(v)$ in\nthe blocks.　(Note: we talk about the algorithm of searching tempering\nparamaeters. The tempering algorithm itself of MT64 is not changed.)\n\n\\subsection*{Results of the Dynamic Creation}\n\nWe made C++ program\ndcmt64(\\url{https://github.com/MersenneTwister-Lab/dcmt64}).  We\nexecuted the program on Super Computer of The Institute of Statistical\nMathematics(ISM) in Japan.\n\n\\begin{center}\n  Execution Environment:\\\\\n  \\medskip\n\\begin{tabular}{rl} \\hline\n  CPU & Intel Xeon Gold 6154 (18 core, 3.0GHz)\\\\\n  Memory & 384GB \\\\\n  OS & Red Hat Linux Enterprise Server 7\\\\\n  Compiler & g++ \\\\\n  \\hline\n\\end{tabular}\n\n\\bigskip\nExecution Results:\\\\\n\\medskip\n\\begin{tabular}{ll|ll} \\hline\n  used time & 10h & used process & 36 \\\\ \\hline\n  specified mexp & 19937 & parameters found & 1161 \\\\\n  \\hline\n\\end{tabular}\n\\end{center}\n\nDimension defect(DD)\\cite[\\S 1.2]{MT} is a simple evaluation index of\n$F2$-linear random number generators. The less DD is the better.\nThe minimum DD of found parameters is 5023 and the maximum one\nis 25258. 95 percent parameters have DD less than 7000.\n\n\\bibliographystyle{plain}\n\\bibliography{sfmt-kanren}\n\\end{document}\n", "meta": {"hexsha": "dcd6f3e25cfb2bfa7dcfd21304172988bfc681cb", "size": 3512, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/dcmt64-rep.tex", "max_stars_repo_name": "MersenneTwister-Lab/dcmt64", "max_stars_repo_head_hexsha": "1848880eee6b32e7b71449023bd633122a0122d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-06-05T17:08:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-06T15:16:56.000Z", "max_issues_repo_path": "tex/dcmt64-rep.tex", "max_issues_repo_name": "MersenneTwister-Lab/dcmt64", "max_issues_repo_head_hexsha": "1848880eee6b32e7b71449023bd633122a0122d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/dcmt64-rep.tex", "max_forks_repo_name": "MersenneTwister-Lab/dcmt64", "max_forks_repo_head_hexsha": "1848880eee6b32e7b71449023bd633122a0122d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-08-02T04:32:32.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-02T04:32:32.000Z", "avg_line_length": 31.6396396396, "max_line_length": 95, "alphanum_fraction": 0.7445899772, "num_tokens": 1088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.32231539495248585}}
{"text": "%!TEX root=main.tex\n\n\\section{Related Work} \\label{sec:related_work}\n\n\\subsection{Uncertainty in Neural Networks}\nNeural networks have achieved state-of-the-art results on estimating human intent~\\cite{Vemula2017, Alahi2016}. However, one fundamental difference in human and neural network reasoning is uncertainty. Neural networks normally predict a mean prediction value and can fail over-confidently on novel data. Humans, in comparison, would reveal their uncertainty saying \\textit{I have never seen this behavior before, hence I do not know how to predict the behavior}. To give the neural networks a similar notion of uncertainty and \\textit{know what they don't know}, we have explored the recent field uncertainty-aware neural networks. \n\nBayesian Neural Networks reason about predictive uncertainty by keeping track of a distribution for each network's parameter~\\cite{MacKay1992, Neal1996}. However, they are computationally intractable due to the expensive calculation of the Bayesian posterior. Even approximate methods, such as Markov Chain Monte Carlo or variational methods, come with extensive computational cost~\\cite{Louizos2016, Graves2011, Springenberg_2016}. Other works, proposes MC-Dropout~\\cite{Gal2015}: the activation of Dropout~\\cite{Dropout2014} during test as approximate Bayesian inference in deep Gaussian processes. However, uncertainty estimates with MC-Dropout have shown to be overconfident on novel data~\\cite{Osband2016, Lakshmi2016}. \n\nAlternative works proposes the Bootstrapping as an approximation of model uncertainty in neural networks~\\cite{Osband2016, Lakshmi2016}. Intuitively, an ensemble of randomly initialized models is trained on overlapping samples of a training dataset and during test the sample variance of predictions indicates the ensemble uncertainty. The predictions of each model will be similar for data points that have often occurred in the training set and differ for data points that have only occurred in one sample of the training set or not occurred at all. \n\n\\subsection{Intuitive physics understanding}\nThis work was inspired by \\cite{Lerer, Bramley2017} who explored how to simulate our intuition about physics, and did so using deep feed-forward models to learn intuitive physics.\n\n\\begin{figure}[]\n\t\\begin{subfigure}[]{1\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width=0.95\\linewidth]{figures/sim_no_coll.png}\n\t\t\\caption{Example trajectory with no collision.}\n\t\t\\label{fig:sim_no_coll}\n\t\\end{subfigure}\n\t\\\\\n\t\\begin{subfigure}[]{1\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width=0.95\\linewidth]{figures/sim_coll.png}\n\t\t\\caption{Example trajectory with collision.}\n\t\t\\label{fig:sim_coll}\n\t\\end{subfigure}\n    \\caption{Pedestrian Simulation. In the beginning of each episode, the pedestrian simulation randomly spawns two pedestrians (dark orange and blue circle) at time $t=0$ at a random $x-y$ position. The simulation uses a pedestrian dynamics model to propagate the positions over time. The  bird's eye perspective of the pedestrian positions is displayed. At each time step the updated pedestrian position is plotted whose color becomes lighter over time. In ~\\cref{fig:sim_no_coll} two pedestrians avoid each other and in~\\cref{fig:sim_coll} two pedestrians collide.} \n    \\label{fig:ped_sim}\n\\end{figure}\n", "meta": {"hexsha": "4850fe4fd363606a70dead610b93cb84d1025ea0", "size": 3286, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/related_work.tex", "max_stars_repo_name": "dkkim93/9.66_collision_final_project", "max_stars_repo_head_hexsha": "67eabc7e16c20905dc171357fdb1edf1f502fed6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paper/related_work.tex", "max_issues_repo_name": "dkkim93/9.66_collision_final_project", "max_issues_repo_head_hexsha": "67eabc7e16c20905dc171357fdb1edf1f502fed6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/related_work.tex", "max_forks_repo_name": "dkkim93/9.66_collision_final_project", "max_forks_repo_head_hexsha": "67eabc7e16c20905dc171357fdb1edf1f502fed6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 102.6875, "max_line_length": 725, "alphanum_fraction": 0.8064516129, "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3223153949524858}}
{"text": "\\subsection{Vectors}\n\\label{Vectors}\nA vector is essentially a map \\(f(i)\\) such that given \\(i, 0 \\leq i < n\\), it\nreturns a value of a given type. The main types that \\Q\\ supports are four variants\nof integers (1, 2, 4, and 8 byte) and two variations of floating point (single\nand double precision). In addition, it supports bit vectors and constant length\nstrings. There is limited support for variable length strings, which are used\nprimarily as dictionaries. \n\nNote that \\Q\\ has 6 types of numbers, in contrast with Lua which uses a \nsingle type {\\tt number}, internally a double precision floating point.\nThis is because data bandwidth plays a significant role in determining\nperformance, as illustrated by Nvidia's\nintroduction of half-precision floating point  \\cite{nvidia2017}. The user is\nencouraged (but not required) to use the smallest type that supports the actual\ndynamic range required. \n\n\nWhen a vector is created, we need to specify (i) its type (ii) whether it has\nnull values (iii) how it will be populuated. We can either (a) ``push'' data to\nit, much like writing to a file in append mode or (b) we can provide a generator\nfunction, which generates a chunk at a time when invoked.\n%% TODO Have not introduced chunk as yet\n\nVectors are evaluated lazily. Hence, a statement like \n{\\tt x = Q.const(\\{len = 10, qtype = I4, val = 0\\})} does not actually create\nten\n4-byte integers with value 0 as one might suspect. Data is populated only when\n{\\tt eval()} is explicity invoked on the vector or the data is \nimplicitly required by some other operator e.g. {\\tt Q.print\\_csv(x)}\n\nVectors are processed in chunks. Consider an expression  like \\(\\sum (a + b\\times\nc)\\), written in \\Q\\ as {\\tt d = Q.sum(Q.add(Q.mul(b,c), a))}.\nWhen {\\tt d} is eval'd, computation alternates between the {\\tt mul, add, sum}\noperators\nprocessing chunks of data at a time until there are\nno more.\nThe chunk size, \\(n_C\\), is chosen large enough that it is amenable to\nvectorization and parallelization and small enough that its memory consumption\nis low.\n\n\nVectors are not mutable (with few exceptions)\nand must be produced sequentially. In other words, the \\(i^{th}\\) element must\nbe produced before the \\({i+1}^{th}\\). Vectors\noperate in ``chunks'' of a fixed size. Let us say that the chunk size is 64K and\nthat we have produced 65K elements. In that case, the current chunk would have\nonly 1K elements. Whether one can get access to an element in the previous chunk\ndepends on whether the vector has been ``memo-ized''. The default behavior, with\na concomitant performance hit, is to memo-ize. However, when the programmer is\naware that the vector will be consumed in a streaming fashion, they set memo\nto false. \n\nMemo-izing is done by appending previous chunks in binary format to a file.\nSubsequent reads of this vector are done by mmap-ing the file. Not all\nalgorithms are readily transformed into streaming operations e.g. sort. There\nare a few cases where we support modifying a vector after it has been fully\nmaterialized by opening it in write mode and mmap-ing it.\n\nMmap-ing gives us the illusion of a linear address space. This is useful to\nincoporate algorithms and libraries that have not been written with streaming in\nmind e.g., \\Q\\ borrows heavily from LAPACK when needed.\n\n\\Q's run time is an alternate approach to ``stream fusion''\n\\cite{Mainland2017}. In\nthat paper, the authors identify this as a technique that allows a compiler to\n``cope with boxed numeric types, handle lazy evaluation, and\neliminate intermediate data structures''.\n", "meta": {"hexsha": "6098d9024af09aaf1aa368cc71c6d939be684d05", "size": 3554, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "DOC/Q_PAPER/SIGMOD_2019/vectors.tex", "max_stars_repo_name": "subramon/qlu", "max_stars_repo_head_hexsha": "2fb8a2b3636dd11e2dfeae2a6477bd130316da47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DOC/Q_PAPER/SIGMOD_2019/vectors.tex", "max_issues_repo_name": "subramon/qlu", "max_issues_repo_head_hexsha": "2fb8a2b3636dd11e2dfeae2a6477bd130316da47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-07-29T16:48:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-26T23:47:22.000Z", "max_forks_repo_path": "DOC/Q_PAPER/SIGMOD_2019/vectors.tex", "max_forks_repo_name": "subramon/qlu", "max_forks_repo_head_hexsha": "2fb8a2b3636dd11e2dfeae2a6477bd130316da47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2015-05-14T22:34:13.000Z", "max_forks_repo_forks_event_max_datetime": "2015-05-14T22:34:13.000Z", "avg_line_length": 51.5072463768, "max_line_length": 83, "alphanum_fraction": 0.7636465954, "num_tokens": 871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3223153949524858}}
{"text": "\\documentclass{article}\n%--------------------------------------------------------\n\\usepackage{hyperref}\n\\usepackage{caption}\n\\usepackage{subcaption}\n\n\\usepackage{graphicx}\n\n\n\\usepackage[left=2.9cm, right=2.9cm, top=3cm, bottom=2cm]{geometry}\n\n\\usepackage{fancyhdr}\n\\pagestyle{fancy}\n\\fancyhf{}\n\\rhead{31.01.2019}\n\\lhead{Pilz GmbH \\& Co. KG}\n\\cfoot{\\thepage}\n\\renewcommand{\\headrulewidth}{0pt}\n\\renewcommand{\\footrulewidth}{0pt}\n\n\\begin{document}\n\\title{Motion Blending}\n\\author{Pilz GmbH \\& Co. KG}\n\\date{31.01.2019}\n\n\\maketitle\n\n\\begin{abstract}\n\\noindent This article describes the techniques used to blend the position and orientation of two robot trajectories within the {\\tt pilz\\_industrial\\_motion\\_planner}\\cite{pilztrajectorygeneration} ROS package.\n\\end{abstract}\n\n\n\\newpage\n\n\\section{Position blending}\n\n\\subsection{Introduction}\n\nSuppose we have two trajectories $x_1(t)$, $t\\in[0,T_1]$ and $x_2(t)$, $t\\in[0,T_2]$ and we want to make a transition from $x_1(t)$ to $x_2(t)$. The transition window technique assumes that the transition happens in a predefined time window. During this transition window, the resulted trajectory (blending trajectory) is given by:\n\\begin{equation}\n\tx_b(t) = x_1(t) + \\alpha(s(t))(x_2(t)-x_1(t)), t \\in [t_0, t_0 + T]\n\\end{equation}\nin which $x_b(t)$ is the transition trajectory. $t_0$ is the start time of transition window and $T$ represents the transition time. $\\alpha(s)$ is the blend function and $s$ is normalized time parameter:\n\\begin{equation}\ns = \\frac{t - t_0}{T}\n\\label{eq:1}\n\\end{equation}\nwhich changes from 0 to 1 during the transition window. Following polynomial is selected as $\\alpha(s)$ so that the boundary conditions at the start and end point of the transition window are fulfilled \\cite{lloyd1993trajectory}:\n\\begin{equation}\n\\alpha(s) = 6s^5 - 15s^4 + 10s^3.\n\\label{eq:2}\n\\end{equation}\n\n\\subsection{Application for blending robot trajectory}\nWe want to move the robot from $p_1$ to $p_2$, then from $p_2$ to $p_3$. $p_2$ is a blending way-point which means that it does not need to be reached exactly. We want the robot moves alongside $p_2$ without stop. The whole process is described below with an one dimensional example.\n\n\\begin{enumerate}\n\t\\item Generate motion trajectories $x_1(t)$ from $p_1$ to $p_2$ and $x_2(t)$ from $p_2$ to $p_3$. $x_1(t)$ and $x_2(t)$ both start and stop with zero velocity/acceleration. Both trajectories start with time zero. As a simple example we generated two one-dimensional linear trajectories in Figure.\\ref{ori_traj}. For robot motion without blending, the two trajectories are executed one after the other, which means $x_2(t)$ needs to be timely shifted by the duration of $x_1(t)$.\n\t\\begin{figure}[ht]%\n\t\\includegraphics[width=0.9\\columnwidth]{figure/original_trajectories.eps}%\n\t\\caption{One-dimensional linear trajectory}%\n\t\\label{ori_traj}\n\t\\end{figure}\n\n\t\\item According to the blending radius $r$, the points $p_{b1}$ on $x_1(t)$ and $p_{b2}$ on $x_2(t)$ which intersects with the blending sphere are computed. We also compute the durations $d_1$ for moving from $p_{b1}$ to $p_2$ on $x_1$ and $d_2$ for moving from $p_2$ to $p_{b2}$ on $x_2$. The transition window should start earliest from the time of $p_{b1}$ on $x_1(t)$ is reached, and ends latest at the time of $p_{b2}$ on $x_2(t)$ is reached. In the example, we take $r=3$ and $p_{b1} = p_{b2} = 5$ (see Figure.\\ref{ori_traj}).\n\n\t\\item Timely shift the $x_2(t)$ and select the transition window time $T$ according to the above rules. In order to avoid stop on the blending trajectory, the time shift $T_s$ of $x_2(t)$ should be smaller than the duration of $x_1(t)$. We now have the second trajectory as $x_2(t-T_s)$ for blending. In the example the duration of $x_1(t)$ is $6s$. Figure.\\ref{blend_case_1} shows a blending case that we shift the $x_2(t)$ with $6s$, which is almost the same as motion without blending. Figure.\\ref{blend_case_2} shows a blending case that we shift the $x_2(t)$ with $3.5s$ and the blending starts at 3.5s, ends at 5.5s. Figure.\\ref{blend_case_3} shows a blending case that we shift the $x_2(t)$ with $4.5s$ and the blending starts at 3.5s, ends at 6.5s.\n\\end{enumerate}\n\nIn the actual implementation, we make the following choice given the durations $d_1$ and $d_2$ inside the blending sphere:\n\\begin{itemize}\n\\item If $d_1\\leq d_2$ we shift exactly to the time when $p_{b1}$ is reached on $x_1$ (when the blending sphere is entered),\n\\item if $d_1>d_2$ we compute $T_s$ such that $T_s+d_2=T_1$. This choice minimizes increases in acceleration/deceleration on the resulting blend trajectory.\n\\end{itemize}\n\n\n\\section{Blending the orientation}\nTo blend the orientation, the method described in \\cite{dantam2014orientation} is used. The equations (18)-(20) in \\cite{dantam2014orientation} are used to calculate the orientation along the blend trajectory. In our application, due to the fact that the orientation change along the original (not blended) trajectories has smooth acceleration and deceleration phases, (18) and (19) from paper \\cite{dantam2014orientation} do not need to be calculated.\\newline\nFor the sake of clarity, it is important to note that our functions for $u_{ij}(t)$ and $u_{jk}(t)$ are different. However, we account for this difference by not explicitly calculating (18) and (19) and using the given samples of the original (not blended) trajectories instead. Furthermore,  (\\ref{eq:2}) is used for $u_{j}(t)$, in other words, $u_{j}(t) = \\alpha(s(t))$.\n\n\n\\begin{figure}[ht]\n\t\\vspace*{-5mm}\n\t\\centering\n\t\\begin{subfigure}[ht]{0.8\\textwidth}%\n\t\t\\centering\n\t\t\\includegraphics[width=0.8\\columnwidth]{figure/blend_case_1.eps}%\n\t\t\\caption{Motion blend case 1: $T_s = 6s$, blending starts at 3.5s, ends at 8s. The resulted blending trajectory comes to a stop in the middle.}%\n\t\t\\label{blend_case_1}%\n\t\\end{subfigure}\n\n\t\\begin{subfigure}[ht]{0.8\\textwidth}%\n\t\t\\centering\n\t\t\\includegraphics[width=0.8\\columnwidth]{figure/blend_case_2.eps}%\n\t\t\\caption{Motion blend case 2: $T_s = 3.5s$, blending starts at 3.5s, ends at 5.5s. The resulted blending trajectory smoothly transits from first trajectory to the second trajectory. The velocity profile has no jumps.}%\n\t\t\\label{blend_case_2}%\n\t\\end{subfigure}\n\n\t\\begin{subfigure}[ht]{0.8\\textwidth}%\n\t\t\\centering\n\t\t\\includegraphics[width=0.8\\columnwidth]{figure/blend_case_3.eps}%\n\t\t\\caption{Motion blend case 3: $T_s = 4.5s$, blending starts at 3.5s, ends at 6.5s. The resulted blending trajectory smoothly transits from first trajectory to the second trajectory. The velocity profile has no jumps.}%\n\t\t\\label{blend_case_3}%\n\t\\end{subfigure}\n\n\\end{figure}\n\n\n\\begin{thebibliography}{9}\n\\bibitem {lloyd1993trajectory}Lloyd, John and Hayward, Vincent \\textit{Trajectory generation for sensor-driven and time-varying tasks}, The International journal of robotics research, 1993\n\\bibitem {dantam2014orientation}Dantam, Neil and Stilman, Mike \\textit{Spherical Parabolic Blends for Robot Workspace Trajectories}, International Conference on Intelligent Robots and Systems (IROS), 2014\n\\bibitem{pilztrajectorygeneration}\\url{https://github.com/ros-planning/moveit/tree/master/moveit_planners/pilz_industrial_motion_planner}\n\\end{thebibliography}\n\\end{document}\n", "meta": {"hexsha": "6238ec8747bc2c90204c03300609175638578830", "size": 7222, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "moveit_planners/pilz_industrial_motion_planner/doc/MotionBlendAlgorithmDescription.tex", "max_stars_repo_name": "lizixroy/moveit", "max_stars_repo_head_hexsha": "4db626d9c3b5d6296b012188a4a0bfe4bddf6bce", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1116, "max_stars_repo_stars_event_min_datetime": "2016-07-29T06:39:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:42:14.000Z", "max_issues_repo_path": "moveit_planners/pilz_industrial_motion_planner/doc/MotionBlendAlgorithmDescription.tex", "max_issues_repo_name": "lizixroy/moveit", "max_issues_repo_head_hexsha": "4db626d9c3b5d6296b012188a4a0bfe4bddf6bce", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2784, "max_issues_repo_issues_event_min_datetime": "2016-07-29T15:19:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T01:35:59.000Z", "max_forks_repo_path": "moveit_planners/pilz_industrial_motion_planner/doc/MotionBlendAlgorithmDescription.tex", "max_forks_repo_name": "tylerjw/moveit", "max_forks_repo_head_hexsha": "39f592037576d5fada0e0b64c27370222c7c286c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 956, "max_forks_repo_forks_event_min_datetime": "2016-07-30T17:03:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:48:31.000Z", "avg_line_length": 62.8, "max_line_length": 757, "alphanum_fraction": 0.7474383827, "num_tokens": 2187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3223153949524858}}
{"text": "\\documentclass[11pt]{scrartcl}\n\\usepackage[sexy]{evan}\n\\usepackage{placeins}\n\\usepackage{ amssymb }\n\\usepackage{verbatim}\n\n\\begin{document}\n\\newcommand{\\Lagr}{\\mathcal{L}}\n\\newcommand{\\Ztran}{\\mathcal{Z}}\n\n\\title{Control Theory: Theory and Applications for Robotics}\n\\subtitle{Including Tricks Learned on the Job}\n\\author{Maverick Zhang}\n\\date{\\today}\n\\maketitle\n\n\\newpage\n\\tableofcontents\n\\newpage\n\n\\section{Introduction}\n\nThis is a paper that I hope will introduce new members to the UC Berkeley and M.I.T. Robotics group to the necessary mathematics and ideas in order to help us out with controlling the robots. A lot of fields intersect at robotics, the biggest of which are mathematics, physics, electrical engineering, mechanical engineering, and computer science. Whenever somebody writes a reference document of some kind, they are always going to be agonizing over how much is too much or too little. The more broad the content, the more easily a person completely unfamiliar to the current field will be able to learn it. The more strict the content, the less. Unfortunately, the tradeoff is that it takes far more effort to cover. \n\n\tMy current plans for this introductory paper will be getting somebody who understands at least AP Calculus BC, and AP Physics C up to the level of a somebody who can intuitively make choices in robotics control theory. As such, I will be making sure understanding (even if it is not rigorous) is put first before rigorous theory. Eventually, sections that are completely rigorous will be written to shore up gaps in understanding. \n\n\tI have to say, while control theory may seem a difficult mathematical creature, the best way to learn it is to play with it yourself. I will be adding notes that will challenge you to understand a concept through experiment, which is the way this theory should be learned.\n\n\tI recommend you read this book in passes. The first pass is the skim. You read quickly trying to understand the ideas behind control theory and robotics. The second pass you should certainly pay closer attention, probably reading proofs in depth and taking as long as it needs to completely explain the proof without this as a reference. Any further passes should be done to ensure you have complete understanding and shoring up any weak points.\n\n\\section{A Fixer Upper: All The Math And Physics You Need Refreshed From High School}\n\nOkay, time to level with you, your Calc BC or Physics C teacher might've been great, but they had a strict timeline to stick to and didn't let you explore some ideas behind these beautiful subjects. I hope that in this section we can get a little more acquainted with these two fields and also remember them a bit better. \n\n\\subsection{Calculus, But Better}\n\nCalculus is a humongous subject. Most of you guys who finished calculus probably thought, ``Wow, that was hard, now it's time to forget all about it,\" or maybe, ``When am I ever going to use this subject?\" Both of these responses are perfectly fine, but I hope that I can at least answer the second question. \n\n\tI think we all agree that word problems in calculus suuuuuuck. It's like, I know you're just disguising a math problem with words to prevent me from answering faster, and that nothing in real life ever uses calculus this way. Well, now let's try to come up with plausible ways to use it. In addition, I want to recast some ideas in calculus in a different perspective.\n\n\\subsubsection{Derivatives}\n\nWe can think of calculus as the mathematics behind approximation. Others might say change, but it is more fundamentally the former. As you should hopefully remember, the main two ingredients in calculus are derivatives and integrals, but I think the third ingredient is *drumroll* \\ldots Taylor Series!\n\n\tI can hear you groaning already. Good thing we won't be using them as annoyingly this time around. The great thing about Taylor series, however much you hate them, is that they are a perfect illustration of this reinterpretation of calculus. The Taylor seriees shows you perfectly how calculus approximates, so let's recast derivatives in terms of these Taylor Series.\n\n\tThe formula for Taylor series is \n\n\\[\n\\sum_{n=0}^{\\infty}\\frac{f^{(n)}(c)(x-c)^n}{n!}\n\\]\nwhich is a basically creates an infinite series made of simple terms power functions that will approximate (most) functions rather well around a point $c.$ For some functions like $\\sin(x)$ or $e^x$, this approximation will eventually approximate the function over all of $\\mathbb{R}$, while with other functions like $1/(1-x)$ it will only work from $(-1,1)$. However, for our purposes, we won't be concerning ourselves with the crazy functions that don't have Taylor series (like $e^{-1/x^2}$ around $0$). Instead, we will only remark that Taylor series approximate a function really well around a certain point. \n\n\tThe existence of Taylor series is intuitive enough, but just because we have an idea doesn't mean it's practical. So with Taylor series, what can we do to understand it better?\n\n\tLet's try to understand what happens when we forget about a huge portion of the series. We chop it off after $n=0$. Alright, so what does our Taylor series do for us? We approximate a function $f$ near $c$ to find that the best approximation is\n\n\\[\nf(x) \\approx f(c) \\quad \\text{when $x$ is near $c.$}\n\\]\n\n%%%Add graph of this%%%\n\n\tThat's pretty unexciting. I think everybody understands that if you want to approximate a function near a point, you can just use that point. What happens when we chop off the Taylor series at $n=1$? We will find something known as the \\vocab{first order approximation} to the function:\n\n\\[\nf(x) \\approx f(c) + f'(c)(x-c) \\quad \\text{when $x$ is near $c.$}\n\\] \n\n\tI think we all agree that this is more exciting. This function is linear in $x$. It is known as the tangent line approximation because it is the line that best kisses the graph at this point. If we examine a graph, it is quite clear that this approximation will let you venture a little bit further than the previous one when approximating. It is from this expression that we can also see why the derivative is so important as the tool of approximation, it is the slope of the tangent line. However, this also shows us \n\n%%%Add Tangent Line%%%\n\t\n\n\n \n\n\\end{document}", "meta": {"hexsha": "c2cd0281d2d14b0559c4ccf1bf8fa8350a6e8bb3", "size": 6281, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "papers/Control-Theory-Theory-and-Applications.tex", "max_stars_repo_name": "0neDividedbyZer0/UCB-MIT-Robotics", "max_stars_repo_head_hexsha": "aeab49714e7f2896360d6bdc6b136e276e94924a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "papers/Control-Theory-Theory-and-Applications.tex", "max_issues_repo_name": "0neDividedbyZer0/UCB-MIT-Robotics", "max_issues_repo_head_hexsha": "aeab49714e7f2896360d6bdc6b136e276e94924a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "papers/Control-Theory-Theory-and-Applications.tex", "max_forks_repo_name": "0neDividedbyZer0/UCB-MIT-Robotics", "max_forks_repo_head_hexsha": "aeab49714e7f2896360d6bdc6b136e276e94924a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 80.5256410256, "max_line_length": 719, "alphanum_fraction": 0.7761502945, "num_tokens": 1425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3223153949524858}}
{"text": "\\XtoCBlock{Exp}\r\n\\label{block:Exp}\r\n\\begin{figure}[H]\\includegraphics{Exp}\\end{figure} \r\n\r\n\\begin{XtoCtabular}{Inports}\r\nIn & Input u\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n\r\n\\begin{XtoCtabular}{Outports}\r\nOut & Result of exp(u)\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n\\subsubsection*{Description:}\r\nComputation of the exponential of the input.\r\n\n% include optional documentation file\r\n\\InputIfFileExists{\\XcHomePath/Library/Math/Doc/Exp_Info.tex}{\\vspace{1ex}}{}\r\n\r\n\\subsubsection*{Implementations:}\r\n\\begin{tabular}{l l}\r\n\\textbf{FiP8} & 8 Bit Fixed Point Implementation\\tabularnewline\r\n\\textbf{FiP16} & 16 Bit Fixed Point Implementation\\tabularnewline\r\n\\textbf{FiP32} & 32 Bit Fixed Point Implementation\\tabularnewline\r\n\\end{tabular}\r\n\r\n\\XtoCImplementation{FiP8}\r\n\\index{Block ID!4848}\r\n\\nopagebreak[0]\r\n% Implementation details\r\n\\begin{tabular}{l l}\r\n\\textbf{Name} & FiP8 \\tabularnewline\r\n\\textbf{ID} & 4848 \\tabularnewline\r\n\\textbf{Revision} & 0.1 \\tabularnewline\r\n\\textbf{C filename} & Exp\\_FiP8.c \\tabularnewline\r\n\\textbf{H filename} & Exp\\_FiP8.h \\tabularnewline\r\n\\end{tabular}\r\n\\vspace{1ex}\r\n\r\n8 Bit Fixed Point Implementation\r\n\r\n% Implementation data structure\r\n\\XtoCDataStruct{Data Structure:}\r\n\\begin{lstlisting}\r\ntypedef struct {\r\n     uint16        ID;\r\n     int8          *In;\r\n     int8          Out;\r\n} EXP_FIP8;\r\n\\end{lstlisting}\r\n\r\n\\ifdefined \\AddTestReports\r\n\\InputIfFileExists{\\XcHomePath/Library/Math/Doc/Test_Exp_FiP8.tex}{}{}\r\n\\fi\r\n\\XtoCImplementation{FiP16}\r\n\\index{Block ID!4849}\r\n\\nopagebreak[0]\r\n% Implementation details\r\n\\begin{tabular}{l l}\r\n\\textbf{Name} & FiP16 \\tabularnewline\r\n\\textbf{ID} & 4849 \\tabularnewline\r\n\\textbf{Revision} & 0.1 \\tabularnewline\r\n\\textbf{C filename} & Exp\\_FiP16.c \\tabularnewline\r\n\\textbf{H filename} & Exp\\_FiP16.h \\tabularnewline\r\n\\end{tabular}\r\n\\vspace{1ex}\r\n\r\n16 Bit Fixed Point Implementation\r\n\r\n% Implementation data structure\r\n\\XtoCDataStruct{Data Structure:}\r\n\\begin{lstlisting}\r\ntypedef struct {\r\n     uint16        ID;\r\n     int16         *In;\r\n     int16         Out;\r\n} EXP_FIP16;\r\n\\end{lstlisting}\r\n\r\n\\ifdefined \\AddTestReports\r\n\\InputIfFileExists{\\XcHomePath/Library/Math/Doc/Test_Exp_FiP16.tex}{}{}\r\n\\fi\r\n\\XtoCImplementation{FiP32}\r\n\\index{Block ID!4850}\r\n\\nopagebreak[0]\r\n% Implementation details\r\n\\begin{tabular}{l l}\r\n\\textbf{Name} & FiP32 \\tabularnewline\r\n\\textbf{ID} & 4850 \\tabularnewline\r\n\\textbf{Revision} & 0.1 \\tabularnewline\r\n\\textbf{C filename} & Exp\\_FiP32.c \\tabularnewline\r\n\\textbf{H filename} & Exp\\_FiP32.h \\tabularnewline\r\n\\end{tabular}\r\n\\vspace{1ex}\r\n\r\n32 Bit Fixed Point Implementation\r\n\r\n% Implementation data structure\r\n\\XtoCDataStruct{Data Structure:}\r\n\\begin{lstlisting}\r\ntypedef struct {\r\n     uint16        ID;\r\n     int32         *In;\r\n     int32         Out;\r\n} EXP_FIP32;\r\n\\end{lstlisting}\r\n\r\n\\ifdefined \\AddTestReports\r\n\\InputIfFileExists{\\XcHomePath/Library/Math/Doc/Test_Exp_FiP32.tex}{}{}\r\n\\fi\r\n", "meta": {"hexsha": "b9947f517bd077ac816e83ec618e45d703b427b9", "size": 2913, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Library/Math/Doc/Exp.tex", "max_stars_repo_name": "AlexisTM/X2C", "max_stars_repo_head_hexsha": "31f39b598afe271a7fd46ef1ee9e06c410b1120c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Library/Math/Doc/Exp.tex", "max_issues_repo_name": "AlexisTM/X2C", "max_issues_repo_head_hexsha": "31f39b598afe271a7fd46ef1ee9e06c410b1120c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Library/Math/Doc/Exp.tex", "max_forks_repo_name": "AlexisTM/X2C", "max_forks_repo_head_hexsha": "31f39b598afe271a7fd46ef1ee9e06c410b1120c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7787610619, "max_line_length": 78, "alphanum_fraction": 0.7133539307, "num_tokens": 933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5544704649604272, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.32231539495248573}}
{"text": "\\chapter{ConFrm}\n\\label{chapter:ConFrm}\n\nConFrm is a framework for proving confidentiality of storage systems. It contains a new confidentiality definition as well as structures such as layer templates, execution semantics among other things to implement file systems with confidentiality proofs. \n\n\\section{Specification: Relatively Deterministic Noninterference}\nFigure \\ref{fig:NI_Matching_Paths} shows that traditional noninterference definition leads to leakage of confidential data when probability of observing a return value is not uniformly distributed. To address this challenge, This thesis introduces a new confidentiality definition that we call \\emph{Relatively Deterministic NonInterference} (RDNI) that takes return value frequencies into account. In the following section we will progressively build this new definition. \n\n\\subsection{Basic Definition}\nNondeterministic noninterference can be interpreted as \"matching\" of executions from equivalent states to equivalent states for some chosen relation between two states \n%\n\\footnote{In reality, nondeterministic noninterference definition does not require relation to be an equivalence. We use \"equivalent states\" instead of \"related states\" to make it clear that it is this relation we are referring to when we say \"equivalent states\" in other chapters.}. \n%\nMore specifically, for each execution from a state, a \"matching execution\" from a equivalent state is an execution with the same return value where resulting states are equivalent as well. Traditional nondeterministic noninterference definition allows multiple executions to be matched with a single execution. For example, in figure \\ref{fig:NI_Matching_Paths}, same execution is matched with two other executions. This flexibility allows matching two set of executions from equivalent states to equivalent states as long as their set of possible return values are the same, but ignores the relative frequencies of the return values.\n\nOne way to ensure that observed return value frequencies are the same is, for each possible return value, requiring that the number of executions that returns it being the same from the equivalent states. This can be achieved by enforcing a 1-to-1 matching between executions from the equivalent states. If an execution can be matched with exactly one execution from an equivalent state, then we can conclude that the number of executions that lead to the same return value from the equivalent states are equal.\n\nSince the nondeterminism is what leads to the multiple possible executions, each execution should be the result of some specific sequence of nondeterministic events. In other words, each sequence of nondeterministic events uniquely identifies an execution, that is, executions are deterministic relative to a sequence of nondeterministic events. Therefore, for a particular sequence of nondeterministic events, there can be at most one execution from each equivalent state. We can enforce a 1-to-1 matching by requiring, for each sequence of nondeterministic events, there should be exactly one matching execution from a equivalent state. \n\nThis requirement is the core idea behind the RDNI definition, and indeed is sufficient to address our challenge. Figure \\ref{fig:RDNI_Matching_Paths} visualizes how the example \\ref{fig:Frequency_Leaking_Program} does not satisfy the new definition, although it satisfies the conventional noninterference. There is no matching execution from the equivalent state if the first generated random bit is 1. There is exactly one execution for from each state when generated bit is 1 and they have different return values.\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[scale=0.5]{templates/figures/matching-paths-rdni.png}\n    \\caption{There is no corresponding execution for the red and black executions.}\n    \\label{fig:RDNI_Matching_Paths}\n\\end{figure}\n\nRDNI formalizes the above notion. RDNI uses an execution relation that takes a sequence of nondeterministic events, which we call an \\emph{oracle}, and refers to it whenever it needs to make a nondeterministic choice (e.g., crashing or successfully executing). One important requirement is that the oracle must capture all the nondeterminism in the system. If all possible nondeterminism in the system is captured by the oracle, it is possible to reason about specific sequence of nondeterministic events by reasoning about the oracle itself. This requirement is enforced by ConFrm through the construction of a layer. Figure \\ref{fig:RDNI_no_recovery} shows the formalization of this approach.\n\n%% I took out users from here but will add at the end.\n\\begin{figure}[H]\n    \\centering\n    \\begin{verbatim}\n    Definition simple_RDNI\n        {T} (p: prog T)\n       (R: state -> state -> Prop) :=\n      forall (o: oracle) (s1 s2: state) (res1: Result T),\n        exec o s1 p res1 ->\n        R s1 s2 ->\n        exists res2, \n            exec o s2 p res2 /\\\n            R (extract_state res1) (extract_state res2) /\\\n            extract_ret res1 = extract_ret res2.\n    \\end{verbatim}\n    \\caption{Simple relatively deterministic noninterference.}\n    \\label{fig:RDNI_no_recovery}\n\\end{figure}\n\nFigure \\ref{fig:RDNI_no_recovery} states that a program $p$ satisfies \\texttt{simple\\_RDNI} for any two states $s_1$ and $s_2$ related by $R$, if there is an execution of $p$ from $s_1$ with oracle $o$ that results in $res_1$, then there is an execution of $p$ from $s_2$ with oracle $o$ that with a result $res_2$ such that, states of $res_1$ and $res_2$ are equivalent by $R$, and return values of $res_1$ and $res_2$ are equal.\n\n\\subsection{Crash, Reboot, and Recovery}\nSince we will be reasoning about crash-safe systems, RDNI should be extended to take crashes, reboots and a recovery into account. We achieve this by changing the execution semantics in the definition with one that captures the entire process of crash-reboot-recovery. There are  important differences in new execution semantics that needs to be explained:\n\\begin{enumerate}\n    \\item Execution relation taking two program arguments, program to run and a recovery program,\n    \\item How the state after a crash followed by a reboot is handled.\n Effects of a reboot of a system may be nondeterministic. One example of this is an asynchronous disk. When a system crashes and reboots, the disk can be in one of the multiple possible states nondeterministically due to buffered and reordered writes. To capture and quantify this source of nondeterminism, we introduce  \\emph{reboot state functions} --- or \\emph{reboot functions} for short. A reboot function takes a state after a crash and returns the state that the system will be after a reboot. Reboot functions make effects of the reboot on a state deterministic, due to the fact that outcome of a function application is deterministic. Similar to the oracles, different outcomes of a nondeterministic reboot is represented by different reboot functions.\n \n \\item Execution semantics of a crash-reboot-recovery process must capture multiple crash and recovery attempts. One way to achieve this is providing semantics for execution of the original program followed by the multiple consecutive executions of a recovery program. Since each execution requires an oracle and each crash requires a reboot function to determine after-reboot state, the new execution semantics will take a list of oracles and a list of reboot functions.\n \\end{enumerate}\n\n We will explain further details of how executions with recovery implemented in the following section. Figure \\ref{fig:RDNI_recovery} shows the formalization with recovery executions.\n\n\\begin{figure}[H]\n    \\centering\n    \\begin{verbatim}\nDefinition RDNI_with_recovery\n    {T} (p: prog T) \n    (rec: prog unit)\n    (R: state -> state -> Prop) :=\n  forall (l_o: list oracle) \n  (l_rf: list (state -> state))\n  (s1 s2: state) (res1: Result T),\n    exec_with_recovery l_o s1 l_rf p rec res1 ->\n    R s1 s2 ->\n    exists res2,\n        exec_with_recovery l_o s2 l_rf p rec res2 /\\\n        R (extract_state res1) (extract_state res2) /\\\n        extract_ret res1 = extract_ret res2.\n    \\end{verbatim}\n    \\caption{RDNI with recovery executions.}\n    \\label{fig:RDNI_recovery}\n\\end{figure}\n\n{\\color{red} One paragraph explaining the changes.}\n\n\n\\subsection{Application specific changes}\nThere are some application specific changes we made to RDNI. First is the addition of a user to the execution semantics. This change allows us to model multi-user systems and discretionary access control.\n\nSecond is conditioning return value equality on a predicate for the user. This way, we can require return value equivalence to hold only for certain users, which is needed to state confidentiality of multi-user systems. For example return value equality is required when the theorem is about adversaries' executions but not needed when it is about normal user's executions.\n\nThird is changing the definition to be about the execution of two programs instead of the same one. This change enables us to reason about functions with different input arguments, because a ConFrm program is a function and its arguments together. \nWith these changes, we reach our final definition for RDNI, which is shown in Figure \\ref{fig:RDNI_final}.\n\n\\begin{figure}[H]\n    \\centering\n    \\begin{verbatim}\n    Definition RDNI\n        {T} (u: user) (p1 p2: prog T) \n        (rec: prog unit)\n       (R: state -> state -> Prop) \n       (cond: user -> Prop):=\n      forall (l_o: list oracle) (l_rf: list (state -> state))\n      (s1 s2: state) (res1: Result T),\n        exec_with_recovery u l_o s1 l_rf p1 rec res1 ->\n        R s1 s2 ->\n        exists res2,\n            exec_with_recovery u l_o s2 l_rf p2 rec res2 /\\\n            R (extract_state res1) (extract_state res2) /\\\n            (cond u -> extract_ret res1 = extract_ret res2).\n    \\end{verbatim}\n    \\caption{Final definition of RDNI}\n    \\label{fig:RDNI_final}\n\\end{figure}\n\n\\subsection{Termination Sensitivity}\nThe RDNI definition requires for each execution, an execution to exist from an equivalent state. This was the case for all the definitions presented so far. This requirement is called \\emph{Termination Sensitivity}. In its essence, termination sensitivity implies that an adversary cannot learn any confidential information by observing if the program terminates or not. An example of a non-termination sensitive implementation could be a function looping infinitely based on some secret bit. If implementation contains such a loop, then adversary who calls the function can learn the value of the secret bit by waiting a reasonable amount of time to see whether the function terminates or not.\n\nMore generally, termination sensitivity is not restricted to infinite loops. Any behavior that causes one execution to \"get stuck\" while another execution finishes will violate termination sensitivity. Which executions can \"get stuck\" depends on how the semantics are defined. For example, if the semantics of a read operation on a disk is defined only for addresses that are in bounds, then any execution that attempts an out-of-bounds access will get stuck. \n\nIt is also worth pointing out that getting stuck is not the same as returning an error for an invalid operation. In the latter case, semantics are still defined. So, in the above example, if the semantics are defined to return an error in case of an out-of-bounds access, then one in-bounds and one out-of-bounds execution would not violate termination sensitivity.\n\nAlthough it captures an important aspect of a possible breach of confidentiality, termination sensitivity is not a necessity in confidentiality specifications. Many different systems in the literature use termination insensitive definitions for their specifications. \\ref{} A termination insensitive definition requires any pair of existing executions from equivalent states to have the same return value and result in equivalent states. However a program now have freedom to get stuck in some equivalent states.\n\nHowever, these definitions are generally variants of deterministic noninterference, where termination insensitive variant is a weaker specification. In the nondeterministic case, termination sensitivity is overly restrictive. The requirement of \\textbf{any} pair of executions from any two equivalent states to have the same return value and also result in equivalent states diminishes power of nondeterminism greatly. For example an abstraction of an allocation function where an unused resource is nondeterministically allocated would not satisfy termination insensitive nondeterministic noninterference. This restriction makes termination insensitive nondeterministic noninterference an unfitting confidentiality specification in many cases.\n\nRelatively deterministic nature of RDNI allows us to define a termination insensitive variant that is not overly restrictive. Formal definition of termination insensitive RDNI can be found in figure \\ref{fig:TI_RDNI} In this variant, pair of executions with the same oracles are allowed to be termination insensitive, but there is no requirement on pair of executions with different oracles. In other words, a pair of executions with different oracles from equivalent states can have different return values and also can result in non-equivalent states. This freedom enables abstractions that are similar to the above example. since return value will be determined by the oracle.\n\n\\begin{figure}[H]\n    \\centering\n    \\begin{verbatim}\n    Definition Termination_Insensitive_RDNI\n        {T} (u: user) (p1 p2: prog T) \n        (rec: prog unit)\n       (R: state -> state -> Prop) \n       (cond: user -> Prop):=\n      forall (l_o: list oracle) (l_rf: list (state -> state))\n      (s1 s2: state) (res1 res2: Result T),\n        exec_with_recovery u l_o s1 l_rf p1 rec res1 ->\n        exec_with_recovery u l_o s2 l_rf p2 rec res2 ->\n        R s1 s2 ->\n        \n        R (extract_state res1) (extract_state res2) /\\\n        (cond u -> extract_ret res1 = extract_ret res2).\n    \\end{verbatim}\n    \\caption{Termination insensitive variant of RDNI}\n    \\label{fig:TI_RDNI}\n\\end{figure}\n\n\\section{Definitions and Meta-theory}\nOn top pf RDNI, ConFrm also includes structures and meta-theory that developers can use to implement confidential and crash-safe storage systems. This portion consists of two parts: (1) support for abstraction, and (2) the meta-theory that provides relevant theorems to prove confidentiality of implementation from the confidentiality of abstraction. We will first present the infrastructure for defining abstractions and then explain the meta-theory.\n\n\\subsection{Abstraction Structures}\n\\paragraph{Cores.}\nConFrm introduces cores as the main way to model the abstract state of the system and the operations that can be performed on it. A core has four components,\n\\begin{enumerate}\n    \\item the state the system\n    \\item the list of possible operations that can be performed,\n    \\item the list of possible nondeterminism tokens,\n    \\item the execution semantics of each operation.\n\\end{enumerate}\n\nAn example core for an in-memory cache can be informally described as\n\\begin{enumerate}\n    \\item the state := a partial function from addresses to data\n    \\item the list of possible operations := \\texttt{read}, \\texttt{write}, \\texttt{evict}, \n    and \\texttt{flush}\n    \\item the list of possible nondeterminism tokens := continue execution, crash here\n    \\item the execution semantics of each operation := ...\n\\end{enumerate}.\n\n{\\color{red}Explain the example?}\n\nAlso, to ensure that tokens capture all the nondeterminism in the semantics, a proof that shows, given a token, execution semantics are deterministic is required.\n  \n\\begin{figure}[H]\n    \\centering\n    \\begin{verbatim}\nRecord Core :=\n  {\n    token : Type;\n    state : Type;\n    operation : Type -> Type;\n    exec: forall T, user -> token -> state ->\n        operation T -> @Result state T -> Prop;\n    \n    exec_deterministic_wrt_token :\n      forall u o s T (p: operation T) ret1 ret2,\n        exec u o s p ret1 ->\n        exec u o s p ret2 ->\n        ret1 = ret2;\n  }.\n    \\end{verbatim}\n    \\caption{Definition of a core}\n    \\label{fig:Core_Definition}\n\\end{figure}\n\n\\paragraph{Crashes.}\nConFrm provides support for crash semantics by defining two different execution results: \\texttt{Finished}, and \\texttt{Crashed}. A \\texttt{Finished} result means that program has successfully completed and contains a state and a return value. A \\texttt{Crashed} result means that the program crashed during its execution and contains only a state, which represents the state of the system after the crash happened but before rebooting.\n\nDevelopers define the crash semantics of the system by defining execution rules that lead to a \\texttt{Crashed} result. It is developer's responsibility to ensure that defined execution semantics correctly models the system's both normal and crash behavior.\n\n\n\\paragraph{Layers.}\nConFrm also includes the machinery that turns a core to a full layer by equipping it with \\texttt{Bind} and \\texttt{Return} operations. This eliminates the repetitive work that must to be done to define layers. It also allows framework to provide core-agnostic theorems and tactics to be used in proofs.\n\nSemantics of the layer are derived from the semantics of its core. New  semantics takes a list of tokens (i.e., an oracle) and consumes exactly one at each step. \n\n{\\color{red} Some of the Bind/Ret semantics displayed here}\n\nConFrm also provides some theorems regarding determinism of an execution as well as relationship between oracles and executions like how two executions relate to each other if one's oracle is a prefix of the other's.\n\n\\paragraph{Recovery semantics.}\nConFrm provides pre-defined recovery semantics for the systems and adds these semantics when it generates a layer from a core. To distinguish recovery semantics from the semantics of the execution of a single program, we will refer to recovery semantics as executing-with-recovery. In ConFrm's recovery model, only two outcomes are possible when executing-with-recovery: (1) execution can finish without any crashes, or (2) execution crashes then recovers after certain number of attempts. To represent these two outcomes, ConFrm uses two types of recovery result: \\texttt{RFinished} and \\texttt{Recovered}. \\texttt{RFinished} corresponds to case (1) and \\texttt{Recovered} corresponds to case (2). Since there is no rule for crashing infinitely many times, the provided semantics implicitly assume that recovery eventually will succeed. \n\n\\begin{figure}[H]\n    \\centering\n    \\begin{verbatim}\nInductive exec_with_recovery :\nforall T, user -> list oracle -> state -> \nlist (state -> state) -> prog T -> prog unit -> \n@Recovery_Result state T -> Prop :=\n    | ExecFinished :\n      forall T (p: prog' T) p_rec\n        u o d d' t,\n        exec u o d p (Finished d' t) ->\n        exec_with_recovery u [o] d [] p p_rec (RFinished d' t)\n    | ExecRecovered :\n      forall T (p: prog' T) p_rec\n        u o lo d d' get_reboot_state l_grs ret,\n        exec u o d p (Crashed d') ->\n        exec_with_recovery u lo (get_reboot_state d') \n            l_grs p_rec p_rec ret ->\n        exec_with_recovery u (o::lo) d (get_reboot_state::l_grs) \n            p p_rec (Recovered (extract_state ret)).\n    \\end{verbatim}\n    \\caption{Recovery semantics in ConFrm}\n    \\label{fig:Recovery_Semantics}\n\\end{figure}\n\nFigure \\ref{fig:Recovery_Semantics} displays the formal definition.\nSemantics for (1) is stated in \\texttt{ExecFinished} rule. It is quite straightforward. If the program successfully executes, then it successfully executes-with-recovery.\nSemantics for (2) is stated in \\texttt{ExecRecovered} rule and more involved. It is inductively defined to capture repeated attempts of recovery until it succeeds. The rule states that, if the original program crashes, and recovery program executes-with-recovery to some result, then original program executes-with-recovery to the state of that result. Execution uses a new oracle and a new reboot function every time a crash-reboot-recovery cycle happens. Therefore, lengths of those lists implicitly determine how many times the recovery will crash until it succeeds.\n\n\\paragraph{Refinements.}\nConFrm's main mechanism for relating abstractions and implementations is refinements. \nConFrm defines a refinement as an object between an implementation layer and a core abstracting it. We extend the standard refinement definition to accommodate both crashes and oracles.\n\nAs shown in figure \\ref{fig:Core_Refinement_Definition}, a refinement has four components that corresponds the four components of a core, and a theorem states that a successful execution preserves the state refinement relation. The four components are\n\\begin{itemize}\n    \\item a \\texttt{compile} function, that turns an  abstract operation to its implementation program,\n    \\item a \\texttt{refines} relation that relates an abstract state to an implementation state,\n    \\item a \\texttt{refines\\_reboot} relation that relates an abstract reboot state to an implementation reboot state,\n    \\item and  \\texttt{token\\_refines} relation that relates an abstract token to an implementation oracle.\n\\end{itemize}\n\n\\begin{figure}[H]\n    \\centering\n    \\begin{verbatim}\nRecord CoreRefinement {O_imp} (L_imp: Layer O_imp) (O_abs: Core) :=\n  {\n    compile_core : forall T, O_abs.(Core.operation) T -> L_imp.(prog) T;\n    \n    refines_core: L_imp.(state) -> O_abs.(Core.state) -> Prop;\n    \n    refines_reboot_core: L_imp.(state) -> O_abs.(Core.state) -> Prop;\n    \n    token_refines: forall T, user -> L_imp.(state) -> \n        O_abs.(Core.operation) T -> (L_imp.(state) -> \n        L_imp.(state)) -> L_imp.(oracle) -> \n        O_abs.(Core.token) -> Prop;\n    \n    exec_compiled_preserves_refinement_finished_core :\n      forall T (p2: O_abs.(Core.operation) T) o1 s1 s1' r u,\n        (exists s2, refines_core s1 s2) ->\n        L_imp.(exec) u o1 s1 (compile_core T p2) (Finished s1' r) ->\n        (exists s2', refines_core s1' s2');\n  }.\n    \\end{verbatim}\n    \\caption{Definition of a core refinement}\n    \\label{fig:Core_Refinement_Definition}\n\\end{figure}\n\nBoth \\texttt{compile} and \\texttt{refines} are part of the standard definition. However \\texttt{refines\\_reboot} and \\texttt{token\\_refines} relations require more explanation.\n\nWe separate \\texttt{refines\\_reboot} from \\texttt{refines} because, in general, \\texttt{refines} relation is too strong to hold for after-reboot states but we also needed a relation between them to ensure that recovery restores the original \\texttt{refines} relation. {\\color{red} Add example here. Cache not having latest value or smth.}\n\nThe \\texttt{token\\_refines} relation is more complicated. On top of the oracle and the token it relates, it takes the following parameters\n\\begin{itemize}\n    \\item a user,\n    \\item an implementation state,\n    \\item an abstract operation,\n    \\item and an implementation reboot function.\n\\end{itemize}\nAll these parameters are necessary to capture intricate relationship between abstract tokens and implementations' crash and recovery behavior. We can demonstrate the roles they play by examining the following example.\n\nAssume that we are abstracting an implementation of a checksum-based log on an asynchronous disk with a \\texttt{write} function.\nA crash during a write to a checksum-based log may leave the log in such a state that whether the \\texttt{write} succeeded or not would depends on which blocks made it to the disk before crash happened (which is determined by the after-reboot state of the implementation). In other words, success of a write after crash depends on (1) state of the disk just after the crash, and (2) state of the disk after reboot. To determine (1), we need to know the user, the starting state, and data being written, which is in the operation. To determine (2), we need to know the reboot function. Therefore, capturing the behavior of the write in this particular case requires all the parameters listed above. Other operations may require some or all of those parameters as well.\n\nSimilar to generating a layer from a core, ConFrm can automatically generate a refinement between two layers given a core refinement between an implementation layer and an abstraction core. A refinement for a layer differs from a refinement for a core in three places. First, \\texttt{compile} function transforms programs from the abstraction layer to implementation layer. Second, \\texttt{token\\_refines} turns into \\texttt{oracle\\_refines}, which relates an abstract oracle and an implementation oracle.\nThird, a finished execution of any compiled program should preserve the refinement. ConFrm also provides \\texttt{recovery\\_oracles\\_refine} relation, which relates list of implementation oracles to list of abstraction oracles by \\texttt{oracle\\_refines} inductively.\n\n{\\color{red} Refinement picture here.}\n\n\\paragraph{Horizontal Compositions.}\nTo enable modular implementations, ConFrm provides automatic derivation of a new, composite core from two given cores via horizontal composition. State of the composite core is a pair that contains the state of each the component cores. This capability allows developers to develop the system in small, self contained parts that can be combined at will when desired without much overhead. A layer derived from a composite ConFrm contains support for \"lifting\" the programs written in a layer of the one of the component cores to the layer of the composite core. Similarly, it allows automatic derivation of a refinement between the two composite layers if a component of first layer is a refinement of a component of the second layer.\n\n\n\\subsection{Meta-theory}\nAt the heart of ConFrm lies the theorem \\ref{fig:RDNI_Transfer_Definition}, which derives the confidentiality of a compiled program from the confidentiality of its abstraction. The theorem reveals sufficient conditions for preserving RDNI through refinement. The two conditions are:\n\n\\begin{enumerate}\n    \\item there should be a simulation between implementation and abstraction with respect to refinement relations, and\n    \\item if a list of implementation oracles refine a list of abstract oracles from a state with the first program, then it should refine the same oracle from any state that is equivalent to the first state with the second program.\n\\end{enumerate}\n\nFirst condition ensures that there is no execution of a compiled program that is not captured by an execution of an abstract program. This is necessary for a property of any abstract execution to imply a property of any implementation execution. If there was an implementation execution that does not correspond to an abstract execution, then it would not be possible to reason about such execution through an abstract execution.\n\nSecond condition can be interpreted as the necessity that abstraction does not inject dependency to the confidential data into abstract oracles. Abstractions modelling some deterministic behaviors of an implementation as nondeterminism is a common pattern. For example, an abstraction of a resource allocator may model the allocation function to return an unused resource nondeterministacally, even though the implementation's behavior is actually deterministic (e.g., returning the first available one). \n\nThis property makes sure that developer does not abstract a behavior that depends on the confidential data in such a way. If such action would be permitted, then two implementation executions from equivalent states with the same implementation oracles could correspond to two abstraction executions with different oracles. In such a case, the noninterference of the abstraction with the same oracles wouldn't be strong enough to establish the same fact in implementation, due to the fact that noninterference of the abstraction does not state anything about executions with different oracles. Formalization of this condition can be seen in figure \\ref{fig:ORS_Definition}.\n\n{\\color{red} Give example for above paragraph.}\n\n\\begin{figure}[H]\n\\centering\n\\begin{verbatim}\nDefinition oracle_refines_same_from_equivalent\n    (u: user) {T} (p1_abs p2_abs: L_abs.(prog) T)\n    rec_abs l_get_reboot_state_imp\n    (equivalent_states_abs: L_abs.(state) -> L_abs.(state) -> Prop) :=\n    \nforall l_o_imp l_o_abs l_o_abs' s1_imp s2_imp,\n\n    refines_equivalent equivalent_states_abs s1_imp s2_imp ->\n\n    recovery_oracles_refine \n        u s1_imp p1_abs rec_abs \n        l_get_reboot_state_imp \n        l_o_imp l_o_abs ->\n\n    recovery_oracles_refine \n        u s2_imp p2_abs rec_abs \n        l_get_reboot_state_imp \n        l_o_imp l_o_abs' ->\n\n    recovery_oracles_refine \n        u s2_imp p2_abs rec_abs \n        l_get_reboot_state_imp \n        l_o_imp l_o_abs.\n\\end{verbatim}\n\\caption{Formalization of oracle refinement being independent of confidential data}\n\\label{fig:ORS_Definition}\n\\end{figure}\n\n\\paragraph{Simulations.}\nThe first condition above states that a simulation must exist between the abstraction and the implementation. Since we introduced oracles and crash-and-recovery into execution relations, we modify the standard simulation definition to accommodate those changes. \n\nAs shown in figure \\ref{fig:Simulation_Definition}, the first change is that the modified simulation definition has three simulation relations, one for the starting states, one for the end states, and one for the oracles. We separate the relation that relates the starting and end state to be able to reason about recovery where the relation that holds at the beginning and at the end are different. \n\nIn the context of RDNI transfer of recovery program, start and end simulation relations coincide with the state refinement relations \\texttt{refines\\_reboot} and \\texttt{refines}, respectively. We also define a two relation variant to use in definition  \\ref{fig:RDNI_Transfer_Definition}, where start and end relations are both \\texttt{refines} relation.\n\nSecond change is that a simulation is defined over an entire execution-with-recovery. This allows simulation relation to be broken temporarily after a crash, as long as it is restored by the recovery process. This change is necessary because crashes may expose states that will never appear during a normal execution. This way, refinement relation can only consider the states that appear during normal execution. How to represent crash states is entirely left to the developer.   \n\n\\begin{figure}[H]\n\\centering\n\\begin{verbatim}\nDefinition Simulation\n   u T (p_abs: L_abs.(prog) T) (rec_abs : L_abs.(prog) unit)\n   l_get_reboot_state_imp\n   l_get_reboot_state_abs\n   R_begin R_end :=\n   \n  forall l_o_imp s_imp  s_imp' s_abs,\n    R_begin s_imp s_abs ->\n   L_imp.(exec_with_recovery) u l_o_imp s_imp\n    l_get_reboot_state_imp (R.(compile) p_abs)\n    (R.(compile) rec_abs) s_imp' ->\n    exists l_o_abs s_abs',\n        recovery_oracles_refine u s_imp p_abs rec_abs l_get_reboot_state_imp l_o_imp l_o_abs /\\\n        L_abs.(exec_with_recovery) u l_o_abs s_abs l_get_reboot_state_abs p_abs rec_abs s_abs' /\\\n        R_end (extract_state_r s_imp') (extract_state_r s_abs') /\\\n        extract_ret_r s_imp' = extract_ret_r s_abs').\n\\end{verbatim}\n\\caption{ConFrm's simulation relation with oracles and execution-with-recovery}\n\\label{fig:Simulation_Definition}\n\\end{figure}\n\n\n\\begin{figure}[H]\n\\centering\n\\begin{verbatim}\nLemma RDNI_transfer:\n  forall O_imp O_abs (L_imp: Layer O_imp) (L_abs: Layer O_abs) \n    (R: Refinement L_imp L_abs)\n    u T (p1_abs p2_abs: L_abs.(prog) T) rec_abs\n    l_get_reboot_state_imp\n    l_get_reboot_state_abs\n    equivalent_states_abs cond,\n\n    RDNI\n      u p1_abs p2_abs rec_abs\n      equivalent_states_abs\n      cond l_get_reboot_state_abs ->\n    \n    Simulation R \n      u p1_abs rec_abs \n      l_get_reboot_state_imp\n      l_get_reboot_state_abs ->\n\n    Simulation R \n      u p2_abs rec_abs \n      l_get_reboot_state_imp\n      l_get_reboot_state_abs ->\n    \n    oracle_refines_same_from_equivalent R \n      u p1_abs p2_abs rec_abs \n      l_get_reboot_state_imp \n      equivalent_states_abs ->\n    \n    RDNI\n      u (R.(compile) p1_abs)\n      (R.(compile) p2_abs)\n      (R.(compile) rec_abs)\n      (refines_equivalent R equivalent_states_abs)\n      cond l_get_reboot_state_imp.\n\\end{verbatim}\n\\caption{RDNI transfer theorem}\n\\label{fig:RDNI_Transfer_Definition}\n\\end{figure}\n\n%%%% SOme conclusion here\n\\iffalse\n\\section{Property Transfers}\n\n\\subsection{RDNI transfer}\n- Required properties\n\n-- SimulationForProgram\n    \n-- abstract oracles exist wrt (AOE)\n\n-- oracle refines same from equivalent (ORS)\n\n-- exec compiled preserves validity (Trivial in our case because all of our top states are valid)\n\n-- Termination Sensitive (TS)\n\n\\subsection{ORS}\n-- have same structure (program flow equivalence) (HSS)\n\n\\begin{minted}{coq}\nLemma token_refines_finished_prefix_eq:\nforall ...,\n\ntoken_refines u s1 op1 grs1 o1 t1 ->\ntoken_refines u s2 op2 grs2 o2 t2 ->\n\nexec u s1 o1 (compile op1) (Finished s1' r1) ->\nexec u s2 o2 (compile op2) (Finished s2' r2) ->\n\nhave_same_structure op1 op2 -> \n\n(exists s1a,refines s1 s1a) ->\n(exists s2a, refines s2 s2a) ->\n\none_prefix_of_other o1 o2 ->\no1 = o2 /\\ t1 = t2.\n\\end{minted}\n\n\\begin{minted}{coq}\nLemma token_refines_crashed_prefix_eq:\nforall ...,\n\ntoken_refines u s1 op1 grs1 o1 t1 ->\ntoken_refines u s2 op2 grs2 o2 t2 ->\n\nexec u s1 o1 (compile op1) (Crashed s1') ->\nexec u s2 o2 (compile op2) (Crashed s2') ->\n\nhave_same_structure op1 op2 -> \n\n(exists s1a,refines s1 s1a) ->\n(exists s2a, refines s2 s2a) ->\n\none_prefix_of_other o1 o2 ->\nt1 = t2.\n\\end{minted}\n\n\\begin{minted}{coq}\nLemma oracle_refines_impl_eq:\nforall ...,\n    oracle_refines u s1 p1 imp_reboot_f o1 oa1 ->\n    oracle_refines u s2 p2 imp_reboot_f o2 oa2 ->\n    \n    refines s1 s1a ->\n    refines s2 s2a ->\n    \n    exec u o1 s1 (compile p1) (Finished s1' r1) ->\n    exec u o2 s2 (compile p2) (Finished s2' r2) ->\n    \n    have_same_structure p1 p2 u s1a s2a ->\n    \n    token_refines_finished_prefix_eq ->\n    \n    one_prefix_of_other o1 o2 ->\n    not_init p1 ->\n    not_init p2 ->\n    \n    o1 = o2 /\\ oa1 = oa2.\n\\end{minted}\n\n\\begin{minted}{coq}\nLemma oracle_refines_independent_from_reboot_function:\nforall ...,\n    exec u o s (compile p) (Finished s' r) ->\n    oracle_refines u s p grs o o_abs ->\n    forall grs', \n      oracle_refines u s p grs' o o_abs.\n\\end{minted}\n\n\\begin{minted}{coq}\nLemma oracle_refines_prefix_finished_not_crashed:\nforall ...,\n    oracle_refines u s1 p1 imp_reboot_f o1 oa1 ->\n    oracle_refines u s2 p2 imp_reboot_f o2 oa2 ->\n    \n    refines s1 s1a ->\n    refines s2 s2a ->\n    \n    exec u o1 s1 (compile p1) (Finished s1' r1) ->\n    exec u o2 s2 (compile p2) (Crashed s2') ->\n    \n    have_same_structure p1 p2 u s1a s2a ->\n    \n    one_prefix_of_other o1 o2 ->\n    not_init p1 ->\n    not_init p2 ->\n    False.\n\\end{minted}\n\nThese are compositional in the sense that proving corresponding properties for \neach operation implies it is true for all programs created from them. \n\n\\subsection{AOE}\n\\fi", "meta": {"hexsha": "571ec0036e824d5562f209340b9d26bfe7b489d9", "size": 35054, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ConFrm Thesis/templates/contents/confrm.tex", "max_stars_repo_name": "Atalay-Ileri/Disksec-Doc", "max_stars_repo_head_hexsha": "28befcf9571b0308bcabd229ab6dcba8acb6c503", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ConFrm Thesis/templates/contents/confrm.tex", "max_issues_repo_name": "Atalay-Ileri/Disksec-Doc", "max_issues_repo_head_hexsha": "28befcf9571b0308bcabd229ab6dcba8acb6c503", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ConFrm Thesis/templates/contents/confrm.tex", "max_forks_repo_name": "Atalay-Ileri/Disksec-Doc", "max_forks_repo_head_hexsha": "28befcf9571b0308bcabd229ab6dcba8acb6c503", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 64.084095064, "max_line_length": 838, "alphanum_fraction": 0.7653334855, "num_tokens": 8190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.32231538639319757}}
{"text": "\\section{Quark or diquark annihilation in hadronic processes.}\n\n\\hspace{1.0em}\nWe consider also hadron-hadron inelastic processes when antiquark or \nantidiquark from hadron projectile annihilate with corresponding quark \nor diquark from hadron target.\nIn this case excitation of one baryonic (string with quark and diquark \nends) or mesonic (string with quark and antiquark ends) is created, \nrespectively. These processes in the Regge theory correspond to cut \nreggeon exchange diagrams. Initial energy $\\sqrt{s}$ \ndependences of these processes \ncross sections are defined by  intercepts of reggeon exchange trajectories.\nFor example $\\sigma_{\\pi^{+}p\\rightarrow S(s)} \\sim s^{\\alpha_{\\rho}(0)-1}$, \n$S$ notes string and $\\alpha_{\\rho}(0)$ is the intercept of $\\rho$ reggeon \ntrajectory. Thus $\\sigma_{\\pi^{+}p\\rightarrow S(s)}\n$ decreases with energy \nrise. Cross sections for other quark and diquark proccesses have simiar \nas $\\sigma_{\\pi^{+}p\\rightarrow S(s)}$ initial energy dependences. \nThus quark and diquark annihilation processes are important at \nrelative low initial energies. Another example of these processes is \n$\\bar{p}p \\rightarrow S$, which is used in the kinetic model to describe \nfinal state of $\\bar{p}p$ annihilation.\nSimulation of such kind process is rather simple. We should randomly \n(according to weight calculated using hadron wave function)\nchoose quark (antiquark) or diquark (antidiquark) from projectile and \nfind suitable (with the same flavor content) partner for annihilation \nfrom target. The created string four-momentum will be equal total reaction \nfour-momentum since annihilated system has small neglected momentum (only \nlow momenta quarks are able to annihilate).\n \nTo determine statistical weights for \n quark annihilation processes are leading to a string production \nand separate them from processes, when two or more strings can be produced we \nuse the Regge motivated total cross section parametrization suggested by\nDonnachie and Landshoff \\cite{DL92}. Using their parametrization the\nstatistical weight for the one string production process is given by\n\\begin{equation}\n\\label{OSE1} W_{1} = \\frac{Y_{hN}s^{-\\eta}}{\\sigma^{tot}_{hN}(s)}\n\\end{equation}\nand statistical weight to produce two and more strings is given by \n\\begin{equation}\n\\label{OSE2} W_{2} = \\frac{X_{hN}s^{\\epsilon}}{\\sigma^{tot}_{hN}(s)},\n\\end{equation}\nwhere hadron-nucleon total cross sections  $\\sigma^{tot}_{hN}(s)$ and its \nfit parameters $Y_{hN}$, $X_{hN}$, which do not depend \nfrom the total c.m. energy squared $s$ and depend on type of\nprojectile hadron $h$ and target nucleon $N$ can be found in \\cite{PDG96}. \nThe reggeon intercept $\\eta \\approx \n0.45$ and the pomeron intercept $\\epsilon \\approx 0.08$.\n", "meta": {"hexsha": "13441462aed1b664a67054a6a95f651e5b9c6319", "size": 2737, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "geant4/hadronic/theory_driven/PartonString/OneStringExcitation.tex", "max_stars_repo_name": "berghaus/cernlib-docs", "max_stars_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-24T12:30:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-24T12:30:01.000Z", "max_issues_repo_path": "geant4/hadronic/theory_driven/PartonString/OneStringExcitation.tex", "max_issues_repo_name": "berghaus/cernlib-docs", "max_issues_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geant4/hadronic/theory_driven/PartonString/OneStringExcitation.tex", "max_forks_repo_name": "berghaus/cernlib-docs", "max_forks_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 54.74, "max_line_length": 78, "alphanum_fraction": 0.771282426, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6654105454764747, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.322311616096689}}
{"text": "%% beamer packages\n% other themes: AnnArbor, Antibes, Bergen, Berkeley, Berlin, Boadilla, boxes, \n% CambridgeUS, Darmstadt, Dresden, Frankfurt, Goettingen, Hannover, Ilmenau,\n%JuanLesPins, Luebeck, Madrid, Malmoe, Marburg, Montpellier, PaloAlto,\n%Pittsburgh, Rochester, Singapore, Szeged, Warsaw\n% other colors: albatross, beaver, crane, default, dolphin, dove, fly, lily, \n%orchid, rose, seagull, seahorse, sidebartab, structure, whale, wolverine,\n%beetle\n\n%\\documentclass[xcolor=dvipsnames]{beamer}\n\\documentclass[table,dvipsnames]{beamer}\n\\usepackage{beamerthemesplit}\n\\usepackage{bm,amsmath,marvosym}\n\\usepackage{listings,color}%xcolor\n\\usepackage[ngerman]{babel}\n\\usepackage{natbib}\n\\usepackage[utf8]{inputenc}\n\\definecolor{shadecolor}{rgb}{.9, .9, .9}\n\\definecolor{darkblue}{rgb}{0.0,0.0,0.5}\n\\definecolor{myorange}{cmyk}{0,0.7,1,0}\n\\definecolor{mypurple}{cmyk}{0.3, 0.9, 0.0, 0.2}\n\n% make a checkmark\n\\usepackage{tikz}\n\\def\\checkmark{\\tikz\\fill[scale=0.4](0,.35) -- (.25,0) -- (1,.7) -- (.25,.15) -- cycle;} \n\n% dot product\n\\usetikzlibrary{arrows,positioning}\n\\tikzset{\n    %Define standard arrow tip\n    >=stealth',\n    % Define arrow style\n    pil/.style={->,thick}\n}\n\n% math stuff\n\\newcommand{\\argmin}{\\operatornamewithlimits{argmin}}\n\n\\lstnewenvironment{code}{\n    \\lstset{backgroundcolor=\\color{shadecolor},\n        showstringspaces=false,\n        language=python,\n        frame=single,\n        framerule=0pt,\n        keepspaces=true,\n        breaklines=true,\n        basicstyle=\\ttfamily,\n        keywordstyle=\\bfseries,\n        basicstyle=\\ttfamily\\scriptsize,\n        keywordstyle=\\color{blue}\\ttfamily,\n        stringstyle=\\color{red}\\ttfamily,\n        commentstyle=\\color{green}\\ttfamily,\n        columns=fullflexible\n    }\n}{}\n\n\\lstnewenvironment{codeout}{\n    \\lstset{backgroundcolor=\\color{shadecolor},\n        frame=single,\n        framerule=0pt,\n        breaklines=true,\n        basicstyle=\\ttfamily\\scriptsize,\n        columns=fullflexible\n    }\n}{}\n\n\\hypersetup{colorlinks = true, linkcolor=darkblue, citecolor=darkblue,urlcolor=darkblue}\n\\hypersetup{pdfauthor={A. Richards}, pdftitle={Intro to probabilistic programming}}\n\n\\newcommand{\\rd}{\\textcolor{red}}\n\\newcommand{\\grn}{\\textcolor{green}}\n\\newcommand{\\keywd}{\\textcolor{myorange}}\n\\newcommand{\\highlt}{\\textcolor{NavyBlue}}\n\\newcommand{\\norm}[1]{\\left\\lVert#1\\right\\rVert}\n\\def\\ci{\\perp\\!\\!\\!\\perp}\n% set beamer theme and color\n\\usetheme{Frankfurt}\n%\\usetheme{Berkeley}\n\\usecolortheme{orchid}\n%\\usecolortheme{seagull}\n\n%% modify the font\n%\\usepackage{fontspec}\n%setting a font\n%\\setsansfont{TeX Gyre Adventor}\n%\\usepackage{newcent}\n\n%% fix the section title for literature\n\\renewcommand{\\bibsection}{\\subsubsection*{\\bibname } }\n\n\\title[Project teams]{Introduction to probabilistic programming \\\\ (with PyMC3)}\n\\author[A. Richards]{A. Richards}\n\\institute{}\n\\date[]{02.08.2017}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{document}\n\\frame{\\titlepage}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame{\n\\footnotesize\n\\tableofcontents\n\\normalsize\n}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Introduction}\n\\subsection{}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame{   \n\\frametitle{Probabilistic programming}\n\\footnotesize\n\\begin{block}{A probabilistic programming language makes it easy to:}\n \\begin{enumerate}\n  \\item write out complex probability models\n  \\item And subsequently solve these models automatically.\n \\end{enumerate}\n \\end{block}\n\n\\begin{block}{Generally this is accomplished by:}\n \\begin{enumerate}\n  \\item Random variables are handled as a \\href{https://en.wikipedia.org/wiki/Language\\_primitive}{primitive}\n  \\item Inference is handled behind the scenes\n  \\item Memory and processor management is abstracted away\n \\end{enumerate}\n \\end{block} \n}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame{ \n\\frametitle{The pros and the cons}\n\\footnotesize\n\\textbf{Why you might want to use probabilistic programming}\n\\begin{enumerate}\n \\item \\keywd{Customization} - We can create models that have built-in hypothesis tests\n \\item \\keywd{Propagation of uncertainty} - There is a degree of belief associated prediction and estimation\n \\item \\keywd{Intuition} - The models are essentially 'white-box' which provides insight into our data\n\\end{enumerate}\n\\textbf{Why you might \\highlt{NOT} want use out probabilistic programming}\n\\begin{enumerate}\n \\item \\keywd{Deep dive} - Many of the online examples will assume a fairly deep understanding of statistics\n \\item \\keywd{Overhead} - Computational overhead might make it difficult to be production ready\n \\item \\keywd{Sometimes simple is enough} - The ability to customize models in almost a plug-n-play manner has to come with some cost. \n\\end{enumerate}\n}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame{ \n\\frametitle{Bayesian Inference}\n\\large \\highlt{Degree of belief} \\\\ \\ \\\\\n\\footnotesize\nYou are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, \\textit{even more difficult}, test too! You are \\highlt{starting to believe} that there may be no bugs in this code...\n\n\\begin{flushleft}\n\\href{https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers}{Bayesian methods for hackers}\n\\end{flushleft}\n\nThis is \\href{http://www.kdnuggets.com/2016/12/datascience-introduction-bayesian-inference.html}{a nice intro to Bayesian thinking done on kdnuggets (using PyMC3)}\n}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame{ \n\\frametitle{Some terminology}\n\\footnotesize\n\\begin{equation}\nP(\\theta|x) = \\frac{P(x|\\theta)P(\\theta)}{P(x)}\n\\end{equation}\n\n\\begin{itemize}\n \\item \\keywd{prior} - $P(\\theta)$ - one's beliefs about a quantity before presented with evidence\n \\item \\keywd{posterior} - $P(\\theta|x)$ - probability of the parameters given the evidence\n \\item \\keywd{likelihood} - $P(x|\\theta)$  - probability of the evidence given the parameters\n \\item \\keywd{normalizing constant} - $P(x)$\n\\end{itemize}\n\n\\begin{itemize}\n \\item $P(\\theta)$: This big, complex code likely has a bug in it. \n \\item $P(\\theta|X)$: The code passed all X tests; there still might be a bug, but it is less likely now.\n\\end{itemize}\n}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame{\n\\begin{center}\n\\includegraphics[scale=0.32]{coin_flip.png}\n\\end{center}\n}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Warm up}\n\\subsection{}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}[fragile]\n\\frametitle{PyMC3}\n\\footnotesize\n\\begin{code}\nimport pymc3 as pm\n\\end{code}\n\n\\begin{itemize}\n \\item Developed by John Salvatier, Thomas Wiecki, and Christopher Fonnesbeck \\citep{Salvatier16}\n \\item Comes with \\href{https://github.com/pymc-devs/pymc3/tree/master/pymc3/examples}{loads of good examples}\n \\item API is is not backwards compartible with models specified in PyMC2\n \\item Can still be run in Python2.7+.\n\\end{itemize}\n\n\\highlt{Basic workflow}\n\\begin{enumerate}\n \\item Define hyperpriors\n \\item Open a model context\n \\item Perform inference\n\\end{enumerate}\n\\end{frame}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame{\n\\frametitle{Markov chain Monte Carlo (MCMC)}\n\\footnotesize\n\\keywd{MCMC}\n\\begin{itemize}\n \\item It is an family of algorithms for obtaining a sequence of random samples from a probability distribution for which direct sampling is difficult.\n \\item The sequence can then be used to approximate the distribution\n \\item It allows for inference on complex models\n\\end{itemize}\n\nA particularly useful class of MCMC, known as Hamliltonian Monte Carlo, requires \\href{https://en.wikipedia.org/wiki/Gradient}{gradient} information which is often not readily available so PyMC3 uses Theano to get around this problem.  Something that has recently made this whole field a lot more interesting is the No-U-turn sampler (NUTS) because there are \\highlt{self-tuning strategies} \\citep{Hoffman14}.\n\\\\ \\ \\\\\nOne of the really nice things about probabilistic programming is that \\highlt{you do not have to know how inference is performed}, but it can be useful.  \n\n\\begin{itemize}\n \\item \\href{http://twiecki.github.io/blog/2015/11/10/mcmc-sampling/}{MCMC for Dummies}\n \\item \\href{https://arxiv.org/pdf/1206.1901.pdf}{More on Hamliltonian MCMC (Not for dummies)}\n \\item \\href{http://twiecki.github.io/blog/2014/01/02/visualizing-mcmc/}{How to animate MCMC (for everyone)}\n\\end{itemize}\n}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}[fragile]\n\\begin{block}{PyMC3 is an improvement over PyMC2}\n\\begin{itemize}\n \\item Intuitive model specification syntax e.g. \\\\\n \\begin{equation*}\n x \\sim N(0,1) \\textrm{ becomes } x = \\textrm{Normal}(0,1)\n \\end{equation*}\n \\item Powerful sampling algorithms such as the \\href{http://arxiv.org/abs/1111.4246}{No U-Turn Sampler}\n \\item \\highlt{Variational inference}: \\href{http://arxiv.org/abs/1506.03431}{ADVI} for fast approximate posterior estimation as well as \\highlt{mini-batch} ADVI for large data sets.\n \\item Relies on \\href{http://deeplearning.net/software/theano}{Theano} which provides:\n \\begin{itemize}\n \\item Numpy broadcasting and advanced indexing\n \\item Linear algebra operators\n \\item Computation optimization and dynamic C compilation\n \\item Simple extensibility\n \\end{itemize}\n \\item Transparent support for \\highlt{missing value imputation}\n\\end{itemize}\n\\end{block}\n\\end{frame}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame{ \n\\frametitle{Getting started}\n\\footnotesize\n\n\\begin{block}{}\n We will be using probabilistic programming with PyMC3 to perform automatic Bayesian inference on user-defined probabilistic models\n\\end{block}\n\\vspace{0.5cm\t}\nThese are some of the best getting started resources out there\n\\begin{itemize}\n \\item \\href{https://github.com/pymc-devs/pymc3}{PyMC3 repo}\n \\item \\href{http://pymc-devs.github.io/pymc3/notebooks/getting_started.html}{Getting started guide}\n \\item \\href{https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers}{Bayesian methods for hackers}\n\\end{itemize}\n\\vspace{0.5cm}\nNow that we have an intuition for Bayesian inference and a general idea of what to expect with PyMC3 lets dive in.\n}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}[fragile]\n\\frametitle{PyMC3}\n\\footnotesize\n\\begin{code}\nimport pymc3 as pm\n\nn,h,alpha,beta,niter = 100,61,2,2,1000\n\n# context management\nwith pm.Model() as model: \n    p = pm.Beta('p', alpha=alpha, beta=beta)\n    y = pm.Binomial('y', n=n, p=p, observed=h)\n\n    start = pm.find_MAP()\n    step = pm.Metropolis()\n    trace = pm.sample(niter, step, start)\n\\end{code}\n\nData $\\rightarrow$ Model context $\\rightarrow$ Priors $\\rightarrow$ Likelihood $\\rightarrow$ Sampler $\\rightarrow$ Inference\n\\vspace{0.5cm}\n\\\\ \\noindent To the notebooks!\n\\end{frame}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame{   \n\\frametitle{Where are we...}\n\\begin{block}{}\n \\begin{itemize}\n  \\item[\\checkmark] Overview\n  \\item[\\checkmark] Coin-flip example\n  \\item[\\checkmark] Estimating the mean and standard deviation of a Normal\n  \\item[\\checkmark] Switchpoint analysis of text messages\n  \\end{itemize}\n\\end{block}\n}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{frame}[fragile]\n\\frametitle{There are more examples..}\n\\begin{block}{}\n But what about linear regression--the classical example??\n\\end{block}\n\nThe linear regression example \\href{http://pymc-devs.github.io/pymc3/notebooks/getting_started.html}{is well explained in the docs}, but I did want to point out that we now have access to GLM style formulations in PyMC3.\n\\vspace{1cm}\n\\begin{code}\nimport pymc3 as pm\n\n...\n\ndata = dict(x=x, y=y)\n\nwith pm.Model() as model:\n    pm.glm.glm('y ~ x', data)\n    step = pm.NUTS()\n    trace = pm.sample(2000, step, progressbar=True)\n\\end{code}    \n\\end{frame}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{PMF}\n\\subsection{}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame{ \n\\frametitle{Recommenders}\n\n\\begin{table}\n\\begin{center}\nWhat will a user \\textit{buy}, \\textit{click}, \\textit{like}...\n\\end{center}\n\\ \\\\ \\ \\\\\n\\begin{tabular}{|l|c|c|c|c|c|c|c|c|}\n\\hline\n        & A  &  B & C & D & E & F & G & ... \\\\\n\\hline        \nFrodo   & 1  &  ? & 2 & 1 & 1 & 4 & 1 & ... \\\\\nSam     & ?  &  ? & 1 & 3 & ? & 3 & 1 & ... \\\\\nMerry   & ?  &  ? & 1 & 1 & ? & 1 & 1 & ... \\\\\nGimli   & 1  &  1 & ? & 1 & ? & 1 & ? & ... \\\\\nLegolas & 1  &  1 & ? & 1 & ? & 1 & ? & ... \\\\\n\\hline\n\\end{tabular}\n\\end{table}\n\n\\begin{itemize}\n \\item Ebay and Amazon who recommends items for purchase\n \\item Movies, dating services, social network feeds, recipes, jokes, hikes, ...\n\\end{itemize}\n}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame{ \n\\footnotesize\n\nThere are numerous types of recommender systems\n\\begin{itemize}\n \\item \\keywd{Popularity} - Most viewed, most well-liked, not customized to users\n \\item \\keywd{User-User} - Recommend items liked by users with similar results\n \\item \\keywd{Item-Item} - Recommend items similar to what the current user rated favorably\n \\item \\keywd{Matrix-Factorization} - Estimate a users underlying preferences\n\\end{itemize}\n-------------------------------------------------------------------------------- \\\\\nTwo of the most commonly implemented varieties are:\n\\begin{itemize}\n \\item \\keywd{collaborative filtering} - Imagine that user 1 and user 2 both like the same 4 science fiction novels we can then infer that if user 1 also likes another similar novel then user 2 will have a good chance of also liking it.\n \\item \\keywd{Content-based recommender} - These systems also make use of extra features associated with the user\n\\end{itemize}\n}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame{ \n\\frametitle{Probabilistic matrix factorization (PMF)}\n\\footnotesize\n\\begin{itemize}\n \\item Probabilistic approach to the collaborative filtering problem that takes a Bayesian perspective \\citep{Salakhutdinov08}.\n \\item The ratings $R$ are modeled as draws from a Gaussian distribution\n \\item We use precision $\\alpha$, a fixed parameter, that reflects the uncertainty of the estimations; the normal distribution is commonly reparameterized in terms of precision, which is the inverse of the variance.\n \\item small precision parameters help control the growth of our latent parameters\n \\end{itemize}\nThe following implementation is modified from the \\href{https://pymc-devs.github.io/pymc3/notebooks/pmf-pymc.html}{example in the PyMC3 documentation}.\n\\vspace{1cm}\nBack to the notebook!\n}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame{ \n\\frametitle{Conclusions}\n\\footnotesize\n\\begin{itemize}\n \\item Our results demonstrate that the mean of means method is our best baseline on our prediction task. \n \\item We are able to obtain a significant decrease in RMSE using the PMF MAP estimate obtained via Powell optimization. \n \\item We illustrated one way to monitor convergence of an MCMC sampler with a high-dimensionality sampling space \n \\item The traceplots using this method seem to indicate that our sampler converged to the posterior.\n \\item Results using this posterior showed that attempting to improve the MAP estimation using MCMC sampling actually overfit the training data and increased test RMSE. This was likely caused by the constraining of the posterior via fixed precision parameters $\\alpha$, $\\alpha U$ and $\\alpha V$.\n\\end{itemize}\n\n\\href{https://gist.github.com/macks22/00a17b1d374dfc267a9a}{this gist} is a working version of a fully Bayesian implementation.\n}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Cool down}\n\\subsection{}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame{ \n\\frametitle{Neural Nets}\n\\begin{block}{Thomas Wiecki}\nHas a \\href{http://twiecki.github.io/blog/2016/06/01/bayesian-deep-learning/}{great blog post talking about exactly how to do this}\n\\end{block}\n\nThe notebook that is provided in this repo has not been significantly modified from  \\href{https://github.com/twiecki/WhileMyMCMCGentlySamples/blob/master/content/downloads/notebooks/bayesian_neural_network.ipynb}{its original form}.  Although, check the original repository for the latest version.\n}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame{\n\\begin{center}\n\\includegraphics[scale=0.5]{../notebooks/nn-0.png}\n\\end{center}\n}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame{\n\\begin{center}\n\\includegraphics[scale=0.5]{../notebooks/nn-1.png}\n\\end{center}\n}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame{\n\\begin{center}\n\\includegraphics[scale=0.5]{../notebooks/nn-2.png}\n\\end{center}\n}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame{ \n\\frametitle{Another take on probabilistic programming}\n\\footnotesize\n\\begin{block}{}\n Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, \\highlt{a probabilistic program is run in both the forward and backward direction}. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.\n\\end{block}\n\\vspace{1cm}\n\\href{https://plus.google.com/u/0/107971134877020469960/posts/KpeRdJKR6Z1}{Why Probabilistic Programming matters? (Beau Cronin)}\n}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame{   \n\\frametitle{What did we cover again?}\n\\begin{block}{}\n \\begin{itemize}\n  \\item[\\checkmark] Overview\n  \\item[\\checkmark] Coin-flip example\n  \\item[\\checkmark] Estimating the mean and standard deviation of a Normal\n  \\item[\\checkmark] Switchpoint analysis of text messages\n  \\item[\\checkmark] Probabilistic matrix factorization\n  \\item[\\checkmark] Probabilistic neural networks\n  \\end{itemize}\n\\end{block}\n}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame{ \n\\frametitle{Where to go from here}\n\\footnotesize\n\nExamples, examples, examples...\n\\begin{itemize}\n \\item \\href{https://github.com/pymc-devs/pymc3}{PyMC3 repo}\n \\item \\href{http://pymc-devs.github.io/pymc3/notebooks/getting_started.html}{Getting started guide}\n \\item \\href{https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers}{Bayesian methods \nfor hackers}\n  \\item \\href{http://twiecki.github.io}{Blog by Thomas Wiecki}\n  \\item \\href{http://www.amazon.com/Doing-Bayesian-Analysis-Second-Edition/dp/0124058884/ref=dp_ob_title_bk}{Doing Bayesian Data Analysis by John Kruschke}\n  \\item \\href{https://github.com/markdregan/Bayesian-Modelling-in-Python}{Resource by Mark Dregan}\n\\end{itemize}\n\nThere is also \\href{https://github.com/stan-dev/example-models/wiki}{PyStan} (\\href{http://www.stat.columbia.edu/~gelman/research/unpublished/stan-resubmit-JSS1293.pdf}{Stan paper})\n}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame[allowframebreaks]{  \n\\frametitle{References}\n\\begin{tiny} \\bibliography{pp.bib}\n\\bibliographystyle{apalike}         % Style BST file\n\\end{tiny}\n}\n\n\\end{document}", "meta": {"hexsha": "497d4d14b267e7a46dfa3b9a7a5b0f033c106993", "size": 20383, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "slides/probabilistic-programming-intro.tex", "max_stars_repo_name": "GalvanizeDataScience/probabilistic-programming-intro", "max_stars_repo_head_hexsha": "9e007b6ae8e9d0ca2aff6c3c5e00c0aa4c012595", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2017-02-08T04:18:46.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-10T14:33:13.000Z", "max_issues_repo_path": "slides/probabilistic-programming-intro.tex", "max_issues_repo_name": "zipfian/probabilistic-programming-intro", "max_issues_repo_head_hexsha": "9e007b6ae8e9d0ca2aff6c3c5e00c0aa4c012595", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slides/probabilistic-programming-intro.tex", "max_forks_repo_name": "zipfian/probabilistic-programming-intro", "max_forks_repo_head_hexsha": "9e007b6ae8e9d0ca2aff6c3c5e00c0aa4c012595", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2017-02-09T01:06:04.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-09T06:09:29.000Z", "avg_line_length": 39.9666666667, "max_line_length": 567, "alphanum_fraction": 0.6465191581, "num_tokens": 5222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.32226613094138096}}
{"text": "\\documentclass{article}\n\n\\usepackage[english]{babel}\n\\usepackage{filecontents}\n\\usepackage[letterpaper,top=2cm,bottom=2cm,left=3cm,right=3cm,marginparwidth=1.75cm]{geometry}\n\n\\usepackage{amsmath}\n\\usepackage{csquotes}\n\\usepackage{graphicx}\n\\usepackage{amsthm}\n\\usepackage{amsfonts}\n\n\\usepackage[colorlinks=true, allcolors=blue]{hyperref}\n\n\\usepackage{biblatex}\n\\begin{filecontents*}[overwrite]{general.bib}\n @article{fokkink2005simplifying,\n  title={Simplifying Itai-Rodeh leader election for anonymous rings},\n  author={Fokkink, Wan and Pang, Jun},\n  journal={Electronic Notes in Theoretical Computer Science},\n  volume={128},\n  number={6},\n  pages={53--68},\n  year={2005},\n  publisher={Elsevier}\n}\n\\end{filecontents*}\n\\addbibresource{general.bib}\n\\nocite{*}\n\n\\usepackage{indentfirst}\n\n\\usepackage{cleveref}\n\\newtheorem{lemma}{Lemma}\n\\newtheorem{theorem}{Theorem}\n\\begin{document}\n\\section*{Itai-Rodeh Leader Election for Anonymous Rings}\n\n\\subsection*{Introduction}\nItai-Rodeh leader election algorithm is a probabilistic leader election algorithm for anonymous unidirectional rings with asynchronous communication. Additionally, the size of the ring is known to all processes.\n\nProcesses select random identities from a finite domain (of size bigger than $1$). Processes with the largest identities start another new election rounds, select new identities, and continue broadcasting messages until a leader is elected. Processes with smaller identities became passive that only pass on the messages they receive. It is assumed that the size of the ring is known to all processes so that each process can recognize its own message. The Itai-Rodeh algorithm terminates with probability one, and eventually, exactly one leader is elected. The expected number of messages is at most $O(n^2)$.\n\n\\subsection*{The algorithm}\n\\subsubsection*{Process $i$ maintains:}\n\\begin{itemize}\n    \\item $id_i \\in \\{1, \\ldots , k\\}$ --- random identity of a process selected anew each round\n    \\item $state_i \\in \\{active,\\ passive,\\ leader\\}$\n    \\item $round_i \\in \\mathbb{N}^+$ --- represents the number of the current election round\n    \\item[$\\star$] additionally process keeps track of number of the messages it sent, received and whether leader was selected to properly terminate\n\\end{itemize}\n\n\\subsubsection*{Message format:}\n\\begin{itemize}\n    \\item $id$ --- information about the original sender\n    \\item $round$ --- information about the original sender\n    \\item $hop$ --- distance that a message travelled\n    \\item $bit$ --- whether there exist identical process to the original sender (need to select new identity)\n    \\item[$\\star$] additionally message id of the preceding process is send to properly terminate\n\\end{itemize}\n\n\\subsubsection*{Procedures}\nPrecise description can be found on page 5 in \\cite{fokkink2005simplifying}. I will only describe an algorithm with words for simplicity.\n\n\\textbf{Initialization:} all processes are active, and each process pi randomly selects its identity $id_i$ and sends the message $(id_i,\\ 1,\\ 1,\\ true)$\n\n\\textbf{Passive process:} Upon receipt of a message, passes on the message, increasing the $hop$ counter by one.\n\n\\textbf{Active process:} Upon receipt of a message $(id,\\ round\\ hop,\\ bit)$ behaves according to the following steps:\n\\begin{itemize}\n    \\item if a process receives message from itself and $bit == true$, then becomes leader\n    \\item else if a process receives message from itself and $bit == false$, then selects new identity, moves to another round and sends the message $(id_i,\\ round_i,\\ 1,\\ true)$\n    \\item else if a process receives a message from the identical process then passes it on with $bit == false$ and increased $hop$ counter\n    \\item else if the process receives a message with pair $(round,\\ id)$ lexicographically bigger than itself, then it becomes passive and passes on message with increased $hop$ counter\n    \\item else purges the message\n\\end{itemize}\n\n\\clearpage\n\n\\subsection*{Correctness}\nFirst, let's consider a simpler case in which the algorithm was lucky, and each process's identity is different. Then we would get a problem of leader election for a unidirectional ring with asynchronous communication but this time with unique identities. No $bit$ would change. No process would advance to round 2. Itai-Rodeh algorithm would be reduced to Chang and Roberts algorithm for leader selection.\n\nIn the general case, an algorithm has $round$'s and $bit$'s are tracking information about duplicate $id$'s.  On the ring, until a leader is elected there always exists a message with lexicographically largest pair $(round,\\ id)$ that travels to its owner (maybe a few of them). If there exists at least one process lexicographically smaller than this message and it reaches him, then one more process will become passive bringing us a step closer to electing a leader. Otherwise, all the processes will move to the next round and with some luck, some processes will become passive. Eventually, the leader will be elected. \n\nIf there exist at least $2$ active processes in the same round and the domain of drawing identities is of size $2$ then the probability that they drew different $id$'s is at least $\\frac{1}{2}$. Furthermore, the probability that a lexicographically bigger message reaches a lexicographically smaller process to make him passive is at least $\\frac{1}{2}$. With a number of rounds converging on infinity probability of a single process becoming passive converges to $1$. With a finite number of processes probability of algorithm terminating equals $1$.\n\n\\subsection*{Complexity analysis}\n\nIn the worst-case scenario domain of identities equals $\\{0,1\\}$. Let $n$ be a number of processes. Then expected number of processes with identity $1$ in the first round equals $\\frac{n}{2}$. In each following round number of active processes will be reduced by half. The expected number of rounds equals $\\log n$.\n\nAll the messages that reach its owner have to travel the way around the ring. Consequently, in a round with $k$ active processes, there will be $kn$ messages. \n\nThen the formula for an expected total number of messages throughout the algorithm will be:\n$$\nO\\left(n\\left(n + \\frac{n}{2} + \\frac{n}{4} + \\ldots + 1 \\right)\\right) = O(n^2)\n$$\n\n\\printbibliography\n\n\\end{document}", "meta": {"hexsha": "3e41ba3f43cd2250f9b6fdf5bb3789e04012f696", "size": 6298, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "text/1126923/async_itai_rodeh.tex", "max_stars_repo_name": "mateuszpach/distributed-framework", "max_stars_repo_head_hexsha": "b42edf435753d2677f2a0cf614ab2c1902affec4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "text/1126923/async_itai_rodeh.tex", "max_issues_repo_name": "mateuszpach/distributed-framework", "max_issues_repo_head_hexsha": "b42edf435753d2677f2a0cf614ab2c1902affec4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "text/1126923/async_itai_rodeh.tex", "max_forks_repo_name": "mateuszpach/distributed-framework", "max_forks_repo_head_hexsha": "b42edf435753d2677f2a0cf614ab2c1902affec4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 62.98, "max_line_length": 623, "alphanum_fraction": 0.7683391553, "num_tokens": 1519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.511716619597144, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.3222661296533569}}
{"text": "\\pdfoutput=1 % only if pdf/png/jpg images are used\n\\documentclass{JINST}\n\n\n\\title{New Approaches to Uniform Boosting}\n\n\\author{\nAleksandar Bukva, \nVladimir Gligorov$^d$,\nAlex Rogozhnikov$^{a,b}$\\thanks{Corresponding author.}~ ,\nAndrey Ustuzhanin$^b$ and\nMike Williams$^c$\\\\\n\\llap{$^a$}Lomonosov Moscow State University, Moscow, Russia\\\\\n\\llap{$^b$}Yandex LLC, Moscow, Russia\\\\\n\\llap{$^c$}Massachusetts Institute of Technology, Cambridge, MA, United States \\\\\n\\llap{$^d$}Organisation Europ\\'eenne pour la Recherche Nucl\\'eaire (CERN), Geneva, Switzerland  \\\\\nE-mail: \\email{alex.rogozhnikov@yandex.ru}}\n\n\n\\abstract{\n% Abstract must be short enough to appear in this page together with title, authors, their addresses and keywords.\nThe use of multivariate classifiers has become commonplace in particle physics. \nTypically, a series of classifiers is trained rather than just one to enhance the performance; this is known as boosting. \n\nIn some applications of high energy physics (i.e., amplitude analyses) \nclassifiers should not only optimize some integrated figure of merit, but produce a uniform selection efficiency in a space of selected physical variables.\nRecently uBoost technique of boosting was proposed which addresses this issue.\n\nIn this paper we introduce several approaches to measure the uniformity of efficiency and propose new boosting techniques.\n}\n\n\n\n\n\n% AMS packages:\n\\usepackage{amsmath, amsthm, amsfonts}\n\n\n% Theorems\n%-----------------------------------------------------------------\n\n\\newtheorem{thm}{Theorem}[section]\n\\newtheorem{cor}[thm]{Corollary}\n\\newtheorem{lem}[thm]{Lemma}\n\\newtheorem{prop}[thm]{Proposition}\n\\theoremstyle{definition}\n\\newtheorem{defn}[thm]{Definition}\n\\theoremstyle{remark}\n\\newtheorem{rem}[thm]{Remark}\n\n\\def\\RR{\\mathbb{R}}\n\\def\\ZZ{\\mathbb{Z}}\n\\newcommand{\\abs}[1]{\\left\\vert#1\\right\\vert}\n\\newcommand{\\sgn}{\\operatorname{sgn}}\n\n\n%-----------------------------------------------------------------\n\n\n\\begin{document}\n\\maketitle\n\n\n\\section{Introduction}\n\nMethods of machine learning are playing a important role in particles physics nowadays, in particular, multivariate analysis (MVA). \nDifferent classifiers like boosted decision trees (BDTs) and artificial neural networks (ANNs) are often used as an important step in analysis selection criteria. \n\nBDTs are now even used in software triggers [link]. The main point of boosting technique is training many simple classifiers and building a composition of their outputs.\nClassifiers are trained one-after-another, their inputs are augmented in such a way that new classifier should target more at those events which were poorly classified by previous ones. The resulting classifier obtained by combining them often much more powerful, than individual ones.\n\n\nIn practice, however, there are some restrictions that trained classifier should meet (apart from having good classification quality, which is usually measured by some integrated FOM). For example, in an amplitude analysis obtaining a uniform efficiency in a multivariate space of physics variates, i.e., variates that are of physical interest, is often times more important than any integrated FOM based on the total amount of signal and background. Such analyses often have many variates in which a uniform efficiency is desired. A uniform efficiency reduces systematic uncertainties and helps maintain sensitivity to all hypotheses being tested.\n\nThe one approach that was already proposed is uBoost (uniform BOOSTing) --- a modification of AdaBoost algorithm [link]\n\nWhy do we need such algorithms:\n\n\\begin{enumerate}\n\t\\item The result of classification is stable to check different hypotheses\n\t\\item To get unbiased distribution of signal, this enables us to compute real mass of particle\n\t\\item Not to get fake peak, thus not get a false discovery\n\\end{enumerate}\n\nThe features, along which we want the prediction to be flat, will be referred to as \n\\textit{uniform variables}. In high energy physics these are usually masses.\n\n\\section{Uniformity Measurement}\n\nIn this section we come up with some approaches on how to measure uniformity of prediction. The typical way of 'checking' uniformity of prediction used by physicists \nis fitting the distribution of the events that were classified as signal (or background) over the mass (or some other variable).\n\nThis approach is hardly formalizable, and not automatable --- each time you should assume some kind of distribution. \nIdeally we want to have some easy-to-use out-of-the-box metrics like FOMs in machine learning (like area under the ROC, f1 or ).\n\n\\subsection{Ideal uniformity}\n\nWe start from the simplest case --- when we are fully satisfied by predictions of our classifier. Remember that output of \nclassification is probabilities of each event being a signal and background event, only after we select some cut on probability we get classification.\n\nIdeal uniformity of signal prediction means that whichever cut we select, the efficiency (part of signal event that passed the cut) doesn't depend on uniform variables: \nin every region of uniform variables space the part of signal events that passed the cut is the same.\n\nIn practice, of course, this never happens.\n\nThere is uniformity of predictions on signal and uniformity of efficiency on background, which can be defined one from another by swapping classes. \nIn what follows in this section we are writing about the efficiency on signal events.\n\nA good example of classifier that has close to ideal uniformity is classifier which returns a random probability in [0, 1] range. What a pity: in practice it's absolutely useless.\n\n% The most significant drawback of the upcoming metrics is they are ill-defined if there are not too many events of the named class. \n\n\\subsection{Some Restrictions on Uniformity Metrics}\n\nThere are some additional conditions which we expect metric to meet:\n\\begin{enumerate}\n\\item\nshouldn't depend much on the number of events (i.e., if we randomly select half of the events, the metrics should roughly be the same)\n\\item\nshouldn't depend on the weights renormalization: if we multiply all the weight by some arbitrary number, it shouldn't change at all.\n\\item \ndepends only on the order of predictions, not the exact values of probabilities.\nThis is because we care about which events pass the cut and which don't, not about the exact values of predictions.\n\nExample: correlation of prediction and mass doesn't satisfy this restriction.\n\\item\nparameter stability: if it uses bins, changing the number of bins shouldn't affect the metrics value much, if it uses $k$-nearest neighbors, it should be stable to small deviations of $k$.\n\\end{enumerate}\n\n\n\\subsection{Standard Deviation of Efficiency on Bins (SDE)}\n\n\\def\\bineff{\\text{eff}_\\text{bin}}\n\\def\\binweight{\\text{weight}_\\text{bin}}\n\\def\\globaleff{\\text{eff}}\n\\def\\SDE{\\text{SDE}}\n\\def\\bin{\\text{bin}}\n\n\nLet's split the space of uniform features into bins, the uniformity in these terms is following: when we select some probability cut, \nthe part of signal events that passes the cut is equal in all bins. Assume we selected some cut, then we have global efficiency\n\\[\n\t\\globaleff = \\dfrac{\n\t\t\\text{total weight of signal events that passed the cut}}\n\t\t{\\text{total weight of signal events}}\n\\]\n\nEfficiency in every bin is defined respectively, \n\\[\n\t\\bineff = \\dfrac{\n\t\t\\text{weight of signal events in bin that passed the cut}}\n\t\t{\\text{weight of signal events in this bin}} \n\\]\n\nSo, basically, what we want to have in our dreams:\n\\[\n\t\\bineff = \\text{global efficiency} \\qquad \\forall \\; \\text{bin}\n\\]\n\n\nTo measure how far we are from ideal situation we use standard deviation:\n\\[\n\t\\sqrt{\\sum_{\\bin} \\left( \\bineff - \\globaleff \\right)^2  }\n\\]\n\nWhat is bad in this formula that every bin has some impact in the result, which does not depend on how many events are there, so metrics becomes very unstable to deviations in bins with only few events. To cure this, we add weights to the bins (note that $\\sum_\\bin \\binweight = 1$):\n\\[\n\t\\binweight = \\dfrac{\\text{total weight of signal events in bin}}\n\t\t{\\text{total weight of signal events}},\n\\]\nso we have SDE formula:\n\\[\n\t\\SDE(\\globaleff) = \n\t\\sqrt{\\sum_{\\bin} \\binweight \\times \\left(\\bineff - \\globaleff \\right)^2}. \n\\] \nIn fact, the expression depends on the cut, but for cuts which produce equal efficiency, this is \n\n\nFinally we note that the weighted average of $\\bineff$ is $\\globaleff$:\n\\[\n\t\\globaleff = < \\bineff > =  \\sum_{\\bin} \\binweight \\times \\bineff,\n\\]\nand this is why the introduced metrics was named SDE --- this is a weighted standard deviations of array of bin efficiencies.\n\nBut this is how we measure the non-uniformity for only one fixed cut, to measure the overall non-flatness, we take several global efficiencies (for instance, [0.5, 0.6, 0.7, 0.8, 0.9], because in practice usually we are interested in cuts with high global efficiency) and use \n\\[\n\t\\SDE^2  =  \\frac{1}{k} \n\t\\sum_{\\globaleff \\in [\\globaleff_1 \\dots \\globaleff_k] }  \n\t\t\\text{SDE}^2(\\globaleff)\n\\]\n\nSome other power $p \\neq 2$ can be used as well, but $p=2$ is considered as the default value: \n\\[\n\t\\SDE^p(\\globaleff) = \n\t\\sum_{\\bin} \\binweight \\times \\abs{\\bineff - \\globaleff}^p,\n\\qquad\n\t\\SDE^p  =  \\frac{1}{k} \n\t\\sum_{\\globaleff \\in [\\globaleff_1 \\dots \\globaleff_k] }  \n\t\t\\text{SDE}^p(\\globaleff).\n\\]\n\n\n\n\\subsection{Theil Index of Efficiency}\n\\def\\theil{\\text{Theil}}\n\nOne more measure uses Theil Index frequently used to measure economic inequality:\n\\[\n\t\\theil = \\frac{1}{N} \\sum_i \\frac{x_i}{<x>} \\ln{\\frac{x_i}{<x>}}, \n\t\t\\qquad <x> = \\frac{1}{N} \\sum_i x_i\n\\]\nIn our case we have to alter formula a bit to take into account that different bins have different impact, thus the formula turns into\n\\[\n\t\\theil(\\globaleff) = \\sum_\\bin \\binweight \\; \\frac{\\bineff}{\\globaleff} \\; \\ln{\\frac{\\bineff}{\\globaleff}}\n\\]\n\nTODO how to combine Theil for different global efficiencies?\n\\[\n\t\\theil = ??? \\text{from} \\theil(\\globaleff)\n\\]\n\n\\subsection{Distribution Similarity Approach}\n\\label{sec:similarity}\n\nLet's start from reformulation of what is uniform predictions in signal. First we split all signal events into some bins in uniform variables. There is some empirical distribution $F_\\bin$ of predictions in each bin. Ideal uniformity means that all the distributions $F_\\bin$ are equal and hence equal to the global distribution $F(x)$. \n\nTo 'measure' non-flatness we can use some distribution distance, like Kolmogorov-Smirnov:\n\\[\n\t \\sum_{\\bin} \\binweight \\max_x \\abs{F_{\\bin}(x) - F(x)},\n\\]\nbut Cram\\'er--von Mises similarity is more informative (usually $p=2$ is used):\n\\[\n\t \\sum_{\\bin} \\binweight \\int \\abs{F_{\\bin}(x) - F(x)}^p dF(x),\n\\]\n\nThe good point is we don't need to select some global efficiencies like in the other metrics.\n\n\n\\subsection{Connection Between SDE and Distance Similarity Approach}\n\nSDE and DSA based on Cram\\'er--von Mises similarity can be shown to have connection.\nLet's consider the SDE with global efficiencies $= [1/N, 2/N, \\dots, N/N]$. In the limit $N \\to \\infty$\n\\[\n\t\\lim_{N \\to \\infty} \\SDE^2 = \n\t\\lim_{N \\to \\infty} \\frac{1}{N} \\sum_{\\globaleff}\\SDE^2(\\globaleff) = \n\t\\int_0^1 \\SDE^2(\\globaleff) d\\, \\globaleff = \n\t\\int_0^1 \\sum_{\\bin} \\binweight \\abs{\\bineff - \\globaleff}^2 d\\, \\globaleff\n\\]\n\nFrom the other side, we can write the expression for similarity-based measure (for $p=2$) \n\\[\n\t\\sum_{\\bin} \\binweight \\int \\abs{F_\\text{bin}(x) - F(x)}^2 dF(x) =\n\t\\int \\sum_{\\bin} \\binweight \\abs{F_\\text{bin}(x) - F(x)}^2 dF(x) \n\\] The hard thing now is to believe this is literally the same and these two expressions are equal.\n\n\n\\subsection{Knn-based modifications}\n\n\\def\\knni{\\text{knn}(i)}\n\\def\\effknni{\\text{eff}_{\\knni}}\n\\def\\weightknni{\\text{weight}_{\\knni}}\n\\def\\Fknn{F_{\\knni}}\n\n\\def\\knnSDE{\\text{knnSDE}}\n\nThough operating with bins is usually both simple and very efficient, \nin many cases it is hard to find optimal size of bins in the space of uniform variables (specifically in the case of more than two dimensions).\nOne more situation when bins-based approach fails, is when we have too few events to obtain a good statistics at least in several bins.\n\nIn these cases we can switch to $k$-nearest neighbors: for each signal event we find $k$ nearest signal events (including the event itself) in the space of uniform variables. Now we can compute the efficiency $\\effknni$, empirical distribution $\\Fknn$ of nearest neighbors. \nThe weights for $\\knni$ are proportional to the total weight of events in $\\knni$:\n\\[\n\t\\weightknni = \\alpha \\sum_{j \\in \\knni} w_j, \\qquad \\alpha^{-1} = \\sum_i \\sum_{j \\in \\knni} w_j,\n\\]\nso again weights are normed to 1: $\\sum_{i} \\knni = 1$. \n\nNow we are ready to write knn version of SDE:\n\\[\n\t\\knnSDE^2(\\globaleff)\n\t\t= \\sum_{i \\in \\text{events}} \\weightknni \\abs{\\effknni - \\globaleff}^2\n\\]\n\\[\n\t\\knnSDE^2 = \\sum_{\\globaleff \\in [\\globaleff_1, \\dots \\globaleff_k]}\n\t\t\\knnSDE^2(\\globaleff),\n\\]\nknn version of Theil index of Efficiency\n\\[\n\t\\text{knnTheil}(\\globaleff) = \\sum_{i \\in \\text{events}} \\weightknni \\; \\frac{\\effknni}{\\globaleff} \\; \\ln{\\frac{\\effknni}{\\globaleff}}\n\\]\n\\[\n\t\\text{knnTheil} = ??? \\text{knnTheil}(\\globaleff)\n\\]\nand knn version of similarity-based measure:\n\n\\[\n\t \\sum_{i \\in \\text{events}} \\weightknni \\int \\abs{\\Fknn(x) - F(x)}^p dF(x),\n\\]\n\n\n$K$-nearest neighbors approach suffers from the other drawback: the impact of different events has very little connection with the weights, because some events are met in knn of other events much more frequently while the other.\nThis effect can be suppressed by dividing initial weight of the event by the number of times it is met in knn. \n\n\n\n\n\\subsection{Advantages and Disadvantages of Different Metrics}\n\n... TODO, here some plots with comparison, maybe timings ...\n\n\n\\section{Approaches Proposed}\n\n\\subsection{Mean Ada Boost}\n\nThis is a modification of AdaBoost algorithm. In AdaBoost one multiplies weights in such a way:\n\\[\n\tw_i = w_i \\times \\exp[-y_i \\, \\text{score}_i],\n\\]\nto enlarge the weights of poorly classified events ($y_i$ is $+1$ for signal and $-1$ for background).\n\nBut now we use the mean of prediction of $k$ nearest neighbors (of the same class)\n\\[\n\tw_i = w_i \\times \\exp[-y_i \\, \\dfrac{1}{k} \\sum_{j \\in \\knni} \\text{score}_j]\n\\]\nThus boosting focuses not on the events that were poorly classified, but on the regions with poor classification.\n\n\n\\subsection{Gradient Boosting with AdaLoss Modification (knn-Ada)}\n\n\\def\\score{\\text{score}}\n\\def\\knn{\\text{knn}}\n\\def\\FL{\\text{FL}}\n\nGradient boosting on trees is widely used algorithm[link], it's built upon decision tree regressors with usage of some loss function. \n\nLet's start with examples. One of the popular losses used is AdaLoss:\n\\[\n\t\\sum_{i \\in \\text{events}} w_i \\times \\exp [- \\score_i \\, y_i] \n\\]\nwhere $y_i$ is either +1 (for signal events) or -1 (for background events). Good classification supposes that signal events should have large positive scores, while background ones should have large negative.\n\nThe predictions of separate regressors are simply summed up to form a score:\n\\[\n\t\\score_i = \\sum_{r \\in \\text{regressors}} \\text{pred}_r(i),\n\\]\nwhich can be 'translated' into probabilities by logistic function.\n\nSo the goal of algorithm is now to minimize the loss function. At each stage it trains one more regressor, which should decrease the value of loss, the most vivid way is to train it on negative gradient of loss. In the case of AdaLoss this can be done pretty easy:\n\\[\n\t-\\dfrac{\\partial \\, \\text{AdaLoss}}{\\partial \\, \\score_i} = w_i \\, y_i \\exp[- \\score_i \\, y_i],\n\\]\nso it is positive for signal events, negative for background events and has larger modulus for the events which are poorly classified.\n\nAfter a new tree was built, it's output is altered: for each leaf we can compute such a value, that the result will give the smallest possible value for loss.\n\n...computation of optimal value goes here...\n\nThis loss function can be easily modified to take in account not only the score for individual elements, but also 'finds' regions with lower-than-average quality.\n\n\\[\n\t\\text{knnAdaLoss} = \\sum_{i \\in events} \\exp[-y_i \\times \\sum_{j \\in \\text{knn}(i)} \\score_j],\n\\]\nwhere the index $j$ goes over the $k$ nearest neighbors of $i$th event, which belongs to the same class (signal or background).\n\nWe can introduce a supplementary sparse matrix $A \\in \\RR^{N \\times N}$ ($N$ is number of events), which is defined as \n\\[\na_{ij} = \\begin{cases} \n1, & j \\in \\knn(i), \\text{ events $i$ and $j$ belong to the same class} \\\\\n0, & \\text{otherwise},\n\\end{cases}\n\\] so the loss can be written as\n\\[\n\t\\text{knnAdaLoss} = \\sum_i \\exp [- y_i \\sum_j a_{ij} \\, \\score_j ],\n\\]\nit's negative gradient is easily computed:\n\\[\n\t-\\dfrac{\\partial \\, \\text{knnAdaLoss}} {\\partial \\, \\score_k} = \n\t y_k \\, \\sum_i a_{ik} \\exp [- y_i \\sum_j a_{ij} \\, \\score_j ],\n\\]\nfrom this we can see that new algorithm will pay more attention to the events, which has poorly classified neighbors (and neighbors of neighbors). The named loss targets to obtain uniformity in both signal and background.\n\nAnd the post-correction can be handled by using second-order Newton-Raphson optimization step \n\n... TODO computation of optimal value goes here ...\n\nOne can note, that the matrix $A$ doesn't need to be necessarily square. One can introduce $M$ groups of events (which may intersect), each group consists of several events with close uniform variables (and close events). Then one introduces $A \\in \\RR^{M \\times N}$:\n\\[\n\ta_{mj} = \\begin{cases}\n\t\t1, & \\text{event $j$ is in group $m$} \\\\\n\t\t0, & \\text{otherwise}\n\t\\end{cases}\n\\]\n\nIn particular, if we take $A$ to be identity matrix: $A = I$ (each event to be in it's own group), knnAdaLoss turns into a simple AdaLoss.\n\n\n\n\\subsection{Gradient Boosting with Flatness Loss (FL)}\n\nLet's use the metrics introduces in the section \\ref{sec:similarity}:\n\\[\n\t\\sum_{\\bin} \\binweight \\int \\abs{F_{\\bin}(x) - F(x)}^p dF(x),\n\\]\nwhich is good as a measure, but due to the non-smoothness of $F(x)$ it's \ngradient is singular, so we use instead\n\\[\n\t\\FL = \\sum_{\\bin} \\binweight \\int \\abs{F_{\\bin}(x) - F(x)}^p dx.\n\\]\n\nSo, the derivative looks like:\n\\[\n\t\\dfrac{\\partial} {\\partial \\, \\score_i} \\FL\n\t= \\sum_{\\bin} \\binweight \\frac{\\partial }{ \\partial \\, \\score_i} \n\t\t\t\\int \\abs{F_\\bin(x) - F(x)}^p dx\n\\]\nLet $\\bin(i)$ be a bin to which event $i$ belongs, then we can compute:\n\\def\\binIweight{\\text{weight}_\\text{\\bin(i)}}\n\n% TODO sign \n\n\\begin{multline*}\n\t- \\dfrac{\\partial} {\\partial \\, \\score_i} \\FL = \n\t\t- \\binIweight\n\t\t\\frac{\\partial }{ \\partial \\, \\score_i} \n\t\t\t\\int \\abs{F_{\\bin(i)}(x) - F(x)}^p dx \\cong \\\\\n\t\\cong \\binIweight \\, p \\,  \\abs{F_{\\bin(i)}(x) - F(x)}^{p-1} \n\t\t\\sgn[F_{\\bin(i)}(x) - F(x)]\n\t\t\\dfrac{w_i}{\\binIweight}\n\t\t\\Bigg|_{x=\\score_i} = \\\\\n\t= \n\t\tw_i \\, p \\,  \\abs{F_{\\bin(i)}(x) - F(x)}^{p-1}\n\t\t\\sgn[F_{\\bin(i)}(x) - F(x)]\n\t\t\\Bigg|_{x=\\score_i}\n\\end{multline*}\n\nTODO give explanations here\n\nThe next thing we need to point is FL doesn't take into account the quality of predictions. So what we use in practice is linear combination of FlatnessLoss and AdaLoss:\n\\[\n\t\\text{loss} = \\FL + \\alpha \\, \\text{AdaLoss}\n\\]\n\nFirst one penalizes the non-uniformity, second one --- poor predictions.\n\n\\section{Dataset}\n\nHere should be some description of $D \\to hhh$ sample.\n\n\\section{Plots}\n\n\\section{Timings}\n\nThe main drawback of uBoost technique is it's high computational complexity: \nwhile simple AdaBoost trains $M$ trees, uBoost builds $100 \\times M$ trees (contribution of other operations usually can be neglected). \n\nPresented in this paper classifiers are building $M$ trees, though there is more complicated boosting, it takes at each iteration ($k$ is number of neighbors, $N$ is number of events in training sample)\n\n\\begin{itemize}\n\t\\item meanAdaBoost: $O(k \\times N)$\n\t\\item knnAdaLoss: $O(k \\times N)$, for the arbitrary matrix $A$ it is \n\t$O( \\text{\\#nonzero elements in the matrix})$\n\t\\item FlatnessLoss: $O(N \\ln N)$\n\\end{itemize}\n\n\n\\section{Summary}\n\n\\section{Source code}\n\nThe link on the repository ans links to final notebooks with results in the article.\n\n\\acknowledgments\n\n\n\n\\begin{thebibliography}{9}\n\n\\bibitem{bib1}\nAuthors,\n\\emph{Title},\n\\emph{J. Ref.} \\textbf{vol} (year) page.\n\n\\bibitem{bib2}\nA. Pietropaolo et al., \\emph{DINS measurements on VESUVIO in the\n    resonance detector configuration: proton mean kinetic energy in\n    water}, \\jinst{1}{2006}{P04001}.\n\n\\bibitem{bib3}\nA.I. Harris,\n\\emph{Spectroscopy with multichannel correlation radiometers},\n\\href{http://dx.doi.org/10.1063/1.1898643}\n{\\emph{Rev.\\ Sci.\\ Instrum.} {\\bf 76} (2005) 054503}\n[\\astroph{0504449}].\n\n\\bibitem{bib4}\nG.F. Knoll, \\emph{Radiation detection and measurements}, John Wiley\n    and Sons, Inc., New York 2000.\n\n\\bibitem{bib5}\nV. Dangendorf, \\emph{Time-resolved fast-neutron imaging with a\npulse-counting image intensifier}, in proceedings of\n\\emph{International workshop on fast neutron detectors and\napplications}, April, 3--6, 2006 University of Cape Town, South Africa\n\\pos{PoS(FNDA2006)008}.\n\n\\end{thebibliography}\n\n\\end{document}\n", "meta": {"hexsha": "8754dfe9fa6e5204c239c31129e12167759d15fd", "size": 21021, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "assets/paperdraft/paper_draft.tex", "max_stars_repo_name": "mityinzer/lhcb_trigger_ml", "max_stars_repo_head_hexsha": "30a85d91a0b860a6b89348143f5bebdb8d25e76b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-07-08T03:25:11.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-08T03:25:11.000Z", "max_issues_repo_path": "assets/paperdraft/paper_draft.tex", "max_issues_repo_name": "mityinzer/lhcb_trigger_ml", "max_issues_repo_head_hexsha": "30a85d91a0b860a6b89348143f5bebdb8d25e76b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assets/paperdraft/paper_draft.tex", "max_forks_repo_name": "mityinzer/lhcb_trigger_ml", "max_forks_repo_head_hexsha": "30a85d91a0b860a6b89348143f5bebdb8d25e76b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.2176470588, "max_line_length": 648, "alphanum_fraction": 0.7302221588, "num_tokens": 5915, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646140788308, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.32205566397886887}}
{"text": "\\subsection{Combining type models}\n\\label{subsec:transformation_framework:type_models_and_type_graphs:combining_type_models}\n\nThe structure of \\cref{fig:transformation_framework:type_models_and_type_graphs:structure_type_models_graphs} shows that the type models $Tm_A$ and $Tm_B$ are combined into one type model $Tm_{AB}$. This section provides the definition of this combination and its corresponding theorems. Please note that the definitions presented here are as generic as possible, and do not actively take into account that $Tm_{A}$ and $Tm_{B}$ are mostly distinct. This bit of information is added later as part of a theorem and proof.\n\n\\begin{defin}[Combination function on type models]\n\\label{defin:transformation_framework:type_models_and_type_graphs:combining_type_models:combine}\n$\\mathrm{combine}$ is a binary function on two type models which combines two type models into one type model. It is defined as follows:\n\\begin{align*}\n\\mathrm{combine}(Tm_A, Tm_B) = \\langle&\nClass = Class_{Tm_A} \\cup Class_{Tm_B} \\\\&\nEnum = Enum_{Tm_A} \\cup Enum_{Tm_B} \\\\&\nUserDataType = UserDataType_{Tm_A} \\cup UserDataType_{Tm_B} \\\\&\nField = Field_{Tm_A} \\cup Field_{Tm_B} \\\\&\n\\mathrm{FieldSig} = \\mathrm{fieldsig\\_\\!combine}(Tm_A, Tm_B) \\\\&\nEnumValue = EnumValue_{Tm_A} \\cup EnumValue_{Tm_B} \\\\&\nInh = Inh_{Tm_A} \\cup Inh_{Tm_B} \\\\&\nProp = \\mathrm{prop\\_\\!combine}(Tm_A, Tm_B) \\\\&\nConstant = Constant_{Tm_A} \\cup Constant_{Tm_B} \\\\&\n\\mathrm{ConstType} = \\mathrm{consttype\\_\\!combine}(Tm_A, Tm_B)\\rangle\n\\end{align*}\n\nIn which $\\mathrm{fieldsig\\_\\!combine}$ is given as part of \\cref{defin:transformation_framework:type_models_and_type_graphs:combining_type_models:fieldsig_combine}, $\\mathrm{prop\\_\\!combine}$ as part of \\cref{defin:transformation_framework:type_models_and_type_graphs:combining_type_models:prop_combine} and $\\mathrm{consttype\\_\\!combine}$ as part of \\cref{defin:transformation_framework:type_models_and_type_graphs:combining_type_models:consttype_combine}.\n\\isabellelref{tmod_combine}{Ecore.Type_Model_Combination}\n\\end{defin}\n\nThe combination of two type models is rather simple in its definition, at least for all the sets defined as part of a type model. Intuitively, the definition makes sense. To combine two type models, we need the types from both type models, so we merge the classes, enumerations types, enumeration values and user-defined data types. The constants should also be preserved, so these are merged too. To preserve all attributes and relations, we merge the set of fields and the inheritance relation as well.\n\nMerging the different functions is done by using a new function. First, the combination of field signatures will be discussed.\n\n\\begin{defin}[Combination function for field signatures]\n\\label{defin:transformation_framework:type_models_and_type_graphs:combining_type_models:fieldsig_combine}\n$\\mathrm{fieldsig\\_\\!combine}$ is a partial function on two type models which returns a new function $Field_{Tm_{AB}} \\Rightarrow (Type_{Tm_{AB}} \\times \\mathbb{M})$. It is defined as follows:\n\\begin{multline*}\n    \\mathrm{fieldsig\\_\\!combine}(Tm_{A}, Tm_{B}, f) = \\\\\n        \\begin{cases}\n        s & \\mathrm{if } f \\in Field_{Tm_A} \\cap Field_{Tm_B} \\land \\mathrm{type}_{Tm_A}(f) = \\mathrm{type}_{Tm_B}(f) \\\\\n        \\mathrm{FieldSig}_{Tm_A}(f) & \\mathrm{if } f \\in Field_{Tm_A} \\setminus Field_{Tm_B} \\\\\n        \\mathrm{FieldSig}_{Tm_B}(f) & \\mathrm{if } f \\in Field_{Tm_B} \\setminus Field_{Tm_A}\n    \\end{cases}\n\\end{multline*}\nwhere\n\\begin{equation*}\n\\begin{split}\n    s = \\bigg(\\mathrm{type}_{Tm_A}(f), \\Big(\\max\\left(\\mathrm{lower}(\\mathrm{FieldSig}_{Tm_A}(f)), \\mathrm{lower}(\\mathrm{FieldSig}_{Tm_B}(f))\\right) ..\\\\ \\min\\left(\\mathrm{upper}(\\mathrm{FieldSig}_{Tm_A}(f)), \\mathrm{upper}(\\mathrm{FieldSig}_{Tm_B}(f))\\right)\\Big)\\bigg)\n\\end{split}\n\\end{equation*}\n\\isabellelref{tmod_combine_fieldsig}{Ecore.Type_Model_Combination}\n\\end{defin}\n\nAlthough the above definition looks quite complex, the intuition behind it is straightforward. For a field that only occurs in type model $Tm_A$, the field signature over from $Tm_A$ is copied. For a field that only occurs in $Tm_B$, the field signature from $Tm_B$ is copied. In the case that a field occurs in both $Tm_A$ and $Tm_B$, it should be the case that the type of the fields is the same. If this is indeed the case, the field type is copied, and a new multiplicity is created. This multiplicity takes the maximum of the lower bounds of the field in $Tm_A$ and $Tm_B$ as new lower bound, and the minimum of the upper bounds of the field in $Tm_A$ and $Tm_B$ as new upper bound.\n\n\\begin{figure}\n    \\centering\n    \\begin{subfigure}{0.45\\textwidth}\n        \\centering\n        \\includegraphics{images/04_transformation_framework/type_models_combination/fieldsig_combine_tmod1.pdf}\n        \\caption{First type model $Tm_A$}\n        \\label{fig:transformation_framework:type_models_and_type_graphs:combining_type_models:fieldsig_combine_tmod1}\n    \\end{subfigure}\n    \\begin{subfigure}{0.45\\textwidth}\n        \\centering\n        \\includegraphics{images/04_transformation_framework/type_models_combination/fieldsig_combine_tmod2.pdf}\n        \\caption{Second type model $Tm_A$}\n        \\label{fig:transformation_framework:type_models_and_type_graphs:combining_type_models:fieldsig_combine_tmod2}\n    \\end{subfigure}\n    \\par\\medskip\n    \\begin{subfigure}{\\textwidth}\n        \\centering\n        \\includegraphics{images/04_transformation_framework/type_models_combination/fieldsig_combine_tmod12.pdf}\n        \\caption{Combined type model $Tm_{AB}$}\n        \\label{fig:transformation_framework:type_models_and_type_graphs:combining_type_models:fieldsig_combine_tmod12}\n    \\end{subfigure}\n    \\caption{Combination of field signatures when field is present in both type models}\n    \\label{fig:transformation_framework:type_models_and_type_graphs:combining_type_models:fieldsig_combine}\n\\end{figure}\n\nAn example of the combination of two field signatures in the case of a field being present in both $Tm_A$ and $Tm_B$ is given in \\cref{fig:transformation_framework:type_models_and_type_graphs:combining_type_models:fieldsig_combine}. It is possible to combine the field $\\type{x}$, since in both $Tm_A$ and $Tm_B$ field $\\type{x}$ references class type $\\type{B}$. The multiplicity for both field signatures is different and is combined as defined. The maximum of the lower bounds is taken, which results in $\\max(3, 1) = 3$. Furthermore, the minimum of the upper bounds is taken, which results in $\\min(6, 4) = 4$. Therefore the multiplicity of $\\type{x}$ in $Tm_{AB}$ will become $3..4$.\n\nBesides a function for field signatures, a type model also defines a function for constant types. The combination of constant types is discussed in the next definition.\n\n\\begin{defin}[Combination function for constant types]\n\\label{defin:transformation_framework:type_models_and_type_graphs:combining_type_models:consttype_combine}\n$\\mathrm{consttype\\_\\!combine}$ is a partial function on two type models which returns a new function \\\\$Constant_{Tm_{AB}} \\Rightarrow Type_{Tm_{AB}}$. It is defined as follows:\n\\begin{multline*}\n    \\mathrm{consttype\\_\\!combine}(Tm_{A}, Tm_{B}, c) = \\\\\n        \\begin{cases}\n        \\mathrm{ConstType}_{Tm_A}(c) & \\mathrm{if}\\ c \\in Constant_{Tm_A} \\cap Constant_{Tm_B} \\land \\mathrm{ConstType}_{Tm_A}(c) = \\mathrm{ConstType}_{Tm_B}(c) \\\\\n        \\mathrm{ConstType}_{Tm_A}(c) & \\mathrm{if}\\ c \\in Constant_{Tm_A} \\setminus Constant_{Tm_B} \\\\\n        \\mathrm{ConstType}_{Tm_B}(c) & \\mathrm{if}\\ c \\in Constant_{Tm_B} \\setminus Constant_{Tm_A}\n    \\end{cases}\n\\end{multline*}\n\\isabellelref{tmod_combine_const_type}{Ecore.Type_Model_Combination}\n\\end{defin}\n\nThe definition of the combination of constant types is similar to the combination of field signatures. The combination of constant types is less complicated because there is no notion of multiplicities involved. By definition, if a constant only occurs in $Tm_{A}$, the constant type of $Tm_{A}$ is copied. For constants that only occur in $Tm_{B}$, the constant type of $Tm_{B}$ is copied. In case that a constant occurs in both $Tm_{A}$ and $Tm_{B}$, the constant is copied if the constant types for that constant are the same in both $Tm_{A}$ and $Tm_{B}$.\n\nThe last definition that remains to be given is the definition of combining the set of properties. The set of properties cannot be united by merely taking the union of $Prop_{Tm_A}$ and $Prop_{Tm_B}$ since this might invalidate the satisfaction of these properties on the level of an instance graph. Instead, the inductive set $\\mathrm{prop\\_\\!combine}$ is defined to specify under which circumstances a property can be combined.\n\n\\begin{defin}[Combination of model properties]\n\\label{defin:transformation_framework:type_models_and_type_graphs:combining_type_models:prop_combine}\n$\\mathrm{prop\\_\\!combine}(Tm_A, Tm_B)$ is defined as a subset of $Prop_{Tm_A} \\cup Prop_{Tm_B}$. The contents of the set are then defined as follows:\n\nFor $\\type{abstract}$ properties:\n\\begin{mathpar}\n    \\inferrule{[ \\type{abstract}, c ] \\in Prop_{Tm_A} \\\\ c \\not\\in Class_{Tm_B}}{[ \\type{abstract}, c ] \\in \\mathrm{prop\\_\\!combine}(Tm_A, Tm_B)}\n    \\and\n    \\inferrule{[ \\type{abstract}, c ] \\in Prop_{Tm_B} \\\\ c \\not\\in Class_{Tm_A}}{[ \\type{abstract}, c ] \\in \\mathrm{prop\\_\\!combine}(Tm_A, Tm_B)}\n    \\and\n    \\inferrule{[ \\type{abstract}, c ] \\in Prop_{Tm_A} \\\\ [ \\type{abstract}, c ] \\in Prop_{Tm_B}}{[ \\type{abstract}, c ] \\in \\mathrm{prop\\_\\!combine}(Tm_A, Tm_B)}\n\\end{mathpar}\n\nFor $\\type{containment}$ properties:\n\\begin{mathpar}\n    \\inferrule{[ \\type{containment}, r ]\\in Prop_{Tm_A}}{[ \\type{containment}, r ]\\in \\mathrm{prop\\_\\!combine}(Tm_A, Tm_B)}\n    \\and\n    \\inferrule{[ \\type{containment}, r ]\\in Prop_{Tm_B}}{[ \\type{containment}, r ]\\in \\mathrm{prop\\_\\!combine}(Tm_A, Tm_B)}\n\\end{mathpar}\n\nFor $\\type{defaultValue}$ properties:\n\\begin{mathpar}\n    \\inferrule{[ \\type{defaultValue}, f, v ]\\in Prop_{Tm_A} \\\\ f \\not\\in Field_{Tm_B}}{[ \\type{defaultValue}, f, v ]\\in \\mathrm{prop\\_\\!combine}(Tm_A, Tm_B)}\n    \\and\n    \\inferrule{[ \\type{defaultValue}, f, v ]\\in Prop_{Tm_B} \\\\ f \\not\\in Field_{Tm_A}}{[ \\type{defaultValue}, f, v ]\\in \\mathrm{prop\\_\\!combine}(Tm_A, Tm_B)}\n    \\and\n    \\inferrule{[ \\type{defaultValue}, f, v ]\\in Prop_{Tm_A} \\\\ [ \\type{defaultValue}, f, v ]\\in Prop_{Tm_B}}{[ \\type{defaultValue}, f, v ]\\in \\mathrm{prop\\_\\!combine}(Tm_A, Tm_B)}\n\\end{mathpar}\n\nFor $\\type{identity}$ properties:\n\\begin{mathpar}\n    \\inferrule{[ \\type{identity}, c, A ]\\in Prop_{Tm_A} \\\\ c \\not\\in Class_{Tm_B}}{[ \\type{identity}, c, A ]\\in \\mathrm{prop\\_\\!combine}(Tm_A, Tm_B)}\n    \\and\n    \\inferrule{[ \\type{identity}, c, A ]\\in Prop_{Tm_B} \\\\ c \\not\\in Class_{Tm_A}}{[ \\type{identity}, c, A ]\\in \\mathrm{prop\\_\\!combine}(Tm_A, Tm_B)}\n    \\and\n    \\inferrule{[ \\type{identity}, c, A ]\\in Prop_{Tm_A} \\\\ [ \\type{identity}, c, A ]\\in Prop_{Tm_B}}{[ \\type{identity}, c, A ]\\in \\mathrm{prop\\_\\!combine}(Tm_A, Tm_B)}\n\\end{mathpar}\n\nFor $\\type{keyset}$ properties:\n\\begin{mathpar}\n    \\inferrule{[ \\type{keyset}, r, A ]\\in Prop_{Tm_A} \\\\ r \\not\\in Field_{Tm_B}}{[ \\type{keyset}, r, A ]\\in \\mathrm{prop\\_\\!combine}(Tm_A, Tm_B)}\n    \\and\n    \\inferrule{[ \\type{keyset}, r, A ]\\in Prop_{Tm_B} \\\\ r \\not\\in Field_{Tm_A}}{[ \\type{keyset}, r, A ]\\in \\mathrm{prop\\_\\!combine}(Tm_A, Tm_B)}\n    \\and\n    \\inferrule{[ \\type{keyset}, r, A ]\\in Prop_{Tm_A} \\\\ [ \\type{keyset}, r, A ]\\in Prop_{Tm_B}}{[ \\type{keyset}, r, A ]\\in \\mathrm{prop\\_\\!combine}(Tm_A, Tm_B)}\n\\end{mathpar}\n\nFor $\\type{opposite}$ properties:\n\\begin{mathpar}\n    \\inferrule{[ \\type{opposite}, r1, r2 ]\\in Prop_{Tm_A} \\\\ r1 \\not\\in Field_{Tm_B} \\\\ r2 \\not\\in Field_{Tm_B}}{[ \\type{opposite}, r1, r2 ]\\in \\mathrm{prop\\_\\!combine}(Tm_A, Tm_B)}\n    \\and\n    \\inferrule{[ \\type{opposite}, r1, r2 ]\\in Prop_{Tm_B} \\\\ r1 \\not\\in Field_{Tm_A} \\\\ r2 \\not\\in Field_{Tm_A}}{[ \\type{opposite}, r1, r2 ]\\in \\mathrm{prop\\_\\!combine}(Tm_A, Tm_B)}\n    \\and\n    \\inferrule{[ \\type{opposite}, r1, r2 ]\\in Prop_{Tm_A} \\\\ [ \\type{opposite}, r1, r2 ]\\in Prop_{Tm_B}}{[ \\type{opposite}, r1, r2 ]\\in \\mathrm{prop\\_\\!combine}(Tm_A, Tm_B)}\n\\end{mathpar}\n\nFor $\\type{readonly}$ properties:\n\\begin{mathpar}\n    \\inferrule{[ \\type{readonly}, f ] \\in Prop_{Tm_A} \\\\ f \\not\\in Field_{Tm_B}}{[ \\type{readonly}, f ] \\in \\mathrm{prop\\_\\!combine}(Tm_A, Tm_B)}\n    \\and\n    \\inferrule{[ \\type{readonly}, f ] \\in Prop_{Tm_B} \\\\ f \\not\\in Field_{Tm_A}}{[ \\type{readonly}, f ] \\in \\mathrm{prop\\_\\!combine}(Tm_A, Tm_B)}\n    \\and\n    \\inferrule{[ \\type{readonly}, f ] \\in Prop_{Tm_A} \\\\ [ \\type{readonly}, f ] \\in Prop_{Tm_B}}{[ \\type{readonly}, f ] \\in \\mathrm{prop\\_\\!combine}(Tm_A, Tm_B)}\n\\end{mathpar}\n\\isabellelref{tmod_combine_prop}{Ecore.Type_Model_Combination}\n\\end{defin}\n\nAs can be seen from the definition of $\\mathrm{prop\\_\\!combine}(Tm_A, Tm_B)$, properties are only copied under specific circumstances. For $\\type{abstract}$ properties, it holds that a class is only abstract in the combination of $Tm_A$ and $Tm_B$ if the class is abstract in both $Tm_A$ and $Tm_B$ or if the class is abstract in one of them, and the class does not occur in the other. Intuitively, this makes sense for correctness. If a class is abstract in both type models, there will not be instances of that class in any of the combined instance models type by those type models. The same holds if the class only occurs in one of the type models, as an instance model cannot contain an instance of a class that is not present in its type model.\n\nFor the containment property, it holds that the containment property is always copied over. There are no other conditions here. If there is a containment property in $Prop_{Tm_A} \\cup Prop_{Tm_B}$ it will also be in the combination of $Tm_A$ and $Tm_B$.\n\nA default value property is copied over from one of the type models if the other type model does not have the corresponding field defined. Furthermore, a default value may be in the combination of properties of $Tm_A$ and $Tm_B$ if the field occurs in both, and both have the same constant set as the default value for the field. Intuitively, this last requirement makes sense. If we set a default value for a field within a type model, it should not change after combining the type model with another type model, as instance models might depend on the default value set for that field.\n\nIdentity properties follow a similar pattern to default value properties. An identity is copied over from one of the type models if the corresponding class is not defined in the other type model. Furthermore, an identity can be preserved if it is set for the same class and attributes in both type models. Again, intuitively, this is the desired solution. If a type model has a class of which a set of attributes can uniquely define the instances, then this should also be the case after the combination with another type model. Merging two sets of attributes might have preserved the identity property as well, but this would be a questionable decision from a practical standpoint, as this means that the identity of instances changes, which makes no sense in real-world scenarios.\n\nThe argumentation for identity properties also holds for keyset properties. Therefore these follow a similar pattern, in which the keyset properties of a type model are only copied if the corresponding field does not occur in the other type model, or if the keyset property for a field occurs with the same attributes in both type models.\n\nThe opposite property is preserved if it occurs in a type model, but the other type model does not define both of the corresponding fields. Alternatively, the property is preserved if it occurs in both type models with the same fields. All different ways to combine an opposite property would result in an invalid type model according to \\cref{defin:formalisations:ecore_formalisation:type_models:type_model_consistency}, which is undesired.\n\nThe read-only properties follow a similar pattern to the abstract properties. If a field is read-only in both type models, then it is read-only in the combination. Furthermore, if a field is read-only in one of the type models and the field is not defined in the other type model, then the read-only property can be copied too.\n\n\\begin{figure}\n    \\centering\n    \\begin{subfigure}{\\textwidth}\n        \\centering\n        \\includegraphics{images/04_transformation_framework/type_models_combination/chat_partial2.pdf}\n        \\caption{The chat application model $Tm_{Chat}$}\n        \\label{fig:transformation_framework:type_models_and_type_graphs:combining_type_models:combine_example_tmod1}\n    \\end{subfigure}\n    \\par\\medskip\n    \\begin{subfigure}{\\textwidth}\n        \\centering\n        \\includegraphics{images/04_transformation_framework/type_models_combination/chat_partial1.pdf}\n        \\caption{The contact extension model $Tm_{Extension}$}\n        \\label{fig:transformation_framework:type_models_and_type_graphs:combining_type_models:combine_example_tmod2}\n    \\end{subfigure}\n    \\par\\medskip\n    \\begin{subfigure}{\\textwidth}\n        \\centering\n        \\includegraphics{images/04_transformation_framework/type_models_combination/chat_combined.pdf}\n        \\caption{The extended chat application model $Tm_{ChatExt}$}\n        \\label{fig:transformation_framework:type_models_and_type_graphs:combining_type_models:combine_example_tmod12}\n    \\end{subfigure}\n    \\caption{Example of the combination of type models}\n    \\label{fig:transformation_framework:type_models_and_type_graphs:combining_type_models:combine_example}\n\\end{figure}\n\nWith all definitions in place, it is possible to provide a larger example. Suppose the model of a multi-protocol chat application. It consists of $\\type{Thread}$s of $\\type{Message}$s. Since the application is multi-protocol, each $\\type{Thread}$ can use one of the supported $\\type{Protocol}$s. The formal definition of the model of such an application could be as follows:\n\n\\begin{align*}\nTm_{Chat} =\\ &\\langle&\nClass =\\ &\\{ \\type{.Message}, \\type{.Thread} \\} \\\\&&\nEnum =\\ &\\{ \\type{.Protocol} \\} \\\\&&\nUserDataType =\\ &\\{\\} \\\\&&\nField =\\ &\\{\n( \\type{.Message}, \\type{text} ), \n( \\type{.Thread}, \\type{id} ), \n( \\type{.Thread}, \\type{messages} ), \n( \\type{.Thread}, \\type{proto} )\\} \\\\&&\n\\mathrm{FieldSig} =\\ &\\big\\{\n\\big( ( \\type{.Message}, \\type{text} ), ( \\type{string}, 1..1 ) \\big), \\big( ( \\type{.Thread}, \\type{id} ), ( \\type{string}, 1..1 ) \\big),\\\\&&& \n\\big( ( \\type{.Thread}, \\type{messages} ), ( [ \\type{seqof}, !\\type{.Message} ], 0..\\mstar ) \\big),\\\\&&& \n\\big( ( \\type{.Thread}, \\type{proto} ), ( \\type{.Protocol}, 1..1 ) \\big) \\big)\n\\big\\} \\\\&&\nEnumValue =\\ &\\{\n( \\type{.Protocol}, \\type{IRC} ), \n( \\type{.Protocol}, \\type{MTPROTO} ), \n( \\type{.Protocol}, \\type{BLUB\\!-\\!E} )\\} \\\\&&\nInh =\\ &\\{\\} \\\\&&\nProp =\\ &\\big\\{\n\\big( \\type{identity}, \\type{.Message}, \\{( \\type{.Thread}, \\type{id} )\\} \\big)\n\\big\\} \\\\&&\nConstant =\\ &\\{\\} \\\\&&\n\\mathrm{ConstType} =\\ &\\{\\}\n\\\\&\\rangle\n\\end{align*}\n\nAn visual representation of $Tm_{Chat}$ is included as  \\cref{fig:transformation_framework:type_models_and_type_graphs:combining_type_models:combine_example_tmod1}. Now, assume a model that represents an extension to this application, adding support for $\\type{Contact}$s. Each thread can belong to a $\\type{Contact}$. A $\\type{Contact}$ has a name and some identifier that is protocol specific. For that identifier, the user-defined data type $\\type{ProtocolSpecificId}$ is introduced. This extension could formally be defined as:\n\n\\begin{align*}\nTm_{Extension} =\\ &\\langle&\nClass =\\ &\\{ \\type{.Contact}, \\type{.Thread} \\} \\\\&&\nEnum =\\ &\\{\\} \\\\&&\nUserDataType =\\ &\\{ \\type{.ProtocolSpecificId} \\} \\\\&&\nField =\\ &\\{\n( \\type{.Contact}, \\type{name} ), \n( \\type{.Contact}, \\type{id} ), \n( \\type{.Thread}, \\type{contact} )\\} \\\\&&\n\\mathrm{FieldSig} =\\ &\\big\\{\n\\big( ( \\type{.Contact}, \\type{name} ), ( \\type{string}, 1..1 ) \\big),\\\\&&& \\big( ( \\type{.Contact}, \\type{id} ), ( \\type{.ProtocolSpecificId}, 1..1 ) \\big),\\\\&&& \n\\big( ( \\type{.Thread}, \\type{contact} ), ( ?\\type{.Contact}, 0..1 ) \\big) \\big)\n\\big\\} \\\\&&\nEnumValue =\\ &\\{\\} \\\\&&\nInh =\\ &\\{\\} \\\\&&\nProp =\\ &\\big\\{\n\\big( \\type{identity}, \\type{.Contact}, \\{( \\type{.Contact}, \\type{id} )\\} \\big)\n\\big\\} \\\\&&\nConstant =\\ &\\{\\} \\\\&&\n\\mathrm{ConstType} =\\ &\\{\\}\n\\\\&\\rangle\n\\end{align*}\n\nThe visual representation of the extension is included as \\cref{fig:transformation_framework:type_models_and_type_graphs:combining_type_models:combine_example_tmod2}. Now, using \\cref{defin:transformation_framework:type_models_and_type_graphs:combining_type_models:combine}, it is possible to combine these models into one model. This will yield the following model:\n\n\\begin{align*}\nTm_{ChatExt} =\\ &\\langle&\nClass =\\ &\\{ \\type{.Contact}, \\type{.Message}, \\type{.Thread} \\} \\\\&&\nEnum =\\ &\\{ \\type{.Protocol} \\} \\\\&&\nUserDataType =\\ &\\{ \\type{.ProtocolSpecificId} \\} \\\\&&\nField =\\ &\\{\n( \\type{.Contact}, \\type{name} ), \n( \\type{.Contact}, \\type{id} ),\n( \\type{.Message}, \\type{text} ),\\\\&&&\n( \\type{.Thread}, \\type{contact} ),\n( \\type{.Thread}, \\type{id} ),\n( \\type{.Thread}, \\type{messages} ),\\\\&&& \n( \\type{.Thread}, \\type{proto} )\\} \\\\&&\n\\mathrm{FieldSig} =\\ &\\big\\{\n\\big( ( \\type{.Contact}, \\type{name} ), ( \\type{string}, 1..1 ) \\big),\\\\&&& \\big( ( \\type{.Contact}, \\type{id} ), ( \\type{.ProtocolSpecificId}, 1..1 ) \\big),\\\\&&& \n\\big( ( \\type{.Message}, \\type{text} ), ( \\type{string}, 1..1 ) \\big),\\\\&&&\n\\big( ( \\type{.Thread}, \\type{contact} ), ( ?\\type{.Contact}, 0..1 ) \\big) \\big),\\\\&&&\n\\big( ( \\type{.Thread}, \\type{id} ), ( \\type{string}, 1..1 ) \\big),\\\\&&& \n\\big( ( \\type{.Thread}, \\type{messages} ), ( [ \\type{seqof}, !\\type{.Message} ], 0..\\mstar ) \\big),\\\\&&& \n\\big( ( \\type{.Thread}, \\type{proto} ), ( \\type{.Protocol}, 1..1 ) \\big) \\big)\n\\big\\} \\\\&&\nEnumValue =\\ &\\{\n( \\type{.Protocol}, \\type{IRC} ), \n( \\type{.Protocol}, \\type{MTPROTO} ), \n( \\type{.Protocol}, \\type{BLUB\\!-\\!E} )\\} \\\\&&\nInh =\\ &\\{\\} \\\\&&\nProp =\\ &\\big\\{\n\\big( \\type{identity}, \\type{.Contact}, \\{( \\type{.Contact}, \\type{id} )\\} \\big),\\\\&&&\n\\big( \\type{identity}, \\type{.Message}, \\{( \\type{.Thread}, \\type{id} )\\} \\big)\n\\big\\} \\\\&&\nConstant =\\ &\\{\\} \\\\&&\n\\mathrm{ConstType} =\\ &\\{\\}\n\\\\&\\rangle\n\\end{align*}\n\nA visual representation of this combined model is included as \\cref{fig:transformation_framework:type_models_and_type_graphs:combining_type_models:combine_example_tmod12}. The example perfectly shows why the combination of type models is useful: It allows for building larger models out of smaller building blocks. This is the exact goal of this definition within the transformation framework.\n\nAlthough the definitions of the combination of type models are given, no mathematical properties or theorems are defined yet. Some mathematical properties hold for the combination of type models, that will be presented in the following theorems.\n\n\\begin{thm}[Commutativity of the combination of type models]\n\\label{defin:transformation_framework:type_models_and_type_graphs:combining_type_models:tmod_combine_commute}\nAssume that $Tm_A$ and $Tm_B$ are type models, then the $\\mathrm{combine}$ function is commutative:\n\\begin{equation*}\n    \\mathrm{combine}(Tm_A, Tm_B) = \\mathrm{combine}(Tm_B, Tm_A)\n\\end{equation*}\n\\isabellelref{tmod_combine_commute}{Ecore.Type_Model_Combination}\n\\end{thm}\n\n\\begin{thm}[Associativity of the combination of type models]\n\\label{defin:transformation_framework:type_models_and_type_graphs:combining_type_models:tmod_combine_assoc}\nAssume that $Tm_A$, $Tm_B$ and $Tm_C$ are type models, then the $\\mathrm{combine}$ function is associative:\n\\begin{equation*}\n    \\mathrm{combine}(\\mathrm{combine}(Tm_A, Tm_B), Tm_C) = \\mathrm{combine}(Tm_A, \\mathrm{combine}(Tm_B, Tm_C))\n\\end{equation*}\n\\isabellelref{tmod_combine_assoc}{Ecore.Type_Model_Combination}\n\\end{thm}\n\n\\begin{thm}[Idempotence of the combination of type models]\n\\label{defin:transformation_framework:type_models_and_type_graphs:combining_type_models:tmod_combine_idemp}\nAssume that $Tm_A$ is a type model and that it is consistent in the sense of \\cref{defin:formalisations:ecore_formalisation:type_models:type_model_consistency}. Then the following property holds:\n\\begin{equation*}\n    \\mathrm{combine}(Tm_A, Tm_A) = Tm_A\n\\end{equation*}\n\\isabellelref{tmod_combine_idemp_alt}{Ecore.Type_Model_Combination}\n\\end{thm}\n\nThese properties follow directly from \\cref{defin:transformation_framework:type_models_and_type_graphs:combining_type_models:combine}, but the corresponding proofs will not be included here. It should be noted that these properties are indeed proven correct as part of this thesis, and the corresponding proofs are validated within Isabelle.\n\nBesides these properties, the combination of type models also has an identity element. The empty type model represents this identity element, but it needs to be defined first:\n\n\\begin{defin}[Empty type model]\n\\label{defin:transformation_framework:type_models_and_type_graphs:combining_type_models:empty_type_model}\nLet $Tm_{\\epsilon}$ be the empty type model. $Tm_{\\epsilon}$ is defined as:\n\\begin{align*}\nTm_{\\epsilon} = \\langle&\nClass = \\{\\} \\\\&\nEnum = \\{\\} \\\\&\nUserDataType = \\{\\} \\\\&\nField = \\{\\} \\\\&\n\\mathrm{FieldSig} = undefined \\\\&\nEnumValue = \\{\\} \\\\&\nInh = \\{\\} \\\\&\nProp = \\{\\} \\\\&\nConstant = \\{\\} \\\\&\n\\mathrm{ConstType} = undefined\\rangle\n\\end{align*}\n\\end{defin}\n\n\\begin{thm}[Correctness of the empty type model]\n\\label{defin:transformation_framework:type_models_and_type_graphs:combining_type_models:tmod_empty_correct}\nThe empty type model, $Tm_{\\epsilon}$, is consistent with respect to\n\\cref{defin:formalisations:ecore_formalisation:type_models:type_model_consistency}.\n\\isabellelref{tmod_empty_correct}{Ecore.Type_Model}\n\\end{thm}\n\nThe proof for the correctness of the empty type model is trivial. Still, a validated version of this proof can be found within the Isabelle theories of this thesis.\n\nAs mentioned earlier, the empty type model acts as an identity element when combining two type models. The following theorem specifies this behaviour.\n\n\\begin{thm}[Identity of the combination of type models]\n\\label{defin:transformation_framework:type_models_and_type_graphs:combining_type_models:tmod_combine_identity}\nAssume that $Tm_A$ is a type model and that it is consistent in the sense of \\cref{defin:formalisations:ecore_formalisation:type_models:type_model_consistency}. Then $Tm_{\\epsilon}$ acts as an identity element in the combination function:\n\\begin{equation*}\n    \\mathrm{combine}(Tm_{\\epsilon}, Tm_A) = Tm_A\n\\end{equation*}\n\\isabellelref{tmod_combine_identity_alt}{Ecore.Type_Model_Combination}\n\\end{thm}\n\nOnce more, the proof of this theorem follows directly from the definition. Therefore, the corresponding proof will not be included here, but a validated version can be found within the Isabelle theories of this thesis.\n\nA final desired property for the combination of type models is a correctness property. \\cref{defin:transformation_framework:type_models_and_type_graphs:combining_type_models:tmod_combine_correct} defines the theorem under which the combination of type models is a consistent type model. Please note that this theorem is a generic theorem, which does not take into account that the type models are mostly distinct.\n\n\\begin{thm}[Consistency of the combination of type models]\n\\label{defin:transformation_framework:type_models_and_type_graphs:combining_type_models:tmod_combine_correct}\nAssume that $Tm_A$ and $Tm_B$ are consistent type models in the sense of \\cref{defin:formalisations:ecore_formalisation:type_models:type_model_consistency}. Furthermore, assume the following properties:\n\\begin{itemize}\n    \\item For all shared fields, the type is the same in both type models: $\\forall f \\in Field_{Tm_A} \\cap Field_{Tm_B}\\!: \\mathrm{type}_{Tm_A}(f) = \\mathrm{type}_{Tm_B}(f)$\n    \\item For all shared fields, the combination of the multiplicities is a valid multiplicity: $\\forall f \\in Field_{Tm_A} \\cap Field_{Tm_B}\\!: \\max\\big(\\mathrm{lower}(\\mathrm{FieldSig}_{Tm_A}(f)), \\mathrm{lower}(\\mathrm{FieldSig}_{Tm_B}(f))\\big) .. \\min\\big(\\mathrm{upper}(\\mathrm{FieldSig}_{Tm_A}(f)),$\\\\ $\\mathrm{upper}(\\mathrm{FieldSig}_{Tm_B}(f))\\big) \\in \\mathbb{M}$\n    \\item For all shared constants, the constant type is the same in both models: $\\forall f \\in Constant_{Tm_A} \\cap Constant_{Tm_B}\\!: \\mathrm{ConstType}_{Tm_A}(f) = \\mathrm{ConstType}_{Tm_B}(f)$\n    \\item Identifiers used for a class in $Tm_A$ cannot be used for an enumeration type or user-defined data type in $Tm_B$: $\\forall c \\in Class_{Tm_A}\\!: c \\not\\in Enum_{Tm_B} \\land c \\not\\in UserDataType_{Tm_B}$.\n    \\item Identifiers used for a class in $Tm_B$ cannot be used for an enumeration type or user-defined data type in $Tm_A$: $\\forall c \\in Class_{Tm_B}\\!: c \\not\\in Enum_{Tm_A} \\land c \\not\\in UserDataType_{Tm_A}$.\n    \\item Identifiers used for an enumeration type in $Tm_A$ cannot be used for a class or user-defined data type in $Tm_B$: $\\forall c \\in Enum_{Tm_A}\\!: c \\not\\in Class_{Tm_B} \\land c \\not\\in UserDataType_{Tm_B}$.\n    \\item Identifiers used for an enumeration type in $Tm_B$ cannot be used for a class or user-defined data type in $Tm_A$: $\\forall c \\in Enum_{Tm_B}\\!: c \\not\\in Class_{Tm_A} \\land c \\not\\in UserDataType_{Tm_A}$.\n    \\item Identifiers from $Tm_A$ may not be in the namespace of an identifier in $Tm_B$: $\\forall x \\in Class_{Tm_A} \\cup Enum_{Tm_A} \\cup UserDataType_{Tm_A}; y \\in Class_{Tm_B} \\cup Enum_{Tm_B} \\cup UserDataType_{Tm_B}\\!:$\\\\$x \\text{ not in the namespace of } y$\n    \\item Identifiers from $Tm_B$ may not be in the namespace of an identifier in $Tm_A$: $\\forall x \\in Class_{Tm_B} \\cup Enum_{Tm_B} \\cup UserDataType_{Tm_B}; y \\in Class_{Tm_A} \\cup Enum_{Tm_A} \\cup UserDataType_{Tm_A}\\!:$\\\\$x \\text{ not in the namespace of } y$\n    \\item The transitive closure of the inheritance relation is irreflexive: $(Inh_{Tm_A} \\cup Inh_{Tm_B})^+$ is irreflexive\n    \\item For any superclass with an identity, the identity of the subclasses must be a superset of the identity of the superclass: $\\forall c_1\\ c_2\\ A_1\\ A_2\\!: [ \\type{identity}, c_1, A_1 ] \\in \\mathrm{prop\\_\\!combine}(Tm_A, Tm_B) \\land [ \\type{identity}, c_2, A_2 ] \\in \\mathrm{prop\\_\\!combine}(Tm_A, Tm_B) \\land c_1 \\neq c_2\\ \\land\\ !c_1 \\not\\sqsubseteq_{Tm_A}\\ !c_2\\ \\land\\ !c_1 \\not\\sqsubseteq_{Tm_B}\\ !c_2\\ \\land\\ !c_1 \\sqsubseteq_{\\mathrm{combine}(Tm_A, Tm_B)}\\ !c_2 \\implies A \\subseteq B$\n    \\item For all shared fields, if $Tm_{A}$ defines a default value, $Tm_{B}$ should define the same default value, and vice versa: $\\forall f \\in Field_{Tm_A} \\cap Field_{Tm_B}\\!: [ \\type{defaultValue}, f, v ] \\in Prop_{Tm_A} \\Longleftrightarrow [ \\type{defaultValue}, f, v ] \\in Prop_{Tm_B}$.\n    \\item For all shared classes, if $Tm_{A}$ defines a identity, $Tm_{B}$ should define the same identity, and vice versa: $\\forall c \\in Class_{Tm_A} \\cap Class_{Tm_B}\\!: [ \\type{identity}, c, A ] \\in Prop_{Tm_A} \\Longleftrightarrow [ \\type{identity}, c, A ] \\in Prop_{Tm_B}$.\n    \\item For all shared fields, if $Tm_{A}$ defines a keyset, $Tm_{B}$ should define the same keyset, and vice versa: $\\forall r \\in Field_{Tm_A} \\cap Field_{Tm_B}\\!: [ \\type{keyset}, r, A ] \\in Prop_{Tm_A} \\Longleftrightarrow [ \\type{keyset}, r, A ] \\in Prop_{Tm_B}$.\n    \\item For all shared fields, if $Tm_{A}$ defines an opposite property, $Tm_{B}$ should define the same opposite property, and vice versa: $\\forall r \\in Field_{Tm_A} \\cap Field_{Tm_B}\\!: [ \\type{opposite}, r, r' ] \\in Prop_{Tm_A} \\Longleftrightarrow [ \\type{opposite}, r, r' ] \\in Prop_{Tm_B}$\n\\end{itemize}\n\nThen $\\mathrm{combine}(Tm_A, Tm_B)$ is a consistent type model in the sense of \\cref{defin:formalisations:ecore_formalisation:type_models:type_model_consistency}\n\\isabellelref{tmod_combine_correct}{Ecore.Type_Model_Combination}\n\\end{thm}\n\n\\begin{proof}\nTo proof that $\\mathrm{combine}(Tm_A, Tm_B)$ is a consistent type model, it needs to be shown that\\\\ $\\mathrm{combine}(Tm_A, Tm_B)$ gives rise to a valid structure for a type model and that \\cref{defin:formalisations:ecore_formalisation:type_models:type_model_consistency} holds. For readability, define $Tm_{AB}$ to be $\\mathrm{combine}(Tm_A, Tm_B)$.\n\n\\emph{Structural properties}\n\\begin{itemize}\n    \\item All elements of $Class_{Tm_{AB}}$ are elements of $Id$.\n    \n    Follows from $Class_{Tm_A} \\subseteq Id$ and $Class_{Tm_B} \\subseteq Id$.\n    \n    \n    \\item All elements of $Enum_{Tm_{AB}}$ are elements of $Id$.\n    \n    Follows from $Enum_{Tm_A} \\subseteq Id$ and $Enum_{Tm_B} \\subseteq Id$.\n    \n    \n    \\item All elements of $UserDataType_{Tm_{AB}}$ are elements of $Id$.\n    \n    Follows from $UserDataType_{Tm_A} \\subseteq Id$ and $UserDataType_{Tm_B} \\subseteq Id$.\n    \n    \n    \\item All elements of $Field_{Tm_{AB}}$ are elements of $(Class_{Tm_{AB}} \\times Name)$.\n    \n    Follows from $Field_{Tm_A} \\subseteq (Class_{Tm_A} \\times Name)$ and $Field_{Tm_B} \\subseteq (Class_{Tm_B} \\times Name)$. To complete the proof, use $Class_{Tm_{AB}} = Class_{Tm_A} \\cup Class_{Tm_B}$.\n    \n    \n    \\item For each field $f$, $\\mathrm{FieldSig}_{Tm_{AB}}(f)$ must be an element of $(Type_{Tm_{AB}} \\times \\mathbb{M})$.\n    \n    First, note that $Type_{Tm_{AB}} = Type_{Tm_A} \\cup Type_{Tm_B}$\\\\(see \\isabelleref{tmod_combine_type}{Ecore.Type_Model_Combination}).\n    \n    If $f \\in Field_{Tm_A} \\setminus Field_{Tm_B}$, then $\\mathrm{FieldSig}_{Tm_{AB}}(f) \\in (Type_{Tm_{AB}} \\times \\mathbb{M})$.\n    \n    Similarly, if $f \\in Field_{Tm_B} \\setminus Field_{Tm_A}$, then $\\mathrm{FieldSig}_{Tm_{AB}}(f) \\in (Type_{Tm_{AB}} \\times \\mathbb{M})$. \n    \n    If $f \\in Field_{Tm_A} \\cap Field_{Tm_B}$, then $\\mathrm{type}_{Tm_A}(f) = \\mathrm{type}_{Tm_B}(f)$ by assumption. Also, the combined multiplicity is correct by assumption. Therefore $\\mathrm{FieldSig}_{Tm_{AB}}(f) \\in (Type_{Tm_{AB}} \\times \\mathbb{M})$.\n    \n    \n    \\item All elements of $EnumValue_{Tm_{AB}}$ are elements of $(Enum_{Tm_{AB}} \\times Name)$.\n    \n    Follows from $EnumValue_{Tm_A} \\subseteq (Enum_{Tm_A} \\times Name)$ and $EnumValue_{Tm_B} \\subseteq (Enum_{Tm_B} \\times Name)$. To complete the proof, use $Enum_{Tm_{AB}} = Enum_{Tm_A} \\cup Enum_{Tm_B}$.\n    \n    \n    \\item All elements of $Inh_{Tm_{AB}}$ are elements of $(Class_{Tm_{AB}} \\times Class_{Tm_{AB}})$.\n    \n    Follows from $Inh_{Tm_A} \\subseteq (Class_{Tm_A} \\times Class_{Tm_A})$ and $Inh_{Tm_B} \\subseteq (Class_{Tm_B} \\times Class_{Tm_B})$. Furthermore, $Class_{Tm_{AB}} = Class_{Tm_A} \\cup Class_{Tm_B}$.\n    \n    \n    \\item All elements of $Prop_{Tm_{AB}}$ are elements of $Property_{Tm_{AB}}$.\n    \n    Make a case distinction for the different possible properties.\n    \\begin{itemize}\n        \\item For $[ \\type{abstract}, c ] \\in Prop_{Tm_{AB}}$, use the fact that $c \\in Class_{Tm_A} \\cup Class_{Tm_B}$. Therefore, $[ \\type{abstract}, c ] \\in Property_{Tm_{AB}}$.\n        \n        \\item For $[ \\type{containment}, r ] \\in Prop_{Tm_{AB}}$, use the fact that $Rel_{Tm_{AB}} = Rel_{Tm_A} \\cup Rel_{Tm_B}$ (see \\isabelleref{tmod_combine_rel}{Ecore.Type_Model_Combination}). Then have $[ \\type{containment}, r ] \\in Property_{Tm_{AB}}$.\n        \n        \\item For $[ \\type{defaultValue}, f, v ] \\in Prop_{Tm_{AB}}$, use the fact that $f \\in Field_{Tm_A} \\cup Field_{Tm_B}$ and $v \\in Constant_{Tm_A} \\cup Constant_{Tm_B}$. Using a case disinction on the combination of properties, it is possible to show that $\\mathrm{ConstType}_{Tm_{AB}}(v) \\sqsubseteq_{Tm_{AB}} \\mathrm{type}_{Tm_{AB}}(f)$. Therefore, $[ \\type{defaultValue}, f, v ] \\in Property_{Tm_{AB}}$.\n        \n        \\item For $[ \\type{identity}, c, A ] \\in Prop_{Tm_{AB}}$, use the fact that $c \\in Class_{Tm_A} \\cup Class_{Tm_B}$ and $A \\subseteq fields_{Tm_A} \\lor A \\subseteq fields_{Tm_B}$. Then have that $A \\subseteq fields_{Tm_{AB}}$ Therefore, $[ \\type{identity}, c, A ] \\in Property_{Tm_{AB}}$.\n        \n        \\item For $[ \\type{keyset}, r, A ] \\in Prop_{Tm_{AB}}$, use the fact that $Rel_{Tm_{AB}} = Rel_{Tm_A} \\cup Rel_{Tm_B}$ (see \\isabelleref{tmod_combine_rel}{Ecore.Type_Model_Combination}) to show $r \\in Rel_{Tm_{AB}}$. Also use the fact that $Attr_{Tm_{AB}} = Attr_{Tm_A} \\cup Attr_{Tm_B}$ to show $A \\subseteq Attr_{Tm_{AB}}$ (see \\isabelleref{tmod_combine_attr}{Ecore.Type_Model_Combination}). Because types are preserved after combining, it is possible to show that $\\forall f \\in A\\!: \\mathrm{uncontainer}(\\mathrm{type}_{Tm_{AB}}(r)) \\sqsubseteq_{Tm_{AB}} \\mathrm{class}_{Tm_{AB}}(f)$. Furthermore, $\\mathrm{type}_{Tm_{AB}}(r) \\in (\\{ \\type{setof}, \\type{ordof} \\} \\times ClassType_{Tm_{AB}})$. Therefore, $[ \\type{keyset}, r, A ] \\in Property_{Tm_{AB}}$.\n        \n        \\item For $[ \\type{opposite}, r, r' ] \\in Prop_{Tm_{AB}}$, use the fact that $Rel_{Tm_{AB}} = Rel_{Tm_A} \\cup Rel_{Tm_B}$ (see \\isabelleref{tmod_combine_rel}{Ecore.Type_Model_Combination}) to show $r \\in Rel_{Tm_{AB}}$ and $r' \\in Rel_{Tm_{AB}}$. Because types are preserved after combining, it is possible to show that $!c1 \\sqsubseteq_{Tm_{AB}} \\mathrm{uncontainer}(\\mathrm{type}_{Tm_{AB}}(r'))$, $!c2 \\sqsubseteq_{Tm_{AB}} \\mathrm{uncontainer}(\\mathrm{type}_{Tm_{AB}}(r))$,\\\\ $\\mathrm{type}_{Tm_{AB}}(r) \\not\\in \\{ \\type{bagof}, \\type{seqof} \\} \\times Type_{Tm_{AB}}$ and finally $type_{Tm_{AB}}(r') \\not\\in \\{ \\type{bagof}, \\type{seqof} \\} \\times Type_{Tm_{AB}}$. Therefore, $[ \\type{opposite}, r, r' ] \\in Property_{Tm_{AB}}$.\n        \n        \\item For $[ \\type{readonly}, f ] \\in Prop_{Tm_{AB}}$, use the fact that $f \\in Field_{Tm_A} \\cup Field_{Tm_B}$. Therefore, $[ \\type{readonly}, f ] \\in Property_{Tm_{AB}}$.\n    \\end{itemize}\n    \n    \n    \\item All elements of $Constant_{Tm_{AB}}$ are elements of $Id$.\n    \n    Follows from $Constant_{Tm_A} \\subseteq Id$ and $Constant_{Tm_B} \\subseteq Id$.\n    \n    \n    \\item For each constant $c$, $\\mathrm{ConstType}_{Tm_{AB}}(c)$ must be an element of $Type_{Tm_{AB}}$.\n    \n    First, note that $Type_{Tm_{AB}} = Type_{Tm_A} \\cup Type_{Tm_B}$\\\\(see \\isabelleref{tmod_combine_type}{Ecore.Type_Model_Combination}).\n    \n    If $c \\in Constant_{Tm_A} \\setminus Constant_{Tm_B}$, then $\\mathrm{ConstType}_{Tm_{AB}}(f) \\in Type_{Tm_{AB}}$.\n    \n    Similarly, if $c \\in Constant_{Tm_B} \\setminus Constant_{Tm_A}$, then $\\mathrm{ConstType}_{Tm_{AB}}(c) \\in Type_{Tm_{AB}}$.\n    \n    If $c \\in Constant_{Tm_A} \\cap Constant_{Tm_B}$, then $\\mathrm{ConstType}_{Tm_A}(c) = \\mathrm{ConstType}_{Tm_B}(c)$ by assumption. Therefore $\\mathrm{ConstType}_{Tm_{AB}}(c) \\in Type_{Tm_{AB}}$.\n    \n    \n    \\item $Class_{Tm_{AB}}$, $DataType$, $Enum_{Tm_{AB}}$ and $UserDataType_{Tm_{AB}}$ are pairwise disjoint.\n    \n    Notice that $Class_{Tm_{A}}$, $DataType$, $Enum_{Tm_{A}}$, $UserDataType_{Tm_{A}}$ are pairwise disjoint. Also, $Class_{Tm_{B}}$, $DataType$, $Enum_{Tm_{B}}$, $UserDataType_{Tm_{B}}$ are pairwise disjoint.\n    \n    Use that $Class_{Tm_{AB}} = Class_{Tm_{A}} \\cup Class_{Tm_{B}}$, $Enum_{Tm_{AB}} = Enum_{Tm_{A}} \\cup Enum_{Tm_{B}}$ and\\\\ $UserDataType_{Tm_{AB}} = UserDataType_{Tm_{A}} \\cup UserDataType_{Tm_{B}}$. Use this to split the possible cases.\n    \n    Only the case where one element is from $Class_{Tm_{A}} \\cup Enum_{Tm_{A}} \\cup UserDataType_{Tm_{A}}$ and one element is from $Class_{Tm_{B}} \\cup Enum_{Tm_{B}} \\cup UserDataType_{Tm_{B}}$ cannot be proven directly. For this case, the proof follows from the assumptions.\n    \n    \n    \\item None of the elements in $Class_{Tm_{AB}}$, $DataType$, $Enum_{Tm_{AB}}$ and $UserDataType_{Tm_{AB}}$ may be in the namespace of another element in that set.\n    \n    Use that $Class_{Tm_{AB}} = Class_{Tm_{A}} \\cup Class_{Tm_{B}}$, $Enum_{Tm_{AB}} = Enum_{Tm_{A}} \\cup Enum_{Tm_{B}}$ and\\\\ $UserDataType_{Tm_{AB}} = UserDataType_{Tm_{A}} \\cup UserDataType_{Tm_{B}}$. Use this to split the possible cases.\n    \n    It is not possible to directly proof the cases where the identifier comes from $Class_{Tm_{A}} \\cup Enum_{Tm_{A}} \\cup UserDataType_{Tm_{A}}$ and the namespace comes from $Class_{Tm_{B}} \\cup Enum_{Tm_{B}} \\cup UserDataType_{Tm_{B}}$. Furthermore, it is also not possible for the cases where the identifier comes from $Class_{Tm_{B}} \\cup Enum_{Tm_{B}} \\cup UserDataType_{Tm_{B}}$ and the namespace comes from\\\\ $Class_{Tm_{A}} \\cup Enum_{Tm_{A}} \\cup UserDataType_{Tm_{A}}$. For these cases, the proof follows from the assumptions.\n    \n    \n    \\item $Inh_{Tm_{AB}}$ is an asymmetric relation, of which the transitive closure is irreflexive.\n    \n    The transitive closure of $Inh_{Tm_{AB}}$ is irreflexive by assumption. Then show that $Inh_{Tm_{AB}}$ is an asymmetric relation using the assumption that the transitive closure of $Inh_{Tm_{AB}}$ is irreflexive.\n\\end{itemize}\n\n\\emph{Consistency properties}\n\\begin{itemize}\n    \\item For all $\\mathrm{type}_{Tm_{AB}}(f) \\in DataType \\cup Enum_{Tm_{AB}} \\cup UserDataType_{Tm_{AB}} \\cup (\\type{proper} \\times Class_{Tm_{AB}})$, it holds that $\\mathrm{lower}_{Tm_{AB}}(f) = 1$.\n    \n    Use the fact that $\\mathrm{type}_{Tm_{AB}}(f) = \\mathrm{type}_{Tm_{A}}(f)$ or $\\mathrm{type}_{Tm_{AB}}(f) = \\mathrm{type}_{Tm_{B}}(f)$.\n    \n    If $\\mathrm{type}_{Tm_{AB}}(f) = \\mathrm{type}_{Tm_{A}}(f)$, then $\\mathrm{type}_{Tm_{AB}}(f) \\in DataType \\cup Enum_{Tm_{AB}} \\cup UserDataType_{Tm_{AB}} \\cup (\\type{proper} \\times Class_{Tm_{AB}})$ only when $\\mathrm{type}_{Tm_{A}}(f) \\in DataType \\cup Enum_{Tm_{A}} \\cup UserDataType_{Tm_{A}} \\cup (\\type{proper} \\times Class_{Tm_{A}})$.\n    \n    Then if $\\mathrm{type}_{Tm_{A}}(f) \\in DataType \\cup Enum_{Tm_{A}} \\cup UserDataType_{Tm_{A}} \\cup (\\type{proper} \\times Class_{Tm_{A}})$, then $\\mathrm{lower}_{Tm_{A}}(f) = 1$. As a consequence, it must be that $\\mathrm{lower}_{Tm_{AB}}(f) = 1$.\n    \n    If $\\mathrm{type}_{Tm_{AB}}(f) = \\mathrm{type}_{Tm_{B}}(f)$, then $\\mathrm{type}_{Tm_{AB}}(f) \\in DataType \\cup Enum_{Tm_{AB}} \\cup UserDataType_{Tm_{AB}} \\cup (\\type{proper} \\times Class_{Tm_{AB}})$ only when $\\mathrm{type}_{Tm_{B}}(f) \\in DataType \\cup Enum_{Tm_{B}} \\cup UserDataType_{Tm_{B}} \\cup (\\type{proper} \\times Class_{Tm_{B}})$.\n    \n    Then if $\\mathrm{type}_{Tm_{B}}(f) \\in DataType \\cup Enum_{Tm_{B}} \\cup UserDataType_{Tm_{B}} \\cup (\\type{proper} \\times Class_{Tm_{B}})$, then $\\mathrm{lower}_{Tm_{B}}(f) = 1$. As a consequence, it must be that $\\mathrm{lower}_{Tm_{AB}}(f) = 1$.\n    \n    \n    \\item For all $\\mathrm{type}_{Tm_{AB}}(f) \\in (\\type{nullable} \\times Class_{Tm_{AB}})$, it holds that $\\mathrm{lower}_{Tm_{AB}}(f) = 0$.\n    \n    Use the fact that $\\mathrm{type}_{Tm_{AB}}(f) = \\mathrm{type}_{Tm_{A}}(f)$ or $\\mathrm{type}_{Tm_{AB}}(f) = \\mathrm{type}_{Tm_{B}}(f)$.\n    \n    If $\\mathrm{type}_{Tm_{AB}}(f) = \\mathrm{type}_{Tm_{A}}(f)$, then $\\mathrm{type}_{Tm_{AB}}(f) \\in (\\type{nullable} \\times Class_{Tm_{AB}})$ only when $\\mathrm{type}_{Tm_{A}}(f) \\in (\\type{nullable} \\times Class_{Tm_{A}})$.\n    \n    Then if $\\mathrm{type}_{Tm_{A}}(f) \\in (\\type{nullable} \\times Class_{Tm_{A}})$, then $\\mathrm{lower}_{Tm_{A}}(f) = 0$. As a consequence, it must be that $\\mathrm{lower}_{Tm_{AB}}(f) = 0$.\n    \n    If $\\mathrm{type}_{Tm_{AB}}(f) = \\mathrm{type}_{Tm_{B}}(f)$, then $\\mathrm{type}_{Tm_{AB}}(f) \\in (\\type{nullable} \\times Class_{Tm_{AB}})$ only when $\\mathrm{type}_{Tm_{B}}(f) \\in (\\type{nullable} \\times Class_{Tm_{B}})$.\n    \n    Then if $\\mathrm{type}_{Tm_{B}}(f) \\in (\\type{nullable} \\times Class_{Tm_{AB}})$, then $\\mathrm{lower}_{Tm_{B}}(f) = 0$. As a consequence, it must be that $\\mathrm{lower}_{Tm_{AB}}(f) = 0$.\n    \n    \n    \\item For all $\\mathrm{type}_{Tm_{AB}}(f) \\not\\in Container_{Tm_{AB}}$, it holds that $\\mathrm{upper}_{Tm_{AB}}(f) = 1$.\n    \n    Use the fact that $\\mathrm{type}_{Tm_{AB}}(f) = \\mathrm{type}_{Tm_{A}}(f)$ or $\\mathrm{type}_{Tm_{AB}}(f) = \\mathrm{type}_{Tm_{B}}(f)$.\n    \n    If $\\mathrm{type}_{Tm_{AB}}(f) = \\mathrm{type}_{Tm_{A}}(f)$, then $\\mathrm{type}_{Tm_{AB}}(f) \\not\\in Container_{Tm_{AB}}$ only when $\\mathrm{type}_{Tm_{A}}(f) \\not\\in Container_{Tm_{A}}$.\n    \n    Then if $\\mathrm{type}_{Tm_{A}}(f) \\not\\in Container_{Tm_{A}}$, then $\\mathrm{upper}_{Tm_{A}}(f) = 1$. As a consequence, must also be $\\mathrm{upper}_{Tm_{AB}}(f) = 1$.\n    \n    If $\\mathrm{type}_{Tm_{AB}}(f) = \\mathrm{type}_{Tm_{B}}(f)$, then $\\mathrm{type}_{Tm_{AB}}(f) \\not\\in Container_{Tm_{AB}}$ only when $\\mathrm{type}_{Tm_{B}}(f) \\not\\in Container_{Tm_{B}}$.\n    \n    Then if $\\mathrm{type}_{Tm_{B}}(f) \\not\\in Container_{Tm_{B}}$, then $\\mathrm{upper}_{Tm_{B}}(f) = 1$. As a consequence, must also be $\\mathrm{upper}_{Tm_{AB}}(f) = 1$.\n\n\n    \\item $[ \\type{containment}, r ] \\in Prop_{Tm_{AB}} \\land [ \\type{opposite}, r, r' ] \\in Prop_{Tm_{AB}} \\Longrightarrow upper_{Tm_{AB}}(r') = 1$.\n    \n    Use the fact that $[ \\type{containment}, r ] \\in Prop_{Tm_{AB}}$ means that $[ \\type{containment}, r ] \\in Prop_{Tm_{A}}$ or $[ \\type{containment}, r ] \\in Prop_{Tm_{B}}$\n    \n    Also use the fact that $[ \\type{opposite}, r, r' ] \\in Prop_{Tm_{AB}}$ means that $[ \\type{opposite}, r, r' ] \\in Prop_{Tm_{A}} \\setminus Prop_{Tm_{B}}$, $[ \\type{opposite}, r, r' ] \\in Prop_{Tm_{B}} \\setminus Prop_{Tm_{A}}$ or $\\type{opposite}, r, r' ] \\in Prop_{Tm_{A}} \\cap Prop_{Tm_{B}}$.\n    \n    Based on these two facts, make a case distinction of all 6 possible cases. The case where $[ \\type{opposite}, r, r' ] \\in Prop_{Tm_{A}} \\setminus Prop_{Tm_{B}}$ and $[ \\type{containment}, r ] \\in Prop_{Tm_{B}}$ is invalid, since $r$ cannot be part of $Field_{Tm_B}$ by definition of the combination of properties. Similarly, the case  $[ \\type{opposite}, r, r' ] \\in Prop_{Tm_{B}} \\setminus Prop_{Tm_{A}}$ and $[ \\type{containment}, r ] \\in Prop_{Tm_{A}}$ is also invalid.\n    \n    For the other cases, at least $\\mathrm{upper}_{Tm_{A}}(r') = 1$ or $\\mathrm{upper}_{Tm_{B}}(r') = 1$. The upper bound of $r$ in the other type model may be larger than $1$. By the definition of the combination of field signatures, $\\mathrm{upper}_{Tm_{AB}}(r') = 1$.\n    \n    \n    \\item $[ \\type{defaultValue}, f, v ] \\in Prop_{Tm_{AB}} \\land [ \\type{defaultValue}, f, v' ] \\in Prop_{Tm_{AB}} \\Longrightarrow v = v'$.\n    \n    Use the fact that $[ \\type{defaultValue}, f, v ] \\in Prop_{Tm_{AB}}$ means that $[ \\type{defaultValue}, f, v ] \\in Prop_{Tm_{A}} \\setminus Prop_{Tm_{B}}$, $[ \\type{defaultValue}, f, v ] \\in Prop_{Tm_{B}} \\setminus Prop_{Tm_{A}}$ or $[ \\type{defaultValue}, f, v ] \\in Prop_{Tm_{A}} \\cap Prop_{Tm_{B}}$.\n    \n    Also use the similar fact for $[ \\type{defaultValue}, f, v' ] \\in Prop_{Tm_{AB}}$.\n    \n    Now make a case distinction based on these facts. The case where $[ \\type{defaultValue}, f, v ] \\in Prop_{Tm_{A}} \\setminus Prop_{Tm_{B}}$ and $[ \\type{defaultValue}, f, v' ] \\in Prop_{Tm_{B}} \\setminus Prop_{Tm_{A}}$ is invalid, since $f$ cannot be part of $Field_{Tm_B}$ by definition of the combination of properties. Similarly, the case $[ \\type{defaultValue}, f, v ] \\in Prop_{Tm_{B}} \\setminus Prop_{Tm_{A}}$ and $[ \\type{defaultValue}, f, v' ] \\in Prop_{Tm_{A}} \\setminus Prop_{Tm_{B}}$ is also invalid.\n    \n    In all other cases, use the fact that $v = v'$ in both $Tm_{A}$ and $Tm_{B}$ to show that $v = v'$ in $Tm_{AB}$.\n    \n    \n    \\item $[ \\type{identity}, c_1, A_1 ] \\in Prop_{Tm_{AB}} \\land [ \\type{identity}, c_2, A_2 ] \\in Prop_{Tm_{AB}}\\: \\land\\: !c_1 \\sqsubseteq_{Tm_{AB}}\\, !c_2 \\Longrightarrow A_1 \\subseteq A_2$.\n    \n    First establish that $!c_1 \\sqsubseteq_{Tm_A}\\ !c_2$, $!c_1 \\sqsubseteq_{Tm_B}\\ !c_2$ or $!c_1 \\not\\sqsubseteq_{Tm_A}\\ !c_2\\ \\land\\ !c_1 \\not\\sqsubseteq_{Tm_B}\\ !c_2$.\n    \n    Then use the fact that $[ \\type{identity}, c_1, A_1 ] \\in Prop_{Tm_{AB}}$ means that $[ \\type{identity}, c_1, A_1 ] \\in Prop_{Tm_{A}} \\setminus Prop_{Tm_{B}}$, $[ \\type{identity}, c_1, A_1 ] \\in Prop_{Tm_{B}} \\setminus Prop_{Tm_{A}}$ or $[ \\type{identity}, c_1, A_1 ] \\in Prop_{Tm_{A}} \\cap Prop_{Tm_{B}}$.\n    \n    Also use the similar fact for $[ \\type{identity}, c_2, A_2 ] \\in Prop_{Tm_{AB}}$.\n    \n    Make a case distinction using the facts above. The case where $!c_1 \\sqsubseteq_{Tm_A}\\ !c_2$, $[ \\type{identity}, c_1, A_1 ] \\in Prop_{Tm_{A}} \\setminus Prop_{Tm_{B}}$ and $[ \\type{identity}, c_2, A_2 ] \\in Prop_{Tm_{B}} \\setminus Prop_{Tm_{A}}$ is invalid, since $c_2$ must be part of $Class_{Tm_A}$ to have $!c_1 \\sqsubseteq_{Tm_A}\\ !c_2$. Similarly, the case $!c_1 \\sqsubseteq_{Tm_B}\\ !c_2$, $[ \\type{identity}, c_1, A_1 ] \\in Prop_{Tm_{B}} \\setminus Prop_{Tm_{A}}$ and $[ \\type{identity}, c_2, A_2 ] \\in Prop_{Tm_{A}} \\setminus Prop_{Tm_{B}}$ is also invalid.\n\n    Furthermore, the case where $!c_1 \\sqsubseteq_{Tm_A}\\ !c_2$ and $[ \\type{identity}, c_1, A_1 ] \\in Prop_{Tm_{B}} \\setminus Prop_{Tm_{A}}$ is invalid, as well as $!c_1 \\sqsubseteq_{Tm_B}\\ !c_2$ and $[ \\type{identity}, c_1, A_1 ] \\in Prop_{Tm_{A}} \\setminus Prop_{Tm_{B}}$\n    \n    Then solve the proof for all cases where $!c_1 \\sqsubseteq_{Tm_A}\\ !c_2$ or $!c_1 \\sqsubseteq_{Tm_B}\\ !c_2$. In the cases where $!c_1 \\sqsubseteq_{Tm_B}\\ !c_2$ or $!c_1 \\not\\sqsubseteq_{Tm_A}\\ !c_2\\ \\land\\ !c_1 \\not\\sqsubseteq_{Tm_B}\\ !c_2$, distinguish once more two cases: $c1 = c2$ and $c1 \\neq c2$.\n    \n    In case that $c1 = c2$, show that when $!c_1 \\sqsubseteq_{Tm_A}\\ !c_2$ or $!c_1 \\sqsubseteq_{Tm_B}\\ !c_2$, it cannot be the case that $!c_1 \\sqsubseteq_{Tm_{AB}}\\, !c_2$ because of the reflexitivity of the subtype relation.\n    \n    Finally, if $c1 \\neq c2$, the proof is given by assumption.\n    \n    \n    \\item $[ \\type{keyset}, r, A ] \\in Prop_{Tm_{AB}} \\land [ \\type{keyset}, r, A' ] \\in Prop_{Tm_{AB}} \\Longrightarrow A = A'$.\n    \n    Use the fact that $[ \\type{keyset}, r, A ] \\in Prop_{Tm_{AB}}$ means that $[ \\type{keyset}, r, A ] \\in Prop_{Tm_{A}} \\setminus Prop_{Tm_{B}}$, $[ \\type{keyset}, r, A ] \\in Prop_{Tm_{B}} \\setminus Prop_{Tm_{A}}$ or $[ \\type{keyset}, r, A ] \\in Prop_{Tm_{A}} \\cap Prop_{Tm_{B}}$.\n    \n    Also use the similar fact for $[ \\type{keyset}, r, A' ] \\in Prop_{Tm_{AB}}$.\n    \n    Now make a case distinction based on these facts. The case where $[ \\type{keyset}, r, A ] \\in Prop_{Tm_{A}} \\setminus Prop_{Tm_{B}}$ and $[ \\type{keyset}, r, A' ] \\in Prop_{Tm_{B}} \\setminus Prop_{Tm_{A}}$ is invalid, since $r$ cannot be part of $Field_{Tm_B}$ by definition of the combination of properties. Similarly, the case $[ \\type{keyset}, r, A ] \\in Prop_{Tm_{B}} \\setminus Prop_{Tm_{A}}$ and $[ \\type{keyset}, r, A' ] \\in Prop_{Tm_{A}} \\setminus Prop_{Tm_{B}}$ is also invalid.\n    \n    In all other cases, use the fact that $A = A'$ in both $Tm_{A}$ and $Tm_{B}$ to show that $A = A'$ in $Tm_{AB}$.\n    \n    \n    \\item $[ \\type{opposite}, r, r' ] \\in Prop_{Tm_{AB}} \\land [ \\type{opposite}, r, r'' ] \\in Prop_{Tm_{AB}} \\Longrightarrow r' = r''$.\n    \n    Use the fact that $[ \\type{opposite}, r, r' ] \\in Prop_{Tm_{AB}}$ means that $[ \\type{opposite}, r, r' ] \\in Prop_{Tm_{A}} \\setminus Prop_{Tm_{B}}$, $[ \\type{opposite}, r, r' ] \\in Prop_{Tm_{B}} \\setminus Prop_{Tm_{A}}$ or $[ \\type{opposite}, r, r' ] \\in Prop_{Tm_{A}} \\cap Prop_{Tm_{B}}$.\n    \n    Also use the similar fact for $[ \\type{opposite}, r, r'' ] \\in Prop_{Tm_{AB}}$.\n    \n    Now make a case distinction based on these facts. The case where $[ \\type{opposite}, r, r' ] \\in Prop_{Tm_{A}} \\setminus Prop_{Tm_{B}}$ and $[ \\type{opposite}, r, r'' ] \\in Prop_{Tm_{B}} \\setminus Prop_{Tm_{A}}$ is invalid, since $r$ cannot be part of $Field_{Tm_B}$ by definition of the combination of properties. Similarly, the case $[ \\type{opposite}, r, r' ] \\in Prop_{Tm_{B}} \\setminus Prop_{Tm_{A}}$ and $[ \\type{opposite}, r, r'' ] \\in Prop_{Tm_{A}} \\setminus Prop_{Tm_{B}}$ is also invalid.\n    \n    In all other cases, use the fact that $r' = r''$ in both $Tm_{A}$ and $Tm_{B}$ to show that $r' = r''$ in $Tm_{AB}$.\n    \n    \n    \\item $[ \\type{opposite}, r, r' ] \\in Prop_{Tm_{AB}} \\Longleftrightarrow [ \\type{opposite}, r', r ] \\in Prop_{Tm_{AB}}$.\n    \n    Use the fact that $[ \\type{opposite}, r, r' ] \\in Prop_{Tm_{AB}}$ means that $[ \\type{opposite}, r, r' ] \\in Prop_{Tm_{A}} \\setminus Prop_{Tm_{B}}$, $[ \\type{opposite}, r, r' ] \\in Prop_{Tm_{B}} \\setminus Prop_{Tm_{A}}$ or $[ \\type{opposite}, r, r' ] \\in Prop_{Tm_{A}} \\cap Prop_{Tm_{B}}$.\n    \n    Show that if $[ \\type{opposite}, r, r' ] \\in Prop_{Tm_{A}} \\setminus Prop_{Tm_{B}}$, then $[ \\type{opposite}, r', r ] \\in Prop_{Tm_{A}} \\setminus Prop_{Tm_{B}}$. And therefore, $[ \\type{opposite}, r', r ] \\in Prop_{Tm_{AB}}$.\n    \n    Also show that if $[ \\type{opposite}, r, r' ] \\in Prop_{Tm_{B}} \\setminus Prop_{Tm_{A}}$, then $[ \\type{opposite}, r', r ] \\in Prop_{Tm_{B}} \\setminus Prop_{Tm_{A}}$. And therefore, $[ \\type{opposite}, r', r ] \\in Prop_{Tm_{AB}}$.\n    \n    Finally, show that if $[ \\type{opposite}, r, r' ] \\in Prop_{Tm_{A}} \\cap Prop_{Tm_{B}}$, then $[ \\type{opposite}, r', r ] \\in Prop_{Tm_{A}} \\cap Prop_{Tm_{B}}$. And therefore, $[ \\type{opposite}, r', r ] \\in Prop_{Tm_{AB}}$.s\n\\end{itemize}\n\nThe proofs of all these individual properties complete the entire proof.\n\\end{proof}\n\nAs explained before, \\cref{defin:transformation_framework:type_models_and_type_graphs:combining_type_models:tmod_combine_correct} does not take into account that the type models are supposed to be distinct except for a set of types. The following lemma is an alternation of the previous theorem, which takes this into account.\n\n\\begin{lem}[Consistency of the combination (mostly) distinct of type models]\n\\label{defin:transformation_framework:type_models_and_type_graphs:combining_type_models:tmod_combine_merge_correct}\nAssume that $Tm_A$ and $Tm_B$ are consistent type models in the sense of \\cref{defin:formalisations:ecore_formalisation:type_models:type_model_consistency}. Also, ensure that the type models are fully distinct except for a set of types $T$. Furthermore, assume the following properties:\n\\begin{itemize}\n    \\item Identifiers used for a class in $Tm_A$ cannot be used for an enumeration type or user-defined data type in $Tm_B$: $\\forall c \\in Class_{Tm_A}\\!: c \\not\\in Enum_{Tm_B} \\land c \\not\\in UserDataType_{Tm_B}$.\n    \\item Identifiers used for a class in $Tm_B$ cannot be used for an enumeration type or user-defined data type in $Tm_A$: $\\forall c \\in Class_{Tm_B}\\!: c \\not\\in Enum_{Tm_A} \\land c \\not\\in UserDataType_{Tm_A}$.\n    \\item Identifiers used for an enumeration type in $Tm_A$ cannot be used for a class or user-defined data type in $Tm_B$: $\\forall c \\in Enum_{Tm_A}\\!: c \\not\\in Class_{Tm_B} \\land c \\not\\in UserDataType_{Tm_B}$.\n    \\item Identifiers used for an enumeration type in $Tm_B$ cannot be used for a class or user-defined data type in $Tm_A$: $\\forall c \\in Enum_{Tm_B}\\!: c \\not\\in Class_{Tm_A} \\land c \\not\\in UserDataType_{Tm_A}$.\n    \\item Identifiers from $Tm_A$ may not be in the namespace of an identifier in $Tm_B$: $\\forall x \\in Class_{Tm_A} \\cup Enum_{Tm_A} \\cup UserDataType_{Tm_A}; y \\in Class_{Tm_B} \\cup Enum_{Tm_B} \\cup UserDataType_{Tm_B}\\!:$\\\\$x \\text{ not in the namespace of } y$\n    \\item Identifiers from $Tm_B$ may not be in the namespace of an identifier in $Tm_A$: $\\forall x \\in Class_{Tm_B} \\cup Enum_{Tm_B} \\cup UserDataType_{Tm_B}; y \\in Class_{Tm_A} \\cup Enum_{Tm_A} \\cup UserDataType_{Tm_A}\\!:$\\\\$x \\text{ not in the namespace of } y$\n    \\item The transitive closure of the inheritance relation is irreflexive: $(Inh_{Tm_A} \\cup Inh_{Tm_B})^+$ is irreflexive\n    \\item For any superclass with an identity, the identity of the subclasses must be a superset of the identity of the superclass: $\\forall c_1\\ c_2\\ A_1\\ A_2\\!: [ \\type{identity}, c_1, A_1 ] \\in \\mathrm{prop\\_\\!combine}(Tm_A, Tm_B) \\land [ \\type{identity}, c_2, A_2 ] \\in \\mathrm{prop\\_\\!combine}(Tm_A, Tm_B) \\land c_1 \\neq c_2\\ \\land\\ !c_1 \\not\\sqsubseteq_{Tm_A}\\ !c_2\\ \\land\\ !c_1 \\not\\sqsubseteq_{Tm_B}\\ !c_2\\ \\land\\ !c_1 \\sqsubseteq_{\\mathrm{combine}(Tm_A, Tm_B)}\\ !c_2 \\implies A \\subseteq B$\n    \\item For all shared classes, if $Tm_{A}$ defines a identity, $Tm_{B}$ should define the same identity, and vice versa: $\\forall c \\in Class_{Tm_A} \\cap Class_{Tm_B}\\!: [ \\type{identity}, c, A ] \\in Prop_{Tm_A} \\Longleftrightarrow [ \\type{identity}, c, A ] \\in Prop_{Tm_B}$.\n\\end{itemize}\n\nThen $\\mathrm{combine}(Tm_A, Tm_B)$ is a consistent type model in the sense of \\cref{defin:formalisations:ecore_formalisation:type_models:type_model_consistency}.\n\\isabellelref{tmod_combine_merge_correct}{Ecore.Type_Model_Combination}\n\\end{lem}\n\n\\begin{proof}\nUse \\cref{defin:transformation_framework:type_models_and_type_graphs:combining_type_models:tmod_combine_correct} to show that $\\mathrm{combine}(Tm_A, Tm_B)$ is a consistent type model. Use the assumptions given. Some assumptions of \\cref{defin:transformation_framework:type_models_and_type_graphs:combining_type_models:tmod_combine_correct} become irrelevant because $Tm_A$ and $Tm_B$ are mostly distinct.\n\\end{proof}\n\nFinally, the concept of compatibility between two type models is defined.\n\n\\begin{defin}[Compatibility of type models]\n\\label{defin:transformation_framework:type_models_and_type_graphs:combining_type_models:compatibility}\nAssume type models $Tm_A$ and $Tm_B$. We say that $Tm_A$ is compatible with $Tm_B$ if $\\mathrm{combine}(Tm_A, Tm_B)$ is a consistent type model in the sense of \\cref{defin:formalisations:ecore_formalisation:type_models:type_model_consistency}.\n\\end{defin}\n\nThe notion of compatibility will be used later as a way to denote type models that can be combined with other type models without loss of consistency.", "meta": {"hexsha": "0fc8d6bd8f2ed85cae1198a31caa6b4ae607ff3b", "size": 57190, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/tex/04_transformation_framework/03_type_models_and_type_graphs/01_combining_type_models.tex", "max_stars_repo_name": "RemcodM/thesis-ecore-groove-formalisation", "max_stars_repo_head_hexsha": "a0e860c4b60deb2f3798ae2ffc09f18a98cf42ca", "max_stars_repo_licenses": ["AFL-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thesis/tex/04_transformation_framework/03_type_models_and_type_graphs/01_combining_type_models.tex", "max_issues_repo_name": "RemcodM/thesis-ecore-groove-formalisation", "max_issues_repo_head_hexsha": "a0e860c4b60deb2f3798ae2ffc09f18a98cf42ca", "max_issues_repo_licenses": ["AFL-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis/tex/04_transformation_framework/03_type_models_and_type_graphs/01_combining_type_models.tex", "max_forks_repo_name": "RemcodM/thesis-ecore-groove-formalisation", "max_forks_repo_head_hexsha": "a0e860c4b60deb2f3798ae2ffc09f18a98cf42ca", "max_forks_repo_licenses": ["AFL-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 87.4464831804, "max_line_length": 782, "alphanum_fraction": 0.6955936353, "num_tokens": 18993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.3220103404593003}}
{"text": "\\begin{appendices}\n    \n\\section{\\sne~magnitude}\n\n\\begin{figure}[htbp]\n\\begin{center}\n  \\includegraphics[width=0.9\\textwidth]{LC_faint.png}\n \\caption{Magnitude as a function of time and redshift for a faint type Ia supernovae and for $g$ (top), $r$ (middle) and $i$ (bottom) bands.}\\label{fig:lcfaint}\n\\end{center}\n\\end{figure}\n\n\\begin{figure}[htbp]\n\\begin{center}\n  \\includegraphics[width=0.9\\textwidth]{LC_medium.png}\n \\caption{Magnitude as a function of time and redshift for a medium type Ia supernovae and for $g$ (top), $r$ (middle) and $i$ (bottom) bands.}\\label{fig:lcmedium}\n\\end{center}\n\\end{figure}\n\n\\begin{figure}[htbp]\n\\begin{center}\n  \\includegraphics[width=0.9\\textwidth]{LC_bright.png}\n \\caption{Magnitude as a function of time and redshift for a bright type Ia supernovae and for $g$ (top), $r$ (middle) and $i$ (bottom) bands.}\\label{fig:lcbright}\n\\end{center}\n\\end{figure}\n\n\\section{Illustration of the method}\n\\begin{figure}[htbp]\n\\begin{center}\n  \\includegraphics[width=0.8\\textwidth]{procedure.png}\n \\caption{Illustration of the method used to estimate saturation effects. To each LC simulated point (first row) corresponds a seeing (second row) from which a factor corresponding to the highest fraction of energy deposited in a pixel is estimated (third row). We multiply this factor by the exposure time (here 15s) and the flux to estimate (fourth row) the highest signal deposited (in pe) in a pixel.  LC points corresponding to saturation are removed if their fluxes are greater or equal the ccd full well ((red dotted line; 90 kpe).}\\label{fig:method}\n\\end{center}\n\\end{figure}\n\n\\section{Saturation effects on flux distribution}\n\n\\begin{figure}[htbp]\n\\begin{center}\n  \\includegraphics[width=0.9\\textwidth]{Flux_faint.png}\n \\caption{Saturation effect on flux distribution for a faint \\sne. Flux fraction variations as a function of the redshift are given for $gri$ bands and four (exposure time, full well) configurations: (15s, 90k \\pe) (top left),  (15s, 120k \\pe) (top right), (30s, 90k \\pe) (bottom left),  (30s, 120k \\pe) (bottom right). All LC points have been considered to draw full lines. Dotted lines correspond to the case where saturated fluxes have been removed in the estimation (median values).}\\label{fig:fluxfaint}\n\\end{center}\n\\end{figure}\n\n\\begin{figure}[htbp]\n\\begin{center}\n  \\includegraphics[width=0.9\\textwidth]{Flux_bright.png}\n  \\caption{Saturation effect on flux distribution for a bright \\sne. Flux fraction variations as a function of the redshift are given for $gri$ bands and four (exposure time, full well) configurations: (15s, 90k \\pe) (top left),  (15s, 120k \\pe) (top right), (30s, 90k \\pe) (bottom left),  (30s, 120k \\pe) (bottom right). All LC points have been considered to draw full lines. Dotted lines correspond to the case where saturated fluxes have been removed in the estimation (median values).}\\label{fig:fluxbright}\n  \n\\end{center}\n\\end{figure}\n\\newpage\n\\section{Saturation effects on Signal-to-Noise Ratio}\n\n\\begin{figure}[htbp]\n\\begin{center}\n  \\includegraphics[width=0.9\\textwidth]{SNR_faint.png}\n \\caption{Saturation effect on Signal-to-Noise Ratio for a faint \\sne. SNR (normalized to SNR values estimated without saturation included) variations as a function of the redshift are given for $gri$ bands and four (exposure time, full well) configurations: (15s, 90k \\pe) (top left),  (15s, 120k \\pe) (top right), (30s, 90k \\pe) (bottom left),  (30s, 120k \\pe) (bottom right),}\\label{fig:snrfaint}\n\\end{center}\n\\end{figure}\n\n\\begin{figure}[htbp]\n\\begin{center}\n  \\includegraphics[width=0.9\\textwidth]{SNR_bright.png}\n \\caption{Saturation effect on Signal-to-Noise Ratio for a bright \\sne. SNR (normalized to SNR values estimated without saturation included) variations as a function of the redshift are given for $gri$ bands and four (exposure time, full well) configurations: (15s, 90k \\pe) (top left),  (15s, 120k \\pe) (top right), (30s, 90k \\pe) (bottom left),  (30s, 120k \\pe) (bottom right),}\\label{fig:snrbright}\n\\end{center}\n\\end{figure}\n\\newpage\n\\section{Saturation effects on \\colorerr}\n\n\\begin{figure}[htbp]\n\\begin{center}\n  \\includegraphics[width=0.9\\textwidth]{sigmac_faint.png}\n \\caption{Saturation effect on \\colorerr~for a faint \\sne. \\colorerr~variations as a function of the redshift are given for $gri$ bands and four (exposure time, full well) configurations: (15s, 90k \\pe) (top left),  (15s, 120k \\pe) (top right), (30s, 90k \\pe) (bottom left),  (30s, 120k \\pe) (bottom right). Dotted lines correspond to median values if LC saturated points are removed from \\colorerr~estimation. Full lines correspond to the case where all LC points are considered (median values).}\\label{fig:sigmafaint}\n\\end{center}\n\\end{figure}\n\n\\begin{figure}[htbp]\n\\begin{center}\n  \\includegraphics[width=0.9\\textwidth]{sigmac_bright.png}\n \\caption{Saturation effect on \\colorerr~for a bright \\sne. \\colorerr~variations as a function of the redshift are given for $gri$ bands and four (exposure time, full well) configurations: (15s, 90k \\pe) (top left),  (15s, 120k \\pe) (top right), (30s, 90k \\pe) (bottom left),  (30s, 120k \\pe) (bottom right). Dotted lines correspond to median values if LC saturated points are removed from \\colorerr~estimation. Full lines correspond to the case where all LC points are considered (median values).}\\label{fig:sigmabright}\n\\end{center}\n\\end{figure}\n\n\n\n\\end{appendices}\n\n\n\n", "meta": {"hexsha": "992c8f1b65da16ec7700e27ba3acee4ec60d4a3a", "size": 5380, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "appendix.tex", "max_stars_repo_name": "pgris/Saturation_Note", "max_stars_repo_head_hexsha": "505f113a37bc8628c6d2c3f176ce073e5a7d71fc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "appendix.tex", "max_issues_repo_name": "pgris/Saturation_Note", "max_issues_repo_head_hexsha": "505f113a37bc8628c6d2c3f176ce073e5a7d71fc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "appendix.tex", "max_forks_repo_name": "pgris/Saturation_Note", "max_forks_repo_head_hexsha": "505f113a37bc8628c6d2c3f176ce073e5a7d71fc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 60.4494382022, "max_line_length": 557, "alphanum_fraction": 0.7470260223, "num_tokens": 1631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381667555713, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.32196816377828635}}
{"text": "%!TEX root = fastZKP.tex\n\\section{Preliminaries}\n\\label{sec::prelim}\n\n\\subsection{Notation}\n\nIn this paper, we use $\\lambda$ to denote the security parameter, and $\\neg(\\lambda)$ to denote the negligible function in $\\lambda$. ``PPT\" stands for probabilistic polynomial time. We use $f(),h()$ for polynomials, $x,y,z$ for vectors of variables and $g,u,v$ for vectors of values. $x_i$ denotes the $i$-th variable in $x$. We use bold letters such as $\\textbf{A}$ to represent arrays. For a multivariate polynomial $f$, its \"variable-degree\" is the maximum degree of $f$ in any of its variables.\n\n\\paragraph{Bilinear pairings.} Let $\\mathbb{G}, \\mathbb{G}_T$ be two groups of prime order $p$ and let $g\\in\\mathbb{G}$ be a generator. $e: \\mathbb{G}\\times\\mathbb{G}\\rightarrow\\mathbb{G}_T$ denotes a bilinear map and we use $\\mathsf{bp}=(p,\\mathbb{G},\\mathbb{G}_T,e,g)\\leftarrow\\mathsf{BilGen}(1^\\lambda)$ for the generation of parameters for the bilinear map. Our scheme relies on the $q$-Strong Bilinear Diffie-Hellman ($q$-SBDH) assumption and an extended version of the Power Knowledge of Exponent (PKE) assumption. We present the assumptions formally in Appendix~\\ref{app:assume}.\n\n\n\n\\subsection{Interactive Proofs and Zero-knowledge Arguments}\n\n\\paragraph{Interactive proofs.} An interactive proof allows a prover $\\P$ to convince a verifier $\\V$ the validity of some statement. The interactive proof runs in several rounds, allowing $\\V$ to ask questions in each round based on $\\P$'s answers of previous rounds. We phrase this in terms of $\\P$ trying to convince $\\V$ that $f(x)=1$. The proof system is interesting only when the running time of $\\V$ is less than the time of directly computing the function $f$. We formalize interactive proofs in the following:\t\n\\begin{definition}\\label{def:ip}\n\tLet $f$ be a Boolean function. A pair of interactive machines $\\langle\\mathcal{P}, \\mathcal{V}\\rangle$ is an interactive proof for $f$ with soundness $\\epsilon$ if the following holds:\n\t\\begin{itemize}\n\t\t\\item {\\bf Completeness.} For every $x$ such that $f(x) = 1$ it holds that $\\Pr[\\langle\\mathcal{P}, \\mathcal{V}\\rangle(x)=accept]=1$.\n\t\t\\item {\\bf $\\epsilon$-Soundness.} For any $x$ with $f(x) \\neq 1$ and any $\\mathcal{P}^*$ it holds that $\\Pr[\\langle\\mathcal{P^*},\\mathcal{V}\\rangle=accept] \\le \\epsilon$\n\t\\end{itemize}\n\\end{definition}\n\n\n\\paragraph{Zero-knowledge arguments.} An argument system for an NP relationship $R$ is a protocol between a computationally-bounded prover $\\P$ and a verifier $\\V$. At the end of the protocol, $\\V$ is convinced by $\\P$ that there exists a witness $w$ such that $(x; w) \\in R$ for some input $x$. We focus on arguments of knowledge which have the stronger property that if the prover convinces the verifier of the statement validity, then the prover must know $w$. We use $\\mathcal{G}$ to represent the generation phase of the public key $\\pk$ and the verification key $\\vk$. Formally, consider the definition below, where we assume $R$ is known to $\\P$ and $\\V$.\n\n\\begin{definition}\\label{def::zkp}\n\t\n\tLet $R$ be an NP relation. A tuple of algorithm $(\\mathcal{G}, \\mathcal{P}, \\mathcal{V})$ is a zero-knowledge argument for $R$ if the following holds.\n\t\n\t\\begin{itemize}\n\t\t\n\t\t\\item \\textbf{Correctness}. For every $(\\pk, \\vk)$ output by $\\mathcal{G}(1^\\lambda)$ and $(x, w) \\in R$, \n\t\t$$\\langle \\P(\\pk, w), \\V(\\vk) \\rangle(x) = \\accept$$\n\t\t%\\babis{should not $R$ be given as input to prover and verifier?}\n\t\t\\item \\textbf{Soundness}. For any PPT prover $\\P$, there exists a PPT extractor $\\varepsilon$ such that for every $(\\pk, \\vk)$ output by $\\mathcal{G}(1^\\lambda)$ and any $x$, it holds that\n\t\t\n\t\t$$\\Pr[\\langle\\P(\\pk), \\V(\\vk) \\rangle(x) = \\accept \\wedge (x, w) \\notin R | w \\leftarrow \\varepsilon(\\pk, x)] \\leq \\neg(\\lambda)$$\n\t\t%\\babis{should not $\\mathcal{G}$ appear somewhere in the soundnesss definition here?}\n\t\t\\item \\textbf{Zero knowledge}. There exists a PPT simulator $\\S$ such that for any PPT adversary $\\A$, auxiliary input $z \\in \\{0, 1\\}^{\\mathsf{poly}(\\lambda)}$, $(x;w)\\in R$, it holds that\\\\\n\t\t%{\\footnotesize\n\t\t$\\Pr\\left[\\langle\\P(\\pk,w),\\A\\rangle=\\accept: (\\pk,\\vk)\\leftarrow\\mathcal{G}(1^\\lambda); (x,w)\\leftarrow\\A(z,\\pk,\\vk) \\right] = $\\\\\n\t\t$\\Pr\\left[\\langle\\S(\\mathsf{trap}, z, \\pk),\\A\\rangle=\\accept:(\\pk,\\vk,\\mathsf{trap})\\leftarrow\\S(1^\\lambda); (x,w)\\leftarrow\\A(z,\\pk,\\vk)\\right]$\\\\\n\t\t%}\n%\\babis{small fontsize looks ugly...}\n\t\t%where $=$ means perfect zero knowledge \\babis{this is weird. = means = probabilities. What you probably want to say is that when the probabilities are equal then the protocol is perfect zero-knowledge}. \n\t\t\n\t\\end{itemize}\n\tWe say that $(\\mathcal{G},\\P,\\V)$ is a \\textbf{succinct} argument system if the\n\trunning time of $\\V$ and the total communication between $\\P$ and $\\V$ (proof size) are $\\mathsf{poly}(\\lambda,|x|,\\log|w|)$.\n\\end{definition}\n\n\\input{CMT}\n\\input{zkvpd}\n", "meta": {"hexsha": "914582549f4c594e0defdfc40146ca83f51d956b", "size": 4882, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/manuscript/prelim.tex", "max_stars_repo_name": "niconiconi/Libra", "max_stars_repo_head_hexsha": "d8b4bebd70c1b0681fdecb66fbadeccb3f9d926e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2020-01-05T12:05:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-23T16:18:40.000Z", "max_issues_repo_path": "paper/manuscript/prelim.tex", "max_issues_repo_name": "niconiconi/Libra", "max_issues_repo_head_hexsha": "d8b4bebd70c1b0681fdecb66fbadeccb3f9d926e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-08-10T17:15:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-11T16:14:46.000Z", "max_forks_repo_path": "paper/manuscript/prelim.tex", "max_forks_repo_name": "niconiconi/Libra", "max_forks_repo_head_hexsha": "d8b4bebd70c1b0681fdecb66fbadeccb3f9d926e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2020-01-31T05:53:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-02T14:05:43.000Z", "avg_line_length": 88.7636363636, "max_line_length": 662, "alphanum_fraction": 0.703809914, "num_tokens": 1516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.3219681550798301}}
{"text": "\\chapter{Periodic Detection}\\label{chapter:detection}\n\nAs noted in XXX, XXX, and XXX, it is possible to frame the problem as a convex optimization program where the reconstruction error is minimized. However, it is important to note that the aim of this dissertation is to examine the application of the periodicity transform to audio processing (encoding to an extent). This means that there is a set of qualitative criteria that we would do well to adhere to. Specifically, the ``atoms'' into which a signal is decomposed must be ``meaningful'' in the sense that manipulating the atoms individually results in something that resembles ``atomic processes'' themselves. In other words, the idea is qualitative \\emph{coherence} versus \\emph{incoherence} of the atoms themselves. This will become increasingly clear in the remaining chapters.\n\nThis is essentially extending the idea of linearity into the qualitative domain.\n\nThe atoms are the periodic bases that describe the signal according to some qualitiative criteria which may or may not comport with the exact solution of a complete power minimization of the input signal.\n\nThis means that although the problem is framed as a power minimization problem, minimization qua minimization is not necessarily the end goal here. We are less concered with the encoding of information so as to create a perfect reconstruction of the input with a set of atoms as with the manipulation of the information after decomposition so that the combined result is qualitatively coherent with the original signal and underlying proceses.\n\nThe words ``bases'' and ``atoms'' are often used interchangebly in this text, although, in general, ``atoms`` refer to a single $p$-periodic component of length $p$ and ``bases'' refers to those atoms periodically extended to $N$, the length of the input signal.\n\n\nTherefore, the primary concern is with retrieving an appropriate set of periodic atoms that describe the input signal to some tolerance such that the period $p$ of the base is such that $p \\leq p_{\\text{max}} < N$. These atoms must further be constrained by the qualitative condition that they must be \"listenable components\" in that when periodically extended, they sound as if they are a component of the sound that is analyzed. This will become clear in Chapter \\ref{chap:issues} when the difficulties of non-integer periods are explored. Briefly, it is possible to construct a periodic signal with virtually no residual using the Natural Bases by means of periodic functions that bear no resemblance, apart from their mathematical derivation, to the input.\\footnote{See the sound installation \\emph{same old person, new mistakes (didn't even notice)} in the author's catalog for an aesthetic exploitation of this phenomenon.}\n\nThe process in this chapter describes a way by which one may decompose an input signal into component periodic waveforms that are \"listenable\". The enumerated list below shows and briefly describes each step. We begin by letting $x$ be the input signal and we initialize $x_r = x$.\n\\begin{enumerate}\n    \\item\\textbf{Detection:} Choose the best periodic projection, $x_{r_{_p}}$, for $x_r$. Keep a record of all best periods found so far in the set $Q_i$ for step $i$. The addition of this result to $Q$ is then checked against the \\emph{stop function}, briefly described below.\n    \\item\\textbf{Reconstruction:} Construct a basis matrix that spans the space of $x$ as described by periods $Q_i$ using the Natural Bases. Compute the reconstruction and the residual error by means of a convex program.\n    \\item\\textbf{Stop Function:} Compute the value of a stop function, $s()$, that determines whether or not to continue processing. This function is arbitrary and may have arbitrary arguments.\n    \\item\\textbf{Recursion:} If one continues processing, set $x_r = x - \\sum_{q \\in Q} x_q$ and repeat the process until $s()$ calls to stop.\n\\end{enumerate}\nThe fundamental difference between this and \\cite{sethares1999periodicity} is the difference in computing the residual. That is, one can frame the residual computation as a quadratic program which allows one to alter the result of the Natural Basis to one that minimizes the reconstruction error.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Detection}\nGiven an input, the first task is to derive what integer-valued period best describes the signal. Several methods have been described in the literature (LIST SOME REFS HERE) and has been the primary are of research on the topic of periodicity transforms. For the purposes of audio manipulation and processing not limited to encoding and reconstruction, some proved to be more useful than others. The method outlined here has shown, in practice, to provide the most useful results for audio processing and is essentially a combination of the iterative methods of \\cite{sethares1999periodicity} and the underlying processes of \\cite{muresan2003orthogonal}.\n\nIn general, period detection is a maximum likelihood estimator (MLE) where the power of some period $p$ is taken on all allowable $p$'s and the result with the maximum power is chosen. Let $P_x$ be the ordered collection of periodic powers in $x$, calculated using one of the methods presented below. To choose the most likely integer period that describes the data, one simply does:\n\\begin{align}\n    \\hat{p}_{i} = argmax(P_x)\n\\end{align}\nwhere $\\hat{p}_{i}$ is the most likley period in $x$ at step $i$. Notice that due to the nature of this process, we select a \\emph{single} best period and choose additional periods during recusion and as a function of the stop function.\n\n    \\subsection{Non-orthogonalized Selection}\n    The non-orthogonal method of Sethares and Staley's $M$-best $\\gamma$ has proven to be useful in recovering component periods although it is prone to noise and miscategorization of hidden periods. Notably, it is often the case that common divisors of hidden periods are chosen in the MLE since the combined power of each component sharing a common divisor is often large due to the construction of Equation \\eqref{eq:intro:sethares:periodicNormGamma}. That is, the columns of the $P_p$ matrix are not orthogonal to each other. It is therefore possible, indeed likley, that during reconstruction, two projections $x_{p_0}$ and $x_{p_1}$ will both contribute to a common divisor period, $d$. Moreover, the $M$-best $\\gamma$ periodic power equation biases toward smaller periods, increasing the likelihood that $d$ would be chosen in the example above.\n\n    In order to calculate $P_x$, one must project $x$ independently onto all possible $p$'s, then take the periodic power of each $x_p$, selecting the one with the highest power:\n    \\begin{align}\n        P_{x_{p}} = \\frac{||x_p||^2} {\\sqrt{Np}}\n    \\end{align}\n    The projection itself is performed by using Equation \\eqref{eq:intro:setharesProjection}.\n    \\footnote{When projecting, it is often easist (and fastest) to rearrange the single row of input $S$ into a rectuangular matrix, zero-padded as necessary. Suppose $x$ is of length $N$ and we are searching for the projection of period $p$ where $N \\neq pm$ for an integer $m$. We first extend $x$ by zero-padding the appropriate number of samples until $N = pm$ and reshape $x$ into a rectangular matrix:\n    \\begin{align}\n        &\\overline{x} = \\text{zp}(x, N - (N \\text{ mod } p)) \\label{eq:detection:overlineS} \\\\\n        &\\overline{x}^{\\text{ } 1 \\times N} \\rightarrow \\overline{x}^{\\text{ } m \\times p} \\label{eq:detection:overlineSReshaped}\n    \\end{align}\n    where $m$ is an integer such that $N = mp$. This is equivalent projecting onto the $\\bm{B}_p$ subspace and omitting the zeros in the $\\delta^s_p$ functions. As such, one can the sum the matrix column-wise and divide each entry by the number of rows except for the final $N - (N \\text{ mod } p)$ columns, which are divided by the number of rows minus 1. Notice that this simply averages the values in the columns which correspond to a particular $\\delta^s_p$ vector, as \\cite{sethares1999periodicity} does.}\n\n    % Each basis matrix of period $p$ has $\\varphi(p)$ columns that are unique to $P_p$. This means that it is possible to take an orthogonal version of $P_p$ by taking only the first $\\varphi(p)$ columns of $P_p$ and setting the rest of the columns to zero. Unfortunately, doing this directly results in projections which have $p - \\varphi(p)$ zeros in every periodic repetition. This is untenable for a vareity of reasons.\n\n    % In order to distinguish a set of basis vectors constructed using the Natural Basis, let $\\bm{B}_p$ be a $N \\times p$ matrix whose columns are periodic with period $p$ so that\n    % \\begin{align}\n    %     \\bm{B}_p &= \\begin{bmatrix}\n    %             \\delta^0_p(N) &\n    %             \\delta^1_p(N) &\n    %             \\hdots &\n    %             \\delta^{p-1}_p(N) &\n    %         \\end{bmatrix}^{T}\n    % \\end{align}\n    % where $\\delta^s_p(N)$ is Eq. \\ref{eq:naturalBasisVector}.\n\n        %\n        %\n        % \\subsubsection{Windowed Projection}\n        % If $N - (N \\text{ mod } p) \\neq 0$, the projection will contain artifacts at values around $N - (N \\text{ mod } p)$ since by cutting the $p$-periodic component at a partial repetition, one introduces a step function. This effect is exacerbated as $p$ approaches $N$. \\cite{muresan2003orthogonal} suggests truncating the input $x$ to be a multiple of $p$ but this is not always desirable or possible if $N$ is small relative $p$. We can mitigate the the artifacts of $N$ not being an integer multiple of the proposed period $p$ by windowing the input and dividing by the appropriate value which will not be the same for each column. This is an application of a weighted mean to a window where the mean is each element multiplied by its weight divided by the sum of the weights:\n        % \\begin{align}\n        %     \\overline{m}_{xw} = \\frac{\\sum_{i=0}^{N-1} x[n]w[n]} {\\sum_{n=0}^{N-1} w[n] }\n        % \\end{align}\n        % where $x$ is a sequence of length $N$ and $w$ is a 1-normalized window function also of length $N$. Notice that this works only if $\\sum_{i=0}^{N-1} w[n] \\geq 1$ which is why one must normalize. By normalizing, we ensure that the sum will always be greater than 1 and that the proportion of the weights is maintained.\n        %\n        % In order to derive the values by which we outght to divide by when using a window, we take the window function $w$ and apply the same process as in Equations \\eqref{eq:detection:overlineS} and \\eqref{eq:detection:overlineSReshaped}, then sum downwards. This results in a vector of length $p$ whose values are used to divide, column-wise, by the same length vector resulting from the column-wise summation of $\\overline{S}^{\\text{ } m \\times p}$. The windowing in essense more heavily ``weights'' the center of the signal where a complete period is more likley to be present and unweights the edges where partial repetitions may be present. This is easily expanded for a no window situation, where we can essntially say that the window is a boxcar (all 1's). Moreover, the application of a window does not exacerbate the effect of an analysis and/or recovery if $N$ is not a large multiple of the contained periods.\n        %\n        % This windowing method has the additional benefit of offsetting some of the effects if the signal is enveloped. Suppose $S$ is a signal which is the composite of two sawtooth waves with periods $p_0$ and $p_1$ with a ramp envelope from $0.5$ to $1$. Here $N$ is not an integer multiple of either $p_0$, $p_1$, nor $p_0 p_1$. Figure XXX, top, shows the composite signal signal; the envelope is plainly visible. In the lower portion, the solid lines shows the recovered waveforms without windowing (or with a boxcar window) while the dashed lines shows the recovered waveforms when applying a Hann window.\n        %\n        % For the rest of this document, we will always include a window function where appropriate and denote it $w$. Thinking specifically of the sections where we project with $A$ and stuff. Probably. Show that this actually gives a better residual.\n\n    \\subsection{Orthogonal Detection}\n    It is often far preferable to detect the periodic components \\emph{orthogonally}; that is, using the method of \\cite{muresan2003orthogonal}, described in Section \\ref{section:intro:orthgonalDecomp}. This is mainly due to the aforementioned fact that for the method of Sethares and Staley above, energies become concentrated in common divisors of the actual periodic components. We follow \\cite{muresan2003orthogonal} in avoiding the direct calculation of the orthogonal subspace $P_{p}^{\\perp}$ by using Equation \\eqref{eq:intro:orthgonalProjection}. We can see that the distribution of powers is much more like what we would expect versus the method of \\cite{sethares1999periodicity}:\n\n    FIGURE HERE\n\n    The computational advantage here is that one need only project \\emph{once} after $p_{i}$ is found for a given iteration. An important note here is that the orthogonal method of Muresan and Parks \\emph{always} truncates the input signal to an integer multiple of the proposed period $p$. This, however, has not been shown to be problematic in practice.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Reconstruction}\nLet $Q_i$ be the set of periods found in $x$ by means of a projection method at step $i$. (Note that $|Q_i| = i + 1$ at the end of the detection stage in step $i$) We now ask ourselves: what is the best representation of $x$ using only periods in $Q_i$? For convience, we will often denote $Q_i$ as simply $Q$, though a particular $i$ is implied.\n\nIn \\cite{sethares1999periodicity}, the reconstruction is computed by simply summing the projections $x_q$ for $q \\in Q$. That is:\n\\begin{align}\n    \\hat{x} &= \\sum_{q \\in Q} x_q\n\\end{align}\n\nIn other literature, reconstruction of $x$ is performed similarly by solving\n\\begin{align} \\label{eq:detection:convex}\n    \\bm{A}x &= b\n\\end{align}\nthen doing\n\\begin{align}\n    \\hat{x} = \\bm{D}_{Q}^{T} b\n\\end{align}\nwhere $\\bm{A}$ is a the covariance matrix of $\\bm{D}_Q$ which is a matrix of basis vectors that spans the space of $x$ using periods $Q$ with linearly independent columns. In most cases, $D_Q$ will not be a square matrix since its row dimension is $N$. For the purposes of this dissertation, this is the primary method of reconstruction. The question now becomes: how must one construct $\\bm{D}_Q$?\n\n    \\subsection{Construction of $\\bm{D}_Q$}\\label{section:detection:D_Q}\n    Let $\\bm{D}_Q$ be a ``basis matrix'', or a matrix of linearly independent columns which span the space of the sequence $x$ with periods $q \\in Q$ of shape $N \\times c_{\\bm{D}_Q}$. The column dimensionality, $c_{\\bm{D}_Q}$, is defined as\n    \\begin{align}\n        R &= \\bigcup_{q_i \\in Q} \\text{factors}(q_i) \\label{eq:A:R} \\\\\n        c_{\\bm{D}_Q} &= \\sum_{R_i \\in R} \\varphi(R_i) \\label{eq:A:c_A}\n    \\end{align}\n    where $R$ is the union of all the factors of the periods in $Q$, $\\text{factors}(n)$ is a function which returns the set of factors of an integer $n$, and $\\varphi(n)$ is Euler's totient function. The columns of $\\bm{D}_Q$ itself are the Natural Basis of period $p$ as defined in Eq. \\ref{eq:naturalBasis}:\n    \\begin{align}\\label{eq:detection:overdeterminedDQ}\n        D_Q = \\begin{bmatrix}\n            \\bm{B}_{q_{0}} & \\bm{B}_{q_{1}} & \\hdots & \\bm{B}_{q_{i}}\n        \\end{bmatrix}^{T}\n    \\end{align}\n\n    Recall two things at this point: that the subspace $P_p$ for a given period $p$ is a matrix of shape $N \\times p$ and that each $P_p$ is not orthogonal to others. This means that $D_Q$ as constructed in Equation \\eqref{eq:detection:overdeterminedDQ} is overdetermined. Therefore, in order to avoid introducing additional power at the period $d$ for $d|p$ and have linearly independent columns, one must remove columns from each $\\bm{P}_p$ accordingly. But what columns to remove?\n\n    According to Lemma XX in \\ref{tenneti2016unified}, a Natural Basis matrix that is a full rank consists of keeping the first $\\varphi(p)$ columns of $\\bm{P}_p$ for all integers betwen 1 and $p$. A complete and not overdetermined dictioary of Natural Bases for periods 1 to $p_{\\text{max}}$ therefore consists of keeping the first $\\varphi(p)$ columns of each $\\bm{B}_p$ for $1 \\leq p \\leq p_{\\text{max}}$. This is essentially saying that for a periodic subspace of period $p$, there are $\\varphi(p)$ degrees of independence between $p$ and all other possible $p$'s. In this case, however, it is not true that we want $\\bm{D}_Q$ to contain all periods between 1 and $p_{\\text{max}}$ but rather only those periods $q \\in Q$.\n     Nonetheless, this gives an idication of how to proceed of which there are two ways: (1) we can construct $\\bm{D}_Q$ so that we separate out every factor which appears in two or more $q \\in Q$ and take care to remove that factor from $\\bm{B}_p$ by removing columns or, (2) we can construct $\\bm{D}_Q$ by keeping track of what periods have been added so far, taking care to not add a factor twice. Although both methods result in a matrix with spans the same space and are functionally equuivalent, the coefficients returned from the convex program have different meanings. The importance of this will become clear in subsequent sections.\n    %%%%% ^^^^ should probably prove that these are equivalent?!?! ^^^^^^^^\n\n        \\subsubsection{Separating out common factors in $\\bm{D}_Q$}\\label{detection:A:separateFactors}\n        For this method, we create a separate subspace for a period $d$ for any $d$ such that for any two periods $q_n, q_m \\in Q$, $d \\in \\text{factors}(q_n)$ and $d \\in \\text{factors}(q_m)$. In other words, suppose $Q = \\{8, 10\\}$. There are two common factors, 1 and 2. Therefore, the 1-space and 2-space (which itself is absent the 1-space it contains) are separated out into separate basis matricies. In this case, then,\n        \\begin{align*}\n            D_Q = \\begin{bmatrix}\n                \\bm{B}_{1} & \\bm{B}_{2} & \\bm{B}_{8} & \\bm{B}_{10}\n            \\end{bmatrix}^{T}\n        \\end{align*}\n        Notice that although 8 also contains a factor of 4 and 10 contains a factor of 5, there is no need to separate out these spaces since any energy in the 5-space will \\emph{only} be contained in the 10-space. Likewise with the 4-space and 8-space.\n\n        Begin by defining $R_i$:\n        \\begin{align}\\label{eq:A:commonFactors:R}\n            R_i &= \\Bigg( \\bigcup_{p, q \\in Q_i} \\text{factors}(p) \\cap \\text{factors}(q) \\Bigg) \\cup Q_i\n        \\end{align}\n        Notice that $R_i$ contains all elements of $Q_i$ as well as any common factors between elements in $Q_i$. In accordance with the previous convention, we will remove the subscript $i$ for simplicity of notation. To find the column dimensionality, $c_{r}$, of the basis matrix $\\bm{B}_r$ for $r \\in R$:\n        \\begin{align}\\label{eq:A:commonFactors:cp}\n            c_{r} &= r - \\sum_{d|r \\in R \\setminus r} \\varphi(d)\n        \\end{align}\n        Therefore, to constuct $\\bm{D}_Q$, we simply concatenate the subspaces $\\bm{B}_r$ for $r \\in R$:\n        \\begin{align}\\label{eq:A:commonFactors:A}\n            \\bm{D}_Q &= \\begin{bmatrix}\n                    \\bm{B}_{r_0}^{c_{r_0}} &\n                    \\bm{B}_{r_1}^{c_{r_1}} &\n                    \\hdots &\n                    \\bm{B}_{r_n}^{c_{r_n}}\n                \\end{bmatrix}\n                , \\text{ } r \\in R\n        \\end{align}\n        where the superscript indicates the number of columns of $\\bm{B}$ to keep. Using this method, it is not imporant which order we concatenate the subspaces but only that we do not doubly count a particular subspace.\\footnote{In practice and in conjunction with the extraction method presented in Chapter \\ref{chapter:extraction}, knowing the order of the columns and what part of what period they represent is of critical importance.} One can confirm the dimensionality by using Eq. \\eqref{eq:A:c_A} and checking that $\\sum_{i = 0}^{|R| - 1} c_{r_i} = c_{\\bm{D}_Q}$ where $|R|$ is the cardinality of $R$.\n\n        As an example, suppose $Q = \\{8, 10, 15\\}$. According to Eq. \\eqref{eq:A:P}:\n        \\begin{align*}\n            R &=\n                \\big(\n                \\text{ } ( \\text{factors}(8) \\cap \\text{factors}(10) ) \\text{ } \\cup\n                \\text{ } ( \\text{factors}(8) \\cap \\text{factors}(15) ) \\text{ } \\cup\n                \\text{ } ( \\text{factors}(10) \\cap \\text{factors}(15) )\n                \\text{ } \\big)\n                \\text{ } \\cup \\{8, 10, 15\\} \\\\\n            R &= \\{1, 2, 5\\} \\text{ } \\cup \\text{ } \\{8, 10, 15\\} \\\\\n            R &= \\{1, 2, 5, 8, 10, 15\\}\n        \\end{align*}\n        Now we can calculate the dimensionality of an arbitrary $p \\in P$ in any order:\n        \\begin{align*}\n            c_1 &= 1 - \\sum_{d|1 \\in \\{2, 5, 8, 10, 15\\}} \\varphi(d) = 1 \\\\\n            c_2 &= 2 - \\sum_{d|2 \\in \\{1, 5, 8, 10, 15\\}} \\varphi(d) = 1 \\\\\n            \\vdots \\\\\n            c_{10} &= 10 - \\sum_{d|10 \\in \\{1, 2, 5, 8, 15\\}} \\varphi(d) = 10 - (1 + 1 + 4) = 4 \\\\\n            \\text{etc...}\n        \\end{align*}\n        We see then that in this case,\n        \\begin{align*}\n            D_Q = \\begin{bmatrix}\n                \\bm{B}_{1}^{1} &\n                \\bm{B}_{2}^{1} &\n                \\bm{B}_{5}^{4} &\n                \\bm{B}_{8}^{6} &\n                \\bm{B}_{10}^{4} &\n                \\bm{B}_{15}^{10} &\n            \\end{bmatrix}^{T}\n        \\end{align*}\n\n    \\subsubsection{Progressive concatenation of $\\bm{D}_Q$}\\label{detection:A:progressiveConcatenation}\n    What if one wants to construct $\\bm{D}_Q$ in such a way as to \\emph{only} include subspaces which are constructed from the elements of $Q$? The advantages of this method is that it is not necessary to add subspaces of factors for the periods we are actually interested in and that it (somewhat) simplifies the process of computing the waveforms containing their subcomponents. However, it requires one to keep track of the order in which periods are added to the subspace. That is, each periodic component $q \\in Q$ also contains the components $d|q$ and one must construct the basis matrix with this in mind, taking care to remove the component from a subspace if it is already present.\n\n    To do so, we exploit the fact that $n = \\sum_{f|n} \\varphi(f)$. Let $c_{\\bm{D}_{Q_i}}$ denote the column dimensionality of $\\bm{D}_Q$ at step $i$. We also redefine Eq. \\eqref{eq:A:R}:\n    \\begin{align}\\label{eq:A:onlyPeriods:R}\n        R_i = \\bigcup^i_{q_j \\in Q_i} f(q_j)\n    \\end{align}\n    Given the above, the total column dimensionality $c_{\\bm{D}_{Q_i}}$ at step $i$ is:\n    \\begin{align*}\n        c_{\\bm{D}_{Q_i}} = \\sum_{r \\in R_i} \\varphi(r)\n    \\end{align*}\n    Therefore, the column dimensionality for any $q$ at step $i$ is:\n    \\begin{align}\\label{eq:A:noFactors:cp}\n        c_{q_i} =\n            \\begin{cases}\n                q_i, & \\text{if } i = 0 \\\\\n                c_{\\bm{D}_{Q_i}} - c_{\\bm{D}_{Q_{i-1}}}, & \\text{otherwise}\n            \\end{cases}\n    \\end{align}\n    Again, we will simplify the notation going forwrd by omitting the subscript $i$. We construct $\\bm{D}_Q$ as:\n    \\begin{align*}\n        \\bm{D}_Q &= \\begin{bmatrix}\n                \\bm{B}_{q_0}^{c_{q_0}} &\n                \\bm{B}_{q_1}^{c_{q_1}} &\n                \\hdots &\n                \\bm{B}_{q_n}^{c_{q_n}}\n            \\end{bmatrix}\n            , \\text{ } \\forall q \\in Q\n    \\end{align*}\n    In doing so, we ensure that for every subsequent subspace in $\\bm{D}_Q$ is orthogonal to all existing subspaces in $\\bm{D}_Q$.\n\n    Returning to the example in the previous section, we see that\n    \\begin{align*}\n        c_{q_0} &= c_{8} = 8 - 0 = 8 \\\\\n        c_{q_1} &= c_{10} = 16 - 8 = 8 \\\\\n        c_{q_2} &= c_{15} = 26 - 16 = 10 \\\\\n    \\end{align*}\n    Therefore:\n    \\begin{align*}\n        \\bm{D}_Q = \\begin{bmatrix}\n            \\bm{B}_{8}^{8} & \\bm{B}_{10}^{8} & \\bm{B}_{15}^{10}\n        \\end{bmatrix}\n    \\end{align*}\n    The total column dimensionality can again can be double-checked using Eq. \\eqref{eq:A:c_A}.\n\n    \\subsection{Approximation of $x$ using $\\bm{D}_Q$}\n    Once $\\bm{D}_Q$ has been appropriately constructed, we can compute $\\bm{A}$ as the covariance matrix of $\\bm{D}_Q$:\n    \\begin{align}\n        \\bm{A} = \\bm{D}_Q \\bm{D}_Q^T\n    \\end{align}\n    One then simply puts $\\bm{A}$ in the convex program and solves for the reconstruction, $\\hat{x}$, with matrix multiplication:\n    \\begin{align}\n        \\bm{A}x &= b \\label{eq:detection:reconstruction:coefficients} \\\\\n        \\hat{x} &= \\bm{A} b^{T} \\label{eq:detection:reconstruction:xHat}\n    \\end{align}\n\n    Notice that due to the reconstitution of $\\bm{D}_Q$ on each iteration, which in turn recomputes $\\bm{A}$, the resulting basis vectors, when retrived using the method described in Chapter \\ref{chapter:extraction} can change so as to minimize $x - \\hat{x}$. This possible change of the bases on each iteration is also part of the motation of the stop function, briefly described in \\ref{section:detection:stopFunction} below. Further, reconstituting $\\bm{D}_Q$ each iteration means that the coefficients $b$ and reconstruction $\\hat{x}$ is identical to projecting onto the subspaces $P_q$ for $q \\in Q$ simultaneously as is possible with orthogonal dictionaries of each component and its factors.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Stop Function}\\label{section:detection:stopFunction}\nThe selection of a stop function is critical for periodic decomposition success if one wishes to pay respect to the qualitiative criteria at the start of this chapter. That is, any formulation of the periodicity transform will invariably detect a peroidic waveform of some period $p$ with an input of Gaussian noise. In other words, just because the detection step returns a ``best'' period does not mean that that period has any correspondence to the actual content of the signal and would be of no interest in audio processing. The ``best'' period in the residual may contribute to minimizing the reconstruction error but this is a fundamentally different prospect than retriving the integer periods which best describe the signal.\n\nIt is important to note that the stop function is evaluated \\emph{before} the detection step on each iteration. This topic will be discussed further in Section \\ref{section:audioEffects:stopFunction} but suffice it to say, for now, that it is almost always a necessary condition of the detection stage as described in this dissertation.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Recursion}\\label{section:detection:recursion}\nThis step hardly needs explaination: if the criteria in the stop function is met, cease processing. Otherwise, continue to process, adding to the total set of periods found.\n\n\n% Define $P$:\n% \\begin{align*}\n%     P &= \\Bigg( \\bigcup_{\\forall p, q \\in Q} f(p) \\cap f(q) \\Bigg) \\cup Q\n% \\end{align*}\n% i.e. the union of the intersections of the factors of all the elements in $Q$.\n%\n% To find the column dimensionality, $c_{p}$, of the basis matrix $\\bm{B_p}$ for $p \\in P$:\n% \\begin{align*}\n%     % c_{p} &= p - \\sum_{f : f(p) \\cap P \\setminus p} \\varphi(f)\n%     c_{p} &= p - \\sum_{d|p \\in P \\setminus p} \\varphi(d)\n% \\end{align*}\n%\n% %% If N is the columns\n% % We then define $\\bm{A}$ as:\n% % \\begin{align*}\n% %     \\bm{A} &= \\begin{bmatrix}\n% %             \\bm{B}_{p_0} \\\\\n% %             \\bm{B}_{p_1} \\\\\n% %             \\vdots \\\\\n% %             \\bm{B}_{p_n} \\\\\n% %         \\end{bmatrix}\n% %         , \\text{ } \\forall p \\in P\n% % \\end{align*}\n% % where there are $n$ elements in $\\bm{P}$.\n%\n% To find the total column dimensionality, $c_{\\boldsymbol{A}}$ of the matrix $\\bm{A}$:\n% \\begin{align*}\n%     c_{\\bm{A}} &= \\sum_{p \\in P} c_p\n% \\end{align*}\n\n% In this way, we can be assured that not only are the basis vectors in $\\bm{A}$ linearly independent, but also that all traces of some period $q$ are removed from the residual signal $h$.\n\n% \\subsection{This also works}\n% We can also get a basis matrix for the periods in $q$ by using the same equation as above that uses $varphi(n)$ by creating $\\bm{A}$ along the way and keeping track of which periods (and factors of the periods) we've added along the way.\n%\n% Let $F = \\emptyset$. To find the column dimensionality, $c_q$, for $q \\in Q$:\n% \\begin{align}\n%     c_q &= q - \\sum_{d|q \\in F} \\varphi(d)\n% \\end{align}\n%\n% We then add elements to $F$ every time we add a basis matrix $\\bm{B}_q$ to $\\bm{A}$:\n% \\begin{align*}\n%     F &= \\{ F \\cup f(q) \\}_{\\neq}\n% \\end{align*}\n% i.e. every time we process a period $q$, add all the factors of $q$ to $F$, removing duplicates.\n%\n% Repeat this process for every $q \\in Q$, adding to $F$ along the way. (This means that we need to keep track of which factors we've added along the way which makes it uglier in some ways, better in others.)\n%\n% Therefore, we then define $\\bm{A}$ as:\n% \\begin{align*}\n%     \\bm{A} &= \\begin{bmatrix}\n%             \\bm{B}_{q_0} &\n%             \\bm{B}_{q_1} &\n%             \\hdots &\n%             \\bm{B}_{q_n}\n%         \\end{bmatrix}\n%         , \\text{ } \\forall q \\in \\bm{Q}\n% \\end{align*}\n% where there are $n$ elements in $\\bm{Q}$.\n%\n% \\section{Not a real section but describing getting the real periods back}\n", "meta": {"hexsha": "3c8673980ee7d5563d7dbfbd468cee9752b3e7d2", "size": 29669, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/detection/detection.tex", "max_stars_repo_name": "woolgathering/ucsdDissertation", "max_stars_repo_head_hexsha": "a0a08d98f6cf0962c7518de6e79ce2750eb2a751", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/detection/detection.tex", "max_issues_repo_name": "woolgathering/ucsdDissertation", "max_issues_repo_head_hexsha": "a0a08d98f6cf0962c7518de6e79ce2750eb2a751", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/detection/detection.tex", "max_forks_repo_name": "woolgathering/ucsdDissertation", "max_forks_repo_head_hexsha": "a0a08d98f6cf0962c7518de6e79ce2750eb2a751", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 93.2987421384, "max_line_length": 929, "alphanum_fraction": 0.6781489096, "num_tokens": 8019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.32196815507983007}}
{"text": "\\section{Related Work} \n\\label{sec:relatedwork}\n\nIn the past, many algorithms have been proposed to mine subgraphs from a\ngiven database of graphs. These algorithms can be mainly divided in to\ntwo classes depending on how the candidate patterns are generated.\nAlgorithms like those in \\cite{IWM03,FSG01,HWP03} are Apriori\nbased methods, i.e., a candidate pattern of size $k+1$ is generated by\ncombining two frequent graphs of size $k$ that have a common $k-1$ sized\nsubgraph.  Algorithms like those in \\cite{gSpan,borgelt2002mmf,HWP03},\non the other hand, belong to the class of pattern growth algorithms in\nwhich a candidate pattern is generated by extending a frequent pattern\nwith an edge. \n\nMining subgraphs from a single graph is a related problem which is\nsurprisingly difficult compared to mining from a database of graphs.  In\n\\cite{kuramochi2005ffp}, they defined the support of a pattern\nin a single graph as the maximum number of edge disjoint isomorphisms,\nwhich is itself a $NP$-Hard problem.  In \\cite{fiedler2007support}, they\nproposed a definition of support based on overlapping ancestor\nisomorphisms.  In \\cite{2012-kais}, they proposed\nCMDB-Miner\\xspace to mine frequent patterns from a single large graph.\nSupport of a pattern is defined as the maximum flow in an appropriately\nconstructed flow network with capacities. This method estimates the\nsupport of a pattern without enumerating its isomorphisms. The authors\nalso proposed methods to summarize the maximal frequent patterns\nextracted from the graph. In \\cite{li2010dessin}, they proposed an\nalgorithm to extract frequent patterns from dense graphs. It uses\nGADDI index proposed in \\cite{Gaddi2009} to efficiently extract the\nisomorphisms of a subgraph. \n\nThere been little work in approximate subgraph\nmining.  In \\cite{gapprox}, they proposed $gApprox$ to mine approximate\nfrequent subgraphs.  The degree of approximation between a pattern and its\nisomorphism includes label mismatches and missing edges. The search space\nis explored in a depth first order and the support of a pattern is\ncomputed by enumerating its isomorphisms. This approach is not feasible\nfor large graphs with label multiplicities as there are potentially\nexponential number of isomorphisms \\cite{2012-kais}.\nIn \\cite{JiaZH11}, they proposed APGM to approximate frequent\nsubgraphs from a database of graphs. The method is similar to the\n$gApprox$ method in that it stores the complete set of approximate\nembeddings of the current frequent pattern. The difference, however, is\nthat in \\cite{JiaZH11} the entire $1$-hop neighborhood of the current\nembeddings is explored to enumerate all extensions of the frequent\npattern and their corresponding embeddings, whereas $gApprox$ enumerates\nthe embeddings for a single extension in each step.  \nIn \\cite{SpeedUpFAS}, the authors proposed strategies\nto speed up the existing mining algorithms, by\nlimiting the number of candidates and also the number of duplicate\nchecks performed.\nIn \\cite{RAM2008}, they proposed a randomized algorithm to mine\napproximate patterns from a database graphs. In this method, an edge in\nthe approximate pattern is required to have at least a given number of\noccurrences. \n\nGraph querying is another problem that is related to\nsubgraph mining. The goal is to find matches of a given query graph in a\nsingle graph or database of graphs.  In \\cite{TALE}, they proposed an\nindexing method to extract the approximate occurrences of a given graph\nquery in large graph databases.  The algorithm proposed in\n\\cite{yan.icde:2006} extracts selective fragments from the query graph\nand queries against an index constructed from the fragments of the\ndatabase graphs. In \\cite{RandomMatching}, they proposed a polynomial\ntime algorithm for detecting isomorphism between spectrally\ndistinguishable graphs. An isomorphism, if it exists, \nis obtained by matching\nthe steady state vectors of Markov chains in both the graphs.  In\n\\cite{BerettiIndexing}, they proposed indexing and retrieval methods for\ngraph models. The problem with most of the indexing approaches is that\nthey are efficient in retrieving a single match for the query graph but\nfail at retrieving all matches, and thus are not suited to mine frequent\npatterns. Furthermore, they assume that the query given, and thus they\ndo not perform pattern enumeration as required in graph mining.\n\nFrequent pattern mining algorithms usually return a large number of\npatterns and interpreting them is a big challenge. This is especially\ntrue if the output is presented to a human user for further analysis.\nSampling approaches like those proposed in\n\\cite{2009-graphsampling,2012-kais,RAM2008} mine a representative set of\nmaximal patterns from a database of graphs or a single graph. \nIn our work, we perform a random walk in the search space\nto enumerate a maximal pattern.\n\n%The concept of using derived labels based on the\n%structure and the attributes is frequently used in detecting graph\n%isomorphism \\cite{zampelli} and computing graph kernels\n%\\cite{shervashidzeJmlr,shervashidzeNips}. \n%Our methods to prune representative sets are somewhat similar to\n%the wiesfieler lehman kernel to test isomorphism between two graphs\n%$G_1$ and $G_2$ \\cite{weisfeiler}, where after every iteration the labels are\n%sorted and renamed with a different string in such a way that the pairwise\n%relationship is maintained. $G_1$ is not isomorphic to $G_2$ \n%if the label set of the graphs differ. The specifics of how and what\n%information we update is different, and also we use the information for\n%subgraph isomorphism instead of graph isomorphism.\n\n", "meta": {"hexsha": "344e548359beb0d51da04c6db11ed4599ba65cb8", "size": 5611, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "finalversion/sigkdd13/relatedwork.tex", "max_stars_repo_name": "PranayAnchuri/approx-graph-mining-with-label-costs", "max_stars_repo_head_hexsha": "4bb1d78b52175add3955de47281c3ee0073c7943", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "finalversion/sigkdd13/relatedwork.tex", "max_issues_repo_name": "PranayAnchuri/approx-graph-mining-with-label-costs", "max_issues_repo_head_hexsha": "4bb1d78b52175add3955de47281c3ee0073c7943", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "finalversion/sigkdd13/relatedwork.tex", "max_forks_repo_name": "PranayAnchuri/approx-graph-mining-with-label-costs", "max_forks_repo_head_hexsha": "4bb1d78b52175add3955de47281c3ee0073c7943", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-05-08T11:17:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-08T11:17:33.000Z", "avg_line_length": 57.2551020408, "max_line_length": 78, "alphanum_fraction": 0.8116200321, "num_tokens": 1308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.32196815507983007}}
{"text": "\\documentclass[a4paper,twocolumn]{article}\n\n\\usepackage[english]{babel}\n\\usepackage[utf8]{inputenc}\n\\usepackage{graphicx}\n\\usepackage{hyperref}\n\\usepackage{fullpage}\n\\usepackage[small]{titlesec}\n\n% patch titlesec bug of not showing (sub)title numbering http://tex.stackexchange.com/a/300259\n\\usepackage{etoolbox}\n\\makeatletter\n\\patchcmd{\\ttlh@hang}{\\parindent\\z@}{\\parindent\\z@\\leavevmode}{}{}\n\\patchcmd{\\ttlh@hang}{\\noindent}{}{}{}\n\\makeatother\n\n\n\\newcommand*\\mean[1]{\\overline{#1}}\n\n\\title{The Cascade-Correlation Learning Architecture $-$ summary}\n\\author{Matěj Nikl}\n\n\\begin{document}\n\\maketitle\n\\noindent\nThe Cascade-Correlation Architecture (CCA) is a architecture as well as a supervised learning algorithm for artificial neural networks (ANNs). Conventional way of training ANNs is to \\textit{somehow} choose a fixed network topology and then train it using back-propagation algorithm.\nCCA eliminates the need of choosing a fixed network topology and provides a way of training this kind of a dynamic network.\n\n\\section{Principles of growing}\nThe network starts with no hidden units, only output units are present. Then, one hidden unit is added at a time, receiving all network inputs and all outputs of the previously added hidden units, each time adding more complexity to the network, possibly creating more and more complex feature detectors.\n\n\\begin{figure}[!h]\n    % \\centering\n    \\includegraphics[width=0.475\\textwidth]{cascade.png}\n    \\caption{The CCA after two hidden units have been added. The vertical lines sum all incoming activations. Boxed connections are frozen, X connections are trained repeatedly.}\n\\end{figure}\n\n\\section{Training}\nThe process of training can be divided into two parts, which will be described in the following subsections, however one constraint holds through both of them: once a new hidden unit is added, its input weights are forever frozen.\n% \\begin{itemize}\n%     \\item \\ref{ssec:nn} training the network output\n%     \\item \\ref{ssec:unit} training a new hidden unit, to-be added to the network\n% \\end{itemize}\n\\subsection{Network output training} \\label{ssec:nn}\nHaving everything except output units' weights frozen translates into optimization of a single layer network, which was one of the authors' goals (to avoid slow back-propagation). The following steps take place:\n\\begin{enumerate}\n    \\item optimize the single layer network, until a convergence is achieved\n    \\item evaluate the test error and if it is low enough, stop\n    \\item otherwise, proceed to subsection \\ref{ssec:unit}\n\\end{enumerate}\n\n\\subsection{New unit training} \\label{ssec:unit}\nIf network's test error is not low enough, we need to add a new hidden unit. To do so, the following steps take place:\n\\begin{enumerate}\n    \\item create a pool of \\textit{candidate} units, having their input weights randomly initialized, each receiving all available inputs\n    \\item maximize $S$, the sum of covariances between the candidate unit's value and the residual output error of all output units, for each candidate unit, by adjusting their input weights, until convergence\n\\[\n    S = \\sum_{o \\in O} \\left| \\sum_{p \\in P} (V_p - \\mean{V})(E_{p,o} - \\mean{E_o}) \\right|\n\\]\n    \\begin{itemize}\n        \\item $O$ is a set of output units\n        \\item $P$ is a set of training patterns (training data)\n        \\item $V_p$ is candidate unit's value for pattern $p$\n        \\item $E_{p,o}$ is the residual output error at output unit $o$ for pattern $p$\n        \\item averages are computed across $P$\n    \\end{itemize}\n\n    \\item choose the candidate unit with the largest $S$ and add it to the network, proceed to \\ref{ssec:nn}\n\\end{enumerate}\n\n\\section{Principles of modularization}\nThe only sense of modularization in the CCA can be seen in viewing individual hidden units as modules, since they are being added throughout the learning process. However, the network as a whole is not modular in the full sense. Hidden units cannot be detached from a network and reattached to a different one. A hidden unit can only be used in conjunction with the hidden units it has been trained with and nowhere else.\n\\paragraph{Similar design}\nA similar partially modular design can be seen in Progressive Neural Networks, where new columns (full-blown NNs) are being added with lateral connections to all of the previously trained columns, showing the same aspects of \\textit{(non)modularity} as CCAs.\n\n\n\\end{document}\n", "meta": {"hexsha": "793178cb17df51173d1307c1a667edd8fde7268f", "size": 4429, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "summary/2/cascade/cascade.tex", "max_stars_repo_name": "MatejNikl/incremental_learning", "max_stars_repo_head_hexsha": "57eb7d02c614d5baa5f1814b2347151cc0378b58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "summary/2/cascade/cascade.tex", "max_issues_repo_name": "MatejNikl/incremental_learning", "max_issues_repo_head_hexsha": "57eb7d02c614d5baa5f1814b2347151cc0378b58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "summary/2/cascade/cascade.tex", "max_forks_repo_name": "MatejNikl/incremental_learning", "max_forks_repo_head_hexsha": "57eb7d02c614d5baa5f1814b2347151cc0378b58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.7820512821, "max_line_length": 421, "alphanum_fraction": 0.7636035222, "num_tokens": 1089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.32196814719028455}}
{"text": "% !TEX root = ../00_thesis.tex\n\n% ------------------------------------------------------------------------------\n\\section{Performance of the \\TTW Scheduler}\n\\label{sec:ttw_evaluation_sched}\n% ------------------------------------------------------------------------------\n\nThe following two sections present the performance evaluation of our \\TTW implementation, presented in~\\cref{sec:ttw_implementation}.\nWe first evaluate the performance of the scheduler. In particular, we illustrate the benefits of the minimal inheritance strategy presented in \\cref{sec:multi_mode} and we show that the complexity of the schedule synthesis is tractable.\n\n% ------------------------------------------------------------------------------\n\\subsection{Benefits of Minimal Inheritance}\n\n\\begin{figure}\n  \\centering\n  \\href{\\ttwfig{Figure-11}}{%\n  \\includegraphics[scale=1]{inheritance_eval}}\n  \\caption{Number of rounds in the different modes' schedule, depending on the inheritance approach considered.\n  \\capt{We consider the number of rounds scheduled over 80\\s, which is the least common multiple of the modes' hyperperiod.}}\n  \\label{fig:inheritance_eval}\n\\end{figure}\n\nEvery round introduces some overhead (mainly from  sending the beacon), which consumes energy.\nTo reduce the energy consumption, \\TTW aims to minimize the number of rounds \\objective{1}.\nThe schedule synthesis for a single mode is optimal in this respect; that is, the procedure guarantees that the schedule minimizes the number of communication rounds~(\\cref{sec:single_mode}).\n\n\\squarepar{%}\n  The second objective of the scheduler is to allow persistent applications to keep the same schedule in different operation modes \\objective{2}.\n  This creates additional constraints that break the optimality guarantee: in other words, the schedule of mode \\modej, when constrained to be compatible with mode \\modei, may contain more rounds than required to schedule the mode \\modej alone.\n  A naive solution to meet \\objective{2} is to completely ``reserve the space'' of previously scheduled modes. This is equivalent to consider that all applications executing in mode \\modei are also executing in \\modej, even if it is not actually the case. We call this the \\emph{full inheritance} approach.\n  This approach does guarantee compatibility but it is very pessimistic: it leads to an excessive increase of the number of rounds and find problems to be non-schedulable when they may in fact be feasible.%\n}\n\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[scale=1]{modeGraph_eval}\n  \\caption{The mode graph \\modeGraph' used in the inheritance evaluation scenario.\n  Mode \\modei has priority $i$. The applications executing in each mode are listed in~\\cref{append:inheritance_eval}.}\n  \\label{fig:modeGraph_eval}\n\\end{figure}\n\n\nIn \\cref{sec:multi_mode}, we derived the minimal set of constraints that are necessary to guarantee the compatibility between modes \\objective{2}, which we refer to as \\emph{minimal inheritance}.\nWe now illustrate with a simple example that the minimal inheritance does not overly increase the number of communication round required and performs much better than the full inheritance.\n%\nWe consider the following configuration (fully detailed in \\cref{append:inheritance_eval}): The system is composed of 13 nodes, running 15 different applications including 45 tasks and 30 messages.\nThe periods and deadlines vary between 10 and 80\\s. The applications are executing in 5 different modes connected by the mode graph shown in~\\cref{fig:modeGraph_eval}.\nFinally, all applications are considered persistent.\nWe synthesize the schedule for the 5 modes while considering\n(i)~no inheritance,%\n%\n\\footnote{Considering no inheritance is equivalent to set all applications as non-persistent. In other words, there are no constraints between the different modes and the individual mode schedules are guaranteed to be optimal in terms of number of rounds~(\\cref{sec:single_mode}).}\n%\n(ii)~our minimal inheritance approach, and (iii)~the naive full inheritance approach.\nThe results are shown in \\cref{fig:inheritance_eval}.\n\nOne important observation is that the number of rounds steadily increases with the full inheritance approach, which is expected: the full inheritance assumes that all previously scheduled applications are still executing. Thus, the number of applications to schedule only increases, and so does the number of round required. Ultimately, this not only wastes energy, it also limits scalability with the number of operation modes.\nIn comparison, our minimal inheritance approach performs much better: Since only the required constraints are included, the minimal inheritance does not suffer from the scalability issue mentioned above. In this example, the minimal inheritance performs optimally (\\ie it does not schedule more rounds that the minimum, captured by the ``no inheritance'' case); but note that this is {\\bf not true in general}, it simply happens to be the case in this example.\n\n\\fakepar{Conclusion}\nThe minimal inheritance approach derived in \\cref{sec:multi_mode} efficiently addresses the challenge of synthesizing compatible schedules~\\objective{2} while minimizing the energy impact in terms of number of rounds scheduled~\\objective{1}.\nThis approach does increase the complexity of the synthesis formulation; however, it is implemented in our \\TTW scheduler, it induces no overhead for the user, and it does not affect the synthesis solving time, as discussed below.\n\n% ------------------------------------------------------------------------------\n\\subsection{Offline Solving Time}\n\n\\squarepar{%}\n  We computational complexity of the schedule synthesis is made tractable by \\TTW's sequential approach: modes are scheduled individually, in order of priority~(\\cref{sec:multi_mode}) and for each mode, the number of rounds to schedule is kept fixed then incremented until a solution is found~(\\cref{sec:single_mode}).\n\n  For the evaluation scenario described above, the solving time for one mode grows up to ten minutes~(\\cref{table:solvingTimes}) and is generally correlated with the complexity of the mode to schedule: mode \\mode{3} and \\mode{4} contains the most applications~(\\cref{append:inheritance_eval}), leading to more constraints in the formulation.\n  Furthermore, we note that the minimal inheritance strategy does not increase the overall solving time compared to ``no inheritance''. The intuition is that, by reserving some applications' schedule, we fix the value of some of the problem variables, thereby reducing the complexity of the problem.\n  However, as shown by the full inheritance approach, if too many variables are fixed, the resulting problem might become harder to solve: more communication rounds become required, which increases the number of variables and thus the complexity.\n\n  \\fakepar{Conclusion}\n  The evaluation scenario is simple but representative of a middle-sized \\CPS. Our evaluation shows that the computational complexity may grow to the scale of minutes for challenging modes, which remains perfectly tractable for a task that needs to be performed only once and before deployment.%\n}\n\n\\begin{table}\n  \\centering\n  \\caption{Approximate solving time for the different modes of the inheritance evaluation~(\\cref{sec:ttw_evaluation_sched}).\n  \\capt{Time expressed in seconds; all computation performed on a commodity laptop.}}\n  \\label{table:solvingTimes}\n  {\\smaller \\input{\\TablePath/solvingTimes.csv}}\n  \\vspace{-5pt}\n\\end{table}\n\n\n\n\n\n\\vspace{-10pt}\n% -----------------------------------------------------------------------------\n\\section{Performance of \\TTnet}\n\\label{sec:ttw_evaluation_implem}\n% ------------------------------------------------------------------------------\n\nAfter the evaluation of the \\TTW scheduler~(\\cref{sec:ttw_evaluation_sched}), we now consider the performance of our \\TTnet implementation, described in \\cref{subsec:implem_ttnet}.\n\n% ------------------------------------------------------------------------------\n\\subsection{Memory Utilization}\n\nFirst, we consider the memory utilization induced by storing the scheduling tables in the nodes' memory.\nFor a given operation mode, the entire schedule contains the task offsets, the message offsets and deadlines, the round starting times, and the allocations of messages to rounds~(\\cref{table:ttw_inputs_outputs}).\nIn addition, nodes must know the task periods and the mode hyperperiod to compute the absolute start time of the tasks and rounds.\n\nSince we dedicate the execution of tasks and the wireless communication to different processors~(\\cref{sec:ttw_implementation}), the memory cost for storing the schedule can be splitted.\nOn the application side, we must store the task offsets and periods, which are required to know when to execute the tasks; \\ie 2 variables per task.\nOn the communication side, we must store the mode hyperperiod and the rounds information, \\ie the offset and allocation of the rounds scheduled within the mode's hyperperiod; \\ie $(\\nslotsmax+1)$ variables per round.\nThe message deadlines are not required at runtime and do not need being stored.\nAs a result, we can generally estimate that the scheduling tables represent tens to hundreds of variables per mode for each processor.\n\n\\squarepar{%}\n  \\fakepar{Conclusion}\n  Our application and communication processors feature 64\\kB~\\cite{msp432} and 4\\kB\\cite{CC430F6137} of RAM, respectively. Thus, considering an average size of two\\bytes per variable, storing the scheduling tables represent a significant overhead and limits the scalability of the system, in particular on the communication processor.\n  This limitation would be significantly relaxed with newer platforms, which commonly feature 256\\kB of RAM~\\cite{nRF52840}.%\n}\n\n% ------------------------------------------------------------------------------\n\\subsection{\\TTnet Model}\n\\label{subsec:model}\n\n\\squarepar{%}\n  As discussed in \\cref{sec:ttw_implementation}, we implement \\TTnet using \\baloo, which allows to derive a precise model of\n  (i)~the execution time of a communication round and\n  (ii)~the time spent with the radio turned on, which correlates with the energy consumed for communication.\n  Estimating the communication time is necessary to synthesize the schedules since the scheduler must know how long the rounds last.\n  This model should be as tight as possible not to ``waste'' time and thus minimize the end-to-end deadlines schedulable by \\TTW, but it must be a safe upper-bound in order to prevent deadline misses.\n  This section presents our \\TTnet model and derives the theoretically achievable performance in terms of minimal message latency and the energy savings expected from using rounds.%\n}\n\nLet $\\app.\\delta$ denote the latency of an application \\app. This latency represents the delay for a complete execution of \\app; that is, the completion of all tasks in \\app.\\predG. Let $\\app.c$ be a \\emph{chain} in \\app.\\predG.\nA chain is defined as a path of \\app.\\predG starting with a task without predecessor and ending with a task without successor.%\n%\n\\footnote{For example, $(\\tau_2, m_2, \\tau_4)$ is a chain of \\predG in \\cref{fig:precedence_graph}.}\n%\nThe minimum achievable latency for a single message in \\TTW is the length of a round composed of only one slot, denoted $\\Tround(L,1)$ where $L$ is the payload size. Thus $\\app.\\delta$ is lower-bounded by\n\\begin{align}\n\\label{eq:min_deadline}\n\\app.\\delta \\;\n\t& \\geq \\; \\max_{\\app.c \\,\\in\\, \\app.\\predG}\n\t\t\\left(\n\t\t\t\\; \\sum_{\\tau \\, \\in \\, \\app.c} \\tau.e \\,+\\, \\sum_{m \\, \\in \\, \\app.c} \\Tround(L,1) \\;\n\t\t\\right)\n\\end{align}\n\n\\begin{remark}\n  By comparison, the best possible guarantee for the latency of a single message provided by  \\DRP~(\\cref{ch:drp}) is of the order of $2*\\Tround(L,\\nslotsmax)$.\n  Since $\\Tround(L,\\nslotsmax) \\approx \\nslotsmax*\\Tround(L,1)$, \\TTW reduces the minimal guarantee on message latency by a factor of approximately $2*\\nslotsmax$.\n  For a relatively small number of slots per round, such as $\\nslotsmax=5$, this represents an order of magnitude improvement.\n  This difference stems from the loose coupling between the task and message schedules in \\DRP, whereas \\TTW statically schedules all tasks and messages.\n\\end{remark}\n\n\n\\afterpage{\n\\begin{figure}\n\\centering\n\\includegraphics[scale=1]{Tslot}\n\\caption{%\nBreak-down of a communication round.\n\\capt{%\nAt the slot level, the colored boxes identify phases where the radio is on.\nIn the ``idle'' phase, the radio is turned off in practice, but this idle time depends on each node's distance to the initiator.\nTo estimate the energy saving of rounds (\\cref{fig:energy_ratio}), we assume that the radio stays on for the whole time of \\Tglossy, as specified in~\\cref{eq:Ton}.\n}\n}\n\\label{fig:Tslot}\n\\end{figure}}\n\nA round \\Tround is composed of up to $(\\nslotsmax+1)$ slots in which Glossy floods~\\cite{ferrari2011Glossy} are executed.\nAn entire slot completes in time $\\Tslot$, decomposed into\n\\begin{equation}\n  \\Tslot = \\Twakeup + \\Tstart + \\Tglossy + \\Tgap\n\\end{equation}\nThe composition of a slot in our implementation is detailed in~\\cref{fig:Tslot}.\nFirst, all nodes wake up (\\Twakeup) and switch on their radio (\\Tstart).\nThen the message flood starts. We denote by \\Thop the time required for one protocol step, \\ie a one-hop transmission. The total length of the flood is\n%\n\\begin{align}\n\\Tglossy = (H+2N-1)*\\Thop\n\\end{align}\nwith $H$ the network diameter and $N$ the number of times each node transmits each packet.%\n%\n\\footnote{Glossy achieves more than 99.9\\% packet reception rate using $N =2$~\\cite{ferrari2011Glossy}.}\n%\n\\Thop is itself divided into\n%\n\\begin{align}\n\\Thop = \\Td + \\Tcal + \\Theader + \\Tpayload\n\\end{align}\nwhere \\Td is a radio delay, and \\Tcal, \\Theader and \\Tpayload are the transmission times of the clock calibration message, the Glossy header and the message payload, respectively.\nWith a bit rate of \\Rbit, the transmission of $L$\\bytes takes\n%\n\\begin{align}\nT(L) = 8L/\\Rbit\n\\end{align}\nOnce the flood is completed, some gap time \\Tgap is necessary to process the received packet.\nThis time is used (among other things) to execute \\baloo's \\texttt{on\\_slot\\_post()} callback, where the received messages are written into \\bolt.\nWe divide \\Tslot into \\Ton and \\Toff, which denote the time spent with radio on and off, respectively.\n%\n\\begin{align}\n\\Toff &\\,=\\,\n\t\\Twakeup + \\Tgap \\\\\n\\nonumber\n\\Ton(L) &\\,=\\,\n\t\\Tstart + \\\\\n\\label{eq:Ton}\n  & \\qquad (H+2N-1) * \\left( \\Td + 8(\\Lcal + \\Lheader + L)/\\Rbit \\right) \\\\\n\\Tslot(L) &\\,=\\,\n  \\Toff + \\Ton(L) \\\\\n\\Tround(L)\n\t&\\,=\\,\n\t\\Tslot(\\Lbeacon) + B*\\Tslot(L) + \\Tpreprocess\n\\end{align}\n\nSending beacons is necessary to let the nodes know about the current state of the system; \\ie which mode is executing and ``how far'' is the system in the scheduling table. Without that information, it is impossible for a failing node to recover and resume its normal operation.\nMoreover, beacons prevent message collisions by guaranteeing that the nodes always know the system's state when a round starts.\nIn a design \\emph{without} round, each message transmission should be preceded by its own beacon to provide the same guarantees. Thus, the transmission time for \\nslots messages of size $L$, denoted $\\Tworound(L)$, would take\n%\n\\begin{align}\n\\Tworound(L) =  B*( \\, \\Tslot(\\Lbeacon) + \\Tslot(L) \\, )\n\\end{align}\n%\nWe can then derive the relative energy savings $E$ granted by using a round-based design, which we compute as $E= (\\Tworoundon - \\Troundon)/\\Tworoundon$.\n\n\n\\afterpage{\n\\begin{figure}\n  \\begin{subfigure}{\\linewidth}\n    \\centering\n    \\href{\\ttwfig{Figure-14}}{%\n    \\includegraphics[scale=1]{T=f(H,B)}}\n  \\end{subfigure}\n  \\begin{subfigure}{\\linewidth}\n    \\centering\n    \\href{\\ttwfig{Figure-14}}{%\n    \\includegraphics[scale=1]{Overhead=f(H,B)}}\n  \\end{subfigure}\n  \\caption{Example values of round length (top) and protocol overhead (bottom) computed using the \\TTnet model~(\\cref{subsec:model}).\n  The protocol overhead is computed as the percentage of time spent to send the beacons relative to the overall communication time for a round containing \\nslots slots.\n  Payload is set to 16\\bytes and we use $N = $2 transmissions in the Glossy floods~\\cite{ferrari2011Glossy}.}\n  \\label{fig:TTWmodel}\n\\end{figure}\n}\n\n\nThe complete \\TTnet model is available in Appendix~(\\cref{appendix:ttw_artifacts}). We use this model to compute the round length \\Tround and the energy savings $E$ for different values of number of slots per rounds (\\nslots), message payload size ($L$), network diameter $H$, and number of transmissions in Glossy floods ($N$).\nSelected results are shown in \\cref{fig:TTWmodel,fig:energy_ratio}.\n\\linebreak\nFor example, with $N$ set to 2, it takes less than 100\\ms to complete a 10-slot round sending 16-bytes messages over a 4-hop network~(\\cref{fig:TTWmodel}, top).\n\n\n\n% ------------------------------------------------------------------------------\n\\subsection{Model Validation}\n\n\\squarepar{%}\n  We now evaluate the runtime execution of our implementation and aim to validate our \\TTnet model.\n  In particular, it is important that the round length model gives safe upper-bounds since the \\TTW scheduler relies on the model to schedule messages and tasks: if a round overruns, this may delay the execution of subsequent tasks and cause deadline misses.\n  We test our \\TTnet implementation for different number of slots per round \\nslots and payload size $L$, we measure the round length and radio-on time experienced by the different nodes in the network, and we compare the results with the \\TTnet model.%\n}\n\n\\fakepar{Evaluation scenario}\nWe program the network to execute, one round with \\nslots slots, followed by \\nslots rounds with one slot.\nFor each of these rounds, we collect the round length and the radio-on time. Both values are measured in software (\\ie the measurement is implemented in the firmware) and use a 32\\kHz timer, leading to a measurement accuracy of about 30\\us.\n\n\\begin{table}\n  \\centering\n  \\caption{\\triscale parameters for the experimental validation of \\TTnet's model}\n  \\label{table:ttw_triscale_param}\n  {\\smaller \\input{\\TablePath/triscale_param.csv}}\n\\end{table}\n\n\n\\fakepar{Experiment design}\nWe design the evaluation using the \\triscale framework (introduced in \\cref{ch:triscale}). The evaluation parameters are listed in \\cref{table:ttw_triscale_param}.\nOur evaluation scenario is terminating (there is a finite task to accomplish); thus there is no need to test for convergence.\nThe round length evaluation aims to validate that the \\TTnet model is a safe upper-bound; thus, we use the maximum measured round length across all nodes as metric for a run.\nFor the same reason, we choose a large KPI (95th percentile) and a high confidence level (95\\%), which leads to a minimal number of 59 runs per series.\nTo investigate the reproducibility of the results, we choose the median and a 75\\% level of confidence for the variability scores, leading to a minimal number or 3 series.\nTo evaluate the average savings provided by using communication rounds, we use the median values across nodes as metric.\nWe perform the evaluation on FlockLab~\\cite{FlockLab}, an indoor testbed located in an office building. It has been shown that the experimental conditions on FlockLab exhibits weekly seasonal components~(\\cref{subsec:network_profiling}); therefore, to avoid biasing our evaluation, we perform our series of runs using a span of one week, during which we schedule randomly 60 runs per set of parameters. We test our \\TTnet implementation using 5, 10, and 30 slots per round, and payloads of 8, 16, and 64\\bytes.\nThe three series of tests were performed between May and October 2019.\nThe KPI values from our evaluation are listed in~\\cref{table:KPIs}.\n\n\\afterpage{\n\\begin{figure}\n  \\centering\n  \\href{\\ttwfig{Figure-15}}{%\n  \\includegraphics[scale=1]{energy_savings}}\n  \\caption{Relative radio-on time savings by using rounds compared to single messages.\n  \\capt{The energy savings induced by a round-based design grow with the number of number of slots per round (X-axis). Conversely, these savings become less significant as the payload size increases (lighter colors).\n  The diamonds show our evaluation KPIs and thus estimate, with a probability of 95\\%, the average energy savings expected in 95\\% of the test runs. $H = 4$, $N = 2$.}}\n  \\label{fig:energy_ratio}\n\\end{figure}}\n\n\\begin{remark}\n  \\squarepar{%}\n  Observe that certain values in~\\cref{table:KPIs} are reported with a {\\ssymbol{1}} or {\\ssymbol{2}} symbol.\n  The {\\ssymbol{1}} marks series where \\triscale independence test fails; this indicates that the metric data do not appear to be \\iid and therefore the KPI value loose its predictive power (\\ie it does not allow to infer what is the expected performance).\n  However, in our evaluation, the autocorrelation plots show no significant differences between the series that passes the test and those that do not~(data available in~\\cref{appendix:ttw_artifacts}).\n  Moreover, the round length KPI values are almost the same in all series.\n  Together, these two facts increase our confidence in the results and suggests that the reported KPIs are robust estimates of the expected performance.\\\\\n  The {\\ssymbol{2}} marks series where we could not collect enough data in order to compute the KPIs. This appended in Series 3 due to construction work taking place in the FlockLab building, where many test runs were lost due to sporadic power outages.\n  In both cases, the table shows the maximum round length or minimum energy savings metric values obtained across all the runs in the series.%\n  }\n\\end{remark}\n\n\\fakepar{Results -- Round length}\nThe results for the round length are extremely stables~(\\cref{table:KPIs}):\nthe differences of KPI values between series are at most one time tick ($\\approx$ 30\\us), which is our measurement accuracy.\nConcretely, this means that, in all series, the largest round length measured by any node is essentially the same.\n\nFurthermore, the KPI values are (i)~very close to and (ii)~consistently lower than the model. By definitions of the KPI, we can estimate with 95\\% probability that (at least) 95\\% of runs will yield a maximal round length smaller than the KPI value, and thus smaller than the model value.\n\\cref{fig:exampleSeries} (top) shows the distribution of the round length measurements from all the nodes collected during one series of 60 runs. We observe that the distribution is narrow (less than 300\\us of spread), which is expected. Indeed, the \\TTnet rounds are fully time-triggered; thus, the measurement differences between nodes mainly come from the difference in execution time of \\baloo's end-of-round operations, which is expected to be small.\n\n\\squarepar{%}\n  In our entire evaluation, there was one case where a node reported a value (77.85\\ms) larger than the model (77.52\\ms). This concerned only one node: in this run%\n  \\footnote{FlockLab test number 66992; data available in~\\cref{appendix:ttw_artifacts}.}\n  the second highest value reported (77.12\\ms) was smaller than the model value.\n  It is hard to know a posteriori what may have cause this.\n  However, we argue that this one overshoot is more likely imputable to some sporadic hardware delay than due to a miscalibration of the model.%\n}\n\n\\afterpage{\n\\begin{figure}\n  \\centering\n  \\begin{subfigure}{\\linewidth}\n    \\centering\n    \\href{\\ttwfig{Figure-16}}{%\n    \\includegraphics[scale=1]{serie2_T_round_H4_N2_L16_B5}}\n  \\end{subfigure}\n  \\begin{subfigure}{\\linewidth}\n      \\centering\n      \\href{\\ttwfig{Figure-16}}{%\n      \\includegraphics[scale=1]{serie2_T_on_round_H4_N2_L16_B5}}\n  \\end{subfigure}\n  \\caption{Distributions of round length (top) and radio-on time (bottom) measurements from all the nodes, collected in one series of 60 runs (Serie 2, $L=16$, $\\nslots=5$).\n  \\capt{\n    While the distribution of round length is very narrow, the radio-on time exhibits a much larger spread. We can see that the \\TTnet model provides a generally overestimate the radio-on time, which is expected since it assumes that nodes keep their radio on for the entirety of \\Tflood~\\textup{(}\\cref{eq:Ton}\\textup{)}, which is not the case in practice: nodes turn the radio off when they have transmitted a packet $N$ times.\n  }}\n  \\label{fig:exampleSeries}\n\\end{figure}}\n\n\\fakepar{Results -- Energy savings}\nThe energy savings results show more fluctuations than the round length, which is not surprising: (i)~the energy model is less precise and (ii)~the dynamic interference conditions affect the radio-on time, as nodes may need to keep their radio on for a longer share of \\Tglossy.\n\\cref{fig:energy_ratio} shows the model and our energy savings KPIs together.\n\\cref{fig:exampleSeries} (bottom) shows the distribution of radio-on time measurements from all the nodes, collected in one series of 60 runs: nodes experience significant differences in radio-on time during a round. This is expected since nodes terminate a flood as soon as they have transmitter a packet $N$ times, which happens earlier for nodes that are closer to the initiator,\n\nOverall, the energy savings come from the ``distribution'' of the overhead from sending beacons between the slots. Thus, the more slots (increasing \\nslots) and the smaller the slots (decreasing $L$), the more radio-on time is spared by using rounds.\nFor a payload of 16\\bytes, we obtain an average energy savings of about 30\\% with only 10 slots per round.\n\n\\afterpage{\n\\begin{landscape}\n\\begin{table}\n  \\centering\n  \\caption{\n  KPIs from the performance evaluation described in~\\cref{sec:ttw_evaluation_implem} and corresponding model values for the \\TTnet round length \\Tround and energy savings $E$; other settings: $H=4$ and $N=2$.\n  \\capt{\n    The value marked in bold corresponds to the one case where the round length KPI is larger than the model value.\n    {\\ssymbol{1}} marks series where \\triscale independence test failed.\n    {\\ssymbol{2}} marks series without enough samples for computing the KPIs.\n    In these two cases, reported values are the maximum round length or minimum energy savings metric values for all the runs in the series.\n  }}\n  \\label{table:KPIs}\n  {\\smaller \\input{\\TablePath/KPIs.csv}}\n\\end{table}\n\\end{landscape}\n}\n\n\\fakepar{Conclusion}\nWe validated the tightness and safeness of \\TTnet round length model, which was found to be an upper-bound of the effective round length for all but one in about 14k measurements collected.\nFurthermore, we showcased that, even with small beacons (2\\bytes in our implementation), a round-based design yields significant reduction of radio-on time, and therefore helps minimizing the overall energy consumption~(\\feature{Efficiency}).\n", "meta": {"hexsha": "72f0de97a17c51f0a463ad529f52fe38273c5454", "size": 26674, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "50_TTW/9_evaluation.tex", "max_stars_repo_name": "romain-jacob/doctoral-theis", "max_stars_repo_head_hexsha": "fd21e9f0cddeda91821eb061c9ab12df9f610da9", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "50_TTW/9_evaluation.tex", "max_issues_repo_name": "romain-jacob/doctoral-theis", "max_issues_repo_head_hexsha": "fd21e9f0cddeda91821eb061c9ab12df9f610da9", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "50_TTW/9_evaluation.tex", "max_forks_repo_name": "romain-jacob/doctoral-theis", "max_forks_repo_head_hexsha": "fd21e9f0cddeda91821eb061c9ab12df9f610da9", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 71.320855615, "max_line_length": 510, "alphanum_fraction": 0.7527180025, "num_tokens": 6396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.32196814719028455}}
{"text": "\\section{Related Work}\n\\label{sec:related-work}\n% different classes of CHC solvers:\nA significant body of previous work has presented solvers for\ndifferent classes of Constrained Horn Clauses, or finding inductive\ninvariants of programs that correspond to solutions of CHCs.\n% solving linear systems:\n\\impact attempts to verify a given sequential procedure by iteratively\nselecting paths and synthesizing invariants for each path. This\napproach corresponds to solving a recursive linear CHC\nsystem~\\cite{mcmillan06}.\n\n% interprocedural verification:\nPrevious work also proposed a verifier for recursive\nprograms~\\cite{heizmann10}.\n%\nThe proposed approach selects interprocedural paths of a program and\nsynthesizes invariants for each as nested interpolants.\n%\nSuch an approach corresponds to attempting to solve a recursive CHC\nsystem $S$ by selecting derivation trees of $S$\nand solving each tree.\n\n% solving recursive systems:\nPrevious work has proposed solvers for recursive systems that, given a\nsystem $S$, attempt to solve $S$ by generating and\nsolving a series of recursion-free unwindings of $S$.\n%\nIn particular, \\eldarica attempts to solve each unwinding\n$S'$ by reducing to and solving body-disjoint systems~\\cite{rummer13a,rummer13b}.\n%\n\\duality attempts to avoid solving all derivation-trees (i.e\nbody-disjoint systems) by using lazy annotation~\\cite{bjorner13}.\n%\nOther optimizations select derivation trees to solve using\nsymbolic analogs of Prolog evaluation with\ntabling~\\cite{jaffar09,mcmillan14}.\n%\n\n\\whale attempts to verify sequential recursive programs by generating\nand solving hierarchical programs, which correspond to recursion-free CHC\nsystems~\\cite{albarghouthi12b}.\n%\nTo solve a particular recursion-free system, \\whale solves a linear\ninlining of the input using a procedure named\n\\vinta~\\cite{albarghouthi12a}.\n%\nIn general, the linear inlining may be exponentially larger than the\ninput.\n\n\\sys is similar to the recursion-free CHC approaches given above in\nthat it reduces the problem to solving a CHC system in a\ndirectly-solvable class.\n%\n\\sys is distinct in that it reduces to solving Clause-Dependent\nDisjoint (CDD) systems.\n%\nAs discussed in \\autoref{sec:overview}, the class of CDD systems is a\nsuperset of classes used by the approaches above. CDD systems can\nalso be solved directly.\n\n\\sys solves general CHC systems using the same strategy as proposed by\nthe above approaches.\n%\nSpecifically, it solves a series of recursion-free unwindings of the\noriginal system, and tries to synthesize a general solution from the\nrecursion-free solutions.\n\nPrevious work describes solvers for non-linear Horn clauses over\nparticular theories.\n%\nIn particular, verifiers have been proposed for recursion-free systems\nover the theory of linear arithmetic~\\cite{komuravelli14}.\n%\nBecause the verifier relies on quantifier elimination, it is not clear\nif it can be extended to richer theories that support interpolation,\nsuch as the combination of linear arithmetic with uninterpreted\nfunctions.\n%\nOther work describes a solver for the class of \\emph{timed pushdown\nsystems}, a subclass of CHC systems over the theory of linear real\narithmetic~\\cite{hoder12}.\n%\nUnlike these approaches, \\sys can solve systems over any theory that\nsupports interpolation.\n\n% DAG inlining:\nDAG inlining attempts to generate compact verification conditions for\nhierarchical programs~\\cite{lal-qadeer15}.\n%\n\\sys attempts to solve recursion-free CHC systems by reducing them to\ncompact CDD systems.\n%\nBecause hierarchical programs and recursion-free CHC systems are\nclosely related, algorithms that operate on hierarchical programs\ncorrespond to algorithms that operate on recursion-free Horn Clauses.\n%\nHowever, it is not apparent whether such algorithms can be used directly\nto synthesize solutions.\n", "meta": {"hexsha": "b52cd027cb0b7c4e03ce9847ea96f81f782daf0a", "size": 3805, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/related-work.tex", "max_stars_repo_name": "DAHeath/shara", "max_stars_repo_head_hexsha": "030d7e94d19e9cb015f9f85b3a2e3c7f796e8a5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paper/related-work.tex", "max_issues_repo_name": "DAHeath/shara", "max_issues_repo_head_hexsha": "030d7e94d19e9cb015f9f85b3a2e3c7f796e8a5f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/related-work.tex", "max_forks_repo_name": "DAHeath/shara", "max_forks_repo_head_hexsha": "030d7e94d19e9cb015f9f85b3a2e3c7f796e8a5f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.05, "max_line_length": 81, "alphanum_fraction": 0.8123521682, "num_tokens": 864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3219494999607148}}
{"text": "\\chapter{Introduction}\n\nThe goal of this Capita Selecta is to investigate the possibilities for a fast MATLAB based implementation of the Block MLDU algorithm.\\\\\n\n\\noindent High performance solvers are usually written in languages like C/C++ because they are compiled, avoiding the sometimes costly step of the interpreter. Languages like MATLAB are dynamically typed and interpreter based, which make them great for prototyping purposes.\\\\\n\n\\noindent The Block MLDU algorithm shows great possibilities, but the lack of a high performance implementation makes it prohibitive to use for large matrices. This is a problem because research projects sometimes encounter very large matrices that need to be solved with the Block MLDU algorithm.\\\\\n\n\\noindent This project tries to alleviate the problem by investigating the performance bottlenecks of a MATLAB based implementation and provide workarounds for them. This should result in a much faster implementation without requiring the extra work associated with a full C/C++ version.\\\\\n\n\\noindent The biggest advantage of this workflow is that the time required to implement a workaround for a bottleneck will be much lower in MATLAB than in C/C++, making it easier to try different approaches to the problems. The lessons learned at this stage will still be useful when the code does finally get ported to C/C++.\\\\\n\n\\noindent The biggest disadvantage to sticking to MATLAB is that the interpreter will always provide some overhead compared to C/C++. The hope is that this overhead will be small compared to the other bottlenecks encountered.\n\n\\newpage\n\n\\section{The Block MLDU algorithm}\n\nThe Block MLDU algorithm is very comparable to the well known LU decomposition. The main difference between the Block MLDU algorithm and LU decomposition is the \"block\" nature of the splitting.\n\n\\subsection{Example}\n\nA simple example will be provided to highlight the differences between LU and Block MLDU. Let matrix $A$ be $4 \\times 4$:\\\\\n\n$\n\\hspace{20mm} A = \n\\left\\lbrack\\begin{array}{rrrr}\n           1&           0&           1&           0\\\\\n           2&           1&          -1&           0\\\\\n           0&          -1&           0&           1\\\\\n          -2&           0&           1&           3\n\\end{array}\\right\\rbrack\n$\n$\n\\hspace{30mm} s =\n\\left\\lbrack\\begin{array}{rrr}\n           2&           1&           1\n\\end{array}\\right\\rbrack\n$\\\\\n\n\\noindent As stated by row $s$, matrix $A$ will first be split using a $2 \\times 2$ block, followed by two $1 \\times 1$ blocks.\\\\\n\n\\noindent \\textbf{Step one:}\\\\\n\n$\n\\left\\lbrack\\begin{array}{rr|rr}\n          D1&          D1&          U1&          U1\\\\\n          D1&          D1&          U1&          U1\\\\ \\hline\n          L1&          L1&          M1&          M1\\\\\n          L1&          L1&          M1&          M1\n\\end{array}\\right\\rbrack\n$\n$\n\\hspace{10mm} L1 = \n\\left\\lbrack\\begin{array}{rr}\n           0&          -1\\\\\n          -2&           0\n\\end{array}\\right\\rbrack\n$\n$\n\\hspace{6mm} D1 = \n\\left\\lbrack\\begin{array}{rr}\n           1&           0\\\\\n           2&           1\n\\end{array}\\right\\rbrack\n$\n$\n\\hspace{6mm} U1 = \n\\left\\lbrack\\begin{array}{rr}\n           1&           0\\\\\n          -1&           0\n\\end{array}\\right\\rbrack\n$\\\\\n\n$\nSchur1 = L1 D1^{-1} U1 =\n$\n$\n\\left\\lbrack\\begin{array}{rr}\n           3&           0\\\\\n          -2&           0\n\\end{array}\\right\\rbrack\n$\n$\n\\hspace{20mm} A - Schur1 = \n\\left\\lbrack\\begin{array}{rrrr}\n           1&           0&           1&           0\\\\\n           2&           1&          -1&           0\\\\\n           0&          -1&  \\textbf{-3}&  \\textbf{1}\\\\\n          -2&           0&   \\textbf{3}&  \\textbf{3}\n\\end{array}\\right\\rbrack\n$\\\\\n\n\\noindent \\textbf{Step two:}\\\\\n\n$\n\\left\\lbrack\\begin{array}{rr|r|r}\n          D1&          D1&          U1&          U1\\\\\n          D1&          D1&          U1&          U1\\\\ \\hline\n          L1&          L1&          D2&          U2\\\\ \\hline\n          L1&          L1&          L2&          M2\n\\end{array}\\right\\rbrack\n$\n$\n\\hspace{10mm} L2 = \n\\left\\lbrack\\begin{array}{r}\n           3\n\\end{array}\\right\\rbrack\n$\n$\n\\hspace{18mm} D2 = \n\\left\\lbrack\\begin{array}{r}\n           -3\n\\end{array}\\right\\rbrack\n$\n$\n\\hspace{10mm} U2 = \n\\left\\lbrack\\begin{array}{r}\n           1\n\\end{array}\\right\\rbrack\n$\\\\\n\n$\nSchur2 = L2 D2^{-1} U2 =\n$\n$\n\\left\\lbrack\\begin{array}{r}\n           -1\n\\end{array}\\right\\rbrack\n$\n$\n\\hspace{12mm} A - Schur1 - Schur2 = \n\\left\\lbrack\\begin{array}{rrrr}\n           1&           0&           1&           0\\\\\n           2&           1&          -1&           0\\\\\n           0&          -1&          -3&           1\\\\\n          -2&           0&           3&   \\textbf{4}\n\\end{array}\\right\\rbrack\n$\\\\\n\n\\noindent \\textbf{Step three:}\\\\\n\n$\n\\left\\lbrack\\begin{array}{rr|r|r}\n          D1&          D1&          U1&          U1\\\\\n          D1&          D1&          U1&          U1\\\\ \\hline\n          L1&          L1&          D2&          U2\\\\ \\hline\n          L1&          L1&          L2&          D3\n\\end{array}\\right\\rbrack\n\\\\$\\\\\n\n\\noindent \\textbf{Result:}\\\\\n\n$\nL = \n\\left\\lbrack\\begin{array}{rrrr}\n           0&           0&           0&           0\\\\\n           0&           0&           0&           0\\\\\n   \\textbf{0}& \\textbf{-1}&          0&           0\\\\\n  \\textbf{-2}&  \\textbf{0}&  \\textbf{3}&          0\n\\end{array}\\right\\rbrack\n$\n$\n\\hspace{10mm} D =\n\\left\\lbrack\\begin{array}{rrrr}\n   \\textbf{1}&  \\textbf{0}&          0&           0\\\\\n   \\textbf{2}&  \\textbf{1}&          0&           0\\\\\n           0&           0&  \\textbf{-3}&          0\\\\\n           0&           0&           0&   \\textbf{4}\n\\end{array}\\right\\rbrack\n$\n$\n\\hspace{10mm} U =\n\\left\\lbrack\\begin{array}{rrrr}\n           0&           0&   \\textbf{1}&  \\textbf{0}\\\\\n           0&           0&  \\textbf{-1}&  \\textbf{0}\\\\\n           0&           0&           0&   \\textbf{1}\\\\\n           0&           0&           0&           0\n\\end{array}\\right\\rbrack\n\\\\$\\\\\n\n$\n\\\\\nA = (L + D)D^{-1}(D + U)\n$\n", "meta": {"hexsha": "460d5fcbab98edaf8c6bf8dc9bc5cdd4db5e443e", "size": 5973, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Report/chapters/introduction.tex", "max_stars_repo_name": "lucasbekker/Block-MLDU", "max_stars_repo_head_hexsha": "80415ec2e28017f0e128d0425e2e06742bb05233", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Report/chapters/introduction.tex", "max_issues_repo_name": "lucasbekker/Block-MLDU", "max_issues_repo_head_hexsha": "80415ec2e28017f0e128d0425e2e06742bb05233", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Report/chapters/introduction.tex", "max_forks_repo_name": "lucasbekker/Block-MLDU", "max_forks_repo_head_hexsha": "80415ec2e28017f0e128d0425e2e06742bb05233", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1129032258, "max_line_length": 328, "alphanum_fraction": 0.5154863553, "num_tokens": 1931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.3219494999607148}}
{"text": "\\chapter{Conclusion}\\label{chap:conclusion}\n\nWe looked at how the give token and random token orders solved the two main problems: Deadlocks and infinite executions. We discussed that there are three different ways to introduce a token, two of them solve both problems. The table token does not solve the deadlock problem because there is the possibility that no agent takes the token off the table. This is illustrated in the following table:\n\n\n\\begin{table}[h!]\n\\centering\n\\resizebox{\\textwidth}{!}{%\n\\begin{tabular}{|l|l|l|l|}\n\\hline\n & table token & random token & give token \\\\ \\hline\nempower token & \\begin{tabular}[c]{@{}l@{}}solves infinite executions \\\\ $\\longrightarrow$ Proposition 1 \\\\ does not solve deadlocks\\end{tabular} & \\begin{tabular}[c]{@{}l@{}}solves infinite executions\\\\ $\\longrightarrow$ Proposition 1 \\\\ solves deadlocks \\\\ $\\longrightarrow$ Proposition 4 \\end{tabular} & \\begin{tabular}[c]{@{}l@{}}solves infinite executions\\\\ $\\longrightarrow$ Proposition 1 \\\\ solves deadlocks \\\\ $\\longrightarrow$ Proposition 4 \\end{tabular} \\\\ \\hline\nforce action token & \\begin{tabular}[c]{@{}l@{}}solves infinite executions \\\\ $\\longrightarrow$ Proposition 2 \\\\ does not solve deadlocks\\end{tabular} & \\begin{tabular}[c]{@{}l@{}}solves infinite executions\\\\ $\\longrightarrow$ Proposition 2 \\\\ solves deadlocks \\\\ $\\longrightarrow$ Proposition 3  \\end{tabular} & \\begin{tabular}[c]{@{}l@{}}solves infinite executions\\\\ $\\longrightarrow$ Proposition 2 \\\\ solves deadlocks \\\\ $\\longrightarrow$ Proposition 3 \\end{tabular}  \\\\ \\hline\n\\end{tabular}%\n}\n\\end{table}\n\nThis means that there are positive results with the introduction of a token based order. In every case, if an agent that has found a plan gets the token, the goal will be reached in a finite number of steps.\n\nFor future work, the way the token changes the search of a plan should be researched. With tokens, the search tree of a plan might have a smaller width because the agents can be prevented from acting. The tree will also have a deeper depth because the agents each have a new action of handing the token to the next player.\\\\\nWe also did not look at how a tokenized planning task changes the existence of i-strong policies. It is unclear if some planning problems become unsolvable through the tokenize function.\n\nThere could also be future research in researching the fairness of the tokens.\\\\\nAnother field of research for the future could be impatient players and the table token execution order. An impatient player will wait for the other player to take the token first, but only for a limited amount of time. For this we would need to extend the formalism since we cannot model time or a waiting agent explicitly.\n", "meta": {"hexsha": "c3ac94e809d736224961868952520b2658c2a634", "size": 2703, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/6-conclusions.tex", "max_stars_repo_name": "ritterchen123/bachelor_thesis", "max_stars_repo_head_hexsha": "cd912e78403641032c4d84b32c460dd252d17959", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/6-conclusions.tex", "max_issues_repo_name": "ritterchen123/bachelor_thesis", "max_issues_repo_head_hexsha": "cd912e78403641032c4d84b32c460dd252d17959", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/6-conclusions.tex", "max_forks_repo_name": "ritterchen123/bachelor_thesis", "max_forks_repo_head_hexsha": "cd912e78403641032c4d84b32c460dd252d17959", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 108.12, "max_line_length": 480, "alphanum_fraction": 0.7635960044, "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.3219494999607148}}
{"text": "% BEGIN LICENSE BLOCK\n% Version: CMPL 1.1\n%\n% The contents of this file are subject to the Cisco-style Mozilla Public\n% License Version 1.1 (the \"License\"); you may not use this file except\n% in compliance with the License.  You may obtain a copy of the License\n% at www.eclipse-clp.org/license.\n% \n% Software distributed under the License is distributed on an \"AS IS\"\n% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.  See\n% the License for the specific language governing rights and limitations\n% under the License. \n% \n% The Original Code is  The ECLiPSe Constraint Logic Programming System. \n% The Initial Developer of the Original Code is  Cisco Systems, Inc. \n% Portions created by the Initial Developer are\n% Copyright (C) 2006 Cisco Systems, Inc.  All Rights Reserved.\n% \n% Contributor(s): \n% \n% END LICENSE BLOCK\n\n\\chapter{Getting started with Finite Domains}\n\n%----------------------------------------------------------------------\n\\section{Using the Finite Domains Library}\nTo use the Finite Domains Library, load the library using either of\n\\begin{quote}\\begin{verbatim}\n:- lib(fd).\n:- use_module(library(fd)).\n\\end{verbatim}\\end{quote}\nSpecify this at the beginning of your program.\n\n%----------------------------------------------------------------------\n\\section{Structure of a Constraint Program}\nThe typical top-level structure of a constraint program is\n\\begin{quote}\\begin{verbatim}\nsolve(Variables) :-\n        read_data(Data),\n        setup_constraints(Data, Variables),\n        labeling(Variables).\n\\end{verbatim}\\end{quote}\nwhere setup_constraints/2 contains the problem model. It creates the\nvariables and the constraints over the variables.\nThis is often deterministic, but not necessarily.\nThe labeling/1 procedure is the search part of the program. It\ntries to find solutions by trying all instantiations for the\nvariables. This search is being pruned by constraint propagation.\n\nThe above program will find all solutions.\nIf the best solution is wanted, we can just wrap a branch-and-bound\nprocedure around the search component of the program:\n\\begin{quote}\\begin{verbatim}\nsolve(Variables) :-\n        read_data(Data),\n        setup_constraints(Data, Variables),\n        min_max(labeling(Variables), Objective).\n\\end{verbatim}\\end{quote}\n\n\n%----------------------------------------------------------------------\n\\section{Modelling}\nThe modelling code need to do the following:\n    \\begin{itemize}\n    \\item Create the variables with their initial domains\n    \\item Setup the constraints between the variables\n    \\end{itemize}\n%\\htmladdnormallink{Example: Send more money}{../../examples/sendmore.pl.txt}\n\nA simple example is the ``cryptarithmetic'' puzzle, \n\\verb0SEND+MORE = MONEY0.\nThe idea is to associate a digit (0-9) with each letter so the\nequation is true.\n\nThe { \\eclipse } code is as follows:\n\\begin{quote}\\begin{verbatim}\n\n:- lib(fd).\n\nsendmore1(Digits) :-\n    Digits = [S,E,N,D,M,O,R,Y],\n\n% Assign a finite domain with each letter - S, E, N, D, M, O, R, Y - \n% in the list Digits\n    Digits :: [0..9],\n\n% Constraints\n    alldifferent(Digits),\n    S #\\= 0,\n    M #\\= 0,\n                 1000*S + 100*E + 10*N + D\n               + 1000*M + 100*O + 10*R + E\n    #= 10000*M + 1000*O + 100*N + 10*E + Y,\n\n% Search\n    labeling(Digits).\n\\end{verbatim}\\end{quote}\n\n%----------------------------------------------------------------------\n\\section{Simple User-defined Constraints}\nConceptual constraints that are just conjunctions of primitive\nconstraints can easily be defined.\n%\\htmladdnormallink{Example: Zebra}{../../examples/zebra.pl.txt}\n\nFor example, let us assume that we have a set of colours and we want\nto define that some colours fit with each other and others do\nnot. This should work in such a    \nway as to propagate possible changes in the domains as soon as this\nbecomes possible.  \n\nLet us assume we have a symmetric relation that defines which colours\nfit with each other: \n\n\\begin{quote}\\begin{verbatim}\n% The basic relation\nfit(yellow, blue).\nfit(yellow, red).\nfit(blue, yellow).\nfit(red, yellow).\nfit(green, orange).\nfit(orange, green).\n\\end{verbatim}\\end{quote}\n\nThe predicate \\verb0nice_pair(X, Y)0 is a constraint and any change of the\npossible values of $X$ or $Y$ is propagated to the other variable. There\nare many ways in which this pairing \ncan be defined in ECLiPSe. They are different solutions with different\nproperties, but they yield the same results.  \n\n\\subsection{Using Evaluation Constraints}\n\nWe can also encode directly the relations between elements in the\ndomains of the two variables:  \n\\begin{quote}\\begin{verbatim}\nnice_pair(A, B) :-\n    np(A, B),\n    np(B, A).\n\nnp(A, B) :-\n    [A,B] :: [yellow, blue, red, orange, green],\n    A #= yellow #=> B :: [blue, red],\n    A #= blue #=> B #= yellow,\n    A #= red #=> B #= yellow,\n    A #= green #=> B #= orange,\n    A #= orange #=> B #= green.\n\\end{verbatim}\\end{quote}\n\nThis method is quite simple and does not need any special analysis; on\nthe other hand it potentially creates a huge number of auxiliary\nconstraints and variables. \n \n\\subsection{Using Propia}\nThe simplest way is to load the Generalised Propagation library ({\\em\npropia} - see \\ref{propia} above) and use\narc-consistency ({\\em ac}) propagation, viz:\n\\begin{quote}\\begin{verbatim}\n?- nice_pair(X,Y) infers ac\n\\end{verbatim}\\end{quote}\n\n\\subsection{Using the {\\em element} Constraint} \n\n\nIn this case we use the \\verb0element/30 predicate, available in the fd\nlibrary.  It is rather awkward to use, because additional\nvariables are required, but it propagates efficiently:  \n\n\\begin{quote}\\begin{verbatim}\nnice_pair(A, B) :-\n    element(I, [yellow, yellow, blue, red, green, orange], A),\n    element(I, [blue, red, yellow, yellow, orange, green], B).\n\\end{verbatim}\\end{quote}\n\nWe define a new variable $I$ which is an index into the clauses\nof the fit predicate. The first colour list contains colours in the\nfirst argument of \\verb0fit/20 and the second list \ncontains colours from the second argument. \n\nBehind the scenes, this is exactly the implementation used for\narc-consistency propagation by the Generalised Propagation library.\n\nBecause of the specific and efficient algorithm implementing the\n\\verb0element/30 constraint,  it is usually faster than the first\napproach, using evaluation constraints.  \n \n\n%----------------------------------------------------------------------\n\\section{Built-in Constraints}\n\n\\begin{description}\n\\item[?Vars :: ?Domain]\\ \\\\\nDomain declaration, in fact just a very simple form of a constraint.\n\n\\item[?T1 \\#\\bsl= ?T2 or ?T1 \\#\\# ?T2]\\ \\\\\n\\index{\\#\\verb+\\=+/2}\nThe value of the rational term {\\it T1} is not equal to the value of the\nrational term {\\it T2}.\n\n\\item[?T1 \\#\\lt ?T2]\\ \\\\\n\\index{\\#$<$/2}\nThe value of the rational term {\\it T1} is less than the value of the\nrational term {\\it T2}.\n\n\\item[?T1 \\#$<=$ ?T2]\\ \\\\\n\\index{\\#$<=$/2}\nThe value of the rational term {\\it T1} is less than or equal to the value of the\nrational term {\\it T2}.\n\n\\item[?T1 \\#= ?T2]\\ \\\\\n\\index{\\#=/2}\nThe value of the rational term {\\it T1} is equal to the\nvalue of the rational term {\\it T2}.\n\n\\item[?T1 \\#$>$ ?T2]\\ \\\\\n\\index{\\#$>$/2}\nThe value of the rational term {\\it T1} is greater than the\nvalue of the rational term {\\it T2}.\n\n\\item[?T1 \\#$>=$ ?T2]\\ \\\\\n\\index{\\#$>=$/2}\nThe value of the rational term {\\it T1} is greater than or equal to the\nvalue of the rational term {\\it T2}.\n\n\\item[element(?Index, +List, ?Value)]\\ \\\\\n\\index{element/3}\nThe {\\it Index}'th element of the ground list {\\it List}\nis equal to {\\it Value}.\n\n\\item[alldifferent(?List)]\n\\index{alldifferent/1}\nAll elements of {\\it List} (domain variables and ground terms) are pairwise\ndifferent.\n\n\\item[atmost(+Number, ?List, +Val)]\\ \\\\\n\\index{atmost/3}\nAt most {\\it Number} elements of the list {\\it List} of domain variables\nand ground terms are equal to the ground value {\\it Val}.\n\\end{description}\n\n%----------------------------------------------------------------------\n%\\section{Propagation}\n\n%----------------------------------------------------------------------\n\\section{Labelling}\n\\begin{description}\n\\item[indomain(+DVar)]\\ \\\\\n\\index{indomain/1}\nThis predicate instantiates the domain variable {\\it DVar} to \nelements of its domain, on backtracking the subsequent value is taken.\nIt is used e.g. to find a value of {\\it DVar} which is consistent\nwith all currently imposed constraints.\nIf {\\it DVar} is a ground term, it succeeds.\nOtherwise, if it is not a domain variable, an error is raised.\n\n\\item[labeling(+List)]\n\\index{labeling/1}\n\\index{labeling!fd}\nThe elements of the {\\it List} are instantiated using the\n\\bipref{indomain/1}{../bips/lib/fd/indomain-1.html} predicate.\n\n\\item[deleteff(?Var, +List, -Rest)]\n\\index{deleteff/3}\nThis predicate is used to select a variable from a list of domain variables\nwhich has the smallest domain.\n{\\it Var} is the selected variable from {\\it List},\n{\\it Rest} is the rest of the list without {\\it Var}.\n\n\\item[deleteffc(?Var, +List, -Rest)]\n\\index{deleteffc/3}\nThis predicate is used to select the most constrained variable from a list\nof domain variables.\n{\\it Var} is the selected variable from {\\it List} which has the least domain\nand which has the most constraints attached to it.\n{\\it Rest} is the rest of the list without {\\it Var}.\n\n\\item[deletemin(?Var, +List, -Rest)]\n\\index{deletemin/3}\nThis predicate is used to select a variable from a list of domain variables\nwhich has the smallest lower domain bound. This is useful e.g.\\ when trying to\nschedule tasks with their earliest possible starting time.\n\\end{description}\n\nThe {\\em fd\\_search} library provides a variety of search routines\nbased on FD.\n\n%----------------------------------------------------------------------\n\\section{Optimization}\n\nThere are optimization predicates in the { \\eclipse } finite\ndomains library.\nHowever it is recommended to use the generic optimization predicates\nin the {\\em branch\\_and\\_bound} library.\nThese predicates support optimization in conjunction with all the\ndifferent solvers in {\\eclipse} which employ variable domains.\n\n\\begin{description}\n\\item[minimize(+Goal,-Cost)]\n\\index{minimize/2}\nThe simplest predicate in the {\\em branch\\_and\\_bound} library is\n\\verb0minimize/20, which behaves as follows.\nA solution of the goal Goal is found that minimizes the value of\nCost. Cost should be a variable that is affected, and eventually\ninstantiated, by Goal. Usually, Goal is the search \nprocedure of a constraint problem and Cost is the variable\nrepresenting the cost. The solution is found using the branch and\nbound method: as soon as a solution is found, it \nis recorded and the search is continued or restarted with an\nadditional constraint on the Cost variable which requires the next\nsolution to be better than the previous one. \nIterating this process yields an optimal solution in the end.\n\n\\item[bb_min(+Goal, -Cost, ++Options)]\n\\index{bb\\_min/3}\nThe user can take more control over the branch and bound behaviour by\ninvoking the predicate \\verb0bb_min/30 which supports a variety of\ndifferent options within the branch and bound framework.\n\\end{description} \n\n%----------------------------------------------------------------------\n\n\\section{Bin Packing}\nThis section presents a worked example using finite domains to solve a\nbin-packing problem.\n\n\\subsection{Problem Definition}\nIn this type of problems the goal is to pack a certain amount of\ndifferent items into the minimal number of bins under specific constraints.\nLet us solve an example given by Andre Vellino in the Usenet\ngroup comp.lang.prolog, June 93:\n\\begin{itemize}\n\\item There are 5 types of items:\n\n        glass, plastic, steel, wood, copper\n\n\\item There are three types of bins:\n\n        red, blue, green\n\n\\item        whose capacity constraints are:\n\n\\begin{itemize}\n\\item        red   has capacity 3\n\\item        blue  has capacity 1\n\\item \t     green has capacity 4\n\\end{itemize}\n\n\\item containment constraints are:\n\\begin{itemize}\n\\item        red   can contain glass, wood, copper\n\\item        blue  can contain glass, steel, copper\n\\item        green can contain plastic, wood, copper\n\\end{itemize}\n\n\\item and requirement constraints are (for all bin types):\n\n        wood requires plastic\n\n\\item Certain component types cannot coexist:\n\n\\begin{itemize}\n\\item        glass and copper exclude each other\n\\item        copper and plastic exclude each other\n\\end{itemize}\n\n\\item and certain bin types have capacity constraint for certain\ncomponents\n\n\\begin{itemize}\n\\item red   contains at most 1 wood item\n\\item green contains at most 2 wood items\n\\end{itemize}\n\n\\item Given an initial supply of:\n\\begin{itemize}\n\\item 1 glass item\n\\item 2 plastic items\n\\item 1 steel items\n\\item 3 wood items\n\\item 2 copper items\n\\end{itemize}\nwhat is the minimum total number of bins required to\ncontain the components?\n\\end{itemize}\n\n\\subsection{Problem Model - Using Structures}\n\nFor modelling this problem we need to refer to an array of quantities\nof glass items, plastic items, steel items, wood items and copper\nitems.\nWe therefore introduce a structure to hold this array:\n\\begin{verbatim}\n:- local struct(contents(glass,plastic,steel,wood,copper))\n\\end{verbatim}\n\nTo represent a bin, with its colour, capacity and contents we use\nanother structure:\n\\begin{verbatim}\n:- local struct(bin(colour,capacity,contents:contents))\n\\end{verbatim}\nThe {\\bf contents} attribute of {\\bf bin} is itself a {\\bf contents}\nstructure. \n\nThe predicate {\\bf solve_bin/2} is the general predicate\nthat takes an amount of components packed into a {\\bf contents}\nstructure and it returns the solution.\n\\begin{quote}\n\\begin{verbatim}\n?- Demand = contents\\{glass:1,plastic:2,steel:1,wood:3,copper:2\\},\n   solve_bin(Demand, Bins).\n\\end{verbatim}\n\\end{quote}\n\n\\subsection{ Handling an Unknown Number of Bins}\n\n{\\bf solve_bin/2}  calls {\\bf bin\\_setup/2} to\ngenerate a list {\\bf Bins}.\nIt adds some redundant constraint to remove symmetries (two\nsymmetrical solutions are\nthe same, but with the bins in a different order).\nFinally it labels all decision variables in the problem.\n\\begin{quote}\n\\begin{verbatim}\nsolve_bin(Demand, Bins) :-\n    bin_setup(Demand,Bins),\n    remove_symmetry(Bins),\n    bin_label(Bins).\n\\end{verbatim}\n\\end{quote}\n\nThe usual pattern for solving finite domain problems is to state\nconstraints on a set of variables, and then label them.\nHowever, because the number of bins needed is not known initially, it\nis awkward to model the problem with a fixed set of variables.\n\nOne possibility would be to take a fixed, large enough, number of bins\nand to try to find a minimum number of non-empty bins.\nHowever, for efficiency, we choose to solve a sequence of problems,\neach one with a - larger - fixed number of bins,\nuntil a solution is found.\n\nThe predicate {\\bf bin_setup/2} to generate a list of bins with appropriate\nconstraints works as follows.\nFirst it tries to match the (remaining) demand with zero,\nand use no (further) bins.\nIf this fails, a new bin is added to the bin list;\nappropriate constraints are imposed on all the new bin's\nvariables;\nits contents are subtracted from the demand;\nand the {\\bf bin_setup/2} predicate calls itself recursively:\n\n\\begin{quote}\n\\begin{verbatim}\nbin_setup(Demand,[]) :- \n        all_zeroes(Demand).\nbin_setup(Demand,[Bin|Bins]) :-\n        constrain_bin(Bin),\n        reduce_demand(Demand,Bin,RemainingDemand),\n        bin_setup(RemainingDemand,Bins).\n\nall_zeroes( \n           contents\\{glass:0,plastic:0,wood:0,steel:0,copper:0\\}\n          ).\n\nreduce_demand( \n              contents\\{glass:G,plastic:P,wood:W,steel:S,copper:C\\},\n              bin\\{glass:BG,plastic:BP,wood:BW,steel:BS,copper:BC\\},\n              contents\\{glass:RG,plastic:RP,wood:RW,steel:RS,copper:RC\\} \n             ) :-\n       RG #= G - BG,\n       RP #= P - BP,\n       RW #= W - BW,\n       RS #= S - BS,\n       RC #= C - BC.\n\t\t\t\n\\end{verbatim}\n\\end{quote}\n\n\\subsection{Constraints on a Single Bin}\n\nThe constraints imposed on a single bin correspond exactly to the\nproblem statement:\n\\begin{quote}\n\\begin{verbatim}\nconstrain_bin(bin\\{colour:Col,capacity:Cap,contents:C\\}) :-\n        colour_capacity_constraint(Col,Cap),\n        capacity_constraint(Cap,C),\n        contents_constraints(C),\n        colour_constraints(Col,C).\n\\end{verbatim}\n\\end{quote}\n\n\\paragraph{colour\\_capacity\\_constraint} \nThe colour capacity constraint relates the colour of the bin to its\ncapacity.  It uses generalised propagation to apply\narc-consistency propagation.\n\\begin{quote}\n\\begin{verbatim}\ncolour_capacity_constraint(Col,Cap) :-\n\tcapacity(Col,Cap) infers ac.\n\ncapacity(blue, 1). \ncapacity(green,4).\ncapacity(red,  3).\n\\end{verbatim}\n\\end{quote}\nAt the end of this section we will present another way to implement the\ncolour\\_capacity\\_constraint, using the explicit \"glass-box\"\nfunctionality of fd. \n\n\\paragraph{capacity\\_constraint}\nThe capacity constraint states:\n\\begin{itemize}\n\\item that the number of items of each\nkind in the bin is non-negative, \n\\item\ntheir sum does not exceed the capacity of the bin,   \n\\item and the bin is non-empty (an empty bin serves no purpose)\n\\end{itemize}\n\n\\begin{quote}\n\\begin{verbatim}\ncapacity_constraint(Cap, contents\\{glass:G,\n                                   plastic:P,\n                                   steel:S, \n                                   wood:W,\n                                   copper:C\\}) :-\n        G #>= 0, P #>= 0, S #>= 0, W #>= 0, C #>= 0,\n        Cap #>= G+P+W+S+C,\n        G+P+W+S+C #> 0.\n\\end{verbatim}\n\\end{quote}\n\n\\paragraph{contents\\_constraints}\nThe contents_constraints directly enforce the restrictions on items in\nthe bin: wood requires paper, glass and copper exclude each other, and\ncopper and plastic exclude each other:\n\\begin{quote}\n\\begin{verbatim}\ncontents_constraints(contents\\{glass:G,plastic:P,wood:W,copper:C\\}) :-\n        requires(W,P),\n        exclusive(G,C),\n        exclusive(C,P).\n\\end{verbatim}\n\\end{quote}\n\nThese constraints are expressed as logical combinations of constraints\non the number of items.\n\"requires\" is expressed using entailment, \\verb0#=>0.\n\"Wood requires paper\" is expressed in logic as \"If the number of wood\nitems is greater than zero, then the number of paper items\nis also greater than zero\":\n\\begin{quote}\n\\begin{verbatim}\nrequires(W,P) :-\n        W #> 0 #=> P #> 0.\n\\end{verbatim}\n\\end{quote}\n\nExclusion is expressed using disjunction, \\verb0#\\/0.\n\"X and Y are exclusive\" is expressed as \"Either the number of items of\nkind $X$ is zero, or the number of items of kind $Y$ is zero\":\n\\begin{quote}\n\\begin{verbatim}\nexclusive(X,Y) :-\n        X #= 0 #\\/ Y #= 0.\n\\end{verbatim}\n\\end{quote}\n\n\\paragraph{colour\\_constraints}\nThe colour constraint limits the number of wooden items in bins of\ndifferent colours.\nLike the capacity constraint, the relation between the colour and\ncapacity ($WCap$ is expressed using generalised propagation to enforce\narc-consistency.  The number of wooden items is then constrained not to\nexceed the capacity:\n\\begin{quote}\n\\begin{verbatim}\ncolour_constraints(Col,contents\\{wood:W\\}) :-\n        colour_wood_cap(Col,WCap) infers ac,\n        WCap #>= W.\n\ncolour_wood_cap(blue, Cap) :- capacity(blue, Cap).\ncolour_wood_cap(green,2).\ncolour_wood_cap(red,1).\n\\end{verbatim}\n\\end{quote}\n\nThis model artificially introduces a capacity of blue bins for\nwood items (set simply at its maximum capacity for all items).\n\n\n\\subsection{Symmetry Constraints}\nTo make sure two solutions are not just different permutations of the\nsame bins, we fix the sequence of variables specifying each bin, and\nlexically order their values.\n\n\\begin{quote}\n\\begin{verbatim}\nremove_symmetry(Bins) :-\n        ( fromto(Bins,[B1,B2|Rest],[B2|Rest],[_Last])\n        do\n            lex_ord(B1,B2)\n        ).\n\\end{verbatim}\n\\end{quote}\n\nSince colours don't have a built-in ordering, we map them to integers\nand apply the lexicographic ordering to the integers instead of the\ncolours.  Since the mapping is defined before values are chosen for the\nvariables, the mapping is turned into a constraint, using generalised\npropagation.  \n\\begin{quote}\n\\begin{verbatim}\nlex_ord(bin\\{colour:Col1,contents:Conts1\\},\n        bin\\{colour:Col2,contents:Conts2\\}) :-\n        colour_map(Col1,Int1) infers ac,\n        colour_map(Col2,Int2) infers ac,\n        term_variables(Conts1,Vars1),\n        term_variables(Conts2,Vars2),\n        lexico_le([Int1|Vars1],[Int2|Vars2]).\n\ncolour_map(blue,1).\ncolour_map(green,2).\ncolour_map(red,3).\n\\end{verbatim}\n\\end{quote}\n(Another way to associate integers with colours is\ndescribed at the end of this section.)\n\nThough lexicographical ordering is defined in the fd\\_global library of\n{ \\eclipse }, Warwick\nHarvey has written a very elegant version that enforces arc-consistency,\nusing a few features of the fd library.  Here it is:\n\n\\begin{quote}\n\\begin{verbatim}\nlexico_le(Xs, Ys) :-\n        lexico_le_bool(Xs, Ys, 1).\n\nlexico_le_bool([], [], 1).\nlexico_le_bool([X | Xs], [Y | Ys], B) :- \n        B isd (X #< Y + B1),\n        lexico_le_bool(Xs, Ys, B1).\n\\end{verbatim}\n\\end{quote}\n\n\\subsection{Search}\n\nThe search is done by first choosing a colour for each bin, and then\nlabelling the remaining variables.\n\\begin{quote}\n\\begin{verbatim}\nbin_label(Bins) :-\n        ( foreach(bin\\{colour:C\\},Bins) do indomain(C) ),\n        term_variables(Bins,Vars),\n        labeleff(Vars).\n\\end{verbatim}\n\\end{quote}\n\nThe remaining variables are labelled using the first fail heuristic\n(using the fd built-in \\verb0deleteff0).  This code illustrates the use\nof \\verb0fromto0 for dynamically ordering the variables to be labelled.\n\\begin{quote}\n\\begin{verbatim}\nlabeleff(Vars) :-\n        ( fromto(Vars,InVars,OutVars,[]) \n        do\n            deleteff(Var,InVars,OutVars),\n            indomain(Var)\n        ).\n\\end{verbatim}\n\\end{quote}\n\n\\subsection{Glass-Box Implementation of colour\\_capacity\\_constraint}\nTo illustrate how the facilities of fd can be used to directly encode\nconstraint behaviour, we have reimplemented the\ncolour\\_capacity\\_constraint without using generalised propagation.\n\nThe first requirement is to ensure the capacity variable has a finite\ndomain.  One way to do this is as follows:\n\\begin{quote}\n\\begin{verbatim}\ncolour_capacity_constraint(Col,Cap) :-\n    ( is_domain(Cap) -> true ; Cap #>= 0 ),\n    col_cap_cons(Col,Cap).\n\\end{verbatim}\n\\end{quote}\n\nIf the colour $Col$ is already known, the constraint is enforced simply by\ninvoking the capacity predicate.  If, however, the colour $Col$ is a\nvariable, then the more complex var\\_col\\_cap predicate is called:\n\n\\begin{quote}\n\\begin{verbatim}\ncol_cap_cons(Col,Cap) :-\n    ( nonvar(Col) -> capacity(Col,Cap) ;\n      var(Col) -> var_col_cap(Col,Cap)\n    ).\n\\end{verbatim}\n\\end{quote}\n\nIf the required capacity (i.e. the minimum value in the domain of $Cap$)\nis more than 1, then the colour cannot be blue.\nIf, moreover, the required capacity is more than 3, then the colour must\nbe green.\nIf the required capacity is either 2 or 3, then any change to the $Col$\nor $Cap$ variables must instantiate them, because each variable has only\ntwo \npossible values).  Since there is a unique\ncolour for each capacity, as well as vice versa, it suffices to call the\ncapacity predicate as soon as either variable is instantiated.\nIf, however the minimum capacity is still 1, then the col\\_cap\\_cons\nconstraint is suspended again, until the colour is instantiated\n\\verb0Col->inst0 or the required\ncapacity increases \\verb0Cap->min0:\n\\begin{quote}\n\\begin{verbatim}\t\t\t  \nvar_col_cap(Col, Cap) :-\n    mindomain(Cap,MinC),\n    (MinC > 1 ->\n        Col #\\= blue,\n        (MinC > 3 ->\n            Col = green\n        ;\n            suspend(capacity(Col, Cap), 3, (Col, Cap)->inst)\n        )\n    ;\n        suspend(col_cap_cons(Col, Cap), 3, [Col->inst, Cap->min])\n    ).\n\n\\end{verbatim}\n\\end{quote}\n\n\\subsection{Using Macros instead of a Colour-Integer Mapping}\n\nAs we discussed in the section on symmetries, above, there is no\nbuilt-in ordering on colours.\n\nTo keep the lexicographic ordering predicate simple and still have a\nsymbolic \nrepresentation of the colour in the program, we can define\ninput macros that transform the colour atoms into integers:\n\n\\begin{quote}\n\\begin{verbatim}\n:- define_macro(no_macro_expansion(blue)/0, tr_col/2, []).\n:- define_macro(no_macro_expansion(green)/0, tr_col/2, []).\n:- define_macro(no_macro_expansion(red)/0, tr_col/2, []).\n\ntr_col(no_macro_expansion(red), 1).\ntr_col(no_macro_expansion(green), 2).\ntr_col(no_macro_expansion(blue), 3).\n\n\\end{verbatim}\n\\end{quote}\n\nNow the symmetry removal can be programmed using the following\nlexical ordering predicate:\n\n\\begin{quote}\n\\begin{verbatim}\nlex_ord(Bin1,Bin2) :-\n       term_variables(Bin1,V1),\n       term_variables(Bin2,V2),\n       lexico_le(V1,V2).\n\\end{verbatim}\n\\end{quote}\n\n\n\n\n", "meta": {"hexsha": "2460e8daf292615c9dd387f425f8ab1799538baf", "size": 24766, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "usr/eclipseclp/documents/tutorial/fdintro.tex", "max_stars_repo_name": "lambdaxymox/barrelfish", "max_stars_repo_head_hexsha": "06a9f54721a8d96874a8939d8973178a562c342f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 111, "max_stars_repo_stars_event_min_datetime": "2015-02-03T02:57:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T23:57:09.000Z", "max_issues_repo_path": "usr/eclipseclp/documents/tutorial/fdintro.tex", "max_issues_repo_name": "lambdaxymox/barrelfish", "max_issues_repo_head_hexsha": "06a9f54721a8d96874a8939d8973178a562c342f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2016-03-22T14:44:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-18T13:30:29.000Z", "max_forks_repo_path": "usr/eclipseclp/documents/tutorial/fdintro.tex", "max_forks_repo_name": "lambdaxymox/barrelfish", "max_forks_repo_head_hexsha": "06a9f54721a8d96874a8939d8973178a562c342f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 55, "max_forks_repo_forks_event_min_datetime": "2015-02-03T05:28:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T05:00:03.000Z", "avg_line_length": 32.121919585, "max_line_length": 81, "alphanum_fraction": 0.7023742227, "num_tokens": 6348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.3219494999607148}}
{"text": "%!TEX root = paper.tex\r\n\\subsection{Nonlinear shoaling wave over submerged bar}\r\nIn this laboratory experiment an incident sin wave travels over a trapezoidal underwater obstacle and the surface elevations of the non-breaking wave are measured at several gauges spread along the obstacle.\r\nThis experiment conducted in different versions by \\cite{BejiBattjes.1993} and \\cite{BejiBattjes.1994}, \\cite{Dingemans.1994} (more cases, here only case A considered), and by Luth et al. (1994) (cited in \\cite{Dingemans.1994}, but I do not have access to the report). \r\nIn this experiments, gauges and setups were different (see tables \\ref{tab:bejibattjes_gauges_SZ} -- \\ref{tab:bejibattjes_gauges_BB1994} and figures \\ref{fig:bejibattjes_setup_SZ} -- \\ref{fig:bejibattjes_setup_BB1994}).\r\n\r\nThe setup is as described in \\cite{StellingZijlema.2003}, and M. Zijlema provided the data. According to the gauges, this should be the data described in \\cite{Dingemans.1994, StellingZijlema.2003} as the data from Luth et al. (1994), but scaled (divided) by a factor of 2. \r\n\r\nThe initial condition is the unperturbed state. The boundary condition is described as in incident wave at the left boundary of the computational domain, where the surface elevation is set to $\\xi=a \\text{sin}\\left(\\frac{2\\pi t}{T}\\right)$ with period $T=2.02 \\,$s and amplitude $a=1.0\\,$cm.\r\nWe impose reflecting boundary conditions at the boundary in x-direction and periodic boundary conditions in y-direction. For the setup see figure \\ref{fig:bejibattjes_setup_SZ}. The computational domain is enlarged to 40m to ensure no reflecting waves disturbing the solution during the simulation time of 40s.\r\n\r\nNote: No boundary conditions are specified for w and q at the moment, computations which set them to zero are running. This hopefully explains the wrong behavior. \r\n\r\n\r\n\\begin{table}[htbp]\r\n\\begin{tabular}{lllllllll}\r\n\\textbf{gauge} & G4 & G5 & G6 & G7 & G8 & G9 & G10 & G11 \\\\\r\n\\toprule\r\n\\textbf{x [m]} & 10.5 & 12.5 & 13.5 & 14.5 & 15.7 & 17.3 & 19.9 & 21.0 \\\\\r\n\\bottomrule\r\n\\end{tabular}\r\n\\caption{Locations of gauges used in \\cite{StellingZijlema.2003}}\r\n\\label{tab:bejibattjes_gauges_SZ}\r\n\\end{table}\r\n\r\n\\begin{table}[htbp]\r\n\\begin{tabular}{lllllllll}\r\n\\textbf{gauge} & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 \\\\\r\n\\toprule\r\n\\textbf{x [m]} & 6.0 & 11.0 & 12.0 & 13.0 & 14.0 & 15.0 & 16.0 & 17.0 \\\\\r\n\\bottomrule\r\n\\end{tabular}\r\n\\caption{Locations of gauges used in \\cite{BejiBattjes.1993}}\r\n\\label{tab:bejibattjes_gauges_BB1993}\r\n\\end{table}\r\n\r\n\\begin{table}[htbp]\r\n\\begin{tabular}{llllllll}\r\n\\textbf{gauge} & 1 & 2 & 3 & 4 & 5 & 6 & 7 \\\\\r\n\\toprule\r\n\\textbf{x [m]} & 6 & 10.8 & 12.8 & 13.8 & 14.8 & 16.0 & 17.6 \\\\\r\n\\bottomrule\r\n\\end{tabular}\r\n\\caption{Locations of gauges used in \\cite{BejiBattjes.1994}}\r\n\\label{tab:bejibattjes_gauges_BB1994}\r\n\\end{table}\r\n\r\n\\begin{figure}[htbp]\r\n\\includegraphics[width=\\textwidth]{bejibattjes_setup_SZ}\r\n\\caption{Setup of the experiment of Beji and Battjes according to \\cite{StellingZijlema.2003}}\r\n\\label{fig:bejibattjes_setup_SZ}\r\n\\end{figure}\r\n\r\n\\begin{figure}[htbp]\r\n\\includegraphics[width=\\textwidth]{bejibattjes_setup_BB1993}\r\n\\caption{Setup of the experiment of Beji and Battjes according to \\cite{BejiBattjes.1993}}\r\n\\label{fig:bejibattjes_setup_BB1993}\r\n\\end{figure}\r\n\r\n\\begin{figure}[htbp]\r\n\\includegraphics[width=\\textwidth]{bejibattjes_setup_BB1994}\r\n\\caption{Setup of the experiment of Beji and Battjes according to \\cite{BejiBattjes.1994}}\r\n\\label{fig:bejibattjes_setup_BB1994}\r\n\\end{figure}\r\n\r\n\\subsubsection{Results of \\nh\\ model}\r\nThe model results can be found in figure \\eqref{fig:nh_bejjibattjes_nh}.\r\nThe results are shifted in time by 4.5s to match the laboratory data at gauge 10 in phase after 20s.\r\n\r\n\\begin{figure}[htbp]\r\n\\begin{minipage}{\\textwidth}\r\n\\includegraphics[width=0.48\\textwidth]{BejiBattjes_nh_x=loc_4}\r\n\\includegraphics[width=0.48\\textwidth]{BejiBattjes_nh_x=loc_5}\r\n\\end{minipage} \\\\\r\n\\begin{minipage}{\\textwidth}\r\n\\includegraphics[width=0.48\\textwidth]{BejiBattjes_nh_x=loc_6}\r\n\\includegraphics[width=0.48\\textwidth]{BejiBattjes_nh_x=loc_7}\r\n\\end{minipage} \\\\\r\n\\begin{minipage}{\\textwidth}\r\n\\includegraphics[width=0.48\\textwidth]{BejiBattjes_nh_x=loc_8}\r\n\\includegraphics[width=0.48\\textwidth]{BejiBattjes_nh_x=loc_9}\r\n\\end{minipage} \\\\\r\n\\begin{minipage}{\\textwidth}\r\n\\includegraphics[width=0.48\\textwidth]{BejiBattjes_nh_x=loc_10}\r\n\\includegraphics[width=0.48\\textwidth]{BejiBattjes_nh_x=loc_11}\r\n\\end{minipage}\r\n\\caption{Comparison of the laboratory (black) sea surface height at gauges with the simulation results of the \\nh\\ model with linear pressure profile (yellow) and quadratic pressure profile (red)}\r\n\\label{fig:nh_bejjibattjes_nh}\r\n\\end{figure}", "meta": {"hexsha": "10e35b121e253f2a1d4fb0b5e77ec1e514d5869b", "size": 4696, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/papers/theoretical_1d/B_bejibattjes.tex", "max_stars_repo_name": "mandli/coastal", "max_stars_repo_head_hexsha": "8c80a4c740f92ea83b54c8a5432d11058c0d3476", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/papers/theoretical_1d/B_bejibattjes.tex", "max_issues_repo_name": "mandli/coastal", "max_issues_repo_head_hexsha": "8c80a4c740f92ea83b54c8a5432d11058c0d3476", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/papers/theoretical_1d/B_bejibattjes.tex", "max_forks_repo_name": "mandli/coastal", "max_forks_repo_head_hexsha": "8c80a4c740f92ea83b54c8a5432d11058c0d3476", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.7640449438, "max_line_length": 311, "alphanum_fraction": 0.7510647359, "num_tokens": 1587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.3219494908153011}}
{"text": "% !TEX TS-program = lualatex\n\\documentclass{article}\n\n%\\usepackage{fontspec}\n\n\n\\begin{document}\n\n\\section{Introduction}\n\\label{Intro}\n\nTherefore we still aim to compute the traces in the drift term exactly. For this we note that the derivative in the trace is an extremely sparse matrix only containing two nonzero $3\\times 3$ blocks located at block-entries $(i,i+\\hat d)$ and $(i+\\hat d,i)$. On multiplication with $D^{-1}$ the product matrix will be sparse, existing of 2 full column-blocks at $(k,i)$ and $(k,i+\\hat d$), $k=1,\\ldots,V$ (a column block has size $3V\\times 3$). To compute such a trace the same columns of $D^{-1}$ are needed. Hence, it looks as if the complete matrix $D^{-1}$ is needed when computing all traces. However, the situation is not as dramatic as it seems. Indeed, on taking the trace of the product matrix only the \\textit{diagonal elements} of the product is needed. To compute these diagonal elements we do not need the complete columns of $D^{-1}$ but only the $3\\times 3$ blocks located at the transposed positions of the $3\\times 3$ derivative blocks $\\partial D/\\partial a$. For example, the derivative block at location $(i+\\hat d,i)$ will only give a contribution to the trace when multiplied with the $3\\times 3$ block of $D^{-1}$ located at $(i, i+\\hat d)$. \n\nTherefore we still aim to compute the traces in the drift term exactly.\nFor this we note that the derivative in the trace is an extremely sparse matrix only containing two nonzero $3\\times 3$ blocks located at block-entries $(i,i+\\hat d)$ and $(i+\\hat d,i)$.\nOn multiplication with $D^{-1}$ the product matrix will be sparse, existing of 2 full column-blocks at $(k,i)$ and $(k,i+\\hat d$), $k=1,\\ldots,V$ (a column block has size $3V\\times 3$).\nTo compute such a trace the same columns of $D^{-1}$ are needed. Hence, it looks as if the complete matrix $D^{-1}$ is needed when computing all traces.\n However, the situation is not as dramatic as it seems.\n Indeed, on taking the trace of the product matrix only the \\textit{diagonal elements} of the product is needed.\n To compute these diagonal elements we do not need the complete columns of $D^{-1}$ but only the $3\\times 3$ blocks located at the transposed positions of the $3\\times 3$ derivative blocks $\\partial D/\\partial a$.\n For example, the derivative block at location $(i+\\hat d,i)$ will only give a contribution to the trace when multiplied with the $3\\times 3$ block of $D^{-1}$ located at $(i, i+\\hat d)$. \n\n\\end{document}\n", "meta": {"hexsha": "a43392a376b45929d55e0beb6fe90884f2cf7ff3", "size": 2488, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "synctex test files/synchronization/2017/problem/problem.tex", "max_stars_repo_name": "templateK/synctex", "max_stars_repo_head_hexsha": "555467da1535b0b1d7e97532a2c6251d9c2b3957", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38, "max_stars_repo_stars_event_min_datetime": "2016-12-23T02:21:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T22:07:39.000Z", "max_issues_repo_path": "synctex test files/synchronization/2017/problem/problem.tex", "max_issues_repo_name": "templateK/synctex", "max_issues_repo_head_hexsha": "555467da1535b0b1d7e97532a2c6251d9c2b3957", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2016-12-23T13:20:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T22:31:48.000Z", "max_forks_repo_path": "synctex test files/synchronization/2017/problem/problem.tex", "max_forks_repo_name": "templateK/synctex", "max_forks_repo_head_hexsha": "555467da1535b0b1d7e97532a2c6251d9c2b3957", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2017-08-28T20:40:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-25T21:50:14.000Z", "avg_line_length": 103.6666666667, "max_line_length": 1165, "alphanum_fraction": 0.7327170418, "num_tokens": 655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.3217369362777521}}
{"text": "%!TEX root = paper.tex\n%\n% AMRClaw\n%\n% Lead currently:  Marsha Berger\n%\n\n\\subsection{\\amrclaw} \\label{sec:amrclaw}\nFortran code in the \\amrclaw repository performs block-structured adaptive mesh\nrefinement \\cite{BO,BC} for both \\clawpack and \\geoclaw  applications.\nThe algorithms implemented in \\amrclaw are discussed in detail in\n\\cite{mjb-rjl:amrclaw,LeVequeGeorgeBerger:an11}, but a  short description is\ngiven here to set the stage for a description of recent changes. \\revised{\nThis type of refinement solves the PDE on a hierarchy of logically rectangular\ngrids.  One (or more) level 1 grids comprise the entire domain, while grids at\nfiner level are created and destroyed (as opposed to moving these grids) to\nfollow important features in the solution.}\n\n\\begin{figure}[tb]\n    \\centering\n    \\includegraphics[width=0.6\\textwidth, trim=40 80 40 70, clip]{final_submission/Fig1.png}\n    \\caption{\\revised{An illustration showing grid cells on levels one and two, and only grid outlines on levels three and four.}}\n    \\label{fig:figure1}\n\\end{figure}\n\n\\amrclaw includes the functionality for:\n\\begin{itemize}\n\\item Coordinating the flagging of points where refinement is needed,\nwith a variety of criteria possible for flagging cells that need refinement\nfrom each level to the next finer level (including Richardson extrapolation,\ngradient testing, or user-specified criteria)\\footnote{See\n\\url{http://www.clawpack.org/flag.html}},\n\\item Organizing the flagged points into efficient grid\npatches at the next finer level, using the algorithm of\n\\cite{mjb-rig:cluster},\n\\item Interpolating the solution to newly created fine grids and initializing\nauxiliary data (topography, wind velocity, metric data and so on) on  these\ngrids,\n\\item Averaging fine grid solutions to coarser grids,\n\\item Orchestrating the adaptive time stepping (i.e. sub-cycling in time),\n\\item Interpolating coarse grid solution to fine grid ghost cells, and\n\\item Maintaining conservation at patch boundaries between resolution levels.\n\\end{itemize}\n\n\\amrclaw now allows users to specify ``regions'' in space-time\n$[x_1,x_2] \\times [y_1,y_2] \\times [t_1,t_2]$ in which refinement is forced to\nbe at least at some level $L_1$ and is allowed to be at most $L_2$.  This can be\nuseful for constraining refinement, e.g. allowing or ensuring resolution of only\na small coastal region in a global tsunami simulation. Previously the user could\nenforce such conditions by writing a custom flagging routine, but now this is\nhandled in a general manner so that the parameters above can all be specified in\nthe Python problem specification. Multiple regions can be specified, and a\nsimple rule is used to determine the constraints at a grid cell that lies in\nmultiple regions.\n\nAuxiliary arrays are often used in \\clawpack to store data that\ndescribes the problem and the routine.\nThe routine \\texttt{setaux} must then be provided by the user to set these values each time a\nnew grid patch is created.  For some applications computing these values can be time-consuming.  In \\clawpack 5.2,\nthis code was improved to allow reuse of values from previous patches at\nthe same level where possible at each regridding time.\nThis is backward compatible, since no harm is done if previously\nwritten routines are used that still compute and overwrite instead of\nchecking a mask.\n\nIn \\clawpack 5.3 the capability to specify spatially varying boundary\nconditions was added. For a single grid, it is a simple matter to\ncompute the location of the ghost cells that extend outside the\ncomputational domain and set them appropriately.  With AMR however,\nthe boundary condition routine can be called for a grid located\nanywhere in the domain, and may contain fewer or larger numbers of\nghost cells. For this reason, the boundary condition routines\n do not assume a fixed number of ghost cells.\n\nAnisotropic refinement is allowed in both two and three dimensions.\nThis means that the spatial and temporal refinement ratios can be\nspecified independently from one another (as long as the temporal\nrefinement satisfies the CFL condition).  In addition, capabilities\nhave been added to automatically select the refinement ratio in time  on each\nlevel based on the CFL condition.  This has only been implemented in\n\\geoclaw where the wave speed in the shallow water equations\ndepends on the local depth. The finest grids are often located only in\nshallow coastal regions, so a large refinement ratio in space does not\nlead to a large refinement ratio in time.\n\n\\amrclaw has been parallelized using OpenMP directives. \\revised{The main\nparadigm in structured AMR is an outer loop over levels of refinement, and an\ninner loop over all grids at that level, where \\revised{the same} operation is\nperformed on each grid (i.e. taking a time step, finding ghost cells,\nconservation updates, etc.).  This inner loop is parallelized using a {\\tt\nparallel for} loop construct.  One thread is assigned to operate on one grid.\nDynamic scheduling is used with a chunk size of one.  To help with load\nbalancing, grids at each level are sorted from largest to smallest, using the\ntotal number of cells in the grid as an indicator of work.  In addition the\ngrids are limited to a maximum of 32 cells in each dimension, otherwise they\nare bisected until this condition is met.}  Note that this approach causes a\nmemory bulge. Each thread must have its own scratch arrays to save the incoming\nand outgoing waves and fluxes for future conservation fix-ups. The bulge is\ndirectly proportional to the number of threads executing. For stack-based memory\nallocation per thread, the use of the environment variable {\\tt OMP\\_STACKSIZE}\nto increase the limit may be necessary.\n\n\\cref{fig:shockbubble} shows two snapshots of the solution to a\nthree-dimensional shock-bubble interaction problem found in the \\clawpack\n\\texttt{apps} repository, illustrating localized phenomena requiring adaptive\nrefinement. In \\cref{fig:amr_scaling} we show scalability tests and some timings\nfor this example, when run on a 24 core Intel Xeon Haswell machine\n\\revised{(E5-2670v3 at 2.3 GHz)}, using\n\\texttt{KMP\\_AFFINITY compact} \\revised{with one thread per core}.\nFor timing purposes, the only modifications made to the input parameters was to\nturn off check-pointing and graphics output. The plot on the left shows that most\nof the wall clock time is in the integration routine (\\texttt{stepgrid}), which\nclosely tracks the total time. The second chunk of time is in the regridding,\nwhich contains algorithms that are not completely scalable. Very little time is\nin the filling of ghost cells, mostly from other patches but also includes those\nat domain boundaries. The efficiency is above 80\\% until 24 cores.\nNote that there are only two grids on level, and an average of\n22.8 level 2 grids. Most of the work is on level 3 grids, where there are an\naverage of 138.1 grids over all the level 3 timestep.  At 24 cores, there are\non average 5.8 grids per core, and the grids are very different sizes.\n\n\\begin{figure}[t]\n  \\begin{center}\n    \\includegraphics[width=\\textwidth]{figures/final_submission/Fig2}\n    % \\plotbox{\\includegraphics[width=0.45\\textwidth]{f1.png}}\\hfil\n    % \\plotbox{\\includegraphics[width=0.45\\textwidth]{f4.png}}\n  \\end{center}\n\\caption{\\amrclaw example demonstrating a\n  shock-bubble interaction in the Euler equations of compressible\n  gas-dynamics at two times, illustrating the need for adaptive refinement\n  to capture localized behavior. \\revised{There are two $20 \\times 10 \\times 10$\n  grids at\n  level 1.  They are refined} where needed\n  by factors of 4 and then 2 in this 3-level run.}\n\\label{fig:shockbubble}\n\\end{figure}\n\n\\begin{figure}[h]\n  \\begin{center}\n    % \\includegraphics[width=0.45\\textwidth]{amr_scaling}\n    % \\plotbox{\\includegraphics[width=0.4\\textwidth,\n    %   clip=true,trim=0cm 1cm 1cm 2cm]{newcpu.pdf}}\\hfil\n    % \\plotbox{\\includegraphics[width=0.4\\textwidth,\n    %   clip=true,trim=0cm 1cm 1cm 2cm]{efficiency.pdf}}\n    \\includegraphics[width=\\textwidth]{final_submission/Fig3.pdf}\n  \\end{center}\n  \\caption{(a) Strong scaling results for the \\amrclaw example shown in\n    \\cref{fig:shockbubble}.\n    (b) Plot of efficiency based on total computational time.}\n  \\label{fig:amr_scaling}\n\\end{figure}\n\n\\revised{The target architecture for \\amrclaw and \\geoclaw are multi-core\nmachines.  \\pyclaw on the other hand scales to tens of\nthousands of cores using MPI via PETSc \\cite{petsc-user-ref} but is not\nadaptive.}\n", "meta": {"hexsha": "a1fac0952b16f71874fda3132f77d7b0ddc4a67a", "size": 8476, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "papers/clawpack-5x/amrclaw.tex", "max_stars_repo_name": "kbarnhart/doc", "max_stars_repo_head_hexsha": "ede1e86c883ad9336f6334c967a89212d2b9cdc7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-01-08T12:17:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-15T21:17:44.000Z", "max_issues_repo_path": "papers/clawpack-5x/amrclaw.tex", "max_issues_repo_name": "kbarnhart/doc", "max_issues_repo_head_hexsha": "ede1e86c883ad9336f6334c967a89212d2b9cdc7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 76, "max_issues_repo_issues_event_min_datetime": "2015-01-31T20:22:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-05T16:55:53.000Z", "max_forks_repo_path": "papers/clawpack-5x/amrclaw.tex", "max_forks_repo_name": "kbarnhart/doc", "max_forks_repo_head_hexsha": "ede1e86c883ad9336f6334c967a89212d2b9cdc7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-03-01T08:26:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-06T02:59:13.000Z", "avg_line_length": 53.9872611465, "max_line_length": 130, "alphanum_fraction": 0.7864558754, "num_tokens": 2142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.3217369362777521}}
{"text": "\\chapter{Experiments}\\label{chap:experiments}\nA series of experiments were carried out to determine the performance of the network in its stated goal of classifying traversability. To this end, the network was tested on the Mapillary Vistas dataset \\cite{mapillary} and its hyperparameters optimized using the Bayesian optimization with hyperband (BOHB) procedure\\cite{bohb}\n\n\\section{Evaluation Metrics} \\label{section:experiments-evaluationmetrics}\nThe mean Intersection over Union (mIoU) is the main evaluation metric chosen.\nIoU measures the intersection of the prediction and the ground truth data, divided by the union of the prediction and the ground truth data.\nThis is formally defined as\n\\begin{align}\n\tJ(A_m,B_m) &= \\frac{|A_m \\cap B_m|}{|A_m \\cup B_m|}\n\\end{align}\nwhere $A$ is the prediction, $B$ the ground truth, and $m$ the class.\nThe mIoU is thus defined as\n\\begin{align}\n\tJ(A,B) &= \\frac{1}{|m|} \\sum_{m}\\frac{|A_m \\cap B_m|}{|A_m \\cup B_m|}\n\\end{align}\nand can be intuitively understood as the average of the class-wise IoU accuracy values.\n\n\\section{Dataset} \\label{section:experiments-dataset}\nWe evaluate our approach on the Mapillary Vistas dataset as it was, to our knowledge, the only street-level dataset that included ground truth segmentations of both curbs and curb cuts at the time of writing.\nThis dataset contains images from all around the world and includes images captured from different imaging devices including mobile phones, action cameras, and professional imaging solutions.\nThese images are captured during various weather, seasonal, and daylight conditions.\nAs such, the dataset provides a challenging level of diversity.\n\nSome image samples from the dataset can be seen in \\figref{fig:experiments-datasetsamples}.\nThese images show some examples of how diverse the images in the dataset can be.\nThe dataset also contains images taken from sidewalks, such as in the case of Figure \\ref{fig:dataset-3}.\nThis is especially useful for our end goal of training a segmentation network for an autonomous pedestrian robot.\nThe diversity of the dataset improves the generalizability of our model.\n\n\\input{figures/experiments/dataset}\n\nThe image dimensions in the dataset are also not standardized, with 156 different image dimensions ranging from $(640 \\times 480)$ to $(6528 \\times 5248)$. \nWith such a diverse range of dimensions, the images must first be preprocessed.\nWe process all the images to conform to a 4:3 size ratio, eliminate images without images of curbs or curb cuts, and extract only road, curb, and curb cut classes.\n\nTo optimize training speed with respect to wall clock time, and given the computational constraints, images were resized for training.\nThe chosen image resolution was $360 \\times 320$ pixels. \nWe use an NVIDIA Titan X GPU with 12 GB of VRAM.\nThis allows a batch size of 16 per GPU.\nTo further optimize training, the images are resized prior to training and the resized images stored.\nThis allows all training and validation images to be loaded into memory once at the beginning of training, reducing the number of file accesses required and reducing training wall clock time by a factor of two.\n\nAfter running an analysis of the dataset with respect to their curb and curb cut content and image dimensions, we found that there were 15,160 usable images in the training set and 1610 usable images in the validation set.\nUsable images in this case refers to images that at least contain both curbs and curb cuts.\nA detailed results of the analysis of the dataset can be found in Appendix section \\ref{appendix:dataset}.\n\nWe also applied image augmentation to our dataset.\nThe augmentations we have applied are Gaussian blur, dropout, brightness adjustment, and contrast adjustment.\n\n\\section{Network Evaluation}\\label{section:experiments-networkevaluation}\nExperiments were done to evaluate the performance of different networks on our dataset.\nSpecifically, we identified the small size of curbs relative to the rest of the image causes a severe class imbalance and increases the difficulty in recognizing the smaller features.\n\nRelative to the entire image, curb and curb cut classes make up a relatively small proportion of the image, making up an average of 0.986\\% and 0.196\\% of images respectively.\nAs such, three networks with good known performance for urban scene segmentation were chosen and evaluated for their performance classifying traversability classes.\nWe experimented with GoogLeNet, described in the paper \"Going Deeper with Convolutions\"~\\cite{googlenet}; FCN16s, described in \"Fully Convolutional Networks for Semantic Segmentation\"~\\cite{fcn}; and DeepLab v3+, described in the paper \"Encoder-Decoder with Atrous Separable Convolution for Semantic Image Segmentation\"~\\cite{deeplab}.\n\nTo evaluate which network would have the most potential, we trained each network on a small subset of the whole dataset to find which networks would yield the highest overall accuracy given a certain budget.\nWe use a subset of 64 images, sampled randomly from the Mapillary Vistas training subset, for training and a subset of 64 images, also sampled randomly from the Mapillary Vistas validation subset, for validation.\nFor each of these runs, the default recommended hyperparameters from the DeepLab v3+ paper were used.\nDue to time constraints, conduct hyperparameter optimization was not done on each of the tested networks.\nThe results can be seen in \\figref{chart:experiments-networkcomparison} and in \\tabref{tab:network-comparison}.\n\nWe observe that DeepLab v3+ starts with the lowest mIoU performance but quickly achieves 28.61\\% mIoU accuracy after only 80 iterations, already outperforming the final result of GoogLeNet, after which training begins to plateau.\nAfter 1000 iterations, it was able to achieve 30.83\\% mIoU accuracy.\nGoogLeNet is able to also train relatively quickly, achieving 22.05\\% mIoU accuracy after 80 iterations, after which performance also began to plateau achieving a final 25.08\\% mIoU accuracy.\nFCN16s was able to achieve 19.97\\% mIoU overall after 1000 iterations.\nWe believe this may be due to FCN16s not being designed to identify smaller structures and features, such as in the case of curbs and curb cuts.\n\nGiven these results, we chose to use DeepLab v3+ as our network.\n\n\\input{tables/experiments/network-comparison-table}\n\\input{figures/experiments/network-comparison-chart}\n\n\\section{Loss Function Evaluation}\\label{section:experiments-loss}\nOur custom loss function masked cross entropy (MCE) loss was evaluated against weighted cross entropy (WCE) loss.\nWe evaluated the two loss functions using the same network hyperparameters and a pretrained backbone.\nThe backbone is pretrained on the ImageNet database, published in 2009 by J. Deng et al~\\cite{imagenet}.\nTraining results, shown in \\figref{chart:experiments-losstraining}, show that both lost functions show similar results until the 40\\textsuperscript{th} iteration, after which the network using MCE loss is able to produce better results.\nValidation accuracy is plotted in \\figref{chart:experiments-lossvalidation}.\nWe observe the validation accuracy to be similar for the first 2370 iterations.\nAfter this point, MCE loss shows a clear advantage in validation accuracy compared to WCE loss.\nAfter 4740 iterations, a clear performance advantage can be seen, with a difference of 5.56 mIoU percentage points.\nAs such, we have chosen to implement our network using MCE loss as our loss function.\n\n\\input{figures/experiments/losscomparison}\n\n\\section{Hyperparameters} \\label{section:experiments-hyperparameters}\nHyperparameter tuning was done by using Bayesian Optimization with HyperBand.\nThe hyperparameters that were tuned were the learning rate; optimizer; momentum, if the optimizer chosen was stochastic gradient descent; epsilon, if the optimizer chosen was Adam; and the loss criterion.\n\nThe learning rate is optimized between the interval $\\left[1 \\times 10^{-5}, 1 \\times 10^{-2}\\right]$, varied on a logarithmic scale.\nThe optimizer is a categorical choice between stochastic gradient descent or Adam.\nThe momentum is optimized between the interval $\\left[0, 0.99\\right]$.\nThe epsilon value is optimized between the interval $\\left[1 \\times 10^{-2}, 1\\right]$.\nThe weight ratio for the loss weight determines the ratio of the weights between the curb and curb cut.\nThe loss criterion is a categorical choice between weighted cross entropy loss or masked cross entropy loss.\nFurther details of the hyperparameters optimized can be found in \\tabref{tab:hyperparameters}.\n\n\\input{tables/experiments/hyperparameters}\n\nThe hyperparameters are optimized according to the above parameters using a cluster of 4 GPUs over a budget of 4 iterations.\nThe resulting optimized values for the hyperparameters are in \\tabref{tab:hyperparameterresults}.\nMore detailed results of each run of the hyperparameter optimization can be found in Appendix section \\ref{appendix:hpoptimresults}.\n\n\\input{tables/experiments/hyperparameter-results}\n\n\\section{Implementation} \\label{section:experiments-trainingpipeline}\nThe training pipeline is a main script which calls the training loop with a set of parameters defined in either a JSON file or through command-line arguments.\nUsing a JSON file makes it simpler to change parameters as nothing is hard-coded and command-line arguments do not have to be memorized or meticulously typed out each time.\n\nA Graphical User Interface (GUI) is also available, made using the tkinter framework, which is capable of visualizing the ground truth segmentation, the network output, a live display of the current loss and mIoU accuracy, and other statistics.\nThis GUI can be seen in \\figref{fig:experiments-gui}.\n\nA Command Line Interface (CLI) is also available, made using the ncurses framework, which is capable of displaying various statistics during training.\nThe CLI also allows training remotely using secure shell (SSH), as the GUI would fail to start if invoked remotely through the command line.\nA screen capture of the CLI can be seen in \\figref{fig:experiments-cli}\n\n\\input{figures/experiments/ui}\n\nThe different components necessary to train the network are written in such a way as to be modular, with nearly everything being easily configurable.\nFor example, the network, optimizer, and loss criterion can easily be swapped by changing command-line arguments or parameters in the JSON file.\nThis makes running different experiments straightforward.\n\n\\section{Results}\\label{section:experiments-results}\nRunning our network with the tuned hyperparameters chosen by the hyperparameter search in Section \\ref{section:experiments-hyperparameters} for 30,336 iterations, we were able to achieve a mIoU accuracy of 50.188\\% on the validation dataset.\n\n\\input{tables/experiments/results}\n\nThe network is able to produce the segmentations seen in \\figref{fig:experiments-resultsmapillary}.\nWe also notice that the network is able to achieve very high IoU accuracy for the road class, as seen in \\tabref{tab:mapillary-results}.\nThis is due to the original purpose of DeepLab v3+ as a road segmentation network \\cite{deeplab}.\nThe IoU accuracy of curbs, curb cuts, and sidewalks are lower than of the road class.\nOne possible reason for this is that IoU is especially hard to fulfill when there are only a few pixels belonging to the class.\nCases where the class has only a few pixels and the borders do not match exactly would return a low IoU.\n\n\\input{figures/experiments/mapillary}\n\\input{figures/experiments/obelix}\n\nIn these results we can observe that the network is quite capable of identifying each of the traversability classes.\n\\figref{fig:mapresult-1} shows an example of how the network is able to identify each of the traversibility classes.\nThe network can also identify traversability classes, specifically curbs and curb cuts, which are in the distance and thus have a relatively small size, as can be observed in Figures \\ref{fig:mapresult-2} - \\ref{fig:mapresult-5}.\nIn these cases, the segmentation is significantly larger than the size of the curb itself, i.e. even though the intersection is significant, there is a significant area around the curb that is falsely identified as also being a part of the curb.\nFigure \\ref{fig:mapresult-5} shows a failure case where the road marking in the bottom right corner is mislabeled as a curb.\nFigures \\ref{fig:mapresult-4} and \\ref{fig:mapresult-5} also show failure cases where the road is labeled as the ignore class.\nFigure \\ref{fig:mapresult-6} shows another failure case where the entire road is mislabeled as sidewalk.\n\nWe also ran inference against a dataset gathered by the onboard cameras on the Obelix robot using the network.\nThe results of this experiment can be seen in \\figref{fig:experiments-resultsobelix}.\nFigures \\ref{fig:obresult-1} and \\ref{fig:obresult-2} show that the network is able to generalize to the Obelix dataset and is able to identify the different traversability classes in the images, despite never having been trained on them.\nFigure \\ref{fig:obresult-3} shows although curb cuts are correctly identified, as in the case of the curb cut across the street, they are also sometimes mislabeled, as in the case of the curb cut directly ahead of the robot.\nWe can observe in Figures \\ref{fig:obresult-4} and \\ref{fig:obresult-5} that the network seems unable to decide whether the asphalt sidewalk is a road or a sidewalk.\nThe same failure case can be seen in Figure \\ref{fig:obresult-6} where the left side of the sidewalk is mislabeled as road while the right side is labeled correctly as sidewalk.\n\nWe observe that the main failure cases of the network are falsely identifying certain road markings as curbs and identifying certain roads as sidewalks or vice versa.\nCertain road markings which are located near road edges are sometimes segmented as curbs, as can be seen in the bottom right corner of \\figref{fig:mapresult-5}.\nWe believe that this is due to the texture of the marking being colored similarly to some curbs as well as its shape which does resemble a curb.\nIn some cases, the sidewalk is identified as a road, as in \\figref{fig:obresult-5} or the entire road is identified as a sidewalk, as in \\figref{fig:mapresult-6}.\nWe believe that this may occur when sidewalks have an asphalt-like texture, as in the case in \\figref{fig:obresult-5}.\n", "meta": {"hexsha": "e54312de51bc4727964486c5fdbae1c23ebf3f99", "size": 14360, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/5-experiments.tex", "max_stars_repo_name": "yvan674/bachelor-thesis", "max_stars_repo_head_hexsha": "00121f35245c20ddf77bd5d0ca9467460849902c", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/5-experiments.tex", "max_issues_repo_name": "yvan674/bachelor-thesis", "max_issues_repo_head_hexsha": "00121f35245c20ddf77bd5d0ca9467460849902c", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/5-experiments.tex", "max_forks_repo_name": "yvan674/bachelor-thesis", "max_forks_repo_head_hexsha": "00121f35245c20ddf77bd5d0ca9467460849902c", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 89.75, "max_line_length": 335, "alphanum_fraction": 0.8059192201, "num_tokens": 3190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.32173693627775196}}
{"text": "% !TEX root=../report.tex\n\n\\section{Giving more choice}\n\n\\begin{grammar}\n  Pretasks\n    & p & ::=& \\ldots       & \\\\\n    &   &\\mid& e_1 \\Or e_2  & – task choosing \\\\\n    &   &\\mid& e_1 \\Xor e_2 & – user choosing \\\\\n  Tasks\n    & t & ::=& \\ldots       & \\\\\n    &   &\\mid& t_1 \\Or t_2  & – task choosing \\\\\n    &   &\\mid& t_1 \\Xor t_2 & – user choosing \\\\\n  Actions\n    & a & ::=& \\ldots       & \\\\\n    &   &\\mid& \\Pick r      & – pick route \\\\\n  Routes\n    & r & ::=& \\Left r      & – go left \\\\\n    &   &\\mid& \\Right r     & – go right \\\\\n    &   &\\mid& \\Here        & – stay here \\\\\n\\end{grammar}\n\n\\begin{equation*}\n  \\userule{T-Or} \\qquad \\userule{T-Xor}\n\\end{equation*}\n\n\\begin{equation*}\n  \\userule{E-Or} \\qquad \\userule{E-Xor}\n\\end{equation*}\n\n\\begin{equation*}\n  \\userule{S-OrLeft} \\qquad \\userule{S-OrRight} \\qquad \\userule{S-OrNone}\n\\end{equation*}\n\n\\begin{equation*}\n  \\userule{S-Xor}\n\\end{equation*}\n\n\\begin{equation*}\n  \\begin{array}{lcl}\n    \\Value(t_1 \\Or t_2) &=& \\left\\{\n      \\begin{array}{ll}\n        v_1  & \\when\\ \\Value(t_1) = v_1 \\\\\n        v_2  & \\when\\ \\Value(t_1) = \\bot \\lor \\Value(t_2) = v_2 \\\\\n        \\bot & \\otherwise\n      \\end{array}\n    \\right.\n  \\end{array}\n\\end{equation*}\n\n\\begin{equation*}\n  \\begin{array}{lcl}\n    \\Failing(t_1 \\Or t_2) &=& \\Failing(t_1) \\lor \\Failing(t_2)\n  \\end{array}\n\\end{equation*}\n\n\\begin{margintext}{Aside: Pairing in iTasks}\n  $\\Or$ is similar to \\type{-||-}\n  and $\\Xor$ does not exist in iTasks.\n\\end{margintext}\n\n\\begin{equation*}\n  \\userule{H-FirstOr} \\qquad \\userule{H-SecondOr}\n\\end{equation*}\n\n\\begin{equation*}\n  \\userule{H-PickLeft} \\qquad \\userule{H-PickRight} \\qquad \\userule{H-PickHere}\n\\end{equation*}\n\n\n\\subsection{Three principles of choosing}\n\n\n\\subsection{Intermezzo: alternative functor and its laws}\n\n\\begin{equation*}\n  \\begin{array}{rclr}\n    \\Fail \\Or t\n      &\\approxeq& t\n      & \\text{(left identity)} \\\\\n    t \\Or \\Fail\n      &\\approxeq& t\n      & \\text{(right identity)} \\\\\n    r \\Or\\ (s \\Or t)\n      &\\approxeq& (r \\Or s) \\Or t\n      & \\text{(associativity)} \\\\\n    & & & \\\\\n    \\Fail \\Then g\n      &\\approxeq& \\Fail\n      & \\text{(left absorption)} \\\\\n    \\Edit x \\Or t\n      &\\approxeq& \\Edit x\n      & \\text{(left catch)}\n  \\end{array}\n\\end{equation*}\n\n\n\n\\subsection{Example: a vending machine}\n\nLet us model a vending machine.\nIn a simple process algebra we can write\n\\begin{equation*}\n  ?\\text{2euro}; (!\\text{tea}\\ \\oplus\\ ?\\text{1euro}; !\\text{coffee}).\n\\end{equation*}\nWhich reads:\nusers should insert 2 Euros,\nafter which they need to make a choice between tea,\nor entering another Euro which results in coffee.\nSo $?\\text{2euro}$ and $?\\text{1euro}$ mean an input of respectively 2 and 1 Euro,\nand $!\\text{tea}$ and $!\\text{coffee}$ are the outputs.\nWe use $\\oplus$ as an external choice operation.\n\nWe can model this vending machine using tasks as follows.\n\\begin{equation*}\n  \\begin{array}{l}\n    \\Enter \\Euro \\Then \\lambda n.\n    \\IF n \\equiv 2.00 \\THEN \\\\\n     \\quad \\Edit \\str{tea}\n      \\Xor\n        \\Enter \\Euro \\Then \\lambda m.\n        \\IF m \\equiv 1.00 \\THEN\n          \\Edit \\str{coffee}\n        \\ELSE\n          \\Fail \\\\\n    \\ELSE \\Fail\n  \\end{array}\n\\end{equation*}\nWhere we use a new type $\\Euro$ to represent amounts of money.\n\nWe see that in the task world we reason with concrete \\emph{values} of a specified \\emph{type}.\nOnly when the user inserted exactly two euros,\nwe will step to the next task.\nIn all other cases,\nthe step will \\emph{fail} and we stay where we are.\nAfter the first step,\nusers need to make an \\emph{explicit} choice by selecting tea or selecting the option to enter more coins.\n\nThe task world explicitly captures that users can, for example, insert five euros:\nThe step will not be taken.\nAlso, it implicitly captures that the user can get his money back.\nThis can be implemented by a button on the vending machine which sends the \\emph{empty} event to the task.\nNext to an input field in a graphical user interface,\na coin insertion component is another way to present the concept of an editor to an end user.\n\n\n% \\begin{TASK}\n%   fill Euro >>= \\ n.\n%     if n == 2 then\n%         edit \"tea\"\n%       <?>\n%         fill Euro >>= \\ m.\n%         if m == 1 then\n%           edit \"coffee\"\n%         else\n%           fail\n%     else\n%       fail\n% \\end{TASK}\n", "meta": {"hexsha": "0b2b0880183f698f6fec8dd45a82b5ea1667cc0c", "size": 4290, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/report/choice.tex", "max_stars_repo_name": "mklinik/task-semantics", "max_stars_repo_head_hexsha": "e7b846338d5da59ed5d00aef81f9874cadbbdd9f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/report/choice.tex", "max_issues_repo_name": "mklinik/task-semantics", "max_issues_repo_head_hexsha": "e7b846338d5da59ed5d00aef81f9874cadbbdd9f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/report/choice.tex", "max_forks_repo_name": "mklinik/task-semantics", "max_forks_repo_head_hexsha": "e7b846338d5da59ed5d00aef81f9874cadbbdd9f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8125, "max_line_length": 106, "alphanum_fraction": 0.6083916084, "num_tokens": 1435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.32173693627775196}}
{"text": "\\documentclass[a4paper,10pt]{article}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{pifont}\n\\usepackage[utf8]{inputenc}\n\\usepackage[left=2.5cm,right=2.5cm,top=2.5cm,bottom=2.0cm]{geometry}\n\\usepackage{multirow}\n\\usepackage{geometry}\n\\usepackage{pdflscape}\n\\usepackage{xcolor}\n\\usepackage{listings}\n\\lstset{basicstyle=\\ttfamily,\n  showstringspaces=false,\n  commentstyle=\\color{red},\n  keywordstyle=\\color{blue}\n}\n\\usepackage{float}\n\\newcommand{\\xmark}{\\ding{55}}%\n\n\n\\title{Elements of Computational Biology\\\\ \\Large\nSubject 15: Distance phylogenetics: UPGMA and NJ}\n\\author{Agata Radys, Paweł Cejrowski, Łukasz Myśliński}\n\\date{\\today}\n\n\\begin{document}\n\\newgeometry{margin=1.8cm}\n\\maketitle\n\n\\section{Usage}\nProgram was developed in Java programming language without any external libraries. All sources are available on Github and compiled using \\texttt{Maven}.\n\\begin{lstlisting}[language=bash,caption={Building project}]\ngit clone git@github.com:MiSSLab/BioComp15.git\nmvn package\n\\end{lstlisting}\nCreated Java archive can be run using \\texttt{JRE}. Sample data can be found in directory \\texttt{resources/}.\n\\begin{lstlisting}[language=bash,caption={Running project using data1.matrix}]\njava -jar -Dfilename=\"resources/data1.matrix\" \\\n    target/distance-phylogenetics-jar-with-dependencies.jar\n\\end{lstlisting}\n\n\\section{Data formats}\n\\subsection{Input}\nApplication requires \\texttt{CSV} data format and quadratic matrix of distances.\n\n\\begin{lstlisting}[caption={Example data file content}]\na,b,c,d,e\n0,8,8,5,3\n8,0,3,8,8\n8,3,0,8,8\n5,8,8,0,5\n3,8,8,5,0\n\\end{lstlisting}\nLabels in header has to be lexicographically sorted, dense vector with every column matching \\texttt{\"[a-z]+\"}.\n\\newpage\n\\subsection{Output}\nResulting trees are printed in \\texttt{ASCII}-art to the \\texttt{STDOUT}.\n\\begin{lstlisting}[caption={UPGMA output}]\nUPGMA(resources/data1.matrix)\n[[8.0]]\n|-[[5.0]]\n|  |-[[3.0]]\n|  |  |---- [[a]]\n|  |  `---- [[e]]\n|  `---- [[d]]\n`-[[3.0a]]\n   |---- [[b]]\n   `---- [[c]]\n\n     a b c d e 8.0 5.0 3.0 3.0a\na   |0 0 0 0 0 0   0   1   0\nb   |0 0 0 0 0 0   0   0   1\nc   |0 0 0 0 0 0   0   0   1\nd   |0 0 0 0 0 0   1   0   0\ne   |0 0 0 0 0 0   0   1   0\n8.0 |0 0 0 0 0 0   1   0   1\n5.0 |0 0 0 1 0 1   0   1   0\n3.0 |1 0 0 0 1 0   1   0   0\n3.00|0 1 1 0 0 1   0   0   0\n\nUPGMA-canonical\n[[a]]\n`-[[3.0]]\n    |---- [[e]]\n    `-[[5.0]]\n        |---- [[d]]\n        `-[[8.0]]\n            `-[[3.0a]]\n                |---- [[b]]\n                `---- [[c]]\n\\end{lstlisting}\n\\newpage\nDespite the fact that NJ returns unrooted tree it is presented as a rooted one with particular node choosen as a root.\n\\begin{lstlisting}[caption={NJ output}]\nNJ(resources/data1.matrix)\n[[g]]\n|---- [1.5-<-[a]]\n|---- [1.5-<-[e]]\n`-[1.75-<-[h]]\n    |---- [1.0-<-[d]]\n    `-[4.0-<-[f]]\n        |---- [1.5-<-[b]]\n        `---- [1.5-<-[c]]\n\n   a b c d e g h f\na|0 0 0 0 0 1 0 0\nb|0 0 0 0 0 0 0 1\nc|0 0 0 0 0 0 0 1\nd|0 0 0 0 0 0 1 0\ne|0 0 0 0 0 1 0 0\ng|1 0 0 0 1 0 1 0\nh|0 0 0 1 0 1 0 1\nf|0 1 1 0 0 0 1 0\n\nNJ-canonical\n[[a]]\n`-[[g]]\n    |---- [[e]]\n    `-[[h]]\n        |---- [[d]]\n        `-[[f]]\n            |---- [[b]]\n            `---- [[c]]\n\\end{lstlisting}\n\\section{Algorithms}\n\n\\subsection{UPGMA (ang. Unweighted Pair Group Method with Arithmetic Mean)}\nData: ultrametric matrix \\textit{d} for set \\textit{L}.\n\\begin{lstlisting}[caption={UPGMA pseudocode}]\nclusters[|L|]\nwhile (clusters.length > 1):\n    calculate distances between clusters\n        (sum of distances between cluster members\n            divided by product of cluster cardinalities)\n    find the lowest distance\n    merge the closest clusters\n\\end{lstlisting}\n\n\\subsection{NJ}\nData: ultrametric matrix \\textit{d} for set \\textit{L}.\\\\ \\\\\nQ - matrix: $ Q(i,j) = (n-2)d(i,j) - \\sum_{k=1}^{n} d(i,k) - \\sum_{k=1}^{n} d(j,k)$ \\\\ \\\\\nDistance from the pair members to the new node: \\\\ \\\\\n$d'(f,u) = \\frac{1}{2}d(f,g) + \\frac{1}{2(n-2)}(\\sum_{k=1}^n d(f,k) - \\sum_{k=1}^n d(g,k))$ \\\\ \\\\\n$d(g,u) = d(f,g) - d'(f,u)$\n\n\\begin{lstlisting}[caption={NJ pseudocode}]\nclusters[|L|]\nwhile (number of clusters > 2):\n    calculate Q-matrix\n    find the lowest q-distance\n    merge the q-closest clusters\n    update distances\nmerge last 2 clusters\n\\end{lstlisting}\n\n\\subsection{Creating adjacency matrix}\nBoth rooted and unrooted trees created via UPGMA and NJ algorithms can be transformed to adjacency matrix. The algorithm for that is as follows:\n\\begin{lstlisting}[caption={Tree to adjacency matrix.}]\nfunction walk(Node rootNode):\n    int x = adjacencyMatrix.establishPosition(rootNode)\n    for (node : rootNode.getChildren ):\n        int y = adjacencyMatrix.establishPosition(node)\n        adjacencyMatrix[x][y] = 1;\n        adjacencyMatrix[y][x] = 1;\n        walk(node);\n\ninit adjacency matrix with 0;\nwalk(tree.rootNode)\n\\end{lstlisting}\n\n\\subsection{Creating canonical tree}\nTo compare trees, we need its canonical form. It will be a tree with the first node from input data as a root.\n\\begin{lstlisting}[caption={Tree to adjacency matrix.}]\nfunction toCanonicalTree:\n    List<Integer> visited = new ArrayList<>();\n    Node rootNode = createNodes(0, visited);\n    return new Tree(rootNode);\n\nfunction Node createNodes(int i, List<Integer> visited):\n    visited.add(i);\n    Node node = new Node(adjacencyMatrix.header[i]);\n    for (j = 0; j < adjacencyMatrix.header.length; j++):\n        if (visited.notContains(j) && adjacencyMatrix[i][j] = 1):\n            node.children.add(createNodes(j, visited));\n    return node;\n\\end{lstlisting}\n\\newpage\n\\subsection{Tree comparison}\nTrees in canonical form can be easily compared using the following algorithm.\n\\begin{lstlisting}[caption={Comparing trees.}]\nfunction equals(Node aNode, Node bNode):\n    if (aNode.children.size = bNode.children.size):\n        if (aNode.children.size == 0 && .children.size  == 0):\n            if (aNode.label = bNode.label):\n                return true\n            else:\n                return false\n        else:\n            comparisons = []\n            for (aChild : aNode.children):\n                comparisons2 = []\n                for (bChild : bNode.children):\n                    boolean equals = equals(aChild, bChild)\n                    comparisons2.add(equals)\n                comparisons.add(comparisons2.reduce(OR))\n            return comparisons.reduce(AND)\n    else:\n        return false;\n\\end{lstlisting}\nAn important assumption in this algorithm is that we can compare labels of leaf-nodes, because they are those given as an input so they have to be equal.\n\n\n\\end{document}\n\n", "meta": {"hexsha": "6307d9b9f973e4688c308099f9821d6057648b77", "size": 6512, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/report.tex", "max_stars_repo_name": "MiSSLab/BioComp15", "max_stars_repo_head_hexsha": "f0cafd8bdc55a1503bb5704564c3f49a7d5fac4d", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "report/report.tex", "max_issues_repo_name": "MiSSLab/BioComp15", "max_issues_repo_head_hexsha": "f0cafd8bdc55a1503bb5704564c3f49a7d5fac4d", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/report.tex", "max_forks_repo_name": "MiSSLab/BioComp15", "max_forks_repo_head_hexsha": "f0cafd8bdc55a1503bb5704564c3f49a7d5fac4d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.288372093, "max_line_length": 153, "alphanum_fraction": 0.6359029484, "num_tokens": 2141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.32173693627775196}}
{"text": "\\documentclass[a4paper]{article}\n\\usepackage{graphicx,subcaption}\n\\usepackage{amsmath,amsfonts}\n\\usepackage{qtree}\n\\title{Notes on Sequence Parsing}\n\\author{G.A. Jarrad}\n\\begin{document}\n\\maketitle\n\\numberwithin{equation}{section}\n\\numberwithin{figure}{section}\n\\numberwithin{table}{section}\n\\section{Introduction}\\label{sec:intro}\nThe purpose of {\\em sequence parsing} is to provide a hierarchically structured interpretation\nof a sequence of tokens, \n$\\vec{\\tau}=(\\tau_1,\\tau_2,...,\\tau_n)$.\nOur primary example is the English sentence $\\vec{\\tau}=({\\tt The},{\\tt cat},{\\tt sat},{\\tt on},{\\tt the},{\\tt mat})$,\nthe parse of which has a variety of representations, as shown by (but not restricted to) \nFigures~\\ref{fig:bracketing}--\\ref{fig:parse-tree}. It is important to note, however, that some\nnatural languages are not so strictly ordered, and so a general sequence parse need not necessarily follow the same\nordering as the token sequence.\n\\begin{figure}[h]\n\\centering\n\\{\n \\{{\\tt The\\, cat}\\}\\,\n \\{{\\tt sat}\\,\n  \\{{\\tt on}\\,\n   \\{{\\tt the\\, mat}\\}\n  \\}\n \\}\n\\}\n\\caption{The parse represented as a hierarchical partitioning of the tokens.}\n\\label{fig:bracketing}\n\\end{figure}\n\\begin{figure}[h]\n\\centering\n\\(\n\\underset{\\rho_5}{\\underline{\n   \\underset{\\rho_1}{\\underline{\\tt The\\;\\;cat}}\\;\\;\n   \\underset{\\rho_4}{\\underline{{\\tt sat}\\;\\;\n     \\underset{\\rho_3}{\\underline{{\\tt on}\\;\\;\n       \\underset{\\rho_2}{\\underline{\\tt the\\;\\;mat}}\n     }}\n  }}\n}}\n\\)\n\\caption{The parse represented as an ordered set of combination rules.}\n\\label{fig:nesting}\n\\end{figure}\n\\begin{figure}[h]\n\\centering\n\\Tree [.S [.NP [.DET The ] [.N cat ] ] [.VP [.V sat ] [.PP [.P on ] [.NP [.DET the ] [.N mat ] ] ] ] ]\n\\caption{The parse represented as a tree of nodes with  part-of-speech categories.}\n\\label{fig:parse-tree}\n\\end{figure}\n\nSequence parsing typically comprises two distinct stages: (i) {\\em token analysis}, discussed more fully in \nSection~\\ref{sec:token-analysis}; \nand (ii) {\\em structure analysis}, discussed in Section~\\ref{sec:structure-analysis}.\nBriefly, the purpose of token analysis is to deduce, for each token $\\tau_i$, the set $\\Lambda(\\tau_i)$ of {\\em leaf nodes}\nthat represent plausible interpretations of the token. For example, in natural language understanding the leaf nodes\nmight include categories such as part-of-speech, as shown in Figure~\\ref{fig:parse-tree}. \nThe purpose of structure analysis is then to deduce a set $\\Pi(\\vec{\\tau})$ of\nrules that recursively combine sequences of nodes into higher-order {\\em derived nodes}, \nuntil a single derived node spans the entire token sequence $\\vec{\\tau}$, \nagain as shown in Figure~\\ref{fig:parse-tree}.\n\nIn summary, $\\Pi(\\vec{\\tau})$ may be characterised as a parse tree graph with a \nset ${\\cal V}$ of nodes (both leaf and derived), and \na set ${\\cal R}$ of rules linking these nodes.\nEach leaf node represents known information about the corresponding \ntoken, including the position of that token in the token sequence.\nLikewise, each derived node represents a \nsequence of leaf and/or derived nodes, which includes knowledge of the positions of all corresponding tokens.\nIn general, therefore, every node $\\nu\\in{\\cal V}$ {\\em spans} a set of tokens. Specifically, we define\nthe span $\\sigma(\\nu)$ of node $\\nu$ to be the ordered set of\nindices of the underlying tokens. \nConsequently, each rule $\\rho\\in{\\cal R}$ then takes the form\n\\begin{eqnarray}\n\\nu_{i_1}\\;\\nu_{i_2}\\;\\cdots\\;\\nu_{i_m} & \\stackrel{\\rho}{\\rightarrow} & \\nu_*\\,,\n\\end{eqnarray}\nwhere the derived node $\\nu_*=\\delta(\\rho)$ combines the {\\em predecessor} nodes \n$\\vec{\\pi}(\\rho)=(\\nu_{i_1},\\ldots,\\nu_{i_m})$\nwith a resulting ordered span of\n\\begin{eqnarray}\n\\sigma(\\delta(\\rho))=\\bigcup_{\\nu\\in\\vec{\\pi}(\\rho)}\\sigma(\\nu)\\,.\n\\end{eqnarray}\n For example, if $\\sigma(\\nu_1)=\\{2,1\\}$ and $\\sigma(\\nu_2)=\\{3\\}$, then the rule\n$\\nu_1\\;\\nu_2\\rightarrow\\nu_3$ implies that $\\sigma(\\nu_3)=\\{2,1,3\\}$.\n\n\\end{document}\n", "meta": {"hexsha": "9ef9906e703b33473cc71b4c5890d04c3461426b", "size": 3950, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "random_thoughts/notes/sequence-parsing-notes.tex", "max_stars_repo_name": "gaj67/gaj-data-science", "max_stars_repo_head_hexsha": "aadcf6ee2cd00606563f213167c2eeeb42430c59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "random_thoughts/notes/sequence-parsing-notes.tex", "max_issues_repo_name": "gaj67/gaj-data-science", "max_issues_repo_head_hexsha": "aadcf6ee2cd00606563f213167c2eeeb42430c59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "random_thoughts/notes/sequence-parsing-notes.tex", "max_forks_repo_name": "gaj67/gaj-data-science", "max_forks_repo_head_hexsha": "aadcf6ee2cd00606563f213167c2eeeb42430c59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.4065934066, "max_line_length": 123, "alphanum_fraction": 0.7093670886, "num_tokens": 1174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.32173693627775196}}
{"text": "\\section{Uncertainty in PIV measurements}\n\\label{sec:piv_uncert}\n\n There are two major sources of measurement uncertainty associated with PIV. \n The first is \"particle lag\", or the ability of the seed particles to follow \n the \n flow, and is related to the inertia of the particle and the force exerted by \n the fluid upon the particle. The mineral oil droplets used in the present \n study are capable of following unsteady movements in the fluid flow on a scale \n much smaller than the PIV is capable of resolving, and so the uncertainty from \n this source is negligible. Sustained rotation similar to a rigid body \n inside the vortex core boundary has the effect of ejecting the relatively \n heavy particles away from the centerline. This particle ejection introduces a \n slight radial velocity bias in all measurements. This bias however is also \n negligible when compared to the second source of uncertainty: the process of \n extracting velocity vector information from the PIV images.\n \n Understanding the uncertainty in a PIV measurement can be accomplished with \n analysis of the PIV optical geometry \\cite{lawson1997b}. Alternatively, Monte \n Carlo techniques for evaluating PIV uncertainty can be used by creating \n artificial image pairs with simulated particle displacements, then passing \n them through the PIV processing chain. In PIV, as previously discussed, each \n camera \n utilizes its own set of coordinate transform equations which allow pixel \n coordinates to be mapped to the coordinates of the interrogation plane. \n Simulated particles are given random coordinates within the views of both \n cameras in the interrogation plane, then mapped onto the coordinate system of \n both cameras. The intensity of each pixel can be determined by summing the \n intensity function of every randomly generated particle as in \n \\cite{adeyinka2005,fouras2007}. This approach has been used successfully once \n before in the same wind tunnel facility with the same PIV system \n \\cite{doan2012}.\n \nThere are a number of factors that contribute to uncertainty in PIV \nmeasurements. Both bias and precision errors can be estimated by considering \ndetailed information about the optical geometry of the PIV setup. Monte-Carlo- \nbased error estimation techniques can be applied by creating artificially \nsimulated images with randomly distributed particles \\cite{adeyinka2005}. \nThe distribution of these particles can be modeled using a Gaussian intensity  \nprofile as described in Equation \n\\ref{eq:piv_gaussian_uncertainty} \\cite{raffel1998}.\n\n\\begin{equation}\n\tI(x,y) = I_0exp \\left( \\frac{-(x_{img} - x_p)^2 - (y_{img} - y_p)^2}\n\t{\\frac{1}{8}d_\\tau^2} \\right)\n\t\\label{eq:piv_gaussian_uncertainty}\n\\end{equation}\n\n\\noindent\nwhere $x_p$ and $y_p$ are the locations of the particle centroid, $d_\\tau$ is \nthe diameter of the particle, and $I_0$ is particle intensity. Particle \nintensity is directly related to the intensity of the light sheet, which is \nmodeled as a Gaussian distribution \\cite{PIVuncertAIAA}. This assumption allows \nus \nto express particle intensity as \\ref{eq:particle_intensity_gaus}\n\n\\begin{equation}\n\tI_0(z_p) = (q)exp\\left(- \\frac{z_p^2}{\\frac{1}{8}\\Delta Z_L^2}\\right)\n\t\\label{eq:particle_intensity_gaus}\n\\end{equation}\n\n\\noindent\nwhere $z_p$ is the particles position within the thickness of the light sheet, \n$q$ is the particle light scattering efficiency, and $\\Delta Z_L$ is the \nthickness of the light sheet.\n\nThese formulae were used to generate artificial image pairs for a single \ncamera. \nA sufficient number of particles were created with $x$, $y$ and $z$ coordinates \nto meet particle density parameters, these coordinates are then \nused to generate light intensities according to Equation \n\\ref{eq:particle_intensity_gaus}, which populate the image plane of the first \nimage $A$. Subsequently, a displacement image, $B$, was generated by shifting \nall the \nparticles in a predetermined direction in three dimensional space. It is worth \nnoting that for a single camera setup, particle movements in the $z$ direction \ndo not produce pixel displacements, but simply determine the intensity of the \nlight reflected from the particle. The known particle displacements can then be \ncompared against outputs calculated with PIV capture and processing software.\n\nTo translate this concept to stereo PIV, an additional step was required. \nInstead of directly distributing particles with known coordinates onto the \nimage \nplane of one camera, they were placed on a conceptual version of the \ninterrogation plane. The coordinate transforms obtained from PIV calibration \nwere used to map the displacements from the conceptual plane into the image \nplane of each camera. These coordinate transforms are unique to each camera, \nand depend upon the optical geometry of the PIV setup. Uncertainty is \ncalculated using the recommended AIAA calibration procedure \n\\cite{PIVuncertAIAA}. To determine the system bias, the mean difference between \nthe velocity standard established by the Monte Carlo simulation and the \nvelocity calculated by the PIV software are compared as follows\n\n\\begin{equation}\n\\overline{\\Delta U} = \\frac{1}{N} \\left(\\sum_{i=1}^N \\Delta U_i \\right),\n\\label{eq:Uerror}\n\\end{equation}\n\n\\begin{equation}\n\\overline{\\Delta V} = \\frac{1}{N} \\left(\\sum_{i=1}^N \\Delta V_i \\right),\n\\label{eq:Verror}\n\\end{equation}\n\n\\begin{equation}\n\\overline{\\Delta W} = \\frac{1}{N} \\left(\\sum_{i=1}^N \\Delta W_i \\right)\n\\label{eq:Werror}\n\\end{equation}\n\n\\noindent\nwhich is simply the average difference between the known velocity components \nand the measured velocity components $\\Delta U$, $\\Delta V$, and $\\Delta W$, \nfor a large number of simulations. This is referred to as the \\textit{bias}, \nand the three bias components are denoted as\n\n\\begin{equation}\n\\beta_{U} = \\overline{\\Delta U},\n\\label{eq:Ubias}\n\\end{equation}\n\\begin{equation}\n\\beta_{V} = \\overline{\\Delta V},\n\\label{eq:Vbias}\n\\end{equation}\n\\begin{equation}\n\\beta_{W} = \\overline{\\Delta W},\n\\label{eq:Wbias}\n\\end{equation}\n\nThe measurement precision is reported as the  \nstandard deviation, calculated as in \n\t\n\\begin{equation}\nS_{\\Delta U} = \\sqrt{\\frac{1}{N-1} \\left(\\sum_{i=1}^N (\\Delta U_i - \n\\overline{\\Delta U})^2 \\right)},\n\\label{eq:Usd}\n\\end{equation}\n\n\\begin{equation}\nS_{\\Delta V} = \\sqrt{\\frac{1}{N-1} \\left(\\sum_{i=1}^N (\\Delta V_i - \n\t\\overline{\\Delta V})^2 \\right)},\n\\label{eq:Vsd}\n\\end{equation}\n\n\\begin{equation}\nS_{\\Delta W} = \\sqrt{\\frac{1}{N-1} \\left(\\sum_{i=1}^N (\\Delta W_i - \n\t\\overline{\\Delta W})^2 \\right)},\n\\label{eq:Wsd}\n\\end{equation}\n\n\\noindent\nresulting in precision calculations given by \n\t\n\\begin{equation}\nP_{\\overline{U}} = \\frac{2 S_{\\Delta U}}{\\sqrt{N}},\n\\label{eq:Uprec}\n\\end{equation}\n\n\\begin{equation}\nP_{\\overline{V}} = \\frac{2 S_{\\Delta V}}{\\sqrt{N}},\n\\label{eq:Vprec}\n\\end{equation}\n\n\\begin{equation}\nP_{\\overline{W}} = \\frac{2 S_{\\Delta W}}{\\sqrt{N}}\n\\label{eq:Wprec}\n\\end{equation}\n\nTotal uncertainty for each component at the 95\\% confidence level was \ncalculated by combining the bias and precision via to obtain\n\n\\begin{equation}\nU_{\\overline{\\Delta U}} = \\sqrt{\\beta_{U}^2 + P_{\\overline{U}}^2}\n\\label{eq:Uuncert}\n\\end{equation}\n\\begin{equation}\nU_{\\overline{\\Delta V}} = \\sqrt{\\beta_{V}^2 + P_{\\overline{V}}^2}\n\\label{eq:Vuncert}\n\\end{equation}\n\\begin{equation}\nU_{\\overline{\\Delta W}} = \\sqrt{\\beta_{W}^2 + P_{\\overline{W}}^2}\n\\label{eq:Wuncert}\n\\end{equation}\n\n\nFor these experiments, uncertainty analysis was conducted after the \nexperimental data were taken. Vortices were characterized by velocities at key \nlocations that allow each vortex to be described by one of the common vortex \nmodels. Characterization velocities of particular interest include the maximum \ntangential velocity about the vortex core, the distance of this maximal \ntangential velocity region from the core axis, which defined the core radius, \nand the typical \naxial velocity distribution near the free stream velocity. Understanding the \nuncertainty of these measurements required a Monte Carlo approach from \nsynthetically created particle imagery as shown in Figures \\ref{fig:la} and \n\\ref{fig:lb}. Artificial pixel displacements were specified to approximate the \ntypical displacement associated with the velocities of greatest interest. \n\n\\vspace{32pt}\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=4in]{figs/artificial_images/la}\n\t\\caption{Left artificial image subset example, station 1, $t=0$.}\n\t\\label{fig:la}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=4in]{figs/artificial_images/lb}\n\t\\caption{Left artificial image subset example, station 1, $t=dt$.}\n\t\\label{fig:lb}\n\\end{figure}\n\n%ensures every page has \"Figure         Page\" at the top of it\n\\makeatletter\n\\addtocontents{lof}{%\n\t\\protect\\afterpage{\\protect\\hbox to \\linewidth%\n\t\t{\\noindent Figure \\hfill Page}\\par%\n\t\t\\protect\\vspace{12\\p@}}}\n\\makeatother\n\nTo add complexity, the time between frame captures, $dt$ was expected to have a \nsignificant impact on uncertainty. Since the range of velocities used in this \nstudy required the use of multiple values of $dt$, artificial images were \ngenerated for a scenario at each value of $dt$ with appropriate associated \nvelocities. \nWith the exception of measurements at station one, all tests were conducted \nwith a $dt$ value of 25, or 40 $\\mu s$. At station one $dt$ values of 35 \n$\\mu s$ were also used. During the experimentation period, great difficulty \nwas encountered in tuning PIV parameters to achieve well-resolved vector fields \nat station one. The uncertainty analysis demonstrated that the actual geometry \nof the viewing angles was also unfavorable at this station, and the quality of \nmeasurements taken this far upstream was poor. Hence, that data were entirely \ndisregarded.\n\nCreation of these artificial images by Monte Carlo was performed with custom \nsoftware written in Python\\texttrademark. This software parses the calibration \nfiles output \nfrom INSIGHT software and constructs the set of equations needed for all \ncoordinate transformations. In order to simulate as accurately as possible, \nartificial images were generated at the full resolution of the specific PIV \ncameras (1280 x 1024). Particles were only generated randomly at coordinates \nthat were within the field of view of both cameras, to eliminate wasted \ncomputation time generating particles which would not aid in the production of \na three-dimensional vector. An excess of 100,000 particles were simulated for \neach image set in order to ensure that the particle density was sufficient to \nresolve a vector in the majority of sectors, and to approximate the \nexperimental seed density as closely as possible. The most accurate way to \nensure that the intensities of each particle was represented accurately was to \nevaluate the intensity for every particle at every point in the full image \nspace of 1280 x 1024 pixels, and then add them together. Since this produces a \nthree-dimensional space in excess \nof five billion values for a set of stereo image pairs, $La, Lb, Ra$ and $Rb$ \nimages, computation time for uncertainty images was a limiting factor. At a \nminimum, one set of uncertainty images for each combination of viewing geometry \nand time step $dt$ was required. Therefore, simulated velocity values were \nchosen for each of the 14 cases to approximate the velocities of greatest \ninterest. \n\nTables \\ref{table:experiment_results_1} through \n\\ref{table:experiment_results_7} show a summary of results from each of the 70 \ntests conducted, including the maximum \nobserved azimuthal velocity, the average measured axial velocity, and the low \naxial velocity at the vortex core. At the three furthest positions downstream \nwhere the vortex appears to have stabilized, the typical value of maximum \ntangential velocity, $\\overline{v}_{\\theta,max}$ in component notation, ranges \nfrom 6.0 to 7.9 $m/s$ for each run with a $dt$ of $25 \\mu s$. This tangential \nvelocity could align with the $X$ or $Y$-axis, and \nit was desirable to simulate displacements in both directions at once to limit \nthe number of Monte Carlo simulations to be performed, so simulated velocities\n$\\overline{u}_{sim}$ and $\\overline{v}_{sim}$\nof $4.9 m/s$ was employed so that the in-plane magnitude would be equal \nto the the middle of this range. Likewise, a simulated $\\overline{u}_{sim}$ and \n$\\overline{v}_{sim}$  velocity of \n$3.3 m/s$ was used to create synthetic images for testing experiments with a \n$dt$ of $40 \\mu s$. In the axial direction, $Z$ , mean values of $19 m/s$ and \n$29 \nm/s$ were used for the high and low velocity experiments respectively. These \nconditions are summarized in Table \\ref{table:uncertainty_sim_table}.\n\n\\vspace{32pt}\n\\input{tables/uncertainty_sim_table}\n\nEven though many samples were taken at every vector location, the uncertainty \nin each individual measurement was of great importance for studying the \nunsteady component of the velocity, and thus turbulent phenomena. Uncertainty \nin the fluctuating component were best represented by using an $N$-value of one \nin precision Equations \\ref{eq:Uprec} through \\ref{eq:Wprec}. \nUncertainty in the stable component was lower, since this measurement is a \nresult of averaging many measurements, and was calculated by using an $N$-value \nof 200 in the precision Equations \\ref{eq:Uprec} through \\ref{eq:Wprec}.\n\n\\clearpage\n\\subsection{Uncertainty Analysis Results}\nThe Monte Carlo analysis was performed for each station employing two \nscenarios. Uncertainty in the measurements for $u, v$ and $w$ \ncomponents are tabulated in Tables \\ref{table:uncertainties_u} and \n\\ref{table:uncertainties_v}. For the $u$ velocity components in the $X$ \ndirection, bias is reported as $\\beta_u$, \nprecisions are reported for both single-sample measurements and with \nmeasurements comprised of 200 averages by $P_{u^\\prime}$ and $P_{\\bar{u}}$ \nrespectively. Total uncertainties are reported as $U_{u^\\prime}$ and \n$U_{\\bar{u}}$. \n\n\\vspace{32pt}\n\\input{tables/uncertainties_u}\n\\input{tables/uncertainties_v}\n\nUncertainties in \nthe $X$ and $Y$ direction were comparable in some cases, while in others $Y$ \nuncertainties were half as high as those in $X$. At all velocities, poor \nprecision in the individual measurements was the primary driver of total \nuncertainty, while high bias was the driver for uncertainties in the \nmeasurements comprised of time averages of 200 samples. Spectral analysis of \nthe turbulence over the observation time is subject to the very high \nuncertainties associated with that of individual measurements. Time averaged \nvelocities, and the derived Reynolds stresses are best characterized by the \nbetter precision offered by many samples. While 200 is nominally used as $N$, \neach grid point may have between 20 and 200 valid vectors making up the set, so \nsome areas where vectors were less frequently resolved successfully may be \ncharacterized with greater uncertainty.\n\nIn the axial or $Z$-direction, the PIV was found to exhibit an extreme bias \ntoward underestimating velocities based on the Monte Carlo simulation.  \nHowever, experimental data \nshowed that the average axial velocity was consistently a few percent above \nfree stream velocity measured in the wind tunnel using dynamic pressure \ninstrumentation, as expected, as shown in Tables \n\\ref{table:experiment_results_1} through \\ref{table:experiment_results_7}. \nTherefore, uncertainties in the $Z$ direction were overestimated by the \ntechnique. The presence of the bias is peculiar, and could not be explained \ndespite best efforts by the author. The mean component of the Reynolds \ndecomposition components are \nstrongly influenced by a high bias, but the fluctuating components are entirely \nsensitive to precision. The Reynolds stress and turbulence values which are of \ngreat importance in this study included contributions of velocity fluctuations \nin the axial direction, which are not impacted by any bias that does exist. \nExperimental data were examined for possible misrepresentation of measurement \nuncertainty in the $X$ and $Y$ direction, but no meaningful \ndiscrepancies were found. Histograms the distribution of measurements for each \nof the 14 cases were included in Appendix \\ref{appendix:uncertainty_histograms}.\n\n\n\\subsection{Bias from Uneven sampling}\n\nEvery grid location with at least 20 successfully resolved vectors was \nsubject to a Reynolds decomposition into average and fluctuating components. \nWith 200 total samples taken for each test, the results are actually made up of \nmany grid points with between 20 and 200 samples. Uncertainty is related to the \nnumber of samples making up a measurement, but visualizing the potential \nimpacts of uncertainty as it varies in two and three dimensional space is \nchallenging. Furthermore, the likelihood of successfully resolving a vector is \ndependent upon aspects of the interaction between tracer particles and the \nfluid flow. A very clear interdependence between areas of high turbulence, and \nthe number of successful vector calculations was observed as shown in Figures \n\\ref{fig:run_55_num_contour_nolab} and \\ref{fig:run_55_ctke_contour_nolab}. \n\n\\input{figs/run_55/run_55_num_contour_nolab}\n\\input{figs/run_55/run_55_ctke_contour_nolab}\n\nIt was assumed that, as long as the number of samples making up any given \nmeasurement remains above the threshold of 20, every vector in the field is \naccurately represented. A sampling technique could be employed by \nwhich a random selection of 20 different values is used at every location, to \nresult in a more statistically homogeneous vector field. However, \nthe uncertainty in a PIV measurement also depends significantly on the \nmagnitude of the velocity measured, thus the benefit of such a sampling scheme \nis arguable.", "meta": {"hexsha": "ffc784cddfce369f653d58678af9edffbb642adf", "size": 17756, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "texdocs/docs/experiment_results/piv_uncertainty.tex", "max_stars_repo_name": "Jwely/thesis-pivpr", "max_stars_repo_head_hexsha": "f07a95610cec2a275f9edb2c15cf0f2dfb99a967", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "texdocs/docs/experiment_results/piv_uncertainty.tex", "max_issues_repo_name": "Jwely/thesis-pivpr", "max_issues_repo_head_hexsha": "f07a95610cec2a275f9edb2c15cf0f2dfb99a967", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "texdocs/docs/experiment_results/piv_uncertainty.tex", "max_forks_repo_name": "Jwely/thesis-pivpr", "max_forks_repo_head_hexsha": "f07a95610cec2a275f9edb2c15cf0f2dfb99a967", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.5136612022, "max_line_length": 80, "alphanum_fraction": 0.7824960577, "num_tokens": 4370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.32173692846631297}}
{"text": "\\title{Improving the Solution Speed of the Continuum Stewart-Gough Inverse Kinematics Simulation}\n\\author{John Till}\n\\date{}\n\n\\documentclass[12pt]{article}\n\n\\usepackage[a4paper, margin=0.75in]{geometry}\n\\usepackage[colorlinks=true,urlcolor=blue]{hyperref}\n\\usepackage{amsmath,amssymb}\n\\usepackage{graphicx}\n\n\\usepackage{xcolor}\n\\definecolor{OffWhite}{rgb}{0.93,0.93,0.93}\n\\definecolor{QtCommentColor}{rgb}{0,0.5,0}\n\\definecolor{QtKeywordColor}{rgb}{0.5,0.5,0}\n\\definecolor{QtPurpleColor}{rgb}{0.5,0,0.5}\n\\definecolor{QtGlobal}{rgb}{0.808,0.361,0}\n\\definecolor{QtFunctionColor}{rgb}{0,0.404,0.486}\n\n\\usepackage[T1]{fontenc} %for upquotes in listings\n\\usepackage{textcomp} %for upquotes in listings\n\\usepackage{listings}\n\\lstset{\n\t\tlanguage=C++,\n\t\tescapeinside={!-}{-!},\n\t\tupquote=true,\n\t\t%\n\t\totherkeywords={Vector3d, DiagonalMatrix, VectorXd, Matrix3d, Map, MatrixXd, Vector6d, Vector2d,\n\t\t\t\t\t\t\t\t\tstd, clock_t, atomic, WORKER_STATE, CALCULATING_OBJFUNC, CALCULATING_JACOBIAN, RESTING, TERMINATED,\n\t\t\t\t\t\t\t\t\twaitOnWorkers, setWorkerState, integrateRod, setJacobianOfLeg,\n\t\t\t\t\t\t\t\t\tUnitX, pow, inverse, transpose, segment, data, UnitZ, cross, hat_postmultiply,\n\t\t\t\t\t\t\t\t\tZero, Identity, UnitY, cosseratRodOde, ode4, cols, row, main, shootingFunction,\n\t\t\t\t\t\t\t\t\tblock, linear_rotation_error, solveLevenbergMarquardt, plot, Ones, join,\n\t\t\t\t\t\t\t\t\tRy, initialize_StewartGough_pattern, clock, endl, jacobianFunction, workerFunction},\n    morekeywords=[2]{Vector3d, DiagonalMatrix, VectorXd, Matrix3d, Map, MatrixXd, Vector6d, Vector2d,\n\t\t                 std, clock_t, atomic, WORKER_STATE, CALCULATING_OBJFUNC, CALCULATING_JACOBIAN, RESTING, TERMINATED},\n\t\tmorekeywords=[3]{UnitX, UnitZ, pow, inverse, transpose, segment, data, cross, hat_postmultiply,\n\t\t                 Zero, Identity, UnitY, cosseratRodOde, ode4, cols, row, main, shootingFunction,\n\t\t\t\t\t\t\t\t\t\t block, linear_rotation_error, solveLevenbergMarquardt, plot, Ones, join,\n\t\t\t\t\t\t\t\t\t\t Ry, initialize_StewartGough_pattern, clock, endl, jacobianFunction,\n\t\t\t\t\t\t\t\t\t \t waitOnWorkers, setWorkerState, integrateRod, setJacobianOfLeg, workerFunction},\n    %\n\t\tframe = single,\n\t\trulecolor=\\color{black},\n    tabsize=4, % tab space width\n    showstringspaces=false, % don't mark spaces in strings\n\t\t%\n\t\tbasicstyle=\\footnotesize,%\\color{QtIdentifier},\n\t\tbackgroundcolor=\\color{OffWhite},\n    commentstyle=\\color{QtCommentColor}, % comment color\n    keywordstyle=\\color{QtKeywordColor}, % keyword color\n\t\tkeywordstyle=[2]{\\color{QtPurpleColor}},\n\t\tkeywordstyle=[3]{\\color{QtFunctionColor}},\n    stringstyle=\\color{QtCommentColor} % string color\n}\n\n\\begin{document}\n\n\\makeatletter\n\\renewcommand{\\@maketitle}{\n\\newpage\n\\null\n\\vskip 2em\n\\begin{center}\n{\\LARGE \\@title \\par}\n\\end{center}\n\\par\n} \\makeatother\n\n\\maketitle\n\n\\section{Setting up the Benchmark}\n\nEventually we want to use our inverse kinematics simulation to control a robot. We need to ensure we are solving the problem fast enough that the robot feels responsive. In this first part, we will setup a benchmark to time how quickly the model solves so that we can measure the effects of changes to the code.\n\nThe benchmark we use is from my paper \\href{https://ieeexplore.ieee.org/document/7139904}{``Efficient Computation of Multiple Coupled Cosserat Rod Models for Real-time Simulation and Control of Parallel Continuum Manipulators''}. The simulation starts with the end effector at $\\boldsymbol{p}_E = \\begin{bmatrix} 0 & 0.02 & 0.48 \\end{bmatrix}^T$. Over the course of 100 numerical solutions the robot moves to $\\boldsymbol{p}_E = \\begin{bmatrix} 0 & 0.12 & 0.58 \\end{bmatrix}^T$, and then returns to the initial position over the course of 100 more solves. The motion is repeated as long as the simulation runs.\n\nThe end effector position variable ``pE'' was previously declared as const, so our first change is to make it mutable (capable of changing state) by declaring it as static instead of const:\n\\begin{lstlisting}\nstatic Vector3d pE = 0.4*Vector3d::UnitZ();\n\\end{lstlisting}\nFor this scenario the end effector orientation remains flat, so we change the declaration:\n\\begin{lstlisting}\nconst Matrix3d RE = Matrix3d::Identity();\n\\end{lstlisting}\nWe also remove the code for plotting and outputting, and the associated variables ``p'', ``px'', and ``pz'' since this is not part of the benchmark. The end effector mass and the density of the rods are neglected. To match the robot from the paper, we also set the Young's modulus to $E=207$GPa, set $G$ using a Poisson’s ratio of 0.305, set the radius as $rad=0.0013/2$mm, and set the number of integration points to $N=40$.\n\nWe will use std::clock\\_t to measure the time elapsed during the simulation, so we include dependencies for ``stdio.h'' and ``ctime''. Then we update the main function to run the benchmark:\n\\begin{lstlisting}\npE = Vector3d(0, 0.02, 0.48);\nguess = solveLevenbergMarquardt<shootingFunction>(guess, 1e-6, 500, 1e-4, 0.5);\n\n//Benchmark speed test\nstd::!-\\textcolor{QtPurpleColor}{clock\\_t}-! start = std::clock();\nconst int M = 100;\nfor(int i = 0; i < M; i++){\n\t\tif(i%200 < 100){\n\t\t\t\tpE(1) += 0.001;\n\t\t\t\tpE(2) += 0.001;\n\t\t}else{\n\t\t\t\tpE(1) -= 0.001;\n\t\t\t\tpE(2) -= 0.001;\n\t\t}\n\t\tguess=solveLevenbergMarquardt<shootingFunction>(guess,1e-6,500,1e-4,0.5);\n}\ndouble duration = ( std::clock() - start ) / double(CLOCKS_PER_SEC);\nstd::cout << \"Time elasped: \" << duration << \"s\" << std::endl;\nstd::cout << \"Solution rate: \" << M/duration << \"Hz\" << std::endl;\n\\end{lstlisting}\nWe specify the total number of solutions as $M = 100$. The number of solutions is low right now since the code is slow, but we'll increase it as we go. The guess is updated with each solution since we get better behavior from the shooting method when the initial guess is close to the solution. We have specified additional solver options in the Levenberg-Marquardt algorithm. The second argument is the solver tolerance, which is the acceptable sum-of-squares of the objective function. The third argument is the maximum iterations to use before aborting and throwing an error. The fourth argument is the initial damping of the Levenberg-Marquardt algorithm, and the fifth argument is the adjustment in damping- in this case the damping is halved after a successful step.\n\nFinally we run the code and get the initial benchmark results. On my desktop the above code solves at 50 Hz. This is definitely on the low end of the computational efficiency we would want to teleoperate the robot.\n\n\\section{Code Optimizations}\n\nIn this section we'll change some of the functions and calculations to speed up the code while maintaining fundamentally the same mathematical approach.\n\nAlthough the diagonal stiffness matrix data structures probably have an efficient inverse calculation, we can still improve the solution speed by taking the inverse in the setup phase:\n\\begin{lstlisting}\nconst DiagonalMatrix<double, 3> Kse_inv =\n\t\tDiagonalMatrix<double, 3>(G*A,G*A,E*A).inverse();\nconst DiagonalMatrix<double, 3> Kbt_inv =\n\t\tDiagonalMatrix<double, 3>(E*I,E*I,G*J).inverse();\n\\end{lstlisting}\n\\begin{lstlisting}\nVector3d v = Kse_inv*R.transpose()*n + Vector3d::UnitZ();\nVector3d u = Kbt_inv*R.transpose()*m;\n\\end{lstlisting}\nThe calculation $\\boldsymbol{R}\\widehat{\\boldsymbol{u}}$ contains several unnecessary multiplications by zero. There is a routine to calculate this more efficiently in ``commonmath.h'' so that we can write:\n\\begin{lstlisting}\nMatrix3d R_s = hat_postmultiply(R,u);\n\\end{lstlisting}\nSimilarly transposing then multiplying wastes effort, so there is a function to do both:\n\\begin{lstlisting}\nVector3d v = Kse_inv*!-\\textcolor{QtFunctionColor}{transposeMultiply}-!(R,n) + Vector3d::UnitZ();\nVector3d u = Kbt_inv*!-\\textcolor{QtFunctionColor}{transposeMultiply}-!(R,m);\n\\end{lstlisting}\nAlso on this line, calling ``Vector3d::UnitZ()'' to increment one index is overkill, so we write:\n\\begin{lstlisting}\nVector3d v = Kse_inv*!-\\textcolor{QtFunctionColor}{transposeMultiply}-!(R,n); v(2) += 1;\n\\end{lstlisting}\n\nIf we run the program, we can see a noticeable improvement in the benchmark speed. However, we haven't addressed what is probably the slowest part of the ODE function- its function signature:\n\\begin{lstlisting}\nVectorXd cosseratRodOde(VectorXd y)\n\\end{lstlisting}\nThis has us allocating two dynamically sized vectors with each call of the ODE function. In this case it's worth using an output argument. That means we'll change the function signature to\n\\begin{lstlisting}\nvoid cosseratRodOde(VectorXd& y_s_out, VectorXd& y)\n\\end{lstlisting}\n\\emph{Output arguments} are often frowned upon, and for good reason since they make code harder to read and reason about, but there is enough of an improvement in the numerical integration ``hot loop'' to justify the use of one here.\n\n\\newpage\n\\noindent Our method of packing the state vector derivative is also slow, and it is faster to use maps:\n\\begin{lstlisting}\n//Refer to the state vector derivative by its components\nMap<Vector3d> p_s (&y_s_out[0]);\nMap<Matrix3d> R_s (&y_s_out[3]);\nMap<Vector3d> n_s (&y_s_out[12]);\nMap<Vector3d> m_s (&y_s_out[15]);\n\n//ODEs\np_s = R*v;\nR_s = hat_postmultiply(R,u);\nn_s = Vector3d::Zero();\nm_s = -p_s.cross(n);\n\\end{lstlisting}\nAssignments made to the map objects will automatically make changes to y\\_s\\_out. Similarly we use maps to unpack the state vector:\n\\begin{lstlisting}\n//Unpack state vector\nMatrix3d R = Map<Matrix3d>(&y[3]);\nMap<Vector3d> n(&y[12]);\nMap<Vector3d> m(&y[15]);\n\\end{lstlisting}\nIt turns out to be preferably to convert $\\boldsymbol{R}$ to a matrix, presumably because it is referenced several times.\n\nNow we have specialized some of the calculations to avoid unnecessary work, and we have made some reasonable changes to the program structure to favor speed over readability while keeping the same number of lines of code. On my desktop this revised code solves at 315 Hz.\n\n\\section{Reducing Number of Numerical Integration Calls}\n\nOne of the most computationally intensive tasks in the control program is numerically integrating the Cosserat ODEs. It turns out we are doing unnecessary integrations, and we can avoid unnecessary numerical integration calls by writing our own function to calculate the Jacobian.\n\nThe Levenberg-Marquardt solver calculates a \\emph{Jacobian matrix}, which is defined as\n\\begin{align*}\n\\boldsymbol{J} := \\frac{\\partial \\boldsymbol{f}(\\boldsymbol{y})}{\\partial \\boldsymbol{y}},\n\\end{align*}\nwhere $\\boldsymbol{y}$ is the guess and $\\boldsymbol{f}(\\boldsymbol{y})$ is the objective function. The solver approximates this partial derivative by a first-order finite difference, that is\n\\begin{align*}\n\\boldsymbol{J}_\\text{col i} \\approx \\frac{\\boldsymbol{f}(\\boldsymbol{y} + \\boldsymbol{e}_i \\Delta) - \\boldsymbol{f}(\\boldsymbol{y})}{\\Delta}\n\\end{align*}\nfor some small increment value $\\Delta$. We hold on to the value of $\\boldsymbol{f}(\\boldsymbol{y})$ after calling the objective function, so to calculate the Jacobian we are calling the objective function 36 times for the 36 columns of the Jacobian. Calling the objective function $\\boldsymbol{f}$ requires 6 rod integrations so that a total of 216 numerical integrations are required to find the Jacobian once.\n\nHowever, the distal variables in rod 1 aren't actually effected when we increment one of the proximal variables of rod 2. Each element of the guess only effects one rod integration, so with a Jacobian calculation specific to our problem, we could use only 36 rod integrations to obtain the Jacobian. Furthermore, the partial derivatives of the distal variables with respect to the arc lengths are already given by the Cosserat ODEs, so we only need 30 rod integrations. More detail is provided in \\href{https://ieeexplore.ieee.org/document/7139904}{``Efficient Computation of Multiple Coupled Cosserat Rod Models for Real-time Simulation and Control of Parallel Continuum Manipulators''}.\n\n\\newpage\nAlthough it is slightly labor intensive, we can provide our own function to calculate the Jacobian which is more efficient than brute force finite differencing. The first change we make is to store the distal rod variables globally instead of locally inside the objective function:\n\\begin{lstlisting}\n//Shooting method objective function\nstatic Vector3d pL_shot[6]; //Now a global variable\nstatic Matrix3d RL_shot[6];\nstatic Vector3d nL[6];\nstatic Vector3d mL[6];\nconst int N = 40;\nVectorXd shootingFunction(VectorXd guess){\n    VectorXd residual(36);\n\n    Vector3d EF = Vector3d::Zero();\n    Vector3d EM = Vector3d::Zero();\n\n    for(int i = 0; i < 6; i++){\n        Vector3d n0 = guess.segment<3>(5*i);\n        Vector2d m0xy = guess.segment<2>(5*i+3);\n        double L = guess(30+i);\n\n        VectorXd y0(18);\n        y0 << p0[i], 1, 0, 0, 0, 1, 0, 0, 0, 1, n0, m0xy, 0;\n\n        //Numerically integrate the Cosserat rod equations\n        MatrixXd Y = ode4<cosseratRodOde,N>(y0, L);\n\n        pL_shot[i] = Y.block<3,1>(0, N-1);\n        RL_shot[i] = Map<Matrix3d>(Y.block<9,1>(3, N-1).data());\n        nL[i] = Y.block<3,1>(12, N-1);\n        mL[i] = Y.block<3,1>(15, N-1);\n\n        residual.segment<3>(5*i) = pL_shot[i] - (pE + RE*r[i]);\n        residual.segment<2>(5*i+3) =\n                linear_rotation_error(RL_shot[i],RE).segment<2>(0);\n\n        EF -= nL[i];\n        EM -= (mL[i] + (RE*r[i]).cross(nL[i]));\n    }\n\\end{lstlisting}\nWe declare static, global variables for the distal values of $\\boldsymbol{p}_i(L)$, $\\boldsymbol{R}_i(L)$, $\\boldsymbol{n}_i(L)$, and $\\boldsymbol{m}_i(L)$, so we can access them throughout the ``main.cpp'' file. These values are stored in arrays so that we can hold the distal states of all the rods.\n\n\\clearpage \\noindent\nNow we can write the a function to calculate the Jacobian:\n\\begin{lstlisting}\nconst double incr = 1e-8;\nvoid jacobianFunction(MatrixXd& J_out, VectorXd& guess, VectorXd&){\n    for(int i = 0; i < 6; i++){\n        double L = guess(30+i);\n        for(int j = 0; j < 5; j++){\n            //A guessed variable is incremented for the finite difference\n            double temp = guess(5*i+j);\n            guess(5*i+j) += incr;\n            Vector3d n0 = Map<Vector3d>(&guess[5*i]);\n            Vector2d m0xy = Map<Vector2d>(&guess[5*i+3]);\n            guess(5*i+j) = temp;\n            VectorXd y0(18);\n            y0 << p0[i], 1, 0, 0, 0, 1, 0, 0, 0, 1, n0, m0xy, 0;\n\n            //Numerically integrate the Cosserat rod equations\n            VectorXd yf = !-\\textcolor{QtFunctionColor}{ode4\\_endpoint}-!<cosseratRodOde,N>(y0, L);\n            Vector3d pL_incr = yf.segment<3>(0);\n            Matrix3d RL_incr = Map<Matrix3d>(&yf(3));\n            Vector3d nL_incr = yf.segment<3>(12);\n            Vector3d mL_incr = yf.segment<3>(15);\n\n            //Jacobian Blocks are partial derivatives of obj. func. equations\n            J_out.block<3,1>(5*i, 5*i+j) = (pL_incr - pL_shot[i]) / incr;\n            J_out.block<2,1>(5*i+3, 5*i+j) =\n              linear_rotation_error((RL_incr-RL_shot[i])/incr, RE).segment<2>(0);\n            Vector3d nL_partial = (nL_incr - nL[i])/incr;\n            J_out.block<3,1>(30, 5*i+j) = -nL_partial;\n            J_out.block<3,1>(33, 5*i+j) = -( (mL_incr - mL[i]) / incr\n                                          +(RE*r[i]).cross(nL_partial) );\n        }\n\n        //Partial derivatives w.r.t. arc length do not require integration\n        VectorXd y_s(18), yL(18);\n        yL << pL_shot[i], Map<VectorXd>(RL_shot[i].data(), 9), nL[i], mL[i];\n        cosseratRodOde(y_s, yL);\n\n        J_out.block<3,1>(5*i, 30+i) = y_s.segment<3>(0);\n        J_out.block<2,1>(5*i+3, 30+i) =\n          linear_rotation_error( Map<Matrix3d>(&y_s[3]), RE).segment<2>(0);\n\n        J_out.block<3,1>(30, 30+i) = -y_s.segment<3>(12);\n        J_out.block<3,1>(33, 30+i) = -( y_s.segment<3>(15)\n                                     +(RE*r[i]).cross(y_s.segment<3>(12)) );\n    }\n}\n\\end{lstlisting}\nThe structure is similar to the objective function, but we find the partial derivatives of the error for each guessed variable. The solver routine with a user-supplied Jacobian function defined in ``convexoptimization.h'' is written so that the Jacobian is initialized to zeroes, so we only need to assign the non-zero elements. Confirming the partial derivative equations and structure of the Jacobian is left as an exercise. We update the solver invocation to include the Jacobian function:\n\\begin{lstlisting}\nguess=solveLevenbergMarquardt<shootingFunction,jacobianFunction>\n                             (guess, 1e-6, 500, 1e-4, 0.5);\n\\end{lstlisting}\n\nWe've gone from $216$ numerical integration calls required to calculate the Jacobian to only $30$ calls. There is one further step we can take to reduce the number of rod integrations. At the start of every solver call, we use the old solution as the initial guess. The result of the numerical integration does not change between solver calls, so we don't need to integrate on the first objective function evaluation. We add a variable to tell us if we should integrate:\n\\begin{lstlisting}\n//Shooting method objective function\nstatic bool integrate = true;\n\\end{lstlisting}\nWe only integrate if this variable is true, and we set it to true at the end of the objective function:\n\\begin{lstlisting}\nfor(int i = 0; i < 6; i++){\n        if(integrate){\n            Vector3d n0 = guess.segment<3>(5*i);\n            Vector2d m0xy = guess.segment<2>(5*i+3);\n            double L = guess(30+i);\n\n            VectorXd y0(18);\n            y0 << p0[i], 1, 0, 0, 0, 1, 0, 0, 0, 1, n0, m0xy, 0;\n\n            //Numerically integrate the Cosserat rod equations\n            MatrixXd Y = ode4<cosseratRodOde,N>(y0, L);\n\n            pL_shot[i] = Y.block<3,1>(0, N-1);\n            RL_shot[i] = Map<Matrix3d>(Y.block<9,1>(3, N-1).data());\n            nL[i] = Y.block<3,1>(12, N-1);\n            mL[i] = Y.block<3,1>(15, N-1);\n        }\n\t\t\t\t\n        ...\n}\nintegrate = true;\n\\end{lstlisting}\nFinally each pass through the benchmark loop we skip an integration\n\\begin{lstlisting}\nfor(int i = 0; i < M; i++){\n        integrate = false;\n\\end{lstlisting}\nThis results in another significant speedup. Now the inverse kinematics benchmark solves at about 1930Hz on my desktop. However, we have added 52 to lines to the program, and rather complicated lines at that.\n\n\n\\section{Multithreading}\n\nI should start this section with a disclaimer that we only achieve a 2x speedup with a significantly more complicated implementation, and the previous performance is likely adequate already. I've opted to keep this section since it may be educational, but it certainly isn't necessary.\n\nIntegrating the rods is an \\emph{embarrassingly parallel} problem, so we stand to gain from using multiple threads in parallel. We include dependencies on ``thread'' and ``atomic'' so that we can implement concurrency. We add a parameter for the number of threads to use:\n\\begin{lstlisting}\n//Independent Parameters\nconst int num_threads = 6;\n\\end{lstlisting}\nIn addition to the main thread of execution, we will have worker threads that follow the orders of the main thread. The number of workers will be the number of threads minus one. The computational effort of numerically integrating is low compared to the effort of starting up a thread, so we need to maintain an active pool of threads that run continuously by receiving commands. To facilitate giving these orders, we create an enum and an array:\n\\newpage\n\\begin{lstlisting}\nenum WORKER_STATE{\n    CALCULATING_OBJFUNC,\n    CALCULATING_JACOBIAN,\n    RESTING,\n    TERMINATED\n};\nstatic std::atomic<WORKER_STATE> worker_states[num_threads-1];\n\\end{lstlisting}\nThe array of worker states will indicate the current status of each worker, and also allow the main thread to tell the workers to perform a calculation.\n\nNext we create a couple of short functions for the master thread to use:\n\\begin{lstlisting}\nstatic void waitOnWorkers(){\n    for(int i = 0; i < num_threads-1; i++)\n        while( worker_states[i]!=RESTING ){ /* !-\\textcolor{QtCommentColor}{Execution is blocked}-! */ }\n}\n\nstatic void setWorkerState(WORKER_STATE command){\n    for(int i = 0; i < num_threads-1; i++) worker_states[i] = command;\n}\n\\end{lstlisting}\nThe first function allows the main thread to wait until workers are finished with their calculations, at which point they will change their state to ``RESTING''. The second function allows the main thread to send commands, for example by setting the workers state to ``CALCULATING\\_OBJFUNC''.\nNext we make the guess and the Jacobian global variables:\n\\begin{lstlisting}\nstatic MatrixXd J_global;\nstatic VectorXd guess_global;\n\\end{lstlisting}\nThis allows us to easily refactor the rod integration into a separate function from the objective function:\n\\begin{lstlisting}\nstatic void integrateRod(int i){\n    Vector3d n0 = Map<Vector3d>(&guess_global[5*i]);\n    Vector2d m0xy = Map<Vector2d>(&guess_global[5*i+3]);\n    double L = guess_global(30+i);\n\n    VectorXd y0(18);\n    y0 << p0[i], 1, 0, 0, 0, 1, 0, 0, 0, 1, n0, m0xy, 0;\n\n    //Numerically integrate the Cosserat rod equations\n    MatrixXd Y = ode4<cosseratRodOde,N>(y0, L);\n\n    pL_shot[i] = Y.block<3,1>(0, N-1);\n    RL_shot[i] = Map<Matrix3d>(Y.block<9,1>(3, N-1).data());\n    nL[i] = Y.block<3,1>(12, N-1);\n    mL[i] = Y.block<3,1>(15, N-1);\n}\n\\end{lstlisting}\nNow we can call the ``integrateRod'' function in parallel from the various threads.\n\\newpage \\noindent\nWith the new rod integration function, we rewrite the objective function to run in the main thread and outsource the integration calls to workers:\n\\begin{lstlisting}\nstatic VectorXd shootingFunction(VectorXd guess){\n    guess_global = guess;\n    VectorXd residual(36);\n\n    if(integrate){\n        setWorkerState(CALCULATING_OBJFUNC);\n        switch(num_threads){\n            case 1: //Do all the work\n                for(int i = 0; i < 6; i++) integrateRod(i);\n                break;\n            case 2: //Do half the work\n                for(int i = 3; i < 6; i++) integrateRod(i);\n                break;\n            case 3: //Do a third of the work\n                for(int i = 4; i < 6; i++) integrateRod(i);\n                break;\n            case 6: //Do a sixth of the work\n                integrateRod(5);\n                break;\n            default:\n                std::cout<<\"Invalid num_threads: must be divisor of 6\"<<std::endl;\n                !-\\textcolor{QtKeywordColor}{throw}-!(1);\n        }\n        waitOnWorkers();\n    }\n    integrate = true;\n\n    Vector3d EF = Vector3d::Zero();\n    Vector3d EM = Vector3d::Zero();\n    for(int i = 0; i < 6; i++){\n        residual.segment<3>(5*i) = pL_shot[i] - (pE + RE*r[i]);\n        residual.segment<2>(5*i+3) =\n           linear_rotation_error(RL_shot[i],RE).segment<2>(0);\n        EF -= nL[i];\n        EM -= (mL[i] + (RE*r[i]).cross(nL[i]));\n    }\n    residual.segment<3>(30) = EF;\n    residual.segment<3>(33) = EM;\n\n    return residual;\n}\n\\end{lstlisting}\nThe main thread commands the workers to start integrating, then performs its share along with the workers, then waits for all the integrations to finish before calculating the residual from the distal variables.\n\n\\clearpage \\noindent\nNow the workers can help to evaluate the objective function, but the Jacobian calculation is still single threaded.\nWe write a function to set the portions the Jacobian corresponding to each leg:\n\\begin{lstlisting}\nstatic void setJacobianOfLeg(int i){\n    for(int j = 0; j < 5; j++){\n        double temp = guess_global(5*i+j);\n        guess_global(5*i+j) += incr;\n        Vector3d n0 = Map<Vector3d>(&guess_global[5*i]);\n        Vector2d m0xy = Map<Vector2d>(&guess_global[5*i+3]);\n        guess_global(5*i+j) = temp;\n        double L = guess_global(30+i);\n        VectorXd y0(18);\n        y0 << p0[i], 1, 0, 0, 0, 1, 0, 0, 0, 1, n0, m0xy, 0;\n        //Numerically integrate the Cosserat rod equations\n        VectorXd yf = !-\\textcolor{QtFunctionColor}{ode4\\_endpoint}-!<cosseratRodOde,N>(y0, L);\n        Vector3d pL_incr = yf.segment<3>(0);\n        Matrix3d RL_incr = Map<Matrix3d>(&yf(3));\n        Vector3d nL_incr = yf.segment<3>(12);\n        Vector3d mL_incr = yf.segment<3>(15);\n\n        J_global.block<3,1>(5*i, 5*i+j) = (pL_incr - pL_shot[i]) / incr;\n        J_global.block<2,1>(5*i+3, 5*i+j) =\n           linear_rotation_error( (RL_incr - RL_shot[i])/incr, RE).segment<2>(0);\n        Vector3d nL_partial = (nL_incr - nL[i])/incr;\n        J_global.block<3,1>(30, 5*i+j) = -nL_partial;\n        J_global.block<3,1>(33, 5*i+j) =\n           -( (mL_incr - mL[i]) / incr  + (RE*r[i]).cross(nL_partial) );\n    }\n\n    VectorXd y_s(18), yL(18);\n    yL << pL_shot[i], Map<VectorXd>(RL_shot[i].data(), 9), nL[i], mL[i];\n    cosseratRodOde(y_s, yL);\n\n    J_global.block<3,1>(5*i, 30+i) = y_s.segment<3>(0);\n    J_global.block<2,1>(5*i+3, 30+i) =\n       linear_rotation_error( Map<Matrix3d>(&y_s[3]), RE).segment<2>(0);\n\n    J_global.block<3,1>(30, 30+i) = -y_s.segment<3>(12);\n    J_global.block<3,1>(33, 30+i) = -( y_s.segment<3>(15)\n                                      +(RE*r[i]).cross(y_s.segment<3>(12)));\n}\n\\end{lstlisting}\nThe main thread doles out work in the Jacobian calculation, exactly like the objective function:\n\\begin{lstlisting}\nstatic void jacobianFunction(MatrixXd& J_out, VectorXd&, VectorXd&){\n    setWorkerState(CALCULATING_JACOBIAN);\n    switch(num_threads){\n        case 1:\n            for(int i = 0; i < 6; i++) setJacobianOfLeg(i);\n            break;\n        case 2:\n            for(int i = 3; i < 6; i++) setJacobianOfLeg(i);\n            break;\n        case 3:\n            for(int i = 4; i < 6; i++) setJacobianOfLeg(i);\n            break;\n        case 6:\n            setJacobianOfLeg(5);\n    }\n    waitOnWorkers();\n    J_out = J_global;\n}\n\\end{lstlisting}\nFinally we write the function which the workers will run to respond to commands:\n\\begin{lstlisting}\nstatic void workerFunction(int id){\n    while( worker_states[id]!=TERMINATED ){\n        if( worker_states[id]==CALCULATING_OBJFUNC ){\n            switch(num_threads){\n                case 2:\n                    integrateRod(0);\n                    integrateRod(1);\n                    integrateRod(2);\n                    break;\n                case 3:\n                    integrateRod(2*id);\n                    integrateRod(2*id+1);\n                    break;\n                case 6:\n                    integrateRod(id);\n                    break;\n            }\n            worker_states[id] = RESTING;\n        }\n\n        if( worker_states[id]==CALCULATING_JACOBIAN ){\n            switch(num_threads){\n                case 2:\n                    setJacobianOfLeg(0);\n                    setJacobianOfLeg(1);\n                    setJacobianOfLeg(2);\n                    break;\n                case 3:\n                    setJacobianOfLeg(2*id);\n                    setJacobianOfLeg(2*id+1);\n                    break;\n                case 6:\n                    setJacobianOfLeg(id);\n                    break;\n            }\n            worker_states[id] = RESTING;\n        }\n    }\n}\n\\end{lstlisting}\nIt's just a continuous loop of checking for work, performing any tasks and reporting completion. Finally in the main script we can start our worker pool:\n\\begin{lstlisting}\nint main(int, char**){\n    std::!-\\textcolor{QtPurpleColor}{thread}-! workers[num_threads-1];\n    setWorkerState(RESTING);\n    for(int i = 0; i < num_threads-1; i++)\n        workers[i] = std::!-\\textcolor{QtPurpleColor}{thread}-!(workerFunction, i);\n\\end{lstlisting}\nAt the end of the main method, we shutdown the worker pool to make sure that the program terminates gracefully:\n\\begin{lstlisting}\nsetWorkerState(TERMINATED);\nfor(int i = 0; i < num_threads-1; i++) workers[i].join();\n\nreturn 0;\n\\end{lstlisting}\nWith two threads the model solves at around 3500 Hz, with three around 4600 Hz, and six is slightly slower than three. Of course by the time you reach six threads, you'll probably struggle to have enough cores to run them in parallel on a single PC.\n\n\\section{Over-optimized Custom Integration Routine}\n\nThe single-threaded integration code is probably good enough in most circumstances. However, I think it's interesting to see how much more performance we can gain if we're willing to over-optimize the numerical integration code. In the fifth example code folder, we write a function which integrates the Cosserat rod ODEs using a hard-coded fourth-order Runge-Kutta method, with calculations written on an element by element basis.\n\nThis code is an unmaintainable mess, but it achieves a performance of about 4200Hz on the benchmark. One interesting aspect is that the tradeoff between readability and performance is not a fundamental issue; the optimizing compiler helps us to ease the burden of this tradeoff, and an optimizing compiler could potentially achieve the performance we see here starting from readable code. However, the C++ standard is fairly conservative in terms of what code transformations result in equivalent code, and the compiler probably isn't allowed to make all the changes we've made. But that's a tangent from robotics.\n\n\\section{Conclusion}\n\nNow we can solve the continuum Stewart-Gough inverse kinematics at rates that are easily fast enough to control the robot. Some simple changes to the code in section 2 resulted in roughly a 6x speedup, and a user-supplied Jacobian calculation in section 3 resulted in another 6x speedup. The multithreading and over-optimized integration code in sections 4 and 5 resulted in roughly a 2x speedup each, which probably doesn't justify the added complexity, but hopefully it is useful to see these modifications.\n\n\\end{document}", "meta": {"hexsha": "e85002376fa6bde5f7a448e5bb35d16d91aa4020", "size": 29540, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "01_Statics/03_CSG_IK_Speedup/LaTeX/CSG_IK_Speedup.tex", "max_stars_repo_name": "ChengzhiSONG6/ContinuumRobotExamples", "max_stars_repo_head_hexsha": "2b872172551bab22a2f984ebde87324143c65a2c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 73, "max_stars_repo_stars_event_min_datetime": "2019-03-21T04:59:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T18:44:50.000Z", "max_issues_repo_path": "01_Statics/03_CSG_IK_Speedup/LaTeX/CSG_IK_Speedup.tex", "max_issues_repo_name": "ChengzhiSONG6/ContinuumRobotExamples", "max_issues_repo_head_hexsha": "2b872172551bab22a2f984ebde87324143c65a2c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2019-04-23T18:22:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T07:05:29.000Z", "max_forks_repo_path": "01_Statics/03_CSG_IK_Speedup/LaTeX/CSG_IK_Speedup.tex", "max_forks_repo_name": "ChengzhiSONG6/ContinuumRobotExamples", "max_forks_repo_head_hexsha": "2b872172551bab22a2f984ebde87324143c65a2c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28, "max_forks_repo_forks_event_min_datetime": "2019-04-02T04:01:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T06:59:02.000Z", "avg_line_length": 52.0987654321, "max_line_length": 772, "alphanum_fraction": 0.6896750169, "num_tokens": 8126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.32165324685182645}}
{"text": "\\section{Predicting point correspondences}\n\nBefore delving into methods for 3D reconstruction, it is first necessary to discuss techniques for identifying \\emph{point correspondences}. Point correspondences have a long history in computer vision for associating the same real-world location as it is represented by multiple camera views or on a 3D model surface. In a multi-image scenario, determining reliable correspondences between image pairs can be used to greatly reduce the ambiguity when reconstructing 3D scenes from 2D images. Even with only a single image available, correspondences can be predicted between the image and a representative 3D template mesh. This 3D-to-2D correspondence type is important for constraining the class of model fitting algorithms (discussed in depth later) which operate by aligning a 3D template mesh to a given 2D image. Of course, determining point correspondences is made more difficult in the presence of particular nuisance factors. In the case of animal imagery, we must associate points on a non-rigid object with independently moving parts (articulated), deal with frequent self-occlusion in which limbs overlap each other from the perspective of the camera, occlusion caused by environmental factors (e.g. trees, fences, humans etc.), varied and unknown backgrounds and a range of complex lighting conditions (including shadows). Throughout this section, the methods highlighted will be appraised against their suitability in this complex setting.\n\n% https://link.springer.com/article/10.1007/s13735-019-00183-w\n% https://arxiv.org/pdf/1603.09114.pdf\n\n\\subsection{Relating separate views of the same object/scene}\n\nThe first class of techniques focuses on classical approaches for determining corresponding image points taken of precisely the same (and almost always rigid) object. Early techniques focused on stereo~\\cite{corres-stereo} or optical flow~\\cite{corres-optflow} imagery, and matched image points based on finding regions with similar pixel intensities. Due to the adverse effects caused by changeable environmental factors (e.g. lighting) would have on the appearance of the real-world location when captured in separate images, attention moved towards designing schemes with improved robustness. Improvements were achieved when matching points based on local \\emph{mid-level features} such as edges and corners, which have greater invariance to colour changes caused by lighting effects. Typical pipeliens would first identify \\emph{interest points} (typically corners~\\cite{corner-moravec,corner-harris,corner-susan} or blobs~\\cite{sift}), from which local image patches could be compared according to either Squared Sum of Intensity Differences (SSD) or a cross-correlation (CC) scheme. Steady improvements were then made through the design of ever-improving feature descriptors, which encode local image information around points and aim for invariance against common transformations (e.g. viewpoint, rotation and scaling). Progress in this field arguably reached maturity with the advent of SIFT~\\cite{sift}, which encodes points according to local histograms of graident orientations and was later speed-up by SURF~\\cite{surf} and DAISY~\\cite{daisy}. There have been modern attempts to learn sophisticated feature representations using convolutional neural network architectures~\\cite{lift, matchnet}, which are shown to offer still further improvement.\n\nThe primary aim of these systems is to derive point correspondences between multiple views of the same object, usually as depicted in stereo images or between successive frames of a video. Unfortunately, by matching points based on local geometric features learnt from few image examples, these techniques do not readily extend to identifying correspondences between different instances of the same category. For example, matching SIFT features is likely to result in poor quality correspondences if tested on two dogs of different breeds due to the differing appearance and body geometry. For similar reasons, this class of techniques tend to deteriorate when tested on articulated objects since the object's structure can change and cause self-occlusion between views. The techniques are also known to suffer in scenarios with significant viewpoint changes (e.g. image of the front/back of an animal), since there are few correpsonding points available for matching. Finally, these techniques do not directly offer a method for identifying correspondences between an image and a representative 3D mesh. Although some work exists that extends some of the aforementioned feature descriptors (e.g. 3D-SIFT~\\cite{sift-3d}) to 3D, matching typically requires a photorealistic 3D scan of the 2D subject which we cannot assume as input for our problem.\n\n\\subsection{Predicting semantically-meaningful keypoints}\n\nThis section will explore an alternative class of methods for identifying point correspondences. So far, the approaches described do not detect correspondences with any semantic meaning; in other words, the returned points cannot truly be `named' and there is no guarantee the same points (or even the same number of points) will be identified in different test images. Instead, this section will focus on techniques which predict a set of keypoint locations which are specified in a pre-defined list (for example: nose, tail tip, toe). In general, data-driven machine learning algorithms are used in order to learn an association between image appearance information and semantic keypoint labels. The techniques fall into two general categories: the former set of \\emph{supervised techniques} rely on large image datasets manually annotated with keypoint locations, and the latter set of \\emph{unsupervised techniques} learn the association through other means. \n\n\\subsubsection{Supervised techniques}\n\nEarly work in the supervised prediction of landmarks began through the refinement of object detection methods to predict fine-grained object part labels and eventually progressed to keypoint locations. Perhaps the earliest techniques in this category made use of face part annotations (referred to as fiducial points) to align target faces to improve the face recongition accuracy. Human detection and pose estimation methods progressed from simple bounding box representations~\\cite{hog}, to object part prediction~\\cite{xxx,xxx}, poselets~\\cite{pose-kposelets} and subsequently 2D keypoint localization~\\cite{xxx,xxx}. Most commonly, methods aim to predict the location of important 2D human joints (such as the shoulders and wrists) in order to roughly approximate the subject's skeletal pose. For this reason, this task is commonly referred to as \\emph{2D human pose estimation}. The earliest techniques represented humans as a graph of parts~\\cite{human-rep-parts} and fit shape primitives (e.g. cylinders~\\cite{pose-hogg}) to detected edges. Tree-based graphical models known as pictorial structures~\\cite{pictorial-structures} were adopted and later made efficient~\\cite{pose-felzen}. Improvements were made with models capable of expressing complex relationships betwen joints, such as flexible part mixtures~\\cite{yang2013articulated,pose-johnson-mixtureparts}.\n\nBefore the popularization of modern deep learning architectures, various methods made use of features computed underneath predicted 2D landmark locations for fine-grained image classification tasks. For this reason, there are limited examples of keypoint datasets for animal categories such as dogs~\\cite{liu2012dog} and birds~\\cite{WelinderEtal2010}. \\Cref{chap:wldo} of this thesis will discuss StanfordExtra, a new dataset complete with annotated keypoint locations and segmentation masks for 12,000 dog images, encompassing 120 different breeds. At the time of publication, StanfordExtra is the largest annotated animal dataset of its kind. \n\n% https://arxiv.org/pdf/2012.13392.pdf\nRecent works in 2D pose estimation typically employ convolutional neural networks (CNNs) due to the complex feature represenations that can be learnt for joints that, when applied discriminatively, enable accurate recongition. An early example~\\cite{pose-embedding} learnt a pose embedding space with a CNN, and employed a nearest neighbour search algorithm to regress a pose. Later, deeper CNN models were used to regress facial point~\\cite{pose-face-earlycnn} and full body~\\cite{toshev2014deeppose} landmarks. More recent works improve robustness by regressing keypoint confidence maps~\\cite{joint-training} rather than 2D keypoints directly, enabling spatial priors to be applied to remove outliers~\\cite{cao2018openpose,Pfister15,Pfister14a,Charles16,joint-training,viewpoints-keypoints,pishchulin2016deepcut}. More recent methods are able to directly produce accurate confidence maps through a multi-stage pipeline~\\cite{wei2016cpm}. Of particular note are hourglass~\\cite{newell2016stacked} (relied upon in this thesis \\Cref{chap:cgas}) and multi-level~\\cite{sun2019deep,Xiao_2018_ECCV} structures, which combine global reasoning of full-body attributes and of fine-grained details. A related class of methods~\\cite{guler2018densepose, taylor2012vitruvian} focus on \\emph{dense} human pose estimation, which relate all 2D image pixels to a representative 3D surface of the human body. \n\nModern techniques in 2D human pose estimation demonstrate impressive accuracy on in-the-wild datasets, and deal with with parsing multiple subjects in challenging poses and in the presence of various occluders. However, part of what enables these achievements is the prevalance of large 2D keypoint datasets which can be used for training. Further discussion of available 2D keypoint datasets has been left for \\Cref{chap:3dmulti}, in which they are considered in-depth. Further discussion on the history and advances in 2D human pose estimation are comprehensively reviewed in~\\cite{2dpose-survey-1, 2dpose-survey-2}.\n\n\\subsubsection{Unsupervised learning}\n\nAs this thesis focuses on developing methods for animal reconstruction, it is useful to review techniques which operate without large 2D keypoint training datasets, which are scarce for animal subjects. Note that the methods in this section all describe approaches for determining point correspondences between different scenes. Under consideration are methods based on transfer learning, unsupervised learning and methods based on weak-supervision. \n\nEarly correspondence techniques include dense alignment methods including SIFT-flow~\\cite{siftflow} which employed optical flow methods to match image using SIFT features, and Bristow et al.~\\cite{Bristow2015DenseSC} who demonstrate a method for learning per-pixel semantic correspondences using geometric priors. They also show examples on various animal categories. Recent unsupervised techniques learn \\emph{category-specific} semantic priors by employing deep networks on large image collections.\n\nZhou et al.~\\cite{flowweb-efros} demonstrate a method for solving correspondences across an image collection by enforcing cycle consistency. Kanazawa et al.~\\cite{kanazawa2016warpnet} introduce WarpNet which predicts a dense 2D deformation field for bird images by learning from synthetic thin-plate spline warps generated on extracted silhouettes. Thewlis et al.~\\cite{thewlis-unsup-sphere} apply a similar trick, by ensuring a consistent mapping of warped facial images to a spherical coordinate frame and show results on human and cats. Jakab et al.~\\cite{unsup-articulated-objects} show they can estimate 2D human pose without training data data by leverging that between two frames of a simple video sequence, human body shape and texture remains reasonably similar but the pose (including global rotation) varies. They therefore construct an architecture that, given a pair of frames $(I, J)$ defines a network $f$ that given frame $I$ predicts a 2D location vector $y$. The system then combines this vector $y$ with the second frame $J$ and trains a secondary network $g$ to reconstruct the original frame $I$. Due to the limited capacity of $v$, the fact that apart from the pose, most of the information necessary for reconstruction is already available in $J$, the network eventually learns to encode 2D pose coordinates using $v$.\n\nTransfer learning describes a family of methods in which a machine learning model is first \\emph{pre-trained} to solve a related task (often making use of secondary dataset with may be larger in size) in order to accumulate knowledge which offers an advantage when solving the original task. DeepLabCut~\\cite{mathis2018deeplabcut}, LEAP~\\cite{leap-animal-pose} and DeepPoseKit~\\cite{graving2019deepposekit} exemplify such techniques, in which existing architectures~\\cite{pishchulin2016deepcut,newell2016stacked,densenet,mobilenetv2} are first trained to predict 2D human pose (making use of the large available datasets), and are then repurposed to predict 2D animal keypoints using few (generally 100s) training examples. Cao et al~\\cite{animalpose} demonstrate a cross-domain adaptation technique, which transfers knowledge gained from a modestly-sized animal dataset to unseen animal types. There are also dense estimation techniques, which extend DensePose~\\cite{guler2018densepose} described above to proximal animal classes~\\cite{DenseposeEvo20}, such as chimpanzees, by aligning the geometry between the animal category to humans for which data is plentiful.\n\n% Also under consideration are methods which learn from yet lesser sources of supervision. \n\n%https://www.robots.ox.ac.uk/~vedaldi/assets/pubs/jakab18unsupervised.pdf\n%https://people.csail.mit.edu/celiu/SIFTflow/SIFTflow.pdf\n%https://people.eecs.berkeley.edu/~tinghuiz/papers/cvpr15_flow.pdf\n%https://www.robots.ox.ac.uk/~vedaldi/assets/pubs/thewlis18modelling.pdf\n%https://www.robots.ox.ac.uk/~vedaldi/assets/pubs/thewlis17dense.pdf\n%https://www.robots.ox.ac.uk/~vedaldi/assets/pubs/thewlis16fully-trainable.pdf\n\n% https://reader.elsevier.com/reader/sd/pii/S0959438819301151?token=7A13D081FA0EE09BD23EDE5D517D499C7678CD59082C5B225CE01EC8063089BDC30D740FA31FFA6330F7FF6D2FEF2D89\n% DeepLabCut: ResNet\n% https://www.nature.com/articles/s41592-018-0234-5 (LEAP, StackedHourglass, recently sped up with MobileNet2)\n% https://github.com/jgraving/DeepPoseKit\n% https://elifesciences.org/articles/47994\n\n% 3D DeepLabCut: https://www.nature.com/articles/s41596-019-0176-0\n% AniPose: https://anipose.readthedocs.io/en/latest/\n% DeepFly3D: https://elifesciences.org/articles/48571\n\n\n% TODO: Find out a bit more about sun2019deep, Xiao 2018 etc.", "meta": {"hexsha": "080c68e2d5c913f6de8ae5e397a3d920e04db3af", "size": 14547, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapter3/1_point-corres.tex", "max_stars_repo_name": "benjiebob/phd-thesis-template", "max_stars_repo_head_hexsha": "2fd86bb807b830c06944d9c59962939d9a95ca7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter3/1_point-corres.tex", "max_issues_repo_name": "benjiebob/phd-thesis-template", "max_issues_repo_head_hexsha": "2fd86bb807b830c06944d9c59962939d9a95ca7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter3/1_point-corres.tex", "max_forks_repo_name": "benjiebob/phd-thesis-template", "max_forks_repo_head_hexsha": "2fd86bb807b830c06944d9c59962939d9a95ca7a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 246.5593220339, "max_line_length": 1758, "alphanum_fraction": 0.8220939025, "num_tokens": 3259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.63341024983754, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.32165323982355787}}
{"text": "\n% \\section{Types of analysis}\n% \\section{Viewing analysis results}\n% \\section{Static analysis}\n% \\section{Modal analysis}\n% \\section{Steady-state analysis}\n% \\section{Transient analysis}\n\n\\section{Types of analysis}\n\nSUGAR supports three basic styles of analysis:\n\\begin{description}\n\\item[Static analysis]:\n  In static analysis, we find the equilibrium state of a device.\nStatic analysis is sometimes called DC analysis by analogy to\nthe equilibrium analysis for direct current circuits.\n\n\\item[Linearized analysis]:\n  A linearized approximation to a system near equilibrium can\nprovide valuable information about the stability of the system\nand the nature of small oscillations about equilibrium.  SUGAR\nprovides two flavors of linearized analysis:\n\\begin{itemize}\n\\item In \\emph{modal analysis}, the characteristic modes of the\n      system (and their corresponding frequencies) are determined.\n      SUGAR can display the shapes of the displacements corresponding\n      to various modes.\n\\item In \\emph{steady-state analysis}, SUGAR computes the frequency \n      response of a user-specified variable when another user-specified\n      variable is sinusoidally excited.  The output of steady\n      state analysis is Bode plots.\n\\end{itemize}\n\n\\item[Transient analysis]:\n  In transient analysis (or dynamic analysis), the motion of the system\nis integrated forward in time.  Transient analysis in SUGAR is still\nsomewhat unreliable; we hope to have better support for it soon.\n\n\\end{description}\n\n\n%\\section{Viewing analysis results}\n%\n%All the analyses except steady state analysis result in one or more\n%\\emph{displacement}, which represent how much the device is displaced\n%from its original state as described in the netlist.  In static analysis,\n%the displacement represents the equilibrium position; in modal analysis,\n%displacements represent the shapes of the fundamental vibrating modes; \n%and in transient analysis, the displacements represent snapshots of the \n%device in time.\n\n\n\\section{Static analysis}\n\nIn static analysis, we attempt to find an equilibrium state for a MEMS\ndevice.  In the most general case, the equilibrium may not be unique;\nin this case, SUGAR will usually find the equilibrium position closest\nto where it starts looking (which, by default, is the undisplaced position).\n\nThe equilibrium state is characterized by a collection of force and moment\nbalance equations (and their electrical and thermal analogues):\n\\[\n  F(x) = 0\n\\]\nwhere $x$ is a vector of displacements from the original positions\n(and voltages, temperatures, etc) of the device.\nWe solve these equations using a standard Newton-Raphson\niteration.  For linear problems, a Newton-Raphson iteration will converge\nin one steps; for nonlinear problems, the iteration may never converge.\nCurrently, SUGAR assumes the iteration has converged when the size of the\nchange between iterations is sufficently small in an appropriately scaled\nnorm.  If convergence has not set in after 40 iterations, the routine\nexits with a diagnostic message.\n\nThe function to perform static analysis is \\texttt{cho\\_dc}:\n\\begin{center}\n\\begin{verbatim}\nres = cho_dc(net, q0, is_sp)\n\\end{verbatim}\n\\end{center}\nThe first argument, \\texttt{net}, is the netlist structure\nreturned from \\texttt{cho\\_load}.  The other arguments are optional.\nThe starting value for the iteration is given by \\texttt{q0};\nby default, the iteration starts at the undisplaced position \n($\\mathtt{q0} = 0$).  The flag \\texttt{is\\_sp} tells the routine\nwhether it should use sparse solvers or not; by default, the flag is\ntrue (sparse solvers are used).  The function returns a vector\nof displacements to reach the computed equilibrium (\\texttt{res.q}),\nand a flag that indicates whether the iteration converged \n(\\texttt{res.converged}).\n\nIn some cases, it is possible to find tricky equilibrium positions\nby approaching them step-by-step.  For example, suppose we wanted\nto determine the equilibrium position of a device near a pull-in\nvoltage.  As we approach the critical voltage, it becomes more\ndifficult to find the equilibrium position, and past the critical\nvoltage, no equilibrium exists.  If the commands\n\\begin{verbatim}\n  params.V = Vfinal;\n  net = cho_load('device.net', params);\n  q = cho_dc(net)\n\\end{verbatim}\nfail, we could try\n\\begin{verbatim}\n  q = [];\n  for V = 0:.5:Vfinal\n    params.V = V\n    net = cho_load('device.net', params);\n    q = cho_dc(net, q);\n  end\n\\end{verbatim}\nEven if we were still unable to find the equilibrium position, we might\nget useful information from seeing how nearly we were able to approach\nthe final voltage, and what the equilibrium was at the last point\nwhere we were able to find it.\n\nThere are two ways to view the results of a static analysis:\n\\begin{enumerate}\n\n\\item \nWe can view individual components of the displacement vector using\nthe command \\texttt{cho\\_dq\\_view}:\n\\begin{verbatim}\n% Find displacement of the y coordinate at node 'tip'\ntipy = cho_dq_view(q, net, 'tip', 'y');\n\\end{verbatim}\nAlternately, we could look up the index of the tip $y$ coordinate,\nand then look at the corresponding entry of the \\texttt{q} vector:\n\\begin{verbatim}\n% Find displacement of the y coordinate at node 'tip'\ntipy_index = lookup_coord(net, 'tip', 'y');\ntipy = q(tipy_index);\n\\end{verbatim}\n\n\\item\nWe can display the shape of the displaced structure using the\n\\texttt{cho\\_display} routine:\n\\begin{verbatim}\n% Display the undisplaced structure in figure 1,\n% and the displaced structure in figure 2.\nq = cho_dc(net);\nfigure(1); cho_display(net);\nfigure(2); cho_display(net, q);\n\\end{verbatim}\n\n\\end{enumerate}\n\n\n\\section{Steady-state and Modal Analysis}\n\nWe determine system behavior near equilibrium by analyzing the linearized\nsystem.  In modal analysis, we find the resonant behavior of the structure,\nassuming no damping, by solving the eigenproblem\n\\[\n  \\det(\\lambda^2 M - K) = 0\n\\]\nThe eigenvalues give the resonant frequencies, and the corresponding\neigenvectors give the resonant modes.  The routine \\verb|cho_mode| returns\nselected frequencies and mode shapes for a structure, along with the\noperating point at which linearization took place.  Mode shapes can\nbe viewed graphically using the \\verb|cho_modeshape| commands.  For small\nproblems, the default dense solvers are adequate; for larger problems,\nusers should select the number of modes they want, and those modes\nwill be computed using a less expensive iterative method.\n\nTo use the steady-state analysis routine, a user specifies a single\ninput degree of freedom and a single output degree of freedom,\nusually by naming a nodal variable.  SUGAR then draws a Bode plot\nillustrating the amplitude gain and phase shift between a harmonic\nexcitation at the input and a measured harmonic at the output.  Note\nthat, unlike the modal analysis routine, the steady state routine\ndoes not discard damping terms.\n\n%To determine the steady-state response, SUGAR first linearizes the system of\n%ordinary differential equation at the point of static equilibrium. The second\n%order system of ODEs is then converted into first order form given by  \n%\\begin{eqnarray}\n%  \\dot{x} & = & Ax + Bu \\\\\n%  y       & = & Cx + Du\n%\\end{eqnarray}\n%where $x$ is the system dynamic state variable, $u$ is the sinusoidal external\n%excitation, and $y$ is the system dynamic response. $A$, $B$, $C$, and $D$ are\n%the system, input coupling, output, and feed forward matrices respectively [1].\n%The solution of equation provides Bode plots as well as modal analysis.  \n\n\n\\section{Transient Analysis}\n\n\\emph{Note: Note yet in SUGAR 3.0}\n\n%The transient solver simulates the dynamic response of a MEMS device.\n%The device model may contain nonlinear elements, non-harmonic excitations,\n%and other features which would make linearized analysis suspect.\n\n%This solver calculates the transient response of a MEMS device, which may\n%contain nonlinear elements and excitations that are functions of time t and\n%state vector q. Several ODE solvers are available, whereby speed may be traded\n%for accuracy and long-term stability. These numerical methods include an\n%implicit second order Rosenbrock solver for stiff problems where low accuracy\n%is acceptable, an explicit Runge-Kutta 4th-5th order solver for non-stiff\n%systems, an implicit multi-step integration method of varying order for stiff\n%problems requiring higher accuracy, and a simple explicit Euler algorithm. The\n%transient solvers require the system ODEs to be in first order form. We do this\n%in the standardized way [2] by introducing a new state vector $Q$ where \n%\\[\n%  \\dot{Q} = \n%    \\frac{d}{dt} \n%      \\left( \n%        \\begin{array}{l} \n%          x \\\\ \n%          \\dot{x} \n%        \\end{array} \n%      \\right) = f(t,x)\n%\\]\n\n\n%\\section{Future analysis routines}\n%\n%In the future, we plan to also support \\emph{sensitivity analysis}.\n%Sensitivity analysis is not an independent style of analysis as much\n%as it is an extension to the forms of analysis listed above.\n%For example, a static sensitivity analysis might tell how the\n%equilibrium position would change due to variations from the nominal\n%material properties, layer thicknesses, etc.  Similarly, sensitivity\n%analysis used with the linearized analysis routines might tell how the\n%fundamental frequencies of the device would change if the device\n%properties were perturbed, and sensitivity analysis of transient results\n%would tell how the dynamic response would be affected by perturbing\n%device properties.  Some forms of sensitivity analysis were supported\n%in SUGAR 1.01, but that code has not yet been integrated into SUGAR 2.0.\n%\n\n%\\section{Sensitivity Analysis}\n\n%The predicted performance of MEMS is subject to process variations that occur\n%during the fabrication stage. Small variations in geometry may lead to\n%performance, which is substantially different from the ideal. SUGAR models this\n%effect by perturbing the system stiffness matrix K. \n%For static analysis \n%\\[\n%  F = [K(g) + \\Delta K(d)] x\n%\\]\n%where $g$ contains the ideal layout geometry and process file parameters. $d$\n%is the variation in $g$ given by Gaussian, uniform, or uniform distribution of\n%corners. The perturbation in stiffness, $\\Delta K(d)$, is determined by both\n%probabilistic and deterministic techniques. \n\n%A Monte-Carlo algorithm [3] evaluates the most likely outcome of equation\n%(3.5) by drawing many samples from a random distribution of geometric\n%variables.  Given the bounds on the geometric variables, an Ellipsoidal\n%Calculus technique [4] is used to find the extreme bounds on performance\n%parameters, i.e. the worst-case scenario. \n\n%  References \n% \n% [1]  Norman S.Nise, \"Control System engineering,\"  The Benjamin/Cummings \n%      Publishing, Inc, CA (1991) \n% [2]  S. Sastry, \"Nonlinear Systems Analysis, Stabil ity, and Control,\" Springer (1999) \n% [3]   D.J.C MacKay, \"Introduction to Monte Car lo Methods,\" M. I. Jordan, (1999) \n% [4]  G. Calafiore, L. El Ghaoui, \"Confidence ellipsoids for uncertain linear equations \n%      with structure,\" In Proceedings of the IEEE CDC , (1999) \n", "meta": {"hexsha": "dc48dc1cae78c07cbc8e1687f453f922dce02bd4", "size": 11062, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "sugar31/manual/analyze.tex", "max_stars_repo_name": "davidgarmire/sugar", "max_stars_repo_head_hexsha": "699534852cb37fd2225a8b4b0072ebca96504d23", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sugar31/manual/analyze.tex", "max_issues_repo_name": "davidgarmire/sugar", "max_issues_repo_head_hexsha": "699534852cb37fd2225a8b4b0072ebca96504d23", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sugar31/manual/analyze.tex", "max_forks_repo_name": "davidgarmire/sugar", "max_forks_repo_head_hexsha": "699534852cb37fd2225a8b4b0072ebca96504d23", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.2213740458, "max_line_length": 89, "alphanum_fraction": 0.7682155126, "num_tokens": 2667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804478040617, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3214696362412742}}
{"text": "% latexmk -pvc -pdf\n\\documentclass[9pt, a4paper]{article}\n\\usepackage[margin=0.65in]{geometry}\n\\usepackage{graphicx}\n\\usepackage{caption}\n\\usepackage{amsmath,amsthm,amsfonts,amssymb}\n\\usepackage{blindtext}\n\\usepackage[english]{babel}\n\\newenvironment{Figure}\n    {\\par\\medskip\\noindent\\minipage{\\linewidth}}\n    {\\endminipage\\par\\medskip}\n\n\\title{Simulating phase contrast imaging for materials with variable density}\n\\author{Ana C. Fabela Hinojosa \\\\\n\\small{Supervisors: Assoc. Prof. Marcus Kitchen}}\n\\small{\\date{\\today,  \\\\Due date: Friday 23\\textsuperscript{th} September, 2021}}\n\n\\begin{document}\n\\maketitle\n\\section{Current objective}\n\nIn this project, I study the theoretical perspective of coherent X-ray imaging. Using simulations, I aim to determine whether a density difference alone can give phase contrast and, if so, whether it is likely to be detected in real experiments. I created several simulations of cylinder-shaped sample materials and subjected these samples to X-ray wave-fields of different energies. In some of my simulations, I use a single cylinder made of a homogeneous material. In others I use two embedded concentric cylinder-shaped samples of materials with either an equal chemical composition and different densities or, different chemical compositions, and densities. \nWith these simulations I demonstrate the importance of material density in phase contrast imaging and by 1) showing how distinctly, phase contrast arises between material boundaries designed to mimic the grey and white matter of the brain and 2) whether the observed phase contrast is density-dependent. The eventual aim is to verify if successful phase retrieval is possible for such samples given variable sample material densities.\n\n\\section{Theory fundamentals}\nFor the single cylinder simulations I use the projection approximation to solve a partial differential equation known as the transport-of-intensity equation (TIE). This equation describes the relationship between the intensity and phase distribution in an optical system, and hence it can be used to quantify the contrast (i.e. refractive (phase) effects) present in propagation-based X-ray phase contrast images\\cite{PagsTutes}.\n\\begin{equation}\\label{eq:1}\n-\\nabla_{T} [I(x, y, z) \\nabla_{T} \\phi(x, y, z)] = k \\frac{\\partial I (x, y, z)}{\\partial z},\n\\end{equation}\nwhere $k$ is the wave-number, $I(x, y, z)$ is the intensity and $\\phi(x, y, z)$ is the phase of the X-ray beam.\nThe projection approximation takes into account, X-ray--matter interaction, therefore the position dependent and complex form of the refractive index is introduced: $n(x, y, z) = 1 - \\delta(x, y, z) + i \\beta(x, y, z)$. The real part of this complex quantity corresponds to the refractive index, while the imaginary part is related only to the absorptive properties of the sample\\cite{PagsTutes}.\nUnder the projection approximation, the Beer-Lambert law of attenuation is used to describe the attenuation of intensity within the sample,\n\\begin{equation}\\label{eq:2}\nI(x, y, z_0) = \\mathrm{exp}[-\\int_{t} \\mu(x, y, z) dz] I(x, y, 0),\n\\end{equation}\nwhere $\\mu = 2k\\beta$ is the \\textit{linear attenuation coefficient} of the sample and constitutes the imaginary part of the sample's complex refractive index.\nThe real part of the complex refractive index ($\\delta$) is known as the refractive index decrement, describing phase-shifts in the wave-front which continuously accumulate in the direction of propagation\n\\begin{equation}\\label{eq:3}\n\\Delta \\phi(x, y) = -k \\int_{t}\\delta(x, y, z)dz,\n\\end{equation}\nwhere $t$ is the projected thickness of the object in the direction of the light flow.\nThe TIE effects observable changes onto the intensity (eq.\\ref{eq:2}) and phase (eq.\\ref{eq:3}) after these are used as the initial conditions of the propagation problem.\n\nTo implement the spatial evolution in the direction of the wave-front propagation, I use the fourth-order Runge-Kutta with the TIE. I employ the Runge-Kutta evolution algorithm as\n\\begin{equation} \\label{eq:4}\n\\begin{split}\n&k_1 = f(z, I_n, \\phi),\\\\\n&k_2 = f(z + \\frac{\\Delta z}{2}, I_n + \\frac{1}{2}k_1, \\phi)),\\\\\n&k_3 = f(z + \\frac{\\Delta z}{2}, I_n + \\frac{1}{2}k_2, \\phi)),\\\\\n&k_4 = f(z + \\Delta z, I_n + k_3, \\phi)),\\\\\n&I_{n + 1} = I_{n} + \\frac{1}{6}(k_1 + 2k_2 + 2k_3 + k_4) + O(\\Delta z^5),\\\\\n\\end{split}\n\\end{equation}\nwhere the spatial evolution step is set as $\\Delta z = 1$~mm. The propagation via fourth order Runge-Kutta over a spatial interval is done by solving a differential equation $f$ using four Euler-style steps (i.e. the $k_i$ coefficients) where each Euler-style step involves one evaluation of the differential equation with slightly different input parameters. This method combines the information obtained for each solution to match a Taylor series expansion up to fourth order. The combined evaluations of the differential equation eliminate the error terms order by order, resulting in the remaining error being very small\\cite{N_R}.\n\nFor the two-cylinder simulations, I also use the projection approximation, but this time I model the propagation of the monochromatic X-ray wave-field using a method known as the angular spectrum formulation (ASF). This method uses Fourier decomposition of wave-fields at a single plane into distinct component plane waves. Each plane wave component is propagated through the Fourier domain to a destination plane, and then the propagated wave-field components are reconstructed via an inverse spatial Fourier transform\\cite{Goodman}. To implement the ASF, I use the X-ray imaging XRI library, since the existing algorithm has already implemented several fixes to undesirable instabilities that can appear in the simulations. This library was built by the Monash X-ray imaging group.\n\n\\subsection{Imaging brain structures}\nThe optical properties of grey and white matter are extremely similar. However, it is known that there is a small difference in the values of the attenuation coefficients of these materials. CT brain imaging has been reported to yield clearly demarcated tissue borders at the grey/white matter boundaries\\cite{Beltran2}. I want to determine if density differences alone would create phase contrast or whether phase contrast is dependent on both density and material differences.\nTo simulate grey and white matter, I use the attenuation coefficients for both materials $\\mu_{GM},\\mu_{WM}$ obtained from CT imaging of rabbit and kitten brain samples. This data was acquired at Japan's SPring-8 synchrotron radiation facility using an X-ray energy of $E = 24$keV and a sample-to-detector distance of $5$m\\cite{Linda}. In my calculations, I also use experimental grey and white matter densities reported in the ``IT’IS Database for thermal and electromagnetic parameters of biological tissues\" (see reference \\cite{ITIS}). To find the complex refractive index components of the whole brain (i.e. $\\delta_B$ and $\\mu_B$) under certain energy X-rays, I use the X-ray imaging group ``X-ray attenuation calculator\" which employs the values recorded in NIST in database 66\\cite{NIST} making these easily accessible via a GUI, (note: I use this specific tool in all my simulations, not only the ones pertaining the brain materials). \nUsing all these tools I calculated an approximate estimate for the grey and white matter refractive index decrements ($\\delta_{GM}$ and $\\delta_{WM}$) The calculations were simple. In one, I modelled the refractive index decrements as proportional to the ratio of the attenuation coefficient value for the full brain from reference\\cite{NIST} and the density of the grey or white matter values reported in reference \\cite{ITIS} (for example for grey matter: $\\delta_{GM} = \\frac{\\mu_B}{\\rho_{GM}} \\delta_B$). In contrast, my second model considered the refractive index decrement to be solely proportional to the ratio between the attenuation coefficient value for the full brain and the value corresponding to either the grey or white matter attenuation coefficients (for example for grey matter: $\\delta_{GM} = \\frac{\\mu_B}{\\mu_{GM}} \\delta_B$). \n\n\\section{Current results}\n\\subsection{Simulating a single homogeneous cylinder}\nI solved the TIE in two-dimensions using the projection approximation to establish my initial conditions. My method applies the fourth order Runge-Kutta evolution algorithm described earlier, to propagate the intensity of the monochromatic scalar electromagnetic wave-field over a total distance in meters. Originally, my code discretised a two-dimensional space as an array with dimensions $x, y = 1024, 512$. I first attempted to solve the TIE in Fourier space. To calculate the wave-field's derivative terms in equation (\\ref{eq:1}), I used the Fourier derivative theorem to write the derivatives. I defined functions describing the geometry and, optical properties (i.e. refractive index: $\\delta(x, y, z)$ and $\\mu(x, y, z)$) of the simulated cylinder. Both $\\delta$ and $\\mu$ functions use a sigmoid function with adjustable gradient to slightly blur the edge of the cylinder and, avoid instability while solving the integrals in equations (\\ref{eq:2}) and (\\ref{eq:3}). My method was slow due to the Fourier derivatives, and the output intensity profile after propagation did not appear very stable, as several instability oscillations can be seen in figure \\ref{fig:1}, to fix this issue, I adjusted the ratio of the spacings in my discretised space several times to make sure that the Nyquist mode of the TIE was resolved adequately. Nevertheless I was unable to obtain a completely smooth, and realistic looking intensity profile in figure \\ref{fig:1}.\n\\begin{Figure}\\label{fig:1}\n\\centering\n\\includegraphics[width=\\linewidth]{Fourier_intensity_profile.pdf}\n\\captionof{figure}{Phase contrast image (a), cross section (b), and enhanced view of (b) showing small ringing artefacts (instability)(c) obtained using the Fourier TIE method. This method was not able to simultaneously match the expected phase contrast peak height, given this energy and, sample material parameters while at the same time remaining fully stable. The parameters used to obtain this image were an X-ray energy of $22.1629$ keV (corresponding to a Ag k-alpha 1 source), a refractive index decrement for the water cylinder of $\\delta = 4.68141\\times10^{-7}$ and an attenuation coefficient of $\\mu = 64.38436~\\mathrm{m^{-1}}$. The cylinder radius was $R = 6.375$ mm. The sigmoid function blurred $0.5$ pixels over the edge of the imaged cylinder. The propagation distance used was $z = 1$ m.}\n\\end{Figure}\n\nTo complement this investigation, I took a slightly different approach and solved the TIE in position space using finite differences. I use \\texttt{numpy.gradient} to evaluate each derivative and \\texttt{scipy.ndimage.laplace} to evaluate the phase Laplacian term in the TIE. My code discretised the two-dimensional space as a 2D array $x, y = 1024, 1024$. \nThe probable underlying reason why my Fourier method didn't work as expected was due to an effect known as Gibbs phenomenon, this effect occurs when the nth partial sum of a Fourier series undergoes large oscillations near regions with jump discontinuities\\cite{Gibbs} (i.e. like the phase contrast fringes). Discovering that higher degree polynomial interpolation does not always improve accuracy was interesting and certainly unexpected.\n\\begin{Figure}\\label{fig:2}  \n\\centering\n\\includegraphics[width=\\linewidth]{FD_intensity_profile.pdf}\n\\captionof{figure}{Phase contrast image and cross section obtained using finite differences and Runge-Kutta. As can be seen here, the phase contrast peaks are much higher than the profile found using the Fourier method in figure \\ref{fig:1}. The parameters used to obtain this image were an X-ray energy of $22.1629$ keV (corresponding to a Ag k-alpha 1 source), a refractive index decrement for the water cylinder of $\\delta = 4.68141\\times 10^{-7}$ and an attenuation coefficient of  $\\mu = 64.38436~\\mathrm{m^{-1}}$. The cylinder radius was $R = 6.375$ mm. The sigmoid function blurred $0.14$ pixels over the edge of the imaged cylinder. The propagation distance used was $z = 1$ m. The apparent asymmetry of the two-dimensional phase contrast image is due to aliasing.}\n\\end{Figure}\nThis result presented an apparent improvement in the height of the expected phase contrast fringes. Because of this, I made sure  and made sure that all input parameters were the equal as those used in the code I used to compare my outputs (the script I used for comparisons was was made by my supervisor).\n\n\\subsection{Testing if Runge-Kutta propagation increases phase contrast}\n\nIn figure \\ref{fig:3}, I obtain phase contrast cross sections from solving the TIE using my finite-difference--Runge-Kutta method and the finite difference method developed by the x-ray imaging group. I demonstrate that my method returns a smooth, and realistic looking phase contrast cross section with higher phase contrast than that returned by the X-ray group's method. \n\n\\begin{Figure}\\label{fig:3}\n\\centering\n\\includegraphics[width=\\linewidth]{RK_TEST.pdf}\n\\captionof{figure}{Phase contrast cross sections obtained by testing: (a) my finite differences with Runge-Kutta propagation method and (b) the TIE propagation method developed by the X-ray imaging group. The input parameters and spatial discretisation codes were identical in both (a) and (b). The parameters were for a single cylinder with a radius of  $R = 2$ mm. The X-ray energy used was $50$keV. The refractive index decrement for the water cylinder is $\\delta = 9.21425\\times 10^{-8}$ and an attenuation coefficient of $\\mu = 22.69615\\mathrm{m^{-1}}$. In figure (a), the sigmoid function blurred $0.14$ pixels over the edge of the imaged cylinder.  \nThe spatial discretisation arrays used in (a) and (b) were both 2D arrays: $x, y = 1024, 1024$ and, the pixel size was$5\\mathrm{\\mu}$ m.The propagation distance used was $z = 1$ m.}\n\\end{Figure}\n\\begin{Figure}\\label{fig:3.5}\n\\centering\n\\includegraphics[width=0.6\\linewidth]{RK_TEST_difference.pdf}\n\\captionof{figure}{Phase contrast cross sections as per figure \\ref{fig:3} plotted together to quantify the difference in phase contrast results. The difference in the brightness peaks and troughs between these results are $I_{\\mathrm{peak}} = 0.165$ and $I_{\\mathrm{trough}} = -0.055$ respectively.}\n\\end{Figure}\nFurther tests need to be done to prove definitely that the addition of the Runge-Kutta algorithm for spatial propagation can drastically improve phase contrast. Nevertheless, the result shown in figures \\ref{fig:3} and \\ref{fig:3.5} is interesting because it is possible that my method could even improve phase retrieval results.\n\n\\subsection{Density difference test: water and ice}\nTo test if there is a density dependence in phase contrast, I first used a sample consisting of two cylinders with the outermost one made of water and the innermost one made of ice.\n\\begin{Figure}\\label{fig:4}\n\\centering\n\\includegraphics[width=\\linewidth]{ice_water_AS.pdf}\n\\captionof{figure}{Phase contrast image and cross section obtained with the angular spectrum formulation method developed by the X-ray imaging group. The X-ray energy used in this simulation was $E = 22.1629$ keV. The water cylinder has a refractive index decrement $\\delta_w = 4.69337\\times10^{-7}$, the attenuation coefficient of water is $\\mu_w = 64.55083~\\mathrm{m^{-1}}$. The ice cylinder has a refractive index decrement $\\delta_i = 4.31790\\times10^{-7}$, and attenuation coefficient $\\mu_i = 59.38677~\\mathrm{m^{-1}}$. The density difference between these materials is $\\Delta \\rho = 0.08~\\mathrm{g cm^{-3}}$. The cylinder's radii were $R_w = 2$mm and $R_i = 1$mm. The propagation distance used was $z = 2.5$ m.}\n\\end{Figure}\nWith the result in figure \\ref{fig:4}. I demonstrate that any changes in material density throughout the imaged sample do affect the imaging process, and therefore the stability the propagation based imaging algorithm developed by Paganin et al. (2002) is actually dependent on the ratio of the differences in the refraction and attenuation coefficients $\\Delta \\delta$ and $\\Delta \\mu$ of the imaged materials.\nIn another simulation I made, I take into account the apparatus parameters and the resolution of the detector used in the lab. I made this simulation to see whether or not we would be able to see the any small fringes in a real experiment. Using magnification factors we would use in the lab (i.e. $2.5$X and $4.0$X) and our photon detector dimensions I resized the spatial array boundaries to match those of the detector. I also scaled the pixel size to match the pixels in the photon detector. I did this so that the pixels in the object plane are adequately sized given the expected size of the pixels in the detector plane. I also calculated the effective propagation distance by dividing the simulation propagation distance by the desired magnification factor.\n\\begin{Figure}\\label{fig:5}\n\\centering\n\\includegraphics[width=\\linewidth]{LAB_ice_water_AS_2_magnifications.pdf}\n\\captionof{figure}{Phase contrast cross sections were obtained with parameters equal to those in the simulation in figure \\ref{fig:4}.}\n\\end{Figure}\nThe plan was to test these results experimentally, but given that the phase contrast fringes observable in figure \\ref{fig:5} were so small, we decided against doing the experiment, since we would not observe much in a lab setting. \n\\subsection{Density difference test: Grey matter and white matter}\nTo continue my tests of the importance of density in phase contrast, I assume in figure \\ref{fig:6}. that grey and white matter have the same chemical compositions but distinct densities.\n\\begin{Figure}\\label{fig:6}\n\\centering\n\\includegraphics[width=\\linewidth]{pessimistic_case.pdf}\n\\captionof{figure}{Phase contrast image (a), cross section (b), and enhanced view of one the inner cylinder phase contrast fringes (c) obtained with the angular spectrum formulation method as developed by the X-ray imaging group. In (c) it can be seen that the phase contrast fringes from the inner cylinder are extremely small but can still be observed when the image in (b) is amplified enough. The X-ray energy is $E = 24$ keV. The grey matter cylinder has a refractive index decrement $\\delta_{GM} = 4.1345\\times10^{-7}$, and the attenuation coefficient of grey matter is $\\mu_{GM} = 58.2978~\\mathrm{m^{-1}}$. The white matter cylinder has a refractive index decrement $\\delta_{WM} = 411.87\\times10^{-7}$ and its attenuation coefficient $\\mu_{WM}= 58.0747~\\mathrm{m^{-1}}$. The density difference between these materials is $\\Delta \\rho = 0.004~\\mathrm{g cm^{-3}}$\\cite{ITIS}. The cylinders' radii were $R_{GM} = 2$ mm and $R_{WM} = 1$ mm. The propagation distance used was $z = 2.5$ m.}\n\\end{Figure}\nMy simulations demonstrate that even a small density difference like the one seen in \\ref{fig:6} can produce phase contrast fringes. Nevertheless, my simulations only consider perfect data, therefore the fringes would be too small to see using real sample materials in a lab experiment.\n\n\\subsection{Chemical difference test: Grey matter and white matter}\n\\begin{Figure}\\label{fig:7}\n\\centering\n\\includegraphics[width=\\linewidth]{optimistic_case.pdf}\n\\captionof{figure}{Phase contrast image and phase contrast cross section obtained with the angular spectrum formulation method developed by the X-ray imaging group. The X-ray energy used in this simulation was $E = 24$keV. The grey matter cylinder has a refractive index decrement $\\delta_{GM} = 4.591\\times10^{-7}$, the attenuation coefficient of grey matter is $\\mu_{GM} = 52\\mathrm{m^{-1}}$\\cite{Linda}. The white matter cylinder has a refractive index decrement $\\delta_{WM} = 4.2631\\times10^{-7}$ and attenuation coefficient $\\mu_{WM}= 56~\\mathrm{m^{-1}}$\\cite{Linda}. The cylinders' radii were $R_{GM} = 2$ mm and $R_{WM} = 1$ mm. The propagation distance used was $z = 2.5$m.}\n\\end{Figure}\n\n\\section{Future Plans}\n\nTo definitely demonstrate that adding the Runge-Kutta algorithm for spatial propagation drastically improves phase contrast as per figure \\ref{fig:3}, I must test my method against other propagation methods used by the X-ray group. These methods include the angular spectrum formulation and Fresnel propagation. If my method consistently yields higher phase contrast, I need to investigate whether higher phase contrast is an accurate measure that would increase the chances of improving phase retrieval results.\n\nI aim to finish my density simulations by creating a graphic user interface (GUI) that allows the user to modify interactively the density parameters of the imaged concentric cylinders in the simulation. The goal is to make an easily operated visual representation of the changes in phase and intensity of the X-rays as they interact with the imaged object in-situ.\n\nMy supervisor and I are planning to test an X-ray target made of silver which has been obtained for the laboratory apparatus. I need to make simulations using the characteristic radiation spectrum of silver and see how the phase contrast fringes behave when isolating monochromatic X-ray fringes and comparing them to each other. My aim is to eventually obtain real laboratory data and analyse it to compare the efficacy of the new silver target to that of the classic tungsten target currently used in the apparatus.\n\n\\section{Conclusion}\nThe aim of my project is to investigate how the phase of incident X-rays changes as the density of distinct sample materials in an arbitrary imaging system changes. I demonstrate that any changes in material density throughout the imaged sample affect the imaging process. The eventual goals of these simulations is to verify if successful phase retrieval can be done of the imaged objects given their variable densities. This report presents a brief outline of the theory behind coherent X-ray imaging, a description of my current progress, and a brief description of my future aims.\n\n\\bibliography{mybib}\n\\bibliographystyle{unsrt}\n\\end{document}\n", "meta": {"hexsha": "2ed713eef4ba3b89b7d795ad012a595161556c9b", "size": 22009, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report2/report2.tex", "max_stars_repo_name": "anabanami/X-ray-kitchen", "max_stars_repo_head_hexsha": "b234dd478f8dba0aad99843f4568d06023eec5f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "report2/report2.tex", "max_issues_repo_name": "anabanami/X-ray-kitchen", "max_issues_repo_head_hexsha": "b234dd478f8dba0aad99843f4568d06023eec5f9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report2/report2.tex", "max_forks_repo_name": "anabanami/X-ray-kitchen", "max_forks_repo_head_hexsha": "b234dd478f8dba0aad99843f4568d06023eec5f9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 153.9090909091, "max_line_length": 1462, "alphanum_fraction": 0.7837702758, "num_tokens": 5221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.32146962893669445}}
{"text": "\\documentclass{article}\n%\n\\usepackage{fullpage}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\n\\usepackage{IEEEtrantools}\n\\usepackage{filecontents}\n\n\n\\newcommand{\\cT}{{\\mathcal T}}\n\\newcommand{\\cS}{{\\mathcal S}}\n\\newcommand{\\cG}{{\\mathcal G}}\n\\newcommand{\\cL}{{\\mathcal L}}\n\\newcommand{\\cW}{{\\mathcal W}}\n\\newcommand{\\bbR}{{\\mathbb R}}\n\\newcommand{\\uP}{\\underline{P}}\n\\newcommand{\\oP}{\\overline{P}}\n\n\\newcommand\\mydescriptionopt{\n\t\\IEEEsetlabelwidth{$g \\in \\cG_{\\textit{off}}^0$]}\n\t\\IEEEusemathlabelsep\n}\n\\begin{document}\n\n\\section{Nomenclature}\n\\subsection{Indices and Sets}\n\\begin{IEEEdescription}[\\mydescriptionopt] \n\t\\item[$g \\in \\cG$] Set of thermal generators.\n\t\\item[$g \\in \\cG_{\\textit{on}}^0$] Set of thermal generators which are initially committed (on).\n\t\\item[$g \\in \\cG_{\\textit{off}}^0$] Set of thermal generators which are not initially committed (off).\n\t\\item[$w \\in \\cW$] Set of renewable generators.\n\t\\item[$t \\in \\cT$] Hourly time steps: $1, \\ldots, T$, $T$ = {\\tt time\\_periods}\n\t\\item[$l \\in \\cL_g$] Piecewise production cost intervals for thermal generator $g$: $1, \\ldots, L_g$.\n\t\\item[$s \\in \\cS_g$] Startup categories for thermal generator $g$, from hottest ($1$) to coldest ($S_g$): $1, \\ldots, S_g$.\n\\end{IEEEdescription}\n\n\\subsection{System Parameters}\n\\begin{IEEEdescription}[\\mydescriptionopt]\n\t\\item[$D(t)$]    Load (demand) at time $t$ (MW), {\\tt demand}.\n\t\\item[$R(t)$]    Spinning reserve at time $t$ (MW), {\\tt reserves}.\n\\end{IEEEdescription}\n\n\\subsection{Thermal Generator Parameters}\n\\begin{IEEEdescription}[\\mydescriptionopt]\n\t\\item[$CS_g^s$]  Startup cost in category $s$ for generator $g$ (\\$), {\\tt startup['cost']}.\n\t\\item[$CP_g^l$]  Cost of operating at piecewise generation point $l$ for generator $g$ (MW), {\\tt piecewise\\_production['cost']}.\n\t\\item[$DT_g$]    Minimum down time for generator $g$ (h), {\\tt time\\_down\\_minimum}.\n\t\\item[$DT^0_g$] Number of time periods the unit has been off prior to the first time period for generator $g$, {\\tt time\\_down\\_t0}.\n\t\\item[$\\oP_g$]   Maximum power output for generator $g$ (MW), {\\tt power\\_output\\_maximum}.\n\t\\item[$\\uP_g$]   Minimum power output for generator $g$ (MW), {\\tt power\\_output\\_minimum}.\n\t\\item[$P_g^0$]   Power output for generator $g$ (MW) in the time period prior to t=1, {\\tt power\\_output\\_t0}.\n\t\\item[$P_g^l$]   Power level for piecewise generation point $l$ for generator $g$ (MW); $P^1_g = \\uP_g$ and $P^{L_g}_g = \\oP_g$, {\\tt piecewise\\_production['mw']}.\n\t\\item[$RD_g$]    Ramp-down rate for generator $g$ (MW/h), {\\tt ramp\\_down\\_limit}.\n\t\\item[$RU_g$]    Ramp-up rate for generator $g$ (MW/h), {\\tt ramp\\_up\\_limit}.\n\t\\item[$SD_g$]    Shutdown capability for generator $g$ (MW), {\\tt ramp\\_shutdown\\_limit}.\n\t\\item[$SU_g$]    Startup capability for generator $g$ (MW), {\\tt ramp\\_startup\\_limit}\n\t\\item[$TS^s_g$] Time offline after which the startup category $s$ becomes active (h), {\\tt startup['lag']}.\n\t\\item[$UT_g$]    Minimum up time for generator $g$ (h), {\\tt time\\_up\\_minimum}.\n\t\\item[$UT^0_g$] Number of time periods the unit has been on prior to the first time period for generator $g$, {\\tt time\\_up\\_t0}.\n\t\\item[$U_g^0$]  Initial on/off status for generator $g$, $U_g^0=1$ for $g \\in \\cG_{\\textit{on}}^0$, $U_g^0=0$ for $g \\in \\cG_{\\textit{off}}^0$,  {\\tt unit\\_on\\_t0}.\n\t\\item[$U_g$] \tMust-run status for generator $g$, {\\tt must\\_run}.\n\\end{IEEEdescription}\n\n\\subsection{Renewable Generator Parameters}\n\\begin{IEEEdescription}[\\mydescriptionopt]\n\t\\item[$\\oP_w(t)$] Maximum renewable generation available from renewable generator $w$ at time $t$ (MW), {\\tt power\\_output\\_maximum}.\n\t\\item[$\\uP_w(t)$] Minimum renewable generation available from renewable generator $w$ at time $t$ (MW), {\\tt power\\_output\\_minimum}.\n\\end{IEEEdescription}\n\n\n\\subsection{Variables}\n\\begin{IEEEdescription}[\\mydescriptionopt]\n\t\\item[$c_g(t)$]    Cost of power produced above minimum for thermal generator $g$ at time $t$ (MW), $\\in \\bbR$.\n\t\\item[$p_g(t)$]    Power above minimum for thermal generator $g$ at time $t$ (MW), $\\geq 0$.\n\t\\item[$p_w(t)$]  Renewable generation used from renewable generator $w$ at time $t$ (MW), $\\geq 0$.\n\t\\item[$r_g(t)$]    Spinning reserves provided by thermal generator $g$ at time $t$ (MW), $\\geq 0$.\n\t\\item[$u_g(t)$]    Commitment status of thermal generator $g$ at time $t$, $\\in \\{0,1\\}$. \n\t\\item[$v_g(t)$]    Startup status of thermal generator $g$ at time $t$, $\\in \\{0,1\\}$. \n\t\\item[$w_g(t)$]    Shutdown status of thermal generator $g$ at time $t$, $\\in \\{0,1\\}$. \\\n\t\\item[$\\delta^s_g(t)$] Startup in category $s$ for thermal generator $g$ at time $t$, $\\in \\{0,1\\}$.\n\t\\item[$\\lambda_g^l(t)$]  Fraction of power from piecewise generation point $l$ for generator $g$ at time $t$ (MW), $\\in [0,1]$.\n\\\n\\end{IEEEdescription}\n\n\\section{Model Description}\nBelow we describe the unit commitment model given by~\\cite{morales2013tight}, with the piecewise production cost description from~\\cite{sridhar2013locally}.\nThe unit commitment problem can then be formulated as:\n{\\allowdisplaybreaks\n\t\t\\begin{align}\n\t\t& \\text{min } \\sum_{g \\in \\cG} \\sum_{t \\in \\cT} \\left( c_g(t) + CP_g^1 \\, u_g(t) + \\sum_{s = 1}^{S_g} \\left( CS^s_g \\delta^s(t) \\right) \\right) \\label{eq:obj} %\\tag{UC} %\\\\\n\t\t%\\text{subject to }  & &  \\nonumber\n\t\t\\end{align}\n\t\tsubject to:\n\t\t\\begin{align}\n\t\t& \\sum_{g \\in \\cG} \\left( p_g(t) + \\uP_g u_g(t) \\right) + \\sum_{w\\in\\cW} p_w(t) = D(t) & \\hspace{5cm} \\forall t \\in \\cT \\label{eq:UCDemand} \\\\\n\t\t& \\sum_{g \\in \\cG} r_g(t) \\geq R(t) &  \\forall t \\in \\cT \\label{eq:UCReserves}\n\t\t\\end{align}\n\t\t\\begin{align}\n\t\t& \\sum_{t=1}^{\\min\\{UT_g - UT_g^0, T\\}} (u_g(t) - 1) = 0 & \\hspace{3cm} \\forall g \\in \\cG_{\\textit{on}}^0 \\label{eq:initialUpRequirement} \\\\\n\t\t& \\sum_{t=1}^{\\min\\{DT_g - DT_g^0, T\\}} u_g(t) = 0 & \\forall g \\in \\cG_{\\textit{off}}^0 \\label{eq:initialDownRequirement} \\\\\n\t\t& u_g(1) - U_g^0 = v_g(1) - w_g(1) & \\forall g \\in \\cG \\label{eq:LogicalInitial} \\\\\t\n\t\t& \\sum_{s=1}^{S_g-1} \\sum_{t=\\max\\{1, TS^{s+1}_g - DT^0_g + 1\\}}^{\\min\\{TS^{s+1}_g -1,T\\}} \\delta^s_g(t) = 0 & \\forall g \\in \\cG \\label{eq:STIInit}\\\\\n\t\t& p_g(1) + r_g(1) - U_g^0(P_g^0-\\uP_g) \\leq RU_g & \\forall g \\in \\cG \\label{eq:RampUpInit} \\\\\n\t\t& U_g^0(P_g^0-\\uP_g) - p_g(1) \\leq RD_g & \\forall g \\in \\cG \\label{eq:RampDownInit} \\\\\n\t\t& U_g^0(P_g^0-\\uP_g) \\leq (\\oP_g - \\uP_g) U_g^0 - \\max\\{(\\oP_g - SD_g),0\\} w_g(1) & \\forall g \\in \\cG \\label{eq:MaxOutput2Init}\n\t\t\\end{align}\n\t\t\\begin{align}\n\t\t& u_g(t) \\geq U_g & \\hspace{1cm} \\forall t \\in \\cT, \\, \\forall g \\in \\cG \\label{eq:MustRun} \\\\\n\t\t& u_g(t) - u_g(t-1) = v_g(t) - w_g(t) & \\forall t \\in \\cT\\setminus\\{1\\}, \\, \\forall g \\in \\cG \\label{eq:Logical} \\\\\n\t\t& \\sum_{i= t-\\min\\{UT_g,T\\} + 1}^t v_g(i) \\leq u_g(t) & \\forall t \\in \\{\\min\\{UT_g,T\\} \\ldots, T\\}, \\, \\forall g \\in \\cG \\label{eq:Startup} \\\\\n\t\t& \\sum_{i= t-\\min\\{DT_g,T\\} + 1}^t w_g(i) \\leq 1 - u_g(t) & \\forall t \\in \\{\\min\\{DT_g, T\\}, \\ldots, T\\}, \\, \\forall g \\in \\cG \\label{eq:Shutdown} \\\\\n\t\t& \\delta^s_g(t) \\leq \\sum_{i = TS^s_g}^{TS^{s+1}_g-1} w_g(t-i) & \\forall t \\in \\{TS^{s+1}_g,\\ldots,T\\},\\,\\forall s \\in \\cS_g\\!\\setminus\\!\\{S_g\\},\\,  \\forall g \\in \\cG \\label{eq:STISelect} \\\\\n\t\t& v_g(t) = \\sum_{s = 1}^{S_g} \\delta^s_g(t) & \\forall t \\in \\cT,\\, \\forall g \\in \\cG \\label{eq:STILink}\n\t\t\\end{align}\n\t\t\\begin{align}\n\t\t& p_g(t) + r_g(t) \\leq (\\oP_g - \\uP_g) u_g(t) - \\max\\{(\\oP_g - SU_g),0\\} v_g(t) & \\forall t \\in \\cT, \\, \\forall g \\in \\cG \\label{eq:MaxOutput1} \\\\\n\t\t& p_g(t) + r_g(t) \\leq (\\oP_g - \\uP_g) u_g(t) - \\max\\{(\\oP_g - SD_g),0\\} w_g(t+1) & \\forall t \\in \\cT\\setminus \\{T\\}, \\, \\forall g \\in \\cG \\label{eq:MaxOutput2} \\\\\n\t\t& p_g(t) + r_g(t) - p_g(t-1) \\leq RU_g & \\forall t \\in \\cT\\setminus\\{1\\}, \\, \\forall g \\in \\cG \\label{eq:RampUp} \\\\\n\t\t& p_g(t-1) - p_g(t) \\leq RD_g & \\forall t \\in \\cT\\setminus\\{1\\}, \\, \\forall g \\in \\cG \\label{eq:RampDown}\n\t\t\\end{align}\n\t\t\\begin{align}\n\t\t& p_g(t) = \\sum_{l \\in \\cL_g} (P_g^l - P_g^1) \\lambda_g^l(t) &\\hspace{5cm} \\forall t \\in \\cT, \\, \\forall g \\in \\cG \\label{eq:PiecewiseParts} \\\\\n\t\t& c_g(t) = \\sum_{l \\in \\cL_g} (CP_g^l - CP_g^1) \\lambda_g^l(t) & \\forall t \\in \\cT, \\, \\forall g \\in \\cG \\label{eq:PiecewisePartsCost} \\\\\n\t\t& u_g(t) = \\sum_{l \\in \\cL_g} \\lambda_g^l(t) & \\forall t \\in \\cT, \\forall g \\in \\cG \\label{eq:PiecewiseLimits}\n\t\t\\end{align}\n\t\t\\begin{align}\n\t\t& \\uP_w(t) \\leq p_w(t) \\leq \\oP_w(t) &\\hspace{6cm} \\forall t \\in \\cT, \\, \\forall w \\in \\cW \\label{eq:WindLimit}\n\t\t\\end{align}\n}%\nNote that in constraints~\\eqref{eq:initialUpRequirement}, \\eqref{eq:initialDownRequirement}, and \\eqref{eq:STIInit}, we use the convention that empty sums are $0$.\n\n%% add the bibtex\n\\begin{filecontents*}{MODEL.bib}\n@article{morales2013tight,\n\ttitle={Tight and compact {MILP} formulation for the thermal unit commitment problem},\n\tauthor={Morales-Espa{\\~n}a, G. and Latorre, J. M. and Ramos, A.},\n\tjournal={IEEE Transactions on Power Systems},\n\tvolume={28},\n\tnumber={4},\n\tpages={4897--4908},\n\tyear={2013},\n\tpublisher={IEEE}\n}\n@article{sridhar2013locally,\n\ttitle={Locally ideal formulations for piecewise linear functions with indicator variables},\n\tauthor={Sridhar, Srikrishna and Linderoth, Jeff and Luedtke, James},\n\tjournal={Operations Research Letters},\n\tvolume={41},\n\tnumber={6},\n\tpages={627--632},\n\tyear={2013},\n\tpublisher={Elsevier}\n}\n\\end{filecontents*}\n\n\\bibliographystyle{acm}\n\\bibliography{MODEL}\t\n\n\\end{document}\n", "meta": {"hexsha": "54a264774bb06883693170a562a007522cfb8792", "size": 9314, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "MODEL.tex", "max_stars_repo_name": "power-grid-lib/pglib-uc", "max_stars_repo_head_hexsha": "cc3ccc1f82a27c66f5e0935fcee005a2fabd1594", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 40, "max_stars_repo_stars_event_min_datetime": "2019-08-08T20:35:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T03:15:55.000Z", "max_issues_repo_path": "MODEL.tex", "max_issues_repo_name": "candleinwindsteve/pglib-uc", "max_issues_repo_head_hexsha": "a7292a763dae1f74d920923c167238a77f6c4a01", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-08-08T20:36:53.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-19T19:34:39.000Z", "max_forks_repo_path": "MODEL.tex", "max_forks_repo_name": "candleinwindsteve/pglib-uc", "max_forks_repo_head_hexsha": "a7292a763dae1f74d920923c167238a77f6c4a01", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2019-11-21T01:34:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-30T19:07:46.000Z", "avg_line_length": 57.850931677, "max_line_length": 192, "alphanum_fraction": 0.6452651922, "num_tokens": 3700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.32146962893669445}}
{"text": "%\n% File acl2018.tex\n%\n%% Based on the style files for ACL-2017, with some changes, which were, in turn,\n%% Based on the style files for ACL-2015, with some improvements\n%%  taken from the NAACL-2016 style\n%% Based on the style files for ACL-2014, which were, in turn,\n%% based on ACL-2013, ACL-2012, ACL-2011, ACL-2010, ACL-IJCNLP-2009,\n%% EACL-2009, IJCNLP-2008...\n%% Based on the style files for EACL 2006 by \n%%e.agirre@ehu.es or Sergi.Balari@uab.es\n%% and that of ACL 08 by Joakim Nivre and Noah Smith\n\n\\documentclass[11pt,a4paper]{article}\n\\usepackage[hyperref]{acl2018}\n\\usepackage{times}\n\\usepackage{latexsym}\n\\usepackage{algorithm}\n\\usepackage{algorithmic}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{tikz}\n\\usetikzlibrary{shapes,arrows}\n%\\usepackage{bibtex}\n\\usepackage{url}\n\n\\aclfinalcopy % Uncomment this line for the final submission\n%\\def\\aclpaperid{***} %  Enter the acl Paper ID here\n\n%\\setlength\\titlebox{5cm}\n% You can expand the titlebox if you need extra space\n% to show all the authors. Please do not make the titlebox\n% smaller than 5cm (the original size); we will check this\n% in the camera-ready version and ask you to change it back.\n\n\n\n\n\\title{Trying Tries Algorithm}\n\n\\author{Denizhan Pak \\\\ Indiana University - Computational\n       Linguistics Department\\\\ {\\tt denpak@iu.edu}}\n\n\\date{October 10, 2019}\n\n\\begin{document}\n\\maketitle\n\\begin{abstract}\n        There are many reasons to apply morphological analysis at the \n        sentence level. For the application of computational tools to \n        corpus data it is important that all tokens are specified to \n        allow the tools to have as informative data as possible.\n        To determine the list of morphemes in a language however is a time\n        consuming task and unsupervised algorithm could relieve quite a few\n        researchers and grad students. In this paper we propose a \n        potentially useful unsupervised machine learning algorithm to \n        accomplish just this task.\n\\end{abstract}\n\n\n\\section{Introduction}\nMorpheme parsing is an important task from a computational linguistics \nstandpoint as it provides a way to denote meaningful units within a corpus\nin turn this allows us to apply the many tools which use these units using the\nlowest components which still provide information. We propose that smaller \nsemantic units can be differentiated by their relative frequency. More \nexplicitly if we are able to identify substrings which occur as a cohesive \nunit with a high relative frequency then those units correspond to morphemes \nor some other sort of semantic unit. The algorithm below provides an \nunsupervised method through which such semantic units can be distinguished.\nThe algorithm uses a data structure similar to a \"trie\" however edges between \nnodes are assigned a transition probability, we shall call this a \"p-trie.\" \nThe algorithm requires 3 user determined hyper parameters: \n$0 < \\lambda $, $< 1 < \\rho$, and a function $f:\\mathbb{Z}\\to[0,1]$. \nWhere $\\rho$ is a reinforcement rate, \n$\\lambda$ is a learning rate, and $f$ is a probability function. (For the \npurpose of this project I will be using a translated sigmoidal function.)\n\\begin{algorithm}\n  \\label{alg:algorithm1}\n\\caption{Build Trie}\n\\begin{algorithmic}\n\\STATE $context \\leftarrow root$\n\\FOR{$char$ in $corpus$}\n\\IF{$pointer ==  root$}\n\\STATE $p_1 = 1,p_2=1$\n\\ELSE\n\\STATE $p_1 = \\lambda, p_2 = \\rho$\n\\ENDIF\n\\IF{$char$ in $context\\to children$}\n\\STATE $weight_{char} \\leftarrow weight_{char} * p_2$\n\\ELSE\n\\STATE $weight_{char} \\leftarrow p_1$\n\\STATE $context\\to children\\ \\textbf{append}\\ char$\n\\ENDIF\n\\STATE $r \\leftarrow \\textbf{random number(0,1)}$\n\\IF{$r > f(weight_{char})$}\n\\STATE $context \\leftarrow root$\n\\ELSE\n\\STATE $context \\leftarrow char$\n\\ENDIF\n\\ENDFOR\n\\STATE $\\textbf{return}\\ root$\n\\end{algorithmic}\n\\end{algorithm}\nAt the end of the algorithm the function will have returned a $p-trie$ with\nthe estimated probability values. Once we have a $p-trie$ it is possible to\nextract potential morphemes as sequences of nodes that start at the root. We\ncan even assign a certainty per morpheme which is the product of the weights \nalong its edges. This certainty can then be used to rate the likelihood of \npossible segmentations. If the corpus is not large enough an easy approach to \nimproving access to data would simply be to randomize the words in the corpus\nand run the algorithm through it again starting with the existing $p-trie$. \nThis technique is similar to random walks along markov chain. Since it is a \nBayesian method we can incorporate priors by passing a previously calculated\n$p-trie$ \\cite{Bayesian}.\n\\section{Proposed Goals}\n\\subsection{Minimum Viable Product}\nThe minimum viable product of this project is a complete implementation of the\nalgorithm defined in \\textbf{Algorithm} \\ref{alg:algorithm1} along with a \ncomprehensive performance analysis. The \nanalysis will include accuracy testing across multiple corpora in multiple\nlanguages along with the effects of different parameterizations.\n\\subsection{Expected Product}\nThe expected product will be the minimum viable product as well as specific \noptimizations such as simulated annealing for the parameter values, a more\ncomplex function for reinforcement, and an automated randomization of the \ncorpus designed to improve performance.\n\\subsection{High-Achievement Product}\nThe high-achievement product will be the expected product as well as a generalization of the algorithm which could be applied to finding meaningful \nsub-sequences in any sequential data with a particular eye toward word \nembeddings. As well as a potential generative application of the generated \n$p-trie$.\n\\section{Requirements}\n\\begin{itemize}\n        \\item A working python implementation of the algorithm.\n        \\item A well documented description of the algorithm and its \n                performance.\n        \\item A report characterizing the algorithm including its strengths \n                and weaknesses.\n\\end{itemize}\n\\section{Timelines}\n\\begin{itemize}\n        \\item 10.15-10.22 A first implementation of the algorithm and basic\n                testing using a single corpus.\n        \\item 10.22-10.29 Testing algorithm using varying parameter sets \n                across multiple languages and corpora.\n        \\item 10.29-11.06 Implementation of simulated annealing and varied\n                reinforcement and corpora randomization.\n        \\item 11.06-11.16 Evaluation of new implementation across corpora\n                and languages.\n        \\item 11.16-11.26 Generalization of the algorithm to any subsequence\n               and evaluation of performance on different data such as word\n               embeddings.\n       \\item 11.26-12.03 Writing final report and preparing presentation.\n\\end{itemize}\nThis does not include literature review or the writing of documentation both \nof which I intend to do as they coincide with different parts of the timeline \nabove.\n\\section{Data Policy}\nAll data and code will be made available on a public git page. The code will \nbe written in Python. The data for testing and evaluation will be taken from\nthe tree UD treebanks \\cite{UDDocumentation} dataset from the following languages:\n\\begin{itemize}\n        \\item English\n        \\item Turkish\n        \\item Chinese\n        \\item Japanese (if time suffices)\n        \\item Toki Pona (if time suffices)\n\\end{itemize}\nFinally the effectiveness of the algorithm will be compared to the morphessor \\cite{Morphessor} \npython implementation.\n\\newpage\n\\section{References}\n\\begin{thebibliography}{9}\n\n  \\bibitem{Bayes}\n  Knight, Kevin\n  \\textit{Bayesian Inference with Tears \n  a tutorial workbook for natural language researchers}\n  \\bibitem{Morphessor}\n    Creutz, Mathias and Lagus, Krista,\n    \\textit{Unsupervised models for morpheme segmentation and morphology \n    learning}\n    \\bibitem{UDDocumentation}\n    de Marneffe, Marie-Catherine  and\n      Dozat, Timothy  and\n      Silveira, Natalia  and\n      Haverinen, Katri  and\n      Ginter, Filip  and\n      Nivre, Joakim  and\n      Manning, Christopher D.,\n      \\textit{Universal Stanford dependencies: A cross-linguistic typology}\n      \\bibitem{ByteEnc}\n      Gage, Philip\n      \\textit{A New Algorithm for Data Compression}\n\\end{thebibliography}\n\\section{Appendix}\nIn \\textbf{Figure 1} the flow diagram is presented \nto explain the functioning of the algorithm.\n% Define block styles\n\\tikzstyle{decision} = [diamond, draw, fill=blue!20,\n    text width=4.5em, text badly centered, node distance=3cm, inner sep=0pt]\n\\tikzstyle{block} = [rectangle, draw, fill=blue!20,\n    text width=5em, text centered, rounded corners, minimum height=4em]\n\\tikzstyle{line} = [draw, -latex']\n\\tikzstyle{cloud} = [draw, ellipse,fill=red!20, node distance=3cm,\n    minimum height=2em]\n    \\begin{figure}\n           \n\\begin{tikzpicture}[node distance = 2cm, auto]\n    % Place nodes\n    \\node [block] (init) {initialize trie};\n    \\node [cloud, right of=init] (system) {corpus};\n    \\node [block, below of=init] (root) {set context to root};\n    \\node [block, below of=root] (terbed) {get input value $\\to char$};\n    \\node [decision, below of=terbed] (pointer) {is pointer set to root?};\n    \\node [block, left of=pointer, node distance=3cm] (update) \n            {set $p_1 = p_2 = 1$};\n    \\node [block, right of=pointer, node distance=3.3cm] (child) \n            {set $p_1 = \\lambda$ and $p_2 = \\rho$};\n    \\node [decision, below of=pointer, node distance=3.3cm] (expected) {is \n            $char$ a child node of pointer?};\n    \\node [block,below of=expected, right of=expected, node distance=2.33cm] \n           (notchild) {add $char$ as child with transition probability $p_1$};\n    \\node [block, below of=expected, left of=expected, node distance=2.33cm] \n            (ischild) {multiply transition probability of char by $p_2$};\n    \n    \\node [block, below of=expected, node distance=6cm] (transition) \n            {set context (probabilistically) $p_3 = f(\\text{transition probability of $char$})$};\n    \\node [block, below of=transition, node distance=3.3cm] (input) \n            {set context to $char$};\n    % Draw edges\n    \\path [line] (init) -- (root);\n    \\path [line] (root) -- (terbed);\n    \\path [line] (terbed) -- (pointer);\n    \\path [line] (pointer) -| node [near start] {yes} (update);\n    \\path [line] (pointer) -- node [near start] {no} (child);\n    \\path [line] (update) |- (expected);\n    \\path [line] (child) |- (expected);\n    \\path [line] (expected) -- node  {yes} (ischild);\n    \\path [line] (expected) -- node  {no} (notchild);\n    \\path [line,dashed] (system) |- (terbed);\n    \\path [line] (ischild) -- (transition);\n    \\path [line] (notchild) -- (transition);\n    \\path [line, dashed] (transition) -- node {$p_3$} (input);\n    \\path [line, dashed] (transition) -|++  (-5,13) node [near start]{$1-p_3$}|- (root);\n    \\path [line] (input) -|++  (-5,13) |- (terbed);\n\\end{tikzpicture}\n        \\label{Flow}\n        \\caption{Flow Diagram}\n \\end{figure}\n\n% include your own bib file like this:\n%\\bibliographystyle{acl}\n%\\bibliography{acl2018}\n\\end{document}\n", "meta": {"hexsha": "b82a1b4a7e19ca2ef38a01f8469b7a818e5102da", "size": 11099, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Writeup/Trying-Trees.tex", "max_stars_repo_name": "denizhanpak/Trying-Tries", "max_stars_repo_head_hexsha": "55da8003e98052b39c5fa112e8c68272811a55b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Writeup/Trying-Trees.tex", "max_issues_repo_name": "denizhanpak/Trying-Tries", "max_issues_repo_head_hexsha": "55da8003e98052b39c5fa112e8c68272811a55b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Writeup/Trying-Trees.tex", "max_forks_repo_name": "denizhanpak/Trying-Tries", "max_forks_repo_head_hexsha": "55da8003e98052b39c5fa112e8c68272811a55b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.186770428, "max_line_length": 148, "alphanum_fraction": 0.7173619245, "num_tokens": 2957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.61878043374385, "lm_q1q2_score": 0.3214696289366944}}
{"text": "\\documentclass[12pt]{article}\n\\usepackage{graphicx}\n\\usepackage{float}\n\\usepackage{amsmath}\n\\usepackage{scrextend}\n\\addtolength{\\textwidth}{1in}\n\\addtolength{\\textheight}{1in}\n\\addtolength{\\evensidemargin}{0.5in}\n\\addtolength{\\oddsidemargin}{-0.5in}\n\\addtolength{\\topmargin}{-0.5in}\n\\title{gl-billiards}\n\\author{Dan Lapp\\\\Taras Mychaskiw\\\\COSC 3P98 Project}\n\\date{January 8th, 2014}\n\n\\begin{document}\n\\maketitle\n    \\begin{abstract}\n    \\end{abstract}\n\n    \\thispagestyle{empty}\n    \\tableofcontents\n    %\\cleardoublepage\n    %\\newpage\n    \\thispagestyle{empty}\n    \\mbox{}\n    \\clearpage\n    \\setcounter{page}{1}\n    \n    \\section{Physics Engine}\n    \n        \\subsection{Taking a Shot}\n        Once a ball is hit by the cue, there are two ways energy is transferred to the ball. First, and more noticeable of the two\n        is the transfer of linear momentum. This sends the ball moving around the table in straight lines. Second is the transfer\n        of angular momentum, which applies spin to the ball. Spin can cause the ball to stop in it's tracks after a collision,\n        bounce off cushions in strange (but predictable) ways and to any pool player, is just as if not more important an aspect\n        to the game as the linear momentum.\n            \\subsubsection{Linear Momentum}\n            To simplify the shot making process, the pool cue is assuming to act like a spring. That is, the further you pull\n            the cue away from the cue you are going to hit, the more powerful your shot will be. Spring motion can be described\n            using Hooke's Law,\n            \\begin{equation}\n                \\vec F = -k \\vec x\n                \\label{equ:hookes_law}\n            \\end{equation}\n            where, $\\vec F$ is the force, $\\vec x$ is how much the spring is stretched and $k$ is the spring constant, which\n            describes basically how powerful (springy) the spring is.\n            \\\\\n            Hooke's Law is equivalent to Newton's Second Law, which states\n            \\begin{equation}\n                \\vec F = m \\vec a\n                \\label{equ:newton}\n            \\end{equation}\n            where, $\\vec F$ is the force, $m$ is the mass of the object and $\\vec a$ is the acceleration of the object. Setting\n            Equation~\\ref{equ:hookes_law} equal to Equation~\\ref{equ:newton} gives\n            \\begin{eqnarray}\n                -k \\vec x &=& m \\vec a \\nonumber \\\\\n                -k \\vec x &=& m \\frac{\\Delta \\vec v}{\\Delta t} \\nonumber \\\\\n                \\Delta \\vec v &=& \\frac{-k \\Delta t}{m}\\vec x  \\nonumber\n            \\end{eqnarray}\n            where $\\vec v$ is the velocity of the object, and $t$ is the time. For pool, the initial velocity of the ball being struck is\n            always zero, so we can simplify the above equation to\n            \\begin{equation}\n                \\vec v = \\frac{-k t}{m}\\vec x\n                \\label{equ:shot_velocity}\n            \\end{equation}\n            where $\\vec x$ is the distance between the ball and the tip of the cue, $m$ is the mass of the ball, $t$ is how much time the\n            cue is in contact with the ball and $k$ is the spring constant of the cue. The values for $t$ and $k$ needed to be experimentally\n            found though trial and error, essentially trying values until what happened in the simulation closely represented real life. The\n            values for $t$ and $k$ were found to be $0.1$s and $10$N/m.\n            %\\end{Linear Velocity}\n            \n            \\subsubsection{Angular Momentum}\n            Angular momentum transfer is more complex. The starting point for this section is also Newton's Second Law, but written\n            in a form more usable to the problem at hand.\n            \\begin{equation}\n                \\vec \\tau = I \\vec \\alpha\n                \\label{equ:newton_rotation}\n            \\end{equation}\n            where $\\vec \\tau$ is the torque applied to the object around it's center of rotation, $I$ is the moment of inertia of the\n            object and $\\vec \\alpha$ is the angular acceleration of the object.\n            \\\\\n            Torque is always given by the equation,\n            \\begin{equation}\n                \\vec \\tau = \\vec r \\times \\vec F\n                \\label{equ:torque}\n            \\end{equation}\n            where $\\vec F$ is the force being applied, $\\vec r$ is the vector between where the force is being applied and the center\n            of rotation of the object, and $\\times$ is the vector cross product.\n            \\\\\n            An important note is the inertia for a solid sphere is given by,\n            \\begin{equation}\n                I_{sphere} = \\frac{2}{5} m R^2\n                \\label{equ:inertia_sphere}\n            \\end{equation}\n            where $R$ is the radius and $m$ is the mass of the sphere.\n            \\\\\n            Setting Equation~\\ref{equ:newton_rotation} equal to Equation~\\ref{equ:torque}, subbing in Equation~\\ref{equ:inertia_sphere}\n            for $I$ and Equation~\\ref{equ:hookes_law} for $\\vec F$, and solving gives,\n            \\begin{eqnarray}\n                \\vec r \\times -k \\vec x &=& \\frac{2}{5} m R^2 \\frac{\\Delta \\vec \\omega}{\\Delta t} \\nonumber \\\\\n                \\Delta \\vec \\omega &=& \\frac{5}{2} \\left(\\frac{\\Delta t}{m R^2}\\right) (\\vec r \\times -k \\vec x) \\nonumber\n            \\end{eqnarray}\n            where $\\vec \\omega$ is the angular velocity of the ball, and $t$ $t$ is how much time the cue is in contact with the ball (the same $t$\n            as in the previous section). Again, for pool, when the ball is struck it is entirely at rest, so the initial angular velocity is zero.\n            The above equation then simplifies to\n            \\begin{equation}\n                \\vec \\omega = \\frac{5}{2} \\left(\\frac{\\Delta t}{m R^2}\\right) (\\vec r \\times -k \\vec x)\n                \\label{equ:shot_angular}\n            \\end{equation}\n            where $\\vec x$ is the distance between the ball and the tip of the cue, $m$ is the mass of the ball, $R$ is the radius of the ball,\n            $t$ is how much time the cue is in contact with the ball, $k$ is the spring constant of the cue and finally $\\vec r$ is the vector\n            between the center of the ball and where the cue strikes the ball.\n            %\\end{Angular Velocity}\n        %\\end{Taking a Shot}\n        \n        \\subsection{Event System}\n        For the purposes of this program, an event is a ball-ball collision, or a ball banking off of the cushion. The way gl-billiards works\n        is each time the screen is redisplayed, some physics updater function is called with a parameter $dt$, which is how much time has passed\n        since the last frame. The engine simulates the pool game up until a time $dt$ has passed. For example, if $1$s was passed, then it would\n        simulate $1$s of play before returning, then the screen would be updated as if $1$s had passed.\n        \\\\\n        So, the engine determines which events occur within time $dt$. Event detection then becomes \\textit{when} do events happen instead\n        of \\textit{if} they happened. The entire update function works as follows:\\\\\n        \\texttt{\n            update($dt$)                                                        \\\\\n            \\begin{addmargin}[1em]{0em}\n            find earliest event that occurs within time $dt$, call it $event$   \\\\\n            if no such event                                                    \\\\\n                \\begin{addmargin}[1em]{0em}\n                roll balls until $dt$                                           \\\\\n                \\end{addmargin}\n            otherwise                                                           \\\\\n                \\begin{addmargin}[1em]{0em}\n                roll balls until $event$ occurs                                 \\\\\n                handle $event$                                                  \\\\\n                $dt$ <-- $dt$ - $event$.$getTime()$                             \\\\\n                call update($dt$) again                                         \\\\\n                \\end{addmargin}\n            \\end{addmargin}\n        }\n        In this manner, all events that happen within $dt$ and handled automatically before the frame updates and the balls slow\n        down due to friction. Note that \"roll balls\" simply means each ball moves at it's speed for some amount of time. Pocketing\n        detection needs to be done there, as it is not a standard event. That is, if a ball is pocketed, it cannot possible participate\n        in any events in time $dt$, since it would bank off the cushion or collide with another ball first. \\\\\n        After $update(dt)$ is finished, each ball gets affected by friction and slows down slightly. Friction takes the form of a\n        slight decrease in the velocity of the ball. \n        %\\end{Event System}\n        \n        \\subsection{Event Detection}\n            \\subsubsection{Ball-Ball Collision Detection}\n            A ball-ball collision will occur when the centers of the balls are two radii apart. In gl-billiards, the trajectory\n            of each ball is simplified to be a straight line per frame since friction is only applied at the end of each frame.\n            Thus, the trajectory of each ball becomes,\n            \\begin{equation}\n                \\vec r = \\vec r_0 + \\vec v t\n                \\label{equ:position}\n            \\end{equation}\n            where $\\vec r$ is the position of the ball, $\\vec r_0$ is the starting position, $\\vec v$ is the velocity of the ball and\n            $t$ is the amount of time elapsed. Then, for each possible collision to occur, the program needs to find at what times the\n            distance from one ball to the other is equal to twice the radius of the ball. Mathematically, this becomes\n            \\begin{eqnarray}\n                | \\vec r_1 - \\vec r_2 | &=& 2 R   \\nonumber   \\\\\n                \\sqrt{ (\\vec r_1 - \\vec r_2) \\cdot (\\vec r_1 - \\vec r_2) } &=& 2 R  \\nonumber\n            \\end{eqnarray}\n            where $R$ is the radius of a ball. Squaring both sides, and subbing in Equation~\\ref{equ:position} for both\n            $\\vec r_1$ and $\\vec r_2$ (using $\\vec{dr_0} = \\vec r_{0_1} - \\vec r_{0_2}$ and $\\vec{dv} = \\vec v_1 - \\vec v_2$),\n            \\begin{eqnarray}\n                (\\vec{dr_0} \\cdot \\vec{dr_0}) + (\\vec{dr_0} \\cdot \\vec{dv}) t + (\\vec{dv} \\cdot \\vec{dv}) t^2 &=& 4 R^2\n                \\label{equ:collision_time}\n            \\end{eqnarray}\n            This is a quadratic equation for $t$ which can be solved easily. If there are real roots to the equation, then\n            a collision occurs, and it occurs at the minimal possible $t$ value which is a solution to Equation~\\ref{equ:collision_time}.\n            %\\end{Ball-Ball Collision Detection}\n            \n            \\subsubsection{Ball-Wall Collision Detection}\n            Ball-wall collision detection is similar to ball-ball, except the ball is a distance one radius away from the wall when it collides.\n            Since the wall doesn't move, a different strategy had to be employed to detect when a ball-wall collision occurs. In this case,\n            both the and wall positions are described using parametric equations.\n            \\begin{eqnarray}\n                \\vec r = \\vec r_0 + (dt~\\vec v) T_b         \\label{equ:ball_parametric} \\\\\n                \\vec w = \\vec s + (\\vec f - \\vec s) T_w     \\label{equ:wall_parametric}\n            \\end{eqnarray}\n            Where, $\\vec r$ is the position of the ball, $\\vec r_0$ is the initial position of the ball, $\\vec v$ is the velocity of the ball,\n            $dt$ is the amount of time that will pass this frame; $\\vec w$ is a point on the wall, $\\vec s$ is one endpoint on the wall, and $\\vec f$\n            is the other endpoint of the wall. $T_b$ and $T_w$ are the parametric variables, and range between $0$ and $1$. \\\\\n            To determine when the ball hits the wall, where the ball hits must be determined first. The center of the ball hits the wall when\n            $\\vec r = \\vec w$, thus the ball actually collides with the wall when $\\vec r - R \\vec n = \\vec w$, where $\\vec n$ is the normal\n            vector to the wall. For simplicity below, we will ignore this offset value, as it is a fairly simple transformation. So, the collision\n            occurs when\n            \\begin{eqnarray}\n                r_{0_x} + (dt~v_x) T_b = s_x + (f_x - s_x) T_w  \\nonumber \\\\\n                r_{0_y} + (dt~v_y) T_b = s_y + (f_y - s_y) T_w  \\nonumber \\\\\n            \\end{eqnarray}\n            Solving for $T_b$ and $T_w$ gives\n            \\begin{eqnarray}\n                T_b &=& \\frac{(f_x - s_x)\\cdot(s_y - r_{0_y}) - (f_y - s_y)\\cdot(s_y - r_{0_y})}{(dt~v_y)\\cdot(f_x - s_x) - (dt~v_x)\\cdot(f_y - s_y)} \\nonumber \\\\\n                T_w &=& \\frac{(dt~v_x)\\cdot(s_y - r_{0_y}) - (dt~v_y)\\cdot(s_y - r_{0_y})}{(dt~v_y)\\cdot(f_x - s_x) - (dt~v_x)\\cdot(f_y - s_y)} \\nonumber \\\\\n            \\end{eqnarray}\n            If both $T_b$ and $T_w$ are between $0$ and $1$, then a ball-wall collision occurs. The point at which can be found by subbing in $T_b$ or $T_w$\n            into Equations~\\ref{equ:ball_parametric} or \\ref{equ:wall_parametric} respectfully. Then the amount of time passed can be solved for using Equations~\\ref{equ:position}.\n            %\\end{Ball-Wall Collision Detection}\n        %\\end{Event Detection}\n        \n        \\subsection{Event Handling and Velocity Updates}\n            \\subsubsection{Ball-Ball Collisions}\n            %\\end{Ball-Ball Collisions}\n            \n            \\subsubsection{Ball-Wall Collisions}\n            %\\end{Ball-Wall Collisions}\n            \n            \\subsubsection{Friction}\n            %\\end{Friction}\n        %\\end{Event Handling and Velocity Updates}\n    \n    %\\end{Physics}\n\n\\end{document}\n", "meta": {"hexsha": "19aeb7ecf3c8755d026a4d9082e5c9624a676d0a", "size": 13784, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/physics/angular/physics.tex", "max_stars_repo_name": "twentylemon/gl-billiards", "max_stars_repo_head_hexsha": "9561b4fa83e49a4deebd1f284cdf1839ae57fc22", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/physics/angular/physics.tex", "max_issues_repo_name": "twentylemon/gl-billiards", "max_issues_repo_head_hexsha": "9561b4fa83e49a4deebd1f284cdf1839ae57fc22", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/physics/angular/physics.tex", "max_forks_repo_name": "twentylemon/gl-billiards", "max_forks_repo_head_hexsha": "9561b4fa83e49a4deebd1f284cdf1839ae57fc22", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-03-31T00:26:11.000Z", "max_forks_repo_forks_event_max_datetime": "2016-03-31T00:26:11.000Z", "avg_line_length": 63.2293577982, "max_line_length": 180, "alphanum_fraction": 0.5903946605, "num_tokens": 3526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3214696216321147}}
{"text": "Monadic AAM begins with recognizing that the abstract semantics from\nsection~\\ref{section:AAMByExample:AbstractSemantics} look suspiciously monadic.\n%\nIn this section we will rewrite the exact same function but in monadic style.\n%\nAfter the exercise, the monad will be generalized in\nsection~\\ref{section:MonadicAAM:Generalizing} and this generalization will be\nexploited in section~\\ref{section:MonadicAAM:Optimizations}.\n\n\\subsubsection{Nondeterminism}\n\\input{sections/04MonadicAAM/00MonadicStyle/00Nondeterminism/Z.tex}\n\n\\subsubsection{State}\n\\input{sections/04MonadicAAM/00MonadicStyle/01State/Z.tex}\n", "meta": {"hexsha": "236d18e1efdf0e5c308c5a41e2b5e0fae8b53941", "size": 605, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "writeup-old/sections/04MonadicAAM/00MonadicStyle/main.tex", "max_stars_repo_name": "davdar/quals", "max_stars_repo_head_hexsha": "ebecd37d5cdda61a8bb250059076ca1dd5f3174c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-12-03T00:43:28.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-03T00:43:28.000Z", "max_issues_repo_path": "writeup-old/sections/04MonadicAAM/00MonadicStyle/main.tex", "max_issues_repo_name": "davdar/quals", "max_issues_repo_head_hexsha": "ebecd37d5cdda61a8bb250059076ca1dd5f3174c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "writeup-old/sections/04MonadicAAM/00MonadicStyle/main.tex", "max_forks_repo_name": "davdar/quals", "max_forks_repo_head_hexsha": "ebecd37d5cdda61a8bb250059076ca1dd5f3174c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3333333333, "max_line_length": 79, "alphanum_fraction": 0.8347107438, "num_tokens": 165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5389832354982647, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.32146746693211753}}
{"text": "% Created 2020-09-29 ter 18:34\n% Intended LaTeX compiler: pdflatex\n\\documentclass[11pt]{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage{lmodern}\n\\usepackage[T1]{fontenc}\n\\usepackage[top=3cm, bottom=2cm, left=3cm, right=2cm]{geometry}\n\\usepackage{graphicx}\n\\usepackage{longtable}\n\\usepackage{float}\n\\usepackage{wrapfig}\n\\usepackage{rotating}\n\\usepackage[normalem]{ulem}\n\\usepackage{amsmath}\n\\usepackage{textcomp}\n\\usepackage{marvosym}\n\\usepackage{wasysym}\n\\usepackage{amssymb}\n\\usepackage{amsmath}\n\\usepackage[theorems, skins]{tcolorbox}\n\\usepackage[style=abnt,noslsn,extrayear,uniquename=init,giveninits,justify,sccite,\nscbib,repeattitles,doi=false,isbn=false,url=false,maxcitenames=2,\nnatbib=true,backend=biber]{biblatex}\n\\usepackage{url}\n\\usepackage[cache=false]{minted}\n\\usepackage[linktocpage,pdfstartview=FitH,colorlinks,\nlinkcolor=blue,anchorcolor=blue,\ncitecolor=blue,filecolor=blue,menucolor=blue,urlcolor=blue]{hyperref}\n\\usepackage{attachfile}\n\\usepackage{setspace}\n\\usepackage{tikz}\n\\author{Gabriel Petrini}\n\\date{October 1st, 2020}\n\\title{Estimating Dynamic Models Without Solving Value Functions}\n\\begin{document}\n\n\\maketitle\n\\tableofcontents\n\n\n\\bibliography{References}\n\n\n\\section*{\\cite{hotzMiller1993}}\n\\label{sec:org9c92db5}\n\nDynamic discrete choice models are complicated to estimate because of the future value terms. \\citet{hotzMiller1993} show:\n\n\\begin{itemize}\n\\item Differences in conditional value functions \\(v_j-v_{j'}\\) can be mapped into \\uline{conditional choice probabilities} ( \\(p_j\\)'s )\n\\item We can pull the \\(p_j\\)'s from the data in a first stage\n\\item \\textbf{Empirical example:} optimal stopping with respect to couples' fertility\n\\end{itemize}\n\n\\subsection*{Difference in \\(v\\)'s and logit errors}\n\\label{sec:orgc62eac5}\n\nConsider an individual who faces two choices where the errors are T1EV. The probability of choice 1 is:\n\\begin{align*}\np_1&=\\frac{\\exp(v_1)}{\\exp(v_0)+\\exp(v_1)}\n\\end{align*}\n\nThe ratio of \\(p_1/p_0\\) is then:\n\\begin{align*}\n\\frac{p_1}{p_0}&=\\frac{\\exp(v_1)}{\\exp(v_0)} = \\exp(v_1 - v_0)\n\\end{align*}\nimplying that:\n\\begin{align*}\n\\ln(p_1/p_0)&=v_1-v_0\n\\end{align*}\n\n\\subsection*{General structure}\n\\label{sec:org916f1e4}\n\nThe inversion theorem of Hotz and Miller says that there exists a mapping, \\(\\psi\\), from the conditional choice probabilities, the \\(p\\)'s, into the differences in the conditional valuation functions, \\(v_j-v_k\\):\n\\begin{align*}\nV_{t+1}&=v_{0t+1}+\\mathbb{E}\\max\\{\\epsilon_{0t+1},v_{1t+1}+\\epsilon_{1t+1}-v_{0t+1},...,\\\\\n&\\phantom{\\text{----}}v_{{J}t+1}+\\epsilon_{{J}t+1}-v_{0t+1}\\}\\\\\nV_{t+1}&=v_{0t+1}+\\mathbb{E}\\max\\{\\epsilon_{0t+1},\\psi_0^1(p_{t+1})+\\epsilon_{1t+1},...,\\psi_0^{{J}}(p_{t+1})+\\epsilon_{{J}t+1}\\}\n\\end{align*}\n\nThe \\(p\\)'s can be taken from the data.  However:\n\n\\begin{enumerate}\n\\item We need the mapping, \\(\\psi\\),\n\\item We need to be able to calculate the expectations of the \\(\\epsilon\\)'s\n\\item We need to do something with the \\(v_0\\)'s\n\\end{enumerate}\n\\end{document}", "meta": {"hexsha": "744b0c6e06b510818845e6d29099bf5e101f6605", "size": 2977, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Notes/Lecture_08.tex", "max_stars_repo_name": "gpetrini/OU_Econometrics_III", "max_stars_repo_head_hexsha": "81b5f35999d6b10f65f84b3344593d1c28acf1e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Notes/Lecture_08.tex", "max_issues_repo_name": "gpetrini/OU_Econometrics_III", "max_issues_repo_head_hexsha": "81b5f35999d6b10f65f84b3344593d1c28acf1e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Notes/Lecture_08.tex", "max_forks_repo_name": "gpetrini/OU_Econometrics_III", "max_forks_repo_head_hexsha": "81b5f35999d6b10f65f84b3344593d1c28acf1e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4494382022, "max_line_length": 214, "alphanum_fraction": 0.7423580786, "num_tokens": 1042, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.32146745809859645}}
{"text": "\\chapter{Literature Review}\n\n\\section{Tensegrity Structures}\nIt is possible to design free-standing structures with axially loaded compression elements in a well crafted network of tensional elements.\nSuch an arrangement is called a tensegrity structure (tensile integrity). \nEach element of the structure experiences either pure axial compression or pure tension \\cite{BuckminsterFuller1975}\\cite{Snelson1965}.\nThe absence of bending or shear forces allows for highly efficient use of materials, \nresulting in lightweight, yet robust systems.\n\nBecause the struts are not directly connected, \ntensegrities have the unique property that externally applied forces distribute through the structure via multiple load paths. \nThis creates a soft structure, for a soft robot, out of inherently rigid materials.\nSince there are no rigid connections within the structure, there are also no lever arms to magnify forces. \nThe result is a global level of robustness and tolerance to forces applied from any direction.\n\n%Tensegrity structures are composed of axially loaded compression elements encompassed within a network of tensional elements, and thus each \n%element experiences either pure linear compression or pure tension.  As a result, individual elements can be extremely lightweight as there are no \n%bending or shear forces that must be resisted.  Because the struts are not directly connected, a unique property of tensegrity structures is how externally applied forces distribute through the structure \n%via multiple load paths, creating a system level robustness and tolerance to forces applied from any direction.  \n%Because there are no rigid connections within the structure, there are also no lever arms to magnify forces.  Instead, all experienced forces act linearly on each structural element.  Combined with the ability to diffuse forces globally, \nThis makes tensegrity robots inherently compliant and extremely well suited for physical interactions with complex and poorly modeled natural environments.  \nActive motion in tensegrity robots can be performed by changing cable lengths in parallel, \nenabling the use of many small actuators that work together, rather than individual heavy actuators which work in series.  \nThere are also many indications that tensegrity properties are prevalent throughout biological systems, \nand the morphology of the SUPERball that we are studying, \nespecially when carrying a payload, \nends up bearing a striking resemblance to the nucleated tensegrity model of cell structure~\\cite{Wang2009}\\cite{Wang2001}.\n\n\\section{Prior Work in Tensegrity Robotics Design}\nAn important advantage of tensegrity structures with respect to general pin-jointed structures is their increased mass-efficiency due to a high fraction of tensile members.\nTensile members are generally more mass-efficient as they do not need to resist buckling.\nA further advantage from a robotics perspective is that forces diffuse in a tensegrity.\nThere are no lever arms and torques do not accumulate at the joints as in a classic serial manipulator.\nForces distribute through multiple load paths, thus increasing robustness and tolerance to mechanical failure.\n\n%advantages\n%applications\nThe static properties of tensegrities have been thoroughly studied and some basic analysis is discussed in section \\ref{modeling}.\nOn the other hand, few examples are known of truly dynamic motion of these structures.\nEarly examples of kinematic motion include the work at EPFL's IMAC laboratory~\\cite{Fest2004}.\nSkelton and Sultan introduced algorithms for the positioning of tensegrity based telescopes and the dynamic control of a tensegrity flight simulator platform~\\cite{sultan2000tensegrity}.\nAlthough there were some early efforts at MIT's CSAIL lab, it wasn't until the work of Paul and Lipson at Cornell University that the concept of tensegrity robotics became widespread~\\cite{Paul2006a}.\nPaul and Lipson were the first to study the properties of dynamic tensegrity structures in hardware and simulation.\nA few years later Fivat and Lipson designed the IcoTens, a small actuated tensegrity icosahedron robot, but did not publish results.\nIn recent years, the BIER lab at the University of Virginia has been studying Central Pattern Generator based control for tensegrity based fish tails,\nwhich is closely related to the control architectures proposed for SUPERball~\\cite{Caluwaerts2013rsif,Bliss2012}.\nMirats-Tur has presented design and controls work on various other tensegrity morphologies that have been tethered or fixed to the ground~\\cite{GraellsRovira2009,miratstur2011athree-dof}.\nAt Union College, Rieffel and colleagues are following an interesting line of work by considering vibration based actuation for small tensegrities~\\cite{khazanov2014developing}.\nRelated work was presented by B\\\"ohm and Zimmermann, who demonstrated controlled locomotion of vibration driven tensegrity robots with a single actuator~\\cite{bohm2013vibration}.\nFinally, Shibata, Hirai and colleagues have developed pneumatically actuated rolling tensegrity structures~\\cite{Shibata2009}. \n%goal\n\nBuilding upon these works, the \\SB{} project seeks to push forward the tensegrity robotics field and develop truly untethered, highly dynamic and compliant robots exploiting the aforementioned advantages.\n\n\\section{Tensegrity Robotics for Space Exploration}\n%NASA is supporting research into tensegrity robotics to create robots with many of the same qualities that benefit biological systems.  \nThe high strength-to-weight ratio of tensegrity structures is very attractive due to the impact of mass on mission launch costs. \nLarge tensegrity structures have been shown to be deployable from small compact configurations which enable them to fit into space constrained launch fairings.   \nWhile the above qualities have inspired studies of deployable antennae and other large space structures~\\cite{Tibert2002}, \nit is in the realm of planetary exploration that we see the most significant role for many of the unique force distribution qualities of tensegrity robots.  \nThe NIAC project currently funding this research~\\cite{NIACfinalreport} specifically studies landing and surface mobility of tensegrities,\nexploiting the controllable compliance and force distribution properties which make for reliable and robust environmental interactions.  \n\nThe main goal is to develop tensegrity probes with an actively controllable tensile network\n to enable compact stowage for launch, followed by deployment in preparation for landing. \nDue to their natural compliance and \nstructural force distribution properties, tensegrity probes can safely absorb \nsignificant impact forces, enabling high speed Entry, Descent, and Landing \n(EDL) scenarios where the probe itself acts much like an airbag.  However, \nunlike an airbag which must be discarded after a single use, the tensegrity \nprobe can actively control its shape to provide compliant rolling mobility \nwhile still maintaining the ability to safely absorb impact shocks that might \noccur during exploration.  This combination of functions from a single \nstructure enables compact and lightweight planetary exploration missions \nwith the capabilities of traditional wheeled rovers, but with a mass and \ncost similar or less than a stationary probe.   \n\nTherefore, a large fraction of the overall weight (as measured at atmospheric entry) of a tensegrity mission can be used for the scientific payload \ndue to the dual use of the structure as a lander and a rover. \nThis allows for cheaper missions and enable new forms of surface exploration that utilize the natural tolerance to impacts of tensegrities~\\cite{Vytas_IPPW_2013}.\n\n% Because  of  the  limited  research  into  actuated  tensegrity\n% robotics,   many   design   aspects   have   yet   to   be   carefully\n% studied. To date, the majority of constructed tensegrity robots\n% have  been  simple  prototypes  using  servo  motors,  limited\n% sensing,  and  are  often  tethered  for  power  and  control  [5].\n% Others have had fewer limbs than the SUPER ball, or have\n% been  secured  to  the  ground  as  opposed  to  free-standing\n% [6][7]. Some related approaches utilize tensegrity as part of a\n% larger, more complicated system, but not as the primary loco-\n% motion method [8]. Others have created designs that do not\n% use direct cable actuation, as in the SUPER ball, but instead\n% have  more  limited  forms  of  locomotion  through  vibration\n% [9][10]. Finally, the most similar designs to the SUPER ball\n% have not been engineered to specific design requirements nor\n% have  the  advanced  sensing  framework  needed  for  controls\n% testing [11]\n%\n% The  high  strength-to-weight  ratio  of  tensegrity  structures\n% is very attractive due to the impact of mass on mission launch\n% costs.  Large  tensegrity  structures  have  been  shown  to  be\n% deployable from small compact configurations which enable\n% them to fit into space constrained launch fairings. While the\n% above qualities have inspired studies of deployable antennae\n% and  other  large  space  structures  [12],  it  is  in  the  realm\n% of  planetary  exploration  that  we  see  the  most  significant\n% role  for  many  of  the  unique  force  distribution  qualities  of\n% tensegrity  robots.  A  recent  NIAC  project  [13]  specifically\n% studies  landing  and  surface  mobility  of  tensegrities,  ex-\n% ploiting  the  controllable  compliance  and  force  distribution\n% properties which make for reliable and robust environmental\n% interactions.\n% The   main   goal   is   to   develop   tensegrity   probes   with\n% an  actively  controllable  tensile  network  to  enable  compact\n% stowage  for  launch,  followed  by  deployment  in  preparation\n% for  landing.  Due  to  their  natural  compliance  and  structural\n% force  distribution  properties,  tensegrity  probes  can  safely\n% absorb significant impact forces, enabling high speed Entry,\n% Descent, and Landing (EDL) scenarios where the probe itself\n% acts  much  like  an  airbag.  However,  unlike  an  airbag  which\n% must  be  discarded  after  a  single  use,  the  tensegrity  probe\n% can  actively  control  its  shape  to  provide  compliant  rolling\n% mobility  while  still  maintaining  the  ability  to  safely  absorb\n% impact  shocks  that  might  occur  during  exploration.  This\n% combination  of  functions  from  a  single  structure  enables\n% compact and lightweight planetary exploration missions with\n% the capabilities of traditional wheeled rovers, but with a mass\n% and cost similar or less than a stationary probe.\n%\n% Therefore, a large fraction of the overall weight (as mea-\n% sured  at  atmospheric  entry)  of  a  tensegrity  mission  can  be\n% used  for  the  scientific  payload  due  to  the  dual  use  of  the\n% structure  as  a  lander  and  a  rover.  This  allows  for  cheaper\n% missions  and  enable  new  forms  of  surface  exploration  that\n% utilize the natural tolerance to impacts of tensegrities [14].\n%\n% Buckminster Fuller [1] and the artist Kenneth Snelson [2]\n% initially  explored  tensegrity  structures  in  the  1960s.  Until\n% the  mid-1990s  the  majority  of  tensegrity  related  research\n% was  concerned  with  form-finding  [15]  and  design  analysis\n% of  static  structure  [16][17].  More  recently,  active  control\n% efforts  for  tensegrities  began  to  emerge  [18],  as  well  as\n% descriptions  of  the  dynamics  of  tensegrity  structures  taking\n% the connectivity pattern into account [17].\n% The tensegrity principle allows for compliance and multi-\n% path load distribution, which is ideal for physical interaction\n% with  the  environment.  However,  these  aspects  also  present\n% significant  challenges  to  traditional  control  approaches.  A\n% recent  review  [19]  shows  that  there  are  still  many  open\n% problems in actively controlling tensegrities, especially when\n% interacting  with  an  environment  during  locomotion  or  ma-\n% nipulation  tasks.  Though  work  has  been  done  to  control  a\n% tensegrity  to  change  into  a  specified  shape  [20],  practical\n% determination  of  the  desired  shape  itself  is  an  ongoing\n% challenge.  Recently,  locomotion  of  icosahedral  tensegrity\n% robots  through  body  deformation  was  demonstrated  [21].\n% Other work has addressed collision between rigid tensegrity\n% elements during control generation [22][23].\n% The  approach  taken  by  the  NASA  Dynamic  Tensegrity\n% Robotics  Lab  builds  on  this  by  developing  body  defor-\n% mation  control  algorithms  based  on  central  pattern  gen-\n% erators  [24][25],  distributed  learning,  reservoir  computing,\n% and  genetic  algorithms  [26],  instead  of  traditional  linear\n% and  nonlinear  systems  approaches.  To  date,  our  approach\n% has  shown  promising  results  at  productively  harnessing  the\n% potential  of  complex,  compliant,  and  nonlinear  tensegrity\n% structures.\n\n% \\section{Motivation an Goal}\n", "meta": {"hexsha": "90ec973e692fd5b81a51ceb740ce1fe131d565be", "size": 13001, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Advancement/tex/LitReview.tex", "max_stars_repo_name": "JEB12345/Advancement_UCSC", "max_stars_repo_head_hexsha": "92c7f0bdaecde6bce2c6ee47d401e0335e449d6b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Advancement/tex/LitReview.tex", "max_issues_repo_name": "JEB12345/Advancement_UCSC", "max_issues_repo_head_hexsha": "92c7f0bdaecde6bce2c6ee47d401e0335e449d6b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Advancement/tex/LitReview.tex", "max_forks_repo_name": "JEB12345/Advancement_UCSC", "max_forks_repo_head_hexsha": "92c7f0bdaecde6bce2c6ee47d401e0335e449d6b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 76.4764705882, "max_line_length": 239, "alphanum_fraction": 0.7894008153, "num_tokens": 3033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.3214674580985964}}
{"text": "\\documentclass{report}\n\n\\usepackage{tikz}\n\\usepackage{graphicx}\n\\usepackage{amsmath}\n\\usepackage{palatino}\n\\usepackage{siunitx}\n\\usepackage{hyperref}\n\\usepackage{listings}\n\n% tables\n\\usepackage{booktabs}\n\\usepackage{tabularx}\n\n% begin tikz\n\\usepackage{tikz}\n\\usetikzlibrary{graphs,graphdrawing,matrix,decorations.pathreplacing}\n\\usegdlibrary{layered}\n% end tikz\n\n% biblio\n\\usepackage[style=authoryear]{biblatex}\n\\addbibresource{references.bib}\n\n\\input{macros.tex}\n\n\\title{Moist Convection ML}\n\\author{Noah D. Brenowitz}\n\\date{\\today}\n\\usepackage{dsfont}\n\\newcommand{\\1}[1]{\\mathds{1}\\left[#1\\right]}\n\\begin{document}\n\\maketitle\n\\tableofcontents\n\n\\chapter*{Notation and Physical Constants}\n\\label{ch:notation}\n\\begin{table}\n  \\centering\n  \\begin{tabularx}{\\textwidth}{lX}\n    \\toprule\n    Symbol & Description\\\\\n    \\toprule\n    $n$ & number of samples \\\\\n    $m$ &  number of features\\\\\n    $X$ & $s \\times m$ data matrix of predictors\\\\\n    $Y$ & $s \\times \\cdot $ data matrix of predictands\\\\\n    \\bottomrule\n  \\end{tabularx}\n  \n  \\caption{List of common notations}\n  \\label{tab:constants}\n\\end{table}\n\n\\begin{table}\n  \\centering\n  \\begin{tabularx}{\\textwidth}{lcX}\n    \\toprule\n    Variable & Value & Description\\\\\n    \\toprule\n    $c_p$ & \\SI{1004}{J/K/kg} & Heat capacity of air\\\\\n    $L_v$ & \\SI{2.5e6}{J/kg} & Latent heat of vaporization\\\\\n    \\bottomrule\n  \\end{tabularx}\n  \n  \\caption{List of physical constants}\n  \\label{tab:constants}\n\\end{table}\n\\chapter{Introduction}\n\n\\chapter{Training Data}\n\n\\section{System for Atmospheric Modeling}\n\\label{sec:sam}\n\nThe System for Atmospheric Modeling (SAM) uses a different set of prognostic\nequations \\autocite{Khairoutdinov2003}. These are given by\n\n\\begin{subequations}\n  \\label{eq:sam}\n  \\begin{align}\n    &\\totd{\\bu}{t} + ( f  + \\beta y) \\mathbf{k}\\times \\bu = - \\nabla \\phi \\\\\n    &\\totd{w}{t} = -\\nabla \\phi + g B \\label{eq:w-full}\\\\\n    &\\totd{h_L}{t}  = Q_{rad}  - \\frac{1}{\\rho_0} \\pd{}{z} \\left( L_c P_r + L_s P_s + L_s P_g \\right)\\\\\n    &\\totd{q_T}{t} = -  \\dot{q}_p^{\\text{micro}} \\label{eq:sam-qT}\\\\\n    &\\totd{q_p}{t} = \\frac{1}{\\rho_0} \\pd{}{z} \\left(  P_r +  P_s + P_g \\right) + \\dot{q}_p^{\\text{micro}}\\\\\n    &\\nabla \\cdot \\bu + \\frac{1}{\\rho_0} \\pd{\\rho_0 w}{z}  = 0.\n  \\end{align}\n\\end{subequations}\nI have neglected the sub-grid-scale flux terms in the formulation above since\nthey are not relevant to the problem considered in this report. The temperature\nand humidity variables introduced in the previous section have been replaced\nhere by\n\\begin{description}\n\\item[Liquid/ice water static energy] $h_L = c_p T +gz - L_c (q_c + q_r) - L_s\n  (q_i + q_s + q_g)$,\n\\item[Total nonprecipitating water] $q_T = q_v + q_c + q_i$, and\n\\item[Total precipitating water] $q_p = q_r + q_s + q_g$.\n\\end{description}\nNote that $h_L$ is only an appropriate variable when hydrostatic balance or\nanelastic equations are satisfied. Otherwise, potential temperature should be\nused. There are a number of diagnostic equations which can be solved to\ndetermine the temperature, and all the mixing ratios for the different species\nof precipitating and non-precipitating water. Perhaps most importantly, the\nwater vapor is assumed to be at or below an approximate saturation value so that\n\\[q_v = \\min(q_T, q_{sat}(p_0, T)),\\]\nwhere\n\\[ q_{sat} = q_{sw} (1-\\omega_i) + \\omega_i q_{si}\\]\nis a convex combination of the saturation mixing ratios of vapor with respect to\nice and liquid water. \n\nA consequence of this diagnostic relation is that the latent\nheating term due to condensation is not explicitly calculated. Instead, SAM\nmodels the microphysical processes which govern the conversion from condensate\n($\\text{cloud water} + \\text{cloud ice}$) to precipitation ($\\text{rain} +\n\\text{snow} + \\text{grauppel}$). These processes are given by\n\\[\n  \\dot{q}_p^{\\text{micro}} = \\text{accretion} - \\text{evaporation} + \\text{autoconversion}.\n\\]\nA nice paper by \\textcite{hernandez-duenas_minimal_2013} contains a more thorough\ndiscussion of a similar set of microphysical equations, which can be helpful for\ngaining intuition. Additional details about the diagnostic relations linking the\nwater species and the prognostic variables $q_T$, $h_L$, and $q_p$ are available\nin Appendix \\ref{sec:diag-q} and in the original SAM paper by \\textcite{Khairoutdinov2003}.\n\nThis formulation is convenient for numerical modeling purposes, but\nmoist-convective processes are often understood as a coupling between dry\ndynamics and moist variables because the bouyancy is related primarily to\ntemperature, rather than moist static energy.\nFor instance, the circulation due to the monsoons and MJO can be understood\nroughly as the response to a imposed heating pattern \\autocite{Gill1980}, and\nthe multiscale theories of Biello and Majda rely upon asympotic analysis of the\nlatent heating.\n\n\\section{Near-global Model Configuration}\n\\label{sec:model-config}\n\nWe configure the model in the same way as \\textcite{Bretherton2015}. \n\nThe size of the domain is (5120, 2560) grid points with a grid size of\n\\SI{4}{\\km}, which in physical units is \\SI{20480}{\\km} by \\SI{12800}{\\km}.\nWe define the central 2560 kilometers in the y-direction as the tropics. \nThis is 16 coarse grained grid boxes out of total of 64, which is [24, 40) in\n0-indexed notation.\n\n\\begin{figure}[ht]\n  \\centering\n  \\includegraphics{images/cld.png}\n  \\caption{\\label{fig:cld}Snapshot of the cloud cover fraction field from the NGAqua simulation.}\n\\end{figure}\n\n% \\begin{tikzpicture}[scale=.5]\n%   \\draw (0,0) rectangle (20.480, 12.800);\n%   \\draw[step=.160] (0,0) grid (20.480, 12.800);\n% \\end{tikzpicture}\n\n\n\\section{Data Availability}\n\nThe coarse-grained NGAqua data is available on the olympus file server in the UW Atmospheric Sciences department as well as in a google cloud storage bucket:\n\\verb|nbren12-largedata/data/id/726a6fd3430d51d5a2af277fb1ace0c464b1dc48|\n\n\\section{Model Outputs}\n\nThe model outputs a collection of three dimensional and two dimensional fields\nat a sampling interval of three hours. \nBecause the model uses an Arakawa C-Grid, some of the variables are staggered\nwhile others are centered. \nFigure \\ref{fig:arakawa-c-grid} provides an illustration of this.\n\n\\begin{figure}\n  \\centering\n\n  \\begin{tikzpicture}[scale=2]\n\n\n    \\draw (-1, 0) -- (3,0);\n    \\draw (0, -1) -- (0,3);\n    \\draw (2, -1) -- (2,3);\n    \\draw (-1, 2) -- (3,2);\n    \n    \\node at (1,1) {$q_v$, $q_p$, $q_n$, $\\phi$, $s_l$};\n    \\node[fill=white] at (1,0) {$u_{i}$};\n    \\node[fill=white] at (1,2) {$u_{i+1}$};\n    \\node[fill=white] at (2,1) {$v_{i+1}$};\n    \\node[fill=white] at (0,1) {$v_{i}$};\n  \\end{tikzpicture}\n\n  \\caption{Arakawa C-Grid. \n    The velocities are represented on the faces, while the scalar quantities are\n    cell-centered. \n    This plot only shows the horizontal grid, but the vertical velocity $w$ is\n    staggered in the vertical direction.}\n  \\label{fig:arakawa-c-grid}\n\\end{figure}\n\n\n\\section{Coarse-graining and Destaggering}\n\\label{sec:post-processing}\n\nThe main post processing steps are\n\n\\begin{enumerate}\n\\item Coarse-graining, and \n\\item computing the apparent heat and moisture source due to convection.\n\\end{enumerate}\n\nThe coarse graining procedure is relatively straightforward. \nSAM outputs the data on a grid with a \\SI{4}{\\km} resolution. \nWe can describe this coarse-graining mathematically. \nLet $f(x,y,z,t)$ be some three dimensional field outputed by the atmospheric\nmodel. \nThen, divide the domain into coarse grained grid boxes $C_{i,j}$ which represent the\ntypical GCM grid box. These grid boxes are defined by\n\n\\[\n  C_{i,j} = \\{(x,y):   j \\Delta x \\leq x < (j+1) \\Delta x\n  \\quad \\cap\\quad j \\Delta y \\leq y < (j+1) \\Delta y \\},\n\\]\nwhere $\\Delta x$ and $\\Delta y$ are the size of the GCM grid box (e.g.\n\\SI{160}{\\km}). Averaging over these grid boxes gives the coarse-grained field\n\\[\n  \\overline{f}_{i,j} = \\int_{C_{ij}} f dA.\n\\]\n\n\\begin{figure}\n  \\centering\n  \\begin{tikzpicture}\n    \\draw (0,0) rectangle (6,6);\n    \\draw[step=1.5mm] (0,0) grid (6,6);\n    \\draw[decorate,decoration={brace,amplitude=10pt,mirror,raise=4pt}] (0,0) -- (6,0);\n    \\node at (3,-.7cm) {$\\Delta x = \\SI{160}{\\km}$};\n  \\end{tikzpicture}\n  \\caption{Coarse-graining procedure. The coarse-grained grid boxes have a\n    length of \\SI{160}{km} and contains $40^2$ fine scale grid boxes.}\n  \\label{fig:coarse-grain}\n\\end{figure}\n\nFigure \\ref{fig:preprocess} contains a flow chart describing the preprocessing pipeline.\n\n\\begin{figure}\n  \\centering\n  \\begin{tikzpicture}[ every node/.style={draw} ]\n    \\graph[layered layout]{\n\n      Input data -> Destagger $u$ and $v$ -> a/ Coarse grain all variables;\n      Input data -> a; a -> w/Destagger coarse grained $\\overline{w}$; {a, w} ->\n      Reshape data and fit models!\n\n    };\n  \\end{tikzpicture}\n  \n  \\caption{Preprocessing pipeline flowchart}\n  \\label{fig:preprocess}\n\\end{figure}\n\\section{Apparent Heating and Moistening}\n\\label{sec:q1q2}\n\nIn SAM, the conserved variables are the liquid-ice static energy and the total non-precipitating water. The liquid static energy is given in temperature units by \n\\[ s_l = T + \\frac{g}{c_p} z - L_c(q_n + q_p),\\]\nwhere $q_n$ is the total cloud condensate, $q_p$ is precipitation, and $L_c$ is the latent heat of condensation. This definition is an approximation which neglects the presence of the frozen phase of water. The total water non-precipitating water is just given by \n$q_t = q_v + q_n.$\n\nThen, for our purposes, the apparent heat source is given by\n\\[Q_1 = \\partial_t {\\bar{s}_l} + \\overline{ \\mathbf{v} }\\cdot \\overline{\\nabla} \\bar{s}_l, \\]\nand the apparent drying is given by\n\\[Q_2 = - \\frac{L_c}{c_p} \\left[\\partial_t {\\bar{q}_t} +\\overline{ \\mathbf{v} } \\cdot \\overline{\\nabla} \\bar{q}_t\\right].\\]\nThe factor $-\\frac{L_c}{c_p}$ is used to ensure that this quantity also has units K/day. Comparing to the original prognostic equations for SAM shows that $Q_1$ contains the source term  $Q_r$ to the temperature equation which represents radiative transfer, which is usually a cooling tendency. For the purposes of cumulus parametrization, it might be possible to assume this is known from other sources (e.g. a radiative transfer code such as RRTMG). Therefore, we will also define the convective component of the apparent heating as $Q_{1c} = Q_1 - Q_r$. \n\nAll the differential operators in these two expression represent a finite\ndifferencing taken on the coarse grid, and we will use centered differences to\ncompute these. Specifically, the formulas for the advection terms are given\nby\n\\renewcommand{\\bf}{\\bar{f}_{i,j}}\n\n% \\[(A_f)_{i,j} = \\left( \\bar{f}_{i+1,j,k} - \\bar{f}_{i-1,j,k} \\right) \\frac{\\bar{u}_{i,j,k}}{2 \\Delta x}\n%               + \\left( \\bar{f}_{i,j+1,k} - \\bar{f}_{i,j-1,k} \\right) \\frac{\\bar{v}_{i,j,k}}{2 \\Delta y}\n%               + \\left(  \\bar{f}_{i,j,k+1} - \\bar{f}_{i,j,k-1} \\right) \\frac{\\bar{v}_{i,j,k}}{z_{k+1} - z_{k-1}}\n%             \\]\n\n\\begin{align}\n  (A_f)_{i,j,k} = &\\left( \\bar{f}_{i+1,j,k} - \\bar{f}_{i-1,j,k} \\right) \\frac{\\bar{u}_{i,j,k}}{2 \\Delta x}\\\\\n              +&\\left( \\bar{f}_{i,j+1,k} - \\bar{f}_{i,j-1,k} \\right) \\frac{\\bar{v}_{i,j,k}}{2 \\Delta y}\\nonumber\\\\\n              +& \\left(  \\bar{f}_{i,j,k+1} - \\bar{f}_{i,j,k-1} \\right) \\frac{\\bar{w}_{i,j,k}}{z_{k+1} - z_{k-1}}.\\nonumber\n\\end{align}\nWe have taken advantage of the constant horizontal grid spacing and the\ncollocation of all the coarse grained variables.\n\nThe numerical estimates of $Q_1$ and $Q_2$ depend on these simple expressions.\nThe apparent heating is given by\n\\begin{equation}\n  \\label{eq:q1-num}\n  Q_1^{n+1/2} = \\frac{\\bar{s_l}^{n+1} - \\bar{s_l}^{n} }{\\Delta t}\n            +  A^{n}_{s_l} .\n\\end{equation}\nwhere the spatial index $i,j,k$ has been dropped. Similarly, the apparent\ndrying is given by\n\\begin{equation}\n  \\label{eq:q2-num}\n  -\\frac{c_p}{L_v} Q_2^{n+1/2} = \\frac{\\bar{q_T}^{n+1} - \\bar{q_T}^{n} }{\\Delta t}\n            +  A^{n}_{q_T} .\n\\end{equation}\nThe factor $\\frac{c_p}{L_v}$ ensures that $Q_2$ has units of temperature over\ntime, just like $Q_1$. These and other important physical quantities are\ndescribed in \\autoref{tab:constants}.\n\n\\section{Reshaping data}\n\nMost machine learning algorithms require two dimensional matrices as inputs, but\nthe SAM produces four-dimensional datasets of humidity, temperature, and other\natmopsheric variables. \nTo reshape this multivariate three-dimensional data into a single vector for\nmachine learning, we must define which dimensions of data are physically\nrelevant. \nWe call these ``feature dimensions'' and the remaining non-relevant dimensions\n``sample dimensions''. The columns of the two-dimnsional data matrix $X$ will\ncorrespond to samples taken along the sample dimensions, and the rows will\ncorrespond to data taken from the feature dimensions. \n\nBecause the time-scale of deep atmopsheric convection is so fast, the inputs for\nthe convection scheme should be non-local in the vertical direction, so the only\nfeature dimension is $z$. \nThe remaining dimensions of the data---$x$, $y$, and time---are the sample\ndimensions. \nTherefore, given a single field of the data $f[x,y,z,t]$, then a particular sample vector\n\\[\n  \\mathbf{f}[x,y,t] =\n    \\begin{bmatrix}\n      f[x,y,1,t] \\\\\n      f[x,y,2,t] \\\\\n      \\vdots\\\\\n      f[x,y,n_z,t]\n    \\end{bmatrix}\n\\]\nis defined for each horizontal location and time point. Then, we can tabulate\nall these vectors in a two dimensional array given by\n\\newcommand{\\fb}{\\mathbf{f}}\n\\[\n  X_f = \n  \\begin{bmatrix}\n    \\fb[1,1,1], \\fb[2,1,1], \\ldots,\\fb[x,y+1,t], \\fb[x+1,y+1,t],\\ldots,\\fb[n_x, n_y,\n    n_t]\n  \\end{bmatrix}\n\\]\n\nIn addition to being 4 dimensional, the data are multivariate, and contains\nmultiple atmopspheric fields, with different physical units. For most of our\nanalysis, we use $q_T$ and $s_L$ to predict the amount of latent heating due to\nconvection. To handle the multivariate case, we simply stack the data matrices\nfor each variable vertically, so that the full data matrix $X_{\\{s_l, q_T\\}}$ is given by\n\\[\n  X_{\\{s_l, q_T\\}}=\\begin{bmatrix}\n    X_{s_l}\\\\\n    X_{q_T}\n  \\end{bmatrix}.\n\\]\nWe define data matrices for more than two variables.\n\nFinally, we must introduce the temporal shifting operator, which we will use to\ncreate models for the dynamics. When time is the only sample dimension, this\noperator is trivial, but having multiple sample dimensions complicates matters.\nIn any case, the time shifting  operator $L$ is defined by\n\\[\n  LX =\n  \\begin{bmatrix}\n    \\mathbf{x}[1,1,2],\\ldots,\\mathbf{x}[x, y, t+1], \\ldots, \\mathbf{x}[n_x, n_y, t]\n  \\end{bmatrix}.\n\\]\nBecause we use this operator extensively below, we will adopt the notation that $X' =\nLX$, so that $X'$ are the data shifted forward by one time sample.\n\n\\chapter{Methods}\n\n\\section{Machine Learning for dynamical systems}\n\nThe ultimate goal of this work is to estimate or simulate the unknown source\nterms. Essentially we need an effective way to draw samples\nfrom\n\\[ \\rho(x_{t+\\Delta t}, t + \\Delta t |x_{[s < t]}).\\] There are two clear problems here. \nFirst, this probability distribution depends on the whole time course of\n$x$ leading up to time $t$. \nIdeally we want to create a Markov description of the data, a task which is\nknown as \\emph{embedding}. \nSupposing $z_t$ is a suitable embedding of $x_t$---Takens''' delay embedding is a natural choice---the conditional pdf becomes\n\\[\\rho(z_{t+\\Delta t}, t+ \\Delta t| z_t, t),\\]\nand we must characterize this conditional density.\nWe also might prefer to use the infinitesmimal generator\n\\[L_z = \\lim_{\\Delta t \\rightarrow 0} \\frac{\\rho(z_{t+\\Delta t}, t+ \\Delta t| z_t,\n    t) - \\delta(z_{t+\\Delta t} - z_t) }{\\Delta t}.\\]\n\nThere are also a series of functions $f_i$ which we trust capture some aspect of\nthe dynamics. \nFor example, we should trust the dynamical core, turbulence, and radiation\nschemes, and not attempt to \\emph{learn} a GCM from scratch.\nBut the functions $f_i$ are not specified in the pdf at all, and we might not\neven know them with perfect accuracy. We can include them in the statistical\nmodel as follows\n\\[\\rho(z_{t+\\Delta t}, t+ \\Delta t| z_t, y_i, t) p(y_i|z_t, t) \\]\nwhere $y_i = f_i(z_t) + \\epsilon_i$.\n\n\n\n\n\\section{Maximum Covariance Analysis}\n\\label{sec:mca}\n\nMaximum Covariance Analysis (MCA) finds the modes which maximize the cross\ncovariance between an input matrix $X$ and output matrix $Y$. \nIf the mean of $X$ and $Y$ along the columns vanishes, then the covariance\nmatrix is given by\n\\[C=X'Y.\\]\nThen, we take an SVD of this matrix to get\n\\[C=U\\Sigma V'.\\] We will call the columns of $U$ the input \\emph{loadings}, and\nthe columns of $V$ the output loadings. \nThe loading vectors each orthornmal bases of the input and output features\nspaces. \nBy projecting the data onto these loadings, we obtain the input and output\n\\emph{scores}, which are respectively defined by $S_x = X U''''''$ and $S_y=YV'$. \n\nFor our analysis, we consider the case where $X$ is the matrix of\nhorizontal-temporal samples of profiles of $q_T$ and $s_L$, and $Y$ contains\nsamples of $Q_{1c}$ and $Q_2$. In other words, there are $2\\cdot n_z$ columns of\n$X$ and $Y$ corresponding. Moreover, the columns of $X$ and $Y$ are weighted by\nthe square root of the corresponding layer mass. The behavior of the NGAqua\ndataset appears to reduce to a two mode structure, and we show the behavior of\nthese two modes in Figures \\ref{fig:mca-loadings} and \\ref{fig:mca-ts}.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[height=5in]{images/mca_modes.pdf}\n  \\caption{Loadings for first two MCA modes.}\n  \\label{fig:mca-loadings}\n\\end{figure}\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=\\textwidth]{images/mca_ts.png}\n  \\caption{Time series of first MCA mode scores for a single location at the\n    equator. \n    Input scores (top) and output scores (bottom). \n    The sign and amplitude of these modes is given by the raw output of the\n    scheme, and does not correspond to the plots in \\autoref{fig:mca-loadings}.}\n  \\label{fig:mca-ts}\n\\end{figure}\n\n\\section{Linear models}\n\n\\begin{figure}[ht]\n  \\centering\n  \\includegraphics[width=\\textwidth]{images/lrf_lm.png}\n  \\caption{\\label{fig:lrf-lm}Linear response matrix for linear regression\n    pipeline. \n    The full outputs are regressed onto the columns of $X$ with a variance\n    larger than .001. \n    This thresholding procedure ensures that the uppper atmosphere\n    moistures---which vanishes---does not enter the regression analysis.} \n\\end{figure}\n\n\\begin{figure}[ht]\n  \\centering\n  \\includegraphics[width=\\textwidth]{images/lrf_mca4.png}\n  \\caption{\\label{fig:lrf-mca}Linear response matrix for MCA linear regression\n    pipeline. \n    The first step is to compute the X scores, and then the full Y outputs are\n    regressed onto these scores.}\n\\end{figure}\n\n\n\\begin{figure}[ht]\n  \\centering\n  \\includegraphics[width=5in]{images/mca-regression-coef}\n  \\caption{\\label{fig:mca-regression-coef}Regression coefficients for each\n    whitened MCA mode. \n    These are the resulting heating patterns if the z-score of the given mode is\n    1.0. \n    These patterns do not need to look like output loadings shown in\n    \\autoref{fig:mca-loadings}, despite their similarity.}\n\\end{figure}\n\n\\section{Time stepping with Neural Networks}\n\nThe data we are using are only evaulated with a coarse sampling time step of 3 hours. On the other hand, we will probably use 10-20 minute time step for the coarse resolution model. This means that the dynamical model we are trying to fit is \n$$ x^i_{n+1} = \\underbrace{f(f(\\ldots f}_{\\text{m times}}(x^i_n))) + \\int_{t_n}^{t_{n+1}} g(x(t), t) dt$$ \nwhere $i$ is the horizontal spatial index, and $n$ is the time step. The number of times the function $f$ is applied is $m=\\frac{\\Delta t}{h}$ where $h$ is the GCMs time step, and $\\Delta t$ is the sampling interval of the stored output. The integral on the right represents the approximately known terms such as advection, and $f$ represents the unknown source terms.\n\nWe solve a minimization problem to find $f$. This is given by \n$$\n\\min_{a} \\lim_{m \\rightarrow \\infty} \\sum_{i,n} ||x^{i}_{n+1} - F^{(m)} x^i_{n} - g_n^{i}||_W^2 \\quad \\text{s.t.}\\quad F^{(m)}(\\cdot) = \\underbrace{f(f(\\ldots f}_{\\text{m times}}(\\cdot))),\\ f(x) = x +  \\frac{ \\Delta t}{m} a(x).\n$$\nIntuitively, the forward operator $F^{(m)}$ is the result applying $m$ forward euler steps to the system $a$.\n\nLet's try performing this fit. First, we need to import the appropriate models, and load the data\n\n\\subsection{Literature Review}\n\\label{sec:blowup-rnn}\n\n\nUnfortunately, applying a function repeatedly like often causes solutions to\nexplode. \nThis issue is discussed known in recurrent neural network (RNN) community\n\\autocite[See Ch. \n10.7]{Goodfellow2016}.\nThey discuss something known as Echo State Networks (ESN), which must repeatedly\nconfront this issue. Apparently, this blow up can be controlled in two ways.\n\\begin{enumerate}\n\\item Control the spectral radius of the Jacobian. I.e. ensure that\n  \\[\\rho \\left( \\frac{\\partial x^{n+1}}{\\partial x^n} \\right) < 1\\]\n  \n\\item Use squashing nonlinearities like $\\tanh$, and allow larger spectral radius.\n\\end{enumerate}\n\nI still need to figure out how exactly they control the spectral radius of\nneural network.\n\nThe deep learning literature discusses the issue of exploding gradients as more\nan issue with back-propagation of gradients than forward propagation or\npredictions. However, I think the solutions are the same.\n\n\n\\section{Time stepping}\n\nWant to formulate a neural network scheme which has inputs that do not depend on the time step. \nThe various physical processes in a climate model update the state sequentially, so that each process sees a state updated by the previous process.\nUnfortunately, these processes can dramatically change the state by up to a few degrees K over a large time step, which makes the inputs for the neural networks scheme depend on the time step.\nThis is not much of an issue for physics based parameterizations, but machine learning schemes cannot be extrapolated to different time steps then they were trained on if their inputs depend on the time steps.\nTherefore, we need to make the inputs to an ML scheme invariant to the time step, which we accomplish with the following time-stepper\n\\begin{align}\n x^* &= x + h g(x, t) \\\\\n x^{+} &= x^* + h f(x, g(x, t), t; \\alpha).\n\\end{align}\n\n\n\n\\section{Enforcing physical constraints}\n\n\\subsection{Positive humidity}\n\nWe would like to ensure that $q> 0$ in a mass conserving way so that it doesn't alter the precipitation.\nTo do this, we first assume that\n\\[ Pq =\n  \\begin{cases}\n    \\alpha q & q >= \\epsilon \\\\\n    \\epsilon & q < \\epsilon\n  \\end{cases}.\n\\]\nThen, choosing\n\\[\\alpha = \\frac{\\langle q \\rangle - \\epsilon \\langle \\1{q < \\epsilon} \\rangle}{\\langle \\1{q \\geq \\epsilon} q \\rangle}\\]\nensures mass conservation.\n\n\\section{Mixture model}\n\nWe first train separate models on different regions in parallel, and then switch between the networks using a mixture modeling approach.\nWe will divide the data into 5 meridionally overallaping regions, and then train the networks on each region in isolation. These regions are\n\\begin{itemize}\n\\item Deep tropics\n\\item 2 Sub-tropics regions\n\\item 2 mid-lat regions\n\\end{itemize}\nBecause this dataset is so large, each region will still have many sampling points, but we do not join the sub-tropcs and mid-latitude regions for the northern and southern hemisphere because there could be climatological difference between these regions.\nThese regions are separated by distinct rainfall regimes.\n\nThe coarse-grained indices corresponding to a given latidue is given by $a \\phi / \\SI{160}{\\km}$ which is $\\frac{a\\pi}{180 \\cdot 160} \\phi $ if $\\phi$ is in degrees. Therefore the indices of the regions above are\n\\begin{enumerate}\n\\item 0,18 (so midlat)\n\\item 16,28 (so sub tropics)\n\\item 26,38 (deep tropics)\n\\item 36,48 (no sub tropics)\n\\item 46,64 (no midlat)\n\\end{enumerate} \n\n\\printbibliography\n\\appendix\n\n\\chapter{Source code}\n\\label{sec:source}\n\n% \\lstinputlisting[language=python]{../lib/linear_regression.py}\n\n\\end{document}\n\n% Local Variables:\n% TeX-master: t\n% TeX-PDF-mode: t\n% TeX-engine: luatex\n% End:\n", "meta": {"hexsha": "84f2cb06b68a602fde9b4f635cf72acf1c460e05", "size": 24108, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/report.tex", "max_stars_repo_name": "nbren12/nn_atmos_param", "max_stars_repo_head_hexsha": "cb138f0b211fd5743e56ad659aec38c082d2b3ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-09-16T20:55:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-06T11:27:50.000Z", "max_issues_repo_path": "docs/report.tex", "max_issues_repo_name": "nbren12/nn_atmos_param", "max_issues_repo_head_hexsha": "cb138f0b211fd5743e56ad659aec38c082d2b3ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-04-07T07:40:39.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-20T06:56:08.000Z", "max_forks_repo_path": "docs/report.tex", "max_forks_repo_name": "nbren12/nn_atmos_param", "max_forks_repo_head_hexsha": "cb138f0b211fd5743e56ad659aec38c082d2b3ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.2102564103, "max_line_length": 557, "alphanum_fraction": 0.7184337149, "num_tokens": 7225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.32146745036587054}}
{"text": "\\documentclass[journal,hidelinks]{IEEEtran}\n\\usepackage[utf8]{inputenc}\n\\usepackage[\n  pdftitle={Final Exam},\n  pdfauthor={Andrei Purcarus},\n  pdfsubject={ECSE-534 -- Analog Microelectronics}\n]{hyperref}\n\\usepackage{graphicx}\n\\usepackage[all]{hypcap}\n\\usepackage{cleveref}\n\\usepackage{indentfirst}\n\\usepackage[per-mode=symbol]{siunitx}\n\\usepackage{amsmath}\n\n\\title{ECSE-534 \\\\ Analog Microelectronics \\\\ Final Exam}\n\\author{Andrei~Purcarus,~260631911,~\\IEEEmembership{McGill~University} \\\\ \\href{mailto:andrei.purcaruscraciun@mail.mcgill.ca}{andrei.purcaruscraciun@mail.mcgill.ca}}\n\n\\begin{document}\n\\sloppy\n\n\\maketitle\n\n\\section{Introduction}\n\n\\IEEEPARstart{T}{his} report follows the design, simulation, and analysis of an anti-aliasing filter for a $\\Delta \\Sigma$ data converter using a 0.13 micron process from IBM. We used Cadence to simulate the design in said process. The filter was required to adhere to the topology shown in \\Cref{fig:filter_topology} and meet the following specifications:\n\\begin{itemize}\n  \\item A DC gain of $\\SI{1}{\\volt\\per\\volt}$.\n  \\item A passband from DC to $\\SI{100}{\\kilo\\hertz}$.\n  \\item A maximum attenuation of $\\SI{0.1}{\\deci\\bel}$ in the passband.\n  \\item A maximum phase shift of $\\SI{10}{\\degree}$ in the passband.\n  \\item A minimum attenuation of $\\SI{40}{\\deci\\bel}$ at frequencies over $\\SI{15}{\\mega\\hertz}$.\n  \\item An input resistance of at least $\\SI{1}{\\kilo\\ohm}$.\n  \\item An output resistance of at most $\\SI{20}{\\ohm}$.\n  \\item An output voltage swing of $\\SI{0.9}{\\volt}$ around an analog ground level of $\\SI{0.6}{\\volt}$.\n  \\item A maximum RMS noise level of $\\SI{100}{\\micro\\volt}$.\n\\end{itemize}\n\nThe filter must meet these specifications while driving a $\\SI{1}{\\pico\\farad}$ load capacitance that represents the input capacitance of the $\\Delta \\Sigma$ data converter.\n\n\\begin{figure}[!htb]\n  \\centering\n  \\includegraphics[width=\\columnwidth]{schematics/filter_topology.png}\n  \\caption{A schematic of the second-order anti-aliasing filter topology.}\n  \\label{fig:filter_topology}\n\\end{figure}\n\nTo meet these requirements, we first calculated the required values for the passive components of the filter. Then, we modified the operational amplifier we designed in the past assignments to meet the specifications. Next, we assembled the filter and verified that it meets the requirements. Finally, we discussed a rough sketch of the layout of the filter.\n\n\\begin{figure*}[!htb]\n  \\centering\n  \\includegraphics[width=\\textwidth]{schematics/folded_cascode.png}\n  \\caption{A schematic of the operational amplifier designed in past assignments.}\n  \\label{fig:folded_cascode}\n\\end{figure*}\n\n\\begin{figure*}[!htb]\n  \\centering\n  \\includegraphics[width=\\textwidth]{schematics/folded_cascode_2.png}\n  \\caption{A schematic of the modified operational amplifier made to meet the requirements.}\n  \\label{fig:folded_cascode_2}\n\\end{figure*}\n\n\\begin{figure*}[!htb]\n  \\centering\n  \\includegraphics[width=\\textwidth]{schematics/filter.png}\n  \\caption{A schematic of the anti-aliasing filter.}\n  \\label{fig:filter}\n\\end{figure*}\n\n\\section{Filter Design}\n\nWe first translated the given specifications into restrictions on our circuit. We started by deriving the transfer function of the filter as\n\\begin{align}\nH(s) &= \\frac{-R}{1 + s R C} \\frac{1}{R/2} \\frac{1/2}{1 + s R C} \\\\\n     &= \\frac{-1}{(1 + s R C)^2}\n\\end{align}\nThis result tells us that the DC gain is $-1$ and the bandwidth is given by $f_{3dB} = 1 / 2 \\pi R C$.\n\nIn order to gain more insight into the operation of the filter, we added a relative mismatch $\\Delta$ to the components in the feedback network. We thus obtained\n\\begin{align}\nH(s) &= \\frac{-R (1 + \\Delta_R)}{1 + s R C (1 + \\Delta_R) (1 + \\Delta_C)} \\frac{1}{R/2} \\frac{1/2}{1 + s R C} \\\\\n     &\\approx \\frac{-R (1 + \\Delta_R)}{1 + s R C (1 + \\Delta_R + \\Delta_C)} \\frac{1}{R/2} \\frac{1/2}{1 + s R C}\n\\end{align}\nThis result tells us that the DC gain can be approximated as $-(1 + \\Delta_R)$ and that there are two poles formed, one at $f_1 = 1 / 2 \\pi R C$ and the other at $f_2 = 1 / 2 \\pi R C (1 + \\Delta_R + \\Delta_C)$.\n\nThe given DC gain requirement means that the feedback resistors in the circuit must match well. In addition, the DC gain of the operational amplifier must be high, say at least $\\SI{60}{\\deci\\bel}$.\n\nThe given attenuation requirements mean that we must have $f_{3dB} \\gg \\SI{100}{\\kilo\\hertz}$ and $f_{3db} \\ll \\SI{15}{\\mega\\hertz}$. Since a second order filter has a roll-off of about $\\SI{40}{\\deci\\bel}$ per decade, this translates approximately to $f_{3db} < \\SI{1.5}{\\mega\\hertz}$.\n\nThe given input resistance requirement means that $R > \\SI{1}{\\kilo\\hertz}$. The given output resistance requirement means that we must have $2 R_{out} < \\SI{20}{\\ohm}$ for the operational amplifier, where $R_{out}$ is the output resistance of the amplifier in the unity gain configuration.\n\nThe given voltage swing requirements translate directly into equivalent requirements for the operational amplifier.\n\nThe given noise requirement must be separated between two sources: the thermal noise generated by the feedback network and the noise generated by the amplifier. We therefore allocate an RMS noise budget of $\\SI{50}{\\micro\\volt}$ to each.\n\nThe RMS thermal noise generated by the feedback network can be approximated as\n\\begin{align}\nv_{n,rms} = \\sqrt{\\frac{kT}{C} + \\frac{kT}{4C}}\n\\end{align}\nTherefore, we have\n\\begin{align}\nv_{n,rms} &< \\SI{50}{\\micro\\volt} \\\\\n\\sqrt{\\frac{kT}{C} + \\frac{kT}{4C}} &< \\SI{50}{\\micro\\volt} \\\\\nC &> \\SI{2}{\\pico\\farad}\n\\end{align}\n\nThe noise generated by the amplifier is harder to quantify. However, since the feedback gain of our circuit is $1 / 2$, the output spectral noise density of the amplifier in this circuit will be equivalent to the input-referred spectral noise density measured in open loop simulation times $2$. Thus, we require an input-referred RMS noise level of at most $\\SI{50}{\\micro\\volt} / \\sqrt{2} = \\SI{35}{\\micro\\volt}$.\n\nTherefore, the requirements for the feedback network are\n\\begin{equation}\nR > \\SI{1}{\\kilo\\ohm}\n\\end{equation}\n\\begin{equation}\nC > \\SI{2}{\\pico\\farad}\n\\end{equation}\n\\begin{equation}\n\\SI{100}{\\kilo\\hertz} \\ll \\frac{1}{2 \\pi R C} < \\SI{1.5}{\\mega\\hertz}\n\\end{equation}\n\nTo minimize the size of the capacitors used, we chose to use $C = \\SI{3}{\\pico\\farad}$. Then, to allow for at least a $\\SI{20}{\\percent}$ margin on the upper bandwidth, we chose to use $f_{3dB} = \\SI{1}{\\mega\\hertz}$, and thus $R = \\SI{53}{\\kilo\\ohm}$.\n\n\\section{Operational Amplifier Design}\n\nFrom the previous section, the main requirements for the operational amplifier are a DC gain of at least $\\SI{60}{\\deci\\bel}$, a maximum output resistance of $\\SI{10}{\\ohm}$ in the unity gain configuration, and an input-referred RMS noise level of at most $\\SI{35}{\\micro\\volt}$ over the given bandwidth. In addition, we require that the unity gain frequency of the amplifier should be at least 10 times our chosen filter bandwidth, at $\\SI{10}{\\mega\\hertz}$.\n\nTo meet these specifications, we reused the operational amplifier designed in the past assignments. A schematic is shown in \\Cref{fig:folded_cascode}. This amplifier has a DC gain of $\\SI{73}{\\deci\\bel}$, a unity gain bandwidth of $\\SI{40}{\\mega\\hertz}$, an output resistance in the unity gain configuration of $\\SI{12.9}{\\ohm}$, and a total input-referred RMS noise of $\\SI{65}{\\micro\\volt}$ between $\\SI{1}{\\hertz}$ and $\\SI{100}{\\kilo\\hertz}$.\n\nThese results show that the amplifier does not meet the specifications for noise and output resistance. In order to modify the amplifier to meet the specifications, we performed a series of transformations on our initial circuit.\n\nA noise analysis in Cadence indicated that the main contributors to the noise level were transistors $T_0$, $T_1$, $T_3$, and $T_4$, with a total contribution of $\\SI{92.68}{\\percent}$. Since flicker noise is inversely proportional to transistor area, we needed to scale the widths of these transistors upward. We achieved this by scaling the widths of $T_0$, $T_1$, $T_3$, and $T_4$ by a factor of $4$, and then scaling the width of $T_2$ to provide sufficient current to $T_0$ and $T_1$ to avoid disturbing the operating point of the other transistors in the circuit. This transistor ended up being scaled by a factor of $5$.\nIn addition, to meet the output resistance specification, we needed to scale the current in the output branch upward. We achieved this by scaling the widths of both $T_7$ and $T_{16}$ by a factor of $2$.\nThis also had the effect of scaling our bandwidth upward, so we scaled $C_c$ to $\\SI{0.72}{\\pico\\farad}$ and $R_c$ to $\\SI{3.3}{\\kilo\\ohm}$ to compensate.\nThe resulting amplifier is shown in \\Cref{fig:folded_cascode_2}.\n\nWe then measured the amplifier's characteristics to confirm that it now met the specifications. The amplifier now had a DC gain of $\\SI{77}{\\deci\\bel}$, a unity gain bandwidth of $\\SI{53}{\\mega\\hertz}$, an output resistance in the unity gain configuration of $\\SI{4.1}{\\ohm}$, and a total input-referred RMS noise of $\\SI{32}{\\micro\\volt}$ between $\\SI{1}{\\hertz}$ and $\\SI{100}{\\kilo\\hertz}$. The first two poles were also moved to $\\SI{8}{\\kilo\\hertz}$ and $\\SI{102}{\\mega\\hertz}$, and the first zero was moved to $\\SI{124}{\\mega\\hertz}$, which are very close to the values they initially had. In addition, we verified that the amplifier was still stable, with a phase margin of $\\SI{57}{\\degree}$.\n\n\\section{Putting It All Together}\n\nWe next assembled the circuit together as previously described. The result is shown in \\Cref{fig:filter}. Note that we split the resistors into units of size $R/4$ in order to better match them in layout, and we split the capacitors into units of size $C$ for the same reason. After some testing, we also changed the value of $R$ to $\\SI{40}{\\kilo\\ohm}$ in order to fully meet the specifications.\n\nTo test the performance of the filter, we used the circuit shown in \\Cref{fig:filter_tb}, which has a load capacitance of $\\SI{1}{\\pico\\farad}$.\n\n\\begin{figure}[!htb]\n  \\centering\n  \\includegraphics[width=\\columnwidth]{schematics/filter_tb.png}\n  \\caption{A schematic of the test-bench used to measure the AC and transient performance of the filter.}\n  \\label{fig:filter_tb}\n\\end{figure}\n\nWe first measured the transient performance of the filter by using a $\\SI{0.9}{\\volt}$ peak-peak, $\\SI{10}{\\kilo\\hertz}$ sine wave centered around $\\SI{0.6}{\\volt}$ as an input. The resulting input and output are shown in \\Cref{fig:filter_tran}. This figure shows that the output signal has no significant distortion even at full range. In fact, we can compute the total harmonic distortion as only $\\SI{0.040}{\\percent}$, which shows that the circuit meets the voltage swing requirement of the $\\Delta \\Sigma$ converter.\n\n\\begin{figure}[!htb]\n  \\centering\n  \\includegraphics[width=\\columnwidth]{results/filter_tran.png}\n  \\caption{Transient response of the filter for a $\\SI{0.9}{\\volt}$ peak-peak, $\\SI{10}{\\kilo\\hertz}$ sine wave centered around $\\SI{0.6}{\\volt}$. The input waveform is shown in brown and the output waveform is shown in red.}\n  \\label{fig:filter_tran}\n\\end{figure}\n\nWe then measured the AC performance of the filter by using small signal analysis. The results are shown in \\Cref{fig:filter_ac}. These results show that we have a DC gain of $\\SI{0.99953}{\\volt\\per\\volt}$, an attenuation of $\\SI{0.053}{\\deci\\bel}$ and a phase shift of $\\SI{8.83}{\\degree}$ at $\\SI{100}{\\kilo\\hertz}$, and an attenuation of $\\SI{41.5}{\\deci\\bel}$ at $\\SI{15}{\\mega\\hertz}$. Therefore, the filter meets all the AC requirements.\n\n\\begin{figure}[!htb]\n  \\centering\n  \\includegraphics[width=\\columnwidth]{results/filter_ac.png}\n  \\caption{AC response of the filter. The plot on the left shows the gain in $\\SI{}{\\deci\\bel}$ and the plot on the right shows the phase in $\\SI{}{\\degree}$.}\n  \\label{fig:filter_ac}\n\\end{figure}\n\nWe next measured the noise properties of the filter. After running an AC noise analysis and integrating the results from $\\SI{1}{\\hertz}$ to $\\SI{100}{\\kilo\\hertz}$, we obtained the results shown in \\Cref{fig:filter_noise}. This figure clearly shows that we have a total RMS output noise of $\\SI{66}{\\micro\\volt}$, which meets the specified maximum noise level for the input to the $\\Delta \\Sigma$ converter.\n\n\\begin{figure}[!htb]\n  \\centering\n  \\includegraphics[width=\\columnwidth]{results/filter_noise.png}\n  \\caption{Noise results for the filter over the bandwidth from $\\SI{1}{\\hertz}$ to $\\SI{100}{\\kilo\\hertz}$.}\n  \\label{fig:filter_noise}\n\\end{figure}\n\nThen, we measured the output resistance of the filter using the circuit shown in \\Cref{fig:filter_tb_2}. With the load resistance set to $\\SI{20}{\\ohm}$ and the input set to $\\SI{1}{\\volt}$, we measured a small signal output voltage of $\\SI{0.6984}{\\volt}$. Using a simple voltage divider equation, we found that the output resistance of the filter was therefore $\\SI{8.62}{\\ohm}$, which is smaller than the maximum output resistance requirement.\n\n\\begin{figure}[!htb]\n  \\centering\n  \\includegraphics[width=\\columnwidth]{schematics/filter_tb_2.png}\n  \\caption{A schematic of the test-bench used to measure the output resistance of the filter.}\n  \\label{fig:filter_tb_2}\n\\end{figure}\n\nFinally, we measured the input resistance of the filter using the circuit shown in \\Cref{fig:filter_tb_3}. With the signal resistance set to $\\SI{40}{\\kilo\\ohm}$ and the input set to $\\SI{1}{\\volt}$, we measured a small signal output voltage of $\\SI{0.49962}{\\volt}$. Using a simple voltage divider equation, we found that the input resistance of the filter was therefore $\\SI{39.98}{\\kilo\\ohm}$, which greatly exceeds the specification.\n\n\\begin{figure}[!htb]\n  \\centering\n  \\includegraphics[width=\\columnwidth]{schematics/filter_tb_3.png}\n  \\caption{A schematic of the test-bench used to measure the input resistance of the filter.}\n  \\label{fig:filter_tb_3}\n\\end{figure}\n\n\\section{Layout}\n\nNext, we planned out a rough sketch of the layout for the filter. As shown in \\Cref{fig:folded_cascode_2}, we made all transistors multiples of a unit size, which reduces the error when trying to match them. We used a combination of the number of fingers to increase the length of a transistor and the multiplicity to increase the width of a transistor, thus ensuring that transistors can be made into rectangular shapes that are not too long and not too wide.\n\nIn addition, we made sure that all transistors that need to be matched have a multiplicity of at least $2$, which allows us to use a common centroid geometry to eliminate the effect of the first order component of the process gradient in producing matching error. An example of this is shown in \\Cref{fig:layout_diff_pair}. In this figure, $T_0$ and $T_1$ are placed such that their centroids coincide. In addition, this figure shows the addition of dummy structures to the boundaries of the pair, which ensures that all transistors have a similar environment and thus creates a better matching. The dummy transistors would typically be connected to $V_{SS}$.\n\n\\begin{figure}[!htb]\n  \\centering\n  \\includegraphics[width=\\columnwidth]{layout/diff_pair.png}\n  \\caption{A common centroid layout for a differential input pair with dummy structures at the boundary. Connections are not shown.}\n  \\label{fig:layout_diff_pair}\n\\end{figure}\n\nFor the passive components, matching was also critical since it controls the DC gain of the filter. In addition, mismatches can split the poles of the filter, causing ringing to occur. To ensure that these components are matched correctly, we again split them into subcomponents of unit size and used a common centroid geometry. A sketch of the layout of the resistors in the circuit is shown in \\Cref{fig:layout_res}, and a sketch of the layout of the capacitors in the circuit is shown in \\Cref{fig:layout_cap}.\nWe note here that while the matching of components is critical, the values of the components themselves are not. Since the $\\Delta \\Sigma$ converter oversamples at a rate of $\\SI{16}{\\mega\\hertz}$ and the signal bandwidth is only $\\SI{100}{\\kilo\\hertz}$, the resulting pole at around $\\SI{1}{\\mega\\hertz}$ can vary by $\\SI{\\pm 20}{\\percent}$ while still producing little passband attenuation and sufficient stopband attenuation.\n\n\\begin{figure}[!htb]\n  \\centering\n  \\includegraphics[width=\\columnwidth]{layout/res.png}\n  \\caption{A common centroid layout for the resistors in the filter. Connections are not shown.}\n  \\label{fig:layout_res}\n\\end{figure}\n\n\\begin{figure}[!htb]\n  \\centering\n  \\includegraphics[width=\\columnwidth]{layout/cap.png}\n  \\caption{A common centroid layout for the capacitors in the filter. Connections are not shown.}\n  \\label{fig:layout_cap}\n\\end{figure}\n\n\\section{Conclusions}\n\nIn conclusion, we designed an anti-aliasing filter capable of acting as a preprocessor for the $\\Delta \\Sigma$ converter specified in the examination question. This filter meets all of the specifications. In addition, we provided a sketch of the approach we would use to lay out such a filter.\n\n\\bibliographystyle{IEEEtran}\n\\bibliography{IEEEabrv,references}\n\n\\end{document}\n", "meta": {"hexsha": "6d824be999f8539c7cd853a1230653889814fc66", "size": 17105, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "FinalExam/main.tex", "max_stars_repo_name": "Gripnook/analog-microelectronics", "max_stars_repo_head_hexsha": "14a426823625ee0890c4d3c1671ef957869d1228", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FinalExam/main.tex", "max_issues_repo_name": "Gripnook/analog-microelectronics", "max_issues_repo_head_hexsha": "14a426823625ee0890c4d3c1671ef957869d1228", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FinalExam/main.tex", "max_forks_repo_name": "Gripnook/analog-microelectronics", "max_forks_repo_head_hexsha": "14a426823625ee0890c4d3c1671ef957869d1228", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 73.4120171674, "max_line_length": 700, "alphanum_fraction": 0.7460976323, "num_tokens": 4793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.3214674503658705}}
{"text": "\\subsection{Enumeration types}\n\\label{subsec:library_of_transformations:type_level_transformations:enumeration_types}\n\n\\begin{figure}[H]\n    \\centering\n    \\begin{subfigure}{0.25\\textwidth}\n        \\centering\n        \\includegraphics{images/05_library_of_transformations/02_type_level_transformations/04_enumeration_types/enum_type.pdf}\n        \\caption{$Tm_{Enum}$ with \\\\$name = .\\type{Example}$ and \\\\$values = \\{ \\type{OPTION\\_A},$\\\\$ \\type{OPTION\\_B}, \\type{OPTION\\_C} \\}$}\n        \\label{fig:library_of_transformations:type_level_transformations:enumeration_types:visualisation:ecore}\n    \\end{subfigure}\n    \\\\\n    \\begin{subfigure}{0.65\\textwidth}\n        \\centering\n        \\input{images/05_library_of_transformations/02_type_level_transformations/04_enumeration_types/enum_as_node_types.tikz}\n        \\caption{$TG_{EnumNodes}$ with $name = .\\type{Example}$ and\\\\$values = \\{ \\type{OPTION\\_A}, \\type{OPTION\\_B}, \\type{OPTION\\_C} \\}$}\n        \\label{fig:library_of_transformations:type_level_transformations:enumeration_types:visualisation:groove_nodes}\n    \\end{subfigure}\n    \\begin{subfigure}{0.25\\textwidth}\n        \\centering\n        \\input{images/05_library_of_transformations/02_type_level_transformations/04_enumeration_types/enum_as_flags.tikz}\n        \\caption{$TG_{EnumFlags}$ with \\\\$name = .\\type{Example}$ and \\\\$values = \\{ \\type{OPTION\\_A},$\\\\$ \\type{OPTION\\_B}, \\type{OPTION\\_C} \\}$}\n        \\label{fig:library_of_transformations:type_level_transformations:enumeration_types:visualisation:groove_flags}\n    \\end{subfigure}\n    \\caption{Visualisations of the transformations of enumeration types}\n    \\label{fig:library_of_transformations:type_level_transformations:enumeration_types:visualisation}\n\\end{figure}\n\nThis section will define the transformation of an enumeration type. Within this transformation, a new enumeration type is introduced, including its possible values. The Ecore type model that introduces such a subclass is defined as follows:\n\n\\begin{defin}[Type model $Tm_{Enum}$]\n\\label{defin:library_of_transformations:type_level_transformations:enumeration_types:tmod_enum}\nLet $Tm_{Enum}$ be the type model containing a enumeration type with identifier $name$. The values of this enumeration type are defined as part of sequence $values$. $Tm_{Enum}$ is defined as:\n\\begin{align*}\nClass =\\ &\\{\\} \\\\\nEnum =\\ &\\{name\\} \\\\\nUserDataType =\\ &\\{\\} \\\\\nField =\\ &\\{\\} \\\\\n\\mathrm{FieldSig} =\\ &\\{\\} \\\\\nEnumValue =\\ &\\{ (name, v) \\mid v \\in values \\} \\\\\nInh =\\ &\\{\\} \\\\\nProp =\\ &\\{\\} \\\\\nConstant =\\ &\\{\\} \\\\\n\\mathrm{ConstType} =\\ &\\{\\}\n\\end{align*}\n\\isabellelref{tmod_enum}{Ecore-GROOVE-Mapping-Library.EnumType}\n\\end{defin}\n\n\\begin{thm}[Correctness of $Tm_{Enum}$]\n\\label{defin:library_of_transformations:type_level_transformations:enumeration_types:tmod_enum_correct}\n$Tm_{Subclass}$ (\\cref{defin:library_of_transformations:type_level_transformations:enumeration_types:tmod_enum}) is a consistent type model in the sense of \\cref{defin:formalisations:ecore_formalisation:type_models:type_model_consistency}.\n\\isabellelref{tmod_enum_correct}{Ecore-GROOVE-Mapping-Library.EnumType}\n\\end{thm}\n\nA visual representation of $Tm_{Enum}$ with $.\\type{Example}$ as identifier for the new enumeration type and $\\type{OPTION\\_A}$, $\\type{OPTION\\_B}$ and $\\type{OPTION\\_C}$ as its values can be seen in \\cref{fig:library_of_transformations:type_level_transformations:enumeration_types:visualisation:ecore}. The correctness proof of $Tm_{Enum}$ is trivial, and therefore not included here. The proof can be found as part of the Isabelle validated proofs.\n\nIn order to make composing transformation functions possible, $Tm_{Enum}$ should be compatible with the type model it is combined with.\n\n\\begin{thm}[Correctness of $\\mathrm{combine}(Tm, Tm_{Enum})$]\n\\label{defin:library_of_transformations:type_level_transformations:enumeration_types:tmod_enum_combine_correct}\nAssume a type model $Tm$ that is consistent in the sense of \\cref{defin:formalisations:ecore_formalisation:type_models:type_model_consistency}. Then $Tm$ is compatible with $Tm_{Enum}$ (in the sense of \\cref{defin:transformation_framework:type_models_and_type_graphs:combining_type_models:compatibility}) if:\n\\begin{itemize}\n    \\item The identifier of the enumeration type in $Tm_{Enum}$ is not yet an identifier for a class, enumeration type or user-defined data type in $Tm$;\n    \\item The identifier of the enumeration type in $Tm_{Enum}$ is not in the namespace of any class, enumeration type or user-defined data type in $Tm$;\n    \\item None of the identifiers in any class, enumeration type or user-defined data type in $Tm$ is in the namespace of the enumeration type in $Tm_{Enum}$.\n\\end{itemize}\n\\isabellelref{tmod_enum_combine_correct}{Ecore-GROOVE-Mapping-Library.EnumType}\n\\end{thm}\n\n\\begin{proof}\nUse \\cref{defin:transformation_framework:type_models_and_type_graphs:combining_type_models:tmod_combine_merge_correct}. It is possible to show that all assumptions hold. Now we have shown that $\\mathrm{combine}(Tm, Tm_{Enum})$ is consistent in the sense of \\cref{defin:formalisations:ecore_formalisation:type_models:type_model_consistency}.\n\\end{proof}\n\nThe definitions and theorems for a regular subclass within Ecore are now complete. \n\n\\subsubsection{Encoding as node type}\n\nA possible encoding for enumeration types in Ecore is using node types in GROOVE. In this case, the enumeration type itself is transformed into an abstract node type. Each value of the enumeration type is converted to its own node type, extending the abstract node type. The encoding corresponding to $Tm_{Enum}$ can then be represented as $TG_{EnumNodes}$, defined in the following definition:\n\n\\begin{defin}[Type graph $TG_{EnumNodes}$]\n\\label{defin:library_of_transformations:type_level_transformations:enumeration_types:tg_enum_as_node_types}\nLet $TG_{EnumNodes}$ be a type graph containing multiple node types. The first node type encodes the enumeration type $name$. The other node types encode the $values$ of enumeration type $name$. $TG_{EnumNodes}$ is defined as:\n\\begin{align*}\nNT =\\ &\\{\\mathrm{ns\\_\\!to\\_\\!list}(name)\\} \\cup \\{ \\mathrm{ns\\_\\!to\\_\\!list}(name) \\append \\langle v \\rangle \\mid v \\in values \\} \\\\\nET =\\ &\\{\\} \\\\\n\\!\\!\\sqsubseteq\\ =\\ &\\{(\\mathrm{ns\\_\\!to\\_\\!list}(name), \\mathrm{ns\\_\\!to\\_\\!list}(name))\\}\\ \\cup \\\\&\n\\{(\\mathrm{ns\\_\\!to\\_\\!list}(name) \\append \\langle v \\rangle, \\mathrm{ns\\_\\!to\\_\\!list}(name) \\append \\langle v \\rangle) \\mid v \\in values \\}\\ \\cup \\\\&\n\\{(\\mathrm{ns\\_\\!to\\_\\!list}(name) \\append \\langle v \\rangle, \\mathrm{ns\\_\\!to\\_\\!list}(name)) \\mid v \\in values \\} \\\\\nabs =\\ &\\{\\mathrm{ns\\_\\!to\\_\\!list}(name)\\} \\\\\n\\mathrm{mult} =\\ &\\{\\} \\\\\ncontains =\\ &\\{\\}\n\\end{align*}\n\\isabellelref{tg_enum_as_node_types}{Ecore-GROOVE-Mapping-Library.EnumType}\n\\end{defin}\n\n\\begin{thm}[Correctness of $TG_{EnumNodes}$]\n\\label{defin:library_of_transformations:type_level_transformations:enumeration_types:tg_enum_as_node_types_correct}\n$TG_{EnumNodes}$ (\\cref{defin:library_of_transformations:type_level_transformations:enumeration_types:tg_enum_as_node_types}) is a valid type graph in the sense of \\cref{defin:formalisations:groove_formalisation:type_graphs:type_graph_validity}.\n\\isabellelref{tg_enum_as_node_types_correct}{Ecore-GROOVE-Mapping-Library.EnumType}\n\\end{thm}\n\nA visual representation of $TG_{EnumNodes}$ with $.\\type{Example}$ as identifier for the encoded enumeration type and $\\type{OPTION\\_A}$, $\\type{OPTION\\_B}$ and $\\type{OPTION\\_C}$ as its values can be seen in \\cref{fig:library_of_transformations:type_level_transformations:enumeration_types:visualisation:groove_nodes}. Please note that in this visualisation, the sequences are concatenated using the dollar sign $\\$$. The correctness proof of $TG_{EnumNodes}$ is trivial, and therefore not included here. The proof can be found as part of the Isabelle validated proofs.\n\nIn order to make composing transformation functions possible, $TG_{EnumNodes}$ should be compatible with the type graph it is combined with.\n\n\\begin{thm}[Correctness of $\\mathrm{combine}(TG, TG_{EnumNodes})$]\n\\label{defin:library_of_transformations:type_level_transformations:enumeration_types:tg_enum_as_node_types_combine_correct}\nAssume a type graph $TG$ that is valid in the sense of \\cref{defin:formalisations:groove_formalisation:type_graphs:type_graph_validity}. Then $TG$ is compatible with $TG_{EnumNodes}$ (in the sense of \\cref{defin:transformation_framework:type_models_and_type_graphs:combining_type_graphs:compatibility}) if:\n\\begin{itemize}\n    \\item There are no shared node types between $TG_{EnumNodes}$ and $TG$.\n\\end{itemize}\n\\isabellelref{tg_enum_as_node_types_combine_correct}{Ecore-GROOVE-Mapping-Library.EnumType}\n\\end{thm}\n\n\\begin{proof}\nUse \\cref{defin:transformation_framework:type_models_and_type_graphs:combining_type_graphs:tg_combine_merge_correct}. It is possible to show that all assumptions hold. Now we have shown that $\\mathrm{combine}(TG, TG_{EnumNodes})$ is valid in the sense of \\cref{defin:formalisations:groove_formalisation:type_graphs:type_graph_validity}.\n\\end{proof}\n\nThe next definitions define the transformation function from $Tm_{Enum}$ to $TG_{EnumNodes}$:\n\n\\begin{defin}[Transformation function $f_{EnumNodes}$]\n\\label{defin:library_of_transformations:type_level_transformations:enumeration_types:tmod_enum_to_tg_enum_as_node_types}\nThe transformation function $f_{EnumNodes}(Tm)$ is defined as:\n\\begin{align*}\nNT =\\ &\\{\\mathrm{ns\\_\\!to\\_\\!list}(e) \\mid e \\in Enum_{Tm}\\} \\cup \\{\\mathrm{ns\\_\\!to\\_\\!list}(e) \\append \\langle v \\rangle \\mid (e, v) \\in EnumValue_{Tm}\\} \\\\\nET =\\ &\\{\\} \\\\\n\\!\\!\\sqsubseteq\\ =\\ &\\{(\\mathrm{ns\\_\\!to\\_\\!list}(e_1), \\mathrm{ns\\_\\!to\\_\\!list}(e_2)) \\mid e_1 \\in Enum_{Tm} \\land e_2 \\in Enum_{Tm} \\}\\ \\cup \\\\&\n\\{(\\mathrm{ns\\_\\!to\\_\\!list}(i) \\append \\langle j \\rangle, \\mathrm{ns\\_\\!to\\_\\!list}(i) \\append \\langle j \\rangle) \\mid (i, j) \\in EnumValue_{Tm} \\}\\ \\cup \\\\&\n\\{(\\mathrm{ns\\_\\!to\\_\\!list}(i) \\append \\langle j \\rangle, \\mathrm{ns\\_\\!to\\_\\!list}(e)) \\mid (i, j) \\in EnumValue_{Tm} \\land e \\in Enum_{Tm} \\} \\\\\nabs =\\ &\\{\\} \\\\\n\\mathrm{mult} =\\ &\\{\\} \\\\\ncontains =\\ &\\{\\}\n\\end{align*}\n\\isabellelref{tmod_enum_to_tg_enum_as_node_types}{Ecore-GROOVE-Mapping-Library.EnumType}\n\\end{defin}\n\n\\begin{thm}[Correctness of $f_{EnumNodes}$]\n\\label{defin:library_of_transformations:type_level_transformations:enumeration_types:tmod_enum_to_tg_enum_as_node_types_func}\n$f_{EnumNodes}(Tm)$ (\\cref{defin:library_of_transformations:type_level_transformations:enumeration_types:tmod_enum_to_tg_enum_as_node_types}) is a valid transformation function in the sense of \\cref{defin:transformation_framework:type_models_and_type_graphs:combining_transformation_functions:transformation_function_type_model_type_graph} transforming $Tm_{Enum}$ into $TG_{EnumNodes}$.\n\\isabellelref{tmod_enum_to_tg_enum_as_node_types_func}{Ecore-GROOVE-Mapping-Library.EnumType}\n\\end{thm}\n\nThe proof of the correctness of $f_{EnumNodes}$ will not be included here. Instead, it can be found in the validated Isabelle theories.\n\nFinally, to complete the transformation, the transformation function that transforms $TG_{EnumNodes}$ into $Tm_{Enum}$ is defined:\n\n\\begin{defin}[Transformation function $f'_{EnumNodes}$]\n\\label{defin:library_of_transformations:type_level_transformations:enumeration_types:tg_enum_as_node_types_to_tmod_enum}\nThe transformation function $f'_{EnumNodes}(TG, name)$ is defined as:\n\\begin{align*}\nClass =\\ &\\{\\} \\\\\nEnum =\\ &\\{\\mathrm{list\\_\\!to\\_\\!ns}(n) \\mid n \\in NT_{TG} \\land n = \\mathrm{id\\_\\!to\\_\\!name}(name)\\} \\\\\nUserDataType =\\ &\\{\\} \\\\\nField =\\ &\\{\\} \\\\\n\\mathrm{FieldSig} =\\ &\\{\\} \\\\\nEnumValue =\\ &\\{(\\mathrm{list\\_\\!to\\_\\!ns}(e), v) \\mid e \\append \\langle v \\rangle \\in NT_{TG} \\land e \\append \\langle v \\rangle \\neq \\mathrm{id\\_\\!to\\_\\!name}(name) \\} \\\\\nInh =\\ &\\{\\} \\\\\nProp =\\ &\\{\\} \\\\\nConstant =\\ &\\{\\} \\\\\n\\mathrm{ConstType} =\\ &\\{\\}\n\\end{align*}\n\\isabellelref{tg_enum_as_node_types_to_tmod_enum}{Ecore-GROOVE-Mapping-Library.EnumType}\n\\end{defin}\n\n\\begin{thm}[Correctness of $f'_{EnumNodes}$]\n\\label{defin:library_of_transformations:type_level_transformations:enumeration_types:tg_enum_as_node_types_to_tmod_enum_func}\n$f'_{EnumNodes}(TG, name)$ (\\cref{defin:library_of_transformations:type_level_transformations:enumeration_types:tg_enum_as_node_types_to_tmod_enum}) is a valid transformation function in the sense of \\cref{defin:transformation_framework:type_models_and_type_graphs:combining_transformation_functions:transformation_function_type_graph_type_model} transforming $TG_{EnumNodes}$ into $Tm_{Enum}$.\n\\isabellelref{tg_enum_as_node_types_to_tmod_enum_func}{Ecore-GROOVE-Mapping-Library.EnumType}\n\\end{thm}\n\nOnce more, the correctness proof is not included here but can be found in the validated Isabelle proofs of this thesis.\n\n\\subsubsection{Encoding as flags}\n\nAnother possible encoding for enumeration types in Ecore is using flags in GROOVE. In this case, the enumeration type itself is transformed into a regular node type. Each value of the enumeration type is converted to a flag on this node type. The encoding corresponding to $Tm_{Enum}$ can then be represented as $TG_{EnumFlags}$, defined in the following definition:\n\n\\begin{defin}[Type graph $TG_{EnumFlags}$]\n\\label{defin:library_of_transformations:type_level_transformations:enumeration_types:tg_enum_as_flags}\nLet $TG_{EnumFlags}$ be a type graph containing a single node type which encodes the enumeration type $name$. The flags on the node type of $name$ encode the different $values$. $TG_{EnumFlags}$ is defined as:\n\\begin{align*}\nNT =\\ &\\{\\mathrm{ns\\_\\!to\\_\\!list}(name)\\} \\\\\nET =\\ &\\{ (\\mathrm{ns\\_\\!to\\_\\!list}(name), \\langle v \\rangle, \\mathrm{ns\\_\\!to\\_\\!list}(name)) \\mid v \\in values \\}\\\\\n\\!\\!\\sqsubseteq\\ =\\ &\\{(\\mathrm{ns\\_\\!to\\_\\!list}(name), \\mathrm{ns\\_\\!to\\_\\!list}(name))\\} \\\\\nabs =\\ &\\{\\} \\\\\n\\mathrm{mult}(e) =\\ &\\begin{cases}\n    (0..1, 0..1) &\\mathrm{if}\\ e \\in ET_{TG_{EnumFlags}}\n\\end{cases}\\\\\ncontains =\\ &\\{\\}\n\\end{align*}\n\\isabellelref{tg_enum_as_flags}{Ecore-GROOVE-Mapping-Library.EnumType}\n\\end{defin}\n\n\\begin{thm}[Correctness of $TG_{EnumFlags}$]\n\\label{defin:library_of_transformations:type_level_transformations:enumeration_types:tg_enum_as_flags_correct}\n$TG_{EnumFlags}$ (\\cref{defin:library_of_transformations:type_level_transformations:enumeration_types:tg_enum_as_flags}) is a valid type graph in the sense of \\cref{defin:formalisations:groove_formalisation:type_graphs:type_graph_validity}.\n\\isabellelref{tg_enum_as_flags_correct}{Ecore-GROOVE-Mapping-Library.EnumType}\n\\end{thm}\n\nA visual representation of $TG_{EnumFlags}$ with $.\\type{Example}$ as identifier for the encoded enumeration type and $\\type{OPTION\\_A}$, $\\type{OPTION\\_B}$ and $\\type{OPTION\\_C}$ as its values can be seen in \\cref{fig:library_of_transformations:type_level_transformations:enumeration_types:visualisation:groove_flags}. The correctness proof of $TG_{EnumFlags}$ is trivial, and therefore not included here. The proof can be found as part of the Isabelle validated proofs.\n\nIn order to make composing transformation functions possible, $TG_{EnumFlags}$ should be compatible with the type graph it is combined with.\n\n\\begin{thm}[Correctness of $\\mathrm{combine}(TG, TG_{EnumFlags})$]\n\\label{defin:library_of_transformations:type_level_transformations:enumeration_types:tg_enum_as_flags_combine_correct}\nAssume a type graph $TG$ that is valid in the sense of \\cref{defin:formalisations:groove_formalisation:type_graphs:type_graph_validity}. Then $TG$ is compatible with $TG_{EnumFlags}$ (in the sense of \\cref{defin:transformation_framework:type_models_and_type_graphs:combining_type_graphs:compatibility}) if:\n\\begin{itemize}\n    \\item There are no shared node types between $TG_{EnumFlags}$ and $TG$.\n\\end{itemize}\n\\isabellelref{tg_enum_as_flags_combine_correct}{Ecore-GROOVE-Mapping-Library.EnumType}\n\\end{thm}\n\n\\begin{proof}\nUse \\cref{defin:transformation_framework:type_models_and_type_graphs:combining_type_graphs:tg_combine_merge_correct}. It is possible to show that all assumptions hold. Now we have shown that $\\mathrm{combine}(TG, TG_{EnumFlags})$ is valid in the sense of \\cref{defin:formalisations:groove_formalisation:type_graphs:type_graph_validity}.\n\\end{proof}\n\nThe next definitions define the transformation function from $Tm_{Enum}$ to $TG_{EnumFlags}$:\n\n\\begin{defin}[Transformation function $f_{EnumFlags}$]\n\\label{defin:library_of_transformations:type_level_transformations:enumeration_types:tmod_enum_to_tg_enum_as_flags}\nThe transformation function $f_{EnumFlags}(Tm)$ is defined as:\n\\begin{align*}\nNT =\\ &\\{\\mathrm{ns\\_\\!to\\_\\!list}(e) \\mid e \\in Enum_{Tm}\\} \\\\\nET =\\ &\\{(\\mathrm{ns\\_\\!to\\_\\!list}(e), v, \\mathrm{ns\\_\\!to\\_\\!list}(e)) \\mid (e, v) \\in EnumValue_{Tm}\\} \\\\\n\\!\\!\\sqsubseteq\\ =\\ &\\{(\\mathrm{ns\\_\\!to\\_\\!list}(e_1), \\mathrm{ns\\_\\!to\\_\\!list}(e_2)) \\mid e_1 \\in Enum_{Tm} \\land e_2 \\in Enum_{Tm} \\} \\\\\nabs =\\ &\\{\\} \\\\\n\\mathrm{mult}(e) =\\ &\\begin{cases}\n    (0..1, 0..1) &\\mathrm{if}\\ e \\in \\{(\\mathrm{ns\\_\\!to\\_\\!list}(n), v, \\mathrm{ns\\_\\!to\\_\\!list}(n)) \\mid (n, v) \\in EnumValue_{Tm}\\}\n\\end{cases}\\\\\ncontains =\\ &\\{\\}\n\\end{align*}\n\\isabellelref{tmod_enum_to_tg_enum_as_flags}{Ecore-GROOVE-Mapping-Library.EnumType}\n\\end{defin}\n\n\\begin{thm}[Correctness of $f_{EnumFlags}$]\n\\label{defin:library_of_transformations:type_level_transformations:enumeration_types:tmod_enum_to_tg_enum_as_flags_func}\n$f_{EnumFlags}(Tm)$ (\\cref{defin:library_of_transformations:type_level_transformations:enumeration_types:tmod_enum_to_tg_enum_as_flags}) is a valid transformation function in the sense of \\cref{defin:transformation_framework:type_models_and_type_graphs:combining_transformation_functions:transformation_function_type_model_type_graph} transforming $Tm_{Enum}$ into $TG_{EnumFlags}$.\n\\isabellelref{tmod_enum_to_tg_enum_as_flags_func}{Ecore-GROOVE-Mapping-Library.EnumType}\n\\end{thm}\n\nThe proof of the correctness of $f_{EnumFlags}$ will not be included here. Instead, it can be found in the validated Isabelle theories.\n\nFinally, to complete the transformation, the transformation function that transforms $TG_{EnumFlags}$ into $Tm_{Enum}$ is defined:\n\n\\begin{defin}[Transformation function $f'_{EnumFlags}$]\n\\label{defin:library_of_transformations:type_level_transformations:enumeration_types:tg_enum_as_flags_to_tmod_enum}\nThe transformation function $f'_{EnumFlags}(TG)$ is defined as:\n\\begin{align*}\nClass =\\ &\\{\\} \\\\\nEnum =\\ &\\{\\mathrm{list\\_\\!to\\_\\!ns}(n) \\mid n \\in NT_{TG}\\} \\\\\nUserDataType =\\ &\\{\\} \\\\\nField =\\ &\\{\\} \\\\\n\\mathrm{FieldSig} =\\ &\\{\\} \\\\\nEnumValue =\\ &\\{(\\mathrm{list\\_\\!to\\_\\!ns}(e), v) \\mid (e, v, e) \\in ET_{TG} \\} \\\\\nInh =\\ &\\{\\} \\\\\nProp =\\ &\\{\\} \\\\\nConstant =\\ &\\{\\} \\\\\n\\mathrm{ConstType} =\\ &\\{\\}\n\\end{align*}\n\\isabellelref{tg_enum_as_flags_to_tmod_enum}{Ecore-GROOVE-Mapping-Library.EnumType}\n\\end{defin}\n\n\\begin{thm}[Correctness of $f'_{EnumNodes}$]\n\\label{defin:library_of_transformations:type_level_transformations:enumeration_types:tg_enum_as_flags_to_tmod_enum_func}\n$f'_{EnumFlags}(TG)$ (\\cref{defin:library_of_transformations:type_level_transformations:enumeration_types:tg_enum_as_flags_to_tmod_enum}) is a valid transformation function in the sense of \\cref{defin:transformation_framework:type_models_and_type_graphs:combining_transformation_functions:transformation_function_type_graph_type_model} transforming $TG_{EnumFlags}$ into $Tm_{Enum}$.\n\\isabellelref{tg_enum_as_flags_to_tmod_enum_func}{Ecore-GROOVE-Mapping-Library.EnumType}\n\\end{thm}\n\nOnce more, the correctness proof is not included here but can be found in the validated Isabelle proofs of this thesis.", "meta": {"hexsha": "e9c700dcd38a23a6bc300600fb3ed64f3dc0b07b", "size": 19558, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/tex/05_library_of_transformations/02_type_level_transformations/04_enumeration_types.tex", "max_stars_repo_name": "RemcodM/thesis-ecore-groove-formalisation", "max_stars_repo_head_hexsha": "a0e860c4b60deb2f3798ae2ffc09f18a98cf42ca", "max_stars_repo_licenses": ["AFL-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thesis/tex/05_library_of_transformations/02_type_level_transformations/04_enumeration_types.tex", "max_issues_repo_name": "RemcodM/thesis-ecore-groove-formalisation", "max_issues_repo_head_hexsha": "a0e860c4b60deb2f3798ae2ffc09f18a98cf42ca", "max_issues_repo_licenses": ["AFL-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis/tex/05_library_of_transformations/02_type_level_transformations/04_enumeration_types.tex", "max_forks_repo_name": "RemcodM/thesis-ecore-groove-formalisation", "max_forks_repo_head_hexsha": "a0e860c4b60deb2f3798ae2ffc09f18a98cf42ca", "max_forks_repo_licenses": ["AFL-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 72.9776119403, "max_line_length": 570, "alphanum_fraction": 0.7668473259, "num_tokens": 5736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.32146744926507526}}
{"text": "\\documentclass[12pt]{article}\n\\usepackage{psfig}\n\\usepackage{fullpage}\n\n% bold math italic font\n\\newcommand{\\mbf}[1]{\\mbox{\\boldmath $#1$}}\n\n% symbol used for sqrt(-1)\n\\newcommand{\\Ci}{\\ensuremath{i}}\n\n\\newcommand{\\var}{{\\rm var}}\n\\newcommand{\\trace}{{\\rm tr}}\n\n\\newcommand{\\Rotation}{{\\bf R}}\n\\newcommand{\\Boost}{{\\bf B}}\n\n\\newcommand{\\vRotation}[1][n]{\\ensuremath{\\Rotation_{\\mbfs{\\hat #1}}}}\n\\newcommand{\\vBoost}[1][m]{\\ensuremath{\\Boost_{\\mbfs{\\hat #1}}}}\n\n\\newcommand{\\rotat}{\\ensuremath{\\vRotation(\\phi)}}\n\\newcommand{\\boost}{\\ensuremath{\\vBoost(\\beta)}}\n\n\\newcommand{\\pauli}[1]{\\ensuremath{ {\\mbf{\\sigma}}_{#1} }}\n\n\\begin{document}\n\n\\section{Introduction}\n\nThis is a quick reference for the Measurement and Error Analysis\nLibrary (MEAL).  The classes defined within the {\\tt MEAL} namespace\nimplement a general-purpose library for performing non-linear\nleast-squares and first-order error propagation.\n\n\\section{Function Characteristics}\n\nA mathematical function or expression is characterized by its return\ntype and input variables; a distinction is made between function\nparameters, ${\\mbf a}=(a_0, a_1, ... , a_N)$ and independent\nvariables, or arguments, ${\\mbf x}=(x_0, x_1, ... , x_M)$.  Parameters\nare double-precision floating point values that can vary freely during\nmodeling.  Arguments have arbitrary type and cannot be treated as free\nvariables during modeling.\n\nThe parameter and argument access interface is defined by the {\\tt\nFunction} base class, and the return type is defined by {\\em\nevaluation base classes} that inherit {\\tt Function}.  The evaluation\nbase classes define an {\\tt evaluate} method that returns a result,\n$f({\\mbf x},{\\mbf a})$, and the partial derivatives of this result\nwith respect to each of the parameters, $\\partial f/\\partial a_i$.\n\nThe behaviour of function expression classes is organized into\nthree categories: Parameter, Argument, and Evaluation.  These\nbehaviours are implemented by the children of three base classes, \neach of which inherits the {\\tt FunctionPolicy} base class.  \nThe behaviour policies are mutually exclusive, and derived classes can \nincorporate pre-defined behaviours by setting the appropriate \npolicy attribute.\n\n\\subsection{Parameter Policy}\n\nA function expression may have an arbitary number of scalar parameters,\n$\\mbf{a}=(a_0, a_1, ... , a_N)$.  Each parameter has an associated\nname, estimated variance, and a flag that indicates if the parameter\nis free or fixed.  Parameter management and access is implemented by\nchildren of the {\\tt ParameterPolicy} base class.\n\n\\subsection{Argument Policy}\n\nA function expression may be further parameterized by an arbitrary number\nof independent variables, or arguments, ${\\mbf x}=(x_0, x_1, ... ,\nx_M)$.  Unlike parameters, arguments have no specified type, no\nestimated variance, and can never be free.  Because they have no\nspecified type, the interface between a {\\tt Function} and its\narguments is mediated through the {\\tt Argument} and {\\tt\nArgument::Value} abstract base classes.  Argument management and\nbehaviour is implemented by children of the {\\tt ArgumentPolicy} base\nclass.\n\n\\subsection{Evaluation Policy}\n\nThe return type of a function expression is unspecified in the \n{\\tt Function} base class definition.  Therefore, derived classes must \ninherit an {\\em evaluation base class}.  The evaluation base classes are \nchildren of the {\\tt Function} base class that define an {\\tt evaluate} method\nand an evaluation policy.  There are currently two evaluation base\nclasses:\n\\begin{itemize}\n\\item {\\tt Scalar} - returns a scalar (double-precision) value\n\\item {\\tt Complex2} - returns a $2\\times2$ complex (double-precision) matrix\n\\end{itemize}\nIn addition, a number of template classes, known as {\\tt Rules},\nimplement basic rules of calculus that may be used to simplify the\ncomputation of more complicated expressions and their partial\nderivatives.  There are currently two policies for dealing with the\nevaluation of a evaluation base-derived class: {\\tt Cached} and {\\tt\nNotCached}.\n\n\\section{Modular Construction}\n\nTO DO: Show how new functions can be built up from more basic elements.\n\n\\section{Example Usage}\n\n\\subsection{Non-linear Least-Squares Estimation}\n\nTO DO: Document lmfit\n\n\\subsection{Error Propagation}\n\nThe {\\tt Estimate} template class is very useful for storing a value\nand its estimated variance.  There are also operators and functions\nwhich enable the propagation of error estimates to derived quantities;\nfor example:\n\\begin{verbatim}\nEstimate<float> y (0.596,0.0034);\nEstimate<float> x (-0.83,0.0072);\nEstimate<float> z = pow (y,x);\n\\end{verbatim}\nautomatically computes the variance of the new variable, {\\tt z}.\nHowever, the {\\tt Estimate} template class fails when a variable\nappears more than once in an expression; e.g.\n\\begin{verbatim}\nEstimate<float> ratio = x/x;\n\\end{verbatim}\nshould yield $1\\pm0$; however, the {\\tt Estimate} template class does\nnot recognize that the numerator and denominator are the same\nvariable, and incorrectly sums the weighted variances.\n\nThe problem of correctly computing the partial derivatives of an\nexpression with respect to its variables makes use of the exact same\nfunctionality used to generate the gradient and Hessian matrix in\nnon-linear least squares fitting.\n\nA simplified interface to this functionality is implemented by the\n{\\tt ScalarMath} class.  {\\tt ScalarMath} objects may be conveniently\ninitialized as a single parameter and its estimated variance using the\n{\\tt Estimate} template class.  As with float and double types, {\\tt\nScalarMath} objects may be combined using normal arithmetic operations\nand basic mathematical functions, creating {\\tt Scalar} functions of\nany number of parameters.  For example:\n\\begin{verbatim}\n  MEAL::ScalarMath x (Estimate<double> (0.9587, 0.00058));\n  MEAL::ScalarMath y (Estimate<double> (-0.283, 0.00034));\n  cerr << \"Polar angle = \" << atan2 (y, x) << endl;\n\\end{verbatim}\nyields the output\n\\begin{verbatim}\n  Polar angle = (-0.287039 +/- 0.0189612)\n\\end{verbatim}\n\n\\noindent\nAs with any native type, the {\\tt ScalarMath} class can be used as a\ntemplate argument, e.g.\n\\begin{verbatim}\n  complex<MEAL::ScalarMath> z (Estimate<double> (0.87, 0.0041),\n                               Estimate<double> (2.38, 0.0095));\n\n  complex<MEAL::ScalarMath> w (Estimate<double> (1.74, 0.0081),\n                               Estimate<double> (-.63, 0.0043));\n\n  Jones<MEAL::ScalarMath> jones (z, conj(z),\n                                 conj(w), w);\n\\end{verbatim}\nenabling error propagation through increasingly complex expressions.\n\n\\end{document}\n\n  \\section model Function Components\n\n  All model components that inherit the MEAL::Function abstract\n  base class represent functions of an arbitrary number of variables.\n  A distinction is made between independent variables, or arguments,\n  \\f${\\bf x}=(x_0, x_1, ... , x_M)\\f$, and model parameters, \\f${\\bf\n  a}=(a_0, a_1, ... , a_N)\\f$.  Through use of the\n  MEAL::Argument and MEAL::Argument::Value abstract base\n  classes, model components may be constrained by one or more\n  independent variables of arbitrary type.  The model parameters,\n  \\f${\\bf a}\\f$, represent double precision floating point values\n  that may need to be constrained by some fitting technique.  Function\n  classes should define an evaluation function that returns a result,\n  \\f$M\\f$, and the partial derivative of this result with respect to\n  each of the model parameters, \\f$\\partial M/\\partial a_i\\f$.  The\n  independent variables,\\f$\\bf x\\f$, represent known values, such as\n  observing frequency and epoch, that may be used to further constrain\n  a model.\n\n  The MEAL::Function class does not define the type of value that\n  it represents.  This is defined by derived types, which must define\n  a type named Result and a method named evaluate:\n\n  virtual Result evaluate (std::vector<Result>* gradient = 0) const = 0;\n\n  The evaluate method returns a value of the type specified by Result\n  and, if a pointer to a vector of Result is passed as the first\n  argument, the vector will return the gradient of the return value\n  with respect to the model parameters.\n\n  The Return type and evaluate method are implemented by two main\n  classes of MEAL::Function derived components:\n\n  <UL> \n  <LI> MEAL::Scalar - a scalar function, \n  \\f$f({\\bf a}; {\\bf x})\\f$, such as the MEAL::Polynomial\n  <LI> MEAL::Complex2 - a complex 2x2 matrix function,\n  \\f$J({\\bf a}; {\\bf x})\\f$, such as the MEAL::Coherency matrix \n  and the MEAL::Rotation transformation.\n  </UL>\n\n\n  \\subsection calculus Partial Derivatives\n\n  A number of template classes may be used to simplify the modular\n  construction of more complicated functions.  These templates\n  implement the following basic rules of differentiation:\n\n  <UL> \n\n  <LI> MEAL::ChainRule - an arbitrary function in which\n  one or more parameters is set equal to the ordinate of a \n  MEAL::Scalar function\n\n  <LI> MEAL::BinaryRule - an associative binary operation, such\n  as the sum (MEAL::SumRule) or product\n  (MEAL::ProductRule).\n\n  </UL>\n", "meta": {"hexsha": "c0007d7e70fa5756d16d0a058508558d32063a7f", "size": 9059, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "More/MEAL/MEAL.tex", "max_stars_repo_name": "xuanyuanstar/psrchive_CDFT", "max_stars_repo_head_hexsha": "453c4dc05b8e901ea661cd02d4f0a30665dcaf35", "max_stars_repo_licenses": ["AFL-2.1"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "More/MEAL/MEAL.tex", "max_issues_repo_name": "xuanyuanstar/psrchive_CDFT", "max_issues_repo_head_hexsha": "453c4dc05b8e901ea661cd02d4f0a30665dcaf35", "max_issues_repo_licenses": ["AFL-2.1"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "More/MEAL/MEAL.tex", "max_forks_repo_name": "xuanyuanstar/psrchive_CDFT", "max_forks_repo_head_hexsha": "453c4dc05b8e901ea661cd02d4f0a30665dcaf35", "max_forks_repo_licenses": ["AFL-2.1"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-13T20:08:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-13T20:08:14.000Z", "avg_line_length": 39.9074889868, "max_line_length": 78, "alphanum_fraction": 0.7469919417, "num_tokens": 2270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.3213827096182992}}
{"text": "\\documentclass{article}\n\\usepackage{amsmath}\n\n\n\n\\begin{document}\n\n\\section{ Field Variables }\n\\begin{tabular}{|c|c|c|}\n\\hline\nSymbol & SILO variable name & description \\\\\n\\hline\n$\\rho_i$ & rho\\_1, rho\\_2, rho\\_3, etc. & ith density fraction. \\\\\n$s_i$ & sx, sy, sz & inertial frame momentum \\\\\n$z_i$ & zx, zy, zz & inertial frame spin momentum relative to cell center \\\\\n$g_i$ & gx, gy, gz & gravitational acceleration \\\\\n$\\phi$ & phi & gravitational potential \\\\\n$E$ & egas & kinetic + internal energy density \\\\\n$\\tau$ & tau & entropy tracer \\\\\n\\hline\n\\end{tabular}\n\n\\section{ Other Variable}\n\n\n\n\n\\begin{tabular}{|c|c|c|}\n\\hline\nSymbol & SILO variable name & description \\\\\n\\hline\n$\\mu_i$ & atomic\\_mass[i-1]  & atomic mass number of ith fraction \\\\ \n$Z_i$ & atomic\\_number[i-1]  & electron number of ith fraction \\\\ \n$X$ & X[i-1] & hydrogen mass fraction of each species \\\\ \n$Z$ & Z[i-1] & metallicity of each species \\\\ \n$\\Omega$ & omega & rotation frequency of the grid \\\\\n\\hline\n\\end{tabular}\n\n\\begin{tabular}{|c|c|}\n\\hline\nversion           & version number for this SILO file \\\\\ncode\\_to\\_g       & units used to convert code mass units to grams \\\\\ncode\\_to\\_s       & units used to convert code time units to seconds\\\\\ncode\\_to\\_cm      & units used to convert code length units to centimeters \\\\\nn\\_speces         & number of species, rho\\_1, rho\\_2, etc. \\\\\neos               & equation of state 0 = ideal 1 = Segretain \\\\\ngravity           & true if gravity module is enabled \\\\\nhydro             & true if hydro module is enabled \\\\\nradiation         & true if radiation module is enabled \\\\\noutput\\_frequency & time between outputs - for binary systems this is in \\\\\n                  & units of orbital periods \\\\\nproblem           & problem specification (sod, dwd, etc. ) \\\\\nrefinment\\_floor  & refinemnt density floor in code units \\\\\ncgs\\_time         & physical time of output from t=0 in seconds \\\\\nrotational\\_time  & time in number of orbits \\\\\nxscale            & the length scale of the grid \\\\\nhostname          & name of the machine this file was produced on \\\\\nnode\\_list        & list of all nodes \\\\\nnode\\_positions   & position of each node in the space filling curve \\\\\nnode\\_count       & total number of nodes in octree \\\\\nleaf\\_count       & total number of SILO leaves, this may be less than the \\\\\n                  & total number of octree leaves if compression is on \\\\\ntimestamp         & time the file was written \\\\\nepoch             & starts at 0 and is incremented by one for each restart \\\\ \n                  & since t = 0 \\\\\nlocality\\_count   & number of localities \\\\\nthread\\_count     & total number of threads \\\\\nstep\\_count       & total number of steps \\\\\ntime\\_elapsed     & time in seconds from either startup or the last output \\\\\n                  & to the current output \\\\\nsteps\\_elapsed    & number of steps from either startup or the last output \\\\\n                  & to the current output  \\\\\n\\hline\n\\end{tabular}\n\n\\section{Derived Expressions}\n\ntotal mass density\n\\begin{equation}\n\\rho := \\Sigma_{i=1}^N \\rho_i \n\\end{equation}\n\nx - velocity relative to grid\n\\begin{equation}\nv_x  := \\frac{s_x}{\\rho} + y \\Omega \n\\end{equation}\n\ny - velocity relative to grid\n\\begin{equation}\nv_y  := \\frac{s_y}{\\rho} - x \\Omega \n\\end{equation}\n\nz - velocity relative to grid\n\\begin{equation}\nv_z  := \\frac{s_z}{\\rho} \n\\end{equation}\n\n\\begin{equation}\n\\end{equation}\n\ninternal gas energy density\n\\begin{equation}\ns^2  :=  {s_x}^2 + {s_y}^2 + {s_z}^2\ne    :=  \\begin{cases}\n       E - \\frac{1}{2} \\frac{s^2}{\\rho} & \\text{if } E - \\frac{1}{2} \\frac{s^2}{\\rho} > 0.001 E \\\\\n       \\tau^\\gamma & \\text{else} \\\\\n     \\end{cases} \n\\end{equation}\n\nnumber density of ith fraction (ions + electrons)\n\\begin{equation}\nn_i := \\frac{\\rho_i}{\\mu_i m_H} \\left ( 1 + Z_i \\right ) \n\\end{equation}\n\n\\begin{equation}\n\\gamma := \\frac{5}{3}\n\\end{equation}\n\ntotal number density\n\\begin{equation}\nn := \\Sigma_{i=1}^N  n_i\n\\end{equation}\n\ntemperature\n\\begin{equation}\nT := \\frac{1}{\\gamma-1} \\frac{e}{n}\n\\end{equation}\n\npressure\n\\begin{equation}\nP := \\left(\\gamma-1\\right) e\n\\end{equation}\n\n\n\\end{document}\n", "meta": {"hexsha": "20416f42143aaa082a4b4489d0010c3db6902bd3", "size": 4129, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/silo_format.tex", "max_stars_repo_name": "srinivasyadav18/octotiger", "max_stars_repo_head_hexsha": "4d93c50fe345a081b7985ecb4cb698d16c121565", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2016-11-17T22:35:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T19:07:36.000Z", "max_issues_repo_path": "doc/silo_format.tex", "max_issues_repo_name": "srinivasyadav18/octotiger", "max_issues_repo_head_hexsha": "4d93c50fe345a081b7985ecb4cb698d16c121565", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 123, "max_issues_repo_issues_event_min_datetime": "2016-11-17T21:29:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T21:40:04.000Z", "max_forks_repo_path": "doc/silo_format.tex", "max_forks_repo_name": "srinivasyadav18/octotiger", "max_forks_repo_head_hexsha": "4d93c50fe345a081b7985ecb4cb698d16c121565", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2018-11-28T18:17:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T12:52:37.000Z", "avg_line_length": 30.1386861314, "max_line_length": 98, "alphanum_fraction": 0.6420440785, "num_tokens": 1198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.3213827032754021}}
{"text": "\\subsection{User-defined data types}\n\\label{subsec:library_of_transformations:instance_level_transformations:user_defined_data_types}\n\nIn this section, the instance level transformation corresponding to the type level transformation of user-defined data types is discussed. The type level transformation of user-defined data types can be found in \\cref{subsec:library_of_transformations:type_level_transformations:user_defined_data_types}.\n\nThis definition does not actually introduce values for user-defined data types. This is done upon instantiating the type via a field. Therefore, an empty instance model and empty instance graph will be used for completeness.\n\nFirst, the corresponding instance model is introduced.\n\n\\begin{defin}[Instance model $Im_{UserType}$]\n\\label{defin:library_of_transformations:instance_level_transformations:user_defined_data_types:imod_userdatatype}\nLet $Im_{UserType}$ be the empty instance model $Im_\\epsilon$ (\\cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_instance_models:empty_instance_model}), except that it is typed by the type model $Tm_{UserType}$ (\\cref{defin:library_of_transformations:type_level_transformations:user_defined_data_types:tmod_userdatatype}).\n\\isabellelref{imod_userdatatype}{Ecore-GROOVE-Mapping-Library.UserDataTypeInstance}\n\\end{defin}\n\n\\begin{thm}[Correctness of $Im_{UserType}$]\n\\label{defin:library_of_transformations:instance_level_transformations:user_defined_data_types:imod_userdatatype_correct}\n$Im_{UserType}$ (\\cref{defin:library_of_transformations:instance_level_transformations:user_defined_data_types:imod_userdatatype}) is a valid instance model in the sense of \\cref{defin:formalisations:ecore_formalisation:instance_models:model_validity}.\n\\isabellelref{imod_userdatatype_correct}{Ecore-GROOVE-Mapping-Library.UserDataTypeInstance}\n\\end{thm}\n\nSince $Im_{UserType}$ does not define any objects, there is no need for a visual representation. However, in order to make composing transformation functions possible, $Im_{UserType}$ should still be compatible with the instance model it is combined with.\n\n\\begin{thm}[Correctness of $\\mathrm{combine}(Im, Im_{UserType})$]\n\\label{defin:library_of_transformations:instance_level_transformations:user_defined_data_types:imod_userdatatype_combine_correct}\nAssume an instance model $Im$ that is valid in the sense of \\cref{defin:formalisations:ecore_formalisation:instance_models:model_validity}. Then $Im$ is compatible with $Im_{UserType}$ (in the sense of \\cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_instance_models:compatibility}) if:\n\\begin{itemize}\n    \\item All requirements of \\cref{defin:library_of_transformations:type_level_transformations:user_defined_data_types:tmod_userdatatype_combine_correct} are met, to ensure the combination of the corresponding type models is valid.\n\\end{itemize}\n\\isabellelref{imod_userdatatype_combine_correct}{Ecore-GROOVE-Mapping-Library.UserDataTypeInstance}\n\\end{thm}\n\n\\begin{proof}\nUse \\cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_instance_models:imod_combine_merge_correct}. It is possible to show that all assumptions hold. Now we have shown that $\\mathrm{combine}(Im, Im_{UserType})$ is consistent in the sense of \\cref{defin:formalisations:ecore_formalisation:instance_models:model_validity}.\n\\end{proof}\n\nThe definitions and theorems for the Ecore instance model corresponding to $Tm_{UserType}$ are now complete. \n\n\\subsubsection{The node type encoding}\n\nAs has been shown earlier, an possible encoding for user-defined data types is by introducing a node type. This has been done in $TG_{UserType}$. Like the Ecore instance model, the GROOVE instance graph is also empty, because the values for the type are not instantiated now. This gives rise to $IG_{UserType}$, which is defined as follows:\n\n\\begin{defin}[Instance graph $IG_{UserType}$]\n\\label{defin:library_of_transformations:instance_level_transformations:user_defined_data_types:ig_userdatatype_as_node_type}\nLet $IG_{UserType}$ be the empty instance graph $IG_\\epsilon$ (\\cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_instance_graphs:empty_instance_graph}), except that it is typed by the type graph $TG_{UserType}$ (\\cref{defin:library_of_transformations:type_level_transformations:user_defined_data_types:tg_userdatatype_as_node_type}).\n\\isabellelref{ig_userdatatype_as_node_type}{Ecore-GROOVE-Mapping-Library.UserDataTypeInstance}\n\\end{defin}\n\n\\begin{thm}[Correctness of $IG_{UserType}$]\n\\label{defin:library_of_transformations:instance_level_transformations:user_defined_data_types:ig_class_as_node_type_correct}\n$IG_{UserType}$ (\\cref{defin:library_of_transformations:instance_level_transformations:user_defined_data_types:ig_userdatatype_as_node_type}) is a valid instance graph in the sense of \\cref{defin:formalisations:groove_formalisation:instance_graphs:instance_graph_validity}.\n\\isabellelref{ig_userdatatype_as_node_type_correct}{Ecore-GROOVE-Mapping-Library.UserDataTypeInstance}\n\\end{thm}\n\nIn order to make composing transformation functions possible, $IG_{UserType}$ should be compatible with the instance graph it is combined with.\n\n\\begin{thm}[Correctness of $\\mathrm{combine}(IG, IG_{UserType})$]\n\\label{defin:library_of_transformations:instance_level_transformations:user_defined_data_types:ig_userdatatype_as_node_type_combine_correct}\nAssume an instance graph $IG$ that is valid in the sense of \\cref{defin:formalisations:groove_formalisation:instance_graphs:instance_graph_validity}. Then $IG$ is compatible with $IG_{UserType}$ (in the sense of \\cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_instance_graphs:compatibility}) if:\n\\begin{itemize}\n    \\item All requirements of \\cref{defin:library_of_transformations:type_level_transformations:user_defined_data_types:tg_userdatatype_as_node_type_combine_correct} are met, to ensure the combination of the corresponding type graphs is valid.\n\\end{itemize}\n\\isabellelref{ig_userdatatype_as_node_type_combine_correct}{Ecore-GROOVE-Mapping-Library.UserDataTypeInstance}\n\\end{thm}\n\n\\begin{proof}\nUse \\cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_instance_graphs:ig_combine_merge_correct}. It is possible to show that all assumptions hold. Now we have shown that $\\mathrm{combine}(IG, IG_{UserType})$ is valid in the sense of \\cref{defin:formalisations:groove_formalisation:instance_graphs:instance_graph_validity}.\n\\end{proof}\n\nThe next definitions define the transformation function from $Im_{UserType}$ to $IG_{UserType}$:\n\n\\begin{defin}[Transformation function $f_{UserType}$]\n\\label{defin:library_of_transformations:instance_level_transformations:user_defined_data_types:imod_userdatatype_to_ig_userdatatype_as_node_type}\nThe transformation function $f_{UserType}(Im)$ is defined as the function that always outputs the empty instance graph $IG_\\epsilon$ (\\cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_instance_graphs:empty_instance_graph}), except that it is typed by $TG_{UserType}$.\n\\isabellelref{imod_userdatatype_to_ig_userdatatype_as_node_type}{Ecore-GROOVE-Mapping-Library.UserDataTypeInstance}\n\\end{defin}\n\n\\begin{thm}[Correctness of $f_{UserType}$]\n\\label{defin:library_of_transformations:instance_level_transformations:user_defined_data_types:imod_userdatatype_to_ig_userdatatype_as_node_type_func}\n$f_{UserType}(Im)$ (\\cref{defin:library_of_transformations:instance_level_transformations:user_defined_data_types:imod_userdatatype_to_ig_userdatatype_as_node_type}) is a valid transformation function in the sense of \\cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:transformation_function_instance_model_instance_graph} transforming $Im_{UserType}$ into $IG_{UserType}$.\n\\isabellelref{imod_userdatatype_to_ig_userdatatype_as_node_type_func}{Ecore-GROOVE-Mapping-Library.UserDataTypeInstance}\n\\end{thm}\n\nThe proof of the correctness of $f_{UserType}$ will not be included here. Instead, it can be found in the validated Isabelle theories. Obviously, the proof is trivial, as the function does not do any conversion. It does just output the empty instance model.\n\nFinally, to complete the transformation, the transformation function that transforms $IG_{UserType}$ into $Im_{UserType}$ is defined:\n\n\\begin{defin}[Transformation function $f'_{UserType}$]\n\\label{defin:library_of_transformations:instance_level_transformations:user_defined_data_types:ig_userdatatype_as_node_type_to_imod_userdatatype}\nThe transformation function $f'_{UserType}(IG)$ is defined as the function that always outputs the empty instance model $Im_\\epsilon$ (\\cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_instance_models:empty_instance_model}), except that it is typed by $Tm_{UserType}$.\n\\isabellelref{ig_userdatatype_as_node_type_to_imod_userdatatype}{Ecore-GROOVE-Mapping-Library.UserDataTypeInstance}\n\\end{defin}\n\n\\begin{thm}[Correctness of $f'_{UserType}$]\n\\label{defin:library_of_transformations:instance_level_transformations:user_defined_data_types:ig_userdatatype_as_node_type_to_imod_userdatatype_func}\n$f'_{UserType}(IG)$ (\\cref{defin:library_of_transformations:instance_level_transformations:user_defined_data_types:ig_userdatatype_as_node_type_to_imod_userdatatype}) is a valid transformation function in the sense of \\cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:transformation_function_instance_graph_instance_model} transforming $IG_{UserType}$ into $Im_{UserType}$.\n\\isabellelref{ig_userdatatype_as_node_type_to_imod_userdatatype_func}{Ecore-GROOVE-Mapping-Library.UserDataTypeInstance}\n\\end{thm}\n\nOnce more, the correctness proof is not included here but can be found in the validated Isabelle proofs of this thesis.", "meta": {"hexsha": "21f0ffa18ec15584afbf53337321449a1c5796cc", "size": 9934, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/tex/05_library_of_transformations/03_instance_level_transformations/05_user_defined_data_types.tex", "max_stars_repo_name": "RemcodM/thesis-ecore-groove-formalisation", "max_stars_repo_head_hexsha": "a0e860c4b60deb2f3798ae2ffc09f18a98cf42ca", "max_stars_repo_licenses": ["AFL-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thesis/tex/05_library_of_transformations/03_instance_level_transformations/05_user_defined_data_types.tex", "max_issues_repo_name": "RemcodM/thesis-ecore-groove-formalisation", "max_issues_repo_head_hexsha": "a0e860c4b60deb2f3798ae2ffc09f18a98cf42ca", "max_issues_repo_licenses": ["AFL-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis/tex/05_library_of_transformations/03_instance_level_transformations/05_user_defined_data_types.tex", "max_forks_repo_name": "RemcodM/thesis-ecore-groove-formalisation", "max_forks_repo_head_hexsha": "a0e860c4b60deb2f3798ae2ffc09f18a98cf42ca", "max_forks_repo_licenses": ["AFL-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 99.34, "max_line_length": 431, "alphanum_fraction": 0.8541373062, "num_tokens": 2394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6688802471698041, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.3213826969325048}}
{"text": "The module {\\module{block}}\ncontains code related to blocks and block chains.\nThis includes code to check if a block header is valid\n(including verifying the properties of the staking asset in the ledger),\nwhether a block is valid\nand if a block or block header is a valid successor to a block or block header.\nIn order to verify these properties we need to know when an asset\nis allowed to stake a block.\nWe also allow for the possibility of forfeiture of block rewards as\na punishment for signing on two different short forks.\n\n{\\bf{Note:}} Unit tests for the {\\module{block}} module have not been written.\n\n{\\bf{Note:}} \nIn the Coq formalization the Coq module {\\coqmod{Blocks}}\ncorresponds to {\\module{block}}.\nFor more information, see~\\cite{White2015b}.\n\n\\section{Stake Modifiers}\n\nA {\\defin{stake modifier}} is a 256 bit number.\nThe type {\\type{stakemod}} is defined as four 64-bit integers\nas a way of representing such a 256 bit number.\nThe functions {\\serfunc{seo\\_stakemod}} and {\\serfunc{sei\\_stakemod}}\nserialize and deserialize stake modifiers.\n\nAt each block height there will be a current stake modifier and a future stake modifier.\nThe current stake modifier determines who will be able to stake the next block.\nThe future stake modifier influences the next 256 current stake modifiers.\n\nThe genesis current and future stake modifiers should be set in the variables\n{\\var{genesiscurrentstakemod}} and\n{\\var{genesisfuturestakemod}}.\nThese will determine who will be able to stake the first $256$ blocks\nand will influence who will be able to stake the next $256$ blocks,\nso it is important that these genesis stake modifiers are chosen in a fair manner.\nThe function {\\func{set\\_genesis\\_stakemods}}\nsets {\\var{genesiscurrentstakemod}}\nand {\\var{genesisfuturestakemod}}\nby taking a 160-bit number (as a 40 character hex string),\napplying one round of {\\tt{SHA256}} to obtain the value for\n{\\var{genesiscurrentstakemod}}\nand another round of {\\tt{SHA256}} to obtain the value for\n{\\var{genesisfuturestakemod}}.\\footnote{The plan was to choose some Bitcoin height in the future and when that height was reached to obtain the 160-bit seed number from the last 20 bytes of the hash of the Bitcoin block header at that height.}\n\nThe following three functions operate on stake modifiers.\n\\begin{itemize}\n\\item {\\func{stakemod\\_pushbit}} takes a bit (as a boolean) and a stake modifier, shifts the 256-bit stake modifier (dropping the most significant bit) and using the new bit as the new least significant bit.\n\\item {\\func{stakemod\\_lastbit}} takes a stake modifier and returns its most significant bit (as a boolean).\n\\item {\\func{stakemod\\_firstbit}} takes a stake modifier and returns its least significant bit (as a boolean).\n\\end{itemize}\nThe current stake modifier changes from one block height to the next by\ntaking the last bit of the future stake modifier and pushing this bit onto the current stake modifier.\nThe future stake modifier changes from one block height to the next by\npushing a new bit (either $0$ or $1$) onto the current future stake modifier.\nThis implies those who stake blocks influence what will be the current stake modifiers,\nbut this influence is limited. If one staker staked 50\\% of blocks, the staker would\nchoose approximately $128$ bits of the $256$ stake modifiers in the future.\nThe hope is that this influence is not enough to significantly improve their\nchances in the future, as each bit not chosen by the staker also has a large influence\non who will be able to stake.\n\nThe function {\\func{hitval}} performs one round of\n{\\tt{SHA256}} on the least significant 32-bits of a 64-bit integer (intended to be the current time),\na hash value (intended to be the asset id of the asset to stake) and a stake modifier (intended to be the current stake modifier).\nIt returns the result as 256-bit number called the {\\defin{hit value}}.\n\n\\section{Targets}\n\nA value of type {\\type{targetinfo}} is a triple\nconsisting of the current stake modifier,\nthe future stake modifier\nand the current target (represented by a {\\type{big\\_int}}).\nThe target info used to determine if an asset\nis allowed to stake the next block.\nIn particular, an asset can stake\nthe hit value is less than the current target times the coinage of the staked asset\n(or, the coinage times $1.25$\nif proof of storage is used).\n\nWe have described above how the current and future stake modifiers\nchange at each block height.\nThe current target should also change in order to target an average $10$ minute\nblock. The function {\\func{retarget}} defines how the target changes\nafter each block.\n\n\\begin{itemize}\n\\item {\\var{genesistarget}} is set to the initial target used for the genesis block.\\footnote{It is currently set to $2^{205}$, but this should be reevaluated after a test run and before the launch of Qeditas.}\n\\item {\\var{max\\_target}} is set to the maximum value for the target (i.e., the minimum difficulty). It\nis currently set to $2^{220}$.\n\\item {\\func{retarget}} takes a target $\\tau$ and a number of seconds $\\Delta$ and returns a new target.\nThe intention is that the given target is the current target and the number of seconds\nis the number of seconds between the current block and the previous block.\nThe value is the minimum of either {\\var{max\\_target}} or\n$\\frac{\\tau (9000 + \\Delta)}{9600}$.\nIn particular, the value returned is never more than the value of {\\var{max\\_target}}\nand remains $\\tau$ if $\\Delta$ is 600.\n\\end{itemize}\n\n\\section{Proof of Storage}\n\nThe consensus system for Qeditas is primarily proof-of-stake,\nbut also includes a proof-of-storage component.\nA node can use evidence that it is storing some\npart of a term or document\nto increase the weight of its stake by $25\\%$.\nThe evidence is a value of type {\\type{postor}}, defined by two constructors:\n\\begin{itemize}\n\\item ${\\constr{PostorTrm}}(h,s,\\alpha,k)$ is evidence of storage of part of a term of a type in a theory at a term address.\nThe optional hash value $h$ identifies a theory,\n$s$ is a term, $\\alpha$ is a type\nand $k$ is a hash value.\nHere $s$ should have type $\\alpha$ in the theory identified by $h$.\nThe way this typing constraint is ensured is by checking that the term\naddress correspond to the object $s$ in theory $h$\nhas an owner as an object.\nThis ownership asset should have assed id $k$.\nThe term $s$ is intended to be minimal:\nall except exactly one left of the tree representing $s$ should be \nan abbreviation (i.e., {\\constr{TmH}} of hash roots).\n(This minimality condition is checked by {\\func{check\\_postor\\_tm\\_r}}.)\n\\item ${\\constr{PostorDoc}}(\\gamma,\\nu,h,\\Delta,k)$ is evidence of storage of part of a document at a publication address.\nHere $\\gamma$ is a pay address, $\\nu$ is a hash value (nonce), $h$ is an optional hash value (identifying a theory), $\\Delta$ is a partial document (of type {\\type{pdoc}})\nand $h$ is a hash value.\nThe intention is that $h$ is the asset id for an asset with preasset ${\\constr{DocPublication}}(\\gamma,\\nu,h,\\Delta')$\nheld and the publication address determined by hashing $\\gamma$, $\\nu$, $h$ and $\\Delta'$.\nHere $\\Delta'$ is a document with the same hash root as the partial document $\\Delta$.\nThe partial document $\\Delta$ should be minimal:\nwith exactly one document item containing more than hashes\nand with that one document item only containing one explicit leaf,\nwith others abbreviated by hash roots.\n(This minimality condition is checked by {\\func{check\\_postor\\_pdoc\\_r}}.)\n\\end{itemize}\nValues of type {\\type{postor}}\ncan be serialized and deserialized using\n{\\serfunc{seo\\_postor}} and\n{\\serfunc{sei\\_postor}}.\n\nThe exception {\\exc{InappropriatePostor}} is raised if a value of type {\\type{postor}}\nis not an appropriate proof of storage\nbecause the term or partial document is not minimal.\n\\begin{itemize}\n\\item {\\func{incrstake}} multiplies the number of cants being staked by $1.25$.\nThis is the adjusted stake used when proof of storage is included.\n\\item {\\func{check\\_postor\\_tm\\_r}} checks the minimality condition for a term,\nreturning the hash of the unique important leaf upon success.\n\\item {\\func{check\\_postor\\_tm}} checks if\n${\\constr{PostorTrm}}(h,s,\\gamma,k)$\ncan be used to increase the chances of staking.\nLet $\\alpha$ be the (p2pkh) address where the asset to be staked is held.\nLet $\\beta$ be the term address for the object $s$ of type $\\gamma$ in the theory identified by $h$.\nLet $h'$ be the hash of the unique exposed leaf given by {\\func{check\\_postor\\_tm\\_r}}.\nLet $h''$ be the result of hashing the pair of $\\beta$ and $h'$.\nLet $h'''$ be the result of hashing $\\alpha$ with $h''$.\nThere are two conditions:\n\\begin{enumerate}\n\\item A certain 16 bits of $h'''$ are all $0$. (This means that given a stake address $\\alpha$,\nonly one in every 65536 items of the form\n${\\constr{PostorTrm}}(h,s,\\gamma,k)$\ncan possibly ever be used to help $\\alpha$ stake, independent of targets and stake modifiers.\n\\item The hit value of $h''$ is less than the target times the adjusted stake.\n\\end{enumerate}\n\\item {\\func{check\\_postor\\_pdoc\\_r}} checks the minimality condition for a partial document,\nreturning the hash of the unique important leaf upon success.\n\\item {\\func{check\\_postor\\_pdoc}} checks if\n${\\constr{PostorDoc}}(\\gamma,\\nu,h,\\Delta,k)$\ncan be used to increase the chances of staking.\nLet $\\alpha$ be the (p2pkh) address where the asset to be staked is held.\nLet $\\beta$ be the publication address for the corresponding document asset.\nLet $h'$ be the hash of the unique exposed leaf given by {\\func{check\\_postor\\_pdoc\\_r}}.\nLet $h''$ be the result of hashing the pair of $\\beta$ and $h'$.\nLet $h'''$ be the result of hashing $\\alpha$ with $h''$.\n\\begin{enumerate}\n\\item A certain 16 bits of $h'''$ are all $0$. (This means that given a stake address $\\alpha$,\nonly one in every 65536 items of the form\n${\\constr{PostorDoc}}(\\gamma,\\nu,h,\\Delta,k)$\ncan possibly ever be used to help $\\alpha$ stake, independent of targets and stake modifiers.\n\\item The hit value of $h''$ is less than the target times the adjusted stake.\n\\end{enumerate}\n\\end{itemize}\n\n\\section{Hits and Cumulative Stake}\n\nWe now describe two functions for checking if an asset\n(optionally with proof of storage) is allowed to stake.\nThis is sometimes informally referred to as ``checking for a hit.''\nA third function {\\func{check\\_hit}} is deferred until\nwe discuss block headers.\n\n\\begin{itemize}\n\\item {\\func{check\\_hit\\_b}} is an auxiliary function which does most of the work\nto check if an currency asset can stake a block.\nIt is given the block height, the birthday of the asset, the obligation of the asset,\nthe number of cants $v$ in the currency asset, the current stake modifier, the current target,\nthe current timestamp, the asset id of the asset to stake, the p2pkh address holding the stake address\\footnote{Note that the obligation of the stake address may mean that a different person can spend the staking asset than the holder who can stake the asset. This could be used to, for example, ``loan'' assets to someone else to stake.}\nand an optional proof of storage.\nIf no proof of storage is given,\nthe asset can stake if its hit value (relative to the time stamp and current stake modifier)\nis less than the product of the target and the coinage (as computed by {\\func{coinage}}) of the asset.\nSuppose a proof of storage is given.\nIn this case, we consider an adjusted stake using $1.25 v$ instead of $v$.\nThe asset can stake if the hit value of the asset is less than the target times the coinage of the adjusted stake\nand the proof of storage can be used (as judged by {\\func{check\\_postor\\_tm}} or {\\func{check\\_postor\\_pdoc}}).\n\\item {\\func{check\\_hit\\_a}} is simply a wrapper function which takes the target info (of type {\\type{targetinfo}})\nand calls {\\func{check\\_hit\\_b}} after extracting the current stake modifier and current target\nfrom the target info. Factoring the functions this way makes it clear that\n{\\func{check\\_hit\\_b}} does not depend on the future stake modifier.\n\\end{itemize}\n\nThe best block chain will be the one with the most cumulative stake.\\footnote{The intention is also to have rolling checkpoints to prevent long range attacks.}\nThe cumulative stake is represented by a {\\type{big\\_int}}.\nThe function {\\func{cumul\\_stake}} computes the new cumulative stake\ngiven the previous cumulative stake, the current target $\\tau$\nand the latest delta time (time between blocks) $\\Delta$.\nIt computes this by adding the following (big integer) value to the previous cumulative stake:\n$$\\lfloor \\frac{\\var{max\\_target}}{\\tau \\Delta 2^{-20}} \\rfloor$$\nor adding $1$ if this value is less than $1$.\n\n\\section{Block Headers}\n\nWe now describe block headers.\nA block header is made up of two sets of information:\nthe header data and the header signature.\nThe data part is represented using the\nrecord type \n{\\type{blockheaderdata}}\nwhile the signature part is represented using the record type\n{\\type{blockheadersig}}.\nA block header (of type {\\type{blockheader}})\nis simply a pair of the data with the signature.\nThe functions\n{\\serfunc{seo\\_blockheader}} and\n{\\serfunc{sei\\_blockheader}} serialize and deserialize block headers.\nThere is a value\n{\\var{fake\\_blockheader}}\nwhich can be used when some data structure needs a block header to be initialized.\n\nThe fields in the record type {\\type{blockheaderdata}} are as follows:\n\\begin{itemize}\n\\item {\\field{prevblockhash}} should contain the hash of the data in the previous block header (or {\\val{None}} for the genesis block header).\n\\item {\\field{newtheoryroot}} should be the hash root of the current theory tree (optional {\\type{ttree}}) after the block with this header has been processed.\nIt will change if some transaction in the block publishes a theory specification.\n\\item {\\field{newsignaroot}} should be the hash root of the current signature tree (optional {\\type{stree}}) after the block with this header has been processed.\nIt will change if some transaction in the block publishes a signature specification.\n\\item {\\field{newledgerroot}} should be the hash root of the current compact tree ({\\type{ctree}})\nafter the block with this header has been processed.\nThis will always change since the asset staked will be spent and there will be\noutputs to the coinstake transaction of the block.\n\\item {\\field{stakeaddr}} should be the p2pkh address where the asset being staked is held.\n\\item {\\field{stakeassetid}} should be the asset id of the asset being staked.\n\\item {\\field{stored}} is an optional proof of storage ({\\type{postor}})\nand will be {\\var{None}} if proof of storage was not used to help stake this block.\n\\item {\\field{timestamp}} is a 64-bit integer time stamp and should correspond to the time the block was staked.\n\\item {\\field{deltatime}} is a 32-bit integer which should contain the difference between the time stamp of this block and the time stamp of the previous block. (For the genesis block header, this should simply be $600$.)\n\\item {\\field{tinfo}} should be the target information (current stake modifier, future stake modifier and current target) for this block header.\n\\item {\\field{prevledger}} is an approximation of the compact tree before processing the block corresponding to this block header.\nThis approximation must contain the asset being staked and, if proof of storage is included,\nthe relevant object ownership asset\nor document asset.\n\\end{itemize}\n\nThe fields in the record type {\\type{blockheadersig}} are as follows:\n\\begin{itemize}\n\\item {\\field{blocksignat}} is a cryptographic signature of type {\\type{signat}}.\nThis should be a signature of a hash of the data in the block header.\nUnless an endorsement is used, the signature should be by the private key\ncorresponding to the stake address.\nIf an endorsement is used, the signature should be by the private key\n\\item {\\field{blocksignatrecid}} is an integer which should be between $0$ and $3$.\nIt is included to help recover the public key for the address (either stake or endorsed) from the signature\n(see the function {\\file{recover\\_key}} in the module {\\module{signat}}).\n\\item {\\field{blocksignatfcomp}} is a boolean indicating if the address (either stake or endorsed) corresponds\nto the compressed or uncompressed public key.\n\\item {\\field{blocksignatendorsement}} is an optional endorsement.\nIf {\\val{None}}, then signature corresponds to the stake address.\nSuppose it is $(\\beta,r,b,\\sigma)$ where $\\beta$ is p2pkh address (the endorsed address), $r$ is an integer ($0\\leq r\\leq 3$),\n$b$ is a boolean and $\\sigma$ is a cryptographic signature.\nHere $\\sigma$ should be a signature of the Bitcoin message\n``\\verb+endorse+ $\\beta$''\nwhere $\\beta$ is the endorsed address (as a Qeditas address in base58 format).\nThe signature $\\sigma$ should be by the private key corresponding to the address $\\alpha$\nand $r$ and $b$ are used to recover the public key.\n\\end{itemize}\n\nThe following functions operate on block headers:\n\\begin{itemize}\n\\item {\\func{blockheader\\_stakeasset}} takes block header data ({\\type{blockheaderdata}})\nand tries to return the staked asset by looking it up \nas {\\field{stakeid}} at location {\\field{stakeaddr}} in the compact tree {\\field{prevledger}}.\nThis can fail in two ways.\nFirst, it could be that the staked asset is not found, in which case an exception {\\exc{HeaderNoStakedAsset}} is raised.\nSecond, it could be that {\\field{prevledger}} includes more information than is necessary to give the staked asset,\nin which case an exception {\\exc{HeaderStakedAssetNotMin}} is raised.\\footnote{The purpose of this condition is to prevent attackers from making unnecessarily large headers. The current implementation seems to be flawed, however, as it would not allow the relevant information from proof-of-storage to be included in {\\field{prevledger}}.}\n\\item {\\func{hash\\_blockheaderdata}} hashes the data in the block header. This is to determine\nthe hash to be signed in the signature part\nas well as the hash to be used in the {\\field{previousblockhash}} field of the next block header.\n\\item {\\func{check\\_hit}} takes block header data ({\\type{blockheaderdata}})\nand checks if the given staked asset is allowed to create the block.\nIt simply calles {\\func{check\\_hit\\_a}} after\nextracting the target info ({\\field{tinfo}}), time stamp ({\\field{timestamp}}),\nstake asset id ({\\field{stakeassetid}}),\naddress where the staked asset is held ({\\field{stakeaddr}})\nand the optional proof of storage ({\\field{stored}})\nfrom given block header data.\n\\item {\\func{valid\\_blockheader}} determines if a block header is a valid block at the current height.\nIn order to check if the block is valid the staked asset must be retrieved from\nthe previous ledger.\nThe staked asset must be a currency asset worth $v$ cants.\nThe auxiliary function {\\func{valid\\_blockheader\\_a}} is called with the extra information given by this asset\nwhich in turn calls two (exported) functions:\n{\\func{valid\\_blockheader\\_signat}} and\n{\\func{valid\\_blockheader\\_allbutsignat}}.\n{\\func{valid\\_blockheader\\_signat}} verifies the signature \nin the blockheader to be a valid signature (either directly or via endorsement) of the hash given by {\\func{hash\\_blockheaderdata}}.\n{\\func{valid\\_blockheader\\_allbutsignat}} checks the following conditions:\n\\begin{enumerate}\n\\item The staked asset has the asset id declared in the header.\n\\item The delta time is greater than $0$.\n\\item The staked asset is a ``hit'' for the current block height.\n\\item If proof of storage is included, then the asset id given for the\nobject ownership of the term or\nfor the document\nis in the given approximation of the previous ledger.\\footnote{This probably no longer works if proof of storage is included, due to the minimality constraint on {\\field{prevledger}}.}\n\\end{enumerate}\n\\item {\\func{blockheader\\_succ}} determines if a second block header is a valid successor to a first block header.\nThe following conditions must be checked:\n\\begin{enumerate}\n\\item The second {\\field{prevblockhash}} is the hash of the data in the first given block header.\n\\item The second {\\field{timestamp}} is the sum of the first {\\field{timestamp}} and the second {\\field{deltatime}}.\n\\item The current stake modifier given in the second {\\field{tinfo}}\n is the result of pushing the last bit of the future stake modifier of the first {\\field{tinfo}}\n onto the current stake modifier of the first {\\field{tinfo}}.\n\\item The future stake modifier given in the second {\\field{tinfo}}\n      is the result of pushing a $0$ or a $1$ onto the future stake modifier of the first {\\field{tinfo}}.\n\\item The target given in the second {\\field{tinfo}} is the result of retargeting using\n      the target given in the first {\\field{tinfo}}\n      and the first {\\field{deltatime}}.\n\\end{enumerate}\n\\end{itemize}\n\n\\section{Proof of Forfeiture}\n\nProof of forfeiture is\noptional data proving a staker signed on two recent chain forks within 6 blocks.\nWhen such a proof is supplied by a staker of a block, the new staker can\ntake recent coinstake rewards from the double signing staker.\nSuch a proof is a value of type {\\type{poforfeit}}\nand consists of a 6-tuple\n$$(b_1,b_2,\\overline{c_1},\\overline{c_2},d,\\overline{h}).$$\nHere $b_1$ and $b_2$ are block headers which should contain different data but both be signed by the\nsame stake address.\nThe values $\\overline{c_1}$ and $\\overline{c_2}$ are lists of block header data\neach of which should have length at most 5.\nFinally, $v$ is the number of cants being forfeited\nand $\\overline{h}$ is a list of hash values (asset ids of the rewards being forfeited).\n\nThe function {\\func{check\\_poforfeit}} verifies if the given value of type {\\type{poforfeit}}\ncan be used to support forfeiture of rewards. It first verifies that the data in $b_1$ and $b_2$\nare different (by ensuring their hashes are different)\nand\nare staked using assets at the same stake address $\\alpha$.\nIt also verifies that $\\overline{c_1}$\nand $\\overline{c_2}$ have no more than 5 elements.\nIt then verifies the signatures for $b_1$ and $b_2$.\nIt calls {\\func{check\\_bhl}} on $\\overline{c_1}$ and $\\overline{c_2}$\nto ensure that each forms a (reverse) chain connecting $b_1$ and $b_2$\nto some previous block hashes $k_1$ and $k_2$,\nand then checks that $k_1 = k_2$. This implies $b_1$ and $b_2$ are signed block headers\nforking from a common block (with hash $k_1$). (The function {\\func{check\\_bhl}} also ensures\nthat the hash of $b_2$ does not occur in $\\overline{c_1}$ as this would mean\nthe second chain is a subchain for the first, rather than a fork. Likewise it ensures\nthe hash of $b_1$ does not occur in $\\overline{c_2}$.)\nFinally it calls {\\func{check\\_poforfeit\\_a}}\nwhich looks up assets by the asset ids listed in $\\overline{h}$\nand verifies that each is a reward less than 6 blocks old\nwhich was paid to address $\\alpha$\nand that the sum of these rewards is $v$ cants.\n\n\\section{Blocks}\n\nA {\\defin{block}} consists of a block header and a block delta.\nThe block delta (implemented as the record type {\\type{blockdelta}})\ncontains information about how to transform the previous ledger (compact tree)\ninto the next ledger (compact tree).\nIn particular, the stake output is given (which completes the coinstake transaction)\nand all other transactions in the block are given.\nIn addition, an optional proof of forfeiture is given which may effectively increase\nthe rewards given to the staker of the block.\nIn order to transform the previous ledger,\none will generally need to graft more information about the previous\nledger than was given in the header.\nThis graft is also given.\n\nThe {\\type{blockdelta}} record type consists of four fields:\n\\begin{itemize}\n\\item {\\field{stakeoutput}} is the output to the coinstake transaction.\n\\item {\\field{forfeiture}} is an optional proof that a recent staker signed on a recent fork, thus\njustifying forfeiture of that staker's recent rewards.\n\\item {\\field{prevledgergraft}} is a graft providing the extra information needed by the output of the coinstake transaction, the other transactions in the block and optionally the data in the {\\field{forfeiture}} field.\n\\item {\\field{blockdelta\\_stxl}} is a list of signed transactions, the transactions in the block.\n\\end{itemize}\nThe functions {\\serfunc{seo\\_blockdelta}} and {\\serfunc{sei\\_blockdelta}} serialize\nand deserialize block deltas.\n\nThe type {\\type{block}} is the product of {\\type{blockheader}} and {\\type{blockdelta}}.\nThe functions {\\serfunc{seo\\_block}} and {\\serfunc{sei\\_block}} serialize\nand deserialize blocks.\n\n\\begin{itemize}\n\\item {\\func{coinstake}} builds the coinstake transaction by\nusing the staked asset possibly combined with forfeited rewards as the input\nand taking {\\field{stakeoutput}} from the block delta for the output.\n\\item {\\func{ctree\\_of\\_block}} returns the compact tree of a block (approximating the ledger state before\nprocessing the block) by taking {\\field{prevledger}} from the block header data\nand grafting on {\\field{prevledgergraft}} from the block delta.\nWe call this the {\\defin{compact tree of a block}}.\n\\item {\\func{tx\\_of\\_block}} combines all the transactions in the block (including the coinstake) into one large transaction combining all the inputs and all the outputs.\nThis is used to check validity of blocks.\n\\item {\\func{txl\\_of\\_block}} returns a list of all (unsigned) transactions in the block,\nincluding the coinstake transaction and the underlying transactions listed in {\\field{blockdelta\\_stxl}} of the block delta.\n\\item {\\func{rewfn}} returns the number of cants of the reward at the current block height.\nThe reward schedule is the same as Bitcoins (except for the amount of precision), except with the assumption that the first 350000 blocks have already passed (since this was the block height for the snapshot).\nWe begin counting with a block height of $1$. From blocks $1$ to $70000$,\nthe block reward is $25$ fraenks (2.5 trillion cants).\nAfter this the reward halves every $210000$ blocks.\nSince the initial distribution contained (slightly less than) 14 million fraenks, this leads to cap of 21 million fraenks.\n\\item {\\func{valid\\_block}} checks if a block is valid at the given height.\nIt does this by looking up the staked asset and passing the information to {\\func{valid\\_block\\_a}}\nwhich checks the following conditions:\n\\begin{enumerate}\n\\item The header must be valid.\n\\item The transaction outputs in {\\field{stakeoutput}} must be valid (as judged by {\\func{tx\\_outputs\\_valid}}).\n\\item If the staked asset has an explicit obligation, then ensure the first output on {\\field{stakeoutput}}\nis of a preasset with the same amount of cants and the same obligation sent to the stake address.\\footnote{This is to support ``loaning'' assets for staking.}\n\\item All outputs in {\\field{stakeoutput}} except possibly the first is explicitly must be marked as a reward\nand\nhave a lock in the obligation at least as long as the value given by {\\func{reward\\_locktime}}.\nFurthermore, all the outputs must be sent to the stake address.\nIf the first output in {\\field{stakeoutput}} is not marked as a reward, then it must also\nbe sent to the stake address, must be a Currency asset with the same number of cants as the staked asset\nand must have the same obligation (possibly the default {\\val{None}} obligation) as the staked asset.\n\\item The compact tree of the block must support the coinstake transaction\nand it must have a reward at least\\footnote{This is to allow for collection of fees and of forfeiture of recent awards. The fact that the output is not too high is guaranteed later.}\nas high as the value given by {\\func{rewfn}}.\n\\item There are no duplicate transactions listed in {\\field{blockdelta\\_stxl}}.\n\\item The graft in {\\field{prevledgergraft}} is valid.\n\\item Each transaction in {\\field{blockdelta\\_stxl}} has valid signatures, is valid and is supported by the compact tree of the block. Furthermore, none of these outputs are marked as rewards, none of these transactions spend the asset being staked. Finally, each transaction consumes at least as many cants as required.\n\\item No two transactions in {\\field{blockdelta\\_stxl}} spend the same input.\n\\item No two transactions in {\\field{blockdelta\\_stxl}} create ownership as an object (resp., as a proposition) at the same term address.\n\\item If a transaction in {\\field{blockdelta\\_stxl}} creates ownership as an object (resp., as a proposition)\nat a term address, then the output of the coinstake transaction does not create the same kind of ownership at the term address.\\footnote{It would make sense to simply disallow creation of non-currency assets in the coinstake transaction, but this is not currently the case.}\n\\item If proof of forfeiture is given, then check it is valid and remember the number of cants being forfeited.\n\\item Let $\\cC$ be the result of transforming the compact tree of the block ({\\func{ctree\\_of\\_block}})\nusing the transactions of the block ({\\func{txl\\_of\\_block}}).\nThe hash root of $\\cC$ must be {\\field{newledgerroot}}.\n\\item Let $\\tau=(\\iota,o)$ be the transaction of the block. The following must hold:\n\\begin{itemize}\n\\item The cost of the outputs of $\\tau$ (see {\\func{out\\_cost}})\nis equal to the sum of the assets being spent\nalong with the reward ({\\func{rewfn}})\nand (possibly) the number of cants being forfeited.\n\\item The transformation of the current theory tree by $o$ must have hash root $\\field{newtheoryroot}$.\n\\item The transformation of the current signature tree by $o$ must have hash root $\\field{newsignatroot}$.\n\\end{itemize}\nUpon success, {\\func{valid\\_block}} returns the transformed theory tree and the transformed signature tree.\nUpon failure, either {\\val{None}} is returned or an exception is raised.\n\\end{enumerate}\n\\end{itemize}\n\n\\section{Databases for Block Information}\n\nThere are three databases for blocks, all using the hash of the block header as the key.\nThe module {\\module{DbBlockHeader}} is a database for block headers (implemented using {\\module{Dbbasic2keyiter}})\nand\nthe module {\\module{DbBlockDelta}} is a database for block deltas (implemented using {\\module{Dbbasic2}}).\n\n\\section{Chains}\n\nThere are additional types\n{\\type{blockchain}}\nand \n{\\type{blockheaderchain}}.\nThese can be used to represent (nonempty) chains of blocks or block headers.\\footnote{It is not clear if this is explicitly needed.}\nIn each case the representation is as a pair\nwhere the first component should be the most recent block of block header\nand the second component is a list of the previous blocks or block headers\nin reverse order.\n\nThe variable {\\var{genesisledgerroot}} gives the ledger root of the initial compact tree\nwith the initial distribution. The value is (as of September 2016):\n\\begin{verbatim}\nfc25150b4880e27235d4878637d32f0ffe2280e6\n\\end{verbatim}\n\n\\begin{itemize}\n\\item {\\func{blockchain\\_headers}} converts a block chain into block header chain by dropping the block deltas.\n\\item {\\func{ledgerroot\\_of\\_blockchain}} takes a block chain and returns the value of {\\field{newledgerroot}} in the latest block header data.\n\\item {\\func{valid\\_blockchain}} checks if a block chain is valid at a given height.\nThis requires checking the validity of each block and that each block header is a valid\nsuccessor to the previous block header. It also requires keeping up with the\ntheory tree and signature tree.\nIn the case of the genesis block, the {\\field{prevblockhash}} should be {\\val{None}},\nthe {\\field{prevledger}} should have hash root {\\var{genesisledgerroot}},\nthe {\\field{tinfo}} should be composed of the values in {\\var{genesisccurrentstakemod}},\n{\\var{genesisfuturestakemod}} and {\\var{genesistarget}}\nand the {\\field{deltatime}} should be $600$.\\footnote{Alternatively, one could set a ``genesis timestamp'' and enforce that the {\\field{deltatime}} of the genesis block is the difference between the time stamp of the genesis block and the fixed genesis timestamp.}\n\\item {\\func{valid\\_blockheaderchain}} checks the validity of a block header chain.\nIt is similar to {\\func{valid\\_blockchain}} but only checks the headers are valid\ninstead of the full blocks.\n\\end{itemize}\n", "meta": {"hexsha": "3807526038be7967e1c9b80d52de7e186649cb8c", "size": 32067, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/techdoc/block.tex", "max_stars_repo_name": "dalcoder/dalilcoin", "max_stars_repo_head_hexsha": "aa6a377abd3c0d244e276eadde6a84f5badb8549", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2017-01-26T10:54:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T15:10:52.000Z", "max_issues_repo_path": "doc/techdoc/block.tex", "max_issues_repo_name": "tezosprime/tezosprime", "max_issues_repo_head_hexsha": "151c6aaadea7b2d1ba46a172955ef2122bb66528", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/techdoc/block.tex", "max_forks_repo_name": "tezosprime/tezosprime", "max_forks_repo_head_hexsha": "151c6aaadea7b2d1ba46a172955ef2122bb66528", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-12-28T12:22:45.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-17T14:39:32.000Z", "avg_line_length": 62.7534246575, "max_line_length": 339, "alphanum_fraction": 0.7682352574, "num_tokens": 8013, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.3213713228576996}}
{"text": "\\section{Skeleton Structures for avatars}\nAn avatar that is to be used for (bodily) animation must\nposses a \\emph{skeleton} or \\emph{bones} structure.\nBy this we do not mean a physical model or a visualization of\na real skeleton, but rather a structure consisting \\emph{joints} and\n\\emph{segments} or \\emph{bones} that is to be used for the purpose of animation.\nSee the picture in \\autoref{figure:skeleton} for an example skeleton.\n%\\vspace{ex}\nA skeleton consists of \\emph{joints}, like the Pelvis or Spine nodes in the picture,\nconnected by means of \\emph{segments} (or ``\\emph{bones}''), shown here by means\nof arrows connecting the joints. It will be clear that a skeleton is a rooted tree.\n(For the example skeleton, the root node is the Pelvis node)\n\n\n\n\\input{\\hmigraphicsreportdir/hmi-graphics-skeletonpicture.tex}\n\n\\def\\Alocal{\\mathstrut^L\\!A}\n\n\n%\\[\n%{}^{14}_{2}\\mathbf{C}^{5+}_{2} \\quad\n%\\prescript{14}{2}{\\mathbf{C}}^{5+}_{2} \\quad\n%\\prescript{4}{12}{\\mathbf{C}}^{5+}_{2} \\quad\n%\\prescript{14}{}{\\mathbf{C}}^{5+}_{2} \\quad\n%\\prescript{}{2}{\\mathbf{C}}^{5+}_{2}\n%\\]\n\n\n\\subsection{Affine and linear transforms}\nWithin this chapter by \\emph{linear} transform we mean an ordinary linear mapping for 3D space, represented\nby a $3\\times 3$ matrix $M$.\nA \\emph{translation} $T$ is defined by a 3D translation vector $t$.\nWhen we want to make this vector it explicit, we write $T_t$ for a translation operation.\nAs is well known, a translation operation $T$ is not linear, so cannot be represented by a $3\\times 3$ matrix.\nWe often need the combination $A$ of a linear transform $M$ followed by a translation $T$, so $A=T\\circ M = T\\,M$.\nSuch a combination is called an \\emph{affine} transform.\nThe combination in the reverse order, i.e. $M\\,T = M\\, T_t$ is also affine, since it is equivalent\nto the affine transform $A = T_{t'} \\, M$, where $t'=M(t)$.\nAs a consequence, a composition of affine transforms $A_0$ and $A_1$ is itself also affine:\n%\n\\begin{gather}\\label{affinecomposition}\nA_0A_1 = T_{t_0}\\,M_0\\, T_{t_1}\\, M_1 = T_{t_0}\\,T_{M_0(t_1)}\\,  M_0 \\,M_1 =\nT_{t'}M',\\\\\n\\text{where } t' = t_0 + M_0(t_1) \\text{ and } M' = M_0\\, M_1.\\notag\n\\end{gather}\n%\n\n\\noindent\nA (non-degenerate) linear transformation can be an \\emph{orthogonal} matrix $Q$\nwhich for 3D spaces is either a pure \\emph{rotation} $R$, or else a rotation combined with a \\emph{reflection}.\n(In the latter case it can represented, for instance, as $Q=R\\,N$, where $R$ is a pure rotation,\nand where $N$ is a reflection. For instance, one may choose $N$ to be $-I$.\nAnother important class of linear transforms is that of \\emph{scaling}.\nIn the simplest case, a scaling matrix $S$ is just the ($3\\times 3$) identity matrix multiplied\nwith a \\emph{uniform scaling} factor $s$. A more complex case is when $S$ is a diagonal matrix\nwith three different scaling factors $s_x$, $s_y$, and $s_z$ on the diagonal, which represents axis-aligned\n\\emph{non-uniform scaling}. In the most complicated case, a scaling matrix $S$ is\nnot even diagonal, but it would be diagonal in some rotated coordinate system.\nSo it represents \\emph{non-unform scaling along rotated axes}, a situation sometimes called \\emph{skewing}.\nAn important result here is that by means of so  called \\emph{polar decomposition}\nany (non-degenerate) 3D matrix $M$ can be decomposed as $M=Q\\, S$,\nwhere $Q$ is orthogonal, and where $S$ is a scaling matrix. A nice property of polar decomposition\nis that $Q$ is not just \\emph{any} orthogonal matrix, but that among all orthogonal matrices it is the one\nthat is \\emph{closest} to $M$. We conclude that, for our purpose, we may assume that\nany linear 3D matrix $M$ has the form $R\\,S$ where $R$ is a pure rotation and where $S$ is a scaling matrix,\npossibly combined with a reflection operation.\nOur affine transforms $A$ are therefore of the form $T\\,R\\,S$. Although $A$ is not a 3D linear transform\nit \\emph{can} be represented by a $4\\times 4$ \\emph{homogeneous} transform matrix.\nSo $A$ has a matrix with the $3\\times 3$ matrix for $R\\,S$ in the upper left part, the translation vector\n$t$ for the translation $T$ in the rightmost column, and a\n bottom row of the form $(0,\\;0,\\;0,\\; 1)$.\n\n\n\n\\subsection{Skeleton transforms}\n\\label{sect:skeletontransforms}\n\nThe main use of skeletons is that they organize a collection of transforms, one transform for every skeleton joint $J_i$.\nNote: skeleton joints are sometimes called ``bones''. This terminology is slightly confusing since for others ``bones'' refer to\nthe skeleton segments in between the joints.\n\n\nFor joint transformations we must distinguish between a \\emph{local transforms} $D_i$ versus the \\emph{global transforms} $A_i$\nassociated with each joint $J_i$.\nThe local transform represents the transform caused by that single joint alone.\nThe global transform $A_i$, is the combined effect of all joints\non the path from the skeleton root up to and including the joint itself.\nFor instance, for the joint called L\\_Forearm in the example skeleton,\nthe global matrix $A_\\text{L\\_Forearm}$ represent the rotations and translations\nfrom the Pelvis joint, the various Spine joints, the Neck joint, the\nL\\_Clavicle joint, L\\_UpperArm joint, and finally the L\\_ForeArm joint itself.\n\nThe \\emph{local transform} $D_i$  for a joint represents just the rotation $R_i$ (and possibly scaling $S_i$)\nintroduced by that joint alone, together with the translation that represents the vector $t$ from the parent\nof that joint to the joint itself.\nFor instance, for the L\\_ForeArm joint the local translation is represented by the vector from L\\_UpperArm to L\\_ForeArm.\nNote that each $D_i$ is an affine transform.\n\n\n The idea of a skeleton is that joint transformations are build up hierarchically, following the tree\n structure of the skeleton. So, when some joint $J_i$ has joint $J_p$ as its parent,\n then $A_i = A_p \\, D_i$, where $A_p$ is the transform associated with $J_p$,\n and where $D_i$ is the \\emph{local} transform associated with joint $J_i$.\n For the special case of the root joint $J_0$, there is no parent, and we assume that in this case the\n transform $A_0$ is simply equal to the local transform $D_0$.\n For long chains of joint, we can thus factorize the transform $A$ of the end of the chain into\n the local transforms of the joints on the chain. For instance, for the example skeleton\n we can calculate the affine matrix of, say, the neck joint as follows:\n %\n  \\begin{equation}\n  A_\\textit{Neck} = D_\\textit{Pelvis} \\: D_\\textit{Spine} \\: D_\\textit{Spine1} \\: D_\\textit{Spine2} \\: D_\\textit{Spine3} \\:D_\\textit{Neck}\n  \\end{equation}\n%\n\\input{\\hmigraphicsreportdir/hmi-graphics-skeletonfragment.tex}\nFor the smaller scale example from \\autoref{figure:skeletonfragment}, we have:\n%\n\\begin{equation}\\label{eq:a3}\n A_3 = A_2\\: D_3 = A_1 \\: D_2\\: D_3 = A_0\\: D_1\\:D_2\\:D_3 = D_0\\: D_1\\:D_2\\:D_3.\n \\end{equation}\n%\n% WinEDT bug triggered by this line??:\n%\\input{\\hmigraphicsreportdir/hmi-graphics-skeletonfragment.tex}\n\n\n%\nWe can decompose each local affine transform $D_i$ into a linear transform $L_i$ followed by\na translation $T_{t_i}$, thus: $D_i = T_{t_i}\\: L_i$.\nUsing \\eqref{affinecomposition} we can rearrange equation \\eqref{eq:a3}.\n%\n\\begin{gather}\nA_3 = T_t \\: L\\\\\n \\text{where } t = t_0 + L_0(t_1) + L_0\\,L_1(t_2) + L_0\\,L_1\\,L_2(t_3)\\notag\\\\\n \\text{and where } L= L_0\\,L_1\\,L_2\\,L_3.\\notag\n\\end{gather}\n%\nSo the net effect of a ``chain'' of local affine transforms, from skeleton root up to some skeleton joint,\nis equivalent to a single affine transform for that joint, which we have introduced before: it is the\n\\emph{global} transform for a joint.\n\n\\subsection{Weight blending}\\label{sect:weightblending}\n\n\n\nSkeletons can be controlled and used by animation software; in those cases, we are only concerned\nwith the local and global joint transforms. But skeletons are also used as an interface between\nanimation engines and graphics rendering engines.\nIn this case, the skeleton transforms are used\nto transform geometry that is used for rendering objects, in particular for rendering human avatars.\nThe general idea is that there are one or more \\emph{meshes}, each consisting of many polygons,\nthat model the  geometric shape of body parts.\nThere are two fundamentally different ways of doing this.\nOne rather simple approach is to cut an animated object into parts, each of which is then animated independently,\nunder the control of a single joint, dedicated to that part. For example, the ``blue guy'' avatar\nuses this approach, and uses separate meshes for limbs and other body part.\nThe geometry associated with the elbow region of the body  is transformed exclusively\nby the global affine transform for the elbow joint.\nOne of the advantages of this simple approach is that all mesh vertices inside a single body part\nare transformed by the same affine matrix; a situation that suits the classical render pipeline\nof graphics hardware, as well as the OpenGL and DirectX interfaces for that hardware.\n Simple or not, an unavoidable problem with this approach is that an avatar body as a whole\n shows seams at places where different body parts connect.\n\n An improved form of animating objects like human avatars is to use only \\emph{one seamless mesh},\n and to use the skeleton transforms to deform by the following process:\n Each mesh vertex $v$ is transformed under the influence of one or more joints $J_{i_0}, \\ldots, J_{i_n}$,\n with \\emph{weights} $w_{i_0}, \\ldots, w_{i_n}$ determining the relative influence of each joint.\n The exact set of joints and weights is unique for every individual vertex. Of course, one expects\n that most vertices will be controlled by a fairly low number of joints, typically one or two, and almost always less than four,\n all located in the neighborhood of the vertex. We would like to write down the transformation for some vertex $v$.\n We denote the global transform for joint $J_i$ by $A_i$ and, for simplicity, we assume that we have some vertex $v$\n that is influenced by joints $J_0, \\ldots J_n$.\n The combined transform for $v$ using weight blending is defined as follows\n%\n\\begin{equation}\\label{eq:weightblending-simple}\n v' = \\sum_{i=0}^{n} w_i\\, A_i(v)\n\\end{equation}\n\n\\subsection{Bind poses}\nWeight blending is an adequate animation method, but it requires both a suitable mesh as well\nas a skeleton that ``fits'' into the mesh. A problem here is that designers of meshes and designers\nof skeleton-based animations have slightly conflicting interests:\nAn animation system would prefer a skeleton that is in some well defined neutral pose\nwhen all joint rotations are set to identity transforms. In that case all affine transforms\nreduce to mere translations. The HAnim standard for skeleton based animation, for instance,\nrequires that in this situation the human avatar has a well defined pose where the body is upright,\narms are pointing downwards, fingers are pointing downwards, the thumbs have a $45^\\circ$ degree orientation\nrelative to the fingers, etcetera.\nThe advantage of such a neutral pose is that an animation engine can put the avatar in some pose by setting well defined\nrotations within joints.\n\nDesigners of nice looking avatar meshes though, prefer a \\emph{different} pose, usually with the arms\nhorizontally stretched, also known as the ``T-pose''. The main reason here is that graphics designers\nneed to work on detailed graphic detail, and some areas like arm pits are difficult to reach and problematic when\nthe avatar is in the HAnim neutral pose, rather than the T-pose.\nThere are some variations of this ``T-pose'', for instance with the arms in a straight line but in a slightly lowered\nposition.\n\nThe result is that meshes and skeleton structures usually do \\emph{not} automatically ``match'', and we need some\nprocess called ``binding'' the mesh to the skeleton. One of the steps in the binding process is\nthat the skeleton, starting initially in its neutral pose, is put into ``bind pose'', by applying suitable\nrotations for its joints. For example, for our HAnim style skeleton, the bind pose for a T-shape avatar\nwould include a $90^\\circ$ rotation for the shoulder joints, in order to get the arms into the T-pose.\nOther joints, for instance for arms and fingers, will likely have also non-identity\nrotations in the bind pose, although angles will not be as large as the $90^\\circ$ degree rotations for the shoulders.\nIn other situations for instance in the case of exporting a virtual character from a tool like 3DSMax, the\ntool itself might use rather complicated transformations internally for binding a mesh to a skeleton.\nUnfortunately such more or less ad hoc bind poses show up when you export the mesh to some external format,\nfor instance in the FBX format or the Collada format\nThe message here is that,even if you are willing to design your character in HAnim pose,\nyou still might have to deal with non-trivial bind poses.\n\nAfter putting a skeleton in bind pose,\nthe next step in the bind process is to assign blend weights to the vertices in the mesh.\nWe won't discuss this (complicated) step here, and assume that you have used some tools to do this.\nFor instance,  most 3D modeling tools have a process called ``weight painting'' that allow you to establish blend weights\nin a more or less intuitive way. In practice, assigning blend weight is a trial and error process.\n\nWe continue with the problems for our animation engine,\ncaused by the difference in the neutral skeleton pose and bind pose.\nSay we would like our avatar to be in our neutral pose when all joint rotations\nare set to identity.\nIt is clear that we must adapt our equation \\ref{eq:weightblending-simple}\nfor weight blending.\nSomehow, we must take into account the joint transforms that were used to\nget the skeleton into the correct bind pose. Let's assume that we know the values for (global) affine joint matrices\nin the bind pose, and let's call these matrices the \\emph{bind matrices} $B_i$.\nThe intuitive idea is that we can use the \\emph{inverse} bind matrices $B_i^{-1}$ to bring our mesh\nback into the neutral pose, and from that neutral pose, we bring it into the desired pose for some animation\nspecified by (global) joint matrices $A_i$.\nThis suggest our improved weight blending equation:\n%\n\\begin{equation}\\label{eq:weightblending}\n v' = \\sum_{i=0}^{n} w_i\\, A_i\\,B_i^{-1}(v)\n\\end{equation}\n%\nOne way of seeing that this must be the ``correct'' equation is to put the avatar in its bind pose again,\n by choosing joint transformations $A_i$ equal to the bind matrices $B_i$:\n for in that case the $A_i$ and $B_i^{-1}$ matrices cancel,\nand we have that for all vertices $v' = v$. Which is correct, since the mesh without transforms applied is,\nby definition, in the bind pose.\n\nSince bind matrices are \\emph{fixed}, one might think that you can get rid of the inverse bind matrices\nin \\autoref{eq:weightblending} by applying these inverse bind matrices just once to the mesh, and\nstore the resulting transformed mesh, which would now be in the (by animators) desired neutral pose.\n\n\\noindent\nThis idea \\emph{would} work if every vertex $v$ would be associated with just a single joint, so for the simple\nmodel from section \\ref{sect:weightblending}, one could transform the various body parts by applying\nthe unique $B_i^{-1}$ for that part. (Note that for the rather special case where the bind pose\nis actual the same as the neutral pose, the bind matrices would reduce to  pure translations of the\nform $T(C_i)$, where $C_i$ is the center position of joint $J_i$. So in this particular case,\napplying $B_i^{-1}$ boils down to a ``shifting back to the origin'' operation for the various body parts.)\n\n\\noindent\nUnfortunately, the idea breaks down when more than one joint influences some vertex $v$.\nWhy? let's try. So we store, in an offline process, the mesh transformed into its neutral pose.\nThe result is that we have transformed vertex $v$ into a vertex $v'$ defined by:\n$ v' = \\sum_{i=0}^{n} w_i\\, B_i^{-1}(v)$.\nIf we now apply \\autoref{eq:weightblending-simple}, where we replace $v$ by our ``corrected'' vertices $v'$,\nthen we get the following vertex $v''$ as the result of applying a pose defined by joint matrices $A_i$:\n%\n\\begin{equation}\\label{eq:weightblending-problem}\n v'' = \\sum_{i=0}^{n} w_i\\, A_i(v') = \\sum_{i=0}^{n} w_i\\, A_i(\\sum_{j=0}^{n} w_j\\, B_j^{-1}(v))\n\\end{equation}\n%\nThis last equation \\ref{eq:weightblending-problem} clearly does not yield the\nsame results as equation \\ref{eq:weightblending}.\nFortunately, we can modify and simplify bind matrices if we are willing to adapt transformation matrices\n$A_i$ from animations. We discuss this below.\n\n% second time , but otherwise WinEdt will have problems:\n\\input{\\hmigraphicsreportdir/hmi-graphics-skeletonfragment.tex}\n\n\\subsubsection{Adjusting bind matrices}\n\nWe have seen the generic weight blending equation \\ref{eq:weightblending} above.\nThere are various situations where we would like to modify the (inverse) bind matrices $B_i^{-1}$,\nthereby redefining the ``neutral pose'' for a character.\nOne reason could be that the neutral pose as defined by some 3D modeling tool is inconvenient.\nFor instance, the neutral position for a Collada export from 3DSMax defines a rather strange looking ``neutral'' position.\nMoreover, in such modeling tools the character mesh is often aligned with the Z-axis, (called the ``up-axis'') and for our animation engine\nwe prefer a world where the Y-axis is the ``up-axis''. A final reason would be\nthat we want to switch to a \\emph{new} neutral position like the one defined by the HAnim standard.\nIn all such cases, three things have to happen:\n\\begin{enumerate}\n\\item The \\emph{(inverse) bind matrices} must be changed. This can be done by multiplying $B_i^{-1}$\nby matrices $V_i$ that must be chosen in a suitable way for each of the situations mentioned above.\n\\item The local \\emph{rotations} for every joint to be used for various poses in animations must be adapted accordingly.\nThis step is necessary only when existing animation data that was created for the ``old'' bind matrices.\nWhen new animation data has to be produced it might be much more convenient to work immediately with\nthe ``new'' bind matrices. For instance, if we switch bind matrices that are suitable for HAnim then\nnew animation data should use the HAnim pose as ``neutral'' pose. On the other hand, existing animation data,\nfor instance, data exported from the 3D modeling tool, will be based upon the ``original'' bind matrices, and so\nwe have to convert the rotations from that data.\n\\item The local \\emph{translations} for every joint must be adapted to the new bind matrix.\nThis can be done once, since translations and (modified) bind matrices are not changed by animation data.\nThe only exception here that we allow is the ``humanoid root translation'' $t_0$, for the root joint $J_0$:\nthis translation is sometimes modified in animations.\n\\end{enumerate}\n%\nWe discuss here first the generic case, where we multiply $B_i^{-1}$ by arbitrary $V_i$.\nWe assume here that $V_i$ is just a rotation, and contains no translation.\nThat means that we replace an inverse bind matrix $B_i^{-1} = U_i^{-1}\\,T_{-C_i}$\nby ${B'}_i^{-1} = V_i\\,U_i^{-1}\\,T_{-C_i}$.\nWe consider some (arbitrary) pose based upon the original bind matrices,\nspecified by a series of rotations $R_0, R_1, \\ldots, R_n$.\nFor this pose, joint $J_i$ has a global transformation $M_i$ of the form:\n%\n\\[ M_i = T_{t_0}\\, R_0\\, T_{t_1}\\, R_1 \\cdots T_{t_i}\\, R_i\\, U_i^{-1}\\, T_{-C_i}\\]\n%\nWhen we multiply the $U_i^{-1}$ matrices with $V_i$, we must switch to a new set of translation\nvectors $t_i'$ and new rotation/scaling matrices $R_i'$, as follows:\n%\n\\[ M_i' = T_{t_0'}\\, R_0'\\, T_{t_1'}\\, R_1' \\cdots T_{t_i'}\\, R_i'\\,  V_i U_i^{-1}\\, T_{-C_i}\\]\n%\nWe require that $M_i' = M_i$ for all $i$, something we\ncan realize by making the following choice for $t_i'$ and $R_i'$:\n%\n\\begin{gather}\nt_i'= V_{i-1}(t_i)\\notag\\\\\n R_i' = V_{i-1}\\,R_i\\,V_i^{-1}\\notag\n\\end{gather}\nHere, we use the convention that $V_{-1} = Id$.\nImagine some virtual joint $J_{-1}$ with identity transformations,\nas parent for the humanoid root node $J_0$.\nNote that because of this, the humanoid root translation $t_0$ need \\emph{not} to be transformed,\nwhich is in particular convenient when this translation is modified in an animation.\n%\n\\begin{gather}\n M_i' = T_{t_0'}\\, R_0'\\, T_{t_1'}\\, R_1' \\cdots T_{t_i'}\\, R_i'\\, V_i U_i^{-1}T_{-C_i}\\notag\\\\\n = T_{t_0}\\,R_0\\,V_0^{-1}\\,T_{V_0(t_1)}\\,V_0\\,R_1\\,V_1^{-1} \\cdots \\notag \\\\\n %   V_{i-1}^{-1}\\,T_{V_{i-1}(t_i)}\\,V_{i-1}\\,R_i\\,V_{i}^{-1}\\, V_i U_i^{-1}T_{-C_i}\\notag\\\\\n = T_{t_0}\\,R_0\\,T_{V_0^{-1}(V_0(t_1))}\\,V_0^{-1}\\,\\,V_0\\,R_1 \\,V_1^{-1}\\cdots  \\notag \\\\\n  % T_{V_{i-1}^{-1}(V_{i-1}(t_i))}\\, V_{i-1}^{-1}\\, V_{i-1}\\,R_i\\,V_{i}^{-1}\\, V_i U_i^{-1}T_{-C_i}\\notag\\\\\n  = T_{t_0}\\,R_0\\,T_{t_1}\\,R_1 \\,V_1^{-1} \\,T_{V_1(t_2)} \\, V_1\\,R_2\\,V_2^{-1}\\cdots \\notag = \\cdots\\notag \\\\\n  %T_{V_{i-1}^{-1}(V_{i-1}(t_i))}\\, V_{i-1}^{-1}\\, V_{i-1}\\,R_i\\,V_{i}^{-1}\\, V_i U_i^{-1}T_{-C_i}\\notag\\\\\n  = T_{t_0}\\,R_0\\,T_{t_1}\\,R_1\\,T_{t_2}\\, R_2 \\cdots T_{t_i}\\,R_i\\,V_i^{-1}\\,V_i U_{i}^{-1}T_{-C_i}  =\\notag\\\\\n   = T_{t_0}\\,R_0\\,T_{t_1}\\,R_1\\,T_{t_2}\\, R_2 \\cdots T_{t_i}\\,R_i\\,U_{i}^{-1}T_{-C_i}  = M_i\\notag\n\\end{gather}\n(This was to be shown.)\n\n\n\\subsubsection{Simplifying bind poses}\n\nThe first application of bind pose modification is to \\emph{simplify} the bind matrices.\nThe main reason for this step would be to get rid of overly complicated bind matrices introduced\nby tools like the Collada exported for 3DSMax: the original ``neutral'' pose looks incomprehensible.\nBefore we start simplifying we have a more detailed look at bind poses and bind matrices.\nLet's assume that, in order to put the skeleton in the bind pose, we must apply\n\\emph{local} joint transformations of the form $T_{t_i} L_i$, where $t_i$ is a local translation, and $L_i$ is a local\nrotation (and possibly scaling).\nWe consider the concatenation of such transformations along a path within the skeleton, starting at\nthe humanoid root, and ending in some joint $J_i$.\nFor convenience we assume here that this chain consists of joints $J_0, J_1, J_2, \\ldots, J_i$.\nThe  global transform for  joint $i$ for the bind pose  must be equal to $B_i$.\nFor in that case, it will be canceled by the inverse bind matrix $B_i^{-1}$, and effectively we have \\emph{no}\ntransformation of the mesh. And the pose where there is no transformation is (by definition) the bind pose.\n Therefore, we see that\n %\n \\[ T_{t_0} L_0 T_{t_1} L_1 \\cdots T_{t_i} L_i = B_i = T_{C_i} U_i.\\]\n%\nThe left hand side of this equation can be rewritten as $T_t L$, where:\n\\begin{gather}\n L = L_0 L_1\\cdots L_i = U_i. \\notag \\\\\n t = t_0 + L_0(t_1) + \\cdots + L_0 L_1\\cdots L_{i-1}(t_i) \\notag\\\\\n  = t_0 + U_0(t_1) + \\cdots + U_{i-1}(t_i) = C_i \\notag\n\\end{gather}\n%\nThe easiest way to simplify bind matrices is\nto replace bind matricies of the form $B_i = T_{C_i} U_i$ by  new\nbind matrices ${B'}_i = T_{C_i}$. So, basically, we want to drop the rotation and scaling parts $U_i$ altogether,\nso that only a translations remains.\nClearly, what must be done is to multiply $B_i^{-1}$ by $U_i$, for in that case we have that\n${B'}_i^{-1} = U_i U_i^{-1} T_{-C_i} = T_{-C_i}$, which is the desired inverse bind matrix.\nFrom the previous section we now see that we must adapt local translations $t_i$ and rotation $R_i$\nas follows:\n\\begin{gather}\nt_i'= U_{i-1}(t_i)\\notag\\\\\nR_i' = U_{i-1}\\,R_i\\,U_i^{-1}\\notag\n\\end{gather}\n%\nFrom the equation above for $t = \\cdots = C_i$, we see that $t_i' = C_i - C_{i-1}$\nSo the modified translation vector $t_i'$ is simply the translation vector from the center position\nof joint $J_{i-1}$ to the center position of joint $J_i$ within the bind pose.\n\n\\subsubsection{Reorienting your avatar}\nThe next step that we want to discuss is how to re-orient mesh data. What we want is an avatar\nwith its mesh and skeleton aligned with the Y-axis, looking into the positive Z-axis direction.\nSlightly more general, we want to apply some (linear) coordinate transform $R$ to the mesh, skeleton,\nand animation poses. For example, if we have some avatar with mesh and skeleton aligned with the Z-axis,\nand some pose where the shoulder joint rotates $-45^\\circ$ around the Y-axis,\nthen after the coordinate transform we have a mesh and skeleton aligned with the Y-axis, and the same\npose now has a shoulder joint rotation of $+45^\\circ$ around the Z-axis.\nIn this case, the coordinate transform $a$ is a rotation of $-90^\\circ$ around the X-axis.\n\nAssume that we have some linear coordinate transform $R$. Usually, $R$ will be a rotation, but it\ncould include scaling.\nWe want to transform mesh coordinates $v$ into $v' =R(v)$, and then later on use our adapted skeleton\nto operate on this transformed mesh.\nThe question now is: how to adapt the skeleton and animation poses.\n\nAssume that some pose is described by local affine joint transforms $D_i$ which\ndescribe local joint pose like the shoulder joint in the example above.\nWithin the new coordinates, the effect of $D_i$ will be achieved\nby $D'_i = R\\:D_i\\:R^{-1}$.\n(Just examine the effect of $D'_i$ on some ``new'' coordinate of the form $v' = R(v)$. The result is that\n$D'_i(v') = R\\:D_i\\:R^{-1} (R(v)) = R\\:D_i(v)$.)\nOf course this is to be expected: $R\\:D_i\\:R^{-1}$ is just the standard linear algebra result\nfor how matrices change under coordinate transforms.\nNow we must take into account that the local transforms $D_i$ that describe some pose\nare affine transforms of the form $D_i = T_{t_i}\\:L_i$ where $t_i$ is the (fixed) local skeleton translation\nfrom the parent of joint $J_i$ to $J_i$ itself, and where $L_i$ is the (changing) rotation matrix for joint $J_i$.\nWe can rewrite the  $D'_i$:\n\\begin{equation}\nD'_i = R\\:D_i\\:R^{-1} = R\\:T_{t_i}\\,L_i\\:R^{-1}\n=R\\,T_{t_i}\\,R^{-1}\\:R\\,L_i\\,R^{-1}.\n\\end{equation}\nThe rightmost three factors, i.e. $R,L_i\\,R^{-1}$, are just the transformed rotations $L'_i$, adapted to\nthe new coordinate system. For instance, if $L_i$ would be the $-45^\\circ$ around the Y-axis from the example\nabove, and $R$ would be the coordinate transform defined by a $-90^\\circ$ rotation around the X-axis,\nthen $R\\:L_i\\:R^{-1}$ is actually the $+45^\\circ$ around the Z-axis, as expected.\n\n\\noindent\nThe left most factors, i.e. $R\\,T_{t_i}\\,R^{-1}$ are the modified translations.\nWe can simplify this considerably:\n\\begin{equation}\\label{eq:transormedtranslation}\nR\\:T_{t_i}\\:R^{-1}\n=T_{R(t_i)}\\:R\\:R^{-1}\n=T_{R(t_i)}\n\\end{equation}\n\n\\noindent\nFinally, we can see how this all fits together, when we apply an linear transform $R$ to\na mesh that is being deformed by means of weight blending, specified by \\autoref{eq:weightblending}.\nWe assume that  $A_i = T_{t_i}\\,L_i$, that $B_i^{-1} = U_i\\,T_{-C_i}$.\nWe denote by $L'_i$ the transformed $L_i$, that is, $R\\,L_i\\,R^{-1}$.\n Similarly  we define ${U'}_i^{-1} = R\\,U_i^{-1}\\,R^{-1}$.\nThen the result of applying $R$ yields the following transformed blend equation:\n%\n\\begin{equation}\n R \\:\\sum_{i=0}^{n} w_i\\, A_i\\,B_i^{-1} = \\sum_{i=0}^{n} w_i\\, R\\,A_i\\,B_i^{-1} \\quad\\text{, where}\\notag\n \\end{equation}\n %\n \\begin{gather}\n R\\,A_i\\,B_i^{-1} = \\notag\\\\\n R\\,T_{t_0}\\,L_0\\,T_{t_1}\\,L_1\\cdots T_{t_i}\\,L_i,U_i^{-1}\\,T_{-C_i}=\\notag\\\\\n R\\,T_{t_0}\\,R^{-1}\\,R\\,L_0\\,R^{-1}\\,R\\,T_{t_1}\\,L_1\\cdots T_{t_i}\\,L_i\\,U_i^{-1}\\,T_{-C_i} =\\notag\\\\\n T_{R(t_0)}\\,L'_0\\, R T_{t_1}\\,L_1\\cdots T_{t_i}\\,L_i\\,U_i\\,T_{-C_i} =\\cdots=\\notag\\\\\n T_{R(t_0)}\\,L'_0\\,T_{R(t_1)}\\,L'_1\\cdots T_{R(t_i)}\\,L'_i\\,U'_i\\,T_{R(-C_i)}\\,R\\notag\n \\end{gather}\n %\n The remaining $R$ at the right end of this last formula is the transform to be applied on the mesh.\n\n We conclude that, apart from transforming the mesh by means of applying $R$ to the vertices,\n we need to adapt translation vectors $t_i$, rotation/scaling matrices $L_i$,\n and the  as follows:\n\\begin{gather}\nt_i'= R(t_i)\\notag\\\\\nL_i' = R\\,L_i\\,R^{-1}\\notag\\\\\nC_i' = R(C_i)\\notag\\\\\nU_i' = R^{-1} U_i R\n\\end{gather}\n\n Since the translations, and the bind matrices are fixed, they can be calculated before we start rendering.\n This is very similar to the transformations for simplifying the bind matrix.\n What is different is that the translation part of the bind matrix is also modified\n\n\n\n\\subsubsection{Redefining the avatar neutral pose}\n\nThe result of the previous sections is an avatar where the original bind pose is also the neutral pose,\nthat is, when all local rotation matrices are set to identity, the avatar will assume a pose equal to\nthe bind pose. We would like to change this, and define some other pose, say the HAnim pose,\nto be the neutral pose.\nThis problem can be split into two steps:\n\\begin{enumerate}\n\\item First, find out how to put the avatar in the HAnim pose,\n\\item Second, define that pose as the neutral pose, by adapting transformations and bind matrices.\n\\end{enumerate}\n%\nWe start with the second step, so, we assume that we have a a pose defined by local rotations (and possibly scaling) $H_i$\nthat define a pose that we would like to set as the neutral pose.\nUsing the existing bind matrices and translation vectors, the global transform for joint $J_i$ for this new neutral pose is:\n%\n\\begin{equation}\nT(t_0)\\,H_0\\,T(t_1)\\,H_1\\,T(t_2)\\, L_2\\cdots T(t_i)\\,H_i\\,B_i^{-1}\\notag\n\\end{equation}\n%\n\nWe would like to modify the bind matrices in such a way that we can represent the same pose using \\emph{identity}\nmatrices replacing the $H_i$ matrices.\nThis can be achieved by using new inverse bind matrices ${B'_i}^{-1}$ and new translation vectors $t_i'$ of the form\n\\begin{gather}\n{B'_i}^{-1} = V_i B_i^{-1} \\notag\\\\\nt_i' = V_{i-1}(t_i) \\textrm{, where} \\notag \\\\\nV_i = H_0 H_1 \\cdots H_i\\notag\\\\\n\\end{gather}\n%\nAlso, an existing (arbitrary) animation pose, defined by rotations/scalings \\\\\n$R_0, R_1, \\ldots , R_n$, must be replaced by an adapted pose $R_0', R_1', \\ldots, R_n'$ where:\n \\[R_i' = V_{i-1} R_i V_i^{-1} \\notag.\\]\n\n\nFor the \\emph{first} step, i.e. putting some skeleton in the HAnim pose, one can use various techniques;\nin the end, all that count is that our VH is in the desired pose.\nFor a pose like the HAnim standard, it is often useful to have a method that aligns specified segments\nof the human body with direction vectors $\\mathit{dir}$. For example, the HAnim standard requires that upper and lower arm\nare ``hanging downwards'', i.e. are aligned with the direction of the (negative) Y-axis.\nIn this case, we would align those segments with a direction vector $(0, -1, 0)$.\nLet us assume that we have determined that the current situation of the body is such that we\nhave two joints, a parent and a child, and that the segment in between those two joints is currently\naligned with some vector $a$.\nIt is easy to establish a quaternion that rotates $a$ into $\\mathit{dir}$.\n(We assume that both $a$ and $\\mathit{dir}$ are normalized vectors, i.e. $|a| = |\\mathit{dir}| = 1$:\nLet $h = ( (a+\\mathit{dir})/ |a+\\mathit{dir}|)$. (That is, $h$ is the normalized half-vector in between $a$ and $\\mathit{dir}$.)\nNow q is simply $(a\\cdot h, a\\times h)$. We are not done yet, since we now know how to rotate our segment \\emph{after} that segment\nhas been rotated by the skeleton transforms. Let us denote the latter rotation by a quaternion $r$.\nThen our construction delivers a quaternion $q$ as above, with the property that $q\\,r$ is a rotation that puts our segment\nin the desired orientation. Here, $r$ itself is a product like $r = r_0 r_1, \\cdots r_n$, where the quaternions $r_i$ are\nthe current (local) rotations of the skeleton joints, starting at the root, up to and including the parent joint rotation.\n What we want instead is a quaternion $s$ with the property $q\\, r = r\\, s$,\nfor in that case, we can replace the local quaternion $r_n$ by $r_n\\, s$, i.e. a post multiplication\nof the local parent joint rotation $r_n$  with the $s$ quaternion. From the equation it follows\nthat $ s= r^{-1}\\, q\\,r$. (Basically, this is is $q$ rotated by $r^{-1}$.)\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "4889b97b47a9b936e64552f10dbd3183c240ba19", "size": 31957, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "HmiGraphics/docs/report/hmi-graphics-skeletons.tex", "max_stars_repo_name": "ArticulatedSocialAgentsPlatform/HmiCore", "max_stars_repo_head_hexsha": "9eeca222ba29413fde786ceef0e2ffb839212036", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-10-26T14:52:01.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-08T09:59:05.000Z", "max_issues_repo_path": "HmiGraphics/docs/report/hmi-graphics-skeletons.tex", "max_issues_repo_name": "ArticulatedSocialAgentsPlatform/HmiCore", "max_issues_repo_head_hexsha": "9eeca222ba29413fde786ceef0e2ffb839212036", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HmiGraphics/docs/report/hmi-graphics-skeletons.tex", "max_forks_repo_name": "ArticulatedSocialAgentsPlatform/HmiCore", "max_forks_repo_head_hexsha": "9eeca222ba29413fde786ceef0e2ffb839212036", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-03T09:20:40.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-03T09:20:40.000Z", "avg_line_length": 59.7327102804, "max_line_length": 139, "alphanum_fraction": 0.7368651626, "num_tokens": 9324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3211598555735616}}
{"text": "\\chapter{The Bow}\\label{ch:bow}\nThe bow is an extremely interesting excitation mechanism from a simulation perspective.\nA bow excites a string with a force due to friction, which introduces a nonlinear element into the system.\nThe string `sticks' to the bow and `slips' again when the restoring force of the string is too great and overcomes the friction force. This `stick-slip' behaviour, first coined by Bowden and Leben in 1939 \\cite{Bowden1939} causes the string to move in a characteristic triangular motion where the corner of the triangle moves back and forth along the string (see Figure \\ref{fig:helmholtz}). Herman Helmholtz was the first to discover this behaviour in the 19\\th century, and later got named \\textit{Helmholtz motion} in his honour \\cite{Helmholtz1860}.\\footnote{Also see \\url{https://www.youtube.com/watch?v=6JeyiM0YNo4}}\n\n\\begin{figure}[h]\n    \\centering\n    \\begin{tikzpicture}[->,node distance=3cm,\n        thick,main node/.style={circle,draw}, scale=0.96, every node/.style={scale=0.96}]\n    \n        \\node[] (image) at (0,0) {\\includegraphics[width=1\\columnwidth]{figures/exciters/helmholtz.eps}};\n    \n        \\draw[thick, ->] (-0.25,0.60) arc (110:430:0.6);\n        \n      \\end{tikzpicture}\n    \\caption{Helmholtz motion. If the bow moves up on the left side of the string, the `Helmholtz corner' travels anti-clockwise. \\label{fig:helmholtz}}\n\\end{figure}\n\nThe Helmholtz motion gives bowed string instruments, such as the violin and cello, their characteristic sound. An ideal case is shown in Figure \\ref{fig:helmholtzTimedomain}, where, for a string described by $u(x,t)$, the location of a point $x_\\text{out}$ along the string follows a sawtooth-like motion due to the `stick-slip' behaviour. \n% Figure \\ref{fig:helmholtzImplementation} for a time domain output of one point along a bowed stiff string. The string is bowed upwards, and the `stick-slip' behaviour is visible (stick for upwards, slip for downwards motion), creating a sawtooth pattern. \n\\begin{figure}[t]\n    \\centering\n    \\includegraphics[width=\\textwidth]{figures/exciters/helmholtzTimedomain.eps}\n    \\caption{An example of the (ideal) Helmholtz motion of a location $x_\\text{out}$ along a bowed string. \\label{fig:helmholtzTimedomain}}\n\\end{figure}\n\nThe rest of this chapter is structured as follows: first, a brief history of bowed-string simulations is presented. Then, an introduction to interpolation and spreading operators, as well as an introduction to the Newton-Raphson method will be given, both of which are necessary to work with bow-string interaction. Finally, a static and a dynamic friction model are presented. The latter, the elasto-plastic friction model, was applied to a FD scheme of the stiff string during this project and is one of the contributions, published in paper \\citeP[C].\n\n\\section{Brief history of bowed-string simulation}\nThe first nonlinear systems in the context of musical instrument simulations, including the bowed string, were presented by McIntyre, et al. in 1983 \\cite{McIntyre1983}. The first real-time implementation of the bowed string was due to Smith in 1986 and used digital waveguides for the string and a look-up table for the friction model \\cite{Smith1986}. Simultaneously, Florens et al. presented a real-time implementation of the bowed string, but instead, the string was modelled using mass-spring systems and the friction model used a static friction model \\cite{Florens1986} (see Section \\ref{sec:staticFricMod}). One of the most complex friction models applied in a musical context to-date is the elasto-plastic friction model due to Dupont \\cite{Dupont2002}, which Serafin et al. \\cite{Serafin2003, Serafin2004} applied to a digital waveguide implementation of the string. \n\nThe first appearance of FDTD methods in bowed string simulations was in a publication by Pitteroff and Woodhouse in \\cite{Pitteroff1998}. Later, Maestre et al. in \\cite{Maestre2014} used FDTD methods to implement a thermal friction model proposed by Woodhouse in \\cite{Woodhouse2003}. In both cases, the string was implemented using digital waveguides. Desvages implemented a bowed string model using a static friction model and a two-polarisation FDTD model for the string in \\cite{Desvages2016, Desvages2018}, but did not implement this in real-time. The first real-time implementation of a bowed stiff string fully modelled using FDTD methods was presented in paper \\citeP[A]. Finally, paper \\citeP[C] presented the first (real-time) implementation of the elasto-plastic friction model applied to a FD scheme in a musical context.\n\n\\section{Interpolation and spreading operators}\\label{sec:interpolationSpreading}\nTo listen to, or interact with a FD scheme between grid points, it is necessary to use some form of interpolation. \n% As should be clear by now, FD schemes are an approximation to continuous space (and time) using a finite number of points. Working with the system between grid points is not impossible, but requires an extra step. If one would like to listen to a location between specified grid points, one can use interpolation. \nFor this end, an \\textit{interpolation operator} $I(x_\\itxt)$ can be introduced and can be applied to a grid function \\cite{theBible}. This operator is a function of $x_\\itxt$, the (continuous) location of interest and can be defined in various levels of accuracy. In this section, a 1D system $u(x,t)$ is assumed where $x\\in \\D$ for spatial domain $\\D$. The theory presented in this section will be extended to 2D in Section \\ref{sec:interpolationSpreading2D}.\n\nAn interpolation operator can be applied to a grid function $\\uln$, which performs the following operation:\n\\begin{equation}\n    I_{l,o}(x_\\itxt)u_l^n = \\sum_{l\\in d} I_{l,o}(x_\\itxt)\\cdot u_l^n.\n\\end{equation} \nHere, $o$ is the order of the operator, and $l\\in d$ with discrete domain $d$, which needs to be the same for both $I_{l,o}(x_\\text{i})$ and $\\uln$.\n\nThe simplest interpolation operator is of '0\\textsuperscript{th}'-order and is defined as\n\\begin{equation}\\label{eq:zerothOrderI}\n    I_{l,0}(x_\\itxt) = \\begin{cases}\n        1, & \\text{if}\\ l = l_\\itxt,\\\\\n        0, & \\text{otherwise},\n    \\end{cases}\n\\end{equation}\nwhere the grid location of interest is defined as $l_\\itxt = \\floor[x_\\itxt / h]$ (see Figure \\ref{fig:zerothOrderInterpol}). Instead of actually performing an interpolation operation, $I_0$ simply floors its input to the grid location below. \n%As an example, for a 1D system of length $L=1$ described by $u(x,t)$, the location of interest is at $x_\\itxt = 0.25$. If the grid spacing $h = 0.2$ the grid point of interest will be $l_\\itxt = \\floor[0.25/0.2] = \\floor[1.25] = 1$. Writing this in operator form yields\n% \\begin{equation*}\n%     u(0.25, t)\\approxeq I_{l,0}(0.25)\\uln = u_1^n.\n% \\end{equation*}\n%\n% \\input{exciters/interpolation.tex}\n%\nA slightly more accurate way to perform 0\\thOrder interpolation is to round $x_\\itxt/h$ to the nearest neighbour, rather than using the flooring operation. \n\nFirst-order or linear interpolation uses the fractional part of the flooring operation as well, according to $\\alpha_\\itxt = x_\\itxt / h - l_\\itxt$ and is defined as\n\\begin{equation}\\label{eq:firstOrderI}\n    I_{l,1}(x_\\itxt) = \\begin{cases}\n        (1-\\alpha_\\itxt), & \\text{if}\\ l = l_\\itxt,\\\\\n        \\alpha_\\itxt , & \\text{if}\\ l = l_\\itxt + 1,\\\\\n        0 & \\text{otherwise.}\n    \\end{cases}\n\\end{equation}\nSee Figure \\ref{fig:firstOrderInterpol}. \n% Using the same example as before, $\\alpha = 1.25 - \\floor[1.25] = 0.25$ and\n% \\begin{equation*}\n%     u(0.25, t)\\approxeq I_{l,1}(0.25)\\uln = 0.75u_1^n + 0.25 u_2^n,\n% \\end{equation*}\n\nThe highest order interpolator used in this project is the Lagrange cubic interpolator: \n\\begin{equation}\\label{eq:cubicI}\n    I_{l,3}(x_\\itxt) = \\begin{cases}\n        -\\alpha_\\itxt (\\alpha_\\itxt-1)(\\alpha_\\itxt-2)/6, & l = l_\\itxt-1,\\\\\n        (\\alpha_\\itxt-1)(\\alpha_\\itxt+1)(\\alpha_\\itxt-2)/2,  & l = l_\\itxt,\\\\\n        -\\alpha_\\itxt (\\alpha_\\itxt+1)(\\alpha_\\itxt-2)/2, & l = l_\\itxt + 1,\\\\\n        \\alpha_\\itxt (\\alpha_\\itxt+1)(\\alpha_\\itxt-1)/6, & l = l_\\itxt + 2,\\\\\n        0, & \\text{otherwise.}\n    \\end{cases}\n\\end{equation}\nSee Figure \\ref{fig:cubicInterpol}. \n% Applied to a grid function using the same example as before, yields\n% \\begin{equation*}\n%     u(0.25, t)\\approxeq I_{l,3}(0.25)\\uln = -0.0547u_0^n + 0.8203u_1^n + 0.2734u_2^n -0.0391 u_3^n.\n% \\end{equation*}\nNotice that the sum of all values of $I_{l, o}(x_\\itxt)$, regardless of the order or the value of $\\alpha_\\itxt$, add up to $1$.\n\n\nOne could potentially create higher-order interpolation operators, but as one is restricted to a finite domain, the flexibility of the implementation reduces. Notice that if $\\alpha_\\itxt = 0$, the higher-order interpolators reduce to the $0$\\thOrder interpolator in Eq. \\eqref{eq:zerothOrderI}.\n\\def\\figWidth{0.32}\n\\begin{figure}[h]\n    \\centering\n    \\subfloat[$0$\\thOrder interpolation.\\label{fig:zerothOrderInterpol}]{\\includegraphics[width=\\figWidth\\textwidth]{figures/exciters/noInterpol2.pdf}}\\hfill\n    \\subfloat[Linear interpolation.\\label{fig:firstOrderInterpol}]{\\includegraphics[width=\\figWidth\\textwidth]{figures/exciters/linearInterpol2.pdf}}\\hfill\n    \\subfloat[Cubic interpolation.\\label{fig:cubicInterpol}]{\\includegraphics[width=\\figWidth\\textwidth]{figures/exciters/cubicInterpol2.pdf}}\n    \\caption{Interpolation with varying orders of accuracy.\\label{fig:interpolation}}\n\\end{figure}\n\nApart from interpolation operators, one may define \\textit{spreading operators} which can be interpreted as an inverse interpolation operation. A spreading operator $J(x_\\itxt)$ is used to interact with a distributed FD scheme in the form of an excitation or other interactions such as connections or collisions between multiple schemes (also see Part \\ref{part:interactions}).\n\nThe spreading operators can be defined in the same way as the interpolation operators described above, yielding a $0$\\thOrder spreading operator\n\\begin{equation}\\label{eq:zerothOrderJ}\n    J_{l,0}(x_\\itxt) = \\frac{1}{h}\\begin{cases}\n        1, & \\text{if}\\ l = l_\\itxt,\\\\\n        0, & \\text{otherwise},\n    \\end{cases}\n\\end{equation}\na linear spreading operator\n\\begin{equation}\\label{eq:firstOrderJ}\n    J_{l,1}(x_\\itxt) = \\frac{1}{h}\\begin{cases}\n        (1-\\alpha_\\itxt), & \\text{if}\\ l = l_\\itxt,\\\\\n        \\alpha_\\itxt , & \\text{if}\\ l = l_\\itxt + 1,\\\\\n        0 & \\text{otherwise,}\n    \\end{cases}\n\\end{equation}\nand a Lagrange cubic spreading operator\n\\begin{equation}\\label{eq:cubicJ}\n    J_{l,3}(x_\\itxt) = \\frac{1}{h}\\begin{cases}\n        -\\alpha_\\itxt (\\alpha_\\itxt-1)(\\alpha_\\itxt-2)/6, & l = l_\\itxt-1,\\\\\n        (\\alpha_\\itxt-1)(\\alpha_\\itxt+1)(\\alpha_\\itxt-2)/2,  & l = l_\\itxt,\\\\\n        -\\alpha_\\itxt (\\alpha_\\itxt+1)(\\alpha_\\itxt-2)/2, & l = l_\\itxt + 1,\\\\\n        \\alpha_\\itxt (\\alpha_\\itxt+1)(\\alpha_\\itxt-1)/6, & l = l_\\itxt + 2,\\\\\n        0, & \\text{otherwise.}\n    \\end{cases}\n\\end{equation}\nNotice the scaling by $1/h$ which will be more elaborated on in Chapter \\ref{ch:connections}. As is the case with the interpolation operators, higher-order spreading operators reduce to Eq. \\eqref{eq:zerothOrderJ} if $\\alpha_\\itxt = 0$.\n\nSpreading operators approximate the spatial Dirac delta function $\\delta(x-x_\\itxt)$ (in m$^{-1}$), which is a test function defined as\n\\begin{equation}\\label{eq:spatialDirac}\n    \\delta(x)= \\begin{cases}\n        \\infty, & x = 0,\\\\\n        0, & \\text{otherwise},\n    \\end{cases} \\qaq \\int_{-\\infty}^{\\infty} \\delta(x)dx = 1,\n\\end{equation}\nused in continuous time to locate an external force to a location $x_\\itxt$ along a system distributed over space $x$. Note that the definition in \\eqref{eq:spatialDirac} will not be used directly. Instead, it can be approximated using the spreading operators presented in this section. \n\n\\subsubsection{Identities}\nThe following identity is extremely useful when solving systems including interpolation and spreading operators of the same order $o$ for any (grid) function $f$ and discrete domain $d$:\n\\begin{equation}\\label{eq:identityIJ}\n    \\langle f_l, J_{l,o}(x_\\itxt) \\rangle_d = I_{l,o}(x_\\itxt) f_l,\n\\end{equation}\nwhere $l\\in d$. From this, it follows that taking the norm of a spreading operator over a given domain is identical to applying to its `dual' interpolation operator (of the same order $o$ and same input $x_\\itxt$):\n\\begin{equation}\\label{eq:JnormIJ}\n    \\langle  J_{l,o}(x_\\itxt), J_{l,o}(x_\\itxt)\\rangle_d = \\lVert J_{l,o}(x_\\itxt)\\rVert^2_d = I_{l,o}(x_\\itxt)J_{l,o}(x_\\itxt).\n\\end{equation}\nSee Section \\ref{sec:innerProduct} for more details on the inner product and the norm.\n\n\\subsubsection{Other distributions}\nThis section presented interpolation and spreading operators that interact with the state of a FD scheme at a single location $x_\\itxt$ and either interpolates or distributes over a range of points. Although multiple grid points might be used for these operations, the interpolation or spreading is not \\textit{distributed}. Physical exciters such as mallets or bows have a non-zero width and thus interact with a larger part of the system. One could make an arbitrary distribution function $E$ with elements $e_l$ (in 1D) where $l\\in d$ for discrete domain $d$ of the system at hand. The \\textit{distribution} and spreading operators become\n\\begin{equation}\\label{eq:otherDistribution}\n    I_l = \\frac{e_l}{\\sum_d e_l} \\qaq J_l = \\frac{1}{h}I_l.\n\\end{equation}\nAlthough any values for $E$ would work, to retain correct scaling, the sum of $E$ needs to be normalised to $1$ as shown in Eq. \\eqref{eq:otherDistribution}.\n\n\\section{The Newton-Raphson method}\\label{sec:newtonRaphson}\nBefore moving on to more complex nonlinear excitation mechanisms, it is useful to go over the process of how to solve some of these mechanisms using an iterative root-finding method called the \\textit{Newton-Raphson} method (or Newton-Raphson for short). \n\nIf a FD scheme not be solved explicitly, due to an implicit dependence on a variable for example, Newton-Raphson can be used. For a continuous and differentiable function $f(x) = 0$, its root can be approached using the following iteration\n\\begin{equation}\\label{eq:newtonRaphson}\n    x_{i+1} = x_i - \\frac{f(x_i)}{f'(x_i)}\\ ,\n\\end{equation}\nwith iteration number $i$ and the tick is used to denote a derivation with respect to $x$.\nThis iteration will then be carried out until the difference between the values of two consecutive iterations is smaller than a given threshold:\n\\begin{equation}\\label{eq:NRthreshold}\n    |x_{i+1} - x_i| < \\epsilon,\n\\end{equation} \nwhere $\\epsilon$ is small, but its value depends on the situation at hand. To prevent Newton Raphson from iterating endlessly (if the iteration can not converge), one can put a cap on the number of iterations allowed. \n\nPreferably, the starting point of the iteration, $x_0$, should be close to the value of where the root is expected to be. This is especially the case for a higher-ordered function with multiple roots (non-uniqueness) or many local variations. \n\nAlgorithm \\ref{alg:NR} shows an example of an implementation of Newton-Raphson using $f(x) = e^x -1\\ \\Rightarrow\\ f'(x) = e^x $ and Figure \\ref{fig:NR} visualises the iterative algorithm.\n\\\\\n\\begin{minipage}{\\textwidth}\n\\setlstMAT\n\\begin{lstlisting}[caption={Example of an implementation of the Newton-Raphson method using $f(x) = e^{x} - 1$.}, label=alg:NR]\n% An example of the Newton Raphson method using f(x) = exp(x) - 1\n\nx = 1;          % starting point\neps = 1e-4;     % threshold\n\n% if the threshold has not been crossed before this number of \n% iterations, do not iterate more\nmaxIterations = 100;    \n    \n% loop until a maximum number of iterations\nfor i = 1:maxIterations\n\n    % calculate next iteration (Eq. %*\\eqrefMatlab[eq:newtonRaphson]*)\n    xNext = x - (exp(x) - 1) / (exp(x));\n\n    % threshold check (Eq. %*\\eqrefMatlab[eq:NRthreshold]*)\n    if abs(xNext - x) < eps \n        break; % break out of the for loop\n    end\n\n    % update the value of x\n    x = xNext;\nend\ndisp(\"The root of f(x) is at x = \" + xNext)\n\\end{lstlisting}\n\\end{minipage}\n\n\\captionsetup[subfigure]{labelformat=empty}\n\\def\\figWidth{0.30}\n\\begin{figure}[h]\n    \\centering\n    \\subfloat[]{\\includegraphics[width=\\figWidth\\textwidth]{figures/exciters/NR1.eps}}\\hfill\n    \\subfloat[]{\\includegraphics[width=\\figWidth\\textwidth]{figures/exciters/NR2.eps}}\\hfill\n    \\subfloat[]{\\includegraphics[width=\\figWidth\\textwidth]{figures/exciters/NR3.eps}}\n    \\vspace{-2em}\\caption{The Newton-Raphson method. The $x$-value of the root of the tangent line at $f(x_i)$ is used to evaluate the next iteration.\\label{fig:NR}}\n\\end{figure}\n\\captionsetup[subfigure]{labelformat=parens}\n\n\\subsection{Multivariate Newton-Raphson}\\label{sec:multivariateNR}\nFor $M$ functions $f_m$ dependent on the same number of independent variables $x_m$ with $m = \\{1, \\hdots, M\\}$, Newton-Raphson can be extended to\n\\begin{equation}\\label{eq:multivariateNR}\n    \\mathbf{x}_{i+1} = \n    \\mathbf{x}_i - \n    {\\underbrace{\\begin{bmatrix}\n        \\frac{\\partial f_1(\\mathbf{x}_i)}{\\partial x_1} & \\hdots & \\frac{\\partial f_1(\\mathbf{x}_i)}{\\partial x_M}\\\\\n        \\vdots & \\ddots & \\vdots\\\\\n        \\frac{\\partial f_M(\\mathbf{x}_i)}{\\partial x_1} & \\hdots & \\frac{\\partial f_M(\\mathbf{x}_i)}{\\partial x_M}\n    \\end{bmatrix}}_{\\mathbf{J}(\\mathbf{x}_i)}}^{-1}\n    \\begin{bmatrix}\n        f_1(\\mathbf{x}_i)\\\\\n        \\vdots\\\\\n        f_M(\\mathbf{x}_i)\n    \\end{bmatrix},\n\\end{equation}\nwhere the column vector $ \\mathbf{x} = [x_1, \\hdots, x_M]^T$ is the collection of independent variables, and the iteration number is (again) denoted by $i$.\nThe matrix in Eq. \\eqref{eq:multivariateNR} is referred to as the \\textit{Jacobian matrix} $\\mathbf{J}$ and contains the derivatives of all functions with respect to each individual independent variable. \n\nAs an example, consider the following system of equations\\footnote{Taken from \\url{http://fourier.eng.hmc.edu/e176/lectures/NM/node21.html}}:\n\\begin{subequations}\n    \\begin{align}\n        f_1(\\mathbf{x}) &= 3 x_1 - \\cos(x_2x_3) - 3/2 = 0,\\\\\n        f_2(\\mathbf{x}) &= 4x_1^2 - 625 x_2^2 + 2x_3-1 = 0,\\\\\n        f_3(\\mathbf{x}) &= 20 x_3 + e^{-x_1x_2}+9 = 0,\n    \\end{align} \n\\end{subequations}\nwhere $\\mathbf{x} = [x_1, x_2, x_3]^T$. The Jacobian matrix will be \n\\begin{equation*}\n    \\mathbf{J}(\\mathbf{x}) = \\begin{bmatrix}\n        3 & x_3 \\sin (x_2x_3) & x_2 \\sin(x_2x_3)\\\\\n        8x_1 & -1250 x_2 & 2\\\\\n        -x_2e^{-x_1x_2} & -x_1e^{-x_1x_2} & 20\n    \\end{bmatrix},\n\\end{equation*}\nand its roots can be found by iteratively calculating Eq. \\eqref{eq:multivariateNR}.\n\n\\section{Static friction models}\\label{sec:staticFricMod}\nA friction model is a nonlinear function that is (at least) dependent on the relative velocity $\\vrel$ between the bow and the string. This function scales how much the bow force affects the bowed object. \nIn static friction models, the friction force is defined as a function of this relative velocity only.\nThe first mathematical description of friction was proposed by Coulomb in 1773 \\cite{Coulomb1773}\\todo{check references here} to which static friction, or \\textit{stiction}, was added by Morin in 1833 \\cite{Morin1833} and viscous friction, or velocity-dependent friction, by Reynolds in 1886 \\cite{Reynolds1886}. In 1902, Stribeck found a smooth transition between the static and the coulomb part of the friction curve now referred to as the Stribeck effect \\cite{Stribeck1902}. The latter is still the standard for static friction models today.\n\nMany static friction models contain a discontinuity where the relative velocity between the  $\\vrel = 0$ due to a multiplication with $\\sgn(\\vrel)$ in their definition. In this project, only the following static friction model has been used \\cite{theBible}\n\\begin{equation}\\label{eq:staticFriction}\n    \\Phi (\\vrel) = \\sqrt{2a}\\vrel e^{-a\\vrel^2 + 1/2},\n\\end{equation}\nas it is continuous and differentiable, but still approximating discontinuous bow models. These characteristics make this model easier to work with in implementation. A definition for $\\vrel$ will be given below.\n\n\\begin{figure}[h]\n    \\centering\n    \\includegraphics[width=0.8\\textwidth]{figures/exciters/frictionCharacteristic.eps}\n    \\caption{The friction model in Eq. \\eqref{eq:staticFriction} with $a = 100$. \\label{fig:frictionCharacteristic}}\n\\end{figure}\\todo{FULL DOC SWEEP: check figure centering}\n\\subsection{The bowed stiff string}\\label{sec:bowedStiffStringStatic}\nConsider a stiff string, its transverse displacement described by $u(x,t)$ defined for $x\\in \\D$ (see Chapter \\ref{ch:stiffString}). The relative velocity between the string at bow position $x_\\Btxt = x_\\Btxt(t) \\in \\D$ and the bow can then be described as\n\\begin{equation}\\label{eq:vrel}\n    \\vrel = \\pt u(x_\\Btxt, t) - v_\\Btxt(t)\n\\end{equation}\n(in m/s) with bow velocity $v_\\Btxt = v_\\Btxt(t)$ (in m/s).\n\nRecalling the PDE of the stiff string in Eq. \\eqref{eq:stiffStringPDE}\n\\begin{equation}\n    \\rho A \\ptt u = T \\pxx u - EI \\pxxxx u - 2 \\sz \\rho A \\pt u + 2 \\so \\rho A\\pt \\pxx u,\n\\end{equation}\none can add the bow force to the equation according to \n\\begin{equation}\\label{eq:bowedStiffStringPDE}\n    \\rho A \\ptt u = T \\pxx u - EI \\pxxxx u - 2 \\sz \\rho A \\pt u + 2 \\so \\rho A\\pt \\pxx u - \\delta(x-x_\\Btxt)f_\\Btxt\\Phi(\\vrel)\n\\end{equation}\nwhere spatial Dirac delta function $\\delta(x-x_\\Btxt)$ (in m$^{-1}$) (see Section \\ref{sec:interpolationSpreading}) positions the bow along the string and $f_\\Btxt = f_\\Btxt(t) \\geq 0$ is the bow force (in N).\\footnote{If the spatial Dirac delta function were omitted, the bow force would be applied to the entire string domain rather than only the bow location $x_\\text{B}$.} \n\n\\subsubsection{Intuition}\nFrom Eq. \\eqref{eq:bowedStiffStringPDE} it can be seen that the bow force gets scaled by the friction model $\\Phi(\\vrel)$ shown in Figure \\ref{fig:frictionCharacteristic}. \nThe figure shows that if $\\vrel$ is too large (either positively or negatively) the bow term in \\eqref{eq:bowedStiffStringPDE} becomes $0$. If, on the other hand, $\\vrel$ is closer to $0$, the bow will have an effect on the string. This can be interpreted in terms of static and dynamic friction\\footnote{`Static' and `dynamic' friction are unrelated to `static' and `dynamic' friction models.}. A stationary object requires more force to be moved than a moving object, i.e., the static friction coefficient is always higher than the dynamic friction coefficient. This is essentially what the friction model tries to simulate.\n\nIt might seem counter-intuitive that the bow term is subtracted from the scheme. This is due to the definition of the relative velocity in Eq. \\eqref{eq:vrel}. For a negative bow velocity $v_\\Btxt$, $\\vrel$ becomes positive. As $\\sgn\\left(\\Phi(\\vrel)\\right) = \\sgn(\\vrel)$ through Eq. \\eqref{eq:staticFriction} and $f_\\Btxt\\geq 0$, the term $\\delta(x-x_\\Btxt)f_\\Btxt\\Phi(\\vrel)$ will be positive for a positive $\\vrel$. As a negative $v_\\Btxt$ needs to have a downwards, or negative, effect on the string, the sign of the bow term also needs to be negative to achieve this.  \n\n\\subsubsection{Discrete time}\nDividing all terms in Eq. \\eqref{eq:bowedStiffStringFDS} by $\\rho A$ and discretising the system yields\n%\n\\begin{equation}\\label{eq:bowedStiffStringFDS}\n    \\dtt \\uln = c^2 \\dxx \\uln - \\kappa^2 \\dxxxx \\uln - 2 \\sz \\dtd \\uln + 2 \\so\\dtm\\dxx \\uln - J_l(x_\\Btxt^n)F_\\Btxt^n\\Phi(\\vrel^n),\n\\end{equation}\nwith $F_\\Btxt^n = f_\\Btxt^n/\\rho A$ and spreading operator $J_l(x_\\Btxt^n) = J_{l,o}(x_\\Btxt^n)$ (in m$^{-1}$) as described in Section \\ref{sec:interpolationSpreading}, where the order $o$ remains undetermined for now. As the bow position, bow velocity and bow force are time-dependent, these have a superscript $n$ in discrete time. These parameters are called \\textit{control parameters} and will be supplied by the performer in an eventual implementation.\n\nThe relative velocity in Eq. \\eqref{eq:vrel} is discretised using a centred difference operator according to\n\\begin{equation}\\label{eq:vrelDisc}\n    \\vrel^n = I_l(x_\\Btxt^n)\\dtd \\uln - v_\\Btxt^n,\n\\end{equation}\nwith interpolation operator $I_l(x_\\Btxt^n) = I_{l,o}(x_\\Btxt^n)$ and is of the same order as $J_l(x_\\Btxt^n)$. Equation \\eqref{eq:vrelDisc} makes the scheme implicit due to the centred difference operator as the FD scheme in Eq. \\eqref{eq:bowedStiffStringFDS} is now nonlinearly dependent on $u_l^{n+1}$. To solve Eq. \\eqref{eq:bowedStiffStringFDS} for $u_l^{n+1}$, an iterative root-finding algorithm, such as Newton-Raphson described in Section \\ref{sec:newtonRaphson}, is required. This process could be circumvented by using a backward  difference operator in Eq. \\eqref{eq:vrelDisc}, but this will affect the accuracy and behaviour of the bow model.\n\n\\subsubsection{Solution}\nTo find a solution for $u_l^{n+1}$ at the bow location, an inner product of the scheme in Eq. \\eqref{eq:bowedStiffStringFDS} with spreading operator $J_l(x_\\Btxt^n)$ must be taken over the discrete domain of the string $d$ which isolates the scheme at the bowing location. Performing this operation and using identity \\eqref{eq:identityIJ} yields\n\\begin{equation}\\label{eq:bowLocFDS}\n    \\begin{aligned}\n    I_l(x_\\Btxt^n)\\dtt\\uln =\\ &c^2 I_l(x_\\Btxt^n)\\dxx \\uln - \\kappa^2 I_l(x_\\Btxt^n)\\dxxxx \\uln- 2 \\sz I_l(x_\\Btxt^n)\\dtd \\uln\\\\\n    & + 2 \\so I_l(x_\\Btxt^n)\\dtm\\dxx \\uln - \\lVert J_l(x_\\Btxt^n)\\rVert^2_d F_\\Btxt^n\\Phi(\\vrel^n).\n    \\end{aligned}\n\\end{equation}\nOne can rewrite Eq. \\eqref{eq:vrelDisc} to \n\\begin{equation}\\label{eq:vrelRewritten}\n   I_l(x_\\Btxt^n)\\dtd \\uln =  \\vrel^n + v_\\Btxt^n,\n\\end{equation}\nand using identity \\eqref{eq:identity1}, Eq. \\eqref{eq:bowLocFDS} can be rewritten and assigned to a function $g(\\vrel^n)$ according to \n\\begin{equation}\\label{eq:staticFrictionNRfunc}\n    g(\\vrel^n) = \\left(\\frac{2}{k} + 2\\sz\\right)\\vrel^n + \\lVert J_l(x_\\Btxt^n)\\rVert^2_d F_\\Btxt^n\\Phi(\\vrel^n) + b^n = 0,\n\\end{equation}\n% Here, $b$ contains all terms not dependent on $\\vrel$. As the operators can be interchanged, i.e., the order of application does not matter, could write $b$ according to\nwhere the terms not dependent on $\\vrel$ are collected in\\footnote{An interpolation operator applied to a spatial derivative can be expanded in a similar fashion to when it is applied to a grid function. A first-order interpolator applied to $\\dxx \\uln$ thus yields $I_{l,1}(x_\\itxt) \\dxx \\uln = (1-\\alpha_\\itxt)\\dxx u_{l_\\itxt}^n + \\alpha \\dxx u_{l_\\itxt+1}^n$.}\n\\begin{equation}\\label{eq:staticbDef}\n    \\begin{aligned}\n        b^n =\\ &-\\frac{2}{k}I_l(x_\\Btxt^n)\\dtm \\uln-c^2 I_l(x_\\Btxt^n)\\dxx \\uln + \\kappa^2 I_l(x_\\Btxt^n)\\dxxxx \\uln \\\\\n        &+ \\left( \\frac{2}{k} + 2 \\sz \\right)v_\\Btxt^n - 2 \\so I_l(x_\\Btxt^n)\\dtm\\dxx \\uln.\n    \\end{aligned}\n    % b =&\\ \\left(-\\frac{2}{k}\\dtm -c^2 \\dxx+ \\kappa^2\\dxxxx - 2 \\so \\dtm\\dxx\\right) I(x_\\Btxt^n)\\uln + \\left( \\frac{2}{k} + 2 \\sz \\right)v_\\Btxt^n.\n\\end{equation}\n%\n\nOne can then perform the Newton-Raphson method detailed in Section \\ref{sec:newtonRaphson} to iteratively solve for $\\vrel$ \n%\n\\begin{equation}\n    (\\vrel^n)_{i+1} = (\\vrel^n)_i - \\frac{g\\left((\\vrel^n)_i\\right)}{g'\\left((\\vrel^n)_i\\right)}\\ ,\n\\end{equation}\nwhere\n\\begin{equation*}\n    g'(\\vrel^n) = \\frac{2}{k} + 2\\sz + \\lVert J_l(x_\\Btxt^n)\\rVert^2_\\D F_\\Btxt^n\\Phi'(\\vrel^n),\n\\end{equation*}\nand \n\\begin{equation*}\n    \\begin{aligned}\n        \\Phi'(\\vrel^n) %&= \\sqrt{2a}e^{-a(\\vrel^n)^2 + 1/2} + \\sqrt{2a}\\vrel^n * (-2a\\vrel^n)e^{-a(\\vrel^n)^2 + 1/2}\\\\\n        %&\n        = \\sqrt{2a}\\left(1 - 2a(\\vrel^n)^2\\right)e^{-a(\\vrel^n)^2+1/2}.\n    \\end{aligned}\n\\end{equation*}\n\\subsection{Implementation and output}\\label{sec:staticImplementation}\nTo implement the bowed stiff string, one must perform the Newton-Raphson iteration every sample. For the implementation shown in this section, the threshold in Eq. \\eqref{eq:NRthreshold} has been set to $\\epsilon = 10^{-7}$ and the maximum number of iterations to $100$. In the following, the parameters used for the string are listed in Table \\ref{tab:stiffStringParams} with $T = 1000$ N and those for the bow are\n\\begin{equation*}\n    x_\\Btxt = \\floor[0.125/h],\\quad f_\\Btxt = 1\\ \\text{N},\\quad v_\\Btxt = 0.2\\  \\text{m/s},\\qaq a = 100.\n\\end{equation*}\nFigure \\ref{fig:staticBowImplementation} shows the behaviour of a bowed stiff string at the beginning of the simulation and shows the characteristic stick-slip behaviour. Figure \\ref{fig:helmholtzState} shows the state of the same simulation 3 seconds later. One can observe the Helmholtz corner move in an anti-clockwise direction as presented in Figure \\ref{fig:helmholtz}. Finally, the time domain output of the string at the bowing location is shown in Figure \\ref{fig:helmholtzImplementation} generally follows the Helmholtz motion shown in Figure \\ref{fig:helmholtzTimedomain}. \n\n\\begin{figure}[h]\n    \\centering\n    \\includegraphics[width=\\textwidth]{figures/exciters/bowImplementation.eps}\n    \\caption{Behaviour of a bowed stiff string at the beginning of the simulation. \\label{fig:staticBowImplementation}}\n\\end{figure}\n\\begin{figure}[h]\n    \\centering\n    \\includegraphics[width=\\textwidth]{figures/exciters/helmholtzState.eps}\n    \\caption{Behaviour of a bowed stiff string simulation after 3 seconds. The string exhibits a Helmholtz motion as presented in Figure \\ref{fig:helmholtz}. \\label{fig:helmholtzState}}\n\\end{figure}\n\\begin{figure}[h]\n    \\centering\n    \\includegraphics[width=\\textwidth]{figures/exciters/helmholtzImplementation.eps}\n    \\caption{Time domain output at the bowing location of a bowed stiff string using the static friction model in Eq. \\eqref{eq:staticFriction}. \\label{fig:helmholtzImplementation}}\n\\end{figure}\n\\subsection{Energy analysis}\nFollowing the energy analysis of the stiff string presented in Section \\ref{sec:energyAnalysisString}, taking an inner product of Eq. \\eqref{eq:bowedStiffStringFDS} (after multiplication by $\\rho A$) with $(\\dtd \\uln)$ over discrete domain $d$ one arrives at the following \n\\begin{align*}\n    \\dtp \\h + \\q &=  - \\langle (\\dtd \\uln), J_l(x_\\Btxt^n)f_\\Btxt^n\\Phi(\\vrel^n) \\rangle_d\\\\[-5pt]\n    \\xLeftrightarrow{\\mystrut\\ \\text{Eq. \\eqref{eq:identityIJ}}\\ }\\qquad &= -I_l(x_\\Btxt^n)(\\dtd \\uln) f_\\Btxt^n \\Phi(\\vrel^n) \\\\[-5pt]\n    \\xLeftrightarrow{\\mystrut\\ \\text{Eq. \\eqref{eq:vrelRewritten}}\\ } \\qquad &= \\underbrace{-f_\\Btxt^n \\Phi(\\vrel^n) \\vrel^n}_{\\text{loss}} - \\underbrace{f_\\Btxt^n \\Phi(\\vrel^n)v_\\Btxt^n}_{\\text{power}},\n\\end{align*}\nwhere $\\h$ and $\\q$ are as defined in Eqs. \\eqref{eq:energyBalanceStiffString} and \\eqref{eq:dampingTermStiffString} respectively. As $\\sgn\\left(\\Phi(\\vrel^n)\\right) = \\sgn\\left(\\vrel^n\\right)$ through Eq. \\eqref{eq:staticFriction}, one can observe that the first term on the right-hand side always has a negative effect on the rate of change of the total energy. This term can therefore be interpreted as the loss of power through the bow (as indicated). The last term is of indeterminate sign and can thus be interpreted as the power supplied by the bow. \n\nThe final energy balance can thus be written as\n\\begin{equation}\\label{eq:energyBalanceBow}\n    \\dtp \\h = -\\q - \\q_\\text{B} - \\p \n\\end{equation}\nwhere \n\\begin{equation*}\n    \\q_\\text{B} = f_\\Btxt^n \\Phi(\\vrel^n) \\vrel^n \\qaq \\p = f_\\Btxt^n \\Phi(\\vrel^n)v_\\Btxt^n.\n\\end{equation*}\nFigure \\ref{fig:energyStaticBow} shows the energy of the bowed stiff string corresponding to the wave propagation in Figure \\ref{fig:staticBowImplementation}. The bow only injects energy into the system when it sticks to the string. \n% Although the normalised energy shows `jumpy` behaviour, correlated to the behaviour of the system, this decreases for a lower value of $\\epsilon$. \n\n\\begin{figure}[h]\n    \\centering\n    \\begin{tikzpicture}[->,node distance=3cm,\n        thick,main node/.style={circle,draw}]\n    \n        \\node[] (image) at (0,0) {\n        \\includegraphics[width=\\textwidth]{figures/exciters/energyBow.eps}\n        };\n    \n        \\node[] (he) at (0.2,0.5) {\\small $\\mathfrak{h}_\\text{e}$};\n\n        \\node[] (h) at (-5.8, 1) {\\small $\\mathfrak{h}$};\n        \\node[] (v) at (-5.8, 0.5) {\\small $\\color{red}\\mathfrak{v}$};\n        \\node[] (t) at (-5.8, 0) {\\small $\\color{blue}\\mathfrak{t}$};\n      \\end{tikzpicture}\n      \\caption{The kinetic (blue), potential (red), and total (black) energy of the bowed stiff string. The right panel shows the normalised energy (according to Eq. \\eqref{eq:normalisedEnergyDamping}) and shows that the deviation of the energy is within machine precision. \\label{fig:energyStaticBow}}\n\\end{figure}\n\n\\section{Dynamic friction models}\nAs opposed to static friction models, dynamic friction models relate the relative velocity to the friction force using a differential equation. Dynamic friction models exhibit a phenomenon called \\textit{hysteresis}, which is the dependence of a system on its history. This hysteresis loop is in the force versus velocity plane and has been confirmed by measurements using a bowing machine in \\cite{Woodhouse2003}.\n\nThe first dynamic friction model was due to Dahl \\cite{Dahl1968} and captured hysteresis effects. The Stribeck effect was, however, not taken into account. The LuGre model (named after the collaboration between Lund and Grenoble) was then proposed by Canudas de Wit et al. in \\cite{Canudas1993, Canudas1995} and extended the Dahl model to take the Stribeck effect into account. The model assumes a large ensemble of bristles between the two sliding surfaces, each of which contributes a tiny amount to the total friction force. The drawback of this model is that it exhibits drift for extremely small external forces. In \\cite{Dupont2002}, Dupont et al. extended the LuGre model by allowing for a purely elastic regime that solves the drift issue. This model is referred to as the \\textit{elasto-plastic} friction model and is used in this project.\n\n\\subsection{The elasto-plastic friction model}\\label{sec:elastoPlastic}\nIn a musical context, the elasto-plastic friction has been investigated in-depth by Serafin et al. in \\cite{Serafin2003, Serafin2004, Avanzini2005}. Like the LuGre model, the elasto-plastic friction model assumes that the friction between the bow and the string is caused by a large quantity of bristles, all contributing a fraction of the total amount of friction. See Figure \\ref{fig:elastoPlastic}.\n\n\\input{exciters/elastoPlasticFig.tex}\n\nUnless denoted otherwise, this section follows the original model by Dupont et al. in \\cite{Dupont2002}, but with the appropriate corrections added as presented in paper \\citeP[C]. As opposed to the static friction model described in the previous section, the friction force $f$ (in N) is now dependent on the average bristle displacement $z = z(t)$ (in m) as well as the relative velocity $v = v(t)$ (in m/s). The friction force is defined as\n\\begin{equation}\\label{eq:elastoPlasticForce}\n    f(v, z) = s_0z + s_1\\dot z + s_2v + s_3w,\n\\end{equation}\nwith bristle stiffness $s_0 \\geq 0$ (in N/m), bristle damping $s_1 \\geq 0$ (in kg/s), viscous friction $s_2 \\geq 0$ (in kg/s) and, as presented in \\cite{Serafin2004}, a dimensionless noise coefficient $s_3$ multiplied onto a pseudorandom function $w = w(t)$ (in N) generating values between $-1$ and $1$. Moreover, for a string defined over domain $\\D$, the relative velocity between the string at bowing location $x_\\Btxt = x_\\Btxt(t) \\in \\D$ and the bow is (similar to Eq. \\eqref{eq:vrel})\n\\begin{equation}\\label{eq:vrelElasto}\n    v = \\pt u(x_\\Btxt,t) - v_\\Btxt,\n\\end{equation}\nwith bow velocity $v_\\Btxt = v_\\Btxt(t)$ (in m/s). Lastly, $\\dot z$ is the rate of change of the bristle displacement (in m/s) and is related to $v$ according to\n\\begin{equation}\\label{eq:zdot}\n    \\dot z = r(v, z) = v \\bigg[ 1-  \\alpha(v, z)\\frac{z}{z_\\text{ss}(v)}\\bigg].\n\\end{equation}\nHere, $z_\\text{ss}$ is the steady-state function\n\\begin{equation}\\label{eq:zss}\n    z_\\text{ss}(v) = \\frac{\\sgn(v)}{s_0}\\left[f_\\text{C}+(f_\\text{S}-f_\\text{C})e^{-(v/v_\\text{S})^2}\\right],\n\\end{equation}\nwhere the $v_\\text{S}$ is the Stribeck velocity (in m/s). Furthermore, using the normal force $f_\\text{N} = f_\\text{N}(t)$ (in N), the Coulomb force and stiction force can be calculated according to $f_\\text{C} = f_\\text{N}\\mu_\\text{C}$ and $f_\\text{S} = f_\\text{N}\\mu_\\text{S}$ respectively (both in N). In these definitions $\\mu_\\text{C}$ and $\\mu_\\text{S}$ are the dimensionless dynamic and static friction coefficients respectively. A plot of the steady state function can be found in Figure \\ref{fig:zss}.\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.8\\textwidth]{figures/exciters/steadyState.eps}\n    \\caption{\\label{fig:zss}The steady-state function $z_\\text{ss}(v)$ plotted against relative velocity $v$ with $s_0 = 10^4$, $\\mu_\\text{C} = 0.3$, $\\mu_\\text{S} = 0.8$, $v_\\text{S} = 0.1$ and $f_\\text{N} = 5$.}\n\\end{figure}\n\nFinally, $\\alpha(v,z)$ in Eq. \\eqref{eq:zdot} is an adhesion map between the bow and the string and is defined as\n\n\\begin{equation}\\label{eq:adhesionMap}\n\\alpha(v, z) = \n\\begin{aligned}\n    \\begin{cases}\n    \\begin{rightcases}\n        &0 & |z| \\leq z_\\text{ba}\\\\\n        &\\alpha_\\text{m}(v,z)&\\ \\ \\ \\, z_\\text{ba}<|z|<|z_\\text{ss}(v)|\\\\        &1 &|z|\\geq|z_\\text{ss}(v)|\n        \\end{rightcases} \n        \n        &\\text{if}\\  \\sgn(v)=\\sgn(z)\\\\\n        \\,0&\\!\\,\\text{if}\\  \\sgn(v)\\neq\\sgn(z),\n    \\end{cases}\n    \\end{aligned}\n\\end{equation}\nwhere the transition between the elastic and plastic behaviour is defined as\n\\begin{equation}\\label{eq:alphaM}\n    \\alpha_\\text{m} = \\frac{1}{2}\\bigg[1+\\sgn(z)\\sin\\bigg(\\pi\\frac{z-\\sgn(z)\\frac{1}{2}(|z_\\text{ss}(v)|+z_\\text{ba})}{|z_\\text{ss}(v)|-z_\\text{ba}}\\bigg)\\bigg],\n\\end{equation}\nwhere the break-away displacement $z_\\text{ba} = z_\\text{ba}(t) = 0.7 f_\\text{C}/s_0$ determines the value of $z$ before bristles start to break. The adhesion map is visualised in Figure \\ref{fig:alphaPlot} and relates to Figure \\ref{fig:elastoPlastic} as described in its caption.\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.8\\textwidth]{figures/exciters/drawAlpha3.eps}\n    \\caption{\\label{fig:alphaPlot}A plot of the adhesion map $\\alpha(v,z)$ in Eq. \\eqref{eq:adhesionMap} plotted against $z$ when $\\sgn(v)  = \\sgn(z)$. The different coloured regions correspond to Figure \\ref{fig:elastoPlastic} according to: yellow - a) \\& b), orange - c) and red - d). (Adapted from paper \\citeP[C].)}\n\\end{figure}\n\n\\subsubsection{Discrete time}\nEquation \\eqref{eq:elastoPlasticForce} can be discretised to\n\\begin{equation}\\label{eq:discForceFunction}\n    f(v^n,z^n) = s_0z^n + s_1r^n+s_2v^n+s_3w^n\n\\end{equation} \nwhere Eq. \\eqref{eq:vrelElasto} can be discretised to\n\\begin{equation}\\label{eq:vrelElastoDisc}\n    v^n = I_l(x_\\Btxt^n)\\dtd\\uln - v_\\Btxt^n,\n\\end{equation}\nwith interpolation operator $I_l(x_\\Btxt^n) = I_{l,o}(x_\\Btxt^n)$ (of unspecified order $o$) and\n\\begin{equation}\\label{eq:r}\n    r^n = r(v^n,z^n) = v^n\\bigg[1-\\alpha(v^n,z^n)\\frac{z^n}{z_\\text{ss}(v^n)}\\bigg]\n\\end{equation}\nis the discrete counterpart of Eq. \\eqref{eq:zdot}. The discrete adhesion map is identical to the continuous definition given in Eqs. \\eqref{eq:adhesionMap} and \\eqref{eq:alphaM}, but with superscripts $n$ added for appearances of $v$ and $z$.\n\n\\subsection{Applied to a FDTD stiff string}\nThe first appearance of a contribution in this work is the elasto-plastic friction model applied to a stiff string implemented using FDTD methods. This has been presented in paper \\citeP[C] and will be summarised in this section. \\todo{state the stability stuff here?}\n\nIn the same way as done with the static friction model in Section \\ref{sec:staticFricMod}, one can add the friction force to the stiff string PDE in Eq. \\eqref{eq:stiffStringPDE} and discretise the system as follows:\n%\n\\begin{equation}\\label{eq:elastoStiffStringFDS}\n    \\dtt \\uln = c^2 \\dxx \\uln - \\kappa^2 \\dxxxx \\uln - 2 \\sz \\dtd \\uln + 2 \\so\\dtm\\dxx \\uln - J_l(x_\\Btxt^n)\\frac{f(v^n,z^n)}{\\rho A},\n\\end{equation}\nwhere spreading operator $J_l(x_\\Btxt^n) = J_{l,o}(x_\\Btxt^n)$ and is of the same order as $I_l(x_\\Btxt^n)$ in Eq. \\eqref{eq:vrelElastoDisc}. Following the same procedure as for the static friction model in Section \\ref{sec:staticFricMod}, one takes an inner product with $J_l(x_\\Btxt^n)$ over discrete string domain $d$ and using identities \\eqref{eq:identityIJ} and \\eqref{eq:identity1}, one can rewrite this similar to the static friction model in Eq. \\eqref{eq:staticFrictionNRfunc} as\n%\n\\begin{equation}\\label{eq:elastog1}\n    g_1(v^n,z^n) = \\left(\\frac{2}{k} + 2\\sz\\right)v^n + \\lVert J_l(x_\\Btxt^n)\\rVert_d^2\\frac{f(v^n,z^n)}{\\rho A}+ b^n= 0,\n\\end{equation}\nwhere\n\\begin{align*}\n    b^n =&-\\frac{2}{k}I_l(x_\\text{B}^n)\\delta_{t-}u_l^n - c^2 I_l(x_\\text{B}^n)\\delta_{xx} u_l^n +\\kappa^2I_l(x_\\text{B}^n)\\delta_{xxxx} u_l^n\\\\\n    &+\\left(\\frac{2}{k}+ 2\\sigma_0\\right)v_\\text{B}^n-2\\sigma_1I_l(x_\\text{B}^n)\\delta_{t-}\\delta_{xx}u_l^n.\n\\end{align*}\nAs $g_1$ contains two unknown variables $v^n$ and $z^n$ that need to be solved for, the multivariate Newton-Raphson method presented in \\ref{sec:multivariateNR} must be performed. To be able to do this, an extra function must be included. \n\nAs $r$ describes $\\dot z$ in Eq. \\eqref{eq:zdot}, one can take another approach to approximate $\\dot z$ using the trapezoid rule \\cite{theBible}\n\\begin{equation}\n    a^n = (\\mtm)^{-1}\\dtm z^n \\quad \\Longrightarrow\\quad a^n = \\frac{2}{k}(z^n - z^{n-1}) + a^{n-1}.\n\\end{equation}\nAs both $a^n$ and $r^n$ approximate $\\dot z$, these can be used to create the second function necessary to solve the full system\n\\begin{equation}\\label{eq:elastog2}\n    g_2(v^n, z^n) = r^n - a^n = 0.\n\\end{equation}\nFinally, one can use the multivariate Newton-Raphson method described in Section \\ref{sec:multivariateNR}, which results in\n\\begin{equation}\\label{eq:NRit}\n    \\begin{bmatrix}\n    v^n\\\\\n    z^n\n    \\end{bmatrix}_{i+1}\n    =\n    \\begin{bmatrix}\n    v^n\\\\\n    z^n\n    \\end{bmatrix}_i\n    -\n    \\begin{bmatrix}\n    \\frac{\\partial g_1}{\\partial v} & \\frac{\\partial g_1}{\\partial z}\\\\\n    \\frac{\\partial g_2}{\\partial v} & \\frac{\\partial g_2}{\\partial z}\\\\\n    \\end{bmatrix}^{-1}\n    \\begin{bmatrix}\n    g_1\\\\\n    g_2\n    \\end{bmatrix}\\,\n    .\n\\end{equation}\nThe derivatives in the Jacobian matrix are given in Appendix \\ref{app:elastoDeriv}.\n\n\\subsection{Output}\nIn the following, the same parameters as presented for the static friction model in Section \\ref{sec:staticImplementation} have been used for the string and the bow (where $f_N = f_\\Btxt$).\nAdditional parameters used for the elasto-plastic friction model are given in paper \\citeP[C].\n\nFigure \\ref{fig:hysteresis} shows that the implementation of the elasto-plastic friction model exhibits a hysteresis loop in the force versus velocity plane as desired from a dynamic friction model. The values around $v=0$ are due to sticking behaviour and the loop on the left is due to slipping behaviour.\nFigure \\ref{fig:elastoWaveform} shows the output of the implementation and follows the characteristic Helmholtz motion shown in Figure \n\\ref{fig:helmholtzTimedomain}. When compared to the output of the static friction model in Figure \\ref{fig:helmholtzImplementation}, the output of the elasto-plastic implementation seems to be more `smooth' overall, which could be explained by the elasticity of the bristles. \n\n\\begin{figure}[ht]\n    \\centering\n    \\begin{tikzpicture}[->,node distance=3cm,\n      thick,main node/.style={circle,draw}, scale=0.9, every node/.style={scale=0.9}]\n  \n      \\node[anchor=south west,inner sep=0] (image) at (0,0) {\\includegraphics[width=\\textwidth]{figures/exciters/hysteresis.eps}};\n      % \\filldraw[black] (arr2B) (2,2) circle (1pt) node[anchor=center](topZ){};\n      % \\filldraw[black] (arr2E) (3,1.5) circle (1pt) node[anchor=center](topZ){};\n      % (arr2B) edge[bend right] node [arrow] {} (arr2E);\n      \n    \\node (arr1B) at (6.3, 4.35) {};\n    \\node (arr1E) at (8.2, 4.25) {};\n    \\node (arr2B) at (8.9, 1.2) {};\n    \\node (arr2E) at (6.7, 1.2) {};\n    \\node (arr3B) at (2.2, 2.05) {};\n    \\node (arr3E) at (2.2, 2.95) {};\n    \\path[every node/.style={font=\\sffamily\\small}]\n  \n      (arr1B) edge[bend left = 20] node [left] {} (arr1E)\n      (arr2B) edge[bend left = 20] node [left] {} (arr2E)\n      (arr3B) edge[bend left = 50] node [left] {} (arr3E);\n      % \\begin{scope}[x={(image.south east)},y={(image.north west)}]\n      %     \\draw[red,ultra thick,rounded corners] (0.62,0.65) rectangle (0.78,0.75);\n      % \\end{scope}\n    \\end{tikzpicture}\n    \\caption{Hysteresis loop showing 500 values up to $n=3\\fs$. (Adapted from paper \\citeP[C].) \\label{fig:hysteresis}}\n\\end{figure}\n\n\\begin{figure}[h]\n    \\centering\n    \\includegraphics[width=\\textwidth]{figures/exciters/elastoplasticWaveForm.eps}\n    \\caption{Time domain output at the bow location of a stiff string bowed using an elasto-plastic friction model. \\label{fig:elastoWaveform}}\n\\end{figure}\n\n\\subsection{Stability through energy analysis}\nAs the elasto-plastic bow model is a differential equation in itself, its approximation will need to abide a stability condition as well.\nAs the system at hand is nonlinear, frequency domain analysis as described in Section \\ref{sec:stabilityAnalysis} can not be performed. Energy analysis, on the other hand, can be used here to determine the necessary stability condition for this model. This section follows the concepts introduced in Section \\ref{sec:stabilityAnalysisEnergy} to obtain a stability conditions for the elasto-plastic friction model. A similar process for finding stability for the LuGre model has been done by Olsson in continuous time \\cite[p. 55]{Olsson1996}. The derivation below is inspired by his. \n\nFirst, all terms of Eq. \\eqref{eq:elastoStiffStringFDS} are multiplied by $\\rho A$ to get the appropriate units for the analysis. Then, the inner product with $\\dtd \\uln$ over the string domain $\\D$ is taken to get\n\\begin{equation}\n    \\dtp \\h_\\text{s} + \\q_\\text{s} = -\\p_\\Btxt\n\\end{equation}\nwhere the definitions for the discrete Hamiltonian $\\h_\\text{s}$ and the damping term $\\q_\\text{s}$ for the string can be found in Section \\ref{sec:energyAnalysisString}. The input power introduced by the bow is defined as (writing $f(v^n,z^n) = f^n$)\n\\begin{equation*}\n    \\p_\\Btxt = \\langle (\\dtd \\uln), J(x_\\Btxt^n)f^n\\rangle_\\D\n\\end{equation*}\nwhich, using identity \\eqref{eq:identityIJ} can be written as \n\\begin{equation*}\n    \\p_\\Btxt = I_l(x_\\text{B}^n)\\dtd \\uln f^n.\n\\end{equation*}\nFinally, using Eq. \\eqref{eq:vrelElastoDisc} yields\n\\begin{equation}\n    \\p_\\Btxt = f^nv^n + f^n v_\\Btxt^n.\n\\end{equation}\nThe term $f^nv^n$ is the important one as $f^nv_\\Btxt^n$ is a driving term, and is zero when the external bow velocity is zero. This means that this does not affect the internal stability of the system. In the following, the superscript $n$ is suppressed for brevity.\n\nSubstituting Eq. \\eqref{eq:discForceFunction} into $fv$ and ignoring the noise term $s_3w^n$ for now, yields\n\\begin{equation}\\label{eq:fv}\n    \\p_\\Btxt = fv = \\sigma_{0}zv +\\sigma_{1}rv+\\sigma_{2}v^2.\n\\end{equation}\nThe definition for $r^n$ in Eq. \\eqref{eq:r} may be rewritten as\n\\begin{equation*}\n    \\begin{aligned}\n        r &= v\\bigg[1-\\alpha\\frac{z}{z_\\text{ss}(v)}\\bigg],\\\\\n        r &= v-\\frac{v\\alpha z}{z_\\text{ss}(v)},\\\\\n        v &= r + \\frac{v\\alpha z}{z_\\text{ss}(v)},\n    \\end{aligned}\n\\end{equation*}\nand (following Olsson) may be substituted in Eq. \\eqref{eq:fv} as\n\\begin{equation}\n    \\p_\\Btxt = s_{0}z\\left(r+ \\frac{v\\alpha z}{z_\\text{ss}(v)}\\right)+s_{1}r\\left(r+ \\frac{v\\alpha z}{z_\\text{ss}(v)}\\right)+s_{2}v^2,\n\\end{equation}\nor\n\\begin{equation}\n    \\p_\\Btxt = s_0zr+s_1\\left(r+\\frac{v\\alpha z}{2z_\\text{ss}(v)}\\right)^2+\\frac{v\\alpha z^2}{z_\\text{ss}(v)}\\left(s_0-\\frac{s_1v\\alpha}{4z_\\text{ss}(v)}\\right)+s_2v^2.\n\\end{equation}\nThe power introduced by the bow can then be subdivided into the total energy in the bristles and their damping. As $r$ approximates $\\dot z$ the first term, one can rewrite this to \n\\begin{equation*}\n    \\dtp \\h_\\text{brist} + \\q_\\text{brist} \\geq 0,\n\\end{equation*}\nand needs to be non-negative for passivity. \n\nStarting with the damping term, which is defined as\n\\begin{equation}\n    \\q_\\text{brist} = s_1\\left(r+\\frac{v\\alpha z}{2z_\\text{ss}(v)}\\right)^2+\\frac{v\\alpha z^2}{z_\\text{ss}(v)}\\left(s_0-\\frac{s_1v\\alpha}{4z_\\text{ss}(v)}\\right)+s_2v^2.\n\\end{equation}\none can show that, as all coefficients are non-negative and $\\sgn(v) = \\sgn(z_\\text{ss}(v))$ (through a multiplication by $\\sgn(v)$ in the definition of in Eq. \\eqref{eq:zss}), $\\q_\\text{brist}$ is non-negative under the following condition:\n\\begin{equation}\n    s_1 \\leq \\frac{4s_0z_\\text{ss}(v)}{v}\\ .\n\\end{equation}\nThis means that as long as one knows the limit of the velocity of the system, the coefficient $s_1$ can be set accordingly.\n\nUsing identity \\eqref{eq:prodIdentity2}, the energy stored in the bristles can be shown to be\n\\begin{equation}\n    \\h_\\text{brist} = \\frac{s_0}{2}z^ne_{t-}z^n,\n\\end{equation}\nwhich is not necessarily non-negative. In \\cite{Olsson1996}, Olsson performs the analysis in continuous time, where the energy in the bristles is defined as to \n\\begin{equation}\n    \\mathfrak{H}_\\text{brist} = \\frac{s_0}{2} z^2,\n\\end{equation}\nwhich is clearly non-negative. See Notes below for a discussion. \n\n% A condition can, however, be retrieved from the damping term and is similar to the condition presented by Olsson in continuous time. The damping term is defined as\n\n\\subsubsection{\\SWcomment[NOTES FOR STEFAN]}\nAs far as I see, to find a stability condition for the model, there are two options:\n\\begin{enumerate}\n    \\item The $s_0z$ term should be discretised using the centred averaging operator, such that the system is inherently stable.\n    \\begin{equation}\n        s_0 (\\mtd z^n)(\\dtd z^n)\\quad \\overset{\\text{Eq. \\eqref{eq:prodIdentity4}}}{\\Longrightarrow} \\quad \\frac{s_0}{2}\\mtm(z^n)^2\n    \\end{equation}\n    This introduces the issue of needing to deal with $z^{n+1}$ issue in the multivariate NR solve.. \n    \\item If the bristles had some sort of mass, one could create a stability condition such as done for the mass-spring system in Section \\ref{sec:stabilityAnalysisEnergy}. This requires a change the model.\n    \\item Or do you see something I don't...?\n\\end{enumerate}\n\n\\section{Discussion and conclusion}\nThis chapter presented the bow as a mechanism to excite stiff strings. Two friction models have been presented: a static friction model where the friction force is only a function of the relative velocity between the string and the bow, and a dynamic elasto-plastic friction model, which relates this relative velocity to the friction force using a differential equation. The latter has been presented in paper \\citeP[C] where it was first applied to stiff strings based on FDTD methods. \n\nAlthough a successful implementation of the elasto-plastic friction model has been made, it has not been used in the project beyond paper \\citeP[C]. It was found that small changes in parameters, both control and model parameters, already yield large behavioural changes. An attempt was made at using the elasto-plastic friction model with a fully modelled instrument (the tromba marina presented in papers \\citeP[D] and \\citeP[E]), but did not yield the desired results, and the predictable static friction model was chosen instead. Future work includes tuning the many parameters that the elasto-plastic model relies on and apply an adjusted version to fully modelled instruments.\n\nAn in-depth comparison between the static and the elasto-plastic friction model in terms of perceptual differences, is also left for future work. A preliminary comparison has been carried out by Onofrei in \\cite{Onofrei2021}, where the author noted that \\textit{\"the\nelasto-plastic model seems to behave more smoothly\"} than the static friction model. This is also what is observed when comparing the output of the friction models in Figures \\ref{fig:helmholtzImplementation} and \\ref{fig:elastoWaveform}. As said, these observations are preliminary, and further work needs to be done to compare the various friction models.\n\nFinally, it must be noted that the applications of the bow are not limited to strings, and can very well be extended to other resonators. In [\\hyperref[ch:listOfPublications]{S4}], for example, the authors apply the elasto-plastic friction model to a 2D drum membrane to simulate a friction drum inspired instrument.", "meta": {"hexsha": "ee8ac9c4339b8f34cb717c6bbc1e3ee439569f15", "size": 52410, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "aauPhdCollectionThesis/exciters/bow.tex", "max_stars_repo_name": "SilvinWillemsen/phdThesis", "max_stars_repo_head_hexsha": "b0a59790e12d0c308a065958c6dc47c8763d8c34", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aauPhdCollectionThesis/exciters/bow.tex", "max_issues_repo_name": "SilvinWillemsen/phdThesis", "max_issues_repo_head_hexsha": "b0a59790e12d0c308a065958c6dc47c8763d8c34", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aauPhdCollectionThesis/exciters/bow.tex", "max_forks_repo_name": "SilvinWillemsen/phdThesis", "max_forks_repo_head_hexsha": "b0a59790e12d0c308a065958c6dc47c8763d8c34", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 77.8751857355, "max_line_length": 877, "alphanum_fraction": 0.7240412135, "num_tokens": 16248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.32115984792011987}}
{"text": "\\documentclass[12pt, a4paper]{scrartcl}\n\\usepackage[utf8]{inputenc}\n\\usepackage{graphicx}\n\\usepackage{amsmath, amsthm, amssymb, textcomp}\n\\usepackage{setspace}\n\\usepackage{paralist}\n\\usepackage{graphicx}\n\\usepackage{caption}\n\\graphicspath{{WSK_im/}} %Graphic is in a folder named WSK_im in the currend directory\n\\usepackage{float}\n\\usepackage{authblk}\n\\renewcommand\\Authfont{\\fontsize{12}{14.4}\\selectfont}\n\\title{Bayesian probability theory - Lesson 7:\\\\\nParameter and model estimation and classification}\n\n\\author{Wolfgang von der Linden, Gerhard Dorn, Johanna Moser}\n\\date{Transcript}\n\n\\begin{document}\n\\setlength{\\parindent}{0pt}\n\\maketitle\n\\onehalfspacing\n\nWelcome to unit 7 of the course on Bayesian probability theory. My\nname is Wolfgang von der Linden and I will enable you to help Captain\nBayes and her crew to fit data by \\textbf{model functions} and to learn the basics of\n\\textbf{parameter estimation, prediction} and \\textbf{classification}\nof data as well as on \\textbf{model selection}.\n\\begin{itemize}\\item We will learn how to apply Bayes theorem to \\textit{derive} the probability\ndistribution for the parameters of an assumed model,\n\\item We will learn how to apply this probability distribution in the \\textit{interpolation} \nof data to help Captain Venn find his treasure\n\\item We will learn how to \\textit{classify} sea areas to be a nature reserve for\nfrogfish or a general fishing ground.\n\\end{itemize}\n\n\nWe begin with the classical \\textbf{regression problem}. It is described as follows:\\\\\nLet there be a \\textit{set of measured data $d_{\\nu}$} that depend on some \\textbf{pivot points $x_{\\nu}$}%7_1\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{7_1.png}\n\\end{figure}\nThese data points can be represented in an $x$-$y$ diagram. \nThe measurements are in general not exact but have some uncertainty that obey a certain distribution.\nIn most cases like in the situation of Captain Venn these\nare additive \\textbf{Gaussian uncertainties}.\nNext we assume that without the experimental uncertainty there is a \\textit{relation}\nbetween intrinsic data and the pivot points that can be described by a\n\\textit{deterministic} function, for instance a physical law that depends on some parameters.\\\\\n\\[y_{\\nu} = f(x_{\\nu},\\vec{a})\\]\n\n\\textit{Then the measured data can be described by adding the measurement uncertainty to the deterministic \nmodel function.}\\[d_{\\nu}=f(x_{\\nu},\\vec{a})+\\eta_{\\nu}\\]\n\n\nNow the goals of regression are twofold:\\\\\n\nFirstly \\textbf{Parameter estimation}: We would like to investigate the relation between \nmeasurement values $d_{\\nu}$ and pivot points $x_{\\nu}$ and therefore \\textit{determine\nthe model and its parameters $\\vec{a}$, their uncertainty $\\sigma_{\\vec{a}}$ and covariance $\\text{CoV}(a_i,a_j)$}. \nIn the case of Captain Venn and his starpath problem the goal is to find \nthe laws of how the stars or rather the earth move. The model could\ninclude the rotation of the earth around a tilted axis with respect to\nthe elliptic orbit around the sun. The parameters could represent the\nduration of such a rotation and the orbital period.\\\\\n\nThe second aim of regression is to \\textbf{predict the values $y^*$} of the function at\nadditional pivot points $x^*$ and their corresponding uncertainty. These\nadditional pivot points could be such, that it was not possible to realize\na measurement at these points. (Remember the case of Captain Venn\nwho was not able to determine the angles of the star Arcturus in the\nshortest night of the year due to bad weather.)\\\\\n\nAnother important application is to \\textbf{extrapolate} physical properties from a small scale\nexperiment to a larger one as is for instance done in fusion plasma reactors.\\\\\n\n\\section*{Parameter estimation}\nNow we come to parameter estimation.\nFor your orientation we recapitulate the \\textit{classical regression procedure} before\nwe introduce the probabilistic approach.\nAs described before we assume we have a suitable model $y_{\\nu}=f(x_{\\nu},\\vec{a})$, which is for instance given by physical \nlaws or is obvious due to a visible trend of the data. \nA very prominent choice are \\textbf{linear models} in which\none uses a linear combination of suitable ansatz functions $\\phi_i (x)$ with\nthe coefficients being the parameters. \n\\[f(x,\\vec{a})=\\sum_i \\phi_i(x)a_i\\]\n\nBased on the model function, a \\textbf{cost function $\\chi^2_{\\vec{a}}$} is introduced that \\textit{quantifies deviation between \nmodel function and data}. A very common cost\nfunction is the \\textbf{root mean square function}.\\\\\n\\begin{equation*}\\boxed{\\chi^2_{\\vec{a}}=\\sum_{\\nu=1}^N\\frac{d_{\\nu}-f(x_{\\nu},\\vec{a})^2}{\\sigma_{\\nu}^2}\n}\\end{equation*}\\\\\n Sometimes the individual contributions get a weight $\\sigma_{\\nu}^2$\naccording to the reliability of the measured data.\nOutliers thus have a very strong impact on the cost function.\\\\\n\nIn the next step the cost function is \\textit{minimized} with respect to the model parameters. This \nis the so-called \\textbf{least squares approach}. In the case of linear regression in combination \nwith a quadratic cost function the\nminimization leads to a matrix equation where the columns of the matrix $M$ are given by the ansatz\nfunctions evaluated at the pivot points.\\\\%7_2\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{7_2.png}\n\\end{figure}\n\nIf one is not entirely sure about the model function in a final step, one can evaluate the model function and\ndiscuss whether is has a reasonable behaviour. \nThis would lead to the field of \\textbf{hypothesis testing}.\\\\\n\n\nNow we come to \\textbf{Bayesian parameter estimation}.\nWe have already mentioned several times that probability theory represents the consistent\ncalculus for dealing with uncertainty. The general approach is the following:\\\\\n\nFirst we have to \\textit{fix all assumptions} like ``the measurement are given for certain pivot points'',\n``the data can be described by an assumed model'', ``the experimental noise follows a given distribution'' \nand so on. Then we have to \\textit{specify the questions} we are interested in, like: ``What \nare the values of the parameters?'' ``What would be the value of the measured quantity at a new pivot point?''\n``Is the assumed model the right one?'' ``What if there are \\textbf{outliers}, which means there are individual data points that are \\textit{corrupted\nby external influences and do not obey the assumed error statistics}?''\\\\\n\nFinally, we compute the corresponding probabilities. \nWe will see at the end of this section when and under which conditions the previously presented statistical procedure is justified. \\\\\n\n\\section*{Probability density of the parameters}\nThe \\textbf{probability density of the parameters} $\\vec{a}$ in the light of the measured data $\\boldsymbol{D}$ is the \\textbf{posterior probability} that can\nbe simplified by Bayes theorem.\n\\begin{equation*}\\boxed{p(\\vec{a}|\\boldsymbol{D},X)=\\frac 1Z p(\\boldsymbol{D}|\\vec{a},X)p(\\vec{a})\n}\\end{equation*}\\\\\n The normalization $Z$ is independent of the parameters and can be determined in the end.\nThe prior probability $p(\\vec{a})$ encodes our \\textit{knowledge about the parameters before we take into account the experimental data}.\nIf nothing is known at all, the most ignorant prior is the \\textbf{uniform prior}; maybe within\ncertain parameter ranges. We will discuss in the next unit how ignorant\npriors can be determined purely based on considerations of symmetries and\ninvariances.\\\\\nA crucial element in Bayes theorem is the \\textbf{likelihood} $p(\\boldsymbol{D}|\\vec{a},X)$.\nIf the measurement errors are uncorrelated the likelihood factorizes.\n\\[ p(\\boldsymbol{D}|\\vec{a},X)=\\prod_{\\nu} p(\\boldsymbol{d}_{\\nu}|\\vec{a},x_{\\nu})\\]\nIn the case of additive Gaussian noise with noise level $\\sigma_v$ we can express the\nlikelihood of one data point given by the model function $f$ and the parameters $\\vec{a}$.%7_3\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{7_3.png}\n\\end{figure}\nSince we are interested in the probability density of the parameters $\\vec{a}$,%%\nwe only need the terms that depend on them. We can replace the product\nof the exponential by the exponential of the sum.\n\\begin{equation*}\\boxed{ p(\\boldsymbol{D}|\\vec{a},X)\\propto \\exp\\left[-\\sum_{\\nu}\\frac{\\boldsymbol{d}_{\\nu}-f(x_{\\nu},\\vec{a})^2}{2\\sigma_{\\nu}^2}\\right]=\\exp\\left[-\\frac 12 \\chi_{\\vec{a}}^2\\right]}\\end{equation*}\\\\\n\nThis misfit term $\\chi_{\\vec{a}}^2$ corresponds to the \\textbf{least squares cost function} which we\nsaw in the classical regression procedure. \nIf there are uncertainties $\\sigma_{x,\\nu}, \\sigma_{y,\\nu}$ in both coordinates and if the regression\nfunction is linear in $x$ $f(x,\\vec{a})=a_1x+a_2$ then the misfit is given by the following expression:\n\\[\\chi_{\\vec{a}}^2=\\sum_{\\nu}\\frac{(\\boldsymbol{d}_{\\nu}-a_2-a_1x_{\\nu})^2}{\\sigma_{y,\\nu}^2+a_1^2\\sigma_{x,\\nu}^2}\\]\n\nIn summary we find the following probability density function for the parameters:\n%7_4\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{7_4.png}\n\\end{figure}\nMore on the difference between pdfs and probability distributions will follow in the next unit.\\\\\n\nAn obvious way to decide on the parameters is to take the \\textit{maximum of the posterior probability density} - the so-\ncalled \\textbf{MAP solution}. In the case of a flat prior this solution is\nequal to the maximum likelihood. The\\textbf{ Maximum Likelihood (ML)} choice of\nthe parameters is the basis of parameter estimation in conventional statistics.\nIf in addition the likelihood is \\textit{Gaussian}, as in the present case, then the\nMAP and ML solution is obtained by \\textit{minimizing} $\\chi_{\\vec{a}}^2$, which is the\n\\textbf{Least-Squares} method that we discussed before.\\\\%7_5\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{7_5.png}\n\\end{figure}\n\\textit{This shows that the least squares approach is \\textit{only applicable} in the case of Gaussian \nexperimental noise and if we have no (or if we ignore) prior knowledge about the parameters.} \\\\\n\nIn general the MAP and hence ML solution is not very robust and highly\nsusceptible to noise. In particular if the likelihood is not \\textbf{unimodal}, which means it has \\textit{several peaks}, \nthe maximum can be misleading if it does not carry the \\textit{dominant probability mass}.\nA more reliable characterization of the parameters is given by the \\textbf{posterior\nmean}.\nHere we finally need the normalization, which can be obtained by the following integral.%7_6\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{7_6.png}\n\\end{figure}\n\nIt cannot be overstressed that a single value for the parameters, be it given\nby the MAP or the mean, is \\textit{meaningless, if we do not know the \\textbf{uncertainty}}.\nThe uncertainty can be quantified by the \\textbf{variance}.\nIn many cases also the \\textbf{covariance} is of great interest.%7_7\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{7_7.png}\n\\end{figure}\n\nIt tells us whether uncertainties are correlated. For instance it could be that\nonly a combination $a_1 + a_2$ is well defined by the data, while the individual\nvalues are not. This can be seen in the covariance.\\\\\n\n\\section*{Predicting values}\nNow we turn to the predictive aspect of regression. We are interested in the\nfunction value $y^*$ at a new position $x^*$, given the data $\\boldsymbol{D}$. If the pivot point\n$x^*$ lies \\textit{within the set of given pivot points}, we call this type of prediction an\n\\textbf{interpolation}, otherwise \\textbf{extrapolation}. The naive and inconsistent approach\nwould be to replace the unknown parameters by the estimated obtained before \nand just insert $x^*$ in the model function to obtain the function value\nat the desired position. \\\\%7_8\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{7_8.png}\n\\end{figure}\nThe correct approach, however, is to \\textit{determine the probability for the function \nvalue $y^*$ given the data, so $P(y^*|\\boldsymbol{D},X)$}.\nWe can compute $p(y^*|\\vec{a},\\boldsymbol{D},X)=\\delta(y^*-f(x^*,\\vec{a}))$ if we know the parameters. So we introduce\nthem via the marginalization rule.%\n\\begin{equation*}\\boxed{p(y^*|\\boldsymbol{D},X)=\\int \\text{d}V_{\\vec{a}}p(y^*|\\vec{a},\\boldsymbol{D},X) \\cdot p(\\vec{a}|\\boldsymbol{D},X)\n}\\end{equation*}\\\\\n Then the moments of $y^*$ are \n \\begin{equation*}\\boxed{\\langle (y^*)^n\\rangle=\\int \\text{d}V_{\\vec{a}}(f(x^*,\\vec{a}))^n \\cdot p(\\vec{a}|\\boldsymbol{D},X)\n}\\end{equation*}\\\\\nThe result becomes particularly simple if the model function depends\nlinearly of the parameters, so $f(x,\\vec{a})=M(x)\\vec{a}$, where $M(x)$ is a row-vector containing the ansatz functions $M=(\\Phi_1(x),\\Phi_2(x),...)$\nevaluated at $x$. Then the mean of the regression value $y^*$ is equal to the \\textit{linear combination\nof the ansatz functions with the mean of the parameters}.\n\\[\\langle y^*\\rangle = M(x^*)\\langle \\vec{a}\\rangle\\]\nSo in the linear case, this is in agreement with the naive approach, with the\nparameters replaced by the posterior mean.\nFor the variance of the regression value we obtain\n\\[\\langle (\\Delta y^*)^2\\rangle = M(x^*)CM^T(x^*)\\]\nThe square root of the variance quantifies the uncertainty of the regression\nvalue.\\\\%\n\n\nCaptain Venn wanted to know the azimutal or horizontal angles of the\nstar Arcturus at midnight on the shortest night of the year. Since the whether\nwas cloudy on that day of observation he wanted to infer the treasure's position\nby interpolating his measurement values.\\\\\nCaptain Venn knows that the accuracy of his measurements is limited by\nhis time measurement which has an accuracy of about one minute. \nThe uncertainty of his angle measurements is given by the \\textit{sum of\nthe deviations due to the time shifts plus the accuracy of his sextant and compass}.\nFrom test measurements he knows the approximate deviations of the angles due to the time inaccuracy.\nWe assume that the deviations of the angles are normal distributed with the derived $\\sigma$ values just mentioned.%7_9\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{7_9.png}\n\\end{figure}\nNext we assume a linear model for which we can apply the formulas we just derived%7_10\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{7_10.png}\n\\end{figure}\nformulas. Following the Bayesian regression steps we end up with a joint\nprobability density for the linear parameter and we can use them to derive a prediction for the desired angles.%7_11\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{7_11.png}\n\\end{figure}\n\n\\textit{Have a look at the interactive Pluto notebooks to get familiar with other\nmodel functions and the numerical tricks to evaluate the integrals over the\nwhole parameter space! Here you can also explore the benefits of using a better \nastronomic model to predict star orbits and check how well extrapolation\nworks within several months.}\\\\\n\n\\section*{Classification}\nNow we turn to the classification problem.\nGiven the \\textit{classification labels} for the two species of fish and their \\textit{positions}, the goal\nis to \\textit{find the border between the fish reserves}, which shall be described by\na linear function.\\\\%7_12\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{7_12.png}\n\\end{figure}\n\nThe function depends on some parameters $\\vec{a}$. \n\\[y_{border}=f(x,\\vec{a})=M(x)\\vec{a}\\]\nHere $M_{ij}(x)=\\phi_j(x_i)$ defines the model, or rather\nthe \\textit{set of ansatz functions that are linearly combined weighted by the parameters}. For instance we can have a linear model or a quadratic model. We can also construct an implicit function. \\[f(x,y,\\vec{a})=M(x,y)\\vec{a}=0\\]\nWhen we insert the position $(x_i|y_i)$ of the fish, the implicit function yields 0 if the fish resides exactly on the boundary. Otherwise the sign of the function tells us on which side of the boundary the fish is located. \nIn order to derive the probability density for the model $p(\\vec{a}|\\boldsymbol{X},M,\\boldsymbol{C})$\nparameters given positions $\\boldsymbol{X}$ and labels $\\boldsymbol{C}$ of all fish and the model $M$, we proceed in a similar manner as in the regression case. Bayes’ theorem yields a proportionality to the product of likelihood and prior.\\[p(\\vec{a}|\\boldsymbol{X},M,\\boldsymbol{C})\\propto p(\\boldsymbol{X}|\\vec{a},M,\\boldsymbol{C})p(\\vec{a}|M)\\]\n\nThe classification label $\\boldsymbol{C}$ has been omitted in the conditional part of the prior as it has no implications. \nMoreover we assume that the likelihood terms are \\textit{uncorrelated} resulting in a product form. \\[p(\\boldsymbol{X}|\\vec{a},M,\\boldsymbol{C})=\\prod_{\\nu}p(\\boldsymbol{x}_{\\nu}|\\vec{a},M,\\boldsymbol{C}_{\\nu}\\]\nThe individual likelihood factors are the \\textit{probability to find a fish of a certain species at a specific position}.\nHere, the model and the corresponding parameters are important because they define the boundary of the fish reserves.\nThe likelihood is a \\textit{property of the fish} and is related to why and how they stick to their reserve. \nThe likelihood could in principle be quite different for the classification of other objects.\nNevertheless, the following considerations show how such classification problems are treated in\nthe framework of Bayesian probability theory in general.\\\\\nAs mentioned before, the sign of the implicit function $f(x_{\\nu},y_{\\nu},\\vec{a})$ tells us on which side of the boundary the fish is located. \\\\\n\nIn the case of a linear implicit model function, the value of $f(x,y,\\vec{a})=xa_1+ya_2+1$ can be used to easily determine the \\textit{shortest distance to the boundary}. Just think of the Hessian normal form.%7_13\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{7_13.png}\n\\end{figure}\n%Generally for a fish at position $x_v$, we define the shortest distance to the border by the following expression.\\\\%\n\nThe distance is defined as positive if the fish is on the correct site of the boundary and negative otherwise.\nIn order to obtain a probability that is constant for a fish in its own reserve and that decreases continuously to zero when crossing the border we choose the logistic function.\nThe likelihood then reads%7_14\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{7_14.png}\n\\end{figure}\nwhere $\\frac {1}{\\beta}$ defines the width of the ``No Fish’s Land'' in which the probability\ndrops continuously to zero. \nIts area is assumed to be \\textit{very small} and the logistic function is almost a step function. \nHence the meaning of the \\textbf{normalization} $Z$ is the \\textit{size of the area of the two reserves}. For simplicity, we assume that the dependence of these areas on the parameters $\\vec{a}$ and on the fish label $C_i$ can be ignored.\nThen $Z$ is an unimportant constant.\\\\\nIt happens that not all fish abide by the rules. $\\epsilon$ is the proportion of such fish and is related to the \\textbf{slack variable}\nin optimization problems. \n$\\epsilon$ makes the classification \\textbf{outlier tolerant}.\nSo by now we have all terms of the probability for the model parameters.\nFrom that we can determine the mean values of the parameters, as well as their uncertainty. %7_15\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{7_15.png}\n\\end{figure}\n\nFinally we can determine the mean and the variance of the boundary. \n\\[\\langle y\\rangle =M(x)\\langle \\vec{a}\\rangle \\qquad C_y=\\langle \\Delta y \\Delta y^T\\rangle = M(x)C_{\\vec{a}}M(x)^T\\]\n\nSo let’s apply the Bayesian logistic classification approach to find the probability for the natural\nboundary of the fish reserve. Using the data Bernoulli provided leads\nto a probability distribution for the two parameters that can be visualized\nby semitransparent borderlines.%7_16\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{7_16.png}\n\\end{figure}\n It can be seen from the formula that the likelihood function is maximized if the number of outliers is minimized. \\\\%7_17\n \\begin{figure}[H]\n \t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{7_17.png}\n\\end{figure}\n\n\\textit{See also the interactive pluto notebook to play with the slack variable $\\epsilon$ and\nother data sets.}\\\\\n\n\\section*{Model selection}\nAnother important question is the \\textbf{model selection}, which answers the question ``\\textit{What is the\nprobability that the correct form of the border is given by the model b, if we\nknow the position of all fish and their labels?}'' Here, Bayes theorem gives the following expression \n\\[P(M|\\boldsymbol{X},\\boldsymbol{C})=\\frac{1}{Z'}p(\\boldsymbol{X}|M,\\boldsymbol{C}) \\cdot P(M,\\boldsymbol{C})\\]\nwhere the normalization can easily be computed in the end.\nNow we use the marginalization rule to introduce the model parameters.\nAs long as we do not know better, we assume a uniform prior within certain\nparameter ranges.\\\\%7_18\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{7_18.png}\n\\end{figure}\n\nHere $V_M$ is the prior volume that depends on the model.\nThen the probability for model M in the light of the data is given by the following expression. %7_19\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{7_19.png}\n\\end{figure}\nHere $\\Omega_M$ is the \\textit{volume in parameter space} allowed by the model.\nIt should be noted that \\textbf{Ockham's razor} is an integral part of the Bayesian expression \nand it \\textit{penalizes unnecessarily complex models} \\textit{(The more complicated a model is, the larger is its parameter volume!)}.\\\\\n \n\nThis concludes unit 7. We have learned Bayesian regression and how to\napply it to parameter estimation and model selection. \nWe learned also how to predict unseen measurement values and their probabilities and we got insights into classification of data.\nNow it’s your turn to actually find Captain Venn’s treasure in the pluto\nnotebooks where you can also work on the boundary issue of Claire and\nMakabe.\nPlease feel free to ask questions in the forum and feel encouraged to test your\nknowledge in the quiz!\n\n\n\\vspace{2cm}\n\\begin{minipage}[t]{1\\textwidth}\n\t\\raggedleft\n\t\\centering\n\t\\includegraphics[width = 0.20\\textwidth]{CC-BY_icon}\n\t\\vspace{0.2cm}\n\t\n\t\\centering\n\t{\\large ITPCP, TU Graz} \\\\\n\thttps://creativecommons.org/licenses/by/4.0/legalcode\n\\end{minipage}\n\\end{document}", "meta": {"hexsha": "3f09451328ac699879c17e097a99fafce265641b", "size": 22307, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "transcripts/tex-files/Lection_7.tex", "max_stars_repo_name": "moserjo/bayes-imoox", "max_stars_repo_head_hexsha": "144bde64410b7e740efa28c82b5e7dfe66885141", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2021-03-19T04:40:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-30T14:12:16.000Z", "max_issues_repo_path": "transcripts/tex-files/Lection_7.tex", "max_issues_repo_name": "moserjo/bayes-imoox", "max_issues_repo_head_hexsha": "144bde64410b7e740efa28c82b5e7dfe66885141", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-02-20T10:51:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-26T13:57:05.000Z", "max_forks_repo_path": "transcripts/tex-files/Lection_7.tex", "max_forks_repo_name": "moserjo/bayes-imoox", "max_forks_repo_head_hexsha": "144bde64410b7e740efa28c82b5e7dfe66885141", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-19T18:14:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-27T07:07:35.000Z", "avg_line_length": 56.7608142494, "max_line_length": 348, "alphanum_fraction": 0.7662617116, "num_tokens": 6010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.32115984792011987}}
{"text": "\\SetPicSubDir{ch-Background}\n\n\\chapter{Background}\n\\label{ch:background}\n\\vspace{2em}\nThis section provides the background required to understand this work. Readers who already have an understanding of Deep Reinforcement Learning and Deep Deterministic Policy Gradient (DDPG) may skip this section.\n\nWe would like to note that a large portion of this section has been reproduced from OpenAI's Spinning Up in Deep RL~\\cite{SpinningUp2018}. What is different in this reproduction, however, is that the background information on DRL has been adapted to fit the ideas and concepts related to map-less navigation found in this work.\n\n\\section{Deep Reinforcement Learning}\nDeep reinforcement learning (DRL) is the combination of reinforcement learning and deep learning. This idea of using neural networks for reinforcement learning, however, is not new and can be dated all the way back to Teasauro's TD-Gammon~\\cite{tesauro_temporal_nodate}. In the early 2010s, however, the field of deep learning began to find groundbreaking success, particularly in speech recognition~\\cite{dahl_context-dependent_2012} and computer vision~\\cite{krizhevsky_imagenet_2017}. This success, combined with the advances in computing power, allowed the revival in interest of using deep neural networks as universal function approximators for reinforcement learning - leading to deep reinforcement learning.\n\nDeep reinforcement learning is useful when~\\cite{SpinningUp2018}:\n\\begin{itemize}\n\\item we have a sequential decision-making problem (which we can represent as a Markov Decision Process)\n\\item we do not know the optimal behaviour (e.g. multi-modal problem)\n\\item but we can still evaluate whether behaviours are good or bad\n\\end{itemize}\n\n\\subsection{Markov Decision Process}\nTo train our agent with deep reinforcement learning, we must be able to model the relationship between the agent and its environment. A Markov Decision Process (MDP) is a mathematical object that describes our agent interacting with a stochastic environment. It is defined by the following components:\n\\begin{itemize}\n\\item $S$: \\textbf{state space}, a set of states of the environment. This is the set of inputs for our robot which contain a view of the world (i.e. a stack of laser scans, the current speed of the robot, and the target position with respect to the robot's local frame)\n\\item $A$: \\textbf{action space}, a set of actions, which the agent selects from each timestep. The actions taken by our robot to reach its target are its linear velocity and angular velocity, both of which are continuous-valued variables\n\\item $P(r, s' | s, a)$: \\textbf{transition probability distribution}. For each state s and action $a$, $P$ specifies the probability that the environment will emit reward $r$ and transition to state $s'$. This transition function describes the relationship between states, actions, next states, and rewards in an environment.\n\\end{itemize}\n\n\\subsection{Policies}\nThe end goal is to find a policy $\\pi$, which tells the agent what actions to take given a state. In DRL, we use parameterized policies: policies whose outputs are computable functions that depend on a set of parameters (e.g. the weights and biases of a neural network) which we can adjust to change the behavior via some optimization algorithm~\\cite{SpinningUp2018}.\n\nWe denote the parameters of such a policy by $\\theta$, and then write this as a subscript on the policy symbol to highlight the connection:\n\n\\begin{equation}\na_{t} \\sim \\pi_{\\theta}(\\cdot | s_{t})\n\\end{equation}\n\n\\subsection{Reward and Return}\n\\label{background:subsec:reward}\nThe reward function $R$ is critically important in reinforcement learning (and specifically for this work). It depends on the current state of the world, the action just taken, and the next state of the world:\n\n\\begin{equation}\nr_{t} = R(s_{t}, a_{t}, s_{t+1})\n\\end{equation}\n\nThe goal of an agent is to maximise the cumulative reward over a trajectory. In this work, the type of return used is called an \\textbf{infinite-horizon discounted return}, which is the sum of all rewards ever obtained by the agent, but discounted by how far off in the future they're obtained. This formulation of reward includes a discount factor $\\gamma \\in (0, 1)$\n\nSpecifically (prior to adding the reward feature proposed in this work), this work uses the reward function for map-less navigation proposed in Xie et. al's AsDDPG network~\\cite{xie_learning_2018}:\n\\begin{equation*}\nReward, r_{t} = \n\\begin{cases}\n  R_{crash}& \\text{if robot crashes},\\\\   \n  R_{reach}& \\text{if robot reaches the goal},\\\\  \n  \\gamma{((d_{t-1} - d_{t})\\Delta{t} - C)}& \\text{otherwise}.\\\\  \n\\end{cases}\n\\end{equation*}\n\n\\subsection{The RL Problem}\nThe goal of reinforcement learning is to select a policy which maximises \\textbf{expected return} when the agent acts according to it. To talk about expected return, we first have to talk about probability distributions over trajectories.\n\nLet’s suppose that both the environment transitions and the policy are stochastic. In this case, the probability of a $T$-step trajectory is:\n\\begin{equation}\nP(\\tau|\\pi) = p_{0}(s_{0}) \\prod_{t=0}^{T-1} P(s_{t-1}|s_{t}, a_{t}) \\pi(a_{t}|s_{t})\n\\end{equation}\n\nThe expected return, denoted by $J(\\pi)$, is then:\n\\begin{equation}\nJ(\\pi) = \\int_{\\tau} P(\\tau|\\pi) R(\\tau) = \\tau \\sim \\pi R(\\tau)\n\\end{equation}\n\nThe central optimization problem in RL can then be expressed by:\n\\begin{equation}\n\\pi^{*} = arg\\underset{\\pi}{max} J(\\pi)\n\\end{equation}\n\nwith $\\pi$ being the optimal policy.\n\n\\subsection{Value Functions}\nIt's often useful to know the \\textbf{value} of a state, or state-action pair. By value, we mean the expected return if you start in\nthat state or state-action pair, and then act according to a particular policy forever after. Value functions are used, one way or another, in almost every RL algorithm.\n\nThere are four main functions of note:\n\\begin{enumerate}\n\\item The \\textbf{On-Policy Value Function}, $V^{\\pi}(s)$, which gives the expected return if you start in a state $s$ and always act according to policy $\\pi$:\n\t\\begin{equation}\n\tV^{\\pi}(s) = \\tau \\sim \\pi R(\\tau)|s_{0} = s\n\t\\end{equation}\n\\item The \\textbf{On-Policy Action-Value Function}, $Q^{\\pi}(s, a)$, which gives the gives the expected return if you start in state $s$, take an arbitrary action $a$ (which may not have come from the policy), and then forever after act according to policy\n$\\pi$:\n\t\\begin{equation}\n\tQ^{\\pi}(s, a) = \\tau \\sim \\pi R(\\tau)|s_{0} = s, a_{0} = a\n\t\\end{equation}\n\\item The \\textbf{Optimal Value Function}, $V^{*}(s)$, which gives the expected return if you start in state $s$ and always act according to the \\textit{optimal} policy in the environment\n\t\\begin{equation}\n\tV^{*}(s) = \\underset{\\pi}{max} \\tau \\sim \\pi R(\\tau)|s_{0} = s\n\t\\end{equation}\n\\item The \\textbf{Optimal Action-Value Function}, $Q^{*}(s, a)$, which gives the expected return if you start in state $s$, take an arbitrary action $a$, and then forever after act according to the \\textit{optimal} policy in the environment:\n\t\\begin{equation}\n\tQ^{*}(s, a) = \\underset{\\pi}{max} \\tau \\sim \\pi R(\\tau)|s_{0} = s, a_{0} = a\n\t\\end{equation}\n\\end{enumerate}\n\n\\subsection{The Optimal Q-Function and the Optimal Action}\nThere is an important connection between the optimal action-value function $Q^{*}(s, a)$ and the action selected by the optimal policy. By definition, $Q^{*}(s, a)$ gives the expected return for starting in state $s$, taking (arbitrary) action $a$, and then acting according to the optimal policy forever after.\n\nThe optimal policy in $s$ will select whichever action maximises the expected return from starting in $s$. As a result, if we have $Q^{*}$, we can directly obtain the optimal action, $a^{*}(s)$, via:\n\\begin{equation}\n\ta^{*}(s) = \\underset{a}{\\argmax} Q^{*}(s, a)\n\\end{equation}\n\nThis connection is important; some RL algorithms learn by improving their policy (thereby directly obtaining \"good\" actions), whereas others learn by improving their Q-Function (which allows them to determine the best action from a set of actions, indirectly obtaining \"good\" actions).\n\n\\subsection{Bellman Equations}\nAll four of the value functions obey special self-consistency equations called \\textbf{Bellman equations}. The basic idea behind the Bellman equations is this:\n\\begin{center}\nThe value of your starting point is the reward you expect to get from being there, plus the value of wherever you land next.\n\\end{center}\n\nThe Bellman equations for the on-policy value functions are:\n\\begin{equation}\n\tV^{\\pi}(s) = \\underset{\\underset{s' \\sim P}{a \\sim \\pi}}{E} [r(s, a) + \\gamma V^{\\pi}(s')]\n\tQ^{\\pi}(s, a) = \\underset{s' \\sim P}{E} [r(s, a) + \\gamma \\underset{a' \\sim \\pi}{E}[Q^{\\pi}(s', a')]]\n\\end{equation}\n\nwhere $s' \\sim P$ is shorthand for $s' \\sim P(\\cdot|s, a)$, indicating that the next state $s'$ is sampled from the environment's transition rules; $a \\sim \\pi$ is shorthand for $a \\sim \\pi(\\cdot|s)$; and $a' \\sim \\pi$ is shorthand for $a' \\sim \\pi(\\cdot|s')$.\n\nThe Bellman equations for the optimal value functions are:\n\\begin{equation}\n\tV^{*}(s) = \\underset{a}{max} \\underset{s' \\sim P}{E} [r(s, a) + \\gamma V^{*}(s')]\n\tQ^{*}(s, a) = \\underset{s' \\sim P}{E} [r(s, a) + \\gamma \\underset{a'}{max}[Q^{*}(s', a')]]\n\\end{equation}\n\nThe crucial difference between the Bellman equations for the on-policy value functions and the optimal value functions, is the absence or presence of the $max$ over actions. Its inclusion reflects the fact that whenever the agent gets to choose its action, in order to act optimally, it has to pick whichever action leads to the highest value.\n\n\\subsection{Advantage Functions}\nSometimes in RL, we don't need to describe how good an action is in an absolute sense, but only how much better it is than others on average. That is to say, we want to know the relative \\textbf{advantage} of that action. We make this concept precise with the \\textbf{advantage function}.\n\nThe advantage function $A^{\\pi}(s, a)$ corresponding to a policy $\\pi$ describes how much better it is to take a specific action $a$ in state $s$, over randomly selecting an action according to $\\pi(\\cdot|s)$, assuming you act according to $\\pi$ forever after. Mathematically, the advantage function is defined by\n\\begin{equation}\nA^{\\pi}(s, a) = Q^{\\pi}(s, a) - V^{\\pi}(s)\n\\end{equation}\n\n\\section{Deep Deterministic Policy Gradient (DDPG)}\nThe network presented in this work is a variant of DDPG~\\cite{xie_learning_2018}. As such, it is crucial that we also provide a background for what DDPG is, and how it works.\n\nDeep Deterministic Policy Gradient (DDPG) is an algorithm which concurrently learns a Q-function and a policy. It uses off-policy data and the Bellman equation to learn the Q-function, and uses the Q-function to learn the policy.\n\nThis approach is closely connected to Q-learning, and is motivated the same way: if you know the optimal action-value function $Q^{*}(s,a)$, then in any given state, the optimal action $a^{*}(s)$ can be found by solving:\n\n\\begin{equation}\na^{*}(s) = \\argmax_{a} Q^*(s,a)\n\\end{equation}\n\nDDPG interleaves learning an approximator to $Q^*(s,a)$ with learning an approximator to $a^*(s)$, and it does so in a way which is specifically adapted for environments with continuous action spaces. But what does it mean that DDPG is adapted specifically for environments with continuous action spaces? It relates to how we compute the max over actions in $\\max_a Q^*(s,a)$.\n\nWhen there are a finite number of discrete actions, the max poses no problem, because we can just compute the Q-values for each action separately and directly compare them. (This also immediately gives us the action which maximizes the Q-value.) But when the action space is continuous, we can't exhaustively evaluate the space, and solving the optimization problem is highly non-trivial. Using a normal optimization algorithm would make calculating $\\max_a Q^*(s,a)$ a painfully expensive subroutine. And since it would need to be run every time the agent wants to take an action in the environment, this is unacceptable.\n\nBecause the action space is continuous, the function $Q^*(s,a)$ is presumed to be differentiable with respect to the action argument. This allows us to set up an efficient, gradient-based learning rule for a policy $\\mu(s)$ which exploits that fact. Then, instead of running an expensive optimization subroutine each time we wish to compute $\\max_a Q(s,a)$, we can approximate it with $\\max_a Q(s,a) \\approx Q(s,\\mu(s))$.\n\n\\subsection{Quick Facts}\n\\begin{itemize}\n\\item DDPG is an off-policy algorithm\n\\item DDPG can only be used for environments with continuous action spaces\n\\item DDPG can be thought of as being deep Q-learning for continuous action spaces\n\\end{itemize}\n\nNext, we'll explain the math behind the two parts of DDPG: learning a Q function, and learning a policy.\n\n\\subsection{The Q-Learning Side of DDPG}\n\nFirst, let's recap the Bellman equation describing the optimal action-value function, $Q^*(s,a)$. It's given by\n\n\\begin{equation}\nQ^*(s,a) = \\underset{s' \\sim P}{E}[r(s, a) + \\gamma \\max_{a'} Q^*(s', a')]\n\\end{equation}\n\nwhere $s' \\sim P$ is shorthand for saying that the next state, $s'$, is sampled by the environment from a distribution $P(\\cdot| s, a)$.\n\nThis Bellman equation is the starting point for learning an approximator to $Q^*(s,a)$. Suppose the approximator is a neural network $Q_{\\phi}(s,a)$, with parameters $\\phi$, and that we have collected a set ${\\mathcal D}$ of transitions $(s,a,r,s',d)$ (where $d$ indicates whether state $s'$ is terminal). We can set up a mean-squared Bellman error (MSBE) function, which tells us roughly how closely $Q_{\\phi}$ comes to satisfying the Bellman equation:\n\n\\begin{equation}\nL(\\phi, {\\mathcal D}) = \\underset{(s,a,r,s',d) \\sim {\\mathcal D}}{{\\mathrm E}}\\left[\n    \\Bigg( Q_{\\phi}(s,a) - \\left(r + \\gamma (1 - d) \\max_{a'} Q_{\\phi}(s',a') \\right) \\Bigg)^2\n    \\right]\n\\end{equation}\n\nHere, in evaluating $(1-d)$, we've used a Python convention of evaluating True to 1 and False to 0. Thus, when $d ==$ True---which is to say, when s' is a terminal state---the Q-function should show that the agent gets no additional rewards after the current state.\n\nQ-learning algorithms for function approximators, such as DQN (and all its variants) and DDPG, are largely based on minimizing this MSBE loss function. There are two main tricks employed by all of them which are worth describing, and then a specific detail for DDPG.\n\n\\textbf{Trick One: Replay Buffers}. All standard algorithms for training a deep neural network to approximate $Q^*(s,a)$ make use of an experience replay buffer. This is the set ${\\mathcal D}$ of previous experiences. In order for the algorithm to have stable behavior, the replay buffer should be large enough to contain a wide range of experiences, but it may not always be good to keep everything. If you only use the very-most recent data, you will overfit to that and things will break; if you use too much experience, you may slow down your learning. This may take some tuning to get right.\n\n\\textbf{Trick Two: Target Networks}. Q-learning algorithms make use of target networks. The term\n\\begin{equation}\nr + \\gamma (1 - d) \\max_{a'} Q_{\\phi}(s',a')\n\\end{equation}\nis called the target, because when we minimize the MSBE loss, we are trying to make the Q-function be more like this target. Problematically, the target depends on the same parameters we are trying to train: $\\phi$. This makes MSBE minimization unstable. The solution is to use a set of parameters which comes close to $\\phi$, but with a time delay---that is to say, a second network, called the target network, which lags the first. The parameters of the target network are denoted $\\phi_{\\text{targ}}$.\n\nIn DQN-based algorithms, the target network is just copied over from the main network every some-fixed-number of steps. In DDPG-style algorithms, the target network is updated once per main network update by polyak averaging:\n\\begin{equation}\n\\phi_{\\text{targ}} \\leftarrow \\rho \\phi_{\\text{targ}} + (1 - \\rho) \\phi,\n\\end{equation}\nwhere $\\rho$ is a hyperparameter between 0 and 1 (usually close to 1).\n\n\\textbf{DDPG Detail: Calculating the Max Over Actions in the Target}. As mentioned earlier: computing the maximum over actions in the target is a challenge in continuous action spaces. DDPG deals with this by using a target policy network to compute an action which approximately maximizes $Q_{\\phi_{\\text{targ}}}$. The target policy network is found the same way as the target Q-function: by polyak averaging the policy parameters over the course of training.\n\nPutting it all together, Q-learning in DDPG is performed by minimizing the following MSBE loss with stochastic gradient descent:\n\\begin{equation}\nL(\\phi, {\\mathcal D}) = \\underset{(s,a,r,s',d) \\sim {\\mathcal D}}{{\\mathrm E}}\\left[\n    \\Bigg( Q_{\\phi}(s,a) - \\left(r + \\gamma (1 - d) Q_{\\phi_{\\text{targ}}}(s', \\mu_{\\theta_{\\text{targ}}}(s')) \\right) \\Bigg)^2\n    \\right],\n\\end{equation}\n\nwhere $\\mu_{\\theta_{\\text{targ}}}$ is the target policy.\n\n\\subsection{The Policy Learning Side of DDPG}\n\nPolicy learning in DDPG is fairly simple. We want to learn a deterministic policy $\\mu_{\\theta}(s)$ which gives the action that maximizes $Q_{\\phi}(s,a)$. Because the action space is continuous, and we assume the Q-function is differentiable with respect to action, we can just perform gradient ascent (with respect to policy parameters only) to solve\n\\begin{equation}\n\\max_{\\theta} \\underset{s \\sim {\\mathcal D}}{{\\mathrm E}}\\left[ Q_{\\phi}(s, \\mu_{\\theta}(s)) \\right].\n\\end{equation}\nNote that the Q-function parameters are treated as constants here.\nExploration vs. Exploitation\n\nDDPG trains a deterministic policy in an off-policy way. Because the policy is deterministic, if the agent were to explore on-policy, in the beginning it would probably not try a wide enough variety of actions to find useful learning signals. To make DDPG policies explore better, we add noise to their actions at training time.\n\nAt test time, to see how well the policy exploits what it has learned, we do not add noise to the actions.", "meta": {"hexsha": "e1d9a05f8c5652b818da16bfabe0513efee3052c", "size": 18139, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/ch-background.tex", "max_stars_repo_name": "watate/nusthesis", "max_stars_repo_head_hexsha": "e987422e5efcb7affe9a52bd0bc8d57ecc80ed48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/ch-background.tex", "max_issues_repo_name": "watate/nusthesis", "max_issues_repo_head_hexsha": "e987422e5efcb7affe9a52bd0bc8d57ecc80ed48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/ch-background.tex", "max_forks_repo_name": "watate/nusthesis", "max_forks_repo_head_hexsha": "e987422e5efcb7affe9a52bd0bc8d57ecc80ed48", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 80.2610619469, "max_line_length": 715, "alphanum_fraction": 0.7475053752, "num_tokens": 4769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.3211598402666781}}
{"text": "\\documentclass[twoside,onecolumn,10pt]{waflarticle}\n% can use option mtpro \n\n\\usepackage{graphicx}\n\\usepackage{rotating}\n\\usepackage{scalefnt}\n\\usepackage{bm}\n\\usepackage{fancyhdr}\n\\usepackage{etoolbox}\n\\usepackage{amsmath}\n\n%\\AtBeginEnvironment{eqnarray}{\\setlength{\\arraycolsep}{2pt}}\n%\\usepackage[hidelinks]{hyperref}\n\n\n\\newlength\\lengthfigure                  % declare a figure width unit\n\\setlength\\lengthfigure{0.16\\textwidth} % make the figure width unit scale with the textwidth\n\\renewcommand{\\fontsizetable}{\\footnotesize\\scalefont{1.0}}\n\\renewcommand{\\fontsizefigure}{\\footnotesize\\scalefont{1.1}}\n\\renewcommand{\\vec}[1]{\\bm{#1}}\n\\let\\citen\\cite\n\\setcounter{tocdepth}{3}\n\n\\newcommand{\\alb}{\\vspace{0.1cm}\\\\} % array line break\n\\newcommand{\\mfd}{\\displaystyle}\n\\newcommand{\\ns}{{n_{\\rm s}}}\n\\newcommand{\\nd}{3}\n\\renewcommand{\\vec}[1]{\\bm{ #1 }}\n\n\n\\journalvolume{Journal of Computational Physics, Vol.\\ 300, Pages 779--799, 2015.}\n\n\\title{Modeling Weakly-Ionized Plasmas in Magnetic Field:\\\\ a New Computationally-Efficient Approach}\n\n\\author{  Bernard Parent\\thanks{Associate Professor, Dept.\\ of Aerospace Engineering, Pusan National University, Busan 609-735, Korea, http://bernardparent.ca.},\n          ~~Sergey O.\\ Macheret\\thanks{Professor, School of Aeronautics and Astronautics, Purdue University, West Lafayette, IN 47907-2045, USA.},\n          ~~and Mikhail N.\\ Shneider\\thanks{Senior Research Scientist, Dept.\\ of Mechanical and Aerospace Engineering, Princeton University, Princeton, NJ 08544-5263, USA.}\\\\\n}\n\n\n%\\setlength\\nomenclaturelabelwidth{0.13\\hsize}  % optional, default is 0.03\\hsize\n%\\setlength\\nomenclaturecolumnsep{0.09\\hsize}  % optional, default is 0.06\\hsize\n\n\\nomenclature{\n  \\begin{nomenclaturelist}{Roman symbols}\n   \\item[$\\vec{A}$] origin of the magnet dipole moment\n   \\item[$A$]         cross-sectional area, $\\rm m^2$\n  \\end{nomenclaturelist}\n\n\n  \\begin{nomenclaturelist}{Greek symbols}\n   \\item[$\\alpha_{ij}$]  commonly used term in the diffusion matrix $K$\n  \\end{nomenclaturelist}\n\n\n  \\begin{nomenclaturelist}{Superscripts}\n   \\item[$\\star$]    sum of turbulent and molecular diffusion\n  \\end{nomenclaturelist}\n\n  \\begin{nomenclaturelist}{Subscripts}\n   \\item[$t$]      turbulent\n  \\end{nomenclaturelist}\n}\n\n\n\\abstract{\nDespite its success at simulating accurately both non-neutral and quasi-neutral weakly-ionized plasmas, the drift-diffusion model has been observed to be a particularly stiff set of equations. Recently, it was demonstrated that the stiffness of the system could be relieved by rewriting the equations such that the potential is obtained from Ohm's law rather than Gauss's law while adding some source terms to the ion transport equation to ensure that Gauss's law is satisfied in non-neutral regions. Although the latter was applicable to multicomponent and multidimensional plasmas, it could not be used for plasmas in which the magnetic field was significant. This paper hence proposes a new computationally-efficient set of electron and ion transport equations that can be used not only for a plasma with multiple types of positive and negative ions, but also for a plasma in magnetic field. Because the proposed set of equations is obtained from the same physical model as the conventional drift-diffusion equations without introducing new assumptions or simplifications, it results in the same exact solution when the grid is refined sufficiently while being more computationally efficient: not only is the proposed approach considerably less stiff and hence requires fewer iterations to reach convergence but it yields a converged solution that exhibits a significantly higher resolution. The combined faster convergence and higher resolution is shown to result in a hundredfold increase in computational efficiency for some typical steady and unsteady plasma problems including non-neutral cathode and anode sheaths as well as quasi-neutral regions.       \n\n}\n\n\\begin{document}\n\n\n\\pagestyle{fancy}\n\\fancyhead{}\n\\fancyhead[CO,CE]{\\begin{minipage}{\\textwidth}\\footnotesize\\center\n      \\it  {B.\\ Parent, S.\\ O.\\ Macheret, M.\\ N.\\ Shneider, ``Modeling Weakly-Ionized Plasmas in Magnetic Field: a New Computationally-Efficient Approach'',\\\\  {Journal of Computational Physics}, Vol.\\ 300, Pages 779--799, 2015.}~\\\\ \\end{minipage}}\n\\renewcommand{\\headrulewidth}{0.0pt}\n\n  \\pagenumbering{arabic}\n  \\setcounter{page}{1}\n  \\maketitle\n%  \\tableofcontents\n%  \\makenomenclature\n%%  \\listoftables\n%%  \\listoffigures\n\n\\linespread{1.05}\n\n\n\n\n\n\n\\section{Introduction}\n\n\\dropword Generally referred to as magneto-plasmadynamics or magnetohydrodynamics (MHD), the process of applying a force on a fluid in motion using a magnetic field is the main mechanism behind several new aerospace technologies such as shockwave control in supersonic flows   \\cite{pof:2002:poggie,aiaa:2004:shneider}, power generation during re-entry using a MHD generator  \\cite{jpp:2009:fujino,aiaa:2009:wan,jsr:2012:kim}, heat shield in hypersonic flows \\cite{jsr:2013:bizek,jsr:2012:kawamura},  thrust generation using a Faraday accelerator \\cite{jpp:2005:parent,jpp:2007:parent}, or efficiency improvement of pulse detonation engines through MHD energy bypass \\cite{jpp:2012:zeineh}. In such devices, the working fluid on which the magnetic field acts is air ionized either through high electric fields, through electron or microwave beams, or through potassium or cesium seeding. Independently of the ionization process, the  ionization fraction of the air remains low (typically less than 0.1\\% or so) due to the energy needed to ionize the air being high relative to the flow enthalpy. For this reason, air plasmas in aerospace applications can be considered  \\emph{weakly-ionized}.  % weakly-ionized plasmas  are such that the electrons collide mostly with non-ionized atoms or molecules, and the momentum and energy of the flow is mostly due to the bulk non-ionized atomic/molecular species\n\nWhen assuming quasi-neutrality throughout, the numerical simulation of weakly-ionized plasmas in magnetic field can be accomplished efficiently by obtaining the potential from the generalized Ohm's law (see Refs.\\ \\cite{aiaa:2009:wan, jpp:2007:parent} for instance). However, because the quasi-neutral assumption limits its use to plasmas in which the positive and negative charges closely approach each other, such a strategy can not be applied in the vicinity of dielectric surfaces or within the cathode and anode sheaths where the positive charge density differs substantially from the negative charge density. Because the accurate modelling of the non-neutral regions near the surfaces is often critical due to the large voltage (and hence power) drop within cathode sheaths, the numerical simulation of many weakly-ionized plasmas can not be accomplished through the generalized Ohm's law  without inducing excessive error in the solution. Rather, it is deemed necessary for many problems to obtain the potential from Gauss's law and to solve additional transport equations to account for the motion of the ions and the electrons with respect to the neutrals. Commonly referred to as the  ``drift-diffusion model'', such a strategy was first demonstrated viable in solving weakly-ionized gases under the influence of an externally-applied magnetic field in Ref.\\ \\cite{jcp:2004:surzhikov}, and was used subsequently to obtain multiple solutions of gas discharges in which the electrons were magnetized (see for instance Refs.\\ \\cite{jpp:2008:poggie,jap:2009:shang,bookchapter:2009:shang}).\n\n\nDespite its success at predicting accurately both non-neutral and quasi-neutral plasmas in the presence of magnetic field, the drift-diffusion model has been observed to be an exceptionally stiff set of equations. That is, the system of equations is such that it forces a numerical method to use an integration steplength which is excessively small in relation to the smoothness of the exact solution, hence resulting in a disproportionate number of iterations to reach convergence. The stiffness is further exacerbated should the plasma contain quasi-neutral regions of substantial size, in which case the number of iterations needed to obtain a solution is in the order of millions. In Ref.\\ \\cite{jcp:2013:parent}, it was argued that the stiffness of the drift-diffusion model originates from the potential equation based on Gauss's law being particularly sensitive to small errors in the charged species densities when the plasma becomes quasi-neutral. It was then demonstrated that the stiffness of the system could be relieved by rewriting the equations such that the potential is obtained from Ohm's law rather than Gauss's law while adding some source terms to the ion transport equation to ensure that Gauss's law is satisfied in non-neutral regions (see Ref.\\ \\cite{jcp:2013:parent} and also Ref.\\ \\cite{jcp:2007:crispel}). \n\nThe recast of the drift-diffusion set of equations first proposed in Ref.\\ \\cite{jcp:2013:parent} was extended to multicomponent and multidimensional plasmas in Ref.\\ \\cite{jcp:2014:parent}, where several test cases involving quasi-neutral plasmas between dielectrics  and non-neutral discharges between electrodes showed a remarkable improvement in computational efficiency compared to the conventional approach: Not only did the recast set of equations permit the use of considerably higher integration steplengths  resulting in a thirtyfold or more reduction in the number of iterations to reach convergence, but it also resulted in a higher resolution of the converged solution whenever the plasma included quasi-neutral regions of substantial size. The combined gains in resolution and convergence rates resulted in the recast system of equations being typically 100 times more computationally efficient than the conventional drift-diffusion equations  while not sacrificing on the generality of the physical model.  \n\nDespite being generally applicable to weakly-ionized plasmas in multiple dimensions including plasmas with various types of ions (including negative ions), the recast set of transport equations presented in Ref.\\ \\cite{jcp:2014:parent} is not applicable to a plasma in which either the ions or the electrons are magnetized and can hence not be used to solve problems in which the external magnetic field is significant. The goal of this paper is hence to craft a new computationally-efficient set of electron and ion transport equations that can be used not only for a multicomponent and multidimensional plasma, but also for a plasma in magnetic field. As will be shown subsequently, this will require the potential equation to be based on the \\emph{generalized} Ohm's law rather than the standard form of Ohm's law and to require a change in the definition of the ambipolar electric field when recasting the transport equations for the negatively-charged species. As in prior work, it is ensured that the recast set of equations is obtained from the same physical model as the conventional drift-diffusion equations and, as such, yields the same exact solution either within quasi-neutral regions or within non-neutral regions including cathode, anode, and dielectric sheaths.            \n\n\n\n\\section{Physical Model}\n\nLet us now outline the physical model from which the recast computationally-efficient set of transport equations will be subsequently derived. Commonly referred to as the ``fluid model'' or ``drift-diffusion model'', the physical model under consideration treats the neutrals and each charged species as independent fluids with their own velocities interacting with the other fluids through collision forces. In the presence of a magnetic field, the drift-diffusion model yields the following mass conservation equation for each charged species (either electrons, positive ions, or negative ions):\n%\n\\begin{equation}\n  \\frac{\\partial N_k}{\\partial t} + \\sum_{i=1}^3 \\frac{\\partial}{\\partial x_i} N_k \\vec{V}_i^k = W_k\n  \\label{eqn:massconservation}\n\\end{equation}\n%\nwhere $k$ is an index associated with the species to be solved and where the species velocity $\\vec{V}^k$ is obtained from:\n%\n\\begin{equation}\n  \\vec{V}^k=\\vec{V}^{\\rm n} + s_k \\mu_k \\left(\\vec{E}+\\vec{V}^k \\times \\vec{B}\\right)-\\frac{\\mu_k}{|C_k| N_k}\\nabla P_k\n \\label{eqn:Vvector}\n\\end{equation}\n% \nThe latter expression for the species velocity can be obtained from the momentum equation by assuming that the terms related to inertia change and to collision forces between charged species are negligible compared to the terms related to the collision forces between the charged species and the neutrals. \n\nIn the mass and momentum equations above, $N_k$ is the number density of species $k$, $\\vec{V}_i^k$ is the $i$th component of the $k$th species velocity including drift and diffusion, $\\vec{V}^{\\rm n}$ is the neutrals velocity vector including drift and diffusion, $W_k$ is the source term containing all chemical reactions, and $P_k$ is the partial pressure. As well, $s_k$ is the species sign  (equal to $+1$ for the positive ions and to $-1$ for the electrons and the negative ions), $C_k$ is the species charge  (equal to $-e$ for the electrons, to $+e$ for the singly-charged positive ions, to $-2e$ for the doubly-charged negative ions, etc, with $e$ the elementary charge), $\\vec{E}$ is the electric field vector, $\\vec{B}$ the magnetic field vector, and $\\mu_k$ the species mobility.\n \nIt can be convenient to rewrite the  charged species velocity vector in tensor form as follows:\n%\n\\begin{equation}\n  \\vec{V}^{k}_i = \\vec{V}^{\\rm n}_i+\\sum_{j=1}^\\nd s_k \\wtilde{\\mu}^k_{ij}  \\vec{E}_j^{\\rm n}\n             - \\sum_{j=1}^\\nd  \\frac{\\wtilde{\\mu}^{k}_{ij}}{|C_k| N_k} \\frac{\\partial P_k}{\\partial x_j}\n  \\label{eqn:V}\n\\end{equation}\n%\nwith $\\vec{E}^{\\rm n}$ being the effective electric field in the neutrals reference frame:\n%\n\\begin{equation}\n\\vec{E}^{\\rm n} \\equiv \\vec{E}+\\vec{V}^{\\rm n} \\times \\vec{B}\n\\label{eqn:En}\n\\end{equation}\n%\nand with the mobility tensor equal to:\n%\n\\begin{equation}\n\\!\\!\\!\n\\begin{array}{l}\\mfd\n\\wtilde{\\mu}^k  =\\frac{\\mu_k}{1+\\mu_k^2|\\vec{B}|^2}\\left[\\!\\!\\begin{array}{ccc} \n      1+\\mu_k^2 \\vec{B}_1^2 \n     & \\mu_k^2\\vec{B}_1\\vec{B}_2+s_k \\mu_k \\vec{B}_3  \n     & \\mu_k^2\\vec{B}_1\\vec{B}_3-s_k \\mu_k \\vec{B}_2 \\alb\n      \\mu_k^2\\vec{B}_1\\vec{B}_2-s_k\\mu_k\\vec{B}_3 & 1+\\mu_k^2\\vec{B}_2^2 &  \\mu_k^2\\vec{B}_2\\vec{B}_3+s_k\\mu_k\\vec{B}_1  \\alb\n      \\mu_k^2\\vec{B}_1\\vec{B}_3 +s_k\\mu_k\\vec{B}_2 & \\mu_k^2 \\vec{B}_2\\vec{B}_3-s_k\\mu_k\\vec{B}_1  & 1+\\mu_k^2\\vec{B}_3^2 \n    \\end{array} \\!\\!\\!\\!\\right]\n\\end{array}\n\\label{eqn:mutilde}\n\\end{equation}\n%\nIn the latter, the magnetic field $\\vec{B}$ corresponds to the externally applied magnetic field, as the induced magnetic field can be shown to have negligible impact on many weakly-ionized plasmas (the so-called low magnetic Reynolds number approximation). When the induced magnetic field plays a negligible role, and when the applied (external) magnetic field does not vary in time, it can be demonstrated that the Maxwell equations reduce to the solution of Gauss's law:\n%\n\\begin{equation}\n\\sum_{j=1}^3 \\frac{\\partial \\vec{E}_j}{\\partial x_j}=\\frac{1}{\\epsilon_0} \\sum_{k=1}^\\ns C_k N_k \n\\label{eqn:gauss}\n\\end{equation}\n%\nin which the electric field vector can be expressed in terms of a potential function as follows:  \n%\n\\begin{equation}\n  \\vec{E}_j=-\\frac{\\partial \\phi}{\\partial x_j}\n  \\label{eqn:potential}\n\\end{equation}\n%\nThe electric field potential $\\phi$ exists as long as the curl of the electric field is zero, which is the case when the magnetic field does not vary in time.  \nAlthough not required to solve the system of equations outlined above, one physical parameter that is often used when analyzing plasma flowfields is the current density $\\vec{J}$, which is defined as:\n%\n\\begin{equation}\n  \\vec{J}_i \\equiv \\sum_{k=1}^\\ns C_k N_k  \\vec{V}^k_i\n \\label{eqn:Jdefinition}\n\\end{equation}\n%\nAfter substituting in the latter the velocity tensor from Eq.\\ (\\ref{eqn:V}), the following expression for the current can be obtained:\n%\n\\begin{equation}\n\\begin{array}{l}\n\\mfd  \\vec{J}_i = \\sum_{j=1}^3  \\wtilde{\\sigma}_{ij} \\vec{E}_j^{\\rm n} \n             - \\sum_{j=1}^3 \\sum_{k=1}^\\ns s_k \\wtilde{\\mu}^k_{ij}  \\frac{\\partial P_k}{\\partial x_j}\n+ \\rho_{\\rm e} \\vec{V}_i^{\\rm n} \n\\end{array}\n\\label{eqn:J}\n\\end{equation}\n%\nin which the tensor conductivity and the net charge density are defined as:\n%\n\\begin{equation}\n\\begin{array}{l}\n\\mfd\n\\wtilde{\\sigma}\\equiv\\sum_{k=1}^\\ns |C_k| N_k \\wtilde{\\mu}^k\n\\end{array}\n\\label{eqn:sigmatilde}\n\\end{equation}\n%\n%\n\\begin{equation}\n\\rho_{\\rm e}\\equiv\\sum_{k=1}^\\ns C_k N_k\n\\label{eqn:rhoe}\n\\end{equation}\n%\nFinally, a constitutive relation that is needed to close the system of equations is the ideal gas law which yields the partial pressure given the number density and the temperature:\n%\n\\begin{equation}\nP_k = N_k k_{\\rm B} T_k\n\\label{eqn:Pk}\n\\end{equation}\n%\nwhere $T_k$ is the species temperature.\n\nCommonly used to simulate weakly-ionized plasmas in the presence of magnetic field, the physical model outlined above can predict accurately not only quasi-neutral phenomena such as ambipolar diffusion and ambipolar drift but also non-neutral phenomena within cathode and anode sheaths. It can also be used to simulate multicomponent plasmas in which there are several types of ions (either negative or positive) as well as unsteady plasmas in which the displacement current is significant. Nonetheless, it is pointed out that the physical model used herein is subject to several assumptions, with the most critical being the following: (i) the forces due to collisions between charged species are small compared to forces due to collisions  between the charged species and the neutrals; (ii) the induced magnetic field is negligible; (iii) within the momentum equation, the terms related to the inertia change are negligible compared to the terms related to collision forces. As was demonstrated in Ref.\\ \\cite{jcp:2011:parent}, such assumptions are well justified as long as the plasma remains weakly-ionized (i.e. the ionization fraction should remain lower than $10^{-3}$ or so), which is the case for a wide variety of plasmas used in industrial applications.     \n\n\n\n\\section{Conventional Governing Equations}\n\nWhen using digital computers, the conventional approach to simulate the drift-diffusion physical model outlined in the previous section  consists of solving a transport equation for each charged species along with the potential equation obtained from Gauss's law (see for instance Refs.\\ \\cite{jcp:2004:surzhikov,jpp:2008:poggie,jap:2009:shang,book:2012:surzhikov,aiaaconf:2014:surzhikov}). The charged species transport equation can be derived from the mass conservation equations as outlined in Eq.\\ (\\ref{eqn:massconservation}) with the species velocity from the momentum equation applicable to a weakly-ionized plasma as shown in Eq.\\ (\\ref{eqn:V}). This  yields the following:\n%\n\\begin{equation}\n  \\frac{\\partial N_k}{\\partial t} + \\sum_{i=1}^3 \\frac{\\partial}{\\partial x_i} N_k\\left(\\vec{V}^{\\rm n}_i+\\sum_{j=1}^\\nd s_k \\wtilde{\\mu}^k_{ij}  \\vec{E}_j^{\\rm n}\n             - \\sum_{j=1}^\\nd  \\frac{\\wtilde{\\mu}^{k}_{ij}}{|C_k| N_k} \\frac{\\partial P_k}{\\partial x_j}\\right) = W_k\n\\end{equation}\n%\nWhen the magnetic field is strong (resulting in an electron Hall parameter $\\mu_{\\rm e}|\\vec{B}|$ approaching or exceeding 1), and when the transport equations are solved through an implicit integration strategy, it is beneficial to the stability of the method to extract from the pressure gradient terms the diffusion terms that are diagonally dominant. This can be achieved by first subtracting and adding a pressure gradient term on the LHS as follows:\n%\n\\begin{equation}\n  \\frac{\\partial N_k}{\\partial t} + \\sum_{i=1}^3 \\frac{\\partial}{\\partial x_i} N_k\\left(\\vec{V}^{\\rm n}_i+\\sum_{j=1}^\\nd s_k \\wtilde{\\mu}^k_{ij}  \\vec{E}_j^{\\rm n}\n             - \\sum_{j=1}^\\nd  \\frac{\\wtilde{\\mu}^{k}_{ij}}{|C_k| N_k} \\frac{\\partial P_k}{\\partial x_j}\n-\\frac{\\mu_k}{|C_k| N_k} \\frac{\\partial P_k}{\\partial x_i} +\\frac{\\mu_k}{|C_k| N_k} \\frac{\\partial P_k}{\\partial x_i}\n\\right) = W_k\n\\end{equation}\n%\nThen, expand the partial pressure using the ideal gas law $P_k=N_k k_{\\rm B} T_k$ and reformat:\n%\n\\begin{equation}\n\\begin{array}{l}\\mfd\n  \\frac{\\partial N_k}{\\partial t} + \\sum_{i=1}^3 \\frac{\\partial}{\\partial x_i} N_k\\left(\\vec{V}^{\\rm n}_i+\\sum_{j=1}^\\nd s_k \\wtilde{\\mu}^k_{ij}  \\vec{E}_j^{\\rm n}\n             - \\sum_{j=1}^\\nd  \\frac{\\wtilde{\\mu}^{k}_{ij}-\\delta_{ij} \\mu_k}{|C_k| N_k} \\frac{\\partial P_k}{\\partial x_j}\\right)\n-\\sum_{i=1}^3 \\frac{\\partial}{\\partial x_i} \\left(\\frac{T_k k_{\\rm B} \\mu_k}{|C_k| } \\frac{\\partial N_k}{\\partial x_i} \\right)\\alb\\mfd\n=W_k+\n\\sum_{i=1}^3 \\frac{\\partial}{\\partial x_i} \\left(\\frac{N_k k_{\\rm B} \\mu_k}{|C_k| } \\frac{\\partial T_k}{\\partial x_i}\n\\right)  \n\\end{array}\n\\end{equation}\n%\nwith $\\delta_{ij}$ the Kronecker delta which is equal to 1 should $i=j$ and to 0 otherwise. We can write the latter in matrix form as follows:\n%\n\\begin{equation}\n R = Z \\frac{\\partial U}{\\partial t} + \\sum_{i=1}^3 \\frac{\\partial}{\\partial x_i} A_i U  - \\sum_{i=1}^3  \\frac{\\partial}{\\partial x_i}  \\left( K \\frac{\\partial U}{\\partial x_i}\\right)  -S\n\\end{equation}\n%\nwhere $R$ is the residual vector and the other matrices correspond to:\n%\n\\begin{eqnarray}\n \\left[U\\right]_k&=&N_k \\alb\n \\left[A_i\\right]_{k,k} &=& \\vec{V}^{\\rm n}_i+\\sum_{j=1}^\\nd s_k \\wtilde{\\mu}^k_{ij}  \\vec{E}_j^{\\rm n}\n             - \\sum_{j=1}^\\nd  \\frac{\\wtilde{\\mu}^{k}_{ij}-\\delta_{ij} \\mu_k}{|C_k| N_k} \\frac{\\partial P_k}{\\partial x_j}  \\alb\n \\left[K\\right]_{k,k} &=& \\frac{T_k k_{\\rm B} \\mu_k}{|C_k|} \\alb\n \\left[Z\\right]_{k,k} &=& 1 \\alb\n \\left[S\\right]_k &=&W_k+\n\\sum_{i=1}^3 \\frac{\\partial}{\\partial x_i} \\left(\\frac{N_k k_{\\rm B} \\mu_k}{|C_k| } \\frac{\\partial T_k}{\\partial x_i}\n\\right) \n\\end{eqnarray}\n%\nwhere the notation $[M]_{k,k}$ denotes the diagonal element on the $k$th row of the matrix $M$ while the notation $[F]_k$ refers to the element on the $k$th row of the vector $F$. The latter yields a diagonally-dominant diffusion matrix $K$ even at high electron Hall parameter, which is a necessary condition for stable integration using an implicit method. As well, extracting the non-diagonal diffusion terms from matrix $K$ and inserting them in the convection matrix $A$ permits standard central stencils to be used when discretizing the diffusion terms. However, should they include cross-derivatives, the diffusion terms would require non-standard upwinded stencils or they would lead to spurious oscillations at a high Hall parameter (see Ref.\\ \\cite{jcp:2011:parent} for more details on this point).   \n\nThe electric field is obtained from the potential as in Eq.\\ (\\ref{eqn:potential}) which itself is found by integrating the potential equation concurrently to the mass conservation equations. To ensure that Gauss's law is satisfied within the non-neutral regions, it is necessary to obtain the potential equation from Gauss's law by substituting Eq.\\ (\\ref{eqn:potential}) into Eq.\\ (\\ref{eqn:gauss}):\n%\n\\begin{equation}\n\\sum_{j=1}^3 \\frac{\\partial^2 \\phi}{\\partial x_j^2}=-\\frac{\\rho_{\\rm e}}{\\epsilon_0}  \n\\label{eqn:potentialgauss}\n\\end{equation}\n%  \nThe latter constitute what is here denoted as the ``conventional governing equations'', which are commonly used to solve weakly-ionized plasmas (either quasi-neutral or non-neutral) in the presence of a magnetic field using discrete methods.\n\n\n\n\n\n\n\n\n\n\n\\section{Recast of the Positively-Charged Species Transport Equations}\n\n\nThe ``conventional governing equations'' outlined in the previous section are well known to be exceptionally stiff. Such stiffness has been observed to be independent of the type of integration strategy used, either explicit or fully-implicit. As first outlined in Ref.\\ \\cite{jcp:2013:parent}, the stiffness originates from the potential equation based on Gauss's law being particularly sensitive to small errors in the electron or ion densities whenever the plasma becomes quasi-neutral. One approach that has been shown successful in relieving the stiffness is by rewriting the governing equations such that the electric field is obtained from a potential based on Ohm's law rather than Gauss's law (see Refs.\\ \\cite{jcp:2013:parent} and \\cite{jcp:2014:parent}). As well, to ensure that Gauss's law is satisfied some source terms need to be added to the positive ion transport equations. \n\nWe here generalize the approach proposed in Ref.\\ \\cite{jcp:2014:parent} to a plasma in magnetic field. To do so, it is convenient to first define $\\Delta \\vec{V}^k$ as the difference between the velocity of species $k$ and the velocity of species $k$ should the magnetic field be zero:\n%\n\\begin{equation}\n\\Delta \\vec{V}^k_i \\equiv \\vec{V}^k_i - \\left(\\vec{V}^{\\rm n}_i+ s_k \\mu_k  \\vec{E}_i\n             -   \\frac{\\mu_k}{|C_k| N_k} \\frac{\\partial P_k}{\\partial x_i}\\right)\n\\label{eqn:deltaV}\n\\end{equation}\n%\nIsolate $\\vec{V}^k$ in the latter and substitute in Eq.\\ (\\ref{eqn:massconservation}), and simplify noting that $s_k=1$ and $C_k$ is positive for the positive ions: \n%\n\\begin{equation}\n  \\frac{\\partial N_{k}}{\\partial t} + \\sum_{i=1}^3 \\frac{\\partial}{\\partial x_i} \\left(N_k \\Delta \\vec{V}_i^k +N_{k} \\vec{V}^{\\rm n}_i+N_{k}  \\mu_k   \\vec{E}_i\n             -    \\frac{\\mu_k }{|C_{k}| } \\frac{\\partial P_{k}}{\\partial x_i}\\right) = W_{k}\n\\end{equation}\n%\nThe source terms that must be added to ensure that Gauss's law is satisfied can be obtained by multiplying Gauss's law Eq.\\ (\\ref{eqn:gauss}) by $\\mu_{k} N_{k}$ and rearranging:\n%\n\\begin{equation}\n0=\\mu_{k} N_{k} \\sum_{i=1}^3 \\frac{\\partial \\vec{E}_i}{\\partial x_i}-\\mu_{k} N_{k}\\frac{1}{\\epsilon_0} \\sum_{r=1}^\\ns C_r N_r \n\\end{equation}\n%\nThen, we add the latter to the former to obtain:\n%\n\\begin{equation}\n  \\frac{\\partial N_{k}}{\\partial t} + \\sum_{i=1}^3 \\frac{\\partial}{\\partial x_i} \\left(N_k \\Delta \\vec{V}_i^k +N_{k} \\vec{V}^{\\rm n}_i+N_{k}  \\mu_k  \\vec{E}_i\n             -    \\frac{\\mu_k }{|C_{k}| } \\frac{\\partial P_{k}}{\\partial x_i}\\right) = W_{k}+\\mu_{k} N_{k} \\sum_{i=1}^3 \\frac{\\partial \\vec{E}_i}{\\partial x_i}-\\mu_{k} N_{k}\\frac{1}{\\epsilon_0} \\sum_{r=1}^\\ns C_r N_r \n\\end{equation}\n%\nAnd we note that the following statement holds:\n%\n\\begin{equation}\n\\mu_{k} N_{k} \\sum_{i=1}^3 \\frac{\\partial \\vec{E}_i}{\\partial x_i}\n= \\sum_{i=1}^3 \\frac{\\partial }{\\partial x_i} \\mu_{k} N_{k} \\vec{E}_i\n - \\sum_{i=1}^3 \\vec{E}_i \\frac{\\partial }{\\partial x_i} \\mu_{k} N_{k}\n\\end{equation}\n%\nSubstitute the latter in the former, rewrite the partial pressure term using the ideal gas law outlined in Eq.\\ (\\ref{eqn:Pk}), expand the pressure derivatives, and rearrange:\n%\n\\begin{equation}\n\\begin{array}{l}\\mfd\n  \\frac{\\partial N_{k}}{\\partial t} \n+ \\sum_{i=1}^3 \\frac{\\partial}{\\partial x_i} N_k \\left(\\Delta \\vec{V}_i^k + \\vec{V}^{\\rm n}_i\\right) \n- \\sum_{i=1}^3  \\frac{\\partial}{\\partial x_i} \\left(\n                 \\frac{\\mu_k k_{\\rm B} T_{k}}{|C_{k}| } \\frac{\\partial N_{k}}{\\partial x_i}\n\\right)\n+ \\sum_{i=1}^3 \\vec{E}_i \\frac{\\partial }{\\partial x_i} \\mu_{k} N_{k}\n \\alb\\mfd~~~~~\n= \n W_{k}\n-\\mu_{k} N_{k}\\frac{1}{\\epsilon_0} \\sum_{r=1}^\\ns C_r N_r \n+ \\sum_{i=1}^3  \\frac{\\partial}{\\partial x_i} \\left(\n                 \\frac{\\mu_k k_{\\rm B} N_{k}}{|C_{k}| } \\frac{\\partial T_{k}}{\\partial x_i}\n\\right)\n\\end{array}\n\\label{eqn:positivespecies}\n\\end{equation}\n%\nThe latter is the modified transport equation for the positively-charged species, and must be used for all positive ions. It is obtained without introducing assumptions or simplifications from the physical model outlined in Section 2.\n\n\n\n\n\\section{Recast of the Negatively-Charged Species Transport Equations}\n\nIt can be shown that a system of equations composed of the recast transport equation outlined in Eq.\\ (\\ref{eqn:positivespecies}) for the positive ions, combined with the standard transport equation for the negative species (Eq.\\ (\\ref{eqn:massconservation})), and combined with a potential equation based on the generalized Ohm's law \\cite{jcp:2011:parent} has the same exact solution as the conventional governing equations outlined in Section 3 while not exhibiting high stiffness. However, such a set of equations would yield a rather low resolution and require significantly more nodes to reach the same accuracy within quasi-neutral regions of the plasma. As was  demonstrated in Ref.\\ \\cite{jcp:2013:parent}, such can be overcome by rewriting the transport equation for the negative species in \\emph{ambipolar form} following the approach outlined in Ref.\\ \\cite{jcp:2011:parent:2}. Rewriting the transport equations in ambipolar form increases the resolution because it reduces the dependence of the potential equation on the charged species transport equations in quasi-neutral regions.     \n\nThe ambipolar form of the negatively-charged species transport equations can be obtained by first isolating $\\vec{V}_i^k$ in  Eq.\\ (\\ref{eqn:deltaV}) and substituting in Eq.\\ (\\ref{eqn:massconservation}) noting that $s_k=-1$ when the species is negatively-charged:\n%\n\\begin{equation}\n\\begin{array}{l}\\mfd\n  \\frac{\\partial N_k}{\\partial t} \n+ \\sum_{i=1}^3 \\frac{\\partial}{\\partial x_i}  N_k \\left(  \\Delta \\vec{V}_i^k +\\vec{V}^{\\rm n}_i - \\mu_k  \\vec{E}_i\n\\right) \n- \\sum_{i=1}^3  \\frac{\\partial}{\\partial x_i}  \\left( \n   \\frac{\\mu_k }{|C_k|} \\frac{\\partial P_k}{\\partial x_i}\n\\right) \n= W_k\n\\end{array}\n\\end{equation}\n%\nThen, without loss of generality, we can add and subtract the ambipolar electric field $\\vec{E}^\\prime$ to the electric field:\n%\n\\begin{equation}\n\\begin{array}{l}\\mfd\n  \\frac{\\partial N_k}{\\partial t} \n+ \\sum_{i=1}^3 \\frac{\\partial}{\\partial x_i}  N_k \\left(  \\Delta \\vec{V}_i^k +\\vec{V}^{\\rm n}_i - \\mu_k  \\left(\\vec{E} -\\vec{E}^\\prime  \\right)_i\n\\right) \n- \\sum_{i=1}^3  \\frac{\\partial}{\\partial x_i}  \\mu_k N_k \\vec{E}^\\prime_i \n- \\sum_{i=1}^3  \\frac{\\partial}{\\partial x_i}  \\left( \n   \\frac{\\mu_k }{|C_k|} \\frac{\\partial P_k}{\\partial x_i}\n\\right) \n= W_k\n\\end{array}\n\\label{eqn:negspecies1}\n\\end{equation}\n%\nAs outlined in Ref.\\ \\cite{jcp:2014:parent}, significant gains in resolution can be reached when $\\vec{E}^\\prime$ is defined as the component of the electric field that cancels out all components of the current except due to drift. However, defining the ambipolar electric field  in this manner leads to some difficulties when the plasma is in the presence of a magnetic field. Not only does this result in a particularly complicated transport equation in which several terms are expensive to compute, but this  also entails convergence hangs when the magnetic field reaches high values. We here find it necessary to define the ambipolar electric field in a slightly different manner as the component of the electric field that cancels out all components of the \\emph{unmagnetized} current except due to drift and due to the motion of the neutrals, with the unmagnetized current being the current that would be obtained locally should the magnetic field be zero. The ambipolar electric field thus takes on the form:\n%\n\\begin{equation}\n \\vec{E}_i^\\prime \\equiv \\vec{E}_i - \\frac{1}{\\sigma} \\left(\\vec{J}_i-\\sum_{r=1}^\\ns C_r N_r \\Delta \\vec{V}_i^r -\\rho_{\\rm e} \\vec{V}_i^{\\rm n} \\right)\n \\label{eqn:Eprimedefinition}\n\\end{equation}\n%\nwhere the term within the bracket on the RHS can be easily shown to be the unmagnetized current density (the current density in the absence of a magnetic field):\n%\n\\begin{equation}\n\\mfd  \\vec{J}_i-\\sum_{r=1}^\\ns C_r N_r \\Delta \\vec{V}_i^r  - \\rho_{\\rm e} \\vec{V}_i^{\\rm n} =   \\sigma \\vec{E}_i \n             -  \\sum_{r=1}^\\ns s_r \\mu_r  \\frac{\\partial P_r}{\\partial x_i}\n\\label{eqn:Jzero}\n\\end{equation}\n%\nand where the conductivity $\\sigma$ is defined as:\n%\n\\begin{equation}\n  \\sigma \\equiv \\sum_{k=1}^\\ns \\mu_k |C_k| N_k \n\\end{equation}\n%\nAfter substituting Eq.\\ (\\ref{eqn:Jzero}) in Eq.\\ (\\ref{eqn:Eprimedefinition}) it can be shown that:\n%\n\\begin{equation}\n   \\vec{E}_i^\\prime =   \n   \\sum_{r=1}^\\ns \\frac{s_r \\mu_r }{\\sigma}  \\frac{\\partial P_r}{\\partial x_i}\n\\label{eqn:Eprime}\n\\end{equation}\n%\nThen, after substituting $\\vec{E}-\\vec{E}^\\prime$ from Eq.\\ (\\ref{eqn:Eprimedefinition}) and $\\vec{E}^\\prime$ from Eq.\\ (\\ref{eqn:Eprime}) into Eq.\\ (\\ref{eqn:negspecies1}) and rearranging, we obtain:\n%\n\\begin{equation}\n\\begin{array}{l}\\mfd\n  \\frac{\\partial N_k}{\\partial t} \n+ \\sum_{i=1}^3 \\frac{\\partial}{\\partial x_i}   N_k \\left(      \\sum_{r=1}^\\ns \\frac{\\delta_{rk}\\sigma+ C_r N_r \\mu_k}{\\sigma}   \\Delta \\vec{V}_i^r +\\left(1+\\frac{\\mu_k \\rho_{\\rm e}}{\\sigma}\\right)\\vec{V}^{\\rm n}_i - \\frac{\\mu_k}{\\sigma}  \\vec{J}_i \\right)\n\\alb\\mfd~~~~\n- \\sum_{i=1}^3 \\sum_{r=1}^{\\ns} \\frac{\\partial}{\\partial x_i} \\left( \\mu_r \\left( \\frac{\\delta_{rk}}{|C_k|}+ \\frac{ \\mu_k N_k s_r }{\\sigma} \\right) \\frac{\\partial P_r}{\\partial x_i}\\right) \n= \nW_k\n\\end{array}\n\\end{equation}\n%\nwhere $\\delta_{rk}$ is the Kronecker delta. \nAfter splitting the derivative involving the current $\\vec{J}$ into two terms and noting that the divergence of the current can be written as:\n%\n\\begin{equation}\n\\sum_{i=1}^3 \\frac{\\partial \\vec{J}_i}{\\partial x_i}=-\\sum_{r=1}^\\ns C_r \\frac{\\partial N_r}{\\partial t}\n\\end{equation}\n%\nthe following is obtained:\n%\n\\begin{equation}\n\\begin{array}{l}\\mfd\n  \\sum_{r=1}^{\\ns} \\frac{\\delta_{rk}\\sigma+C_r  \\mu_k N_k}{\\sigma} \\frac{\\partial N_r}{\\partial t}  \n+ \\sum_{i=1}^3 \\frac{\\partial}{\\partial x_i}   N_k \\left(\\sum_{r=1}^\\ns \\frac{\\delta_{rk}\\sigma+C_r  \\mu_k N_r}{\\sigma} \\Delta \\vec{V}_i^r +\\left(1+\\frac{\\mu_k\\rho_{\\rm e}}{\\sigma}\\right)\\vec{V}^{\\rm n}_i\\right) \n\\alb\\mfd~~~~\n- \\sum_{i=1}^3 \\vec{J}_i \\frac{\\partial}{\\partial x_i}  \\left( \\frac{\\mu_k N_k}{\\sigma} \n\\right) \n- \\sum_{i=1}^3 \\sum_{r=1}^{\\ns} \\frac{\\partial}{\\partial x_i} \\left(\\mu_r \\left(\\frac{ \\delta_{rk} }{ |C_k|}+   \\frac{ \\mu_k N_k s_r}{\\sigma}\\right)  \\frac{\\partial P_r}{\\partial x_i}\\right) \n= W_k\n\\end{array}\n\\end{equation}\n%\nWe then use the ideal gas relationship in Eq.\\ (\\ref{eqn:Pk}), expand the partial derivatives, and rewrite:\n%\n\\begin{equation}\n\\begin{array}{l}\\mfd\n  \\sum_{r=1}^{\\ns} \\frac{\\delta_{rk}\\sigma+C_r  \\mu_k N_k}{\\sigma} \\frac{\\partial N_r}{\\partial t}  \n+ \\sum_{i=1}^3 \\frac{\\partial}{\\partial x_i}   N_k \\left(\\sum_{r=1}^\\ns \\frac{\\delta_{rk}\\sigma+C_r  \\mu_k N_r}{\\sigma} \\Delta \\vec{V}_i^r +\\left(1+\\frac{\\mu_k\\rho_{\\rm e}}{\\sigma}\\right)\\vec{V}^{\\rm n}_i\\right) \n- \\sum_{i=1}^3 \\vec{J}_i \\frac{\\partial}{\\partial x_i}  \\left( \\frac{\\mu_k N_k}{\\sigma} \n\\right) \n\\alb\\mfd~~~~\n- \\sum_{i=1}^3 \\sum_{r=1}^{\\ns} \\frac{\\partial}{\\partial x_i} \\left(\\mu_r k_{\\rm B} T_r\\left(\\frac{ \\delta_{rk} }{ |C_k|}+   \\frac{ \\mu_k N_k s_r}{\\sigma}\\right)  \\frac{\\partial N_r}{\\partial x_i}\\right) \n= W_k\n+ \\sum_{r=1}^\\ns \\sum_{i=1}^3  \\frac{\\partial}{\\partial x_i} \\left( \\mu_r k_{\\rm B} N_r   \\left(\\frac{\\delta_{rk}}{|C_k|}+\\frac{s_r \\mu_k N_k}{\\sigma}\\right)  \\frac{\\partial T_r}{\\partial x_i} \\right)\n\\end{array}\n\\label{eqn:negativespecies}\n\\end{equation}\n%\nThe latter is the proposed ``ambipolar form'' of the transport equation for the negatively-charged species. It must be used not only for the electrons but for all negative ions. It is emphasized that the recast Eq.\\ (\\ref{eqn:negativespecies}) is obtained from the physical model outlined in Section 2 without making any assumption or simplification. As such, it can be used not only in quasi-neutral regions but also in non-neutral regions including cathode and anode sheaths. \n\n\n\n\n\n\n\\section{Proposed Governing Equations}\n\nWe can combine the transport equation for the positively-charged species, Eq.\\ (\\ref{eqn:positivespecies}) and the transport equation for the negatively-charged species, Eq.\\ (\\ref{eqn:negativespecies}) into a single equation:\n%\n\\begin{equation}\n\\begin{array}{l}\\mfd\n  \\sum_{r=1}^{\\ns} \\frac{\\delta_{rk}\\sigma + \\beta^-_k C_r  \\mu_k N_k}{\\sigma} \\frac{\\partial N_r}{\\partial t}  \n+ \\sum_{i=1}^3 \\frac{\\partial}{\\partial x_i}   N_k \\left(\\sum_{r=1}^\\ns \\frac{\\delta_{rk}\\sigma+\\beta_k^- C_r  \\mu_k N_r}{\\sigma} \\Delta \\vec{V}_i^r + \\left(1+\\beta_k^- \\frac{\\mu_k\\rho_{\\rm e}}{\\sigma}\\right)\\vec{V}^{\\rm n}_i\\right) \n\\alb\\mfd~~~~\n-  \\sum_{i=1}^3 \\beta_k^- \\vec{J}_i \\frac{\\partial}{\\partial x_i}  \\left( \\frac{\\mu_k N_k}{\\sigma} \n\\right) \n+ \\sum_{i=1}^3 \\beta_k^+ \\vec{E}_i \\frac{\\partial }{\\partial x_i} \\mu_{k} N_{k}\n- \\sum_{i=1}^3 \\sum_{r=1}^{\\ns} \\frac{\\partial}{\\partial x_i} \\left(\\mu_r k_{\\rm B} T_r\\left(\\frac{ \\delta_{rk} }{ |C_k|}+   \\frac{\\beta_k^- s_r \\mu_k N_k }{\\sigma}\\right)  \\frac{\\partial N_r}{\\partial x_i}\\right) \n\\alb\\mfd~~~~\n= W_k\n+ \\sum_{r=1}^\\ns \\sum_{i=1}^3  \\frac{\\partial}{\\partial x_i} \\left( \\mu_r k_{\\rm B} N_r   \\left(\\frac{\\delta_{rk}}{|C_k|}+\\frac{\\beta_k^- s_r \\mu_k N_k}{\\sigma}\\right)  \\frac{\\partial T_r}{\\partial x_i} \\right)\n-\\beta_k^+ \\mu_{k} N_{k}\\frac{\\rho_{\\rm e}}{\\epsilon_0}  \n\\end{array}\n\\end{equation}\n%\nwith\n%\n\\begin{equation}\n\\beta_k^\\pm = \\max(0,~\\pm s_k)\n\\end{equation}\n%\nWe can simplify further the latter by defining the ambipolar tensor $\\alpha$ as:\n%\n\\begin{equation}\n\\alpha_{kr} \\equiv\n  \\frac{\\delta_{rk}\\sigma+ \\beta_k^- C_r  \\mu_k N_k}{\\sigma} \n=  |C_r| \\left( \\frac{\\delta_{rk}}{|C_k|}+  \\frac{ \\beta_k^- s_r \\mu_k N_k}{\\sigma}\\right)\n=  \\frac{N_k}{N_r}\\frac{\\delta_{rk}\\sigma+ \\beta_k^- C_r  \\mu_k N_r}{\\sigma} \n\\end{equation}\n%\nand by noting that the following equality holds:\n%\n\\begin{equation}\n1+\\beta_k^- \\frac{\\mu_k\\rho_{\\rm e}}{\\sigma} \n= \\sum_{r=1}^\\ns \\frac{\\delta_{rk}\\sigma+ \\beta_k^- C_r  \\mu_k N_r}{\\sigma} \n \\end{equation}\n%\nWe thus obtain:\n%\n\\begin{equation}\n\\begin{array}{l}\\mfd\n  \\sum_{r=1}^{\\ns} \\alpha_{kr} \\frac{\\partial N_r}{\\partial t}  \n+ \\sum_{i=1}^3 \\sum_{r=1}^\\ns  \\frac{\\partial}{\\partial x_i}      \\alpha_{kr} \\left( \\Delta \\vec{V}_i^r + \\vec{V}^{\\rm n}_i \\right)N_r\n+  \\sum_{i=1}^3 \\left( \\beta_k^+ \\vec{E}_i- \\beta_k^- \\vec{J}_i   \\right) \\frac{\\partial}{\\partial x_i}  \\mu_{k} N_{k} \\left( \\beta_k^+ + {\\textstyle \\frac{1}{\\sigma}} \\beta_k^-  \n\\right) \n\\alb\\mfd~~~~\n- \\sum_{i=1}^3 \\sum_{r=1}^{\\ns} \\frac{\\partial}{\\partial x_i} \\left(\\frac{\\mu_r k_{\\rm B} T_r \\alpha_{kr}}{|C_r|}  \\frac{\\partial N_r}{\\partial x_i}\\right) \n= W_k\n-\\beta_k^+ \\mu_{k} N_{k}\\frac{\\rho_{\\rm e}}{\\epsilon_0}  \n+ \\sum_{r=1}^\\ns \\sum_{i=1}^3  \\frac{\\partial}{\\partial x_i} \\left( \\frac{\\mu_r k_{\\rm B} N_r  \\alpha_{kr}}{|C_r|}   \\frac{\\partial T_r}{\\partial x_i} \\right)\n\\end{array}\n\\label{eqn:positivenegativespecies}\n\\end{equation}\n%\nThe proposed charged species transport equations can also be written in general matrix form as follows:\n%\n\\begin{equation}\n  R=Z\\frac{\\partial U}{\\partial t} + \\sum_{i=1}^3\\frac{\\partial}{\\partial x_i} A_i U\n    + \\sum_{i=1}^3 G_i \\frac{\\partial}{\\partial x_i} B U - \\sum_{i=1}^3  \\frac{\\partial}{\\partial x_i} \\left( K \\frac{\\partial U}{\\partial x_i} \\right)-S\n\\label{eqn:Rproposed}\n\\end{equation}\n%\nwhere $R$ is the residual which is driven to zero through the iterative process, and where the other matrices can be shown to correspond to:\n%\n\\begin{eqnarray}\n \\left[U\\right]_k&=&N_k \\alb\n \\left[A_i\\right]_{k,k}&=&\\sum_{r=1}^\\ns \\frac{\\delta_{rk}\\sigma+\\beta_k^- C_r  \\mu_k N_r}{\\sigma} \\Delta \\vec{V}_i^r + \\left(1+\\beta_k^- \\frac{\\mu_k\\rho_{\\rm e}}{\\sigma}\\right)\\vec{V}^{\\rm n}_i \\alb\n% \\left[A_i\\right]_{k,k}&=&\\sum_{r=1}^\\ns \\alpha_{kr}\\frac{N_r}{N_k} \\left(\\Delta \\vec{V}_i^r +\\vec{V}^{\\rm n}_i\\right) \\alb\n \\left[B\\right]_{k,k}&=&\\beta_k^+ \\mu_k + \\frac{1}{\\sigma}\\beta_k^- \\mu_k \\alb\n \\left[G_i\\right]_{k,k}&=&\\beta_k^+ \\vec{E}_i - \\beta_k^- \\vec{J}_i \\alb\n \\left[K\\right]_{k,r} &=& \\frac{\\mu_r k_{\\rm B} T_r \\alpha_{kr}}{|C_r|} \\alb\n \\left[Z\\right]_{k,r} &=& \\alpha_{kr} \\alb\n \\left[S\\right]_k &=& W_k -\\beta_k^+ \\mu_{k} N_{k}\\frac{\\rho_{\\rm e}}{\\epsilon_0} \n+ \\sum_{r=1}^\\ns \\sum_{i=1}^3  \\frac{\\partial}{\\partial x_i} \\left( \\frac{\\mu_r k_{\\rm B} N_r \\alpha_{kr}}{|C_r|}  \\frac{\\partial T_r}{\\partial x_i} \\right)\n\\end{eqnarray}\n%\nIn the latter, the velocity difference $\\Delta \\vec{V}$ can be obtained by substituting Eq.\\ (\\ref{eqn:V}) into Eq.\\ (\\ref{eqn:deltaV}):\n%\n\\begin{equation}\n \\Delta \\vec{V}_i^k = \n   \\sum_{j=1}^\\nd s_k \\wtilde{\\mu}^k_{ij}  \\vec{E}_j^{\\rm n}\n      + \\sum_{j=1}^\\nd  \\left(\\frac{\\delta_{ij} \\mu_k-\\wtilde{\\mu}^{k}_{ij}}{|C_k| N_k}\\right) \\frac{\\partial P_k}{\\partial x_j}\n-  s_k \\mu_k  \\vec{E}_i\n\\end{equation}\n%\nwhile the current density is obtained from Eq.\\ (\\ref{eqn:J}) and the electric field is obtained from the potential equation based on Ohm's law which can be derived from the physical model outlined in Section 2 following the approach shown in Ref.\\ \\cite{jcp:2011:parent}: \n%\n\\begin{equation}\n\\!\\begin{array}{l}\n  \\mfd\\sum_{i=1}^3 \\frac{\\partial}{\\partial x_i}\\left(\\sum_{j=1}^3 \\wtilde{\\sigma}_{ij} \\left(-\\frac{\\partial \\phi}{\\partial x_j}  + \\left(\\vec{V}^{\\rm n} \\times \\vec{B}\\right)_j\\right) \n             - \\sum_{j=1}^3 \\sum_{k=1}^\\ns s_k   \\wtilde{\\mu}^{k}_{ij}  \\frac{\\partial P_k}{\\partial x_j}\n              + \\rho_{\\rm e} \\vec{V}_i^{\\rm n}  \\right)=-  \\frac{\\partial \\rho_{\\rm e}}{\\partial t}\n\\end{array}\n\\end{equation}\n%\nfrom which the electric field can be found using Eq.\\ (\\ref{eqn:potential}).\n\nIt is noted that the set of equations proposed herein is obtained from the same physical model as the conventional set of equations without introducing any additional assumption or simplification. As such, the exact solution obtained from the proposed set of equations is identical to the one obtained from the conventional set not only for quasi-neutral plasmas with significant ambipolar diffusion and drift phenomena but also for non-neutral sheaths, for unsteady plasmas, as well as for plasmas where the displacement current is non-negligible. \n\nDespite yielding the same exact solution as the conventional equations, the set of equations proposed herein is advantaged  by being considerably less stiff and hence requiring significantly less computing effort to reach convergence. Further, as will be shown below in the Test Cases section, the proposed equations yield a considerably higher resolution within plasma regions that are quasi-neutral.    \n\n\n\n\n\n\t\n\n\n\\section{Boundary Conditions}\n\n\nWhen the electron Hall parameter (i.e.\\ the product between the electron mobility and the magnitude of the magnetic field) becomes significant due to a strong applied magnetic field, the enforcement of boundary conditions can become problematic. The difficulties arise when imposing a zero current condition perpendicular to dielectric surfaces by setting to zero the component of $\\vec{J}$ perpendicular to the surface in Eq.\\ (\\ref{eqn:J}). When the magnetic field is non-zero, such leads to the potential $\\phi$ at the boundary node depending not only on the properties of the nearest inner node but also on the properties of the adjacent boundary nodes. Numerical experiments show that such direct dependence between boundary nodes entails major convergence problems for many plasma flowfields either when using the conventional or the proposed set of governing equations. The convergence difficulties become more severe when the electron Hall parameter approaches or exceeds 0.1 often leading to the solution diverging towards aphysical states or continuously oscillating without reaching a root. \n\nOne way that this problem can be overcome is by setting the magnetic field to zero on all boundary nodes and on all inner nodes adjacent to boundary nodes. In doing so, the plasma is not subject to a magnetic field near the surfaces and the same boundary conditions as used for a plasma in the absence of magnetic field can be specified:\n%\n\\begin{equation}\n\\frac{\\partial }{\\partial \\eta} N_+ \\vec{V}^{+}_\\eta = 0\n{~~~~~\\rm and~~~~~}\nN_{-}=0\n{~~~~~\\rm and~~~~~}\nN_{\\rm e}=\\frac{\\gamma}{\\mu_{\\rm e}} \\sum_{k=1}^\\ns N_k \\mu_k \\beta_k^+\n{~~~~~\\rm for~dielectrics~or~for~}\n\\vec{E}_\\eta<0\n\\end{equation}\n%\n%\n\\begin{equation}\nN_{+}=0\n{~~~~~\\rm and~~~~~}\n\\frac{\\partial }{\\partial \\eta} N_- \\vec{V}^{-}_\\eta = 0\n{~~~~~\\rm and~~~~~}\n\\frac{\\partial }{\\partial \\eta} N_{\\rm e} \\vec{V}^{\\rm e}_\\eta= 0\n{~~~~~\\rm otherwise} \n\\end{equation}\n%\nwith $\\gamma$ being the secondary emission coefficient and the subscripts/superscripts ``e'', ``$-$'', and ``$+$'' denoting the electron species, the negative ion species, and the positive ion species respectively. In the latter $\\eta$ refers to the coordinate perpendicular to the boundary and pointing away from the surface towards the nearest inner node, while  $\\vec{E}_\\eta$ and $\\vec{V}^k_\\eta$ refer to the electric field component and $k$th species velocity component in the direction of $\\eta$.   \n\nAs well, the potential on the dielectrics is specified such that the current perpendicular to dielectric surfaces is zero. Because the magnetic field is zero at the boundary nodes and the near-boundary nodes, this yields the following expression for the dielectrics potential:  \n%\n\\begin{equation}\n\\mfd  \\frac{\\partial \\phi}{\\partial \\eta} =     \n             - \\frac{1}{\\sigma}\\sum_{k=1}^\\ns s_k \\mu_k  \\frac{\\partial P_k}{\\partial \\eta}{~~~~~\\rm for~dielectrics~only}\n\\end{equation}\n%\n\nIt may be argued that setting the magnetic field to zero on the boundary and near-boundary nodes may entail some errors in the converged solution. However, such errors disappear as the grid is refined because the volume of the unmagnetized regions near the surfaces becomes insignificant compared to the total volume of the plasma.\n\nWhen applying the boundary conditions, it is found necessary to under-relax the update of the number densities and of the potential on the boundary nodes in order to prevent convergence hangs. For all cases here considered, either when using the conventional or the proposed equations, the relaxation factor is set to 0, 0.8, and 0.5 for the ion, electron, and potential equations respectively. The relaxation factor is such that, when set to 0, the boundary node property does not depend on its previous value when being updated and, when set to 1, the boundary node property remains unaltered. \n\n\n      \n\\section{Discretization and Integration}\n\nTo enable a fair comparison, both the conventional and the proposed sets of equations are discretized using the same stencils and solved using the same iterative procedure. \n\nThe convection terms are discretized with the Steger-Warming scheme turned second-order accurate through the Van Leer TVD limiter, while the diffusion terms are discretized with centered stencils, and the term $G \\delta_x BU$ is discretized as specified in Ref.\\ \\cite{jcp:2013:parent}. When extending the Steger-Warming scheme or the centered diffusion stencils to multiple dimensions, a dimensional-splitting strategy is employed in which the derivatives are split amongst the several dimensions and then discretized using one-dimensional operators. Because the problems tackled herein are such that the molecular and ambipolar diffusion effects are sufficiently strong to prevent discontinuities in the charged species densities, it is found unnecessary to use the upwinded discretization stencils for the potential equation proposed in Ref.\\ \\cite{jcp:2011:parent} (which are needed to prevent even-odd node discoupling of the potential to occur in the vicinity of discontinuities). Rather, all terms within the potential equation are discretized with centered stencils whether the potential equation is based on Gauss's law or the generalized Ohm's law.   \n\nThe discretized set of transport equations is converged by minimizing the residual vector through a block-implicit ADI algorithm \\cite{jcp:1980:briley}. To improve the convergence rates, it is found beneficial to linearize the Townsend ionization chemical source terms under the condition of constant current and to partially linearize the source terms added to enforce Gauss's law within the proposed equations   (see Ref.\\ \\cite{jcp:2014:parent} for details).  The potential equation either based on Ohm's law or Gauss's law is not solved in coupled form with the species transport equations. Rather, as in other plasma solvers, a more robust integration strategy is to solve the potential equation independently through a scalar approximate factorization algorithm (see Ref.\\ \\cite{jcp:2011:parent}). Thus, the convergence procedure consists of performing one iteration in pseudotime of the charged species transport equations keeping the potential constant, followed by one or more iterations  in pseudotime of the potential keeping the charged species densities constant. Such a procedure is repeated until the residual of the potential and of all species transport equations is reduced sufficiently. Through trial and error, it is found that specifying the pseudotime step as follows for the potential equation yields optimal convergence rates:\n%\n\\begin{equation}\n\\Delta \\tau_\\phi = \\left\\{ \n\\begin{array}{ll}\n\\mfd L_{\\rm c}\\cdot \\raisebox{-1.5ex}{$\\stackrel{\\stackrel{\\scriptstyle 3}{\\textstyle \\rm min}}{\\scriptstyle i=1}$} \\left(\\frac{\\Delta x_i}{\\sigma_{\\rm ref}+\\sigma}\\right) & \\textrm{for the potential equation based on Ohm's law} \\alb\n\\mfd L_{\\rm c}\\cdot \\raisebox{-1.5ex}{$\\stackrel{\\stackrel{\\scriptstyle 3}{\\textstyle \\rm min}}{\\scriptstyle i=1}$} \\left({\\Delta x_i}\\right) & \\textrm{for the potential equation  based on Gauss's law} \\alb\n\\end{array}\n\\right.\n\\end{equation}\n%\nAs well, either for the proposed or conventional charged species transport equations, the pseudotime step is set to the same value for all nodes and equal to the highest value that satisfies the following condition on all inner nodes: \n%\n\\begin{equation}\n\\Delta \\tau_N \\le {\\rm CFL}\\cdot \\raisebox{-1.5ex}{$\\stackrel{\\stackrel{\\scriptstyle 3}{\\textstyle \\rm min}}{\\scriptstyle i=1}$} \\left(\\mfd\\frac{\\Delta x_i}{a_{\\rm ref}+\\mu_{\\rm e} \\left|\\vec{E}_i-\\vec{E}^\\prime_i\\right|}\\right)~~~~\\textrm{for all inner nodes}\n\\end{equation}\n%\nwhere $\\Delta x_i$ is the grid spacing in the $i$th dimension, $L_{\\rm c}$ is a characteristic length that varies depending on the problem solved, $a_{\\rm ref}$ and $\\sigma_{\\rm ref}$ are some reference sound speed and conductivity typically set to 300~m/s and 0.003~S/m, and CFL is a user-defined parameter that is set to some low value (close to 1) in the initial stages of convergence and then progressively increased. How the parameters affecting the local pseudotime step are varied will be outlined in more detail for each test case.\n\n\n\n\\section{Test Cases}\n\nThe test cases considered herein consist of simulating electron-beamed ionized air plasmas enclosed by dielectrics and electrodes. Unless otherwise stated, the air plasma includes 6 components ($\\rm N_2$, $\\rm O_2$, $\\rm e^-$, $\\rm N_2^+$, $\\rm O_2^+$, and $\\rm O_2^-$) with the reaction rates  as well as the mobilities for each charged species being taken from Ref.\\ \\cite{jcp:2014:parent}. The plasma chemical reactions include Townsend ionization, electron-beam ionization, ion-ion recombination, electron attachment as well as dissociative recombination. For simplicity and to avoid the handling of the O and N species, we rewrite the dissociative recombination reaction for oxygen $\\rm e^- + O_2^+ \\rightarrow O+O$ to $\\rm e^- + O_2^+ \\rightarrow O_2$ and similarly for nitrogen. As can be demonstrated starting from the energy transport equation for each charged species, the electric field appearing within the expressions for the mobilities and within the Townsend ionization rates must be substituted by the \\emph{effective electric field} in the respective species reference frame, i.e.\\ $|\\vec{E}+\\vec{V}^k \\times \\vec{B}|$. A justification for doing so as well as details on how to obtain the effective electric field through an iterative process are given in Appendix A. The characteristic length scale needed to converge the potential equation is varied cyclically for all cases as  $L_{\\rm c}=0.0003,~0.003,~0.03,~0.0003~{\\rm m},...$, while the CFL number and the number of potential subiterations  are outlined below on a case by case basis.  \n\n\n\n%\n\\begin{table*}\n  \\center\n  \\begin{threeparttable}\n    \\tablecaption{Relative error assessment in solving the multicomponent plasma test case (with quasi-neutral region).\\tnote{a,b}}\n    \\label{tab:case6-error}\n    \\fontsizetable\n    \\begin{tabular*}{\\textwidth}{l@{\\extracolsep{\\fill}}llllcllll}\n    \\toprule\n     ~       & \\multicolumn{9}{c}{Average relative error }\\\\\n\\cmidrule{2-10}\n     ~                         & \\multicolumn{4}{c}{$\\mfd\\frac{1}{S N_{\\rm ref}}\\int_{0}^{S}{\\left|N_{\\rm e}-\\left(N_{\\rm e}\\right)_{\\rm exact}\\right|}~{\\rm d}S$}  &~& \\multicolumn{4}{c}{$\\mfd\\frac{1}{S \\phi_{\\rm ref}}\\int_{0}^{S}{\\left|\\phi-\\phi_{\\rm exact}\\right|}~{\\rm d}S$} \\\\\n\\cmidrule{2-5}\\cmidrule{7-10}\n     Governing equations                         & $44^2$\\,nodes   &  $87^2$\\,nodes  & $173^2$\\,nodes & $345^2$\\,nodes &~& $44^2$\\,nodes & $87^2$\\,nodes & $173^2$\\,nodes & $345^2$\\,nodes \\\\\n    \\midrule \n     Proposed                  & 0.180    &  0.0730     & 0.0250   & 0.0071 &~&  0.205  & 0.0785    & 0.0148  & 0.0047\\\\\n     Conventional              & 0.201    &  0.0811     & 0.0287   & 0.0081 &~&  0.830   & 0.326    & 0.120  & 0.041 \\\\             \n    \\bottomrule\n    \\end{tabular*}\n \\begin{tablenotes}\n   \\item[a] The ``exact solution'' is computed with the proposed governing equations and a mesh of $689^2$ nodes\n   \\item[b] The domain surface area $S$ is set to 9~mm$^2$ while the reference density $N_{\\rm ref}$ and reference potential $\\phi_{\\rm ref}$ are given values of $10^{17}$/m$^3$ and 10~V respectively.\n \\end{tablenotes}\n   \\end{threeparttable}\n\\end{table*}\n%\n\nBeing less stiff and offering significantly faster convergence are not the only advantages that the proposed equations offer. The present approach is further  advantaged by offering a higher resolution of the converged solution within quasi-neutral regions. This becomes apparent when evaluating the relative error on the potential on several meshes, as is done in Table \\ref{tab:case6-error}: for a given mesh size, the error on the potential is typically reduced fourfold when using the proposed equations. Differently put, the present approach can achieve the same accuracy on the potential with a mesh size being 4 times smaller, which would result approximately in a eightfold decrease in computational effort  (the computing time is proportional to the mesh size times the number of iterations, with the number of iterations typically increasing with the square root of the mesh size in 2D). The relatively low resolution of the solution when using the conventional equations is attributed to the potential equation based on Gauss's law being strongly function of the net charge density, which is itself highly sensitive to small errors of the electron and ion densities in regions of quasi-neutrality. This leads to an amplification of the numerical error when computing the potential and a somewhat low resolution of the converged solution. Because the potential equation based on the generalized Ohm's law is not strongly dependent on the net charge density, the proposed equations are not subject to such an error amplification and lead to a solution that is more accurate for a given mesh size. \n\nWhen simulating a non-neutral plasma in which the electrons are magnetized and in which there is a quasi-neutral region of significant size, it is here seen that the proposed equation set is not only considerably less stiff than the conventional set but also exhibits a higher resolution of the converged solution. Combined together, these lead to a considerable two-hundredfold decrease in computing effort for a desired level of accuracy. \n\n\n\n\n\n\\subsection{Gas Discharge}\n\n%\n\\begin{figure}[!b]\n   \\fontsizefigure\n   \\center\n   \\includegraphics[width=3.5\\lengthfigure]{setup_discharge.pdf}\n   \\caption{Gas discharge test case; all dimensions in millimeters.}\n\\label{fig:setup_discharge}\n\\end{figure}\n%\n\nThe third test case here investigated consists of a gas discharge between two electrodes with a voltage difference of 800 Volts and with the boundary conditions and problem setup schematized in Fig.\\ \\ref{fig:setup_discharge}. The magnetic field is fixed to 0.8~Tesla and is perpendicular to the computational plane. This results in a significant magnetic field effect on the flow properties due to the electron Hall parameter being of $0.5$. Because such a test case requires a very high number of iterations to converge when using the conventional equations, and because solving a 6-component plasma chemical model requires significantly more computing effort than a 3-component model, it is here decided to reduce the complexity of the chemical model by solving a reduced set of reactions involving only 3 species. The air plasma here considered is thus composed of one type of positive air ions, one type of air neutral molecules, and electrons, with the chemical reactions and mobilities taken from Ref.\\ \\cite{jcp:2014:parent}. The voltage difference is sufficient for Townsend ionization to occur near the cathode, and the electron-beam power deposited is sufficiently high for a quasi-neutral region to form near the anode. Such a test case is hence well suited to test the performance of the proposed equations in simulating non-neutral cathode sheaths in the presence of a magnetic field typical of plasma magneto-aerodynamics.   \n\n\n\n\n\\section{Conclusions}\n\n\nA new set of equations is here presented to simulate weakly-ionized plasmas in magnetic field using the drift-diffusion fluid model. The proposed set of equations consists of obtaining the potential from the generalized Ohm's law rather than from Gauss's law as is the case in the conventional set of equations. To ensure that Gauss's law is satisfied in non-neutral regions some source terms are added to the ion transport equations. Because the proposed equations are obtained from the same physical model as the conventional equations without introducing new simplifications, they yield the same exact solution either in non-neutral or in quasi-neutral plasma regions (including sheaths near the surfaces as well as regions with significant ambipolar diffusion and drift). \n\nThe present equation set is nonetheless advantaged over the conventional set by not being subject to high stiffness when the plasma includes one or more zones of quasi-neutrality. Reducing the stiffness of the system permits larger integration steplengths to be used which leads to a significant decrease in the number of iterations to reach convergence. Several test cases reveal that the integration steplength can be increased by 20 times or more leading typically to a thirtyfold decrease in  the iteration count whenever a quasi-neutral region of substantial size forms within the plasma. Such gains in convergence acceleration are observed to be independent of the size of the mesh, of the current magnitude, or of the strength of the magnetic and  electric fields.  \n\nAnother advantage of the proposed equations is in yielding a higher resolution of the converged solution within (or in the vicinity of) quasi-neutral regions when the externally-applied magnetic field is significant. Indeed, several grid convergence studies of plasmas  with large quasi-neutral regions show that the electric field potential is subject to excessive error when obtained from a potential equation based on Gauss's law. This is attributed to the latter amplifying the error associated with the charged species densities when the net charge tends towards zero. Such an error amplification is avoided when obtaining the potential from the generalized Ohm's law because the latter is not strongly dependent on the net charge density, which leads to the conventional set of equations typically requiring 5 times more nodes to yield the same accuracy as the proposed set within or nearby quasi-neutral regions.    \n\nNot only is the present set of equations advantaged by being less stiff and hence exhibiting faster convergence, but it also results in a more accurate solution on a given mesh. When combined together, these gains in resolution and convergence acceleration result in a one-hundredfold or more increase in computational efficiency for typical steady and unsteady problems involving a quasi-neutral region of substantial size. On the other hand, should the plasma be entirely non-neutral and not include zones  of quasi-neutrality, the proposed equations are observed to converge as rapidly and to exhibit as high a resolution as the conventional set. Because the proposed governing equations yield significant computational advantages with no associated drawback, they are  unconditionally recommended to simulate numerically through the drift-diffusion model weakly-ionized plasmas in the presence of magnetic field.   \n\n\n\n\n\\section*{Acknowledgment}\n\nThis research was supported by a 2-year Pusan National University Research Grant. \n\n%% The Appendices part is started with the command \\appendix;\n%% appendix sections are then done as normal sections\n% \\appendix\n\n\n\n\\appendix\n\n\n\n\n\n\n\n\n\n\\section{Effective Electric Field in Species Reference Frame}\n\\label{AppendixA}\n\n\nA justification is here given to why the effective electric field must be determined in the electron reference frame rather than in the neutrals reference frame when computing the electron mobility and the Townsend ionization rates. \n\nLet us start from the electron energy transport equation as taken from Ref.\\ \\cite[page 34]{book:1991:raizer}:\n%\n\\begin{equation}\n  \\frac{\\partial }{\\partial t} \\left( \\frac{3}{2} N_{\\rm e} k_{\\rm B} T_{\\rm e} \\right)\n  + \\sum_{i=1}^\\nd \\frac{\\partial }{\\partial x_i} \\left(\\frac{5}{2}  N_{\\rm e} k_{\\rm B} T_{\\rm e} \\vec{V}_i^{\\rm e} \\right)\n  - \\sum_{i=1}^\\nd \\frac{\\partial }{\\partial x_i} \\kappa_{\\rm e} \\frac{\\partial T_{\\rm e}}{\\partial x_i}\n  =\n   \\vec{F}^{\\rm e}\\cdot \\vec{V}^{\\rm e}\n - \\frac{3}{2} N_{\\rm e} k_{\\rm B} T_{\\rm e} \\zeta_{\\rm e} \\nu_{\\rm m} - Q_{\\rm ei}  \n \\end{equation}\n%\nwhere $Q_{\\rm ei}$ represents the amount of energy the electrons lose in creating new electrons through Townsend\nionization (that is, the product between the ionization potential and the number of electrons per unit volume per unit time created by electron-impact processes), $\\kappa_{\\rm e}$ is the thermal diffusivity, $\\nu_{\\rm m}$ the collision frequency, $\\vec{F}^{\\rm e}$ is the force per unit volume acting on the electrons due to electromagnetic fields in the electron reference frame, and $\\zeta_{\\rm e}$ is a term function of the effective electric field which can be determined similarly as in Ref.\\ \\cite{misc:1995:boeuf}.\n\n\n\nConsider the energy transport equation in the ``local approximation'' and neglect the unsteady, convective, and diffusive terms. Then, noting that the collision frequency can be written as follows:\n%\n\\begin{equation}\n\\nu_{\\rm m}=\\frac{e}{m_{\\rm e}\\mu_{\\rm e}}\n\\end{equation}\n%\nwe obtain the following expression for the electron temperature:\n%\n\\begin{equation}\n  T_{\\rm e}  \n=  \n \\frac{2 m_{\\rm e} \\mu_{\\rm e}}{3 e N_{\\rm e} k_{\\rm B} \\zeta_{\\rm e} }\n\\left(  \\vec{F}^{\\rm e}\\cdot \\vec{V}^{\\rm e}\n - Q_{\\rm ei}\\right)\n\\label{eqn:appendix:Te}\n \\end{equation}\n%\nwhere the force per unit volume acting on the electrons in the electron reference frame due to electromagnetic fields  corresponds to:\n%\n\\begin{equation}\n\\vec{F}^{\\rm e} = -eN_{\\rm e}\\left(\\vec{E} + \\vec{V}^{\\rm e} \\times \\vec{B}\\right)\n\\label{eqn:appendix:Fe}\n\\end{equation}\n%\nand where, in the ``local approximation'',  the electron velocity can be taken from Eq.\\ (\\ref{eqn:Vvector}) neglecting the pressure gradients:\n%\n\\begin{equation}\n  \\vec{V}^{\\rm e}=\\vec{V}^{\\rm n} - \\mu_{\\rm e} \\left(\\vec{E}+\\vec{V}^{\\rm e} \\times \\vec{B}\\right)\n\\label{eqn:appendix:Ve}\n\\end{equation}\n% \nSubstitute Eq.\\ (\\ref{eqn:appendix:Ve}) and Eq.\\ (\\ref{eqn:appendix:Fe}) in Eq.\\ (\\ref{eqn:appendix:Te}):\n%\n\\begin{equation}\n  T_{\\rm e}  \n=  \n \\frac{2 m_{\\rm e} \\mu_{\\rm e}}{3 e N_{\\rm e} k_{\\rm B} \\zeta_{\\rm e} }\n\\left( -e N_{\\rm e} \\left(\\vec{E} + \\vec{V}^{\\rm e} \\times \\vec{B}\\right)\\cdot \\left(\\vec{V}^{\\rm n} - \\mu_{\\rm e} \\left(\\vec{E}+\\vec{V}^{\\rm e} \\times \\vec{B}\\right)\\right)\n - Q_{\\rm ei}\\right)\n \\end{equation}\n%\nBecause the magnitude of the neutrals velocity can be assumed small compared to the magnitude of the electron velocity, the electron temperature becomes:\n%\n\\begin{equation}\n  T_{\\rm e}  \n=  \n \\frac{2 m_{\\rm e} \\mu_{\\rm e}}{3 e N_{\\rm e} k_{\\rm B} \\zeta_{\\rm e} }\n\\left(  N_{\\rm e} \\mu_{\\rm e} e |\\vec{E}+\\vec{V}^{\\rm e}\\times \\vec{B}|^2\n - Q_{\\rm ei}\\right)\n \\end{equation}\n%\nFrom the latter, it is clear that in the local approximation the electron temperature is a function of the electric field in the electron reference frame $|\\vec{E}+\\vec{V}^{\\rm e}\\times \\vec{B}|$, not of the electric field in the laboratory frame $|\\vec{E}|$. Because the electron mobility and the Townsend ionization rates depend on the electron temperature, and because the electron temperature is a function of the electric field in the electron reference frame, it follows that the electron mobility and Townsend ionization rates should be determined from an effective electron electric field as follows: \n%\n\\begin{equation}\n E_{\\rm eff}^{\\rm e}=|\\vec{E}^{\\rm e}|=|\\vec{E}+\\vec{V}^{\\rm e}\\times\\vec{B}| \n\\label{eqn:Ee_refframe}\n\\end{equation}\n%\nwhere the electron velocity $\\vec{V}^{\\rm e}$ can be obtained from Eq.\\ (\\ref{eqn:V}):\n%\n\\begin{equation}\n  \\vec{V}^{\\rm e}_i = \\vec{V}^{\\rm n}_i+\\sum_{j=1}^\\nd s_{\\rm e} \\wtilde{\\mu}^{\\rm e}_{ij}  \\vec{E}_j^{\\rm n}\n             - \\sum_{j=1}^\\nd  \\frac{\\wtilde{\\mu}^{\\rm e}_{ij}}{|C_{\\rm e}| N_{\\rm e}} \\frac{\\partial P_{\\rm e}}{\\partial x_j}\n\\label{eqn:Ve_refframe}\n\\end{equation}\n%\nThus, to find $E_{\\rm eff}^{\\rm e}$, proceed iteratively: (i) Find $\\vec{V}^{\\rm e}$ from Eq.\\ (\\ref{eqn:Ve_refframe}), (ii) Find $E_{\\rm eff}^{\\rm e}=|\\vec{E}^{\\rm e}|$ from Eq.\\ (\\ref{eqn:Ee_refframe}), and (iii) update $\\wtilde{\\mu}^{\\rm e}$ using the latest value of $E_{\\rm eff}^{\\rm e}$ found in step (ii). Repeat steps (i)-(iii) until $E_{\\rm eff}^{\\rm e}$ is converged. It is sometimes necessary to under-relax the update of the effective electric field $E_{\\rm eff}^{\\rm e}$ in the above iterative process in order to prevent some convergence hang, with the relaxation factor typically given a value of 0.9.   \n\nSimilarly, it can be demonstrated that the effective electric field  $E_{\\rm eff}^k$ needed for the ion mobilities  must also be determined in the reference frame of the charged species under consideration (i.e. $E_{\\rm eff}^k=|\\vec{E}^k|=|\\vec{E}+\\vec{V}^k\\times \\vec{B}|$). The electric field in the ion frame of reference can be obtained for each ion species through the use of Eq.\\ (\\ref{eqn:V}) by following a similar iterative process as  outlined above. \n \n\n\n\n\n\n\n\n\\bibliographystyle{waflarticle}\n\\bibliography{all}\n\n\\end{document}\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "a995cb540173ad13e719d2e6a9125ead2aeb4bc5", "size": 66630, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "waflarticle/article.tex", "max_stars_repo_name": "bernardparent/TEXSTYLE", "max_stars_repo_head_hexsha": "a38615797ff779d8779ccc4cd17f441abd50c463", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-06-24T04:30:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-10T07:17:32.000Z", "max_issues_repo_path": "waflarticle/article.tex", "max_issues_repo_name": "bernardparent/TEXSTYLE", "max_issues_repo_head_hexsha": "a38615797ff779d8779ccc4cd17f441abd50c463", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "waflarticle/article.tex", "max_forks_repo_name": "bernardparent/TEXSTYLE", "max_forks_repo_head_hexsha": "a38615797ff779d8779ccc4cd17f441abd50c463", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-06-10T07:17:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T01:06:13.000Z", "avg_line_length": 76.7626728111, "max_line_length": 1663, "alphanum_fraction": 0.7351943569, "num_tokens": 19412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.32115984026667804}}
{"text": "%\n% %CopyrightBegin%\n%\n% Copyright Ericsson AB 2017. All Rights Reserved.\n%\n% Licensed under the Apache License, Version 2.0 (the \"License\");\n% you may not use this file except in compliance with the License.\n% You may obtain a copy of the License at\n%\n%     http://www.apache.org/licenses/LICENSE-2.0\n%\n% Unless required by applicable law or agreed to in writing, software\n% distributed under the License is distributed on an \"AS IS\" BASIS,\n% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n% See the License for the specific language governing permissions and\n% limitations under the License.\n%\n% %CopyrightEnd%\n%\n\n\\chapter{Portable hashing}\n\n\\label{chapter:hashing}\n\\index{term!hashing|(}\n\\index{erlang:hash/2 BIF@\\T{erlang:hash/2} BIF|(}\n\\index{hash/2 BIF@\\T{hash/2} BIF|(}\n\nThe function \\I{Hash} defined in this appendix is used as part of the\ndefinition of the BIF \\T{erlang:hash/2} (\\S\\ref{section:hash2}).\nGiven an arbitrary \\Erlang\\ term and a positive integer $r$, it returns\nan integer in the range $[0,r-1]$.  The function has been designed with\nthe aim to make it a good hash function, i.e., that it spreads function\nvalues evenly across the range.\n\\index{erlang:hash/2 BIF@\\T{erlang:hash/2} BIF|)}\n\\index{hash/2 BIF@\\T{hash/2} BIF|)}\n\n\\section{Definitions}\n\n%\\index{C1, ..., C9@$C_1$, \\ldots, $C_9$|(}\nWe make use of nine constants $C_1$, \\ldots, $C_9$:\n\\begin{align*}\nC_1 &= 268440163 \\\\\nC_2 &= 268439161 \\\\\nC_3 &= 268435459 \\\\\nC_4 &= 268436141 \\\\\nC_5 &= 268438633 \\\\\nC_6 &= 268437017 \\\\\nC_7 &= 268438039 \\\\\nC_8 &= 268437511 \\\\\nC_9 &= 268439627\n\\end{align*}\n%\\index{C1, ..., C9@$C_1$, \\ldots, $C_9$|)}\n%\\index{Foldl@\\I{Foldl}|(}\nWe will use a helper function \\I{Foldl}, such that\n\\[\\I{Foldl}(F,E,\\langle v_1,\\ldots,v_k\\rangle) =\nF(v_k,F(v_{k-1},\\ldots F(v_2,F(v_1,E)) \\ldots))\\]\n(Note that $\\I{Foldl}(F,E,\\langle\\rangle) = E$, regardless of $F$.)\n%\\index{Foldl@\\I{Foldl}|)}\n\n\\noindent\\index{  bitwise exclusive OR@$\\otimes$}\n$w_1 \\otimes w_2$ denotes the bitwise exclusive OR of $w_1$ and $w_2$.\n\n\\noindent All arithmetic operations in this appendix are modulo $2^{32}$.\n\n\\section{The hash function}\n\n%\\index{Hash@\\I{Hash}|(}\nThe main function \\I{Hash} is defined as follows:\n\\[\\I{Hash}(\\TZ{t},r) = H(\\TZ{t},0) \\bmod r\\]\n%\\index{Hash@\\I{Hash}|)}\nThe auxiliary function $H$ is defined by cases.\n\\begin{itemize}\n\\item If \\TZ{t} is an atom having a printname with character codes $i_1$, ..., $i_k$,\nwhere for all $j$, $1\\leq j\\leq k$, $i_j\\in[0,255]$, then\n\\[H(\\TZ{t},h) = C_1*h+\\I{Foldl}(F,0,\\langle i_1,\\ldots,i_k\\rangle),\\]\nwhere\n\\begin{align*}\nF(i,h) &= G(16h + i) \\\\\nG(j) &= (j \\bmod 2^{28}) \\otimes 16(\\lfloor j / 2^{28}\\rfloor).\n\\end{align*}\n(Note that for any application of $F$, $i\\in[0,255]$ and $h\\in[0,2^{28}-1]$,\nand for any application of $G$, $j\\in[0,2^{28}-1]$.)\n\\item If \\TZ{t} is a fixnum, then\n\\[H(\\TZ{t},h) = C_2*h+(\\Er[t] \\bmod 2^{32}).\\]\nI'M NOT SURE I GOT THIS RIGHT AND I'D RATHER NOT MENTION FIXNUMS AND BIGNUMS!!!\n\\item If \\TZ{t} is a bignum where the 32-bit words of its absolute value\nin little-endian order is $w_1$, ..., $w_k$, then\n\\[H(\\TZ{t},h) = C*\\I{Foldl}(F,h,\\langle w_1,\\ldots,w_k\\rangle)+k,\\]\nwhere\n\\begin{alignat*}{2}\n     C &= C_2 && \\qquad\\text{if $\\Er[t]\\geq0$;} \\\\\n       &= C_3 && \\qquad\\text{if $\\Er[t]<0$.} \\displaybreak[0]\\\\[\\smallskipamount]\nF(w,h) &= C_2*h+w\n\\end{alignat*}\n\\item If \\TZ{t} is \\T{[]}, then\n\\[H(\\TZ{t},h) = C_3*h+1.\\]\n\\item If \\TZ{t} is a binary consisting of the bytes $i_1$, \\ldots, $i_k$, then\n\\[H(\\TZ{t},h) = C_4*\\I{Foldl}(F,h,\\langle i_1,\\ldots,i_l\\rangle)+k,\\]\nwhere\n\\begin{align*}\nl &= \\min(k,15) \\\\\nF(i,h) = C_1*h+i.\n\\end{align*}\n\\item If \\TZ{t} is a PID, then\n\\[H(\\TZ{t},h) = C_5*h+\\I{MagicPid}(\\TZ{t}).\\]\n\\item If \\TZ{t} is a port or a ref, then\n\\[H(\\TZ{t},h) = C_9*h+\\I{MagicPortRef}(\\TZ{t}).\\]\n\\item If \\TZ{t} is a float represented by the two unsigned 32-bit quantities\n$w_1$ and $w_2$, then (THIS IS NOT VERY PORTABLE!!!)\n\\[H(\\TZ{t},h) = C_6*h+(w_1 \\otimes w_2).\\]\n\\item If \\TZ{t} is a term \\T{[$\\Z{t}_1$,\\tdots,$\\Z{t}_k$|$\\Z{t}_{k+1}$]}, then\n\\[H(\\TZ{t},h) = C_8*H(\\TZ{t}_{k+1},\\I{Foldl}(H,h,\\langle t_1,\\ldots,t_k\\rangle)).\\]\n\\item If \\TZ{t} is a tuple \\T{\\{$\\Z{t}_1$,\\tdots,$\\Z{t}_k$\\}}, then\n\\[H(\\TZ{t},h) = C_9*\\I{Foldl}(H,h,\\langle t_1,\\ldots,t_k\\rangle)+k.\\]\n\\end{itemize}\n\\index{term!hashing|)}\n", "meta": {"hexsha": "8b276f917932d6ada4329ff5ea7402fa4f78fffe", "size": 4318, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/es-hashing.tex", "max_stars_repo_name": "LaudateCorpus1/spec", "max_stars_repo_head_hexsha": "0d70db4d904c45678cb46de8f0f0f93eb35c66f3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 44, "max_stars_repo_stars_event_min_datetime": "2017-11-30T12:10:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T16:15:05.000Z", "max_issues_repo_path": "src/es-hashing.tex", "max_issues_repo_name": "LaudateCorpus1/spec", "max_issues_repo_head_hexsha": "0d70db4d904c45678cb46de8f0f0f93eb35c66f3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2017-11-30T14:08:26.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-05T13:50:58.000Z", "max_forks_repo_path": "src/es-hashing.tex", "max_forks_repo_name": "LaudateCorpus1/spec", "max_forks_repo_head_hexsha": "0d70db4d904c45678cb46de8f0f0f93eb35c66f3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2017-11-30T12:07:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T06:37:00.000Z", "avg_line_length": 36.905982906, "max_line_length": 85, "alphanum_fraction": 0.6433534044, "num_tokens": 1710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.32115227821605596}}
{"text": "\\documentclass[main.tex]{subfiles}\n\n\\begin{document}\n\t\\section{Discussion}\n\tIn this thesis we set out to create a suite of programs to visualise key concept in the field of condensed matter physics. These concepts included crystal structures, families of lattice planes, a simulation of neutron scattering, along with band structures of two dimensional materials.\n\t\n\tThe end result is a code package written in Python which accomplishes just that. It includes 4 main functions: \\texttt{Lattice}, \\texttt{Reciprocal}, \\texttt{Scattering} and \\texttt{Band\\_structure}. These 4 functions take in a wealth of arguments, supplied by the user, and produce some sort of figure. Examples of these being the crystal structure of hexagonal lattice with a one atom basis (figure \\ref{fig:lattice_demo_2}), the (001) family of lattice planes for a bcc lattice (figure \\ref{fig:lattice_planes}), neutron scattering on an fcc lattice (figures \\ref{fig:scattering_no_systemic} and \\ref{fig:scattering_systemic}) or the band structure of a monovalent two dimensional material with a high strength potential (figure \\ref{fig:band_structure_strong}).\n\n\tMore can be done with these programs though, and they are by no means a comprehensive resource. For the lattice plotting program, there is currently no perfect algorithm to detect type of lattice that the user has input.\n\t\n\tThe algorithm employed to detect lattices relies on the user inputting primitive lattice vectors with the specifications from appendix \\ref{app:lattice}. These lattices can be rotated and scaled to the heart's desires, and the program will still detect them. But the algorithm does not take into account the non-uniqueness of primitive lattice vectors. \n\t\n\tThe \"easy\" way to take this into account would be to use the method specified in section \\ref{sec:lattice_theory}, calculating the matrix $ M $ for the different lattices and checking whether or not it meets the necessary criteria. However, this method cannot work if the user also rotates the lattice. Different magnitudes of input primitive lattice vectors will also complicate things, as the program would have to check a range of different sets of primitive lattice vectors for each lattice. For example, say the user inputs an fcc lattice with $ a_1 = a \\D(1,0,0) $, $ a_2 = a\\D(0, 1/2, 1/2) $ and $ a_3 = a\\D(1/2, 0, 1/2) $. There is currently no way for the program to \"know\" which magnitude to use for the primitive lattice vectors used for comparison, and the only recourse is to brute-force check all combinations.\n\n\tSo currently no catch-all solution of classification is implemented. A thing to note is that the current algorithms only depend on the primitive lattice vectors. A different approach may be to construct the full crystal and look for a specific \"type\" of unit cell, corresponding to one of the Bravais lattices. However, this will necessarily involve a more complicated algorithm, which unfortunately there was not time for.\n\t\n\tFurthermore, the program only calculates the relevant quantities for one specific set of values per function call. As such, if the user wants to see how systemic absences appear in scattering experiments, or how the Fermi surface distorts for stronger potentials, they will need to manually call the relevant function multiple times with different form factors or potential strength. This gets tedious after a while.\n\t\n\tA solution to this is to create some sort of GUI which will display input boxes or sliders for the relevant quantities, automatically call the functions and display the results. This can be done, for example with the python package \\href{http://flask.pocoo.org/}{Flask}, which allows the creation of web-applications. These can be run locally on the users machine and allows for javascript integration. This is especially useful (necessary, even!) for accomplishing the goal of added interactivity, as Matplotlib figures can be rendered as javascript objects.\n\t\n\tWith regards to distortion of the Fermi surface: The next (small) step would be to maybe include different two dimensional lattices. A rectangular lattice would be as simple as altering a value or two in the code, for example. But perhaps a better change would be to bump up the dimensions of the lattices to three. Doing this, however, means we run into problems with the number of available dimensions. It seems we live in a universe with only three spatial dimensions, which means we will use up all of those just specifying the geometry of the lattice, leaving no dimension for any other quantities of interest - like the dispersion relation of the particles in the crystal.\n\t\n\tThis limits us to only looking at isosurfaces of energy - like the Fermi surface, where we in two dimensions could view the entire Fermi sea (and the rest of the dispersion relation). While this would be  enough to view the distortion of the Fermi surface (especially if combined with a web-app as specified above), there is the added issue of the computational time required. Currently, for a two dimensional lattice, with $ n_k $ values of $ \\V{k} $ in each direction, and $ n_G $ allowed values of $ \\V{G} $ (again in each direction), necessitates finding the eigenvalues of $ n_k^2 $ matrices of size $ n_G^2 \\times n_G^2 $. By default these values og $ n_k $ and $ n_G $ are around 100 and 7 respectively, meaning the program diagonalises $ 10^4 $ $ 49\\times 49 $ matrices. Increasing the dimensionality would increase both the number of matrices to be diagonalised, and the size of these. We would increase the amount of matrices by a factor of $ n_k $, and the size of each of these would go from $ n_G^2 \\times n_G^2$ to $ n_G^3 \\times n_G^3 $. With the standard arguments this would necessitate the diagonalisation of $ 10^6 $ matrices of size $ 343 \\times 343 $. A very considerable increase.\n\t\n\tAs it currently stands the program does take a while to compute the band structure (around a second or so, for a decent resolution), and to get the same resolution in three dimensions would take at least a factor $ n_k \\approx 100 $ longer (assuming it takes the same amount of time to diagonalise a $ 49 \\times 49 $ matrix as it does a $ 343 \\times 343 $ matrix, which it most certainly does not). So if three dimensions are to be considered, the program would need to be thoroughly optimised. One way to do this would be to employ an algorithm to find just the lowest eigenvalue of these matrices, as we are only concerned with the lowest band - i.e. the Fermi surface. \n\t\n\tA line had to be drawn somewhere though, and a two dimensional lattice seemed like a reasonable compromise between added dimensionality and computational complexity.\n\t\n\tOne last issue is in regards to the programming language and packages chosen. Python is an interpreted language, which means that it necessarily trades computational speed for added ease of development. There are alternatives to this, like \\href{https://nim-lang.org/}{Nim} or \\href{https://julialang.org/}{Julia}, which are properly compiled or just-in-time compiled respectively. They do not, however, have as large a community as Python does, and therefore not as big a support for third-party packages like Matplotlib.\n\t\n\tFurther, Matplotlib has one glaring issue in that it does not support a fully fledged 3D graphics engine. This means that all the three dimensional figures in this thesis and the programs are actually just 2D projections of underlying 3D data (of course, computer screens are 2D, so the projection has to happen at some point, but the way Matplotlib does it has significant drawbacks). This creates artefacts like how there is no proper support for the intersection of surface plots. This can be seen in the band structure program, where the orange horizontal plane, indicating the Fermi energy, does not properly intersect the dispersion relation, seen in blue. \n\t\n\tThere are other packages, like \\href{https://docs.enthought.com/mayavi/mayavi/}{Mayavi} which do support proper 3D plotting. However, these problems (and their potential solution in this package) were discovered too late in the process of writing, so could not be solved in time.\n\t\n\tIn conclusion: 4 programs have been created which illustrate concepts in the field of condensed matter physics. While they are not without their flaws or potential for improvement, they do still hold merit, and could be a valuable tool if used in combination with traditional book-based learning.\n\t\n\\end{document}", "meta": {"hexsha": "353b09ceebc329efa8d9cbad21edf053f6956844", "size": 8475, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/discussion.tex", "max_stars_repo_name": "NikolaiNielsen/Bachelor", "max_stars_repo_head_hexsha": "e26f3cee6dcfc858b606b5d3112f553836dd3990", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-05-17T02:07:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-06T09:18:38.000Z", "max_issues_repo_path": "thesis/discussion.tex", "max_issues_repo_name": "NikolaiNielsen/Bachelor", "max_issues_repo_head_hexsha": "e26f3cee6dcfc858b606b5d3112f553836dd3990", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis/discussion.tex", "max_forks_repo_name": "NikolaiNielsen/Bachelor", "max_forks_repo_head_hexsha": "e26f3cee6dcfc858b606b5d3112f553836dd3990", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-07-19T05:12:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-24T08:32:13.000Z", "avg_line_length": 229.0540540541, "max_line_length": 1203, "alphanum_fraction": 0.7910324484, "num_tokens": 1864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.32100374815570765}}
{"text": "% !TEX TS-program = pdflatex\n% The line above tells TeXShop to use the latex -> dvi -> distiller \n% path to produce the pdf. \n\n\\documentclass[12pt]{article}\n\n\\usepackage{amsmath,amssymb,amsfonts}\n\\usepackage{courier,type1cm,array}\n\\usepackage{makeidx,graphicx,multicol}\n\\usepackage[bottom]{footmisc} % places footnotes at page bottom\n\\usepackage{natbib,float}\n\\usepackage[vmargin=1in,hmargin=1in]{geometry}\n\n\n% allows compilation with pdflatex, under Windows \n\\usepackage{epstopdf}\n\n% Coloring of R code listings\n\\usepackage[formats]{listings}\n\\usepackage{color}\n\\definecolor{mygreen}{rgb}{0.1,0.5,0.1}\n\\definecolor{mygray}{rgb}{0.5,0.5,0.5}\n\\definecolor{mymauve}{rgb}{0.58,0,0.82}\n\\definecolor{mygrey}{rgb}{0.3,0.3,0.1}\n\\lstset{\nlanguage=R,\notherkeywords={data.frame},\nbasicstyle=\\normalsize\\ttfamily, \ncommentstyle=\\normalsize\\ttfamily,\nkeywordstyle=\\normalsize\\ttfamily,\nstringstyle=\\color{mymauve}, \ncommentstyle=\\color{mygreen},\nkeywordstyle=\\color{blue},\nshowstringspaces=false, xleftmargin=2.5ex,\ncolumns=flexible,\nliterate={~}{{$\\sim \\; \\; $}}1,\nalsodigit={\\.,\\_},\ndeletekeywords={on,by,data,R,Q,mean,var,sd,log,family,na,options,q,weights,effects,matrix,nrow,ncol,wt,fix,distance},\n}\n\\lstset{escapeinside={(*}{*)}} \n\n\\lstdefineformat{Rpretty}{\n\t; = \\space,\n\t\\, = [\\ \\,\\]]\\string\\space,\n\t<- = [\\ ]\\space\\string\\space,\n\t\\= = [\\ ]\\space\\string\\space}\n\n\\usepackage[compact]{titlesec} \n\\usepackage{enumitem}\n\\setlist{leftmargin=0.75cm}\n\n\\usepackage{array}\n\\newcolumntype{L}[1]{>{\\raggedright\\let\\newline\\\\\\arraybackslash\\hspace{0pt}}m{#1}}\n\\newcolumntype{C}[1]{>{\\centering\\let\\newline\\\\\\arraybackslash\\hspace{0pt}}m{#1}}\n\\newcolumntype{R}[1]{>{\\raggedleft\\let\\newline\\\\\\arraybackslash\\hspace{0pt}}m{#1}}\n\n% reduce white space above and below verbatim text blocks\n\\usepackage{etoolbox}\n\\makeatletter\n\\preto{\\@verbatim}{\\topsep=0.5pt \\partopsep=0.5pt }\n\\makeatother\n\n% let figs,boxes etc. occupy most of a page near where they\n% appear in the source file, instead of getting pushed to\n% the chapter's end. \n\\renewcommand{\\topfraction}{0.9}\t\n\\renewcommand{\\bottomfraction}{0.9}\t\n\\renewcommand{\\textfraction}{0.07}\t\n\\renewcommand{\\floatpagefraction}{0.85}\t\n% floatpagefraction MUST be less than topfraction\n\\setcounter{topnumber}{2}\n\\setcounter{bottomnumber}{2}\n\\setcounter{totalnumber}{4} \t\n\n% Define Box environment for numbered boxes. \n\\newcounter{box}\n\\newcommand{\\boxnumber}{\\addtocounter{box}{1} \\thebox \\thinspace}\n\n\\floatstyle{boxed}\n\\newfloat{Box}{tcph}{box}[section]\n\\numberwithin{Box}{section}\n\n% A few shortcuts\n% Define \\z so that \\z_0 and z'_0 have the same kerning for _0. \n\\def\\z{z^{}}\n\\def\\Z{\\mathbf{Z}}\n\\def\\N{\\mathbf{N}}\n\n\\newcommand{\\be}{\\begin{equation}}\n\\newcommand{\\ee}{\\end{equation}}\n\\newcommand{\\ba}{\\begin{equation} \\begin{aligned}}\n\\newcommand{\\ea}{\\end{aligned} \\end{equation}}\n\n\\makeindex\n\n\\usepackage[scaled=0.9]{zi4}\n\\usepackage{textcomp}\n\n\n\\linespread{1.2}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%% End of the preamble \n \n\\begin{document}\n\n\\author{Stephen P. Ellner, Dylan Z. Childs and Mark Rees}\n\\title{Errata for \\\\ \\emph{Data-driven Modeling of Structured Populations: \nA Practical Guide to the Integral Projection Model}} \n\n\\date{Last update: \\today} \n\n\\maketitle\n\n\\paragraph{Page 12:} We think that the statement about ``piecewise continuous'' in the footnote is true, \nbut at least one proof in the book isn't valid regardless of what the curves are that divide $\\Z^2$ into \nsubregions. A slightly less general definition, which should be sufficient for any applications, is as follows. \nFor the basic model where the individual-level state space $\\Z$ is a \nbounded interval $[L,U]$, a partition of $\\Z$ is a set of \nintervals \n\\begin{equation}\n\\Z_1 = (z_0,z_1), \\Z_2 = (z_1,z_2), \\cdots, \\Z_m = (z_{m-1},z_m) \n\\end{equation}\nwhere \n\\be\nL=z_0 < z_1 < z_2 < \\cdots < z_M=U. \n\\ee\nA partition breaks $\\Z^2$ into a set of open rectangles \n$$\\Z_{ij} = \\Z_i \\times \\Z_j = \\{(z',z): z' \\in \\Z_i, z \\in \\Z_j\\}.$$\nDefine the kernels $K_{ij}$ to be $K$ restricted to $\\Z_{ij}$. \n\nWe say that $K$ is \\emph{piecewise continuous} if there exists a \npartition such that each of the kernels $K_{ij}$ is continuous on $\\Z_{ij}$, \nand can be defined on the boundary of $\\Z_{ij}$ so that it is continuous\non the closed rectangle $\\bar{\\Z}_{ij}$ consisting of $\\Z_{ij}$ and its boundary.  \n\nThe reason this definition works is the general theory in section 6.9\n(originally in the Appendices to Ellner \\& Rees 2006), applied to the  \nclosed intervals $\\bar{\\Z}_{i} =  [z_0,z_1]$ as a set of continuous components, \nwith continuous component-to-component kernels $K_{ij}$. In terms of the general     \ntheory, this is an IPM with continuous kernels. Formally, there is a separate state distribution \nfunction $n_i(z,t)$ defined on each $\\bar{\\Z}_i$. But we can also think of there being a \nsingle distribution function $n(z,t)$ on all of $[L,U]$, consisting of $n_1,n_2, \\cdots n_M$ \nside-by-side. \n\nEach of the boundary points $z_i$ is in two adjacent components, but this doesn't matter because  \nsingle points contribute nothing to the subsequent population. \nAs an example consider  $\\Z = [0,2]$ and the (contrived) kernel $K(z',z) = 1$ \nif $z'>1$, and 0 otherwise. The partition is $\\Z_1 = (0,1), \\Z_2 = (1,2)$ and the kernels are \n\\be\nK_{11}=K_{12}\\equiv 0, K_{21}=K_{22}\\equiv 1.\n\\ee\nThe population dynamics are \n\\ba\nn_1(z',t+1) & = \\int_0^1 K_{11}(z',z) n_1(z,t) dz + \\int_1^2 K_{12}(z',z) n_2(z,t) dz  = 0 \\\\\nn_2(z',t+1) & = \\int_0^1 K_{21}(z',z) n_1(z,t) dz + \\int_1^2 K_{22}(z',z) n_2(z,t) dz  \\\\\n& =  \\int_0^1 n_1(z,t) dz + \\int_1^2 n_2(z,t) dz.  \n\\label{eqn:badK1}\n\\ea\nSo $n_1(1,t+1)=0$, while $n_2(1,t+1)>0$ unless there were no individuals at time $t$. \nHowever, the values of $n_1$ and $n_2$ at the one point $z=1$ have no effect on the\nintegrals in the population dynamics, so we can regard $n(1,t+1)$ as being undefined,\nor give it an arbitrary value such the average $n_1(1,t+1)$ and $n_2(1,t+1)$. \n\nThe contrived kernel \\eqref{eqn:badK1} is a counter-example to the claim in section 6.9 of the book \nthat a piecewise continuous kernel, as defined in that section, maps $L_1(\\Z)$ into $C(\\Z)$. \nThe gap in the proof is the assertion that the functions $f_n$ converge almost everywhere, \nwhich is not necessarily true regardless of how the partitioning into sets $\\mathcal{U}_k$ is done. But on the \nset of domains $\\bar{\\Z}_{i}$ the component kernels are all continuous and the $f_n$ converge \npointwise, which is sufficient for the rest of the proof. \nIn example \\eqref{eqn:badK1}, $n_1$ is continuous on $\\bar{\\Z}_1$ and \n$n_2$ is continuous on $\\bar{\\Z}_2$, and that is exactly what it means to be continuous\non the state space with domains $\\bar{\\Z}_1$ and $\\bar{\\Z}_2$.  \n\nPlease see the related correction below about \\textbf{Page 181}. \n\n\\paragraph{Page 15:} Equation (2.3.6), $C_1$ should be $C_0$ as it is in the life-cycle diagram, Figure 2.2. \n\n\\paragraph{Page 29:} 9 lines from the bottom, ``the the'' $\\to$ ``the''\n\n\\paragraph{Page 119:} \\emph{Artemisia} is the correct spelling of the genus. \n\n\\paragraph{Page 181:} As we wrote regarding \\textbf{Page 12}, ``piecewise continuous'' needs \nto be defined more narrowly, so that all the claims in this section are valid. \nEven if we ignore the fact that ``continuous curve'' was conveniently undefined, \neqn. \\eqref{eqn:badK1} remains a counterexample to the claim that $K$ maps $L_1(\\Z)$ into $C(\\Z)$. \n\nFortunately, the same approach works in the general setting. A definition of ``piecewise continuous''\nthat actually works is (informally): we can break up $\\Z$ into pieces $\\Z_j$, and thereby break up the kernel into\npieces $K_{ij}$ for transitions from $\\Z_j$ to $\\Z_i$, in such a way that each $K_{ij}$ is continuous. \n\nReading the rest of this item requires some familiarity with the basics of measure theory \nand functional analysis. Sorry, there's no way around this. \n\nWe are considering an IPM where the individual state-space $\\Z$ is a compact metric space with metric $d$, \nand the kernels are defined relative to a finite Borel measure $\\mu$ on $\\Z$. \nThe population dynamics are \n\\be\nn(z',t+1) = \\int_{\\Z} K(z',z)n(z,t) d\\mu(z);\n\\ee \nin the book this is eqn. (6.9.1). The kernel is a function on $\\Z^2 = \\Z times \\Z$, which we give the\n$L_2$ product metric and resulting product topology. Subsets of $\\Z$ and $\\Z^2$ are given the relative\nmetric and measure. \n\nFollowing the definition for the basic model, a partition of $\\Z$ is defined to be a collection of disjoint \nopen (and therefore measurable) sets $\\Z_1, \\Z_2, \\cdots, \\Z_m $ whose boundaries all have $\\mu$-measure 0, \nsuch that the union of their closures $\\bar{\\Z}_j$ is $\\Z$. Again, define the kernels $K_{ij}$ to be $K$ \nrestricted to $\\Z_{ij} = \\Z_i \\times \\Z_j$. \n\nWe say that a kernel $K$ is piecewise continuous if there is a partition such that each $K_{ij}$ is \ncontinuous on each $\\Z_{ij} = \\Z_i \\times \\Z_j$ and can be defined on the boundary \nof $\\Z_{ij}$ so as to be continuous on its closure $\\bar{\\Z}_{ij}$. At a point $(z',z)$ that is on the boundary\nof $\\Z_{ij}$ and of $\\Z_{kl}$, the values chosen for $K_{ij}(z',z)$ and for $K_{kl}(z',z)$ to ensure continuity\nof $K_{ij}$ and $K_{kl}$ do not need to be the same.  \n\nThe reason this works is (again) that the set of kernels $K_{ij}$ (extended to be continuous on their\ndomain $\\bar{\\Z}_{ij}$) defines a general IPM in the sense of section 6.9 in which the overall \nkernel is continuous. The individual-level state space for the general IPM is the collection of \nsets $\\bar{\\Z}_j, j=1,2,\\cdots m$ considered as distinct sets. Formally, define $\\bar{\\Z}^*_j$ to be \nthe set of ordered pairs $(z,j)$ where $z \\in \\bar{\\Z}_j$, and let $\\Z^*$ be the collection \nof all $\\bar{\\Z}^*_j$ with the metric\n\\be\nd^*((z_1,i),(z_2,j)) = \\sqrt{d(z_1,z_2)^2 + (i-j)^2}. \n\\ee\nThe overall kernel is\n\\be\nK^*((z',i),(z,j)) = K_{ij}(z',z). \n\\ee\nA convergent sequence $x^*_n \\to x^*_0$ in $\\Z^* \\times \\Z^*$ must eventually consist of points whose $z$ coordinates \nall lie in the same $\\bar{\\Z}_{ij}$, so the sequence is convergent in $\\bar{\\Z}_{ij}$. So for sufficiently large $n$, \n$K^*(x^*_n) = K_{ij}(x^*_n)$ which converges to $K_{ij}(x^*_0)=K^*(x^*_0)$ because $K_{ij}$ is continuous. The overall\nkernel is therefore continuous. All results in section 6.9 for continuous kernels therefore also hold for\npiecewise continuous kernels under the definition of piecewise continuity given here. \n\n\\paragraph{Page 313:} 2nd line after eqn. (10.7.2), $Cov(Y_1,Y_2)$ $\\to$ $Cov[X_2,Y_2]$\n\n\\paragraph{Page 313:} line before eqn. (10.7.5) should refer to eqn. (10.7.4)\n\n\\paragraph{Page 314:} penultimate line, al\\'{a} $\\to$ \\`{a}  la \n\n\n\n\n\\end{document} \n\n\n\n\n\n", "meta": {"hexsha": "712aa9f5cff6967eecb15e04b00eef50dfb9ba39", "size": 10711, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Ellner-Rcode/Errata.tex", "max_stars_repo_name": "jppeirce/gizshad", "max_stars_repo_head_hexsha": "c767458cb76efc68b29da1636c51b4be44e23a7e", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Ellner-Rcode/Errata.tex", "max_issues_repo_name": "jppeirce/gizshad", "max_issues_repo_head_hexsha": "c767458cb76efc68b29da1636c51b4be44e23a7e", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Ellner-Rcode/Errata.tex", "max_forks_repo_name": "jppeirce/gizshad", "max_forks_repo_head_hexsha": "c767458cb76efc68b29da1636c51b4be44e23a7e", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.844, "max_line_length": 118, "alphanum_fraction": 0.7015218, "num_tokens": 3515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.3209524351177543}}
{"text": "\\documentclass[a4paper,12pt]{article}\r\n\r\n\\usepackage[utf8]{inputenc}\r\n\\usepackage[T1]{fontenc}\r\n\\usepackage{a4}\r\n\\usepackage{lipsum}\r\n\\usepackage{graphicx}\r\n\\usepackage{float}\r\n\\usepackage{listings}\r\n\\usepackage{color}\r\n\\usepackage{hyperref}\r\n\\usepackage{cite}\r\n\\usepackage{textgreek}\r\n\\usepackage{amsfonts}\r\n\\usepackage{amsmath}\r\n\r\n\\usepackage[margin=1in]{geometry}\r\n\r\n\\definecolor{dkgreen}{rgb}{0,0.6,0}\r\n\\definecolor{gray}{rgb}{0.5,0.5,0.5}\r\n\\definecolor{mauve}{rgb}{0.58,0,0.82}\r\n\r\n\\lstset{frame=tb,\r\n  language=matlab,\r\n  aboveskip=5mm,\r\n  belowskip=5mm,\r\n  showstringspaces=false,\r\n  columns=flexible,\r\n  basicstyle={\\small\\ttfamily},\r\n  numberstyle=\\tiny\\color{gray},\r\n  keywordstyle=\\color{blue},\r\n  commentstyle=\\color{dkgreen},\r\n  stringstyle=\\color{mauve},\r\n  breaklines=true,\r\n  breakatwhitespace=true,\r\n  tabsize=2\r\n}\r\n\r\n\\title{\r\n  {\\Huge \\bf Power Systems Lab}\\\\\r\n  \\vspace{0.25in}\r\n\r\n  {\\bf Experiment 4}\\\\\r\n  Laboratory Report\r\n  \\vspace{1in}\r\n}\r\n\\author{\r\n  \\bf Syed Alisamar Husain, 17BEE012\\\\\r\n  B.Tech Electrical Engg, 8th Semester\r\n}\r\n\r\n\\begin{document}\r\n  \\begin{titlepage}\r\n    \\maketitle\r\n    \\vspace*{\\fill}\r\n    \\begin{center}\r\n      {\\bfseries Department of Electrical Engineering} \\\\\r\n      Jamia Millia Islamia, New Delhi\r\n    \\end{center}\r\n    \\thispagestyle{empty}\r\n  \\end{titlepage}\r\n  \r\n  \\newpage\r\n  \\begin{center}\r\n    \\huge Experiment 4\r\n    \\vspace{0.5in}\r\n  \\end{center}\r\n\r\n  \\section{Objective}\r\n  To write a MATLAB program to determine line currents to a Y-connected load\r\n  by mesh analysis and by using symmetrical components.\r\n\r\n  {\\bf Let the given problem be as follows:}\r\n  \\begin{center}\r\n    \\itshape\r\n    A balanced three phase voltage of 120 V line to neutral is applied to a \r\n    Y-connected load with ungrounded neutral. The three phase load consists \r\n    of three mutually-coupled reactances. Each phase has a series reactance of\r\n    $Z_s = j12 \\Omega$, and the mutual coupling between phases is $Z_m = j4 \\Omega$.\r\n  \\end{center}\r\n  \\begin{enumerate}\r\n    \\itshape\r\n    \\item Determine the line currents by mesh analysis.    \r\n    \\item Determine the line currents by using symmetrical components.\r\n  \\end{enumerate}\r\n\r\n  \\section{Theoretical Background}\r\n  Shown below is a 3-phase supply connected to a Y-connected load.\r\n  Each of the voltages $V_1$, $V_2$ and $V_3$ represents the phase voltage\r\n  which are 120 degrees out of phase with each other.\r\n  The impedances are represented by $Z_1$, $Z_2$ and $Z_3$.\r\n\r\n  \\begin{figure}[H]\r\n    \\centering\r\n    \\includegraphics[width=5in]{img/y-load.png}\r\n    \\caption{Y-connected load with ungrounded neutral.}\r\n    \\label{yload}\r\n  \\end{figure}\r\n\r\n    \\subsection{Mesh Analysis}\r\n    The Mesh-Current Method, also known as the Loop Current Method, \r\n    is quite similar to the Branch Current method in that it uses simultaneous \r\n    equations, Kirchhoff’s Voltage Law, and Ohm’s Law to determine unknown \r\n    currents in a network. It differs from the Branch Current method in that \r\n    it does not use Kirchhoff’s Current Law, and it is usually able to solve \r\n    a circuit with less unknown variables and less simultaneous equations.\r\n\r\n    \\pagebreak\r\n    \\subsection{Sequence Components}\r\n    A set of three balanced voltages (phasors) $V_a, V_b, V_c$ is charactertzed by equal\r\n    magnitudes and interphase differences of $120\\deg$. The set is said to have a phase\r\n    sequence $abc$ (positive sequence) if $V_b$ lags $V_a$ by $120\\deg$ and $V_c$ lags \r\n    $V_b$ by $120\\deg$.\r\n\r\n    The three phasors can then be expressed in terms of the reference phasor $V_a$ as\r\n    \\begin{center}\r\n      $V_a$ = $V_a$\\\\\r\n      $V_b$ = $\\alpha^2 V_a$\\\\\r\n      $V_c$ = $\\alpha V_a$\\\\\r\n    \\end{center}\r\n    where the complex number operator $\\alpha$ is defined as $\\alpha = e^{j 120\\deg}$.\r\n    The same applies to voltages or currents.\r\n    \r\n    If the phase sequence is $acb$ (negative sequence), then\r\n    \\begin{center}\r\n      $V_a$ = $V_a$\\\\\r\n      $V_b$ = $\\alpha V_a$\\\\\r\n      $V_c$ = $\\alpha^2 V_a$\\\\\r\n    \\end{center}\r\n\r\n    Thus a set of balanced phasors is fully characterized by its reference phasor\r\n    (say $V_a$) and its phase sequence (positive or negative).\r\n\r\n    Consider now a set of three voltages (phasors) $V_a, V_b, V_c$ which in general may\r\n    be unbalanced. According to {\\bf Fortesque's theorem} the {\\it three phasors can be\r\n    described as the sum of positive, negative and zero sequence phasors}.\r\n\r\n    \\begin{center}\r\n      $V_a = V_a^1 + V_a^2 + V_a^0$\\\\\r\n      $V_b = V_b^1 + V_b^2 + V_b^0$\\\\\r\n      $V_c = V_c^1 + V_c^2 + V_c^0$\r\n    \\end{center}\r\n\r\n    The three phasor sequences (positive, negative and zero) are called the\r\n    {\\bf symmetrical components} of the original phasors. These equations \r\n    can be expressed in the matrix form\r\n    \r\n    \\begin{center}\r\n      \\begin{math}\r\n        \\begin{bmatrix}\r\n          V_a \\\\ V_b \\\\ V_c\r\n        \\end{bmatrix}\r\n        =\r\n        \\begin{bmatrix}\r\n          1 & 1        & 1 \\\\\r\n          1 & \\alpha^2 & \\alpha \\\\\r\n          1 & \\alpha   & \\alpha^2\r\n        \\end{bmatrix}\r\n        \\begin{bmatrix}\r\n          V^0_a \\\\ V^1_b \\\\ V^2_c\r\n        \\end{bmatrix}\r\n      \\end{math}\r\n    \\end{center}\r\n\r\n    \\begin{center}\r\n      $ \\bf V_p = A V_s $\\\\\r\n    \\end{center}\r\n\r\n    To find the sequence components, we can invert the equation\r\n    \\begin{center}\r\n      $ \\bf V_s = A^{-1} V_p $\r\n    \\end{center}\r\n\r\n    \\begin{center}\r\n      where\r\n      \\begin{math}\r\n        {\\bf A^{-1}} =\r\n        \\dfrac{1}{3}\r\n        \\begin{bmatrix}\r\n          1 & \\alpha   & \\alpha^2 \\\\\r\n          1 & \\alpha^2 & \\alpha \\\\\r\n          1 & 1        & 1\r\n        \\end{bmatrix}\r\n      \\end{math}\r\n    \\end{center}\r\n\r\n  \\pagebreak\r\n  \\section{Implementation}\r\n  \\begin{lstlisting}\r\n    % To write a MATLAB program to determine line currents to a Y-connected \r\n    % load by mesh analysis and by using symmetrical components.\r\n\r\n    % 17BEE012 - Alisamar Husain\r\n\r\n    Vp = 120;       % 3-phase Supply Voltage\r\n    \r\n    Zs = 1j*12;     % Branch series reactance\r\n    Zm = 1j*4;      % Branch mutual reactance\r\n\r\n    % 1. Line currents by mesh analysis\r\n    disp('1. Line currents by mesh analysis')\r\n    Vl=sqrt(3)*Vp;\r\n\r\n    Z = [ (Zs-Zm) -(Zs-Zm) 0\r\n          0 (Zs-Zm) -(Zs-Zm)\r\n          1 1 1];\r\n\r\n    V = [ Vl*(cos(pi/6) + 1j*sin(pi/6))\r\n          Vl*(cos(-pi/2) + 1j*sin(-pi/2))\r\n          0];\r\n\r\n    Iabc = Z \\ V;\r\n    disp(Iabc)\r\n\r\n    % 2. Line currents by symmetric components\r\n    disp('2. Line currents by symmetric components')\r\n    a = cos(2*pi/3)+ 1j*sin(2*pi/3);\r\n\r\n    A = [ 1 1 1; \r\n          1 a^2 a; \r\n          1 a a^2];\r\n      \r\n    Z012 = [  Zs+2*Zm 0 0\r\n              0 Zs-Zm 0\r\n              0 0 Zs-Zm];\r\n\r\n    V012 = [0; Vp; 0];\r\n    I012 = Z012 \\ V012;\r\n\r\n    Iabc = A * I012;\r\n    disp(Iabc)\r\n  \\end{lstlisting}\r\n\r\n  \\section{Observations}\r\n  \\begin{figure}[H]\r\n    \\centering\r\n    \\includegraphics{img/run.png}\r\n    \\caption{Result in MATLAB}\r\n    \\label{result}\r\n  \\end{figure}\r\n  The result of the above program with the given parameters \r\n  is shown in figure \\ref{result}.\r\n\r\n  \\section{Result}\r\n  The line currents for the given problem {\\bf by mesh analysis} are found to be\r\n  \\begin{center}\r\n    0.0000 -15.0000i A\\\\\r\n    -12.9904 + 7.5000i A\\\\\r\n    12.9904 + 7.5000i A\r\n  \\end{center}\r\n  and line currents for {\\bf by symmetric components} are found to be\r\n  \\begin{center}\r\n    0.0000 -15.0000i A\\\\\r\n    -12.9904 + 7.5000i A\\\\\r\n    12.9904 + 7.5000i A\r\n  \\end{center}\r\n  It is observed that identical values are obtained by both methods.\r\n\r\n\\end{document}", "meta": {"hexsha": "aa4b295082c8865b6a727b9d72488f3658051184", "size": 7567, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Ex 4/SymComp.tex", "max_stars_repo_name": "zrthxn/powersyslab", "max_stars_repo_head_hexsha": "3b6fc0fde5bed2eaee396cab92e60ed280c4cd8b", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-16T08:48:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-16T08:48:05.000Z", "max_issues_repo_path": "Ex 4/SymComp.tex", "max_issues_repo_name": "zrthxn/powersyslab", "max_issues_repo_head_hexsha": "3b6fc0fde5bed2eaee396cab92e60ed280c4cd8b", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Ex 4/SymComp.tex", "max_forks_repo_name": "zrthxn/powersyslab", "max_forks_repo_head_hexsha": "3b6fc0fde5bed2eaee396cab92e60ed280c4cd8b", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2162162162, "max_line_length": 89, "alphanum_fraction": 0.6130566935, "num_tokens": 2355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.320952427895305}}
{"text": "\\input{../../_common/preamble}\n\n\\title{Probability theory and statistics}\n\n\\begin{document}\n\n\\maketitle\n\n\\begin{frame}{Contents}\n    \\tableofcontents[hideallsubsections]\n\\end{frame}\n\n\\section{Probability theory}\n\n\\begin{frame}{`Random' points}\n    \\begin{center}\n        \\includegraphics[width=\\textwidth]{figures/random_points}\n    \\end{center}\n\\end{frame}\n\n\\begin{frame}{What is probability?}\n    \\begin{quote}\n        `The extent to which something is likely to happen'\n        \\begin{flushright}\n            \\small%\n            --- Oxford English Dictionary\n        \\end{flushright}\n    \\end{quote}\n    \\vfill\n    \\begin{block}{Examples}\n        \\begin{itemize}\n            \\item Probability that it will rain tomorrow\n            \\item Probability that you will win the lottery\n        \\end{itemize}\n    \\end{block}\n\\end{frame}\n\n\\begin{frame}{Sources of uncertainty}\n    \\begin{columns}[t]\n        \\begin{column}{0.5\\textwidth}\n            \\begin{center}\n                \\includegraphics[height=2cm]{figures/rain} \\\\[\\medskipamount]\n                \\alert{Imperfect information}\n            \\end{center}\n            Current predictive tools can only assign a number indicating our\n            degree of certainty\n        \\end{column}\n        \\begin{column}{0.5\\textwidth}\n            \\begin{center}\n                \\includegraphics[height=2cm]{figures/lottery} \\\\[\\medskipamount]\n                \\alert{Stochastic process}\n            \\end{center}\n            The experiment is designed to produce uncertain results (because\n            it's fun)\n        \\end{column}\n    \\end{columns}\n\\end{frame}\n\n\\begin{frame}{Probability theory}\n    \\begin{block}{What?}\n        The branch of mathematics concerned with \\alert{random phenomena}\n    \\end{block}\n    \\vfill\\pause\n    \\begin{block}{How?}\n        Using mathematical \\alert{abstractions} of non\\hyp{}deterministic events\n    \\end{block}\n    \\vfill\\pause\n    \\begin{block}{Why?}\n        To identify \\alert{patterns} in (apparently) random occurrences\n    \\end{block}\n\\end{frame}\n\n\\begin{frame}{Statistical regularity}\n    \\only<1>{%\n        \\begin{center}\n            {\\LARGE%\n             We cannot predict with certainty \\\\ if it's going to rain tomorrow}\n            \\vfill\n            {\\large%\n             but}\n            \\vfill\n            {\\LARGE%\n             we can predict `average behaviour'}\n        \\end{center}}\n    \\only<2>{%\n        In summary\\ldots\n        \\begin{itemize}\n            \\item Probability theory describes the behaviour of random phenomena\n                  \\alert{in the long run}\n            \\item If this information is useful, probability theory can be a\n                  valuable tool for \\alert{decision-making}\n        \\end{itemize}}\n\\end{frame}\n\n\\begin{frame}[t]{Random variables `encapsulate' random events}\n    \\begin{block}{Notation}\n        \\begin{itemize}\n            \\item $X$, $Y$, \\ldots~(upper case) are \\alert{random variables}\n            \\item $X = x$ (lower case) is a value (\\alert{realisation}) of $X$\n            \\item $\\Prob{X = x}$ is the \\alert{probability} that $X = x$\n        \\end{itemize}\n    \\end{block}\n    \\vfill\n    \\begin{block}{Example}\n        \\begin{itemize}\n            \\item $X$ represents the (`archetypal') outcome of a coin toss\n            \\item $X = \\text{`head'}$ represents one (actual) outcome\n            \\item $\\Prob{X = \\text{`head'}}$ is the long\\hyp{}term probability\n                  of the outcome `head'\n        \\end{itemize}\n    \\end{block}\n\\end{frame}\n\n\\begin{frame}{Maximum of two fair dice}\n    \\begin{columns}[t]\n        \\begin{column}{0.5\\textwidth}\n            \\centering\n            \\textbf{A fair die} \\\\[\\bigskipamount]\n            \\begin{tabular}{cc}\n                \\toprule\n                $x$ & $\\Prob{X = x}$ \\\\\n                \\midrule\n                $1$ & $1/6$ \\\\\n                $2$ & $1/6$ \\\\\n                $3$ & $1/6$ \\\\\n                $4$ & $1/6$ \\\\\n                $5$ & $1/6$ \\\\\n                $6$ & $1/6$ \\\\\n                \\bottomrule\n            \\end{tabular}\n        \\end{column}\n        \\begin{column}{0.5\\textwidth}\n            \\centering\n            \\textbf{Maximum of two fair dice} \\\\[\\bigskipamount]\n            \\begin{itemize}\n                \\item How many outcomes?\n                \\item $\\Prob{X = 1}$?\n                \\item $\\Prob{X = 6}$?\n            \\end{itemize}\n        \\end{column}\n    \\end{columns}\n\\end{frame}\n\n\\begin{frame}{Probability distributions}\n    \\begin{center}\n        \\large%\n        \\textbf{Simplified approximations to reality}\n    \\end{center}\n    \\vfill\n    \\begin{itemize}\n        \\item Detailed enough to capture important characteristics and serve as\n              \\alert{prediction tools}\n        \\item Simple enough to be usable in practice\n    \\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Characterising probability distributions}\n    \\begin{block}{Measures of central tendency}\n        \\begin{itemize}\n            \\item (Arithmetic) mean or average\n            \\item Median\n            \\item Mode\n        \\end{itemize}\n    \\end{block}\n    \\vfill\\pause\n    \\begin{block}{Measures of dispersion}\n        \\begin{itemize}\n            \\item Variance\n            \\item Minimum and maximum $\\rightarrow$ range\n            \\item Quantiles (a.k.a.\\ order statistics)\n        \\end{itemize}\n    \\end{block}\n\\end{frame}\n\n\\begin{frame}{Characterising probability distributions}\n    \\begin{center}\n        \\large%\n        1, 8, 16, 30, 32, 37, 53, 80, 86, 91, 93\n    \\end{center}\n    \\vfill\n    \\begin{itemize}\n        \\item Mean?\n        \\item Median?\n        \\item Mode?\n        \\item Variance and standard deviation?\n        \\item Minimum and maximum, and range?\n        \\item Quartiles?\n    \\end{itemize}\n\\end{frame}\n\n\\section{Statistics}\n\n\\begin{frame}{Statistics}\n    \\begin{block}{What?}\n        The science of collecting and analysing numerical data\n    \\end{block}\n    \\vfill\\pause\n    \\begin{block}{How?}\n        By planning studies, exploring and modelling the data using the tools of\n        \\alert{probability theory}\n    \\end{block}\n    \\vfill\\pause\n    \\begin{block}{Why?}\n        To infer properties of a \\alert{population} from a \\alert{sample}\n    \\end{block}\n\\end{frame}\n\n\\begin{frame}[t]{Probability or statistics?}\n    You have a fair coin. You toss it 100 times. \\\\\n    How likely is it to land heads 60 times or more?\n    \\vfill\\pause\n    \\begin{center}\n        \\large%\n        \\textbf{Probability}\n    \\end{center}\n    \\begin{itemize}\n        \\item Random process is known (or assumed): `fair coin'\n        \\item Objective: \\alert{find probability of a certain outcome}\n    \\end{itemize}\n\\end{frame}\n\n\\begin{frame}[t]{Probability or statistics?}\n    I give you a coin. You toss it 100 times and count 60 heads. \\\\\n    Is the coin fair?\n    \\vfill\\pause\n    \\begin{center}\n        \\large%\n        \\textbf{Statistics}\n    \\end{center}\n    \\begin{itemize}\n        \\item Outcome is known (or measured): `$60 / 100$ heads'\n        \\item Objective: \\alert{characterise the random process}\n    \\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Probability theory and statistics}\n    \\begin{columns}[t]\n        \\begin{column}{0.5\\textwidth}\n            \\begin{center}\n                \\textbf{Probability theory}\n            \\end{center}\n            \\begin{itemize}\n                \\item Defines the model\n                \\item \\ldots and often its \\alert{parameters}\n            \\end{itemize}\n        \\end{column}\n        \\begin{column}{0.5\\textwidth}\n            \\begin{center}\n                \\textbf{Statistics}\n            \\end{center}\n            \\begin{itemize}\n                \\item Collects the data\n                \\item `Fits' the model \\\\ (estimates its parameters)\n                \\item Makes \\alert{inferences}\n            \\end{itemize}\n        \\end{column}\n    \\end{columns}\n\\end{frame}\n\n\\end{document}\n\n", "meta": {"hexsha": "10793bb9d004a892518175971f0357178035e37a", "size": 7824, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "05_statistical_thinking/slides/01_probability_statistics.tex", "max_stars_repo_name": "JoseHJBlanco/ga-data-science", "max_stars_repo_head_hexsha": "dff5cfd8fb13c1c49cba099bd100ca79143828e4", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2017-11-17T09:44:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-08T18:02:42.000Z", "max_issues_repo_path": "05_statistical_thinking/slides/01_probability_statistics.tex", "max_issues_repo_name": "itsshaikaslam/ga-data-science", "max_issues_repo_head_hexsha": "b39f3a499749e4423bb193a1376b7dee770152b7", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-03-27T13:05:12.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-27T13:05:12.000Z", "max_forks_repo_path": "05_statistical_thinking/slides/01_probability_statistics.tex", "max_forks_repo_name": "itsshaikaslam/ga-data-science", "max_forks_repo_head_hexsha": "b39f3a499749e4423bb193a1376b7dee770152b7", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 21, "max_forks_repo_forks_event_min_datetime": "2018-01-01T03:26:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-31T19:24:24.000Z", "avg_line_length": 29.8625954198, "max_line_length": 80, "alphanum_fraction": 0.5681237219, "num_tokens": 2076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.320952427895305}}
{"text": "\\documentclass{article}\n\n\\usepackage{hyperref}\n\\usepackage{cite}\n\\usepackage{amsmath}\n\\usepackage{amsfonts}\n\\usepackage[ruled]{algorithm2e}\n\\usepackage[margin=1in]{geometry}\n\\usepackage{appendix}\n\\usepackage{float}\n\\usepackage{verbatim}\n\\usepackage[normalem]{ulem}\n\\usepackage{graphicx}\n\\usepackage{siunitx}\n\\usepackage[section]{placeins}\n\n\\setcounter{section}{-1}\n\\newtheorem{lemma}{Lemma}\n\\newcommand{\\lemmaautorefname}{Lemma}\n\n\\title{CLimate Analysis using Digital Estimations Non-Offical Manual (CLAuDE NOM)}\n\\author{Sam \"TechWizard\" Baggen}\n\\date{\\today}\n\n\\begin{document}\n\n\\maketitle\n\n\\tableofcontents\n\n\\newpage\n\n\\section{Introduction}\n\nThe CLimate Analysis using Digital Estimations model is a simplified planetary climate model. It will be used to educate people on how climate physics works and to experiment with different \nparameters and see how much influence a tiny change can have (like for instance the rotation rate of the planet around its axis). It is built to be accessible to and runnable by everyone, \nwhether they have a super computer or a dated laptop. The model is written in Python and written during the weekly streams of Dr. Simon Clark \\cite{twitch}. There is a useful playlist on \nSimon's Twitch which has all the streams without ad breaks or interruptions \\cite{playlist}. \n\nThe manual itself is split up into distinct sections, each explaining one particular part of the model. Each section will be treating one topic, like radiation, advection or the control panel.\nAlthough many concepts cannot be seen in isolation, as the wind has influence on how much temperature is distributed throughout the atmosphere, the calculations can be split up. The manual is \ncumulative, starting with the basics and slowly building up to the current form of the algorithm. All changes to the algorithms can therefore be found here. An important distinction needs to be \nmade regarding the changes though. If the changes only change one part of the calculations, then it is considered an evolution, which will be added to the relevant section. However if the changes \nare significant and not based on the previous code then the old alghorithms will be relocated to \\autoref{sec:history}. Though the relevant theory will remain, as that is required to gain an \nunderstanding of what the algorithm does. Do note that the radiation \\autoref{sec:rad} is an exception for the first calculations as this forms the basis of the beginning of CLAuDE and the \nfundamentals of the theory which I deem important enough to be left in place even if the calculations end up significantly different.\n\nThis manual will provide an overview of the formulae used and will explain aspects of these formulae. For each equation each symbol will be explained what it is. In such an explanation, the units \nwill be presented in SI units \\cite{SI} between brackets like: $T$: The temperature of the planet ($K$). Which indicates that $T$ is the temperature of the planet in degrees Kelvin. If you need \nto relate SI units to your preferred system of units, please refer to the internet for help with that. There are great calculators online where you only need to plug in a number and select the \nright units.\n\nWithin this manual we will not concern ourselves with plotting the data, instead we focus on the physics side of things and translating formulae into code. If you are interested in how the\nplotting of the data works, or how loading and saving data works, please refer to the relevant stream on Simon's Twitch page \\cite{twitch}.\n\nThis manual is for the toy model, which is as of now still in development. One important thing to note is that the layout may change significantly when new sections are added. This is due to the amount of code that is added/changed. If a lot of code changes, a lot of so called\n'algorithm' blocks are present which have different placement rules than just plain text. Therefore it may occur that an algorithm is referenced even though it is one or two pages later. This is \na pain to fix and if something later on changes, the whole layout may be messed up again and is a pain to fix again. Hence I opt to let \\LaTeX (the software/typeset language used to create this \nmanual) figure out the placement of the algorithm blocks, which may or may not be in the right places.\n\nThe manual is now up on the Planet Factory GitHub repository\\cite{claudeGit}, together with all the source code. There is also a fork \\cite{nomGit} that also contains the source code. \nThe fork will usually be more up to date than the version on the Planet Factory repository as Simon needs to merge pull requests into the repository. However I can update the fork freely so if a \nparticular stream is missing in the version on the Planet Factory repository, check the fork/Discord whether there is a newer version. If that is not the case, you just have to be a bit more \npatient, or you can start writing a part of the manual yourself! Don't forget to ping me in the Discord to notify me of any additions (GitHub refuses to send me emails so I have no other way of \nknowing).\n\n\\FloatBarrier\n\\newpage\n\\input{topics/control_panel.tex}\n\n\\FloatBarrier\n\\newpage\n\\input{topics/util_funcs.tex}\n\n\\FloatBarrier\n\\newpage\n\\input{topics/radiation.tex}\n\n\\FloatBarrier\n\\newpage\n\\input{topics/velocity.tex}\n\n\\FloatBarrier\n\\newpage\n\\input{topics/advection.tex}\n\n\\FloatBarrier\n\\newpage\n\\input{topics/planar.tex}\n\n\\FloatBarrier\n\\newpage\n\\input{topics/master.tex}\n\n\\FloatBarrier\n\\newpage\n\\input{appendices/TTNMETAF.tex}\n\n\\FloatBarrier\n\\newpage\n\\input{appendices/history.tex}\n\n\\FloatBarrier\n\\newpage\n\\input{appendices/vars.tex}\n\n\\newpage\n\\bibliography{references}\n\\bibliographystyle{plain}\n\\end{document}", "meta": {"hexsha": "587e5ad5b1138addd6b9d4000e50d74d2a971f21", "size": 5690, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex-docs/CLAuDE.tex", "max_stars_repo_name": "WardPearce/claude", "max_stars_repo_head_hexsha": "96f2d6af19c1f5a61148c00df559fb39d272a717", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tex-docs/CLAuDE.tex", "max_issues_repo_name": "WardPearce/claude", "max_issues_repo_head_hexsha": "96f2d6af19c1f5a61148c00df559fb39d272a717", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex-docs/CLAuDE.tex", "max_forks_repo_name": "WardPearce/claude", "max_forks_repo_head_hexsha": "96f2d6af19c1f5a61148c00df559fb39d272a717", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.7272727273, "max_line_length": 277, "alphanum_fraction": 0.7959578207, "num_tokens": 1317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.320952427895305}}
{"text": "\\section{Classical simulation}\n\\label{sec:classical}\nWhile the currently applied traditional methods for the analysis of experimental scattering data discussed previously are popular.\nThere is growing interest in the use of multi-modal analysis methods that leverage classical simulation to assist in the analysis of scattering data.\\autocite{ivanovic_temperature-dependent_2018,scoppola_combining_2018,dabkowska_modulation_2014,hub_interpreting_2018}\nThis would involve the simulation of the chemical system in order to educate the analysis of the experimental data.\nThese systems, especially when the materials being simulated are soft in nature, are often highly complex and typically cover large length scales.\nClassical simulation, particularly in combination with coarse-grained potential models, can feasibly enable the simulation of these systems.\n\nIn order to simulate the complexity of a real chemical system, it is necessary to model the electrons of the molecules and their interactions.\nThis is usually achieved using quantum mechanical calculations, where the energy of the system is calculated by finding some approximate solution to the Schr\\\"{o}dinger equation.\nHowever, quantum mechanical calculations are very computationally expensive and are realistically limited to hundreds of atoms.\nIn order to simulate a soft matter system such as a phospholipid monolayer or polymer nanoparticles, it is necessary to simplify the calculation being performed.\nThis leads to the use of classical simulations, where parameterised analytical functions are used to represent the potential energy of the system.\nClassical simulations are used substantially in this work, in terms of molecular dynamics simulations.\\footnote{Molecular dynamics (MD) is discussed in detail in Section~\\ref{sec:optimisation}.}\nTherefore, it is necessary to introduce the underlying theory on which this method is defined.\n\n\\subsection{Potential models}\n\\label{sec:potentmodels}\nPotential modelling is a more computationally efficient method for the calculation of the potential energy of a chemical system.\nA potential model consists of a series of mathematical functions that depend on the atomic positions, $\\mathbf{r}$.\nEach of the functions represents the potential energy of a different interaction for a given atom.\nBroadly, these interactions can be split into bonded and non-bonded, such that the total energy may be described as follows,\n%\n\\begin{equation}\n\\begin{aligned}\n  E_{\\text{total}}(r) = & \\sum_{\\text{bonded pairs}}{E_{\\text{bonded}}(r)} \\\\\n  & + \\sum_{\\text{atom pairs}}{E_{\\text{non-bonded}}(r)}.\n\\end{aligned}\n\\end{equation}\n%\nThe total potential energy is then the sum of the potential energy for each of the individual atoms.\n\nThe bonded terms are used to describe different aspects of chemical bonds.\nThese typically consist of bond stretches, angle bends and dihedral torsions, these interactions have the following mathematical form,\\footnote{These forms are specific to the OPLS2005 potential model (\\cite{banks_integrated_2005}), other potential models may have different functions.}\n%\n\\begin{equation}\n\\begin{aligned}\n  E_{\\text{bonded}}(b, \\theta, \\phi) = & \\sum_{\\text{bonds}}K_b(b-b_0)^2 + \\sum_{\\text{angles}}K_{\\theta}(\\theta-\\theta_0)^2 \\\\\n  & + \\sum_{\\text{dihedrals}} \\frac{1}{2}\\big\\{A_1[1 + \\cos(\\phi)] \\\\\n  & + A_2[1 - \\cos(2\\phi)] + A_3[1 + \\cos(3\\phi)]\\big\\},\n\\end{aligned}\n\\end{equation}\n%\nwhere, $K_b$ and $b_0$, $K_{\\theta}$, $\\theta_0$, and $A_1$, $A_2$, and $A_3$ are interaction dependent parameters for the bonds, angles, and dihedrals respectively, while $b$, $\\theta$, and $\\phi$ are the bond lengths, the size of the angles, and the size of the dihedrals that depend on the atom positions.\\footnote{The values for the interaction dependent parametes are determined as outlined in Section~\\protect\\ref{sec:parameterisation}.}\nIt can be seen that both the bond stretch and angle bend have harmonic functions, whereas the dihedral consists of a more complex multiple cosine functions.\n\nThe non-bonded terms are a series of functions that describe the potential energy of intermolecular interactions, such as electrostatics and London dispersion forces.\nThe potential energies of the short-range interactions are usually modelled as a combination of the attractive London dispersion interaction and the repulsive exchange forces that arise from the Pauli exclusions principle.\\autocite{leach_molecular_1996}\nThese are often forms such as shown below for the Lennard-Jones potential model,\\autocite{lennard-jones_determination_1924}\n%\n\\begin{equation}\n\\begin{aligned}\n  E_{\\text{non-boned}}(r) = & E_{\\text{repulsive}} + E_{\\text{attractive}} \\\\\n  = & \\frac{A}{r^{12}} - \\frac{B}{r^6} = 4\\varepsilon\\Bigg[\\bigg(\\frac{\\sigma}{r}\\bigg)^{12} - \\bigg(\\frac{\\sigma}{r}\\bigg)^6\\Bigg]\n\\end{aligned}\n\\end{equation}\n%\nwhere, $r$ is the distance between two particles, $A$ and $B$ are interaction dependent parameters, and $\\sigma$ and $\\epsilon$ are simple reformations of these parameters,\n%\n\\begin{equation}\n  A = 4\\varepsilon\\sigma^{12} \\;\\;\\;\\; B = 4\\varepsilon\\sigma^6.\n\\end{equation}\n%\nFigure~\\ref{fig:lj} shows each component of the Lennard-Jones potential model for atoms of argon.\\footnote{Using parameters for $A$ and $B$ determined in \\cite{rahman_correlations_1964}.}\nThe Lennard-Jones potential model is not the only form that may be used for the modelling of the short-range non-bonded interactions, others such as the Buckingham and Morse potentials exist.\\autocite{buckingham_classical_1938, morse_diatomic_1929}\nIn each case, there is a short ranged repulsive interaction to describe the electrostatic repulsion between the electron clouds, and a longer range attractive component that represents dispersion interactions.\nHowever, the Lennard-Jones model has been used heavily in this work.\n%\n\\begin{figure}[t]\n    \\forceversofloat\n    \\centering\n    \\includegraphics[width=\\textwidth]{theory/lj}\n    \\caption{The form of each component; attractive (blue), repulsive (orange), of the Lennard-Jones potential model (green) for argon, using parameters in \\cite{rahman_correlations_1964}.}\n    \\label{fig:lj}\n\\end{figure}\n%\n\nWhile the short-range interactions can be accounted for by a function such as the Lennard-Jones potential model, the potential energy of the long-range electrostatic interactions are usually modelled, more consistently, using Coulomb's law for classical electrostatic interaction between point particles,\\autocite{coulomb_premier_1788, coulomb_second_1788}\n%\n\\begin{equation}\n  E_{\\text{Coulomb}}(r) = \\frac{1}{4\\pi\\varepsilon_0}{\\frac{q_iq_je^2}{r^2}},\n  \\label{equ:col}\n\\end{equation}\n%\nwhere, $r$ is the distance between the two particles, $\\varepsilon_0$ is the dielectric permittivity of the vacuum, $e$ is the charge of the electron, and $q_i$ and $q_j$ are the electronic charges on each of the particles.\nIt is clear that when $q_i$ and $q_j$ have the opposite signs Coulomb's law is always attractive.\nThe fact that Equation~\\ref{equ:col} contains a factor of $r^2$ indicates that this is a much longer range interaction than those modelled with the Lennard-Jones model, make the Coulomb potential more complex to compute.\\autocite{frenkel_understanding_1996}\n\nAn example of a very large classical simulation would be $\\sim3$ million atoms.\\autocite{gumbart_regulation_2009}\nHowever, this is still only \\SI{1.8e-16}{\\mol} which is not remotely realistic as a simulation of a ``real'' system.\nA common method to allow for the apparent simulation of a much larger system is the use of periodic boundary conditions.\\footnote{Abbreviated to PBC.}\nThis is where a boundary condition is applied to the edges of the simulation cell, such as to mimic an infinite system, such that the simulation cell is surrounded by identical images of itself, this is shown pictorially in Figure~\\ref{fig:pbc}.\nUsing the PBC means that atomic diffusion is conserved as when an atom reaches the edge of the simulation cell, it will appear on the other side as though it came from the adjacent periodic cell.\nThe use of a PBC is particularly powerful in the simulation of homogenous systems, such as liquids.\n%\n\\begin{figure}[b]\n    \\forceversofloat\n    \\centering\n    \\includegraphics[width=0.8\\textwidth]{theory/pbc}\n    \\caption{A graphical representation of the PBCs. Reprinted, with permission of Elsevier, from \\cite{frenkel_understanding_1996}.}\n    \\label{fig:pbc}\n\\end{figure}\n%\n\nThe cut-off is another important factor for classical simulation, this is the distance after which the energy between two particles is considered to be zero.\nTherefore, for distances greater than the cut-off, it is not necessary to calculate the energy between the two particles as it is taken to be zero.\\footnote{This leads to an increase in computational efficiency.}\nCode Block~\\ref{cb:lj} gives an example of some code that could be used to calculate the Lennard-Jones energy of an atomistic system, where both the PBC and the energy cut-off distance are considered.\n%\n\\begin{listing}[b]\n    \\forcerectofloat\n    \\centering\n    \\caption{Code that may be used to generate the Lennard-Jones energy for a given atomistic system, which accounts for the PBC and the energy cut-off distance. The input varibles are \\texttt{coordinates} which is an array of floats describing the position of the \\texttt{N} particles, \\texttt{cell} which are the unit cell vectors, \\texttt{cut\\_off} which is potential energy cut-off, and \\texttt{A} and \\texttt{B} which are the Lennard-Jones potential parameters. This returns an array with the energy for each particle.}\n    \\lstinputlisting[nolol]{reports/code_blocks/lennardjones.py}\n    \\label{cb:lj}\n\\end{listing}\n%\n\nThe use of the PBC may be problematic for systems containing long-range interactions, such as classical electrostatics, due to the fact that the range of the electrostatic interaction may be much greater than the size of half of the simulation cell, which can be taken to be the energy cut-off distance.\nIn order to avoid truncation artefacts, the Ewald summation is often used for the calculation of the electrostatic contribution to the potential energy.\\autocite{ewald_berechnung_1921}\nThe Ewald summation involves performing the summation of the contributing interaction energies in reciprocal space rather than in real space as is the case for the short-range interactions.\nMost modern MD simulation software packages implement the Ewald summation using a particle mesh Ewald method.\\autocite{essmann_smooth_1995}\n\n\\subsection{Parameterisation}\n\\label{sec:parameterisation}\nSection~\\ref{sec:potentmodels} introduced the idea of potential models that may be used to evaluate the potential energy of a given system, requiring much less time than methods that rely on the use of quantum mechanics.\nHowever, for these methods to be effective, it is important that the potential models used are able to model the system under study accurately.\nThis is achieved initially by selecting the correct potential model for a given interaction, and then by ensuring that the interaction-dependent parameters are accurate for a given interaction.\nThe method of obtaining such parameters is referred to as ``parameterising'' the model.\nModel parameterisation is important for all types of potential models, for example it is necessary to determine the equilibrium bond length $b_0$ and the force constant $K_b$ for a given covalent bonds, or the partial electrostatic charge that is present on a carbonyl oxygen atom when it interacts with the hydrogen atom from a neighbouring hydroxyl group.\n\nParameterisation of a potential model is usually achieved by fitting the potential model functions to energetic data obtained using a higher accuracy technique.\\footnote{These may be quantum mechanical calculations or experimental methods.}\nWe will not dwell on the details of potential model parameterisation,\\footnote{This is discussed in detail in many textbooks such as \\cite{harvey_computational_2018,leach_molecular_19962}} however, it is important to note that the parameters used in MD simulation are not absolute and depend heavily on the merits of the parameterisation method.\n\nIn this work, we have focused heavily on the use of off-the-shelf potential models, to ensure the easy replicability of the work.\nOff-the-shelf potential models are those that are determined to be applied to a wide range of chemical systems.\nAn example includes the OPLS potential model which was parameterised by comparison to quantum mechanical measurements and crystallographic data.\\autocite{jorgensen_opls_1988}\nWhile these off-the-shelf potential models are useful for their ease-of-use, it is noted that often these forcefields may require optimisation for the particular system.\n\n\\subsection{Coarse-graining}\n\\label{sec:coarsegraining}\nThe atomistic simulation of very large systems, such as multiple surfactant micelles or large phospholipid monolayers, require a huge number of atoms.\nWhile computational efficiency improvements such as the PBC or the energy cut-off distance are able to reduce the time taken to simulate these systems, it is often still not possible to produce physically meaningful simulations,\\footnote{In particular for emergent properties that depend on large system sizes and long simulation times.} without including some other efficiency improvements.\n\nThis has led to the use of coarse-graining of molecules in simulations.\nThis is the definition of super-atoms, in the place of groups of atoms, known as ``beading'', some examples are shown for the MARTINI force field\\autocite{marrink_martini_2007} in Figure~\\ref{fig:cg}.\nEach of the super-atoms must correspond to the chemistry of the underlying atoms.\nFor example, the MARTINI potential model introduces five different apolar, beads to represent the polarity of the carbon atoms that make up the super-atom.\nAdditionally, there are thirteen other super-atom types that can be used to model polar, nonpolar, and charged atomic groups.\n%\n\\begin{figure}[t]\n    \\forcerectofloat\n    \\centering\n    \\includegraphics[width=0.8\\textwidth]{theory/beading}\n    \\caption{Three examples of the MARTINI coarse-graining mechanism for (a) aspertic acid, (b) a water cluster, and (c) a molecule of DPPC. Reprinted with permission of the Institute of Physics, from \\cite{pluhackova_biomembranes_2015}.}\n    \\label{fig:cg}\n\\end{figure}\n%\n\nIn addition to the computational benefit of having fewer particles in the simulation,\\footnote{Therefore requiring fewer integrations of the equations of motion} there is also the opportunity to increase the timestep length for the simulation.\\autocite{pluhackova_biomembranes_2015}\nThis can be achieved as the highest frequency vibrations that must be modelled in the system are integrated out.\nFor example, another coarse-grained model called the united atom potential model, where the hydrogen atoms have been integrated out, the timestep may be larger than for the same all-atom system as it is no longer necessary to model the high-frequency \\ce{C-H} bond.\n\nThe technique of coarse-graining a molecule can range from the integration of the hydrogen atoms into the heavier atoms to which they are bound, all the way to the treatment of entire molecules as a single ``bead'', with the inclusion of an implicit solvent.\nThe parameterisation of a coarse-grained potential model is carried out in much the same way as discussed in Section~\\ref{sec:parameterisation} for all-atom potential models.\nThe coarse-grained parameters are determined by comparison with a higher-resolution technique.\\footnote{Often this is all-atom MD simulations.}\n", "meta": {"hexsha": "bd538777c31c7ba174415700023d9b39f203299a", "size": 15617, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "reports/chapters/theory/classical.tex", "max_stars_repo_name": "arm61/thesis", "max_stars_repo_head_hexsha": "4c76e837b1041472a5522427de0069a5a28d40c9", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-06-04T20:53:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-01T06:25:20.000Z", "max_issues_repo_path": "reports/chapters/theory/classical.tex", "max_issues_repo_name": "arm61/thesis", "max_issues_repo_head_hexsha": "4c76e837b1041472a5522427de0069a5a28d40c9", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-06-04T17:11:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-04T17:11:33.000Z", "max_forks_repo_path": "reports/chapters/theory/classical.tex", "max_forks_repo_name": "arm61/thesis", "max_forks_repo_head_hexsha": "4c76e837b1041472a5522427de0069a5a28d40c9", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 94.078313253, "max_line_length": 524, "alphanum_fraction": 0.7975923673, "num_tokens": 3689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.320952427895305}}
{"text": "\\section{State of the Art}\n\nBefore the main matter of the thesis, it is important to expose the current\nstate of the art, to check if the previous research done in the topics\nrelated to this project. First, the section will sum up the current state of\nthe art in the algorithms that will be used by the thesis, as well as all\nnaming several libraries currently used for that purpose. Last, this section\nwill provide a basic state of the language to be used, Haskell; that will also\nserve as a motivation for why to develop the project using this tool.\\\\\n\n\\subsection{Heuristic Search}\n\nHeuristic Search is a problem solving method that belongs to Artificial\nIntelligence \\cite{rusell-2003-aima} used in robotics, pathfinding, computer\ngaming among other fields. We can distinguish two types of heuristic search\nalgorithms: uninformed algorithms, which do not use a heuristic function and\nperform a brute-force search; and informed algorithms, which use a heuristic\nfunction to provide better performance than the aforementioned brute-force\nalgorithms.\\\\\n\n\\begin{figure}[ht]\n\\centering\n\\includegraphics[width=0.8\\textwidth]{img/empty-tree.png}\n\\caption{Example of a search tree}\n\\label{tree:empty}\n\\end{figure}\n\nAlthough every algorithm included in this thesis can work with implicit graphs,\nthe best way to gain some intuition about them is to reflect their behavior on\na search tree, like the one in Figure \\ref{tree:empty}. This tree presents a\nroot node (top of the image), from which is possible to see two different\noriented edges going out to two new nodes. This presents in a explicit way the\nfact of being able to traverse the search space using operators given in a\nproblem space. The green nodes present final states. The objective of any\nsearch algorithm then is to find a path from the root node (which is the\ninitial state defined in the problem space) to a final node, using different\nconstraints depending on the problem at hand: the shortest path, lowest cost\npath, or just a solution that can be found in the shortest time possible. Using\nthis graphical representation, we can now go deep into explaining the current\nstate of the art of the algorithms that will be included in the framework.\\\\\n\n\\subsubsection{Uninformed Algorithms}\n\nOne of the basic brute-force algorithms is, undoubtedly, Breadth-First Search.\nIt was first introduced by Konrad Zuse in 1945, although published years later\n\\cite{zuse-1972-plankalkul}. This algorithm uses a queue (First In, First Out)\ndata structure to store the nodes expanded. The use of this queue to sort the\nnodes to expand results in an exhaustive search per depth in the tree: first\nthe depth 0 nodes are expanded, the depth 1, the depth 2, etc, until the\nsolution is found or until the search space is completely exhausted. This\nbehavior can be appreciated in Figure \\ref{tree:bfs}.\\\\\n\n\\begin{figure}[ht]\n\\centering\n\\includegraphics[width=0.8\\textwidth]{img/bfs.png}\n\\caption{Breadth-First Search execution on the tree}\n\\label{tree:bfs}\n\\end{figure}\n\nIn Figure \\ref{tree:bfs} it is possible to see that the nodes are visited from\nshallower to deeper levels, ensuring that the solution returned by this\nalgorithm is indeed the one with the shortest path from the initial state. The\nalgorithm is complete, that is, it will find a solution if it exists in the\nsearch space, even if such space is infinite. The solution found will be the\nnearest to the initial state, which is ensured to be the optimal if there no\nvariable costs. Its complexity is defined by $O(|V|)$, that is, the total\nnumber of states. This is common to all search algorithms: theoretically, they\nhave to check all states in a worst case scenario. However, it is important to\nnotice that the complexity to finding a certain solution at a depth $d$ is\n$O(b^{d+1})$, where $b$ is the branching factor of the problem\n\\cite{rusell-2003-aima}.\\\\\n\nAnother well-known uninformed algorithm is Depth-First Search. This algorithm\nuses the opposite approach to the problem: tries to search as deep as possible\nbefore exhausting a branch or finding a solution. This algorithm was first\nstudied by Charles Pierre Trémaux in the 19th Century, with the purpose of\nsolving mazes with well defined passages \\cite{even-2011-graph}. This algorithm\ndoes not need a auxiliary data structure to hold nodes: instead, it is possible\nto explore the nodes in depth just using recursive calls to the algorithm. This\nallows Depth-First Search to perform searches in linear space, since it only\nneeds to store the stack calls needed to keep track of the search. Although\nthis is convenient for this project, it is possible as well to use a stack\nstructure (Last In, First Out) to hold all the nodes in an imperative language\nin case the recursion is not desired \\cite{rusell-2003-aima}. A complete\nexecution of this algorithm can be found in Figure \\ref{tree:dfs}\\\\\n\n\\begin{figure}[ht]\n\\centering\n\\includegraphics[width=0.8\\textwidth]{img/dfs.png}\n\\caption{Depth-First Search execution on the tree}\n\\label{tree:dfs}\n\\end{figure}\n\nIn the execution of Figure \\ref{tree:dfs}, it is possible to see how it\nexhausts the first branch until no more nodes can be expanded, to then\nbacktrack. This backtracking can be implicitly implemented (by using recursive\ncalls it is possible to recover from an exhausted branch). We can see how this\nsearch returns a worse solution than Breadth-First: the solution found by the\nalgorithm is 3 operations away from the initial state, while the existing\nsolution found before has been completely ignored by this algorithm. The main\nadvantage of this algorithm is its space complexity to find a given solution at\na depth $d$ is indeed linear, and its execution to find a solution should\naverage faster than Breadth-First Search \\cite{zhang-1995-bnb}. However,\nDepth-First Search is not complete in implicit graphs: since the depth of the\ntree can be infinite, the search can get lost expanding nodes that do not lead\nto a recursion \\cite{rusell-2003-aima}.\\\\\n\nFor that reason, the Iterative-Deepening Depth-First Search was developed: by\nlimiting the depth at which a Depth-First algorithm can explore, the\nbacktracking is used to explore certain depths \\cite{korf-1985-depth}. This\neliminates the lack of completeness, and makes IDDFS equivalent to a\nBreadth-First Search if the step used to increase the depth bound is one. It is\nhowever important to remark that this algorithm is faster than BFS in the last\niteration but most likely slower if taking into account the cumulative time of\nall depth executions. Its time and space complexity are the same of Depth-First\nSearch, but it is complete and optimal if the depth is increased one by one.\\\\\n\nThe last uninformed algorithm to explore is Uniform Cost Search. This algorithm\nperforms a brute-force search expanding first the lowest-cost node, using a\nBFS-like fashion to explore the search space \\cite{rusell-2003-aima}. This\nalgorithm is sometimes referred to as Dijkstra's Algorithm, although the latter\nis considered to be subtly different and since we are applying it to implicit\ngraphs, the algorithm will be treated as UCS along the thesis\n\\cite{felner-2011-dijkstra}. This algorithm relies on a priority queue that\nsorts the nodes and always returns the one whose current cost is lower. For\nthat reason, Uniform Cost Search can be seen as a variation of Breadth-First\nSearch that takes into account variable cost paths and thus always return the\nlowest cost solution, instead the shorter one. UCS is, therefore, complete and\noptimal.\\\\\n\n\\subsubsection{Informed Algorithms}\n\nInformed algorithms are those that perform searches using a heuristic function.\nThis function evaluates a state and returns a value that presents how close\nthat state is to a solution. Using those values, the states can be ranked on\nhow convenient they are for the search (the closer to the solution, the more\nrelevant to the search is to expand such state) \\cite{pearl-1984-heuristics}.\\\\\n\nThe main informed algorithm to take into account is the well-known A*\nalgorithm. First developed in 1968 as an extension of Dijkstra's algorithm, it\nfeatures an evaluation function that takes into account both the cost of a node\nand its heuristic value \\cite{hart-1968-formal}. The algorithm uses a priority\nqueue to sort the nodes in ascending order of $f$, the aforementioned\nevaluation function. This function is defined as $f(n) = g(n) + h(n)$ where $g$\nis the cost of the node and $h$ is the value of the heuristic function. That\nway, the algorithm expands the nodes keeping a balance of current and expected\ncost to obtain the solution. Two examples of this algorithm can be found in\nFigure \\ref{tree:astar}.\\\\\n\n\\begin{figure}[ht]\n\\centering\n\\includegraphics[width=0.8\\textwidth]{img/astar.png}\n\\caption{A* Search executions using two different heuristics}\n\\label{tree:astar}\n\\end{figure}\n\nIn the first execution of Figure \\ref{tree:astar} shows how the nodes are\nexpanded using the values computed at each iteration. At each new iteration,\nthe branch expanded is the one with lower projected costs. In the second\nexecution, we can see how a different heuristic returns the same solution but\nexpanding less nodes. This introduces an important concept of A*: with a\nperfect heuristic, A* performs a perfect search, expanding only the necessary\nnodes to obtain and ensure that the solution found is optimal\n\\cite{dechter-1985-astar}. This implies that the heuristic is relevant for the\nnode performance, but not only that: A* is only complete and optimal if the\nheuristic function used is admissible, that is, if it never underestimates the\nactual cost of getting from a node to a solution \\cite{pearl-1984-heuristics}.\nIts complexity in worst case scenario is the one of Breadth-First Search;\n$O(b^{d+1})$.\\\\\n\nFollowing a similar idea, but using iterative-deepening for obtaining a better\nmemory performance, it is important to mention Iterative-Deepening A*\n\\cite{korf-1985-depth}. The basic idea behind it is to perform a depth-first\nsearch using the $f$ function of A*. This results in a linear-memory algorithm,\nthat explores the solutions in thresholds defined by $f$ as a cutoff function.\nThis makes an interesting algorithm when memory constraints exist, and it is\nensured to return the shortest path from the initial state to a solution as\nlong as the heuristic is admissible.\\\\\n\n\\begin{figure}[ht]\n\\centering\n\\includegraphics[width=0.8\\textwidth]{img/dfbnb.png}\n\\caption{Depth-First Branch and Bound Search execution on the tree}\n\\label{tree:dfbnb}\n\\end{figure}\n\nLast, it is important to remark the family of Branch and Bound algorithms.\nThese algorithms uses a solution that is found to keep on the search, using the\ncost of the current best solution as a bound for the rest of the search\n\\cite{zhang-1995-bnb}. These algorithms result as well in linear-memory\nexecutions but ensure that the optimal solution is found (since the execution\nonly ends when the search space is exhausted). It is possible to see an example\nexecution of Depth-First Branch and Bound in Figure \\ref{tree:dfbnb}, where\neach new solution found creates a new bound for the search (the red highlight\nindicates the part of search tree that is out of bounds when tried to be\nexpanded).\\\\\n\nThese algorithms can be tuned to use different bounds like depth, cost or other\nevaluations. It is specially relevant for this project an informed version of\nthis algorithm proposed in \\cite{zhang-1995-bnb}, that uses the $f$ function to\nexpand the nodes and creates bounds using cost of each solution found.\\\\\n\n\n\\subsubsection{Libraries}\n\nDue to being more appropriate for the performance that is in general desired,\nwe can find that the most amount of work on Heuristic Search is done in\nimperative, fast languages like C++ or Java.\\\\\n\nIn C++, we can find full search frameworks like \\emph{HOG2} \\cite{hog2},\n\\emph{Research code for heuristic search} \\cite{cpp-search} or \\emph{The\n  Heuristic Search Research Framework} \\cite{goldenberg-2017-framework}. All\nthese frameworks offer a full set of algorithms and procedures to override the\ndefault implementations (such as cost, heuristic or expansion functions) in\norder to adapt the library's behavior to the problem at hand. Also, these\nframeworks offer visual representations options; a feature which is indeed the\nmain goal in the case of \\emph{The Heuristic Search Research Framework}, that\noffers a general visualization of algorithm behavior instead of domain specific\nones. On the other hand, in Java we can find similar projects like\n\\emph{Combinatorial Search for Java} \\cite{cs4j} or \\emph{AIMA}\n\\cite{java-aima}.\\\\\n\nTrying to find similar projects in functional languages is more complicated\nthan that. However, one can find interesting projects like \\emph{AIMA} written\nin Common Lisp \\cite{lisp-aima} or even a complete search framework written in\nOCaml \\cite{ocaml-search}. In Haskell, however, projects of this size are\nnowhere to be found: All the algorithms are distributed in individual packages\nwith completely different implementations, as well as the data structures used\nto perform the search.\\\\\n\n\\subsection{Haskell}\n\nHaskell's first version was released in 1990 after the efforts of a committee\nin FPCA '87 for creating an open standard for a ``non-strict, purely functional\nlanguage'' \\cite{haskell-history}. Haskell's main features have remain patent\nin the language, but constantly evolving: the language's main pillars are\n\\cite{haskell-98, haskell-2010}:\n\n\\begin{enumerate}\n\\item \\textbf{Strong and statically typed}: the types are checked at compile\n  time. That makes the run-time be sure that every function will get as\n  parameter the expected object, making it more robust. However, no explicit\n  type declaration is needed (although it is usually considered a good\n  practice); types can be inferred most of the times by the compiler.\n\\item \\textbf{Purely functional}: this type system is what allows Haskell to be\n  purely functional. For Haskell, a string literal is of type \\texttt{String},\n  while an user's input on the prompt is a \\texttt{IO String}. While at first\n  shocking, this quality of Haskell maintains the referential transparency\n  intact: the same function call with the same arguments is guaranteed to\n  provide always the same output. All side effects are contained into monads\n  (like the aforementioned \\texttt{IO} monad) so they are contained and\n  isolated.\n\\item \\textbf{Lazy}: the fact that Haskell's evaluation is lazy (contrary to\n  more common strict evaluation) means that a expression is only computed if\n  its result is really necessary at a moment in time. This allows expressions\n  to be defined in a much higher level: telling the computer what something is\n  rather than how to compute it, and leaving the details of it to the compiler.\n  Lazy evaluation provides for instance the use of infinite lists (since only\n  the necessary part will be actually evaluated).\n\\item \\textbf{Concurrent abstractions}: All the aforementioned characteristics\n  also add up to the fact that the compiler is able to include concurrent\n  optimizations into regular Haskell code thanks to its high-level definitions.\n\\end{enumerate}\n\nCurrently, the Glasgow Haskell Compiler (GHC) can be almost considered the\nde-facto standard in Haskell compilers: widely spread and with an impressive\ninterface of pragmas to enable different optimizations by the compiler, it is\nthe compiler used for most projects because of the language extensions it\nprovides. Regarding packaging frameworks we can use Cabal, as a more\nestablished option; or Stack, that wraps around Cabal configurations offering\nmore robust dependency installs and builds. Both frameworks offer several tools\nfor compilation, packaging, documentation, distribution, testing and profiling.\nThese tools will be explained in detail as they appear in the thesis.\\\\\n\nAlthough not yet mainstream, Haskell is a language used in the industry that is\nspecially well-regarded in web backends: its concurrency is based in threads\nthat are so light that can be spawned in much larger densities than average\nthreads \\cite{epstein-2011-cloud}. This fits specially well in a web server,\nwhere every request can get one thread without compromising performance.\nHaskell's type system also prevents different attacks (like SQL/XSS injection)\nto be performed in these systems \\cite{snoyman-2015-yesod}.\n\n\\newpage\n\n%%% Local Variables:\n%%% TeX-master: \"tfg\"\n%%% End:", "meta": {"hexsha": "9bf0959dd45171e11db3a0ff2f207fd25e9898e9", "size": 16435, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/2-state-art.tex", "max_stars_repo_name": "DiegoVicen/bachelor-thesis", "max_stars_repo_head_hexsha": "feb1657ef4082402434d5e6519ec57eac85ac7a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-01-25T13:07:49.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-02T18:49:06.000Z", "max_issues_repo_path": "thesis/2-state-art.tex", "max_issues_repo_name": "DiegoVicen/bachelor-thesis", "max_issues_repo_head_hexsha": "feb1657ef4082402434d5e6519ec57eac85ac7a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis/2-state-art.tex", "max_forks_repo_name": "DiegoVicen/bachelor-thesis", "max_forks_repo_head_hexsha": "feb1657ef4082402434d5e6519ec57eac85ac7a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 57.2648083624, "max_line_length": 79, "alphanum_fraction": 0.7956191056, "num_tokens": 3801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3209524278953049}}
{"text": "\\RequirePackage[l2tabu, orthodox]{nag}\n\\documentclass[10pt, a4paper]{article}\n\n\\usepackage[T1]{fontenc}\n\\usepackage{fancyvrb}\n\n\\title{The dvi-format and the program dvitype}\n\\author{Ernst Reissner (rei3ner@arcor.de)}\n\n\\begin{document}\n\n\\maketitle\n\\tableofcontents\n\n\\section{Introduction}\nThis document describes the dvi file format \ntraditionally used by \\LaTeX{} \nand still in use with \\texttt{htlatex} and that like. \n\n\nA \\texttt{DVI} file is a stream of 8-bit bytes, which may be regarded as a\nseries of commands in a machine-like language. The first byte of each command\nis the operation code, and this code is followed by zero or more bytes\nthat provide parameters to the command. The parameters themselves may consist\nof several consecutive bytes; \nfor example, the `\\texttt{set\\_rule}' command has two\nparameters, each of which is four bytes long. Parameters are usually\nregarded as nonnegative integers; but four-byte-long parameters,\nand shorter parameters that denote distances, can be\neither positive or negative. Such parameters are given in two's complement\nnotation. For example, a two-byte-long distance parameter has a value between\n$-2^{15}$ and $2^{15}-1$.\n\n\nA \\texttt{DVI} file consists of a ``preamble,'' \nfollowed by a sequence of one or more ``pages,'' \nfollowed by a ``postamble''. \nThe preamble is simply a \\texttt{pre} command, \nwith its parameters that define the dimensions used in the file; \nthis must come first.  \nEach ``page'' consists of a \\texttt{bop} command,\nfollowed by any number of other commands that tell where characters are to\nbe placed on a physical page, followed by an \\texttt{eop} command. \nThe pages appear in the order that they were generated, \nnot in any particular numerical order. \nIf we ignore \\texttt{nop} commands and \\texttt{fnt\\_def} commands\n(which are allowed between any two commands in the file), \neach \\texttt{eop} command is immediately followed by a \\texttt{bop} command, \nor by a \\texttt{post} command; \nin the latter case, there are no more pages in the file, \nand the remaining bytes form the postamble.  \nFurther details about the postamble will be explained later.\n\nSome parameters in \\texttt{DVI} commands are ``pointers''. \nThese are four-byte quantities that give the location number \nof some other byte in the file; \nthe first byte is number~0, then comes number~1, and so on. \nFor example, one of the parameters of a \\texttt{bop} command \npoints to the previous \\texttt{bop};\nthis makes it feasible to read the pages in backwards order, \nin case the results are being directed to a device \nthat stacks its output face up. \nSuppose the preamble of a \\texttt{DVI} file occupies bytes 0 to 99. \nNow if the first page occupies bytes 100 to 999, say, \nand if the second page occupies bytes 1000 to 1999, \nthen the \\texttt{bop} that starts in byte 1000\npoints to 100 and the \\texttt{bop} that starts in byte 2000 points to 1000. \n(The very first \\texttt{bop}, \ni.e., the one that starts in byte 100, has a pointer of $-1$.)\n\n\nThe  \\texttt{DVI} format is intended to be both \ncompact and easily interpreted by a machine. \nCompactness is achieved by making most of the information implicit \ninstead of explicit. \nWhen a \\texttt{DVI}-reading program reads the commands for a page, \nit keeps track of several quantities: \n%\n\\begin{itemize}\n\\item\nThe current font $f$ is an integer; \nthis value is changed only by \\texttt{fnt} and \\texttt{fnt\\_num} commands. \n\\item\nThe current position on the page \nis given by two numbers called the horizontal and vertical coordinates,\n$h$ and $v$. \nBoth coordinates are zero at the upper left corner of the page; \nmoving to the right corresponds to increasing the horizontal coordinate, and\nmoving down corresponds to increasing the vertical coordinate. \nThus, the coordinates are essentially Cartesian, \nexcept that vertical directions are flipped; \nthe Cartesian version of $(h,v)$ would be $(h,-v)$.  \n\\item\nThe current spacing amounts \nare given by four numbers $w$, $x$, $y$, and $z$,\nwhere $w$ and~$x$ are used for horizontal spacing and where $y$ and~$z$\nare used for vertical spacing. \n\\item\nThere is a stack containing $(h,v,w,x,y,z)$ values; \nthe \\texttt{DVI} commands \\texttt{push} and \\texttt{pop} are used \nto change the current level of operation. \nNote that the current font~$f$ is not pushed and popped; \nthe stack contains only information about positioning.\n\\end{itemize}\n\nThe values of $h$, $v$, $w$, $x$, $y$, and $z$ are signed integers having up\nto 32 bits, including the sign. Since they represent physical distances,\nthere is a small unit of measurement such that increasing $h$ by~1 means\nmoving a certain tiny distance to the right. The actual unit of\nmeasurement is variable, as explained below. \n\nHere is a list of all the commands that may appear in a \\texttt{DVI} file. \nEach command is specified by its symbolic name (e.g., \\texttt{bop}), \nits opcode byte (e.g., 139), and its parameters (if any). \nThe parameters are followed by a bracketed number \ntelling how many bytes they occupy; for example,\n`$p[4]$' means that parameter $p$ is four bytes long. \n\n\\section{The Op-Codes}\\label{sec:opCodes}\n\n\\begin{itemize}\n\n\\item[0-127] \\texttt{set\\_char\\_$<d>$ $d$} where $d\\in\\{0,\\dots,127\\}$. \n\nTypeset character number~$d$ from font~$f$ \nsuch that the reference point of the character is at $(h,v)$. \nThen increase $h$ by the width of that character. \nNote that a character may have zero or negative width, \nso one cannot be sure that $h$ will advance after this command; \nbut $h$ usually does increase.\n\n\\item[128-131] \\texttt{set\\_$<d>$ $128+d$ $c[d]$} where $d\\in\\{1,\\dots,4\\}$. \nSame as \\texttt{set\\_char\\_0}, except that character number~$c$ is typeset. \nNote that $d$ determines the number of characters. \n\\texttt{set\\_$2$} is intended for oriental languages \nwith a script with a lot of characters. \n\n\n\\item[132] \\texttt{setrule $132$ $a[4]$ $b[4]$}. \nTypeset a solid black rectangle of height $a$ and width $b$, \nwith its bottom left corner at $(h,v)$. \nThen set $h:=h+b$. If either $a<=0$ or $b<=0$, nothing should be typeset. \nNote that if $b<0$, the value of $h$ will decrease \neven though nothing else happens. \nPrograms that typeset from \\texttt{DVI} files \nshould be careful to make the rules line up carefully \nwith digitized characters, \nas explained in connection with the \\texttt{rule\\_pixels} subroutine below.\n\n\\item[137] \\texttt{put$<d>$ $132+d$ $c[d]$} where $d\\in\\{1,\\dots,4\\}$. \nTypeset character number~$c$ from font~$f$\nsuch that the reference point of the character is at $(h,v)$. \n(The `put' commands are exactly like the `set' commands, \nexcept that they simply put out a character or a rule \nwithout moving the reference point afterwards.)\n\n\n\\item[137] \\texttt{put\\_rule $137$ $a[4]$ $b[4]$}. \nSame as \\texttt{set\\_rule}, except that $h$ is not changed. \n\n\\item[138] \\texttt{nop}. \nNo operation, do nothing. Any number of \\texttt{nop}'s\nmay occur between \\texttt{DVI} commands, \nbut a \\texttt{nop} cannot be inserted \nbetween a command and its parameters or between two parameters. \n\n\\item[139] \\texttt{bop $139$ $c_0[4]$ $c_1[4]$ $\\ldots$ $c_9[4]$ $p[4]$}. \nIndicates the beginning of a page: \nSet $(h,v,w,x,y,z):=(0,0,0,0,0,0)$ and set the stack empty. \nSet the current font $f$ to an undefined value.  \nThe ten $c_i$ parameters can be used to identify pages, \nif a user wants to print only part of a \\texttt{DVI} file; \n\\TeX82 gives them the values of \\texttt{count0} $\\ldots$ \\texttt{count9} \nat the time \\texttt{shipout} was invoked for this page.  \nThe parameter $p$ points to the previous \\texttt{bop} command in the file, \nwhere the first \\texttt{bop} has $p=-1$.\n\n\\item[140] \\texttt{eop $140$} \nEnd of page: \nPrint what you have read since the previous \\texttt{bop}. \nAt this point the stack should be empty. \n(The \\texttt{DVI}-reading programs that drive most output devices \nwill have kept a buffer of the material \nthat appears on the page that has just ended. \nThis material is largely, but not entirely, \nin order by $v$ coordinate and (for fixed $v$) by $h$~coordinate; \nso it usually needs to be sorted into some order that is\nappropriate for the device in question. \n\\texttt{DVItype} does not do such sorting.)\n\n\n\\item[141] \\texttt{push $141$}. \nPush the current values of $(h,v,w,x,y,z)$ onto the top of the stack; \ndo not change any of these values. Note that $f$ is not pushed. \n\n\n\\item[142] \\texttt{pop $142$}. \nPop the top six values off of the stack and assign them to $(h,v,w,x,y,z)$. \nThe number of pops should never exceed the number of pushes, \nsince it would be highly embarrassing if the stack were empty \nat the time of a \\texttt{pop} command.\n\n\\item[143-146] \\texttt{right$<d>$ $142+d$ $b[d]$} where $d\\in\\{1,\\dots,4\\}$. \nSet $h:=h+b$, i.e., move right $b$ units.\nThe parameter is a signed number in two's complement notation; \nif $b<0$, the reference point actually moves left.\n\n\\item[147] \\texttt{w0 $147$ }. \nSet $h:=h+w$; i.e., move right $w$ units. With luck,\nthis parameterless command will usually suffice, because the same kind of motion\nwill occur several times in succession; the following commands explain how\n$w$ gets particular values. \n\n\\item[148-151] \\texttt{w$<d>$ $147+d$ $b[d]$} where $d\\in\\{1,\\dots,4\\}$. \nSet $w:=b$ and $h:=h+b$. \nThe value of $b$ is a signed quantity in two's complement notation. \nThis command changes the current $w$~spacing and moves right by $b$.\n\n\n\\item[152] \\texttt{x0 $152$}. \nSet $h:=h+x$; i.e., move right $x$ units. The `$x$'\ncommands are like the `$w$' commands except that they involve $x$ instead\nof $w$.\n\n\\item[153-156] \\texttt{x$<d>$ $152+d$ $b[d]$} where $d\\in\\{1,\\dots,4\\}$. \nSet $x:=b$ and $h:=h+b$. \nThe value of $b$ is a signed quantity in two's complement notation. \nThis command changes the current $x$~spacing and moves right by $b$.\n\n\n\\item[159] \\texttt{down$<d>$ $156+d$ $b[d]$} where $d\\in\\{1,\\dots,4\\}$. \nSet $v:=v+a$, i.e., move down $a$ units. \nThe parameter is a signed number in two's complement notation; \nif $a<0$, the reference point actually moves up.\n\n\n\\item[161] \\texttt{y0 $161$}. \nSet $v:=v+y$; i.e., move down $y$ units. \nWith luck, this parameterless command will usually suffice, \nbecause the same kind of motion will occur several times in succession.\n\n\\item[162-165] \\texttt{y$<d>$ $161+d$ $a[d]$} where $d\\in\\{1,\\dots,4\\}$. \nSet $y:=a$ and $v:=v+a$. \nThe value of $a$ is a signed quantity in two's complement notation. \nThis command changes the current $y$~spacing and moves down by $a$. \n\n\\item[166] \\texttt{z0 $166$}. \nSet $v:=v+z$; i.e., move down $z$ units. \nWith luck, this parameterless command will usually suffice, \nbecause the same kind of motion will occur several times in succession.\nThe `\\texttt{z}' commands are like the `\\texttt{y}' commands \nexcept that they involve $z$ instead of $y$. \n\n\\item[167-170] \\texttt{z$<d>$ $166+d$ $a[d]$} where $d\\in\\{1,\\dots,4\\}$. \nSet $y:=a$ and $v:=v+a$. \nThe value of $a$ is a signed quantity in two's complement notation. \nThis command changes the current $z$~spacing and moves down by $a$. \n\n\n\\item[171] \\texttt{fntnum0 $171$}. \nSet $f:=0$. Font 0 must previously have been\ndefined by a \\texttt{fnt\\_def} instruction, as explained below.\n\n\\item[172-234] \\texttt{fntnum$<d>$ $171+d$ } where $d\\in\\{1,\\dots,63\\}$. \nSet $f:=d$. \n\n\n\\item[235-238] \\texttt{fnt$<d>$ $235+d$ $k[d]$} where $d\\in\\{1,\\dots,4\\}$. \nSet $f:=k$. \nAn application of \\texttt{fnt$2$} or higher \nmaybe used for fonts with colors and texture information. \n\n\\item[239-242] \\texttt{xxx$<d>$ $238+d$ $k[2]$ $x[k]$} \nwhere $d\\in\\{1,\\dots,4\\}$. \nThis command is undefined in general; \nit functions as a $(k+2)$-byte \\texttt{nop} \nunless special \\texttt{DVI}-reading programs are being used. \n\\TeX82 generates \\texttt{xxx1} when a short enough \\texttt{special} appears, \nsetting $k$ to the number of bytes being sent. \nIt is recommended that $x$ be a string having the form of a keyword \nfollowed by possible parameters relevant to that keyword.\n\n\\item[243-246] \\texttt{fntdef$<d>$ $242+d$ \n$k[d]$ $c[4]$ $s[4]$ $d[4]$ $a[1]$ $l[1]$ $n[a+l]$} \nwhere $d\\in\\{1,\\dots,4\\}$. \nDefine font $k$; font definitions will be explained shortly.\n\n\\item[247] \\texttt{pre $247$ $i[1]$ $num[4]$ $den[4]$ $mag[4]$ $k[1]$ $x[k]$}.\nBeginning of the preamble; \nthis must come at the very beginning of the file. \nParameters $i$, $num$, $den$, $mag$, $k$, and $x$ are explained below.\n\n\\item[248] \\texttt{post $248$}. \nBeginning of the postamble, see below. \n\n\\item[249] \\texttt{post\\_post $249$}. \nEnding of the postamble, see below. \n\n\\item[250-255] undefined currently. \n\\end{itemize}\n\n\\section{The Preamble}\n\\label{sec:preamble}\n\nThe preamble contains basic information about the file as a whole. \nAs stated above, there are six parameters:\n%\n\\[\n\\hbox{i[1]| num[4], den[4], mag[4], k[1], x[k]}\n\\]\n%\nThe $i$ byte identifies \\texttt{DVI} format; \ncurrently this byte is always set to~2. \n(The value $i=3$ is currently used for an extended format that\nallows a mixture of right-to-left and left-to-right typesetting.\nSome day we will set $i=4$, when \\texttt{DVI} format makes another\nincompatible change---perhaps in the year 2048.)\n\nThe next two parameters, $num$ and $den$, are positive integers that define\nthe units of measurement; they are the numerator and denominator of a\nfraction by which all dimensions in the \\texttt{DVI} file could be multiplied\nin order to get lengths in units of $10^{-7}$ meters. (For example, there are\nexactly 7227 \\TeX\\ points in 254 centimeters, and \\TeX82 works with scaled\npoints where there are $2^{16}$ sp in a point, so \\TeX82 sets $num=25400000$\nand $den=7227\\cdot2^{16}=473628672$.)\n\n\nThe $mag$ parameter is what \\TeX82 calls \\texttt{mag}, i.e., 1000 times the\ndesired magnification. The actual fraction by which dimensions are\nmultiplied is therefore $mn/1000d$. Note that if a \\TeX\\ source document\ndoes not call for any `{true}' dimensions, and if you change it only by\nspecifying a different \\texttt{mag} setting, the \\texttt{DVI} file that \\TeX\\\ncreates will be completely unchanged except for the value of $mag$ in the\npreamble and postamble. (Fancy \\texttt{DVI}-reading programs allow users to\noverride the $mag$~setting when a \\texttt{DVI} file is being printed.)\n\nFinally, $k$ and $x$ allow the \\.{DVI} writer to include a comment, which is not\ninterpreted further. The length of comment $x$ is $k$, where $0<=k<256$.\n\n\n\\section{Font definitions}\n\\label{sec:fontDef}\n\nFont definitions for a given font number $k$ contain further parameters\n\\[\n\\hbox{$c[4]$ $s[4]$ $d[4]$ $a[1]$ $l[1]$ $n[a+l]$.}\n\\]\nThe four-byte value $c$ is the check sum that \\TeX\\ (or whatever program\ngenerated the \\texttt{DVI} file) found in the \\texttt{TFM} file for this font;\n$c$ should match the check sum of the font found by programs that read\nthis \\texttt{DVI} file.\n\n\nParameter $s$ contains a fixed-point scale factor that is applied to the\ncharacter widths in font $k$; font dimensions in \\texttt{TFM} files and other\nfont files are relative to this quantity, which is always positive and\nless than $2^{27}$. \nIt is given in the same units as the other dimensions of the \\texttt{DVI} file. \nParameter $d$ is similar to $s$; it is the ``design size,'' \nand (like~$s$) it is given in \\texttt{DVI} units. \nThus, font $k$ is to be used at $mag\\cdot s/1000d$ times its normal size.\n\nThe remaining part of a font definition gives the external name of the font,\nwhich is an ASCII string of length $a+l$. The number $a$ is the length\nof the ``area'' or directory, and $l$ is the length of the font name itself;\nthe standard local system font area is supposed to be used when $a=0$.\nThe $n$ field contains the area in its first $a$ bytes.\n\nFont definitions must appear before the first use of a particular font number.\nOnce font $k$ is defined, it must not be defined again; \nhowever, we shall see below \nthat font definitions appear in the postamble as well as in the pages, \nso in this sense each font number is defined exactly twice, if at all. \nLike \\texttt{nop} commands, \nfont definitions can appear before the first \\texttt{bop}, \nor between an \\texttt{eop} and a \\texttt{bop}. \n\n\\section{The Postamble}\n\\label{sec:postamble}\n\nThe last page in a \\texttt{DVI} file is followed by `\\texttt{post}'; \nthis command introduces the postamble, \nwhich summarizes important facts that \\TeX\\ has accumulated about the file, \nmaking it possible to print subsets of the data with reasonable efficiency. \nThe postamble has the form\n%$$\\vbox{\\halign{\\hbox{#\\hfil}\\cr\n%  \\texttt{post} |p[4]| |num[4]| |den[4]| |mag[4]| |l[4]| |u[4]| |s[2]| |t[2]|\\cr\n%  $\\langle\\,$font definitions$\\,\\rangle$\\cr\n%  \\texttt{post_post} |q[4]| |i[1]| 223's$[{\\G}4]$\\cr}}$$\nHere $p$ is a pointer to the final \\texttt{bop} in the file. The next three\nparameters, $num$, $den$, and $mag$, are duplicates of the quantities that\nappeared in the preamble.\n\nParameters $l$ and $u$ give respectively the height-plus-depth of the tallest\npage and the width of the widest page, in the same units as other dimensions\nof the file. These numbers might be used by a \\texttt{DVI}-reading program to\nposition individual ``pages'' on large sheets of film or paper; however,\nthe standard convention for output on normal size paper is to position each\npage so that the upper left-hand corner is exactly one inch from the left\nand the top. \nExperience has shown that it is unwise to design \\texttt{DVI}-to-printer\nsoftware that attempts cleverly to center the output; a fixed position of\nthe upper left corner is easiest for users to understand and to work with.\nTherefore $l$ and~$u$ are often ignored.\n\nParameter $s$ is the maximum stack depth \n(i.e., \nthe largest excess of \\texttt{push} commands over \\texttt{pop} commands)\n needed to process this file. \nThen comes $t$, the total number of pages (\\texttt{bop} commands) present.\n\nThe postamble continues with font definitions, \nwhich are any number of \\texttt{fnt\\_def} commands as described above, \npossibly interspersed with \\texttt{nop} commands. \nEach font number that is used in the \\texttt{DVI} file must be defined\nexactly twice: Once before it is first selected by a \\texttt{fnt} command, \nand once in the postamble.\n\n@ The last part of the postamble, following the \\texttt{post\\_post} byte \nthat signifies the end of the font definitions, \ncontains $q$, a pointer to the \\texttt{post} command \nthat started the postamble.  \nAn identification byte, $i$, comes next; \nthis currently equals~2, as in the preamble.\n\nThe $i$ byte is followed by four or more bytes that are all equal to\nthe decimal number 223 (i.e., @'337 in octal). \\TeX\\ puts out four to seven of\nthese trailing bytes, until the total length of the file is a multiple of\nfour bytes, since this works out best on machines that pack four bytes per\nword; but any number of 223's is allowed, as long as there are at least four\nof them. In effect, 223 is a sort of signature that is added at the very end.\n\n\nThis curious way to finish off a \\texttt{DVI} file makes it feasible for\n\\texttt{DVI}-reading programs to find the postamble first, on most computers,\neven though \\TeX\\ wants to write the postamble last. Most operating\nsystems permit random access to individual words or bytes of a file, so\nthe \\texttt{DVI} reader can start at the end and skip backwards over the 223's\nuntil finding the identification byte. Then it can back up four bytes, read\n$q$, and move to byte $q$ of the file. This byte should, of course,\ncontain the value 248 (\\texttt{post}); now the postamble can be read, so the\n\\texttt{DVI} reader discovers all the information needed for typesetting the\npages. Note that it is also possible to skip through the \\texttt{DVI} file at\nreasonably high speed to locate a particular page, if that proves\ndesirable. \nThis saves a lot of time, \nsince \\texttt{DVI} files used in production jobs tend to be large.\n\n\\begin{Verbatim}[fontsize=\\scriptsize]\nftp://ftp.rrzn.uni-hannover.de/pub/mirror/tex-archive/systems/knuth/dist/texware/dvitype.web\n\\end{Verbatim}\n\\end{document}\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: t\n%%% End:\n", "meta": {"hexsha": "3d115d13c943993ff17a594ee5e8fc5266b131dc", "size": 20010, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "maven-latex-plugin/src/site/tex/dvi/dviFormat.tex", "max_stars_repo_name": "Reissner/maven-latex-plugin", "max_stars_repo_head_hexsha": "b5da5d2a60cd73a16c6c9b1fe7f0813d2604e4c5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "maven-latex-plugin/src/site/tex/dvi/dviFormat.tex", "max_issues_repo_name": "Reissner/maven-latex-plugin", "max_issues_repo_head_hexsha": "b5da5d2a60cd73a16c6c9b1fe7f0813d2604e4c5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "maven-latex-plugin/src/site/tex/dvi/dviFormat.tex", "max_forks_repo_name": "Reissner/maven-latex-plugin", "max_forks_repo_head_hexsha": "b5da5d2a60cd73a16c6c9b1fe7f0813d2604e4c5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.6899563319, "max_line_length": 92, "alphanum_fraction": 0.7264867566, "num_tokens": 5917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.32095242789530487}}
{"text": "\\documentclass[aps, prd,\n%%%%%%%%%%%%%\n% Choose one of the two following options:\n%preprint,%\n%onecolumn,\ntwocolumn,%\n%%%%%%%%%%%%\n%tightenlines,\nsuperscriptaddress,\nshowpacs, nofootinbib, eqsecnum, amsmath, amssymb, floatfix\n%floats\n]{revtex4}\n%\\maxdeadcycles=1000\n%\\pdfimageresolution=72x\n\n\\usepackage{hyperref}\n\\usepackage{bm}\n\\usepackage{graphicx}\n\\usepackage[usenames]{color}\n\\usepackage{ulem}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\n\\maxdeadcycles=5000\n\n%%%%%%%%%%%%\n% Uncomment the following line to display all labels\n%\\usepackage{showkeys}\n%%%%%%%%%%%%\n\n\\allowdisplaybreaks\n% Better to do this locally for a given very long equation:\n% {\\allowdisplaybreaks \\begin{eqnarray} ... \\end{eqnarray}}\n% \\noindent\n\n\\newcommand{\\ui}{\\mathrm{i}}\n\\newcommand{\\ud}{\\mathrm{d}}\n\\newcommand{\\uD}{\\mathrm{D}}\n\\newcommand{\\bmSeffp}{{\\bm{S}_{0}^+}}\n\\newcommand{\\bmSeffm}{{\\bm{S}_{0}^-}}\n\\newcommand{\\Seffp}{{S_{0}^+}}\n\\newcommand{\\Seffm}{{S_{0}^-}}\n\n\\newcommand{\\IAP}{\\affiliation{Institut d'Astrophysique de Paris,\n   UMR 7095 CNRS Universit\\'e Pierre \\& Marie Curie, 98$^{\\text{bis}}$\n   boulevard Arago, 75014 Paris, France}}\n\\newcommand{\\Maryland}{\\affiliation{Maryland Center for Fundamental\n    Physics \\& Joint Space-Science Institute,\\\\ Department of Physics,\nUniversity of Maryland, College\n    Park, MD 20742, USA}}\n\n\\newcommand{\\red}{\\textcolor{red}}\n\\newcommand{\\blue}{\\textcolor{blue}}\n\n\\newcommand{\\comment}[1]{\\textcolor{red}{[#1]}}\n\\newcommand{\\tanja}[1]{\\textcolor{green}{#1}}\n\\newcommand{\\gf}[1]{\\textcolor{cyan}{#1}}\n\\newcommand{\\ab}[1]{\\textcolor{blue}{#1}}\n\n\\begin{document}\n\n\\title{Spin effects on gravitational waves from inspiraling compact binaries\nat second post-Newtonian order}\n\n\\author{Alessandra Buonanno} \\Maryland%\n\\author{Guillaume Faye} \\IAP %\n\\author{Tanja Hinderer} \\Maryland %\n\n\\date{\\today}\n\n\\begin{abstract}\n  We calculate the gravitational waveform for spinning, precessing compact\n  binary inspirals through second post-Newtonian order in the amplitude. When\n  spins are collinear with the orbital angular momentum and the orbits are\n  quasi-circular, we further provide explicit expressions for the\n  gravitational-wave polarizations and the decomposition into spin-weighted\n  spherical-harmonic modes. Knowledge of the second post-Newtonian spin terms\n  in the waveform could be used to improve the physical content of analytical\n  templates for data analysis of compact binary inspirals and for more\n  accurate comparisons with numerical-relativity simulations.\n\\end{abstract}\n\n\\pacs{04.30.-w, 04.25.-g}\n\n\\maketitle\n\n\\section{Introduction}\n\\label{sec:intro}\n\nCoalescing compact binary systems are a key source of gravitational\nradiation for ground-based gravitational-wave detectors such as the\nadvanced Laser Interferometer Gravitational Wave Observatory\n(LIGO)~~\\cite{Abbott:2007}, the advanced Virgo~\\cite{Acernese:2008},\nthe GEO-HF~\\cite{Grote:2008zz}, the Large Cryogenic Gravitational\nTelescope (LCGT) (or KAGRA)~\\cite{Kuroda:2010}, coming into\noperation within the next few years, and future space-based\ndetectors~\\cite{lisa,ESALISAwebsite}. For this class of\ngravitational-wave sources, the signal detection and interpretation\nwill be based on the method of matched filtering~\n\\cite{Finn1992,Finn1993}, where the noisy detector output is cross\ncorrelated with a bank of theoretical templates. The accuracy\nrequirement on the templates is that they remain as much as possible\nphase coherent with the signal over the hundreds to thousands of\ncycles of inspiral that are within the detector's sensitive\nbandwidth.\n\nConstructing such accurate templates has motivated a significant\nresearch effort during the past 30 years. In the regime where the\nseparation between the two bodies is large, gravitational waveforms\ncan be computed using the post-Newtonian (PN) approximation\nmethod~\\cite{Sasaki:2003xr,\n  Blanchet2006, Futamase:2007zz}. In the post-Newtonian scheme, the results\nare written as an asymptotic expansion in powers of $v_A/c$, with\n$v_A$ being the magnitude of the orbital coordinate velocity\n$\\bm{v}_A$ of body $A$ at a given time. This approximation is\nphysically relevant for $v_A/c \\ll 1$, i.e. in the so-called\ninspiraling regime where the radiation reaction forces, of order\n$\\sim (v_A/c)^5 $ are negligible over an orbital period and act\nadiabatically on a quasiconservative system. In the domain of\nvalidity of the post-Newtonian scheme, the separation $r \\sim (G\nm_A/v^2)\\sim (c/v)^2$, with $m=m_1 + m_2$ and $v = |\\bm{v}| \\equiv\n|\\bm{v}_1 - \\bm{v}_2 |$, remains large with respect to the radii of\nboth compact objects $\\sim G m_A/c^2$ or, in other words, the bodies\ncan be regarded effectively as point particles.\n\nPost-Newtonian waveforms cease to be reliable near the end of the inspiral and\nthe coalescence phase, where numerical-relativity simulations should be used\nto predict the gravitational-wave signal ~\\cite{Pretorius2005a,\n  Campanelli2006a, Baker2006a}. By combining the information from\npost-Newtonian predictions and the numerical-relativity simulations it is\npossible to accurately and analytically describe the gravitational-wave signal\nduring the entire inspiral, plunge, merger and ringdown\nprocess~\\cite{Buonanno99, Buonanno00, DJS00, Buonanno-Cook-Pretorius:2007,\n  Ajith:2008, Damour2009a, Pan:2009wj, Santamaria:2010yb, Pan:2011gk}.\n\nFor nonspinning binaries, the post-Newtonian expansion has been iterated to\n$3.5$PN order beyond the leading Newtonian order in the gravitational-wave\nphasing~\\cite{Blanchet95a, Blanchet04, Blanchet2005b}. The gravitational-wave\namplitude has been computed through $3$PN\norder~\\cite{Blanchet96a, Kidder07, Kidder2008, BFIS} and the quadrupole mode\nthrough $3.5$PN order~\\cite{Faye:2012we}. However, black hole binaries could\npotentially have large spins~\\cite{Miller2009} which may be misaligned with\nthe orbital angular momentum, in which case the precession effects add\nsignificant complexity to the emitted gravitational\nwaves~\\cite{Apostolatos1994}. Ignoring the effects of black hole spins could\nlead to a reduction in the signal-to-noise ratio and decrease the detection\nefficiency~\\cite{Apostolatos1996, Buonanno:2002fy} although this should be\novercome with phenomenological and physical\nmodels~\\cite{Pan:2003qt, Buonanno2004, Buonanno:2005pt, Buonanno06,\n  Ajith:2009, Pan:2009wj, Ajith:2011ec, Brown:2012gs, Taracchini:2012ig}.\nTo maximize the payoffs for astrophysics will require extracting the source\nparameters from the gravitational-wave signal using template models computed\nfrom the most accurate physical prediction\navailable~\\cite{CutlerFlanagan1994, PoissonWill95, vanderSluys, AjithBose2009}.\nSpin effects in the waveform are currently known through much lower\npost-Newtonian order than for nonspinning binaries. More specifically, spin\neffects are known through $2.5$PN order in the\nphase~\\cite{Mikoczi:2005dn,Faye-Blanchet-Buonanno:2006,\nBlanchet-Buonanno-Faye:2006}, $1.5$PN\norder in the polarizations for spin-orbit effects~\\cite{Kidder:1995zr,\n  Arun:2009}, 2PN order for the spin${}_1$-spin${}_2$\neffects~\\cite{Kidder:1995zr, Will96} and partially $3$PN order in the\npolarizations for the tail-induced spin-orbit\neffects~\\cite{BlanchetEtAl:2011}.\n\nIn this paper, we compute all spin effects in the gravitational-wave\nstrain tensor through 2PN order. This requires knowledge of the\ninfluence of the spins on the system's orbital dynamics as well as\non the radiative multipole moments. At this PN order, nonlinear spin\neffects attributable to the spin-induced quadrupole moments of the\ncompact objects first appear. Using results from\nRef.~\\cite{1980AnPhy.130..188B,PortoRothstein2006,Porto:2008jj,SP10},\nwe derive the stress-energy tensor with self-spin terms and compute\nthe self-induced quadrupole terms in the equations of motion and in\nthe source multipole moments at 2PN order. Our results are in\nagreement with previous calculations~\\cite{Poisson:1997ha,Damour01c,\nSteinhoff:2010zz,Porto:2012x}.\n\nThe two main inputs entering our calculation of the gravitational-wave strain\ntensor through 2PN order are (i) the results of Refs.~\\cite{Kidder:1995zr,\n  Poisson:1997ha, Blanchet-Buonanno-Faye:2006} for the influence of the spins\non the system's orbital dynamics, which have also been derived by effective\nfield theory and canonical methods \\cite{PortoRothstein2006,Porto:2008tb,\n  Porto:2010tr,Damour:2007nc, Steinhoff08, Steinhoff08a, Steinhoff08b}, and (ii) the spin\neffects in the system's radiative multipole\nmoments~\\cite{Blanchet-Buonanno-Faye:2006}. Recently, the necessary knowledge\nto compute the waveform at 2.5PN order was obtained using the effective field\ntheory approach \\cite{Porto:2010tr,Porto:2012x}. Here we use (i) and (ii) in\nthe multipolar wave generation formalism~\\cite{thorne80, Blanchet:1992br,\n  Blanchet:1995fr} to obtain the waveform for spinning, precessing binaries\nthrough 2PN order. To compute the gravitational polarizations from\nthis result, one must specify an appropriate source frame and\nproject the strain tensor onto a polarization triad. For precessing\nsystems, there are several frames that could be\nemployed~\\cite{Finn1993, Kidder:1995zr, Buonanno:2002fy,\nSchmidt:2010it,OShaughnessy2011, Ochsner2012,\n2011PhRvD..84l4011B,Schmidt:2012rh}. For nonprecessing binaries with\nthe spins collinear to the orbital angular momentum, the most\nnatural frame is the one used for nonspinning binaries. Therefore,\ninstead of choosing one frame, for simplicity, we specialize to the\nnonprecessing case and quasicircular orbits and provide the explicit\nexpressions for the gravitational polarizations. Lengthy\ncalculations are performed with the help of the scientific software\n\\textsc{mathematica}{\\footnotesize \\textregistered}, supplemented by\nthe package xTensor~\\cite{xtensor} dedicated to tensor calculus. Our\ngeneric, precessing result is available in \\textsc{mathematica}\nformat upon request and can be used to compute the polarizations for\nspecific choices of frame. We notice that the 2PN terms in the\npolarizations, for circular orbits, linear in the spins were also\ncomputed in Ref.~\\cite{1998PhRvD..57.6168O}. However, these results\ncontain errors in the multipole moments, which were corrected in\nRef.~\\cite{Blanchet-Buonanno-Faye:2006}.\n\nFor future work at the interface of analytical and numerical\nrelativity, we also explicitly compute the decomposition of the\nstrain tensor into spin-weighted spherical-harmonic modes for\nnonprecessing spinning binaries on circular orbits. The\ntest-particle limit of these results can also be directly compared\nwith the black-hole perturbation calculations of\nRefs.~\\cite{Tagoshi:1996gh,Pan2010hz}, and we verify that the\nrelevant terms agree.\n\nThe organization of the paper is as follows. In\nSec.~\\ref{sec:modelling}, we review the Lagrangian for compact\nobjects with self-induced spin effects\n~\\cite{1980AnPhy.130..188B,PortoRothstein2006,Porto:2008jj,Steinhoff:2010zz},\ncompute the stress-energy tensor and derive the self-induced spin\ncouplings in the two-body acceleration and source multipole moments\n~\\cite{Poisson:1997ha,Damour01c,Steinhoff:2010zz,Porto:2012x}. In\nSec.~\\ref{sec:dynamics} we summarize the necessary information about\nspin effects in the equations of motion and the wave generation\nnecessary for our calculation. In Sec.~\\ref{sec:SO} we calculate the\nspin-orbit effects at 2PN order in the strain tensor for generic\nprecessing binaries. In Sec.~\\ref{sec:SS} we complete the knowledge\nof 2PN spin-spin terms by including the spin self-induced quadrupole\nterms in addition to the spin${}_1$-spin${}_2$ terms obtained in\nRef.~\\cite{Kidder:1995zr}. In Sec.~\\ref{sec:pol} we specialize to\nquasicircular orbits and explicitly give the polarization tensors\nfor nonprecessing systems. Then, in Sec.~\\ref{sec:modes} we\ndecompose the polarizations into spin-weighted spherical-harmonic\nmodes. Finally, Sec.~\\ref{sec:conclusions} summarizes our main\nfindings.\n\n%We use units where Newton constant is $G =1$, but retain factors of\n%the speed of light $c$, with $1/c^2$ serving as the formal expansion\n%parameter for the post-Newtonian expansion.\nWe use lowercase Latin letters $a, b, ..., i, j, ...$ for indices of spatial\ntensors. Spatial indices are contracted with the Euclidean metric, with up or\ndown placement of the indices having no meaning and repeated indices summed\nover. We use angular brackets to denote the symmetric, trace-free (STF)\nprojection of tensors, e.g., $T_{\\langle ij\\rangle} = {\\rm\n  STF}[T_{ij}]=T_{(ij)}-\\frac{1}{3}\\delta_{ij}T_{kk}$, where the round\nparentheses indicate the symmetrization operation. Square\nparentheses indicate antisymmetrized indices, e.g., $T_{[ij]} =\n\\frac{1}{2} (T_{ij} - T_{ji})$. The letter $L=i_1... i_\\ell$\nsignifies a multi-index composed of $\\ell$ STF indices. The\ntransverse-traceless (TT) projection operator is denoted ${\\cal\nP}_{ijab}^\\mathrm{TT}={\\cal P}_{a(i}{\\cal\n  P}_{j)b}-\\frac{1}{2}{\\cal P}_{ij}{\\cal P}_{ab}$, where ${\\cal\n  P}_{ij}=\\delta_{ij}-N_iN_j$ is the projector orthogonal to the unit\ndirection $\\bm{N}=\\bm{X}/R$ of a radiative coordinate system\n$X^\\mu=(cT, \\bm{X})$, where the boldface denotes a spatial\nthree-vector. As usual, $g_{\\mu\\nu}$ represents the space-time\nmetric and $g$ its determinant. The quantity $\\varepsilon_{ijk}$ is\nthe antisymmetric Levi-Civit\\`a symbol, with $\\varepsilon_{123}=1$,\nand $\\epsilon_{\\mu\\nu\\rho\\sigma}$ stands for the Levi-Civit\\`a\nfour-volume form, with $\\epsilon_{0123} = + \\sqrt{-g}$. Henceforth,\nwe shall indicate the spin${}_1$-spin${}_2$ terms with $S_1S_2$, the\nspin${}^2_1$, spin${}^2_2$ terms with $S^2$ and the total spin-spin\nterms with ${\\rm SS}$. Throughout the paper, we retain only the\nterms relevant to our calculations and omit all other terms, which\neither are already known or appear at a higher post-Newtonian order\nthan required for our purposes.\n\n\\section{Modeling spinning compact objects with self-induced quadrupoles}\n\\label{sec:modelling}\n\nIn this section we review the construction of a Lagrangian for compact objects\nwith self-induced quadrupole spin effects\n~\\cite{Tulczyjew1959,1980AnPhy.130..188B,PortoRothstein2006,Porto:2008jj,\nSteinhoff:2010zz},\ncompute the stress-energy tensor and derive the self-induced spin couplings in\nthe two-body acceleration and source multipole moments. Our findings are in\nagreement with previous\nresults~\\cite{Poisson:1997ha,Damour01c,Steinhoff:2010zz,Porto:2012x}.\n\n\\subsection{Lagrangian for compact objects with self-induced spin effects}\n\nA Lagrangian for a system of spinning compact objects with\nnondynamical\\footnote{We shall not include kinetic terms in the\nLagrangian\n  for the quadrupole moment that can describe resonance effects in neutron\n  stars.} self-induced quadrupole moments can be obtained by augmenting the\nLagrangian for point particles with $L^{\\text{S}^2}_A$ describing\nthe quadrupole-curvature coupling for each body $A$. Since the\naction for body $A$ must admit a covariant representation, the\ncorresponding Lagrangian $L^{\\text{S}^2}_A$ should be a function of\nthe four-velocity $u_A^\\mu$, the metric $g_{\\mu\\nu}$, the Riemann\ntensor $R^\\lambda_{~\\rho\\mu\\nu}$ and its covariant derivatives,\nevaluated at the worldline point $y_A^\\mu$, and the spin variables\nentering via the antisymmetric spin tensor $S_A^{\\mu\\nu}$.\n\nThe spin tensor $S_A^{\\mu\\nu}$ contains six degrees of freedom. It\nis well known that in order to reduce them to the three physical\ndegrees of freedom a spin supplementary condition (SSC) should be\nimposed~~\\cite{BOC79}. This is equivalent to performing a shift of\nthe worldline $y_A^\\mu$. In this paper we specialize to the SSC\n$S_A^{\\mu\\nu}p^A_\\nu=0$ which is equivalent to\n$S_A^{\\mu\\nu}u^A_\\nu=0$ since $p_A^\\mu \\approx m_A c u_A^\\mu$\nthrough 2.5PN order. To ensure the preservation of the SSC under the\nevolution, we follow Ref.~\\cite{Porto:2008jj} and introduce the spin\ntensor ${{{{\\cal{S}}}}}_A^{\\mu\\nu} =S_A^{\\mu\\nu} + 2 u_A^{[\\mu}\nS_A^{\\nu]\\lambda} u^A_\\lambda$. The spin tensor\n${{{{\\cal{S}}}}}_A^{\\mu\\nu}$ automatically satisfies the algebraic\nidentity ${{{{\\cal{S}}}}}^{\\mu\\nu}_A u^A_\\nu = 0$, which provides\nthree constraints that can be used to reduce the spin degrees of\nfreedom from six to three.\n\nFrom the above discussion and Refs.~\\cite{Porto:2005ac,\nPortoRothstein2006}, we assume that the Lagrangian of particle $A$\nis of the form $L^{\\text{S}^2}_A=L_{A\\, \\mu\\nu\\lambda\\rho}\n{{{\\cal{S}}}}_A^{\\mu\\nu} {{{\\cal{S}}}}_A^{\\lambda\\rho}$, where\n$L_{A\\, \\mu\\nu\\lambda\\rho}$ is a polynomial in the Riemann tensor\nand its derivatives, as well as the four-velocity $u_A^\\mu$. As\nnoticed in Ref.~\\cite{DE98a}, any term proportional to\n$\\nabla_{...}R_{\\alpha\\beta}$ evaluated at point $y_A^\\mu$ can be\nrecast into a redefinition of the gravitational field. As a result,\nthe Riemann tensor may be replaced in each of its occurrences by the\nWeyl tensor $C^\\lambda_{~\\rho\\mu\\nu}$, which can be decomposed into\na combination of the gravitoelectric- and gravitomagnetic-type STF\ntidal quadrupole moments $G_{\\mu\\nu}^A \\equiv G_{\\mu\\nu}(y_A^\\alpha)\n\\equiv - c^2 R_{\\mu\\alpha\\nu\\beta} u_A^{\\alpha} u_A^{\\beta}$ and\n$H^A_{\\mu\\nu}\\equiv H_{\\mu\\nu}(y_A^\\alpha) \\equiv 2 c^3\nR^{A*}_{\\mu\\alpha\\nu\\beta} u_A^{\\alpha} u_A^{\\beta}$ with\n$R^*_{\\mu\\nu\\alpha\\beta} \\equiv \\frac{1}{2}\n\\epsilon_{\\mu\\nu\\rho\\sigma} R^{\\rho\\sigma}_{~~\\alpha\\beta}$. More\ngenerally, the multiple space derivatives of\n$C^\\lambda_{~\\rho\\mu\\nu}$ at point $y_A^\\mu$ may be expressed in\nterms of some STF tidal multipole moments $G^A_{\\mu_1 ...\\mu_\\ell}$\nand $H^A_{\\mu_1 ... \\mu_\\ell}$ of parity $1$ and $-1$ respectively.\nHowever, those higher-order moments will play no role in this paper.\n\nTaking into account that the contraction of the velocity vector $u_A^\\nu$\nwith both $G^A_{\\mu\\nu}$ and ${{{\\cal{S}}}}^{\\mu\\nu}_A$ vanishes, that the\nspin and tidal multipole tensors are traceless, and that the Lagrangian must\nobey parity and time-reversal\nsymmetries %and that we are interested in describing\n%the self-induced quadrupole terms,\nwe obtain~\\cite{1980AnPhy.130..188B,Porto:2005ac,PortoRothstein2006,\nPorto:2008jj}\n%\n\\begin{equation} \\label{eq:LSSA}\nL^{\\text{S}^2}_A = - \\frac{\\kappa_A}{2 m_A c^2} G_{\\mu\\nu} S^\\mu_{A\n  \\lambda}\\,S_A^{\\lambda \\nu} \\, .\n\\end{equation}\n%\nHere, we have also assumed that the rotating body is axially symmetric and we\nhave replaced ${{{\\cal{S}}}}^{\\mu \\nu}_A$ with $S^{\\mu \\nu}_A$ since the\ndifference between these spin variables contributes to the equations of motion\nat $\\mathcal{O}(S_A^3)$, where $S_A= \\sqrt{|S_A^\\mu S^A_\\mu|}$ with $S^A_\\mu =\n\\epsilon_{\\rho\\sigma\\nu\\mu} S^{\\rho\\sigma}_A p^\\nu_A/(2 m_A c)$.\n\nFor a neutron star the numerical constant $\\kappa_A$ in\nEq.~(\\ref{eq:LSSA}) depends on the equation of state of the fluid\n\\cite{Laarakkers99}. For an isolated black hole\n$\\kappa_A=1$~\\cite{Poisson:1997ha,Damour01c}, but for a black hole\nin a compact binary $\\kappa_A$ can deviate from 1. However, these\ndeviations occur at PN orders that are much higher than the ones\nconsidered here. We notice that the leading contribution\n$\\kappa_A=1$ can be obtained by computing the acceleration of body\n$A$ from Eq.~(\\ref{eq:LSSA}) in a compact binary for $m_A\\ll m$ and\nmatching it with the acceleration of a test particle in the\ngravitational field of a Kerr black hole of mass\n$m$~\\cite{Porto:2005ac}.\n\n\\subsection{Effective stress-energy tensor with self-induced quadrupoles}\n\nThe piece of the stress-energy tensor encoding the self-induced quadrupole\ndynamics of body $A$ reads by definition\n%\n\\begin{equation} \\label{eq:TSSAdef}\nT^{\\mu\\nu}_{\\text{quad},A} = \\frac{2}{\\sqrt{-g}} \\frac{\\delta}{\\delta g_{\\mu\\nu}(x)}\n\\int d\\tau_A\\, L^{\\text{S}^2}_A[y_A^\\alpha(\\tau_A), S^{\\alpha\\beta}_A(\\tau_A)] \\, ,\n\\end{equation}\n%\nwhere $L_A^{\\text{S}^2}$ is the Lagrangian~\\eqref{eq:LSSA}. To\ndetermine the action of the operator $\\delta/\\delta g_{\\mu\\nu}$,\nwhich stands for the usual ``functional derivative'' with respect to\nthe field $g_{\\mu\\nu}$, we need to adopt a specific model for the\nspin. The rotational state of the extended object $A$ is usually\nrepresented by a tetrad of orthonormal vectors\n$e^{\\mu}_{A\\overline{\\alpha}}(\\tau_A)$ with $\\overline{\\alpha} \\in\n\\{0,1,2,3\\}$ along the worldline $y^\\mu_A$ with affine parameter\n$\\tau_A$. The corresponding angular rotation tensor is then defined\nas $\\Omega^{\\mu\\nu}_A = \\eta^{\\overline{\\alpha}\\overline{\\beta}}\ne_{A\\overline{\\alpha}}^{\\mu} D e^\\nu_{A\\overline{\\beta}}/d\\tau_A$.\nWe now make the reasonable physical hypothesis that the rotation of\nthe axially symmetric object takes place about the symmetry axis.\nThe moment of inertia $I_A$ along that direction is a 2PN-order\nquantity $ \\sim G^2 m_A^3/c^4$ for compactness parameters of order\n1, whereas $\\Omega^{\\mu\\nu}_A \\sim V_A/R_A$, $R_A$ being the radius\nof body $A$ and $V_A$ its typical internal velocity, is roughly\nequal to $ c^3/(G m_A)$. In the weak field limit where $G$ goes\nformally to zero, the spin must satisfy the relation $S^{\\mu\\nu}_A =\nI_A \\Omega^{\\mu\\nu}_A$, as in special relativity~\\cite{HR74}. In the\npresence of a nonnegligible gravitational field, this relation is\nexpected to be modified by nonminimal coupled terms proportional to\npositive powers of $R^A_{\\mu\\nu\\alpha\\beta}$ times positive powers\nof $I_A$ and $S^{\\mu\\nu}_A$~\\cite{Porto:2005ac}:\n%\n\\begin{equation} \\label{eq:hatspin}\n\\hat{S}_A^{\\mu\\nu} = I_A\n\\Big[ \\Omega_A^{\\mu\\nu} + \\mathcal{O}\\Big(\\frac{\\hat{S}_A}{c^2}\\Big) \\Big] \\, .\n\\end{equation}\n%\nHere we use a hat to distinguish the generic spin variable from the\none related to our specific spin model. The corrections $ I_A\\times\n\\mathcal{O}(\\hat{S}_A/c^2)$ are not relevant for the two-body\ndynamics in this paper because they correspond to the 4.5PN order\nwhen taking into account the factor $\\mathcal{O}(1/c)$ contained in\nthe spin variable.\n\nUsing the definition~\\eqref{eq:hatspin} for the spin variables, we compute in a\ncovariant manner the variation of the action\n%\n\\begin{align}\n\\mathcal{A}^{\\text{S}^2} &=\n\\int d\\tau_A L_A^{\\text{S}^2}(\\tau_A) \\nonumber \\\\ &= \\int \\frac{d^4\nx}{c} \\sqrt{-g} \\int d\\lambda_A L_A^{\\text{S}^2}(\\lambda_A) \\frac{\\delta^4(x^\\alpha -\ny^\\alpha_A(\\lambda_A))}{\\sqrt{-g}} \\, ,\n\\end{align}\n%\nwhen the metric varies by $\\delta g_{\\mu\\nu}(x)$, and find the following\nquadrupolar piece of the stress-energy tensor\n%\n\\begin{align} \\label{eq:TSSA}\nT^{\\mu\\nu}_{\\text{quad},A} & =  \\frac{\\kappa_A}{m_A c^2} \\Big[ \\frac{n^*_A}{2}\n\\Big(-3 u_A^\\mu u^\\nu_A G^A_{\\lambda \\rho} \\hat{S}^{\\lambda \\sigma}_A\n\\hat{S}_\\sigma^{A\\rho}\\nonumber  \\\\ & \\qquad -  c^2 R^{(\\mu}_{A\\lambda\\rho \\tau} u_A^{\\nu)}\n\\hat{S}^\\lambda_{A\\sigma} \\hat{S}_A^{\\sigma \\rho} u_A^\\tau + G^{(\\mu}_{A\\lambda}\n\\hat{S}^{\\nu)}_{A\\rho} \\hat{S}_A^{\\rho \\lambda} \\Big) \\nonumber \\\\ & + \\nabla_\\rho\n\\Big( I_A c\\, n_A^* (G^{A(\\mu}_\\lambda u_A^{\\nu)} \\hat{S}_A^{\\lambda \\rho} -\nG_\\lambda^{A\\rho} \\hat{S}^{\\lambda(\\mu}_A u_A^{\\nu)} ) \\Big) \\Big] \\nonumber\n\\\\ & -2 \\nabla_\\lambda \\nabla_\\rho\n\\Big[ n^*_A \\hat{S}_A^{\\sigma [\\lambda} u_A^{(\\mu]} \\hat{S}_{\\sigma}^{A[\\nu)}\nu_A^{\\rho]} \\Big] \\, ,\n\\end{align}\n%\nwhere we have indicated with $n^*_A$ the Dirac-type scalar density\n$n^*_A(x^\\mu) = \\int d\\lambda_A \\, \\delta^4(x^\\mu-\ny_A^\\mu(\\lambda_A))/\\sqrt{-g(x^\\nu)}$ and, in the last term, we have adopted\nthe convention that\nsymmetrization of indices applies after antisymmetrization.\nAs derived in Ref.~\\cite{Tulczyjew1959}, the most general form of the\neffective stress-energy tensor is\n%\n\\begin{multline}\nT^{\\mu\\nu}_{\\text{skel} , A}(x^\\mu) = \\\\\\sum_{\\ell = 0}^{+\\infty}\n\\nabla_{\\lambda_1} \\nabla_{\\lambda_2} ... \\nabla_{\\lambda_\\ell}\n\\Big[t_A^{\\mu\\nu\n  | \\lambda_1 \\lambda_2 ...  \\lambda_\\ell}(\\tau_A) n^*_A(x^\\mu) \\Big] \\, ,\n\\label{skeletonTmunu}\n\\end{multline}\n%%\nwhere $\\tau_A$ is the proper time of the $A$th worldline at event\n$y_A^\\mu$ with $y_A^0 = x^0$ and the coefficients $t^{\\mu\\nu |\n\\lambda_1\n  \\lambda_2 ... \\lambda_\\ell}_A(\\tau_A)$ are the ``skeleton'' multipole\nmoments. The latter are not arbitrary but satisfy algebraic\nconstraints imposed by the equation of conservation $\\nabla_\\nu\nT^{\\mu\\nu}_\\text{skel} =0$. Let us check that we can indeed recast\nthe total stress-energy tensor, including the monopolar, dipolar and\nquadrupolar pieces, in the form (\\ref{skeletonTmunu}). If we add\n$T^{\\mu\\nu}_{\\text{quad}}$ to the monopolar and dipolar\ncontributions~\\cite{Papa51spin,Tulczyjew1959,Dixon1964,\n  Tagoshi-Ohashi-Owen:2001,Faye-Blanchet-Buonanno:2006}\n%\n\\begin{align} \\label{eq:TMon}\nT^{\\mu\\nu}_{\\text{mon}+\\text{dipole}}  =  \\sum_{A} \\Big[n_A^*\n\\tilde{p}_A^{(\\mu} u^{\\nu)}_A c  + \\nabla_\\lambda  \\Big( n_A^* c\\,\nu_A^{(\\mu} \\tilde{S}_A^{\\nu) \\lambda}\\Big)\\Big]  \\,,\n\\end{align}\n%\nand redefine the spin variable entering the quadrupolar piece as\n%\n\\begin{equation}\nS^{\\mu\\nu}_A = \\tilde{ S}^{\\mu\\nu}_A  - \\frac{2 \\kappa_A}{m_A c^2} I_A\n\\hat{S}_A^{\\lambda[\\mu} G_{A\\lambda}^{\\nu]} \\,,\n\\label{S:red}\n\\end{equation}\n%\nwe obtain the total stress-energy tensor in the form\n%\n\\begin{subequations}\n\\label{eq:TmunuJ}\n\\begin{align} \\label{eq:Tmunu}\nT^{\\mu\\nu} & = \\sum_{A} \\Big[n_A^* \\Big( p_A^{(\\mu} u^{\\nu)}_A c + \\frac{1}{3}\nR^{(\\mu}_{A\\tau\\lambda\\rho} J_A^{\\nu)\\tau\\lambda\\rho}c^2 \\Big) \\nonumber \\\\ & \\qquad +\n\\nabla_\\lambda  \\Big( n_A^*\nc\\, u_A^{(\\mu} S_A^{\\nu) \\lambda}\\Big) \\nonumber \\\\ & \\qquad - \\frac{2}{3}\n\\nabla_{\\lambda}\\nabla_{\\rho}\\Big(n_A^* c^2 J_A^{\\lambda(\\mu\\nu) \\rho}\n\\Big)\\Big] \\, ,\n\\end{align}\n%\nwhere the four-rank tensor $J_A^{\\lambda\\rho\\mu\\nu}$ takes the\nfollowing expression in our effective description:\n%\n\\begin{equation}\n\\label{JA}\nJ_A^{\\lambda\\rho\\mu\\nu}  = \\frac{3 \\kappa_A}{m_A c^2} S_A^{\\sigma[\\lambda}\nu^{\\rho]}_A S^{A[\\mu}_\\sigma u_A^{\\nu]} \\, .\n\\end{equation}\n\\end{subequations}\n%\nConsistently with the approximation already made in the spin\nmodel~\\eqref{eq:hatspin}, we have neglected here the difference of\norder $I_A\\times \\mathcal{O}(\\hat{S}_A/c^2)$ between the spins\n$\\hat{S}^{\\mu\\nu}_A$ and $S^{\\mu\\nu}_A$ in the above formula. The\nnet result is that Eq.~(\\ref{eq:Tmunu}) matches\nEq.~(\\ref{skeletonTmunu}) for $\\ell = 0,1,2$ as expected. Moreover,\nEqs.~(\\ref{eq:TmunuJ}) agree with Refs.~\\cite{Steinhoff:2010zz,SP10}.\n\nLastly, the conservation of the stress-energy tensor~\\eqref{eq:Tmunu} is\nequivalent to the equation of motion for the particle worldline, supplemented\nby the spin precession equation~\\cite{SP10}. They read\n%\n\\begin{subequations}\n\\begin{align}  \\label{eq:Dixon_EOM}\n\\frac{D p_A^\\mu}{d\\tau_A} &= - \\frac{c}{2} R^\\mu_{A\\rho\\nu\\lambda} u_A^\\rho\nS^{\\nu \\lambda}_A - \\frac{c^2}{3} \\nabla_\\tau  R^\\mu_{A\\rho\\nu\\lambda}\nJ_A^{\\tau\\rho\\nu\\lambda} \\, , \\\\ \\label{eq:Dixon_precession}\n\\frac{DS^{\\mu\\nu}}{d\\tau_A} &= 2 c \\, p_A^{[\\mu} u_A^{\\nu]} + \\frac{4c^2}{3}\nR^{[\\mu}_{A\\tau\\lambda\\rho} J_A^{\\nu]\\tau\\lambda\\rho} \\, .\n\\end{align}\n\\end{subequations}\n%\nThose equations are in full agreement with the equations of evolution derived\nfrom the Dixon formalism truncated at the quadrupolar order~\\cite{Dixon1974}.\n\n\\subsection{Self-induced quadrupole terms in the 2PN binary dynamics and\nsource multipole moments}\n\nOnce the stress-energy tensor has been derived, the post-Newtonian equations\nof motion and the source multipole moments parametrizing the linearized\ngravitational field outside the system can be computed by means of the usual\nstandard techniques~\\cite{Blanchet2006}. At 2PN order, the accelerations\nincluding the self-spin interactions were obtained in\nRefs.~\\cite{Poisson:1997ha,Damour01c}, but the self-induced quadrupole effects\nin the source multipole moments were never explicitly included in the standard\nversion of the post-Newtonian scheme, although recently they were calculated\nat 3PN order using effective-field-theory techniques~\\cite{Porto:2010zg}. Here\nwe can use the results of the previous section, which constitutes a natural\nextension of the standard post-Newtonian approximation for spinning compact\nbodies~\\cite{Faye-Blanchet-Buonanno:2006}, and explicitly derive the\nself-induced quadrupole couplings in the 2PN dynamics and source multipole\nmoments.\n\nHenceforth, we define the spin vectors $S_A^i$ by the relation\n$S_i^A/c = g_{ij}^A S_A^j$, where $S_i^A$ is the three-form induced\non the hypersurface $t= {\\rm const}$ by $S_\\mu^A$. Note that it is\n$S^i_A/c$ that has the dimension of a spin, while $S^i_A$ has been\nrescaled in order to have a nonzero Newtonian limit for compact\nobjects.\n\nIn the post-Newtonian formalism for point particles in the harmonic gauge, it\nis convenient to represent effectively the source by the mass density $\\sigma\n= (T^{00}+T^{ii})/c^2$, the current density $\\sigma_i = T^{0i}/c$, and the\nstress density $\\sigma_{ij}= T^{ij}$. They are essentially the components of\nthe stress-energy tensor rescaled so as not to vanish in the formal limit $c\n\\to 0$ for weakly stressed, standard matter. At 2PN order, the second term in\nthe right-hand side of Eq.~(\\ref{eq:Tmunu}) does not contribute. From the\nlast term, we obtain the following self-spin\ncontributions:\n%\n\\begin{subequations}\n\\begin{align} \\label{eq:sigma}\n& \\sigma^{\\text{S}^2} = \\frac{\\kappa_1}{2 m_1 c^2} \\partial_{ij} [\\delta_1\nS_1^{ki} S_1^{kj}]\n+ 1 \\leftrightarrow 2 + \\mathcal{O}\\Big(\\frac{S_A^2}{c^4} \\Big) \\, ,\\\\\n& \\sigma^{\\text{S}^2}_i =  \\mathcal{O}\\Big(\\frac{S_A^2}{c^2}\\Big) \\, , \\\\\n& \\sigma^{\\text{S}^2}_{ij} =  \\mathcal{O}\\Big(\\frac{S_A^2}{c^2}\\Big) \\, .\n\\end{align}\n\\end{subequations}\n%\nwhere $1 \\leftrightarrow 2$ represents the counterpart of the\npreceding term with particles 1 and 2 exchanged, and $\\delta_1\n\\equiv \\delta^3(\\bm{x}-\\bm{y}_1)$.\n\nAt 2PN order, the spin$^{2}$ part of the equations of\nmotion~\\eqref{eq:Dixon_EOM} for, say, the first particle, reduce to\n%\n\\begin{equation}\n\\frac{D(u_i^1 c)}{d\\tau_1} = \\text{non-}S_1^2\\text{ terms}\n-\\frac{\\kappa_1}{2m_1^2} \\partial_k R^1_{i0j0} S_1^{lk} S_1^{lj} + \\mathcal{O}\n\\Big(\\frac{S_1^2}{c^4} \\Big) \\, .\n\\end{equation}\n%\nThe only occurrence of self-spin interactions at 2PN order on the\nleft-hand side of the above equation comes from the gradient of the\ntime component of the metric, $g_{00} = -1 + 2 V/c^2 +\n\\mathcal{O}(1/c^4)$, where the Newton-like potential $V$ satisfies\n$\\Box V = - 4\\pi G \\sigma$. Although $V$ coincides with the\nNewtonian potential $U$ in the leading approximation, it contains\nhigher order corrections, including quadratic-in-spin terms coming\nfrom the mass density~\\eqref{eq:sigma}, which are smaller than $U$\nby a factor $\\mathcal{O}(1/c^4)$. They read\n%\n\\begin{align}\nV_{\\text{S}^2}  &= - \\frac{2\\pi G \\kappa_1}{m_1 c^2} \\partial_{ij} \\Delta^{-1}\n[\\delta_1 S_1^{ki} S_1^{kj}] + 1 \\leftrightarrow 2 + \\mathcal{O}\n\\Big(\\frac{S_A^2}{c^4} \\Big) \\nonumber \\\\\n& =  \\frac{ G \\kappa_1}{2m_1 c^2} \\partial_{ij} \\frac{1}{r_1} S_1^{ki} S_1^{kj} + 1\n\\leftrightarrow 2 + \\mathcal{O}  \\Big(\\frac{S_A^2}{c^4} \\Big)\\, ,\n\\end{align}\n%\nwith $\\partial_i = \\partial/\\partial x^i$ and $r_1\\equiv |\\bm{x}-\\bm{y}_1|$,\nthe symbol $\\Delta^{-1}$ holding for the retarded integral operator. Other\npotentials appear at the 1PN approximation or beyond, but their sources cannot\ncontain a self-induced quadrupole below $\\mathcal{O}(1/c^4)$; thus they are\nnegligible here. The self-induced spin part of the acceleration $\\bm{a}_1$ of\nthe first particle is therefore given by\n%\n\\begin{equation}\n  (a^i_1)_{\\text{S}^2} = -c^2 (\\Gamma_{~0 i}^0)_{\\text{S}^2} -\n  \\frac{\\kappa_1}{2m_1^2} \\partial_k R^1_{i0j0} S_1^{lk} S_1^{lj} +\n  \\mathcal{O}  \\Big(\\frac{S_A^2}{c^4} \\Big) \\ .\n\\end{equation}\n%\nReplacement of the Christoffel symbols $\\Gamma_{~\\mu\\nu}^\\lambda$ and the Riemann\ntensor by the leading order values\n%\n\\begin{align}\n\\Gamma_{~0 i}^0 = - \\frac{\\partial_i V}{c^2} +\n\\mathcal{O}\\Big(\\frac{1}{c^4}\\Big) \\, , ~\nR_{i0j0} = - \\frac{ \\partial_{ij} U}{c^2} +\n\\mathcal{O}\\Big(\\frac{1}{c^4}\\Big) \\, ,\n\\end{align}\n%\nwith $U = G m_1/r_1 + G m_2 /r_2 + \\mathcal{O}(1/c^2)$ yields the more\nexplicit result (posing $\\partial_{1i} \\equiv \\partial/\\partial y_1^i$):\n%\n\\begin{align}\n\\label{aSS}\n(a^i_1)_{\\text{S}^2} &= - \\frac{G}{2c^2} \\partial_{1ijk} \\frac{1}{r} \\Big[\n\\frac{\\kappa_2}{m_2} S_2^j S_2^k + \\frac{m_2 \\kappa_1}{m_1^2} S_1^j S_1^k\n\\Big] \\nonumber \\\\ &+ \\mathcal{O} \\Big( \\frac{1}{c^4} \\Big) \\, ,\n\\end{align}\n%\nwhich agrees with Refs.~\\cite{Poisson:1997ha,Damour01c} in the\ncenter-of-mass frame, for $S_A^i/c = \\varepsilon_{ijk} S^{jk} +\n\\mathcal{O}( 1/c^3)$.\n\nSelf-induced quadrupolar deformations of the bodies also produce 2PN-order\nterms in the source multipole moments $I_L$ and $J_L$. Those are defined as\nvolume integrals whose integrands are certain polynomials in the densities\n$\\sigma$, $\\sigma_i$ and $\\sigma_{ij}$ as well as some gravitational\npotentials, such as $V$, that parametrize the metric. Now, since those\npotentials are multiplied by prefactors of order $\\mathcal{O}(1/c^2)$ and\ncannot contain themselves spin${}^2$ interactions below the 2PN order,\nmonomials involving one potential or more may be ignored for the calculation.\nThe remaining sources are linear in the $\\sigma$ variables. With the help of\nthe general formula~(5.15) of Ref.~\\cite{Blanchet98}, it is then immediate to\nget the self-spin contribution to $I_L$:\n%\n\\begin{equation}\nI_L^{\\text{S}^2} =\\int d^3\\!\\bm{x} \\, x^{\\langle i_1}\\!\\! ...\\, x^{i_\\ell\n  \\rangle}\\sigma_{\\text{S}^2}  +\n\\mathcal{O} \\Big(\\frac{S_A^2}{c^4} \\Big) \\, .\n\\end{equation}\n%\nInserting expression~\\eqref{eq:sigma} for $\\sigma_{\\text{S}^2}$ and\nperforming a straightforward integration, we arrive at\n%\n\\begin{equation}\nI_L^{\\text{S}^2} = \\frac{\\kappa_1}{2m_1 c^2} \\partial_{1ij}\n(y_1^{\\langle i_1}\\! \\! ...\\, y_1^{i_\\ell \\rangle}) S_1^{ki} S_1^{kj} +  1\n\\leftrightarrow 2 + \\mathcal{O} \\Big( \\frac{S_A^2}{c^4}\\Big) \\, .\n\\end{equation}\n%\nWe can show similarly that $J_L$ is of order $\\mathcal{O}(S_A^2/c^2)$. As a\nresult, at the accuracy level required for the 2PN waveform, the only terms\nquadratic in one of the spins that originate from the source moments come\nfrom the quadrupole $\\ell=2$, for which we have\n%\n\\begin{equation}\n\\label{eq:ISSresult}\nI_{ij}^{\\text{S}^2} = - \\frac{\\kappa_1}{m_1 c^4} S_1^{\\langle i} S_1^{j\\rangle} + 1\n\\leftrightarrow 2 + \\mathcal{O} \\Big( \\frac{1}{c^6}\\Big)\\, ,\n\\end{equation}\n%\nwhereas similar terms in $(I_L)_{\\ell \\ge 3}$ or $(J_L)_{\\ell \\ge\n2}$ lie beyond our approximation. The above correction to the mass\nquadrupole agrees with that of Porto \\textit{et\nal}.~\\cite{Porto:2010zg} truncated at 2PN order. It is formally of\norder $\\mathcal{O}(1/c^4)$ but, because $\\dot{\\bm{S}}_A=\n\\mathcal{O}(1/c^2)$, it is cast to the 3PN order in the waveform\nexpansion given below [see Eq.~\\eqref{eq:hij}] after the second time\nderivative is applied. This result was already argued in\nRef.~\\cite{Racine2008}.\n\n\n\\section{Two-body dynamics with spin effects through 2PN order}\n\\label{sec:dynamics}\n\nThe equations of motion in harmonic coordinates for the relative orbital\nseparation $\\bm{x}=r\\,\\bm{n}$ in the center of mass frame are\n~\\cite{Blanchet2006}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{subequations}\n \\label{eq:eom}\n\\begin{eqnarray}\n\\frac{d^2 x^i}{dt^2}&=&a^i_{\\rm Newt}+\\frac{1}{c^2}a^i_{\\rm 1PN}+\n\\frac{1}{c^3}a^i_{\\rm SO} \\nonumber \\\\\n&& +\\frac{1}{c^4}\\left[a^i_{\\rm S_1S_2}+a^i_{\\text{S}^2}+\na^i_{\\rm 2PN}\\right], \\label{eq:eomscale}\n\\end{eqnarray}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nwhere\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{align}\n\\bm{a}_{\\rm Newt}&=-\\frac{G m}{r^2}\\bm{n} \\, , \\\\\n\\bm{a}_{\\rm 1PN}&=-\\frac{G m}{r^2}\\left\\{\\left[(1+3\\nu)v^2-\n\\frac{3}{2}\\nu\\dot r^2-2(2+\\nu)\\frac{G m}{r}\\right]\\bm{n}  \\right.\\nonumber\\\\\n& \\qquad  \\qquad  -2 \\dot r (2-\\nu) \\bm{v}\\Bigg\\},\n\\end{align}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nwith $m\\equiv m_1+m_2$, $\\nu\\equiv m_1\\,m_2/m^2$, $\\bm{n}=\\bm{x}/r$ and\n$\\bm{v}=d\\bm{x}/dt$.\nThe 2PN acceleration given, e.g., in Ref.~\\cite{Kidder:1995zr} will not be\nneeded for our calculation. The spin-orbit terms are~\\cite{Kidder:1995zr}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{align}\n&\\bm{a}_{\\rm SO}=\\frac{G}{r^3} \\left\\{6\\left[(\\bm{n} \\times \\bm{v})\\cdot\n    \\left(2 \\bm{S} +\n\\delta\\, \\bm{\\Sigma}\\right)\\right]\\bm{n} \\right. \\label{eq:aSO} \\\\\n& \\left. \\qquad \\qquad - \\left[\\bm{v}\\times \\left(7 \\bm{S}+\n3\\delta\\, \\bm{\\Sigma}\\right)\\right] +3\\dot r \\left[\\bm{n}\\times \\left(3 \\bm{S}+\n\\delta\\,\\bm{\\Sigma}\\right)\\right] \\right\\} \\, ,\\nonumber\n\\end{align}\n\\end{subequations}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nwhere we denote with $\\delta=(m_1-m_2)/m$ and\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{subequations}\\label{SDelta}\\begin{align}\n\\bm{S} &\\equiv \\bm{S}_1 + \\bm{S}_2\\,,\\\\ \\bm{\\Sigma}\n&\\equiv m\\left[\\frac{\\bm{S}_2}{m_2} -\n\\frac{\\bm{S}_1}{m_1}\\right]\\,.\n\\end{align}\\end{subequations}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nThe spin$_1$-spin$_2$ interaction terms are~\\cite{Kidder:1995zr}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{subequations}\n\\begin{align}\n&\\bm{a}_{\\rm S_1 S_2}=-\\frac{3G}{m \\nu r^4}\\bigg[ \\left[\n( \\bm{S}_1 \\cdot \\bm{S}_2)-5 (\\bm{n}\\cdot \\bm{S}_1)\n(\\bm{n} \\cdot \\bm{S}_2)\\right]\\bm{n}    \\nonumber\\\\\n&  \\qquad \\qquad \\qquad \\quad +(\\bm{n} \\cdot \\bm{S}_1)\\bm{S}_2+(\\bm{n}\\cdot\n\\bm{S}_2)\\bm{S}_1 \\bigg].\n\\end{align}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nAs originally computed in Ref.~\\cite{Poisson:1997ha} [see\nEq.~(\\ref{aSS}) above], an additional term due to the influence of\nthe spin-induced mass quadrupole moment on the motion arises at 2PN\norder:\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{align}\n&\\bm{a}_{\\text{S}^2}=-\\frac{3G}{2m \\nu r^4}\\bigg\\{\n\\bm{n}\\left[\\frac{\\kappa_1}{q} S_1^2+q \\ \\kappa_2 S_2^2 \\right]\\nonumber\\\\\n& \\ \\ \\ +2 \\left[\\frac{\\kappa_1}{q}(\\bm{n} \\cdot \\bm{S}_1)\\bm{S}_1 +\nq \\, \\kappa_2 (\\bm{n}\\cdot \\bm{S}_2)\\bm{S}_2\\right]\\nonumber\\\\\n& \\ \\ \\ -\\bm{n}\\left[\\frac{5\\kappa_1}{q} (\\bm{n}\\cdot \\bm{S}_1)^2+5 q \\,\n\\kappa_2 (\\bm{n}\\cdot \\bm{S}_2)^2\\right]\\bigg\\}. \\label{eq:aspinspin}\n\\end{align}\n\\end{subequations}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nHere, $q=m_1/m_2$ is the mass ratio and we recall that the parameters\n$\\kappa_A$ characterize the mass quadrupole moments of the\nbodies.\n% For an axisymmetric rotating body, the quadrupole moment scalar is\n% $Q_{A}=-\\kappa_A S_A^2/m$, with $\\kappa_A=1$ for a Kerr black hole.\n\nWe find that the quadratic spin contribution to the acceleration can\nbe rewritten in a simpler way by introducing the spin variables\n%\n\\begin{align}\n\\bmSeffp &= \\frac{m}{m_1} \\left(\\frac{\\kappa_1}{\\kappa_2}\n\\right)^{1/4} (1+ \\sqrt{1-\\kappa_1 \\kappa_2})^{1/2} \\bm{S}_1 \\nonumber \\\\ &+\n\\frac{m}{m_2} \\left(\\frac{\\kappa_2}{\\kappa_1}\n\\right)^{1/4} (1- \\sqrt{1-\\kappa_1 \\kappa_2})^{1/2} \\bm{S}_2 \\, ,\n\\end{align}\n%\nand $\\bmSeffm$, which is obtained by exchanging the labels 1 and 2\nin the above equation.~\\footnote{In the formal limit where the\ninduced quadrupole of\n  at least one body vanishes, so that e.g. $\\kappa_2 \\to 0$, we may define the\n  effective spins as: $\\bmSeffp = \\frac{m}{m_1} \\sqrt{2} \\bm{S}_1$, $\\bmSeffm\n  = \\frac{m}{m_1} \\frac{\\kappa_1}{\\sqrt{2}} \\bm{S}_1 + \\frac{m}{m_2} \\sqrt{2}\n  \\bm{S}_2$.} Those variables generalize the quantity $\\bm{S}_0$ of\nRef.~\\cite{Damour01c} in the case where the two bodies are not black\nholes. In terms of these spin variables the spin-spin part of the\nacceleration reads\n%\n\\begin{multline}\n\\label{eq:ssaccel}\n\\bm{a}_{\\rm S_1 S_2} + \\bm{a}_{\\text{S}^2} = - \\frac{3G}{2 m r^4} [ \\bm{n} \\,\n(\\bmSeffp \\cdot \\bmSeffm) + (\\bm{n} \\cdot\n\\bmSeffp) \\, \\bmSeffm\n\\\\   +  (\\bm{n} \\cdot \\bmSeffm) \\, \\bmSeffp -\n5  \\bm{n} \\, (\\bm{n} \\cdot \\bmSeffp)  (\\bm{n} \\cdot\n\\bmSeffm) ]\n\\, .\n\\end{multline}\n\nThe spin precession equations through 2PN order are~\\cite{Kidder:1995zr,\n  Racine:2008qv}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{subequations}\n\\begin{align}\n&\\frac{d\\bm{S}}{dt}=\\frac{G m \\nu}{c^2 r^2}\\bigg\\{\n\\left[-4 (\\bm{v}\\cdot \\bm{S})-\n2 \\delta\\,(\\bm{v}\\cdot \\bm{\\Sigma})\\right]\\bm{n} \\nonumber\\\\\n& \\qquad~ +\\left[3 (\\bm{n}\\cdot \\bm{S})+\n\\delta\\,(\\bm{n}\\cdot \\bm{\\Sigma})\\right]\\bm{v}+\\dot r \\left[2 \\bm{S}+\n\\delta\\,\\bm{\\Sigma}\\right]\\bigg\\},\\\\\n%\\nonumber\\\\\n%&& \\ \\ \\ \\ \\ + \\ \\frac{3}{r^3c^3}\n% \\left[\\frac{\\kappa_1}{q}\\left(\\bm{n}\\cdot \\bm{S}_1\\right)+\n%\\left(\\bm{n}\\cdot \\bm{S}_2\\right) \\right](\\bm{n}\\times \\bm{S}_1)\\nonumber\\\\\n%&& \\ \\ \\ \\ \\ +\n%\\ \\frac{3}{r^3c^3}\\bigg[ q\\, \\kappa_2\\left(\\bm{n}\\cdot \\bm{S}_2\\right)\n%+\\left(\\bm{n}\\cdot \\bm{S}_1\\right)\\bigg]%(\\bm{n}\\times \\bm{S}_2), \\\\\n%%%%\n&\\frac{d\\bm{\\Sigma}}{dt}= \\frac{G m}{c^2 r^2}\\bigg\\{\n\\left[-2 \\delta\\,(\\bm{v}\\cdot \\bm{S})-\n2(1-2\\nu)(\\bm{v}\\cdot \\bm{\\Sigma})\\right]\\bm{n}\\nonumber\\\\\n& \\qquad~ +\\left[\\delta\\, (\\bm{n}\\cdot \\bm{S})+\n(1-\\nu)(\\bm{n}\\cdot \\bm{\\Sigma})\\right]\\bm{v}\\nonumber\\\\\n& \\qquad~ +  \\dot r \\left[\\delta\\,\\bm{S}+\n(1-2\\nu)\\bm{\\Sigma}\\right]\\bigg\\}.\n%\\nonumber\\\\\n%&& \\ \\ \\ \\ \\ -\n%\\  \\frac{3(1+q)}{q c^3r^3}\\left[\\frac{\\kappa_1}{q}(\\bm{n}\\cdot \\bm{S}_1)\n%+ (\\bm{n}\\cdot \\bm{S}_2)\\right](\\bm{n}\\times %\\bm{S}_1)\\nonumber\\\\\n%&& \\ \\ \\ \\ \\\n%+\\ \\frac{3(1+q)}{c^3r^3}\\bigg[q \\, \\kappa_2 (\\bm{n}\\cdot \\bm{S}_2)+\n%(\\bm{n}\\cdot \\bm{S}_1)\\bigg](\\bm{n}\\times %\\bm{S}_2)\\nonumber\\\\\n%&& \\ \\ \\ \\ \\ + \\ \\frac{q^2-1}{q c^3 r^3}(\\bm{S}_2\\times \\bm{S}_1).\n%\\label{eq:eomscale1}\n\\end{align}\n\\end{subequations}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nIt is often convenient to use a different set of spin variables\n$S^{\\rm c}_{\\!Ai}$ whose magnitude remains constant and that obey\nprecession equations of the form $d{\\bm{S}}^{\\rm\nc}_A/dt=\\bm{\\Omega}_A \\times \\bm{S}_A^{\\rm c}$. The relationship\nbetween the spin variables appearing in the equations of motion\nabove and the constant magnitude spin variables is~\\cite{\nBlanchet-Buonanno-Faye:2006}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{subequations}\n\\begin{align}\n\\bm{S}_{\\rm c}&= \\bm{S}+\\frac{G m \\nu}{r c^2}\\left[2 \\bm{S}+\n\\delta\\,\\bm{\\Sigma}\\right]\\nonumber\\\\\n&-\\frac{\\nu}{2 c^2}\\left[(\\bm{v}\\cdot \\bm{S})+\n\\delta\\,(\\bm{v}\\cdot \\bm{\\Sigma})\\right]\\bm{v}\\, ,\\\\\n%%%%\n\\bm{\\Sigma}_{\\rm c}&= \\bm{\\Sigma}+\\frac{G m}{r c^2}\\left[\\delta\\,\\bm{S}\n+(1-2\\nu)\\bm{\\Sigma}\\right]\\nonumber\\\\\n&-\\frac{1}{2 c^2}\\left[\\delta\\,(\\bm{v}\\cdot \\bm{S})+\n(1-3\\nu)(\\bm{v}\\cdot \\bm{\\Sigma})\\right]\\bm{v}. \\ \\ \\ \\ \\ \\ \\ \\\n\\end{align}\n\\end{subequations}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Waveforms with spin effects at 2PN order }\n\n\\subsection{General formalism}\n\\label{subsec:general}\n\nThe gravitational radiation from the two-body system is calculated from\nsymmetric trace-free radiative multipole moments $I_{L}$ and $J_{L}$ using the\ngeneral formula from Ref.~\\cite{thorne80} truncated at 2PN order\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{align} \\label{eq:hij}\n&h_{ij}^{\\mathrm{ TT}}=\\frac{2G}{Rc^4}\\bigg\\{I_{ab}^{(2)}+\n\\frac{1}{3c} I_{ abc}^{(3)}N^c+\\frac{1}{12 c^2}I_{abcd}^{(4)}\nN^{c}N^{d}\\nonumber\\\\ &+\n\\frac{1}{60 c^3}I^{(5)}_{ abcde}N^{c}N^{d}N^{e}+\\frac{1}{360c^4}\nI^{(6)}_{abcdef}N^{c}N^{d}N^{e}N^{f} \\nonumber\\\\\n& + N^{k}\\varepsilon_{cka}\\bigg[\\frac{4}{3c}J_{ bc}^{(2)}+\n\\frac{1}{2c^2}J_{ bcd }^{(3)}N^d +\\frac{2}{15 c^3}\nJ_{ bcde}^{(4)}N^{d}N^{e}\\nonumber\\\\\n& \\qquad \\qquad +\n\\frac{1}{36c^4}J_{ bcdef}^{(5)}N^{d}N^{e}N^{f}\\bigg]\\bigg\\}{\\cal P}_{ijab}^{\\mathrm{TT}},\n\\end{align}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nwhere $\\bm{N}$ is the unit vector pointing from the center of mass\nof the source to the observer's location and $R$ is the distance\nbetween the source and the observer. Here, the superscript ${(n)}$\nsignifies the $n$th time derivative, and the transverse-traceless\nprojection operator is\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{equation}\n{\\cal P}_{ijab}^{\\mathrm{TT}}={\\cal P}_{a(i}{\\cal P}_{j)b}-\n\\frac{1}{2}{\\cal P}_{ij}{\\cal P}_{ab},\n\\end{equation}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nwith ${\\cal P}_{ij}=\\delta_{ij}-N_{i}N_{j}$.\n\nThe gravitational radiation (\\ref{eq:hij}) can be rewritten in a\npost-Newtonian expansion as\n%\n\\begin{align}\n\\label{eq:hexpansion} h_{ij}^{\\mathrm{TT}} =&\\frac{1}{c^4}\\,\\bigg[\nh^{\\rm Newt}_{{ij~{\\mathrm{TT}}}} + \\frac{1}{c^2}\\,h^{\\rm\n1PN}_{{ij~{\\mathrm{TT}}}}+\\frac{1}{c^2}\\,h^{\\rm 1PN SO}_{{ij \\\n{\\mathrm{TT}}}} +\n\\frac{1}{c^3}\\,h^{\\rm 1.5PN  SO}_{{ij \\   {\\mathrm{TT}}}} \\hfill ~ \\; \\; \\; \\;  \\; ~ \\; \\nonumber \\\\\n& \\; \\; + \\frac{1}{c^4}\\,h^{\\rm 2PN}_{{ij \\   {\\mathrm{TT}}}} +\n\\frac{1}{c^4}\\,h^{\\rm 2PN  SO}_{{ij \\   {\\mathrm{TT}}}} +\n\\frac{1}{c^4}\\,h^{\\rm 2PN  SS}_{{ij \\   {\\mathrm{TT}}}} + \\cdots\\bigg]\\,.  \n\\end{align}\n%\nThe 1PN and 1.5PN spin terms are given explicitly in Refs.\n\\cite{Kidder:1995zr, Arun:2009}. The terms in the source multipole\nmoments that are \\textit{a priori} needed to compute the spin-orbit\nwaveform exactly at 2PN order are identified by considering their\nschematic structure,\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{subequations}\n\\begin{align} I_{L} &=I_{L}^{\\rm Newt}+\n\\frac{1}{c^2}I_{L}^{\\rm 1PN}+\\frac{1}{c^3}I_{L}^{\\rm SO}\\nonumber \\\\ & \\qquad\n\\quad~~ +\n\\frac{1}{c^4}(I_{L}^{\\rm 2PN}+I_L^{\\rm SS}) \\,, \\label{eq:ulstruct}\\\\\nJ_{L}&=J_{L}^{\\rm Newt}+\\frac{1}{c}J_{L}^{\\rm\nSO}+\\frac{1}{c^2}J_{L}^{\\rm 1PN} \\nonumber \\\\ & \\qquad\n\\quad~~ +\n\\frac{1}{c^3}J_{L}^{\\rm 1.5PNSO}\\,,\n\\label{eq:vlstruct}\n\\end{align}\n\\end{subequations}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ntogether with the scalings of Eqs.~(\\ref{eq:hij}) and\n(\\ref{eq:eomscale}). Specifically, the following pieces are\nrequired: $(I_{abc}^{\\rm Newt})^{(3)}$ using the $1.5$PN motion and\n$(I_{abc}^{\\rm SO})^{(3)}$ with $\\bm{a}^{\\rm Newt}$, $(J_{ab}^{\\rm\nSO})^{(2)}$ with the 1PN motion and the spin evolution, $(J_{ab}^{\n\\rm 1.5PNSO})^{(2)}$ with $\\bm{a}^{\\rm Newt}$, $(J_{ab}^{ \\rm\nNewt})^{(2)}$ with the $1.5$PN accurate motion, and $(J_{abcd}^{\\rm\nSO})^{(4)}$ with $\\bm{a}^{\\rm Newt}$. For the SS part, we need\n$(I_{ab}^{\\rm Newt})^{(2)}$ with $a^{\\rm SS}$, as the time\nderivative of $I_{ab}^{\\rm SS}$ does not contribute at 2PN order.\nWhen we write the waveform in terms of the constant magnitude spin\nvariables, there is an additional contribution to the 2PN spin piece\nof the waveform coming from $J_{ab}^{\\rm SO}$ with $\\bm{a}^{\\rm\nNewt}$ and the 1PN conversion factor in $\\Sigma^{\\rm c}$. The\nrelevant spin contributions to the multipole moments\nare~\\cite{Blanchet-Buonanno-Faye:2006}\n\\begin{widetext}\n\\begin{subequations}\n\\begin{align}\\label{JijS}\nJ^{\\rm spin}_{ij} &=\n\\frac{\\nu}{c}\\biggl\\{-\\frac{3}{2} r \\,n^{\\langle\ni}\\, \\Sigma^{ j\\rangle}\\biggr\\}\\nonumber\\\\\n%%\n&+\n\\frac{\\nu}{c^3}\\biggl\\{\\left(\\frac{3}{7}-\\frac{16}{7}\\nu\\right)\nr \\, \\dot r\\,v^{\\langle i}\\, \\Sigma^{j\\rangle} +\n\\frac{3}{7} \\,\\delta \\, r \\, \\dot r\n\\,v^{\\langle i}\\,S^{j\\rangle} +\n\\left[\\left(\\frac{27}{14}-\\frac{109}{14}\\nu\\right)\n(\\bm{v}\\cdot\\bm{\\Sigma}) + \\frac{27}{14} \\delta\n\\,(\\bm{v}\\cdot\\bm{S})\\right] r \\, n^{\\langle\ni}\\, v^{j\\rangle}\\nonumber\\\\\n%%%\n& \\qquad  +\n\\left[\\left(-\\frac{11}{14}+\\frac{47}{14}\\nu\\right)\n(\\bm{n}\\cdot\\bm{\\Sigma}) - \\frac{11}{14} \\delta\n\\,(\\bm{n}\\cdot\\bm{S})\\right]r \\,  v^{\\langle i} \\ v^{j\\rangle} +\n\\left[\\left(\\frac{19}{28}+\\frac{13}{28}\\nu\\right) \\frac{G m}{r} +\n\\left(-\\frac{29}{28}+\\frac{143}{28}\\nu\\right) v^2\\right] r \\, n^{\\langle\ni} \\, \\Sigma^{ j\\rangle}\\nonumber\\\\\n%%%\n&\\qquad  +\n\\left[\\left(-\\frac{4}{7}+\\frac{31}{14}\\nu\\right) (\\bm{n}\\cdot\n\\bm{\\Sigma}) - \\frac{29}{14} \\delta\n\\,(\\bm{n}\\cdot \\bm{S})\\right] G m  \\, n^{\\langle\ni}\\, n^{j\\rangle} + \\left[-\\frac{1}{14}\\frac{G m}{r} -\n\\frac{2}{7} v^2\\right] \\delta\\, r\n\\, n^{\\langle i}\\, S^{j\\rangle}\\biggr\\}\\,, \\\\\nI^{\\rm spin}_{ijk} &=\n\\frac{\\nu}{c^3} \\, r^2 \\, \\biggl\\{-\\frac{9}{2}\\,\\delta\n\\,n^{\\langle i}n^j(\\bm{v}\\times\\bm{S})^{k\\rangle}-\n\\frac{3}{2}\\,(3-11\\nu)\\,n^{\\langle i}n^j(\\bm{v}\\times\\bm{\\Sigma})^{k\\rangle}\n\\nonumber\\\\\n& \\qquad \\quad~~ +3\\,\\delta \\,n^{\\langle i} v^j(\\bm{n}\\times\\bm{S})^{k\\rangle}+\n3\\,(1-3\\nu)\\,n^{\\langle i}v^j(\\bm{n}\\times \\bm{\\Sigma})^{k\\rangle}\\biggr\\} \\,,\\\\\nJ^{\\rm spin}_{ijkl} &=\n-\\frac{5\\nu}{2 c} \\, r^3 \\, \\left\\{\\delta\\, n^{\\langle i}n^j n^k S^{l\\rangle}+\n(1-3\\nu)n^{\\langle i}n^{j} n^{k}\\Sigma^{l\\rangle}\\right\\}\\,.\n\\end{align}\n\\label{spinmultis}\n\\end{subequations}\n\\end{widetext}\n\nThe nonspinning contributions to the multipole moments that we employed in our\ncalculation are\n%\n\\begin{subequations}\n \\label{nonspinmultis}\n\\begin{align}\nI_{ij} &=m\\nu  \\, r^2 \\, n^{\\langle i}n^{j\\rangle}\\,, \\\\\nI_{ijk} &= -m\\nu\\, r^3 \\, \\delta  \\, n^{\\langle i} n^j n^{k \\rangle}\\,, \\\\\nJ_{ij} &=- m\\nu\\, r^2 \\,  \\delta \\,\n\\varepsilon_{ab\\langle i} n^{j\\rangle}n^{ a}v^b \\,.\n\\end{align}\n\\end{subequations}\n\n\n\\subsection{Spin-orbit effects}\n\\label{sec:SO}\nUsing the multipole moments of Eqs. (\\ref{spinmultis}) and\n(\\ref{nonspinmultis}) in Eq. (\\ref{eq:hij}) and substituting the equations of\nmotion (\\ref{eq:eom}) and (\\ref{eq:aspinspin}), we find the following 2PN\nspin-orbit piece:\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{widetext}\n\\begin{align}\n\\label{eq:hijSO}\nh_{ij \\ {\\rm{TT}}}^{\\rm 2PN SO}&=\n\\frac{2 G^2 m\\nu}{r^2R}{\\cal P}^{\\rm TT}_{ijab}\\Bigg\\{\nn^a \\, n^b \\left[\\frac{5}{2} (3-13\\nu) \\, \\dot r^2 \\, (\\bm{n}\\times\n\\bm{\\Sigma}_{\\rm c})\\cdot \\bm{N} +30 (1-4\\nu)(\\bm{n}\\cdot \\bm{N}) \\,\n\\dot r \\, (\\bm{n}\\times\\bm{v})\\cdot \\bm{\\Sigma}_{\\rm c}\n\\right.\\nonumber\\\\\n& \\left. \\; \\; \\; -\n(7-29\\nu) \\, \\dot r \\, (\\bm{v}\\times \\bm{\\Sigma}_{\\rm c})\\cdot \\bm{N}\n -6(1-4\\nu) (\\bm{v}\\cdot\n\\bm{N})(\\bm{n}\\times\\bm{v})\\cdot \\bm{\\Sigma}_{\\rm c} -\n\\frac{1}{2}(3-13\\nu) \\, v^2\n\\, (\\bm{n}\\times \\bm{\\Sigma}_{\\rm c})\\cdot \\bm{N}\n\\right.\\nonumber\\\\\n& \\left. \\; \\; \\; - \\frac{2G m}{3r}(1-5\\nu)\n(\\bm{n}\\times \\bm{\\Sigma}_{\\rm c})\\cdot \\bm{N} +\\delta \\left(\n\\frac{35}{2}\\,  \\dot r^2 \\, (\\bm{n}\\times \\bm{S}_{\\rm c})\\cdot \\bm{N}-\n\\frac{7}{2} \\, v^2 \\,  (\\bm{n}\\times \\bm{S}_{\\rm c})\\cdot \\bm{N} +\n\\ 60 (\\bm{n}\\cdot \\bm{N}) \\, \\dot r (\\bm{n}\\times\\bm{v})\\cdot \\bm{S}_{\\rm c}\n\\right.\\right. \\nonumber\\\\\n&  \\; \\; \\;  -\n12(\\bm{v}\\cdot \\bm{N})(\\bm{n}\\times\\bm{v})\\cdot \\bm{S}_{\\rm c} -13 \\, \\dot r \\,\n(\\bm{v}\\times \\bm{S}_{\\rm c})\\cdot \\bm{N} \\bigg) \\bigg]\\, +\n\\, n^{a}(\\bm{n}\\times \\bm{S}_{\\rm c})^{b} \\delta \\bigg[\n35 (\\bm{n}\\cdot \\bm{N}) \\, \\dot r^2-\n14 (\\bm{v}\\cdot \\bm{N}) \\, \\dot r-\n7 (\\bm{n}\\cdot \\bm{N}) \\, v^2 \\bigg]\\nonumber\\\\\n%%%%\n%%%%\n& + n^{a}(\\bm{n}\\times \\bm{N})^{b}\\left[\\frac{5}{2}(3-13\\nu)\n\\, \\dot r^2 \\, (\\bm{n}\\cdot \\bm{\\Sigma}_{\\rm c})-\\frac{1}{2}(3-13\\nu) \\,\nv^2  \\, (\\bm{n}\\cdot \\bm{\\Sigma}_{\\rm c})+\n\\frac{15}{2}(1-3\\nu) \\, \\dot r^2\n\\, (\\bm{n}\\cdot \\bm{N}) (\\bm{N}\\cdot \\bm{\\Sigma}_{\\rm c}) \\right.\\nonumber\\\\\n& \\left. \\; \\; \\;   -5 (1-3\\nu)\\, \\dot r \\,\n(\\bm{v}\\cdot \\bm{N}) (\\bm{N}\\cdot \\bm{\\Sigma}_{\\rm c}) -\n\\frac{3}{2}(1-3\\nu) \\, v^2\n\\, (\\bm{n}\\cdot \\bm{N})(\\bm{N}\\cdot \\bm{\\Sigma}_{\\rm c})-\\frac{2Gm}{r}(1-3\\nu)\n(\\bm{n}\\cdot \\bm{N}) (\\bm{N}\\cdot \\bm{\\Sigma}_{\\rm c})\\right.\\nonumber\\\\\n&\\left. \\; \\; \\; +\n\\frac{4Gm}{3r}(1-5\\nu) (\\bm{n}\\cdot \\bm{\\Sigma}_{\\rm c}) -\n(3+11\\nu) \\, \\dot r \\,  (\\bm{v}\\cdot \\bm{\\Sigma}_{\\rm c})+\n\\delta \\left(\\frac{4Gm}{r} (\\bm{n}\\cdot \\bm{S}_{\\rm c}) +\n\\frac{35}{2}\\, \\dot r^2 \\, (\\bm{n}\\cdot \\bm{S}_{\\rm c}) -\n\\frac{7}{2}  \\, v^2  \\, (\\bm{n}\\cdot \\bm{S}_{\\rm c})\\right. \\right.\\nonumber\\\\\n&\\left. \\; \\; \\;+\n\\frac{15}{2}  \\, \\dot r^2 \\,(\\bm{n}\\cdot \\bm{N}) (\\bm{N}\\cdot \\bm{S}_{\\rm c})-\n\\frac{2Gm}{r}(\\bm{n}\\cdot \\bm{N}) (\\bm{N}\\cdot \\bm{S}_{\\rm c})-\n\\frac{3}{2}  \\, v^2  \\, (\\bm{n}\\cdot \\bm{N})(\\bm{N}\\cdot \\bm{S}_{\\rm c}) -\n5 \\, \\dot r \\, (\\bm{v}\\cdot \\bm{N}) (\\bm{N}\\cdot \\bm{S}_{\\rm c}) +\n\\, \\dot r \\, (\\bm{v}\\cdot \\bm{S}_{\\rm c}) \\bigg) \\right]\n\\nonumber\\\\\n%%%\n%%%\n&+ n^{a}(\\bm{n}\\times \\bm{\\Sigma}_{\\rm c})^{b}\n\\bigg[5 (3-13\\nu)(\\bm{n}\\cdot \\bm{N})\\, \\dot r^2\\, -\n(3-13\\nu) (\\bm{n}\\cdot \\bm{N})\\, v^2-2(3-14 \\nu)(\\bm{v}\\cdot \\bm{N}) \\,\n\\dot r  \\nonumber\\\\\n&\\left. \\; \\; \\; -\n\\frac{4Gm}{3r}(1-5\\nu)(\\bm{n}\\cdot \\bm{N}) \\right]\\, +\n\\, n^{a}(\\bm{n}\\times\\bm{v})^{b} \\, \\dot r \\,  \\left[2\n(1-4\\nu)(\\bm{N}\\cdot \\bm{\\Sigma}_{\\rm c})+6 \\delta\\,\n(\\bm{N}\\cdot \\bm{S}_{\\rm c})\\right]\\nonumber\\\\\n%%%\n%%%\n&+ (\\bm{n}\\times\\bm{N})^{a} \\Sigma_{\\rm c}^{b}\n\\left[ \\frac{5}{4} (1+7\\nu)\\, \\dot r^2 +\n\\frac{15}{4} (1-3\\nu) (\\bm{n}\\cdot \\bm{N})^2 \\, \\dot r^2 -\n5(1-3\\nu) (\\bm{n}\\cdot \\bm{N})(\\bm{v}\\cdot \\bm{N})\\dot r+\n\\frac{5}{3}(1-3\\nu) (\\bm{v}\\cdot \\bm{N})^2\\right.\\nonumber\\\\\n& \\left. \\; \\; \\; + \\frac{1}{12} (11-25\\nu) v^2-\n\\frac{3}{4}(1-3\\nu) (\\bm{n}\\cdot \\bm{N})^2 \\, v^2 -\n\\frac{G m}{3r} (11+2\\nu)-\\frac{G m}{r}(1-3\\nu) (\\bm{n}\\cdot \\bm{N})^2\\right]\n\\, \\nonumber\\\\\n%%%%\n& +  (\\bm{n}\\times\\bm{N})^{a} S_{\\rm c}^{ b}\n\\ \\delta\\left[-\\frac{5}{4}\\, \\dot r^2+\n\\frac{15}{4} (\\bm{n}\\cdot \\bm{N})^2 \\, \\dot r^2-\n5(\\bm{n}\\cdot \\bm{N})(\\bm{v}\\cdot \\bm{N}) \\, \\dot r+\n\\frac{5}{3}(\\bm{v}\\cdot \\bm{N})^2+\\frac{1}{4} \\, v^2\\right. \\nonumber\\\\\n& \\left. \\; \\; \\;   -\\frac{3}{4} (\\bm{n}\\cdot \\bm{N})^2 \\, v^2 -\n\\frac{G m}{r} (\\bm{n}\\cdot \\bm{N})^2\\right] \\, +\n\\, (\\bm{n}\\times\\bm{v})^{a}\\Sigma_{\\rm c}^{b}\n\\ (1-4\\nu) \\bigg[2(\\bm{v}\\cdot \\bm{N})-\n2(\\bm{n}\\cdot \\bm{N})  \\dot r\\bigg] \\nonumber\\\\\n%%%\n%%%\n& +n^{a} \\, v^{ b}\\left[36 (-1+4\\nu) (\\bm{n}\\cdot \\bm{N})\n(\\bm{n}\\times \\bm{v}) \\cdot \\bm{\\Sigma}_{\\rm c} -4(2-9\\nu) \\, \\dot r\n\\, (\\bm{n}\\times \\bm{\\Sigma}_{\\rm c})\\cdot \\bm{N}+\n\\frac{2}{3}(13-55\\nu) (\\bm{v}\\times\n\\bm{\\Sigma}_{\\rm c})\\cdot \\bm{N}\n\\right.\\nonumber\\\\\n&\\left. \\; \\; \\; +\\delta \\left(\n -72 (\\bm{n}\\cdot \\bm{N}) (\\bm{n}\\times \\bm{v}) \\cdot \\bm{S}_{\\rm c}-\n20 \\, \\dot r\\, (\\bm{n}\\times \\bm{S}_{\\rm c})\\cdot \\bm{N}+\n\\frac{50}{3} (\\bm{v}\\times \\bm{S}_{\\rm c})\\cdot \\bm{N}\\right)\\right]\n\\nonumber\\\\\n%%%\n%%%\n&+ (\\bm{n}\\times\\bm{v})^{a} S_{\\rm c}^{b}\n\\delta\\left[-6 (\\bm{n}\\cdot \\bm{N})  \\dot r+\n\\frac{14}{3}(\\bm{v}\\cdot \\bm{N}) \\right]\\, +\nn^{a} (\\bm{v}\\times \\bm{S}_{\\rm c})^{b} \\delta\n\\bigg[-26 \\, \\dot r \\, (\\bm{n}\\cdot \\bm{N})+\n12 (\\bm{v}\\cdot \\bm{N})\\bigg]\\nonumber\\\\\n%%%%\n& +  n^{a}(\\bm{v}\\times \\bm{\\Sigma}_{\\rm c})^{b}\\left[\n2(-7+29\\nu) \\, \\dot r \\, (\\bm{n}\\cdot \\bm{N}) +\n\\frac{2}{3}(10-43\\nu) (\\bm{v}\\cdot \\bm{N})\\right] \\, +\n\\, v^{a}(\\bm{v}\\times\\bm{S}_{\\rm c})^{b} \\,  \\delta\\,\n\\frac{64}{3} (\\bm{n}\\cdot \\bm{N})\\nonumber\\\\\n%%%\n& + v^{a}(\\bm{n}\\times \\bm{\\Sigma}_{\\rm c})^{b}\n\\left[-2(5-22\\nu)\\, \\dot r \\, (\\bm{n}\\cdot \\bm{N})+\\frac{4}{3}\\left(1-\n6 \\nu\\right) (\\bm{v}\\cdot \\bm{N}) \\right]  \\, +\n\\,  v^{a}(\\bm{v}\\times \\bm{\\Sigma}_{\\rm c})^{b}\n\\ \\frac{2}{3} (16-67 \\nu) (\\bm{n}\\cdot \\bm{N})\\nonumber\\\\\n%%%\n&  +v^{a}(\\bm{n}\\times \\bm{S}_{\\rm c})^{b} \\delta\\left[\n-26 \\, \\dot r \\, (\\bm{n}\\cdot \\bm{N})+\n\\frac{4}{3}(\\bm{v}\\cdot \\bm{N})\\right]\\, +\n\\, v^{a} (\\bm{n}\\times \\bm{v})^{b} \\left[\n2(-1+4\\nu) (\\bm{N}\\cdot \\bm{\\Sigma}_{\\rm c}) -\n\\frac{14}{3}\\delta\\, (\\bm{N}\\cdot \\bm{S}_{\\rm c})\\right]\n\\nonumber\\\\\n%%%%\n& + v^{a}(\\bm{n}\\times \\bm{N})^{b}\\left[-(3-23\\nu)\\,\n\\dot r\\, (\\bm{n}\\cdot\\bm{\\Sigma}_{\\rm c})-\n5 (1-3\\nu)\\, \\dot r\\, (\\bm{n}\\cdot \\bm{N})(\\bm{N}\\cdot \\bm{\\Sigma}_{\\rm c})+\n\\frac{2}{3}(1+8\\nu) (\\bm{v}\\cdot \\bm{\\Sigma}_{\\rm c})\\right.\\nonumber\\\\\n&\\left. \\; \\; \\;  +\n\\frac{10}{3}(1-3\\nu)(\\bm{v}\\cdot \\bm{N}) (\\bm{N}\\cdot \\bm{\\Sigma}_{\\rm c})+\n\\delta \\left(\n\\frac{10}{3} (\\bm{v}\\cdot \\bm{N}) (\\bm{N}\\cdot \\bm{S}_{\\rm c})-\n11  \\, \\dot r\\, (\\bm{n}\\cdot \\bm{S}_{\\rm c})-\n5 \\, \\dot r\\, (\\bm{n}\\cdot \\bm{N})(\\bm{N}\\cdot \\bm{S}_{\\rm c})\n\\right.\\right.\\nonumber\\\\\n& \\; \\; \\;   -\n\\frac{2}{3} (\\bm{v}\\cdot \\bm{S}_{\\rm c}) \\bigg)\\bigg] \\, +\n\\, S_{\\rm c}^{a} (\\bm{v}\\times \\bm{N})^{b} \\delta\\left[\n\\frac{5}{6}\\, \\dot r-\\frac{5}{2} \\, \\dot r \\, (\\bm{n}\\cdot \\bm{N})^2+\n\\frac{10}{3}(\\bm{v}\\cdot \\bm{N})(\\bm{n}\\cdot \\bm{N})\\right]\\nonumber\\\\\n%%%\n%%%\n& + \\Sigma_{\\rm c}^{a} (\\bm{v}\\times \\bm{N})^{b} \\left[\n-\\frac{29}{6}(1+\\nu) \\, \\dot r -\n\\frac{5}{2} (1-3\\nu) \\, \\dot r \\, (\\bm{n}\\cdot \\bm{N})^2+\n\\frac{10}{3} (1-3\\nu) (\\bm{v}\\cdot \\bm{N}) (\\bm{n}\\cdot \\bm{N}) \\right]\n\\nonumber\\\\\n%%%\n%%%\n& + v^{a} (\\bm{v}\\times \\bm{N})^{b}\\left[\n-\\frac{40\\nu}{3} (\\bm{n}\\cdot \\bm{\\Sigma}_{\\rm c})+\n\\frac{10}{3} (1-3\\nu)(\\bm{n}\\cdot \\bm{N}) (\\bm{N}\\cdot \\bm{\\Sigma}_{\\rm c}) +\n\\delta \\left(\\frac{20}{3} (\\bm{n}\\cdot \\bm{S}_{\\rm c}) +\n\\frac{10}{3} (\\bm{n}\\cdot \\bm{N})(\\bm{N}\\cdot \\bm{S}_{\\rm c}) \\right)\\right]\n\\nonumber\\\\\n%%%\n&+  v^{a} \\, v^{b} \\left[\n \\left(\\frac{2}{3}-4\\nu\\right)(\\bm{n}\\times \\bm{\\Sigma}_{\\rm c})\\cdot \\bm{N}+\n\\frac{2}{3} \\delta\\,(\\bm{n}\\times \\bm{S}_{\\rm c})\\cdot \\bm{N}\n\\right]\\nonumber\\\\\n%%%%\n&\\, +({\\bm\\Sigma}_{\\rm c} \\times\n\\bm{N})^{a}n^{b}\\bigg[\\frac{5}{4}(1+7\\nu)\\dot r^2+\\frac{15}{4}(1-3\\nu)\\dot\nr^2(\\bm{n}\\cdot \\bm{N})^2+5(-1+3\\nu)\\dot r(\\bm{n}\\cdot \\bm{N})(\\bm{v}\\cdot\n\\bm{N})+\\frac{5}{3}(1-3\\nu)(\\bm{v}\\cdot \\bm{N})^2\\nonumber\\\\\n& \\; \\; \\; +\\frac{1}{12}(11-25\\nu)v^2+\\frac{3}{4}(-1+3\\nu)(\\bm{n}\\cdot\n\\bm{N})^2 v^2\n%-\\frac{m}{3r}(11+2\\nu)\n+\\frac{G m}{3r}(-17+10\\nu)+\\frac{G m}{r}(-1+3\\nu)(\\bm{n}\\cdot\n\\bm{N})^2\\bigg]\\nonumber\\\\\n%%%%%%%%\n&  +({\\bm S}_{\\rm c}\\times \\bm{N})^{a}{n}^{b}\\delta\\bigg[-\\frac{5}{4}\\dot\nr^2+\\frac{15}{4}\\dot r^2({\\bm n}\\cdot \\bm{N})^2-5\\dot r ({\\bm n}\\cdot\n\\bm{N})({\\bm v}\\cdot \\bm{N})+\\frac{5}{3}({\\bm v}\\cdot\n\\bm{N})^2+\\frac{1}{4}v^2-\\frac{3}{4}v^2 ({\\bm n}\\cdot \\bm{N})^2\\nonumber\\\\\n& \\; \\; \\; -\\frac{2G m}{r}-\n\\frac{G m}{r}({\\bm n}\\cdot \\bm{N})^2\\bigg]\\nonumber\\\\\n%%%%%%\n&+(\\bm{\\Sigma}_{\\rm c}\\times \\bm{N})^{a}v^{b}\\bigg[-\\frac{29}{6}(1+\\nu)\\dot\nr+\\frac{5}{2}(-1+3\\nu)\\dot r(\\bm{n}\\cdot\n\\bm{N})^2+\\frac{10}{3}(1-3\\nu)(\\bm{n}\\cdot \\bm{N})(\\bm{v}\\cdot\n\\bm{N})\\bigg]\\nonumber\\\\\n&  +(\\bm{S}_{\\rm c}\\times \\bm{N})^{a}v^{b}\\delta\\bigg[\\frac{5}{6}\\dot\nr-\\frac{5}{2}\\dot r (\\bm{n}\\cdot \\bm{N})^2+\\frac{10}{3}(\\bm{n}\\cdot\n\\bm{N})(\\bm{v}\\cdot \\bm{N})\\bigg]\\nonumber\\\\\n& +(\\bm{v}\\times \\bm{N})^{a}n^{b}\\bigg[(-3+23 \\nu)\\dot r (\\bm{n}\\cdot\n\\bm{\\Sigma}_{\\rm c})+5(-1+3\\nu) \\dot r(\\bm{n}\\cdot \\bm{N})(\\bm{\\Sigma}_{\\rm\n  c}\\cdot \\bm{N})%+\\frac{2}{3}(1+8\\nu)\n+\\frac{1}{3}(5+7\\nu) (\\bm{v}\\cdot \\bm{\\Sigma}_{\\rm c})\\nonumber\\\\\n& \\; \\; \\; +\\frac{10}{3}(1-3\\nu)(\\bm {v}\\cdot \\bm{N})(\\bm{\\Sigma}_{\\rm\n  c}\\cdot \\bm{N})+ \\delta \\left(-11\\dot r (\\bm{n}\\cdot \\bm{S}_{\\rm c})-5 \\dot\n  r (\\bm{n}\\cdot \\bm{N})(\\bm{S}_{\\rm c}\\cdot \\bm{N})%-\\frac{2}{3}\n+\\frac{1}{3}(\\bm{v}\\cdot \\bm{S}_{\\rm\n  c})+\\frac{10}{3}(\\bm{v}\\cdot\\bm{N})(\\bm{S}_{\\rm c}\\cdot \\bm{N})\\right)\n\\bigg] \\ \\ \\ \\ \\ \\\n\\end{align}\n\\end{widetext}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%Here, we have omitted the structures $\\delta^{ij}$ and $N^i$ which would be\n%annihilated by the TT-projection.\nThese contributions add linearly to the other known terms in the\nwaveform. Note that in Eq. (\\ref{eq:hijSO}) we have already\nanticipated the transverse-traceless projection and simplified the\nexpression using\n$\\delta^{ij}_{\\mathrm{TT}}=N^i_{\\mathrm{TT}}=N^j_{\\mathrm{TT}}=0$\nand the interchange identity \\cite{Kidder:1995zr}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{equation}\n {\\cal P}_{ijab}^{\\mathrm{TT}} \\  A^a (\\bm{B}\\times \\bm{N})^b=\n{\\cal P}_{ijab}^{\\mathrm{TT}}\\  B^a(\\bm{A}\\times \\bm{N})^b,\n\\end{equation}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfor any vectors $\\bm{A}$ and $\\bm{B}$.\n\n\n\n\\subsection{Spin-spin effects}\n\\label{sec:SS}\n\nSpin-spin terms in the waveform at 2PN order are entirely\nattributable to the equations of motion; they arise when\nsubstituting $\\bm{a}^{\\rm SS}$ in the time derivatives of\n$I_{ab}^{\\rm Newt}$. The second time derivative of the contribution\n$I_{ab}^{\\text{S}^2}$ given in Eq.~\\eqref{eq:ISSresult} is at least\nof 3PN order (because of the fact that spins are constant at leading\napproximation) and therefore vanishes for our calculation. We derive\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \\begin{align}\n\\label{eq:hijSS}\n  h^{\\rm 2PN  SS}_{{ij \\   {\\mathrm{TT}}}} &=\\frac{6G^2 \\nu}{r^3 R} {\\cal\n    P}_{ijab}^{\\mathrm{TT}}\n\\bigg\\{ \\nonumber \\\\ & \\quad ~ n^a \\, n^b  \\Big[5 (\\bm{n}\\cdot\n\\bmSeffp)(\\bm{n}\\cdot \\bmSeffm)-\n (\\bmSeffp\\cdot \\bmSeffm) \\Big]\\nonumber\\\\\n%%%%\n& \\qquad ~ -  n^a \\, \\Seffp^b (\\bm{n}\\cdot \\bmSeffm)- n^a \\,\n\\Seffm^b (\\bm{n}\\cdot \\bmSeffp)  \\bigg\\}\\,.\n\\end{align}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nWe notice that the spin-orbit contributions at 2PN order are zero\nfor an equal-mass, equal-spin black-hole binary. This is a\nconsequence of the multipoles (\\ref{spinmultis}) being zero for this\nhighly symmetric binary configuration.\n\nThe general results (\\ref{eq:hijSO}) and (\\ref{eq:hijSS}) are\navailable as a \\textsc{mathematica} notebook upon request to be used\nto compute the gravitational polarizations and spherical harmonic\nmodes for precessing binaries for any choice of the source frame and\nthe polarization triad~\\cite{Finn1993,\n  Kidder:1995zr,Buonanno:2002fy,Schmidt:2010it,OShaughnessy2011, Ochsner2012,\n  2011PhRvD..84l4011B,Schmidt:2012rh}. Below, we shall derive the\npolarizations and spin-weighted spherical-harmonic modes for the\ncase of nonprecessing compact binaries on circular orbits.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\subsection{Reduction to quasicircular orbits}\n\nWe now specialize Eqs.~(\\ref{eq:hijSO}) and (\\ref{eq:hijSS}) to the\ncase of orbits that have a constant separation $r$ in the absence of\nradiation reaction and for which the precession time scale is much\nlonger than an orbital period.  The details of the derivation of the\nmodified Kepler law relating the orbit-averaged orbital angular\nfrequency $\\omega$ and the orbit-averaged orbital separation are\ndiscussed in Ref.~\\cite{Racine2008}. The instantaneous accelerations\n(\\ref{eq:eom}) and (\\ref{eq:ssaccel}) are projected onto a triad\nconsisting of the following unit vectors: $\\bm{n}=\\bm{x}/r$, the\nvector $\\bm{\\ell}=\\bm{L}_{\\rm N}/|\\bm{L}_{\\rm N}|$ orthogonal to the\ninstantaneous orbital plane, where $\\bm{L}_{\\rm N}=m\\nu\\,\n\\bm{x}\\times \\bm{v}$ denotes the Newtonian orbital angular momentum,\nand $\\bm{\\lambda}=\\bm{\\ell}\\times \\bm{n}$. The orbital separation\n$r$ and angular frequency $\\omega$ are decomposed into their orbit\naveraged piece, indicated by an overbar, and remaining fluctuating\npieces, $r=\\bar r+\\delta r$ and $\\omega=\\bar \\omega+\\delta \\omega$.\nProjecting the equations of motion along $\\bm{\\lambda}$ yields the\nequality $2 \\omega \\, \\dot{r} + \\dot{\\omega}\\, r$ or,\nequivalently~\\cite{Racine2008}\n%\n\\begin{equation}\n\\frac{d}{dt} (\\omega\\, r^2) = - \\frac{3G}{2 m \\omega\\,r^3c^4} \\frac{d}{dt}\n(\\bm{n} \\cdot \\bmSeffp) (\\bm{n} \\cdot \\bmSeffm) \\, .\n\\end{equation}\n%\nAt the 2PN order, $r$ and $\\omega$ can be replaced by the constants\n$\\overline{r}$ and $\\overline{\\omega}$, respectively, on the right-hand side.\nThe expression for $\\omega\\, r^2$ follows from (i) dropping the time\nderivatives in the above equation, and (ii) adding an integration constant\ndetermined by averaging $\\omega\\, r^2$ over an orbit. Inserting the result in\nthe projection along $\\bm{n}$ of the equations of motion,\n%\n\\begin{equation}\n\\ddot{r} - \\omega^2 r =  (\\bm{n}\\cdot \\bm{a}) \\,\n\\end{equation}\n%\nand linearizing in $\\delta r$ we find an explicit solution to the differential\nequation given by\n%\n\\begin{subequations}\n\\begin{align}\n\\label{eq:rdot}\n\\dot{r} &= \\frac{d\\delta r}{dt} \\nonumber \\\\ &\n= - \\frac{\\omega}{2 m^2 r c^4}\n[(\\bm{n} \\cdot \\bmSeffp) (\\bm{\\lambda} \\cdot \\bmSeffm) +\n(\\bm{\\lambda}\\cdot \\bmSeffp) (\\bm{n}\\cdot \\bmSeffm)]  \\, ,\\\\\n\\omega^2 &= \\frac{\\ddot{r}-(\\bm{n} \\cdot \\bm{a})}{r} \\nonumber \\\\*\n&  = \\frac{G m}{r^3} \\Big[1 - (3-\\nu) \\frac{G m}{rc^2} \\nonumber \\\\*\n& \\qquad  \\quad- \\Big(\\frac{G m}{r c^2}\\Big)^\\frac{1}{2}\n\\frac{5 (\\bm{\\ell}\\cdot \\bm{S}_{\\rm c})+ 3 \\delta\\, (\\bm{\\ell}\\cdot\n  \\bm{\\Sigma}_{\\rm c})}{mrc^2}\n\\nonumber \\\\* & \\qquad \\quad + \\frac{1}{2m^2 r^2c^4} \\Big((\\bmSeffp\n\\cdot\n\\bmSeffm) +  2 (\\bm{\\ell}\\cdot \\bmSeffp) (\\bm{\\ell}\\cdot\n\\bmSeffm)\\nonumber \\\\*\n& \\qquad \\quad ~-5 (\\bm{n}\\cdot\\bmSeffp)\n(\\bm{n}\\cdot \\bmSeffm)\\Big) \\Big] \\, .  \\label{eq:omegaofr}\n\\end{align}\n\\end{subequations}\n%\nInverting Eq.~(\\ref{eq:omegaofr}) to write $r$ as a function of $\\omega$ in\nEq. (\\ref{eq:hijSO}) and inserting there the expression~\\eqref{eq:rdot} of\n$\\dot{r}$, we obtain the following spin-orbit terms in the waveform:\n%\n\\begin{widetext}\n\\begin{eqnarray}\n\\label{eq:hijSOcirc}\nh_{ij\\  {\\rm{TT}}}^{\\mathrm {2PN SO}}&=& \\frac{G^2 \\nu m \\omega^2}{3R }{\\cal\n  P}_{ijab}^{\\mathrm{TT}}\\Bigg\\{\n n^a \\, n^b\\, \\left[\n4 (1-7\\nu)(\\bm{\\ell}\\cdot \\bm{\\Sigma}_{\\rm c})(\\bm{\\lambda}\\cdot \\bm{N})-\n(13-59\\nu)(\\bm{n}\\times \\bm{\\Sigma}_{\\rm c})\\cdot \\bm{N}-\n21\\delta\\,(\\bm{n}\\times \\bm{S}_{\\rm c})\\cdot \\bm{N}\\right]\\nonumber\\\\\n%%%\n && \\, + \\lambda^a \\, \\lambda^b \\, \\left[\n4(7-24\\nu)(\\bm{\\ell}\\cdot \\bm{\\Sigma}^{\\rm c})(\\bm{\\lambda}\\cdot \\bm{N})+\n4(1-6\\nu)(\\bm{n}\\times \\bm{\\Sigma}^{\\rm c})\\cdot \\bm{N}+\n\\delta  \\bigg(4 (\\bm{n}\\times \\bm{S}^{\\rm c})\\cdot \\bm{N}+\n52 ( \\bm{\\ell}\\cdot \\bm{S}^{\\rm c})(\\bm{\\lambda}\\cdot \\bm{N})\\bigg)\\right]\n\\nonumber\\\\\n%%%%\n%%%%\n&& \\, + \\lambda^{a} \\, n^{b} \\, \\bigg[\n4(13-55\\nu)(\\bm{\\lambda}\\times \\bm{\\Sigma}_{\\rm c}) \\cdot \\bm{N}+\n2(-63+239\\nu)(\\bm{n}\\cdot \\bm{N})(\\bm{\\ell}\\cdot \\bm{\\Sigma}_{\\rm c})\n\\nonumber\\\\\n&& \\left. \\; \\; \\; \\; \\;  +\n\\delta \\bigg(100  (\\bm{\\lambda}\\times \\bm{S}_{\\rm c})\\cdot \\bm{N}-\n262(\\bm{n}\\cdot \\bm{N})(\\bm{\\ell}\\cdot \\bm{S}_{\\rm c}) \\bigg)\\right] \\,\n+ \\Sigma_{\\rm c}^{a}\\,  \\ell^{b} \\, 12 (1-4\\nu) (\\bm{\\lambda}\\cdot \\bm{N})\n\\nonumber\\\\\n%%%%\n%%%\n&&+ \\lambda^{a} \\, {\\ell}^{b}\\bigg[\n12(-1+4\\nu)(\\bm{N} \\cdot \\bm{\\Sigma}_{\\rm c})+\n8(1-6\\nu) (\\bm{\\lambda}\\cdot \\bm{\\Sigma}_{\\rm c}) (\\bm{\\lambda}\\cdot \\bm{N})+\n4 (-16+67\\nu) (\\bm{n}\\cdot \\bm{\\Sigma}_{\\rm c}) (\\bm{n}\\cdot \\bm{N}) \\nonumber\\\\\n&& \\left. \\; \\; \\; \\; \\; +\\delta \\bigg(\n- 28(\\bm{N}\\cdot \\bm{S}_{\\rm c})+\n8   (\\bm{\\lambda}\\cdot \\bm{S}_{\\rm c}) (\\bm{\\lambda}\\cdot \\bm{N})-\n128(\\bm{n}\\cdot \\bm{S}_{\\rm c}) (\\bm{n}\\cdot \\bm{N})\\bigg)\n \\right]\\nonumber\\\\\n%%%%\n&&+ n^{a} \\, {\\ell}^{b}\\bigg[\n2(-13+59\\nu) (\\bm{\\lambda}\\cdot \\bm{\\Sigma}_{\\rm c})(\\bm{n}\\cdot \\bm{N})+\n4(-10+43\\nu) (\\bm{n}\\cdot \\bm{\\Sigma}_{\\rm c})(\\bm{\\lambda}\\cdot \\bm{N})\n\\nonumber\\\\\n&& \\left. \\; \\; \\; \\; \\; +\n\\delta \\bigg(\n-42 (\\bm{\\lambda}\\cdot \\bm{S}_{\\rm c})(\\bm{n}\\cdot \\bm{N})-\n72 (\\bm{n}\\cdot \\bm{S}_{\\rm c})(\\bm{\\lambda}\\cdot \\bm{N})\\bigg)\\right]\\, +\nS_{\\rm c}^{a}\\,  \\ell^{b} \\, 28\\delta\\, (\\bm{\\lambda}\\cdot \\bm{N})\n\\nonumber\\\\\n%%%%\n&&+ n^{a}(\\bm{n}\\times \\bm{N})^{b}\\left[\n-(1+\\nu) (\\bm{n}\\cdot \\bm{\\Sigma}_{\\rm c})-\n21(1-3\\nu) (\\bm{n}\\cdot \\bm{N}) (\\bm{N}\\cdot \\bm{\\Sigma}_{\\rm c}) +\n\\delta \\bigg(3(\\bm{n} \\cdot \\bm{S}_{\\rm c}) -\n21 (\\bm{n}\\cdot \\bm{N}) (\\bm{N}\\cdot \\bm{S}_{\\rm c}) \\bigg)\\right]\\nonumber\\\\\n%%%%%\n&&+ \\lambda^{a}(\\bm{n}\\times \\bm{N})^{b}\\left[\n2(7+23\\nu) (\\bm{\\lambda}\\cdot \\bm{\\Sigma}_{\\rm c})+\n40 (1-3\\nu)(\\bm{N}\\cdot \\bm{\\Sigma}_{\\rm c}) (\\bm{\\lambda} \\cdot \\bm{N}) +\n\\delta \\bigg(\n40 (\\bm{N}\\cdot \\bm{S}_{\\rm c}) (\\bm{\\lambda} \\cdot \\bm{N})  -\n2(\\bm{\\lambda}\\cdot \\bm{S}_{\\rm c})\\bigg)\\right]\\nonumber\\\\\n%%%%%\n&& + \\Sigma_{\\rm c}^{a} (\\bm{n}\\times \\bm{N})^{b}\\bigg[-(21+17\\nu)+\n20 (1-3\\nu) (\\bm{\\lambda}\\cdot \\bm{N})^2+\n21(-1+3\\nu)(\\bm{n}\\cdot \\bm{N})^2\\bigg]\\nonumber\\\\\n%%%%%%\n&&+ S_{\\rm c}^{a} (\\bm{n}\\times \\bm{N})^{b} \\delta \\bigg[\n-9+20 (\\bm{\\lambda}\\cdot \\bm{N})^2-21(\\bm{n}\\cdot \\bm{N})^2\\bigg]\\, +\nS_{\\rm c}^{a} \\, (\\bm{\\lambda}\\times \\bm{N})^{b} \\, 40\n\\, \\delta \\, (\\bm{\\lambda}\\cdot \\bm{N}) (\\bm{n} \\cdot \\bm{N})\n\\nonumber\\\\\n%%%%%%\n&&+ \\lambda^{a} \\, (\\bm{\\lambda}\\times \\bm{N})^{b} \\left[\n-80 \\nu (\\bm{n}\\cdot \\bm{\\Sigma}_{\\rm c})+\n20(1-3\\nu) (\\bm{n}\\cdot \\bm{N}) (\\bm{N}\\cdot \\bm{\\Sigma}_{\\rm c})+\n\\delta \\bigg(40 (\\bm{n}\\cdot \\bm{S}_{\\rm c})+\n20 (\\bm{N} \\cdot \\bm{S}_{\\rm c}) (\\bm{n}\\cdot \\bm{N})\\bigg)\\right]\\nonumber\\\\\n%%%%\n&&+\\Sigma_{\\rm c}^{a} \\, (\\bm{\\lambda}\\times \\bm{N})^{b}\n\\, 40(1-3\\nu) (\\bm{\\lambda}\\cdot \\bm{N}) (\\bm{n} \\cdot \\bm{N}) \\Bigg\\} \\,.\n\\end{eqnarray}\n\\end{widetext}\n%%%%%%%\nHere, we have used that\n%\n\\begin{equation}\n (\\bm{n}\\times\\bm{S}_{\\rm c})^i=-\\lambda^i(\\bm{\\ell}\\cdot \\bm{S}_{\\rm c})+\n\\ell^i(\\bm{\\lambda}\\cdot \\bm{S}_{\\rm c}),\n\\end{equation}\n%\nand similarly for $\\bm{\\Sigma}_{\\rm c}$.\n\nFinally, we derive the 2PN spin-spin terms for circular orbits. They read\n%\n\\begin{align}\n& h_{ij \\ \\mathrm{ TT}}^{\\mathrm {2 PN SS}}= \\frac{2G  \\nu \\omega^2}{m R} {\\cal\n  P}_{ijab}^{\\mathrm{TT}} \\bigg\\{\nn^a\\, n^b\n \\Big[-\\frac{8}{3} ( \\bmSeffp\\cdot \\bmSeffm)\n\\nonumber \\\\ & \\qquad  \\qquad \\quad +\n\\frac{2}{3}\n(\\bm{\\ell}\\cdot \\bmSeffp) (\\bm{\\ell}\\cdot\n\\bmSeffm) +\n\\frac{40}{3} (\\bm{n}\\cdot \\bmSeffp) (\\bm{n}\\cdot\n\\bmSeffm) \\Big]\\nonumber \\\\ & \\qquad +\n \\lambda^a \\, \\lambda^b\n\\Big[ \\frac{2}{3} ( \\bmSeffp\\cdot \\bmSeffm) + \\frac{4}{3}\n(\\bm{\\ell}\\cdot \\bmSeffp) (\\bm{\\ell}\\cdot \\bmSeffm)\n\\nonumber \\\\ & \\qquad \\qquad \\quad -\n\\frac{10}{3} (\\bm{n}\\cdot \\bmSeffp) (\\bm{n}\\cdot \\bmSeffm) \\Big]\n\\nonumber \\\\ & \\qquad -2\nn^a \\, \\lambda^b \\Big[ (\\bm{n}\\cdot \\bmSeffp) (\\bm{\\lambda}\\cdot\n\\bmSeffm)+\n(\\bm{n}\\cdot \\bmSeffm) (\\bm{\\lambda}\\cdot \\bmSeffp)\\Big]\n\\nonumber \\\\ & \\qquad -3\n(\\bm{n}\\cdot \\bmSeffp)\\,  n^{(a} \\, \\Seffm^{b)}\n- 3 (\\bm{n}\\cdot \\bmSeffm) \\, n^{(a} \\, \\Seffp^{b)}\n\\bigg\\} \\, .\n\\end{align}\n%\n%with $v = (G m\\,\\omega/c^3)^{1/3}$.\n\n\\subsection{Polarizations for nonprecessing, spinning compact bodies}\n\\label{sec:pol}\n\nThe two polarization states $h_+$ and $h_\\times$ are obtained by choosing a\ncoordinate system and taking linear combinations of the components of\n$h_{ij}^\\mathrm{TT}$. Using an orthonormal triad consisting of $\\bm{N}$ and two\npolarization vectors $\\bm{P}$ and $\\bm{Q}$, the polarizations are\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{subequations}\n \\label{eq:polarizations}\n\\begin{eqnarray}\nh_+&=& \\frac{1}{2}\\left(P^iP^j-Q^iQ^j\\right)h_{ij}^\\mathrm{TT}\\,,\\\\\nh_\\times&=&\\frac{1}{2}\\left(P^iQ^j+Q^iP^j\\right)h_{ij}^\\mathrm{TT}\\, .\n\\end{eqnarray}\n\\end{subequations}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nAlthough different choices of $\\bm{P}$ and $\\bm{Q}$ give different\npolarizations, the particular linear combination of $h_+$ and\n$h_\\times$ corresponding to the physical strain measured in a\ndetector is independent of the convention used. For nonspinning\nbinaries, one usually chooses a coordinate system such that the\norbital plane lies in the $x\\mbox{-}y$ plane, and the direction of\ngravitational-wave propagation $\\bm{N}$ is in the $x\\mbox{-}z$\nplane.\n\nWhen the spins of the bodies are aligned or anti-aligned with the\norbital angular momentum, the system's evolution is qualitatively\nsimilar to the case of nonspinning bodies. This case is characterized\nby the absence of precession of the spins and orbital angular momentum\nand thus the orbital plane remains fixed in space. However, the effect\nof the spins gives a contribution to the phase and a correction to the\namplitude of the waveform, which we explicitly provide in this\nsubsection.  We use the conventions that the $z$ axis coincides with\n$\\bm{\\ell}$ and the vectors $ \\bm{\\ell}$, $\\bm{N}$, $\\bm{n}$, and $\\bm{\\lambda}$ have\nthe following $(x,y,z)$ components:\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{subequations}\n\\begin{eqnarray}\n\\bm{\\ell}&=& (0,0,1), \\; \\; \\; \\; \\;  \\; \\; \\; \\; \\;  \\; \\; \\; \\; \\; \\; \\; \\; \\; \\bm{N}=\n(\\sin\\theta, 0 ,\\cos\\theta), \\; \\; \\; \\; \\; \\; \\; \\ \\; \\; \\; \\; \\; \\\\\n%%%%\n \\bm{n}&=& (\\sin\\Phi, -\\cos\\Phi, 0), \\ \\ \\ \\  \\bm{\\lambda}=\n(\\cos \\Phi, \\sin \\Phi, 0),  \\ \\ \\ \\; \\; \\; \\; \\; \\; \\; \\; \n\\end{eqnarray}\n\\end{subequations}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nwhere $\\Phi$ is the orbital phase defined such that at the initial time,\n$\\bm{n}$ points in the $x$ direction. We use the following polarization\nvectors:\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{equation}\n\\bm{P}=\\bm{N}\\times \\bm{\\ell}, \\ \\ \\ \\bm{Q}=\\bm{N}\\times \\bm{P}.\n\\end{equation}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nThe vector $\\bm{P}$ is the ascending node where the orbital\nseparation vector crosses the plane of the sky from below. With\nthese conventions, Eqs. (\\ref{eq:polarizations}) with Eqs.\n(\\ref{eq:hijSOcirc}), specialized to the case where the only\nnonvanishing spin components are $(\\bm{\\Sigma^{\\rm c}}\\cdot\n\\bm{\\ell})$ and $(\\bm{S}^{\\mathrm{c}}\\cdot\\bm{\\ell})$, become\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{widetext}\n\\begin{eqnarray}\n\\label{eq:hplus}\nh_+^{\\mathrm{2PN \\ spin} }\n&=&-\\frac{G^2\\nu m \\omega^2}{12 R }\\cos\\Phi \\ \\sin\\theta\\left\\{\n3 \\delta\\, (\\bm{\\ell}\\cdot \\bm{S}_{\\rm c})(-33+\\cos ^2\\theta)+\n\\left[(-93+167\\nu)+\n9(1-3\\nu)\\cos^2\\theta\\right]( \\bm{\\ell}\\cdot \\bm{\\Sigma_{\\rm c}})\\right\\}\n\\nonumber\\\\\n%%%%\n&&-\\frac{9G^2\\nu m\\omega^2}{4 R  }\\cos (3\\Phi) \\ \\sin\\theta \\left\\{\n\\delta\\,(5-\\cos^2\\theta)( \\bm{\\ell}\\cdot \\bm{S}_{\\rm c}) +\n3(1-3\\nu)\\sin^2\\theta (\\bm{\\ell}\\cdot \\bm{\\Sigma_{\\rm c}})\\right\\}\\nonumber \\\\\n%%%%\n&&-\\frac{2G \\nu \\omega^2}{m R }\\cos (2\\Phi)\\left(1+\\cos^2 \\theta\\right)\n( \\bm{\\ell}\\cdot \\bmSeffp )(\\bm{\\ell}\\cdot \\bmSeffm )\\,\n,\\ \\\\\n%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nh_\\times^{\\mathrm{2PN \\ spin} }&=&\n-\\frac{G^2\\nu m  \\omega^2}{48 R  }\\sin\\Phi \\sin(2\\theta)\\left\\{\n6\\delta\\, ( \\bm{\\ell}\\cdot \\bm{S}_{\\rm c})\n\\left(-33+\\cos^2\\theta\\right)+ \\left[(-171+289 \\nu)+\n3(1-3\\nu)\\cos(2\\theta)\\right]( \\bm{\\ell}\\cdot \\bm{\\Sigma}_{\\rm c})\\right\\}\n\\nonumber\\\\\n%%%%\n&&-\\frac{9G^2\\nu m \\omega^2}{8 R }\\sin(3\\Phi)\\sin(2\\theta)\\left\\{\n\\delta\\, ( \\bm{\\ell}\\cdot \\bm{S}_{\\rm c})\\left(7-3\\cos^2\\theta\\right)+\n3(1-3\\nu)\\sin^2\\theta ( \\bm{\\ell} \\cdot \\bm{\\Sigma_{\\rm c}})\\right\\}\\nonumber\\\\\n%%%%\n&&-\\frac{4G\\nu \\omega^2}{m R}\\sin(2\\Phi)\\cos\\theta\n( \\bm{\\ell}\\cdot \\bmSeffp )( \\bm{\\ell}\\cdot \\bmSeffm\n)\\,. \\label{eq:hcross}\n\\end{eqnarray}\n\\end{widetext}\nHere, the convention for the 2PN spin pieces of the polarizations is analogous to that adopted for the PN expansion of the waveform  (\\ref{eq:hexpansion}), with the expansion coefficients related by Eqs. (\\ref{eq:polarizations}) at each PN order.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\subsection{Gravitational modes for nonprecessing, spinning compact bodies}\n\\label{sec:modes}\nThe gravitational wave modes are obtained by expanding the complex polarization\n\\begin{equation}\nh =  h_+\n- i h_\\times\\,,\n\\label{hcomplex}\n\\end{equation}\ninto  spin-weighted $s=-2$ spherical harmonics as\n%\n\\begin{equation}\\label{eq:modeexp}\nh(\\theta,\\phi) = \\sum_{\\ell = 2}^{+\\infty} \\sum_{m=-\\ell}^{\\ell} h_{\\ell m}\\,\n{}_{-2}Y^{\\ell m}(\\theta,\\phi) \\, ,\n\\end{equation}\n%\nwhere\n%\n\\begin{equation}\n{}_{-s} Y^{\\ell m}(\\theta,\\phi) = (-1)^s \\sqrt{\\frac{2\\ell + 1}{4\\pi}}\n\\, d_{sm}^\\ell(\\theta)\\, e^{i m \\phi}\\,,\n\\end{equation}\n%\nwith\n%\n\\begin{eqnarray}\n&&d_{sm}^\\ell(\\theta) = \\sum_{k=\\max(0,m-s)}^{\\min(\\ell+m,\\ell-s)}\n\\frac{(-1)^k}{k!} \\nonumber\\\\\n&&\\times\n\\frac{\\sqrt{(\\ell + m)! (\\ell - m)!(\\ell + s)!(\\ell - s)!}}{(k - m + s)!\n    (\\ell + m - k)!  (\\ell - k - s)!} \\ \\ \\ \\ \\ \\ \\ \\ \\ \\nonumber\\\\\n&&\\times \\left(\\cos (\\theta/2)\\right)^{2\\ell+m-2k-s}\n\\left( \\sin (\\theta/2) \\right)^{2k-m+s} \\,.\n\\end{eqnarray}\n%\nThe modes $h_{\\ell m}$ can be extracted by computing\n\\begin{equation}\n\\label{eq:hlm}\nh_{\\ell m} = \\int d\\Omega  \\, h(\\theta, \\phi)\n\\, {}_{-2}{Y}^{\\ell  m*}(\\theta,\\phi) \\,,\n\\end{equation}\n%\nwhere the integration is over the solid angle $\\int d\\Omega=\\int^{\\pi}_0\n\\sin\\theta d\\theta \\int^{2\\pi}_0d\\phi $\nand using the orthogonality property\n%\n$ \\int d\\Omega   \\ {}_{-s}Y^{\\ell m}(\\theta,\\phi)\n\\, {}_{-s}Y^{\\ell' m' *}(\\theta,\\phi) = \\delta^{\\ell \\ell'} \\delta^{m m'}$,\n%\nwhere $ \\delta^{\\ell \\ell'}$ is the Kronecker symbol and the star denotes\ncomplex conjugation.\n%\nUsing Eqs. (\\ref{eq:hplus}) and (\\ref{eq:hcross}) in Eq.\n(\\ref{eq:hlm}) we find the following nonvanishing modes:\n%\n\\begin{equation}\n( h_{\\ell m})^\\mathrm{2PN\\,spin }=-\\frac{2 G^2 m \\nu \\,\n  \\omega^2}{R}\\sqrt{\\frac{16\\pi}{5}}e^{-im\\Phi}\n\\ \\hat h_{\\ell m},\n\\end{equation}\n%\n\\begin{subequations}\n\\label{eq:hlmnonprec}\n\\begin{eqnarray}\n\\hat h_{21}&=&\n -\\frac{43}{21} \\delta\\, (\\bm{\\ell}\\cdot \\bm{S}_{\\rm c})+\n\\frac{1}{42}(-79+139\\nu)(\\bm{\\ell}\\cdot \\bm{\\Sigma}_{\\rm c})\\,, \\nonumber \\\\\\\\\n\\hat h_{22}&=& \\frac{(\\bm{\\ell}\\cdot\n\\bmSeffp)(\\bm{\\ell}\\cdot \\bmSeffm )}{G m^2}\n\\,, \\label{eq:h22} \\\\\n\\hat h_{31}&=& \\frac{1}{24\\sqrt{14}} \\delta\\,\n(\\bm{\\ell}\\cdot \\bm{S}_{\\rm c})+\n\\frac{5}{24\\sqrt{14}}(1-3\\nu)(\\bm{\\ell}\\cdot \\bm{\\Sigma}_{\\rm c})\n\\,,\\nonumber \\\\ \\\\\n\\hat h_{33}&=&-\\frac{3\\sqrt{105}}{8\\sqrt{2}}\n\\delta\\, (\\bm{\\ell}\\cdot \\bm{S}_{\\rm c})-\n\\frac{9}{8}\\sqrt{\\frac{15}{14}}(1-3\\nu)(\\bm{\\ell}\\cdot \\bm{\\Sigma_{\\rm c}})\\,,\n\\nonumber \\\\ \\\\\n\\hat h_{41}&=&\\frac{\\sqrt{5} }{168\\sqrt{2}}\\delta\\,\n(\\bm{\\ell}\\cdot \\bm{S}_{\\rm c})+\n\\frac{\\sqrt{5} }{168\\sqrt{2}}(1-3\\nu)(\\bm{\\ell}\\cdot \\bm{\\Sigma}_{\\rm c})\\,,\n\\nonumber \\\\\\\\\n\\hat h_{43}&=&\\frac{9\\sqrt{5}}{8\\sqrt{14}}\\delta\\,\n(\\bm{\\ell}\\cdot \\bm{S}_{\\rm c})+\n\\frac{9\\sqrt{5}}{8\\sqrt{14}}(1-3\\nu)(\\bm{\\ell}\\cdot \\bm{\\Sigma}_{\\rm c})\n\\,.\\ \\nonumber \\\\\n\\end{eqnarray}\n\\end{subequations}\n%\nWe have explicitly checked that in the test-mass limit $\\nu\\to 0$, Eqs.\n(\\ref{eq:hlmnonprec}) reduce to the 2PN ${\\cal O}(q)$ and ${\\cal O}(q^2)$\nterms given in Eqs. (22) of Ref.~\\cite{Pan2010hz} (see also \\cite{Tagoshi:1996gh}), after\naccounting for the factor of $(-i)^m$ attributable to the different conventions for the\nphase origin, as explained in Ref.~\\cite{Arun:2009}.\n\nIt is interesting to note from Eq. (\\ref{eq:h22}) that in the\nnonprecessing case, the dominant $h_{22}$ mode contains only terms\nthat are quadratic in the spin at 2PN order. By contrast, for\nprecessing binaries, the 2PN spin-orbit terms will give a\nnonvanishing contribution to the $22$-mode.\n\n\\section{CONCLUSIONS}\n\\label{sec:conclusions}\n\nWe have extended the knowledge of the spin terms in the gravitational-wave\nstrain tensor to 2PN accuracy for precessing binaries. Our result includes the\nspin-orbit as well as the spin${}_1$-spin${}_2$ and spin${}^2_1$,\nspin${}_{2}^2$ effects. The quadratic-in-spin terms are entirely due to the\nequations of motion, whereas the 2PN spin-orbit terms come from both the\ncorrections to the orbital dynamics and the radiation field.\n\nFor a given choice of an orthonormal polarization triad and a source frame,\nthe gravitational-wave polarizations can be obtained by projecting our result\nfor the gravitational-wave strain tensor given in Secs.~\\ref{sec:SO}\nand~\\ref{sec:SS} orthogonal to the propagation direction. For precessing\nbinaries, there is no preferred unique choice of the source\nframe~\\cite{Finn1993, Kidder:1995zr,Buonanno:2002fy,Schmidt:2010it,\n  OShaughnessy2011, Ochsner2012, 2011PhRvD..84l4011B,Schmidt:2012rh}, but in\nthe case that the spins are collinear with the orbital angular\nmomentum, the procedure to obtain the polarizations can be carried\nout in a similar fashion as for nonspinning binaries. For the\nnonprecessing case and circular orbits, we provided ready-to-use\nexpressions for the gravitational polarizations in\nSec.~\\ref{sec:pol}, which could be directly employed in time-domain\npost-Newtonian, phenomenological and effective-one-body--based\ntemplate models~\\cite{Kidder:1995zr,\nArun:2009,Ajith:2008,Damour2009a,Pan:2009wj,\n  Santamaria:2010yb,Pan:2011gk}.\n\nIn view of the current interest in interfacing analytical and\nnumerical relativity, we also provided the decomposition of the\nwaveform into spin-weighted spherical harmonic modes for\nnonprecessing binaries and quasicircular orbits. We verified that\nthe test-particle limit of our result reduces to the expressions\nobtained from black-hole perturbation\ntheory~~\\cite{Tagoshi:1996gh,Pan2010hz}. We noted that for spins\ncollinear with the orbital angular momentum, the dominant $h_{22}$\nmode of the waveform contains only quadratic-in-spin effects since\nthe spin-orbit contributions vanish in this case, although they are\nnonzero for generic, precessing configurations.\n\n\\begin{acknowledgments} A.B. acknowledges partial support from NSF Grants\nNo. PHY-0903631 and No. PHY-1208881, and NASA Grant NNX09AI81G. A.B.\nalso thanks the Kavli Institute for Theoretical Physics (supported\nby the NSF Grant No. PHY11-25915) for hospitality during the\npreparation of this manuscript. T.H. acknowledges support from  NSF\nGrants No. PHY-0903631 and No. PHY-1208881,  and the Maryland Center\nfor Fundamental Physics. We thank Gilles Esposito-Far\\`ese, Larry\nKidder and Etienne Racine for useful interactions, as well as David\nDelavaquerie for help in finalizing one of our \\textsc{mathematica}\ncodes.\n\\end{acknowledgments}\n\n\\appendix*\n\n\n\\section{USEFUL IDENTITIES}\n\nAccording to the way the waveform is computed, the result may take various\nforms, which are not immediately seen to be equivalent. Their difference\nvanishes because of some dimensional identities valid in three dimensions. They all\namount to expressing the fact that a tensor with four antisymmetrized indices\nmust vanish. We shall present here two of such identities, which turned out to\nbe particularly useful for our checks, together with Eqs.~(5.2) of\nRef.~\\cite{Faye-Blanchet-Buonanno:2006}.\n\nLet $\\bm{U}_A=U_A^i$, for $A\\in \\{1,2,3\\}$, be three vectors of $\\mathbb{R}^3$.\nThe first identity tells us that for any vector $\\bm{U}$, we must have\n%\n\\begin{align}\n& (\\bm{U}_1 \\times \\bm{U}_2)^{(i} [U_3^{j)} (\\bm{U}_4 \\cdot \\bm{U}) - U_4^{j)}\n(\\bm{U}_3 \\cdot \\bm{U})]\n \\\\ & ~ =\nU_4^{(i} [(\\bm{U}\\times \\bm{U}_1)^{j)} (\\bm{U}_2 \\cdot \\bm{U}_3) -  (\\bm{U}\\times\n\\bm{U}_2)^{j)} (\\bm{U}_1 \\cdot \\bm{U}_3)] \\nonumber \\\\ & \\quad + U_3^{(i}\n[(\\bm{U}\\times \\bm{U}_2)^{j)} (\\bm{U}_1 \\cdot \\bm{U}_4) - (\\bm{U}\\times\n\\bm{U}_1)^{j)} (\\bm{U}_2 \\cdot \\bm{U}_4)] \\, .\n\\nonumber \\end{align}\n%\nTo show this, we compute $\\varepsilon^i_{~ab} \\varepsilon^{mjk}\n\\varepsilon_{mpq} U_1^a U_2^b U_3^p U_4^q$ in two different manners:\n(i) we group the first two epsilons, which are next expanded in\nterms of the identity tensor $\\delta^i_{~j}$ using the standard\nformula $\\varepsilon_{iab} \\varepsilon^{mjk} =3! \\delta_{~[i}^m\n\\delta_{~a}^j \\delta_{~b]}^k$; (ii) we group the last two epsilons\nand apply the contracted version of the previous equation:\n$\\varepsilon^{mjk} \\varepsilon_{mpq} = 2 \\delta^j_{~[p}\n\\delta^k_{~q]}$. One of the remaining free indices, say $k$, is\nfinally contracted with $U_k$.\n\nThe second identity reads:\n\\begin{widetext}\n%\n\\begin{align} \\label{eq:identity2}\n  & \\delta^{ij} [U_1^2 U_2^2 U_3^2 -\n  U_1^2 (\\bm{U}_2 \\cdot \\bm{U}_3)^2 -\n  U_2^2 (\\bm{U}_3  \\cdot \\bm{U}_1)^2 -\n  U_3^2 (\\bm{U}_1 \\cdot \\bm{U}_2)^2 + 2 (\\bm{U}_1 \\cdot \\bm{U}_2) (\\bm{U}_2\n  \\cdot \\bm{U}_3) (\\bm{U}_3 \\cdot \\bm{U}_1)]\n  \\nonumber \\\\ & \\qquad +\n  2 U_1^{(i} U_3^{j)} [ U_2^2 (\\bm{U}_3 \\cdot \\bm{U}_1) - (\\bm{U}_1 \\cdot\n  \\bm{U}_2) (\\bm{U}_2 \\cdot \\bm{U}_3)] + 2 U_1^{(i}\n  U_2^{j)} [ U_3^2 (\\bm{U}_1 \\cdot \\bm{U}_2) - (\\bm{U}_2 \\cdot \\bm{U}_3)\n  (\\bm{U}_3 \\cdot \\bm{U}_1)]\n  \\nonumber \\\\ & \\qquad + 2 U_2^{(i} U_3^{j)} [ U_1^2 (\\bm{U}_2 \\cdot\n  \\bm{U}_3) - (\\bm{U}_1 \\cdot \\bm{U}_2) (\\bm{U}_1 \\cdot \\bm{U}_3)] +\n  U_1^i U_1^j [ (\\bm{U}_2 \\cdot \\bm{U}_3)^2 - U_2^2 U_3^2]\n  + U_2^i U_2^j [ (\\bm{U}_1 \\cdot \\bm{U}_3)^2 - U_1^2 U_3^2]\n  \\nonumber \\\\ & \\qquad +\n  U_3^i U_3^j [ (\\bm{U}_1 \\cdot \\bm{U}_2)^2 - U_1^2 U_2^2] =0 \\, .\n\\end{align}\n%\n\\end{widetext}\nIt is proved by contracting the equality $U_1^{[a} U_2^b U_3^c\n\\delta^{i]j}=0$ with $U_{1a} U_{2b} U_{3c}$ and expanding. As the\ntrace of the left-hand side of Eq.~\\eqref{eq:identity2} is\nidentically zero, the nontrivial content of this identity consists\nof its STF part.\n\n\\begin{thebibliography}{94}\n\\expandafter\\ifx\\csname natexlab\\endcsname\\relax\\def\\natexlab#1{#1}\\fi\n\\expandafter\\ifx\\csname bibnamefont\\endcsname\\relax\n  \\def\\bibnamefont#1{#1}\\fi\n\\expandafter\\ifx\\csname bibfnamefont\\endcsname\\relax\n  \\def\\bibfnamefont#1{#1}\\fi\n\\expandafter\\ifx\\csname citenamefont\\endcsname\\relax\n  \\def\\citenamefont#1{#1}\\fi\n\\expandafter\\ifx\\csname url\\endcsname\\relax\n  \\def\\url#1{\\texttt{#1}}\\fi\n\\expandafter\\ifx\\csname urlprefix\\endcsname\\relax\\def\\urlprefix{URL }\\fi\n\\providecommand{\\bibinfo}[2]{#2}\n\\providecommand{\\eprint}[2][]{\\url{#2}}\n\n\\bibitem[{\\citenamefont{Abbott et~al.}(2009)}]{Abbott:2007}\n\\bibinfo{author}{\\bibfnamefont{B.}~\\bibnamefont{Abbott}} \\bibnamefont{\\textit{et~al}.}\n  (\\bibinfo{collaboration}{LIGO Scientific Collaboration}),\n  \\bibinfo{journal}{Rep. Prog. Phys.} \\textbf{\\bibinfo{volume}{72}},\n  \\bibinfo{pages}{076901} (\\bibinfo{year}{2009}).%, \\eprint{0711.3041}.\n\n\\bibitem[{\\citenamefont{Acernese \\textit{et~al}.}(2008)\\citenamefont{Acernese \\textit{et~al}.}}]{Acernese:2008}\n\\bibinfo{author}{\\bibfnamefont{F.}~\\bibnamefont{Acernese}}\n  %\\bibinfo{author}{\\bibfnamefont{M.}~\\bibnamefont{Alshourbagy}},\n  %\\bibinfo{author}{\\bibfnamefont{P.}~\\bibnamefont{Amico}},\n  %\\bibinfo{author}{\\bibfnamefont{F.}~\\bibnamefont{Antonucci}},\n  %\\bibinfo{author}{\\bibfnamefont{S.}~\\bibnamefont{Aoudia}},\n  \\bibnamefont{\\textit{et~al}.}, \\bibinfo{journal}{Classical Quantum Gravity}\n  \\textbf{\\bibinfo{volume}{25}}, \\bibinfo{pages}{184001}\n  (\\bibinfo{year}{2008}).\n\n\\bibitem[{\\citenamefont{Grote}(2008)}]{Grote:2008zz}\n\\bibinfo{author}{\\bibfnamefont{H.}~\\bibnamefont{Grote}}\n  (\\bibinfo{collaboration}{LIGO Scientific Collaboration}),\n  \\bibinfo{journal}{Classical Quantum Gravity} \\textbf{\\bibinfo{volume}{25}},\n  \\bibinfo{pages}{114043} (\\bibinfo{year}{2008}).\n\n\\bibitem[{\\citenamefont{Kuroda and the\n  {LCGT}~Collaboration}(2010)}]{Kuroda:2010}\n\\bibinfo{author}{\\bibfnamefont{K.}~\\bibnamefont{Kuroda}} \\bibnamefont{and}\n  \\bibinfo{author}{\\bibnamefont{the {LCGT}~Collaboration}},\n  \\bibinfo{journal}{Classical Quantum Gravity} \\textbf{\\bibinfo{volume}{27}},\n  \\bibinfo{pages}{084004} (\\bibinfo{year}{2010}).\n\n\\bibitem[{\\citenamefont{{{Prince}, T.~A., {Binetruy}, P., {Centrella}, J.,\n  {Finn}, L.~S., {Hogan}, C. and {Nelemans}, G., {Phinney}, E.~S., {Schutz}, B.\n  and LISA International ~Science ~Team}}(2007)}]{lisa}\n\\bibinfo{author}{\\bibnamefont{{{T.~A. Prince}, {P. Binetruy}, J. {Centrella},\n  L.~S. {Finn}, C. {Hogan}, G. {Nelemans}, E.~S. {Phinney}, and B. {Schutz} ~ ~ (LISA International ~Science ~Team)}}}, \\bibinfo{type}{Technical\n  Report}, \\bibinfo{institution}{{LISA science case document}},\n \\bibinfo{year}{2007}, \\bibinfo{note}{\n  \\url{http://list.caltech.edu/mission_documents}}.\n\n\\bibitem[{ESA()}]{ESALISAwebsite}\n\\bibinfo{howpublished}{\\url{http://sci.esa.int/lisa}}.\n\n\\bibitem[{\\citenamefont{Finn}(1992)}]{Finn1992}\n\\bibinfo{author}{\\bibfnamefont{L.~S.} \\bibnamefont{Finn}},\n  \\bibinfo{journal}{Phys.\\ Rev.\\ D} \\textbf{\\bibinfo{volume}{46}},\n  \\bibinfo{pages}{5236} (\\bibinfo{year}{1992}).\n\n\\bibitem[{\\citenamefont{Finn and Chernoff}(1993)}]{Finn1993}\n\\bibinfo{author}{\\bibfnamefont{L.~S.} \\bibnamefont{Finn}} \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{D.~F.} \\bibnamefont{Chernoff}},\n  \\bibinfo{journal}{Phys.\\ Rev.\\ D} \\textbf{\\bibinfo{volume}{47}},\n  \\bibinfo{pages}{2198} (\\bibinfo{year}{1993}).\n\n\\bibitem[{\\citenamefont{Sasaki and Tagoshi}(2003)}]{Sasaki:2003xr}\n\\bibinfo{author}{\\bibfnamefont{M.}~\\bibnamefont{Sasaki}} \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{H.}~\\bibnamefont{Tagoshi}},\n  \\bibinfo{journal}{Living Rev. Rel.} \\textbf{\\bibinfo{volume}{6}},\n  \\bibinfo{pages}{6} (\\bibinfo{year}{2003}), \n\\bibinfo{howpublished}{\\url{http://www.livingreviews.org/lrr-2003-6}}\n\n\\bibitem[{\\citenamefont{Blanchet}(2006)}]{Blanchet2006}\n\\bibinfo{author}{\\bibfnamefont{L.}~\\bibnamefont{Blanchet}},\n  \\bibinfo{journal}{Living Rev. Rel.} \\textbf{\\bibinfo{volume}{9}},\n  \\bibinfo{pages}{4} (\\bibinfo{year}{2006}),\n\\bibinfo{howpublished}{\\url{http://www.livingreviews.org/lrr-2006-4}}\n\n\\bibitem[{\\citenamefont{Futamase and Itoh}(2007)}]{Futamase:2007zz}\n\\bibinfo{author}{\\bibfnamefont{T.}~\\bibnamefont{Futamase}} \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{Y.}~\\bibnamefont{Itoh}},\n  \\bibinfo{journal}{Living Rev. Rel.} \\textbf{\\bibinfo{volume}{10}},\n  \\bibinfo{pages}{2} (\\bibinfo{year}{2007}), \n\\bibinfo{howpublished}{\\url{http://www.livingreviews.org/lrr-2007-2}}\n\n\\bibitem[{\\citenamefont{Pretorius}(2005)}]{Pretorius2005a}\n\\bibinfo{author}{\\bibfnamefont{F.}~\\bibnamefont{Pretorius}},\n  \\bibinfo{journal}{Phys.\\ Rev.\\ Lett.} \\textbf{\\bibinfo{volume}{95}},\n  \\bibinfo{pages}{121101} (\\bibinfo{year}{2005})%, \\eprint{gr-qc/0507014}.\n\n\\bibitem[{\\citenamefont{Campanelli et~al.}(2006)\\citenamefont{Campanelli,\n  Lousto, Marronetti, and Zlochower}}]{Campanelli2006a}\n\\bibinfo{author}{\\bibfnamefont{M.}~\\bibnamefont{Campanelli}},\n  \\bibinfo{author}{\\bibfnamefont{C.~O.}~\\bibnamefont{Lousto}},\n  \\bibinfo{author}{\\bibfnamefont{P.}~\\bibnamefont{Marronetti}},\n  \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{Y.}~\\bibnamefont{Zlochower}},\n  \\bibinfo{journal}{Phys.\\ Rev.\\ Lett.} \\textbf{\\bibinfo{volume}{96}},\n  \\bibinfo{pages}{111101} (\\bibinfo{year}{2006})%, \\eprint{gr-qc/0511048}.\n\n\\bibitem[{\\citenamefont{Baker et~al.}(2006)\\citenamefont{Baker, Centrella,\n  Choi, Koppitz, and van Meter}}]{Baker2006a}\n\\bibinfo{author}{\\bibfnamefont{J.~G.} \\bibnamefont{Baker}},\n  \\bibinfo{author}{\\bibfnamefont{J.}~\\bibnamefont{Centrella}},\n  \\bibinfo{author}{\\bibfnamefont{D.-I.} \\bibnamefont{Choi}},\n  \\bibinfo{author}{\\bibfnamefont{M.}~\\bibnamefont{Koppitz}}, \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{J.}~\\bibnamefont{van Meter}},\n  \\bibinfo{journal}{Phys.\\ Rev. \\ Lett.} \\textbf{\\bibinfo{volume}{96}},\n  \\bibinfo{pages}{111102} (\\bibinfo{year}{2006})%, \\eprint{gr-qc/0511103}.\n\n\\bibitem[{\\citenamefont{Buonanno and Damour}(1999)}]{Buonanno99}\n\\bibinfo{author}{\\bibfnamefont{A.}~\\bibnamefont{Buonanno}} \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{T.}~\\bibnamefont{Damour}},\n  \\bibinfo{journal}{Phys.\\ Rev.\\ D} \\textbf{\\bibinfo{volume}{59}},\n  \\bibinfo{pages}{084006} (\\bibinfo{year}{1999})%, \\eprint{gr-qc/9811091}.\n\n\\bibitem[{\\citenamefont{Buonanno and Damour}(2000)}]{Buonanno00}\n\\bibinfo{author}{\\bibfnamefont{A.}~\\bibnamefont{Buonanno}} \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{T.}~\\bibnamefont{Damour}},\n  \\bibinfo{journal}{Phys.\\ Rev.\\ D} \\textbf{\\bibinfo{volume}{62}},\n  \\bibinfo{pages}{064015} (\\bibinfo{year}{2000}). %, \\eprint{gr-qc/0001013}.\n\n\\bibitem[{\\citenamefont{Damour et~al.}(2000)\\citenamefont{Damour, Jaranowski,\n  and Schaefer}}]{DJS00}\n\\bibinfo{author}{\\bibfnamefont{T.}~\\bibnamefont{Damour}},\n  \\bibinfo{author}{\\bibfnamefont{P.}~\\bibnamefont{Jaranowski}},\n  \\bibnamefont{and} \\bibinfo{author}{\\bibfnamefont{G.}~\\bibnamefont{Schafer}},\n  \\bibinfo{journal}{Phys.\\ Rev.\\ D} \\textbf{\\bibinfo{volume}{62}},\n  \\bibinfo{pages}{084011} (\\bibinfo{year}{2000}). %, \\eprint{gr-qc/0005034}.\n\n\\bibitem[{\\citenamefont{Buonanno et~al.}(2007)\\citenamefont{Buonanno, Cook, and\n  Pretorius}}]{Buonanno-Cook-Pretorius:2007}\n\\bibinfo{author}{\\bibfnamefont{A.}~\\bibnamefont{Buonanno}},\n  \\bibinfo{author}{\\bibfnamefont{G.~B.} \\bibnamefont{Cook}}, \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{F.}~\\bibnamefont{Pretorius}},\n  \\bibinfo{journal}{Phys.\\ Rev.\\ D} \\textbf{\\bibinfo{volume}{75}},\n  \\bibinfo{pages}{124018} (\\bibinfo{year}{2007}). %, \\eprint{gr-qc/0610122}.\n\n\\bibitem[{\\citenamefont{Ajith et~al.}(2008)\\citenamefont{Ajith, Babak, Chen,\n  Hewitson, Krishnan et~al.}}]{Ajith:2008}\n\\bibinfo{author}{\\bibfnamefont{P.}~\\bibnamefont{Ajith}}\n%,\n%  \\bibinfo{author}{\\bibfnamefont{S.}~\\bibnamefont{Babak}},\n%  \\bibinfo{author}{\\bibfnamefont{Y.}~\\bibnamefont{Chen}},\n%  \\bibinfo{author}{\\bibfnamefont{M.}~\\bibnamefont{Hewitson}},\n%  \\bibinfo{author}{\\bibfnamefont{B.}~\\bibnamefont{Krishnan}},\n  \\bibnamefont{\\textit{et~al}.}, \\bibinfo{journal}{Phys.\\ Rev.\\ D}\n  \\textbf{\\bibinfo{volume}{77}}, \\bibinfo{pages}{104017}\n  (\\bibinfo{year}{2008}).%, \\eprint{0710.2335}.\n\n\\bibitem[{\\citenamefont{Damour and Nagar}(2009)}]{Damour2009a}\n\\bibinfo{author}{\\bibfnamefont{T.}~\\bibnamefont{Damour}} \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{A.}~\\bibnamefont{Nagar}},\n  \\bibinfo{journal}{Phys.\\ Rev.\\ D} \\textbf{\\bibinfo{volume}{79}},\n  \\bibinfo{pages}{081503} (\\bibinfo{year}{2009}). %, \\eprint{0902.0136}.\n\n\\bibitem[{\\citenamefont{Pan et~al.}(2010)\\citenamefont{Pan, Buonanno, Buchman,\n  Chu, Kidder et~al.}}]{Pan:2009wj}\n\\bibinfo{author}{\\bibfnamefont{Y.}~\\bibnamefont{Pan}},\n  \\bibinfo{author}{\\bibfnamefont{A.}~\\bibnamefont{Buonanno}},\n  \\bibinfo{author}{\\bibfnamefont{L.~T.} \\bibnamefont{Buchman}},\n  \\bibinfo{author}{\\bibfnamefont{T.}~\\bibnamefont{Chu}},\n  \\bibinfo{author}{\\bibfnamefont{L.~E.} \\bibnamefont{Kidder}},\n \\bibinfo{author}{\\bibfnamefont{H.~P.} \\bibnamefont{Pfeiffer}} \\bibfnamefont{and} \\bibinfo{author}{\\bibfnamefont{M.~A.} \\bibnamefont{Scheel}}, \\bibinfo{journal}{Phys.\\ Rev.\\ D}\n  \\textbf{\\bibinfo{volume}{81}}, \\bibinfo{pages}{084041}\n  (\\bibinfo{year}{2010}). %, \\eprint{0912.3466}.\n\n\\bibitem[{\\citenamefont{Santamar\\'{i}a\n  et~al.}(2010)\\citenamefont{Santamar\\'{i}a, Ohme, Ajith, Br{\\\"u}gmann,\n  Dorband, Hannam, Husa, M{\\\"o}sta, Pollney, Reisswig\n  et~al.}}]{Santamaria:2010yb}\n\\bibinfo{author}{\\bibfnamefont{L.}~\\bibnamefont{Santamar\\'{i}a}}%,\n  %\\bibinfo{author}{\\bibfnamefont{F.}~\\bibnamefont{Ohme}},\n  %\\bibinfo{author}{\\bibfnamefont{P.}~\\bibnamefont{Ajith}},\n  %\\bibinfo{author}{\\bibfnamefont{B.}~\\bibnamefont{Br{\\\"u}gmann}},\n  %\\bibinfo{author}{\\bibfnamefont{N.}~\\bibnamefont{Dorband}},\n  %\\bibinfo{author}{\\bibfnamefont{M.}~\\bibnamefont{Hannam}},\n  %\\bibinfo{author}{\\bibfnamefont{S.}~\\bibnamefont{Husa}},\n  %\\bibinfo{author}{\\bibfnamefont{P.}~\\bibnamefont{M{\\\"o}sta}},\n  %\\bibinfo{author}{\\bibfnamefont{D.}~\\bibnamefont{Pollney}},\n  %\\bibinfo{author}{\\bibfnamefont{C.}~\\bibnamefont{Reisswig}},\n  \\bibnamefont{\\textit{et~al}.}, \\bibinfo{journal}{Phys.\\ Rev.\\ D}\n  \\textbf{\\bibinfo{volume}{82}}, \\bibinfo{pages}{064016}\n  (\\bibinfo{year}{2010}).\n\n\\bibitem[{\\citenamefont{Pan et~al.}(2011{\\natexlab{a}})\\citenamefont{Pan,\n  Buonanno, Boyle, Buchman, Kidder et~al.}}]{Pan:2011gk}\n\\bibinfo{author}{\\bibfnamefont{Y.}~\\bibnamefont{Pan}},\n  \\bibinfo{author}{\\bibfnamefont{A.}~\\bibnamefont{Buonanno}},\n  \\bibinfo{author}{\\bibfnamefont{M.}~\\bibnamefont{Boyle}},\n  \\bibinfo{author}{\\bibfnamefont{L.~T.} \\bibnamefont{Buchman}},\n  \\bibinfo{author}{\\bibfnamefont{L.~E.} \\bibnamefont{Kidder}},\n \\bibinfo{author}{\\bibfnamefont{H.~P.} \\bibnamefont{Pfeiffer}} \\bibfnamefont{and} \\bibinfo{author}{\\bibfnamefont{M.~A.} \\bibnamefont{Scheel}}, \\bibinfo{journal}{Phys.\\ Rev.\\ D}\n  \\textbf{\\bibinfo{volume}{84}}, \\bibinfo{pages}{124052}\n  (\\bibinfo{year}{2011}{\\natexlab{a}})%, \\eprint{1106.1021}.\n\n\\bibitem[{\\citenamefont{Blanchet et~al.}(1995)\\citenamefont{Blanchet, Damour,\n  and Iyer}}]{Blanchet95a}\n\\bibinfo{author}{\\bibfnamefont{L.}~\\bibnamefont{Blanchet}},\n  \\bibinfo{author}{\\bibfnamefont{T.}~\\bibnamefont{Damour}}, \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{B.~R.} \\bibnamefont{Iyer}},\n  \\bibinfo{journal}{Phys.\\ Rev.\\ D} \\textbf{\\bibinfo{volume}{51}},\n  \\bibinfo{pages}{5360} (\\bibinfo{year}{1995}).\n\n\\bibitem[{\\citenamefont{Blanchet et~al.}(2004)\\citenamefont{Blanchet, Damour,\n  and Esposito-Far\\`{e}se}}]{Blanchet04}\n\\bibinfo{author}{\\bibfnamefont{L.}~\\bibnamefont{Blanchet}},\n  \\bibinfo{author}{\\bibfnamefont{T.}~\\bibnamefont{Damour}}, \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{G.}~\\bibnamefont{Esposito-Far\\`{e}se}},\n  \\bibinfo{journal}{Phys.\\ Rev.\\ D} \\textbf{\\bibinfo{volume}{69}},\n  \\bibinfo{pages}{124007} (\\bibinfo{year}{2004}).\n\n\\bibitem[{\\citenamefont{LucBlanchet et~al.}(2005)\\citenamefont{LucBlanchet,\n  Qusailah, and Will}}]{Blanchet2005b}\n\\bibinfo{author}{\\bibnamefont{K.~G.  Arun}},\n\\bibinfo{author}{\\bibnamefont{L.~ Blanchet}},\n \\bibinfo{author}{\\bibfnamefont{B.~R.} \\bibnamefont{Iyer}},\n \\bibnamefont{and}  \\bibinfo{author}{\\bibfnamefont{M.~S.~S.} \\bibnamefont{Qusailah}},\n  \\bibinfo{journal}{Classical Quantum Gravity} \\textbf{\\bibinfo{volume}{21}},\n  \\bibinfo{pages}{377} (\\bibinfo{year}{2004}). %, \\eprint{arXiv:astro-ph/0507692}.\n\n\\bibitem[{\\citenamefont{Blanchet et~al.}(1996)\\citenamefont{Blanchet, Iyer,\n  Will, and Wiseman}}]{Blanchet96a}\n\\bibinfo{author}{\\bibfnamefont{L.}~\\bibnamefont{Blanchet}},\n  \\bibinfo{author}{\\bibfnamefont{B.~R.} \\bibnamefont{Iyer}},\n  \\bibinfo{author}{\\bibfnamefont{C.~M.} \\bibnamefont{Will}}, \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{A.~G.} \\bibnamefont{Wiseman}},\n  \\bibinfo{journal}{Classical Quantum Gravity} \\textbf{\\bibinfo{volume}{13}},\n  \\bibinfo{pages}{575} (\\bibinfo{year}{1996}).\n\n\\bibitem[{\\citenamefont{{Kidder} et~al.}(2007)\\citenamefont{{Kidder},\n  {Blanchet}, and {Iyer}}}]{Kidder07}\n\\bibinfo{author}{\\bibfnamefont{L.~E.} \\bibnamefont{{Kidder}}},\n  \\bibinfo{author}{\\bibfnamefont{L.}~\\bibnamefont{{Blanchet}}},\n  \\bibnamefont{and} \\bibinfo{author}{\\bibfnamefont{B.~R.}\n  \\bibnamefont{{Iyer}}}, \\bibinfo{journal}{Classical Quantum Gravity}\n  \\textbf{\\bibinfo{volume}{24}}, \\bibinfo{pages}{5307} (\\bibinfo{year}{2007}).\n\n\\bibitem[{\\citenamefont{Kidder}(2008)}]{Kidder2008}\n\\bibinfo{author}{\\bibfnamefont{L.~E.} \\bibnamefont{Kidder}},\n  \\bibinfo{journal}{Phys.\\ Rev.\\ D} \\textbf{\\bibinfo{volume}{77}},\n  \\bibinfo{pages}{044016} (\\bibinfo{year}{2008}).%, \\eprint{0710.0614}.\n\n\\bibitem[{\\citenamefont{Blanchet et~al.}(2008)\\citenamefont{Blanchet, Faye,\n  Iyer, and Sinha}}]{BFIS}\n\\bibinfo{author}{\\bibfnamefont{L.}~\\bibnamefont{Blanchet}},\n  \\bibinfo{author}{\\bibfnamefont{G.}~\\bibnamefont{Faye}},\n  \\bibinfo{author}{\\bibfnamefont{B.~R.} \\bibnamefont{Iyer}}, \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{S.}~\\bibnamefont{Sinha}},\n  \\bibinfo{journal}{Classical Quantum Gravity} \\textbf{\\bibinfo{volume}{25}},\n  \\bibinfo{pages}{165003} (\\bibinfo{year}{2008}).%, \\eprint{0802.1249}.\n\n\\bibitem[{\\citenamefont{Faye et~al.}(2012)\\citenamefont{Faye, Marsat, Blanchet,\n  and Iyer}}]{Faye:2012we}\n\\bibinfo{author}{\\bibfnamefont{G.}~\\bibnamefont{Faye}},\n  \\bibinfo{author}{\\bibfnamefont{S.}~\\bibnamefont{Marsat}},\n  \\bibinfo{author}{\\bibfnamefont{L.}~\\bibnamefont{Blanchet}}, \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{B.~R.} \\bibnamefont{Iyer}},\n\\bibinfo{journal}{Classical Quantum Gravity} \\textbf{\\bibinfo{volume}{29}},\n  \\bibinfo{pages}{175004} (\\bibinfo{year}{2012}). %, \\eprint{1204.1043}.\n\n\\bibitem[{\\citenamefont{{Miller} et~al.}(2009)\\citenamefont{{Miller},\n  {Reynolds}, {Fabian}, {Miniutti}, and {Gallo}}}]{Miller2009}\n\\bibinfo{author}{\\bibfnamefont{J.~M.} \\bibnamefont{{Miller}}},\n  \\bibinfo{author}{\\bibfnamefont{C.~S.} \\bibnamefont{{Reynolds}}},\n  \\bibinfo{author}{\\bibfnamefont{A.~C.} \\bibnamefont{{Fabian}}},\n  \\bibinfo{author}{\\bibfnamefont{G.}~\\bibnamefont{{Miniutti}}},\n  \\bibnamefont{and} \\bibinfo{author}{\\bibfnamefont{L.~C.}\n  \\bibnamefont{{Gallo}}}, \\bibinfo{journal}{\\apj}\n  \\textbf{\\bibinfo{volume}{697}}, \\bibinfo{pages}{900} (\\bibinfo{year}{2009}).%,\n  %\\eprint{0902.2840}.\n\n\\bibitem[{\\citenamefont{Apostolatos et~al.}(1994)\\citenamefont{Apostolatos,\n  Cutler, Sussman, and Thorne}}]{Apostolatos1994}\n\\bibinfo{author}{\\bibfnamefont{T.~A.} \\bibnamefont{Apostolatos}},\n  \\bibinfo{author}{\\bibfnamefont{C.}~\\bibnamefont{Cutler}},\n  \\bibinfo{author}{\\bibfnamefont{G.~J.} \\bibnamefont{Sussman}},\n  \\bibnamefont{and} \\bibinfo{author}{\\bibfnamefont{K.~S.}\n  \\bibnamefont{Thorne}}, \\bibinfo{journal}{Phys.\\ Rev.\\ D}\n  \\textbf{\\bibinfo{volume}{49}}, \\bibinfo{pages}{6274 } (\\bibinfo{year}{1994}).\n\n\\bibitem[{\\citenamefont{{Apostolatos}}(1996)}]{Apostolatos1996}\n\\bibinfo{author}{\\bibfnamefont{T.~A.} \\bibnamefont{{Apostolatos}}},\n  \\bibinfo{journal}{\\prd} \\textbf{\\bibinfo{volume}{54}}, \\bibinfo{pages}{2421}\n  (\\bibinfo{year}{1996}).\n\n\\bibitem[{\\citenamefont{Buonanno et~al.}(2003)\\citenamefont{Buonanno, Chen, and\n  Vallisneri}}]{Buonanno:2002fy}\n\\bibinfo{author}{\\bibfnamefont{A.}~\\bibnamefont{Buonanno}},\n  \\bibinfo{author}{\\bibfnamefont{Y.}~\\bibnamefont{Chen}}, \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{M.}~\\bibnamefont{Vallisneri}},\n  \\bibinfo{journal}{Phys.\\ Rev.\\ D} \\textbf{\\bibinfo{volume}{67}},\n  \\bibinfo{pages}{104025} (\\bibinfo{year}{2003}).%, \\eprint{gr-qc/0211087}.\n\n\\bibitem[{\\citenamefont{Pan et~al.}(2004)\\citenamefont{Pan, Buonanno, Chen, and\n  Vallisneri}}]{Pan:2003qt}\n\\bibinfo{author}{\\bibfnamefont{Y.}~\\bibnamefont{Pan}},\n  \\bibinfo{author}{\\bibfnamefont{A.}~\\bibnamefont{Buonanno}},\n  \\bibinfo{author}{\\bibfnamefont{Y.}~\\bibnamefont{Chen}}, \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{M.}~\\bibnamefont{Vallisneri}},\n  \\bibinfo{journal}{Phys.\\ Rev.\\ D} \\textbf{\\bibinfo{volume}{69}},\n  \\bibinfo{pages}{104017} (\\bibinfo{year}{2004}).%, \\eprint{gr-qc/0310034}.\n\n\\bibitem[{\\citenamefont{Buonanno et~al.}(2004)\\citenamefont{Buonanno, Chen,\n  Pan, and Vallisneri}}]{Buonanno2004}\n\\bibinfo{author}{\\bibfnamefont{A.}~\\bibnamefont{Buonanno}},\n  \\bibinfo{author}{\\bibfnamefont{Y.}~\\bibnamefont{Chen}},\n  \\bibinfo{author}{\\bibfnamefont{Y.}~\\bibnamefont{Pan}}, \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{M.}~\\bibnamefont{Vallisneri}},\n  \\bibinfo{journal}{Phys.\\ Rev.\\ D} \\textbf{\\bibinfo{volume}{70}},\n  \\bibinfo{pages}{104003} (\\bibinfo{year}{2004}).\n\n\\bibitem[{\\citenamefont{Buonanno et~al.}(2005)\\citenamefont{Buonanno, Chen,\n  Pan, Tagoshi, and Vallisneri}}]{Buonanno:2005pt}\n\\bibinfo{author}{\\bibfnamefont{A.}~\\bibnamefont{Buonanno}},\n  \\bibinfo{author}{\\bibfnamefont{Y.}~\\bibnamefont{Chen}},\n  \\bibinfo{author}{\\bibfnamefont{Y.}~\\bibnamefont{Pan}},\n  \\bibinfo{author}{\\bibfnamefont{H.}~\\bibnamefont{Tagoshi}}, \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{M.}~\\bibnamefont{Vallisneri}},\n  \\bibinfo{journal}{Phys.\\ Rev.\\ D} \\textbf{\\bibinfo{volume}{72}},\n  \\bibinfo{pages}{084027} (\\bibinfo{year}{2005}).%, \\eprint{gr-qc/0508064}.\n\n\\bibitem[{\\citenamefont{Buonanno et~al.}(2006)\\citenamefont{Buonanno, Chen, and\n  Damour}}]{Buonanno06}\n\\bibinfo{author}{\\bibfnamefont{A.}~\\bibnamefont{Buonanno}},\n  \\bibinfo{author}{\\bibfnamefont{Y.}~\\bibnamefont{Chen}}, \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{T.}~\\bibnamefont{Damour}},\n  \\bibinfo{journal}{Phys.\\ Rev.\\ D} \\textbf{\\bibinfo{volume}{74}},\n  \\bibinfo{pages}{104005} (\\bibinfo{year}{2006}).%, \\eprint{gr-qc/0508067}.\n\n\\bibitem[{\\citenamefont{{Ajith} et~al.}(2009)\\citenamefont{{Ajith}, {Hannam},\n  {Husa}, {Chen}, {Bruegmann}, {Dorband}, {Mueller}, {Ohme}, {Pollney},\n  {Reisswig} et~al.}}]{Ajith:2009}\n\\bibinfo{author}{\\bibfnamefont{P.}~\\bibnamefont{{Ajith}}},\n  \\bibinfo{author}{\\bibfnamefont{M.}~\\bibnamefont{{Hannam}}},\n  \\bibinfo{author}{\\bibfnamefont{S.}~\\bibnamefont{{Husa}}},\n  \\bibinfo{author}{\\bibfnamefont{Y.}~\\bibnamefont{{Chen}}},\n  \\bibinfo{author}{\\bibfnamefont{B.}~\\bibnamefont{{Bruegmann}}},\n  \\bibinfo{author}{\\bibfnamefont{N.}~\\bibnamefont{{Dorband}}},\n  \\bibinfo{author}{\\bibfnamefont{D.}~\\bibnamefont{{Mueller}}},\n  \\bibinfo{author}{\\bibfnamefont{F.}~\\bibnamefont{{Ohme}}},\n  \\bibinfo{author}{\\bibfnamefont{D.}~\\bibnamefont{{Pollney}}},\n  \\bibinfo{author}{\\bibfnamefont{C.}~\\bibnamefont{{Reisswig}}},\n  \\bibinfo{author}{\\bibfnamefont{L.}~\\bibnamefont{{Santamar\\'{i}a}}},\n\\bibnamefont{and} \\bibinfo{author}{\\bibfnamefont{J.}~\\bibnamefont{{Seiler}}},  \n \\bibinfo{journal}{Phys.\\ Rev.\\ Lett.} \\textbf{\\bibinfo{volume}{106}},\n  \\bibinfo{pages}{241101} (\\bibinfo{year}{2011}) \n%, \\bibinfo{journal}{ArXiv e-prints}\n  %(\\bibinfo{year}{2009}).%, \\eprint{0909.2867}.\n\n\\bibitem[{\\citenamefont{Ajith}(2011)}]{Ajith:2011ec}\n\\bibinfo{author}{\\bibfnamefont{P.}~\\bibnamefont{Ajith}},\n  \\bibinfo{journal}{Phys.\\ Rev.\\ D} \\textbf{\\bibinfo{volume}{84}},\n  \\bibinfo{pages}{084037} (\\bibinfo{year}{2011}).%, \\eprint{1107.1267}.\n\n\\bibitem[{\\citenamefont{Brown et~al.}(2012)\\citenamefont{Brown, Lundgren, and\n  O'Shaughnessy}}]{Brown:2012gs}\n\\bibinfo{author}{\\bibfnamefont{D.~A.} \\bibnamefont{Brown}},\n  \\bibinfo{author}{\\bibfnamefont{A.}~\\bibnamefont{Lundgren}}, \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{R.}~\\bibnamefont{O'Shaughnessy}},\n\\bibinfo{journal}{Phys.\\ Rev.\\ D} \\textbf{\\bibinfo{volume}{86}},\n  \\bibinfo{pages}{064020} (\\bibinfo{year}{2012}).%, \\eprint{1203.6060}.\n\n\\bibitem[{\\citenamefont{Taracchini et~al.}(2012)\\citenamefont{Taracchini, Pan,\n  Buonanno, Barausse, Boyle et~al.}}]{Taracchini:2012ig}\n\\bibinfo{author}{\\bibfnamefont{A.}~\\bibnamefont{Taracchini}},\n  \\bibinfo{author}{\\bibfnamefont{Y.}~\\bibnamefont{Pan}},\n  \\bibinfo{author}{\\bibfnamefont{A.}~\\bibnamefont{Buonanno}},\n  \\bibinfo{author}{\\bibfnamefont{E.}~\\bibnamefont{Barausse}},\n  \\bibinfo{author}{\\bibfnamefont{M.}~\\bibnamefont{Boyle}},\n\\bibinfo{author}{\\bibfnamefont{T.}~\\bibnamefont{Chu}},\n\\bibinfo{author}{\\bibfnamefont{G.}~\\bibnamefont{Lovelace}},\n\\bibinfo{author}{\\bibfnamefont{H.~P.} \\bibnamefont{Pfeiffer}}, \\bibfnamefont{and}\n\\bibinfo{author}{\\bibfnamefont{M.~A.} \\bibnamefont{Scheel}}\n\\bibinfo{journal}{Phys.\\ Rev.\\ D} \\textbf{\\bibinfo{volume}{86}},\n  \\bibinfo{pages}{024011} (\\bibinfo{year}{2012}).%, \\eprint{1202.0790}.\n\n\\bibitem[{\\citenamefont{Cutler and Flanagan}(1994)}]{CutlerFlanagan1994}\n\\bibinfo{author}{\\bibfnamefont{C.}~\\bibnamefont{Cutler}} \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{E.~E.} \\bibnamefont{Flanagan}},\n  \\bibinfo{journal}{Phys.\\ Rev.\\ D} \\textbf{\\bibinfo{volume}{49}},\n  \\bibinfo{pages}{2658} (\\bibinfo{year}{1994}).\n\n\\bibitem[{\\citenamefont{{Poisson} and {Will}}(1995)}]{PoissonWill95}\n\\bibinfo{author}{\\bibfnamefont{E.}~\\bibnamefont{{Poisson}}} \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{C.~M.} \\bibnamefont{{Will}}},\n  \\bibinfo{journal}{Phys.\\ Rev.\\ D} \\textbf{\\bibinfo{volume}{52}},\n  \\bibinfo{pages}{848} (\\bibinfo{year}{1995}).%, \\eprint{arXiv:gr-qc/9502040}.\n\n\\bibitem[{\\citenamefont{{van der Sluys} et~al.}(2008)\\citenamefont{{van der\n  Sluys}, {R{\\\"o}ver}, {Stroeer}, {Raymond}, {Mandel}, {Christensen},\n  {Kalogera}, {Meyer}, and {Vecchio}}}]{vanderSluys}\n\\bibinfo{author}{\\bibfnamefont{M.~V.} \\bibnamefont{{van der Sluys}}},\n  \\bibinfo{author}{\\bibfnamefont{C.}~\\bibnamefont{{R{\\\"o}ver}}},\n  \\bibinfo{author}{\\bibfnamefont{A.}~\\bibnamefont{{Stroeer}}},\n  \\bibinfo{author}{\\bibfnamefont{V.}~\\bibnamefont{{Raymond}}},\n  \\bibinfo{author}{\\bibfnamefont{I.}~\\bibnamefont{{Mandel}}},\n  \\bibinfo{author}{\\bibfnamefont{N.}~\\bibnamefont{{Christensen}}},\n  \\bibinfo{author}{\\bibfnamefont{V.}~\\bibnamefont{{Kalogera}}},\n  \\bibinfo{author}{\\bibfnamefont{R.}~\\bibnamefont{{Meyer}}}, \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{A.}~\\bibnamefont{{Vecchio}}},\n  \\bibinfo{journal}{Astrophys.\\ J.\\ Lett.} \\textbf{\\bibinfo{volume}{688}},\n  \\bibinfo{pages}{L61} (\\bibinfo{year}{2008}).%, \\eprint{0710.1897}.\n\n\\bibitem[{\\citenamefont{Ajith and Bose}(2009)}]{AjithBose2009}\n\\bibinfo{author}{\\bibfnamefont{P.}~\\bibnamefont{Ajith}} \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{S.}~\\bibnamefont{Bose}},\n  \\bibinfo{journal}{Phys.\\ Rev.\\ D} \\textbf{\\bibinfo{volume}{79}},\n  \\bibinfo{pages}{084032} (\\bibinfo{year}{2009}).%,\n % \\eprint{arXiv:0901.4936[gr-qc]}.\n\n\\bibitem[{\\citenamefont{Mikoczi et~al.}(2005)\\citenamefont{Mikoczi, Vasuth, and\n  Gergely}}]{Mikoczi:2005dn}\n\\bibinfo{author}{\\bibfnamefont{B.}~\\bibnamefont{Mikoczi}},\n  \\bibinfo{author}{\\bibfnamefont{M.}~\\bibnamefont{Vasuth}}, \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{L.~A.} \\bibnamefont{Gergely}},\n  \\bibinfo{journal}{\\prd} \\textbf{\\bibinfo{volume}{71}},\n  \\bibinfo{pages}{124043} (\\bibinfo{year}{2005}).%, \\eprint{astro-ph/0504538}.\n\n\\bibitem[{\\citenamefont{Faye et~al.}(2006)\\citenamefont{Faye, Blanchet, and\n  Buonanno}}]{Faye-Blanchet-Buonanno:2006}\n\\bibinfo{author}{\\bibfnamefont{G.}~\\bibnamefont{Faye}},\n  \\bibinfo{author}{\\bibfnamefont{L.}~\\bibnamefont{Blanchet}}, \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{A.}~\\bibnamefont{Buonanno}},\n  \\bibinfo{journal}{Phys.\\ Rev.\\ D} \\textbf{\\bibinfo{volume}{74}},\n  \\bibinfo{eid}{104033} (\\bibinfo{year}{2006}).\n\n\\bibitem[{\\citenamefont{Blanchet et~al.}(2006)\\citenamefont{Blanchet, Buonanno,\n  and Faye}}]{Blanchet-Buonanno-Faye:2006}\n\\bibinfo{author}{\\bibfnamefont{L.}~\\bibnamefont{Blanchet}},\n  \\bibinfo{author}{\\bibfnamefont{A.}~\\bibnamefont{Buonanno}}, \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{G.}~\\bibnamefont{Faye}},\n  \\bibinfo{journal}{Phys.\\ Rev.\\ D} \\textbf{\\bibinfo{volume}{74}},\n  \\bibinfo{eid}{104034} (\\bibinfo{year}{2006}).\n\n\\bibitem[{\\citenamefont{Kidder}(1995)}]{Kidder:1995zr}\n\\bibinfo{author}{\\bibfnamefont{L.~E.} \\bibnamefont{Kidder}},\n  \\bibinfo{journal}{Phys. Rev. D} \\textbf{\\bibinfo{volume}{52}},\n  \\bibinfo{pages}{821} (\\bibinfo{year}{1995}).\n\n\\bibitem[{\\citenamefont{Arun et~al.}(2009)\\citenamefont{Arun, Buonanno, Faye,\n  and Ochsner}}]{Arun:2009}\n\\bibinfo{author}{\\bibfnamefont{K.~G.}~\\bibnamefont{Arun}},\n  \\bibinfo{author}{\\bibfnamefont{A.}~\\bibnamefont{Buonanno}},\n  \\bibinfo{author}{\\bibfnamefont{G.}~\\bibnamefont{Faye}}, \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{E.}~\\bibnamefont{Ochsner}},\n  \\bibinfo{journal}{Phys. Rev. D} \\textbf{\\bibinfo{volume}{79}},\n  \\bibinfo{pages}{104023} (\\bibinfo{year}{2009}).%, \\eprint{0810.5336}.\n\n\\bibitem[{\\citenamefont{Will and Wiseman}(1996)}]{Will96}\n\\bibinfo{author}{\\bibfnamefont{C.~M.} \\bibnamefont{Will}} \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{A.~G.} \\bibnamefont{Wiseman}},\n  \\bibinfo{journal}{Phys.\\ Rev.\\ D} \\textbf{\\bibinfo{volume}{54}},\n  \\bibinfo{pages}{4813} (\\bibinfo{year}{1996}).\n\n\\bibitem[{\\citenamefont{Blanchet et~al.}(2011)\\citenamefont{Blanchet, Buonanno,\n  and Faye}}]{BlanchetEtAl:2011}\n\\bibinfo{author}{\\bibfnamefont{L.}~\\bibnamefont{Blanchet}},\n  \\bibinfo{author}{\\bibfnamefont{A.}~\\bibnamefont{Buonanno}}, \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{G.}~\\bibnamefont{Faye}},\n  \\bibinfo{journal}{Phys.\\ Rev.\\ D} \\textbf{\\bibinfo{volume}{84}},\n  \\bibinfo{pages}{064041} (\\bibinfo{year}{2011}).%, \\eprint{1104.5659}.\n\n\\bibitem[{\\citenamefont{{Bailey} and {Israel}}(1980)}]{1980AnPhy.130..188B}\n\\bibinfo{author}{\\bibfnamefont{I.}~\\bibnamefont{{Bailey}}} \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{W.}~\\bibnamefont{{Israel}}},\n  \\bibinfo{journal}{Ann. Phys. (N.Y.)} \\textbf{\\bibinfo{volume}{130}},\n  \\bibinfo{pages}{188} (\\bibinfo{year}{1980}).\n\n\\bibitem[{\\citenamefont{{Porto} and {Rothstein}}(2006)}]{PortoRothstein2006}\n\\bibinfo{author}{\\bibfnamefont{R.~A.} \\bibnamefont{{Porto}}} \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{I.~Z.} \\bibnamefont{{Rothstein}}},\n  \\bibinfo{journal}{Phys.\\  Rev.\\  Lett.} \\textbf{\\bibinfo{volume}{97}},\n  \\bibinfo{eid}{021101} (\\bibinfo{year}{2006}).%, \\eprint{arXiv:gr-qc/0604099}.\n\n\\bibitem[{\\citenamefont{Porto and\n  Rothstein}(2008{\\natexlab{a}})}]{Porto:2008jj}\n\\bibinfo{author}{\\bibfnamefont{R.~A.} \\bibnamefont{Porto}} \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{I.~Z.} \\bibnamefont{Rothstein}},\n  \\bibinfo{journal}{Phys.\\ Rev.\\ D} \\textbf{\\bibinfo{volume}{78}},\n  \\bibinfo{pages}{044013} (\\bibinfo{year}{2008}{\\natexlab{a}}).%,\n % \\eprint{0804.0260}.\n\n\\bibitem[{\\citenamefont{Steinhoff and Puetzfeld}(2010)}]{SP10}\n\\bibinfo{author}{\\bibfnamefont{J.}~\\bibnamefont{Steinhoff}} \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{D.}~\\bibnamefont{Puetzfeld}},\n  \\bibinfo{journal}{Phys.\\ Rev.\\ D} \\textbf{\\bibinfo{volume}{81}},\n  \\bibinfo{pages}{044019} (\\bibinfo{year}{2010}).\n\n\\bibitem[{\\citenamefont{Poisson}(1998)}]{Poisson:1997ha}\n\\bibinfo{author}{\\bibfnamefont{E.}~\\bibnamefont{Poisson}},\n  \\bibinfo{journal}{Phys.\\ Rev.\\ D} \\textbf{\\bibinfo{volume}{57}},\n  \\bibinfo{pages}{5287} (\\bibinfo{year}{1998}). %, \\eprint{gr-qc/9709032}.\n\n\\bibitem[{\\citenamefont{Damour}(2001)}]{Damour01c}\n\\bibinfo{author}{\\bibfnamefont{T.}~\\bibnamefont{Damour}},\n  \\bibinfo{journal}{Phys.\\ Rev.\\ D} \\textbf{\\bibinfo{volume}{64}},\n  \\bibinfo{pages}{124013} (\\bibinfo{year}{2001}).%, \\eprint{gr-qc/0103018}.\n\n\\bibitem[{\\citenamefont{Steinhoff}(2011)}]{Steinhoff:2010zz}\n\\bibinfo{author}{\\bibfnamefont{J.}~\\bibnamefont{Steinhoff}},\n  \\bibinfo{journal}{Annalen Phys. (Berlin)} \\textbf{\\bibinfo{volume}{523}},\n  \\bibinfo{pages}{296} (\\bibinfo{year}{2011}).%, \\eprint{1106.4203}.\n\n\\bibitem[{\\citenamefont{{Porto} et~al.}(2012)\\citenamefont{{Porto}, {Ross}, and\n  {Rothstein}}}]{Porto:2012x}\n\\bibinfo{author}{\\bibfnamefont{R.~A.} \\bibnamefont{{Porto}}},\n  \\bibinfo{author}{\\bibfnamefont{A.}~\\bibnamefont{{Ross}}}, \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{I.~Z.} \\bibnamefont{{Rothstein}}},\n  \\bibinfo{journal}{J. Cosmol. Astropart. Phys. 09}  (\\bibinfo{year}{2012}) 028.\n  %\\eprint{1203.2962}.\n\n\\bibitem[{\\citenamefont{Porto and\n  Rothstein}(2008{\\natexlab{b}})}]{Porto:2008tb}\n\\bibinfo{author}{\\bibfnamefont{R.~A.} \\bibnamefont{Porto}} \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{I.~Z.} \\bibnamefont{Rothstein}},\n  \\bibinfo{journal}{\\prd} \\textbf{\\bibinfo{volume}{78}},\n  \\bibinfo{pages}{044012} (\\bibinfo{year}{2008}{\\natexlab{b}}).%,\n % \\eprint{0802.0720}.\n\n\\bibitem[{\\citenamefont{Porto}(2010)}]{Porto:2010tr}\n\\bibinfo{author}{\\bibfnamefont{R.~A.} \\bibnamefont{Porto}},\n  \\bibinfo{journal}{Classical Quantum Gravity} \\textbf{\\bibinfo{volume}{27}},\n  \\bibinfo{pages}{205001} (\\bibinfo{year}{2010}).%, \\eprint{1005.5730}.\n\n\\bibitem[{\\citenamefont{Damour et~al.}(2008)\\citenamefont{Damour, Jaranowski,\n  and Schaefer}}]{Damour:2007nc}\n\\bibinfo{author}{\\bibfnamefont{T.}~\\bibnamefont{Damour}},\n  \\bibinfo{author}{\\bibfnamefont{P.}~\\bibnamefont{Jaranowski}},\n  \\bibnamefont{and} \\bibinfo{author}{\\bibfnamefont{G.}~\\bibnamefont{Schafer}},\n  \\bibinfo{journal}{\\prd} \\textbf{\\bibinfo{volume}{77}},\n  \\bibinfo{pages}{064032} (\\bibinfo{year}{2008}).%, \\eprint{0711.1048}.\n\n\\bibitem[{\\citenamefont{{Steinhoff}\n  et~al.}(2008{\\natexlab{a}})\\citenamefont{{Steinhoff}, {Sch{\\\"a}fer}, and\n  {Hergt}}}]{Steinhoff08}\n\\bibinfo{author}{\\bibfnamefont{J.}~\\bibnamefont{{Steinhoff}}},\n  \\bibinfo{author}{\\bibfnamefont{G.}~\\bibnamefont{{Sch{\\\"a}fer}}},\n  \\bibnamefont{and} \\bibinfo{author}{\\bibfnamefont{S.}~\\bibnamefont{{Hergt}}},\n  \\bibinfo{journal}{\\prd} \\textbf{\\bibinfo{volume}{77}}, \\bibinfo{eid}{104018}\n  (\\bibinfo{year}{2008}{\\natexlab{a}}).%, \\eprint{0805.3136}.\n\n\\bibitem[{\\citenamefont{{Steinhoff}\n  et~al.}(2008{\\natexlab{b}})\\citenamefont{{Steinhoff}, {Hergt}, and\n  {Sch{\\\"a}fer}}}]{Steinhoff08a}\n\\bibinfo{author}{\\bibfnamefont{J.}~\\bibnamefont{{Steinhoff}}},\n  \\bibinfo{author}{\\bibfnamefont{S.}~\\bibnamefont{{Hergt}}}, \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{G.}~\\bibnamefont{{Sch{\\\"a}fer}}},\n  \\bibinfo{journal}{\\prd} \\textbf{\\bibinfo{volume}{77}},\n  \\bibinfo{pages}{081501} (\\bibinfo{year}{2008}{\\natexlab{b}}).%,\n  %\\eprint{0712.1716}.\n\n\\bibitem[{\\citenamefont{{Steinhoff}\n  et~al.}(2008{\\natexlab{c}})\\citenamefont{{Steinhoff}, {Hergt}, and\n  {Sch{\\\"a}fer}}}]{Steinhoff08b}\n\\bibinfo{author}{\\bibfnamefont{J.}~\\bibnamefont{{Steinhoff}}},\n  \\bibinfo{author}{\\bibfnamefont{S.}~\\bibnamefont{{Hergt}}}, \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{G.}~\\bibnamefont{{Sch{\\\"a}fer}}},\n  \\bibinfo{journal}{\\prd} \\textbf{\\bibinfo{volume}{78}}, \\bibinfo{eid}{101503}\n  (\\bibinfo{year}{2008}{\\natexlab{c}}).%, \\eprint{0809.2200}.\n\n\\bibitem[{\\citenamefont{Thorne}(1980)}]{thorne80}\n\\bibinfo{author}{\\bibfnamefont{K.~S.} \\bibnamefont{Thorne}},\n  \\bibinfo{journal}{Rev. Mod. Phys.} \\textbf{\\bibinfo{volume}{52}},\n  \\bibinfo{pages}{299} (\\bibinfo{year}{1980}).\n\n\\bibitem[{\\citenamefont{Blanchet and Damour}(1992)}]{Blanchet:1992br}\n\\bibinfo{author}{\\bibfnamefont{L.}~\\bibnamefont{Blanchet}} \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{T.}~\\bibnamefont{Damour}},\n  \\bibinfo{journal}{Ann. Inst. Henri Poincare, Phys. Theor.} \\textbf{\\bibinfo{volume}{50}},\n  \\bibinfo{pages}{377} (\\bibinfo{year}{1989}),\n\\bibinfo{howpublished}{\\url{http://www.numdam.org/item?id=AIHPA_1989__50_4_377_0}}.\n\n\\bibitem[{\\citenamefont{Blanchet}(1995)}]{Blanchet:1995fr}\n\\bibinfo{author}{\\bibfnamefont{L.}~\\bibnamefont{Blanchet}},\n  \\bibinfo{journal}{\\prd} \\textbf{\\bibinfo{volume}{51}},\n  \\bibinfo{pages}{2559} (\\bibinfo{year}{1995}).%, \\eprint{gr-qc/9501030}.\n\n\\bibitem[{\\citenamefont{Schmidt et~al.}(2011)\\citenamefont{Schmidt, Hannam,\n  Husa, and Ajith}}]{Schmidt:2010it}\n\\bibinfo{author}{\\bibfnamefont{P.}~\\bibnamefont{Schmidt}},\n  \\bibinfo{author}{\\bibfnamefont{M.}~\\bibnamefont{Hannam}},\n  \\bibinfo{author}{\\bibfnamefont{S.}~\\bibnamefont{Husa}}, \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{P.}~\\bibnamefont{Ajith}},\n  \\bibinfo{journal}{Phys. Rev. D} \\textbf{\\bibinfo{volume}{84}},\n  \\bibinfo{pages}{024046} (\\bibinfo{year}{2011}).%, \\eprint{1012.2879}.\n\n\\bibitem[{\\citenamefont{{O'Shaughnessy}\n  et~al.}(2011)\\citenamefont{{O'Shaughnessy}, {Vaishnav}, {Healy}, {Meeks}, and\n  {Shoemaker}}}]{OShaughnessy2011}\n\\bibinfo{author}{\\bibfnamefont{R.}~\\bibnamefont{{O'Shaughnessy}}},\n  \\bibinfo{author}{\\bibfnamefont{B.}~\\bibnamefont{{Vaishnav}}},\n  \\bibinfo{author}{\\bibfnamefont{J.}~\\bibnamefont{{Healy}}},\n  \\bibinfo{author}{\\bibfnamefont{Z.}~\\bibnamefont{{Meeks}}}, \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{D.}~\\bibnamefont{{Shoemaker}}},\n  \\bibinfo{journal}{\\prd} \\textbf{\\bibinfo{volume}{84}}, \\bibinfo{eid}{124002}\n  (\\bibinfo{year}{2011}).%, \\eprint{1109.5224}.\n\n\\bibitem[{\\citenamefont{{Ochsner} and {O'Shaughnessy}}(2012)}]{Ochsner2012}\n\\bibinfo{author}{\\bibfnamefont{E.}~\\bibnamefont{{Ochsner}}} \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{R.}~\\bibnamefont{{O'Shaughnessy}}},\n  \\bibinfo{journal}{Phys. Rev. D}  \\textbf{\\bibinfo{volume}{86}}, \\bibinfo{pages}{104037}  (\\bibinfo{year}{2012}).%\n % \\eprint{1205.2287}.\n\n\\bibitem[{\\citenamefont{{Boyle} et~al.}(2011)\\citenamefont{{Boyle}, {Owen}, and\n  {Pfeiffer}}}]{2011PhRvD..84l4011B}\n\\bibinfo{author}{\\bibfnamefont{M.}~\\bibnamefont{{Boyle}}},\n  \\bibinfo{author}{\\bibfnamefont{R.}~\\bibnamefont{{Owen}}}, \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{H.~P.} \\bibnamefont{{Pfeiffer}}},\n  \\bibinfo{journal}{\\prd} \\textbf{\\bibinfo{volume}{84}}, \\bibinfo{eid}{124011}\n  (\\bibinfo{year}{2011}).%, \\eprint{1110.2965}.\n\n\\bibitem[{\\citenamefont{Schmidt et~al.}(2012)\\citenamefont{Schmidt, Hannam, and\n  Husa}}]{Schmidt:2012rh}\n\\bibinfo{author}{\\bibfnamefont{P.}~\\bibnamefont{Schmidt}},\n  \\bibinfo{author}{\\bibfnamefont{M.}~\\bibnamefont{Hannam}}, \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{S.}~\\bibnamefont{Husa}}\n \\bibinfo{journal}{Phys. Rev. D}  \\textbf{\\bibinfo{volume}{86}}, \\bibinfo{pages}{104063}  (\\bibinfo{year}{2012}).\n % (\\bibinfo{year}{2012}), \\eprint{1207.3088}.\n\n\\bibitem[{\\citenamefont{Mart\\'in-Garc\\'ia et~al.}(GPL\n  2002--2012)\\citenamefont{Mart\\'in-Garc\\'ia, Garc\\'ia-Parrado, Stecchina,\n  Wardell, Pitrou, Brizuela, Yllanes, Faye, Stein, Portugal et~al.}}]{xtensor}\n\\bibinfo{author}{\\bibfnamefont{J.~M.} \\bibnamefont{Mart\\'in-Garc\\'ia}},\n  \\bibinfo{author}{\\bibfnamefont{A.}~\\bibnamefont{Garc\\'ia-Parrado}},\n  \\bibinfo{author}{\\bibfnamefont{A.}~\\bibnamefont{Stecchina}},\n  \\bibinfo{author}{\\bibfnamefont{B.}~\\bibnamefont{Wardell}},\n  \\bibinfo{author}{\\bibfnamefont{C.}~\\bibnamefont{Pitrou}},\n  \\bibinfo{author}{\\bibfnamefont{D.}~\\bibnamefont{Brizuela}},\n  \\bibinfo{author}{\\bibfnamefont{D.}~\\bibnamefont{Yllanes}},\n  \\bibinfo{author}{\\bibfnamefont{G.}~\\bibnamefont{Faye}},\n  \\bibinfo{author}{\\bibfnamefont{L.}~\\bibnamefont{Stein}},\n  \\bibinfo{author}{\\bibfnamefont{R.}~\\bibnamefont{Portugal}},\n  \\bibnamefont{et~al.} (\\bibinfo{year}{GPL 2002--2012}),\n  \\bibinfo{note}{http://www.xact.es/}.\n\n\\bibitem[{\\citenamefont{{Owen} et~al.}(1998)\\citenamefont{{Owen}, {Tagoshi},\n  and {Ohashi}}}]{1998PhRvD..57.6168O}\n\\bibinfo{author}{\\bibfnamefont{B.~J.} \\bibnamefont{{Owen}}},\n  \\bibinfo{author}{\\bibfnamefont{H.}~\\bibnamefont{{Tagoshi}}},\n  \\bibnamefont{and} \\bibinfo{author}{\\bibfnamefont{A.}~\\bibnamefont{{Ohashi}}},\n  \\bibinfo{journal}{\\prd} \\textbf{\\bibinfo{volume}{57}}, \\bibinfo{pages}{6168}\n  (\\bibinfo{year}{1998}).%, \\eprint{arXiv:gr-qc/9710134}.\n\n\\bibitem[{\\citenamefont{Tagoshi et~al.}(1996)\\citenamefont{Tagoshi, Shibata,\n  Tanaka, and Sasaki}}]{Tagoshi:1996gh}\n\\bibinfo{author}{\\bibfnamefont{H.}~\\bibnamefont{Tagoshi}},\n  \\bibinfo{author}{\\bibfnamefont{M.}~\\bibnamefont{Shibata}},\n  \\bibinfo{author}{\\bibfnamefont{T.}~\\bibnamefont{Tanaka}}, \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{M.}~\\bibnamefont{Sasaki}},\n  \\bibinfo{journal}{\\prd} \\textbf{\\bibinfo{volume}{54}},\n  \\bibinfo{pages}{1439} (\\bibinfo{year}{1996}).%, \\eprint{gr-qc/9603028}.\n\n\\bibitem[{\\citenamefont{Pan et~al.}(2011{\\natexlab{b}})\\citenamefont{Pan,\n  Buonanno, Fujita, Racine, and Tagoshi}}]{Pan2010hz}\n\\bibinfo{author}{\\bibfnamefont{Y.}~\\bibnamefont{Pan}},\n  \\bibinfo{author}{\\bibfnamefont{A.}~\\bibnamefont{Buonanno}},\n  \\bibinfo{author}{\\bibfnamefont{R.}~\\bibnamefont{Fujita}},\n  \\bibinfo{author}{\\bibfnamefont{E.}~\\bibnamefont{Racine}}, \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{H.}~\\bibnamefont{Tagoshi}},\n  \\bibinfo{journal}{\\prd} \\textbf{\\bibinfo{volume}{83}},\n  \\bibinfo{pages}{064003} (\\bibinfo{year}{2011}{\\natexlab{b}}). %\\eprint{1006.0431}.\n\n\\bibitem[{\\citenamefont{Tulczyjew}(1959)}]{Tulczyjew1959}\n\\bibinfo{author}{\\bibfnamefont{W.}~\\bibnamefont{Tulczyjew}},\n  \\bibinfo{journal}{Acta Phys. Polon.} \\textbf{\\bibinfo{volume}{18}},\n  \\bibinfo{pages}{393} (\\bibinfo{year}{1959}).\n\n\\bibitem[{\\citenamefont{Barker and O'Connell}(1979)}]{BOC79}\n\\bibinfo{author}{\\bibfnamefont{B.~M.} \\bibnamefont{Barker}} \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{R.~F.} \\bibnamefont{O'Connell}},\n  \\bibinfo{journal}{Gen. Relativ. Gravit.} \\textbf{\\bibinfo{volume}{11}},\n  \\bibinfo{pages}{149} (\\bibinfo{year}{1979}).\n\n\\bibitem[{\\citenamefont{Porto}(2006)}]{Porto:2005ac}\n\\bibinfo{author}{\\bibfnamefont{R.~A.} \\bibnamefont{Porto}},\n  \\bibinfo{journal}{\\prd} \\textbf{\\bibinfo{volume}{73}},\n  \\bibinfo{pages}{104031} (\\bibinfo{year}{2006}).%, \\eprint{gr-qc/0511061}.\n\n\\bibitem[{\\citenamefont{Damour and Esposito-Far{\\`e}se}(1998)}]{DE98a}\n\\bibinfo{author}{\\bibfnamefont{T.}~\\bibnamefont{Damour}} \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{G.}~\\bibnamefont{Esposito-Far{\\`e}se}},\n  \\bibinfo{journal}{Phys.Rev.D} \\textbf{\\bibinfo{volume}{58}},\n  \\bibinfo{pages}{042001} (\\bibinfo{year}{1998}).%, \\eprint{gr-qc/9803031}.\n\n\\bibitem[{\\citenamefont{{Laarakkers} and {Poisson}}(1999)}]{Laarakkers99}\n\\bibinfo{author}{\\bibfnamefont{W.~G.} \\bibnamefont{{Laarakkers}}}\n  \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{E.}~\\bibnamefont{{Poisson}}},\n  \\bibinfo{journal}{\\apj} \\textbf{\\bibinfo{volume}{512}}, \\bibinfo{pages}{282}\n  (\\bibinfo{year}{1999}).%, \\eprint{arXiv:gr-qc/9709033}.\n\n\\bibitem[{\\citenamefont{Hanson and Regge}(1974)}]{HR74}\n\\bibinfo{author}{\\bibfnamefont{A.~J.} \\bibnamefont{Hanson}} \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{T.}~\\bibnamefont{Regge}},\n  \\bibinfo{journal}{Ann. Phys. (N.Y.)} \\textbf{\\bibinfo{volume}{87}},\n  \\bibinfo{pages}{498} (\\bibinfo{year}{1974}).\n\n\\bibitem[{\\citenamefont{Papapetrou}(1951)}]{Papa51spin}\n\\bibinfo{author}{\\bibfnamefont{A.}~\\bibnamefont{Papapetrou}},\n  \\bibinfo{journal}{Proc. R. Soc. A} \\textbf{\\bibinfo{volume}{209}},\n  \\bibinfo{pages}{248} (\\bibinfo{year}{1951}).\n\n\\bibitem[{\\citenamefont{Dixon}(1964)}]{Dixon1964}\n\\bibinfo{author}{\\bibfnamefont{W.~G.} \\bibnamefont{Dixon}},\n  \\bibinfo{journal}{Nuovo Cimento} \\textbf{\\bibinfo{volume}{34}},\n  \\bibinfo{pages}{317} (\\bibinfo{year}{1964}).\n\n\\bibitem[{\\citenamefont{{Tagoshi} et~al.}(2001)\\citenamefont{{Tagoshi},\n  {Ohashi}, and {Owen}}}]{Tagoshi-Ohashi-Owen:2001}\n\\bibinfo{author}{\\bibfnamefont{H.}~\\bibnamefont{{Tagoshi}}},\n  \\bibinfo{author}{\\bibfnamefont{A.}~\\bibnamefont{{Ohashi}}}, \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{B.~J.} \\bibnamefont{{Owen}}},\n  \\bibinfo{journal}{Phys.\\ Rev.\\ D} \\textbf{\\bibinfo{volume}{63}},\n  \\bibinfo{pages}{044006} (\\bibinfo{year}{2001}).\n\n\\bibitem[{\\citenamefont{Dixon}(1974)}]{Dixon1974}\n\\bibinfo{author}{\\bibfnamefont{W.~G.} \\bibnamefont{Dixon}},\n  \\bibinfo{journal}{Phil. Trans. R. Soc. A} \\textbf{\\bibinfo{volume}{277}},\n  \\bibinfo{pages}{59} (\\bibinfo{year}{1974}).\n\n\\bibitem[{\\citenamefont{Porto et~al.}(2011)\\citenamefont{Porto, Ross, and\n  Rothstein}}]{Porto:2010zg}\n\\bibinfo{author}{\\bibfnamefont{R.~A.} \\bibnamefont{Porto}},\n  \\bibinfo{author}{\\bibfnamefont{A.}~\\bibnamefont{Ross}}, \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{I.~Z.} \\bibnamefont{Rothstein}},\n  \\bibinfo{journal}{J. Cosmol. Astropart. Phys.} \\textbf{\\bibinfo{volume}{1103}}, \\bibinfo{pages}{009}\n  (\\bibinfo{year}{2011}).%, \\eprint{1007.1312}.\n\n\\bibitem[{\\citenamefont{Blanchet}(1998)}]{Blanchet98}\n\\bibinfo{author}{\\bibfnamefont{L.}~\\bibnamefont{Blanchet}},\n  \\bibinfo{journal}{Classical Quantum Gravity} \\textbf{\\bibinfo{volume}{15}},\n  \\bibinfo{pages}{1971} (\\bibinfo{year}{1998}).\n\n\\bibitem[{\\citenamefont{Racine et~al.}(2009)\\citenamefont{Racine, Buonanno, and\n  Kidder}}]{Racine2008}\n\\bibinfo{author}{\\bibfnamefont{E.}~\\bibnamefont{Racine}},\n  \\bibinfo{author}{\\bibfnamefont{A.}~\\bibnamefont{Buonanno}}, \\bibnamefont{and}\n  \\bibinfo{author}{\\bibfnamefont{L.~E.} \\bibnamefont{Kidder}},\n  \\bibinfo{journal}{Phys. Rev. D} \\textbf{\\bibinfo{volume}{80}},\n  \\bibinfo{pages}{044010} (\\bibinfo{year}{2009}).\n\n\\bibitem[{\\citenamefont{Racine}(2008)}]{Racine:2008qv}\n\\bibinfo{author}{\\bibfnamefont{E.}~\\bibnamefont{Racine}},\n  \\bibinfo{journal}{\\prd} \\textbf{\\bibinfo{volume}{78}},\n  \\bibinfo{pages}{044021} (\\bibinfo{year}{2008}).\n\n\\end{thebibliography}\n\n\\end{document}\n", "meta": {"hexsha": "636aae5056431d47a750bbf72d43059c3128bdbc", "size": 124398, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Waveforms/source/BFH/BHF.tex", "max_stars_repo_name": "keefemitman/PostNewtonian", "max_stars_repo_head_hexsha": "853d6577cb0002da5eebe1cb55f0c28fbc114324", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2015-03-26T01:04:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T19:26:21.000Z", "max_issues_repo_path": "Waveforms/source/BFH/BHF.tex", "max_issues_repo_name": "keefemitman/PostNewtonian", "max_issues_repo_head_hexsha": "853d6577cb0002da5eebe1cb55f0c28fbc114324", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2015-01-08T23:46:29.000Z", "max_issues_repo_issues_event_max_datetime": "2017-09-20T19:13:51.000Z", "max_forks_repo_path": "Waveforms/source/BFH/BHF.tex", "max_forks_repo_name": "keefemitman/PostNewtonian", "max_forks_repo_head_hexsha": "853d6577cb0002da5eebe1cb55f0c28fbc114324", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-05-13T02:36:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-23T21:36:32.000Z", "avg_line_length": 48.8218210361, "max_line_length": 246, "alphanum_fraction": 0.6603160823, "num_tokens": 47708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.3208484655425162}}
{"text": "% $Id: 4ab38b73d20edef7032a785ba8fc6325fc362bd8 $\n\n\\section{SAT Solving Modulo Tableau and Rewriting Theories}\n\\label{sec:smt}\n\nIn this section, we recall the classic architecture of SMT solvers and we then\nintroduce the tableau and rewriting theories.\n\nCompared to genuine tableau automated theorem provers, like \\princess{} or\n\\zenon{} for example, our approach has the benefit of being versatile since the\ntableau rules are actually integrated as a regular SMT theory. This way, the\ntableau rules can be easily combined with other theories, such as equality logic\nwith uninterpreted functions or arithmetic. The way we integrate the tableau\nrules into the SAT solver (mainly by boxing/unboxing first order formulas) is\nclose to what is done in the \\satallax{} tool~\\cite{CEB12}. The difference\nresides in the fact that we are in a pure first order framework, which has\nsignificant consequences in the management of quantifiers and unification in\nparticular (see Sec.~\\ref{sec:super}).\n\nRegarding the integration of rewriting, automated theorem provers rely on\nseveral solutions (superposition rule for first order provers, triggers for SMT\nsolvers, etc.). But deduction modulo theory~\\cite{DA03} is probably the most\ngeneral approach, where a theory can be partly turned in to a set of rewrite\nrules over both terms and propositions. Several proof search methods have been\nextended to deduction modulo theory, resulting in tools such as \\iproverm{} and\n\\zenm{}. This paper can be seen as a continuation of these previous experiments\nadapted to the framework of SMT solving.\n\n\\subsection{SAT Solving Modulo Theories}\n\nIn this subsection, we recall the classic architecture of SMT\nsolvers~\\cite{BEA06}. We introduce $\\mathcal{T}$ and $\\mathcal{F}$ respectively\nthe sets of first order terms and formulas over the signature\n$\\mathcal{S}=(\\mathcal{S}_\\mathcal{F},\\mathcal{S}_\\mathcal{P})$, where\n$\\mathcal{S}_\\mathcal{F}$ is the set of function symbols, and\n$\\mathcal{S}_\\mathcal{P}$, the set of predicate symbols, such that\n$\\mathcal{S}_\\mathcal{F}\\cap\\mathcal{S}_\\mathcal{P}=\\emptyset$. The set\n$\\mathcal{T}$ is extended with two kinds of terms specific to tableau proof\nsearch, i.e. $\\epsilon{}$-terms (used instead of Skolemization) of the form\n$\\epsilon(x).P(x)$, where $P(x)$ is a formula, and which means some $x$ that\nsatisfies $P(x)$, if it exists, and metavariables (often named free variables in\nthe tableau-related literature) of the form $X_P$, where $P$ is the formula that\nintroduces the metavariable, and which is either $\\forall{}x.Q(x)$ or\n$\\neg\\exists{}x.Q(x)$, with $Q(x)$ a formula.\n\nA boxed formula is of the form $\\lfloor{}P\\rfloor$, where $P$ is a formula. A\nboxed formula is called atom, and a literal is either an atom, or the negation\nof an atom. A literal is such that there is no negation on top of the boxed\nformula (which means that $\\lfloor\\neg{}P\\rfloor=\\neg\\lfloor{}P\\rfloor$, and\n$\\neg\\neg\\lfloor{}P\\rfloor=\\lfloor{}P\\rfloor$). A clause is a disjunction of\nliterals. It should be noted that SAT solving usually reasons over sets of\nclauses composed of first order literals; here, a literal is a first order\nformula (possibly with quantifiers), which requires to box formulas to get a\nregular SAT solving problem where boxed formulas are propositional variables.\n\nAn assignment of the boxed formulas is a partial function that assigns to boxed\nformulas an element of $\\{\\top,\\bot\\}$ (values of the Boolean algebra). Given a\nclause $C$, we say that $C$ is valid and write $\\models{}C$, if $C$ evaluates to\n$\\top$ for every assignment. Given a set of clauses $S$, we say that $S$ is\nvalid and write $\\models{}S$, if each clause of $S$ is valid. Given two sets of\nclauses $S$ and $S'$, we say that $S$ implies $S'$ and write $S\\models{}S'$ if,\nfor every assignment, if each clause of $S$ evaluates to $\\top$ then each clause\nof $S'$ evaluates to $\\top$. If $S$ is a set of literals, then we say that $S$\nis a model of $S'$.\n\nA theory $T$ is a set of formulas over a given signature $\\mathcal{S}$, which\nare called axioms of the theory $T$. A clause $C$ is a tautology in the theory\n$T$, written $\\models_TC$, if the axioms of $T$ imply the formula $C'$, where\n$C'$ is the clause $C$ where all the boxed formulas have been unboxed. A set of\nclauses $S$ is a tautology in the theory $T$ if each clause of $S$ is a\ntautology in $T$. Given two sets of clauses $M$ and $S$, we say that $M$ is a\nmodel of $S$ modulo the theory $T$ and write $M\\models_TS$, if $M$ is a model of\n$S$ and $M$ is a tautology in $T$.\n\nA SAT solver modulo theories is characterized by a set of theories $S_T$ and an\ninternal state of the form $M\\parallel{}S$, where $M$ is an ordered list of\nliterals (if $M=l_1,l2,\\ldots,l_n$ then $l_1<l_2<\\ldots<l_n$) and $S$ a set of\nclauses. Intuitively, $M$ represents the model of $S$, which will be built\nprogressively (initially, we have $M=\\emptyset$) by the application of a set of\nrules over the internal state of the solver. This set of rules is presented in\nFig.~\\ref{fig:smt}. Each time a literal is propagated (rule\n``$\\mathrm{unit~prop}$'') or decided (rule ``$\\mathrm{decide}$''), it is given\nto each theory, which may generate new clauses (rule ``$\\mathrm{learn}$''). If a\nclause is unvalidated by the model, then it is possible to backtrack the\ndecision over a given literal of the model if it exists (rule\n``$\\mathrm{backjump}$''). There are two final states in this transition\nsystem. The first one is ``$\\mathrm{unsat}$'', which means that $S$ is\nunsatisfiable (rule ``$\\mathrm{unsat}$''). The second one is $M\\parallel{}S$,\nwhere $M$ is a model of $S$ and a tautology for every theory in $S_T$. In this\nlast case, if $M$ is not a tautology in a theory $T$, this theory generates a\nset of conflict clauses (rule ``$\\mathrm{learn}$'').\n\n\\begin{figure}[t]\n\\parbox{\\textwidth}\n{\\small\n\\begin{center}\n$\\begin{array}{l@{\\hspace{0.4cm}}l@{\\hspace{0.4cm}}l}\nM\\parallel{}S,C\\lor{}l\\longrightarrow{}M,l\\parallel{}S,C\\lor{}l &\n(\\mathrm{unit~prop}) & \\mbox{if }l\\not\\in{}M\\mbox{ and }M\\models{}\\neg{}C\\\\\\\\\n\nM\\parallel{}S\\longrightarrow{}M,l^\\mathrm{d}\\parallel{}S & (\\mathrm{decide}) &\n\\mbox{if }l\\not\\in{}M\\mbox{, and }l\\in{}S\\mbox{ or }\\neg{}l\\in{}S\\\\\\\\\n\nM\\parallel{}S,C\\longrightarrow\\mathrm{unsat} & (\\mathrm{unsat}) &\n\\mbox{if }M'\\models{}\\neg{}C\\mbox{ s.t. }M'\\subseteq{}M\\\\\n&& \\mbox{and there is no }l^\\mathrm{d}\\leq{}l'\\mbox{ in }M\\\\\n&& \\mbox{for all }l'\\in{}M'\\\\\\\\\n \nM,l^\\mathrm{d},M'\\parallel{}S,C\\longrightarrow{}M,l'\\parallel{}S,C &\n(\\mathrm{backjump}) & \\mbox{if }M,l^\\mathrm{d},M'\\models\\neg{}C\n\\mbox{, and there is}\\\\\n&& \\mbox{some clause }C'\\lor{}l' s.t.:\\\\\n&& l'\\not\\in{}M\\mbox{, and }l'\\in{}S\\mbox{ or }\\neg{}l'\\in{}S\\\\\n&& \\mbox{or }l'\\in{}M,l^\\mathrm{d},M'\\mbox{ or }\n\\neg{}l'\\in{}M,l^\\mathrm{d},M',\\\\\n&& \\mbox{and }S,C\\models{}C'\\lor{}l'\\mbox{, and }M\\models\\neg{}C'\\\\\\\\\n\nM\\parallel{}S\\longrightarrow{}M\\parallel{}S,S'\n& (\\mathrm{learn}) & \\models_TS'\\mbox{, where }T\\mbox{ is a theory}\n\\end{array}$\n\\end{center}}\n\\caption{Rules of SAT Solving Modulo Theory}\n\\label{fig:smt}\n\\end{figure}\n\n\\subsection{The Tableau Theory}\n\nIn the SAT solver previously described, the tableau proof search method is\nintegrated as a regular theory. When a literal is propagated or decided, we\ngenerate a set of clauses corresponding to the application of a tableau rule\nover the logical connective at root of the formula in the box of the\nliteral. More precisely, for a literal $l$, we generate the set of clauses\n$\\llbracket{}l\\rrbracket$, where the function $\\llbracket\\cdot\\rrbracket$ is\ndescribed by the rules of Fig.~\\ref{fig:tabth}. When a literal is propagated or\ndecided, we use all the rules of Fig.~\\ref{fig:tabth} except the instantiation\n$\\gamma$-rules (rules $\\gamma_{\\forall\\mathrm{inst}}$ and\n$\\gamma_{\\neg\\exists\\mathrm{inst}}$). It should be noted that we use the same\nnames for the rules than in tableau calculus ($\\alpha$-rules, $\\beta$-rules,\netc.), but there is no precedence between rules and therefore no priority in the\napplication of the rules contrary to the tableau proof search method (where\n$\\alpha$ rules are applied before $\\beta$-rules, and so on).\n\nWhen the SAT solver reaches a state $M\\parallel{}S$, where $M$ is a model of\n$S$, we look for a conflict in $M$ between two literals by unification and we\ngenerate the clauses corresponding to the instantiation of the metavariables\nusing the result of the unification. More precisely, if there exist two literals\n$l$ and $\\neg{}l'$ in $M$ such that $l=\\lfloor{}Q\\rfloor$ and\n$l'=\\lfloor{}R\\rfloor$, with $Q$ and $R$ two formulas, then for each\nsubstitution $(X_{\\forall{}x.P(x)}\\mapsto{}t)\\in\\mathrm{mgu}(Q,R)$ (resp.\n$(X_{\\neg\\exists{}x.P(x)}\\mapsto{}t)\\in\\mathrm{mgu}(Q,R)$) such that there is no\n$Y_T\\in\\forall{}x.P(x)$ (resp. $Y_T\\in\\neg\\exists{}x.P(x)$), we can generate the\nclauses $\\llbracket\\lfloor\\forall{}x.P(x)\\rfloor{}\\rrbracket$ \n(resp. $\\llbracket\\neg\\lfloor\\exists{}x.P(x)\\rfloor{}\\rrbracket$) using the rule\n$\\gamma_{\\forall\\mathrm{inst}}$ (resp. $\\gamma_{\\neg\\exists\\mathrm{inst}}$) of\nFig.~\\ref{fig:tabth}.\n\n\\begin{figure}[t]\n\\parbox{\\textwidth}\n{\\small\n\\underline{Analytic Rules}\n\\begin{center}\n$\\begin{array}{lll@{\\hspace{0.5cm}}l}\n\\llbracket\\lfloor{}P\\land{}Q\\rfloor{}\\rrbracket & = &\n\\neg\\lfloor{}P\\land{}Q\\rfloor\\lor\\lfloor{}P\\rfloor,\n\\neg\\lfloor{}P\\land{}Q\\rfloor\\lor\\lfloor{}Q\\rfloor & (\\alpha_\\land)\\\\\\\\\n\n\\llbracket\\neg\\lfloor{}P\\land{}Q\\rfloor{}\\rrbracket & = &\n\\lfloor{}P\\land{}Q\\rfloor\\lor\\neg\\lfloor{}P\\rfloor\\lor\\neg\\lfloor{}Q\\rfloor &\n(\\beta_{\\neg\\land})\\\\\\\\\n\n\\llbracket{}\\lfloor{}P\\lor{}Q\\rfloor{}\\rrbracket & = &\n\\neg\\lfloor{}P\\lor{}Q\\rfloor\\lor\\lfloor{}P\\rfloor\\lor\\lfloor{}Q\\rfloor &\n(\\beta_\\lor)\\\\\\\\\n\n\\llbracket\\neg\\lfloor{}P\\lor{}Q\\rfloor{}\\rrbracket & = &\n\\lfloor{}P\\lor{}Q\\rfloor\\lor\\neg\\lfloor{}P\\rfloor,\n\\lfloor{}P\\lor{}Q\\rfloor\\lor\\neg\\lfloor{}Q\\rfloor &\n(\\alpha_{\\neg\\lor})\\\\\\\\\n\n\\llbracket{}\\lfloor{}P\\Rightarrow{}Q\\rfloor{}\\rrbracket & = &\n\\neg\\lfloor{}P\\Rightarrow{}Q\\rfloor\\lor\\neg\\lfloor{}P\\rfloor\\lor\n\\lfloor{}Q\\rfloor & (\\beta_\\Rightarrow)\\\\\\\\\n\n\\llbracket\\neg\\lfloor{}P\\Rightarrow{}Q\\rfloor{}\\rrbracket & = &\n\\lfloor{}P\\Rightarrow{}Q\\rfloor\\lor\\lfloor{}P\\rfloor,\n\\lfloor{}P\\Rightarrow{}Q\\rfloor\\lor\\neg\\lfloor{}Q\\rfloor &\n(\\alpha_{\\neg\\Rightarrow})\\\\\\\\\n\n\\llbracket{}\\lfloor{}P\\Leftrightarrow{}Q\\rfloor{}\\rrbracket & = &\n\\neg\\lfloor{}P\\Leftrightarrow{}Q\\rfloor\\lor\\lfloor{}P\\Rightarrow{}Q\\rfloor,\n\\neg\\lfloor{}P\\Leftrightarrow{}Q\\rfloor\\lor\\lfloor{}Q\\Rightarrow{}P\\rfloor &\n(\\beta_\\Rightarrow)\\\\\\\\\n\n\\llbracket{}\\neg\\lfloor{}P\\Leftrightarrow{}Q\\rfloor{}\\rrbracket &\n= &\n\\lfloor{}P\\Leftrightarrow{}Q\\rfloor\\lor\\neg\\lfloor{}P\\Rightarrow{}Q\\rfloor\\lor\n\\neg\\lfloor{}Q\\Rightarrow{}P\\rfloor & (\\beta_{\\neg\\Rightarrow})\n\\end{array}$\n\\end{center}\n\n\\underline{$\\delta$-Rules}\n\\begin{center}\n$\\begin{array}{lll@{\\hspace{0.5cm}}l}\n\\llbracket\\lfloor\\exists{}x.P(x)\\rfloor{}\\rrbracket & = &\n\\neg{}\\lfloor\\exists{}x.P(x)\\rfloor\\lor\\lfloor{}P(\\epsilon(x).P(x))\\rfloor &\n(\\delta_\\exists)\\\\\\\\\n\n\\llbracket\\neg\\lfloor\\forall{}x.P(x)\\rfloor{}\\rrbracket & = &\n\\lfloor\\forall{}x.P(x)\\rfloor\\lor\\neg\\lfloor{}P(\\epsilon(x).\\neg{}P(x))\\rfloor &\n(\\delta_{\\neg\\forall})\n\\end{array}$\n\\end{center}\n\n\\underline{$\\gamma$-Rules}\n\\begin{center}\n$\\begin{array}{lll@{\\hspace{0.5cm}}l}\n\\llbracket\\lfloor\\forall{}x.P(x)\\rfloor{}\\rrbracket & = &\n\\neg\\lfloor\\forall{}x.P(x)\\rfloor\\lor\\lfloor{}P(X_{\\forall{}x.P(x)})\\rfloor &\n(\\gamma_{\\forall{}M})\\\\\\\\\n\n\\llbracket\\neg\\lfloor\\exists{}x.P(x)\\rfloor{}\\rrbracket & = &\n\\lfloor\\exists{}x.P(x)\\rfloor\\lor\n\\neg\\lfloor{}P(X_{\\neg\\exists{}x.P(x)})\\rfloor &\n(\\gamma_{\\neg\\exists{}M})\\\\\\\\\n\n\\llbracket\\lfloor\\forall{}x.P(x)\\rfloor{}\\rrbracket & = &\n\\neg\\lfloor\\forall{}x.P(x)\\rfloor\\lor\\lfloor{}P(t)\\rfloor &\n(\\gamma_{\\forall\\mathrm{inst}})\\\\\\\\\n\n\\llbracket\\neg\\lfloor\\exists{}x.P(x)\\rfloor{}\\rrbracket & = &\n\\lfloor\\exists{}x.P(x)\\rfloor\\lor\\neg\\lfloor{}P(t)\\rfloor &\n(\\gamma_{\\neg\\exists\\mathrm{inst}})\n\\end{array}$\n\\end{center}}\n\\caption{Rules of Tableau Theory}\n\\label{fig:tabth}\n\\end{figure}\n\nTo show how this theory works, let us prove that\n$\\exists{}x.P(x)\\Rightarrow{}P(a)\\land{}P(b)$, where $P$ is a predicate symbol\nand $a,b$ two constants. The SAT solver is initiated with the state\n$\\emptyset\\parallel\n\\neg\\lfloor\\exists{}x.P(x)\\Rightarrow{}P(a)\\land{}P(b)\\rfloor$, and the proof is\ndescribed in Fig.~\\ref{fig:tab}, where $X$ is a shortcut for\n$X_{\\neg\\exists{}x.P(x)\\Rightarrow{}P(a)\\land{}P(b)}$. It should be noted that\nto do this proof in sequent calculus, a right contraction is necessary to\ninstantiate the formula twice (with $a$ and $b$). In Fig.~\\ref{fig:tab}, it is\ndone by propagating the literal $\\lfloor{}P(X)\\rfloor{}$, which can provide as\nmany instantiations (by unification) as necessary.\n\n\\begin{figure}[t!]\n\\parbox{\\textwidth}\n{\\small\n\\begin{center}\n$\\begin{array}{lcl}\n\\emptyset\\parallel\\neg{}A & \\longrightarrow & (\\mathrm{unit~prop})\\\\\n\n\\boldsymbol{\\neg{}A}\\parallel{}\\neg{}A & \\longrightarrow & (\\mathrm{learn})\\\\\n\n\\neg{}A\\parallel\\neg{}A,\\boldsymbol{A\\lor\\neg{}B} & \\longrightarrow &\n(\\mathrm{unit~prop})\\\\\n\n\\neg{}A,\\boldsymbol{\\neg{}B}\\parallel\\neg{}A,A\\lor\\neg{}B & \\longrightarrow &\n(\\mathrm{learn})\\\\\n\n\\neg{}A,\\neg{}B\\parallel\\neg{}A,A\\lor\\neg{}B,\\boldsymbol{B\\lor{}C},\n\\boldsymbol{B\\lor\\neg{}D} & \\longrightarrow & (\\mathrm{unit~prop})\\times{}2\\\\\n\n\\neg{}A,\\neg{}B,\\boldsymbol{C},\\boldsymbol{\\neg{}D}\\parallel\\neg{}A,\nA\\lor\\neg{}B,B\\lor{}C,B\\lor\\neg{}D & \\longrightarrow & (\\mathrm{learn})\\\\\n\n\\neg{}A,\\neg{}B,C,\\neg{}D\\parallel\\neg{}A,A\\lor\\neg{}B,B\\lor{}C,B\\lor\\neg{}D,\\\\\n~~~~\\boldsymbol{D\\lor\\neg{}E\\lor\\neg{}F} & \\longrightarrow & (\\mathrm{decide})\\\\\n\n\\neg{}A,\\neg{}B,C,\\neg{}D,\\boldsymbol{\\neg{}E^d}\\parallel\n\\neg{}A,A\\lor\\neg{}B,B\\lor{}C, & \\longrightarrow &\n(\\mathrm{learn})\\\\\n~~~~B\\lor\\neg{}D,D\\lor\\neg{}E\\lor\\neg{}F && \\{X\\mapsto{}a\\}=\\mathrm{mgu}(C,E)\\\\\n\n\\neg{}A,\\neg{}B,C,\\neg{}D,\\neg{}E^d\\parallel\n\\neg{}A,A\\lor\\neg{}B,B\\lor{}C,\\\\\n~~~~B\\lor\\neg{}D,D\\lor\\neg{}E\\lor\\neg{}F,\\boldsymbol{A\\lor\\neg{}G} &\n\\longrightarrow & (\\mathrm{unit~prop})\\\\\n\n\\neg{}A,\\neg{}B,C,\\neg{}D,\\neg{}E^d,\\boldsymbol{\\neg{}G}\\parallel\n\\neg{}A,A\\lor\\neg{}B,B\\lor{}C,\\\\\n~~~~B\\lor\\neg{}D,D\\lor\\neg{}E\\lor\\neg{}F,A\\lor\\neg{}G & \\longrightarrow &\n(\\mathrm{learn})\\\\\n\n\\neg{}A,\\neg{}B,C,\\neg{}D,\\neg{}E^d,\\neg{}G\\parallel\n\\neg{}A,A\\lor\\neg{}B,B\\lor{}C,\\\\\n~~~~B\\lor\\neg{}D,D\\lor\\neg{}E\\lor\\neg{}F,A\\lor\\neg{}G,\\boldsymbol{G\\lor{}E},\n\\boldsymbol{G\\lor\\neg{}D} & \\longrightarrow & (\\mathrm{backjump})\\\\\n\n\\neg{}A,\\neg{}B,C,\\neg{}D,\\boldsymbol{E}\\parallel\n\\neg{}A,A\\lor\\neg{}B,B\\lor{}C,\\\\\n~~~~B\\lor\\neg{}D,D\\lor\\neg{}E\\lor\\neg{}F,A\\lor\\neg{}G,G\\lor{}E,G\\lor\\neg{}D &\n\\longrightarrow & (\\mathrm{unit~prop})\\times{}2\\\\\n\n\\neg{}A,\\neg{}B,C,\\neg{}D,E,\\boldsymbol{\\neg{}F},\\boldsymbol{\\neg{}G}\\parallel\n\\neg{}A,A\\lor\\neg{}B,B\\lor{}C, & \\longrightarrow & (\\mathrm{learn})\\\\\n~~~~B\\lor\\neg{}D,D\\lor\\neg{}E\\lor\\neg{}F,A\\lor\\neg{}G,G\\lor{}E,G\\lor\\neg{}D &&\n\\{X\\mapsto{}b\\}=\\mathrm{mgu}(C,F)\\\\\n\n\\neg{}A,\\neg{}B,C,\\neg{}D,E,\\neg{}F,\\neg{}G\\parallel\n\\neg{}A,A\\lor\\neg{}B,B\\lor{}C,\\\\\n~~~~B\\lor\\neg{}D,D\\lor\\neg{}E\\lor\\neg{}F,A\\lor\\neg{}G,G\\lor{}E,G\\lor\\neg{}D\\\\\n~~~~\\boldsymbol{A\\lor\\neg{}H} & \\longrightarrow & (\\mathrm{unit~prop})\\\\\n\n\\neg{}A,\\neg{}B,C,\\neg{}D,E,\\neg{}F,\\neg{}G,\\boldsymbol{\\neg{}H}\\parallel\n\\neg{}A,A\\lor\\neg{}B,B\\lor{}C,\\\\\n~~~~B\\lor\\neg{}D,D\\lor\\neg{}E\\lor\\neg{}F,A\\lor\\neg{}G,G\\lor{}E,G\\lor\\neg{}D\\\\\n~~~~A\\lor\\neg{}H & \\longrightarrow & (\\mathrm{learn})\\\\\n\n\\neg{}A,\\neg{}B,C,\\neg{}D,E,\\neg{}F,\\neg{}G,\\neg{}H\\parallel\n\\neg{}A,A\\lor\\neg{}B,B\\lor{}C,\\\\\n~~~~B\\lor\\neg{}D,D\\lor\\neg{}E\\lor\\neg{}F,A\\lor\\neg{}G,G\\lor{}E,G\\lor\\neg{}D\\\\\n~~~~A\\lor\\neg{}H,\\boldsymbol{H\\lor{}F},\\boldsymbol{H\\lor{}\\neg{}D} &\n\\longrightarrow & (\\mathrm{unsat})\\\\\n\n\\mathrm{unsat}\n\\end{array}$\n\\end{center}\n\\begin{flushleft}\n$\\begin{array}{l}\n\\mbox{where:}\\\\\n\\begin{array}{ll}\n~~~~A\\equiv\\lfloor\\exists{}x.P(x)\\Rightarrow{}P(a)\\land{}P(b)\\rfloor &\n~~~~B\\equiv\\lfloor{}P(X)\\Rightarrow{}P(a)\\land{}P(b)\\rfloor\\\\\n~~~~C\\equiv\\lfloor{}P(X)\\rfloor{} &\n~~~~D\\equiv\\lfloor{}P(a)\\land{}P(b)\\rfloor{}\\\\\n~~~~E\\equiv\\lfloor{}P(a)\\rfloor &\n~~~~F\\equiv\\lfloor{}P(b)\\rfloor\\\\\n~~~~G\\equiv{}\\lfloor{}P(a)\\Rightarrow{}P(a)\\land{}P(b)\\rfloor &\n~~~~H\\equiv{}\\lfloor{}P(b)\\Rightarrow{}P(a)\\land{}P(b)\\rfloor\n\\end{array}\n\\end{array}$\n\\end{flushleft}}\n\\caption{Example of Proof Using the Tableau Theory}\n\\label{fig:tab}\n\\end{figure}\n\n\\subsection{The Rewriting Theory}\n\\label{sec:rew}\n\nA rewriting theory allows us to introduce a computational behavior to the SAT\nsolver. We aim to integrate rewriting in the broadest sense of the term as\nproposed by deduction modulo theory. Deduction modulo theory~\\cite{DA03} focuses\non the computational part of a theory, where axioms are transformed into rewrite\nrules, which induces a congruence over propositions, and where reasoning is\nperformed modulo this congruence. In deduction modulo theory, this congruence is\nthen induced by a set of rewrite rules over both terms and propositions.\n\nIn the following, we borrow some of the notations and definitions\nof~\\cite{DA03}. We call $\\mathrm{FV}$ the function that returns the set of\nfree variables of a term or a formula. A term rewrite rule is a pair of terms\ndenoted by $l\\rew{}r$, where $\\mathrm{FV}(r)\\subseteq\\mathrm{FV}(l)$. A\nproposition rewrite rule is a pair of propositions denoted by $l\\rew{}r$, where\n$l$ is an atomic proposition and $r$ is an arbitrary proposition, and where\n$\\mathrm{FV}(r)\\subseteq\\mathrm{FV}(l)$. A class rewrite system is a pair of\nrewrite systems, denoted by $\\mathcal{RE}$, consisting of $\\mathcal{R}$, a set\nof proposition rewrite rules, and $\\mathcal{E}$, a set of term rewrite rules.\n\nGiven a class rewrite system $\\mathcal{RE}$, the relations $=_\\mathcal{E}$ and\n$=_\\mathcal{RE}$ are the congruences generated respectively by the sets\n$\\mathcal{E}$ and $\\mathcal{R}\\cup\\mathcal{E}$. In the following, we use the\nstandard concepts of subterm and term replacement: given an occurrence $\\omega$\nin a proposition $P$, we write $P_{|\\omega}$ for the term or proposition at\n$\\omega$, and $P[t]_\\omega$ for the proposition obtained by replacing\n$P_{|\\omega}$ by $t$ in $P$ at $\\omega$. Given a class rewrite system\n$\\mathcal{RE}$, the proposition $P$ $\\mathcal{RE}$-rewrites to $P'$, denoted by\n$P\\rew_\\mathcal{RE}P'$, if $P=_\\mathcal{E}Q$, $Q_{|\\omega}=\\sigma(l)$, and\n$P'=_\\mathcal{E}Q[\\sigma(r)]_\\omega$, for some rule $l\\rew{}r\\in\\mathcal{R}$,\nsome proposition $Q$, some occurrence $\\omega$ in $Q$, and some substitution\n$\\sigma$.\n\nThe relation $=_\\mathcal{RE}$ is not decidable in general, but there are some\ncases where this relation is decidable depending on the class rewrite system\n$\\mathcal{RE}$ and the rewrite relation $\\rew_\\mathcal{RE}$. In particular, if\nthe rewrite relation $\\rew_\\mathcal{RE}$ is confluent and (weakly) terminating,\nthen the relation $=_\\mathcal{RE}$ is decidable.\n\nThe rewriting theory is integrated into the SAT solver in a similar way than for\nthe tableau theory. When a literal is propagated or decided, we generate a\nclause introducing a new formula that is congruent to the formula in the box of\nthe literal. More precisely, given a literal $\\lfloor{}P\\rfloor$, where $P$ is a\nformula, and a formula $P'$ such that $P=_\\mathcal{RE}P'$, we generate the\nfollowing clause:\n\n$$\\left(\\bigvee_{(l,r)\\in\\mathcal{R}}\n\\neg\\lfloor\\forall{}\\vec{x}.l\\Leftrightarrow{}r\\rfloor\\right)\\lor\n\\left(\\bigvee_{(l,r)\\in\\mathcal{E}}\\neg\\lfloor\\forall{}\\vec{x}.l=r\\rfloor\\right)\\lor\n\\lfloor{}P\\Leftrightarrow{}P'\\rfloor$$\n\nwhere $\\vec{x}=\\mathrm{FV}(l)\\cup\\mathrm{FV}(r)$.\n\nIt should be noted that in usual SMT solvers, rewriting can be emulated by means\nof triggers that are actually the left-hand side members of the class rewrite\nsystem $\\mathcal{RE}$ introduced above. But in our rewriting theory, we can\ngenerate the formula where rewritings have been done, while triggers can just\ngenerate bindings, i.e. instances of the rewrite rules, which are used later to\nrelate the initial and rewritten formulas. Moreover, in our case, we can perform\nseveral rewritings at once, while a trigger can only emulate one rewriting at a\ntime.\n\nLet us illustrate the use of the rewriting theory by means of an example in set\ntheory. Let us prove that\n$(\\forall{}s,t.s\\subseteq{}t\\Leftrightarrow{}\\forall{}x.x\\in{}s\\Rightarrow{}\nx\\in{}t)\\Rightarrow{}a\\subseteq{}a$, where $a$ is a constant. The proof is given\nby Fig.~\\ref{fig:rew}, where the rules ``$\\mathrm{learn~tab}$'' and\n``$\\mathrm{learn~rew}$'' represent the rule ``$\\mathrm{learn}$'' using\nrespectively the tableau and rewriting theories.\n\n\\begin{figure}[t!]\n\\parbox{\\textwidth}\n{\\small\n\\begin{center}\n$\\begin{array}{lcl}\n\\emptyset\\parallel\n\\neg{}A & \\longrightarrow & (\\mathrm{unit~prop})\\\\\n\n\\boldsymbol{\\neg{}A}\\parallel{}\\neg{}A & \\longrightarrow &\n(\\mathrm{learn~tab})\\\\\n\n\\neg{}A\\parallel\n\\neg{}A,\\boldsymbol{A\\lor{}B},\\boldsymbol{A\\lor\\neg{}C} & \\longrightarrow &\n(\\mathrm{unit~prop})\\times{}2\\\\\n\n\\neg{}A,\\boldsymbol{B},\\boldsymbol{\\neg{}C}\\parallel\n\\neg{}A,A\\lor{}B,A\\lor\\neg{}C & \\longrightarrow & (\\mathrm{learn~rew})\\\\\n\n\\neg{}A,B,\\neg{}C\\parallel\\neg{}A,A\\lor{}B,A\\lor\\neg{}C,\n\\boldsymbol{\\neg{}B\\lor{}D} & \\longrightarrow & (\\mathrm{unit~prop})\\\\\n\n\\neg{}A,B,\\neg{}C,\\boldsymbol{D}\\parallel\\neg{}A,A\\lor{}B,A\\lor\\neg{}C,\n\\neg{}B\\lor{}D & \\longrightarrow & (\\mathrm{learn~tab})\\\\\n\n\\neg{}A,B,\\neg{}C,D\\parallel\\neg{}A,A\\lor{}B,A\\lor\\neg{}C,\\neg{}B\\lor{}D,\n\\boldsymbol{\\neg{}D\\lor{}E},\\boldsymbol{\\neg{}D\\lor{}F} & \\longrightarrow &\n(\\mathrm{unit~prop})\\times{}2\\\\\n\n\\neg{}A,B,\\neg{}C,D,\\boldsymbol{E},\\boldsymbol{F}\\parallel\n\\neg{}A,A\\lor{}B,A\\lor\\neg{}C,\\neg{}B\\lor{}D,\\neg{}D\\lor{}E,\\\\\n~~~~\\neg{}D\\lor{}F & \\longrightarrow & (\\mathrm{learn~tab})\\\\\n\n\\neg{}A,B,\\neg{}C,D,E,F\\parallel\\neg{}A,A\\lor{}B,A\\lor\\neg{}C,\\neg{}B\\lor{}D,\n\\neg{}D\\lor{}E\\\\\n~~~~\\neg{}D\\lor{}F,\\boldsymbol{\\neg{}F\\lor\\neg{}G\\lor{}C} & \\longrightarrow &\n(\\mathrm{unit~prop})\\\\\n\n\\neg{}A,B,\\neg{}C,D,E,F,\\boldsymbol{\\neg{}G}\\parallel\\neg{}A,A\\lor{}B,\nA\\lor\\neg{}C,\\neg{}B\\lor{}D,\\neg{}D\\lor{}E\\\\\n~~~~\\neg{}D\\lor{}F,\\neg{}F\\lor\\neg{}G\\lor{}C & \\longrightarrow &\n(\\mathrm{learn~tab})\\\\\n\n\\neg{}A,B,\\neg{}C,D,E,F,\\neg{}G\\parallel\\neg{}A,A\\lor{}B,A\\lor\\neg{}C,\n\\neg{}B\\lor{}D,\\neg{}D\\lor{}E\\\\\n~~~~\\neg{}D\\lor{}F,\\neg{}F\\lor\\neg{}G\\lor{}C,\\boldsymbol{G\\lor\\neg{}H} &\n\\longrightarrow & (\\mathrm{unit~prop})\\\\\n\n\\neg{}A,B,\\neg{}C,D,E,F,\\neg{}G,\\boldsymbol{\\neg{}H}\\parallel\\neg{}A,A\\lor{}B,\nA\\lor\\neg{}C,\\neg{}B\\lor{}D\\\\\n~~~~\\neg{}D\\lor{}E,\\neg{}D\\lor{}F,\\neg{}F\\lor\\neg{}G\\lor{}C,\nG\\lor\\neg{}H & \\longrightarrow & (\\mathrm{learn~tab})\\\\\n\n\\neg{}A,B,\\neg{}C,D,E,F,\\neg{}G,\\neg{}H\\parallel\\neg{}A,A\\lor{}B,A\\lor\\neg{}C,\n\\neg{}B\\lor{}D\\\\\n~~~~\\neg{}D\\lor{}E,\\neg{}D\\lor{}F,\\neg{}F\\lor\\neg{}G\\lor{}C,\nG\\lor\\neg{}H,\\boldsymbol{H\\lor{}I},\\boldsymbol{H\\lor\\neg{}I} & \\longrightarrow &\n(\\mathrm{unit~prop})\\\\\n\n\\neg{}A,B,\\neg{}C,D,E,F,\\neg{}G,\\neg{}H,\\boldsymbol{I}\\parallel\\neg{}A,A\\lor{}B,\nA\\lor\\neg{}C,\\neg{}B\\lor{}D\\\\\n~~~~\\neg{}D\\lor{}E,\\neg{}D\\lor{}F,\\neg{}F\\lor\\neg{}G\\lor{}C,\nG\\lor\\neg{}H,H\\lor{}I,H\\lor\\neg{}I & \\longrightarrow & (\\mathrm{unsat})\\\\\n\n\\mathrm{unsat}\n\\end{array}$\n\\end{center}\n\\begin{flushleft}\n$\\begin{array}{l}\n\\mbox{where:}\\\\\n\\begin{array}{ll}\n\\multicolumn{2}{l}{\n~~~~A\\equiv\\lfloor(\\forall{}s,t.s\\subseteq{}t\\Leftrightarrow{}\n\\forall{}x.x\\in{}s\\Rightarrow{}x\\in{}t)\\Rightarrow{}a\\subseteq{}a\\rfloor}\\\\\n~~~~B\\equiv\\lfloor\\forall{}s,t.s\\subseteq{}t\\Leftrightarrow{}\n\\forall{}x.x\\in{}s\\Rightarrow{}x\\in{}t\\rfloor &\n~~~~C\\equiv\\lfloor{}a\\subseteq{}a\\rfloor\\\\\n~~~~D\\equiv\\lfloor{}a\\subseteq{}a\\Leftrightarrow\n\\forall{}x.x\\in{}a\\Rightarrow{}x\\in{}a\\rfloor &\n~~~~E\\equiv\\lfloor{}a\\subseteq{}a\\Rightarrow\n\\forall{}.x\\in{}a\\Rightarrow{}x\\in{}a\\rfloor\\\\\n~~~~F\\equiv\\lfloor(\\forall{}.x\\in{}a\\Rightarrow{}x\\in{}a)\n\\Rightarrow{}a\\subseteq{}a\\rfloor &\n~~~~G\\equiv\\lfloor\\forall{}.x\\in{}a\\Rightarrow{}x\\in{}a\\rfloor\\\\\n~~~~H\\equiv\\lfloor\\epsilon_x\\in{}a\\Rightarrow\\epsilon_x\\in{}a\\rfloor &\n~~~~I\\equiv\\lfloor\\epsilon_x\\in{}a\\rfloor\n\\end{array}\\\\\\\\\n\\mbox{with: }\\epsilon_x=\\epsilon(x).\\neg(x\\in{}a\\Rightarrow{}x\\in{}a)\n\\end{array}$\n\\end{flushleft}}\n\\caption{Example of Proof Using the Rewriting Theory}\n\\label{fig:rew}\n\\end{figure}\n", "meta": {"hexsha": "4ab38b73d20edef7032a785ba8fc6325fc362bd8", "size": 24021, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "papers/ijcar18/tabrew.tex", "max_stars_repo_name": "Gbury/archsat", "max_stars_repo_head_hexsha": "322fbefa4a58023ddafb3fa1a51f8199c25cde3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2018-08-19T14:41:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T14:07:03.000Z", "max_issues_repo_path": "papers/ijcar18/tabrew.tex", "max_issues_repo_name": "Gbury/archsat", "max_issues_repo_head_hexsha": "322fbefa4a58023ddafb3fa1a51f8199c25cde3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-04-10T02:05:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T15:41:36.000Z", "max_forks_repo_path": "papers/ijcar18/tabrew.tex", "max_forks_repo_name": "Gbury/archsat", "max_forks_repo_head_hexsha": "322fbefa4a58023ddafb3fa1a51f8199c25cde3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-02-12T14:25:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-14T11:12:52.000Z", "avg_line_length": 47.4723320158, "max_line_length": 84, "alphanum_fraction": 0.6904375338, "num_tokens": 8414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.320814258527653}}
{"text": "\\section{Notations}\n\\begin{table}[H]\n  \\centering\n  \\caption{Important Notations.}\n  \\label{Notation}\n  \\begin{tabular*}{\\hsize}{@{\\extracolsep{\\fill}}clc}\n    \\toprule\n    Symbol & Description & Unit \\\\\n    \\midrule\n    $S_{cylinder}$ & side surface area of cylinder & $m^2$ \\\\\n    $\\bm{E}$ & electric field intensity on the surface of uniformly charged cylinder & $N/C$ \\\\\n    $\\Phi$ & electric flux & $N\\cdot m^2/C$ \\\\\n    $DR$ & decomposition rate & Unitless \\\\\n    $\\alpha$ & fungi linear density & Unitless \\\\\n    $\\varepsilon_{DR}$ & environmental decomposition constant & Unitless \\\\\n    $ACT$ & fungal activity factor & Unitless \\\\\n    $\\beta$ & fungi areal density & Unitless \\\\\n    $HER$ & hyphal extension rate & $mm/day$ \\\\\n    $RMT$ & relative moisture tolerance & Unitless \\\\\n    $R^2$ & sample correlation coefficient & Unitless \\\\\n    $N(t)$ & current population size & Unitless \\\\\n    $RGB$ & relative growth blocking index & Unitless \\\\\n    $X$ & time series data & Unitless \\\\\n    \\bottomrule\n  \\end{tabular*}\n\\end{table}", "meta": {"hexsha": "5e88cb0ad43f36ccb1b707812a277511373a1e13", "size": 1041, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "3/index.tex", "max_stars_repo_name": "syy11cn/2021-mcm-meritorious-article", "max_stars_repo_head_hexsha": "3eaf143f4319fae681d98134bfc7e699833d8273", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-11-07T14:38:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-11T10:37:34.000Z", "max_issues_repo_path": "3/index.tex", "max_issues_repo_name": "syy11cn/2021-mcm-meritorious-article", "max_issues_repo_head_hexsha": "3eaf143f4319fae681d98134bfc7e699833d8273", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3/index.tex", "max_forks_repo_name": "syy11cn/2021-mcm-meritorious-article", "max_forks_repo_head_hexsha": "3eaf143f4319fae681d98134bfc7e699833d8273", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0384615385, "max_line_length": 95, "alphanum_fraction": 0.6368876081, "num_tokens": 298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.32081425095402993}}
{"text": "\\documentclass{article}\n\\pagestyle{empty}\n\\textwidth155mm\n\\oddsidemargin2.1mm\n\\topmargin-8mm\n\\textheight225mm\n\n\\def\\rgtbox#1#2{\\phantom{#1}\\hbox to0pt{\\hss#2}}\n\\def\\lftbox#1#2{\\hbox to0pt{#2\\hss}\\phantom{#1}}\n\n\\begin{document}\n\n\\subsection*{The Apriori Algorithm for Finding Association Rules}\n\n\\vskip5mm\n\\begin{tabbing}\n00 \\= 00 \\= 00 \\= 00 \\= \\hskip60mm \\= \\kill\n{\\bf function} apriori $(I, T, s_{\\min}, c_{\\min}, k_{\\max})$\n   \\>\\>\\>\\>\\> $(*$ apriori algorithm for association rules $*)$ \\\\\n{\\bf begin} \\\\\n\\> $\\lftbox{C_k}{$k$} := 1$;\n   \\>\\>\\>\\> $(*$ --- find frequent item sets $*)$ \\\\\n\\> $C_k := \\bigcup_{i \\in I} \\{i\\};$\n   \\>\\>\\>\\> $(*$ start with single element sets $*)$ \\\\\n\\> $\\lftbox{C_k}{$F_k$} := \\mbox{prune}(C_k, T, s_{\\min})$;\n   \\>\\>\\>\\> $(*$ and determine the frequent ones $*)$ \\\\\n\\> {\\bf while} $F_k \\neq \\emptyset$\n   {\\bf and}   $k \\le k_{\\max}$ {\\bf do begin}\n   \\>\\>\\>\\>   $(*$ while there are frequent item sets $*)$ \\\\\n\\> \\> $C_{k+1} := \\mbox{candidates}(F_k)$;\n   \\>\\>\\>     $(*$ create item sets with one item more $*)$ \\\\\n\\> \\> $\\lftbox{C_{k+1}}{$F_{k+1}$}\n               := \\mbox{prune}(C_{k+1}, T, s_{\\min})$;\n   \\>\\>\\>     $(*$ and determine the frequent ones $*)$ \\\\\n\\> \\> $\\lftbox{C_{k+1}}{$k$} := k+1$;\n   \\>\\>\\>     $(*$ increment the item counter $*)$ \\\\\n\\> {\\bf end}; \\\\\n\\> $R := \\emptyset$;\n   \\>\\>\\>\\>   $(*$ --- generate association rules $*)$ \\\\\n\\> {\\bf forall} $f \\in \\bigcup_{j=2}^k F_j$ {\\bf do begin}\n   \\>\\>\\>\\>   $(*$ traverse the frequent item sets $*)$ \\\\\n\\> \\> $\\lftbox{H_m}{$m$} := 1$;\n   \\>\\>\\>     $(*$ start with rule heads (consequents) $*)$ \\\\\n\\> \\> $H_m := \\bigcup_{i \\in f} \\{i\\}$;\n   \\>\\>\\>     $(*$ that contain only one item $*)$ \\\\\n\\> \\> {\\bf repeat}\n   \\>\\>\\>     $(*$ traverse rule heads of increasing size $*)$ \\\\\n\\> \\> \\> {\\bf forall} $h \\in H_m$ {\\bf do}\n   \\>\\>       $(*$ traverse the possible rule heads $*)$ \\\\\n\\> \\> \\> \\> {\\bf if} $\\frac{s(f)}{s(f-h)} \\ge c_{\\min}$\n   \\>         $(*$ if the confidence of the rule $*)$ \\\\\n\\> \\> \\> \\> {\\bf then} $\\lftbox{H_m}{$R$}\n                       := R \\cup \\{ [(f-h) \\to h] \\}$;\n   \\>         $(*$ is high enough, add it to the result, $*)$ \\\\\n\\> \\> \\> \\> \\lftbox{\\bf then}{\\bf else} $H_m := H_m - \\{h\\}$;\n   \\>         $(*$ otherwise discard the rule head $*)$ \\\\\n\\> \\> \\> $H_{m+1} := \\mbox{candidates}(H_m)$;\n   \\>\\>       $(*$ create rule heads with one item more $*)$ \\\\\n\\> \\> \\> $\\lftbox{H_{m+1}}{$m$} := m+1$;\n   \\>\\>       $(*$ increment the head item counter $*)$ \\\\\n\\> \\> {\\bf until} $H_m = \\emptyset$ {\\bf or} $m \\ge |f|$;\n   \\>\\>\\>     $(*$ until there are no more rule heads $*)$ \\\\\n\\> {\\bf end};\n   \\>\\>\\>\\>   $(*$ or the antecedent would become empty $*)$ \\\\\n\\> {\\bf return} $R$;\n   \\>\\>\\>\\>   $(*$ return the rules found $*)$ \\\\\n{\\bf end} $(*$ apriori $*)$ \\\\\n\\\\\n{\\bf function} candidates $(F_k)$\n   \\>\\>\\>\\>\\> $(*$ generate candidates with $k+1$ items $*)$\\\\\n{\\bf begin} \\\\\n\\> $C := \\emptyset$;\n   \\>\\>\\>\\>   $(*$ initialize the set of candidates $*)$ \\\\\n\\> {\\bf forall} $f_1, f_2 \\in F_k$\n   \\>\\>\\>\\>   $(*$ traverse all pairs of frequent item sets $*)$ \\\\\n\\> \\lftbox{\\bf forall}{\\bf with} $f_1 = \\{i_1,\\ldots,i_{k-1},i_k\\}$\n   \\>\\>\\>\\>   $(*$ that differ only in one item and $*)$ \\\\\n\\> \\lftbox{\\bf forall}{\\bf and}  $f_2 = \\{i_1,\\ldots,i_{k-1},i_k'\\}$\n   \\>\\>\\>\\>   $(*$ are in a lexicographic order $*)$ \\\\\n\\> \\lftbox{\\bf forall}{\\bf and}  $i_k < i_k'$ {\\bf do begin}\n   \\>\\>\\>\\>   $(*$ (the order is arbitrary, but fixed) $*)$ \\\\\n\\> \\> $f := f_1 \\cup f_2 = \\{i_1,\\ldots,i_{k-1},i_k,i_k'\\}$;\n   \\>\\>\\>     $(*$ the union of these sets has $k+1$ items $*)$ \\\\\n\\> \\> {\\bf if} $\\;\\forall i \\in f:\\; f -\\{i\\} \\in F_k$\n   \\>\\>\\>     $(*$ only if all $k$ element subsets are frequent, $*)$ \\\\\n\\> \\> {\\bf then} $C := C \\cup \\{f\\}$;\n   \\>\\>\\>     $(*$ add the new item set to the candidates $*)$ \\\\\n\\> {\\bf end};\n   \\>\\>\\>\\>   $(*$ (otherwise it cannot be frequent) $*)$ \\\\\n\\> {\\bf return} $C$;\n   \\>\\>\\>\\>   $(*$ return the generated candidates $*)$ \\\\\n{\\bf end} $(*$ candidates $*)$ \\\\\n\\\\\n{\\bf function} prune $(C, T, s_{\\min})$\n   \\>\\>\\>\\>\\> $(*$ prune infrequent candidates $*)$ \\\\\n{\\bf begin} \\\\\n\\> {\\bf forall} $c \\in C$ {\\bf do}\n   \\>\\>\\>\\>   $(*$ initialize the support counters $*)$ \\\\\n\\> \\> $s(c) := 0$;\n   \\>\\>\\>     $(*$ of all candidates to be checked $*)$ \\\\\n\\> {\\bf forall} $t \\in T$ {\\bf do}\n   \\>\\>\\>\\>   $(*$ traverse the transactions $*)$ \\\\\n\\> \\> {\\bf forall} $c \\in C$ {\\bf do}\n   \\>\\>\\>     $(*$ traverse the candidates $*)$ \\\\\n\\> \\> \\> {\\bf if} $c \\in t$\n   \\>\\>       $(*$ if the transaction contains the candidate, $*)$ \\\\\n\\> \\> \\> {\\bf then} $s(c) := s(c) +1$;\n   \\>\\>       $(*$ increment the support counter $*)$ \\\\\n{\\bf end} $(*$ prune $*)$\n\\end{tabbing}\n\n\\end{document}", "meta": {"hexsha": "c37a5962176babe091322b65cb542466c47cb321", "size": 4726, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "apriori/doc/apriori.tex", "max_stars_repo_name": "lucidfrontier45/pyarules", "max_stars_repo_head_hexsha": "7fe85101b50e65c278c49e97503643495cd3618f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2015-09-26T01:04:00.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-27T07:45:04.000Z", "max_issues_repo_path": "apriori/doc/apriori.tex", "max_issues_repo_name": "lucidfrontier45/pyarules", "max_issues_repo_head_hexsha": "7fe85101b50e65c278c49e97503643495cd3618f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-10-06T01:00:13.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-06T01:00:13.000Z", "max_forks_repo_path": "apriori/doc/apriori.tex", "max_forks_repo_name": "lucidfrontier45/pyarules", "max_forks_repo_head_hexsha": "7fe85101b50e65c278c49e97503643495cd3618f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2015-09-27T12:16:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-05T12:21:40.000Z", "avg_line_length": 42.1964285714, "max_line_length": 72, "alphanum_fraction": 0.4676258993, "num_tokens": 1905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3208142509540299}}
{"text": "\\documentclass{article}\r\n\r\n\\usepackage[top=.75in, bottom=.75in]{geometry}\r\n\r\n\\usepackage{amsmath}\r\n\\usepackage{graphicx}\r\n\\usepackage{xcolor}\r\n\r\n\\begin{document}\r\n\r\n\\newcommand{\\tda}[1]{\\textcolor{red}{#1}}\r\n\\newcommand{\\tdb}[1]{\\textcolor{orange}{#1}}\r\n\\newcommand{\\tdc}[1]{\\textcolor{blue}{#1}}\r\n\\newcommand{\\unk}[1]{\\textcolor{red}{#1}}\r\n\\newcommand{\\der}[1]{\\textcolor{orange}{#1}}\r\n\\newcommand{\\off}[2]{\\textnormal{\\emph{Off}}_{#1\\rightarrow#2}}\r\n\r\n\\section*{Setup:} Assume 3 polypoint tags (A, B, C), all 1~m from each other.\r\n\r\n\\begin{itemize}\r\n  \\item $t_A$ = tx delay for tag A (unknown)\r\n  \\item $r_A$ = rx delay for tag A (unknown)\r\n  \\item $\\lambda$ = time of flight for 1~m ($\\lambda = \\frac{1}{c}\\times\\textnormal{\\texttt{DWT\\_TIME\\_UNITS}}$)\r\n  \\item $\\epsilon$ = precise delay before sending the next packet (i.e.\\ 5\\,ms)\r\n\\end{itemize}\r\n\r\nThe goal is to determine the calibration factor for a tag, $cal_A = t_A + r_A$.\r\n\r\n\\section*{Protocol:}\r\n\r\nThe following sequence will recover the $cal_C$. Note that timestamps from\r\nlocal clocks are not synchronized, nor can the clocks be assumed to be running\r\nat exactly the same speed.\r\n\r\n\\bigskip\r\n\r\n\\noindent\r\n\\begin{minipage}{.35\\textwidth}\r\n  \\begin{enumerate}\r\n    \\item Tag A sends a packet\r\n    \\item Tag C sends a packet after $\\epsilon$\r\n    \\item Tag C sends a packet after $\\epsilon$\r\n  \\end{enumerate}\r\n\\end{minipage}%\r\n~~~~~%\r\n\\begin{minipage}{.65\\textwidth}\r\n  \\includegraphics[width=\\linewidth]{calibration_diagram}\r\n\\end{minipage}\r\n\r\n\\begin{align}\r\n  BRX1 &= ATX1 + t_A + \\lambda + r_B \\\\\r\n  BRX2 &= ATX1 + t_A + \\lambda + r_C + \\epsilon_C + t_C + \\lambda + r_B \\\\\r\n  BRX2-BRX1 = \\Delta_B &= r_C + t_C + \\epsilon_C + \\lambda \\\\\r\n  ~\\nonumber\\\\\r\n  k_{C\\rightarrow B} &= \\frac{BRX3-BRX2}{CTX3-CTX2} \\\\\r\n  ~\\nonumber\\\\\r\n  r_C + t_C &= \\Delta_B - \\epsilon_C \\times k_{C\\rightarrow B} - \\lambda\r\n\\end{align}\r\n\r\n\r\n\\end{document}\r\n", "meta": {"hexsha": "8827b651923c17356420c2207fcf88920dc9ca21", "size": 1900, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "software/tottag/calibration/doc/calibration.tex", "max_stars_repo_name": "wsluo/socitrack", "max_stars_repo_head_hexsha": "b559c407ae46f62b23517c7968718ce5e0061d6e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-10-17T00:24:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T11:09:15.000Z", "max_issues_repo_path": "software/tottag/calibration/doc/calibration.tex", "max_issues_repo_name": "wsluo/socitrack", "max_issues_repo_head_hexsha": "b559c407ae46f62b23517c7968718ce5e0061d6e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2020-07-30T14:49:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-04T16:18:20.000Z", "max_forks_repo_path": "software/tottag/calibration/doc/calibration.tex", "max_forks_repo_name": "wsluo/socitrack", "max_forks_repo_head_hexsha": "b559c407ae46f62b23517c7968718ce5e0061d6e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-07-29T22:05:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T11:09:17.000Z", "avg_line_length": 30.6451612903, "max_line_length": 113, "alphanum_fraction": 0.6573684211, "num_tokens": 646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.3208142509540299}}
{"text": "\\chapter{Conclusions}\\label{ch6}\n\\setlength{\\epigraphrule}{0pt}\n\\setlength{\\epigraphwidth}{0.75\\textwidth}\n\\epigraph{\\textit{The true delight is in the finding out rather than in the knowing.}}{Isaac Asimov}\n\n\nIn this work we have introduced the \\acrlong{v2dm} to solve the many-body problem.\nThe \\acrfull{2dm} contains all necessary information to describe such a system, and the expectation value of one- or two-particle operators\ncan be expressed as a linear function of the \\gls{2dm}.\nUnlike the more conventional quantum mechanical methods, the wave function is never used. This method itself has a long history and attracted quite some attention in the second half of\nthe previous century. At first glance, it has many interesting properties: the \\gls{2dm} has a much better scaling than the wave function,\nand the method is strictly variational. Unlike wavefunction-based methods, it produces a strict lower bound on the energy (instead of an\nupper bound).\nUnfortunately, the complexity of the many-body problem has not disappeared, but is shifted to the $N$-representability problem: what are the\nnecessary and sufficient conditions for a \\gls{2dm} to be derivable from an ensemble of many-fermion wave functions?\nIn the 1960's, there was still hope that this problem could be solved in some way, but time has learned that it is a very hard problem (see\nlater).\n\n% vim: spell spelllang=en syntax=tex tw=140 \n", "meta": {"hexsha": "20ac3748d9c24f8d735afbfd6a4834a361b7c9af", "size": 1416, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "conclusions.tex", "max_stars_repo_name": "wpoely86/PhD-template", "max_stars_repo_head_hexsha": "2415b5954e9140bf21d57121f263118abd558283", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "conclusions.tex", "max_issues_repo_name": "wpoely86/PhD-template", "max_issues_repo_head_hexsha": "2415b5954e9140bf21d57121f263118abd558283", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "conclusions.tex", "max_forks_repo_name": "wpoely86/PhD-template", "max_forks_repo_head_hexsha": "2415b5954e9140bf21d57121f263118abd558283", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 70.8, "max_line_length": 184, "alphanum_fraction": 0.793079096, "num_tokens": 343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.32062225838908404}}
{"text": "\\chapter{Characterization of the grating testing setup}\n\n\\section{Monochromator}\n\n%Cartoon of overall layout\n\\begin{figure}\n\\begin{center}\n    \\includegraphics[width=0.48\\textwidth]{question_mark.ps}\n  \\end{center}\n  \\caption[DK480 monochromator layout]{Spectral products' DK480 monochromator layout.  The monochromator is an SP DK480 with selectable 300 g/mm and 150 g/mm gratings on the grating assembly.  Table 1 summarizes the expected properties of the monochromator.  The image is from \\url{http://www.spectralproducts.com}.}\n\\end{figure}\n\nFirst, let's work out the expected resolution of the monochromator.  The monochromator has 2 gratings, one with a blaze peak at 2.0 $\\mu$m and one with a blaze peak at 4.0 $\\mu$m.  For the purposes of this document we will concern ourselves with the 2.0 $\\mu$m blazed grating because this one is in the $1.5 < \\lambda/\\mu\\rm{m} <\\;2.5$ range of the IGRINS instrument.  The monochromator table summarizes the properties of these gratings.  There we see that the 2 $\\mu$m grating is 300 grooves/mm, or $\\sigma$=3.3 $\\mu$m.  The grating has a blaze angle of 17.5$^\\circ$, operates in first order, and has $\\beta \\sim 8^\\circ$ so $\\cos{\\beta} \\sim 1$.  From classical diffraction grating theory (Schroeder 2000) we can calculate the angular dispersion, and then calculate the linear dispersion at the exit slit with the monochromator focal length (480 mm):\n\\begin{eqnarray}\n  \\frac{d\\beta}{d\\lambda}&=& \\frac{m}{\\sigma \\cos{\\beta}}      \\nonumber \\\\\n  \\frac{dx}{d\\lambda}&=& \\frac{d\\beta}{d\\lambda} \\times f = \\frac{f}{\\sigma}  \\nonumber\\\\\n  \t&\\sim& 480 / (3.3 \\times 10^{-3}) \\sim 1.5 \\times 10^{5}\n\\end{eqnarray}\nFor example, a 1 mm slit will cover approximately 7 nm of spectral bandwidth, and the entire visible portion of the spectrum $(\\Delta \\lambda = 300 \\;\\rm{nm})$ should cover about 4 cm at the focal plane, which is consistent with visual inspection.  The minimum slitwidth of 10 $\\mu$m should provide a resolution of 0.07 nm, which is equivalent to a resolution $R=\\frac{\\lambda}{\\delta \\lambda}=30,000$.  However, diffraction and optical aberrations limit the resolution to $R<30,000$.  Specifically, the resolution for a given number $N$ of illuminated grooves in order $m$ is given by $R=mN$, with the number of illuminated grooves given by $N=W/\\sigma$, where $W=68$ mm is the width of the grating in the DK480.  $R=20,000$, which is the same as saying $\\delta x = \\lambda/W \\times f \\sim 14\\;\\mu$m for $\\lambda=2\\;\\mu$m.  This spot size is comparable to the minimum slitwidth, and so this spot size and grating limited resolution is convolved with the slit function.  To take all these contributions into account, we add the $\\delta \\lambda$'s in quadrature:\n\\begin{eqnarray}\n\t \\delta \\lambda_{net}^2 &=& \\delta \\lambda_{disp}^2 + \\delta \\lambda_{grat}^2\n\\end{eqnarray}\n\nIn any case, the delivered resolution will be somewhat less than the predicted resolution due to optical aberrations.  The delivered resolution was measured with a HeNe laser at the factory, and is listed in the table.  For the 10 $\\mu$m slit the average delivered resolution is 0.25 nm or $R=2500$.  The figure below shows the expected and delivered resolution as a function of slit width.  In the next section on the camera and detector system, we study how the finite angular resolution of the camera system provides a related limitation to our spectral resolution.\n\n\n%Table of monochromator properties\n\\input{gta_CA1_tab_SP_monch.tex}\n\n%Efficiency as a function of wavelength for the 300 g/mm grating\n\\begin{figure}\n\\begin{center}\n    \\includegraphics[width=0.8\\textwidth]{question_mark.ps}\n  \\end{center}\n  \\caption[Absolute efficiency of the 300 g/mm grating in the DK480 monochromator]{Absolute efficiency of the 300 g/mm grating in the DK480 monochromator.  The light intensity delivered to the optic is the product of the efficiencies of the light source spectral energy distribution, the filter curves, the gratings in the monochromator, the post slit lenses and mirrors, and the detector efficiency.}\n\\end{figure}\n\n\\begin{figure}\n\\begin{center}\n    \\includegraphics[width=0.8\\textwidth]{question_mark.ps}\n  \\end{center}\n  \\caption[Absolute efficiency of the 300 g/mm grating in the DK480 monochromator, part II. ]{Absolute efficiency of the 300 g/mm grating in the DK480 monochromator over the wavelength range 0.5 to 2.5 $\\mu$m.}\n\\end{figure}\n\n\\begin{figure}\n  \\centering\n  \\subfloat[Visible lamp]{\\label{fig:vis_curve}\\includegraphics[width=0.5\\textwidth]{GTA_eff_vis_clear_2um_PbS}}\n  \\subfloat[NIR lamp]{\\label{fig:nir_curve}\\includegraphics[width=0.5\\textwidth]{GTA_eff_nir_clear_2um_PbS}}\n  \\caption[Predicted relative spectral efficiency of experimental setup- visible and near-IR]{Expected relative efficiency for the specified combination of monochromator light source, monochromator grating, and detector.  We assume no filter is in the beam path.  The relative efficiency is roughly what we've seen from experiments.  The left plot demonstrates the visible lamp light source which has a color temperature of 3100 K, the right plot demonstrates the near-IR light source which has a color temperature of 950$^\\circ$ C.  The visible light source lamp was used in experiments 8 and 9, and the NIR lamp was used primarily in more recent experiments.  Experiments employing the visible light source will demonstrate order-overlap since there is quite a bit of blue second order light overlapping.  We do not know if the PbS detector is sensitive below 1.0 $\\mu$m.  It's important to note that these are (predicted) relative efficiencies, not absolute efficiencies.  The visible lamp may be brighter at any given near-IR wavelength, depending on its power, and coupling to the entrance slit.  This plot is merely to inform the design of experiments, and over what wavelength ranges we can expect to achieve relatively high signal to noise.  It looks like 1.5 to 2.5 $\\mu$m has relatively smoothly variable signal in both scenarios.}\n  \\label{fig:GTA_layout}\n\\end{figure}\n\n\n\\subsection{Filterwheel and filters}\nThe filter wheel is the AB300-T from Spectral Products.  The AB300-T is connected to the DK480 monochromator by a serial cable, and can be commanded through the DK480's connection to the computer.  The AB300-T has five slots sized for 1 inch filters.  Commercially available 1-inch filters generally are unthreaded and need to be secured with a 1-inch retaining ring such as Thorlabs part number SM1RR, and then tightened or loosened with a pin spanner wrench like Thorlabs part number SPW602.  On November 15, 2011 I identified that the filter wheel was unresponsive to the DK480 commands issued from the computer.  I  contacted Spectral Products to troubleshoot the issue.  I will send the filter wheel back to Spectral Products.\n\n%Table of filter wheel slots\n\\input{gta_CA1_tab_filters.tex}\n\n%Efficiency as a function of wavelength for the AB Filters\n\\begin{figure}\n    \\includegraphics[width=1.0\\textwidth]{question_mark.ps}\n  \\caption[Spectral products filter curves]{Filter curves for the AB series filters provided by Spectral Products.  We have two low pass filters from Spectral products- AB3190, AB3300. The filter curve for AB3300 is not shown, and was not included in their supplied filter curves data.  The online table indicates that AB3300 is a low pass filter with transition wavelength of 3000 nm, with a transition tolerance of 50nm.  We also have a Melles Griot 10 nm FWHM interference filter.  See the table on filter properties.  It is important to use order blocking filters because second order light could overlap and mimic ghost orders, or throw off the calibration with reference mirrors.  Since we want to measure efficiencies at the few percent levels, we probably should use order blocking filters unless it is demonstrated the order overlap is negligible.}\n\\end{figure}\n\n%Efficiency as a function of wavelength for the AB Filters\n\\begin{figure}\n    \\includegraphics[width=0.9\\textwidth]{exp48_49}\n  \\caption[FEL1450 LP filter]{The need for order blocking filters.  The left panel shows the raw data with and without the FEL1450 LP filter.  The light blue and purple curves are scans of an Al mirror with the visible light source before and after the green curve scan, which is a scan of the identical system, but with an FEL1450 Thorlabs low-pass filter placed directly behind the post-slit collimating lens (optic number 10 in the diagram of our optical bench configuration).  In subsequent trials employing the FEL1450 filter we placed the filter on an easily removable flip mount post at position 11, which is roughly the position of the image of the grating since it is almost one focal length behind the post-slit lens.  The FEL1450 has an cut-on wavelength of 1450 nm.  The primary purpose of this filter is to block second order light from the bright visible lamp from blanketing the first order infrared light.  The presence of this pernicious second order visible light is clear in the figure on the right, in which the efficiency approaches 100\\% at 2900 nm, which is where second order 1450 nm light will cut on.  The blue curve on the right panel is the ratio of the green and light blue curves on the right, so with and without the FEL1450 filter.  The solid red curve is the manufacturer-provided specification data for the cut-on filter efficiency in the range $1400 < \\lambda(\\mathrm{nm}) < 1650 $.  The dotted red curve is the extrapolation of that curve from the manufacturer claim that the the minimum peak efficiency is 70\\% through 2200 nm.  It is not clear how the filter performs after this wavelength.  It is also surprising that the observed flux ratio just after the cut-on wavelength at 1500$-$1700 nm exceeds the manufacturer provided efficiency data.  Either our filter is out-performing the specification or there is additional second order light falling at 1500 nm, which would be coming from 750 nm.  The filter properties at that short of a wavelength are not known, but this scenario is unlikely anyways since the detector and grating are inefficient at these wavelengths.}\n\\end{figure}\n\n\\section{Camera System and Differential lens/detector motion}\n\\subsection{Angular resolution of the camera system}\nIt is important to understand the camera system's angular resolution, because our system must be able to separate adjacent diffraction orders of the diffraction gratings we seek to measure.  The pixel sizes for our detectors are listed in the table detailing detector properties in the appendix.  We have two camera lenses- with focal lengths of 110 mm and 200 mm.  Note that examination of the pixel is deceiving because the active detecting area is actually much smaller than the entire surface area of the metallic surface seen in visual inspection.  The next figure demonstrates the sub-area which is active.  Experiments 26, 27, 28, 31, and 32 probed the demonstrated slit image width.  We were surprised to find that experiments 26, 27 and 28 demonstrated a big dip in the center of the convolved intensity profile.\n\nOne cause of angular resolution loss and a potential cause of systematic error is the differential camera lens and detector motion.  In our design the camera lens and detector system share a common axis which pivots about the axis rotation, which through the immersion grating.  The next figure shows a cartoon of the geometry of the differential lens and detector motion.\n\n\\begin{figure}\n  \\centering\n  \\subfloat[Dispersion relation]{\\includegraphics[width=0.5\\textwidth]{question_mark.ps}}\n  \\subfloat[160 $\\mu$m slit with CA1a, 2D profile]{\\includegraphics[width=0.5\\textwidth]{question_mark.ps}} \\\\ \n    \\subfloat[160 $\\mu$m slit with Al mirror]{\\includegraphics[width=0.5\\textwidth]{question_mark.ps}}\n      \\subfloat[160 $\\mu$m slit with CA1a, 1D profile]{\\includegraphics[width=0.5\\textwidth]{question_mark.ps}}\n  \\caption[Dispersion for $f$=200 mm camera]{Dispersion for the $f$=200 mm camera, as measured by the $\\alpha$NIR focal plane array.  The $\\alpha$NIR detector has small (39 $\\mu$m) pixels and does not require detector motion, so these values are accurate unconvolved profiles of the dispersion relation.  The light blue solid line in the upper left panel is the expected behavior for perfect imaging optics- the imaged width would be about twice the slit width, assuming a 2:1 camera to collimator focal length ratio.}\n\\end{figure}\n\n\n\\begin{figure}\n\\begin{center}\n    \\includegraphics[width=0.8\\textwidth]{question_mark.ps}\n  \\end{center}\n  \\caption[Differential camera motion]{Cartoon of the camera's differential motion}\n\\end{figure}\n\nWe can work out the amplitude of the differential camera motion in the following way.  First, notice in the previous figure in the first and third panel that beams diffracted from the grating at an angle $\\theta_{d} = \\theta_{a}$ from the optical axis are centered on the detector and so centroids of diffracted beams are undeviated.  The apparent angular widths are deviated by a factor involving the geometric values of the system.  Specifically, we are interested in case 2 in the figure, in which $\\theta_{d} \\ne \\theta_{a}$.  In this case the focused spot position is one focal length behind the lens, parallel to the incoming beam.\n\n\\begin{eqnarray}\n\t%x_{lens}&=&L \\cos{\\theta_a} \\nonumber \\\\\n\ty_{lens}&=&L \\sin{\\theta_a} \\nonumber \\\\\n\tx_{spot}&\\sim&(L+f_c)\\cos{\\theta_a}  \\nonumber \\\\\n\ty_{spot}&=&y_{lens} \\nonumber \\\\\n\t\\tan{\\theta_d} &=& \\frac{y_{spot}}{x_{spot}} \\sim \\frac{L \\sin{\\theta_a}}{ (L+f_c)\\cos{\\theta_a}}  \\nonumber \n\\end{eqnarray}\n\nWhat we really want is $d\\theta_d/d\\theta_a$:\n\n\\begin{eqnarray}\n\t\\frac{d}{d\\theta_a} \\tan{\\theta_d} &=& \\frac{d}{d\\theta_a} \\frac{1}{1+\\frac{f_c}{L}} \\tan{\\theta_a} \\nonumber \\\\\n\t\\frac{d\\theta_d}{d\\theta_a} &=& k  \\nonumber \\\\\n\t\\mathrm{with \\;}k=\\frac{1}{1+\\frac{f_c}{L}}  \\nonumber \n\\end{eqnarray}\n\nWhat is it we are actually measuring?  The output signal, which we will call $h(\\theta)$, from the detector is the convolution of many angular and spectral functions:\n\\begin{description}\n\\item[$s(\\theta)$]\tThe exit slit function. Set by the slit width, a negligibly weak function of $\\lambda$.\n\\item[$b(\\theta)$]\tThe blur spot of the optics. Principally from intentional defocusing at the detector plane.\n\\item[$g(\\theta, \\lambda)$]\tThe grating dispersion function.  This is a function of wavelength and angle. \n\\item[$p(\\theta)$]\tThe pixel response function.  Looks like a tophat, but can have sub-pixel efficiency variations.\n\\end{description}\n\nIn principle, everything is a weak function of wavelength, for example the blur spot will change as a function of wavelength through chromatic aberrations.  We ignore these negligible wavelength dependent effects, except for the the grating which disperses the finite bandwidth beam into an angular spread (see previous figures).  For the purposes of figuring out the effect of the differential camera motion, will group $s$, $b$, and $g$, and any other heretofore unaccounted for (albeit negligible) angular and spectral functions, into a single delivered focal plane intensity profile, $f(\\theta, \\lambda)=g \\convolution b \\convolution s$.  First, let's consider the case in which the beam is monochromatic, so that $g(\\theta, \\lambda)=g(\\theta)\\delta(\\lambda)$.  Let us further compare two different cases of angular motion.  In case 1 the beam and lens are stationary and only the detector moves steadily through the focal plane, pivoting about the axis of rotation centered on the immersion grating.  In case 2 both the lens and detector move along the same rigid arm, so that the image spot and detector are moving, albeit at different angular rates.  Let $\\tau=\\theta_a$ represent the angular position of the swing arm holding the detector for case 1, or lens and detector for case 2, with $\\tau=0^\\circ$ equal to the principal ray of the diffracted beam.  The angular center position of the focused spot in the detector plane is $\\theta_d$, with $\\theta_d= k \\theta_a$ with $k$ defined above.\n\n\\begin{figure}\n\\begin{center}\n    \\includegraphics[width=1.0\\textwidth]{question_mark.ps}\n  \\end{center}\n  \\caption[Immersion grating transfer function]{Cartoon of the immersion grating transfer function.  The grating transfer function $g=g(\\theta, \\lambda)$ is a function of angle and wavelength.}\n\\end{figure}\n\nCase 1: Detector motion only, lens fixed\n\\begin{eqnarray}\n\th(\\tau) = \\int_{-\\infty}^{\\infty} f(\\theta) p(\\tau - \\theta)\\,\\mathrm{d}\\theta  \\nonumber \\\\\n\th(\\tau)=f(\\theta) \\convolution p(\\theta)  \\nonumber\n\\end{eqnarray}\n\nCase 2: Detector and lens differential motion\n\\begin{eqnarray}\n\th(\\tau) = \\int_{-\\infty}^{\\infty} f(\\theta_d - \\theta) p(\\theta_a - \\theta)\\,\\mathrm{d}\\theta  \\nonumber \\\\\n%\t\\mathrm{Which\\; is\\; the\\; same\\; as:\\;}  \\nonumber \\\\\n\th(\\tau) = \\int_{-\\infty}^{\\infty} f(\\theta) p([1-k]\\tau-\\theta)\\,\\mathrm{d}\\theta  \\nonumber \\\\\n\th([1-k]\\tau)=f(\\theta) \\convolution p(\\theta) \\nonumber \n\\end{eqnarray}\n\nCase 1 is a pure convolution, which is consistent with our intuition of smearing pixels with PSFs.  No problemo.  Case 2 is similar, the output function $h(\\theta)$ is a convolution of $f$ and $p$, except stretched out by a factor of $1-k$.  Neat.  If the input signal is polychromatic, then $g(\\theta)$ is a strong function of wavelength, but in fact the convolution proceeds the same way, stretching convolution of $g$ and $p$ by the factor $1-k$.  At the end of the day what we really want is the ratio, $r$, of the integrated intensity of a single monochromatic order from the immersion grating to the integrated intensity of a monochromatic beam from a reference mirror.  In terms of the quantities already defined, $r= \\int h_{g}(\\theta)/h_{m}(\\theta)\\,\\mathrm{d}(\\theta)$.  The area under the curve of a convolution is the product of the areas under the curves, so the pixel function (which is common to both the denominator and numerator in the ratio $r$), cancels out, as do all other common factors like $s$ and $b$.  Evidently $r$ is indifferent to the differential camera motion, which was not initially obvious to me, but now makes intuitive sense since the effect of the differential camera motion is merely a stretching of the pixel function.  To get a sense for the magnitude of the stretching, let us predict the factor $1-k$ for the geometry of our system under its two different operation modes.  For these modes $L=20.5$ and $f=110 \\mathrm{\\;or\\;} 200$ mm.  The angular profiles will be stretched by factors of 2.9 and 2.0, respectively.  That there is less stretching for the longer focal length camera can be understood since it is more similar to the scenario of the detector moving freely from the lens, or in other words the relative motion is faster.  This whole angular rates problem is analogous to the difference between sidereal and synoptic rates in the apparent motion of celestial bodies in the solar system- Mars moves more slowly through the sky than does Jupiter even though Mars' angular space motion relative to the sun is faster than that of Jupiter.  \n\n\\begin{figure}\n\\begin{center}\n    \\includegraphics[width=0.8\\textwidth]{exp45_46}\n  \\end{center}\n  \\caption[Angular resolution experiment]{Experiment 45 and experiment 46 angular resolution experiments- observed instrumental profiles.  The width of the mirror slit is a few times smaller than the pixel width so that these profiles mostly indicate the instrumental pixel and motion response.The left panel is the instrumental profile of a monochromatic mirror beam with the lens mounted to the optical bench.  The right panel is the instrumental profile of a monochromatic mirror beam with the lens mounted to the swinging arm along the same axis as the detector.  The last panel is the latter experiment with its $x-$axis shrunk by a factor of 2, which is predicted from the differential motion and geometry of the system.  The match is good.  Based on the first panel we can directly estimate the effective width of the pixel- the $0.16^\\circ$ width translates into 0.54 mm pixel width, but strictly less than this value since there is also some small contribution from the convolution of the slit.  This width is almost half as small as the 1 mm width we had been assuming based on the specs of comparable detectors and the limited information we had about our model. Our operational instrumental profile is the second panel, which has an angular width of about $0.30^\\circ$.}\n\\end{figure}\n\nIn experiments 45 and 46 I directly measured the stretching factor for the system with $L=205$mm and $f_C=200$mm.  In experiment 45 I mounted the camera lens to the static optical bench so that the lens did not move with the swing arm, but the detector swung about the optical axis.  Experiment 46 had the lens mounted to the camera swing arm.  The angular scan profiles are shown in the next figure, with raw signal plotted against angular position, that is the angle of the arm.  The first panel shows experiment 45, the second panel shows experiment 46, and the last panel shows experiment 46 with its $x-$ scale compressed by a factor of 2, as predicted above for this camera system.\n\n\n\\begin{figure}\n\\begin{center}\n    \\includegraphics[width=0.45\\textwidth]{question_mark.ps}\n  \\end{center}\n  \\caption[Observed and predicted slit functions]{The observed slit function for the 110 mm focal length camera system.  The pixel demonstrates non-uniform sub-pixel response, up to a factor of 20\\%.}\n\\end{figure}\n\n\n\n\\section{Detectors}\n%Table of single pixel detector properties\n\\input{gta_CA1_tab_detectors.tex}\n\n\n\\begin{figure}\n\\begin{center}\n    \\includegraphics[width=0.8\\textwidth]{question_mark.ps}\n  \\end{center}\n  \\caption[PbS detector pixel geometry]{PbS detector pixel geometry.  The active area of the pixel is a subset of the entire metallic surface.  The dashed white lines show the detector's active area.  The ruler numbers demonstrate centimeters with sub-ticks equal to 1 mm.  The thick white bars near the pixel on the blow up image represent 3 and 1 mm.  The long axis of the detector active area must be parallel to the image long axis.  This requirement is tricky to accommodate with simple mountings, however, since the detector mounting set-screw is perpendicular to the long axis.  Casey Deen pointed out these issues in the geometry on October 31, 2011.  Experiments I performed before this date should not demonstrate sharp top-hat function PSFs.}\n\\end{figure}\n\n\n\\begin{figure}\n  \\centering\n  \\subfloat[Slit image]{\\label{fig:GTA_slit}\\includegraphics[width=0.5\\textwidth]{question_mark.ps}}\n  \\subfloat[Pupil image]{\\label{fig:GTA_im01}\\includegraphics[width=0.5\\textwidth]{question_mark.ps}}\n  \\caption[Slit and pupil image compared to single pixel detector size]{ \n  \n  \\emph{Left-} Layout of the IR detector areas compared to the image of the slit, as produced with a reference mirror and the current optical camera configuration, which includes a $f=110$mm focal length lens.  The blue dashed line is the footprint of the $\\alpha$NIR 2D focal plane array, which has 316 $\\times$ 252 array of 39 $\\mu$m square pixels.  The solid red line is the single pixel detector which is 1 $\\times$ 3 mm, as shown in the previous figure.  The background shows a filled contour plot of the slit image taken with the $\\alpha$NIR from 100 combined dark subtracted frames, with the $f=110$ mm focal length camera lens, 250 $\\mu$m slit width and the minimum slit height provided by the monochromator, with $\\lambda$=1.6 $\\mu$m.  Apparently the minimum slit height the monochromator provides is not sufficiently small to capture the full slit image height.  Either the slit height should be reduced or the camera lens focal length should be reduced to capture all the incident light.\n  \n  \\emph{Right-} Same as the previous figure, except the background shows a filled contour plot of an image of the light source lamp filament with a 2.9 mm slit width and the maximum slit height provided by the monochromator, with $\\lambda$=1.6 $\\mu$m.  The contours on the image are black-blue-light blue with 10, 20, 40, 80, 160, 320 counts/pixel, with the noise floor at 5.4 counts with $\\sigma=$ 2.5 counts/pixel.  The single pixel detector cannot capture all the light of the grating image onto the single pixel detector.  I discourage the choice of this image, since the image width does not shrink appreciably with decreasing slit size, meaning we lose light off the sides of the detector, and we lose angular resolution.}\n\\end{figure}\n\n\n\\begin{figure}\n  \\centering\n  \\subfloat[PbS and PbSe detectors]{\\label{fig:PbS_det_eff}\\includegraphics[width=0.8\\textwidth]{question_mark.ps}} \\\\\n  \\subfloat[InGaAs and Ge detectors]{\\label{fig:Ge_det_eff}\\includegraphics[width=0.8\\textwidth]{question_mark.ps}}\n  \\caption[Relative efficiency of single pixel detectors]{Relative efficiency of detectors comparable to but different from the models in our lab.  See the table with information on the detectors. The data are from \\url{http://www.newport.com}.}\n\\end{figure}\n\n\n\n\\section{Equipment operation and performance}\nThe measurement system presents some challenges, specifically aligning and collimating the low intensity invisible monochromatic beam, and scanning the diffracted orders with a small single pixel detector.  In this section we characterize the measurement equipment through tests of the resolution and delivered optical and electronic performance.  We scrutinize the experimental strategy for sources of systematic errors.\n\n\\subsection{Repeatability}\nA key limitation in our measurement strategy is the repeatability and stability of the optical alignment, and electronic and lamp conditions.  Specifically, our strategy is to take reference beam or reference mirror measurements before and after the scans of our grating or optic of interest.  Since our scans last up to 30 hours or more, reference calibration measurements can be temporally separated by several days.  The measured signal can drift for many reasons, for example drift in the lamp filament temperature or detector temperature, or mechanical sag of mirror mounts induced by thermal expansion or vibration.  Ideally our measurement strategy would take contemporaneous calibrations or near-contemporaneous calibrations on scales much shorter than the thermal drift time scale.  Our measurement system's structural design currently makes contemporaneous reference measurements prohibitive.  In principle the addition of a motorized retractable mirror or a beam splitter could provide near-contemporaneous or contemporaneous reference measurement, but these hardware upgrades are not going to be pursued at this time.  In this section we quantify the delivered repeatability of our measurements.  Naturally, we can repeat measurements many times to average out the variations in repeatability, but of course this adds to the measurement timescale and turnaround.  Our goal is to achieve about 5\\% repeatability of measurements.  This level of uncertainty is comparable to what is delivered in industry applications (as noted from our experience with II-VI Infrared, who reported a 3\\% systematic error in their wafer witness samples for the JWST project, for example).  Furthermore, 5\\% is a fair estimate for our other systematic errors arising from vignetting of optical components or chromatic aberrations, among milliard other factors, so doing much better than this in any single experiment is likely just fooling ourselves.\n\nThe next figure demonstrates the repeatability of experiment 22 and 24.  These experiments served as the pre- and post- reference mirror calibrations for experiment 23.  The measurements were separated by 4 days, specifically from a experiment 22 was started on Friday November 17, 2011 and experiment 24 was started on Monday November 21, 2011.  Both experiments took 20 hours to complete.  One aspect of the experimental setup was altered over this time- the necessary swapping of the reference mirror for the CA1 immersion grating, and the subsequent re-replacement of the mirror.  This process has its own affiliated repeatability limitations, but notably our mount was designed to be stable by using a 2-pin ball stud plate and 2-hole base plate.  The repeatability of this mount has not be independently examined, but in principle could be tested to a few arcseconds with a simple laser.  In any case when replacing the ball stud plate I typically monitor the instantaneous signal reported on the lock-in amplifier front panel, and I carefully attempt to torque the ball stud plate.  I did not notice any change in the instantaneous signal.\n\n\n\\begin{figure}\n\\begin{center}\n    \\includegraphics[width=0.7\\textwidth]{exp22-24_plusdif}\n  \\end{center}\n  \\caption[Repeatability experiment]{Experiment 22 and experiment 24 overplotted to demonstrate the level of the repeatability of the measurements separated by 4 days.  The bottom panel shows the fractional difference of two curves which was computed as the absolute value of the difference divided by the sum of the two experiments, which is the same as half of the difference divided by the mean of the two experiments.  Blue line is the raw data, overplotted in black with a 21 pixel boxcar smooth.  The yellow dashed line is 5\\% fractional difference from the mean.  The repeatability is better than 5\\% over 1.5 $-$ 2.5 $\\mu$m, which is our wavelength range of interest.}\n\\end{figure}\n\n\\begin{figure}\n\\begin{center}\n    \\includegraphics[width=1.0\\textwidth]{exp25and30}\n  \\end{center}\n  \\caption[Stability experiment]{Experiment 25 and experiment 30 overplotted to demonstrate the level of the stability of measurements at $\\lambda = 2.0 \\; \\rm{ and } \\;2.3\\; \\mu$m. \\emph{Left:} The measured signal normalized to its starting value as a function of time.  No changes were made to the experimental setup over the duration of the experiment.  Experiment 25 lasted 17.6 hours, experiment 30 lasted 52.9 hours.  The standard deviations over those times was about 9\\% and 2\\%, with peak to valley amplitudes of and 91\\% and 23\\%.  Experiment 25 shows about 4.5 times as much instability as does experiment 30, despite the fact that experiment 25 is 3 times shorter than experiment 30.  This level of instability is demonstrated in the previous figure, where the curves at $\\lambda=2.3 \\; \\mu$m match to 0.3\\%, but the difference at $\\lambda=2.0\\;\\mu$m is about 2\\%.  It's not clear what is the cause of the wavelength-dependent instability, but my guess is that the near-IR lamp is warming or cooling and since 2.0 $\\mu$m is on the Wein side of the black body curve, it is much more sensitive to minute temperature differences than the 2.3 $\\mu$m measurements, which are close to the blackbody peak.  The sampling rates were semi-regular, with delivered mean time steps and standard deviations of $15.86\\pm0.34$ and $15.85\\pm0.09$ s, but maximum separations of up to 29 and 20 seconds respectively.  \\emph{Right:} The power spectrum of experiment 30, normalized to its peak value, with the DC component removed.  The red dashed line is an unweighted linear fit to the data frequencies less than 0.001 Hz, excluding the DC component.  Since the sampling was not strictly regular, we interpolated (i.e. \\emph{interpol()} in IDL) the time samples onto a 5 times finer grid than the semi-regular native sampling.  The fitted power law slope is -1.4, which is consistent with 1/$f$ ``flicker\" noise.}\n\\end{figure}\n\n\n\n\\section{Early Experiments}\n\n\\begin{figure}\n  \\centering\n  \\subfloat[Early polychromatic beam profile experiment]{\\label{fig:exp7}\\includegraphics[width=0.45\\textwidth]{dat07_wls_1}}\n  \\subfloat[90$^\\circ$ Rotated PbS detector]{\\label{fig:rot_detect}\\includegraphics[width=0.45\\textwidth]{exp7_vs_ex8_norm}}\n  \\caption[Rotating the PbS detector improved the angular resolution by a factor of 3]{ \\emph{Left-} Experiment 7 polychromatic detector profiles.  These profiles were taken before we rotated the slit so its long axis was perpendicular to the direction of the angular scanning, and before improvements to the optical quality, particularly the focus.  \\emph{Right-} Factor of 3 improvement in angular resolution from correct detector mounting. Experiment 7 and 8 detector profiles for $\\lambda = 2.5 \\; \\mu$m.  Between experiment 7 and 8 I rotated the PbS detector so that the long axis of the photosensitive detector area was perpendicular to the axis of the swinging arm.  The detector area is 1 $\\times$ 3 mm$^{2}$, so with our $f=$ 110 mm camera lens and PbS detector configuration we expect 1.8$^\\circ$ and 0.6$^\\circ$ field of view for experiments 7 and 8, respectively.  The measured FWHM of the PSFs for experiments 7 and 8 are 1.8$^\\circ$ and 0.63$^\\circ$.  Notice the sidelobes on experiment 8, these came from calibration problems, specifically a background scan was subtracted off of this scan, but the background scan was not taken with a dark aperture cover and so this PSF is really the difference of two PSFs.  Still the width of the feature is unaffected, and the improved spectral resolution from rotating is demonstrated.}\n\\end{figure}\n\n\n\\begin{figure}\n\\begin{center}\n    \\includegraphics[width=0.6\\textwidth]{question_mark.ps}\n  \\end{center}\n  \\caption[Factor of 50-100 improvement in signal from optical and electronic improvements]{Voltage as a function of wavelength for a 100 $\\mu$m slit width, during experiments 1-5 and experiment 7$-$ experiments 1-5 are clustered below 1 mV, whereas experiment 7 is well above 10 mV.  The optical setup was unchanged during experiments 1-5.  I aborted experiment 6 because the scanning was goofed up.  Before experiment 7 I increased the on-detector gain setting by a factor of 5, maximized the signal by nulling the signal to 0 and then adding 90$^\\circ$ of phase, increased the chopper frequency from 80 to 180 Hz, reset the lock-in amplifier pre- and post- measurement time-constant to steady the signal reported on the LCD display, fine adjusted the detector focus and height by comparison to the lock-in amplifier LCD display.  I also fine adjusted the exit-slit collimator lens, coarse-adjusted the input light source positioning on the lab jack, and triggered the TE cooler for the detector.  It is not clear if these last 3 changes had any effect, but all the changes combined to improve the signal by a factor of 50-100.  The beam profile also improved, although they are still not flat-topped.  See the figure of the beam profiles.}\n\\end{figure}\n\n\n\n\n%------------------------------------------------------------------------------------------\n%Long Tables\n%------------------------------------------------------------------------------------------\n\\input{gta_CA1_tab_exper_parms.tex}\n\\input{gta_CA1_tab_experlog2.tex}\n", "meta": {"hexsha": "1b985a46b04dc107c090f075ac4b9767c9ee7ee0", "size": 34692, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "appendices/chapter-appendix1.tex", "max_stars_repo_name": "BrownDwarf/gullyDiss", "max_stars_repo_head_hexsha": "2b5be79e4b05ea98f5748011e1e4a5df142e06f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "appendices/chapter-appendix1.tex", "max_issues_repo_name": "BrownDwarf/gullyDiss", "max_issues_repo_head_hexsha": "2b5be79e4b05ea98f5748011e1e4a5df142e06f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "appendices/chapter-appendix1.tex", "max_forks_repo_name": "BrownDwarf/gullyDiss", "max_forks_repo_head_hexsha": "2b5be79e4b05ea98f5748011e1e4a5df142e06f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 139.3253012048, "max_line_length": 2110, "alphanum_fraction": 0.7748184019, "num_tokens": 8570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.32058914319477727}}
{"text": "\\documentclass{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage{amsmath}\n\\usepackage{graphicx}\n\\graphicspath{ {images/} }\n\\newcommand{\\Mod}[1]{\\ (\\mathrm{mod}\\ #1)}\n\n\\title{Sonny: A curve designed to perform high security circuit operations for Elliptic Curve protocols in Zero Knowledge }\n\\author{\n  Carlos Perez\\\\\n  Dusk Foundation\\footnote{https://dusk.network/}\\\\\n  \\texttt{carlos@dusk.network}\n  \\and\n  Luke Pearson\\\\\n  Dusk Foundation\\\\\n  \\texttt{luke@dusk.network}\n}\n\\date{October 2019}\n\n\\begin{document}\n\n\n\n\\maketitle\n\\thispagestyle{empty}\n\\pagestyle{empty}\n\n\\begin{abstract}\n\n\n\n\\end{abstract}\n\n\\newpage\n\n\\tableofcontents\n\n\\newpage\n\n\\section{Introduction}\nThe construction and use of elliptic curves is paramount to many cryptographic protocols. Elliptic curves are among the fastest performing primitives where the Discrete Logarithm Problem (DLP) is hard, which is why they are regarded as dominant in the field of cryptography. As the field of cryptography advances, elliptic curves have been proven to be unparalleled in their use for cryptographic systems which have speed and security as two of the most outstanding features. As they are held in such high regard, they can greatly steer the direction of new cryptographic protocols. When outlining new protocols which rely upon elliptic curves, there are a multitude of features which are affected depending on design; often regarded as factors of opportunity cost which leads to compromise on critical features within Elliptic Curve Cryptography (ECC). However, some contemporary techniques can be used to better facilitate systems that rely so heavily upon these primitives. Since many previous protocols are proven to be secure, it is $often$ far more efficient to add to these standards with compound technologies rather than seeking entire system replacements. \\\\\\\\ One of the most groundbreaking techniques used in state of the art cryptography is the constructing of Zero Knowledge  (ZK) proofs for nearly universal computation. As is with many cryptographic protocols, there is a choice of which proof system is best tailored to a system. Which includes a trade off, between proof sizes, verification times and other factors making up a ZK proof.  For particular proof systems, their expression relies upon an elliptic curve and an arithmetic circuit. The elliptic curve here is a function used to encode the public outputs which are represented as field elements, upon which a lot of operations rely. The operations for these proofs systems, however, are expressed in terms of a circuit which is determined by scalar curve arithmetic. This unfortunately restricts the operations which can be performed as they are dependent upon standard arithmetic circuit outputs - addition, multiplication, subtraction and division. Many protocols such as Elliptic Curve Digital Signature Algorithms (ECDSA), which are performed using field encodings, are in operable through the medium of generic ZK proofs which are expressed in terms of a circuit. \\\\\\\\ \n\\boldsymbol{A} \\boldsymbol{profound} \\boldsymbol{solution}.\nIn section 3, we elaborate on how we use our derived curve, which is embedded into the scalar field of Curve25519, in order to extend the circuit operations to those which exceed the traditional bounds of constraint systems. The curve is constructed across a scalar field, as a base field, thus allowing the portability of ZK proofs onto non scalar protocols.\\\\\\\\\nAs with all elliptic curves, their construction will strongly influence the outcomes of the protocols in which they are implemented. In addition to this, there can be discrepancies in both the security and speed of cryptographic systems dependant upon on how they're implemented. For this reason, we wanted to make use of the the fastest complete formulas for elliptic curves, which are Twisted Edwards curves. In conjunction to their complete formulas, Twisted Edwards curves have been proven by Bernstein et al, to be Birationally equivalent to Montgomery curves. Which fit the purpose of the augmented construction, as Montgomery operations in arithmetic circuits were proven by the Z-cash team to provide a fast Montgomery ladder for in circuit multiplication. Whilst these curves models can provide some of the fastest and most simplistic operations, they do provide issues in security. Neither Montgomery, nor Edwards curves deliver prime order groups in their implementations. They provide curves which have a cofactor, $h$, which multiplies the prime of the subgroup to give the group order. Whereas curves like Weierstrass give prime order but their formulas are too inefficient for circuit operations.\\\\\\\\ \nFor non prime order curve groups, the mismatch in desirability of prime order curves and inability to implement one directly from the curve can be patched with uniquely tailored modifications.  However, these fixes oft become perplexing to the non-implementors and with higher level protocols they are seldom straightforward. Using curves which provide prime order groups, such as Weierstrass Curves, have slower formulae and are very difficult to implement in constant time. Plentiful curve families allow for the encoding of different related curves for protocol specific purposes. For example, [] library uses Twisted Edwards forms for out of circuit operations like public key generation to exploit the high speed formula but uses Montgomery form for in circuit operations to benefit from the ladder multiplication. If an ad hoc fix needs to be given to each related curve model, then the implementation can become tedious and very complex.\\\\\\\\\n\\boldsymbol{A} \\boldsymbol{centric} \\boldsymbol{solution}.\nIn section 4, we explain how to use the Ristretto technique, which constructs prime order Edwards curves from non prime order groups, with our embedded curve, to compress the cofactor such that $h$ = 1. Ristretto makes use of the relationship between curves and provides a fix for the cofactor complication for all models in one place.\\\\\\\\\n\n\n\n\n\\subsection{$Compatibility$} (isogenies/facility) ristretto - sig - scalar\n\n\\section{Notation and Formulae} \n\\subsection{General notation}\n$Finite Field$: $F_p$ is the finite field where the $char$ \\neq {2}\\vee{3}\\\\\\\\\n$\\varepsilon_{a,d}$ is a Edwards curve, given by the equation: $$ {a}x^2+y^2=1+{d}x^2y^2 $$ where {$d$} and {$ad$} are none square in $F$ and has no points at infinity. In this paper, the primary focus is upon Twisted Edwards curves, where $a = -1$. The identity point of an Edwards curve, $\\varepsilon$, where (X,Y) $\\epsilon$ in $F_p$, is given encoded to (0,1). When Edwards points are expressed in Extended Twisted coordinates, the identity encoding is given by (X : Y : Z : T) = (0 : 1 : 1 : 0).\\\\\\\\\n${M}_{a,\\frac{2-4d}{a}}$ is a Montgomery curve, given by the equation: $$ y^2=x^3+Ax^2+Bx $$ A Montgomery curve is Birationally equivalent to an Edwards curve - a definition used for algebraic substitution -  where its point at of infinity is the identity point, denoted as (0 : 1 : 0).\\\\\\\\  \n$\\jmath_{a^{2},a−{2d}}$ is a Jacobi curve, given by the equation: $$y\n^2 = {e}x^4 + 2Ax^2 + 1$$ A Jacobi curve, better known as a Jacobi quartic, is central to all curve models and to utilise this curve relationship we will only be using Jacobi curves where $e = {a}^2$, as such curves have a full 2-torsion point.\\\\\\\\\n$Torsion\\ points$:\\ An element [P] in  $G$ is a torsion point if there is a mapping of $M$, by means of multiplication, where $M$ \\cdot\\ [P] = $0_{G}$. Torquing elements for a curve form a subgroup, $G$[$M$], where the order is divisible by ${M}^2$. The torsion subgroups for this curve family have order 1, 2 or 4.  \\\\\\\\ \n$Isogeny$: An isogeny, $\\varphi$ , is a function which maps algebraic groups whilst preserving the group structure. This mapping must satisfy the properties of being surjective and having a finite kernel. The isogeny, in this paper, is used to transport an encoding between different curve models.\\\\\\\\\n$Curve forms$: $\\varepsilon_{a,d}$; ${M}_{a,\\frac{2-4d}{a}}$; $\\jmath_{a^{2},a-{2d}}$ \\\\\\\\ These curve models are all isogenous to one another. The Edwards, Montgomery and Twisted Edwards are independently 2-isogenous to the Jacobi quartic and are therefore 4-isogenous to one another.  \\\\\\\\\n$Arithmetic$\\ $circuits$: These are the computational models for computing circuits. They are universally bound to add and multiply, which are the functions performed at each node on all given inputs. \\\\\\\\\n$Cofactor$\\ $compression$: This refers a quasi-construction of cofactor 1 curves from cofactor 8 groups. Also known as cofactor division, it involves the process of point compression when points of order 4 or 8 are produced.\\\\ \n\n\\subsection{Our contributions}\n\\subsubsection{Elliptic curve}\nHere we present an elliptic curve, created for an safe and efficient Elliptic curve operations inside bulletproofs; called Sonny. Sonny is defined as an embedded curve which the gives the input for the proofs and the discrete log based proof is implemented using the outer curve, Curve25519. \\\\\\\\\n\n\\noindent\\fbox{%\n    \\parbox{\\textwidth}{%\n    $$ Sonny  $$\n        \\begin{itemize}\n    \\item Curve equation in Twisted Edwards form: $$ ax^2+y^2=1-dx^2y^2 $$ \n    \\item $a= -1$\n    \\item $d= -\\frac{126296}{126297}$\n    \\item $Basepoint: Y = \\frac{3}{5}$\\\\\n    \\item Montgomery form equivalent: $$ y^2=x^3+Ax^2+x $$\n    \\item $A = 505186 $\n    \\item $Basepoint: X = 4$\\\\\n    \\item The curve group order, G, is $$ 2^{252}+115924404605461509904689566245241897752 $$      \n    \\item The order of the scalar field, $r$, is $$ 2^{249}+15114490550575682688738086195780655237219 $$       \\item The order of the base field, $p$, is  $$ 2^{252} + 27742317777372353535851937790883648493 $$\n    \\item Cofactor: $$ h =\\frac{G}{r} = 8$$\n    \\item Weierstrass form equivalent: \\\\  $$y^2=x^3+ax+b $$\n    \\item $a$ = 7237005577332262213973186563042994240857116359379907606001\\\\950828033483786813\n    \\item $b$ = 445582015604702849664\n\\end{itemize}\n    }%\n}\\\\\\\\\n\n\n\n\\section{Finite fields}\nA finite field is a set of numbers on which arithmetic operations are performed and satisfies a specific set of rules. These operations include multiplication, addition, subtraction and division - notably, the most fundamental operations in ECC. Elliptic Curve arithmetic uses the finite field of integers reduced mod$p$, where $p$ is some prime. The use of finite fields as the extension of elliptic curves is to reinforce the hardness of the DLP, as well as make certain cryptographic assumptions about the order of the set. The choice of finite fields for elliptic curves, known as base curves, provide a cyclic group which gives precise knowledge to the amount of bits that need to be stored by point outputs. As stated, the base fields dictate the operations for the elliptic curves and thus selection of these fields affects the security, speed and simplicity of the implementation of the curve. Supplementary to standard operations performed mod$p$, there are many protocols can be performed in ECC which are implemented using finite sets but do not make use of the base field. They rely upon another prime order field, which is the curves scalar field, also known as the subgroup.  The existing systems like the verification systems are already deployed and because their operations are performed on on the base field, and not a scalar field, they are not directly updateable with a large range of contemporary techniques. This paper and findings focuses on Zero Knowledge  proofs as the 'add-on technology' for existing schemes. \\\\\\\\ Elliptic curves have both a base field, which is the finite field in which they are defined; and a scalar field, which is associated with the number of points on the curve. DL based proofs which use a curve and a circuit rely upon both of the finite fields. The base field here is a function used to encode the public coordinates which are represented as field elements. However, as the operations are performed mod$p$, where $p$ is prime,  the outputs are reduced to the prime scalar field. Thus operations which require the base field, cannot be performed inside proof systems which use arithmetic circuits as an expression. As a result the ZK outputs are limited to what circuit operations can be performed by the elliptic curves scalar field. The circuit, in this case, encodes relation between the input and outputs.\n\\subsection{Efficient ZK for higher operability }\nTo extend the range of ZK elliptic curves operations to those which employ the base field, we have built a curve which has a base field equal to the scalar field of Curve25519. This is defined in the following manner: Let $\\varepsilon_{1}$ and $\\varepsilon_{2}$ be elliptic curves. Where the prime subgroup order, or scalar field, of $\\varepsilon_{1}$ is $r$; we define $\\varepsilon_{2}$ over the base field $F_p$, where \\#$F_p$ = $r$. \nThis will allow us to perform fast in circuit operations using $\\varepsilon_{2}$ as the embedded curve within the scalar field of $\\varepsilon_{1}$.One particular current issue that embedding curves helps to alleviate is the adding to, or updating of, existing software protocols with privacy techniques so that already deployed systems can benefit from high levels of privacy preservation. By constructing this, we are making a quasi representation of one finite field as both a scalar and a base field. We can therefore encode the field based protocols curve over the scalar field of existing systems - and protocols such as key signature verification, can be performed inside a Zero Knowledge  proof. We present a means of verifying only the scalar operation, in Zero Knowledge , so that Zero Knowledge  proof of statements derived for signature schemes can be proven rather than the signature itself. This is performed by expressing ZK proof of computations as the argument for computational models, such as arithmetic circuits.\\\\\\\\\nIn the case of Zerocaf protocol, we have the outer curve operations, using Curve25519, which implement the ZK proof system, where the operations are performed as integers mod the base field. Then there is Sonny, the inner curve, known as the embedded curve which is the curve we make the proofs about. For the case of signature schemes, like Elliptic Curve Digital Signature Algorithm (ECDSA), the operations for the signature generation are made using Sonny then the Zero Knowledge  arguments for these outputs are generated using Curve25519. By setting the scalar field of Curve25519 as the base field of Sonny, all the operations are efficient when expressed in terms of a circuit. The validation keys here are effectively turned into discrete log proofs, as the generation of ZK values is performed in one amalgamated protocol, even though it comes from two different curves. \\\\\\\\\nMany software layers require information from the user - just like authentication certificates for websites, where the type of secret keys is known to the website for verification. The information given is often burnt into the hard memory of the website, which can be used by the software owners to discriminate against different keys and brands of keys hence the need to preserve privacy on these existing protocols.\n\\subsection{Circuits}\nAn circuit is combinational set of operations which are aligned in a set or series for the ultimate purpose of optimising otherwise standardised mathematical process. The operations, better known as the basic arithmetic operations (addition, subtraction, multiplication, and division), are theoretically performed in constant time. This statement is derived from the fact that the required RAM required is roughly equal for all operations. However, when computing these operations for some large integers, it is apparent that the magnitude greatly affects the costs of RAM. Thus giving a discrepancy for computational time between the theoretical arguments and the practical implementation. When the expression of these arithmetic operations is performed in a circuit, it is referred to as an arithmetic circuit. When expressed for computations within computer systems, any arithmetic circuit is constructed from various combinational elements, which are connected by wires. A combinational element is fixed element which performs a specific function from a constant number of inputs and outputs.\nCircuits are used alongside the elliptic curves to construct discrete log based proof systems; when the circuit is defined over the scalar field.\n\n\n\\section{Prime order groups}\n'A group of prime order' is always a cyclic group, that has a mapping - which respects the group structure - to the quotient of the group of integers by a subgroup. This subgroup is generated by a prime number. Groups of prime order are often a prerequisite to crytpographic prototcols, as they provide the basis for a hard DLP and thus increased security for implementation. For implementation, we have made efficiency the most paramount factor for curve selection, which led to us choosing a Twisted Edwards curve form. This is because the Edwards forms of the curves provide the fastest known formulas, which can be accredited to extended Twisted Edwards, introduced by Hysil et al, where auxiliary points are used with fewer field inversions. As elliptic curves are Abelian groups, they provide varying order for their respective groups. Edwards curves and their birational Montgomery equivalents, provide 'not quite' prime order groups over fields - the absence of prime groups can lead to timing variations when implementing protocols such as the signature schemes Sonny implements. Instead of certain Elliptic curve groups being prime, they have a cofactor $h$, meaning that $h \\cdot q$ is the group order, where $h > 1$ and $q$ is a large prime. Having this property where $h > 1$ can lead to many implementation complexities.\\\\\\\\\nThere are cofactor relates attacks designed to extract information, in the form of bits, about a users private key. When generating a public key, it is ideally performed using a point operation on a given curve point, where a chosen scalar outputs a new point, modulo the base field. This provides a public key, from which the scalar, known as the private key, cannot be extracted. However, if points on the curve are selected by attackers to have order which divides $h$, then presented as valid curve points, they can be mistakenly used by a user. If an incognizant user generates a public key by inputting a secret scalar to a function which operates with points of order $h$, then the attacker can gain some bits about the input scalar. Whereas within a prime order group, there is no means of generating valid points which have order dividing $h$. The abstraction of having non prime order groups can be solved with specialised modifications towards individual protocols. One notorious method is to multiply points by the cofactor and check the result; if the resulting point is the identity point then it can be discarded. Many of the individual techniques produce continuous and substantial flaws, especially with regards to patchwork comprehension, which occurs when the protocols are being implemented by those who did not design them, i.e. Implementors not knowing at which step to multiply by $h$. \n\\subsection{Cofactor compression}\nThere are various advantages and disadvantages to having a cofactor larger than one, therefore a thorough analysis must be performed,  so that it is known whether or not cofactor manipulation is needed. For all curves, except for Hessian curves, the cofactor is divisible by 4. To become more useful to a broad spectrum of cryptography, Ristretto is apt for a large number of curves, which have a cofactor of 8 or 4. When the cofactor is greater than 1 multiple operations can be hindered. A quotient group can be constructed to allow for the implementation of prime order groups, thus effectively compressing the cofactor, by applying the Ristretto technique. This technique requires just one additional step to Mike Hamburgs decaf proposal for cofactor-4 curves. The technique works using following four functions:\\\\\\\\   \n${Equality}$ ${testing}$ This function checks the equality of group elements. \\\\\\\\\n${Encode}$\\ The encoding function is applied to an Edwards point and this becomes the internal representation for the new \"Ristretto point', meaning the same Edwards point operations are performed on the Ristretto point, and with no overhead cost. The function encodes the elements as byte strings so that that the Ristretto elements can be encoded identically.\\\\\\\\\n${Decode}$\\ This function decodes the byte strings into the internal representations of Ristretto points. There is also a validity check which assesses the canonical representation of points, and only accepts those which are outputs of the encoding function. \\\\\\\\\n${Curve}$ ${hashing}$\\ For many protocols, mapping elements in a group to a curve is done by a hash function, as it provides standardised digests which can be encoded. Ristretto using an Elligator 2, which gives a 1:1 mapping of group elements to the curve. Elliga\n \n\\subsection{Isogenies}\nBy using the Ristretto technique, we are able to solve all cofactor related issues in one place and with one step. This is facilitated by its use in the relationship of the curves, and how this lets us transport the cofactor compression for curves, via the isogeny, to another curve in the same family. Which in turn means we work with prime order points in any operations of ECC. Otherwise, the implementation would have to deal with the issue at varying stages which is dependent upon a protocols ultimate design. An isogeny is a function which maps one algebraic group to another, whilst maintaining the structure of the group - which in terms of elliptic curves, means that a curve is allowed curve to take on the values of another and preserve the same point addition method. These functions are non-constant and are used as a tool for effective 'transportation' between curve models. Just as with all concrete mathematical formulae, these functions have a domain and co-domain, which means that given these two, it is possible to compute the function itself. In this document isogenies will be given the generalization as the multiplication by $m$ map, where they have a finite kernel and are restricted to rational mappings.  \nA deeper understanding of isogenies for elliptic curves has greatly advanced the field of ECC, as it is possible to deduce one mapping from the form of another. Additionally, if these relationships are well understood then they can be applied or integrated into other functions and broaden their domain of propriety to more use cases.\\\\\\\\\nWhen there exists a non-constant function, $\\varphi$, which gives a rational mapping from one group to another denoted as $\\varphi$ : $\\varepsilon$ $\\rightarrow$ $\\varepsilon\\prime$. This mapping from $\\varepsilon$ to $\\varepsilon\\prime$ has degree $n$. Where there is this separable isogeny, then exists a mapping from $\\varepsilon$ to $\\varepsilon\\prime$, which is known as the dual isogeny, $\\hat{\\varphi}$, where both functions have degree $n$. The dual isogeny is conveyed as $\\hat{\\varphi}$ : $\\varepsilon\\prime$ $\\rightarrow$ $\\varepsilon$ of degree $n$. The isogeny $\\hat{\\varphi}$ here is known as the dual of $\\varphi$, such that $\\hat{\\varphi}$ $\\circ$ $\\varphi$ is the multiplication by $n$, where $n$ = $\\hat{\\varphi}$ $\\circ$ $\\varphi$, from $\\varepsilon$ to $\\varepsilon\\prime$. This dual isogeny has certain properties which allow for the two way transportation of functions between curves. These can be exploited to provide abstraction of protocols where it would otherwise be inapplicable.\n\n\\subsubsection {Curve mappings}\nAs curve models $\\varepsilon_{a,d}$; ${M}_{a,\\frac{2-4d}{a}}$; $\\jmath_{a^{2},a-{2d}}$, have different implementation features we can utilise these relationships to achieve the implementation we desire, namely a prime order curve. It is possible to construct prime order curves using the Montgomery and Edwards curve forms by transporting encoding to and from the Jacobi quartic, via isogenies. The functions for cofactor compression would typically be used on the Jacobi quartic form, by means of canonically selecting outputs for curve points. Now this selection process can be applied to the Edwards and Montgomery form by integrating it to the function which maps between them. \\\\\\\\ \n\n\\subsubsection{Encoding types}\n\\section{Zerocaf}\nAs is previously explained our curve has a base field which is the scalar field of Curve25519, to allow for the use of efficient Zero Knowledge  on operations within a circuit. the difficulty of breaking cryptographic systems stems solely from the hardness of the mathematical problems on which they are based. However, this proves not to be the case in practical implementations because of side channel attacks, which target the implementation as medium of encoding the cryptography - to circumvent these attacks, the operations need to be performed in constant time. The use of Edwards curves results in a uniform implementation which better facilitates these constant time operations.  The Edwards form of a curve is considered complete, as any two inputs, given as x and y, provide a correct result. Whereas in circuit operations can greater benefit from variable time implementations, as they perform faster. They can be applied when there is no secret data to protect, as they may lead to leakage of data. We therefore present an implementation which performs statement proofs in constant time with high security, and verification in variable time and high speed. \\\\ \n\n\n\n\n\\section{Future work}\nR1CS optimisation for constraints \nFurther isogeny use cases \n\n\\section{Conclusion}\n \n\\section{Acknowledgements}\nWe would like to give special thanks to Henry de Valence for his personalised help in understanding the Ristretto Protocol and being so responsive for questions regarding the implementation. We would also like to show our strong appreciation for Marta Bellés Muñoz for her contributions with the discrete log based theory used in the understanding of this project. \n\n\n\\newpage\n\n\n\n\\begin{thebibliography}{99}\n\n\\bibitem{c1} Stanford University, University College London and BlockStream, Benedikt Bünz, Johnathan Bootle, Dan Boneh, Andrew Polestra, Pieter Wuille and Greg Maxwell. Bulletproofs: Short Proofs for Confidential Transactions and More.\\\\ https://eprint.iacr.org/2017/1066.pdf\n\\bibitem{c2} Shafi Goldwasser, Silvio Micali, and Charles Rackoff. The knowledge complexity of interactive\nproof-systems (extended abstract). In 17th Annual ACM Symposium on Theory of Computing\n(STOC’85), pages 291–304, 1985.\"\n\\bibitem{c3} Pedersen T.P. (1992) Non-Interactive and Information-Theoretic Secure Verifiable Secret Sharing. In: Feigenbaum J. (eds) Advances in Cryptology — CRYPTO ’91. CRYPTO 1991. Lecture Notes in Computer Science, vol 576. Springer, Berlin, Heidelberg\n\\bibitem{c4} Isis Lovecruft and Henry de Valence. Ristretto. https://Ristretto.group/Ristretto.html\n\\bibitem{c5} Mike Hamburg : Deacaf. November, 2015. https://eprint.iacr.org/2015/673.pdf\n\\bibitem{c6} Feng Hao, Thales E-Security, Cambridge, UK https://eprint.iacr.org/2010/149.pdf\n\\bibitem{c7}Robert Dijkgraaf: Mirror Symmetry and Elliptic Curves, university of Amsterdam, November 15, 2002\n\\bibitem{c8} Tehcnological University of Visvesvaraya, Jnana Sangama https://www.academia.edu/8777556/\n\n\\end{thebibliography}\n\n\n\n\n\\end{document}", "meta": {"hexsha": "ba62d960a8f225786623a428df5327aa44f74a58", "size": 27497, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/main.tex", "max_stars_repo_name": "3for/dusk-zerocaf", "max_stars_repo_head_hexsha": "0c5db6b1072a537e9e9d683ed0502d007e65e45a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/main.tex", "max_issues_repo_name": "3for/dusk-zerocaf", "max_issues_repo_head_hexsha": "0c5db6b1072a537e9e9d683ed0502d007e65e45a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/main.tex", "max_forks_repo_name": "3for/dusk-zerocaf", "max_forks_repo_head_hexsha": "0c5db6b1072a537e9e9d683ed0502d007e65e45a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-01T02:48:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-01T02:48:26.000Z", "avg_line_length": 168.6932515337, "max_line_length": 2364, "alphanum_fraction": 0.7898679856, "num_tokens": 6161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.4649015713733884, "lm_q1q2_score": 0.3204592703345866}}
{"text": "\\section{The Trust Graph}\n  We now engage in the formal description of the proposed system, accompanied by helpful examples.\n  \\subimport{common/definitions/}{gamegraph.tex}\n  \\noindent The nodes represent the players, the edges represent the existing direct trusts and the weights represent the\n  amount of value attached to the corresponding direct trust. As we will see, the game evolves in turns. The subscript of the\n  graph represents the corresponding turn.\n  \\subimport{common/definitions/}{players.tex}\n  \\noindent Each node has a corresponding non-negative number that represents its capital. A node's capital is the total value\n  that the node possesses exclusively and nobody else can spend.\n  \\subimport{common/definitions/}{capital.tex}\n  \\noindent The capital is the value that exists in the game but is not shared with trusted parties. The capital of $A$ can be\n  modified only during her turns, according to her actions. No capital can be added in the course of the game through external\n  means.\n\n  We also define a player's assets to be the sum of her capital and her total outgoing trust.\n\n  \\subimport{thesis/definitions/}{assets.tex}\n  \\noindent We consider the outgoing trust of a player as part of her assets. The formal definition of direct trust follows:\n  \\subimport{common/definitions/}{directtrust.tex}\n  \\noindent This definition agrees with the title of this paper and coincides with the intuition and sociological experimental\n  results of \\cite{kmrs} that the trust $Alice$ shows to $Bob$ in real-world social networks corresponds with the extent of\n  danger in which $Alice$ is willing and able to expose herself to in order to help $Bob$. An example graph with its\n  corresponding transactions in the UTXO can be seen below.\n\n  \\subimport{common/figures/}{utxo.tikz}\n\n  \\noindent Any algorithm that has access to the graph $\\mathcal{G}_j$ has implicitly access to all direct trusts of this\n  graph.  We use the notation $N^{+}(A)$ to refer to the nodes directly trusted by $A$ and $N^{-}(A)$ for the nodes that\n  directly trust $A$. We also use the notation $in_{A, j}, out_{A, j}$ to refer to the total incoming and outgoing direct\n  trust respectively. For a reference of common definitions, see the Appendix.\n", "meta": {"hexsha": "86513e00eee7909b4aab0bd16ce4205260eff6db", "size": 2247, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/graph.tex", "max_stars_repo_name": "dionyziz/DecentralizedTrust", "max_stars_repo_head_hexsha": "60f65bff00041e7e940491913bd4ca3f11bf22d9", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2017-03-15T14:33:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-01T14:07:45.000Z", "max_issues_repo_path": "thesis/graph.tex", "max_issues_repo_name": "dionyziz/DecentralizedTrust", "max_issues_repo_head_hexsha": "60f65bff00041e7e940491913bd4ca3f11bf22d9", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2017-03-07T12:25:26.000Z", "max_issues_repo_issues_event_max_datetime": "2017-07-31T14:42:20.000Z", "max_forks_repo_path": "thesis/graph.tex", "max_forks_repo_name": "dionyziz/DecentralizedTrust", "max_forks_repo_head_hexsha": "60f65bff00041e7e940491913bd4ca3f11bf22d9", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-03-07T10:49:58.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-28T06:32:33.000Z", "avg_line_length": 72.4838709677, "max_line_length": 126, "alphanum_fraction": 0.7730307076, "num_tokens": 523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.5273165233795672, "lm_q1q2_score": 0.32043083010208795}}
{"text": "\\section{Inter Rater Agreement}\n\\label{chp:fundamentals:sec:inter_rater_agreement}\nMany \\ac{ML} models require a dataset which is used to train them.\nThis data is often generated by multiple raters which assign a label to each datapoint.\nThe used dataset directly influences the \\ac{ML} model \\parencite{Gray:2011} and therefore, well designed research studies must include mechanisms to capture \\ac{IRA} \\parencite{McHugh:2012}.\n\nThis section gives an introduction to different \\ac{IRA} metrics and their applications.\n\n\\input{chapters/02_fundamentals/sections/inter_rater_agreement/subsections/cohens_kappa}\n\\input{chapters/02_fundamentals/sections/inter_rater_agreement/subsections/scotts_pi}\n\\input{chapters/02_fundamentals/sections/inter_rater_agreement/subsections/fleiss_kappa}\n\\input{chapters/02_fundamentals/sections/inter_rater_agreement/subsections/free_marginal_multirater_kappa}\n", "meta": {"hexsha": "917d923fd6ce915af7864bad0002cdd0ddf86a06", "size": 892, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/02_fundamentals/sections/inter_rater_agreement/inter_rater_agreement.tex", "max_stars_repo_name": "HaaLeo/vague-requirements-thesis", "max_stars_repo_head_hexsha": "f9bb53c6f17c2cd1731531ad2a68dd53d72e52e9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/02_fundamentals/sections/inter_rater_agreement/inter_rater_agreement.tex", "max_issues_repo_name": "HaaLeo/vague-requirements-thesis", "max_issues_repo_head_hexsha": "f9bb53c6f17c2cd1731531ad2a68dd53d72e52e9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/02_fundamentals/sections/inter_rater_agreement/inter_rater_agreement.tex", "max_forks_repo_name": "HaaLeo/vague-requirements-thesis", "max_forks_repo_head_hexsha": "f9bb53c6f17c2cd1731531ad2a68dd53d72e52e9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 68.6153846154, "max_line_length": 191, "alphanum_fraction": 0.8464125561, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.3204308301020879}}
{"text": "\\section*{Materials and Methods}\n\\label{sec:M&M}\n\n\\subsection*{Data Provenance}\n\n\\subsubsection*{Growth Data}\nThe first data set is an inventory of all trees over 10cm in Diameter at Breast Height (DBH), i.e. measured at 1.3m high, in nine 1-ha plots in French Guiana (see map~\\autoref{fig:map}). In each plot, tree diameters were measured every two or five years depending on the plot.\n\nWe selected a common measured period between 2001 and 2013 comprising a total of 3549 trees; we estimated annual growth rate (AGR) in diameter by fitting a linear regression of DBH over years. The slope of the regression gave us an average AGR for each followed tree on the comprised \n\n\n\\subsubsection*{Trait Data}\n\nThe second data set was a collection of five functional traits (see~\\autoref{tab:seltraits}) extracted from a bigger database \\citep{baraloto_decoupled_2010} on the same trees. Selected traits can be seen in two orthogonal axes of variations: leaf and stem economics spectra, contrasting different ecological strategies~\\citep{westoby_leaf-height-seed_1998, baraloto_decoupled_2010}.\n\n\\textbf{Leaf economics spectrum.} Specific Leaf Area (SLA) is the photo-sensitive area per unit of dry mass of the leaf; high SLA underlines investment on high light-capturing leaves that have a short payback time per gram of dry matter invested; while low SLA reflects strategies with less light-capturing leaves and longer payback time that may appear competitive in some conditions. Total leaf chlorophyll content reflects the global strategy of the plant of having resource-expansive leaves with high payback or resource-cheap leaves with lower payback~\\citep{coste_assessing_2010}. Laminar toughness measures the resistance of a leaf to pinching, high toughness values correlates with low herbivory rate, it correlates with defense strategy~\\citep{westoby_leaf-height-seed_1998}.\n\n\\textbf{Stem economics spectrum.} Wood density underlines different ecological strategy for trees, a low wood density makes wood less stable and less better protected against herbivory but cheap volumetric construction cost because of low resource requirements; while a high wood density makes the tree more stable but with higher construction cost, meaning a lower growth~\\citep{chave_towards_2009}. Trunk bark thickness associate with defense strategies in neotropical forests, thicker bark provides higher resistance to pathogens and herbivores~\\citep{paine_functional_2010}.\n\n\\subsection*{Statistical analyses}\n\n\\subsubsection*{How are intra-specific variabilities structured compared to inter-specific variabilities?}\n\nTo understand how inter-specific variability contrasted with intra-specific variability, we partitioned the variance of each trait and performance using ANalyses Of VAriances (ANOVAs) with a species term as follow:\n\\begin{subequations}\n\t\\begin{align}\n\t\\label{eq:anovatrait}\n\t\\text{Tr}_{s, i} &= \\mu_s + \\epsilon_i\\\\\n\t\\label{eq:anovaagr}\n\t\\text{AGR}_{s, i} &= \\overline{\\text{AGR}_{s}} + \\epsilon'_i,\n\t\\end{align}\n\\end{subequations}\nwith $\\text{Tr}_{s, i}$, the trait of individual $i$ of species $s$; $\\mu_s$ the mean trait of species $s$; $\\epsilon_i$ the individual trait error term with a Gaussian distribution; $\\text{AGR}_{s, i}$ the AGR of individual $i$ of species $s$; $\\overline{\\text{AGR}_{s}}$ the average AGR of species $s$; $\\epsilon'_i$ the individual AGR error term and $\\epsilon_i \\sim \\mathcal{N}(0, \\sigma^2), \\epsilon'_i \\sim \\mathcal{N}(0, \\sigma'^2)$. The explained variance by the species effect can then be expressed by the proportion of group sum of squares over the total sum of squares. We considered the residual sum of squares as being the individual variance plus white noise. We partitioned the variance similarly for AGR.\n\n\\subsubsection*{How does trait intra-specific variability influence radial growth?}\n\nIn order to understand the influence of trait intra-specific variability on radial growth, we modeled AGR with a mixed linear model of traits and other factors. Based on~\\citet{herault_functional_2011} ontogenical model, we used fixed terms $DBH$ and $\\log(DBH)$, because they capture well the hump shape of growth during ontogeny for tropical trees. As they did, we modeled $\\log(AGR + 1)$ because of data high heteroscedasticity. We added a random intercept for species effect to take inter-specific variability into account, this effect also influenced the slopes of $DBH$ and $\\log(DBH)$ terms. We also added a random intercept plot effect to take inter-plot variability into account. Then depending on the hypothesis tested various fixed terms were added to the model:\n\n\\begin{align}\n\t\\label{eq:growth_mod}\n\t\\log(\\text{AGR}_{p, s, i} + 1) =& \\prescript{0}{}\\theta + \\prescript{0}{}\\gamma_s + \\gamma_p \\nonumber \\\\\n\t\t&+ (\\prescript{1}{}\\theta + \\prescript{1}{}\\gamma_s) \\times \\text{DBH} \\nonumber \\\\\n\t\t&+ (\\prescript{2}{}\\theta + \\prescript{2}{}\\gamma_s) \\times \\log(\\text{DBH}) \\nonumber \\\\\n\t\t&+ \\delta + \\epsilon_i,\n\\end{align}\nwith $\\epsilon_i \\sim \\mathcal{N}(0, \\prescript{3}{}\\theta)$ the individual residual,\nwhere $\\text{AGR}_{p, s, i}$ is the AGR of tree $i$ of species $s$ in plot $p$; $\\prescript{0}{}\\theta \\dots \\prescript{3}{}\\theta$ are parameters to be estimated; $\\prescript{0}{}\\gamma_{s} \\dots \\prescript{2}{}\\gamma_s$ and $\\gamma_p$ follow a zero-centered Gaussian distribution with unknown variances $\\prescript{0}{}\\sigma^2_s \\dots \\prescript{2}{}\\sigma^2_s$ and $\\sigma^2_p$. $\\text{Tr}_s$ is the average trait value for species $s$.\n\nWe tested different hypotheses through the $\\delta$ term in~\\autoref{eq:growth_mod}. If we position an individual relative to its species mean, we can compare them on a hierarchy of traits, and the relevant variable is the hierarchical distance between individual trait and species average trait. We may also hypothesized as~\\citet{kunstler_competitive_2012} did for competition, that the relevant relation for AGR would be the absolute distance. We obtain two models that have to be compared with models having only the specific trait or the individual trait.\n\\begin{equation}\n\\label{eq:delta}\n\\delta = \\left\\{\n\t\\begin{array}{lll}\n\t\t\\prescript{4}{}\\theta\\times \\text{Tr}_s & \\text{Species Average} &  \\\\\n\t\t\\prescript{4}{}\\theta \\times \\text{Tr}_s & + \\prescript{5}{}\\theta \\times(\\text{Tr}_i - \\text{Tr}_s) & \\text{Hierarchical Dist.} \\\\\n\t\t\\prescript{4}{}\\theta \\times \\text{Tr}_s & + \\prescript{5}{}\\theta' \\times \\vert \\text{Tr}_i - \\text{Tr}_s \\vert & \\text{Absolute Dist.} \\\\\n\t\t\\prescript{4}{}\\theta' \\times \\text{Tr}_i & \\text{Individual Trait} & \\\\\n\t\\end{array}\n\\right.\n\\end{equation}\n\n\n $\\text{Tr}_s$ the species average value, with a parameter $\\prescript{4}{}\\theta$; $\\text{Tr}_i - \\text{Tr}_s$ the hierarchical distance of individual trait value $\\text{Tr}_i$ to species average trait value $\\text{Tr}_s$; or $\\vert \\text{Tr}_i - \\text{Tr}_s \\vert$ the absolute distance to species average trait; and $\\text{Tr}_i$ the individual trait value.\n\n\\subsubsection*{Intra-specific variability vs. inter-specific variability effects on performance for each trait}\n\nIntra-specific variability and inter-specific variaibilty may have different impacts on performance. For each trait we selected the growth model from~\\autoref{eq:delta} that had the highest adapted R-squared for mixed models~\\citep{nakagawa_general_2013}, i.e. the model that best described our data. Using them we predicted AGR based on a 5\\%-95\\% range of species average and hierarchical distance.\n\n\\subsection*{Data analysis}\n\nAll data analyses were made using \\texttt{R} \\citep{R_language} version 3.2.0 (2015-04-16), plots were made with \\texttt{ggplot2} \\citep{ggplot2_pkg}. We fit mixed-models with \\texttt{lme4} \\texttt{R} package \\citep{lme4_pkg} 1.1-7 and computed adapted R-squared for mixed-models \\citep{nakagawa_general_2013} implemented in \\texttt{MuMIn} \\texttt{R} package \\citep{mumin_pkg} version 1.13.4.\n\n\\begin{table*}\n\t\\begin{center}\n\t\t\\begin{tabular}{lccc}\n\t\t\\hline\n\t\tTrait Name & Units & Role \\\\\n\t\t\\hline\n\t\tTrunk bark thickness & mm & Stem economics \\\\\n\t\tXylem density (wood density) & $\\text{g}.\\text{cm}^{-3}$ & Stem economics \\\\\n\t\tSpecific Leaf Area (SLA) & $\\text{cm}^2.\\text{g}^{-1}$ & Leaf economics \\\\\n\t\tLaminar total chlorophyll & $\\text{µm}.\\text{mm}^{-2}$  & Leaf economics \\\\\n\t\tLaminar toughness & N & Leaf economics \\\\\n\t\t\\hline\n\t\t\\end{tabular}\n\t\t\\caption{\\textbf{Selected functional traits.} Stem and Leaf Economics Spectrum are defined as in~\\citep{baraloto_decoupled_2010}, the two axes unravel distinct ecological strategies. Leaf economics spectrum contrasts} \n\t\t\\label{tab:seltraits}\n\t\\end{center}\n\\end{table*}\n", "meta": {"hexsha": "c081f32729c7f5c143ac53584e298435f0569ede", "size": 8623, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "2-MaterialsAndMethods.tex", "max_stars_repo_name": "Rekyt/report-ecofog-2015", "max_stars_repo_head_hexsha": "145863f6c43200f3348ec5a82ca750eb348145ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2-MaterialsAndMethods.tex", "max_issues_repo_name": "Rekyt/report-ecofog-2015", "max_issues_repo_head_hexsha": "145863f6c43200f3348ec5a82ca750eb348145ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2-MaterialsAndMethods.tex", "max_forks_repo_name": "Rekyt/report-ecofog-2015", "max_forks_repo_head_hexsha": "145863f6c43200f3348ec5a82ca750eb348145ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 95.8111111111, "max_line_length": 784, "alphanum_fraction": 0.7601762728, "num_tokens": 2381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6076631556226292, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3204308226087817}}
{"text": "%\\begin{center}SECTION\\end{center}\n\n\\chapter{CONCLUSIONS}\n\n\\section{CHARACTERIZATION OF TRANSPORT REGIME TRANSITIONS IN NON-CONSERVATIVE RANDOM MEDIA}\n\nThe purpose of the first portion of this dissertation was to characterize the effect of absorption and gain in ballistic, diffusive, and localized transport regimes. Particle and wave-based transport models were studied in one dimension (1D) and quasi-1D geometries. \n\nAn investigation of the ratio of transmission to energy in the system, $T/{\\cal E}$, was performed in 1D using theoretical and numerical methods~\\cite{2010_Payne_TE}. %~(c.f.~Section \\ref{sec:TE2009}). \nThe numerical model uses the transfer matrix method~\\cite{1981_MacKinnon_scaling} with self-embedding~\\cite{1999_yamilov_selfembed} to simulate layers of dielectric material with random widths. Since diffusion cannot occur in 1D, the response of the parameter $T/{\\cal E}$ in the regime of Anderson localization when gain is present was found. A decrease of $T/{\\cal E}$ from the value given by the classical un-renormalized diffusion coefficient may be attributed to wave-interference localization effects. Although $T/{\\cal E}$ does not diverge as the random lasing threshold is approached, there is a dependence on the position of the center of localization. This position dependence is closely related to the existance of necklace states~\\cite{1987_Pendry}. \n\nTo investigate the transition from diffusion to Anderson localization, the previous numerical model was extended to quasi-1D geometry. To guide our efforts we developed a phase space diagram with 15 different transport regimes~\\cite{2010_Yamilov_Regimes}. A way of characterizing which regime a given system is in was clearly needed. In the process of using the numerical model in this geometry, we showed that evanescant channels do not need to be included in simulations of passive media~\\cite{2010_Payne_closed}. The effect of evanescant channels is renormalize the transport mean free path while conforming to single parameter scaling. \n\nA parameter related to $T/{\\cal E}$, the position dependent diffusion coefficient $D(z)$, was investigated for use in characterizing the multiple transport regimes in quasi-1D non-conservative random media~\\cite{2010_Payne_PRL}. Our results indicate that $D(z)$ may serve as a useful criterion for the enumerated transport regimes. \n\n\\section{ANALYSIS OF DETERMINISTIC APERIODIC STRUCTURES}\n\n\n\nAlthough random media produces novel features, these systems lack easy reproducibility. For applications such as photonic integrated circuits we are interested in novel features unavailable to periodic media while maintaining reproducibility. Thus media correlated disorder is a natural avenue of pursuit. The numerical model used in this dissertation can simulate any arrangement of scatters, making it amenable to aperiodic media. %The same simulation tool used for random media was applied to aperiodic media. \n\nIn the studies of deterministic aperiodic structures (DAS) we focused on the Thue-Morse pattern. This generation algorithm yeilds a singular continuous Fourier transform spectrum with self-similar features. We demonstrated the possibility of mapping the array of micro-cavities in the two dimensional (2D) Thue Morse DAS onto a periodic square lattice~\\cite{2012_Payne_Mapping_2D_TM}. Such mapping allowed us to uniquely identify and enumerate the configurations of nearest and next-nearest neighbors. Thus the original aperiodic structure is reduced to the periodic structure with aperiodic arrangement of the limited set of pairings. \n\nOnce this step was completed, we demonstrated the applicability of the tight binding approach in a deterministic aperiodic array of photonic micro-cavities. Under realistic conditions, we observed hybridization of the modes of individual micro-cavities into the eigenstates of the entire array. Our work adds the tight binding approach to the arsenal of theoretical tools for studying of 2D~Thue-Morse structures as well as for design and analysis of experiments.\n\nThe tight binding model allows us to investigate the size scaling of the density of the optical states in large arrays of optical micro-cavities; monitor the evolution of the spectra; and to study spatial properties of the eigenstates via e.g. the inverse participation ratio. The inverse participation ratio shows coexistence of localized and extended states in the same spectral regions. Some of the extended states have nearly constant intensity across the entire sample. This property makes the considered system extremely promising for practical applications in optical control of light propagation via e.g. wave-front shaping.\n \n\n\n%\\section{TEST OF BORDERS}\n\n%Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Ut purus elit, vestibulum ut, placerat ac, adipiscing vitae, felis. Curabitur dictum gravida mauris. Nam arcu libero, nonummy eget, consectetuer id, vulputate a, magna. Donec vehicula augue eu neque. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Mauris ut leo. Cras viverra metus rhoncus sem. Nulla et lectus vestibulum urna fringilla ultrices. Phasellus eu tellus sit amet tortor gravida placerat. Integer sapien est, iaculis in, pretium quis, viverra ac, nunc. Praesent eget sem vel leo ultrices bibendum. Aenean faucibus. Morbi dolor nulla, malesuada eu, pulvinar at, mollis ac, nulla. Curabitur auctor semper nulla. Donec varius orci eget risus. Duis nibh mi, congue eu, accumsan eleifend, sagittis quis, diam. Duis eget orci sit amet orci dignissim rutrum. Nam dui ligula, fringilla a, euismod sodales, sollicitudin vel, wisi. Morbi auctor lorem non justo. Nam lacus libero, pretium at, lobortis vitae, ultricies et, tellus. Donec aliquet, tortor sed accumsan bibendum, erat ligula aliquet magna, vitae ornare odio metus a mi. Morbi ac orci et nisl hendrerit mollis. Suspendisse ut massa. Cras nec ante. Pellentesque a nulla. Cum sociis natoque penatibus et magnis dis par turient montes, nascetur ridiculus mus. Aliquam tincidunt urna. Nulla ullamcorper vestibulum turpis. Pellentesque cursus luctus mauris. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Ut purus elit, vestibulum ut, placerat ac, adipiscing vitae, felis. Curabitur dictum gravida mauris. Nam arcu libero, nonummy eget, consectetuer id, vulputate a, magna. Donec vehicula augue eu neque. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Mauris ut leo. Cras viverra metus rhoncus sem. Nulla et lectus vestibulum urna fringilla ultrices. Phasellus eu tellus sit amet tortor gravida placerat. Integer sapien est, iaculis in, pretium quis, viverra ac, nunc. Praesent eget sem vel leo ultrices bibendum. Aenean faucibus. Morbi dolor nulla, malesuada eu, pulvinar at, mollis ac, nulla. Curabitur auctor semper nulla. Donec varius orci eget risus. Duis nibh mi, congue eu, accumsan eleifend, sagittis quis, diam. Duis eget orci sit amet orci dignissim rutrum. Nam dui ligula, fringilla a, euismod sodales, sollicitudin vel, wisi. Morbi auctor lorem non justo. Nam lacus libero, pretium at, lobortis vitae, ultricies et, tellus. Donec aliquet, tortor sed accumsan bibendum, erat ligula aliquet magna, vitae ornare odio metus a mi. Morbi ac orci et nisl hendrerit mollis. Suspendisse ut massa. Cras nec ante. Pellentesque a nulla. Cum sociis natoque penatibus et magnis dis par turient montes, nascetur ridiculus mus. Aliquam tincidunt urna. Nulla ullamcorper vestibulum turpis. Pellentesque cursus luctus mauris. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Ut purus elit, vestibulum ut, placerat ac, adipiscing vitae, felis. Curabitur dictum gravida mauris. Nam arcu libero, nonummy eget, consectetuer id, vulputate a, magna. Donec vehicula augue eu neque. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Mauris ut leo. Cras viverra metus rhoncus sem. Nulla et lectus vestibulum urna fringilla ultrices. Phasellus eu tellus sit amet tortor gravida placerat. Integer sapien est, iaculis in, pretium quis, viverra ac, nunc. Praesent eget sem vel leo ultrices bibendum. Aenean faucibus. Morbi dolor nulla, malesuada eu, pulvinar at, mollis ac, nulla. Curabitur auctor semper nulla. Donec varius orci eget risus. Duis nibh mi, congue eu, accumsan eleifend, sagittis quis, diam. Duis eget orci sit amet orci dignissim rutrum. Nam dui ligula, fringilla a, euismod sodales, sollicitudin vel, wisi. Morbi auctor lorem non justo. Nam lacus libero, pretium at, lobortis vitae, ultricies et, tellus. Donec aliquet, tortor sed accumsan bibendum, erat ligula aliquet magna, vitae ornare odio metus a mi. Morbi ac orci et nisl hendrerit mollis. Suspendisse ut massa. Cras nec ante. Pellentesque a nulla. Cum sociis natoque penatibus et magnis dis par turient montes, nascetur ridiculus mus. Aliquam tincidunt urna. Nulla ullamcorper vestibulum turpis. Pellentesque cursus luctus mauris. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Ut purus elit, vestibulum ut, placerat ac, adipiscing vitae, felis. Curabitur dictum gravida mauris. Nam arcu libero, nonummy eget, consectetuer id, vulputate a, magna. Donec vehicula augue eu neque. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Mauris ut leo. Cras viverra metus rhoncus sem. Nulla et lectus vestibulum urna fringilla ultrices. Phasellus eu tellus sit amet tortor gravida placerat. Integer sapien est, iaculis in, pretium quis, viverra ac, nunc. Praesent eget sem vel leo ultrices bibendum. Aenean faucibus. Morbi dolor nulla, malesuada eu, pulvinar at, mollis ac, nulla. Curabitur auctor semper nulla. Donec varius orci eget risus. Duis nibh mi, congue eu, accumsan eleifend, sagittis quis, diam. Duis eget orci sit amet orci dignissim rutrum. Nam dui ligula, fringilla a, euismod sodales, sollicitudin vel, wisi. Morbi auctor lorem non justo. Nam lacus libero, pretium at, lobortis vitae, ultricies et, tellus. Donec aliquet, tortor sed accumsan bibendum, erat ligula aliquet magna, vitae ornare odio metus a mi. Morbi ac orci et nisl hendrerit mollis. Suspendisse ut massa. Cras nec ante. Pellentesque a nulla. Cum sociis natoque penatibus et magnis dis par turient montes, nascetur ridiculus mus. Aliquam tincidunt urna. Nulla ullamcorper vestibulum turpis. Pellentesque cursus luctus mauris.\n\n", "meta": {"hexsha": "ba52797628796f0cb29734480e92065c527eb01e", "size": 10389, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/conclusion.tex", "max_stars_repo_name": "bhpayne/physics_phd_dissertation", "max_stars_repo_head_hexsha": "646123088fdd226e8677e6f3edb8d109be96994e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/conclusion.tex", "max_issues_repo_name": "bhpayne/physics_phd_dissertation", "max_issues_repo_head_hexsha": "646123088fdd226e8677e6f3edb8d109be96994e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/conclusion.tex", "max_forks_repo_name": "bhpayne/physics_phd_dissertation", "max_forks_repo_head_hexsha": "646123088fdd226e8677e6f3edb8d109be96994e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 305.5588235294, "max_line_length": 5680, "alphanum_fraction": 0.8131677736, "num_tokens": 2729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631556226291, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.32043082260878164}}
{"text": "\\documentclass{article}\n\n\n\n\\setlength{\\topmargin}{-0.75in}\n\\setlength{\\textheight}{9in}\n\\setlength{\\textwidth}{6.5in}\n\\setlength{\\oddsidemargin}{0in}\n\\setlength{\\evensidemargin}{0in}\n\n\\begin{document}\n\n\\title{Energy Prediction and Adaptation in flux-e}\n\\author{Jacob Sorber\\\\Matt Brennan}\n\\maketitle\n\n\n\\section{Goal and Premise}\nGiven an energy buffer and source, our obvious goal is to never deplete our resources. Additionally, we want our energy state to remain as stable as possible, as this will give the user the most predictable system response. \\\\\nWe assume that there is periodicity in both the system load and the energy harvesting.  We divide this period in to epochs, and make our state adjustments on these boundaries.  \n\n\\section{Definitions and Data Structures}\n\\begin{eqnarray*}\n{paths\\_trig} & \\equiv & \\mbox{set of triggered paths}\\\\\n{paths\\_timed} & \\equiv & \\mbox{set of timed paths}\\\\\n{period} & \\equiv & \\mbox{length of time over which load and supply repeats}\\\\\n{epoch} & \\equiv & \\mbox{division of a period for which statistics are separately}\\\\\n{states} & \\equiv & \\mbox{set of possible energy states} \\\\\n\\delta_c & \\equiv & \\mbox{cost prediction adjustment dampening factor} \\in(0,1)\\\\\n\\delta_r & \\equiv & \\mbox{revenue prediction adjustment dampening factor} \\in(0,1)\\\\\n\\delta_b & \\equiv & \\mbox{buffer adjustment dampening factor} \\in(0,1)\\\\\n{cost\\_actual} & \\equiv  & \\mbox{actual energy spent during previous epoch}\\\\\n{cost\\_pred}   & \\equiv  & \\mbox{predicted energy cost for previous epoch}\\\\\n{rev\\_actual} & \\equiv  & \\mbox{actual energy acquisition during previous epoch}\\\\\n{rev\\_pred}   & \\equiv  & \\mbox{energy acquisition predicted for previous epoch}\\\\\n{timer\\_level} & \\equiv & \\mbox{percentage of timer range selected} \\\\\n{freq}[{path}][{state}] & \\equiv  &\\mbox{probability of taking a given path in a given state}\\\\\n{load}[{epoch}] & \\equiv & \\mbox{average of loads during given epoch}\\\\\n{energy\\_in}[{epoch}] & \\equiv & \\mbox{average energy revenue during given epoch}\\\\\n{cost\\_static} & \\equiv & \\mbox{minimum energy cost of an epoch (ie, when idle)}\\\\\n{cost}[{path}] & \\equiv & \\mbox{average energy cost of a given path, in addition to }{cost\\_static}\\\\\n{buffer\\_level} & \\equiv & \\mbox{the percent of the buffer's capacity currently in use}\\\\\n{buffer\\_goal} & \\equiv & \\mbox{the percent of the buffer's capacity to aim for}\\\\\n{scale\\_cost} & \\equiv & \\mbox{a scaling factor to the stochastic energy consumption}\\\\\n{scale\\_rev} & \\equiv & \\mbox{a scaling factor to the energy revenue}\\\\\n\\end{eqnarray*}\n\n\n\\section{State Selection}\n\nAt the beginning of each ${epoch}$, we predict the base energy cost and revenue for the next ${period}$ (that is to say, the next ${NUM\\_EPOCHS}$).  Base energy cost is calculated based on the probability of taking a triggered path, and assuming that timed paths are taken at the minimum frequency allowed for the state. A goal is set based on the expected revenue and the ${buffer\\_level}$.  We then select the highest state which will have a cost lower than our goal.\n\nTimer periods remain unselected.  To determine them, we calculate the cost for the same state with maximum frequency for all the active timers.  We find where our goal lies between the minimum and maximum costs, and scale the timers proportionally.\n\n\nMore precisely,\n\n\\begin{eqnarray*}\n{scale\\_rev} & = & 1 + \\left(\\delta_r\\frac{{rev\\_actual}-{rev\\_pred}}{{rev\\_pred}}\\right) \\\\\n{scale\\_cost} & =&  1 + \\left(\\delta_c\\frac{{cost\\_actual}-{cost\\_pred}}{{cost\\_pred}}\\right) \\\\\n{predicted\\_cost}_{min}[{state}]&  =&  \\sum_{e\\in{epoch}}\\sum_{p\\in{paths\\_trig}}\\left[ {freq}[p][{state}] \\cdot {load}[e] \\cdot {cost}[p] \\right] \\cdot {scale\\_cost} +\\\\\n                          &  &  \\sum_{e\\in{epoch}}\\sum_{p\\in{paths\\_timed}}{cost}[p]\\cdot1/{max\\_period}_p \\\\\\\\\n{predicted\\_cost}_{max}[{state}]&  =&  \\sum_{e\\in{epoch}}\\sum_{p\\in{paths\\_trig}}\\left[ {freq}[p][{state}] \\cdot {load}[e] \\cdot {cost}[p] \\right] \\cdot {scale\\_cost} +\\\\\n                          &  &   \\sum_{e\\in{epoch}}\\sum_{p\\in{paths\\_timed}}{cost}[p]\\cdot1/{min\\_period}_p \\\\\\\\\n{predicted\\_revenue}&  =&  \\sum_{e\\in{epoch}} {energy\\_in}[e] \\cdot {scale\\_rev}\\\\\n{goal} & = & {predicted\\_revenue} \\cdot \\delta_b\\left(({buffer\\_level} - {buffer\\_goal}\\cdot{buffer\\_capacity}\\right)\n\\\\\n\\end{eqnarray*}\n\\ttfamily\n${state}$ = ${MAX\\_STATE}$ ;\\\\\nwhile (${predicted\\_cost}_{min} < {goal}$) \\\\\n\\hspace{1cm}${state}$--;\\\\\n\\({timer\\_level} = \\frac{{goal} - {predicted\\_cost}_{min}}{{predicted\\_cost}_{min} - {goal}}\\)\n    \n\\rmfamily\n\n\n\n\n\\section{Path Cost Measurement}\n\nGiven the energy flow through the buffer (implemented as a hardware fuel gauge), and the total consumption of the system (implemented as a software fuel gauge), we are able to keep track of the power being consumed during execution of paths.  We allow for the possibility of parallel path execution by attributing equal parts of the total power consumption to each active path.  Acknowledging that this method may result in skewed values of ${cost}[{path}]$, we argue probabilistically that this will have nominal effect on our overall energy prediction.  If two paths with large energy consumption differences have a high enough probability of running in parallel enough to skew each other's results, that same high probability infers that it is unnecessary to distinguish between their values.\n\n\\end{document}\n", "meta": {"hexsha": "940fd1ed0adc63ede7d9f27db2c567c819fb423f", "size": 5384, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "eon/eon/doc/energyprediction.tex", "max_stars_repo_name": "tinyos-io/tinyos-3.x-contrib", "max_stars_repo_head_hexsha": "3aaf036722a2afc0c0aad588459a5c3e00bd3c01", "max_stars_repo_licenses": ["BSD-3-Clause", "MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-28T20:35:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-28T20:35:09.000Z", "max_issues_repo_path": "eon/eon/doc/energyprediction.tex", "max_issues_repo_name": "tinyos-io/tinyos-3.x-contrib", "max_issues_repo_head_hexsha": "3aaf036722a2afc0c0aad588459a5c3e00bd3c01", "max_issues_repo_licenses": ["BSD-3-Clause", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eon/eon/doc/energyprediction.tex", "max_forks_repo_name": "tinyos-io/tinyos-3.x-contrib", "max_forks_repo_head_hexsha": "3aaf036722a2afc0c0aad588459a5c3e00bd3c01", "max_forks_repo_licenses": ["BSD-3-Clause", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 63.3411764706, "max_line_length": 795, "alphanum_fraction": 0.713781575, "num_tokens": 1529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.3204196065939125}}
{"text": "\\chapter{Simulated Annealing}\r\n\\section{Introduction}\r\nThe Simulated Annealing search algorithm is examined in this chapter, looking  initially at the strategy options and configuration choices. The results section shows the performance of the algorithm in preliminary trials with a range of annealing schedules before presenting the results of the main trials. \r\n\r\n\\section{Search Strategy Options}\r\nTo be consistent with efforts of Random Search and Hill Climbing we again limit each trial to 25000 evaluations of the objective function. The operators used for Simulated Annealing are those that were used with Hill Climbing, however we have reduced the probability of occurrence of the shrink and grow operators based on our observations regarding duplication of solutions as discussed in Section~\\ref{duplicate_solutions}.\r\n\r\nThe approach in general is similar to Hill Climbing, as the operators have been selected to allow fine-grained exploration of the search space while exploiting the capability of Simulated Annealing to avoid the pitfalls of local optima. The principle strategy choice for Simulated Annealing will be the selection of a suitable annealing schedule (see Section~\\ref{schedule}), this is covered in detail in Section~\\ref{schedule_selection}.\r\n\r\n\r\n\r\n\\section{Experimental Conditions}\r\nTable~\\ref{sa_param_table} shows the parameters used to configure Simulated Annealing. Symbolic Integration, Santa Fe and Blocks use initial Genome lengths of 100 while Symbolic Regression uses an initial length of 200. A temperature change rate of 0.95 is used to reduce the temperature on each iteration. A minimum temperature of \\emph{0} is used to halt the annealing schedule. For a more complete explanation Section~\\ref{sa_algorithm} provides a step-by-step guide to the algorithm.\r\n\r\n\r\n\r\n\\begin{table}[!hbp]\r\n\\begin{center}\r\n\\begin{tabular}{|l|l|l|l|l|}\r\n\\hline\r\nParameter &\\multicolumn{4}{l|}{Problems}\\\\\r\n\\cline{2-1} \\cline{3-1} \\cline{4-1} \\cline{5-1} \r\n & Sym Int & Santa Fe & Blocks & Sym Reg  \\\\\r\n\\hline\r\nNumber of Trials & 1000 & 1000 & 1000 & 1000  \\\\\r\nNumber of Objective & & & & \\\\ \r\nFunction Evaluations  & 25000 & 25000 & 25000 & 25000 \\\\\r\nInitial Genome Length & 100 & 100 & 100 & 200  \\\\\r\nVariation Range  & 10\\% & 10\\% & 10\\% & 10\\%  \\\\\r\nZero Improvement Accept  & off & off & off & off  \\\\\r\nProbability of Selecting & & & & \\\\\r\nShrink Operator  & .05 & .05 & .05 & .05  \\\\\r\nProbability of Selecting & & & & \\\\\r\nGrow Operator  & .05 & .05 & .05 & .05  \\\\\r\nProbability of Selecting & & & & \\\\\r\nForce-up Operator  & .45 & .45 & .45 & .45  \\\\\r\nProbability of Selecting & & & & \\\\\r\nForce-down Operator  & .45 & .45 & .45 & .45 \\\\\r\nTemperature Change Rate & 0.95 & 0.95 & 0.95 & 0.95  \\\\\r\nMinimum Temperature & 0 & 0 & 0 & 0  \\\\\r\n\\hline\r\n\\end{tabular}\r\n\\caption{\\label{sa_param_table} Parameters used for the Simulated Annealing Search Algorithm.}\r\n\\end{center}\r\n\\end{table}\r\n\r\n\r\n\\section{Establishing an Annealing Schedule}\r\n\\label{schedule_selection}The establishment of an appropriate annealing schedule for each of the problems centres on selecting the desired level of probability for acceptance of a dis-improving solution. \r\nAt a temperature $t$, the probability $P$ for a change  in energy of magnitude $\\delta E$ is given by \r\n\r\n\\large\r\n\\begin{displaymath}\r\nP(\\delta E) = e ^{ \\frac{-\\delta E}{kt}}\r\n\\end{displaymath}\r\n\\normalsize\r\n\r\nFigure~\\ref{santafe_accept_prob_score_delta} shows the change in the probability of accepting a dis-improving solution for a range of score deltas. Three different temperatures have been shown. If it was possible to predict the type of score deltas we were likely to see in the course of a trial then we could usefully employ this information to select a suitable starting temperature. We know from the analysis of the Hill Climbing results that solutions often emerge from areas of the solution landscape where scores are low score. This might suggest that it is reasonable to accept large dis-improving deltas late in a trial. However this policy would also have the consequence of having us accept even larger score deltas early in a trial, this could force the search to remain trapped in sub optimal regions of the search space.\r\n\r\nThis is better illustrated in Figure~\\ref{santafe_accept_prob_score_temp} which again shows the change in the probability of accepting a dis-improving solution but this time it has been plotted against increasing temperature. Three plots for score deltas of 1, 5 and 10 have been included. Again we see some of the trade offs in this graph a high starting temperature exposes the search to higher probabilities of moving into low scoring regions of the search space while starting with a very low temperatures might leave the search unable to effectively explore the search space because of a overly captious approach.\r\n\r\n\r\n\\begin{figure}[]\r\n\\centerline{\\hbox{\r\n\\psfig{file=Chapter7/graphs/accept_prob_score_delta.ps,width=4in}}}\r\n\\caption[Probability of accepting a dis-improving Solution for a Range of Score Deltas]{Probability of accepting a dis-improving Solution for a Range of Score Deltas at three different Temperatures on the Santafe Trail Problem.}\r\n\\label{santafe_accept_prob_score_delta}\r\n\\end{figure}\r\n\r\n\r\n\\begin{figure}[]\r\n\\centerline{\\hbox{\r\n\\psfig{file=Chapter7/graphs/accept_prob_temp_change.ps,width=4in}}}\r\n\\caption[Probability of accepting a dis-improving Solution for a Range of Temperatures]{Probability of accepting a dis-improving Solution for a Range of Temperatures at three different Score Deltas on the Santafe Trail Problem.}\r\n\\label{santafe_accept_prob_score_temp}\r\n\\end{figure}\r\n\r\nIn order to get some indication of suitable  annealing schedules for the problems a limited number of runs were first performed for a range of starting temperatures. The number of iterations at each temperature accordingly  varied in order to maintain our limit of 25000 evaluations of the objective function in a single trial.\r\nThe results of these preliminary runs plus the results of the extended runs are presented in the next section.\r\n\r\n\r\n\r\n\\section{Results}\r\n\r\nTables~\\ref{sa_symint_sched_table},~\\ref{sa_santafe_sched_table} and~\\ref{sa_blocks_sched_table} show the results from the preliminary trials used to determine the appropriate annealing schedule for Symbolic Integration, Santa Fe and Blocks respectively. Similar runs on the Symbolic Regression problem failed to find any correct solutions. \r\n\r\nThese preliminary trials consisted of 500 runs for each start temperature. The table shows the starting temperature and  the number of successes achieved.\r\n\r\nFor the case of Symbolic Integration the success rate appears to peak at 11\\% for starting temperatures of 1 with the success rate trailing off either side of this. On the Santa Fe problem we see a plateau of similar scores for temperatures of 1 or less with a significant fall off in success rates for higher starting temperatures. The schedules for Blocks follows a  similar pattern to that of Santa Fe showing higher success rates at starting temperatures of one or less. The Symbolic Regression problem was not solved in any of the preliminary trials.\r\n\r\n\r\n  \r\n\\begin{table}[h]\r\n\\begin{center}\r\n\\begin{tabular}{|l|l|}\r\n\\hline\r\nStarting Temperature & Successful Runs \\\\\r\n\\hline\r\n0.3 & 10\\% \\\\\r\n0.1 & 6\\% \\\\\r\n1   &  11\\% \\\\\r\n5   &  5\\% \\\\\r\n10  & 2\\% \\\\\r\n\\hline\r\n\\end{tabular}\r\n\\caption{\\label{sa_symint_sched_table} Results from 500 trials of Simulated Annealing on the Symbolic Integration Problem for a Range of Starting Temperatures.}\r\n\\end{center}\r\n\\end{table}\r\n\r\n\r\n\r\n\\begin{table}[h]\r\n\\begin{center}\r\n\\begin{tabular}{|l|l|}\r\n\\hline\r\nStarting Temperature &  Successful Runs \\\\\r\n\\hline\r\n0.3   &  17\\%\\\\\r\n0.1   &  20\\%\\\\\r\n1    &  19\\% \\\\\r\n5    &  4\\% \\\\\r\n10   &  5\\% \\\\\r\n\\hline\r\n\\end{tabular}\r\n\\caption{\\label{sa_santafe_sched_table} Results from 500 trials of Simulated Annealing on the Santa Fe Trail Problem for a Range of Starting Temperatures.}\r\n\\end{center}\r\n\\end{table}\r\n\r\n\\begin{table}[h]\r\n\\begin{center}\r\n\\begin{tabular}{|l|l|}\r\n\\hline\r\nStarting Temperature &  Successful Runs \\\\\r\n\\hline\r\n0.1   &   11\\%\\\\\r\n0.3    &   13\\%\\\\\r\n1     &   12\\%\\\\\r\n5     &   6\\%\\\\\r\n10    &   9\\%\\\\\r\n\\hline\r\n\\end{tabular}\r\n\\caption{\\label{sa_blocks_sched_table} Results from 500 trials of Simulated Annealing on the Blocks Problem for a Range of Starting Temperatures.}\r\n\\end{center}\r\n\\end{table}\r\n\r\n\r\nTable~\\ref{sa_results_table} provides a summary of the final results for Simulated Annealing. 1000 runs were performed using most successful starting temperature of 1 from the preliminary trials. Symbolic Regression was not solved in any of the attempts, however Symbolic Integration and Blocks have similar success rates scoring 11\\% and 13\\% respectively, while Santa Fe scores 21\\%.\r\nWhile the algorithm is more successful on the Symbolic Integration and Santa Fe problems than Hill Climbing, the overall results are still poor relative to those of Random Search. \r\n\r\n\\begin{table}[h]\r\n\\begin{center}\r\n\\begin{tabular}{|l|l|}\r\n\\hline\r\nProblem & Successful Runs \\\\\r\n\\hline\r\nSymbolic Integration & 11\\% \\\\\r\nSanta Fe Trail & 21\\% \\\\\r\nBlocks & 13\\% \\\\\r\nSymbolic Regression & 0\\% \\\\\r\nSpirals & 0\\% \\\\\r\n\\hline\r\n\\end{tabular}\r\n\\caption{ \\label{sa_results_table} Results from the Simulated Annealing Trials.}\r\n\\end{center}\r\n\\end{table}\r\n\r\n\r\n\r\n\r\n\r\n\\section{Characteristics of Solutions found by Simulated Annealing}\r\n\r\nTable~\\ref{sa_results_analysis_table} shows details of the solutions found by Simulated Annealing, wrapping features prominently in Santa Fe and Blocks. The average solution length for Santa Fe is 58 codons of which 48 are expressed. Symbolic Integration has solutions with an average genome length of 76 of which only 19 are expressed. An aspect of the results from the Blocks problem is that the number of expressed codons was 91, which is considerably greater than the average number of codons in a solution at 54. This aspect of the Block's results is caused by multiple wrap events where the codons are repeatedly re-used until a successful solution is found.  \r\n\r\n\r\n\\begin{table}[h]\r\n\\begin{center}\r\n\\begin{tabular}{|l|l|l|l|l|}\r\n\\hline\r\nFeature & Sym Int & Santa Fe & Blocks & Sym Reg  \\\\\r\n\\hline\r\nAvg Number of Codons & & & &  \\\\ \r\nin Solution & 76 & 58 & 54 & n/a  \\\\\r\nAvg Number of expressed & & & &  \\\\\r\nCodons in Solution & 19 & 48 & 91 & n/a  \\\\\r\nAvg Number of Solutions & & & &  \\\\\r\nfeaturing Wrapping & 0\\% & 50\\% & 66\\% & n/a  \\\\\r\n\\hline\r\n\\end{tabular}\r\n\\caption{\\label{sa_results_analysis_table} Analysis of Characteristics from Solutions found by Simulated Annealing.}\r\n\\end{center}\r\n\\end{table}\r\n\r\n\r\n\r\n\r\n\\subsection{Analysis of search trajectory}\r\n\r\nA typical search trajectory for a Simulated Annealing trial is shown in ~\\ref{sa_search1}. In the early stages the algorithm explores areas of both low and high fitness but as the trials progresses we see a steady climb to areas of high fitness as the decreasing temperature reduces the probability of selecting dis-improving solutions.\r\n\r\n\\begin{figure}[hbp]\r\n\\centerline{\\hbox{\r\n\\psfig{file=Chapter7/graphs/search_trajectory_sa.ps,width=5in}}}\r\n\\caption{\\label{sa_search1}Search Trajectory for a Successful Simulated Annealing Trial}\r\n\\end{figure}\r\n\r\n\r\n\r\n\\section{Summary}\r\nIn this chapter we have looked at Simulated Annealing, a metaheuristic, which models itself on the way crystals form in solids during the cooling process. The principle strategy choice for the method was the selection of a suitable annealing schedule, to assist this selection a number of preliminary trials were performed using a range of starting temperatures. The final results showed unsuccessful attempts on two of the problem, Symbolic Regression and Spirals and low success rates on the other three.\r\n\r\nThe additional capability of Simulated Annealing to avoid sub-optima would appear to have added little or no improvement on the scores achieved by Hill Climbing, leaving it a considerable way behind Random Search. \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "fd7f607cd78d1e961322afbaa6b4a6a1966062d3", "size": 12010, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Content/Masters/Chapter7/chapter7.tex", "max_stars_repo_name": "johnosbb/Grammatical-Evolution", "max_stars_repo_head_hexsha": "95b83a99bfb488281effdcd704f1802138f21dd0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Content/Masters/Chapter7/chapter7.tex", "max_issues_repo_name": "johnosbb/Grammatical-Evolution", "max_issues_repo_head_hexsha": "95b83a99bfb488281effdcd704f1802138f21dd0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Content/Masters/Chapter7/chapter7.tex", "max_forks_repo_name": "johnosbb/Grammatical-Evolution", "max_forks_repo_head_hexsha": "95b83a99bfb488281effdcd704f1802138f21dd0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.3247863248, "max_line_length": 834, "alphanum_fraction": 0.7530391341, "num_tokens": 2969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166195971441, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.3203981545592985}}
{"text": "\\chapter{Analysis}\n\\label{Analysis}\n\nLike any algorithm, we can not define \"the best cryptography method;\" rather, the cryptography algorithm that you use is \nvery case-dependant. In order to find a suitable candidate(s), one must examine the merits of a set of different algorithms.\n\nWhen it comes to cryptography, security is at the root of the question. But how much do you \\textit{really} value security?\nFor some, it may be a matter of \"life or death.\" For others, security is a secondary feature of their program. Maybe you don't\neven care about security? This can surely be the case, consider a puzzle game, one could employ the use of a substitution or \ntransposition cipher to create an interesting cryptography puzzle.\n\nLet us consider a \\textit{live chat application}. This application will send messages from one user to another (over the network).\nWe will assume that the messages sent are sensitive. In this case, security does seem to play a vital role in the function\nof the application. Though we must also consider the \\textit{comprising party}---the party which intends to infiltrate the \ncommunication network. \n\nSay we are designing a chat application for an intranet,\\footnote{An intranet is a private network that is only accessible to\nmembers of the network. An organization may use an intranet; only staff of the organization may access the network.} there may \nno comprising party or the risk of a comprising party is low. Therefore we may not require any complex cryptography systems, \ninstead opting for a simple symmetric-key algorithm (such as Caesar Cipher or the slightly more complex DES scheme). On the \nother hand, if we are developing a chat application for the internet where anyone can access the communication network. We may\nplace more importance on security as the network is public.\n\nWhat if do we require a complex asymmetric-key system? We could use the discussed RSA scheme. All around, the RSA\nscheme is an excellent cryptography method---it is extremely reliable---it is purely a mathematical solution---and it is secure. \nBut as always, there exists a caveat. The RSA scheme generates insanely large numbers. This is due to the fact that our plaintext\nmust be smaller than our modulus (the shared key). As discussed in \n\\hyperref[Asymmetric-key cryptography]{Asymmetric-key cryptography}, if our plaintext is\nlarger than our modulus, we must split our plaintext into appropriately sized blocks. We then encrypt each block in some mode\nof operation (such as Feistel cipher). Unfortunately, this type of encryption will reveal redundancies in the ciphertext which\nmakes the cipher easier to break. Alternatively, we can expand the size of our modulus (and private and public keys)\nto suit the size of our plaintext. This technique will work in theory but in practice there exists a hardware limitation---the\nsize of a data type; RSA will quickly exceed the max value of a $64$-bit integer. Instead we can use a \\textit{Big Integer}, a\ndata structure which allows us to store \\textit{very very} large numbers. This does however use a lot of memory. Nonetheless,\ndespite the existing alternatives, there exists the fact that RSA is a memory-hog. And despite advancements in computer \ntechnology, there always exists an instantial upper-bound---whether it be storage or speed.\n", "meta": {"hexsha": "bc80e32b0c1c7001d82137304a490943349126a2", "size": 3320, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapters/Analysis.tex", "max_stars_repo_name": "GalacticGlum/CryptographyResearchPaper", "max_stars_repo_head_hexsha": "b538ba91fcee47995b2bf102affa9425badafc0c", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapters/Analysis.tex", "max_issues_repo_name": "GalacticGlum/CryptographyResearchPaper", "max_issues_repo_head_hexsha": "b538ba91fcee47995b2bf102affa9425badafc0c", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapters/Analysis.tex", "max_forks_repo_name": "GalacticGlum/CryptographyResearchPaper", "max_forks_repo_head_hexsha": "b538ba91fcee47995b2bf102affa9425badafc0c", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 89.7297297297, "max_line_length": 130, "alphanum_fraction": 0.7972891566, "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.3203981380944565}}
{"text": "\\section{2021-09-22 Lecture}\n\nThis is a class that cannot fail,\nbecause if it crashes and burns,\nthe qualifier fails.\n\nThis is my favourite lecture.\nSorry it's online.\nIt's conceptual.\nThis used to not be covered in standard classes,\nbut it because so popular there's no way out.\nI'm going to start from something everyone knows.\nThe double slit experiment.\n\nIf you're not comfortable,\nit means two things:\nyou don't know QM and you should laern straight away.\n\nThe best way to learn is to open the old Feynman lectures on physics.\nOf course you can go to Youtube anddo the same thing,\nwith beautiful computer graphics,\nbut unfortanaltely many of them are wrong.\nFeynman knows physics.\n\n\nIf there's only one hole nothing exciting happens.\nThe particle hits the screen,\nmostly behind the hole.\nHere I plot the number of particles that hit the screen.\nIf the hole is left,\nyou get particles on the lfet.\nIf the hole is right,\nyou get particles on the right.\n\nButy what happens when you shoot two holes?\nThey interferer with each other.\nThe result is surpricingly,\nin fact the most likely place to get a particle is in the middle,\nwhich is neither the single hole scneairos.\nIt's more than just the sum of the two.\nYou get an interference pattern.\n\nYou seen t his before.\nIt's pretty.\nThere are regions where the waves interfere desctructively and you don't get a\nparticle behin the screen.\nthat's how all waves behave.\nIf you make waves no thel ake,you get he same thing,\nso it's not surprising.\nWhat is surprising is tat the aprticles sometimes behave like particles,\nand sometimes waves.\nIn fact,\nwhat you get on the screen is this.\n\nIf you send particles one by one and you start counting,\nevery time you send a particle,\nyou get one spot on the screen,\nhowever the probability fo getting apricles obeys the interference pattern.\nThat's this other way we see this particle-wave duality.\n\nI'm going to switch to my laptop.\nThat's a drawing of the situation here.\nI want to remind you how to descrbie this quanutm mechancially.\n\n\nLet's say the left sitautions is $\\ket{L}$\nand the situation for the right hole open is $\\ket{R}$.\nWhen you have both holes open,\nthe state is going to be a linear combination\n\\begin{align}\n    \\ket{\\psi} = \\alpha\\ket{L} + \\beta\\ket{R}\n\\end{align}\nHow do you get intference?\nLet's measure $A_y$ that counts the number of particles,\nor the probablity of the particle arriving at coordinate $y$\non hte screen.\nOf course,\nI want to take the expectation value.\n\\begin{align}\n    \\bra{\\psi} A_y \\ket{\\psi} &=\n    \\left( \\alpha^* \\bra{L} + \\beta^*\\bra{R} \\right)\n    A_y\n    \\left( \\alpha\\ket{L} + \\beta\\ket{R} \\right)\\\\\n    &=\n    |\\alpha|^2 \\bra{L}A_y\\ket{L}\n    + |\\beta|^2 \\bra{R}A_y\\ket{R}\n    + \\alpha\\beta^* \\bra{L}A_y\\ket{R}\n    + \\alpha^*\\beta \\bra{R}A_y\\ket{L}\n\\end{align}\nThe first two terms are familiar.\nThey are just the probabilities for if the left hole is open only\nand the rigt hole is open only respectively.\nTHe novelty of course in QM is that you have inerference terms,\nthe last two terms.\nWhile the $|\\alpha|^2$ and $|\\beta^2|$ terms are positive,\nthose $\\alpha\\beta^*$ and $\\beta\\alpha^*$ terms are not necessarily positive,\nso it's possible you cna have cancelation.\nAnd that's why you get zeros in the distribution,\nit's because of intereference and cancellation.\n\nSo this is well known.\nThe fact you have uqanutm intereference out of linear combinations,\nyou get this pretty well.\n\nLet's compare this with a different situation.\nLet's say I have a different siuaiton like this.\nExcept the two slits are never open at the same time.\n\nI'm going to trow a dice.\nIf the number is odd,\nI open the left hole.\nIf the number is even,\nI open the right hole.\nWhat am I going to get?\n\nhal the time I'm going to get the L distributino,\nand half the time I'm going to ge the R distribution.\nAnd I get a double-bump distirbution.\n\nSo then this quantity,\nThe previous situation would be left AND right.\nBut now I will call this dice roll situation left OR right.\n\\begin{align}\n    \\bar{A}_y &=\n    p_L \\bra{L}A_y\\ket{L}\n    + p_R \\bra{R}A_y\\ket{R}\n\\end{align}\nwhere $p_L$ and $p_R$ are the probabilities of having the left or right holes\nopen respectively.\nYou notice that this matces the first two terms of the previous formula.\nWhat you do not find is the second two terms,\nso there is no interference.\nThis is a different physical sitaution.\n\nThose two things are not the same.\nIf you plot $A_y$ vs $y$,\nin the QM superposition,\nyou get this\n[picture]\n\nBut if you have the classical probability,\nyou get two bumps.\n[picture]\n\nThese two sitautions are very common,\nand you need to give these names.\nhaving L and R in superpsotiion quantum mechanically,\nwe have a \\emph{coherent} sum.\nBut the classical probability situation,\nis the \\emph{incoherent sum}.\nThe incorhernet sitaution happens all the time\nin classical physics.\n\nBut the coherent sum is something very special to QM,\nthere is no classical analogue for that.\n\nThis situation where you have a combination of this,\nwhere some of it is quanutm mehaonical,\nbut I also don't know what the wave function is,\nappears commonly in physics too.\n\nSo ther eare two kinds of uncertainty.\nThere is the quantum uncertainty of the wave function,\nbutther'es the classical uncertainty of not knowing what the wave function is in\nthe first place.\nThere is a formalism to deal with this.\n\nSuppose you have some observablve $A$.\nThen\n\\begin{align}\n    \\bar{A} &=\n    \\underbrace{\n    \\sum_n \\underbrace{p_n}_{\\text{prob. in $\\ket{n}$}} \\underbrace{\\bra{n} A \\ket{n}}_{\\text{quantum average}}\n    }_{\\text{classical average}}\n\\end{align}\nSo we have a quantum and a classical average\n\nThere's a cute way to write this as a trace.\n\\begin{align}\n    \\bar{A} = \\Tr\\left[\n    \\left( \\sum_n p_n \\ket{n}\\bra{n} \\right) A\n    \\right]\n\\end{align}\nIs this the same?\nIt's easy to see,\nbecause to compute the trace,\none way of computing the trace is to take a basis,\nfor example the same basis $\\ket{n}$,\nthen compute the sandwich of whatever is in the trace and then sum over elements\nof the basis,\nbut you see this is easy to compute.\n\\begin{align}\n    \\Tr\\left[\n    \\left( \\sum_n p_n \\ket{n}\\bra{n} \\right) A\n    \\right]\n    &=\n    \\sum_{m} \\bra{m}\n    \\sum_n p_n \\ket{n}\\bra{n} A\\ket{m}\\\\\n    &= \\sum_{m,n} \\cdots\n\\end{align}\nThen observe the following things.\nThen we call that part the density matrix.\n\\begin{align}\n    \\rho = \\sum_n p_n \\ket{n}\\bra{n}   \n\\end{align}\nThis contains all the information about the system.\nIt doesn't tell me what the wave function is,\nbecause there's uncertainty about what the wave function is.\nBut the probabliies are al defined by this $\\rho$.\nStates whree therare different clasical probailitesi of different wave fucntions\nis called a \\emph{mixed state}.\nIn situations wher we know what hte wave function is,\nthey are called \\emph{pure dstates}.\n\nTo be clear,\n\\begin{align}\n    \\bar{A} = \\Tr(\\rho A)\n\\end{align}\nRemember $\\rho$ contains informaiton about all possible wave functions the\nsystem may have.\n\nAre we good up to now?\nBy the way,\nyou can raise a question by raising a hand,\nbut it's better to shout,\njust unmute yourself and shout.\nYou can even go and ask questions in the chat.\n\n\\begin{question}\n    Can you elaborate on mixed state?\n\\end{question}\nIf you know thw ave function of the sytem,\nyou call it a pure state,\nthat's what you learnt in QM so far.\nA pure state is just a real state.\nBut then suppose you have a harmonic oscillator\nwith 30\\% chance in the ground state and 70\\% chance in the first excited state,\nthat is a mixed state.\nYou should not be confused though.\nTake hte harmonic oscilator for exmaple.\n\\begin{align}\n    \\ket{\\varphi} &=\n    \\frac{3}{5}\\ket{0}\n    + \\frac{4}{5}\\ket{1}\n    \\ne\n    \\rho\n    =\n    \\left( \\frac{3}{5} \\right)^2 \\ket{0}\\bra{0}\n    \\left( \\frac{4}{5} \\right)^2 \\ket{1}\\bra{1}\n\\end{align}\nThese states here have the same probabiliteis,\nbut they are completely different states.\nI can even add a phase.\n\\begin{align}\n    \\ket{\\varphi} &=\n    \\frac{3}{5}\\ket{0}\n    + i\\frac{4}{5}\\ket{1}\n    \\ne\n    \\rho\n    =\n    \\left( \\frac{3}{5} \\right)^2 \\ket{0}\\bra{0}\n    \\left( \\frac{4}{5} \\right)^2 \\ket{1}\\bra{1}\n\\end{align}\nIt's either one or the other.\nNo matter how smart I am,\nI will know a way to measure.\n\nhere's an example.\n\nHow do we describe th sitaution where both holes are open.\nWe already have that,\na quantum superpsoition of left and right.\nWhen I compuet the probablity of getting a particle on the sreen,\nI get interference tersm.\nIf I have a phsae,\nthe probabilities $|\\alpha|^2$ and $|\\beta|^2$ don't change,\nbut I get a different interefernece pattern.\n\nThat's usual quantum mechanics,\nbut I can describe the sitaution with desity matrices too\nwhich account for probabilities that arise because I am too dumb to know.\n\nSo I can describe the double slit experiment with density matrices too.\nFor example,\nthe incoehreent sum is\n\\begin{align}\n    \\rho &= \\frac{1}{2} \\ket{L}\\bra{L}\n    + \\frac{1}{2}\\ket{R}\\bra{R}\n\\end{align}\nand you can computet the probabilities\n\\begin{align}\n    \\bar{A} &=\n    \\Tr(\\rho A_y)\\\\\n    &=\n    \\Tr\\left( \\frac{1}{2}\\ket{L}\\bra{L} + \\frac{1}{2}\\ket{R}\\bra{R} \\right) A\\\\\n    &=\n    \\bra{L}\\left( \n    \\frac{1}{2} \\ket{L}\\bra{L}\n    + \\frac{1}{2} \\ket{R}\\bra{R}\n    \\right)A_y\n    \\ket{R}\n    + \\bra{L}\\left( \n    \\frac{1}{2} \\ket{L}\\bra{L}\n    + \\frac{1}{2} \\ket{R}\\bra{R}\n    \\right)A_y\n    \\ket{R}\\\\\n    &= \\frac{1}{2}\\bra{L} A_y \\ket{L}\n    + \\frac{1}{2}\\bra{R} A_{y} \\ket{R}\n\\end{align}\nNow look at what we thoguht it should be\n\\begin{align}\n    \\bar{A}_\n    &= p_L\\bra{L} A_y \\ket{L}\n    + p_R\\bra{R} A_{y} \\ket{R}\n\\end{align}\nso the formalism works!\nLet me tell you a couple of probabilities it's to satisfy.\n\nFirstly, $\\rho$ is a Hermitian operator.\nIt's weird,\nbecause it's not an observable,\nbut it's the state of the system.\n\\begin{align}\n    \\rho^{\\dagger} = \\rho\n\\end{align}\nCan you see this is true?\nSure\n\\begin{align}\n    \\left( \\sum_n p_n \\ket{n}\\bra{n} \\right)^{\\dagger}\n    &= \\sum_n p_n^* \\ket{n}\\bra{n}\\\\\n    &= \\sum_n p_n \\ket{n}\\bra{n}\n\\end{align}\nbecause $p_n$ are real probabilities,\nso very straighforward.\n\nAnotherp robability isthat it has unit trace.\n\\begin{align}\n    \\Tr \\rho = 1\n\\end{align}\nTo see this,\n\\begin{align}\n    \\Tr \\rho &=\n    \\Tr \\sum_n p_n\\ket{n}\\bra{n}\\\\\n    &= \\sum_m \\bra{m} \\sum_n p_n\\ket{n}\\bra{n} \\ket{m}\\\\\n    &= \\sum_{n,m} p_n \\braket{m}{n} \\braket{n}{m}\\\\\n    &= \\sum_n p_n\\\\\n    &= 1\n\\end{align}\nbecause the total probability is equal to 1.\n\n\nFinally, $\\rho$ is positive definite.\nIt follows from the fact that $p_n$ has to be positive or zero.\nPositive definite means that\n\\begin{align}\n    \\bra{\\phi}\\rho\\ket{\\phi} &=\n    \\bra{\\phi} \\sum_n p_n\\ket{n}\\braket{n}{\\phi}\\\\\n    &=\n    \\sum_n p_n \\braket{\\phi}{n} \\braket{n}{\\phi}\\\\\n    &= \\sum_n p_n |\\braket{n}{\\phi}|^2\\\\\n    &\\ge 0\n\\end{align}\n\nThere's one final property.\nFor some special states, we have\n\\begin{align}\n    \\rho^2 = \\rho\n\\end{align}\nif and only if $\\rho=\\ket{\\psi}\\bra{\\psi}$ is a pure state.\nYou can see this clearly because if\n$\\rho = \\sum_n p_n \\ket{n}\\bra{n}$\nand if $p_n=0$ except $p_{\\bar{n}}=1$,\nthen obviously $\\ket{\\bar{n}}=\\ket{n}$.\nThere are two things to prove,\nbecause it's if and only if.\nIt's a simple test.\nSuppose $\\rho$ is pure,\nthen\n\\begin{align}\n    \\rho^2 &=\n    \\ket{\\psi}\\braket{\\psi}{\\psi}\\bra{\\psi} = \\rho\n\\end{align}\nIt's a bit of extra work to go the other way around.\n\nSuppose $\\rho^2 = \\rho$.\nThen \n\\begin{align}\n    \\sum_n p_n \\ket{n}\\bra{n}\n    \\sum_m p_m \\ket{m}\\bra{m}\n    &= \\sum_{n,m} p_n p_m \\ket{n} \n    \\underbrace{\\braket{n}{m}}_{\\delta_{nm}} \\bra{m}\\\\\n    &= \\sum_n p_n^2 \\ket{n}\\bra{n}\\\\\n    &= \\sum_n p_n \\ket{n}\\bra{n}\n\\end{align}\nso we know that $p_n^2=p_n$ for all $n$.\nThere are only two ways this can be true.\nEither $p_n=0$ or $p_n=1$.\nBut probabilities sum to 1,\nso only one of these can be $p_{\\bar{n}}=1$,\nand all the other $p_n=0$.\nWhat does that prove?\nIn other words,\n\\begin{align}\n    \\rho = \\sum_n p_n\\ket{n}\\bra{n} = \\ket{\\bar{n}}\\bra{\\bar{n}}\n\\end{align}\n\nOh there's a question.\nIt's just one word: magical.\n\nYou're just in awe of the power of density matrices and bras and kets?\n\nBy the way,\nLandau invented density matrices.\nHe was two years too young to invent QM,\nbut he invented density matrices.\nBras and kets,\nI'm tired of syaing it's a beautiful thing,\nbut I hope you can appreciate how the algebra just works without thinking.\nIt's importnat to understand why it works,\nbut once you do,\nit's easy.\n\nThe name of this class is quantum and statistical physics.\nForgoet about the deep stuff.y\nYou're goign to use distributions of positions and momentum classical,\nbut the density analogue is density matrices,\nwhere you have distributions over wave functions.\n\n\n\\begin{question}\n    So $\\rho$ is diagonal?\n\\end{question}\nWell $\\bra{n}\\rho\\ket{n'}$ is a diagonal matrix in this basis,\nbut in a different basis,\nit will not necessarily be a diagonal matrix,\ndespite describing the same physics.\nIf the operator was diagonal,\nI wouldn't talk about htis operator,\nit would be overkill.\nIn this basiss to define $\\rho$,\nbut may be diagonal,\nbut in another basis,\nit's not diagonal\nand it's not obvoius at all it's not a pure state.\n", "meta": {"hexsha": "b477812fffdb1471acaafb8f847a67461965f146", "size": 13209, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "phys612/lecture10.tex", "max_stars_repo_name": "ehua7365/umdphysnotes", "max_stars_repo_head_hexsha": "00e4e2b6aba3d03baaec5caa36903e5135b014de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-11T12:53:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T12:53:46.000Z", "max_issues_repo_path": "phys612/lecture10.tex", "max_issues_repo_name": "ehua7365/umdphysnotes", "max_issues_repo_head_hexsha": "00e4e2b6aba3d03baaec5caa36903e5135b014de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phys612/lecture10.tex", "max_forks_repo_name": "ehua7365/umdphysnotes", "max_forks_repo_head_hexsha": "00e4e2b6aba3d03baaec5caa36903e5135b014de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6831460674, "max_line_length": 111, "alphanum_fraction": 0.7041411159, "num_tokens": 3980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.3203981380944565}}
{"text": "\\section{Types}\n\n\\subsection{Primary types}\nTypes are composed of several key expressions:\n\n\\begin{grammar}\n<type> ::= <name>\n      \\alt <type application>\n      \\alt <forall>\n      \\alt <constraint>\n      \\alt <type function>\n      \\alt <type tuple>\n      \\alt `(' <type> `)'\n      \\alt `_'\n      \\alt `[' <type> `]'\n      \\alt `[|' <type> `|]'\n      \\alt <record>\n      \\alt <row>\n      \\alt <union>\n      \\alt <unifies>\n\n<var> ::= <ident>\n     \\alt `(' <ident> : <type> `)'\n\n<type application> ::= <type> <type>\n                  \\alt <type> <name> <type>\n                  \\alt <type> \\lit{\\`{}} <name> \\lit{\\`{}} <type>\n\n<forall>        ::= `forall' \\{ <var> \\} `.' <type>\n\n<constraint>    ::= <type> `=>' <type>\n\n<function type> ::= <type> `->' <type>\n\n<tuple type>    ::= <type> \\{ `*' <type> \\}\n\n<unifies>       ::= <type> \\lit{$\\sim$} <type>\n\\end{grammar}\nThe $type\\ application$, $forall$, $constraint$ and $type\\ function$ rules are right associative, whilst $unifies$ is non-associative.\n\n\\todo[inline]{What is the precedence of these?}\n\n\\subsection{Type annotations}\n\\begin{itemize}\n\\item \\texttt{:} is used to annotate a variable or expression having a type.\n\\item \\texttt{\\_} can be used to mark a type wildcard (not a type variable, just something you don’t want to explicitly write). So you could have \\texttt{[\\_]} to constrain it to be a list of something.\n\\end{itemize}\n\n\\subsubsection{Rows and Unions}\nRows are composed of a series of key-type pairs or a union of two rows:\n\n\\begin{grammar}\n<row body> ::= \\{<ident> `:' <type> `,'\\}\n          \\alt <ident>\n          \n<row union> ::= `'\n           \\alt <row_body> \\{ `|' <row_body> \\}\n\n<row>      ::= `(' <row union> `)'\n\\end{grammar}\n\n\\todo[inline]{What syntax are we using for union types? Braces are taken for record syntax.}\n\n\\subsubsection{Records}\nRecord definitions are composed of a series of identifier keys to type pairs separated by commas within braces.\n\n\\begin{grammar}\n<record>      ::= `\\{' <row union> `\\}'\n\\end{grammar}\n\n\\subsection{Type declarations}\nTypes can only be declared in a module. There are two forms of type declarations:\n\n\\begin{itemize}\n\\item Aliases: allowing referencing a longer type name as a shorter one (or renaming it if it conflicts or any other reason)\n\\item Type definitions: used for creating sum and product types.\n\\end{itemize}\n\n\\subsubsection{Type names}\nType names are defined as an identifier followed by a series of free type variables and/or concrete types.\nThe parameters that are specified within the RHS of the definition \\textit{must} exist on the LHS.\n\n\\subsubsection{Type aliases}\nThe \\texttt{type} keyword is used to define a type alias:\n\n\\begin{grammar}\n<type name def> ::= <ident> \\{ <var> \\} \n               \\alt `op' (`left' | `right') [<digit>] <var> <ident> <var>\n               \\alt <var> \\lit{\\`{}} <ident> \\lit{\\`{}} <var>\n\n<type name>     ::= <type name>  [ `:' <type> ]\n\n<type def> ::= `type' <type name> `=' <type>\n          \\alt `type' `foreign' <type name>\n\\end{grammar}\n\n\\subsubsection{Sum type definitions}\nSum types are composed of one or more type-constructors, each followed by the types the product type is composed of.\n\n\\begin{grammar}\n<product name> ::= <ident> \\{<type>\\}\n              \\alt <type> `(' <ident> `)' <type>\n              \\alt <type> \\lit{\\`{}} <ident> \\lit{\\`{}} <type>\n\n<product type> ::= <product name>  [ `:' <type> ]\n\n<sum type>     ::= `data' <type name> `=' \\{`|' <product type> \\}\n              \\alt `data' `foreign' <sum name>\n\\end{grammar}\n\nIf the declaration starts on a new line it should have a leading `|', otherwise not.\n\n\\begin{minted}{haskell}\ndata X = A | B\n\ndata Y = \n    | C Int\n    | D \n\\end{minted}\n\n\\paragraph{GADTs}\nGADTs are defined as so:\n\n\\begin{minted}{haskell}\ndata Foo a = Foo1 Int : Foo Int\n           | Foo2     : Foo a\n\\end{minted}\n\nType variables defined on the RHS are accessible on the left:\n\n\\begin{minted}{haskell}\ndata Bar a = Bar1 a b : forall b . Foo a\n           | Bar2     : Foo a\n\\end{minted}\n\n\\subsubsection{Type classes}\nType classes are marked with the \\texttt{class} keyword. You can then specify a series of constraints on various parameters before specifying the actual type. All constraints’ parameters must appear in the type class’s definition.\n\n\\begin{grammar}\n<class constraint> ::= <type> `=>'\n\n<functional dep>   ::= \\{ <ident> \\} `->' \\{ <ident> \\}\n\n<binding>  ::= <lhs> [`:' <type> ] [`=' <expr>]\n\n<bindings> ::= <binding>\n          \\alt <binding> \\{ `and' <binding> \\}\n\n<class body> ::= `type' <type name> [`=' <type> ]\n            \\alt `data' <type name> [`=' \\{ '|' <product type> \\} ]\n            \\alt `let' [`rec'] <bindings>\n\n<class>            ::= `class' \\{ <class constraint> \\} <type> [ `|' <functional dep> \\{ `,` <functional dep> \\} ] `where' <class body>\n\n<instance>         ::= `impl' <ident> \\{ <var> \\} `=' <type> `where' <class body>\n\\end{grammar}\n\n\\begin{minted}{haskell}\nclass Show a where -- or class Show a =\n    let show : a -> String\n\nimpl X = Show String where\n    let show x = \"!\" ++ x ++ \"!\"\n\\end{minted}\n\nThe beginning of the type class’s body is marked with the \\texttt{where} keyword and an indent. The body contains a series of variables with type annotations with optional definitions. It is possible for all definitions to be filled and depend on one another: when creating an implementation Amulet will determine if you have provided sufficient information for a complete definition.\n\n\\paragraph{Type class implementations}\nImplementations share a similar syntax to type class definitions, using \\texttt{impl} instead of \\texttt{class}. However, instead of following the type class with type parameters you can use any type expression.\n\nThe body of the implementation uses an identical syntax to that of type classes, though empty definitions are not allowed.", "meta": {"hexsha": "d2be31c0f110068cc6c91108e0f16e9fbeb71ab0", "size": 5813, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "design/syntax/types.tex", "max_stars_repo_name": "SquidDev/amulet", "max_stars_repo_head_hexsha": "1b1fea8188f67e6e338f8040a770f11acf179cfb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2016-05-31T23:41:37.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-17T23:11:24.000Z", "max_issues_repo_path": "design/syntax/types.tex", "max_issues_repo_name": "SquidDev/amulet", "max_issues_repo_head_hexsha": "1b1fea8188f67e6e338f8040a770f11acf179cfb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2016-05-31T15:22:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-21T19:03:04.000Z", "max_forks_repo_path": "design/syntax/types.tex", "max_forks_repo_name": "SquidDev/amulet", "max_forks_repo_head_hexsha": "1b1fea8188f67e6e338f8040a770f11acf179cfb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-10-16T19:41:13.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-16T19:41:13.000Z", "avg_line_length": 33.9941520468, "max_line_length": 384, "alphanum_fraction": 0.6315155686, "num_tokens": 1629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3203577778060876}}
{"text": "\\documentclass[preprint,showkeys,nofootinbib]{revtex4-1}\n\n\n% linking references\n\\usepackage{hyperref}\n\\hypersetup{\n  breaklinks=true,\n  colorlinks=true,\n  linkcolor=blue,\n  urlcolor=cyan,\n}\n\n\n% general physics / math packages and commands\n\\usepackage{physics,amsmath,amssymb,braket,dsfont}\n\\renewcommand{\\t}{\\text} % text in math mode\n\\newcommand{\\f}{\\dfrac} % shorthand for fractions\n\\newcommand{\\p}[1]{\\left(#1\\right)} % parenthesis\n\\renewcommand{\\sp}[1]{\\left[#1\\right]} % square parenthesis\n\\renewcommand{\\set}[1]{\\left\\{#1\\right\\}} % curly parenthesis\n\\newcommand{\\bk}{\\braket} % shorthand for braket\n\n\\renewcommand{\\d}{\\text{d}}\n\\newcommand{\\g}{\\text{g}}\n\\newcommand{\\e}{\\text{e}}\n\\newcommand{\\x}{\\text{x}}\n\\newcommand{\\y}{\\text{y}}\n\\newcommand{\\z}{\\text{z}}\n\n\\renewcommand{\\c}{\\hat{c}}\n\\newcommand{\\n}{\\hat{n}}\n\n\\newcommand{\\A}{\\mathcal{A}}\n\\newcommand{\\B}{\\mathcal{B}}\n\\newcommand{\\D}{\\mathcal{D}}\n\\newcommand{\\E}{\\mathcal{E}}\n\\newcommand{\\G}{\\mathcal{G}}\n\\renewcommand{\\H}{\\mathcal{H}}\n\\newcommand{\\I}{\\mathcal{I}}\n\\newcommand{\\K}{\\mathcal{K}}\n\\renewcommand{\\L}{\\mathcal{L}}\n\\newcommand{\\M}{\\mathcal{M}}\n\\newcommand{\\N}{\\mathcal{N}}\n\\renewcommand{\\O}{\\mathcal{O}}\n\\renewcommand{\\P}{\\mathcal{P}}\n\\newcommand{\\Q}{\\mathcal{Q}}\n\\renewcommand{\\S}{\\mathcal{S}}\n\\newcommand{\\U}{\\mathcal{U}}\n\n\\newcommand{\\1}{\\mathds{1}}\n\n\\newcommand{\\mA}{m_{\\text{A}}} % symbol for the mass of an atom\n\n\n% \"left vector\" arrow; requires tikz package\n\\usepackage{tikz}\n\\newcommand{\\lvec}[1]\n{\\reflectbox{\\ensuremath{\\vec{\\reflectbox{\\ensuremath{#1}}}}}}\n\n\n% figures\n\\usepackage{graphicx} % for figures\n\\usepackage{grffile} % help latex properly identify figure extensions\n\\graphicspath{{./figures/}} % set path for all figures\n\\usepackage[caption=false]{subfig} % subfigures (via \\subfloat[]{})\n\n\n% inline lists\n\\usepackage[inline]{enumitem}\n\\setlist[enumerate,1]{label={(\\roman*)}}\n\n\n% for feynman diagrams\n\\usepackage{tikz,tikz-feynman}\n\\tikzset{\n  baseline = (current bounding box.center)\n}\n\\tikzfeynmanset{\n  compat = 1.1.0,\n  every feynman = {/tikzfeynman/small}\n}\n\\newcommand{\\shrink}[1]{\\scalebox{0.8}{#1}} % for smaller diagrams\n\n\n% color definitions (used in a figure)\n\\usepackage{xcolor}\n\\definecolor{lightblue}{RGB}{31,119,180}\n\\definecolor{orange}{RGB}{255,127,14}\n\\definecolor{green}{RGB}{44,160,44}\n\\definecolor{lightred}{RGB}{214,39,40}\n\n% proper coloring inside math environment\n\\makeatletter\n\\def\\mathcolor#1#{\\@mathcolor{#1}}\n\\def\\@mathcolor#1#2#3{\n  \\protect\\leavevmode\n  \\begingroup\n    \\color#1{#2}#3\n  \\endgroup\n}\n\\makeatother\n\\newcommand{\\bmu}{\\mathcolor{lightblue}{\\mu}}\n\\newcommand{\\onu}{\\mathcolor{orange}{\\nu}}\n\\newcommand{\\grho}{\\mathcolor{green}{\\rho}}\n\\newcommand{\\re}{\\mathcolor{lightred}{\\text{e}}}\n\n\n% leave a note in the text, visible in the compiled document\n\\newcommand{\\note}[1]{\\textcolor{red}{#1}}\n\n% for strikeout text\n% normalem included to prevent underlining titles in the bibliography\n\\usepackage[normalem]{ulem}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{document}\n\n\\title{Effective multi-body SU($N$)-symmetric interactions of\n  ultracold fermionic atoms on a 3-D lattice}\n\n\\author{M A Perlin}\n\\email{mika.perlin@gmail.com}\n\\author{A M Rey}\n\\affiliation{JILA, National Institute of Standards and Technology and\n  University of Colorado, 440 UCB, Boulder, Colorado 80309, USA}\n\\affiliation{Center for Theory of Quantum Matter, 440 UCB, Boulder,\n  Colorado 80309, USA}\n\\affiliation{Department of Physics, University of Colorado, 390 UCB,\n  Boulder, Colorado 80309, USA}\n\n\\begin{abstract}\n  Rapid advancements in the experimental capabilities with ultracold\n  alkaline-earth-like atoms (AEAs) bring to a surprisingly near term\n  the prospect of performing quantum simulations of spin models and\n  lattice field theories exhibiting SU($N$) symmetry.  Motivated in\n  particular by recent experiments preparing high density samples of\n  strongly interacting ${}^{87}$Sr atoms in a three-dimensional\n  optical lattice, we develop a low-energy effective theory of\n  fermionic AEAs which exhibits emergent multi-body SU($N$)-symmetric\n  interactions, where $N$ is the number of atomic nuclear spin levels.\n  Our theory is limited to the experimental regime of\n  \\begin{enumerate*}\n  \\item a deep lattice, with\n  \\item at most one atom occupying each nuclear spin state on any\n    lattice site.\n  \\end{enumerate*}\n  The latter restriction is a consequence of initial ground-state\n  preparation.  We fully characterize the low-lying excitations in our\n  effective theory, and compare predictions of many-body interaction\n  energies with direct measurements of many-body excitation spectra in\n  an optical lattice clock.  Our work makes the first step in enabling\n  a controlled, bottom-up experimental investigation of multi-body\n  SU($N$) physics.\n\\end{abstract}\n\n\\keywords{\\it ultracold atoms, optical lattices, SU(N) magnetism,\n  multi-body interactions}\n\n\\maketitle\n\n\\tableofcontents\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Introduction}\n\\label{sec:introduction}\n\nFermionic alkaline-earth atoms (AEAs), in addition to other atoms such\nas ytterbium (Yb) sharing similar electronic structure, are currently\nthe building blocks of the most precise atomic clocks in the world\n\\cite{derevianko2011colloquium, katori2011optical, ludlow2015optical}.\nThese atoms have a unique, ultra-narrow optical transition between\nmetastable ${}^1S_0$ and ${}^3P_0$ electronic orbital states, i.e.~the\n``clock states'', that allows for coherence times which can exceed 100\nseconds \\cite{porsev2004hyperfine, santra2004properties}.\nFurthermore, AEAs can be trapped in fully controllable optical lattice\npotentials and interrogated with ultra-stable lasers that can resolve\nand probe their rich hyperfine spectra, consisting of $N$ different\nnuclear spin levels with $N$ as large as 10 in strontium (${}^{87}$Sr)\nand 6 in ytterbium (${}^{173}$Yb).\n\nIn 2015 the ${}^{87}$Sr optical lattice clock (OLC) at JILA, operated\nin a one-dimensional (1-D) lattice at microkelvin temperatures,\nachieved a total fractional uncertainty of $2\\times10^{-18}$\n\\cite{bloom2014optical, nicholson2015systematic}.  More recently\n(2017), a new generation of OLCs became operational at JILA,\ninterrogating a Fermi degenerate gas of ${}^{87}$Sr atoms in a 3-D\nlattice at nanokelvin temperatures \\cite{campbell2017fermidegenerate}.\nAll of these atoms' degrees of freedom, including the electronic\norbital, nuclear spin, and motional states, can be fully controlled\nwith high fidelity in a 3-D lattice \\cite{daley2008quantum,\n  gorshkov2009alkalineearthmetal, daley2011quantum,\n  daley2011statedependent}.  With frequency measurements reaching the\n$10^{-19}$ fractional uncertainty level, the new OLCs are thus\nenabling an exciting opportunity to probe, for the first time, quantum\ndynamics with sub-millihertz spectral resolution\n\\cite{campbell2017fermidegenerate}.\n\nA wonderful consequence of the efforts to build better clocks is the\ndevelopment of highly controllable quantum simulators of many-body\nsystems in the strongly-interacting regime, where inter-particle\ninteractions set the largest energy scale relevant for system dynamics\n\\cite{swallows2011suppression, lemke2011wave,\n  campbell2017fermidegenerate}.  The marriage between precision clock\nspectroscopy and quantum many-body physics \\cite{taie2012su,\n  martin2013quantum, scazza2014observation, cappellini2014direct,\n  zhang2014spectroscopic, rey2014probing} has an enormous potential to\nenable novel explorations of physics for the same reason that makes\nAEAs such remarkable time-keepers.  Specifically, due to the lack of\nelectronic orbital angular momentum in the ${}^1S_0$ and ${}^3P_0$\nstates, AEAs exhibit decoupled orbital and nuclear spin degrees of\nfreedom.  For atoms with $N$ nuclear spin levels, this decoupling\nleads to nuclear-spin-conserving SU($N$)-symmetric interactions\ngoverned entirely by orbital-state parameters\n\\cite{cazalilla2009ultracold, taie2012su, zhang2014spectroscopic}.\n\nThe presence of this exotic SU($N$) symmetry in a highly controllable\nexperimental platform opens the door to experimental studies of\ne.g.~the SU($N$) Heisenberg model, whose phase diagram is believed to\nexhibit features such as a chiral spin liquid (CSL) phase with\ntopological order and fractional statistics \\cite{hermele2009mott,\n  hermele2011topological, chen2016syntheticgaugefield}.  In addition\nto illuminating open questions in our understanding of the fractional\nquantum Hall effect and unconventional superconductivity\n\\cite{lee2006doping, lee2008high, gong2014emergent}, the CSL can\nsupport non-Abelian excitations which allow for universal topological\nquantum computation \\cite{freedman2004class, hermele2011topological}.\nHarnessing the SU($N$)-symmetric interactions of AEAs might also\nenable the simulation of various lattice gauge theories\n\\cite{wieseu.-j.2013ultracold, zohar2016quantum}, some of which share\nimportant qualitative features with quantum chromodynamics such as\nfew-body bound states and confinement \\cite{banerjee2013atomic,\n  rico2018nuclear}.  These direct, quantum simulations have an\nextraordinary potential to provide novel insights by circumventing\ne.g.~severe sign problems which plague classical simulations of\nstrongly interacting fermionic systems \\cite{wieseu.-j.2013ultracold,\n  wu2003exact}.\n\nIn this work, we investigate the first experimental capabilities with\nultracold fermionic AEAs to prepare high-density samples in a 3-D\nlattice with multiple occupation of individual lattice sites\n\\cite{goban2018emergence}.  Specifically, we consider ground-state\npreparation of isolated few-body systems in the deep-lattice limit,\nand carry out a bottom-up investigation of emergent multi-body\ninteractions on multiply-occupied lattice sites.  These multi-body\ninteractions appear in a low-energy effective theory of the atoms, and\ninherit the SU($N$) symmetry of their bare, pair-wise interactions,\nthereby enabling experimental studies of multi-body SU($N$) physics\nthrough the exquisite capabilities with OLCs.  Our theory is limited\nto the experimental regime of at most one atom occupying each nuclear\nspin state on any lattice site, which is a consequence of the\nexperimental protocol which starts with all atoms in the ground state.\n\nThough effective multi-body interactions have previously been studied\nin the context of harmonically \\cite{johnson2012effective,\n  yin2014universal} and lattice-confined \\cite{johnson2009effective}\nneutral bosons prepared in a single hyperfine state, our work deals\nfor the first time with fermions that have internal degrees of freedom\nand multiple collisional parameters.  Some past work has detected\nexperimental signatures of multi-body interactions in the form of\nquantum phase revivals \\cite{will2010timeresolved}.  We instead\ncompare the many-body interaction energies predicted by our low-energy\neffective theory to the experimental measurements of the\ndensity-dependent orbital excitation spectra performed in\nref.~\\cite{goban2018emergence}, similarly to the measurements with\nbosons performed in ref.~\\cite{mark2011precision}.  To facilitate this\ncomparison of excitation spectra and to characterize the low-lying\nexcitations in our effective theory, we consider a restriction of our\ntheory to states with at most one orbital excitation per lattice site.\nIn this case, we find that the SU($N$) symmetry of atomic collisions\nallow the effective multi-body interactions to take a remarkably\nsimple form.\n\nThe remainder of this paper is structured as follows.  In section\n\\ref{sec:overview} we summarize the experimental procedures relevant\nto our work, provide an overview of the one- and two-body physics of\nultracold atoms in a deep lattice, and preview our main technical\nresults.  In section \\ref{sec:low_energy} we discuss our method for\nderiving a low-energy effective theory, provide a perturbative\nexpansion for the net effective Hamiltonian, and compute all $M$-body\nHamiltonians through third order in the low-energy effective theory.\nWe then analyze the low-lying excitations of the effective theory in\nsection \\ref{sec:spectra}, comparing spectral predictions with\nexperimental measurements, and study the orbital-state dynamics of\nnuclear spin mixtures interrogated via Rabi spectroscopy.  Finally, we\nsummarize and conclude our findings in section \\ref{sec:summary}, and\nprovide some discussion of future outlooks.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Background and overview}\n\\label{sec:overview}\n\nThe work in this paper is closely tied to the experimental work\nreported in ref.~\\cite{goban2018emergence}; we begin with a short\nsummary of the relevant experimental procedures therein.  The\nexperiment begins by preparing a degenerate gas of $10^4$-$10^5$\n(fermionic) ${}^{87}$Sr atoms in a uniform mixture of their ten\nnuclear spin states and at $\\sim0.1$ of their fermi temperature\n($\\sim10$ nanokelvin) \\cite{campbell2017fermidegenerate,\n  marti2018imaging}.  This gas is loaded into a primitive cubic\noptical lattice at the ``magic wavelength'' for which both ground\n(${}^1S_0$) and first-excited (${}^3P_0$) electronic orbital states of\nthe atoms experience the same lattice potential \\cite{ye2008quantum}.\nLattice depths along the principal axes of the lattice are roughly\nequal in magnitude, with a geometric mean that can be varied from 30\nto 80 $E_{\\t{R}}$, where $E_{\\t{R}}\\approx3.5\\times2\\pi~\\t{kHz}$ is\nthe lattice photon recoil energy of the atoms (with the reduced Planck\nconstant $\\hbar=1$ throughout this paper).  These lattice depths are\nsufficiently large as to neglect tunneling on the time scales relevant\nto the experiment.  The temperature of the atoms is also low enough to\nneglect thermal occupation of motional states outside the ground-state\nmanifold.\n\nOnce loaded into an optical lattice, atoms are addressed by an\nexternal (``clock'') interrogation laser with an ultranarrow (26 mHz)\nlinewidth, detuned by $\\Delta$ from the single-atom ${}^1S_0-{}^3P_0$\ntransition frequency $\\omega_0$.  After a fixed interrogation time,\nthe experiment turns off the interrogation laser, removes all\nground-state (${}^1S_0$) atoms from the lattice, and uses absorption\nimaging to count the remaining excited-state (${}^3P_0$) atoms.\nNon-interacting atoms in singly-occupied lattice sites feature the\ntypical single particle lineshape peaked at $\\Delta=0$.  The\nlineshapes of multiply-occupied lattice sites, meanwhile, are shifted\nby inter-atomic interactions, which results in spectroscopic peaks\n(i.e.~local maxima in excited-state atom counts) away from $\\Delta=0$.\nA sweep across different detunings $\\Delta$ (on the scale of\ninter-atomic interaction energies) thus constitutes a measurement of\nthe many-body orbital excitation spectrum.  We note that this\nspectroscopic protocol addresses only singly-excited orbital states of\nlattice sites.  Doubly-excited states are off resonant due to\n\\begin{enumerate*}\n\\item the interaction-induced non-linearity ($\\sim$kHz) of the orbital\n  excitation energies, and\n\\item the ultranarrow linewidth ($\\sim$mHz) of the interrogation\n  laser.\n\\end{enumerate*}\n\nAlthough an external trapping potential will generally break discrete\ntranslational symmetry of the lattice, any background inhomogeneity\ncan be made negligible by spectroscopically addressing a sufficiently\nsmall region of the lattice \\cite{goban2018emergence}.  Throughout\nthis paper, we work strictly in the deep-lattice regime with\nnegligible tunneling between lattice sites.  We also neglect any\nlattice inhomogeneities and assume that both atomic orbital states\n(i.e.~${}^1S_0$ and ${}^3P_0$) experience identical lattice\npotentials.  The single-particle Hamiltonian of the atoms can then be\nwritten in the form\n\\begin{align}\n  H_0 = \\sum_{i,n,\\mu,s} E_n \\c_{in\\mu s}^\\dag \\c_{in\\mu s},\n  \\label{eq:H_0}\n\\end{align}\nwhere $\\c_{in\\mu s}$ is a fermionic operator which annihilates a\nsingle atom on lattice site $i\\in\\mathbb{Z}^3$ in motional state\n$n\\in\\mathbb{N}_0^3$ with nuclear spin $\\mu\\in\\set{-I,-I+1,\\cdots,I}$\n(i.e.~projected onto a quantization axis) and orbital state\n$s\\in\\set{\\g,\\e}$; and $E_n$ is the energy of a single atom in\nmotional state $n$.  In a harmonic trap approximation we would have\n$E_n=\\p{3/2+n_\\x+n_\\y+n_\\z}\\omega$ for an on-site angular trap\nfrequency $\\omega$, but in general the aharmonicity of the lattice\npotential will cause a non-negligible shift in motional state\nenergies.\n\nIn the absence of hyperfine coupling, as when addressing the spinless\n${}^1S_0$ ($\\g$) and ${}^3P_0$ ($\\e$) orbital states of AEAs,\ninteractions between any two atoms are governed by their orbital\nstates alone, and are therefore characterized by four scattering\nlengths $a_X$ with $X\\in\\set{\\g\\g,\\e\\g^-,\\e\\g^+,\\e\\e}$, where the $+$\n($-$) superscript denotes symmetrization (anti-symmetrization) of a\ntwo-body orbital state under particle exchange.  In the low-energy\nlimit, we can write the bare two-body interaction Hamiltonian in the\nform \\cite{gorshkov2010twoorbital}\n\\begin{align}\n  H_{\\t{int}} = \\sum_{\\substack{\\mu<\\nu\\\\s}}\n  G_s \\int \\d^3x~ \\hat\\rho_{\\mu s} \\hat\\rho_{\\nu s}\n  + G_+ \\sum_{\\mu,\\nu}\n  \\int \\d^3x~ \\hat\\rho_{\\mu,\\e} \\hat\\rho_{\\nu,\\g}\n  + G_- \\sum_{\\mu,\\nu} \\int \\d^3x~\n  \\hat\\psi_{\\mu,\\e}^\\dag \\hat\\psi_{\\nu,\\g}^\\dag\n  \\hat\\psi_{\\nu,\\e} \\hat\\psi_{\\mu,\\g},\n  \\label{eq:H_int_start}\n\\end{align}\nwhere $\\hat\\psi_{\\mu s}$ is a fermionic field operator for atoms with\nnuclear spin $\\mu$ and orbital state $s$;\n$\\hat\\rho_{\\mu s}\\equiv\\hat\\psi_{\\mu s}^\\dag\\hat\\psi_{\\mu s}$ is an\natomic density field operator; and the coupling constants $G_X$ are\ndefined in terms of the scattering lengths $a_Y$ by\n\\begin{align}\n  G_{s=\\g,\\e} \\equiv \\f{4\\pi}{\\mA}~ a_{ss}, &&\n  G_\\pm \\equiv \\f{2\\pi}{\\mA}~ \\p{a_{\\e\\g+} \\pm a_{\\e\\g-}},\n  \\label{eq:couplings}\n\\end{align}\nwhere $\\mA$ is the mass of a single atom.  Defining for brevity\n\\begin{align}\n  G^{qr}_{st} \\equiv \\left\\{\n    \\begin{array}{ll}\n      G_q & ~ q = r = s = t \\\\\n      G_+ & ~ q \\ne r ~ \\t{and} ~ (q,r) = (s,t) \\\\\n      G_- & ~ q \\ne r ~ \\t{and} ~ (q,r) = (t,s) \\\\\n      0 & ~ \\t{otherwise}\n    \\end{array}\\right.,\n  \\label{eq:coupling_tensor}\n\\end{align}\nwhere $q,r,s,t\\in\\set{\\g,\\e}$ are orbital state indices, we can\nalternately write the bare two-body interaction Hamiltonian in the\nmore compact form\n\\begin{align}\n  H_{\\t{int}}\n  = \\f12 \\sum_{\\substack{q,r,s,t\\\\\\mu,\\nu}} G^{qr}_{st} \\int \\d^3x~\n  \\hat\\psi_{\\mu s}^\\dag \\hat\\psi_{\\nu t}^\\dag\n  \\hat\\psi_{\\nu r} \\hat\\psi_{\\mu q}.\n  \\label{eq:H_int_fields}\n\\end{align}\nFor nuclear spins $\\mu,\\nu$, the symbol $G^{qr}_{st}$ gives the\ncoupling constant between the two-atom states\n$(\\mu,q)+(\\nu,r)\\leftrightarrow(\\mu,s)+(\\nu,t)$.\n\nNote that the Hamiltonian in \\eqref{eq:H_int_fields} is not the true\nmicroscopic interaction Hamiltonian of AEAs, but rather a generic form\nfor a low-energy effective field theoretic description of two-body\ninteractions \\cite{scazza2014observation, cazalilla2009ultracold,\n  johnson2012effective, yin2014universal, johnson2009effective,\n  gorshkov2010twoorbital, wall2013strongly, busch1998two}.  There are\ntherefore two important points to keep in mind concerning our use of\n\\eqref{eq:H_int_fields} to describe two-body interactions.  First, the\nuse of effective field theory generically gives rise to divergences\nthat must be dealt with either through regularization, e.g.~of the\nzero-range interaction potential implicitly assumed in the expression\nof \\eqref{eq:H_int_fields} \\cite{giorgini2008theory}, or through\nrenormalization of the coupling constants in the theory.  We chose the\nlatter approach, as we will in any case find it convenient to\nrenormalize the coupling constants in the effective theory developed\nin section \\ref{sec:low_energy}.  The choice of method to regulate\ndivergences has no effect on the underlying physics.\n\nSecond, \\eqref{eq:H_int_fields} is only the first term in a low-energy\nexpansion of two-body interactions in effective field theory, which\ngenerally includes additional terms containing derivatives of field\noperators.  Derivative terms correspond to the dependence of two-body\nscattering on the relative momentum $k$ of particles involved, with\n$k\\to0$ in the zero-energy limit.  In the present case of $s$-wave\nscattering, the leading dependence of the two-body interaction\nHamiltonian on the relative momentum $k$ can be captured by use of an\nenergy-dependent pseudo-potential, which amounts to using a\n$k$-dependent effective scattering length \\cite{blume2002fermi}.  This\neffective scattering length can be determined by expanding the\n$s$-wave collisional phase shift in powers of the relative momentum\n$k$ \\cite{giorgini2008theory, flambaum1999analytical}.  Details of\nthis expansion will depend on the characteristic length scale of\nfinite-range interactions.  In our work, these corrections to\n\\eqref{eq:H_int_fields} will be relevant only for the calculation of\ntwo-body interaction energies, appearing at third order in the\ncoupling constants $G_X$.  As we are primarily interested in $M$-body\ninteractions for $M\\ge3$, we defer this calculation to Appendix\n\\ref{sec:momentum_dependence}.  We note that our approach of using an\nunregularized contact potential, renormalizing coupling constants, and\nseparately accounting for momentum-dependent scattering is essentially\nthe same as the approach used for similar calculations in\nrefs.~\\cite{johnson2012effective, yin2014universal,\n  johnson2009effective}.  While this approach does not provide insight\ninto the microscopic structure of inter-atomic interactions, it is\nsuitable for the phenomenological description of these interactions,\nand in particular for our eventual development of a low-energy\neffective theory.\n\nWe now expand the field operators $\\hat\\psi_{\\mu s}$ in the Wannier\nbasis for a 3-D lattice, such that\n$\\hat\\psi_{\\mu s}(x) = \\sum_{i,n} \\phi_{in}(x) \\c_{in\\mu s}$ with\nspatial wavefunctions $\\phi_{in}$ and fermionic annihilation operators\n$\\c_{in\\mu s}$ indexed by lattice sites $i$ and motional states $n$.\nInvoking the tight-binding approximation, we assume that the spatial\noverlap integral in \\eqref{eq:H_int_fields} is negligible unless all\nwavefunctions are localized at the same lattice site; we discuss the\nbreakdown of this approximation and its consequences for our\nlow-energy effective theory in Appendix \\ref{sec:error}.  The relevant\nspatial overlap integral is then\n\\begin{align}\n  K^{k\\ell}_{mn}\n  \\equiv \\int \\d^3x~ \\phi_{im}^* \\phi_{in}^* \\phi_{i\\ell} \\phi_{ik},\n  \\label{eq:K_klmn}\n\\end{align}\nwhich for a lattice with discrete translational invariance is\nindependent of the lattice site $i$.  The two-body interaction\nHamiltonian can be written in terms of this overlap integral as\n\\begin{align}\n  H_{\\t{int}}\n  = \\f12 \\sum_{\\substack{i,k,\\ell,m,n\\\\q,r,s,t\\\\\\mu,\\nu}}\n  K^{k\\ell}_{mn} G^{qr}_{st}\n  \\c_{im\\mu s}^\\dag \\c_{in\\nu t}^\\dag \\c_{i\\ell\\nu r} \\c_{ik\\mu q}\n  \\equiv \\f12 \\sum K^{k\\ell}_{mn} G^{qr}_{st}\n  \\c_{m\\mu s}^\\dag \\c_{n\\nu t}^\\dag \\c_{\\ell\\nu r} \\c_{k\\mu q},\n  \\label{eq:H_int}\n\\end{align}\nwhere for brevity we will henceforth suppress the identical site index\n($i$) on all operators, and implicitly sum over all free indices in a\nsummand (i.e.~indices which do not have a fixed value).  We may also\nat times suppress motional state indices on the overlap integral\n$K^{k\\ell}_{mn}$, in which case the suppressed indices are implicitly\nzero (corresponding to a motional ground state); i.e.\n\\begin{align}\n  K^{\\ell m}_n \\equiv K^{\\ell m}_{n,0},\n  &&\n  K^m_n \\equiv K^{m,0}_{n,0},\n  &&\n  K_{mn} \\equiv K^{0,0}_{mn},\n  &&\n  K_n \\equiv K^{0,0}_{n,0},\n  &&\n  K \\equiv K^{0,0}_{0,0}.\n  \\label{eq:K}\n\\end{align}\nFor simplicity, we will also generally work in a gauge for which all\ntwo-body overlap integrals are real, such that\n$K^{k\\ell}_{mn}={K^{k\\ell}_{mn}}^*=K^{mn}_{k\\ell}$.  The existence of\nsuch a gauge is guaranteed by the analytic properties of the Wannier\nwavefunctions $\\phi_{in}$ \\cite{kohn1959analytic}.\n\nCurrent experiments with ${}^{87}$Sr can prepare up to five atoms in\nthe same (ground) orbital state on a single lattice site, and\ncoherently address states with a single orbital excitation per lattice\nsite \\cite{goban2018emergence}.  At ultracold temperatures well below\nthe non-interacting motional excitation energies\n$\\Delta_n\\equiv E_n-E_0$ for $n>0$, atoms only occupy their motional\nground state in the lattice.  For this reason, it is common to map the\ndescription of these atoms onto a single-band Hubbard model that\ncaptures all dynamics within the subspace of motional ground states of\nnon-interacting atoms, i.e.~with wavefunctions $\\phi_{i,0}$.\nInteractions, however, modify atoms' motional ground-state\nwavefuctions.  The true motional ground state of a collection of\ninteracting atoms is then an admixture of the non-interacting motional\neigenstates, and a naive Hubbard model that assumes atomic\nwavefunctions $\\phi_{i,0}$ will fail to reproduce the interacting\natoms' orbital excitation spectrum.  Formally, corrections to the\nspectrum of interacting atoms can be accounted for by a perturbative\ntreatment of far-off-resonant terms in the interaction Hamiltonian of\n\\eqref{eq:H_int} that create atoms in excited motional states,\ne.g.~$\\sim\\c_{n\\mu s}^\\dag \\c_{0,\\nu t}^\\dag \\c_{0,\\nu r} \\c_{0,\\mu\n  q}$ with $n>0$.  These corrections can be understood through\ninteraction-induced {\\it virtual} occupation of higher bands\n(i.e.~excited motional states), which becomes relevant as more atoms\noccupy the same lattice site, such that their interaction energy\nbecomes non-negligible compared to the motional excitation energies\n$\\Delta_n$.\n\nIn order to recast interaction-induced modifications to orbital\nexcitation spectra as corrections to the simple Hubbard model\n(i.e.~computed using the non-interacting ground-state wavefunctions\n$\\phi_{i,0}$), we develop a low-energy effective theory of interacting\nAEAs in a deep lattice.  To simplify our theory, we assume that any\n$N$ atoms on a single lattice site occupy distinct nuclear spin\nstates.  This assumption applies for any experimental protocol in\nwhich all atoms are initially prepared in their orbital and motional\nground states (as e.g.~in ref.~\\cite{goban2018emergence}).  In this\ncase, multiple occupation of a single nuclear spin state on any given\nlattice site is initially forbidden by fermionic statistics.\nSubsequent violation of this condition cannot occur in the absence of\ninter-site effects or hyperfine coupling between nuclear spin states,\nas is the case of the experiment in ref.~\\cite{goban2018emergence}.\n\nOur low-energy effective theory exhibits SU($N$)-symmetric multi-body\ninteractions, such that the effective interaction Hamiltonian can be\nwritten in the form\n\\begin{align}\n  H_{\\t{int}}^{\\t{eff}} = \\sum_{M=2}^{2I+1} \\sum_{p\\ge1} H_M^{(p)},\n\\end{align}\nwhere $H_M^{(p)}$ is an $M$-body Hamiltonian of order $p$ in the\ncoupling constants $G_X$, and $I$ is the total nuclear spin of each\natom (e.g.~$I=9/2$ for ${}^{87}$Sr).  The sum terminates at $2I+1$\nbecause this is the largest number of atoms which may initially occupy\na single lattice site.  We explicitly compute all $M$-body\nHamiltonians $H_M\\equiv\\sum_p H_M^{(p)}$ through order $p=3$, yielding\neffective two-, three-, and four-body interactions.  To\n\\begin{enumerate*}\n\\item facilitate a comparison with the experimental measurements of\n  many-body orbital excitation spectra performed in\n  ref.~\\cite{goban2018emergence} and\n\\item characterize the low-lying excitations in our effective theory,\n\\end{enumerate*}\nwe additionally restrict the multi-body Hamiltonians $H_M$ to states\nwith at most one orbital excitation per lattice site.  Under this\nrestriction, we find that the SU($N$) symmetry of atomic collisions\nallows us to express all multi-body Hamiltonians in the simple form\n\\begin{align}\n  H_M = \\sum_{\\abs{\\set{\\mu_j}}=M}\n  H_2^{(\\mu_1,\\mu_2)} \\prod_{\\alpha=3}^M \\n_{\\mu_\\alpha,\\g},\n  \\label{eq:H_M_preview}\n\\end{align}\nwhere $H_2^{(\\mu_1,\\mu_2)}$ is a two-body Hamiltonian addressing atoms\nwith nuclear spin $\\mu_1,\\mu_2$; and\n$\\n_{\\mu s}=\\c_{\\mu s}^\\dag\\c_{\\mu s}$ is a number operator for atoms\nwith nuclear state $\\mu$ and orbital state $s$.  The sum in\n\\eqref{eq:H_M_preview} is performed over all choices of nuclear spins\n$\\mu_j$ with $j=1,2,\\cdots,M$ for which all $\\mu_j$ are distinct, or\nequivalently all choices of $\\mu_j$ for which the set $\\set{\\mu_j}$\ncontains $M$ elements, for a total of ${2I+1\\choose M}\\times\\p{M!}$\nnuclear spin combinations.  The key feature of the $M$-body\ninteractions in \\eqref{eq:H_M_preview} is that they ultimately take\nthe same form as two-body interactions, but with the addition of $M-2$\nspectator atoms.  This form is a direct consequence of the SU($N$)\nsymmetry of underlying two-body interactions.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Low-energy effective theory}\n\\label{sec:low_energy}\n\nThe net Hamiltonian $H = H_0 + H_{\\t{int}}$ for interacting AEAs on a\nlattice is not diagonal with respect to single-particle motional state\nindices (e.g.~$n\\in\\mathbb{N}_0^3$).  The problem of determining\ninteracting atoms' orbital excitation spectrum therefore nominally\ninvolves all atomic motional degrees of freedom.  At zero temperature,\nhowever, each orbital state of a collection of interacting atoms is\nassociated with a single motional ground state.  In order to compute\nan orbital excitation spectrum at zero temperature, in principle we\nneed to identify this motional ground state.  We can then ignore all\nexcited motional states, which will be neither thermally occupied nor\nexternally interrogated.  Such a procedure would drastically reduce\nthe dimensionality of the Hilbert space necessary to describe the\natoms, thereby greatly simplifying any description of the atoms'\norbital spectrum and internal (i.e.~nuclear and orbital) dynamics.  In\npractice, however, identifying the motional ground states of\ninteracting atoms and writing down a Hamiltonian restricted to this\nsubspace is a very difficult process to carry out analytically.\n\nWe denote the motional ground-state subspace of the non-interacting\nHamiltonian $H_0$ by $\\H_{\\t{ground}}^{\\t{single}}$, and the motional\nground-state subspace of the interacting Hamiltonian\n$H = H_0 + H_{\\t{int}}$ by $\\H_{\\t{ground}}^{\\t{multi}}$.  That is,\nall atomic wavefunctions for states within\n$\\H_{\\t{ground}}^{\\t{single}}$ are described by $\\phi_{i,0}$, while\nthe atomic wavefunctions for states within\n$\\H_{\\t{ground}}^{\\t{multi}}$ are generally unknown, and are in\nprinciple determined by minimizing the energy of a state with respect\nto its motional degrees of freedom.  Both\n$\\H_{\\t{ground}}^{\\t{single}}$ and $\\H_{\\t{ground}}^{\\t{multi}}$ are\nsubspaces of the full Hilbert space $\\H_{\\t{full}}$.  When\ninteractions are sufficiently weak compared to the spectral gap\n$\\Delta$ between $\\H_{\\t{ground}}^{\\t{single}}$ and its orthogonal\ncomplement $\\H_{\\t{full}}\\setminus\\H_{\\t{ground}}^{\\t{single}}$, one\ncan identify a particular unitary operator $U$ (acting on the full\nHilbert space $\\H_{\\t{full}}$) which rotates\n$\\H_{\\t{ground}}^{\\t{multi}}$ into $\\H_{\\t{ground}}^{\\t{single}}$\n\\cite{bravyi2011schrieffer}.  This unitary $U$ can be used to\nconstruct an {\\it effective Hamiltonian} $H_{\\t{eff}} = U H U^\\dag$\nwith two key properties:\n\\begin{enumerate*}\n\\item $H_{\\t{eff}}$ is diagonal in the same (known) basis as the\n  non-interacting Hamiltonian $H_0$, and\n\\item the spectrum of $H_{\\t{eff}}$ on $\\H_{\\t{ground}}^{\\t{single}}$\n  is identical to that of the interacting Hamiltonian $H$ on\n  $\\H_{\\t{ground}}^{\\t{multi}}$.\n\\end{enumerate*}\nThe use of an effective Hamiltonian $H_{\\t{eff}}$ thus overcomes the\nneed to identify $\\H_{\\t{ground}}^{\\t{multi}}$ in order to compute the\norbital spectrum of $H$ at zero temperature.  This method for\nconstructing an effective theory is commonly known as the\nSchrieffer-Wolff transformation, named after the authors of its\ncelebrated application in relating the Anderson and Kondo models of\nmagnetic impurities in metals \\cite{schrieffer1966relation}.\n\nUsing the machinery developed in ref.~\\cite{bravyi2011schrieffer} for\nperforming a rotation between low-energy subspaces of a perturbed\n(i.e.~interacting) and unperturbed (i.e.~non-interacting) Hamiltonian,\nwe derive an expansion for an effective interaction Hamiltonian\n$H_{\\t{int}}^{\\t{eff}}$ in terms two-body interaction Hamiltonian\n$H_{\\t{int}}$ (see Appendix \\ref{sec:eff_derivation}).  This expansion\ntakes the form\n\\begin{align}\n  H_{\\t{int}}^{\\t{eff}} = \\sum_{p\\ge1} H_{\\t{int}}^{(p)},\n  \\label{eq:H_int_eff}\n\\end{align}\nwhere $H_{\\t{int}}^{(p)}$ is order $p$ in $H_{\\t{int}}$.  Letting\n$\\E_0\\equiv \\H_{\\t{full}}\\setminus\\H_{\\t{ground}}^{\\t{single}}$ denote\nthe orthogonal complement of $\\H_{\\t{ground}}^{\\t{single}}$\n(i.e.~$\\E_0$ is the space of all states with at least one atom in an\nexcited motional state), $\\B_0\\p{\\E_0}$ denote an eigenbasis of $\\E_0$\nwith respect to the single-particle Hamiltonian $H_0$, and $E_\\alpha$\ndenote the motional energy (with respect to $H_0$) of a state\n$\\ket\\alpha\\in\\E_0$ relative to the corresponding motional\nground-state energy, we define the operator\n\\begin{align}\n  \\I \\equiv \\sum_{\\ket\\alpha\\in\\B_0\\p{\\E_0}} \\f{\\op\\alpha}{E_\\alpha},\n\\end{align}\nwhich sums over projections onto excited states with corresponding\nenergetic suppression factors.  The operator $\\I$ together with the\nprojector $\\P_0$ onto $\\H_{\\t{ground}}^{\\t{single}}$ allows us\nconcisely write the first few terms in \\eqref{eq:H_int_eff} as\n\\begin{align}\n  H_{\\t{int}}^{(1)} = \\P_0 H_{\\t{int}} \\P_0,\n  &&\n  H_{\\t{int}}^{(2)} = -\\P_0 H_{\\t{int}} \\I H_{\\t{int}} \\P_0,\n  \\label{eq:H_int_1_2}\n\\end{align}\n\\begin{align}\n  H_{\\t{int}}^{(3)}\n  = \\P_0 H_{\\t{int}} \\I H_{\\t{int}} \\I H_{\\t{int}} \\P_0\n  - \\f12\\sp{\\P_0 H_{\\t{int}} \\P_0,\n    \\P_0 H_{\\t{int}} \\I^2 H_{\\t{int}} \\P_0}_+,\n  \\label{eq:H_int_3}\n\\end{align}\nwhere $\\sp{X,Y}_+\\equiv XY+YX$.  Writing down a single-band Hubbard\nmodel that simply neglects excited atomic motional states and uses\n$H_{\\t{int}}$ directly to describe the orbital spectrum of interacting\natoms is thus equivalent to truncating our expansion for\n$H_{\\t{int}}^{\\t{eff}}$ at first order.  In addition to this first\norder term, the expansion involves {\\it effective corrections} to the\naction of $H_{\\t{int}}$ on the non-interacting motional ground states\n(i.e.~on $\\H_{\\t{ground}}^{\\t{single}}$) in the form of higher-order\nterms with {\\it intermediate} or {\\it virtual occupation} of excited\nstates, manifest in $\\I$.\n\nSubstituting the definition of $\\I$ into\n\\eqref{eq:H_int_1_2}-\\eqref{eq:H_int_3} yields expressions that are\nhighly reminiscent of standard non-degenerate perturbation theory in\nquantum mechanics, but which nonetheless exhibit crucial differences.\nThe first, and most obvious difference is that these expressions are\noperator equations, and that the sums over virtual states are\nperformed over a basis for the orthogonal complement of the subspace\n$\\H_{\\t{ground}}^{\\t{single}}$, rather than a basis for the orthogonal\ncomplement of a single state, as in non-degenerate perturbation\ntheory.  Second, the non-degeneracy condition in standard perturbation\ntheory is here elevated to a restriction on the magnitude of the\nperturbation $H_{\\t{int}}$ relative to the spectral gap $\\Delta$ of\nthe non-interacting Hamiltonian $H_0$ between\n$\\H_{\\t{ground}}^{\\t{single}}$ and the excited subspace $\\E_0$.\nSpecifically, the validity of \\eqref{eq:H_int_1_2}-\\eqref{eq:H_int_3}\nis conditional only on $\\norm{H_{\\t{int}}}\\le\\Delta/2$, where\n$\\norm{X}\\equiv\\max_{\\ket\\psi\\in\\H}\\sqrt{\\bk{\\psi|X^\\dag X|\\psi}}$ is\nthe operator norm, with no restrictions on spectral gaps or\ndegeneracies within $\\H_{\\t{ground}}^{\\t{single}}$ \\cite{davis1969new,\n  bravyi2011schrieffer}.  Finally, the effective theory involves no\ncorrections to the non-interacting many-body energy eigenstates; the\npurpose of constructing the effective Hamiltonian\n$H_{\\t{eff}} = H_0 + H_{\\t{int}}^{\\t{eff}}$ is to reproduce, on the\nknown eigenstates of the non-interacting Hamiltonian $H_0$ within\n$\\H_{\\t{ground}}^{\\t{single}}$, the spectrum of the interacting\nHamiltonian $H = H_0 + H_{\\t{int}}$ on $\\H_{\\t{ground}}^{\\t{multi}}$.\n``Correcting'' the eigenstates of the non-interacting Hamiltonian\n$H_0$ on $\\H_{\\t{ground}}^{\\t{single}}$ thus invalidates the effective\ntheory.\n\nAs a last comment, we note that our chosen method for constructing an\neffective Hamiltonian is distinct from adiabatic elimination methods\nwhich are commonly used in the atomic physics and quantum optics\ncommunities to develop effective theories for e.g.~the low-lying\nlevels of a Lambda system \\cite{brion2007adiabatic,\n  james2007effective, reiter2012effective, sanz2016adiabatic}.  Unlike\nthe perturbative, but exact Schieffer-Wolff transformation, adiabatic\nelimination methods use approximations which rely on the fast dynamics\nof excited states.  While generally reasonable, these approximations\nmust be made carefully to avoid potential problems with\nself-consistency (see section 3 of ref.~\\cite{brion2007adiabatic}),\nand yield no obvious or straightforward means to compute effective\ncorrections beyond second order in the couplings between low- and\nhigh-energy sectors of a Hilbert space \\cite{james2007effective,\n  reiter2012effective, sanz2016adiabatic}.  While at least one attempt\nat systematically computing higher-order corrections in the framework\nof adiabatic elimination has recently been made\n\\cite{sanz2016adiabatic}, the resulting expressions do not lend\nthemselves as nicely to analytical treatment, and were in any case\nfound by the authors to be equivalent to a Schrieffer-Wolff\ntransformation.\n\n\n\\subsection{Diagrammatic representation of effective Hamiltonians}\n\nThe form of the bare two-body interaction Hamiltonian $H_{\\t{int}}$ in\n\\eqref{eq:H_int} motivates a diagrammatic representation of terms in\nthe effective Hamiltonian $H_{\\t{eff}}$ in \\eqref{eq:H_int_eff},\nsimilarly to the diagrams used to represent elements of the scattering\nmatrix in standard quantum field theory.  Effective $M$-body\ninteraction terms at order $p$ in $H_{\\t{int}}$ can be represented by\ndirected graphs containing $p$ vertices with degree greater than one,\nwhich we call {\\it internal vervices}.  Each internal vertex and its\nassociated edges correspond respectively to a coupling constant and\nthe associated field operators in $H_{\\t{int}}$.  An example 2-vertex\ndiagram representing an effective 3-body interaction term is provided\nin figure \\ref{fig:diagram}.  All diagrams are read from left to right\nto construct a sequence of operators from right to left; the internal\nvertices of a diagram are thus strictly ordered, with the $n$-th\ninternal vertex from the left corresponding to the $n$-th interaction\nHamiltonian $H_{\\t{int}}$ from the right in \\eqref{eq:H_int_1_2} or\n\\eqref{eq:H_int_3}.  Solid (dashed) lines represent field operators\nacting on the lowest (arbitrary) motional states.  Spatial overlap\nfactors at each vertex are determined by the motional states of the\nedges which connect to (i.e.~field operators associated with) that\nvertex.  While it is possible to construct explicit rules for\ndetermining the energetic suppression factors (i.e.~from $\\I$) of the\nterm represented by a diagram, these factors are most easily\ndetermined by examination of the effective Hamiltonians in\n\\eqref{eq:H_int_1_2} and \\eqref{eq:H_int_3}.\n\n\\begin{figure}\n  \\centering\n  \\(\n  \\begin{tikzpicture}\n    \\begin{feynman}\n      \\vertex (v1);\n      \\vertex[above left = of v1] (f1) {$\\bmu,\\g$};\n      \\vertex[below left = of v1] (f2) {$\\onu,\\re$};\n      \\vertex[right = of v1] (vm);\n      \\vertex[right = of vm] (v2);\n      \\vertex[above = of vm] (f3) {$\\bmu,\\g$};\n      \\vertex[below = of vm] (f4) {$\\grho,\\g$};\n      \\vertex[below right = of v2] (f5) {$\\grho,\\re$};\n      \\vertex[above right = of v2] (f6) {$\\onu,\\g$};\n      \\vertex [left = 0.5em of v1] {$G^{\\g\\re}_{\\g\\re}$};\n      \\vertex [right = 0.5em of v2] {$G^{\\re\\g}_{\\g\\re}$};\n      \\diagram* {\n        (f1) --[fermion, color = lightblue] (v1)\n        --[fermion, color = lightblue] (f3),\n        (f2) --[fermion, color = orange] (v1)\n        --[charged scalar,\n        edge label = {$\\mathcolor{black}{n}\n          \\mathcolor{orange}{\\nu}\\mathcolor{black}{,\\re}$},\n        color = orange] (v2),\n        (f4) --[fermion, color = green] (v2)\n        --[fermion, color = green] (f5),\n        (v2) --[fermion, color = orange] (f6), };\n    \\end{feynman}\n  \\end{tikzpicture}\n  \\begin{array}{ll}\n    &= \\P_0 \\p{\\f12 K_n G^{\\re\\g}_{\\g\\re}\n      \\c_{\\onu,\\g}^\\dag \\c_{\\grho,\\re}^\\dag\n      \\c_{\\grho,\\g} \\c_{n\\onu,\\re}}\n      \\f1{E_n}\n      \\p{\\f12 K_n G^{\\g\\re}_{\\g\\re}\n      \\c_{\\bmu,\\g}^\\dag \\c_{n\\onu,\\re}^\\dag\n      \\c_{\\onu,\\re} \\c_{\\bmu,\\g}} \\P_0 \\\\[1em]\n    &= \\f14 \\f{K_n^2}{E_n}~ G^{\\g\\re}_{\\g\\re} G^{\\re\\g}_{\\g\\re}~\n      \\P_0 \\c_{\\bmu,\\g}^\\dag \\c_{\\onu,\\g}^\\dag \\c_{\\grho,\\re}^\\dag\n      \\c_{\\grho,\\g} \\c_{\\onu,\\re} \\c_{\\bmu,\\g} \\P_0\n  \\end{array}\n  \\)\n  \\caption{\\footnotesize An example second-order diagram and the\n    corresponding three-body interaction term in $H_{\\t{int}}^{(2)}$,\n    with $n>0$ and $\\c_{\\mu s}\\equiv\\c_{0,\\mu s}$.  Diagrams are read\n    from left to right to construct a sequence of operators from right\n    to left.  Solid (dashed) lines represent field operators acting on\n    the lowest (arbitrary) motional states.  For the sake of\n    presentation, this diagram has colors associated with nuclear spin\n    and orbital states, an arrow on each line to emphasize that they\n    are directed left-to-right, and an explicit coupling constant\n    written next to each vertex; we will generally not include these\n    features, as they are not necessary to uniquely identify the term\n    represented by a diagram.  We will also drop explicit appearances\n    of the ground-state projector $\\P_0$ in our expressions, with the\n    understanding that the low-energy effective theory implicitly\n    addresses only non-interacting motional ground states.}\n  \\label{fig:diagram}\n\\end{figure}\n\nThe diagram in figure \\ref{fig:diagram} explicitly labels all edges\nwith indices of the corresponding field operators, but in general we\nmay suppress these indices, in which case the diagram includes a sum\nover the suppressed indices.  These sums are performed over all\nallowed values of the suppressed indices, with the restriction that\nvirtual states (i.e.~vertical slices of the diagram between internal\nvertices) represented with dashed lines must have at least one\nmotional excitation.  While we include factors of $1/2$ from\n$H_{\\t{int}}$ as expressed in \\eqref{eq:H_int} in the definition of a\ndiagram, in all but the two-body case these factors of $1/2$ will be\ncancelled out by corresponding symmetry factors, i.e.~the appearance\nof duplicate diagrams which are equal up to a relabeling of indices\n(see Appendix \\ref{sec:diagrams}).  The explicit signs and factor of\n$1/2$ which appear in the effective Hamiltonians in\n\\eqref{eq:H_int_1_2} and \\eqref{eq:H_int_3} are not included in the\ndefinition of a diagram, and must be kept track of manually.\n\n\n\\subsection{Effective two-body interactions and renormalization}\n\\label{sec:two_body}\n\nThe effective two-body Hamiltonian in \\eqref{eq:H_int_eff} has\ncontributions at all orders in the coupling constants, and can be\nexpanded in the form\n\\begin{align}\n  H_2 = \\shrink{\n    \\begin{tikzpicture}\n      \\begin{feynman}\n        \\vertex (v);\n        \\vertex[above left = of v] (f1);\n        \\vertex[below left = of v] (f2);\n        \\vertex[above right = of v] (f3);\n        \\vertex[below right = of v] (f4);\n        \\diagram* {\n          (f1) -- (v),\n          (f2) -- (v),\n          (v) -- (f3),\n          (v) -- (f4) };\n      \\end{feynman}\n    \\end{tikzpicture}}\n  - \\shrink{\n    \\begin{tikzpicture}\n      \\begin{feynman}\n        \\vertex (v1);\n        \\vertex[above left = of v1] (f1);\n        \\vertex[below left = of v1] (f2);\n        \\vertex[right = of v1] (v2);\n        \\vertex[above right = of v2] (f3);\n        \\vertex[below right = of v2] (f4);\n        \\diagram* {\n          (f1) -- (v1),\n          (f2) -- (v1),\n          (v2) -- (f3),\n          (v2) -- (f4),\n          (v1) --[scalar, half left] (v2),\n          (v1) --[scalar, half right] (v2) };\n      \\end{feynman}\n    \\end{tikzpicture}}\n  + \\shrink{\n    \\begin{tikzpicture}\n      \\begin{feynman}\n        \\vertex (v1);\n        \\vertex[above left = of v1] (f1);\n        \\vertex[below left = of v1] (f2);\n        \\vertex[right = of v1] (v2);\n        \\vertex[right = of v2] (v3);\n        \\vertex[above right = of v3] (f3);\n        \\vertex[below right = of v3] (f4);\n        \\diagram* {\n          (f1) -- (v1),\n          (f2) -- (v1),\n          (v3) -- (f3),\n          (v3) -- (f4),\n          (v1)\n          --[scalar, half left] (v2)\n          --[scalar, half left] (v3),\n          (v1)\n          --[scalar, half right] (v2)\n          --[scalar, half right] (v3) };\n      \\end{feynman}\n    \\end{tikzpicture}}\n  + \\cdots \\equiv \\shrink{\n    \\begin{tikzpicture}\n      \\begin{feynman}\n        \\vertex[blob] (v) {};\n        \\vertex[above left = of v] (f1);\n        \\vertex[below left = of v] (f2);\n        \\vertex[above right = of v] (f3);\n        \\vertex[below right = of v] (f4);\n        \\diagram* {\n          (f1) -- (v),\n          (f2) -- (v),\n          (v) -- (f3),\n          (v) -- (f4) };\n      \\end{feynman}\n    \\end{tikzpicture}},\n  \\label{eq:H_2_expansion}\n\\end{align}\nwhere the blob on the right schematically represents the net effective\ntwo-body interaction.  On physical grounds, the net two-body\ninteraction must clearly be finite, but individual sums over excited\nstates in the loop diagrams of \\eqref{eq:H_2_expansion} may generally\ndiverge \\cite{johnson2012effective}.  These divergences ultimately\nappear due to our use of effective field theory to describe\ninter-atomic interactions in \\eqref{eq:H_int_start},\n\\eqref{eq:H_int_fields}, and \\eqref{eq:H_int}, rather than a detailed\nmicroscopic description of two-atom scattering.  Divergences of this\nsort are a generic feature of field theories, and can be dealt with\nusing standard techniques such as renormalization.  We therefore\nrenormalize our coupling constants by introducing counter-terms\n$\\widetilde G_X$ into the interaction Hamiltonian.\n\nThe introduction of counter-terms is merely a formal decomposition of\nthe ``bare'' coupling constants $G_X^{\\t{bare}}$ that are used in\n\\eqref{eq:H_2_expansion} as $G_X^{\\t{bare}} = G_X + \\widetilde G_X$.\nIn performing such a decomposition, we are free to choose the values\nof $G_X$, which in turn fixes the values of\n$\\widetilde G_X \\equiv G_X^{\\t{bare}} - G_X$.  For convenience, we can\nchoose the values of $G_X$ to be those of the net effective coupling\nconstants on the right-hand side of \\eqref{eq:H_2_expansion}.\nRepresenting the new coupling constants $G_X$ by regular vertices and\nthe counter-terms $\\widetilde G_X$ by a crossed dot (i.e.~$\\otimes$),\nthis choice leads to the {\\it renormalization condition}\n\\begin{align}\n  \\substack{\n    \\shrink{\n      \\begin{tikzpicture}\n        \\begin{feynman}\n          \\vertex (v);\n          \\vertex[above left = of v] (f1);\n          \\vertex[below left = of v] (f2);\n          \\vertex[above right = of v] (f3);\n          \\vertex[below right = of v] (f4);\n          \\diagram* {\n            (f1) -- (v),\n            (f2) -- (v),\n            (v) -- (f3),\n            (v) -- (f4) };\n        \\end{feynman}\n      \\end{tikzpicture}}\n    \\\\ \\O(G)}\n  + \\substack{\n    \\shrink{\n      \\begin{tikzpicture}\n        \\begin{feynman}\n          \\vertex[crossed dot] (v) {};\n          \\vertex[above left = of v] (f1);\n          \\vertex[below left = of v] (f2);\n          \\vertex[above right = of v] (f3);\n          \\vertex[below right = of v] (f4);\n          \\diagram* {\n            (f1) -- (v),\n            (f2) -- (v),\n            (v) -- (f3),\n            (v) -- (f4) };\n        \\end{feynman}\n      \\end{tikzpicture}}\n    \\\\ \\O(\\widetilde G)}\n  - \\substack{\n    \\shrink{\n      \\begin{tikzpicture}\n        \\begin{feynman}\n          \\vertex (v1);\n          \\vertex[above left = of v1] (f1);\n          \\vertex[below left = of v1] (f2);\n          \\vertex[right = of v1] (v2);\n          \\vertex[above right = of v2] (f3);\n          \\vertex[below right = of v2] (f4);\n          \\diagram* {\n            (f1) -- (v1),\n            (f2) -- (v1),\n            (v2) -- (f3),\n            (v2) -- (f4),\n            (v1) --[scalar, half left] (v2),\n            (v1) --[scalar, half right] (v2) };\n        \\end{feynman}\n      \\end{tikzpicture}}\n    \\\\ \\O(G^2)}\n  + \\cdots = \\substack{\n    \\shrink{\n      \\begin{tikzpicture}\n        \\begin{feynman}\n          \\vertex (v);\n          \\vertex[above left = of v] (f1);\n          \\vertex[below left = of v] (f2);\n          \\vertex[above right = of v] (f3);\n          \\vertex[below right = of v] (f4);\n          \\diagram* {\n            (f1) -- (v),\n            (f2) -- (v),\n            (v) -- (f3),\n            (v) -- (f4) };\n        \\end{feynman}\n      \\end{tikzpicture}}\n    \\\\ \\O(G)}.\n  \\label{eq:counter_term}\n\\end{align}\nThis renormalization condition has the benefit of allowing us to\nexpress effective two-body interactions simply in terms of net\neffective two-body coupling constants, rather than in terms of long\nsums at all order of the bare coupling constants.  By construction,\nthe counter-terms we have introduced exactly cancel all terms beyond\nleading order in \\eqref{eq:H_2_expansion}, which implies that the\neffective two-body interaction Hamiltonian is simply\n\\begin{align}\n  H_2 = \\shrink{\n    \\begin{tikzpicture}\n      \\begin{feynman}\n        \\vertex (v);\n        \\vertex[above left = of v] (f1);\n        \\vertex[below left = of v] (f2);\n        \\vertex[above right = of v] (f3);\n        \\vertex[below right = of v] (f4);\n        \\diagram* {\n          (f1) -- (v),\n          (f2) -- (v),\n          (v) -- (f3),\n          (v) -- (f4), };\n      \\end{feynman}\n    \\end{tikzpicture}}\n  = \\f12 \\alpha_2^{(1)} \\sum_{\\abs{\\set{\\mu,\\nu}}=2} G^{qr}_{st}\n  \\c_{\\mu s}^\\dag \\c_{\\nu t}^\\dag \\c_{\\nu r} \\c_{\\mu q},\n  \\label{eq:H_2}\n\\end{align}\nwhere for consistency with existing literature\n\\cite{johnson2012effective} we define $\\alpha_2^{(1)} \\equiv K$ as the\noverlap integral between two atoms occupying non-interacting motional\nground states.\n\nBefore moving on to consider effective three-body interactions, there\nare a few comments we must make concerning renormalization and the\nresult in \\eqref{eq:H_2}.  First, the effective two-body interaction\n$H_2$ in \\eqref{eq:H_2} takes the same form as the bare two-body\ninteraction $H_{\\t{int}}$ in \\eqref{eq:H_int}, but without excited\nmotional states, and with renormalized coupling constants.  Our choice\nof renormalization scheme, while convenient for the analytical\ndevelopment of a low-energy effective theory, no longer allows us to\nuse the coupling constants $G_X$ as defined by the free-space\nscattering lengths $a_X$ in \\eqref{eq:couplings} to compute\ninteraction energies.  The renormalization condition in\n\\eqref{eq:counter_term} explicitly fixes $G_X$ to the net effective\ncoupling constants in any given setting.  Instead of using free-space\ncoupling constants to compute interaction energies in a lattice, we\nmust therefore first compute the effective coupling constants\n$G_X^{\\t{lattice}}\\p{\\U}$, which now depend on the lattice depth $\\U$,\nand in turn use these effective coupling constants to compute\ninteraction energies.  We discuss the calculation of effective\ncoupling constants in Appendix \\ref{sec:renormalization}.\n\nSecond, the renormalization condition in \\eqref{eq:counter_term}\nimplies that the counter terms $\\widetilde G_X$ are second order in\nthe coupling constants $G_X$, i.e.~$\\widetilde G_X\\sim G_X^2$.\nAlthough the effective Hamiltonian expansions in \\eqref{eq:H_int_1_2}\nand \\eqref{eq:H_int_3} are organized in powers of the interaction\nHamiltonian $H_{\\t{int}}$, the couplings $G_X$ are the ``small''\nparameters in which we can formally organize a perturbation theory;\nmore specifically, the formally small quantities organizing our\nperturbation theory are two-body ground-state interaction energies\n(proportional to the couplings $G_X$) divided by the spectral gap of\nthe single-atom Hamiltonian $H_0$ (see Appendix\n\\ref{sec:pert_params}).  If $M$ atoms can only couple through terms\nrepresented by a $p$-vertex diagrams for $p\\ge p_M^{\\t{min}}$, then\nthe leading order contribution to $M$-body interactions is order\n$p_M^{\\t{min}}$ in the couplings $G_X$.  If the same\n$p_M^{\\t{min}}$-vertex diagrams involve any counter-terms, however,\nthen these diagrams are at least order $p_M^{\\t{min}}+1$ in the\ncouplings $G_X$.  Counter-terms therefore only appear at\nnext-to-leading order (NLO) in the calculation of effective $M$-body\ninteractions.\n\nFinally, our result in \\eqref{eq:H_2} neglects the effect of\nmomentum-dependent two-body scattering.  When the effective range of\ninteractions is comparable to the scattering lengths $a_X$, as is the\ncase for ultracold ${}^{87}$Sr, these momentum-dependent effects are\nthird order in the coupling constants $G_X$.  Just as the $\\O\\p{G^2}$\ncounter-terms do not affect $M$-body interactions until\nnext-to-leading order (NLO), the $\\O\\p{G^3}$ momentum-dependent terms\ndo not come into play until next-next-leading order (NNLO).  Given\nthat we develop our low-energy effective theory through third order in\nthe coupling constants, these interactions will not appear in any of\nour three- and four-body calculations, but they do need to be\nconsidered in the calculation of pair-wise interaction energies.  The\nprimary interest of our work, however, concerns effective $M$-body\ninteractions for $M\\ge3$; we therefore defer the calculation of\nmomentum-dependent two-body interactions to Appendix\n\\ref{sec:momentum_dependence}.\n\n\n\\subsection{Effective three-body interactions at second order}\n\nOur theory of effective multi-body interactions assumes no\nnon-universal contribution to the three-body interaction energy, which\nis to say that we assume the absence of real (as opposed to\neffective), bare three-body interactions.  Consequently, three-body\ninteractions do not appear until second order in the coupling\nconstants of the effective theory, in the expansion of\n$H_{\\t{int}}^{(2)}$ in \\eqref{eq:H_int_1_2}.  The virtual state of\nthree-body terms in $H_{\\t{int}}^{(2)}$ cannot have two atoms in\nexcited motional states, as otherwise the second application of\n$H_{\\t{int}}$ in $H_{\\t{int}}^{(2)}$ would have to address both of\ntheses atoms to bring them back down to the ground state, resulting in\na two-body process as in the second diagram of\n\\eqref{eq:H_2_expansion}.  All second-order three-body terms must\ntherefore have only one excited atom in the virtual state, and take\nthe form\n\\begin{align}\n  \\begin{tikzpicture}\n    \\begin{feynman}\n      \\vertex (v1);\n      \\vertex[above left = of v1] (f1) {$\\mu r$};\n      \\vertex[below left = of v1] (f2) {$\\nu s$};\n      \\vertex[right = of v1] (vm);\n      \\vertex[right = of vm] (v2);\n      \\vertex[above = of vm] (f3) {$\\mu r'$};\n      \\vertex[below = of vm] (f4) {$\\rho t$};\n      \\vertex[below right = of v2] (f5) {$\\rho t'$};\n      \\vertex[above right = of v2] (f6) {$\\nu s''$};\n      \\diagram* {\n        (f1) -- (v1) -- (f3),\n        (f2) -- (v1) --  [scalar, edge label=$n\\nu s'$] (v2),\n        (f4) -- (v2) -- (f5),\n        (v2) -- (f6), };\n    \\end{feynman}\n  \\end{tikzpicture}\n  \\propto K_n^2 G^{rs}_{r's'} G^{s't}_{s''t'}\n  \\c_{\\mu r'}^\\dag \\c_{\\nu s''}^\\dag \\c_{\\rho t'}^\\dag\n  \\c_{\\rho t} \\c_{\\nu s} \\c_{\\mu r}\n  \\label{eq:H_3_2_diagram}.\n\\end{align}\nUnlike for the two-body diagram in \\eqref{eq:H_2}, the explicit\nfactors of $1/2$ which appear in the bare two-body Hamiltonian\n$H_{\\t{int}}$ in \\eqref{eq:H_int} are now cancelled out by symmetry\nfactors which account for duplicate diagrams; this cancellation will\ngenerally occur for all connected $M$-body diagrams with $M>2$ (see\nAppendix \\ref{sec:diagrams}).  The net effective three-body\ninteraction Hamiltonian at second order is then given by the sum over\nall diagrams of the form in \\eqref{eq:H_3_2_diagram}, i.e.\n\\begin{align}\n  H_3^{(2)} = - \\shrink{\n    \\begin{tikzpicture}\n      \\begin{feynman}\n        \\vertex (v1);\n        \\vertex[above left = of v1] (f1);\n        \\vertex[below left = of v1] (f2);\n        \\vertex[right = 4em of v1] (v2);\n        \\vertex[above right = of v1] (f3);\n        \\vertex[below left = of v2] (f4);\n        \\vertex[below right = of v2] (f5);\n        \\vertex[above right = of v2] (f6);\n        \\diagram* {\n          (f1) -- (v1) -- (f3),\n          (f2) -- (v1) --[scalar] (v2),\n          (f4) -- (v2) -- (f5),\n          (v2) -- (f6), };\n      \\end{feynman}\n    \\end{tikzpicture}}\n  = -\\alpha_3^{(2)} \\sum_{\\abs{\\set{\\mu,\\nu,\\rho}}=3}\n  G^{rs}_{r's'} G^{s't}_{s''t'}\n  \\c_{\\mu r'}^\\dag \\c_{\\nu s''}^\\dag \\c_{\\rho t'}^\\dag\n  \\c_{\\rho t} \\c_{\\nu s} \\c_{\\mu r},\n  \\label{eq:H_3_2}\n\\end{align}\nwhere $\\alpha_3^{(2)} \\equiv \\sum_{n>0} K_n^2/E_n$, and the preceding\nminus sign is as prescribed by $H_{\\t{int}}^{(2)}$ in\n\\eqref{eq:H_int_1_2}.\n\n\n\\subsection{Effective three-body interactions at third order}\n\nThe third-order effective interaction Hamiltonian $H_{\\t{int}}^{(3)}$\nin \\eqref{eq:H_int_3} contains both three- and four-body terms.  To\ncompactly enumerate and evaluate all three-body diagrams at third\norder, we introduce an expanded coupling symbol\n\\begin{align}\n  G^{\\mu q;\\nu r}_{\\rho s;\\sigma t} \\equiv \\left\\{\n    \\begin{array}{ll}\n      G^{qr}_{st} & ~ \\p{\\mu,\\nu} = \\p{\\rho,\\sigma}\n      \\\\\n      - G^{qr}_{ts} & ~ \\p{\\mu,\\nu} = \\p{\\sigma,\\rho}\n      \\\\\n      0 & ~ \\t{otherwise}\n    \\end{array}\\right.\n  \\label{eq:G_expanded}\n\\end{align}\nfor more general\n$\\p{\\mu,q}+\\p{\\nu,r}\\leftrightarrow\\p{\\rho,s}+\\p{\\sigma,t}$ coupling\ninduced by terms proportional to\n$\\c_{\\rho s}^\\dag \\c_{\\sigma t}^\\dag \\c_{\\nu r} \\c_{\\mu q}$.  The\nminus sign in \\eqref{eq:G_expanded} accounts for fermionic statistics:\nif $\\p{\\mu,\\nu}=\\p{\\sigma,\\rho}$, then we are considering a term of\nthe form\n\\begin{align}\n  G^{\\mu q;\\nu r}_{\\nu s;\\mu t}\n  \\c_{\\nu s}^\\dag \\c_{\\mu t}^\\dag \\c_{\\nu r} \\c_{\\mu q}\n  = -G^{qr}_{ts} \\c_{\\nu s}^\\dag \\c_{\\mu t}^\\dag \\c_{\\nu r} \\c_{\\mu q}\n  = G^{qr}_{ts} \\c_{\\mu t}^\\dag \\c_{\\nu s}^\\dag \\c_{\\nu r} \\c_{\\mu q}.\n\\end{align}\nAt the cost of introducing an additional sum over new nuclear spin\nindices, the expanded coupling symbol allows us to collect together\ndiagrams which have the same graph topology, but represent different\nmatrix elements of the effective Hamiltonian due to the exchange of\nnuclear spins at a vertex.  The third order three-body diagrams in\n$H_{\\t{int}}^{(3)}$ are then\n\\begin{align}\n  \\begin{tikzpicture}\n    \\begin{feynman}\n      \\vertex (v1);\n      \\vertex[below right = of v1] (v2);\n      \\vertex[above right = of v2] (v3);\n      \\vertex[above left = of v1] (f1) {$\\mu r$};\n      \\vertex[left = of v1] (f2) {$\\nu s$};\n      \\vertex[below left = of v2] (f3) {$\\rho t$};\n      \\vertex[above right = of v3] (f4) {$\\mu r''$};\n      \\vertex[right = of v3] (f5) {$\\nu's'''$};\n      \\vertex[below right = of v2] (f6) {$\\rho't'$};\n      \\diagram* {\n        (f1) -- (v1) --[scalar, edge label=$\\ell\\mu r'$] (v3) -- (f4),\n        (f2) -- (v1)\n        --[scalar, edge label'=$m\\nu s'$] (v2)\n        --[scalar, edge label'=$n\\nu's''$] (v3)\n        -- (f5),\n        (f3) -- (v2) -- (f6), };\n    \\end{feynman}\n  \\end{tikzpicture}\n  \\propto K_{\\ell m} K^m_n K_{\\ell n}\n  G^{rs}_{r's'} G^{\\nu s';\\rho t}_{\\nu's'';\\rho't'} G^{r's''}_{r''s'''}\n  \\c_{\\mu r''}^\\dag \\c_{\\nu's'''}^\\dag \\c_{\\rho't'}^\\dag\n  \\c_{\\rho t} \\c_{\\nu s} \\c_{\\mu r},\n  \\label{eq:H_3_3_S}\n\\end{align}\n\\begin{align}\n  \\begin{tikzpicture}\n    \\begin{feynman}\n      \\vertex (v1);\n      \\vertex[right = of v1] (v2);\n      \\vertex[below right = of v2] (v3);\n      \\vertex[above left = of v1] (f1) {$\\mu r$};\n      \\vertex[below left = of v1] (f2) {$\\nu s$};\n      \\vertex[below left = of v3] (f3) {$\\rho t$};\n      \\vertex[above right = of v2] (f4) {$\\mu r''$};\n      \\vertex[above right = of v3] (f5) {$\\nu s'''$};\n      \\vertex[below right = of v3] (f6) {$\\rho t'$};\n      \\diagram* {\n        (f1) -- (v1)\n        --[half left, scalar, edge label=$\\ell\\mu r'$] (v2)\n        -- (f4),\n        (f2) -- (v1)\n        --[half right, scalar, edge label'=$m\\nu s'$] (v2)\n        --[scalar, edge label=$n\\nu s''$] (v3)\n        -- (f5),\n        (f3) -- (v3) -- (f6), };\n    \\end{feynman}\n  \\end{tikzpicture}\n  \\propto K_{\\ell m} K^{\\ell m}_n K_n\n  G^{rs}_{r's'} G^{r's'}_{r''s''} G^{s''t}_{s'''t'}\n  \\c_{\\mu r''}^\\dag \\c_{\\nu s'''}^\\dag \\c_{\\rho t'}^\\dag\n  \\c_{\\rho t} \\c_{\\nu s} \\c_{\\mu r},\n  \\label{eq:H_3_3_O}\n\\end{align}\nand the mirror image of \\eqref{eq:H_3_3_O}.  As prescribed by\n$H_{\\t{int}}^{(3)}$ in \\eqref{eq:H_int_3}, these diagrams have an\nassociated minus sign if they contain only one excited virtual state,\nand a factor of $1/2$ if they contain a virtual ground state.\nRemembering that counter-terms are $\\O\\p{G^2}$, there are additionally\ntwo third-order three-body diagrams in $H_{\\t{int}}^{(2)}$, namely\n\\begin{align}\n  \\begin{tikzpicture}\n    \\begin{feynman}\n      \\vertex[crossed dot] (v1) {};\n      \\vertex[above left = 4em of v1] (f1) {$\\mu r$};\n      \\vertex[below left = 4em of v1] (f2) {$\\nu s$};\n      \\vertex[right = 4em of v1] (v2);\n      \\vertex[above right = 4em of v1] (f3) {$\\mu r'$};\n      \\vertex[below left = of v2] (f4) {$\\rho t$};\n      \\vertex[below right = of v2] (f5) {$\\rho t'$};\n      \\vertex[above right = of v2] (f6) {$\\nu s''$};\n      \\diagram* {\n        (f1) -- (v1) -- (f3),\n        (f2) -- (v1)\n        --[scalar, edge label=$n\\nu s'$] (v2),\n        (f4) -- (v2) -- (f5),\n        (v2) -- (f6), };\n    \\end{feynman}\n  \\end{tikzpicture}\n  \\propto K_n^2 \\widetilde G^{rs}_{r's'} G^{s't}_{s''t'}\n  \\c_{\\mu r'}^\\dag \\c_{\\nu s''}^\\dag \\c_{\\rho t'}^\\dag\n  \\c_{\\rho t} \\c_{\\nu s} \\c_{\\mu r}\n  \\label{eq:H_3_3_counter_term}\n\\end{align}\nand its mirror image, where $\\widetilde G^{qr}_{st}$ is equal to the\ncounter-term associated with $G^{qr}_{st}$.\n\nThe net contribution to the third-order three-body interaction\nHamiltonian from three-particle-loop diagrams of the form in\n\\eqref{eq:H_3_3_S} is\n\\begin{align}\n  \\shrink{\n    \\begin{tikzpicture}\n      \\begin{feynman}\n        \\vertex (v1);\n        \\vertex[below right = of v1] (v2);\n        \\vertex[above right = of v2] (v3);\n        \\vertex[above left = of v1] (f1);\n        \\vertex[left = of v1] (f2);\n        \\vertex[below left = of v2] (f3);\n        \\vertex[above right = of v3] (f4);\n        \\vertex[right = of v3] (f5);\n        \\vertex[below right = of v2] (f6);\n        \\diagram* {\n          (f1) -- (v1) --[scalar] (v3) -- (f4),\n          (f2) -- (v1) --[scalar] (v2) --[scalar] (v3) -- (f5),\n          (f3) -- (v2) -- (f6), };\n      \\end{feynman}\n    \\end{tikzpicture}}\n  - \\f12 \\shrink{\n    \\begin{tikzpicture}\n      \\begin{feynman}\n        \\vertex (v1);\n        \\vertex[below right = of v1] (v2);\n        \\vertex[above right = of v2] (v3);\n        \\vertex[above left = of v1] (f1);\n        \\vertex[left = of v1] (f2);\n        \\vertex[below left = of v2] (f3);\n        \\vertex[above right = of v3] (f4);\n        \\vertex[right = of v3] (f5);\n        \\vertex[below right = of v2] (f6);\n        \\diagram* {\n          (f1) -- (v1) -- (v3) -- (f4),\n          (f2) -- (v1) --[scalar] (v2) -- (v3) -- (f5),\n          (f3) -- (v2) -- (f6), };\n      \\end{feynman}\n    \\end{tikzpicture}}\n  - \\f12 \\shrink{\n    \\begin{tikzpicture}\n      \\begin{feynman}\n        \\vertex (v1);\n        \\vertex[below right = of v1] (v2);\n        \\vertex[above right = of v2] (v3);\n        \\vertex[above left = of v1] (f1);\n        \\vertex[left = of v1] (f2);\n        \\vertex[below left = of v2] (f3);\n        \\vertex[above right = of v3] (f4);\n        \\vertex[right = of v3] (f5);\n        \\vertex[below right = of v2] (f6);\n        \\diagram* {\n          (f1) -- (v1) -- (v3) -- (f4),\n          (f2) -- (v1) -- (v2) --[scalar] (v3) -- (f5),\n          (f3) -- (v2) -- (f6), };\n      \\end{feynman}\n    \\end{tikzpicture}}\n  = \\p{\\alpha_{3,1}^{(3)} - \\alpha_5^{(3)}} \\H_{3,1}^{(3)},\n\\end{align}\nwhere\n\\begin{align}\n  \\alpha_{3,1}^{(3)} \\equiv \\sum_{\\substack{\\ell+m>0\\\\\\ell+n>0}}\n  \\f{K_{\\ell m} K^m_n K_{\\ell n}}{E_{\\ell m} E_{\\ell n}},\n  &&\n  \\alpha_5^{(3)}\n  \\equiv  K \\sum_{n>0} \\f{K_n^2}{E_n^2},\n  \\label{eq:alph_3_3_1}\n\\end{align}\nand\n\\begin{align}\n  \\H_{3,1}^{(3)} \\equiv \\sum_{\\abs{\\set{\\mu,\\nu,\\rho}}=3}\n  G^{rs}_{r's'} G^{\\nu s'\\rho t}_{\\nu's''\\rho't'} G^{r's''}_{r''s'''}\n  \\c_{\\mu r''}^\\dag \\c_{\\nu's'''}^\\dag \\c_{\\rho't'}^\\dag\n  \\c_{\\rho t} \\c_{\\nu s} \\c_{\\mu r}.\n\\end{align}\nEven though this contribution comes from loop diagrams, the factors\n$\\alpha_{3,1}^{(3)}$ and $\\alpha_5^{(3)}$ in \\eqref{eq:alph_3_3_1} are\nfinite.  At large motional state indices $n$, atoms become free\nparticles for which $n$ essentially indexes discrete momentum states.\nThese atoms thus have an energy which asymptotically scales as\n$E_n\\sim n^2\\equiv n_\\x^2+n_\\y^2+n_\\z^2$.  Furthermore, the\noscillatory behavior of atomic wavefunctions with increasing motional\nstate indices $\\ell,m$ implies that the overlap integral $K_{\\ell m}$\nbecomes sharply peaked at $\\ell\\approx m$ as $\\ell$ and $m$ get large.\nThe asymptotic behavior of $\\alpha_{3,1}^{(3)}$ at large $\\ell,m,n$ is\ntherefore\n\\begin{align}\n  \\alpha_{3,1}^{(3)}\n  \\sim \\int \\f{\\d^3\\ell~\\d^3m~\\d^3n}{\\p{\\ell^2+m^2}\\p{\\ell^2+n^2}}\n  ~\\delta\\p{\\ell-m}\\delta\\p{\\ell-n}\n  \\sim \\int \\f{\\d^3\\ell}{\\ell^4}\n  \\sim \\int_{\\ell_{\\t{min}}}^\\infty \\f{\\d\\ell}{\\ell^2}\n  \\sim \\f1{\\ell_{\\t{min}}},\n  \\label{eq:alph_3_3_1_integral}\n\\end{align}\nwhere in the last integral we changed to spherical coordinates, and\n$\\ell_{\\t{min}}^2$ is the minimum value of $\\ell^2$ for which\n\\begin{enumerate*}\n\\item the energy $E_\\ell\\sim\\ell^2$, and\n\\item the integral expression in \\eqref{eq:alph_3_3_1_integral} is a\n  good approximation to the corresponding sum in\n  \\eqref{eq:alph_3_3_1}.\n\\end{enumerate*}\nNote that the introduction of $\\ell_{\\t{min}}$ amounts to neglecting a\nfinite number of terms in the sum over $\\ell,m,n$ in\n\\eqref{eq:alph_3_3_1}, whose contribution to the value of\n$\\alpha_{3,1}^{(3)}$ is finite.  Convergence of $\\alpha_5^{(3)}$ is\nsimilarly guaranteed by the fact that the overlap integral $K_n$ does\nnot asymptotically grow with increasing $n$, such that\n$\\alpha_5^{(3)}$ asymptotically behaves as\n\\begin{align}\n  \\alpha_5^{(3)} \\sim \\int \\f{\\d^3 n}{n^4}\n  \\sim \\int_{n_{\\t{min}}}^\\infty \\f{\\d n}{n^2}\n  \\sim \\f1{n_{\\t{min}}},\n  \\label{eq:alph_5_3_integral}\n\\end{align}\nwhere again $n_{\\t{min}}$ is defined similarly to $\\ell_{\\t{min}}$.\n\nThe sum over loop diagrams in \\eqref{eq:H_3_3_O}, meanwhile, contains\na divergence that must be cancelled out by the counter-terms in\n\\eqref{eq:H_3_3_counter_term}.  To leading order in the coupling\nconstants, the renormalization condition in \\eqref{eq:counter_term}\nimplies that\n\\begin{align}\n  \\shrink{\n    \\begin{tikzpicture}\n      \\begin{feynman}\n        \\vertex[crossed dot] (v) {};\n        \\vertex[above left = of v] (f1);\n        \\vertex[below left = of v] (f2);\n        \\vertex[above right = of v] (f3);\n        \\vertex[below right = of v] (f4);\n        \\diagram* {\n          (f1) -- (v),\n          (f2) -- (v),\n          (v) -- (f3),\n          (v) -- (f4), };\n      \\end{feynman}\n    \\end{tikzpicture}}\n  = \\shrink{\n    \\begin{tikzpicture}\n      \\begin{feynman}\n        \\vertex (v1);\n        \\vertex[right = of v1] (v2);\n        \\vertex[above left = of v1] (f1);\n        \\vertex[below left = of v1] (f2);\n        \\vertex[above right = of v2] (f3);\n        \\vertex[below right = of v2] (f4);\n        \\diagram* {\n          (f1) -- (v1) --[half left, scalar] (v2) -- (f3),\n          (f2) -- (v1) --[half right, scalar] (v2) -- (f4), };\n      \\end{feynman}\n    \\end{tikzpicture}},\n\\end{align}\nwhich can be expanded to find\n\\begin{align}\n  K \\widetilde G^{rs}_{r''s''}\n  = \\sum_{\\ell,m,r',s'} \\f{K_{\\ell m}^2}{E_{\\ell m}}\n  G^{rs}_{r's'} G^{r's'}_{r''s''}.\n\\end{align}\nIn terms of ordinary coupling constants, the counter-term diagram in\n\\eqref{eq:H_3_3_counter_term} is therefore\n\\begin{align}\n  \\begin{tikzpicture}\n    \\begin{feynman}\n      \\vertex[crossed dot] (v1) {};\n      \\vertex[above left = 4em of v1] (f1) {$\\mu r$};\n      \\vertex[below left = 4em of v1] (f2) {$\\nu s$};\n      \\vertex[right = 4em of v1] (v2);\n      \\vertex[above right = 4em of v1] (f3) {$\\mu r''$};\n      \\vertex[below left = of v2] (f4) {$\\rho t$};\n      \\vertex[below right = of v2] (f5) {$\\rho t'$};\n      \\vertex[above right = of v2] (f6) {$\\nu s'''$};\n      \\diagram* {\n        (f1) -- (v1) -- (f3),\n        (f2) -- (v1)\n        --[scalar, edge label=$n\\nu s''$] (v2),\n        (f4) -- (v2) -- (f5),\n        (v2) -- (f6), };\n    \\end{feynman}\n  \\end{tikzpicture}\n  = \\sum_{\\ell,m,r',s'}\n  \\f{K_{\\ell m}^2 K_n^2}{K E_{\\ell m} E_n}\n  G^{rs}_{r's'} G^{r's'}_{r''s''} G^{s''t}_{s'''t'}\n  \\c_{\\mu r''}^\\dag \\c_{\\nu s'''}^\\dag \\c_{\\rho t'}^\\dag\n  \\c_{\\rho t} \\c_{\\nu s} \\c_{\\mu r}.\n\\end{align}\nAltogether, the contribution to the third-order three-body interaction\nHamiltonian from loop diagrams of the form in \\eqref{eq:H_3_3_O} and\ncounter-term diagrams of the form in \\eqref{eq:H_3_3_counter_term} is\n\\begin{multline}\n  \\shrink{\n    \\begin{tikzpicture}\n      \\begin{feynman}\n        \\vertex (v1);\n        \\vertex[right = of v1] (v2);\n        \\vertex[below right = of v2] (v3);\n        \\vertex[above left = of v1] (f1);\n        \\vertex[below left = of v1] (f2);\n        \\vertex[below left = of v3] (f3);\n        \\vertex[above right = of v2] (f4);\n        \\vertex[above right = of v3] (f5);\n        \\vertex[below right = of v3] (f6);\n        \\diagram* {\n          (f1) -- (v1) --[half left, scalar] (v2) -- (f4),\n          (f2) -- (v1) --[half right, scalar] (v2)\n          --[scalar] (v3) -- (f5),\n          (f3) -- (v3) -- (f6), };\n      \\end{feynman}\n    \\end{tikzpicture}}\n    - \\shrink{\n    \\begin{tikzpicture}\n      \\begin{feynman}\n        \\vertex[crossed dot] (v1) {};\n        \\vertex[right = 4em of v1] (v2);\n        \\vertex[above left = of v1] (f1);\n        \\vertex[below left = of v1] (f2);\n        \\vertex[above right = of v1] (f3);\n        \\vertex[below left = of v2] (f4);\n        \\vertex[below right = of v2] (f5);\n        \\vertex[above right = of v2] (f6);\n        \\diagram* {\n          (f1) -- (v1) -- (f3),\n          (f2) -- (v1) --[scalar] (v2),\n          (f4) -- (v2) -- (f5),\n          (v2) -- (f6), };\n      \\end{feynman}\n    \\end{tikzpicture}}\n  - \\f12 \\shrink{\n    \\begin{tikzpicture}\n      \\begin{feynman}\n        \\vertex (v1);\n        \\vertex[right = of v1] (v2);\n        \\vertex[below right = of v2] (v3);\n        \\vertex[above left = of v1] (f1);\n        \\vertex[below left = of v1] (f2);\n        \\vertex[below left = of v3] (f3);\n        \\vertex[above right = of v2] (f4);\n        \\vertex[above right = of v3] (f5);\n        \\vertex[below right = of v3] (f6);\n        \\diagram* {\n          (f1) -- (v1) --[half left, scalar] (v2) -- (f4),\n          (f2) -- (v1) --[half right, scalar] (v2)\n          -- (v3) -- (f5),\n          (f3) -- (v3) -- (f6), };\n      \\end{feynman}\n    \\end{tikzpicture}}\n  - \\f12 \\shrink{\n    \\begin{tikzpicture}\n      \\begin{feynman}\n        \\vertex (v1);\n        \\vertex[right = of v1] (v2);\n        \\vertex[below right = of v2] (v3);\n        \\vertex[above left = of v1] (f1);\n        \\vertex[below left = of v1] (f2);\n        \\vertex[below left = of v3] (f3);\n        \\vertex[above right = of v2] (f4);\n        \\vertex[above right = of v3] (f5);\n        \\vertex[below right = of v3] (f6);\n        \\diagram* {\n          (f1) -- (v1) --[half left] (v2) -- (f4),\n          (f2) -- (v1) --[half right] (v2)\n          --[scalar] (v3) -- (f5),\n          (f3) -- (v3) -- (f6), };\n      \\end{feynman}\n    \\end{tikzpicture}} \\\\\n  = \\p{\\alpha_{3,2}^{(3)} - \\f12\\alpha_{4,3}^{(3)} - \\f12\\alpha_5^{(3)}}\n  \\H_{3,2}^{(3)},\n\\end{multline}\nwhere\n\\begin{align}\n  \\alpha_{3,2}^{(3)}\n  \\equiv \\sum_{\\substack{\\ell+m>0\\\\n>0}}\n  \\f{K_{\\ell m} K_n}{E_{\\ell m} E_n}\n  \\p{K^{\\ell m}_n - \\f{K_{\\ell m} K_n}{K}},\n  &&\n  \\alpha_{4,3}^{(3)}\n  \\equiv K \\sum_{m+n>0} \\f{K_{mn}^2}{E_{mn}^2},\n  \\label{eq:alph_3_3_2}\n\\end{align}\nand\n\\begin{align}\n  \\H_{3,2}^{(3)} \\equiv \\sum_{\\abs{\\set{\\mu,\\nu,\\rho}}=3}\n  G^{rs}_{r's'} G^{r's'}_{r''s''} G^{s''t}_{s'''t'}\n  \\c_{\\mu r''}^\\dag \\c_{\\nu s'''}^\\dag \\c_{\\rho t'}^\\dag\n  \\c_{\\rho t} \\c_{\\nu s} \\c_{\\mu r}.\n\\end{align}\nAn equal contribution comes from the mirror images of these diagrams,\nsuch that the net third-order three-body interaction Hamiltonian is\n\\begin{align}\n  H_3^{(3)} = \\p{\\alpha_{3,1}^{(3)} - \\alpha_5^{(3)}} \\H_{3,1}^{(3)}\n  + \\p{2\\alpha_{3,2}^{(3)} - \\alpha_{4,3}^{(3)} - \\alpha_5^{(3)}}\n  \\H_{3,2}^{(3)}.\n  \\label{eq:H_3_3}\n\\end{align}\nNote that the aforementioned divergence and its cancellation are\nburied in $\\alpha_{3,2}^{(3)}$.  Formally, this factor is calculated\nby imposing an ultraviolet cutoff $\\Lambda$ for the maximum values of\nmotional state indices $\\ell,m,n$, and then taking the limit\n$\\Lambda\\to\\infty$.  This procedure ensures that there are no\ndivergences in $\\alpha_{3,2}^{(3)}$.\n\n\n\\subsection{Effective four-body interactions at third order}\n\nAt third order in the coupling constants, we have four-body terms of\nthe form\n\\begin{align}\n  \\begin{tikzpicture}\n    \\begin{feynman}\n      \\vertex (v1);\n      \\vertex[above right = 1.5em of v1] (v2);\n      \\vertex[below right = 2.5em of v1] (v3);\n      \\vertex[right = 0.5em of v1] (label)\n      {$\\let\\scriptstyle\\textstyle\\substack{m\\mu q'\\\\n\\nu r'}$};\n      \\vertex[above left = of v1] (f1) {$\\mu q$};\n      \\vertex[below left = of v1] (f2) {$\\nu r$};\n      \\vertex[above left = of v2] (f3) {$\\rho s$};\n      \\vertex[below left = of v3] (f4) {$\\sigma t$};\n      \\vertex[above right = of v2] (f5) {$\\rho s'$};\n      \\vertex[right = of v2] (f6) {$\\mu q''$};\n      \\vertex[right = of v3] (f7) {$\\nu r''$};\n      \\vertex[below right = of v3] (f8) {$\\sigma t'$};\n      \\diagram* {\n        (f1) -- (v1) --[scalar] (v2) -- (f6),\n        (f2) -- (v1) --[scalar] (v3) -- (f7),\n        (f3) -- (v2) -- (f5),\n        (f4) -- (v3) -- (f8),\n      };\n    \\end{feynman}\n  \\end{tikzpicture}\n  \\propto K_{mn} K_m K_n G^{qr}_{q'r'} G^{q's}_{q''s'} G^{r't}_{r''t'}\n  \\c_{\\mu q''}^\\dag \\c_{\\nu r''}^\\dag \\c_{\\rho s'}^\\dag \\c_{\\sigma t'}^\\dag\n  \\c_{\\sigma t} \\c_{\\rho s} \\c_{\\nu r} \\c_{\\mu q}\n  \\label{eq:H_4_3_B}\n\\end{align}\nand its mirror image, as well as\n\\begin{align}\n  \\begin{tikzpicture}\n    \\begin{feynman}\n      \\vertex[label=0:$~m\\mu q'$] (v1);\n      \\vertex[below right = of v1, label=0:$~n\\mu'q''$] (v2);\n      \\vertex[below right = of v2] (v3);\n      \\vertex[above left = of v1] (f1) {$\\mu q$};\n      \\vertex[below left = of v1] (f2) {$\\nu r$};\n      \\vertex[below left = of v2] (f3) {$\\rho s$};\n      \\vertex[below left = of v3] (f4) {$\\sigma t$};\n      \\vertex[above right = of v1] (f5) {$\\nu r'$};\n      \\vertex[above right = of v2] (f6) {$\\rho's'$};\n      \\vertex[above right = of v3] (f7) {$\\sigma t'$};\n      \\vertex[below right = of v3] (f8) {$\\mu'q'''$};\n      \\diagram* {\n        (f1) -- (v1) -- (f5),\n        (f2) -- (v1) -- (f5),\n        (v1) --[scalar] (v2) --[scalar] (v3) -- (f8),\n        (f3) -- (v2) -- (f6),\n        (f4) -- (v3) -- (f7),\n      };\n    \\end{feynman}\n  \\end{tikzpicture}\n  \\propto K_m K^m_n K_n\n  G^{qr}_{q'r'} G^{\\mu q'\\rho s}_{\\mu'q''\\rho's'} G^{q''t}_{q'''t'}\n  \\c_{\\mu'q'''}^\\dag \\c_{\\nu r'}^\\dag \\c_{\\rho's'}^\\dag \\c_{\\sigma t'}^\\dag\n  \\c_{\\sigma t} \\c_{\\rho s} \\c_{\\nu r} \\c_{\\mu q}.\n  \\label{eq:H_4_3_C}\n\\end{align}\nAs we are computing the leading-order contribution to effective\nfour-body interactions, there are no counter-terms contributions.  In\nprinciple, there is now also the possibility to make the disconnected\ndiagrams of the form\n\\begin{align}\n  \\shrink{\n    \\begin{tikzpicture}\n      \\begin{feynman}\n        \\vertex (v1);\n        \\vertex[above left = of v1] (f1);\n        \\vertex[below left = of v1] (f2);\n        \\vertex[right = of v1] (v2);\n        \\vertex[above right = of v2] (f3);\n        \\vertex[below right = of v2] (f4);\n        \\vertex[below = 1em of f2] (f5);\n        \\vertex[below = of f5] (f6);\n        \\vertex[below = 1em of f4] (f7);\n        \\vertex[below = of f7] (f8);\n        \\diagram* {\n          (f1) -- (v1),\n          (f2) -- (v1),\n          (v2) -- (f3),\n          (v2) -- (f4),\n          (v1) --[scalar, half left] (v2),\n          (v1) --[scalar, half right] (v2),\n          (f5) -- (f8),\n          (f6) -- (f7) };\n      \\end{feynman}\n    \\end{tikzpicture}},\n  &&\n  \\shrink{\n    \\begin{tikzpicture}\n      \\begin{feynman}\n        \\vertex (v1);\n        \\vertex[above left = of v1] (f1);\n        \\vertex[below left = of v1] (f2);\n        \\vertex[right = of v1] (v2);\n        \\vertex[above right = of v2] (f3);\n        \\vertex[below right = of v2] (f4);\n        \\vertex[left = of f2] (a1);\n        \\vertex[left = of f4] (a2);\n        \\vertex[below = 1em of a1] (f5);\n        \\vertex[below = of f5] (f6);\n        \\vertex[below = 1em of a2] (f7);\n        \\vertex[below = of f7] (f8);\n        \\diagram* {\n          (f1) -- (v1),\n          (f2) -- (v1),\n          (v2) -- (f3),\n          (v2) -- (f4),\n          (v1) --[scalar, half left] (v2),\n          (v1) --[scalar, half right] (v2),\n          (f5) -- (f8),\n          (f6) -- (f7) };\n      \\end{feynman}\n    \\end{tikzpicture}},\n  &&\n  \\t{and}\n  &&\n  \\shrink{\n    \\begin{tikzpicture}\n      \\begin{feynman}\n        \\vertex (v1);\n        \\vertex[above left = of v1] (f1);\n        \\vertex[below left = of v1] (f2);\n        \\vertex[right = of v1] (v2);\n        \\vertex[above right = of v2] (f3);\n        \\vertex[below right = of v2] (f4);\n        \\vertex[right = of f2] (a1);\n        \\vertex[right = of f4] (a2);\n        \\vertex[below = 1em of a1] (f5);\n        \\vertex[below = of f5] (f6);\n        \\vertex[below = 1em of a2] (f7);\n        \\vertex[below = of f7] (f8);\n        \\diagram* {\n          (f1) -- (v1),\n          (f2) -- (v1),\n          (v2) -- (f3),\n          (v2) -- (f4),\n          (v1) --[scalar, half left] (v2),\n          (v1) --[scalar, half right] (v2),\n          (f5) -- (f8),\n          (f6) -- (f7) };\n      \\end{feynman}\n    \\end{tikzpicture}}.\n\\end{align}\nAs prescribed by $H_{\\t{int}}^{(3)}$ in \\eqref{eq:H_int_3}, however,\nthe second and third of these diagrams pick up a factor of $-1/2$, so\nthe sum over disconnected diagrams vanishes.\n\nThe contribution to the third-order four-body interaction Hamiltonian\nfrom diagrams of the form in \\eqref{eq:H_4_3_B} is\n\\begin{align}\n  \\shrink{\n    \\begin{tikzpicture}\n      \\begin{feynman}\n        \\vertex (v1);\n        \\vertex[above right = 1.5em of v1] (v2);\n        \\vertex[below right = 2.5em of v1] (v3);\n        \\vertex[above left = of v1] (f1);\n        \\vertex[below left = of v1] (f2);\n        \\vertex[above left = of v2] (f3);\n        \\vertex[below left = of v3] (f4);\n        \\vertex[above right = of v2] (f5);\n        \\vertex[right = of v2] (f6);\n        \\vertex[right = of v3] (f7);\n        \\vertex[below right = of v3] (f8);\n        \\diagram* {\n          (f1) -- (v1) --[scalar] (v2) -- (f6),\n          (f2) -- (v1) --[scalar] (v3) -- (f7),\n          (f3) -- (v2) -- (f5),\n          (f4) -- (v3) -- (f8),\n        };\n      \\end{feynman}\n    \\end{tikzpicture}}\n  - \\f12 \\shrink{\n    \\begin{tikzpicture}\n      \\begin{feynman}\n        \\vertex (v1);\n        \\vertex[above right = 1.5em of v1] (v2);\n        \\vertex[below right = 2.5em of v1] (v3);\n        \\vertex[above left = of v1] (f1);\n        \\vertex[below left = of v1] (f2);\n        \\vertex[above left = of v2] (f3);\n        \\vertex[below left = of v3] (f4);\n        \\vertex[above right = of v2] (f5);\n        \\vertex[right = of v2] (f6);\n        \\vertex[right = of v3] (f7);\n        \\vertex[below right = of v3] (f8);\n        \\diagram* {\n          (f1) -- (v1) --[scalar] (v2) -- (f6),\n          (f2) -- (v1) -- (v3) -- (f7),\n          (f3) -- (v2) -- (f5),\n          (f4) -- (v3) -- (f8),\n        };\n      \\end{feynman}\n    \\end{tikzpicture}}\n  = \\p{\\alpha_{4,1}^{(3)} - \\f12\\alpha_5^{(3)}} \\H_{4,1},\n\\end{align}\nwhere\n\\begin{align}\n  \\alpha_{4,1}^{(3)}\n  \\equiv \\sum_{\\substack{m\\ge0\\\\n>0}} \\f{K_{mn} K_m K_n}{E_{mn} E_n},\n\\end{align}\nand\n\\begin{align}\n  \\H_{4,1}^{(3)}\n  \\equiv \\sum_{\\abs{\\set{\\mu,\\nu,\\rho,\\sigma}}=4}\n  G^{qr}_{q'r'} G^{q's}_{q''s'} G^{r't}_{r''t'}\n  \\c_{\\mu q''}^\\dag \\c_{\\nu r''}^\\dag \\c_{\\rho s'}^\\dag \\c_{\\sigma t'}^\\dag\n  \\c_{\\sigma t} \\c_{\\rho s} \\c_{\\nu r} \\c_{\\mu q}.\n\\end{align}\nAn equal contribution comes from the mirror images of these diagrams.\nThe contribution from diagrams of the form in \\eqref{eq:H_4_3_C},\nmeanwhile, is\n\\begin{align}\n  \\shrink{\n    \\begin{tikzpicture}\n      \\begin{feynman}\n        \\vertex (v1);\n        \\vertex[below right = of v1] (v2);\n        \\vertex[below right = of v2] (v3);\n        \\vertex[above left = of v1] (f1);\n        \\vertex[below left = of v1] (f2);\n        \\vertex[below left = of v2] (f3);\n        \\vertex[below left = of v3] (f4);\n        \\vertex[above right = of v1] (f5);\n        \\vertex[above right = of v2] (f6);\n        \\vertex[above right = of v3] (f7);\n        \\vertex[below right = of v3] (f8);\n        \\diagram* {\n          (f1) -- (v1) -- (f5),\n          (f2) -- (v1) -- (f5),\n          (v1) --[scalar] (v2) --[scalar] (v3) -- (f8),\n          (f3) -- (v2) -- (f6),\n          (f4) -- (v3) -- (f7),\n        };\n      \\end{feynman}\n    \\end{tikzpicture}}\n  - \\f12 \\shrink{\n    \\begin{tikzpicture}\n      \\begin{feynman}\n        \\vertex (v1);\n        \\vertex[below right = of v1] (v2);\n        \\vertex[below right = of v2] (v3);\n        \\vertex[above left = of v1] (f1);\n        \\vertex[below left = of v1] (f2);\n        \\vertex[below left = of v2] (f3);\n        \\vertex[below left = of v3] (f4);\n        \\vertex[above right = of v1] (f5);\n        \\vertex[above right = of v2] (f6);\n        \\vertex[above right = of v3] (f7);\n        \\vertex[below right = of v3] (f8);\n        \\diagram* {\n          (f1) -- (v1) -- (f5),\n          (f2) -- (v1) -- (f5),\n          (v1) --[scalar] (v2) -- (v3) -- (f8),\n          (f3) -- (v2) -- (f6),\n          (f4) -- (v3) -- (f7),\n        };\n      \\end{feynman}\n    \\end{tikzpicture}}\n  - \\f12 \\shrink{\n    \\begin{tikzpicture}\n      \\begin{feynman}\n        \\vertex (v1);\n        \\vertex[below right = of v1] (v2);\n        \\vertex[below right = of v2] (v3);\n        \\vertex[above left = of v1] (f1);\n        \\vertex[below left = of v1] (f2);\n        \\vertex[below left = of v2] (f3);\n        \\vertex[below left = of v3] (f4);\n        \\vertex[above right = of v1] (f5);\n        \\vertex[above right = of v2] (f6);\n        \\vertex[above right = of v3] (f7);\n        \\vertex[below right = of v3] (f8);\n        \\diagram* {\n          (f1) -- (v1) -- (f5),\n          (f2) -- (v1) -- (f5),\n          (v1) -- (v2) --[scalar] (v3) -- (f8),\n          (f3) -- (v2) -- (f6),\n          (f4) -- (v3) -- (f7),\n        };\n      \\end{feynman}\n    \\end{tikzpicture}}\n  = \\p{\\alpha_{4,2}^{(3)} - \\alpha_5^{(3)}} \\H_{4,2},\n\\end{align}\nwhere\n\\begin{align}\n  \\alpha_{4,2}^{(3)}\n  \\equiv \\sum_{m,n>0} \\f{K_m K^m_n K_n}{E_m E_n},\n\\end{align}\nand\n\\begin{align}\n  \\H_{4,2}^{(3)}\n  \\equiv \\sum_{\\abs{\\set{\\mu,\\nu,\\rho,\\sigma}}=4}\n  G^{qr}_{q'r'} G^{\\mu q'\\rho s}_{\\mu'q''\\rho's'} G^{q''t}_{q'''t'}\n  \\c_{\\mu'q'''}^\\dag \\c_{\\nu r'}^\\dag \\c_{\\rho's'}^\\dag \\c_{\\sigma t'}^\\dag\n  \\c_{\\sigma t} \\c_{\\rho s} \\c_{\\nu r} \\c_{\\mu q}.\n\\end{align}\nThe net third-order four-body interaction Hamiltonian is therefore\n\\begin{align}\n  H_4^{(3)}\n  = \\p{2\\alpha_{4,1}^{(3)} - \\alpha_5^{(3)}} \\H_{4,1}^{(3)}\n  + \\p{\\alpha_{4,2}^{(3)} - \\alpha_5^{(3)}} \\H_{4,2}^{(3)}.\n  \\label{eq:H_4_3}\n\\end{align}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Low-excitation Hamiltonians, eigenstates, and spectra}\n\\label{sec:spectra}\n\nCurrent experiments with ultracold ${}^{87}$Sr on a lattice can\ncoherently address ground states and single orbital excitations of up\nto five atoms per lattice site \\cite{goban2018emergence}.  Due to the\nSU($N$) symmetry of inter-atomic interactions, manifest in the fact\nthat all coupling constants are independent of nuclear spin, a\nrestriction of the $M$-body Hamiltonians $H_M=\\sum_p H_M^{(p)}$ to the\nsubspace of experimentally addressed states takes the form\n\\begin{align}\n  H_M = \\sum_{\\abs{\\set{\\mu_j}}=M}\n  \\p{U_{M,\\g} \\n_{\\mu_1,\\g} \\n_{\\mu_2,\\g}\n    + U_{M,+} \\n_{\\mu_1,\\e} \\n_{\\mu_2,\\g}\n    + U_{M,-} \\c_{\\mu_1,\\g}^\\dag \\c_{\\mu_2,\\e}^\\dag\n    \\c_{\\mu_2,\\g} \\c_{\\mu_1,\\e}}\n  \\prod_{\\alpha=3}^M \\n_{\\mu_\\alpha,\\g},\n  \\label{eq:H_M}\n\\end{align}\nwhere $\\n_{\\mu s}\\equiv \\c_{\\mu s}^\\dag\\c_{\\mu s}$ is a number\noperator, and the coefficients $U_X$ can be determined from the\ncoupling constants $G_Y$ and prefactors $\\alpha_Z^{(p)}$ of the\neffective $M$-body Hamiltonians derived in section\n\\ref{sec:low_energy} (see Appendix \\ref{sec:U_X}).  For a lattice with\n$N\\ge M$ atoms occupying nuclear spins $\\N=\\set{\\mu_j}$ for\n$j=1,2,\\cdots,N$, the $M$-body Hamiltonian $H_M$ has a single ground\nstate $\\ket{\\N,0}$, and a singly-excited state $\\ket{\\N,+}$ which is\nfully symmetric in the orbital degrees of freedom; these states are\n\\begin{align}\n  \\ket{\\N,0}\n  \\equiv \\p{\\prod_{\\mu\\in\\N} \\c_{\\mu,\\g}^\\dag} \\ket{\\t{vacuum}},\n  &&\n  \\ket{\\N,+} \\equiv \\f1{\\sqrt{N}} \\sum_{\\mu\\in\\N}\n  \\c_{\\mu,\\e}^\\dag \\c_{\\mu,\\g} \\ket{\\N,0}.\n  \\label{eq:states_S}\n\\end{align}\nAs these states are fully symmetric in their orbital degrees of\nfreedom, they are anti-symmetric in their nuclear spin degrees of\nfreedom, forming an SU($N$) singlet.  Furthermore, the symmetric state\nis particularly interesting as its orbital degrees of freedom form an\n$N$-body entangled $W$ state, which belongs to a special class of\nmulti-partite entangled states that are robust against disposal or\nloss of particles.  This state thus constitutes an important resource\nfor many quantum information processing and quantum communication\ntasks \\cite{zang2015generating}.\n\nIn addition to the states in \\eqref{eq:states_S}, the multi-body\nHamiltonian $H_M$ in \\eqref{eq:H_M} has an $\\p{N-1}$-fold degenerate\nexcited-state eigenspace which is asymmetric in the orbital degrees of\nfreedom, spanned by the states\n\\begin{align}\n  \\ket{\\N,-,j} \\equiv \\f1{\\sqrt2}\n  \\p{\\c_{\\mu_1,\\e}^\\dag \\c_{\\mu_1,\\g} - \\c_{\\mu_j,\\e}^\\dag \\c_{\\mu_j,\\g}}\n  \\ket{\\N,0}\n  \\label{eq:states_A}\n\\end{align}\nfor $j=2,\\cdots,N$.  If $N>2$, the asymmetric states are not separable\nin their orbital and nuclear spin degrees of freedom.  An important\nfeature of the excited states in \\eqref{eq:states_S} and\n\\eqref{eq:states_A} is that they are entirely independent of $M$,\nwhich implies that the effect of multi-body interactions is simply to\nmodify the many-body atomic energy spectra without affecting the\nenergy eigenstates.  The eigenvalues $E_{NX}^{(M)}=\\bk{\\N X|H_M|\\N X}$\nof $H_M$ associated with each of the eigenstates in\n\\eqref{eq:states_S} and \\eqref{eq:states_A} are provided in table\n\\ref{tab:eigen}, both in terms of the coefficients $U_{MX}$ of $H_M$\nas expressed in \\eqref{eq:H_M} and the $M$-body eigenvalues\n$E_{MX}^{(M)}$.  Due to the SU($N$) symmetry of the multi-body\nHamiltonian $H_M$, the eigenvalues $E_{NX}^{(M)}$ depend on the number\nof nuclear spins on a lattice site, $N$, but not on the actual nuclear\nspins $\\mu\\in\\N$ which are occupied.  The total $N$-body interaction\nenergies $E_{NX}$ are given in terms of the $M$-body eigenvalues\n$E_{NX}^{(M)}$ by $E_{NX}=\\sum_ME_{NX}^{(M)}$.\n\n\\begin{table}\n  \\centering\n  \\caption{\\footnotesize Low-excitation eigenvalues of $M$-body\n    Hamiltonians $H_M$.  Many-body energy eigenstates are labeled by\n    the nuclear spins they occupy (i.e.~$\\N$ with $N\\equiv\\abs{\\N}$)\n    and whether they are in an orbital ground ($0$), singly-excited\n    symmetric ($+$), or singly-excited asymmetric ($-$) state.  The\n    corresponding $N$-body eigenvalues $E_{NX}^{(M)}$ of $H_M$ are\n    given in terms of the coefficients $U_{MX}$ as appearing in\n    \\eqref{eq:H_M} (first three rows), in addition to the $M$-body\n    eigenvalues $E_{MX}^{(M)}$ (last three rows).}\n  \\label{tab:eigen}\n  \\begin{tabular}{c|c}\n    Eigenstate\n    & $H_M$ eigenvalue ($M\\le N$) \\\\ \\hline\\hline\n    $\\ket{\\N,0}$\n    & $M! {N \\choose M} U_{M,\\g}$ \\\\ \\hline\n    $\\ket{\\N,+}$\n    & $M! {N-1 \\choose M} U_{M,\\g}\n    + \\p{M-1}! {N-1 \\choose M-1} \\p{U_{M,+} + U_{M,-}}$ \\\\ \\hline\n    $\\ket{\\N,-}$\n    & $M! {N-1 \\choose M} U_{M,\\g}\n    + \\p{M-1}! {N-1 \\choose M-1} U_{M,+}\n    - \\p{M-2}! {N-2 \\choose M-2} U_{M,-}$ \\\\ \\hline\\hline\n    $\\ket{\\N,0}$\n    & ${N \\choose M} E_{M,0}^{(M)}$ \\\\ \\hline\n    $\\ket{\\N,+}$\n    & ${N-1 \\choose M} E_{M,0}^{(M)}\n    + {N-1 \\choose M-1} E_{M,+}^{(M)}$ \\\\ \\hline\n    $\\ket{\\N,-}$\n    & ${N-1 \\choose M} E_{M,0}^{(M)}\n    + M^{-1} \\sp{{N-1 \\choose M-1} - {N-2 \\choose M-2}} E_{M,+}^{(M)}\n    + \\sp{\\p{1 - M^{-1}} {N-1 \\choose M-1}\n      + M^{-1} {N-2 \\choose M-2}} E_{M,-}^{(M)}$\n  \\end{tabular}\n\\end{table}\n\n\n\\subsection{Many-body state spectroscopy}\n\nSpectroscopic interrogation is a powerful means to probe the internal\nstructure and dynamics of a system under examination.  Consequently,\nwe consider Rabi spectroscopy of the low-lying energy eigenstates in\nmultiply-occupied lattice sites.  If we interrogate a lattice site by\na laser red-detuned by $\\Delta$ from the single-atom orbital state\nexcitation energy, we realize the Hamiltonian\n\\begin{align}\n  H_{\\t{Rabi}}\n  = \\sum_X E_X \\P_X\n  + \\sum_\\mu\\p{\\Delta T_\\mu^\\z + \\Omega_\\mu T_\\mu^\\x},\n  \\label{eq:H_rabi}\n\\end{align}\nwhere $E_X$ is an eigenvalue of the effective interaction Hamiltonian\n$H_{\\t{int}}^{\\t{eff}}$, $\\P_X$ is a projector onto the corresponding\neigenspace, and\n\\begin{align}\n  T_\\mu^\\z \\equiv \\f12 \\p{\\c_{\\mu,\\e}^\\dag \\c_{\\mu,\\e}\n    - \\c_{\\mu,\\g}^\\dag \\c_{\\mu,\\g}},\n  &&\n  T_\\mu^\\x \\equiv \\f12 \\p{\\c_{\\mu,\\e}^\\dag \\c_{\\mu,\\g}\n    + \\c_{\\mu,\\g}^\\dag \\c_{\\mu,\\e}},\n\\end{align}\nare single-atom pseudospin operators.  The Rabi frequency $\\Omega_\\mu$\nis proportional to the Clebsch-Gordan coefficient\n$\\bk{I,\\mu;1,0|I,\\mu}\\propto\\mu$ for a photon-induced\nnuclear-spin-conserving orbital state transition of an atom with\nnuclear spin $\\mu$.  We therefore define the ``bare'' Rabi frequency\n$\\Omega_0\\equiv\\Omega_\\mu/\\mu$ to explicitly factor out dependence on\nnuclear spins $\\mu$.\n\nConsider now a single lattice site in the orbital ground state\n$\\ket{\\N,0}$ with nuclear spins $\\N\\equiv\\set{\\mu_j}$ for\n$j=1,2,\\cdots,N$.  If we red-detune the interrogation laser by\n$\\delta$ from a many-body orbital state excitation energy, i.e.~set\n$\\Delta=\\Delta_{NX}-\\delta$ for $\\Delta_{NX}\\equiv E_{NX}-E_{N,0}$ and\n$X\\in\\set{+,-}$, then in the subspace of the target states\n$\\set{\\ket{\\N,0},\\ket{\\N X}}$ the Hamiltonian in \\eqref{eq:H_rabi}\nbecomes\n\\begin{align}\n  H_{\\N X} = \\delta S_{\\N X}^\\z + \\Omega_{\\N X} S_{\\N X}^\\x,\n  \\label{eq:H_NX}\n\\end{align}\nwhere\n\\begin{align}\n  S_{\\N X}^\\z &\\equiv \\f12\\p{\\op{\\N X}-\\op{\\N,0}},\n  \\label{eq:S_NX_z} \\\\\n  S_{\\N X}^\\x &\\equiv \\f12\\p{\\op{\\N X}{\\N,0}+\\op{\\N,0}{\\N X}},\n  \\label{eq:S_NX_x}\n\\end{align}\nare many-body pseudospin operators, and the Rabi frequencies\n$\\Omega_{\\N X}$ are determined by\n\\begin{align}\n  H_{\\t{Rabi}}\\ket{\\N,0}\n  = \\f12\\Omega_0\\sum_\\mu\\mu\\c_{\\mu,\\e}^\\dag\\c_{\\mu,\\g}\\ket{\\N,0}\n  = \\f12\\Omega_{\\N,+}\\ket{\\N,+} + \\f12\\Omega_{\\N,-}\\ket{\\N,-}.\n  \\label{eq:O_NX}\n\\end{align}\nWhile the symmetric excited state $\\ket{\\N,+}$ is given in\n\\eqref{eq:states_S}, at this point we have not explicitly solved for\nthe asymmetric excited state $\\ket{\\N,-}$.  The asymmetric state is\nimplicitly defined by \\eqref{eq:O_NX}, and lies somewhere in the span\nof the $N-1$ asymmetric states given in \\eqref{eq:states_A}.\nDetermining the symmetric-state Rabi frequency $\\Omega_{\\N,+}$ is\nsimply a matter of projecting the expression in \\eqref{eq:O_NX} onto\n$\\ket{\\N,+}$, which yields\n\\begin{align}\n  \\Omega_{\\N,+}\n  = \\bk{\\N,+|\\Omega_0\\sum_\\mu\\mu\\c_{\\mu,\\e}^\\dag\\c_{\\mu,\\g}|\\N,0}\n  = \\Omega_0 \\sum_{\\mu\\in\\N} \\f{\\mu}{\\sqrt{N}}\n  = \\Omega_0 \\sqrt{N} \\bar\\mu_\\N,\n  \\label{eq:O_N+}\n\\end{align}\nwhere $\\bar\\mu_\\N\\equiv\\sum_{\\mu\\in\\N}\\mu/N$ is the average nuclear\nspin $\\mu\\in\\N$.  In order to determine the asymmetric-state Rabi\nfrequency $\\Omega_{\\N,-}$, we rearrange \\eqref{eq:O_NX} to find\n\\begin{align}\n  \\Omega_{\\N,-}\\ket{\\N,-}\n  = \\Omega_0\\sum_\\mu\\mu\\c_{\\mu,\\e}^\\dag\\c_{\\mu,\\g}\\ket{\\N,0}\n  - \\Omega_{\\N,+}\\ket{\\N,+}\n  = \\Omega_0 \\sum_{\\mu\\in\\N} \\p{\\mu - \\bar\\mu_\\N}\n  \\c_{\\mu,\\e}^\\dag \\c_{\\mu,\\g} \\ket{\\N,0}.\n\\end{align}\nDenoting the standard deviation of nuclear spins $\\mu\\in\\N$ by\n$\\sigma_\\N$, normalization of $\\ket{\\N,-}$ thus determines the\nasymmetric-state Rabi frequency\n\\begin{align}\n  \\Omega_{\\N,-}\n  = \\Omega_0 \\sp{\\sum_{\\mu\\in\\N}\\p{\\mu-\\bar\\mu_\\N}^2}^{1/2}\n  = \\Omega_0 \\sqrt{N} \\sigma_\\N,\n  \\label{eq:O_N-}\n\\end{align}\nwhich in turn implies that the asymmetric excited state $\\ket{\\N,-}$\nis\n\\begin{align}\n  \\ket{\\N,-} = \\f1{\\sqrt{N}}\\sum_{\\mu\\in\\N}\n  \\p{\\f{\\mu-\\bar\\mu_\\N}{\\sigma_\\N}}\n  \\c_{\\mu,\\e}^\\dag \\c_{\\mu,\\g} \\ket{\\N,0}.\n\\end{align}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics{coefficients_table.pdf}\n  \\caption{\\footnotesize Multiplicities of the magnitudes of reduced\n    Rabi frequencies\n    $\\omega_{\\N X}\\equiv\\Omega_{\\N X}/\\Omega_0\\sqrt{N}$ in a lattice\n    with a uniform mixture of nuclear spins with $I=9/2$ and\n    single-site occupation numbers $N$ which are achievable in current\n    ${}^{87}$Sr experiments.}\n  \\label{fig:coefficients}\n\\end{figure}\n\nFigure \\ref{fig:coefficients} shows multiplicities of the magnitudes\nof reduced Rabi frequencies\n$\\omega_{\\N X}\\equiv\\Omega_{\\N X}/\\Omega_0\\sqrt{N}$ in a lattice with\na uniform mixture of nuclear spins with $I=9/2$ for single-site\noccupation numbers $N$ which are achievable in current ${}^{87}$Sr\nexperiments \\cite{goban2018emergence}.  On average, asymmetric-state\nRabi frequencies are greater in magnitude, which becomes more\npronounced for larger single-site occupation numbers.\n\n\n\\subsection{Experimental signatures and comparison}\n\n\\begin{figure}\n  \\centering\n  \\subfloat{\\includegraphics{sweep_V54_O50.pdf}}\n  \\subfloat{\\includegraphics{sweep_expt_V54.pdf}}\n  \\caption{\\footnotesize Population (in arbitrary units) of the\n    excited ${}^3P_0$ orbital state of ${}^{87}$Sr atoms in a uniform\n    mixture of nuclear spins.  Atoms are prepared in the ground state\n    of a lattice with depth $\\U=54 E_{\\t{R}}$, where\n    $E_{\\t{R}}\\approx3.5\\times2\\pi~\\t{kHz}$ is the lattice photon\n    recoil energy of the atoms, and interrogated by a laser with Rabi\n    frequency $\\Omega_I=50\\times2\\pi~\\t{Hz}$ for a time\n    $t=\\pi/\\Omega_I$.  ({\\bf Left}) Populations predicted by the\n    low-energy effective theory (with $s$-wave scattering parameters\n    retrieved from ref.~\\cite{zhang2014spectroscopic}), averaged over\n    all nuclear spin combinations of $N\\in\\set{1,\\cdots,5}$ atoms per\n    lattice site for a fixed total atom number.  ({\\bf Right})\n    Experimental measurements of ${}^3P_0$ populations retrieved from\n    ref.~\\cite{goban2018emergence}, with Lorentzian fits to each peak\n    as a visual guide.  Resonance peaks are identified by the\n    many-body orbital states which are excited at the\n    peak.}\n  \\label{fig:sweep}\n\\end{figure}\n\nWe now consider samples of ${}^{87}$Sr atoms in a uniform mixture of\nnuclear spins $\\mu\\in\\set{-I,-I+1,\\cdots,I}$ prepared in motional\nground states of a rectangular lattice with depths\n$\\U=\\p{\\U_\\x,\\U_\\y,\\U_\\z}=\\p{41,55,69} E_{\\t{R}}$, where\n$E_{\\t{R}}\\approx3.5\\times2\\pi~\\t{kHz}$ is the lattice photon recoil\nenergy of the atoms.  Such samples can be prepared in experiments\nwhich can vary the single-site occupation number $N$, and which can\ncontrol for the total number of atoms that are addressed by an\nexternal interrogation laser.  Figure \\ref{fig:sweep} shows the\npopulation of the excited ${}^3P_0$ orbital state when these atoms are\ninterrogated for a time $t=\\pi/\\Omega_I$ by a laser with Rabi\nfrequency $\\Omega_I=50\\times2\\pi~\\t{Hz}$ (i.e.~for individual atoms\nwith nuclear spin $\\mu=I$) and detuning $\\Delta$ from the single-atom\n${}^1S_0\\to{}^3P_0$ orbital excitation energy.  The ${}^3P_0$\npopulation peaks when the laser detuning $\\Delta$ is equal to the\nmany-body excitation energy $\\Delta_{NX}\\equiv E_{NX}-E_{N,0}$ for\n$X\\in\\set{+,-}$, as this is precisely when the on-resonance condition\n$\\delta=0$ is satisfied in the many-body Rabi Hamiltonian $H_{\\N X}$\nin \\eqref{eq:H_NX}.  Due to experimental uncertainties which vary with\nsingle-site occupation number $N$, the heights of experimental peaks\nin figure \\ref{fig:sweep} are not well-calibrated between different\nvalues of $N$.  Nonetheless, figure \\ref{fig:sweep} exhibits\nsignatures of larger asymmetric-state Rabi frequencies than\nsymmetric-state ones in the form of higher asymmetric-state peaks for\nfixed $N$.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics{shifts_table.pdf}\n  \\caption{\\footnotesize Multi-body excitation energies of ultracold\n    ${}^{87}$Sr atoms at various lattice depths.  The top plot in each\n    sub-figure with fixed $N,X$ shows the excitation energies\n    $\\Delta_{NX}\\equiv E_{NX}-E_{N,0}$ measured experimentally in\n    ref.~\\cite{goban2018emergence} and those predicted by the\n    low-energy effective theory at different orders in the coupling\n    constants, when applicable both with and without four-body\n    contributions.  The bottom plot in each sub-figure shows the\n    relative error\n    $\\eta_{NX}\\equiv\n    \\Delta_{NX}^{\\t{theory}}/\\Delta_{NX}^{\\t{experiment}}-1$.  Error\n    bars represent experimental error or conservatively estimated\n    theoretical uncertainties from nearest-neighbor hopping of virtual\n    states in the low-energy effective theory (see Appendix\n    \\ref{sec:error}).}\n  \\label{fig:shifts}\n\\end{figure}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics{shifts_summary.pdf}\n  \\caption{\\footnotesize Summary of the many-body excitation spectra\n    in figure \\ref{fig:shifts}, retrieved from\n    ref.~\\cite{goban2018emergence}.}\n  \\label{fig:shifts_summary}\n\\end{figure}\n\nIdentifying peaks in excitation spectra such as in figure\n\\ref{fig:sweep} constitutes a measurement of many-body excitation\nenergies, which was performed in ref.~\\cite{goban2018emergence} to\ndetect signatures of effective multi-body interactions.  Figure\n\\ref{fig:shifts} shows a comparison between\n\\begin{enumerate*}\n\\item experimental measurements of the many-body excitation energies\n  $\\Delta_{NX}$ for all $\\p{N,X}\\in\\set{3,4,5}\\times\\set{+,-}$ at\n  various mean lattice depths $\\U$, and\n\\item the corresponding values of $\\Delta_{NX}$ predicted by the\n  low-energy effective theory at different orders in the coupling\n  constants.\n\\end{enumerate*}\nA known source of error in our effective theory comes from neglecting\nthe inter-site matrix elements of all Hamiltonians.  This error is\ndiscussed in Appendix \\ref{sec:error}, and leads to theoretical\nuncertainties represented by error bars on the $\\O\\p{G^3}$ theory in\nfigure \\ref{fig:shifts}.  A summary of figure \\ref{fig:shifts} is\nprovided in figure \\ref{fig:shifts_summary}.  We note that many-body\ninteraction energy shifts are smaller for asymmetric ($-$) states than\nsymmetric ($+$) ones due to the competition between contributions of\nopposite sign in the asymmetric case (see rows 2 and 3 of table\n\\ref{tab:eigen}, where as a consequence of positive scattering lengths\nin the case of $^{87}$Sr, all $U_{MX}$ for fixed $M$ have the same\nsign).  This competition is a many-body analogue of the two-body case\nwith a competition between direct and exchange terms in the\ninteraction energies of singly-excited states.\n\nThe results in figures \\ref{fig:shifts} and \\ref{fig:shifts_summary}\nhighlight a few important points about ultracold, high-density\n${}^{87}$Sr experiments and our low-energy effective theory.  First,\nthese experiments exhibit clear signatures of multi-body interactions,\nas evidenced by a stark disagreement between the observed many-body\nexcitation energies $\\Delta_{NX}$ and those that are predicted by the\ntwo-body $\\O\\p{G}$ theory.  Multi-body interactions are thus crucial\nfor understanding these high-density experiments in the context of a\nsingle-band Hubbard model, which naturally arises in the\nzero-temperature limit when all atoms occupy their motional ground\nstate.  Second, the inter-atomic interactions in these experiments are\nstrong enough to require going beyond leading order for the\ndescription of multi-body interactions in the low-energy effective\ntheory.  The formally small quantities organizing our perturbation\ntheory are two-body ground-state interaction energies (proportional to\nthe couplings $G_X$) divided by the spectral gap of the single-atom\nHamiltonian $H_0$.  These reduced (dimensionless) interaction energies\nvary from $\\sim0.05-0.15$ in the parameter regimes of the ${}^{87}$Sr\nexperiments considered here (see Appendix \\ref{sec:pert_params}).  As\nexperiments begin to operate at higher atom densities with amplified\ninteraction effects, reliably predicting interaction energies may\nrequire going to yet higher orders in perturbation theory.  Due to a\ncombinatorial explosion of the number of diagrams which appear at\nincreasing orders in the effective theory, however, we need more\nsystematic methods to compute effective multi-body Hamiltonians at\nfourth order.  In any case, we are agnostic as to whether such a\ncalculation would provide better agreement between experiment and\ntheory without first performing a detailed analysis of systematic\nerrors.\n\n\n\\subsection{Orbital-state dynamics of a nuclear spin mixture}\n\nIn addition to spectral measurements of many-body interaction\nenergies, we consider the dynamics of multiply-occupied lattice sites\nduring spectroscopic interrogation.  While these dynamics do not\nprovide information about the nature or origin of effective multi-body\ninteractions, they provide tools and intuition for addressing the\nlow-lying orbital excitations which are readily accessible in an\nexperimental setting.  If we initialize all atoms in the $N$-body\nground state with an incoherent mixture of all nuclear spins, then we\nprepare the mixed state $\\rho_{N,0}=\\P_{N,0}/\\tr\\P_{N,0}$, where\n\\begin{align}\n  \\P_{NX} \\equiv \\sum_{\\abs{\\N}=N}\\op{\\N X}\n  \\label{eq:P_NX}\n\\end{align}\nis a projector onto the space of the $N$-body orbital states\n$\\ket{\\N X}$.  Interrogating the atoms for a time $t$ by a laser\nresonant with the excitation energy $\\Delta_{N\\pm}$ then gives us the\nstate\n\\begin{align}\n  \\rho_N^{(\\pm)}\\p{t} = \\f1{\\tr\\P_{N,0}}\n  \\sum_{\\abs{\\N}=N} \\exp\\p{-it\\Omega_{\\N\\pm}S_{\\N\\pm}^\\x}\n  \\op{\\N,0} \\exp\\p{it\\Omega_{\\N\\pm}S_{\\N\\pm}^\\x},\n\\end{align}\nwhere the Rabi frequencies $\\Omega_{\\N,+},\\Omega_{\\N,-}$ and\npseudo-spin operators $S_{\\N\\pm}^\\x$ are respectively given in\n\\eqref{eq:O_N+}, \\eqref{eq:O_N-}, and \\eqref{eq:S_NX_x}.  Denoting the\neigenstates of $S_{\\N\\pm}^\\x$ by\n\\begin{align}\n  \\ket{\\N,\\S_\\pm} \\equiv \\f1{\\sqrt2} \\p{\\ket{\\N,0} + \\ket{\\N\\pm}},\n  &&\n  \\ket{\\N,\\A_\\pm} \\equiv \\f1{\\sqrt2} \\p{\\ket{\\N,0} - \\ket{\\N\\pm}},\n\\end{align}\nand defining the identity operator projected to the relevant subspace,\n\\begin{align}\n  \\1_{\\N\\pm} \\equiv \\op{\\N,0} + \\op{\\N\\pm}\n  = \\op{\\N,\\S_\\pm} + \\op{\\N,\\A_\\pm},\n\\end{align}\nwe can write the state $\\rho_N^{(\\pm)}\\p{t}$ and excited-state\nprojectors $\\P_{N\\pm}$ in the form\n\\begin{align}\n  \\rho_N^{(\\pm)}\\p{t} = \\f1{\\tr\\P_{N,0}} \\sum_{\\abs{\\N}=N} \\f12\n  \\sp{\\1_{\\N\\pm} + e^{i2t\\Omega_{\\N\\pm}}\\op{\\N,\\S_\\pm}{\\N,\\A_\\pm}\n    + e^{-i2t\\Omega_{\\N\\pm}}\\op{\\N,\\A_\\pm}{\\N,\\S_\\pm}},\n  \\label{eq:rho_N_pm_t}\n\\end{align}\nand\n\\begin{align}\n  \\P_{N\\pm} = \\sum_{\\abs{\\N}=N} \\f12\n  \\sp{\\1_{\\N\\pm}-\\op{\\N,\\S_\\pm}{\\N,\\A_\\pm}-\\op{\\N,\\A_\\pm}{\\N,\\S_\\pm}},\n\\end{align}\nfrom which it follows that the net excited-state population at time\n$t$ is\n\\begin{align}\n  \\bk{\\P_{N\\pm}\\p{t}}\n  \\equiv \\tr\\sp{\\rho_N^{(\\pm)}\\p{t}\\P_{N\\pm}}\n  = \\f12 - \\f12 \\bk{\\cos\\p{2t\\Omega_{\\N\\pm}}}_{\\abs{\\N}=N},\n  \\label{eq:P_N_pm_t}\n\\end{align}\nwhere $\\bk{X}_{\\abs{\\N}=N}\\equiv\\sum_{\\abs{\\N}=N}X/\\tr\\P_{N,0}$ is an\naverage of $X$ over all choices of $N$ distinct nuclear spins.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics{time_table.pdf}\n  \\caption{\\footnotesize Net population of the $N$-body orbital\n    excited states $\\set{\\ket{\\N\\pm}}$ after interrogation of an\n    initial mixed state $\\rho_{N,0}=\\P_{N,0}/\\tr\\P_{N,0}$ for a\n    reduced time $\\tau_N\\equiv t\\Omega_0/\\sqrt{N}$ (i.e.~with real\n    time $t$) by a laser with bare Rabi frequency $\\Omega_0$ which is\n    resonant with the $N$-body excitation energy $\\Delta_{NX}$.  Here\n    $\\P_{NX}$, defined in \\eqref{eq:P_NX}, is a projector onto the\n    space of the $N$-body orbital states $\\ket{\\N X}$.}\n  \\label{fig:time}\n\\end{figure}\n\nFigure \\ref{fig:time} shows the excited-state population\n$\\bk{\\P_{N\\pm}\\p{t}}$ for several occupation numbers $N$.  With the\nexception of $N=2$, the asymmetric-state populations generally have an\ninitial short period of growth before falling back to\n$\\bk{\\P_{N,-}}\\approx1/2$.  This behavior can be understood by the\nfact that for fixed $N>2$, any pair of Rabi frequencies\n$\\Omega_{\\N_1,-},\\Omega_{\\N_2,-}$ with\n$\\Omega_{\\N_1,-}\\ne\\Omega_{\\N_2,-}$ are mutually incommensurate, which\nimplies that at times $t$ with\n$\\min_{\\abs{\\N}=N}\\set{2t\\Omega_{\\N,-}}\\gtrsim1$ the averaging in\n\\eqref{eq:P_N_pm_t} effectively becomes a pseudo-random sampling\naverage of $\\cos x$ over values of $x$, so\n$\\bk{\\cos\\p{2t\\Omega_{\\N,-}}}_{\\abs{\\N}=N}\\approx0$.  When $N=2$, the\nasymmetric-state Rabi frequencies essentially take on the same values\nas the symmetric-state ones (see figure \\ref{fig:coefficients}); the\nbehavior of asymmetric-state population dynamics for $N=2$ can\ntherefore be understood by the following discussion of symmetric-state\npopulation dynamics.\n\nTo understand the periodic collapse and revival of symmetric-state\npopulations in figure \\ref{fig:time}, we observe from \\eqref{eq:O_N+}\nthat the symmetric-state phases in \\eqref{eq:rho_N_pm_t} and\n\\eqref{eq:P_N_pm_t} take the form\n\\begin{align}\n  2t\\Omega_{\\N,+} = \\tau_N \\sum_{\\mu\\in\\N} 2\\mu\n  &&\n  \\t{with}\n  &&\n  \\tau_N \\equiv \\f{t\\Omega_0}{\\sqrt{N}},\n  \\label{eq:2tO_N+}\n\\end{align}\nwhere for fermionic atoms with half-integer nuclear spin, $2\\mu$ is\nalways an odd integer, which implies that the sum in \\eqref{eq:2tO_N+}\nis an integer with the same parity (i.e.~even/odd) as the occupation\nnumber $N$ (i.e.~the number of elements in $\\N$).  At reduced times\n$\\tau_N=n\\pi$ with integer $n$, therefore, if the occupation number\n$N$ is even then all phases $2t\\Omega_{\\N,+}$ are integer multiples of\n$2\\pi$, which leads to a collapse of the excited-state populations as\n$\\left.\\rho_N^{(\\pm)}\\p{t}\\right|_{\\tau_N=n\\pi} = \\rho_N^{(\\pm)}\\p{0}\n= \\rho_{N,0}$.  If the occupation $N$ is odd, meanwhile, then the\nphases $2t\\Omega_{\\N,+}$ are all odd (even) integer multiples of $\\pi$\nfor odd (even) $n$.  This alignment of phases implies a complete\npopulation transfer to the excited state\n$\\rho_{N,-}\\equiv\\P_{N,-}/\\tr\\P_{N,-}$ for odd $n$, and a collapse\nback to the orbital ground state $\\rho_{N,0}$ for even $n$, precisely\nas observed in figure \\ref{fig:time}.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Summary and outlook}\n\\label{sec:summary}\n\nCurrent 3-D optical lattice experiments with fermionic AEAs are\ncapable of operating in the low-temperature, high-density,\nstrongly-interacting limit where inter-atomic interactions set the\ndominant energy scale governing system dynamics.  For AEAs with total\nnuclear spin $I$ and $N=2I+1$ nuclear spin states, these interactions\nexhibit an exotic SU($N$) symmetry which is of great interest for\nnear-term quantum simulations of SU($N$) spin models and lattice field\ntheories.  Working in the deep-lattice limit and the experimental\nregime of at most one atom occupying each nuclear spin state on any\nlattice site, we have derived a low-energy effective theory of these\natoms.  Our theory exhibits emergent multi-body interactions that\ninherit the SU($N$) symmetry of the bare two-body interactions.\nConsidering a restriction of our theory to the subspace of at most one\norbital excitation per lattice site, we found that the SU($N$)\nsymmetry of all $M$-body Hamiltonians allowed us to express them in a\nsimple form, and to fully characterize their eigenstates and spectra.\nCapitalizing on the extreme precision of state-of-the-art clock\nspectroscopy, we have tested spectral predictions of our theory\nagainst direct experimental measurements of the many-body ${}^{87}$Sr\nexcitation spectrum.  This comparison shows good agreement between\ntheory and experiment, clearly demonstrating the need to consider\nmulti-body effects for understanding the low-energy physics of high\ndensity AEA samples on a 3-D lattice.  Finally, we analyzed the\nmany-body orbital-state dynamics of multiply-occupied lattice sites\nprepared in a nuclear spin mixture and interrogated via Rabi\nspectroscopy.  This analysis is useful for future experimental probes\nof many-body state structures, as well as for the preparation of\nlong-lived states with multi-partite entanglement (i.e.~$\\ket{\\N\\pm}$)\nwhich may be used as a resource to perform quantum information\nprocessing tasks.\n\nDespite the nominal success of our low-energy effective theory in\nreproducing experimental observations, there remains room for\nimprovement in the form of controlled, systematic treatment of\nhigher-order and tunneling processes.  Nonetheless, our work makes a\nmajor step towards the experimental investigation of multi-body\nSU($N$) physics, providing the necessary framework for future studies\ngoing beyond the deep-lattice limit to realize multi-body\nsuper-exchange dynamics and orbital SU($N$) quantum magnetism with\nAEAs.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section*{Acknowledgements}\n\nWe acknowledge helpful discussions with R.~B.~Hutson, G.~E.~Marti,\nS.~L.~Campbell, J.~Ye, P.~Julienne, J.~P.~D'Incao, C.~Kennedy, and\nL.~Radzihovsky; and in particular close correspondence and technical\ncontributions from A.~Goban.  This work is supported by the Air Force\nOffice of Scientific Research (AFOSR) grant FA9550-18-1-0319; the\nAFOSR Multidisciplinary University Research Initiative (MURI) grant;\nthe Defense Advanced Research Projects Agency (DARPA) and Army\nResearch Office (ARO) grant W911NF-16-1-0576; the National Science\nFoundation (NSF) grant PHY-1820885; JILA-NSF grant PFC-173400; and the\nNational Institute of Standards and Technology (NIST).\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section*{Appendices}\n\\appendix\n\\setcounter{figure}{0}\n\\renewcommand\\thefigure{\\thesection.\\arabic{figure}}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Derivation of the effective Hamiltonian expansion}\n\\label{sec:eff_derivation}\n\nSuppose we have a Hamiltonian $H_0$ on a Hilbert space\n$\\H=\\G_0\\oplus\\E_0$ for a zero-energy manifold $\\G_0$ decoupled from a\npositive-energy manifold $\\E_0$, and that we perturb $H_0$ by an\noperator $V$ which weakly couples $\\G_0$ and $\\E_0$.  For all\n$\\ket{\\psi_\\g}\\in\\G_0$ and $\\ket{\\phi_\\e},\\ket{\\chi_\\e}\\in\\E_0$, we\nhave $\\bk{\\psi_\\g|H_0|\\psi_\\g}=0$, $\\bk{\\phi_\\e|H_0|\\psi_\\g}=0$, and\n$\\abs{\\bk{\\phi_\\e|V|\\psi_\\g}}\\ll\\bk{\\chi_\\e|H_0|\\chi_\\e}$.  The net\nHamiltonian $H=H_0+V$ will naturally admit a decomposition of the\nHilbert space as $\\H=\\G\\oplus\\E$ for a subspace $\\G$ which is spanned\nby the low-energy eigenstates of $H$ and has the same dimension as\n$\\G_0$, i.e.~$\\abs{\\G}=\\abs{\\G_0}$.\n\nWe can perform a canonical transformation between $\\G$ and $\\G_0$\nwhich yields an {\\it effective Hamiltonian} $H_{\\t{eff}}$ on $\\G_0$\nthat reproduces the spectrum of $H$ on $\\G$\n\\cite{bravyi2011schrieffer}.  Given an eigenbasis\n$\\set{\\ket{\\alpha_0}}$ for $H_0$ on $\\G_0$ and $\\set{\\ket\\alpha}$ for\n$H$ on $\\G$, this transformation is implemented by a unitary $U$ for\nwhich $\\ket{\\alpha_0}=U\\ket\\alpha$ and $U\\to\\1$ as $\\norm{V}\\to0$.\nThe effective Hamiltonian is then simply\n\\begin{align}\n  H_{\\t{eff}} = U H U^\\dag.\n  \\label{eq:H_eff}\n\\end{align}\nThe prescription in \\eqref{eq:H_eff} for constructing an effective\nHamiltonian is commonly known as a Schieffer-Wolff transformation\n\\cite{schrieffer1966relation}.  Unitaries $U$ which follow this\nprescription are not unique, and different choices of $U$ amount to\ndifferent realizations of the Schieffer-Wolff transformation.  In\nref.~\\cite{bravyi2011schrieffer}, the authors construct the unique\noperator $S$ which generates a {\\it direct} or {\\it minimal} rotation\n$U_{\\t{min}}=e^S$ between $\\G$ and $\\G_0$, and use this construction\nto expand \\eqref{eq:H_eff} as a perturbative series in $V$.  The\nrotation $U_{\\t{min}}$ is minimal in the sense that it minimizes the\ndistance of candiate unitaries $U$ from the identity $\\1$ with respect\nto the Euclidian operator norm\\footnote{The Euclidean operator norm is\n  also known as the $L_{2,2}$, Hilbert-Schmidt, or Frobenius norm.}\n$\\norm{X}_{\\t{E}}\\equiv\\sqrt{\\tr\\p{X^\\dag X}}$.  This rotation is\ndetermined uniquely by enforcing\n\\begin{enumerate*}\n\\item that the generator $S$ is strictly block-off-diagonal with\n  respect to $\\G_0$ and $\\E_0$,\n\\item that the norm $\\norm{S}_{\\t{E}}<\\pi/2$, and\n\\item that the block-off-diagonal parts of \\eqref{eq:H_eff} are zero.\n\\end{enumerate*}\n\nTo summarize the solution in ref.~\\cite{bravyi2011schrieffer}, the\neffective Hamiltonian $H_{\\t{eff}}$ induced by a direct rotation can\nbe expanded as\n\\begin{align}\n  H_{\\t{eff}} = \\sum_{p\\ge0} H_{\\t{eff}}^{(p)},\n  \\label{eq:H_eff_expansion}\n\\end{align}\nwhere $H_{\\t{eff}}^{(p)}$ is order $p$ in $V$.  Letting $\\P_0$ denote\nthe projector onto $\\G_0$, $\\Q_0\\equiv\\1-\\P_0$ denote the projector\nonto $\\E_0$, and $X$ denote any operator on $\\H$, we define the\nsuperoperators\n\\begin{align}\n  \\D X \\equiv \\P_0 X \\P_0 + \\Q_0 X \\Q_0,\n  &&\n  \\O X \\equiv \\P_0 X \\Q_0 + \\Q_0 X \\P_0,\n\\end{align}\nwhich select out the diagonal ($\\D$) and off-diagonal ($\\O$) parts of\n$X$ with respect to $\\G_0$ and $\\E_0$, and\n\\begin{align}\n  \\L X \\equiv \\sum_{\\alpha,\\beta}\n  \\f{\\op\\alpha \\O X \\op\\beta}{E_\\alpha - E_\\beta}\n  &&\n  \\t{where}\n  &&\n  H_0 = \\sum_\\alpha E_\\alpha \\op\\alpha.\n\\end{align}\nThe first few terms of the expansion in \\eqref{eq:H_eff_expansion} are\nthen, as derived in ref.~\\cite{bravyi2011schrieffer},\n\\begin{align}\n  H_{\\t{eff}}^{(0)} = \\P_0 H_0 \\P_0,\n  &&\n  H_{\\t{eff}}^{(1)} = \\P_0 V \\P_0,\n  \\label{eq:H_eff_0_1}\n\\end{align}\n\\begin{align}\n  H_{\\t{eff}}^{(2)} = - \\f12 \\P_0 \\sp{\\O V,\\L V} \\P_0,\n  &&\n  H_{\\t{eff}}^{(3)} = \\f12 \\P_0 \\sp{\\O V, \\L \\sp{\\D V, \\L V}} \\P_0.\n\\end{align}\nExploiting the fact that in our case $\\bk{\\psi|H_0|\\psi}=0$ for all\n$\\ket\\psi\\in\\G_0$, we let $\\B_0\\p{\\E_0}$ denote an eigenbasis of $H_0$\nfor $\\E_0$ and define the operator\n\\begin{align}\n  \\I \\equiv \\sum_{\\ket\\alpha\\in\\B_0\\p{\\E_0}}\\f{\\op\\alpha}{E_\\alpha},\n\\end{align}\nwhich sums over projections onto excited states with corresponding\nenergetic suppression factors.  We then expand\n\\begin{align}\n  \\L X = \\O\\p{\\L X} = \\Q_0 \\L X \\P_0 + \\P_0 \\L X \\Q_0\n  = \\I X \\P_0 - \\P_0 X \\I,\n\\end{align}\nwhich simplifies the expression for $H_{\\t{eff}}^{(2)}$ as\n\\begin{align}\n  H_{\\t{eff}}^{(2)}\n  = - \\f12 \\P_0 \\p{\\sp{\\O V, \\I V \\P_0}\n    - \\sp{\\O V, \\P_0 V \\I}} \\P_0\n  = - \\P_0 V \\I V \\P_0.\n  \\label{eq:H_eff_2}\n\\end{align}\nWorking toward a similar expansion for $H_{\\t{eff}}^{(3)}$, we compute\n\\begin{align}\n  \\sp{\\D V, \\L V}\n  = \\sp{\\D V, \\I V \\P_0} - \\sp{\\D V, \\P_0 V \\I}\n  = \\O\\p{V \\I V} - \\I V \\P_0 V \\P_0 - \\P_0 V \\P_0 V \\I,\n\\end{align}\nand in turn\n\\begin{align}\n  H_{\\t{eff}}^{(3)}\n  &= \\f12 \\P_0 \\p{\\sp{\\O V, \\I \\sp{\\D V, \\L V} \\P_0}\n    - \\sp{\\O V, \\P_0 \\sp{\\D V, \\L V} \\I}} \\P_0 \\\\\n  &= \\f12 \\P_0 \\p{V \\I \\sp{\\D V, \\L V}\n    + \\sp{\\D V, \\L V} \\I V} \\P_0 \\\\\n  &= \\P_0 V \\I V \\I V \\P_0\n  - \\f12 \\P_0 V \\I^2 V \\P_0 V \\P_0\n  - \\f12 \\P_0 V \\P_0 V \\I^2 V \\P_0 \\\\\n  &= \\P_0 V \\I V \\I V \\P_0\n  - \\f12 \\sp{\\P_0 V \\P_0, \\P_0 V \\I^2 V \\P_0}_+,\n  \\label{eq:H_eff_3}\n\\end{align}\nwhere $\\sp{X,Y}_+\\equiv XY+YX$.  The expressions in\n\\eqref{eq:H_eff_0_1}, \\eqref{eq:H_eff_2}, and \\eqref{eq:H_eff_3}\ncomplete the derivation for our expansion of the effective interaction\nHamiltonian $H_{\\t{int}}^{\\t{eff}}$ in \\eqref{eq:H_int_eff} through\nthird order.  In the case of ultracold atoms on a lattice, the\nmotional ground-state subspace $\\G_0$ actually contains many internal\natomic states with different energies.  Nonetheless, the total Hilbert\nspace is completely separable into uncoupled subspaces associated with\neach symmetrized many-body internal atomic state.  One can therefore\ndiagonalize the interaction Hamiltonian with respect to these internal\nstates and derive an effective theory within each of the corresponding\nsubspaces, in each case setting the appropriate ground-state energy to\nzero.  This procedure is equivalent to simultaneously calculating the\neffective Hamiltonian $H_{\\t{int}}^{\\t{eff}}$ for all internal states\nvia the prescriptions we have provided, but letting $E_\\alpha$ denote\nonly the motional excitation energy of states\n$\\ket{\\alpha_0}\\in\\B_0\\p{\\E_0}$.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Diagram counting and symmetry factors}\n\\label{sec:diagrams}\n\nThe fact that we include factors of $1/2$ from the bare two-body\ninteraction Hamiltonian $H_{\\t{int}}$ in the definition of diagrams\nimplies that $p$-vertex diagrams acquire a factor of $1/2^p$.  In\npractice, however, these factors are exactly cancelled out by\ncorresponding symmetry factors in all $M$-body diagrams with $M>2$.\nAs an illustrative example, consider the second-order effective\nHamiltonian $H_{\\t{int}}^{(2)}$ in \\eqref{eq:H_int_1_2}, which\nexpanded in full reads\n\\begin{align}\n  H_{\\t{int}}^{(2)} = -\\sum_{m+n>0} \\P_0\n  \\p{\\f12 K_{mn} G^{st}_{s't'}\n    \\c_{\\rho s'}^\\dag \\c_{\\sigma t'}^\\dag \\c_{n\\sigma t} \\c_{m\\rho s}}\n  \\f1{E_{mn}}\n  \\p{\\f12 K_{mn} G^{qr}_{q'r'}\n    \\c_{m\\mu q'}^\\dag \\c_{n\\nu r'}^\\dag \\c_{\\nu r} \\c_{\\mu q}} \\P_0.\n  \\label{eq:H_int_2_full}\n\\end{align}\nThe three-body terms in this Hamiltonian have\n$\\abs{\\set{\\mu,\\nu,\\rho,\\sigma}}=3$ and only one virtually excited\natom.  The non-vanishing three-body terms must therefore either have\n$\\rho\\in\\set{\\mu,\\nu}$ and contain a factor of the form\n$\\c_X^\\dag \\c_{\\sigma t'}^\\dag \\c_{\\sigma t} \\c_Y$, or have\n$\\sigma\\in\\set{\\mu,\\nu}$ with a factor of the form\n$\\c_{\\rho s'}^\\dag \\c_X^\\dag \\c_Y \\c_{\\rho s}$, where the labels $X,Y$\nboth address whichever nuclear spin (i.e.~$\\mu$ or $\\nu$) was excited\nin the corresponding term.  Diagrammatically, we have terms of the\nform\n\\begin{align}\n  \\begin{tikzpicture}\n    \\begin{feynman}\n      \\vertex (v1);\n      \\vertex[above left = of v1] (f1) {$\\mu q$};\n      \\vertex[below left = of v1] (f2) {$\\nu r$};\n      \\vertex[right = of v1] (vm);\n      \\vertex[right = of vm] (v2);\n      \\vertex[above = of vm] (f3) {$Z$};\n      \\vertex[below = of vm] (f4) {$\\sigma t$};\n      \\vertex[below right = of v2] (f5) {$\\sigma t'$};\n      \\vertex[above right = of v2] (f6) {$X$};\n      \\diagram* {\n        (f1) -- (v1) -- (f3),\n        (f2) -- (v1) --  [scalar, edge label=$Y$] (v2),\n        (f4) -- (v2) -- (f5),\n        (v2) -- (f6), };\n    \\end{feynman}\n  \\end{tikzpicture}\n  &&\n  \\t{and}\n  &&\n  \\begin{tikzpicture}\n    \\begin{feynman}\n      \\vertex (v1);\n      \\vertex[above left = of v1] (f1) {$\\mu q$};\n      \\vertex[below left = of v1] (f2) {$\\nu r$};\n      \\vertex[right = of v1] (vm1);\n      \\vertex[right = of vm1] (vm2);\n      \\vertex[right = of vm2] (v2);\n      \\vertex[above = of vm1] (f3) {$Z$};\n      \\vertex[above = of vm2] (f4) {$\\rho s$};\n      \\vertex[above right = of v2] (f5) {$\\rho s'$};\n      \\vertex[below right = of v2] (f6) {$X$};\n      \\diagram* {\n        (f1) -- (v1) -- (f3),\n        (f2) -- (v1) --  [scalar, edge label=$Y$] (v2),\n        (f4) -- (v2) -- (f5),\n        (v2) -- (f6), };\n    \\end{feynman}\n  \\end{tikzpicture}.\n  \\label{eq:rho_sigma}\n\\end{align}\nObserving that\n$\\c_{\\rho s'}^\\dag \\c_X^\\dag \\c_Y \\c_{\\rho s} = \\c_X^\\dag \\c_{\\rho\n  s'}^\\dag \\c_{\\rho s} \\c_Y$, however, it is clear that both of the\nterms represented in \\eqref{eq:rho_sigma} are equal up to the\nre-indexing $\\p{\\sigma,t,t'}\\leftrightarrow\\p{\\rho,s,s'}$.  There is\ntherefore a symmetry factor of $2$ associated with the second vertex\nof the diagrams in \\eqref{eq:rho_sigma}, which cancels out with the\nexplicit factor of $1/2$ at that vertex, i.e.~the first factor of\n$1/2$ in \\eqref{eq:H_int_2_full}.  A symmetry factor of essentially\nidentical origin appears at every vertex with an ``incoming'' virtual\nstate, as in e.g.~the second and third vertices of\n\\begin{align}\n  \\shrink{\n    \\begin{tikzpicture}\n      \\begin{feynman}\n        \\vertex (v1);\n        \\vertex[below right = of v1] (v2);\n        \\vertex[above right = of v2] (v3);\n        \\vertex[above left = of v1] (f1);\n        \\vertex[left = of v1] (f2);\n        \\vertex[below left = of v2] (f3);\n        \\vertex[above right = of v3] (f4);\n        \\vertex[right = of v3] (f5);\n        \\vertex[below right = of v2] (f6);\n        \\diagram* {\n          (f1) -- (v1) --[scalar] (v3) -- (f4),\n          (f2) -- (v1) --[scalar] (v2) --[scalar] (v3) -- (f5),\n          (f3) -- (v2) -- (f6), };\n      \\end{feynman}\n    \\end{tikzpicture}}\n  &&\n  \\t{and}\n  &&\n  \\shrink{\n    \\begin{tikzpicture}\n      \\begin{feynman}\n        \\vertex (v1);\n        \\vertex[below right = of v1] (v2);\n        \\vertex[below right = of v2] (v3);\n        \\vertex[above left = of v1] (f1);\n        \\vertex[below left = of v1] (f2);\n        \\vertex[below left = of v2] (f3);\n        \\vertex[below left = of v3] (f4);\n        \\vertex[above right = of v1] (f5);\n        \\vertex[above right = of v2] (f6);\n        \\vertex[above right = of v3] (f7);\n        \\vertex[below right = of v3] (f8);\n        \\diagram* {\n          (f1) -- (v1) -- (f5),\n          (f2) -- (v1) -- (f5),\n          (v1) --[scalar] (v2) -- (v3) -- (f8),\n          (f3) -- (v2) -- (f6),\n          (f4) -- (v3) -- (f7),\n        };\n      \\end{feynman}\n    \\end{tikzpicture}},\n  \\label{eq:diagram_example_1}\n\\end{align}\nor the last vertex of\n\\begin{align}\n  \\shrink{\n    \\begin{tikzpicture}\n      \\begin{feynman}\n        \\vertex (v1);\n        \\vertex[below right = 2.5em of v1] (v3);\n        \\vertex[below left = 1.7em of v3] (v2);\n        \\vertex[above left = of v1] (f1);\n        \\vertex[left = of v1] (f2);\n        \\vertex[left = of v2] (f3);\n        \\vertex[below left = of v2] (f4);\n        \\vertex[above right = of v1] (f5);\n        \\vertex[above right = of v3] (f6);\n        \\vertex[below right = of v3] (f7);\n        \\vertex[below right = of v2] (f8);\n        \\diagram* {\n          (f1) -- (v1) -- (f5),\n          (f2) -- (v1) --[scalar] (v3) -- (f6),\n          (f3) -- (v2) -- (v3) -- (f7),\n          (f4) -- (v2) -- (f8), };\n      \\end{feynman}\n    \\end{tikzpicture}}.\n  \\label{eq:diagram_example_2}\n\\end{align}\nWe can thus account for cancellations of $1/2$ at all vertices except\nthose which address two ``initial'' ground-state atoms, as in the\nfirst vertex of the diagrams in \\eqref{eq:rho_sigma} and\n\\eqref{eq:diagram_example_1}, or the first two vertices of the diagram\nin \\eqref{eq:diagram_example_2}.  For such vertices, there are two\npossibilities: either\n\\begin{enumerate}\n\\item both edges leaving the vertex in question (i.e.~leaving to the\n  right) terminate at different vertices, as in the examples above, or\n  \\label{enum:different_vertices}\n\\item both edges leaving the vertex in question terminate at the same\n  vertex, as in for example the first vertex of\n  \\label{enum:same_vertex}\n  \\begin{align}\n    \\shrink{\n      \\begin{tikzpicture}\n        \\begin{feynman}\n          \\vertex (v1);\n          \\vertex[right = of v1] (v2);\n          \\vertex[below right = of v2] (v3);\n          \\vertex[above left = of v1] (f1);\n          \\vertex[below left = of v1] (f2);\n          \\vertex[below left = of v3] (f3);\n          \\vertex[above right = of v2] (f4);\n          \\vertex[above right = of v3] (f5);\n          \\vertex[below right = of v3] (f6);\n          \\diagram* {\n            (f1) -- (v1) --[half left, scalar] (v2) -- (f4),\n            (f2) -- (v1) --[half right, scalar] (v2)\n            --[scalar] (v3) -- (f5),\n            (f3) -- (v3) -- (f6), };\n        \\end{feynman}\n      \\end{tikzpicture}}.\n    \\label{eq:diagram_example_3}\n  \\end{align}\n\\end{enumerate}\nIn the former case, \\ref{enum:different_vertices}, the vertex in\nquestion has an associated symmetry factor of 2 to account for the\npossibility of a nuclear spin exchange at that vertex.  Considering\nagain our example of the second-order effective Hamiltonian\n$H_{\\t{int}}^{(2)}$ in \\eqref{eq:H_int_2_full}, the non-vanishing\nthree-body terms must either have $m=0$ and contain the factor\n$\\c_{\\mu q'}^\\dag \\c_{n\\nu r'}^\\dag \\c_{\\nu r} \\c_{\\mu q}$, or have\n$n=0$ with the factor\n$\\c_{m\\mu q'}^\\dag \\c_{\\nu r'}^\\dag \\c_{\\nu r} \\c_{\\mu q}$, which\ndiagrammatically translates to\n\\begin{align}\n  \\begin{tikzpicture}\n    \\begin{feynman}\n      \\vertex (v1);\n      \\vertex[above left = of v1] (f1) {$\\mu q$};\n      \\vertex[below left = of v1] (f2) {$\\nu r$};\n      \\vertex[right = of v1] (vm);\n      \\vertex[right = of vm] (v2);\n      \\vertex[above = of vm] (f3) {$\\mu q'$};\n      \\vertex[below = of vm] (f4) {$\\sigma t$};\n      \\vertex[below right = of v2] (f5) {$\\sigma t'$};\n      \\vertex[above right = of v2] (f6) {$\\nu r''$};\n      \\diagram* {\n        (f1) -- (v1) -- (f3),\n        (f2) -- (v1) --  [scalar, edge label=$n\\nu r'$] (v2),\n        (f4) -- (v2) -- (f5),\n        (v2) -- (f6), };\n    \\end{feynman}\n  \\end{tikzpicture}\n  &&\n  \\t{or}\n  &&\n  \\begin{tikzpicture}\n    \\begin{feynman}\n      \\vertex (v1);\n      \\vertex[above left = of v1] (f1) {$\\mu q$};\n      \\vertex[below left = of v1] (f2) {$\\nu r$};\n      \\vertex[right = of v1] (vm);\n      \\vertex[right = of vm] (v2);\n      \\vertex[above = of vm] (f3) {$\\nu r'$};\n      \\vertex[below = of vm] (f4) {$\\sigma t$};\n      \\vertex[below right = of v2] (f5) {$\\sigma t'$};\n      \\vertex[above right = of v2] (f6) {$\\mu q''$};\n      \\diagram* {\n        (f1) -- (v1) -- (f3),\n        (f2) -- (v1) --  [scalar, edge label=$m\\mu q'$] (v2),\n        (f4) -- (v2) -- (f5),\n        (v2) -- (f6), };\n    \\end{feynman}\n  \\end{tikzpicture}.\n  \\label{eq:mu_nu}\n\\end{align}\nThese terms are equal up to the re-indexing\n$\\p{\\nu,r,r',r'',n}\\leftrightarrow\\p{\\mu,q,q',q'',m}$, which implies\nthat there is a symmetry factor of $2$ associated with the first\nvertex of the diagrams in \\eqref{eq:mu_nu}.  A symmetry factor of\nidentical origin is associated with the first vertex of the diagrams\nin \\eqref{eq:diagram_example_1}, and the first two vertices of the\ndiagram in \\eqref{eq:diagram_example_2}.\n\nThe final case we must consider is \\ref{enum:same_vertex}, which\noccurs in the first vertex of \\eqref{eq:diagram_example_3}.  In this\ncase, the symmetry factor of $2$ which appears in case\n\\ref{enum:different_vertices} to account for the possibility of a\nnuclear spin exchange simply gets ``pushed forward'' to the vertex at\nwhich the two nuclear spins in question part ways, e.g.~to account for\nthe two possibilities\n\\begin{align}\n  \\begin{tikzpicture}\n    \\begin{feynman}\n      \\vertex (v1);\n      \\vertex[right = of v1] (v2);\n      \\vertex[below right = of v2] (v3);\n      \\vertex[above left = of v1] (f1) {$\\mu r$};\n      \\vertex[below left = of v1] (f2) {$\\nu s$};\n      \\vertex[below left = of v3] (f3) {$\\rho t$};\n      \\vertex[above right = of v2] (f4) {$\\mu r''$};\n      \\vertex[above right = of v3] (f5) {$\\nu s'''$};\n      \\vertex[below right = of v3] (f6) {$\\rho t'$};\n      \\diagram* {\n        (f1) -- (v1)\n        --[half left, scalar, edge label=$\\ell\\mu r'$] (v2)\n        -- (f4),\n        (f2) -- (v1)\n        --[half right, scalar, edge label'=$m\\nu s'$] (v2)\n        --[scalar, edge label=$n\\nu s''$] (v3)\n        -- (f5),\n        (f3) -- (v3) -- (f6), };\n    \\end{feynman}\n  \\end{tikzpicture}\n  &&\n  \\t{and}\n  &&\n  \\begin{tikzpicture}\n    \\begin{feynman}\n      \\vertex (v1);\n      \\vertex[right = of v1] (v2);\n      \\vertex[below right = of v2] (v3);\n      \\vertex[above left = of v1] (f1) {$\\mu r$};\n      \\vertex[below left = of v1] (f2) {$\\nu s$};\n      \\vertex[below left = of v3] (f3) {$\\rho t$};\n      \\vertex[above right = of v2] (f4) {$\\nu s''$};\n      \\vertex[above right = of v3] (f5) {$\\mu r'''$};\n      \\vertex[below right = of v3] (f6) {$\\rho t'$};\n      \\diagram* {\n        (f1) -- (v1)\n        --[half left, scalar, edge label=$\\ell\\mu r'$] (v2)\n        -- (f4),\n        (f2) -- (v1)\n        --[half right, scalar, edge label'=$m\\nu s'$] (v2)\n        --[scalar, edge label=$n\\mu r''$] (v3)\n        -- (f5),\n        (f3) -- (v3) -- (f6), };\n    \\end{feynman}\n  \\end{tikzpicture},\n  \\label{eq:mu_nu_loop}\n\\end{align}\nwhich are equal up to the re-indexing\n$\\p{\\nu,s,s',s'',s''',m}\\leftrightarrow\\p{\\mu,r,r',r'',r''',\\ell}$.\nThe arguments for a symmetry factor in cases\n\\ref{enum:different_vertices} and \\ref{enum:same_vertex} fail only if\nthe two nuclear spins in question take identical paths through the\ninternal vertices of a diagram, such that there is no meaningful sense\nin which two diagrams can be said to differ by a nuclear spin\nexchange, as in \\eqref{eq:mu_nu} and \\eqref{eq:mu_nu_loop}.  If two\natoms take identical paths through the internal vertices of a diagram,\nhowever, then they have only participated in a two-body process, as in\n\\begin{align}\n  \\shrink{\n    \\begin{tikzpicture}\n      \\begin{feynman}\n        \\vertex (v);\n        \\vertex[above left = of v] (f1);\n        \\vertex[below left = of v] (f2);\n        \\vertex[above right = of v] (f3);\n        \\vertex[below right = of v] (f4);\n        \\diagram* {\n          (f1) -- (v),\n          (f2) -- (v),\n          (v) -- (f3),\n          (v) -- (f4) };\n      \\end{feynman}\n    \\end{tikzpicture}},\n  &&\n  \\shrink{\n    \\begin{tikzpicture}\n      \\begin{feynman}\n        \\vertex (v1);\n        \\vertex[above left = of v1] (f1);\n        \\vertex[below left = of v1] (f2);\n        \\vertex[right = of v1] (v2);\n        \\vertex[above right = of v2] (f3);\n        \\vertex[below right = of v2] (f4);\n        \\diagram* {\n          (f1) -- (v1),\n          (f2) -- (v1),\n          (v2) -- (f3),\n          (v2) -- (f4),\n          (v1) --[scalar, half left] (v2),\n          (v1) --[scalar, half right] (v2) };\n      \\end{feynman}\n    \\end{tikzpicture}},\n  &&\n  \\shrink{\n    \\begin{tikzpicture}\n      \\begin{feynman}\n        \\vertex (v1);\n        \\vertex[above left = of v1] (f1);\n        \\vertex[below left = of v1] (f2);\n        \\vertex[right = of v1] (v2);\n        \\vertex[right = of v2] (v3);\n        \\vertex[above right = of v3] (f3);\n        \\vertex[below right = of v3] (f4);\n        \\diagram* {\n          (f1) -- (v1),\n          (f2) -- (v1),\n          (v3) -- (f3),\n          (v3) -- (f4),\n          (v1)\n          --[scalar, half left] (v2)\n          --[scalar, half left] (v3),\n          (v1)\n          --[scalar, half right] (v2)\n          --[scalar, half right] (v3) };\n      \\end{feynman}\n    \\end{tikzpicture}},\n  &&\n  \\cdots.\n\\end{align}\nAfter summing over all free indices, therefore, all two-body diagrams\nhave a remaining factor of $1/2$ from the first vertex.  In all\nconnected $M$-body diagrams with $M>2$, meanwhile, every factor of\n$1/2$ can be identified one-to-one with a corresponding symmetry\nfactor of $2$.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Effective coupling constants in a lattice}\n\\label{sec:renormalization}\n\nDue to our choice of renormalization scheme in section\n\\ref{sec:two_body}, the interaction energies prescribed by our\nlow-energy effective theory for multiply-occupied lattice sites are\nnot given directly by the coupling constants $G_X$ defined by the\nfree-space scattering lengths $a_X$ in \\eqref{eq:couplings}.  Instead,\nwe must first compute effective coupling constants\n$G_X^{\\t{lattice}}\\p{\\U}$ in a lattice with depth $\\U$, and in turn\nuse the effective coupling constants to compute interaction energies.\nAs the renormalization procedure $G_X\\to G_X^{\\t{lattice}}$ is\nidentical for all coupling constants, we henceforth drop the subscript\n$X\\in\\set{\\g\\g,\\e\\g^-,\\e\\g^+,\\e\\e}$ on coupling constants $G_X$ in the\nremainder of this Appendix.  To further simplify notation, we will\nalso neglect the explicit dependence of parameters on the lattice\ndepth $\\U$, which we generally keep fixed.\n\nProper calculations of the interaction energy of two ultracold\nfermions in an optical lattice were performed in\nrefs.~\\cite{wall2013strongly} and \\cite{buchler2010microscopic} using\na two-channel model of a Feshbach resonance, yielding prescriptions\nfor computing effective coupling constants in a lattice from\nfree-space interaction parameters.  These calculations, however, are\nboth analytically and numerically involved.  We therefore instead opt\nto use a modified version of the considerably simpler single-channel\ncalculation in ref.~\\cite{busch1998two} of the interaction energy of\ntwo ultracold atoms in a harmonic trap.  Our approach is equivalent to\nthe calculation of Hubbard parameters performed in\nref.~\\cite{dickerscheid2005feshbach}, and has been demonstrated to\nreproduce correct results in the limit of a deep lattice (compared to\nthe lattice photon recoil energy) and small positive scattering\nlengths (compared to the effective harmonic oscillator length)\n\\cite{buchler2010microscopic}.\n\nThe exact result in Eq. 16 of ref.~\\cite{busch1998two} for the\ninteraction energy of two ultracold atoms in a harmonic oscillator\nwith angular trap frequency $\\omega$ can be written in the form\n\\begin{align}\n  \\p{G_{\\t{free}} K_{\\t{HO}}/\\omega}^{-1}\n  = \\f{\\sqrt{\\pi}~ \\Gamma\\p{-G_{\\t{HO}}K_{\\t{HO}}/2\\omega}}\n  {\\Gamma\\p{-G_{\\t{HO}}K_{\\t{HO}}/2\\omega-1/2}},\n  &&\n  K_{\\t{HO}} \\equiv \\int \\d^3x~ \\abs{\\phi_0^{\\t{HO}}}^4,\n  \\label{eq:harmonic_gamma}\n\\end{align}\nwhere $G_{\\t{HO}}$ is an effective coupling constant in the harmonic\ntrap, $\\phi_0^{\\t{HO}}\\p{x}$ is the corresponding non-interacting\nground-state wavefunction, and $\\Gamma$ is the gamma function.  The\nexpression in \\eqref{eq:harmonic_gamma} can be solved numerically as\nis, or expanded about $G_{\\t{HO}}K_{\\t{HO}}/\\omega=0$ to get\n\\begin{align}\n  G_{\\t{free}}^{-1} = G_{\\t{HO}}^{-1}\n  \\sum_{n=0}^\\infty c_n \\p{G_{\\t{HO}}K_{\\t{HO}}/\\omega}^n,\n  \\label{eq:harmonic_series}\n\\end{align}\nwhere the first few coefficients are\n\\begin{align}\n  c_0 = 1,\n  &&\n  c_1 = 1 - \\ln 2,\n  &&\n  c_2 = -\\f{\\pi^2}{24} - \\ln 2 + \\f12 \\p{\\ln 2}^2.\n\\end{align}\nThe series in \\eqref{eq:harmonic_series} can in turn be inverted to\nsolve for $G_{\\t{HO}}$ with an expansion of the form\n\\begin{align}\n  G_{\\t{HO}} = G_{\\t{free}}\n  \\sum_{n=0}^\\infty \\tilde c_n \\p{G_{\\t{free}}K_{\\t{HO}}/\\omega}^n,\n  \\label{eq:inverted_series}\n\\end{align}\nwhere if we truncate the series in \\eqref{eq:harmonic_series} at\n$n=2$, the first few coefficients of \\eqref{eq:inverted_series} are\n\\begin{align}\n  \\tilde c_0 = 1,\n  &&\n  \\tilde c_1 = 1 - \\ln 2,\n  &&\n  \\tilde c_2 = -\\f{\\pi^2}{24} - \\ln 2 + \\f12 \\p{\\ln 2}^2\n  + \\p{1 - \\ln 2}^2.\n  \\label{eq:inverted_coefficients}\n\\end{align}\nThe coefficients $\\tilde c_n$ thus found are consistent with the\ncoefficients $c_2^{(n+1)}$ reported in table 1 of\nref.~\\cite{johnson2012effective}, in which the authors compute the\nfirst few terms of the two-body Hamiltonian $H_2$ directly as\nexpressed in \\eqref{eq:H_2_expansion} by using a renormalization\nscheme which subtracts off divergences term by term.\n\nAll of the above results are exact for two atoms in a harmonic\noscillator interacting via $s$-wave scattering.  In order to adapt\nthese results for a lattice, we expand the lattice potential about a\nlattice site centered at $x=(0,0,0)$ as\n\\begin{align}\n  \\U\\sin^2\\p{k_{\\t{L}} \\cdot x}\n  \\approx \\U \\sp{\\p{k_{\\t{L}}^\\x k_{\\t{L}}^\\y k_{\\t{L}}^\\z}^{1/3} x}^2\n  = \\f12 \\mA \\omega_{\\t{eff}}^2 x^2,\n  &&\n  \\omega_{\\t{eff}} \\equiv \\sqrt{2~ \\U k_{\\t{L}}^2 / \\mA},\n\\end{align}\nwhere $k_{\\t{L}}=\\p{k_{\\t{L}}^\\x,k_{\\t{L}}^\\y,k_{\\t{L}}^\\z}$ is the\nlattice wavenumber, $\\mA$ is the atomic mass, and $\\omega_{\\t{eff}}$\nis an effective angular harmonic trap frequency.  We then use\n$\\omega_{\\t{eff}}$ in place of $\\omega$ in \\eqref{eq:harmonic_gamma},\nand use an overlap integral $K$ computed with the ground-state\nwavefunctions $\\phi_0$ in a lattice rather than those in a harmonic\noscillator.  We retrieve free-space $s$-wave scattering lengths\n$a_{\\t{free}}$ for ${}^{87}$Sr from ref.~\\cite{zhang2014spectroscopic}\nto determine the free-space coupling constants\n$G_{\\t{free}} \\equiv \\p{4\\pi/\\mA} a_{\\t{free}}$.  This procedure\nyields an effective coupling constant $G_{\\t{lattice}}$ given by\n\\begin{align}\n  \\p{G_{\\t{free}} K/\\omega_{\\t{eff}}}^{-1}\n  = \\f{\\sqrt{\\pi}~ \\Gamma\\p{-G_{\\t{lattice}}K/2\\omega_{\\t{eff}}}}\n  {\\Gamma\\p{-G_{\\t{lattice}}K/2\\omega_{\\t{eff}}-1/2}},\n\\end{align}\nwith a solution\n\\begin{align}\n  G_{\\t{lattice}} = G_{\\t{free}}\n  \\sum_{n=0}^\\infty \\tilde c_n \\p{G_{\\t{free}}K/\\omega_{\\t{eff}}}^n,\n\\end{align}\nwhere the first few coefficients are provided in\n\\eqref{eq:inverted_coefficients}.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Momentum-dependent $s$-wave interactions}\n\\label{sec:momentum_dependence}\n\nIn addition to the renormalization of coupling constants discussed in\nAppendix \\ref{sec:renormalization}, computing two-body interaction\nenergies $E_{NX}^{(2)}$ at third order in the low-energy effective\ntheory requires accounting for the contribution of momentum-dependent\n$s$-wave interactions.  At next-to-leading order in the relative\nmomentum $k$ between two atoms, the effective momentum-dependent\nscattering length $a_{\\t{eff}}$ is given in terms of the zero-momentum\nscattering length $a$ by \\cite{giorgini2008theory, blume2002fermi,\n  flambaum1999analytical}\n\\begin{align}\n  \\f1{a_{\\t{eff}}}\n  = \\f1a - \\f12 r_{\\t{eff}} k^2\n  = \\f1a\\p{1 - \\f12 r_{\\t{eff}} a k^2},\n\\end{align}\nwhich for $r_{\\t{eff}} a k^2 \\ll 1$, implies that\n\\begin{align}\n  a_{\\t{eff}}\n  \\approx a\\p{1 + \\f12 r_{\\t{eff}} a k^2}\n  = a + \\f12 r_{\\t{eff}} a^2 k^2.\n  \\label{eq:a_eff}\n\\end{align}\nHere $r_{\\t{eff}}$ is an effective range of $\\O\\p{k^2}$ interactions,\ndetermined in atomic units by the scattering length $a$ and van der\nWaals $C_6$ coefficient by \\cite{flambaum1999analytical}\n\\begin{align}\n  r_{\\t{eff}} = \\f13 \\xi^{-2} \\chi \\p{1 - 2\\chi + 2\\chi^2} a,\n  &&\n  \\t{where}\n  &&\n  \\xi \\equiv \\f{\\Gamma\\p{3/4}}{\\Gamma\\p{1/4}},\n  &&\n  \\chi \\equiv \\sqrt{2}~ \\xi~ \\f{\\p{\\mA C_6}^{1/4}}{a},\n  \\label{eq:effective_range}\n\\end{align}\nand $\\Gamma$ is the gamma function.  As $\\chi\\sim1$ for ${}^{87}$Sr,\nthe momentum-dependent correction to the effective scattering length\n$a_{\\t{eff}}$ is $\\O\\p{a^3}$ without an additional separation of\nscales (i.e.~which could have occurred if we had $\\chi\\ll1$ or\n$\\chi\\gg1$).  The momentum-independent $\\O\\p{k^0}$ contribution to\n$a_{\\t{eff}}$ in \\eqref{eq:a_eff} gives rise to the bare two-body\ninteractions in \\eqref{eq:H_int} by use of an unregularized contact\n(i.e.~$\\delta$-function) potential, while the momentum-dependent\n$\\O\\p{k^2}$ term gives rise to the interaction Hamiltonian\n\\cite{blume2002fermi, johnson2012effective}\n\\begin{align}\n  H_{\\t{int}}'\n  \\equiv \\f12 \\sum {G'}^{qr}_{st} \\int \\d^3 x~d^3y~\\delta\\p{z}\n  \\sp{\\hat\\psi_{\\mu q}^\\dag\\p{x} \\hat\\psi_{\\nu r}^\\dag\\p{y}}\n  \\hat k_z^2\\sp{\\hat\\psi_{\\nu t}\\p{y} \\hat\\psi_{\\mu s}\\p{x}},\n  \\label{eq:H_int_primed}\n\\end{align}\nwhere\n\\begin{align}\n  z \\equiv x - y,\n  &&\n  \\hat k_z^2\n  \\equiv -\\f12 \\p{\\vec\\nabla_z^2 + \\lvec\\nabla_z^2},\n\\end{align}\nand the primed couplings ${G'}^{qr}_{st}$ are defined similarly to\nunprimed couplings $G^{qr}_{st}$ in \\eqref{eq:couplings} and\n\\eqref{eq:coupling_tensor}, but with scattering lengths\n$a\\to r_{\\t{eff}}a^2/2$ and the effective range $r_{\\t{eff}}$ defined\nby \\eqref{eq:effective_range} for each scattering length with an\nappropriate $C_6$ coefficient.  We retrieve $C_6$ coefficients for\n${}^{87}$Sr from the supplementary material of\nref.~\\cite{zhang2014spectroscopic}.  The squared relative momentum\noperator $\\hat k_z^2$ is represented by symmetrized left- and\nright-acting derivative operators in order to preserve manifest\nHermiticity of $H_{\\t{int}}'$.  At third order in the low-energy\neffective theory developed in section \\ref{sec:low_energy}, the bare\nmomentum-dependent interactions in \\eqref{eq:H_2} yield only the\neffective two-body Hamiltonian\n\\begin{align}\n  H_2' \\equiv \\f12 K' \\sum {G'}^{qr}_{st}\n  \\c_{\\mu s}^\\dag \\c_{\\nu t}^\\dag \\c_{\\nu r} \\c_{\\mu q},\n  \\label{eq:H_2_prime}\n\\end{align}\nwhere, letting $\\Re\\sp{X}$ denote the real part of $X$,\n\\begin{align}\n  K' \\equiv \\f12 \\int \\d^3x~\n  \\Re\\sp{\\p{\\phi_0^*}^2\n    \\p{\\vec\\nabla\\phi_0\\cdot\\vec\\nabla\\phi_0\n      - \\phi_0\\vec\\nabla^2\\phi_0}}.\n\\end{align}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Bounds on theoretical uncertainties from inter-site effects}\n\\label{sec:error}\n\nIn our overview of the relevant one- and two-particle physics of\nultracold atoms on a lattice (section \\ref{sec:overview}), we made two\napproximations which introduce error into the low-energy effective\ntheory.  Both approximations concern the on-site locality of the\nsingle- and two-body Hamiltonians: we assumed that\n\\begin{enumerate*}\n\\item tunneling between lattice sites and\n\\item inter-site interactions are negligible.\n\\end{enumerate*}\nThese approximations are justified for single-particle motional ground\nstates of atoms in a deep lattice, but generally break down when\nconsidering virtual states occupying highly excited motional levels,\nwhose spatial wavefunctions can span multiple lattice sites.\nNonetheless, we can place upper bounds on the magnitude of inter-site\ncorrections to the effective on-site interaction Hamiltonians by\ntreating tunneling and inter-site interactions of virtual excited\nstates perturbatively and assuming no energetic penalty for\nnearest-neighbor hopping.  These bounds can be used to diagnose the\nbreakdown of the on-site effective theory, and signal when a more\ncareful consideration of inter-site effects is necessary to make\nprecise predictions about many-body spectra and dynamics.\n\nIf we still assume negligible overlap between single-particle\nground-state wavefunctions in different lattice sites but consider\nnearest-neighbor wavefunction overlaps of states with motional\nexcitations, our one-body and bare two-body Hamiltonians become\n\\begin{align}\n  H_0 = \\sum E_n \\c_{in\\mu s}^\\dag \\c_{in\\mu s}\n  - \\sum_{\\substack{\\bk{i,j}\\\\m,n>0}}\n  \\p{t_{mn} \\c_{jn\\mu s}^\\dag \\c_{im\\mu s} + \\t{h.c.}},\n  \\label{eq:H_0_neighbor}\n\\end{align}\nand\n\\begin{align}\n  H_{\\t{int}} &= \\f12 \\sum K^{k\\ell}_{mn} G^{qr}_{st}\n  \\c_{im\\mu s}^\\dag \\c_{in\\nu t}^\\dag \\c_{i\\ell\\nu r} \\c_{ik\\mu q}\n  + \\f12 \\sum_{\\substack{\\bk{i,j}\\\\n>0}} G^{\\mu q;\\nu r}_{\\rho s;\\sigma t}\n  \\p{\\K_n \\c_{j,0,\\rho s}^\\dag \\c_{j,0,\\sigma t}^\\dag\n    \\c_{j,0,\\nu r} \\c_{in\\mu q} + \\t{h.c.}} \\nonumber \\\\\n  &\\quad + \\f12 \\sum_{\\substack{\\bk{i,j}\\\\m,n>0}}\n  G^{\\mu q;\\nu r}_{\\rho s;\\sigma t}\n  \\p{\\K_{mn} \\c_{j,0,\\rho s}^\\dag \\c_{j,0,\\sigma t}^\\dag\n    \\c_{in\\nu r} \\c_{im\\mu q} +\n    \\tilde\\K_{mn} \\c_{in\\rho s}^\\dag \\c_{j,0,\\sigma t}^\\dag\n    \\c_{j,0,\\nu r} \\c_{im\\mu q} + \\t{h.c.}},\n  \\label{eq:H_int_neighbor}\n\\end{align}\nwhere $t_{mn}$ is a tunneling rate; $\\K_n,\\K_{mn},\\tilde\\K_{mn}$ are\ninter-site spatial overlap integrals; $\\t{h.c.}$ denotes a Hermitian\nconjugate, i.e.~$\\p{X+\\t{h.c.}}\\equiv \\p{X+X^\\dag}$; and $\\bk{i,j}$\ndenotes the set of all lattice sites $i$ together with their adjacent\nsites $j$.  Note that we have neglected terms in\n\\eqref{eq:H_int_neighbor} which involve more than two field operators\naddressing states with motional excitations, as these terms will not\nappear in the leading-order corrections to the effective on-site\ninteraction Hamiltonians.  We also still neglect terms which involve\nproducts of atomic wavefunctions for motional ground states in\ndifferent lattice sites.\n\nDiagrammatically representing matrix elements of $H_0$ and\n$H_{\\t{int}}$ which are off-diagonal in lattice site by a dot\n(i.e.~$\\bullet$) and marking lines which represent field operators\naddressing neighboring lattice sites by a cross (i.e.~$+$ or $\\times$,\ndepending on the line orientation), the dominant terms in the\neffective theory which we previously neglected by assuming on-site\nlocality are\n\\begin{align}\n  \\begin{tikzpicture}\n    \\begin{feynman}\n      \\vertex (v1);\n      \\vertex[above left = of v1] (f1);\n      \\vertex[below left = of v1] (f2);\n      \\vertex[right = of v1] (v2);\n      \\vertex[above right = of v2] (f3);\n      \\vertex[below right = of v2] (f4);\n      \\diagram* {\n        (f1) -- (v1),\n        (f2) -- (v1),\n        (v1) --[scalar, half left] (v2),\n        (v1) --[scalar, half right] (v2),\n        (v2) --[insertion = 0.5] (f3),\n        (v2) --[insertion = 0.5] (f4) };\n      \\draw[fill=black] (v2) circle(0.8mm);\n    \\end{feynman}\n  \\end{tikzpicture}\n  &\\sim \\gamma_2^{(2)} G^2,\n  & \\gamma_2^{(2)} &\\equiv \\sum_{n+m>0} \\f{K_{mn}\\K_{mn}}{E_{mn}},\n  \\label{eq:g_2_2} \\\\[1em]\n  \\begin{tikzpicture}\n    \\begin{feynman}\n      \\vertex (v1);\n      \\vertex[above left = of v1] (f1);\n      \\vertex[below left = of v1] (f2);\n      \\vertex[right = 4em of v1] (v2);\n      \\vertex[above right = of v1] (f3);\n      \\vertex[below left = of v2] (f4);\n      \\vertex[below right = of v2] (f5);\n      \\vertex[above right = of v2] (f6);\n      \\diagram* {\n        (f1) -- (v1) -- (f3),\n        (f2) -- (v1) --[scalar] (v2),\n        (f4) --[insertion = 0.5] (v2) --[insertion = 0.5] (f5),\n        (v2) --[insertion = 0.5] (f6), };\n      \\draw[fill=black] (v2) circle(0.8mm);\n    \\end{feynman}\n  \\end{tikzpicture}\n  &\\sim \\gamma_{3,1}^{(2)} G^2,\n  & \\gamma_{3,1}^{(2)} &\\equiv \\sum_{n>0} \\f{K_n\\K_n}{E_n},\n  \\label{eq:g_3_1_2} \\\\[1em]\n  \\begin{tikzpicture}\n    \\begin{feynman}\n      \\vertex (v1);\n      \\vertex[above left = of v1] (f1);\n      \\vertex[below left = of v1] (f2);\n      \\vertex[right = 2em of v1] (v2);\n      \\vertex[right = 2em of v2] (v3);\n      \\vertex[above right = of v1] (f3);\n      \\vertex[below left = of v3] (f4);\n      \\vertex[below right = of v3] (f5);\n      \\vertex[above right = of v3] (f6);\n      \\diagram* {\n        (f1) -- (v1) -- (f3),\n        (f2) -- (v1) --[scalar] (v2) --[scalar, insertion = 0.5] (v3),\n        (f4) --[insertion = 0.5] (v3) --[insertion = 0.5] (f5),\n        (v3) --[insertion = 0.5] (f6), };\n      \\draw[fill=black] (v2) circle(0.8mm);\n    \\end{feynman}\n  \\end{tikzpicture}\n  &\\sim \\gamma_{3,2}^{(2)} G^2,\n  & \\gamma_{3,2}^{(2)} &\\equiv \\sum_{n,m>0} \\f{K_mt_{mn}K_n}{E_mE_n},\n  \\label{eq:g_3_2_2}\n\\end{align}\nwhere we have identified, up to an assignment of coupling constants\n$G$, the magnitude of all nonzero matrix elements of the diagrams with\nrespect to an eigenbasis of the on-site single-particle Hamiltonian\n$H_0$ in \\eqref{eq:H_0}.\n\nThe terms in \\eqref{eq:g_2_2}-\\eqref{eq:g_3_2_2} can be used to\nestimate an upper bound on the magnitude of dominant corrections to\nthe spectrum of the low-energy theory from off-diagonal (i.e.~in\nlattice site) matrix elements of the Hamiltonians in\n\\eqref{eq:H_0_neighbor} and \\eqref{eq:H_int_neighbor}.  Conservatively\nassuming no energetic penalty and no Pauli blocking for any inter-site\nprocess, the dominant correction $\\delta E_N$ to the interaction\nenergy of a lattice site with $N$ atoms and $b$ neighboring sites\n(e.g.~$b=6$ in a primitive cubic lattice) is roughly bounded as\n\\begin{align}\n  \\abs{\\delta E_N} \\lesssim b {N\\choose 2}\n  \\max\\set{\\abs{\\gamma_2^{(2)}},\n    \\p{N-1} \\abs{\\gamma_{3,1}^{(2)} + \\gamma_{3,2}^{(2)}}} G^2,\n  \\label{eq:delta_E_N}\n\\end{align}\nwhere the factor of $b$ accounts for the multiplicity of neighboring\nsites; the factor of ${N\\choose2}$ accounts for the number of on-site\npairs of atoms which are addressed by the diagrams in\n\\eqref{eq:g_2_2}-\\eqref{eq:g_3_2_2}; and the factor of $N-1$ on\n$\\gamma_{3,X}^{(2)}$ accounts for the number of atoms in a neighboring\nsite which are addressed by the corresponding processes.  These\nfactors count the number of matrix elements in the Hamiltonian with\nmagnitude $\\sim\\gamma_X^{(2)}G^2$.  The maximization in\n\\eqref{eq:delta_E_N} is performed because the relevant two- and\nthree-body processes are mutually exclusive, requiring a different\nnumber of atoms on neighboring lattice sites.  For a conservative\nbound of $\\abs{\\delta E_N}$, the coupling factor $G^2$ in\n\\eqref{eq:delta_E_N} can simply be maximized over its allowed values\nfor a given state of atoms on a lattice site, e.g.~$G_\\g^2$ for a\nstate with no orbital excitations, or $\\max\\set{G_\\g^2,G_+^2,G_-^2}$\nfor a state with one net orbital excitation (in both cases, assuming\nno orbital excitations in neighboring sites).  In the latter case, the\nbound in \\eqref{eq:delta_E_N} can also be reduced by observing that to\nconserve energy, it must be the excited atom which moves to a\nneighboring site, which reduces the factor of ${N\\choose2}$ in down to\n$N-1$.  We emphasize that the bound in \\eqref{eq:delta_E_N} is by no\nmeans an exact measure of error, and is merely intended to provide a\nconservative range of energies and corresponding time scales for which\ninter-site effects could become relevant despite negligible\nsingle-particle ground-state tunneling rates.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Perturbative parameters for the effective theory}\n\\label{sec:pert_params}\n\nThe perturbative effective theory developed in Section\n\\ref{sec:low_energy} is organized in powers of the coupling constants\n$G_X$.  The formally small, dimensionless quantities for this\nperturbation theory are the two-body interaction energies $K G_X$\ndivided by the spectral gap $\\Delta$ of the non-interacting\nHamiltonian $H_0$.  Here $K$ is a ground-state two-body overlap\nintegral and $G_X$ is a coupling constant.  The quantities $K$, $G_X$,\nand $\\Delta$ all depend on the lattice depth $\\U$.  Figure\n\\ref{fig:pert_params} shows these parameters for the case of\n${}^{87}$Sr atoms with $X\\in\\set{\\g\\g, \\e\\g_-, \\e\\g_+, \\e\\e}$ at\nlattice depths $\\U\\in\\sp{30,80}E_{\\t{R}}$, where\n$E_{\\t{R}}\\approx3.5\\times2\\pi~\\t{kHz}$ is the lattice photon recoil\nenergy of the atoms.  The fact that these perturbative parameters grow\nwith increasing lattice depth $\\U$ is a consequence of the fact that\nthe overlap integral $K$ grows faster with $\\U$ than the spectral gap\n$\\Delta$.  In the case of a harmonic trap with angular frequency\n$\\omega$, for example, by dimensional analysis these parameters would\nbe\n\\begin{align}\n  \\f{K_{\\t{HO}} G_X}{\\omega}\n  = \\f{G_X}{\\omega} \\int \\d^3 x~\\abs{\\phi_{\\t{HO}}}^4\n  = \\f{G_X}{\\omega} \\sp{\\int \\d x~\n    \\abs{\\p{\\f{\\mA\\omega}{\\pi}}^{1/4} e^{-\\mA\\omega x^2/2}}^4}^3\n  \\propto \\sqrt{\\omega},\n\\end{align}\nwhere we assumed that the coupling constants $G_X$ vary weakly with\n$\\omega$.  While this result may seem to suggest that the low-energy\neffective theory should become better at smaller lattice depths,\nsmaller lattice depths also result in increased theoretical\nuncertainties from the growing relevance of the inter-site effects\ndiscussed in Appendix \\ref{sec:error}.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics{perturbative_params.pdf}\n  \\caption{\\footnotesize Dependence of the perturbative parameters\n    $KG_X/\\Delta$ on the lattice depth $\\U$.}\n  \\label{fig:pert_params}\n\\end{figure}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Low-excitation $M$-body Hamiltonian coefficients}\n\\label{sec:U_X}\n\nWhen restricted to the subspace of at most one orbital excitation per\nlattice site, the $M$-body Hamiltonians of the low-energy effective\ntheory developed in Section \\ref{sec:low_energy} can be written in the\nform\n\\begin{align}\n  H_M = \\sum_{\\abs{\\set{\\mu_j}}=M}\n  \\p{U_{M,\\g} \\n_{\\mu_1,\\g} \\n_{\\mu_2,\\g}\n    + U_{M,+} \\n_{\\mu_1,\\e} \\n_{\\mu_2,\\g}\n    + U_{M,-} \\c_{\\mu_1,\\g}^\\dag \\c_{\\mu_2,\\e}^\\dag\n    \\c_{\\mu_2,\\g} \\c_{\\mu_1,\\e}}\n  \\prod_{\\alpha=3}^M \\n_{\\mu_\\alpha,\\g},\n\\end{align}\nwhere the coefficients can be expanded as\n$U_{MX} = \\sum_p U_{MX}^{(p)}$ with terms $U_{MX}^{(p)}$ at order $p$\nin the coupling constants $G_Y$.  The terms $U_{MX}^{(p)}$ can be\ndetermined from the $M$-body $p$-order Hamiltonians $H_M^{(p)}$\nderived in section \\ref{sec:low_energy}, i.e.~in \\eqref{eq:H_2},\n\\eqref{eq:H_3_2}, \\eqref{eq:H_3_3}, and \\eqref{eq:H_4_3}.  For the\neffective 2-, 3-, and 4-body Hamiltonians through third order in the\ncoupling constants, the coefficients are\n\\begin{align}\n  U_{2,\\g} = \\f12 \\alpha_2^{(1)} G_\\g,\n  &&\n  U_{2,+} = \\alpha_2^{(1)} G_+,\n  &&\n  U_{2,-} = \\alpha_2^{(1)} G_-,\n\\end{align}\n\\begin{align}\n  U_{3,\\g}^{(2)} = - \\alpha_3^{(2)} G_\\g^2,\n  &&\n  U_{3,+}^{(2)} = - \\alpha_3^{(2)} G_+ \\p{G_+ + 2 G_\\g},\n\\end{align}\n\\begin{align}\n  U_{3,-}^{(2)} = - \\alpha_3^{(2)} G_- \\p{2 G_+ + G_- + 2 G_\\g},\n\\end{align}\n\\begin{align}\n  U_{3,\\g}^{(3)}\n  = \\p{\\alpha_{3,1}^{(3)} - \\alpha_5^{(3)}} 2 G_\\g^3\n  + \\p{2\\alpha_{3,2}^{(3)} - \\alpha_{4,3}^{(3)} - \\alpha_5^{(3)}} G_\\g^3,\n\\end{align}\n\\begin{align}\n  U_{3,+}^{(3)}\n  &= \\p{\\alpha_{3,1}^{(3)} - \\alpha_5^{(3)}} \\p{G_+^3 + 4 G_+^2 G_\\g\n    + G_+ G_-^2 + G_+ G_\\g^2 + G_-^3 + G_-^2 G_\\g} \\nonumber \\\\\n  &\\quad + \\p{2\\alpha_{3,2}^{(3)} - \\alpha_{4,3}^{(3)} - \\alpha_5^{(3)}}\n  \\p{G_+^3 + G_+^2 G_\\g + G_+ G_-^2 + G_+ G_\\g^2 + G_-^2 G_\\g},\n\\end{align}\n\\begin{align}\n  U_{3,-}^{(3)}\n  &= \\p{\\alpha_{3,1}^{(3)} - \\alpha_5^{(3)}} G_- \\p{3 G_+^2\n    + 2 G_+ G_- + 8 G_+ G_\\g + 3 G_- G_\\g + G_\\g^2} \\nonumber \\\\\n  &\\quad + \\p{2\\alpha_{3,2}^{(3)} - \\alpha_{4,3}^{(3)} - \\alpha_5^{(3)}}\n  G_- \\p{3 G_+^2 + 2 G_+ G_- + 2 G_+ G_\\g + G_-^2 + G_\\g^2},\n\\end{align}\n\\begin{align}\n  U_{4,\\g}^{(3)}\n  = \\p{2\\alpha_{4,1}^{(3)} - \\alpha_5^{(3)}} G_\\g^3\n  + \\p{\\alpha_{4,2}^{(3)} - \\alpha_5^{(3)}} 2 G_\\g^3,\n\\end{align}\n\\begin{align}\n  U_{4,+}^{(3)}\n  &= \\p{2\\alpha_{4,1}^{(3)} - \\alpha_5^{(3)}}\n  2 G_+ G_\\g \\p{G_+ + G_\\g}\n  + \\p{\\alpha_{4,2}^{(3)} - \\alpha_5^{(3)}}\n  G_+ \\p{G_+^2 + 2 G_+ G_\\g + 5 G_\\g^2},\n\\end{align}\n\\begin{align}\n  U_{4,-}^{(3)}\n  &= \\p{2\\alpha_{4,1}^{(3)} - \\alpha_5^{(3)}}\n  2 G_- G_\\g \\p{2 G_+ + G_- + G_\\g} \\nonumber \\\\\n  &\\quad + \\p{\\alpha_{4,2}^{(3)} - \\alpha_5^{(3)}}\n  G_- \\p{3 G_+^2 + 3 G_+ G_- + 4 G_+ G_\\g + G_-^2\n    + 2 G_- G_\\g + 5 G_\\g^2},\n\\end{align}\nIn terms of the spatial overlap integrals defined in \\eqref{eq:K_klmn}\nand \\eqref{eq:K}, the prefactors $\\alpha_X^{(p)}$ on the coefficients\n$U_X^{(p)}$ are\n\\begin{align}\n  \\alpha_2^{(1)} \\equiv K,\n  &&\n  \\alpha_3^{(2)} \\equiv \\sum_{n>0} \\f{K_n^2}{E_n},\n  &&\n  \\alpha_5^{(3)}\n  \\equiv  K \\sum_{n>0} \\f{K_n^2}{E_n^2},\n\\end{align}\n\\begin{align}\n  \\alpha_{3,1}^{(3)} \\equiv \\sum_{\\substack{\\ell+m>0\\\\\\ell+n>0}}\n  \\f{K_{\\ell m} K^m_n K_{\\ell n}}{E_{\\ell m} E_{\\ell n}},\n  &&\n  \\alpha_{3,2}^{(3)}\n  \\equiv \\sum_{\\substack{\\ell+m>0\\\\n>0}}\n  \\f{K_{\\ell m} K_n}{E_{\\ell m} E_n}\n  \\p{K^{\\ell m}_n - \\f{K_{\\ell m} K_n}{K}},\n\\end{align}\n\\begin{align}\n  \\alpha_{4,1}^{(3)}\n  \\equiv \\sum_{\\substack{m\\ge0\\\\n>0}} \\f{K_{mn} K_m K_n}{E_{mn} E_n},\n  &&\n  \\alpha_{4,2}^{(3)}\n  \\equiv \\sum_{m,n>0} \\f{K_m K^m_n K_n}{E_m E_n},\n  &&\n  \\alpha_{4,3}^{(3)}\n  \\equiv K \\sum_{m+n>0} \\f{K_{mn}^2}{E_{mn}^2}.\n\\end{align}\n\n\\bibliography{\\jobname}\n\n\\end{document}", "meta": {"hexsha": "77bc3481c6bf6a9d0acea5be1e875e70b44b9850", "size": 154787, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "multi_body_interactions/papers/theory/paper.tex", "max_stars_repo_name": "perlinm/rey_research", "max_stars_repo_head_hexsha": "491d1d33cc8d20dc1b72de552ac7c1b65fb3ee63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "multi_body_interactions/papers/theory/paper.tex", "max_issues_repo_name": "perlinm/rey_research", "max_issues_repo_head_hexsha": "491d1d33cc8d20dc1b72de552ac7c1b65fb3ee63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "multi_body_interactions/papers/theory/paper.tex", "max_forks_repo_name": "perlinm/rey_research", "max_forks_repo_head_hexsha": "491d1d33cc8d20dc1b72de552ac7c1b65fb3ee63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.7116445916, "max_line_length": 75, "alphanum_fraction": 0.6567088967, "num_tokens": 51888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.32035776959250534}}
{"text": "\\input{../../_common/preamble}\n\n\\title{Generalised linear models}\n\n\\begin{document}\n\n\\maketitle\n\n\\begin{frame}{Contents}\n    \\tableofcontents[hideallsubsections]\n\\end{frame}\n\n\\section{Regression models}\n\n\\begin{frame}{Regression models}\n    Regression models explore associations between:\n    \\begin{itemize}\n        \\item A \\alert{response} variable $\\vec{y}$\n        \\item \\alert{Explanatory} variables (or \\alert{predictors})\n              $\\vec{x_{1}}, \\ldots, \\vec{x_{p}}$\n    \\end{itemize}\n    \\vfill\\pause\n    \\begin{block}{Question}\n        Do the $\\vec{x_{1}}, \\ldots, \\vec{x_{p}}$ capture the\n        \\alert{variability} of $\\vec{y}$?\n    \\end{block}\n\\end{frame}\n\n\\begin{frame}{Regression modelling steps}\n    \\begin{itemize}\n        \\item \\alert{Formulation}\n              \\begin{enumerate}\n                  \\item Error distribution for the response $\\vec{y}$\n                  \\item Combination of predictors\n                  \\item Link function \\\\[\\bigskipamount]\n              \\end{enumerate}\n        \\item \\alert{Estimation} of regression coefficients \\\\[\\bigskipamount]\n        \\item \\alert{Diagnostics} (does the model fit the data well?) \\\\[\\bigskipamount]\n        \\item \\alert{Selection} (can we improve the fit?)\n    \\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Components of regression models}\n    \\begin{enumerate}[(1)]\n        \\item A model for the \\alert{variability} of the response $\\vec{y}$\n              \\begin{itemize}\n                  \\item $\\vec{y}$ is continuous $\\rightarrow$ normal distribution\n                  \\item $\\vec{y}$ is dichotomous $\\rightarrow$ binomial distribution \\\\[\\bigskipamount]\n              \\end{itemize}\n        \\pause\n        \\item A \\alert{combination of predictors} $\\vec{x_{1}}, \\ldots, \\vec{x_{p}}$\n              \\begin{itemize}\n                  \\item Often linear, e.g.\\ $2 \\vec{x_{1}} + 3 \\vec{x_{2}}$\n                  \\item $\\beta_{1} = 2$ and $\\beta_{2} = 3$ are\n                        \\alert{regression coefficients} \\\\[\\bigskipamount]\n              \\end{itemize}\n        \\pause\n        \\item A \\alert{link} between the two\n              \\begin{itemize}\n                  \\item Often depends on the model for the response\n                  \\item Linear regression:\n                        $\\E{\\vec{y}} = 2 \\vec{x_{1}} + 3 \\vec{x_{2}}$\n              \\end{itemize}\n    \\end{enumerate}\n\\end{frame}\n\n\\begin{frame}{Predictors and response}\n    \\begin{block}{Predictors}\n        \\begin{itemize}\n            \\item Viewed as \\alert{fixed} variables\n            \\item Assumed not to be affected by \\alert{measurement error}\n            \\item[$\\rightarrow$] `Independent' or `exogenous'\n        \\end{itemize}\n    \\end{block}\n    \\vfill\n    \\begin{block}{Response}\n        \\begin{itemize}\n            \\item \\alert{Variability is modelled} \\\\\n                  (but could also be attributed to other factors)\n            \\item[$\\rightarrow$] `Dependent' or `endogenous'\n        \\end{itemize}\n    \\end{block}\n\\end{frame}\n\n\\section{Linear regression}\n\n\\begin{frame}{Simple linear regression}\n    \\begin{columns}[c]\n        \\begin{column}{0.5\\textwidth}\n            \\centering\n            \\includegraphics[width=\\textwidth]{figures/lm}\n        \\end{column}\n        \\begin{column}{0.5\\textwidth}\n            {\\small%\n             For the $i^{\\,\\text{th}}$ observation:}\n            \\vspace{-1ex}\n            \\begin{center}\n                $y_{i} = \\beta_{0} + \\beta_{1}\\,x_{i} + \\epsilon_{i}$ \\\\[\\bigskipamount]\n                \\begin{tabular}{ll}\n                    \\toprule\n                    $\\beta_{0}$    & Intercept \\\\\n                    $\\beta_{1}$    & Slope \\\\\n                    $\\epsilon_{i}$ & Individual error term \\\\\n                    \\bottomrule\n                \\end{tabular}\n            \\end{center}\n        \\end{column}\n    \\end{columns}\n\\end{frame}\n\n\\begin{frame}[t]{Regression coefficients}\n    \\[\n        y_{i} = \\alert{\\beta_{0}} + \\alert{\\beta_{1}}\\,x_{i} + \\epsilon_{i}\n    \\]\n    \\vfill\n    \\begin{description}\n        \\item[\\textbf{Intercept}] Average $y$ when $x = 0$\n        \\item[\\textbf{Slope}] Increase in $y$ for a one\\hyp{}unit increase in $x$\n    \\end{description}\n    \\vfill\n    The regression line passes through:\\vspace{-1ex}\n    \\begin{itemize}\n        \\item The point $(0, \\beta_{0})$\n        \\item The `centre' of the data $(\\bar{\\vec{x}}, \\bar{\\vec{y}})$\n    \\end{itemize}\n\\end{frame}\n\n\\begin{frame}[t]{Error term}\n    \\[\n        y_{i} = \\beta_{0} + \\beta_{1}\\,x_{i} + \\alert{\\epsilon_{i}}\n    \\]\n    \\vfill\n    \\begin{itemize}\n        \\item `Sucks up' unaccounted variation in $\\vec{y}$\n        \\item Model assumptions are mostly on $\\epsilon$\n    \\end{itemize}\n\\end{frame}\n\n\\begin{frame}[t]{Multiple linear regression}\n    \\only<1>{%\n        {\\small%\n         For the $i^{\\,\\text{th}}$ observation:}\n        \\vspace{-1ex}\n        \\begin{center}\n            $y_{i} = \\beta_{0} + \\sum_{j} \\beta_{j}\\,x_{ij} + \\epsilon_{i}$ \\\\[\\bigskipamount]\n            \\begin{tabular}{ll}\n                \\toprule\n                $\\beta_{0}$    & Intercept \\\\\n                $\\beta_{j}$    & Slopes \\\\\n                $\\epsilon_{i}$ & Individual error term \\\\\n                \\bottomrule\n            \\end{tabular}\n        \\end{center}\n        \\vfill\n        \\begin{description}\n            \\item[\\textbf{Intercept}] Average $y$ when all $x_{\\,\\cdot\\,j} = 0$\n            \\item[\\textbf{Slopes}] Increase in $y$ for a one\\hyp{}unit increase\n                                   in $x_{\\,\\cdot\\,j}$ \\\\\n                                   \\alert{all else being equal}\n        \\end{description}}\n    \\only<2>{%\n        {\\small\n         In matrix form:}\n        \\vspace{-1ex}\n        \\begin{center}\n            $\\vec{y} = \\mat{X} \\vec{\\beta} + \\vec{\\epsilon}$ \\\\[\\bigskipamount]\n            \\begin{tabular}{ll}\n                \\toprule\n                $\\mat{X}$        & Design matrix\\\\\n                $\\vec{\\beta}$    & Regression coefficients \\\\\n                $\\vec{\\epsilon}$ & Error term \\\\\n                \\bottomrule\n            \\end{tabular}\n        \\end{center}}\n\\end{frame}\n\n\\begin{frame}{Gauss--Markov assumptions (plus one)}\n    \\begin{itemize}\n        \\item The relationship between $\\vec{y}$ and $\\mat{X}$ is linear\n        \\item The $\\vec{x_{1}}, \\ldots, \\vec{x_{p}}$ are not collinear\n        \\item Exogeneity\n              \\begin{itemize}\n                  \\item Given $\\mat{X}$, errors have mean 0\n                  \\item Since $\\mat{X}_{i}$ is deterministic, it is uncorrelated\n                        with $\\epsilon_{i}$\n              \\end{itemize}\n        \\item Spherical errors\n              \\begin{itemize}\n                  \\item Errors have a fixed variance (homoscedasticity)\n                  \\item Errors are uncorrelated between observations\n                        (no autocorrelation)\n              \\end{itemize}\n        \\item (Given $\\mat{X}$, errors are normally distributed)\n    \\end{itemize}\n\\end{frame}\n\n\\begin{frame}[t]{Model fitting by maximum likelihood}\n    \\begin{center}\n        $Y_{i} \\sim \\Normal{\\mu_{i}}{\\sigma^{2}}$\n        \\quad\n        where\n        \\quad\n        $\\mu_{i} = \\beta_{0} + \\sum_{j} \\beta_{j}\\,x_{ij}$\n    \\end{center}\n    \\vfill\n    \\only<1>{%\n        \\begin{description}\n            \\item[$\\beta_{j}$] `True' values (\\alert{fixed but unknown})\n            \\item[$\\hat{\\beta}_{j}$] Our estimates for the $\\beta_{j}$\n                                     (\\alert{computed from the data})\n        \\end{description}\n        \\vfill\n        Given some values for the $\\hat{\\beta}_{j}$\\ldots\\vspace{-1ex}\n        \\begin{itemize}\n            \\item We can write down the probability of observing each $Y_{i}$\n                  alone\n            \\item Since the $Y_{i}$ are independent by assumption, we can write\n                  down the \\alert{joint} probability of observing the $Y_{i}$\n                  together\n            \\item[$\\rightarrow$] $f\\,( \\vec{y}\\,|\\,\\hat{\\beta}_{j} )$ is the\n                                 probability of the data\n                                 \\alert{given the parameters}\n        \\end{itemize}}\n    \\only<2>{%\n        \\begin{block}{Maximum likelihood principle}\n            \\begin{itemize}\n                \\item Consider instead the \\alert{likelihood function}\n                      $f\\,( \\hat{\\beta}_{j}\\,|\\,\\vec{y} )$\n                \\item Same as $f\\,( \\vec{y}\\,|\\,\\hat{\\beta}_{j} )$, but\n                      interpreted as the probability of certain parameter values\n                      \\alert{given the data}\n                \\item[$\\rightarrow$] Can optimise to estimate the $\\hat{\\beta}_{j}$\n            \\end{itemize}\n        \\end{block}}\n\\end{frame}\n\n\\begin{frame}{Hypothesis testing for parameters}\n    How do we know the \\alert{estimates} $\\hat{\\beta}_{j}$ are not just random\n    fluctuations?\n    \\vfill\\pause\n    \\begin{center}\n        Additional assumption: $\\epsilon_{i} \\simiid \\Normal{0}{\\sigma^{2}}$ \\\\[\\bigskipamount]\n        $\\downarrow$ \\\\[\\bigskipamount]\n    \\end{center}\n    \\begin{itemize}\n        \\item Define confidence intervals for $\\hat{\\beta}_{j}$\n        \\item Test $H_{0}$ that $\\hat{\\beta}_{j} = 0$ (no effect)\n    \\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Diagnostics for linear regression}\n    \\begin{center}\n        \\begin{tabular}{llp{0.5\\textwidth}}\n            \\toprule\n            \\textbf{Assumption violated} & \\textbf{Severity} & \\textbf{Causes} \\\\\n            \\midrule\n            Linearity or additivity & ++++ & Model misspecification \\\\[\\medskipamount]\n            Independence            & +++  & Autocorrelation \\newline (typical of time series) \\\\[\\medskipamount]\n            Homoscedasticity        & ++   & $\\sigma^{2}$ changes over the range of $\\vec{y}$ \\\\[\\medskipamount]\n            Normality               & +    & Outliers \\\\\n            \\bottomrule\n        \\end{tabular}\n    \\end{center}\n\\end{frame}\n\n\\begin{frame}{Many datasets, one regression line}\n    \\begin{center}\n        \\includegraphics[height=0.8\\textheight]{figures/anscombe}\n    \\end{center}\n\\end{frame}\n\n\\section{Logistic regression}\n\n\\begin{frame}{Classification problems}\n    \\begin{center}\n        What happens if the outcome $\\vec{y}$ is dichotomous?\n    \\end{center}\n    \\vfill\\pause\n    We can model the \\alert{probability}\n    \\[\n        \\Prob{y_{i} = 1 \\,\\left|\\,\\vec{x}_{i} \\right.\\!} = p_{i}\\text{,}\n    \\]\n    i.e.\\ the probability of belonging to some non\\hyp{reference} category, as a\n    function of the predictors $\\vec{x_{1}}, \\ldots, \\vec{x_{p}}$\n    \\vfill\n    \\begin{flushright}\n        \\ldots but how?\n    \\end{flushright}\n\\end{frame}\n\n\\begin{frame}{Logistic regression}\n    \\begin{block}{Idea}\n        Transform the linear predictor to lie on the unit interval \\\\[\\bigskipamount]\n        {\\small%\n         For the $i^{\\,\\text{th}}$ observation:}\n        \\[\n            \\logit\\!\\left( p_{i} \\right)\n            = \\log\\!\\left( \\frac{p_{i}}{1 - p_{i}} \\right)\n            = \\beta_{0} + \\sum_{j} \\beta_{j} x_{ij} + \\epsilon\n        \\]\n        $\\beta_{0}, \\ldots, \\beta_{p}$ represent the\n        \\alert{log odds ratios} between classes\n    \\end{block}\n\\end{frame}\n\n\\begin{frame}{Probability and odds}\n    \\begin{columns}[c]\n        \\begin{column}{0.5\\textwidth}\n            \\centering\n            \\[\n                \\logit\\!\\left( p \\right) = \\log\\!\\left( \\frac{p}{1 - p} \\right)\n            \\]\n            \\includegraphics[width=0.8\\textwidth]{figures/logit}\n        \\end{column}\n        \\begin{column}{0.5\\textwidth}\n            Throw a fair die. \\\\\n            How often will you get a $1$?\n            \\begin{block}{Probability}\n                \\[\n                    p = \\frac{1}{6} \\approx 16.67\\% \\text{ of the time}\n                \\]\n            \\end{block}\n            \\vspace{-0.5em}\n            \\begin{block}{Odds}\n                \\[\n                    \\frac{p}{1 - p} = \\frac{1/6}{5/6} = \\frac{1}{5} = 0.2\n                \\]\n                {\\footnotesize%\n                 (once for every $5$ times you don't)}\n            \\end{block}\n        \\end{column}\n    \\end{columns}\n\\end{frame}\n\n\\begin{frame}[t]{Odds ratio}\n    \\only<1>{%\n        \\[\n            \\text{OR} = \\frac{\\text{odds in some group ($y = 1$)}}\n                             {\\text{odds in a reference group ($y = 0$)}}\n        \\]}\n    \\only<2>{%\n        \\begin{block}{Example}\n            \\[\n                \\text{OR} = \\frac{\\text{odds of smoking in lung cancer patients}}\n                                 {\\text{odds of smoking in cancer\\hyp{}free individuals}}\n            \\]\n        \\end{block}\n        \\vfill\n        \\begin{block}{Interpretation}\n            \\[\n                \\text{OR}\n                \\begin{cases}\n                    < 1 & \\text{smoking is \\alert{less likely}} \\\\\n                    = 1 & \\text{smoking is \\alert{no more likely} in lung cancer patients} \\\\\n                    > 1 & \\text{smoking is \\alert{more likely}}\n                \\end{cases}\n            \\]\n        \\end{block}}\n\\end{frame}\n\n\\begin{frame}{Logistic regression recap}\n    \\begin{block}{Model}\n        \\begin{itemize}\n            \\item Outcome is the \\alert{probability} of being in some\n                  non\\hyp{}reference class\n            \\item Regression coefficients represent \\alert{log odds ratios}\n        \\end{itemize}\n    \\end{block}\n    \\vfill\n    \\begin{block}{Interpretation of coefficients}\n        \\begin{itemize}\n            \\item $\\exp\\!\\left( \\beta \\right)$ is the \\alert{odds ratio} between\n                  $y = 0$ and $y = 1$\n            \\item $\\text{OR} = 1$ is the threshold corresponding to no effect\n        \\end{itemize}\n    \\end{block}\n\\end{frame}\n\n\\end{document}\n\n", "meta": {"hexsha": "89561c610794bdc64a0e42c5eb15a60585d522c0", "size": 13582, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "06_glms/slides/glms.tex", "max_stars_repo_name": "JoseHJBlanco/ga-data-science", "max_stars_repo_head_hexsha": "dff5cfd8fb13c1c49cba099bd100ca79143828e4", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2017-11-17T09:44:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-08T18:02:42.000Z", "max_issues_repo_path": "06_glms/slides/glms.tex", "max_issues_repo_name": "itsshaikaslam/ga-data-science", "max_issues_repo_head_hexsha": "b39f3a499749e4423bb193a1376b7dee770152b7", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-03-27T13:05:12.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-27T13:05:12.000Z", "max_forks_repo_path": "06_glms/slides/glms.tex", "max_forks_repo_name": "itsshaikaslam/ga-data-science", "max_forks_repo_head_hexsha": "b39f3a499749e4423bb193a1376b7dee770152b7", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 21, "max_forks_repo_forks_event_min_datetime": "2018-01-01T03:26:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-31T19:24:24.000Z", "avg_line_length": 35.6482939633, "max_line_length": 113, "alphanum_fraction": 0.5212045354, "num_tokens": 3782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.32030014908712984}}
{"text": "\\documentclass[12pt]{article}\n\\usepackage[pdftex]{graphicx}\n\n\\usepackage{qtree}\n\n\n\n\n\\usepackage{setspace} \n\\usepackage{float}\n\n\\usepackage{stmaryrd}\n\\usepackage{mathptmx}% http://ctan.org/pkg/mathptmx\n\\usepackage{times}\n\\usepackage{amsmath}\n\\usepackage{amsthm}\n\\usepackage{amsfonts}\n\\usepackage{amssymb}\n\n\\theoremstyle{definition}\n\\newtheorem{definition}{Definition}[section]\n\\newtheorem{lemma}{Lemma}[section]\n\\newtheorem{thm}{Theorem}[section]\n\n\n\\title{People who want to parse bigrams and finite state machines\\\\good}\n\\author{Meaghan ``geitje'' Fowlie and Floris ``konijntje'' van Vugt}\n\n\n\\begin{document}\n\n\\maketitle\n\n\\section{Definitions}\n\n\n\n%\\newcommand\\STATES{\\mathcal{S}}\n\\newcommand\\STATES{\\ensuremath{\\mathbb{S}}}\n%\\newcommand\\OPS{\\mathcal{O}}\n\\newcommand\\OPS{\\ensuremath{\\mathbb{O}}}\n%\\newcommand\\BIGR{\\mathcal{B}}\n\\newcommand\\BIGR{\\ensuremath{\\mathbb{B}}}\n\\newcommand\\FSA{\\textsc{FSA}}\n%\\newcommand\\PARSES{\\mathcal{P}}\n\\newcommand\\PARSES{\\ensuremath{\\mathbb{P}}}\n\\newcommand\\SC{\\text{\\textsc{sc}}}\n\\newcommand\\TC{\\text{\\textsc{tc}}}\n\\newcommand\\UC{\\text{\\textsc{uc}}}\n\\newcommand\\BC{\\text{\\textsc{bc}}}\n\\newcommand\\N{\\ensuremath{\\mathbb{N}}}\n\\newcommand\\sg{\\ensuremath{\\Sigma}}\n\\newcommand\\la{\\ensuremath{\\langle}}\n\\newcommand\\ra{\\ensuremath{\\rangle}}\n\\newcommand\\arr{\\ensuremath{\\rightarrow}}\n\\newcommand\\emp{\\ensuremath{\\epsilon}}\n\\newcommand\\op{\\text{\\textsl{op}}}\n\\newcommand\\mg{\\text{\\textsl{mg}}}\n\\newcommand\\cp{\\text{\\textsl{copy}}}\n\\newcommand\\cl{\\text{\\textsl{clear}}}\n\\newcommand\\ed{\\text{\\textsl{end}}}\n\\newcommand\\expr{\\text{\\textsl{expr}}}\n\\newcommand\\Lex{\\text{\\textsl{Lex}}}\n\\newcommand\\fea[1]{\\text{\\texttt{#1}}}\n\\newcommand\\LBOUND{\\ensuremath{\\rtimes}}\n\\newcommand\\RBOUND{\\ensuremath{\\ltimes}}\n\\newcommand\\OURG{\\text{\\textsc{cath}}}\n\n\n\\newcommand\\llb{\\ensuremath{\\llbracket}}\n\\newcommand\\rrb{\\ensuremath{\\rrbracket}}\n\n\n\\newcommand\\der{\\leftarrow}\n%\\newcommand\\der{\\text{:-}}\n\n\nWe define a deterministic finite state automaton over operations and a Markov chain over the alphabet. these two components make up the grammar. \\\\\n\n\\noindent\\textbf{Notation} the size of a set or sequence $A$ is notated $|A|$ or $\\#A$. The \\textit{i}th member of a sequence $A$ is notated $A(i)$ and the last member $A(-1)$. $\\epsilon$ is the empty sequence.\n\n\n\\subsection{The Grammar}\n\\label{sec:grammar}\n\n\n\n\\begin{definition}[Deterministic Finite State Automaton]\n  A deterministic finite state automaton (DFSA) is a five-tuple \n\\[\\la \\sg, Q, q_0, F, \\delta  \\ra  \\]\nwhere:\n\n\\noindent $\\sg$ is an alphabet\\\\\n$Q$ is a finite set (\\textit{states})\\\\\n$q_0\\in Q$ is the designated \\textit{start state}\\\\\n$F\\subseteq Q$ is the set of \\textit{final states}\\\\\n$\\delta: Q\\times \\sg \\arr Q$ is the \\textit{transition function} \n\nA string $s\\in\\sg^*$ is accepted/generated by a DFSA $A$ iff\n$\\exists \\mathbf{q} \\in Q_A^*$ such that $\\mathbf{q}(0)=q_0$, $\\mathbf{q}(-1)\\in F_A$, and $\\forall i<|s|$, $\\delta(\\mathbf{q}(i),s(i))=\\mathbf{q}(i+1)$\n\\label{def:dfsa}\n\\end{definition}\n\n\\begin{definition}\n  We say a triple $(q,e,q')$ where $q,q'\\in Q$ and $e\\in\\sg$ is a \\textit{transition} of an\n  FSA iff $\\delta(q,e)=q'$.\n\\end{definition}\n\nWe define a grammar which generates a language \\textit{surface strings} over an alphabet \\sg~ by application of operations $\\OPS=\\{\\mg,\\cl,\\cp,\\ed\\}$. The choice of operation is governed by a DFSA in which the operations are the emissions of transitions.\n\nIn our operations FSA, the set of all possible states is $\\STATES=$\\{S,NotCL,CL$_S$,CL,F\\} and the alphabet is the set of all operations is $\\OPS=\\{\\mg,\\cl,\\cp,\\ed\\}$. The bigram set or transition set, is $\\BIGR\\subseteq\\sg^*$.\n\n\n\\begin{definition}[Operations FSA]\n  The operations FSA is a deterministic finite state automaton over states \\STATES~ and alphabet \\OPS.\n\\end{definition}\n\n\\begin{definition}[Transition Probabilities]\n   \n  A probability assignment $\\phi$ is a function from transitions of the operations FSA to [0,1] such that\n\n$$\\forall q\\in \\STATES,~~\\sum_{e\\in\\OPS,q'\\in \\STATES} \\phi(q,e,q') = 1 $$\n\n\\end{definition}\n\n\\begin{definition}[Markov Chain]\n  A Markov chain is a 4-tuple $\\la \\sg, S, B, \\phi  \\ra $ where \n\n\\sg~ is a finite alphabet of symbols, \n\n$S\\subseteq \\sg$ is a set of start categories,\n \n$B\\subseteq \\sg\\times\\sg$ is a set of transitions between members of \\sg, and\n\n$\\phi: \\sg \\times \\sg \\arr [0,1]$ is a probability distribution over transitions such that\n\n$$\\forall a\\in \\sg,~~\\sum_{b\\in\\sg} \\phi(a,b) = 1 $$\n\n\nA sequence $s$ is accepted/generated by the chain iff $s$ is a sequence of alphabet items such that $s(0) \\in S$ and $\\forall i<|s|$, $\\phi(s(i),s(i+1))>0$ \n\n\\end{definition}\n\n\\begin{definition}[route]\n  A \\emph{route} is a route through the $\\FSA$ of say $n$ steps, defined as a tuple $(Q,E)$ where $Q$ is the sequence of states visited, i.e.\n%  $Q=\\la q_i\\in\\STATES|i<n\\ra$, and $E$ is the sequence of emissions.\n $E=\\la e_i\\in\\OPS|i<n-1\\ra$ such that $\\forall i<n,~ \\delta(q_i,e_i)=q_{i+1}$.\n\n\\end{definition}\n\n  I think we need a homomorphism of the sort in Koller's paper to define the relationship between the operations and the surface strings?\n\n\n\\begin{definition}[\\OURG]\n  \\OURG = \\la \\OPS,\\BIGR\\ra~ where\n\n  $\\OPS = \\la \\{\\mg,\\cp,\\cl,\\ed\\}, \\{S,NotCL,CL_S,CL,F\\}, S, \\{F\\}, \\phi_\\OPS\\ra$ is the DFSA given in Figure \\ref{fig:ops}\n\n  $\\BIGR = \\la \\sg\\cup\\{{\\LBOUND}\\}, \\{\\LBOUND\\}, B, \\phi_\\BIGR \\ra$ is a Markov Chain  for some alphabet \\sg~and a left boundary marker \\LBOUND.\n  \n\\end{definition}\n\n\n\\begin{figure}[H]\n  \\centering\n  \\includegraphics[width=5in]{ops.png}\n  \\caption{\\OPS}\n  \\label{fig:ops}\n\\end{figure}\n\n  \n\\begin{definition}[expression]\n  An expression is anything that can participate in an operation. For \\OURG:\n\n  \\expr = $(\\LBOUND\\sg^*\\times\\sg^*) \\cup \\sg^*$\n  \n\\end{definition}\n\n\\begin{definition}[Operation]\n\\label{def:ops}\n  Operations are functions from expressions to expressions.\n\n  We have four operations. $O=\\{\\mg,\\cp,\\cl,\\ed\\}$ \n\n  \\cp, \\cl~are  functions between (surface string, buffer) pairs, i.e.\n\n  $\\cp,\\cl : \\LBOUND\\sg^* \\times \\sg^* \\arr  \\LBOUND\\sg^* \\times \\sg^*$\n\n  \\begin{description}\n  \\item[\\cp] $\\cp(s,b) = (sb,bb)$ \\hfill \\cp~copies the buffer and appends it to both the string and the buffer\n\n \\item[\\cl] $\\cl(s,b) = (s,\\epsilon)$ \\hfill \\cl~clears the buffer\n\n\n  \\end{description}\n\n\n\n  \\begin{description}\n  \\item[\\ed]   \\ed~maps from string, buffer pairs to strings, i.e.\n\n  $\\ed : \\LBOUND\\sg^* \\times \\sg^* \\arr  \\sg^*$\n\n  $\\ed(\\LBOUND s,b) = s$ \\hfill \\ed~returns the string\n\n  \n  \\end{description}\n\n%   Given a bigram set \\BIGR, we define \\mg~as a function from (string, buffer, $a\\in\\sg$) triples to (string, buffer) pairs, i.e.\n\n%   $mg : (\\sg^* \\times \\sg^*) \\times \\sg \\arr  \\sg^* \\times \\sg^*$\n\n\n%   \\begin{description}\n%   \\item[\\mg] $\\mg((s,b),a) = \n%     \\begin{cases}\n%       (s^\\frown a, b^\\frown a) & \\text{ if } (s(-1),a)\\in\\BIGR\\\\\n%       \\text{undefined} & \\text{otherwise}\n%     \\end{cases}\n% $\n\n   \\begin{description}\n\n   \\item[\\mg] \\mg~is a probabilistic function $\\mg:\\LBOUND\\sg^*\\times\\sg^*\\arr \\LBOUND\\sg^*\\times\\sg^*$, which means actually $\\mg:\\LBOUND\\sg^*\\times\\sg^* \\arr (\\LBOUND\\sg^*\\times\\sg^* \\arr [0,1])$.\n     \\mg~adds a symbol to the end of both the string and the buffer if the transition is legal according to \\BIGR.\n     \n     The subdistribution, call it $\\delta$, from $\\LBOUND\\sg^*\\times\\sg^*$ to [0,1], is defined as follows, where $\\phi_\\BIGR$ is the probability function of \\BIGR:\n\nfor $(s,b)\\in\\LBOUND\\sg^*\\times\\sg^*$, $\\mg(s,b) = \\delta_{s,b}$ s.t.\n     \n$  \\delta_{s,b}(s',b') =\n\\begin{cases}\n  \\phi_\\BIGR(s'(-2),s'(-1)) & \\text{ if } \\exists a\\in\\sg (s' = sa)\\\\\n  0 & \\text{otherwise}\n\\end{cases}\n$\n\nWhen $a\\in\\sg$ is chosen, we call the operation a \\textit{merge of a}.\n\n\n  \\end{description}\n\n\\end{definition}\n\nInterpretation function of derivations. Defined recursively.\n\n$I(ops,bis,t) = \n\\begin{cases}\n  \\llb t\\rrb & \\text{ if } ops=bis=\\emp\\\\\n  I(ops[1:],bis[1:],\\llb ops[0]\\rrb(\\llb t\\rrb,bis[0])) & \\text{ if } ops[0]=\\mg~ \\&~ bis\\neq\\emp\\\\\n  I(ops[1:],bis,\\llb ops[0]\\rrb(\\llb t\\rrb)) & \\text{ if } ops[0]\\neq\\mg\\\\\n  \\text{undefined} & \\text{ otherwise}\n\\end{cases}\n$\n\nFor strings:\n\n\\llb\\mg\\rrb = \\mg~as defined in definition \\ref{def:ops}\n\n\\llb\\cp\\rrb = \\cp~as defined in definition \\ref{def:ops}\n\n\\llb\\cl\\rrb = \\cl~as defined in definition \\ref{def:ops}\n\n\\llb\\ed\\rrb = \\ed~as defined in definition \\ref{def:ops}\n\n\\llb start \\rrb = (\\LBOUND,\\emp)\n\n\n$s\\in L(\\OURG)$ iff $\\exists ops\\in O^*$ that is accepted by \\OPS\nand $\\exists bis\\in \\sg^*$ that is accepted by \\BIGR \nsuch that\n$I(ops,bis,start) = s$\\\\\n\nMCFG:\\\\\n\n$  \\begin{array}{r  r c l l}\n    \\cl & C(s,x) &\\der& T(s,b,x)\\\\\n    \\cp & T(sb,bb,x) &\\der& T(s,b,x)\\\\\n    \\mg & T(sa,ba,a) &\\der& T(s,b,c), a & \\forall (c,a)\\in\\BIGR\\\\\n    \\mg & T(sa,a,a) &\\der& C(s,c), a & \\forall (c,a)\\in\\BIGR\\\\\n    \\ed & S(s) &\\der& T(s,b,x)\\\\\n    \\text{\\textsl{start}} & C(\\emp,\\LBOUND) &\\der&\\\\\n\n   \\end{array}$\\\\\\\\\n\nNotice that the name and RHS are enough to uniquely identify the\nactual rule. So we can interpret the derivation tree output from I in\nthe MCFG too:\n\n\\cl(T(s,b,x)) = C(s,x)\\\\\n\\cp(T(s,b,x)) = T(sb,bb,x)\\\\\n\\ed(T(s,b,x)) = S(s)\\\\\n\\mg(T(s,b,c),a) = T(sa,ba,a) $\\forall (c,a)\\in\\BIGR$\\\\\n\\mg(C(s,c),a) = T(sa,a,a) $\\forall (c,a)\\in\\BIGR$\\\\\n\n\\llb start \\rrb = C(\\emp,\\LBOUND)\\\\\n\\llb\\cl\\rrb = the rule named \\cl~ in the MCFG above\\\\\n\\llb\\cp\\rrb = the rule named \\cp~ in the MCFG above\\\\\n\\llb\\mg\\rrb(t,a) = $\n\\begin{cases}\n  T(sa,ba,a) & \\text{ if } t = T(s,b,c) \\exists c\\in\\sg\\\\\n  T(sa,a,a) & \\text{ if } t = C(s,c) \\exists c\\in\\sg\\\\\n\\end{cases}\n$\\\\\n\nThis isn't right yet, or these are two different ways of saying it.\n\n\\begin{definition}\n  A derivation step is a pair of expressions such that the second is the result of applying one operation to the first.\n\n  Specifically,  $(e_1,e_2)$ is a derivation step iff $\\exists \\op\\in O$ such that $e_2=\\op(e_1)$ or $(\\op(e_1))(e_2)>0$. The former case is for \\cp, \\cl, and \\ed, and the latter for \\mg.\n\n  For $e_i\\in\\expr$  we write $e_1 \\Rightarrow e_2$ if $(e_1,e_2)$ is a derivation step and say that $e_2$ is \\textit{derived from} $e_1$.\n\n  If there is a series of $n$ derivation steps $e_0\\Rightarrow e_1 \\Rightarrow \\dots \\Rightarrow e_n$, then we write $e_0\\Rightarrow^n e_n$, or, in the general case, $e_0\\Rightarrow^* e_n$, and say  $e_n$ is \\textit{derived from} $e_0$.\n\n  If $e_0\\Rightarrow^n s$, a sequence of operations $o_1,o_2,...,o_{n-1}$ such that $\\forall i<n-1, e_{i+1}=o_i(e_i)$ or $(\\op(e_1))(e_2)>0$ is an \\textit{operation string of s}. \n\n%  If there is a finite series of derivation steps $(e_0,e_1),(e_1,e_2)...,(e_{n-1},e_n)$ where for each consecutive pair of steps the second element of the first step is the same as the first element of the second step, then we write $e_0\\Rightarrow^* e_n$ and say  $e_n$ is \\textit{derived from} $e_0$. \n\n\\end{definition}\n\n\\begin{definition}[Language defined by \\OURG]\n$L(\\OPS,\\BIGR)\\subseteq\\sg^*$ is the language defined by the grammar (\\OPS,\\BIGR) defined as follows:   $s\\in L(\\OPS,\\BIGR)$ iff $(\\LBOUND,\\epsilon)\\Rightarrow^*s$ and there is an operation string of $s$ that is accepted by \\OPS~with probability greater than 0.\n\\end{definition}\n\n\n\\subsection{Minimalist Grammars and PMCFGs}\n\\label{sec:minimalist-grammars}\n\n\nWe can define a parallel multiple context free grammar that is equivalent to our grammar. We add a third element to the (string,buffer) pair to track the most recent merge. The quantifications are short for the full set of rules that satisfy the predicate. The start category is, ironically, \\ed.\nI think this is a (3,1)-PMCFG. (In terms of the class, is there a problem with the deletion of the buffer? What about the fact that in \\cp, $b$ occurs three times, not just 2?)\n\n\\begin{definition}[PMCFG]\\\n\n  \\noindent$NT = \\mg,\\cp,\\cl,\\ed$\\\\\n  $T = \\sg$\\\\\n  Start category: \\ed\\\\\n  Variables: $s,b,x$\\\\\n  Metavariables: $a,c$ over \\sg\\\\\n  \n$  \\begin{array}{r c l l}\n    \\cl(s,x) &\\der& \\mg(s,b,x)\\\\\n    \\cl(s,x) &\\der& \\cp(s,b,x)\\\\\n    \\cp(sb,bb,x) &\\der& \\mg(s,b,x)\\\\\n    \\cp(sb,bb,x) &\\der& \\cp(s,b,x)\\\\\n    \\mg(sa,ba,a) &\\der& \\mg(s,b,c) & \\forall (c,a)\\in\\BIGR\\\\\n    \\mg(sa,ba,a) &\\der& \\cp(s,b,c)&\\forall (c,a)\\in\\BIGR\\\\\n    \\mg(sa,a,a) &\\der& \\cl(s,c) &\\forall (c,a)\\in\\BIGR\\\\\n    \\mg(a,a,a) &\\der&  &\\forall(\\LBOUND,a)\\in\\BIGR\\\\\n    \\ed(s) &\\der& \\mg(s,b,x)\\\\\n    \\ed(s) &\\der& \\cp(s,b,x)\\\\    \n   \\end{array}$\\\\\\\\\n\n   If we're working with right boundary symbols, the two \\ed~rules can be replaced by\n   \n   $\\ed(s)\\der\\mg(s,b,a) ~~~~~\\forall a\\in\\sg$ s.t. $(a,\\RBOUND)\\in\\BIGR$\n   \n   $\\ed(s)\\der\\cp(s,b,a) ~~~\\forall a\\in\\sg$ s.t. $(a,\\RBOUND)\\in\\BIGR$\n\\label{def:pmcfg}\n \\end{definition}\n\n\n \\begin{thm}\n   The PMCFG (call it P) in definition \\label{def:pmcfg} is weakly equivalent to the two-part grammar in definition \\label{def:g}.\n \\end{thm}\n\n \\begin{proof}\n   We proceed by induction on the depth of the derivation tree. of zo.\n\n   \\begin{enumerate}\n   \\item a dt of depth 1 would have to be $\\ed(a)$ for some $a\\in\\sg$ since \\ed is the start symbol. This is impossible since neither \\ed rule is an axiom.\n   \\item a dt of depth 2 could be \\ed(\\cp(a)) or \\ed(\\mg(a)) for some a. The former is impossible since no \\cp rule is an axiom. However, \\mg has a set of axioms: one for each a with $(\\LBOUND,a)\\in\\BIGR$. \\mg(a,a,a) is an RHS for \\ed, so $a\\in L(P)$ iff $(\\LBOUND,a)\\in\\BIGR$.\n\n     Conversely, $a\\in L(\\OURG)$ whenever $(\\LBOUND,a)\\in\\BIGR$ since (S,\\mg,NotCL) and (NotCL,\\ed,F) $\\in \\OPS$, which generates \\ed(\\mg(\\LBOUND,\\emp)), \\mg(\\LBOUND,\\emp) = $\\delta_{\\LBOUND,\\emp}$ and  $\\delta_{\\LBOUND,\\emp}(\\LBOUND a,a) = \\phi((\\LBOUND,a))$\n\n     \n   \\end{enumerate}\n\n   \n \\end{proof}\n\n \n\\subsubsection{MGs}\n\\label{sec:mgs}\n\n\n\nWe define some weakly and strongly equivalent MGs because that seems smart.\n\nThis MG doesn't work quite like ours because you can clear the buffer pretty much whenever.\n\n\\begin{definition}[Minimalist Grammar]\\ \n\n  \\begin{description}\n  \\item[Features] $F=\\{\\fea{=a, a} | a\\in \\sg \\}\\cup\\{S,F\\}$\n    % \\begin{itemize}\n    % \\item Bare features $BF=\\sg\\cup\\{S\\}$, $S$ a designated start feature\n    % \\item $F=BF\\cup\\{\\fea{=a} | a\\in sg\\}$\n    % \\end{itemize}\n\n  \\item[\\Lex]\n    \\begin{itemize}\n    \\item $\\forall (a,b) \\in \\BIGR$ we have\n      $b::\\fea{=ab} \\in \\Lex$ \n      \n    \\item and $b::\\fea{=a}\\in\\Lex$ OR $\\forall (a,b),(b,{]})\\in\\BIGR, b::\\fea{=aF}\\in\\Lex$\n    \\item $\\forall ({[},a)\\in\\BIGR$ we have $a::\\fea{=Sa}$\n    \\item $\\emp::\\fea{S}\\in\\Lex$\n    \\end{itemize}\n\n  \\item[\\mg] $\\mg( a::X, (s,b)::\\fea{=X}\\beta) = (sa,ba)::\\beta$\n  \\item[\\cp] $\\cp((s,b)::\\alpha) = (sb,bb)::\\alpha$\n  \\item[\\cl] $\\cl((s,b)::\\alpha) = (s,\\epsilon)::\\alpha$ ~~~~if $b\\neq\\emp$\n  \\item[\\ed] $\\ed((s,b)::\\fea{F}) = s$\n\n\n  \\end{description}\n\\end{definition}\n\n\\Tree[.\\ed\\\\aabab [.\\cp\\\\(aabab,abab)::\\fea{F} [.\\mg\\\\(aab,ab)::\\fea{F} [.\\mg\\\\(aa,a)::\\fea{a} [.\\cl\\\\(a,\\emp)::\\fea{a}  [.\\mg\\\\(a,a)::\\fea{a} \\emp::\\fea{S} a::\\fea{=Sa} ]] a::\\fea{=aa} ] b::\\fea{=aF} ]]]\\\\\n\n\n% \\begin{definition}[Minimalist Grammar 2]\\ \n\n%   \\begin{description}\n%   \\item[Features] $F=\\{\\fea{=a,a} | a\\in \\sg \\} \\cup\\{\\fea{S,F,+clear,-clear}\\}$\n%     % \\begin{itemize}\n%     % \\item Bare features $BF=\\sg\\cup\\{S\\}$, $S$ a designated start feature\n%     % \\item $F=BF\\cup\\{\\fea{=a} | a\\in sg\\}$\n%     % \\end{itemize}\n\n%   \\item[\\Lex]\n%     \\begin{itemize}\n%     \\item $\\forall (a,b) \\in \\BIGR$ we have\n%       $b::\\fea{=ab} \\in \\Lex$\n%     \\item $\\forall (a,b),(b,{]})\\in\\BIGR$ (OR $\\forall (a,b)$) we have $b::\\fea{=aF}\\in\\Lex$\n%     \\item $\\forall ({[},a)\\in\\BIGR$ we have $a::\\fea{=Sa}\\in\\Lex$\n%     \\item $(\\emp::\\fea{S},\\emp::\\fea{-clear})\\in\\Lex$\n%     \\end{itemize}\n\n%   \\item[\\mg] $\\mg(a::\\fea{X},(s::\\fea{=X}\\beta,b::\\fea{\\ensuremath{\\alpha}clear})) = (sa::\\beta,ab::\\fea{\\ensuremath{\\alpha}clear})$\n%   \\item[\\cp] $\\cp((s::\\beta,b::\\pm\\fea{clear}) = (sb::\\beta, bb::\\fea{-clear})$\\hfill if $b\\neq\\emp$\n%   \\item[\\cl] $\\cl(s::\\beta,b::\\fea{-clear}) = (s::\\beta,\\emp::\\fea{+clear})$\\hfill if $b\\neq\\emp$\n%   \\item[\\ed] $\\ed(s::\\fea{F},b::\\fea{-clear}) = s$\n\n\n%   \\end{description}\n% \\end{definition}\n\n% \\Tree[.\\ed\\\\aabab [.\\cp\\\\aabab::\\fea{F},abab::\\fea{-cl} [.\\mg\\\\aab::\\fea{F},ab::\\fea{+cl} [.\\mg\\\\aa::\\fea{a},a::\\fea{+cl} [.\\cl\\\\a::\\fea{a},\\emp::\\fea{+cl}  [.\\mg\\\\a::\\fea{a},a::\\fea{-cl} \\emp::\\fea{S},\\emp::\\fea{-cl} a::\\fea{=Sa} ]] a::\\fea{=aa} ] b::\\fea{=aF} ]]]\n\n\n\n\n\n\\subsubsection{The right one}\n\\label{sec:right-one}\n\nWe designed the grammar so that we never copy or clear vacuously. This means that we only copy or clear if there is something in the buffer to copy or clear, and also that we only clear if that act of clearing will define the start of a copy. The former is accomplished by adding a state for when the buffer is empty, from which we can only Merge. The latter is done by adding a new state that we move to when we clear, and from which we can't clear again, nor can we end without first actually copying. When we put these strategies together, we have five states. The start state has no buffer so we can only Merge. From there we go to NotCL, because we have not recently cleared. From here we can do anything, but if we clear, we move to CL$_S$ in which we have cleared (so we can't clear or end) but we also have no buffer so we can't copy either. We Merge and move to CL from which we can't clear or end. If we copy, we move back to NotCL.\n\nIn other words, our states are \\fea{F} plus the full complement of $\\pm$buffer, $\\pm$cleared:\n\n\\begin{table}[H]\n  \\centering\n  \\begin{tabular}[H]{c|c  c}\n  & \\fea{+clear} &  \\fea{-clear}\\\\\n\\hline\n \\fea{+buffer}& CL  & NotCL\\\\\n \\fea{-buffer}& CL$_S$ & S\\\\\n\\end{tabular}\n\n\\caption{Features and equivalent states}\n\\label{tab:features-states}\n\\end{table}\nWe design the MG with features on the string and the buffer. The features on the string model the bigrams \\BIGR~and the ones on the buffer model the states \\STATES.\n\n\n\n\\begin{definition}[Minimalist Grammar 2]\\ \n\n  \\begin{description}\n  \\item[Features] $F=\\{\\fea{=a,a} | a\\in \\sg \\} \\cup\\{\\fea{S,F,+clear,-clear,+buf,-buf}\\}$\n    % \\begin{itemize}\n    % \\item Bare features $BF=\\sg\\cup\\{S\\}$, $S$ a designated start feature\n    % \\item $F=BF\\cup\\{\\fea{=a} | a\\in sg\\}$\n    % \\end{itemize}\n\n  \\item[\\Lex]\n    \\begin{itemize}\n    \\item $\\forall (a,b) \\in \\BIGR$ we have\n      $b::\\fea{=ab} \\in \\Lex$\n    \\item $\\forall (a,b),(b,\\RBOUND)\\in\\BIGR$ (OR $\\forall (a,b)$) we have $b::\\fea{=aF}\\in\\Lex$\n    \\item $\\forall (\\LBOUND,a)\\in\\BIGR$ we have $a::\\fea{=Sa}\\in\\Lex$\n    \\item $(\\emp::\\fea{S},\\emp::\\fea{-clear,-buf})\\in\\Lex$\n    \\end{itemize}\n\n  \\item[\\mg] $\\mg(a::\\fea{X},(s::\\fea{=X}\\beta,b::\\fea{\\ensuremath{\\alpha}clear,\\ensuremath{\\gamma}buf})) = (sa::\\beta,ab::\\fea{\\ensuremath{\\alpha}clear,+buf})$\n  \\item[\\cp] $\\cp((s::\\beta,b::\\pm\\fea{clear,+buf}) = (sb::\\beta, bb::\\fea{-clear,+buf})$\n  \\item[\\cl] $\\cl(s::\\beta,b::\\fea{-clear,+buf}) = (s::\\beta,\\emp::\\fea{+clear,-buf})$\n  \\item[\\ed] $\\ed(s::\\fea{F},b::\\fea{-clear},\\fea{+buf}) = s$\n\n\n  \\end{description}\n\\end{definition}\n\n\\begin{figure}[H]\n  \\Tree[.\\ed\\\\aabab [.\\cp\\\\aabab::\\fea{F},abab::\\fea{-cl,+buf}\n  [.\\mg\\\\aab::\\fea{F},ab::\\fea{+cl,+buf}\n  [.\\mg\\\\aa::\\fea{a},a::\\fea{+cl,+buf}\n  [.\\cl\\\\a::\\fea{a},\\emp::\\fea{+cl,-buf}\n  [.\\mg\\\\a::\\fea{a},a::\\fea{-cl,+buf}\n  \\emp::\\fea{S},\\emp::\\fea{-cl,-buf} a::\\fea{=Sa} ]] a::\\fea{=aa} ]\n  b::\\fea{=aF} ]]]\n  \\Tree[.\\ed\\\\aabab [.\\cp\\\\aabab,abab\n  [.\\mg\\\\aab,ab\n  [.\\mg\\\\aa,a\n  [.\\cl\\\\a,\\emp~\n  [.\\mg\\\\a,a\n   a ]] a ]\n  b ]]]\n  \n  \\caption{Example parallel MG and our grammar derivations}\n  \\label{fig:mg-der}\n\\end{figure}\n\n\\begin{thm}\n  Our grammar, which needs a name, is strongly equivalent to MG2.\n\\end{thm}\n\n\\begin{proof}[Proof]\n  Every transition in the operations FSA has an equivalent MG rule and vice versa. Every transition in \\BIGR is represented as a Merge step of a lexical item.\n\n  \\begin{enumerate}\n  \\item Operations FSA\n    We use the feature equivalents of the state names. Note there are nine transitions in the FSA including the start state definition, and there are nine featural configurations in the MG in which an operation is defined, modulo the bigram features \\fea{a,=a} etc. All nine are covered here.\n\nIn the table below we show the parallel FSA transitions and MG rules. In the MG rules we include only the relevant features for clarity.\n\n    \\begin{tabular}[H]{p{0.5\\textwidth} | p{0.5\\textwidth}}\n      Transition & MG\\\\\n      \\hline\n      $q_o=(\\fea{-buf,-clear})$ & The only lexical item that does not select is the start item (\\emp::\\fea{S},\\emp\\fea{-buf-clear}). Merge is to the left so this will be the first word of the string. \\\\      \\hline\n      (\\fea{-buf-clear},\\mg,\\fea{+buf-clear}) is the only transition from \\fea{-buf,-clear}&Only \\mg~ is defined for expressions with feature \\fea{-buf}. \\mg(\\fea{-buf,-clear}) = \\fea{+buf,-clear} \\\\\n      \\hline\n      (\\fea{-buf+clear},\\mg,\\fea{+buf+clear}) is the only transition from \\fea{-buf,+clear}&Only \\mg~ is defined for expressions with feature \\fea{-buf}. \\mg(\\fea{-buf,+clear}) = \\fea{+buf,+clear} \\\\\n      \\hline\n      (\\fea{+buf-clear},\\mg,\\fea{+buf-clear}) & \\mg(\\fea{+buf,-clear})=\\fea{+buf,-clear}\\\\      \\hline\n      (\\fea{+buf-clear},\\cp,\\fea{+buf-clear}) & \\cp(\\fea{+buf,-clear})=\\fea{+buf,-clear}\\\\      \\hline\n      (\\fea{+buf-clear},\\cl,\\fea{-buf+clear}) & \\cl(\\fea{+buf,-clear})=\\fea{-buf,+clear}\\\\      \\hline\n      (\\fea{+buf-clear},\\ed,\\fea{F}) & \\ed(s::\\fea{F},b::\\fea{+buf,-clear})=s\\\\      \\hline\n      (\\fea{+buf+clear},\\mg,\\fea{+buf+clear}) & \\mg(\\fea{+buf,+clear})=\\fea{+buf,+clear}\\\\      \\hline\n      (\\fea{+buf+clear},\\mg,\\fea{+buf-clear}) & \\cp(\\fea{+buf,+clear})=\\fea{+buf,-clear}\\\\\n\n\n    \\end{tabular}\n    \n  \\item \\BIGR: \n    \\begin{itemize}\n    \\item each bigram $(a,b)\\in\\BIGR$ such that $a,b\\in\\sg$ has a\n      lexical item in the MG b::\\fea{=ab}.\n    \\item each bigram $({[},a)\\in\\BIGR$ has a lexical item in the MG a::\\fea{=Sa}. There is an empty start item with feature \\fea{S}. It is the only LI with category \\fea{S}.\n    \\item If we want to include final bigrams, $(a,{]})$, then we include in the MG LIs a::\\fea{=bF} for each $(b,a)\\in\\BIGR$. Otherwise we include such LIs for all bigrams. This is the equivalent of some or all states of the Markov chain being final states.\n    \\end{itemize}\nOnly Merge and End interact in any way with the features that come with the ``string''. These features are the features that are based on the lexical items and \\fea{S} and \\fea{F}. Merge only allows items to join the derivation if they create legal bigrams and End only allows the derivation to end if we have a final category.\n\n  \\end{enumerate}\n\\end{proof}\n\nAs to whether MG3 is equivalent to a parallel MG, we can begin by simplifying the grammar so that we don't care whether or not we Copy or Clear vacuously. The resulting grammar is clearly weakly equivalent to this one: the only difference is that sometimes operations that do nothing to either the string or the buffer are performed. \\ed might look a little worrying, but it is fine too since \\fea{F} is the final category, and the start LI has feature \\fea{S}. Therefore we don't add an empty string to the yield. This is MG1 above. \n\nMG1 is featurally normal for an MG: no weird features like \\fea{-clear}. Merge is also defined exactly the same as in an MG. I've simplified the definition to exclude cases that never arise because of the simplicity of the lexicon, but this is unnecessary. \n\nThe difference is that we build two strings in parallel, the string and the buffer. The buffer can also be independently emptied. Unlike in a normal MG, these operations are not triggered by features, but rather occur freely. We could add in licensing features to keep everything feature-driven. If we want a model in which whether \\mg, \\cp, or \\cl~occurs depends on what word was most recently merged, we could add features like this. However, we currently want a model in which copy and clear are independent of words.\n\n\n\n\\subsubsection{Copy-move}\n\\label{sec:copy-move}\n\n\\newcommand\\bcp{\\text{\\textsl{begCP}}}\n\\newcommand\\ecp{\\text{\\textsl{endCP}}}\n\n\nEd also wanted to be able to basically copy-move. We can do this by replacing \\cl~with two operations: \\bcp, which opens the buffer, and \\ecp, which stops writing to the buffer. When the buffer is existent and open we Merge and Copy to it. When it is existent closed we can Copy it. \n\n\\begin{definition}[Minimalist Grammar 3]\\ \n\n\n  \\begin{description}\n  \\item[Features] $F=\\{\\fea{=a,a} | a\\in \\sg \\}\\cup\\{\\fea{S,F,-copy,+copy}\\}$\n    % \\begin{itemize}\n    % \\item Bare features $BF=\\sg\\cup\\{S\\}$, $S$ a designated start feature\n    % \\item $F=BF\\cup\\{\\fea{=a} | a\\in sg\\}$\n    % \\end{itemize}\n\n  \\item[\\Lex]\n    \\begin{itemize}\n    \\item $\\forall (a,b) \\in \\BIGR$ we have\n      $a::\\fea{a}, b::\\fea{=ab} \\in \\Lex$\n    \\item $\\forall (a,b),(b,{]})\\in\\BIGR$ (OR $\\forall (a,b)$) we have $b::\\fea{=aF}\\in\\Lex$\n    \\item $\\forall ({[},a)\\in\\BIGR$ we have $a::\\fea{=Sa}$\n    \\item $\\emp::\\fea{S}\\in\\Lex$\n    \\end{itemize}\n\n  \\item[Merge simple] $\\mg( a::\\fea{X}, s::\\fea{=X}\\beta) = sa::\\beta$\n  \\item[Merge and build a copy] $\\mg( a::\\fea{X}, (s::\\fea{=X}\\beta,b::\\fea{+copy})) = (sa::\\beta,ba::\\fea{+copy})$\n  \\item[Merge and hold a copy] $\\mg( a::\\fea{X}, (s::\\fea{=X}\\beta,b::\\fea{-copy})) = (sa::\\beta,b::\\fea{-copy})$\n  \\item[Begin building a copy] $\\bcp(s::\\beta) = (s::\\beta,\\emp::\\fea{+copy})$\n  \\item[Store the copy] $\\ecp(s::\\beta,b::\\fea{+copy}) = (s::\\beta,b::\\fea{-copy})$\n\n\n  \\item[Copy and keep building the copy] $\\cp((s::\\beta,b::\\fea{+copy}) = (sb::\\beta, bb::\\fea{+copy})$\n  \\item[Copy and end copy] $\\cp((s::\\beta,b::\\fea{-copy}) = sb::\\beta$\n\n  \\item[\\ed] $\\ed(s::\\fea{F}) = s$\n\n\n  \\end{description}\n\n\n\\end{definition}\n\n{\\small\n\\Tree[.\\ed\\\\aabab [.\\cp\\\\aabab::\\fea{F}~ [.\\ecp\\\\aab::\\fea{F},ab::\\fea{-copy}  [.\\mg\\\\aab::\\fea{F},ab::\\fea{+copy} [.\\mg\\\\aa::\\fea{a},a::\\fea{+copy} [.\\bcp\\\\a::\\fea{a},\\emp::\\fea{+copy}  [.\\mg\\\\a::\\fea{a} \\emp::\\fea{S} a::\\fea{=Sa} ]] a::\\fea{=aa} ] b::\\fea{=aF} ]]]]\n\\Tree[.\\ed\\\\aabcab [.\\cp\\\\aabcab::\\fea{F} [.\\mg\\\\aabc::\\fea{F},ab::\\fea{-copy}  [.\\ecp\\\\aab::\\fea{b},ab::\\fea{-copy}  [.\\mg\\\\aab::\\fea{b},ab::\\fea{+copy} [.\\mg\\\\aa::\\fea{a},a::\\fea{+copy} [.\\bcp\\\\a::\\fea{a},\\emp::\\fea{+copy}  [.\\mg\\\\a::\\fea{a} \\emp::\\fea{S} a::\\fea{=Sa} ]] a::\\fea{=aa} ] b::\\fea{=ab} ]]  c::\\fea{=bF} ] ]]\n}\n\n\\includegraphics[width=5in]{ops_distance.png}\n\n\n\n% \\begin{definition}[Trying to make a prolog notation MCSG]\n% This is the intuition, but it's not right. We need to include the bigram rules in the category names, thus multiplying the rules all the hell.\n\n%   \\begin{eqnarray*}\n%   T(\\emp,\\emp) &\\der&\\\\ \n%   L(a) &\\der& a ~~~~~~~~~~~~~~~~~~~\\forall a\\in\\sg\\\\\n%   T(xa,ya) &\\der& T(x,y)~ L(a)  \\\\\n%   T(xy,yy) &\\der& T(x,y)\\\\\n%   T(x,\\emp) &\\der& T(x,y)\\\\\n%   S(x) &\\der& T(x,y)\\\\\n%   \\end{eqnarray*}\n\n% Assuming (a,b) and (b,a) are legal bigrams we get:\n\n%   \\begin{eqnarray*}\n%   T(\\emp,\\emp) &\\der&\\\\ \n%   A(a) &\\der& a \\\\\n%   TA(xz,yz) &\\der& T(x,y)~ A(z)  \\\\\n%   TA(xz,yz) &\\der& TA(x,y)~ A(z)  \\\\\n%   TA(xz,yz) &\\der& TB(x,y)~ A(z)  \\\\\n%   TA(xy,yy) &\\der& TA(x,y)\\\\\n%   TA(x,\\emp) &\\der& TA(x,y)\\\\\n%   S(x) &\\der& TA(x,y)\\\\\n%     \\\\\n%   B(b) &\\der& b\\\\\n%   TB(xz,yz) &\\der& T(x,y)~ B(z)  \\\\\n%   TB(xz,yz) &\\der& TA(x,y)~ B(z)  \\\\\n%   TB(xz,yz) &\\der& TB(x,y)~ B(z)  \\\\\n%   TB(xy,yy) &\\der& TB(x,y)\\\\\n%   TB(x,\\emp) &\\der& TB(x,y)\\\\\n%   S(x) &\\der& TB(x,y)\\\\\n% \\\\\n% etc\\\\\n%   \\end{eqnarray*}\n\n\n\n% \\end{definition}\n\n\n\n\\subsection{Parser}\n\\label{sec:parser}\n\n\n\n\\begin{definition}[parse]\n\nA \\textit{parse} for surface string $s$ is a pair $(b,r)$ where $b\\in\\sg^*$, and $r=(Q,E)$ is a route through the operations $\\FSA$ such that there is a derivation of length $|Q|$ from\n $(\\epsilon,\\epsilon)$ to  $s$ where the $i$th derivation step is an application of $E(i)$ and the $i$th \\mg~in $E$ is a merge of $b(i)$.\n\nThe set of all parses of sentence $s$ is written $\\PARSES(s)$\n\\end{definition}\n\n\\noindent We want some counts from a parse for the learner:\n\n\\begin{definition}[state counts]\n  Given a route $(Q,E)$, we define $\\SC_Q : \\STATES \\rightarrow\\N$ as follows: $\\SC_Q(q) = \\#\\{ i | Q(i)=q \\}$\n\\end{definition}\n\n\n\\begin{definition}[transition counts]\n  Given a route $(Q,E)$, we define $\\TC_{Q,E} : \\FSA \\rightarrow\\N$ as follows: $\\TC_{Q,E}(q,e,q') = \\#\\{ i<n | Q(i)=q,E(i)=e,Q({i+1})=q'\\}$\n\\end{definition}\n\n\\begin{definition}[unigram counts]\n  Given a sequence of words $b\\in\\sg^*$, we define a function $\\UC_b : \\sg \\rightarrow\\N$ as follows: $\\UC_b(w) = \\#\\{ i | b(i) = w \\}$\n\\end{definition}\n\n\n\\begin{definition}[bigram counts]\n  Given a sequence of words $b\\in\\sg^*$, we define a function $\\BC_{b} : \\BIGR \\rightarrow\\N$ as follows: $\\BC_b(a,b) = \\#\\{ i | b(i)=a \\& b(i+1) = b \\}$\n\\end{definition}\n\n\n\\section{Likelihoods}\n\n\\begin{definition}[rule probability assignment]\nA rule probability assignment is an assignment of a probability to each transition of the operations FSA, i.e. $p(q,e,q')$, such that $\\sum_{e,q'}p(q,e,q')=1$, and to each bigram/transition in the Markov chain.\n\\end{definition}\n\n\n\\begin{definition}[likelihoods]\nA rule probability assignment can then be extended in a straightforward way to yield. \n\nThe probability of a parse $(b,(Q,E))$ is the product of the probabilities of its transitions in both the operations FSA and the Markov chain. We take the product because the probability of the parse is the probability of this transition \\textit{and} this transition \\textit{and}... etc\n\n$$p(b,(Q,E)) = \\prod_{i<|s|} p(Q(i),E(i),Q(i+1)) \\prod_{i<|b|} p(b(i),b(i+1))$$\n\n\nThe probability of a sentence is the sum of the probabilities of its parses. We take the sum because the probability of the sentence is the probability of this parse \\textit{or} this parse \\textit{or}... etc\n\n$$p(s) = \\sum_{(b,r)\\in\\PARSES(s)} p(b,r)$$\n\n By extension the probability of a corpus $C$ is the product of the probabilities of the sentences\n\n$$p(C)=\\prod_{s\\in C}p(s)$$\n\\end{definition}\n\nSo our task is given a corpus $C$ to find a probability assignment that maximises $p(C)$. \n\nSince the search space is large, it may only be possible to find a local maximum and not a global maximum.\n\nWe're somewhat unsure how the following achieves this, but it seems to work.\n\n\n\\section{Iterative rule updates}\n\n\nWe want to estimate the likelihood of each rule in a given corpus. For this, we iteratively re-estimate the rule probabilities: given a rule probability assignment, we can re-estimate the probabilities of every parse of a sentence, and then this changes the probabilities that each rule was used.\n\nRoughly speaking, a transition from state $q$ to $q'$ can be estimated to happen with the following likelihood:\n$$\\phi(q,q') = \\frac{\\textrm{expected number of times we went }q\\rightarrow q'}{\\textrm{expected number of times we were in }q}$$\n\nNow, given say a sentence $s$, the expected number of times we used a particular transition, is:\n\\begin{eqnarray*}\n  E_s(q,e,q') & = & \\textrm{expected number of times we went }~q\\rightarrow^eq'~\\textrm{to make sentence}~s \\\\\n  & = & \\sum_{(b,r)\\in\\PARSES(s)}\\frac{p_\\phi(b,r)}{p_\\phi(s)}[\\textrm{number of times}~q\\rightarrow^eq'\\textrm{ occurs in }r ] \\\\\n  & = & \\sum_{(b,r)\\in\\PARSES(s)}\\frac{p_\\phi(b,r)}{p_\\phi(s)}\\TC_r(q,e,q')\n  \\end{eqnarray*}\n\nWhy divide by the probability of the sentence? This is because the sentence is given. For example, if a sentence has exactly one parse, but it uses a lot of rules, then the expected number of times a particular rule got used is exactly the number of times it got used in that one parse, \\emph{not} dividing by the (very small) probability of that sentence.\n\nSimilarly for the Markov chain:\n\n\\begin{eqnarray*}\n  E_s(x,y) & = & \\textrm{expected number of times we went }~x\\rightarrow y~\\textrm{to make sentence}~s \\\\\n  & = & \\sum_{(b,r)\\in\\PARSES(s)}\\frac{p_\\phi(b,r)}{p_\\phi(s)}[\\textrm{number of times}~x\\arr y\\textrm{ occurs in }b ] \\\\\n  & = & \\sum_{(b,r)\\in\\PARSES(s)}\\frac{p_\\phi(b,r)}{p_\\phi(s)}\\BC_b(x,y)\n  \\end{eqnarray*}\n\n\n\nNow given a corpus $C$, we simply add the expected number of times rules got used in each sentence, i.e.\n\\begin{eqnarray*}\n  E_C(q,e,q')& = &\\sum_{s\\in C}E_s(q,e,q')\\\\\n  E_C(x,y)& = &\\sum_{s\\in C}E_s(x,y)\n\\end{eqnarray*}\n\n\n\n\\begin{definition}[corpus update rule]\n  Given a corpus $C$ and given a probability assignment $\\phi$ we can define an updated probability assignment $\\phi'$ as follows:\n\n  $$\\phi_C'(q,e,q') = \\frac{\\sum_{s\\in C}\\sum_{(b,r)\\in\\PARSES(s)} \\frac{p_\\phi(b,r)}{p_\\phi(s)}~ \\TC_r(q,e,q')}{\\sum_{s\\in C}\\sum_{(b,r)\\in\\PARSES(s)} \\frac{p_\\phi(b,r)}{p_\\phi(s)}~ \\SC_r(q)}$$ \n\nAnd for the bigrams:\n\n  $$\\phi_C'(x,y) = \\frac{\\sum_{s\\in C}\\sum_{(b,r)\\in\\PARSES(s)} \\frac{p_\\phi(b,r)}{p_\\phi(s)}~ \\BC_b(x,y)}{\\sum_{s\\in C}\\sum_{(b,r)\\in\\PARSES(s)} \\frac{p_\\phi(b,r)}{p_\\phi(s)}~ \\UC_b(x)}$$ \n\n\\end{definition}\n\n\nEquivalently,\n\n$$\\phi_C'(q,e,q') = \\frac{\\sum_{s\\in C}\\frac{1}{p_\\phi(s)}\\sum_{(b,r)\\in\\PARSES(s)} p_\\phi(b,r)~ \\TC_r(q,e,q')}{\\sum_{s\\in C}\\frac{1}{p_\\phi(s)}\\sum_{(b,r)\\in\\PARSES(s)} p_\\phi(b,r)~ \\SC_r(q)}$$ \n\nand \n\n$$\\phi_C'(x,y) = \\frac{\\sum_{s\\in C}\\frac{1}{p_\\phi(s)}\\sum_{(b,r)\\in\\PARSES(s)} p_\\phi(b,r)~ \\BC_b(x,y)}{\\sum_{s\\in C}\\frac{1}{p_\\phi(s)}\\sum_{(b,r)\\in\\PARSES(s)} p_\\phi(b,r)~ \\UC_b(x)}$$ \n\n\n\n\n\n\\subsection{Some basic results}\n\n\\begin{lemma}[no-ambiguity]\n  If there is no ambiguity, $\\phi_C'(q,e,q')$ does not depend on the original rule probability assignment.\n\\end{lemma}\n\n\\begin{proof}\n  If there is no ambiguity, for any sentence one parse $(b,r)$ exists for which $p(s)=p(b,r)$. Further, none of the counts depend on rule probability assignment $\\phi$. Thus the expected counts of each transition/bigram and each state/unigram are simply their counts in the corpus.\n\n  \\begin{eqnarray*}\n    \\phi_C'(q,e,q')& = &\\frac{\\sum_{s\\in C}\\sum_{(b,r)\\in\\PARSES(s)} \\frac{p_\\phi(b,r)}{p_\\phi(s)}~ \\TC_r(q,e,q')}{\\sum_{s\\in C}\\sum_{(b,r)\\in\\PARSES(s)} \\frac{p_\\phi(b,r)}{p_\\phi(s)}~ \\SC_r(q)}\\\\\n    & = &\\frac{\\sum_{s\\in C} 1 \\times \\TC_r(q,e,q')}{\\sum_{s\\in C} 1 \\times \\SC_r(q)}\n  \\end{eqnarray*}\n\n  \\begin{eqnarray*}\n    \\phi_C'(x,y)& = &\\frac{\\sum_{s\\in C}\\sum_{(b,r)\\in\\PARSES(s)} \\frac{p_\\phi(b,r)}{p_\\phi(s)}~ \\BC_b(x,y)}{\\sum_{s\\in C}\\sum_{(b,r)\\in\\PARSES(s)} \\frac{p_\\phi(b,r)}{p_\\phi(s)}~ \\UC_b(x)}\\\\\n    & = &\\frac{\\sum_{s\\in C} 1 \\times \\BC_b(x,y)}{\\sum_{s\\in C} 1 \\times \\UC_b(x)}\n  \\end{eqnarray*}\n\n\n\\end{proof}\n\nAs a corollary, in an unambiguous corpus the algorithm will converge to a global likelihood maximum in one step, irrespective of the original rule probabilities.\n\n\n\n\\section{Higher level points}\n\\label{sec:higher-level-points}\n\n\\subsection{The hypothesis}\n\\label{sec:hypothesis}\n\n\nSongbirds whose songs are made up of a vocabulary of chirps are normally thought to determine their next chirp entirely on the basis of the previous chirp; in other words their grammar is a Markov chain. They have a probability distribution over the bigrams of their vocabulary ($\\sg \\times \\sg \\arr [0,1]$) and that is the extent of the complexity of their grammar.\n\nWe claim that the California Thrasher has a more complex grammar. We observe that the bird has repeated substrings in its songs, some even embedded inside other repeated fragments. This might just be a coincidence, or it might be that the bird includes copying in its grammar.  A grammar with copying is far above a Markov chain in the Chomsky hierarchy: it is mildly context sensitive, like human language grammars. \n\n\\subsection{How we try to answer the question}\n\\label{sec:how-we-try}\n\nAll we have is samples of the bird's song. Naturally, a finite sample can always be generated by the simplest grammar available: a finite grammar of legal songs. We can't ask the bird for grammaticality judgements so all we have to go on is the corpus. We can make up a bigram grammar that generates the corpus, and we can also make up a grammar with copying that generates the corpus, and we can make them up so that they generate exactly the same language.\n\nHowever, since birds are thought to be stochastic creatures -- they use not just a bigram grammar but a Markov chain, which is a probabilistic bigram grammar -- we have additional evidence for what their grammar might really look like: we have the probability distribution in the corpus. We can therefore compare the performance of two grammars, one with copying and the other without, on the corpus. \n\nTo do this we take a part of the corpus and find the best fit of the rule probabilities in each grammar for that part of the corpus. We then test each fitted grammar's ability to predict the rest of the corpus. The grammar that makes a better prediction is a more likely grammar for that corpus.\n\n\\subsection{Questions and concerns}\n\\label{sec:questions-concerns}\n\n\\begin{itemize}\n\\item If you add copying to the grammar of just any bird, will it perform better?\n\\item Floris's fancy repetition-measurer finds that the bigrams themselves predict \\textit{more} copying, not less. On the one hand this is fine: the point is that the bird needs to be able to independently control copying. But on the other hand, this is very weird: we started with this surface observation of copying, and now we claim that the bird is a copy bird based on \\textit{less} copying?\n\\item Do we need to prove that no sub-MCS grammar predicts the corpus as well as the copy grammar in order to be saying anything about the bird's Chomsky-hierarchy status? (note: this is impossible)\n\\item Do we need to prove that our grammar is indeed copying? Or that it is indeed MCS?\n\\end{itemize}\n\n\\subsection{Notes on the Chomsky hierarchy}\n\\label{sec:notes-chomsky-hier}\n\n\\includegraphics[width=6in]{Chomsky-hierarchy.pdf}\n\nThere are certain surface patterns that are known to only be generable with grammars of certain types. For example, $a^nb^n$ famously requires a context free grammar. However, since this is a hierarchy anything you can generate with a lower-level grammar you can also generate with a higher-level grammar. If we have a language or a corpus that is, say, regular, we might still want to say that the grammar that generated it is supra-regular. This would have to be based on either additional facts about the language or corpus, on arguments from parsimony, or on additional information about the source of the corpus. \n\nIn our case we argue from the probability distribution in the corpus. If we have reason to think that the bird generates his song probabilistically, then the probabilities in the grammar predict probabilities in the corpus. A grammar with ``room'' in it to include probabilities for copying should better predict the corpus if the bird is indeed copying.\n\nPMCFGs defined in Seki et al , originally in (Kasami 1988a),(Seki 1991). Copy language $ww\\in \\mathcal{L}(PMCFG)$; $a^{2^n}\\in \\mathcal{L}(PMCFG)$\n\nKasami, T. et al. 1988a. \"Generalized Context-Free Grammars and Multiple Context-Free Grammars\", Trans. IEICE, J71-D-I, 5:758-765. \n\n\n\\subsection{TODO}\n\\begin{itemize}\n\\item Prove in a grammar without ambiguity that the algorithm actually moves to the global likelihood maximum.\n\\item Prove correctness (rule probabilities with the same left hand side sum to one).\n\\item Prove that each rule update increases the likelihood of the corpus.\n\\item Prove convergence.\n\\end{itemize}\n\n\n\n\n\n\n\n\n\\section{Historical and mostly wrong stuff}\n\n\n\n\nPreviously we used this update rule:\n\n\\begin{definition}[sentence-level update rule]\n  Given a sentence $s$ and given a probability assignment $\\phi$ we can define an updated probability assignment $\\phi'$ as follows:\n\n  $$\\phi_s'(q,e,q') = \\frac{\\sum_{(b,r)\\in\\PARSES(s)}p_\\phi(b,r)~\\TC_r(q,e,q')}{\\sum_{(b,r)\\in\\PARSES(s)}p_\\phi(b,r)~\\SC_r(q)}$$\n\\end{definition}\n\n%\\begin{definition}[sentence-level update rule]\n%  Given a sentence $s$ and given a probability assignment $\\phi$ we can define an updated probability assignment $\\phi'$ as follows:%\n%\n%  $$\\phi_s'(q,e,q') = \\sum_{(b,r)\\in\\PARSES(s)}\\frac{p_\\phi(b,r)}{\\sum_{(b',r')\\in\\PARSES(s)}p_\\phi(b',r')}\\frac{\\TC_r(q,e,q')}{\\SC_r(q)}$$\n%\\end{definition}\n\n%We can write more simply $p_\\phi(s)=\\sum_{(b',r')\\in\\PARSES(s)}p_\\phi(b',r')$ so that\n\n%$$\\phi_s'(q,e,q') = \\frac{1}{p(s)}\\sum_{(b,r)\\in\\PARSES(s)}p(b,r)\\frac{\\TC_r(q,e,q')}{\\SC_r(q)}$$\n\n\nSimilarly, given a corpus, we compute the updates based on all parses in parallel:\n\\begin{definition}[corpus update rule]\n  Given a corpus $C$ and given a probability assignment $\\phi$ we can define an updated probability assignment $\\phi'$ as follows:\n\n $$\\phi_C'(q,e,q') = \\frac{\\sum_{s\\in C}\\sum_{(b,r)\\in\\PARSES(s)} p_\\phi(b,r)~ \\TC_r(q,e,q')}{\\sum_{s\\in C}\\sum_{(b,r)\\in\\PARSES(s)} p_\\phi(b,r)~ \\SC_r(q)}$$ \n\\end{definition}\n\n%Floris' version:\n%$$\\phi_C'(q,e,q') = \\frac{\\sum_{s\\in C}p(s)\\phi_s'(q,e,q')}{\\sum_{s\\in C}p(s)}$$ \n\nThe sums can't be combined into one sum because sometimes there are parses that visit state $q$ but don't follow transition $(q,e,q')$. However, we still want that visit in the state counts for that transition.\n\nWe can't use the probability of the whole corpus because not all sentences have parses that visit all states.\n\n\n\n\\end{document}\n\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: t\n%%% End:\n", "meta": {"hexsha": "e0faafa3097d80e3965695cee823e92ac4afbde8", "size": 41047, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "conceptual_smart_stuff.tex", "max_stars_repo_name": "megodoonch/birdsong", "max_stars_repo_head_hexsha": "582e7ddecf6c9c1b75f17418097f7bcbf6784d31", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "conceptual_smart_stuff.tex", "max_issues_repo_name": "megodoonch/birdsong", "max_issues_repo_head_hexsha": "582e7ddecf6c9c1b75f17418097f7bcbf6784d31", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "conceptual_smart_stuff.tex", "max_forks_repo_name": "megodoonch/birdsong", "max_forks_repo_head_hexsha": "582e7ddecf6c9c1b75f17418097f7bcbf6784d31", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.0891514501, "max_line_length": 942, "alphanum_fraction": 0.6576120057, "num_tokens": 14061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.3203001409480639}}
{"text": "The \\xmlNode{Components} node contains the technical and economic definitions of the components (or\nunits) within the grid system that needs to be solved. The \\xmlNode{Components} node contains many\n\\xmlNode{Component} nodes defining each of the grid components.\n\n\\subsection{Component Activity}\nAt each time point in a dispatch optimization, HERON attempts to calculate the most optimal usage of\neach component in the system. To report the usage of each resource in each unit in the system, HERON\nuses some conventions that we explain here.\n\nWe can consider two quantities when reporting the activity of a component over time: the quantity of\nproduct consumed or produced, or the rate at which a product is consumed or produced. For instance,\nif a Component produces ``widgets'', at a particular hour we can either talk about the total number\nof widgets produced during an hour period, or about the rate (in widgets per second) at which they\nwere produced. Generally, we only track the rate of production for all Components when performing\ndispatch optimization; however, for a \\xmlNode{Component} who \\xmlNode{stores} a resource, we track\nthe \\emph{level} (or \\emph{net quantity produced}) instead of the \\emph{rate}.\n\n\\subsubsection{General Activity}\nFor most components, when the activity is reported at a particular time for a component, it\nrepresents the instantaneous production level of that component at that time. For example, if a\ncomponent's max capacity is given as 10 widgets per second, and the activity reported for hour 2 is\n3, then instantaneously at the beginning of hour 2 the unit is assumed to be producing 3 widgets per\nsecond. Simlarly, if a power plant has a capacity of 100 MW and activity is reported as 5 for a\nparticular hour, then at beginning of that hour the plant is producing 5 MW. Between time points, it\nis assumed that the rate of production varies linearly between the reported time points.\n\n\\subsubsection{Storage Activity}\nUnlike other components, for a storage (a \\xmlNode{Component} who \\xmlNode{stores} a resource) we\nreport the instantaneous \\emph{level} of the storage instead of the instantaneous production rate.\nWe formally define the level (or ``net quantity produced'') at a specific time as\n\\begin{equation}\n  L(t) = L_0 + \\int_{t_0}^t R(t) dt,\n\\end{equation}\nwhere:\n\\begin{itemize}\n  \\item $L$ is the net quantity produced at time $t$,\n  \\item $L_0$ is an initial level at the start of the analysis period,\n  \\item $t$ is the continuous variable for \\emph{time},\n  \\item $t_0$ is the starting time, at which the components has level $L_0$, and\n  \\item $R(t)$ is the rate of production for the component at time $t$.\n\\end{itemize}\nIn discrete terms,\n\\begin{equation}\n  L_k = L_0 + \\sum_{i=1}^{k-1} R_i \\Delta_k,\n\\end{equation}\nwhere:\n\\begin{itemize}\n  \\item $k$ is an index for discrete time intervals $t_k$,\n  \\item $L_k$ is the level at the beginning of time interval $t_k$,\n  \\item $R_k$ is the production rate for the component during time interval $t_k$, and\n  \\item $\\Delta_k$ is the length of the time interval $t_k$.\n\\end{itemize}\nThe equivalent continuous production rate for a storage component is therefore\n\\begin{equation}\n  R(t) = \\frac{\\partial}{\\partial t} L(t),\n\\end{equation}\nor, in discrete form given the constant production assumption,\n\\begin{equation}\n  R_k = \\frac{L_{k+1} - L_k}{\\Delta_k}.\n\\end{equation}\nWe want to emphasize this key difference: the \\emph{production rate} is interpreted differently for\nstorage and other producers. For \\textbf{storages},\n\\begin{itemize}\n  \\item production rate during a time step is considered \\emph{discontinuously constant}, and\n  \\item activity is reported as the \\emph{level} of the storage at the beginning of the time step.\n\\end{itemize}\nFor \\textbf{all other components},\n\\begin{itemize}\n  \\item production rate during a time step is considered \\emph{continuously linear}, and\n  \\item activity is reported as the \\emph{instantaneous production rate} of the storage at the\n        beginning of the time step.\n\\end{itemize}\nThis difference has significant impact when developing a \\xmlNode{Validator} or plotting dispatch\nresults. As a demonstration, see Figures \\ref{fig:producer_example} and \\ref{fig:storage_example}.\n\nIn Figure \\ref{fig:producer_example}, the black dots indicate the statepoints that HERON reports,\nwhile the green dashed line is the assumed production between statepoints. Note the\n$y$-axis is in units of production rate.\n\n\\begin{figure}[h!]\n  \\centering\n  \\includegraphics[width=0.5\\textwidth]{../pics/producer_activity_explained.png}\n  \\caption{Producer Example}\n  \\label{fig:producer_example}\n\\end{figure}\n\nIn Figure \\ref{fig:storage_example}, the black dots indicate the statepoints that HERON reports,\nwith units of emph{level}, not production rate. The red dotted line is the assumed level between\nstatepoints, and the green dashed lines are the equivalent production between each statepoint.\nNote the dual $y$-axis: one is in units of production rate (green, left), while the other is in units of level or\nquantity (red, right). That is, the storage unit filly slowly, then fills quickly, then totally depletes before\nfilling again. This same activity can be represented by the production rates in the dashed green\nlines, with negative production indicating absorbing into storage and positive production indicating\nemission from storage.\n\\begin{figure}[h!]\n  \\centering\n  \\includegraphics[width=0.5\\textwidth]{../pics/storage_activity_explained.png}\n  \\caption{Storage Example}\n  \\label{fig:storage_example}\n\\end{figure}\n", "meta": {"hexsha": "310e6b4d1be29795a8b2b3ad7c8905e4bbb251e4", "size": 5567, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/user_manual/src/components_intro.tex", "max_stars_repo_name": "worseliz/HERON", "max_stars_repo_head_hexsha": "fa5f346a0bc9f9d5ea4659618ffeb52bea812cee", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2020-07-28T21:35:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T17:31:39.000Z", "max_issues_repo_path": "doc/user_manual/src/components_intro.tex", "max_issues_repo_name": "worseliz/HERON", "max_issues_repo_head_hexsha": "fa5f346a0bc9f9d5ea4659618ffeb52bea812cee", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 112, "max_issues_repo_issues_event_min_datetime": "2020-07-29T15:25:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:21:00.000Z", "max_forks_repo_path": "doc/user_manual/src/components_intro.tex", "max_forks_repo_name": "worseliz/HERON", "max_forks_repo_head_hexsha": "fa5f346a0bc9f9d5ea4659618ffeb52bea812cee", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 22, "max_forks_repo_forks_event_min_datetime": "2020-07-28T20:08:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T21:22:03.000Z", "avg_line_length": 55.1188118812, "max_line_length": 113, "alphanum_fraction": 0.776181067, "num_tokens": 1399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.3203001409480639}}
{"text": "% Created: Enze Chen, June 2017\r\n% Last edited: Enze Chen, December 2017\r\n%\r\n% Chapter 6 of the MSE 142 coursereader. This chapter discusses parabolic potentials and the quantum harmonic oscillator. Students are introduced to operators, and in particular use the ladder operators to solve the Schrodinger equation. A wealth of additional properties are rather lamely appended to the last section.\r\n\r\n% Uncomment the following three lines and last line to individually compile this chapter\r\n%\\documentclass[12pt, english]{book}\r\n%\\usepackage{142crstyle}\r\n%\\begin{document}\r\n\r\n\\chapter{Quantum Harmonic Oscillators} \\label{ch:qho}\r\n%{ \\doublespacing \r\nIn this chapter, we will consider what happens when a particle is placed in a parabolic potential, which lacks the sharp discontinuities present in previous examples. We will see some pretty amazing behavior when we try to solve the \\Sch\\ equation for this non-constant potential, which will give us a much better understanding of quantization in quantum mechanical systems.\r\n\r\n\r\n\\section{Parabolic potential}\r\nConsider a one-dimensional quadratic potential energy surface given by $V(x)=\\frac{1}{2}kx^2$ which is typically associated with harmonic oscillators. Like the simple harmonic oscillator (see Appendix~\\ref{sec:shm} for a short review), the \\textbf{quantum harmonic oscillator} (QHO) also has an effective spring constant $k$ and an associated angular frequency $\\omega$ that is related by $\\omega = \\sqrt{k/m}$. The QHO is a powerful model for things like the forces that hold atoms together in materials and any potential surface near a local minimum (Figure~\\ref{fig:qpot}).\r\n\r\n\\begin{figure}[!h]\r\n\t\\centering\r\n\t\\subfloat[]{\\raisebox{1.7\\height}{\\includegraphics[width=0.25\\linewidth]{atoms-spring}} \\label{fig:qho-mod1}} \\hspace{4ex}\r\n\t\\subfloat[]{\\includegraphics[width=0.43\\linewidth]{qpot-min} \\label{fig:qho-mod2}}\r\n\t\\caption{The quantum harmonic oscillator is particularly powerful at modeling \\protect\\subref{fig:qho-mod1} the forces that hold atoms together, which are often approximated with springs, and \\protect\\subref{fig:qho-mod2} the minima of any generic potential surface, which is approximately parabolic when one considers the Taylor series near the minimum.}\r\n\t\\label{fig:qpot}\r\n\\end{figure}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n\\section{Operators}\r\nIn order to work with the QHO, we will have to revisit the concept of \\textbf{operators}, which are just special functions that represent physical observables. If we represent the quadratic potential energy in terms of angular frequency, i.e. $V(x)=\\frac{1}{2}m\\omega^2x^2$, we can then represent the Hamiltonian of the particle, which is the sum of the kinetic and potential energies, as\r\n\\begin{tcolorbox}[title = Hamiltonian for the QHO] \\vspace{-2ex}\r\n\t\\begin{equation}\r\n\t\\hat{H} = \\frac{\\hat{p}^2}{2m} + \\frac{1}{2}m\\omega^2x^2 \\label{eq:ham-qho}\r\n\t\\end{equation}\r\n\\end{tcolorbox}\r\n\r\nNotice that in the first term, we used $\\hat{p}$ to represent the momentum operator, which is defined as $\\hat{p}=-i\\hbar\\dv{x}$.\\footnote{Technically position here is also an operator $\\hat{x}$, but it happens to be defined as $\\hat{x}=x$, so we substitute.} Now we need to solve the time-independent \\Sch\\ equation, given by:\r\n\\begin{tcolorbox}[title = \\Sch\\ equation for the QHO] \\vspace{-2ex}\r\n\t\\begin{equation}\r\n\t\t\\hat{H}\\Psi = -\\frac{\\hbar^2}{2m}\\dv[2]{\\Psi}{x} + \\frac{1}{2}m\\omega^2x^2\\Psi = E\\Psi \\label{eq:se-qho}\r\n\t\\end{equation}\r\n\\end{tcolorbox}\r\n\r\nRecall that this form for the operator $\\hat{p}$ was motivated by the first wave equation we wrote down, corresponding to the free particle. This was an expression of the form $\\exp\\left(i(kx-\\omega t)\\right) = \\exp \\left( \\frac{i}{\\hbar}(px-Et) \\right)$. If we act on this wave equation with the operator $\\hat{p}$ defined as above, we get the same function back multiplied by $p$:\r\n\\begin{align*}\r\n\t\\hat{p}\\exp \\left(\\frac{i}{\\hbar}(px-Et)\\right) &= -i\\hbar\\exp \\left(\\frac{i}{\\hbar}(px-Et)\\right) \\left(\\frac{ip}{\\hbar}\\right) \\\\\r\n\t&= p\\exp \\left(\\frac{i}{\\hbar}(px-Et)\\right)\r\n\\end{align*}\r\nOne can think of this as essentially representative of what it means to make a measurement of the momentum in a quantum mechanical system. \\par \r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n\\subsection{Ladder operators}\r\nIn order to solve Equation~\\ref{eq:se-qho}, we will attempt to \\emph{factor} the Hamiltonian given by Equation~\\ref{eq:ham-qho}. To see the motivation behind this, notice that if the Hamiltonian was given by two real numbers $c^2+d^2$, we could then factor this expression as \r\n\\begin{equation*}\r\n\tc^2 + d^2 = (c + di)(c - di)\r\n\\end{equation*}\r\n\r\nFollowing this example, we first reformulate the Hamiltonian so that we can factor it as follows:\r\n\\begin{align*}\r\n\t\\hat{H} &= \\frac{\\hat{p}^2 }{2m} + \\frac{1}{2}m\\omega^2\\hat{x}^2 \\\\\r\n\t&= \\frac{m\\omega^2}{2}\\left[\\hat{x}^2 + \\frac{\\hat{p}^2}{m^2\\omega^2}\\right] \\\\\r\n\t&= \\frac{m\\omega^2}{2}\\left[\\hat{x} + \\frac{i\\hat{p}}{m\\omega}\\right] \\left[\\hat{x}-\\frac{i\\hat{p}}{m\\omega}\\right] \\numberthis \\label{eq:ham-factored}\r\n\\end{align*}\r\n\r\n\\emph{A word of caution}: Though it seems straightforward, we actually hand-waved a lot of the rigor here, because dealing with operators (which are functions) is trickier than dealing with real quantities. The theory is outside the scope of this course, but we will see shortly how this affects what are normally intuitive results. \\par \r\n\r\nNow, the factored Hamiltonian in Equation~\\ref{eq:ham-factored} is suggestive of some form of symmetry, particularly the expressions inside the square brackets. We are now going to define two new operators\r\n\\begin{tcolorbox}[title = Ladder operators] \\vspace{-2ex}\r\n\t\\begin{align}\r\n\t\ta &= \\sqrt{\\frac{m\\omega}{2\\hbar}}\\left(\\hat{x} + \\frac{i\\hat{p}}{m\\omega}\\right) = \\sqrt{\\frac{m\\omega}{2\\hbar}}\\left(\\hat{x} + \\frac{\\hbar}{m\\omega}\\dv{x}\\right) \\label{eq:annihile} \\\\\r\n\t\t\\ad &= \\sqrt{\\frac{m\\omega}{2\\hbar}}\\left(\\hat{x} - \\frac{i\\hat{p}}{m\\omega}\\right) = \\sqrt{\\frac{m\\omega}{2\\hbar}}\\left(\\hat{x} - \\frac{\\hbar}{m\\omega}\\dv{x}\\right) \\label{eq:creation}\r\n\t\\end{align}\r\n\\end{tcolorbox}\r\n\r\nThe method we are using to solve the \\Sch\\ equation involves these two \\textbf{ladder operators} $a$ and $\\ad$ (called ``a-dagger''), which are known as the \\textbf{annihilation}/\\textbf{lowering} operator and \\textbf{creation}/\\textbf{raising} operator respectively (you will soon see why). This clever method was developed by Paul Dirac\\footnote{Dirac was extremely influential in developing the formalism of quantum theory, introducing this and bra-ket notation which you will see later. He shared the 1933 Nobel Prize in Physics with \\Sch. Curiously, Einstein describes that ``[he has] trouble with Dirac. This balancing on the dizzying path between genius and madness is awful.'' (N. Sukumar, \\emph{A Matter of Density}, 2012).} and allows us to eventually solve for the energy without directly solving the \\Sch\\ equation. Note that we chose the coefficient of $\\sqrt{m\\omega/2\\hbar}$ largely for the purpose of eliminating constants in the end.\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n\\subsection{Hamiltonian revisited}\r\nWe see that the ladder operators are individually defined in terms of the position and momentum operators, so why not try solving for them? If we add Equation~\\ref{eq:annihile} and~\\ref{eq:creation}, we get \r\n\\begin{equation*}\r\n\ta + \\ad = \\sqrt{\\frac{m\\omega}{2\\hbar}}2\\hat{x}\r\n\\end{equation*}\r\nwhich allows us to solve for the position operator as\r\n\\begin{tcolorbox}[title = Position operator] \\vspace{-2ex}\r\n\t\\begin{equation}\r\n\t\t\\hat{x} = \\sqrt{\\frac{\\hbar}{2m\\omega}}\\left(\\ad + a \\right) \\label{eq:x-op}\r\n\t\\end{equation}\r\n\\end{tcolorbox}\r\n\r\nSimilarly, we can subtract the two ladder operators to get\r\n\\begin{equation*}\r\n\ta - \\ad = \\sqrt{\\frac{m\\omega}{2\\hbar}} \\frac{2i\\hat{p}}{m\\omega}\r\n\\end{equation*}\r\nwhich gives the momentum operator as \r\n\\begin{tcolorbox}[title = Momentum operator] \\vspace{-2ex}\r\n\t\\begin{equation}\r\n\t\\hat{p} = i\\sqrt{\\frac{m\\omega\\hbar}{2}}\\left(\\ad - a \\right) \\label{eq:p-op}\r\n\t\\end{equation}\r\n\\end{tcolorbox}\r\n\r\nOK, so why might this be useful? Let's rewrite the Hamiltonian in terms of these new operators:\r\n\\begin{align*}\r\n\t\\hat{H} &= \\frac{\\hat{p}^2}{2m} + \\frac{1}{2}m\\omega^2\\hat{x}^2 \\\\\r\n\t&= -\\frac{1}{2m}\\frac{m\\omega\\hbar}{2}\\left(\\ad - a\\right)^2 + \\frac{1}{2}m\\omega^2 \\frac{\\hbar}{2m\\omega} \\left(\\ad + a \\right)^2 \\\\\r\n\t&= -\\frac{\\hbar\\omega}{4} \\left(\\left(\\ad\\right)^2 - \\ad a - a\\ad + a^2\\right) + \\frac{\\hbar\\omega}{4}\\left(\\left(\\ad\\right)^2 + \\ad a + a\\ad + a^2 \\right) \\\\\r\n\t\\Aboxed{ \\hat{H} &= \\frac{\\hbar\\omega}{2} \\left( \\ad a + a\\ad \\right)} \\numberthis \\label{eq:ham-qho2}\r\n\\end{align*}\r\n\r\nNow, we might be tempted to combine the $\\ad a$ term with the $a \\ad$ term, but this is one of the tricky aspects of operators: in general, \\textbf{they do not commute} with each other, so we can't expect them to represent the same quantity when we switch the order. \\par \r\n\r\nOf course, we shouldn't be fazed by this fact and we will try to see if we can find some relationship between the two terms. Luckily, in quantum mechanics, there is a quantity called the \\textbf{commutator} (adopted from group theory) that precisely indicates to what degree two operators fail to commute. Given two operators $A$ and $B$, we define the commutator as\r\n\\begin{equation}\r\n\t[A,B] = AB - BA \\label{eq:comm}\r\n\\end{equation}\r\nwhich you can see for normal variables should be zero. \\par \r\n\r\nAs a first example, let's consider the commutation relation between $\\hat{x}$ and $\\hat{p}$, i.e. $[\\hat{x}, \\hat{p}]$. To aid the derivation, we will have both operators act on an arbitrary dummy function $\\Psi$ that we will discard in the end.\r\n\\begin{align*}\r\n\t[\\hat{x}, \\hat{p}]\\Psi &= (\\hat{x}\\hat{p})\\Psi - (\\hat{p}\\hat{x})\\Psi \\\\\r\n\t&= x\\left(-i\\hbar \\dv{x}\\Psi \\right) + i\\hbar \\dv{x}(x\\Psi) \\\\\r\n\t&= -i\\hbar x \\dv{x}\\Psi + i\\hbar x \\dv{x}\\Psi + i\\hbar\\Psi \\\\\r\n\t&= i\\hbar\\Psi \r\n\\end{align*}\r\n\r\nFrom this, one then concludes that \r\n\\begin{tcolorbox}[title = Canonical commutation relation] \\vspace{-2ex}\r\n\t\\begin{equation}\r\n\t\t[\\hat{x}, \\hat{p}] = i\\hbar\r\n\t\\end{equation}\r\n\\end{tcolorbox}\r\n\r\nwhich is known as the \\textbf{canonical commutation relation} because it establishes a fundamental relationship between two conjugate variables, such as $\\hat{x}$ and $\\hat{p}$, that eventually leads to the uncertainty principle. \\par \r\n\r\nNow what about the commutation relation between $a$ and $\\ad$? The result actually follows nicely from the canonical commutation relation. First, we also show that if two operators can be expressed as $f+g$ and $f-g$, where $f$ and $g$ are arbitrary operators, then their commutation relation can be simplified as follows:\r\n\\begin{align*}\r\n\t[f+g,f-g] &= (f+g)(f-g) - (f-g)(f+g) \\\\\r\n\t&= f^2 - fg + gf -g^2 - f^2 - fg + gf + g^2 \\\\\r\n\t&= 2(gf - fg) \\\\\r\n\t&= 2[g,f]\r\n\\end{align*}\r\n\r\nWe can apply this result to find that\r\n\\begin{align*}\r\n\t[a, \\ad] &= \\frac{m\\omega}{2\\hbar}\\left[\\hat{x} + \\frac{i\\hat{p}}{m\\omega}, \\hat{x} - \\frac{i\\hat{p}}{m\\omega} \\right] \\\\\r\n\t&= \\frac{m\\omega}{\\hbar} \\left[ \\frac{i\\hat{p}}{m\\omega}, \\hat{x} \\right] \\\\\r\n\t&= \\frac{i}{\\hbar}[\\hat{p},\\hat{x}] \\\\\r\n\t&= \\frac{i}{\\hbar}(-i\\hbar) \r\n\\end{align*}\r\n\r\n\\begin{tcolorbox}[title = Ladder operators commutation relation] \\vspace{-2ex}\r\n\t\\begin{equation}\r\n\t\t[a,\\ad] = a\\ad - \\ad a = 1  \\label{eq:a-comm}\r\n\t\\end{equation}\r\n\\end{tcolorbox}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n\\section{Solutions of the QHO}\r\nWe're almost there! Now using this commutation relation, we can rewrite Equation~\\ref{eq:ham-qho2} in its standard form. In particular, using the fact that $a\\ad = 1 + \\ad a$, we find that\r\n\\begin{tcolorbox}[title = Hamiltonian of the QHO (with ladder operators)] \\vspace{-2ex}\r\n\t\\begin{equation}\r\n\t\\hat{H} = \\hbar\\omega \\left(\\ad a + \\frac{1}{2} \\right) \\label{eq:ham-qho3}\r\n\t\\end{equation}\r\n\\end{tcolorbox}\r\n\r\nOK, now let's try to understand why all of the above definitions and mathematics are useful in terms of solving the QHO problem. To begin with, let's rewrite the time-independent \\Sch\\ equation in terms of these new variables. We have:\r\n\\begin{equation}\r\n\\hbar\\omega \\left(\\ad a + \\frac{1}{2} \\right)\\psi_n = E_n\\psi_n \\label{eq:sch-qho}\r\n\\end{equation}\r\nwhere we have introduced a quantum number $n$ as an index for the allowed solutions of this equation, just like we did for the particle in a box. Now let's act from the left on Equation~\\ref{eq:sch-qho} with the lowering operator $a$, carefully keeping track of the order of the operators since we know they don't commute with each other (but they can commute with scalars, like the energy $E_n$). This gives\r\n\\begin{align*}\r\n\\hbar\\omega \\left(\\ad a + \\frac{1}{2} \\right)\\psi_n &= E_n\\psi_n \\\\\r\n\\hbar\\omega \\left(a \\ad a + \\frac{1}{2} a\\right)\\psi_n &= E_na\\psi_n \\\\\r\n\\hbar\\omega \\left(\\left(1 + \\ad a \\right) a + \\frac{1}{2} a\\right)\\psi_n &= E_na\\psi_n \\\\\r\n\\hbar\\omega \\left(1 + \\ad a + \\frac{1}{2} \\right) a\\psi_n &= E_na\\psi_n \\\\\r\n\\Aboxed{\\hbar\\omega \\left(\\ad a + \\frac{1}{2} \\right) (a\\psi_n) &= (E_n-\\hbar\\omega)(a\\psi_n)} \\numberthis \\label{eq:sch-qho2}\r\n\\end{align*}\r\n\r\nIf we look carefully at this equation and compare it to Equation~\\ref{eq:sch-qho}, we see that they are the same form! This says in particular that if $\\psi_n$ is a solution of the QHO with energy $E_n$, then $a\\psi_n$ is also a solution, with energy $E_n-\\hbar\\omega$. This is a key result and explains why $a$ is called the lowering operator. From a known solution one can essentially generate all other known solutions of lower energy by applying this operator. This is quite handy!\r\n\r\nSo imagine that one starts from some known solution and starts applying this operator, generating lower and lower energy states. At some point one must find the ground state solution. But what happens if one then applies the lowering operator to this? If this gives some new function, then this can't really have been the ground state! We therefore conclude that the ground state wave function must satisfy the simple equation\r\n\\begin{equation*}\r\na\\psi_0 = 0\r\n\\end{equation*}\r\n\r\nHere you can really see how we have successfully factorized the initial second order differential equation (Equation~\\ref{eq:se-qho}) to obtain a solution for the wave function. In particular, we can use the right hand side of Equation~\\ref{eq:annihile} to substitute for the lowering operator $a$ and obtain a first order differential equation:\r\n\\begin{equation*}\r\n\t\\left(x + \\frac{\\hbar}{m\\omega} \\dv{x}\\right)\\psi_0 = 0\r\n\\end{equation*}\r\n\r\nWe can solve this using separation of variables as follows.\r\n\\begin{align*}\r\n\t\\left(x + \\frac{\\hbar}{m\\omega} \\dv{x}\\right)\\psi_0 &= 0 \\\\\r\n\t\\frac{\\hbar}{m\\omega} \\dv{\\psi_0}{x} &= -x\\psi_0 \\\\\r\n\t\\frac{1}{\\psi_0} \\dd{\\psi_0} &= -\\frac{m\\omega}{\\hbar}x \\dd{x} \\\\\r\n\t\\ln (\\psi_0) &= -\\frac{m\\omega}{2\\hbar}x^2 \\\\\r\n\t\\Aboxed{\\psi_0 &= A \\exp \\left(-\\frac{m\\omega}{2\\hbar}x^2\\right)} \\numberthis\r\n\\end{align*}\r\n\r\nWe have to normalize the wave function the same way we always do, which allows us to solve for $A$ as\r\n\\begin{align*}\r\n\t\\int_{-\\infty}^{\\infty} \\abs{\\psi_0}^2 \\dd{x} &= 1 \\\\\r\n\t\\abs{A}^2 \\int_{-\\infty}^{\\infty} \\exp \\left(-\\frac{m\\omega}{\\hbar} x^2 \\right) \\dd{x} &= 1 \\\\\r\n\t\\abs{A}^2 \\sqrt{\\frac{\\pi\\hbar}{m\\omega}} &= 1  \\tag{We use $\\displaystyle\\int_{-\\infty}^{\\infty}e^{-ax^2} \\dd{x} = \\sqrt{\\frac{\\pi}{a}}$}\\\\\r\n\t\\Aboxed{A &= \\left(\\frac{m\\omega}{\\pi\\hbar}\\right)^{1/4}} \\numberthis\r\n\\end{align*}\r\n\r\nCombining these two results finally gives us\r\n\\begin{tcolorbox}[title = Ground state for the QHO] \\vspace{-2ex}\r\n\t\\begin{equation}\r\n\t\t\\psi_0 = \\left(\\frac{m\\omega}{\\pi\\hbar}\\right)^{1/4} \\exp \\left(-\\frac{m\\omega}{2\\hbar}x^2\\right) \\label{eq:qho-ground}\r\n\t\\end{equation}\r\n\\end{tcolorbox}\r\n\r\nOne can easily substitute this back into the \\Sch\\ equation to verify this does indeed solve the differential equation. A sketch of this wave function has a Gaussian shape within the boundary of the potential with probability maximized at the center of the quadratic potential, analogous to the equilibrium position of the effective mass on a spring (Figure~\\ref{fig:qho-ground}). The key difference between this state and its classical analogue is that the quantum ground state has non-zero energy.\r\n\r\n\\begin{figure}[!h]\r\n\t\\centering\r\n\t\\includegraphics[width=0.38\\linewidth]{qho-ground}\r\n\t\\caption{A sketch of the ground state of the particle inside the parabolic potential. The wave function has a Gaussian profile within the parabolic potential and it is centered about the minimum.}\r\n\t\\label{fig:qho-ground}\r\n\\end{figure}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n\\subsection{Zero-point energy}\r\nWhat is the energy of the particle in this ground state? One can substitute Equation~\\ref{eq:qho-ground} into the differential equation and solve for $E_0$, or explicitly solve Equation~\\ref{eq:sch-qho} when $n=0$. Both approaches work, and we will proceed with the latter approach to obtain\r\n\\begin{align*}\r\n\t\\hbar\\omega \\left(\\ad a + \\frac{1}{2} \\right)\\psi_0 &= E_0\\psi_0 \\\\\r\n\t\\frac{\\hbar\\omega}{2}\\psi_0 &= E_0\\psi_0 \\tag{since $a\\psi_0=0$}\r\n\\end{align*}\r\nwhich gives the energy for the ground state as\r\n\\begin{tcolorbox}[title = Zero-point energy] \\vspace{-2ex}\r\n\t\\begin{equation}\r\n\t\tE_0 = \\frac{\\hbar\\omega}{2} \\label{eq:zpe}\r\n\t\\end{equation}\r\n\\end{tcolorbox}\r\n\r\nThis ground state energy is commonly referred to as \\textbf{zero-point energy}, a concept that we've been alluding to previously. The zero-point energy arises due to quantum mechanical fluctuations between energy states that occur even at absolute zero, which explains, for example, why liquid helium does not freeze at standard pressure regardless of temperature.\\footnote{Physicists Richard Feynman and John Wheeler have calculated that the zero-point energy in a vacuum the size of a light bulb is enough to boil all the world's oceans. See M. Pilkington, \\href{https://www.theguardian.com/education/2003/jul/17/research.highereducation}{\\emph{The Guardian}} (2003).} Although it fits the contexts of the models presented in this text, the physical manifestations of zero-point energy are still poorly understood and are an active area of research. \\par \r\n\r\nNow we leave it as an exercise to the reader to show, using a similar procedure as above, that if $\\psi_n$ is a solution with energy $E_n$, then $\\ad\\psi_n$ is also a solution with energy $E_n+\\hbar\\omega$ and thus $\\ad$ behaves as a raising operator. Given this, we can now essentially reconstruct all solutions at least in principle by simply applying the raising operator to the known ground state solution. By this procedure, we can write down a very simple result for the allowed energy states:\r\n\\begin{tcolorbox}[title = Allowed energy states of the QHO] \\vspace{-2ex}\r\n\t\\begin{equation}\r\n\t\tE_n = \\hbar\\omega\\left(n + \\frac{1}{2}\\right) \\label{eq:estates-qho}\r\n\t\\end{equation}\r\n\\end{tcolorbox}\r\n\r\nWe see that like the particle in a box, the energy states of the QHO are quantized and indexed by the quantum number $n$. Where the two differ is that while the energy levels of the particle in a box scale as $n^2$, the energy levels here scale linearly in $n$, which means that these discrete energy levels are equally spaced by $\\hbar\\omega$. \\par \r\n\r\nNow, you might be asking yourself if this procedure really generates all the possible solutions or just a subset of them. The answer is that it really does get them all! If there was some other state $\\psi_m$ not generated by applying the raising operator successively from the ground state, one could simple lower this state by successively applying the lowering operator until eventually one arrives at the ground state satisfying $a\\psi_0 = 0$. But this is just the ground state we've already uniquely identified and indicates that there are no other unique solutions of the \\Sch\\ equation that we've somehow missed.\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n\\section{Additional properties}\r\n\\subsection{Bra-ket notation} \\label{sec:braket}\r\nWe will start by formally introducing some notation to help us from here on out. Back in Chapter~\\ref{ch:intro}, we used $\\ket{S}$ as a way to describe quantum states. This is standard \\textbf{bra-ket notation}, where $\\ket{S}$ is called the \\textbf{ket} and represents the state of the quantum system, whether it's the momentum, position, or something else. Every ket has an associated \\emph{dual} or ``left half'' called the \\textbf{bra}, written as $\\bra{S}$. Energy states can be expressed as both $\\ket{\\Psi_0}$ or just $\\ket{0}$ for short. \\par \r\n\r\nAs you can probably imagine, the bra and ket can be combined together. Specifically, if we have $\\bra{\\Psi_m}$ and $\\ket{\\Psi_n}$ representing two quantum states, then this leads to\r\n\\begin{tcolorbox}[title = Bra-ket inner product] \\vspace{-2ex}\r\n\t\\begin{equation}\r\n\t\t\\braket{\\Psi_m}{\\Psi_n} = \r\n\t\t\\int_{-\\infty}^{\\infty} \\Psi_m^*\\Psi_n \\dd{x} \\label{eq:bk-int}\r\n\t\\end{equation}\r\n\\end{tcolorbox}\r\n\r\nEssentially this notation is representing an \\textbf{inner product}, which is a generalization of the dot product that you have seen in previous math classes. Indeed, one can think of a bra as a row vector that is multiplying a column vector ket. Furthermore, changing a quantum state from a bra to a ket (e.g. $\\bra{f} \\rightarrow \\ket{f}$) is equivalent to taking the conjugate transpose. Working with this vector notation, we can also easily to apply operators by multiplying it to the left of a ket, e.g.\r\n\\begin{equation*}\r\n\t\\hat{H} \\ket{\\Psi} = E\\ket{\\Psi} \r\n\\end{equation*}\r\nwhere you can treat $\\hat{H}$ as a $n\\times n$ matrix and $E$ as a constant.\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n\\subsection{Expected value}\r\nSince we work with probabilities in quantum mechanics, it is only suitable (and perhaps even delayed at this point) that we cover the concept of \\textbf{expectation}, which can be thought of as the \\textbf{average} or \\textbf{mean} value. Given a quantity $x$, we denote the expected value of $x$ by $\\expval{x}$. In general, the average value of some function of $x$ is given by \r\n\\begin{equation}\r\n\t\\expval{g(x)} = \\sum_{i=1}^{\\infty} g(x_i) p(x_i)\r\n\\end{equation}\r\nwhere $p(x_i)$ is the probability of obtaining $g(x_i)$. This is the case for \\emph{discrete} variables, such as the expected value of the roll of a die. For \\emph{continuous} variables, we can't use a single probability for a point (it would be equal to zero) but rather a \\textbf{probability density} $\\rho(x)$ that can be applied over an interval. You're already experienced with probability densities since you've worked with the modulus squared of the wave function. Now our definition for the expectation of a function of a continuous variable becomes\r\n\\begin{equation}\r\n\t\\expval{f(x)} = \\int_{-\\infty}^{\\infty} f(x) \\rho(x) \\dd{x}\r\n\\end{equation}\r\n\r\nWhen we're working with operators or physical observables, the expectations turn nicely into \r\n\\begin{equation}\r\n\t\\expval{f(x)} = \\int_{-\\infty}^{\\infty} \\Psi^* f(x) \\Psi \\dd{x} = \\mel{\\Psi}{f}{\\Psi} \\label{eq:expval}\r\n\\end{equation}\r\n\r\nNow, a measurement of the energy or momentum must return a real outcome, which means $\\expval{f(x)}=\\expval{f(x)}^*$. This can be rewritten as\r\n\\begin{equation*}\r\n\t\\int_{-\\infty}^{\\infty} \\Psi^* f(x) \\Psi \\dd{x} = \\left( \\int_{-\\infty}^{\\infty} \\Psi^* f(x) \\Psi \\dd{x} \\right)^* = \\int_{-\\infty}^{\\infty} \\left( f(x) \\Psi\\right)^* \\Psi \\dd{x}\r\n\\end{equation*}\r\n\r\nor\r\n\\begin{equation}\r\n\t\\braket{\\Psi}{f\\Psi} = \\braket{f\\Psi}{\\Psi} \\label{eq:hermitian}\r\n\\end{equation}\r\n\r\nThis condition defines the operator $f$ as \\textbf{Hermitian}, which gives real values for the expectation and has real eigenvalues among its many nice properties. As a result, all quantum mechanical operators for physical observables are Hermitian, e.g. momentum, Hamiltonian, position, etc.\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n\\subsection{Hermitian conjugates}\r\nWe show that $a$ and $\\ad$ are \\textbf{Hermitian conjugates} (or \\textbf{Hermitian adjoints}), which are operators that are related by\r\n\\begin{tcolorbox}[title = Hermitian conjugates] \\vspace{-2ex}\r\n\t\\begin{equation}\r\n\t\t\\braket{f}{ag} = \\braket{\\ad f}{g} \\label{eq:h-conj}\r\n\t\\end{equation}\r\n\\end{tcolorbox}\r\nfor arbitrary $f$ and $g$. If we go back to the integral definition in Equation~\\ref{eq:bk-int}, we get that\r\n\\begin{equation*}\r\n\t\\int_{-\\infty}^{\\infty} f^*ag \\dd{x} = \\int_{-\\infty}^{\\infty} (\\ad f)^*g \\dd{x}\r\n\\end{equation*}\r\n\r\nwhich says that $a$ operating on $g$ must give the same result for the integral as $\\ad$ operating on $f$. To prove this, we will use the differential form of the operator $a$ and integrate by parts.\r\n\\begin{align*}\r\n\t\\braket{f}{ag} &= \\int_{-\\infty}^{\\infty} f^* \\left(x + \\frac{\\hbar}{m\\omega} \\dv{x} \\right)g \\dd{x} \\\\\r\n\t&= \\int_{-\\infty}^{\\infty} f^*xg \\dd{x} + \\frac{\\hbar}{m\\omega} \\int_{-\\infty}^{\\infty} f^* \\dv{g}{x} \\dd{x} \\\\\r\n\t&= \\int_{-\\infty}^{\\infty} f^*xg \\dd{x} + \\frac{\\hbar}{m\\omega} \\left[ \\cancel{f^*g} \\bigg|_{-\\infty}^{\\infty} - \\int_{-\\infty}^{\\infty} \\dv{f^*}{x} g \\dd{x} \\right] \\\\\r\n\t&= \\int_{-\\infty}^{\\infty} \\left[ \\left(x - \\frac{\\hbar}{m\\omega} \\dv{x}\\right) f \\right]^* g \\dd{x} \\\\\r\n\t&= \\int_{-\\infty}^{\\infty} \\left(\\ad f\\right)^*g \\dd{x} \\\\\r\n\t&= \\braket{\\ad f}{g} \r\n\\end{align*}\r\n\r\nIt is also true that\r\n\\begin{equation*}\r\n\t\\braket{f}{\\ad g} = \\braket{af}{g}\r\n\\end{equation*}\r\n\r\nWe note here that even though the ladder operators are Hermitian conjugates, their product, which appears in the Hamiltonian, \\emph{is} a Hermitian operator.\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n\\subsection{Scaling factor}\r\nWe already know that the raising and lowering operators generate new solutions of the \\Sch\\ equation. But this is defined only up to a proportionality factor. Given a normalized solution like $\\psi_0$ found above, how do we find the higher order solutions exactly? We could normalize each one by brute force, but there is a simpler result. We start by saying that \r\n\\begin{equation*}\r\n\t\\ad \\ket{\\psi_n} = c_n \\ket{\\psi_{n+1}}\r\n\\end{equation*}\r\n\r\nNext, we can apply the result of Equation~\\ref{eq:h-conj} in a clever way and note that\r\n\\begin{equation*}\r\n\t\\braket{\\ad \\psi_n}{\\ad \\psi_n} = \\braket{a\\ad \\psi_n}{\\psi_n}\r\n\\end{equation*}\r\n\r\nThen, if we take a closer look at our two expressions for the allowed energy states of the QHO (Equation~\\ref{eq:sch-qho} and~\\ref{eq:estates-qho}), we see that it must be the case that \r\n\\begin{align}\r\n\t\\ad a \\psi_n &= n\\psi_n \\label{eq:ada-prop} \\\\\r\n\ta \\ad \\psi_n &= (\\ad a + 1)\\psi_n = (n+1)\\psi_n \\label{eq:aad-prop}\r\n\\end{align} \r\n\r\nWe can combine these results to obtain\r\n\\begin{equation*}\r\n\t\\braket{\\ad \\psi_n}{\\ad \\psi_n} = \\braket{a\\ad \\psi_n}{\\psi_n} = (n+1) \\braket{\\psi_n}{\\psi_n} = \\abs{c_n}^2\\braket{\\psi_{n+1}}{\\psi_{n+1}}\r\n\\end{equation*}\r\n\r\nSince $\\psi_n$ and $\\psi_{n+1}$ are normalized, it follows that $\\abs{c_n}^2 = n+1$, and we have\r\n\\begin{tcolorbox}[title = Raising operator proportionality] \\vspace{-2ex}\r\n\t\\begin{equation}\r\n\t\t\\ad \\psi_n = \\sqrt{n+1} \\psi_{n+1} \\label{eq:ad-prop}\r\n\t\\end{equation}\r\n\\end{tcolorbox}\r\n\r\nWe will leave it as an exercise to the reader to derive (in essentially the same fashion) the proportionality coefficient for the lowering operator, which is \r\n\\begin{equation}\r\n\ta \\psi_n = \\sqrt{n} \\psi_{n-1} \\label{eq:a-prop}\r\n\\end{equation}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n\\subsection{Orthogonality}\r\nAs you may have guessed by now, the stationary state solutions to the QHO are orthogonal,\\footnote{In fact they also form an orthonormal basis.} which means that \r\n\\begin{equation}\r\n\t\\braket{\\psi_m}{\\psi_n} = \\int_{-\\infty}^{\\infty} \\psi_m^*\\psi_n \\dd{x} = \\delta_{mn} \\label{eq:ortho_qho}\r\n\\end{equation}\r\n\r\nWe can prove this using Equation~\\ref{eq:h-conj} and~\\ref{eq:ada-prop}. First, the second equation gives us\r\n\\begin{equation}\r\n\t\\braket{\\psi_m}{\\ad a \\psi_n} = \\braket{\\psi_m}{n\\psi_n} = n\\braket{\\psi_m}{\\psi_n} \\label{eq:qho-orth1}\r\n\\end{equation}\r\n\r\nHowever, we can also apply the first equation twice to the left hand side and obtain\r\n\\begin{equation}\r\n\t\\braket{\\psi_m}{\\ad a \\psi_n} = \\braket{a \\psi_m}{a \\psi_n} = \\braket{\\ad a \\psi_m}{\\psi_n} = m\\braket{\\psi_m}{\\psi_n} \\label{eq:qho-orth2}\r\n\\end{equation}\r\n\r\nPutting Equation~\\ref{eq:qho-orth1} and~\\ref{eq:qho-orth2} together, one obtains\r\n\\begin{equation*}\r\n\t(m-n)\\braket{\\psi_m}{\\psi_n} = 0\r\n\\end{equation*}\r\n\r\nwhich shows that if $m \\neq n$, then \r\n\\begin{equation*}\r\n\t\\braket{\\psi_m}{\\psi_n} = \\int_{-\\infty}^{\\infty} \\psi_m^*\\psi_n \\dd{x} = 0\r\n\\end{equation*}\r\nand the orthogonality condition is satisfied. \r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n\\section[Applications]{Applications of the QHO}\r\nBy now we've seen just how powerful the QHO model is and how useful some of these properties are. The existence of an exact, analytical solution to the QHO makes it a powerful framework for developing more advanced theories to analyze complex quantum mechanical systems. We mentioned at the beginning of this chapter how the QHO could be used to model subatomic particles and the forces between atoms, but a proper treatment involves delving a little deeper into \\textbf{quantum field theory} (QFT), which is a framework that is partially derived from the concepts presented in this chapter. Rather than cramming this rich topic into a section here, we will instead be devoting the entire next chapter to QFT and combining the results from QFT and the QHO to analyze vibrational modes in solids called \\textbf{phonons}. Stay tuned! \\par \r\n\r\n% TODO: Consider adding power series to Appendix C?\r\nFor the time being, however, let's briefly revisit the wave function solutions we derived earlier. We sidestepped a lot of the ugly algebra by employing the ladder operators method, but I would be doing you a disservice (particularly if you continue to study quantum mechanics in a different field like physics or electrical engineering), if I didn't at least \\emph{mention} the analytic method using \\textbf{power series}.\\footnote{We will skip all the details here, but there's a thorough derivation in Griffiths, Chapter 2.3.} When we work out the math, we arrive at the following expression for the stationary states of the QHO:\\footnote{I encourage you to derive another expression for the $n$th stationary state using just the ladder operators! \\emph{Hint}: The expression is far more concise, albeit recursive.} \r\n\\begin{equation}\r\n\t\\psi_n(x) = \\left(\\frac{m\\omega}{\\pi\\hbar}\\right)^{1/4} \\frac{1}{\\sqrt{2^n \\cdot n!}} H_n \\left(\\sqrt{\\frac{m\\omega}{\\hbar}}x\\right) \\exp \\left(-\\frac{m\\omega x^2}{2\\hbar}\\right) \\label{eq:pow-qho}\r\n\\end{equation}\r\n\r\nwhere $H_n$ are the \\textbf{Hermite polynomials}, given explicitly and recursively by\r\n\\begin{align*}\r\n\tH_n(z) &= (-1)^n e^{z^2} \\dv[n]{z} \\left( e^{-z^2} \\right) \\\\\r\n\tH_n(z) &= 2zH_{n-1}(z) - 2(n-1)H_{n-2}(z)\r\n\\end{align*}\r\n\r\nMore concretely, the first few Hermite polynomials are\r\n\\begin{align*}\r\n\tH_0(z) &= 1 \\\\\r\n\tH_1(z) &= 2z \\\\\r\n\tH_2(z) &= 4z^2-2 \\\\\r\n\tH_3(z) &= 8z^3 - 12z \\\\\r\n\tH_4(z) &= 16z^4 - 48z^2 + 12\r\n\\end{align*}\r\n\r\nThe benefit of this method is that we have a closed-form expression for the wave function at any energy level. We already saw what the ground state $\\psi_0$ looked like, which had maximum amplitude at the center of the quadratic potential, so now we plot $\\abs{\\psi_{50}}$ in Figure~\\ref{fig:qho-50}.\r\n\r\n\\begin{figure}[!h]\r\n\t\\centering\r\n\t\\includegraphics[width=0.5\\linewidth]{hermite}\r\n\t\\caption{The probability density function of the QHO with $n=50$ contains nodes where the probability of finding the particle is zero. The general profile also resembles the probability density of a classical harmonic oscillator.}\r\n\t\\label{fig:qho-50}\r\n\\end{figure}\r\n\r\nThere are two interesting properties of this probability density function. First, notice that there are nodes where the probability of finding the particle is zero, just like the particle in a box. This is true of all energy states above the ground state. Second, we notice that the profile looks very different from the ground state; namely, the regions of largest probability are at the sides instead of the middle. This actually corresponds to a classical harmonic oscillator if you think about it---a moving mass on a spring with high elastic potential energy will spend the longest amount of time when it's most stretched out or most compressed (it moves the slowest as it changes direction), whereas it will move the fastest when it passes the equilibrium position. Thus we see a nice analogy where the high-energy quantum mechanical system begins to exhibit classical behavior.\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n\\section{Summary}\r\nWhew! This was a lengthy chapter that was heavy on operators and bra-ket notation. Using ladder operators, we derived the ground state of the quantum harmonic oscillator, from which one can theoretically construct all the stationary states. We also discovered zero-point energy and determined that the allowed energies of the QHO are evenly spaced by $\\hbar\\omega$. I hope you found the derivations conducive towards your learning, and please come talk to me in office hours if something is unclear! Students find it helpful to try deriving some of these equations on their own to ensure full understanding. In the next chapter we will explore quantum field theory as an extension of the concepts presented here.\r\n\r\n%} % for doublespacing\r\n%\\end{document}", "meta": {"hexsha": "d5ad18873e4f1b941019ca5041afb8b6f2e201df", "size": 33879, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/chapter_6.tex", "max_stars_repo_name": "Enze-Chen/mse_142_cr", "max_stars_repo_head_hexsha": "a98585b32f26f6c189b96345d9cc1e9727156268", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-13T17:08:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-13T17:08:24.000Z", "max_issues_repo_path": "tex/chapter_6.tex", "max_issues_repo_name": "Enze-Chen/mse_142_cr", "max_issues_repo_head_hexsha": "a98585b32f26f6c189b96345d9cc1e9727156268", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/chapter_6.tex", "max_forks_repo_name": "Enze-Chen/mse_142_cr", "max_forks_repo_head_hexsha": "a98585b32f26f6c189b96345d9cc1e9727156268", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 76.649321267, "max_line_length": 951, "alphanum_fraction": 0.6978364178, "num_tokens": 9956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.32030013280899805}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\subsection{A decay example}\n\n\\marginpar{Wednesday\\\\ 2020-4-1, \\\\ compiled \\\\ \\today}\n\nThis and next week we will finish the introduction to particle physics, then we will start discussing the open problems in cosmology and astroparticle physics. \n\nWe consider the following process: \n%\n\\begin{align}\ne^{+} e^{-} \\to \\mu^- \\mu^+\n\\,,\n\\end{align}\n%\nwhere the mass of the electron is around \\(m_e \\sim \\SI{.5}{MeV}\\), the mass of the muon is around \\(m_{\\mu } \\sim \\SI{100}{MeV}\\). \n\nDigression: there are different families of fermions (leptons and quarks), the first encompasses \\(e, \\nu_{e}, u, d\\); the second encompasses \\(\\mu, \\nu_{\\mu }, c, s\\) and the third encompasses \\(\\tau, \\nu_{\\tau }, t, b\\). \nThe characteristics of the four members of the family are well-known, and between families the characteristics are the same: the only thing which varies between the families is the mass. \n\nSo, Rabi famously asked ``who ordered the fermions''? \n\nComing back to our problem: the state \\(\\ket{e^{+}e^{-}}\\) must be annihilated by the EM current \\(j^{\\mu }_{EM} = \\overline{\\psi}_e \\gamma^{\\mu } \\psi_e \\); it is then converted to a photon, which however is not on mass shell --- it cannot be, since its momentum must be that of the electron-positron pair, so a timelike vector. \nIt is then called a \\emph{virtual photon}: it can exist, as long as it does so for a short time. \n\nThen, this photon decays to a muon-antimuon pair: then we will have a term \\(\\bra{\\mu^- \\mu^+} j^{\\mu }_(\\mu )\\). The index between parenthesis is not a Lorentz one, it just means that this is a muonic current, different from the electronic one.\n\nLet us call \\(p_{-}\\) and \\(p_{+}\\) the momenta of the electron and positron, and \\(p^{\\prime }_{-}\\) and \\(p^{\\prime }_{+}\\) those of the muon and antimuon. \n\nThe momentum \\(q\\) of the photon cannot have \\(q^2  =0 \\), but this is fine: it is just an excitation. \n\nThe physics of the process is all contained in the matrix element \\(\\mathcal{M}(e^{+}e^{-} \\to \\mu^+ \\mu^-)\\). How do we calculate it? We will not go into details here, but it can be directly derived from the Feynman diagram of the interaction \\cite[sec.\\ 4.1.2]{tissinoTheoreticalPhysicsNotes2020}: we have \n%\n\\begin{align}\n\\mathcal{M}(e^{+}e^{-} \\to \\mu^+ \\mu^-) = \n(-e)\n\\bra{\\mu^- \\mu^+} j^{\\mu } \\ket{0}\n\\frac{1}{q^2}\n(-e)\n\\bra{0} j_{\\mu } \\ket{e^{+} e^{-}}\n\\,,\n\\end{align}\n%\nwhere the \\(-e\\) factor is because of the EM coupling to the photon. \nThe Breit-Wigner factor looks like \n%\n\\begin{align}\n\\frac{1}{P^2-M_R^2}\n\\,,\n\\end{align}\n%\nbut for the photon we have no mass, therefore we only get a factor \\(1/q^2\\). \n\nThe Feynman diagrams are just a way to collect the Feynman rules needed to compute the process, they are not meant to represent how the process ``looks like''. \n\nLet us take the ultrarelativistic limit, in which the energy of the process is much larger than the muon's mass. \nIf this is the case, then we can set \\(m_e = m_\\mu  = 0\\). \n\nLet us consider the Dirac equation, in the case in which the mass \\(m\\) is equal to zero: then we get \n%\n\\begin{align}\ni \\slashed{\\partial} \\psi = 0\n\\,.\n\\end{align}\n\nLet us use the chiral representation for the \\(\\gamma \\) matrices: \n%\n\\begin{subequations}\n\\begin{align}\n\\gamma^{\\mu } = \\left[\\begin{array}{cc}\n0 & \\sigma^{\\mu } \\\\ \n\\overline{\\sigma}^{\\mu } & 0\n\\end{array}\\right] \n\\,,\n\\end{align}\n\\end{subequations}\n%\nwhere we mean by \\(\\sigma^{0} = \\mathbb{1}\\), \\(\\sigma^{\\mu } = (\\sigma^{0}, \\sigma^{i})\\) and \\(\\overline{\\sigma}^{\\mu } = (\\sigma^{0}, - \\sigma^{i})\\).\n\nLet us then split the spinor \\(\\psi \\) into \n%\n\\begin{subequations}\n\\begin{align}\n\\psi = \\left[\\begin{array}{c}\n\\psi_{L} \\\\ \n\\psi_{R}\n\\end{array}\\right]\n\\,,\n\\end{align}\n\\end{subequations}\n%\nwhere \\(\\psi_{L, R}\\) are two-component spinors. This allows us to write two two-dimensional equations: \n%\n\\begin{subequations}\n\\begin{align}\ni \\overline{\\sigma}^{\\mu } \\partial_{\\mu } \\psi_{L} &= 0 \\\\\ni \\sigma^{\\mu } \\partial_{\\mu } \\psi_{R} &= 0\n\\,,\n\\end{align}\n\\end{subequations}\n%\nwhere we get no interaction terms between the two: if we have no mass the equations decouple. \n\nWe can do the same thing if the Dirac equation is coupled to the EM field, since the issue is with the structure of the \\(\\gamma^{\\mu }\\), it does not matter if we have \\(\\gamma^{\\mu } \\DD_{\\mu }\\) or \\(\\gamma^{\\mu } \\partial_{\\mu }\\); however we will write the decoupled solution for now.\n\nSo, for the right-handed spinor we have:\n%\n\\begin{align}\n\\qty(i \\partial_{t} + i \\vec{\\sigma} \\cdot \\vec{\\partial}) \\psi_{R}\n\\,,\n\\end{align}\n%\nwhich is solved by a plane wave: \n%\n\\begin{align}\n\\psi_{R} = u_R (p) e^{-iEt + i \\vec{p} \\cdot \\vec{x}}\n\\,.\n\\end{align}\n\nLet us suppose the equation reads \n%\n\\begin{subequations}\n\\begin{align}\n\\qty(E - p \\sigma^{3}) u_R = \\left[\\begin{array}{cc}\nE-p & 0 \\\\ \n0 & E+p\n\\end{array}\\right] u_{R} = 0\n\\,,\n\\end{align}\n\\end{subequations}\n%\nso we must have two solutions: they look like \n%\n\\begin{subequations}\n\\begin{align}\n\\psi_{R} = \\left[\\begin{array}{c}\n1 \\\\ \n0\n\\end{array}\\right] e^{-i Et + i E x_3 }\n\\qquad \\text{and} \\qquad\n\\psi_{R} = \\left[\\begin{array}{c}\n0 \\\\ \n1\n\\end{array}\\right] e^{+i Et + i E x_3 }  \n\\,.\n\\end{align}\n\\end{subequations}\n\nThe solution \\(\\psi_{R} \\sim \\exp(-iEt + i E x_3)\\) describes a right-handed electron with spin eigenvalue \\(+1/2\\) along the direction of motion (this is called the \\emph{helicity} \\cite[sec.\\ 1.4.9]{tissinoTheoreticalPhysicsNotes2020})\n\nOn the other hand, the solution \\(\\psi_{R} \\sim \\exp(iEt + iE x_3)\\) describes a right-handed electron with spin eigenvalue \\(s = - 1/2\\). \n\nOur quantum field operator \\(\\psi_{R}\\) acts as on the right by destroying a right-handed electron:\n%\n\\begin{align}\n\\bra{0}\\psi_{R} \\ket{e^{-}_{R} (p)} = u_R(p) e^{-ipx}\n\\,.\n\\end{align}\n\nThen, we can have it acting on the left by destroying a left-handed positron:\n%\n\\begin{align}\n\\bra{e^{+}_{L}(p)} \\psi_{R} \\ket{0} = v_L (p) e^{+ipx}\n\\,.\n\\end{align}\n\nIf we were to repeat the analysis for the other spinor, we would get the specular result. \n\nThe Lagrangian can be written as \n%\n\\begin{align}\n\\mathscr{L} = \n\\psi_R ^\\dag \\qty(i \\sigma \\cdot \\partial) \\psi_{R}+\n\\psi_L ^\\dag \\qty(i \\overline{\\sigma} \\cdot \\partial) \\psi_{L}\n- m \\qty( \\psi ^\\dag _R \\psi_{L}\n+ \\psi ^\\dag_L \\psi_{R})\n\\,,\n\\end{align}\n%\nso the coupling between the left and right handed fermions depends on the mass, if we are in a situation in which \\(T \\gg m\\) they effectively decouple.\n\n\nIn order to describe this spin, we introduce the helicity quantum number, which is defined as \n%\n\\begin{align}\nh = \\hat{p} \\cdot \\vec{s}\n\\,,\n\\end{align}\n%\nthe projection of the spin along the direction of motion. \nFor \\(\\psi_{R}\\), we have the \\((1,0)\\) state with helicity \\(h = 1/2\\), while the state \\((0,1)\\) is a positron with helicity \\(h = - 1/2\\). \n\nIf \\(m=0\\), then helicity is exactly conserved. At high energies, it is suppressed by a factor \\(m / E\\). \n\nLet us compute the cross section: we must calculate  \n%\n\\begin{align}\n\\bra{0} j^{\\mu } \\ket{e^{-}_{R} (p_{-}) e^{+}_{L} (p_+)} \n\\,,\n\\end{align}\n%\nwhere we have a term \\(j^{\\mu } = \\overline{\\psi} \\gamma^{\\mu } \\psi = \\psi ^\\dag \\gamma^{0} \\gamma^{\\mu } \\psi \\); the term \\(\\gamma^{0} \\gamma^{\\mu }\\) reads \n%\n\\begin{align}\n\\gamma^{0} \\gamma^{\\mu } = \\left[\\begin{array}{cc}\n0 & \\mathbb{1} \\\\ \n\\mathbb{1} & 0\n\\end{array}\\right]\n\\left[\\begin{array}{cc}\n0 & \\sigma^{\\mu } \\\\ \n\\overline{\\sigma}^{\\mu } & 0\n\\end{array}\\right] \n= \\left[\\begin{array}{cc}\n\\overline{\\sigma}^{\\mu } & 0 \\\\ \n0 & \\sigma^{\\mu }\n\\end{array}\\right]\n\\,,\n\\end{align}\n%\nso we get \n%\n\\begin{align}\nj^{\\mu } = \\psi_{L} ^\\dag \\overline{\\sigma}^{\\mu } \\psi_{L} + \\psi_{R} ^\\dag \\sigma^{\\mu } \\psi_{R}\n\\,.\n\\end{align}\n\nWe describe the process in the center-of-mass frame, and we choose to align the axes so that the electron and positron have momenta \\(p^{\\mu } = (E, 0, 0, \\pm E)\\) respectively (minus for the positron).\n\nThe wavefunction \\(\\psi ^\\dag_{R}\\) annihilates the positron \\(e^{+}_{L}\\) yielding a term \\(v ^\\dag _L (p_+)\\), the wavefunction \\(\\psi_{R}\\) annihilates the electron \\(e^{-}_{R}\\) yielding a term \\(u_R (p_-)\\). \n\nThen, we are left with  \n%\n\\begin{align}\nv_L ^\\dag (p_+) \\sigma^{\\mu } u_R (p_-) &= \\sqrt{2E} \n\\left[\\begin{array}{cc}\n0 & 1\n\\end{array}\\right]\n(\\mathbb{1}, \\vec{\\sigma}) \\sqrt{2E}\n\\left[\\begin{array}{c}\n1 \\\\ \n0\n\\end{array}\\right]  \\\\\n&= 2E (0, 1, i, 0)^{\\mu }\n\\,,\n\\end{align}\n%\nso if we define the vector \\(\\vec{\\epsilon}_{+} = (\\hat{1} + i \\hat{2}) / \\sqrt{2}\\) we can write \n%\n\\begin{align}\n\\bra{0}\nj^{\\mu } \n\\ket{e^{-}_R (p_-) e^{+}_L (p_+)}\n= 2 E \\sqrt{2} \\qty(0, \\vec{\\epsilon}_{+})^{\\mu }\n\\,,\n\\end{align}\n%\nwhile we would have \n%\n\\begin{align}\n\\bra{0}\nj^{\\mu } \n\\ket{e^{-}_L (p_-) e^{+}_R (p_+)}\n= - 2 E \\sqrt{2} \\qty(0, \\vec{\\epsilon}_{-})^{\\mu }\n\\,,\n\\end{align}\n%\nwith \\(\\vec{\\epsilon}_{-} =(\\hat{1} + i \\hat{2}) / \\sqrt{2} \\). \n\nOn the other hand, the terms \\(e_{R}^{-} e_{R}^{+}\\) and \\(e_{L}^{-} e_{L}^{+}\\) do not contribute (in our \\(m = 0\\) approximation).\n\nThe muons are massless fermions as well in our treatment, so we get analogous terms: \n%\n\\begin{align}\n\\bra{\\mu^-_R (p'_-) \\mu^+_L (p'_+)} j^{\\mu } \\ket{0} &= 2E \\sqrt{2} \\qty(0, \\vec{\\epsilon}^{\\prime *}_+)^{\\mu } \\\\\n\\bra{\\mu^-_L (p'_-) \\mu^+_R (p'_+)} j^{\\mu } \\ket{0} &= - 2E \\sqrt{2} \\qty(0, \\vec{\\epsilon}^{\\prime *}_-)^{\\mu }\n\\,,\n\\end{align}\n%\nso in the end we find \n%\n\\begin{align}\n\\mathcal{M} (e^{-}_{L} e^{+}_{R} \\to \\mu^-_R \\mu^+_L) \n&= - \\frac{e^2}{q^2} 2 (2E)^2 \n\\vec{\\epsilon}^{\\prime *}_{+} \\cdot \\vec{\\epsilon}_{+}  \\\\\n&= - 2 e^2 \\vec{\\epsilon}^{\\prime *}_{+} \\cdot \\vec{\\epsilon}_{+}\n\\,,\n\\end{align}\n%\nsince \\(q  =2 E\\). \nThe scalar product here depends on the direction of emission of the muons in the center of mass frame, \\(\\theta \\); we find the absolute value \\(\\abs{\\mathcal{M}}^2 = e^{4} (1 \\pm \\cos \\theta )^2\\), depending on whether we are looking at an \\(LR \\to LR\\) process or \\(LR \\to RL\\) process. The unpolarized (spin-averaged) differential cross section comes out to be: \n%\n\\begin{align}\n\\dv{\\sigma }{\\cos \\theta } = \\frac{1}{2} \\frac{\\pi \\alpha^2}{2 E_{CM}^2} \\qty(1 + \\cos^2\\theta )\n\\,,\n\\end{align}\n%\nwhich can be integrated across the sphere to get the total cross section for the process \\(e^{-} e^{+} \\to \\mu^- \\mu^+\\): \n%\n\\begin{align}\n\\sigma = \\frac{4 \\pi }{3} \\frac{\\alpha^2}{E^2_{CM}}\n\\,.\n\\end{align}\n\nWe could have guessed the dependence on \\(\\alpha^2  / E^2_{CM}\\), but for the numerical factor we needed to do the full computation. \nThis is because the cross section is a length square, so it must depend on the inverse square of our only energy parameter, \\(E_{CM}\\). \n\nAlso, the coupling was fixed: we are working in QED, so we only have a coupling constant: \\(e\\), so we will have terms \\(e^2 / 4 \\pi = \\alpha \\) inside of \\(\\mathcal{M}\\), so we will get \\(\\alpha^2\\) inside of \\(\\abs{\\mathcal{M}}^2\\). \nThe \\(4 \\pi \\)s will cancel because of the phase-space angular integrals.\n\nOnce we have done this, can we generalize it? suppose we want to compute the cross section \\(\\sigma (e^{+}e^{-} \\to \\text{hadrons})\\). How could we do it?\n\nWe can make a similar kind of reasoning: the process will look like \\(e^{-} e^{+} \\to q \\overline{q}\\), and while the coupling for the first vertex in the Feynman diagram will be \\(-e\\) the one for the second vertex will look like \\(Q_q\\), the charge of these quarks.\nWe calculate the unpolarized cross section, counting all the quarks which can be produced at a fixed COM energy: we assume \\(E \\sim \\SI{100}{GeV}\\), so all the quarks except for the top are candidates; so the computation goes: \n%\n\\begin{align}\n\\frac{\\sigma (e^{+} e^{-} \\to q \\overline{q})}{\\sigma (e^{+ }e^{-} \\to \\mu^+ \\mu^-)} \\approx \\sum _{q} Q_q^2 = \\underbrace{2 \\frac{4}{9} }_{u, c} + \\underbrace{3 \\frac{1}{9}}_{d, s, b}\n= \\frac{11}{9}\n\\,.\n\\end{align}\n\nIn experiments, however, we get a cross section ratio which is \\(11/3\\), 3 times larger than expected: this indicates that we have a different type of charge, color charge, which means we have a multiplicity of \\(3\\) for each quark. \n\nWe shall see that this is related to certain kinds of internal symmetries of our field theory. \n\n\\end{document}\n", "meta": {"hexsha": "98e58b58a07d0b27ddd0c60492fe7ac784b8c613", "size": 12156, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ap_second_semester/astroparticle_physics/apr01.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "ap_second_semester/astroparticle_physics/apr01.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ap_second_semester/astroparticle_physics/apr01.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 37.1743119266, "max_line_length": 365, "alphanum_fraction": 0.6428101349, "num_tokens": 4253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3202041236470688}}
{"text": "\\chapter{Results}\nThis chapter consists of two main parts. In the first part of the chapter, the results from training models for predicting sex and brain age from brain graphs will be presented. The models were first evaluated using ten-fold cross validation on the training/validation set. Then, a final model was trained and evaluated on the test set. In the second part of the chapter, the saliency maps for these final models will be presented, with the aim of gaining insight into what functional brain networks in the data are related to age and sex differences. \n\nTo reliably evaluate the models, the data set was split into a training/validation set and a test set. These data sets where then undersampled to make them unbiased, which yielded training/validation sets of size 30000 and 20000, and test sets of size 4678 and 3148 for sex and age prediction, respectively. For age prediction, an unbiased data set corresponds to a uniform distribution of ages. Model training and evaluation was implemented in \\texttt{Python} \\cite{python} using \\texttt{Keras} \\cite{keras} with the \\texttt{TensorFlow} \\cite{tensorflow} backend. Furthermore, all models where trained using the \\texttt{Adam} \\cite{adam} optimizer.\n\n\\section{Evaluating model performance}\n\\label{sec:model_pred}\nThe model performance for both sex and age prediction is presented in the form of the loss and two additional metrics. For sex classification, these metrics are \\acrfull{bce} (loss), accuracy and \\acrfull{mcc}. For age regression, they are \\acrfull{mse} (loss), \\acrfull{mae} and Pearson correlation coefficient ($r$). \\acrshort{mcc} is defined identically to $r$, but refers to the performance of a binary classifier. An \\acrshort{mcc} of +1 thus indicates a perfect prediction, -1 all miss-predicted and 0 randomly guessing.\n\n\\subsection{Sex}\n\nTo evaluate the model performance for sex classification, the three metrics calculated from cross-validation on the training/validation set are presented in \\cref{tab:sex_model_results}. All three metrics indicate that Baseline, GCN and Popencoder have comparable performance, with an accuracy around $79\\,\\%$. It is also clear that these three models significantly outperform Poptoy regardless of metric. The performance of the final models, evaluated on an external test set, is presented in \\cref{tab:sex_final_model_results}. The final models' performance are in line with the cross-validation results in \\cref{tab:sex_model_results}, where all metrics are within, or around, one standard deviation. Thus, the performance of the models generalises to external data.\n\\begin{table}[!htbp]\n    \\centering\n    \\caption{\\acrfull{bce}, accuracy (in $\\%$) and \\acrfull{mcc} for each of the four models, evaluated using ten-fold cross validation, with the mean and standard deviation calculated over the ten folds.}    \n    \\begin{tabular}{c|c|c|c}\n         & BCE & Accuracy & MCC\\\\ \\hline\n        Baseline & $0.450\\pm0.008$ & $79.0\\pm0.6$ &$0.58\\pm 0.01$\\\\\n        GCN &$0.45\\pm0.02$ & $79.2\\pm0.9$& $0.59\\pm0.02$\\\\\n        Poptoy &$0.674\\pm 0.006$ & $58\\pm1$ &$0.17\\pm0.02$\\\\\n        Popencoder &$0.446\\pm0.009$& $79.3\\pm 0.6$ & $0.59\\pm0.01$\\\\\n    \\end{tabular}\n    \\label{tab:sex_model_results}\n\\end{table}\n\\begin{table}[!htbp]\n    \\centering\n    \\caption{\\acrfull{bce}, accuracy (in $\\%$) and \\acrfull{mcc} for each of the four models evaluated on the test set.}\n    \\begin{tabular}{c|c|c|c}\n         & BCE & Accuracy & MCC\\\\ \\hline\n        Baseline & 0.444 & 79.5 &0.59\\\\\n        GCN & 0.43& 80.2 & 0.60 \\\\\n        Poptoy &0.678 &57.4 &0.16\\\\\n        Popencoder & 0.450 & 79.1& 0.59\\\\\n    \\end{tabular}\n    \\label{tab:sex_final_model_results}\n\\end{table}\n\nThe results presented in \\cref{tab:sex_model_results} and \\cref{tab:sex_final_model_results} have several interesting implications. Observe that there is basically no performance difference between Baseline, GCN and Popencoder, implying that increasing model complexity beyond Baseline is not necessary for classifying sex. Furthermore, the main difference between Popencoder and Baseline and GCN is that Popencoder takes a population graph as input, in addition to the brain graphs for all subjects. One explanation of why including the population graph does not improve performance could be that our chosen similarity measure does not introduce any extra information relevant for sex classification. Since the similarity measure is calculated from each subject's brain graph, it is possible that the information encoded by the similarity measure is only a subset of all the information contained in the individual graphs. Another explanation is that the similarity measure adds some extra information, but that the amount of information is small. In the case of either explanation, the similarity measure does not introduce enough information to improve the prediction of a subject's sex. That the similarity measure is not very informative is further supported by the poor performance of Poptoy, since Poptoy bases its prediction solely on the population graph. However, Poptoy still performs better than random guessing, indicating that some valuable information resides in the population graph. \n\n\\subsection{Age}\nTo evaluate the model performance for age regression, the three metrics calculated from cross-validation are presented in \\cref{tab:age_model_results}. From \\cref{tab:age_model_results}, the three metrics clearly indicate that, just as for sex classification, Baseline, GCN and Popencoder all perform within the uncertainty of each other, whilst Poptoy performs significantly worse.  \\cref{tab:age_final_model_results} presents the performance of the final models trained on all data and evaluated on an external test set. The results are within one standard deviation of the results in \\cref{tab:age_model_results}, which indicates that the models generalise well to external data. One possible exception is Popencoder, which performs slightly better on the test set than during cross-validation, however, the difference in performance is small.\n\n\\begin{table}[!htbp]\n    \\centering\n    \\caption{\\acrfull{mse}, \\acrfull{mae} and Pearson correlation coefficient ($r$) for each of the four models, evaluated using ten-fold cross validation, with the mean and standard deviation calculated over the ten folds.}\n    \\begin{tabular}{c|c|c|c}\n         &  MSE [years$^2$]& MAE [years] & $r$ \\\\ \\hline \n        Baseline &$52\\pm1$& $5.9\\pm0.1$&$0.52\\pm0.01$\\\\\n        GCN & $53\\pm1$& $5.96\\pm 0.09 $& $0.52\\pm0.01$\\\\\n        Poptoy &$71\\pm 1$ & $7.24\\pm0.07$ &$ 0.11\\pm 0.01$\\\\\n        Popencoder &$53\\pm1$& $5.93\\pm 0.09$ & $0.52\\pm0.02$\\\\\n    \\end{tabular}\n    \\label{tab:age_model_results}\n\\end{table}\n\nThe age prediction results for the different models are in line with the two main conclusions for sex classification in the previous section. Firstly, Baseline, GCN and Popencoder perform similarly which indicates that increasing the model complexity beyond Baseline is unnecessary. Secondly, the poor performance of Poptoy compared to the other models, combined with Popencoder not performing better than Baseline and GCN, indicates that the similarity measure is not very informative with regards to age either. \n\n\\begin{table}[!htbp]\n    \\centering\n    \\caption{\\acrfull{mse}, \\acrfull{mae} and Pearson correlation coefficient ($r$) for each of the four models evaluated on the test set.}\n    \\begin{tabular}{c|c|c|c}\n         &  MSE [years$^2$]& MAE [years] & $r$ \\\\ \\hline \n        Baseline & $51 $& $5.9 $&$0.53 $\\\\\n        GCN & $51 $& $5.9  $& $0.53 $\\\\\n        Poptoy &$71 $ & $7.18 $ &$ 0.09 $\\\\\n        Popencoder &50 & $5.7 $ & $0.55 $\\\\\n    \\end{tabular}\n    \\label{tab:age_final_model_results}\n\\end{table}\n\nTo set the poor performance of Poptoy into perspective, consider a naive age prediction model that always outputs the average age of the population when predicting a subject's age. The performance of such a model on the test set would yield an \\acrshort{mse} of $71\\rm\\,years^2$ and an MAE of $7.3\\rm\\,years$. The correlation for constant prediction with the actual ages is undefined. Comparing this with the results for Poptoy, one can conclude that Poptoy only performs slightly better, demonstrating Poptoy's poor performance.\n\nTurning to the results on the test set for the three other models, all have an \\acrshort{mse} loss of around 50--$51\\rm\\,years^2$ , an \\acrshort{mae} of 5.7--$5.9\\rm\\,years$ and a correlation of around 0.53--0.55. The fact that the correlation is much lower than 1 indicates that the prediction is not perfect. In fact, it turns out that all these models are somewhat biased in predicting the mean of the age distribution in the data set. This can be seen clearly in \\cref{fig:age_regression}, where a prediction with Baseline on the test set is performed. The figure suggests that the model to some extent can determine if a subject is old or young, but that the error in the age prediction is much larger for younger and older subjects than for subjects close to the mean age. This is a form of underfitting, indicating either that the model is not complex or general enough to better fit the data, or that the data does not contain enough information for a better prediction of age.\n\n\\begin{figure}[!htbp]\n    \\centering\n    \\begin{center}\n        \\resizebox {0.6\\linewidth} {!} {\n            \\input{chapters/images_results/predict_example.pgf}\n        }\n    \\end{center}\n    \\caption{A plot of the Baseline predicted ages for the subjects in the test set, versus the target ages. The dots are the predictions for individual subjects, the orange line is a linear fit to the individual predictions, and the black dashed line is what the perfect predictions (no error) would look like. Note that the error in the prediction is the largest for the youngest and the oldest subjects.}\n    \\label{fig:age_regression}\n\\end{figure}\n\n\\section{Saliency maps of functional brain networks}\nThe saliency mapping consisted of two methods: naive node removal and Zorro; both applied for sex and age prediction on Baseline and GCN. Poptoy was not analysed because of its low performance, and Popencoder because of its high complexity. Including Popencoder would probably also be redundant, because of its similar performance to Baseline and GCN. \n\nNaive node removal was performed with the difference in loss ($\\Delta$\\acrshort{bce} for sex prediction and $\\Delta$\\acrshort{mse} for age prediction) evaluated on the test set. The naive analysis was repeated ten times with different model initialisations to estimate the impact of model uncertainty on node importance. Zorro was performed only for the final models presented in \\cref{sec:model_pred}, and was run with a fidelity threshold of $\\tau=0.9$. The tolerance for an age prediction to be considered correct was set to be similar to the MAE of the final models, at $t=6\\rm\\,years$. The results for all subjects in the test set were aggregated into groups of 200 subjects, and the mean importance score for each node in each group was calculated. Then, the average and standard deviation over the importance scores in each group was calculated. The standard deviations of the Zorro results over these sub-groups represent the uncertainty in the importance for each node when varying subjects. Ideally, Zorro should also be evaluated over different model intialisations. However, it would require repeating Zorro evaluated on all subjects in the test set for several different models. Due to the computational complexity of Zorro, this was not possible because of time constraints. A smaller investigation into the model uncertainty for Zorro was performed for a few subjects, presented in \\cref{app:zorro_model_uncertainty}, from which it was concluded that the model uncertainty is similar, but generally smaller than the subject uncertainty. \n\n\\subsection{Sex}\n\\label{sec:results_analysis_sex}\nAs a measure of node importance, $\\Delta$\\acrshort{bce} when performing naive node removal for Baseline and GCN is presented in \\cref{fig:naive_sex}.\n\n\\begin{figure}[!htbp]\n    \\centering\n    \\begin{center}\n    \\resizebox {0.7\\linewidth} {!} {\n        \\input{chapters/images_results/node_masking/shared_x_sex.pgf}\n    }\n    \\end{center}\n    \\caption{Results from performing the naive node removal analysis for Baseline and GCN, for sex prediction. The analysis was repeated for ten different model initialisation, over which the dots and error bars in the figures represent the mean and standard deviation, respectively.}\n    \\label{fig:naive_sex}\n\\end{figure}\n\nFrom the figures it is observed that the effect of removing a node for both models is on the order of $\\Delta \\text{BCE} \\sim 0.01$, which is small compared to the absolute performance of the reference models, $\\text{BCE} \\approx 0.45$. It is also observed that removing any node has a negative effect on performance, $\\Delta\\text{BCE}>0$. These two observations indicate two things. Firstly, no node seems to be crucial for the prediction, since the change in performance is small for all nodes. Secondly, all nodes are to some extent important, since removing any node has a negative impact on the performance. Despite the small absolute change in performance, there are clear differences in the relative importance between nodes. The results for both models indicates that \\acrshort{smm}, \\acrshort{cb2}, \\acrshort{pl} and \\acrshort{pmc} are more important than the other nodes. Further, observe that the uncertainties are much larger for GCN than for Baseline. This could be due to GCN not converging to the same degree as Baseline, either due to overfitting, early stopping or because of it being a more complex model. The two models, however, give roughly the same result, even if the uncertainties for GCN are large. \n\n\\begin{figure}[!htbp]\n    \\centering\n    \\begin{center}\n        \\resizebox {0.7\\linewidth} {!} {\n            \\input{chapters/images_results/zorro/shared_x_sex.pgf}\n        }\n    \\end{center}\n    \\caption{Zorro analysis results for the Baseline and GCN models. The analysis results were grouped into 23 different groups of 200 subjects for each model, to yield a mean and standard deviation in importance for each node.}\n    \\label{fig:zorro_sex}\n\\end{figure}\n\nThe result from the Zorro analysis for Baseline and GCN is presented in \\cref{fig:zorro_sex}. The uncertainties in the result for both models are small, but note that they do not include potential uncertainties regarding the model variability, as previously discussed. Generally, it is clear that the results for Baseline and GCN are to a large extent in agreement: for both models \\acrshort{smm} is pointed out to be the most important node. Other nodes that may be regarded to be somewhat important according to both models are \\acrshort{cb2}, \\acrshort{pl}, \\acrshort{ts} and \\acrshort{pmc}. It is also interesting to note that \\acrshort{vv1m} seems to be more important when analysing Baseline than GCN. One possible interpretation could be that this is an artefact of the method, but this inconsistency will be discussed more in-depth in \\cref{chap:discussion}.\n\n\\begin{figure}[H]\n    \\centering\n    \\begin{center}\n    \\resizebox {0.7\\linewidth} {!} {\n        \\input{chapters/images_results/thesis_naive_zorro_sex.pgf}\n    }\n    \\end{center}\n    \\caption{Comparison of the results for naive node removal and Zorro for sex prediction, from \\cref{fig:naive_sex} and \\cref{fig:zorro_sex}, respectively. Note that the error bars are omitted for visibility.}\n    \\label{fig:comparison_sex}\n\\end{figure}\n\nTo more easily compare the result of naive node removal and Zorro for both models, \\cref{fig:comparison_sex} is presented, without error bars for visibility reasons. The comparison of the result reveal that the methods are generally in agreement, but some clear differences exist. For instance, both methods agree that \\acrshort{smm} is important but disagree on the degree of importance for \\acrshort{cb2} and \\acrshort{pl}. By comparing the methods and models, \\acrshort{smm} seems to be most important node for classifying sex, and \\acrshort{cb2}, \\acrshort{pl}, \\acrshort{ts} and \\acrshort{pmc} may to some extent be important.\n\n\\subsection{Age}\n\nAs a measure of node importance, $\\Delta$\\acrshort{mse} when performing naive node removal for Baseline and GCN is presented in \\cref{fig:naive_age}. \n\n\\begin{figure}[!htbp]\n    \\centering\n    \\begin{center}\n        \\resizebox {0.7\\linewidth} {!} {\n            \\input{chapters/images_results/node_masking/shared_x_age.pgf}\n        }\n    \\end{center}\n    \\caption{Results from performing the naive node removal analysis for Baseline and GCN, for age prediction. The analysis was repeated for ten different model initialisation, over which the dots and error bars in the figures represent the mean and standard deviation, respectively.}\n    \\label{fig:naive_age}\n\\end{figure}\n\nThe general change in loss is observed to be small, $\\Delta\\text{MSE}\\sim1\\rm\\,years^2$ relative to $\\text{MSE}\\sim50\\rm\\,years^2$. As was the case for sex prediction, this indicates that no node is crucial and that all nodes are to some extent important for predicting age. Furthermore, the model uncertainty is larger for GCN than for Baseline in the case of age prediction as well. This could be due to GCN not fully converging, as discussed in \\cref{sec:results_analysis_sex}. Observe that the most important nodes for both models are \\acrshort{smm}, \\acrshort{cb2} and \\acrshort{pmc}, where \\acrshort{cb1} is additionally important for Baseline. Overall, the models are generally in agreement with some small exceptions. \n\n\\begin{figure}[!htbp]\n    \\centering\n    \\begin{center}\n    \\resizebox {0.7\\linewidth} {!} {\n        \\input{chapters/images_results/zorro/shared_x_age.pgf}\n    }\n    \\end{center}\n    \\caption{Zorro analysis results for the Baseline and GCN models for age prediction. The analysis results were grouped into 15 different groups of 200 subjects for each model, to yield a mean and standard deviation in importance for each node.}\n    \\label{fig:zorro_age}\n\\end{figure}\n\nThe result from the Zorro analysis for Baseline and GCN is presented in \\cref{fig:zorro_age}. Observe that the algorithm finds \\acrshort{cb1}, \\acrshort{dmn}, \\acrshort{smm}, \\acrshort{sn}, \\acrshort{cb2} and \\acrshort{pl} important for Baseline, and \\acrshort{smm} and \\acrshort{cb2} important for GCN. Another observation is that generally the importance scores for Baseline are higher than for GCN, especially for \\acrshort{cb1}, \\acrshort{dmn} and \\acrshort{sn}. This means that more nodes are required in the explanations for Baseline than for GCN in order to reach a fidelity of $\\tau=0.9$.\n\n\\begin{figure}[H]\n    \\centering\n    \\begin{center}\n    \\resizebox {0.7\\linewidth} {!} {\n        \\input{chapters/images_results/thesis_naive_zorro_age.pgf}\n    }\n    \\end{center}\n    \\caption{Comparison of the results for naive node removal and Zorro for age prediction, in \\cref{fig:naive_age} and \\cref{fig:zorro_age} respectively. Note that the error bars are omitted for visibility.}\n    \\label{fig:comparison_age}\n\\end{figure}\n\nIn order to more easily compare the result for the naive node removal and Zorro for both models, \\cref{fig:comparison_age} is presented. By comparing the results for both methods and models, \\acrshort{smm} and \\acrshort{cb2} stand out, since they are deemed important in all cases. In addition to \\acrshort{smm} and \\acrshort{cb2}, other nodes that might be important, but not consistently for all methods and models, are \\acrshort{cb1}, \\acrshort{dmn}, \\acrshort{sn}, \\acrshort{pl} and \\acrshort{pmc}. Most of these are nodes that are only considered important by Zorro for the Baseline model. However, since they are only deemed important in one out of the four cases, it might suggest that they are artefacts of the method or model.\nThere are also some differences in the results for naive node removal compared with Zorro. For example, \\acrshort{pmc} may be deemed more important by the naive method. However, the differences between the two analysis methods seem to be smaller than the discrepancy between Baseline and GCN for Zorro. These differences and discrepancies will be discussed in more detail in \\cref{chap:discussion}.\n\n", "meta": {"hexsha": "a302fd6c39d3f05872ca943c0795d61958fdce60", "size": 20237, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/results.tex", "max_stars_repo_name": "elindgren/master_thesis", "max_stars_repo_head_hexsha": "62185cdeafbf1ce65a49bb41828281c09435ac87", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/results.tex", "max_issues_repo_name": "elindgren/master_thesis", "max_issues_repo_head_hexsha": "62185cdeafbf1ce65a49bb41828281c09435ac87", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/results.tex", "max_forks_repo_name": "elindgren/master_thesis", "max_forks_repo_head_hexsha": "62185cdeafbf1ce65a49bb41828281c09435ac87", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 113.691011236, "max_line_length": 1552, "alphanum_fraction": 0.7637989821, "num_tokens": 5063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.32020412364706874}}
{"text": "\\section{High energy physics applications}\n\\label{sec:hep}\n\n\\subsection{B physics}\n\n\\subsubsection{Data sample}\n\nIn order to demonstrate the functionality of the toolkit, data samples generated\nfrom the RapidSim package~\\cite{rapid} are used. The interesting signal is chosen\nto be the $\\Bs\\to\\jpsi(\\to\\mu\\mu )\\phi (\\to\\PK\\PK )$ decay, and the background is\nthe $\\Dz\\to\\pi\\pi\\pi\\pi$ decay. A total of 10000 candidates is generated for each decay.\n\n\\subsubsection{Training of the original classifier}\n\\label{sec:orig_training}\n\n%The machine learning classifier chosen is the Multi-layer perceptron of SciKit-Learn,\n%which is constructed as\nThe machine learning classifier, using the Keras framework~\\cite{keras},\nis constructed as\nwhich is constructed as\n\\begin{lstlisting}\nclassifier = Sequential()\nclassifier.add(LocallyConnected1D(\nfilters = 90, kernel_size = 2,\nactivation = 'sigmoid',\ninput_shape = (len(setTrain[0]), 1)))\nclassifier.add(GlobalMaxPooling1D())\nclassifier.add(Dense(30, activation = 'sigmoid'))\nclassifier.add(Dense(1, activation = 'sigmoid'))\nclassifier.compile(optimizer = 'adam',\nloss = 'binary_crossentropy'\n, metrics = ['accuracy'])\n\\end{lstlisting}\n%\\begin{lstlisting}\n%classifier = MLPClassifier(activation='relu',\n%    batch_size='auto', beta_1=0.9, beta_2=0.999,\n%    early_stopping=False, epsilon=1e-08,\n%    hidden_layer_sizes=(3, 3),\n%    learning_rate='constant',\n%    learning_rate_init=0.001, max_iter=200,\n%    nesterovs_momentum=True, power_t=0.5,\n%    random_state=1, shuffle=True,\n%    solver='lbfgs', tol=0.0001, momentum=0.9,\n%    validation_fraction=0.1, verbose=False,\n%    warm_start=False, alpha=1e-05)\n%\\end{lstlisting}\n\nThe neural network is trained using kinematic properties of the respective decays.\nThese include the pseudorapidity, $\\eta$, and momentum transverse to the direction of the\ninput proton beams, \\pt, of the decaying particle. In addition, the minimum and maximum \\pt and $\\eta$\nof the final state particles is used. The signal and background distributions of the input variables\nare shown in Fig.~\\ref{fig:inputs}.\n%\n\\begin{figure*}[t]\n\\centering\n\\includegraphics[width=0.33\\textwidth]{pt_comp}\n\\includegraphics[width=0.33\\textwidth]{eta_comp}\n\\includegraphics[width=0.33\\textwidth]{minpt_comp}\n\\includegraphics[width=0.33\\textwidth]{maxpt_comp}\n\\includegraphics[width=0.33\\textwidth]{mineta_comp}\n\\includegraphics[width=0.33\\textwidth]{maxeta_comp}\n\\caption{\\small Comparison of the signal and background distributions\nused to train the Keras B decay classifier.}\n\\label{fig:inputs}\n\\end{figure*}\n\nIn the training of the original classifier, half of the data is\nreserved in order to test for overtraining.\n%The output probability distributions of the signal and background samples\n%after the training are shown in Fig.~\\ref{fig:output}.\n%It can be seen that the test and training samples are in good agreement,\n%showing that the original SciKit-Learn classifier is not significantly overtrained.\n%\\begin{figure*}[t]\n%\\centering\n%\\includegraphics[width=0.45\\textwidth]{event_probability}\n%\\caption{\\small\n%Output distributions of the signal and background training and\n%test samples from the classifier after training.\n%}\n%\\label{fig:output}\n%\\end{figure*}\n\n\n\\subsection{Jet separation}\n\\label{sec:hepGPD}\n\n\\subsubsection{Data sample}\n\nA further demonstration is provided demonstrating a classifiers ability to separate different\nkinds of jets. The data sample to show this has been generated from Pythia~\\cite{Sjostrand:2007gs}\nsimulating pp collisions at 14\\tev.\nThe jets themselves are reconstructed in the Rivet analysis framework~\\cite{Buckley:2010ar}\nand are created using the FastJet~\\cite{Cacciari:2011ma} package using the $K_t$ algorithm~\\cite{Salam:2007xv}\n(the definition\nof the $K_t$ variable and a review of jet reconstruction algorithms\nmay be found in Ref.~\\cite{Atkin:2015msa}).\nA jet \\pt requirement of 20\\gev is imposed on all jets.\nAll other parameters remain at the default values for Rivet version 2.5.4.\nThe signal sample is chosen to correspond to a $qg\\to qg$ type of interaction,\nwhereas the background is chosen to correspond to a $gg \\to gg$ type.\nJets that originate from gluons in the final state form a background to many\nanalyses, therefore efficient rejection of such processes is important in making\nmeasurements~\\cite{Komiske:2016rsd}.\n\n\\subsubsection{Training of the original classifier}\n\nThe machine learning classifier chosen is also a Keras-based convolutional neural net,\nconstructed in an similar way as described in Sec~\\ref{sec:orig_training}.\n\\begin{lstlisting}\nclassifier = Sequential()\nclassifier.add(LocallyConnected1D(\nfilters = 32, kernel_size = 2,\nactivation = 'relu', input_shape = sig_data[0].shape))\nclassifier.add(MaxPooling1D(pool_size = 3,\nstrides = 1))\nclassifier.add(Dropout(0.25))\nclassifier.add(Conv1D(filters = 32, kernel_size = 3,\nactivation = 'relu'))\nclassifier.add(MaxPooling1D(pool_size = 2,\nstrides = 2))\nclassifier.add(Dropout(0.25))\nclassifier.add(Conv1D(filters = 32, kernel_size = 2,\nactivation = 'relu'))\nclassifier.add(MaxPooling1D(pool_size = 2,\nstrides = 2))\nclassifier.add(Dropout(0.5))\nclassifier.add(Flatten())\nclassifier.add(Dense(50, activation = 'relu'))\nclassifier.add(Dense(1, activation = 'sigmoid'))\nclassifier.compile(optimizer = 'adam',\nloss = 'binary_crossentropy'\n, metrics = ['accuracy'])\nearlystop = EarlyStopping(patience = 3)\nmodel.fit(setTrain, labels, batch_size = batchSize,\nepochs = epochNum, validation_data = (setTest, labels),\ncallbacks = [earlystop])\n\\end{lstlisting}\n\nThe training data is prepared as described in Sec. 3.1 of~\\cite{Komiske:2016rsd}. Four images\nin two dimensions (azimuthal angle, $\\phi$, and rapidity, $\\eta$) are created from the multiplicity and\ntransverse energy of charged and neutral particles. The resulting images are centred and\ncropped in a region $\\eta$, $\\phi$ $\\in (-0.4, 0.4)$. Finally the images are normalised\n(pixel intensities sum to 1, $\\sum_{ij} I_{ij} = 1$), zero-centred (normalised mean subtracted\nfrom pixel intensity, $I_{ij}^{'} = I_{ij} - \\mu_{ij}$) and standardised (divide pixel intensity\nby the standard deviation, $I^{''}_{ij} = I^{'}_{ij} / (\\sigma_{ij} + r)$, $r = 10^-5$).\nFinally, a further step is added where the images are projected in two 1-D projections each and\nfour channels are considered: charged \\& neutral particle transverse energy and charged \\& neutral\nparticle multiplicity. The resulting 1-D feature vector is appended with some\ntotal kinematic properties such as the $K_t$ of the jet, its momentum, energy, mass,\nmultiplicity, etc. - producing a total of 140 individual features.\n% The neural network is trained using 4 jet properties consisting of the energy,\n% the combined mass of the particles in the jet, the pseudorapidity, and the jet $K_t$.\nThe signal and background distributions of the input variables\nare shown in Fig.~\\ref{fig:inputsGPD}.\n%\n\\begin{figure*}[t]\n\\centering\n\\includegraphics[width=0.33\\textwidth]{et_comp_gpd}\n\\includegraphics[width=0.33\\textwidth]{eta_comp_gpd}\n\\includegraphics[width=0.33\\textwidth]{m_comp_gpd}\n\\includegraphics[width=0.33\\textwidth]{kt_comp_gpd}\n\\caption{\\small Comparison of the signal and background distributions\nused to train the Keras classifier .}\n\\label{fig:inputsGPD}\n\\end{figure*}\n\n\\subsection{Drone conversions}\n\nThe drone neural networks are trained following the procedure outlined in Sec.~\\ref{sec:dlearn},\nIn total, 1500 epochs are used with\nthe learning rate of the stochastic gradient descent set to 0.05.\nThe value of $\\kappa$ is chosen to be 0.01.\n\nThe loss history of the drone approximations are shown in Fig.~\\ref{fig:loss}\nas a function of epoch number.\nThe convergence is also shown in Fig.~\\ref{fig:iterdiff}, which shows\nthe difference in the value of the loss function with respect to the previous\nepoch. The epochs that trigger an increase in the number of hyperparameters\nare also overlaid.\nIn total for the case of B decays, an increase was triggered 38 times compared to 67 times for the\njet separation classifier. The total number\nof parameters in the final drone neural networks are therefore 302 and 10152 for the B decay drone\nand the jet separation drone, respectively. It is interesting\nto note that with the algorithm design of Sec.~\\ref{sec:dlearn}, the introduction\nof the new parameter space causes the drone networks to learn faster, as evidenced by\nincreases in Fig.~\\ref{fig:iterdiff} with continuing descent of the loss functions.\n%\nThe performance of the original classifiers compared to the drone classifiers are shown in Figure~\\ref{fig:roc}.\n\\begin{figure*}[t]\n\\centering\n\\includegraphics[width=0.45\\textwidth]{loss_history}\n\\includegraphics[width=0.45\\textwidth]{loss_history_gpd}\n\\caption{\\small\nConvergence of the loss function during the drone training\n  for the case of the B\n  decay (left) and jet separation (right) examples.\n}\n\\label{fig:loss}\n\\end{figure*}\n\\begin{figure*}[t]\n\\centering\n\\includegraphics[width=0.45\\textwidth]{diff_history}\n\\includegraphics[width=0.45\\textwidth]{diff_history_gpd}\n\\caption{\\small\nDifference in the loss function with respect to the previous iteration\n  for the case of the B\n  decay (left) and jet separation (right) examples.\n  The green triangles\ndepict the epoch number in which the number of hyperperameters was increased.\n}\n\\label{fig:iterdiff}\n\\end{figure*}\n\\begin{figure*}[t]\n\\centering\n\\includegraphics[width=0.45\\textwidth]{roc}\n\\includegraphics[width=0.45\\textwidth]{roc_gpd}\n\\caption{\\small\n  Signal efficiency versus background rejection of the original classifier (red) and drone\n  approximation (blue)\n  for the case of the B\n  decay (left) and jet separation (right) examples.\n}\n\\label{fig:roc}\n\\end{figure*}\n\n\n\\section{Drone storage and transferability and suitability\nfor low-latency environments}\n\\label{sec:storage}\n\nThe hyperparameters and structure of the drone are required to be\nportable and easily stored for later usage. For this the {\\tt JSON} format was chosen as\nmediator. It is human-readable and easily accessible in the {\\tt Python} and {\\tt C++}\nenvironments commonly used in HEP. Thus, it is readily deployable in both personal and production environments.\n\nProvided is a tool to export and save a drone neural network to a {\\tt JSON}\nformatted file which preserves the input \\& output structure,\nthe layers and nodes, all hyperparameters and activation functions.\nThe drone configuration is later read in by an equivalent tool into the production software framework,\nwhich then constructs a class object based on the Keras model. The {\\tt C++} class implements\na flexible member structure that is capable of completely reproducing the original drone. The production\nimplementation may be used for all data reduction levels, be it in the form of a low-latency trigger\nfor example up to the latest stages of data handling and output.\n\nA major advantage of this method is that analysts and users have the full freedom of latest developments\nof industry standards, but need only to support a more manageable implementation in the low-latency\nsoftware. This is further aided by projects such as ONNX~\\cite{ONNX}, which enable classifiers from a wider\nrange of software packages to be converted to a framework in which an approximation converter\nis available.\n\nThe identical performance show in Fig.~\\ref{fig:roc} is clearly the ideal scenario, even though\nsuch good agreement is not always required to give better results than other low-latency methods.\nHowever it is worth noting that the drones created in the examples of Sec.~\\ref{sec:hep} are faster to\nevaluate. The comparison of the time taken for each model evaluation, determined from a desktop\nusing a Intel Core i7-4770 processor is shown in Table~\\ref{tab:comp}.\n\\begin{table}[t]\n  \\centering\n  \\caption{Hyperparameter number comparisons of the original models and drone\n  approximations for the HEP examples. \\label{tab:comp_param}}\n  \\begin{tabular}{l|rr}\n                   & original model                  & drone \\\\\n    \\hline\n    B decay        & 4,111 & 302 \\\\\n    jet separation & 71,429 & 10152 \\\\\n  \\end{tabular}\n\\end{table}\n\n\\begin{table}[t]\n  \\centering\n  \\caption{Processing time comparisons of the original models and drone\n  approximations for the HEP examples. \\label{tab:comp}}\n  \\begin{tabular}{l|rr}\n                   & original model                  & drone \\\\\n    \\hline\n    B decay        & $19.3 \\pm 0.2 \\times 10^{-5}$ s & $2.7 \\pm 0.2 \\times 10^{-5}$ s \\\\\n    jet separation &  $3.2 \\pm 0.2 \\times 10^{-3}$ s & $4.3 \\pm 0.2 \\times 10^{-4}$ s \\\\\n  \\end{tabular}\n\\end{table}\n", "meta": {"hexsha": "0dbc50093cad0085d95480e2a501885524433cb2", "size": 12561, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "documents/paper/example.tex", "max_stars_repo_name": "Tevien/NNDrone", "max_stars_repo_head_hexsha": "76dce457324ea03a8757d74f6403fbf60132294b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-11-06T11:21:20.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-20T14:47:21.000Z", "max_issues_repo_path": "documents/paper/example.tex", "max_issues_repo_name": "Tevien/NNDrone", "max_issues_repo_head_hexsha": "76dce457324ea03a8757d74f6403fbf60132294b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-01-12T15:49:40.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-06T02:29:56.000Z", "max_forks_repo_path": "documents/paper/example.tex", "max_forks_repo_name": "Tevien/NNDrone", "max_forks_repo_head_hexsha": "76dce457324ea03a8757d74f6403fbf60132294b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2018-01-12T15:46:35.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-21T22:41:56.000Z", "avg_line_length": 45.0215053763, "max_line_length": 112, "alphanum_fraction": 0.7664994825, "num_tokens": 3277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.72487026428967, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.32015562834573}}
{"text": "\\documentclass{revtex4-2}\n\n\\usepackage{amsmath}\n\\usepackage{amsbsy}\n\\usepackage{amssymb}\n\\usepackage{graphicx}\n\\usepackage{bm,ulem,color}\n\\usepackage{natbib}\n\n\\include{gyrokinetics-macros}\n\\include{macros}\n\n\\usepackage[colorlinks=true]{hyperref}\n\\providecommand{\\pitens}{\\tensor{\\pi}}\n\\begin{document}\n\n\\date{\\today}\n\n\\title{\\mctrans{} Reference Manual}\n\\author{Ian G. Abel}\n\n\n\\maketitle\n\\section{Introduction}\n\n\\mctrans{} is the scoping tool used by the CMFX project and others for designing centrifugal magnetic mirrors.\n\n\\section{\\mctrans{}: A User's Guide}\n\n\\mctrans{} is driven from a configuration file. This file is written in the \\href{https://github.com/toml-lang/toml}{TOML} language. This language endeavours\nto be transparent and easy to use. The configuration file is broken up into blocks. ARRANGE THE BLOCKS (or finish writing this manual).\n\n\\section{The Physics Model of \\mctrans{}}\n\n\\mctrans{} solves simplified transport equations for the centrifugally-confined plasma. The underlying models are all based on the assumption that the plasma is well-confined and that the thermal Mach number is large compared to one.\n\nIn many places we use formulae straight from the NRL Plasma Formulary. \n\n\\subsection{Fundamental Equations}\n\nAs with any transport solver, \\mctrans{} solves equations for the fluid-like conserved quantities -- particles, energy, and momentum.\nWe work in the usual $(R,\\tor,Z)$ cylindrical coordinate system.\nThe magnetic field lies purely in the $R-Z$ plane,\\footnote{Estimates of ripple / mis-alignment induced transport can be computed, but it is currently out of scope for \\mctrans{}.}\nand is given by\n\\begin{equation}\n\\bm{B} = \\grad\\psi\\times\\grad \\tor,\n\\end{equation}\nwhere $\\psi$ is the poloidal flux function (proportional to the toroidal component of the vector potential).\nThe electric field is given by\n\\begin{equation}\n\\bm{E} = -\\grad \\psi \\frac{d \\Phi}{d\\psi} - \\grad \\pot,\n\\end{equation}\nwhere we have split off the dominant radial electric field into the first term (which gives rise to the sonic rotation) and put all other electric field variation into the second term. Estimating the size of the two terms, we see that\n\\begin{equation}\n\\Phi \\sim \\frac{a M T_e}{e \\rho_i} \\gg \\pot \\sim \\frac{T_e}{e},\n\\end{equation}\nwhere $a$ is a typical radial scale length, $M$ the thermal Mach number, and $\\rho_i$ the thermal ion Larmor radius.\n\nWe assume that the flow velocity $\\bm{u}$ is the same for all species and given by\n\\begin{equation}\n\\bm{u} = \\omega R^2 \\grad\\tor,\n\\end{equation}\nwhere $\\omega$ is the toroidal angular velocity. We also assume that the angular velocity is only a function of flux-surface-label $\\psi$.\n\nThe underlying transport equations are thus:\n\\begin{eqnarray}\n\\label{parttrans}\n\\frac{d n_s}{dt} + \\dv\\bm{\\Gamma}_s &=& S_{n\\,s}\\\\\n\t\t\\label{heattrans}\n\\frac{d}{dt} \\left( \\frac{3}{2} n_s T_s \\right) + \\dv\\bm{q}_s &=& \\left(\\grad\\psi \\cdot \\pitens \\cdot \\grad\\tor\\right) R^2 \\frac{d\\omega}{d \\psi}   + Q_s + S_{E\\,s}\\\\\n\t\\label{momtrans}\n\\frac{d \\omega}{dt} + \\dv\\left(\\pitens\\cdot R^2\\grad\\tor\\right) &=& \\bm{j} \\times\\bm{B} \\cdot R^2\\grad\\tor + S_{\\omega}.\n\\end{eqnarray}\nIn these equations the transport fluxes $\\bm{\\Gamma}_s$ and $\\bm{q}_s$ are the particle and heat fluxes of each species, and the species-summed momentum flux tensor is denoted by $\\pitens$. We have also included arbitrary sources of particles $S_{n\\,s}$, energy $S_{E\\,s}$, and angular momentum $S_{\\omega\\,s}$; these source terms will be used to account for collisionless parallel losses and energy sources such as alpha-particle heating.\n\nCurrently, \\mctrans{} does not solve all these equations. In fact, we only solve for the transport of heat. The particle transport equation is assumed to contain a \nsource that is feedback controlled to maintain the electron density at a fixed value. This restiction may be lifted at a later date.\n\nThe momentum transport equation is more interesting. We know that the angular velocity is driven by $\\bm{E}\\times\\bm{B}$ rotation, and so is given by\n\\begin{equation}\n\\omega = - \\frac{d \\Phi}{d\\psi},\n\\end{equation}\nwhere the effect of $\\pot$ in $\\bm{E}$ is small and can be neglected.  Due to the electrical configuration of a centrifugal mirror (see figure) we often\nwish to consider the behaviour of a centrifugal plasma given a fixed input voltage. In this case, the momentum transport equation becomes an equation to determine\nthe radial current drawn from the power supply in terms of other quantities. We never need to solve \\eref{momtrans} for $\\omega$ in this setup. If we instead held the input power or current fixed then \\eref{momtrans} would be solved as normal.\n\nIn steady-state operation, \\mctrans{} sets the time derivatives to zero and solves the ensuing nonlinear algebraic equations to balance heat generation and heat losses.\nIn the following subsections we will explain the approximations used to calculate those heat losses explicitly in terms of the system state.\n\n\\subsection{Approximations to the Magnetic Geometry}\nThe simplest, and most transparent, geometric approximation is the ``square well'' model. In this model we assume the field lines to be straight, directed in the $Z$ direction, with a step-function shape and a step function in field strength. We demonstrate this in \\Figref{squarewellplot}.\n\\begin{figure}\n\\includegraphics{SquareWell.pdf}\n\\caption{An example plot of field lines and the square-well approximation to the central field line}\n\\label{squarewellplot}\n\\end{figure}\n\n\\subsection{The Centrifugal Potential}\n\nMany results have been derived for confinement in mirror machines which possess an electrostatic potential that varies along the field line. We can make use of these results by noting the following fact: the potential energy of a charged particle on a rotating field line at radius $R$ with angular velocity $\\omega$ is\n\\begin{equation}\n\\Xi_s = Z_s e \\pot - \\frac{m_s}{2} \\omega^2 R^2.\n\\end{equation}\nWe can thus reuse results from existing papers simply by making the substitution $Z_s e\\pot \\rightarrow \\Xi_s$.\n\nPhysically, this electrostatic potential exists to keep the electrons (which are light and barely affected by the centrifugal force) next to the ions which are pushed to regions of large $R$ by the centrifugal force.\nHence, the potential $\\pot$ has to be solved for by insisting that the plasma is quasineutral along field lines (and that the loss rate is ambipolar).\nIf we assume that the plasma rotates at a large Mach number $M \\gg 1$, then the plasma is well-confined and the confinement time is long compared to the collision time (this can be checked \\textit{a posteriori}). In such a situation the plasma is locally Maxwellian (equivalently it is in LTE) and we can write the density of species $s$ as~\\cite{catto:2784,flowtome1}:\n\\begin{equation}\nn_s = N_s(\\psi) \\exp\\left( - \\frac{\\Xi_s}{T_s} \\right).\n\\label{confinedDensity}\n\\end{equation}\nIf we now insist that the plasma is made up of ions (mass $m_i$ and charge $Z_i e$) and electrons (mass $m_e$ and charge $-e$) then quasineutrality reads\n\\begin{equation}\nZ_i N_i \\exp\\left( - \\frac{Z_i e\\pot}{T_i} + \\frac{m_i}{2T_i} \\omega^2 R^2 \\right) = N_e \\exp\\left( \\frac{e\\pot}{T_e} + \\frac{m_e}{2T_e} \\omega^2 R^2 \\right).\n\\end{equation}\nWithout loss of generality, we can pick a baseline for $\\pot$ such that $Z_i N_i = N_e$ (to see this, average along a field line, use the fact that neither $N_s$ nor $T_s$ varies along the field line). Furthermore, by neglecting the term containing the electron mass, we can solve the resulting equation for $\\pot$:\n\\begin{equation}\n\\pot = \\left( \\frac{Z_i e}{T_i} + \\frac{e}{T_e}\\right)^{-1} \\frac{m_i}{2 T_i} \\omega^2 R^2,\n\\end{equation}\nup to a possible constant offset. It is clear that this potential is $\\Or(M^2T_e/e)$ and is, in fact, the leading order term in an asymptotic series in $M^{-1}$.\\footnote{In computing the densities in \\eref{confinedDensity}, we have integrated over a full Maxwellian distribution, neglecting the fact that some small number of high-energy particles are in fact lost alongt he field line. This is a consistent approximation as we have determined that the potential barrier is $\\Or(M^2T_e)$, which to leading order is effectively infinite.} \nTo compute the next-order terms in this series we need to know about lost particles and hence parallel transport. This is tackled in the next section. We end with a convenient expression for the potential drop from the centre of a flux surface (at $R = R_{max}$) in terms of suitably normalized variables:\n\n\\begin{equation}\n\\frac{e \\pot}{T_e} = \\left( \\frac{Z_i}{\\tau} + 1 \\right)^{-1} \\frac{M^2}{2} \\left( \\frac{R^2}{R_{\\mathrm{max}}^2} - 1 \\right) + \\Or(1),\n\\end{equation}\nwhere we let $\\tau = T_i/T_e$ be the temperature ratio, and we have defined the sonic Mach number $M = \\omega R_{max} / \\cs$ in terms of the sound speed $\\cs^2 = T_e / m_i$.\\footnote{This is not the speed at which sound waves propagate in a warm plasma, but provides a very convenient normalization. It is the cold-ion limit of the sound speed, and we will continue to call it the sound speed despite this abuse of terminology.}\nThis is only the leading-order term in a $M \\gg 1$ expansion, and so we collect all higher-order terms and denote them by $\\pot_0$.\nNote that if $Z_i = \\tau = 1$ then we get the usual $M^2/4$ scaling for the potential drop. \nIt is also useful to note that, as a consequence of flux conservation\n\t\\begin{equation}\n\t\\frac{B_{\\mathrm{min}}}{B_{\\mathrm{max}}} = \\left(\\frac{R_{\\mathrm{max}}}{R_{\\mathrm{min}}}\\right)^2, \n\\end{equation}\nand so we can relate the ratio of the radius of the flux surface at throat and in the central cell to the ``Mirror Ratio'' given by the ratio of magnetic field strengths.\n\nFor electrons, the only term in the potential energy is the electrostatic potential:\n\\begin{equation}\n\\Xi_e = \\left( \\frac{Z_i}{\\tau} + 1 \\right)^{-1} \\frac{M^2}{2} T_e \\left( 1 - \\frac{R^2}{R_{\\mathrm{max}}^2} \\right) - e \\phi_0,\n\\end{equation}\nbut for ions we need to include the centrifugal potential to obtain\n\\begin{equation}\n\\Xi_i = \\left( \\frac{Z_i}{\\tau} + 1 \\right)^{-1} \\frac{M^2}{2} T_i \\left( 1 - \\frac{R^2}{R_{\\mathrm{max}}^2} \\right) + Z_i e \\phi_0,\n\\end{equation}\nwhere we have picked the constant offset of $\\pot$ such that $\\Xi_i = \\Xi_e = 0$ at the midplane ($Z=0$, $R=R_{\\mathrm{max}}$). Again, $\\pot_0$ is the higher-order part of $\\pot$ that must be determined by evaluating the parallel losses.\n\n\\textbf{N.B. In contrast to a tandem mirror, where the only confining potential is electric, the addition of the centrifugal term allows the \n\tpotential to be confining for \\textit{both} the species.}\n\n\\subsection{Parallel Transport}\n\nWe assume that the plasma is hot enough to be in the collisionless regime where the particle bounce time (inside the potential well formed by the centrifugal force) is extremely short compared to the particle collision time. This is manifestly true in reactor-grade plasmas ($\\left.\\nu_{ii} L_\\parallel \\right/ \\vth \\sim 10^{-5}$ or smaller) but is even valid for warm plasmas above a few hundred electron Volts in temperature. The collisionality parameter is reported and if it is not much less than one the results of \\mctrans{} are not valid.\n\nIn this collisionless regime we use formulae that are derived in the manner originally used by Pastukhov~\\cite{Pastukhov1974} for the case of a tandem mirror with an electron-confining electrostatic potential. Pastukhov originally derived his results for electrons alone. We need the result for a multispecies plasma.  \nWe can find this result in \\citet{CattoBernsteinMirror1} by taking the square-well limit of (40) of that work to obtain the particle loss rate in our notation:\n\\begin{equation}\n\\left(\\pd{n_s}{t}\\right)_{\\mathrm{End Losses}} = \n\t- \\left( \\frac{2 n_s \\Sigma}{\\sqrt{\\pi}} \\right) \\nu_s \\frac{1}{\\ln\\left( R_{\\mathrm{mirror}} \\Sigma\\right)} \\frac{\\exp\\left( -\\Xi_s/T_s \\right)}{\\Xi_s/T_s},\n\t\\label{ParticleLossRate}\n\\end{equation}\nwhere $\\Sigma = Z_i + 1$ for electrons and $\\Sigma = 1$ for ions, and $\\nu_s$ is the appropriate collision frequency for species $s$. For electrons this is the combination of electron-electron and electron-ion collisions. For ions this is just the ion-ion collision frequency.\n\nNote that this equation only agrees with the results of \\citet{Pastukhov1974} and \\citet{cohen1978collisional} in the limit of $R_{\\mathrm{mirror}} \\rightarrow \\infty$. The error induced by not knowing this prefactor accurately is much smaller than the approximation by a square well, and is comparable with the effect of several other approximations made in the analytic work.\n\nWe anticipate upgrading \\mctrans{} to use the full formulae of \\citet{CattoBernsteinMirror1} in the near future, thereby including some effect of the actual magnetic geometry.\n\nThis particle loss rate can be used to compute heat losses by multiplying by $\\Xi_s$ -- the energy loss is dominated by energetic particles, nullifying the extra power of $\\Xi_s$ in the denominator of \\eref{ParticleLossRate}. Similarly, loss of toroidal angular momentum can be computed by multiplying the particle loss rate by the angular momentum lost per ion (electrons carrying negligible momentum).\n\n\\subsubsection{Ambipolar Parallel Losses and Solving for $\\pot$}\nIn the formula \\eref{ParticleLossRate} for the losses we see that $\\Xi_s$ appears in the exponential. The leading order part of $\\Xi_s$ is $\\Or(M^2 T_s)$, so this exponential is what strongly suppresses the collisional loss rate. Expanding this exponential schematically we have\n\\begin{equation}\n\\exp\\left( -\\frac{\\Xi_s}{T_s} \\right) \\approx \\exp\\left[ - (\\dots) M^2 \\right] \\exp\\left( -Z_s e \\pot_0 / T_s \\right),\n\\end{equation}\nand we see that even though $\\pot_0$ is small compared to the leading-order part of the potential it has an $\\Or(1)$ effect on the loss rate and must be accounted for.\n\nWe find $\\pot_0$ by equating the electron and ion loss rates along the field line to enforce zero net charge loss along the field line. \\textbf{N.B. This part of the code can be a little tempremental, and if you find a case that doesn't work it may be because you're starting to search for an equilibrium from a starting point that is so poorly confined that quasineutrality cannot be satisfied within the bounds that the code is searching.}\n\n\\subsection{Perpendicular Transport}\n\nTo completely evaluate the heat transport equations we need expressions for $\\bm{q}_s$ and $\\pitens$. \nWe consider only the classical collisional contribution to these transport fluxes. Turbulent transport should be fully suppressed by the flow shear.\n\nWe handle the heat flux first.\nFrom (2.14) of \\citet{braginskii1965tpp} the collisional ion heat flux in a strongly-magnetized plasma is \n\\begin{equation}\nq_i = -\\chi_{i\\parallel} \\bm{b}\\bm{b}\\dg T_i - \\chi_{i\\perp} \\grad_\\perp T_i + \\frac{5}{2} \\frac{n_i T_i}{m_i \\cycfreq[i]} \\bm{b}\\times\\grad T_i.\n\\end{equation}\nNow, in the collisionless limit, $T_i = T_i(\\psi)$ and so the first term vanishes, and the third term is purely toroidal. Thus, when we evaluate the divergence of the heat flux, we obtain (using axisymmetry)\n\\begin{equation}\n\\dv\\bm{q}_i = \\dv\\left( \\chi_{i\\perp} \\grad_\\perp T_i \\right).\n\\end{equation}\nTo estimate this term, we assume that all the plasma profiles vary on a scale $a$ that is related to the width of the plasma column $w$ by $a = w/2$, see \\Figref{scales} for more details. Thus, we have that\n\\begin{equation}\n\\dv{\\bm{q}_i} \\approx \\frac{1}{a^2} \\chi_{i\\perp} T_i = \\frac{2 n_i T_i^2}{m_i \\cycfreq[i]^2 \\tau_i a^2},\n\\end{equation}\nwhere we have used (2.16) of \\citet{braginskii1965tpp} for $\\chi_{i\\perp}$ and $\\tau_i$ is the ion-ion collision time.\n\nFor electrons, the same geometric algebra applies and we have\n\\begin{equation}\n\\dv{\\bm{q}_e} \\approx \\frac{1}{a^2} \\chi_{e\\perp} T_e = \\frac{4.66 n_e T_e^2}{m_e \\cycfreq[e]^2 \\tau_e a^2},\n\\end{equation}\nwhich is approximately $\\sqrt{m_e/m_i}$ smaller than the ion heat loss, and usually negligible.\n\n\\begin{figure}\n\\includegraphics{ScaleLengths.pdf}\n\\caption{Plasma column showing its width $w$, lenght $L$, and scale length $a$}\n\\label{scales}\n\\end{figure}\n\nWe only compute the stress tensor for the ions, electron perpendicular viscosity is at least $m_e/m_i$ smaller than the ion viscosity and always negligible.\nTo compute the Braginskii viscous stress tensor, we need to know the rate of strain tensor $\\tensor{W}$:\n\\begin{equation}\n\\tensor{W} = \\left(\\grad\\bm{u}\\right) + \\left(\\grad\\bm{u}\\right)^{T} - \\frac{2}{3} \\left(\\dv\\bm{u}\\right)\\idmat,\n\\end{equation}\nwhich, upon using $\\bm{u} = \\omega R^2 \\grad\\tor$, becomes\n\\begin{equation}\n\\tensor{W} = R^2 \\frac{d \\omega}{d\\psi} \\left( \\grad\\psi \\grad \\tor + \\grad \\tor \\grad \\psi\\right) \\approx \\frac{R}{a} \\omega\n\\end{equation}\nEvaluating this on the midplane, we see that in Braginskii's cartesian coordinates (with $z$ along $\\bm{b}$) the only nonzero component of $\\tensor{W}$ is $W_{xy}$ (equivalently $W_{yx}$).\nThus, using (2.21) of Braginskii, we can compute the nonzero components of the stress tensor. The quantities we need are\n\\begin{equation}\n\\dv\\left( \\pitens\\cdot R^2\\grad\\tor \\right) \\approx \\frac{1}{a} \\pi_{xy} R = - \\frac{R}{a} \\frac{3}{10} \\frac{n_i T_i}{\\cycfreq[i]^2 \\tau_i} W_{xy} = - \\frac{R}{a} \\frac{3}{10} \\frac{n_i T_i}{\\cycfreq[i]^2 \\tau_i} \\frac{R}{a} \\omega,\n\\end{equation}\nand\n\\begin{equation}\n\\pitens \\bm{:}\\grad\\bm{u} = \\frac{1}{2} \\pi_{xy} W_{xy} \\approx - \\frac{3}{10} \\frac{n_i T_i}{\\cycfreq[i]^2 \\tau_i}\\frac{R^2\\omega^2}{a^2}.\n\\end{equation}\n\nNote that, because we are using Braginskii's formulae, we also have to use his formula for the collision times (see \\citet{braginskii1965tpp}) which differ by $\\sqrt{2}$ from some other definitions of $\\tau_i$.\n\n\\subsection{Alpha Particles and Nuclear Physics}\nOur fundamental model for alpha particles is that they are all born with a delta-function distribution at the birth energy of $E_\\alpha = 3.52$ MeV:\n\\begin{equation}\n\\left( \\pd{f_\\alpha}{t}\\right)_{\\mathrm{Source}} = \\frac{S_\\alpha \\delta(v-v_*)}{4\\pi v_*^2}\n\\end{equation}\nwhere $v_*$ is the birth velocity corresponding to $E_\\alpha$ and $S_\\alpha$ is the birth rate of alphas per unit time per unit volume.\n\n\\subsubsection{Prompt Alpha Losses}\nAlpha particles are born isotropically. Thus, a fraction of them are born directly into the unconfined region of velocity space.\nThe birth energy of alphas $E_\\alpha$ is much greater than the centrifugal potential which is roughly $M^2 T_e / 4$ (at fusion temperatures and parameters this remains\nless than $0.5$ MeV). We thus model the loss region for energetic alphas as a cone, and only classical mirror confinement applies, thus an alpha is lost if\n\\begin{equation}\n\\mu_\\alpha B_{\\mathrm{max}} > E_\\alpha.\n\\end{equation}\nIntegrating this over all velocity space, we see that the fraction of alphas that is lost is\n\\begin{equation}\nf_{\\mathrm{lost}} = 1 - \\sqrt{1 - \\frac{1}{R_{\\mathrm{mirror}}}}.\n\\end{equation}\nThis fraction of alpha particles is removed from \\mctrans{} and hurled against the end plates.\nThis prompt loss of alpha particles is taken into account in assessing quasineutrality.\n\n\\subsubsection{Collisional Alpha Losses}\nCurrently, we do not have any explicit collisional losses of alpha particles. However, the approximate lifetime of alpha particles in the machine is (under the twin assumptions that of $R_{\\mathrm{mirror}} \\gg 1$ and that we can treat alphas like main ions, see e.g. \\citet{ryutovOpenTraps})\n\\begin{equation}\n\\tau_\\alpha \\approx 0.4 \\tau_{\\alpha i} \\ln R_{\\mathrm{mirror}},\n\\end{equation}\nwhere $\\tau_{\\alpha e}$ is the alpha-ion collision time (alpha-electron collisions do not change the pitch-angle of the alpha particles), which is marginally longer than the time it takes the alphas to deposit a reasonably large amount of their energy into electrons and ions.\nReally we should solve the Fokker-Planck kinetic equation for alpha particles with a source and a loss cone as is done in \\citet{santarius1982}.\n\n\\subsubsection{Alpha Heating}\nCurrently, all the energy in the retained alpha particles is deposited into the electron species as heating through collisions.\nThis is a pessimistic assumption as electron heating leads to a lower Mach number, faster electron losses, an increasingly electron-confining $\\pot$, and hence increased ion losses. \n\n\\subsection{Neutral Transport}\nWe currently have no model of transport due to neutral particles. A first step towards this will be implementing a diagnostic for \nthe neutral mean free path in our plasma. In the limit of either very small or very long mean free path, we may be able to make further approximations to evaluate the \nlosses from charge exchange.\n\\\\\n\\textbf{N.B. Until more neutral physics is implemented, we have no way to handle self-consistent fuelling scenarios. The only reasonable assumption\n\tis that losses due to neutrals are small and feedback control is used to target a fixed electron density.}\n\n\\subsection{Radiative Processes and Impurities}\nThere are two ways to model impurities in \\mctrans{}. Firstly is a ``lumped impurity'' that only changes the effective charge state $Z_{\\mathrm{eff}}$ and \nprovides \\textit{only} bremsstrahlung radiation. It does not dilute the main ion species, so quasineutrality is enforced by only considering the main ions and \nelectrons.\n\n\\subsubsection{Bremsstrahlung and Synchrotron Radiation}\nTaking the formulae for bremsstrahlung from the NRL formulary~\\cite{nrlformulary} and writing it in convenient units we have\n\\begin{equation}\nP_{\\mathrm{rad}} =  5.34 \\times 10^3\\, Z_{\\mathrm{eff}} \\left(\\frac{n_e}{10^{20} \\mathrm{m}^{-3}}\\right)^2 \\left(\\frac{T_e}{1 \\mathrm{keV}}\\right)^{1/2}\\, \\mathrm{W}/\\mathrm{m}^3,\n\\end{equation}\nwhere we have used the definition\n\\begin{equation}\nZ_{\\mathrm{eff}} = \\frac{1}{n_e} \\sum_{s} Z_s^2 n_s,\n\\end{equation}\nof the effective charge state of the plasma (summation taken over all positively charged species).\nSimilarly, we can take the synchrotron radiation formula from the formulary~\\cite{nrlformulary} and write it as\n\\begin{equation}\nP_{\\mathrm{rad}} =  6.21 \\times 10^3 \\,\\left( \\frac{B}{1\\,\\mathrm{T}} \\right)^2 \\left( \\frac{n_e}{10^{20}\\, \\mathrm{m}^{-3}} \\right) \\left( \\frac{T_e}{1\\,\\mathrm{keV}} \\right)\\, \\mathrm{W}/\\mathrm{m}^3.\n\\end{equation}\n\nThe plasma is assumed to be optically thin, and so all radiation is lost onto the first wall.\n\n\\subsubsection{Line Radiation}\n Without a better model for the impurity species that are present (including multiple charge states) we cannot reliably predict the amount of line radiation lost from the plasma.\n\\\\\n\\textbf{N.B. Because of the lack of ionization and radiative cooling, one should view low-temperature outputs from \\mctrans{} extremely sceptically!}\n\n\n\\appendix\n\\section{Full Syntax for \\mctrans{} configuration files}\n\n\\section{Non-Physical Implementation}\nThe use of \"fudge-factors\" has been included to simulate arbitrarily better or worse confinement. The default value is 1, and values less than or greater than 1 result in better or worse confinement, respectively. The fudge factors are applied to loss rates (either particle or heat). There are separate fudge factors for perpendicular and parallel, and viscous and thermal transport.\n\n\n\\bibliographystyle{apsrev}\n\\bibliography{references}\n\\end{document}\n\n", "meta": {"hexsha": "189e4dd60f71d2fb813c6d86acc715acbd363b55", "size": 23321, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "manual/MCTrans.tex", "max_stars_repo_name": "MylesKelly/MCTrans", "max_stars_repo_head_hexsha": "9d38178d3150d4c1dcde16489a2df3cca2d49c74", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-02-10T15:55:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T15:56:00.000Z", "max_issues_repo_path": "manual/MCTrans.tex", "max_issues_repo_name": "MylesKelly/MCTrans", "max_issues_repo_head_hexsha": "9d38178d3150d4c1dcde16489a2df3cca2d49c74", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2021-05-25T20:06:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T05:58:49.000Z", "max_forks_repo_path": "manual/MCTrans.tex", "max_forks_repo_name": "MylesKelly/MCTrans", "max_forks_repo_head_hexsha": "9d38178d3150d4c1dcde16489a2df3cca2d49c74", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-05T19:55:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T19:55:49.000Z", "avg_line_length": 75.2290322581, "max_line_length": 545, "alphanum_fraction": 0.7541700613, "num_tokens": 6542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.3201550256041377}}
{"text": "\\section{Spacecraft Model}\n\n\\subsection{RF Hardware Models}\n\nThe RF Hardware models in GMAT include transmitters, receiver, and transponders.  For each type of RF Hardware there are models for signal transmission/reception feasibility, received frequency, and transmitted frequency to name a few.  In the sections below we present these models for each type of RF Hardware.\n\n\\subsubsection{Receiver}\n\nThe receiver model supports a frequency model and a reception feasibility model.  The frequency model allows the user to specify the frequency capabilities of the receiver using different methods.  The feasibility model determines whether an RF signal sensed at the receiver can feasibly detected given the receivers capability as defined by the frequency model.\n  \nWhen the frequency model \\st{CenterAndBandwidth} is selected, the feasibility test is as follows.  Define the frequency transmitted by the originating transmitter as $F_t$, the receiver's center frequency as $F_C$, the bandwidth as $\\Delta F$, and the range rate between transmitter and receiver as $\\dot{\\rho}$ (which is positive when the distance $\\rho$ is increasing).  The frequency at the receiver is calculated using\n%\n\\begin{equation}\n     F_r = F_t(1 - \\frac{\\dot{\\rho}}{c})\n\\end{equation}\n%\nwhere $c$ is the speed of light.  Define the upper limit of the receiver as $F_u = F_c + \\Delta F / 2$ and the lower limit as $F_l = F_c - \\Delta F / 2$ .  If\n%\n\\begin{equation}\n       F_l \\leq F_r \\leq F_u\n\\end{equation}\n%\nthen the received frequency is received by the receiver model.  If the above test fails, the receiver does not receive the signal.\n\n\\subsubsection{Transmitter}\n\n\n\n\\subsubsection{Transponder}\n\n\n\\subsubsection{Antenna}\n\n\\subsection{Thruster Models}\n\nGMAT supports several thruster models.  The thruster models employ\nphysics and empirical data provided by the thruster manufacturer to\nmodel thrust and mass flow rate used in orbit and attitude equations\nof motion.   The thrust magnitude and $I_{sp}$ are assumed to be\nfunctions of thruster inlet flow conditions including  pressure,\ntemperature, and for bi-propellant thrusters, the oxidizer to fuel\nratio.\n\nIn the following subsections we present models for thrust magnitude\nand mass flow rates for several thruster types.  All thrusters have\na location and orientation.  The location is described in the\nspacecraft body system.  The orientation can be described with\nrespect to any coordinate system known to GMAT. Let's define the\nrotation matrix from the thruster frame $\\mathcal{F}_T$ to Earth's\nMJ2000 Equator as $\\mathbf{R}_T$. Then, the thrust used in the orbit\nequations of motion is\n%\n\\begin{equation}\n    \\mathbf{F}_T = F_T \\mathbf{R}_T \\hat{\\mathbf{T}}\n\\end{equation}\n%\nwhere $F_T$ is the thrust magnitude and is thruster dependent, and\n$\\hat{\\mathbf{T}}$\n\nNow let's look at how to calculate the thrust magnitude for a\nmono-propellant chemical thruster.\n\n\\subsubsection{Mono-Propellant Chemical Thruster}\n\ntemperature.  The specific form of Eqs.~(\\ref{Eq:MonoPropThrust})\nand (\\ref{Eq:MonoPropIsp}) are determined by fitting test data to\napproximate thrust and $I_{sp}$ as function $T_i$ and $P_i$.  The\nuser can supply this relationship via a scripte\n%\n\\begin{figure}[h!]\n\\centerline{\n\\begin{picture}(100,480)\n\\special{psfile= ./Images/MonoPropThruster.eps hoffset= -20 voffset= 250\nhscale=25 vscale=25}\n\\makebox(100,540){$\\dot{m}_e$,$P_e$,$v_e$}\n%\n\\makebox(-105,710){$\\dot{m}_c$,$T_c$,$P_c$}\n%\n\\makebox(-105,920){$m_f$,$T_f$,$P_f$}\n%\n\\makebox(-255,880){Catalyst Bed}\n\\end{picture}}\\vskip -3.75 in  \\caption{ Mono-Prop Thruster Diagram} \\label{fig:MonoPropThruster}\n\\end{figure}\n\nWe assume thruster data is given as a function of thruster inlet\nproperties (as opposed to thrust chamber properties), and thrust\nmagnitude and $I_{sp}$ are modelled using\n%\n\\begin{equation}\n    F_T = f(P_i,T_i)\\label{Eq:MonoPropThrust}\n\\end{equation}\n%\n\\begin{equation}\n    I_{sp} = f(P_i,T_i)\\label{Eq:MonoPropIsp}\n\\end{equation}\n%\nwhere $P_i$ and $T_i$ are the thruster inlet pressure and\ntemperature.  The specific form of Eqs.~(\\ref{Eq:MonoPropThrust})\nand (\\ref{Eq:MonoPropIsp}) are determined by fitting test data to\napproximate thrust and $I_{sp}$ as function $T_i$ and $P_i$.  The\nuser can supply this relationship via a scripted equation or by\nproviding a function name.  After calculating $F_T$ and $I_{sp}$, we\ncalculate the mass flow rate using\n%\n\\begin{equation}\n   \\dot{m}_e = \\frac{F_T}{I_{sp}}\n\\end{equation}\n\n\\subsubsection{Bi-Propellant Chemical Thruster}\n\n\\begin{figure}[h!]\n\\centerline{\n    \\begin{picture}(100,470)\n    \\special{psfile= ./Images/BiPropThruster.eps hoffset= -20 voffset= 260\n    hscale=25 vscale=25}\n    \\makebox(80,545){$\\dot{m}_e$,}\\makebox(-47,545){$P_e$,}\n    \\makebox(-30,545){$v_e$}\n    \\makebox(-70,730){$\\dot{m}_c$,$m_r$,$T_c$,$P_c$}\n    \\makebox(-30,938){$m_f$,$T_f$,$P_f$}\n    \\makebox(-140,938){$m_o$,$T_o$,$P_o$}\n    \\end{picture}}\\vskip -3.75 in  \\caption{ Bi-Prop Thruster Diagram} \\label{fig:BiPropThruster}\n\\end{figure}\n\n\\begin{equation}\n    m_r = \\frac{\\dot{m}_o}{\\dot{m}_f}\n\\end{equation}\n%\n\\begin{equation}\n    \\dot{m}_c = \\dot{m}_o + \\dot{m}_f\n\\end{equation}\n%\n\\begin{equation}\n    T'=  \\frac{\\dot{m}_o T_o + \\dot{m}_f T_f}{\\dot{m}_o + \\dot{m}_f}\n\\end{equation}\n%\n\\begin{equation}\n    P' =  \\frac{\\dot{m}_o P_o + \\dot{m}_f P_f}{\\dot{m}_o + \\dot{m}_f}\n\\end{equation}\n%\n\\begin{equation}\n   F = f(P_c,T_c,of)\n\\end{equation}\n%\n\\begin{equation}\n   I_{sp} = f(P_c,T_c,of)\n\\end{equation}\n%\n\\begin{equation}\n   \\dot{m}_e = \\frac{\\mathbf{F}_T}{I_{sp}}\n\\end{equation}\n\n\\subsubsection{Thruster Pulse Modelling}\n\n\\begin{equation}\nT'=\\frac{T(t)}{T_{max}} = \\left\\{\\begin{array}{ll}\n             \\displaystyle\\frac{t^2(t - t_{si})^2}{t_{si}^4} &\n             \\mbox{$t \\leq t_{si}$}\\\\\n             1 & \\mbox{$t_{si}<t<t_{sf}$}\\\\\n             \\displaystyle\\frac{(t - 2 t_{sf} + t_{f})^2(t - t_f)^2}{(t_f - t_{sf})^4}\n             & \\mbox{$t_{sf} \\leq t \\leq t_f$}\\\\\n             \\end{array}\\label{eq:quartic}\n      \\right.\n\\end{equation}\n%\n\\begin{figure}[ht]\n\\centerline{\n    \\begin{picture}(100,385)\n    \\special{psfile= ./Images/ThrustPulseProfile.eps hoffset= -150 voffset= 60\n    hscale=65 vscale=65}\n    \\end{picture}}\\vskip -3.75 in  \\caption{ Sample Thrust Pulse Profile } \\label{fig:ThrustPulseProfile}\n\\end{figure}\n%\n%\nThe time to the thrust centroid, $t_c$, is calculated using\n%\n\\begin{equation}\n     t_c = \\displaystyle\\frac{\\displaystyle\\int_0^{t_{f}} t \\mbox{ }T'(t) dt}{\\displaystyle\\int_0^{t_{f}} T'(t)dt}\n\\end{equation}\n%\nperforming the integral yields\n%\n\\begin{equation}\n    t_c = \\frac{-4 t_{si}^2  + 4 t_{sf}^2  + 6 t_{sf} t_f + 5 t_f^2 }{-14 t_{si} + 14 t_{sf} + 16 t_f}\n\\end{equation}\n\n\\subsubsection{Thruster Hot Fire Test Data \\\\ and Thruster Models}\n\nThruster hot fire test data is used to develop empirical models that\ndescribe thruster performance as a function of inlet conditions such\nas fuel pressure and temperature.  In this section we'll discuss how\nthe empirical models are developed and discuss how the empirical\nmodels are consistent with the physical models.  First we present\nthe physics model  for a thruster test stand experiment.  Next we\npresent what is measured during a thrust stand test, and show how\nthe measurements are used in combination with the physics model to\ngenerate a model of thruster performance over  a given range of\nthruster inlet conditions.\n\nIn Fig.~\\ref{fig:ThrustStand} we see an illustration of a simple\nthrust test setup.  The thruster is mounted to a rigid surface.\n%\n\\begin{figure}[h!]\n\\centerline{\n\\begin{picture}(100,400)\n\\special{psfile= ./Images/ThrusterOnStand.eps hoffset= -35 voffset= 220\nhscale=25 vscale=25}\n\\makebox(-120,700){$\\dot{m}$}\\makebox(-120,675){$T_i$}\n\\makebox(-125,650){$P_i$}\\makebox(225,705){$\\dot{m}$}\\makebox(-190,680){$c^*=\nI_{sp}g$}\\makebox(-225,655){$P_e$}\\makebox(-225,530){$F_T$}\n\\end{picture}}\\vskip -3.5 in  \\caption{ Thrust Stand Illustration} \\label{fig:ThrustStand}\n\\end{figure}\n%\nThe force due to thrust, $F_T$, can be written as\n%\n\\begin{equation}\n    F_T = \\dot{m}v_e - (P_e - P_a)A_e\n\\end{equation}\n%\nwhere\n\\begin{tabbing}\n    12345678 \\= Reynolds number based on length $s$ \\kill\n    $\\dot{m}$    \\>  mass flow rate, kg/s \\\\\n    $T_i$        \\>  fuel inlet temperature, K$^{\\circ}$\\\\\n    $P_i$        \\>  fuel inlet pressure, Pa\\\\\n    $c^*$        \\>  characteristic velcocity, m/s \\\\\n    $I_sp$       \\>  specific impulse, s \\\\\n    $g_o$        \\>  9.801 m/s$^2$ \\\\\n    $P_e$        \\>  nozzle exit pressure, Pa\\\\\n    $A_e$        \\>  nozzle exit area, m$^2$\\\\\n    $F_T$        \\>  force due to thrust, N\\\\\n\\end{tabbing}\n%\nwe can rewrite this as\n\\begin{equation}\n    F_T = \\dot{m}\\left(v_e - \\frac{(P_e - P_a)A_e}{\\dot{m}}\\right)  \\label{Eq:Fvsmv}\n\\end{equation}\n%\nFrom this equation we define the characteristic velocity, $c^*$,\nusing\n%\n\\begin{equation}\n    c^* = \\left(v_e - \\frac{(P_e - P_a)A_e}{\\dot{m}}\\right)\n\\end{equation}\n%\nIn practice, $v_e$ or $P_e$ are not measured.  We'll assume the\ntests are performed in a vacuum so $P_a = 0$.  To understand how we\nrelate the measurements to physical model, let's define a new\nquantity $I_{sp}$, where\n%\n\\begin{equation}\n    I_{sp} = \\frac{F_T}{\\dot{m} g_o}\n\\end{equation}\n%\nwe can rewrite this as\n%\n\\begin{equation}\n    F_T = \\dot{m} I_{sp} g_o \\label{Eq:IspVer2}\n\\end{equation}\n%\nComparing Eq.s~(\\ref{Eq:Fvsmv}) and (\\ref{Eq:IspVer2}) we see that\n%\n\\begin{equation}\n     c^* = I_{sp} g_o = v_e - \\frac{(P_e - P_a)A_e}{\\dot{m}}\n     \\label{Eq:CstarIsp}\n\\end{equation}\n%\nEquation (\\ref{Eq:CstarIsp}) shows that $I_{sp}$ is a measure of the\neffective (characteristic) exhaust velocity.  $I_{sp}$ contains\ninformation on the energy stored in the fuel and how that energy\ntranslates to exit velocity.   When $I_{sp}$ is calculated from\nmeasured thrust data, the $I_{sp}$ contains a correction for exhaust\nvelocity for force due to pressure $(P_e - P_a)A_e$.\n\nThe characteristic velocity, and hence $I_{sp}$, depend on the type\nof fuel and the inlet temperature and pressure of the fuel.\nExperimental data determines how\n%\n\\begin{equation}\n    I_{sp}(T_i,P_i) = \\left.\\frac{F_T}{\\dot{m}g_o}\\right|_{(T_i,P_i)}\n\\end{equation}\n%\n\\begin{tabbing}\n    12345678     \\= Reynolds number based on length $s$ \\kill\n    $\\dot{m}$    \\>  Known      \\\\\n    $T_i$        \\>  Known      \\\\\n    $P_i$        \\>  Known      \\\\\n    $g_o$        \\>  Known      \\\\\n    $F_T$        \\>  Measured   \\\\\n    $I_sp$       \\>  Calculated \\\\\n\\end{tabbing}\n\n\\include{TankModels}\n\n\\subsection{Mass Properties}\n\n\\subsubsection{Spherical Tank}\n\\clearpage\n\\begin{figure}[ht]\n\\centerline{\n    \\begin{picture}(110,440)\n    \\special{psfile= ./Images/PartiallyFilledTank.eps hoffset= -110 voffset=\n    90\n    hscale=55 vscale=55}\n    \\makebox(-47,665){$h$}\n    \\makebox(135,620){$r$}\n    \\makebox(0,695){$\\hat{y}$}\n    \\makebox(-165,850){$\\hat{z}$}\n    \\makebox(-165,515){($\\hat{x}$ is out of the page)}\n    \\end{picture}}\\vskip -3.65 in  \\caption{ Geometry For Mass Properties of Partially Filled Spherical Tank} \\label{fig:PartiallyFilledTank}\n\\end{figure}\n\n\\begin{equation}\n    V = \\frac{1}{3}\\pi \\left( 3r - h \\right)h^2\n\\end{equation}\n%\n\\begin{equation}\n    cg_z = \\displaystyle\\frac{-\\displaystyle\\frac{3}{4}h^2 + 3hr - 3r^2}{3r - h}\n\\end{equation}\n%\n\\begin{equation}\n    cg_x = cg_y = 0\n\\end{equation}\n%\n\\begin{equation}\n   I_{zz} = \\frac{\\pi \\rho}{2}\\left(\\frac{1}{5}\\left( h - r\\right)^5 - \\frac{2}{3}r^2\\left( h - r\\right)^3  + r^4(h-r) + \\frac{8}{15}r^5 \\right)\n\\end{equation}\n%\n\\begin{equation}\n   I_{xx} = \\frac{\\pi \\rho}{2}\\left(-\\frac{3}{10}\\left( h - r\\right)^5 + \\frac{1}{3}r^2\\left( h - r\\right)^3  + \\frac{1}{2}r^4(h-r) + \\frac{8}{15}r^5 \\right)\n\\end{equation}\n%\n\\begin{equation}\n   I_{yy} = I_{xx}\n\\end{equation}\n%\n\\begin{equation}\n    \\mathbf{I}' = \\mathbf{R}_{bt}^T\n    \\left(\\begin{array}{ccc}\n         I_{xx} & 0 & 0 \\\\\n         0 & I_{yy} & 0\\\\\n         0 & 0 & I_{zz}\\\\\n    \\end{array}\\right)\n     \\mathbf{R}_{bt} \\\n\\end{equation}\n%\nEstey \\cite{Estey:83} gives appoximate equations for the area of\ndifferent portions for a partially filled sphere. The area of the\nspherical shell in contact with the gaseous region is given by\n%\n\\begin{equation}\n   A_g = 4.0675 \\cdot V^{2/3}\\left(\\frac{V_g}{V}\\right)^{0.62376}\n\\end{equation}\n%\nThe area of the boundary between the liquid and the gaseous region\nis given by\n%\n\\begin{equation}\n   A_b = A_g - 3.4211 \\cdot V^{2/3}\\left(\\frac{V_g}{V}\\right)^{1.24752}\n\\end{equation}\n%\nFinally, the area of the spherical shell in contact with the liquid\nis given by\n%\n\\begin{equation}\n   A_l = \\pi D^2 - A_g\n\\end{equation}\n%\n\n%\\input{FlowModelling}\n", "meta": {"hexsha": "aa7c5a37137173481be3ca60eba11bb830e20c97", "size": 12598, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/SystemDocs/MathematicalSpecification/SpacecraftModel.tex", "max_stars_repo_name": "Randl/GMAT", "max_stars_repo_head_hexsha": "d6a5b1fed68c33b0c4b1cfbd1e25a71cdfb8f8f5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-01-01T13:14:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-09T07:05:07.000Z", "max_issues_repo_path": "doc/SystemDocs/MathematicalSpecification/SpacecraftModel.tex", "max_issues_repo_name": "ddj116/gmat", "max_issues_repo_head_hexsha": "39673be967d856f14616462fb6473b27b21b149f", "max_issues_repo_licenses": ["NASA-1.3"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-03-15T08:58:37.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-20T20:11:26.000Z", "max_forks_repo_path": "doc/SystemDocs/MathematicalSpecification/SpacecraftModel.tex", "max_forks_repo_name": "ddj116/gmat", "max_forks_repo_head_hexsha": "39673be967d856f14616462fb6473b27b21b149f", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-13T10:26:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-09T07:06:55.000Z", "avg_line_length": 34.0486486486, "max_line_length": 422, "alphanum_fraction": 0.6814573742, "num_tokens": 4238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.3201550256041377}}
{"text": "\\appchapter{Generated Data}\n\\label{appendix:data}\n\\section{Uniform}\n\\label{appendix:data:uniform}\n\\begin{figure}[H]\n\\centering\n\\begin{subfigure}{.8\\textwidth}\n\t\\includegraphics[width=.9\\textwidth]{img/0_UNIFORM_plot.png}\n\\end{subfigure}%\n\\begin{subfigure}{.2\\textwidth}\n  \\centering\n  \\begin{minipage}{1\\textwidth}\n\\textbf{Widths:}\n\\\\\nmin: 47\n\\\\\nmax: 47\n\\\\\nmean: 47.00\n\\\\\nvariance: 0.00\n\\\\\nstd: 0.00\n\\\\\nskewness: 0.00\n\\\\\nkurtosis: $-3.00$\n\\\\\\\\\n\\textbf{Heights:}\n\\\\\nmin: 109\n\\\\\nmax: 109\n\\\\\nmean: 109.00\n\\\\\nvariance: 0.00\n\\\\\nstd: 0.00\n\\\\\nskewness: 0.00\n\\\\\nkurtosis: $-3.00$\n  \\end{minipage}\n\\end{subfigure}\n% \\caption{Data distribution for 0\\_Uniform.in}\n% \\source{Compiled by the authors}\n\\end{figure}\n\\section{Random}\n\\label{appendix:data:rand}\n\\begin{figure}[H]\n\\centering\n\\begin{subfigure}{.8\\textwidth}\n\t\\includegraphics[width=.9\\textwidth]{img/1_RAND_plot.png}\n\\end{subfigure}%\n\\begin{subfigure}{.2\\textwidth}\n  \\centering\n  \\begin{minipage}{1\\textwidth}\n\\textbf{Widths:}\n\\\\\nmin: 7\n\\\\\nmax: 511\n\\\\\nmean: 259.78\n\\\\\nvariance: 21293.52\n\\\\\nstd: 145.92\n\\\\\nskewness: $-0.01$\n\\\\\nkurtosis: $-1.20$\n\\\\\\\\\n\\textbf{Heights:}\n\\\\\nmin: 13\n\\\\\nmax: 1201\n\\\\\nmean: 606.26\n\\\\\nvariance: 120065.68\n\\\\\nstd: 346.50\n\\\\\nskewness: 0.00\n\\\\\nkurtosis: $-1.20$\n  \\end{minipage}\n\\end{subfigure}\n% \\caption{Data distribution for 1\\_Rand.in}\n% \\source{Compiled by the authors}\n\\end{figure}\n\n\\section{Random with Constant Height}\n\\label{appendix:data:randconstheight}\n\\begin{figure}[H]\n\\centering\n\\begin{subfigure}{.8\\textwidth}\n\t\\includegraphics[width=.9\\textwidth]{img/2_RANDCONSTHEIGHT_plot.png}\n\\end{subfigure}%\n\\begin{subfigure}{.2\\textwidth}\n  \\centering\n  \\begin{minipage}{1\\textwidth}\n\\textbf{Widths:}\n\\\\\nmin: 7\n\\\\\nmax: 511\n\\\\\nmean: 258.52\n\\\\\nvariance: 21358.88\n\\\\\nstd: 146.15\n\\\\\nskewness: $-0.00$\n\\\\\nkurtosis: $-1.20$\n\\\\\\\\\n\\textbf{Heights:}\n\\\\\nmin: 109\n\\\\\nmax: 109\n\\\\\nmean: 109.00\n\\\\\nvariance: 0.00\n\\\\\nstd: 0.00\n\\\\\nskewness: 0.00\n\\\\\nkurtosis: $-3.00$\n  \\end{minipage}\n\\end{subfigure}\n% \\caption{Data distribution for 2\\_Randconstheight.in}\n% \\source{Compiled by the authors}\n\\end{figure}\n\n\\section{Random with Constant Width}\n\\label{appendix:data:randconstwidth}\n\\begin{figure}[H]\n\\centering\n\\begin{subfigure}{.8\\textwidth}\n\t\\includegraphics[width=.9\\textwidth]{img/3_RANDCONSTWIDTH_plot.png}\n\\end{subfigure}%\n\\begin{subfigure}{.2\\textwidth}\n  \\centering\n  \\begin{minipage}{1\\textwidth}\n\\textbf{Widths:}\n\\\\\nmin: $47$\n\\\\\nmax: $47$\n\\\\\nmean: $47.00$\n\\\\\nvariance: $0.00$\n\\\\\nstd: $0.00$\n\\\\\nskewness: $0.00$\n\\\\\nkurtosis: $-3.00$\n\\\\\\\\\n\\textbf{Heights:}\n\\\\\nmin: $13$\n\\\\\nmax: $1201$\n\\\\\nmean: $607.04$\n\\\\\nvariance: $119714.09$\n\\\\\nstd: $346.00$\n\\\\\nskewness: $-0.00$\n\\\\\nkurtosis: $-1.20$\n  \\end{minipage}\n\\end{subfigure}\n% \\caption{Data distribution for 3\\_Randconstwidth.in}\n% \\source{Compiled by the authors}\n\\end{figure}\n\\section{Skewed}\n\\label{appendix:data:skewed}\n\\begin{figure}[H]\n\\centering\n\\begin{subfigure}{.8\\textwidth}\n\t\\includegraphics[width=.9\\textwidth]{img/4_SKEWED_plot.png}\n\\end{subfigure}%\n\\begin{subfigure}{.2\\textwidth}\n  \\centering\n  \\begin{minipage}{1\\textwidth}\n\\textbf{Widths:}\n\\\\\nmin: 7\n\\\\\nmax: 511\n\\\\\nmean: 60.90\n\\\\\nvariance: 2490.82\n\\\\\nstd: 49.91\n\\\\\nskewness: 5.19\n\\\\\nkurtosis: 40.29\n\\\\\\\\\n\\textbf{Heights:}\n\\\\\nmin: 13\n\\\\\nmax: 1201\n\\\\\nmean: 195.35\n\\\\\nvariance: 17598.95\n\\\\\nstd: 132.66\n\\\\\nskewness: 2.40\n\\\\\nkurtosis: 14.07\n  \\end{minipage}\n\\end{subfigure}\n% \\caption{Data distribution for 4\\_Skewed.in with 1\\% total skewed options}\n% \\source{Compiled by the authors}\n\\end{figure}\n\\section{Skewed with Constant Height}\n\\label{appendix:data:skewedconstheight}\n\\begin{figure}[H]\n\\centering\n\\begin{subfigure}{.8\\textwidth}\n\t\\includegraphics[width=.9\\textwidth]{img/5_SKEWEDCONSTHEIGHT_plot.png}\n\\end{subfigure}%\n\\begin{subfigure}{.2\\textwidth}\n  \\centering\n  \\begin{minipage}{1\\textwidth}\n\\textbf{Widths:}\n\\\\\nmin: 7\n\\\\\nmax: 511\n\\\\\nmean: 61.06\n\\\\\nvariance: 2493.88\n\\\\\nstd: 49.94\n\\\\\nskewness: 5.15\n\\\\\nkurtosis: 39.87\n\\\\\\\\\n\\textbf{Heights:}\n\\\\\nmin: 13\n\\\\\nmax: 1201\n\\\\\nmean: 602.58\n\\\\\nvariance: 121471.29\n\\\\\nstd: 348.53\n\\\\\nskewness: 0.01\n\\\\\nkurtosis: $-1.22$\n  \\end{minipage}\n\\end{subfigure}\n% \\caption{Data distribution for 5\\_Skewedconstheight.in with 1\\% total skewed options}\n% \\source{Compiled by the authors}\n\\end{figure}\n\\section{Skewed with Constant Width}\n\\label{appendix:data:skewedconstwidth}\n\\begin{figure}[H]\n\\centering\n\\begin{subfigure}{.8\\textwidth}\n\t\\includegraphics[width=.9\\textwidth]{img/6_SKEWEDCONSTWIDTH_plot.png}\n\\end{subfigure}%\n\\begin{subfigure}{.2\\textwidth}\n  \\centering\n  \\begin{minipage}{1\\textwidth}\n\\textbf{Widths:}\n\\\\\nmin: 7\n\\\\\nmax: 507\n\\\\\nmean: 254.24\n\\\\\nvariance: 21164.27\n\\\\\nstd: 145.48\n\\\\\nskewness: 0.02\n\\\\\nkurtosis: $-1.21$\n\\\\\\\\\n\\textbf{Heights:}\n\\\\\nmin: 13\n\\\\\nmax: 1201\n\\\\\nmean: 194.23\n\\\\\nvariance: 17615.88\n\\\\\nstd: 132.72\n\\\\\nskewness: 2.41\n\\\\\nkurtosis: 14.05\n  \\end{minipage}\n\\end{subfigure}\n% \\caption{Data distribution for 6\\_Skewedconstwidth.in with 1\\% total skewed options}\n% \\source{Compiled by the authors}\n\\end{figure}", "meta": {"hexsha": "cd3d5fcf4846e43b38629981fcadbae2e0333618", "size": 4949, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/appendices/GeneratedData.tex", "max_stars_repo_name": "MartinMetaksov/diku.OptionsPricing", "max_stars_repo_head_hexsha": "1734801dddf7faa9e7c6ed1a46acb6ef8492e33c", "max_stars_repo_licenses": ["ISC"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-01-11T11:13:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T10:20:46.000Z", "max_issues_repo_path": "thesis/appendices/GeneratedData.tex", "max_issues_repo_name": "MartinMetaksov/diku.OptionsPricing", "max_issues_repo_head_hexsha": "1734801dddf7faa9e7c6ed1a46acb6ef8492e33c", "max_issues_repo_licenses": ["ISC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis/appendices/GeneratedData.tex", "max_forks_repo_name": "MartinMetaksov/diku.OptionsPricing", "max_forks_repo_head_hexsha": "1734801dddf7faa9e7c6ed1a46acb6ef8492e33c", "max_forks_repo_licenses": ["ISC"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-09T21:47:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-09T21:47:46.000Z", "avg_line_length": 15.1809815951, "max_line_length": 87, "alphanum_fraction": 0.6859971711, "num_tokens": 2083, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.32006976331715836}}
{"text": "\\documentclass[runningheads]{llncs}\n\n\\usepackage{graphicx}\n\\usepackage{placeins}\n\\usepackage{hyperref,xcolor}\n\\renewcommand\\UrlFont{\\color{blue}\\rmfamily}\n\\usepackage{amsmath}\n\n\\begin{document}\n\n\\title{Alternatives for Neighborhood Function in Kohonen Maps \\thanks{This work was supported by a private funding of Velbazhd Software LLC.}}\n\\titlerunning{Neighborhood in SOM}\n\n\\author{Iliyan Zankinski \\and\nKolyu Kolev \\and\nTodor Balabanov\\orcidID{0000-0003-3139-069X}}\n\\authorrunning{I. Zankinski et al.}\n\n\\institute{Institute of Information and Communication Technologies \\\\\nBulgarian Academy of Sciences \\\\\nacad. Georgi Bonchev Str., Block 2, 1113 Sofia, Bulgaria \\\\\n\\email{iliyan@hsi.iccs.bas.bg} \\\\\n\\url{http://iict.bas.bg/}}\n\n\\maketitle\n\n\\begin{abstract}\nIn the field of the artificial intelligence artificial neural networks are one of the most researched topics. Multilayer perceptron has a reputation for the most used type of artificial neural network, but other types such as Kohonen maps, generalized nets\\cite{tashev01} or combinations with Kalman filter\\cite{alexandrov01,voort01} are also very interesting. Proposed by Teuvo Kohonen in the 1980s, self-organizing maps have application in meteorology, oceanography, project prioritization and selection, seismic facies analysis for oil and gas exploration, failure mode and effects analysis, creation of artwork and many other areas. Self-organizing maps are very useful for visualization by data dimensions reduction. Unsupervised competitive learning is used in self-organizing maps and the basic idea is the net to classify input data in predefined number of clusters. When the net has fewer nodes it achieve results similar to K-means clustering. One of the components in the self-organizing maps is the neighborhood function. It gives scaling factor for the distance between one neuron and other neurons in each step. The simplest form of a neighborhood function gives 1 for the closest nodes and 0 for all other, but the most used neighborhood function is a Gaussian function. In this research fading cosine and exponential regulated cosine functions are proposed as alternatives for neighborhood function.\n\n\\keywords{Artificial neural networks \\and Self-organizing maps \\and Neighborhood functions.}\n\\end{abstract}\n\n\\section{Introduction}\n\nSelf-organizing maps or Kohonen Neural Networks (KNNs) are networks with unsupervised training \\cite{schreck01}. They are very useful in finding nonlinear dependencies when data are presented in very high dimensional spaces. The projection from the high-dimensional space is usually done in a rectangular lower-dimensional space \\cite{macq01}. The main idea behind KNNs is the organization of unlabeled vectors with particular features in predefined number of groups called clusters \\cite{cottrell01}. Grid of the self-organizing map is a handy tool for convenient visualization which can reveal different features of the network. SOMs are attractive when they consist of two or more separate regions. The real goal is not to find a perfect clustering but get good idea of the cluster structure. \n\n\\subsection{Clustering}\n\nClustering means a separation of the data set in set of groups. In separation where each data sample belongs exactly to only one group it is called straight clustering. If each data sample has varying degree of membership to different groups it is called fuzzy clustering.\n\nGenerally accepted concept of an optimal clustering is data set separation which minimizes the distance inside the cluster and maximizes the distance between the clusters. The most used form of distance measurement is the Euclidean norm \\cite{lozano01}. \n\n\\subsection{SOM Training}\n\nThe network consists of a grid (usually two dimensional \\cite{wehrens01}) with units. The units are connected to adjacent units with a neighborhood relation. The amount of grid units, which usually varies from a few dozen up to several thousand, gives the accuracy and generalization possibilities of the KNN. The network forms an elastic mesh that folds as a cloud formed by the input data during training phase. Data samples lying near each other in the input space are mapped into nearby grid units. \n\nThe network training is done iteratively. A data sample vector is randomly chosen from the input data set, as first step. As second step, distances between the selected vector and all the prototype vectors are computed. The best matching unit is the grid unit with prototype closest the selected vector. In the third step, the prototype vectors in the grid are updated. The best matching unit and its topological neighbors are moved closer to the input vector in the input space \\cite{vesanto01,аmerijckx01}.\n\n\\section{Neighborhood Function}\n\nThe most used KNN's neighborhood function is the Gaussian function. In this research two alternative functions are proposed. The first function is fading cosine, which is shown in Fig.\\ref{fig01}-Left. The second function is exponential regulated cosine, which is shown in FIg.\\ref{fig01}-Right.\n\n\\begin{figure}\n\\includegraphics[width=1.0\\textwidth]{fig01.png}\n\\centering\n\\caption{Left - Fading cosine neighborhood function. Right - Exponential regulated cosine neighborhood function.} \\label{fig01}\n\\end{figure}\n\\FloatBarrier\n\nThe idea for the both functions is to stress grid nodes down and up. The exponential regulated cosine Eq.\\ref{equ02} gives smoother stress than the fading cosine Eq.\\ref{equ01}. \n\n\\begin{equation} \\label{equ01}\nf(x) = \n\t\\begin{cases} \n\t\tcos(x) & -\\pi/2 < x < \\pi/2 \\\\\n\t\t\\frac{cos(x)}{|x|} & +\\pi/2 \\geq x \\leq -\\pi/2 \\\\\n\t\\end{cases}\n\\end{equation}\n\n\\begin{equation} \\label{equ02}\nf(x) = \\frac{cos(x)}{e^{|x|}}\n\\end{equation}\n\n\\section{Experiments and Results}\n\nAll experiments were done on a single processor desktop machine - Intel Core i5, 2.3 GHz, 2 Cores, 8GB RAM and Mac OS X 10.13.6, Apple LLVM version 9.1.0.\n\n\\begin{figure}\n\\includegraphics[width=1.0\\textwidth]{fig03.png}\n\\centering\n\\caption{Rents and living area data set \\cite{garriga01}.} \\label{fig03}\n\\end{figure}\n\\FloatBarrier\n\nAs experimental data set rents and living area (shown in Fig.\\ref{fig03}) are taken from the open source project, which can be found at \\cite{garriga01}. \n\nExperiments are done with Gausssian neighborhood function Fig.\\ref{fig02}-Left, fading cosine neighborhood function Fig.\\ref{fig02}-Center and exponential regulated cosine neighborhood function Fig.\\ref{fig02}-Right. Results show that fading cosine function performs less effective than exponential regulated cosine, but exponential regulated cosine gives sharper clusters separation than the Gaussian function. All three functions give clear clusterization. Data are separated in four common groups as it is shown on middle row of Fig. \\ref{fig02}.\n\n\\begin{figure}\n\\includegraphics[width=1.0\\textwidth]{fig02.png}\n\\centering\n\\caption{Left - Gausssian neighborhood function. Center - Fading cosine neighborhood function. Right - Exponential regulated cosine neighborhood function.} \\label{fig02}\n\\end{figure}\n\\FloatBarrier\n\n\\section{Conclusions}\n\nThe proposed neighbor functions give promising results as it is shown in the experimental section. Stressing the neighboring nodes down and up leads to better separation between the formed clusters. As further research it will be interesting the proposed neighborhood functions to be combined with different distance norms. In some problems Hausdorff distance can be used for example. Situations in time series \\cite{atanasova01} are also interesting for classification with KNN and the capabilities of the soft computing \\cite{angelova01}.\n\n\\begin{thebibliography}{8}\n\n\\bibitem{tashev01}\nTashev, T., Hristov, H.: Modeling of synthesis of information processes with generalized nets. Cybernetics and Information Technologies, \\textbf{3}(2), 92--104 (2003) \n\n\\bibitem{alexandrov01}\nAlexandrov, A.: AD HOC Kalman filter based fusion algorithm for real-time Wireless Sensor Data Integration. In: FQAS-2015 Proceedings, pp. 151--160. Springer, Heidelberg (2015)\n\n\\bibitem{voort01}\nvan der Voort, M., Dougherty, M.,Watson, S.: Combining kohonen maps with arima time series models to forecast traffic flow. Transportation Research Part C: Emerging Technologies, \\textbf{4}(5), 307--318 (1996) \n\n\\bibitem{schreck01}\nSchreck, T., Bernard, J., Landesberger, T. von, Kohlhammer, J.: Visual Cluster Analysis of Trajectory Data with Interactive Kohonen Maps. Information Visualization, \\textbf{8}(1), 14--29 (2009)\n\n\\bibitem{macq01}\nMacq, D., Verleysen, M., Jespers, P., Legat, J.D.: Analog implementation of a Kohonen map with on-chip learning. IEEE Transactions on Neural Networks, \\textbf{4}(3), 456--461 (1993)\n\n\\bibitem{cottrell01}\nCottrell M., Letremy P., Roy E.: Analysing a contingency table with Kohonen maps: A factorial correspondence analysis. In: Mira J., Cabestany J., Prieto A. (eds) New Trends in Neural Computation. Lecture Notes in Computer Science, pp. 305--311. Springer, Heidelberg (1993)\n\n\\bibitem{lozano01}\nLozano, S., Guerrero, F., Onieva, L., Larraneta, J.: Kohonen maps for solving a class of location-allocation problems. European Journal of Operational Research, \\textbf{108}(1), 106--117 (1998)\n\n\\bibitem{wehrens01}\nWehrens, R., Buydens, L.: Self- and Super-organizing Maps in R: The kohonen Package. Journal of statistical software, \\textbf{21}(5), 1--19 (2007)\n\n\\bibitem{vesanto01}\nVesanto, J., Alhoniemi, E.: Clustering of the Self-Organizing Map. IEEE Transactions on Neural Networks, \\textbf{11}(3), 586--600 (2000) \n\n\\bibitem{аmerijckx01}\nAmerijckx, C., Verleysen, M., Thissen, P., Legat, J.D.: Image compression by self-organized Kohonen map. IEEE Transactions on Neural Networks, \\textbf{9}(3), 503--507 (1998)\n\n\\bibitem{garriga01}\nComplete C implementation of the Kohonen Neural Network (SOM algorithm), \\url{http://github.com/Coding-Sunday-Sofia/Kohonen}. Last accessed 01 Mar 2019\n\n\\bibitem{atanasova01}\nAtanasova T., Barova M.: Exploratory analysis of Time Series for hypothesize feature values. In: UniTech17 Proceedings,  \\textbf{16}(2), 399--403 (2017)\n\n\\bibitem{angelova01}\nAngelova, V.: Investigations in the Area of Soft Computing Targeted State of the Art Report. Cybernetics and Information Technologies \\textbf{9}(1), 18--24 (2009)\n\n\\end{thebibliography}\n\\end{document}\n", "meta": {"hexsha": "d51ec734e716d92d4e934a310c00a17d2555331d", "size": 10268, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Alternatives-for-Neighborhood-Function-in-Kohonen-Maps/paper.tex", "max_stars_repo_name": "TodorBalabanov/Large-Scale-Scientific-Computations-2019", "max_stars_repo_head_hexsha": "c265ba248244c59ab90af608c6b4fcc5cfae77d0", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-01-01T14:41:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-01T14:41:16.000Z", "max_issues_repo_path": "Alternatives-for-Neighborhood-Function-in-Kohonen-Maps/paper.tex", "max_issues_repo_name": "TodorBalabanov/Large-Scale-Scientific-Computations-2019", "max_issues_repo_head_hexsha": "c265ba248244c59ab90af608c6b4fcc5cfae77d0", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Alternatives-for-Neighborhood-Function-in-Kohonen-Maps/paper.tex", "max_forks_repo_name": "TodorBalabanov/Large-Scale-Scientific-Computations-2019", "max_forks_repo_head_hexsha": "c265ba248244c59ab90af608c6b4fcc5cfae77d0", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 71.8041958042, "max_line_length": 1415, "alphanum_fraction": 0.7900272692, "num_tokens": 2570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.32006975532940757}}
{"text": "\\section{Methodology}\n%Description of D3ploy\nIn \\Cyclus, developers have the option to design \nagents using C++ or Python. \nThe \\deploy \\texttt{Institution} agent was \nimplemented in Python to enable the use of \nwell-developed time series forecasting Python packages. \n\nDuring a \\Cyclus simulation, at every time step, \\deploy \npredicts the supply and demand of each commodity for the next time \nstep. \nIt is assumed that facility deployment occurs \nwithin one time step (month). \nCommodities refer to materials in the nuclear fuel cycle such as \nreactor fuel. \nUpon undersupply for any commodity, \n\\deploy deploys facilities to meet its predicted demand.\nTherefore, if the simulation begins with user-defined power \ndemand, \\deploy deploys reactors to meet power demand, \nfollowed by enrichment facilities to meet fuel demand, and so on,\nto create the supply chain.\nBased on the demand and supply trends of each commodity, \n\\deploy predicts their \nfuture demand and supply, and deploys facilities \naccordingly to meet the future demand to prevent demand \nfrom surpassing supply. \nFigure \\ref{fig:flow} shows the logical flow of \\deploy \nat every time step. \nIn subsequent subsections, we describe how to set up a \ntransition scenario using \\deploy and the input parameters \n\\deploy accepts. \n\n\\begin{figure}[]\n\t\\centering\n\t\\resizebox{0.8\\textwidth} {0.8\\height}{\n    \\begin{tikzpicture}[node distance=2.5cm]\n    \\tikzstyle{every node}=[font=\\large]\n\t\\node (Start) [bblock] {\\textbf{Start time step ($t$).}};\n\t\\node (Predict) [bblock, below of=Start] {\\textbf{Calculate predicted $D(t+1)$ and $S(t+1)$ for a commodity}};\n\t\\node (IsThere) [oblock, below of=Predict]{\\textbf{$U(t+1) = S(t+1)-D(t+1)$}};\n\t\\node (Deploy) [bblock, below of=IsThere, xshift = -3.5cm]{\\textbf{Deploy Facilities}};\n    \\node (NoDeploy) [bblock, right of=Deploy, xshift = 3.5cm]{\\textbf{No Deployment} };\n    \\node (All) [oblock, below of=Deploy, xshift = 3.5cm] {\\textbf{Has $D(t+1)$ and \\\\ $S(t+1)$ been calculated for all commodities?}};\n    \\node (End) [bblock, below of=All] {\\textbf{Proceed to next time step.}};\n\t\n\t\\draw [arrow] (Start) -- (Predict); \n\t\\draw [arrow] (Predict) -- (IsThere);\n    \\draw [arrow] (IsThere) -- node[anchor=east] {$U(t+1) <$ buffer} (Deploy);\n    \\draw [arrow] (IsThere) -- node[anchor=west] {$U(t+1) \\geq$ buffer} (NoDeploy);\n    \\draw [arrow] (Deploy) -- (All);\n    \\draw [arrow] (NoDeploy) -- (All);\n    \\draw [arrow] (All) -- node[anchor=west] {yes} (End);\n    \\draw [arrow] (All) -- ([shift={(-4cm,0.8cm)}]All.south west)-- node[anchor=east] {no} ([shift={(-4cm,-0.8cm)}]Predict.north west)--(Predict);\n    \\draw [arrow] (End) |-([shift={(3cm,-0.5cm)}]End.south east)-- ([shift={(3cm,0.5cm)}]Start.north east)-|(Start);\n\t\\end{tikzpicture}\n\t}\n    \\caption{\\deploy logic flow at every time step in \\Cyclus \\cite{chee_demonstration_2019}.}\n    \\label{fig:flow}\n\\end{figure}\n\n\\deploy aims to minimize the undersupply of power:\n\\begin{align}\n\t\\label{eq:pow}\n\t\\textrm{obj} &= \\min \\sum_{t=1}^{t_{f}} |D_{t,p}-S_{t,p}|.\n    \\intertext{where:}\n    t_f &= \\mbox{Number of time steps [months]} \\nonumber \\\\ \n    t &= \\mbox{time [month]} \\nonumber \\\\\n\tD &= \\mbox{Demand} \\nonumber\\\\\n\tS &= \\mbox{Supply} \\nonumber\\\\\n\tp &= \\mbox{power [MW]} \\nonumber \n\\end{align} \nThe sub-objectives are to minimize the number of time \nsteps of undersupply or under-capacity of any \ncommodity: \n\\begin{align}\n\t\\label{eq:sub1}\n    obj &= min \\sum_{c=1}^{M}\\sum_{t=1}^{t_f} |D_{t,c}-S_{t,c}|, \\\\\n    \\intertext{and to minimize excessive oversupply of all commodities: }\n    obj &= min \\sum_{c=1}^{M}\\sum_{t=1}^{t_f} |S_{t,c}-D_{t,c}|. \\\\\n    \\intertext{where:}\n    c &= \\mbox{commodity type} \\nonumber \\\\\n\tM &= \\mbox{Number of commmodities} \\nonumber\n\\end{align}\n\nMinimizing excessive oversupply \nreflects reality, in which utilities ensure grid availability \nby ensuring power plants are never short of fuel while \navoiding expensive storage of excess fuel. \nNuclear fuel cycle simulations often face power shortages \ndue to lack of viable fuel, despite having sufficient installed \nreactor capacity.  \nUsing \\deploy to automate the deployment of supporting \nfacilities prevents this.  \n\n\\subsection{Structure}\nFront-end facilities \nmeet the demand for commodities they produce, whereas back-end \nfacilities meet supply for the commodities they demand. \nTherefore, in \\deploy two distinct institutions control \nfront-end and back-end fuel cycle facilities: \n\\texttt{DemandDrivenDeploymentInst} and \n\\texttt{SupplyDrivenDeploymentInst}, respectively. \nFor example, when a reactor facility \ndemands fuel, \\texttt{DemandDriven-}\n\n\\noindent\n\\texttt{DeploymentInst}\ndeploys fuel fabrication facilities to create fuel\nsupply. \nFor back-end facilities, the reactor generates spent fuel, and \n\\texttt{SupplyDrivenDeploymentInst} deploys \nused fuel storage facilities to create capacity to store the spent fuel. \nFigure \\ref{fig:insts} depicts a simple once-through fuel cycle \nand the \\texttt{Institution} type governing each \nfacility's deployment.    \n\n\\begin{figure}[]\n\t\\centering\n\t\\resizebox{\\textwidth}{!}{\n\t\\trimbox{0cm -.5cm 0cm 0cm}{ \n\\begin{tikzpicture}[node distance=2.7cm,auto,>=latex']\n\t\\tikzstyle{every node}=[font=\\scriptsize]\n    \\node [bbslock] (a) {\\textbf{Mine}};\n    \\node [bbslock] (b) [right of=a] {\\textbf{Enrichment \\\\ Facility}};\n\t\\node [bbslock] (c) [right of=b] {\\textbf{Reactor}};\n\t\\node [obslock] (d) [right of=c] {\\textbf{Cooling \\\\ Pool}};\n\t\\node [obslock] (e) [right of=d] {\\textbf{Repository}};\n    \\path[->] (a) edge node {\\shortstack{Natl \\\\ U}} (b);\n    \\draw [arrow] (b) -- ([xshift=0.5cm,yshift=0.9cm]b.north west)-- node[anchor=south] {Demand for Natl U} ([shift={(0cm,0.9cm)}]a.north)--(a);\n    \\draw [arrow] (c) -- ([shift={(0.5cm,0.9cm)}]c.north west)-- node[anchor=south] {Demand for Fuel} ([shift={(0cm,0.9cm)}]b.north)--(b);\n    \\draw [arrow] (c) -- ([shift={(1.5cm,0.9cm)}]c.north west)-- node[anchor=south] {\\shortstack{Demand for Cooling \\\\ Pool Capacity}} ([shift={(0cm,0.9cm)}]d.north)--(d);\n\t\\draw [arrow] (d) -- ([shift={(1.5cm,0.9cm)}]d.north west)-- node[anchor=south] {\\shortstack{Demand for \\\\ Repository Capacity}} ([shift={(0cm,0.9cm)}]e.north)--(e);\n    \\draw[->] (b) edge node {Fuel} (c) ;\n\t\\draw[->] (c) edge node {\\shortstack{Used \\\\ Fuel}} (d) ;\n\t\\draw[->] (d) edge node {\\shortstack{Cooled \\\\ Used \\\\ Fuel}} (e) ;\n\\end{tikzpicture}\n\t}}\n\n\\resizebox{0.5\\textwidth}{!}{\n    \\fbox{\\begin{tabular}{ll}\n        \\textcolor{illiniblue}{$\\blacksquare$} & Deployed by \\texttt{DemandDrivenDeploymentInst}\\\\\n        \\textcolor{illiniorange}{$\\blacksquare$} & Deployed by \\texttt{SupplyDrivenDeploymentInst} \n\t\t\\end{tabular}}}\n\t\t\\caption{Simple once-through fuel cycle depicting which facilities are deployed by \n\t\t\\texttt{DemandDrivenDeploymentInst} and \\texttt{SupplyDrivenDeploymentInst}.}\n\\label{fig:insts}\n\\end{figure}\n\n\\subsubsection{Deployment-Driving Method}\n\\label{sec:ddm}\nTo prevent over-deployment of facilities with an intermittent \nsupply such as reactors that require refueling, and\nto prevent infinite deployment of a facility that demands \na commodity no longer available in the simulation, \nwe introduced the capability to deploy facilities \nbased on the difference between predicted demand and installed capacity. \nThe user may deploy facilities based on the difference \nbetween predicted demand and predicted supply, \\textit{or}\npredicted demand and installed capacity. \nFor example, a reprocessing plant that fabricates Sodium-Cooled Fast Reactor \n(SFR) fuel demands for Pu after depletion of the existing Pu inventory and \ndecommissioning of the \\glspl{LWR} that produce it. \nIf we used the deployment-driving method driven by \nthe difference in predicted demand and predicted supply, this results in \ninfinite deployment of reprocessing facilities in a futile attempt \nto produce SFR fuel, crashing the simulation. \nInstead, if we use the deployment-driving method driven by the\ndifference in predicted demand and installed capacity, only one reprocessing \nfacility will be deployed, the simulation will finish, and the user will see that \na large Pu inventory must be accumulated. \nTherefore, using the deployment-driving method that deploys facilities based on \nthe difference between predicted demand and installed capacity is ideal for most \ntransition scenarios. \n\n\\subsection{Input Variables}\nTable \\ref{tab:inputs} lists and gives examples of the input \nvariables \\deploy accepts. \nThe user must define the following input variables:\n\\begin{enumerate}\n\\item \\textbf{The available facilities for \\deploy to deploy in the simulation and their respective capacities.}\nUsers must define the facilities they want \\deploy to deploy. It is the user's responsibility to \nensure the defined facilities create a supply chain to produce the demand driving commodity.\n\\item \\textbf{The demand driving commodity and its demand equation.} For most simulations, the demand driving \ncommodity is power. The demand equation is defined by a mathematical equation with units of MW. For example, \na constant power demand equation is $10000$, while a linearly increasing power demand equation is $100t$.\n\\item \\textbf{The deployment driving method}. This input variable is described in Section \\ref{sec:ddm}. \n\\item \\textbf{The prediction method}. This input variable is described in Section \\ref{sec:pm}.\nThere are also optional input variables: \n\\item \\textbf{Supply/capacity buffers for individual commodities.} This input variable is described in \nsection \\ref{sec:buf}.\n\\item \\textbf{Facility preferences.} This input variable is described in section \\ref{sec:pref}.\n\\item \\textbf{Facility fleet shares.} This input variable is described in section \\ref{sec:pref}.\n\\end{enumerate}\n\n\\begin{table}[]\n\t\\centering\n    \\caption{\\deploy's required and optional input parameters with examples.}\n    \\label{tab:inputs}\n        \\begin{tabular}{l|ll}\n        \\hline\n            & \\textbf{Input Parameter}                                                           & \\textbf{Examples}                                                                                                          \\\\ \\hline\n            \\multirow{5}{*}{\\textbf{Required}} & Demand driving commodity                                                           & Power                                                                                                                      \\\\ \\cline{2-3} \n                                                      & Demand equation [MW]                                                                   & P(t) = $10000, sin(t), 10000t$                                                                                                                 \\\\ \\cline{2-3} \n                                                      & Available Facilities                                                             & Mine, \\gls{LWR}, Repository, etc.                                                                                                      \\\\ \\cline{2-3} \n                                                      & Capacities of the facilities                                                       & 3000 kg, 1000 MW, 50000 kg                                                                                                     \\\\ \\cline{2-3} \n                                                      & Prediction method                                                                  & \\begin{tabular}[c]{@{}l@{}}Power: Fast Fourier Transform\\\\ Fuel: Moving Average\\\\ Spent fuel: Moving Average\\end{tabular} \\\\ \\cline{2-3} \n                                                      & Deployment driven by & Installed Capacity                                                                                                                    \\\\ \\hline\n            \\multirow{4}{*}{\\textbf{Optional}} & Supply/Capacity Buffer type                                                                        & Absolute                                                                                                                  \\\\ \\cline{2-3} \n                                                      & Supply/Capacity Buffer size                                                                        & \\begin{tabular}[c]{@{}l@{}}Power: 3000 MW\\\\ Fuel: 0 kg \\\\ Spent fuel: 0 kg\\end{tabular}                                   \\\\ \\cline{2-3} \n                                                      & Facility preferences [month]                                                              & \\begin{tabular}[c]{@{}l@{}}\\gls{LWR} = 100-t\\\\ SFR = t-99 \\end{tabular}          \\\\ \\cline{2-3} \n                                                      & Fleet share percentage [\\%]                                                            & \\begin{tabular}[c]{@{}l@{}}MOX \\gls{LWR} = 85\\%\\\\ SFR = 15\\% \\end{tabular}          \\\\ \\hline\n                    \\end{tabular}\n\\end{table}\n\\subsubsection{Supply/Capacity Buffer}\n\\label{sec:buf}\nThe user has the option to specify a \nsupply buffer for each commodity; \\deploy accounts for the buffer when \ncalculating predicted demand and deploys facilities accordingly.\nThe buffer is defined as a percentage: \n\\begin{align}\n\tS_{pwb} &= S_{p}(1+d)\n\\intertext{or an absolute value:}\n    S_{pwb} &= S_{p}+b \n\\end{align}\n    \\begin{align}\n\t\\intertext{where:}\n\tS_{pwb} &= \\mbox{predicted supply/capacity with buffer} \\nonumber\\\\\n\tS_p &= \\mbox{predicted supply/capacity} \\nonumber\\\\\n\td &= \\mbox{buffer's percentage value in decimal form} \\nonumber\\\\\n\tb &= \\mbox{buffer's absolute value} \\nonumber\n\\end{align}\n\nUsing the buffer capability and  \ninstalled capacity to drive facility deployment in a transition \nscenario simulation will effectively minimize undersupply of a \ncommodity while avoiding excessive oversupply. \nThis is demonstrated in Section \\ref{sec:demo}. \n\n\\subsection{Facility Preference and Fleet Share}\n\\label{sec:pref}\nThe user can define time-dependent preference equations to facilities'  \nthat supply the same commodity. \nIf there are two reactor types, \\glspl{LWR} and \\glspl{SFR}, in a simulation, \nthe user can make use of time-dependent \npreferences to make the simulation deploy \\glspl{LWR} at earlier times \nin the simulation, and deploy SFRs at later times in the \nsimulation when there is a power demand. \nIn Table \\ref{tab:inputs}, \nthe user defined that the \\gls{LWR} has a preference of $100-t$, while \nthe SFR has a preference of $t-99$. \nFigure \\ref{fig:prefplot} depicts how the preference for each reactor changes \nwith time. \nWhen there is a power undersupply, \\deploy will deploy the reactor that has a\nlarger preference at that time step.\nAt time step 100, \\gls{LWR} preference is 0, while SFR preference is 1; \ntherefore an SFR is deployed if there is a power shortage. \nThus, the transition occurs at the $100^{th}$ time step.\n\n\\begin{figure}[]\n\t\\begin{center}\n\t\t\\includegraphics[width=\\linewidth]{./figures/prefplot}\n\t\\end{center}\t\n\t\t\\caption{\\deploy has a $100-t$ preference for \\glspl{LWR} and a $t-99$ preference for SFRs.\n\t\tWhen there is a power undersupply, \\deploy will deploy the reactor that has a\n\t\tlarger preference at that time step.}\n\t\\label{fig:prefplot}\n\\end{figure}\n\nThe user also has the option to specify percentage-share for facilities \nthat provide the same commodity. \nFor example, if there are two reactor types, \\gls{MOX} \\glspl{LWR} and SFRs, in a simulation,\nthe user can make use of percentage-share specifications to determine the \npercentage of power supplied by each reactor.   \nWhen MOX \\gls{LWR} has a share of $s\\%$ and \n\\gls{SFR} has a share of $(100-s)\\%$, \nMOX \\gls{LWR} deployment constrains to $s\\%$ of total power demand \nand SFR deployment constrains to $(100-s)\\%$ of total power demand.  \n\nThe transition year is selected by customizing facility \npreferences to prefer advanced reactors at that year.\nThe fleet-share percentage determines the\nshare of each type of reactor to transition to. \nFigure \\ref{fig:deployflow} shows the logical flow of\nwhich facility \\deploy deploys when there are multiple facilities \noffering the same commodity. \n\n\\begin{figure}[]\n\t\\centering\n\t\\resizebox{0.9\\textwidth} {0.8\\height}{\n    \\begin{tikzpicture}[node distance=3cm]\n    \\tikzstyle{every node}=[font=\\large]\n    \\node (fs)[olblock]{\\textbf{Are there fleet share constraints?}};\n    \\node (fsyes) [bbmlock, below of=fs, xshift = -3.5cm] {\\textbf{Deploy facilities to meet fleet share $\\%$}};\n    \\node (pref) [olblock, right of=fsyes, xshift = 3.5cm]{\\textbf{Are there facility \\\\ preferences?}};\n    \\node (prefyes) [bbmmlock, below of=pref, xshift = -3cm] {\\textbf{Deploy facilities in preference order to meet their fleet share \\%}};\n    \\node (prefno) [bbmlock, right of=prefyes, xshift = 3cm, yshift=-0.05cm] {\\textbf{Deploy facilities to minimize total no. of facilities and minimize oversupply.}};\n\t\\draw [arrow] (fs) -- node[anchor=east] {yes} (fsyes);\n    \\draw [arrow] (fs) -- node[anchor=east] {no} (pref);\n    \\draw [arrow] (pref) -- node[anchor=east] {yes} (prefyes);\n    \\draw [arrow] (pref) -- node[anchor=east] {no} (prefno);\n\t\\end{tikzpicture}}\n\t\n    \\caption{Logical flow of how \\deploy \n\tselects which facility to deploy when there are multiple facilities \n\toffering the same commodity.}\n\t\\label{fig:deployflow}\n\\end{figure}\n\n\\subsection{Prediction Methods}\n\\label{sec:pm}\n\\deploy records supply and demand at each time step for all \ncommodities. Time-series data informs \\deploy's time series \nforecasting methods which predict future supply and demand for each \ncommodity.  \nThe time series forecasting methods investigated include non-optimizing, \ndeterministic-optimizing, and stochastic-optimizing methods. \nNon-optimizing methods are techniques that harness \nsimple moving average and autoregression concepts which use \nhistorical data to infer future supply and demand values. \nDeterministic-optimizing and stochastic-optimizing \nmethods are techniques \nthat use an assortment of more sophisticated time series forecasting \nconcepts to predict future supply and demand values. \nDeterministic-optimizing methods give deterministic solutions,\nwhile stochastic-optimizing methods give stochastic solutions. \n\nDepending on the scenario in question, each forecasting method \noffers distinct benefits and disadvantages.\nThe various methods are compared for each type of simulation \nto determine the most effective prediction method for \na given scenario. \nThe following sections describe the prediction methods. \n\n\\subsubsection{Non-Optimizing Methods}\nNon-optimizing methods include: Moving Average (\\texttt{MA}), \nAutoregressive Moving Average (\\texttt{ARMA}), and \nAutoregressive Heteroskedasticity (\\texttt{ARCH}). \nThe \\texttt{MA} method calculates the average of \na user-defined number of previous entries in a commodity's \ntime series and returns it as the predicted value \n(equation \\ref{eq:ma}).\n\n\\begin{align}\n\t\\label{eq:ma}\n\tPV &= \\frac{\\sum_{n=1}^N V_n}{n}\n    \\intertext{where:}\n    PV &= \\mbox{predicted value} \\nonumber \\\\\n\tV_n &= \\mbox{time series value} \\nonumber\\\\\n\tN &= \\mbox{length of time series} \\nonumber\n\\end{align}\n\nThe \\texttt{ARMA} method combines moving average and\nautoregressive models (equation \\ref{eq:arma}).\nThe first term is a constant, the second term is \nwhite noise, the third term is the autoregressive\nmodel, and the fourth term is the moving average\nmodel.\nThe \\texttt{ARMA} method is more accurate than the \n\\texttt{MA} method \nbecause of the inclusion of the autoregressive term: \n\\begin{align}\n\t\\label{eq:arma}\n\tX_t &= c + \\epsilon_t + \n\t\\sum_{i=1}^p\\varphi_i X_{t-i} +\t\n\t\\sum_{i=1}^q\\theta_i\\epsilon_{t-i}.\n\t\\intertext{where:}\n    c &= \\mbox{a constant} \\nonumber\\\\\n    \\epsilon_t &= \\mbox{error terms (white noise)} \\nonumber\\\\\n    \\varphi &= \\mbox{the autoregressive model’s parameters} \\nonumber\\\\\n    \\theta &= \\mbox{the moving average model’s parameters} \\nonumber \\\\\n    p &= \\mbox{order of the autoregressive polynomial} \\nonumber \\\\\n    q &= \\mbox{order of the moving average polynomial} \\nonumber\n\\end{align}\n\nThe \\texttt{ARCH} method models time series data by describing the \nvariance of the current \nerror term as a function of the sizes of the previous time periods' \nerror terms \\cite{engle_autoregressive_1982}. \nThis allows the method to support changes in the time dependent volatility, \nsuch as increasing and decreasing volatility in the same series\n\\cite{engle_autoregressive_1982}.\nThe \\texttt{ARCH} method is\nbetter than the \\texttt{ARMA} method for volatile \ntime-series data \\cite{flanagan_methods_2019}. \nThe StatsModels \\cite{seabold_statsmodels:_2010}\nPython package is used to implement \\texttt{ARMA} and \n\\texttt{ARCH} methods in \\deploy. \n\n\\subsubsection{Deterministic-Optimizing Methods}\nDeterministic methods include\nFast Fourier Transform (\\texttt{FFT}), \nPolynomial Fit (\\texttt{POLY}), \nExponential Smoothing (\\texttt{EXP-SMOOTHING}), \nand Triple Exponential Smoothing (\\texttt{HOLT-WINTERS}). \nThe \\texttt{FFT} method uses the fast Fourier transform\nalgorithm to map a time series into the frequency domain. \nThe algorithm returns complex numbers from which frequency, \namplitude, and phase is extracted. \nFuture demand and supply values are predicted by summing \nthe significant components, then using the inverse \nFourier transform method to return it into a usable form. \nThe discrete Fourier transform (DFT) transforms a sequence of \nN complex numbers ($X_k$) into another sequence of complex numbers\n($x_n$) \\cite{rao_fast_2011}:\n\\begin{align}\n\t\\label{eq:fft}\n\tX_k &= \\sum_{n=0}^{N-1}x_n e^{-i2\\pi kn/N}.\n    \\intertext{where:}\n    X &= \\mbox{sequence of complex numbers} \\nonumber \\\\\n    k &= 0,...,N-1 \\nonumber\\\\\n    N &= \\mbox{No. of complex numbers} \\nonumber\\\\\n    x &= \\mbox{sequence of complex numbers} \\nonumber \\\\\n    n &= 0,...,N-1 \\nonumber\n\\end{align}\n\n\\noindent\nThis method is implemented in \\deploy using the \nSciPy \\cite{jones_scipy:_2016} Python package. \n\nThe \\texttt{POLY} method fits the time series data \nwith a user-defined $n^{th}$ degree polynomial and uses \nthe fitted trend-line to determine future demand and \nsupply values: \n\n\\begin{align}\n    Y_t &= \\beta_0 + \\sum_{n=1}^N \\beta_n t^n + \\varepsilon \\\\\n    \\intertext{where:}\n    t &= \\mbox{time index} \\nonumber \\\\\n    n &= \\mbox{polynomial order} \\nonumber \\\\\n    \\beta &= \\mbox{fitted parameters} \\nonumber \\\\\n    \\varepsilon &= \\mbox{unobserved random error} \\nonumber\n\\end{align}\n\n\\noindent\nThis method was implemented in \\deploy using the \nNumPy \\cite{oliphant_guide_2006} Python package. \n\nThe \\texttt{EXP-SMOOTHING} and \\texttt{HOLT-WINTERS} \nmethods use a weighted average \nof time-series data with exponentially decaying weights \nfor older time series values \\cite{hyndman_forecasting:_2018}\nto create a model to determine future demand and supply values. \nThe \\texttt{EXP-SMOOTHING} method excels in \nmodeling univariate time series data without trend or seasonality\n\\cite{hyndman_forecasting:_2018}: \n\n\\begin{align}\n    \\label{eq:expsm}\n    y_{t+1} &= \\alpha y_i + (1-\\alpha)y_t. \\\\ \n    \\intertext{where:}\n    y &= \\mbox{timeseries value} \\nonumber \\\\\n    \\alpha &= \\mbox{smoothing factor } (0 < \\alpha < 1) \\nonumber\n\\end{align}\n\n\\noindent\nThe \\texttt{HOLT-WINTERS} method applies triple exponential \nsmoothing, resulting in higher accuracy when \nmodeling seasonal time series data \n\\cite{sematech_engineering_2006}: \n\n\\begin{align}\n    F_{t+m} &= (S_t +mb_t)I_{t-L+m} \\\\\n    S_t &= \\alpha \\frac{y_t}{I_{t-L}}+(1-\\alpha)(S_{t-1}+b_{t-1}) \\nonumber \\\\\n    b_t &= \\gamma(S_t-S_{t-1})+)(1-\\gamma)b_{t-1} \\nonumber \\\\\n    I_t &= \\beta \\frac{y_t}{S_t} + (1-\\beta)I_{t-L} \\nonumber \\\\\n    \\intertext{where:}\n    F &= \\mbox{forecast at m periods ahead} \\nonumber \\\\\n    t &= \\mbox{time period index} \\nonumber \\\\\n    L &= \\mbox{periods in a season} \\nonumber \\\\\n    S &= \\mbox{smoothed observation} \\nonumber \\\\\n    y &= \\mbox{the observation} \\nonumber \\\\\n    b &= \\mbox{trend factor} \\nonumber \\\\\n    I &= \\mbox{seasonal index} \\nonumber \\\\\n    \\alpha, \\beta, \\gamma &= \\mbox{constants} \\nonumber\n\\end{align}\n\n\\noindent\nThe StatsModels \\cite{seabold_statsmodels:_2010}\nPython package was used to implement the \\texttt{EXP-SMOOTHING} \nand \\texttt{HOLT-WINTERS} methods in \\deploy. \n\n\\subsection{Stochastic-Optimizing Methods}\nWe implemented one stochastic-optimizing method: step-wise \nseasonal method (\\texttt{SW-SEASONAL}).\nThe method was implemented in \\deploy by the \\gls{ARIMA} \nmethod in the pmdarima \\cite{smith_pmdarima:_2017}\nPython package. \nThe \\gls{ARIMA} model is a dependent time series that is \nmodeled as a linear combination of its own past values \nand past values of an error series \\cite{institute_sas_1985}: \n\n\\begin{align}\n    (1-B)^dY_t &= \\mu + \\frac{\\theta(B)}{\\phi(B)}a_t \\\\ \n    \\intertext{where:}\n    t &= \\mbox{time index} \\nonumber \\\\\n    \\mu &= \\mbox{mean term} \\nonumber \\\\\n    B &= \\mbox{backshift operator, such that } BX_t = X_{t-1} \\nonumber \\\\\n    d &= \\mbox{no. of roots} \\nonumber \\\\\n    Y &= \\mbox{timeseries data} \\nonumber \\\\\n    \\phi(B) &= \\mbox{autoregressive operator} \\nonumber \\\\\n    \\theta(B) &= \\mbox{moving average operator} \\nonumber \\\\\n    a_t &= \\mbox{random error} \\nonumber \n\\end{align}\n\n", "meta": {"hexsha": "611383c76ccfcd2f9ebbc11007e1c3f5db953b32", "size": 25152, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "methods.tex", "max_stars_repo_name": "arfc/2019-ddca-journal-article", "max_stars_repo_head_hexsha": "cd7bee4adcf034968874f2ab3e61cfe4cdddf41a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-29T16:04:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-29T16:04:12.000Z", "max_issues_repo_path": "methods.tex", "max_issues_repo_name": "arfc/2019-ddca-journal-article", "max_issues_repo_head_hexsha": "cd7bee4adcf034968874f2ab3e61cfe4cdddf41a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2019-09-11T16:36:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-14T18:21:48.000Z", "max_forks_repo_path": "methods.tex", "max_forks_repo_name": "arfc/2019-ddca-journal-article", "max_forks_repo_head_hexsha": "cd7bee4adcf034968874f2ab3e61cfe4cdddf41a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-07-06T17:35:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-17T15:01:41.000Z", "avg_line_length": 49.8059405941, "max_line_length": 303, "alphanum_fraction": 0.6709208015, "num_tokens": 6806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819874558604, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3200097732075297}}
{"text": "\\section{CurryVerify: A Tool to Support the Verification of Curry Programs}\n\\label{sec-curry2verify}\n\nCurryVerify\\index{CurryVerify}\\index{verifying programs}\\index{program!verification}\nis a tool that supports the verification of Curry programs\nwith the help of other theorem provers or proof assistants.\nBasically, CurryVerify extends CurryCheck (see Section~\\ref{sec-currycheck}),\nwhich tests given properties of a program,\nby the possibility to verify these properties.\nFor this purpose, CurryVerify translates properties\ninto the input language of other theorem provers or proof assistants.\nThis is done by collecting all operations directly or indirectly\ninvolved in a given property and translating them together with\nthe given property.\n\nCurrently, only Agda \\cite{Norell09} is supported as\na target language for verification (but more target languages\nmay be supported in future releases).\nThe basic schemes to translate Curry programs into Agda programs\nare presented in \\cite{AntoyHanusLibby17EPTCS}.\nThat paper also describes the limitations of this approach.\nSince Curry is a quite rich programming language,\nnot all constructs of Curry are currently supported\nin the translation process (e.g., no case expressions,\nlocal definitions, list comprehensions, do notations, etc).\nOnly a kernel language, where the involved rules\ncorrespond to a term rewriting system, are translated into Agda.\nHowever, these limitations might be relaxed in future releases.\nHence, the current tool should be considered as a first prototypical\napproach to support the verification of Curry programs.\n\n\\subsection{Installation}\n\nThe current implementation of CurryVerify is a package\nmanaged by the Curry Package Manager CPM\n(see also Section~\\ref{sec-cpm}).\nThus, to install the newest version of CurryVerify, use the following commands:\n%\n\\begin{curry}\n> cypm update\n> cypm install verify\n\\end{curry}\n%\nThis downloads the newest package, compiles it, and places\nthe executable \\code{curry-verify} into the directory \\code{\\$HOME/.cpm/bin}.\nHence it is recommended to add this directory to your path\nin order to execute CurryVerify as described below.\n\n\\subsection{Basic Usage}\n\nTo translate the properties of a Curry program stored\nin the file \\code{prog.curry} into Agda,\none can invoke the command\\pindex{curry-verify}\\pindex{verify}\n%\n\\begin{curry}\ncurry-verify prog\n\\end{curry}\n%\nThis generates for each property $p$ in module \\code{prog}\nan Agda program \\ccode{TO-PROVE-$p$.agda}.\nIf one completes the proof obligation in this file,\nthe completed file should be renamed into\n\\ccode{PROOF-$p$.agda}.\nThis has the effect that CurryCheck does not test this property again\nbut trusts the proof and use this knowledge to simplify other tests.\n\nAs a concrete example, consider the following Curry module \\code{Double},\nshown in Figure~\\ref{fig:double-curry},\nwhich uses the Peano representation of natural numbers\n(module \\code{Nat}) to define an operation to double the value\nof a number, a non-deterministic operation \\code{coin}\nwhich returns its argument or its incremented argument,\nand a predicate to test whether a number is even.\nFurthermore, it contains a property specifying that\ndoubling the coin of a number is always even.\n\n\\begin{figure}[t]\n\\begin{curry}\n\nmodule Double(double,coin,even) where\n\nimport Nat\nimport Test.Prop\n\ndouble x = add x x\n\ncoin x = x ? S x\n\neven Z         = True\neven (S Z)     = False\neven (S (S n)) = even n\n\nevendoublecoin x = always (even (double (coin x)))\n\n\\end{curry}\n\\caption{Curry program \\code{Double.curry}\\label{fig:double-curry}}\n\\end{figure}\n\nIn order to prove the correctness of this property,\nwe translate it into an Agda program by executing\n%\n\\begin{curry}\n> curry-verify Double\n$\\ldots$\nAgda module 'TO-PROVE-evendoublecoin.agda' written.\nIf you completed the proof, rename it to 'PROOF-evendoublecoin.agda'.\n\\end{curry}\n%\nThe Curry program is translated with\nthe default scheme (see further options below) based on\nthe ``planned choice'' scheme, described in \\cite{AntoyHanusLibby17EPTCS}.\nThe result of this translation is shown in\nFigure~\\ref{fig:to-prove-evendoublecoin}.\n\n\\begin{figure}[t]\n\\begin{curry}\n-- Agda program using the Iowa Agda library\n\nopen import bool\n\nmodule TO-PROVE-evendoublecoin\n  (Choice : Set)\n  (choose : Choice $\\to$ ${\\mathbb B}$)\n  (lchoice : Choice $\\to$ Choice)\n  (rchoice : Choice $\\to$ Choice)\n  where\n\nopen import eq\nopen import nat\nopen import list\nopen import maybe\n\n---------------------------------------------------------------------------\n-- Translated Curry operations:\n\nadd : ${\\mathbb N}$ $\\to$ ${\\mathbb N}$ $\\to$ ${\\mathbb N}$\nadd zero x = x\nadd (suc y) z = suc (add y z)\n\ncoin : Choice $\\to$ ${\\mathbb N}$ $\\to$ ${\\mathbb N}$\ncoin c1 x = if choose c1 then x else suc x\n\ndouble : ${\\mathbb N}$ $\\to$ ${\\mathbb N}$\ndouble x = add x x\n\neven : ${\\mathbb N}$ $\\to$ ${\\mathbb B}$\neven zero = tt\neven (suc zero) = ff\neven (suc (suc x)) = even x\n\n---------------------------------------------------------------------------\n\nevendoublecoin : (c1 : Choice) $\\to$ (x : ${\\mathbb N}$) $\\to$ (even (double (coin c1 x))) $\\equiv$ tt\nevendoublecoin c1 x = ?\n\n\\end{curry}\n\\caption{Agda program \\code{TO-PROVE-evendoublecoin.agda}\\label{fig:to-prove-evendoublecoin}}\n\\end{figure}\n\nThe Agda program contains all operations involved in the property\nand the property itself.\nNon-deterministic operations, like \\code{coin}, have an additional\nadditional argument of the abstract type \\code{Choice}\nthat represents the plan to execute some non-deterministic branch\nof the program. By proving the property for all possible branches\nas correct, it universally holds.\n\nIn our example, the proof is quite easy. First, we prove\nthat the addition of a number to itself is always even\n(lemma \\code{even-add-x-x}, which uses an auxiliary lemma\n\\code{add-suc}). Then, the property is an immediate consequence\nof this lemma:\n%\n\\begin{curry}\nadd-suc : $\\forall$ (x y : ${\\mathbb N}$) $\\to$ add x (suc y) $\\equiv$ suc (add x y)\nadd-suc zero    y = refl\nadd-suc (suc x) y rewrite add-suc x y = refl\n\neven-add-x-x : $\\forall$ (x : ${\\mathbb N}$) $\\to$ even (add x x) $\\equiv$ tt\neven-add-x-x zero    = refl\neven-add-x-x (suc x) rewrite add-suc x x | even-add-x-x x = refl\n\nevendoublecoin : (c1 : Choice) $\\to$ (x : ${\\mathbb N}$) $\\to$ (even (double (coin c1 x))) $\\equiv$ tt\nevendoublecoin c1 x rewrite even-add-x-x (coin c1 x) = refl\n\\end{curry}\n%\nAs the proof is complete, we rename this Agda program\ninto \\code{PROOF-evendoublecoin.agda} so that the proof\ncan be used by further invocations of CurryCheck.\n\n\n\\subsection{Options}\n\nThe command \\code{curry-verify} can be parameterized\nwith various options.\nThe available options can also be shown by executing\n\\begin{curry}\ncurry-verify --help\n\\end{curry}\nThe options are briefly described in the following.\n\n\\begin{description}\n\\item{\\code{-h}, \\code{-?}, \\code{--help}}\nThese options trigger the output of usage information.\n\n\\item{\\code{-q}, \\code{--quiet}}\nRun quietly and produce no informative output.\nHowever, the exit code will be non-zero if some translation error occurs.\n\n\\item{\\code{-v[$n$]}, \\code{--verbosity[=$n$]}}\nSet the verbosity level to an optional value.\nThe verbosity level \\code{0} is the same as option \\code{-q}.\nThe default verbosity level \\code{1} shows the translation progress.\nThe verbosity level \\code{2} (which is the same as omitting the level)\nshows also the generated (Agda) program.\nThe verbosity level \\code{3} shows also more details about\nthe translation process.\n\n\\item{\\code{-n}, \\code{--nostore}}\nDo not store the translated program in a file but show it only.\n\n\\item{\\code{-p $p$}, \\code{--property=$p$}}\nAs a default, all properties occurring in the source program are\ntranslated. If this option is provided, only property $p$ is translated.\n\n\\item{\\code{-t $t$}, \\code{--target=$t$}}\nDefine the target language of the translation.\nCurrently, only $t = \\code{Agda}$ is supported, which is also the\ndefault.\n\n\\item{\\code{-s $s$}, \\code{--scheme=$s$}}\nDefine the translation scheme used to represent Curry programs\nin the target language.\n\nFor the target \\code{Agda}, the following schemes are supported:\n\\begin{description}\n\\item[\\code{choice}]\nUse the ``planned choice'' scheme, see \\cite{AntoyHanusLibby17EPTCS}\n(this is the default).\nIn this scheme, the choices made in a non-deterministic computation\nare abstracted by passing a parameter for these choices.\n\\item[\\code{nondet}]\nUse the ``set of values'' scheme, see \\cite{AntoyHanusLibby17EPTCS},\nwhere non-deterministic values are represented in a tree structure.\n\\end{description}\n\n\\end{description}\n\n% LocalWords: CurryCheck\n", "meta": {"hexsha": "acb1be5c7a8b0a98f2f809626a72487e6e17a385", "size": 8636, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/src/tooldocs/verify/manual.tex", "max_stars_repo_name": "DouglasRMiles/pakcs_lib", "max_stars_repo_head_hexsha": "c34d76595b23e5152e6a5883ad3b0ec1d840f6d9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-06T18:32:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-21T22:25:28.000Z", "max_issues_repo_path": "docs/src/tooldocs/verify/manual.tex", "max_issues_repo_name": "DouglasRMiles/pakcs_lib", "max_issues_repo_head_hexsha": "c34d76595b23e5152e6a5883ad3b0ec1d840f6d9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-02-21T22:25:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-24T12:41:30.000Z", "max_forks_repo_path": "docs/src/tooldocs/verify/manual.tex", "max_forks_repo_name": "DouglasRMiles/pakcs_lib", "max_forks_repo_head_hexsha": "c34d76595b23e5152e6a5883ad3b0ec1d840f6d9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-09T16:02:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-09T16:02:18.000Z", "avg_line_length": 34.544, "max_line_length": 102, "alphanum_fraction": 0.7373784159, "num_tokens": 2294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.32000976579500295}}
{"text": "%!TEX root = main.tex\n\\chapter{Filters}\n\\label{chap:filters}\n\n\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\includegraphics[width = 14cm]{img/Narciss_Caravaggio.jpg}\n\t\t\\caption{Caravaggio, Narziss. ad Feedback: Echo liebt Narziss etc.}\n\t\t\\label{fig:narziss}\n\t\\end{center}\n\\end{figure}\n\n\\begin{center}\n\\begin{figure}[h!]\n\\tikzset{concept/.append style={fill={none}}}\n\\begin{tikzpicture}\n  \\path[mindmap,concept color=black,text=black]\n    node[concept] {Filters}\n    [clockwise from=0]\n    child[concept color=red!50!black] {\n      node[concept] {Systems}\n      % }\n      [clockwise from=90]\n      child { node[concept] {Impulse Response} }\n      child { node[concept] {Difference Equation} }\n      child { node[concept] {Transfer Function} }\n      % child { node[concept] {pro\\-gramming languages} }\n      % child { node[concept] {software engineer\\-ing} }\n    }\n    child[concept color=blue] {\n      node[concept] (IIR) {IIR}\n      [clockwise from=-30]\n    }\n    child[concept color=red] { node[concept] (FIR){FIR} }\n    child[concept color=orange] { node[concept] (sd) {Sound design Challenge} };\n\n\n\\begin{pgfonlayer}{background}\n    \\draw [circle connection bar]\n      (fm) edge (sd)\n      (fm) edge (pm);\n  \\end{pgfonlayer}\n\n\\end{tikzpicture}\n\\caption{Lecture Contents}\n\\end{figure}\n\\end{center}\n\n\n\n\nWhat is a filter? We use filters a lot. We often need to shape the spectrum of a signal. Be it for technical reasons (DC-Offset removal, Anti-aliasing filters, crossovers, interpolation, ...) or for aesthetic ones (EQ-ing, subtractive synthesis)\\\\\nPlease take a moment and seriously ask yourself, knowing what you know about signals, knowing what we can do with a computer: How do we actually do this? What is a digital Filter? This is what this chapter will try to explain.\\\\\n\n\\section{Seeing Frequency Content in the Time Domain}\n\nLet's first try to get a feel for how signals \\textit{look}. It's a lot easier to understand how a filter works afterwards. This might be obvious but let's state clearly:\n\n\\begin{framed}\n\tHigh frequency signals have a short \\textit{period}. That means the signal ``moves'' fast, or a lot in short time. Therefore: The more movement is in a signal or the more fluctuation or the faster the signal changes the more high frequency content it has.\n\\end{framed}\n\n\nThree Questions in order to make you think about signals:\n\n\n\\begin{question}\n\tPlease look at the image below. Can you draw an approximation of its spectrum? What signals could have been mixed to obtain this result? To help you think about this: How would you explain the graph to somebody who doesn't see it?\n% subsection raetsel (end)\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\includegraphics[width = 14cm]{raetsel_original.png}\n\t\t\\caption{Original Signal}\n\t\t\\label{fig:originalSignal}\n\t\\end{center}\n\\end{figure}\n\\end{question}\n\n\n\\begin{Answer}\nYou should be able to see that there is a sinusoidal component in the signal. This sinusoid has a period of 10 ms, so a frequency of 100 Hz. But also you should see that it is not a clean sine wave, there is some noisy component in there. This is what you should have been able to infer from the image. In fact it is an (attenuated) 100Hz sinusoid mixed with (attenuated) white noise.\n\\end{Answer}\n\n\n\\begin{question}\n\tThe signal in figure \\ref{fig:originalSignal} was filtered. As a result we obtained the signal in figure \\ref{fig:filtered1}. What kind of filter could have been used?\n\t\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\includegraphics[width = 14cm]{raetsel_highpass.png}\n\t\t\\caption{Filtered Signal 1}\n\t\t\\label{fig:filtered1}\n\t\\end{center}\n\t\\end{figure}\n\\end{question}\n\n\\begin{Answer}\n\tIt could have been a notch or stopband filter at 100 Hz or a highpass. In fact, it was a highpass.\n\\end{Answer}\n\n\n\\begin{question}\n\tAgain, the signal in figure \\ref{fig:originalSignal} (so the original signal again) was filtered. As a result we obtained the signal in figure \\ref{fig:raetsel_2} . What kind of filter could have been used?\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\includegraphics[width = 14cm]{raetsel_lowpass.png}\n\t\t\\caption{Filtered Signal 2}\n\t\t\\label{fig:raetsel_2}\n\t\\end{center}\n\\end{figure}\n\n\\end{question}\n\n\n\\begin{Answer}\n\tIt could have been a bandpass at 100Hz, or a lowpass. In fact, it was a lowpass. We see that the signal got a lot smoother.\n\\end{Answer}\n\n\\section{Ways of Describing a Filter}\nThere are a couple of ways to \\textit{fully} describe a linear time invariant system (LTI), filters typically\\footnote{filters can be augmented with non-linear or time-varying elements, for example distortion or modulation. In sound design, this is actually very common. But describing such a system mathematically is out of the scope of this work.} are such systems.\\\\\nBelow is an (incomplete) list of methods that are all able to describe a filter. They offer very different possibilities of understanding and manipulating a filter.\n\\begin{itemize}\n\t\\item Difference Equation\n\t\\item Magnitude and Phase Response\n\t\\item Impulse Response\n\t\\item Code (graphical, such as Max/MSP, pure data, simulink)\n\t\\item Code (text, such as C++)\n\t\\item Block Diagram\n\t\\item Transfer Function (Rational Function)\n\t\\item Unit Step Response\n\\end{itemize}\n\n\n\\begin{figure}[htb]\n  \\centering\n  \\label{fig:conversions}\n\n  \\begin{tikzpicture}[auto, thick, node distance=2.3cm, >=triangle 45]\n\n  % \\draw node at (0,0) [input] (excitation) {};\n  \\draw node at (0,0) [block] (de) {difference Equation};\n  \\draw node [block, right of=de, node distance = 8cm] (tf) {transfer function};\n  \\draw node [block, below of= de] (ir) {impulse Response};\n  \\draw node [block, below of= ir] (sr) {step Response};\n  \\draw node [block, below of= tf] (fr) {frequency Response};\n  \\draw node [block, above of= de] (bd) {block diagram};\n\n\n\n  % \\draw node [block, below of=delay, node distance = 2cm] (loss) {\\Large$G(z)$};\n  % \\draw node at (6.,-0.001) {\\textbullet};\n\n  % \\draw node [output, right of=delay,node distance = 3cm] (out) {};\n  \\draw[<->] (de) -- node {by inspection}(bd);\n  \\draw[->] (de) -- node {\\Large$z transform$}(tf);\n  \\draw[->] (tf) -- node {evaluate on unit circle}(fr);\n  \\draw[->] (de) -- node {set $x[n]=\\delta[n]$}(ir);\n  % \\draw[->] (sum1) -- node {}(delay);\n  % \\draw[->] (loss.west) -| node {}(sum1.south);\n\n  % \\draw[->] (6., -0.001) |- node {}(loss.east);\n\n\n  \\draw[->] (ir) -- node {\\Large$\\int x dt$}(sr);\n  \\draw[->] (ir) -- node {\\Large$\\mathcal{F} $}(fr);\n  % \\draw[<-] (ir) -- node {\\Large$\\mathcal{F^{-1}} $}(fr);\n\n  \\end{tikzpicture}\n  \\caption{Ways of describing LTI systems and how to get from one to the other}\n\\end{figure}\n\n\n\n\nWhile in practice, the transfer function is very important, we will mostly work with block diagrams, pd programs and difference equations.\\\\\nIt is an important skill to be able to switch between these representations, for example to calculate the impulse response from a difference equation or block diagram.\n\n\\subsection{Difference Equations}\n\\label{sub:diff}\n\nA difference equation is of the form mentioned in the introduction. So for example\n\\begin{equation}\n\ty(n) = x(n)+x(n-1)\n\t\\label{eq:simple}\n\\end{equation}\nHere, $y$ is the output $x$ is the input and $n$ denotes indexing those two signals.\\\\\n$y(n)=x(n)$ means: take the incoming sample and make it the output. $x(n-1)$ denotes a delay by one sample. Please note that the above equation describes a \\textit{system}, a filter in this case. But it can be seen as using an input array (the input signal), indexed by $n$ and creating an output array.\\\\\nLet's visualize this idea. Given the input signal in figure \\ref{fig:diffImpResp}, we can create the output using the equation.\n\n\\begin{figure}[h]\n\t\\centering\n\t\\includegraphics[width=\\textwidth]{diffEqViz1}\n\t\\caption[shortCaption]\n\t{The input and corresponding output of the equation given above.}\n\t\\label{fig:diffImpResp}\n\\end{figure}\n Also it becomes obvious that the $n-1$ expression is a delay, since it makes us look up the 3rd index for creating the 4th sample at the output in this case, or $y(4) = x(4)+x(4-1)$.\\footnote{The impulse in this example input signal is at position $n=3$ so the third sample. This was chosen at random and has no meaning. It could just as well sit at $n=5$.}\\\\\n So for more clarity, let's see all the values at all $n$s (compare this with figure \\ref{fig:diffImpResp}):\n\n\\begin{center}\n\n\\begin{tabular}{l|l|l|l}\n\t$n$ & $y(n)$ & $x(n)$ &$x(n-1)$\\\\\n\t\\hline\n\t0 & 0 & 0 &0\\\\\n\t1 & 0 & 0 &0\\\\\n\t2 & 0 & 0 &0\\\\\n\t3 & 1 & 1 &0\\\\\n\t4 & 1 & 0 &1\\\\\n\t5 & 0 & 0 &0\\\\\n\\end{tabular}\n\\end{center}\n\n\n\n\\subsection{Block Diagrams} % (fold)\n\\label{sub:block}\n\nBlock diagrams are nice because they are very visual and sometimes easier to understand. Also, if we work in pure data, or a different graphical programming language (such as Max/MSP or MATLAB Simulink) it's very straight forward to implement a block diagram. Translating from a block diagram to text code or difference equations or vice versa can be hard sometimes.\\\\\nIn figure \\ref{fig:diffImpResp}, we can see a block diagram representation of equation \\ref{eq:simple}. This \\textit{is} the same thing.\n\n% subsection subsection_name (end)\n\n\\begin{figure}[H]\n  \\centering\n  \\label{fig:simpleLPdiag}\n  \\begin{tikzpicture}[auto, thick, node distance=2.5cm, >=triangle 45]\n  \\draw node at (0,0) [input] (inp) {};\n  \\draw node at (2.5,-0.001) (junct) {\\textbullet};\n  \\draw node at (4,2) [block] (delay) {\\Large$z^{-1}$};\n  \\draw node [sum, right of=inp, node distance = 5.cm] (sum1) {\\Large$+$};\n\n  \\draw node [output, right of=sum1,node distance = 3cm] (out) {};\n  \\draw[->] (inp) -- node {}(sum1);\n  % \\draw[->] (junct) |- node {}(delay);\n  \\draw[->] (delay.east) -| node {}(sum1.north);\n\n  \\draw[->] (2.5, -0.001) |- node {}(delay.west);\n\n\n  \\draw[->] (sum1) -- node {\\Large$y[n]$}(out);\n\n  \\node[text width=3cm] at (1.7,0.4)\n    {\\Large$x[n]$};\n\n  \\end{tikzpicture}\n  \\caption{A very simple lowpass filter.}\n  \\label{fig:blockDiagr}\n\\end{figure}\n\nDon't be irritated by the $z^{-1}$ block. This notation stands for a delay by one sample. A block $z^{-m}$ would stand for a delay by $m$ samples. This is a convention we need to remember. This way of notating a delay might seem unnecessarily complex, but it has its reasons.\n\n\\bgInfo{This notation, $z^{-1}$, comes from the fact that analyzing the frequency response of a system is very easy when working with complex numbers (so compounds of real and imaginary numbers). Complex numbers are often denoted by $Z$, which is another convention. Not only do we work with complex numbers, but with complex sinusoids when analyzing such systems. We imagine complex sinusoids coming into our system. A multiplication by another complex sinusoid can cause a phase shift (a delay). Dividing ($z^{-1} = \\frac{1}{z}$) an incoming complex sinusoid by the complex sinusoid at the same frequency causes a phase shift that is equals to a delay by 1 sample. If you want to understand all this and stop with mickey-mouse-explanations I can recommend reading \\cite{miller_puckette_theory_2006} and \\cite{smith_introduction_2007}. Both of these works can be found on-line for free.\\\n\nBut let's quickly calculate the frequency response, so you've seen it once:\nWe take our difference equation (we could also start from the block diagram):\n\\begin{equation}\n\ty(n) = x(n)+x(n-1)\n\\end{equation}\nWe then do a process called the z-transform, that is, we get rid of all the indexing. We now think about applying the process of filtering to the whole signal at once and we denote the delay by a multipliaction with a complex sinusoid that causes a phase shift:\n\\begin{equation}\n\tY = X + X \\cdot Z^{-1}\n\\end{equation}\n\nWe then solve the equation for $Y/X$:\n\n\\begin{equation}\n\tY = X \\cdot (1 + Z^{-1})\n\\end{equation}\n\\begin{equation}\n\t\\frac{Y}{X} = 1+Z^{-1}\n\\end{equation}\n\nTypically we substitute $\\frac{Y}{X}$ with a new name, typically $H$ and now make this a function of $Z$.\n\n\\begin{equation}\n\tH(Z) = 1 + Z^{-1}\n\\end{equation}\nThis is called a system's transfer function. This is the actual standard for talking about systems. Typically we do two things with this, either, we draw a so called \\textit{Pole-Zero-Plot}.\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=\\textwidth]{poleZero.png}\n\t\\caption[pole zero plot]\n\t{a pole zero plot. This indicates where the function $H(z)$ has zeros(where its value is zero) or poles(where its value is infinity). Actually there is also a pole at $0+0i$ which is not shown here. This is because a pole at this position has no frequency dependent effect.}\n\t\\label{fig:poleZero}\n\\end{figure}\n\nWe can also evaluate the function $H(z)$for complex sinusoids.\\\\\nThe absolute value of $H$ is the output amplitude, if we just plot this value for all complex numbers we see this:\n\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=\\textwidth]{poleZero3dPlot.png}\n\t\\caption[poles and zeros, 3D in the complex plane]\n\t{Evaluation of the Transfer function in the complex plane. The unit circle is visible as a dotted line. This plot is not too easy to read but if you look at the coordinate $-1+0i$, you can see that the value there is very low. This seems to indicate a lowpass. You can basically ignore the huge mountain in the middle. It sits at $0+0i$ and has therefore equal effect on all frequencies.}\n\t\\label{fig:poleZero3d}\n\\end{figure}\n\nIt's OK if this plot doesn't tell you much. The really important thing is to evaluate this surface using complex sinusoids:\n$cos(\\omega) + i\\cdot sin(\\omega)$. This is the same as looking at the values along the dotted line. We can now plot the magnitude response over $\\omega$. So we effectively evaluate the formula\n\\begin{equation}\n\t|H(\\omega)| = |1 + (cos(\\omega)+i \\cdot sin(\\omega))^{-1}|\n\\end{equation}\nWhere $\\omega$ ranges from $0$ to $\\pi$(sic!). This is the same as going along the dotted line, starting at $1+0i$ (lowest frequency) and ending at $-1+0i$ (the highest frequency). Then we finally get the magnitude response:\n\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=\\textwidth]{magResp.png}\n\t\\caption[Filter magnitude response]\n\t{Magnitude response, so $|H(\\omega)| = |1 + (cos(\\omega)+i \\cdot sin(\\omega))^{-1}|$}\n\t\\label{fig:magResp}\n\\end{figure}\n\n\n\n}\n\n\\subsection{pd Code} % (fold)\n\\label{sub:pd_code}\nIf we program the filter in pd (or any other programming language) we obviously also fully defined the filter. Try to build the filter from above in pd! Start from the difference equation or the block diagram, what ever is harder to understand for you.\\\\\nIn figure \\ref{fig:pdSimpleFir} you can see the translation to pd.\n\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics{simpleFir}\n\t\\caption[FIR filter in pd]\n\t{A simple filter in pure data.}\n\t\\label{fig:pdSimpleFir}\n\\end{figure}\n\n\n\n% subsection pd_code (end)\n\n\\subsection{Impulse Response}\n\nAn impulse has the advantage that it contains all frequencies. It has a flat spectrum.  So recording how a filter reacts to the impulse gives us the magnitude of the spectrum at all frequencies.\\\\\nWe can see the impulse response of the filter we are describing in this section in  multiple ways in figure \\ref{fig:diffImpResp}.\n\n\\bgInfo{\n\\subsection{Text Oriented Code} % (fold)\n\\label{sub:tcode}\nBelow, we can see a code implementation in the language MATLAB.\n\n\\lstinputlisting[label=code,\ncaptionpos=b,\ncaption=A script that creates an impulse implements a vectorized filter and plots the result.]{code/FIRvectorized.m}\n}\n\n\\section{Ways of Getting an Intuitive Understanding}\n\nSo now we learned some ways to define a filter, to talk about a filter. But what is this filter actually doing? It is a very simple lowpass filter. It cuts away high frequencies. But why is adding a signal to itself but one sample delayed making a lowpass? This certainly is a bit surprising, so let's try to understand what's happening.\n\n\\subsection{Combfilter to Lowpass}\nFirst let's view the problem from another angle. We know what this structure from above is: It's a combfilter, right? It's taking a signal and adding a delayed version of it. Let's quickly review what a combfilter is:\nThe combfilter effect can come up if we record something with a microphone and we get the direct signal and a delayed (e.g. via a reflection) signal also. These two signals mix together and this is what we get in our recording.\\\\\nThe result is that some frequencies cancel out.\\\\\nWe can simply simulate this situation in Max using a delay and an addition.\n\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics{simpleComb}\n\t\\caption[simple comb filter]\n\t{A very simple comb filter}\n\t\\label{fig:simpleComb}\n\\end{figure}\n\nThis canceling out of frequencies \\footnote{also called destructive interference} can be imagined if we look at figure \\ref{fig:destIntereference}.\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=\\textwidth]{destInterference}\n\t\\caption[Destructive Interference]\n\t{Destructive Interference. The two waves would cancel out completely if mixed together(=added).}\n\t\\label{fig:destIntereference}\n\\end{figure}\n\nPlease note that the signal is a sine wave with a frequency of 100 Hz, so a period of 10 milliseconds. The delay is set to be 5 ms, so half of the period of the input signal in this case. It it was set to be equals the period, the two waves would \\textit{interfere constructively}, so we would get out a higher amplitude. \\\\\n\n\\important{In a combfilter, the first frequency that cancels out is the one whose period is double the delay time. Or, to put it differently\n\\begin{equation}\n\tf_c = \\frac{1}{2d}\n\\end{equation}\nIf $f_c$ is the first frequency that cancels out and d is the delay time in seconds. \\\\\nHow to calculate this fast, if you are given the delay time:\njust calculate the frequency for the given delay, and then use half of that. For example, if given delay 1ms, the corresponding frequency would be 1000 Hz. Half of that (=double the period) is 500 Hz, and that's where the first trough in the spectrum would be.\n\n}\n\nIn figure \\ref{fig:combToLowpass} we can see the \\textit{frequency response}\\footnote{The impulse response is recorded a couple of times and the output's spectrum has been analyzed} of our combfilter. We see a couple of plots, it's always the same filter but the delay is different. We see that for delay times >1 sample, we observe our typical comb pattern. But at Delay = 1 sample, there is just a ramp left, leaving us with a lowpass.\n\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=\\textwidth]{FromCombfilterToLowpass}\n\t\\caption[From comb filter to lowpass]\n\t{Different amounts of delays result in different magnitude responses. The extreme case of a comb filter, a delay of 1 sample, is looking like a lowpass.}\n\t\\label{fig:combToLowpass}\n\\end{figure}\n\n\\bgInfo{\n\tWe can also calculate what's happening with our equation from above:\n\tThe delay is $1/f_s$, so 1 over samplerate. This is called the sampling intervall, let's call it $I_s$, just to get rid of the fraction. The frequency that cancels out is then $1/2I$. By inspection we find that this means the frequency that has double the wavelength of the sampling frequency, so half the sampling frequency, so \\textit{Nyquist}.\n}\n\n\n\\subsection{Prolonging an Impulse}\nWe can also take a different route to understand why this is a lowpass. Let's recall what the spectrum of an impulse looks like and what the spectrum of DC offset looks like. Taking a look at figure \\ref{fig:impToDc}, we see an impulse, the impulse response of our filter and a DC-Offset signal. Recalling from the introduction, and looking at the figure, we know that the DC-offset signal contains only energy at 0Hz. Now look at the time domain signals: Isn't making our impulse signal last for one sample longer a small step towards generating a DC-offset signal?\n\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=\\textwidth]{impulseToDC}\n\t\\caption[Spectrum Impulse, Lowpass, DC]\n\t{Impulse, impulse response and DC offset signal and their spectra. Note that there are very few samples here and the DC-Offset signal's spectrum seems to ramp down from 0Hz. In fact, there is a single high value at 0Hz.}\n\t\\label{fig:impToDc}\n\\end{figure}\n\n\\subsection{A moving Average}\nHow is \\textit{average} defined? There are a lot of different ways to compute an average, but typically we mean the \\textit{arithmetic mean}, so adding all numbers and dividing by the count of items:\n\\begin{equation}\n\tA = \\frac{1}{N} \\sum_{n=1}^N x(n)\n\\end{equation}\n\nLooking back at our filter, we will notice that we are adding up the current sample and the last sample. If we were to divide that sum by two (so the number of elements, since it's two samples we are adding up), we would arrive at the definition above. So we could say, that our lowpass is always outputting the average of the current and the last sample. It is therefore called a moving average filter. \\\\\nTaking the average of something always reduces information and we get something that is fluctuating less than its input. If we would make a website or something that would always show the average temperature in Vienna of the last two weeks, this display wouldn't start jumping around if there was a single hot day in winter. It would remove high frequency data (jumps). It would be some kind of lowpass filter.\n\n\n\\subsection{A sine at Nyquist}\nHere is yet another way of understanding why the structure we saw is a lowpass. Let's imagine a sine wave at Nyquist frequency, the highest frequency we can work with. We can see what such a sine looks like in Figure~\\ref{fig:nyqSine}. If we apply this moving average filter, so that lowpass we have been talking about, what do you think comes out? Go ahead and calculate the average for each sample and its previous sample. We add $1 + -1 = 0$, $-1 + 1 = 0$, $1 + -1 = 0$, ... So you can see, if we feed a sine at nyquist into our lowpass, what we get is silence.\n\n\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=\\textwidth]{sineWaveNyq.png}\n\t\\caption[Sine wave at nyquist frequency]\n\t{Sine wave at nyquist frequency}\n\t\\label{fig:nyqSine}\n\\end{figure}\n\n\n\\subsection{Highpass} % (fold)\n\\label{sub:Highpass}\n\nYou should already be familiar with the basic types of filters, so lowpass, highpass, bandpass etc. We now saw how we can build a lowpass filter, but what about a highpass, what about notching, peak, shelving filters? This is getting pretty involved quickly, but let's have a look at a highpass. Highpass filtering is the opposite of lowpass filtering. It emphasizes movement in the signal, since everything that moves fast must contain high frequencies. One simple form of a highpass is taking the difference between the current and the last sample, so:\n\n\n\\begin{figure}[H]\n  \\centering\n  \\label{fig:sipleHP}\n  \\begin{tikzpicture}[auto, thick, node distance=2.5cm, >=triangle 45]\n  \\draw node at (0,0) [input] (inp) {};\n  \\draw node at (2.5,-0.001) (junct) {\\textbullet};\n  \\draw node at (4,2) [block] (delay) {\\Large$z^{-1}$};\n  \\draw node [sum, right of=inp, node distance = 5.cm] (sum1) {\\Large$+$};\n\n  \\draw node [output, right of=sum1,node distance = 3cm] (out) {};\n  \\draw[->] (inp) -- node {}(sum1);\n  % \\draw[->] (junct) |- node {}(delay);\n  \\draw[->] (delay.east) -| node {}(sum1.north);\n\n  \\draw[->] (2.5, -0.001) |- node {}(delay.west);\n\n\n  \\draw[->] (sum1) -- node {\\Large$y[n]$}(out);\n\n  \\node[text width=3cm] at (1.7,0.4)\n    {\\Large$x[n]$};\n\n\\node[text width=3cm] at (6.7,0.9)\n    {\\Large$-$};\n\n\n  \\end{tikzpicture}\n  \\caption{A very simple highpass filter. Please compare to \\ref{fig:blockDiagr}. }\n  \\label{fig:blockDiagrHigh}\n\\end{figure}\n\nYou will notice that figure \\ref{fig:blockDiagrHigh} and figure \\ref{fig:blockDiagr} are identical with oly one little exception. In this highpass filter we \\textbf{subtract} the delayed signal from the input. This is denoted by the little $-$ sign next to one line leading to the addition. One might think, ``Why don't we just use a minus sign instead of the addition sign?'' Because order matters with subtraction, it makes a difference if we subtract 3 from 5 or 5 from 3.\\\\\nThe structure above is also called a differentiator, since it is a way of approximating the derivative of a signal.\n\n\n\n\n% subsection filter_types (end)\n\n\\subsection{Video Filters}\n\n\\video{\n\tFilters in video work the same way and are as common as in audio. But in video we have another question to answer before we start filtering: Does our operation (adding two neighboring samples) apply to time, or to space? In other words: Do we want to add neighboring pixels to produce an output pixel or do we want to add whole frames over time to produce an output frame?\\\\\n\tHave a look at figure \\ref{fig:v_origianl}. We will take this still from a video as a reference. We send the video through a couple of filters (one at a time, not in series) and watch the output. \\\\\n\tFor each of the output frames, try to think about how this could have been generated from the input, what kind of a filter could have been used!?\n\n\t\\begin{figure}[H]\n\t\t\\begin{center}\n\t\t\t\\includegraphics[width = 14cm]{vidFilters_o.png}\n\t\t\t\\caption[Video Filters: Original]{Frame from the original video}\n\t\t\t\\label{fig:v_origianl}\n\t\t\\end{center}\n\t\\end{figure}\n\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\includegraphics[width = 14cm]{vidFiltersFIRs.png}\n\t\t\\caption[Video Filters: Blur]{This effect is known as a \\textit{blur} It is generalted by using a FIR lowpass in the space domain. That means, in the simplest case, each output pixel is the average of the input pixel at the same location and its neighbors. In practice, weighting functions are used to control, how much the input pixel and how much its neighbors contribute. These weighting functions are called kernels, (since this FIR filtering is the same as convolution). Typical kernels are: Gaussian, Box, the sinc function, etc. }\n\t\t\\label{fig:v_blur}\n\t\\end{center}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\includegraphics[width = 14cm]{vidFilters_IIRt.png}\n\t\t\\caption[Video Filters: IIR Lowpass, time domain]\n\t\t{Here we can see a kind of lowpass (IIR) in the time domain. The current input-frame and a mixture of past (output-)frames are added up to generate this output frame.}\n\t\t\\label{fig:v_TLP}\n\t\\end{center}\n\\end{figure}\n\n\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\includegraphics[width = 14cm]{vidFiltersHPFIRs.png}\n\t\t\\caption[Video Filters: FIR Highpass, space domain]\n\t\t{We can hardly see anything here, but if you look closely, edges from the original are still visible. What happened here is a FIR filtering in the space domain, so the opposite of blurring: Edge detection.}\n\t\t\\label{fig:vidFiltHP}\n\t\\end{center}\n\\end{figure}\n\n\n\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\includegraphics[width = 14cm]{vidFiltersHPFIRt.png}\n\t\t\\caption[Video Filters: FIR Highpass, time domain]\n\t\t{What we can see here is another highpass, but in the time domain. It computes the difference between the current and the last frame.}\n\t\t\\label{fig:vidFilHPt}\n\t\\end{center}\n\\end{figure}\n\n\n\n\n\n}\n\n\\section{Filters in Max/MSP}\nPlease note that what we did so far was filtering signals, but we \\textbf{built} the filters with very low level operations (Addition, multiplication and time shift = delay). This was in order to understand how filters work. Sometimes we need to build a filter, but often we can just \\textit{use} filters, which are built in to Max or any other environment.\\\\\n\\subsection{Lowpass}\nIn pd, we can use \\pd{lop\\textasciitilde}, \\pd{onepole\\textasciitilde}, \\pd{lores\\textasciitilde} and \\pd{vcf\\textasciitilde}. \\pd{lores\\textasciitilde } has a resonance parameter. This emphasizes frequencies at the cutoff frequency of the filter. \\pd{vcf\\textasciitilde} also has this parameter and an additional bandpass output.\n\n\\subsection{Highpass}\nThere is \\pd{hip\\textasciitilde}, which is a highpass filter. But we can just use a structure that subtracts a lowpassed version from our original signal also. For example:\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\includegraphics{pdhighpass.png}\n\t\t\\caption{Highpass filter}\n\t\t\\label{fig:pdHP}\n\t\\end{center}\n\\end{figure}\n\n\\subsection{Bandpass} % (fold)\nThere are two bandpass filters in Max, \\pd{reson\\textasciitilde} and \\pd{svf\\textasciitilde}. Additionally \\pd{biquad\\textasciitilde} can be used in bandpass mode.\nWe can also make our own custom bandpass using a lowpass and a highpass in series:\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics{bandpass}\n\t\\caption[bandpass]\n\t{Bandpass Filter in pd}\n\t\\label{fig:filterInPd}\n\\end{figure}\n\n% subsection subsection_name (end)\n\n\n\nMore basic building blocks that can be used to realize a filter are \\pd{rpole\\textasciitilde }, \\pd{rzero\\textasciitilde }, \\pd{cpole\\textasciitilde }. \\pd{czero\\textasciitilde }. \\pd{biquad\\textasciitilde } is a very powerful filter that allows more or less arbitrary responses.\\\\\n\n\\section{Types of Digital Filters}\n\nIt is important to understand that there are two types of filters\\footnote{We are going to ignore that one can also filter by using FFT approaches}.\n\\begin{itemize}\n\t\\item Finite Impulse Response (FIR) Filters\n\t\\item Infinite Impulse Response (IIR) Filters\n\\end{itemize}\n\nWe have been dealing with a FIR filter so far. An infinite impulse response filter does not have an infinite impulse response in practice, but it \\textit{can} have one. How is this achieved? By using feedback. A FIR filter does not have feedback, an IIR filter does.\n\n\n\\begin{figure}[htb]\n  \\centering\n  \\label{fig:IIRlowpass}\n\n  \\begin{tikzpicture}[auto, thick, node distance=2.3cm, >=triangle 45]\n\n  \\draw node at (0,0) [input] (excitation) {};\n  \\draw node [sum, right of=excitation, node distance = 2.cm] (sum1) {\\Large$+$};\n  \\draw node at (5,-2) [block ] (delay) {\\Large$z^{-1}$};\n  \\draw node [mult,shape border rotate=180, left of=delay, node distance = 2cm] (loss) {$0.5$};\n  \\draw node at (6.,-0.001) {\\textbullet};\n\n  \\draw node [output, right of=sum1,node distance = 5cm] (out) {};\n  \\draw[->] (excitation) -- node {\\Large$x[n]$}(sum1);\n  % \\draw[->] (sum1) -- node {}(6., -0.001);\n  \\draw[->] (loss.west) -| node {}(sum1.south);\n\n  \\draw[->] (6., -0.001) |- node {}(delay.east);\n  \\draw[->] (delay) -- node {}(loss);\n\n\n  \\draw[->] (sum1) -- node {\\Large$y[n]$}(out);\n\n  \\end{tikzpicture}\n  \\caption{A simple IIR filter. Note that the arrows are circling, there is feedback involved.}\n\\end{figure}\n\n\nIf we look at the impulse Response, we can see that it is  ``longer'' than what we had before. If you look closely, we can see that the output sample at which the impulse arrives(n=3), just has the value of the input(1). After that, we can see that the next value is always the sample before times 0.5, so the impulse respopnse is a \\textit{geometric series}: $\\{1,0.5,0.25,0.125,..\\}$ or $\\{1, \\frac{1}{2}, \\frac{1}{4}, \\frac{1}{8}, ...\\}$. This is the case since the coefficient in the feedback path is 0.5, so $\\frac{1}{2}$.\n\n\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=\\textwidth]{IIR1}\n\t\\caption[Impulse Response of $y(n)=x(n)+\\frac{1}{2}y(n-1)$]\n\t{Impulse Response of $y(n)=x(n)+\\frac{1}{2}y(n-1)$}\n\t\\label{fig:iir2}\n\\end{figure}\n\nLet's translate the above diagram to a difference equation, so we see another representation of the same system.\n\\begin{equation}\n \ty(n) = x(n)+y(n-1) \\cdot 0.5\n \\end{equation}\n\nFinally, let's quickly summarize some of the differences between the two filter types:\n\\begin{center}\n\n\\begin{tabular}{l|l|l}\n\n& \\textbf{IIR} & \\textbf{FIR} \\\\\n\\hline\nstability & possibly unstable & always stable \\\\\nReal time Efficiency & Very efficient & inefficient \\\\\ntopology & Feedback & no feedback \\\\\n\n\\end{tabular}\n\\end{center}\n\n\\subsection{IIR Filters in Max}\nThere are several ways to use IIR filters in Max (\\pd{biquad\\textasciitilde}, \\pd{onepole\\textasciitilde}, \\pd{cascade\\textasciitilde}, ... ). If we want to \\textit{create} an IIR filter from scratch, we should use \\pd{gen\\textasciitilde}. After creating a \\pd{gen\\textasciitilde} object, we can double click it to edit it. In there we are allowed to do signal processing on a sample-by-sample level. This is necessary in order to use feedback with a single sample delay. A simple IIR lowpass filter would look like depicted in Figure \\ref{fig:iirGen}.\n\n\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics{img/genIIR.PNG}\n\t\\caption[IIR lowpass filter made in gen.]\n\t{IIR lowpass filter made in gen. $y(n)=x(n)+0.99 \\cdot y(n-1)$}\n\t\\label{fig:iirGen}\n\\end{figure}\n\n% \\section{Convolution}\n% Convolution is a very important concept in DSP. We already encountered it in chapter \\ref{Modulation}. We know that convolution reverbs use impulse responses of rooms to simulate these rooms. But how is this done? It \\textit{can} be done using a FIR filter.\n\n\n\n\n\\section{Key Points}\n\\begin{itemize}\n\t\\item Make sure you understood the differences between a FIR and an IIR filter.\n\t\\item Make sure you can make an educated guess what kind of a filter we see if you encounter a block diagram.\n\t\\item Make sure you can do simple translations between Max, blockdiagrams and difference equations.\n\t\\item Make sure you know when a combfilter turns into a lowpass.\n\t\\item Make sure you know and understand the formula to calculate the first phase cancellation in a combfilter.\n\\end{itemize}\n\n\\section{Homework}\n\nBuild the structure depicted in Figure~\\ref{fig:genFx} in Max/MSP.\n\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=\\textwidth]{img/effect.png}\n\t\\caption[Generalized Effects Structure proposed by Dattoro]\n\t{Effects Structure proposed by Dattoro}\n\t\\label{fig:genFx}\n\\end{figure}\n\n\n% Notizen aus erster UE:\\\\\n% Viellt. mit IR anfangen?\n% Vielleicht davor noch: das beispiel mit noise + sinus.\n\n% IR, bypass system, hall system.\n\n% garnicht faltung. Moving average zu long FIR.\n% Impuls antworten anhand beispielen besprechen.\n\n\n% \\begin{enumerate}\n% \t\\item FIR!\n\n% kammfilter(FF)\n\n% dann FIR kammfilter\n\n% chorus\n% flanger\n\n% LFO\n\n% ->index/tiefe, offset, frequenz wdh.\n\n\n% -frequenzgang\n% ausl\\\"oschungen, rechnen..\n\n% \\item\n% FIR one sample delay\\\\\n\n% FIR bauen, vllt. an tafel blockdiagramm.\\\\\n\n% FIR hipass\\\\\n\n\n% \\item\n\n% mehrere Samples delay\n% IR\n% differenzen gleichung\n\n% eventuell Faltung(faltungs hall connection herstellen)\n\n% faltung als multiplikation d. spektra\n% multiplikation als faltung d spektra.\n\n% M4L faltungs hall herzeigen\n\n% LTI?\n\n% differentiator, akkumulator?\n\n% \\item\n% IIR\\\\\n\n\n\n% notizen POlyphonie\n% was separat, was einmal\n\n% \\end{enumerate}\n\n% \\section{einfuehrung} % (fold)\n% \\label{sub:einfuehrung}\n\n\n% Ziel der LV:\\\\\n% \\begin{enumerate}\n% \t\\item Gefühl dafür bekommen was die häufigsten Operationen der DSV eigentlich tun.\n% \t\\item Gefühl dafür bekommen, dass es günstig ist, zwischen verschiedenen repräsentationen hin und her zu wechseln (time und frequency domain, aber auch system repräsentationen)\n% \t\\item Sich in professioneller literatur(DSP lehrbücher) nicht völlig verloren fühlen.\n% \t\\item schönheit zu sehen dass alles das \\glqq{}gleiche\\grqq{} ist.(Delay, filter, reverb, chorus, flanger etc)\n% \\end{enumerate}\n\n% Wozu?:\\\\\n% \\begin{enumerate}\n% \t\\item Wir arbeiten ständig mit Operationen der DSV. Filter sind nicht nur in synthesizern. Ein tieferes verständnis erleichtert die arbeit. Wie funktioniert zum beispiel ein blur?\n% \t\\item Was ist ein FeedForward compressor?\n% \\end{enumerate}\n\n\n% Nachdenken über filter allgemein. Was ist ein filter im gespür d. studenten. \\\\\n% Bekannt was ein LTI system ist?\\\\\n\n\n% \\newpage\n% -Wie könnte ein filter realisiert werden?\\\\\n% -Ein digitales signal ist eine reihe von zahlen, eine sequenz von werten. (über bildliche darstellungen sprechen)\\\\\n% -Echtzeit fall: ich bekomme in ein system ein signal(also ständig werte) und soll ein zb. lowpass gefilteretes signal ausgeben.\\\\\n% \\textbf{Was kann ich mit dem signal machen? Zum beispiel addieren, multiplizieren, verzögern.}\\\\\n\n\n% Einfacher moving average. Zunächst nur an der tafel!\n% Impulsantowrt ausrechnen!\n% Was ist ein impuls.\\\\\n% Was ist eine impulsantwort? Beispiele.. untit impulse ( = dirac impuls, dirac gunktion, delta function)\\\\\n\n% Diagramm aufmalen:\n\n% impuls \\(\\rightarrow\\) Raum \\(\\rightarrow\\) Impulsantwort\\\\\n% oderr \\\\\n% impuls \\(\\rightarrow\\) beliebiges system \\(\\rightarrow\\) Impulsantwort\\\\\n% \\textbf{anwendugsbeispiel:} tontechnik bei okto; mischpult ausmessen, dbmax ausmessen(fragwürdige sache! Wieso?)\n\n\n\n\n% \\textbf{FRAGE}\\\\\n% Ein system(zB. ein Filter) hat folgende Eigenschft:\\\\\n% Wenn zwei signale getrennt (d.h. unabhängig voneinander, zB. nacheinander.) in das system geschickt werden, und die Ergebnisse summiert werden, entsteht das signal \\(P\\). Wenn andererseits die signale zuvor summiert werden und dann in das system geschickt werden entsteht ebenfalls \\(P\\). Welche gleichung etspricht einer beschreibung dieser eigenschaft?\n\n\n\n% \\begin{enumerate}\n% \t\\item \\(f(x)+f(y) = f (x * y) = P\\)\n% \t\\item \\(f(x)+f(y) = f (x + y) = P\\)\n% \t\\item \\(f(x)+f(x) = f (x + y) = P\\)\n% \t\\item \\(f(x)+f(y) = f (x + x) = P\\)\n% \t\\item nichts von alledem.\n% \\end{enumerate}\n\n% \\newpage\n% richtig : nr.2 \\\\\n% \\\\\n\n% Erklärung eines LTI systems:\n\n% \\begin{itemize}\n% \t\\item Linear:\n% \t\t\\begin{itemize}\n% \t\t\t\\item Superpositionsprinzip \\(f(x)+f(y) = f (x + y)\\)\n% \t\t\t\\item Homogenität \\(a*f(x) = f(a*x)\\)\n% \t\t\\end{itemize}\n% \t\\item Time Invariant (zeit-invariant)\n% \\end{itemize}\n\n\n% Zurück zu filter:\n% was glauben sie wie er funktioniert. \\\\\n% \\\\\n\n% \\section {kammfilter}\n\n% Wiederum fragen was sich die studenten vorstellen.\\\\\n\n\n% \\glqq{}Wir bauen ein delay.\\grqq{}\n% nicht vergessen: block~, subpatcher.\n\n\n% \\begin{figure}[h]\n% \t\\begin{center}\n% \t\t\\includegraphics[width = 14cm]{simpleDelay.png}\n% \t\t\\caption{SimpleDelay}\n% \t\t\\label{fig:simpleDelay}\n% \t\\end{center}\n% \\end{figure}\n\n% Studenten sollen ausprobieren. Verschiedene inputs f. kammfilter. \\\\\n\n% Modulation des kammfilters. Studenten sollen LFO an den kammfilter dran bauen.\\\\\n% \\(\\rightarrow\\) Flager \\\\\n% \\(\\rightarrow\\) Chorus \\\\\n\n% \\textbf{index/tiefe, offset, frequenz wiederholen.}\n\n\n% \\begin{figure}[h]\n% \t\\begin{center}\n% \t\t\\includegraphics[width = 14cm]{generalizedEffect.png}\n% \t\t\\caption{generalized Effect structure}\n% \t\t\\label{fig:genEffect}\n% \t\\end{center}\n% \\end{figure}\n\n% über name sprechen, sowohl spectrum als auch Impulsantwort(IIR variante) sind kammförmig. \\\\\n% Eigentlich einfach ein delay, ein delay mit feedback im falle von IIR.\\\\\n\n\n\n\n% \\begin{figure}[h]\n% \t\\begin{center}\n% \t\t\\includegraphics[width = 14cm]{img/combFIR_patch.png}\n% \t\t\\caption{Der Patch 01\\_combFilter.pd}\n% \t\t\\label{fig:01_combFilter}\n% \t\\end{center}\n% \\end{figure}\n\n\n\n% Zunächst nicht wichtig die versch. representationen zu verstehen. \\\\\n% Patch representation kurz durchbesprechen. Sollte verständlich sein.\\\\\n\n% Unterschiedliche representationen durchbesprechen.\n% Fragen, abstimmen?, was die studenten für die angenehmste representation halten.\n\n\n\n% \\begin{itemize}\n% \t\\item Patch: vorteile: interaktiv, allgemein, reinfolge der events nachvollziehbar. Nachteil: nicht sehr übersichtlich. Nicht sehr konzis, nicht kompakt.\n% \t\\item Block Diagramm: übersichtlich, allgemein. Reinfolge der events klar, pfeile! Fluss, richtung, eindeutig. Nachteile: Nicht kompakt.\n% \t\\item differenzen gleichung: Vorteil: kompakt, konzis. Nachteil: reinfolge der events nicht klar ersichtlich: kein rezept, eher eine beschreibung. (nicht imperativ sondern deklarativ, va. im Fall von Feedback)\n% \t\\item Impulsantwort: \\textbf{Frage: was ist ein Impuls?}  Vor/Nachteil: Nicht allgemein, nur ein spezieller zustand des systems beschrieben. Nicht kompakt, aber kann sehr intuitiv sein. Beispiele an tafel: IR von bypass-system, IR mit viel hall, IR von bandpass filter mit hoher resonanz, eventuell: differentiator, accumulator.\n% \t\\item andere representationen: text-code, transfer funktion, frequency response(magnitude + phase response/group delay)\n% \\end{itemize}\n\n\n\n\n% \\newpage\n\n\n% \\section {Moving Average}\n\n% \\textbf{Wo hat der kammfilter immer sein erstes Tal im spectrum?}\n% Sinus an tafel malen.\n% Antwort:\n% bei\n\n% \\(\\lambda =  (2* \\Delta t) \\)\n% (wobei \\(\\Delta t\\) die delay zweit in sekunden. und \\(\\lambda\\)  die periodendauer der gesuchten frequenz.) Daher:\\\\\n% \\(\n% f_c = 1/(2* \\Delta t)\n% \\)\n\n% Nun wird das delay auf ein sample reduziert. Ein lowpass entsteht der seine grenzfrequenz bei sr/2 hat.\\\\\n\n% Frage: was macht ein lowpass filter in der timedomain?\n\n\n% \\begin{figure}[h]\n% \t\\begin{center}\n% \t\t\\includegraphics[width = 14cm]{movingAverage.png}\n% \t\t\\caption{movingAverage}\n% \t\t\\label{fig:movingAverage}\n% \t\\end{center}\n% \\end{figure}\n\n\n% \\textbf{EXKURS: VIDEO FILTER, lowpass, time domain erkennen.}\n\n\n% \\newpage\n% \\textbf{Frage:} Vergleiche original und die gefilterte variante (01.mov) . Was für ein filter könnte angewandt worden sein:\n% \\begin{enumerate}\n%  \t\\item lowpass\n%  \t\\item bandpass\n%  \t\\item hipass\n%  \t\\item notch\n%  \t\\item nichts von alledem\n%  \\end{enumerate}\n\n\n% wie könnte ein highpass realisiert werden? Wie schaut der effekt eines highpass filters in der frequenz- und wie in der timedomain aus?\n\n\n% \\section{convolution, Faltung}\n\n% Video (unten) zeigen, vorher erklären: \\\\\n\n% conv theorem.\n\n% http://youtu.be/\\_vyke3vF4Nk?t=25m16s \\\\\n% start bei min 25.\n\n% \\textbf{maxpatch}\n\n\n\n\n% %%--------------------------------------------------------------------------\n% %% IIR/FIR\n% %%--------------------------------------------------------------------------\n% \\section {IIR/FIR}\n\n% Je steiler die Filterflanke sein, je komplexer der filter sein soll, desto mehr delays werden benötigt.\\\\\n\n% Wieso: einfache Erklärung: Um aus einem signal, das alle frequenzen enthält (zB dirac impuls) ein signal zu machen, das hauptsächlich sehr tiefe frequenzen enthält wird ein system benötigt das \\glqq{}lange wellen\\grqq{} zu produzieren im stande ist.\n\n% An tafel zeichnen: dirac impuls und unit step/ DC. Frage nach spectrum.\\\\\n\n% frage nach FIR der diesen IR haben könnte.\n\n% \\textbf{Patch: lomgSimpleFir}\n\n% Grenzfall: integrator macht aus unit impulse, \\(delta [n]\\), unit step signal\\(u[n]\\)(DC).\n\n% Integrator an tafel malen.\\\\\n\n% Daher:\n% Es kann gezeigt werden dass ein feedback pfad einer unendlichen menge an delays gleichkommt, siehe IR.\n\n% \\textbf{Patch: 02\\_combFilterIIR}\n\n% nebenbei:\n% linear phase = symmetrischer IR, immer FIR, daher weniger performant.\n% Linear phase filter sind notwendig wenn die timedomain wellenform möglichst unbeeinträchtigt bleiben soll.\n\n% \\subsection{Onepole} % (fold)\n% \\label{ssub:onepole}\n\n% % subsubsection subsubsection_name (end)\n% onepole an tafel beschreiben. Block diagramm, malen, nach differenzengleichung fragen. Patch herzeigen.\\\\\n\n% \\textbf{patch: IIRtest} \\\\\n% danach:\\\\\n% \\textbf{patch: IIRtest2} \\\\\n\n% Fragwürdig aber falls interesse:\n% onepole coeff berechnung zB:\\\\\n\n% \\begin{equation}\n% a_0 = \\frac{2 \\pi f_c} {sr}\n% \\end{equation}\n\n% oder\n\n% \\begin{equation}\n% a_0 = sin(\\frac{2 \\pi f_c} {sr})\n% \\end{equation}\n\n\n% \\section{Hausübung}\n\n% hausübung: Baue einen einen chorus. TESTSIGNAL AUSBESSERN! nicht noise!!\n", "meta": {"hexsha": "1ef44f37905fbb3fd9ea93077416bb1227eee8e4", "size": 42774, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "05_filters.tex", "max_stars_repo_name": "hrtlacek/dspCourse", "max_stars_repo_head_hexsha": "32e251b2e3756a1265fe73596515f58f51c4489f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2018-09-04T22:32:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-10T22:18:47.000Z", "max_issues_repo_path": "05_filters.tex", "max_issues_repo_name": "hrtlacek/dspCourse", "max_issues_repo_head_hexsha": "32e251b2e3756a1265fe73596515f58f51c4489f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-01-23T13:42:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-23T13:44:43.000Z", "max_forks_repo_path": "05_filters.tex", "max_forks_repo_name": "hrtlacek/dspCourse", "max_forks_repo_head_hexsha": "32e251b2e3756a1265fe73596515f58f51c4489f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-09-05T13:18:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-21T02:42:58.000Z", "avg_line_length": 42.3086053412, "max_line_length": 888, "alphanum_fraction": 0.728830598, "num_tokens": 12413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.32000976579500295}}
{"text": "\\documentclass{spec}\n\n\\usepackage{amsfonts,bm,amsmath}\n\\usepackage{verbatim}\n\\usepackage{algorithm, algpseudocode}\n\\usepackage{caption}\n\n\\input{nlls_header.tex}\n\\newcommand{\\scalarinteger}[1]{\\itt{int #1}}\n\\newcommand{\\scalarreal}[1]{\\itt{double #1}}\n\\newcommand{\\scalarlogical}[1]{\\itt{bool #1}}\n\\newcommand{\\ronearrayreal}[2]{\\itt{double *#1}}\n\\newcommand{\\scalarcharacter}[2]{\n  % need to advance the size by one for the c version compared to the fortran version...\n  \\newcount\\charsize\n  \\charsize=#2 \n  \\advance\\charsize by 1 % \n  \\itt{character #1[\\the\\charsize]}\n}\n\\newcommand{\\mainroutine}{{\\tt nlls\\_solve}}\n\\newcommand{\\onestep}{{\\tt ral\\_nlls\\_iterate}}\n\\newcommand{\\ct}{.}\n\\newcommand{\\vecentry}[2]{\\texttt{#1[#2]}}\n\\newcommand{\\fortranonly}[1]{}\n\\newcommand{\\conly}[1]{#1}\n\\begin{document}\n\n\\hslheader\n\n\\begin{center}\n\\huge \\sc  C Interface\n\\end{center}\n\n\\hslsummary\n\n\\input{summary.tex}\n\n%!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\\hslattributes\n\\hslversions{\\versionum\\ (\\versiondate)}.\n\\hslIRDCZ Real (single, double).\n\\hsllanguage Fortran 2003 subset (F95+TR155581).\n\\hsldate January 2016.\n\\hslorigin The Numerical Analysis Group, Rutherford Appleton Laboratory.\n\\hslremark The development of this package was\npartially supported by EPSRC grant EP/M025179/1.\n\n%!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\\newpage\n\\hslhowto\n\n\\subsection{Calling sequences}\n\nFunctions signatures are defined in a header file\n\\begin{verbatim}\n   #include \"ral_nlls.h\"\n\\end{verbatim}\n\\medskip\n\n\\noindent The user callable subroutines are:\n\\vspace{-0.1cm}\n\\begin{description}\n   \\item[\\texttt{ral\\_nlls\\_default\\_options()}] initializes solver options to default values.\n   \\item[\\texttt{nlls\\_solve()}]  solves the non-linear least squares problem (Section~\\ref{eq:nlls_problem}).\n   \\item[\\texttt{ral\\_nlls\\_init\\_workspace()}] initialises a workspace for use with \\texttt{ral\\_nlls\\_iterate()}.\n   \\item[\\texttt{ral\\_nlls\\_iterate()}] performs a single iteration of the solver algorithm.\n   \\item[\\texttt{ral\\_nlls\\_free\\_workspace()}] frees memory allocated by a call to \\texttt{ral\\_nlls\\_init\\_workspace()}.\n\\end{description}\n\n%%%%%%%%%%%%%%%%%%%%%% derived types %%%%%%%%%%%%%%%%%%%%%%%%\n\n\\hsltypes\n\\label{derived types}\nFor each problem, the user must employ the derived types defined by the\nmodule to declare scalars of the types {\\tt struct ral\\_nlls\\_options}, and\n{\\tt ral\\_nlls\\_inform}.\nThe following pseudocode illustrates this.\n\\begin{verbatim}\n   #include \"ral_nlls.h\"\n   ...\n   struct ral_nlls_options options;\n   struct ral_nlls_inform inform;\n   ...\n\\end{verbatim}\nThe members of these structs are explained\nin Sections~\\ref{typeoptions} and \\ref{typeinform}.\n\n\n%%%%%%%%%%%%%%%%%%%%%% argument lists %%%%%%%%%%%%%%%%%%%%%%%%\n\\hslarguments\n\n\\subsubsection{Integer and package types}\n%{\\tt INTEGER} denotes default {\\tt INTEGER} and\n%{\\tt INTEGER(long)} denotes {\\tt INTEGER(kind=selected\\_int\\_kind(18))}.\nThe term {\\bf package type} is used to mean \\texttt{float}\nif the single precision version is being used and\n\\texttt{double} for the double precision version.\n\n\\subsubsection{To initialise members of \\texttt{struct nlls\\_options} to default values}\n\nTo initialise the value of \\texttt{struct nlls\\_options}, the user \\textbf{must} make a\ncall to the following suboutine (failure to do so will result in undefined behaviour):\n\\begin{verbatim}\n   void ral_nlls_default_options(struct ral_nlls_options *options);\n\\end{verbatim}\n\n\\begin{description}\n   \\itt{*options} will be initialised to default values on return.\n\\end{description}\n\n\\subsubsection{To solve the non-linear least squares problem}\n\\label{sec:solve}\n\nTo solve the non-linear least squares problem make a call of the following\nsubroutine:\n\n\\begin{verbatim}\n   void nlls_solve( int n, int m, double X[], ral_nlls_eval_r_type eval_r,\n      ral_nlls_eval_j_type eval_j, ral_nlls_eval_hf_type eval_hf,\n      void* params, struct nlls_options const* options, struct nlls_inform* inform,\n      double weights[])\n\\end{verbatim}\n\n\\begin{description}\n\\itt{n} holds the number $n$ of\nvariables to be fitted; i.e., $n$ is the length of the unknown vector $\\bm x$.\n\n\\itt{m} holds the number $m$ of\ndata points available; i.e., $m$ is the number of functions $f_i$.\n\\textbf{Restriction:} \\texttt{m},\\texttt{n}$>$\\texttt{0}\n\n\\itt{x} must hold the initial guess for $\\bm x$, and on\nsuccessful exit it holds the solution to the non-linear least squares problem.\n\n\\itt{eval\\_r} specifies a callback function that, given a point $\\iter{\\vx}$,\nreturns the vector $\\vr(\\iter{\\vx})$. Details of the function signature and\nrequirements are are given in Section~\\ref{sec::function_eval}.\n\n\\itt{eval\\_j} specifies a callback function that, given a point $\\iter{\\vx}$,\nreturns the $m \\times n$ Jacobian matrix, $\\iter{\\vJ}$, of $\\vr$ at $\\iter{\\vx}$. Details of the function signature and requirements are are given in\nSection~\\ref{sec::function_eval}.\n\n\\itt{eval\\_hf} is a {\\tt PROCEDURE} that, given a point $\\iter{\\vx}$\nand function $\\vr(\\iter{\\vx})$, returns the second-order terms of the Hessian at $\\iter{\\vx}$.\nFurther details of the format required are given in Section~\\ref{sec::function_eval}.\n\n\\itt{params} is a pointer to user data that is passed unaltered to the callback\nfunctions {\\tt eval\\_r}, {\\tt eval\\_J}, and {\\tt eval\\_Hf}.\n\n\\itt{inform} provides information about the execution\nof the subroutine, as explained in Section~\\ref{typeinform}.\n\n\\itt{options} specifies options that control the execution of the subroutine,\nsee Section~\\ref{typeoptions}.\n\n\\itt{weights} may be {\\tt NULL}, otherwise it is a rank-1 array of size {\\tt m}. If present, {\\tt weights} holds the square-roots of the \ndiagonal entries of the weighting matrix, $\\vW$, in (\\ref{eq:nlls_problem}).  If absent, then the norm in (\\ref{eq:nlls_problem}) is taken to be the 2-norm, that is, $\\vW = I$.\n\\end{description}\n\n\\subsubsection{To initialise a workspace for use with \\texttt{ral\\_nlls\\_iterate()}}\n\nPrior to the first call of \\texttt{ral\\_nlls\\_iterate()}, the workspace must be\ninitialised by a call to the following subroutine:\n\\begin{verbatim}\n   void ral_nlls_init_workspace(void **workspace);\n\\end{verbatim}\n\n\\begin{description}\n   \\itt{*workspace} will, on return, be allocated and initialised using Fortran intrinsics.\n      To avoid a memory leak, it must be freed through a call to \\texttt{ral\\_nlls\\_free\\_workspace()}.\n\\end{description}\n\n\\subsubsection{To iterate once}\n\\label{sec:iterate}\nAlternatively, the user may step through the solution process one iteration at\na time by making a call of the following form:\n\n\\begin{verbatim}\n   void ral_nlls_iterate( int n, int m, double X[], void* workspace,\n      ral_nlls_eval_r_type eval_r, ral_nlls_eval_j_type eval_j, ral_nlls_eval_hf_type eval_hf,\n      void* params, struct nlls_options const* options, struct nlls_inform* inform,\n      double weights[])\n\\end{verbatim}\n\n\\begin{description}\n\n\\item[\\normalfont \\texttt{n}, \\texttt{m}, \\texttt{eval\\_F}, \\texttt{eval\\_J}, \\texttt{eval\\_HF}, \\texttt{params}, \\texttt{options}, \\texttt{inform}, and \\texttt{weights}] are as described in Section~\\ref{sec:solve}.\n\n\\itt{X} is an array of size {\\tt n}. On the first call, it must hold the initial guess for\n$\\bm x$. On return it holds the value of $\\bm x$ at the current iterate, and\nmust be passed unaltered to any subsequent call to \\texttt{ral\\_nlls\\_iterate()}.\n\n\\itt{w} is workspace allocated and initialised through a previous call to\n\\texttt{ral\\_nlls\\_init\\_workspace()}.\n\n\\end{description}\n\n\\subsubsection{To free a workspace when it is no longer required}\n\nMemory allocated during the call to \\texttt{ral\\_nlls\\_init\\_workspace()} may be freed\nby a call to the following subroutine:\n\\begin{verbatim}\n   void ral_nlls_free_workspace(void **workspace);\n\\end{verbatim}\n\n\\begin{description}\n   \\itt{*workspace} is the workspace to be freed. On exit it will be set to \\texttt{NULL}.\n\\end{description}\n\n\n\\subsection{User-supplied function evaluation routines}\n\\label{sec::function_eval}\nIn order to evaluate the function, Jacobian and Hessian at a point, the user\nmust supply callback functions that perform this operation that the code\n{\\tt ral\\_nlls} will call internally.\n\nIn order to pass user-defined data into the evaluation calls, the parameter\n\\texttt{params} is passed unaltered to the callback functions. Typically this\nwill be a pointer to a user defined structure that stores the data to be fitted.\n\n\\subsubsection{For evaluating the function $\\vr(\\vx)$}\n\nA subroutine must be supplied to calculate $\\vr(\\vx)$ for a given vector $\\vx$. \nIt must have the following signature:\n\\begin{verbatim}\n  int eval_r (int n, int m, void const* params, double const* x, double* r);\n\\end{verbatim}\n\n\\input{eval_r.tex}\n\n\\subsubsection{For evaluating the function $J = \\nabla \\vr(\\iter{\\vx})$}\nA subroutine must be supplied to calculate $J = \\nabla \\vr(\\iter{\\vx})$ for a given vector $\\vx$. It must have the following signature:\n\n\\begin{verbatim}\n   int eval_j (int n, int m, void const* params, double const* x, double* J);\n\\end{verbatim}\n\n\\input{eval_j.tex}\n\n\\subsubsection{For evaluating the function $Hf = \\sum_{i=1}^m r_i(\\vx) \\vW  \\nabla^2 \\vr_i(x)$}\nA subroutine must be supplied to calculate $Hf = \\sum_{i=1}^m (\\vr)_i \\nabla^2 r_i(\\vx)$ for given vectors $\\vx \\in \\mathbb{R}^n$ and $\\vr \\in \\mathbb{R}^m$; here \\((\\vr)_i\\) denotes the $i$th component of the vector $\\vr$.  \nIt must have the following signature\n\n\\begin{verbatim}\nint eval_hf (int n, int m, void const* params, double const* x, double const* r, double* Hf);\n\\end{verbatim}\n\n\\input{eval_hf.tex}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n\\subsection{The options derived data type}\n\\label{typeoptions}\n\n\\input{options_type.tex}\n\n\\subsection{The derived data type for holding information}\n\\label{typeinform}\n\n\\input{info_type.tex}\n\n%%%%%%%%%%%%%%%%%%%%%% Warning and error messages %%%%%%%%%%%%%%%%%%%%%%%%\n\n\\hslerrors\n\nA successful return from a subroutine in the package is indicated by\n{\\tt inform.status} having the value zero.\nA non-zero value is associated with an error message that by default will\nbe output on the Fortran unit {\\tt inform.error}.  This string is also passed to the \ncalling routine in {\\tt inform.error\\_message}.\n\n\\input{errors.tex}\n\n\\hslgeneral\n\n\\hslrestrictions {\\tt m$\\ge$n$\\ge$1}.\n\n\\hslmethod\n\\label{method}\n\n\\input{method.tex}\n\n\\hslexample\n\n\\input{example_text.tex}\n\n\\verbatiminput{../example/C/nlls_example.c}\n\n\n\\end{document}\n", "meta": {"hexsha": "0ff050fe586c3b844d03fa6f5696401d0ff37219", "size": 10440, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "libRALFit/doc/nlls_c.tex", "max_stars_repo_name": "andpic/RALFit", "max_stars_repo_head_hexsha": "d8bd77217b5163f79069eaf7c5238a854f4843e3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2018-04-02T12:24:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T00:11:45.000Z", "max_issues_repo_path": "libRALFit/doc/nlls_c.tex", "max_issues_repo_name": "andpic/RALFit", "max_issues_repo_head_hexsha": "d8bd77217b5163f79069eaf7c5238a854f4843e3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 95, "max_issues_repo_issues_event_min_datetime": "2016-09-13T15:16:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-23T14:08:27.000Z", "max_forks_repo_path": "libRALFit/doc/nlls_c.tex", "max_forks_repo_name": "andpic/RALFit", "max_forks_repo_head_hexsha": "d8bd77217b5163f79069eaf7c5238a854f4843e3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2018-04-02T12:24:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-23T17:12:42.000Z", "avg_line_length": 35.6313993174, "max_line_length": 225, "alphanum_fraction": 0.7254789272, "num_tokens": 2955, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.32000976579500295}}
{"text": "\\documentclass[preprint]{sigplanconf}\n\n\\usepackage{graphicx}\n\\usepackage{comment}\n\\usepackage{amsmath}\n\\usepackage{xspace}\n\\usepackage{amssymb}\n\\usepackage{stmaryrd}\n\\usepackage{proof}\n\\usepackage{multicol}\n\\usepackage[nodayofweek]{datetime}\n\\usepackage{etex}\n\\usepackage[all, cmtip]{xy}\n\\usepackage{xcolor}\n\\usepackage{listings}\n\\usepackage{multicol}\n\\newcommand\\hmmax{0} % default \\newcommand\\bmmax{0} % default 4\n\\usepackage{bm}\n\\usepackage{cmll}\n\n\\newcommand{\\fname}[1]{\\ulcorner #1 \\urcorner}\n\\newcommand{\\fconame}[1]{\\llcorner #1 \\lrcorner}\n\n\\newcommand{\\xcomment}[2]{\\textbf{#1:~\\textsl{#2}}}\n\\newcommand{\\amr}[1]{\\xcomment{Amr}{#1}}\n\\newcommand{\\roshan}[1]{\\xcomment{Roshan}{#1}}\n\n\\newcommand{\\asterix}[0]{*}\n\n\\newcommand{\\ie}{\\textit{i.e.}\\xspace}\n\\newcommand{\\eg}{\\textit{e.g.}\\xspace}\n\n\\newcommand{\\lcal}{\\ensuremath{\\lambda}-calculus\\xspace}\n\\newcommand{\\G}{\\ensuremath{\\mathcal{G}}\\xspace}\n\n\\newcommand{\\code}[1]{\\lstinline[basicstyle=\\small]{#1}\\xspace}\n\\newcommand{\\name}[1]{\\code{#1}}\n\n\\def\\newblock{}\n\n\\newenvironment{floatrule}\n    {\\hrule width \\hsize height .33pt \\vspace{.5pc}}\n    {\\par\\addvspace{.5pc}}\n\n\\newtheorem{theorem}{Theorem}[section]\n\\newtheorem{lemma}[theorem]{Lemma}\n\\newtheorem{definition}[theorem]{Definition}\n\\newtheorem{proposition}[theorem]{Proposition}\n\\newenvironment{proof}[1][Proof.]{\\begin{trivlist}\\item[\\hskip \\labelsep {\\bfseries #1}]}{\\end{trivlist}}\n\n\\newcommand{\\arrow}[1]{\\mathtt{#1}}\n\n\\newcommand{\\dgm}[2][0.95]{\n\\begin{center}\n\\scalebox{#1}{\n\\includegraphics{diagrams/#2.pdf}\n}\n\\end{center}\n}\n\n%subcode-inline{bnf-inline} name langRev\n%! swap+ = \\mathit{swap}^+\n%! swap* = \\mathit{swap}^*\n%! dagger =  ^{\\dagger}\n%! assocl+ = \\mathit{assocl}^+\n%! assocr+ = \\mathit{assocr}^+\n%! assocl* = \\mathit{assocl}^*\n%! assocr* = \\mathit{assocr}^*\n%! identr* = \\mathit{uniti}\n%! identl* = \\mathit{unite}\n%! dist = \\mathit{distrib}\n%! factor = \\mathit{factor}\n%! eta = \\eta\n%! eps = \\epsilon\n%! eta+ = \\eta^+\n%! eps+ = \\epsilon^+\n%! eta* = \\eta^{\\times}\n%! eps* = \\epsilon^{\\times}\n%! trace+ = trace^+\n%! trace* = trace^{\\times}\n%! ^^^ = ^{-1}\n%! (o) = \\circ\n%! (;) = \\fatsemi\n%! (*) = \\times\n%! (+) = +\n%! LeftP = L^+\n%! RightP = R^+\n%! LeftT = L^{\\times}\n%! RightT = R^{\\times}\n%! alpha = \\alpha\n%! bool = \\textit{bool}\n%! color = \\textit{color}\n%! Gr = G\n\n%subcode-inline{bnf-inline} regex \\{\\{(((\\}[^\\}])|[^\\}])*)\\}\\} name main include langRev\n%! Gx = \\Gamma^{\\times}\n%! G = \\Gamma\n%! [] = \\Box\n%! |-->* = \\mapsto^{\\asterix}\n%! |-->> = \\mapsto_{\\ggg}\n%! |--> = \\mapsto\n%! <--| = \\mapsfrom\n%! |- = \\vdash\n%! <><> = \\approx\n%! ==> = \\Longrightarrow\n%! <== = \\Longleftarrow\n%! <=> = \\Longleftrightarrow\n%! <-> = \\leftrightarrow\n%! ~> = \\leadsto\n%! -o+ = \\multimap^{+}\n%! -o* = \\multimap^{\\times}\n%! -o = \\multimap\n%! ::= = &::=&\n%! /= = \\neq\n%! @@ = \\mu\n%! [^ = \\lceil\n%! ^] = \\rceil\n%! forall = \\forall\n%! exists = \\exists\n%! empty = \\epsilon\n%! Pi = \\Pi\n%! Pi0 = \\Pi^{o}\n%! PiEE* = \\Pi^{\\eta\\epsilon}_{*}\n%! PiEE+ = \\Pi^{\\eta\\epsilon}_{+}\n%! PiEE = \\Pi^{\\eta\\epsilon}\n%! CatSet = \\textbf{Set}\n%! theseus = Theseus\n%! sqrt(x) = \\sqrt{#x}\n%! surd(p,x) = \\sqrt[#p]{#x}\n%! inv(x) = \\frac{1}{#x}\n%! frac(x,y) = \\frac{#x}{#y}\n%! * = \\times\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{document}\n\n\\conferenceinfo{POPL'13}{}\n\\CopyrightYear{}\n\\copyrightdata{}\n\\titlebanner{}\n\\preprintfooter{}\n\n\\title{Negative and Fractional Types} \n\n\\authorinfo{Roshan P. James}\n           {Indiana University}\n           {rpjames@indiana.edu}\n\\authorinfo{Zachary Sparks} \n           {Indiana University}\n           {zasparks@indiana.edu}\n\\authorinfo{Jacques Carette} \n           {McMaster University}\n           {carette@mcmaster.ca}\n\\authorinfo{Amr Sabry}\n           {Indiana University}\n           {sabry@indiana.edu}\n\n\\maketitle\n\n\\begin{abstract}\n\n\\end{abstract}\n\n\\category{D.3.1}{Formal Definitions and Theory}{}\n\\category{F.3.2}{Semantics of Programming Languages}{}\n\\category{F.3.3}{Studies of Program Constructs}{Type structure}\n\n\\terms\nLanguages, Theory\n\n\\keywords continuations, information flow, linear logic, logic programming,\nquantum computing, reversible logic, symmetric monoidal categories, compact\nclosed categories.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Introduction}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{The Core Reversible Language: {{Pi}} }\n\\label{sec:pi}\n\nWe review our reversible language {{Pi}}: the presentation in this\nsection differs from the one in our previous paper~\\cite{infeffects} in two\naspects. First, we add the empty type {{0}} which is necessary to express the\nadditive duality. Second, instead of explaining evaluation using a natural\nsemantics, we give a small-step operational semantics that is more\nappropriate for the connections with continuations explored in this paper.\n\n%%%%%%%%%%%%%%%%%%%%\n\\subsection{Syntax and Types} \n\\label{sec:pi-syntax}\n\nUnlike the traditional situation with the $\\lambda$-calculus, in {{Pi}},\nthere is a sharp distinction between data and programs. \n\n\\paragraph*{Data.} The sets of values and their types include:\n%subcode{bnf} include main\n% value types, b ::= 0 | 1 | b + b | b * b \n% values, v ::= () | left v | right v | (v, v)\nTypes include the empty type {{0}}, the unit type {{1}}, sum types {{b1+b2}},\nand products types {{b1*b2}}.  Values includes {{()}} which is the only value\nof type {{1}}, {{left v}} and {{right v}} which inject {{v}} into a sum type,\nand {{(v1,v2)}} which builds a value of product type. There are no values of\ntype {{0}}.\n\n\\paragraph*{Programs.} All the programs of {{Pi}} are special maps of type\n{{v \\rightarrow v}}. Specifically, they are witnesses to the following type\nisomorphisms:\n%subcode{bnf} include main\n%! columnStyle = r@{\\hspace{-0.5pt}}c@{\\hspace{-0.5pt}}l\n%zeroe :&  0 + b <-> b &: zeroi\n%swap+ :&  b1 + b2 <-> b2 + b1 &: swap+\n%assocl+ :&  b1 + (b2 + b3) <-> (b1 + b2) + b3 &: assocr+\n%identl* :&  1 * b <-> b &: identr*\n%swap* :&  b1 * b2 <-> b2 * b1 &: swap*\n%assocl* :&  b1 * (b2 * b3) <-> (b1 * b2) * b3 &: assocr*\n%dist0 :& 0 * b <-> 0 &: factor0\n%dist :&~ (b1 + b2) * b3 <-> (b1 * b3) + (b2 * b3)~ &: factor\nEach line of the above table introduces one or two combinators that witness\nthe isomorphism in the middle. Collectively the isomorphisms state that the\nstructure {{(b,+,0,*,1)}} is a \\emph{commutative semiring}, i.e., that each\nof {{(b,+,0)}} and {{(b,*,1)}} is a commutative monoid and that\nmultiplication distributes over addition. The isomorphisms are extended to\nform a congruence relation by adding the following constructors that witness\nequivalence and compatible closure:\n%subcode{proof} include main\n%@  ~\n%@@ id : b <-> b \n%\n%@ c : b1 <-> b2\n%@@ sym c : b2 <-> b1\n%\n%@ c1 : b1 <-> b2\n%@ c2 : b2 <-> b3\n%@@ c1(;)c2 : b1 <-> b3\n%---\n%@ c1 : b1 <-> b3\n%@ c2 : b2 <-> b4\n%@@ c1 (+) c2 : b1 + b2 <-> b3 + b4\n%\n%@ c1 : b1 <-> b3\n%@ c2 : b2 <-> b4\n%@@ c1 (*) c2 : b1 * b2 <-> b3 * b4\n\n\\noindent\nTo summarize, the syntax of {{Pi}} is given as follows. \n\n\\begin{definition}{(Syntax of {{Pi}})}\n\\label{def:Pi}\nWe collect our types, values, and combinators, to get the full language\ndefinition.\n%subcode{bnf} include main\n% value types, b ::= 0 | 1 | b+b | b*b \n% values, v ::= () | left v | right v | (v,v) \n%\n% comb.~types, t ::= b <-> b\n% iso ::= zeroe | zeroi \n%     &|& swap+ | assocl+ | assocr+ \n%     &|& identl* | identr* \n%     &|& swap* | assocl* | assocr* \n%     &|& dist0 | factor0 | dist | factor \n% comb., c ::= iso | id | sym c | c (;) c | c (+) c | c (*) c \n\\end{definition}\n\n\\paragraph*{Adjoint.} \nAn important property of the language is that every combinator {{c}} has an\nadjoint {{c{dagger}}} that reverses the action of {{c}}. This is evident by\nconstruction for the primitive isomorphisms. For the closure combinators, the\nadjoint is homomorphic except for the case of sequencing in which the order\nis reversed, i.e., {{(c1 (;) c2){dagger} = (c2{dagger}) (;) (c1{dagger}) }}.\n\n\\begin{definition}[Size of a type]\n\\label{def:size}\nThe size of a type {{b}}, denoted by {{[^ b ^]}}, is a numeric value\nand is defined to be:\n\\vspace{-20pt}\n\\begin{multicols}{2}\n%subcode{opsem} include main\n% [^ b1 + b2 ^] '= [^ b1 ^] + [^ b2 ^]\n% [^ b1 * b2 ^] '= [^ b1 ^] * [^ b2 ^]  \n\n%subcode{opsem} include main\n% [^ 0 ^] '= 0\n% [^ 1 ^] '= 1\n\\end{multicols}\n\nwhere {{+}} is numeric addition and {{*}} is numeric multiplication. \n  \n\\end{definition}\n\\noindent\nIn the setting of {{Pi}} the \\emph{size}, {{[^ b ^]}}, may be simply thought of as\nthe number of inhabitants (an arity) of the type. This intuition will\nhowever become tenuous in the presence of negative and fractional\ntypes.\n\n%%%%%%%%%%%%%%%%%%%\n\\subsection{Graphical Language}\n\nThe syntactic notation above is often obscure and hard to read.\nFollowing the tradition established for monoidal\ncategories~\\cite{springerlink:10.1007/978-3-642-12821-94}, we present\na graphical language that conveys the intuitive semantics of the\nlanguage (which is formalized in the next section).\n\nThe general idea of the graphical notation is that combinators are modeled by\n``wiring diagrams'' or ``circuits'' and that values are modeled as\n``particles'' or ``waves'' that may appear on the wires. Evaluation therefore\nis modeled by the flow of waves and particles along the wires.\n\n\\begin{itemize}\n\\item The simplest sort of diagram is the {{id : b <-> b}} combinator which\n  is simply represented as a wire labeled by its type {{b}}, as shown on the\n  left. In more complex diagrams, if the type of a wire is obvious from the\n  context, it may be omitted. When tracing a computation, one might imagine a\n  value {{v}} of type {{b}} on the wire, as shown on the right.\n\n  \\begin{multicols}{2}\n\\begin{center}\n\\scalebox{0.95}{\n\\includegraphics{diagrams/thesis/b-wire.pdf}\n}\n\\end{center}\n\\begin{center}\n\\scalebox{0.95}{\n\\includegraphics{diagrams/thesis/b-wire-value.pdf}\n}\n\\end{center}\n  \\end{multicols}\n\n\\item The product type {{b1*b2}} may be represented using either one wire\n  labeled {{b1*b2}} or two parallel wires labeled {{b1}} and {{b2}}. In the\n  case of products represented by a pair of wires, when tracing execution\n  using particles, one should think of one particle on each wire or\n  alternatively as in folklore in the literature on monoidal categories as a\n  ``wave.''\n\\begin{multicols}{2}\n\\begin{center}\n\\scalebox{0.95}{\n%%subcode-line{pdfimage}[diagrams/thesis/pair-one-wire.pdf]\n\\includegraphics{diagrams/thesis/product-one-wire.pdf}\n}\n\\end{center}\n\\begin{center}\n\\scalebox{0.95}{\n\\includegraphics{diagrams/thesis/product-one-wire-value.pdf}\n}\n\\end{center}\n\\end{multicols}\n\\begin{multicols}{2}\n\\begin{center}\n\\scalebox{0.95}{\n%%%subcode-line{pdfimage}[diagrams/thesis/pair-of-wires.pdf]\n\\includegraphics{diagrams/thesis/product-two-wires.pdf}\n}\n\\end{center}\n\\begin{center}\n\\scalebox{0.95}{\n\\includegraphics{diagrams/thesis/product-two-wires-value.pdf}\n}\n\\end{center}\n\\end{multicols}\n\n\\item Sum types may similarly be represented by one wire or using\n  parallel wires with a {{+}} operator between them. When tracing the\n  execution of two additive wires, a value can reside on only one of the two\n  wires.\n\\begin{multicols}{2}\n\\begin{center}\n\\scalebox{0.95}{\n%%subcode-line{pdfimage}[diagrams/thesis/sum-one-wire.pdf]\n\\includegraphics{diagrams/thesis/sum-one-wire.pdf}\n}\n\\end{center}\n\\begin{center}\n\\scalebox{0.95}{\n\\includegraphics{diagrams/thesis/sum-two-wires-left-value.pdf}\n}\n\\end{center}\n\\end{multicols}\n\\begin{multicols}{2}\n\\begin{center}\n\\scalebox{0.95}{\n%%subcode-line{pdfimage}[diagrams/thesis/sum-of-wires.pdf]\n\\includegraphics{diagrams/thesis/sum-two-wires.pdf}\n}\n\\end{center}\n\\begin{center}\n\\scalebox{0.95}{\n\\includegraphics{diagrams/thesis/sum-two-wires-right-value.pdf}\n}\n\\end{center}\n\\end{multicols}\n\n\\item Associativity is implicit in the graphical language. Three parallel\n  wires represent {{b1*(b2*b3)}} or {{(b1*b2)*b3}}, based on the context.\n\\begin{center}\n\\scalebox{0.95}{\n%%subcode-line{pdfimage}[diagrams/thesis/associate.pdf]\n\\includegraphics{diagrams/thesis/assoc.pdf}\n}\n\\end{center}\n\n\\item Commutativity is represented by crisscrossing wires.\n\\begin{multicols}{2}\n\\begin{center}\n\\scalebox{0.95}{\n%%subcode-line{pdfimage}[diagrams/thesis/swap-pair.pdf]\n\\includegraphics{diagrams/thesis/swap_times.pdf}\n}\n\\end{center}\n\\begin{center}\n\\scalebox{0.95}{\n%%subcode-line{pdfimage}[diagrams/thesis/swap-sum.pdf]\n\\includegraphics{diagrams/thesis/swap_plus.pdf}\n}\n\\end{center}\n\\end{multicols}\n\nBy visually tracking the flow of particles on the wires, one can\nverify that the expected types for commutativity are satisfied.\n\n\\begin{multicols}{2}\n\\begin{center}\n\\scalebox{0.95}{\n\\includegraphics{diagrams/thesis/swap_times_value.pdf}\n}\n\\end{center}\n\\begin{center}\n\\scalebox{0.95}{\n\\includegraphics{diagrams/thesis/swap_plus_value.pdf}\n}\n\\end{center}\n\\end{multicols}\n\n\n\\item The morphisms that witness that {{0}} and {{1}} are the additive and\n  multiplicative units are represented as shown below. Note that since there\n  is no value of type 0, there can be no particle on a wire of type {{0}}.\n  Also since the monoidal units can be freely introduced and eliminated, in\n  many diagrams they are omitted and dealt with explicitly only when they are\n  of special interest.\n\\begin{multicols}{2}\n\\begin{center}\n\\scalebox{0.95}{\n%%subcode-line{pdfimage}[diagrams/thesis/identr1.pdf]\n\\includegraphics{diagrams/thesis/uniti.pdf}\n}\n\\end{center}\n\\begin{center}\n\\scalebox{0.95}{\n%%subcode-line{pdfimage}[diagrams/thesis/identl1.pdf]\n\\includegraphics{diagrams/thesis/unite.pdf}\n}\n\\end{center}  \n\\end{multicols}\n\\begin{multicols}{2}\n\\begin{center}\n\\scalebox{0.95}{\n%%subcode-line{pdfimage}[diagrams/thesis/identr0.pdf]\n\\includegraphics{diagrams/thesis/zeroi.pdf}\n}\n\\end{center}\n\\columnbreak\n\\begin{center}\n\\scalebox{0.95}{\n%%subcode-line{pdfimage}[diagrams/thesis/identl0.pdf]\n\\includegraphics{diagrams/thesis/zeroe.pdf}\n}\n\\end{center}\n\\end{multicols}\n\n\\item Finally, distributivity and factoring are represented using the dual\n  boxes shown below:\n\\begin{multicols}{2}\n\\begin{center}\n  \\includegraphics{diagrams/thesis/dist.pdf}\n\\end{center}\n\\begin{center}\n  \\includegraphics{diagrams/thesis/factor.pdf}\n\\end{center}\n\\end{multicols}\n\nDistributivity and factoring are interesting because they represent\ninteractions between sum and pair types. Distributivity should\nessentially be thought of as a multiplexer that redirects the flow of\n{{v:b}} depending on what value inhabits the type {{b1+b2}}, as shown\nbelow. Factoring is the corresponding adjoint operation.\n\n\\begin{multicols}{2}\n\\begin{center}\n  \\includegraphics{diagrams/thesis/dist-wire-value1.pdf}\n\\end{center}\n\\begin{center}\n  \\includegraphics{diagrams/thesis/dist-wire-value2.pdf}\n\\end{center}\n\\end{multicols}\n\n\\item Composition TODO.\n\n  \\begin{multicols}{2}\n\\dgm{c1c2_par_sum}\n\\dgm{c1c2_par_times}\n  \\end{multicols}\n\\dgm{c1c2_seq}    \n\n\\end{itemize}\n\n\\noindent \n\\textit{Example.}  We use the type {{bool}} as a shorthand to denote\nthe type {{1+1}} and use {{left ()}} to be {{true}} and {{right ()}}\nto be {{false}}. The following combinator is represented by the given\ndiagram:\n\n{{c : b * bool <-> b + b}}\n\n{{c = swap* (;) dist (;) (identl* (+) identl*)}}\n\n\\begin{center}\n\\scalebox{0.95}{\n%%subcode-line{pdfimage}[diagrams/thesis/example1-crop.pdf]\n\\includegraphics{diagrams/thesis/example1.pdf}\n}\n\\end{center}\n\n%%%%%%%%%%%%%%%%%%%\n\\subsection{Semantics}\n\nThe operational semantics of {{Pi}} is summarized below (also see\n\\cite{infeffects}).  The semantics of the primitive combinators is\ngiven by the following single-step reductions below. Since there are\nno values of type {{0}}, the rules omit the impossible cases:\n\\begin{scriptsize}\n%subcode{opsem} include main\n%! columnStyle = rlcl\n% swap+ & (left v) &|-->& right v\n% swap+ & (right v) &|-->& left v \n% assocl+ & (left v1) &|-->& left (left v1)\n% assocl+ & (right (left v2)) &|-->& left (right v2)\n% assocl+ & (right (right v3)) &|-->& right v3 \n% assocr+ & (left (left v1)) &|-->& left v1\n% assocr+ & (left (right v2)) &|-->& right (left v2)\n% assocr+ & (right v3) &|-->& right (right v3)\n% identl* & ((), v) &|-->& v \n% identr* & v &|-->& ((), v) \n% swap* & (v1, v2) &|-->& (v2, v1) \n% assocl* & (v1, (v2, v3)) &|-->& ((v1, v2), v3) \n% assocr* & ((v1, v2), v3) &|-->& (v1, (v2, v3)) \n% dist & (left v1, v3) &|-->& left (v1, v3)\n% dist & (right v2, v3) &|-->& right (v2, v3)\n% factor & (left (v1, v3)) &|-->& (left v1, v3) \n% factor & (right (v2, v3)) &|-->& (right v2, v3)   \n\\end{scriptsize}\nThe operational semantics of the closure conditions are presented in\nthe usual big-step style.\n\\begin{scriptsize}\n%subcode{proof} include main\n%@ ~\n%@@ id v |--> v \n%\n%@ c{dagger} v1 |--> v2\n%@@ (sym c) v1 |--> v2\n%\n%@ c1  v1 |--> v\n%@ c2  v |--> v2\n%@@ (c1(;)c2)  v1 |--> v2\n%---\n%@ c1  v1 |--> v2\n%@@ (c1 (+) c2)  (left v1) |--> left v2\n%\n%@ c2  v1 |--> v2\n%@@ (c1 (+) c2)  (right v1) |--> right v2\n%---\n%@ c1  v1 |--> v3\n%@ c2  v2 |--> v4\n%@@ (c1 (*) c2)  (v1, v2) |--> (v3, v4)\n\\end{scriptsize}\n\nThe type safety of {{Pi}} follows directly from the correspondence\nbetween inductive definitions of the types and the big-step\nsemantics. Previous work also established the following properties:\n\n\\begin{proposition}[Strong Normalizing]\n\\label{prop:termination-pi} \n{{Pi}} computations always terminate.  \n\n{{forall. c:b1<->b2, v:b1, exists v':b2.}}  \n{{c v |--> v'}}\n\\end{proposition}\n\n\\begin{proposition}[Logical Reversibility]\n\\label{prop:logrev}\n{{c v |--> v'}} iff \n{{ c{dagger} v' |--> v}}\n\\end{proposition}\n\n%%%%%%%%%%%%%%%%%%%\n\\subsection{Constructions}\n\n\\paragraph*{Booleans and Conditionals.} \nGiven any combinator {{c : b <-> b}} we can construct a combinator called\n{{if_c : bool*b <->bool*b}} in terms of {{c}}, where {{if_c}} behaves like a\none-armed $\\mathit{if}$-expression. If the supplied boolean is {{true}} then\nthe combinator {{c}} is used to transform the value of type~{{b}}. If the\nboolean is {{false}}, then the value of type {{b}} remains unchanged. We can\nwrite down the combinator for {{if_c}} in terms of {{c}} as \n{{ dist (;) ((id (*) c) (+) id) (;) factor }}.\n\n\\noindent The diagram below shows the input value of type {{(1+1)*b}}\nprocessed by the distribute operator {{dist}}, which converts it into a value\nof type {{(1*b)+(1*b)}}. In the {{left}} branch, which corresponds to the\ncase when the boolean is {{true}} (i.e. the value was {{left ()}}), the\ncombinator~{{c}} is applied to the value of type~{{b}}. The right branch\nwhich corresponds to the boolean being {{false}} passes along the value of\ntype {{b}} unchanged.\n\n\\begin{center}\n\\scalebox{1.0}{\n%%subcode-line{pdfimage}[diagrams/if_c.pdf]\n\\includegraphics{diagrams/thesis/cnot.pdf}\n}\n\\end{center}\n\nThe combinator {{if_{not} }} has type {{bool*bool<->bool*bool}} and\nnegates its second argument if the first argument is {{true}}. This\ngate {{if_{not} }} is often referred to as the {{cnot}} gate. An\nequivalent construction that is useful is {{else_{not} }} where we\nnegate the second argument only if the first is {{false}}. \n\nSimilarly, we can iterate the construction of {{if_c}} to check several\nbits. The gate {{if_{cnot} }}, which we may also write as {{if^2_{not} }},\nchecks two booleans and negates the result wire only if they are both\n{{true}}. The gate {{if^2_{not} }} is well known as the Toffoli gate and is a\nuniversal reversible gate. We can generalize this construction to\n{{if^n_{not} }} which checks {{n}} bits and negates the result wire only if\nthey are all {{true}}.\n\n\\paragraph*{Cloning.}\nAlthough cloning is generally not allowed in reversible languages, it is\npossible at the cost of having additional constant inputs. For example,\nconsider the gate {{else_{not} }}. Generally, the gate maps\n{{(false,a)}} to {{(false,not a)}} and {{(true,a)}} to {{(true,a)}}. Focusing\non the cases in which the second input is {{true}}, we get that the gate maps\n{{(false,true)}} to {{(false,false)}} and {{(true,true)}} to {{(true,true)}},\ni.e., the gate clones the first input. A circuit of {{n}} parallel\n{{else_{not} }} gates can hence clone {{n}} bits.  They also consume {{n}}\n{{true}} inputs in the process.  Let us call this construction\n{{clone^n_{bool} }}.\n\n%%%%%%%%%%%%%%%%%\n\\subsection{Categorical Structure}\n\nFor the purpose of establishing equivalence of morphisms in the\ncategorical presentation we use the following notion of equality:\n\n\\begin{lemma}[{{c1  = c2}}]\nWe say {{c1 = c2}} if {{c1:b1<->b2}} and {{c2:b1<->b2}} and for all\n{{v1:b}}, we have {{c1 v1 |--> v2}} iff {{c2 v1 |--> v2}} and {{v2:b2}}.\n\\end{lemma}\n\nWe present the categorical structure with minimum commentary. More\ndetails may be found in excellent references such as Barr and Wells\n[CITE] and Selinger \\cite{springerlink:10.1007/978-3-642-12821-94}.\n\n\\begin{lemma}[{{Pi}} is a category]\n  The category {{Pi}} has the types {{b}} as objects and equivalence\n  classes of well-typed combinators {{b1<->b2}} as morphisms. One can\n  check:\n  \\begin{enumerate}\n  \\item Every object {{b}} has an identity morphism {{id : b <->b}}.\n  \\item Composition {{g (o) f}} of morphisms {{f:b1 <->b2}} and\n    {{g:b2<->b3}} is given by sequencing {{f (;) g}}. \n  \\item Associativity of composition follows from operational\n    equivalence of {{f(;)(g(;)h)}} and {{(f(;)g)(;)h}} (where\n    {{h:b3<->b4}}). \n\n    Assuming {{v1:b1}}, {{v2:b2}}, {{v3:b3}}, {{v4:b4}},\n    {{f~v1|-->v2}}, {{g v2 |--> v3}} and {{h~v3 |--> v4}}, one can\n    check:\n\n\\vspace{-20pt}\n    \\begin{multicols}{2}\n      \\begin{scriptsize}\n        \n%subcode{proof} include main\n%@@ f v1 |--> v2\n%@ g v2 |--> v3\n%@ h v3 |--> v4\n%@@ g (;) h  v2 |--> v4\n%@@@ f (;) (g (;) h) v1 |--> v4\n~\n%subcode{proof} include main\n%@ f v1 |--> v2\n%@ g v2 |--> v3\n%@@ f (;) g v1 |--> v3\n%@@ h v3 |--> v4\n%@@@ (f (;) g) (;) h v1 |--> v4\n\n      \\end{scriptsize}\n    \\end{multicols}\n\n  \\item Composition respects identity: {{id (;) f = f}} and {{g(;)id=g}}.\n  \\end{enumerate}\n\\end{lemma}\n\n\\begin{lemma}[Dagger]\n  {{Pi}} is a dagger category, where every morphism {{f : b1<->b2}}\n  has the adjoint {{f^{dagger}:b2 <->b1}}. The following properties\n  hold (where {{g : b2 <-> b3}}): \n  \\begin{enumerate}\n  \\item {{id^{dagger} = id : b <-> b}}.\n  \\item {{(f (;) g)^{dagger} = g^{dagger} (;) f^{dagger}: b3 <-> b1}}.\n  \\item {{f^{dagger dagger} = f : b1 <-> b2}}.\n  \\end{enumerate}\n\\end{lemma}\n\n\\begin{lemma}[Symmetric Monoidal (+, 0)]\n  {{Pi}} is a symmetric monoidal category with tensor {{+}} and\n  monoidal unit {{0}}. The monoidal operation on morphisms is the\n  additive composition of combinators {{c1 (+) c2}}.\n\n  \\begin{proof}\n    To establish that category is monoidal one must show isomorphisms\n    \\begin{enumerate}\n    \\item {{b1 + (b2 + b3) <-> (b1 +b2) + b3}} given by {{assocl+}}.\n    \\item {{0 + b <-> b}} given by {{zeroe}}.\n    \\item {{b + 0 <-> b}} given by {{swap+ (;) zeroe}}.\n    \\item We need to check that {{+}} is a bifunctor. \n      \\begin{enumerate}\n      \\item {{id_{b1<->b1}(+)id_{b2<->b2} = id_{b1+b2<->b1+b2} }}.\n      \\item {{(f(+)g)(;)(j(+)k) = (f (;) j) (+) (g (;) k)}}.\n      \\end{enumerate}\n    \\item We need to check the naturality of {{assocl+}}, {{zeroe}} and\n      {{swap+(;)zeroe}}.\n      \\begin{enumerate}\n      \\item {{assocl+ (;) ((f (+)g) (+) h) = (f (+)(g (+) h)) (;) assocl+}}.\n      \\item {{zeroe (;) f = (id (+) f) (;) zeroe}}.\n      \\item {{(swap+ (;) zeroe) (;) f = (f (+) id) (;) (swap+ (;) zeroe)}}.\n      \\end{enumerate}\n    \\item Satisfy certain coherence conditions which are usually\n      called the ``pentagon'' and ``triangle'' axioms (see Sec 3.1\n      \\cite{springerlink:10.1007/978-3-642-12821-94})\n    \\end{enumerate}\n\n    The last three points require checking equality of combinators by\n    writing out their derivation trees as we did in the case of\n    associativity of sequential composition. To show symmetry, we need\n    a braiding operation {{b1+b2 <-> b2+b1}} which is given by\n    {{swap+}} (see Sec. 3.3 and 3.5\n    \\cite{springerlink:10.1007/978-3-642-12821-94}).\n\n    \\begin{enumerate}\n    \\item The braiding must satisfy two ``hexagon'' axioms.\n    \\item The braiding is self inverse,\n      {{swap+_{b1+b2}=(swap+_{b2+b1})^{dagger} }}.\n    \\end{enumerate}\n\n\n  \\end{proof}\n\n\\end{lemma}\n\n\\begin{lemma}[Symmetric Monoidal {{(*, 1)}}]\n  {{Pi}} is a symmetric monoidal category over the tensor {{*}} and\n  unit {{1}}. The details mirror those of the {{(0, +)}} monoid.\n\\end{lemma}\n\n\\noindent\nSome technical and pedantic comments are due at this point. \n\n\\begin{itemize}\n\\item We have established the categorical structure of {{Pi}} as a\n  dagger symmetric monoidal category with two monoidal structures,\n  {{(0, +)}} and {{(*, 1)}}. In Sec. \\ref{sec:int} we will see that a\n  {{trace}} operator can be admitted in this category without any\n  change of expressiveness.\n\n\\item To be pedantic, what we have shown is that the ``term model'' of\n  {{Pi}} that follows from the extensional operational equality of\n  combinators has the requisite categorical structure. A consequence\n  is that the ``wiring diagrams'' of {{Pi}} correspond closely with ``string\n  diagrams'' developed for categories.\n\n  To establish the later rigorously, we will need to show when it is\n  valid to slide one wire over the other and that equivalent diagrams\n  for syntactically different combinators such as\n  {{(f(+)g)(;)(j(+)k)}} and {{(f(;)j)(+)(g(;)k)}} do respect\n  operational equivalence.  We don't formalize the graphical notation\n  in this work. Joyal et. al's work on ``planar isotopy'' and\n  Selinger's survey \\cite{springerlink:10.1007/978-3-642-12821-94}\n  show how this has been addressed before in the categorical\n  setting. In the absence of any prior knowledge of category theory\n  however, our wiring diagrams may be read as the ``flow of types'' in\n  a combinator-circuit.\n\n\\item By definition, in {{Pi}} every morphism is an isomorphism --\n  this makes {{Pi}} a groupoid.\n\n\\item The category {{Pi}} has no initial and terminal objects. The\n  objects {{0}} and {{1}} would be initial and terminal if we admitted\n  all functions (as in the category {{CatSet}}).\n\n\\item The category {{Pi}} has neither categorical products, nor\n  categorical co-products, i.e. {{*}} and {{+}} are merely monoidal\n  tensors. This follows from the fact that injection and projection\n  maps are not isomorphisms.\n\\end{itemize}\n\nWhile we don't do so in this work, if we extend {{Pi}} with products\nand co-products (say through the addition of information effects) it\nis conceivable that part of its structure collapses. This sort of\ncollapse, while catastrophic for algebraic structures (effectively\ntrivializing them), still retains some interest in computing, because\nin computing we are interested in the specific operational nature (the\ncomputational content, so to speak) of the morphisms. Anecdotal evidence\nfollows from the fact several real-world programming language have\ninconsistent type systems. blah blah blah...\n\n%%%%%%%%%%%%%\n\\subsection{Small Step Semantics}\n\nThe reductions for the primitive isomorphisms above are exactly the same as\nhave been presented before~\\cite{infeffects}. The reductions for the closure\ncombinators are however presented in a small-step operational style using the\nfollowing definitions of evaluation contexts and machine states:\n\n\\begin{scriptsize}\n%subcode{bnf} include main\n% Combinator Contexts, C = [] | Fst C c | Snd c C \n%                  &|& LeftT C c v | RightT c v C \n%                  &|& LeftP C c | RightP c C \n% Machine states = <c, v, C> | {[c, v, C]}\n% Start state = <c, v, []> \n% Stop State = {[c, v, []]}\n\\end{scriptsize}\nThe machine transitions below track the flow of particles through a\ncircuit. The start machine state, {{<c,v,[]>}}, denotes the\nparticle~{{v}} about to be evaluated by the circuit {{c}}. The end\nmachine state, {{[c, v, [] ]}}, denotes the situation where the particle\n{{v}} has exited the circuit {{c}}.\n\n\\begin{scriptsize}\n%subcode{opsem} include main\n%! columnStyle = rclr\n% <iso, v, C> &|-->& {[iso, v', C]} & (1)\n% & & where iso v |--> v' &\n% <c1(;)c2, v, C> &|-->& <c1, v, Fst C c2> & (2) \n% {[c1, v, Fst C c2]} &|-->& <c2, v, Snd c1 C> & (3) \n% {[c2, v, Snd c1 C]} &|-->& {[ c1(;)c2, v, C ]} & (4) \n% <c1(+)c2, left v, C> &|-->& <c1, v, LeftP C c2> & (5) \n% {[ c1, v, LeftP C c2 ]} &|-->& {[c1 (+) c2, left v, C ]} & (6)\n% <c1(+)c2, right v, C> &|-->& <c2, v, RightP c1 C> & (7)\n% {[ c2, v, RightP c1 C ]} &|-->& {[c1 (+) c2, right v, C ]} & (8)\n% <c1(*)c2, (v1, v2), C> &|-->& <c1, v1, LeftT C c2 v2> & (9)\n% {[ c1, v1, LeftT C c2 v2 ]} &|-->& <c2, v2, RightT c1 v1 C> & (10) \n% {[ c2, v2, RightT c1 v1 C ]} &|-->& {[ c1 (*) c2, (v1, v2), C ]} & (11)\n\\end{scriptsize}\nRule (1) describes evaluation by a primitive isomorphism. Rules (2), (3) and\n(4) deal with sequential evaluation. Rule (2) says that for the value {{v}}\nto flow through the sequence {{c1 (;) c2}}, it should first flow through\n{{c1}} with {{c2}} pending in the context ({{Fst C c2}}). Rule (3) says the\nvalue {{v}} that exits from {{c1}} should proceed to flow\nthrough~{{c2}}. Rule (4) says that when the value {{v}} exits {{c2}}, it also\nexits the sequential composition {{c1(;)c2}}. Rules (5) to (8) deal with \n{{c1 (+) c2}} in the same way. In the case of sums, the shape of the value,\ni.e., whether it is tagged with {{left}} or {{right}}, determines whether\npath {{c1}} or path {{c2}} is taken. Rules (9), (10) and (11) deal with \n{{c1 (*) c2}} similarly. In the case of products the value should have the\nform {{(v1, v2)}} where {{v1}} flows through {{c1}} and {{v2}} flows through\n{{c2}}. Both these paths are entirely independent of each other and we could\nevaluate either first, or evaluate both in parallel. In this presentation we\nhave chosen to follow {{c1}} first, but this choice is entirely arbitrary.\n\nThe interesting thing about the semantics is that it represents a reversible\nabstract machine. In other words, we can compute the start state from the\nstop state by changing the reductions {{|-->}} to run backwards\n{{<--|}}. When running backwards, we use the isomorphism represented by a\ncombinator {{c}} in the reverse direction, i.e., we use the adjoint\n{{c{dagger}}}.\n\n\\begin{proposition}[Correspondence]\n  Evaluation in the small-step evaluator corresponds to evaluation in\n  the natural semantics.\n\n  {{c v |--> v'}} iff {{<c, v, []> |-->* [c', v', [] ]}}\n\\end{proposition}\n\\begin{proof}\n  To prove the above, we first show that a more general lemma holds,\n  namely that: {{c v |--> v'}} iff {{<c, v, C> |-->* [c', v', C ]}}.\n\n  To show the left-to-right direction we proceed by induction on the\n  derivation of {{c v |--> v'}}. In the case of primitive isomorphisms\n  the condition holds trivially. In the case of composition, we work\n  out the case of {{c1+c2}} as an example. Given {{c1 +c2 v |--> v'}}\n  we have to show that there is a small step derivation sequence that\n  matches it. Here {{v:b1+b2}} can be of the form {{left v1}} or\n  {{right v2}}. Assuming {{left v1}}, we have: \n\n%subcode{proof} include main\n%@ c1 v1 |--> v1' ==> <c1, v1, C'> |-->* {[c1',v1',C']}\n%@@ c1+c2 (left v1) |--> left v1' ==> ? \n\nChoosing {{C' =Lft c2 C}}, we have the required derivation sequence: \n{{ <c1+c2, left v1, C> |--> <c1,v1,LeftP c2 C> |-->* {[c1',v1', LeftP c2 C]} |--> {[c1'+c2,left v1',C]} }}. The proof follows similarly for the {{right v2}} case.  \n\nTo show the right-to-left direction we proceed by induction of the\nsequence of {{|-->*}} derivations. Again the case for primtive\nisomorphisms follows trivially. Taking the case of {{c1+c2}} we are\nrequired to show that given a sequence \n{{<c1+c2,v,C> |-->* {[c', v', C]} }} there is a derviation tree for\n{{c1+c2 v |--> v'}}. In the case that {{v:v1+b2}} has the form\n{{left~v1}}, this follows by observing that the given sequence must have the form\n{{ <c1+c2, left v1, C> |--> <c1,v1,LeftP c2 C> |-->* {[c1',v1', LeftP c2 C]} |--> {[c1'+c2,left v1',C]} }}. \nFor the strictly smaller inner subsequence by induction we have\n{{c1~v1 |--> v1'}} which lets us complete the derivation of\n{{c1+c2~(left v1) |--> left v1'}}. The {{right v2}} follows similarly. \n\n\\end{proof}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{small}\n\\bibliographystyle{abbrvnat}\n\\bibliography{cites}\n\\end{small}\n\n\\end{document}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n", "meta": {"hexsha": "405353db78a7a722197735ae565959bd2220b7bb", "size": 32294, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "popl13/p.tex", "max_stars_repo_name": "JacquesCarette/pi-dual", "max_stars_repo_head_hexsha": "003835484facfde0b770bc2b3d781b42b76184c1", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2015-08-18T21:40:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T01:07:57.000Z", "max_issues_repo_path": "popl13/p.tex", "max_issues_repo_name": "JacquesCarette/pi-dual", "max_issues_repo_head_hexsha": "003835484facfde0b770bc2b3d781b42b76184c1", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-06-07T16:27:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-29T20:41:23.000Z", "max_forks_repo_path": "popl13/p.tex", "max_forks_repo_name": "JacquesCarette/pi-dual", "max_forks_repo_head_hexsha": "003835484facfde0b770bc2b3d781b42b76184c1", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-05-29T01:56:33.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-10T09:47:13.000Z", "avg_line_length": 34.7995689655, "max_line_length": 164, "alphanum_fraction": 0.6495943519, "num_tokens": 10373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.32000976579500295}}
{"text": "\\documentclass[a4paper,oneside,11pt]{report}\n\\usepackage[cm]{fullpage}\n\\usepackage{lmodern,amsmath,amssymb}\n\\usepackage{a4wide}\n\\setlength{\\marginparwidth}{3cm}\n\\setlength{\\topmargin}{0cm}\n\\setlength{\\voffset}{0cm}\n\\setlength{\\headsep}{0cm}\n\\title{Modeling Durotaxis using Mechanical Bidomain model}\n\\author{Prof Brad Roth, Debabrata Auddya}\n%\\usepackage{etoolbox}\n%\\preto\\equation{\\setcounter{equation}{0}}\n%\\makeatletter\n%\\pretocmd\\start@gather{\\setcounter{equation}{0}}{}{}\n%\\pretocmd\\start@align{\\setcounter{equation}{0}}{}{}\n%\\pretocmd\\start@multline{\\setcounter{equation}{0}}{}{}\n%\\makeatother\n\\usepackage{listings}\n\\usepackage{color}\n\\usepackage{dsfont}\n\\usepackage{footmisc}\n\\usepackage{verbatim}\n\\usepackage{smartdiagram}\n\\setlength{\\marginparwidth}{0cm}\n\\setlength{\\topmargin}{0cm}\n\\setlength{\\voffset}{0cm}\n\\setlength{\\headsep}{0cm}\n\\definecolor{dkgreen}{rgb}{0,0.6,0}\n\\definecolor{gray}{rgb}{0.5,0.5,0.5}\n\\definecolor{mauve}{rgb}{0.58,0,0.82}\n\n\\lstset{frame=tb,\n\tlanguage=Java,\n\taboveskip=3mm,\n\tbelowskip=3mm,\n\tshowstringspaces=false,\n\tcolumns=flexible,\n\tbasicstyle={\\small\\ttfamily},\n\tnumbers=none,\n\tnumberstyle=\\tiny\\color{gray},\n\tkeywordstyle=\\color{blue},\n\tcommentstyle=\\color{dkgreen},\n\tstringstyle=\\color{mauve},\n\tbreaklines=true,\n\tbreakatwhitespace=true,\n\ttabsize=3\n}\n\\begin{document}\n\\maketitle\n\\section*{Analytical treatment - 10/03/2018}\nThe equations formulated below consider a gradient in the extracellular stiffness in a 1-d strand of tissue using the mechanical bidomain model. \\\\\n\nConsider $u_{x}$ and $w_{x}$ as the intra- and extra-cellular displacements of the bidomain layer. x being the principal direction of the one-dimensional tissue strand, T being the tension, p and q being the intra- and extra-cellular pressure contributions arising mostly from hydrostatic forces. \\\\\n\nThe standard equations of the bidomain model are as follows \\cite{roth2012}: \n\\begin{align}\n-\\frac{\\partial p}{\\partial x} + \\nu(\\frac{\\partial^{2}u_x}{\\partial x^2} + \\frac{\\partial^{2}u_x}{\\partial y^2} ) + \\gamma\\frac{\\partial^{2}u_x}{\\partial x^2} + \\frac{\\partial T}{\\partial x} = K(u_x - w_x) \\\\\n-\\frac{\\partial q}{\\partial x} + \\mu(\\frac{\\partial^{2}w_x}{\\partial x^2} + \\frac{\\partial^{2}w_x}{\\partial y^2} ) = -K(u_x - w_x) \n\\end{align}   \nFor this problem we consider:\n\\begin{itemize} \n\\item $\\mu = \\mu_0 + gx$ \n\\item No contributions along the y axis\n\\item p,q and T are constant and hence their gradients are zero along the x axis\n\\item Slope of $\\mu$ is a constant \n\\item K is same for intra- and extra-cellular displacements\n\\end{itemize}\n\\begin{align}\n    \\nu\\frac{\\partial^{2}u_x}{\\partial x^2} + \\gamma\\frac{\\partial^{2}u_x}{\\partial x^2} = K(u_x - w_x)  \\\\\n    \\mu_0\\frac{\\partial^{2}w_x}{\\partial x^2} + gx\\frac{\\partial^{2}w_x}{\\partial x^2} = -K(u_x - w_x) \n\\end{align}\nSimplifying the above expression, replacing $u_x$ in equation (2) from (1): \n\\begin{align}\n   u_x = w_x + \\frac{\\nu}{K}\\frac{\\partial^{2}u_x}{\\partial x^2} + \\frac{\\gamma}{K}\\frac{\\partial^{2}u_x}{\\partial x^2} + \\gamma\\frac{\\partial^{2}u_x}{\\partial x^2} \\\\\n   \\therefore \\frac{\\mu_0}{K}\\frac{\\partial^{2}w_x}{\\partial x^2} + x\\frac{g}{k}\\frac{\\partial^{2}w_x}{\\partial x^2} = - ( \\frac{\\nu}{K}\\frac{\\partial^{2}u_x}{\\partial x^2} + \\frac{\\gamma}{K}\\frac{\\partial^{2}u_x}{\\partial x^2} )\n\\end{align}\nFinal form the equation can be written as: \n\\begin{align}\n\\frac{\\partial^{2}w_x}{\\partial x^2} (\\frac{\\mu_0}{K} + \\frac{gx}{K}) + \\frac{\\partial^{2}u_x}{\\partial x^2} (\\frac{\\nu}{K} + \\frac{\\gamma}{K} ) = 0\n\\end{align}\n\\clearpage\n\\section*{Analytical treatment - 10/04/2018}\nThe equations formulated below consider a gradient in the extracellular stiffness in a 1-d strand of tissue using the mechanical bidomain model. \\\\\n\nConsider $u_{x}$ and $w_{x}$ as the intra- and extra-cellular displacements of the bidomain layer. x being the principal direction of the one-dimensional tissue strand, T being the tension, p and q being the intra- and extra-cellular pressure contributions arising mostly from hydrostatic forces. \\\\\n\nThe intra and extra-cellular stresses arising in the 1-d strand of tissue can be expressed as \\cite{roth2015}: \n\\begin{align}\n\\tau_{ix} = -p + 2\\nu\\epsilon_{ix} + T \\\\\n\\tau_{ex} = -q + 2\\mu(x)\\epsilon_{ex}   \n\\end{align}\nRelationship between the strains and displacement can be written as: \n\\begin{align}\n\\frac{\\partial\\tau_{ix}}{\\partial x} = K (u_x - w_x) \\\\\n\\frac{\\partial\\tau_{ex}}{\\partial x} = - K (u_x - w_x) \n\\end{align}\nUsing equation (8) and (9) in (10) and (11) the resulting intra- and extra-cellular equations are: \n\\begin{align}\n\\frac{\\partial}{\\partial x}(-p + 2\\nu\\frac{\\partial u_x}{\\partial x}) = K (u_x - w_x) \\\\\n\\frac{\\partial}{\\partial x}(-q + 2\\mu (x) \\frac{\\partial w_x}{\\partial x}) = -K (u_x - w_x)\n\\end{align}\nFor the problem we have assumed $\\mu = \\mu_0 + gx$ , where g is a constant. Rewriting (12) and (13) we have:\n\\begin{align}\n- \\frac{\\partial p}{\\partial x} + 2\\nu\\frac{\\partial^{2}u_x}{\\partial x^2} = K (u_x - w_x) \\\\\n- \\frac{\\partial q}{\\partial x} + 2(g\\frac{\\partial w_x}{\\partial x} + \\frac{\\partial^{2}w_x}{\\partial x^2} \\mu(x)) = -K(u_x - w_x)\n\\end{align}\n\\clearpage\n\\section*{Analytical treatment - 11/13/2018}\nIn order to obtain an analytical solution for the problem initially we consider g = 0. The boundary limits of the 1-dimensional problem assume the length of the domain spanning form x=-L to x=+L. The stresses are taken to be zero at each of the boundaries. We begin by implementing a trial solution for $u_x$ and $w_x$.\n\\begin{align}\nu_x = Ax + Bsinh \\Big ( \\frac{x}{\\sigma} \\Big )\\\\\nw_x = Cx + Dsinh \\Big ( \\frac{x}{\\sigma} \\Big )\n\\end{align}\nFor estimating the values of A,B,C,D we assume additionally p=q=0. \nRewriting (12):\n\\begin{align}\n2\\nu\\frac{\\partial^{2}}{\\partial x^2}\\Big ( Ax + Bsinh\\Big ( \\frac{x}{\\sigma} \\Big ) \\Big ) = K \\Big ( Ax + Bsinh \\Big ( \\frac{x}{\\sigma} \\Big ) - Cx - Dsinh \\Big ( \\frac{x}{\\sigma} \\Big )  \\Big )\\\\\n2\\nu\\frac{\\partial}{\\partial x} \\Big ( A + \\frac{B}{\\sigma}cosh\\Big ( \\frac{x}{\\sigma} \\Big ) \\Big ) = K \\Big ((A - C)x + (B - D)sinh\\Big ( \\frac{x}{\\sigma} \\Big ) )\\\\\n2\\nu\\frac{B}{\\sigma^2} sinh\\Big ( \\frac{x}{\\sigma} \\Big ) = K \\Big ( (A - C)x + (B - D)sinh\\Big ( \\frac{x}{\\sigma} \\Big )\\Big )\n\\end{align}\nand (13)\n\\begin{align}\n2\\mu(x)\\frac{\\partial^{2}}{\\partial x^2}\\Big ( Cx + Dsinh\\Big ( \\frac{x}{\\sigma} \\Big ) \\Big ) = -K \\Big ( Ax + Bsinh \\Big ( \\frac{x}{\\sigma} \\Big ) - Cx - Dsinh \\Big ( \\frac{x}{\\sigma} \\Big )  \\Big )\\\\\n2\\mu(x)\\frac{\\partial}{\\partial x} \\Big ( C + \\frac{D}{\\sigma}cosh\\Big ( \\frac{x}{\\sigma} \\Big ) \\Big ) = -K \\Big ((A - C)x + (B - D)sinh\\Big ( \\frac{x}{\\sigma} \\Big ) )\\\\\n2\\mu(x)\\frac{D}{\\sigma^2} sinh\\Big ( \\frac{x}{\\sigma} \\Big ) = -K \\Big ( (A - C)x + (B - D)sinh\\Big ( \\frac{x}{\\sigma} \\Big )\\Big )\n\\end{align}\nFrom (20) and (23) we have:\n\\begin{align}\nD = -\\frac{\\nu}{\\mu(x)} B\n\\end{align}\nComparing coefficients of hyperbolic sine terms we see that (20) and (23) is satisfied only when the coefficient of the linear term is zero. Therefore,\n\\begin{align}\nA = C\n\\end{align}\nHence the length constant\\footnote{This might also be a variable since $\\mu$ is a function of x for the problem} $\\sigma$ has the value\\footnote{$\\mu(x)$ is also written as $\\mu$}\n\\begin{equation}\n\\begin{aligned}\n\\sigma = \\sqrt{\\frac{2\\nu\\mu}{K(\\nu + \\mu)}}\n\\end{aligned}\n\\end{equation}\nTo obtain the values of the unknown parameters B and C, we impose boundary conditions. At the edge (x = $\\pm$L) we have, normal stresses $\\tau_{ix}$ and $\\tau_{ex}$ as zero. As a result we get,\n\\begin{align}\nC + \\frac{D}{\\sigma}cosh\\Big ( \\frac{L}{\\sigma} \\Big ) = 0\\\\\nA + \\frac{B}{\\sigma}cosh\\Big ( \\frac{L}{\\sigma} \\Big ) = -\\frac{T}{2\\nu}\n\\end{align} \nSolving (27) and (28) using (24)-(26) we have:\n\\begin{align}\nA = C = -\\frac{T}{2(\\nu + \\mu)}\\\\\nB = -\\frac{T}{2\\nu}\\Big ( \\frac{\\mu}{\\nu + \\mu} \\Big )\\frac{\\sigma}{cosh(\\frac{L}{\\sigma})}\\\n, D = \\frac{T}{2(\\mu + \\nu)}\\frac{\\sigma}{cosh(\\frac{L}{\\sigma})}\n\\end{align}\nUsing this we get the intra and extracellular displacement in terms of T as:\n\\begin{align}\nu_x = -\\frac{T}{2(\\nu + \\mu)} \\Big ( x + \\frac{\\mu}{\\nu} \\sigma \\frac{sinh(\\frac{x}{\\sigma})}{cosh(\\frac{L}{\\sigma})}\\Big )\\\\\nw_x = -\\frac{T}{2(\\nu + \\mu)} \\Big ( x - \\sigma \\frac{sinh(\\frac{x}{\\sigma})}{cosh(\\frac{L}{\\sigma})}\\Big )\n\\end{align}\nSince $\\mu$ is variable for the problem we now write it as: $\\mu = \\mu_0 + gx$. Remaining derivation of $u_x$ and $w_x$ along with its derivatives and double derivatives has been attached separately. \n\\newpage\n\\section*{Analytical treatment - 12/22/2018}\nWe are considering plane stress conditions for the model. Nothing depends on y. \n\\begin{align*}\n\\tau_{exx} = -q + 2\\mu\\epsilon_{exx} \\\\\n\\tau_{eyy} = -q \\\\\n\\tau_{ezz} = -q + 2\\mu\\epsilon_{ezz} \\\\\n\\end{align*}\nSince $\\tau_{ezz}$  = 0 so\n\\begin{align*}\n-q + 2\\mu\\epsilon_{ezz} = 0\n\\end{align*}\nor, $q=2\\mu\\epsilon_{ezz}$, but, $\\epsilon_{exx} + \\epsilon_{ezz} = 0$, so \n\\begin{align*}\nq=-2\\mu\\epsilon_{exx}\n\\end{align*}\nTherefore the stresses along the principal directions can be written as:\n\\begin{align*}\n\\tau_{exx} = 4\\mu\\epsilon_{exx} \\hspace{0.5cm} \\tau_{eyy} = 2\\mu\\epsilon_{exx}\\hspace{0.5cm} \\tau_{ezz}=0\\hspace{0.5cm}\\tau_{exy}=0\n\\end{align*}\nThe final partial differential form of the equations look like: \n\\begin{align*}\n\\frac{\\partial\\tau_{exx}}{\\partial x} + \\frac{\\partial\\tau_{exy}}{\\partial y} = -K(u_x - w_x) \\\\\nor, \\hspace{0.5cm}4\\Big ( \\frac{\\partial \\mu}{\\partial x}\\epsilon_{exx}  + \\mu \\frac{\\partial \\epsilon_{exx}}{\\partial x}\\Big ) = -K(u_x - w_x)\n\\end{align*}\nFor the intracellular layer the principal stress is the same except that Tension T along the principal direction (x) is also taken into account. Thus the final set of working equations are, considering $\\mu$ has a gradient along x and $\\nu$ is a constant for the problem. \n\\[\\boxed{\\!\\begin{aligned}\n\t&4\\mu\\frac{\\partial^2 w}{\\partial x^2} + 4\\frac{\\partial w}{\\partial x}\\frac{\\partial \\mu}{\\partial x} = -K(u_x - w_x) \\\\\n &4\\nu\\frac{\\partial^2 u}{\\partial x^2} = K(u_x - w_x)\n\\end{aligned}\n}\n\\]\n\\section*{$\\mu$ = constant }\n\\[\\boxed{\\!\\begin{aligned}\n\t&4\\mu\\frac{\\partial^2 w}{\\partial x^2} = -K(u_x - w_x) \\\\\n\t&4\\nu\\frac{\\partial^2 u}{\\partial x^2} = K(u_x - w_x)\n\t\\end{aligned}\n}\n\\]\nThe stresses are taken to be zero at each of the boundaries. We begin by implementing a trial solution for $u_x$ and $w_x$.\n\\begin{align*}\nu_x = Ax + Bsinh \\Big ( \\frac{x}{\\sigma} \\Big )\\\\\nw_x = Cx + Dsinh \\Big ( \\frac{x}{\\sigma} \\Big )\n\\end{align*}\nFor estimating the values of A,B,C,D we assume: \nRewriting (12):\n\\begin{align*}\n4\\nu\\frac{\\partial^{2}}{\\partial x^2}\\Big ( Ax + Bsinh\\Big ( \\frac{x}{\\sigma} \\Big ) \\Big ) = K \\Big ( Ax + Bsinh \\Big ( \\frac{x}{\\sigma} \\Big ) - Cx - Dsinh \\Big ( \\frac{x}{\\sigma} \\Big )  \\Big )\\\\\n4\\nu\\frac{\\partial}{\\partial x} \\Big ( A + \\frac{B}{\\sigma}cosh\\Big ( \\frac{x}{\\sigma} \\Big ) \\Big ) = K \\Big ((A - C)x + (B - D)sinh\\Big ( \\frac{x}{\\sigma} \\Big ) )\\\\\n4\\nu\\frac{B}{\\sigma^2} sinh\\Big ( \\frac{x}{\\sigma} \\Big ) = K \\Big ( (A - C)x + (B - D)sinh\\Big ( \\frac{x}{\\sigma} \\Big )\\Big )\n\\end{align*}\nand (13)\n\\begin{align*}\n4\\mu(x)\\frac{\\partial^{2}}{\\partial x^2}\\Big ( Cx + Dsinh\\Big ( \\frac{x}{\\sigma} \\Big ) \\Big ) = -K \\Big ( Ax + Bsinh \\Big ( \\frac{x}{\\sigma} \\Big ) - Cx - Dsinh \\Big ( \\frac{x}{\\sigma} \\Big )  \\Big )\\\\\n4\\mu(x)\\frac{\\partial}{\\partial x} \\Big ( C + \\frac{D}{\\sigma}cosh\\Big ( \\frac{x}{\\sigma} \\Big ) \\Big ) = -K \\Big ((A - C)x + (B - D)sinh\\Big ( \\frac{x}{\\sigma} \\Big ) )\\\\\n4\\mu(x)\\frac{D}{\\sigma^2} sinh\\Big ( \\frac{x}{\\sigma} \\Big ) = -K \\Big ( (A - C)x + (B - D)sinh\\Big ( \\frac{x}{\\sigma} \\Big )\\Big )\n\\end{align*}\nFrom (20) and (23) we have:\n\\begin{align}\nD = -\\frac{\\nu}{\\mu} B\n\\end{align}\nComparing coefficients of hyperbolic sine terms we see that (20) and (23) is satisfied only when the coefficient of the linear term is zero. Therefore,\n\\begin{align}\nA = C\n\\end{align}\nLength constant $\\sigma$ remains as: \n\\begin{align}\n\t\\sigma = \\sqrt{\\frac{4\\nu\\mu}{K(\\nu + \\mu)}}\n\\end{align}\nTo obtain the values of the unknown parameters B and C, we impose boundary conditions. At the edge (x = $\\pm$L) we have, normal stresses $\\tau_{ix}$ and $\\tau_{ex}$ as zero. As a result we get,\n\\begin{align}\nC + \\frac{D}{\\sigma}cosh\\Big ( \\frac{L}{\\sigma} \\Big ) = 0\\\\\nA + \\frac{B}{\\sigma}cosh\\Big ( \\frac{L}{\\sigma} \\Big ) = -\\frac{T}{4\\nu}\n\\end{align}\nSolving the equations using given by (33) - (35) and using them in (36) and (37) we have: \nSolving (27) and (28) using (24)-(26) we have:\n\\begin{align}\nA = C = -\\frac{T}{4(\\nu + \\mu)}\\\\\nB = -\\frac{T}{4\\nu}\\Big ( \\frac{\\mu}{\\nu + \\mu} \\Big )\\frac{\\sigma}{cosh(\\frac{L}{\\sigma})}\\\n, D = \\frac{T}{4(\\mu + \\nu)}\\frac{\\sigma}{cosh(\\frac{L}{\\sigma})}\n\\end{align}\nUsing this we get the intra and extracellular displacement in terms of T as:\n\\begin{align}\nu_x = -\\frac{T}{4(\\nu + \\mu)} \\Big ( x + \\frac{\\mu}{\\nu} \\sigma \\frac{sinh(\\frac{x}{\\sigma})}{cosh(\\frac{L}{\\sigma})}\\Big )\\\\\nw_x = -\\frac{T}{4(\\nu + \\mu)} \\Big ( x - \\sigma \\frac{sinh(\\frac{x}{\\sigma})}{cosh(\\frac{L}{\\sigma})}\\Big )\n\\end{align}\n\\section*{$\\mu = \\mu_0$ + gx }\nFor this condition the set of equations which we need to consider for obtaining an analytical solution are: \n\\begin{align}\n4\\mu\\frac{\\partial^2 w}{\\partial x^2} + 4\\frac{\\partial w}{\\partial x}\\frac{\\partial \\mu}{\\partial x} = -K(u_x - w_x) \\\\\n4\\nu\\frac{\\partial^2 u}{\\partial x^2} = K(u_x - w_x)\n\\end{align}\nReplacing unknowns term by term from the previous solutions and given data we have an expression for the difference between $u_x$ and $w_x$: \n%\\begin{align*}\n\\[\\boxed{\\frac{-4}{K}(\\mu_0 + gx )\\frac{\\partial^2}{\\partial x^2}\\Bigg( -\\frac{T}{4(\\nu + \\mu)} \\Big ( x - \\sigma \\frac{sinh(\\frac{x}{\\sigma})}{cosh(\\frac{L}{\\sigma})}\\Big )\\Bigg) - \\frac{4g}{K}\\frac{\\partial}{\\partial x}\\Bigg( -\\frac{T}{4(\\nu + \\mu)} \\Big ( x - \\sigma \\frac{sinh(\\frac{x}{\\sigma})}{cosh(\\frac{L}{\\sigma})}\\Big )\\Bigg)}\\]\n%\\end{align*}\n\\section*{Mathematica Code}\nThe code below returns the value of the above expression. f(x) returns the value of $u_x - w_x$\n\\begin{lstlisting}\nsigma[x_] = ((4*(muz + gx)*nu)/(K*(nu+muz+gx)))^0.5\ng[x_] = -(Tx/(4*(nu+muz+gx))) + ((T*sigma[x_]*sinh[x/sigma[x]])/(4*(nu+muz+gx)*cosh[L/sigma[x]]))\ng'[x_]\ng''[x_]\nf[x_] = (-4/K)*(muz+gx)*g''[x] + (-4*g/K)*g'[x] \n\\end{lstlisting}\n\\newpage\n\\section*{Analytical treatment - 12/28/2018}\nWe assume the trial solution for $u_x$ and $w_x$ for the given problem as: \n\\begin{align}\nu_x = Ax + Bsinh \\Big ( \\frac{x}{\\sigma} \\Big )\\\\\nw_x = Cx + Dsinh \\Big ( \\frac{x}{\\sigma} \\Big )\n\\end{align}\nAdditionally the extracellular gradient is taken as $\\mu = \\mu_0 + gx$. The final set of working equations are taken as: \n\\[\\boxed{\\!\\begin{aligned}\n\t&4\\mu\\frac{\\partial^2 w}{\\partial x^2} + 4\\frac{\\partial w}{\\partial x}\\frac{\\partial \\mu}{\\partial x} = -K(u_x - w_x) \\\\\n\t&4\\nu\\frac{\\partial^2 u}{\\partial x^2} = K(u_x - w_x)\n\t\\end{aligned}\n}\n\\]\nReplacing the values for u and w with that of (44)-(45) we have\n\\begin{align}\n4(\\mu_0 + gx)\\frac{D}{\\sigma^2}sinh(\\frac{x}{\\sigma}) + 4g(C + \\frac{D}{\\sigma}cosh(\\frac{x}{\\sigma})) = -K \\Big ( (A - C)x + (B - D)sinh\\Big ( \\frac{x}{\\sigma} \\Big )\\Big )\\\\\n4\\nu\\frac{B}{\\sigma^2}sinh(\\frac{x}{\\sigma}) = K \\Big ( (A - C)x + (B - D)sinh\\Big ( \\frac{x}{\\sigma} \\Big )\\Big )\n\\end{align}\nUsing boundary conditions on $\\epsilon_{exx} = 0$ at x=L (Since we have $\\tau_{exx} = 0$ at x=$\\pm$L )\n\\begin{align*}\n\\frac{\\partial w}{\\partial x} = 0\\\\\n\\therefore \\hspace{0.5cm}\nC + \\frac{D}{\\sigma}cosh(\\frac{x}{\\sigma}) = 0\\\\\n\\end{align*}\nPlugging the above result in equation (46) and (47) we have: \n\\begin{align*}\n(\\mu_0 + gx)\\frac{D}{\\sigma^2}sinh(\\frac{L}{\\sigma}) = -\\nu\\frac{B}{\\sigma^2}sinh(\\frac{L}{\\sigma})\n\\end{align*}\n\\[\\boxed{\nD = -\\frac{\\nu}{\\mu_0 + gL} B\n}\n\\]\nFor finding relation between A and C we manipulate equation (47) with the relationship between B and D\n\\begin{align*}\n4\\nu\\frac{B}{\\sigma^2}sinh(\\frac{x}{\\sigma}) = K \\Big ( (A - C)x + (B - D)sinh\\Big ( \\frac{x}{\\sigma} \\Big )\\Big )\\\\\n\\textit{or,} \\hspace{0.35cm} 4\\nu\\frac{B}{\\sigma^2}sinh\\Big (\\frac{x}{\\sigma} \\Big ) - K (B - D)sinh\\Big ( \\frac{x}{\\sigma} \\Big ) = K (A - C)x \\\\\n\\textit{or,} \\hspace{0.35cm} sinh \\Big( \\frac{x}{\\sigma}\\Big ) \\Big( \\frac{4\\nu B}{\\sigma^2 } - K(B + \\frac{B\\nu}{\\mu_0 + gL}) \\Big ) = K (A - C)x \n\\end{align*}\n\\[\\boxed{\nA - C = \\frac{B}{Kx} sinh \\Big( \\frac{x}{\\sigma}\\Big ) \\Big( \\frac{4\\nu }{\\sigma^2 } - K(1+ \\frac{\\nu}{\\mu_0 + gL}) \\Big )\n}\n\\]\nTo obtain the values of the unknown parameters B and C, we impose boundary conditions. At the edge (x = $\\pm$L) we have, normal stresses $\\tau_{ix}$ and $\\tau_{ex}$ as zero. Rewriting it, we have,\n\\begin{align}\nC + \\frac{D}{\\sigma}cosh\\Big ( \\frac{L}{\\sigma} \\Big ) = 0\\\\\nA + \\frac{B}{\\sigma}cosh\\Big ( \\frac{L}{\\sigma} \\Big ) = -\\frac{T}{4\\nu}\n\\end{align}\nSubtracting (49) - (48) we have: \n\\begin{align}\n(A - C) + (\\frac{B - D}{\\sigma})cosh\\Big ( \\frac{L}{\\sigma} \\Big ) = -\\frac{T}{4\\nu}\n\\end{align}\nPlugging in A - C and B,D relationship in the equation we have: \n\\begin{align*}\n\\frac{B}{Kx} sinh \\Big( \\frac{x}{\\sigma}\\Big ) \\Big( \\frac{4\\nu }{\\sigma^2 } - K(1+ \\frac{\\nu}{\\mu_0 + gL}) \\Big ) + \\frac{1}{\\sigma}\\Big (B + \\frac{B\\nu}{\\mu_0 + gL}\\Big )cosh\\Big ( \\frac{L}{\\sigma} \\Big ) = -\\frac{T}{4\\nu}\n\\end{align*}\nHowever we have to replace x in the above equation with L as we have been using boundary conditions in (48) - (49). The final form is: (taking out B common in the expression)\n\\begin{align}\n\\textbf{B} = -\\frac{T}{4\\nu} \\Bigg ( \\frac{1}{sinh \\Big( \\frac{L}{\\sigma}\\Big ) \\Big ( \\frac{4\\nu}{\\sigma^2 L} - \\frac{K}{L} (1+ \\frac{\\nu}{\\mu_0 + gL}) \\Big ) + cosh\\Big ( \\frac{L}{\\sigma} \\Big ) \\Big (  \\frac{1}{\\sigma} (1+ \\frac{\\nu}{\\mu_0 + gL}) \\Big )} \\Bigg)\n\\end{align}\nThe value of D can be computed using its relationship with B which is $D = -\\frac{\\nu}{\\mu_0 + gL} B$\n\\begin{align}\n\\textbf{D} = \\frac{T}{4(\\mu_0 + gL)} \\Bigg ( \\frac{1}{sinh \\Big( \\frac{L}{\\sigma}\\Big ) \\Big ( \\frac{4\\nu}{\\sigma^2 L} - \\frac{K}{L} (1+ \\frac{\\nu}{\\mu_0 + gL}) \\Big ) + cosh\\Big ( \\frac{L}{\\sigma} \\Big ) \\Big (  \\frac{1}{\\sigma} (1+ \\frac{\\nu}{\\mu_0 + gL}) \\Big )} \\Bigg)\n\\end{align}\nThe value of C can be computed from (48) as $C = -\\frac{D}{\\sigma}cosh\\Big ( \\frac{L}{\\sigma} \\Big )$\n\\begin{align}\n\\textbf{C} = -\\frac{T}{4(\\mu_0 + gL)} \\Bigg ( \\frac{cosh\\Big ( \\frac{L}{\\sigma} \\Big )}{sinh \\Big( \\frac{L}{\\sigma}\\Big ) \\Big ( \\frac{4\\nu}{\\sigma L} - \\frac{K \\sigma}{L} (1+ \\frac{\\nu}{\\mu_0 + gL}) \\Big ) + cosh\\Big ( \\frac{L}{\\sigma} \\Big ) \\Big ( 1+ \\frac{\\nu}{\\mu_0 + gL} \\Big )} \\Bigg)\n\\end{align}\nThe value of A can be obtained from (49) as $A = -\\frac{B}{\\sigma}cosh\\Big ( \\frac{L}{\\sigma} \\Big ) -\\frac{T}{4\\nu}$\n\\begin{align*}\n\\textbf{A} = -\\frac{T}{4(\\nu)} \\Bigg ( 1 - \\frac{cosh\\Big ( \\frac{L}{\\sigma} \\Big )}{sinh \\Big( \\frac{L}{\\sigma}\\Big ) \\Big ( \\frac{4\\nu}{\\sigma L} - \\frac{K \\sigma}{L} (1+ \\frac{\\nu}{\\mu_0 + gL}) \\Big ) + cosh\\Big ( \\frac{L}{\\sigma} \\Big ) \\Big ( 1+ \\frac{\\nu}{\\mu_0 + gL} \\Big )} \\Bigg)\n\\end{align*}\n\\begin{align}\n\\therefore \\hspace{0.35cm}\n\\textbf{A} = -\\frac{T}{4\\nu} \\Bigg ( \\frac{sinh \\Big( \\frac{L}{\\sigma}\\Big ) \\Big ( \\frac{4\\nu}{\\sigma L} - \\frac{K \\sigma}{L} (1+ \\frac{\\nu}{\\mu_0 + gL}) \\Big ) + cosh\\Big ( \\frac{L}{\\sigma} \\Big ) \\Big ( \\frac{\\nu}{\\mu_0 + gL} \\Big )}{sinh \\Big( \\frac{L}{\\sigma}\\Big ) \\Big ( \\frac{4\\nu}{\\sigma L} - \\frac{K \\sigma}{L} (1+ \\frac{\\nu}{\\mu_0 + gL}) \\Big ) + cosh\\Big ( \\frac{L}{\\sigma} \\Big ) \\Big ( 1+ \\frac{\\nu}{\\mu_0 + gL} \\Big )} \\Bigg)\n\\end{align}\nThus the value of of $u_x$ is: \n\\begin{align*}\nu_x = -\\frac{T}{4(\\nu)} \\Bigg ( \\frac{sinh \\Big( \\frac{L}{\\sigma}\\Big ) \\Big ( \\frac{4\\nu}{\\sigma L} - \\frac{K \\sigma}{L} (1+ \\frac{\\nu}{\\mu_0 + gL}) \\Big ) + cosh\\Big ( \\frac{L}{\\sigma} \\Big ) \\Big ( \\frac{\\nu}{\\mu_0 + gL} \\Big )}{sinh \\Big( \\frac{L}{\\sigma}\\Big ) \\Big ( \\frac{4\\nu}{\\sigma L} - \\frac{K \\sigma}{L} (1+ \\frac{\\nu}{\\mu_0 + gL}) \\Big ) + cosh\\Big ( \\frac{L}{\\sigma} \\Big ) \\Big ( 1+ \\frac{\\nu}{\\mu_0 + gL} \\Big )} \\Bigg)\\textbf{x} \\\\ -\\frac{T}{4\\nu} \\Bigg ( \\frac{1}{sinh \\Big( \\frac{L}{\\sigma}\\Big ) \\Big ( \\frac{4\\nu}{\\sigma^2 L} - \\frac{K}{L} (1+ \\frac{\\nu}{\\mu_0 + gL}) \\Big ) + cosh\\Big ( \\frac{L}{\\sigma} \\Big ) \\Big (  \\frac{1}{\\sigma} (1+ \\frac{\\nu}{\\mu_0 + gL}) \\Big )} \\Bigg) \\textbf{sinh} \\Big ( \\frac{x}{\\sigma} \\Big )\\\\\n\\end{align*}\nThe value of $w_x$ is: \n\\begin{align*}\nw_x = -\\frac{T}{4(\\mu_0 + gL)} \\Bigg ( \\frac{cosh\\Big ( \\frac{L}{\\sigma} \\Big )}{sinh \\Big( \\frac{L}{\\sigma}\\Big ) \\Big ( \\frac{4\\nu}{\\sigma L} - \\frac{K \\sigma}{L} (1+ \\frac{\\nu}{\\mu_0 + gL}) \\Big ) + cosh\\Big ( \\frac{L}{\\sigma} \\Big ) \\Big ( 1+ \\frac{\\nu}{\\mu_0 + gL} \\Big )} \\Bigg)\\textbf{x} + \\\\\n\\frac{T}{4(\\mu_0 + gL)} \\Bigg ( \\frac{1}{sinh \\Big( \\frac{L}{\\sigma}\\Big ) \\Big ( \\frac{4\\nu}{\\sigma^2 L} - \\frac{K}{L} (1+ \\frac{\\nu}{\\mu_0 + gL}) \\Big ) + cosh\\Big ( \\frac{L}{\\sigma} \\Big ) \\Big (  \\frac{1}{\\sigma} (1+ \\frac{\\nu}{\\mu_0 + gL}) \\Big )} \\Bigg)\\textbf{sinh} \\Big ( \\frac{x}{\\sigma} \\Big )\n\\end{align*}\n\\section*{Issues}\nNeed some insights for calculating the length constant $\\sigma$\n\\newpage\n\\section*{Perturbation Theory - 1/22/2019}\nThe following result has been obtained using first order perturbation to obtain approximate analytical solutions.\\\\\n\\begin{align*}\nu_0 = -\\frac{T}{4(\\nu + \\mu)} \\Big ( x + \\frac{\\mu}{\\nu} \\sigma \\frac{sinh(\\frac{x}{\\sigma})}{cosh(\\frac{L}{\\sigma})}\\Big )\\\\\nw_0 = -\\frac{T}{4(\\nu + \\mu)} \\Big ( x - \\sigma \\frac{sinh(\\frac{x}{\\sigma})}{cosh(\\frac{L}{\\sigma})}\\Big )\\\\\nu_1 = c_1 e^{\\sqrt{\\phi_1}x} + c_2 e^{-\\sqrt{\\phi_1}x} - \\frac{\\phi_2 e^{-\\sqrt{\\phi_1}x}(e^{2\\sqrt{\\phi_1}x}Ei(-\\sqrt{\\phi_1 x}) + Ei(\\sqrt{\\phi_1 x}) - 2e^{\\sqrt{\\phi_1}x} ln(x))}{2\\phi_1}\\\\\nw_1 = c_3 ln(x)\\\\\nEi(x) = -\\int_{-x}^{\\infty} \\frac{e^{-t}}{t} dx\n\\end{align*}\nwhere Ei(x) is the Exponential Integral Function. \nHowever this is different from the proposed guess for  $u_1$ which involved  consisting of sinh and cosh terms only. \n\\begin{thebibliography}{9}\n\t\\bibitem{roth2012}\n\tBradley J Roth\n\t\\textit{The Mechanical Bidomain Model: A Review}\n\tISRN Tissue Eng. 2013\n\t\\bibitem{roth2015}\n\t Sharma, Kharananda; Al-Asuoad, Nofe; Shillor, Meir; Roth, Bradley J.\n\t\\textit{Intracellular, extracellular, and membrane forces in remodeling and mechanotransduction: The mechanical bidomain model}\n\tJournal of Coupled Systems and Multiscale Dynamics, Volume 3, Number 3, September 2015, pp. 200-207(8)\n\\end{thebibliography}\n\\end{document}\n ", "meta": {"hexsha": "432eff263843d7cbfc56055fc0b001a730f36a42", "size": 22312, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "notebook/notebook.tex", "max_stars_repo_name": "auddya/mechanicalBidomainModel", "max_stars_repo_head_hexsha": "c62cc7e5bd8335418b960347500063c7c07c4062", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-02-06T16:58:26.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-06T16:58:26.000Z", "max_issues_repo_path": "notebook/notebook.tex", "max_issues_repo_name": "auddya/mechanicalBidomainModel", "max_issues_repo_head_hexsha": "c62cc7e5bd8335418b960347500063c7c07c4062", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebook/notebook.tex", "max_forks_repo_name": "auddya/mechanicalBidomainModel", "max_forks_repo_head_hexsha": "c62cc7e5bd8335418b960347500063c7c07c4062", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.81769437, "max_line_length": 747, "alphanum_fraction": 0.630916099, "num_tokens": 8800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.32000976579500295}}
{"text": "\\subsection{gammapy.modeling}\n\\label{ssec:gammapy-modeling}\n\\todo{Quentin Remy}\n\ngammapy.modeling contains all the functionality related to modeling and fitting\ndata. This includes spectral, spatial and temporal model classes, as well as\nthe fit and parameter API.\n\n\\subsubsection{Models}\n\\label{ssec:models}\n\nThe models are grouped into the following categories:\n\n\\begin{itemize}\n\t\\item SpectralModel: models to describe spectral shapes of sources\n\t\\item SpatialModel: models to describe spatial shapes (morphologies) of sources\n\t\\item TemporalModel: models to describe temporal flux evolution of sources, such as\n\t      light and phase curves\n\n\\end{itemize}\n\nThe models follow a naming scheme which contains the category as a suffix to\nthe class name.\n\nThe  Spectral Models include a special class of Normed models, which have a\ndimension-less normalisation. These spectral models feature a norm parameter\ninstead of amplitude and are named using the NormSpectralModel suffix. They\nmust be used along with another spectral model, as a multiplicative correction\nfactor according to their spectral shape. They can be typically used for\nadjusting template based models, or adding a EBL correction to some analytic\nmodel. The analytic Spatial models are all normalized such as they integrate to\nunity over the sky but the template Spatial models may not, so in that special\ncase they have to be combined with a NormSpectralModel.\n\nThe SkyModel is a factorised model that combine the spectral, spatial and\ntemporal model components (by default the spatial and temporal components are\noptional). SkyModel objects represents additive emission components, usually\nsources or diffuse emission, although a single source can also be modeled by\nmultiple components. To handle list of multiple SkyModel components, Gammapy\nhas a Models class.\n\nThe model gallery provides a visual overview of the available models in\nGammapy. Most of the analytic models  commonly used in gamma-ray astronomy are\nbuilt-in. We also offer a wrapper to radiative models implemented in the Naima\npackage~\\cite{naima}. The modeling framework can be easily extended with\nuser-defined models. For example agnpy models that describe leptonic radiative\nprocesses in jetted Active Galactic Nuclei (AGN) can wrapped into\ngammapy~\\citep[see section3.5 of ][]{2021arXiv211214573N} .\n\n\\begin{figure}\n\t\\import{code-examples/generated/}{gp_models}\n\t\\caption{Using gammapy.modeling.models}\n\t\\label{fig*:minted:gp_models}\n\\end{figure}\n\n\\subsubsection{Fit}\n\\label{ssec:fit}\n\nThe Fit class provides methods to fit i.e., optimise parameters and estimate\nparameter errors and correlations. It interfaces with a Datasets object, which\nin turn is connected to a Models object containing the model parameters in its\nParameters object. Models can be unique for a given dataset, or contribute to\nmultiple datasets and thus provide links, allowing e.g., to do a joint fit to\nmultiple IACT datasets, or to a joint IACT and \\textit{Fermi}-LAT dataset. Many\nexamples are given in the tutorials.\n\nThe Fit class provides a uniform interface to multiple fitting backends:\n“minuit”~\\citep{iminuit}, “scipy”,~\\citep{2020SciPy-NMeth}, and\n“sherpa”~\\citep{sherpa-2005,sherpa-2011}. Note that, for now, covariance matrix\nand errors are computed only for the fitting with MINUIT. However depending on\nthe problem other optimizers can better perform, so sometimes it can be useful\nto run a pre-fit with alternative optimization methods. In future we plan to\nextend the supported Fit backend, including for example MCMC solutions.\n\\footnote{a prototype is available in gammapy-recipes,\n\t\\url{https://gammapy.github.io/gammapy-recipes/_build/html/notebooks/mcmc-sampling-emcee/mcmc_sampling.html}\n}\n", "meta": {"hexsha": "d50edf3e29e78fc1cf98fd4d7205766f313e3b1b", "size": 3727, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/text/2-package-subsections/modeling.tex", "max_stars_repo_name": "bkhelifi/gammapy-v1.0-paper", "max_stars_repo_head_hexsha": "edb61c092ad90b523282be363150ed6013af0a43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/text/2-package-subsections/modeling.tex", "max_issues_repo_name": "bkhelifi/gammapy-v1.0-paper", "max_issues_repo_head_hexsha": "edb61c092ad90b523282be363150ed6013af0a43", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/text/2-package-subsections/modeling.tex", "max_forks_repo_name": "bkhelifi/gammapy-v1.0-paper", "max_forks_repo_head_hexsha": "edb61c092ad90b523282be363150ed6013af0a43", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.4025974026, "max_line_length": 109, "alphanum_fraction": 0.8073517574, "num_tokens": 878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.31989712377313917}}
{"text": "%Prelim, Chapter 1\n% by Rachel Slaybaugh\n\n\\chapter{Introduction}\n\\label{sec:Chp1}\n\nNuclear technology plays an important role in society, particularly within the field of energy generation. More nuclear reactors are being constructed, existing designs are being refined, and new plants are being developed. For progress to continue in these areas, the modeling of nuclear systems must also progress. \n\nThe neutron transport equation describes ``where all the neutrons are'' in a nuclear system. The more accurately this is known, the more accurately new systems can be developed. This means that solutions to the transport equation are needed in high-fidelity in all parts of phase space. Very large computers are now available to perform such high-fidelity calculations, but most existing solution methods are not able to take full advantage of new computer architectures and converge slowly for some kinds of problems.  \n\nThe goal of this research is to accelerate transport calculations with methods that use new computers fully and effectively, facilitating the design of better nuclear systems. Three complimentary methods have been implemented that accomplish this goal. In the chapters that follow this one, background information, past work, mathematics and implementation, and results will be discussed for each method in turn. \n\nThis introductory chapter is intended to provide the foundation of this document. The types of neutron transport problems that have been, are, and could be solved are discussed first, including why such problems matter. This is followed by a presentation of the transport equation and its discretization. Finally, the way each method contributes to meeting the overall goal of this work is outlined. \n\n%--------------------------------------------------------------------------------\n%--------------------------------------------------------------------------------\n\\section{Motivation}\nThe problems typically of interest in the nuclear engineering community are of large scale, with many independent variables representing the pertinent nuclear physics. Some of the most important applications are finding reactor core power distributions for cooling and safety needs, determining the criticality state of the reactor, and predicting isotope depletion. All of these applications require high-resolution neutron flux spectra, where flux is the number of particles per unit length squared per second in some portion of phase of space. Commercial light water reactors can have core heights of three to four meters and contain anywhere from 700 to 1200 fuel bundles \\cite{Fennern2006}. Geometrically large shielding applications are commonly of interest as well. To obtain the needed quantities with sufficient precision and resolution, the size of required calculations can become quite large. \n\nSolving the full steady-state transport equation, which depends on location, energy, and solid angle, is computationally intensive. For a reasonable discretization of reactor-type calculations, $10^{8}$ coupled algebraic equations could easily be required. In the past, such large calculations were generally intractable because of computer hardware limitations: lack of memory and processing capability. There was simply not enough space to store all of the required data, and it would take too long to conduct the number of floating point operations (flops) needed. Calculations with fine enough discretizations to get high-resolution answers were impossible to perform using the transport equation \\cite{Duderstadt1976}. \n\nAccordingly, simplifying approximations were used to solve problems in practice. Approximations include modeling reactor geometries in one or two dimensions rather than three; approximating neutron sources as isotropic; approximating neutron scattering as isotropic; eliminating the angular component of the solution through the diffusion approximation (discussed in Appendix \\ref{sec:AppendixA}); physically truncating geometries by taking advantage of geometric symmetries or near symmetries, particularly for reactor cores with repeated lattice structures; and suppressing energy dependence or using very few energy groups \\cite{Duderstadt1976}.\n\nWhile all such approximations can be appropriate and give good results in some situations, they are generally not as accurate as solving the full, finely discretized transport equation. The way the nuclear industry has compensated for approximate answers is by building conservative margins into designs by using thicker shields, lower operating powers, larger safety margins, and so on. All of this costs money, which is of crucial import since economic competitiveness may be the largest barrier to the construction of new nuclear plants and, correspondingly, provision of emissions-free energy. Having higher-fidelity neutron fluxes could influence design bases and have a meaningful impact on current reactor operations and new reactor designs. \n\n%--------------------------------------------------------------------------------\n\\subsection{Problems of Interest}\nTo get more accurate fluxes, typical transport problems today are three-dimensional, have up to thousands $\\times$ thousands $\\times$ thousands of mesh points, use up to $\\sim$150 energy groups, include accurate expansions of scattering terms, and are solved over many directions. Some examples of problems solved recently using discrete ordinates codes on parallel machines are shown next. The exact meaning of the expansions will become clear in the next section.\n\\begin{itemize}\n  \\item In 1998, 30 million unknowns\\footnote{In each example the number of unknowns assumes one spatial unknown per cell; some spatial discretizations result in more than one spatial unknown per cell.}: a 3-D time dependent shielding problem where a 10 $\\times$ 10 $\\times$ 10 cm innermost region containing water and a uniform source is surrounded by 10 cm of iron, which is surrounded by 30 more cm of water. Three energy groups, a 50 $\\times$ 50 $\\times$ 50 Cartesian mesh, $S_{8}$ scattering quadrature, $P_{0}$ scattering expansion, and the adaptive weighted diamond difference method were used \\cite{Alcouffe1998}.\n  \\item In 2004, 1.62 million unknowns: a cylinder with a 3.5 cm radius and 9 cm length containing layers of boron-10, water, and highly enriched uranium was solved with 13,500 cells, $S_{4}$ Chebyshev-Legendre quadrature, and five energy groups \\cite{Warsa2004a}. \n  \\item In 2010, 78.5 billion unknowns: a Pressurized Water Reactor (PWR)-900 with two groups, a 578 $\\times$ 578 $\\times$ 700 mesh, using $S_{16}$ level-symmetric quadrature, and with $P_{0}$ scattering was solved \\cite{Davidson2010}. \n\\end{itemize}\n%\nThe size and scope of problems of interest have been increasing as larger computer resources have made it possible to solve them. \n\nThe next phase of challenging problems are even more highly refined. High-fidelity, coupled, multi-physics calculations are the new ``grand challenge'' problems for reactor analysis. Of particular interest in nuclear systems is feedback between neutronics and thermal-hydraulics. A recent INCITE grant was awarded to spatially quantify data uncertainties in 3-D Boiling Water Reactor assembly calculations. When neutron transport is coupled to a fluid dynamics code it is important to know whether or not homogenizing the materials in the subchannels being analyzed will have a large impact. Such uncertainty studies will require spatial meshes exceeding 500 million elements \\cite{Evans2009a}. Calculations of this detail present the next generation of challenges for computational neutronics. \n\n%--------------------------------------------------------------------------------\n\\subsection{Enabling Technology}\nNuclear transport computation began in the age of run tapes and punch cards with widely used codes being written in advanced programming languages such as FORTRAN IV \\cite{Fortran1998}. Computer technology has evolved quickly and radically since that time. Now there are machines like Jaguar, which consists of two partitioned machines, the Cray XT4 and the Cray XT5. Jaguar has 84 XT4 cabinets containing 7,832 quad-core Opteron 1354 \"Budapest\" processors, each with eight gigabytes of DDR2-800 memory. The 200 XT5 cabinets have 37,376 six-core Opteron 2435 \"Istanbul\" processors with 16 gigabytes of memory per node. The machine has a total of 362 terabytes of high-speed memory \\cite{Sciences2010}. A table of machine parameters can be seen in Figure~\\ref{fig:jaguar}. \n\n\\begin{figure}[!h]\n  \\begin{center}\n    \\includegraphics [width=0.55\\textwidth, height=0.35\\textheight ] {jaguarSpecs09}\n  \\end{center}\n  \\caption{Jaguar Machine Specifications \\cite{Sciences2010}}\n  \\label{fig:jaguar}\n\\end{figure}\n\nWhile the fastest computer in the world in 2010 may not be the best example of what is standard, machines on which parallel codes can be run are widely available and are becoming faster over time. Access to such machines has changed the landscape of the types of neutron transport problems that can be solved practically. \n\nWhenever an equation is being mathematically approximated, errors can be introduced that are inherent in the approximation. These errors are present regardless of machine roundoff, phase space discretization, etc. and cannot be changed without changing the approximation. Accepting this mathematical limit as a given, the factor that can be changed to improve calculations is machine architecture. This means that the quality of calculations for a given method is ultimately limited by computers. The research presented here is intended to provide methods that can take full advantage of these new computers, pushing back the frontier of limiting calculations.\n\n%--------------------------------------------------------------------------------\n%--------------------------------------------------------------------------------\n\\section{The Transport Equation}\nTo understand the methods that were developed for this work and how they will enable the use of leadership-class hardware, the mathematical details of the transport equation must be discussed first. This section does this for neutrons in steady-state systems. \n\nNeutrons can have many different kinds of interactions that influence a system's behavior. These interactions are described by cross sections, which reflect the likelihood of a particular interaction occurring and are given in units of inverse length. Of particular interest is the total cross section, $\\Macro$, which includes all possible interactions; the scattering cross section, $\\Macro_{s}$, where scattering can change the momentum and kinetic energy of a neutron; and the fission cross section, $\\Macro_{f}$.   \n\nFission is the process through which a nucleus splits into (typically two) smaller atoms. \\\\Through this process a relatively large amount of energy is released along with several neutrons. These neutron are available to go on to cause other fissions, creating a chain reaction. The quantity $\\nu$ is the average number of neutrons released per fission. Most of the energy released from fission is kinetic, which creates the heat used to make electricity \\cite{Lewis1993}.  \n\nIf fission is occurring, it is often of interest to know the asymptotic behavior of the system. A reactor is called ``critical'' if the chain reaction is self-sustaining and time-independent. If the system is not in equilibrium then the asymptotic neutron distribution, or the fundamental mode, will grow or decay exponentially over time. A convenient way to capture this behavior is to assume $\\nu$ can be adjusted to obtain a time-independent solution by replacing it with $\\frac{\\nu}{k}$, where $k$ is the parameter expressing the deviation from critical. \n\nThis substitution changes the transport equation into an eigenvalue problem. A spectrum of eigenvalues can be found, but at long times only the non-negative solution corresponding to the largest real eigenvalue will dominate. The eigenproblem can be written as:\n%\n\\begin{align}\n   [\\hat{\\Omega} \\cdot \\nabla + \\Macro(\\vec{r}, E)] \\psi(\\vec{r}, \\hat{\\Omega}, E)  &=  \\int dE' \\int d\\hat{\\Omega'} \\:\\Macro_{s}(\\vec{r}, E' \\to E, \\hat{\\Omega'} \\cdot \\hat{\\Omega}) \\psi(\\vec{r}, \\hat{\\Omega'}, E') \\nonumber \\\\\n&+\\frac{ \\chi(E)}{k} \\int dE' \\:\\nu \\Macro_{f}(\\vec{r}, E') \\int d\\hat{\\Omega'} \\:\\psi(\\vec{r}, \\hat{\\Omega'}, E') \\:,\n\\label{eq:neutron transport}\n\\end{align}\n%\n\\noindent where the quantities are at location $\\vec{r}$, traveling in directions $\\hat{\\Omega}$, and at energy E and are defined as:\n\\begin{list}{}{\\hspace{2em}}\n  \\item $\\psi(\\vec{r}, \\hat{\\Omega}, E)$ is the angular neutron flux in neutrons per unit length squared per steradian and expresses where all the neutrons are in phase space, \n  \\item $\\chi(E)$ is the fission spectrum and specifies the energy distribution of neutrons born from fission,\n  \\item $k$ can be thought of as the asymptotic ratio of the number of neutrons in one generation to the number in the next \\cite{Lewis1993}.\n\\end{list}\n\nIf fission is not present the transport equation becomes a fixed source rather than eigenvalue problem. The term containing $k$ is replaced by an external source, $q_{ex}(\\vec{r}, \\hat{\\Omega}, E)$, and the equation becomes a standard linear system. \n\nA brief aside about some properties of the transport equation will aid in understanding the challenge of finding solution techniques that work in all cases. In a void, the transport equation is like a hyperbolic wave equation. For highly-scattering regions where $\\Macro_{s}$ is close to $\\Macro$, the equation becomes elliptic for the steady-state case. If the scattering is forward-peaked then the equation is parabolic. All of these classes of equations have different solution strategies. The equation is linear, though non-linearities can be introduced if temperature-dependence of cross sections and other similar physics are considered \\cite{Adams2002}.  The non-linear considerations are beyond the scope of this work and only the linear case is considered here.\n\nTo numerically solve Equation \\eqref{eq:neutron transport} it is discretized in space, angle, and energy. This work uses the multigroup approximation, the scattering term is expanded in Legendre polynomials, and discrete ordinates are used to treat direction of neutron travel. There are many spatial differencing methods available, the discussion of which are beyond the scope of this document as the proposed work is not dependent upon the spatial discretization employed. To ensure the new methods apply to the most general cases it will be assumed that the matrices resulting from discretization are not necessarily symmetric. \n\n%--------------------------------------------------------------------------------\n\\subsection{Multigroup Approximation}\nThe first variable to discretize is energy. In the multigroup approximation, the energy range of interest is broken into $G$ groups. The neutron flux is constant in energy over each group. The groups are ordered such that the highest energy group bound corresponds with $g = 0$, meaning group 1 is defined over $E_{1}$ to $E_{0}$, and the lowest energy bound corresponds with $g = G$. On this grid the group angular flux is defined as: \n%\n\\begin{equation}\n  \\psi_{g}(\\vec{r},\\hat{\\Omega}) = \\int_{g} dE \\:\\psi(\\vec{r}, \\hat{\\Omega}, E) = \\int_{E_{g}}^{E_{g-1}}dE \\:\\psi(\\vec{r}, \\hat{\\Omega}, E) \\:.\n\\end{equation}\n\nJustification of this definition comes from assuming the angular flux within each energy group can be approximated by the product of the group flux and a known function: $\\psi(\\vec{r}, \\hat{\\Omega}, E) \\approx f(E)  \\psi_{g}(\\vec{r},\\hat{\\Omega})$ for $E_{g} < E \\le E_{g-1}$. The function is normalized for a specific group $g$ such that $\\int_{g' = g} dE \\:f(E) = 1$ and $\\int_{g' \\ne g} dE \\:f(E) = 0$. The details of $f$ are isotope-dependent and can be garnered from nuclear data \\cite{Lewis1993}. With this notation, group quantities are defined as:\n\n\\indent $\\Macro_{g}(\\vec{r}) = \\int_{g} dE \\:\\Macro(\\vec{r}, E) f(E)$, \\\\\n\\indent $\\nu \\Macro_{fg}(\\vec{r}) = \\int_{g} dE \\:\\nu \\Macro_{f}(\\vec{r}, E) f(E)$, \\\\ \n\\indent $\\Macro_s^{gg'}(\\vec{r}, \\hat{\\Omega'} \\cdot \\hat{\\Omega}) = \\int_{g} dE \\:\\int_{g'} dE' \\:\\Macro_{s}(\\vec{r}, E' \\to E, \\hat{\\Omega'} \\cdot \\hat{\\Omega})  f(E')$ is the scattering from $g'$ into $g$, \\\\\n\\indent $\\chi_{g} = \\int_{g} dE \\:\\chi(E)$, and \\\\\n\\indent $q^{e}_{g}(\\vec{r}, \\vOmega) = \\int_{g} dE \\:q_{ex}(\\vec{r}, \\hat{\\Omega}, E)$.\n\n\\noindent Using these terms, the eigenvalue form of Equation \\eqref{eq:neutron transport} can be rewritten for each group $g$ as seen in \\eqref{eq:group-transport} \\cite{Lewis1993}. Using more energy groups represents the physics in the cross sections more accurately, but also increases the cost of a calculation in terms of both operations and storage. \n% \n\\begin{align}\n   [\\hat{\\Omega} \\cdot \\nabla + \\Macro_{g}(\\vec{r})] \\psi_{g}(\\vec{r}, \\hat{\\Omega})  &=  \\sum_{g'=1}^{G} \\int d\\hat{\\Omega'} \\:\\Macro_s^{gg'}(\\vec{r}, \\hat{\\Omega'} \\cdot \\hat{\\Omega}) \\psi_{g'}(\\vec{r}, \\hat{\\Omega'})  \\nonumber \\\\\n&+ \\frac{\\chi_{g}}{k}   \\sum_{g'=1}^{G} \\nu \\Macro_{fg'}(\\vec{r}) \\int d\\hat{\\Omega'} \\:\\psi_{g'}(\\vec{r}, \\hat{\\Omega'}) \n\\label{eq:group-transport}\n\\end{align}\n\n%--------------------------------------------------------------------------------\n\\subsection{Scattering Discretization}\nIn Equation \\eqref{eq:group-transport} the scattering cross section is a complicated function of angle. Simplifying this term will make the system easier to solve. Because of rotational symmetry of nuclear collisions, $\\Macro_{s}$ is only a function of the cosine between the incoming and outgoing angles. This allows the scattering cross section to be written as a series expansion of Legendre polynomials as follows, where the the spatial variable has been supressed:\n%\n\\begin{equation}\n  \\sigg{}(\\vOmega' \\cdot \\vOmega) = \\sum_{l=0}^{N} \\frac{2l+1}{4\\pi} P_{l}(\\vOmega' \\cdot \\vOmega)\\sigg{l} \\:.\n\\end{equation}\n\nThe addition theorem of spherical harmonics can be used to evaluate the Legendre function, $P_{l}(\\vOmega' \\cdot \\vOmega)$, with spherical harmonic terms, $Y_{lm}$. These can then be expanded into real and imaginary components. The imaginary components must be zero since scattering must be real. All of this gives:\n%\n\\begin{equation}\n  P_l(\\vOmega' \\cdot \\vOmega) = \\frac{4\\pi}{2l+1} \\Bigl[ Y^e_{l0}(\\vOmega) Y^e_{l0}(\\vOmega') + \\sum_{m=1}^l \\bigl( Y^e_{lm}(\\vOmega) Y^e_{lm}(\\vOmega') + Y^o_{lm}(\\vOmega) Y^o_{lm}(\\vOmega') \\bigr) \\Bigr]\\:.\n\\end{equation}\n%\nThe $Y^e$ and $Y^o$ terms obey the following orthogonality relationships: $\\int d\\vOmega \\:Y^{e}_{lm}(\\vOmega)Y^{e}_{l'm'}(\\vOmega) = \\frac{1}{2}(1 + \\delta_{m0})\\delta_{ll'}\\delta_{mm'}$ and $\\int d\\vOmega \\:Y^{o}_{lm}(\\vOmega)Y^{o}_{l'm'}(\\vOmega) = \\frac{1}{2}(1 - \\delta_{m0})\\delta_{ll'}\\delta_{mm'}$. The spherical harmonics therefore form an orthonormal basis in which the Legendre polynomials are expressed \\cite{Evans2009}, \\cite{Lewis1993}. \n\nBy putting all of this information together, the scattering source can be expressed as: \n%\n\\begin{equation}\n  q^g_{s} (\\vec{r}, \\vOmega) = \\sum_{g'=1}^G \\sum_{l=0}^N \\sigg{l}(\\vec{r}) \\Bigl[ Y^e_{l0}(\\vOmega) \\evenp_{l0}(\\vec{r}) + \\sum_{m=1}^l \\bigl( Y^e_{lm}(\\vOmega) \\evenp_{lm}(\\vec{r}) + Y^o_{lm}(\\vOmega) \\oddp_{lm}(\\vec{r}) \\bigr) \\Bigr]\\:.\n   \\label{eq:mg-scattering-source}\n\\end{equation}\n%\nIn Equation \\eqref{eq:mg-scattering-source} two terms, called the even and odd flux moments, have been used:\n%\n\\begin{alignat}{3}\n  \\even_{lm} &= \\int_{4\\pi} d\\vOmega' \\:Y^e_{lm}(\\vOmega') \\psi^g(\\vOmega') \\:, \\quad& m\\ge 0\\:,\\qquad \\text{even} \\:, \\label{eq:even-flux}\\\\\n  %\n  \\odd_{lm} &= \\int_{4\\pi} d\\vOmega' \\:Y^o_{lm}(\\vOmega')\\psi^g(\\vOmega') \\:, \\quad& m>0 \\:,  \\qquad \\text{odd} \\label{eq:odd-flux} \\:.\n\\end{alignat}\n%\nThe external source can be similarly discretized if desired, making the two sources consistent with one another. The full details of these expansions and bases can be found in \\cite{Evans2009}. \n\nThe multigroup, anisotropic scattering source found in Equation \\eqref{eq:mg-scattering-source} is characterized by the order of Legendre scattering, $P_{N}$. For a given Legendre expansion there are $(N + 1)^{2}$ flux moments. Using more moments represents scattering more accurately, but increases the cost of calculation \\cite{Evans2009}.  \n\n%--------------------------------------------------------------------------------\n\\subsection{Discrete Ordinates Approximation}\nThe next area of phase space to discretize is direction. The discrete ordinates or \\Sn approximation is a collocation method that is used to express the transport equation on a discrete set of $n$ ordinates, where the ordinates are described by angles and represent direction of neutron travel. A collocation method represents a continuous function on a finite set of collocation points using a linear combination of basis functions. The approximate solution must satisfy the differential equation at those collocation points \\cite{Heath2002}. \n\nFor the transport equation, the basis functions are the angular fluxes along specific directions and the collocation points are the angle sets. The linear combination is done by weighting the basis functions using a quadrature set. \n\nTo implement this, the transport equation is written for neutrons traveling in $d\\vOmega$ about direction $\\vOmega_{a}$. Now $\\psi^{g}_{a}$ can be defined as $\\psi^{g}(\\vOmega_{a})$, and the angular flux can be related to the scalar flux as $\\phi^{g} = \\sum_{a=1}^{n}\\psi^{g}_{a}w_{a}$. Using these terms, including the discretized scattering source and suppressing spatial dependence, Equation \\eqref{eq:group-transport} becomes:\n%\n\\begin{align}\n \\bigl( \\vOmega_{a} \\cdot \\nabla + \\Macro_{g} \\bigr) \\psig_{a} = \\sum_{g' = 1}^{G} \\sum_{l=0}^{N} \\sigg{l} \\bigl[ Y^{e}_{l0}(\\vOmega_{a}) \\evenp_{l0} &+ \\sum_{m=1}^{l} \\bigl( Y^{e}_{lm}(\\vOmega_{a}) \\evenp_{lm} + Y^{o}_{lm}(\\vOmega_{a}) \\oddp_{lm} \\bigr) \\bigr] \\nonumber \\\\\n &+ \\frac{\\chi^{g}}{k} \\sum_{g'=1}^{G} \\nu \\Macro_{f}^{g'}\\phi^{g'} \\:,\n  \\label{eq:mg-sn-transport}\n\\end{align}\n\nThe quadrature weights, $w_{a}$, are defined such that $\\int_{4 \\pi} d\\vOmega =  \\sum_{a=1}^{n}w_{a} = 4 \\pi$. One of the choices in the \\Sn approximation is what quadrature set to use. The number of unknowns contributed by discretization of direction is determined by the quadrature set. For example, level-symmetric quadrature gives $n = N(N+2)$ unknowns for an \\Sn approximation. The scalar flux is also collocated on the ordinates using the desired quadrature set to linearly combine the angular flux basis functions \\cite{Evans2009}. This results in the flux moments:\n%\n\\begin{align}\n  \\even_{lm} &= \\sum_{a=1}^{n}Y^e_{lm}(\\vOmega'_a)\\psi^g_a w_a\\:,\n  \\label{eq:even-flux-quad-int}\\\\\n  \\odd_{lm} &= \\sum_{a=1}^{n}Y^o_{lm}(\\vOmega'_a)\\psi^g_a w_a\\:.\n  \\label{eq:odd-flux-quad-int}\n\\end{align}\n\n%--------------------------------------------------------------------------------\n\\subsection{Operator Form}\nNow that the transport equation has been discretized, it can be expressed in operator notation. Using the operator form of the transport equation will facilitate the presentation of the solution techniques discussed in the remainder of this document. In general, uppercase bolded letters will indicate matrices and lowercase italicized letters will indicate vectors and scalars. The following operators are used to express the transport equation:\\\\\n%\n\\indent $\\mathbf{L} = \\vOmega \\cdot \\nabla + \\Macro$ is the transport operator, \\\\\n\\indent $\\mathbf{M}$ is the operator that converts harmonic moments into discrete angles, \\\\\n\\indent $\\mathbf{S}$ is the scattering matrix, \\\\\n\\indent $f$ contains the fission source, $\\nu \\Macro_{f}$; $\\mathbf{F} =\\mathbf{\\chi} f^{T}$, \\\\ \n\\indent $\\mathbf{D} = \\ve{M^{T}}\\ve{W} = \\sum_{a=1}^{n}Y^{e/o}_{lm}w_{a}$ is the discrete-to-moment operator. \n\nWith this notation Equation \\eqref{eq:mg-sn-transport} can be written as \\eqref{eq:operator-form}; it can be formulated as a fixed source problem by replacing the fission term with $\\ve{M}q_{e}$. This has two unknowns, the angular flux and the moments, which are related by the discrete-to-moment operator as seen in Equation \\eqref{eq:moments}.\n%\n\\begin{align}\n  \\mathbf{L} \\psi &= \\mathbf{MS}\\phi + \\frac{1}{k}\\mathbf{MF}\\phi \\label{eq:operator-form}\\\\\n  \\phi &= \\mathbf{D}\\psi \n  \\label{eq:moments}\n\\end{align}\nThe typical strategy for solving Equation \\eqref{eq:operator-form} is to combine it with \\eqref{eq:moments} and form one equation involving only the moments, where $Q$ is comprised of the fixed or fission source: \n\\begin{equation}\n   (\\ve{I} - \\ve{DL}^{-1}\\ve{MS})\\phi = Q \\:.\n\\end{equation}  \nThis is solved for $\\phi$ from which $\\psi$ can be determined at the end of the calculation.\n\nThe size of the operators can be defined in terms of the granularity of discretization: \\\\\n%\n\\indent $G$ = number of energy groups, \\\\\n\\indent $t$ = number of moments, \\\\\n\\indent $n$ = number of angular unknowns, \\\\\n\\indent $c$ = number of cells, \\\\\n\\indent $u$ = number of unknowns per cell, which is determined by spatial discretization. \\\\\n%\nThese can be combined to define $a = G \\times n \\times c \\times u$ and $f = G \\times t \\times c \\times u$. Using $a$ and $f$, Equation \\eqref{eq:operator-form} can be presented in terms of operator size: $(a \\times a)(a \\times 1) = (a \\times f) (f \\times f) (f \\times 1) + (a \\times f) (f \\times f) (f \\times 1)$. The index variables, their meaning, and their ranges are shown in Table \\ref{table:index}. \n%\n\\begin{table}[!h]\n\\caption{Meaning and Range of Indices Used in Transport Discretization}\n\\begin{center}\n\\begin{tabular}{l c c c c}\n\\hline\nVariable & Symbol & First & Last \\\\[0.5ex]\n\\hline\nEnergy & g & 1 & G \\\\\nSolid Angle & a & 1 & n \\\\\nSpace & suppressed & n/a & n/a \\\\\nLegendre moment ($P_{N}$) & $l$ & 0 & N \\\\\nSpherical harmonic moment ($Y$) & m & 0 & $l$ \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\label{table:index}\n\\end{table}\n%\n\nThe structures of the vectors and matrices are shown in the next few equations as this will make some of the proposed methods easier to understand and visualize \\cite{Evans2009}. The angular flux vector is explicitly written first, where for each discrete angle, $a$, and energy group, $g$, the set of angular fluxes, $ \\psi^g_a$, includes all spatial unknowns.\n%\n \\begin{align}\n    \\psi &=     \\begin{pmatrix}\n    [\\psi]_{1} & [\\psi]_2 & \\cdots & [\\psi]_g & \\cdots [\\psi]_{G} \n  \\end{pmatrix}^T  \\:, \\qquad \\text{and} \\nonumber \\\\\n  %\n    [\\psi]_g &= \\begin{pmatrix}\n    \\psi^g_1 & \\psi^g_2& \\cdots & \\psi^g_a & \\cdots \\psi^g_n \n  \\end{pmatrix}^T \\:.  \\nonumber \n\\end{align}\n%\n\\begin{alignat}{2}\n  \\mathbf{M} &=    \\begin{pmatrix}\n      [\\ve{M}]_{11} & 0 & 0 & \\cdots & 0 \\\\\n      0 & [\\ve{M}]_{22} & 0 & \\cdots & 0 \\\\\n      0 & 0 & [\\ve{M}]_{33} & \\cdots & 0 \\\\\n      \\vdots & \\vdots & \\vdots & \\ddots   & \\vdots \\\\\n      0 & 0 & 0 & \\cdots & [\\ve{M}]_{GG} \\\\\n    \\end{pmatrix} \\nonumber  \\:,& \\qquad\n    %\n  \\mathbf{S}  =     \\begin{pmatrix}\n      [\\ve{S}]_{11} & [\\ve{S}]_{12} & [\\ve{S}]_{13} & \\cdots &\n      [\\ve{S}]_{1G} \\\\\n      [\\ve{S}]_{21} & [\\ve{S}]_{22} & [\\ve{S}]_{23} & \\cdots &\n      [\\ve{S}]_{2G} \\\\\n      [\\ve{S}]_{31} & [\\ve{S}]_{32} & [\\ve{S}]_{33} & \\cdots &\n      [\\ve{S}]_{3G} \\\\\n      \\vdots & \\vdots & \\vdots & \\ddots & \\vdots \\\\\n      [\\ve{S}]_{G1} & [\\ve{S}]_{G2} & [\\ve{S}]_{G3} & \\cdots &\n      [\\ve{S}]_{GG}\n    \\end{pmatrix} \\nonumber  \\:,\n \\end{alignat}\n %\n \\begin{alignat}{2}\n      \\mathbf{F}  &=     \\begin{pmatrix}\n     \\chi^{1}[\\nu\\Macro_{f}]^{1} &\\chi^{1}[\\nu\\Macro_{f}]^{2} & \\cdots &\n      \\chi^{1}[\\nu\\Macro_{f}]^{G} \\\\\n      \\chi^{2}[\\nu\\Macro_{f}]^{1} &\\chi^{2}[\\nu\\Macro_{f}]^{2} & \\cdots &\n      \\chi^{2}[\\nu\\Macro_{f}]^{G}\\\\\n      \\vdots & \\vdots & \\ddots & \\vdots \\\\\n      \\chi^{G}[\\nu\\Macro_{f}]^{1} &\\chi^{G}[\\nu\\Macro_{f}]^{2} & \\cdots &\n      \\chi^{G}[\\nu\\Macro_{f}]^{G}\\\\\n    \\end{pmatrix} \\:, \\nonumber & \\qquad\n    %\n  [\\ve{S}]_{gg'} = \\begin{pmatrix}\n    \\sigg{0} & 0 & \\cdots & 0  \\\\\n    0 & \\sigg{1} & \\cdots & 0 \\\\\n    \\vdots & 0 & \\ddots  & \\vdots \\\\\n     0 & 0 & \\cdots & \\sigg{N}\n  \\end{pmatrix}\\:, \\nonumber\n \\end{alignat}\n    %\n\\begin{equation}    \n   [\\ve{M}]_{gg} = \\begin{pmatrix}\n    \\Ye{00}{1} & \\Ye{10}{1} & \\Yo{11}{1} & \\Ye{11}{1} & \n    \\Ye{20}{1} & \\cdots & \\Yo{NN}{1} & \\Ye{NN}{1} \\\\\n    \\Ye{00}{2} & \\Ye{10}{2} & \\Yo{11}{2} & \\Ye{11}{2} & \n    \\Ye{20}{2} & \\cdots & \\Yo{NN}{2} & \\Ye{NN}{2} \\\\\n    \\Ye{00}{3} & \\Ye{10}{3} & \\Yo{11}{3} & \\Ye{11}{3} & \n    \\Ye{20}{3} & \\cdots & \\Yo{NN}{3} & \\Ye{NN}{3} \\\\\n    \\vdots     & \\vdots     & \\vdots     & \\vdots     & \n    \\vdots     &  \\ddots    & \\vdots     & \\vdots     \\\\\n    \\Ye{00}{n} & \\Ye{10}{n} & \\Yo{11}{n} & \\Ye{11}{n} & \n    \\Ye{20}{n} & \\cdots & \\Yo{NN}{n} & \\Ye{NN}{n}\n  \\end{pmatrix}\\:. \\nonumber \\\\\n\\end{equation}\n\n\\noindent Note that $[\\ve{M}]_{11} = [\\ve{M}]_{22} =  \\hdots = [\\ve{M}]_{GG} = [\\ve{M}]$. These are written with subscripts to simplify the visualization of which blocks correspond to which equations and multiply which other blocks. \n\n%--------------------------------------------------------------------------------\n\\subsection{Solution Procedure}\nOnce the matrices are multiplied together, a series of single-group equations that are each only a function of space and angle result:\n%\n\\begin{equation}\n  \\begin{aligned}\n    \\ve{L}[\\psi]_1 &= [\\ve{M}]\\bigl([\\ve{S}]_{11}[\\phi]_1 + \n    [\\ve{S}]_{12}[\\phi]_2 + \\ldots + [\\ve{S}]_{1G}[\\phi]_G\\bigr) + \n    \\frac{1}{k}[\\ve{M}]\\sum_{i=1}^{G}[\\ve{F}]_{1i}[\\phi]_{i} \\:, \\\\\n    %%\n    \\ve{L}[\\psi]_2 &= [\\ve{M}]\\bigl([\\ve{S}]_{21}[\\phi]_1 + \n    [\\ve{S}]_{22}[\\phi]_2 + \\ldots + [\\ve{S}]_{2G}[\\phi]_G\\bigr) + \n     \\frac{1}{k}[\\ve{M}]\\sum_{i=1}^{G}[\\ve{F}]_{2i}[\\phi]_{i} \\:, \\\\\n    %%\n    &\\vdots\\\\\n    %%\n    \\ve{L}[\\psi]_G &= [\\ve{M}]\\bigl([\\ve{S}]_{G1}[\\phi]_1 + \n    [\\ve{S}]_{G2}[\\phi]_2 + \\ldots + [\\ve{S}]_{GG}[\\phi]_G\\bigr) + \n     \\frac{1}{k}[\\ve{M}]\\sum_{i=1}^{G}[\\ve{F}]_{Gi}[\\phi]_{i} \\:.\n  \\end{aligned}\n  \\label{eq:group-equations}\n\\end{equation}\n%\nEach ``within-group'' equation is solved for that group's flux. If the groups are coupled together, as they often are, then multiple ``multigroup'' solves over the coupled portion of the energy range may be required. If the eigenvalue is desired an additional ``eigenvalue'' solve is needed as well \\cite{Evans2009}. The details of these steps will be discussed later as they relate to the new methods.  \n\n\n%--------------------------------------------------------------------------------\n%--------------------------------------------------------------------------------\n\\section{Meeting the Goal}\nThe fully discretized steady-state transport equation can become very large when trying to solve ``grand challenge'' types of problems. The continued improvement of computational resources has enabled the invention of massively parallel codes designed to work on leadership-class computers. The goal of this work is to develop and implement methods that will accelerate transport calculations by efficiently taking advantage of cutting-edge computer architectures. \n\nThe code being used in this work is Denovo \\cite{Evans2009}, a massively parallel discrete ordinates code being developed at Oak Ridge National Laboratory (ORNL). The code allows multiple combinations of spatial discretizations, quadrature sets, and solution methodologies. Denovo is three-dimensional; uses a non-uniform, structured, Cartesian grid; has a flexible front end; and is capable of writing and reading input parameters rapidly for high performance computing. \n\nAt the outset of this work, Denovo could be decomposed for parallel computation in five of the six dimensions of phase space over which the steady-state transport equation is solved. The nature of the decomposition dictated how many cores Denovo could use efficiently. Studies presented in Chapter \\ref{sec:Chp2} illustrate that this number of cores was not sufficient to solve real problems of interest. \n\nThe original suite of solvers in Denovo included Source Iteration (SI) and Krylov methods as within group solvers, Gauss Seidel (GS) as a multigroup solver, and power iteration (PI) as an eigenvalue solver. These solvers have some significant limitations in many cases. Each method and its associated challenges will be described in detail in following chapters. \n\nAcceleration of Denovo has been accomplished by implementing three complimentary solution strategies. The first is a multigroup solver that allows Denovo to be decomposed in energy for fixed source problems such that multigroup solves can be parallelized in the energy dimension. This addition lets Denovo take advantage of many more cores without significantly degrading the scaling. The \\emph{multigroup Krylov solver} also converges more quickly than Gauss Seidel. This work is discussed in Chapter~\\ref{sec:Chp2}.\n\nThe second strategy was to add an eigenvalue method with properties that can be superior to power iteration, particularly for loosely coupled problems. \\emph{Rayleigh Quotient Iteration} (RQI) applies a shift to the equations that improves the eigenvalue convergence properties. The shift also increases the degree of effective group-to-group coupling. The multigroup Krylov solver enables RQI because it solves coupled groups efficiently and decomposes those coupled groups for energy parallelization. The details of this work are discussed in Chapter~\\ref{sec:Chp3}.\n\nThe third step was to add a new physics-based preconditioner that is a multigrid method in energy. This capitalizes on the energy decomposition added by the first method. Since energy groups can be treated independently, they can be combined and re-separated in a multigrid fashion very easily. The preconditioner is applicable to both fixed source problems and eigenvalue calculations, and it reduces the number of iterations required for convergence. The \\emph{multigrid-in-energy preconditioner} is discussed in Chapter~\\ref{sec:Chp4}.\n\nFast and scalable codes are necessary for solving truly large and challenging neutron transport problems. This work developed methods that accelerate an existing transport code by allowing it to scale to hundreds of thousands of cores and converge in fewer iterations than its previous methods, thus enabling the development of new and useful nuclear energy systems. These methods may also be beneficial for the larger computational community.\n\n\\separatorpage{}  \n", "meta": {"hexsha": "3eb087588178ae7a03e76f14e9e48995bf5852e2", "size": 34465, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "intro.tex", "max_stars_repo_name": "rachelslaybaugh/RNS_Thesis", "max_stars_repo_head_hexsha": "d931afe50367e1d91b952a9d570c286e0b7f6d42", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2016-01-07T09:06:04.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-16T17:13:56.000Z", "max_issues_repo_path": "intro.tex", "max_issues_repo_name": "rachelslaybaugh/RNS_Thesis", "max_issues_repo_head_hexsha": "d931afe50367e1d91b952a9d570c286e0b7f6d42", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "intro.tex", "max_forks_repo_name": "rachelslaybaugh/RNS_Thesis", "max_forks_repo_head_hexsha": "d931afe50367e1d91b952a9d570c286e0b7f6d42", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-24T17:15:21.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-24T17:15:21.000Z", "avg_line_length": 102.2700296736, "max_line_length": 905, "alphanum_fraction": 0.7109821558, "num_tokens": 9196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.31989712377313917}}
{"text": "\\documentclass{article}\n\\usepackage{fuzz}\n\\usepackage{url}\n\\usepackage{listings}\n\n\\lstset{numbers=left, language={}, basicstyle={\\small\\ttfamily}, tabsize=4, captionpos=b}\n\n\\title{Core SHACL Formal Semantics}\n\\author{Arthur Ryman, {\\tt arthur.ryman@gmail.com}}\n\\date{\\today}\n\n\\begin{document}\n\\bibliographystyle{acm}\n\n\\maketitle\n\n\n\\section{Introduction}\n\\label{sec-introduction}\nThe W3C RDF Data Shapes Working Group \\cite{w3c:shapeswg} is developing SHACL, a new language for describing constraints on RDF graphs.\nA semantics for Core SHACL has been proposed \\cite{iovka:core-shacl}, hereafter referred to as the {\\em semantics document}.\nThe proposed semantics includes an abstract syntax, inference rules, and a definition of typing which allows for certain kinds of recursion.\nThe semantics document uses precise mathematical language, but is informal in the sense that it is not written in a formal specification language\nand therefore cannot benefit from tools such as type-checkers.\n\nThis document provides a formal translation of the semantics document into Z Notation  \\cite{spivey:zrm}.\nThe \\LaTeX\\ source for this article has been type-checked using the \\fuzz\\ type-checker \\cite{spivey:fuzz}.\nWe hope that the exercise of formalizing and type-checking the semantics document will help to improve its quality. \n\n\\section{Basic RDF Concepts}\n\\label{sec-basic-rdf-concepts}\nThis section formalizes some basic RDF concepts.\nWe reuse some formal definitions given in \\cite{arthur:recursion}, modifying the identifiers to match those given in the semantics document.\n\n\\subsection{$TERM$}\nLet $TERM$ be the set of all RDF {\\em terms}.\n\\begin{zed}\n\t[TERM]\n\\end{zed}\n\n\\subsection{$Iri$, $Blank$, and $Lit$}\nThe set of all RDF terms is partitioned into IRIs, blank nodes, and literals.\n\\begin{axdef}\n\tIri, Blank, Lit: \\power TERM\n\\where\n\t\\langle Iri, Blank, Lit \\rangle \\partition TERM\n\\end{axdef}\n\n\\subsection{$IRI$}\nThe semantics document introduces the term $Iri$, but it uses the term $IRI$ in the definitions of the abstract syntax.\nWe treat $IRI$ as a synonym for $Iri$.\n\\begin{zed}\n\tIRI == Iri\n\\end{zed}\n\n\\subsection{$Triple$}\nAn RDF triple is an ordered triple of RDF terms referred to as the subject, predicate, and object.\n\\begin{zed}\n\tTriple == \\{~ s, p, o:TERM | s \\notin Lit \\land p \\in IRI ~\\}\n\\end{zed}\n\\begin{itemize}\n\\item The subject is not a literal.\n\\item The predicate is an IRI.\n\\end{itemize}\n\n\\subsection{$subject$, $predicate$, and $object$}\nIt is convenient to define generic functions that select the first, second, or third component of a Cartesian product of three sets.\n\\begin{zed}\n\tfst[X,Y,Z] == (\\lambda x:X; y:Y; z:Z @ x~)\n\\also\n\tsnd[X,Y,Z] == (\\lambda x:X; y:Y; z:Z @ y~)\n\\also\n\ttrd[X,Y,Z] == (\\lambda x:X; y:Y; z:Z @ z~)\n\\end{zed}\n\nThe subject, predicate, and object of an RDF triple are the terms that appear in the corresponding positions.\n\\begin{zed}\n\tsubject == (\\lambda t:Triple @ fst(t) ~)\n\\also\n\tpredicate == (\\lambda t:Triple @ snd(t) ~)\n\\also\n\tobject == (\\lambda t:Triple @ trd(t) ~)\n\\end{zed}\n\n\\subsection{$Graph$}\nAn RDF graph is a finite set of RDF triples.\n\\begin{zed}\n\tGraph == \\finset Triple\n\\end{zed}\n\n\\subsection{$subjects$, $predicates$, and $objects$}\nThe subjects, predicates, and objects of a graph are the sets of RDF terms that appear in the corresponding positions of its triples.\n\\begin{zed}\n\tsubjects == (\\lambda g: Graph @ \\{~ t:g @ subject(t) ~\\} ~)\n\\also\n\tpredicates == (\\lambda g: Graph @ \\{~ t:g @ predicate(t) ~\\} ~)\n\\also\n\tobjects == (\\lambda g: Graph @ \\{~ t:g @ object(t) ~\\} ~)\n\\end{zed}\n\n\\subsection{$nodes$}\nThe nodes of an RDF are its subjects and objects.\n\\begin{zed}\n\tnodes == (\\lambda g: Graph @ subjects(g) \\cup objects(g) ~)\n\\end{zed}\n\n\\subsection{$PointedGraph$}\nA pointed graph is a graph and a distinguished node in the graph.\nThe distinguished node is variously referred to as the start, base, or focus node of the pointed graph, depending on the context.\n\\begin{zed}\n\tPointedGraph == \\{~ g: Graph; n: TERM | n \\in nodes(g) ~\\}\n\\end{zed}\n\n\\section{Abstract Syntax}\n\\label{sec-abstract-syntax}\nThis section contains a translation of the abstract syntax into Z.\nThe approach used here is to interpret each term or expression that appears in the abstract syntax as\na mathematical set that is isomorphic to the set of abstract syntax tree fragments denoted by the term or expression.\nCare has been taken to preserve the exact spelling and case of each term so that there is a direct correspondence\nbetween the abstract syntax and Z.\nFor example, the term {\\tt Schema} is interpreted as the set $Schema$.\n\nThere is a Z definition for each abstract syntax term that appears on the left-hand side of the definition operator ({\\tt ::=}).\nThe order in which these terms appear in the semantics document has been preserved in this document.\n\nA sequence of two or more abstract syntax terms is interpreted as the Cartesian product of the corresponding sets, i.e.\n{\\tt A B} is interpreted as $A \\cross B$.\n\nThe abstract syntax Kleene star ({\\tt *}) and plus ({\\tt +}) operators are interpreted as sequence ($\\seq$) \nand non-empty sequence ($\\seq_1$) operators on the corresponding sets, i.e.\n{\\tt A+} is interpreted as $\\seq_1 A$.\n\nThe abstract syntax optional operator ({\\tt ?}) is interpreted as taking the set of singletons and empty set of the corresponding set\nusing the generic function $OPTIONAL$ (defined below), i.e.\n{\\tt A?} is interpreted as $OPTIONAL[A]$.\n\nAbstract syntax terms that are defined as alternations ({\\tt |}) of two or more expressions are translated into free types or unions.\nA side effect of this process is that constructors may be required for each branch of the alternation.\nIn some cases the name of the constructors can be derived from a corresponding element of the abstract syntax.\nFor example, in {\\tt ShapeDefinition}, {\\tt open} and {\\tt close} are mapped to the constructors $open$ and $close$.\nIn the cases where there is no convenient element of the abstract syntax, we mint new constructor names.\n\nWe also introduce new Z identifiers when the element of the abstract syntax does not map to a valid alphanumeric Z identifier.\nFor example the the shape label negation operator ({\\tt !}) is mapped to $negate$.\n\n\\subsection{$OPTIONAL$}\nAn optional value is represented by a singleton set, if the value is present, or the empty set, if the value is absent.\n\\begin{zed}\n\tOPTIONAL[X] == \\{~v:X@\\{v\\}~\\} \\cup \\{ \\emptyset \\}\n\\end{zed}\n\n\\subsection{$Schema$}\nA schema is a sequence of one or more rules.\n\\begin{zed}\n\tSchema == \\seq_1 Rule\n\\end{zed}\n\n\\subsection{$Rule$}\nA rule consists of a shape label, a shape definition, and a sequence of zero or more extension conditions.\n\\begin{zed}\n\tRule == ShapeLabel \\cross ShapeDefinition \\cross \\seq ExtensionCondition\n\\end{zed}\n\nIt is convenient to introduce functions that select the components of a rule.\n\\begin{zed}\n\tshapeLabel == (\\lambda r:Rule @ fst(r) ~)\n\\also\n\tshapeDef == (\\lambda r:Rule @ snd(r) ~)\n\\also\n\textConds == (\\lambda r:Rule @ trd(r) ~)\n\\end{zed}\n\n\\subsection{$ShapeLabel$}\nA shape label is an identifier drawn from some given set.\n\\begin{zed}\n\t[ShapeLabel]\n\\end{zed}\n\n\\subsection{$ShapeDefinition$}\nA shape definition is either a closed shape or an open shape.\n\\begin{zed}\n\tShapeDefinition ::= \\\\\n\\t1\t\tclose \\ldata ShapeExpr \\rdata | \\\\\n\\t1\t\topen \\ldata OPTIONAL[InclPropSet] \\cross ShapeExpr \\rdata\n\\end{zed}\nNote that abstract syntax terms that are defined using alternation are naturally represented as free types in Z Notation.\n\\begin{itemize}\n\\item $close$ is the constructor for closed shapes.A closed shape consists of a shape expression.\n\\item $open$ is the constructor for open shapes. An open shape consists of an optional included properties set and a shape expression.\n\\end{itemize}\n\nGiven a shape definition $d$, let $shapeExpr(d)$ be its shape expression.\n\\begin{axdef}\n\tshapeExpr: ShapeDefinition \\fun ShapeExpr\n\\where\n\t\\forall x: ShapeExpr @ \\\\\n\\t1\t\tshapeExpr(close(x)) = x\n\\also\n\t\\forall o: OPTIONAL[InclPropSet]; x: ShapeExpr @ \\\\\n\\t1\t\tshapeExpr(open(o,x)) = x\n\\end{axdef}\n\n\\subsection{$ClosedShape$}\nThe set of closed shapes is the range of the $close$ shape definition constructor.\n\\begin{zed}\n\tClosedShape == \\ran close\n\\end{zed}\n\n\\subsection{$OpenShape$}\nThe set of open shapes is the range of the $open$ shape definition constructor.\n\\begin{zed}\n\tOpenShape == \\ran open\n\\end{zed}\n\n\\subsection{$InclPropSet$}\nAn included properties set is a properties set.\n\\begin{zed}\n\tInclPropSet == PropertiesSet\n\\end{zed}\nNote that there seems little motivation to introduce the term $InclPropSet$ since it is identical to $PropertiesSet$.\n\n\\subsection{$PropertiesSet$}\nA properties set is a set of IRIs.\n\\begin{zed}\n\tPropertiesSet == \\power IRI\n\\end{zed}\n\n\\subsection{$ShapeExpr$}\nA shape expression defines constraints on RDF graphs.\n\\begin{zed}\n\tShapeExpr ::= \\\\\n\\t1\t\temptyshape | \\\\\n\\t1\t\ttriple \\ldata DirectedTripleConstraint \\cross Cardinality \\rdata | \\\\\n\\t1\t\tsomeOf \\ldata \\seq_1 ShapeExpr \\rdata | \\\\\n\\t1\t\toneOf \\ldata \\seq_1 ShapeExpr \\rdata | \\\\\n\\t1\t\tgroup \\ldata \\seq_1 ShapeExpr \\rdata | \\\\\n\\t1\t\trepetition \\ldata ShapeExpr \\cross Cardinality \\rdata\n\\end{zed}\n\\begin{itemize}\n\\item $emptyshape$ is the empty shape expression.\n\\item $triple$ is the constructor for triple constraint shape expressions. \nA triple constraint shape expression consists of a directed triple constraint and a cardinality.\n\\item $someOf$ is the constructor for some-of shape expressions.\nA some-of shape expression consists of a sequence of one or more shape expressions.\n\\item $oneOf$ is the constructor for one-of shape expressions.\nA one-of shape expression consists of a sequence of one or more shape expressions.\n\\item $group$ is the constructor for grouping shape expressions.\nA grouping shape expression consists of a sequence of one or more shape expressions.\n\\item $repetition$ is the constructor for repetition shape expressions.\nA repetition shape expression consists of a shape expression and a cardinality.\n\\end{itemize}\n\n\\subsection{$EmptyShape$}\nThe set of empty shape expressions is the singleton set that contains the empty shape.\n\\begin{zed}\n\tEmptyShape == \\{ emptyshape \\}\n\\end{zed}\n\n\\subsection{$DirectedPredicate$}\n\nA directed predicate is an IRI with a direction that indicates its usage in a triple. \n$nop$ indicates the normal direction, namely the predicate relates the subject node to the object node. \n$inv$ indicates the inverse direction, namely the predicate relates the object node to the subject node.\n\\begin{zed}\n\tDirectedPredicate ::= \\\\\n\\t1\t\tnop \\ldata IRI \\rdata | \\\\\n\\t1\t\tinv \\ldata IRI \\rdata\n\\end{zed}\n\nThe semantics document uses the notation {\\tt \\verb+^+p} for $inv(p)$.\n\n\\begin{axdef}\n\tpredDP : DirectedPredicate \\fun IRI\n\\where\n\t\\forall p: IRI @ \\\\\n\\t1\t\tpredDP(nop(p)) = predDP(inv(p)) = p\n\\end{axdef}\n\n\\subsection{$DirectedTripleConstraint$}\nA directed triple constraint is value or shape constraint on the object of a triple, or a shape constraint on the subject of a triple.\n\\begin{zed}\n\tDirectedTripleConstraint == \\\\\n\\t1\t\t\\{~ dp: DirectedPredicate; C: Constraint | \\\\\n\\t2\t\t\tdp \\in \\ran inv \\implies C \\in ShapeConstr ~\\}\n\\end{zed}\n\nThe semantics document uses the notation {\\tt p::C} for $(nop(p),C)$ and {\\tt \\verb+^+p::C} for $(inv(p),C)$.\n\n\\begin{axdef}\n\tpredDTC: DirectedTripleConstraint \\fun IRI\n\\where\n\t\\forall dp: DirectedPredicate; C: Constraint | \\\\\n\\t1\t\t(dp, C) \\in DirectedTripleConstraint @ \\\\\n\\t2\t\t\tpredDTC(dp, C) = predDP(dp)\n\\end{axdef}\n\n\\begin{axdef}\n\tconstrDTC: DirectedTripleConstraint \\fun Constraint\n\\where\n\t\\forall dp: DirectedPredicate; C: Constraint | \\\\\n\\t1\t\t(dp, C) \\in DirectedTripleConstraint @ \\\\\n\\t2\t\t\tconstrDTC(dp, C) = C\n\\end{axdef}\n\n\\subsection{$TripleConstraint$}\nA triple constraint places conditions on triples whose subject is a given focus node\nand whose predicate is a given IRI.\n\\begin{axdef}\n\tTripleConstraint: \\power DirectedTripleConstraint\n\\where\n\tTripleConstraint = \\\\\n\\t1\t\t\\{~ p: IRI; C: Constraint @ (nop(p),C) ~\\}\n\\end{axdef}\n\n\\subsection{$InverseTripleConstraint$}\nAn inverse triple constraint places conditions on triples whose object is a given focus node\nand whose predicate is a given IRI.\n\\begin{axdef}\n\tInverseTripleConstraint: \\power DirectedTripleConstraint\n\\where\n\tInverseTripleConstraint = \\\\\n\\t1\t\t\\{~ p: IRI; C: ShapeConstr @ (inv(p),C) ~\\}\n\\end{axdef}\n\n\\subsection{$Constraint$}\nA constraint is a condition on the object node of a triple or the subject node of an inverse triple.\n\\begin{zed}\n\tConstraint ::= \\\\\n\\t1\t\tvalueSet \\ldata \\power (Lit \\cup IRI) \\rdata | \\\\\n\\t1\t\tdatatype \\ldata LiteralDatatype \\cross OPTIONAL[XSFacet] \\rdata | \\\\\n\\t1\t\tkind \\ldata NodeKind \\rdata | \\\\\n\\t1\t\tor \\ldata \\seq_1 ShapeLabel \\rdata | \\\\\n\\t1\t\tand \\ldata \\seq_1 ShapeLabel \\rdata | \\\\\n\\t1\t\tnor \\ldata \\seq_1 ShapeLabel \\rdata | \\\\\n\\t1\t\tnand \\ldata \\seq_1 ShapeLabel \\rdata\n\\end{zed}\n\\begin{itemize}\n\\item $valueSet$ is the constructor for value set values constraints.\nA value set values constraint consists of a set of literals and IRIs.\n\\item $datatype$ is the constructor for literal datatype value constraints.\nA literal datatype value constraint consists of a literal datatype and an optional XML Schema facet.\n\\item $kind$ is the constructor for node kind value constraints.\nA node kind value constraint consists of a specification for a subset of RDF terms.\n\\item $or$ is the constructor for disjunction shape constraints.\nA node must satisfy at least one of the shapes.\n\\item $and$ is the constructor for conjunction shape constraints.\nA node must satisfy all of the shapes.\n\\item $nor$ is the constructor for negated disjunction shape constraints.\nA node must satisfy none of the shapes.\n\\item $nand$ is the constructor for negated conjunction shape constraints.\nA node must satisfy none of the shapes.\n\\end{itemize}\n\n\\subsection{$Cardinality$}\nCardinality defines a range for the number of elements in a set.\n\\begin{zed}\n\tCardinality == MinCardinality \\cross MaxCardinality\n\\end{zed}\n\\begin{itemize}\n\\item A cardinality consists of a minimum cardinality and a maximum cardinality.\n\\end{itemize}\n\n\\subsection{$MinCardinality$}\nMinimum cardinality is the minimum number of elements required to be in a set.\n\\begin{zed}\n\tMinCardinality == \\nat\n\\end{zed}\n\n\\subsection{$MaxCardinality$}\nMaximum cardinality is the maximum number of elements required to be in a set.\n\\begin{zed}\n\tMaxCardinality ::= maxCard \\ldata \\nat \\rdata | unbound\n\\end{zed}\n\\begin{itemize}\n\\item $maxCard$ is the constructor for finite maximum cardinalities.\nA finite maximum cardinality is a natural number.\nNote that a maximum cardinality of $0$ means that the set must be empty.\n\\item $unbound$ indicates that the maximum number of elements in a set is unbounded.\n\\end{itemize}\n\n\\subsection{$inBounds$}\nA natural number $k$ is said to be in bounds of a cardinality when $k$ is between the minimum and maximum\nlimits of the cardinality.\n\\begin{axdef}\n\tinBounds: \\nat \\rel Cardinality\n\\where\n\t\\forall k, n: \\nat @ \\\\\n\\t1\t\tk \\inrel{inBounds} (n,unbound) \\iff n \\leq k\n\\also\n\t\\forall k, n, m: \\nat @ \\\\\n\\t1\t\tk \\inrel{inBounds} (n,maxCard(m)) \\iff n \\leq k \\leq m\n\\end{axdef}\n\n\\subsection{Notation}\nLet $a$ be an IRI, let $C$ be a value or shape constraint, let $n$ and $m$ be non-negative integers.\nThe semantics document uses the notation listed in Table~\\ref{notation-meaning} for some shape expressions.\n\n\\begin{table}[h]\n\\begin{center}\n\\begin{tabular}{|c|c|}\n\\hline\nNotation\t\t\t\t& Meaning \\\\\n\\hline\n{\\tt a::C[n;m]}\t\t\t& $triple(nop(a,C),(n,maxCard(m)))$\\\\\n{\\tt \\verb+^+a::C[n;m]}\t& $triple(inv(a,C),(n,maxCard(m)))$ \\\\\n\\hline\n{\\tt a::C}\t\t\t\t& {\\tt a::C[1;1]}\\\\\n{\\tt \\verb+^+a::C}\t\t& {\\tt \\verb+^+a::C[1;1]} \\\\\n\\hline\n{\\tt !a::C}\t\t\t\t& {\\tt a::C[0;0]} \\\\\n{\\tt !\\verb+^+a:C}\t\t& {\\tt \\verb+^+a::C[0;0]} \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\caption{Meaning of shape expression notation}\n\\label{notation-meaning}\n\\end{table}\n\\begin{itemize}\n\\item If the cardinality is {\\tt [1;1]} it may be omitted.\n\\item The negated shape expressions are semantically equivalent to the corresponding non-negated shape expressions with cardinality {\\tt [0;0]}.\n\\end{itemize}\n\n\\subsection{$none$, $one$}\nIt is convenient to define some common cardinalities.\n\\begin{zed}\n\tnone == (0,maxCard(0))\n\\also\n\tone == (1,maxCard(1))\n\\end{zed}\n\\begin{itemize}\n\\item A cardinality of $none =$ {\\tt [0;0]} is used to indicate a negated triple or inverse triple constraint.\n\\item A cardinality of $one =$ {\\tt [1;1]} is the default cardinality of a triple or inverse triple constraint\nwhen no cardinality is explicitly given in the notations {\\tt a::C} and {\\tt \\verb+^+a::C}.\n\\end{itemize}\n\n\\subsection{$NegatedTripleConstraint$}\nA negated triple constraint shape expression is a triple constraint shape expression that has a cardinality of $none$.\n\\begin{zed}\n\tNegatedTripleConstraint == \\\\\n\\t1\t\t\\{~ tc: TripleConstraint @ triple(tc,none) ~\\}\n\\end{zed}\n\n\\subsection{$NegatedInverseTripleConstraint$}\nA negated inverse triple constraint shape expression is an inverse triple constraint shape expression that has a cardinality of $none$.\n\\begin{zed}\n\tNegatedInverseTripleConstraint == \\\\\n\\t1\t\t\\{~ itc: InverseTripleConstraint @ triple(itc,none) ~\\}\n\\end{zed}\n\n\\subsection{$ValueConstr$}\nA value constraint places conditions on the object nodes of triples.\n\\begin{zed}\n\tValueConstr == \\ran valueSet \\cup \\ran datatype \\cup \\ran kind\n\\end{zed}\n\n\\subsection{$ValueSet$}\nThe set of value set value constraints is the range of the $valueSet$ constructor.\n\\begin{zed}\n\tValueSet == \\ran valueSet\n\\end{zed}\n\n\\subsection{$LiteralDatatype$}\nA literal datatype is an IRI that identifies a set of literal RDF terms.\nWe assume that this subset of IRIs is given.\n\\begin{axdef}\n\tLiteralDatatype: \\power IRI\n\\end{axdef}\n\nWe also assume that we are given an interpretation of each literal datatype as a set of literals.\n\\begin{axdef}\n\tliteralsOfDatatype: LiteralDatatype \\fun \\power Lit\n\\end{axdef}\n\n\\subsection{$NodeKind$}\nA node kind identifies a subset of RDF terms.\n\\begin{zed}\n\tNodeKind ::= iri | blank | literal | nonliteral\n\\end{zed}\n\\begin{itemize}\n\\item $iri$ identifies the set of IRIs.\n\\item $blank$ identifies the set of blank nodes.\n\\item $literal$ identifies the set of literals.\n\\item $nonliteral$ identifies the complement of the set of literals, i.e. the union of IRIs and blank nodes.\n\\end{itemize}\n\nEach node kind corresponds to a set of RDF terms.\n\\begin{axdef}\n\ttermsOfKind: NodeKind \\fun \\power TERM\n\\where\n\ttermsOfKind(iri) = IRI\n\\also\n\ttermsOfKind(blank) = Blank\n\\also\n\ttermsOfKind(literal) = Lit\n\\also\n\ttermsOfKind(nonliteral) = TERM \\setminus Lit\n\\end{axdef}\n\n\\subsection{$XSFacet$}\nAn XML Schema facet places restrictions on literals.\nWe assume this is a given set.\n\\begin{zed}\n\t[XSFacet]\n\\end{zed}\n\nWe also assume that we are given an interpretation of facets as sets of literals.\n\\begin{axdef}\n\tliteralsOfFacet: LiteralDatatype \\cross XSFacet \\fun \\power Lit\n\\where\n\t\\forall d: LiteralDatatype; f: XSFacet @ \\\\\n\\t1\t\tliteralsOfFacet(d,f) \\subseteq literalsOfDatatype(d)\n\\end{axdef}\n\\begin{itemize}\n\\item The literals that correspond to a facet of a datatype are a subset of the literals that correspond to the datatype.\n\\end{itemize}\n\n\\subsection{$ShapeConstr$}\nA shape constraint requires that a node satisfy logical combinations of one or more other shapes which are identified by their shape labels.\n\\begin{zed}\n\tShapeConstr == \\ran or \\cup \\ran and \\cup \\ran nor \\cup \\ran nand\n\\end{zed}\n\n\\subsection{$DisjShapeConstr$}\nThe set of all disjunctive shape constraints is the range of the $or$ constructor.\n\\begin{zed}\n\tDisjShapeConstr == \\ran or\n\\end{zed}\n\n\\subsection{$ConjShapeConstraint$}\nThe set of all conjunctive shape constraints is the range of the $and$ constructor.\n\\begin{zed}\n\tConjShapeConstraint == \\ran and\n\\end{zed}\n\n\\subsection{$SomeOfShape$}\nThe set of some-of shape expressions is the range of $someOf$.\n\\begin{zed}\n\tSomeOfShape == \\ran someOf\n\\end{zed}\n\n\\subsection{$OneOfShape$}\nThe set of one-of shape expressions is the range of $oneOf$.\n\\begin{zed}\n\tOneOfShape == \\ran oneOf\n\\end{zed}\n\n\\subsection{$GroupShape$}\nThe set of grouping shape expressions is the range of $group$.\n\\begin{zed}\n\tGroupShape == \\ran group\n\\end{zed}\n\n\\subsection{$RepetitionShape$}\nThe set of repetition shape expressions is the range of $repetition$.\n\\begin{zed}\n\tRepetitionShape == \\ran repetition\n\\end{zed}\n\n\\subsection{$ExtensionCondition$}\nAn extension condition is the definition of a constraint written in an extension language\n\\begin{zed}\n\tExtensionCondition == ExtLangName \\cross ExtDefinition\n\\end{zed}\n\n\\subsection{$ExtLangName$}\nAn extension language name is an identifier for an extension language, such as JavaScript.\nWe assume this is a given set.\n\\begin{zed}\n\t[ExtLangName]\n\\end{zed}\n\n\\subsection{$ExtDefinition$}\nAn extension definition is a program written in some extension language that implements a constraint check.\nWe assume this is a given set.\n\\begin{zed}\n\t[ExtDefinition]\n\\end{zed}\n\nAn extension condition represents a function that takes as input a pointed graph, and returns\nas output a boolean with the value {\\tt true} if the constraint is violated and {\\tt false} is satisfied.\nWe assume we are given a mapping that associates each extension condition with the set of pointed graphs that violate it.\n\\begin{axdef}\n\tviolatedBy: ExtensionCondition \\fun \\power PointedGraph\n\\end{axdef}\n\n\\subsection{$ShapeLabel$ Definitions}\nGiven a schema $S$, let $defs(S)$ be the set of all shape labels defined in $S$.\n\\begin{zed}\n\tdefs == (\\lambda S: Schema @ \\\\\n\\t1\t\t\\{~ r: \\ran S @ shapeLabel(r) ~\\} ~)\n\\end{zed}\n \nEach rule in a schema must be identified by a unique shape label.\n\\begin{zed}\n\tSchemaUL == \\{~ S: Schema | \\# S = \\# (defs(S)) ~\\}\n\\end{zed}\n\\begin{itemize}\n\\item In a schema with unique rule labels there are as many rules as labels.\n\\end{itemize}\n\n\\subsection{$rule$}\nGiven a schema $S$ with unique rule labels, and a label $T$ defined in $S$, let $rule(T,S)$ be the corresponding rule.\n\\begin{axdef}\n\trule: ShapeLabel \\cross SchemaUL \\pfun Rule\n\\where\n\t\\dom rule = \\{~ T: ShapeLabel; S: SchemaUL | T \\in defs(S) ~\\}\n\\also\n\t\\forall S: SchemaUL@\\\\\n\\t1\t\t\\forall r: \\ran(S) @ \\\\\n\\t2\t\t\t\\LET T == shapeLabel(r) @ \\\\\n\\t3\t\t\t\trule(T,S) = r\n\\end{axdef}\n\n\\subsection{$ShapeLabel$ References}\nGiven a schema $S$, let $refs(S)$ be the set of shape labels referenced in $S$.\n\\begin{zed}\n\trefs == (\\lambda S: Schema @ \\bigcup \\{~ r: \\ran S @ refsRule(r) ~\\} ~)\n\\end{zed}\n\\begin{itemize}\n\\item The set of references in a schema is the union of the sets of references in its rules.\n\\end{itemize}\n\nGiven a rule $r$, let $refsRule(r)$ be the set of shape labels referenced in $r$.\n\\begin{zed}\n\trefsRule == (\\lambda r: Rule @ refsShapeDefinition(shapeDef(r)) ~)\n\\end{zed}\n\\begin{itemize}\n\\item The set of references in a rule is the set of references in its shape definition.\n\\end{itemize}\n\nGiven a shape definition $d$, let $refsShapeDefinition(d)$ be the set of shape labels referenced in $d$.\n\\begin{axdef}\n\trefsShapeDefinition: ShapeDefinition \\fun \\finset ShapeLabel\n\\where\n\t\\forall d: ShapeDefinition @ \\\\\n\\t1\t\trefsShapeDefinition(d) = refsShapeExpr(shapeExpr(d))\n\\end{axdef}\n\\begin{itemize}\n\\item The set of references in a closed shape definition is the set of references in its shape expression.\n\\item The set of references in an open shape definition is the set of references in its shape expression.\n\\end{itemize}\n\nGiven a shape expression $x$, let $refsShapeExpr(x)$ be the set of shape labels referenced in $x$.\n\\begin{axdef}\n\trefsShapeExpr: ShapeExpr \\fun \\finset ShapeLabel\n\\where\n\trefsShapeExpr(emptyshape) = \\emptyset\n\\also\n\t\\forall dtc: DirectedTripleConstraint; c: Cardinality @ \\\\\n\\t1\t\trefsShapeExpr(triple(dtc,c)) = \\\\\n\\t2\t\t\trefsDirectedTripleConstraint(dtc)\n\\also\n\t\\forall xs: \\seq_1 ShapeExpr @ \\\\\n\\t1\t\trefsShapeExpr(someOf(xs)) = \\\\\n\\t1\t\trefsShapeExpr(oneOf(xs)) = \\\\\n\\t1\t\trefsShapeExpr(group(xs)) = \\\\\n\\t2\t\t\t\\bigcup \\{~ x: \\ran xs @ refsShapeExpr(x) ~\\}\n\\also\n\t\\forall x: ShapeExpr; c: Cardinality @ \\\\\n\\t1\t\trefsShapeExpr(repetition(x,c)) = \\\\\n\\t2\t\t\trefsShapeExpr(x)\n\\end{axdef}\n\\begin{itemize}\n\\item The empty shape expression references no labels.\n\\item A directed triple constraint shape expression references the labels referenced in the directed triple constraint.\n\\item A some-of or one-of or group shape expression references the union of the labels referenced in each component shape expression.\n\\item A repetition shape expression references the labels referenced in its unrepeated shape expression.\n\\end{itemize}\n\nGiven a directed triple constraint $dtc$, let $refsDirectedTripleConstraint(dtc)$ be the set of shape labels referenced in $dtc$.\n\\begin{axdef}\n\trefsDirectedTripleConstraint: \\\\\n\\t1\t\tDirectedTripleConstraint \\fun \\finset ShapeLabel\n\\where\n\t\\forall a: IRI; C: ValueConstr @ \\\\\n\\t1\t\trefsDirectedTripleConstraint((nop(a),C)) = \\emptyset\n\\also\n\t\\forall a: IRI; C: ShapeConstr @ \\\\\n\\t1\t\trefsDirectedTripleConstraint((nop(a),C)) = \\\\\n\\t1\t\trefsDirectedTripleConstraint((inv(a),C)) = \\\\\n\\t2\t\t\trefsShapeConstr(C)\n\\end{axdef}\n\\begin{itemize}\n\\item A value triple constraint references no labels.\n\\item A shape triple constraint references the labels in its shape constraint.\n\\end{itemize}\n\nGiven a shape constraint $C$, let $refsShapeConstr(C)$ be the set of shape labels referenced in $C$.\n\\begin{axdef}\n\trefsShapeConstr: ShapeConstr \\fun \\finset ShapeLabel\n\\where\n\t\\forall ls: \\seq_1 ShapeLabel @ \\\\\n\\t1\t\trefsShapeConstr(or(ls)) = \\\\\n\\t1\t\trefsShapeConstr(and(ls)) = \\\\\n\\t1\t\trefsShapeConstr(nor(ls)) = \\\\\n\\t1\t\trefsShapeConstr(nand(ls)) = \\\\\n\\t2\t\t\t\\ran ls\n\\end{axdef}\n\\begin{itemize}\n\\item A shape constraint references the range of its sequence of shape labels.\n\\end{itemize}\n\nEvery shape label referenced in a schema must be defined in the schema.\n\\begin{zed}\n\tSchemaRD == \\{~ s:Schema | refs(s) \\subseteq defs(s) ~\\}\n\\end{zed}\n\nA schema is well-formed if its rules have unique labels and all referenced shape labels are defined.\n\\begin{zed}\n\tSchemaWF == SchemaUL \\cap SchemaRD\n\\end{zed}\n\n\\section{Evaluation}\n\\label{sec-evaluation}\nThis section defines the interpretation of shapes as constraints on RDF graphs.\nAll functions that are defined in the semantics document are given formal definitions here.\nWe assume that from this point on whenever the semantics document refers to schemas they are well-formed.\n\n\\subsection{$shapes$}\nGiven a well-formed schema $S$, let $shapes(S)$ be the set of shape labels that appear in $S$.\n\\begin{zed}\n\tshapes == (\\lambda S: SchemaWF @ defs(S) ~)\n\\end{zed}\n\n\\subsection{$expr$}\nGiven a shape label $T$ and a well-formed schema $S$, let $expr(T,S)$ be the shape expression in the rule with label $T$ in $S$.\n\\begin{axdef}\n\texpr: ShapeLabel \\cross SchemaWF \\pfun ShapeExpr\n\\where\n\t\\dom expr = \\{~ T: ShapeLabel; S: SchemaWF | T \\in shapes(S) ~\\} \\\\\n\\also\n\t\\forall T: ShapeLabel; S: SchemaWF | T \\in shapes(S) @ \\\\\n\\t1\t\t\\LET r == rule(T,S) @ \\\\\n\\t2\t\t\texpr(T,S) = shapeExpr(shapeDef(r))\n\\end{axdef}\n\\begin{itemize}\n\\item The shape expression for a shape label $T$ is the shape expression in the shape definition of the rule $r$ that has shape label $T$.\n\\end{itemize}\n\n\\subsection{$incl$}\n\nGiven a shape label $T$ defined in a well-formed schema $S$, let $incl(T,S)$ be the,\npossibly empty, set of included properties.\n\\begin{axdef}\n\tincl: ShapeLabel \\cross SchemaWF \\pfun InclPropSet\n\\where\n\t\\dom incl = \\{~ T: ShapeLabel; S: SchemaWF | T \\in shapes(S) ~\\}\n\\also\n\t\\forall T: ShapeLabel; S: SchemaWF | T \\in shapes(S) @ \\\\\n\\t1\t\t\\exists_1 r: \\ran S | T = shapeLabel(r) @ \\\\\n\\t2\t\t\tincl(T,S) = inclShapeDefinition(shapeDef(r))\n\\end{axdef}\n\\begin{itemize}\n\\item The included properties set for a shape label $T$ is the included properties set in the shape definition of the rule $r$ that has shape label $T$.\n\\end{itemize}\n\nGiven a shape definition $d$, let $inclShapeDefinition(d)$ be its included properties set.\n\\begin{axdef}\n\tinclShapeDefinition: ShapeDefinition \\fun InclPropSet\n\\where\n\t\\forall x: ShapeExpr @ \\\\\n\\t1\t\tinclShapeDefinition(close(x)) = \\\\\n\\t1\t\tinclShapeDefinition(open(\\{ \\emptyset \\},x)) \\\\\n\\t2\t\t\t= \\emptyset\n\\also\n\t\\forall ips: InclPropSet; x: ShapeExpr @ \\\\\n\\t1\t\tinclShapeDefinition(open(\\{ ips \\},x)) = ips\n\\end{axdef}\n\\begin{itemize}\n\\item The included property set of a closed shape definition or an open definition with no included\nproperty set is the empty set.\n\\item The included property set of an open shape definition with an included property set is that\nincluded property set.\n\\end{itemize}\n\n\\subsection{$properties$}\n\nGiven a shape expression $x$, let $properties(x)$ be the set of properties that appear in some \ntriple constraint in $x$.\n\\begin{axdef}\n\tproperties: ShapeExpr \\fun PropertiesSet\n\\where\n\tproperties(emptyshape) = \\emptyset\n\\also\n\t\\forall tc: TripleConstraint; c: Cardinality @ \\\\\n\\t1\t\tproperties(triple(tc,c)) = \\\\\n\\t2\t\t\tpropertiesTripleConstraint(tc)\n\\also\n\t\\forall itc: InverseTripleConstraint; c: Cardinality @ \\\\\n\\t1\t\tproperties(triple(itc,c)) = \\\\\n\\t2\t\t\t\\emptyset\n\\also\n\t\\forall xs: \\seq_1 ShapeExpr @ \\\\\n\\t1\t\tproperties(someOf(xs)) = \\\\\n\\t1\t\tproperties(oneOf(xs)) = \\\\\n\\t1\t\tproperties(group(xs)) = \\\\\n\\t2\t\t\t\\bigcup \\{~ x: \\ran xs @ properties(x) ~\\}\n\\also\n\t\\forall x: ShapeExpr; c: Cardinality @ \\\\\n\\t1\t\tproperties(repetition(x,c)) = properties(x)\n\\end{axdef}\n\\begin{itemize}\n\\item An empty shape expression has no properties.\n\\item The properties of a triple constraint shape expression or an negated triple constraint\nshape expression are the properties of their triple constraints.\n\\item Inverse triple constraint shape expressions and negated inverse triple constraint shape expressions\nhave no properties.\n\\item The properties of a some-of, one-of, or grouping shape expression is the union of the properties of their\ncomponent shape expressions.\n\\item The properties of a repetition shape expression are the properties of the shape expression being repeated.\n\\end{itemize}\n\nGiven a triple constraint $tc$, let $propertiesTripleConstraint(tc)$ be its set of properties.\n\\begin{axdef}\n\tpropertiesTripleConstraint: TripleConstraint \\fun PropertiesSet\n\\where\n\t\\forall a: IRI; C: Constraint @ \\\\\n\\t1\t\tpropertiesTripleConstraint((nop(a),C)) = \\{ a \\}\n\\end{axdef}\n\\begin{itemize}\n\\item The properties of a triple constraint is the singleton set that contains its IRI.\n\\end{itemize}\n\n\\subsection{$invproperties$}\n\nGiven a shape expression $x$, let $invproperties(x)$ be the set of properties that appear in some \ninverse triple constraint in $x$.\n\\begin{axdef}\n\tinvproperties: ShapeExpr \\fun PropertiesSet\n\\where\n\tinvproperties(emptyshape) = \\emptyset\n\\also\n\t\\forall tc: TripleConstraint; c: Cardinality @ \\\\\n\\t1\t\tinvproperties(triple(tc,c)) = \\\\\n\\t2\t\t\t\\emptyset\n\\also\n\t\\forall itc: InverseTripleConstraint; c: Cardinality @ \\\\\n\\t1\t\tinvproperties(triple(itc,c)) = \\\\\n\\t2\t\t\tinvpropertiesInverseTripleConstraint(itc)\n\\also\n\t\\forall xs: \\seq_1 ShapeExpr @ \\\\\n\\t1\t\tinvproperties(someOf(xs)) = \\\\\n\\t1\t\tinvproperties(oneOf(xs)) = \\\\\n\\t1\t\tinvproperties(group(xs)) = \\\\\n\\t2\t\t\t\\bigcup \\{~ x: \\ran xs @ invproperties(x) ~\\}\n\\also\n\t\\forall x: ShapeExpr; c: Cardinality @ \\\\\n\\t1\t\tinvproperties(repetition(x,c)) = invproperties(x)\n\\end{axdef}\n\\begin{itemize}\n\\item An empty shape expression has no inverse properties.\n\\item A triple constraint shape expression or an negated triple constraint\nshape expression has no inverse properties.\n\\item The inverse properties of an inverse triple constraint shape expression or negated inverse triple constraint shape expression\nare the inverse properties in its inverse triple constraint.\n\\item The inverse properties of a some-of, one-of, or grouping shape expression is the union of the inverse properties of their\ncomponent shape expressions.\n\\item The inverse properties of a repetition shape expression are the inverse properties of the shape expression being repeated.\n\\end{itemize}\n\nGiven an inverse triple constraint $itc$, let $invpropertiesInverseTripleConstraint(tc)$ be its set of inverse properties.\n\\begin{axdef}\n\tinvpropertiesInverseTripleConstraint: \\\\\n\\t1\t\tInverseTripleConstraint \\fun PropertiesSet\n\\where\n\t\\forall a: IRI; C: ShapeConstr @ \\\\\n\\t1\t\tinvpropertiesInverseTripleConstraint((inv(a),C)) = \\{ a \\}\n\\end{axdef}\n\\begin{itemize}\n\\item The inverse properties of an inverse triple constraint is the singleton set that contains its IRI.\n\\end{itemize}\n\n\\subsection{$dep\\_graph$}\n\n\\subsubsection{$DiGraph$}\nA directed graph consists of a set of nodes and a set of directed edges that connect the nodes.\n\\begin{schema}{DiGraph}[X]\n\tnodes: \\power X \\\\\n\tedges : X \\rel X\n\\where\n\tedges \\in nodes \\rel nodes\n\\end{schema}\n\\begin{itemize}\n\\item Each edge connects a pair of nodes in the graph.\n\\end{itemize}\n\n\\subsubsection{$DepGraph$}\nGiven a well-formed schema $S$, let the shapes dependency graph be the directed graph \nwhose nodes are the shape labels in $S$ and whose edges connect label $T1$ to label $T2$ when the shape expression \nthat defines $T1$ refers to $T2$.\\begin{schema}{DepGraph}\n\tS: SchemaWF \\\\\n\tDiGraph[ShapeLabel]\n\\where\n\tnodes = shapes(S)\n\\also\n\tedges =  \\{~ T1, T2 : nodes | T2 \\in refsShapeExpr(expr(T1,S)) ~\\}\n\\end{schema}\n\n\\subsubsection{$dep\\_graph$}\nLet $dep\\_graph(S)$ be the dependency graph of $S$.\n\\begin{axdef}\n\tdep\\_graph: SchemaWF \\fun DiGraph[ShapeLabel]\n\\where\n\tdep\\_graph = \\{~ DepGraph @ S \\mapsto \\theta DiGraph ~\\}\n\\end{axdef}\n\n\\subsection{$dep\\_subgraph$}\n\n\\subsubsection{$reachable$}\nGiven a directed graph $g$ and a node $T$ in $g$, a node $U$ is reachable from $T$ if there is a directed path of one or more edges that connects\n$T$ to $U$.\n\\begin{gendef}[X]\n\treachable : DiGraph[X] \\cross X \\fun \\power X\n\\where\n\t\\forall g: DiGraph[X]; T: X @ \\\\\n\\t1\t\t\\LET edges == g.edges @ \\\\\n\\t2\t\t\treachable(g, T) = \\{~ U: X | T \\mapsto U \\in edges\\plus ~\\}\n\\end{gendef}\n\n\\subsubsection{$DepSubgraph$}\nGiven a well-formed schema $S$ and a shape label $T$ in $S$, the shapes dependency\ngraph is the subgraph induced by the nodes that are reachable from $T$.\n\\begin{schema}{DepSubgraph}\n\tS: SchemaWF \\\\\n\tT: ShapeLabel \\\\\n\tDiGraph[ShapeLabel]\n\\where\n\tT \\in shapes(S)\n\\also\n\t\\LET g == dep\\_graph(S) @ \\\\\n\\t1\t\tnodes = reachable(g,T) \\land \\\\\n\\t1\t\tedges = g.edges \\cap (nodes \\cross nodes)\n\\end{schema}\n\\begin{itemize}\n\\item The nodes of the subgraph consist of all the nodes reachable from $T$.\n\\item The edges of the subgraph consist of all edges of the graph whose nodes are in the subgraph.\n\\end{itemize}\n\nNote that the above formal definition of the dependency subgraph is a literal translation of the text in the semantics document.\nIn particular, this literal translation does not explicitly include the label $T$ as a node.\nTherefore $T$ will not be in the subgraph unless it is in a directed cycle of edges.\n\n\\subsubsection{$dep\\_subgraph$}\nLet $dep\\_subgraph(T,S)$ be the dependency subgraph of $T$ in $S$.\n\\begin{axdef}\n\tdep\\_subgraph : ShapeLabel \\cross SchemaWF \\pfun DiGraph[ShapeLabel]\n\\where\n\tdep\\_subgraph = \\{~ DepSubgraph @ (T,S) \\mapsto \\theta DiGraph ~\\}\n\\end{axdef}\n\n\\subsection{$negshapes$}\nThe definition of $negshapes$ makes use of several auxilliary definitions. \nIn the following we assume that $S$ is a well-formed schema and that $T$ is a shape label in $S$.\n\n\\subsubsection{$inNeg$}\nLet $inNeg(S)$ be the set of labels that appear in some negated shape constraint.\n\\begin{axdef}\n\tinNeg: SchemaWF \\fun \\finset ShapeLabel\n\\where\n\t\\forall S: SchemaWF @ \\\\\n\\t1\t\tinNeg(S) = \\bigcup \\{~ T: shapes(S) @ inNegExpr(expr(T,S)) ~\\}\n\\end{axdef}\n\nGiven a shape expression $x$, let $inNegExpr(x)$ be the set of labels that appear in some negated shape constraint in $x$.\n\\begin{axdef}\n\tinNegExpr: ShapeExpr \\fun \\finset ShapeLabel\n\\where\n\tinNegExpr(emptyshape) = \\emptyset\n\\also\n\t\\forall tc: TripleConstraint; c: Cardinality @ \\\\\n\\t1\t\tinNegExpr(triple(tc,c)) = \\\\\n\\t2\t\t\tinNegTripleConstraint(tc)\n\\also\n\t\\forall itc: InverseTripleConstraint; c: Cardinality @ \\\\\n\\t1\t\tinNegExpr(triple(itc,c)) = \\\\\n\\t2\t\t\tinNegInverseTripleConstraint(itc)\n\\also\n\t\\forall xs: \\seq_1 ShapeExpr @ \\\\\n\\t1\t\tinNegExpr(someOf(xs)) = \\\\\n\\t1\t\tinNegExpr(oneOf(xs)) = \\\\\n\\t1\t\tinNegExpr(group(xs)) = \\\\\n\\t2\t\t\t\\bigcup \\{~ x: \\ran xs @ inNegExpr(x) ~\\}\n\\also\n\t\\forall x: ShapeExpr; c: Cardinality @ \\\\\n\\t1\t\tinNegExpr(repetition(x,c)) = inNegExpr(x)\n\\end{axdef}\n\nGiven a triple constraint $tc$, let $inNegTripleConstraint(tc)$ be the set of labels that appear in some negated shape constraint in $tc$.\n\\begin{axdef}\n\tinNegTripleConstraint: TripleConstraint \\fun \\finset ShapeLabel\n\\where\n\t\\forall a: IRI; C: ValueConstr @ \\\\\n\\t1\t\tinNegTripleConstraint((nop(a),C)) = \\emptyset\n\\also\n\t\\forall a: IRI; C: ShapeConstr @ \\\\\n\\t1\t\tinNegTripleConstraint((nop(a),C)) = inNegShapeConstr(C)\n\\end{axdef}\n\nGiven an inverse triple constraint $itc$, let $inNegInverseTripleConstraint(tc)$ be the set of labels that appear in some negated shape constraint in $itc$.\n\\begin{axdef}\n\tinNegInverseTripleConstraint: \\\\\n\\t1\t\tInverseTripleConstraint \\fun \\finset ShapeLabel\n\\where\n\t\\forall a: IRI; C: ShapeConstr @ \\\\\n\\t1\t\tinNegInverseTripleConstraint((inv(a),C)) = inNegShapeConstr(C)\n\\end{axdef}\n\nGiven a shape constraint $C$, let $inNegShapeConstr(C)$ be the set of labels that appear in $C$ when it is negated, or the\nempty set otherwise.\n\\begin{axdef}\n\tinNegShapeConstr: ShapeConstr \\fun \\finset ShapeLabel\n\\where\n\t\\forall Ts: \\seq_1 ShapeLabel @ \\\\\n\\t1\t\tinNegShapeConstr(or(Ts)) = \\\\\n\\t1\t\tinNegShapeConstr(and(Ts)) = \\\\\n\\t2\t\t\t\\emptyset\n\\also\n\t\\forall Ts: \\seq_1 ShapeLabel @ \\\\\n\\t1\t\tinNegShapeConstr(nor(Ts)) = \\\\\n\\t1\t\tinNegShapeConstr(nand(Ts)) = \\\\\n\\t2\t\t\t\\ran Ts\n\\end{axdef}\n\n\\subsubsection{$underOneOf$}\nLet $underOneOf(S)$ be the set of labels that appear in some triple constraint or inverse triple constraint under a one-of constraint\nin $S$.\n\\begin{axdef}\n\tunderOneOf: SchemaWF \\fun \\finset ShapeLabel\n\\where\n\t\\forall S: SchemaWF @ \\\\\n\\t1\t\tunderOneOf(S) = \\\\\n\\t2\t\t\\bigcup \\{~ T: shapes(S) @ underOneOfExpr(expr(T,S)) ~\\}\n\\end{axdef}\n\nGiven a shape expression $x$, let $underOneOfExpr(x)$ be the set of labels that appear in some triple constraint or inverse triple constraint under a one-of constraint in $x$.\n\\begin{axdef}\n\tunderOneOfExpr: ShapeExpr \\fun \\finset ShapeLabel\n\\where\n\t\\forall x: ShapeExpr @ \\\\\n\\t1\t\tunderOneOfExpr(x) = \\\\\n\\t2\t\t\t\\IF x \\in \\ran someOf \\\\\n\\t3\t\t\t\t\\THEN refsShapeExpr(x) \\\\\n\\t3\t\t\t\t\\ELSE \\emptyset\n\\end{axdef}\n\n\\subsubsection{$inTripleConstr$}\nLet $inTripleConstr(S)$ be the set of labels $T$ such that there is a shape label $T1$ and a triple constraint \n{\\tt p::C} or an inverse shape triple constraint\n{\\tt \\verb+^+p::C} $x$ in $expr(T1, S)$, and $T$ appears in $x$.\nNote that this definition looks wrong since it does not involve negation of shapes.\nNevertheless, a literal translation is given here.\nThe only difference between $inTripleConstr(S)$ and $refs(S)$ seems to be that the cardinality on the triple and inverse triple\nconstraints is {\\tt [1,1]} since it is not explicitly included in the notations {\\tt p::C} and {\\tt \\verb+^+p::C}.\n\\begin{axdef}\n\tinTripleConstr: SchemaWF \\fun \\finset ShapeLabel\n\\where\n\t\\forall S: SchemaWF @ \\\\\n\\t1\t\tinTripleConstr(S) = \\\\\n\\t2\t\t\t\\bigcup \\{~ T1: shapes(S) @ inTripleConstrExpr(expr(T1,S)) ~\\}\n\\end{axdef}\n\nGiven a shape expression $x$, let $inTripleConstrExpr(x)$ be the set of labels $T$ such that $x$ contains a triple constraint \n{\\tt p::C} or an inverse shape triple constraint {\\tt \\verb+^+p::C} and $T$ appears in $x$.\n\\begin{axdef}\n\tinTripleConstrExpr: ShapeExpr \\fun \\finset ShapeLabel\n\\where\n\tinTripleConstrExpr(emptyshape) = \\emptyset\n\\also\n\t\\forall dtc: DirectedTripleConstraint; c: Cardinality @ \\\\\n\\t1\t\tinTripleConstrExpr(triple(dtc,c)) = \\\\\n\\t2\t\t\t\\IF c = one \\\\\n\\t3\t\t\t\t\\THEN refsDirectedTripleConstraint(dtc) \\\\\n\\t3\t\t\t\t\\ELSE \\emptyset\n\\also\n\t\\forall xs: \\seq_1 ShapeExpr @ \\\\\n\\t1\t\tinTripleConstrExpr(someOf(xs)) = \\\\\n\\t1\t\tinTripleConstrExpr(oneOf(xs)) = \\\\\n\\t1\t\tinTripleConstrExpr(group(xs)) = \\\\\n\\t2\t\t\t\\bigcup \\{~ x: \\ran xs @ inTripleConstrExpr(x) ~\\}\n\\also\n\t\\forall x: ShapeExpr; c: Cardinality @ \\\\\n\\t1\t\tinTripleConstrExpr(repetition(x,c)) = inTripleConstrExpr(x)\n\\end{axdef}\n\n\\subsubsection{$negshapes$}\nThe semantics document makes the following statement.\n\\begin{quote}\nIntuitively, negshapes(S) is the set of shapes labels for which one needs to check whether some nodes in a graph do not satisfy these shapes, in order to validate the graph against the schema S.\n\\end{quote}\n\nLet $negshapes(S)$ be the set of negated shape labels that appear in $S$.\n\\begin{axdef}\n\tnegshapes: SchemaWF \\fun \\finset ShapeLabel\n\\where\n\t\\forall S: SchemaWF @ \\\\\n\\t1\t\tnegshapes(S) = inNeg(S) \\cup underOneOf(S) \\cup inTripleConstr(S)\n\\end{axdef}\n\\begin{itemize}\n\\item A negated shape label is a shape label that appears in a negated shape constraint, or in a triple or inverse triple constraint under a one-of shape expression, or in a triple or inverse triple constraint that has cardinality {\\tt [1,1]}.\n\\end{itemize}\nNote that, as remarked above, the definition of $inTripleConstr$ seems wrong.\n\n\\subsection{$ShapeVerdict$}\nThe semantics document defines the notation {\\tt !T} for shape labels $T$ to indicate that $T$ is negated.\nThe semantics of a schema involves assigning sets of shape labels and negated shape labels to the nodes of a graph, \nwhich indicates which shapes must be satisfied or violated at each node. \n\nA shape verdict indicates if a shape must be satisfied or violated.\nAn asserted label must be satisfied.\nA negated label must be violated.\n\\begin{zed}\n\tShapeVerdict ::= \\\\\n\\t1\t\tassert\\ldata ShapeLabel \\rdata | \\\\\n\\t1\t\tnegate\\ldata ShapeLabel \\rdata\n\\end{zed}\n\nThe notation {\\tt !T} corresponds to $negate(T)$.\n\n\\subsection{$allowed$}\nGiven a value constraint $V$, let $allowed(V)$ be the set of all allowed values defined by $V$.\n\\begin{axdef}\n\tallowed: ValueConstr \\fun \\power (Lit \\cup IRI)\n\\where\n\t\\forall vs: \\power (Lit \\cup IRI) @ \\\\\n\\t1\t\tallowed(valueSet(vs)) = vs\n\\also\n\t\\forall dt: LiteralDatatype @ \\\\\n\\t1\t\tallowed(datatype(dt,\\emptyset)) = literalsOfDatatype(dt)\n\\also\n\t\\forall dt:LiteralDatatype; f: XSFacet @ \\\\\n\\t1\t\tallowed(datatype(dt,\\{f\\})) = literalsOfFacet(dt,f)\n\\also\n\t\\forall k: NodeKind @ \\\\\n\\t1\t\tallowed(kind(k)) = termsOfKind(k)\n\\end{axdef}\n\n\\subsubsection{DAG}\nA directed, acyclic graph is a directed graph in which no node is reachable from itself.\n\\begin{schema}{DAG}[X]\n\t DiGraph[X]\n\\where\n\t\\LET g == \\theta DiGraph @ \\\\\n\\t1\t\t\\forall T: nodes @ T \\notin reachable(g,T)\n\\end{schema}\n\n\\subsection{$ReplaceShape$}\nThe semantics document introduces the notation $S_{ri}$ for a reduced schema where $S$ is a schema, \n$r$ is a rule-of-one node in a proof tree, and $i$ corresponds to a premise of $r$.\nThe reduced schema is constructed by replacing a shape with one in which the corresponding one-of component is eliminated.\nThis replacement operation is described here.\nThe full definition of $S_{ri}$ is given below following the definition of proof trees.\n\nGiven a schema $S$, a shape label $T$ defined in $S$, and a shape expression $Expr'$, the schema $replaceShape(S,T,Expr')$\nis the schema $S'$ that is the same as $S$ except that $expr(T,S') = Expr'$.\n\\begin{schema}{ReplaceShape}\n\tS, S': SchemaWD \\\\\n\tT: ShapeLabel \\\\\n\tExpr': ShapeExpr \\\\\n\tl: \\nat_1\\\\\n\td, d': ShapeDefinition \\\\\n\tecs: \\seq ExtensionCondition\n\\where\n\tl \\in \\dom S\n\\also\n\tS(l) = (T, d, ecs)\n\\also\n\t\\forall o: OPTIONAL[InclPropSet]; Expr: ShapeExpr | \\\\\n\\t1\t\td = open(o, Expr) @ \\\\\n\\t2\t\t\td' = open(o, Expr')\n\\also\n\t\\forall Expr: ShapeExpr | \\\\\n\\t1\t\td = close(Expr) @ \\\\\n\\t2\t\t\td' = close(Expr')\n\\also\n\tS' = S \\oplus \\{ l \\mapsto (T, d', ecs) \\}\n\\end{schema}\n\n\\begin{axdef}\n\treplaceShape: \\\\\n\\t1\t\tSchemaWF \\cross ShapeLabel \\cross ShapeExpr \\pfun SchemaWF\n\\where\n\treplaceShape = \\{~ ReplaceShape@ (S, T, Expr') \\mapsto S' ~\\}\n\\end{axdef}\n\n\\subsection{$SchemaWD$}\nGiven a well-formed schema $S$, it is said to be well-defined if for each negated label $T$ in $negshapes(T)$, the dependency subgraph\n$dep\\_subgraph(T,S)$ is a directed, acyclic graph.\n\\begin{zed}\n\tSchemaWD == \\\\\n\\t1\t\t\\{~ S: SchemaWF | \\\\\n\\t2\t\t\t\\forall T: negshapes(S) @ \\\\\n\\t3\t\t\t\tdep\\_subgraph(T,S) \\in DAG[ShapeLabel] ~\\}\n\\end{zed}\n\nThe semantics of shape expression schemas is sound only for well-defined schemas.\nOnly well-defined schema will be considered from this point forward.\n\n\\section{Declarative semantics of shape expression schemas}\nRecall that negated triple and inverse triple shape expressions are represented by the corresponding non-negated expressions with cardinality\n$none =$ {\\tt [0;0]}.\n\n\\subsection{$LabelledTriple$}\nA labelled triple is either an incoming or outgoing edge in an RDF graph.\n\\begin{zed}\n\tLabelledTriple ::= \\\\\n\\t1\t\tout \\ldata Triple \\rdata | \\\\\n\\t1\t\tinc \\ldata Triple \\rdata\n\\end{zed}\n\nSometimes labelled triples are referred to simply as triples.\n\n\\subsection{$matches$}\nA labelled triple matches a directed triple constraint when they have the same direction and predicate.\n\\begin{axdef}\n\tmatches: LabelledTriple \\rel DirectedTripleConstraint\n\\where\n\tmatches = matches\\_out \\cup matches\\_inc\n\\end{axdef}\n\n\\subsubsection{$matches\\_out$}\n$matches\\_out$ matches outgoing triples to triple constraints.\n\\begin{zed}\n\tmatches\\_out == \\\\\n\\t1\t\t\\{~ s, p, o: TERM; C: Constraint | \\\\\n\\t2\t\t\t(s,p,o) \\in Triple @ \\\\\n\\t3\t\t\t\tout(s,p,o) \\mapsto (nop(p),C) ~\\}\n\\end{zed}\n\nNote that this definition ignores any value constraints defined in $C$.\nThe absence of restrictions imposed by value constraints makes matching weaker than it could be.\nThis may be an error in the semantics document.\n\nThe semantics documents contains the following text.\n\\begin{quote}\nThe following definition introduces the notion of satisfiability of a shape constraint by a set of triples. Such satisfiability is going to be used for checking that the neighbourhood of a node satisfies locally the constraints defined by a shape expression, without taking into account whether the shapes required by the triple constraints and inverse triple constraints are satisfied.\n\\end{quote}\n\nRead literally, only shape constraints should be ignored, so unless value constraints are handled elsewhere, \nthe semantics document has an error in the definition of $matches$.\n\n\\subsubsection{$matches\\_inc$}\n$matches\\_inc$ matches incoming triples to inverse triple constraints.\n\\begin{zed}\n\tmatches\\_inc == \\\\\n\\t1\t\t\\{~ s, p, o: TERM; C: ShapeConstr | \\\\\n\\t2\t\t\t(s,p,o) \\in Triple @ \\\\\n\\t3\t\t\t\tinc(s,p,o) \\mapsto (inv(p),C) ~\\} \n\\end{zed}\n\n\\subsection{$satifies$}\nA set of labelled triples $Neigh$ is said to satisfy a shape expression $Expr$ if the constraints, other than shape constraints,\ndefined in $Expr$ are satisfied.\n\nNote that the definition of $matches$ ignores both value and shape constraints.\n\n\\begin{axdef}\n\tsatisfies: \\finset LabelledTriple \\rel ShapeExpr\n\\end{axdef}\n\nThis relation is defined recursively by inference rules for each type of shape expression.\n\\begin{zed}\n\tsatisfies = \\\\\n\\t1\t\trule\\_empty \\cup \\\\\n\\t1\t\trule\\_triple\\_constraint \\cup \\\\\n\\t1\t\trule\\_inverse\\_triple\\_constraint \\cup \\\\\n\\t1\t\trule\\_some\\_of \\cup \\\\\n\\t1\t\trule\\_one\\_of \\cup \\\\\n\\t1\t\trule\\_group \\cup \\\\\n\\t1\t\trule\\_repeat\n\\end{zed}\n\n\\subsubsection{$InfRule$}\nAn inference rule defines a relation between a set of labelled triples and a shape expression.\nIt is convenient to define a base schema for the inference rules.\n\\begin{schema}{InfRule}\n\tNeigh: \\finset LabelledTriple \\\\\n\tExpr: ShapeExpr\n\\end{schema}\n\n\\subsubsection{$rule\\_empty$}\nAn empty set of triples satisfies the empty shape expression.\n\\begin{schema}{RuleEmpty}\n\tInfRule\n\\where\n\tExpr = emptyshape\n\\also\n\tNeigh = \\emptyset\n\\end{schema}\n\n\\begin{axdef}\n\trule\\_empty: \\finset LabelledTriple \\rel ShapeExpr\n\\where\n\trule\\_empty = \\\\ \n\\t1\t\t\\{~ RuleEmpty @ Neigh \\mapsto Expr ~\\}\n\\end{axdef}\n\n\\subsubsection{$rule\\_triple\\_constraint$}\nA set of triples satisfies a triple constraint shape expression when each triple matches the constraint\nand the total number of constraints is within the bounds of the cardinality.\n\\begin{schema}{RuleTripleConstraint}\n\tInfRule \\\\\n\tk: \\nat \\\\\n\tp: IRI \\\\\n\tC: Constraint \\\\\n\tc: Cardinality\n\\where\n\tExpr = triple((nop(p),C),c)\n\\also\n\tk = \\# Neigh\n\\also\n\tk \\inrel{inBounds} c\n\\also\n\t\\forall t: Neigh @ t \\inrel{matches} (nop(p),C)\n\\end{schema}\n\n\\begin{axdef}\n\trule\\_triple\\_constraint: \\finset LabelledTriple \\rel ShapeExpr\n\\where\n\trule\\_triple\\_constraint = \\\\\n\\t1\t\t\\{~ RuleTripleConstraint @ Neigh \\mapsto Expr ~\\}\n\\end{axdef}\n\n\\subsubsection{$rule\\_inverse\\_triple\\_constraint$}\nA set of triples satisfies an inverse triple constraint shape expression when each triple matches the constraint\nand the total number of constraints is within the bounds of the cardinality.\n\n\\begin{schema}{RuleInverseTripleConstraint}\n\tInfRule \\\\\n\tk: \\nat \\\\\n\tp: IRI \\\\\n\tC: Constraint \\\\\n\tc: Cardinality\n\\where\n\tExpr = triple((inv(p),C),c)\n\\also\n\tk = \\# Neigh\n\\also\n\tk \\inrel{inBounds} c\n\\also\n\t\\forall t: Neigh @ t \\inrel{matches} (inv(p),C)\n\\end{schema}\n\n\\begin{axdef}\n\trule\\_inverse\\_triple\\_constraint: \\finset LabelledTriple \\rel ShapeExpr\n\\where\n\trule\\_triple\\_constraint = \\\\\n\\t1\t\t\\{~ RuleInverseTripleConstraint @ Neigh \\mapsto Expr ~\\}\n\\end{axdef}\n\n\\subsubsection{$rule\\_some\\_of$}\nA set of triples satisfies a some-of shape expression when the set of triples satisfies one of the component\nshape expressions.\n\\begin{schema}{RuleSomeOf}\n\tInfRule \\\\\n\tExprs: \\seq_1 ShapeExpr \\\\\n\ti: \\nat\n\\where\n\tExpr = someOf(Exprs)\n\\also\n\ti \\in \\dom Exprs\n\\also\n\tNeigh \\inrel{satisfies} Exprs(i)\n\\end{schema}\n\n\\begin{axdef}\n\trule\\_some\\_of: \\finset LabelledTriple \\rel ShapeExpr\n\\where\n\trule\\_some\\_of = \\\\\n\\t1\t\t\\{~ RuleSomeOf @ Neigh \\mapsto Expr ~\\}\n\\end{axdef}\n\n\\subsubsection{$rule\\_one\\_of$}\nA set of triples satisfies a one-of shape expression when the set of triples satisfies one of the component\nshape expressions.\n\\begin{schema}{RuleOneOf}\n\tInfRule \\\\\n\tExprs: \\seq_1 ShapeExpr \\\\\n\ti: \\nat\n\\where\n\tExpr = oneOf(Exprs)\n\\also\n\ti \\in \\dom Exprs\n\\also\n\tNeigh \\inrel{satisfies} Exprs(i)\n\\end{schema}\n\n\\begin{axdef}\n\trule\\_one\\_of: \\finset LabelledTriple \\rel ShapeExpr\n\\where\n\trule\\_one\\_of = \\\\\n\\t1\t\t\\{~ RuleOneOf @ Neigh \\mapsto Expr ~\\}\n\\end{axdef}\n\nThe semantics document contains the following text.\n\\begin{quote}\nNote that the conditions for some-of and one-of shapes are identical. \nThe distinction between both will be made by taking into account also the non-local, shape constraints.\n\\end{quote}\n\n\\subsubsection{$rule\\_group$}\nA set of triples satisfies a group shape expression when the set of triples can be partitioned into a sequence of subsets whose length\nis the same as the sequence of component shape expressions, and each subset satisfies the corresponding component shape expression.\n\\begin{schema}{RuleGroup}\n\tInfRule \\\\\n\tNeighs: \\seq_1 (\\finset LabelledTriple) \\\\\n\tExprs: \\seq_1 ShapeExpr\n\\where\n\tExpr = group(Exprs)\n\\also\n\tNeighs \\partition Neigh\n\\also\n\t\\# Neighs = \\# Exprs\n\\also\n\t\\forall j: \\dom Neighs @ \\\\\n\\t1\t\tNeighs(j) \\inrel{satisfies} Exprs(j)\n\\end{schema}\n\n\\begin{axdef}\n\trule\\_group: \\finset LabelledTriple \\rel ShapeExpr\n\\where\n\trule\\_group = \\\\\n\\t1\t\t\\{~ RuleGroup @ Neigh \\mapsto Expr ~\\}\n\\end{axdef}\n\n\\subsubsection{$rule\\_repeat$}\nA set of triples satisfies a repetition shape expression when the set of triples can be partitioned into a sequence of subsets whose length is\nin the bounds of the cardinality, and each subset satisfies the component shape expression of the repetition shape expression.\n\\begin{schema}{RuleRepeat}\n\tInfRule \\\\\n\tExpr1: ShapeExpr \\\\\n\tNeighs: \\seq_1 (\\finset LabelledTriple) \\\\\n\tk: \\nat \\\\\n\tc: Cardinality\n\\where\n\tExpr = repetition(Expr1,c)\n\\also\n\tk = \\# Neighs\n\\also\n\tk \\inrel{inBounds} c\n\\also\n\tNeighs \\partition Neigh\n\\also\n\t\\forall j: \\dom Neighs @ \\\\\n\\t1\t\tNeighs(j) \\inrel{satisfies} Expr1\n\\end{schema}\n\n\\begin{axdef}\n\trule\\_repeat: \\finset LabelledTriple \\rel ShapeExpr\n\\where\n\trule\\_repeat = \\\\\n\\t1\t\t\\{~ RuleRepeat @ Neigh \\mapsto Expr ~\\}\n\\end{axdef}\n\n\\subsection{Proof Trees}\nThe preceding definition of $satisfies$ is based on the existence of certain characteristics of the set of triples.\nFor example, a set of triples satisfies one of a sequence of shape expressions when it satisfies exactly one of the them, \nbut the $satisfies$ relation forgets the actual shape expression that the set of triples satisfies.\nWe can remember this type of information in a proof tree.\n\n\\subsubsection{$RuleTree$}\nA rule tree is a tree of inference rules and optional child rule trees.\nChild rule trees occur in cases where the inference rule depends on other inference rules.\n\\begin{zed}\n\tRuleTree ::= \\\\\n\\t1\t\truleEmpty \\ldata RuleEmpty \\rdata | \\\\\n\\t1\t\truleTripleConstraint \\ldata RuleTripleConstraint \\rdata | \\\\\n\\t1\t\truleInverseTripleConstraint \\ldata RuleInverseTripleConstraint \\rdata | \\\\\n\\t1\t\truleSomeOf \\ldata RuleSomeOf \\cross RuleTree \\rdata | \\\\\n\\t1\t\truleOneOf \\ldata RuleOneOf \\cross RuleTree \\rdata | \\\\\n\\t1\t\truleGroup \\ldata RuleGroup \\cross \\seq_1 RuleTree \\rdata | \\\\\n\\t1\t\truleRepeat \\ldata RuleRepeat \\cross \\seq_1 RuleTree \\rdata\n\\end{zed}\n\n\\subsubsection{$baseRule$}\nEach node in a rule tree contains an inference rule and, therefore, a base inference rule.\n\\begin{axdef}\n\tbaseRule: RuleTree \\fun InfRule\n\\where\n\t\\forall RuleEmpty @ \\\\\n\\t1\t\t\\LET rule == \\theta RuleEmpty; \\\\\n\\t2\t\t\tbase == \\theta InfRule @ \\\\\n\\t3\t\t\t\tbaseRule(ruleEmpty(rule)) = base\n\\also\n\t\\forall RuleTripleConstraint @ \\\\\n\\t1\t\t\\LET rule == \\theta RuleTripleConstraint; \\\\\n\\t2\t\t\tbase == \\theta InfRule @ \\\\\n\\t3\t\t\tbaseRule(ruleTripleConstraint(rule)) = base\n\\also\n\t\\forall RuleInverseTripleConstraint @ \\\\\n\\t1\t\t\\LET rule == \\theta RuleInverseTripleConstraint; \\\\\n\\t2\t\t\tbase == \\theta InfRule @ \\\\\n\\t3\t\t\t\tbaseRule(ruleInverseTripleConstraint(rule)) = base\n\\also\n\t\\forall RuleSomeOf; tree: RuleTree @ \\\\\n\\t1\t\t\\LET rule == \\theta RuleSomeOf; \\\\\n\\t2\t\t\tbase == \\theta InfRule @ \\\\\n\\t3\t\t\t\tbaseRule(ruleSomeOf(rule,tree)) = base\n\\also\n\t\\forall RuleOneOf; tree: RuleTree @ \\\\\n\\t1\t\t\\LET rule == \\theta RuleOneOf; \\\\\n\\t2\t\t\tbase == \\theta InfRule @ \\\\\n\\t3\t\t\t\tbaseRule(ruleOneOf(rule,tree)) = base\n\\also\n\t\\forall RuleGroup; trees: \\seq_1 RuleTree @ \\\\\n\\t1\t\t\\LET rule == \\theta RuleGroup; \\\\\n\\t2\t\t\tbase == \\theta InfRule @ \\\\\n\\t3\t\t\t\tbaseRule(ruleGroup(rule,trees)) = base\n\\also\n\t\\forall RuleRepeat; trees: \\seq_1 RuleTree @ \\\\\n\\t1\t\t\\LET rule == \\theta RuleRepeat; \\\\\n\\t2\t\t\tbase == \\theta InfRule @ \\\\\n\\t3\t\t\t\tbaseRule(ruleRepeat(rule,trees)) = base\n\\end{axdef}\n\n\\subsubsection{$baseNeigh$}\nEach node in a rule tree has a base set of labelled triples.\n\\begin{axdef}\n\tbaseNeigh: RuleTree \\fun \\finset LabelledTriple\n\\where\n\t\\forall tree: RuleTree @ \\\\\n\\t1\t\tbaseNeigh(tree) = (baseRule(tree)).Neigh\n\\end{axdef}\n\n\\subsubsection{$baseExpr$}\nEach node in a rule tree has a base shape expression.\n\\begin{axdef}\n\tbaseExpr: RuleTree \\fun ShapeExpr\n\\where\n\t\\forall tree: RuleTree @ \\\\\n\\t1\t\tbaseExpr(tree) = (baseRule(tree)).Expr\n\\end{axdef}\n\n\\subsubsection{$ProofTree$}\nA proof tree is a rule tree in which the child trees prove subgoals of their parent nodes.\n\\begin{axdef}\n\tProofTree: \\power RuleTree\n\\end{axdef}\n\nThe definition of proof tree is recursive so it is given by a set of constraints, one for each type of node.\n\nAny rule tree whose root node contains an empty shape expression is a proof tree\nsince it has no subgoals.\n\\begin{zed}\n\t\\ran ruleEmpty \\subset ProofTree\n\\end{zed}\n\nAny rule tree whose root node node contains a triple constraint shape expression is a proof tree\nsince it has no subgoals.\n\\begin{zed}\n\t\\ran ruleTripleConstraint \\subset ProofTree\n\\end{zed}\n\nAny rule tree whose root node node contains an inverse triple constraint shape expression is a proof tree\nsince it has no subgoals.\n\\begin{zed}\n\t\\ran ruleInverseTripleConstraint \\subset ProofTree\n\\end{zed}\n\nA rule tree whose root node contains a some-of shape expression is a proof tree if and only if\nits child rule tree correspond to the distinguished shape expression at index $i$ and it is a proof tree.\n\\begin{zed}\n\t\\forall RuleSomeOf; tree: RuleTree @ \\\\\n\\t1\t\truleSomeOf(\\theta RuleSomeOf, tree) \\in ProofTree \\iff \\\\\n\\t2\t\t\tbaseNeigh(tree) = Neigh \\land \\\\\n\\t2\t\t\tbaseExpr(tree) = Exprs(i) \\land \\\\\n\\t2\t\t\ttree \\in ProofTree\n\\end{zed}\n\nA rule tree whose root node contains a one-of shape expression is a proof tree if and only if\nits child rule tree correspond to the distinguished shape expression at index $i$ and it is a proof tree.\n\\begin{zed}\n\t\\forall RuleOneOf; tree: RuleTree @ \\\\\n\\t1\t\truleOneOf(\\theta RuleOneOf, tree) \\in ProofTree \\iff \\\\\n\\t2\t\t\tbaseNeigh(tree) = Neigh \\land \\\\\n\\t2\t\t\tbaseExpr(tree) = Exprs(i) \\land \\\\\n\\t2\t\t\ttree \\in ProofTree\n\\end{zed}\n\nA rule tree whose root node contains a group shape expression is a proof tree if and only if\nits sequence of child rule trees correspond to its sequence of component neighbourhood and shape expressions\nand each child rule tree is a proof tree.\n\\begin{zed}\n\t\\forall RuleGroup; trees: \\seq_1 RuleTree @ \\\\\n\\t1\t\truleGroup(\\theta RuleGroup, trees) \\in ProofTree \\iff \\\\\n\\t2\t\t\t\\# Exprs = \\# trees \\land \\\\\n\\t2\t\t\t(\\forall i: \\dom trees @ \\\\\n\\t3\t\t\t\tbaseNeigh(trees(i)) = Neighs(i) \\land \\\\\n\\t3\t\t\t\tbaseExpr(trees(i)) = Exprs(i) \\land \\\\\n\\t3\t\t\t\ttrees(i) \\in ProofTree)\n\\end{zed}\n\nA rule tree whose root node contains a repetition shape expression is a proof tree if and only if\nits sequence of child rule trees correspond to its sequence of component neighbourhoods\nand each child rule tree is a proof tree.\n\\begin{zed}\n\t\\forall RuleRepeat; trees: \\seq_1 RuleTree @ \\\\\n\\t1\t\truleRepeat(\\theta RuleRepeat, trees) \\in ProofTree \\iff \\\\\n\\t2\t\t\t\\# Neighs = \\# trees \\land \\\\\n\\t2\t\t\t(\\forall i: \\dom trees @ \\\\\n\\t3\t\t\t\tbaseNeigh(trees(i)) = Neighs(i) \\land \\\\\n\\t3\t\t\t\tbaseExpr(trees(i)) = Expr1 \\land \\\\\n\\t3\t\t\t\ttrees(i) \\in ProofTree)\n\\end{zed}\n\nWe have the following relation between proof trees and the $satisfies$ relation.\n\\[\\vdash\n\tsatisfies = \\\\\n\\t1\t\t\\{~ tree: ProofTree @ baseNeigh(tree) \\mapsto baseExpr(tree) ~\\}\n\\]\n%%\\begin{zed}\n%%\tsatisfies = \\\\\n%%\\t1\t\t\\{~ tree: ProofTree @ baseNeigh(tree) \\mapsto baseExpr(tree) ~\\}\n%%\\end{zed}\n\n\\subsection{Reduced Schema for rule-one-of}\nAs mentioned above, inference rules and proof trees treat rule-one-of exactly the same as rule-some-of.\nThe difference between these rules appears when considering valid typings, which are described in detail later.\n\nLet $t$ be a valid typing of graph $G$ under schema $S$.\nLet $n$ be a node in $G$ and let $T$ be a shape label in $t(n)$.\nLet $Expr = expr(T,S)$ be the shape expression for $T$.\nLet $tree$ be a proof tree that the neighbourhood of $n$ satisfies $Expr$.\nLet $r$ be a node of the proof tree that contains an application of rule-one-of\nand let $i$ be the index of the component expression used in the application of the rule.\nThe intention of the one-of shape expression is that the triples match exactly one of the component expressions.\nTherefore, if the matched shape expression is removed from the one-of expression then there must not be any valid typings\nof $G$ under the reduced schema $S_{ri}$.\n\nNote that a one-of shape expression may have one or more components.\nThe number of components is denoted by $k$ in the inference rule.\nHowever, if it contains exactly one component then there no further semantic conditions that must hold and there\nis no corresponding reduced schema.\nTherefore, the definition of the reduced schema only applies to the case where the number of components is greater than one,\ni.e. $k > 1$.\n\nRule trees are ordered trees.\nA child tree can be specified by giving its index among all the children.\nThe maximum index of a child depends on the type of rule.\nFor leaf trees, the maximum child index is 0.\n\\begin{axdef}\n\tmaxChild: RuleTree \\fun \\nat\n\\where\n\t\\forall tree: \\ran ruleEmpty @ maxChild(tree) = 0\n\\also\n\t\\forall tree: \\ran ruleTripleConstraint @ maxChild(tree) = 0\n\\also\n\t\\forall tree: \\ran ruleInverseTripleConstraint @ maxChild(tree) = 0\n\\also\n\t\\forall tree: \\ran ruleSomeOf @ maxChild(tree) = 1\n\\also\n\t\\forall tree: \\ran ruleOneOf @ maxChild(tree) = 1\n\\also\n\t\\forall r: RuleGroup; trees: \\seq_1 RuleTree @ \\\\\n\\t1\t\tmaxChild(ruleGroup(r,trees)) = \\# trees\n\\also\n\t\\forall r: RuleRepeat; trees: \\seq_1 RuleTree @ \\\\\n\\t1\t\tmaxChild(ruleRepeat(r,trees)) = \\# trees\n\\end{axdef}\n\nGiven a tree $tree$ and a valid child index $j$, the child tree at the index is $childAt(tree,j)$.\n\\begin{axdef}\n\tchildAt: RuleTree \\cross \\nat_1 \\pfun RuleTree\n\\where\n\t\\dom childAt = \\\\\n\\t1\t\t\\{~ tree: RuleTree; ci: \\nat_1 | ci \\leq maxChild(tree) ~\\}\n\\also\n\t\\forall r: RuleSomeOf; tree: RuleTree @ \\\\\n\\t1\t\tchildAt(ruleSomeOf(r,tree),1) = tree\n\\also\n\t\\forall r: RuleOneOf; tree: RuleTree @ \\\\\n\\t1\t\tchildAt(ruleOneOf(r,tree),1) = tree\n\\also\n\t\\forall r: RuleGroup; trees: \\seq_1 RuleTree @ \\\\\n\\t1\t\t\\LET tree == ruleGroup(r,trees) @ \\\\\n\\t2\t\t\t\\forall ci: 1 \\upto maxChild(tree) @ \\\\\n\\t3\t\t\t\tchildAt(tree,ci) = trees(ci)\n\\also\n\t\\forall r: RuleRepeat; trees: \\seq_1 RuleTree @ \\\\\n\\t1\t\t\\LET tree == ruleRepeat(r,trees) @ \\\\\n\\t2\t\t\t\\forall ci: 1 \\upto maxChild(tree) @ \\\\\n\\t3\t\t\t\tchildAt(tree,ci) = trees(ci)\n\\end{axdef}\n\nThe location of a node within a rule tree can be specified by giving a sequence of positive integers that specify the index of each child tree.\nThe root of the tree is specified by the empty sequence.\nSuch a sequence of integers is referred to as a rule path.\nGiven a rule tree $tree$, the set of all of its rule paths is $rulePaths(tree)$.\n\\begin{axdef}\n\trulePaths: RuleTree \\fun \\finset (\\seq \\nat_1)\n\\where\n\t\\forall tree: RuleTree | maxChild(tree) = 0 @ \\\\\n\\t1\t\trulePaths(tree) = \\{ \\langle \\rangle \\}\n\\also\n\t\\forall tree: RuleTree | maxChild(tree) > 0 @ \\\\\n\\t1\t\trulePaths(tree) = \\\\\n\\t2\t\t\t\\bigcup \\{~ ci : 1 \\upto maxChild(tree) @ \\\\\n\\t3\t\t\t\t\\{~ path: rulePaths(childAt(tree,ci)) @ \\langle ci \\rangle \\cat path ~\\} ~\\}\n\\end{axdef}\n\nGiven a rule tree $tree$ and a rule path $path$, the tree node specified by the path is $treeAt(tree,path)$,\n\\begin{axdef}\n\ttreeAt: RuleTree \\cross \\seq \\nat_1 \\pfun RuleTree\n\\where\n\t\\dom treeAt = \\\\\n\\t1\t\t\\{~ tree: RuleTree; path: \\seq \\nat_1 | path \\in rulePaths(tree) ~\\}\n\\also\n\t\\forall tree: RuleTree @ treeAt(tree, \\langle \\rangle) = tree\n\\also\n\t\\forall tree: RuleTree; ci: \\nat_1; path: \\seq \\nat_1 | \\\\\n\\t1\t\t\\langle ci \\rangle \\cat path \\in rulePaths(tree) @ \\\\\n\\t2\t\t\ttreeAt(tree, \\langle ci \\rangle \\cat path) = treeAt(childAt(tree,ci), path)\n\\end{axdef}\n\nGiven a one-of shape expression $Expr$ that has more than one component, and an index $i$ of one component,\n$elimExpr(Expr,i)$ is the reduced expression in which component $i$ is eliminated.\n\\begin{schema}{ElimExpr}\n\tExpr, Expr': ShapeExpr \\\\\n\tExprs, ExprsL, ExprsR: \\seq_1 ShapeExpr \\\\\n\ti: \\nat\n\\where\n\tExpr = oneOf(Exprs)\n\\also\n\t\\# Exprs > 1\n\\also\n\ti \\in \\dom Exprs\n\\also\n\tExprs = ExprsL \\cat \\langle Exprs(i) \\rangle \\cat ExprsR\n\\also\n\tExpr' = oneOf(ExprsL \\cat ExprsR)\n\\end{schema}\n\n\\begin{axdef}\n\telimExpr: ShapeExpr \\cross \\nat \\pfun ShapeExpr\n\\where\n\telimExpr = \\{~ ElimExpr @ (Expr,i) \\mapsto Expr' ~\\}\n\\end{axdef}\n\nGiven a proof tree $tree$ with the shape expression $Expr$ as its base, and a path $path$ to some application $r$ of rule-one-of in $tree$\nin which the rule-of expression has more than one component,\n\\begin{schema}{RuleOneOfApplication}\n\ttree: ProofTree \\\\\n\tpath: \\seq \\nat_1 \\\\\n\tr, rChild: ProofTree \\\\\n\tR: RuleOneOf\n\\where\n\tpath \\in rulePaths(tree)\n\\also\n\tr = treeAt(tree,path) = ruleOneOf(R,rChild)\n\\also\n\t\\# R.Exprs > 1\n\\end{schema}\n\\begin{itemize}\n\\item The path is a valid rule path in the proof tree.\n\\item\tThe tree at the path is an application of rule-one-of.\n\\item There are more than one components in the one-of shape expression.\n\\end{itemize}\n\n$reduceExpr(tree,path)$ is the reduced base shape expression with the corresponding one-of expression in $Expr$ replaced by the reduced one-of expression.\n\\begin{axdef}\n\treduceExpr: ProofTree \\cross \\seq \\nat_1 \\pfun ShapeExpr\n\\where\n\t\\dom reduceExpr = \\{~ RuleOneOfApplication @ (tree,path) ~\\}\n\\also\n\t\\forall RuleOneOfApplication | \\\\\n\\t1\t\tpath = \\langle \\rangle \\land \\\\\n\\t1\t\ttree = r @ \\\\\n\\t2\t\t\treduceExpr(r,\\langle \\rangle) = elimExpr(R.Expr, R.i)\n\\end{axdef}\n\\begin{itemize}\n\\item The domain of this function requires that the path be a valid rule path in the proof tree.\n\\item In the case of an empty path, the tree must be a one-of tree and the branch taken is eliminated.\n\\item When the path is not empty, this function is defined recursively by additional constraints which follow.\nThere are four possible cases in which the proof tree has children. These cases correspond to applications of\nrule-some-of, rule-one-of, rule-group, and rule-repeat.\nEach case is defined by a schema below.\n\\end{itemize}\n\n\\begin{schema}{ReduceSomeOf}\n\tRuleOneOfApplication \\\\\n\tRuleSomeOf \\\\\n\tchild: ProofTree \\\\\n\ttail: \\seq \\nat_1 \\\\\n\tExprsL, ExprsR: \\seq ShapeExpr \\\\\n\tExpr': ShapeExpr\n\\where\n\ttree = ruleSomeOf(\\theta RuleSomeOf, child)\n\\also\n\tpath = \\langle 1 \\rangle \\cat tail\n\\also\n\tExprs = ExprsL \\cat \\langle Exprs(i) \\rangle \\cat ExprsR\n\\also\n\tExpr' = someOf(ExprsL \\cat \\langle reduceExpr(child,tail) \\rangle \\cat ExprsL)\n\\end{schema}\n\n\\begin{zed}\n\t\\forall ReduceSomeOf @ \\\\\n\\t1\t\treduceExpr(tree,path) = Expr'\n\\end{zed}\n\n\\begin{schema}{ReduceOneOf}\n\tRuleOneOfApplication \\\\\n\tRuleOneOf \\\\\n\tchild: ProofTree \\\\\n\ttail: \\seq \\nat_1 \\\\\n\tExprsL, ExprsR: \\seq ShapeExpr \\\\\n\tExpr': ShapeExpr\n\\where\n\ttree = ruleOneOf(\\theta RuleOneOf, child)\n\\also\n\tpath = \\langle 1 \\rangle \\cat tail\n\\also\n\tExprs = ExprsL \\cat \\langle Exprs(i) \\rangle \\cat ExprsR\n\\also\n\tExpr' = oneOf(ExprsL \\cat \\langle reduceExpr(child,tail) \\rangle \\cat ExprsL)\n\\end{schema}\n\n\\begin{zed}\n\t\\forall ReduceOneOf @ \\\\\n\\t1\t\treduceExpr(tree,path) = Expr'\n\\end{zed}\n\n\\begin{schema}{ReduceGroup}\n\tRuleOneOfApplication \\\\\n\tRuleGroup \\\\\n\tchildren: \\seq_1 ProofTree \\\\\n\tci: \\nat_1 \\\\\n\ttail: \\seq \\nat_1 \\\\\n\tExprsL, ExprsR: \\seq ShapeExpr \\\\\n\tExpr': ShapeExpr\n\\where\n\ttree = ruleGroup(\\theta RuleGroup, children)\n\\also\n\tpath = \\langle ci \\rangle \\cat tail\n\\also\n\tExprs = ExprsL \\cat \\langle Exprs(ci) \\rangle \\cat ExprsR\n\\also\n\tExpr' = group(ExprsL \\cat \\langle reduceExpr(children(ci),tail) \\rangle \\cat ExprsL)\n\\end{schema}\n\n\\begin{zed}\n\t\\forall ReduceGroup @ \\\\\n\\t1\t\treduceExpr(tree,path) = Expr'\n\\end{zed}\n\n\\begin{schema}{ReduceRepeat}\n\tRuleOneOfApplication \\\\\n\tRuleRepeat \\\\\n\tchildren: \\seq_1 ProofTree \\\\\n\tci: \\nat_1 \\\\\n\ttail: \\seq \\nat_1 \\\\\n\tExpr': ShapeExpr\n\\where\n\ttree = ruleRepeat(\\theta RuleRepeat, children)\n\\also\n\tpath = \\langle ci \\rangle \\cat tail\n\\also\n\tExpr' = repetition(reduceExpr(children(ci),tail),c)\n\\end{schema}\n\n\\begin{zed}\n\t\\forall ReduceRepeat @ \\\\\n\\t1\t\treduceExpr(tree,path) = Expr'\n\\end{zed}\n\\begin{itemize}\n\\item Something looks wrong here because if a repetition expression has a one-of expression as a child then there is no way\nto associate the reduced one-of expression with just the path taken in the proof tree since all the children of a repetition expression\nshare the same shape expression. However, a rule-repeat node in the proof tree has many children and there is no requirement\nthat all children would use the same branch of the one-of expression.\nTo make progress, I'll assume that all children of the repeat will eliminate the same branch of the one-of.\nI will report this to the mailing list later, along with the observation that the reduction should only one done when a one-of expression\nhas more than one component.\n\\end{itemize}\n\n\\subsection{Witness Mappings}\nGiven a set of labelled triples $Neigh$, a shape expression $Expr$ and a proof tree $tree$ that proves $Neigh$ satisfies $Expr$, \neach labelled triple $triple$ appears in a unique leaf node of the proof tree whose rule matches $triple$ with a directed triple constraint $dtc$.\nThis association of $triple$ with $dtc$ is called a witness mapping, $wm(triple) = dtc$.\n\n\\subsection{$WitnessMapping$}\n\\begin{zed}\n\tWitnessMapping == LabelledTriple \\pfun DirectedTripleConstraint\n\\end{zed}\n\n\\subsubsection{$witness$}\n\\begin{axdef}\n\twitness: ProofTree \\fun WitnessMapping\n\\where\n\t\\forall r: RuleEmpty @ \\\\\n\\t1\t\t\\LET tree == ruleEmpty(r) @ \\\\\n\\t2\t\twitness(tree) = \\emptyset\n\\also\n\t\\forall r: RuleTripleConstraint; dtc: DirectedTripleConstraint; c: Cardinality | \\\\\n\\t1\t\tr.Expr = triple(dtc,c) @ \\\\\n\\t2\t\t\t\\LET tree == ruleTripleConstraint(r) @ \\\\\n\\t3\t\t\t\twitness(tree) = baseNeigh(tree) \\cross \\{dtc\\}\n\\also\n\t\\forall r: RuleInverseTripleConstraint; dtc: DirectedTripleConstraint; c: Cardinality | \\\\\n\\t1\t\tr.Expr = triple(dtc,c) @ \\\\\n\\t2\t\t\t\\LET tree == ruleInverseTripleConstraint(r) @ \\\\\n\\t3\t\t\t\twitness(tree) = baseNeigh(tree) \\cross \\{dtc\\}\n\\also\n\t\\forall r: RuleSomeOf; subtree: ProofTree @ \\\\\n\\t1\t\t\\LET tree == ruleSomeOf(r, subtree) @ \\\\\n\\t2\t\t\ttree \\in ProofTree \\implies \\\\\n\\t3\t\t\t\twitness(tree) = witness(subtree)\n\\also\n\t\\forall r: RuleOneOf; subtree: ProofTree @ \\\\\n\\t1\t\t\\LET tree == ruleOneOf(r, subtree) @ \\\\\n\\t2\t\t\ttree \\in ProofTree \\implies \\\\\n\\t3\t\t\t\twitness(tree) = witness(subtree)\n\\also\n\t\\forall r: RuleGroup; subtrees: \\seq_1 ProofTree @ \\\\\n\\t1\t\t\\LET tree == ruleGroup(r, subtrees) @ \\\\\n\\t2\t\t\ttree \\in ProofTree \\implies \\\\\n\\t3\t\t\t\twitness(tree) = \\bigcup \\{~ subtree: \\ran subtrees @ witness(subtree) ~\\}\n\\also\n\t\\forall r: RuleRepeat; subtrees: \\seq_1 ProofTree @ \\\\\n\\t1\t\t\\LET tree == ruleRepeat(r, subtrees) @ \\\\\n\\t2\t\t\ttree \\in ProofTree \\implies \\\\\n\\t3\t\t\t\twitness(tree) = \\bigcup \\{~ subtree: \\ran subtrees @ witness(subtree) ~\\}\n\\end{axdef}\n\n\\subsection{$outNeigh$}\nThe outgoing neighbourhood of a node $n$ in an RDF graph $G$ is the set of outgoing labelled triples that correspond to triples\nin $G$ with subject $n$.\n\\begin{axdef}\n\toutNeigh: Graph \\cross TERM \\fun \\finset LabelledTriple\n\\where\n\t\\forall G: Graph; n: TERM @ \\\\\n\\t1\t\toutNeigh(G,n) = \\{~ p, o: TERM | (n,p,o) \\in G @ out(n,p,o) ~\\}\n\\end{axdef}\n\n\\subsection{$incNeigh$}\nThe ingoing neighbourhood of a node $n$ in an RDF graph $G$ is the set of ingoing labelled triples that correspond to triples\nin $G$ with object $n$.\n\\begin{axdef}\n\tincNeigh: Graph \\cross TERM \\fun \\finset LabelledTriple\n\\where\n\t\\forall G: Graph; n: TERM @ \\\\\n\\t1\t\tincNeigh(G,n) = \\{~ p, s: TERM | (s,p,n) \\in G @ inc(n,p,s) ~\\}\n\\end{axdef}\n\n\\subsection{$Typing$}\nGiven a schema $S$ and a graph $G$, a typing $t$ is a map that associates to each node $n$ of $G$ a, possibly empty, set $t(n)$ of shape labels and negated shape labels such that if {\\tt T} is a negated shape label then either {\\tt T} or {\\tt !T} is in $t(n)$.\nHere I infer that {\\tt T} and {\\tt !T} are mutually exclusive.\n\nA typing map associates a finite, possibly empty, set of shape verdicts to nodes.\n\\begin{zed}\n\tTyping == TERM \\pfun \\finset ShapeVerdict\n\\end{zed}\n\n\\begin{schema}{TypingMap}\n\tG: Graph \\\\\n\tS: SchemaWD \\\\\n\tt: Typing\n\\where\n\t\\dom t = nodes(G)\n\\also\n\t\\forall n: nodes(G); T: ShapeLabel | assert(T) \\in t(n) @ \\\\\n\\t1\t\tT \\in shapes(S)\n\\also\n\t\\forall n: nodes(G); T: ShapeLabel | negate(T) \\in t(n) @ \\\\\n\\t1\t\tT \\in negshapes(S)\n\\also\n\t\\forall n: nodes(G); T: negshapes(S) @ \\\\\n\\t1\t\tassert(T) \\in t(n) \\lor negate(T) \\in t(n)\n\\also\n\t\\forall n: nodes(G); T: shapes(S) @ \\\\\n\\t1\t\tassert(T) \\notin t(n) \\lor negate(T) \\notin t(n)\n\\end{schema}\n\\begin{itemize}\n\\item The typing associates a set of shape verdicts to each node in the graph.\n\\item If a node is required to satisfy $T$ then $T$ must be a shape label of the schema.\n\\item If a node is required to violate $T$ then $T$ must be a negated shape label of the schema.\n\\item If $T$ is a negated shape label of the schema then each node must be required to either satisfy or violate it.\n\\item No node must be required to both satisfy and violate the same shape.\n\\end{itemize}\n\n\\begin{axdef}\n\ttypings: Graph \\cross SchemaWD \\fun \\power Typing\n\\where\n\t\\forall G: Graph; S: SchemaWD @ \\\\\n\\t1\t\ttypings(G,S) = \\{~ m: TypingMap | m.G = G \\land m.S = S @ m.t ~\\}\n\\end{axdef}\n\n\\subsection{$TypingSatisfies$}\nGiven a typing $t$, a node $u$, and a shape constraint $C$, the typing satisfies the constraint at the node if the \nboolean conditions implied by the shape constraint hold.\n\n\\begin{schema}{TypingSatisfies}\n\tTypingMap \\\\\n\tu: TERM \\\\\n\tC: ShapeConstr \\\\\n\tTs: \\seq_1 ShapeLabel\n\\where\n\tu \\in nodes(G)\n\\also\n\tC = and(Ts) \\implies \\\\\n\\t1\t\t(\\forall T: \\ran Ts @ assert(T) \\in t(u))\n\\also\n\tC = or(Ts) \\implies \\\\\n\\t1\t\t(\\exists T: \\ran Ts @ assert(T) \\in t(u))\n\\also\n\tC = nand(Ts) \\implies \\\\\n\\t1\t\t(\\exists T: \\ran Ts @ negate(T) \\in t(u))\n\\also\n\tC = nor(Ts) \\implies \\\\\n\\t1\t\t(\\forall T: \\ran Ts @ negate(T) \\in t(u))\n\\end{schema}\n\\begin{itemize}\n\\item The node is in the graph.\n\\item The node is required to satisfy every shape in an and shape constraint.\n\\item The node is required to satisfy some shape in an or shape constraint.\n\\item The node is required to violate some shape in a nand shape constraint.\n\\item The node is required to violate every shape in a nor shape constraint.\n\\end{itemize}\n\n\\begin{axdef}\n\ttypingSatisfies: Typing \\cross TERM \\rel ShapeConstr\n\\where\n\ttypingSatisfies = \\\\\n\\t1\t\t\\{~ TypingSatisfies @ (t, u) \\mapsto C ~\\}\n\\end{axdef}\n\n\\subsection{$Matching$}\nGiven a node $n$ in graph $G$, a typing $t$, and a directed triple constraint $X$, let $Matching(G,n,t,X)$ be the set of triples in the graph with focus node $n$ that match $X$ under $t$.\n\n\\begin{schema}{MatchingTriples}\n\tTypingMap \\\\\n\tn, p: TERM \\\\\n\tX: DirectedTripleConstraint \\\\\n\tC: Constraint \\\\\n\ttriples: \\finset LabelledTriple\n\\where\n\tC \\in ValueConstr \\land X = (nop(p),C) \\implies \\\\\n\\t1\t\ttriples = \\{~ u: TERM | (n,p,u) \\in G \\land \\\\\n\\t2\t\t\tu \\in allowed(C)@ out(n,p,u) ~\\}\n\\also\n\tC \\in ShapeConstr \\land X = (nop(p),C) \\implies \\\\\n\\t1\t\ttriples = \\{~ u: TERM | (n,p,u) \\in G \\land \\\\\n\\t2\t\t\t(t,u) \\inrel{typingSatisfies} C @ out(n,p,u) ~\\}\n\\also\n\tC \\in ShapeConstr \\land X = (inv(p),C) \\implies \\\\\n\\t1\t\ttriples = \\{~ u: TERM | (u,p,n) \\in G \\land \\\\\n\\t2\t\t\t(t,u) \\inrel{typingSatisfies} C @ inc(u,p,n) ~\\}\n\\end{schema}\n\\begin{itemize}\n\\item An outgoing triple matches a value constraint if its object is an allowed value.\n\\item An outgoing triple matches a shape constraint if the typing of its object satisfies the constraint.\n\\item An incoming triple matches a shape constraint if the typing of its subject satisfies the constraint.\n\\end{itemize}\n\n\\begin{axdef}\n\tMatching: Graph \\cross TERM \\cross Typing \\cross DirectedTripleConstraint \\fun \\\\\n\\t1\t\t\\finset LabelledTriple\n\\where\n\tMatching = \\{~ MatchingTriples @ (G, n, t, X) \\mapsto triples ~\\}\n\\end{axdef}\n\n\\subsection{$validTypings$}\nThe definition of what it means for a graph to satisfy a shape schema is given in terms of the existence of a valid typing.\nGiven a graph $G$ and a schema $S$, a valid typing of $G$ by $S$ is a typing that satisfies certain additional conditions\nat each node $n$ in $G$.\n\\begin{axdef}\n\tvalidTypings: Graph \\cross SchemaWD \\fun \\power Typing\n\\where\n\t\\forall G: Graph; S: SchemaWD @ \\\\\n\\t1\t\tvalidTypings(G,S) \\subseteq typings(G,S)\n\\end{axdef}\n\n\\subsubsection{$ValidTypingNodeLabel$}\nThe definition of a valid typing is given in terms of a series of conditions that must hold at each node and for each shape verdict at that node.\nIt is convenient to introduce the following base schema for conditions.\n\\begin{schema}{ValidTypingNodeLabel}\n\tTypingMap \\\\\n\tn: TERM \\\\\n\tT: ShapeLabel \\\\\n\truleT: Rule \\\\\n\tdefT: ShapeDefinition \\\\\n\tExpr: ShapeExpr \\\\\n\tXs: \\finset DirectedTripleConstraint\n\\where\n\tt \\in validTypings(G,S)\n\\also\n\tn \\in nodes(G)\n\\also\n\tassert(T) \\in t(n) \\lor negate(T) \\in t(n)\n\\also\n\truleT = rule(T,S) \\\\\n\tdefT = shapeDef(ruleT)\n\\also\n\tExpr = expr(T,S) \\\\\n\tXs = tripleConstraints(Expr)\n\\end{schema}\n\n\\subsubsection{$tripleConstraints$}\nGiven a shape expression $Expr$ let $tripleConstraints(Expr)$ be the set of all triple or inverse triple constraints contained in it.\n\\begin{axdef}\n\ttripleConstraints: ShapeExpr \\fun \\finset DirectedTripleConstraint\n\\where\n\ttripleConstraints(emptyshape) = \\emptyset\n\\also\n\t\\forall dtc: DirectedTripleConstraint; c: Cardinality @ \\\\\n\\t1\t\ttripleConstraints(triple(dtc,c)) = \\{dtc\\}\n\\also\n\t\\forall Exprs: \\seq_1 ShapeExpr @ \\\\\n\\t1\t\ttripleConstraints(someOf(Exprs)) = \\\\\n\\t1\t\ttripleConstraints(oneOf(Exprs)) = \\\\\n\\t1\t\ttripleConstraints(group(Exprs)) = \\\\\n\\t2\t\t\t\\bigcup \\{~ Expr: \\ran Exprs @ tripleConstraints(Expr) ~\\}\n\\also\n\t\\forall Expr: ShapeExpr; c: Cardinality @ \\\\\n\\t1\t\ttripleConstraints(repetition(Expr,c)) = tripleConstraints(Expr)\n\\end{axdef}\n\n\\subsubsection{$NegatedShapeLabel$}\nThe semantics document states:\n\\begin{quote}\nfor all negated shape label !T, if !T $\\in$ t(n), then t1 is not a valid typing, where t1 is the typing that agrees with t everywhere, except for T $\\in$ t1(n)\n\\end{quote}\n\\begin{schema}{NegatedShapeLabel}\n\tValidTypingNodeLabel\n\\where\n\tnegate(T) \\in t(n)\n\\end{schema}\n\\begin{itemize}\n\\item The shape $T$ is negated at node $n$.\n\\end{itemize}\n\n\\subsubsection{$AssertShape$}\n\\begin{schema}{AssertShape}\n\tNegatedShapeLabel \\\\\n\tt1: Typing\n\\where\n\tt1 = t \\oplus \\{ n \\mapsto (t(n) \\setminus \\{negate(T)\\} \\cup \\{assert(T)\\}) \\}\n\\end{schema}\n\\begin{itemize}\n\\item The typing $t1$ is the same as $t$ except that at node $n$ the shape label $T$ is asserted instead of negated.\n\\end{itemize}\n\nIn a valid typing if any node has a negated shape, then the related typing with this shape asserted is invalid.\n\\begin{zed}\n\t\\forall AssertShape @ \\\\\n\\t1\t\tt1 \\notin validTypings(G,S)\n\\end{zed}\nAlthough this condition on $t(n)$ is recursive in terms of the definition of $validTypings$, \nit is well-founded since $t1(n)$ has one fewer negated shapes than $t(n)$. \nTherefore it remains to define the meaning of $validTypings$ for typings that contain no negated shapes.\n\n\\subsubsection{$assertShape$}\nGiven a typing $t$, node $n$, and shape label $T$ such that $negate(T) \\in t(n)$, define $assertShape(t,n,T)$ to be the typing $t1$\nthat is the same as $t$ except that $assert(T) \\in t1(n)$.\n\\begin{axdef}\n\tassertShape: Typing \\cross TERM \\cross ShapeLabel \\pfun Typing\n\\where\n\tassertShape = \\\\\n\\t1\t\t\\{~ AssertShape @ \\\\\n\\t2\t\t\t(t, n, T) \\mapsto t1 ~\\}\n\\end{axdef}\n\n\\subsubsection{$AssertedShapeLabel$}\n\nThe semantics document defines the meaning of valid typings $t$ by imposing several conditions that must hold for all nodes $n$ and all\nasserted shape labels $assert(T) \\in t(n)$.\n\\begin{schema}{AssertedShapeLabel}\n\tValidTypingNodeLabel\n\\where\n\tassert(T) \\in t(n)\n\\end{schema}\n\\begin{itemize}\n\\item The shape label $T$ is asserted at node $n$.\n\\end{itemize}\n\nThe semantics document states that the following conditions must hold for all valid typings $t$ and all nodes $n$ such that $T$ is asserted at $n$:\n\\begin{quote}\nfor all shape label $T$, if $T \\in t(n)$, then there exist three mutually disjoint sets $Matching, OpenProp, Rest$ such that\n\\begin{enumerate}\n\\item $out(G, n) \\cup inc(G, n) = Matching \\cup OpenProp \\cup Rest$, and\n\\item $Rest = Rest_{out} \\cup Rest_{inc}$, where \n\\begin{itemize}\n\\item $Rest_{out} = \\{(out, n, p, u) \\in out(G, n) | p \\notin properties(expr(T, S))\\}$, and \n\\item $Rest_{inc} = \\{(inc, u, p, n) \\in inc(G, n) | p \\notin invproperties(expr(T, S))\\}$, and\n\\end{itemize}\n\\item $Matching$ is the union of the sets $Matching(n, t, X)$ for all triple constraint or inverse triple constraint $X$ that appears in $expr(T, S)$, and\n\\item if $T$ is a closed shape, then $Rest_{out} = \\emptyset$ and $OpenProp = \\emptyset$\n\\item if $T$ is an open shape, then $OpenProp \\subseteq \\{(out, n, p, u) \\in out(G, n) | p \\in incl(T, S)\\}$\n\\item there exists a proof tree with corresponding witness mapping $wm$ for the fact that $Matching$ satisfies $expr(T, S)$, and s.t.\n\\begin{itemize}\n\\item for all outgoing triple $(out, n, p, u)$, it holds $(out, n, p, u) \\in Matching(n, t, wm((out, n, p, u)))$, and moreover if $wm((out, n, p, u))$ is a shape triple constraint, then there is no value triple constraint p::C in $expr(T, S) s.t. (out, n, p, u) \\in Matching(n, t, p::C)$, and\n\\item for all incoming triple $(inc, u, p, n) \\in G$, it holds $(inc, u, p, n) \\in Matching(n, t, wm((inc, u, p, n)))$, and\n\\item for all node $r$ that corresponds to an application of rule-one-of in the proof tree, there does not exist a valid typing $t1$ of $G$ by $S_{ri}$ s.t. $T \\in t1(n)$, and\n\\end{itemize}\n\\item for all extension condition $(lang, cond)$, associated with the type $T$, $f_{lang}(G, n, cond)$ returns true or undefined.\n\\end{enumerate}\n\\end{quote}\n\n\\subsubsection{$MatchingOpenRest$}\n\\begin{quote}\nfor all shape label $T$, if $T \\in t(n)$, then there exist three mutually disjoint sets $Matching, OpenProp, Rest$\n\\end{quote}\n\\begin{schema}{MatchingOpenRest}\n\tAssertedShapeLabel \\\\\n\tMatchingNeigh, OpenProp, Rest: \\finset LabelledTriple\n\\where\n\t\\disjoint \\langle MatchingNeigh, OpenProp, Rest \\rangle\n\\end{schema}\n\\begin{itemize}\n\\item There are three mutually disjoint sets of labelled triples.\n\\item Note that the name $MatchingNeigh$ is used to avoid conflict with the previously defined $Matching$ function.\n\\end{itemize}\n\n\\begin{zed}\n\t\\forall AssertedShapeLabel @ \\\\\n\\t1\t\t\\exists MatchingNeigh, OpenProp, Rest: \\finset LabelledTriple @ \\\\\n\\t2\t\t\tMatchingOpenRest\n\\end{zed}\n\n\\subsubsection{$PartitionNeigh$}\n\\begin{quote}\n$out(G, n) \\cup inc(G, n) = Matching \\cup OpenProp \\cup Rest$\n\\end{quote}\n\\begin{schema}{PartitionNeigh}\n\tMatchingOpenRest\n\\where\n\t\\langle MatchingNeigh, OpenProp, Rest \\rangle \\partition \\\\\n\\t1\t\toutNeigh(G,n) \\cup incNeigh(G,n)\n\\end{schema}\n\n\\begin{zed}\n\t\\forall AssertedShapeLabel @ \\\\\n\\t1\t\t\\exists MatchingNeigh, OpenProp, Rest: \\finset LabelledTriple @ \\\\\n\\t2\t\t\tPartitionNeigh\n\\end{zed}\n\n\n\\subsubsection{$RestDef$}\n\\begin{quote}\n$Rest = Rest_{out} \\cup Rest_{inc}$, where \n\\begin{itemize}\n\\item $Rest_{out} = \\{(out, n, p, u) \\in out(G, n) | p \\notin properties(expr(T, S))\\}$, and \n\\item $Rest_{inc} = \\{(inc, u, p, n) \\in inc(G, n) | p \\notin invproperties(expr(T, S))\\}$, and\n\\end{itemize}\n\\end{quote}\n\\begin{schema}{RestDef}\n\tMatchingOpenRest \\\\\n\tRest\\_out, Rest\\_inc : \\finset LabelledTriple\n\\where\n\tRest = Rest\\_out \\cup Rest\\_inc\n\\also\n\tRest\\_out = \\\\\n\\t1\t\t\\{~ p, u: TERM | \\\\\n\\t2\t\t\tout(n,p,u) \\in outNeigh(G,n) \\land \\\\\n\\t2\t\t\tp \\notin properties(expr(T,S)) @ \\\\\n\\t3\t\t\t\tout(n,p,u) ~\\}\n\\also\n\tRest\\_inc = \\\\\n\\t1\t\t\\{~ p, u: TERM | \\\\\n\\t2\t\t\tinc(u,p,n) \\in incNeigh(G,n) \\land \\\\\n\\t2\t\t\tp \\notin invproperties(expr(T,S)) @\\\\\n\\t3\t\t\t\tinc(u,p,n) ~\\}\n\\end{schema}\n\n\\begin{zed}\n\t\\forall MatchingOpenRest @ \\\\\n\\t1\t\t\\exists_1 Rest\\_out, Rest\\_inc : \\finset LabelledTriple @ \\\\\n\\t2\t\t\tRestDef\n\\end{zed}\n\n\\subsubsection{$MatchingDef$}\n\\begin{quote}\n$Matching$ is the union of the sets $Matching(n, t, X)$ for all triple constraint or inverse triple constraint $X$ that appears in $expr(T, S)$\n\\end{quote}\n\\begin{schema}{MatchingDef}\n\tMatchingOpenRest \n\\where\n\tMatchingNeigh = \\\\\n\\t1\t\t\\bigcup \\{~ X:  Xs @ Matching(G, n, t, X) ~\\}\n\\end{schema}\n\n\\begin{zed}\n\t\\forall MatchingOpenRest @ \\\\\n\\t1\t\tMatchingDef\n\\end{zed}\n\n\\subsubsection{$ClosedShapes$}\n\\begin{quote}\nif $T$ is a closed shape, then $Rest_{out} = \\emptyset$ and $OpenProp = \\emptyset$\n\\end{quote}\n\\begin{schema}{ClosedShapes}\n\tRestDef\n\\where\n\tdefT \\in \\ran close \\implies \\\\\n\\t1\t\tRest\\_out = \\emptyset \\land \\\\\n\\t1\t\tOpenProp = \\emptyset\n\\end{schema}\n\n\\begin{zed}\n\t\\forall RestDef @ \\\\\n\\t1\t\tClosedShapes\n\\end{zed}\n\n\\subsubsection{$OpenShapes$}\n\\begin{quote}\nif $T$ is an open shape, then \n\\[\nOpenProp \\subseteq \\{(out, n, p, u) \\in out(G, n) | p \\in incl(T, S)\\}\n\\]\n\\end{quote}\n\\begin{schema}{OpenShapes}\n\tMatchingOpenRest \\\\\n\\where\n\tdefT \\in \\ran open \\implies \\\\\n\\t1\t\tOpenProp \\subseteq \\\\\n\\t2\t\t\t\\{~ p, u: TERM | \\\\\n\\t3\t\t\t\tout(n,p,u) \\in outNeigh(G,n) \\land \\\\\n\\t3\t\t\t\tp \\in incl(T,S) @ \\\\\n\\t4\t\t\t\t\tout(n,p,u) ~\\}\n\\end{schema}\n\n\\begin{zed}\n\t\\forall MatchingOpenRest @ \\\\\n\\t1\t\tOpenShapes\n\\end{zed}\n\n\\subsubsection{$ProofWitness$}\n\\begin{quote}\nthere exists a proof tree with corresponding witness mapping $wm$ for the fact that $Matching$ satisfies $expr(T, S)$, and s.t.\n\\begin{itemize}\n\\item for all outgoing triple $(out, n, p, u)$, it holds $(out, n, p, u) \\in Matching(n, t, wm((out, n, p, u)))$, and moreover if $wm((out, n, p, u))$ is a shape triple constraint, then there is no value triple constraint p::C in $expr(T, S) s.t. (out, n, p, u) \\in Matching(n, t, p::C)$, and\n\\item for all incoming triple $(inc, u, p, n) \\in G$, it holds $(inc, u, p, n) \\in Matching(n, t, wm((inc, u, p, n)))$, and\n\\item for all node $r$ that corresponds to an application of rule-one-of in the proof tree, there does not exist a valid typing $t1$ of $G$ by $S_{ri}$ s.t. $T \\in t1(n)$, and\n\\end{itemize}\n\\end{quote}\n\\begin{schema}{ProofWitness}\n\tMatchingDef \\\\\n\ttree: ProofTree \\\\\n\twm: WitnessMapping\n\\where\n\tbaseNeigh(tree) = MatchingNeigh \\\\\n\tbaseExpr(tree) = Expr\n\\also\n\twm = witness(tree)\n\\end{schema}\n\n\\begin{zed}\n\t\\forall MatchingDef @ \\\\\n\\t1\t\t\\exists tree: ProofTree; wm: WitnessMapping @ \\\\\n\\t2\t\t\tProofWitness\n\\end{zed}\n\n\\subsubsection{$OutgoingTriples$}\n\\begin{quote}\nfor all outgoing triple $(out, n, p, u)$, it holds \n\\[\n(out, n, p, u) \\in Matching(n, t, wm((out, n, p, u))), \n\\]\nand moreover if $wm((out, n, p, u))$ is a shape triple constraint, then there is no value triple constraint p::C in $expr(T, S)$ s.t. \n\\[\n(out, n, p, u) \\in Matching(n, t, p::C)\n\\]\n\\end{quote}\n\\begin{schema}{OutgoingTriples}\n\tProofWitness\n\\where\n\t\\forall triple: outNeigh(G,n); p, u: TERM | \\\\\n\\t1\t\ttriple = out(n,p,u) @ \\\\\n\\t2\t\t\t\\LET X == wm(triple) @ \\\\\n\\t3\t\t\t\ttriple \\in Matching(G, n, t, X) \\land \\\\\n\\t3\t\t\t\t(constrDTC(X) \\in ShapeConstr \\implies \\\\\n\\t4\t\t\t\t\t\\lnot (\\exists C: ValueConstr | (nop(p),C) \\in Xs @ \\\\\n\\t5\t\t\t\t\t\ttriple \\in Matching(G, n, t, (nop(p),C))))\n\\end{schema}\n\n\\begin{zed}\n\t\\forall ProofWitness @ \\\\\n\\t1\t\tOutgoingTriples\n\\end{zed}\n\n\\subsubsection{$IncomingTriples$}\n\\begin{quote}\nfor all incoming triple $(inc, u, p, n) \\in G$, it holds\n\\[\n(inc, u, p, n) \\in Matching(n, t, wm((inc, u, p, n)))\n\\]\n\\end{quote}\n\\begin{schema}{IncomingTriples}\n\tProofWitness\n\\where\n\t\\forall triple: incNeigh(G,n) @ \\\\\n\\t1\t\t\\LET X == wm(triple) @ \\\\\n\\t2\t\t\ttriple \\in Matching(G, n, t, X)\n\\end{schema}\n\n\\begin{zed}\n\t\\forall ProofWitness @ \\\\\n\\t1\t\tIncomingTriples\n\\end{zed}\n\n\\subsubsection{$OneOfNodes$}\n\\begin{quote}\nfor all node $r$ that corresponds to an application of rule-one-of in the proof tree, \nthere does not exist a valid typing $t1$ of $G$ by $S_{ri}$ s.t. $T \\in t1(n)$\n\\end{quote}\n\nLet $OneOfNodes$ describe the situation where we are\ngiven a graph $G$, a schema $S$, a typing $t$ of $G$ under $S$, a node $n$ in $G$, a shape label $T$\nin $t(n)$, a proof tree $tree$ for the triples $MatchNeigh$ and the expression $Expr= expr(T,S)$ and an application\nof rule-one-of $r$ in the proof tree.\n\n\\begin{schema}{OneOfNodes}\n\tProofWitness \\\\\n\tRuleOneOfApplication \\\\\n\tExpr\\_ri : ShapeExpr \\\\\n\tS\\_ri : SchemaWD\n\\where\n\tExpr\\_ri = reduceExpr(tree, path)\n\\also\n\tS\\_ri = replaceShape(S, T, Expr\\_ri)\n\\end{schema}\n\nWhenever rule-one-of is applied in the proof tree, there must not be any valid typings $t1$\nfor the reduced schema $S\\_ri$ in which the selected component of the one-of shape expression is eliminated.\n\n\\begin{zed}\n\t\\forall OneOfNodes @ \\\\\n\\t1\t\t\\lnot (\\exists t1: validTypings(G,S\\_ri) @ \\\\\n\\t2\t\t\tassert(T) \\in t1(n))\n\\end{zed}\n\n\\subsubsection{$ExtensionConditions$}\n\\begin{quote}\nfor all extension condition $(lang, cond)$, associated with the type $T$, $f_{lang}(G, n, cond)$ returns true or undefined\n\\end{quote}\n\nThe semantics of an extension condition is given by a language oracle function\nthat evaluates the extension condition $cond$ on a pointed graph $(G,n)$\nand returns a code indicating whether the pointed graph\nsatisfies the extension condition, or if an error condition holds, or if the extension condition is undefined.\n\\begin{axdef}\n\tf : ExtLangName \\cross Graph \\cross TERM \\cross ExtDefinition \\fun ReturnCode\n\\where\n\t\\forall G: Graph; n: TERM| (G, n) \\in PointedGraph @ \\\\\n\\t1\t\t\\forall lang: ExtLangName; cond: ExtDefinition @ \\\\\n\\t2\t\t\t\\LET returnCode == f(lang, G, n, cond) @ \\\\\n\\t3\t\t\t\treturnCode = trueRC \\implies (G,n) \\notin violatedBy(lang, cond) \\land \\\\\n\\t3\t\t\t\treturnCode = falseRC \\implies (G,n) \\in violatedBy(lang, cond)\n\\end{axdef}\n\\begin{itemize}\n\\item If the oracle returns true then the pointed graph satisfies the extension condition.\n\\item If the oracle returns false then the pointed graph violates the extension condition.\n\\end{itemize}\n\nLet the return codes for the language oracles be $ReturnCode$.\n\\begin{zed}\n\tReturnCode ::= trueRC | falseRC | errorRC | undefinedRC\n\\end{zed}\n\\begin{itemize}\n\\item true means the extension condition is satisfied.\n\\item false means the extension condition is violated.\n\\item error means an error occurred.\n\\item undefined means the extension condition is undefined.\n\\end{itemize}\n\n\\begin{schema}{ExtensionConditions}\n\tMatchingOpenRest \\\\\n\tlang: ExtLangName \\\\\n\tcond: ExtDefinition\n\\where\n\t\\LET ecs == extConds(ruleT) @ \\\\\n\\t1\t\t(lang,cond) \\in \\ran ecs\n\\end{schema}\n\\begin{itemize}\n\\item $(lang, cond)$ is an extension condition for $T$.\n\\end{itemize}\n\n\\begin{zed}\n\t\\forall ExtensionConditions @ \\\\\n\\t1\t\tf(lang, G, n, cond) \\in \\{trueRC, undefinedRC \\}\n\\end{zed}\n\n\\bibliography{shapes}\n\\end{document}  \n\n", "meta": {"hexsha": "8f89a9a4288e5e17e5b5f77dc83e8c3d7c62a020", "size": 88590, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "core-shacl-formal-semantics/core-shacl-formal-semantics.tex", "max_stars_repo_name": "agryman/data-shapes", "max_stars_repo_head_hexsha": "f82b9b5f8f22344de74506ec4274f2c4e5bd35b4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core-shacl-formal-semantics/core-shacl-formal-semantics.tex", "max_issues_repo_name": "agryman/data-shapes", "max_issues_repo_head_hexsha": "f82b9b5f8f22344de74506ec4274f2c4e5bd35b4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2015-06-16T20:48:13.000Z", "max_issues_repo_issues_event_max_datetime": "2015-06-23T23:53:57.000Z", "max_forks_repo_path": "core-shacl-formal-semantics/core-shacl-formal-semantics.tex", "max_forks_repo_name": "agryman/data-shapes", "max_forks_repo_head_hexsha": "f82b9b5f8f22344de74506ec4274f2c4e5bd35b4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6642512077, "max_line_length": 386, "alphanum_fraction": 0.7200474094, "num_tokens": 26336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011397337391, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.31989711586211583}}
{"text": "\\documentclass{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage[backend=biber]{biblatex}\n\\usepackage{amssymb}\n\\usepackage{amsmath}\n\\usepackage{dsfont}\n\\addbibresource{bib.bib}\n\\setlength{\\parindent}{0em}\n\\bibliography{bib}\n\\setlength{\\parskip}{6pt}\n\\usepackage[margin=1.0in]{geometry}\n\\usepackage{graphicx}\n\\usepackage{caption}\n\\usepackage{subcaption}\n\\usepackage{wrapfig}\n\\usepackage{url}\n\n\\title{Intro to deep learning with PyTorch}\n\\author{Miguel A. Saavedra-Ruiz}\n\\date{Abril 2020}\n\\linespread{1.0}\n\n\\nocite{*}\n\n\n\\begin{document}\n\n\\maketitle\n\n\\section*{Introduction to Neural Networks}\n\nDeep learning is everywhere, applications in games such as Go or jeopardy, detecting spam in emails, forecasting stock prices, recognizing images in a picture, and diagnosing illnesses sometimes with more precision than doctors are just few examples.\n\nThe heart of Deep learning are object called \\textbf{neural networks}. Neural networks vaguely mimic the process of how the brain operates, with neurons that fire bits of information. The next image shows a neural network \\ref{fig:f1}.\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.35\\textwidth,height=0.35\\textheight,keepaspectratio]{images/nn.PNG}\n    \\captionsetup{justification=centering}\n    \\caption{A Neural network}\n    \\label{fig:f1}\n\\end{figure}\n\nA neural network is a function approximator which is capable to split data. Given some data in the form of blue or red points, the neural network will look for the best line that separates the data \\ref{fig:f2}..\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.2\\textwidth,height=0.2\\textheight,keepaspectratio]{images/data.PNG}\n    \\captionsetup{justification=centering}\n    \\caption{A Neural network splitting data}\n    \\label{fig:f2}\n\\end{figure}\n\nThe separation line is called a model and its job is to split the data. A model might not be perfect, but it most be as accurate as possible. Imagine the next example where we plot the acceptance rate of students based on their grades and test scores. The blue dots are accepted and red rejected. Furthermore, the line plotted is \"the model\" Fig. \\ref{fig:f3}.\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.5\\textwidth,height=0.5\\textheight,keepaspectratio]{images/example_1.PNG}\n    \\captionsetup{justification=centering}\n    \\caption{Neural network model}\n    \\label{fig:f3}\n\\end{figure}\n\nBased on that, it is safe to predict that if a point is over the line the student gets accepted and if it's under the line then the student gets rejected.\n\nTaking into account that Test is label as \\(x_1\\) and Grades as \\(x_2\\), the \\textbf{boundary line} that separates the blue and the red points is going to have a linear equation. The equation of the one drawn above is describes in \\eqref{eq:1}.\n\n\\begin{equation}\n2 x_1 + x_2 - 18 = 0 \\label{eq:1}\n\\end{equation}\n\nThe equation \\eqref{eq:1} means that the method for accepting or rejecting students says the following: take this equation as our score where \\(score =2.Test + Grades - 18\\), if a student has \\(score > 0\\) the he gets accepted, otherwise he is rejected. This process is called a prediction. Additionally, by convention it is possible to say that if the score is 0, the student will get accepted although this won't matter much at the end. \\textbf{The linear equation is the model}.\n\nIn the more general case, a boundary will be an equation of the following form \\eqref{eq:2}.\n\n\\begin{equation}\nwx_1+w_2x_2+b=0 \\label{eq:2}\n\\end{equation}  \n\nThe last equation can be abbreviate in vector notation as \\eqref{eq:3}.\n\n\\begin{equation}\nwx+b=0 \\label{eq:3}\n\\end{equation}  \n\nWhere w and x are vectors as shown below:\n\n\\[ w = (w_1, w_2)\\]\n\\[ x = (x_1, x_2)\\]\n\nX can be refereed as the input, w as the weights and b as the bias. For a student coordinates \\(x_1, x_2\\), a label denoted as Y will be used as the value to predict. So if the student gets accepted, namely the point is blue,\nthen the label is \\( y = 1\\), And if the student gets rejected, namely the point is red and then the label is \\( y = 0\\)\n\nThe prediction made by our algorithm is going to be called \\(\\hat{y}\\) and it will be what the algorithm predicts that the label will be \\eqref{eq:4}. Where one means accepted and zero rejected.\n\n\\begin{equation}\n\\label{eq:4}\n\\hat{y} =\n  \\begin{cases}\n    1, & \\text{if } Wx + b \\geq 0 \\\\\n    0, & \\text{if } Wx + b < 0 \\\\\n  \\end{cases}\n\\end{equation}  \n\nSo, to summarize, the points above the line have \\( \\hat{y} = 1\\) and the points below the line have \\( \\hat{y} = 0\\). And, the blue points have \\( y = 1\\) and the red points have \\( y = 0\\).\n\nSubsequently, if we have more data columns so not just testing grades, but maybe something else like the ranking of the student in the class it will turn the problem into a three-dimensional space. The only difference now is that the problem won't be working in two dimensions but three. So now, the three axis are: \\(x_1\\) for the test, \\(x_2\\) for the grades and \\(x_3\\) for the class ranking. The data will looks like Fig. \\ref{fig:f4}.\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.5\\textwidth,height=0.5\\textheight,keepaspectratio]{images/example_2.PNG}\n    \\captionsetup{justification=centering}\n    \\caption{3D data example}\n    \\label{fig:f4}\n\\end{figure}\n\nThe equation won't be a line in two dimension, but a plane in three dimensions with a similar equation as before. Now, the equation would be \\eqref{eq:5} which will separate this space into two regions.\n\n\\begin{equation}\nw_1x_1 + w_2x_2 + w_3x_3 + b = 0, \\label{eq:5}\n\\end{equation}  \n\nThis equation \\eqref{eq:5} can still be abbreviated by \\eqref{eq:3} (\\(wx+b=0\\)) except our vectors will now have three entries instead of two. The prediction will be the same as described by \\eqref{eq:4}.\n\nIf we have many columns like say n of them as shown in Fig. \\ref{fig:f5}, the data just leaps in n-dimensional space. Here the points are just things with n coordinates called \\(x_1, x_2, x_3, \\dots, x_n  \\) with the labels being \\(y\\).\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.5\\textwidth,height=0.5\\textheight,keepaspectratio]{images/multiple_dimension.PNG}\n    \\captionsetup{justification=centering}\n    \\caption{Multi-dimensional data}\n    \\label{fig:f5}\n\\end{figure}\n\nTherefore, the boundaries just an \\(n-1\\) dimensional hyperplane, and the equation of this \\(n-1\\) dimensional hyperplane is going to be the one shown in \\eqref{eq:6} or the abbreviated form shown in \\eqref{eq:3} and the predictions still being the same as shown by equation \\eqref{eq:4}.\n\n\\begin{equation}\nw_1x_1 + w_2x_2 + \\dots + w_n x_n + b = zero, \\label{eq:6}\n\\end{equation}  \n\ne.g Given the table in the Fig. \\ref{fig:f5}, the dimensions for input features (x), the weights (W), and the bias (b) to satisfy (Wx + b) would be \\( W(1xn), x(nx1) \\text{and} b(1x1)\\) for a single student.\n\nNow it is time to introduce the notion of a \\textbf{Perceptron}, which is the building block of neural networks. It is possible to show an example based on Fig. \\ref{fig:f3}, where it is possible to encode the previous equations into a small graph. Let's fit The data and boundary line inside a node. Add small nodes for the inputs which in this case, they are the test and grades. The Fig. \\ref{fig:f6} presents the mention before, with a specific value of test and grades. The Perceptron checks if the point is in the positive or negative area. If the point is in the positive area, then it returns a yes, otherwise a no.\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.5\\textwidth,height=0.5\\textheight,keepaspectratio]{images/perceptron_1.PNG}\n    \\captionsetup{justification=centering}\n    \\caption{Perceptron example with student admission}\n    \\label{fig:f6}\n\\end{figure}\n\nRecall that the prediction consists of accepting the student based on \\(score =2.Test + Grades - 18\\), if the \\( score \\geq 0\\) he gets accepted, and rejecting them if the \\(score < 0\\)\n\nThe weights \\(2\\), \\(1\\) and \\(-18\\) are what define the linear equation, and so they are used as labels in the graph Fig. \\ref{fig:f6}. Another way to graph this node is to consider the bias as part of the input.\n\nSince \\(w_1\\) gets multiplied by \\(x_1\\) and \\(w_2\\) by \\(x_2\\), it's natural to think that \\(b\\) gets multiplied by a one. So the bias will have the B labeling and and edge coming from a one. Then what the node does is it multiplies the values coming from the incoming nodes by the values and the corresponding edges. Then it adds them and finally, it checks if the result is greater than or equal to zero. If it is, then the node returns a yes or a value of one, and if it isn't then the node returns a no or a value of zero as shown in Fig. \\ref{fig:f7}.\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.45\\textwidth,height=0.45\\textheight,keepaspectratio]{images/perceptron_2.PNG}\n    \\captionsetup{justification=centering}\n    \\caption{Perceptron with weights and bias}\n    \\label{fig:f7}\n\\end{figure}\n\nIn the general case, a node looks like the one presented in Fig. \\ref{fig:f8}.The node has inputs coming in with values \\(x_1\\) up to \\(x_n\\) and one (for the bias), and edges with weights \\(w_1\\) up to \\(w_n\\), and \\(b\\) corresponding to the bias unit. Then the node calculates the linear equation \\eqref{eq:3}, which is this case is \\(\\sum_{i=1}^n w_i x_i + B\\). This node then checks if the value is zero or bigger, and if it is, then the node returns a value of one for yes and if not, then it returns a value of zero for no. \n\n\\[wx+b = \\sum_{i=1}^n w_i x_i + b\\]\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.5\\textwidth,height=0.5\\textheight,keepaspectratio]{images/general_perceptron.PNG}\n    \\captionsetup{justification=centering}\n    \\caption{General Perceptron}\n    \\label{fig:f8}\n\\end{figure}\n\nIn the last Figure, an implicit function is being used, this is called a step function. What the step function does is it returns a one if the input is positive or zero if the input is negative Fig. \\ref{fig:f9}.\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.4\\textwidth,height=0.4\\textheight,keepaspectratio]{images/step.PNG}\n    \\captionsetup{justification=centering}\n    \\caption{Step function}\n    \\label{fig:f9}\n\\end{figure}\n\n\\[\ny =\n  \\begin{cases}\n    1, & \\text{if } x \\geq 0 \\\\\n    0, & \\text{if } x < 0 \\\\\n  \\end{cases}\n\\]\n\nIn reality, the perceptron can be seen as a combination of nodes, where the first node calculates a linear equation based on the inputs and weights. The second node applies the step function to the result, giving the final outcome of the perceptron Fig. \\ref{fig:f10}. The \\(\\sum\\) represents a linear function in the first node and the drawing represents a step function in the second node. Nevertheless, we can use different step functions or generally, activation functions in this node.\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.5\\textwidth,height=0.5\\textheight,keepaspectratio]{images/simple_perceptron.PNG}\n    \\captionsetup{justification=centering}\n    \\caption{The simple perceptron}\n    \\label{fig:f10}\n\\end{figure}\n\nThe name \"neural network\" comes from the fact that perceptrons look like neurons in the brain. In the Fig. \\ref{fig:f11} can be seen a perceptron in the Left with four inputs, these inputs are the dendrites in a Neuron and they receive nervous impulses. Similarly, the computation is made in the node of the perceptron or nucleus. Finally, the perceptron outputs the final result as a neuron does through its axon, which is the mechanism a neuron use to outputs nervous impulses. \\textbf{The neural networks mimic the concept of neuron and brain} by taking the output from one neuron and turning it into the input for another one.\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.5\\textwidth,height=0.5\\textheight,keepaspectratio]{images/perceotron_neuron.png}\n    \\captionsetup{justification=centering}\n    \\caption{The perceptron as a neuron}\n    \\label{fig:f11}\n\\end{figure}\n\nPerceptrons can be used as logic operators (AND, OR, XOR). E.g the ND operator can be represented as a two inputs perceptron with 1 output, where the inputs can be 1 or 0 as well as the output. To recall the true table of the perceptron, it is presented in Fig. \\ref{fig:f12}. The perceptron presented in the same figure shows how it splits the points with a boundary line, where the dots in the red area corresponds to a zero and the point in the blue area corresponds to a one. In the file called \\textit{introduction/and\\_perceptron.py} can be seen an example of this which use the general equation of a boundary \\eqref{eq:2} (\\(wx_1+w_2x_2+b=0\\)). \n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.5\\textwidth,height=0.5\\textheight,keepaspectratio]{images/and_table.png}\n    \\captionsetup{justification=centering}\n    \\caption{True table of the AND operator}\n    \\label{fig:f12}\n\\end{figure}\n\nIt is possible to represent logic operators as AND or OR with simple perceptrons, nevertheless, a problem arises when the problem has non-linear boundaries. \n\nTo find the boundary line for a simple logic operator the process is really straightforward. Imagine a classification problem as shown by Fig. \\ref{fig:f13}, the goal is to classify both the blue and red points correctly. However, there are one blue point and red point misclassified. To solve this, one logic approach would be to make the line closer to the misclassified points (located in the blue region) and hence change its label.\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.25\\textwidth,height=0.25\\textheight,keepaspectratio]{images/split_data.png}\n    \\captionsetup{justification=centering}\n    \\caption{Splitting the data example}\n    \\label{fig:f13}\n\\end{figure}\n\nNow imagine the line plotted in Fig. \\ref{fig:f14}, where the line equation is given by \\(3x_1+ 4x_2 - 10 = 0\\) and out labels are: blue area if \\(\\hat{y} > 0\\) or red area if \\(\\hat{y} < 0\\). Suppose that the line has coordinates \\((4,5)\\), based on the approach described above, the point coordinates should be subtracted to the line equation as shown by the equation below, where \\(x_1 = 4, x_2 = 5 \\text{ and } b = 1\\).\n\n\\[\n\\begin{bmatrix}  \\text{new } w_1 \\\\\n                 \\text{new } w_2 \\\\\n                \\text{new } b \\end{bmatrix} = \\begin{bmatrix}\n                                    3 - 4 \\\\\n                                    4 - 5 \\\\\n                                    -10 - 1\n                                    \\end{bmatrix} = \\begin{bmatrix}\n                                                    -1 \\\\\n                                                    -1 \\\\\n                                                    -11\n                                                    \\end{bmatrix}\n\\]\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.25\\textwidth,height=0.25\\textheight,keepaspectratio]{images/moving_line.png}\n    \\captionsetup{justification=centering}\n    \\caption{Making the line closer example}\n    \\label{fig:f14}\n\\end{figure}\n\nWith the new parameters, the equation will be \\(-1x_1+ 4-1x_2 - 11 = 0\\). Nevertheless, this might be a very drastic change in the equation, leading to misclassification of other well-classified points. The idea is to make the line take small moves towards the misclassified point. To solve this, it is neccesary to take small steps towards the point, therefore, a new concept needs to be introduced. This concepts is called \\(\\alpha\\) or \\textbf{learning rate}. The learning rate is a small number between zero and one and its function is to minimize the change in the model equation by multiplying its value to the values of the point. E.g, using a learning rate of \\(0.1\\) and the same example as before, the result will be the shown in the equation and Fig. \\ref{fig:f15}\n\n\\[\n\\begin{bmatrix}  \\text{new } w_1 \\\\\n                 \\text{new } w_2 \\\\\n                \\text{new } b \\end{bmatrix} = \\begin{bmatrix}\n                                    3 - 4*(0.1) \\\\\n                                    4 - 5*(0.1) \\\\\n                                    -10 - 1*(0.1)\n                                    \\end{bmatrix} = \\begin{bmatrix}\n                                                    2.6 \\\\\n                                                    3.5 \\\\\n                                                    -10.1\n                                                    \\end{bmatrix}\n\\]\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.25\\textwidth,height=0.25\\textheight,keepaspectratio]{images/new_line.png}\n    \\captionsetup{justification=centering}\n    \\caption{Moving the line closer to the point}\n    \\label{fig:f15}\n\\end{figure}\n\nSimilarly, if the misclassified point is located in the red area, instead of subtracting the point to the model equation it needs to be added. As a thumb rule, the \\eqref{eq:7} shows the process of adding or substracting based on the point's location.\n\n\\begin{equation}\n\\label{eq:7}\n  \\begin{cases}\n    Substract, & \\text{if } \\text{point is located in region } > 0 \\\\\n    Add, & \\text{if } \\text{point is located in region } < 0 \\\\\n  \\end{cases}\n\\end{equation}  \n\nBased on the technique given above, it is possible to determine the perceptron algorithm. This one is presented in the Fig. \\ref{fig:f16} and shows and iterative process that tries to classify correctly all the misclassified points. The process works iteratively and can run until all the points are correctly classified or a minimum of misclassified points are obtained. A code example of this is given in \\textit{introduction/perceptron\\_algorithm.py}\n  \n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.2\\textwidth,height=0.2\\textheight,keepaspectratio]{images/perceotron_algorithm.png}\n    \\captionsetup{justification=centering}\n    \\caption{The perceptron Pseudocode}\n    \\label{fig:f16}\n\\end{figure}\n  \nLet's look more carefully at the model presented in Fig. \\ref{fig:f3} for accepting and rejecting students. Imagine that the student four got nine in the test but only one on the grades. According to the model this student gets accepted since it's placed in the positive region of this line. Nevertheless, this is not accurate. A more precise model is presented in Fig. \\ref{fig:f7}, however, this is non-linear separable. To create an accurate model a different boundary should be used, two lines, a circle or a polynomial function are just few examples of this. Unfortunately, \\textbf{the perceptron algorithm won't work well for non-linear problems}. Therefore, something more complex needs to be applied to redefine the simple perceptron algorithm for a line in a way that it'll generalize to other types of curves. Nevertheless, this problem will be tackle later.\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.35\\textwidth,height=0.35\\textheight,keepaspectratio]{images/non_linear.png}\n    \\captionsetup{justification=centering}\n    \\caption{Non-linear area}\n    \\label{fig:f17}\n\\end{figure}\n\nTo tackle Deep learning problems, it is necessary to introduce the concept of \\textbf{Error function}. This is simply something that tells how far is the current model from the solution. An example of a simple error function used in the last example would be a function that tells how far is a point from its good classification region (distance).\n\n\\textbf{Gradient descent} is a method to reduce the error of a problem and find the global optimum using known metrics. This algorithm calculates the error and then takes a step towards the direction that minimizes the error in a problem. As an example for the Fig. \\ref{fig:f13} it is possible to construct an error function which consists of the sum of the distance of the points to the boundary lines, where the misclassified points have a big penalty while the well classifies have a low penalty. This function can be used to guide the boundary line towards a direction that minimizes the error and thus, find the optimal model to solve the problem. \\textbf{Note:} the error function should be differentiable and continuous. \n\nRecall that a discrete prediction might be something like a 1 or zero, whereas a continuous prediction would be a number, normally between zero and one. As an example, see the  Fig. \\ref{fig:f18} where we have students with discrete predictions (left) and continuous predictions(right). In the discrete plot, the algorithm will tell if a student is accepted (1 - blue) or rejected (0 - red). In the continuous plot, the farther the point is from the black line, the more drastic these probabilities are. Points that are well into the blue area get very high probabilities And points that are well into the red region are given very low probabilities. The points over the line are all given a 50\\% probability. The probability is a function of the distance from the line.\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.5\\textwidth,height=0.5\\textheight,keepaspectratio]{images/discrete_continuous.png}\n    \\captionsetup{justification=centering}\n    \\caption{Discrete and continuous predictions}\n    \\label{fig:f18}\n\\end{figure}\n\nTo change from discrete to continuous predictions it is necessary to use a \\textbf{Sigmoid function} (Fig. \\ref{fig:f19}) instead of a unitary step as the activation function. This activation will guarantee a continuous functions instead of a discrete one, allowing the usage of gradient descent techniques. The equation of the Sigmoid function is given in the Equation \\eqref{eq:8}. Before the model consisted of a line with a positive region and a negative region. With the Sigmoid function now it consists of an entire probability space for each point in the plane.\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.35\\textwidth,height=0.35\\textheight,keepaspectratio]{images/sigmoid.png}\n    \\captionsetup{justification=centering}\n    \\caption{Sigmoid function}\n    \\label{fig:f19}\n\\end{figure}\n\n\\begin{equation}\n\\label{eq:8}\n\\sigma(x) = \\frac{1}{1 - e^{-x}} \n\\end{equation}  \n\nUsing the Sigmoid function as the activation function to predict \\(\\hat{y}\\), the output of the perceptron will be as follows Eq. \\eqref{eq:9}. The simple perceptron seen in Fig. \\ref{fig:f8} with a step function can be modified as shown by Fig. \\ref{fig:f20} to work with a Sigmoid function as the activation function.  Before it used to say the student got accepted or not, with the Sigmoid function it says the probability of the student got accepted is this much.\n\n\\begin{equation}\n\\label{eq:9}\n\\hat{y} = \\sigma(Wx + b)\n\\end{equation} \n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.30\\textwidth,height=0.30\\textheight,keepaspectratio]{images/perceptron_sigmoid.png}\n    \\captionsetup{justification=centering}\n    \\caption{Simple perceptron with a sigmoid activation function}\n    \\label{fig:f20}\n\\end{figure}\n\n\\textbf{The softmax function} is used when the problem has more than two classes and gives a probability of zero or one being zero as \"not the class\" and one as \"object of this class\". This is the equivalent of the sigmoid activation function, but when the problem has 3 or more classes. It is important to point out that the probability of all classes must add to one and there could not be any negative probability. To define the Softmax function let's imagine that there are N classes and a linear model that gives the following scores \\( Z_1, Z_2, \\dots Z_n\\), each score for each of the classes in the problem. The softmax probability of the class \\(Z_i\\) is defined by the equation \\eqref{eq:10}.\n\n\\begin{equation}\n\\label{eq:10}\nP(\\text{class i}) = \\frac{e^{Z_i}}{e^{Z_i} + \\dots + e^{Z_n}}  = \\frac{e^{Z_i}}{\\sum_k^N e^{Z_k}}\n\\end{equation} \n\nWhen there are multiple output classes, it is necessary to use a specific output format called \\textbf{one-hot encoding}. This format assign one variable per class and outputs a one in the specific class that is selected.  Imagine that the classes are Duck, Beaver and Walrus. Here it is necessary to assign one variable for each of the classes. In the Fig. \\ref{fig:f21} That's one variable for Duck, one for Beaver and one for Walrus And, each one has its corresponding column. E.g., if the input is a duck then the variable for duck is 1 and the variables for beaver and walrus are 0.\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.45\\textwidth,height=0.45\\textheight,keepaspectratio]{images/one_hot.png}\n    \\captionsetup{justification=centering}\n    \\caption{One-hot encoding}\n    \\label{fig:f21}\n\\end{figure}\n\n\\textbf{Maximum likelihood} is when the model picked gives the existing labels the highest probability. Thus, by maximizing the probability, it is possible to pick the best possible model. To use an example of how maximum likelihood works, see the model presented in Fig. \\ref{fig:f22}, where the value presented in each dot is the probability of being blue or red (determined by the color of the number). To determine which model is better, it is necessary to compute the probability of the four points, this probability is called the \\textbf{probability space} and will tell if the points are of the colors that they actually are. For the left model, the probability space is \\(0.1 x 0.6 x 0.7 x 0.2 = 0.0084\\) which is a very small value, whereas for the right model the probability space is \\(0.7 x 0.8 x 0.9 x 0.6 = 0.3024\\). This value means that the probability that the points of the left model are of these colors is 0.0084 and the right model is 0.3024, therefore, it confirms that the model on the right is better because it makes the arrangement of the points much more likely to have those colors. If the likelihood or probability space of the model is improved, hence the model will be better/\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.45\\textwidth,height=0.45\\textheight,keepaspectratio]{images/likelihood.png}\n    \\captionsetup{justification=centering}\n    \\caption{Maximum likelihood example}\n    \\label{fig:f22}\n\\end{figure}\n\nMaximizing the probability is equivalent to minimizing the error function and thus, improve the model. To start with this, it is important to transform the products of the probability of the whole arrangement into a sum, this is possible by passing the individual probabilities in a logarithmic function owing to \\(\\ln{ab} = \\ln{a} + \\ln{b}\\). Applying logarithms to the example shown in Fig. \\ref{fig:f22}, and taking into account that the logarithm of a number between zero and one is always negative, it is possible to use the sum of the negatives of the logarithms instead of a positive sum. Therefore, the model of the left gives \\(\\ln{0.6} - \\ln{0.2} - \\ln{0.1} - \\ln{0.7} = 4.8\\) ad \\(\\ln{0.8} - \\ln{0.6} - \\ln{0.7} - \\ln{0.9} = 1.2\\). This concepts of the negative sum of logarithms is called \\textbf{Cross-entropy} and it gives a high value for bad models (left) and low values for good models (right) which is a measurement of how good the model is. \n\nUsing the Cross Entropy concept in the last example the result can be seen in Fig. \\ref{fig:f23}. The Cross-Entropy of misclassified points have really high values whereas the well classified points have low values. Thus it is possible to think of the negatives of these logarithms as errors at each point. Points that are correctly classified will have small errors and points that are misclassified will have large errors. With this it is feasible to concluded that the cross-entropy will tell us if a model is good or bad. The goal has changed from maximizing a probability to minimizing a cross-entropy in order to get from the model in left to the model in the right in Fig. \\ref{fig:f23}. \\textbf{The error-function is the cross-entropy}.\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.45\\textwidth,height=0.45\\textheight,keepaspectratio]{images/cross_entrophy.png}\n    \\captionsetup{justification=centering}\n    \\caption{Using Cross Entropy example}\n    \\label{fig:f23}\n\\end{figure}\n\nThe formula of the Cross-entropy is given in Eq. \\eqref{eq:11} where \\(y_i\\) is the true label of the class being 1 for blue and 0 for red (see Fig. \\ref{fig:f23}). If \\(y_i\\) is one, then the probability is \\(p_i\\), otherwise the probability will be \\((1 - p_i)\\) which is the probability for \\(y_i = 0\\).\n\n\\begin{equation}\n\\label{eq:11}\nCross-Entropy = - \\sum_{i = 1}^m y_i \\ln{p_i} + (1 - y_i) \\ln{(1 - p_i)}\n\\end{equation} \n\nWhen there are more than two classes, the equation of cross-entropy has to change and find a different expressions to compute these probabilities. In the Fig. \\ref{fig:f24} it is possible to see an example of this. There are three different animal classes and three different \"doors\". Recall that the probability of each column or door must add up to 1. E.g, the probability to obtain a duck from the door two is equals to \\(P_{12}\\).\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.3\\textwidth,height=0.3\\textheight,keepaspectratio]{images/multiple_classes.png}\n    \\captionsetup{justification=centering}\n    \\caption{Multiple classes example}\n    \\label{fig:f24}\n\\end{figure}\n\nExpressing this mathematically as shown by Fig. \\ref{fig:f25} the output \\(y_{ij}\\) is one if a specific class is obtained from the door \\(j\\). Therefore, the equation for \\textbf{multi-class entropy} is given by Eq. \\eqref{eq:12} where m is the number of classes.\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.3\\textwidth,height=0.3\\textheight,keepaspectratio]{images/multiple_notation.png}\n    \\captionsetup{justification=centering}\n    \\caption{Multiple classes notation}\n    \\label{fig:f25}\n\\end{figure}\n\n\\begin{equation}\n\\label{eq:12}\nCross-Entropy = - \\sum_{i = 1}^m \\sum_{j=1}^n y_{ij}  \\ln{p_{ij}}\n\\end{equation} \n\nRecall the Fig. \\ref{fig:f23} where there are two models and the cross-entrophy was calculated. The cross-entropy calculation gave 4.8 for the left model and 1.2 for the right model. The expression given in Eq \\eqref{eq:13} can be used as an error given the following data. Consider that if \\(y = 1\\) which is blue class then \\(P(blue) = \\hat{y}\\), therefore \\(Error = -\\ln{(\\hat{y})}\\). Now, analizing the red classification if \\(y = 0\\) (red class) then \\(P(red) = 1 - P(blue) = 1 - \\hat{y}\\), thus the error for the red class would be \\(Error = -\\ln{(1 - \\hat{y})}\\).\n\nThe last analizis leads to the next Error expression.\n\n\\begin{equation}\n\\label{eq:13}\nError = -(1 - y)(\\ln{(1 - \\hat{y})} - y\\ln{(\\hat{y})}\n\\end{equation} \n\nThe expression given in Eq \\eqref{eq:13} can be used as an error, so changing the notation the error function and averaging by m gives the Equation in \\eqref{eq:14}.\n\n\\begin{equation}\n\\label{eq:14}\nError = - \\frac{1}{m} \\sum_{i=1}^m (1 - y_i) (\\ln{(1 - \\hat{y})}) + y_i\\ln{(\\hat{y})}\n\\end{equation} \n\nWhere \\(\\hat{y}\\) is the output of the network. Transforming \\(\\hat{y}\\) in terms of Eq. \\eqref{eq:9}, the Eq. \\eqref{eq:14} will be as follows (Eq. \\eqref{eq:15}).\n\n\\begin{equation}\n\\label{eq:15}\nE(W,b) = - \\frac{1}{m} \\sum_{i=1}^m (1 - y_i) (\\ln{(1 - \\sigma(Wx^{(i)} + b))}) + y_i\\ln{(\\sigma(Wx^{(i)} + b))}\n\\end{equation} \n\nThe goal is to minimize the Error function given by Eq. \\eqref{eq:15}. Now if there are more than two classes, the only change would be to add the additional summation as shown by Eq. \\eqref{eq:12} to the error function. The Error function for more than one class is given as follows Eq. \\eqref{eq:16}.\n\n\\begin{equation}\n\\label{eq:16}\nE(W,b) = - \\frac{1}{m} \\sum_{i=1}^m \\sum_{j=1}^n y_{ij}\\ln{(\\sigma(Wx^{(ij)} + b))} \n\\end{equation} \n\nMinimizing this error leads to an algorithm called \\textbf{Logistic regression } which is very popular in Machine Learning and AI. The procedure of this algorithm is given as follows:\n\n\\begin{itemize}\n  \\item Take the data\n  \\item Pick a random model\n  \\item Calculate the error\n  \\item Minimize the error, and obtain a better model\n\\end{itemize}\n\nNow, to accomplish the last step of the items and minimize the error it is necessary to use the gradient descent algorithm which will allow the minimization of the error and pass from \\(E(W,b)\\) to \\(E(W',b')\\) where \\(E(W',b') < E(W,b)\\).\n\nImagine a person somewhere in a Mount where the objective is to go down Fig. \\ref{fig:f26}. The inputs of the functions are \\(W_1\\) and \\(W_2\\), the error function is given by E. The gradient of E (\\(\\nabla E\\)) is given by the vector sum of the partial derivatives \\(\\frac{\\partial E}{\\partial w_1}\\) and \\(\\frac{\\partial E}{\\partial w_2}\\). This gradient actually tells the direction the person has to move if he want to increase the error function the most (go up). Thus, taking the negative of the gradient,leads to decrease the error function the most. Taking the negative direction of the gradient will eventually take the person to the bottom of the mountain and decrease the error to a minimum expression. Additinally, taking steps in the direction of the negative of the gradient will also change the Weights and Bias values. This is basically the \\textbf{gradient descent} algorithm. \n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.45\\textwidth,height=0.45\\textheight,keepaspectratio]{images/gradient.png}\n    \\captionsetup{justification=centering}\n    \\caption{Gradient descent example}\n    \\label{fig:f26}\n\\end{figure}\n\nTo calculate the gradient the next equations are used. First of all the initial prediction is given by the next equation.\n\n\\[\\hat{y} = \\sigma(Wx + b)\\]\n\nWriting the prediction in terms of the vectors W and B gives.\n\n\\[\\hat{y} = \\sigma(W_1X_1 + \\dots + W_nX_n + b)\\]\n\nThe gradient of the error function is the vector formed by the partial derivative of the error function with respect to the weights and the bias.\n\n\\[\\nabla E = (\\frac{\\partial E}{\\partial W_1}, \\dots, \\frac{\\partial E}{\\partial W_2}, \\frac{\\partial E}{\\partial b})\\]\n\nTo avoid any drastic changes, a small learning rate alpha is introduced.\n\n\\[\\alpha = 0.1\\]\n\nMultiplying the gradient by the learning rate \\(\\alpha\\) and taking a step is the negative direction of the gradient is the same thing as updating the weights and the bias as follows, where the weight \\(W_i\\) will now become \\(W_i'\\)\n\n\\[w_i' \\leftarrow w_i - \\alpha \\frac{\\partial E}{\\partial W_i}\\]\n\nThe bias will now become:\n\n\\[b_i' \\leftarrow b - \\alpha \\frac{\\partial E}{\\partial b}\\]\n\nThe full derivation of the gradient descent is as follows. First of all, it is necessary to compute the derivative of the sigmoid function (supposing that this is our activation function) which is Eq. \\eqref{eq:17}\n\n\\begin{equation}\n\\label{eq:17}\n\\sigma'(x) = \\sigma(x)(1 - \\sigma(x)) \n\\end{equation} \n\nThe demonstration of the last result is shown below.\n\n\\[\\sigma'(x) = \\frac{\\partial}{\\partial x} \\frac{1}{1 + e ^{-x}}\\]\n\\[\\sigma'(x) = \\frac{e ^{-x}}{(1 + e ^{-x})^2}\\]\n\\[\\sigma'(x) = \\frac{1}{1 + e ^{-x}} \\frac{e ^{-x}}{1 + e ^{-x}}\\]\n\\[\\sigma'(x) = \\sigma(x)(1 - \\sigma(x)) \\]\n\nRecall the Fig. \\ref{fig:f23} where there are m points labeled \\(X^{(1)}, X^{(2)}, \\dots, X^{(m)} \\), thus the error equation would be Eq. \\eqref{eq:14}\n\n\\[E = - \\frac{1}{m} \\sum_{i=1}^m y_i\\ln{(\\hat{y})} + (1 - y_i) (\\ln{(1 - \\hat{y})})\\]\n\nThe goal is to calculate \\(\\nabla E\\), at a point \\(x = (x_1, x_2,\\dots,x_n)\\)), given by the partial derivatives\n\n\\[\\nabla E = \\frac{\\partial E}{\\partial w_1}, \\dots, \\frac{\\partial E}{\\partial w_n}, \\frac{\\partial E}{\\partial b}\\]\n\nTo simplify the calculations, think of the error that each point produces, and calculate the derivative of this error. The total error, then, is the average of the errors at all the points. The error produced by each point is:\n\n\\[ E = -y_i\\ln{(\\hat{y})} - (1 - y_i) (\\ln{(1 - \\hat{y})})\\]\n\nIn order to calculate the derivative of this error with respect to the weights, first calculate \\(\\frac{\\partial \\hat{y}}{\\partial w_j}\\), recalling that \\(\\hat{y} = \\sigma(Wx + b) = \\sigma(\\theta)\\). The \n\n\\[\\frac{\\partial \\hat{y}}{\\partial w_j} = \\frac{\\partial}{\\partial w_j} \\sigma(Wx + b) \\]\n\\[\\frac{\\partial \\hat{y}}{\\partial w_j} = \\sigma(Wx + b)(1 - \\sigma(Wx + b)) \\frac{\\partial}{\\partial w_j}Wx + b \\]\n\\[\\frac{\\partial \\hat{y}}{\\partial w_j} = \\hat{y}(1 - \\hat{y}) \\frac{\\partial}{\\partial w_j}(w_1x_1+\\dots+w_ix_i+\\dots+w_nx_n, + b) \\]\n\\[\\frac{\\partial \\hat{y}}{\\partial w_j} = \\hat{y}(1 - \\hat{y}) x_i \\]\n\nThe last equality is because the only term in the sum which is not a constant with respect to \\(w_j\\) is \\( w_jx_j\\) which clearly has derivative \\(x_j\\).\n\nReall that the gradient descent is based on the chain rule, which would be the one described in Eq. \\eqref{eq:18} where \\(\\theta = Wx + b\\)\n\n\\begin{equation}\n\\label{eq:18}\n\\frac{\\partial E}{\\partial w_j} = \\frac{\\partial E}{\\partial \\hat{y}} \\frac{\\partial \\hat{y}}{\\partial w_j} =  \\frac{\\partial E}{\\partial \\hat{y}} \\frac{\\partial \\sigma(\\theta)}{\\partial \\theta} \\frac{\\partial \\theta}{\\partial w_j}\n\\end{equation} \n\nNow, To calculate the derivative of the error \\(E\\) at a point \\(x\\) with respect to the weight \\(w_j\\) is as follows.\n\n\\[\\frac{\\partial E}{\\partial w_j} = \\frac{\\partial}{\\partial w_j} [-y\\ln{(\\hat{y})} - (1 - y) (\\ln{(1 - \\hat{y})})] \\]\n\\[\\frac{\\partial E}{\\partial w_j} = -y \\frac{\\partial}{\\partial w_j} \\ln{(\\hat{y})} - (1 - y) \\frac{\\partial}{\\partial w_j} \\ln{(1 - \\hat{y})} \\]\n\\[\\frac{\\partial E}{\\partial w_j} = -y \\frac{1}{\\hat{y}} \\frac{\\partial}{\\partial w_i} \\hat{y} - (1 - y) \\frac{1}{1 - \\hat{y}} \\frac{\\partial}{\\partial w_i} (1 - \\hat{y}) \\]\n\\[\\frac{\\partial E}{\\partial w_j} = -y \\frac{1}{\\hat{y}} \\hat{y}(1 - \\hat{y}) x_i - (1 - y) \\frac{1}{1 - \\hat{y}} (-1)(\\hat{y}(1 - \\hat{y}) x_i) \\]\n\\[\\frac{\\partial E}{\\partial w_j} = -y (1 - \\hat{y}) x_i + (1 - y)\\hat{y}x_i \\]\n\\[\\frac{\\partial E}{\\partial w_j} = -(y - \\hat{y})x_i \\]\n\nThe Eq. \\eqref{eq:19} gives the gradient of the weights.\n\n\\begin{equation}\n\\label{eq:19}\n\\frac{\\partial E}{\\partial w_j} = -(y - \\hat{y})x_i\n\\end{equation} \n\nSimilarly, the result for the bias is Eq. \\eqref{eq:20}\n\n\\[ \\frac{\\partial E}{\\partial b} = \\frac{\\partial E}{\\partial \\hat{y}} \\frac{\\partial \\hat{y}}{\\partial b} =  \\frac{\\partial E}{\\partial \\hat{y}} \\frac{\\partial \\sigma(\\theta)}{\\partial \\theta} \\frac{\\partial \\theta}{\\partial b} \\]\n\n\\begin{equation}\n\\label{eq:20}\n\\frac{\\partial E}{\\partial b} = -(y - \\hat{y})\n\\end{equation} \n\nIn summary the gradient is:\n\n\\[\\nabla E = -(y - \\hat{y})(x_1,\\dots ,x_n,1)\\]\n\nTherefore, a small gradient means that it changes the coordinates by a little bit, and a large gradient means it changes the coordinates by a lot.\n\n\\textbf{The gradient descent step} rule to update the weights is as follows Eq. \\eqref{eq:21}\n\n\\begin{equation}\n\\label{eq:21}\nw_i' \\leftarrow w_i - \\alpha-(y - \\hat{y})x_i = w_i + \\alpha(y - \\hat{y})x_i\n\\end{equation}\n\nTo update the bias the equation is the next:\n\n\\begin{equation}\n\\label{eq:22}\nb' \\leftarrow b + \\alpha(y - \\hat{y})\n\\end{equation}\n\nNote: Since the average of the errors were taken, the term added should be \\(\\frac{1}{m}*\\alpha\\) instead of \\(\\alpha\\) but as \\(\\alpha\\) is a constant, then in order to simplify calculations, it is possible to take \\(\\frac{1}{m}*\\alpha\\) to be the learning rate, and abuse the notation by just calling it \\(\\alpha\\).\n\nThe gradient descent algorithm is given in the Fig. \\ref{fig:f27}.\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.45\\textwidth,height=0.45\\textheight,keepaspectratio]{images/gradient_algorithm.png}\n    \\captionsetup{justification=centering}\n    \\caption{Gradient descent algorithm}\n    \\label{fig:f27}\n\\end{figure}\n\nRecall the problem presented in Fig. \\ref{fig:f17}, where the problem was not linear separable. To tackle this problem it is necessary to generate a non-linear probability distribution which accurately classified the blue and red points.\n\\textbf{Nonlinear models} can be generated by the combination of two linear models. To make it possible, see the Fig. \\ref{fig:f28} where in the left are the linear models to be combined, in the middle is the computation of one single point of the model and finally, the result after the application of the sigmoid function. \n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.6\\textwidth,height=0.6\\textheight,keepaspectratio]{images/adding_perceptrons.png}\n    \\captionsetup{justification=centering}\n    \\caption{Adding two perceptrons}\n    \\label{fig:f28}\n\\end{figure}\n\nImagine taking the point highlighted in the Fig. \\ref{fig:f28}, which has a probability of \\(0.7\\) in the first linear model and \\(0.8\\) in the second model. Adding some weights to this model is possible and hence, modify its influence on the result. In this particular example, the first model has a weight of \\(7\\) and the second of \\(5\\). Therefore, the linear equation for the point highlighted gives the next linear combination \\(7*0.7 + 5*0.8 - 6 = 2.9\\), where \\(b = -0.6\\) and \\(P(x_i) = 2.9\\) is the probability of that point being blue. The final step is apply the sigmoid function to approximate the probability to 1, with this the final result of the point is \\(0.95\\) which is the probability of being blue in the resulting probability space. \n\nThe overall steps to generate nonlinear models with linear ones is:\n\n\\begin{itemize}\n  \\item Calculate the probability for one of the points\n  \\item calculate the probability for the other models\n  \\item Add the probabilities times its weights and bias\n  \\item Apply the sigmoid function\n\\end{itemize}\n\nThis might result very simple but this is at the heart of how neural networks work.\n\nThe following image (Fig. \\ref{fig:f29}) shows the representation of the example in Fig. \\ref{fig:f28} but as a combination of nodes and weights. This representation clearly shows how the perceptrons are combined to produce and new non-linear output.\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.25\\textwidth,height=0.25\\textheight,keepaspectratio]{images/adding_perceptrons_2.png}\n    \\captionsetup{justification=centering}\n    \\caption{The perceptrons as a neural network}\n    \\label{fig:f29}\n\\end{figure}\n\nThe Fig. \\ref{fig:f30} is an even more simplified representation of Fig. \\ref{fig:f29} where all the input nodes connects with the middle nodes and these connects to a unique output. Additionally, this representation has the bias in each layer and shows the activation function needed (sigmoid) to obtain a non-linear function in the input.\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.4\\textwidth,height=0.4\\textheight,keepaspectratio]{images/adding_perceptrons_3.png}\n    \\captionsetup{justification=centering}\n    \\caption{The simplified representation of multiple perceptrons in a neural network}\n    \\label{fig:f30}\n\\end{figure}\n\nNeural networks have a certain special \\textbf{architecture} with layers. The first layer is called the input layer, which contains the inputs. The next layer is called the hidden layer, which is a set of linear models created with this first input layer. Then the final layer is called the output layer, where the linear models get combined to obtain a nonlinear model. It is possible to create different architectures with various inputs, hidden layers or outputs. \n\n\\textbf{The number of input} noted defined the dimension of the problem. Two input nodes turn the second layer into a two-dimensional representation whereas three inputs generates three dimensional representations or planes in the hidden layer. \n\n\\textbf{Adding hidden layers} increase the amount of representations that can be generated with the neural network and create more complex boundaries than with only two layers. \n\nFinally, \\textbf{adding more outputs} creates multiple categories and opens the possiblity to classify different things like cat, dogs or birds. \\textbf{Note:} if the model has multiple outputs, it is necessary to change the activation in the last function for a Softmax activation function and add as many outputs as classes are present in the problem. This activation function will guarantee a probability distribution in the last layer and will show which of the classes is the selected one with the highest probability.\n\n\\textbf{Feedforward} is the process neural networks use to turn the input into an output, passing the whole data throughout the network. In the Fig. \\ref{fig:f31} is an example of this with a network with two input layers, two hidden units and one output. The Weights \\(W^{1}\\) corresponds to the weights between the input layer and the hidden layer, for a matter of simplicity, the bias was added to this set of weights. Similarly, the weights \\(W^{2}\\) are between the hidden layer and the output layer. Mathematically, the feedforward process can be expressed as shown by Eq. \\eqref{eq:23}. \\textbf{Note:} the bias are now denoted as \\(W_{31}^{(1)}, W_{32}^{(1)}, W_{31}^{(2)}\\)\n\n\\begin{equation}\n\\label{eq:23}\n\\hat{y} = \\sigma(\\sigma (\\begin{bmatrix}\n           x_{1} \\\\\n           x_{2} \\\\\n           1\n         \\end{bmatrix} \\cdot \\begin{pmatrix}\n                                W_{11}^{(1)} & W_{12}^{(1)} \\\\\n                                W_{21}^{(1)} & W_{22}^{(1)} \\\\\n                                W_{31}^{(1)} & W_{32}^{(1)}\n                                \\end{pmatrix} ) \\cdot \\begin{bmatrix}\n                                                           W_{11}^{(2)} \\\\\n                                                           W_{21}^{(2)} \\\\\n                                                           W_{31}^{(2)}\n                                                         \\end{bmatrix})\n\\end{equation}\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.4\\textwidth,height=0.4\\textheight,keepaspectratio]{images/feedforward.png}\n    \\captionsetup{justification=centering}\n    \\caption{Feedforward in a neural network}\n    \\label{fig:f31}\n\\end{figure}\n\nEquation \\eqref{eq:23} can be simplied into Eq. \\eqref{eq:24}. As a rule of thumb, feedforward takes the input vector and then apply a sequence of linear models and sigmoid functions or whatever activation function is used in the network. The feedforward process is used to obtain the prediction from the input vector. These steps can be extended into more deep networks as the procedure is always the same.\n\n\\begin{equation}\n\\label{eq:24}\n\\hat{y} = \\sigma(\\sigma(W^{(1)} \\cdot X) \\cdot W^{(2)})\n\\end{equation}\n\nThe error function for a multi-layer perceptron is exactly the same used for the perceptron algorithm which is Eq. \\eqref{eq:14} or the Cross-entropy. Similarly, \\(\\hat{y} = \\sigma(Wx + b)\\) but for a neural netowrk with multiple layers, the only difference is that \\(\\hat{y}\\) is more complex and is a combination of multiplications and sigmoid functions as shown here \\[\\hat{y} = \\sigma W^{(3)} \\cdot \\sigma W^{(2)} \\cdot \\sigma W^{(1)} \\cdot X \\]\n\n\\textbf{Backpropagation} is the method used to train multilayer perceptrons or deep neural networks. At a glance, this is the opposite process of feeding forward a neural network, to propagate the error backwards and correct the value of the weights towards a good model or solution. The steps for this algorithm are:\n\n\\begin{itemize}\n  \\item Doing a feedforward operation.\n  \\item Comparing the output of the model with the desired output.\n  \\item Calculating the error.\n  \\item Running the feedforward operation backwards (backpropagation) to spread the error to each of the weights.\n  \\item Use this to update the weights, and get a better model.\n  \\item Continue this until we have a model that is good.\n\\end{itemize}\n\nTo start, recall that for the perceptron algorithm, the prediction was given by Eq. \\eqref{eq:9}, the error is the cross-entropy (Eq. \\eqref{eq:14}) and the objective is to calculate the gradient of the error function \\(\\nabla E = \\frac{\\partial E}{\\partial w_1}, \\dots, \\frac{\\partial E}{\\partial w_n}, \\frac{\\partial E}{\\partial b}\\).\n    \nFor a multilayer perceptron as the one presented in Fig. \\ref{fig:f31}, The prediction is given by Eq. \\eqref{eq:25}, the error function is exactly the same as in the perceptron algorithm Eq. \\eqref{eq:14} and the gradients of the error are the same but with way more calculations Eq. \\eqref{eq:26}.\n    \n\\begin{equation}\n\\label{eq:25}\n\\hat{y} = \\sigma W^{(3)} \\cdot \\sigma W^{(2)} \\cdot \\sigma W^{(1)} \\cdot X\n\\end{equation}\n\n\\begin{equation}\n\\label{eq:26}\n\\nabla E = (\\dots, \\frac{\\partial E}{\\partial w_j^i}, \\dots)\n\\end{equation}\n    \nWriting this more formally, the prediction is a composition of matrix multiplications and sigmoid functions.\n\n\\[\\hat{y} = \\sigma W^{(2)} \\cdot \\sigma W^{(1)} \\cdot x\\]\n\nWhere: \n\n\\[ W^{(1)} = \\begin{pmatrix}\n                                W_{11}^{(1)} & W_{12}^{(1)} \\\\\n                                W_{21}^{(1)} & W_{22}^{(1)} \\\\\n                                W_{31}^{(1)} & W_{32}^{(1)}\n                                \\end{pmatrix} \\]\n\n\\[ W^{(2)} = \\begin{bmatrix}\n               W_{11}^{(2)} \\\\\n               W_{21}^{(2)} \\\\\n               W_{31}^{(2)}\n             \\end{bmatrix}\\]\n                                \nWith a gradient that can be formalized as (in reality \\(\\nabla E\\) is a long vector: \n\n\\[ \\nabla E = \\begin{pmatrix}\n                                \\frac{\\partial E}{\\partial W_{11}^{(1)}} & \\frac{\\partial E}{\\partial W_{12}^{(1)}} & \\frac{\\partial E}{\\partial W_{11}^{(2)}} \\\\\n                                \\frac{\\partial E}{\\partial W_{21}^{(1)}} & \\frac{\\partial E}{\\partial W_{22}^{(1)}} & \\frac{\\partial E}{\\partial W_{11}^{(2)}} \\\\\n                                \\frac{\\partial E}{\\partial W_{31}^{(1)}} & \\frac{\\partial E}{\\partial W_{32}^{(1)}} & \\frac{\\partial E}{\\partial W_{11}^{(2)}} \n                                \\end{pmatrix} \\]\n                                \nThe update step for the backpropagation would be Eq. \\eqref{eq:27}:\n\n\\begin{equation}\n\\label{eq:27}\nW_{ij}^{'k} \\leftarrow W_{ij}^{k} + \\alpha \\frac{\\partial E}{\\partial W_{ij}^{(k)}}\n\\end{equation}\n\nAt this point is important to recall the chain rule, which is presented in the Fig. \\ref{fig:f32}.\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.5\\textwidth,height=0.5\\textheight,keepaspectratio]{images/chain_rule.png}\n    \\captionsetup{justification=centering}\n    \\caption{The chain rule}\n    \\label{fig:f32}\n\\end{figure}\n\n\\[\\frac{\\partial B}{\\partial x} = \\frac{\\partial B}{\\partial A} \\frac{\\partial A}{\\partial x}\\]\n\nTo start with the calculation of the backgropagation algorithm, the first step is to do a forward pass. The hidden nodes and the output nodes have been labeled \\(h_1, h_2, h\\) respectively Fig. \\ref{fig:f33}. The equation of these nodes is given as follows.\n\n\\[h_1 = W_{11}^{(1)}x_1 +  W_{21}^{(1)}x_2 + W_{31}^{(1)}\\]\n\\[h_2 = W_{12}^{(1)}x_1 +  W_{22}^{(1)}x_2 + W_{32}^{(1)}\\]\n\\[h = W_{11}^{(2)}\\sigma(h_1) + W_{21}^{(2)}\\sigma(h_2) + + W_{31}^{(2)}\\]\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.4\\textwidth,height=0.4\\textheight,keepaspectratio]{images/feedforward_pass.png}\n    \\captionsetup{justification=centering}\n    \\caption{A feedforward pass in a MLP}\n    \\label{fig:f33}\n\\end{figure}\n\nSimilarly, the prediction is:\n\n\\[\\hat{y} = \\sigma(h)\\]\n\n\\[\\hat{y} = \\sigma W^{(2)} \\cdot \\sigma W^{(1)} \\cdot x\\]\n\nTo backpropagate the error it is neccesary to calculate the gradients of the error function Eq. \\eqref{eq:14} \\(E(W) = - \\frac{1}{m} \\sum_{i=1}^m y_i\\ln{(\\hat{y})} + (1 - y_i) (\\ln{(1 - \\hat{y})})\\) using the chain rule.\n\nSince the error function is function of the prediction and the prediction is function of the weights the error function can be written as a function of the weights \\(W_{ij}^{k}\\) as follows:\n\n\\[E(W) = E(W_{11}^{(1)}, W_{12}^{(1)}, \\dots, W_{31}^{(2)})\\]\n\nTherefore, the gradient is the vector formed by all the partial derivatives of the error function E with respect to each of the weights.\n\n\\[\\nabla E = (\\frac{\\partial E}{\\partial W_{11}^{(1)}}, \\dots, \\frac{\\partial E}{\\partial W_{31}^{(2)}})\\]\n\nWith this information, it is possible to do an example and calculate the partial derivative of the error with respect to \\(W_{11}^{(1)}\\), this partial derivative is given by the next equation Eq. \\eqref{eq:28}.\n\n\\begin{equation}\n\\label{eq:28}\n\\frac{\\partial E}{\\partial W_{11}^{(1)}} = \\frac{\\partial E}{\\partial \\hat{y}} \\frac{\\partial \\hat{y}}{\\partial h} \\frac{\\partial h}{\\partial h_1} \\frac{\\partial h_1}{\\partial W_{11}^{(1)}}\n\\end{equation}\n\nWhere most of the partial derivatives are already know from the perceptron algorithm Eq. \\eqref{eq:19}, the only new term is: \\(\\frac{\\partial h}{\\partial h_1} \\). The partial derivative of this term is giving by Eq. \\eqref{eq:29} and is based on the partial derivative of the sigmoid function in Eq. \\eqref{eq:17}.\n\n\\begin{equation}\n\\label{eq:29}\n\\frac{\\partial h}{\\partial h_1} = W_{11}^{(2)} \\sigma(h_1)(1 - \\sigma(h_1))\n\\end{equation}\n\nThis process has to be repeated for each of the weights in the neural network but it is mainly the same. If the activation function is changed, then the derivative will change. Nevertheless, the process still being the same and the gradient descent algorithm can be easy applied to different neural networks with multiple layers.\n\nNow that the backpropagtion algorithm has been introduced, it is time to talk about testing. \\textbf{Testing} is the process of evaluating a model with two different tests, the training set and the test set. In the Fig. \\ref{fig:f34} the solid color points are the training set and the points with the white inside are the testing set. The training set is used to train the model without looking the test set and once the model is completely trained, the test set is used to evaluate how good the model is actually doing.\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.4\\textwidth,height=0.4\\textheight,keepaspectratio]{images/testing.png}\n    \\captionsetup{justification=centering}\n    \\caption{Splitting the data into training and test sets}\n    \\label{fig:f34}\n\\end{figure}\n\nOversimplifying the problem means trying a solution that is too simple and won't do the job. In machine learning, this is called \\textbf{underfitting}. On the other hand, when a solution is overly complicated it will probably leads to bad solutions and extra complexity when a simpler solution was just the answer. In machine learning, this is called \\textbf{overfitting}. Generally, an overfitting model fits the data well but it fails when generalizing (error due to variance), whereas an underfitting model generalizes too much and tends to get the dataset bad (error due to bias).\n\nIn the Fig. \\ref{fig:f35} can be seen an example of how a underfitting, just right and overfitting model looks like.\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.6\\textwidth,height=0.6\\textheight,keepaspectratio]{images/under_over.png}\n    \\captionsetup{justification=centering}\n    \\caption{Underfitting and Overfitting models}\n    \\label{fig:f35}\n\\end{figure}\n\nTo try to solve this problem, it is better to always try to go for a slightly overfitting model. The idea is to approach as close as possible to the solution and then use some techniques to avoid overfitting.\n\nOne technique to solve the overfitting issue is called \\textbf{early stopping}, and this is presented in Fig. \\ref{fig:f36}. The plot is called the model complexity graph. In the Y-axis, there is a measure of the error and in the X-axis is a measure of the complexity of the model. In this case, the measure of complexity is the number of epochs. It is possible to see in the figure that in the left are high testing and training error, hence the model is underfitting. In the right, there are a high testing error and low training error, therefore the model is overfitting. Nevertheless in the middle is the right spot to obtain the best train and test error, the main idea of this plot is to determines the number of epochs needed.\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.5\\textwidth,height=0.5\\textheight,keepaspectratio]{images/early.png}\n    \\captionsetup{justification=centering}\n    \\caption{Early stopping}\n    \\label{fig:f36}\n\\end{figure}\n\nAnother technique to stop overfitting is called \\textbf{regularization}. To explain it, first see the Fig. \\ref{fig:f37} which presents two models with exactly the same boundary line. The only difference is that the weights of the model in the right are bigger. This difference in the weights will create a bigger estimate value which being pass through the activation function (sigmoid) will result in values very close to zero and one. However, the left model creates values between zero and one with more disparity. \n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.6\\textwidth,height=0.6\\textheight,keepaspectratio]{images/regularization.png}\n    \\captionsetup{justification=centering}\n    \\caption{Early stopping}\n    \\label{fig:f37}\n\\end{figure}\n\nThis particular situation might leads the thought \"The right model is the best\" despite this is not true. The right model will generate a very well known problem when the gradient descent step is applied which will generate very similar values (0 or 1) when the training is being executed.\n\nOne way to prevent this is use L1 (Eq. \\eqref{eq:30}) and L2 regularization (Eq. \\eqref{eq:31}), which is a technique to prevent the drastic increase in the weights of the network.\n\n\\[\\text{Large Coefficientes} \\rightarrow \\text{Overfitting}\\]\n\n\\begin{equation}\n\\label{eq:30}\n\\text{L1 Error function} = - \\frac{1}{m} \\sum_{i=1}^m y_i\\ln{(\\hat{y})} + (1 - y_i) (\\ln{(1 - \\hat{y})} + \\lambda (|w_1|+\\dots+|w_n|))\n\\end{equation}\n\n\\begin{equation}\n\\label{eq:31}\n\\text{L2 Error function} = - \\frac{1}{m} \\sum_{i=1}^m y_i\\ln{(\\hat{y})} + (1 - y_i) (\\ln{(1 - \\hat{y})} + \\lambda (w_1^2+\\dots+w_n^2))\n\\end{equation}\n\nThe main difference between L1 and L2 is that L1 is good for feature selection because at the end the model end up with sparse vectors \\([0,1,1,0,0]\\) this means that small weights then to go to zero and big ones to one. However, L2 is normally better for training models because it tries to maintain all the weights homogeneously small \\([0.2, 0.5, 0.7 ,0.9, 0.2]\\).\n\n\\textbf{Dropout} is another technique to prevent overfitting. This technique randomly turn off some of the nodes and prevents the data to pass through there. In that case, the other nodes have to pick up the slack and take more part in the training. This process improves the training process a guarantee a good training of all the nodes in the network. Each epoch different nodes are turned off and this is governed by a probability, let's say \\(0.2\\) this probability means that per each epoch, each node has a probability of 20\\% to be turned off. \n\nThere is a problem related to the application of the backpropagation algorithm to minimize the error and it is the \\textbf{local minimums}. A local minimum is a point that doesn't have more apparently logic direction to move which will decrease the error, e.g, Fig. \\ref{fig:f38} presents an example of this. The person is located in a local minimum (yellow point) which for the algorithm seems like the global optimum (green point), nevertheless, this is not.\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.6\\textwidth,height=0.6\\textheight,keepaspectratio]{images/minima.png}\n    \\captionsetup{justification=centering}\n    \\caption{Local minima}\n    \\label{fig:f38}\n\\end{figure}\n\nOne way to solve the local minimum issue is to do \\textbf{random restarts} as a very simple approach. The model starts from a few different random places and do gradient descend from all of them. This increases the probability that the model gets to the global minimum, or at least a pretty good local minimum.\n\n\\textbf{Vanishing gradient} is caused when the derivative of the activation function is small. The sigmoid function is an example of this, the derivative of the regions that are close to one or zero are almost zero, leading to a very small gradient and complicating the propagation of the error backwards (tiny values of gradient leads to small changes in the weights during the training process). This problem gets even worse when more layers are added to the neural network, increasing the number of activation functions and hence, reducing the gradient of the error towards zero.\n\nA solution to the vanishing gradient problem is the use of different activation functions. One of these is the hyperbolic tangent function Eq. \\eqref{eq:32} or the rectified linear unit (ReLU) Eq. \\eqref{eq:33}\n\n\\begin{equation}\n\\label{eq:32}\ntanh(x) = \\frac{e^x - e^{-x}}{e^x + e^{-x}}\n\\end{equation}\n\n\\begin{equation}\n\\label{eq:33}\nrelu(x) = \\begin{cases} \n            x & \\text{if } x \\geq 0  \\\\\n            0 & \\text{if } x < 0\n            \\end{cases}\n\\end{equation}\n\nThe ReLU activation function can be seen in Fig. \\ref{fig:f39}.\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.5\\textwidth,height=0.5\\textheight,keepaspectratio]{images/relu.png}\n    \\captionsetup{justification=centering}\n    \\caption{ReLU activation function}\n    \\label{fig:f39}\n\\end{figure}\n\n\\textbf{Stochastic gradient} descent is a technique to save computation time and find the optimum quicker when the amount of data is huge. The idea behind stochastic gradient descent is simply take small subsets of data, run them through the neural network, calculate the gradient of the error function based on those points and then move one step in that direction. Now, to use all the data it is necessary to split the data into several batches. These batches are then passed through the neural network, one batch per step, until all the batches are passed through the neural network.\n\nThis method will eventually converge to a good solution in the model, not as accurate as the one got with the full batch of data. However, in practice it's much better to take a bunch of slightly inaccurate steps than to take one good one in a lot of time.\n\nThe learning rate is very important during the training of the model. A very high learning rate will make the model oscillate in a local minimum, whereas a small learning rate will take longer to find the minimum but it will eventually find it. As a rule of thumb, it is always better to work with tiny learning rates Fig. \\ref{fig:f40}\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.6\\textwidth,height=0.6\\textheight,keepaspectratio]{images/learning_rate.png}\n    \\captionsetup{justification=centering}\n    \\caption{The impact of learning rates}\n    \\label{fig:f40}\n\\end{figure}\n\nFinally, another way to solve the local minimum problem is with the use of the Momentum. The idea is to walk a bit fast with momentum and determination in a way that if the model gets stuck in a local minimum, it can sort it off and get over the hump to look for a lower minimum Fig. \\ref{fig:f41}.\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.75\\textwidth,height=0.75\\textheight,keepaspectratio]{images/momentum.png}\n    \\captionsetup{justification=centering}\n    \\caption{Momentum}\n    \\label{fig:f41}\n\\end{figure}\n\nMomentum is a constant \\(\\beta\\) between 0 and 1 that attaches to the steps as follows: the previous step gets multiplied by 1, the one before, by beta, the one before, by beta squared, the one before, by beta cubed, etc (Eq. \\eqref{eq:34}). In this way, the steps that happened a long time ago will matter less than the ones that happened recently.\n\n\\begin{equation}\n\\label{eq:34}\nstep(n) = step(n) + \\beta(step_{n-1}) + \\beta^2(step_{n-2}) + \\dots\n\\end{equation}\n\n\\printbibliography\n\n\\end{document}\n", "meta": {"hexsha": "9df1b237f66360938b64b66af9bcb84c61d32d88", "size": 63383, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "introduction_neural_networks/Notes/notes.tex", "max_stars_repo_name": "MikeS96/intro_deep_torch", "max_stars_repo_head_hexsha": "a32be9472e889fd86ae71081cd9a87d839caf077", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "introduction_neural_networks/Notes/notes.tex", "max_issues_repo_name": "MikeS96/intro_deep_torch", "max_issues_repo_head_hexsha": "a32be9472e889fd86ae71081cd9a87d839caf077", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "introduction_neural_networks/Notes/notes.tex", "max_forks_repo_name": "MikeS96/intro_deep_torch", "max_forks_repo_head_hexsha": "a32be9472e889fd86ae71081cd9a87d839caf077", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 66.9303062302, "max_line_length": 1207, "alphanum_fraction": 0.7156808608, "num_tokens": 17448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.629774621301746, "lm_q1q2_score": 0.3198070245189696}}
{"text": "\\documentclass{article}  %Need this.\n\n\\usepackage{amsmath,amsthm,amssymb}\n\n\\usepackage[margin=1in]{geometry}\n\n\n\\newtheorem*{thm}{Theorem}\n\\newtheorem*{cnj}{Conjecture}\n\\newtheorem*{lem}{Lemma}\n\\newtheorem*{cor}{Corollary}\n\\newtheorem*{prop}{Proposition}\n\n\\newcommand{\\N}{\\mathbb{N}}\n\\newcommand{\\Z}{\\mathbb{Z}}\n\\newcommand{\\R}{\\mathbb{R}}\n\n\n\n\n\n\\title{I Heart \\LaTeX}\n\\author{Me!}\n\n\\begin{document}\n\\maketitle\n\n\n\n\nRemember your $\\$$ signs!  $x^2+y^2=1$, $\\frac{a}{b}$.\n\n\\section{Lists}\n%%%%%%%%%%%%%%%\n\\begin{enumerate}\n\\item {\\bf First Point (Bold Face)}\n\\item {\\em Second Point (Italic)}\n\\item {\\Large Third Point (Large Font)}\n    \\begin{enumerate}\n        \\item {\\small First Subpoint (Small Font)} \n        \\item {\\tiny Second Subpoint (Tiny Font)} \n        \\item {\\Huge Third Subpoint (Huge Font)} \n    \\end{enumerate}\n\\item[$\\bullet$] {\\sf Bullet Point (Sans Serif)}\n\\item[$\\circ$] {\\sc Circle Point (Small Caps)} \n\\end{enumerate}\n\n\n\\section{Equations}\n%%%%%%%%%%%%%%%%%%%\n\n\\subsection{Binomial Theorem}\n\\begin{thm}[Binomial Theorem]\nFor any nonnegative integer $n$, we have\n$$(1+x)^n = \\sum_{i=0}^n {n \\choose i} x^i$$\n\\end{thm}\n\n\n\\subsection{Sets}\n\n\\begin{thm}\nFor any sets $A$, $B$ and $C$, we have\n$$ (A\\cup B)-(C-A) = A \\cup (B-C)$$\n\\end{thm}\n\n\\begin{proof}\n\\begin{eqnarray*}\n(A\\cup B)-(C-A) &=& (A\\cup B) \\cap (C-A)^c\\\\\n&=& (A\\cup B) \\cap (C \\cap A^c)^c \\\\\n&=& (A\\cup B) \\cap (C^c \\cup A) \\\\\n&=& A \\cup (B\\cap C^c) \\\\\n&=& A \\cup (B-C)\n\\end{eqnarray*}\n\\end{proof}\n\n\n\n\n\n\\end{document}", "meta": {"hexsha": "74f4c9c8cde459eaf01ef44961fab27da34a3f20", "size": 1494, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "from LDK/LaTeX/TestFile.tex", "max_stars_repo_name": "mkjanssen/discrete", "max_stars_repo_head_hexsha": "4038b6d102000f4eeb27adaa8d0fd2bde63c28ac", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "from LDK/LaTeX/TestFile.tex", "max_issues_repo_name": "mkjanssen/discrete", "max_issues_repo_head_hexsha": "4038b6d102000f4eeb27adaa8d0fd2bde63c28ac", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "from LDK/LaTeX/TestFile.tex", "max_forks_repo_name": "mkjanssen/discrete", "max_forks_repo_head_hexsha": "4038b6d102000f4eeb27adaa8d0fd2bde63c28ac", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.675, "max_line_length": 54, "alphanum_fraction": 0.6104417671, "num_tokens": 553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.31980701746173923}}
{"text": "\\section{Framework description}\n\\label{sec:method}\n\nIn this section, the proposed artificial neural networks-evolutionary algorithm (\\gls{ann-ea}) based method for prognostics is presented. Our method uses a multi-layer perceptron (\\gls{mlp}) as the main regressor for estimating the \\gls{rul} of the engines at each subset of the \\gls{cmaps} dataset. For the training sets, the feature vectors are generated by using a strided time window while the labels vectors are generated using a constant \\gls{rul} for the early cycles of the simulation and then linearly decreasing the number of remaining cycles, this is the so-called piecewise linear degradation model \\citep{Ramasso2014}. For the test set, a time window is taken from the last sensors readings of the engine and used to predict the \\gls{rul} of the engine.\n\nThe window-size $n_w$, window-stride $n_s$, and early-\\gls{rul} $R_e$ data-related parameters, which for the sake of clarity and formalism in this study are considered as components of a vector $\\nu \\in \\mathbb{Z}^3$ such that $\\nu = (n_w, n_s, R_e)$, have a considerable impact on the quality of the predictions made by the regressor. Handpicking the best parameters, i.e. $\\nu$,  is time consuming, furthermore, grid search approaches as the ones used for hyperparameter tuning in neural networks are computationally expensive given the dimension of the search spaces of the data-related parameters. In this paper, we propose the use of an evolutionary algorithm to fine tune the data-related parameters. The optimization framework here proposed allows for the use of a simple neural network architecture while attaining better results in terms of the quality of the predictions made by the other methods in the current literature.\n\n\\subsection{The Neural Network Architecture}\n\nFor this study we propose to use a rather simple \\gls{mlp} architecture and the structure of the network remained consistent for all the four subsets. All the implementations were done in python using the Keras/Tensorflow environment, the source code is publicly available at the git repository \\url{https://github.com/dlaredo/NASA_RUL_-CMAPS-}. \n\nThe choice of the network architecture was made using an iterative process; comparing 6 different architectures, training each for $100$ iterations using a mini-batch size of $512$ and averaging their results over $10$ different runs. Two objectives were pursued: that the architecture was compact, e.g. in terms of layers and neurons within each layer, and that the performance indicators presented in Section \\ref{sec:rul_dataset} were minimized. \n\nThe process for choosing the network architecture is as follows: First, chose a fixed $\\nu$, for the following experiment let $\\nu = (30, 1, 140)$. Next, six different \\gls{ann} architectures are defined, details of the architectures are provided in Appendix \\ref{sec:appendices}. For each of the six different architectures, the performance is assessed using a cross-validation set from subset 1 of \\gls{cmaps}. Table \\ref{table:tested_architectures_100} summarizes the results for each tested architectures while Table \\ref{table:proposed_nn} presents the architecture chosen for the remainder of this work. The chosen architecture provided the best compromise between compactness and performance among the rest of the tested architectures. \n\n\\begin{table}[!htb]\n\\centering\n\n\\begin{tabular}{l | r r r r | r r r r}\n\t\\hline\t\n\t& \\multicolumn{4}{| c}{RMSE} & \\multicolumn{4}{| c}{RHS} \\\\\n\tTested Architecture & Min. & Max. & Avg. & STD & Min. & Max. & Avg. & STD\\\\\n  \t\\hline\n  \tArchitecture 1 & 15.86 & 17.26 & 16.47 & 0.43 & 5.98 & 10.06 & 7.33 & 1.11\\\\\n  \tArchitecture 2 & 15.56 & 17.15 & 16.35 & 0.65 & 6.52 & 20.11 & 4.50 & 4.50\\\\\n  \tArchitecture 3 & 16.07 & 19.18 & 17.67 & 1.12 & 6.91 & 19.18 & 12.78 & 4.72\\\\\n  \tArchitecture 4 & 15.32 & 19.99 & 17.63 & 1.48 & 5.93 & 24 & 13.54 & 6.28\\\\\n  \tArchitecture 5 & 15.70 & 17.24 & 16.37 & 0.49 & 4.84 & 8.57 & 6.35 & 1.25\\\\\n  \tArchitecture 6 & 15.58 & 16.92 & 15.95 & 0.39 & 5.44 & 7.65 & 6.38 & 0.68\\\\\n  \t\\hline\n\\end{tabular}\n\n\\caption{Results for different architectures for subset 1, 100 epochs}\n\\label{table:tested_architectures_100}\n\\end{table}\n\n\\begin{table}[!htb]\n\\centering\n\\begin{tabular}{l l l l}\n\t\\hline\n\tLayer & Shape & Activation & Additional Information\\\\\n  \t\\hline\n  \tHidden layer & 20 & ReLU & L2 regularization factor = 0.2\\\\\n  \tOutput layer & 1 & Linear & \\\\\n  \t\\hline\n\\end{tabular}\n\\caption{Proposed Neural Network architecture}\n\\label{table:proposed_nn}\n\\end{table}\n\n\\subsection{Shaping the data}\n\nThis section covers the data preprocessing applied to the raw sensors readings in each of the datasets. Although the original datasets contains $21$ different sensors readings, some of the sensors do not present much variance or convey redundant information, such sensors are therefore discarded. In the end, only $14$ sensors out of the $21$ are considered for this study, their indices in the \\gls{cmaps} dataset are $\\left\\lbrace 2, 3, 4, 7, 8, 9, 11, 12, 13, 14, 15, 17, 20, 21 \\right\\rbrace$. The raw measurements are then used to create the strided time windows with window-size $n_w$ and window-stride $n_s$. For the training labels, $R_e$ is used at the early stages and then the \\gls{rul} is linearly decreased. The data is also normalized to be within the range $\\left[ -1,1 \\right]$ using the min-max normalization.\n\n\\begin{equation}\n\\hat{x}_i = 2* \\frac{x_i - min(x_i)}{max(x_i) - min(x_i)} - 1,\n\\label{eq:min_max_norm}\n\\end{equation}\nwhere $x_i$ denotes the $m$-dimensional vector whose components are all the readings for the \\textit{i-th} sensor and $\\hat{x}_i$ is the normalized $x_i$ vector.\n\n\\subsubsection{Time Window Processing}\n\nIn multivariate time-series based problems such as \\gls{rul}, more information can be generally obtained from the temporal sequence of data as compared with the multivariate data point at a single time stamp. Let $n_w$ denote the size of the time window, for a time window with a stride $n_s = 1$, all the past sensors values within the time window are collected and put together to form a feature vector $\\mathbf{x}$. This approach has successfully been tested in \\citep{Li2018, Lim2016} where the authors propose the use of a moving window with values raging from 20 to 30. In this paper we propose not only the use of a moving time window, but also a \\textit{strided} time window that updates $n_s$ elements at the time instead of $1$. A graphical depiction of the strided time window is shown in Figure \\ref{fig:time_window}.\n\n\\begin{figure}[!htb]\n\\centering\n\\includegraphics[width=0.9\\textwidth]{../img/time_window.png}\n\\caption{Graphical depiction of the time window used in this framework.}\n\\label{fig:time_window}\n\\end{figure}\n\nThe use of a \\textit{strided time window} allows for the regressor to take advantage not only of the previous information available, but also to control the ratio at which the algorithm is fed with new information. With the usual time window approach only one point is updated for every new time window, on the contrary, the strided time window allows for updating $n_s$ points at the time, allowing for the algorithm to catch newer information with fewer iterations, furthermore, the information contained in the strided time window is likely more rich than the one contained in a time window with stride of one.\n\n\\subsubsection{Piecewise linear degradation model}\n\nDifferent from common regression problems, the desired output value of the input data is difficult to determine for a \\gls{rul} problem. It is usually impossible to evaluate the precise health condition and estimate the \\gls{rul} of the system at each time step without an accurate physics based model. For this kind of applicatios, a piece-wise linear degradation model has been proposed in \\citep{Ramasso2014}. The piece-wise linear degradation model assumes that the engines have a constant \\gls{rul} label in the early cycles and then the \\gls{rul} starts degrading linearly until it reaches 0 as shown in Figure \\ref{fig:piecewise_model}. The piecewise linear degradation approach is used for this work, in here we denote the value for the \\gls{rul} at the early stages as $R_e$. \n\n\\begin{figure}[!htb]\n\\centering\n\\includegraphics[width=0.7\\textwidth]{../img/test_engine.png}\n\\caption{Piecewise linear degradation for \\gls{rul}.}\n\\label{fig:piecewise_model}\n\\end{figure}\n\n\\subsection{Choosing optimal data-related parameters}\n\\label{sec:choosing_otimal_data-related_params}\n\nAs mentioned in the previous sections, the choice of the data-related parameters $\\nu$ has a large impact on the performance of the regressor, i.e. the \\gls{mlp}. In this section we present a framework for picking the optimal combination of the data-related parameters $n_w$, $n_s$ and $R_e$ while being computationally efficient.\n\nRecall that $\\nu = (n_w, n_s, R_e)$, where $n_w \\in \\left[1, b\\right]$, $n_s \\in \\left[1, 10\\right]$, and $R_e \\in \\left[90, 140 \\right]$ are the specific boundaries for the \\gls{cmaps} dataset and all the intervals are integer. The value of $b$ is dependent upon the specific subset, Table \\ref{table:b_values} presents the different values $b$ can take for each dataset.\n\n\\begin{table}[!htb]\n\\centering\n\\begin{tabular}{l | l l l l}\n\t\\hline\n\t & FD001 & FD002 & FD003 & FD004\\\\\n  \t\\hline\n  \t$b$ & 30 & 20 & 30 & 18\\\\\n  \t\\hline\n\\end{tabular}\n\\caption{Allowed values for $b$ per subset}\n\\label{table:b_values}\n\\end{table}\n\nLet also $X(\\nu)$ be the training/cross-val/test sets parametrized by $\\nu$ and used by the \\gls{mlp} to perform the \\gls{rul} estimation. Finally, let $f(\\nu)=e_{rms}(X(\\nu))$, recall from Equation (\\ref{eq:rmse}) that $d = \\hat{y} - y$ and that $\\hat{y}$ depends on $X(\\nu)$, also note that one function evaluation of $f(\\nu)$ implies training the \\gls{mlp} and computing the result of Equation (\\ref{eq:rmse}). Here we propose to fine tune $\\mathbf{\\nu}$, formally speaking\n\n\\begin{equation}\n\\begin{aligned}\n& \\underset{\\nu \\in \\mathbb{Z}^3}{\\text{min}}\n& & f(\\nu) \\\\\n\\end{aligned}\n\\label{eq:optimization_problem}\n\\end{equation}\n\nGiven the nature of the problem at hand; namely that no analytical form of the problem is given, gradient information is unavailable, and the integer nature of the function variables, an evolutionary algorithm is the natural choice for the optimization process.\n\n\\subsubsection{Obtaining the true optimal data-related parameters}\n\nThe size of \\gls{cmaps} dataset and the search space of $\\nu$ allows for an exhaustive search to be performed in order to find the true optimal data-related parameters. We would like to emphasize tough, that although exhaustive search is a possibility for \\gls{cmaps} dataset it is in no way a possibility in a more general setting, therefore the use of the evolutionary algorithm (\\gls{ea}) adopted in this framework. Nevertheless, the possibility to perform exhaustive search on the \\gls{cmaps} dataset can be exploited to demonstrate the accuracy of the chosen \\gls{ea} and of the framework overall. Taking subsets FD001 and FD002 an exhaustive search is performed to find the true optimal values for $\\nu$. The \\gls{mlp} is trained for only $20$ epochs as in this experiment we are only interested in comparing the effect of different combinations for $\\nu$ instead of obtaining the best performance. Table \\ref{table:true_optimal_data_params} shows the optimal as well as the worst combinations of data-related parameters $\\nu$ and the total number of function evaluations used by the exhaustive search.\n\n\\begin{table}[!htb]\n\\centering\n\\begin{tabular}{l | c r c r r l}\n\t\\hline\n\t Dataset & argmin $\\nu$ & min $f(\\nu)$ & argmax $\\nu$ & max $f(\\nu)$ & Function evals.\\\\\n  \t\\hline\n  \tFD001 & $\\left[ 30, 1, 125 \\right]$ & $17.43$ & $\\left[ 19, 1, 97 \\right]$ & $80.92$ & 7500\\\\\n  \tFD002 & $\\left[ 20, 1, 135 \\right]$ & $36.89$ & $\\left[ 19, 10, 109 \\right]$ & $76.80$ & 2500\\\\\n  \t\\hline\n\\end{tabular}\n\\caption{Exhaustive search results for subsets FD001 and F002.}\n\\label{table:true_optimal_data_params}\n\\end{table}\n\n\\subsubsection{Evolutionary algorithms for obtaining the optimal data-related parameters}\n\\label{sec:ea_optimization_process}\n\nEvolutionary algorithms/meta-heuristics are a family of methods that optimize a problem by iteratively trying to improve a set of candidate solutions with regard to a given measure of quality. The methods do not make any assumptions about the problem, treating it as a black box that merely provides a measure of quality given a candidate solution. Furthermore \\glspl{ea} do not require the gradient of the problem being optimized, making them very suitable for applications such as neural networks. Among the drawbacks of this kind of methods are that they usually require considerable computing effort to converge to a solution.\n\nFor this particular application, differential evolution (\\gls{de}) \\citep{Storn1997} is chosen as the optimization algorithm. Though in principle any meta-heuristic capable of handling integer variables is suitable for this application, \\gls{de} has been stablished itself as one of the most reliable, robust and easy to use \\glspl{ea}. Furthermore, a ready to use python implementation of \\gls{de} is available through the scipy package \\citep{scipy}. Although \\gls{de} does not have special operators for treating integer variables a very simple modification to the algorithm, consisting on rounding every component of a candidate solution $\\nu'$ to its nearest integer, is used for this work.\n\nAs mentioned earlier, evolutionary algorithms such as \\gls{de} tend to use several function evaluations for obtaining the optimal solutions, recall that for this application one function evaluations implies retraining the  neural network from scratch. This is not a desirable scenario, as obtaining the optimal data-related parameters $\\nu$ would entail an extensive use of computational power. Instead of running for \\gls{de} for several iterations and with a large population size we propose to run it just for $30$ iterations (generations in the literature of evolutionary computation) and using a population size of $12$, which seems reasonable given the size of the search space of $\\nu$. \n\nFurthermore, during the optimization process the \\gls{mlp} is not trained for  $100$ epochs but for just $20$ instead, this is done mainly for two reasons: the use of the mini-batch in the training process allows for a speed up in the convergence, therefore it can be assumed that the algorithm will most likely be very close to its optima after just a couple of iterations, second and most important is the assumption that parameters that lead to lower score values in the early stages of the \\gls{mlp} training process are more likely to provide better performance when trained for a larger number of epochs. Given the similarities between subsets FD001/FD003 and FD002/FD004 we have decided to just tune $\\nu$ for subsets FD001 and FD002 and then use the obtained results on sets FD003 and FD004 respectively. Details for the use of \\gls{de} in finding the optimum data-related parameters are described in Table \\ref{table:de_hyperparams}.\n\n\\begin{table}[!htb]\n\\centering\n\\begin{tabular}{l l l l l}\n\t\\hline\n\t Population Size & Generations & Strategy & \\gls{mlp} epochs\\\\\n  \t\\hline\n  \t12 & 30 & Best1Bin & 20\\\\\n  \t\\hline\n\\end{tabular}\n\\caption{Differential Evolution hyper-parameters.}\n\\label{table:de_hyperparams}\n\\end{table}\n\n\\begin{comment}\n\\begin{table}[!htb]\n\\centering\n\\begin{tabular}{l l l l l}\n\t\\hline\n\t Dataset & Window Size $n_w$ & Window Stride $n_s$ & Early RUL $R_e$\\\\\n  \t\\hline\n  \tFD001 & 26 & 2 & 100\\\\\n  \tFD002 & 16 & 2 & 91\\\\\n  \tFD003 & 30 & 2 & 97\\\\\n  \tFD004 & 16 & 2 & 92\\\\\n  \t\\hline\n\\end{tabular}\n\\caption{Optimal data-related parameters for each subset.}\n\\label{table:optimal_data_params}\n\\end{table}\n\\end{comment}\n\nThe optimal data-related parameters for each of the subsets found by \\gls{de} are shown in Table \\ref{table:optimal_data_params}. As can be observed the results obtained by \\gls{de} are in fact very close to the real optima (displayed in Table \\ref{table:true_optimal_data_params}) for both datasets, nevertheless the computational burden is reduced by one order of magnitude when using \\gls{de}. From the results in Table \\ref{table:optimal_data_params} it can be observed that the maximum allowable time window is always preferred while, on the contrary, small window strides yield better results, for the case of early RUL it can be observed that large $R_e$ improve the results.\n\n\\begin{table}[!htb]\n\\centering\n\\begin{tabular}{l | c r r l}\n\t\\hline\n\t Dataset & argmin $\\nu$ & min $f(\\nu)$ & Function evals.\\\\\n  \t\\hline\n  \tFD001 & $\\left[ 30, 1, 128 \\right]$ & $17.78$ & 372\\\\\n  \tFD002 & $\\left[ 20, 2, 134 \\right]$ & $37.65$ & 372\\\\\n  \t\\hline\n\\end{tabular}\n\\caption{Data-related parameters for each subset obtained with Differential Evolution.}\n\\label{table:optimal_data_params}\n\\end{table}\n\n\\subsection{The ANN-EA RUL estimation Framework}\n\nHaving described the major building blocks of the proposed method, we now introduce the complete framework in Algorithm \\ref{alg:rul_framework}.\n\n\\setcounter{algorithm}{0}\n\\begin{algorithm}[H]\n\\caption{\\gls{ann}-\\gls{ea} \\gls{rul} estimation Framework}\\label{alg:rul_framework}\n\\textbf{Input:} Initial set of data-related parameters $\\nu \\in \\mathbb{Z}^n$, Raw training/testing data $X$ and training labels $y$\\\\\n\\textbf{Output:} Optimal set of data-related parameters $\\nu^*$\n\t\\begin{algorithmic}[1]\n\t\t\\State Choose regressor architecture (\\gls{ann}, \\gls{svm}, linear/logistic regression, etc).\n\t\t\\State Define $f(\\nu)$ as in Section\\ref{sec:choosing_otimal_data-related_params}.\n\t\t\\State Optimize $f(\\nu)$ using the preferred evolutionary algorithm, i.e. differential evolution, evolutionary strategies, genetic algorithm, etc, using the proposed guidelines from Section \\ref{sec:ea_optimization_process}.\n\t\t\\State Use $\\nu^*$ to train the regressor for as many epochs as needed.\n\t\\end{algorithmic}\n\\end{algorithm}", "meta": {"hexsha": "6cc32a15233db1e2fccd30e6ed617c7101069166", "size": 17986, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Papers/RUL_NN_DE_paper/jmlr_submission/rul_paper_method.tex", "max_stars_repo_name": "dlaredo/NASA_RUL_-CMAPS-", "max_stars_repo_head_hexsha": "b4fc4267e2abb4b0542e4658fd8ee931ba848fd1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2018-05-09T09:18:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T06:37:53.000Z", "max_issues_repo_path": "Papers/RUL_NN_DE_paper/jmlr_submission/rul_paper_method.tex", "max_issues_repo_name": "hard10086/NASA_RUL_-CMAPS-", "max_issues_repo_head_hexsha": "b4fc4267e2abb4b0542e4658fd8ee931ba848fd1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-06-11T09:09:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-08T21:23:07.000Z", "max_forks_repo_path": "Papers/RUL_NN_DE_paper/jmlr_submission/rul_paper_method.tex", "max_forks_repo_name": "hard10086/NASA_RUL_-CMAPS-", "max_forks_repo_head_hexsha": "b4fc4267e2abb4b0542e4658fd8ee931ba848fd1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-07-06T03:40:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T07:30:26.000Z", "avg_line_length": 86.4711538462, "max_line_length": 1108, "alphanum_fraction": 0.7601467808, "num_tokens": 4820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.3197742284357521}}
{"text": "\\chapter{Equivalent current Dipole fitting}\n\\label{ch:eeg_ecd}\n\nThis little chapter demonstrates how to use the ECD (Equivalent Current Dipole) routines with the multimodal dataset available on the FIL website. The aim is to fit a single dipole on the N170 wave visible in the 3 conditions.\nI will briefly describe how to analyse the dataset. For more details about the implementation, please refer to the help bit of and comments in the routines themselves.\n\n\\section{Necessary data}\nBefore proceeding any further, we have to make sure that we have all the necessary data in the right format\nWe need \n\\begin{itemize}\n\\item the {\\it amri.img/hdr} structural MRI of the subject. It will be used to build the head model and display the results in the subject's anatomical space.\\\\\n\\item the {\\it mae\\_eeg.dat/mat} EEG data files. These are the fully processed data with one ERP per condition.\n\\item the coordinates of the sensors, fiducial markers and scalp points (headshape) in 3 distinct {\\it *.mat} files.\n\\end{itemize}\n\nIn the dataset provided on the web, the raw {\\it *.pol} files are available. It is necessary to prepare these files to use them with the source reconstruction routines. This is a crucial step as the registration between the \"EEG space\" and \"patient/image space\" relies entirely on these files! \nTo prepare these files, use the little script {\\it create\\_fid\\_files.m} distributed with SPM5. A copy is also available at the end of this chapter.\n\nOnce we have all the files ready, we can proceed with the 3 main steps: building the model, fitting the dipole and displaying the results. To launch the GUI, press \"3D source reconstruction\" in the main window of SPM.\n\n\\section{Model building}\nAfter selecting the data file {\\it mae\\_eeg.mat} and the method \"ECD\", the first step is building the meshes for the scalp and inner skull volume. This is done automatically through the \"Meshes\" button. Select the structural MRI to use ({\\it amri.img} here) and wait...\n\nThis step takes some time as the MRI is normalised and segmented. The normalisation parameters are saved in the {\\it amri\\_vbm\\_inv\\_sn.mat} file and will be used later to map coordinates between the template and subject spaces. With the segmentation, the brain and scalp binary volumes are built ({\\it amri\\_iskull.img} and {\\it amri\\_oscalp.img} ). These are used to build the outer scalp and inner skull surface meshes. These are saved in the {\\it model\\_head\\_amri.mat} file with other information. The scalp mesh is also saved in the file {\\it amri\\_scVert.mat}.\n\nOnce the head model is ready, we can co-register the EEG space with subject/image space. Use the \"Data Reg.\" button and decide if the registration should be based on the fiducials only (which is quite approximate) or the fiducials and the scalp surface (which should be more precise). Then select the appropriate files: {\\it fid\\_eeg.mat}, {\\it fid\\_MRI.mat}, {\\it headshape\\_orig.mat}, {\\it amri\\_scVert.mat} and let the routine work.\n\nTo prepare the model for the forward solution, simply press \"ForwardComp.\" and \"individual\" to use the subject's own MRI. The forward model uses a spherical approximation. The best fitting sphere are adjusted on the scalp surface and 2 other spheres are added to model the scalp and skull outer surfaces. Obviously the head is not spherical and there will be a mismatch between the scalp/brain surfaces and their respective spheres. We have used the idea proposed by Spinelli et al., 2000 \\cite{Spinelli2000}, where the brain volume is warped into a sphere. This allows us to use an analytical formula to calculate the forward solution for each dipole location while preserving some anatomical characteristics: superficial (resp. deep) sources remain superficial (resp. deep) in the spherical head model.\n\nAt this last step, the electrodes are also introduced in the head\nmodel and positioned relative to the subject head, as in the MRI. The\n{\\it model\\_head\\_amri.m} at contains the information about the fitted spheres and electrodes. Dipole fitting of the data is now possible.\n\n\\section{Dipole fitting}\nBy pressing the \"Inverse Sol.\" you launch the dipole fitting procedure. A number of questions have to be answered in order to specify the kind of solution you want:\n\\begin{itemize}\n\\item \"Condition to use\", select which condition is used to fit the dipole(s). So far, it is not possible to fit multiple conditions (or linear combinations of them) at the same time. For example, for differences between conditions, you should pre-calculate this difference before trying to fit ECDs. \\\\\n\\item \"Time window\", define the time window in ms on which the ECDs should be fitted. With the N170 demo data, a good window is 150 to 180.\\\\\n\\item \"Number of dipoles\", this is the crucial questions. How many dipoles should be used? It's up to you to decide... With the demo data, from the look of the EEG scalp map, 1 ECD should be enough.\\\\\n\\item \"Number of random seeds\". In order to avoid being trapped in a local minimum during the optimisation process because of a peculiar starting point. The algorithm can be launched from multiple random starting 'seeds'. If they all converge to approximately the same solution, then we'll have most surely reached the local optimum.\\\\\n\\item \"Orientation of the dipoles\". The location of the ECD will be constant throughout the time window but its orientation can be left free or be fixed as well. Leaving the orientation free allows the dipoles to rotate over time. To fix the orientation, we can use the (weighted according to the EEG power)) mean over the time window or use the orientation of the ECD fitting the time instant with maximum EEG power.\\\\\n\\item \"File name\". File names are suggested but feel free to change it!\n\\end{itemize}\n\nAfter fitting the N random seeds, the routine tries to group them in clusters of similar ECDs according to their location and signal variance explained. Eventually, these 'grouped' ECDs are displayed on the subject anatomy. The result of this clustering is saved in a mat file starting by {\\it res\\_} and finishing with the name you entered.\n\n\\section{Result display}\n\nResults can be redisplayed with the routine {\\it spm\\_eeg\\_inv\\_ecd\\_DrawDip.m}. The routine asks you to select the solution file you want to display and the MR image to be used.\n\n\\section{Preparing the *.pol files}\n\\begin{quote}\n% Just quick and dirty programming to extract the information from the .pol\n% files: fiducials, sensors & headshape in EEG space.\n \n% Actually, I just opened the ascii files and copy the coord of the EEG \n% fiducials here... Much easier.\n \n% Order of the fiducials is: LE, RE, Na\nfid\\_eeg = ([-0.0587687  6.79448 -0.00636311 ; ...\n            0.0352661   -6.78906    -0.00369206 ; ...\n            9.3675  0.0260009   0.00481311] + ...\n           [-0.0328487  6.78991 0.00636288 ; ...\n            0.0563513   -6.79533    0.00369206 ; ...\n            9.45206 -0.0260009  -0.00481297])/2 ...\n            * 10 ; % To convert cm into mm\n \n% These are coordinates picked by hand on the sMRI.\n% So it's quite an approximation of where the fiducials are really...\nfid\\_mri = [-71.8 3.5 -58.8 ; ...\n            71.3 -6  -62.5 ; ...\n            0   90.6 -28.4]        ;\n            \n% I edited the .pol files to REMOVE the first few lines with\n% fiducial information.\nsensors = load('sensors\\_noFid.pol','-ASCII')*10;\nheadshape = load('headshape\\_noFid.pol','-ASCII')*10;\n    % Again, multiply by 10 to get the measures in mm instead of cm\n \n% ATTENTION !!!\n% Polhemus, uses the axes in a different orientation!\n% It's still a right handed system but axes are:\n% - x: from back to front (versus left to right)\n% - y: from right to left (versus back to front)\n% - z: from bottom to top\n%\n% To make coord systems compatible, it is necessary to rotate clockwise the\n% coord by 90 degree around the z axis.\n \nRot = spm\\_matrix([0 0 0 0 0 -pi/2]); Rot = Rot(1:3,1:3);\nfid\\_eeg = (Rot*fid\\_eeg')';\nsensors = (Rot*sensors')';\nheadshape = (Rot*headshape')';\n \nsave fid\\_eeg fid\\_eeg\nsave fid\\_mri fid\\_mri\nsave sensors\\_orig sensors\nsave headshape\\_orig headshape\n\n\\end{quote}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n", "meta": {"hexsha": "7a0c0522c8105340b62b81a5dd5fa5bd2569d146", "size": 8176, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "lib/spm5/man/meeg/eeg_ecd.tex", "max_stars_repo_name": "awangga/braindecoding", "max_stars_repo_head_hexsha": "97128a8346263c81c9ccd606cfa54b35dacd6ca1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/spm5/man/meeg/eeg_ecd.tex", "max_issues_repo_name": "awangga/braindecoding", "max_issues_repo_head_hexsha": "97128a8346263c81c9ccd606cfa54b35dacd6ca1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-10-13T13:34:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-13T14:23:51.000Z", "max_forks_repo_path": "lib/BDTB-1.2.2/open/spm5/man/meeg/eeg_ecd.tex", "max_forks_repo_name": "awangga/braindecoding", "max_forks_repo_head_hexsha": "97128a8346263c81c9ccd606cfa54b35dacd6ca1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 78.6153846154, "max_line_length": 804, "alphanum_fraction": 0.7463307241, "num_tokens": 2039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6654105454764747, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.31971557924967325}}
{"text": "\n\\subsection{A witness-oriented approach}\n\n\n\\begin{frame}[fragile]\n\\frametitle{A witness-oriented approach}\n\nSubset-mode often works in practice, but does not seem ideal\n\\begin{itemize}\n\\item Strange normal form that affects all booleans\n\\item Strange iff-rewrites needed for all UBDD-making functions\n\\item Free variables in transitivity and the preservation of membership\n\\item Rules about \\Code{q-ite} seem somehow fragile\n\\end{itemize}\n\n\\SmallSkip\n\\Highlight{Witness-mode} is a more advanced alternative\n\\begin{itemize}\n\\item Intuitively, ``Pick all of the probably-relevant points''\n\\item Casts everything in terms of \\Code{eval-bdd}\n\\item Works with existing normal forms\n\\end{itemize}\n\\end{frame}\n\n\n\n\n\\begin{frame}[fragile]\n\\frametitle{The witness approach, graphically}\n\n\\includegraphics[width=12cm]{venn-diagrams}\n\n\\end{frame}\n\n\n\\begin{frame}[fragile]\n\\frametitle{The basic transformation}\n\nHypothesis: \\Code{x} $\\neq$ \\Code{y}  (or \\Code{x})\n\\begin{itemize}\n\\item Means $\\exists$ \\Code{v} : \\Code{(eval-bdd x v)} $\\neq$ \\Code{(eval-bdd y v)}\n\\item Introduce a new variable, \\Code{v}\n\\item Replace the hyp with \\Code{(eval-bdd x v)} $\\neq$ \\Code{(eval-bdd y v)} \n\\end{itemize}\n\n\\SmallSkip\n\nHypothesis: \\Code{x} $=$ \\Code{y}   (or \\Code{(not x)})\n\\begin{itemize}\n\\item Means $\\forall$ \\Code{v} : \\Code{(eval-bdd x v)} $=$ \\Code{(eval-bdd y v)} \n\\item Collect all \\Code{v} occurring in the clause\n\\item Replace the hyp with \\Code{(eval-bdd x v)} $=$ \\Code{(eval-bdd y v)} \n\\end{itemize}\n\n\\end{frame}\n\n\n\\begin{frame}[fragile]\n\\frametitle{Transformation example}\n\n\\begin{verbatim}\n  (IMPLIES (AND ;; (NORMP C)\n                ;; (NORMP HYP)\n                (Q-ITE C HYP NIL)\n                (NOT (EQUAL (Q-ITE C HYP NIL) HYP))\n                HYP\n                (NOT (EQUAL C T))\n                (NOT (Q-ITE C NIL HYP))\n                (NOT (EVAL-BDD C ARBITRARY-VALUES)))\n           (NOT (EVAL-BDD HYP ARBITRARY-VALUES))))\n\\end{verbatim}\n\n\\end{frame}\n\n\n\\begin{frame}[fragile]\n\n\\begin{verbatim}\n  (IMPLIES (AND (NOT (EQUAL (EVAL-BDD (Q-ITE C HYP NIL) V1)\n                            (EVAL-BDD NIL V1)))\n                (NOT (EQUAL (EVAL-BDD (Q-ITE C HYP NIL) V2)\n                            (EVAL-BDD HYP V2)))\n                (NOT (EQUAL (EVAL-BDD HYP V3)\n                            (EVAL-BDD NIL V3)))\n                (NOT (EQUAL (EVAL-BDD C V4)\n                            (EVAL-BDD T V4)))\n                (NOT (Q-ITE C NIL HYP))\n                (NOT (EVAL-BDD C ARBITRARY-VALUES)))\n           (NOT (EVAL-BDD HYP ARBITRARY-VALUES))))\n\\end{verbatim}\n\nValues: \\Code{V1}, \\Code{V2}, \\Code{V3}, \\Code{V4}, \\Code{ARBITRARY-VALUES}\n\n\\end{frame}\n\n\n\\begin{frame}[fragile]\n\n{\\footnotesize \\begin{verbatim}\n  (IMPLIES (AND (NOT (EQUAL (EVAL-BDD (Q-ITE C HYP NIL) V1)\n                            (EVAL-BDD NIL V1)))\n                (NOT (EQUAL (EVAL-BDD (Q-ITE C HYP NIL) V2)\n                            (EVAL-BDD HYP V2)))\n                (NOT (EQUAL (EVAL-BDD HYP V3)\n                            (EVAL-BDD NIL V3)))\n                (NOT (EQUAL (EVAL-BDD C V4)\n                            (EVAL-BDD T V4)))\n\n                (EQUAL (EVAL-BDD (Q-ITE C NIL HYP) V1)\n                       (EVAL-BDD NIL V1))\n                (EQUAL (EVAL-BDD (Q-ITE C NIL HYP) V2)\n                       (EVAL-BDD NIL V2))\n                (EQUAL (EVAL-BDD (Q-ITE C NIL HYP) V3)\n                       (EVAL-BDD NIL V3))\n                (EQUAL (EVAL-BDD (Q-ITE C NIL HYP) V4)\n                       (EVAL-BDD NIL V4))\n                (EQUAL (EVAL-BDD (Q-ITE C NIL HYP) ARBITRARY-VALUES)\n                       (EVAL-BDD NIL ARBITRARY-VALUES))\n\n                (NOT (EVAL-BDD C ARBITRARY-VALUES)))\n           (NOT (EVAL-BDD HYP ARBITRARY-VALUES))))\n\\end{verbatim}}\n\n\\end{frame}\n\n\n\\begin{frame}[fragile]\n\n{\\small \\begin{verbatim}\n  (IMPLIES (AND (EVAL-BDD (Q-ITE C HYP NIL) V1)\n                (NOT (EQUAL (EVAL-BDD (Q-ITE C HYP NIL) V2)\n                            (EVAL-BDD HYP V2)))\n                (EVAL-BDD HYP V3)\n                (NOT (EVAL-BDD C V4))\n\n                (NOT (EVAL-BDD (Q-ITE C NIL HYP) V1))\n                (NOT (EVAL-BDD (Q-ITE C NIL HYP) V2))\n                (NOT (EVAL-BDD (Q-ITE C NIL HYP) V3))\n                (NOT (EVAL-BDD (Q-ITE C NIL HYP) V4))\n                (NOT (EVAL-BDD (Q-ITE C NIL HYP) ARBITRARY-VALUES))\n\n                (NOT (EVAL-BDD C ARBITRARY-VALUES)))\n           (NOT (EVAL-BDD HYP ARBITRARY-VALUES))))\n\\end{verbatim}}\n\nFollows from cases introduced by \\Code{eval-bdd-of-q-ite}\n\n\\end{frame}\n\n\n\\begin{frame}[fragile]\n\\frametitle{The {\\tt eval-bdd-cp} clause processor (1/2)}\n\n\\Code{(diff x y)}\n\\begin{itemize}\n\\item When \\Code{x} $\\neq$ \\Code{y},\n       \\Code{(eval-bdd x (diff x y))} $\\neq$ \\Code{(eval-bdd y (diff x y))}\n\\end{itemize}\n\n\\SmallSkip\n{\\bf 1a.}.  Gather hyps of the form \\Code{x} $\\neq$ \\Code{y}, where\n\\Code{x}, \\Code{y} are (likely) UBDDs\n\\begin{itemize}\n\\item A hyp which is just \\Code{x} also counts: \\Code{x} $\\neq$ \\Code{NIL}\n\\end{itemize}\n\n\\SmallSkip\n{\\bf 1b.}.  For each \\Code{x} $\\neq$ \\Code{y} found, replace the hyp with\n\\begin{center}\n\\Code{(implies (and (normp x) (normp y))) \\qquad \\qquad \\qquad \\qquad \\qquad \\qquad \\quad \\;} \\\\\n\\qquad \\Code{(eval-bdd x (diff x y))} $\\neq$ \\Code{(eval-bdd y (diff x y))}\n\\end{center}\n\nThis is sound\n\\begin{itemize}\n\\item In the \\Code{normp} case, the clauses are equivalent\n\\item Otherwise, the new clause implies the original\n\\end{itemize}\n\n\\end{frame}\n\n\n\\begin{frame}[fragile]\n\\frametitle{The {\\tt eval-bdd-cp} clause processor (2/2)}\n\n{\\bf 2.} As a convenience, generalize away all \\Code{(diff x y)} terms just\nintroduced with fresh variables. (trivially sound)\n\n\\SmallSkip\n{\\bf 3.} Gather up all \\Code{v} which are used, anywhere, as arguments to\n\\Code{eval-bdd}, i.e., \\Code{(eval-bdd x v)}.\n\n\\SmallSkip\n{\\bf 4a.} Gather hyps of the form \\Code{x} $=$ \\Code{y} found, where \\Code{x},\n\\Code{y} are (likely) UBDDs\n\\begin{itemize}\n\\item A hyp which is \\Code{(not x)} also counts: \\Code{x} $=$ \\Code{NIL}\n\\end{itemize}\n\n\\SmallSkip\n{\\bf 4b.} Replace these hyps with \\Code{(eval-bdd x v)} $=$ \\Code{(eval-bdd y v)}, \nfor all \\Code{v} found in step 3. (trivially sound)\n\n\\end{frame}\n\n\n\n\\begin{frame}[fragile]\n\\frametitle{Automating {\\tt eval-bdd-cp}}\n\nWe use a default hint\n\n\\begin{itemize}\n\\item The clause must be \\Code{stable-under-simplificationp}\n\\item The definition of \\Code{eval-bdd-cp-hint} must be enabled\n\\item The transformation must modify the clause\n\\end{itemize}\n\n\\SmallSkip\nThe hint we give\n\\begin{verbatim}\n(:or (:clause-processor ...)\n     (:no-op t))\n\\end{verbatim}\n\n\\end{frame}\n", "meta": {"hexsha": "7679a9ea08ee4c57e2c31fe099e344f3afa59c31", "size": 6579, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "books/centaur/ubdds/slides/witness.tex", "max_stars_repo_name": "mayankmanj/acl2", "max_stars_repo_head_hexsha": "849d399c6e57a5e46675bd802eb66dd03bc41053", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 305, "max_stars_repo_stars_event_min_datetime": "2015-01-16T02:12:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T18:45:52.000Z", "max_issues_repo_path": "books/centaur/ubdds/slides/witness.tex", "max_issues_repo_name": "mayankmanj/acl2", "max_issues_repo_head_hexsha": "849d399c6e57a5e46675bd802eb66dd03bc41053", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 546, "max_issues_repo_issues_event_min_datetime": "2015-01-04T15:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T07:36:47.000Z", "max_forks_repo_path": "books/centaur/ubdds/slides/witness.tex", "max_forks_repo_name": "mayankmanj/acl2", "max_forks_repo_head_hexsha": "849d399c6e57a5e46675bd802eb66dd03bc41053", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 117, "max_forks_repo_forks_event_min_datetime": "2015-01-25T21:15:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T23:34:14.000Z", "avg_line_length": 28.9823788546, "max_line_length": 96, "alphanum_fraction": 0.587627299, "num_tokens": 2142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3196862956638711}}
{"text": "\\section{Introduction} \\label{intro}\n\n% Big picture.\n\nEconomics is thinking in models that abstract from the world by imposing assumptions on economic relations. These assumptions are defendable as long as they are sufficiently realistic for the research question at hand \\citep{F53}, prompting the question what this means. Often, assumptions are decided upon by mathematical convenience: do the assumptions grant that the model is solvable, i.e. whether a solution exists in closed form and whether this solution is unique.\n\n% Economics is thinking in models that abstract from the actually existing economic systems by imposing assumptions on economic relations. Those assumptions are defendable as long as they are sufficiently realistic for the research question at hand \\citep{F66}, what prompts the question, what sufficiently realistic means. Often, assumptions are decided upon by mathematical convenience: do the assumptions grant that the model is solvable, i.e. whether a solution exists in closed form and whether this solution is unique.\n\n% Narrow it down.\n\nWith the advent of numerical methods, we are less coerced to impose insufficiently realistic assumptions. Even if the model at hand does not have an analytical solution, one can still obtain an approximate solution by applying numerical methods \\citep{MF04}.\n\n% Due to the advancements in computational tractability we are less coerced to impose insufficiently realistic assumptions if numerical methods can be applied. That is, since even if the model at hand does not have an analytical solution, one can still obtain an approximate solution by applying numerical methods \\citep{MF04}.\n\nYet, if predictions shall be derived from a model in which the outcome is modelled as a function of inputs, it is crucial to understand how sensitive the model’s output is to changes in its inputs. Sensitivity analysis plays a major role in structural econometrics where the estimated model is oftentimes used to investigate counterfactual policies by quantifying the effects of a policy on some output \\citep{LM17}. If these models are actually used for policy making, the structural model and its assumptions have real-world consequences. The question arises whether the imposed model assumptions are sufficiently realistic to inform policy. Thus, thorough modelling is crucial for structural econometrics.\n\n% Now explain sensitivity analysis?\n\nConsider the following model\n\\begin{equation*}\nY = f(X),\n\\end{equation*}\n\n\\noindent where $Y$ is the response variable that depends on the values of some independent variables $X$. Let $X$ denote the vector $X = (X_1, \\dots, X_k)' \\in \\mathbb{R}^k$, where $k$ is the number of independent variables. Let $x$ be the vector of specific values assigned to $X$, i.e. one realisation of $X$. Let $f(\\cdot)$ denote a function that describes in which way $Y$ depends on $X$. This function may be some complex function (e.g. computer code) or a model that can be solved by numerical methods only. Thus, $f$ is generally not available in closed form and, hence, the relationship between $Y$ and $X$ is considered a black box.\n\nIn the remainder of this work, I name $Y$ the (model) output and the vector $X$ the (model) inputs. In this thesis, I will consider $X$ as being stochastic, that is, the $X_i$, $i = 1,\\dots, k$, follow a joint cumulative distribution function $G(X)$. Thus, although $f$ is assumed to be a deterministic function of $X$, the output $Y$ is also stochastic due to the uncertainty in $X$ \\citep{SNS16}. Sensitivity analysis sheds light on this input-output relationship \\citep{BP16}.\n\nAny assumption we impose can be such an input. One common objective of sensitivity analysis is Factor Fixing (FF), where we want to know whether an input can be fixed without influencing the output. For example, if we assume an estimated parameter to be deterministic by assigning a value to it, we implicitly neglect that this estimate is subject to uncertainty \\citep{R21}. This assumption is troubling if the model output is very sensitive to the value assigned to this input. Such an input we call \\textit{important}. Sensitivity analysis can guide research by identifying these important inputs \\citep{R21}. For example, we could focus on estimating important inputs more precisely, thus reducing output uncertainty.\n\nGenerally, sensitivity analysis can be structured into local and global methods. Local methods conduct sensitivity analysis around a certain point, or base case, $x_0$, in a deterministic framework, i.e. no probability distribution is assigned to $X$ \\citep{BP16}. In contrast, when performing global sensitivity analysis, we find ourselves in a stochastic context, which requires knowledge of the distribution of $X$, be it joint or marginal, with or without dependence between the inputs \\citep{ST02}. The result of performing sensitivity analysis is some sensitivity measure, that depends on the sensitivity method we apply to the context we find ourselves in. The methods applied in this thesis yield global sensitivity measures.\n\n% Research Gap.\n\nOne popular method to conduct global sensitivity analysis are Shapley effects. They are a well-suited sensitivity method that is easily interpreted and can be applied to both independently and dependently distributed inputs. Despite these and other appealing features, estimation of Shapley effects can be computationally demanding. This is where the Morris method, a qualitative sensitivity method first introduced by \\citet{M91}, comes into play since it promises to serve similar purposes as the Shapley effects, but to come at a lower computational cost.\n\n% Short summary of your paper and main results.\n\nThis paper assesses the predictive validity of the Morris method by applying it to a classical structural econometric model, the single-agent dynamic stochastic model of discrete choice introduced by \\citet{R87}. The Morris method employs a one-at-a-time algorithm to assess input importance: it uses the relative change in the model output due to a change in a model input. If inputs are dependent, the original Morris method can be subject to Type II error, i.e. it can identify inputs as uninfluential even if they are not, since it does not account for influence due to dependence among inputs. I compare the performance of the Morris method for \\textit{dependent} inputs as proposed by \\citet{GM17} to Shapley effects, which serve as the benchmark. I compare them based on the input ranking they imply.\n\nI find that the Morris method is a substitute for Shapley effects only if the resulting indices are interpreted with caution. Morris indices are very volatile. % since they perform very well in identifying uninfluential inputs and in ranking the inputs accordingly for the Rust model.\nMy results suggest further that the extension of Morris indices for dependent inputs by \\citet{GM17} is an important contribution since their proposed measure reduces the Type II error in identifying uninfluential inputs.\n\nAlthough the \\textit{extended} Morris method has been applied in some cases \\citep[e.g.][]{MMA18, RZY19}, to my knowledge their predictive validity has been assessed in the original paper by \\citet{GM17} only. In economics, structured global sensitivity analysis is not a common practice: \\citet{HMSW19} cite only few articles in economics that applied global sensitivity analysis. The contribution of this thesis is that it assesses the extended Morris method by applying it to an economic model.\n\n% In the context of structural econometrics sensitivity analysis has an important role. Structural econometrics imposes structure on the relationship between economic parameters \\citep{LM17}. The structural model is then taken to the data and deep economic parameters are estimated \\citep{LM17}. Structural econometrics can be used to investigate counterfactual policies by quantifying the effects of a policy on some output \\citep{LM17}. If these models are actually used for policy making, the structural model and its assumptions have real-world consequences. The question arises whether the imposed model assumptions are realistic enough to inform policy. Therefore, thorough modelling is crucial for structural econometrics.\n\n% Sensitivity analysis analyses how sensitive the model outcome is to model inputs \\citep{R21}.\n\n\n\n% In this work, I assess the predictive validity of Morris indices, a qualitative sensitivity method introduced by \\citet{M91}. Qualitative sensitivity methods aim at identifying uninfluential inputs and ranking inputs with respect to their importance \\citep{BP16}. The Morris method employs a one-at-a-time algorithm to assess input importance: it uses the relative change in the model output due to a change in a model input \\citep{M91}. I compare the performance of the Morris method for dependent inputs as proposed by \\citet{GM17} to Shapley effects, a variance-based quantitative sensitivity method \\citep{O14}.\n\n\n\n% Variance-based sensitivity analysis, a method that evaluates the importance of an input by assigning to it the expected reduction in output variance if this input was known with certainty \\citep{BP16}. Shapley values are a concept from game theory introduced by \\citet{S53}. The main advantages of Shapley values for sensitivity analysis are that they are as easily applied to dependent inputs as they are interpreted. Furthermore, Shapley values satisfy a range of desirable properties, the most important being efficiency and the null-player property \\citet{S53, O14}. In the context of sensitivity analysis, \\citet{SNS16} use the term Shapley effects. Despite of these appealing features, estimation of Shapley effects can be computationally demanding \\citep{SNS16}.\n\n%  I consider the \\textit{extended} Morris method introduced by \\citet{GM17} that handles correlated inputs.\n\n% Say something about the literature.\n\n\n% In this paper I estimate Morris indices for  and compare these to Shapley effects. Interestingly, I find that the Morris method is a worthy substitute for Shapley effects since they perform very well in identifying uninfluential inputs and in ranking the inputs accordingly for the Rust model. I find that the extension of Morris indices for dependent inputs by \\citet{GM17} is an important contribution since their proposed measure reduces the Type-II error in identifying influential inputs.\n\n% One set of common variance-based sensitivity measure are the total and first-order effects, or Sobol' indices, introduced by \\citet{S93} for independently distributed input variables, which are based on an Analysis of Variances (henceforth ANOVA) decomposition. One obvious drawback of the Sobol' indices in the original definition is that they rely on the assumption of inputs independence. Even if the ANOVA decomposition is adapted to handle dependent inputs, they suffer from problems \\citep{OP17} which are discussed in \\cref{var_based_sa}. \\citet{OP17} suggest using Shapley values instead, which were suggested in the context\n\n% Overview over thesis.\n\nThe remainder of this thesis is organised as follows: \\cref{rust_model} introduces the Rust model for which I conduct sensitivity analysis. In \\cref{comp_shap}, I estimate Shapley effects as a benchmark for the assessment. \\Cref{comp_morris} gives details on how the extended Morris method is used for sensitivity analysis, while \\cref{comparison} discusses the results. \\Cref{conclusion} offers some concluding remarks.", "meta": {"hexsha": "87befa8035ff725844f78f7a4fb334a80a650df1", "size": 11459, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/introduction.tex", "max_stars_repo_name": "bhmueller/thesis", "max_stars_repo_head_hexsha": "3bb9a55b356eee4aee65d0e035731809db57acc6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tex/introduction.tex", "max_issues_repo_name": "bhmueller/thesis", "max_issues_repo_head_hexsha": "3bb9a55b356eee4aee65d0e035731809db57acc6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/introduction.tex", "max_forks_repo_name": "bhmueller/thesis", "max_forks_repo_head_hexsha": "3bb9a55b356eee4aee65d0e035731809db57acc6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 168.5147058824, "max_line_length": 807, "alphanum_fraction": 0.8067894232, "num_tokens": 2375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.5428632831725051, "lm_q1q2_score": 0.31968629478685817}}
{"text": "\\documentclass[./\\jobname.tex]{subfiles}\n\\begin{document}\n\\chapter {Experiment 0: Serial Memetic JADE}\n\\label{chap:experimet_0}\n\nThis chapter describes the results obtained by the most basic adaption of JADE for solving \\gls{pde}s. The algorithm used here builds on the concepts described in \\cite{chaquet_using_2019}. Aside from substituting some parameters, the only main difference is the usage of JADE instead of a \\gls{cma_es}. \n\n\\section{Hypotheses}\nA memetic algorithm was first mentioned by \\cite{moscato_evolution_2000}. In essence, it is a hybridisation of a population-based evolutionary algorithm and a deterministic direct or local search. The pseudocode \\ref{algo: memeticJADE} below shows the implementation of such a memetic JADE. At first, JADE performs the global search and places its population around the optimum. Then the Downhill Simplex (\\gls{ds}) exploits this area. The budget of \\gls{nfe} is split into two parts: JADE takes nearly all \\gls{nfe} and leaves $2\\cdot dim$ \\gls{nfe} for the \\gls{ds}. The SciPy implementation of the \\gls{ds} is used (\\cite{scipy_scipyoptimizefmin_2020}).\n\n\\begin{algorithm}[h]\n\t\\SetAlgoNoLine\n\t\\DontPrintSemicolon\n\t\\SetKwFunction{FmJADE}{memeticJADE}\n\t\\SetKwProg{Fn}{Function}{:}{}\n\t\\Fn{\\FmJADE{$\\mathbf{X}$, $funct$, $minErr$, $maxFE$}}{\n\t\t$dim$, $popsize$ $\\gets size(\\mathbf{X})$\\;\n\t\t$p \\gets 0.3$\\;\n\t\t$c \\gets 0.5$\\;\n\t\t$pop$, $FE$, $F$, $CR$ $\\gets JADE($$\\mathbf{X}$, $p$, $c$, $funct$, $minErr$, $maxFE - 2 dim$ $)$\\;\n\t\t$bestIndex = argmin(FE)$\\;\n\t\t$bestSol = pop[bestIndex]$\\;\n\t\t$pop$, $FE$ $ = downhill\\text{ }simplex($$funct$, $bestSol$, $minErr$, $2 dim)$\\;\n\t\t\\Return $pop$, $FE$, $F$, $CR$\n\t}\n\t\\unterschrift{Pseudocode of memetic JADE}{}{}\n\t\\label{algo: memeticJADE}\n\\end{algorithm}\n\nThis experiment provides a first insight into the performance of the proposed algorithm. It tries to answer the question if JADE is a suitable surrogate algorithm for a \\gls{cma_es}. Further, the memory usage and solving time is compared to the \\gls{fem} results obtained in chapter \\ref{chap:fem_baseline_results}. \n\n\\section{Experiment Setup}\nThe standard parameters from table \\ref{tab:ci_parameter} are taken. The memetic JADE is limited to either $10^4$ \\gls{nfe} or $10^6$ \\gls{nfe}. The experiment is done on two different machines. The first try with $10^4$ \\gls{nfe} is run on the same machine ($\\rightarrow$ machine 1) as the \\gls{fem} experiment. This allows a fair memory and solving time comparison. This comparison can not be performed with the data obtained by using $10^6$ \\gls{nfe} ($\\rightarrow$ machine 2). Further, 5 \\gls{gak} are used which results in a dimension of 20 parameters. Thus, the population consists of 40 individuals. \n\nTo validate the results, a statistical significance test is performed. The test function is based on the Wilcoxon test. The Wilcoxon test checks for significance at $\\alpha = 0.05$. To decide if the results are better or worse, the mean and the median are compared. If both are smaller, the results are better. Contrary, if both are larger, the results are worse. If only one of the values is smaller, the results are undecided. The implementation is further explained in appendix \\ref{chap:apendix_post_proc}. \n\n\\section{Results}\n\\label{chap:experimet_0_results}\nTable \\ref{tab:results_literature_comparison} compares the obtained results with results from previous research papers. Therefore, the common testbed functions \\gls{pde} 2 and \\gls{pde} 3 are used. It is important to notice that the parameters used to obtain the results might not coincide. \\cite{tsoulos_solving_2006} also use these two \\gls{pde}s, but their paper did not provide any usable error metric. \n\\begin{table}[H]\n\t\\centering\n\t\\noindent\\adjustbox{max width=\\linewidth}{\n\t\t\\begin{tabular}{|c|c|c|c|}\n\t\t\t\n\t\t\t\\hline\n\t\t\t\\rowcolor[HTML]{\\farbeTabA}\n\t\t\t\n\t\t\tPaper & Parameter & RMSE \\gls{pde} 2 & RMSE \\gls{pde} 3 \\\\ \\hline\n\t\t\t\\cite{chaquet_using_2019} & \\multilinecell{4 kernel \\\\ max \\gls{nfe}=$10^6$ \\\\ 50 replications } & $(1.75 \\pm 1.14) 10^{-4}$ & $(1.09 \\pm 0.846) 10^{-5}$  \\\\ \\hline\n\t\t\t\\cite{chaquet_solving_2012} & \\multilinecell{10 harmonics \\\\ max \\gls{nfe} = $G \\cdot \\lambda$ = $1.2 \\cdot 10^6$ \\\\ 10 replications} & $(6.37 \\pm 0.733) 10^{-3}$ & $(5.90 \\pm 0.799)10^{-3}$ \\\\ \\hline\n\t\t\t\\cite{sobester_genetic_2008}& \\multilinecell{50 max tree length \\\\ 12 generations \\\\ 20 replications} & $(6.9 \\pm 8.3)10^{-4}$ & N/A \\\\ \\hline\n\t\t\t\\cite{panagant_solving_2014}& \\multilinecell{unknowns: N/A \\\\ \\gls{nfe}=$5\\cdot 10^5$ \\\\ replications: N/A} & $7.256 10^{-4}$ & $9.489 10^{-6}$ \\\\ \\hline\n\t\t\tserial memetic JADE & \\multilinecell{5 kernel \\\\ max \\gls{nfe} = $10^6$ \\\\ 20 replications} & $(2.9798 \\pm 1.5541)10^{-2}$ & $(3.8225 \\pm 1.9438)10^{-2}$ \\\\ \\hline\n\t\t\t\n\t\t\\end{tabular}\n\t}\n\t\\unterschrift{This table compares the results obtained with the serial memetic JADE to the numerical results obtained by similar work in literature. The same metric must be used, thus the RMSE as defined in equation \\eqref{eq:rmse_chaquet} is calculated.}{}{}\n\t\\label{tab:results_literature_comparison}\n\\end{table}\n\nThe following table \\ref{tab:serial_jade_compare_10^6_10^4} lists the smallest L2 norm reached after $10^4$ \\gls{nfe} and $10^6$ \\gls{nfe}, respectively. A standard Wilcoxon test, as described in the appendix \\ref{chap:apendix_post_proc}, is performed. Remarkable is that the results on \\gls{pde} 5 get significantly worse when more \\gls{nfe} are used.  \n\n\\begin{table}[H]\n\t\\centering\n\t\\noindent\\adjustbox{max width=\\linewidth}{\n\t\t\\begin{tabular}{|c|c|c|c|c|l|}\n\t\t\t\n\t\t\t\\hline\n\t\t\t\\rowcolor[HTML]{\\farbeTabA}\n\t\t\t\n\t\t\t\\gls{nfe} & \\multicolumn{2}{|c|}{$10^4$} & \\multicolumn{2}{|c|}{$10^6$} & \\\\ \\hline\n\t\t\tstat & mean & median & mean & median & Wilcoxon Test \\\\ \\hline \\hline\n\t\t\t\\gls{pde} 0A & 1.9415 $\\pm$ 0.3321 & 1.8844 & 0.6596 $\\pm$ 0.5510 & 0.9285 & sig. better \\\\ \\hline\n\t\t\t\\gls{pde} 0B & 0.7137 $\\pm$ 0.1979 & 0.6354 & 0.2027 $\\pm$ 0.1302 & 0.1516 & sig. better \\\\ \\hline\n\t\t\t\\gls{pde}  1 & 0.1874 $\\pm$ 0.0408 & 0.1938 & 0.0149 $\\pm$ 0.0049 & 0.0151 & sig. better \\\\ \\hline\n\t\t\t\\gls{pde}  2 & 0.0890 $\\pm$ 0.0334 & 0.0760 & 0.0257 $\\pm$ 0.0140 & 0.0224 & sig. better \\\\ \\hline\n\t\t\t\\gls{pde}  3 & 0.2409 $\\pm$ 0.1051 & 0.2309 & 0.0328 $\\pm$ 0.0169 & 0.0285 & sig. better \\\\ \\hline\n\t\t\t\\gls{pde}  4 & 0.1102 $\\pm$ 0.0367 & 0.0985 & 0.0378 $\\pm$ 0.0083 & 0.0352 & sig. better \\\\ \\hline\n\t\t\t\\gls{pde}  5 & 0.6645 $\\pm$ 0.1930 & 0.6263 & 1.1968 $\\pm$ 0.0286 & 1.2056 & sig. worse \\\\ \\hline\n\t\t\t\\gls{pde}  6 & 1.9660 $\\pm$ 1.3845 & 1.6540 & 0.4135 $\\pm$ 1.2133 & 0.0018 & sig. better \\\\ \\hline\n\t\t\t\\gls{pde}  7 & 0.0457 $\\pm$ 0.0137 & 0.0452 & 0.0221 $\\pm$ 0.0019 & 0.0223 & sig. better \\\\ \\hline\n\t\t\t\\gls{pde}  8 & 0.2186 $\\pm$ 0.0045 & 0.2191 & 0.2170 $\\pm$ 0.0019 & 0.2175 & unsig. better \\\\ \\hline\n\t\t\t\\gls{pde}  9 & 0.0525 $\\pm$ 0.0147 & 0.0516 & 0.0451 $\\pm$ 0.0119 & 0.0459 & unsig. better \\\\ \\hline\n\t\t\t\n\t\t\\end{tabular}\n\t}\n\t\\unterschrift{L2 norm reached with serial JADE at $10^4$ \\gls{nfe} and $10^6$ \\gls{nfe}}{}{}\n\t\\label{tab:serial_jade_compare_10^6_10^4}\n\\end{table}\n\nThe following two images \\ref{fig:serial_jade_time_boxplot} and \\ref{fig:serial_jade_memory_boxplot} show the time and memory usage for solving the testbed with $10^4$ \\gls{nfe} in relation to the \\gls{fem} solver. The images highlight the varying complexity of the testbed-\\gls{pde}s and their corresponding fitness function. Although these results are not obtained for $10^6$ \\gls{nfe}, they provide insight on how the solver scales with more \\gls{nfe}. \n\n\\begin{figure}[H]\n\t\\centering\n\t\\noindent\\adjustbox{max width=0.66\\linewidth}{\n\t\t\\includegraphics[width=\\textwidth]{../../code/experiments/experiment_0/time_boxplot_ci_exp0.pdf}\n\t}\n\t\\unterschrift{Relative solving time results of memetic JADE after $10^4$ \\gls{nfe}.}{}{}\n\t\\label{fig:serial_jade_time_boxplot}\n\\end{figure}\n\n\n\\begin{figure}[H]\n\t\\centering\n\t\\noindent\\adjustbox{max width=0.66\\linewidth}{\n\t\t\\includegraphics[width=\\textwidth]{../../code/experiments/experiment_0/mem_boxplot_ci_exp0.pdf}\n\t}\n\t\\unterschrift{Relative memory usage results of memetic JADE after $10^4$ \\gls{nfe}.}{}{}\n\t\\label{fig:serial_jade_memory_boxplot}\n\\end{figure}\n\n\\section{Discussion}\n\nThe results presented in chapter \\ref{chap:experimet_0_results} above are discussed on the following pages. A comparison to the current literature is drawn. The solving time and memory consumption in relation to the \\gls{fem} solver NGSolve is examined. Especially interesting are the results obtained on \\gls{pde} 0A and \\gls{pde} 5. \n\n\\subsection{Comparison to Literature}\n\nThe \\gls{rmse} reached on the \\gls{pde} 2 and 3, are clearly not as good as the results obtained in previous papers, especially the results presented in \\cite{chaquet_using_2019}. There might be a few reasons for that: \n\\begin{itemize}\n\t\\item As stated in the previous table \\ref{tab:ci_parameter}, the penalty and weighting factor on the collocation points are different. These settings have been chosen on the basis of preliminary experiments, but there is no guarantee that the choice of these parameters is optimal. Setting these values is not a trivial task and must be tailored to the optimisation algorithm and the differential equation. \n\t\\item Since \\gls{pde} 0A is defined as a combination of 5 \\gls{gak}, at least that many kernels must be provided to the solver. This setup results in a greater search dimension, as compared in table \\ref{tab:results_literature_comparison}. In general, more kernels result in a better solution, which is confirmed by experiments in \\cite{chaquet_using_2019} and in chapter \\ref{chap:pde 2 3 4 7}. \n\tTo reduce the computational effort per generation, and thus allow JADE to adapt the internal parameters for a longer period, the population size is set to $2 \\cdot dim$. According to \\cite{mallipeddi_empirical_2008}, the population size should not be lower than that. Again, choosing these parameters is not necessarily simple. The combination of larger problem dimension and smaller population size could influence the convergence to the worse. \n\t\\item Compared to \\cite{chaquet_using_2019}, the \\gls{nfe}-budget for the local \\gls{ds} search is smaller. Thus, the algorithm puts more emphasis on the exploration. However, due to the internal parameter-adaption JADE can perform both - exploration and exploitation. Preliminary experiments have shown that the direct search converges fast with very little progress after more than 100 \\gls{nfe}.  \n\t\\item JADE might simply be not as well suited for the problem as e.g. a \\gls{cma_es}. \n\\end{itemize}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%\n%        time/mem       %\n%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\subsection{Solving Time/Memory Usage}\n\nThe results from table \\ref{tab:serial_jade_compare_10^6_10^4} show that the \\gls{ci} solver can not nearly compete with the results obtained by the \\gls{fem} solver from table \\ref{tab:fem_sol_quality}. \nHowever, more interesting is the comparison of time and memory usage. \nIn the current implementation, the population and the corresponding function values as well as the F and the CR history are recorded at every generation. Therefore, the memory usage scales linearly with the number of function evaluations used. This information is not necessary for the actual algorithm, but helpful for evaluating the results. In later implementations, this could be disregarded in order to even further reduce the memory consumption. Depending on the testbed \\gls{pde}, only 1.5 to 4.0 percent of the memory used by the \\gls{fem} solver is needed. The \\gls{ci} solver uses less memory on all problems (figure \\ref{fig:serial_jade_memory_boxplot}). \n\nThe \\gls{ci} solver takes between 3 and 40 times as long as the \\gls{fem} solver (figure \\ref{fig:serial_jade_time_boxplot}) to perform $10^4$ \\gls{nfe}. Since the solving time scales linearly, $10^6$ \\gls{nfe} take about 10 times longer. An interesting observation is the distribution of the solving time within the testbed. The more operations a fitness function needs, the more expensive is one function evaluation and thus the longer is its solving time. However, this does not necessarily correspond with the quality of the solutions. For example, \\gls{pde} 0B requires the longest absolute evaluation time ($29 \\cdot 5 \\text{ s} \\approx 145\\text{ s}$), compared to the other \\gls{pde}s, it reaches a ``fairly'' good quality. \n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%\n%         PDE0A         %\n%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\subsection{PDE 0A}\n\\label{chap: experiment_0_pde_0A}\n\nThe purpose of this \\gls{pde} is to show that the solver would converge globally towards the analytical solution, if it can be represented by a finite number of kernels. However, his can not be confirmed with the current implementation. While more function evaluations do tend to generate better results (as confirmed by the Wilcoxon test in table \\ref{tab:serial_jade_compare_10^6_10^4}), it is common for the \\gls{ci} solver to result in different functions. A typical phenomenon is that the obtained approximation has some of its Gauss ``bumps'' outside of the domain $\\Omega$. The comparison of two solutions with $10^4$ \\gls{nfe} and $10^6$ \\gls{nfe} in figure \\ref{fig:serial_jade_pde0a_sol_comparison} shows this behaviour. Since the results improve from $10^4$ to $10^6$, it is possible that the results from $10^6$ \\gls{nfe} can be refined with an even larger \\gls{nfe} budget. However, this is not tested due to the already extensive computational effort. \n\n\\begin{figure}[H]\n\t\\centering\n\t\\begin{subfigure}[b]{0.45\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width=1\\textwidth]{../../code/experiments/experiment_0/pde0a_missing_bump_sol_10_4.pdf}\n\t\t\\caption{\\gls{pde} 0A error; $10^4$ \\gls{nfe}: \\\\ L2 norm: 2.5075 \\\\ FE value: 4.4129 \\\\ RMSE: 0.5699}\n\t\t\\label{fig:pde0a_sol_10_4}\n\t\\end{subfigure}% \n\t%\n\t\\begin{subfigure}[b]{0.45\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width=1\\textwidth]{../../code/experiments/experiment_0/pde0a_missing_bump_sol_10_6.pdf}\n\t\t\\caption{\\gls{pde} 0A error; $10^6$ \\gls{nfe}: \\\\ L2 norm: 0.9281 \\\\ FE value: 1.3762 \\\\ RMSE: 0.2111}\n\t\t\\label{fig:pde0a_sol_10_6}\n\t\\end{subfigure}%\n\t\\unterschrift{Comparison of two typical \\gls{pde} 0A solutions. }{}{}%\n\t\\label{fig:serial_jade_pde0a_sol_comparison}\n\\end{figure}\n\n\n\\subsection{PDE 5}\n\\label{chap:ex0_pde5}\n%%%%%%%%%%%%%%%%%%%%%%%%%\n%         PDE5          %\n%%%%%%%%%%%%%%%%%%%%%%%%%\nA fascinating property of \\gls{pde} 5 is observed: more function evaluations (from $10^4$ to $10^6$) result in a significantly worse solution quality. This is confirmed by a Wilcoxon test, as seen in table \\ref{tab:serial_jade_compare_10^6_10^4}. \nThis property can even be concluded from a visual perspective. A comparison between the best solution after $10^4$ \\gls{nfe} and the best solution after $10^6$ \\gls{nfe} is shown in figure \\ref{fig:serial_jade_pde5_sol_comparison}. The solution after $10^4$ \\gls{nfe} describes the global structure more accurately. It seems that the correct description of the boundary points gets lost with more \\gls{nfe}.\n\n\\begin{figure}[H]\n\t\\centering\n\t\\begin{subfigure}[b]{0.3333\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width=1\\textwidth]{../../code/experiments/experiment_0/pde5_best_sol_10_4.pdf}\n\t\t\\caption{best solution $10^4$ \\gls{nfe} \\\\ L2 norm: 0.4283 \\\\ FE value: 2980.96}\n\t\t\\label{fig:pde5_sol_10_4}\n\t\\end{subfigure}% \n\t%\n\t\\begin{subfigure}[b]{0.3333\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width=1\\textwidth]{../../code/experiments/experiment_0/pde5_best_sol_10_6.pdf}\n\t\t\\caption{best solution $10^6$ \\gls{nfe} \\\\ L2 norm: 1.1095 \\\\ FE value: 1007.44}\n\t\t\\label{fig:pde5_sol_10_6}\n\t\\end{subfigure}%\n\t%\n\t\\begin{subfigure}[b]{0.3333\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width=1\\textwidth]{../../code/testbed/pde5/sol_pde_5.pdf}\n\t\t\\caption{analytical solution \\\\to testbed \\\\ \\gls{pde} 5.}\n\t\t\\label{fig:pde5_analytical_solution}\n\t\\end{subfigure}%\n\t\\unterschrift{Comparison of best solution after $10^4$ and $10^6$ \\gls{nfe}.}{}{}%\n\t\\label{fig:serial_jade_pde5_sol_comparison}\n\\end{figure}\n\nThe distributions of the achieved fitness value after $10^4$ and $10^6$ \\gls{nfe} is shown in figure \\ref{fig:pde5_fitness_histogram}. They are clearly separated with distinct mean and median. As expected, both the mean and the median after $10^6$ \\gls{nfe} are significantly smaller than these values after $10^4$ \\gls{nfe}. The corresponding L2 norm distributions are plotted in figure \\ref{fig:pde5_norm_histogram}. As described by the Wilcoxon test, the results are inverted. The mean and the median of the L2 norm after $10^4$ \\gls{nfe} are smaller than the ones after $10^6$ \\gls{nfe}.\n\n\\begin{figure}[H]\n\t\\centering\n\t\\begin{subfigure}[b]{0.5\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width=1\\textwidth]{../../code/experiments/experiment_0/pde5_fit_histogram.pdf}\n\t\t\\caption{Histogram of the fitness value reached on \\gls{pde} 5.}\n\t\t\\label{fig:pde5_fitness_histogram}\n\t\\end{subfigure}%\n\t%\n\t\\begin{subfigure}[b]{0.5\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width=1\\textwidth]{../../code/experiments/experiment_0/pde5_norm_histogram.pdf}\n\t\t\\caption{Histogram of the L2 norm reached on \\gls{pde} 5.}\n\t\t\\label{fig:pde5_norm_histogram}\n\t\\end{subfigure}% \n\t\\unterschrift{Histograms of the fitness and the L2 norm reached with $10^4$ \\gls{nfe} and $10^6$ \\gls{nfe} on \\gls{pde} 5.}{}{}%\n\t\\label{fig:pde5_histograms}\n\\end{figure}\n\nThis phenomenon can be explained by the structural difference between the fitness function and the L2 norm. The fitness of a candidate solution can only decrease or stay the same, due to the greedy selection used in JADE (line 15 in the pseudocode \\ref{algo: jade}). The monotonically decreasing fitness value at every generation of an exemplary individual within the population is plotted in figure \\ref{fig:ex0_pde5_gak_fit_vs_l2}. Because the L2 norm is not the property that gets optimised, the quality of an individual at every generation is not necessarily monotonically decreasing. The L2 norm and the fitness at every generation of one individual from the population is plotted in figure \\ref{fig:ex0_pde5_gak_fit_vs_l2}.\n\n\\begin{figure}[H]\n\t\\centering\n\t\\noindent\\adjustbox{max width=0.7\\linewidth}{\n\t\t\\includegraphics[width=\\textwidth]{../../code/experiments/misc/pde5_gak_fit_l2_history.pdf}\n\t}\n\t\\unterschrift{Fitness value and L2 Norm of one individual at every generation on \\mbox{\\gls{pde} 5.}}{}{}\n\t\\label{fig:ex0_pde5_gak_fit_vs_l2}\n\\end{figure}\n\nThis indicates that the current fitness function does not fully describe the optimisation problem. Some possible solutions to this problem could be:\n\\begin{itemize}\n\t\\item An adaptive number of kernels reduces the dimensionality of the problem and only increases the kernel number if necessary. \n\t\\item A different kernel type that better resembles the structure of the solution could be used. \n\t\\item A denser grid of collocation points alters the fitness function. This introduces more points that might sit at more interesting positions within the domain. However, this also increases the computational effort to evaluate the fitness function. Alternatively, a scheme that adapts the collocation points during the optimisation process could balance out the computational effort and interesting probing locations.\n\\end{itemize}\n\nAn adaptive kernel scheme is proposed in chapter \\ref{chap:experimet_2}. The \\gls{gsk} kernel type is examined in chapter \\ref{chap:experimet_3}.\n\n\\end{document}", "meta": {"hexsha": "19bc4e16c6e511b550b3c605a447dcf5c671b584", "size": 19386, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "master_thesis_doc/tex/Experiment0.tex", "max_stars_repo_name": "nicolai-schwartze/Masterthesis", "max_stars_repo_head_hexsha": "7857af20c6b233901ab3cedc325bd64704111e16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-13T10:02:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-13T10:02:02.000Z", "max_issues_repo_path": "master_thesis_doc/tex/Experiment0.tex", "max_issues_repo_name": "nicolai-schwartze/Masterthesis", "max_issues_repo_head_hexsha": "7857af20c6b233901ab3cedc325bd64704111e16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "master_thesis_doc/tex/Experiment0.tex", "max_forks_repo_name": "nicolai-schwartze/Masterthesis", "max_forks_repo_head_hexsha": "7857af20c6b233901ab3cedc325bd64704111e16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 79.1265306122, "max_line_length": 966, "alphanum_fraction": 0.7352728773, "num_tokens": 6123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725053, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3196862869532281}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%                                                                 %\n%   MINUIT User Guide -- LaTeX Source                             %\n%                                                                 %\n%   Chapter 3                                                     %\n%                                                                 %\n%   The following external EPS files are referenced:              %\n%                                                                 %\n%   Editor: Michel Goossens / CN-AS                               %\n%   Last Mod.:  1 June 1992 10:10 mg                              %\n%                                                                 %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n\\chapter{How to Use Minuit}\n\n\\section{The Function FCN.}\nThe user must always supply a Fortran subroutine which calculates\nthe function value to be minimized or analyzed.\n\\medskip\n\\Shubr{FCN}{(NPAR,GRAD,FVAL,XVAL,IFLAG,FUTIL)}\n\n\\begin{DLtt}{1234567}\n\\item[{\\rm\\bf Input parameters}] \\mbox{}\n\\item[NPAR]  number of currently variable parameters.\n\\item[XVAL]  vector of (constant and variable) parameters.\n\\item[IFLAG] Indicates what is to be calculated (see example below).\n\\item[FUTIL] Name of utilitary routine (if needed, it\n             must be declared \\Lit{EXTERNAL} and provided by the user).\n\\item[{\\rm\\bf Output parameters}] \\mbox{}\n\\item[FVAL]  The calculated function value.\n\\item[GRAD]  The (optional) vector of first derivatives).\n\\end{DLtt}\n\nNote that when Minuit is being used through an intermediate package such as\nHBOOK or PAW, then the \\Rind{FCN} may be supplied by the this package.\n\n\\begin{XMPt}{Example of \\Lit{FCN} routine}\n        SUBROUTINE FCN(NPAR,GRAD,FVAL,XVAL,IFLAG,FUTIL)\n        IMPLICIT DOUBLE PRECISION (A-H,O-Z)  !  for 32-bit machines\n        DIMENSION GRAD(*),XVAL(*)\n        EXTERNAL FUTIL   !    (if needed and supplied by user)\nC-\n        IF (IFLAG .EQ. 1)  THEN\nC           read input data,\nC           calculate any necessary constants, etc.\n        ENDIF\n        IF (IFLAG .EQ. 2)  THEN\nC           calculate GRAD, the first derivatives of FVAL\nC           (this is optional)\n        ENDIF\nC             Always calculate the value of the function, FVAL,\nC             which is usually a chisquare or log likelihood.\nC                  Optionally, calculation of FVAL may involve\n        FTHEO = FUTIL(....)\nC                  It is responsability of user to pass\nC                  any parameter values needed by FUTIL,\nC                  either through arguments, or in a COMMON block\n         IF (IFLAG .EQ. 3)  THEN\nC            will come here only after the fit is finished.\nC            Perform any final calculations, output fitted data, etc.\n        ENDIF\n        RETURN\n        END\n\\end{XMPt}\n\nThe name of the subroutine may be chosen freely (in documentation we\ngive it the generic name \\Rind{FCN}) and must be declared \\Lit{EXTERNAL} in the\nuser's program which calls Minuit (in data-driven mode) or calls\nMinuit subroutines (in Fortran-callable mode).\nThe meaning of the parameters \\Lit{XVAL} is of course defined by\nthe user, who uses the values of those parameters to calculate his\nfunction value.\nThe starting values must be specified by the user\n(either by supplying parameter\ndefinitions from a file, or typing them at the terminal,\nin data-driven mode; or\nby calling subroutine \\Rind{MNPARM} in Fortran-callable mode),\nand later values are determined by Minuit as it searches for the\nminimum or performs whatever analysis is requested by the user.\n\\Rind{FUTIL} represents the name of a function or subroutine which may\nbe defined and supplied by the user and called from \\Rind{FCN}.\nIf the user does not use the \\Rind{FUTIL} feature, the last argument\nmay be given as zero, but if used, the name of \\Rind{FUTIL} must\nbe declared \\Lit{EXTERNAL} and a subprogram of that name must be\nsupplied at loading time.\n \nIt is possible, by giving them different names, to analyze several\ndifferent \\Rind{FCN}s in one job.\nHowever, one analysis must be completed before the next is started.\nIn order to avoid interference between the analyses of two different\n\\Rind{FCN}s, the user should call Minuit (in data-driven mode) or \\Rind{MNINIT}\n(in Fortran-callable mode) each time a new \\Rind{FCN} is to be studied.\n\n\\section{Running Minuit in Data-driven Mode.}\n\nMinuit can be run in two different modes:\n{\\bf Data-driven mode}\n\\index{data driven mode}\n\\index{mode!data driven}\nmeans that the user drives Minuit with data, either typed\ninteractively from a terminal or from a data file in batch; and\n\\index{Fortran-callable mode}\n\\index{mode!Fortran-callable}\n{\\bf Fortran-callable mode}\nmeans that Minuit is driven directly from Fortran subroutine\ncalls, without data.\nTo some extent, the two modes may also be mixed.\nThis section describes the first mode, and is valid for both\ninteractive and batch running.\nThe differences between interactive and batch are described in\na separate subsection below.\n \n\\index{data driven mode}\n\\index{mode!data driven}\nIn {\\bf data-driven mode}, the user must supply,\nin addition to the subroutine \\Rind{FCN}, a\n{\\bf main program} which includes the following\nstatements (the statements in upper case are required, those\ngiven in lower case are optional):\n\n\\begin{XMPt}{Example of main program when using Minuit in data driven mode}\n      EXTERNAL FCN\n      external futil\n      call mintio(ird,iwr,isav)\n      CALL MINUIT(FCN,futil)\n\\end{XMPt}\n\nThe name of \\Rind{FCN} may be chosen freely, and is communicated\nto Minuit as its first argument.\n\\Rind{FUTIL} is the generic name of a function or subroutine which the\nuser may optionally call from \\Rind{FCN}, and if he does call such\na routine, he must declare it external and communicate its\nname to Minuit as well.  If \\Rind{FUTIL} is not used, then the second\nargument may be put equal to \\Lit{0}, \nand need not be declared \\Lit{EXTERNAL}; if \\Rind{FUTIL} is\ndeclared \\Lit{EXTERNAL}, it must be supplied in the loading process.\n\n\\newpage\n\n\\Shubr{MINTIO}{(IREAD,IWRITE,ISAVE)}\n\n\\medskip\\Action\nThe purpose of \\Rind{MINTIO} is to communicate to Minuit the I/O units.\n\n\\begin{DLtt}{1234567}\n\\item[{\\rm\\bf Input parameters}] \\mbox{}\n\\item[IREAD]  Fortran unit number for reading (default 5).\n\\item[IWRITE] Fortran unit number for writing (default 6).\n\\item[Isave]  Fortran unit number for saving (default 7).\n\\end{DLtt}\n\n\\index{input/output units}\n\nIf the default values are acceptable, then it is not necessary to\ncall \\Rind{MINTIO}.\nIt is the user's responsibility that the I/O units are properly\nopened for the appropriate operations.\n \n\\subsection*{Note}\n \nIn data-driven mode, that is with \\Lit{CALL}~\\Rind{MINUIT}, you should\n{\\bf not call \\Rind{MNINIT}}, since Minuit takes care of all\ninitialization. \nTo change unit numbers, call \\Rind{MINTIO} \n{\\bf before calling \\Rind{MINUIT}}.\n \nIn order that control returns to the user program after\n\\Lit{CALL MINUIT}, the last command in the corresponding Data Block\nshould be \\Cind[RETurn]{RETURN}.  \nIf the last command is \\Cind{EXIT} or \\Cind{STOP},\nthen Minuit will execute a Fortran \\Lit{STOP}, and if the last\ncommand is \\Cind{END}, Minuit will read a new Data Block from the current\ninput unit.\n \n\\Subsection{10cm}{Data to drive Minuit}\n \nIn data-driven mode, either interactively or in batch,\nMinuit reads the following data provided by the user:\n\n\\begin{UL}\n\\item {\\bf Title:} (a string of 50 characters or less)\n      which can be chosen freely by the user, to help identify the job.\n\\item {\\bf Parameter definitions:} for each parameter one record giving:\n      \\begin{OL}\n      \\item {\\bf The parameter number.}\n            This is the index in the array \\Lit{XVAL} by which the\n            user function \\Rind{FCN} will access the value of the parameter.\n      \\item {\\bf The parameter name.}\n            A string of ten characters to help the user in\n            reading the Minuit output.\n      \\item {\\bf The starting value} of the parameter.\n      \\item {\\bf The starting step size,}\n             or expected uncertainty in this parameter,\n             if it is to be a variable parameter. Otherwise blank or zero if the\n             value is to be constant.\n      \\item [Optional] The {\\bf lower bound}\n            (limit) below which the parameter value must not vary.\n      \\item [Optional] The {\\bf upper bound}\n            (limit) above which the parameter value must not vary.\n      \\end{OL}\n      Normally the user should {\\bf not} specify limits on the parameters, that is\n      both should be left blank. If one limit is specified, then BOTH must\n      be specified. The properties of limits are explained elsewhere\n      in this document.\n \n      The format of the parameter definitions may be either\n      fixed-field (each item in a field of width ten columns),\n      or in free-field format.\n      In the free-field format, items are separated by blanks or one comma,\n      and the parameter name must be given between single quotes.\n      The program assumes free-field format if it finds two single\n      quotes in the line.\n      Parameter names will be blank-padded or truncated to be\n      ten characters long.\n\\item {\\bf A blank record:} indicates the end of parameter definitions.\n\\item If the user \\Rind{FCN} reads input data from the same input stream as the\n       Minuit data (the default stream is \\Lit{UNIT 5}),\n       then the \\Lit{FCN} data should appear here.\n\\item {\\bf Minuit commands:} these specify actions which should be performed by Minuit.\n       Commands must not contain leading or embedded blanks, but may be\n       truncated to three characters, and may be given in upper or lower case.\n       Some commands have numerical arguments, and these may be given in\n       free-field format, separated by blank(s) or one comma\\footnote{%\n       In older versions of Minuit, there was a special format for the \\Cind{MINOs}\n       command, when specifying a list of parameters; the new Minuit reads\n       the \\Cind{MINOs} command with the same free-field format as the other\n       commands, so if parameter numbers are specified, they must now\n       be separated by a blank or comma.}.\n       The list of recognized commands is given and explained below.\n       The command \\Cind{HELP} causes Minuit to write to the output stream a list\n       of currently recognized commands.\n       The command \\Cind{HELP SHOw} lists the available \\Cind{SET} \n       and \\Cind{SHOw} commands.\n\\end{UL}\n\nAny or all of the above data read by Minuit\ncan reside on one or more different files,\nand Minuit can be instructed\nto switch to reading a different file with the \\Cind[SET INPut]{SET INPUT} command.\nOptionally, the {\\bf title} record may be preceeded by a record\nbeginning with the characters \\Cind[SET TITle]{SET TITLE}, and the\n{\\bf parameter definitions} may be preceeded by a record\nbeginning with the characters \\Cind[PARameters]{PARAMETERS}.\nIt is in fact recommended always to include these optional\nrecords when preparing a data file, since the file can then be\nread at any time (not just at the beginning of a Minuit run)\nand will always be interpreted correctly by Minuit.\n \n\\begin{XMPt}{Example of a typical Minuit data set}\nSET TITLE\nFit to time distribution of K decays, Expt NA94\nPARAMETERS\n1 'Real(X)'  0.  .1\n2 'Imag(X)'  0.  .1\n5 'Delta M'  .535   .01\n10 'K Short LT'  .892\n11 'K Long LT'   518.3\n \nfix 5\nmigrad\nset print 0\nminos\nrestore\nmigrad\nminos\nfix 5\nset param  5   0.535\ncontour 1 2\nstop\n\\end{XMPt}\n\n\\subsection{Batch and interactive running.}\n\n\\index{batch run}\n\\index{interactive session}\nIn its initialization phase, Minuit attempts to determine whether\nor not it is running interactively, by calling the logical function\n\\Rind{INTRAC}, a routine in the CERN Program Library which can\nbe provided for all commonly used computers.\nFor our purposes, we define ``running interactively'' as meaning that\ninput is coming from a terminal under the control of an intelligent\nbeing, able to make decisions based on the output he receives at\nthe terminal. It is not always easy for \\Rind{INTRAC} to know whether this\nis the case, so, depending on your operating system, Minuit can be\nfooled in certain cases. When this happens, the user can always override\nthe beliefs of \\Rind{INTRAC} with the commands \\Cind{SET BATch} and\n\\Cind{SET INTeractive}. \nThe command \\Cind{SHOw INTeractive} informs the user of the current mode.\n \nAccording to whether or not it believes it is running interactively,\nMinuit behaves differently in the following ways:\n\n\\begin{UL}\n\\item If interactive, the user is prompted before each data record is read.\n\\item If interactive, Minuit recovers from many error conditions\n      and prompts the user to enter correct data or to specify\n      additional required input.\n      If the same error conditions occur in batch mode, the program either\n      exits (if no corrective action seems possible) or ignores the incorrect\n      data (for example, a command it cannot interpret) and continues.\n\\item The default page size for output is a typical terminal dimension\n      (80 by 24) if interactive, and a typical printed page size (120 by 56)\n      if batch, but these can be overridden with the commands \n      \\Cind[SET WIDthpage]{SET WIDth} and \\Cind[SET LINesperpage]{SET LINes}.\n\\end{UL}\n\nWhen an interactive user requests Minuit to read\nfurther input from an external file (the \\Cind{SET INPut} command),\nthen further input is considered to be temporarily\nin batch mode, until input reverts to the primary input stream.\n\n\\Section{5cm}{Running Minuit in Fortran-callable mode.}\n\nThe following Minuit subroutines are provided in order to allow\nthe user to communicate with Minuit and perform all Minuit\nfunctions (define parameters, execute commands, etc.) directly\nfrom Fortran through subroutine calls.\nIn the following list of subroutines, output arguments are indicated\nby appending a star \\Lit{*} to its name.\nIt should also be noted that for the Double Precision version of\nMinuit (recommended for all 32-bit machines such as IBM, Vax,\nUnix workstations, etc.), all the \\Lit{REAL} arguments given below must be\ndeclared \\Lit{DOUBLE PRECISION}.\n\n\\Subsection{4cm}{Initialize Minuit}\n \n\\Shubr{MNINIT}{(IRD,IWR,ISAV)}\n \n\\begin{DLtt}{123456}\n\\item[{\\rm\\bf Input parameters:}]\n\\item[IRD]  Unit number for input to Minuit.\n\\item[IWR]  Unit number for output from Minuit.\n\\item[ISAV] Unit number for use of the SAVE command.\n\\end{DLtt}\n \n\\Subsection{4cm}{Specify a title for a problem}\n \n\\Shubr{MNSETI}{(CTITLE)}\n \n\\begin{DLtt}{123456}\n\\item[{\\rm\\bf Input parameter:}]\n\\item[CTITLE] Character string of up to 50 characters containing\n              an identification text for the present job or fit.\n\\end{DLtt}\n \n\\Subsection{4cm}{Define a parameter}\n \n\\Shubr{MNPARM}{(NUM,CHNAM,STVAL,STEP,BND1,BND2,IERFLG*)}\n \n\\begin{DLtt}{123456}\n\\item[{\\rm\\bf Input parameters:}]\n\\item[NUM]    Parameter number as referenced by user in \\Rind{FCN}.\n\\item[CHNAM]  Character string of up to 10 characters containing\n              the name which the user assigned to the given parameter.\n\\item[STVAL]  Starting value\n\\item[STEP]   Starting step size or approximate parameter error.\n\\item[BND1]   Lower bound (limit) on parameter value, if any (see below).\n\\item[BND2]   Upper bound (limit) on parameter value, if any (see below).\n\\item[{\\rm\\bf Output parameter:}]\n\\item[IERFLG] Error return code: \\Lit{0} if no error, \\Lit{>0} if request failed.\n\\end{DLtt}\n \nIf \\Lit{BND1=BND2=0.}, then the parameter is considered unbounded, which\nis recommended unless limits are needed to make things behave well.\n \n\\Subsection{4cm}{Execute a Minuit command}\n \n\\Shubr{MNEXCM}{(FCN,CHCOM,ARGLIS,NARG,IERFLG,FUTIL)}\n \n\\begin{DLtt}{123456}\n\\item[{\\rm\\bf Input parameters:}]\n\\item[FCN]    Name fo the function being analyzed (to be declared \\Lit{EXTERNAL})\n\\item[CHCOM]  Character string containing the name of the Minuit\n              command to be executed (see below).\n\\item[ARGLIS] Array of dimension \\Lit{MAXARG}, containing the numeric arguments \n              to the command (if any),\n\\item[NARG]   Number of arguments specified (\\Lit{NARG}$\\leq${MAXARG}),\n\\item[FUTIL]  Name fo a function called by \\Rind{FCN} (or \\Lit{=0} if not used).\n              If used this function must be declared \\Lit{EXTERNAL}.\n\\item[{\\rm\\bf Output parameter:}]\n\\item[IERFLG] Error return code: \\Lit{0} if the command was executed normally, \n              \\Lit{>0} otherwise.\n\\end{DLtt}\n \nExecuting a command by calling \\Rind{MNEXCM} has exactly the same\neffect as reading the same command in data-driven mode, except that\na few commands would make no sense and are not available in\nFortran-callable mode (e.g. \\Cind[SET INPut]{SET INPUT}).\nThe other difference is that {\\bf control always returns to the\ncalling routine from \\Rind{MNEXCM}}, even after commands \\Cind{END},\n\\Cind{EXIT}, and \\Cind{STOP}.\n \n\\Subsection{4cm}{Get the current value of a parameter}\n\nThis routine is the inverse of \\Rind{MNPARM} and\ncan for instance be used after a fit.\n\n\\Shubr{MNPOUT}{(NUM,CHNAM*,VAL*,ERROR*,BND1*,BND2*,IVARBL*)}\n \n\\begin{DLtt}{123456}\n\\item[{\\rm\\bf Input parameter:}]\n\\item[NUM]    Parameter number as referenced by user in \\Rind{FCN} and\n              about which information is required.\n\\item[{\\rm\\bf Output parameters:}]\n\\item[CHNAM]  Character string of up to 10 characters containing\n              the name which the user assigned to the given parameter.\n\\item[VAL]    Current parameter value (fitted value if fit has converged),\n\\item[ERROR]  Current estimate of parameter uncertainty (or zero if constant)\n\\item[BND1]   Lower limit on parameter value, if any (otherwise zero).\n\\item[BND2]   Upper limit on parameter value, if any (otherwise zero).\n\\item[IVARBL] Internal parameter number if parameter is variable, or\n              zero if parameter is constant, or negative if parameter is undefined.\n\\end{DLtt}\n \n\\Subsection{4cm}{Get the current status of minimization}\n\n\\Shubr{MNSTAT}{(FMIN*,FEDM*,ERRDEF*,NPARI*,NPARX*,ISTAT*)}\n \n\\begin{DLtt}{123456}\n\\item[{\\rm\\bf Output parameters:}]\n\\item[FMIN]   The best function value found so far\n\\item[FEDM]   The estimated vertical distance remaining to minimum\n\\item[ERRDEF] The value of \\Lit{UP} defining parameter uncertainties\n\\item[NPARI]  The number of currently variable parameters\n\\item[NPARX]  The highest (external) parameter number defined by user\n\\item[ISTAT]  A status integer indicating how good is the covariance matrix:\n              \\begin{DLtt}{1}\n                \\item[0] Not calculated at all\n                \\item[1] Diagonal approximation only, not accurate\n                \\item[2] Full matrix, but forced positive-definite\n                \\item[3] Full accurate covariance matrix (After \\Cind[MIGrad]{MIGRAD}, \n                         this is the indication of normal convergence.)\n              \\end{DLtt}\n\\end{DLtt}\n \n\\Subsection{4cm}{Get the current value of the covariance matrix}\n\n\\Shubr{MNEMAT}{(EMAT*,NDIM)}\n \n\\begin{DLtt}{123456}\n\\item[{\\rm\\bf Input parameter:}]\n\\item[NDIM]   Integer variable specifying the number of rows and columns\n              the suer has reserved in \\Lit{EMAT} to store the matrix elements.\n              \\Lit{NDIM} should be at least as large as the number of parameters \n              variable at the time of the call, otherwise the user will get\n              only part of the full matrix.\n\\item[{\\rm\\bf Output parameter:}]\n\\item[EMAT]   Array declared as \\Lit{DIMENSION EMAT(NDIM,NDIM)} which\n              is to be filled with the (external) covariance matrix.\n\\end{DLtt}\n \n\\Subsection{4cm}{Access current parameter errors}\n\n\\Shubr{MNERRS}{(NUM,EPLUS*,EMINUS*,EPARAB*,GLOBCC*)}\n \n\\begin{DLtt}{123456}\n\\item[{\\rm\\bf Input parameter:}]\n\\item[NUM]    Parameter number. \n              If \\Lit{NUM>0}, this is taken to be an external parameter number; \n              if \\Lit{NUM<0}, it is the negative of an internal parameter number.\n\\item[{\\rm\\bf Output parameters:}]\n\\item[EPLUS]  The positive \\Cind[MINOs]{MINOS} error of parameter \\Lit{NUM}.\n\\item[EMINUS] The negative \\Cind[MINOs]{MINOS} error (a negative number).\n\\item[EPARAB] The ``parabolic'' parameter error, from the error matrix.\n\\item[GLOBCC] The global correlation coefficient for parameter \\Lit{NUM}.\n              This is a number between zero and one which gives the correlation\n              between parameter \\Lit{NUM} and that linear combination of all other\n              parameters which is most strongly correlated with \\Lit{NUM}.\n\\end{DLtt}\n \nNote that this call does not cause the errors to be\ncalculated, it merely returns the current existing values.\nIf any of the requested values has not been calculated, or has\nbeen destroyed (for example, by a redefinition of parameter values)\n\\Rind{MNERRS} returns a value of zero for that argument.\nThus the call to \\Rind{MNERRS} will normally follow the execution of\ncommands \\Cind[MIGrad]{MIGRAD}, \\Cind[HESse]{HESSE}, \n\\Cind{MNContour}, and/or \\Rind[MINOs]{MINOS}.\n \n\\Subsection{4cm}{Find a function contour with the MNContour method}\n\n\\Shubr{MNCONT}{(FCN,NUM1,NUM2,NPT,XPT*,YPT*,NFOUND*,FUTIL)}\n \n\\begin{DLtt}{123456}\n\\item[{\\rm\\bf Input parameters:}]\n\\item[FCN]    Name of the function being treated (to be declared \\Lit{EXTERNAL})\n\\item[NUM1/2] Parameter numbers with respect to which the contour\n              is to be determined (external).\n\\item[NPT]    The number of points required on the contour (\\Lit{>4}).\n\\item[FUTIL]  Name of a function called by \\Rind{FCN} (or =0 if not used).\n              If used this function must be declared \\Lit{EXTERNAL}.\n\\item[{\\rm\\bf Output parameters:}]\n\\item[XPT]    Array of x-coordinates of contour points with \n              values for parameter \\Lit{NUM1}.\n              It must be declared with a \\Lit{DIMENSION XPT(NPT)}.\n\\item[YPT]    Array of y-coordinates of contour points with\n              values for parameter \\Lit{NUM2}.\n              It must be declared with a \\Lit{DIMENSION YPT(NPT)}.\n\\item[NFOUND] The number of points actually found on the contour.\n              If all goes well, this will be equal to \\Lit{NPT}, but it can be\n              negative (if the input arguments are not valid), or zero if\n              less than four points have been found, or less than \\Lit{NPT} if the\n              program could not find \\Lit{NPT} points.\n\\end{DLtt}\n \nNote that alternatively \\Cind{MNContour} can be calculated\nby calling \\Rind{MNEXCM} to issue the \\Cind{MNContour} command,\nbut then the user does not have Fortran access to the actual\npoint coordinates \\Lit{XPT} and \\Lit{YPT}.\n \n\\Subsection{4cm}{Switch to command-reading mode}\n\nThis facility can be useful when one wants to continue interactively.\n\n\\Shubr{MNINTR}{(FCN,FUTIL)}\n \n\\begin{DLtt}{123456}\n\\item[{\\rm\\bf Input parameters:}]\n\\item[FCN]    Name of the function being treated (to be declared \\Lit{EXTERNAL})\n\\item[FUTIL]  Name of a function called by \\Rind{FCN} (or \\Lit{=0} if not used).\n              If used this function must be declared \\Lit{EXTERNAL}.\n\\end{DLtt}\n \nThe call to \\Rind{MNINTR} will cause Minuit to read commands from\nthe unit \\Lit{IRD} (originally specified by the user in his call to \\Rind{MNINIT},\n\\Lit{IRD} is usually 5 by default,\nwhich in turn is usually the terminal by default).\nMinuit then reads and executes commands until it encounters\na command \\Cind{END}, \\Cind{EXIT}, \\Cind{RETurn}, or \\Cind{STOP}, \nor an end-of-file on input\n(or an unrecoverable error condition while reading\nor trying to execute a command), in which case control returns\nto the program which called \\Rind{MNINTR}.\n", "meta": {"hexsha": "a32585deef51dc023737dae922b63f173036815f", "size": 23600, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "longwrups/minuit/minch3.tex", "max_stars_repo_name": "berghaus/cernlib-docs", "max_stars_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-24T12:30:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-24T12:30:01.000Z", "max_issues_repo_path": "longwrups/minuit/minch3.tex", "max_issues_repo_name": "berghaus/cernlib-docs", "max_issues_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "longwrups/minuit/minch3.tex", "max_forks_repo_name": "berghaus/cernlib-docs", "max_forks_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.1947565543, "max_line_length": 87, "alphanum_fraction": 0.7016525424, "num_tokens": 6151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3196862791195977}}
{"text": "\\section{Proofs for metatheory}\n\\label{sec:metatheory:proofs}\n\n\\begin{itemize}\n\\item\n  For simplicity, we only consider terms in A-normal forms following the grammar:\n  \\begin{align*}\n    e ::=~& \\ldots \\mid \\aiapp{x}{x'} \\mid \\aipair{k}{x}{x'} \\mid \\aimatchin\\etransfm{x,y}{z}{e}\n  \\end{align*}\n  Typing and semantics rules are unchanged.\n\\item Borrow qualifiers  $\\BQ ::= \\IBORROW_n \\mid \\MBORROW_n$ where\n  $n\\ge0$ is a region level. A vector of borrow qualifiers $\\Multi\\BQ$\n  is wellformed if all $\\IBORROW$s come before all $\\MBORROW$s in the vector. \n\\item Borrow compatibility\n  $\\Multi\\BQ \\Bcompatible \\BQ$,\n  \\begin{mathpar}\n  \\inferrule{}{\n    \\BQ_n\\Multi\\BQ \\Bcompatible \\BQ_n\n  }\n  %\n  % \\inferrule{}{\n  %   \\MBORROW_n\\Multi\\MBORROW \\Bcompatible \\MBORROW_n\n  % }\n  \\end{mathpar}\n\\item Store typing $ \\vdash \\Store : \\SE$,\n  \\begin{mathpar}\n    \\inferrule{\n      (\\forall \\Loc \\in \\Dom\\Store)~~\n      \\SE \\vdash \\Store (\\Loc) : \\SE (\\Loc)\n    }{ \\vdash \\Store : \\SE }\n  \\end{mathpar}\n\\item Relating storables to type schemes $\\SE \\vdash w : \\schm$\n\n  We write $\\Disjoint\\E$ for $\\Active\\VEnv$ and $\\MutableBorrows\\VEnv$\n  and $\\ImmutableBorrows\\VEnv$ and $\\Suspended\\VEnv$ are all disjoint.\n  \\begin{mathpar}\n  \\inferrule{\n    (\\exists \\E)~ \\SE \\vdash \\VEnv : \\E\n    \\\\\n    \\Disjoint\\E\n    \\\\\n    \\inferS{C}{\\E; \\bvar x{\\tau_2}}{e}{\\tau_1}\n    \\\\\n    \\Multi\\tvar = \\fv{\\tau_1,\\tau_2} \\setminus \\fv{\\E}\n  }{\n    \\SE \\vdash (\\VEnv, \\ilam {\\Multi\\kvar}{\\Multi\\tvar}Ckx{e})\n    : \\forall\\Multi\\kvar\\forall\\Multi{\\bvar{\\tvar}{k}}.(\\qual{C}{\\tau_2\\tarr{k}\\tau_1})\n  }\n  \\end{mathpar}\n\\item Relating storables to types $ \\SE \\vdash w : \\tau$\n  \\begin{mathpar}\n    \\ruleStorableClosure\n    \n    \\ruleStorablePair\n\n    \\ruleStorableResource\n\n    \\ruleStorableFreed\n  \\end{mathpar}\n%\\item Relating  results to types $ \\SE \\vdash r : \\tau$,\n\\item Relating results to type schemes $\\SE \\vdash r : \\schm$\n  \\begin{mathpar}\n    \\ruleResultConstant\n\n    \\ruleResultLocation\n\n    \\ruleResultBorrow\n  \\end{mathpar}\n\\item\nWe write $\\Affine\\SE\\Loc$ to express that $\\Loc$ points to a resource\nthat requires at least affine treatment. Borrow types do not appear in\nstore types as the store only knows about the actual resources.\n\nDefine  $\\Affine\\SE\\Loc$ if one of the following cases holds:\n\\begin{itemize}\n\\item $\\SE (\\Loc) =\n  \\forall\\Multi\\kvar\\forall\\Multi{\\bvar{\\tvar}{k}}.(\\qual{C}{\\tau_2\\tarr{k}\\tau_1})$\n  and $C \\wedge (k \\lk \\kun_\\infty)$ is contradictory;\n\\item $\\SE (\\Loc) = \\tau_2\\tarr{k}{\\tau_1}$ and $\\Cleq{\\kaff}{k}$;\n\\item $\\SE (\\Loc) = \\tyPair[k]{\\tau_1}{\\tau_2}$ and $\\Cleq \\kaff\n  k$;\n\\item $\\SE (\\Loc) = \\tapp{\\tcon}{\\Multi\\tau}$.\n% \\item if $\\SE (\\Loc) = \\borrow[\\MBORROW]\\tau$, then $\\Loc$ is affine\n%   \\dots (THAT SHOULDN'T REALLY  BE A STORE TYPE)\n% \\item if $\\SE (\\Loc) = \\borrow[\\IBORROW]\\tau$, then $\\Loc$ is not affine\n%   \\dots (THAT SHOULDN'T REALLY  BE A STORE TYPE)\n\\end{itemize}\n\\item\nWe write $\\Linear\\SE\\Loc$ to express that $\\Loc$ points to a linear\nresource.\n\nDefine  $\\Linear\\SE\\Loc$ if one of the following cases holds:\n\\begin{itemize}\n\\item $\\SE (\\Loc) =\n  \\forall\\Multi\\kvar\\forall\\Multi{\\bvar{\\tvar}{k}}.(\\qual{C}{\\tau_2\\tarr{k}\\tau_1})$\n  and $C \\wedge (k \\lk \\kaff_\\infty)$ is contradictory;\n\\item $\\SE (\\Loc) = \\tau_2\\tarr{k}{\\tau_1}$ and $\\Cleq{\\klin}{k}$;\n\\item $\\SE (\\Loc) = \\tyPair[k]{\\tau_1}{\\tau_2}$ and $\\Cleq \\klin\n  k$;\n\\item $\\SE (\\Loc) = \\tapp{\\tcon}{\\Multi\\tau}$.\n\\end{itemize}\n\\item\nIt remains to characterize unrestricted resources.\nDefine $\\Unrestricted\\SE\\Loc$ if neither $\\Affine\\SE\\Loc$ nor\n$\\Linear\\SE\\Loc$ holds.\n\\item\n  Relating environments to contexts\\\\\n  $\\SE \\vdash \\Active\\VEnv, \\MutableBorrows\\VEnv,\n\\ImmutableBorrows\\VEnv, \\Suspended[\\kaff]\\VEnv, \\Suspended[\\kun]\\VEnv : \\E$.\n\nHere we consider an\nenvironment $\\VEnv = (\\Active\\VEnv, \\MutableBorrows\\VEnv,\n\\ImmutableBorrows\\VEnv, \\Suspended\\VEnv)$ as a tuple\nconsisting of the active entries in $\\Active\\VEnv$ and the\nentries for exclusive borrows in $\\MutableBorrows\\VEnv$ and for\nshared borrows in $\\ImmutableBorrows\\VEnv$, and suspended entries\nin $\\Suspended\\VEnv = \\Suspended[\\kaff]\\VEnv, \\Suspended[\\kun]\\VEnv$\nfor affine and unrestricted entries. The\nsuspended entries cannot be used directly, but they can be activated\nby appropriate borrowing on entry to a region.\n\\end{itemize}\n\n\n\\begin{mathpar}\n  \\inferrule{}{\\SE \\vdash \\Sempty, \\Sempty, \\Sempty, \\Sempty : \\Eempty}\n  \\\\\n  \\inferrule{\n    \\SE \\vdash \\Active\\VEnv, \\MutableBorrows\\VEnv,\n    \\ImmutableBorrows\\VEnv, \\Suspended\\VEnv : \\E\n    \\\\ \\SE \\vdash r : \\schm\n    \\\\ \\Linear\\SE r}\n  {\\SE \\vdash \\Active\\VEnv[ x\\mapsto r], \\MutableBorrows\\VEnv ,\n    \\ImmutableBorrows\\VEnv, \\Suspended\\VEnv : \\E;\\bvar x\\schm }\n\n  \\inferrule{\n    \\SE \\vdash \\Active\\VEnv, \\MutableBorrows\\VEnv,\n    \\ImmutableBorrows\\VEnv, \\Suspended\\VEnv : \\E\n    \\\\ \\SE \\vdash r : \\schm\n    \\\\ \\Affine\\SE r}\n  {\\SE \\vdash \\Active\\VEnv, \\MutableBorrows\\VEnv[ x\\mapsto r] ,\n    \\ImmutableBorrows\\VEnv, \\Suspended\\VEnv : \\E;\\bvar x\\schm }\n\n  \\inferrule{\n    \\SE \\vdash \\Active\\VEnv, \\MutableBorrows\\VEnv,\n    \\ImmutableBorrows\\VEnv, \\Suspended\\VEnv : \\E\n    \\\\ \\SE \\vdash r : \\schm\n    \\\\ \\Unrestricted\\SE r}\n  {\\SE \\vdash \\Active\\VEnv, \\MutableBorrows\\VEnv,\n    \\ImmutableBorrows\\VEnv[ x\\mapsto r], \\Suspended\\VEnv : \\E;\\bvar\n    x\\schm }\n\n  \\inferrule{\\SE \\vdash \\Active\\VEnv, \\MutableBorrows\\VEnv,\n    \\ImmutableBorrows\\VEnv, \\Suspended[\\kaff]\\VEnv, \\Suspended[\\kun]\\VEnv : \\E \\\\\n    \\SE \\vdash r : \\schm}\n  { \\SE \\vdash \\Active\\VEnv, \\MutableBorrows\\VEnv,\n    \\ImmutableBorrows\\VEnv, \\Suspended[\\kaff]\\VEnv, \\Suspended[\\kun]\\VEnv[ x\\mapsto r] :\n    \\E;\\svar[\\IBORROW] x\\schm^n }\n\n  \\inferrule{\\SE \\vdash \\Active\\VEnv, \\MutableBorrows\\VEnv,\n    \\ImmutableBorrows\\VEnv, \\Suspended[\\kaff]\\VEnv, \\Suspended[\\kun]\\VEnv : \\E \\\\\n    \\SE \\vdash r : \\schm}\n  { \\SE \\vdash \\Active\\VEnv, \\MutableBorrows\\VEnv,\n    \\ImmutableBorrows\\VEnv, \\Suspended[\\kaff]\\VEnv[ x\\mapsto r], \\Suspended[\\kun]\\VEnv :\n    \\E;\\svar[\\MBORROW] x\\schm^n }\n\n  \\inferrule{\\SE \\vdash \\Active\\VEnv, \\MutableBorrows\\VEnv,\n    \\ImmutableBorrows\\VEnv, \\Suspended\\VEnv : \\E \\\\ \\SE \\vdash\n    \\IBORROW\\Addr : \\schm}\n  {\\SE \\vdash \\Active\\VEnv, \\MutableBorrows\\VEnv,\n    \\ImmutableBorrows\\VEnv[ x\\mapsto \\IBORROW\\Addr], \\Suspended\\VEnv :\n    \\E;\\bbvar[\\IBORROW] x k{ \\schm} }\n\n  \\inferrule{\\SE \\vdash \\Active\\VEnv, \\MutableBorrows\\VEnv,\n    \\ImmutableBorrows\\VEnv, \\Suspended\\VEnv : \\E \\\\ \\SE \\vdash\n    \\MBORROW\\Addr : \\schm}\n  {\\SE \\vdash \\Active\\VEnv, \\MutableBorrows\\VEnv[ x\\mapsto \\MBORROW\\Addr],\n    \\ImmutableBorrows\\VEnv, \\Suspended\\VEnv\n    : \\E;\\bbvar[\\MBORROW] x k{ \\schm} }\n\\end{mathpar}\n\\paragraph{Extending environments and stores}\n\\begin{mathpar}\n  \\inferrule{}{\\SE \\le \\SE}\n\n  \\inferrule{\\SE \\le \\SE' \\\\ \\Loc \\notin \\Dom\\Store}{\\SE \\le \\SE' (\\Loc : \\schm)}\n\\\\\n  \\inferrule{}{\\Store\\le\\Store}\n\n  \\inferrule{\\Store \\le \\Store' \\\\ \\Loc \\notin \\Dom\\Store\n  }{\\Store \\le \\Store'[ \\Loc \\mapsto w] }\n\\end{mathpar}\n\n\\begin{lemma}[Store Weakening]\\label{lemma:store-weakening}\n  $\\SE \\vdash \\VEnv : \\E$ and $\\SE \\le \\SE'$ implies $\\SE' \\vdash\n  \\VEnv : \\E$.\n\\end{lemma}\n\n\\begin{lemma}[Store Extension]\\label{lemma:store-extension-transitive}\n  \\begin{itemize}\n  \\item If $\\SE_1 \\le \\SE_2$ and $\\SE_2 \\le \\SE_3$, then $\\SE_1 \\le\n    \\SE_3$.\n  \\item If $\\Store_1 \\le \\Store_2$ and $\\Store_2 \\le \\Store_3$, then\n    $\\Store_1 \\le \\Store_3$.\n  \\end{itemize}\n\\end{lemma}\n\nWe write $\\Rawloc\\cdot$ for the function that extracts a multiset of\n\\emph{raw locations} from a result or from the range of the variable\nenvironment.\n\n\\begin{align*}\n  \\Rawloc{\\Multi\\BQ\\Loc} &= \\{\\Loc\\} \\\\\n  \\Rawloc{c} &= \\{ \\} \\\\\n  \\Rawloc\\Eempty &= \\{\\} \\\\\n  \\Rawloc{\\VEnv( x \\mapsto r)} &= \\Rawloc\\VEnv \\cup \\Rawloc r\n\\end{align*}\n\nWe write $\\Reach\\Store\\VEnv$ for the multiset of all \\emph{addresses}\nreachable from $\\Rawloc\\VEnv$\nassuming that $\\Rawloc\\VEnv \\subseteq \\Dom\\Store$\\footnote{In\n  mixed comparisons between a multiset and a set, we tacitly convert\n  a multiset $M$ to its supporting set $\\{ x \\mid \\MultiNumber x M \\ne 0\\}$.}.\nThe function $\\Reach\\Store\\cdot$ is defined in\ntwo steps. First a helper function\nfor results, storables, and environments.\n\n\\begin{align*}\n  \\RS\\Store\\Eempty &= \\Eempty \\\\\n  \\RS\\Store{\\VEnv (x \\mapsto r)} &= \\RS\\Store\\VEnv \\cup\n                                      \\RS\\Store r \\\\\n  \\RS\\Store\\Addr &= \\{ \\Addr \\}  \\\\\n  \\RS\\Store c &= \\{ \\} \\\\\n  \\RS\\Store{\\StPClosure \\VEnv {\\Multi\\kvar} C k x e} &=\n                                       \\RS\\Store\\VEnv\n  \\\\\n  \\RS\\Store{\\StClosure \\VEnv k x e} &=\n                                                   \\RS\\Store\\VEnv\n  \\\\\n  \\RS\\Store{\\StPair k {r_1} {r_2}} &=\n                                                   \\RS\\Store{r_1}\n                                                   \\cup \\RS\\Store{r_2}\n  \\\\\n  \\RS\\Store{\\StRes r} &=\n                                   \\RS\\Store r\n  \\\\\n  \\RS\\Store{\\StFreed} &= \\{ \\}\n\\end{align*}\n\nThis multiset is closed transitively by store lookup. We define\n$\\Reach\\Store\\VEnv$ as the smallest multiset $\\REACH$ that fulfills\nthe following inequations. We assume a nonstandard\nmodel of multisets such that an element $\\Loc$ may occur infinitely often as in\n$\\MultiNumber\\Loc\\REACH = \\infty$.\n\\begin{align*}\n  \\REACH &\\supseteq \\RS\\Store\\VEnv \\\\\n  \\REACH &\\supseteq \\RS\\Store w & \\text{if }\n                                     \\Multi\\BQ\\Loc\n                                     \\in \\REACH \\wedge w = \\Store (\\Loc)\n\\end{align*}\n\n\\begin{definition}[Wellformed permission]\n  A permission $\\Perm$ is \\emph{wellformed} if it contains at most one\n  address for each raw location.\n\\end{definition}\n\\begin{definition}[Permission closure]\n  The closure of a permission $\\Sclos\\Perm$ is the set of addresses\n  reachable from $\\Perm$ by stripping an arbitrary number of borrows\n  from it. It is the homomorphic extension of the closure\n  $\\Sclos\\Addr$ for a single address.\n  \\begin{align*}\n    \\Sclos\\Loc & = \\{ \\Loc \\} & \\Sclos{(\\BQ\\Addr)} & = \\{ \\BQ\\Addr \\}  \\cup \\Sclos\\Addr\n  \\end{align*}\n\\end{definition}\n\n\\begin{lemma}[Containment]\\label{lemma:containment}\n  Suppose that $\\vdash \\Store : \\SE$,\n  $\\SE \\vdash r : \\tau$, $\\entail C\n  {\\Cleq{\\tau}{k} \\Cand \\Cleq{k}{\\klin_{m-1}}}$.\n  Then $\\Reach\\Store r$ cannot contain addresses $\\Addr$ such that\n  $\\Addr = \\BORROW_n\\Addr'$ with $n\\ge m$.\n\\end{lemma}\n\\begin{proof}\n  By inversion of result typing there are three cases.\n\n  \\textbf{Case }$\\ruleResultConstant$. Immediate: reachable set\n  is empty.\n\n  \\textbf{Case }$\\ruleResultBorrow$. The typing constraint enforces\n  that $n < m$.\n\n  \\textbf{Case }$\\ruleResultLocation$. We need to continue by\n  dereferencing $\\Loc$ and inverting store typing.\n\n  \\textbf{Case }$\\ruleStorableFreed$. Trivial.\n\n  \\textbf{Case }$\\ruleStorableResource$. We assume the implementation\n  type of a result to be unrestricted.\n\n  \\textbf{Case }$\\ruleStorablePair$.\n\n  The typing constraint yields that $k \\le \\klin_{m-1}$.\n  By induction and transitivity of $\\le$, we find that\n  $\\Reach\\Store{r_1}$ and $\\Reach\\Store{r_2}$ cannot contain offending addresses.\n\n  \\textbf{Case }$\\ruleStorableClosure$.\n\n  The typing constraint yields that $k\\le\\klin_{m-1}$.\n  By transitivity of $\\le$ and $\\SE \\vdash \\VEnv:\\E$, we find that the\n  types of all addresses in \n  $\\VEnv$ have types bounded by $\\klin_{m-1}$ and, by induction, they\n  cannot contain offending addresses.\n\\end{proof}\n\\clearpage{}\n\\lstMakeShortInline[keepspaces,style=rule]@\n\n\\SoundnessThm\n\nSome explanations are in order for the resource-related assumptions\nand statements.\n\nIncoming resources are always active (i.e., not freed).\nLinear and affine resources as well as suspended affine borrows have\nexactly one pointer in the environment.\n\nThe Frame condition states that only store locations reachable from\nthe current environment can change and that all permissions outside\nthe reachable locations remain the same.\n\nUnrestricted values, resources, and borrows do not change their\nunderlying resource and do not spend their permission.\n\nAffine borrows and resources may or may not spend their\npermission. Borrows are not freed, but resources may be freed. The\npermissions for suspended entries remain intact.\n\n% Incoming suspended borrows have no permission attached to them and\n% their permission has been retracted on exit of their region.\n\nA linear resource is always freed.\n\nOutgoing permissions are either inherited from the caller or they\nrefer to newly created values.\n\n\n\n\\newpage\n\\begin{proof}\n  By induction on the evaluation of\n  @eval \\Store \\Perm \\VEnv i e@.\n\n  The base case is trivial as\n  @eval \\Store \\Perm \\VEnv 0 e = \\TimeOut@.\n\n  For $i>0$ consider the different cases for expressions. For lack of\n  spacetime, we only give details on some important cases.\n\n  \\textbf{Case $e$ of}\n  \\lstsemrule{slet}\n  We need to invert rule \\TirName{Let} for monomorphic let:\n  \\begin{gather*}\n    \\ruleSDILet\n    % \\ruleSDLet\n  \\end{gather*}\n  %% PJT: separate lemma about splitting needed\n  As $\\Sp$ is the evidence for the splitting judgment and @vsplit@\n  distributes values according to $\\Sp$, we obtain\n  \\begin{gather}\n    \\label{eq:16}\n    \\SE \\vdash \\VEnv_1 : \\E_1\n    \\\\\\label{eq:17}\n    \\SE \\vdash \\VEnv_2 : \\E_2\n  \\end{gather}\n  Moreover (using $\\uplus$ for disjoint union),\n  \\begin{itemize}\n  \\item $\\Active\\VEnv = \\Active{\\VEnv_1} \\uplus\\Active{\\VEnv_2}$,\n  \\item $\\MutableBorrows\\VEnv = \\MutableBorrows{\\VEnv_1} \\uplus\n    \\MutableBorrows{\\VEnv_2}$,\n  \\item $\\ImmutableBorrows\\VEnv =\n    \\ImmutableBorrows{\\VEnv_1} = \\ImmutableBorrows{\\VEnv_2}$,\n  \\item $\\Suspended\\VEnv = \\Suspended{\\VEnv_1} \\uplus\n    \\Suspended{\\VEnv_2}$ (this splitting does not distinguish potentially\n    unrestricted or affine bindings)\n  \\end{itemize}\n  We establish the assumptions for the call\n  @eval \\Store \\Perm \\VEnv_1  i' e_1@.\n  \\begin{enumerate}[({A1-}1)]\n  \\item From inversion: $\\inferS{C \\Cand D}{\\E_1}{e_1}{\\tau_1} $\n  \\item From~\\eqref{eq:16}: $\\SE \\vdash \\VEnv_1 : \\E_1$\n  \\item From assumption\n  \\item From assumption\n  \\item From assumption because $\\VEnv_1$ is projected from $\\VEnv$.\n  \\item From assumption because $\\VEnv_1$ is projected from $\\VEnv$.\n  \\item From assumption because $\\VEnv_1$ is projected from $\\VEnv$.\n  \\end{enumerate}\n  Hence, we can apply the induction hypothesis and obtain\n  \\begin{enumerate}[({R1-}1)]\n  \\item \\resultOk{}{_1}\n  \\item\\label{item:8} \\resultEnv{}{_1}\n  \\item\\label{item:9} $\\SE_1 \\vdash r_1 : \\tau_1$\n  \\item\\label{item:14} \\resultPermDom{}{_1}\n  \\item\\label{item:13} \\resultReachPerm{}{_1}\n  \\item\\label{item:16} \\resultFrame{}{_1}{_1}\n  \\item\\label{item:24} \\resultImmutables{}{}{_1}\n  \\item\\label{item:26} \\resultMutables{}{}{_1}\n  % \\item\\label{item:28} \\resultSuspended{}{}{_1}\n  \\item\\label{item:30} \\resultResources{}{}{_1}\n  \\item\\label{item:10} \\resultThinAir{}{_1}\n  \\end{enumerate}\n  To establish the assumptions for the call \\\\\n  @eval delta_1 pi_1 gamma_2(x-:>r_1) i' e_2@,\n  we write $\\VEnv_2' = \\VEnv (x \\mapsto r_1)$.\n  \\begin{enumerate}[({A2-}1)]\n  \\item From inversion: $\\inferS{C}{\\E;\\bvar{x}{\\tau_1}}{e_2}{\\tau_2}$\n  \\item From~\\eqref{eq:17} we have $\\SE \\vdash \\VEnv_2 : \\E_2$.\n    By store weakening (Lemma~\\ref{lemma:store-weakening}) and\n    using~\\ref{item:8}, we have\n    $\\SE_1 \\vdash \\VEnv_2 : \\E_2$.\n    With~\\ref{item:9}, we obtain\n    $\\SE_1 \\vdash \\VEnv_2 (x \\mapsto r_1 ) : \\E_2;\\bvar x {\\tau_1}$.\n  \\item Immediate from~\\ref{item:8}.\n  \\item Immediate from~\\ref{item:14}.\n  \\item Show \\assumeReachable{_1}{'_2}\\\\\n    % $\\Reach{\\Store_1}{\\Active{\\VEnv_2'}, \\MutableBorrows{\\VEnv_2'},\n    %   \\ImmutableBorrows{\\VEnv_2'}} \\subseteq \\Perm_1$ \\\\\n    From~\\ref{item:12}, we have\n    \\assumeReachable{_1}{_2}\n    % $\\Reach{\\Store_1}{\\Active{\\VEnv_2}, \\MutableBorrows{\\VEnv_2},\n    %   \\ImmutableBorrows{\\VEnv_2}} \\subseteq \\Perm_1$.\n    The extra\n    binding $(x \\mapsto r_1)$ goes into one of the compartments\n    according to its type. We conclude by~\\ref{item:13}.\n  \\item Disjointness holds by assumption for $\\VEnv_2$ and it remains\n    to discuss $r_1$. But $r_1$ is either a fresh resource, a\n    linear/affine resource from $\\VEnv_1$ (which is disjoint), or\n    unrestricted. In each case, there is no overlap with another\n    compartment of the environment.\n  \\item We need to show\n    \\assumeIncoming{_1}{_2'}\n    The first item holds by assumption, splitting, and (for $r_1$)\n    by~\\ref{item:14} and~\\ref{item:13}.\n\n    The second and third items hold by assumption~\\ref{item:15},\n    splitting, and framing~\\ref{item:16}.\n  \\end{enumerate}\n  Hence, we can apply the induction hypothesis and obtain\n  \\begin{enumerate}[({R2}-1)]\n  \\item\\label{item:17} \\resultOk{_1}{_2}\n  \\item\\label{item:18} \\resultEnv{_1}{_2}\n  \\item\\label{item:19} $\\SE_2 \\vdash r_2 : \\tau_2$\n  \\item\\label{item:20} \\resultPermDom{_1}{_2}\n  \\item\\label{item:21} \\resultReachPerm{_1}{_2}\n  \\item\\label{item:22} \\resultFrame{_1}{_2'}{_2}\n  \\item\\label{item:23} \\resultImmutables{_1}{_2'}{_2}\n  \\item\\label{item:25} \\resultMutables{_1}{_2'}{_2}\n  % \\item\\label{item:27} \\resultSuspended{_1}{_2'}{_2}\n  \\item\\label{item:29} \\resultResources{_1}{_2'}{_2}\n  \\item\\label{item:31} \\resultThinAir{_1}{_2}\n  \\end{enumerate}\n\n  It remains to establish the assertions for the let expression.\n  \\begin{enumerate}[({R}-1)]\n  \\item \\resultOk{_1}{_2}\n    \\\\ Immediate from~\\ref{item:17}.\n  \\item \\resultEnv{}{_2}\n    \\\\ Transitivity of store extension\n    (Lemma~\\ref{lemma:store-extension-transitive}), \\ref{item:18},\n    and~\\ref{item:8}.\n  \\item  $\\SE_2 \\vdash r_2 : \\tau_2$\n    \\\\ Immediate from~\\ref{item:19}.\n  \\item \\resultPermDom{}{_2}\n    \\\\ Immediate from~\\ref{item:20}.\n  \\item \\resultReachPerm{}{_2}\n    \\\\ Immediate from~\\ref{item:21}\n    %% \\textcolor{red}\n    {because $\\Reach{\\Store_2}{\\VEnv_1}\n    \\subseteq \\Reach{\\Store_2}{\\VEnv} $ and\n    $\\Reach{\\Store_2}{\\Suspended{\\VEnv_1}} \\subseteq\n    \\Reach{\\Store_2}{\\Suspended\\VEnv}$.\n    Moreover, $\\Dom\\Store \\subseteq \\Dom{\\Store_1}$.\n  }\n\\item \\resultFrame{}{}{_2}\n    ~\\\\ Suppose that $\\Loc \\in \\Dom\\Store \\setminus\n    \\Rawloc{\\Reach{\\Store_2}{\\VEnv}}$.\n    \\\\ Then $\\Loc \\in \\Dom\\Store \\setminus\n    \\Rawloc{\\Reach{\\Store_1}{\\VEnv_1}}$.\n    \\\\ By~\\ref{item:16}, $\\Store_1 (\\Loc) = \\Store (\\Loc)$ and for any\n    $\\Addr$ with $\\Rawloc\\Addr = \\{\\Loc\\}$: $\\Addr \\in \\Perm\n    \\Leftrightarrow \\Addr \\in \\Perm_1$.\n    \\\\ But also $\\Loc \\in \\Dom{\\Store_1} \\setminus\n    \\Rawloc{\\Reach{\\Store_2}{\\VEnv_2'}}$.\n    \\\\ By~\\ref{item:22}, $\\Store_2 (\\Loc) = \\Store_1 (\\Loc)$ for\n    applicable $\\Addr$, $\\Addr \\in \\Perm_1\n    \\Leftrightarrow \\Addr \\in \\Perm_2$.\n    \\\\ Taken together, we obtain the claim.\n  \\item \\resultImmutables{}{}{_2}\n    \\\\ Follows from~\\ref{item:23} or~\\ref{item:24} because\n    $\\ImmutableBorrows\\VEnv = \\ImmutableBorrows{\\VEnv_1} =\n    \\ImmutableBorrows{\\VEnv_2}$.\n  \\item \\resultMutables{}{}{_2}\n    \\\\ Follows from~\\ref{item:25},~\\ref{item:26}, and framing.\n  % \\item \\resultSuspended{}{}{_2}\n  %   ~\\\\ Follows from~\\ref{item:27},~\\ref{item:28}, and framing.\n  \\item \\resultResources{}{}{_2}\n    \\\\ Follows from disjoint splitting of\n    $\\Active\\VEnv$,~\\ref{item:29},~\\ref{item:30}, and framing.\n  \\item \\resultThinAir{}{_2}\n    \\\\ Immediate from~\\ref{item:31}.\n  \\end{enumerate}\n\n  \\newpage{}\n  \\textbf{Case $e$ of}\n  \\lstsemrule{sappanf}\n\n  We need to invert rule \\TirName{App}:\n  \\begin{mathpar}\n    \\ruleSDAIApp\n    %\\ruleSDVApp\n  \\end{mathpar}\n\n  We need to establish the assumptions for the recursive call\n  @eval \\Store' \\Perm' \\VEnv'(x'-:>r_2) i' e'@.\n  We write $\\VEnv_2' = \\VEnv' (x'\\mapsto r_2)$.\n  \\begin{enumerate}[({A1-}1)]\n  \\item $\\inferS{C'}{\\E'; \\bvar{x'}{\\tau_2}}{e'}{\\tau_1}$, for some\n    $C'$ and $\\E'$\\\\\n    Applying the first premise of \\TirName{App} to $r_1 = \\VEnv\n    (x_1)$, $\\SE \\vdash \\VEnv : \\E$, and inversion of result typing\n    yields that $r_1 = \\Loc_1$ with $\\SE (\\Loc_1) = \\tau_2 \\tarr{k}\n    \\tau_1$.\n    By inversion of store typing and storable typing, we find that\n    there exist $\\E'$ and $C'$ such that\n    \\begin{enumerate}\n    \\item $\\Store (\\Loc_1) = (\\VEnv', \\lam[k]{x'}{e'})$\n    \\item $\\Disjoint{\\E'}$\n    \\item\\label{item:32} $\\SE \\vdash \\VEnv', \\E'$\n    \\item $\\inferS{C'}{\\E';\\bvar {x'}{\\tau_2}}{e'}{\\tau_1}$\n    \\item $\\addlin{\\entail{C'}{\\Cleq{\\E'}{k}}}$\n    \\end{enumerate}\n  \\item $\\SE \\vdash \\VEnv' (x' \\mapsto r_2) : \\E';\n    \\bvar{x'}{\\tau_2}$\\\\\n    By~\\ref{item:32}, assumption on $\\VEnv$, and the subtyping premise.\n  \\item $\\vdash \\Store' : \\SE'$ \\\\\n    by assumption and the released rule of store typing (where we\n    write $\\SE'=\\SE$ henceforth)\n  \\item \\assumeWellformed{'} \\\\\n    the possible removal of a permission does not violate\n    wellformedness; the permission is taken away exactly when the\n    closure is destroyed\n  \\item\n    \\assumeReachable{}{'_2} \\\\\n    as the reach set is a subset of the incoming environment's reach\n  \\item $\\Rawloc{\\Active{\\VEnv_2'}}$,\n    $\\Rawloc{\\MutableBorrows{\\VEnv_2'}}$,\n    $\\Rawloc{\\ImmutableBorrows{\\VEnv_2'}}$, and\n    $\\Rawloc{\\Suspended{\\VEnv_2'}}$ are all disjoint follows from\n    $\\Disjoint{\\E'}$ and since $r_2= \\E (x_2)$ which is an entry\n    disjoint from the closure $\\E(x_1)$.\n  \\item \\assumeIncoming{'}{_2'}\n    The first item holds because of assumption~\\ref{item:15}.\n\n    The second item holds because $\\REACH' \\subseteq \\REACH$ from\n    assumption~\\ref{item:15}.\n  \\end{enumerate}\n  The inductive hypothesis yields that\n    $\\exists$ $\\Store_3$, $\\Perm_3$, $r_3$, $\\SE_3$ such that\n  \\begin{enumerate}[({R1-}1)]\n  \\item \\resultOk{}{_3}\n  \\item \\resultEnv{'}{_3}\n  \\item $\\SE_3 \\vdash r_3 : \\tau_1$\n  \\item \\resultPermDom{}{_3}\n  \\item \\resultReachPerm{}{_3}\n  \\item \\resultFrame{'}{_2'}{_3}\n  \\item \\resultImmutables{'}{_2'}{_3}\n  \\item \\resultMutables{'}{_2'}{_3}\n    % \\item \\resultSuspended{}{}{'}\n  \\item \\resultResources{'}{_2'}{_3}\n  \\item \\resultThinAir{'}{_3}\n  \\end{enumerate}\n  The desired results are immediate because $\\Dom\\Store = \\Dom{\\Store'}$.\n\n  \\newpage{}\n  \\textbf{Case $e$ of}\n  \\lstsemrule{sregion}\n\n  We need to invert rule \\TirName{Region}\n  \\begin{mathpar}\n    \\ruleSDRegion\n  \\end{mathpar}\n\n  We need to establish the assumptions for the recursive call\n  @eval \\Store \\Perm' \\VEnv' i' e'@ where  $\\VEnv' =\n  \\VEnv (x\\mapsto \\Addr')$.\n\n  \\begin{enumerate}[({A1-}1)]\n  \\item $\\inferS{C}{\\E'}{e}{\\tau}$ \\\\\n    immediate from the inverted premise\n  \\item $\\SE \\vdash \\VEnv' : \\E'$ \\\\\n    the only change of the environments is at $x$; adding the borrow\n    modifier $\\BORROW$ succeeds due to the second premise; the address $\\Addr'$\n    stored into $x$ is compatible with its type by store typing\n  \\item $\\vdash \\Store : \\SE$ \\\\\n    Immediate by outer assumption\n  \\item\\label{item:11} \\assumeWellformed{} \\\\\n    Immediate by outer assumption; adding the modifier does not change\n    the underlying raw location\n  \\item\\label{item:12} \n    \\assumeReachable{}{'} \\\\\n    locations were swapped simultaneously\n    %% this may not work because the pair's components do not change\n    %% their permissions\n  \\item $\\Rawloc{\\Active{\\VEnv'}}$,\n    $\\Rawloc{\\MutableBorrows{\\VEnv'}}$,\n    $\\Rawloc{\\ImmutableBorrows{\\VEnv'}}$, and\n    $\\Rawloc{\\Suspended{\\VEnv'}}$ are all disjoint \\\\\n    Immediate by assumption\n  % \\item  $\\VEnv'$ with $\\Rawloc{\\VEnv'}\n  %   \\subseteq \\Dom\\Store$ and $\\Dom\\VEnv \\cap \\Dom{\\VEnv'}=\\emptyset$\n  \\item\\label{item:15} \\assumeIncoming{}{'}\n    Immediate by assumption.\n  \\end{enumerate}\n\n  The induction hypothesis yields the following statements.\n  $\\exists$ $\\Store_1$, $\\Perm_1$, $r_1$, $\\SE_1$ such that\n  \\begin{enumerate}[({R1-}1)]\n  \\item \\resultOk{}{_1}\n  \\item \\resultEnv{}{_1}\n  \\item $\\SE_1 \\vdash r_1 : \\tau$\n  \\item \\resultPermDom{}{_1}\n  \\item \\resultReachPerm{}{_1}\n  \\item \\resultFrame{}{'}{_1}\n  \\item \\resultImmutables{}{'}{_1}\n  \\item \\resultMutables{}{'}{_1}\n  % \\item \\resultSuspended{}{}{'}\n  \\item \\resultResources{}{'}{_1}\n  \\item \\resultThinAir{}{_1}\n  \\end{enumerate}\n\n  It remains to derive the induction hypothesis in the last line. The\n  only additional action is the exchange of permissions which\n  withdraws the borrow.\n  \\begin{enumerate}[({R}1)]\n  \\item \\resultOk{}{_1}\\\\\n    Immediate\n  \\item \\resultEnv{}{_1}\\\\\n    Immediate\n  \\item $\\SE_1 \\vdash r_1 : \\tau$\\\\\n    Immediate\n  \\item \\resultPermDom{}{_1} \\\\\n    The addresses $\\Addr$ and $\\Addr'$ (as well as the elements of\n    $\\Perm'$ and $\\Perm''$) have the same raw location, so\n    exchanging them does not affect wellformedness. The underlying set\n    of locations does not change.\n  \\item \\resultReachPerm{}{_1} \\\\\n    This case is critical for region encapsulation. Here we need to\n    argue that $\\Addr'$ (and hence $\\Perm''$) is not reachable from $r_1$ because its type\n    $\\tau$ is bounded by $\\klin_{n-1}$ according to the fourth\n    premise. We conclude with Lemma~\\ref{lemma:containment}.\n    %%% need lemma\n  \\item \\resultFrame{}{'}{_1}\n    Immediate\n  \\item \\resultImmutables{}{'}{_1} \\\\\n    Immediate\n  \\item \\resultMutables{}{'}{_1} \\\\\n    Immediate\n  % \\item \\resultSuspended{}{}{'}\n  \\item \\resultResources{}{'}{_1} \\\\\n    Immediate\n  \\item \\resultThinAir{}{_1} \\\\\n    Immediate\n  \\end{enumerate}\n\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n  \\newpage{}\n  \\textbf{Case $e$ of}\n  \\lstsemrule{screateanf}\n\n  We need to invert the corresponding rule\n  \\begin{mathpar}\n    \\ruleSDCreate\n  \\end{mathpar}\n\n  It is sufficient to show that there is some $\\SE_1 = \\SE(\\Loc_1 :\n  \\tapp\\tres\\tau)$ such that  \n  $\\Store_1$, $\\Perm_1$, and $r_1 = \\Loc_1$ fulfill the following requirements.\n  \\begin{enumerate}[({R}1)]\n  \\item \\resultOk{}{_1}\n  \\item \\resultEnv{}{_1} \\\\\n    For the last item, we need to show that $\\SE (\\Loc_1) :\n    \\tapp\\tres\\tau$, but this follows from the setting of $w$ to a\n    resource storable in the semantics.\n  \\item $\\SE_1 \\vdash r_1 : \\tapp\\tres\\tau$ \\\\\n    Immediate from the discussion of the preceding case\n  \\item \\resultPermDom{}{_1} \\\\\n    Follows from the assumption on $\\Perm$ and for $\\Loc_1$ from the\n    allocation of the resource.\n  \\item \\resultReachPerm{}{_1} \\\\\n    Immediate from the assignment to $\\Perm_1$.\n  \\item \\resultFrame{}{}{_1} \n    Obvious as no existing location is changed.\n  \\item \\resultImmutables{}{}{_1} \\\\\n    Obvious as no existing location has changed and no permission is withdrawn.\n  \\item \\resultMutables{}{}{_1} \\\\\n    Obvious as no existing location has changed and no permission is\n    withdrawn.\n    % \\item \\resultSuspended{}{}{'}\n  \\item \\resultResources{}{}{_1} \\\\\n    By the constraint on $\\E$ in the \\TirName{Create} rule, $\\Active\\VEnv = \\emptyset$.\n  \\item \\resultThinAir{}{_1} \\\\\n    Immediate\n  \\end{enumerate}\n  \n  \\newpage\n  \\textbf{Case $e$ of}\n  \\lstsemrule{sdestroyanf}\n\n  We need to invert rule \\TirName{Destroy}.\n  \\begin{mathpar}\n    \\ruleSDDestroy\n  \\end{mathpar}\n  It is sufficient to show that $\\SE_1 = \\SE$,\n  $\\Store_1$, $\\Perm_1$, and $r_1 = ()$ fulfill the following\n  requirements.\n  \\begin{enumerate}[({R}1)]\n  \\item \\resultOk{}{_1}\n  \\item \\resultEnv{}{_1} \\\\\n    Immediate: $\\Loc$ was updated to void, which has any type.\n  \\item $\\SE_1 \\vdash () : \\tunit$\n  \\item \\resultPermDom{}{_1}\\\\\n    By assumption on $\\Perm$ and because $\\Loc$ was removed.\n  \\item \\resultReachPerm{}{_1} \\\\\n    Immediate because the reach set is empty\n  \\item \\resultFrame{}{}{_1} \n    Only $\\Store (\\Loc)$ was changed, which is not reachable from the frame.\n  \\item \\resultImmutables{}{}{_1} \\\\\n    Immediate because we updated (destroyed) a resource (in $\\Active\\VEnv$).\n  \\item \\resultMutables{}{}{_1} \\\\\n    Immediate because we updated (destroyed) a resource (in $\\Active\\VEnv$).\n  % \\item \\resultSuspended{}{}{'}\n  \\item \\resultResources{}{}{_1} \\\\\n    By the constraint on $\\E$, $\\Loc$ was the only resource passed to\n    this invocation of eval. The claimed condition holds as $\\Loc$ was\n    removed from $\\Perm_1$ and the location's contents cleared.\n  \\item \\resultThinAir{}{_1}\n    \\\\ Immediate\n  \\end{enumerate}\n\n  \\newpage\n  \\textbf{Case $e$ of}\n  \\lstsemrule{var}\n\n  We need to invert rule \\TirName{Var}.\n  \\begin{mathpar}\n    \\ruleSDIVar\n  \\end{mathpar}\n\n  We establish that the claims hold for\n  $\\Store' = \\Store$, $\\Perm' = \\Perm$, $r = \\VEnv (x)$, and $\\SE' = \\SE$.\n  \\begin{enumerate}[({R}1)]\n  \\item \\resultOk{}{}\n  \\item \\resultEnv{}{}\n    \\\\ Immediate by reflexivity and assumption.\n  \\item $\\SE \\vdash r : \\tau$\n    \\\\ Immediate by assumption~\\ref{item:32}.\n  \\item \\resultPermDom{}{}\n    \\\\ Immediate by assumption~\\ref{item:11}\n  \\item \\resultReachPerm{}{}\n    \\\\ Immediate\n  \\item \\resultFrame{}{}{}\n    Immediate as permissions and store stay the same.\n  \\item \\resultImmutables{}{}{}\n    \\\\ Immediate\n  \\item \\resultMutables{}{}{}\n    \\\\Immediate\n  % \\item \\resultSuspended{}{}{'}\n  \\item \\resultResources{}{}{}\n    \\\\ As $\\Perm$ remains the same, a linear resource in $x$ is\n    returned untouched.\n  \\item \\resultThinAir{}{}\n    \\\\ Immediate\n  \\end{enumerate}\n\n  \\newpage\n  \\textbf{Case $e$ of}\n  \\lstsemrule{const}\n\n  We need to invert rule \\TirName{Const}.\n  \\begin{mathpar}\n    \\ruleSDConst\n  \\end{mathpar}\n\n  We need to establish the claims for $\\Store' = \\Store$,\n  $\\Perm'=\\Perm$, $r' = c$, and $\\SE' = \\SE$:\n  \\begin{enumerate}[({R}1)]\n  \\item \\resultOk{}{}\n  \\item \\resultEnv{}{} \\\\\n    By assumption~\\ref{item:33}.\n  \\item $\\SE \\vdash c : \\CType c$\n    \\\\by result typing.\n  \\item \\resultPermDom{}{}\n    \\\\ By assumption~\\ref{item:11}.\n  \\item \\resultReachPerm{}{}\n    \\\\ As $\\Reach\\Store c = \\emptyset$.\n  \\item \\resultFrame{}{}{}\n    Immediate\n  \\item \\resultImmutables{}{}{}\n    \\\\ Immediate\n  \\item \\resultMutables{}{}{}\n  % \\item \\resultSuspended{}{}{'}\n  \\item \\resultResources{}{}{}\n    \\\\ Immediate as $\\Active\\VEnv = \\emptyset$.\n  \\item \\resultThinAir{}{}\n    \\\\ Immediate\n  \\end{enumerate}\n\n  \\newpage\n  \\textbf{Case $e$ of}\n  \\lstsemrule{spairanf}\n\n  We need to invert rule \\TirName{Pair}.\n  \\begin{mathpar}\n    \\ruleSDAIPair\n  \\end{mathpar}\n  Show that $\\Store'$, $\\Perm'$, $r' = \\Loc'$, $\\SE' = \\SE (\\Loc' : \\tyPair[k]{\\tau_1}{\\tau_2})$ such that\n  \\begin{enumerate}[({R}1)]\n  \\item \\resultOk{}{'}\n  \\item \\resultEnv{}{'}\n  \\item $\\SE' \\vdash \\Loc' : \\tyPair{\\tau_1}{\\tau_2}$\n  \\item \\resultPermDom{}{'}\n    \\\\ By assumption~\\ref{item:11} and because $\\Loc'$ is properly initialized.\n  \\item \\resultReachPerm{}{'}\n    \\\\ By assumption~\\ref{item:12}, $\\Reach{\\Store'}{\\Loc'} =\n    \\Reach\\Store{r_1, r_2} \\cup \\{\\Loc'\\} \\subseteq\n    \\Reach{\\Store}\\VEnv \\cup \\{\\Loc'\\}$ and $\\{\\Loc'\\} = \\Dom{\\Store'}\n    \\setminus \\Dom\\Store$.\n  \\item \\resultFrame{}{}{'}\n    Immediate\n  \\item \\resultImmutables{}{}{'}\n    \\\\ Immediate\n  \\item \\resultMutables{}{}{'}\n    \\\\ Immediate\n  % \\item \\resultSuspended{}{}{'}\n  \\item \\resultResources{}{}{'}\n    \\\\ Every such $\\Loc$ must be reachable either from $r_1$ or\n    $r_2$. So they become reachable from $\\Loc'$, as required.\n  \\item \\resultThinAir{}{'}\n    \\\\ Immediate\n  \\end{enumerate}\n\n  \\newpage\n  \\textbf{Case $e$ of}\n  \\lstsemrule{lam}\n\n  We need to invert rule \\TirName{Abs}\n  \\begin{mathpar}\n    \\ruleSDLam\n  \\end{mathpar}\n\n  Show that $\\Store'$, $\\Perm'$, $r' = \\Loc'$, and $\\SE' = \\SE (\\Loc'\n  : \\tau_2\\tarr{k}\\tau_1)$ fulfill\n  \\begin{enumerate}[({R}1)]\n  \\item \\resultOk{}{'}\n  \\item \\resultEnv{}{'} \\\\\n    Immediate by definition and store typing\n  \\item $\\SE' \\vdash r' : \\tau_2\\tarr{k}\\tau_1$ \\\\\n    Immediate by store typing\n  \\item \\resultPermDom{}{'} \\\\\n    Wellformedness holds by assumption on $\\Perm$ and because $\\Loc'$ is a new location.\n    The domain constraint is assumed for $\\Perm$ and $\\Loc'$ is\n    initialized to a  closure.\n  \\item \\resultReachPerm{}{'} \n    \\begin{align*}\n      \\Reach{\\Store'}{r'} & = \\{ \\Loc' \\} \\cup \\Reach{\\Store'}{\\VEnv} \\\\\n      &= \\Dom{\\Store'}\\setminus\\Dom\\Store \\cup \\Reach{\\Store'}{\\VEnv}\n    \\end{align*}\n    Moreover, the constraint ${\\Cleq{\\E}{k}}$ implies that\n    $\\Suspended\\VEnv = \\emptyset$.\n  \\item \\resultFrame{}{}{'} \n    Immediate\n  \\item \\resultImmutables{}{}{'}   \\\\\n    Immediate\n  \\item \\resultMutables{}{}{'} \\\\\n    Immediate\n  % \\item \\resultSuspended{}{}{'}\n  \\item \\resultResources{}{}{'} \\\\\n    The second case is immediately applicable.\n  \\item \\resultThinAir{}{'} \\\\\n    Immediate\n  \\end{enumerate}\n\n  \\newpage\n  \\textbf{Case $e$ of}\n  \\lstsemrule{sborrow}\n\n  We have to invert rule \\TirName{Borrow}\n  \\begin{mathpar}\n    \\ruleSDBorrow\n  \\end{mathpar}\n\n  Show that $\\Store' = \\Store$, $\\Perm' = \\Perm$, $r' = \\Addr$, $\\SE'\n  = \\SE$ such that\n  \\begin{enumerate}[({R}1)]\n  \\item \\resultOk{}{'}\n  \\item \\resultEnv{}{'} \\\\\n    Immediate, no changes.\n  \\item $\\SE' \\vdash r' : \\borrowty{k}{\\tau}$\\\\\n    Immediate by result typing and because the interpreter checks that\n    the permissions of the borrow are very restricted.\n  \\item \\resultPermDom{}{'}\\\\\n    Immediate (no change).\n  \\item \\resultReachPerm{}{'} \\\\\n    By typing, $\\Addr$ is not in $\\Suspended\\VEnv$.\n    Hence,  the condition is immediate.\n  \\item \\resultFrame{}{}{'} \n    Immediate as no change.\n  \\item \\resultImmutables{}{}{'}\\\\\n    Immediate as no change\n  \\item \\resultMutables{}{}{'} \\\\\n    Immediate\n  % \\item \\resultSuspended{}{}{'}\n  \\item \\resultResources{}{}{'} \\\\\n    Immediate because $\\REACH$, $\\REACH'$ must be empty\n  \\item \\resultThinAir{}{'}\\\\\n    Immediate.\n  \\end{enumerate}\n\n  \\newpage\n  \\textbf{Case $e$ of}\n  \\lstsemrule{sobserveanf}\n\n  We have to invert the rule \\TirName{Observe}\n  \\begin{mathpar}\n    \\ruleSDObserve\n  \\end{mathpar}\n  Show that $\\Store' = \\Store$, $\\Perm' = \\Perm$, $r'$, and $\\SE' =\n  \\SE$ fulfill\n  \\begin{enumerate}[({R}1)]\n  \\item \\resultOk{}{'}\n  \\item \\resultEnv{}{'} \\\\\n    By reflexivity and assumption.\n  \\item $\\SE' \\vdash r' : \\tau$ \\\\\n    Immediate by store typing\n  \\item \\resultPermDom{}{'} \\\\\n    Immediate: no changes.\n  \\item \\resultReachPerm{}{'} \\\\\n    Immediate\n  \\item \\resultFrame{}{}{'}\n    Immediate: no changes.\n  \\item \\resultImmutables{}{}{'} \\\\\n    Immediate: no changes to immutables.\n  \\item \\resultMutables{}{}{'}  \\\\\n    Immediate: one particular $\\Addr$ is overwritten, but not freed.\n  % \\item \\resultSuspended{}{}{'}\n  \\item \\resultResources{}{}{'} \\\\\n    Immediate because $\\REACH = \\emptyset$\n  \\item \\resultThinAir{}{'} \\\\\n    Immediate\n  \\end{enumerate}\n\n  \\newpage\n  \\textbf{Case $e$ of}\n  \\lstsemrule{supdateanf}\n\n  We need to invert rule \\TirName{Update}\n  \\begin{mathpar}\n    \\ruleSDUpdate\n  \\end{mathpar}\n\n  We need to show that $\\Store'$, $\\Perm'$, $r' = ()$, $\\SE' = \\SE$ fulfill\n  \\begin{enumerate}[({R}1)]\n  \\item \\resultOk{}{'}\n  \\item \\resultEnv{}{'} \\\\\n    Immediate by store typing for $\\Loc$\n  \\item $\\SE' \\vdash r' : \\tunit$ \\\\\n    Immediate\n  \\item \\resultPermDom{}{'} \\\\\n    Immediate, as we remove a permission from $\\Perm$\n  \\item \\resultReachPerm{}{'}\\\\\n    Immediate, as we only update a reachable $\\Loc$\n  \\item \\resultFrame{}{}{'}\n    Immediate\n  \\item \\resultImmutables{}{}{'} \\\\\n    Immediate\n  \\item \\resultMutables{}{}{'} \\\\\n    Immediate; for $\\Loc$, we observe that it is overwritten, but not  freed.\n  % \\item \\resultSuspended{}{}{'}\n  \\item \\resultResources{}{}{'} \\\\\n    Immediate because $\\Active\\VEnv = \\emptyset$ and hence $\\REACH = \\emptyset$.\n  \\item \\resultThinAir{}{'}\n  \\end{enumerate}\n\n  \\newpage\n  \\textbf{Case $e$ of}\n  \\lstsemrule{smatchanf}\n\n  We need to invert rule \\TirName{MatchPair}\n  \\begin{mathpar}\n    \\ruleSDAIMatchPair\n  \\end{mathpar}\n  The case VMatch corresponds to the match specification\n  $\\etransfm = \\operatorname{id}$.\n\n  Establish the assumptions for the recursive call\n  with $\\VEnv'_2 = \\VEnv_2 (x\\mapsto r_1) (x' \\mapsto r_1')$ and $\\SE' = \\SE$:\n  \\begin{enumerate}[({A1-}1)]\n  \\item $\\inferS{C}{\\E_2 (x:\\tau_1) (x':\\tau'_1)}{e_2}{\\tau_2}$ by inversion\n  \\item $\\SE \\vdash \\VEnv_2 : \\E_2$  by assumption; moreover, $\\SE\n    \\vdash r_1 : \\tau_1$ and $\\SE \\vdash r_1' : \\tau'_1$ by inversion\n    of the store typing for $\\Loc$. As $\\SE'=\\SE$, we have $\\SE' \\vdash \\VEnv_2' : \\E_2 (x:\\tau_1) (x':\\tau_1')$.\n  \\item $\\vdash \\Store' : \\SE'$ : the only change from assumption is in\n    $\\Loc$ which potentially maps to $\\StFreed$.\n  \\item \\assumeWellformed{'} : permission to $\\Loc$ is removed iff\n    $\\Loc$ is mapped to $\\StFreed$.\n  \\item \\assumeReachable{'}{'_2} \\\\\n    by assumption\n  \\item $\\Rawloc{\\Active{\\VEnv'_2}}$,\n    $\\Rawloc{\\MutableBorrows{\\VEnv'_2}}$,\n    $\\Rawloc{\\ImmutableBorrows{\\VEnv'_2}}$, and\n    $\\Rawloc{\\Suspended{\\VEnv'_2}}$ are all disjoint: by assumption\n    and splitting\n  % \\item  $\\VEnv'$ with $\\Rawloc{\\VEnv'}\n  %   \\subseteq \\Dom\\Store$ and $\\Dom\\VEnv \\cap \\Dom{\\VEnv'}=\\emptyset$\n  \\item \\assumeIncoming{'}{'_2}\n  \\end{enumerate}\n\n  Hence the call to @eval@ yields\n  $\\exists$ $\\Store_2$, $\\Perm_2$, $r_2$, $\\SE_2$ such that\n  \\begin{enumerate}[({R1-}1)]\n  \\item \\resultOk{}{_2}\n  \\item \\resultEnv{'}{_2}\n  \\item $\\SE_2 \\vdash r_2 : \\tau_2$\n  \\item \\resultPermDom{}{_2}\n  \\item \\resultReachPerm{}{_2}\n  \\item \\resultFrame{}{}{_2}\n  \\item \\resultImmutables{}{}{'}\n  \\item \\resultMutables{}{}{'}\n  % \\item \\resultSuspended{}{}{'}\n  \\item \\resultResources{}{}{'}\n  \\item \\resultThinAir{}{'}\n  \\end{enumerate}\n  As $R_2$ is also returned from the match, these results carry over.\n  \n  \\newpage\n  \\textbf{Case $e$ of}\n  \\lstsemrule{matchborrowanf}\n\n  We need to invert rule \\TirName{MatchPair}\n  \\begin{mathpar}\n    \\ruleSDAIMatchPair\n  \\end{mathpar}\n  The case VMatchborrow corresponds to the match specification\n  $\\etransfm = \\&^{\\BORROW}$.\n  In contrast to the non-borrowing match, the borrowed pair is never deallocated.\n\n  Establish the assumptions for the recursive call\n  with  $\\SE'' = \\SE$:\n  \\begin{enumerate}[({A1-}1)]\n  \\item $\\inferS{C}{\\E_2 (x:\\borrow{\\tau_1}) (x':\\borrow{\\tau'_1})}{e_2}{\\tau_2}$ by inversion\n  \\item $\\SE \\vdash \\VEnv_2 : \\E_2$  by assumption; moreover, $\\SE\n    \\vdash r_1'' : \\borrow{\\tau_1}$ and $\\SE \\vdash r_2'' : \\borrow{\\tau'_1}$ by inversion\n    of the store typing for $\\Addr$. As $\\SE''=\\SE$, we have $\\SE'' \\vdash \\VEnv_2'' : \\E_2 (x:\\borrow{\\tau_1}) (x':\\borrow{\\tau_1'})$.\n  \\item $\\vdash \\Store' : \\SE''$ : the only change from assumption is in\n    $\\Loc$ which potentially maps to $\\StFreed$.\n  \\item \\assumeWellformed{''} : permission to $\\Loc$ is removed iff\n    $\\Loc$ is mapped to $\\StFreed$.\n  \\item \\assumeReachable{''}{''_2} \\\\\n    by assumption\n  \\item $\\Rawloc{\\Active{\\VEnv''_2}}$,\n    $\\Rawloc{\\MutableBorrows{\\VEnv''_2}}$,\n    $\\Rawloc{\\ImmutableBorrows{\\VEnv''_2}}$, and\n    $\\Rawloc{\\Suspended{\\VEnv''_2}}$ are all disjoint: by assumption\n    and splitting\n  % \\item  $\\VEnv'$ with $\\Rawloc{\\VEnv'}\n  %   \\subseteq \\Dom\\Store$ and $\\Dom\\VEnv \\cap \\Dom{\\VEnv'}=\\emptyset$\n  \\item \\assumeIncoming{''}{'_2}\n  \\end{enumerate}\n\n  Hence the call to @eval@ yields\n  $\\Store_2$, $\\Perm_2$, $r_2$, $\\SE_2$ such that\n  \\begin{enumerate}[({R1-}1)]\n  \\item \\resultOk{}{_2}\n  \\item\\label{item:1} \\resultEnv{''}{_2}\n  \\item\\label{item:3} $\\SE_2 \\vdash r_2 : \\tau_2$\n  \\item\\label{item:4} \\resultPermDom{}{_2}\n  \\item\\label{item:5} \\resultReachPerm{_2''}{_2}\n  \\item\\label{item:6} \\resultFrame{''}{_2''}{_2}\n  \\item\\label{item:7} \\resultImmutables{''}{_2''}{_2}\n  \\item\\label{item:34} \\resultMutables{''}{_2''}{_2}\n  % \\item \\resultSuspended{}{}{'}\n  \\item\\label{item:35} \\resultResources{''}{_2''}{_2}\n  \\item\\label{item:36} \\resultThinAir{''}{_2}\n  \\end{enumerate}\n\n  It remains to relate to result with the original call to @eval@.\n  \\begin{enumerate}[(R1)]\n  \\item \\resultOk{}{_2}\n  \\item \\resultEnv{}{_2} because $\\SE'' = \\SE$ and \\ref{item:1}.\n  \\item $\\SE_2 \\vdash r_2 : \\tau_2$ by \\ref{item:3}\n  \\item \\resultPermDom{}{_2}\n    Immediate from~\\ref{item:4}.\n  \\item \\resultReachPerm{}{_2} By~\\ref{item:5} and because $\\Store =\\Store''$.\n  \\item \\resultFrame{}{}{_2} Immediate from~\\ref{item:6} because\n    $\\Store = \\Store''$\n  \\item \\resultImmutables{}{}{_2}\n  \\item \\resultMutables{}{}{_2}\n  % \\item \\resultSuspended{}{}{'}\n  \\item \\resultResources{}{}{_2}\n    Immediate by~\\ref{item:35} because the borrowing match does not deallocate.\n  \\item \\resultThinAir{}{_2}\n  \\end{enumerate}\n\n\\end{proof}\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: \"main\"\n%%% End:\n", "meta": {"hexsha": "035a49ed3e7b55e5629b0d24953e650d265aac13", "size": 39988, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "kindly/metatheory-extra.tex", "max_stars_repo_name": "peterthiemann/uniqueness", "max_stars_repo_head_hexsha": "5ec0c1b7cefc68de96d4e39f5e965b28945a6321", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-03-08T07:19:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-24T19:19:31.000Z", "max_issues_repo_path": "kindly/metatheory-extra.tex", "max_issues_repo_name": "peterthiemann/uniqueness", "max_issues_repo_head_hexsha": "5ec0c1b7cefc68de96d4e39f5e965b28945a6321", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kindly/metatheory-extra.tex", "max_forks_repo_name": "peterthiemann/uniqueness", "max_forks_repo_head_hexsha": "5ec0c1b7cefc68de96d4e39f5e965b28945a6321", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-05-08T11:59:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-13T17:05:05.000Z", "avg_line_length": 35.8315412186, "max_line_length": 135, "alphanum_fraction": 0.6417425228, "num_tokens": 13733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.3196717484584797}}
{"text": "\\section{GPUE: GPU Gross--Pitaevskii equation solver}\\label{sec:GPUE}\n\nGiven the effectiveness of GPU computing in the simulation of the linear Sch\\\"odinger equation system for SAP, we next applied the newly-developed techniques to simulating Bose--Einstein condensates, which formed the bulk of work during my thesis. The body of software developed for this project has been released as the tool ``GPUE'', available at \\url{https://github.com/mlxd/gpue}~\\cite{MLXD_GPUE}. Performance testing of this code was carried out by Peter Wittek, ICFO, Barcelona~\\cite{Wittek:2016}. A comparison was performed between GPUE, the Trotter--Suzuki (TS) package developed by Wittek \\textit{et} al. \\cite{NUM:Wittek_cpc_2013}, and the mature GPELab software suite for MATLAB \\cite{NUM:GPElab_1,NUM:GPElab_2}. The sample results taken for time evolution are given in Fig.~\\ref{fig:gpuevsts}. GPUE and GPU-enabled TS clearly beat MATLAB, and CPU performance by a significant margin. Although TS is a more generalised suite for computing, as far as we are currently aware the GPU computation does not yet allow for Gross--Pitaevskii solutions with angular momentum. GPUE is currently the optimal choice for rotating condensate systems out of the examined software suites.\n\n\\begin{figure}[htb]\n    \\centering\n    \\includegraphics[width=0.5\\textwidth,]{ch3_numerics/GPUEvsTS.png}\n    \\caption{Performance benchmark of GPUE and other simulation packages for the evolution of a harmonically trapped atom in a superposition state between ground and first excited states. Lower numbers are better and give results in faster times. Data adapted from \\cite{Wittek:2016}. }\n    \\label{fig:gpuevsts}\n\\end{figure}\n\nFigures ~\\ref{fig:profile_ev} and \\ref{fig:profile_im} demonstrate some of the resulting calls to different segments of the code, with timings given in Tables \\ref{tbl:gpue_ev} and \\ref{tbl:gpue_im}. The important data of the figures is both the kernel percentage utilisation, and that the operations are mostly saturating the available number of GPU cores. The data shows the average time spent in each individual kernel during both real and imaginary time evolution for 1010 steps at $2^{10}\\times 2^{10}$ resolution with (real) and without (imaginary) angular momentum operators. As can be seen, the inclusion of angular momentum operators lead to a performance hit, compared with an imaginary time evolution for a static condensate. While further optimisations can almost always be provided for such simulations, the performance of the software as a whole is defined by its slowest component. In this case the routines are equally met in performance by the Fourier transforms, which are already fully optimised as an external library. As such, improving performance much beyond this with the other kernels will be wasteful in time and resources.\n\n%\\iffalse\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=0.98\\textwidth,]{ch3_numerics/CUDA/Profiler_ev_1k_1024.png}\n    \\caption{Nvidia Nsight performance analysis of GPUE for real time evolution simulation for 1010 steps at $2^{10}\\times 2^{10}$ resolution. The respective kernel calls and total utilisation are listed on the left.}\n    \\label{fig:profile_ev}\n\\end{figure}\n\n\\begin{table}\n    \\scriptsize\n    \\centering\n\\begin{tabular}{c|c|c|c|c}\n\\textbf{Kernel}  & \\textbf{Info} & \\textbf{Avg. runtime} & \\textbf{\\# Runs} & \\textbf{Total time} \\\\\n\\hline\nMem. copy [H2D] & Memory copy from host to GPU & $2.312$ ms & 11 & $25.432$ ms\\\\\nMem. copy [D2H] & Memory copy from GPU to host & $2.18$ ms & 9 & $19.62$ ms\\\\\ncMult & Complex mult. in time ev. & $0.342$ ms & 3030 & $1.0363$ s\\\\\ncMultDensity & Complex mult. in time ev. for nonlinear op. & $0.456$ ms & 2020 & $0.921$ s \\\\\nscalarDiv & Renorm. of $\\Psi$ following FFT & $0.2216$ ms & 8080 & $1.791$ s\\\\\ndpRadix0032B & Internal CUFFT operation & $0.237$ ms & 8080 & $1.915$ s\\\\\ndpVector1024D & Internal CUFFT operation & $0.252$ ms & 8080 & $2.0362$ s\\\\\n\\end{tabular}\n\\caption{Kernel usage and timings for 1010 steps of real time evolution with angular momentum.}\\label{tbl:gpue_ev}\n\\end{table}\n\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=0.98\\textwidth,]{ch3_numerics/CUDA/Profiler_im_1k_1024.png}\n    \\caption{Nvidia Nsight performance analysis of GPUE for imaginary time simulation for 1010 steps at $2^{10}\\times 2^{10}$ resolution with angular momentum. The respective kernel calls and total utilisation are listed on the left.}\n    \\label{fig:profile_im}\n\\end{figure}\n\n\\begin{table}\n    \\scriptsize\n    \\centering\n\\begin{tabular}{c|c|c|c|c}\n\\textbf{Kernel}  & \\textbf{Info} & \\textbf{Avg. runtime} & \\textbf{\\# Runs} & \\textbf{Total time} \\\\\n\\hline\nMem. copy [H2D] & Memory copy from host to GPU & $2.311$ ms & 3 & $6.933$ ms\\\\\nMem. copy [D2H] & Memory copy from GPU to host & $1.85$ ms & 5 & $9.25$ ms\\\\\ncMult & Complex mult. in time ev. & $0.342$ ms & 1010 & $0.345$ s\\\\\ncMultDensity & Complex mult. in time ev. for nonlinear op. & $0.346$ ms & 2020 & $0.698$ s \\\\\nmultipass & Optimised parallel summation & $0.125$ ms & 3030 & $0.378$ s \\\\\nscalarDiv & Renorm. of $\\Psi$ following FFT & $0.221$ ms & 2020 & $0.446$ s \\\\\nscalarDiv_wfcNorm & Normalisation of wavefunction during ev. & $0.226$ ms & 1010 & $0.228$ s\\\\\ndpRadix0032B & Internal CUFFT operation & $0.237$ ms & 4040 & $0.957$ s \\\\\ndpVector1024D & Internal CUFFT operation & $0.251$ ms & 2020 & $0.507$ s \\\\\n\\end{tabular}\n\\caption{Kernel usage and timings for 1010 steps of imaginary time evolution for a non-rotating condensate.}\\label{tbl:gpue_im}\n\\end{table}\n\nA simplified sequence and state diagram combination is given in Figs.~\\ref{fig:gpue_seq1} and~\\ref{fig:gpue_seq2} which describes the operating process for GPUE. A document listing all aspects of component dependencies and intercommunication is available at~\\cite{MLXD_GPUE}. For brevity, we will refer the reader to this location for more information.\\footnote{The documentation is built using ~\\href{http://www.stack.nl/~dimitri/doxygen/}{Doxygen} with the command ``doxygen ./docs/gpue_doxy.conf'', and requires the \\textit{dot} package for figure generation. This may change during future releases.}.\n\n\\begin{figure}[]\n    \\centering\n        \\includegraphics[height=\\textwidth,angle=270]{ch3_numerics/GPUE_Seq1}\n    \\caption{Simplified combined sequence and state diagram for GPUE operation (1 of 2). The operation procedure of GPUE is outlined in sequence from top-to-bottom. While much of the setup and analysis takes place on the host (CPU), the device (GPU) is used to offload all the time-evolution calculations. After setup, the wavefunction and all required operators are sent to the GPU.}\n    \\label{fig:gpue_seq1}\n\\end{figure}\n\\begin{figure}[]\n    \\centering\n        \\includegraphics[height=\\textwidth,angle=270]{ch3_numerics/GPUE_Seq2}\n    \\caption{Simplified combined sequence and state diagram for GPUE operation (2 of 2). Following the completion of the time evolution after a predetermined number of steps, the wavefunction is unloaded from the GPU and returned to the CPU for output. Minimising this transfer allows for optimal performance from the device. Further details of dependencies and data flow are given by \\cite[docs/gpue.pdf]{MLXD_GPUE}.}\n    \\label{fig:gpue_seq2}\n\\end{figure}\n\n\\subsection{Angular momentum operators using Fourier split-operator  method}\\label{ss:ang_mom_fso}\nAs discussed earlier, in the presence of large values of angular momentum, the condensate wavefunction will accommodate many vortices. To ensure a well ordered lattice, more consideration is required than to just directly numerically solve the GPE at the required rotation rate. Assuming an initial Gaussian guess, and using the imaginary time evolution algorithm to find the ground state, a large number of vortices will enter the condensate from the edge and compete for lattice sites to form the expected Abrikosov pattern. Due to the highly dense spectrum of the condensate close to the ground state in this regime, only minimal energy shifts will be given for deviations from the perfect Abriksov geometry. As a result, it can take a significantly long time to reach an ordered state for rotation frequencies close to the transverse trapping frequency \\cite{Vtx:Mueller_prl_2002}. To overcome this issue, one can choose to follow the ground state of the condensate with a ramp of the rotation rate. This essentially mimics adiabatic evolution, and allows for the determination of the vortex lattice ground state for all rotation frequencies.\n\nThe Fourier split-operator algorithm described earlier works well in handling cases where the individual operators live in position or momentum space respectively. However, the angular momentum operators are a combination of both spaces. Taking the angular momentum operator along the $z$-axis, $L_z = xp_y - yp_x$, and applying it to the wavefunction requires each basis element to be in a different space in the different directions. For applying this operator we must therefore Fourier transform along a single dimension, multiply by the respective $\\mathbf{k}$-space component, take the inverse, multiply by the respective $\\mathbf{r}$-space component in the other direction, and then perform this operation along the other dimensions, summing the results.\n\nThis accrues an error which is not encountered using methods that are solely in position or momentum space. Following the process given in Sec.~\\ref{sec:fso} the error can be determined by checking the commutativity of the respective components of the angular momentum operator as\n\n \\begin{align}\n \t\\alpha_1 = [x p_y,-y p_x] &= [x p_y,-y] p_x  -  y[x p_y,p_x] = -[-y,x p_y] p_x + y [p_x, x p_y] \\nonumber \\\\\n \t\t&= -\\left( {\\cancelto{0}{[-y,x]}} p_y + x [-y,p_y] \\right) p_x + y \\left( [p_x,x] p_y + x {\\cancelto{0}{[p_x,p_y]}} \\right) \\nonumber \\\\\n \t\t&= -x {\\cancelto{-\\textrm{i}\\hbar}{[-y, p_y]}} p_x + y {\\cancelto{-\\textrm{i}\\hbar}{[p_x,x]}} p_y \\nonumber \\\\\n        &= \\textrm{i}\\hbar \\left(x p_x - y p_y \\right).\n \\end{align}\n\n The complex error term can be seen as, in the case of the above implemented evolution, allowing the angular momentum operator to change from imaginary time to real-time, and vice-versa in each respective case. To overcome this, we simply swap the application order of the operator components, between odd and even steps during the evolution. Starting with the alternate order we obtain a value of $\\alpha_2 = [-y p_x, x p_y] = \\textrm{i}\\hbar \\left(-x p_x + y p_y \\right)$. Since we are applying these operators to the condensate we can overcome the error of one term by the application of the other, as\n \\begin{equation}\n \\exp{\\textrm{i} \\alpha_1}\\exp{\\textrm{i} \\alpha_2} = 1.\n \\end{equation}\n\n Although alternating will provide a cancellation of this error, it can be assumed that for large timesteps the error will have a significant contribution to the overall dynamics, as the wavefunction evolves during each timestep. For greater accuracy of this method one can perform a decomposition following Eq.~\\eqref{eqn:3} for a third-order error, or using the above splitting for second-order.\n\nAn example of the density of the ground state and the associated wavefunction phase at a rotation frequency of $\\Omega = 0.995\\omega_x$ is given in Fig.~\\ref{fig:showingoff} at a resolution of $2^{11}\\times 2^{11}$ ($2048\\times 2048$). Although aliasing may be apparent in the phase, this is due to the limited resolution of the computer monitor (printer). The presence of a well ordered Abrikosov lattice is clearly visible.\n\n \\begin{figure}\n     \\centering\n     \\includegraphics[width=0.45\\textwidth,]{ch3_numerics/Rho_995}\n     \\includegraphics[width=0.45\\textwidth,]{ch3_numerics/phi_995}\n     \\caption{Condensate density (left) and phase (right) at a rotation rate of $\\Omega=0.995\\omega_x$ for a $2^{11}\\times 2^{11}$ grid showing approximately 600 vortices in the visible density regions. For both images the box size is $700~\\mu\\textrm{m} ~\\times ~700~\\mu\\textrm{m}$.}\n     \\label{fig:showingoff}\n \\end{figure}\n\n \\subsection{Vortex tracking}\\label{sec:vortrack}\n To efficiently follow the dynamics of individual vortices, a robust algorithm is needed to track their positions. One could track regions where the density drops to zero. However, this gives very little information on the topological excitation, and may miss many vortices, as the numerical wavefunction may never truly approach this value. A more effective way is to locate the $\\pm 2\\pi$ charge in the wavefunction phase, which is a signature of quantum vortices. For this we examine each $2\\times 2$ subgrid of the underlying lattice and check if the phase rotates from $-\\pi$ to $+\\pi$ (or vice versa). After an initial pass to identify vortex locations closest the nearest grid element, a least-squares fit is performed to more accurately determine the vortex core position \\cite{c42f}. Linear least squares is used generally for an overdetermined linear system $\\mathbf{A}\\mathbf{r} = \\mathbf{b}$, where unique solutions are unlikely to exist. Thus, for a solution, we seek the best fit plane that minimises the error, of the form\n\n \\begin{equation}\n S(\\mathbf{r}) = \\displaystyle\\sum |b_i - \\displaystyle\\sum A_{ij} r_j |^2\n \\end{equation}\n where $S$ is the objective function to be minimised, following $\\mathbf{b} = \\argmin S(\\mathbf{r})$. The solution of this minimisation problem is given by\n \\begin{subequations}\n\\begin{align}\n    \\mathbf{A} ^{T}\\mathbf{A} \\mathbf{r} &= \\mathbf{A} ^{T}\\mathbf{b}, \\\\\n    \\mathbf{r} &= (\\mathbf{A}^{T}\\mathbf{A})^{-1}\\mathbf{A}^{T}\\mathbf{b}.\n\\end{align}\n\\end{subequations}\nThe best-fit plane is sought of the form\n$a_0 c + \\displaystyle\\sum\\limits_{i}^{m} a_i r_i = f(\\mathbf{r})$\nwhich for a two-dimensional system, $\\mathbf{r} = (x,y)$, is given by the matrix,\n\\begin{equation}\n    \\mathbf{A} = \\left(\n    \\begin{array}{ccc}\n        0 & 0 & 1 \\\\\n        0 & 1 & 1 \\\\\n        1 & 0 & 1 \\\\\n        1 & 1 & 1\n    \\end{array}\\right).\n\\end{equation}\nThe above matrix is composed of all possible planes that can fit over a square $2\\times 2$ grid plaquette,\nand\n\\begin{equation}\n    \\mathbf{b} = \\left(\n    \\begin{array}{cccc}\n        \\Psi(x_0,y_0) & \\Psi(x_0,y_1) & \\Psi(x_1,y_0) & \\Psi(x_1,y_1)\n    \\end{array} \\right)^{T},\n\\end{equation}\nare the wavefunction values around the sampled $2\\times 2$ grid.\nUpon evaluating the vector $\\mathbf{r}$ above, one can obtain the best fit plane  solution as\n\\begin{equation}\\left(\n    \\begin{array}{c}\n        x \\\\\n        y \\\\\n        c\n    \\end{array}\\right)\n    = \\left(\n    \\begin{array}{c}\n        {\\left( -\\Psi(x_0,y_0) + \\Psi(x_0,y_1) - \\Psi(x_1,y_0) + \\Psi(x_1,y_1) \\right)}{/2} \\\\\n        {\\left( -\\Psi(x_0,y_0) - \\Psi(x_0,y_1) + \\Psi(x_1,y_0) + \\Psi(x_1,y_1) \\right)}{/2} \\\\\n        3\\Psi(x_0,y_0) + \\Psi(x_0,y_1) - \\Psi(x_1,y_0) - \\Psi(x_1,y_1)\n    \\end{array}\\right).\n\\end{equation}\n\nThe goal is to find where both the real and imaginary components cross through zero, and thus we seek a solution of the form $x + y = -c$. Rearranging the above equations as\n\\begin{equation}\\left(\n    \\begin{array}{cc}\n        \\Re(x) & \\Re(y) \\\\\n        \\Im(x) & \\Im(y) \\\\\n    \\end{array}\\right)\n    \\left(\n    \\begin{array}{c}\n        \\delta x \\\\\n        \\delta y\n    \\end{array}\\right)\n    = -\n    \\left(\n    \\begin{array}{c}\n        \\Re(c) \\\\\n        \\Im(c)\n    \\end{array}\\right),\n\\end{equation}\nand again solving the linear system by inverting the left-hand matrix and multiplying across allows one to seek the corrections to the vortex position, $\\delta \\mathbf{r} = (\\delta x, \\delta y )$.\n\n With this, we can accurately determine the position of the vortices with high precision. To track their motion during the evolution, we create an initial list of positions and give each vortex a unique identifier (UID). Assuming the vortex cores can travel a limited distance (some multiple of the grid resolution) between time steps, we can say at subsequent times which vortex has moved to the newly found positions.\n\n This process is performed by representing the vortices as a graph, each with an assigned unique identifier, associated location, phase winding and on/off flag. Edges are created between vortices that are separated by at most root-two the average of the inter-vortex spacings. A finite boundary is chosen to examine only vortices in areas of significant condensate density, since vortices can easily appear and disappear close to the condensate boundary. Any vortex which appears without association to an initial vortex, or any tracked vortex that crosses the boundary, is switched off and remains so for all analysis. A graph for an initial ($t=0$) vortex lattice shown in Fig.~\\ref{fig:graphit}, with the identifiers indicated on each node, and the neighbouring distances indicated by the edge weights. %The almost perfect triangular structure is clearly confirmed. %%This is a graph, not a location plot. Positions are chosen at mathematicas discretion\n\n \\begin{figure}\n     \\centering\n     \\includegraphics[width=0.98\\textwidth,]{ch3_numerics/Graph_full}\n     \\caption{Graph of vortex lattice positions indicating the vortex identifier and the intervortex distances in units of grid-spacing $\\Delta= \\Delta x = \\Delta y$. A hard-walled boundary is chosen such that the vortex distances remain almost uniform, and are shown here with a mean value of $\\bar{r} = 30.2451$ and variance of $\\sigma^2 = 0.16118$.}\n     \\label{fig:graphit}\n \\end{figure}\n", "meta": {"hexsha": "05c4bb4fb44552fecfc7638aa4122e224412c2c6", "size": 17412, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "MainText/ch3_numerics/num_gpue.tex", "max_stars_repo_name": "mlxd/PhDThesis", "max_stars_repo_head_hexsha": "1b5c6bfd1bfd073b47aa0b1b5abbc7bff5cd521e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MainText/ch3_numerics/num_gpue.tex", "max_issues_repo_name": "mlxd/PhDThesis", "max_issues_repo_head_hexsha": "1b5c6bfd1bfd073b47aa0b1b5abbc7bff5cd521e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MainText/ch3_numerics/num_gpue.tex", "max_forks_repo_name": "mlxd/PhDThesis", "max_forks_repo_head_hexsha": "1b5c6bfd1bfd073b47aa0b1b5abbc7bff5cd521e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 91.6421052632, "max_line_length": 1183, "alphanum_fraction": 0.7417298415, "num_tokens": 4834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.3196548645398315}}
{"text": "% !TEX root = ../00_thesis.tex\n\n\\section{Concrete Realization of \\DRP}\n\\label{sec:concrete_realization}\n\n\\squarepar{%}\n  This section discusses how to concretely implement \\DRP's concepts. In particular, one needs to define\n  (i)~the fixed flushing interval $T_f^s$ of the \\CPs~(\\cref{subsec:CP_schedule}), and\n  (ii)~how to dynamically compute the network deadline \\ndeadlinei of a flow \\flowi and the flushing interval $T_f^d$ of each \\ap (\\cref{subsec:D_Tfd_computation}).%\n}\n\nThen, a worst-case buffer analysis (\\cref{subsec:WC_buffer}) will allow to formulate admission tests (\\cref{subsec:admission}), one for {\\ap}s and one for {\\cp}s.\nThe success of all admission tests guarantees that both contracts \\textbf{Source}~$\\boldsymbol{\\leftrightarrow}$~\\textbf{Blink} and \\textbf{Blink}~$\\boldsymbol{\\leftrightarrow}$~\\textbf{Destination} can be satisfied by \\DRP.\n\n\\subsection{Setting \\CPs' Flushing Interval}\\label{subsec:CP_schedule}\n\n\\squarepar{%}\n  To guarantee that all \\CPs fulfill their share of the contracts (\\ie prevent buffer overflows), we conceive a time-triggered approach to schedule all tasks of \\CPs. It consists of (\\emph{i}) setting the flushing interval $T_f^s$ of all \\CPs to the same constant value, and (\\emph{ii}) letting the round interval $T_{net}$ be a multiple of $T_f^s$.\n  As discussed in \\cref{sec:designDetailed}, $T_f^s$ should not to constrain the achievable deadline: thus, we aim to set it as short as possible.\n  \\CPs have three tasks to perform%\n}\n\n\\begin{itemize}\n \\item flushing \\bolt before each communication round,\n \\item participating in the communication during the rounds,\n \\item writing all received messages into \\bolt after the rounds.\n\\end{itemize}\n\nPerforming those tasks altogether takes $C_{CP} + C_{net}$ time units, where $C_{CP} = C_f + \\nslotsmax * C_w$, and \\nslotsmax denotes the number of time slots in one round.\nHence, $C_{CP} + C_{net}$ is the smallest admissible round interval (otherwise \\CPs' task set is not schedulable). Thus we set for all \\CPs in the system,\n\\begin{align}\n\\label{eq:design_flush_period_source}\n\t& T_f^s = C_{CP} + C_{net} \\\\\n\\intertext{and we let the round interval be a multiple of $T_f^s$. That is, for $k \\in \\mathbb{N}$, $k > 0$,}\n\\label{eq:design_round_period}\n\t& T_{net} = k * T_f^s\n\\end{align}\nFor a given $C_{net}$, a larger $k$ entails less available bandwidth but also lower energy consumption.\n\\blink is designed to dynamically adjust $k$ to match the bandwidth requirements and save energy~\\cite{zimmerling2017Blink}.\n\n\\subsection{\\mbox{Computing Network Deadlines \\& \\APs ' Flushing Interval}}\n\\label{subsec:D_Tfd_computation}\n\nHaving fixed \\CPs' flushing interval, we now turn to the problem of dynamically computing the network deadline \\ndeadlinei of flow \\flowi and the flushing interval $T_f^d$ of \\flowi's destination \\apdst, such that the end-to-end deadline \\deadlinei is met.\nTo this end, we need to define expressions for the functions $f$ and $g$ (introduced in \\cref{sec:designDetailed}), and derive values for \\ndeadlinei and $T_f^d$ such that equations \\eqref{eq:function_f} and \\eqref{eq:function_g} are satisfied.\n\n\\begin{theorem}\n  \\label{thm:delta}\n  For any flow \\flowi = (\\flowsrci,\\flowdsti,\\periodi,\\jitteri,\\deadlinei), and given the duration of communication rounds $C_{net}$, functions $f$ and $g$ are upper-bounded as follows\n  \\begin{align}\n  f(T_f^s ,  \\ndeadlinei)\n  \t& \\; \\leq \\;\n  \tT_i + D_i + \\overline{\\jitteri}  + \\delta_f^{const} \\label{eq:expression_f}\\\\\n  g(T_f^d)\n  \t& \\; \\leq  \\;\n  \tT_f^d(\\flowdsti) + \\delta_g^{const} \\label{eq:expression_g}\n  \\end{align}\n  where $ \\delta_f^{const}$ and $\\delta_f^{const}$ are constant delays that depend on the WCETs of the \\bolt API functions, on the maximum number of messages \\nslotsmax that can be %inside a \\bolt queue at the end of a round\n  served by \\blink in one round, and on the fixed flushing interval $T_f^s$ of \\CPs,\n  \\begin{align}\n  \\delta_f^{const} &\\;= \\;\\; C_w + C_f + T_f^s \\\\\n  \\delta_g^{const} &\\;= \\;\\;\\nslotsmax*C_w - (\\nslotsmax-1)* C_r + C_f\\\\\n  \\label{eq:jitter_bar}\n  \\overline{\\jitteri}  &\\;= \\;\\; \\floor*{(\\jitteri + C_f - C_r)/{T_f^s}}\\cdot T_f^s\n  \\end{align}\n\\end{theorem}\n\n\\begin{proof}%\nFunction $f$ is the time between when a message is written into \\bolt by the source \\apsrc and when the communication round in which the message is sent by \\blink ends (\\ie when the message is available at the destination \\cpdst).\nThis is the sum of two delays: $\\delta_{source}$, the time until the message is available for communication at the source \\cpsrc; and $\\delta_{network}$, the time until the message is shipped over the network to \\cpdst.\n\nSimilarly, function $g$ is the time between when a packet is available at the destination \\cpdst and the end of the \\opflush operation that reads the message out of \\bolt at the destination \\apdst (\\ie when the message can be processed by the destination application).\nWe refer to this delay as $\\delta_{dest}$.\n\nHence, the expressions for functions $f$ and $g$ in \\eqref{eq:expression_f} and \\eqref{eq:expression_g} directly follow from the delays expression derived in Lemmas~\\ref{lem:delta_source}, \\ref{lem:delta_network}, and \\ref{lem:delta_destination}~(\\cref{append:drp_WCanalysis}).\n\\\n\\end{proof}\n\nWe use Theorem~\\ref{thm:delta} to express conditions on \\ndeadlinei and $T_f^d$ such that \\eqref{eq:function_f} and \\eqref{eq:function_g} are satisfied.\nIn particular, it is sufficient that for any flow $\\flowi = (\\flowsrci,\\flowdsti,\\periodi,\\jitteri,\\deadlinei) \\in \\flowset$\n\\begin{align}\n\\nonumber\n T_i + D_i + \\overline{\\jitteri} \\;\n\t& \\leq  \\;\\; r * \\deadlinei - \\delta_f^{const} \\\\\n\\label{eq:ndeadline_constraint_latency}\n\\Rightarrow \\qquad T_i \\;\n\t& \\leq  \\;\\; r * \\deadlinei - \\delta_f^{const} - D_i - \\overline{\\jitteri} \\\\\n\\intertext{and}\n\\label{eq:APflush_constraint_base}\nT_f^d(\\flowdsti) \\;\n\t& \\leq \\, (1-r)*\\deadlinei -  \\delta_g^{const}\n\\end{align}\n\nAs low-power wireless networks typically feature limited bandwidth,%\n\\footnote{Low-power radio bit rates are often limited to 256\\kbps; the latest version of Bluetooth (Bluetooth~5) supports up to 2\\Mbps.}\n%\nit makes sense to choose the network deadline \\ndeadlinei as large as possible in order to increase the schedulability of flows in the network.\nHowever, \\blink only supports constrained deadlines ($\\ndeadlineany \\leq \\periodany$) and deadlines must be multiples of the round length ($\\ndeadlineany = 0 \\mod \\rperiod $).\nFurthermore, a network deadline cannot be smaller than \\rperiodmin (see \\cref{subsec:details_blink}).\n%\nHence, for any flow \\flowi, it must hold that\n\\begin{align}\n  \\label{eq:ndeadline_constraint_period}\n  \\rperiodmin \\; &\\leq \\; \\ndeadlinei \\; \\leq \\; \\periodi \\\\\n  \\ndeadlinei \\; &= \\; 0 \\mod \\rperiod\n\\end{align}\n\nFinally, to satisfy all contracts in the system, \\eqref{eq:ndeadline_constraint_latency}, \\eqref{eq:APflush_constraint_base} and \\eqref{eq:ndeadline_constraint_period} must hold for all flows $\\flowi \\in \\flowset$.\nHence, the values for \\ndeadlinei and $T_f^d$ computed dynamically at runtime must satisfy for any flow $\\flowi = (\\flowsrci,\\flowdsti,\\periodi,\\jitteri,\\deadlinei) \\in \\flowset$ and any $n \\in \\mathcal{N}$\n\\begin{align}\n\\label{eq:design_ndeadline}\n\\ndeadlinei \\;\n\t& = \\; \\min \\left(\\; \\periodi \\;\\, , \\,  r*\\deadlinei - \\delta_f^{const} - \\periodi - \\overline{\\jitteri} \\right) - (\\ndeadlinei \\mod \\rperiod) \\\\\n\\label{eq:design_delay_destination}\nT_f^d(n) \\;\n\t& \\leq \\; \\min_{F_j\\in \\mathcal{F}, n = \\flowdstj}\n\t\\left( (1-r)*\\deadlinej - \\delta_g^{const} \\right)\n\\end{align}\nIf using \\eqref{eq:design_ndeadline} leads to a violation of the constraint in \\eqref{eq:ndeadline_constraint_period} or if $T_f^d$ results in a load that \\ap at node $n$ cannot handle, \\DRP rejects the flow since the two contracts cannot be guaranteed.\n\n\n\\subsection{Worst-case Buffer Analysis}\n\\label{subsec:WC_buffer}\n\nSatisfying all contracts entails preventing overflows of message buffers in the system.\nSpecifically, as shown in \\cref{fig:design_overview},\n\\begin{itemize}\n\t\\item \\APs are responsible for ensuring that the incoming \\bolt queues do not overflow, and\n\t\\item \\CPs are responsible for ensuring that their local message buffers and the outgoing \\bolt queues do not overflow.\n\\end{itemize}\n\n\\squarepar{%}\n  To formulate the admission tests for {\\ap}s and {\\cp}s, we first need the worst-case buffer sizes (\\ie maximum number of messages in a buffer) induced by a given flow set \\flowset.\n  For ease of exposition, we make the following hypothesis.%\n}\n\\begin{hypothesis}\\label{hyp:f_max}\nFor a given flow set \\flowset, an \\ap (resp. \\cp) never writes more messages into \\bolt than can be flushed by \\cp (resp. \\ap) in one \\emph{\\opflush} operation in the time span between two \\emph{\\opflush}.\n\\end{hypothesis}\nThis hypothesis implies that the \\bolt queues are always empty at the end of a \\opflush operation.\nWe prove at the end of this section that our admission tests effectively guarantee that Hypothesis~\\ref{hyp:f_max} is always verified.\n\n\\begin{lemma} \\label{lem:buffer_bolt_out}\nGiven a flow set \\flowset, the buffer size of the outgoing \\bolt queue of node $n \\in \\nodeset$, $B_{\\bolt,out}(n)$, is upper-bounded,\n\\begin{equation}\n\\label{eq:bolt_out_buffer_stress}\n\tB_{\\bolt, out}(n) \\; \\leq \\;\n\t\\sum_{\\substack{F_i\\in \\mathcal{F},\\, n = \\flowsrci}} \\ceil*{\\frac{T_f^s + C_w + C_r + \\jitteri}{T_i}}\n\\end{equation}\n\\end{lemma}\n\n\\begin{proof}%\nAccording to the \\textbf{Source} $\\boldsymbol{\\leftrightarrow}$ \\textbf{Blink} contract, \\apsrc at node $n$ does not write more than one message every \\periodi with jitter \\jitteri into the outgoing \\bolt queue.\nBased on Hypothesis~\\ref{hyp:f_max}, the buffer size is bounded by the number of messages that can be written by \\apsrc during the maximum time a message can stay inside the queue, which is $\\Delta = T_f^s + C_w + C_r$ (see \\cref{fig:delta_source_time_graph}).\nThe maximum number of messages that can be written by \\apsrc within any time interval $\\Delta$ is $\\ceil*{(\\Delta + J_i)/{T_i}}$ for each flow \\flowi sourced by~$n$. \\\n\\end{proof}\n\n\nThe worst-case buffer size of a \\cp depends on (i) the maximum time a message can stay in \\cp's local memory awaiting to be served by \\blink, and (ii) the number of messages that can be sent within one round to a node.\n\n\\begin{lemma} \\label{lem:buffer_CP}\nGiven a flow set \\flowset, the buffer size of {\\cp}'s internal memory of node $n \\in \\nodeset$, $B_{CP}(n)$, is upper-bounded,\n\\begin{equation}\n\\label{eq:CP_memory_stress}\n\tB_{CP}(n) \\leq\n\t\\sum_{\\substack{F_i\\in \\mathcal{F},\\\\ n = \\flowsrci}}\n\t1 + \\ceil*{\\frac{\\ndeadlinei + \\overline{\\jitteri} + C_f}{T_i}} +\n\t\\sum_{\\substack{F_i\\in \\mathcal{F},\\\\ n = \\flowdsti}} 1\n\\end{equation}\n\\end{lemma}\n\n\\begin{proof}%\nOn the source side, we make the conservative assumption that all messages read out during a \\emph{\\opflush} occupy memory in \\cpsrc from the beginning of the \\emph{\\opflush}. Hence, the maximum waiting time in \\cpsrc for a message until it is served by \\blink is $\\delta_{network} + C_f$ (see Lemma~\\ref{lem:delta_network} -- \\cref{append:drp_WCanalysis}). The number of messages in \\cpsrc due to the source is upper-bounded by the maximum number of messages \\apsrc can write during this time interval, given by\n$\\ceil*{\\delta_{network} + C_f)/T_i}$.\nUsing Lemma~\\ref{lem:delta_network}, this is at most\n$1 + \\ceil*{( \\ndeadlinei + \\overline{\\jitteri} + C_f)/\\periodi }$  per outgoing flow.\n\n\n\nOne the destination side, during a round, \\cpdst may receive several messages, which it immediately writes into \\bolt after the round.\nHowever, \\blink expects one packet every \\periodi from each flow, which it serves within \\ndeadlinei. As $\\ndeadlinei \\leq \\periodi$, \\blink never schedules more than one packet per round for each flow.\nThus, the maximum number of messages in \\cpdst due to the destination is 1 packet per incoming flow.\n\\\n\\end{proof}\n\n\\begin{lemma} \\label{lem:buffer_bolt_in}\nGiven a flow set \\flowset, the buffer size of the incoming \\bolt queue of node $n \\in \\nodeset$, $B_{\\bolt,in}(n)$, is upper-bounded,\n\\begin{equation}\n\\label{eq:bolt_in_buffer_stress}\n\tB_{\\bolt, in}(n)\\;  \\leq \\;\n\t\\sum_{\\substack{F_i\\in \\mathcal{F},\\\\ n = \\flowdsti}} \\ceil*{\\frac{T_f^d(n) + C_w + C_r + D_i}{T_i}}\n\\end{equation}\n\\end{lemma}\n\n\\begin{proof}%\nAs specified in the \\textbf{Source} $\\boldsymbol{\\leftrightarrow}$ \\textbf{Blink} contract, \\blink delivers packets from any flow \\flowi before the network deadline \\ndeadlinei~(\\cref{sec:designDetailed}). Therefore, \\blink delivers at most one packet every \\periodi time units, with a jitter equal to \\ndeadlinei, which are written into \\bolt immediately after the round.\n\nBased on Hypothesis~\\ref{hyp:f_max},\nthe buffer constraint of the incoming \\bolt queue is bounded by the number of packets that can be written by \\cpdst during the maximum elapsed time before a packet is read out by \\apdst. As in the proof of Lemma~\\ref{lem:buffer_bolt_out}, there are at most $\\ceil*{(T_f^d(n) + C_w + C_r + D_i)/{T_i}}$ such messages from each flow \\flowi that has node $n$ as destination.\n\\end{proof}\n\n\n\\subsection{Admission Tests}\n\\label{subsec:admission}\n\nWe now combine the above results and formulate the admission tests for \\CPs and \\APs, which form the cornerstone of \\DRP's registration mechanism described in \\cref{sec:designDetailed}.\nWe further show that the computation complexity of the admission tests is not only small but \\emph{constant}, and hence supports the requirements of \\feature{Adaptability} and \\feature{Efficiency}.\n\n\\squarepar{%}\n  Let $F_j$ be the flow for which a request has been issued, and $\\mathcal{F}_{new} = \\mathcal{F} \\cup \\{F_j\\}$.\n  The \\cp of node $n$ is responsible for preventing overflows of its local memory (of size $S_{CP}$) and of the outgoing \\bolt queue of node $n$ (of size $S_{\\bolt}$).%\n}\n\n\\begin{theorem}[{Admission Test of \\cp}]\\label{thm:CP}\nIf\n\\begin{align*}\nS_{\\bolt} \\;\n\t & \\geq \\sum_{\\substack{\\flowi \\in \\mathcal{F}_{new}, \\\\ n = \\flowsrci}}\n\t \t\\ceil*{\\frac{T_f^s + C_w + C_r + \\jitteri}{T_i}} \\\\\n\\textup{and}\\qquad\nS_{CP} \\;\n \t& \\geq\n\t\\sum_{\\substack{\\flowi \\in \\mathcal{F}_{new}, \\\\ n = \\flowsrci}}\n\t\t1 + \\ceil*{\\frac{\\ndeadlinei + \\overline{\\jitteri} + C_f}{T_i}}\n\t+ \\sum_{\\substack{\\flowi \\in \\mathcal{F}_{new}, \\\\ n = \\flowdsti}}\n\t\t1\n\\end{align*}\nthen the requested flow \\flowj can be safely admitted by $\\cp$.\n\\end{theorem}\n\n\\begin{proof}Immediate from Lemmas~\\ref{lem:buffer_bolt_out} and \\ref{lem:buffer_CP}. \\\n\\end{proof}\n\n\nThe \\ap of node $n$ is responsible for preventing overflows of the incoming \\bolt queue (of size $S_{\\bolt}$) and for guaranteeing its share of the end-to-end deadline.\n\n\\begin{theorem}[{Admission Test of \\ap}]\n\\label{thm:AP}\n  If there exists $T_f^d(n)$ such that\n  \\begin{align*}\n    T_f^d(n) \\;\n    & \\leq \\, \\min_{\\substack{F_i\\in \\mathcal{F}_{new}, \\\\  n = \\flowdsti}}\n    \\left( (1-r)*\\deadlinei - \\delta_g^{const} \\right)\\\\\n\\textup{and}\\qquad\n    S_{\\bolt} \\;\n    & \\geq \\sum_{\\substack{\\flowi \\in \\mathcal{F}_{new}, \\\\ n = \\flowdsti}} \\ceil*{\\frac{T_f^d(n) + C_w + C_r + D_i}{T_i}}\n  \\end{align*}\n  then the requested flow \\flowj can be safely admitted by $\\ap$.\n\\end{theorem}\n\\begin{proof}\nImmediate from Lemma~\\ref{lem:buffer_bolt_in} and equation \\eqref{eq:design_delay_destination}.\n\\end{proof}\n\nFinally, we verify that Hypothesis~\\ref{hyp:f_max} holds, showing the validity of our buffer analysis. From \\eqref{eq:f_max=M} we have $f_{max} = S_{\\bolt}$. Thus, by performing the admission tests at runtime, it follows from Theorems~\\ref{thm:CP} and \\ref{thm:AP} and Lemmas~\\ref{lem:buffer_bolt_out} and \\ref{lem:buffer_bolt_in} that $f_{max}$ is always bigger than the filling level of any \\bolt queue, which entails Hypothesis~\\ref{hyp:f_max} is true.\n", "meta": {"hexsha": "a67c6762bdcfa374e725e68574eb16ec74d5769d", "size": 15749, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "40_DRP/6_admission.tex", "max_stars_repo_name": "romain-jacob/doctoral-theis", "max_stars_repo_head_hexsha": "fd21e9f0cddeda91821eb061c9ab12df9f610da9", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "40_DRP/6_admission.tex", "max_issues_repo_name": "romain-jacob/doctoral-theis", "max_issues_repo_head_hexsha": "fd21e9f0cddeda91821eb061c9ab12df9f610da9", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "40_DRP/6_admission.tex", "max_forks_repo_name": "romain-jacob/doctoral-theis", "max_forks_repo_head_hexsha": "fd21e9f0cddeda91821eb061c9ab12df9f610da9", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 62.0039370079, "max_line_length": 511, "alphanum_fraction": 0.7285541939, "num_tokens": 4849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251201477015, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.31959610689543644}}
{"text": "\\title{\\bf Spectra}\n\n\\section{Basics \\& Nomenclature}\n\nSpectra of objects can be determined in a number of ways, through\nrefraction, diffraction, or through energy-sensitive devices (most\ncommonly in the X-rays). Here we concentrate on the issues most\nrelevant to diffraction grating spectra, though many of these issues\nare also relevant in other contexts.\n\nTypically, spectra are obtained by putting a dispersive element in the\ncollimated beam. Although prisms can and have been used at the\nobjective pupil, more typically the dispersing element is at a pupil\nbeyond the focus. In addition to providing a smaller area for the\ndispersing element to cover, this allows the focal plane to be used to\nremove light not associated with the object or object of\ninterest. Slit spectrographs put a slit (or many slits) in this focal\nplane, recollimate the diverging beam, disperse it, and then refocus\nit on a new focal plane. Fiber spectrographs use optical fibers in the\nfocal plane and then align the fiber outputs in a convenient manner\nwith respect to the detectors.\n\nDiffraction gratings consist of optical elements ruled in some manner\nwith a set of closely spaced apertures. At any given wavelength, light\ncoming through the grating will be diffracted. The majority of energy\npasses straight through in the 0th order mode, but diffraction causes\nadditional modes at angles perpendicular to the ruling. The location\nof the 1st and greater order modes depends on wavelength, meaning the\nhigher-order modes yield spectra, with larger dispersion but a smaller\nfraction of the incoming energy at higher order modes. Traditional\ndiffraction gratings were usually ruled metal or mirrors, often mated\nto a prism (a configuration known as a {\\it grism}) to reorient the\ndesired mode along a convenient path. Modern gratings are usually\nvolume-phase holographic gratings, created within a substrate through\nholographic techniques. With greater control over the grating\ngeometry, these gratings typically result in optics with higher\nthroughput by avoiding occlusion along the geometric optics light\npath.\n\nSpectra can be described as having a characteristic resolution. The\nraw spectrum is usually detected on in a two-dimensional image, and\nthe spectrum appears along a somewhat curved line, known as the {\\it\ntrace}, traversing the image along the dispersion direction. The\nresolution parallel to the dispersion direction is known as the {\\it\nline spread function}, whereas the resolution perpendicular to the\ndispersion direction is known as the {\\it point spread function}, in\nanalogy to an image.\n\nFor slit spectra, the point spread function is determined largely by\nthe seeing and telescope PSF; the actual profile of the spectrum\nperpendicular to the trace is the image of the object convolved with\nthe PSF. For fiber spectra, the light is usually sufficiently\nscrambled that the width of the PSF is determined by the size of the\nfiber, as reimaged by the camera.\n\nThe line spread function is charactered by the resolution $R= \\lambda\n/ \\Delta \\lambda$, where $\\Delta\\lambda$ is usually the FWHM of the\nLSF (but not always). It is determined by the size of the fiber and\nthe dispersion power of the grating. For exposures more than a few\nminutes, any flexure of the spectrograph over the course of the\nexposure may also cause blurring in the LSF (or PSF).\n\nThe raw spectra need to be extracted and calibrated. The {\\it\nextraction} involves inferring a signal as a function of position on\nthe trace, to create a one-dimensional spectrum. The position in\npixels needs to be converted to wavelength; the relationship between\nthe two is usually inferred by injecting a signal into the\nspectrograph, often sourced by an {\\it arc lamp} which emits light at\ndiscrete lines associated with ionized inert gases (He, Ne, Ar,\netc).\n\nThe signal needs to be converted to flux units. If we assume the\ndetector is bias-subtracted as if it were an image, the signal in the\ntrace can be modeled as:\n\\begin{equation}\n{\\rm DN}(x) = \\left[f(\\lambda(x)) + f_{\\rm\nsky}(\\lambda(x))\\right] \\times F(x) \\times T(\\lambda)\n\\end{equation}\nThe quantity $F(x)$, the {\\it flat}, characterizes the effects of the\ndetector response and is typically determined by injecting light from\na flat-field lamp, which has a broad spectrum; in fact, only\nsmall-scale features are usually retained from the flat-field for\nreasons that will soon be clear.\n\nThe quantity $T(\\lambda)$ characterizes the throughput as a function\nof wavelength, and is affected by the atmospheric transmission, how\nmuch of the light enters the spectroscopic aperture at any given\nwavelength, and the throughput of the optics, as well as any remaining\ndependence of efficiency on wavelength on scales larger than those\nprobed by the flat. It must be determined in part by observing\nstandard stars whose true spectra are assumed, either through\nadditional slits or fibers at the same time as the objects of\ninterest, or through the same slits or fibers at slightly different\ntimes. Either approach requires accounting for the resulting slight\ndifferences in the observations. \n\nThe sky signal $f_{\\rm sky}(\\lambda)$ also needs to be removed. In the\ncase of slit observations, the sky can be estimated from the outer\nparts of the slit, which contain little object flux. In the case of\nfiber observations, the sky needs to be estimated from other nearby\nfibers. Because the fiber varies with position and time on the sky,\nthis can be uncertain.\n\n\\section{Commentary}\n\nIn ground-based spectroscopy it is extremely important to pay\nattention to the chromatic atmospheric refraction. This effect can\nlead to different amounts of light getting through fiber or slit as a\nfunction of wavelength, because the image in the telescope focal plane\nis a function of wavelength. These differences lead to both a\nvariation in throughput and potential loss of signal-to-noise, and\nalso may make the spectrum hard to calibrate (if the standards used\nare not under the same conditions). Slit spectra are often arranged so\nthat the slit is parallel to the parallactic direction to minimize\nthis effect, but there is no such mitigation for fibers. Atmospheric\ndispersion correctors consisting of crossed prisms can be used to\nreduce this effect, but they need to act in a pupil so are large and\nexpensive.\n\nIn practice, the difficulty in sky subtraction is almost entirely due\nto the LSF modeling. Typically the issue arises because there are\nstrong lines that need to be subtracted, and so the LSF model needs to\nbe very good to be accurate enough. In addition, the sky can have a\ndifferent LSF than the object, since there are slit-filling\nissues or due to imperfections in the extraction method.\n\n\\section{Key References}\n\n\\begin{itemize}\n  \\item\n    {\\it Design and Construction of Large Telescopes},\n      \\citet{bely03a}\n  \\item\n    {\\it Astrophysical Techniques}, \\citet{kitchin09a}\n\\end{itemize}\n\n\n\\section{Order-of-magnitude Exercises}\n\n\\begin{enumerate} \n\\item Assuming the centroid accuracy is related to $R$ and $S/N$ ratio\n    in a similar way for optical spectra of single emission lines as\n    for point sources in an image, for an unresolved line with\n    $S/N \\sim 10$ in its total flux, how high $R$ do you have to be to\n    determine a Doppler velocity to 10 km s$^{-1}$ precision?  How\n    would a redshift determination using a full optical spectrum\n    (i.e. using many lines) change the precision of the determination\n    qualitatively? How does dependence of the velocity precision on\n    $R$ differ qualitatively for absorption lines?\n\n\\begin{answer}[Author: Matthew Daunt]\n    Due to the Doppler shift, we can predict the radial velocity of an\n    object using the observed wavelength and observed wavelength,\n    via\n\\begin{equation}\n    v_r = \\frac{\\lambda_{obs} -\\lambda_0}{\\lambda_0} c\n\\end{equation}\n    Resolution is defined as\n    \\begin{equation}\n        R = \\frac{\\lambda}{\\Delta \\lambda}\n    \\end{equation}\n    where $\\Delta \\lambda$ is the full width half max (FWHM). We\n    can express the resolution in velocity units therefore as\n    \\begin{equation}\n    \\Delta v = \\frac{\\lambda}{R } \\frac{c}{\\lambda} = \\frac{c}{R}\n\\end{equation}\n    The precision in the radial velocity should be better when the FWHM is\n    smaller and the $S/N$ is higher. The scaling is the same as for\n    positions in an image, such that\n    \\begin{equation}\n    \\sigma \\sim {\\rm FWHM~}/ (S/N) = \\frac{c}{R} \\frac{1}{S/N}\n    \\end{equation}\n    For $S/N = 10$, this equation is therefore:\n    \\begin{equation}\n    \\sigma \\sim \\frac{30,000 {\\rm ~km} {\\rm ~s}^{-1}}{R}\n    \\end{equation}\n    which therefore requires $R\\sim 3,000$.  If you have more than one\n    emission line, you can use the $S/N$ in each of the, and the\n    combined precision will be better than just using one. The case of\n    absorption lines will differ because the noise in the continuum\n    will contribute, and a larger width of the line will degrade the\n    precision further than for an emission line.\n\\end{answer}\n\\end{enumerate} \n\n\n% \\section{Analytic Exercises}\n\n% \\begin{enumerate}\n% \\item Assuming that the \n% \\end{enumerate}\n\n\\section{Numerics and Data Exercises}\n\n\\begin{enumerate}\n\\item Find an SDSS spectrum of a galaxy and sky fiber from the same\n    plate of the BOSS survey. Plot the sky and the object spectrum.\n\\item Find an arc spectrum from the BOSS survey, and a corresponding sky\nspectrum taken during the same calibration-exposure sequence. You will\nneed to use\nthe \\href{https://data.sdss.org/datamodel/files/SPECTRO_REDUX/RUN2D/PLATE4/spPlan2d.html}{\\tt\nspPlan2d} files to figure out which\n\\href{https://data.sdss.org/datamodel/files/BOSS_SPECTRO_REDUX/RUN2D/PLATE4/spCFrame.html}{\\tt\nspCframe} files to use. Find at least one pair of sky and arc lines,\neach of which is bright and isolated from other lines. Estimate the\nFWHM of the LSF from each and compare them.\n\\end{enumerate}\n\n\\bibliographystyle{apj}\n\\bibliography{exex}  \n", "meta": {"hexsha": "72ec00687be1d1729210c425bb01248edc28dee2", "size": 9951, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/spectra-text.tex", "max_stars_repo_name": "blanton144/exex", "max_stars_repo_head_hexsha": "b4d9d52b4fe8af761783f49b2c197a109d94cfdf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tex/spectra-text.tex", "max_issues_repo_name": "blanton144/exex", "max_issues_repo_head_hexsha": "b4d9d52b4fe8af761783f49b2c197a109d94cfdf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/spectra-text.tex", "max_forks_repo_name": "blanton144/exex", "max_forks_repo_head_hexsha": "b4d9d52b4fe8af761783f49b2c197a109d94cfdf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.1611374408, "max_line_length": 94, "alphanum_fraction": 0.7754999498, "num_tokens": 2406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.319596100118134}}
{"text": "\\part{part}\npart text\npart text\n\\chapter{chapter long title}\n chapter text\n chapter text\n \\[\n\t f(x)=x^2\n \\]\n \\section[for the toc]{section}\n  section text\n  section text\n \\section[for the toc]{section}\n  section text\n  section text\n  \\subsection[for the toc]{subsection}\n  subsection text\n  subsection text\n  \\subsection[for the toc]{subsection}\n  subsection text\n  subsection text\n \\section[for the toc]{section}\n  section text\n  section text\n\\chapter{chapter}\n chapter text\n chapter text\n \\part{part}\n part text\n part text\n\\chapter[toc]{chapter title}\n chapter text\n chapter text\n \\section[for the toc]{section}\n  section text\n  section text\n  \\subsubsection[for the toc]{subsubsection}\n  subsubsection text\n  subsubsection text\n  \\paragraph{paragraph}\n  paragraph text\n  paragraph text\n  \\subparagraph{subparagraph}\n  subparagraph text\n  subparagraph text\n \\section[for the toc]{section}\n  section text\n  section text\n  \\subsubsection[for the toc]{subsubsection}\n  subsubsection text\n  subsubsection text\n  \\paragraph{paragraph}\n  paragraph text\n  paragraph text\n  \\subparagraph{subparagraph}\n  subparagraph text\n  subparagraph text\n\\chapter[somethingelse]{goes here}\n", "meta": {"hexsha": "92801d6c516c410ee76dc9ba5af1c5928ecbe653", "size": 1171, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "project/server/dependencies/latexindent.pl-master/test-cases/headings/testHeadings2.tex", "max_stars_repo_name": "digorithm/latex-linter", "max_stars_repo_head_hexsha": "d6b63002cdcecf291e2abc7a399e0d7af4bd9038", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "project/server/dependencies/latexindent.pl-master/test-cases/headings/testHeadings2.tex", "max_issues_repo_name": "digorithm/latex-linter", "max_issues_repo_head_hexsha": "d6b63002cdcecf291e2abc7a399e0d7af4bd9038", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project/server/dependencies/latexindent.pl-master/test-cases/headings/testHeadings2.tex", "max_forks_repo_name": "digorithm/latex-linter", "max_forks_repo_head_hexsha": "d6b63002cdcecf291e2abc7a399e0d7af4bd9038", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8474576271, "max_line_length": 44, "alphanum_fraction": 0.7532023911, "num_tokens": 307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.3195512558143848}}
{"text": "\\chapter{Fitting in the light of LHC data}\n\\label{ch:LHClight}\nThe addition of the first LHC datasets into an NNPDF fit allowed for important gains to be made in the precision of the resulting sets. However the potential dataset available for PDF determination from the LHC is increasing at a considerable rate, and datasets are being rapidly updated with more precise measurements. There is therefore still much more potential in the LHC to provide PDF constraint, especially in collider only fits.\n\nWith the ever enlarging dataset comes an important question: whether the fitting methodology applied to the pre-LHC dataset is still the best procedure for the extraction of precise parton densities in the LHC era. In order to accommodate the growing LHC dataset and to be able to efficiently explore methodological options, the toolchain used by the NNPDF collaboration had to be updated. The need for an updated fitting apparatus was recognised near the end of development of the NNPDF2.3 PDF set. Previous NNPDF sets were generated by a {\\tt FORTRAN} codebase which grew out of the earliest NNPDF determinations. Consequently the codebase suffered from a great deal of inflexibility with regard to the treatment of data. In particular, performing varying cuts and fits to reduced or special datasets were complicated procedures. Additionally as the fits to the pre-LHC dataset were considerably less computationally intensive the core fitting apparatus was not designed with computational efficiency as the first priority, meaning that fits with the LHC dataset were rather sluggish. Beyond being a mere technicality, such slow fits actually meant that detailed studies of the methodology applied to an LHC dataset were prohibitively expensive in computer time.\n\nWith these issues in mind, the {\\tt nnpdf++} project was initiated, whereby the full NNPDF toolchain has been implemented from scratch in {\\tt C++}. The core of the project was built around the efficient $\\tt FK$ method described previously, allowing for a much clearer separation in code between theoretical predictions and experimental data along with a much greater efficiency in the convolution. The {\\tt FK} products themselves are accelerated via explicit use of {\\tt SIMD} vectorisation, and {\\tt OpenMP}~\\cite{openmp08} provides multiprocessor options.\n\nThe framework was designed to be as modular as possible, to allow for the simple and safe modification of sections of the NNPDF methodology without requiring major modifications to the remaining codebase. The re-implementation of the whole NNPDF toolchain also provided an extremely thorough cross-check of the two implementations, and allowed for the step-by-step evaluation of several methodological elements. The results of this re-evaluation and investigation of alternative procedures shall be described in this chapter along with the consequences for future determinations.\n\n\\section{Closure testing}\n\\label{sec:closuretest}\nThe central element in the methodological review conducted with the {\\tt nnpdf++} code after NNPDF2.3 is the closure testing procedure.\n\nIn a closure test, a PDF fitter takes their tools and applies them to a set of pseudo-experimental data generated from a known prior parton distribution set. Provided that the theory used to generate the pseudodata is identical to that used in the fitting procedure, the results of the fit should reproduce the generating function to within the estimation of PDF error. The test is an extremely sensitive check of a fitting procedure, in that it tests the ability of a methodology to resolve the underlying law when said law is known exactly. The method can also be used to study the effect of data inconsistencies by artificially modifying data uncertainties as is examined in Ref.~\\cite{Watt:2012tq}, however here we shall restrict ourselves to examining the quality of reproduction of the underlying law.\n\nClosure tests in the NNPDF methodology can be performed in a number of ways. One possible method is a direct fit to theoretical predictions generated from a known distribution, in this way the pseudo-dataset is free from the statistical noise that would be present in experimental data. $N_{\\text{rep}}$ PDF replicas are then fitted to the theory predictions, without performing the generation of a Monte Carlo artificial data sample. In this type of fit one aims to reproduce as well as possible the generating function at the end of the fit. As no statistical noise is inserted at any point the final fit quality should approach $\\chi^2=0$, we shall therefore denote such a fit a \\emph{level zero} closure test.\n\nAlternatively one may perform a fit where statistical noise is introduced to the pseudo-dataset according to the experimental uncertainty present in the real dataset. This can be done in two ways; either the noise is introduced directly to the pseudo-data itself whereby all Monte Carlo replicas fit to the same noisy sample, or noise is introduced on a replica-by-replica basis as in the normal Monte Carlo procedure. These types of fit we denote \\emph{level one} closure tests.\n\nFinally one can introduce two levels of noise to the data. The first; applied directly to the pseudo-data, simulates the experimental noise in the distributions. The second level is introduced through the normal Monte Carlo generation of artificial data replicas. This is denoted a \\emph{level two} closure test and is the closest to a full fledged PDF fit. The main exception here being the lack of any inconsistency between datasets, as they have all been generated from the same initial distribution. In the case of a level two fit the PDF fitter wishes to reproduce the underlying law to within their quoted PDF uncertainties, the exact reproduction available at level zero is now unavailable due to the introduced pseudo-experimental noise. The level two fit is therefore the most stringent test of a fitting procedure in that it tests the central claim of a fitting group; that the underlying law should lie within the quoted PDF uncertainty band at the quoted confidence level. The settings used in the different closure tests are summarised in Table~\\ref{tab:closurelevel}. As a direct comparison of some example pseudodata, Figure~\\ref{fig:closurepseudodata} shows example data at closure test levels zero, one and two.\n\nThe new structure present in the {\\tt nnpdf++} code, particularly the modular treatment of experimental data and theoretical predictions, allows for the straightforward use of predictions in the place of experimental data while keeping the experimental covariance matrices intact. The closure testing method has therefore been extensively applied to the development of the NNPDF methodology, with the procedure used for the NNPDF3.0 determination being guided largely by results from closure testing. Here we shall outline some general results, before demonstrating the application of the procedure to methodological development in the subsequent sections.\n\n\\begin{table}[h!]\n\\label{tab:closurelevel}\n\\begin{center}\n\\begin{tabular}{|c|c|c|}\n\\hline\nC.~Level & Exp.~Noise & Art.~Data\\\\ \\hline\n0  &  \\text{\\sffamily X} & \\text{\\sffamily X} \\\\\n1a  & \\checkmark & \\text{\\sffamily X} \\\\\n1b  & \\text{\\sffamily X} & \\checkmark \\\\\n2  & \\checkmark & \\checkmark \\\\\n\\hline\n\\end{tabular}\n\\caption[Levels available in a closure test fit]{Levels available in a closure test fit (C.~Level), Exp.~Noise corresponds to simulating experimental noise in the pseudodata sample. Art.~Data refers to the generation of artificial data replicas in the Monte Carlo uncertainty procedure.}\n\\end{center}\n\\end{table}%\n\n\\begin{figure}[hp]\n\\centering\n\\includegraphics[width=0.9\\textwidth]{7-PostLHC/figs/Closuretest_levels/closuretest_levels.pdf}\n\\caption[Closure test pseudodata example]{Examples of pseudodata used in a closure test for all three levels. The black circles show the level zero pseudodata, and the experimental error bars. The blue squares show the pseudodata after experimental noise has been simulated (level one) and the red diamonds after both statistical noise simulation and Monte Carlo replica generation (level two). All points are normalised to the generating PDF set (NNPDF2.3).}\n\\label{fig:closurepseudodata}\n\\end{figure}\n\\clearpage\n\n\\subsubsection{Early closure tests}\nThe earliest NNPDF closure tests were conducted to assess the usefulness of the procedure, and performed with the full NNPDF2.3 procedure. As an initial test, a fit was performed to the toy PDF parametrisation as used in the Les Houches evolution benchmarks~\\cite{Giele:2002hx}, a parametrisation based upon the CTEQ5M determination~\\cite{Lai:1999wy}. In this set, the initial state distributions are given as\n\n\\begin{eqnarray}\n\\label{gsav-eq9}\n  xu_v(x,\\mu_{\\rm f,0}^2)       &\\! =\\! & 5.107200\\: x^{0.8}\\: (1-x)^3,  \n    \\nonumber \\\\\n  xd_v(x,\\mu_{\\rm f,0}^2)       &\\! =\\! & 3.064320\\: x^{0.8}\\: (1-x)^4,  \n    \\nonumber \\\\\n  xg\\,(x,\\mu_{\\rm f,0}^2)       &\\! =\\! & 1.700000\\, x^{-0.1} (1-x)^5, \n    \\nonumber \\\\\n  x\\bar{d}\\,(x,\\mu_{\\rm f,0}^2) &\\! =\\! & .1939875\\, x^{-0.1} (1-x)^6,\n    \\nonumber\\\\\n  x\\bar{u}\\,(x,\\mu_{\\rm f,0}^2) &\\! =\\! & (1-x)\\: x\\bar{d}\\,(x,\\mu_{\\rm f,0}^2),\n    \\nonumber\\\\\n  xs\\,(x,\\mu_{\\rm f,0}^2)       &\\! =\\! & x\\bar{s}\\,(x,\\mu_{\\rm f,0}^2) \n    \\: = \\: 0.2\\, x(\\bar{u}+\\bar{d}\\,)(x,\\mu_{\\rm f,0}^2),\n\\end{eqnarray}\nwhere $u_v$ and $d_v$ refer to the up and down valence distributions respectively. Predictions for the NNPDF2.3 dataset were made according to these distributions, and used in the place of experimental data. Experimental noise was simulated in the pseudodata by application of the same procedure used to provide artificial data replicas. The full NNPDF2.3 procedure including Monte Carlo artificial replicas was then applied to the dataset, the resulting PDF set therefore being a level two type closure test where the generating PDF set should be recovered by the fit within the estimated uncertainties.\n\nFigure~\\ref{fig:LHtoyclosure1} displays the results of the level two closure test fit with the Les Houches toy PDFs used as a generating function. The result demonstrates impressive agreement, with the NNPDF2.3 methodology able to accommodate the predictions of the Les Houches toy generating function despite it deviating significantly from the standard NNPDF2.3 result. For all four PDF combinations shown, the results of the closure test maintain distances of less than one standard deviation to the generating function across a wide kinematic range. Of additional interest are the strange distributions, relatively poorly constrainted by the data included in the pseudo-dataset. The strange valence in particular is set to zero in the Les Houches toy. Figure~\\ref{fig:LHtoyclosure2} shows the results from the closure test for both the total strangeness and strange valence distributions, the NNPDF methodology is able to clearly reproduce the underlying law within uncertainties in both cases, and is able to comfortably resolve a zero strange valence contribution.\n\nThe results are particularly impressive considering that this is a test of a methodology that has not been previously verified by closure test. The example case of a pseudo-dataset generated according to the Les Houches toy PDF is however a rather simplified case, and methodological refinements can be made by examining closure tests with greater structure in the generating function.\n\nA good level of agreement can also be found at the level of the $\\chi^2$ to both the pseudodata sample, and the real experimental data. In Figure~\\ref{fig:CPPclosurechi2} we compare the fit quality of a closure test and its generating PDF dataset by dataset by presenting the $\\chi^2$ to each measurement from both the closure test result and the generating PDF. In this case the generating function has considerably greater complexity, being an early {\\tt nnpdf++} test fit with most of the NNPDF methodology in place. While agreement is generally very good, especially on the level of total $\\chi^2$; we begin to see some elements of discrepancy in datasets sensitive to flavour separation and strangeness such as the NuTeV dataset and electroweak vector boson production data. Such discrepancies can help in pinpointing areas where further development is needed.\n\n\\clearpage\n\\begin{figure}[h!]\n\\centering\n\\includegraphics[width=0.48\\textwidth]{7-PostLHC/figs/gluon.pdf}\n\\includegraphics[width=0.48\\textwidth]{7-PostLHC/figs/singlet.pdf}\\\\\n\\includegraphics[width=0.48\\textwidth]{7-PostLHC/figs/valence.pdf}\n\\includegraphics[width=0.48\\textwidth]{7-PostLHC/figs/triplet.pdf}\n\\caption[PDFs obtained through a Closure test fit with toy PDFs as a generating function]{PDFs obtained through a closure test fit with Les Houches toy PDFs as a generating function, displayed as a ratio to the generating function. Shown are the distributions for the gluon, singlet, valence and triplet PDFs. In green are the results obtained through the closure test, and the red curves show the standard NNPDF2.3 result.}\n\\label{fig:LHtoyclosure1}\n\\end{figure}\n\\begin{figure}[h!]\n\\centering\n\\includegraphics[width=0.48\\textwidth]{7-PostLHC/figs/strangesea.pdf}\n\\includegraphics[width=0.48\\textwidth]{7-PostLHC/figs/c1_n64.pdf}\n\\caption[Strange PDFs obtained through a Closure test fit with toy PDFs as a generating function]{Strange sea (left) and valence (right) PDFs obtained through a closure test fit with Les Houches toy PDFs as a generating function. The strange sea is presented as a ratio to the LH toy PDF, and the strange valence is presented directly as the PDF, with the (zero) LH toy line shown.}\n\\label{fig:LHtoyclosure2}\n\\end{figure}\n\\clearpage\n\n\\begin{figure}[!]\n\\centering\n\\includegraphics[width=0.48\\textwidth]{7-PostLHC/figs/chi2_histo_nnpdf1.pdf}\n\\includegraphics[width=0.48\\textwidth]{7-PostLHC/figs/chi2_histo_nnpdf2.pdf}\n\\caption[$\\chi^2$ values to the pseudo- and experimental-datasets of a closure fit and the generating PDF]{Example $\\chi^2$ values to the pseudo- (left) and experimental- (right) datasets of a closure fit and the generating PDF from early {\\tt nnpdf++} test fits. The red bars show the fit quality of the generating PDF set while the green bars demonstrate the $\\chi^2$ for the closure test set. The horizontal lines indicate the average and $1\\sigma$ of the fit qualities in their associated colours.}\n\\label{fig:CPPclosurechi2}\n\\end{figure}\n\n\\section{Preprocessing}\n\nEarly closure tests performed with the NNPDF2.3 methodology showed generally very good agreement between the produced PDFs and the underlying functions used to generate the pseudo-dataset. However some PDF combinations demonstrated rather poorer agreement than others, particularly distributions sensitive to flavour separation. Such disagreements became more apparent when considering closure tests to underlying functions with more structure than available in the Les Houches toy set. The disagreements were found to originate in the choice of the preprocessing exponents used in the definition of the NNPDF parametrisation. Recalling Eqn.~\\ref{eq:NNPDF23param}, the structure of the basic NNPDF parametrisation follows\n\\be f(x) \\propto x^{-\\alpha} (1-x)^{\\beta} \\text{NN}(x),\\ee\nwhere NN represents the neural network itself, and $\\alpha$ and $\\beta$ are the preprocessing exponents randomised on a replica-by-replica basis at the start of a fit. The range in which the exponents were randomised has been fixed in the fits up to and including NNPDF2.3, set to a span large enough such that the dependence of the results upon the choice of range was minimised. In such a way the preprocessing was considered to provide a backbone for the neural-network fit and, aside from improving fitting efficiency, to have a minimal impact upon the results.\n\nTo study the effect of different preprocessing ranges we can look at estimators for the \\emph{effective} asymptotic exponents,\n\\be \\alpha_{\\text{eff}} = -\\frac{\\log{(|f(x)|)}}{\\log(x)},\\quad\\quad \\beta_{\\text{eff}} = \\frac{\\log{(|f(x)|)}}{\\log(1-x)}, \\ee\nsuch that in the limits of $x\\to0,1$ the exponents $\\alpha,\\beta$ are recovered. By examining these effective exponents in the high- and low-$x$ regions, we can ascertain if there is a data preference for a different preprocessing range than was used in a fit, and if the preprocessing range used was too restrictive.\n\nIn Figure~\\ref{fig:preproc1} an example preprocessing analysis is shown for a closure test based upon an MSTW08 underlying law at NLO. The sea asymmetry $\\bar{u} -\\bar{d}$ is shown for two choices of preprocessing range, the NNPDF2.3 standard and a range modified to better accommodate the data preference visible in the effective exponents. From the figure we can see that the choice of exponent randomisation range has a significant effect on the resulting distributions, and that the effective exponents can show a clear data preference for a different range. In Figure~\\ref{fig:preproc2} we can see the same analysis applied to the triplet PDF where similar conclusions may be drawn.\n\nThese analyses demonstrate that the sensitivity to the preprocessing exponent randomisation ranges is somewhat larger than suspected previously, and needs to be studied in detail in order to avoid minimisation difficulties in a fit where the preprocessing ranges are ill-suited to the dataset. Furthermore, the uncertainty bulges visible in both the triplet and sea asymmetry distributions in Figures~\\ref{fig:preproc1} and~\\ref{fig:preproc2} are generated by the preprocessing suppressing genuine data uncertainty in the asymptotic regions. These problems may be alleviated by lifting the requirement that such distributions should be preprocessed to zero at low-$x$, and implementing a procedure for the iterative and data-driven determination of preprocessing exponents.\n\nTo improve the minimisation performance, hampered by ill-suited preprocessing, NNPDF fits have now adopted the following iterative procedure for the determination of both high and low-$x$ randomisation ranges:\n\n\\begin{itemize}\n\\item \\textbf{Singlet and gluon PDFs}\\\\\nExponent randomisation ranges are set to be twice the $1\\sigma$ interval of the previous iteration's effective exponents\nat the asymptotic points.\n\\item \\textbf{Nonsinglet PDF combinations}\\\\\nThe low-$x$ randomisation interval is set to be the maximal extent of two effective exponent ranges; twice the $1\\sigma$ interval at the asymptotic point and twice the $1\\sigma$ interval at the point $x=1\\times 10^{-3}$. The high-$x$ interval is set identically as with the singlet and gluon.\n\\end{itemize} \n\nIn such a way convergence of the randomisation interval can be established typically in two or three fit iterations, and the preprocessing exponents are obtained from the preference of the experimental dataset. As an example of a fit generated from such an iterative procedure consider Figure~\\ref{fig:preproc3} which demonstrates the preprocessing analysis for the $\\Delta_s$ and Triplet distributions resulting from the new procedure. In comparison to Figure~\\ref{fig:preproc1} where the old settings are used, the low-$x$ preprocessing ranges have relaxed considerably and are no longer constrained by the chosen exponent range but driven by the experimental data. Furthermore the agreement with the underlying law is noticeably improved over the previous result shown in Figure~\\ref{fig:preproc1}. \n\n\\begin{figure}[hp!]\n\\centering\n\\includegraphics[width=0.48\\textwidth]{7-PostLHC/figs/Preproc1/pdf_xDs_log_others.pdf}\n\\includegraphics[width=0.48\\textwidth]{7-PostLHC/figs/Preproc2/pdf_xDs_log_others.pdf}\n\\includegraphics[width=0.48\\textwidth]{7-PostLHC/figs/Preproc2/alphapreproc_4.pdf}\n\\includegraphics[width=0.48\\textwidth]{7-PostLHC/figs/Preproc2/betapreproc_4.pdf}\n\\caption[Demonstration of the impact made by changes in preprocessing to the sea asymmetry PDF in a closure test fit]{Demonstration of the impact made by changes in preprocessing to the sea asymmetry PDF in a closure test fit to an MSTW08 NLO underlying law. The top two figures demonstrate the results for the $\\Delta_s$ distribution for two choices of preprocessing ranges, with the left figure using NNPDF2.3 standard preprocessing. In both cases, the red curve shows the underlying law used in the Closure test. The right figure demonstrates slightly improved agreement, particularly at low-$x$. The lower figures show the low and high $x$ effective exponent plots for the two ranges. The solid horizontal lines delineate the regions in which the preprocessing exponents were initialised, and the bands show the $1\\sigma$ contours of the effective exponents.}\n\\label{fig:preproc1}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}[!]\n\\centering\n\\includegraphics[width=0.42\\textwidth]{7-PostLHC/figs/Preproc1/pdf_xT3_log_others.pdf}\n\\includegraphics[width=0.42\\textwidth]{7-PostLHC/figs/Preproc2/pdf_xT3_log_others.pdf}\n\\includegraphics[width=0.42\\textwidth]{7-PostLHC/figs/Preproc2/alphapreproc_3.pdf}\n\\includegraphics[width=0.42\\textwidth]{7-PostLHC/figs/Preproc2/betapreproc_3.pdf}\n\\caption[Demonstration of the impact made by changes in preprocessing to the triplet PDF in a closure test fit]{A further preprocessing analysis as in Figure~\\ref{fig:preproc1}, performed upon the Triplet PDF combination for the same two closure test fits.}\n\\label{fig:preproc2}\n\\end{figure}\n\n\\begin{figure}[!]\n\\centering\n\\includegraphics[width=0.42\\textwidth]{7-PostLHC/figs/PreprocFixed/pdf_xDs_log_others.pdf}\n\\includegraphics[width=0.42\\textwidth]{7-PostLHC/figs/PreprocFixed/pdf_xDs_others.pdf}\n\\includegraphics[width=0.42\\textwidth]{7-PostLHC/figs/PreprocFixed/pdf_xT3_log_others.pdf}\n\\includegraphics[width=0.42\\textwidth]{7-PostLHC/figs/PreprocFixed/pdf_xT3_others.pdf}\n\\caption[Impact of improved preprocessing range selection in the sea asymmetry and triplet PDFs]{Impact of improved preprocessing range selection in the sea asymmetry and triplet PDFs. The top figures demonstrate the $\\Delta_s$ PDF obtained via a closure test to MSTW08 using the improved preprocessing procedure in green, with the underlying law shown in red. The figures below show the equivalent plots for the triplet PDF with the improved preprocessing ranges.}\n\\label{fig:preproc3}\n\\end{figure}\n\\clearpage\n\n% Old figures\n%\\begin{figure}[!]\n%\\centering\n%\\includegraphics[width=0.42\\textwidth]{7-PostLHC/figs/PreprocFixed/pdf_xDs_log_others.pdf}\n%\\includegraphics[width=0.42\\textwidth]{7-PostLHC/figs/PreprocFixed/pdf_xDs_others.pdf}\n%\\includegraphics[width=0.42\\textwidth]{7-PostLHC/figs/PreprocFixed/alphapreproc_4.pdf}\n%\\includegraphics[width=0.42\\textwidth]{7-PostLHC/figs/PreprocFixed/betapreproc_4.pdf}\n%\\caption[Impact of improved preprocessing range selection in the sea asymmetry PDF]{Impact of improved preprocessing range selection in the sea asymmetry PDF. The top figures demonstrate the $\\Delta_s$ PDF obtained via a closure test to MSTW08 using the improved preprocessing procedure in green, with the underlying law shown in red. The figures below show the effective exponents for this PDF, and the effect of the improved range selection.}\n%\\label{fig:preproc3}\n%\\end{figure}\n%\\clearpage\n%\n%\n%\\begin{figure}[!]\n%\\centering\n%\\includegraphics[width=0.42\\textwidth]{7-PostLHC/figs/PreprocFixed/pdf_xT3_log_others.pdf}\n%\\includegraphics[width=0.42\\textwidth]{7-PostLHC/figs/PreprocFixed/pdf_xT3_others.pdf}\n%\\includegraphics[width=0.42\\textwidth]{7-PostLHC/figs/PreprocFixed/alphapreproc_3.pdf}\n%\\includegraphics[width=0.42\\textwidth]{7-PostLHC/figs/PreprocFixed/betapreproc_3.pdf}\n%\\caption[Impact of improved preprocessing range selection in the triplet PDF]{Impact of improved preprocessing range selection in the triplet PDF. Displayed as in Figure~\\ref{fig:preproc3}. In the case of the high $x$ effective exponent, the data's preferred range lies well within the set randomisation range of the exponents. For the small-$x$ exponent, more iteration is needed here to settle on a larger range. The general features of the extended preprocessing ranges can be clearly seen in the top figures.}\n%\\label{fig:preproc4}\n%\\end{figure}\n\n\\subsection{Strange valence preprocessing}\nA special case when considering the preprocessing of the neural networks is that of the strange valence distribution. As specified in Equation~\\ref{eq:NNPDF23param}, the strange valence PDF in the NNPDF2.3 determination had an auxiliary term to encourage the PDF to perform its required sign change in the valence region. Such an additional term has been previously needed due to the lack of specific data constraints upon the strange valence distribution before the LHC, introducing a bias, albeit a physically motivated one. Additionally the auxiliary term provides a mechanism by which the strange valence sum rule may be imposed. In the NNPDF3.0 determination and beyond this auxiliary term has been removed given the enlarged dataset and it's improved sensitivity to the strange PDF.\n\nFigure~\\ref{fig:preproc5} demonstrates the effect of the removal of the strange auxiliary term upon a closure test fit to the MSTW08 set. While the NNPDF2.3 methodology closure fit struggles to accommodate the MSTW08 strange valence distribution, the updated methodology is able to reproduce the underlying law well, within enlarged uncertainties.\n\n\\begin{figure}[h!]\n\\centering\n\\includegraphics[width=0.42\\textwidth]{7-PostLHC/figs/Preproc1/pdf_xsminus_log_others.pdf}\n\\includegraphics[width=0.42\\textwidth]{7-PostLHC/figs/Preproc1/pdf_xsminus_others.pdf}\n\\includegraphics[width=0.42\\textwidth]{7-PostLHC/figs/PreprocFixed/pdf_xsminus_log_others.pdf}\n\\includegraphics[width=0.42\\textwidth]{7-PostLHC/figs/PreprocFixed/pdf_xsminus_others.pdf}\n\\caption[Impact of more flexible treatment of strange valence PDF in fits post NNPDF2.3]{Impact of more flexible treatment of strange valence PDF in fits post NNPDF2.3. The top two figures show a comparison of a closure test performed with the NNPDF2.3 preprocessing, and the figures below show the results using the more flexible parametrisation.}\n\\label{fig:preproc5}\n\\end{figure}\n\n\\clearpage\n\n\\section{PDF parametrisation}\nThe choice of PDF parameterisation and basis used in the fitting procedure has been reassessed with the help of the closure test procedure. In particular, a modification to the choice of fitting basis has been made necessary by the removal of the strange valence sum rule enforcing auxiliary term in the strange valence parametrisation. The most direct choice of fitting basis is the same basis as is used in PDF evolution, and therefore the basis required for PDFs in the {\\tt FK} product. In this basis, the required quantum number sum rules may be applied as normalisations to the total valence, $V_3$ and $V_8$ distributions,\n\\ba V(x,Q^2_0) &=& N_V \\left( u^- + d^-+ s^- \\right)(x,Q^2_0),\\nonumber \\\\\nV_3(x,Q^2_0) &=& N_{V3} \\left( u^- - d^- \\right)(x,Q^2_0), \\nonumber \\\\\nV_8(x,Q^2_0) &=& N_{V8} \\left( u^- + d^- - 2s^-\\right)(x,Q^2_0),\n\\ea\nwhere the normalisations $N$ are set such that\n\\ba \\int_0^1 dx\\, V(x,Q^2_0) &=& 3,\\\\\n \\int_0^1 dx\\, V_3(x,Q^2_0) &=& 1,\\\\\n \\int_0^1 dx\\, V_8(x,Q^2_0) &=& 3.\\ea\n\nIn such a way, the total valence quantum number is fixed, along with the up, down and strange valence quantum numbers. The evolution basis also has the advantage of being\nparticularly efficient, not requiring any transformation before combination with {\\tt FK} tables to calculate physical observables. We have shown, based upon closure test results, that the fit results\nshow a good degree of stability under such a change in parametrisation basis. While the previous strategy was designed to construct PDF combinations with specific data constraints, the flexibility of the fit\nmeans that the results do not suffer when moving away from such a basis. Figure~\\ref{fig:EVOLvs23BASIS} shows the statistical distance between a fit with the full evolution basis with a fit based upon the standard NNPDF2.3 parametrisation basis.\nAs expected, any differences are isolated to those PDFs whose parametrisation (and therefore preprocessing) has substantially changed e.g $\\Delta_S$ and the strange PDFs. Even in these PDFs the differences are typically\nless than half a standard deviation.\n\n\n\\begin{figure}[!]\n\\centering\n\\includegraphics[width=0.9\\textwidth]{7-PostLHC/figs/EVOLvs23BASIS/distances_evol.pdf}\n\\caption[Distance comparison of two closure test fits with differing parametrisation bases]{Distance comparison of two closure test fits with differing parametrisation bases. Distances are defined through the measure in Appendix~\\ref{app:distances}, whereby a distance of 10 corresponds to $1\\sigma$.}\n\\label{fig:EVOLvs23BASIS}\n\\end{figure}\n  \n\\section{Minimisation and stopping}\nIn addition to examining areas where the choice of parametrisation may lead to some degree of bias, the closure test procedure is particularly useful for assessing the efficacy of a fitting methodology. Furthermore, the substantial gains in computational efficiency made in the transition to the {\\tt nnpdf++} code mean that far more aggressive genetic minimisation strategies may be implemented.\n\nThe entirety of the NNPDF minimisation procedure has therefore been re-examined to ensure that it is the most effective methodology in the light of additional constraints coming from the LHC. Here we shall summarise some of the major modifications made since the NNPDF2.3 determination.\n\n\\subsection{Target weighted training}\nTarget Weighted Training (TWT) was a central feature of previous NNPDF determinations. TWT was developed in early NNPDF fits as a method of obtaining a balanced training across datasets, solving a problem with early neural network fits whereby some smaller datasets\nwere largely ignored by the minimisation in favour of larger, more constraining sets. This typically led to a very uneven fit quality profile over the complete experimental dataset. The TWT procedure solved this problem by introducing a training epoch at the beginning of a fit where each dataset had a target $\\chi^2$. In the event where a fit iteration reached a $\\chi^2$ value higher than the target, a large weight in fit quality was applied to that dataset in order to bring its fit quality down. \n\nWhile ensuring a relatively even training profile, the TWT procedure had a number of difficulties. The most important being the restriction of the early fit to a $\\chi^2$ fit quality measure applied on a dataset-by-dataset basis, ignoring experimental uncertainty cross-correlations such as luminosity uncertainties, between datasets. Furthermore the TWT procedure introduced a considerable amount of complexity in the fitting procedure. With this in mind, real data fits with target weighted training were compared to fits without in the {\\tt nnpdf++} framework with the large experimental dataset of NNPDF2.3 and updated genetic algorithm parameters. Figure~\\ref{fig:twtvsnotwt} compares the dataset-by-dataset fit quality of two such example fits. With these fits we can see clearly that with a larger dataset and more efficient GA procedure, no large training imbalance can be seen in the fits even without the TWT procedure applied. Future NNPDF fits will therefore be performed without target weights, allowing for the consistent application of the experimental correlations across datasets throughout the fitting procedure.\n\n\\begin{figure}[!]\n\\centering\n\\includegraphics[width=1\\textwidth]{7-PostLHC/figs/TWTvsnoTWT/chi2_histo.pdf}\n\\caption[Comparison of $\\chi^2$ by dataset between real data fits with and without Target Weighted Training]{Comparison of $\\chi^2$ by dataset between real data fits with (green bars) and without (red bars) Target Weighted Training.}\n\\label{fig:twtvsnotwt}\n\\end{figure}\n\n\\subsection{Genetic algorithm}\nA number of changes have been made to the GA procedure used in NNPDF fits in order to improve fitting efficiency and provide more precise PDF determinations. In the analysis of the efficacy of a GA, level zero closure tests are particularly helpful in that they\ndirectly test the ability of a minimisation procedure to reproduce a given function precisely. In these fits the closure test fit should be able to effectively draw a line between datapoints, leading to an ideal $\\chi^2$ of zero to the pseudo-data.\n%\n%\n%140430-r1753-001-sc.ini - DynStop\n%140512-r1765-003-cd.ini  - LookBack 30k\n%140512-r1765-004-cd.ini  - LookBack 60k\n%\n%\nA number of modifications to the procedure have been tested, the most effective of which is the implementation of \\emph{Nodal} mutations in the GA~\\cite{Montana:1989:TFN:1623755.1623876}. In previous versions of the NNPDF GA, mutations were performed upon individual parameters of each neural network with no consideration as to their position in the network. \n\nThe concept of nodal mutations introduces the strategy of mutating all parameters associated with a particular neural network \\emph{node} at once. In this procedure a node of the network is chosen at random, then all of its associated weights connected to the earlier layer are mutated along with its threshold parameter. Doing so yields a much more effective genetic algorithm as demonstrated in the comparison in Figure~\\ref{fig:nodalvsnonnodal}, where a standard GA is compared to a nodal mutation GA in their reproduction of the MSTW underlying law. The nodal GA is able to better resolve the underlying law, and to a greater precision. The comparison in Figure~\\ref{fig:nodalvsnonnodal} is corroborated by the $\\chi^2$ values of the two fits to the perfect pseudo-data in the level zero fit. The standard GA fit shown in the figure obtained a final $\\chi^2$ of 0.0279 compared to 0.0043 for the nodal GA. The nodal GA strategy has therefore been adopted for future NNPDF determinations.\n\n\\begin{figure}[!]\n\\centering\n\\includegraphics[width=0.48\\textwidth]{7-PostLHC/figs/NodalGA/singlet.pdf}\n\\includegraphics[width=0.48\\textwidth]{7-PostLHC/figs/NodalGA/triplet.pdf}\n\\caption[Comparison of a conventional NNPDF GA fit with a Nodal GA fit in a closure test to MSTW2008]{Comparison of a conventional NNPDF GA fit (red bands) with a Nodal GA fit (green bands) in a closure test to MSTW08. PDFs are given as a ratio to the generating PDF set for the singlet (left) and triplet (right) distributions.}\n\\label{fig:nodalvsnonnodal}\n\\end{figure}\n\n\\subsection{Dynamical stopping}\nThe cross-validation dynamical stopping procedure utilised in previous {\\tt FORTRAN} based NNPDF fits was triggered by a slope-detection algorithm applied to the fit quality profiles of each replica to the validation dataset. While providing a reasonable stopping criteria and preventing excessive overfitting, the relative balance between the degree of under- and over-learning was governed by the parameters of the slope-detection algorithm. Such sensitivity to the stopping parameters meant that a re-tune was often necessary upon large modifications to the dataset or minimisation algorithm. \n\nThe modular nature of the stopping criteria implemented in the {\\tt nnpdf++} framework means that alternative stopping procedures may be quickly and safely implemented to investigate their impact. One such stopping criterion that has demonstrated greater stability than the previous slope-detection based procedure is that of \\emph{look-back} cross-validation. \n\nIn this procedure all replicas are run for the maximum number of generations $N_{\\text{gen}}^{\\text{max}}$, all the while storing the GA generation that best described the validation dataset. At the end of the fit, the GA generation that minimised the $\\chi^2$ to the validation set is selected as the best-fit stopping point, and that replica is used as a member of the Monte Carlo ensemble. This method yields an extremely clean stopping criterion, having no tuneable parameters aside from the maximum number of generations, and offers a very faithful implementation of the cross-validation method. Furthermore, the look-back procedure is not practically more time-consuming to implement despite running each replica to the maximum number of generations, as even in the previous dynamical stopping procedure the time taken to run a fit is typically given by the time taken by the slowest replica. In Figure~\\ref{fig:LBCVchi2prof} the fit quality profile for a single PDF replica can be seen for the training and validation sets alongside the look-back stopping point. In this case, the look-back method can clearly discern an overlearning signal, as the fit quality to the validation set worsens while the training set $\\chi^2$ improves.\n\n\\begin{figure}[!]\n\\centering\n\\includegraphics[width=0.7\\textwidth]{7-PostLHC/figs/lookbackchi2prof.pdf}\n\\caption[Fit quality profiles for the training and validation sets in look-back cross validation]{Fit quality profiles for the training and validation sets in look-back cross validation. The red curve shows the fit quality to the training set, and the blue curve to the validation set as the number of fit generations goes on. The green line indicates the stopping point selected by the look-back criterion, generation 12813 having the minimum validation $\\chi^2$.}\n\\label{fig:LBCVchi2prof}\n\\end{figure}\n\n\nIn Figure~\\ref{fig:30kLBvsDYN} we compare the results for the singlet and gluon PDFs in the case of a look-back fit with $N_{\\text{gen}}^\\text{max}=$ 30,000 generations, and a fit with the NNPDF2.3 standard dynamical stopping. In both instances, the fit performed was a level two closure test using MSTW2008 as the underlying law. While differences are small the look-back fit demonstrates slightly smaller uncertainties, implying a marginal underlearning present in the NNPDF2.3 dynamical stopping procedure. The fits yield essentially equivalent results, although the optimal point determined in the look-back method is typically somewhat later than in the dynamical stopping as can be seen in the comparison of training length histograms in Figure~\\ref{fig:30kLBvsDYNtl}. In this figure it is clear also that several PDF replicas in the look-back method stop close to the maximum number of generations available, implying that no significant overlearning can been resolved in their cases over the given GA interval.\n\nIn order to examine the effect of increasing the length of the look-back period, we compare the 30,000 generation fit to an extended 60,000 generation fit in Figure~\\ref{fig:30kLBvs60kLB} where we use the PDF distance definition in Appendix~\\ref{app:distances}. Distances of effectively zero throughout the PDF combinations and $x$-range mean that no change is observed between the two fits, demonstrating the stability of the method once a sufficiently large look-back length is used. The look-back cross-validation method as discussed here will therefore be implemented as the default stopping criterion for the NNPDF3.0 family of fits.\n\n\n\\begin{figure}[h!]\n\\centering\n\\includegraphics[width=0.48\\textwidth]{7-PostLHC/figs/LB30kvsDYN/pdf_xg_log.pdf}\n\\includegraphics[width=0.48\\textwidth]{7-PostLHC/figs/LB30kvsDYN/pdf_xg.pdf}\\\\\n\\includegraphics[width=0.48\\textwidth]{7-PostLHC/figs/LB30kvsDYN/pdf_xsigma_log.pdf}\n\\includegraphics[width=0.48\\textwidth]{7-PostLHC/figs/LB30kvsDYN/pdf_xsigma.pdf}\n\\caption[Comparison of PDFs obtained through look-back cross validation and NNPDF2.3 standard dynamical stopping]{Comparison of PDFs obtained through look-back cross validation and NNPDF2.3 standard dynamical stopping. PDFs for the singlet and gluon are shown, with green bands representing fits using the look-back method and red demonstrating those with the slope-detection algorithm used in NNPDF2.3 and earlier.}\n\\label{fig:30kLBvsDYN}\n\\end{figure}\n \n  \\begin{figure}[!]\n\\centering\n\\includegraphics[width=0.48\\textwidth]{7-PostLHC/figs/LB30kvsDYN/tl.pdf}\n\\includegraphics[width=0.48\\textwidth]{7-PostLHC/figs/LB30kvsDYN/tl_ref.pdf}\n\\caption[Comparison of training lengths in look-back cross-validation and NNPDF2.3 standard dynamical stopping]{Comparison of training lengths in look-back cross-validation and NNPDF2.3 standard dynamical stopping. The left figure demonstrates the 'optimal point' determined by looking back over the while GA interval for the minimum validation $\\chi^2$. The right figure shows the stopping point based upon the slope-detection algorithm.}\n\\label{fig:30kLBvsDYNtl}\n\\end{figure}\n\n\\begin{figure}[!]\n\\centering\n\\includegraphics[width=0.9\\textwidth]{7-PostLHC/figs/LB30kvsLB60k/distances_evol.pdf}\n\\caption[Distance comparison of two closure test fits with look-back stopping enabled and different maximum training lengths]{Distance comparison of two closure test fits with look-back stopping enabled and different maximum training lengths. Distances are computed between all evolution basis PDFs at the initial scale between $N_{\\text{gen}}^\\text{max}=$ 30,000 and $N_{\\text{gen}}^\\text{max}=$ 60,000 generation look-back fits.}\n\\label{fig:30kLBvs60kLB}\n\\end{figure}\n\n\\section{Methodology for NNPDF3.0}\nWe have performed an overview of the methodological developments made since the release of the NNPDF2.3 PDF set, with an aim to outline the procedure to be used in the forthcoming NNPDF3.0 set. To provide a stringent verification of the combined procedure, we shall now examine a set of closure test fits performed at various levels to differing generating PDF sets. In this section we present fits based upon a nodal genetic algorithm minimisation with look-back cross-validation stopping as detailed previously, with the iterative preprocessing procedure and new PDF fitting basis. Therefore the fits represent preliminary closure test results for the NNPDF3.0 methodology, upon a global pseudo-dataset of hadronic and DIS data. Results in this section will be presented using NLO calculations for the observables in the fit, although the conclusions will be very similar for an identical analysis at NNLO, as the closure test procedure is relatively insensitive to theory choices.\n\n\\subsection{Closure tests for NNPDF3.0}\n\nFirstly let's consider the results obtained when fitting to an MSTW2008 generating PDF, the closure test guiding the methodological choices made so far in this section. In Figure~\\ref{fig:finalClosure_MSTW} the ratio of the resulting closure test PDFs to the generating MSTW08 distributions are shown for some of the evolution basis PDFs. Here we show results for the kinematic region most constrained by the experimental pseudo-dataset: $10^{-2} \\le x \\le 1$. The level zero curves in Figure~\\ref{fig:finalClosure_MSTW} closely reproduce the MSTW central values, achieving a final total $\\chi^2/N_{\\text{dat}} = 0.00182$. The uncertainty band in the case of the level zero result corresponds directly to the functional freedom available within the fitted pseudo-dataset. The level two fit clearly demonstrates the variations introduced by the simulated experimental noise, with the expected level of deviation clearly visible in the resulting PDFs. Given the simulated noise in the pseudo-dataset, the closure test still tracks the central value to an excellent level of accuracy, achieving an almost statistically ideal fit quality of $\\chi^2/N_{\\text{dat}} = 1.00021$.\n\nAs the preliminary NNPDF3.0 methodology has been validated against closure test fits to the MSTW2008 set, it is important to test the procedure's ability to reproduce a generating PDF with greater functional complexity. To verify the preliminary methodology in this case we now consider a closure test fit to the NNPDF2.3 PDF set. Figure~\\ref{fig:finalClosure_NNPDF} demonstrates once more the level zero and two closure test fits to NNPDF2.3. Even given the greater functional freedom present in the previous NNPDF determination, the 3.0 closure test provides an excellent reproduction of the generating functions, with fit qualities of  $\\chi^2/N_{\\text{dat}} = 0.00287$ and $1.01356$ respectively. Once again the uncertainty due to parametrisation flexibility is demonstrated in the level zero fit, while the level two fit provides a closer simulation of a full fledged experimental data fit. These figures therefore suggest that the preliminary NNPDF3.0 methodological choices can accurately determine complex functional forms without any modification with respect to fits to much simpler parametrisations.\n\nFor a final closure test, we shall now consider a fit using the CT10 PDF set as a set of generating functions. In this way we can verify the NNPDF3.0 method in a way that is independent of the closure PDF set guiding the methodological development (MSTW2008) and previous NNPDF determinations. The results of the test, once more at level zero and two, are shown in Figure~\\ref{fig:finalClosure_CT10}. The closure test fit provides once again an excellent description of data, with $\\chi^2/N_{\\text{dat}} = 0.00130$ for the level zero fit and $1.01324$ for the level one. The procedure detailed here has now been validated against three different generating PDFs in a closure test and is able to convincingly reproduce the generating sets in each of them. We can therefore be confident that when applied to real experimental data the procedure will yield an accurate result up to theoretical uncertainties.\n\n\\begin{figure}[!]\n\\centering\n\\includegraphics[width=0.45\\textwidth]{7-PostLHC/figs/finalClosure/MSTW0/gluon.pdf}\n\\includegraphics[width=0.45\\textwidth]{7-PostLHC/figs/finalClosure/MSTW0/singlet.pdf}\n\\includegraphics[width=0.45\\textwidth]{7-PostLHC/figs/finalClosure/MSTW0/valence.pdf}\n\\includegraphics[width=0.45\\textwidth]{7-PostLHC/figs/finalClosure/MSTW0/triplet.pdf}\n\\caption[NNPDF3.0 methodology closure test fit to MSTW2008 NLO]{NNPDF3.0 methodology closure test fit to MSTW2008 NLO. Curves are shown normalised to the generating PDF for the gluon, singlet, triplet and valence distributions. The green curves show the results of a level zero closure test, while the red curves show the results of a level two test.}\n\\label{fig:finalClosure_MSTW}\n\\end{figure}\n\\begin{figure}[!]\n\\centering\n\\includegraphics[width=0.45\\textwidth]{7-PostLHC/figs/finalClosure/NNPDF23/gluon.pdf}\n\\includegraphics[width=0.45\\textwidth]{7-PostLHC/figs/finalClosure/NNPDF23/singlet.pdf}\n\\includegraphics[width=0.45\\textwidth]{7-PostLHC/figs/finalClosure/NNPDF23/valence.pdf}\n\\includegraphics[width=0.45\\textwidth]{7-PostLHC/figs/finalClosure/NNPDF23/triplet.pdf}\n\\caption[NNPDF3.0 methodology closure test fit to NNPDF2.3 NLO]{NNPDF3.0 methodology closure test fit to NNPDF2.3 NLO. Plots as in Figure~\\ref{fig:finalClosure_MSTW}. }\n\\label{fig:finalClosure_NNPDF}\n\\end{figure}\n\\begin{figure}[!]\n\\centering\n\\includegraphics[width=0.45\\textwidth]{7-PostLHC/figs/finalClosure/CT10/gluon.pdf}\n\\includegraphics[width=0.45\\textwidth]{7-PostLHC/figs/finalClosure/CT10/singlet.pdf}\n\\includegraphics[width=0.45\\textwidth]{7-PostLHC/figs/finalClosure/CT10/valence.pdf}\n\\includegraphics[width=0.45\\textwidth]{7-PostLHC/figs/finalClosure/CT10/triplet.pdf}\n\\caption[NNPDF3.0 methodology closure test fit to CT10 NLO]{NNPDF3.0 methodology closure test fit to CT10 NLO. Plots as in Figure~\\ref{fig:finalClosure_MSTW}. }\n\\label{fig:finalClosure_CT10}\n\\end{figure}\n\n\\subsection{Improvements in data fits for NNPDF3.0}\nWhile we have now validated much of the methodology to be used in the NNPDF3.0 determination, we shall now finally investigate some of the expected differences arising with respect to the NNPDF2.3 results in the case of a fit to experimental data. In order to directly assess the changes arising purely from the methodological differences in the two approaches, we shall perform two fits to a small common dataset, one with the full NNPDF2.3 machinery and the second with the improvements implemented in the NNPDF3.0 procedure. It should be noted that these results are of an extremely preliminary nature and as so should only be taken as roughly indicative of the final results. Furthermore, the full NNPDF3.0 set will benefit from a considerably expanded dataset with respect to the NNPDF2.3 determination. \n\nFor these test fits, we use a collider-only dataset to ensure a maximally consistent set of experimental data, including the full NNPDF2.3 LHC and Tevatron datasets, and the HERA-1 combined DIS results. Once more, the fits were run with a maximum number of generations of $N_{\\text{gen}} = 30,000$. The NNPDF2.3-like fit was otherwise performed according to the settings of the central NNPDF2.3 fit. The NNPDF3.0 fits were performed with identical settings to the closure test fits described in the previous section. \n\nLooking firstly at the gluon and singlet sectors, in Figure~\\ref{fig:23vs30methodology_1} we see the results of the two methodology test fits compared as a ratio to the NNPDF2.3 methodology fit's central value. The first feature to note is that in the region where data constraints in this test fit are largest, the two methodologies remain very consistent in their results, with the most significant changes occurring in the extrapolation regions and for the large-$x$ singlet. At small-$x$ the NNPDF3.0 methodology fit is more confident in the extrapolation for both singlet and gluon PDFs, resulting in a systematically smaller uncertainty. At large-$x$ there is a moderate shift in the gluon central value in the NNPDF3.0 result, and a broadening of uncertainties. The same pattern can be found in the large-$x$ gluon, where once again uncertainties are slightly larger and there is some change in central value. However both distributions remain in agreement within their uncertainties, validating that the two methodologies remain compatible within the experimental uncertainty present in the test dataset.\n\nTo investigate the impact of the methodological changes to PDFs sensitive to the valence distributions and quark flavour separation, we plot the valence and triplet PDF combinations in Figure~\\ref{fig:23vs30methodology_2}. In the valence PDF comparison, we see a similar pattern as for the singlet and gluon PDFs, where the low-$x$ result from the NNPDF3.0 methodology fit obtained a narrower distribution, and at high-$x$ the uncertainties are systematically larger. The triplet PDF shows by some way the largest differences between the two methodologies, with PDF uncertainties being significantly larger across the whole range of $x$. This effect is largely due to the much more flexible preprocessing used for the triplet PDF, where now there is no requirement that the PDF be preprocessed to zero at low-$x$, the constraint now being entirely based on experimental data. Such a treatment leads to a rather conservative determination of the low-$x$ triplet, however this effect should be at least partially offset by increased data constraints in the full NNPDF3.0 determination.\n\nHere we have seen the two methodologies provide consistent results when applied to the same experimental dataset. However there are significant changes in the fit results due to methodological improvements, particularly important in the PDF extrapolation regions at large and small values of parton-$x$, and for PDF combinations sensitive to light flavour separation. As has been shown in the validation with closure tests, the methodological modifications, particularly in allowing for greater preprocessing flexibility, result in an improved reproduction of a test PDF distribution. The upgraded methodology should therefore provide a more reliable estimate of the parton densities of the proton.\n\n\\clearpage\n\\begin{figure}[!]\n\\centering\n\\includegraphics[width=0.45\\textwidth]{7-PostLHC/figs/30meth/plots/glulog.pdf}\n\\includegraphics[width=0.45\\textwidth]{7-PostLHC/figs/30meth/plots/glulin.pdf}\\\\\n\\includegraphics[width=0.45\\textwidth]{7-PostLHC/figs/30meth/plots/snglog.pdf}\n\\includegraphics[width=0.45\\textwidth]{7-PostLHC/figs/30meth/plots/snglin.pdf}\n\n\\caption[Comparison of NNPDF2.3 and NNPDF3.0 fitting methodologies when applied to a common experimental dataset. Gluon and singlet PDF combinations]{Comparison of NNPDF2.3 and NNPDF3.0 fitting methodologies when applied to a common experimental dataset. Here the gluon (top) and singlet (bottom) PDFs are shown, with all values normalised to the result of the NNPDF2.3 methodology fit.}\n\\label{fig:23vs30methodology_1}\n\\end{figure}\n\n\\begin{figure}[!]\n\\centering\n\\includegraphics[width=0.45\\textwidth]{7-PostLHC/figs/30meth/plots/vallog.pdf}\n\\includegraphics[width=0.45\\textwidth]{7-PostLHC/figs/30meth/plots/vallin.pdf}\\\\\n\\includegraphics[width=0.45\\textwidth]{7-PostLHC/figs/30meth/plots/t3log.pdf}\n\\includegraphics[width=0.45\\textwidth]{7-PostLHC/figs/30meth/plots/t3lin.pdf}\n\n\\caption[Comparison of NNPDF2.3 and NNPDF3.0 fitting methodologies when applied to a common experimental dataset. Valence and triplet PDF combinations]{Comparison of NNPDF2.3 and NNPDF3.0 fitting methodologies when applied to a common experimental dataset, for the valence (top) and triplet (bottom) PDF combinations. Plots as in Figure~\\ref{fig:23vs30methodology_1}.}\n\\label{fig:23vs30methodology_2}\n\\end{figure}", "meta": {"hexsha": "c27a0ebe75479fe6512f6c32cebe5c8ec6133296", "size": 52781, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "7-PostLHC/chapter7.tex", "max_stars_repo_name": "nhartland/thesis", "max_stars_repo_head_hexsha": "a58dc2b3d8b218b3893f4a8f0c1e6bcdcc545c55", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "7-PostLHC/chapter7.tex", "max_issues_repo_name": "nhartland/thesis", "max_issues_repo_head_hexsha": "a58dc2b3d8b218b3893f4a8f0c1e6bcdcc545c55", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "7-PostLHC/chapter7.tex", "max_forks_repo_name": "nhartland/thesis", "max_forks_repo_head_hexsha": "a58dc2b3d8b218b3893f4a8f0c1e6bcdcc545c55", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 138.1701570681, "max_line_length": 1264, "alphanum_fraction": 0.8039446013, "num_tokens": 12734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926666143434, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.31943736059287126}}
{"text": "\\documentclass[12pt, oneside]{article}\n\n\\usepackage{float}\n\\usepackage{lineno}\n\\usepackage{color, amssymb, amsmath, amsthm, verbatim, wasysym}\n\\usepackage{natbib}\n\\usepackage{epsfig}\n\\usepackage[mathscr]{eucal}\n\\usepackage{mathrsfs}\n\\usepackage{appendix}\n\\raggedbottom\n\\usepackage[left=0.8in,right=0.8in,top=0.8in,bottom=0.9in,centering]{geometry}      \n\n% Uncomment to show references.\n%\\usepackage[notcite,notref]{showkeys}\n\n% To make really wide hats that cover everything:\n\\usepackage{scalerel}\n\\usepackage{stackengine}\n\\setstackEOL{\\#}\n\\stackMath\n\\def\\hatgap{1pt}\n\\def\\subdown{-0.2pt}\n\\newcommand\\reallywidehat[2][]{%\n\\renewcommand\\stackalignment{l}%\n\\stackon[\\hatgap]{#2}{%\n\\stretchto{%\n    \\scalerel*[\\widthof{$#2$}]{\\kern-.6pt\\bigwedge\\kern-.6pt}%\n    {\\rule[-\\textheight/2]{1ex}{\\textheight}}%WIDTH-LIMITED BIG WEDGE\n}{0.6ex}% THIS SQUEEZES THE WEDGE TO 0.5ex HEIGHT\n_{\\smash{\\belowbaseline[\\subdown]{\\scriptstyle#1}}}%\n}}\n\n% For a 'strut' that creates space above underbraces\n\\newcommand*\\mystrut[1]{\\vrule width0pt height0pt depth#1\\relax}\n\n% Punctuation\n\\newcommand{\\com}{\\, ,}\n\\newcommand{\\per}{\\, .}\n\n% A nice 'definition'\n\\newcommand{\\defn}{\\ensuremath{\\stackrel{\\mathrm{def}}{=}}}\n\n% Use \\bar to over line solo symbols\n\\newcommand{\\av}[1]{\\left \\langle{#1} \\right \\rangle}\n\\newcommand{\\avbg}[1]{\\overline{#1}}\n\\newcommand{\\avbgg}[1]{\\overline{#1}}\n\\newcommand{\\hav}[1]{\\widehat{#1}}\n\n% Begin and end equations\n\\newcommand{\\beq}{\\begin{equation}}\n\\newcommand{\\eeq}{\\end{equation}}\n\n% Vector calculus operators\n\\newcommand{\\p}{\\partial}\n\\newcommand{\\bnabla}{\\boldsymbol \\nabla}\n\\newcommand{\\pnabla}{\\boldsymbol \\nabla_{\\! \\! \\perp}}\n\\newcommand{\\hnabla}{\\bnabla_{\\! \\! h}}\n\\newcommand{\\bnablad}{\\bnabla_{\\! \\! \\alpha}}\n\\newcommand{\\bcdot}{\\boldsymbol \\cdot}\n\\newcommand{\\hlap}{\\triangle_h}\n\\newcommand{\\lap}{\\triangle}\n\\newcommand{\\grad}{\\bnabla}\n\\newcommand{\\curl}{\\bnabla \\!\\times\\!}\n\\newcommand{\\diver}{\\bnabla \\bcdot }\n\\newcommand{\\cross}{\\times}\n\n% Bold symbolds\n\\newcommand{\\bu}{\\boldsymbol u}\n\\newcommand{\\buh}{\\boldsymbol u_h}\n\\newcommand{\\bx}{\\boldsymbol x}\n\\newcommand{\\ba}{\\boldsymbol{a}}\n\\newcommand{\\bk}{\\boldsymbol{k}}\n\\newcommand{\\bh}{\\boldsymbol{h}}\n\\newcommand{\\bm}{\\boldsymbol{m}}\n\\newcommand{\\bn}{\\boldsymbol{\\hat n}}\n\\newcommand{\\bxh}{\\hspace{0.1em} \\boldsymbol{\\hat x}}\n\\newcommand{\\byh}{\\hspace{0.1em}\\boldsymbol{\\hat y}}\n\\newcommand{\\bzh}{\\hspace{0.1em}\\boldsymbol{\\hat z}}\n\\newcommand{\\bnh}{\\hspace{0.1em}\\boldsymbol{\\hat n}}\n\\newcommand{\\bomega}{\\boldsymbol \\omega}\n\\newcommand{\\bOmega}{\\boldsymbol \\Omega}\n\\newcommand{\\bxi}{\\ensuremath {\\boldsymbol {\\xi}}}\n\\newcommand{\\bXi}{\\ensuremath {\\boldsymbol {\\Xi}}}\n\\newcommand{\\bU}{\\boldsymbol{U}}\n\\newcommand{\\bX}{\\boldsymbol{X}}\n\n% Greek abbrevs\n\\newcommand{\\ep}{\\epsilon}\n\\newcommand{\\om}{\\omega}\n\\newcommand{\\kap}{\\kappa}\n\n% Roman characters\n\\newcommand{\\ee}{\\mathrm{e}}\n\\newcommand{\\ii}{\\mathrm{i}}\n\\newcommand{\\cc}{\\mathrm{cc}}\n\\newcommand{\\dd}{{\\rm d}}\n\\newcommand{\\id}{{\\, \\rm d}}\n\\newcommand{\\DD}{{\\rm D}}\n\\newcommand{\\J}{\\mathrm{J}}\n\\renewcommand{\\L}{\\mathrm{L}}\n\n% Non-dimensional numbers \n\\newcommand{\\Ri}{Ri}\n\\newcommand{\\Ro}{Ro}\n\\newcommand{\\Bu}{Bu}\n\\newcommand{\\Pe}{Pe}\n\n% Material derivative\n\\newcommand{\\Dt}[1]{\\mathrm{D}_t #1}\n\n% Small in-line fractions\n\\newcommand{\\half}{\\tfrac{1}{2}}\n\n% Bold 'F' for 'forcing'\n\\newcommand{\\bff}{\\boldsymbol{F}}\n\\newcommand{\\fh}{\\breve f}\n\n% Dissipation operator\n\\newcommand{\\friction}{\\mathrm{F}}\n\\newcommand{\\mixing}{\\mathrm{M}}\n\n\\newcommand{\\mode}{\\phi}\n\\newcommand{\\q}{\\tilde q}\n\\newcommand{\\qpsi}{\\tilde \\psi}\n\n\\begin{document}\n\n\\title{\\vspace{-4ex} Quasi-geostrophic flow with tracers}\n\\author{Greg}\n\\date{} \\maketitle \\vspace{-4ex}\n\n\\section{Preliminaries}\n\nMore or less according to Vallis (2006), two-layer quasi-geostrophic flow is governed by the equations\n\\begin{align}\n\\q_{1t} + \\J \\big ( \\qpsi_1, \\q_1 \\big ) &= \\friction \\big ( \\hlap \\qpsi_1 \\big ) \\\\\n\\q_{2t} + \\J \\big ( \\qpsi_2, \\q_2 \\big ) &= -r \\hlap \\qpsi_2 + \\friction  \\big( \\hlap \\qpsi_2 \\big ) \\com \n\\end{align}\nwhere the potential vorticities $Q_i$ are defined by\n\\begin{align}\n\\q_{1} &= \\hlap \\qpsi_1 - F_1 \\big ( \\qpsi_1 - \\qpsi_2 \\big ) + \\beta y \\com \\\\\n\\q_2 &= \\hlap \\qpsi_2 + F_2 \\big ( \\qpsi_1 - \\qpsi_2 \\big ) + \\beta y \\com\n\\end{align}\nand the Burger numbers $F_1$ and $F_2$ are defined by $F_i = f_0^2 / g' H_i$, where $H_i$ is the height of layer $i$ and $g'$ is the reduced gravity. The number of parameters in the problem are reduced if the deformation `radius' $R$ and layer depth ratio $\\delta$ are defined through\n\\beq  \nR^2 \\defn \\frac{g' H_1 H_2}{f_0^2 \\left ( H_1 + H_2 \\right )} \\com \\qquad \\text{and} \\qquad \\delta \\defn \\frac{H_1}{H_2} \\com\n\\eeq\nso that \n\\beq\nF_1 = \\frac{R^{-2}}{1 + \\delta} \\com \\qquad \\text{and} \\qquad F_2 = \\frac{\\delta R^{-2}}{1 + \\delta} \\per\n\\eeq\nWe decompose $\\qpsi_i$ into $\\qpsi_i = - U_i y + \\psi_i$, so that\n\\begin{align}\n\\q_1 &= \\underbrace{\\mystrut{1.4ex}  \\beta y + F_1 \\big ( U_1 - U_2 \\big )y}_{\\defn Q_1} + \\underbrace{\\mystrut{1.4ex} \\hlap \\psi_1 - F_1 ( \\psi_1 - \\psi_2 )}_{\\defn q_1} \\com \\\\\n\\q_2 &= \\underbrace{\\mystrut{1.4ex}  \\beta y - F_2 \\big ( U_1 - U_2 \\big )y}_{\\defn Q_2} + \\underbrace{\\mystrut{1.4ex} \\hlap \\psi_2 + F_2 ( \\psi_1 - \\psi_2 )}_{\\defn q_2} \\com\n\\end{align}\nThe potential vorticity conservation equations become\n\\begin{align}\nq_{1t} + \\J \\left( \\psi_1, q_1 \\right ) + U_1 q_{1x} + \\psi_{1x} Q_{1y} &= \\friction \\left ( \\hlap \\psi_1 \\right) \\com \\\\\n q_{2t} + \\J \\left( \\psi_2, q_2 \\right ) + U_2 q_{2x} + \\psi_{2x} Q_{2y} &= - r \\hlap \\psi_2 + \\friction \\left ( \\hlap \\psi_2 \\right) \\per\n\\end{align}\n\n\\section{Streamfunction inversion}\n\nThe streamfunction-vorticity relationship is usefully expressed in matrix form, \n\\beq\n\\left [ \\, \\begin{matrix}\nq_1 \\\\\nq_2 \\\\\n\\end{matrix} \\, \\right ] = \\underbrace{ \\mystrut{3ex} \\left [ \\,\n\\begin{matrix} \n\\hlap - F_1 & - F_1 \\\\\n- F_2 & \\hlap - F_2 \\\\\n\\end{matrix} \\, \\right ]}_{\\defn \\mathsf{M}} \\left [ \\, \\begin{matrix}\n\\psi_1 \\\\\n\\psi_2 \\\\\n\\end{matrix} \\, \\right ]\n\\eeq\nWhich, in Fourier space, reads\n\\beq\n\\left [ \\, \\begin{matrix}\n\\hat q_1 \\\\\n\\hat q_2 \\\\\n\\end{matrix} \\, \\right ] = - \\left [ \\,\n\\begin{matrix} \nK^2 + F_1 & F_1 \\\\\nF_2 & K^2 + F_2  \\\\\n\\end{matrix} \\, \\right ] \\left [ \\, \\begin{matrix}\n\\hat \\psi_1 \\\\\n\\hat \\psi_2 \\\\\n\\end{matrix} \\, \\right ]\n\\eeq\nNoting that $\\left ( K^2 + F_1 \\right ) \\left ( K^2 + F_2 \\right ) - F_1 F_2 = K^2 \\left ( K^2 + F_1 + F_2 \\right )$, the inversion of $\\mathsf{M}$ in Fourier space yields\n\\beq\n\\mathsf{M}^{-1} = \\frac{1}{K^2 \\left ( K^2 + F_1 + F_2 \\right )} \\left [ \\,\n\\begin{matrix}\n- \\left ( K^2 + F_2 \\right ) & F_1 \\\\\nF_2 & - \\left (K^2 + F_1\\right ) \\\\\n\\end{matrix} \\, \\right ] \\per\n\\eeq\n\n\\section{Two-layer tracers}\n\nThe two-layer tracer equations are\n\\begin{align}\nc_{1t} + \\J \\left ( \\psi_1, c_1 \\right ) + U_1 c_{1x} &= - \\kappa \\left ( c_1 - c_2 \\right ) + \\mixing c_1 \\com \\\\\nc_{2t} + \\J \\left ( \\psi_2, c_2 \\right ) + U_2 c_{2x} &=  \\kappa \\left ( c_1 - c_2 \\right ) + \\mixing c_2 \n\\end{align}\n\n\\section{Numerics}\n\nWhen we compute the right hand side, we either dealias or use an exponential filter of the form\n\\beq\n\\mathscr{F} = \\exp \\Big \\{ - d \\left [ \\left ( k / k_c \\right )^2 + \\left ( \\ell / \\ell_c \\right )^2 - 1 \\right ]^{n/2} \\Big \\} \\per\n\\eeq\n\n\\bibliographystyle{jfm}\n\\bibliography{refs}\n\n\\end{document}", "meta": {"hexsha": "98fa6a28c8b63d89cea21d2c0d89d8e154ac6b74", "size": 7305, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/quasigeostrophicTracers/quasigeostrophicTracers.tex", "max_stars_repo_name": "glwagner/doublyPeriodicModels", "max_stars_repo_head_hexsha": "69f4e4bc338f9a60ee3b6d0760605d4ed3281fe8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-03T12:07:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-03T12:07:15.000Z", "max_issues_repo_path": "docs/quasigeostrophicTracers/quasigeostrophicTracers.tex", "max_issues_repo_name": "glwagner/doublyPeriodicModels", "max_issues_repo_head_hexsha": "69f4e4bc338f9a60ee3b6d0760605d4ed3281fe8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/quasigeostrophicTracers/quasigeostrophicTracers.tex", "max_forks_repo_name": "glwagner/doublyPeriodicModels", "max_forks_repo_head_hexsha": "69f4e4bc338f9a60ee3b6d0760605d4ed3281fe8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-05-13T01:40:00.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-13T01:40:00.000Z", "avg_line_length": 33.0542986425, "max_line_length": 284, "alphanum_fraction": 0.6603696099, "num_tokens": 2927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3194373528372637}}
{"text": "% !TEX root=../presentation_1.tex\n\\section{Method}\n\n\\begin{frame}\n\\frametitle{A Simple Deterministic Algorithm [Elk17]}\n\\begin{itemize}\n    \\item Idea: use better BFS broadcasting structure.\n    \\item Like \\textbf{GHS}, still merging components, but now use an auxillary BFS tree to coordinate - $O(D)$.\n    \\item Suppose we have an $(n/k,O(k))$-MST forest $\\mathcal{F}$ using GHS. \n    \\item At most $n/k$ fragments, diameter $O(k)$.\n    \\item $O(k \\log^*n)$ rounds with $O(m + k \\log n)$ messages.\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}\n\\frametitle{A Simple Deterministic Algorithm [Elk17]}\n\\begin{itemize}\n    \\item Build an auxillary BFS tree $\\tau$.\n    \\item $O(D)$ time and $O(m)$ messages.\n    \\item Each node compute the BFS interval.\n    \\begin{itemize}\n        \\item One convergecast to count the number of leaves under each node.\n        \\item One broadcast to assign interval.\n        \\item $O(D)$ time and $O(n)$ messages.\n    \\end{itemize}\n    \\item Interval is computed so that we know how to route messages from the root to any base fragment F\n\\end{itemize}\n\\begin{figure}\n\\centering\n\\includegraphics[width=0.4\\textwidth,trim={0cm 5cm 12cm 0},clip]{figures/bfstree.pdf}\n\\includegraphics[width=0.4\\textwidth,trim={0cm 10cm 20cm 0},clip]{figures/interval.pdf}\n\\end{figure}\n\\end{frame}\n\n\\begin{frame}\n\\frametitle{A Simple Deterministic Algorithm [Elk17]}\n\\begin{itemize}\n    \\item Finally conduct a pipelined convergecast and the root learns the intervals of all the base fragments. Sends messages of the maximum interval of each fragment.\n    \\item Takes $O(D+\\frac{n}{k})$ and $O(D \\cdot \\frac{n}{k})$ messages. (Need to aggregate messages of one fragment at a time.)\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}\n\\frametitle{A Simple Deterministic Algorithm [Elk17]}\n\\begin{itemize}\n    \\item To send the fragment ID: $O(1)$ rounds and $O(m)$ messages.\n    \\item To convergecast the $\\frac{n}{k}$ fragment IDs: $O(D+\\frac{n}{k})$ rounds and $O(D \\cdot\\frac{n}{k})$ messages.\n    \\item Assume each vertex knows its fragment ID, and also the fragments IDs of its neighbors\n    \\item We can compute MWOE locally, and send to the root of the fragment\n    \\item Now suppose $D \\le \\sqrt{n}$, and we select $k=\\sqrt{n}$.\n    \\item $O(k)=O(\\sqrt{n})$ rounds and $O(n)$ messages.\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}\n\\frametitle{A Simple Deterministic Algorithm [Elk17]}\n\\begin{itemize}\n    \\item Perform a \\textbf{pipelined convergecast} to the root, send MWOE of each component.\n    \\item $O(D+\\frac{n}{k})$ rounds and $O(D \\cdot \\frac{n}{k})$ messages.\n    \\item Then the root tells each fragment which one to merge with.\n    \\item Sends message $<F,F'>$ through pipelined broadcast, to tell $F$ to merge with $F'$.\n    \\item The node that receives merge message, changes the fragment ID.\n    \\item $O(D+\\frac{n}{k})$ rounds and $O(D \\cdot \\frac{n}{k})$ messages.\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}\n\\frametitle{A Simple Deterministic Algorithm [Elk17]}\n\\begin{itemize}\n    \\item Finally, every vertex notifies its neighbors about the change in fragment ID. \n    \\item $O(1)$ rounds and $O(m)$ messages.\n    \\item Round: $O(D+\\frac{n}{k}) + O(k\\log^* n) + O((D + k + \\frac{n}{k})\\log n) = O(\\sqrt{n}\\log n)$.\n    \\item Message: $O(E \\log n + n\\log n \\cdot \\log^* n)$\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}\n\\frametitle{A Simple Deterministic Algorithm [Elk17]}\n\\begin{itemize}\n    \\item If $D > \\sqrt{n}$, then let $k=D$.\n    \\item $O(D+\\frac{n}{k}) + O(k\\log^* n) + O((D + k + \\frac{n}{k})\\log n) = O(D\\log n)$ rounds\n    \\item The number of messages is the same as before.\n    \\item Round: $O((D + \\sqrt{n})\\log n)$\n    \\item Message: $O(E \\log n + n\\log n \\cdot \\log^* n)$\n\\end{itemize}\n\\end{frame}\n\n\n\\begin{frame}\n\\frametitle{Conclusion}\n\\begin{itemize}\n    \\item Near optimal time and message complexities.\n    \\item A fully deterministic algorithm.\n\\end{itemize}\n\n\\input{sections/table}\n\\end{frame}\n", "meta": {"hexsha": "93b90a1bb856e1977963860b3f031fa8a94e4a85", "size": 3924, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "sections/method.tex", "max_stars_repo_name": "renmengye/dist-mst-talk", "max_stars_repo_head_hexsha": "25f6a36c4cae5688fe7fa7965d4945e07f4b2909", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sections/method.tex", "max_issues_repo_name": "renmengye/dist-mst-talk", "max_issues_repo_head_hexsha": "25f6a36c4cae5688fe7fa7965d4945e07f4b2909", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sections/method.tex", "max_forks_repo_name": "renmengye/dist-mst-talk", "max_forks_repo_head_hexsha": "25f6a36c4cae5688fe7fa7965d4945e07f4b2909", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0408163265, "max_line_length": 168, "alphanum_fraction": 0.6773700306, "num_tokens": 1235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665855647394, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.31943734508165617}}
{"text": "\\chapter{Discussion and Conclusions}\\label{ch:discussion}\n\n\\lang is neither perfect nor complete:\nthe nature of the syntactic model requires that inductives live in a universe\nhigher than that in which their corresponding unsized types would live,\nand it's missing features such as an infinite size and coinductives.\nIn this chapter, I discuss some of these shortcomings\nand give some possible directions for future work based on them.\n\n\\section{The Infinite Size} \\label{sec:infinity}\n\nIn prior sized type systems, the infinite size\\index{infinite size} $\\infty$ is applied to sized inductive types\nto represent a ``full'' inductive type encompassing that inductive at all sizes,\nwhich essentially corresponds to the usual unsized inductive.\nWhereas an inductive of some size $s$ can be thought of as the type of elements\nwith at most $s$ many layers of constructors,\nthe full inductive can be thought of as the type of elements with any number of layers of constructors.\n\nThe infinite size is characterized by its subsizing behaviour:\n$\\subsize*{s}{\\infty}$ holds for \\emph{any} $s$.\nThis includes its own successor, \\ie $\\subsize*{\\sss{\\infty}}{\\infty}$,\nleading to non--well-founded sequences of strictly ``decreasing'' sizes:\n$\\dots < \\infty < \\infty < \\infty$.\nNaturally, there's no way to model the infinite size as an element of $\\SizeT$\ngiven that I've shown that $\\SizeT$s \\emph{are} well founded.\nIf there were, then it'd be possible to prove an inconsistency.\nLet $\\inftyT$ be the translation of $\\infty$,\nand let $\\inftyltinfty$ be the translation of $\\subsize*{\\sss{\\infty}}{\\infty}$.\n\\begin{align*}\n&\\LetT{\\tg{{\\neg}wf\\inftyT}}{\\arrT*{\\app{\\AccT}{\\inftyT}}{\\botT}}{\\funT{\\mathit{acc}}{\\app{\\AccT}{\\inftyT}}{\\matchT*{\\mathit{acc}}{\\app{\\accT}{p} \\RightarrowT \\app{p}{\\inftyT}{\\inftyltinfty}}}} \\\\\n&\\LetT{\\tg{false}}{\\botT}{\\app{\\tg{{\\neg}wf\\inftyT}}{(\\app{\\accessible}{\\inftyT})}}\n\\end{align*}\n\nIn set-theoretic models of sized type systems with an infinite size,\nsizes are modelled as set-theoretic (transfinite) ordinals,\nthe infinite size isn't modelled as a single ordinal;\ninstead, for each use of the infinite size,\nits set-theoretic interpretation is an ordinal that is ``large enough'' in that context.\nFor instance, the interpretation of the infinite size of $\\N{\\infty}$\nis the first limit ordinal $\\omega$.\n\nThis strategy doesn't adapt well to \\lang with its size abstractions and syntactic model\\index{syntactic model},\nsince it requires a non-local translation of sizes.\nFor instance, given the size application $\\App{e}{\\infty}$,\nwhat $\\infty$ translates to would hypothetically depend on what $e$ translates to,\nand likely require further static analysis of $\\compile{e}$ beyond a simple translation\nover typing derivations.\n\nSince the motivation for having the infinite size is specifically for representing full inductives,\none alternative could be to define the full inductive separately\nand provide functions to and from the corresponding sized inductive,\nsuch as the following for $\\W*$.\n\\begin{align*}\n& \\data{\\App{\\app{\\W*}{(\\annot{A}{\\Type{i}})}{(\\annot{B}{\\arr*{A}{\\Type{i}}})}}{\\infty}}{\\Type{i+1}} \\\\\n& \\quad \\annot{\\constr{sup\\infty}}{\\arr{x}{A}{\\arr*{(\\arr*{\\app{B}{x}}{\\app{\\App{\\W*}{\\infty}}{A}{B}})}{\\App{\\app{\\W*}{A}{B}}{\\infty}}}}\n\\end{align*}\n\nDefining a function from $\\W{x}{A}{B}{s}$ to $\\W{x}{A}{B}{\\infty}$ is trivial,\nsince we're discarding size information.\nWhat about going from $\\W{x}{A}{B}{\\infty}$ to $\\W{x}{A}{B}{s}$?\nWhat should $s$ be?\nThe size algebra could be augmented to be able to represent transfinite ordinals\nso that $s$ is again a size that is ``large enough'',\nbut we can hardly expect programmers to manipulate ordinals,\nand I conjecture that we would lose any hope of deciding $\\subsize*{}{}$\nwithout any user intervention.\n\nThe key insight is that what's important about an element of a full inductive\nisn't its precise size and depth of constructors,\nbut merely that it has \\emph{some} unknown size.\nAnother alternative to the infinite size, then, could be to represent a full inductive\nas an existentially-quantified sized inductive,\n\\ie $\\Pairtype{\\alpha}{\\N{\\alpha}}$ and $\\Pairtype{\\alpha}{\\W{x}{A}{B}{\\alpha}}$.\nWe've already seen existential sizes in action: they're in the return types of $\\qsort$ and $\\msort$.\n\nThere is still a limitation similar to that in \\cref{sec:examples:limitations}\nwhen trying to represent the constructors of full inductives.\nFor $\\Pairtype{\\alpha}{\\W{x}{A}{B}{\\alpha}}$, we need a ``constructor'' of the following type.\n\\begin{align*}\n\\annot{\\const{sup'}}{\\arr{x}{A}{\\arr*{(\\arr*{B}{\\Pairtype{\\alpha}{\\W{x}{A}{B}{\\alpha}}})}{\\Pairtype{\\alpha}{\\W{x}{A}{B}{\\alpha}}}}}\n\\end{align*}\nAll we need is a function\n$$\\annot{\\const{ac}}{\\arr{x}{A}{\\arr*{(\\arr*{B}{\\Pairtype{\\alpha}{\\W{x}{A}{B}{\\alpha}}})}{\\Pairtype{\\alpha}{(\\arr*{B}{\\W{x}{A}{B}{\\alpha}})}}}}$$\nand we're good to go.\n\\begin{align*}\n\\app{\\const{sup'}}{x}{f} =\n\\unpair*{\\alpha}{f'}{\\app{\\const{ac}}{x}{f}}{\\Pair{\\sss{\\alpha}}{\\sup{x}{A}{B}{\\sss{\\alpha}}{\\alpha}{x}{f'}}}\n\\end{align*}\n\nUnfortunately, as the name might suggest,\n$\\const{ac}$ is an instance of the axiom of choice\\punctstack{,}%\n\\footnote{The ``choice'' made here is the existentially-quantified size in the consequent:\nthe axiom asserts that there's always a way to choose a size such that\nall of the well-founded trees returned have that size.}\nwhich for weak existentials\\index{weak dependent pair} (whose elements we can't project out)\nis nonconstructive,\nso there's no hope of implementing $\\const{ac}$.\nHowever, if we take weak existentials as a primitive of \\lang\nrather than being defined as an encoding,\nand model them by strong dependent pairs in \\CICE,\nthen the translation of $\\const{ac}$ \\emph{can} be implemented as a function,\nalso making use of the limit operator.\nIn other words, the syntactic model\\index{syntactic model} justifies the axiom $\\const{ac}$ in the source.\nThe mechanization of $\\compile{\\const{ac}}$ in Agda and Coq are given in\n\\cref{app:mechanization:agda:W} and \\cref{app:mechanization:coq:W}, respectively.\n\nNevertheless, $\\const{ac}$ remains a noncomputing axiom\nunless the size algebra is augmented to include a limit operator\nand size expressions consequently treated as regular terms.\nThere is no way to represent generalized full inductives as\nsized inductives existentially quantified by sizes\nand faithfully define their constructors without losing either\ndecidability of subsizing from exposing the underlying ordinal representation of sizes,\nor canonicity from the inclusion of a noncomputing axiom.\nRepresenting ordinary full inductives (namely naturals) this way,\nhowever, has been previously explored~\\citep{guarded, modal-sizes}.\n\n\\section{Universe Levels of Inductives} \\label{sec:universe-levels}\n\nThe universes in which the type of natural numbers and W types in \\lang live\nare, in a sense, one level\\index{universe level} higher than is usually expected;\ntheir typing rules are reproduced below.\n$\\N*$ is typically in $\\Type{0}$,\nwhile $\\W*$ is typically in $U$ rather than $\\axioms{U}$.\n\\begin{mathpar}\n\\inferrule[\\rref*{nat}]{\n  \\wf{\\Phi}{\\Gamma} \\\\\n  \\wf{\\Phi}{s}\n}{\n  \\infer{\\Phi; \\Gamma}{\\N{s}}{\\Type{1}}\n}\n\\and\n\\inferrule[\\rref*{wft}]{\n  \\wf{\\Phi}{s} \\\\\n  \\infer{\\Phi; \\Gamma}{\\sigma}{U} \\\\\\\\\n  \\infer{\\Phi; \\Gamma, \\annot{x}{\\sigma}}{\\tau}{U}\n}{\n  \\infer{\\Phi; \\Gamma}{\\W{x}{\\sigma}{\\tau}{s}}{\\axioms{U}}\n}\n\\end{mathpar}\n\nThis is due to how the translation is defined:\n$\\NatT$ and $\\WT$ have a $\\SizeT$ as parameter,\nthe $\\limT$ operator quantifies over the type of the domain of its function argument,\nand that type must be ``large'' enough to accommodate the correct type.\nFor $\\app{\\WT}{\\sigmaT}{\\tauT}{\\sT}$,\nthe domain is $\\app{\\tauT}{\\aT}$ for some $\\aT$\\punctstack{,}%\n\\footnote{For generalized inductives, given a recursive argument in the form of a function,\nthe domain of $\\limT$ should encompass the domain of that function.}\nas is the case for the definition of $\\compile{\\const{ac}}$,\nso if its universe is $\\TypeT{\\iT}$,\nthen the universe of the type of $\\sT$ must be $\\TypeT{\\tg{i+1}}$,\naccording to the definition of $\\SizeT$, reproduced below.\n\n\\begin{align*}\n&\\dataT{\\SizeT}{\\TypeT{\\tg{i+1}}} \\\\\n&\\quad \\annotT{\\sucT}{\\arrT*{\\SizeT}{\\SizeT}} \\\\\n&\\quad \\annotT{\\limT}{\\funtypeT{A}{\\TypeT{\\iT}}{\\arrT*{(\\arrT*{A}{\\SizeT})}{\\SizeT}}}\n\\end{align*}\n\nThis is a nonnegotiable condition:\ndefining $\\SizeT$ to be in the same universe as that which $\\limT$ quantifies over\nleads to $\\szltT$ no longer being well founded,\nsince in this hypothetical scenario $\\SizeT$ itself could be applied to $\\limT$\nto define an $\\inftyT$ size.\n\\begin{align*}\n&\\LetT{\\inftyT}{\\SizeT}{\\app{\\limT}{\\SizeT}{(\\funT{\\xT}{\\SizeT}{\\xT})}} \\\\\n&\\LetT{\\inftyltinfty}{\\inftyT \\szltT \\inftyT}{\\app{\\coconeT}{\\SizeT}{(\\app{\\sucT}{\\inftyT})}{(\\funT{\\xT}{\\SizeT}{\\xT})}{(\\app{\\sucT}{\\inftyT})}{(\\app{\\reflleq}{(\\app{\\sucT}{\\inftyT})})}}\n\\end{align*}\n\nOne way to ``shrink'' the universe of $\\SizeT$, so to speak,\ncould be to parametrize it over the type over which $\\limT$ currently quantifies over,\nyielding the following inductive definition.\n\\begin{align*}\n&\\dataT{\\app{\\SizeT}{(\\annotT{A}{\\TypeT{\\iT}})}}{\\TypeT{\\iT}} \\\\\n&\\quad \\annotT{\\sucT}{\\arrT*{\\SizeT}{\\SizeT}} \\\\\n&\\quad \\annotT{\\limT}{\\arrT*{(\\arrT*{A}{\\SizeT})}{\\SizeT}}\n\\end{align*}\n\nThe problem with this alternative is that for $\\app{\\WT}{\\sigmaT}{\\tauT}$,\nthe parameter of its size parameter would be $\\app{\\tauT}{\\aT}$,\nwhere $\\annotT{\\aT}{\\sigmaT}$ is the third formal argument to its constructor $\\supT$,\nbut this argument is only part of the constructor, not the type.\nThe intuition is that the parametrized $\\SizeT$ is too restrictive\nand there aren't ``enough'' sizes to cover all well-founded trees of any particular type.\n\nIn a sense, it's reasonable to expect that $\\SizeT$ needs to live in a larger universe.\nThe r\\^ole of $\\SizeT$ is to represent all of the possible sizes of a given full inductive,\nso we would expect $\\SizeT$ to be just as large as the inductive itself.\nAside from situations where the inductive is impredicative\\index{impredicativity}, \\ie in $\\PropT$,\nparametrizing over $\\SizeT$ then necessarily requires moving up a universe\nso that it's not essentially quantifying over itself.\n\nIf having inductive types in the correct universe were more important than\nthe potential expressibility of infinitude,\nwe could eliminate $\\limT$ altogether and model sizes as ordinary naturals.\nThen $\\SizeT$ would live in $\\Type{0}$, $\\NatT$ and $\\WT$ would live in the correct universes,\nas well as $\\N*$ and $\\W*$.\nAlthough this would affect the judgements of both \\lang and \\CICE,\nthis wouldn't affect the proofs, since the changes are the same for both languages.\nHowever, this does mean giving up $\\const{ac}$\nand likely any hope of defining any infinitary constructs like $\\const{\\omega}$\nwhen using this model.\n\n\\section{Streams and Coinductives}\n\nDual to inductive types, coinductive types allow for constructing\npotentially infinitely large elements in a principled manner,\nand are present in many proof assistants such as Coq, Agda, and Idris.\nConventionally, while fixpoints are guarded by destructors\\index{guardedness}\nand destruct elements of inductives by recurring only on syntactically smaller elements,\ncofixpoints are guarded by constructors and occur only as a syntactic argument to a constructor~\\citep{guard}.\nSince coinductives aren't present in pCIC\\index{Calculus of Inductive Constructions!Predicative \\textasciitilde},\nupon which \\CICE is based, I don't include them in \\lang either,\nas they would lack a translation in the syntactic model.\nNevertheless, we can speculate on how they might appear and interact with sizes.\nHere, I define the classic example of coinductive streams,\ncomposed of a head element and a tail stream.\n\\begin{mathpar}\n\\inferrule[\\rlabel*{stream}]{\n  \\wf{\\Phi}{s} \\\\\n  \\infer{\\Phi; \\Gamma}{\\tau}{U}\n}{\n  \\infer{\\Phi; \\Gamma}{\\Stream{\\tau}{s}}{U}\n}\n\\and\n\\inferrule[\\rlabel*{hd}]{\n  \\infer{\\Phi; \\Gamma}{e}{\\Stream{\\tau}{s}}\n}{\n  \\infer{\\Phi; \\Gamma}{\\shd{e}}{\\tau}\n}\n\\and\n\\inferrule[\\rlabel*{tl}]{\n  \\infer{\\Phi; \\Gamma}{e}{\\Stream{\\tau}{s}}\n}{\n  \\infer{\\Phi; \\Gamma}{\\stl{e}}{\\Funtype<{\\alpha}{s}{\\Stream{\\tau}{\\alpha}}}\n}\n\\and\n\\inferrule[\\rlabel*{scons}]{\n  \\infer{\\Phi; \\Gamma}{e_1}{\\tau} \\\\\n  \\infer{\\Phi, \\bound{\\alpha}{s}; \\Gamma}{e_2}{\\Stream{\\tau}{\\alpha}}\n}{\n  \\infer{\\Phi; \\Gamma}{\\scons{\\alpha}{s}{e_1}{\\alpha}{s}{e_2}}{\\Stream{\\tau}{s}}\n}\n\\and\n\\inferrule[\\rlabel*{cofix}]{\n  \\infer{\\Phi, \\alpha; \\Gamma}{\\sigma}{U} \\\\\n  \\fresh{\\beta} \\\\\n  \\check{\\Phi, \\alpha; \\Gamma, \\annot{f}{\\Funtype<{\\beta}{\\alpha}{\\subst{\\sigma}{\\alpha}{\\beta}}}}{e}{\\sigma}\n}{\n  \\infer{\\Phi; \\Gamma}{\\cofix{f}{\\alpha}{\\sigma}{e}}{\\Funtype{\\alpha}{\\sigma}}\n}\n\\end{mathpar}\n\nJust as the size of an inductive informally indicates at most how many layers of constructors its elements contain,\nthe size of a coinductive informally indicates \\emph{at least} how many layers,\nand in the case of $\\app{\\Stream*}{A}$, at least how many elements of $A$ it contains.\nOf course, streams may contain an infinite number of elements,\nso the analogy works better in the relative sense:\nif a stream contains at least $s$ elements,\nthen its tail must contain at least $\\bound{\\alpha}{s}$, strictly fewer, elements.\nThe reduction rules of streams, omitted here, operate as expected:\n$\\shd{}$ projects out the head and $\\stl{}$ projects out the tail.\n\nTo actually construct infinite streams, we need cofixpoint expressions.\nThe natural correspondence of guardedness\\index{guardedness} in sized types\nis that cofixpoint bodies must construct coinductives larger than\ntheir own occurrences inside the body,\nwhich coincides with the structure of \\rref{fix}.\nCofixpoints also reduce when applied to a size that has some subsize,\njust like fixpoints.\nInterestingly, this suggests that cofixpoints might also be translated in the syntactic model\nto well-founded induction\\index{well-founded induction} on sizes despite constructing a coinductive type.\n\n\\clearpage % TODO: clearpage\nWith cofixpoints, we can then construct an infinite stream of some single element.\nLet $A$ in the definitions to follow be some type.\n\\begin{align*}\n& \\Let{\\dup}{\\arr*{A}{\\Funtype{\\alpha}{\\Stream{A}{\\alpha}}}}{\\\\\n& \\quad \\fun{a}{A}{\\cofix{\\dup*}{\\alpha}{\\Stream{A}{\\alpha}}{\\\\\n& \\qquad \\scons{\\beta}{\\alpha}{a}{\\beta}{\\alpha}{\\App{\\dup*}{\\beta}}}}}\n\\end{align*}\n\nNotice that the stream produced has \\emph{any} size,\nwhich can be interpreted as having ``at least'' any number of elements---a\ntruly infinite stream.\nMore generally, a coinductive universally quantified by size corresponds to a full coinductive,\ndual to a inductive existentially quantified by a size corresponding to a full inductive.\n\nWe can manipulate sized streams as expected,\nsuch as taking only the odd elements of a stream\nor interleaving two streams by alternation.\n\\begin{align*}\n& \\Let{\\odds}{\\Funtype{\\alpha}{\\arr*{(\\Funtype{\\beta}{\\Stream{A}{\\beta}})}{\\Stream{A}{\\alpha}}}}{ \\\\\n& \\quad \\cofix{\\odds*}{\\alpha}{\\arr*{(\\Funtype{\\beta}{\\Stream{A}{\\beta}})}{\\Stream{A}{\\alpha}}}{ \\\\\n& \\qquad \\fun{s}{\\Funtype{\\beta}{\\Stream{A}{\\beta}}}{\\scons{\\beta}{\\alpha}{\\shd{(\\App{s}{\\alpha})}}{\\beta}{\\alpha}{\\app{\\App{\\odds*}{\\beta}}{(\\Fun{\\gamma}{\\App{\\stl{(\\App{\\stl{(\\App{s}{\\sss{\\sss{\\gamma}}})}}{\\sss{\\gamma}})}}{\\gamma}})}}}}} \\\\\n\\hfill \\\\\n& \\Let{\\interleave}{\\Funtype{\\alpha}{\\arr*{\\Stream{A}{\\alpha}}{\\Stream{A}{\\alpha}}{\\Stream{A}{\\alpha}}}}{ \\\\\n& \\quad \\cofix{\\interleave*}{\\alpha}{\\arr*{\\Stream{A}{\\alpha}}{\\Stream{A}{\\alpha}}{\\Stream{A}{\\alpha}}}{ \\\\\n& \\qquad \\fun{s_1}{\\Stream{A}{\\alpha}}{\\fun{s_2}{\\Stream{A}{\\alpha}}{\\scons{\\beta}{\\alpha}{\\shd{s_1}}{\\beta}{\\alpha}{ \\\\\n& \\qquad \\quad \\scons{\\gamma}{\\beta}{\\shd{s_2}}{\\gamma}{\\beta}{\\app{\\App{\\interleave*}{\\alpha}}{(\\App{\\stl{s_1}}{\\gamma})}{(\\App{\\stl{s_2}}{\\gamma})}}}}}}}\n\\end{align*}\n\nJust as with lists, we can write size-preserving functions on streams\nand use them to define cofixpoints that would otherwise not pass syntactic guard checking.\nOne common example from Haskell is defining a stream of Fibonacci numbers using,\nin our case, a size-preserving zipping function.\nSuppose we have a function $\\annot{f}{\\arr*{A}{A}{A}}$ and some element $\\annot{a}{A}$.\n(For the actual Fibonacci numbers, $A$ would be the naturals, $f$ would be addition, and $a$ would be 1.)\n\\begin{align*}\n& \\Let{\\zip}{\\Funtype{\\alpha}{\\arr*{\\Stream{A}{\\alpha}}{\\Stream{A}{\\alpha}}{\\Stream{A}{\\alpha}}}}{ \\\\\n& \\quad \\cofix{\\zip*}{\\alpha}{\\arr*{\\Stream{A}{\\alpha}}{\\Stream{A}{\\alpha}}{\\Stream{A}{\\alpha}}}{ \\\\\n& \\qquad \\fun{s_1}{\\Stream{A}{\\alpha}}{\\fun{s_2}{\\Stream{A}{\\alpha}}{ \\\\\n& \\qquad \\quad \\scons{\\beta}{\\alpha}{\\app{f}{\\shd{s_1}}{\\shd{s_2}}}{\\beta}{\\alpha}{\\app{\\App{\\zip*}{\\beta}}{(\\App{\\stl{s_1}}{\\beta})}{(\\App{\\stl{s_2}}{\\beta})}}}}}}\n\\end{align*}\n\n\\begin{align*}\n& \\Let{\\fibs}{\\Funtype{\\alpha}{\\Stream{A}{\\alpha}}}{ \\\\\n& \\quad \\cofix{\\fibs*}{\\alpha}{\\Stream{A}{\\alpha}}{ \\\\\n& \\qquad \\scons{\\beta}{\\alpha}{a}{\\beta}{\\alpha}{\\scons{\\gamma}{\\beta}{a}{\\gamma}{\\beta}{\\app{\\App{\\zip}{\\gamma}}{(\\App{\\fibs*}{\\gamma})}{(\\App{\\stl{(\\App{\\fibs*}{\\beta})}}{\\gamma})}}}}}\n\\end{align*}\n\nCoinductive types in general can be implemented as record definitions\njust as inductive types can be implemented as data definitions.\nHowever, sized coinductives in Agda's standard library are implemented\nin terms of a single coinductive $\\Thunk{F}{s}$ record%\n\\footnote{See \\textsf{Codata.Sized.Thunk} from the Agda standard library, URL \\url{https://agda.github.io/agda-stdlib/Codata.Sized.Thunk.html}.}\nwith sized parameter $F$ and size $s$,\nand all other coinductives are implemented as nested inductives,\nwhere occurrences of the type in its constructors' types are wrapped around a $\\Thunk*$.\n\\begin{mathpar}\n\\inferrule[\\rlabel*{thunk}]{\n  \\wf{\\Phi}{s} \\\\\n  \\infer{\\Phi; \\Gamma}{F}{\\Funtype{\\alpha}{U}}\n}{\n  \\infer{\\Phi; \\Gamma}{\\Thunk{F}{s}}{U}\n}\n\\and\n\\inferrule[\\rlabel*{force}]{\n  \\infer{\\Phi; \\Gamma}{e}{\\Thunk{F}{s}}\n}{\n  \\infer{\\Phi; \\Gamma}{\\force{e}}{\\Funtype<{\\alpha}{s}{\\App{F}{\\alpha}}}\n}\n\\and\n\\inferrule[\\rlabel*{think}]{\n  \\infer{\\Phi, \\bound{\\alpha}{s}; \\Gamma}{e}{\\App{F}{\\alpha}}\n}{\n  \\infer{\\Phi; \\Gamma}{\\thunk{\\alpha}{s}{e}}{\\Thunk{F}{s}}\n}\n\\end{mathpar}\n\nThis alternate technique is equally expressive,\nsince it allows encoding M types, the dual of W types, not just streams.\n\\begin{align*}\n& \\data{\\Stream{(\\annot{A}{\\Type{i}})}{\\alpha}}{\\Type{i+1}} \\\\\n& \\quad \\annot{\\scons*}{\\arr*{A}{\\Thunk{(\\app{\\Stream*}{A})}{\\alpha}}{\\Stream{A}{\\alpha}}} \\\\\n\\hfill \\\\\n& \\data{\\App{\\app{\\M*}{(\\annot{A}{\\Type{i}})}{(\\annot{B}{\\arr*{A}{\\Type{i}}})}}{\\alpha}}{\\Type{i+1}} \\\\\n& \\quad \\annot{\\inf*}{\\arr{a}{A}{\\arr*{(\\arr*{\\app{B}{a}}{\\Thunk{(\\app{\\M*}{A}{B})}{\\alpha}})}{\\App{\\app{\\M*}{A}{B}}{\\alpha}}}}\n\\end{align*}\n\n\\section{Designing for Syntactic Modelling}\n\nChoosing to use a syntactic model imposes some constraints on the design\nof the source and target languages, as well as on the proof architecture.\nMost notably, proof of correctness of syntactic models proceed\nby induction on the source derivations,\nso \\lang uses untyped conversion to avoid a dependency between typing and definitional equality,\nwhich would otherwise require a large and complex mutually inductive proof of type preservation.\n\n\\iffalse\nStrictly speaking, such a proof would still be possible,\nsince the compositionality lemmas are merely up to syntactic equality.\nIf they were instead up to typed equivalence\n(as is the case for the translations in \\citet{wjb}),\nthen the base cases would fail:\nto show\n$\\defeq{\\compile{\\Phi}, \\compile{\\Gamma}}{\\yT}{\\yT}{\\compile{\\tau}}$\nvia \\rref{equiv-refl} for instance,\n$\\type{\\compile{\\Phi}, \\compile{\\Gamma}}{\\yT}{\\compile{\\tau}}$\nwould be required,\nbut this can't be constructed even from\n$\\type{\\Phi; \\Gamma}{y}{\\tau}$\nas it's not a premise and therefore the mutual type preservation induction hypothesis can't be applied.\nStill, I use untyped conversion to avoid any other potential complications with the mutual induction.\n\\fi\n\nOn the other hand, induction isn't done on the derivations of the target,\nbut since equality reflection is needed for translation-specific reasons,\n\\CICE uses typed equivalence instead to avoid the inconsistency and loss of subject equivalence\narising from reflecting propositional equality into transitive, untyped conversion,\nas detailed in \\cref{sec:target}.\n\nDue to the incongruity between untyped conversion in the source and typed equivalence in the target,\nthe na\\\"ive proof attempts at preservation using only the relevant source derivation\nand well-typedness of the source terms would be missing crucial typing information\nto construct the target derivations, especially for equivalence.\nThis is why, in all of the preservation lemmas, well-typedness of the translated terms\nare also required as premises, essentially replacing what would've been mutual or circular appeals\nto type preservation with just the right amount of typing information.\n\nQuite unexpectedly, requiring well-typedness of translated terms\nalso has an effect on whether conversion in the source is declarative or algorithmic.\nIf conversion were declarative like \\CICE's equivalence, with no reduction rules or their closures,\nthen transitivity of subtyping would need to be an explicit rule rather than a theorem.\n%\n\\begin{mathpar}\n\\inferrule{\n  \\subtype{\\Phi; \\Gamma}{\\tau_1}{\\tau_2} \\\\\n  \\subtype{\\Phi; \\Gamma}{\\tau_2}{\\tau_3}\n}{\n  \\subtype{\\Phi; \\Gamma}{\\tau_1}{\\tau_3}\n}\n\\end{mathpar}\n%\nRecall that preservation of subtyping states that if $\\subtype{\\Phi; \\Gamma}{\\tau_1}{\\tau_3}$ holds\nand $\\tau_i, \\compile{\\tau_i}$ for $i = 1, 2$ are well typed,\nthen $\\subtype{\\compile{\\Phi}, \\compile{\\Gamma}}{\\compile{\\tau_1}}{\\compile{\\tau_3}}$ holds.\nTo apply the induction hypotheses in the above transitivity case,\nwe would need well-typedness of all of $\\compile{\\tau_1}, \\compile{\\tau_2}, \\compile{\\tau_3}$;\nfor the first and last, they're provided as premises.\nBut where would we derive the well-typedness of $\\compile{\\tau_2}$?\nThere's no ``subject subtyping'' as there is for subject reduction, and indeed,\n$\\subtype{\\mt; \\mt}{\\Type{1}}{\\App{(\\fix{f}{\\alpha}{\\N{\\alpha}}{\\Type{2}})}{\\sss{\\circ}}}$\nholds while the right-hand side, which is convertible to $\\Type{2}$, isn't even well typed.\n\nSo simply by deciding on a syntactic model into an extensional type theory,\ndefinitional equality in the source must be untyped and algorithmic,\nwhile in the target it must be typed,\nlest we create headaches for ourselves with these complex yet avoidable issues.\n\nThese consequences have further effects on the design of the source syntax,\nparticularly concerning type annotations, if we also take into account\nthe other required metatheoretical properties.\nProving subject reduction in the case of $\\delta$-reduction requires that\ndefinitions in the environment have type annotations;\notherwise, even if $\\Gamma = (\\define*{x}{e}), (\\annot{x}{\\tau})$ were well formed,\nwe can't guarantee that $x$ reduces to $e$ of the \\emph{same} type $\\tau$,\nonly that $e$ has \\emph{some} type.\nType-annotated definitions in turn force locally-named expressions\nin $\\kw{let}$ expressions to have annotations as well.\nIn the congruence rule that reduces the body of a $\\kw{let}$ expression,\nthe named expression needs to be added as a definition to the environment,\nbut since reduction is untyped, its type can't be derived:\nit must be provided by the $\\kw{let}$ expression itself.\n\nAlthough not directly related to the type preservation proofs,\nproving confluence requires that the notion of $\\rhd^*$ be\nexactly the reflexive, transitive closure of $\\rhd$,\nso the congruence rules need to be a part of $\\rhd$ and not of $\\rhd^*$.\n\nSome of these constraints are not so serious:\n$\\kw{let}$ expressions without type annotations, for instance,\ncan be easily elaborated into a core calculus with annotations.\nOther constraints require more work to handle:\nalthough a variant of \\lang with typed equivalence would instinctively be equivalent\nto \\lang without, proving that nothing has been broken by the introduction of typed equivalence\nrequires yet another syntactic model, which would have the same mutual induction issues.\nIn other words, a syntactic model constrains us to a particular presentation of the type theory\nand its judgement rules, and changing the presentation (\\eg for implementation in a type checker)\nrequires either more proof work or a certain amount of trust in the correctness of the changes.\n\n\\section{Future Directions}\n\nThere is still a long way to go towards a sized dependent type system\nthat is expressive, consistent, and useable.\nWe've seen from \\cref{sec:examples} that working without an infinite size\nor full inductives is verbose at best, in the case of $\\msort$ and $\\qsort$,\nand impossible at worse, in the case of $\\const{\\omega}$,\nwhile attempts at including them either involve inconsistency, undecidability, or noncanonicity.\nAlternate approaches need to be investigated to circumvent these problems.\n\nWhile the issue with the universe levels of inductive types appears to be cosmetic\nand not affect any important significant metatheoretical properties,\nit might be a mere symptom of a larger issue with how sizes are modelled,\nespecially since prior sized type systems shown to be consistent\nhaven't required any similar restrictions.\nOne possibility is to take inspiration from Agda and\nmake $\\SizeT$ live in a universe $\\SizeUnivT$ independent of $\\TypeT{}$,\nbut the consistency of arbitrarily adding a new universe is questionable,\nespecially when $\\SizeUnivT$ needs to be slightly impredicative:\n$\\arrT*{\\TypeT{}}{\\SizeT}$ would remain in $\\SizeUnivT$\n(as would be the case for $\\limT$)\nand $\\funtypeT{\\alpha}{\\SizeT}{\\N{\\alpha}}$ would remain in $\\TypeT{0}$\n(as would be the case for $\\zeroT$).\n\nThe main barrier to a syntactic model\\index{syntactic model} of \\lang with any coinductive types\nis the lack of an established target type theory with coinductive types\nwith nice properties.\nWhereas pCIC\\index{Calculus of Inductive Constructions!Predicative \\textasciitilde}\nand pCuIC\\index{Predicative Calculus of Cumulative Inductive Constructions} lack them,\nMetaCoq\\index{MetaCoq} mechanizes Coq-style coinductive types,\nbut necessarily cannot prove its own consistency.\nMeanwhile, older CICs with coinductive types and cofixpoints guarded by constructors\\index{guardedness}\n(\\eg \\citet{guard}) have issues with subject reduction~\\citep{coind-SR}\\index{subject reduction},\nwhich is a necessary property for proving type preservation\\index{type preservation} in \\cref{ch:proofs}.\nAnother potential issue is the translation of cofixpoints into applications of\na well-founded induction principle, which is suspicious and also requires further investigation.\n\nFinally, \\lang is missing some important but comparatively simple features\nfrom the perspective of the syntactic model, namely inductive types in general.\nThey can be added directly to \\lang as a generalization of the existing inductives,\nand I conjecture that the type preservation proofs would be a straightforward extension.\nAlternatively, since there already are well-founded trees,\n\\lang could instead be augmented with dependent pairs and an equality type,\nboth of which I also conjecture to be straightforward;\nthen mutual inductives, indexed inductives \\citep{whynotW}, some nested inductives \\citep{barras},\nand even some inductive--inductive types \\citep{ind-ind}\ncan be encoded, along with their induction principles, using W types and propositional equality.\n\n\\hfill\n\nIn terms of metatheory, \\lang is missing proof of two desirable properties:\nstrong normalization and decidability of type checking.\nBecause \\nameref{lem:pres-red} only preserves reduction up to equivalence in \\CICE,\nnot reduction, normalization doesn't hold immediately from the translation.\nIn particular, the proof of \\nameref{lem:pres-red} uses equality reflection\nto obtain an equivalence between two proofs of accessibility\\index{accessibility predicate} of a size,\nand \\citet{SProp} show that this equivalence can lead to nonnormalization in\nparticular inconsistent environments,\nas is the case for $\\tg{false}$.\n\nEven so, I conjecture that translation of a \\lang term will never lead to\na \\CICE term with a subterm in an appropriate inconsistent environment that leads to nonnormalization,\nbecause the translation will never yield an assumption of the form $\\sT \\szltT \\sT$.\nBy inspection of the translation, the only fitting subsizing relation possible is of the form $\\alphaT \\szltT \\alphaT$,\nand the only possible sources $\\Funtype<{\\alpha}{\\alpha}{\\tau}$, $\\Fun<{\\alpha}{\\alpha}{e}$ are ill-scoped.\nSince fixpoints only reduce when applied to sizes that have a subsize\nand we can't obtain infinitely decreasing chains of subsizes,\nthey can't unfold endlessly and must stop eventually.\n\nDecidability of type checking, meanwhile, rests not only on strong normalization,\nbut also on decidability of subsizing, \\ie deciding whether $\\bound{r}{s}$ holds.\nThe trickiest rule is transitivity of subsizing,\nbut I conjecture that subsizing, too, is decidable,\nas the size environment only contains a finite number of bounded size variables,\nand sizes can only have a finite number of successor operators applied.\nMoreover, Agda has transitive subsizing, and so far hasn't had issues with its decidability.\n\n\\hfill\n\nAs for implementation, the consistency of \\lang shows that sized types for inductives in Agda\nare likely to be consistent were the infinite size\\index{infinite size} removed.\nThis immediately poses a significant problem to Agda's standard library,\nas 20 of the 33 files that use sized types in version 1.7.1 of the standard library use the infinite size.\nFurthermore, 30 of those files deal with coinductives rather than inductives,\nand it remains to be seen whether \\lang with coinductives really is consistent as well.\nThe addition of the $\\const{ac}$ axiom to recover some of the expressivity of the infinite size\nisn't ideal for a proof assistant either, since it would block computation.\n\n\\section{Conclusion}\n\nIn this thesis, I introduced \\lang, a sized dependent type theory\nwith higher-rank size quantification and bounded size quantification,\nbut without an infinite size that is strictly greater than itself,\nalong with sized naturals and well-founded trees.\nI gave examples of programming with sized inductives to write recursive programs\nthat would have otherwise not passed the usual syntactic guard checks,\nas well as limitations of programming without the infinite size.\nI then reduced the consistency of \\lang to that of \\CICE,\nan extensional dependent type theory, by translating \\lang terms to \\CICE terms\nand proving that the translation is type preserving.\nFinally, I discussed the tradeoffs in the design of \\lang for this syntactic model to work,\nnamely the lack of an infinite size and raising the universe levels of the inductives,\nas well as some potential extensions and future work.", "meta": {"hexsha": "691ab813d3b6d561f9538f48f7b21a4b49ad8da1", "size": 30965, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/discussion.tex", "max_stars_repo_name": "ionathanch/msc-thesis", "max_stars_repo_head_hexsha": "8fe15af8f9b5021dc50bcf96665e0988abf28f3c", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/discussion.tex", "max_issues_repo_name": "ionathanch/msc-thesis", "max_issues_repo_head_hexsha": "8fe15af8f9b5021dc50bcf96665e0988abf28f3c", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/discussion.tex", "max_forks_repo_name": "ionathanch/msc-thesis", "max_forks_repo_head_hexsha": "8fe15af8f9b5021dc50bcf96665e0988abf28f3c", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 54.8053097345, "max_line_length": 242, "alphanum_fraction": 0.739964476, "num_tokens": 8623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6334102705979902, "lm_q1q2_score": 0.31917934383082186}}
{"text": "\\documentclass[12pt]{amsart}\n\\usepackage[margin=0.5in]{geometry} \n\t% see geometry.pdf on how to lay out the page. There's lots.\n\\usepackage{bsymb}\n\\usepackage{../unitb}\n\\usepackage{calculational}\n\\usepackage{ulem}\n\\usepackage{hyperref}\n\\normalem\n\\geometry{a4paper} % or letter or a5paper or ... etc\n% \\geometry{landscape} % rotated page geometry\n\n% See the ``Article customise'' template for some common\n% customisations\n\n\\title{}\n\\author{}\n\\date{} % delete this line to display the current date\n\n%%% BEGIN DOCUMENT\n\\setcounter{tocdepth}{4}\n\\begin{document}\n\n\\maketitle\n\\tableofcontents\n\n\\input{main8/machine_m1}\n\\input{main8/machine_m2}\n\\newcommand{\\stmt}[1]{ $#1$ }\n% \\newcommand{\\comment}[2]{ \n% \t% \\begin{tabular}{|l|l|} \n% \t% \t\\hline\n% \t\t\\begin{description}\n% \t\t\\item[{#1}] ~ #2 \n% \t\t\\end{description}\n% \t% \t\\hline \n% \t% \\end{tabular} \n% \t}\n\\newcommand{\\commentbox}[1]{ \n\t\\begin{block} \\item \\small{ #1 } \\end{block} }\n\\newcommand{\\G}{\\text{Val}}\n\\newcommand{\\Req}{\\text{Req}}\n% \\renewcommand{\\H}{\\text{H}}\n\n\\section{Initial model --- Requests}\n\\input{main8/machine_m0}\n\\begin{machine}{m0}\n\t\\with{functions}\n\t\\with{sets}\n\t\\newset{\\G} \\newset{\\Req}\n\t\\newevent{req:push:left}{request\\_push\\_left}\n\t\\newevent{req:push:right}{request\\_push\\_right}\n\t\\newevent{req:pop:left}{request\\_pop\\_left}\n\t\\newevent{req:pop:right}{request\\_pop\\_right}\n\t\\newevent{resp:push:left}{respond\\_push\\_left}\n\t\\newevent{resp:push:right}{respond\\_push\\_right}\n\t\\newevent{resp:pop:left}{respond\\_pop\\_left}\n\t\\newevent{resp:pop:right}{respond\\_pop\\_right}\n\t\\[\\variable{ppL,ppR : \\set[\\Req] } \\]\n\t\\[\\variable{psL,psR : \\Req \\pfun \\G }\\]\n\t\\[ \\dummy{r : \\Req} \\]\n\t\\[ \\dummy{X : \\G} \\]\n    \\[ \\param{req:push:left}{r : \\Req} \\]\n    \\[ \\param{req:push:right}{r : \\Req} \\]\n    \\[ \\param{req:push:left}{x : \\G} \\]\n    \\[ \\param{req:push:right}{x : \\G} \\]\n    \\[ \\param{req:pop:left}{r : \\Req} \\]\n    \\[ \\param{req:pop:right}{r : \\Req} \\]\n\\subsection{Issuing requests}\n\n\\begin{align}\n\t&\\evguard{req:push:left}{m0:grd0}{ \\neg r \\in \\dom.psL } \\\\\n\t&\\evbcmeq{req:push:left}{m0:act0}{psL}{ psL \\1| r \\fun x } \\\\\n\t&\\evguard{req:push:right}{m0:grd0}{ \\neg r \\in \\dom.psR } \\\\\n\t&\\evbcmeq{req:push:right}{m0:act0}{psR}{ psR \\1| r \\fun x } \\\\\n\t&\\evguard{req:pop:left}{m0:grd0}{ \\neg r \\in ppL } \\\\\n\t&\\evbcmeq{req:pop:left}{m0:act0}{ppL}{ ppL \\1\\bunion \\{r\\} } \\\\\n\t&\\evguard{req:pop:right}{m0:grd0}{ \\neg r \\in ppR } \\\\\n\t&\\evbcmeq{req:pop:right}{m0:act0}{ppL}{ ppL \\1\\bunion \\{r\\} }\n\\end{align}\n\n\\subsection{Requirements}\n\n\\begin{align}\n\t\\progress{m0:p0}\n\t\t{r \\in \\dom.psL }\n\t\t{ \\neg r \\in \\dom.psL } \\\\\n\t\\progress{m0:p1}\n\t\t{r \\in \\dom.psR }\n\t\t{ \\neg r \\in \\dom.psR } \\\\\n\t\\progress{m0:p2}\n\t\t{r \\in ppL }\n\t\t{ \\neg r \\in ppL } \\\\\n\t\\progress{m0:p3}\n\t\t{r \\in ppR }\n\t\t{ \\neg r \\in ppR } \\\\\n\t\\safety{m0:s0}\n\t\t{ psL.r = X }\n\t\t{ \\neg r \\in \\dom.psL } \\\\\n\t\\safety{m0:s1}\n\t\t{ psR.r = X }\n\t\t{ \\neg r \\in \\dom.psR }\n\\end{align}\n\n\\subsection{Addressing the requirements}\n\\[ \\indices{resp:pop:right}{r : \\Req} \\]\n\\[ \\indices{resp:pop:left}{r : \\Req} \\]\n\\[ \\indices{resp:push:right}{r : \\Req} \\]\n\\[ \\indices{resp:push:left}{r : \\Req} \\]\n\\begin{align}\n\t\\refine{m0:p0}{ensure}{resp:push:left}{ \\index{r}{r' = r} }\n\t\\cschedule{resp:push:left}{m0:sch0}{ r \\in \\dom.psL } \\\\\n\t\\evbcmeq{resp:push:left}{m0:act0}{psL}{ \\{r\\} \\domsub psL }\n\\end{align}\n% \\removecoarse{resp:push:left}{default}\n\\begin{align}\n\t\\refine{m0:p2}{ensure}{resp:pop:left}{ \\index{r}{r' = r} }\n\t\\cschedule{resp:pop:left}{m0:sch0}{ r \\in ppL } \\\\\n\t\\evbcmeq{resp:pop:left}{m0:act0}{ppL}{ ppL \\setminus \\{ r \\} }\n\\end{align}\n% \\removecoarse{resp:pop:left}{default}\n\\begin{align}\n\t\\refine{m0:p1}{ensure}{resp:push:right}{ \\index{r}{r' = r} }\n\t\\cschedule{resp:push:right}{m0:sch0}{ r \\in \\dom.psR } \\\\\n\t\\evbcmeq{resp:push:right}{m0:act0}{psR}{ \\{r\\} \\domsub psR }\n\\end{align}\n% \\removecoarse{resp:push:right}{default}\n\\begin{align}\n\t\\refine{m0:p3}{ensure}{resp:pop:right}{ \\index{r}{r' = r} }\n\t\\cschedule{resp:pop:right}{m0:sch0}{ r \\in ppR } \\\\\n\t\\evbcmeq{resp:pop:right}{m0:act0}{ppR}{ ppR \\setminus \\{ r \\} }\n\\end{align}\n% \\removecoarse{resp:pop:right}{default}\n\\end{machine}\n\\section{First Refinement --- Sequence of Values}\n\\input{main8/machine_m1}\n\\begin{machine}{m1}\n\t\\refines{m0}\n\t\\with{intervals}\n\\splitevent{resp:pop:right}{resp:pop:right:empty,resp:pop:right}\n\\splitevent{resp:pop:left}{resp:pop:left:empty,resp:pop:left}\n\t\\[ \\variable{p,q : \\Int} \\]\n\t\\[ \\variable{qe : \\Int \\pfun \\G} \\]\n\t\\[ \\variable{emp : \\Bool } \\]\n\t\\[ \\variable{ res : \\G } \\]\n\\begin{align}\n\t\\invariant{m1:inv0}{ qe \\in \\intervalR{p}{q} \\tfun \\G } \\\\\n\t\\invariant{m1:inv1}{ p \\le q } \\\\\n\t\\initialization{m1:init0}{ qe = \\emptyfun } \\\\\n\t\\initialization{m1:init1}{ p = 0 \\land q = 0 } \\\\\n\t\\evbcmeq{resp:push:right}{m1:act0}{q}{q+1} \\\\\n\t\\evguard{resp:push:right}{m1:grd0}{ r \\in \\dom.psR } \\\\\n\t\\evbcmeq{resp:push:right}{m1:act1}{qe}{ qe \\1| q \\fun psR.r } \\\\\n\t\\evbcmeq{resp:pop:right}{m1:act0}{q}{q-1} \\\\\n\t\\evguard{resp:pop:right}{m1:grd0}{\\neg p = q} \\\\\n\t\\fschedule{resp:pop:right}{m1:sch0}{\\neg p = q} \\\\\n\t\\evbcmeq{resp:pop:right}{m1:act1}{qe}{ \\{ q\\0-1 \\} \\domsub qe } \\\\\n\t\\evbcmeq{resp:pop:right}{m1:act2}{emp}{ \\false } \\\\\n\t\\evbcmeq{resp:pop:right}{m1:act3}{res}{ qe.(q\\0-1) } \\\\\n\t\\fschedule{resp:pop:right:empty}{m1:sch0}{ p = q } \\\\\n\t\\evguard{resp:pop:right:empty}{m1:grd0}{ p = q } \\\\\n\t\\evbcmeq{resp:pop:right:empty}{m1:act2}{emp}{ \\true } \\\\\n\t\\evbcmeq{resp:push:left}{m1:act0}{p}{p-1} \\\\\n\t\\evguard{resp:push:left}{m1:grd0}{ r \\in \\dom.psL } \\\\\n\t\\evbcmeq{resp:push:left}{m1:act1}{qe}{qe \\1| p\\0-1 \\fun psL.r} \\\\\n\t\\evbcmeq{resp:pop:left}{m1:act0}{p}{p+1} \\\\\n\t\\evguard{resp:pop:left}{m1:grd0}{\\neg p = q} \\\\\n\t\\fschedule{resp:pop:left}{m1:sch0}{\\neg p = q} \\\\\n\t\\evbcmeq{resp:pop:left}{m1:act1}{qe}{ \\{ p \\} \\domsub qe } \\\\\n\t\\evbcmeq{resp:pop:left}{m1:act2}{emp}{ \\false } \\\\\n\t\\evbcmeq{resp:pop:left}{m1:act3}{res}{ qe.p } \\\\\n\t\\fschedule{resp:pop:left:empty}{m1:sch0}{ p = q } \\\\\n\t\\evguard{resp:pop:left:empty}{m1:grd0}{ p = q } \\\\\n\t\\evbcmeq{resp:pop:left:empty}{m1:act2}{emp}{ \\true } \n\\end{align}\n\\end{machine}\n\\begin{machine}{m2}\n\t\\refines{m1}\n\\end{machine}\n\\end{document}", "meta": {"hexsha": "3a600d082c82a8b1a77b641b4354eb5488be2502", "size": 6059, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Tests/lock-free deque/main8.tex", "max_stars_repo_name": "literate-unitb/literate-unitb", "max_stars_repo_head_hexsha": "0d843456dc103bb09babc5b12855435d2e10f534", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-07-27T11:05:56.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-20T14:53:33.000Z", "max_issues_repo_path": "Tests/lock-free deque/main8.tex", "max_issues_repo_name": "unitb/literate-unitb", "max_issues_repo_head_hexsha": "0d843456dc103bb09babc5b12855435d2e10f534", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32, "max_issues_repo_issues_event_min_datetime": "2017-06-25T03:53:02.000Z", "max_issues_repo_issues_event_max_datetime": "2017-06-25T04:28:38.000Z", "max_forks_repo_path": "Tests/lock-free deque/main8.tex", "max_forks_repo_name": "literate-unitb/literate-unitb", "max_forks_repo_head_hexsha": "0d843456dc103bb09babc5b12855435d2e10f534", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6611111111, "max_line_length": 67, "alphanum_fraction": 0.6255157617, "num_tokens": 2590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778403, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3191793403437156}}
{"text": "%\\section{SNoW for MWMR setting}\\label{mwmr}\nHere present  algorithm  $B$, which satisfies  SNW and \"one-version\" properties, in MWMR setting where a \\rot{} must consist of one version of the data but, possibly, multiple communication trips between the reader and the servers.% We denote the type of object  that satisfies the SNoW properties by $\\tilde{\\mathcal{O}}_T$.   \n%Note that $B$ can also tolerate crash failure of writers and readers. \nIn B, the steps for the writers are shown in Pseudocode~\\ref{fig:algo_bc} and for readers and the servers  are presented in Pseudocode~\\ref{fig:algo_b}.\nWe assume  a set of writers $\\mathcal{W}$,  a set of readers $\\mathcal{R}$ and a set of $k \\geq 1$ servers,  $\\mathcal{S}$, with ids $s_1, s_2\\cdots s_k$ that stores the objects $o_1, o_2, \\cdots, o_k$, respectively.  We define  key ${\\kappa}$ is defined as a pair $(z, w)$, \nwhere $z \\in \\mathbb{N}$ and $w \\in \\mathcal{W}$ the  id of a writer. We use $\\mathcal{K}$ to denote the set of all possible keys. \nIn $B$, the keys are used to uniquely identify each transaction. Also, with each transaction we associate a tag $t \\in \\mathbb{N}$. \n%We assume writers can send message to the reader, i.e., we allow client-to-client messages.\n% We assume that each process has a unique id. We assume that each server $s$ stores object $o_s$, due to sharding.  For the sake of simplicity, we assume that the \\wots{} issued by a writer are of the form: \\emph{ write value $v_1$ to object $o_1$, $v_2$ to $o_2$, and so on}. In other words, we assume that such a  transaction consists of the set of operations $\\{ \\writeop{o_1}{v^{(1)}}, \\writeop{o_2}{v^{(2)}}\\cdots \\writeop{o_k}{v^{(k)}}\\} $, which we denote by $write(v_1, v_2, \\cdots, v_k)$.  \\wots{} where only a subset of  the objects are updates will be discussed later. We also assume that  the \\rots{} are of the form  $\\{ \\readop{o_1}, \\readop{o_2}\\cdots \\readop{o_k}\\}$ consisting of $k$ reads to $k$ distinct objects.\t\n\t\nIn  $B$, we designate one of the servers as coordinator, denote as $s^*$,\n for the transactions. The $s^*$  maintains the order of the \\wots{} and the objects that are updated during the \\wot{} in the variable $List$.  %Note that in a system, where there are many objects \n%different objects may be use different servers  as coordinators based on some load-balancing rule. \n\n\\textit{\\textbf{State variables:}} Each of the writers and servers maintain a set of state variables as follows: $(i)$ At  any  \\emph{writer $w$}, there is  a counter $z$ to keep track of the\n number of \\wot{}  the writer has  invoked, initially $0$. $(ii)$ At any  \\emph{server}, $s_i$, \n for $i \\in [k]$, there is  a set variable $Vals$ \n with elements \n that are  key-value pairs $({\\kappa}, v_i) \\in \\mathcal{K} \\times \\mathcal{V}_i$. Initially,\n  $Vals= \\{ ({\\kappa}^0, v_i^0)\\}$. %This ensures that each \\wot{} generates a unique key.\nA server also contains an\n ordered list variable $List$  of elements  as $({\\kappa}, (b_1, \\cdots, b_k))$,  where \n ${\\kappa}  \\in \\mathcal{K}$  and \n $(b_1, \\cdots b_k) \\in  \\{0, 1\\}^k$. Initially,  \n $List= [ ({\\kappa}^0, (1, \\cdots 1) ]$, where ${\\kappa}^0  \\equiv (0, w_0)$, \n where $w_0$ is any\n  place holder identifier string for writer id. The elements in $List$ can be identified with an index, e.g., \n  $List[0] =({\\kappa}^0, (1, \\cdots, 1))$.  Essentially, a $(k+1)$-tuple  $(\\kappa, (b_1, \\cdots, b_k))$ in $List$ corresponds to a \\wot{} and \n   identifies the set of objects that are updated during the \\wot{}, i.e., if $b_i=1$ then object \n   $o_i$ was updated  during  the  \\wot{}, otherwise $b_i=0$.\n\t\t\t%labeled with phase names, viz., {\\readGetTag}, {\\readValueTag}, {\\readCompleteTag} and {\\writeGetTag}. The server to server messages are labeled as {\\readDisperseTag}. Also, in some phases of {\\SODA},  the message-disperse primitives {\\mdmetaprim} and {\\mdvalueprim} are used  as services. \n\t\t\t\t\t\n\\textit{\\textbf{Writer steps:}} A \\wot{} updates\n\t\t\ta  list of $p$ objects $o_{i_1}, o_{i_2}, \\cdots o_{i_p}$  with values\n\t\t\t $v_{i_1}, v_{i_2}, \\cdots v_{i_p}$, respectively, is invoked at $w$ via the procedure\n\t\t\t$\\Writetr{ (o_{i_1}, v_{i_1}), \\cdots, (o_{i_p}, v_{i_p}) }$.\nWe use the notations:  $I \\triangleq \\{i_1, i_2, \\cdots, i_p\\}$  and $S_I\\triangleq \\{s_{i_1}, s_{i_2}, \\cdots, s_{i_p}\\}$.\nThis procedure  consists of two phases: {\\writeValue} and {\\updateCoord}. \n%We denote the set of servers involved   in the \\wot{}  by  $S_I=\\{s_{i_1}, s_{i_2}, \\cdots, s_{i_p}\\}$.   \nDuring the {\\writeValue} phase,  $w$ creates a new key ${\\kappa}$ as \n $ {\\kappa}  \\equiv (z + 1, w)$, where $w$ identifies the writer; and also increments the local counter $z$ by one.  Then $w$ sends $(${\\writeValueTag}$, ({\\kappa}, v_{i}))$ to each server in $S_I$, and awaits {\\ackTag}  \nfrom all servers in $S_I$.\nAfter receiving {\\ackTag} from all servers in $S_I$,  $w$\ninitiates the {\\updateCoord} phase where it sends \n(\\updateCoordTag, $({\\kappa}, (b_{1}, \\cdots b_{k})$) to $s^*$, where for any $i \\in [k]$,  $b_i=1$ if $s_i \\in S_I$, \notherwise $b_i=0$,   and completes then \\wot{} after it receive a   ({\\ackTag}, $t_w$) from $s^*$.  \n%\t  After receiving message  ({\\ackTag}, $t_w$),  $w$ completes the \\wot{}.\n\n%At $s^*$, upon receiving  (\\updateCoordTag, $({\\kappa}, (b_{1}, \\cdots, b_{k})$) from $w$ appends  \n%\t\t\t $({\\kappa}, (b_{1}, \\cdots, b_{k}))$ to its  $List$,  and responds with  \n%\t\t\t {\\ackTag} and $t_{w}$ (set to be the number of elements in the local list $List$)  to $w$.\n%\t\t\t The order of the  elements in  $List$ corresponds to  the order  \n%the \\wots{}, the order of the incoming  {\\updateCoordTag} updates,  as seen by $s^*$.\n%\t\t\t  After receiving an ({\\ackTag}, $t_w$),  $w$ completes the \\wot{}.\n\n\\textit{\\textbf{Reader steps:}}\nWe use the same notations for $I$ and $S_I$ as above but the indices can vary across  transactions.\nThe procedure  \\Readtr{$ o_{i_1},  o_{i_2}, \\cdots, o_{i_p}$} can be \ninitiated by  some reader  $r$,   as a \\rot{}, intending to read the values of \nsubset $o_{i_1},  o_{i_2}, \\cdots, o_{i_p}$ of the objects. The procedure \nconsists of two consecutively executed phases of communication rounds\nbetween the $r$ and the  servers, viz.,  {\\getTagArray} and {\\readValue}. \n%\nDuring  the  phase {\\getTagArray},  $r$ sends $s^*$ the message  {\\getTagArrayTag}  \n requesting the  list of the latest added keys for each object. \n Once $r$ receives a list of tags, such as, $(t_r, ({\\kappa}_1, {\\kappa}_2, \\cdots,  {\\kappa}_k))$ from $s^*$   the phase completes.\n%\n%\nIn the subsequence phase, {\\readValue},   $r$ requests each server $s_i$ in $S_I$ by sending the message \n$(\\text{\\readValueTag}, \\kappa_i)$. \n% Then upon receiving such a request, any server $s_i$ responds with  $(${\\readValueTag}$, {\\kappa}^{s_i})$, i.e., one version of  $o_i$ corresponding to the key $t_i$ to $r$, stored in its $Vals$. \n%\n%During  phase {\\readValue}, \t the reader sends to each of the servers in \n%$\\mathcal{S}$, say $s_i$ the key ${\\kappa}^{s_i}$ corresponding \n%\t\t\t to $(k+1)$-tuple of $List$ with the latest  index $j^*$ such that $b_i =1$ such that \n%$i \\in I$, where $I \\triangleq  \\{{i_1},  {i_2}, \\cdots, {i_p}\\}$,  requesting the corresponding value.  \n%Any server $s_i$ upon receiving \n%such a message with $(${\\readValueTag}$, {\\kappa}^{s_i})$ responds with $v$ such that $({\\kappa}^{s_i}, v_i)$ is in its variable $Vals$. \nAfter  receiving the values $v_{i_1}$, $v_{i_2}, \\cdots v_{i_p}$ from the servers in $\\mathcal{S_I}$, \n $r$ completes the transaction  by \n returning the tuple of values $(v_{i_1}, \\cdots v_{i_p})$.\n % and set the tag $t_r$ as  the latest index in $List$ corresponding to a \\wot{} that updated  one of the object in the \\rot{}, i.e., $\\max_{1 \\leq j \\leq |List|} \\{ j : List[j].b_i = 1 \\wedge i \\in I\\}$.\n\n\\textit{\\textbf{Server steps:}}  \nWhen a server $s_i$ receives a message of type $(${\\writeValueTag}$, ({\\kappa}, v_{i}))$ from a writer $w$ then \n%to each server in $S_I$, and awaits {\\ackTag}  \n%from all servers in $S_I$.\nit  adds $({\\kappa}, v_i)$ to its set variable  \n$Vals$ and sends {\\ackTag} back to $w$.\n\nIf the coordinator $s^*$ receives  (\\updateCoordTag, $({\\kappa}, (b_{1}, \\cdots, b_{k})$) from writer $w$, then it appends  \n\t\t\t $({\\kappa}, (b_{1}, \\cdots, b_{k}))$ to its  $List$,  and responds with  \n\t\t\t {\\ackTag} and $t_{w}$ (set to be the number of elements in the local list $List$)  to $w$.\n\t\t\t The order of the  elements in  $List$ corresponds to  the order  \nthe \\wots{}, the order of the incoming  {\\updateCoordTag} updates,  as seen by $s^*$.\n\t\nWhen $s^*$  receives  the message  {\\getTagArrayTag} from $r$  it responds with \n$(\\kappa_1, \\cdots, \\kappa_k)$ such that for each $i \\in [k]$, $\\kappa_i$ is the key  part of the $(k+1)$-tuple that was modified\nlast, i.e., \t${\\kappa}_i = List[j^*].{\\kappa}$ such that \t $j^* \\triangleq\\max \\{ j : List[j].b_i =1 \\}$, and \n$t_r$, $t_r \\triangleq \\max_{1 \\leq j \\leq |List|} \\{ j : List[j].b_i = 1 \\wedge i \\in I\\}$.\n%\n  \tIf any server $s_i$ receives a message  $(${\\readValueTag}$, {\\kappa})$ from a reader $r$ then it responds to $r$ with \n   the value $v_i$ corresponding to key with value  $\\kappa$ in  $Vals$. \n\nThe following result states that algorithm $B$ respects SNW and \"one-round\" properties.\n% and the proof is omitted for now since it is very straightforward. Note that the liveness property of \\rot{} and \\wot{}  transactions are a part of the SNOW properties.\n%Consider any failure-free and fair execution of algorithm $B$. \n%For the purpose of proving the $S$ property, for every transaction transaction  $\\phi$ in an execution of $B$ we associate a tag $tag(\\phi)$ as described below.\n% the variable $t_r$ in a reader and $t_w$ in \n%a writer are used to associate a tag as described below.\n% $ \\triangleq \\max_{1 \\leq j \\leq |List|} \\{ j : List[j].b_i = 1 \\wedge i \\in I\\}$, which is presented as a comment in the pseudo-code for $A$.\n%If $\\phi$ is a \\wot{} (\\rot{}) then  $tag(\\phi)$ is the value of the variable $t_w$ ($t_r$) immediately before the \n%operation completes.\n\n\\begin{theorem} Any well-formed  and fair execution of algorithm $B$  satisfies the SNW and \"one-round\"  properties. %Algorithm $B$ also tolerates any client crash failures.\n\\end{theorem}\n\n%\t\\begin{theorem} Any well-formed  and fair execution of algorithm $B$ is an implementation of  an object of type $\\tilde{\\mathcal{O}}_T$ in the MWMR setting, \twith no client-to-client communication,  comprising of objects $o_1, o_2, \\cdots o_k$ stored in servers $s_1, s_2, \\cdots, s_k$, respectively; and it satisfies the SNoW  properties. %Algorithm $B$ also tolerates any client crash failures.\\end{theorem}\n\n\n\n\\remove{\n\\begin{proof} Below we show that algorithm $B$ satisfies the  SNoW properties. \n\t\n\t\\noindent{\\emph{\\underline{S property:}}} \n\tLet $\\beta$ be any fair execution  of  $B$ and \n suppose all clients in $\\beta$ behave in a well-formed\nmanner. Suppose $\\beta$ contains no incomplete transactions and let  $\\Pi$ be the set of transactions in $\\beta$.  We define an irreflexive partial ordering ($\\prec$) in $\\Pi$ as follows:  if $\\phi$ and $\\pi$ are any two distinct transactions in $\\Pi$ then we say \n\t$\\phi \\prec \\pi$ if either $(i)$ $tag(\\phi) < tag(\\pi)$ or $(ii)$ $tag(\\phi) = tag(\\pi)$ and $\\phi$ is a \\wot{} and $\\pi$ is a \\rot{}. Below we prove the $S$  property of $B$ by showing that  properties $P1$, $P2$, $P3$ and $P4$ of Lemma~\\ref{lem:equivalence} hold for $\\beta$. \n\t\n\t\\emph{P1:}   Clearly, from an inspection of the algorithm, \n\t $tag(\\pi) \\in \\mathbb{N}$. From inspection of the algorithm, each \\wot{} increases the size of \n\t $List$, and the value of the tags are  defined by the size of $List$. Therefore, there can be at \n\t most a finite number of \\wots{} such that can precede $\\pi$ (w.r.t. $\\prec$) in $\\beta$.\n\t  On the other hand, if $\\pi$ is a \\rot{} then since all \\rot{}s are invoked by readers  in a well-formed manner,  and there are only finite number of readers \n\ttherefore, there cannot be an infinite number of \\rot{}s such that they all \n\tprecede $\\pi$ (w.r.t $\\prec$).\n\t\n\t \n\t  \n\t\\emph{P2:}  Suppose $\\phi$ and $ \\pi$ are any two transactions in $\\Pi$, such that, $\\pi$ begins after $\\phi$ completes. Then we show that we have  we cannot have $\\pi \\prec \\phi$. Now, we consider four cases, depending on whether $\\phi$ and $\\pi$ are \\rot{}s or \\wots{}.\t\n\t\\begin{enumerate}\n\t    \\item [$(a)$] $\\pi$ and $\\phi$ are \\wots{} invoked by writers $w_{\\pi}$ and $w_{\\phi}$, respectively. Since the size of $List$, in $s^*$ grows monotonically due to each \\wot{}  hence  $w_{\\pi}$ receives the  tag  from $s^*$ at least as high as $tag(\\phi)$, so $\\pi\\not \\prec \\phi$.\n\t      %\n\t       \\item [$(b)$] $\\pi$ is a \\rot{}, $\\phi$ is a \\wot{} invoked by reader  $r_{\\pi}$ and writer $w_{\\phi}$, respectively.  \n\t        Since the size of $List$, in $s^*$,  grows monotonically,  because  $r_{\\pi}$  invokes $\\pi$ after $\\phi$ completes hence $tag(\\pi)$ is at least as high as $tag(\\phi)$, so $\\pi\\not \\prec \\phi$.\n\t      %\n\t        \\item[$(c)$]$\\pi$ and $\\phi$ are both \\rot{}s  invoked by readers $r_{\\pi}$ and $r_{\\phi}$, respectively. \n\t           Since the size of $List$, in $s^*$, grows monotonically,  because   $w_{\\pi}$ invokes $\\pi$ after $\\phi$ completes hence $tag(\\pi)$ is at least as high as $tag(\\phi)$, so $\\pi\\not \\prec \\phi$.\n\t        %\n\t         \\item [$(d)$] $\\pi$ is a \\wot{}, $\\phi$ is a \\rot{}  invoked by writer $w_{\\pi}$ and reader $r_{\\phi}$, respectively.\n\t         This case is simple because new values are added to $List$, in $s^*$,  only  by writers, and $tag(\\pi)$  has to be larger than the tag of $\\phi$ and hence   $\\pi\\not \\prec \\phi$. \n\t\\end{enumerate}\n\t\n\t\n\t\\emph{P3:} This is from  the fact that any \\wot{} always creates a unique tag and all tags are totally ordered since they all belong to $\\mathbb{N}$\n\t\n\t\t\\emph{P4:} Consider a \\rot{} $\\rho$ as $READ(o_{i_1}, o_{i_2}, \\cdots, o_{i_q})$, in $\\beta$. \nLet the returned value from $\\rho$ be $\\mathbf{v} \\equiv $$(v_{i_1}, v_{i_2}, \\cdots, v_{i_q})$ such that \n$1 \\leq {i_1} <  {i_2} <  \\cdots <  {i_q} \\leq k$, where value  $v_{i_j}$ corresponds to $o_{i_j}$. \n\tSuppose $tag(\\rho) \\in \\mathbb{N}$ was created during some \\wot{}, say $\\phi$, i.e., $\\phi$ is the \\wot{} that \n\tadded the elements in index $(tag(\\rho)-1)$ of $List$ at the coordinator $s^*$. Note that element in index $0$ contains the initial value.\n\t%because \\rots{} do not generate new tags as they do not add any new item to the $Vals$ of any server.\n\t Now we consider two cases:\n\t \n\t\\emph{Case $tag(\\rho) = 1$.} We  know that it corresponds the initial default value $v_i^0$ at each sub-object $o_i$, and this equates to $\\rho$ returning the default initial value for each sub-object.\n\t %\n\t% Therefore, $tag(\\rho) = tag(\\phi)$. \n\t \n\t \\emph{Case $tag(\\rho) > 1$.} Then we argue that there exists no \\wot{}, say $\\pi$, that updated object $o_{i_j}$,   in $\\beta$, such that,  $\\pi \\neq \\phi$ and $\\rho$ returns values written by $\\pi$ and $\\phi \\prec \\pi \\prec \\rho$. Suppose we assume the \tcontrary, which means $tag(\\phi) < tag(\\pi) < tag(\\rho)$. The latter implies $tag(\\phi)  = tag(\\pi)$ which is not possible because \n\tthis contradicts the fact that for any two distinct \\wots{} $tag(\\phi) \\neq tag(\\pi)$  in any execution of   $B$.\n\n\t\\noindent{\\emph{\\underline{N, o and W properties:}}}  Evident from an inspection of the algorithm.\n\t% for the  response steps  of the servers to the reader.\n\t\\end{proof}\n}", "meta": {"hexsha": "0f7ed420ad9dc6563c644584ce6d5ab182f04065", "size": 15427, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "SNW-one-version-short-v1.tex", "max_stars_repo_name": "kishori82/DISC2020-SNOW-Revisited", "max_stars_repo_head_hexsha": "65f35b83186e9a3c5d83ad0851c3730271ff42f1", "max_stars_repo_licenses": ["LPPL-1.3c"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SNW-one-version-short-v1.tex", "max_issues_repo_name": "kishori82/DISC2020-SNOW-Revisited", "max_issues_repo_head_hexsha": "65f35b83186e9a3c5d83ad0851c3730271ff42f1", "max_issues_repo_licenses": ["LPPL-1.3c"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SNW-one-version-short-v1.tex", "max_forks_repo_name": "kishori82/DISC2020-SNOW-Revisited", "max_forks_repo_head_hexsha": "65f35b83186e9a3c5d83ad0851c3730271ff42f1", "max_forks_repo_licenses": ["LPPL-1.3c"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 87.6534090909, "max_line_length": 733, "alphanum_fraction": 0.659882025, "num_tokens": 5137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.5039061705290806, "lm_q1q2_score": 0.31917933336950305}}
{"text": "% -*- root: ../main.tex -*-\n\\chapter{Design\\label{chap:design}}\n\n\\paragraph{Abstract} \n\nIn this chapter we define the way that formal verification can be achieved, for which first we define some notation and definitions.\n%\nAfter some generalities about formal verification, we define more concrete aspects of the formal verification we aim to achieve, such us the linked-list theory used.\n%\n%\n%\n\\section{Program correctness}\n%\nWe are finally ready to apply this concepts to a real word problem. In this \\thisworkm we apply those concepts to prove some properties of programs.\n%\nThe remaining task is to define the framework and the conventions we use to formally prove  properties of programs.\n\nThe way we approach to assess correctness is by proving properties. \n%\nThere are \\concept{liveness}, \\concept{safety} and \\concept{functional} properties. \n%\nSafety properties refer, informally, to “bad things never happens”. Proving \\textit{ variable x is never 0 } is a safety property. \n%\nProving valid this property can assure that a division by zero error will never occur. \n%\nWhether a program finishes or not is a liveness property, and producing an output for a concrete input is a functional property. \n\nThese properties are written in some logic. \n%\nLiveness properties require the use of temporal logic but we restrict ourselves to use safety properties so no machinery for temporal properties is needed.\n%\nAs the properties are expressed formally in \\gls{FOL}, it is necessary to define a formal representation of a program.\n\n\n\\label{def:SPL}\n\\input{src/spl}\n\n\n\\subsection{Partial correctness (Safety)}\n\nA function (or the whole program) is \\textbf{partially correct} if whenever the function's precondition is satisfied on entry, its postcondition is satisfied when the function returns (if it ever does).\n%\nWe present the \\concept{inductive assertion method} for proving partial correctness.\n\n\nLet $\\varphi$ be the \\gls{FOL} property to study. \n%\nThe procedure is the following:\n%\nFirst each function is reduced to a finite set of \\gls{FOL} formulae called \\concept[Verification condition]{\\gls{VC}}.\n%\nThis reduction is done with the basic reducing cases we studied in \\ref{def:SPL}.\n%\nThe goal is to prove that $\\varphi$ is valid in every state of the execution.\n%\n\\textbf{Induction} is the methodology used.\n%\nFirst, we assert $\\varphi$ is valid before the program starts (induction base).\n%\nThen, we assume $\\varphi$ in the precondition and prove $\\varphi'$ valid (induction step) for every possible transition.\n\nThis method is not complex to understand but it requires a lot of work even for simple programs. \n%\nWe illustrate this method with an example in \\ref{app:exampleFactorial}.\n\n\\vspace{-0.3cm}\n\\section{Parametrized systems}\n\nThe correctness of a program executed by just one thread it is an easier problem because the program runs sequentiality.\n%\nMultiple threads executing the same program is a different and more difficult problem to solve.\n%\nAn unbounded number of threads executing is another important and difficult extension.\n%\nIf the number of threads is bounded, one could unroll the formula for all the threads in the problem. \n%\nAs this is the usual scenario, we focus the unbounded case.\n\nWe are going to study those cases. \n%\nTo do so, we need to parametrize the program executed by multiple threads.\n%\nTypically we use  $i$,$j$,$k_0$,$k_i$ for threads identifiers.\n\n\\vspace{-0.3cm}\n\\subsubsection{Arbitrary number of threads}\n\nFor example, the web servers may not have a bound of the number of clients they can accept.\n%\nCan we prove correctness when an unbounded number of processes are using the same global variables?\n\nA recent research \\citeapos{paperParametrizedInvariants} has proven a very important result. \n%\nWe will present this result new as it is fundamental for this work. \n%\nWe will not formally prove any of the results proven in \\citep{paperParametrizedInvariants}.\n\nBefore we enunciate the theorem, we need some previous concepts.\n%\nWe need to extend the concept of support to parametrized formulas.\n\n\n\\begin{defn}[Support]\n  Let $\\psi$, $A$ and $B$ be parametrized formulas, and let $S$ be the\n  set of possible substitutions from the set of parametrized variables in $\\psi$ ($\\Var(\\psi)$) into the set of parametrized variables of $(A\\Into B)$ ($\\Var(A\\Into B)$).\n%\n  We say that $\\psi$ supports $(A\\Into B)$, whenever\n%\n  \\[ \\big( (\\bigwedge_{\\sigma\\in S} \\sigma(\\psi)\\big) \\andcond A\\big) \\Into B \\hspace{4em} \\text{is valid} \\]\n%\n  We use $\\psi\\supports(A\\Into B)$ as a short notation for\n  $\\big((\\bigwedge_{\\sigma\\in S} \\sigma(\\psi)) \\andcond A\\big) \\Into B$.  \n\\end{defn}\nNote that if $S'\\subseteq S$ is a subset of the substitutions, and \n%\n  \\[ \\big( (\\bigwedge_{\\sigma\\in S'} \\sigma(\\psi)\\big) \\andcond A\\big) \\Into B \\hspace{4em} \\text{is valid} \\]\n%\nthen\n%\n  \\[ \\big( (\\bigwedge_{\\sigma\\in S} \\sigma(\\psi)\\big) \\andcond A\\big) \\Into B \\hspace{4em} \\text{is also valid} \\]\n%\n  Essentially, if one succeeds in proving the validity of a formula obtained by removing some of the conjuncts from the antecedent, the validity of the full formula is preserved.\n%\n  Hence, in practice, it is enough to consider only some of the partial substitutions to show that a support formula is valid.\n\n\n\\begin{itheorem}[Bound an arbitrary number of threads]\n\tLet $\\varphi$ be a thread-parametrized formula, where $\\overline{k}=\\Var(\\varphi)$. \n\t%\n\tLet $\\tau$ be a transition of $P$ and $\\ThetaParam$ the initial condition of $P$.\n\n\tTo show that $P$ satisfies $\\Always\\varphi$ (that is, $\\varphi$ is an invariant of $P$):\n\t\\hspace{-1em}\n\t\\[ \n\t\t\\begin{array}{r@{\\;\\;}lr@{\\;}@{\\;}cl@{\\hspace{1em}}l}\n\t\t\t\\Premise{S1}. & & \\ThetaParam(\\overline{k}) &\\supports & \\varphi & \\\\\n\n\t\t\t\\Premise{S2}. & \\varphi \\supports & \\tau^{(i)} &\\Into& \\varphi'  & \\text{forall $\\tau$ and all $i\\in \\overline{k}$}\\\\\n\t\t\t\\Premise{S3}. & \\varphi\\supports & \\big(\\bigwedge\\limits_{x\\in\\Var(\\varphi)} j\\neq x \\andcond \\tau^{(j)} &\\Into& \\varphi' \\big)& \\text{forall $\\tau$ and one fresh $j\\notin\\overline{k}$}\\\\ \\hline\n\t\t\t& \\multicolumn{4}{c}{\\hspace{3em} \\Always \\varphi} &\n\t\t\\end{array}\n\t\\]\n\\label{thm:biggest}\n\\end{itheorem}\n\n\n\nUsing this powerful result, we have reduced an arbitrary number of processes sharing the same variables to a finite number of threads sharing the variable. \n%\nThe proof of this result can be found in \\citeapos{paperParametrizedInvariants}.\n%\nWe will refer to $\\Premise{S1}$ as \\concept{initiation} because it depends on the initial condition.\n%\n$\\Premise{S2}$ will be referred as \\concept{self-consecution} because it captures the execution of one of the threads mentioned in the formula.\n%\nFinally, $\\Premise{S3}$ will be referred as \\concept{others-consecution} because it captures the execution of threads which do not appear in the formula. \n%\nThe example included in appendix \\ref{app:exampleFactorial} illustrate the concept of support. \n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{A Theory of Linked Lists}\n\n\\subsection{Description}\n\nIn order to work with linked lists in a context with multiple thread using the same list \nthere are two possible approaches. \n%\nA thread could lock the entire list, work with the list and then release the lock. \n%\nThere could be some optimizations in this approach, such as a writer-reader system.\n%\nHowever, this is extremely unefficient although it could more secure in terms of preventing deadlocks.\n%\nThe other approach is locking and unlocking each node of the list, so multiple threads can work simultaneously using the same list as long as they do not need to use the same node.\n%\nThis approach is called lock-coupling lists.\n\n\n\n\\begin{defn}[Lock-coupling linked list]\nA lock-coupling concurrent list is \na concurrent data type that implements a set by maintaining in the heap an \nordered single-linked list with non-repeating elements.\n%\nEach node in the list is protected by a lock which guarantees that a \nsingle thread can access the node at the same time.\n%\n\\end{defn}\n\nThe way a thread iterates over the list is the following.\n%\nThe thread acquires the lock of the node\nthat it visits and after that tries to acquire the next node.\nThe first lock is only released after the lock of the\nsecond node has been successfully acquired.\n%\nThis technique of protecting cells with locks (instead of protecting\nthe whole data-structure with a single coarse-grain lock) is known as\n\\concept{fine-grained locking}.\n\n\nThe nodes of a concurrent lock-coupling list are instances of the following \n\\ListNode class:\n%\n\\[\n\t  \\class \\;\\Node  \\;\\left\\{\n\t\t\t\tElem \\:\\;\\; data; \\;\n\t\t\t\tAddr \\:\\;\\; next; \\;\n\t\t\t\tLock \\:\\;\\; lock; \\;\n\t\t\\right\\}\n\\]\n%\nWhere the fields are:\n\\begin{itemize}\n\t\t\\item \\fData: the value stored in the node. This field is also used to keep \n\t\t\tthe list ordered.\n\t\t\\item \\fNext: a pointer that stores the address of the next node in \n\t\t\tthe list.\n\t\t\\item \\fLock: the lock protecting the node.\n\\end{itemize}\n\nWe assume that the operating system provides the atomic operations \\fLock \nand \\fUnlock. \n\nWe will use \\concept[Ghost variable]{ghost variables} which are variables that are not present in the program but are added to aid in the verification process.\n%\nThe implementation of concurrent lock-coupling lists has 3 global variables.\n%\nTwo of them are global addresses \\head and \\tail, and one ghost global variable \\region.\n%%\nThe variable \\head, an address points to the first node of the list which has the lowest possible value ($-\\infty$).\n%\nThe variable \\tail, an address points to the last node of the list  which has the lowest possible value ($+\\infty$).\n%\nFinally, the variable \\region, a set of addresses, is used to keep track of the portion of the heap whose cells form the list.\n%\nIn Figure \\ref{fig:listcode} we present the code of the implementation chosen.\n\n\\begin{figure}\n\t\\centering\t\n\t\\label{fig:listcode}\n\t\\includegraphics[scale=0.4]{listcode}\n\t\\caption{Code of the implementation chosen.}\n\\end{figure}\n%\nThere are three procedures, \\Search, \\Insert and \\Remove which traverses through the list the way it was explained.\n\n\n\n\\subsection{TL3}\nTo prove verification conditions generated in the proof of invariants of lock-coupling lists we need a theory of lists to work with, and axioms in order to prove \\gls{FOL} formulas.\n\n\\emph{Theory of Linked Lists with Locks}: \\TLLpL, is the theory we use for describing linked-list heap memory layouts.\n%\n\\TLLpL is a multi-sorted first-order theory.\n%\nIt is multi-sorted because it has multiple types for its variables (address, element,...).\n%\nIt is a first-order theory because only variables are quantifiable, as in unsorted \\gls{FOL}.\n\nIn this section we briefly present \\TLLpL. \n%\nA more complete and formal definition of \\TLLpL can be found in \\citeapos{paperAle} and \\citep[6.2]{thesisAle}.\n\nAlthough some functions are originally defined \\citep{thesisAle} in suffix notation (\\fNext,\\fData and \\fLock fields), preffix-notation has been used to describe the theory. \n%\nThe reason for this modification is to be consistent with the syntax of \\spass.\n%\nFurthermore, we use subset of \\TLLpL. \n%\nIn the same way \\gls{FOL} can be expressed with $\\neg,\\vee$ but sometimes $\\implies$ is included but $\\dimplies$ is not,\n%\na few functions of \\TLLpL have not been used because they can be expressed using others functions in the theory. \n%\nWe proceed to describe the subset of \\TLLpL used.\n\n\n\\TLLpL is a composition of theories. The \\textbf{sorts} used among this theories are: \n%\n\\cell (representing the nodes of the list),\n%\n\\elem (representing elements),\n%\n\\addr (representing address),\n%\n\\tid (representing thread id),\n%\n\\mem (representing the memory also called heap, represented as maps of \\addr to \\cell ),\n%\n\\path (representing a finite sequence of address),\n%\n\\sSetTid, \\sSetAddr, \\sSetElem to represent sets of \\tid,\\addr or \\elem respectively.\n\nFor each sort, there is a theory containing its constants, functions and predicates. \n%\nThere is one more theory, $\\Sigma_{Bridge}$ is a \\emph{bridge theory} containing auxiliary\nfunctions, for example, that allow to map paths of addresses to set of \naddresses, or to obtain the set of addresses reachable from a given \naddress following a chain of \\fNext fields.\n\n\n\n\\subsection{Signature}\n\nWe proceed to describe the signature of each theory, listing the sorts used and explaining its functions, predicates and constants. \n%\nEvery theory includes the equality theory \\ref{theory:equality} \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%\t\t\t\t\tTID \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\\begin{center}\\rule{4cm}{0.4pt} $\\Sigma_{\\tid}$ \\rule{4cm}{0.4pt}\\end{center}\n\\paragraph{$\\Sigma_{\\tid}$ : }\n%\nThe sort used is \\tid. The “no-thread” value is represented with \\fNoThread.\n%\nApart from the equality theory, this theory does not have any other predicates or functions.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%\t\t\t\t\tELEM\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%\\begin{center}\\rule{4cm}{0.4pt} $\\Sigma_{\\elem}$ \\rule{4cm}{0.4pt}\\end{center}\n\\paragraph{$\\Sigma_{\\elem}$ : }\n%\nThe sort used is \\elem. \n%\nThere is a total order which allows to order every set of \\elem.\n%\nIn addition, this sort is upper and lower bounded.\n%\n The top block contains the functions and the lower block lists the predicates.\n\n\\begin{center}\n\\begin{tabular}{|rrl|}\n  \\hline\n\\fHighest & \\elem & Maximum value an \\elem can take.\\\\\n\\fLowest & \\elem & Minimum value an \\elem can take.\\\\\n\\hline\\hline\n\\fLselem & \\elem$\\times$\\elem & Total order relation between \\elem.\n\\\\\\hline\n\\end{tabular}\n%\\caption{\\textbf{Signature of $\\Sigma_{\\ensuremath{\\mathit{elem}}}$.} The top block contains the functions and the lower block lists the predicates.}\n%\\label{table:elem_signature}\n\\end{center}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%\t\t\t\t\tCELL\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%\\begin{center}\\rule{4cm}{0.4pt} $\\Sigma_{\\cell}$ \\rule{4cm}{0.4pt}\\end{center}\n\\paragraph{$\\Sigma_{\\cell}$ : }\n%\nThe sorts used are \\cell,\\;\\elem,\\;\\addr,\\;\\tid.\n\n\\begin{center}\n\\begin{tabular}{|rrl|}\n  \\hline\n\\fMkcell & $\\elem\\times\\addr\\times\\tid \\to \\cell$ & Constructor\\\\\n\\fNext & $\\cell \\to \\addr$ & Getter of \\fNext field \\\\ \n\\fData & $\\cell \\to \\elem$ & Getter of \\fData field \\\\ \n\\fLockID & $\\cell \\to \\tid$ & Getter of \\fLockID field \\\\ \n\\fLock & $\\cell\\times\\tid\\to\\cell$ & Construct a new \\cell with \\fData and \\fNext \\\\\n&&\\;\\;\\;\t\t\t\t\t\t\t\tvalues of the given \\cell, \\\\\n&&\\;\\;\\;\t\t\t\tusing the \\tid for the \\fLockID field.\\\\\n\\fError & $\\cell$ & Constant value used to model \\\\ \n&&\\;\\;\\;\t\t\t\tincorrect memory deference.\n\\\\\\hline\n\\end{tabular}\n%\\caption{\\textbf{Functions of $\\Sigma_{\\cell}$} theory.}\n%\\label{table:cell_signature}\n\\end{center}\n\nThe function \\fUnlock could be considered. Actually, \\cite{thesisAle} includes it in the theory but it has not been included in this work.\n%\nThe reason is justified because to \\fUnlock a \\cell is equivalent to \\fLock a \\cell with \\fNoThread value.\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%\t\t\t\t\tMEMORY\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%\\begin{center}\\rule{4cm}{0.4pt} $\\Sigma_{\\mem}$ \\rule{4cm}{0.4pt}\\end{center}\n\\paragraph{$\\Sigma_{\\mem}$ : }\n%\nThe sorts used are \\mem,\\cell and \\addr. \n\n\\begin{center}\n\\begin{tabular}{|rrl|}\n  \\hline\n\\fNull & $\\addr$ & Null address \\\\\n\\fRd & $\\mem\\times\\addr\\to\\cell$ & Models memory deference. \\\\\n&&\t\t\t\t\t\t\t\t\\;\\;\\; Returns the value from the \\mem the \\cell \\\\\n&&\t\t\t\t\t\t\t\t\\;\\;\\; stored in the \\addr.\\\\\n\\fUpd & $\\mem\\times\\addr\\times\\cell\\to\\mem$ & Creates a new \\mem from the given one\n\\\\\\hline\n\\end{tabular}\n%\\caption{\\textbf{Functions of $\\Sigma_{\\mem}$} theory}\n\\label{table:memory_signature}\n\\end{center}\n\nA function related with \\mem theory is \\fMalloc, used in the \\insertprg procedure.\n%\nThe function \\fMalloc does not belongs to \\gls{SPL} or \\TLLpL but it can be translated as a conjunction of assignments and assignments are allowed in both theories.\n%\nThe function \\fMalloc returns a new fresh address different to every other address in use, so the \\freshaddr returned by \\fMalloc is not equal to \\head, nor \\tail, etc.\n%\n\\fMalloc formal representation correspond to a big conjunction of all the formulas stating \\freshaddr is not equal to \\addr, for all \\addr appearing in the formula (except itself).\n%\\[\\forall x,y. [x\\neq y \\andcond x=\\fMalloc(h) \\implies h(x)\\neq h(y)]\\]\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%\t\t\t\t\tSETADDR\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%\\begin{center}\\rule{4cm}{0.4pt} $\\Sigma_{\\sSetAddr}$ \\rule{4cm}{0.4pt}\\end{center}\n\\paragraph{$\\Sigma_{\\sSetAddr}$ : }\n%\nIt models the usual set theory. \n%\nWe preferred a prefix version of each function and predicate to be consistent with Section \\ref{ax::fulllist}.\n%\n\n\nThe intersection function and the subset predicate have not been included, even tough \\citep{thesisAle} uses them. \n%\nThey were not used because they were redundant.\n\n\\begin{center}\n\\begin{tabular}{|rrl|}\n  \\hline\n\\fEmptyset & \\sSetAddr & Empty set\\\\\n\\fSingl & $\\addr\\to\\sSetAddr $& Constructor of a single-element set.\\\\\n\\fUnion & $\\sSetAddr\\times\\sSetAddr\\to\\sSetAddr$&\\\\\n\\fSetdiff & $\\sSetAddr\\times\\sSetAddr\\to\\sSetAddr$&\\\\\n\\hline\\hline\n\\pIn & $\\sAddr\\times\\sSetAddr $& \n\\\\\\hline\n\\end{tabular}\n%\\caption{\\textbf{Signature of $\\Sigma_{\\sSetAddr}$.} The top block contains the functions and the lower block lists the predicates.}\n\\label{table:setaddr_signature}\n\\end{center}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%\t\t\t\t\tSETELEM\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%\\begin{center}\\rule{4cm}{0.4pt} $\\Sigma_{\\sSetElem}$ \\rule{4cm}{0.4pt}\\end{center}\n\\paragraph{$\\Sigma_{\\sSetElem}$ : }\n%\nAgain, it models the usual set theory.\n%\nThe signature is described in Table \\ref{table:setelem_signature}.\n\n\\begin{center}\n\\begin{tabular}{|rrl|}\n  \\hline\n\\fEmptysetElem & $\\sSet $& Empty set\\\\\n\\fSinglElem & $\\elem\\to\\sSet $& Constructor of a single-element set.\\\\\n\\fUnionElem & $\\sSet\\times\\sSet\\to\\sSet$&\\\\\n\\fSetdiffElem & $\\sSet\\times\\sSet\\to\\sSet$&\\\\\n\\hline\\hline\n\\pInElem & $\\sAddr\\times\\sSet $& \n\\\\\\hline\n\\end{tabular}\n%\\caption{\\textbf{Signature of $\\Sigma_{\\sSetElem}$.} The top block contains the functions and the lower block lists the predicates.}\n\\label{table:setelem_signature}\n\\end{center}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%\t\t\t\t\tSETTID\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%\\begin{center}\\rule{4cm}{0.4pt} $\\Sigma_{\\sSetTid}$ \\rule{4cm}{0.4pt}\\end{center}\n\\paragraph{$\\Sigma_{\\sSetTid}$ : }\n%\nThe signature is described in Table \\ref{table:settid_signature}.\n\n\\begin{center}\n\\begin{tabular}{|rrl|}\n  \\hline\n\\fEmptysetTid & $\\sSetAddr $& Empty set\\\\\n\\fSinglTid & $\\addr\\to\\sSetAddr $& Constructor of a single-element set.\\\\\n\\fUnionTid & $\\sSetAddr\\times\\sSetAddr\\to\\sSetAddr$&\\\\\n\\fSetdiffTid & $\\sSetAddr\\times\\sSetAddr\\to\\sSetAddr$&\\\\\n\\hline\\hline\n\\pInTid & $\\sAddr\\times\\sSetAddr$ &\n\\\\\\hline\n\\end{tabular}\n%\\caption{\\textbf{Signature of $\\Sigma_{\\sSetAddr}$.} The top block contains the functions and the lower block lists the predicates.}\n\\label{table:settid_signature}\n\\end{center}\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%\t\t\t\t\tBRIDGE\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%\\begin{center}\\rule{4cm}{0.4pt} $\\Sigma_{Bridge}$ \\rule{4cm}{0.4pt}\\end{center}\n\\paragraph{$\\Sigma_{Bridge}$ : }\n%\nThis theory is much more extensive in \\cite{thesisAle}. \n%\nHowever, aiming for simplicity, we do not include every function and predicate because we do not use them in our proofs. \n%\nThe only function used in the proofs is:\n\\begin{center}\n\\begin{tabular}{|rrl|}\n  \\hline\n\\fAddrToSet & $\\mem\\times\\addr\\to\\sSetAddr $& Returns the set of \\addr reachable from the \\addr given.\\\\\n\\hline\n\\end{tabular}\n%\\caption{\\textbf{Signature of $\\Sigma_{\\sSetAddr}$.}}\n\\label{table:bridge_signature}\n\\end{center}\n\n\n\n", "meta": {"hexsha": "604fa3c3c31c1c6673d1ac8d150e400fbd76fe84", "size": 20221, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/design.tex", "max_stars_repo_name": "VicdeJuan/tfg", "max_stars_repo_head_hexsha": "ee2c372816b111620bf30f470decd60685f15a21", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/design.tex", "max_issues_repo_name": "VicdeJuan/tfg", "max_issues_repo_head_hexsha": "ee2c372816b111620bf30f470decd60685f15a21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/design.tex", "max_forks_repo_name": "VicdeJuan/tfg", "max_forks_repo_head_hexsha": "ee2c372816b111620bf30f470decd60685f15a21", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-01-21T12:44:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-29T11:14:52.000Z", "avg_line_length": 36.368705036, "max_line_length": 202, "alphanum_fraction": 0.6872558232, "num_tokens": 5373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.31917933336950305}}
{"text": "\\documentclass{beamer}\n\\usepackage{appendixnumberbeamer}\n\n\\mode<presentation>{\\usetheme[subsectionpage=progressbar,block=fill,numbering=none]{metropolis}}\n\n\\usepackage[sfdefault]{FiraSans} %% option 'sfdefault' activates Fira Sans as the default text font\n\\usepackage[english]{babel}\n% \\usepackage[utf8]{inputenc}\n\n\\usepackage{graphicx} % Allows including images\n\\usepackage{caption}\n\\usepackage{booktabs} % Allows the use of \\toprule, \\midrule and \\bottomrule in tables\n\\usepackage{multicol}\n\n% Math packages\n\\usepackage{amsmath}\n\\usepackage{mathtools}\n\\usepackage{amssymb}\n\\usepackage{mathpartir}\n\\usepackage{stmaryrd}\n\\usepackage{centernot}\n\\usepackage[normalem]{ulem}\n\n%% Coding\n\\usepackage[outputdir=build]{minted}\n\n% Coloured boxes\n\\usepackage{tcolorbox}\n\\colorlet{alert}{mLightBrown}\n\\colorlet{mLightBrownTransparent}{white!70!mLightBrown}\n\\newtcolorbox{alertbox}\n{standard jigsaw, opacityback=0,colframe=alert}\n\\newtcolorbox{tbox}\n{standard jigsaw, opacityback=0,opacityframe=0}\n\n%% Quotes with author\n\\usepackage{xparse}\n\n\\let\\oldquote\\quote\n\\let\\endoldquote\\endquote\n\n\\RenewDocumentEnvironment{quote}{o}\n  {\\oldquote}\n  {\\IfValueT{#1}{\\par\\nobreak\n   \\hfill--- #1}\\endoldquote\\addvspace{\\smallskipamount}}\n\n\\newcommand{\\dotcup}{\\mathbin{\\mathaccent\\cdot\\cup}}\n\\newcommand{\\fromto}[2]{\\{#1,\\dotsc,#2\\}}\n\\newcommand{\\denot}[1]{\\llbracket#1\\rrbracket}\n\\newcommand{\\listt}[1]{\\mathsf{List}~#1}\n\\newcommand{\\map}{\\mathsf{map}}\n\\newcommand{\\haskell}[1]{\\mintinline{haskell}{#1}}\n\\newcommand{\\vint}[1]{\\mathcal{V}\\denot{#1}}\n\\newcommand{\\tint}[1]{\\mathcal{E}\\denot{#1}}\n\\newcommand{\\wt}[1]{\\mathsf{wt}_{#1}}\n\\newcommand{\\rels}{\\mathcal{R}}\n\\newcommand{\\values}{Val}\n\\newcommand{\\bool}{\\mathsf{Bool}}\n\\newcommand{\\nat}{\\mathsf{Nat}}\n\\newcommand{\\zero}{\\mathsf{0}}\n\\newcommand{\\suc}{\\mathsf{succ}}\n\\newcommand{\\pair}{\\mathsf{pair}}\n\\newcommand{\\true}{\\mathsf{true}}\n\\newcommand{\\false}{\\mathsf{false}}\n\\newcommand{\\nil}{\\mathsf{nil}}\n\\newcommand{\\cons}{\\mathsf{cons}}\n\\newcommand{\\length}{\\mathsf{length}}\n\\newcommand{\\eq}{\\mathsf{eq}}\n\\newcommand{\\cmp}{\\mathsf{cmp}}\n\\newcommand{\\nf}[1]{#1{\\downarrow}}\n\\newcommand{\\eqnf}{=^*}\n\n\n\\title{Theorems for Free!} % the title on the title page\n\\subtitle{by Philip Wadler}\n\n\\author{Kevin Kappelmann} % Your name\n\\institute[TU Munich]{Technical University of Munich}\n\\date{May 27, 2021} % Date, can be changed to a custom date\n\n\\begin{document}\n\n\\maketitle\n\n%------------------------------------------------\n\\section{Type Systems and Polymorphism}\n% \\begin{frame}[fragile]{Haskell Has Types}\n\n% \\begin{minted}{haskell}\n% appTwice :: (Int -> Int) -> Int -> Int\n% appTwice f x = f (f x)\n% \\end{minted}\n\n% \\pause\n% \\centering What is the result of\\dotso\n\n% \\begin{uncoverenv}<3>\n% \\begin{onlyenv}<1-3>\n% \\begin{minted}{haskell}\n% appTwice (*2) 1 = ?\n% \\end{minted}\n% \\end{onlyenv}\n% \\end{uncoverenv}\n\n% \\begin{onlyenv}<4>\n% \\begin{minted}{haskell}\n% appTwice (*2) 1 = 4\n% \\end{minted}\n% \\end{onlyenv}\n\n% \\begin{onlyenv}<5>\n% \\begin{minted}{haskell}\n% appTwice (*2) 1 = 4\n% appTwice (*2) \"bogus\" = ?\n% \\end{minted}\n% \\end{onlyenv}\n\n% \\begin{onlyenv}<6>\n% \\begin{minted}{haskell}\n% appTwice (*2) 1 = 4\n% appTwice (*2) \"bogus\" = ...\n% \\end{minted}\n% \\begin{alertbox}\n% \\begin{minted}[escapeinside=??]{bash}\n% • Couldn?'?t match expected type ‘Int’ with\n  % actual type ‘[Char]’\n% • In the second argument of ‘appTwice’,\n  % namely ‘\"bogus\"’\n  % In the expression: appTwice (*2) \"bogus\"...\n% \\end{minted}\n% \\end{alertbox}\n% \\end{onlyenv}\n% \\end{frame}\n\n% \\begin{frame}\n% \\centering\n% \\Huge Thank you, type system!\n% \\end{frame}\n\n% \\begin{frame}{What is a Type System?}\n\n% {\\Large Type systems are mechanisms that guarantee the absence of certain programming errors.}\n\n% \\pause\n% \\vspace{3\\baselineskip}\n% \\centering{\\alert{\\large \\dotso is there a catch?}}\n% \\end{frame}\n\n\\begin{frame}[fragile]{Sigh, Just Apply It Twice!}\n\\begin{minted}{haskell}\nappTwice :: (Int -> Int) -> Int -> Int\nappTwice f x = f (f x)\n\\end{minted}\n\n\\centering What is the result of\\dotso\n\n\\begin{onlyenv}<1-2>\n\\begin{uncoverenv}<2>\n\\begin{minted}{haskell}\nappTwice (*2) 1 = ?\n\\end{minted}\n\\end{uncoverenv}\n\\end{onlyenv}\n\n\\begin{onlyenv}<3>\n\\begin{minted}{haskell}\nappTwice (*2) 1 = 4\n\\end{minted}\n\\end{onlyenv}\n\n\\begin{onlyenv}<4>\n\\begin{minted}{haskell}\nappTwice (*2) 1 = 2\nappTwice (*2) \"bogus\" = ?\n\\end{minted}\n\\end{onlyenv}\n\n\\begin{onlyenv}<5>\n\\begin{minted}{haskell}\nappTwice (*2) 1 = 2\nappTwice (*2) \"bogus\" = ...\n\\end{minted}\n\\end{onlyenv}\n\n\\begin{onlyenv}<1-5>\n\\begin{uncoverenv}<5>\n\\begin{alertbox}\n\\begin{minted}[escapeinside=??]{bash}\n• Couldn?'?t match expected type ‘Int’ with\n  actual type ‘[Char]’\n• In the second argument of ‘appTwice’,\n  namely ‘\"bogus\"’\n  In the expression: appTwice (*2) \"bogus\"...\n\\end{minted}\n\\end{alertbox}\n\\end{uncoverenv}\n\\end{onlyenv}\n\n\\begin{onlyenv}<6>\n\\begin{minted}{haskell}\nappTwice (*2) 1 = 2\nappTwice (++\"l\") \"haske\" = ?\n\\end{minted}\n\\end{onlyenv}\n\n\\begin{onlyenv}<7>\n\\begin{minted}{haskell}\nappTwice (*2) 1 = 2\nappTwice (++\"l\") \"haske\" = ...\n\\end{minted}\n\\end{onlyenv}\n\n\\begin{onlyenv}<6->\n\\begin{uncoverenv}<7->\n\\begin{alertbox}\n\\begin{minted}[escapeinside=??]{bash}\n• Couldn?'?t match type ‘[Char]’ with ‘Int’\n  Expected type: Int -> Int\n  Actual type: [Char] -> [Char]\n• In the first argument of ‘appTwice’,\n  namely ‘(++\"l\")’\n  In the expression: appTwice (++\"l\") \"haske\"...\n\\end{minted}\n\\end{alertbox}\n\\end{uncoverenv}\n\\end{onlyenv}\n\n\\end{frame}\n\n% \\begin{frame}[fragile]{Do Not Repeat Yourself}\n% Well then, let us fix this problem:\n\n% \\begin{onlyenv}<1-3>\n% \\begin{uncoverenv}<2-3>\n% \\begin{minted}{haskell}\n% appTwiceInt :: (Int -> Int) -> Int -> Int}\n% appTwiceInt f x = f (f x)\n\n% appTwiceString :: (String -> String) -> String -> String\n% appTwiceString f x = f (f x)\n% \\end{minted}\n% \\end{uncoverenv}\n% \\end{onlyenv}\n\n% \\begin{onlyenv}<4>\n% \\begin{minted}[highlightlines={2,5},highlightcolor=mLightBrownTransparent]{haskell}\n% appTwiceInt :: (Int -> Int) -> Int -> Int}\n% appTwiceInt f x = f (f x)\n\n% appTwiceString :: (String -> String) -> String -> String\n% appTwiceString f x = f (f x)\n% \\end{minted}\n% \\end{onlyenv}\n% \\only<1-3>{\\uncover<3>{And we are happy again:}}\n% \\only<4>{And we are \\sout{happy} \\alert{unhappy} again:}\n\n% \\begin{uncoverenv}<3->\n% \\begin{minted}{haskell}\n% appTwiceInt (*2) 1 = 4\n% appTwiceSting (++\"l\") \"haske\" = \"haskell\"\n% \\end{minted}\n% \\end{uncoverenv}\n% \\end{frame}\n\n% \\begin{frame}{The \\emph{Abstraction Principle}}\n% \\begin{quote}[Benjamin Pierce]\n% Each significant piece of functionality in a program should be implemented in just one place in the source code. Where similar functions are carried out by distinct pieces of code, it is generally beneficial to combine them into one by abstracting out the varying parts.\n% \\end{quote}\n% \\end{frame}\n\n\\begin{frame}[fragile]{Polymorphism to the Rescue!}\nHaskell knows \\emph{parametric polymorphism}: we\ncan abstract over types by using type variables.\n\n\\pause\n\n\\begin{minted}{haskell}\nappTwice :: (a -> a) -> a -> a\nappTwice f x = f (f x)\n\\end{minted}\n\n\\pause\nAnd we are happy:\n\n\\begin{minted}{haskell}\nappTwice (*2) 1 = 4\nappTwice (++\"l\") \"haske\" = \"haskell\"\n\\end{minted}\n\n\\pause\n\\centering {\\large End of the story? \\pause \\alert{Of course not!}}\n\n\\end{frame}\n\n\\begin{frame}\n\\centering {\\Huge Polymorphism comes with another twist!}\n\\end{frame}\n\n\\begin{frame}[fragile]{Black Magic}\nI show you a term's type but not its definition.\nYou tell me the possible results:\n\\footnote{Let us forget about \\mintinline{haskell}{undefined} for a moment.}\n\n% \\begin{uncoverenv}<2>\n% \\begin{onlyenv}<1-2>\n% \\begin{minted}{haskell}\n% f :: a -> b -> a\n% -- def. of f hidden\n\n% f 42 \"hi\" = ?\n% f \"hi\" 42 = ?\n% \\end{minted}\n% \\end{onlyenv}\n% \\end{uncoverenv}\n\n% \\begin{onlyenv}<3>\n% \\begin{minted}{haskell}\n% f :: a -> b -> a\n% -- def. of f hidden\n\n% f 42 \"hi\" = 42\n% f \"hi\" 42 = \"hi\"\n% \\end{minted}\n% \\end{onlyenv}\n\n% \\begin{onlyenv}<4>\n% \\begin{minted}{haskell}\n% f :: a -> b -> a\n% f x y = x\n\n% f 42 \"hi\" = 42\n% f \"hi\" 42 = \"hi\"\n% \\end{minted}\n% \\end{onlyenv}\n\n\\begin{uncoverenv}<2>\n\\begin{onlyenv}<1-2>\n\\begin{minted}{haskell}\ng :: (a -> a) -> a -> a\n-- def. of g hidden\n\ng (*2) 1 =? 1\ng (*2) 1 =? 2\ng (*2) 1 =? 3\ng (*2) 1 =? 16\ng (*2) 1 =? 42\n\\end{minted}\n\\end{onlyenv}\n\\end{uncoverenv}\n\n\\begin{onlyenv}<3-4>\n\\begin{minted}[highlightlines={4,5,7},highlightcolor=mLightBrownTransparent]{haskell}\ng :: (a -> a) -> a -> a\n-- def. of g hidden\n\ng (*2) 1 =? 1\ng (*2) 1 =? 2\ng (*2) 1 /= 3\ng (*2) 1 =? 16\ng (*2) 1 /= 42\n\\end{minted}\n\\end{onlyenv}\n\n\\begin{onlyenv}<5>\n\\begin{minted}[highlightlines={7},highlightcolor=mLightBrownTransparent]{haskell}\ng :: (a -> a) -> a -> a\n-- def. of g hidden\n\ng (*2) 1 /= 1\ng (*2) 1 /= 2\ng (*2) 1 /= 3\ng (*2) 1 = 16\ng (*2) 1 /= 42\n\\end{minted}\n\\end{onlyenv}\n\n\\begin{onlyenv}<6>\n\\begin{minted}[highlightlines={7},highlightcolor=mLightBrownTransparent]{haskell}\ng :: (a -> a) -> a -> a\ng f x = f (f (f (f x)))\n\ng (*2) 1 /= 1\ng (*2) 1 /= 2\ng (*2) 1 /= 3\ng (*2) 1 = 16\ng (*2) 1 /= 42\n\\end{minted}\n\\end{onlyenv}\n\n\n\\uncover<4-6>{\nWhat if I told you that \\mintinline{haskell}{g (++\"I\") \"\" = \"IIII\"}?\n}\n\\end{frame}\n\n\\begin{frame}\n\\Large Polymorphic functions are defined once and for all for any type and as such must work uniformly on values of any type.\n\n\\pause\n\n\\Large From the type of a polymorphic function,\nwe can derive a theorem that it satisfies.\n\\end{frame}\n\n\\begin{frame}\n\\centering \\huge Polymorphic types provide us \\emph{theorems for free}.\n\\end{frame}\n\n\\section{Technical Development}\n\n\\begin{frame}{System F}\n\nThe polymorphic lambda calculus aka System F:\n\n\\pause\nTypes:\n\\begin{equation*}\n\\tau \\Coloneqq  \\alpha \\mid \\tau \\to \\tau \\mid \\forall \\alpha.\\ \\tau\n\\end{equation*}\n\n\\pause\nTerms:\n\\begin{equation*}\nt \\Coloneqq x \\mid \\lambda x : \\tau.\\ t \\mid t\\, t \\mid \\Lambda \\alpha.\\ t \\mid  t\\,[\\tau]\n\\end{equation*}\n\n\\pause\nValues:\n\\begin{equation*}\nv \\Coloneqq x\\mid \\lambda x : \\tau.\\ t \\mid \\Lambda \\alpha.\\ t\n\\end{equation*}\n\n\n\\pause\nHere is our \\mintinline{haskell}{appTwice} function:\n\\begin{align*}\n&\\Lambda \\alpha.\\,\\lambda f : \\alpha\\to\\alpha.\\,\\lambda x : \\alpha.\\, f\\ (f\\, x) : \\forall \\alpha.\\, (\\alpha\\to\\alpha)\\to\\alpha\\to\\alpha\n\\end{align*}\n\n\\pause\n\nWe can call it like this: \\mintinline{haskell}{appTwice [Int] (+1) 0}\n\\end{frame}\n\n\\begin{frame}[fragile]{Types as Relations}\n\\only<1>{It is natural to interpret a type $\\tau$ as a set $\\denot{\\tau}$ containing all values of type $\\tau$, e.g. $\\denot{\\mintinline{haskell}{Bool}}=\\{\\mintinline{haskell}{True,False}\\}$ in Haskell.}\n\\only<2>{\\sout{It is natural to interpret a type $\\tau$ as a set $\\denot{\\tau}$ containing all values of type $\\tau$, e.g. $\\denot{\\mintinline{haskell}{Bool}}=\\{\\mintinline{haskell}{True,False}\\}$ in Haskell.}}\n\n% \\pause\n\n% The key idea to derive free theorems is to instead interpret a \\emph{type as a relation} that\n% \\begin{enumerate}[<+->]\n% \\item relates terms of the given type and\n% \\item whose membership is preserved under eliminating forms.\n% \\end{enumerate}\n\n\\vspace{\\baselineskip}\n\n\\uncover<2>{\\centering \\Large New slogan: \\alert{types relate terms and related terms lead to related results.}}\n\\end{frame}\n\n\\begin{frame}{Types as Relations: Examples}\n\\begin{columns}\n\t\\column{\\dimexpr\\paperwidth-10pt}\n\\begin{itemize}[<+->]\n  \\item Base types are interpreted as their identity relation,\n    e.g.\\\n    $\\denot{\\haskell{Bool}}=\\{(\\haskell{True,True}),(\\haskell{False,False})\\}$.\n  \\item Two pairs are related if their components are related, i.e.\n\\vspace{-0.5\\baselineskip}\n\\begin{equation*}\n\t\\bigl((t_1,t_2),(t_1',t_2')\\bigr)\\in\\denot{(\\tau_1,\\tau_2)} \\iff (t_1,t_1')\\in\\denot{\\tau_1}\\land (t_2,t_2')\\in\\denot{\\tau_2}.\n\\end{equation*}\n  \\item Two lists are related if they have the same length and their elements are related, i.e.\n\\vspace{-0.5\\baselineskip}\n\\begin{align*}\n&\\bigl([t_1,\\dotsc,t_n],[t_1',\\dotsc,t_{n'}']\\bigr)\\in \\denot{\\listt{\\tau}}\\\\\n\\iff&n = n' \\land \\forall i\\in\\fromto{1}{n}.\\ (t_i,t_i')\\in \\denot{\\tau}.\n\\end{align*}\n  \\item Two functions are related if they map related arguments to related results, i.e.\n\\vspace{-0.5\\baselineskip}\n\\begin{equation*}\n\t(f,f')\\in \\denot{\\tau_1 \\to \\tau_2} \\iff \\forall (t,t')\\in \\denot{\\tau_1}.~\\bigl(f\\, t, f'\\, t'\\bigr)\\in\\denot{\\tau_2}.\n\\end{equation*}\n\\end{itemize}\n\\end{columns}\n\\end{frame}\n\n\\begin{frame}{Recipe for Logical Relations}\nA \\emph{logical relation} $R\\denot{\\tau}$ is an inductive family of relations indexed by types.\n\n\n\\pause\nIf we want to prove a property $P$ for the terms of our language,\nwe construct $R\\denot{\\tau}$ in a way such that:\n\\begin{enumerate}[<+->]\n  \\item If $R\\denot{\\tau}\\bigl(t_1,\\dotsc,t_n\\bigr)$ then\n  \\begin{enumerate}\n    \\item $\\vdash t_i : \\tau$ for $1\\leq i \\leq n$ (we write $\\wt{\\tau}(t_1,\\dotsc,t_n)$)\n    \\item $P\\bigl(t_1,\\dotsc,t_n\\bigr)$\n  \\end{enumerate}\n  \\item The conditions of the relation are preserved by eliminating forms.\n\\end{enumerate}\n\n\\end{frame}\n\n\\begin{frame}{Our Logical Relation}\nWe split our logical relation into two parts:\n\\begin{enumerate}\n\\item $\\vint{\\tau}$ on values\n\\item $\\tint{\\tau}$ on general terms\n\\end{enumerate}\n\n\\pause\n\\begin{align*}\n  \\tint{\\tau}\\coloneqq\\bigl\\{(t_1,t_2)\\mid\n  \\wt{\\tau}(t_1,t_2)\\land (\\nf{t_1},\\nf{t_2})\\in\\vint{\\tau}\\bigr\\}\n\\end{align*}\n\n\\end{frame}\n\n\\begin{frame}{Relating Functions}\n\nIf we had a $\\haskell{Bool}$ base type, we would first define:\n\\begin{equation*}\n  \\vint{\\haskell{Bool}}\\coloneqq\\{(\\haskell{True,True}),(\\haskell{False,False})\\}\n\\end{equation*}\n\n\\pause\nAnd then continue with function types:\n\\begin{align*}\n  \\vint{\\tau_1\\to\\tau_2}\\coloneqq\n  \\Bigl\\{&(\\lambda x : \\tau_1.\\ t_1, \\lambda x : \\tau_1.\\ t_2) \\mid\\\\\n  \\onslide<3->{&\\phantom{\\land\\, }\\wt{\\tau_1\\to\\tau_2}(\\lambda x : \\tau_1.\\ t_1, \\lambda x : \\tau_1.\\ t_2)\\\\}\n  \\onslide<4->{&\\land\\forall (v_1,v_2)\\in\\vint{\\tau_1}.\\ \\bigl(t_1[v_1/x],t_2[v_2/x]\\bigr)\\in\\tint{\\tau_2}} \\Bigr\\}\n\\end{align*}\n% \\begin{align*}\n  % \\vint{\\tau_1\\to\\tau_2}_\\rho\\coloneqq\n  % \\Bigl\\{&\\bigl(\\lambda x : \\rho(\\tau_1).\\ t_1, \\lambda x : \\rho(\\tau_1).\\ t_2\\bigr) \\mid\\\\\n  % &\\phantom{\\land\\, }\\wt{\\rho(\\tau_1)\\to\\rho(\\tau_2)}\\bigl(\\lambda x : \\rho(\\tau_1).\\ t_1, \\lambda x : \\rho(\\tau_1).\\ t_2\\bigr)\\\\\n  % & \\land \\forall (v_1,v_2)\\in\\vint{\\tau_1}_\\rho.\\ \\bigl(t_1[v_1/x],t_2[v_2/x]\\bigr)\\in\\tint{\\tau_2}_\\rho \\Bigr\\}\n% \\end{align*}\n\\end{frame}\n\n\\begin{frame}{Relating Type Abstractions: First Try}\n\\begin{align*}\n  \\vint{\\forall \\alpha.\\ \\tau}\\coloneqq\n  \\Bigl\\{&(\\Lambda \\alpha.\\ t_1, \\Lambda \\alpha.\\ t_2) \\mid\\\\\n  \\onslide<2->{&\\phantom{\\land\\, }\\wt{\\forall \\alpha.\\, \\tau}(\\Lambda \\alpha.\\ t_1, \\Lambda \\alpha.\\ t_2)\\\\}\n  \\onslide<3->{&\\land\\forall \\tau_1,\\tau_2.\\ \\bigl(t_1[\\tau_1/\\alpha],t_2[\\tau_2/\\alpha]\\bigr)\\in\\tint{\\tau[?/\\alpha]}} \\Bigr\\}\n\\end{align*}\n\n\\uncover<4>{\n\\alert{Under which type should $t_1[\\tau_1/\\alpha]$ and $t_2[\\tau_2/\\alpha]$ be related under?}\n}\n\n\\end{frame}\n\n\\begin{frame}{Relating Type Abstractions: Second Try}\nTrick: keep track of the chosen types in a substitution $\\rho$\n\\pause\n\\begin{align*}\n  \\vint{\\forall \\alpha.\\ \\tau}_{\\alert{\\rho}}\\coloneqq\n  \\Bigl\\{&(\\Lambda \\alpha.\\ t_1, \\Lambda \\alpha.\\ t_2) \\mid\\\\\n   &\\phantom{\\land\\, }\\wt{\\forall \\alpha.\\, \\alert{\\rho(\\tau)}}(\\Lambda \\alpha.\\ t_1, \\Lambda \\alpha.\\ t_2)\\\\\n &\\land\\forall \\tau_1,\\tau_2.\\ \\bigl(t_1[\\tau_1/\\alpha],t_2[\\tau_2/\\alpha]\\bigr)\\in\\alert{\\tint{\\tau}_{\\rho[\\alpha\\mapsto(\\tau_1,\\tau_2)]}} \\Bigr\\},\n\\end{align*}\n\n\\end{frame}\n\n\\begin{frame}{Relating Variables: First Try}\n\\begin{align*}\n\\vint{\\alpha}_\\rho\\coloneqq\n  \\Bigl\\{&(v_1,v_2) \\mid\\\\\n  \\onslide<2->{&\\phantom{\\land\\, }\\wt{\\rho(\\alpha)}(v_1,v_2)}\\\\\n &\\onslide<3->{\\land\\ \\alert{?}}\\hspace{5cm}\\Bigr\\}\n\\end{align*}\n\n\\onslide<3>{\n\\alert{How should we relate values of possibly different types?}\n}\n\\end{frame}\n\n\\begin{frame}{Relating Type Abstractions: Final Version}\n\nIdea: whenever we pick two types $\\tau_1,\\tau_2$, we also pick a relation on $\\tau_1$ and $\\tau_2$.\n\\pause\n\\begin{align*}\n  \\vint{\\forall \\alpha.\\ \\tau}_\\rho\\coloneqq\n  \\Bigl\\{&(\\Lambda \\alpha.\\ t_1, \\Lambda \\alpha.\\ t_2) \\mid\\\\\n  &\\phantom{\\land\\, }\\wt{\\forall \\alpha.\\, \\rho(\\tau)}(\\Lambda \\alpha.\\ t_1, \\Lambda \\alpha.\\ t_2)\\\\\n  &\\land \\forall \\tau_1,\\tau_2,\\alert{R\\in\\rels(\\tau_1,\\tau_2)}.\\ \\\\\n  &\\quad\\bigl(t_1[\\tau_1/\\alpha],t_2[\\tau_2/\\alpha]\\bigr)\\in\\tint{\\tau}_{\\rho[\\alert{\\alpha\\mapsto(\\tau_1,\\tau_2,R)}]} \\Bigr\\},\n\\end{align*}\n\\pause\nwhere $R$ is just a relation of closed, well-typed values:\n\\begin{equation*}\n\\rels(\\tau_1,\\tau_2)\\coloneqq\\bigl\\{R\\in\\mathcal{P}(\\values\\times \\values)\\mid \\forall(v_1,v_2)\\in R.\\ \\wt{\\tau_1}(v_1)\\land\\wt{\\tau_2}(v_2)\\bigr\\}.\n\\end{equation*}\n\\end{frame}\n\n\\begin{frame}{Final Updates}\n\\begin{equation*}\n  \\vint{\\alpha}_\\rho\\coloneqq\n  \\bigl\\{(v_1,v_2) \\in R \\mid\n  \\wt{\\rho(\\alpha)}(v_1,v_2) \\land \\rho(\\alpha)=(\\tau_1,\\tau_2,R) \\bigr\\}\n\\end{equation*}\n\\pause\n\\begin{align*}\n  \\vint{\\tau_1\\to\\tau_2}_{\\alert{\\rho}}\\coloneqq\n    \\Bigl\\{&\\bigl(\\lambda x : \\alert{\\rho(\\tau_1)}.\\ t_1, \\lambda x : \\alert{\\rho(\\tau_1)}.\\ t_2\\bigr) \\mid\\\\\n&\\phantom{\\land\\, }\\wt{\\alert{\\rho(\\tau_1)}\\to\\alert{\\rho(\\tau_2)}}\\bigl(\\lambda x : \\alert{\\rho(\\tau_1)}.\\ t_1, \\lambda x : \\alert{\\rho(\\tau_1)}.\\ t_2\\bigr)\\\\\n& \\land \\forall (v_1,v_2)\\in\\vint{\\tau_1}_{\\alert{\\rho}}.\\ \\bigl(t_1[v_1/x],t_2[v_2/x]\\bigr)\\in\\tint{\\tau_2}_{\\alert{\\rho}} \\Bigr\\}\n\\end{align*}\n\\begin{align*}\n  \\tint{\\tau}_{\\alert{\\rho}}\\coloneqq\\bigl\\{(t_1,t_2)\\mid\n  \\wt{\\alert{\\rho(\\tau)}}(t_1,t_2)\\land (\\nf{t_1},\\nf{t_2})\\in\\vint{\\tau}_{\\alert{\\rho}}\\bigr\\}\n\\end{align*}\n\\end{frame}\n\n\\begin{frame}{Parametricity Theorem}\n\\begin{theorem}[Parametricity Theorem]\n  If $\\vdash t : \\tau$ then\n  $(t,t\\bigr)\\in\\tint{\\tau}_\\emptyset$.\n\\end{theorem}\n\n\\large In other words: \\alert{every closed, well-typed term is related to itself.}\n\n\\end{frame}\n\n\\section{Examples of Free Theorems}\n\n% \\begin{frame}{Natural Numbers}\n% Assume we have a base type $\\mathbb{N}$ with $\\suc : \\mathbb{N}\\to\\mathbb{N}$.\n\n% \\pause\n% Assume we are given some value $t : \\forall \\alpha.\\, (\\alpha\\to\\alpha)\\to\\alpha\\to\\alpha$, a type $\\tau$, and values $s : \\tau\\to\\tau$ and $z : \\tau$.\n% What is the result of $t\\,[\\tau]\\,s\\,z$?\n\n% \\pause\n% Set $R\\coloneqq \\bigl\\{(n,\\nf{(s^n\\, z)})\\mid n\\in\\mathbb{N}\\bigr\\}$ and note that $(\\suc, s)\\in\\vint{\\alpha\\to\\alpha}_{[\\alpha\\mapsto(\\mathbb{N},\\tau,R)]}$:\\\\\n% \\pause If $(v_1,v_2)\\in\\vint{\\alpha}_{[\\alpha\\mapsto(\\mathbb{N},\\tau,R)]}$\n% then $(v_1,v_2)=\\bigl(n,\\nf{(s^n\\, z)}\\bigr)$ for some $n$.\n% Thus $(\\suc\\,v_1,s\\,v_2)\\eqnf\\bigl(n+1,\\nf{(s^{n+1}\\, z)}\\bigr)\\in R$.\n\n% \\pause\n% Hence, $\\bigl(t\\,[\\mathbb{N}]\\,\\suc\\, 0,t\\,[\\tau]\\,s\\,z\\bigr)\\in\\tint{\\alpha}_{[\\alpha\\mapsto(\\mathbb{N},\\tau,R)]}$ by the Parametricity Theorem.\n% \\pause So there is $v' : \\mathbb{N}$ and $v : \\tau$ such that\n% $t\\,[\\mathbb{N}]\\,\\suc\\, 0\\to^*v'$ and $t\\,[\\tau]\\,s\\,z\\to^*v$ and $(v',v)\\in R$.\n% \\pause Hence $v \\eqnf s^n\\, z$ where $n$ is determined by $t\\,[\\mathbb{N}]\\,\\suc\\, 0\\to^*v'\\eqnf n$.\n% \\end{frame}\n\n\\begin{frame}{Rearranging Lists}\nAssume we are given a value\n$t : \\forall \\alpha.\\, \\listt{\\alpha}\\to\\listt{\\alpha}$.\n\n\\pause\nWe show that\n\\begin{equation*}\n  \\forall \\alpha,\\alpha',(f : \\alpha\\to\\alpha'),(xs : \\listt{\\alpha}).\\, \\map\\,f\\,(t\\,[\\alpha]\\,xs)\\eqnf t\\,[\\alpha']\\,(\\map\\,f\\,xs)\n\\end{equation*}\n\n\\pause\nPick any $\\tau,\\tau',f : \\tau\\to\\tau'$.\n\\pause\nBy the Parametricity Theorem, for any $R$ and $(xs,xs')\\in\\vint{\\listt{\\alpha}}_{[\\alpha\\mapsto(\\tau,\\tau',R)]}$, we have $(t\\,[\\tau]\\, xs,t\\,[\\tau']\\, xs')\\in\\tint{\\listt{\\alpha}}_{[\\alpha\\mapsto(\\tau,\\tau',R)]}$.\n\n\\pause\nIf we specialise $R=\\bigl\\{(v,\\nf{(f\\, v)})\\mid \\wt{\\tau}(v)\\bigr\\}$,\nthe property $(xs,xs')\\in\\vint{\\listt{\\alpha}}_{[\\alpha\\mapsto(\\tau,\\tau',R)]}$\ntranslates to $xs'\\eqnf \\map\\, f\\, xs$.\n\n\\pause\nSimilarly,\n$\\bigl(t\\,[\\tau]\\, xs,t\\,[\\tau']\\, xs'\\bigr)\\in\\tint{\\listt{\\alpha}}_{[\\alpha\\mapsto(\\tau,\\tau',R)]}$\ntranslates to\n$t\\, [\\tau']\\,xs' \\eqnf \\map\\,f\\,(t\\,[\\tau]\\, xs)$.\n\n\\pause\nPutting it together: $t\\, [\\tau']\\,(\\map\\, f\\, xs) \\eqnf \\map\\,f\\,(t\\,[\\tau]\\, xs)$.\n\\end{frame}\n\n\\begin{frame}{Negative Results}\nNote that in Haskell \\haskell{undefined :: forall a. a}.\nCan we define such a term in System F?\n\n\\pause\nAssume there is a value $u : \\forall \\alpha.\\, \\alpha$.\nPick any $\\tau,\\tau'$ and set $R=\\emptyset$.\n\\pause\nThen by the Parametricity Theorem,\n$\\bigl(u\\,[\\tau],u[\\tau']\\bigr)\\in R=\\emptyset$,\nwhich is impossible.\n\n\\end{frame}\n\n\\section{Going Beyond System F}\n\\begin{frame}{Further Applications and Extensions}\n\\begin{enumerate}[<+->]\n\\item Representation independence of abstract data types\n\\item Free Theorems for non-total extensions with general recursion\n\\item Free Theorems for recursive data types\n\\item Free Theorems for type constructors and type classes\n\\item Free Theorems for pure type systems (and hence in particular for dependent type systems)\n\\item Free Theorems for gradually typed systems\n\\item Free Theorems in interactive theorem provers (Isabelle: transfer)\n\\end{enumerate}\n\\end{frame}\n\n\\begin{frame}\n\n\\begin{quote}[Wadler]\n\\Large How useful are the [free] theorems so generated? Only time and experience will tell\\dots\n\\end{quote}\n\n\\pause\n\\vspace{\\baselineskip}\n\\begin{quote}[Me]\nIt kicked off much fruitful research and the results can indeed be very useful in formal verification.\n\\end{quote}\n\\end{frame}\n\n%------------------------------------------------\n\\begin{frame}[standout]\n\\Large{\\alert{Any questions?}}\n\n\\includegraphics[scale=0.49]{wadlers.jpg}\n\\end{frame}\n%----------------------------------------------------------------------------------------\n%\\begin{frame}[allowframebreaks]{References}\n  %\\bibliography{../paper/sources.bib}\n  %\\bibliographystyle{abbrv}\n%\\end{frame}\n\n% \\begin{frame}[allowframebreaks]{Image Sources}\n% \\begin{itemize}\n% \\end{itemize}\n% \\end{frame}\n\n\\begin{frame}{Natural Numbers}\nAssume we have a base type $\\mathbb{N}$ with $\\suc : \\mathbb{N}\\to\\mathbb{N}$.\n\n\\pause\nAssume we are given some value $t : \\forall \\alpha.\\, (\\alpha\\to\\alpha)\\to\\alpha\\to\\alpha$, a type $\\tau$, and values $s : \\tau\\to\\tau$ and $z : \\tau$.\nWhat is the result of $t\\,[\\tau]\\,s\\,z$?\n\n\\pause\nSet $R\\coloneqq \\bigl\\{(n,\\nf{(s^n\\, z)})\\mid n\\in\\mathbb{N}\\bigr\\}$ and note that $(\\suc, s)\\in\\vint{\\alpha\\to\\alpha}_{[\\alpha\\mapsto(\\mathbb{N},\\tau,R)]}$:\\\\\n\\pause If $(v_1,v_2)\\in\\vint{\\alpha}_{[\\alpha\\mapsto(\\mathbb{N},\\tau,R)]}$\nthen $(v_1,v_2)=\\bigl(n,\\nf{(s^n\\, z)}\\bigr)$ for some $n$.\nThus $(\\suc\\,v_1,s\\,v_2)\\eqnf\\bigl(n+1,\\nf{(s^{n+1}\\, z)}\\bigr)\\in R$.\n\n\\pause\nHence, $\\bigl(t\\,[\\mathbb{N}]\\,\\suc\\, 0,t\\,[\\tau]\\,s\\,z\\bigr)\\in\\tint{\\alpha}_{[\\alpha\\mapsto(\\mathbb{N},\\tau,R)]}$ by the Parametricity Theorem.\n\\pause So there is $v' : \\mathbb{N}$ and $v : \\tau$ such that\n$t\\,[\\mathbb{N}]\\,\\suc\\, 0\\to^*v'$ and $t\\,[\\tau]\\,s\\,z\\to^*v$ and $(v',v)\\in R$.\n\\pause Hence $v \\eqnf s^n\\, z$ where $n$ is determined by $t\\,[\\mathbb{N}]\\,\\suc\\, 0\\to^*v'\\eqnf n$.\n\\end{frame}\n\n\\begin{frame}{Negative Results II}\nWe cannot define a polymorphic equality function $\\eq : \\forall \\alpha.\\, \\alpha\\to\\alpha\\to\\bool$:\n\nWe would get $\\eq\\,[\\tau]\\,v_1\\,v_2 \\eqnf \\eq\\,[\\tau']\\,(f\\,v_1)\\,(f\\,v_2)$ for any $f : \\tau\\to\\tau',v_1 : \\tau,v_2 : \\tau$.\n\\end{frame}\n\n\n\\end{document}\n", "meta": {"hexsha": "e990e870716640cab54344f9a8978b74d83ec647", "size": 23021, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "presentation/presentation_theorems_for_free.tex", "max_stars_repo_name": "kappelmann/seminar_theorems_for_free", "max_stars_repo_head_hexsha": "e043636b913164cd6aff73afca8e61305c623b8a", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "presentation/presentation_theorems_for_free.tex", "max_issues_repo_name": "kappelmann/seminar_theorems_for_free", "max_issues_repo_head_hexsha": "e043636b913164cd6aff73afca8e61305c623b8a", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "presentation/presentation_theorems_for_free.tex", "max_forks_repo_name": "kappelmann/seminar_theorems_for_free", "max_forks_repo_head_hexsha": "e043636b913164cd6aff73afca8e61305c623b8a", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9752604167, "max_line_length": 272, "alphanum_fraction": 0.6534468529, "num_tokens": 8851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3191504470240181}}
{"text": "\\section{\\src{dyn_vert_adv_limiter}}\n\\label{dyn_vert_adv_limiter}\n\n\\subsection{Description}\n\nKernel \\src{dyn_vert_adv_limiter} is taken from the original\nsubroutine \\src{vertical_limiter_thuburn} in \\NICAM.\n%\nThis subroutine is originally defined in \\src{mod_src_tracer}, that is\nto contain several subroutines for tracer advection.\n%\nSubroutine \\src{vertical_limiter_thuburn} is to ensure distribution of\ntracer quantities' monotonicity in advection scheme, using the flux\nlimitter proposed by \\cite{Thuburn:1996in}.\n%\nThis subroutine is for vertical advection only and horizontal advection\nis treated by other subroutine \\src{horizontal_limiter_thuburn}, which\nis also kernelized in this pacakage (See \\autoref{dyn_horiz_adv_limiter}).\n%\nSee section 4. in \\cite{Tomita2010ecmwf} for details of the tracer scheme in \\NICAM.\n\n\n\\subsection{Discretization and code}\n\nArgument lists and local variables definition part of this subroutine is\nas follows.\n\n\\begin{LstF90}[name=vertical_limiter_thuburn]\nsubroutine vertical_limiter_thuburn( &\n     q_h, q_h_pl, &\n     q,   q_pl,   &\n     d,   d_pl,   &\n     ck,  ck_pl   )\n!ESC!    use mod_const, only: &\n!ESC!       CONST_HUGE, &\n!ESC!       CONST_EPS\n!ESC!    use mod_adm, only: &\n!ESC!       ADM_have_pl, &\n!ESC!       ADM_gall,    &\n!ESC!       ADM_gall_pl, &\n!ESC!       ADM_lall,    &\n!ESC!       ADM_lall_pl, &\n!ESC!       ADM_kall,    &\n!ESC!       ADM_kmin,    &\n!ESC!       ADM_kmax\n  implicit none\n\n  real(RP), intent(inout) :: q_h   (ADM_gall   ,ADM_kall,ADM_lall   )\n  real(RP), intent(inout) :: q_h_pl(ADM_gall_pl,ADM_kall,ADM_lall_pl)\n  real(RP), intent(in)    :: q     (ADM_gall   ,ADM_kall,ADM_lall   )\n  real(RP), intent(in)    :: q_pl  (ADM_gall_pl,ADM_kall,ADM_lall_pl)\n  real(RP), intent(in)    :: d     (ADM_gall   ,ADM_kall,ADM_lall   )\n  real(RP), intent(in)    :: d_pl  (ADM_gall_pl,ADM_kall,ADM_lall_pl)\n  real(RP), intent(in)    :: ck    (ADM_gall   ,ADM_kall,ADM_lall   ,2)\n  real(RP), intent(in)    :: ck_pl (ADM_gall_pl,ADM_kall,ADM_lall_pl,2)\n\n  real(RP) :: Qout_min_k\n  real(RP) :: Qout_max_k\n  real(RP) :: Qout_min_km1(ADM_gall)\n  real(RP) :: Qout_max_km1(ADM_gall)\n  real(RP) :: Qout_min_pl(ADM_gall_pl,ADM_kall)\n  real(RP) :: Qout_max_pl(ADM_gall_pl,ADM_kall)\n\n  real(RP) :: Qin_minL, Qin_maxL\n  real(RP) :: Qin_minU, Qin_maxU\n  real(RP) :: qnext_min, qnext_max\n  real(RP) :: Cin, Cout\n  real(RP) :: CQin_min, CQin_max\n  real(RP) :: inflagL, inflagU\n  real(RP) :: zerosw\n\n  integer  :: gall, kmin, kmax\n  real(RP) :: EPS, BIG\n\n  integer  :: g, k, l\n  !---------------------------------------------------------------------------\n\\end{LstF90}\n%\nHere \\src{q_h} is $q$ at half level of the vertical layer, which modified by the flux limiter.\n%\n\\src{q} is $q$ at grid point,\n\\src{ck} is Courant number,\n\\src{d} is a correction factor derived from an artificial viscosity for the total density.\n%\nNote that \\src{ck} has the 4th dimension whose size is 2, which specify\nlower/upper face, i.e. half integer level.\n\n\n\nThe first section of the subroutine is as follows.\n\n\\begin{LstF90}[name=vertical_limiter_thuburn]\n  call DEBUG_rapstart('____vertical_adv_limiter')\n\n  gall = ADM_gall\n  kmin = ADM_kmin\n  kmax = ADM_kmax\n\n  EPS  = CONST_EPS\n  BIG  = CONST_HUGE\n\n  do l = 1, ADM_lall\n     !$omp parallel default(none), &\n     !$omp private(g,k,zerosw,inflagL,inflagU,Qin_minL,Qin_minU,Qin_maxL,Qin_maxU, &\n     !$omp         qnext_min,qnext_max,Cin,Cout,CQin_min,CQin_max,Qout_min_k,Qout_max_k),  &\n     !$omp shared(l,gall,kmin,kmax,q_h,ck,q,d,Qout_min_km1,Qout_max_km1,EPS,BIG)\n\n!OCL XFILL\n       !$omp do\n       do g = 1, gall\n          k = kmin ! peeling\n\n          inflagL = 0.5_RP - sign(0.5_RP,ck(g,k  ,l,1)) ! incoming flux: flag=1\n          inflagU = 0.5_RP + sign(0.5_RP,ck(g,k+1,l,1)) ! incoming flux: flag=1\n\n          Qin_minL = min( q(g,k,l), q(g,k-1,l) ) + ( 1.0_RP-inflagL ) * BIG\n          Qin_minU = min( q(g,k,l), q(g,k+1,l) ) + ( 1.0_RP-inflagU ) * BIG\n          Qin_maxL = max( q(g,k,l), q(g,k-1,l) ) - ( 1.0_RP-inflagL ) * BIG\n          Qin_maxU = max( q(g,k,l), q(g,k+1,l) ) - ( 1.0_RP-inflagU ) * BIG\n\n          qnext_min = min( Qin_minL, Qin_minU, q(g,k,l) )\n          qnext_max = max( Qin_maxL, Qin_maxU, q(g,k,l) )\n\n          Cin      = (        inflagL ) * ck(g,k,l,1) &\n                   + (        inflagU ) * ck(g,k,l,2)\n          Cout     = ( 1.0_RP-inflagL ) * ck(g,k,l,1) &\n                   + ( 1.0_RP-inflagU ) * ck(g,k,l,2)\n\n          CQin_min = (        inflagL ) * ck(g,k,l,1) * Qin_minL &\n                   + (        inflagU ) * ck(g,k,l,2) * Qin_minU\n          CQin_max = (        inflagL ) * ck(g,k,l,1) * Qin_maxL &\n                   + (        inflagU ) * ck(g,k,l,2) * Qin_maxU\n\n          zerosw = 0.5_RP - sign(0.5_RP,abs(Cout)-EPS) ! if Cout = 0, sw = 1\n\n          Qout_min_k = ( ( q(g,k,l) - qnext_max ) + qnext_max*(Cin+Cout-d(g,k,l)) - CQin_max ) &\n                     / ( Cout + zerosw ) * ( 1.0_RP - zerosw )                                 &\n                     + q(g,k,l) * zerosw\n          Qout_max_k = ( ( q(g,k,l) - qnext_min ) + qnext_min*(Cin+Cout-d(g,k,l)) - CQin_min ) &\n                     / ( Cout + zerosw ) * ( 1.0_RP - zerosw )                                 &\n                     + q(g,k,l) * zerosw\n\n          Qout_min_km1(g) = Qout_min_k\n          Qout_max_km1(g) = Qout_max_k\n       enddo\n       !$omp end do\n\n       do k = kmin+1, kmax\n!OCL XFILL\n          !$omp do\n          do g = 1, gall\n             inflagL = 0.5_RP - sign(0.5_RP,ck(g,k  ,l,1)) ! incoming flux: flag=1\n             inflagU = 0.5_RP + sign(0.5_RP,ck(g,k+1,l,1)) ! incoming flux: flag=1\n\n             Qin_minL = min( q(g,k,l), q(g,k-1,l) ) + ( 1.0_RP-inflagL ) * BIG\n             Qin_minU = min( q(g,k,l), q(g,k+1,l) ) + ( 1.0_RP-inflagU ) * BIG\n             Qin_maxL = max( q(g,k,l), q(g,k-1,l) ) - ( 1.0_RP-inflagL ) * BIG\n             Qin_maxU = max( q(g,k,l), q(g,k+1,l) ) - ( 1.0_RP-inflagU ) * BIG\n\n             qnext_min = min( Qin_minL, Qin_minU, q(g,k,l) )\n             qnext_max = max( Qin_maxL, Qin_maxU, q(g,k,l) )\n\n             Cin      = (        inflagL ) * ck(g,k,l,1) &\n                      + (        inflagU ) * ck(g,k,l,2)\n             Cout     = ( 1.0_RP-inflagL ) * ck(g,k,l,1) &\n                      + ( 1.0_RP-inflagU ) * ck(g,k,l,2)\n\n             CQin_min = (        inflagL ) * ck(g,k,l,1) * Qin_minL &\n                      + (        inflagU ) * ck(g,k,l,2) * Qin_minU\n             CQin_max = (        inflagL ) * ck(g,k,l,1) * Qin_maxL &\n                      + (        inflagU ) * ck(g,k,l,2) * Qin_maxU\n\n             zerosw = 0.5_RP - sign(0.5_RP,abs(Cout)-EPS) ! if Cout = 0, sw = 1\n\n             Qout_min_k = ( ( q(g,k,l) - qnext_max ) + qnext_max*(Cin+Cout-d(g,k,l)) - CQin_max ) &\n                        / ( Cout + zerosw ) * ( 1.0_RP - zerosw )                                 &\n                        + q(g,k,l) * zerosw\n             Qout_max_k = ( ( q(g,k,l) - qnext_min ) + qnext_min*(Cin+Cout-d(g,k,l)) - CQin_min ) &\n                        / ( Cout + zerosw ) * ( 1.0_RP - zerosw )                                 &\n                        + q(g,k,l) * zerosw\n\n             q_h(g,k,l) = (        inflagL ) * max( min( q_h(g,k,l), Qout_max_km1(g) ), Qout_min_km1(g) ) &\n                        + ( 1.0_RP-inflagL ) * max( min( q_h(g,k,l), Qout_max_k      ), Qout_min_k      )\n\n             Qout_min_km1(g) = Qout_min_k\n             Qout_max_km1(g) = Qout_max_k\n          enddo\n          !$omp end do\n       enddo\n\n     !$omp end parallel\n  enddo\n\n\\end{LstF90}\n%\nIn the long $l$-loop, there seems to be two blocks, but they are almost\nthe same, except that the first one is only for \\src{kmin}, that is the\nlowest level, and the second one is the rest of \\src{k} to the top level.\n%\n\\src{inflagL} and \\src{inflagU} are flag that takes the value $1$ if there is an\nincoming flux to the current layer through the lower/upper face.\n%\n\\src{Qin_*} are the smaller/larger values of $q$ at lower/upper\nneighboring layer, that is meaningful only if inflag at lower/upper is $1$.\n%\n\\src{Cin} and \\src{Cout} are the sum of Courant number at both face of\nthe layer, for example, \\src{Cin} is the sum of \\src{ck} at lower face\nand upper face, if both of \\src{inflagL} and \\src{inflagU} is $1$, which\nmeans that there are inflow through both lower/upper face.\n%\n\\src{CQin_*} are the min/max of \\src{Cin} times \\src{Qin_*}, which\nspecify the minimun/maximum of inflow.\n%\nThen \\src{CQout_*} are calculated.\n%\nFinaly \\src{q_h} is calculated, which is bounded by \\src{Qout_*}.\n\n\nThe second section of this subroutine is as follows.\n\n\\begin{LstF90}[name=vertical_limiter_thuburn]\n  if ( ADM_have_pl ) then\n     do l = 1, ADM_lall_pl\n\n        do k = ADM_kmin, ADM_kmax\n          do g = 1, ADM_gall_pl\n             inflagL = 0.5_RP - sign(0.5_RP,ck_pl(g,k  ,l,1)) ! incoming flux: flag=1\n             inflagU = 0.5_RP + sign(0.5_RP,ck_pl(g,k+1,l,1)) ! incoming flux: flag=1\n\n             Qin_minL = min( q_pl(g,k,l), q_pl(g,k-1,l) ) + ( 1.0_RP-inflagL ) * BIG\n             Qin_minU = min( q_pl(g,k,l), q_pl(g,k+1,l) ) + ( 1.0_RP-inflagU ) * BIG\n             Qin_maxL = max( q_pl(g,k,l), q_pl(g,k-1,l) ) - ( 1.0_RP-inflagL ) * BIG\n             Qin_maxU = max( q_pl(g,k,l), q_pl(g,k+1,l) ) - ( 1.0_RP-inflagU ) * BIG\n\n             qnext_min = min( Qin_minL, Qin_minU, q_pl(g,k,l) )\n             qnext_max = max( Qin_maxL, Qin_maxU, q_pl(g,k,l) )\n\n             Cin      = (        inflagL ) * ( ck_pl(g,k,l,1) ) &\n                      + (        inflagU ) * ( ck_pl(g,k,l,2) )\n             Cout     = ( 1.0_RP-inflagL ) * ( ck_pl(g,k,l,1) ) &\n                      + ( 1.0_RP-inflagU ) * ( ck_pl(g,k,l,2) )\n\n             CQin_max = (        inflagL ) * ( ck_pl(g,k,l,1) * Qin_maxL ) &\n                      + (        inflagU ) * ( ck_pl(g,k,l,2) * Qin_maxU )\n             CQin_min = (        inflagL ) * ( ck_pl(g,k,l,1) * Qin_minL ) &\n                      + (        inflagU ) * ( ck_pl(g,k,l,2) * Qin_minU )\n\n             zerosw = 0.5_RP - sign(0.5_RP,abs(Cout)-EPS) ! if Cout = 0, sw = 1\n\n             Qout_min_pl(g,k) = ( ( q_pl(g,k,l) - qnext_max ) + qnext_max*(Cin+Cout-d_pl(g,k,l)) - CQin_max ) &\n                              / ( Cout + zerosw ) * ( 1.0_RP - zerosw )                                       &\n                              + q_pl(g,k,l) * zerosw\n             Qout_max_pl(g,k) = ( ( q_pl(g,k,l) - qnext_min ) + qnext_min*(Cin+Cout-d_pl(g,k,l)) - CQin_min ) &\n                              / ( Cout + zerosw ) * ( 1.0_RP - zerosw )                                       &\n                              + q_pl(g,k,l) * zerosw\n          enddo\n          enddo\n\n        do k = ADM_kmin+1, ADM_kmax\n        do g = 1, ADM_gall_pl\n           inflagL = 0.5_RP - sign(0.5_RP,ck_pl(g,k,l,1)) ! incoming flux: flag=1\n\n           q_h_pl(g,k,l) = (        inflagL ) * max( min( q_h_pl(g,k,l), Qout_max_pl(g,k-1) ), Qout_min_pl(g,k-1) ) &\n                         + ( 1.0_RP-inflagL ) * max( min( q_h_pl(g,k,l), Qout_max_pl(g,k  ) ), Qout_min_pl(g,k  ) )\n        enddo\n        enddo\n\n     enddo\n  endif\n\n  call DEBUG_rapend  ('____vertical_adv_limiter')\n\n  return\nend subroutine vertical_limiter_thuburn\n\\end{LstF90}\n%\nThis section is for the pole region, and doing almost the same procedure\nwith the regular region.\n\n\n\n\\subsection{Input data and result}\n\n\nMax/min/sum of input/output data of the kernel subroutine are output as\na log.\n%\nBelow is an example of \\src{$IAB_SYS=Ubuntu-gnu-ompi} case.\n\n\\begin{LstLog}\n ### Input ###\n +check[q_h_prev        ] max=  7.2663804548391786E+00,min=  0.0000000000000000E+00,sum=  2.4959084727640115E+06\n +check[q_h_prev_pl     ] max=  6.4080655438269076E+00,min=  0.0000000000000000E+00,sum=  1.8117616747458535E+03\n +check[check_q_h       ] max=  7.3763287914601054E+00,min=  0.0000000000000000E+00,sum=  2.4996023860691669E+06\n +check[check_q_h_pl    ] max=  7.0217121722230473E+00,min=  0.0000000000000000E+00,sum=  1.8122948877569047E+03\n +check[q               ] max=  7.3763287914601054E+00,min=  0.0000000000000000E+00,sum=  2.4959084727641600E+06\n +check[q_pl            ] max=  7.0217121722230473E+00,min=  0.0000000000000000E+00,sum=  1.8117616747458526E+03\n +check[d               ] max= -0.0000000000000000E+00,min= -0.0000000000000000E+00,sum=  0.0000000000000000E+00\n +check[d_pl            ] max=  0.0000000000000000E+00,min=  0.0000000000000000E+00,sum=  0.0000000000000000E+00\n +check[ck              ] max=  3.1666977358687308E-02,min= -3.3842023700197510E-02,sum= -3.3888707532669278E+00\n +check[ck_pl           ] max=  2.8817336749971920E-02,min= -3.0878557008837175E-02,sum= -2.9483051886829596E-02\n ### Output ###\n +check[q_h             ] max=  7.3763287914601054E+00,min=  0.0000000000000000E+00,sum=  2.4996023860691669E+06\n +check[q_h_pl          ] max=  7.0217121722230473E+00,min=  0.0000000000000000E+00,sum=  1.8122948877569047E+03\n ### Validation : point-by-point diff ###\n +check[check_q_h       ] max=  0.0000000000000000E+00,min=  0.0000000000000000E+00,sum=  0.0000000000000000E+00\n +check[check_q_h_pl    ] max=  0.0000000000000000E+00,min=  0.0000000000000000E+00,sum=  0.0000000000000000E+00\n *** Finish kernel\n\\end{LstLog}\n\nCheck the lines below \\src{``Validation : point-by-point diff''} line,\nthat shows difference between calculated output array and\npre-calculated reference array.\nThese should be zero or enough small to be acceptable.\n\nThere are sample output log files in \\file{reference/}\nin each kernel program directory, for reference purpose.\n\n\n\\subsection{Sample of perfomance result}\n\nHere's an example of the performance result part of the log output.\nBelow is an example executed with the machine environment described in \\autoref{s:measuring_env}.\n%\nNote that in this program kernel part is iterated one time.\n\n\\begin{LstLog}\n *** Computational Time Report\n *** ID=001 : MAIN_dyn_vert_adv_limiter        T=     0.032 N=      1\n *** ID=002 : ____vertical_adv_limiter         T=     0.032 N=      1\n\\end{LstLog}\n\n", "meta": {"hexsha": "fea32e048317a022100e311b96415f8568f19a31", "size": 13955, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/NICAM/src/34_vert_adv_limiter.tex", "max_stars_repo_name": "aimes-project/IcoAtmosBenchmark_v1", "max_stars_repo_head_hexsha": "44b8f12dcf0e50094a2d0f78a8794febda270007", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/NICAM/src/34_vert_adv_limiter.tex", "max_issues_repo_name": "aimes-project/IcoAtmosBenchmark_v1", "max_issues_repo_head_hexsha": "44b8f12dcf0e50094a2d0f78a8794febda270007", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/NICAM/src/34_vert_adv_limiter.tex", "max_forks_repo_name": "aimes-project/IcoAtmosBenchmark_v1", "max_forks_repo_head_hexsha": "44b8f12dcf0e50094a2d0f78a8794febda270007", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-04T04:07:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-04T04:07:38.000Z", "avg_line_length": 41.9069069069, "max_line_length": 117, "alphanum_fraction": 0.5741311358, "num_tokens": 4920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.319150439347027}}
{"text": "\n\\documentclass{article} % For LaTeX2e\n\\usepackage{format/nips13submit_e}\n\\nipsfinalcopy % Uncomment for camera-ready version\n\\usepackage{times}\n\\usepackage{hyperref}\n\\usepackage{url}\n\\usepackage{color}\n\\definecolor{mydarkblue}{rgb}{0,0.08,0.45}\n\\hypersetup{\n    pdfpagemode=UseNone,\n    colorlinks=true,\n    linkcolor=mydarkblue,\n    citecolor=mydarkblue,\n    filecolor=mydarkblue,\n    urlcolor=mydarkblue,\n    pdfview=FitH}\n\n\\usepackage{graphicx, amsmath, amsfonts, bm, lipsum, capt-of}\n\n\\usepackage{natbib, xcolor, wrapfig, booktabs, multirow, caption}\n\n\\usepackage{float}\n\n\\def\\ie{i.e.\\ }\n\\def\\eg{e.g.\\ }\n\n\\title{An automatic report for the dataset : 01-airline}\n\n\\author{\nJames Robert Lloyd\\\\\nUniversity of Cambridge\\\\\nDepartment of Engineering\\\\\n\\texttt{jrl44@cam.ac.uk}\n\\And\nDavid Duvenaud\\\\\nUniversity of Cambridge \\\\\nDepartment of Engineering \\\\\n\\texttt{dkd23@cam.ac.uk}\n\\And\nRoger Grosse\\\\\nM.I.T.\\\\\nBrain and Cognitive Sciences \\\\\n\\texttt{rgrosse@mit.edu}\n\\And\nJoshua B. Tenenbaum\\\\\nM.I.T.\\\\\nBrain and Cognitive Sciences \\\\\n\\texttt{jbt@mit.edu}\n\\And\nZoubin Ghahramani\\\\\nUniversity of Cambridge \\\\\nDepartment of Engineering \\\\\n\\texttt{zoubin@eng.cam.ac.uk}\n}\n\n\\newcommand{\\fix}{\\marginpar{FIX}}\n\\newcommand{\\new}{\\marginpar{NEW}}\n\n\\setlength{\\marginparwidth}{0.9in}\n\\input{include/commenting.tex}\n\n%% For submission, make all render blank.\n%\\renewcommand{\\LATER}[1]{}\n%\\renewcommand{\\fLATER}[1]{}\n%\\renewcommand{\\TBD}[1]{}\n%\\renewcommand{\\fTBD}[1]{}\n%\\renewcommand{\\PROBLEM}[1]{}\n%\\renewcommand{\\fPROBLEM}[1]{}\n%\\renewcommand{\\NA}[1]{#1}  % Note, NA's pass through!\n\n\\begin{document}\n\n\\allowdisplaybreaks\n\n\\maketitle\n\n\\begin{abstract}\nThis report was produced automatically by the Gaussian process structure search algorithm.\nSee \\url{http://arxiv.org/abs/1302.4922} for a preliminary paper and see \\url{https://github.com/jamesrobertlloyd/gpss-research} for the latest source code.\n\\end{abstract}\n\n\\section{Executive summary}\n\nThe raw data and full model posterior with extrapolations are shown in figure~\\ref{fig:rawandfit}.\n\n\\begin{figure}[H]\n\\newcommand{\\wmgd}{0.5\\columnwidth}\n\\newcommand{\\hmgd}{3.0cm}\n\\newcommand{\\mdrd}{figures/01-airline}\n\\newcommand{\\mbm}{\\hspace{-0.3cm}}\n\\begin{tabular}{cc}\n\\mbm \\includegraphics[width=\\wmgd,height=\\hmgd]{\\mdrd/01-airline_raw_data} & \\includegraphics[width=\\wmgd,height=\\hmgd]{\\mdrd/01-airline_all}\n\\end{tabular}\n\\caption{Raw data (left) and model posterior with extrapolation (right)}\n\\label{fig:rawandfit}\n\\end{figure}\n\nThe structure search algorithm has identified four additive components in the data.\nThe  first 2 additive components explain 99.3\\% of the variation in the data as shown by the coefficient of determination ($R^2$) values in table~\\ref{table:stats}.\nAfter the first 3 components the cross validated mean absolute error (MAE) does not decrease by more than 0.1\\%.\nThis suggests that subsequent terms are modelling very short term trends, uncorrelated noise or are artefacts of the model or search procedure.\nShort summaries of the additive components are as follows:\n\\begin{itemize}\n\n  \\item \\input{figures/01-airline/01-airline_1_short_description.tex} \n\n  \\item \\input{figures/01-airline/01-airline_2_short_description.tex} \n\n  \\item \\input{figures/01-airline/01-airline_3_short_description.tex} \n\n  \\item \\input{figures/01-airline/01-airline_4_short_description.tex} \n\n\\end{itemize}\n\n\\begin{table}[htb]\n\\begin{center}\n{\\small\n\\begin{tabular}{|r|rrrrr|}\n\\hline\n\\bf{\\#} & {$R^2$ (\\%)} & {$\\Delta R^2$ (\\%)} & {Residual $R^2$ (\\%)} & {Cross validated MAE} & Reduction in MAE (\\%)\\\\\n\\hline\n- & - & - & - & 280.30 & -\\\\\n\n1 & 86.2 & 86.2 & 86.2 & 32.42 & 88.4\\\\\n\n2 & 99.3 & 13.1 & 95.1 & 9.57 & 70.5\\\\\n\n3 & 99.8 & 0.5 & 68.1 & 7.54 & 21.2\\\\\n\n4 & 100.0 & 0.2 & 100.0 & 7.54 & 0.0\\\\\n\n\\hline\n\\end{tabular}\n\\caption{\nSummary statistics for cumulative additive fits to the data.\nThe residual coefficient of determination ($R^2$) values are computed using the residuals from the previous fit as the target values; this measures how much of the residual variance is explained by each new component.\nThe mean absolute error (MAE) is calculated using 10 fold cross validation with a contiguous block design; this measures the ability of the model to interpolate and extrapolate over moderate distances.\nThe model is fit using the full data so the MAE values cannot be used reliably as an estimate of out-of-sample predictive performance.\n}\n\\label{table:stats}\n}\n\\end{center}\n\\end{table}\n\n\\section{Detailed discussion of additive components}\n\n\\subsection{Component 1 : A very smooth monotonically increasing function}\n\n\\input{figures/01-airline/01-airline_1_description.tex}\n\nThis component explains 86.2\\% of the total variance.\nThe addition of this component reduces the cross validated MAE by 88.4\\% from 280.3 to 32.4.\n\n\n\\begin{figure}[H]\n\\newcommand{\\wmgd}{0.5\\columnwidth}\n\\newcommand{\\hmgd}{3.0cm}\n\\newcommand{\\mdrd}{figures/01-airline}\n\\newcommand{\\mbm}{\\hspace{-0.3cm}}\n\\begin{tabular}{cc}\n\\mbm \\includegraphics[width=\\wmgd,height=\\hmgd]{\\mdrd/01-airline_1} & \\includegraphics[width=\\wmgd,height=\\hmgd]{\\mdrd/01-airline_1_cum}\n\\end{tabular}\n\\caption{Posterior of component 1 (left) and the posterior of the cumulative sum of components with data (right)}\n\\label{fig:comp1}\n\\end{figure}\n\n\\subsection{Component 2 : An approximately periodic function with a period of 1.0 years and with approximately linearly increasing amplitude}\n\n\\input{figures/01-airline/01-airline_2_description.tex}\n\nThis component explains 95.1\\% of the residual variance; this increases the total variance explained from 86.2\\% to 99.3\\%.\nThe addition of this component reduces the cross validated MAE by 70.47\\% from 32.42 to 9.57.\n\n\n\\begin{figure}[H]\n\\newcommand{\\wmgd}{0.5\\columnwidth}\n\\newcommand{\\hmgd}{3.0cm}\n\\newcommand{\\mdrd}{figures/01-airline}\n\\newcommand{\\mbm}{\\hspace{-0.3cm}}\n\\begin{tabular}{cc}\n\\mbm \\includegraphics[width=\\wmgd,height=\\hmgd]{\\mdrd/01-airline_2} & \\includegraphics[width=\\wmgd,height=\\hmgd]{\\mdrd/01-airline_2_cum}\n\\end{tabular}\n\\caption{Posterior of component 2 (left) and the posterior of the cumulative sum of components with data (right)}\n\\label{fig:comp2}\n\\end{figure}\n\n\\subsection{Component 3 : A smooth function}\n\n\\input{figures/01-airline/01-airline_3_description.tex}\n\nThis component explains 68.1\\% of the residual variance; this increases the total variance explained from 99.3\\% to 99.8\\%.\nThe addition of this component reduces the cross validated MAE by 21.22\\% from 9.57 to 7.54.\n\n\n\\begin{figure}[H]\n\\newcommand{\\wmgd}{0.5\\columnwidth}\n\\newcommand{\\hmgd}{3.0cm}\n\\newcommand{\\mdrd}{figures/01-airline}\n\\newcommand{\\mbm}{\\hspace{-0.3cm}}\n\\begin{tabular}{cc}\n\\mbm \\includegraphics[width=\\wmgd,height=\\hmgd]{\\mdrd/01-airline_3} & \\includegraphics[width=\\wmgd,height=\\hmgd]{\\mdrd/01-airline_3_cum}\n\\end{tabular}\n\\caption{Posterior of component 3 (left) and the posterior of the cumulative sum of components with data (right)}\n\\label{fig:comp3}\n\\end{figure}\n\n\\subsection{Component 4 : Uncorrelated noise with linearly increasing standard deviation}\n\n\\input{figures/01-airline/01-airline_4_description.tex}\n\nThis component explains 100.0\\% of the residual variance; this increases the total variance explained from 99.8\\% to 100.0\\%.\nThe addition of this component reduces the cross validated MAE by 0.00\\% from 7.54 to 7.54.\nThis component explains residual variance but does not improve MAE which suggests that this component describes very short term patterns, uncorrelated noise or is an artefact of the model or search procedure.\n\n\\begin{figure}[H]\n\\newcommand{\\wmgd}{0.5\\columnwidth}\n\\newcommand{\\hmgd}{3.0cm}\n\\newcommand{\\mdrd}{figures/01-airline}\n\\newcommand{\\mbm}{\\hspace{-0.3cm}}\n\\begin{tabular}{cc}\n\\mbm \\includegraphics[width=\\wmgd,height=\\hmgd]{\\mdrd/01-airline_4} & \\includegraphics[width=\\wmgd,height=\\hmgd]{\\mdrd/01-airline_4_cum}\n\\end{tabular}\n\\caption{Posterior of component 4 (left) and the posterior of the cumulative sum of components with data (right)}\n\\label{fig:comp4}\n\\end{figure}\n\n\\section{Extrapolation}\n\nSummaries of the posterior distribution of the full model are shown in figure~\\ref{fig:extrap}.\nThe plot on the left displays the mean of the posterior together with pointwise variance.\nThe plot on the right displays three random samples from the posterior.\n\n\\begin{figure}[H]\n\\newcommand{\\wmgd}{0.5\\columnwidth}\n\\newcommand{\\hmgd}{3.0cm}\n\\newcommand{\\mdrd}{figures/01-airline}\n\\newcommand{\\mbm}{\\hspace{-0.3cm}}\n\\begin{tabular}{cc}\n\\mbm \\includegraphics[width=\\wmgd,height=\\hmgd]{\\mdrd/01-airline_all} & \\includegraphics[width=\\wmgd,height=\\hmgd]{\\mdrd/01-airline_all_sample}\n\\end{tabular}\n\\caption{Full model posterior. Mean and pointwise variance (left) and three random samples (right)}\n\\label{fig:extrap}\n\\end{figure}\n\n\\subsection{Component 1 : A very smooth monotonically increasing function}\n\nSome discussion about extrapolation.\n\n\\begin{figure}[H]\n\\newcommand{\\wmgd}{0.5\\columnwidth}\n\\newcommand{\\hmgd}{3.0cm}\n\\newcommand{\\mdrd}{figures/01-airline}\n\\newcommand{\\mbm}{\\hspace{-0.3cm}}\n\\begin{tabular}{cc}\n\\mbm \\includegraphics[width=\\wmgd,height=\\hmgd]{\\mdrd/01-airline_1_extrap} & \\includegraphics[width=\\wmgd,height=\\hmgd]{\\mdrd/01-airline_1_sample} \\\\\n\\mbm \\includegraphics[width=\\wmgd,height=\\hmgd]{\\mdrd/01-airline_1_cum_extrap} & \\includegraphics[width=\\wmgd,height=\\hmgd]{\\mdrd/01-airline_1_cum_sample}\n\\end{tabular}\n\\caption{Posterior of component 1. Mean and pointwise variance (left) and three random samples from this distribution (right)}\n\\label{fig:extrap1}\n\\end{figure}\n\n\\subsection{Component 2 : An approximately periodic function with a period of 1.0 years and with approximately linearly increasing amplitude}\n\nSome discussion about extrapolation.\n\n\\begin{figure}[H]\n\\newcommand{\\wmgd}{0.5\\columnwidth}\n\\newcommand{\\hmgd}{3.0cm}\n\\newcommand{\\mdrd}{figures/01-airline}\n\\newcommand{\\mbm}{\\hspace{-0.3cm}}\n\\begin{tabular}{cc}\n\\mbm \\includegraphics[width=\\wmgd,height=\\hmgd]{\\mdrd/01-airline_2_extrap} & \\includegraphics[width=\\wmgd,height=\\hmgd]{\\mdrd/01-airline_2_sample} \\\\\n\\mbm \\includegraphics[width=\\wmgd,height=\\hmgd]{\\mdrd/01-airline_2_cum_extrap} & \\includegraphics[width=\\wmgd,height=\\hmgd]{\\mdrd/01-airline_2_cum_sample}\n\\end{tabular}\n\\caption{Posterior of component 2. Mean and pointwise variance (left) and three random samples from this distribution (right)}\n\\label{fig:extrap2}\n\\end{figure}\n\n\\subsection{Component 3 : A smooth function}\n\nSome discussion about extrapolation.\n\n\\begin{figure}[H]\n\\newcommand{\\wmgd}{0.5\\columnwidth}\n\\newcommand{\\hmgd}{3.0cm}\n\\newcommand{\\mdrd}{figures/01-airline}\n\\newcommand{\\mbm}{\\hspace{-0.3cm}}\n\\begin{tabular}{cc}\n\\mbm \\includegraphics[width=\\wmgd,height=\\hmgd]{\\mdrd/01-airline_3_extrap} & \\includegraphics[width=\\wmgd,height=\\hmgd]{\\mdrd/01-airline_3_sample} \\\\\n\\mbm \\includegraphics[width=\\wmgd,height=\\hmgd]{\\mdrd/01-airline_3_cum_extrap} & \\includegraphics[width=\\wmgd,height=\\hmgd]{\\mdrd/01-airline_3_cum_sample}\n\\end{tabular}\n\\caption{Posterior of component 3. Mean and pointwise variance (left) and three random samples from this distribution (right)}\n\\label{fig:extrap3}\n\\end{figure}\n\n\\subsection{Component 4 : Uncorrelated noise with linearly increasing standard deviation}\n\nSome discussion about extrapolation.\n\n\\begin{figure}[H]\n\\newcommand{\\wmgd}{0.5\\columnwidth}\n\\newcommand{\\hmgd}{3.0cm}\n\\newcommand{\\mdrd}{figures/01-airline}\n\\newcommand{\\mbm}{\\hspace{-0.3cm}}\n\\begin{tabular}{cc}\n\\mbm \\includegraphics[width=\\wmgd,height=\\hmgd]{\\mdrd/01-airline_4_extrap} & \\includegraphics[width=\\wmgd,height=\\hmgd]{\\mdrd/01-airline_4_sample} \\\\\n\\mbm \\includegraphics[width=\\wmgd,height=\\hmgd]{\\mdrd/01-airline_4_cum_extrap} & \\includegraphics[width=\\wmgd,height=\\hmgd]{\\mdrd/01-airline_4_cum_sample}\n\\end{tabular}\n\\caption{Posterior of component 4. Mean and pointwise variance (left) and three random samples from this distribution (right)}\n\\label{fig:extrap4}\n\\end{figure}\n\n\\end{document}\n", "meta": {"hexsha": "165bf4e681b323ceef6c3ee4a7d9e16119f6d092", "size": 11876, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "papers/workshop/airline/01-airline.tex", "max_stars_repo_name": "jaesikchoi/gpss-research", "max_stars_repo_head_hexsha": "2a64958a018f1668f7b8eedf33c4076a63af7868", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 151, "max_stars_repo_stars_event_min_datetime": "2015-01-09T19:25:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T02:05:52.000Z", "max_issues_repo_path": "papers/workshop/airline/01-airline.tex", "max_issues_repo_name": "jaesikchoi/gpss-research", "max_issues_repo_head_hexsha": "2a64958a018f1668f7b8eedf33c4076a63af7868", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-08-04T13:12:51.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-04T13:12:51.000Z", "max_forks_repo_path": "papers/workshop/airline/01-airline.tex", "max_forks_repo_name": "jaesikchoi/gpss-research", "max_forks_repo_head_hexsha": "2a64958a018f1668f7b8eedf33c4076a63af7868", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 59, "max_forks_repo_forks_event_min_datetime": "2015-02-04T19:13:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-28T23:36:09.000Z", "avg_line_length": 37.7015873016, "max_line_length": 217, "alphanum_fraction": 0.7572414955, "num_tokens": 3771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.319150439347027}}
{"text": "\\chapter{Case Study}\n\\label{case_study}\n\\thispagestyle{empty}\n\nIn this chapter we focus on our research goal \\textbf{RG1.2} as defined in section \\ref{research_goals}. In the previous chapter we had worked with synthetic networks and after having conducted several experiments with them with various parameters we wish to now analyze the bias in recommendations for some empirical networks. We start the chapter by talking about the empirical data we wish to use in our thesis and how we process it and set it up for our experiment. We also list down names and few of the network properties for each of the datasets which we use. In the next section we look at the results of our experiment on each of these datasets individually. We primarily analyze the disparate visibility bias for each of the chosen datasets.\n\n\\section{Setup}\n\nWe work on the \\textbf{Facebook100} \\cite{traud2012social} dataset published by Traud et. al. in 2011. This huge dataset contains snapshots of Facebook \\textit{`friendship networks'} for 100 universities across the United States of America. We choose 4 datasets among the 100 for our thesis and use our recommendation methods on them to receive the recommended nodes list on which we carry out the disparate visibility analysis as we had done previously for \\textit{static networks} in section \\ref{static_networks}.\n\n\\subsection{Dataset overview}\n\nTable \\ref{table_facebook_datadet} gives an overview of the networks we choose from the \\textbf{Facebook100} dataset to carry out our experiments. The \\textbf{NetworkID} is the same as used to identify individual networks in the original dataset. We choose \\textit{gender} as the node attribute to distinguish nodes belonging to the \\textit{minority} or \\textit{majority} group. The \\textbf{Minority} column in the table shows the gender representing the minority group in each network. The fraction of nodes which belong to the minority group is given as $f$. We estimate the homophily value for each group using the method outlined by Karimi et. al. \\cite{karimi2018homophily}. The minority and majority homophily values are given as $h_{minority}$ and $h_{majority}$ respectively. As we had mentioned earlier in \\ref{back_networks}, real-world networks exhibit asymmetric homophily, which we can observe here for the chosen empirical networks. All values for $f$, $h_{minority}$ and $h_{majority}$ have been rounded off to 2 decimal places for our experiments.\n\n\\begin{table}[h]\n\t\\centering\n\t\\begin{tabular}{ |c|c|c|c|c|c|c| }\n\t\t\\hline\n\t\t\\textbf{Network ID} & \\textbf{Total nodes} & \\textbf{Total edges} & \\textbf{Minority} & \\textbf{$f$} & \\textbf{$h_{minority}$} & \\textbf{$h_{majority}$} \\\\\n\t\t\\hline\n\t\tCaltech36 & 703 & 15464 & female & 0.32 & 0.75 & 0.6 \\\\\n\t\tReed98 & 865 & 15948 & male & 0.42 & 0.73 & 0.7 \\\\\n\t\t%Haverford76 & 1350 & 53904 & male & 0.46 & 0.73 & 0.82 \\\\\n\t\tSimmons81 & 1422 & 30486 & male & 0.01 & 0.47 & 0.87 \\\\\n\t\tSwarthmore42 & 1521 & 53726 & male & 0.49 & 0.72 & 0.78 \\\\\n\t\t\\hline\n\t\\end{tabular}\n\t\\caption{Details of chosen empirical networks from \\textbf{Facebook100} dataset}\n\t\\label{table_facebook_datadet}\n\\end{table}\n\nWe parse the original dataset, which is provided as a sparse matrix to form our own network adjacency matrices. For each network multiple nodes are found to not possess the \\textit{gender} information. We choose to discard such nodes and the edges they form from our final network. \n\n\\subsection{Experimental Setup}\n\nFor each of the networks $G(V,E)$ chosen by us (as listed in table \\ref{table_facebook_datadet}) we use the \\textit{Topological} and \\textit{Reinforcement} recommender methods (as detailed in chapter \\ref{recommender_methods}) to get a recommendation list $L_{v}$ for each node $v \\in V$.\n\nOnce we have received this recommendation list, we measure the Disparate visibility \\cite{fabbri2020effect} for the recommendations (similar to what we did in section \\ref{static_networks}). \n\n\\section{Results}\n\n\\subsection{Caltech36}\n\nFor the network \\textbf{Caltech36} \\textit{females} form the minority group with 32\\% of the nodes belonging to this group. The minority group has a homophily value of 0.75 which is slightly higher than the majority group homophily value of 0.6. \n\n\\begin{SCfigure}[1][h!]\n\t\\centering\n\t\\includegraphics[trim=0 10 0 10, clip, width=0.75\\textwidth]{images/dd_caltech.png}\n\t\\caption{Degree distribution for \\textbf{Caltech36}}\n\t\\label{dd_caltech}\n\\end{SCfigure}\n\nLooking at the degree distribution plot (figure \\ref{dd_caltech}) we can see that both majority and minority nodes hold quite high degrees. Since both the groups are homophilic in nature with minority being more homophilic, this kind of distribution can be expected for the minority fraction of 0.3. \n\n\\begin{SCfigure}[1][h!]\n\t\\centering\n\t\\includegraphics[trim=0 10 0 10, clip, width=0.75\\textwidth]{images/dv_caltech.png}\n\t\\caption{Disparate Visibility for \\textbf{Caltech36}. Black dotted lines represent the range for the disparate visibility measure given the minority fraction and the solid black line shows the equal visibility mark at 0.}\n\t\\label{dv_caltech}\n\\end{SCfigure}\n\nUpon using our recommender methods, we find that the disparate visibility (figure \\ref{dv_caltech}) is positive, which means that the minority nodes are more visible in recommendations than majorities. This result holds for all recommender methods used. The range of disparate visibility measure for this network lies between [-1.48, 3.08]. \n\nIn our earlier experiments with measuring disparate visibility for static networks in section \\ref{static_dv} we had assumed that for a homophilic regime the networks would have higher visibility for majorities. However, here we see that at the homophilic regime minorities are more visible. We however did not have information for the disparate visibility measure at homophily values of $h=0.6$ or $h=0.7$. Thus we might have missed information in our experiments which we can observe in this case. \n\nFor the \\textbf{PA-Homophily} method we can deduce that minorities are more visible owing to only slightly high homophily value for majorities and a greater homophily among minorities. This would mean that for both type of nodes there is a higher chance of having minorities as node recommendations. This is also seen in the \\textbf{reinforcement methods}. In the case of \\textbf{Top-Rank} we see much more visibility for minorities at $r=0.0$ and $r=0.5$, but this visibility decreases from others in the case of $r=1.0$. Here we see that the ranking factor actually has a much more sever effect than what we had observed previously in our experiments with static networks. What we can deduce is that since both minority and majority nodes have higher degrees and they both have only slightly varying homophily, the ranking factor in this case plays a major role in boosting the probability for nodes in \\textit{click model}. Lesser visibility for minorities would however mean that the Top-Rank method has a higher mix of majority and minority nodes at upper precedence partitions. This is what causes the minority visibility to drop.\n\n\\subsection{Reed98}\n\nFor the network \\textbf{Reed98}, \\textit{males} form the minority group with 42\\% of the nodes belonging to this group. The minority group has a homophily value of 0.73 which is very close to the majority group homophily value of 0.7, thus having almost symmetric homophily in this network. \n\n\\begin{SCfigure}[1][h!]\n\t\\centering\n\t\\includegraphics[trim=0 10 0 10, clip, width=0.75\\textwidth]{images/dd_reed.png}\n\t\\caption{Degree distribution for \\textbf{Reed98}}\n\t\\label{dd_reed}\n\\end{SCfigure}\n\nLooking at the degree distribution plot (figure \\ref{dd_reed}) we can see that both the majority and minority nodes hold high degrees. Since the network is moderately homophilic, with the minority group size quite high this can be expected with both groups supporting themselves. \n\n\\begin{SCfigure}[1][h!]\n\t\\centering\n\t\\includegraphics[trim=0 10 0 10, clip, width=0.75\\textwidth]{images/dv_reed.png}\n\t\\caption{Disparate Visibility for \\textbf{Reed98}. Black dotted lines represent the range for the disparate visibility measure given the minority fraction and the solid black line shows the equal visibility mark at 0.}\n\t\\label{dv_reed}\n\\end{SCfigure}\n\nFrom the disparate visibility plot (figure \\ref{dv_reed}), upon using our recommender methods on the network, we find that visibility for both groups borders the equal visibility mark. \n\nWe had seen almost equal visibility for a minority size of $f=0.4$ in our synthetic network experiments too. The results corroborate with our findings for this network.\n\nThe range for disparate visibility measure for this network lies between [-1.72, 2.4]. Most values are slightly positive which shows that the minority group is at a very slight advantage, but this is very negligible ($\\leq 5\\%$). The \\textbf{Top-Rank} method at $r=1.0$ however shows opposite behavior than the rest, putting majorities as more visible. The behavior which we had seen earlier in the case of \\textbf{Caltech36} is thus seen here too for Top-Rank(r=1.0).\n\n\\subsection{Simmons81}\n\nFor the network \\textbf{Simmons81}, \\textit{males} form the minority group with only 1\\% of the nodes belonging to this group. The minority group has a homophily value of 0.47 while the majority group has a homophily value of 0.87. This is a group with a very less minority who connects in an almost group-agnostic way while the majority has strong homophilic tendencies. So while the majority nodes have strong in-group support they also get connections from the minorities.\n\n\\begin{SCfigure}[1][h!]\n\t\\centering\n\t\\includegraphics[trim=0 10 0 10, clip, width=0.75\\textwidth]{images/dd_simmons.png}\n\t\\caption{Degree distribution for \\textbf{Simmons81}}\n\t\\label{dd_simmons}\n\\end{SCfigure}\n\nLooking at the degree distribution plot (figure \\ref{dd_simmons}) we see that the majority nodes hold much higher degrees compared to the minority as we could expect looking at the homophily values. While a fair amount of majority nodes have degrees above 100, the maximum degree a minority node holds is far less than 100. This shows that majority nodes are much more well-connected than minorities.\n\n\\begin{SCfigure}[1][h!]\n\t\\centering\n\t\\includegraphics[trim=0 10 0 10, clip, width=0.75\\textwidth]{images/dv_simmons.png}\n\t\\caption{Disparate Visibility for \\textbf{Simmons81}. Black dotted lines represent the range for the disparate visibility measure given the minority fraction and the solid black line shows the equal visibility mark at 0.}\n\t\\label{dv_simmons}\n\\end{SCfigure}\n\nFrom the disparate visibility plot (figure \\ref{dv_simmons}), upon using our recommender methods on the nodes in the network, we find that visibility is higher for majority nodes. The range of disparate visibility measure for this network lies in the range of [-1.01, 83.65].\n\nSince the majorities have high homophily and the minorities have almost neutral homophily, the majorities would be winning in the recommendations game in the \\textbf{PA-Homophily} and subsequently the \\textbf{reinforcement methods} cases. For both the majority and minority nodes there would be more majority nodes which would be suggested. Also since the minorities are so few in number most of them would already be connected with other minorities thus further increasing chances of majorities to be recommended. If the minority group size was higher we would probably see a higher minority visibility for our network. \n\n\\subsection{Swarthmore42}\n\nFor the network \\textbf{Swarthmore42}, \\textit{males} barely form the minority group with 49\\% of the nodes belonging to this group. The minority group has a homophily value of 0.72 while the majority group has a homophily value of 0.78. This is a network with equal node-group sizes exhibiting almost symmetric homophilic behavior.\n\n\\begin{SCfigure}[1][h!]\n\t\\centering\n\t\\includegraphics[trim=0 10 0 10, clip, width=0.75\\textwidth]{images/dd_swarthmore.png}\n\t\\caption{Degree distribution for \\textbf{Swarthmore42}}\n\t\\label{dd_swarthmore}\n\\end{SCfigure}\n\nLooking at the degree distribution plot (figure \\ref{dd_swarthmore}) we see that both majority and minority nodes have an almost equal distribution. The plot however does not strictly demonstrate the properties of a scale-free network as in there are lower degree nodes with lower probability also present in the network. The number of edges in this network is also quite high which would mean that there the nodes are well connected with a higher average degree.\n\n\\begin{SCfigure}[1][h!]\n\t\\centering\n\t\\includegraphics[trim=0 10 0 10, clip, width=0.75\\textwidth]{images/dv_swarthmore.png}\n\t\\caption{Disparate Visibility for \\textbf{Swarthmore42}. Black dotted lines represent the range for the disparate visibility measure given the minority fraction and the solid black line shows the equal visibility mark at 0.}\n\t\\label{dv_swarthmore}\n\\end{SCfigure}\n\nFrom the disparate visibility plot (figure \\ref{dv_swarthmore}), upon using our recommender methods on the network, we find that visibility for most cases is only negligibly higher for majority nodes. This suggests that the recommendations are quite balanced for both groups as we could have expected for a equal group size. The range of disparate visibility measure for this network lies between [-1.97, 2.03]. \n\nFor the case of \\textbf{Adamic-Adar} we see that the minority seems to have higher visibility than what is projected by the other methods. As we know that the Adamic-Adar method is completely structure dependent this could mean the network structure favors minorities in certain way. However this difference is very negligible to make a concrete comment on why this happens.\n\n\\section{Summary}\n\nUsing the various recommendation methods $R$ as we had defined in chapter \\ref{recommender_methods} we carry out our experiment on empirical networks to get recommendations for each node in the networks. We use selected network from the \\textbf{Facebook100} dataset to measure the disparate visibility found in the recommendations.\n\nFrom our experiments we only see the \\textbf{Caltech36} network give a higher visibility score in favor of minorities. The other networks either have an almost equal group-size or have a very small minority size which puts them close to the equal visibility measure.\n\nIn \\textbf{Caltech36} we see that minorities are more visible which is different from what we were expecting from our experiments on synthetic networks. This clearly points to a limitation of our work since we do not know the disparate visibility behavior in the in-between homophily cases. Our consideration of homophily values for experiments is limited and the behavior in more such cases is something worth exploring in the future.", "meta": {"hexsha": "059e75a0a9f6e9fad1661e3dbbfc0e5b8efdb855", "size": 14767, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/thesis/chapters/case_study.tex", "max_stars_repo_name": "dvaruas/minority_recommendations", "max_stars_repo_head_hexsha": "8adcbf5af5c322e4b20d4336b12ecda62a5c4d5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/thesis/chapters/case_study.tex", "max_issues_repo_name": "dvaruas/minority_recommendations", "max_issues_repo_head_hexsha": "8adcbf5af5c322e4b20d4336b12ecda62a5c4d5f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/thesis/chapters/case_study.tex", "max_forks_repo_name": "dvaruas/minority_recommendations", "max_forks_repo_head_hexsha": "8adcbf5af5c322e4b20d4336b12ecda62a5c4d5f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 99.777027027, "max_line_length": 1136, "alphanum_fraction": 0.7906819259, "num_tokens": 3645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.319150439347027}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Author: Sébastien Gardoll copyright all rights reserved %\n% email: sebastien@gardoll.fr                             %\n% LaTeX Project Public License 1.3c                       %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\chapter{Title of the chapter}\n\\label{chap:title_of_the_chapter}\nSome preambule.\n\n\\section{Text emphasis}\n\n\\textbf{bold text}\n\\textit{italicied text}\n\\underline{underlined text}\n\\emph{emphasising text}\n\n\\section{Itemize example}\n\n\\begin{itemize}\n\\item {Item1: \\lipsum[1]}\n\\item {Item2}\n\\item {Item3}\n\\end{itemize}\n\\begin{itemize}\n\\item {carriaged return item:}\n\\end{itemize}\n\\lipsum[1]\n\n\\section{Section}\n\n\\lipsum[1]\n\\lipsum[2]\n\n\\subsection{Subsection}\n\n\\lipsum[1]\n\n\\subsubsection{Subsubsection}\n\n\\lipsum[1-2]\n\n\\section{Image inclusions}\n\n\\ref{fig:pic1.png} is an example of a full width page inclusion\nof a picture (aspect ratio is kept):\n\n\\includeimg{1}{pic1.png}{The caption of the picture.}\n\n\\ref{fig:pic2.png} is an example of a scaled down picture:\n\n\\includeimg{0.5}{pic2.png}{The caption of the picture.}\n\n\\ref{fig:pic3.png} is an example of a rotated picture:\n\n\\includeimgsideways{0.5}{pic3.png}{The rotated caption of the picture.}\n\n\\section{Citations}\n\nAccording to \\cite{inbook-full}...\nThis is a footnote citation\\footfullcite{incollection-minimal}.\n\n\\section{Some fancy maths}\n\n\\[\\textit{MSE}=E(Y-\\hat{Y})^2=\\underbrace{\\left[F(X)-\\hat{F}(X)\\right]^2}_{\\text{reductible}} + \\underbrace{\\textit{Var}(\\varepsilon)}_{\\text{irréductible}}\\]\n\n\\[d=\\left\\{\n        \\begin{array}{l}\n        1\\ si\\ A>\\alpha \\\\\n        0\\ si\\ A\\leqslant\\alpha\n        \\end{array}\n        \\right.\n      \\]\n\n\\[d(x_1,\\ x_2)=\\sqrt{\\ \\sum_{j=1}^n\\frac{1}{f_n}(f_{1j}-f_{2j})^2}\\]\n\n\\begin{theo}[Morgan's Law]\n\\[\\overline{P \\wedge Q} \\Leftrightarrow \\bar{P} \\vee \\bar{Q}\\]\n\\[\\overline{P \\vee Q} \\Leftrightarrow \\bar{P} \\wedge \\bar{Q}\\]\n\\end{theo}\n\n\\section{Tables}\n\nFrom the CTABLE man (link \\href{https://ctan.org/pkg/ctable}{here}):\n\n\\ctable[\ncap     = The Skewing Angles,\ncaption = The Skewing Angles ($\\beta$) for\n$\\fam0 Mu(H)+X_2$ and $\\fam0 Mu(H)+HX$~\\tmark,\nlabel   = nowidth,\npos     = h\n]{rlcc}{\n\\tnote{for the abstraction reaction,\n$\\fam0 Mu+HX \\rightarrow MuH+X$.}\n\\tnote[b]{1 degree${} = \\pi/180$ radians.}\n\\tnote[c]{this is a particularly long note, showing that\nfootnotes are set in raggedright mode as we don’t like\nhyphenation in table footnotes.}\n}{                                                          \\FL\n&            & $\\fam0 H(Mu)+F_2$     & $\\fam0 H(Mu)+Cl_2$ \\ML\n&$\\beta$(H)  & $80.9^\\circ$\\tmark[b] & $83.2^\\circ$       \\NN\n&$\\beta$(Mu) & $86.7^\\circ$          & $87.7^\\circ$       \\LL\n}", "meta": {"hexsha": "000f9ffb6fb2e94fa27a38d0d2a835b3241535f9", "size": 2695, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapter_1.tex", "max_stars_repo_name": "SebastienGardoll/thesis_latex_template", "max_stars_repo_head_hexsha": "bb13515b5960a38661d14ea44a3a2f7c47c0c56d", "max_stars_repo_licenses": ["LPPL-1.3c"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapter_1.tex", "max_issues_repo_name": "SebastienGardoll/thesis_latex_template", "max_issues_repo_head_hexsha": "bb13515b5960a38661d14ea44a3a2f7c47c0c56d", "max_issues_repo_licenses": ["LPPL-1.3c"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter_1.tex", "max_forks_repo_name": "SebastienGardoll/thesis_latex_template", "max_forks_repo_head_hexsha": "bb13515b5960a38661d14ea44a3a2f7c47c0c56d", "max_forks_repo_licenses": ["LPPL-1.3c"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4215686275, "max_line_length": 158, "alphanum_fraction": 0.6096474954, "num_tokens": 905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.6187804337438502, "lm_q1q2_score": 0.31905551509805513}}
{"text": "\\renewcommand{\\chapid}{fc}\n\\chapter{The Effect of Fiber Collisions on the Galaxy Power Spectrum Multipoles \\chaplabel{fc}}\n\n\nThis \\paper\\ is joint work with Roman~Scoccimarro (NYU), \nMichael~R.~Blanton (NYU), Jeremy~L.~Tinker (NYU), and Sergio Rodr\\'{i}guez-Torres \n(Universidad Aut\\'{o}noma de Madrid) published in the \\emph{Monthly Notices of the Royal\nAstronomical Society} as \\cite{Hahn:2017a}. \n\n\\newcommand{\\lexp}{\\mathop{\\langle}}\n\\newcommand{\\rexp}{\\mathop{\\rangle}}\n\\newcommand{\\rexpc}{\\mathop{\\rangle_c}}\n\\def\\k{{\\hbox{\\BF k}}}\n\\def\\x{{\\hbox{\\BF x}}}\n\\def\\r{{\\hbox{\\BF r}}}\n\\def\\s{{\\hbox{\\BF s}}}\n\\def\\la{\\mathrel{\\mathpalette\\fun <}}\n\\def\\ga{\\mathrel{\\mathpalette\\fun >}}\n\\def\\fun#1#2{\\lower3.6pt\\vbox{\\baselineskip0pt\\lineskip.9pt\n\\ialign{$\\mathsurround=0pt#1\\hfill##\\hfil$\\crcr#2\\crcr\\sim\\crcr}}}\n\n%\\title{The Effect of Fiber Collisions on the Galaxy Power Spectrum Multipoles} \n\n\\section{Chapter Abstract}\n\\qquad Fiber-fed multi-object spectroscopic surveys, with their ability to collect an unprecedented number of redshifts, currently dominate large-scale structure studies. However, physical constraints limit these surveys from successfully collecting redshifts from galaxies too close to each other on the focal plane. This ultimately leads to significant systematic effects on galaxy clustering measurements. Using simulated mock catalogs, we demonstrate that fiber collisions have a significant impact on the power spectrum, $P(k)$, monopole and quadrupole that exceeds sample variance at scales smaller than $k\\sim0.1~h/{\\rm Mpc}$.\n\n\\qquad We present two methods to account for fiber collisions in the power spectrum. The first statistically reconstructs the clustering of fiber collided galaxy pairs by modeling the distribution of the line-of-sight displacements between them. It also properly accounts for fiber collisions in the shot-noise correction term of the $P(k)$ estimator. Using this method, we recover the true $P(k)$ monopole of the mock catalogs with residuals of $<0.5\\%$ at $k=0.3~h/{\\rm Mpc}$ and $<4\\%$ at $k=0.83~h/{\\rm Mpc}$ -- a significant improvement over existing correction methods. The quadrupole, however, does not improve significantly.\n\n\\qquad The second method models the effect of fiber collisions on the power spectrum as a convolution with a configuration space top-hat function that depends on the physical scale of fiber collisions. It directly computes theoretical predictions of the fiber-collided $P(k)$ multipoles and reduces the influence of smaller scales to a set of nuisance parameters. Using this method, we reliably model the effect of fiber collisions on the monopole and quadrupole down to the limiting scales of theoretical predictions. The methods we present in this paper will allow us to robustly analyze galaxy power spectrum multipole measurements to much smaller scales than previously possible.\n\n\n\\section{Introduction} \nCosmological measurements such as galaxy clustering statistics are\nno longer dominated by uncertainties from statistical precision, but from \nsystematic effects of the measurements. This is a result of the millions of \nredshifts to distant galaxies that have been obtained through redshift surveys\nsuch as the 2dF Galaxy Redshift Survey (2dFGRS; \\citealt{Colless:1999aa}) and \nthe Sloan Digital Sky Survey III Baryon Oscillation Spectroscopic Survey \n(SDSS-III BOSS; \\citealt{Anderson:2012aa, Dawson:2013aa}). Current surveys, \nsuch as the Extended Baryon Oscillation Spectroscopic Survey (eBOSS; \\citealt{Dawson:2015aa}), \nand future surveys such as the Dark Energy Spectroscopic Instrument (DESI; \\citealt{Schlegel:2011aa, \nMorales:2012aa, Makarem:2014aa}), and the Subaru Prime Focus Spectrograph \n(PFS; \\citealt{Takada:2014aa}), \nwill continue to collect many more million redshifts, extending our measurements \nto unprecedented statistical precision. These completed and future surveys, all use \nand will use fiber-fed spectrographs. \n%All these surveys, both completed and future,  \n%use fiber-fed spectrographs. \n\n%As of 2016, millions of redshifts to distant galaxies have been obtained \n%through redshift surveys. Cosmological measurements such as galaxy clustering \n%statistics are no longer dominated by uncertainties from statistical precision, \n%but from systematic effects of the measurements. These surveys, such as the 2dF \n%Galaxy Redshift Survey (2dFGRS; \\citealt{Colless:1999aa}) and the Sloan Digital \n%Sky Survey III Baryon Oscillation Spectroscopic Survey (SDSS-III BOSS; \n%\\citealt{Anderson:2012aa, Dawson:2013aa}), and future surveys, such as the \n%Extended Baryon Oscillation Spectroscopic Survey (eBOSS; \\citealt{Dawson:2015aa}), \n%Dark Energy Survey Instrument (DESI; \\citealt{Schlegel:2011aa, \n%Morales:2012aa, Makarem:2014aa}), and Subaru Prime Focus Spectrograph (PFS; \\citealt{Takada:2014aa}), \n%use fiber-fed spectrographs. \n\nFor each galaxy, a fiber is used to obtain a spectroscopic redshift. However, \nthe physical size of the fiber housing and other physical constraints limit \nhow well any of these surveys can observe close pairs of galaxies. In the SDSS, \nif two galaxies are located within the fiber collision angular scale from \none another on the sky, separate fibers cannot be placed adjacently to \nobserve them simultaneously \n(\\citealt{Yoon:2008aa}). In these situations, only a single redshift \nis measured. With redshifts of galaxies in close angular proximity missing \nfrom the sample, any clustering statistic probing these scales will be \nsystematically affected. \n\nAs our cosmological surveys extend further to higher redshifts, the systematic\neffect becomes more severe. The fiber collision angular scale corresponds \nto a larger comoving scale at higher redshift, thereby affecting our measurements on larger \nscales. BOSS, in particular, has an angular fiber collision scale \nof $62\"$. This corresponds to $\\sim 0.43 \\;\\mathrm{Mpc}/h$ at the \ncenter of the survey's redshift range; fiber-collided galaxies \naccount for $\\sim 5\\%$ of the galaxy sample (\\citealt{Anderson:2012aa, \nReid:2012aa, Guo:2012aa}). \nWhile this may seem like a relatively small fraction of redshifts, its \neffect on clustering measurements such as the power spectrum and bispectrum \nis significant and needs to be accounted for in order to probe mildly non-linear scales. \nUnfortunately, future spectroscopic surveys such \nas DESI, which will use robotic fiber positioner \ntechnology, will be subject to similar effects. \nIn fact, based on the DESI Final Design \nReport\\footnote{DESI Final Design Report: \\url{http://desi.lbl.gov/tdr/}}, which estimates that \n$\\sim 6\\%$ of Luminous Red Galaxies and \n$>20\\%$ of Emission-Line Galaxies will be fiber-collided, \nfiber collisions will affect a {\\em larger} fraction of the target \nsample than in BOSS.\nTherefore, \naccounting for the effects of fiber collisions will remain a crucial and \nunavoidable challenge for analyzing clustering measurements. \n\n%Meanwhile, improvements in our modeling of clustering measurements continue \n%to extend the physical scales we can model. Galaxy power spectrum models\n%continue to reliably model higher $k$ domains with improvements in the \n%non-linear regime. In \n%\n%For instance, the $\\mathtt{RegPT}$ model (\\citealt{Taruya:2012aa}), which was used in a \n%recent analysis of power spectrum multipoles by \\cite{Beutler:2014aa},\n%can reliably probe up to $k = 0.28\\;h/\\mathrm{Mpc}$ at $z = 0.55$, the center \n%of the BOSS redshift range.  \n\nTo correct for fiber collisions, one common approach used in clustering \nmeasurements is the nearest neighbor method (\\citealt{Zehavi:2002aa, Zehavi:2005aa, \nZehavi:2011aa, Berlind:2006aa, Anderson:2012aa}). For fiber-collided galaxies without \nresolved redshifts, the method assigns the statistical weight of the \nfiber-collided galaxy to its nearest angular neighbor. This provides \na reasonable correction for the fiber collision effects at scales much \nlarger than the fiber collision scales; however the correction falls short \nelsewhere. In fact, as \\cite{Zehavi:2005aa} find, \nfiber collisions affect the two-point correlation function (2PCF) \nmeasurements even on scales significantly larger than the fiber collision \nscale ( $> 1\\;\\mathrm{Mpc}/h$). \n\nFor power spectrum measurements in BOSS, \nthe nearest neighbor method has recently been supplemented with adjustments \nin the constant shot-noise term of the power spectrum estimator to correct \nfor fiber collisions~\\citep{Beutler:2014aa, Gil-Marin:2014aa, \nGil-Marin:2016ab, Gil-Marin:2016aa, Beutler:2016aa, Grieb:2016aa}. More specifically, \nmethods like the one used in \n\\cite{Gil-Marin:2014aa} obtain the value of the shot-noise term from mock catalogs and thus rely entirely on their accuracy to correct for fiber collisions. \nThis is concerning since, as we shall demonstrate in detail, fiber \ncollisions depend systematically on the small-scale power spectrum, and mock catalogs used for large scale structure analyses are typically \nnot based on high resolution N-body simulations. In addition, there is no way to validate and \ncalibrate the shot-noise term independently for observations. A more \nreliable approach is to marginalize over the value of the shot-noise \nterm, and this is the approach that has recently become more popular\n~\\citep{Gil-Marin:2016ab, Beutler:2016aa, Grieb:2016aa, Gil-Marin:2016aa}. \nHowever, adjustments to the shot-noise term are limited to the power spectrum monopole, since higher order multipoles do not have a shot-noise term. However, as we shall discuss in detail below, {\\em fiber collisions affect all multipoles in a $k$-dependent way}, not just adding a constant for the monopole power.\n\n\\cite{Guo:2012aa}, focusing on SDSS-III BOSS like samples, proposed \na fiber collision correction method for the 2PCF that is able to reasonably \ncorrect for fiber collisions above and below the collision scale. \n\\cite{Guo:2012aa} estimates the total contribution of fiber-collided galaxies \nto the 2PCF by examining the pair statistics in overlapping tiling regions of \nthe survey, where a smaller fraction of galaxies suffer from fiber collisions.\nUnfortunately, applying an analogous method in Fourier space proves to be more difficult. \nThe \\cite{Guo:2012aa} method in Fourier space would involve measuring the power spectra \nfor individual overlapping regions. Given the complex geometry of these \nregions, the systematic effect introduced by the window function makes \nmeasuring the power spectrum at larger scales intractable. \n\n%Applying an analogous method to Fourier space would first involve taking \n%power spectrum measurements of each overlapping and non-overlapping \n%region individually. Afterwards, the window function of those regions \n%would have to be deconvolved from the measurements in order to model \n%the power spectrum contribution from fiber collided galaxies. \\todo{Unfortunately, \n%due to the complex geometry of the overlapping regions, the systematic effects of\n%including the window function modeling the }\n\nMeanwhile, galaxy redshift-space power spectrum models from perturbation theory continue to \nreliably model higher $k$ in the weakly non-linear regime\n\\citep{Taruya:2010aa, Taruya:2014aa, Okumura:2015aa, Beutler:2016aa, Grieb:2016aa, Sanchez:2016aa}.\n%\\citep{Taruya:2010aa, Sato:2011aa, Taruya:2012aa, Okumura:2012aa, Taruya:2013aa, Taruya:2014aa, Beutler:2014aa, Okumura:2015aa, Beutler:2016aa, Grieb:2016aa, Sanchez:2016aa}.\nRecent analyses of galaxy power spectrum \nmultipoles (\\citealt{Beutler:2014aa, Gil-Marin:2014aa, Gil-Marin:2016ab, Gil-Marin:2016aa, Beutler:2016aa, Grieb:2016aa}) use scales up to $k_{\\rm max}=0.15-0.2 h$/Mpc for BOSS galaxies, and this limit will for sure move towards smaller scales in upcoming analyses. As statistical errors decrease the importance of systematics due to fiber collisions plays an increasingly important role. The main goal of this paper is to quantify this systematic effect for the power spectrum multipoles and to provide ways to overcome it; for this purpose we\ndevelop two distinct approaches. \n\nThe first approach improves upon the nearest neighbor method by modeling the \ndistribution of the line-of-sight displacement between resolved fiber collided \ngalaxies to statistically reconstruct the clustering of fiber-collided galaxies. \nThis uses information on resolved fiber collided galaxies that is available from \nthe data themselves (e.g. in tiling overlap regions). The difficulty with this \nmethod is that it works statistically, i.e. we cannot reconstruct the {\\em actual} \ngalaxy by galaxy line of sight displacement due to collisions. As a result of this, \nwhile the method works very well to recover the true power spectrum monopole \nfrom fiber collided galaxy catalogs, it does not work sufficiently well for the \npower spectrum quadrupole which is far more sensitive to the precise structure of ``fingers of god''. \n\nThe second approach addresses the shortcomings of the first one by modeling the effects of fiber collisions on the {\\em predictions} instead of trying to undo their effect on the data before computing power spectrum statistics. It approximates the effect of fiber collisions on the 2PCF as \na 2D top hat function. Then it derives the effect of fiber collisions on the galaxy power spectrum as a \nconvolution of the true power spectrum with the top hat function. Therefore the theoretical predictions for the power spectrum are fiber collided and then can be compared  directly to the observed fiber collided power spectrum in clustering analyses. \n\nThis paper is organized as follows. \nIn Section \\ref{sec:catalog}, we briefly describe the simulated mock catalogs \nwith realistic fiber collisions and the power spectrum estimator used throughout \nthe paper. We then demonstrate the impact of fiber collisions on power spectrum \nmeasurements and how the nearest neighbor method does not adequately account \nfor fiber collisions in Section \\ref{sec:fc_pk}. We present our two methods \nof accounting for fiber collisions along with the results for mock catalogs in \nSection \\ref{sec:dlospeak} and Section \\ref{sec:fourier}, respectively. Finally \nin Section \\ref{sec:summary} we summarize our results and conclude. \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Fiber-collided Mock catalogs\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Fiber-collided Mock catalogs} \\label{sec:catalog}\nFor various purposes, such as characterizing the impact of the survey window function on statistics and estimating covariance matrices, simulated mock \ncatalogs play a crucial role in interpreting  \nclustering measurements of observed galaxies \n\\citep[][also see citations in \\citealt{Chuang:2015aa}]{ Cole:1998aa, Scoccimarro:2002aa, Anderson:2012aa, Beutler:2014aa, Carretero:2015aa}. \n%\\citep{Cole:1998aa, Scoccimarro:2002aa, Yan:2004aa, Anderson:2012aa, Manera:2013aa,  Monaco:2013aa, Beutler:2014aa, Gil-Marin:2014aa, White:2014aa, Manera:2015aa, Tassev:2015aa, Carretero:2015aa, Howlett:2015aa, Izard:2016aa, Chuang:2015aa, Kitaura:2016aa, Munari:2016aa, Sunayama:2016aa}. \nThey also provide a means of understanding systematic effects such as  \nfiber collisions (\\citealt{Guo:2012aa, Manera:2013aa}).\nSince systematic effects can be simulated on them, they allow us to test \nhow these effects influence clustering measurements and devise correction \nmethods that attempt to account for these effects.\n\nA direct way of understanding the effects of fiber collisions on clustering \nstatistics in observations is to first apply fiber collisions to mock catalogs\nand then compare the clustering statistics obtained from mock catalogs with \nand without the fiber collisions. Correction methods for fiber collisions can \nthen be applied to the fiber-collided mocks. The merit of the correction \nmethod can be assessed by how successfully they reproduce the clustering statistics \nof the original mock catalogs without fiber collisions. The correction \nmethod can then be applied to the observed data with some assurance that it \naccounts for fiber collisions and improves the clustering measurements. \n\nWhen applying the fiber collisions to the mock catalogs, it is essential to \napply them in the same manner they affect the observations. For BOSS, galaxies\nwithin $62\"$ are fiber-collided (\\citealt{Anderson:2012aa}). In reality, \nthis criteria is further complicated by the tiling scheme of observing \nplates that create overlapping regions, which have a higher success rate in \nresolving galaxy spectra within the fiber collision angular scale (\\citealt{\nGuo:2012aa, Reid:2012aa}). Furthermore, fiber collisions are only one of the \nsystematic effects that influence BOSS data. Systematic effects include the \nunique geometry of the BOSS survey, the variable completeness in different areas  \ncovered by unique sets of spectroscopic plates, and redshift failures \n(\\citealt{Anderson:2012aa, Ross:2012aa}). \n\n\\def \\cmasscolor{black}\n\\def \\ldgcolor{blue}\n\\def \\nseriescolor{orange}\n\\def \\qpmcolor{blue}\n\\def \\tmcolor{green}\n\\def \\bmdcolor{red}\n\n% FIGURE %%%%%%\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=1.\\textwidth]{figs/fc/mock_catalog_z_dist.pdf} \n\\caption{Normalized galaxy redshift distribution of the Nseries (\\nseriescolor), \nQPM (\\qpmcolor), and BigMultiDark (\\bmdcolor) mock catalogs. The \nnormalized redshift distribution of BOSS DR12 CMASS sample galaxies \nis also plotted (\\cmasscolor). Each of the distributions were computed\nwith a bin size of $\\Delta z = 0.025$. All of the mock catalogs used \nin this work closely trace the BOSS CMASS redshift distribution.}\n\\label{fig:zdist}\n\\end{center}\n\\end{figure}\n\nEffects of fiber collisions must be understood and interpreted in conjunction \nwith the other systematic effects. Therefore, in this paper, we use Quick \nParticle Mesh (\\citealt{White:2014aa}), Nseries (Tinker et al. in prep), and \nthe BigMultiDark (\\citealt{Rodriguez-Torres:2015aa}) mock catalogs, which \nhave already been extensively used in interpreting clustering results for  \nBOSS and are generated through different prescriptions. Therefore they \nprovide a robust sets of data to measure the effects of fiber collisions and \nto test our correction methods. \n\nThe QPM mock galaxy catalogs uses a ``quick particle mesh\" method, which uses \na low resolution particle-mesh N-body solver, with a resolution of \n$2\\;\\mathrm{Mpc}/h$, to evolve particles within a \nperiodic simulation volume. The particles are assigned halo masses in order \nto match the halo mass function and large-scale bias of halos of high resolution \nsimulations. Afterwards the HOD parameterization of \\cite{Tinker:2012aa} is \nused to populate the halos. The mock galaxy sample is then trimmed to the \nBOSS CMASS survey footprint, downsampled based on angular sky completeness \n(sector completeness) and radial selection. Furthermore, QPM mocks model the \nfiber collisions of the BOSS CMASS sample ($62\"$). QPM uses the following \n$\\Lambda$CDM cosmology: $\\Omega_\\mathrm{m} = 0.29$, $\\Omega_\\Lambda = 0.71$, \n$\\sigma_8 = 0.8$, $n_\\mathrm{s} = 0.97$ and $h=0.7$. We use 100 realizations \nof the QPM catalog. For a detailed description of the QPM galaxy mock catalogs \nwe refer readers to \\cite{White:2014aa}. \n\nNext, the Nseries mock catalogs are created from a series of high-resolution \nN-body simulations. Each mock has the same angular selection function as the \nNorth Galactic Cap region of the BOSS DR12 large-scale structure sample for \nCMASS galaxies (\\citealt{Cuesta:2016aa}). They also reproduce the \nredshift distribution of the BOSS CMASS sample. The Nseries mock catalogs are \ncreated from seven independent N-body simulations, each of the same cosmology. \nEach simulation box is $2.5\\;\\mathrm{Gpc}/h$ per side with cosmology: \n$\\Omega_\\mathrm{m} = 0.286$, $\\Omega_\\Lambda = 0.714$, $\\sigma_8 = 0.82$,\n$n_\\mathrm{s} = 0.96$ and $h=0.7$. Out of these Nseries box simulations, the \nthree orthogonal projections of each box is used to create $84$ mocks.\nEach of the cut-out mocks is then passed through the same fiber assignment \ncode as the actual BOSS data using the distribution of plates in BOSS. \nThus, the angular variation of fiber collisions faithfully reproduces \nthat of the data, with $\\sim 5\\%$ of the targets without fibers due to close \nneighbors in regions of the footprint only covered by one tile. \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% P(k) plot for mocks and BOSS --------------------------------------------------\n\\begin{figure*}\n\\begin{center}\n\\includegraphics[width=1.\\textwidth]{figs/fc/mock_catalog_Plk.pdf} \n\\caption{\nPower spectrum monopole $P_0(k)$ and \nquadrupole $|P_2(k)|$ measurements for the Nseries (\\nseriescolor), \nQPM (\\qpmcolor), and BigMultiDark (\\bmdcolor) mock catalogs \n(Section \\ref{sec:catalog}). The $P_l(k)$ measurements \nfor the Nseries and QPM mock catalogs are averaged over the\nmultiple mock realizations and the width of the power spectra represents \nthe sample variance ($\\sigma_l(k)$; Eq.~\\ref{eq:pk_var}) of the realizations. \nFor the quadrupole, we plot the $|{P_2(k)}|$ instead of \n${P_2(k)}$ because the measurement becomes negative for \n$k \\gtrsim 0.35\\;h/\\mathrm{Mpc}$. For comparison, we also include the monopole and \nquadrupole power spectra of the BOSS DR12 CMASS sample, which are calculated \nusing the same estimator but with statistical weights described in Eq.~(\\ref{eq:weight}). \nWhile fiber collisions are inevitably included in the BOSS CMASS power spectra, \nthey are {\\it not} yet applied to the mock catalogs power spectra measurements above. } \n\\label{fig:mockpk}\n\\end{center}\n\\end{figure*}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nFinally the BigMultiDark galaxy mock catalog is generated using the \nBigMultiDark Planck (BigMDPL), one of the MultiDark3 N-body simulations \n(\\citealt{Klypin:2014aa}). BigMDPL uses a GADGET-2 code (\\citealt{Springel:2005ab})\nin a cubic box of $2.5\\;h^{-1}\\mathrm{Gpc}$ sides with $3840^3$ dark matter \nparticles and a mass resolution of $2.4\\times 10^{10} h^{-1}M_\\odot$. \nAs the name suggests, BigMDPL uses Planck cosmological parameters in a flat $\\Lambda$CDM cosmology: \n$\\Omega_m = 0.307$, $\\Omega_B = 0.048$, $\\Omega_\\lambda = 0.693$, $\\sigma_8 = 0.829$, \n$n_s = 0.96$ and $h = 0.678$. \n\nFrom the BigMDPL N-body simulation, \\cite{Rodriguez-Torres:2015aa} uses \nthe $\\mathtt{RockStar}$ (Robust Overdensity Calculation using K-Space Topologically \nAdaptive Refinement) halo finder (\\citealt{Behroozi:2013aa}) to obtain \na dark matter halo catalog. Afterwards, they use the \nSUrvey GenerAtoR code ($\\mathtt{SUGAR}$) to generate a galaxy catalog from the halo \ncatalog. $\\mathtt{SUGAR}$ uses halo abundance matching with an intrinsic scatter \non the stellar mass function of the Portsmouth SED-fit DR12 stellar mass\ncatalog (\\citealt{Maraston:2013aa}) to populate the dark matter halos with  \ngalaxies. \\cite{Rodriguez-Torres:2015aa} then model fiber collisions using \n\\cite{Guo:2012aa} in order to reproduce the effect of fiber collisions on \nthe observed BOSS galaxies. For any further details on the BigMultiDark \ngalaxy mock catalog, we refer readers to \\cite{Rodriguez-Torres:2015aa}.\n\nIn Figure \\ref{fig:zdist}, we plot the normalized redshift distribution of the \nNseries (\\nseriescolor), QPM (\\qpmcolor), and BigMultiDark (\\bmdcolor) \nmock catalogs along with the redshift distribution of the BOSS DR12 \nCMASS sample galaxies. All of these mock catalogs were constructed\nfor the BOSS analysis and their redshift distributions closely \ntrace the observed BOSS distribution.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Powerspectrum Estimator\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Power Spectrum Estimator} \\label{sec:pk_est}\nIn this paper, out of the many possible clustering measurements, we focus on the \ngalaxy power spectrum and its monopole and quadrupole in redshift space. \nThroughout the paper, unless specified, when we measure the \npower spectrum we use the estimator described in \\cite{Scoccimarro:2015aa}, \nwhich accounts for radial redshift space distortions (see also \\citealt{Bianchi:2015aa}). \nIn this estimator, galaxies are interpolated and Fast Fourier \ntransformed as discussed in \\cite{Sefusatti:2016aa}. \nSince the algorithm is efficient, it makes power spectrum computations \nfor large number of mock realizations tractable.\n\nTo summarize the method, we calculate the \nmonopole component of the power spectrum using: \n\\begin{equation}\\label{eq:roman_p0k}\n\\widehat{P_0}(k) = \\frac{1}{I_{22}} \\left[ \\int \\frac{d\\Omega_k}{4 \\pi} |F_0({\\bf k})|^2 - N_0 \\right]\n\\end{equation}\nwhere \n\\begin{equation}\nF_0({\\bf k}) = \\left( \\sum_{j = 1}^{N_g} - \\alpha \\sum_{j=1}^{N_r} \\right) w_j\\;e^{i {\\bf k}\\cdot{\\bf x}_j}\n\\end{equation}\nwith normalization constant\n\\begin{equation} \\label{eq:i22}\nI_{22} = \\alpha \\sum^{N_r}_{j=1} \\bar{n}({\\bf x}_j)w_j^2\n\\end{equation}\nand shot noise term following from the estimator is \\citep{Scoccimarro:2015aa}\n\\begin{equation} \\label{eq:roman_shotnoise}\nN_0 = \\left( \\sum_{j = 1}^{N_g} + \\alpha^2 \\sum_{j=1}^{N_r} \\right) w_j^2, \n\\end{equation}\nwhich represents the constant shot noise contribution to the power due to \nthe discrete density field of our galaxies and random catalog. Here $\\alpha$ is the ratio of the \nnumber of galaxies ($N_g$) over the number of synthetic random galaxies \n($N_r$), $\\bar{n}({\\bf x})$ is the mean density of the galaxies at position \n${\\bf x}$, and $w_j$ is weight of each object, which includes the minimum \nvariance weight from \\cite{Feldman:1994aa}: \n\\begin{equation}\nw_{\\mathrm{FKP}} ({\\bf x}_j) = \\frac{1}{1+\\bar{n}({\\bf x}_j) P_0}\n\\end{equation}\nwhere $P_0$ is the power spectrum amplitude at which the error is minimized. \nWe use $P_0 = 20000\\; \\mathrm{Mpc}^3/h^3$ for our analysis, which corresponds \nto $k \\sim 0.1\\; h/\\mathrm{Mpc}$. We note that the shot noise term in \nEq.~(\\ref{eq:roman_shotnoise}) differs from the standard shot noise term from\n\\cite{Feldman:1994aa}. The difference between various shot noise expressions used in the literature  \nwill be discussed in detail in Section \\ref{sec:shotnoise}. \n\nFor the quadrupole, we have \n\\begin{equation}\\label{eq:roman_p2k}\n\\widehat{P_2}(k) = \\frac{5}{I_{22}} \\int \\frac{d\\Omega_k}{4 \\pi} F_2({\\bf k}) F_0^*({\\bf k})\n\\end{equation}\nwhere \n\\begin{equation}\nF_2({\\bf k}) = \\frac{3}{2}\\hat{k}_a\\hat{k}_b Q^{ab}({\\bf k}) - \\frac{1}{2} F_0({\\bf k})\n\\end{equation}\nwith \n\\begin{equation}\nQ^{ab}({\\bf k}) = \\left( \\sum_{j = 1}^{N_g} - \\alpha \\sum_{j=1}^{N_r} \\right) \\hat{x}_j^a\\hat{x}_j^b w_j \\;e^{i {\\bf k}\\cdot{\\bf x}_j}\n\\end{equation}\n\nIn Figure \\ref{fig:mockpk}, we plot the  power spectrum monopole and quadrupole, ${P_0(k)}$ \nand $|{P_2(k)}|$, measured using Eq.~(\\ref{eq:roman_p0k}) and Eq.~(\\ref{eq:roman_p2k}), respectively, for the Nseries, QPM, and BigMultiDark \nmock catalogs. We plot $|{P_2(K)}|$ because the power spectrum quadruple \nbecomes negative for $k \\gtrsim 0.35\\;h/\\mathrm{Mpc}$. ${P_0(k)}$ and\n$|{P_2(k)}|$ are averaged over the $84$ and $100$ realizations for\nNseries and QPM. We note that fiber collisions are not applied to these mock \ncatalogs. Without fiber collisions, the weights of the objects are equivalent \nto the FKP weights, $w_j = w_{j,\\mathrm{FKP}}$. \n\nWe also plot the $P_0(k)$ and $P_2(k)$ of the BOSS Data Release 12 CMASS \ndata (\\cmasscolor) in Figure \\ref{fig:mockpk}. For BOSS DR12 CMASS, \nsystematic weights are assigned to the galaxies in order to account for \nsector completeness, redshift failures, and fiber collisions. Each galaxy \nhas a statistical weight determined by, \n\\begin{equation} \\label{eq:weight}\nw_{j, \\mathrm{tot}} = w_{j, \\mathrm{sys}} (w_{j, \\mathrm{rf}} + w_{j, \\mathrm{fc}} -1), \n\\end{equation} \n(\\citealt{Anderson:2012aa, Ross:2012aa, Beutler:2014aa}), which are included in the \nfinal object weight $w_j$ along with $w_{j, \\mathrm{FKP}}$. In this formula, $w_{j,\\mathrm{rf}}$ is a weight that accounts for redshift failures and $w_{j,\\mathrm{fc}}$\nis the fiber collision weight determined by the nearest angular neighbor method, which we\nlater discuss in Section \\ref{sec:fc_pk}. The statistical \nweights are also included in $\\alpha = \\sum_{j=1}^{N_g} w_\\mathrm{tot} / N_r$. \nWe note that fiber collisions are inevitably included in the CMASS $P_l(k)$.\nHowever they are not yet included in the $P_l(k)$ of the mock catalogs in Figure \\ref{fig:mockpk}.\n\nFor the mock catalogs with multiple realizations (QPM and Nseries), we \ncompute the sample variance of the power spectrum\n\\begin{equation} \\label{eq:pk_var}\n\\sigma_l (k)= \\sqrt{\\frac{1}{N_\\mathrm{mocks}-1} \\sum\\limits_{i=1}^{N_\\mathrm{mocks}} (P^i_l(k)- \\langle{P_l(k)}\\rangle)^2 \\ }. \n\\end{equation}\n$N_\\mathrm{mock}$ is the number of mock realizations (84 for Nseries and 100 for \nQPM) and $P^i_l(k)$ is the power spectrum for each realization. $\\sigma_l(k)$ is \nrepresented in Figure \\ref{fig:mockpk} by the width of the shaded regions. \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% NN P_l(k) Residual figures \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{figure*}\n\\begin{center}\n\\includegraphics[width=1.\\textwidth]{figs/fc/mock_catalog_NN_true_P024k_resid_rebin6x.pdf} \n\\caption{The fiber collision power spectrum residual, \n$(P_l^\\mathrm{NN}-P_l^\\mathrm{true})$ \n(Section \\ref{sec:fc_pk}), for the monopole (top), quadrupole \n(middle), and hexadecapole (bottom) of the Nseries (left), QPM (middle), and \nBigMultiDark (right) mock catalogs. For the Nseries and QPM mocks, \nwe plot the sample variances $\\sigma_l(k)$ (grey shaded region) of \n$P_l^\\mathrm{true}(k)$ for comparison. The power spectrum residual for the \nNN method is an improvement over the residual with no correction \n($\\Delta P_l^\\mathrm{NoW}(k)$; x) at most scales probed. \nHowever, we highlight that at $k > 0.1 \\;h/\\mathrm{Mpc}$ and \n$k > 0.2\\;h/\\mathrm{Mpc}$, for the monopole and quadrupole \nrespectively, the residuals from fiber collision surpass the sample \nvariance. \nAt smaller scales, NN method does not sufficiently account for \nthe effects of fiber collisions in $P_l(k)$ measurements.}\n\\label{fig:fc_pk}\n\\end{center}\n\\end{figure*}\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=0.7\\textwidth]{figs/fc/mock_catalog_NN_true_P0k_norm_resid_rebin6x.pdf} \n\\caption{{\\it Top Panel}: The normalized residuals, \n$1 - \\overline{P_0^\\mathrm{NN}}/\\overline{P_0^\\mathrm{true}}(k)$, \nof the NN method for the Nseries (\\nseriescolor), \nQPM (\\qpmcolor), and BigMultiDark (\\bmdcolor) power spectrum monopole. \nWe also plot the normalized sample variance $\\sigma_0(k) / P_0(k)$ \n(gray shaded region) of the Nseries mocks for comparison.\nThe QPM $\\sigma_0(k) / P_0(k)$ is effectively the same as the Nseries \n$\\sigma_0(k)/P_0(k)$, so we do not included in the figure. \nThe comparison reveals that the effect of fiber collisions not only \nbiases the power spectrum beyond sample variance at $k \\gtrsim 0.1 \\;h/\\mathrm{Mpc}$, \nbut that the effect increases relative to sample variance at smaller scales. At \n$k = 0.2\\;h/\\mathrm{Mpc}$,  \nthe normalized residual is greater than $4$ times the normalized sample variance.\n{\\it Bottom Panel}: We mark $k_{\\chi^2}$ where $\\Delta \\chi^2(k_{\\chi^2}) = 1$ (Eq.~\\ref{eq:chisquared}) for the NN method. $k^\\mathrm{NN}_{\\chi^2}$ is a conservative \nscale limit of the NN method. Arrows above the dashed \nline mark $k_{\\chi^2}$ for the monopole while the arrows below the dashed line mark\n$k_{\\chi^2}$ for the quadrupole. The color of the arrows indicate the mock catalog: \nNseries (\\nseriescolor), QPM (\\qpmcolor), and BigMultiDark (\\bmdcolor). Averaged\nover the three mock catalogs, we get $k^\\mathrm{NN}_{\\chi^2} = 0.068$ and $0.17 \\;h/\\mathrm{Mpc}$.\nfor the monopole and quadrupole respectively.}\n\\label{fig:NN_norm_resid}\n\\end{center}\n\\end{figure}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% fiber collision Correction Method\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Fiber Collision Methods} \\label{sec:fc_corr}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Effects of Fiber Collision on the Power Spectrum \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Nearest Angular Neighbor Method (NN)} \\label{sec:fc_pk}\nA common approach to accounting for fiber collisions in clustering measurements has been \nto use the nearest angular neighbor method (\\citealt{Zehavi:2002aa, Zehavi:2005aa, \nBerlind:2006aa, Zehavi:2011aa, Anderson:2012aa}),\nhereafter NN method. For galaxies without resolved spectroscopic redshifts due to fiber \ncollisions, the entire statistical weight of the galaxy is assigned to its nearest angular \nneighbor with resolved redshift. \nAccording to \\cite{Zehavi:2002aa}, this method \neffectively assumes that all galaxies within the angular fiber collision scale ($< 62\"$ for BOSS) are correlated with one another. \nIn the context of the halo model, the NN method assumes that \ngalaxies within the fiber collision angular scale reside in the same halo \nso displacing one of the galaxies and placing it on top of the other does \nnot significantly impact clustering statistics. % change it so that it sounds like we're quoting other people's work.\nThis is a reasonable assumption  \nfor the 2PCF and the power spectrum on scales far greater than fiber collisions.  \n\nOne consequence of this method is that galaxies coincidentally within the angular \nfiber collision scale (hereafter referred to as ``chance \nalignments\") are incorrectly assumed to be gravitationally correlated and \nwithin the same halo. So when the statistical weight of the collided galaxy\nis added to its nearest angular neighbor, the collided galaxy is in fact \ndisplaced significantly from its true radial position. This displacement can even \nbe on the scale of the survey depth, which corresponds to $\\sim500\\;\\mathrm{Mpc}$\nfor BOSS. Furthermore, even for fiber collided galaxies that reside in the \nsame gravitationally bound structures such as groups or clusters, up-weighting \nthe nearest neighbor disregards the line-of-sight displacements within these \nstructures. \n\nTo precisely quantify the effect of fiber collisions on the power spectrum, \nwe compare the power spectrum measurements of the NN weighted fiber collided\nmock catalogs $P_l^\\mathrm{NN}$ to the power spectrum measurements of \nthe mock catalogs without fiber collisions, the ``true'' power spectrum \n$P_l^\\mathrm{true}$. Specifically, in Figure \\ref{fig:fc_pk}, we \nplot the power spectrum residual $(P_l^\\mathrm{NN} - P_l^\\mathrm{true})$ as a function of $k$. \nThe power spectrum estimators Eq.~(\\ref{eq:roman_p0k}) and~(\\ref{eq:roman_p2k})  \nare used to calculate the monopole (top) and quadrupole (center) respectively. \nWe include measurements of the sample \nvariance, $\\sigma_l(k)$, for the Nseries and QPM mock catalogs (Eq.~\\ref{eq:pk_var}). \nWe also include the power spectrum residual $\\Delta P_l^\\mathrm{NoW}(k) = \nP_l^\\mathrm{NoW}(k) - P_l^\\mathrm{true}(k)$ (dashed), where $P_l^\\mathrm{NoW}(k)$ is the \npower spectrum of the fiber collided mock catalogs with {\\em no} NN weights,\nwith the collided galaxies removed from the sample. \nIn this paper we focus on the monopole and quadrupole, \nhowever for reference, we also include the effect of fiber collisions on the power spectrum hexadecapole (bottom).\n\nAs both $P_l(k)$ and $\\sigma_l(k)$ vary significantly over the probed $k$ range, the significance \nof the discrepancies between $P^\\mathrm{NN}_l(k)$ and $P^\\mathrm{true}_l(k)$ \nare not adequately portrayed in Figure \\ref{fig:fc_pk}, especially for the monopole. \nTherefore, to compare $P_0^\\mathrm{NN}$ and $P_0^\\mathrm{true}$ over a wide $k$ \nrange and to especially highlight the discrepancies at small scales, in \nFigure \\ref{fig:NN_norm_resid}, we compare the normalized monopole residuals, \n$1 - P_0^\\mathrm{NN}/P_0^\\mathrm{true}$, to the normalized sample variance,\n$\\sigma_0(k)/P_0^\\mathrm{true}$. \n% and plot the normalized residual rather than the  $P_l^\\mathrm{NN} - P_l^\\mathrm{true}$  because $P_l(k)$ spans over three orders of magnitude over the $k$ range probed in our measurement. For instance, although $P_l^\\mathrm{NN} - P_l^\\mathrm{true}$  decreases at small scales, $P_l(k)$ decreases as well; so as the normalized residuals  highlight, the discrepancy is more significant at small scales.  \n\nFor the monopole, Figure \\ref{fig:fc_pk} demonstrates that while the \nNN method (circles) provides an overall improvement over applying no correction (crosses)\nat most scales, fiber collisions still significantly bias the corrected \npower spectrum at all scales. The effect also has a significant $k$ \ndependence, which implies that an adjusted \nconstant shot noise term alone is insufficient in accounting for the deviation. \nEven at $k \\approx 0.1\\;h/\\mathrm{Mpc}$, the effect of \nfiber collisions in the NN method alarmingly surpasses sample variance. \nWhile the amplitude of the residual decreases as $k$ increases, Figure\n\\ref{fig:NN_norm_resid} reveals that as a fraction of \n$P_0^\\mathrm{true}(k)$, the discrepancy is in fact increasing. \nIn other words, the NN method becomes less effective at correcting for \nfiber collisions on smaller scales, as expected. At the smallest scales probed \n($k = 0.83\\;h/\\mathrm{Mpc}$), the $P_0^\\mathrm{NN}(k)$ underestimates the \ntrue power spectrum monopole by over $20\\%$. \n%More importantly, at the scale limits of \n%current power specturm monopole models ($k\\sim 0.3\\;h/\\mathrm{Mpc}$; \n%\\todo{CITECITE}), the average normalized residual of the NN method \n%is $9.8\\%$, which is over six times the normalized cosmic variance, $1.5\\%$. \n\nFor the quadrupole, the NN method improves the power spectrum residuals over \nno correction. However, even with the NN method, the effect of fiber collisions begins \nto significantly grow at $k=0.1\\;h/\\mathrm{Mpc}$ and becomes comparable to \nthe sample variance at $k \\sim 0.2\\;h/\\mathrm{Mpc}$. For $k > 0.2\\;h/\\mathrm{Mpc}$, \nthe effect continues to increase and quickly overtakes the decreasing \nsample variance. At the smallest scales measured ($k = 0.83 \\;h/\\mathrm{Mpc}$) the \nresidual is over eight times the sample variance.\n\nRecently power spectrum analyses have measured the power spectrum using a wide range of \n$k$ bins: for example, \\cite{Anderson:2012aa} use $\\Delta k = 0.04 \\;h/\\mathrm{Mpc}$ and \\cite{Beutler:2014aa} and \\cite{Grieb:2016aa} use \n$\\Delta k = 0.005\\;h/\\mathrm{Mpc}$. Here, we use $\\Delta k = 0.01\\;h/\\mathrm{Mpc}$, \nwhich is within this general range, in agreement with~\\cite{Beutler:2016aa} and \\cite{Gil-Marin:2016ab}. Sample variance measured with larger $\\Delta k$ \nis smaller; so a straight comparison in Figure \\ref{fig:fc_pk} between the power spectrum residuals (symbols) \nand the sample variance (shaded region) has a significant dependence on \nthe choice of $\\Delta k$. What is independent of binning is a cumulative $\\chi^2$ as a function of $k$, and thus we define a $k$ scale limit $k_{\\chi^2}$  \nso that $\\Delta  \\chi^2(k_{\\chi^2}) = 1$, where \n\\beq \\label{eq:chisquared}\n\\Delta \\chi^2(k') = \\sum\\limits_{i,j < N_k} \n\\left[P^\\mathrm{NN}_{l,i} - P^\\mathrm{true}_{l,i}\\right] C^{-1}_{l;\\; i,j}\n\\left[P^\\mathrm{NN}_{l,j} - P^\\mathrm{true}_{l,j}\\right]\n\\eeq\nwhere $N_k$ is the number of bins where $k < k'$ and $C^{-1}_{l; i,j}$ are the elements of the\ninverse covariance matrix for $P_l^\\mathrm{true}(k)$. The elements of the covariance matrix \n$\\mathbf{C}_l$ are computed as \n\\beq\n\\mathrm{C}_{l;\\; i,j} = \\frac{1}{N_{\\mathrm{mocks}}-1}\\sum_{k=1}^{N_{\\mathrm{mocks}}}\n\\Big[P^{(k)}_{l;\\;i}-\\overline{P}_{l;\\;i}\\Big]\n\\Big[P^{(k)}_{l;\\;j}-\\overline{P}_{l;\\;j}\\Big]\n\\nonumber\n\\eeq\nfor the Nseries and QPM mocks. For BigMD, which only has one realization, we use the\ncovariance matrix of the Nseries realizations.  In the lower panel of Figure \\ref{fig:NN_norm_resid}, \nwe mark the monopole and quadrupole $k^\\mathrm{NN}_{\\chi^2}$ for the mock \ncatalogs using the NN method. Arrows above the dashed line mark the monopole \n$k^\\mathrm{NN}_{\\chi^2}$ for Nseries (\\nseriescolor), QPM (\\qpmcolor) and \nBigMultiDark (\\bmdcolor) catalogs. Similarly, the arrows below the dashed line \nmark the quadrupole $k^\\mathrm{NN}_{\\chi^2}$ for the mock catalogs. \nAveraged over the three mock catalogs, we get $k^\\mathrm{NN}_{\\chi^2} = 0.068 \n\\;\\mathrm{and}\\; 0.17\\;h/\\mathrm{Mpc}$ for the monopole and quadrupole respectively.\n% Because of the fine binning we use, the sample variance is overestimated in comparison \n% to the sample variance used in typical analyses. List the delta k bin sizes we use and \n% the one used in other studies. As a result, we define a more conservative metric k_chi^2\n% which is independent of the binning. \n% k_chi^2 definitely reveals that both the monopole and quadrupole are no sufficiently corrected from just the NN method. \n\nAt $k = 0.2\\;h/\\mathrm{Mpc}$, the fiber collision residual for \nthe monopole is over four times sample variance with average normalized \nresidual of $4.4\\%$ compared to the $0.9\\%$ normalized sample variance. \nMoreover, we find that $k_{\\chi^2} = 0.068\\;h/\\mathrm{Mpc}$, which is well below the maximum wavenumbers used typically in analyses. \nFor the quadrupole, the fiber collision residual is approximately equivalent to \nsample variance at $k = 0.2\\;h/\\mathrm{Mpc}$ and $k_{\\chi^2} = 0.17\\;h/\\mathrm{Mpc}$, but it quickly deteriorates with increasing $k$. \nTherefore for theoretical predictions that attempt to go beyond these scales, the effects of \nfiber collisions undoubtedly dominate the sample variance for both the power \nspectrum monopole and quadrupole and the NN method proves to be insufficient. In order to \ncorrect for this effect,  we next present our first approach: the `line-of-sight \nreconstruction' method.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% DLOS Distribution Plot \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{figure*}\n\\begin{center}\n\\includegraphics[width=1.\\textwidth]{figs/fc/mock_catalog_dlos.pdf}\n\\caption{\nNormalized distribution of $d_{\\mathrm{LOS}}$ for Nseries\n(\\nseriescolor), QPM (\\qpmcolor), and BigMultiDark (\\tmcolor) \nmock catalogs. The normalized $d_{\\mathrm{LOS}}$ distribution of \nBOSS DR12 is also plotted (\\cmasscolor). The mock catalog distributions \nhave bin sizes of $\\Delta d = 0.2\\, \\mathrm{Mpc}$, while the CMASS distribution has\na bin size of $\\Delta d = 0.5\\, \\mathrm{Mpc}$. The distribution extends beyond \nthe range of the above plot to $\\sim \\pm 500 \\; \\mathrm{Mpc}$. \nIn the discussion of Section \\ref{sec:dlospeak}, we focus mainly \non the peak of the distribution at roughly\n$-20 \\; \\mathrm{Mpc} < d_\\mathrm{LOS} < 20 \\;\\mathrm{Mpc}$.} \n\\label{fig:d_los}\n\\end{center}\n\\end{figure*}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% DLOSPEAK METHOD \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Line-of-Sight Reconstruction Method} \\label{sec:dlospeak}\n% LOS DISPLACEMENT %%%%\n\\subsubsection{Line-of-Sight Displacement of Fiber Collided Pairs} \\label{sec:dlos}\nIt is impossible to determine definitively from observed galaxy data whether \nindividual fiber collided galaxies without resolved spectroscopic redshifts \nare correlated or chance alignments. However, the line-of-sight displacement of \nfiber collided galaxy pairs with resolved redshifts make it possible to model \nthe overall impact fiber collisions have on displacing galaxies.\n\nFor the BOSS galaxy catalog, fiber collided pairs with resolved spectroscopic \nredshifts are mainly located in the overlapping regions (Section \\ref{sec:catalog}).\nFor the simulated mock catalogs, fiber collisions are post-processed after \nthe galaxy positions are generated. Therefore, \nall galaxies in fiber collided pairs have resolved redshifts. From these resolved \nredshifts we calculate the comoving line-of-sight displacement ($d_{\\mathrm{LOS}}$) \nby taking the difference between the line-of-sight comoving distance of the \nresolved redshifts: \n\\begin{equation}\nd_{\\mathrm{LOS}} = D_{\\mathrm{C}} (z_1) - D_{\\mathrm{C}} (z_2). \n\\end{equation}\n$D_{\\mathrm{C}}(z)$ here is the line-of-sight comoving distance at $z$ \n(\\citealt{Hogg:1999aa}), and $z_1$ and $z_2$ represent the resolved redshifts \nof the two galaxies in the fiber collided pair.\n\nThe normalized distributions of the calculated $d_\\mathrm{LOS}$ for all\nresolved fiber collided pairs are presented in Figure \\ref{fig:d_los}\nfor Nseries (\\nseriescolor), QPM (\\qpmcolor), BigMultiDark (\\bmdcolor), and BOSS DR12 \n(\\cmasscolor). The $d_{\\mathrm{LOS}}$ distributions for all catalogs \nconsist of two components: a peak roughly within the range $-20\\;\\mathrm{Mpc} \n< d_{\\mathrm{LOS}} < 20\\;\\mathrm{Mpc}$ and a flat component (hereafter ``tail\" component) \noutside the peak that extends to $d_{\\mathrm{LOS}} \\sim \\pm 500 \\;\\mathrm{Mpc}$. The \nentire range of the distribution is not displayed in Figure \\ref{fig:d_los}. \nFor BOSS, as mentioned above, the $d_\\mathrm{LOS}$ distribution only reflects the \n$d_\\mathrm{LOS}$ values from galaxy pairs within the fiber collision angular scale \nwith resolved spectroscopic redshifts, mostly from overlapping regions of the survey.\n\nGalaxies within the same halo, due to their gravitational interactions at halo-scales, \nare more likely to be in close angular proximity with each other. These galaxies in \nover-dense regions cause the peak in the $d_{\\mathrm{LOS}}$ distribution. The ``tail\" \ncomponent consists of chance aligned galaxy pairs that happen to be in close angular \nproximity in the sky. \n\nFocusing on the peak of the distribution, we note that it closely traces \na Gaussian functional form. Therefore, we fit\n\\begin{equation} \\label{eq:peak} \np(d_{\\mathrm{LOS}}) = A \\; e^{-{d_{\\mathrm{LOS}}^2}/{2\\sigma_\\mathrm{LOS}^2}}\n\\end{equation}\nfor an analytic prescription of the $d_{\\mathrm{LOS}}$ distribution peak as a \nfunction of $d_\\mathrm{LOS}$ for each of the mock catalogs. We list the \nbest-fit $\\sigma_\\mathrm{LOS}$ obtained by fitting Eq.~(\\ref{eq:peak}) to the \n$d_{\\mathrm{LOS}}$ distribution peak using \nMPFIT (\\citealt{Markwardt:2009aa}) in Table \\ref{tab:mpfit}. The parameter values\nin Table \\ref{tab:mpfit} and Figure \\ref{fig:d_los} illustrate that the \n$d_{\\mathrm{LOS}}$ distributions for the mock catalogs closely trace \nthe BOSS DR12 distribution, which encourages our use of these mock \ncatalogs in our investigation.  \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% DLOS Peak Best-fit Table \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{table} \n\\caption{$d_{\\mathrm{LOS}}$ Distribution Best-fit Parameters} \\label{tab:mpfit}\n\\begin{spacing}{1.5}\n\\begin{center}\n\\leavevmode\n\\begin{tabular}{ccc} \\hline \\hline\nCatalog &$\\sigma_\\mathrm{LOS}$ ($\\mathrm{Mpc}$) & $f_{\\mathrm{peak}}$\\\\ \\hline\nNseries&3.88&0.69\\\\\nQPM&4.35&0.62\\\\\nBigMultiDark&5.47&0.60\\\\ \nCMASS&6.56&0.70\\\\ \\hline\n\\end{tabular} \\par\n%\\begin{tabular}{ccc} \\hline \\hline\n%Catalog &$\\sigma$ ($\\mathrm{Mpc}$) & $f_{\\mathrm{peak}}$\\\\ \\hline\n%Nseries  & 6.85  & 0.71 \\\\ \n%QPM        & 4.98  & 0.65 \\\\ \n%Big Multidark    & 5.38  & 0.57 \\\\ \n%\\end{tabular} \\par\n\\end{center}\n\\end{spacing}\n%    \\bigskip \n{\\bf Notes}: Best-fit parameter $\\sigma_\\mathrm{LOS}$ (Eq.~\\ref{eq:peak}) and peak fraction $f_{\\mathrm{peak}}$ (Eq.~\\ref{eq:fpeak}) for the $d_{\\mathrm{LOS}}$ distributions in Figure \\ref{fig:d_los}. \n\\smallskip\n\\end{table}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nUsing the best-fit to the peak of the $d_{\\mathrm{LOS}}$ distribution, \nwe estimate the fraction of collided pairs that are within the peak as \nthe ratio of pairs with $|d_\\mathrm{LOS}| < 3\\sigma_\\mathrm{LOS}$ \nover the total number of pairs:  \n\\begin{equation} \\label{eq:fpeak}\nf_{\\mathrm{peak}} = \\frac{\\sum\\limits_{|d_\\mathrm{LOS}| < 3 \\sigma_\\mathrm{LOS}} p(d_{\\mathrm{LOS}})}{N_{\\mathrm{pairs}}}, \n\\end{equation}\nwhere $N_{\\mathrm{pairs}}$ is the total number of fiber collided pairs. \n$f_\\mathrm{peak}$ roughly corresponds to the fraction of galaxy pairs that are \ncorrelated. The $f_{\\mathrm{peak}}$ values calculated for the mock catalogs are\nlisted in Table \\ref{tab:mpfit}. They are consistent with the BOSS DR12 $f_\\mathrm{peak}$. \n\nFor the NN method of the previous section to be entirely correct, \nthe $d_{\\mathrm{LOS}}$ distribution in Figure \\ref{fig:d_los} would \nhave to be a delta function, which is clearly not the case. By simply \nincorporating the peak of the $d_{\\mathrm{LOS}}$ distribution, we \ncan significantly improve clustering statistics on small scales. Rather \nthan placing the fiber collided galaxy on top of its nearest angular \nneighbor as the NN correction does, placing the fiber collided galaxy at a \nline-of-sight displacement, sampled from the peak of the $d_{\\mathrm{LOS}}$\ndistribution, away from its nearest neighbor better reconstructs the \ngalaxy clustering on small scales. \n\n%%%%%%%%%% KEY paragraph %%%%%%%% at the end we use SOME of the LOS info, not all! \n% Note that to  reconstruct the full $d_{\\mathrm{LOS}}$ distribution, one would have to sample from it (obtained from overlap tiling regions) to assign redshifts of the collided galaxies. However, here is where one runs into a difficulty: on an object by object basis one does not know a priori if it is physically associated with the colliding galaxy (belonging to a peak) or a chance alignment (belonging to the tail). Therefore, undoing the delta function LOS distribution (given by the NN method) into the correct LOS distribution will make significant mistakes (in object by object basis) particularly for the  fraction $(1-f_\\mathrm{peak})$ of collided galaxies that are deemed to be in the tail of the distribution. As a result, it is more accurate to displace only $f_\\mathrm{peak}$ of the collided pairs, the fraction that is deemed to be correlated, while the other $(1-f_\\mathrm{peak})$ pairs should retain their NN weights. Mistakes will still happen, but for pairs that are physical and are assigned NN weights, we are overestimating the small-scale power, while for chance alignment pairs that are assigned  \n\n% one should not mistake tail objects by uncorrelated, they are approx uncorrelated to the galaxy they collide with, but they are correlated with others, so putting something random is not a good idea after all. NN uses all the positions that are already in the mix, so correlations are preserved up to weights which can be corrected.\n\n\nOnly $f_\\mathrm{peak}$ of the \ncollided pairs should be displaced, since only $f_\\mathrm{peak}$ of the fiber \ncollided pairs are correlated. Meanwhile, the other $(1-f_\\mathrm{peak})$ pairs \nshould retain their NN weights since they are uncorrelated. Displacing these galaxies as well according to the tail piece of the $d_{\\mathrm{LOS}}$ distribution is not desirable because  in an object by object basis we do not know which galaxies should actually be in the tail of the distribution, thus we will be making large mistakes in $d_{\\mathrm{LOS}}$ galaxy by galaxy. In addition, it is difficult to incorporate that these galaxies should be correlated with others and ignoring this modifies large-scale power. In our approach, the remaining $(1 - f_\\mathrm{peak})$ fiber collided pairs are thus kept with their NN weights, and this is reflected in the shot noise correction of our estimator (Eq.~\\ref{eq:roman_shotnoise}), which in turn makes connection to previous methods in the literature as we now discuss.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SHOT NOISE CORRECTION \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% People dicuss shot noise correction in the context of FOurier space thinking that adjusting the shot noise is enough to correct fiber collisions, but of course this is not true. First, if this were true the 2pt function would show no correction; second, fiber collisions would only affect the power spectrum monopole. None of these things is the case. Nevertheless since this has received significant attention in the literature we discuss it in detail in this section. \n\n\\subsubsection{Shot Noise Corrections} \\label{sec:shotnoise} \nMeasurements of the power spectrum are made on observations of discrete \ndistributions of galaxies rather than continuous density fields. The \ndiscreteness contributes to the power spectrum. In order to correct for \nthis contribution, galaxies are assumed to be Poisson samplings of the \nunderlying distribution and a shot noise correction term \nis included in the power spectrum estimator \\citep{Peebles:1980aa, Feldman:1994aa}. \n\nThe expectation value of the shot noise term takes the following form \\citep{Feldman:1994aa},\n\\begin{equation} \\label{eq:integral_shotnoise}\nP_\\mathrm{shot} = \\frac{ (1+\\alpha) \\int d^3r \\;\\bar{n}({\\bf r})w^2({\\bf r})}{\\int\\limits^{ } d^3r \\;\\bar{n}^2({\\bf r})w^2({\\bf r})}. \n\\end{equation}\n\n\\noindent Note that for the case of uniform weights ($w={\\rm const.}$), \nconstant number density and no random catalog this reduces to the standard \nshot-noise Poisson correction $P_\\mathrm{shot} =\\bar{n}^{-1}$. \nIn practice the integrals in Eq.~(\\ref{eq:integral_shotnoise}) can be \nwritten as discrete sums over the synthetic random catalog \n\\citep{Feldman:1994aa}. $\\int d^3r \\; \\bar{n}({\\bf r}) ...$ \nis computed as $\\alpha \\sum_{\\mathrm{ran}}...$. Then the shot noise term \nbecomes, \n\\begin{equation} \\label{eq:fkp_shotnoise}\nP^\\mathrm{FKP}_\\mathrm{shot} = \\frac{(1+\\alpha) \\alpha \\sum\\limits_{\\mathrm{random}} w_\\mathrm{FKP}^2({\\bf r})}{\\alpha \\sum\\limits_{\\mathrm{random}}^{ } \\bar{n}({\\bf r})\\; w_\\mathrm{FKP}^2({\\bf r})}.\n\\end{equation} \nThis however, represents the expectation value of the shot noise, not the actual value \n(\\citealt{Hamilton:1997aa}) since all quantities involved are mean values (calculated through the random catalog). To use the full information provided by the data, the shot noise of the galaxies should be computed from the actual galaxy weights, not the randoms. This simply corresponds to taking the self-pairs in the power spectrum estimator, Eq.~(\\ref{eq:roman_p0k}), which leads to Eq.~(\\ref{eq:roman_shotnoise}) and we can rewrite here as,\n\n\\beqa \\label{eq:ourshot}\nP^\\mathrm{Hahn+}_\\mathrm{shot} &=& \\frac{\\sum\\limits_{\\mathrm{galaxy}} w^2_\\mathrm{FKP}({\\bf r})\\, w^2_\\mathrm{tot}({\\bf r}) + \\alpha^2 \\sum\\limits_{\\mathrm{random}} w_\\mathrm{FKP}^2({\\bf r})}{\\alpha \\sum\\limits^{ }_{\\mathrm{random}} \\bar{n}({\\bf r})\\, w_\\mathrm{FKP}^2({\\bf r})}\\nonumber  \\\\ & & \n\\eeqa\nwhere $\\alpha = (\\sum_\\mathrm{gal} w_\\mathrm{tot} )/N_r$. \nWe emphasize that this is {\\em the} shot noise of the estimator. \nIn other words, if one takes the limit $k \\to \\infty$, the \nestimator in Eq.~(\\ref{eq:roman_p0k}) will approach this \nvalue if no shot-noise subtraction is applied. The systematic \neffects from completeness, redshift failures and fiber collisions are accounted for through $w_\\mathrm{tot}$ of the observed galaxies. In our case, $w_\\mathrm{tot}=w_\\mathrm{sys}$ for the resolved $f_\\mathrm{peak}$ fraction of galaxies that have been displaced away from their NN positions, while $w_\\mathrm{tot}>w_\\mathrm{sys}$ for the $(1-f_\\mathrm{peak})$ fraction of galaxies that are deemed to be in the tail of the LOS distribution and are described by NN weights of the galaxies they collided with. \n\n\n% now connect to the literature...\n% people had tried to model the effects of fc's by adjusting shot noise as a way to describe the large-scale effects of fc's\n% problem: is not just a constant, does nothing for quad, does nothing for xi, the true constant depends on small scale power as we shall see so it's hard to hack it this way.\n\nRecent work in the literature of power spectrum analysis modeled the effect of fiber collisions by solely modifying the shot noise term for the NN method \\citep{Beutler:2014aa, Gil-Marin:2014aa}. \nThis assumes that the effect of fiber collisions beyond NN weights is to alter the large-scale effective shot noise, and therefore that only the power spectrum monopole is affected since the quadrupole is free of shot noise. \n\\cite{Beutler:2014aa} supplements the NN method with a shot noise correction term given by,\n\\begin{equation} \\label{eq:florian}\nP^\\mathrm{B2014}_\\mathrm{shot} = \\frac{\\sum\\limits_{\\mathrm{galaxy}} w^2_\\mathrm{FKP}w_\\mathrm{tot}({\\bf r})w_\\mathrm{sys}({\\bf r}) + \n\\alpha^2 \\sum\\limits_{\\mathrm{random}} w_\\mathrm{FKP}^2({\\bf r})}\n{\\alpha \\sum\\limits_{\\mathrm{random}}^{ } \\bar{n} \\; w_\\mathrm{FKP}^2({\\bf r})}.\n\\end{equation}\nNote that in the first term of the numerator in this equation $w_\\mathrm{fc}$ is only \nincluded in $w_\\mathrm{tot}$ as it does not enter in $w_\\mathrm{sys}$. \nWe note that beyond their choice of Eq.~(\\ref{eq:florian}) \nfor the shot noise correction term, \\cite{Beutler:2014aa} marginalizes over \na constant stochasticity term in their analysis \\citep[see Eq.~40 in][]{Beutler:2014aa}.\nThus, the impact of this particular choice is not straightforward. \n%It is also worth noting that \\cite{Beutler:2014aa} ends up marginalizing over the value of the shot noise in their analysis, thus the impact of this particular choice is not straightforward.\n\n\nMeanwhile, \\cite{Gil-Marin:2014aa} constructs $P_\\mathrm{shot}$ using two separate \ncomponents: one for ``true pairs'' and the other for ``false pairs\". \nThe shot-noise contribution to the power from ``true pairs'' is the same as \nEq.~(\\ref{eq:florian}) while the ``false pairs'' shot-noise contribution is \n(same as Eq.~\\ref{eq:ourshot}), \n\\begin{equation} \\label{eq:gm_falsepairs}\nP^\\mathrm{False}_\\mathrm{shot} = \\frac{\\sum\\limits_{\\mathrm{galaxy}} w^2_\\mathrm{FKP}w^2_\\mathrm{tot}({\\bf r}) + \n\\alpha^2 \\sum\\limits_{\\mathrm{random}} w_\\mathrm{FKP}^2({\\bf r})}\n{\\alpha \\sum\\limits^{ }_{\\mathrm{random}} \\bar{n} \\; w_\\mathrm{FKP}^2({\\bf r})}.\n\\end{equation}\n\\cite{Gil-Marin:2014aa} calculates the total $P_\\mathrm{shot}$ as the \nweighted combination of $P^\\mathrm{True}_\\mathrm{shot}$ and\n$P^\\mathrm{False}_\\mathrm{shot}$: \n\\begin{equation} \\label{eq:gm_shot}\nP^\\mathrm{GM2014}_\\mathrm{shot} = (1- x_\\mathrm{PS}) P^\\mathrm{True}_\\mathrm{shot} +\nx_\\mathrm{PS}\\, P^\\mathrm{False}_\\mathrm{shot}\n\\end{equation}\nIn their analysis, \\cite{Gil-Marin:2014aa} use $x_\\mathrm{PS} = 0.58$, \nwhich they infer by measuring the difference between \nthe true and the fiber-collided power spectrum monopole in the $\\mathtt{PTHalos}$ \ngalaxy mock catalogs (\\citealt{Manera:2013aa}). Unfortunately, since the true \npower spectrum is the measurement we are trying to recover from the observations, the \n$x_\\mathrm{PS}$ parameter cannot be inferred or validated from the actual \nBOSS observations. Moreover, one might worry about relying $\\mathtt{PTHalos}$ or similar methods that are not based on \nhigh resolution N-body simulations, to extract corrections for fiber collisions that depend on small-scale power. An extension of this approach is used in recent BOSS analyses  \\citep{Beutler:2016aa,Grieb:2016aa,Gil-Marin:2016aa} where Eq.~(\\ref{eq:gm_shot}) is used and is supplemented with a marginalization over the shot noise value. However, as we discussed above, this has no effect in the quadrupole power spectrum, which remains the same as in the NN method.\n\nAt this point it is worth casting our ``line-of-sight reconstruction\" (LRec) \nmethod in similar language to the methods we just discussed. We treat the \n``true pairs\" (what we called peak-pairs) by displacing them according to \nthe peak LOS distribution, which modifies all the power spectrum multipoles, \nand use the NN method for the ``false pairs\" (pairs in the tail of the LOS \ndistribution). Our shot noise correction is not adjusted, rather it is the \ntrue shot noise from the estimator. \n%, although note that because a fraction $f_{\\rm peak}$ pairs have been resolved, the weights for all such pairs is $w_\\mathrm{fc}=1$, which of course will be reflected in a lower shot noise value. \nWe now discuss the implementation and performance of our  LRec fiber collision method. \n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% dLOS Peak Correction P(k) Ratio Figure \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{figure*}\n\\begin{center}\n\\includegraphics[width=1.\\textwidth]{figs/fc/mock_catalog_dlospeak_true_Plk_resid_floran_offset250_0_rebin6x.pdf} \n\\caption{The power spectrum residual of the line-of-sight reconstruction (LRec) \nmethod (Section \\ref{sec:dlospeak}), \n$\\Delta P_\\ell \\equiv P_l^\\mathrm{LRec} -P_l^\\mathrm{true}$, \nfor the monopole (top) and quadrupole (bottom) power spectra of the \nNseries (left), QPM (middle), and BigMultiDark (right) mock catalogs. \nWe again plot the Nseries and QPM sample variances, $\\sigma_l(k)$.\nThe residuals for the monopole show good agreement between \n$P_0^\\mathrm{LRec}$ and $P_0^\\mathrm{true}$ for the entire $k$ range. \nFor the quadrupole, while the LOS Reconstruction method improves the residuals \ncompared to the NN method at small scales ($k > 0.2\\;h/\\mathrm{Mpc}$), \nthe residuals remain comparable to sample variance at $k=0.2\\;h/\\mathrm{Mpc}$.\nIn the top panels, we include the residuals from the fiber collision \ncorrection method of \\cite{Gil-Marin:2014aa} (dashed). \nAs the \\cite{Gil-Marin:2014aa} method supplements \nthe NN method with adjustments to the constant shot noise term of the estimator, \nit fails to correct for the $k$ dependence of the effect and is insufficient \nin accounting for fiber collisions at small scales. \nWe do not include the correction method of \\cite{Beutler:2014aa} because they \nmarginalize over a constant stochasticity term in their analysis so the effect \nof their correction on $P(k)$ is not straightforward.}\n%so we plot the correction from Eq.~(\\ref{eq:florian}) offset by $-250$ to match \n%low-$k$ residuals on the left panel.}} \n\\label{fig:peaksn}\n\\end{center}\n\\end{figure*}\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=0.75\\textwidth]{figs/fc/mock_catalog_dlospeak_true_P0k_norm_resid_rebin6x.pdf} \n\\caption{{\\it Top Panel}: The normalized residual, \n$1 - P_l^\\mathrm{LRec}/P_l^\\mathrm{true}$, \nfor the Nseries (\\nseriescolor), QPM (\\qpmcolor), and BigMultiDark (\\bmdcolor)\nmonopole power spectra. The normalized sample variance $\\sigma_l / P_l(k)$ \n(gray shaded region) of the Nseries mocks is plotted for comparison. At \n$k = 0.1 \\;h/\\mathrm{Mpc}$, where the NN method residuals exceeds sample \nvariance, the average normalized residual for the LRec method is $0.25\\%$ \ncompared to $1.5\\%$ normalized sample variance. In fact, the average \nresidual stays below the sample variance until $k = 0.53\\;h/\\mathrm{Mpc}$.\n{\\it Bottom Panel}: We mark $k^\\mathrm{LRec}_{\\chi^2}$ for the monopole (arrows above the \ndashed line) and quadrupole (arrows below the dashed line). \nThe average $k^\\mathrm{LRec}_{\\chi^2}$ for the mock catalogs\nare $0.29$ and $0.14\\;h/\\mathrm{Mpc}$ for the monopole and quadrupole respectively. \nFor comparison, we mark $k^\\mathrm{NN}_{\\chi^2}$ (black) from Section \\ref{sec:fc_pk}. \nWe also include $k_{\\chi^2}$ of the \\cite{Gil-Marin:2014aa} correction method (gray) for \nthe monopole. The LOS reconstruction method significantly \nextends $k_{\\chi^2}$ beyond that of the NN method and \\cite{Gil-Marin:2014aa} for $l=0$. \nHowever, it does not improve $k_{\\chi^2}$ for the quadrupole. \n} \n\\label{fig:dlospeak_norm_resid}\n\\end{center}\n\\end{figure}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Correction Method in Practice \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{In Practice}\nWe first begin with fiber collided mock catalogs with the NN \nfiber collision weights that accurately simulate the effects of \nfiber collisions on the actual BOSS observations. From this catalog, we\nconstruct the $d_\\mathrm{LOS}$ distribution, as described in Section \n\\ref{sec:dlos} and fit for the best-fit parameters $\\sigma_\\mathrm{LOS}$ \nand $f_\\mathrm{peak}$ of Eq.~(\\ref{eq:peak}).\n\nWe select $f_\\mathrm{peak}$ of the fiber collided galaxy pairs in the catalog \nand designate them as correlated pairs that lie within the peak of the \n$d_\\mathrm{LOS}$ distribution. We refer to these fiber collided pairs as \n``peak-assigned\". At this point, each of these pairs, based on their NN \nweights, consist of the ``nearest-neighbor\" galaxy with $w_\\mathrm{fc} > 1$ \nand the ``collided\" galaxy with $w_\\mathrm{fc} = 0$. We discard the collided galaxy\nsince the redshifts of collided galaxies are not known in actual observations. \n\nNext for each of the nearest-neighbor galaxies in peak-assigned pairs, we \nplace a new galaxy with $w_\\mathrm{fc} = 1$ at a displacement $d_\\mathrm{peak}$ \naway from it along the line-of-sight but at the same angular position. The $d_\\mathrm{peak}$ \nvalue is sampled from a Gaussian with best-fit $\\sigma_\\mathrm{LOS}$ from \nTable \\ref{tab:mpfit}. The $w_\\mathrm{fc}$ of the ``nearest-neighbor\" galaxy \nis then reduced by $1$. This process is repeated, in the cases of triplets \nor higher with $w_{\\rm fc} > 2$, until all the nearest-neighbor galaxy in \npeak-assigned pairs have $w_\\mathrm{fc}=1$. The resulting {\\em total} catalog will have fewer \ngalaxies with $w_\\mathrm{fc} > 1$ compared to the initial fiber collided catalog.\nHowever, the total statistical weight ($\\sum_\\mathrm{gal} w_\\mathrm{tot}$) of \nthe catalog, being equal to the total number of galaxies before the collisions\nare applied, is conserved. \n%\\todo{I'm confused by this explanation, at the end of the day $w_{fc}=1$ for all, right?}\n\nNow that we have the ``LOS reconstructed\" mock catalog, we measure its power \nspectrum monopole and quadrupole ($P^\\mathrm{LRec}_l$). In Figure \n\\ref{fig:peaksn} we present the power spectrum residual, \n$(P^\\mathrm{LRec}_l-P^\\mathrm{true}_l)$,  \nfor $l = 0$ and $2$ of the LOS Reconstruction method power spectrum averaged over all the available realizations. \nWe again include the Nseries and QPM sample variance, $\\sigma_l(k)$ \n(grey shaded region) for comparison.  In Figure \\ref{fig:dlospeak_norm_resid}, \nwe normalize both the residuals and the sample variance by $P_0^\\mathrm{true}$ \nto better compare $P_0^\\mathrm{LRec}$ and $P_0^\\mathrm{true}$ at different scales \nand to highlight the small scales. \n\nFor the monopole, at the scale where $P^\\mathrm{NN}_0$ deviates from \n$P^\\mathrm{true}_0$ by more than the sample variance ($k \\sim 0.1\\;h/\\mathrm{Mpc}$), \nFigure \\ref{fig:peaksn} shows that the LOS reconstructed residual is well within the \nsample variance, $P^\\mathrm{LRec}_0 - P^\\mathrm{true}_0 < 0.17\\, \\sigma_0$. \nEven at the smallest scales measured for our monopole measurements \n($k = 0.83\\;h/\\mathrm{Mpc}$), well beyond the scales that can be predicted from current models based on perturbation theory, the normalized residuals for \nthe LOS reconstructed method remains at $3.7\\%$. At $k \\sim 0.2\\;h/\\mathrm{Mpc}$, the average normalized \nresidual is $0.19\\%$ compared to the $0.9\\%$ normalized sample variance. \nWhen we calculate the $k_{\\chi^2}$ of the LOS reconstruction method for \nthe three mock catalogs, as we did for the NN method in Section \\ref{sec:fc_pk}, \nwe get the average $k_{\\chi^2}^\\mathrm{LRec} = 0.29\\;h/\\mathrm{Mpc}$ for the monopole. \nFor each of the mocks, we mark $k_{\\chi^2}^{\\mathrm{LRec};\\;l=0}$ in the lower panel \nof Figure \\ref{fig:dlospeak_norm_resid} above the dashed horizontal line. \n\n\nFor the monopole, we also include residuals from the \nfiber collision correction method of \\cite{Gil-Marin:2014aa} (dashed) in \nFigure~\\ref{fig:peaksn}.\n\\cite{Gil-Marin:2014aa} corrects for fiber collisions by adjusting the \nconstant shot noise term in the estimator in addition to the NN method \n(Section \\ref{sec:shotnoise}).\nHowever, as the NN method power spectrum residuals reveal in \nFigure \\ref{fig:fc_pk}, the effect is $k$ dependent, especially \nat $k > 0.1 \\;h/\\mathrm{Mpc}$. \nSo while this correction can reduce the residuals \nto within sample variance on large scales, it fails to account for \nthe $k$ dependence, which quickly goes on to dominate sample variance \nat smaller scales, $k > 0.1 \\;h/\\mathrm{Mpc}$.\n\nWe also calculate $k_{\\chi^2}$ for the \\cite{Gil-Marin:2014aa} \ncorrection method using the mock catalogs, \n$k_{\\chi^2}^\\mathrm{GM+} = 0.17 \\;h/\\mathrm{Mpc}$ (gray arrow; Figure \\ref{fig:dlospeak_norm_resid}), \nwhich is significantly lower than that of the LOS Reconstruction method. \nThe LOS reconstruction method better accounts for fiber collisions at all \nscales. Furthermore, as already discussed, the \\cite{Gil-Marin:2014aa} \nmethod does {\\em not} provide corrections for the power spectrum \nquadrupole or higher multipoles, thus Figure~\\ref{fig:fc_pk} still applies for $\\ell=2$.\n\nWe note that the correction method of \\cite{Beutler:2014aa} \nis not included in Figure~\\ref{fig:peaksn}. Instead of using \na fixed value for the constant shot noise as \\cite{Gil-Marin:2014aa} does, \n\\cite{Beutler:2014aa} includes a constant `stochasticity term', $N$, \nin their analysis (see Eq. 40 of \\citealt{Beutler:2014aa}). This $N$ is \nwithin the exponential factor that models the Finger-of-God effect, so their \ncorrection is $k$ dependent and impacts the multipoles beyond the monopole.\nHowever because \\cite{Beutler:2014aa} marginalizes over $N$, the effect \nof this correction is not straightforward. When we use the best-fit parameter \nvalues from \\cite{Beutler:2014aa}, we find that the correction actually \n{\\em increases} the effect of fiber collisions on both the monopole \nand quadrupole. This however, neglects the impact of stochastic bias \nin the $P(k)$ model. Nevertheless, we also find that no value of $N$ in the \n\\cite{Beutler:2014aa} correction can simultaneously \naccount for the effect of fiber collisions in both the monopole and quadrupole.\n\n%For the monopole, we also include the residuals from the \n%fiber collision correction methods of \\cite{Beutler:2014aa} (pluses) and \n%\\cite{Gil-Marin:2014aa} (dashed) in Figure \\ref{fig:peaksn}. \n%Both these analyses correct for fiber collisions by adjusting the constant \n%shot noise term in the estimator in addition to the NN method (Section \\ref{sec:shotnoise}).\n%However, as the NN method power spectrum residuals reveal in Figure \\ref{fig:fc_pk},\n%the effect has a $k$ dependence, especially at $k > 0.1 \\;h/\\mathrm{Mpc}$.  \n%So while these corrections can reduce the residuals to within sample variance \n%at large scales, they fail to account for the $k$ dependence, \n%which quickly goes on to dominate sample variance at smaller scales, \n%$k > 0.1 \\;h/\\mathrm{Mpc}$.  \n\n%We note that instead of using a fixed value for the constant shot noise\n%as \\cite{Gil-Marin:2014aa} does, \\cite{Beutler:2014aa} marginalize over \n%the constant term in their analysis. To  reflect this,\n%we offset the power spectrum residual we get using Eq.~(\\ref{eq:florian}) \n%by $-250$ in Figure \\ref{fig:peaksn} to force agreement at $k\\to 0$ \n%in the Nseries case. For simplicity, we only calculate $k_{\\chi^2}$ \n%for the \\cite{Gil-Marin:2014aa} correction method using the mock catalogs: \n%$k_{\\chi^2}^\\mathrm{GM+} = 0.17 \\;h/\\mathrm{Mpc}$ (gray arrow; Figure \\ref{fig:dlospeak_norm_resid}), \n%which is significantly lower than that of the LOS Reconstruction method. \n%Compared to either method, the LOS reconstruction \n%method better accounts for fiber collisions at all scales. \n%{\\color{red} \\bf Furthermore, as already discussed, \n%the \\cite{Gil-Marin:2014aa} method does not provide corrections for the power \n%spectrum quadrupole or higher multipoles, thus Figure~\\ref{fig:fc_pk} \n%still applies for $\\ell=2$.}\n\nFrom Figure~\\ref{fig:peaksn} we see that for the quadrupole, the LOS reconstruction method does not \nsufficiently improve corrections for fiber collisions compared to the NN method.\nThe residuals for $k > 0.2\\;h/\\mathrm{Mpc}$ are improved compared to Figure~\\ref{fig:fc_pk}; however, they \nstill exceed the sample variance. Unfortunately, these improvements on small scales\ncome at the cost of increased residuals on large scales. In the $k_{\\chi^2}$ marked \nin Figure \\ref{fig:dlospeak_norm_resid} (below the dashed line), we see that the\nincreased residuals at large scales actually make the average $k_{\\chi^2}^\\mathrm{NN} > \nk_{\\chi^2}^\\mathrm{LRec} = 0.14\\;h/\\mathrm{Mpc}$ for the quadrupole, although there is significant dispersion between the different simulations with Nseries showing improvements when compared to the NN method while the other two showing worse performance. Consequently, neither the LOS reconstruction method nor the NN method sufficiently \naccount for fiber collisions in the power spectrum quadrupole. \n\nThe shortcomings of the LOS reconstruction method for the quadrupole compared \nto the monopole does not come as a surprise since the quadrupole is more \nsensitive to getting the correct LOS displacements galaxy by galaxy \n(not just statistically), as these modify the fingers-of-god effect. \nIn order to make further progress with this method one would have to \ndetermine for each galaxy the most likely halo in which it lives \n(this could be nearby or a distant, chance alignment), determine its \nvelocity dispersion and then assign a LOS displacement consistent \nwith the dispersion and the observed LOS distribution. \n\nLet us now discuss a few attempts that we have implemented along these lines. \nThe first is incorporating more information about the fiber collided pairs \nin order to better classify \ncorrelated and chance alignment pairs. For example, information about \nlarger scale galaxy environment in the form of the $N^{th}$ nearest neighbor \ndistance ($d_{nNN}$), can be included to parameterize the $\\sigma_\\mathrm{LOS}$ \nand $f_\\mathrm{peak}$ (Table \\ref{tab:mpfit}) as a function of $d_{nNN}$. \nThe $d_{nNN}$ in this case is the distance of the $n^{th}$ nearest \nneighbor of the nearest-neighbor galaxy within the fiber collided pair.  \nAnother way the LOS reconstructed method can be improved is by utilizing \nthe photometric redshifts of the collided galaxies to improve the \ncorrelated/change alignment pair classification. \n\nWe explored the LOS reconstructed method with both of these improvements \non the mock catalogs. We find that there is indeed a significant correlation \nbetween $d_{nNN}$ and the parameters $\\sigma_\\mathrm{LOS}$ and \n$f_\\mathrm{peak}$, which can be exploited. Also, photometric redshifts assigned \nto collided galaxies based on the \n$|z_\\mathrm{spec} - z_\\mathrm{photo}|/(1 + z_\\mathrm{spec})$\nof actual BOSS photometric redshift catalogs improves classification of \ncorrelated versus chance alignment fiber collided pairs, as well. These \nimprovements bring the normalized residuals of the monopole to $\\sim 1\\%$\nat $k = 0.83\\;h/\\mathrm{Mpc}$. However, the improvement in the fiber collision \ncorrection for the quadrupole is marginal; the effect of fiber collisions \nat $k = 0.2\\;h/\\mathrm{Mpc}$ is still comparable to the sample variance. So \neven with these improvements the LOS reconstructed method is insufficient. \n\nFurthermore, for the Nseries mocks, we find that if we use the LOS reconstructed method with \nperfectly classified correlated and chance alignment pairs, the \nresidual is roughly half the sample variance at $k \\sim 0.2\\;h/\\mathrm{Mpc}$\nand greater than sample variance at $k > 0.35\\;h/\\mathrm{Mpc}$.\nThe displacement of the collided galaxy by $d_\\mathrm{LOS}$ sampled from Eq.~(\\ref{eq:peak}) \nalone causes the power spectrum quadrupole to deviate from the true value\nat small scales. A method such as the LOS reconstructed method for the quadrupole \nwould require more sophisticated modeling of the fiber collided galaxy pairs that capture the displacements in an object by object basis. \n\nAs a result of the shortcomings of the LOS reconstructed method for the power spectrum \nquadrupole, we now present a complementary approach in dealing with fiber collision \nin power spectrum multipole analyses, which rather than attempting to correct the \ndata before making measurements, computes theoretical predictions of the fiber-collided \npower spectrum multipoles. \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% 2PCF Ratio, tophat figure\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{figure*}\n\\begin{center}\n\\includegraphics[width=1.\\textwidth]{figs/fc/2pcf_Nseries_upweighted_5mocks_5x5_tophat.pdf} \n\\caption{$1 - (1 + \\xi^\\mathrm{NN})/(1+\\xi^\\mathrm{true})$ as a \nfunction of transverse displacement, $r_p$, and line-of-sight \ndisplacement $\\pi$ (left). The color bar represents the value of this quantity. Note there is no detectable dependence on $\\pi$.\nThe dashed vertical line (black) represents the constant \n$r_p = D_\\mathrm{fc}(z=0.55)$ (Section \\ref{sec:fourier}). \nWe also plot $1 - (1 + \\xi^\\mathrm{NN})/(1+\\xi^\\mathrm{true})$\nprojected along $\\pi$ (right). In the left panel, the $r_p = D_\\mathrm{fc}(z=0.55)$ \nvertical line and the sharp cut-off of the contour show good agreement with the expected characteristic scale. \nIn the right panel, the projected $1 - (1 + \\xi^\\mathrm{NN})/(1+\\xi^\\mathrm{true})$\nis in good agreement with $f_s W_\\mathrm{fc}(r_p)$. The agreement in both panels\njustify the characterization of the effect of fiber collisions on the 2PCF in \nEq.~(\\ref{eq:tophat_2pcf}).}\n\\label{fig:2pcf_tophat}\n\\end{center}\n\\end{figure*}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Fourier Tophat Method \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Effective Window Method} \\label{sec:fourier}\nThe LOS Reconstruction method corrects for fiber collisions in the observed galaxy positions \nin order to estimate the systematics-free true power \nspectrum. In power spectrum analyses, this true power spectrum estimate\ncan be compared to model power spectrum for cosmological parameter inference. \nAlternatively, however, the observed fiber collided power spectrum can be \ncompared to the model power spectrum with the effect of fiber collisions imposed \non it. This is the approach we follow from now on.\n\nWe proceed as follows. In Section \\ref{sec:tophat_theory} we find that the effect of fiber collisions \non the two-point correlation function can be well approximated by a simple \nanalytic expression. Using this, we accurately estimate the \neffect of fiber collisions on the power spectrum in Fourier space. The effect \nis a function of the true power spectrum and depends significantly on the \npower spectrum at small scales, which cannot reliably be modeled from first principles. As a result, in Section~\\ref{sec:tophat_practice}, we \npresent a practical approach to circumvent this issue and account for the effect of fiber collisions in \npower spectrum analyses. \n\n\\subsubsection{In Theory} \\label{sec:tophat_theory}\nIn the BOSS galaxy catalog, which spans the redshifts $0.43 < z < 0.7$, \nthe comoving distance of the $62\"$ fiber collision angular scale \n($D_\\mathrm{fc}$) ranges from $0.35\\;\\mathrm{Mpc}$ to $0.52\\;\\mathrm{Mpc}$. \nGiven the relatively small variation in $D_\\mathrm{fc}$, we assume \nthat throughout the survey redshift the physical scale remains\nconstant as $D_\\mathrm{fc}(z \\sim 0.55) = 0.43 \\mathrm{Mpc}$, at the median \nredshift of the survey. If the physical scale of fiber collisions is constant, \nfiber collisions will affect the two-dimensional configuration space two-point \ncorrelation function, $\\xi(r_p, \\pi)$, through its effect on galaxy pairs with \ntransverse separations $r_p < D_\\mathrm{fc}$. As no pairs will be found \nbelow this characteristic scale, $\\xi(r_p, \\pi)$ will be -1 \nfor $r_p < D_\\mathrm{fc}$, and note that  the same is true for the two-point function in the NN method (since small-$r_p$ pairs are collapsed into zero separation described by weights). On the other hand, at large scales we can approximate $\\xi(r_p, \\pi)$ by the NN method which preserves the large-scale angular correlation function, thus \nthe effect of fiber collisions on $\\xi(r_p, \\pi)$ can be analytically characterized by  the following relation between the true and the NN two-point functions,\n\\begin{equation} \\label{eq:tophat_2pcf}\n\\frac{1 + \\xi^\\mathrm{NN}(r_p, \\pi)}{1 + \\xi^\\mathrm{true}(r_p, \\pi)} =1 -  f_s W_\\mathrm{fc}(r_p)\n\\end{equation}\nwhere $W_\\mathrm{fc}(r_p)$ represents the top-hat function\n\\begin{spacing}{1.5}\n\\begin{equation} \\label{eq:tophat}\nW_\\mathrm{fc}(r_p) = \n\\begin{cases}\n1 & \\text{if}\\ r_p < D_\\mathrm{fc} \\\\\n0 & \\text{otherwise}\n\\end{cases}\n\\end{equation}\n\\end{spacing}\n\\noindent and $f_s$ represents the fraction of the survey area affected by fiber \ncollisions. Note in Eq.~(\\ref{eq:tophat_2pcf}) we have assumed that we can linearly superpose the contributions to the two-point function from regions with and without collisions, and a key property of Eq.~(\\ref{eq:tophat_2pcf}) is that its right hand side does not depend on $\\pi$, something we test explicitly below. \nIn the BOSS, $f_s$ is precisely known because \nit corresponds to the fraction of the survey geometry that suffers from \nfiber collisions. These are the regions that do not have overlapped tiling \n(Section \\ref{sec:catalog}). For BOSS DR12 $f_s = 0.6$. \n\nWe measure $\\xi^\\mathrm{NN}$ and $\\xi^\\mathrm{true}$ for the Nseries \nmock catalogs using the $\\mathtt{CUTE}$ software (\\citealt{Alonso:2012aa}), which \nuses the standard \\cite{Landy:1993aa} estimator. $\\xi^\\mathrm{NN}$ \nis calculated from the NN fiber collided Nseries mocks while \n$\\xi^\\mathrm{true}$ is calculated from the Nseries mocks without fiber \ncollisions. Using the measured $\\xi^\\mathrm{NN}$ and $\\xi^\\mathrm{true}$, \nwe plot \n$1- (1+\\xi^\\mathrm{NN})/(1 + \\xi^\\mathrm{true})$ averaged over realizations as \na function of $r_p$ and $\\pi$ (left) and its projection \nalong $\\pi$ (right) in Figure \\ref{fig:2pcf_tophat}. The dashed vertical \nline (black; left) marking $r_p = D_\\mathrm{fs}(z=0.55)$ and $f_s W_\\mathrm{fc}(r_p)$ \n(black dashed; right) are plotted for comparison. The agreement \nbetween the $\\xi(r_p, \\pi)$ contours and the $r_p = D_\\mathrm{fc}(z=0.55)$ \ncutoff along with the agreement between the projection and \n$f_s W_\\mathrm{fc}(r_p)$ justify our assumption of a constant physical \nfiber collision scale. The exact survey tiling of the BOSS sample is \nimposed on the Nseries mocks, so we expect Figure \\ref{fig:2pcf_tophat} \nto hold for the BOSS observations. The left panel illustrates \nthe $\\pi$-independence of the left hand side of Eq.~(\\ref{eq:tophat_2pcf}). \nThe right panel demonstrates that \n$1- (1+{\\xi^\\mathrm{NN}})/(1 + {\\xi^\\mathrm{true}})$ projected\nalong $\\pi$ agrees remarkably well with a top-hat function. \n\nIn principle, however,\n$W_\\mathrm{fc}$ is not necessarily a top-hat function. In fact,\nin eBOSS, due to the complex targeting scheme involving ``knock-outs'' from \nhigher priority targeting samples, $W_\\mathrm{fc}$ will not be top-hat function \n(Zhai et al. in prep). However, these complications are not present in our implementation of collisions; the reason for the deviations from a top-hat function here can be thought as arising from a sum of top-hats of slightly different radii along the line of sight (for fixed angular scale) weighted by the probability of collisions at each depth, leading to a smoother transition than a sharp top-hat function. In principle, our formalism  can be improved by including this numerical profile rather than a top-hat, as we shall mention below (see discussion after Eq.~\\ref{DeltaPell2}). \n\n\nWith the confirmation of Eq.~(\\ref{eq:tophat_2pcf}), we solve for $\\xi^\\mathrm{NN}$   \n:\n\\beqa\n\\xi^\\mathrm{NN}(r_p, \\pi) &=& \\xi^\\mathrm{true}(r_p, \\pi) - f_s W_\\mathrm{fc}(r_p)\\ (1 + \\xi^\\mathrm{true}(r_p, \\pi)),\n\\nonumber \\\\ & & \n\\eeqa\n\nand to get an expression for the power spectrum, we Fourier transform to get \n\\beqa \n\\label{eq:tophat_pk}\n\\Delta P({\\bf k}) &\\equiv& P^\\mathrm{NN}({\\bf k}) - P^\\mathrm{true}({\\bf k})  \\nonumber \\\\ & & \n= - f_s\\, {W_\\mathrm{fc}}({\\bf k})- f_s \\int {\\mathrm{d}^3q\\over (2\\pi)^3} P({\\bf q})\\, {W_\\mathrm{fc}}({\\bf k} - {\\bf q}). \\nonumber \\\\ & & \n\\eeqa\nWe see that the effect of fiber collisions on the true power spectrum \ncan be characterized by two terms: Fourier transform of the \ntop-hat function (corresponding to chance collisions) \nand the power spectrum convolved with the top-hat function (corresponding to \nphysically correlated pairs). We refer to these two terms as $\\Delta P^\\mathrm{uncorr}$ and \n$\\Delta P^\\mathrm{corr}$ respectively. Note that none of these terms is independent of $k$.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Del P comparison figure  \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{figure*}\n\\begin{center}\n\\includegraphics[width=1.\\textwidth]{figs/fc/mock_catalog_tophatconv_upw_delPlk_rebin6x.pdf}\n\\caption{Comparison of the power spectrum residuals from NN-corrected fiber collisions \n$\\Delta P_l = P_l^\\mathrm{NN} - P_l^\\mathrm{true}$ (dashed black) with \nthe $\\Delta P_l$ from the effective window method obtained by adding Eqs.~(\\ref{DeltaPellUC}) and~(\\ref{DeltaPell2}) (\\nseriescolor) for the monopole (left)\nand quadrupole (right). The standard deviation of the power spectrum residual, \n$\\sigma_{\\Delta P_l}$, for the Nseries mock catalogs is shaded in gray.}\n\\label{fig:delP}\n\\end{center}\n\\end{figure*}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\nThe first term, $\\Delta P^\\mathrm{uncorr}$, can be easily obtained:\n\\begin{align} \\label{eq:delp_uncorr}\n\\Delta P^\\mathrm{uncorr} &=  - f_s\\, \\widehat{W_\\mathrm{fc}}({\\bf k}) = \n-f_s \\int e^{i {\\bf k} \\cdot {\\bf r}} \\: W_\\mathrm{fc}({\\bf r}) \\, d^3{r} \\nonumber \\\\\n& = -f_s \\ 2 \\pi \\delta_D(k_\\parallel) \\; \\pi D_\\mathrm{fc}^2 \\; W_\\mathrm{2D}(k_\\perp D_\\mathrm{fc}). \n\\end{align}\nwhere $W_\\mathrm{2D}(x) \\equiv 2 J_1(x)/x$ is the top-hat function in 2D (a cylinder), and \n$J_1$ is a Bessel function of the first kind and of order $1$. The multipole \ncontributions of Eq.~(\\ref{eq:delp_uncorr}) are then \n\\beqa\n\\Delta P^\\mathrm{uncorr}_l(k) & = & -f_s \\  (2l+1) \\mathcal{L}_l(0) \\,  {(\\pi D_\\mathrm{fc})^2 \\over k} \\;  W_\\mathrm{2D}(k D_\\mathrm{fc}),\n\\nonumber \\\\ & & \n\\label{DeltaPellUC}\n\\eeqa\nwhere ${\\cal L}_l$ are the Legendre polynomials. The $k^{-1}$ prefactor here, arising from the delta function in Eq.~(\\ref{eq:delp_uncorr}) is an approximation for scales smaller than the survey size, since the delta function follows from assuming we can integrate up to infinity along the line of sight in Eq.~(\\ref{eq:delp_uncorr}).\nEquation~(\\ref{DeltaPellUC}) gives a correction that alternates in sign as a function of multipole $l$.\nNote that since for practical purposes $k D_\\mathrm{fc} \\ll 1$, we can expand \n\\beqa\n\\Delta P^\\mathrm{uncorr}_l(k)  &= & -f_s \\pi D_\\mathrm{fc}^2  \\,  \\Big({2\\pi \\over k}\\Big) \\ {(2l+1) \\over 2}\\, \\mathcal{L}_l(0) \\nonumber \\\\\n& & \\times \\Big(1 - \\frac{(k D_\\mathrm{fc})^2}{8} + \\ldots \\Big),\n\\label{DeltaPuncorrexp}\n\\eeqa\n% note  the leading order term is independent of type of window assumed!\nand for scales involved in typical analysis the first term suffices, which means that the uncorrelated piece of fiber collisions decays as $k^{-1}$ across the relevant range of scales. The magnitude of this uncorrelated  effect (chance collisions) is small, given by the effective survey area affected by fiber collisions $f_s \\pi D_\\mathrm{fc}^2$ times the wavelength of perturbations $2\\pi/k$.\n\nFor the correlated piece $\\Delta P^\\mathrm{corr}$, we see from Eqs.~(\\ref{eq:tophat_pk}) and~(\\ref{eq:delp_uncorr})  that we need $W_\\mathrm{2D}(|{\\bf k}_\\perp -{\\bf q}_\\perp| D_\\mathrm{fc})$ for which we can use the addition theorem for 2D top-hat functions~\\citep{Bernardeau:2002aa},\n\\beqa\nW_\\mathrm{2D}(|{\\bf k}_\\perp -{\\bf q}_\\perp| D_\\mathrm{fc}) &=& \\sum_{k=0} (k+1)\\, U_k(\\hat{k}_\\perp\\cdot \\hat{q}_\\perp) \\nonumber\n\\\\ & & W_\\mathrm{2D}^{(k/2)}(k_\\perp D_\\mathrm{fc}) \\,\nW_\\mathrm{2D}^{(k/2)}(q_\\perp D_\\mathrm{fc}) \\nonumber \\\\ & & \n\\label{ADDtheo}\n\\eeqa\nwhere the $U_k$'s are the Chebyshev polynomials and $W_\\mathrm{2D}^{(k/2)}(x) \\equiv 2J_{k+1}(x)/x$. Now, again, as we are interested in scales for which $k D_\\mathrm{fc} \\ll 1$ is an excellent approximation, dropping ${\\cal O}(k_\\perp D_\\mathrm{fc})^2$ we can just use the $k=0$ term in this expression. This gives us $W_\\mathrm{2D}(|{\\bf k}_\\perp -{\\bf q}_\\perp| D_\\mathrm{fc}) \\approx W_\\mathrm{2D}( q_\\perp D_\\mathrm{fc})$ as expected and leads to,\n\\beqa\n\\Delta P^\\mathrm{corr}({\\bf k}) &\\approx& -{f_s \\pi D_\\mathrm{fc}^2}\\int {d^2q_\\perp\\over (2\\pi)^2} \\, P(k_\\parallel,q_\\perp) \\, W_\\mathrm{2D}( q_\\perp D_\\mathrm{fc}) \\nonumber \\\\ & &  \\label{eq:delp_corr}\n\\eeqa\nThis is a simple result, showing that the correlated effect of fiber collisions is  proportional to the effective survey area affected by fiber collisions and to the  integral of the power spectrum over 2D modes perpendicular to the line of sight smoothed at the fiber collision scale. \nThe multipole components of Eq.~(\\ref{eq:delp_corr}) are, after expanding $P(k_\\parallel,q_\\perp)$ in multipoles,\n\\beq\n\\Delta P^\\mathrm{corr}_l(k) \\approx -\\frac{f_s D_\\mathrm{fc}^2}{2} \\sum_{l'=0}^\\infty \\int_0^\\infty q dq P_{l'}(q) \\, f_{l l'}(k,q), \n\\label{DeltaPell}\n\\eeq\nwhere, again neglecting ${\\cal O}(k D_\\mathrm{fc})^2$,\n\\beqa\nf_{ll'}(k,q) &\\equiv &\n\\Big(\\frac{2l+1}{2}\\Big) \\int_{\\mathrm{max}(-1,-q/k)}^{\\mathrm{min}(1,q/k)} d\\mu  \\, {\\cal L}_l(\\mu)\\, {\\cal L}_{l'}(k\\mu/q) \\nonumber \\\\ & &\n\\  \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\times \\ W_\\mathrm{2D}( q\\, D_\\mathrm{fc})\n\\label{fellellp}\n\\eeqa\nThis has a simple expression for $l=l'$,\n\\beq\nf_{ll}(k,q) = f_*(k,q)\\, W_\\mathrm{2D}( q\\, D_\\mathrm{fc})\\, \\Big(\\frac{k_<}{k_>}\\Big)^l\n\\label{fdiag}\n\\eeq\nwhere $f_*(k,q)=q/k$ for $q\\leq k$ and unity otherwise, and $k_>=\\mathrm{max}(k,q)$ and $k_<=\\mathrm{min}(k,q)$. On the other hand, off the diagonal we have ($l \\neq l'$)\n\\beq\nf_{ll'}(k,q) = f_*(k,q)\\, W_\\mathrm{2D}( q\\, D_\\mathrm{fc})\\, \\Big(\\frac{2l+1}{2}\\Big) \\,H_{l_>l_<}\\Big(\\frac{k_<}{k_>}\\Big),\n\\label{foffdiag}\n\\eeq\nwhere $l_{>}=\\mathrm{max}(l,l')$ and similarly $l_<$, and  $H_{l_>l_<}(x)$ is a polynomial of degree $l_>$ which vanishes unless $l$ and $k$ are both larger or  smaller than $l'$ and $q$ respectively. The first few polynomials are listed in the \nAppendix~\\ref{chap:append1}. Since $f_{l>l'}(k<q) = f_{l<l'}(k>q)=0$ it is convenient to split the integrals depending on whether $q$ is larger or smaller than $k$, which leads to\n\\beqa\n\\Delta P^\\mathrm{corr}_l(k) &\\approx & -\\frac{f_s D_\\mathrm{fc}^2}{2} \\Bigg[\\,\n\\sum_{l'\\leq l} \\int_0^k q dq \\, P_{l'}(q) \\, f_{l l'}(q\\leq k) \\nonumber \\\\ & & + \n\\sum_{l'\\geq l} \\int_k^\\infty q dq\\, P_{l'}(q) \\, f_{l l'}(q\\geq k) \\Bigg],\n\\label{DeltaPell2}\n\\eeqa\nwhich shows that the change of power spectrum multipole $l$ due to correlated \nfiber collisions comes from long modes of lower multipoles ($l'\\leq l$) and \nshort modes of higher multipoles ($l'\\geq l$). Going back to the results \ndisplayed in Figure~\\ref{fig:2pcf_tophat}, we can now formulate how our results \nchange if we use the observed numerical profile in the right panel of \nFigure~\\ref{fig:2pcf_tophat} (red line) instead of the top-hat (black dashed). \nOne can check that to leading order in $k D_\\mathrm{fc}$, which is all we are using in this paper, our expression for the uncorrelated and correlated change in power are valid as long as we replace the 2D top-hat by the numerical profile in Eq.~(\\ref{fellellp}), and redefine the scale $D_\\mathrm{fc}$ that appears in Eqs.~(\\ref{DeltaPuncorrexp}) and~(\\ref{DeltaPell}) from the area of the numerical profile, that is \n\\beq\n\\int d^2r_\\perp \\, W_\\mathrm{2D}({\\bf r}_\\perp) \\equiv \\pi\\, D_\\mathrm{fc}^2\n\\label{redefDfc}\n\\eeq\n\n%\n%\\begin{align} \\label{eq:delp_corr}\n%\\Delta P^\\mathrm{corr}  \n%&= -4 \\pi^3 f_s D_\\mathrm{fc}^2 \\int P(k_\\parallel \\hat{e}_\\parallel + q_\\perp \\hat{e}_\\perp) \\times \\nonumber \\\\\n%& \\qquad \\frac{J_1(D_\\mathrm{fc}(k_\\perp - q_\\perp))}{D_\\mathrm{fc}(k_\\perp - q_\\perp)}\n%\\;\\frac{\\mathrm{d}^3q}{(2\\pi)^3} \\nonumber \\\\\n%&= - \\frac{f_s D_\\mathrm{fc}^2}{2} \\int q_\\perp P(k_\\parallel \\hat{e}_\\parallel + q_\\perp \\hat{e}_\\perp) \\times \\nonumber \\\\\n%& \\qquad W_\\mathrm{1D} \\left(k_\\perp D_\\mathrm{fc}, \\; q_\\perp D_\\mathrm{fc} \\right) \\; \\mathrm{d}q_\\perp\n%\\end{align}\n%where \n%\\begin{align} \\label{eq:w1d}\n%W_\\mathrm{1D}(x, \\; y) = \n%\\int\\limits_{0}^{2\\pi} \\frac{J_1(\\sqrt{x^2 + y^2 - 2 x y\\;cos \\phi})}\n%{\\sqrt{x^2 + y^2 - 2 x y\\;cos \\phi}}\\; \\frac{\\mathrm{d}\\phi}{2\\pi}.\n%\\end{align}\n%The multipole components of Eq. \\ref{eq:delp_corr} are \n%\\begin{align}\n%\\Delta P^\\mathrm{corr}_l(k) &= -\\frac{f_s D_\\mathrm{fc}^2}{2} \\; \n%\\left(\\frac{2l+1}{2} \\right)  \\bigg[\n%\\int\\limits_{-1}^{1} \\mathrm{d}\\mu\\;\\mathcal{L}_l(\\mu) \n%\\int\\limits_{0}^{\\infty} q_\\perp\\mathrm{d}q_\\perp \\nonumber \\\\\n%& P(k\\mu\\;\\hat{e}_\\parallel + q_\\perp \\hat{e}_\\perp) \\;\n%W_\\mathrm{1D} \\left(k\\sqrt{1 - \\mu^2} D_\\mathrm{fc}, \n%\\; q_\\perp D_\\mathrm{fc} \\right) \\; \n%\\bigg]\n%\\end{align}\n%\n%\\noindent Since $q = \\sqrt{k^2\\mu^2+q_\\perp^2}$, the integral can be rearranged to  \n%\\begin{align} \\label{eq:pkmu_delpcorr}\n%\\Delta P^\\mathrm{corr}_l(k) \n%&= -\\frac{f_s D_\\mathrm{fc}^2}{2} \\; \\left(\\frac{2l+1}{2} \\right)\\bigg[\n%\\int\\limits_{0}^{\\infty} q\\; \\mathrm{d}q\n%\\int\\limits_{\\mathtt{max}(-1, \\frac{q}{k})}^{\\mathtt{min}(1, \\frac{q}{k})} \\mathrm{d}\\mu \\; \\mathcal{L}_l(\\mu) \\times \\nonumber \\\\ \n%& P(q, \\frac{k\\mu}{q})\\; W_\\mathrm{1D} \\left(k D_\\mathrm{fc} \\sqrt{1 - \\mu^2}, \n%\\; q D_\\mathrm{fc} \\sqrt{1 - \\frac{k^2\\mu^2}{q^2}} \\right)\\bigg]\n%\\end{align} \n%From $P(k, \\mu)$, we can calulate both $\\Delta P_l^\\mathrm{corr}$ and \n%$\\Delta P_l^\\mathrm{uncorr}$. In other words, we can model the effect of \n%fiber collisions on the power spectrum monopole and quadrupole from $P(k, \\mu)$. \n\n                                                                                                                                                                                                                                                                            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n                                                                                                                                                                                                                                                                            % Del P Untrusted comparison figure  \n                                                                                                                                                                                                                                                                            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{figure*}\n\\begin{center}\n\\includegraphics[width=1.\\textwidth]{figs/fc/mock_catalog_tophatconv_delPlk_untrusted_18_rebin6x.pdf}\n\\caption{Comparison of the correlated power spectrum residuals from unreliable modes obtained from mocks (dashed), Eq.~(\\ref{eq:delp_untrust_nseries}), \nto the polynomial approximation of  \nEq.~(\\ref{eq:delp_poly}) for $l' \\leq 18$ (orange). The left and right panels\ncorrespond to $l = 0$ and $2$ respectively. The gray shaded region is the \nstandard deviation for the Nseries $(P_l^\\mathrm{NN} - P_l^\\mathrm{true})$.  \nWe also include Eq.~(\\ref{eq:delp_poly}) evaluated only for $l' \\leq 2$ (blue). \nThe agreement between Eq.~(\\ref{eq:delp_poly}) for $l' \\leq 2$ and Eq.~(\\ref{eq:delp_untrust_nseries}) demonstrate that while higher orders of $l'$ are \nnecessary to properly model $\\Delta P_l^\\mathrm(k)$ at higher $k$ values, \nfor $k < k_\\mathrm{trust}$ ($0.3\\;h/\\mathrm{Mpc}$ above) $l' \\leq 2 $ are \nsufficient.}\n\\label{fig:delP_untrust}\n\\end{center}\n\\end{figure*}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\nWe now proceed to testing these results, for which we need the true power spectrum multipoles down to small scales to feed into Eq.~(\\ref{DeltaPell2}). Unfortunately, in the nonlinear regime the multipole expansion is not very efficient (in the sense that the amplitude of multipoles does not decrease sharply with increasing multipole), so a large number of multipoles $l'$ is required to capture the contribution from small scale modes.  Measuring multipoles higher than the hexadecapole for realistic survey geometries  using our estimator becomes expensive due to the number of \nFast Fourier Transforms (FFTs) that needs to be computed, and even for the most efficient version of the multipole estimators that requires only 7 FFTs one would worry about increased cosmic variance (see discussion in \\citealt{Scoccimarro:2015aa}). \n\nA more efficient approach is to use the Nseries simulation boxes to test Eqs.~(\\ref{eq:delp_uncorr}) and~(\\ref{DeltaPell2}). The Nseries simulation boxes are the \noriginal simulations where the Nseries mocks were \ncut out from (Section \\ref{sec:catalog}). Since the Nseries mocks \nare cut outs of the boxes, \ndiscrepancies in their power spectra are caused by the BOSS survey \ngeometry and occur mainly at the largest scales, $k < 0.05\\;h/\\mathrm{Mpc}$ \\citep{Beutler:2014aa,Grieb:2016aa}. \nAt smaller scales, the difference between the power spectrum monopole, \nquadrupole and hexadecapole of Nseries mocks versus the Nseries boxes are \nnegligible. \nTherefore, we calculate the $P_{l'}(q)$ from the Nseries simulation box, \nusing periodic boundary conditions, which only requires one FFT and go up to $q = 43.5\\;h/\\mathrm{Mpc}$ and $l'=18$ to compute the corrections predicted by  Eq.~(\\ref{DeltaPell2}).  \n\nIn Figure \\ref{fig:delP}, we compare $\\Delta P_l = \\Delta P_l^\\mathrm{corr} + \n\\Delta P_l^\\mathrm{uncorr}$ calculated from the Nseries Box power spectrum multipoles using Eqs.~(\\ref{eq:delp_uncorr}) and~(\\ref{DeltaPell2}) (\\nseriescolor) to the Nseries mock catalogs power spectrum residuals, $\\Delta P_l = P_l^\\mathrm{NN} - P_l^\\mathrm{true}$ (dashed). \nThe left panel compares the monopoles ($l = 0$) while the right panel compares \nthe quadrupoles ($l=2$). We also include in the gray shaded \nregion, the standard deviation of Nseries mock catalogs power spectrum residuals,\n$\\sigma_{\\Delta P_l}$. For both the monopole and quadrupole, the predictions (orange) agree with the measured residuals from NN-corrected fiber collisions (dashed black) well within the errors throughout the probed $k$ range up to $k=0.83\\;h/\\mathrm{Mpc}$. At low-$k$, the downturn (upturn) in the monopole (quadrupole) is due to the contribution of the $k^{-1}$ uncorrelated piece. \nThe overall quality of the  agreement demonstrates that the effective window method can be used to robustly \nestimate the effect of fiber collisions on $P_l(k)$. Furthermore, with its\nexcellent performance for the quadrupole, the effective window approach \nprovides an improvement over the LOS reconstruction method (Section\n\\ref{sec:dlospeak}). \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Tophat Convolution in Practice\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{In Practice} \\label{sec:tophat_practice}\nThere are, however, practical limitations to the effective window model \nas it described above. The \n$\\Delta P^\\mathrm{corr}_l$ calculations in \nEq.~(\\ref{DeltaPell2}) involves integrating the power spectrum over the $q$\nrange of $0$ to $\\infty$. While this integral converges for $q \\approx10\\;h/\\mathrm{Mpc}$ \nfor both monopole and quadrupole, in practice one cannot compute reliably the power spectrum multipoles down to these scales. We now \ndiscuss a way to overcome this issue.\n\nLet $k_\\mathrm{trust}$ represent the scale up to which we can calculate reliably power \nspectrum multipoles. We therefore split the second term in Eq.~(\\ref{DeltaPell2}) \ninto a reliable piece (integration from $k$ to $k_\\mathrm{trust}$) and an \nunreliable piece (integration from $k_\\mathrm{trust}$ to $\\infty$), so schematically\n\\beq \\label{eq:delp_split}\n\\Delta P^\\mathrm{corr}_l =  \\Delta P^\\mathrm{corr}_l \\bigg|_{q=0}^{q=k_\\mathrm{trust}} +  \n\\Delta P^\\mathrm{corr}_l \\bigg|_{q=k_\\mathrm{trust}}^{q=\\infty}.\n\\eeq\nThe first term can be reliably calculated from first principles \nsince it involves modes from $q=0$ to $q=k_\\mathrm{trust}$ and corresponds to  the first term  plus the reliable piece of the second term in Eq.~(\\ref{DeltaPell2}). Now, the key fact is that because the second term in Eq.~(\\ref{eq:delp_split}) only depends on $k$ through $f_{l l'}(q\\geq k)$, from Eqs.~(\\ref{fdiag}-\\ref{foffdiag}) it follows that the $k$-dependence of the unreliable term is simply a polynomial in $k$,\n\n\\begin{align} \\label{eq:delp_poly}\n\\Delta P^\\mathrm{corr}_l \\bigg|_{q=k_\\mathrm{trust}}^{q=\\infty} &= \n\\sum\\limits_{n= 0, 2, 4 ... } C_{l,n}\\;k^{n}. \n\\end{align}\nThe coefficients of the polynomial, $C_{l, n}$, are obtained by collecting powers of $k$ from the sum over the $H$-polynomial contributions to the second term in Eq.~(\\ref{DeltaPell2}). How important are these unreliable contributions? In order to test this, in Figure \\ref{fig:delP_untrust} \nwe calculate $C_{l, n}$ from the $P_{l'}(q)$ multipoles measured \nfrom the Nseries simulation boxes (blue and orange for terms up \n                                                                                                                                                                                                                                                                            to $l'=2$ and $18$ respectively) and compare to (black dashed)\n\\beq \\label{eq:delp_untrust_nseries}\n    \\Delta P_l^\\mathrm{Nseries}(k) - \\Delta P^\\mathrm{uncorr}_l(k) - \n    \\Delta P^\\mathrm{corr}_l(k) \\bigg|^{q=k_\\mathrm{trust}}_{q=0}\n\\eeq  \nwhere $\\Delta P_l^\\mathrm{Nseries}$ is the power spectrum \nresidual $P_l^\\mathrm{NN}- P_l^\\mathrm{true}$ for the Nseries mocks (Figure \\ref{fig:delP}). We once again include the standard deviation \nof the power spectrum residual in shaded gray. The agreement \nbetween Eq.~(\\ref{eq:delp_poly}) and Eq.~(\\ref{eq:delp_untrust_nseries}) \nis more or less equivalent to the agreement seen in Figure~\\ref{fig:delP}, which includes uncorrelated and reliable correlated contributions as well; this \nshould of course not come as a surprise.\n\nMore importantly, when we examine the contribution to \n$\\Delta P^\\mathrm{corr}_l |_{k_\\mathrm{trust}}^\\infty$ from each individual \n$l'$ order term of the Eq.~(\\ref{eq:delp_poly}) polynomial, we find that the\nmain contributors at $k < k_\\mathrm{trust} \\sim 0.3\\; h/\\mathrm{Mpc}$ are \nthe $l' \\leq 2$ order terms. In fact, the higher order ($l' > 2$) terms of the \npolynomial contribute at higher $k$. For instance, the $l' = 4, 6,$ and $ 8$ terms \nonly begin to significantly contribute at scales of $k > 0.3, \\; 0.45$, and \n$0.6\\;h/\\mathrm{Mpc}$ respectively, which is not surprising since higher $k$ powers come together with increasing inverse powers of $q$ and thus suppress the value of the coefficients that result from integrating over small-scale modes. Hence, when we plot Eq.~(\\ref{eq:delp_poly})  \nfor just $l' \\leq 2$ (blue) in Figure~\\ref{fig:delP_untrust}, we find that \nit is in good agreement with both Eq.~(\\ref{eq:delp_poly}) for $l' \\leq 18$ \nand Eq.~(\\ref{eq:delp_untrust_nseries}). We also note that for $l = 2$, \n$C_{2, l'=0} = 0$ so the main contribution to \n$\\Delta P^\\mathrm{corr}_2(k < k_\\mathrm{trust}) |_{k_\\mathrm{trust}}^\\infty$ \ncomes solely from the $l' = 2$ term of the polynomial. \n\nTo use the effective window method for cosmological inference, we can \nutilize the fact that Eq.~(\\ref{eq:delp_poly}) with only $l' \\leq 2$ terms \nprovides an accurate estimate of the unreliable correlated change in power (Figure~\\ref{fig:delP_untrust}). In cosmological analyses, the coefficients $C_{l, 0}$ and $C_{l, 2}$\ncan be nuisance parameters with priors obtained from  \nmock catalogs. More specifically, for the quadrupole, since $C_{2, 0} = 0$\nonly one nuisance parameter is necessary. Meanwhile \nfor the monopole, a constant shot noise term is typically already included as\na nuisance parameter in the analysis (\\citealt{Beutler:2014aa,Beutler:2016aa,Grieb:2016aa,Gil-Marin:2016aa}) so there is \nalso only one extra nuisance parameter for $l=0$. Therefore, \nby adding $C_{l, 2}$ as nuisance parameters to cosmological inference \nanalyses of the power spectrum multipoles, we can use the effective window \nmethod to robustly marginalize over the effects of fiber collision for the \nentire $k$ range of power spectrum models based on perturbation theory. \n\n%\\todo{ May be Fig.10 shows that the extra $k^2$ terms are not needed? They look like small contributions, most $k^2$ dependence seems to be from the reliable correlated piece. Can we just calculate $k_{\\chi^2}$ for the CM (convolution method) without the $k^2$ terms but correct $k^0$ shot noise? It'd be nice to see what $k_{\\chi^2}$ is for the CM and put this method in the same footing as NN and LRec.}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Summary and Discussion  \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Summary and Conclusions} \\label{sec:summary}\nUsing simulated mock catalogs designed specifically for interpreting BOSS \nclustering measurements with realistically imposed fiber collisions, we \ndemonstrate that the Nearest Neighbor method (NN), most common used for dealing \nwith fiber collisions, is insufficient in accounting for the effect of \nfiber collisions on the galaxy power spectrum monopole and quadrupole.  \nAlthough fiber collisions have little significant effect on \nthe power spectrum at large scales, their effect quickly overtakes sample \nvariance on scales smaller than $k \\approx 0.1 \\;h/\\mathrm{Mpc}$. At  $k \\sim 0.3 \\;h/\\mathrm{Mpc}$\nfiber collisions have over a $7.3\\%$ and $73\\%$ \nimpact on the power spectrum monopole and quadrupole, respectively. The \neffect is equivalent to $7.3$ and $2.5$ times the sample variance of CMASS for \n$\\delta k \\approx 0.01\\;h/\\mathrm{Mpc}$, leading to a binning-independent scale of validity of the NN method of \n$k_{\\chi^2}=0.068\\;h/\\mathrm{Mpc}$ for the monopole and $k_{\\chi^2}=0.17\\;h/\\mathrm{Mpc}$ for the \nquadrupole (see bottom panel of Figure~\\ref{fig:dlospeak_norm_resid}).  \nConsequently at these scales, measurements of the power spectrum becomes \ndominated by the systematic effects of fiber collisions. \n\nSome recent methods (\\citealt{Beutler:2014aa,Gil-Marin:2014aa,Beutler:2016aa,Grieb:2016aa,Gil-Marin:2016aa}) have supplemented\nthe NN method with adjustments to the constant shot noise term in the power spectrum \nestimator. While these methods improve the overall residual for the monopole, e.g. $k_{\\chi^2}=0.17\\;h/\\mathrm{Mpc}$ for the method by \\cite{Gil-Marin:2014aa}, they fail to account for the $k$-dependence of the systematic effect on smaller \nscales. Furthermore, since the quadrupole does not have a shot \nnoise term, these methods provide no improvements for $l \\geq 2$. \n\nIn this paper, we first model the distribution of the line-of-sight displacement between \nfiber collided pairs using  mock catalogs. From the model, we statistically reconstruct the \nclustering of fiber collided galaxies that reside in the same halo. This, combined with the actual shot noise subtraction   \nof the power spectrum estimator that accounts for chance alignments, \nleads to our LOS Reconstruction method that recovers very well the true power \nspectrum monopole from fiber collided data. As an added advantage, the method \nonly relies on parameters ($\\sigma_\\mathrm{LOS}$ and $f_\\mathrm{peak}$) \nmeasured from the actual observations. This makes the performance of the method \nindependent from the accuracy of the mock catalogs, which are known to be unreliable \nat small scales. \n\nUsing the LOS Reconstruction method, we can recover the true power \nspectrum monopole to scales well beyond previous methods. The LOS Reconstruction monopole power spectrum residuals remain within sample \nvariance until $k \\sim 0.53\\;h/\\mathrm{Mpc}$ and $k_{\\chi^2}$ extends to  \n$0.29\\;h/\\mathrm{Mpc}$. However, for the power spectrum quadrupole\nat $k = 0.2\\;h/\\mathrm{Mpc}$,\nthe LOS Reconstruction method only reduces the discrepancy between the \nfiber collided $P_2(k)$ and the true $P_2(k)$ to roughly the sample variance. \nTherefore, the true monopole power spectrum estimate from \nthe LOS reconstruction method can be compared to the systematics free predicted  \npower spectrum monopole to infer the cosmological parameters of interest without \nbiases from fiber collisions, but for the quadrupole power spectrum the method is not a substantial improvement over previous methods. We trace this problem  to the fact that the quadrupole is more sensitive to the object by object finger of god effect, while the LOS reconstruction works only statistically starting from the distribution of close pairs. \n\nTo improve on the LOS reconstruction results we develop the effective window method which, rather than attempting to correct the data before making measurements, computes theoretical predictions of the fiber-collided power spectrum multipoles.\nIn this approach, we approximate the effect that \nfiber collisions have on the two-dimensional configuration space two-point \ncorrelation function of the NN method as a scaled top-hat function. \nThen the effect of fiber collisions can be written as the sum of two contributions: 1) that of uncorrelated chance collisions, with an amplitude proportional to the \nthe effective survey area affected by fiber collisions times the wavelength of perturbations, and 2) that of correlated collisions, which is also proportional to the effective survey area affected by fiber collisions and to the integral of the power spectrum over 2D modes perpendicular to the line of sight smoothed at the fiber collision scale.\n\nUsing high resolution mock catalogs, we demonstrate that our  analytic prescription \naccurately models the power spectrum residuals from the NN method to within sample variance of BOSS volumes  \nat $k < 0.83\\;h/\\mathrm{Mpc}$ for both the monopole and quadrupole when the true power spectrum is known down to small scales from simulations, allowing to compute the fiber-collided predictions. Since typically we do not have fast reliable ways of computing the small scale power spectrum, we develop a practical approach when the power spectrum predictions are reliable up to some scale $k_\\mathrm{trust}$. We split the contributions of the correlated fiber collisions effect into a  piece that can be calculated reliably as it depends on large-scale modes, and an unreliable piece that depends on modes that are not under control. We show that the latter piece can be written as polynomials in $k$, and demonstrate that for scales up to $k \\sim 0.3\\;h/\\mathrm{Mpc}$, the unreliable contribution can be accurately estimated by a quadratic  polynomial in $k$. In principle, this method can be applied to larger $k_\\mathrm{trust}$ than used here as a reasonable example ($k_\\mathrm{trust} = 0.3\\;h/\\mathrm{Mpc}$). \n\nTherefore, using the effective window method we can model the fiber collided power \nspectrum as the systematics-free  power spectrum plus three contributions due to  \nfiber collisions: an uncorrelated piece (independent of the model power spectrum), a calculable piece (which involves integrating the model power spectrum over 2D long-wavelength modes perpendicular to the line of sight), and an unreliable contribution that is a quadratic polynomial, $C_{l,0} + C_{l,2}\\, k^2$. \nWhile the precise values of $C_{l, n}$ cannot be robustly predicted in practice \nbecause of its dependence on small scale power, the coefficients \ncan be treated as nuisance parameters in the analysis. Typically a constant shot \nnoise term is already included as a nuisance parameter, while the constant contribution vanishes for higher multipoles, therefore only one extra parameter \nper multipole is required (the $k^2$ corrections). For cosmological parameter inference, the fiber collided model power spectrum \ncan be compared directly to the observed fiber \ncollided power spectrum. Then by marginalizing over these free coefficients, we marginalize \nover the effect of small-scale power induced fiber collisions on the power spectrum, which allows us to robustly \ninfer the cosmological parameters of interest.\n\nThe fiber collision correction methods we present will enable us to robustly \naccount for the effects of fiber collisions in galaxy clustering analyses \nto the smallest scales allowed by theoretical predictions. They can also be extended to \nfuture surveys such as eBOSS  or any other large fiber-fed \nsurveys that suffer from systematic effects of fiber collisions. Our fiber\ncollision correction method can also be extended to higher order clustering \nstatistics such as bispectrum (Hahn et al., in prep.). We will use the methods \npresented in this paper to analyze the galaxy power spectrum and bispectrum \nmultipoles in future work.\n\n\\section*{Acknowledgements}\nCHH and MRB were supported by NSF-AST-1109432 and NSF-AST-1211644.\nSRT is grateful for support from the Campus de Excelencia Internacional UAM/CSIC.\nWe thank A. I. Malz, Mohammadjavad Vakili, Johan Comparat and particularly \nDavid W. Hogg for helpful discussions. CHH also thanks the Instituto \nde F\\'{i}sica Teo\\'{o}rica (UAM/CSIC) and \nparticularly Francisco Prada for their hospitality during his summer \nvisit, where part of this work was completed.\n", "meta": {"hexsha": "ed030bed5e95f452a2d6690470eba8b13fe1709b", "size": 113808, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/observations.tex", "max_stars_repo_name": "changhoonhahn/DisThesis", "max_stars_repo_head_hexsha": "2eaa61691d22d8a5ff36e801da6fd882528f3981", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/observations.tex", "max_issues_repo_name": "changhoonhahn/DisThesis", "max_issues_repo_head_hexsha": "2eaa61691d22d8a5ff36e801da6fd882528f3981", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/observations.tex", "max_forks_repo_name": "changhoonhahn/DisThesis", "max_forks_repo_head_hexsha": "2eaa61691d22d8a5ff36e801da6fd882528f3981", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 71.6675062972, "max_line_length": 1122, "alphanum_fraction": 0.727602629, "num_tokens": 30894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.3190555150980551}}
{"text": "\\vssub\n\\subsection{~Air-sea processes}\n\\vsssub\n\\subsubsection{~General concepts}\n\\vsssub\n\nAdditional subroutines are provided within \\ws\\ for use as part of coupled ocean-wave or ocean-atmosphere systems.\nThese subroutines are designed to compute additional quantities related to the surface wave field which are intended to be passed to external models (e.g. ocean models).\nThe motivation for these subroutines is to allow the external model to include the impact of waves on quantities such as the wind stress and the upper ocean turbulence.\n\n\\paragraph{Sea-state dependent air-sea fluxes}\n\nThe air-sea momentum flux, or the total wind stress, is the sum of the momentum flux into both surface waves and subsurface currents.\nCoupled atmosphere-ocean models that do not consider the impact of the surface gravity wave field typically compute the total wind stress based on an empirical relationship between the wind speed and the wind stress (via a drag coefficient, $C_d$).\nThe provided {\\it FLD} subroutines allows the computation of the total wind stress based on the \\ws\\ wavenumber-direction spectrum for use in coupled numerical models.\n\nTo the leading order, the total wind stress is equal to the sum of the momentum flux into surface waves (form drag of surface waves) and the momentum flux directly into the subsurface currents (through viscous stress).\nThe momentum flux into the waves may be expressed as an integral of the wave variance spectrum multiplied by the wave growth rate (momentum-uptake rate).\nA few assumptions are needed to calculate the wave form drag.\nFirst, the wave form drag is sensitive at the leading order to the level of the high frequency waves (or the spectral tail).\nThis part of the wave spectrum contains a great deal of uncertainty within the wave model, and therefore may need to be separately parameterized for computing the wind stress.\nAn assumption must therefore be made to parameterize the high frequency, which is not constrained by observational data and wind speeds above 15 m/s.\nSecond, assumptions of the wave growth-rate function are needed since it has historically been parameterized from either the wind speed or the wind stress.\nIn either case, empirical coefficients are needed within the growth-rate function based on wavelength and wave direction relative to the wind and/or stress.\nThird, there is feedback due to the wave form drag on the turbulence profile and the wind profile within the wave boundary layer (roughly the upper 10 meters above the air-sea interface).\nHow important this feedback is on determining the wind stress and the mean wind profile is not entirely understood.\nFinally, the growth rate is known to be different over breaking and non-breaking waves.\nHowever, there are no simple methods for explicitly including the breaking wave impact within wind-stress calculation models.\nTherefore, no separation is made in either of the present {\\it FLD} subroutines between breaking and non-breaking wave growth-rates.\n\nThe total air-sea momentum flux can be expressed (to the leading order) as:\n\\begin{equation}\n\\vec{\\tau}=\\vec{\\tau}_{\\nu}+\\vec{\\tau}_{f},\n\\end{equation}\nwhere $\\vec{\\tau}_{\\nu}$ is the viscous stress vector and $\\vec{\\tau}_{f}$ is the wave form drag.\nAt the air-sea interface, the wave form drag can be computed as the contribution of the momentum flux into all waves:\n\\begin{equation}\\label{formdrag}\n\\vec{\\tau}_{f}=\\rho_w\\int_{k_{min}}^{k_{max}}\\int_{-\\pi}^{\\pi} \\beta_g(k,\\theta) \\sigma F (k,\\theta) d\\theta \\vec{k} dk,\n\\end{equation}\nwhere $\\rho_w$ is the water density, $k$ is the wavenumber, $\\theta$ is the wave direction, $\\sigma$ is the angular frequency, $\\beta_g (k,\\theta)$ is the growth rate,\n$F (k,\\theta)$ is the wave variance spectrum, and $k_{min}$ and $k_{max}$ are the minimum and maximum wavenumbers of contributing waves.\nThe expression for the growth rate varies based on the theory applied in the model, and will be described separately for each theory in their following descriptions.\n\nThe spectral tail at wind speeds above 15 m/s is not well constrained observationally or theoretically.\nTherefore, the spectral tail level in the {\\it FLD} subroutines has been empirically parameterized such that the mean drag coefficient corresponds to the standard bulk drag coefficient used within the modeling system.\nIn this way, the mean value of the wind stress will not be modified by using any explicit sea state dependent wind stress formulation, but the stress will deviate from the mean based on the sea-state.\nIt is assumed that the tail level is a function of a wind speed only and is independent of sea states.", "meta": {"hexsha": "cc6d0f8e057ceca5a16d455a4970d55f097d41eb", "size": 4630, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "WW3/manual/eqs/airseaprocesses.tex", "max_stars_repo_name": "minsukji/ci-debug", "max_stars_repo_head_hexsha": "3e8bbbe6652b702b61d2896612f6aa8e4aa6c803", "max_stars_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WW3/manual/eqs/airseaprocesses.tex", "max_issues_repo_name": "minsukji/ci-debug", "max_issues_repo_head_hexsha": "3e8bbbe6652b702b61d2896612f6aa8e4aa6c803", "max_issues_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-05-31T15:49:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-04T14:17:45.000Z", "max_forks_repo_path": "WW3/manual/eqs/airseaprocesses.tex", "max_forks_repo_name": "minsukji/ci-debug", "max_forks_repo_head_hexsha": "3e8bbbe6652b702b61d2896612f6aa8e4aa6c803", "max_forks_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-01T09:29:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T09:29:46.000Z", "avg_line_length": 98.5106382979, "max_line_length": 248, "alphanum_fraction": 0.7933045356, "num_tokens": 1014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.3189243179182409}}
{"text": "\\documentclass[12pt]{IEEEtran}%\n\\usepackage{amsmath}\n\\usepackage{cite}\n\\usepackage{graphicx}\n\\usepackage{graphics}\n%\\usepackage{geometry}\n\\usepackage{setspace}\n\\usepackage{amsfonts}\n\\usepackage{amssymb}\n\\usepackage{hyperref}\n\\usepackage{comment}\n\\usepackage{algorithm}\n\\usepackage{algpseudocode}%\n\\setcounter{MaxMatrixCols}{30}\n%TCIDATA{OutputFilter=latex2.dll}\n%TCIDATA{Version=5.50.0.2953}\n%TCIDATA{CSTFile=IEEEtran.cst}\n%TCIDATA{Created=Monday, February 05, 2001 16:11:19}\n%TCIDATA{LastRevised=Saturday, September 29, 2018 22:28:54}\n%TCIDATA{<META NAME=\"GraphicsSave\" CONTENT=\"32\">}\n%TCIDATA{<META NAME=\"SaveForMode\" CONTENT=\"1\">}\n%TCIDATA{BibliographyScheme=BibTeX}\n%TCIDATA{Language=American English}\n%BeginMSIPreambleData\n\\providecommand{\\U}[1]{\\protect\\rule{.1in}{.1in}}\n%EndMSIPreambleData\n\\hypersetup{\n    colorlinks=true,\n    linkcolor=black,\n    filecolor=magenta,      \n    urlcolor=black,\n    citecolor=black\n}\n%\\geometry{left=1in,right=1in,top=1in,bottom=1in}\n\\begin{document}\n%\n%TCIMACRO{\\QSubDoc{Include IEEEHeading}{\\input{IEEEHeading.tex}}}%\n%BeginExpansion\n\\input{IEEEHeading.tex}\n%EndExpansion\n\n\n\\section{Introduction}\n\n\\label{sec:rul_intro}\n\nTraditionally, maintenance of mechanical systems has been carried out based on\nscheduling strategies. Such strategies are often costly and less capable of\nmeeting the increasing demand of efficiency and reliability\n\\cite{Gebraeel2005, Zaidan2013}. Condition based maintenance (CBM) also known\nas intelligent prognostics and health management (PHM) allows for maintenance\nbased on the current health of the system, thus cutting down the costs and increasing\nthe reliability of the system \\cite{Zhao2017}. Here, we refer to prognostics\nas the estimation of remaining useful life of a system. The remaining useful life (RUL) of\nthe system can be estimated based on the historical data. This data-driven\napproach can help optimize maintenance schedules to avoid engineering failures\nand to save the costs \\cite{Lee2014}.\n\nThe existing PHM methods can be grouped into three different categories:\nmodel-based \\cite{Yu2001}, data-driven \\cite{Liu2009, Mosallam2013} and\nhybrid approaches \\cite{Pecht2010, Liu2012}. Model-based approaches attempt to\nincorporate physical models of the system into the estimation of the RUL. If\nthe system degradation is modeled precisely, model-based approaches usually\nexhibit better performance than data-driven approaches \\cite{Qian2017}. This\ncomes at the expense of having extensive a priori knowledge of the underlying\nsystem and having a fine-grained model of the system, which can involve\nexpensive computations. On the other hand, data-driven approaches use pattern\nrecognition to detect changes in system states. Data-driven approaches are\nappropriate when the understanding of the first principles of the system\ndynamics is not comprehensive or when the system is sufficiently complex such as\njet engines, car engines and complex machineries, for which it is prohibitively difficult \nto develop an accurate model.\n\nCommon disadvantages for the data-driven approaches are that they usually\nexhibit wider confidence intervals than model-based approaches and that a fair\namount of data is required for training. Many data-driven algorithms have been\nproposed. Good prognostics results have been achieved. Among the most popular\nalgorithms we can find artificial neural networks (ANNs) \\cite{Gebraeel2004},\nsupport vector machine (SVM) \\cite{Benkedjouh2013}, Markov hidden chains (MHC)\n\\cite{Dong2007} and so on. Over the past few years, data-driven approaches\nhave gained more attention in the PHM community. A number of machine learning\ntechniques, especially neural networks, have been applied successfully to\nestimate the RUL of diverse mechanical systems. ANNs have demonstrated good\nperformance in modeling highly nonlinear, complex, multi-dimensional systems\nwithout any prior knowledge on the system behavior \\cite{Li2018}. While the\nconfidence limits for the RUL predictions cannot be analytically provided\n\\cite{Sikorska2011}, the neural network approaches are promising for\nprognostic problems.\n\nNeural networks for estimating the RUL of jet engines have been previously\nexplored in \\cite{Lim2016} where the authors propose a multi-layer perceptron\n(MLP) coupled with a feature extraction (FE) method and a time window for the\ngeneration of the features for the MLP. In the publication, the authors\ndemonstrate that a moving window combined with a suitable feature extractor\ncan improve the RUL prediction as compared with the studies with other similar\nmethods in the literature. In \\cite{Li2018}, the authors explore a deep\nlearning ANN architecture, the so-called convolutional neural networks (CNNs),\nwhere they demonstrate that by using a CNN without any pooling layers coupled\nwith a time window, the predicted RUL is further improved.\n\nIn this paper we propose a novel framework for estimating the RUL of complex\nmechanical systems. The framework consists of a MLP to estimate the RUL of the\nsystem, coupled with an evolutionary algorithm for the fine tuning of\ndata-related parameters, i.e. parameters that define the shape and quality of\nthe features used by the MLP. The publicly available NASA CMAPS dataset\n\\cite{CMAPS2008} is used to assess the efficiency and reliability of the\nproposed framework. This approach allows for a simple and small MLP to obtain\nbetter results than those reported in the current literature while using less\ncomputing power.\n\nThe remainder of this paper is organized as follows. The CMAPS dataset is\npresented in Section \\ref{sec:rul_dataset}. The framework and its components\nare thoroughly reviewed in Section \\ref{sec:method}. The method is evaluated\nusing the CMAPS dataset in Section \\ref{sec:rul_eval}. A comparison with the\nstate-of-the-art is also provided. Finally, the conclusions are presented in\nSection \\ref{sec:conclusions}.\n\n\\section{NASA C-MAPSS Dataset}\n\n\\label{sec:rul_dataset}\n\nThe NASA CMAPS dataset is used to evaluate performance of the proposed method\n\\cite{CMAPS2008}. The CMAPS dataset contains simulated data produced using a\nmodel based simulation program developed by NASA. The dataset is further\ndivided into 4 subsets composed of multi-variate temporal data obtained from\n21 sensors.\n\nFor each of the 4 subsets, a training and a test set are provided. The training\nsets include run-to-failure sensor records of multiple aero-engines collected\nunder different operational conditions and fault modes as described in Table\n\\ref{TabCMAPSS}.\n\nThe data is arranged in an $n\\times26$ matrix where $n$ is the number of data\npoints in each subset. The first two variables represent the engine and cycle\nnumbers, respectively. The following three variables are operational settings\nwhich correspond to the conditions in Table \\ref{TabCMAPSS} and have a\nsubstantial effect on the engine performance. The remaining variables\nrepresent the 21 sensor readings that contain the information about the engine\ndegradation over time.\n\nEach trajectory within the training and test sets represents the life cycles\nof the engine. Each engine is simulated with different initial health\nconditions, i.e. no initial faults. For each trajectory of an engine the last\ndata entry corresponds to the cycle at which the engine is found faulty. On\nthe other hand, the trajectories of the test sets terminate at some point\nprior to failure, hence the need to predict the remaining useful life. The aim\nof the MLP NN model is to predict the RUL of each engine in the test set. The\nactual RUL values of test trajectories are also included in the dataset for\nverification. Further discussions of the dataset and details on how the data\nis generated can be found in \\cite{Saxena2008}.\n\n\\subsection{Performance Metrics}\n\n\\label{sec:rul_metrics}\n\nTo evaluate the performance of the proposed approach on the CMAPS dataset, we\nmake use of two scoring indicators, namely the Root Mean Squared Error (RMSE)\ndenoted as $e_{rms}(d)$ and a score proposed in \\cite{Saxena2008} which we\nrefer as the RUL Health Score (RHS) denoted as $s_{rh}(d)$. The two scores are\ndefined as follows,\n\\begin{equation}\ne_{rms} = \\sqrt{ \\frac{1}{N} \\sum_{i=1}^{N}{d_{i}^{2}}} \\label{eq:rmse}%\n\\end{equation}\n%\n\n\\begin{align}\ns_{rh}  &  = \\frac{1}{N} \\sum_{i=1}^{N}{s_{i}}\\nonumber\\\\\ns_{i}  &  =\n\\begin{cases}\ne^{-\\frac{d_{i}}{13}} - 1, & d_{i} < 0\\\\\ne^{\\frac{d_{i}}{10}} - 1, & d_{i} \\geq0,\n\\end{cases}\n\\label{eq:rhs}%\n\\end{align}\nwhere $N$ is the total number of samples in the test set and $d = \\hat{y} - y$\nis the error between the estimated RUL values $\\hat{y}$, and the actual RUL\nvalues $y$ for each engine within the test set. It is important to note that\n$s_{rh}(d)$ penalizes late predictions more than early predictions since\nusually late predictions lead to more severe consequences in fields such as aerospace.\n\n\\section{Framework Description}\n\n\\label{sec:method}\n\nIn this section, the proposed ANN-EA based method for prognostics is\npresented. The model consists of a multi-layer perceptron (MLP) as the main\nregressor for estimating the RUL of the engines in the CMAPS dataset. For the\ntraining sets, the feature vectors are generated by using a moving time window\nwhile a label vector is generated with the RUL of the engine. The label has a\nconstant RUL for the early cycles of the simulation, and becomes a linearly\ndecreasing function of the cycle in the remaining cycles. This is the\nso-called piecewise linear degradation model \\cite{Ramasso2014}. For the test\nset, a time window is taken from the last sensor readings of the engine. The\ndata of the test set is used to predict the RUL of the engine.\n\nThe window-size $n_{w}$, window-stride $n_{s}$, and early-RUL $R_{e}$ are\ndata-related parameters, which for the sake of clarity and formalism in this\nstudy, form a vector $v \\in\\mathbb{Z}^{3}$ such that $v = (n_{w}, n_{s},\nR_{e})$. The vector $v$ has a considerable impact on the quality of the\npredictions by the regressor. It is computationally intensive to find the best\nparameters of $v$ given the search space inherent to these parameters. In this\npaper, we propose an evolutionary algorithm to optimize the data-related\nparameters $v$. The optimized parameter set $v$ allows the use of a simple\nneural network architecture while attaining better results in terms of the\nquality of the predictions compared with the results by other methods in the literature.\n\n\\subsection{The Network Architecture}\n\nAfter careful examinations of the CMAPS dataset, we propose to use a rather\nsimple MLP architecture for all the four subsets of the data. The\nimplementations are done in Python using the Keras/Tensorflow environment. The\nsource code is publicly available at the git repository \\url{https://github.com/dlaredo/NASA_RUL_-CMAPS-}.\n\nThe choice of the network architecture is made by following an iterative\nprocess: comparing 6 different architectures, training each for $100$\niterations using a mini-batch size of $512$ and averaging their results over\n$10$ different runs. Also, L1 (Lasso) and L2 regularization (Ridge) \n\\cite{Buhlmann2011} are used to prevent overfitting. L1 regularization \npenalizes the sum of the absolute value of the weights and biases of the networks, \nwhile L2 regularization penalizes the sum of the squared value of the weights and biases. \nTwo objectives are pursued during the iterations: 1) the architecture must be minimal in \nterms of layers and neurons in each layer; and 2) the performance indicators must be minimized.\n\nThe process for choosing the network architecture is as follows. First, choose\na $v$ for the experiment, say $v= (30, 1, 140)$. Next, six different ANN\narchitectures are defined. These architectures are provided in\nthe appendix. For each of the six different architectures,\nits performance is assessed using a cross-validation set from subset 1 of\nCMAPS. Table \\ref{table:tested_architectures_100} summarizes the results for\neach tested architecture, while Table \\ref{table:proposed_nn} presents the\narchitecture chosen for the remainder of this work. The chosen architecture\nprovides the best compromise between compactness and performance among the\ntested architectures.\n\n\\subsection{Shaping the Data}\n\nThis section covers the data preprocessing applied to the raw sensor readings\nin each of the datasets. Although the original datasets contain $21$ different\nsensor readings, some of the sensors do not present much variance or convey\nredundant information. These sensors are therefore discarded. In the end, only\n$14$ sensor readings out of the $21$ are considered for this study. Their\nindices are $\\left\\lbrace 2, 3, 4, 7, 8, 9, 11, 12, 13, 14, 15, 17, 20, 21\n\\right\\rbrace $. The raw measurements are then used to create the strided time\nwindows with window size $n_{w}$ and window stride $n_{s}$. For the training\nlabels, $R_{e}$ is used at the early stages and then the RUL is linearly\ndecreased. The data is normalized to be within the range $\\left[  -1,1\n\\right]  $ using the min-max normalization.\n\\begin{equation}\n\\hat{x}_{i} = 2* \\frac{x_{i} - min(x_{i})}{max(x_{i}) - min(x_{i})} - 1,\n\\label{eq:min_max_norm}%\n\\end{equation}\nwhere $x_{i}$ denotes the $m$-dimensional vector whose components are all the\nreadings for the \\textit{i-th} sensor and $\\hat{x}_{i}$ is the normalized\n$x_{i}$ vector.\n\n\\subsubsection{Time Window and Stride}\n\nIn multivariate time-series problems such as RUL, more information can be\ngenerally obtained from the temporal sequence of the data as compared with the\nmultivariate data point at a single time stamp. For a time window of size\n$n_{w}$ with a stride $n_{s}=1$, all the sensor readings in the time window\nform a feature vector $\\mathbf{x}$. This approach has successfully been tested\nin \\cite{Li2018,Lim2016} where the authors propose the use of a moving window\nwith sizes ranging from 20 to 30. In this paper, we propose not only the use of\na moving time window, but also a \\textit{strided} time window that updates\nmore than one elements ($n_{s}>1$) at the time. A graphical depiction of the\nstrided time window is shown in Figure \\ref{FigWindow}.\n\nThe use of a strided time window allows for the regressor to take advantage\nnot only of the previous information, but also to control the ratio at which\nthe algorithm is fed with new information. With the usual time window\napproach, only one point is updated for every new time window. The strided\ntime window considered in this study allows for updating more than one point\nat the time for the algorithm to make use of the new information with less iterations. It\nis believed that the information contained in the time window with stride size\n$n_{s}>1$ is likely richer than the one contained in a time window with stride\nsize $n_{s}=1$.\n\n\\subsubsection{Piecewise Linear Degradation Model}\n\nDifferent from common regression problems, the desired output value of the\ninput data is difficult to determine for a RUL problem. It is usually\nimpossible to evaluate the precise health condition and estimate the RUL of\nthe system at each time step without an accurate physics based model. For this\npopular dataset, a piece-wise linear degradation model has been proposed in\n\\cite{Ramasso2014}. The model assumes that the engines have a constant RUL\nlabel in the early cycles, and then the RUL starts degrading linearly until it\nreaches 0 as shown in Figure \\ref{FigRULinear}. The piecewise linear\ndegradation assumption is used in this work. We denote the value of the RUL in\nthe early cycles as $R_{e}$. Initially,  $R_{e}$ is randomly chosen between 95 and 140 \ncycles. When the difference between the cycle count in the time window and the terminating cycle \nof the training data is less than the initial value of $R_{e}$, $R_{e}$ begins the linear \ndescent toward the terminating cycle.\n\n\\subsection{Optimal Data Parameters}\n\n\\label{sec:otimal_data_params}\n\nAs mentioned in the previous sections the choice of the data-related\nparameters $v$ has a large impact on the performance of the regressor. In this\nsection, we present the framework for picking the optimal combination of the\ndata-related parameters $n_{w}$, $n_{s}$ and $R_{e}$ while being\ncomputationally efficient.\n\nRecall that $v = (n_{w}, n_{s}, R_{e})$ specific to the CMAPS dataset are\nbounded such that $n_{w} \\in\\left[  1, b\\right]  $, $n_{s} \\in\\left[  1,\n10\\right]  $, and $R_{e} \\in\\left[  90, 140 \\right]  $, where all the\nvariables are integer. The value of $b$ is different for different subsets of\nthe data, Table \\ref{table:b_values} shows the different values of $b$ for\neach subset.\n\nLet $X(v)$ be the training/cross-validate/test sets parametrized by $v$ and\nused by the MLP to perform the RUL estimation. Finally, let $f(v)=e_{rms}%\n(X(v))$. Recall from Equation (\\ref{eq:rmse}) that $d = \\hat{y} - y$ and that\n$\\hat{y}$ depends on $X(v)$. Note that one function evaluation of $f(v)$\nimplies training the MLP and computing the result of Equation (\\ref{eq:rmse}).\nHere we propose to optimize $v$ such that\n\\begin{equation}\n\\underset{v \\in\\mathbb{Z}^{3}}{\\mathrm{min}} f(v)\n\\label{eq:optimization_problem}%\n\\end{equation}\n\n\nThe problem to find optimal data-related parameters has no analytical\ndescriptions. Therefore, no gradient information is available. An evolutionary\nalgorithm is the natural choice for this optimization problem.\n\n\\subsubsection{True Optimal Data Parameters}\n\nThe finite size of CMAPS dataset and finite search space \nof $v$ allow an exhaustive\nsearch to be performed in order to find the true optimal data-related\nparameters. We would like to emphasize that although exhaustive search is a\npossibility for CMAPS dataset, it is in no way a possibility in a more general\nsetting. Nevertheless, the possibility to perform exhaustive search on the\nCMAPS dataset can be exploited to demonstrate the accuracy of the chosen EA\nand of the framework overall. In the following studies, we use the results and\ncomputational efforts of the exhaustive search as benchmarks to examine the\naccuracy and efficiency of the proposed approach.\n\nWe should note that the subsets of the data FD001 and FD003 have similar\nfeatures and that the subsets FD002 and FD004 have similar features. Because\nof this, we have decided to just optimize the data-related parameters by\nconsidering the subsets FD001 and FD002 only. An exhaustive search is\nperformed to find the true optimal values for $v$. \nThe MLP is only trained for $20$ epochs. Table\n\\ref{table:true_optimal_data_params} shows the optimal as well as the worst\ncombinations of data-related parameters and the total number of function\nevaluations used by the exhaustive search. It is important to notice that for \nthis experiment the window size is limited to be larger than or equal to $15$.\n\n\\subsubsection{Evolutionary Algorithm for Optimal Data Parameters}\n\n\\label{sec:ea_optimization_process}\n\nEvolutionary algorithms (EAs) are a family of methods for optimization\nproblems. The methods do not make any assumptions about the problem, treating\nit as a black box that merely provides a measure of quality given a candidate\nsolution. Furthermore, EAs do not require the gradient when searching for\noptimal solutions, making them very suitable for applications such as neural networks.\n\nFor the current application, the differential evolution (DE) method is chosen\nas the optimization algorithm \\cite{Storn1997}. Though other meta-heuristic\nalgorithms may also be suitable for this application, the DE has been\nstablished itself as one of the most reliable, robust and easy to use EAs.\nFurthermore, a ready to use Python implementation is available through the\nscipy package \\cite{scipy}. Although the DE method does not have special\noperators for treating integer variables, a very simple modification to the\nalgorithm, i.e. rounding every component of a candidate solution to its\nnearest integer, is used for this work.\n\nAs mentioned earlier, evolutionary algorithms such as the DE use several\nfunction evaluations when searching for the optimal solutions. Recall that for\nthis application, one function evaluation implies retraining the neural\nnetwork from scratch. This is not a desirable scenario, as obtaining the\noptimal data-related parameters would entail an extensive computational\neffort. Instead of running the DE for several iterations and with a large\npopulation size, we propose to run it just for $30$ iterations, i.e. the\ngenerations in the literature of evolutionary computation, with a population\nsize of $12$, which seems reasonable given the size of the search space of $v$.\n\nDuring the optimization, the MLP is trained only $20$ epochs. The small number\nof epochs of training the MLP is reasonable in this case because a small batch\nof data is used in the training, because we only look for the trend of the scoring indicators.\nFurthermore, it is common to observe that the parameters leading to lower\nscore values in the early stages of the training are more likely to provide\nbetter performance after more epochs of trainings. The settings of\nthe DE algorithm to find the optimal data-related parameters are listed in\nTable \\ref{table:de_hyperparams}.\n\nThe optimal data-related parameters for the subsets FD001 and FD002 found by\nthe DE algorithm are listed in Table \\ref{table:optimal_data_params}. As can be\nobserved, the results are in fact very close to the true optimal ones \nin Table \\ref{table:true_optimal_data_params} for both the subsets of the\ndata. The computational effort is reduced by one order of magnitude when using\nthe DE method as compared to the exhaustive search for the true optimal\nparameters. From the results in Table \\ref{table:optimal_data_params}, it can\nbe observed that the maximum allowable time window is always preferred while,\non the other hand, small window strides yield better results. For the case of\nearly RUL, it can be observed that larger values of $R_{e}$ are favored.\n\n\\subsection{The Estimation Algorithm}\n\nHaving described the major building blocks of the proposed method, we now\nintroduce the complete framework in the form of Algorithm \\ref{alg:rul_framework}.\n\n\\setcounter{algorithm}{0} \n\\begin{algorithm}[H]\n\\caption{\\newline ANN-EA RUL Estimation Framework}\\label{alg:rul_framework}\n\\textbf{Input:} Initial set of data-related parameters $v \\in \\mathbb{Z}^n$, \nRaw training/testing data $X$ and training labels $y$\\\\\n\\textbf{Output:} Optimal set of data-related parameters $v^*$\n\\begin{algorithmic}[1]\n\\State Choose regressor architecture (ANN, SVM, linear/logistic regression, etc).\n\\State Define $f(v)$ as in Section\\ref{sec:otimal_data_params}.\n\\State Optimize $f(v)$ using the preferred evolutionary algorithm, i.e. \ndifferential evolution, evolutionary strategies, genetic algorithm, etc, using the proposed \nguidelines from Section \\ref{sec:ea_optimization_process}.\n\\State Use $v^*$ to train the regressor for as many epochs as needed.\n\\end{algorithmic}\n\\end{algorithm}\n\n\n\\section{Evaluation of the Proposed Method}\n\n\\label{sec:rul_eval}\n\nIn this section, we evaluate the performance of the proposed method. The\narchitecture of the MLP is described in Table \\ref{table:proposed_nn}. \nThe MLP was trained $10$ times for $200$\nepochs each and tested in each subset of the CMAPS dataset.\nThe combinations of the optimal window size $n_{w}$, window\nstride $n_{s}$ and early RUL $R_{e}$ are presented in Table\n\\ref{table:data_params_de}.\n\nThe obtained results for $f(v)$ using the above setting are presented in Table\n\\ref{table:results_ann_de}. Notice that the performances obtained for datasets\nFD001 and FD002 are improved as compared with the results \nin Table \\ref{table:optimal_data_params}. This is due to the fact that the MLP is trained\nfor more epochs, thus obtaining better results.\n\n%Next, the possibility of using a single set of data-related parameters for all\n%the subsets is explored. For this experiment, the $n_{w}$ is fixed for all of\n%the four datasets, given that the maximum allowable window size for all\n%datasets is $18$. Hence, the data-related parameters are chosen as $v=(17, 1,\n%139)$. The results of predictions are shown in Table \\ref{table:results_ann_1}.\n\n%As can be observed, the performance is decreased for the subsets FD001 and\n%FD003. This indicates that larger window sizes are beneficial for this\n%regression problem. Figures \\ref{FigRMSEcomparison} and \\ref{FigRHScomparison}\n%show a comparison of the scores for each dataset by changing the data-related\n%parameters.\n\n%\\subsection{Comparison with Published Works}\n\nThe performance of the proposed method is compared against\nother state-of-the-art methods. Most of the methods chosen to compare here \nhave only reported the results on the test set FD001 in terms of\n$e_{rms}$. The results are shown in Table \\ref{table:results_comparison}. The\n$e_{rms}$ value of the proposed method in Table \\ref{table:results_comparison}\nis the mean value of 10 independent runs. The values of other methods are\nidentical to those reported in their respective original papers.\n\nFrom the comparison studies of the prediction results, we can conclude that\nthe proposed method performs better than the majority of the chosen methods\nwhen taking into consideration the whole dataset FD001. Two existing methods\ncome close to the performance of the proposed approach in this paper, namely\nthe time window ANN \\cite{Lim2016} and the Networks Ensemble \\cite{Zhang2016}.\nWhile the performance of these two methods comes close to the results of the\nproposed method in this paper, the proposed method is more computationally\nefficient. Furthermore, the framework proposed herein is simple to understand\nand implement, robust, generic and light-weight. These are the features \nimportant to highlight when comparing the proposed method against other\nstate-of-the-art approaches.\n\n\\section{Conclusions}\n\n\\label{sec:conclusions}\n\nWe have presented a novel framework for predicting the RUL of mechanical\ncomponents. While the method has been tested on the jet-engine dataset\nCMAPS, the method is general enough that it can be applied to other similar\nsystems. The framework makes use of a strided moving time window to generate\nthe training and test records. A shallow MLP to make the predictions of the RUL\nhas been found to be sufficient for the current dataset. The evolutionary\nalgorithm DE needs to be run just once to find the best data-related\nparameters that optimize the scoring functions. The results presented in this\npaper demonstrate that the proposed framework is accurate and computationally\nefficient, which makes this framework suitable for applications that have\nlimited computational resources such as embedded systems. Furthermore, the\ncomparison with other state-of-the-art methods has shown that the proposed\nmethod is the best overall performer.\n\nTwo major features of the proposed framework are its generality and\nscalability. While for this study, specific regressors and evolutionary\nalgorithms are chosen, many other combinations are possible and may be more\nsuitable for different applications. Furthermore, the framework can, in\nprinciple, be used for model-construction, i.e. generating the best possible\nneural network architecture tailored to a specific application.\n\n\\bibliographystyle{IEEEtran}\n\\bibliography{reference_rul_paper}\n%\n\n%TCIMACRO{\\QSubDoc{Include IEEE Bio}{\\input{IEEEBios.tex}}}%\n%BeginExpansion\n%\\input{IEEEBios.tex}\n%EndExpansion\n\n\n\\clearpage\n\n\n\\onecolumn%\n\n%TCIMACRO{\\TeXButton{Begin+Table+Center+Cap}{\\begin{table}\n%\\begin{center}\n%\\caption{C-MAPSS Dataset details.}}}%\n%BeginExpansion\n\\begin{table}\n\\begin{center}\n\\caption{C-MAPSS Dataset details.}%\n%EndExpansion\n%\n\n\\begin{tabular}\n[c]{l|cccc}\\hline\n& \\multicolumn{4}{c}{C-MAPSS}\\\\\nDataset & FD001 & FD002 & FD003 & FD004\\\\\\hline\\hline\nTraining Trajectories & 100 & 260 & 100 & 248\\\\\nTest Trajectories & 100 & 259 & 100 & 248\\\\\nOperating Conditions & 1 & 6 & 1 & 6\\\\\nFault Modes & 1 & 1 & 2 & 2\\\\\\hline\n\\end{tabular}\n\\label{TabCMAPSS}%\n\n%TCIMACRO{\\TeXButton{End+Center+Table}{\\end{center}\n%\\end{table}\n%}}%\n%BeginExpansion\n\\end{center}\n\\end{table}\n%EndExpansion\n%\n\n%TCIMACRO{\\TeXButton{Begin+Table+Center+Cap}{\\begin{table}\n%\\begin{center}\n%\\caption{Results for different architectures for subset 1, 100 epochs.}}}%\n%BeginExpansion\n\\begin{table}\n\\begin{center}\n\\caption{Results for different architectures for subset 1, 100 epochs.}%\n%EndExpansion\n%\n\n\\begin{tabular}\n[c]{l|cccc|cccc}\\hline\n& \\multicolumn{4}{|c}{RMSE} & \\multicolumn{4}{|c}{RHS}\\\\\nTested Architecture & Min. & Max. & Avg. & STD & Min. & Max. & Avg. &\nSTD\\\\\\hline\\hline\nArchitecture 1 & 15.51 & 17.15 & 16.22 & 0.49 & 4.60 & 7.66 & 5.98 & 0.91\\\\\nArchitecture 2 & 15.24 & 16.46 & 15.87 & 0.47 & 4.07 & 6.26 & 5.29 & 0.82\\\\\nArchitecture 3 & 15.77 & 17.27 & 16.15 & 0.45 & 5.11 & 8.25 & 5.93 & 0.94\\\\\nArchitecture 4 & 15.13 & 17.01 & 15.97 & 0.47 & 3.90 & 7.54 & 5.65 & 1.2\\\\\nArchitecture 5 & 16.39 & 17.14 & 16.81 & 0.23 & 5.19 & 6.58 & 5.98 & 0.42\\\\\nArchitecture 6 & 16.42 & 17.36 & 16.87 & 0.30 & 5.15 & 7.09 & 6.12 &\n0.62\\\\\\hline\n\\end{tabular}\n\\label{table:tested_architectures_100}%\n\n%TCIMACRO{\\TeXButton{End+Center+Table}{\\end{center}\n%\\end{table}}}%\n%BeginExpansion\n\\end{center}\n\\end{table}%\n%EndExpansion\n%\n\n%TCIMACRO{\\TeXButton{Begin+Table+Center+Cap}{\\begin{table}\n%\\begin{center}\n%\\caption{Proposed Neural Network architecture}.}}%\n%BeginExpansion\n\\begin{table}\n\\begin{center}\n\\caption{Proposed Neural Network architecture}.%\n%EndExpansion\n%\n\n\\begin{tabular}\n[c]{llll}\\hline\nLayer & Shape & Activation & Additional Information\\\\\\hline\\hline\nFully connected & \\multicolumn{1}{c}{20} & \\multicolumn{1}{c}{ReLU} &\n$L1=0.1,L2=0.2$\\\\\nFully connected & \\multicolumn{1}{c}{20} & \\multicolumn{1}{c}{ReLU} &\n$L1=0.1,L2=0.2$\\\\\nFully connected & \\multicolumn{1}{c}{1} & \\multicolumn{1}{c}{Linear} &\n$L1=0.1,L2=0.2$\\\\\\hline\n\\end{tabular}\n\\label{table:proposed_nn}%\n\n%TCIMACRO{\\TeXButton{End+Center+Table}{\\end{center}\n%\\end{table}}}%\n%BeginExpansion\n\\end{center}\n\\end{table}%\n%EndExpansion\n%\n\n%TCIMACRO{\\TeXButton{Begin+Table+Center+Cap}{\\begin{table}\n%\\begin{center}\n%\\caption{Allowed values for $b$ per subset.}}}%\n%BeginExpansion\n\\begin{table}\n\\begin{center}\n\\caption{Allowed values for $b$ per subset.}%\n%EndExpansion\n%\n\n\\begin{tabular}\n[c]{c|cccc}\\hline\n& FD001 & FD002 & FD003 & FD004\\\\\\hline\n$b$ & 30 & 20 & 30 & 18\\\\\\hline\n\\end{tabular}\n\\label{table:b_values}%\n\n%TCIMACRO{\\TeXButton{End+Center+Table}{\\end{center}\n%\\end{table}}}%\n%BeginExpansion\n\\end{center}\n\\end{table}%\n%EndExpansion\n%\n\n%TCIMACRO{\\TeXButton{Begin+Table+Center+Cap}{\\begin{table}\n%\\begin{center}\n%\\caption{Exhaustive search results for subsets FD001 and F002.}}}%\n%BeginExpansion\n\\begin{table}\n\\begin{center}\n\\caption{Exhaustive search results for subsets FD001 and F002.}%\n%EndExpansion\n%\n\n\\begin{tabular}\n[c]{l|crcrr}\\hline\nDataset & argmin $v$ & min $f(v)$ & argmax $v$ & max $f(v)$ & Function\nevals.\\\\\\hline\\hline\nFD001 & $\\left[  24,1,127\\right]  $ & \\multicolumn{1}{c}{$15.11$} & $\\left[\n25,10,94\\right]  $ & \\multicolumn{1}{c}{$85.19$} & \\multicolumn{1}{c}{8160}\\\\\nFD002 & $\\left[  16,1,138\\right]  $ & \\multicolumn{1}{c}{$30.93$} & $\\left[\n17,10,99\\right]  $ & \\multicolumn{1}{c}{$59.78$} & \\multicolumn{1}{c}{3060}%\n\\\\\\hline\n\\end{tabular}\n\\label{table:true_optimal_data_params}%\n\n%TCIMACRO{\\TeXButton{End+Center+Table}{\\end{center}\n%\\end{table}}}%\n%BeginExpansion\n\\end{center}\n\\end{table}%\n%EndExpansion\n\n\n\\bigskip%\n%TCIMACRO{\\TeXButton{Begin+Table+Center+Cap}{\\begin{table}\n%\\begin{center}\n%\\caption{Differential evolution hyper-parameters.}}}%\n%BeginExpansion\n\\begin{table}\n\\begin{center}\n\\caption{Differential evolution hyper-parameters.}%\n%EndExpansion\n%\n\n\\begin{tabular}\n[c]{llll}\\hline\nPopulation Size & Generations & Strategy & MLP epochs\\\\\\hline\n\\multicolumn{1}{c}{12} & \\multicolumn{1}{c}{30} & \\multicolumn{1}{c}{Best1Bin \\cite{Engelbrecht2007}}\n& \\multicolumn{1}{c}{20}\\\\\\hline\n\\end{tabular}\n\\label{table:de_hyperparams}%\n\n%TCIMACRO{\\TeXButton{End+Center+Table}{\\end{center}\n%\\end{table}}}%\n%BeginExpansion\n\\end{center}\n\\end{table}%\n%EndExpansion\n%\n\n%TCIMACRO{\\TeXButton{Begin+Table+Center+Cap}{\\begin{table}\n%\\begin{center}\n%\\caption\n%{Data-related parameters for each subset obtained with differential evolution.}%\n%}}%\n%BeginExpansion\n\\begin{table}\n\\begin{center}\n\\caption\n{Data-related parameters for each subset obtained with differential evolution.}%\n%EndExpansion\n%\n\n\\begin{tabular}\n[c]{l|crr}\\hline\nDataset & argmin $v$ & min $f(v)$ & Function evals.\\\\\\hline\\hline\nFD001 & $\\left[  24,1,129\\right]  $ & \\multicolumn{1}{c}{$15.24$} &\n\\multicolumn{1}{c}{372}\\\\\nFD002 & $\\left[  17,1,139\\right]  $ & \\multicolumn{1}{c}{$30.95$} &\n\\multicolumn{1}{c}{372}\\\\\\hline\n\\end{tabular}\n\\label{table:optimal_data_params}%\n\n%TCIMACRO{\\TeXButton{End+Center+Table}{\\end{center}\n%\\end{table}}}%\n%BeginExpansion\n\\end{center}\n\\end{table}%\n%EndExpansion\n%\n\n%TCIMACRO{\\TeXButton{Begin+Table+Center+Cap}{\\begin{table}\n%\\begin{center}\n%\\caption{Data-related parameters for each subset as obtained by DE.}}}%\n%BeginExpansion\n\\begin{table}\n\\begin{center}\n\\caption{Data-related parameters for each subset as obtained by DE.}%\n%EndExpansion\n%\n\n\\begin{tabular}\n[c]{lrrr}\\hline\nDataset & $n_{w}$ & $n_{s}$ & $R_{e}$\\\\\\hline\\hline\nFD001 & 24 & 1 & 129\\\\\nFD002 & 17 & 1 & 139\\\\\nFD003 & 24 & 1 & 129\\\\\nFD004 & 17 & 1 & 139\\\\\\hline\n\\end{tabular}\n\\label{table:data_params_de}%\n\n%TCIMACRO{\\TeXButton{End+Center+Table}{\\end{center}\n%\\end{table}}}%\n%BeginExpansion\n\\end{center}\n\\end{table}%\n%EndExpansion\n%\n\n%TCIMACRO{\\TeXButton{Begin+Table+Center+Cap}{\\begin{table}\n%\\begin{center}\n%\\caption\n%{Scores for each dataset using the data-related parameters obtained by DE (Second architecture).}%\n%}}%\n%BeginExpansion\n\\begin{table}\n\\begin{center}\n\\caption\n{Scores for each dataset using the data-related parameters obtained by DE (Second architecture).}%\n%EndExpansion\n%\n\n\\begin{tabular}\n[c]{l|cccc|cccc}\\hline\n& \\multicolumn{4}{|c}{RMSE} & \\multicolumn{4}{|c}{RHS}\\\\\nData Subset & min & max & avg & STD & min & max & avg & STD\\\\\\hline\\hline\nFD001 & 14.24 & 14.57 & 14.39 & 0.11 & 3.25 & 3.58 & 3.37 & 0.11\\\\\nFD002 & 28.90 & 29.23 & 29.09 & 0.11 & 45.99 & 53.90 & 50.69 & 2.17\\\\\nFD003 & 14.74 & 16.18 & 15.42 & 0.50 & 4.36 & 6.85 & 5.33 & 0.95\\\\\nFD004 & 33.25 & 35.10 & 34.74 & 0.53 & 58.52 & 78.62 & 74.77 & 5.88\\\\\\hline\n\\end{tabular}\n\\label{table:results_ann_de}%\n\n%TCIMACRO{\\TeXButton{End+Center+Table}{\\end{center}\n%\\end{table}}}%\n%BeginExpansion\n\\end{center}\n\\end{table}%\n%EndExpansion\n%\n\n%%TCIMACRO{\\TeXButton{Begin+Table+Center+Cap}{\\begin{table}\n%%\\begin{center}\n%%\\caption\n%%{Scores for each dataset using the single set of data-related parameters.}}}%\n%%BeginExpansion\n%\\begin{table}\n%\\begin{center}\n%\\caption\n%{Scores for each dataset using the single set of data-related parameters.}%\n%%EndExpansion\n%%\n%\n%\\begin{tabular}\n%[c]{l|rrrr|rrrr}\\hline\n%& \\multicolumn{4}{|c}{RMSE} & \\multicolumn{4}{|c}{RHS}\\\\\n%Data Subset & min & max & avg & STD & min & max & avg & STD\\\\\\hline\\hline\n%FD001 & 16.74 & 17.23 & 17.06 & 0.18 & 8.08 & 9.26 & 8.64 & 0.45\\\\\n%FD002 & 29.77 & 30.12 & 29.94 & 0.11 & 54.90 & 63.53 & 58.82 & 2.39\\\\\n%FD003 & 16.94 & 18.52 & 17.77 & 0.39 & 6.02 & 10.18 & 7.64 & 1.37\\\\\n%FD004 & 33.95 & 35.46 & 35.14 & 0.44 & 58.71 & 67.91 & 65.78 & 2.64\\\\\\hline\n%\\end{tabular}\n%\\label{table:results_ann_1}%\n%%TCIMACRO{\\TeXButton{End+Center+Table}{\\end{center}\n%%\\end{table}}}%\n%%BeginExpansion\n%\\end{center}\n%\\end{table}%\n%%EndExpansion\n%%\n\n%TCIMACRO{\\TeXButton{Begin+Table+Center+Cap}{\\begin{table}\n%\\begin{center}\n%\\caption\n%{Performance comparison of the proposed method and the latest related papers on the CMAPS dataset.}%\n%}}%\n%BeginExpansion\n\\begin{table}\n\\begin{center}\n\\caption\n{Performance comparison of the proposed method and the latest related papers on the CMAPS dataset.}%\n%EndExpansion\n%\n\n\\begin{tabular}\n[c]{l|r}\\hline\nMethod & $e_{rms}$\\\\\\hline\nESN trained by Kalman Filter \\cite{Peng2012} & 63.45\\\\\nSupport Vector Machine Classifier \\cite{Louen2013} & 29.82\\\\\nTime Window Neural Network \\cite{Lim2016} & 15.16\\\\\nMulti-objective deep belief networks ensemble \\cite{Zhang2016} & 15.04\\\\\nDeep Convolutional Neural Network \\cite{Babu2016} & 18.45\\\\\n\\textbf{Proposed method with $n_{w}=30$, $n_{s}=1$ and $R_{e}=128$} &\n14.39\\\\\\hline\n\\end{tabular}\n\\label{table:results_comparison}%\n\n%TCIMACRO{\\TeXButton{End+Center+Table}{\\end{center}\n%\\end{table}}}%\n%BeginExpansion\n\\end{center}\n\\end{table}%\n%EndExpansion\n%\n\n%TCIMACRO{\\TeXButton{Clearpage}{\\clearpage}}%\n%BeginExpansion\n\\clearpage\n%EndExpansion\n%\n\n%TCIMACRO{\\FRAME{ftbpFU}{4.0421in}{1.5212in}{0pt}{\\Qcb{Graphical depiction of\n%the time window used in this framework.}}{\\Qlb{FigWindow}}{time_window.png}%\n%{\\special{ language \"Scientific Word\";  type \"GRAPHIC\";\n%maintain-aspect-ratio TRUE;  display \"USEDEF\";  valid_file \"F\";\n%width 4.0421in;  height 1.5212in;  depth 0pt;  original-width 10.933in;\n%original-height 4.0672in;  cropleft \"0\";  croptop \"1\";  cropright \"1\";\n%cropbottom \"0\";  filename 'Figures/time_window.png';file-properties \"XNPEU\";}}\n%}%\n%BeginExpansion\n\\begin{figure}\n[ptb]\n\\begin{center}\n\\includegraphics[\n%natheight=4.067200in,\n%natwidth=10.933000in,\n%height=1.5212in,\nwidth=4.0421in\n]%\n{Figures/time_window.png}%\n\\caption{Graphical depiction of the time window used in this framework.}%\n\\label{FigWindow}%\n\\end{center}\n\\end{figure}\n%EndExpansion\n\n\n%\n\n%TCIMACRO{\\FRAME{ftbpFU}{3.2897in}{2.3661in}{0pt}{\\Qcb{Piecewise linear\n%degradation for RUL.}}{\\Qlb{FigRULinear}}{test_engine.png}%\n%{\\special{ language \"Scientific Word\";  type \"GRAPHIC\";\n%maintain-aspect-ratio TRUE;  display \"USEDEF\";  valid_file \"F\";\n%width 3.2897in;  height 2.3661in;  depth 0pt;  original-width 5.3463in;\n%original-height 3.8337in;  cropleft \"0\";  croptop \"1\";  cropright \"1\";\n%cropbottom \"0\";  filename 'Figures/test_engine.png';file-properties \"XNPEU\";}}\n%}%\n%BeginExpansion\n\\begin{figure}\n[ptb]\n\\begin{center}\n\\includegraphics[\nnatheight=3.833700in,\nnatwidth=5.346300in,\nheight=2.3661in,\nwidth=3.2897in\n]%\n{Figures/test_engine.png}%\n\\caption{Piecewise linear degradation for RUL.}%\n\\label{FigRULinear}%\n\\end{center}\n\\end{figure}\n%EndExpansion\n%\n\n%%TCIMACRO{\\FRAME{ftbpFU}{3.5405in}{2.2995in}{0pt}{\\Qcb{Comparison of RMSE\n%%results for different sets of data-related parameters.}}%\n%%{\\Qlb{FigRMSEcomparison}}{rmse_comparisson.png}%\n%%{\\special{ language \"Scientific Word\";  type \"GRAPHIC\";\n%%maintain-aspect-ratio TRUE;  display \"USEDEF\";  valid_file \"F\";\n%%width 3.5405in;  height 2.2995in;  depth 0pt;  original-width 5.6593in;\n%%original-height 3.6599in;  cropleft \"0\";  croptop \"1\";  cropright \"1\";\n%%cropbottom \"0\";\n%%filename 'Figures/rmse_comparisson.png';file-properties \"XNPEU\";}} }%\n%%BeginExpansion\n%\\begin{figure}\n%[ptb]\n%\\begin{center}\n%\\includegraphics[\n%natheight=3.659900in,\n%natwidth=5.659300in,\n%height=2.2995in,\n%width=3.5405in\n%]%\n%{Figures/rmse_comparisson.png}%\n%\\caption{Comparison of RMSE results for different sets of data-related\n%parameters.}%\n%\\label{FigRMSEcomparison}%\n%\\end{center}\n%\\end{figure}\n%%EndExpansion\n%%\n%\n%%TCIMACRO{\\FRAME{ftbpFU}{3.5405in}{2.3013in}{0pt}{\\Qcb{Comparison of RHS\n%%results for different sets of data-related parameters.}}%\n%%{\\Qlb{FigRHScomparison}}{rhs_comparisson.png}%\n%%{\\special{ language \"Scientific Word\";  type \"GRAPHIC\";\n%%maintain-aspect-ratio TRUE;  display \"USEDEF\";  valid_file \"F\";\n%%width 3.5405in;  height 2.3013in;  depth 0pt;  original-width 5.6559in;\n%%original-height 3.6599in;  cropleft \"0\";  croptop \"1\";  cropright \"1\";\n%%cropbottom \"0\";\n%%filename 'Figures/rhs_comparisson.png';file-properties \"XNPEU\";}} }%\n%%BeginExpansion\n%\\begin{figure}\n%[ptb]\n%\\begin{center}\n%\\includegraphics[\n%natheight=3.659900in,\n%natwidth=5.655900in,\n%height=2.3013in,\n%width=3.5405in\n%]%\n%{Figures/rhs_comparisson.png}%\n%\\caption{Comparison of RHS results for different sets of data-related\n%parameters.}%\n%\\label{FigRHScomparison}%\n%\\end{center}\n%\\end{figure}\n%%EndExpansion\n%\n\n\\clearpage\n\n\n\\appendix\n\n\n\\section*{Tested Neural Network Architectures}\n\n%\\label{sec:appendices}\n\\bigskip\n\n\\begin{table}[tbh]\n\\centering\n\\caption{Proposed Neural Network architecture 1.}%\n\\begin{tabular}\n[c]{llll}\\hline\nLayer & Shape & Activation & Additional Information\\\\\\hline\\hline\nFully connected & 20 & ReLU & L1 = 0.1, L2 = 0.2\\\\\nFully connected & 20 & ReLU & L1 = 0.1, L2 = 0.2\\\\\nFully connected & 1 & Linear & L1 = 0.1, L2 = 0.2\\\\\\hline\n\\end{tabular}\n\\label{table:proposed_nn_1}%\n\\end{table}\n\n\\begin{table}[tbh]\n\\centering\n\\caption{Proposed Neural Network architecture 2.}%\n\\begin{tabular}\n[c]{llll}\\hline\nLayer & Shape & Activation & Additional Information\\\\\\hline\\hline\nFully connected & 50 & ReLU & L1 = 0.1, L2 = 0.2\\\\\nFully connected & 20 & ReLU & L1 = 0.1, L2 = 0.2\\\\\nFully connected & 1 & Linear & L1 = 0.1, L2 = 0.2\\\\\\hline\n\\end{tabular}\n\\label{table:proposed_nn_2}%\n\\end{table}\n\n\\begin{table}[tbh]\n\\centering\n\\caption{Proposed Neural Network architecture 3.}%\n\\begin{tabular}\n[c]{llll}\\hline\nLayer & Shape & Activation & Additional Information\\\\\\hline\nFully connected & 100 & ReLU & L1 = 0.1, L2 = 0.2\\\\\nFully connected & 50 & ReLU & L1 = 0.1, L2 = 0.2\\\\\nFully connected & 1 & Linear & L1 = 0.1, L2 = 0.2\\\\\\hline\n\\end{tabular}\n\\label{table:proposed_nn_3}%\n\\end{table}\n\n\\begin{table}[tbh]\n\\centering\n\\caption{Proposed Neural Network architecture 4.}%\n\\begin{tabular}\n[c]{llll}\\hline\nLayer & Shape & Activation & Additional Information\\\\\\hline\nFully connected & 250 & ReLU & L1 = 0.1, L2 = 0.2\\\\\nFully connected & 50 & ReLU & L1 = 0.1, L2 = 0.2\\\\\nFully connected & 1 & Linear & L1 = 0.1, L2 = 0.2\\\\\\hline\n\\end{tabular}\n\\label{table:proposed_nn_4}%\n\\end{table}\n\n\\begin{table}[tbh]\n\\centering\n\\caption{Proposed Neural Network architecture 5.}%\n\\begin{tabular}\n[c]{llll}\\hline\nLayer & Shape & Activation & Additional Information\\\\\\hline\\hline\nFully connected & 20 & ReLU & L1 = 0.1, L2 = 0.2\\\\\nFully connected & 1 & Linear & L1 = 0.1, L2 = 0.2\\\\\\hline\n\\end{tabular}\n\\label{table:proposed_nn_5}%\n\\end{table}\n\n\\begin{table}[tbh]\n\\centering\n\\caption{Proposed Neural Network architecture 6.}%\n\\begin{tabular}\n[c]{llll}\\hline\nLayer & Shape & Activation & Additional Information\\\\\\hline\\hline\nFully connected & 10 & ReLU & L1 = 0.1, L2 = 0.2\\\\\nFully connected & 1 & Linear & L1 = 0.1, L2 = 0.2\\\\\\hline\n\\end{tabular}\n\\label{table:proposed_nn_6}%\n\\end{table}\n\\end{document}", "meta": {"hexsha": "87171f2e45538882c504693a2e36572c8dafde14", "size": 42181, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Papers/RUL_NN_DE_paper/RUL-IEEE/IEEE/RUL1.tex", "max_stars_repo_name": "dlaredo/NASA_RUL_-CMAPS-", "max_stars_repo_head_hexsha": "b4fc4267e2abb4b0542e4658fd8ee931ba848fd1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2018-05-09T09:18:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T06:37:53.000Z", "max_issues_repo_path": "Papers/RUL_NN_DE_paper/RUL-IEEE/IEEE/RUL1.tex", "max_issues_repo_name": "hard10086/NASA_RUL_-CMAPS-", "max_issues_repo_head_hexsha": "b4fc4267e2abb4b0542e4658fd8ee931ba848fd1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-06-11T09:09:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-08T21:23:07.000Z", "max_forks_repo_path": "Papers/RUL_NN_DE_paper/RUL-IEEE/IEEE/RUL1.tex", "max_forks_repo_name": "hard10086/NASA_RUL_-CMAPS-", "max_forks_repo_head_hexsha": "b4fc4267e2abb4b0542e4658fd8ee931ba848fd1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-07-06T03:40:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T07:30:26.000Z", "avg_line_length": 40.2490458015, "max_line_length": 106, "alphanum_fraction": 0.7587776487, "num_tokens": 12193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982179521105, "lm_q2_score": 0.4921881357207955, "lm_q1q2_score": 0.3188385972171028}}
{"text": "\\documentclass[12pt]{article}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{geometry}\n\\usepackage{enumerate}\n\\usepackage{natbib}\n\\usepackage{float}%稳定图片位置\n\\usepackage{graphicx}%画图\n\\usepackage[english]{babel}\n\\usepackage{a4wide}\n\\usepackage{indentfirst}%缩进\n\\usepackage{enumerate}%加序号\n\\usepackage{multirow}%合并行\n\\title{Final Report}\n\n\\begin{document}\n\\maketitle\n\\newpage\n\\section{Search Algorithm}\n\\subsection{Room Segment}\nThe general function of the base board is moving to your appointed destination and return. To realize it, we cut the room into many small squares with coordinates. Then, we can tell  the coordinates of the destination. In addition, since the coordinate system is absolute, Metbin also should know the coordinates of its initial place to calculate its relative position about the destination.\n\\begin{figure}[H]\n\\centering\n\\includegraphics[scale=0.8]{P1.jpg}\n\\caption{Room segment with coordinates}\n\\end{figure}\nIn the figure 1, the room is cut into $4\\times4$ squares with coordinates, and there are x and y axis. So we can know the initial position of Metbin is (4,4) and the destination's coordinates are (4,1). \n\\subsection{Direction of Metbin}\nSince we use a search algorithm, Metbin must know its direction relative to x and y axis, so it can know towards which square it's moving. Since the room is cut into squares, so we introduce a direction variable \\textbf{d} of four values to represent robot's current direction. \n\\begin{figure}[H]\n\\centering\n\\includegraphics[scale=1]{P2.jpg}\n\\caption{Direction variable}\n\\end{figure}\nThe figure shows the direction in the room. Since its also absolute, it should be input to the Metbin in advance. We set the direction parallel to y axis is 1, and it will become plus one after Metbin turn right 90 degrees, and it will minus 1 after it turn left. It is worth to mention that \\textbf{d} only has 4 values (1$\\sim$4), so when its reaches 5, it will minus 4.\nSimilarly, when \\textbf(d) is smaller than 1, it will plus 4.\n\\par In the figrue 1, it's clear that Metbin can only move against the direction of x axis, so its initial \\textbf{d} is 4.\n\\subsection{Square Information and its Variables}\nTo realize the search function, we introduce ten variables to describe each square.\n\\begin{table}[H]\n\\centering\n\\begin{tabular}{|c|c|c|c|}\n\\hline\nvariable name & meaning  & value range  \\\\ \\hline\n\\textbf{E} &The order of the square first reached by Metbin  & 1$\\sim$16   \\\\ \\hline\n\\textbf{X[E]} &The x coordinate of square \\textbf{E}  &  1$\\sim$4  \\\\ \\hline\n\\textbf{Y[E]} &The y coordinate of square \\textbf{E}  &  1$\\sim$4  \\\\ \\hline\n\\textbf{D[E]} &Metbin's \\textbf{d} when it first reaches square \\textbf{E}  &1$\\sim$4    \\\\ \\hline\n\\textbf{L[E]} &The left obstacle situation when Metbin first reaches square \\textbf{E}  &-1$\\sim$16  \\\\ \\hline\n\\textbf{F[E]} &The front obstacle situation when Metbin first reaches square \\textbf{E}  &-1$\\sim$16     \\\\ \\hline\n\\textbf{R[E]} &The right obstacle situation when Metbin first reaches square \\textbf{E}  &-1$\\sim$16     \\\\ \\hline\n\\textbf{l[E]} &The left priority when Metbin reach square \\textbf{E}  &0$\\sim$3     \\\\ \\hline\n\\textbf{f[E]} &The front priority when Metbin reach square \\textbf{E}  &0$\\sim$3     \\\\ \\hline\n\\textbf{r[E]} &The right priority when Metbin reach square \\textbf{E}  &0$\\sim$3    \\\\ \\hline\n\\end{tabular}\n\\caption{Variables describing a square}\n\\end{table}\n\\subsubsection{Square Order \\textbf{E} and Direction \\textbf{D[E]}}\nAs mentioned in table 1, \\textbf{E} represents the order of the square first reached by Metbin. For example, in Figure 1, Metbin's initial position's \\textbf{E} is 1 and the square with coordinates (3,4) is 2. Every square only has one corresponding \\textbf{E}. If Metbin return a square which already has \\textbf{E}, it won't change. Since there are 16 squares in the field, $E_{max}=16$.\n\\par Additionally, when Metbin first reaches the square, its \\textbf{d} will be recorded as square \\textbf{E}'s \\textbf{D[E]}. It also won't change later.  \n\\subsubsection{Obstacle situation \\textbf{L[E]}, \\textbf{F[E]}, and \\textbf{R[E]}}\nAs mentioned the before, the three variable describe the obstacle situation in three sides when Metbin is in the square with direction \\textbf{D[E]}. If there is an obstacle on right side, then \\textbf{R[E]} will be 0. If there is no obstacle then, if there is a reached square \\textbf{E'}, then \\textbf{R[E]}=\\textbf{E'}, else ]\\textbf{R[E]}=-1. Since there are 16 squares in the field, the obstacle variable can't be bigger than 16.  \n\\par If every square's obstacle situation is bigger than -1, than Metbin has already reached every squares.\n\\subsubsection{Priority Variable \\textbf{l[E]}, \\textbf{f[E]}, and \\textbf{r[E]}}\nThe three variable in lower case describe the order of directions to turn when Metbin reach \\textbf{E} with \\textbf{D[E]}. These variable value is smaller than 3 because there is only 3 directions Metbin can advance. Metbin will choose the biggest variable and go its corresponding direction. \n\\par For example , if Metbin reaches square \\textbf{5} and \\textbf{l[5]}=0, \\textbf{f[E]}=1, and \\textbf{r[5]}=3, then it will turn right keep going. Then \\textbf{r[5]} will become 0 after Metbin go back.\n\\par When Metbin reaches a new square, the three variables will generated according to Metbin's relative location to the destination and obstacle situation variables. If there is an obstacle on the left side (\\textbf{L[E]}=0) then \\textbf{l[E]} will also be 0 because there can't go. If there is no wall, then if the obstacle is in front of Metbin, then \\textbf{f[E]} will be 3. Then if the obstacle is on the right, \\textbf{r[E]} will be 2 and \\textbf{l[E]}=1. If the obstacle is on the back of Metbin, then \\textbf{f[E]} will be 1 and other two variables will plus one correspondingly. Otherwise, Metbin will go at the order of left, front, then right.\n\\subsubsection{An Example without return from Figure 1}\n\\begin{figure}[H]\n\\centering\n\\includegraphics[scale=0.4]{P3.jpg}\n\\caption{Direction variable}\n\\end{figure}\nThe first 5 squares' \\textbf{E} is already shown on the picture and the following table shows the information recorder when Metbin first reaches square 5.\n\\begin{table}[H]\n\\centering\n\\begin{tabular}{|c|c|c|c|c|c|c|c|c|c|}\n\\hline\n\\textbf{E}&\\textbf{X[E]}&\\textbf{Y[E]}&\\textbf{D[E]}&\\textbf{L[E]}&\\textbf{F[E]}&\\textbf{R[E]}&\\textbf{l[E]}&\\textbf{f[E]}&\\textbf{r[E]}\\\\ \\hline\n1 &4  &4  &4  &0 &2 &0 &0 &2 &0  \\\\ \\hline\n2 &3  &4  &4  &0 &3 &0 &0 &1 &0  \\\\ \\hline\n3 &2  &4  &4  &4 &-1&0 &3 &2 &0  \\\\ \\hline\n4 &2  &3  &3  &-1&5&-1 &2 &3 &1 \\\\ \\hline\n5 &2  &2  &3  &-1&0&0  &2 &0 &0 \\\\ \\hline\n\\end{tabular}\n\\caption{Information variables of the first 5 squares.}\n\\end{table}\n\\begin{figure}[H]\n\\centering\n\\includegraphics[scale=0.5]{P4.jpg}\n\\caption{Flow chart between square 1 and square 2}\n\\end{figure}\nIf there are only few obstacles, Metbin can go to the destination according to the above flow chart.\n\\begin{figure}[H]\n\\centering\n\\includegraphics[scale=0.5]{P5.jpg}\n\\caption{Metbin's route to destination}\n\\end{figure}\n\\subsection{Realization of Return Function}\nHowever, if there are many obstacles in the room, Metbin may reach a square \\textbf{E} which has three walls around it (\\textbf{L[E]}=0,\\textbf{F[E]}=0, and \\textbf{R[E]}=0). Then Metbin must return to another square \\textbf{E'} who must have one obstacle situation variable equals to \\textbf{E}. If there are many \\textbf{E'} has such variable, then Metbin will go to the square with smallest \\textbf{E'}.\n\\begin{figure}[H]\n\\centering\n\\includegraphics[scale=0.7]{P6.jpg}\n\\caption{Metbin's whole route in example 2}\n\\end{figure}\nIn the Figure 6, Metbin's initial square's coordinates are \\textbf{X[1]}=1, \\textbf{Y[1]}=1, and \\textbf{D[1]}=1. The destination's coordinates are \\textbf{X[E]}=4 and \\textbf{Y[E]}=3. \nWe draw the route of Metbin according to our algorithm, the black lines represent Metbin's route to a new square and the white lines represent its route of returning. Some square's \\textbf{E} are already shown on the figure. This will be recorded when Metbin's moving. In this field, square \\textbf{3}, \\textbf{7}, and \\textbf{8} has three obstacles around it, so Metbin will return after reached these squares. In addition, since the destination's coordinates has already been input to Metbin and it keeps recording its own coordinates. When these coordinates are same, Metbin knows that it has reached the destination and return.\n\\section{Computer Simulation}\nSince the algorithm is hard to realize, we decide to simulate it on computer first. In this procedure, we draw a field and Metbin's route. Then we input the obstacle situation variable according to Metbin's route. This will be detected by infra-red sensors in real field. We only input 0 or -1 as every square's obstacle situation variable's value. (-1 means there is no obstacle and 0 represents there is an obstacle.)\n\\par for example in figure 6, we can input the following list\n\\begin{table}[H]\n\\centering\n\\begin{tabular}{|c|c|c|c|}\n\\hline\n\\textbf{E}  & \\textbf{L[E]} & \\textbf{F[E]} & \\textbf{R[E]} \\\\ \\hline\n1  & 0        & -1       & -1       \\\\ \\hline\n2  & 0        & -1       & 0        \\\\ \\hline\n3  & 0        & 0        & 0        \\\\ \\hline\n4  & -1       & -1       & 0        \\\\ \\hline\n5  & -1       & -1       & 0        \\\\ \\hline\n6  & -1       & 0        & 0        \\\\ \\hline\n7  & 0        & 0        & 0        \\\\ \\hline\n8  & 0        & 0        & 0        \\\\ \\hline\n9  & 0        & -1       & 0        \\\\ \\hline\n10 & 0        & -1       & -1       \\\\ \\hline\n11 & -1       & -1       & 0        \\\\ \\hline\n12 & -1       & 0        & 0        \\\\ \\hline\n\\end{tabular}\n\\caption{Input of Obstacle Situation}\n\\end{table}\nThen the Metbin can generate every square's information variable according table 3\n\\begin{table}[H]\n\\centering\n\\begin{tabular}{|c|c|c|c|c|c|c|c|c|c|}\n\\hline\n\\textbf{E}  & \\textbf{X[E]}  & \\textbf{Y[E]} & \\textbf{D[E]} & \\textbf{L[E]} & \\textbf{F[E]} & \\textbf{R[E]} & \\textbf{l[E]} & \\textbf{f[E]} & \\textbf{r[E]} \\\\ \\hline\n1  & 1        & 1        & 1        & 0        & 2        & 4        & 0        & 3        & 2        \\\\ \\hline\n2  & 1        & 2        & 1        & 0        & 3        & 0        & 0        & 3        & 0        \\\\ \\hline\n3  & 1        & 3        & 1        & 0        & 0        & 0        & 0        & 0        & 0        \\\\ \\hline\n4  & 2        & 1        & 2        & 9        & 5        & 0        & 2        & 3        & 0        \\\\ \\hline\n5  & 3        & 1        & 2        & 8        & 6        & 0        & 2        & 3        & 0        \\\\ \\hline\n6  & 4        & 1        & 2        & 7        & 0        & 0        & 3        & 0        & 0        \\\\ \\hline\n7  & 4        & 2        & 1        & 0        & 0        & 0        & 0        & 0        & 0        \\\\ \\hline\n8  & 3        & 2        & 1        & 0        & 0        & 0        & 0        & 0        & 0        \\\\ \\hline\n9  & 2        & 2        & 1        & 0        & 10       & 0        & 0        & 3        & 0        \\\\ \\hline\n10 & 2        & 3        & 1        & 0        & -1       & 11       & 0        & 2        & 3        \\\\ \\hline\n11 & 3        & 3        & 2        & -1       & 12       & 0        & 2        & 3        & 0        \\\\ \\hline\n12 & 4        & 3        & 2        & -1       & 0        & 0        & 0        & 0        & 0        \\\\ \\hline\n\\end{tabular}\n\\caption{Information variable}\n\\end{table}\nTo test whether Metbin will move according to the correct route, we introduce a array \\textbf{A[i]} of four values from $1\\sim3$. \n\\begin{table}[H]\n\\centering\n\\begin{tabular}{|c|c|c|c|}\n\\hline\n\\textbf{A[i]} & 1                           & 2                    & 3                     \\\\ \\hline\n         & move forward to next square & turn left 90 degrees & turn right 90 degrees \\\\ \\hline\n\\end{tabular}\n\\caption{Array \\textbf{A}}\n\\end{table}\nSo Metbin should generate \\textbf{A[i]=$\\lbrace 11133111333111212213133212213133211311221121131\\rbrace$}\nif the Metbin can generate the correct \\textbf{A[i]} according to our input obstacle information, we just need to let Metbin read the array and make the correct motion\n\\section{Realization of \\textbf{A[i]}} \nSince the environment is of great randomness, we must use multiple sensors to ensure Metbin is in the correct position in the field. We decide to use posture sensors, encoders and many infra-red sensors.\n\\subsection{Posture Sensors}\nThe posture sensors have many functions such as detect the magnetic field and its angle. It can calculate its deflection angle by angular acceleration integral and this is the only function required. so I can set it on computer.\n\\begin{figure}[H]\n\\centering\n\\includegraphics[scale=0.5]{P7.jpg}\n\\caption{Posture Sensors' setting surface on computer}\n\\end{figure}\nThe posture sensors can return a value \\textbf{z} describing the angle deflected. It's value range is $0\\sim360$. If the Metbin needs to turning right 90 degrees, it will only turn until \\textbf{z}-\\textbf{$\\mathbf{z_{initial}}$}$\\approx90^o$. Similarly to \\textbf{d} in Search Algorithm, $\\mathbf{\\bigtriangleup_z}$ may be small than 0 sometime, so it need to be dealt with. \n\\subsection{Encoders}\nWe use encoders to recorded how far does Metbin move on the field. To eliminate accumulative, it will be set to 0 every time Metbin meet an obstacle. The encoders can return 1 and 0 when it receive a change in Motor's voltage. So we can record the number of pulse to calculate how far does Metbin move. After many experiments, we think when Metbin will move 55cm when 1500 pulse are returned.\n\\subsection{Infra-red Sensors}\nInfra-red sensors can return its distance from obstacle. \n\\begin{figure}[H]\n\\centering\n\\includegraphics[scale=0.5]{P8.jpg}\n\\caption{Relation between the distance and return value. }\n\\end{figure}\nWhen infra-red sensors' return value is bigger than 100, we assume there is an obstacle before it. We install five infra-red sensors on Metbin, one is installed at the head and two are installed at left and right sides respectively. In addition ,infra-red sensors can be used to detect whether Metbin is parallel to the wall. Since there are two infra-red sensors on one side. If $\\frac{v_1-v_2}{v_1+v_2}<0.01$ then Metbin is parallel to the wall. The posture's accumulative error will be eliminate at the time.\n\\end{document}", "meta": {"hexsha": "d36b740d91c02543965b10a62a8679890b8dfb31", "size": 14324, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "VG100IntroEngineering/P2/Baseboard Solution/Solution.tex", "max_stars_repo_name": "PANDApcd/SJTU-Entrepreneurship", "max_stars_repo_head_hexsha": "d50ca8b0298a5f96518397d2cdd7772d63927cfc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "VG100IntroEngineering/P2/Baseboard Solution/Solution.tex", "max_issues_repo_name": "PANDApcd/SJTU-Entrepreneurship", "max_issues_repo_head_hexsha": "d50ca8b0298a5f96518397d2cdd7772d63927cfc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "VG100IntroEngineering/P2/Baseboard Solution/Solution.tex", "max_forks_repo_name": "PANDApcd/SJTU-Entrepreneurship", "max_forks_repo_head_hexsha": "d50ca8b0298a5f96518397d2cdd7772d63927cfc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 77.847826087, "max_line_length": 654, "alphanum_fraction": 0.6621055571, "num_tokens": 4443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3188256822288364}}
{"text": "\\section{Introduction}\\label{sec:introduction}\n\nA bunch of different characteristics in complex systems can be tracked down to\nnon-stationarity \\cite{non_stat_1,non_stat_2}. These systems lack any kind of\nequilibrium \\cite{comp_sys_1,comp_sys_2,comp_sys_3,comp_sys_4}. Financial\nmarkets are perfect examples of non-stationarity as they fluctuate considerably\nin time. In general, the business relations between companies and agents can\nchange due to market expectations. During a state of crisis, non-stationarity\nbecomes dramatic\n\\cite{state_crisis_1,state_crisis_2,state_crisis_3,state_crisis_4,state_crisis_5,state_crisis_6,state_crisis_7}.\n\nThe fluctuation of the correlations induces generic features in financial time\nseries, where we showed that these fluctuations lift the tails of the\nmultivariate amplitude distributions, making them heavy-tailed\n\\cite{non_stationarity_fin_guhr,exact_distributions_guhr}.\n\nOur goal is to use the analytical results for the multivariate distributions of\namplitudes, measured as time series in correlated, non-stationary financial\nmarkets and provide quantitative measures for the degree of non-stationarity in\nthe correlations using the methodology first proposed in\n\\cite{non_stationarity_fin_guhr} and extended in\n\\cite{exact_distributions_guhr}. These amplitudes refer to the stock price\nchanges for the entire market.\n\nWe carry out a detailed data analysis that exposes generic features. Then we\nuse a random matrix model to explain them. We show that non-stationarity of the\ncorrelations leads to heavy tails in the multivariate return distribution and\nfinally, we use the approach in\n\\cite{non_stationarity_fin_guhr,exact_distributions_guhr} to map a\nnon-invariant situation to an effectively invariant one.\n\nA remarkable feature of the multivariate distributions we use to compare with\nthe financial data, is that eventually, they are of closed form or involve only\nsingle integrals. Moreover, they use a low number of free parameters: one\nmeasuring how strongly the non-stationary correlations fluctuate, and one or\ntwo shape parameters for the tails. All the other parameters can be directly\nmeasured from the data \\cite{exact_distributions_guhr}.\n\nRandom matrix models \\cite{random_matrix_1,random_matrix_2} fall into two\nclasses: (I) The ensemble is fictitious. It comes into play via an ergodicity\nargument only. (II) The ensemble really exists and can be identified in the\nsystem. The issue of ergodicity does not arise. It is conceptually important\nthat we here use a random matrix model in class (II) which may be seen as a new\ninterpretation of the Wishart model and generalizations thereof for random\ncovariance or correlation matrices \\cite{wishart}. In finance there are\nnumerous random matrix applications\n\\cite{matrix_fin_01,matrix_fin_02,matrix_fin_03,matrix_fin_04,matrix_fin_05,matrix_fin_06,matrix_fin_07,matrix_fin_08,matrix_fin_09,matrix_fin_10,matrix_fin_11,matrix_fin_12,matrix_fin_13}\nincluding non-Gaussian ensembles. To the best of our knowledge, all of them\nfall into class (I) and focus on other observables. The distributions we use\narrive at rather universal and generic results, supporting the view that\nnon-stationarities can lead to universal features. To facilitate the\nreproduction of our results, the source code for the data analysis is available\nin Ref. \\cite{code}.\n\nThe paper is organized as follows: in Sect. \\ref{sec:data_set} we present our\ndata set of stocks. We define the key concepts, present the epochs analysis of\nthe stock time series and discuss the method used by T. A. Schmitt et al.\n\\cite{non_stationarity_fin_guhr} in Sect. \\ref{sec:epochs}. In Sect.\n\\ref{sec:simulations} we simulate returns time series to test the rotation and\nscaling method and check the influence of the epochs in the results. We define\nthe general considerations to use the exact multivariate distributions in Sect.\n\\ref{sec:exact_distributions}. In Sect. \\ref{sec:comparison_returns} we compare\nthe theoretical distributions with the empirical aggregated distribution of\nreturns. Our conclusions follow in Sect. \\ref{sec:conclusion}.", "meta": {"hexsha": "99d0a7e39e10a2f60488638f6f29f41aafbf33bc", "size": 4111, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/exact_distributions_financial_paper/sections/03_introduction.tex", "max_stars_repo_name": "juanhenao21/exact_distributions_financial", "max_stars_repo_head_hexsha": "02eb058e5f963fbccb9029aae3fb6e15def7a93a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-20T18:24:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-15T07:25:50.000Z", "max_issues_repo_path": "paper/exact_distributions_financial_paper/sections/03_introduction.tex", "max_issues_repo_name": "juanhenao21/exact_distributions_financial", "max_issues_repo_head_hexsha": "02eb058e5f963fbccb9029aae3fb6e15def7a93a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/exact_distributions_financial_paper/sections/03_introduction.tex", "max_forks_repo_name": "juanhenao21/exact_distributions_financial", "max_forks_repo_head_hexsha": "02eb058e5f963fbccb9029aae3fb6e15def7a93a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 64.234375, "max_line_length": 188, "alphanum_fraction": 0.8297251277, "num_tokens": 981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3188256822288364}}
{"text": "\\documentclass[a4paper,11pt]{article}\n%\\documentclass[a4\\mfrakpa\\mfrakper,11\\mfrakpt]{scrartcl}\n\n\n\n\\input{../preambles/preamble}\n\\input{../preambles/unicode}\n\n\\setmainlanguage{english}\n\\setotherlanguages{german,greek,russian}\n\n\\input{../preambles/math-single}\n\\input{../preambles/math-brac}\n\\input{../preambles/math-thm}\n\\input{../preambles/phys-chem}\n\n% \\setromanfont[Mappping=tex-text]{Linux Libertine O}\n% \\setsansfont[Mapping=tex-text]{DejaVu Sans}\n% \\setmonofont[Mapping=tex-text]{DejaVu Sans Mono}\n\n\\usepackage[%style=authoryear-icomp,\n\t\t\tbackend=biber]{biblatex}\n\\addbibresource{./cosmo-perturb.bib}\n\n\\title{Cosmological Perturbations}\n\\author{Yi-Fan Wang (王\\ 一帆)}\n%\\date{}\n\n\\begin{document}\n\\maketitle\n\nMost of the conventions and notations in \\cite[ch.~5]{Weinberg2008} will be \nfollowed.\n\nSuppose the metric can be expanded up to the linear \norder as\n\\begin{align}\ng = g^{(0)} + \\epsilon g^{(1)} + \\rfun{\\Omicron}{\\epsilon^2}.\n\\end{align}\nThe background metric $g^{(0)}$ takes the Robertson--Walker form\n\\begin{align}\ng^{(0)}_{\\mu\\nu}\\,\\dd x^\\mu\\,\\dd x^\\nu =\n-\\rfun{N^2}{t}\\,\\dd t^2 + \\rfun{a^2}{t}\\,\\dd \\Omega_\\text{3F}^2,\n\\end{align}\nin which $\\dd\\Omega_\\text{3F}^2 =\n\\dd\\chi^2 + \\chi^2\\rbr{\\dd\\theta^2 + \\sin^2\\theta\\,\\dd \\phi^2}$ is the \ndimensionless flat spatial metric.\nThe linear perturbation can be decomposed into scalar, vector and \ntensor parts\n\\begin{align}\ng^{(1)}_{00} &= -E, \\\\\ng^{(1)}_{i0} = g^{(1)}_{i0} &= F_{,i}+G_i, \\\\\ng^{(1)}_{ij} &= A \\delta_{ij} + B_{,i,j}+C_{i,j}+C_{j,i}+D_{ij}.\n\\end{align}\n\nHere one has some weird condition, where the contractions do not follow the \none-up-one-down tradition\n\\begin{align}\nC_{i,i} = G_{i,i} = 0,\n\\quad\nD_{ij,i} = 0,\n\\quad\nD_{ii} = 0.\n\\end{align}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Metric perturbation under diffeomorphism}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nConsider a diffeomorphism generated by $\\xi^\\mu$\n\\begin{align}\nx^\\mu \\to \\overline{x}^\\mu = x^\\mu - \\epsilon \\xi^\\mu.\n\\end{align}\nThe generator $\\xi^\\mu$ can in turn be decomposed into $\\xi_0 = \\zeta$, \n$\\xi_i \n= \\xi^\\text{S}_{,i} + \\xi^\\text{V}_{i}$.\n\nOne has here again some weird condition, where the contractions do not follow \nthe one-up-one-down tradition\n\\begin{align}\n\\xi^\\text{V}_{i,i} = 0.\n\\end{align}\n\nThe Lie derivative of the metric $\\BbbL_{\\xi} g$ is\n\\begin{align}\n\\rbr{\\BbbL_{\\xi} g}_{\\mu\\nu} =\n\\xi^\\lambda g_{\\mu\\nu,\\lambda} + \n\\xi^{\\lambda}{}_{,\\mu} g_{\\lambda\\nu} +\n\\xi^{\\lambda}{}_{,\\nu} g_{\\mu\\lambda}.\n\\end{align}\nIn components and expansion, these are\n\\begin{align}\n\\rbr{\\BbbL_{\\xi} g}_{00} &=\n2\\dot\\zeta - 2\\zeta \\frac{\\dot{N}}{N} + \\rfun{\\Omicron}{\\epsilon}, \\\\\n\\rbr{\\BbbL_{\\xi} g}_{i0} = \\rbr{\\BbbL_{\\xi} g}_{0i} &=\n\\rbr{\\zeta-2\\frac{\\dot{a}}{a}\\xi^\\text{S}+\\dot{\\xi}^\\text{S}}_{,i} +\n\\rbr{-2\\frac{\\dot{a}}{a}\\xi^\\text{V}_{i}+\\dot{\\xi}^\\text{V}_{i}}\n+ \\rfun{\\Omicron}{\\epsilon}, \\\\\n\\rbr{\\BbbL_{\\xi} g}_{ji} = \\rbr{\\BbbL_{\\xi} g}_{ij} &=\n-\\frac{2a\\dot{a}}{N^2} \\zeta \\delta_{ij} + 2\\xi^\\text{S}_{,i,j}\n+ \\xi^\\text{V}_{i,j} + \\xi^\\text{V}_{j,i} + \\rfun{\\Omicron}{\\epsilon}.\n\\end{align}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Scalar perturbations}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\begin{align}\n-N^2 - \\epsilon E + \\rfun{\\Omicron}{\\epsilon^2} \\to\n-N^2 - \\epsilon E + \\epsilon\\rbr{2\\dot\\zeta - \n2\\zeta\\frac{\\dot{N}}{N}}\n+ \\rfun{\\Omicron}{\\epsilon^2},\n\\end{align}\nso one can write\n\\begin{align}\n\\BbbL_\\xi E = -2 \\dot{\\zeta} + 2 \\zeta \\frac{\\dot{N}}{N}.\n\\end{align}\nSimilarly one can read-off\n\\begin{align}\n\\BbbL_\\xi F &= \\zeta - 2\\frac{\\dot{a}}{a}\\xi^\\text{S} + \\dot{\\xi}^\\text{S}, \\\\\n\\BbbL_\\xi A &= -\\frac{2a\\dot{a}}{N^2}\\zeta, \\\\\n\\BbbL_\\xi B &= 2\\xi^\\text{S}.\n\\end{align}\n\nThe four scalar perturbations are generated by $\\zeta$ and $\\xi^\\text{S}$, \nso that only two independent perturbations exists. It is clear that\n\\begin{align}\n\\BbbL_\\xi\\rbr{\\frac{F}{a}-\\frde{}{t}\\frac{B}{2a}} = \\frac{\\zeta}{a}.\n\\end{align}\nOne can verify that\n\\begin{align}\n\\BbbL_\\xi\\cbr{\\frac{E}{2N}+\n\\frde{}{t}\\sbr{\\frac{a}{N}\\rbr{\\frac{F}{a}-\\frde{}{t}\\frac{B}{2a}}}} &= 0, \\\\\n\\BbbL_\\xi\\cbr{\\frac{A}{2}+\n\\frac{a^2 \\dot{a}}{N^2}\\rbr{\\frac{F}{a}-\\frde{}{t}\\frac{B}{2a}}} &= 0.\n\\end{align}\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Vector perturbations}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Tensor perturbations}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Scalar field perturbation under diffeomorphism}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n\\printbibliography\n\n\\end{document}\n", "meta": {"hexsha": "4243b52f60e10e0770ff7143443b961bb9ce93d4", "size": 4495, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "cosmo-perturb/cosmo-perturb-old.tex", "max_stars_repo_name": "cmp0xff/Notes", "max_stars_repo_head_hexsha": "afd712c1e42275bf781a030d6c5f1b7f4c6ec57b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cosmo-perturb/cosmo-perturb-old.tex", "max_issues_repo_name": "cmp0xff/Notes", "max_issues_repo_head_hexsha": "afd712c1e42275bf781a030d6c5f1b7f4c6ec57b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cosmo-perturb/cosmo-perturb-old.tex", "max_forks_repo_name": "cmp0xff/Notes", "max_forks_repo_head_hexsha": "afd712c1e42275bf781a030d6c5f1b7f4c6ec57b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.078313253, "max_line_length": 78, "alphanum_fraction": 0.5993325918, "num_tokens": 1726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.6001883592602049, "lm_q1q2_score": 0.31882568222883634}}
{"text": "% Author: Dominik Harmim <harmim6@gmail.com>\n\n\\documentclass[a4paper, 10pt, twocolumn]{article}\n\n\\usepackage[british]{babel}\n\\usepackage[utf8]{inputenc}\n\\usepackage[T1]{fontenc}\n\\usepackage[left=2cm, top=2cm, text={17cm, 25cm}]{geometry}\n\\usepackage[unicode, colorlinks, hypertexnames=false, citecolor=red]{hyperref}\n\\usepackage{times}\n\\usepackage{graphicx}\n\\usepackage{amsmath}\n\n\\setlength{\\parindent}{0pt}\n\\setlength{\\parskip}{.5 \\bigskipamount}\n\n\n\\begin{document}\n    \\twocolumn[\n        \\begin{@twocolumnfalse}\n            \\begin{center}\n                {\\Large\n                    Brno University of Technology \\\\\n                    Faculty of Information Technology \\\\\n                }\n                {\\includegraphics[width=.4 \\linewidth]{img/FIT_logo.pdf}} \\\\\n\n                {\\LARGE\n                    Cryptography \\\\\n                    2.~Project\\,--\\,RSA \\\\[.4cm]\n                }\n\n                {\\large\n                    Dominik Harmim (xharmi00) \\\\\n                    \\texttt{xharmi00@stud.fit.vutbr.cz} \\\\\n                    \\today\n                }\n            \\end{center}\n        \\end{@twocolumnfalse}\n    ]\n\n\n    \\section{Introduction}\n\n    The goal of this project is to implement the RSA algorithm\\,---\\,an\n    asymmetry cryptography algorithm. The program that should be created\n    should be able to generate parameters of the RSA, encrypt and decrypt\n    messages, and break the algorithm using factorisation of the public\n    modulus. The program is implemented in~C++ and it is used arithmetic\n    library GMP\\footnote{Arithmetic library\n    \\textbf{GMP}\\,--\\,\\url{https://gmplib.org}.} for the computation with\n    large numbers. In the following chapters, there are briefly described\n    the methods and algorithms used. Appropriate bibliography and other\n    sources are mentioned as well.\n\n\n    \\section{Encryption and Decryption}\n\n    An encryption and decryption is implemented by~\\cite{pkcrypt}. The\n    private transformation~$ D $~and the public transformation~$ E $~are\n    defined as follows: $ D(c) = m = c^d\\,\\mod n $; $ E(m) = c = m^e\\,\\mod\n    n $, where~$ m $~is a~decrypted message, $ c $~is an encrypted message,\n    $ e $~is the public exponent, $ d $~is the private exponent, and\n    $ n $~is the public modulus.\n\n\n    \\section{RSA Parameters Generation}\n\n    The generation of RSA parameters is implemented according\n    to~\\cite{pkcrypt}. At first, two random prime numbers ($ p $~and~$ q $)\n    are generated and $ n = p \\cdot q $ and $ h = (p - 1) \\cdot (q - 1) $ is\n    computed. Then, it is chosen~$ e $~to be an integer in range\n    $ (2, h - 1) $ with $ GCD(e, h) = 1 $. Further, it is found the\n    multiplicative inverse~$ d $~of~$ e $, modulo~$ h $. Now, $ n $~and~$ e\n    $~are public and~$ d $, $ p $, $ q $, $ h $ are secret.\n\n    The computation of a~greatest common divisor (the $ GCD $ function)\n    is done using the Euclid's algorithm. The computation of a~multiplicative\n    inverse is done using the extended Euclid's algorithm. These algorithms\n    are in detail described in~\\cite{pkcrypt}.\n\n    For the generation of the prime numbers, it is used the probabilistic\n    approach using Solovay-Strassen test with the computation of the\n    Jacobi symbol. These algorithms are explained and demonstrated\n    in~\\cite{pkcrypt, solovay, jacobi}.\n\n\n    \\section{Breaking the Algorithm}\n\n    Breaking of the algorithm is achieved using the factorisation of the\n    public modulus. Once the factorisation is done, one of the secret\n    prime numbers is obtained and the other one is then easily calculated\n    as well as the private exponent. So, the private key is obtained.\n\n    Factorisation of the public modulus is implemented using the\n    Pollard Rho Brent Integer Factorisation, see~\\cite{brent, brentOnline}.\n\n\n    \\section{Conclusion}\n\n    Within this project, the RSA algorithm has been successfully\n    implemented in a~desirable way. It was successfully tested on\n    computer \\texttt{merlin.fit.vutbr.cz}. It was experimentally\n    verified that the program can correctly generate keys for the public\n    modulus up to~4096 bits length and that it can break the algorithm\n    for the public modulus up to~100 bits length quite fast. The program\n    works properly also for longer keys but, as expected, it will take\n    more time.\n\n\n    \\bibliographystyle{englishiso}\n    \\renewcommand{\\refname}{Bibliography}\n    \\bibliography{doc}\n\\end{document}\n", "meta": {"hexsha": "426143241ff23029d632576ce924618517c596a4", "size": 4436, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/doc.tex", "max_stars_repo_name": "harmim/vut-kry-project2", "max_stars_repo_head_hexsha": "cec7b2e628452385663082935424cdd58ea7a574", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/doc.tex", "max_issues_repo_name": "harmim/vut-kry-project2", "max_issues_repo_head_hexsha": "cec7b2e628452385663082935424cdd58ea7a574", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/doc.tex", "max_forks_repo_name": "harmim/vut-kry-project2", "max_forks_repo_head_hexsha": "cec7b2e628452385663082935424cdd58ea7a574", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5739130435, "max_line_length": 78, "alphanum_fraction": 0.665915239, "num_tokens": 1164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.6001883592602049, "lm_q1q2_score": 0.31882568222883634}}
{"text": "\\chapter{Radiometry}\n\nRemote sensing is not just a matter of taking pictures, but also --\nmostly -- a matter of measuring physical values. In order to properly\ndeal with physical magnitudes, the numerical values provided by the\nsensors have to be calibrated. After that, several indices with\nphysical meaning can be computed.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Radiometric Indices}\n\\label{sec:VegetationIndex}\n\\label{sec:RadiometricIndex}\n\n\\subsection{Introduction}\n\nWith multispectral sensors, several indices can be computed, combining several\nspectral bands to show features that are not obvious using only one band.\nIndices can show:\n\\begin{itemize}\n  \\item Vegetation (Tab~\\ref{tab:vegetationindices})\n  \\item Soil (Tab~\\ref{tab:soilindices})\n  \\item Water (Tab~\\ref{tab:waterindices})\n  \\item Built up areas (Tab~\\ref{tab:builtupindices})\n\\end{itemize}\n\nA vegetation index is a quantitative measure used to measure biomass\nor vegetative vigor, usually formed from combinations of several\nspectral bands, whose values are added, divided, or multiplied in\norder to yield a single value that indicates the amount or vigor of\nvegetation.\n\nNumerous indices are available in OTB and are listed in\ntable~\\ref{tab:vegetationindices} to \\ref{tab:builtupindices} with their\nreferences.\n\n\\begin{table}[htb]\n\\centering\n\\begin{tabular}{|c|l|}\n\\hline\nNDVI &  Normalized Difference Vegetation Index \\cite{Rouse1973-NDVI} \\\\\nRVI &  Ratio Vegetation Index \\cite{Pearson1972-RVI}\\\\\nPVI & Perpendicular Vegetation Index \\cite{Richardson1977-PVI,Wiegand1991-PVI}\\\\ \nSAVI & Soil Adjusted Vegetation Index \\cite{Huete1988-SAVI} \\\\\nTSAVI & Transformed Soil Adjusted Vegetation Index \\cite{Baret1989-TSAVI,Baret1991-TSAVI} \\\\\nMSAVI & Modified Soil Adjusted Vegetation Index  \\cite{Qi1994-MSAVI} \\\\\nMSAVI2 & Modified Soil Adjusted Vegetation Index  \\cite{Qi1994-MSAVI} \\\\\nGEMI &   Global Environment Monitoring Index \\cite{Pinty1992-GEMI} \\\\\nWDVI & Weighted Difference Vegetation Index  \\cite{Clevers1988-WDVI,Clevers1991-WDVI} \\\\ \nAVI & Angular Vegetation Index  \\cite{AVI}\\\\\nARVI & Atmospherically Resistant  Vegetation Index \\cite{ARVI} \\\\\nTSARVI & Transformed Soil Adjusted Vegetation Index   \\cite{ARVI} \\\\\nEVI & Enhanced Vegetation Index \\cite{Huete1994-EVI,Justice1998-EVI} \\\\\nIPVI & Infrared Percentage Vegetation Index  \\cite{Crippen1990-IPVI} \\\\\nTNDVI & Transformed NDVI  \\cite{Deering1975-TNDVI} \\\\\n\\hline\n\\end{tabular}\n\\caption{Vegetation indices}\\label{tab:vegetationindices}\n\\end{table}\n\n\\begin{table}[htb]\n\\centering\n\\begin{tabular}{|c|l|}\n\\hline\nIR  & Redness Index  \\cite{Pouget1990-IRIC} \\\\\nIC  & Color Index  \\cite{Pouget1990-IRIC} \\\\\nIB  & Brilliance Index  \\cite{Nicoloyanni1990-IB} \\\\\nIB2 & Brilliance Index  \\cite{Nicoloyanni1990-IB} \\\\\n\\hline\n\\end{tabular}\n\\caption{Soil indices}\\label{tab:soilindices}\n\\end{table}\n\n\\begin{table}[htb]\n\\centering\n\\begin{tabular}{|c|l|}\n\\hline\nSRWI & Simple Ratio Water Index \\cite{ZarcoTejada2001-SRWI} \\\\\nNDWI & Normalized Difference Water Index  \\cite{Gao1996-NDWI} \\\\\nNDWI2 &  Normalized Difference Water Index \\cite{McFeeters1996-NDWI2} \\\\\nMNDWI &  Modified Normalized Difference Water Index  \\cite{Xu2006-MNDWI} \\\\\nNDPI &  Normalized Difference Pond Index \\cite{Lacaux2007-NDTI} \\\\\nNDTI &  Normalized Difference Turbidity Index  \\cite{Lacaux2007-NDTI} \\\\\nSA & Spectral Angle \\\\\n\\hline\n\\end{tabular}\n\\caption{Water indices}\\label{tab:waterindices}\n\\end{table}\n\n\\begin{table}[htb]\n\\centering\n\\begin{tabular}{|c|l|}\n\\hline\nNDBI &  Normalized Difference Built Up Index \\cite{Zha2003-NDBI} \\\\\nISU &  Index Surfaces Built \\cite{Abdellaoui1997-ISU} \\\\\n\\hline\n\\end{tabular}\n\\caption{Built-up indices}\\label{tab:builtupindices}\n\\end{table}\n\n\nThe use of the different indices is very similar, and only few example are\ngiven in the next sections.\n\n\\subsection{NDVI}\n\\label{secNDVI}\nNDVI was one of the most successful of many attempts to simply and\nquickly identify vegetated areas and their {\\em condition}, and it remains\nthe most well-known and used index to detect live green plant canopies\nin multispectral remote sensing data. Once the feasibility to detect\nvegetation had been demonstrated, users tended to also use the NDVI to\nquantify the photosynthetic capacity of plant canopies. This, however,\ncan be a rather more complex undertaking if not done properly.\n\\input{NDVIRAndNIRVegetationIndexImageFilter.tex}\n\n\\subsection{ARVI}\n\\label{secARVI}\n\\input{ARVIMultiChannelRAndBAndNIRVegetationIndexImageFilter.tex}\n\n\\subsection{AVI}\n\\label{secAVI}\n\\input{AVIMultiChannelRAndGAndNIRVegetationIndexImageFilter.tex}\n\n\n\n\n\\section{Atmospheric Corrections}\n\\label{secAtmosphericCorrections}\n\\input{AtmosphericCorrectionSequencement.tex}\n", "meta": {"hexsha": "b506394d623d2c774f584a614e52f91274ab4775", "size": 4714, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Documentation/SoftwareGuide/Latex/Radiometry.tex", "max_stars_repo_name": "xcorail/OTB", "max_stars_repo_head_hexsha": "092a93654c3b5d009e420f450fe9b675f737cdca", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-02-13T14:48:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-03T02:54:28.000Z", "max_issues_repo_path": "Documentation/SoftwareGuide/Latex/Radiometry.tex", "max_issues_repo_name": "xcorail/OTB", "max_issues_repo_head_hexsha": "092a93654c3b5d009e420f450fe9b675f737cdca", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2015-10-14T10:11:38.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-15T08:26:23.000Z", "max_forks_repo_path": "Documentation/SoftwareGuide/Latex/Radiometry.tex", "max_forks_repo_name": "xcorail/OTB", "max_forks_repo_head_hexsha": "092a93654c3b5d009e420f450fe9b675f737cdca", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2015-10-08T12:04:06.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-19T08:00:47.000Z", "avg_line_length": 36.5426356589, "max_line_length": 92, "alphanum_fraction": 0.7681374629, "num_tokens": 1401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.31882567463101913}}
{"text": "\\chapter*{Summary \\& Conclusion}\\addcontentsline{toc}{chapter}{Summary \\& Conclusion}\n\nIn this thesis we have presented a series of works aimed to better understand black hole accretion through numerical simulation.  \\chap{numerics} introduced \\grdisco, a novel moving mesh GRMHD code for simulating disk-like flows.  In \\chap{minidisk} we use \\discogr\\ to study minidisks in accreting binary systems and identify spiral shock waves as a potentially efficient accretion mechanism.  \\chap{scalefit} analyzed GRB afterglow light curves with \\scalefit, producing the first evidence that GRBs are viewed off-axis.\n\nTo further the numerical study of black hole accretion we developed \\grdisco, a new GRMHD extension to the moving-mesh code \\disco\\ \\citep{Duffell16}.  This three dimensional code solves the equations of general relativistic magnetohydrodynamics using sophisticated Riemann solvers and a novel constrained transport algorithm and is efficiently parallelized to run on large computer clusters.  The moving mesh allows the code to take longer time steps while reducing error due to numerical diffusion.  We believe this will be an essential feature for studying the long-term behaviour of realistic accretion disks.  In \\chap{numerics} we present \\discogr 's numerical algorithm and demonstrate its accuracy on a number of test problems.  \\discogr\\ is open source and freely available online\\footnote{\\url{https://github.com/geoffryan/Disco.git}}.\n\nThe first use of \\discogr\\ is a study of minidisks in binary black hole systems, presented in \\chap{minidisk}.  The aim of this work was to better understand the dynamics and observational characteristics of minidisks to better inform global simulations of circumbinary accretion and searches for supermassive binary black hole systems.  We find that spiral shocks, excited in the outer minidisk by tidal forces, can propagate to the minidisk interior and efficiently drive accretion.  This allows minidisks to accrete with an effective $\\alpha$-parameter $\\sim 10^{-2}$ without the need for magnetic fields or other accretion mechanisms.  By ray-tracing through the black hole spacetime we are able to create a synthetic spectrum directly from the radiative losses of the accretion disk.  We find minidisks have a spectrum resembling the standard thin-disk models but with a high energy excess due to shock dissipation near the innermost stable circular orbit.  This mechanism may also be active in x-ray binaries, whose disks are also subject to tidal forces, as well as minidisks.\n\nIn \\chap{scalefit} we change tactics, using numerical simulation to build a model of GRB afterglows with sufficient fidelity to use in data analysis.  Being a relatively well-understood phenomenon, GRB afterglows can potentially be used to learn much about the GRB central engine.  We analyze 226 afterglow x-ray light curves from the \\swiftXRT, about a third of all recorded GRBs from 2005 to 2012.  Our analysis uses high resolution numerical relativistic hydrodynamic simulations to simulate a blast wave propagating in the circumburst medium.  These simulations are fed into a radiative transfer code to calculate a template bank of high fidelity light curves and spectra.  The \\scalefit\\ package, developed for this work, performs Bayesian parameter estimation on afterglow light curves by fitting them to this template bank.  The jet opening angle $\\thO$, the electron spectral index $p$, and for the first time the observer viewing angle $\\thobs$ could be constrained in many bursts.  The distribution of $\\thO$ is highly asymmetric with a median of 0.097 rad. The electron index $p$ has a median value of $2.3$ over the sample, consistent with previous results.  The distribution of $\\thobs$ has a median of $0.57 \\thO$ and only thirteen bursts in the entire sample reported $\\thobs < 0.2 \\thO$.  This provides the first evidence that GRBs are viewed off-axis, lowering inferred total jet energies by up to a factor of four.  This directly impacts the required power of the central engine, thought to be an accreting black hole or rapidly spinning magnetar.\n\n%The development and applications of the methods presented here are ongoing.  The ultimate goal for GR-DISCO is the production of high fidelity, long term simulations of black hole accretion disks.  These simulations, processed through a radiative transfer calculation, could generate a template bank of light curves and spectra.  This would serve as the backbone of a tool like \\scalefit, able to constrain the physical parameters of observed accretion disks from a first principles calculation.\n\nThis dissertation comprises several works aimed to better understand black hole accretion in a variety of contexts.  \\chap{numerics} is primarily methodological, developing a new numerical tool to simulate relativistic accretion disks.  \\chap{minidisk} is a detailed a numerical study of a particular system, the minidisks which form during binary black hole accretion.  This study demonstrates the efficacy of spiral shock waves in driving accretion, an effect relevant for minidisks, x-ray binaries, and possibly binary star formation.  \\chap{scalefit} uses numerical simulations to develop a model useful to data analysis, providing the first constraints of the gamma-ray burst viewing angle.  Presented here, these works provide a step towards a better unified understanding of black hole accretion.\n\n", "meta": {"hexsha": "4aeb1a2a8be1f234cad4ba130292f46cba43e22a", "size": 5413, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "conclusion.tex", "max_stars_repo_name": "geoffryan/thesis", "max_stars_repo_head_hexsha": "cc20180fbc46b92c19ee05f67068183f9ee92aee", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-02-14T15:43:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-14T15:43:00.000Z", "max_issues_repo_path": "conclusion.tex", "max_issues_repo_name": "geoffryan/thesis", "max_issues_repo_head_hexsha": "cc20180fbc46b92c19ee05f67068183f9ee92aee", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "conclusion.tex", "max_forks_repo_name": "geoffryan/thesis", "max_forks_repo_head_hexsha": "cc20180fbc46b92c19ee05f67068183f9ee92aee", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 360.8666666667, "max_line_length": 1565, "alphanum_fraction": 0.8099020876, "num_tokens": 1183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.31874252019756405}}
{"text": "\\documentclass{llncs}\r\n\\usepackage{amsmath}\r\n\\usepackage{amssymb}\r\n\\usepackage{comment}\r\n\\usepackage{hyperref}\r\n\\usepackage{longtable}\r\n\\usepackage{stmaryrd}\r\n\\newcommand{\\interp}[1]{\\llbracket #1 \\rrbracket}\r\n\\newcommand{\\maps}{\\colon}\r\n\\renewcommand{\\:}{\\colon}\r\n\\newcommand{\\FinSet}{\\mathrm{FinSet}}\r\n\\newcommand{\\Set}{\\mathrm{Set}}\r\n\\newcommand{\\Cat}{\\mathrm{Cat}}\r\n\\newcommand{\\Calc}{\\mathrm{Calc}}\r\n\\newcommand{\\Mon}{\\mathrm{Mon}}\r\n\\newcommand{\\BoolAlg}{\\mathrm{BoolAlg}}\r\n\\renewcommand{\\Form}{\\mathrm{Form}}\r\n\\newcommand{\\leftu}{\\mathrm{left}}\r\n\\newcommand{\\rightu}{\\mathrm{right}}\r\n\\newcommand{\\send}{\\mathrm{send}}\r\n\\newcommand{\\recv}{\\mathrm{recv}}\r\n\\newcommand{\\comm}{\\mathrm{comm}}\r\n\\renewcommand{\\quote}[1]{``#1\"}\r\n\\newcommand{\\deref}[1]{\\mathrm{eval}(#1)}\r\n\\newcommand{\\op}{\\mathrm{op}}\r\n\\newcommand{\\NN}{\\mathbb{N}}\r\n\\newcommand{\\pic}{$\\pi$-calculus}\r\n\r\n\\makeatletter\r\n\\gdef\\tshortstack{\\@ifnextchar[\\@tshortstack{\\@tshortstack[c]}}\r\n\\gdef\\@tshortstack[#1]{%\r\n  \\leavevmode\r\n  \\vtop\\bgroup\r\n    \\baselineskip-\\p@\\lineskip 3\\p@\r\n    \\let\\mb@l\\hss\\let\\mb@r\\hss\r\n    \\expandafter\\let\\csname mb@#1\\endcsname\\relax\r\n    \\let\\\\\\@stackcr\r\n    \\@ishortstack}\r\n\\makeatother\r\n\r\n\\title{Logic, resource, and reflection}\r\n\\author{\r\nL.G. Meredith\\inst{2}\\\\\r\n\\and\r\nMichael Stay\\inst{1}\\\\\r\n}\r\n\\institute{\r\n  {Pyrofex Corp.}\\\\\r\n  \\email{\\fontsize{8}{8}\\selectfont stay@pyrofex.net}\\\\\r\n  \\and\r\n  {RChain Cooperative}\\\\\r\n  \\email{\\fontsize{8}{8}\\selectfont lgreg.meredith@rchain.coop}\r\n}\r\n\\begin{document}\r\n\\maketitle\r\n\\begin{abstract}\r\n\\noindent\r\n  We present an algorithm for deriving a spatial-behavioral type\r\n  system and term assignment from a formal presentation of a\r\n  interactive computational calculus. This turns out to identify a\r\n  species of category which we offer an axiomatic characterization of\r\n  interaction categories.\r\n\\end{abstract}\r\n\r\n\\section{Introduction and motivation}\r\n\r\nIn groundbreaking work, Abramsky, Gay, and Nagarajan put forward the\r\nidea of interaction categories to give a categorical framework for\r\ninteractive models of computing. Indeed, interactive models of\r\ncomputation are relatively new and offer distinct insights because\r\nthey include the computational environment as part of the\r\ncomputation. Examples include the {\\pic}, in fact, all the mobile\r\nprocess calculi, as well as the lambda calculus. However, interaction\r\ncategories fail to say axiomatically what interaction is.\r\n\r\nWe put forward a simple, intuitive axiomatic characterization of\r\ninteraction and use this to derive not only a logic but a proof theory\r\nand term assignment algorithm for all systems satisfying these\r\naxioms. The resulting structure identifies a species of category and\r\nwe offer this as an axiomatic characterization of interaction\r\ncategories.\r\n\r\n\\subsection{Intuitions}\r\n\r\nThe key idea in this construction is to use both the evaluation\r\ncontext of Meredith and Stay, and computational reflection, similar to\r\nwhat is found in Meredith and Radestock, to build a proof theory with\r\na cut elimination that corresponds exactly with the notion of\r\ncomputation embodied in any interactive rewrite system.\r\n\r\nThe requirement that the rewrite system is interactive means the left\r\nhand side of every rewrite rule will necessarily be a term\r\nconstructor, say $\\mathsf{K}$, taking at least two terms. That is, when\r\nviewed as a piece of syntax it is at least a tuple of terms. Then, by\r\ncontrolling evaluation with an evaluation context we can force a\r\ndistinction between a tensor and a cut, where the cut forms the redex\r\nwith an evaluation context supplied, and the tensor is denied the\r\nevaluation context, effectively rendering it a data structure. Of\r\ncourse, the data is inaccessible until there is a means to unpack it,\r\nand a par term is constructed as the principal means to extract the\r\ndata from the tensor.\r\n\r\nThe use of the term constructor that forms a redex as a data structure\r\nis the essential use of reflection. The lack of a reduction context\r\ngives us the ability to suspend computation. Having suspended it, we\r\nreify computation as data, and use par to unpack the data making up\r\nthe computation. Completing the circle, the tensor-par cut rule\r\nconstitutes the means to reflect computational data back into actual\r\ncomputations.\r\n\r\nIt turns out that denying the evaluation context is not the only way\r\nto suspend computation. We can also form contexts. In this case, we\r\nonly admit 1-holed contexts, ranged over by $\\chi$. With contexts we can\r\ndefine a notion of rely-guarantee, two notions actually (indicated by\r\nthe operations $(- \\rhd -)$, and $(- \\lhd -)$), as a redex term constructor\r\nmight not be commutative. .\r\n\r\n\\begin{eqnarray*}\r\n\\tau \\rhd_{\\mathsf{K}} \\tau’ & \\triangleq & \\{ u \\quad | \\quad \\exists t. u = \\mathsf{!}\\mathsf{K}[]r(t, []),\\forall u’ : \\tau. (\\exists \\rho : u@u’ \\rightarrow v) \\Rightarrow v:\\tau’ \\} \\\\\r\n\\tau’ \\lhd_{\\mathsf{K}} \\tau & \\triangleq & \\{ t \\quad | \\quad \\exists u. t = \\mathsf{K}[]l([], u)\\mathsf{!},\\forall t’ : \\tau. (\\exists \\rho: t@t’ \\rightarrow v) \\Rightarrow v : \\tau’ \\}\r\n\\end{eqnarray*}\r\n\r\nIn the sequel we drop the subscript on the triangles if it’s understood from\r\ncontext. We use the notation $\\chi @ t$ to mean the term formed by\r\nsubstituting $t$ for hole in $\\chi$. Thus, $\\mathsf{K}(t, [])@u = \\mathsf{K}(t, [])[u/[]] = \\mathsf{K}(t,u)$ and similarly, $\\mathsf{K}([], u)@t = \\mathsf{K}([], u)[t/[]] = \\mathsf{K}(t,u)$\r\n\r\nTo give some examples, the comm rule of rho-calculus is given by\r\n\r\n\\begin{equation*}\r\n  \\mathsf{for}( y \\leftarrow x )P \\quad | \\quad x\\mathsf{!}(Q) \\rightarrow P\\{ @Q/y \\}\r\n\\end{equation*}\r\n\r\nIn this case K is parallel composition, and the revised, resource\r\nconstrained comm rule, looks like\r\n\r\n\\begin{equation*}\r\n  R | \\mathsf{for}( y \\leftarrow x )P \\quad | \\quad x\\mathsf{!}(Q) \\rightarrow P\\{ @Q/y \\}\r\n\\end{equation*}\r\n\r\nIn the lambda calculus, $\\beta$-reduction is given by\r\n\r\n\\begin{equation*}\r\n  (\\lambda x.M)N \\rightarrow M\\{ N/x \\}\r\n\\end{equation*}  \r\n\r\n$\\mathsf{K}$ is application, and the revised, resource constrained $\\beta$-reduction is given by\r\n\r\n\\begin{equation*}\r\n  R((\\lambda x.M)N) \\rightarrow M\\{ N/x \\}\r\n\\end{equation*}    \r\n\r\nIn what follows we will focus on calculi that don’t employ binding\r\noperators and so-called nominal phenomena. This is not to say that we\r\ncan’t handle nominal phenomena, just that the content is already\r\ncomplex enough and we want to focus on the core ideas.\r\n\r\n\r\n\\subsection{Related work}\r\nIn many ways this work is inspired by and derives from domain theory\r\nin logical form (DTLF). In much the same way that DTLF takes as input\r\na notion of computation encoded in a domain theory and produces a\r\nlogical system encoding the same notion of computation, but from the\r\nlogical view, this is an algorithm that takes as input a notion of\r\ncomputation encoded as a Lawvere theory and produces a new Lawvere\r\ntheory that is resource constrained and enjoys a type system that\r\nguarantees a range of security and liveness properties, while at the\r\nsame time having the tightest possible conformance to the original\r\nnotion of computation. In particular, the resulting type theory is\r\nalso a logic enjoying a notion of cut-elimination and proof\r\nnormalization that matches exactly with the operational semantics of\r\nthe original theory. As such, it automatically enjoys a Curry-Howard\r\ncorrespondence.\r\n\r\nOther inspiration and guidance come from the two major branches in the\r\ndevelopment of behavioral types. One branch derives from the spatial\r\nlogics of Caires, et al, while the other derives from the session\r\ntypes of Wadler, et al. The former is predominantly model theory\r\nbased, while the latter is predominantly proof theory based. In the\r\nspatial logics branch the negation is largely set-based, while in the\r\nsession types work the negation is related to the reduction of\r\nterms. This construction brings both branches together and offers both\r\nmodel theory and proof theory that enjoys a full abstraction-like\r\nproperty.\r\n\r\nThe discussion would not be complete without mentioning\r\nblockchain. While the idea of resource limiting computation certainly\r\nhas a long and illustrious history, inspired by catalysts in chemical\r\nand biochemical reactions, it has immediate practical application in\r\nblockchain platforms such as RChain and Ethereum. Here, the\r\nprogramming model is throttled by the existence of a resource. The\r\ncost of obtaining that resource constitutes a prophylactic against\r\ndenial-of-service attacks. Specifically, an attacker attempting to\r\ndeploy computations that run forever or take up infinite storage must\r\npay for the corresponding infinite resources necessary to enable the\r\ninfinite computations.\r\n\r\n\\subsection{Notation}\r\nWe use \r\n\r\n\\begin{itemize}\r\n  \\item $\\Gamma , \\Delta , \\Xi$  to range over type contexts;\r\n  \\item $\\rhd , \\lhd$ for left and right residuation;\r\n  \\item $(-)_{\\perp}$ and $ _{\\perp}(-)$  for left and right negations;\r\n  \\item $!(-)$ and $(-)!$  for left and right abstractions; \r\n  \\item $\\rho$ to range over rewrite rules;\r\n  \\item $\\chi$ to range over contexts;\r\n  \\item $\\bindnasrepma, \\otimes, \\sqcap, \\sqcup$ for logical connectives derived from $K$; $\\sqcap$ serial, $\\otimes$ parallel\r\n  \\item both double and single sided $\\vdash$ for typing judgments;\r\n  \\item $\\Rightarrow$ for meta level logical implication.\r\n\\end{itemize}\r\n\r\n\\section{Construction}\r\nTo illustrate the general construction we apply it to the simplest\r\npossible interactive rewrite theory, consisting of a single sort, $T$,\r\nfor term, a single constant, $C$, and a single term constructor $K$, along\r\nwith left and right identities for $K$ (which are, of course,\r\nconstants). It has a single rewrite rule, $\\rho$.\r\n\r\nWe add a resource, $R$, which can be thought of as either an evaluation\r\ncontext, or as a constant. In the resourced theory, the rewrite rule\r\nonly applies in an evaluation context.\r\n\r\nThen we add a notion of 1-holed context. We add a new sort, $\\chi_{T}$, then a\r\nconstant for the hole, together with left and right maps for placing\r\nthe hole in either side of $K$, along with left and right maps $!(-)$ and\r\n$(-)!$ essentially for treating contexts as abstractions. We add a map\r\n$@(-,-)$ for substituting a term into a context marked as an\r\nabstraction.\r\n\r\nIt is important to note that we do not allow the rewrite rule to\r\noperate on contexts. Thus, there are two ways to suspend computation:\r\nwithholding a resource, or forming an abstraction.  Input to the\r\nalgorithm It is to be understood that the initial theory is provided\r\nas input to the system. As mentioned earlier, this is an algorithm\r\nthat takes as input a notion of computation encoded as a Lawvere\r\ntheory and produces a new Lawvere theory that is resource constrained\r\nand enjoys a type system that guarantees a range of security and\r\nliveness properties.\r\n\r\nWe encode term calculi as Lawvere theories by starting with the theory\r\nof reflexive directed multigraphs:\r\n\r\n\\begin{itemize}\r\n  \\item one sort $T$\r\n  \\item function symbols $s, t: T \\rightarrow T$\r\n  \\item equations $ss = ts = s$, $st = tt = t$\r\n\\end{itemize}\r\n\r\nTo this theory, we add function symbols for each term constructor and\r\nreduction rule.  We also add equations for the source and target of\r\neach reduction rule.  For example, we can model the $\\mathsf{SKI}$ combinator\r\ncalculus by adding\r\n\r\n\\begin{itemize}\r\n  \\item $S, K, I : 1 \\rightarrow T$\r\n  \\item $(- -) : T^{2} \\rightarrow T$\r\n  \\item $\\sigma : T^{3} \\rightarrow T$\r\n  \\item $\\kappa : T^{2} \\rightarrow T$\r\n  \\item $\\iota : T \\rightarrow T$\r\n  \\item $s\\sigma(x, y, z) = (((S x) y) z$\r\n  \\item $t\\sigma(x, y, z) = ((x z) (y z))$\r\n  \\item $s\\kappa(x, y) = ((K x) y)$\r\n  \\item $t\\kappa(x, y) = x$\r\n  \\item $s\\iota(x) = (I x)$\r\n  \\item $t\\iota(x) = x$\r\n\\end{itemize}\r\n\r\nWe'll use the following symbols to talk about a generic term calculus\r\nwith at least one binary term constructor and one rewrite rule that\r\nuses the term constructor as its source.\r\n\r\n\\begin{itemize}\r\n  \\item $C, l_{K}, r_{K} : 1 -> T$\r\n  \\item $K : T^{2} \\rightarrow T$\r\n  \\item $\\rho : T^{2} \\rightarrow T$             %%//( \\x -> M N) → M{N/x}     for( y <- x )P | x!(Q) → P{@Q/y}$\r\n  \\item $K(l_{K}, u) = u$\r\n  \\item $K(t, r_{K}) = t$\r\n  \\item $s(\\rho(t,u)) = K(t, u)$\r\n  \\item $t(\\rho(t,u)) = f(t,u)$\r\n\\end{itemize}\r\n\r\nNote that K may not be commutative, so we ask for either a left\r\nidentity, lK, or a right identity, rK, or if we have both they must\r\ncoincide.\r\n\r\nWe proceed in stages, producing first a resourced version of the\r\ntheory that requires an evaluation context to run the rewrite rule,\r\nthen producing a contextualized version of the theory.\r\n\r\n\\subsubsection{Resourced theory}\r\n\\begin{itemize}\r\n  \\item $C, l_{K}, r_{K} : 1 \\rightarrow T$\r\n  \\item $K : T^{2} \\rightarrow T$\r\n  \\item $R : T \\rightarrow T$\r\n  \\item $\\bindnasrepma_{\\rho} : T^{2} \\rightarrow T$\r\n  \\item $\\sqcup_{\\rho} : T^{2} \\rightarrow T$\r\n  \\item $\\rho : T^{2} \\rightarrow T$             %%//( \\x \\rightarrow M N) → M{N/x}     for( y <- x )P | x!(Q) → P{@Q/y}\r\n  \\item $K(l_{K}, u) = u$\r\n  \\item $K(t, r_{K}) = t$\r\n  \\item $s(\\rho(t,u)) = RK(t, u)$\r\n  \\item $t(\\rho(t,u)) = f(t,u)$                    %%// f can mention R, e.g. if R is not a linear resource\r\n\\end{itemize}\r\n\r\n%% \\subsubsection{Contextualized Resourced theory}\r\n%% We add a new sort, 𝛘T, and the following maps\r\n\r\n%% C, lK, rK : 1 -> T\r\n%% K : T x T -> T\r\n%% [] : 1 -> 𝛘T\r\n%% K[]l : 𝛘T x T -> 𝛘T\r\n%% K[]r : T x 𝛘T -> 𝛘T\r\n%% !(-) : 𝛘T  -> T\r\n%% (-)! : 𝛘T  -> T\r\n%% @ : T x T -> T\r\n%% @[] : 𝛘T x T -> T\r\n%% R : T -> T\r\n%% ⅋ρ : T x T -> T\r\n%% ⊔ρ : T x T -> T\r\n%% ρ : T x T -> T             //( \\x -> M N) -> M{N/x}     for( y <- x )P | x!(Q) -> P{@Q/y}\r\n%% s(ρ(t,u)) = RK(t, u) \r\n%% t(ρ(t,u)) = f(t,u) // f can mention R, e.g. if R is not a linear resource\r\n%% K(lK, u) = u\r\n%% K(t, rK) = t\r\n%% @([]!,t) = t\r\n%% @(![],t) = t\r\n%% @(K[]l (χ, t)!, u) = K(@[(χ[, u), t)\r\n%% @(!K[]r (t, χ), u) = K(t, @[(χ[, u))\r\n\r\n%% As mentioned before, the basic notion of arrow is given by\r\n\r\n%% τ ▷K τ’ ≜ { u | ∃t. u = !K[]r(t, []),∀u’:τ. (∃ ρ: u@u’ → v) ⇒ v:τ’ }\r\n%% τ’ ◁K τ ≜ { t | ∃u. t = K[]l([], u)!,∀t’:τ. (∃ ρ: t@t’ → v) ⇒ v:τ’ } \r\n\r\n%% However, they can be generalized to\r\n\r\n%% τ ▷K τ’ ≜ { u | ∃t,χ. u = !K[]r(t, χ),∀u’:τ. (∃ ρ: u@u’ → v) ⇒ v:τ’ }\r\n%% τ’ ◁K τ ≜ { t | ∃u,χ. t = K[]l(χ, u)!,∀t’:τ. (∃ ρ: t@t’ → v) ⇒ v:τ’ }\r\n\r\n%% which allows the hole to be buried, rather than at the top level,\r\n\r\n%% Types\r\n%% τ ::=  ⊤ | τ ▷ τ | τ ◁ τ | C | {} | τ ∪ τ | Rτ | K(τ,τ) | ρ⊗(τ,τ) | ρ⅋(τ,τ) | ρ⊓(τ,τ) | ρ⊔(τ,τ) \r\n\r\n%% Abbreviations\r\n%% τ⊥ = τ ▷ rK, τ◦ = τ ▷ {}\r\n%% ⊥τ = lK ◁ τ, ◦τ = {} ◁ τ\r\n\r\n\\section{Main theorems}\r\nIn this section, we prove a cut-elimination theorem.\r\n\\subsection{Cut-elimination}\r\nEvery proof that uses a cut can be transformed into a proof that does\r\nnot use a cut.  Compilation from contextualized resource theory back\r\nto original theory. In $lambda$-calculus and {\\pic}, $\\mathsf{K}$ is\r\nnot directly interpreted as application or parallel,\r\nrespectively. Instead, it turns into a data type so we can extract the\r\ninfo using a par term introduced in the contextualized resource\r\ntheory.  In $\\rho$, there's no need because it's reflective.  But either\r\nway, the term calculi are powerful enough to support the embedding of\r\nthe new terms back into the original.\r\n\r\nIt remains to show that the embedding is full and faithful.\r\n\r\n%% Intuitionistic Term assignment\r\n%% Terms, their types and cuts\r\n\r\n%% ———-- constants\r\n%% ⊢ C : C\r\n\r\n%% Γ ⊢ t : τ  Δ ⊢ u : τ’\r\n%% __________________ ρ tensor τ\r\n%% Γ, Δ ⊢ K(t, u) : ρ⊗(τ, τ’)\r\n\r\n%% Γ ⊢ t : τ, u : τ’\r\n%% __________________ ρ par\r\n%% Γ ⊢ ⅋ρ (t, u) : ρ⅋(τ, τ’)\r\n\r\n%% Γ ⊢ ⅋ρ (t’, u’) : ρ⅋(τ⊥, τ’⊥)  Δ ⊢ K(t, u) : ρ⊗(τ, τ’) \r\n%% _____________________________________ ρ par-tensor-cut\r\n%% Γ, Δ ⊢ R(K(K(t’, t), K(u’, u))) : R(rK)\r\n%% τ ▷ τ' = { u | ∃t,χ. u = !K[]r(t, χ),∀u’:τ. (∃ ρ: u@u’ → v) ⇒ v:τ’ }\r\n%% τ⊥ = τ ▷ rK = { u | ∃t,χ. u = !K[]r(t, χ),∀u’:τ. (∃ ρ: u@u’ → v) ⇒ v:rK }\r\n\r\n%% Γ ⊢ t : τ, u : τ’\r\n%% _______________ ρ serialize\r\n%% Γ ⊢ K(t,u) : ρ⊓(τ,τ’)\r\n\r\n%% Γ ⊢ t : τ, u : τ’\r\n%% ______________ ρ deserialize\r\n%% Γ ⊢ ⊔(t,u) : ρ⊔(τ,τ’)\r\n\r\n%% Γ ⊢ ⊔ρ (t, u) : ρ⊔(τ’’ ▷ τ⊥, τ’’)  Δ ⊢ K(t', u') : ρ⊓(τ’ ▷ τ, τ’)\r\n%% -----------------------------------------------------------------------------------  ρ serialize-deserialize-cut\r\n%% Γ, Δ ⊢ R(K(K( t, u), K(t’, u’)) : R(rK)\r\n\r\n\r\n%% Γ ⊢ t’ : τ⊥, Δ ⊢ t : τ\r\n%% ---------------------------- ρ cut is the special case of ρ⊗ with ⅋ρ (rK, rK)\r\n%% Γ, Δ ⊢ R(K(t’,t)) : R(rK)\r\n%% Contexts, their types and cuts\r\n%% Below we identify the formation of each kind of context: tensor-parallel, tensor-serial, par-parallel, and par-serial.\r\n\r\n\r\n%% structure\r\n%% destructure\r\n%% parallel\r\n%% tensor (⊗)\r\n%% par (⅋)\r\n%% serial\r\n%% serialize (⊓)\r\n%% deserialize (⊔)\r\n\r\n%% Axiom\r\n\r\n%% —————— axiom\r\n%% [] : τ ⊢ [] : τ\r\n%% Left and right context formation and cut\r\n\r\n%% Γ, [] : τ  ⊢ χ : τ’\r\n%% --------------------\r\n%% Γ ⊢ χ! : τ’ ◁ τ\r\n\r\n%% Γ, [] : τ  ⊢ χ : τ’\r\n%% -------------------\r\n%% Γ ⊢ !χ : τ ▷ τ’\r\n\r\n%% Γ ⊢ K([],u)! : τ’ ◁ τ,  Δ ⊢ t : τ\r\n%% ------------------------------------- context-cut-left\r\n%% Γ, Δ ⊢ R(K(t,u)) : Rτ’\r\n\r\n\r\n\r\n\r\n%% Γ ⊢ !K(t,[]) : τ ▷ τ’,  Δ ⊢ u : τ\r\n%% -------------------------------------- context-cut-right\r\n%% Γ, Δ ⊢ R(K(t,u)) : Rτ’\r\n%% Classical Term assignment\r\n%% In the classical setting we transform double-sided sequents\r\n\r\n%% —————— axiom\r\n%% [] : τ ⊢ [] : τ\r\n\r\n%% to single sided sequents\r\n\r\n%% —————— axiom\r\n%% ⊢ [] : τ⊥, [] : τ\r\n\r\n%% And the interpretation of “,” is tensor, which is just the K constructor.\r\n\r\n%% K( [] : τ⊥, [] : τ )\r\n\r\n%% Expanding this out and instantiating K to application, we would get\r\n\r\n%% App( [] : τ ▷ lK, [] : τ )\r\n\r\n%% This yields exactly the property we are demanding.\r\n\r\n%% More formally, we adapt the Lawvere theory as follows.\r\n\r\n%% We add new sorts, 𝛘, and 𝛘, 𝛘𝛘, and the following maps\r\n\r\n%% C, lK, rK : 1 -> T\r\n%% K : T x T -> T\r\n%% KA : 1 -> 𝛘𝛘\r\n%% K[][] : 𝛘 x 𝛘 -> 𝛘𝛘\r\n%% K[]l : T x 𝛘𝛘 -> 𝛘𝛘\r\n%% K[]r :  𝛘𝛘 x T ->𝛘𝛘\r\n%% ?(-) : 𝛘𝛘  -> 𝛘\r\n%% (-)? : 𝛘𝛘  -> 𝛘\r\n%% !(-) : 𝛘  -> T\r\n%% (-)! : 𝛘  -> T\r\n%% @ : T x T -> T\r\n%% R : T -> T\r\n%% ⅋ρ : T x T -> T\r\n%% ⊔ρ : T x T -> T\r\n%% ρ : T x T -> T             //( \\x -> M N) -> M{N/x}     for( y <- x )P | x!(Q) -> P{@Q/y}\r\n%% s(ρ(t,u)) = RK(t, u) \r\n%% t(ρ(t,u)) = f(t,u) // f can mention R, e.g. if R is not a linear resource\r\n%% K(lK, u) = u\r\n%% K(t, rK) = t\r\n%% @([]!,t) = t\r\n%% @(![],t) = t\r\n%% @(K[]l (χ, t)!, u) = K(@(χ, u), t)\r\n%% @(!K[]r (t, χ), u) = K(t, @(χ, u))\r\n\r\n%% Terms, their types and cuts\r\n\r\n%% ———- constants\r\n%% ⊢ C : C\r\n\r\n%% ⊢ Γ, t : τ   ⊢ u : τ’, Δ\r\n%% __________________ ρ tensor\r\n%% ⊢ Γ, K(t, u) : ρ⊗(τ, τ’), Δ\r\n\r\n%% ⊢ Γ, t : τ, u : τ’\r\n%% __________________ ρ par\r\n%% ⊢ Γ, ⅋ρ (t, u) : ρ⅋(τ, τ’)\r\n\r\n%% ⊢ Γ, ⅋ρ (t’, u’) : ρ⅋(τ⊥, τ’⊥)  ⊢ K(t, u) : ρ⊗(τ, τ’), Δ\r\n%% _____________________________________ ρ par-tensor-cut\r\n%% ⊢ Γ, R(K(K(t’, t), K(u’, u))) : R(rK), Δ\r\n\r\n%% ⊢ Γ, t : τ, u : τ’\r\n%% _______________ ρ serialize\r\n%% ⊢ Γ, K(t,u) : ρ⊓(τ,τ’)\r\n\r\n%% ⊢ Γ, t : τ, u : τ’\r\n%% ______________ ρ deserialize\r\n%% ⊢ Γ, ⊔(t,u) : ρ⊔(τ,τ’)\r\n\r\n%% ⊢ Γ, ⊔ρ (t, u) : ρ⊔(D ▷ A⊥, u:D)  ⊢ K(t', u') : ρ⊓(C ▷ A, C), Δ \r\n%% -----------------------------------------------------------------------------------  ρ serialize-deserialize-cut\r\n%% ⊢ Γ, R(K(K( t, u), K(t’, u’)) : R(rK), Δ \r\n\r\n%% ⊢Γ,  t’ : τ⊥  ⊢ t : τ, Δ \r\n%% ------------------------------ ρ cut is the special case of ρ⊗ with ⅋ρ (rK, rK)\r\n%% ⊢ Γ, R(K(t’,t)) : R(rK), Δ \r\n%% Contexts, their types and cuts\r\n%% Below we identify the formation of each kind of context: tensor-parallel, tensor-serial, par-parallel, and par-serial.\r\n\r\n\r\n%% structure\r\n%% destructure\r\n%% parallel\r\n%% tensor (⊗)\r\n%% par (⅋)\r\n%% serial\r\n%% serialize (⊓)\r\n%% deserialize (⊔)\r\n\r\n\r\n%% Axiom\r\n\r\n%% —————— axiom\r\n%% ⊢ [] : τ⊥, [] : τ\r\n%% Tensor-parallel-context and cut\r\n\r\n%% ⊢ Γ, [] : τ , χ : τ’\r\n%% ---------------------\r\n%% ⊢ Γ, χ! : τ’ ◁ τ\r\n\r\n%% ⊢ Γ, [] : τ , χ : τ’\r\n%% --------------------\r\n%% ⊢ Γ, !χ : τ ▷ τ’\r\n\r\n%% ⊢ Γ, K([],u)! : τ’ ◁ τ,  ⊢ t : τ, Δ \r\n%% --------------------------------- ρ⊗ context-cut-left\r\n%% ⊢ Γ, R(K(t,u)) : Rτ’, Δ \r\n\r\n%% ⊢ Γ, !K(t,[]) : τ ▷ τ’,  Δ ⊢ u : τ\r\n%% -------------------------------- ρ⊗ context-cut-right\r\n%% ⊢ Γ, R(K(t,u)) : Rτ’, Δ \r\n\r\n%% Examples\r\n%% Applying the algorithm\r\n%% Now that we’ve worked out the type system in general above, we need to redo this example using the refined notation.\r\n\r\n%% Below we give an example of the construction applied to the rho-combinators.\r\n%% Rho combinators\r\n%% Here is a relatively standard SoS presentation of the combinatorial system. \r\n\r\n%% atom\r\n%% P ::= 0 | m(a,b) | d(a, b, c) | k(a) | fw(a, b) | br(a, b) | bl(a, b) | s(a, b, c)\r\n%% process\r\n%% | ∗ a | P|P\r\n\r\n%% nominal\r\n%% a ::= @P\r\n\r\n%% Rewrite rules\r\n%% d(a, b, c) | m(a,d) → m(b,d) | m(c,d)\r\n%% k(a)|m(a,b) → 0\r\n%% fw(a, b)|m(a,c) → m(b,c)\r\n%% br(a, b)|m(a,c) → fw(b,c)\r\n%% bl(a, b)|m(a,c) → fw(c, b)\r\n%% s(a, b, c)|m(a,d) → fw(b, c)\r\n%% ∗(a)|m(a,@P) → P\r\n\r\n%% P → P′   ⇒   P|Q → P′|Q\r\n\r\n%% P ≡ P′    ∧    P′ → Q′    ∧    Q′ ≡ Q    ⇒    P → Q\r\n\r\n%% To interpret this presentation as a multi-sorted Lawvere theory per the input format given above, we start with the Lawvere theory of reflexive directed multigraphs and add new sorts, function symbols, and equations.  The theory of reflexive directed multigraphs has\r\n\r\n%% one sort P\r\n%% function symbols src, trgt: P -> P\r\n%% equations src ○ src = trgt ○ src = src, trgt ○ trgt = src ○ trgt = trgt\r\n\r\n%% We adjoin a sort N for names. We express each of the syntactic generators as function symbols, thus 0 : 1 -> P, m : N x N -> P, @:P -> N, *:N -> P, |:P x P -> P, etc. The base case rewrite rules are given in terms of the src and trgt functions, thus \r\n\r\n%% src( d(a, b, c) | m(a,d) → m(b,d) | m(c,d) ) = d(a, b, c) | m(a,d)\r\n%% trgt( d(a, b, c) | m(a,d) → m(b,d) | m(c,d) ) = m(b,d) | m(c,d)\r\n\r\n%% Note that rewrites do not occur within a name because there is no rule for making src and @ commute with each other.\r\n%% The inference rule P → P′ ⇒ P|Q → P′|Q is encoded as an equation involving src, trgt, and |:\r\n\r\n%% src( P | Q ) = src(P) | src(Q)\r\n%% trgt( P | Q ) = trgt(P) | trgt(Q)\r\n\r\n%% Structural congruence is encoded as equations:\r\n\r\n%% 0 | P = P\r\n%% P | Q = Q | P\r\n%% (P | (Q | R)) = ((P | Q) | R)\r\n%% *@P = P\r\n\r\n%% Given that congruence is equality, the final inference rule is an identity.\r\n%% SKI\r\n%% Below, we give an explicit example of the construction applied to the SKI calculus.\r\n\r\n%% Reduction contexts for tensor vs cut, with idempotent commutative monoids for collection\r\n%% T\r\n\r\n%% S, K, I, {}: 1 -> T\r\n%% R: T -> T\r\n%% (- -), ∪: T x T -> T\r\n%% // Pars & plusses come from LHS with ≥ 2 holes\r\n%% ⅋σ: T x T x T -> T \r\n%% ⅋κ: T x T -> T\r\n%% ⊕σ: T x T x T -> T \r\n%% ⊕κ: T x T -> T\r\n\r\n%% RR = R\r\n%% R(x y) = (Rx y)\r\n%% ∪, {} associative, commutative, unital, idempotent\r\n\r\n%% σ: (((RS x) y) z) ▷ ((Rx z) (y z))\r\n%% κ: ((rK x) y) ▷ Rx\r\n%% ι: (RI x) ▷ Rx\r\n\r\n%% [[-]]: Coll + (Term + Pars) ▷ Coll ○ (Term + Pars)\r\n\r\n%% Types\r\n%% τ ::=  T | τ ▷ τ | S | K | I | {} | Rτ | (τ τ) | τ ∪ τ | σ⅋(τ,τ,τ,τ,τ,τ) | σ⊕(τ,τ,τ) | (kappa versions of ⅋⊕)\r\n\r\n%% We use the abbreviations\r\n%% σ⊗(A,B,C) ≜ (((S A▷B▷C) A▷B) A) \r\n%% σ&(A,B,C,C') ≜ (((S A▷B▷C'▷C) A▷B) A) \r\n\r\n%% Inference rules\r\n\r\n%% Γ ⊢ x: A▷B▷C  Δ ⊢ y: A▷B,  Ξ ⊢ z: A\r\n%% ------------------------------------------------------------------------------- σ tensor\r\n%% Γ, Δ, Ξ ⊢ (((S x) y) z): σ⊗(A,B,C)\r\n\r\n%% Γ ⊢ x: A⇒D⇒E⇒F, y: B⇒D⇒E, z: C⇒D\r\n%% --------------------------------------------------------- σ par\r\n%% Γ ⊢ ⅋σ (x, y, z): σ⅋(A,B,C,D,E,F)\r\n\r\n%% Γ ⊢ ⅋σ (x, y, z): σ⅋(A,B,C,D,E,F)  Δ ⊢ (((S x') y') z'): σ⊗(A,B,C)\r\n%% ----------------------------------------------------------------------------------- σ par-tensor-cut\r\n%% Γ, Δ ⊢ R(((S (x x')) (y y')) (z z')): RF\r\n%% F is the property we'd like to hold at the end.\r\n\r\n\r\n\r\n%% Γ ⊢ x: A▷B▷C'▷C, y: A▷B, z: A\r\n%% ---------------------------------------------- σ with\r\n%% Γ, Δ, Ξ ⊢ (((S x) y) z): σ&(A,B,C',C)\r\n\r\n\r\n%% Γ ⊢ x: A▷B▷C, y: A▷B, z: A\r\n%% ------------------------------------------ σ plus\r\n%% Γ ⊢ ⊕(x, y, z): σ⊕(A,B,C)\r\n\r\n%% Γ ⊢ (((S x) y) z): σ&(A,B,C',C)   Δ ⊢ ⊕(x', y', z'): σ⊕(A',B',C')\r\n%% --------------------------------------------------------------------------------  σ with-plus-cut\r\n%% Γ, Δ ⊢ R((((S x) y) z) (((S x') y') z')): RC\r\n\r\n%% C is the property we'd like to hold at the end.\r\n\r\n\r\n%% Γ ⊢ x: A▷B▷C  Δ ⊢ y: A▷B,  Ξ ⊢ z: A\r\n%% ----------------------------------------------------- σ cut is the special case of σ⊗ with ⅋σ (I, I, I)\r\n%% Γ, Δ, Ξ ⊢ (((RS x) y) z): RC\r\n\r\n%% Some useful properties and their proofs\r\n%% TBD\r\n\r\n  \r\n\r\n\\section{Conclusion and future work}\r\n\r\nThe aim of this construction is to generate a logic and its proof\r\ntheory from a notion of computation expressed as a graph-enriched\r\nLawvere theory. The logic respects both a Curry-Howard correspondence,\r\nas well as realizability. Additionally, it enjoys a cut-elimination\r\nproperty, and proof normalization corresponds precisely to the\r\noperational semantics of the notion of computation provided in the\r\ngraph-enriched Lawvere theory.\r\n\r\nWe have not addressed nominal aspects of rewrite systems such as the\r\n$\\lambda$-calculus or the {\\pic}. We note that there are two very\r\npromising directions. One is captured in Clouston’s work on nominal\r\nLawvere theories. The other is expressed in Fiore’s work on HOAS. It\r\nalso bears mentioning that we can generate the names used by such a\r\nnominal theory using reflection, ala Meredith and Radestock.\r\n\r\nAlso, in the spirit of Meredith and Radestock, we can seek to minimize\r\nrisk taken on in the theory in the form of “outside influences.”\r\n\r\n\r\n\\bibliographystyle{amsplain}\r\n\\bibliography{ladl}\r\n\\end{document}\r\n", "meta": {"hexsha": "6f78f51ab7b785ca95065734fd876be80e21bcb0", "size": 25750, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "AProofTheoryForLADL/ladl.tex", "max_stars_repo_name": "rchain/pi4u", "max_stars_repo_head_hexsha": "f866e87eb2855565b28adc5eb6deb2a0ec1cc83b", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-06-07T15:29:17.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-07T15:29:17.000Z", "max_issues_repo_path": "AProofTheoryForLADL/main.tex", "max_issues_repo_name": "rchain/pi4u", "max_issues_repo_head_hexsha": "f866e87eb2855565b28adc5eb6deb2a0ec1cc83b", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2018-07-06T19:01:06.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-19T22:39:58.000Z", "max_forks_repo_path": "AProofTheoryForLADL/main.tex", "max_forks_repo_name": "rchain/pi4u", "max_forks_repo_head_hexsha": "f866e87eb2855565b28adc5eb6deb2a0ec1cc83b", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-08-07T18:14:57.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-03T10:42:15.000Z", "avg_line_length": 36.524822695, "max_line_length": 270, "alphanum_fraction": 0.5950679612, "num_tokens": 8500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.4493926344647596, "lm_q1q2_score": 0.3186279819438283}}
{"text": "The \\eslmod{random} module contains routines for generating uniformly\ndistributed pseudorandom numbers and sampling random deviates from\ndistributions. The heart of the module is the \\ccode{esl\\_random()}\npseudorandom number generator.\n\nThe \\ccode{esl\\_random()} random number generator is portable,\nreentrant, and threadsafe. It gives reproducible results on all\nplatforms.\n\nThe default \\ccode{esl\\_random()} generator implements the Mersenne\nTwister algorithm MT19937 \\citep{Matsumoto98}. MT19937 has strong\nproperties, including a period of $2^{19937}-1$ and equidistribution\nover $2^{32}$ values. The default Mersenne Twister should be suitable\nfor all but a few speed-critical applications.\n\nAlternatively, a simple and classic linear congruential generator\n(LCG) can be chosen \\citep{Knu-81a}. The LCG is much faster to\ninitialize (about 20x) and somewhat faster to generate samples (about\n25\\%), while still generating pseudorandom numbers suitable for most\napplications. Because of its initialization speed, the LCG is\nadvantageous when a small number of reasonably random samples is\nneeded in a speed-critical application. However, it has a relatively\nshort period ($2^32$), making it unsuitable for large simulations.\n\nA new generator can either be seeded with a number that you provide,\nor using an arbitrary (quasirandom) seed. If you seed it yourself, you\ncan guarantee reproducibility: two generators seeded with the same\nseed will give exactly the same sequence, even on different hardware\nplatforms and operating systems. If you let it seed itself\narbitrarily, you will get different sequences. Multiple instances of\nrunning the same program will get quite different arbitrary seeds even\nif you start them at the same time.\n\nBit streams from \\ccode{esl\\_random()}'s two generators were tested\nagainst a National Institute of Standards and Technology statistical\nbenchmark for random number generators \\citep{NIST08}.  The default\nMersenne Twister passes the benchmark suite as expected\n\\citep{Matsumoto98}. The fast LCG passes most but not all of the NIST\ntests.\n\n\\ccode{esl\\_random()} returns a double-precision floating point sample\non the interval $0.0 \\leq x < 1$. \n\nTable~\\ref{tbl:random_api} lists the functions in the \\eslmod{random}\nAPI. The module implements one object, \\ccode{ESL\\_RANDOMNESS}, which\ncontains state information for the random number generator.  This\nmakes random number generation reentrant and threadsafe. You can have\nmore than one active generator and they will not interfere with each\nother. The object is meant to be opaque; you should not need to use\nits contents.  \n\n\n\n\n% Table generated by autodoc -t esl_random.c (so don't edit here, edit esl_random.c:)\n\\begin{table}[hbp]\n\\begin{center}\n{\\small\n\\begin{tabular}{|ll|}\\hline\n\\apisubhead{The \\ccode{ESL\\_RANDOMNESS} object.}\\\\\n\\hyperlink{func:esl_randomness_Create()}{\\ccode{esl\\_randomness\\_Create()}} & Create an RNG with a given seed.\\\\\n\\hyperlink{func:esl_randomness_CreateFast()}{\\ccode{esl\\_randomness\\_CreateFast()}}& Create a fast RNG with a given seed.\\\\\n\\hyperlink{func:esl_randomness_Destroy()}{\\ccode{esl\\_randomness\\_Destroy()}} & Free an RNG.            \\\\\n\\hyperlink{func:esl_randomness_Init()}{\\ccode{esl\\_randomness\\_Init()}} & Reinitialize an RNG.           \\\\\n\\hyperlink{func:esl_randomness_GetSeed()}{\\ccode{esl\\_randomness\\_GetSeed()}} & Returns the value of RNG's seed.\\\\\n\\apisubhead{The generator, \\ccode{esl\\_random()}}\\\\\n\\hyperlink{func:esl_random()}{\\ccode{esl\\_random()}} & Generate a uniform random deviate $0.0 <= x < 1.0$.\n\\\\\n\\apisubhead{Other fundamental sampling (including Gaussian, gamma)}\\\\\n\\hyperlink{func:esl_rnd_UniformPositive()}{\\ccode{esl\\_rnd\\_UniformPositive()}} & Generate a uniform positive random deviate $0 < x < 1$.\\\\\n\\hyperlink{func:esl_rnd_Gaussian()}{\\ccode{esl\\_rnd\\_Gaussian()}} & Generate a Gaussian-distributed sample.\\\\\n\\hyperlink{func:esl_rnd_Gamma()}{\\ccode{esl\\_rnd\\_Gamma()}} & Returns a random deviate from a Gamma(a, 1) distribution.\\\\\n\\apisubhead{Multinomial sampling from discrete probability n-vectors}\\\\\n\\hyperlink{func:esl_rnd_DChoose()}{\\ccode{esl\\_rnd\\_DChoose()}} & Return random choice from discrete multinomial distribution.\n\\\\\n\\hline\n\\end{tabular}\n}\n\\end{center}\n\\caption{The \\eslmod{random} API.}\n\\label{tbl:random_api}\n\\end{table}\n\n\\subsection{Example of using random}\n\nFigure~\\ref{fig:random_example} shows a program that initializes the\nrandom number generator with a seed you provide on the command line,\nthen samples 10 random numbers using \\ccode{esl\\_random()}.\n\n\\begin{figure}\n\\input{cexcerpts/random_example}\n\\caption{An example of using the random number generator.}\n\\label{fig:random_example}\n\\end{figure}\n\nWhen a \\ccode{ESL\\_RANDOMNESS} object is created with\n\\ccode{esl\\_randomness\\_Create()}, it needs to be given a \\emph{seed},\nan integer $\\geq 0$, which specifies the initial state of the\ngenerator. After a generator is seeded, it is typically never seeded\nagain. A series of \\ccode{esl\\_random()} calls generates a\npseudorandom number sequence from that starting point. If you create\ntwo \\ccode{ESL\\_RANDOMNESS} objects seeded identically, they are\nguaranteed to generate the same random number sequence on all\nplatforms. This makes it possible to reproduce stochastic simulations.\nThus, if you run the example multiple times, you get the same ten\nnumbers, because the generator is always seeded with 42.\n\nOften one wants different runs to generate different random number\nsequences, which creates a chicken and the egg problem: how can we\nselect a pseudorandom seed for the pseudorandom number generator?\nCalling \\ccode{esl\\_randomness\\_Create(0)} (i.e., a seed argument of\n0) causes Easel to select an arbitrary seed. The arbitrary seed is\nconstructed by a combination of the current wall clock time (in\nseconds), the elapsed cpu time since starting the program (in\nmilliseconds or microseconds), and (if available) the process\nid.\\footnote{Specifically, by a bitwise mixing function that combines\n  input from \\ccode{time()}, \\ccode{clock()}, and \\ccode{getpid()}. On\n  some platforms, \\ccode{getpid()} is not available, and an arbitrary\n  constant is used instead; on those platforms, arbitrary seeds are a\n  little less arbitrary, but are still quite randomly distributed.  It\n  is improbable to get two generators with the same arbitrary seed; to\n  try, you would have to start two generators in the same process at\n  the same time.} Two different \\ccode{ESL\\_RANDOMNESS} objects\ncreated this way are expected to always produce different pseudorandom\nnumber sequences.\n\n\n", "meta": {"hexsha": "f73c78c1b43ddb5ada8d273e309a8d1830f00dc2", "size": 6569, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "hmmer-3.3/easel/esl_random.tex", "max_stars_repo_name": "WooMichael/Project_Mendel", "max_stars_repo_head_hexsha": "ff572f7ce7f9beca148f7351cf34dbf11d670bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hmmer-3.3/easel/esl_random.tex", "max_issues_repo_name": "WooMichael/Project_Mendel", "max_issues_repo_head_hexsha": "ff572f7ce7f9beca148f7351cf34dbf11d670bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hmmer-3.3/easel/esl_random.tex", "max_forks_repo_name": "WooMichael/Project_Mendel", "max_forks_repo_head_hexsha": "ff572f7ce7f9beca148f7351cf34dbf11d670bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.3203125, "max_line_length": 139, "alphanum_fraction": 0.7812452428, "num_tokens": 1735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.31852277552903857}}
{"text": "\\documentclass[aps,showpacs,twocolumn,\nprd,superscriptaddress,nofootinbib]{revtex4-1}\n\n\\usepackage{amsmath}\n\\usepackage{amsfonts}\n\\usepackage{amssymb}\n\\usepackage{latexsym}\n\\usepackage{graphicx}\n\\usepackage{bm}\n\\usepackage{color}\n\\usepackage{enumerate}\n\\usepackage{tabularx}\n\\usepackage{braket}\n\n\\usepackage{graphicx}\n\\usepackage[caption=false]{subfig}\n%\\usepackage{caption}\n%\\usepackage{subcaption}\n%\\captionsetup{compatibility=false}\n\n\\usepackage{color}\n\\usepackage[usenames,dvipsnames,svgnames,table]{xcolor}\n%\\usepackage[colorlinks=true,\n%            linkcolor=green,\n%            urlcolor=blue,\n%            citecolor=red]{hyperref}\n\\usepackage[colorlinks=true,\n            linkcolor=YellowOrange,\n            urlcolor=RoyalBlue,\n            citecolor=RedViolet]{hyperref}\n\n%\\usepackage{showlabels}\n\n\\newcommand{\\be}{\\begin{equation}}\n\\newcommand{\\ee}{\\end{equation}}\n\\newcommand\\ud{{\\mathrm{d}}}\n\\newcommand\\uD{{\\mathrm{D}}}\n\\newcommand\\calO{{\\mathcal{O}}}\n\\newcommand\\calM{{\\mathcal{M}}}\n\\newcommand\\calF{{\\mathcal{F}}}\n\\newcommand\\calT{{\\mathcal{T}}}\n\\newcommand\\calD{{\\mathcal{D}}}\n\\newcommand\\calA{{\\mathcal{A}}}\n\\newcommand\\bfx{\\mathbf{x}}\n\\newcommand{\\ov}[1]{\\overline{#1}}\n\\newcommand{\\ph}[1]{\\phantom{#1}}\n\\newcommand{\\cte}{\\mathrm{cte}}\n\\newcommand{\\nn}{\\nonumber}\n\\newcommand{\\hatk}{k}\n\\newcommand{\\Hz}{\\,\\mathrm{Hz}}\n\\newcommand{\\yr}{\\,\\mathrm{yr}}\n\\newcommand{\\sinc}{\\,\\mathrm{sinc}}\n\\newcommand{\\Msol}{M_{\\odot}}\n\\newcommand{\\Mchirp}{M_{c}}\n\\newcommand{\\tf}{t_{f}}\n\\newcommand{\\Tf}{T_{f}}\n\\newcommand{\\tfd}{t_{f}^{d}}\n\\newcommand{\\tfSPA}{t_{f}^{\\rm SPA}}\n\\newcommand{\\TfSPA}{T_{f}^{\\rm SPA}}\n\n\\newcolumntype{C}[1]{>{\\centering\\arraybackslash}p{#1}}\n\\newcolumntype{L}[1]{>{\\raggedright\\arraybackslash}p{#1}}\n\n\\newcommand{\\SM}[1]{{\\color{Red} #1}}\n\\newcommand{\\jgb}[1]{{\\color{DarkGreen} #1}}\n\n\\begin{document}\n\n\\title{Fourier-domain modulations and delays of gravitational-wave signals}\n\n\\author{Sylvain Marsat}\n\\affiliation{Max Planck Institute for Gravitational Physics (Albert Einstein Institute), Am M\\\"uhlenberg 1, Potsdam-Golm, 14476, Germany}\n\\author{John G. Baker}\n\\affiliation{Gravitational Astrophysics Laboratory, NASA Goddard Space Flight Center, 8800 Greenbelt Rd., Greenbelt, MD 20771, USA}\n\\affiliation{Joint Space-Science Institute, University of Maryland, College Park, MD 20742, USA}\n\n\\date{\\today}\n\n\\begin{abstract}\n\nWe present a Fourier-domain approach to modulations and delays of gravitational wave signals, a problem which arises in two different contexts. For space-based detectors like LISA, the orbital motion of the detector introduces a time-dependency in the response of the detector, consisting of both a modulation and a varying delay. In the context of signals from precessing spinning binary systems, a useful tool for building models of the waveform consists in representing the signal as a time-dependent rotation of a quasi-non-precessing waveform. In both cases, being able to compute transfer functions for these effects directly in the Fourier domain may enable performance gains for data analysis applications by using fast frequency-domain waveforms. Our results generalize previous approaches based on the stationary phase approximation for inspiral signals, extending them by including delays and computing corrections beyond the leading order, while being applicable to the broader class of inspiral-merger-ringdown signals. In the LISA case, we find that a leading-order treatment is accurate for high-mass and low-mass signals that are chirping fast enough, with errors consistently reduced by the corrections we derived. By contrast, low-mass binary black holes, if far away from merger and slowly-chirping, cannot be handled by this formalism and we develop another approach for these systems. In the case of precessing binaries, we explore the merger-ringdown range for a handful of cases, using a simple model for the post-merger precession. We find that deviations from leading order can give large fractional errors, while affecting mainly subdominant modes and giving rise to a limited unfaithfulness in the full waveform. Including higher-order corrections consistently reduces the unfaithfulness, and we further develop an alternative approach to accurately represent post-merger features.\n\n\\end{abstract}\n\n\\pacs{\n04.25.D-, % numerical relativity\n04.70.Bw, % classical black holes\n04.80.Nn, % Gravitational wave detectors and experiments\n95.30.Sf, % relativity and gravitation\n95.55.Ym, % Gravitational radiation detectors\n97.60.Lf  % black holes (astrophysics)\n}\n\n\\maketitle\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Introduction}\n\\label{sec:intro}\n\nWith the unprecedented recent gravitational-wave detections of coalescencing binary black holes and binary neutron stars, announced by the LIGO-Virgo collaboration~\\cite{LIGO-theevent-2016, LIGO-christmasevent-2016, LIGO-O1BBH-2016, LIGO-BNSevent-2017}, gravitational-wave astronomy has entered its observational era. As LIGO prepares for even more sensitive observation runs, and with the recent expansion of the ground-based detectors network with Virgo~\\cite{Virgo} (and eventually also KAGRA~\\cite{KAGRA} and LIGO-India~\\cite{INDIGO}), observations of such compact object coalescences are expected at an ever-increasing rate.\n\nMoreover, the European Space Agency has recently selected the Laser Interferometer Space Antenna (LISA)~\\cite{LISA17} to realize the ``Gravitational Universe'' science theme~\\cite{elisa13} as the 3rd large space mission of its Cosmic Vision program, with a tentative launch around 2034. A technology demonstrator, LISA Pathfinder, has tested with great success some of the key mission technologies~\\cite{LISAPathfinder2016, LISAPathfinder2018}. LISA will be able to detect and characterize, among several important gravitational wave source targets, comparable-mass binary black hole coalescences from cosmological distances over a wide range of masses. These will range from high-redshift observations of supermassive black hole binaries with $M\\sim 10^{7} \\Msol$ down to the observation of LIGO-type sources with $M\\sim 10-100 \\Msol$~\\cite{Sesana16}.\n\nData analysis for gravitational-wave observations of compact binary coalescences require accurate models (or templates) for the signals, both for ensuring efficient detections of signals that may be buried in instrumental noise, and to extract the physical parameters of the source in a subsequent analysis. Bayesian analysis for parameter estimation of gravitational-wave signals, as was performed for the LIGO detections~\\cite{LIGO-theeventPE-2016,LIGO-O1BBH-2016}, may require millions of evaluations of the likelihood function to sample the posterior probability distribution. The greater sensitivity of LISA and other future instruments will require further increases in the accuracy and computational efficiency of signal templates.\n\nThe GW community is making progress assembling higher-fidelity tools for these coming challenges. State-of-the-art IMR templates combine information from the perturbative results of post-Newtonian (PN) theory covering the inspiral (see e.g.~\\cite{BlanchetLiving}) and from numerical relativity (NR) simulations covering the end of the inspiral and the merger-ringdown phase (see e.g.~\\cite{Pfeiffer12}).  Approaches to template construction include phenomenological templates postulating an analytic ansatz for the Fourier-domain amplitude and phase~\\cite{Husa+15, Khan+15,Hannam+13}, and the Effective-One-Body (EOB) approach~\\cite{BD99,Taracchini+13, Pan+13, Bohe+16} incorporating PN and NR information. Where needed, Reduced Order Models (ROM), also called surrogate models, have been developed to considerably speed up waveform generation, without losing accuracy~\\cite{Field+13, Puerrer14, Blackman+17a}. Put together, these tools provide efficient non-precessing IMR Fourier-domain waveforms, while recent progress has been made for precessing systems as well~\\cite{Hannam+13, Chatziioannou+17, Blackman+17b}. Importantly for this work, the resulting waveforms can be represented by an amplitude and phase for each mode, with only a few hundred samples~\\cite{Puerrer14}.\n\nA complete representation of spin effects across parameter space in fast IMR templates still remains a frontier of gravitational wave signal modelling. In presence of misaligned spins, the system will endure precession of the orbital plane as it evolves, leading to modulations of the signal as seen by the observer~\\cite{Apostolatos+94, Kidder95}. The presence of six degrees of freedom for the spins increases the dimensionality of the problem.\n\nA promising approach to modeling the effect of precession on the emitted waveform, as proposed in~\\cite{BCV03b, BCPTV05, Schmidt+10, OShaughnessy+11, Boyle+11}, is to decompose precessing waveforms by performing a time-dependent rotation, following the precession of the orbital plane. The resulting waveform in the rotated frame can then be modelled by a non-precessing waveform, an approximation which is used both in the construction of the inspiral part of precessing EOB waveforms~\\cite{Pan+13} and in the construction of precessing phenomenological waveforms~\\cite{Hannam+13}. To follow this modelling approach and efficiently create Fourier-domain waveforms, one needs to understand how to translate the time-domain modulations created by the frame rotation into a Fourier-domain transfer function.\n\nBeyond a fast representation of the incident gravitational wave, observational analyses also require transforming the signals through some instrumental response. For short duration mergers such as LIGO  has detected, this can be treated by a simple multiplier and a fixed timeshift between detectors.  For future instruments though, the instrumental response will be more complicated.\n\nWhereas LIGO and Virgo are typically sensitive to chirping binaries for a minute or less, LISA signals may accumulate over months or years. The response of a LISA-type instrument is thus time-dependent~\\cite{Cutler97}. The motion and change of orientation of the detector constellation along its orbit lead to significant time variability in the form of a modulation and a varying delay. These effects then convey information about the localization of the gravitational-wave source in the sky. Direct time-domain implementation of the detector response is straightforward~\\cite{Vallisneri04, Petiteau+08, CR02, RCP04}, but at a high computational cost for parameter-estimation analyses. To leverage the performance of state-of-the-art Fourier-domain IMR templates~\\cite{BTB16,Khan+15}, we must efficiently process the signals through the time-dependent response of the dectector while staying in the Fourier domain.\n\nThe purpose of this paper is to introduce a formalism for efficiently processing signals through a time-domain modulation and delay within the Fourier domain, while retaining the compactness of a Fourier-domain amplitude and phase representation of the signals. This will allow us to address both the issue of the Fourier-domain response of the LISA instrument, as well as the issue of Fourier-domain precession modulation for IMR signals from precessing binaries.\n\nIn previous works focused on gravitational-wave inspirals, the Stationary Phase Approximation (SPA) (see e.g.~\\cite{Thorne300, CF94}) has been often used for this purpose. While the SPA is a common approximation to compute the Fourier transform of non-precessing signals during the inspiraling phase, it is not applicable for IMR waveforms.\n\nIn the case of precessing binaries, applying the SPA directly to the modulated signal is prone to pathologies. In Refs.~\\cite{KCY13,KCY14}, a formalism (called shifted uniform asymptotics or SUA) was introduced to go beyond the SPA and compute more accurately the modulation in the Fourier domain; however, this formalism still relies on the SPA for the underlying precessing-frame signal, and is as such limited to inspiraling signals. The simplified treatment of the precession response in the phenomenological waveforms of Ref.~\\cite{Hannam+13} takes another approach, treating the precession modulation in the frequency domain by directly associating the Fourier frequency with the post-Newtonain orbital frequency. As we will explain, this corresponds to the zeroth-order approximation of the SUA.\n\nIn the case of the LISA response, the SPA provides a natural map from time-domain (for the orbit) to Fourier-domain (for the signal)~\\cite{Cutler97}, and was used by many previous studies with inspiral waveforms. Ref.~\\cite{Klein+15} included the orbital motion of the detector in the SUA treatment of precessing inspiral signals, within a low-frequency approximation of the constellation response. Consistently extending these previous approaches to the merger-ringdown part of the signals, while including the delays in the full LISA response at all frequencies, assessing and understanding the errors made along the way, is part of the objectives of this paper.\n\nWe seek to overcome two limitations in such previous approaches.  The first is that  SPA-based methods are not applicable to IMR waveforms. Second, there is often no clear way to improve the accuracy of these methods beyond the intuitive leading order treatment in order to meet the high-accuracy needs of future detectors. Our approach exploits separation of time-scales approximations, based on a general treatment directly in the Fourier domain of slowly varying delays and amplitude modulations for chirping waveforms.\n\nThe plan of the paper is as follows. In Sec.~\\ref{sec:motivation}, we provide a general presentation of the problem of Fourier-domain modulation and introduce the relevant timescales for both the response of LISA-type detectors and the modulation of precessing signals. In Sec.~\\ref{sec:formalism}, we present our general formalism, give its leading order approximation as well as higher-order corrections, introduce new timescales based on the Fourier-domain signal, and refine the previous results for both the quadratic-in-phase corrections and the treatment of the delays. We then apply our formalism to the response of the LISA detector in Sec.~\\ref{sec:LISA}, and to the case of signals from precessing binaries in Sec~\\ref{sec:precession}. We discuss and summarize our results in Sec.~\\ref{sec:discussion}.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{GW signals in the frequency domain}\n\\label{sec:motivation}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nIn our presentation, we will consider a formal signal processing problem encompassing the challenges posed by both the LISA response and the precession modulations. Given a signal $h(t)$, we apply a time-varying delay $d(t)$ to the waveform followed by a multiplicative modulation function $F(t)$,\n\\be\n\\label{eq:delay-mod-defs}\n\th_{d}(t) = h(t+d(t)) \\,, \\quad s(t) = F(t)h_{d}(t) \\,.\n\\ee\nWe then seek an efficient way to compute the Fourier transform $\\tilde{s}(f)$, expressed by means of a Fourier-domain transfer function $\\calT$ such that\n\\be\\label{eq:deftransfer}\n\t\\tilde{s}(f) \\equiv \\calT(f) \\tilde{h}(f) \\,.\n\\ee\n\nAs is well known, GW signals decomposed in spin-weighted spherical harmonic components are smoothly varying functions of frequency in amplitude/phase form. An important consequence is that these signal components can be accurately represented in terms of a relatively coarsely sampled frequency grid. This property will also extend to the transfer functions, allowing one to keep a compact representation of the full signals. (See Appendix~\\ref{app:notation} for details of our notation and conventions for Fourier transforms and spherical harmonics.)\n\nIn the case of precessing binaries, the delays will be absent and the modulation functions will be the time-dependent Wigner coefficients applied to rotate the waveform from a precessing orbital frame, in which waveform modes exhibit smooth amplitude and phase variation, to an inertial frame where the observations take place. In the case of a LISA-type detector, the signal $h(t)$ will simply be the waveform in a fixed heliocentric frame, and the delays will come from the motion of each detector against the wave front, while the modulation will represent the time-variation in the detector orientation.\n\nIn full generality computing the transfer function $\\calT(f)$ would require a convolution, a costly (discretized) integral over the full frequency domain for each value of $f$. For our context though, there are some properties of $h(t)$, $d(t)$ and $F(t)$ which we can exploit for a more efficient computation. In particular, we will be able to exploit the separation of the different timescales in the problem.\n\nFirst, the gravitational waveforms present a clear separation between the timescales of orbital motion and radiation-reaction. This leads to a general feature of GW signals from compact binaries, during the inspiral phase but also for black hole mergers, that the signal is relatively localized in time-frequency. The localization is particularly clear during the inspiral phase, where the SPA (see Sec.~\\ref{subsec:SPA} below) provides an unambiguous time-to-frequency correspondence, however we will find that the applicability of the SPA will not be a limiting factor of our approach.\n\nSecond, the delay and modulation functions we consider are much more slowly varying than the GW signal. The relevant timescales are either the precession timescale for precessing binaries or the fixed annual-orbital motion timescale for the LISA response. This means that the modulation and delay have relatively compact support in the Fourier domain, hence the convolution with the signal will be localized in frequency, which justifies writing its output as a transfer function as in~\\eqref{eq:deftransfer}.\n\nTogether, these observations lead us to expect that, for a given $f$, only a limited range of times should be relevant in $d(t)$ and $F(t)$ so that we may expect to find a treatment for the transfer function that would be local in time for the modulation and delay. This general idea has already been applied for inspiral signals in the limit of an extremely slowly varying $d(t)$ and $F(t)$, where intuitively we should be able to simply evaluate them at the time given by the time-to-frequency correspondence of the SPA.\n\nFurthermore, a natural quantitative criterion for the applicability of this idea is given by the comparison of the radiation-reaction timescale of the signal with the modulation timescale. In other words, the change in frequency of the signal over a characteristic time of the modulation should be large for the separation of timescales to work. However, as we will see below, for this problem the dimensional analysis falls short of the full picture: the separation of timescales can be affected by frequency-dependent dimensionless factors in presence of delays.\n\nOur objective is to find an approximate treatment for $\\calT(f)$ which allows us to exploit these properties without relying on unnecessary limiting assumptions for the signal (like the limitation of the SPA to inspiral signals), which is extensible to the high-accuracies which will be required by LISA and other future gravitational-wave instruments, while being computationally efficient and widely applicable to GW analysis. In preparation for developing our formalism we first review the salient features of our application problems.\n\n\\subsection{Instrumental modulations and delays for LISA-type detectors}\n\\label{subsec:modulationLISA}\n\nThe response of a detector of the LISA type to an incident gravitational wave can be written in two different, equivalent forms, in terms of phase or frequency measurements. Here we will work with the second representation, which will prove more convenient for our purposes. Moreover, various notation and conventions have been used in the literature to label the spacecraft and describe their orbits. We refer the reader to~\\cite{Vallisneri04} for a comparative account on these various conventions. In this work, we will keep close to the conventions of~\\cite{Vallisneri04}, which were also used in the Mock LISA Data Challenges (MLDC)~\\cite{MLDC4}.\n\nWe use a coordinate system centered on the solar system barycenter (SSB), and represent the center of the constellation by the vector $p_{0}$. We introduce the notation $\\hatk$ for the propagation vector of the gravitational wave, which we denote by $h_{ij}^{\\rm TT}(t)$ in transverse-traceless matrix form, as measured at the SSB (thus, at position $p$, $h_{ij}^{\\rm TT}(t, p) = h_{ij}^{\\rm TT}(t - \\hatk \\cdot p)$). We denote by $p_{A}$ ($A=1,2,3$) the position of the individual spacecraft and $n_{l}$ the unit vectors of the three links, with the convention that $n_{3}$ points from 1 to 2.\n\nWritten in terms of the fractional laser frequency shifts between two spacecraft, the elementary response of the detector reads~\\cite{EW75, RCP04, Vallisneri04}\n\\begin{align}\\label{eq:yslr}\n\ty_{slr} &\\equiv \\frac{\\nu_{r} - \\nu_{s}}{\\nu} \\nn\\\\\n\t&= \\frac{1}{2} \\frac{n_{l}^{i}n_{l}^{j}}{1 - \\hatk\\cdot n_{l}} \\left[ h_{ij}^{\\rm TT}(t - L - \\hatk\\cdot p_{s}) - h_{ij}^{\\rm TT}(t - \\hatk\\cdot p_{r}) \\right] \\,.\n\\end{align}\nWe will use a rigid instantaneous model, approximating the geometry of the constellation by a moving equilateral triangle (neglecting the flexing of the arms induced by corrections in the orbits), and evaluating all geometric factors in~\\eqref{eq:yslr} at a single time $t$ (neglecting point-ahead corrections). The additional delay $L$ (we use $c=1$) in the first term represents the light propagation time along the arm between spacecraft $s$ and $r$.\n\nThe first- and second-generation TDI observables are then built as combinations of these basic building blocks, evaluated at delayed times. Since in our rigid approximation these delays will take a simple form in Fourier domain, we will focus in this paper on the $y_{slr}$ observables. Sec.~\\ref{subsec:modelLISA} provides more details on the response of LISA-type detectors and on the approximations that enter the derivation of the basic response~\\eqref{eq:yslr} above.\n\nThe structure of~\\eqref{eq:yslr} is such that one can build the full signal from individual contributions of the form\n\\be\n\ts(t) = F(t) h(t + d(t)) \\,.\n\\ee\nHere, $h(t)$ represents one of the individual modes building the full gravitational wave signal (see Eq.~\\eqref{eq:defmodes}), $d(t)$ represents the time-varying delays of the form $-\\hatk\\cdot p_{A}(t)$, and $F(t)$ incorporates all the relevant geometric prefactors.\n\nFor the LISA response, the functions $F(t)$ and $d(t)$ vary on a timescale of one year, with a frequency $f_{0} = 1/\\mathrm{yr} \\simeq 3.169\\times10^{-8} \\mathrm{Hz}$ (we will also use $\\Omega_{0} = 2\\pi f_{0}$). When neglecting small non-periodic orbital perturbations (such as those caused by the influence of the Earth and of the other planets on the orbits), both $F(t)$ and $d(t)$ are periodic. It will also be useful to separate the delays in two types of terms: the first, $d_{0} = -\\hatk\\cdot p_{0}$, relates the waveform at the SSB to the waveform at the center of the constellation, whereas the second, $d_{L}$, represents the various delays between the spacecraft of the constellation. Concretely, we assume the basic reference design parameters of the LISA mission\\cite{LISA17} recently selected by the European Space Agency(ESA), with orbit radius $R=1\\,\\mathrm{au}$ and armlength $L=2.5\\times10^{6}\\mathrm{km}$, and with $d_{0} \\sim R/c \\simeq 500\\mathrm{s}$ and $d_{L} \\sim L/c \\simeq 8\\mathrm{s}$.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\subsection{Precession modulation for spinning binaries}\n\\label{subsec:modulationPrec}\n\nFor spinning compact objects, angular momentum interactions typically lead to the precession of the orbit~\\cite{Apostolatos+94, Kidder95}, which can have large effects on the waveform. In particular, it breaks the planar symmetry of the gravitational wave emission, causing modulations that are especially important for systems that are observed edge-on.\n\nA number of authors~\\cite{BCV03b, BCPTV05, Schmidt+10, OShaughnessy+11, Boyle+11} have suggested that the effect of the precession can be modeled, to a good approximation, by a time-dependent rotation of a effectively non-precessing waveform. This allows for a modelling approach where one separately models a precessing frame following the evolution of the plane of the orbit, and approximates the waveform in this precessing frame by using a effective non-precessing model. Different prescriptions have been proposed for the construction of a precessing frame from the waveform itself~\\cite{Schmidt+10, OShaughnessy+11, Boyle+11}.\n\nIf $(\\alpha, \\beta, \\gamma)$ are the Euler angles relating the precessing frame to the inertial frame in the $(z,y,z)$ convention, the modes in the inertial frame $h_{\\ell m}^{\\rm I}$ are then related to the modes in the precessing frame $h_{\\ell m}^{\\rm P}$ by~\\cite{Goldberg+67}\n\\be\\label{eq:wignerrotintro}\n\th_{\\ell m}^{\\rm I} = \\sum\\limits_{m=-\\ell}^{\\ell} \\calD^{\\ell *}_{mm'} (\\alpha,\\beta,\\gamma) h_{\\ell m'}^{\\rm P} \\,,\n\\ee\nwhere the $\\calD^{\\ell}_{mm'}$ are Wigner matrices (see App.~\\ref{app:wigner}).\n\nIf we make the assumption that the precessing-frame waveform $h^{\\rm P}$ is approximated by a non-precessing model that provides us with a smooth Fourier-domain amplitude and phase, then the problem reduces to computing the Fourier transform of the signal\n\\be\\label{eq:defmodulationprec}\n\ts(t) = F(t) h(t) \\,,\n\\ee\nwhere the modulation function $F(t)$ is given by a Wigner matrix and depends on time through the Euler angles $(\\alpha, \\beta, \\gamma)(t)$.\n\nIn Eq.~\\eqref{eq:defmodulationprec} above, the modulation function $F$ has time variations on the precessional timescale, which evolves throughout the inspiral. In the limit of low frequencies, we will see in Sec.~\\ref{sec:precession} below that, although the precession and orbital timescales become more and more separated, the decrease in the chirping rate gives raise to a corrective contribution that does not vanish in this limit. We will also explore  the application of our formalism to a precessing-frame decomposition of the waveform extended through the merger and ringdown phase.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\subsection{Stationary phase approximation}\n\\label{subsec:SPA}\n\nAs a preliminary step, we recall here an approximation widely used for similar purposes in treating gravitational waves signals emitted by inspiraling binaries, the Stationary Phase Approximation (thereafter SPA, and also sometimes called the steepest-descent method). It applies in general to chirping signals, and we refer the reader to~\\cite{FC93, CF94} for details. One first writes the time-domain signal in amplitude and phase form as $h(t) = a(t) e^{-2i\\varphi(t)}$, where for gravitational wave signals $\\varphi$ will correspond to the orbital phase, with the orbital frequency being $\\omega = \\dot{\\varphi}$. In order to keep close to the notation used in the gravitational wave literature, we introduced a factor of 2 in the phase of the wave, which is appropriate for the dominant 22 harmonic of the signal. The approximation then applies to signals verifying the conditions\\footnote{Note that the third condition is not always written explicitly, in particular not in Refs.~\\cite{FC93, CF94}. It becomes important if we generalize $a$ to be an envelope function incorporating a modulation.}\n\\be\\label{eq:conditionsSPA}\n\t\\left| \\frac{\\dot{a}/a}{\\omega} \\right| \\ll 1\\,, \\quad \\left|\\frac{\\dot{\\omega}}{\\omega^{2}} \\right| \\ll 1\\,, \\quad \\left| \\frac{(\\dot{a}/a)^{2}}{\\dot{\\omega}} \\right| \\ll 1 \\,.\n\\ee\nSince the integral~\\eqref{eq:defFT} defining the Fourier transform is rapidly oscillatory unless the term $2\\pi f t$ cancels the evolution of $-2\\varphi(t)$, its support is well centered around the point of stationary phase. This determines the time-to-frequency correspondence in the stationary phase approximation, and leads to the definition of this time as an implicit function of frequency by the relation\n\\be\\label{eq:deftfSPA}\n\t\\omega(\\tfSPA) = \\pi  f \\,.\n\\ee\nFor a chirping signal of increasing phase, $\\omega>0$ and $\\dot{\\omega}>0$, there is a unique point of stationary phase, located in the positive frequency range $f>0$. Using the conditions above, one can formally expand the signal around $\\tfSPA$ to quadratic order in time, according to\n\\begin{align}\n\t\\tilde{h}_{\\rm SPA} (f) &\\simeq a(\\tfSPA) \\exp\\left[2i\\pi f \\tfSPA-2i\\varphi(\\tfSPA) \\right] \\nn\\\\\n\t& \\qquad \\cdot \\int \\ud t \\, e^{-i \\dot{\\omega} (\\tfSPA) (t-\\tfSPA)^{2}} \\,.\n\\end{align}\nNote that to be able to treat the amplitude as a constant in the integral above, we used the third condition in~\\eqref{eq:conditionsSPA}. The resulting complex Gaussian integral yields\\footnote{The expressions given here are valid for the dominant mode $h_{22}$ of the waveform. They can be generalized to other modes $h_{\\ell m}$, $m\\neq 0$ with phase $e^{-im\\varphi}$ as follows: $t_{f}^{\\rm SPA}$ is now such that $m\\omega = 2\\pi f$, $A$ acquires a factor $\\sqrt{2/m}$, in $\\Psi$ the term $2\\varphi$ becomes $m\\varphi$.}\n\\begin{subequations}\n\\begin{align}\n\t\\tilde{h}_{\\rm SPA}(f) &= A_{\\rm SPA}(f) e^{-i\\Psi_{\\rm SPA}(f)} \\,, \\\\\n\tA_{\\rm SPA}(f) &= a(\\tfSPA) \\sqrt{\\frac{\\pi}{\\dot{\\omega}(\\tfSPA)}} \\,, \\label{eq:ASPA} \\\\\n\t\\Psi_{\\rm SPA}(f) &= 2\\varphi(\\tfSPA) - 2\\pi f \\tfSPA + \\frac{\\pi}{4} \\,. \\label{eq:PsiSPA}\n\\end{align}\n\\end{subequations}\nRef.~\\cite{Droz+99} evaluated the first correction to this approximation, within the context of post-Newtonian signals, and found that it can be considered as a term of the fifth post-Newtonian order, beyond the accuracy level of our current best models~\\cite{BlanchetLiving}.\n\nTo understand the separation of timescales in the problem, it will be useful to have at hand the leading-order scaling laws for an inspiral (labeled the Newtonian order in the PN language). Although inaccurate for the purpose of waveform modelling, these leading-order estimates will give useful orders of magnitude of the relevant timescales in the inspiral. For a binary with masses $m_{1}, m_{2}$, we define the total mass $M=m_{1}+m_{2}$ and the symmetric mass ratio $\\nu = m_{1}m_{2}/M^{2}$. Introducing a time of coalescence $t_{c}$, the relations between the orbital frequency and phase and the time to coalescence $t_{c} - t$ are then given by\n\\begin{subequations}\\label{eq:omegaphiN}\n\\begin{align}\n\t\\omega(t) &= \\left[ \\frac{256\\nu}{5c^{5}} (GM)^{5/3} (t_{c}-t) \\right]^{-3/8} \\,, \\\\\n\t\\varphi(t) &= -\\left[ \\frac{c^{3}}{5 G M \\nu^{3/5}} (t_{c}-t) \\right]^{5/8} \\,.\n\\end{align}\n\\end{subequations}\nAs for the leading-order time-domain amplitude of the $22$ mode, we have~\\cite{BlanchetLiving}\n\\be\\label{eq:a22N}\n\ta_{22}^{\\rm N} (t) = \\frac{2 G M \\nu v^{2}}{D c^{2}} \\sqrt{\\frac{16 \\pi}{5}} \\,,\n\\ee\nwhere we set $v = (G M\\omega/c^{3})^{1/3}$ and where $D$ is the luminosity distance to the observer. For this Newtonian inspiral, applying the SPA gives for the $22$ mode $\\tilde{h}(f) = A_{\\rm N}(f)e^{-i\\Psi_{\\rm N}(f)}$ with\n\\begin{subequations}\\label{eq:SPAN}\n\\begin{align}\n\tA_{N}(f) &= \\frac{G^{2}M^{2} \\pi}{Dc^{5}} \\sqrt{\\frac{2\\nu}{3}} v^{-7/2}\\,, \\label{eq:ASPAN}\\\\\n\t\\Psi_{\\rm SPA}^{\\rm N}(f) &= \\phi_{0} - 2\\pi f t_{0} - \\frac{3}{128\\nu v^{5}} \\,, \\label{eq:PsiSPAN}\n\\end{align}\n\\end{subequations}\nwhere $v=(G M \\pi f/c^{3})^{1/3}$ according to the SPA correspondence~\\eqref{eq:deftfSPA}, and where $t_{0}, \\phi_{0}$ are constants\\footnote{For modes $h_{\\ell m}$ with $m\\neq 0$, the phase $\\Psi$ acquires a factor $m/2$ and has to be evaluated at $(2/m)^{1/3} v$.}. It is also customary to rewrite the above relations in terms of the chirp mass $\\Mchirp \\equiv M\\nu^{3/5}$, which is the only mass combination characterizing the signal at the leading PN order.\n\nIn this Newtonian, low-frequency limit one can check that each of the combinations \\eqref{eq:conditionsSPA} indeed vanish at $\\calO{(v^5)}$. but as the system approaches merger, these condition are no-longer satisfied. Near and after the merger, the SPA treatment is not applicable. Nonetheless, the SPA has been a useful workhorse in many gravitational analyses involving frequency domain transfer functions of the form~\\eqref{eq:deftransfer}. The usual approach is simply to replace any time dependencies appearing the transfer function using \\eqref{eq:deftfSPA}. We will reference the SPA treatment, as a familiar touchstone, as we develop a more general formalism.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Perturbative Fourier-domain approach to modulations and delays}\n\\label{sec:formalism}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nIn this section we develop a perturbative Fourier-domain formalism for treating time-delays and temporally multiplicative signal transformations, exploiting the separation of timescales in the problem.\n\n\\subsection{Fourier transform of a modulated and delayed signal}\n\\label{subsec:FTgeneral}\n\nWe begin by expression our delay and modulation function definitions in \\eqref{eq:delay-mod-defs} using the Fourier transform (note our unusal convention~\\eqref{eq:defFT}),\n\\begin{align}\nh_{d}(t) & =  h(t+d(t)) \\nonumber\\\\\n&=\\int \\ud f \\, e^{-2i\\pi f (t+d(t))}\\tilde{h}(f) \\,,\n\\end{align}\nand\n\\begin{align}\n  \\tilde{s}(f) &= \\mathrm{FT} \\left[ F h_{d}\\right] (f) \\nn \\\\\n  &= \\int \\ud t \\, e^{2i\\pi f t} F(t)  \\int \\ud f' \\, e^{-2i\\pi f' (t+d(t))}\\tilde{h}(f') \\nn\\\\\n\t&= \\int \\ud f' \\, \\tilde{h}(f-f') \\int \\ud t \\, e^{2i\\pi f' t} e^{-2i\\pi (f-f') d(t)} F(t) \\,.\n\\end{align}\nThe last equation can then be rewritten as a generalized convolution integral with a frequency-dependent Kernel, according to\n\\be\\label{eq:FDkernel}\n\t\\tilde{s}(f) = \\int \\ud f' \\, \\tilde{h}(f-f') \\tilde{G}(f-f',f') \\,,\n\\ee\nwhere we introduced the frequency-dependent function of time $G(f,t)$, and its Fourier transform in the auxiliary frequency $f'$, denoted by $\\tilde{G}(f,f')$, as\n\\begin{subequations}\\label{eq:defG}\n\\begin{align}\n\tG(f,t) &= e^{-2i\\pi f d(t)} F(t) \\,, \\\\\n\t\\tilde{G}(f,f') &= \\int \\ud t \\, e^{2i\\pi f' t} G(f,t) \\,.\n\\end{align}\n\\end{subequations}\nIn the absence of delays $d(t)$, as in the case of precessing binaries, the function $G$ loses its frequency-dependence and becomes a modulation in the form of a function of time $F(t)$, and the result~\\eqref{eq:FDkernel} above reduces to the familiar convolution theorem for the Fourier transform.\n\nA direct computation of the generalized convolution~\\eqref{eq:FDkernel} using~\\eqref{eq:defG} will generally be computationally demanding, but we can exploit the separation of timescales in the problem to seek an accurate but efficient approximation and to compute the transfer function $\\calT(f)$ as in~\\eqref{eq:deftransfer}.\n\nFor example, under appropriate conditions with slowly varying modulations and delays, we can expect that the Fourier transform $\\tilde{G}(f,f')$ should have a compact support, limited to $f' \\in [-f_{\\rm max}, f_{\\rm max}]$ with $f_{\\rm max}$ a maximal frequency for the modulation, roughly the inverse of its characteristic timescale. This makes the convolution integral~\\eqref{eq:FDkernel} localized in frequency, as the waveform is to be evaluated only at frequencies close to $f$. We can then approximate $\\tilde{h}(f-f')$ by $\\tilde{h}(f)$, with a simple Taylor expansion of their difference. Doing so, we will recover at leading order a locality in time: the response is approximately reduced to an evaluation of the modulation and delay at a representative signal-dependent time $\\tf$, which will be equivalent to $\\tfSPA$ for inspiral signals.\n\nNow consider the limitations to this straightforward argument. The first is that we did not yet specify what $f_{\\rm max}$ should be compared with, in order for the approximation to work. As shown in Sec.~\\ref{subsec:SPA}, the Fourier-domain expressions for the amplitude and phases inspiral signals are steep power-laws. We will therefore need a quantitative criterion to ensure $\\tilde{h}(f-f')$ does not vary too much on the range $f'\\in [-f_{\\rm max}, f_{\\rm max}]$. Second, although clear when considering a fixed characteristic timescale for the modulation and delay (like in the LISA case), the above argument does not apply as such to modulations with a varying timescale (like in the case of precessing binaries, where the precession goes faster when arriving at merger). We will show below that what will be relevant is the characteristic timescale at the time $t_{f}$ associated to $f$.\n\nIn presence of delays, the above is also complicated by the additional delay phases in the signal Fourier transform. Depending on the frequency $f$, this can lead $G(f,t)$ to have faster variations than its nominal timescale ($1\\mathrm{yr}$ for LISA). Thus, to assess the validity of our approximations we cannot limit ourselves to comparing the dimensionful timescales at play in the problem. As we will see in Sec.~\\ref{subsec:lisafom}, we must also include in the analysis dimensionless factors of the form $2\\pi f d$.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\subsection{Leading order: the local-in-frequency approximation}\n\\label{subsec:LLP}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=.98\\linewidth]{tf_py.pdf}\n  \\caption{Time-to-frequency correspondence $t_{f}$, as defined directly from the phase of the Fourier-domain signal in~\\eqref{eq:deftf}, in geometric units. We show only the high-frequency part of the signal, corresponding to the merger region. The PhenomD waveforms have been aligned such that the time-domain amplitude (obtained by an IFFT) peaks at $t=0$. The two aligned spins are equal, with components of $0.95$ ($++$, blue), $0$ ($00$, red), and $-0.95$ ($--$, yellow), for mass ratios $q=1$ (full line) and $q=8$ (dashed). The vertical lines shows the time-domain instantaneous frequency at the peak $\\omega^{22}_{\\rm peak}/(2\\pi)$, and the fact that the curves $t_{f}$ do not pass exactly by the crossing with the $t=0$ horizontal line reflects the fact that the link between time-domain frequency and Fourier frequency $f$ is only approximate at merger. Note that $t_{f}$ increases to at most $\\sim 30M$ after the peak, and is not monotonous.}\n  \\label{fig:tf}\n\\end{figure}\n\nAs a first step, we perform a formal leading-order expansion of the signal $\\tilde{h}(f-f')$ around $f$. We use the amplitude/phase decomposition~\\eqref{eq:defAPsi}, treat the Fourier-domain amplitude $A$ as a constant, expand the Fourier-domain phase $\\Psi$ to the first order, and discard the $f'$ dependence in the first argument of $\\tilde{G}(f-f', f')$.\n\nFor the signal, then, we have\n\\be\n\t\\tilde{h}(f-f') \\simeq A(f) \\exp\\left[ -i\\left( \\Psi(f) - f' \\frac{\\ud \\Psi}{\\ud f} \\right) \\right] \\,,\\label{eq:leadingorderwf}\n\\ee\nPlugging this relation into~\\eqref{eq:FDkernel}, we obtain\n\\begin{align}\n\t\\tilde{s}(f) &\\simeq \\tilde{h}(f) \\int \\ud f' \\, \\exp\\left[ i f' \\frac{\\ud \\Psi}{\\ud f} \\right] \\tilde{G}(f,f') \\nn\\\\\n\t&= \\tilde{h}(f) G\\left( f, -\\frac{1}{2\\pi} \\frac{\\ud \\Psi}{\\ud f} \\right) \\,,\\label{eq:leadingorderresponse}\n\\end{align}\nwhich we can think of as a local evaluation of the kernel function $G(f,t)$ at a frequency-dependent effective time\n\\be\\label{eq:deftf}\n\t\\tf \\equiv -\\frac{1}{2\\pi} \\frac{\\ud \\Psi}{\\ud f} \\,.\n\\ee\nIt is worth noting that a shift in time of the time-domain signal will, by virtue of~\\eqref{eq:shifttime}, be appropriately propagated to $t_{f}$. Because of the freedom of adding a linear term to $\\Psi(f)$ by simply shifting the signal in time, no assumption can be made on the smallness of the first derivative of the phase, and this is really a leading order approximation.\n\nThe definition~\\eqref{eq:deftf} is a straightforward generalization of the time-to-frequency correspondence at the heart of the SPA~\\eqref{eq:deftfSPA}. Indeed, using~\\eqref{eq:deftfSPA} one can verify that the derivative of the SPA phase $\\Psi_{\\rm SPA}$~\\eqref{eq:PsiSPA} with respect to $f$ yields back $\\tfSPA$, as\n\\be\\label{eq:tfSPA}\n\t\\tfSPA = -\\frac{1}{2\\pi} \\frac{\\ud \\Psi_{\\rm SPA}}{\\ud f} \\,.\n\\ee\nHowever, $\\tf$ refers only to the Fourier-domain waveform. We do not need to relate the frequency $f$ to a time-domain frequency like the orbital frequency $\\omega$, and the definition is independent of the SPA being valid or not for the underlying signal $\\tilde{h}$.\n\nThe main advantage of the time-of-frequency function~\\eqref{eq:deftf} is that it extends naturally to the merger-ringdown part of the signals. As such, it is used in the PhenomD and PhenomHM waveform models~\\cite{Khan+15, London+17}. Fig.~\\ref{fig:tf} shows the behaviour of the time function $\\tf$ around merger for six example waveforms, for mass ratios $q=1$ and $q=8$ and for aligned spin components $\\chi=0.95,0.,-0.95$. In particular, one should note that $\\tf$ is not monotonically increasing with frequency anymore after reaching in the high-frequency part of the waveform, corresponding to the ringdown. As long as the Fourier phase is differentiable $t_{f}$ is a well-defined function of $f$. While its non-monotonicity would forbid an unambiguous definition of a reciprocal frequency-of-time function $f(t)$, like that in the SPA, no such function will be needed in our treatment.\n\nWith \\eqref{eq:leadingorderresponse} we have brought the modulated and delayed signal in to the form~\\eqref{eq:deftransfer} with transfer function\n\\be\\label{eq:transferlocal}\n\t\\calT_{\\rm local}(f) = G(f, \\tf) = F(t_{f}) e^{-2i\\pi f d(t_{f})}\\,.\n\\ee\nThe interpretation of this approximation is straightforward: the signal is simply multiplied by the response function evaluated at the time $\\tf$, the delay phase becoming the same linear phase contribution as one would have in~\\eqref{eq:shifttime} with a time shift $d(t_{f})$ treated like a constant. The locality in frequency at $f$ for $\\tilde{h}$ translates into a locality in time at $t_{f}$ for $F,d$.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\subsection{Taylor expansion in the Fourier domain}\n\\label{subsec:TaylorFD}\n\nIf the width of the kernel function $G(f-f',f')$ is not quite negligible compared to the scale of significant variations of $\\tilde{h}(f)$ with $f$, it can be useful to extend our approach beyond the leading-order approximation. With the waveform represented in the amplitude and phase form~\\eqref{eq:defAPsi}, the elements of~\\eqref{eq:FDkernel} may be formally Taylor-expanded in the variable $f'$:\n\\begin{subequations}\\label{eq:expandfprime}\n\\begin{align}\n\t\\Psi(f-f') &= \\Psi(f) + 2\\pi f' \\tf + \\sum\\limits_{p\\geq 2} \\frac{(-1)^{p}}{p!} {f'}^{p} \\frac{\\ud^{p} \\Psi}{\\ud f^{p}} \\,, \\label{eq:expandPsi}\\\\\n\tA(f-f') &= A(f)+A(f) \\sum\\limits_{q\\geq 1} \\frac{(-1)^{q}}{q!} {f'}^{q} \\frac{1}{A}\\frac{\\ud^{q} A}{\\ud f^{q}} \\,, \\label{eq:expandA}\\\\\n\t\\tilde{G}(f-f', f') &=\\tilde G(f,f')+ \\sum\\limits_{r\\geq 1} \\frac{(-1)^{r}}{r!} {f'}^{r} \\frac{\\partial^{r} }{\\partial f^{r}}  \\tilde{G}(f,f') \\label{eq:expandG} \\,,\n\\end{align}\n\\end{subequations}\nusing the definition of $t_{f}$ introduced in~\\eqref{eq:deftf}.\n\nThe leading order transfer function~\\eqref{eq:transferlocal} is obtained by leaving off all the terms in the sums.  In the following, we will consider the resulting transfer functions when keeping some of the next few terms in each of these expansions. Notice that we expand $\\tilde{G}(f-f',f')$ in $f'$ only in its first argument, and that we can commute the $f$-derivatives of $G$ with the Fourier transform operation.\n\nWe can also formally expand the exponential of the phase corrections $\\delta \\Psi$ beyond the first two terms in~\\eqref{eq:expandPsi} as\n\\be\n\t\\exp\\left[ -i\\delta\\Psi \\right] = \\sum_{j \\geq 0}\\frac{(-i\\delta\\Psi)^j}{j!} \\,,\n\\label{eq:expandexp}\n\\ee\nto obtain a pure $f'$-expansion. The resulting power series in $f'$ can then be recast as a temporal Taylor series, by applying the formal derivative rule\n\\allowdisplaybreaks\n\\be\n\t\\int \\ud f'\\, {(-2i\\pi f')}^{n} \\frac{\\partial^{m}}{\\partial f^{m}} \\tilde{G}(f,f') e^{-2i\\pi f' \\tf} = \\frac{\\partial^{m} }{\\partial f^{m}} \\frac{\\partial^{n} }{\\partial t^{n}} G (f,\\tf) \\,.\n\\ee\nThe fully expanded result is a rather cumbersome expression with multiple sums, that we will not use directly. Instead, it will be more instructive to separately consider the different expansions in~\\eqref{eq:expandfprime}. Later, in Sec.~\\ref{subsec:executivesummary} we will come back to combining our results together.\n\nWe first consider the effect of the higher-order corrections in~\\eqref{eq:expandPsi}. We will find that the third and higher derivatives of the phase are always negligible for our purposes, and we will ignore them. Keeping only the first term of the sum in~\\eqref{eq:expandPsi}, corresponding to the second derivative of $\\Psi$, with just the leading terms from \\eqref{eq:expandA} and \\eqref{eq:expandG}, and expanding the phase exponential \\eqref{eq:expandexp} so that the result can be cast as a Taylor series in time, we obtain straightforwardly\n\\be\\label{eq:resulttaylorPsi}\n\t\\calT_{\\rm phase}(f) = \\sum\\limits_{p\\geq 0} \\frac{1}{p!} \\left( \\frac{i}{8\\pi^{2}}\\frac{\\ud^{2} \\Psi}{\\ud f^{2}} \\right)^{p} \\left( \\frac{\\partial^{2p} }{\\partial t^{2p}} G \\right)(f, \\tf) \\,.\n\\ee\nThis correction to the transfer function is of particular interest to us. It will be quantitatively dominant over the other ones in most contexts, and it will be shown in Sec.~\\ref{subsec:resumquadphase} that it generalizes the previous approach of~\\cite{KCY14}. This result shows that the transfer function is signal-dependent, not only through the time-to-frequency correspondence $t_{f}$ but also through the second derivative of the phase $\\Psi$.\n\nSimilarly, applying the expansion of the Fourier-domain amplitude~\\eqref{eq:expandA} while preserving only the leading order terms in \\eqref{eq:expandPsi} and \\eqref{eq:expandG} gives\n\\be\\label{eq:resulttaylorA}\n\t\\calT_{\\rm amp}(f) = \\sum\\limits_{p\\geq 0} \\frac{1}{(2i\\pi)^{p}p!} \\frac{1}{A} \\frac{\\ud^{p} A}{\\ud f ^{p}}  \\left( \\frac{\\partial^{p} }{\\partial t^{p}} G \\right)(f,\\tf) \\,.\n\\ee\n\nLastly, expanding only the frequency-dependence of $G$ as in~\\eqref{eq:expandG} yields\n\\be\\label{eq:resulttaylordelay}\n\t\\calT_{\\rm delay}(f) = \\sum\\limits_{p\\geq 0} \\frac{1}{(2i\\pi)^{p}p!} \\left( \\frac{\\partial^{p} }{\\partial f^{p}} \\frac{\\partial^{p} }{\\partial t^{p}} G \\right)(f,\\tf) \\,,\n\\ee\nwhich interestingly looks like a Taylor expansion of $G$, but this time with joint derivatives in frequency and time. This last expansion, taken separately from the other corrections, is signal-independent as it only depends on the kernel function $G$ and not on $A$, $\\Psi$.\n\nAs will be explained in Sec.~\\ref{subsec:executivesummary}, we will also use these formal Taylor expansions to build error measures (constructed as the magnitude of the first term ignored in the series, see~\\eqref{eq:deffom}) designed to estimate if these three types of corrections are important to take into account.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\subsection{Signal-dependent timescales}\n\\label{subsec:timescales}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=.98\\linewidth]{TfTA_py.pdf}\n  \\caption{Fourier-domain amplitude and phase timescales, as defined in~\\eqref{eq:defTf} and~\\eqref{eq:defTA}, in geometric units for an equal-mass, non-spinning system. The hierarchy of these timescales is roughly the same for higher mass ratio and higher spin systems. The time-domain frequency at merger and the ringdown frequency are represented by the thick and thin vertical lines. The derivatives from which these timescales are built encounter zero-crossings and change sign in the high-frequency range.}\n  \\label{fig:TfTA}\n\\end{figure}\n\nWhen considering the impact on the transfer function from including the next higher-order phase term, that is the difference between~\\eqref{eq:resulttaylorPsi} and~\\eqref{eq:transferlocal}, it is natural to define a new timescale, as a function of frequency,\n\\be\\label{eq:defTf}\n\t\\Tf^{2} = \\frac{1}{4\\pi^{2}}\\left| \\frac{\\ud^{2}\\Psi}{\\ud f^{2}} \\right| \\,.\n\\ee\nFor the correction to be small, this timescale should be small compared to the time-scale of variations in the kernel $G(f,t)$ encoding the modulation and delay. We can use this notation to rewrite~\\eqref{eq:resulttaylorPsi} as\n\\begin{align}\\label{eq:resultdffPsiTf}\n\t \\calT_{\\rm phase}(f) &= \\sum\\limits_{p\\geq 0} \\frac{(-i\\epsilon)^{p}}{2^{p}p!} \\Tf^{2p} \\left( \\frac{\\partial^{2p} }{\\partial t^{2p}} G \\right)(f, \\tf) \\,,\n\\end{align}\nwhere $\\epsilon = -\\mathrm{sgn}(\\ud^{2}\\Psi/\\ud f^{2} )$ is $1$ in the inspiral.\n\nWe can obtain a straighforward physical interpretation of this timescale $\\Tf$ by considering inspiral signals for which the SPA is valid. In that case\n\\be\n\t\\left(\\Tf^{\\rm SPA} \\right)^{2} = -\\frac{1}{4\\pi^{2}}  \\frac{\\ud^{2} \\Psi_{\\rm SPA}}{\\ud f^{2}} \\,,\n\\ee\nwhere $\\ud^{2}\\Psi/\\ud f^{2} < 0$ in the SPA with our sign conventions.\nThen, taking two derivatives of~\\eqref{eq:PsiSPA}, we find\n\\be\\label{eq:TfSPA}\n\t\\Tf^{\\rm SPA} \\equiv \\frac{1}{\\sqrt{2\\dot{\\omega}(\\tfSPA)}} \\,.\n\\ee\nThus, when the SPA applies, $\\Tf$ corresponds to the radiation-reaction timescale: the shorter this timescale, the faster the binary chirps to higher frequencies on its quasi-circular inspiral.\n\nHowever, in the same way that the definition~\\eqref{eq:deftf} for the time-of-frequency function $t_{f}$ generalizes the SPA definition~\\eqref{eq:deftfSPA}, the definition~\\eqref{eq:defTf} only refers to the phase of the Fourier-domain signal and does not require introducing a time-domain frequency like $\\omega$. This defintion thus extends naturally to the merger-ringdown part of the signal. In this part of the signal, its physical interpretation as the timescale of radiation reaction is obscured, and the second derivative $\\ud^{2}\\Psi/\\ud f^{2}$ can go through zero and change sign, as shown in Fig.~\\ref{fig:TfTA}. We include an absolute value in the definition~\\eqref{eq:defTf} to allow for this possibility, and keep track of the sign via $\\epsilon$.\n\nNext, we consider the impact on the transfer function~\\eqref{eq:resulttaylorA} from amplitude corrections beyond leading order. This series also leads to the natural introduction of a set of another set of timescales related to the successive derivatives of the amplitude. In an analogous manner to the definition~\\eqref{eq:defTf} of the timescale $\\Tf$, we can define\n\\be\\label{eq:defTA}\n\t\\left( T_{Ap} \\right)^{p} \\equiv \\frac{1}{(2 \\pi)^{p}} \\frac{1}{A(f)} \\left| \\frac{\\ud^{p} A}{\\ud f^{p}} \\right| \\,,\n\\ee\nwhere we included an absolute value to accomodate the possible sign changes in the right-hand side. With this notation, \\eqref{eq:resulttaylorA} becomes simply\n\\be\\label{eq:resultATA}\n\t\\calT_{\\rm amp}(f) = \\sum\\limits_{p\\geq 0} \\frac{1}{p!} (T_{Ap})^{p}  \\left( \\partial_{t}^{p} G \\right) (f,\\tf) \\,,\n\\ee\nAlthough the above is written for a generic $p\\geq 0$, in practice only the first few of these timescales will be relevant. In this paper we will use only the first two, $T_{A1}$ and $T_{A2}$.\n\nBy contrast, the impact of higher-order terms in the kernel function on the transfer function~\\eqref{eq:resulttaylordelay} is signal-independent. It does not lead to the introduction of new timescales since the coupled time and frequency derivatives are dimensionless. We will see however in Sec.~\\ref{subsec:lisafom} that treating delays does require taking into account dimensionless factors of the type $2\\pi f d$.\n\nWe can obtain useful estimates for these timescales from the leading order post-Newtonian expressions~\\eqref{eq:SPAN}, valid for the dominant harmonic $h_{22}$. The leading-order radiation-reaction and amplitude timescales are:\n\\begin{subequations}\\label{eq:timescalesN}\n\\begin{align}\n\t\\Tf^{\\rm N} &= \\frac{1}{8} \\sqrt{\\frac{5}{3\\nu}} \\frac{G M}{c^{3}} v^{-11/2} \\,, \\label{eq:TfN}\\\\\n\tT_{A1}^{\\rm N} &= \\frac{7}{6} \\frac{1}{2\\pi f}\\,, \\quad T_{A2}^{\\rm N} = \\frac{\\sqrt{91}}{6} \\frac{1}{2\\pi f} \\,. \\label{eq:TA1N-TA2N}\n\\end{align}\n\\end{subequations}\nOne can check explicitly that this expression for $\\Tf$ agrees with~\\eqref{eq:TfSPA}. With a simple power-law amplitude as in~\\eqref{eq:ASPAN}, all higher-order amplitude timescales are also simply proportional to $1/f$ and differ only by their numerical factor. For higher harmonics $h_{\\ell m}$ with $m\\neq 0$, as discussed in Sec.~\\ref{subsec:SPA}, $T_{f}$ acquires a factor $(m/2)^{4/3}$. The amplitude of higher harmonics starts at a higher PN order~\\cite{BlanchetLiving}, differing from~\\eqref{eq:a22N} by a different constant and an additional scaling $v^{\\kappa_{\\ell m}}$ with $\\kappa_{\\ell m} = \\ell - 2 + (\\ell + m \\; \\mathrm{mod} \\; 2)$, which changes the constant in the amplitude timescale as $7/6 \\rightarrow (7-2\\kappa_{\\ell m})/6$ in $T_{A1}^{\\rm N}$ and $\\sqrt{91}/6 \\rightarrow \\sqrt{(7-2\\kappa_{\\ell m})(13-2\\kappa_{\\ell m})}/6$ in $T_{A2}^{\\rm N}$.\n\nWe show in Fig.~\\ref{fig:TfTA} the timescales $\\Tf$, $T_{A1}$, $T_{A2}$ for an equal-mass and non-spinning system. In the inspiral, they follow the scalings~\\eqref{eq:timescalesN} and $\\Tf$ is much larger than the other two. For frequencies above the merger frequency, $\\Tf$ can go through zero while the amplitude-related timescales become comparable or larger.\n\nIn the following, we will compare these signal-dependent timescales to the timescales present in the modulations and delays. In the case of signals from precessing binaries, the precession timescale decreases as the system gets closer to merger, as will be discussed in details in Sec.~\\ref{subsec:sizecorrPrec} below. In the case of the response of a LISA-like detectors, the modulation and delay evolve with a fixed timescale of one year, as will be detailed in Sec.~\\ref{subsec:lisafom}.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\subsection{Quadratic term in the phase and relation to the SUA}\n\\label{subsec:resumquadphase}\n\nIf we restrict to the case of a pure undelayed modulation, $d=0$ and $G(f,t) = F(t)$, we can relate our result~\\eqref{eq:resultdffPsiTf} for the transfer function including up to quadratic phase terms, with the treatment of Ref.~\\cite{KCY13, KCY14}, where the authors extend the SPA in a formalism called the Shifted Uniform Asymptotic expansion (SUA).\n\nThe main intermediate result of~\\cite{KCY14}, their equation~(34), reads exactly like~\\eqref{eq:resultdffPsiTf} with $\\epsilon=1$ and with the identifications $\\tilde{H}_{corr}(f)\\rightarrow \\calT(f)$ for the transfer function, $T\\rightarrow \\Tf$ for the radiation-reaction timescale and $e^{-i\\delta\\phi} \\rightarrow F$ for the modulation function (which is restricted in their framework to a phase, amplitudes being treated jointly with the amplitude of the signal). Thus, our treatment gives a straightforward rederivation of the result of~\\cite{KCY14} which corresponds in our framework to the approximation~\\eqref{eq:expandPsi}, where in the Fourier-domain convolution the phase of the signal is expanded to quadratic order and the amplitude is not expanded. The main difference is that the approach of~\\cite{KCY14} still relies on the SPA being valid for the underlying signal.\n\nThe authors of~\\cite{KCY14} then proposed a resummation scheme for~\\eqref{eq:resultdffPsiTf}, using finite differences for the derivatives. Indeed, the result~\\eqref{eq:resultdffPsiTf} looks like a symmetrized Taylor expansion, except for the factors $i^{p}$ and $1/p!$ instead of $1/(2p)!$. Truncating the sum at some finite order $N$, one can write (following~\\cite{KCY14})\n\\be\\label{eq:stencilresult}\n\t\\calT_{\\rm phase}(f) \\simeq \\sum\\limits_{p = 0}^{N} \\frac{(-i\\epsilon\\Tf^{2})^{p}}{2^{p}p!} \\partial_{t}^{2p}F(\\tf) \\simeq \\calF^{N}_{\\Tf, \\epsilon}[F] (\\tf) \\,,\n\\ee\nwith the operator $\\calF_{T, \\epsilon}^{N}$ defined as\n\\be\\label{eq:stencilfresnel}\n\t\\calF_{T, \\epsilon}^{N}[F] (t) \\equiv \\frac{1}{2}\\sum\\limits_{k=0}^{N} a_{N,k}^{\\epsilon} \\left( F(t + kT) + F(t - k T) \\right) \\,,\n\\ee\nwhere the complex coefficients $a_{N,k}^{\\epsilon}$ are a solution of the $N+1$-dimensional linear system~\\cite{KCY14}\n\\be\\label{eq:stencilsystem}\n\t(-i\\epsilon)^{p} (2p-1)!! = \\sum\\limits_{k=0}^{N} a_{N,k}^{\\epsilon} k^{2p} \\quad \\text{for } p=0,\\dots,N \\,.\n\\ee\nIn practice, $N$ will be most often less than $5$, although we will consider in one case $N=10$ and $20$. In~\\cite{KCY14}, only the case $\\epsilon=1$ was needed, as inspiral signals were considered. The two solutions for the stencil coefficients in the two cases $\\epsilon = \\pm 1$ are simply related by a complex conjugation. Explicit expressions for the stencil coefficients $a_{N,k}^{\\epsilon}$ are given in App.~\\ref{app:stencil} for the first values of $N$.\n\nAn immediate advantage of this reformulation is its improved numerical stability. In waveform modelling applications, it can be bery hard to control high-order numerical derivatives of the modulation. Here, one simply evaluates the original smooth modulation function at shifted times. In the following, we will adopt this implementation for our quadratic-in-phase treatment.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\subsection{Quadratic phase corrections as an integral transform}\n\\label{subsec:fresneltransform}\n\nWe can give an alternative interpretation of the quadratic-phase expansion~\\eqref{eq:resultdffPsiTf} and of Sec.~\\ref{subsec:resumquadphase} in terms of an integral transform. For simplicity of notation, here we keep to the case of a pure modulation $F$ with no delays, $d=0$. We will reintroduce the delays below in Sec.~\\ref{subsec:delays}. To obtain~\\eqref{eq:resultdffPsiTf}, we expanded the phase exponential using~\\eqref{eq:expandexp}. If instead we do not expand this factor, we have\n\\be\\label{eq:integralquadphase}\n\t\\tilde{s}(f)\t\\simeq \\tilde{h}(f) \\int \\ud t\\, F(t) \\int\\ud f'\\, e^{2i\\pi f' (t-\\tf)} \\exp\\left[ 2i\\pi^{2} \\epsilon{f'}^{2} \\Tf^{2} \\right] \\,,\n\\ee\nwhere we recall that $\\epsilon = -\\mathrm{sgn}(\\ud ^{2} \\Psi/\\ud f^{2})$. The integral over $f'$ is a simple complex Gaussian integral which can be carried out explicitly. The result is a complex Gaussian integral over time which is analogous to a Fresnel transform of the function $F$. For this Fresnel transform, we introduce the notation\n\\be\\label{eq:defFresnel}\n\t\\calF_{\\tau}[F](t_{0}) \\equiv \\frac{e^{i\\frac{\\pi}{4}}}{\\sqrt{2\\pi} \\tau} \\int \\ud t \\, \\exp\\left[ - \\frac{i}{2} \\left( \\frac{t-t_{0}}{\\tau} \\right)^{2}\\right] F(t) \\,,\n\\ee\ntogether with the additional notation\n\\be\\label{eq:Fresnelsign}\n\t\\calF_{\\tau, \\epsilon}[F](t_{0}) \\equiv\n\\begin{cases}\n\t \\calF_{\\tau}[F](t_{0}) &\\text{ if } \\epsilon=1 \\\\\n\t \\calF_{\\tau}[F^{*}](t_{0})^{*} &\\text{ if } \\epsilon=-1\n\\end{cases}\n\\ee\nto accomodate for the possible sign change represented by $\\epsilon$. The integral~\\eqref{eq:integralquadphase} then gives for the transfer function\n\\be\\label{eq:resultFresnel}\n\t\\calT_{\\rm phase}(f) = \\calF_{\\Tf, \\epsilon}[F](\\tf) \\,.\n\\ee\n\nThe Fresnel transform~\\eqref{eq:defFresnel} is localized, in the sense that the part of the integral that is centered around $t_{0}$ contributes predominantly, due to the cancelling oscillations far from $t_{0}$. The parameter $\\tau$ determines how local the transform is. In the limit $\\tau\\rightarrow 0$, fast oscillations away from the central value $t_{0}$ will cancel out, leading to the integral taking the value $F(t_{0})$. For large values of $\\tau$, by contrast, the integral~\\eqref{eq:defFresnel} has an extended support. Note also that only the part of the function $F$ that is symmetric about $t_{0}$ contributes to the integral in~\\eqref{eq:defFresnel}.\n\nIn our result~\\eqref{eq:resultFresnel}, both the scale $\\Tf$ and the central time $\\tf$ are functions of the frequency $f$. Since we have seen that $\\Tf$ can be interpreted as the radiation reaction timescale in the SPA regime, this means that a faster-chirping signal ($\\Tf$ small) will have a Fresnel transform that is more focused, whereas a slower-chirping signal ($\\Tf$ large) will have a Fresnel transform that is more extended. The Fresnel width must then be compared with how fast the function $F(t)$ in the integrand is varying. In Sec.~\\ref{subsec:executivesummary}, we will build an estimate for the magnitude of these phase corrections by comparing the radiation-reaction timescale to the timescale of variation of the modulation.\n\nThus, the previous result~\\eqref{eq:stencilresult}-\\eqref{eq:stencilfresnel} can be rephrased as a quadrature rule, and the stencil $\\calF_{T, \\epsilon}^{N}$ is an quadrature approximation of the Fresnel transfrom $\\calF_{T, \\epsilon}$. If one allows for polynomial integrands\\footnote{Note that such integrals with a polynomial integrand are formally divergent. One can regularize them for instance by introducing a small imaginary part in $\\tau$ that is sent it to $0$ at the end of the computation.} in~\\eqref{eq:defFresnel}, using the stencil~\\eqref{eq:stencilfresnel} amounts to building a quadrature rule for the particular choice of nodes $\\tf \\pm k \\Tf$, which is exact (with a regularization) if $F$ is a symmetric polynomial of degree $\\leq 2N$. As a verification, performing a formal Taylor expansion in time of $F(t)$ around $\\tf$ in the integral~\\eqref{eq:defFresnel} and integrating term by term yields back~\\eqref{eq:resultdffPsiTf}.\n\nNote that the choice of a stencil with quadrature nodes $\\tf \\pm k\\Tf$, even if natural, is by no means unique, and other choices would have led to different stencils. The formulation of the result~\\eqref{eq:resultdffPsiTf} as a Fresnel transform~\\eqref{eq:resultFresnel} opens the way for future investigations of different numerical approaches to the problem. For practical computations, in this work we will rely on the approximations $\\calF_{T, \\epsilon}^{N}[F] (t)$ in \\eqref{eq:stencilfresnel}, introduced by~\\cite{KCY14}.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\subsection{Response treatment including delays}\n\\label{subsec:delays}\n\nIn the case of a LISA-type detector response, the presence of the delay $d(t)$ is responsible for the frequency-dependence of the kernel $G$ introduced in~\\eqref{eq:defG}. As an improvement over the Taylor expansion of the kernel function in~\\eqref{eq:resulttaylordelay}, in this section we will propose a different approach based on a change of variable.\n\nAs a first step, we consider the transfer function when we keep only the leading order of the expansion~\\eqref{eq:leadingorderwf}, leaving off additional amplitude and phase terms in~\\eqref{eq:resulttaylorA} and~\\eqref{eq:resulttaylorPsi}, but treating the kernel function nonperturbatively. The response then depends on the signal only by the time-to-frequency correspondence and reads\n\\begin{equation}\n\t\\tilde{s}(f) = \\tilde{h}(f) \\int \\ud t \\, F(t) e^{-2i\\pi f d(t)} \\int \\ud f' \\, e^{2i\\pi f' (t+d(t) - t_{f})} \\,,\n\\end{equation}\nwith $\\tf$ defined in~\\eqref{eq:deftf}. This motivates a change of variable to the delayed time function $t_{d}:t \\mapsto t+d(t)$. Assuming the delay does not vary too quickly, we can also define the reciprocal function $t_{d}^{-1}$, and a modified time-to-frequency correspondence $\\tfd = t_{d}^{-1}(\\tf)$, defined implicitly by\n\\be\n\t\\left. (t + d(t) - t_{f})\\right|_{t=t_{f}^{d}} = 0 \\,.\n\\ee\nThe above integral gives then for the transfer function\n\\begin{align}\\label{eq:delaycorrleading}\n\t\\calT(f) &= \\int \\ud t \\, F(t) e^{-2i\\pi f d(t)} \\delta(t + d(t) - t_{f}) \\nn \\\\\n\t&= F(t_{f}^{d}) \\frac{e^{-2i\\pi f d(t_{f}^{d})}}{1+\\dot{d}(t_{f}^{d})} \\,.\n\\end{align}\nThis differs from~\\eqref{eq:transferlocal} both by the replacement $\\tf \\rightarrow t_{f}^{d}$ and by the extra denominator.\n\nFor the proposed LISA configuration~\\cite{LISA17}, we have for the orbital delays the scaling $d_{0}\\sim R/c \\simeq 500s$, and for the constellation delays the scaling $d_{L}\\sim L/c \\simeq 8s$ (ignoring the dependence on angular factors). Since the motion of the constellation is anually periodic, with a frequency $\\Omega_{0} \\simeq 2 \\times 10^{-7}\\mathrm{rad}.s^{-1}$, we have $\\dot{d}_{0} \\sim \\Omega_{0} R/c \\simeq 10^{-4}$ and $\\dot{d}_{L} \\sim \\Omega_{0} L/c \\simeq 1.7 \\times 10^{-6}$. The smallness of the dimensionless quantity $\\dot{d} \\ll 1$ (and of its subsequent derivatives) will allow us to treat it perturbatively with a very good approximation, and shows also that the function $t_{d}$ is univalued and that there is no ambiguity in defining the reciprocal $t_{d}^{-1}$.\n\nBy treating $\\dot{d}$ as a perturbation and keeping only first-order terms, we obtain for the delayed time reciprocal function\n\\begin{align}\n\tt_{d}^{-1}(t) &\\simeq t-d(t) (1-\\dot{d}(t)) \\,,\\nn\\\\\n\td(t_{f}^{d}) &\\simeq d(t_{f}) ( 1 - \\dot{d}(t_{f})) \\,.\n\\end{align}\nNow, the most relevant correction in~\\eqref{eq:delaycorrleading} comes from the phase factor at high frequencies, where the factors $2\\pi f d_{0}$ and $2\\pi f d_{L}$ give a magnification reaching respectively $3.10^{3}$ and $10^{2}$ at $1\\Hz$. Ignoring the other corrections, we thus arrive at the following form for the dominant delay correction in the transfer function:\n\\be\n\t\\calT(f) \\simeq F(t_{f})\\exp\\left[ -2i\\pi f d(t_{f}) (1-\\dot{d}(t_{f})) \\right] \\,.\n\\ee\nThis first correction beyond the leading order is signal-independent and affects purely the phase of the output signal.\n\nNext, we consider the case where the quadratic phase correction is kept as well, as in Sec.~\\ref{subsec:fresneltransform}, and where we keep all the first-order terms in $\\dot{d}$ (neglecting its higher derivatives). We can write\n\\begin{widetext}\n\\begin{align}\n\t\\tilde{s}(f) &\\simeq \\tilde{h}(f) \\int \\ud t \\, F(t) e^{-2i\\pi f d(t)} \\int \\ud f' \\, \\exp\\left[ 2i\\pi \\epsilon \\Tf^{2} f'^{2} + 2i\\pi f' (t+d(t) - \\tf) \\right] \\nn\\\\\n\t&\\simeq \\tilde{h}(f) \\frac{e^{i\\epsilon\\frac{\\pi}{4}}}{\\sqrt{2\\pi}\\Tf} \\int \\ud \\tau \\, \\frac{F(\\tau - d(\\tau))}{1+\\dot{d}(\\tau)} e^{-2i\\pi f d(\\tau)(1-\\dot{d}(\\tau))}\\exp\\left[ -\\frac{i\\epsilon}{2} \\frac{(\\tau - \\tf)^{2}}{\\Tf^{2}} \\right] \\,,\n\\end{align}\nwhere we used a change of variable $\\tau = t_{d}(t)$. We see that the result can again be expressed as a Fresnel transform.\n\nFinally, when considering amplitude corrections as well, as in~\\eqref{eq:resulttaylorA}, additional powers of $f'$ can be translated as time derivatives with respect to the variable $\\tau$ after performing the change of variables. This produces the result:\n\\be\\label{eq:transferfinal}\n\t\\calT(f) = \\sum\\limits_{k \\geq 0} \\frac{(-i)^{k}}{k!} (T_{Ak})^{k} \\calF_{\\Tf, \\epsilon} \\left[ \\frac{\\ud^{k}}{\\ud \\tau^{k}} \\left( \\frac{F(\\tau - d(\\tau))}{1+\\dot{d}(\\tau)} e^{-2i\\pi f d(\\tau)(1-\\dot{d}(\\tau))} \\right) \\right] (\\tf) \\,.\n\\ee\n\\end{widetext}\n\n\\subsection{Summary of the formalism}\\label{subsec:executivesummary}\n\nIn this Section, we gather our previous results for the convenience of the reader, and explain how we will use them in practice. For a modulation $F$ and delay $d$, so that $s(t) = F(t) h(t+d(t))$, we obtained the transfer function $\\calT (f) = \\tilde{s}(f)/\\tilde{h}(f)$ given in~\\eqref{eq:transferfinal}.\n\nIn this result, the Fresnel transform $\\calF^{\\epsilon}_{\\Tf}$ can in turn be approximated by the stencil $\\calF^{N}_{\\Tf, \\epsilon}$ using the formula~\\eqref{eq:stencilfresnel}. The timescales $\\Tf$ and $T_{Ak}$ were defined in~\\eqref{eq:defTf} and~\\eqref{eq:defTA}, and the generalized time-to-frequency function $t_{f}$ was given in~\\eqref{eq:deftf}. The delays $d$ are present only in the LISA context, while in the context of precessing binaries we only have to consider the modulation function $F$. In practice, only the first few of the terms in the series expansion are relevant. We will investigate several orders of approximation, combining corrections from the phase, amplitude and delays, and explore which ones are relevant for a given level of accuracy. We will use symbols of the form $\\{N | A | d\\}$ to indicate the order of the stencil in~\\eqref{eq:stencilfresnel}, the maximal order of the amplitude correction included, and the inclusion or not of the delay corrections at first order in $\\dot{d}$ as derived in Sec.~\\ref{subsec:delays}.\n\nIn the LISA context, due to the smallness of the corrections we will only go up to $k=1$ in~\\eqref{eq:transferfinal}, and in computing the remaining time derivatives in~\\eqref{eq:transferfinal} we will neglect the second and higher derivatives. We will also use $F(\\tau - d(\\tau)) \\simeq (F - d \\dot{F})(\\tau)$. This gives concretely:\n\\begin{widetext}\n\\begin{subequations}\\label{eq:summaryNAd}\n\\begin{align}\n\t\\{N | A:0 | d:0\\}&: \\; \\calT(f) = \\calF^{N}_{\\Tf, \\epsilon} \\left[ F e^{-2i\\pi f d} \\right] (t_{f}) \\,, \\\\\n\t\\{N | A:1 | d:0\\}&: \\; \\calT(f) = \\calF^{N}_{\\Tf, \\epsilon} \\left[ \\left(F - i T_{A1} \\left( \\dot{F} - 2i\\pi f \\dot{d}\\right) \\right) e^{-2i\\pi f d} \\right] (t_{f}) \\,, \\\\\n\t\\{N | A:0 | d:1\\}&: \\; \\calT(f) = \\calF^{N}_{\\Tf, \\epsilon} \\left[ \\frac{F - d\\dot{F}}{1+\\dot{d}} e^{-2i\\pi f d (1-\\dot{d})} \\right] (t_{f})\\,, \\\\\n\t\\{N | A:1 | d:1\\}&: \\; \\calT(f) = \\calF^{N}_{\\Tf, \\epsilon} \\left[ \\frac{1}{1+\\dot{d}}\\left(  F - d\\dot{F} - i T_{A1} \\left( \\dot{F} - 2i\\pi f \\dot{d} \\right) \\right) e^{-2i\\pi f d (1 - \\dot{d})} \\right] (t_{f})\\,.\n\\end{align}\n\\end{subequations}\n\\end{widetext}\n\nIn the context of precessing binaries, the delays are absent and we will go up to $k=2$ in~\\eqref{eq:transferfinal}. The tranfer function at different orders of approximation will be:\n\\begin{subequations}\\label{eq:summaryNA}\n\\begin{align}\n\t\\{N | A:0\\}&: \\; \\calT(f) = \\calF^{N}_{\\Tf, \\epsilon} \\left[ F \\right] (t_{f}) \\,, \\\\\n\t\\{N | A:1\\}&: \\; \\calT(f) = \\calF^{N}_{\\Tf, \\epsilon} \\left[ F - i T_{A1} \\dot{F} \\right] (t_{f}) \\,, \\\\\n\t\\{N | A:2\\}&: \\; \\calT(f) = \\calF^{N}_{\\Tf, \\epsilon} \\left[ F - i T_{A1} \\dot{F} - \\frac{1}{2} (T_{A2})^{2} \\ddot{F} \\right] (t_{f}) \\,.\n\\end{align}\n\\end{subequations}\n\nIn the following, it will be convenient to introduce error estimates built from the Taylor-like series~\\eqref{eq:resulttaylorPsi},~\\eqref{eq:resulttaylorA} and~\\eqref{eq:resulttaylordelay}. We simply define these error estimates at a certain level of approximation as the magnitude of the first term ignored in the original Taylor series. To give these quantities a relative meaning, we divide by the leading term. Thus we define, with $G(f,t) = F(t) e^{-2i\\pi f d(t)}$,\n\\begin{subequations}\\label{eq:deffom}\n\\begin{align}\n\t\\epsilon_{\\Psi 2} &\\equiv \\frac{1}{2} \\Tf^{2} \\left| \\frac{1}{G}\\partial_{tt}G \\right| \\,, \\\\\n\t\\epsilon_{A 1} &\\equiv T_{A1} \\left| \\frac{1}{G} \\partial_{t} G \\right| \\,, \\\\\n\t\\epsilon_{A 2} &\\equiv \\frac{1}{2} T_{A2}^{2} \\left| \\frac{1}{G} \\partial_{tt}G \\right| \\,, \\\\\n\t\\epsilon_{d} &\\equiv \\frac{1}{2\\pi} \\left| \\frac{1}{G} \\partial_{tf} G \\right| \\,,\n\\end{align}\n\\end{subequations}\nwhere the function $G$ and its derivatives are evaluated at $(f, t_{f})$. For $\\epsilon \\ll 1$, the perturbative approach applies and $\\epsilon$ can be used as an estimate for the magnitude of the effect. Reaching $\\epsilon \\sim 1$ will indicate a breakdown of the perturbative approach.\n\nThe physical interpretation of these error measures is clear: when the modulation and delay obey the simple scaling $\\partial_{t}^{n} \\rightarrow \\Omega^{n}$, with $\\Omega_{0}$ a characteristic frequency, the phase and amplitude error estimates are simply ratios of timescales. For instance, with this scaling $\\epsilon_{\\Psi 2} \\sim T_{f}^{2}\\Omega^{2}/2$, so that the approximation will work well when the radiation-reaction timescale is shorter than the characteristic timescale of the modulation. However, as we will show in Sec.~\\ref{subsec:lisafom} this simple picture will need to be refined in the presence of delays, due to the presence of additional dimensionless factors of the form $2\\pi f d$, which can be larger than 1.\n\nOn top of this perturbative formalism, in the LISA case we will also develop another approach exploiting the periodicity of the modulation and delays (see Sec.~\\ref{subsec:comblisa}), while in the case of precessing binaries we will use a trigonometric polynomial approach to represent the merger-ringdown part of the signal (see Sec.~\\ref{subsec:trigopoly})\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Application to the response of LISA-type detectors}\n\\label{sec:LISA}\n\nIn this Section, we apply the formalism of Sec.~\\ref{sec:formalism} to the Fourier-domain response of a LISA-like detector, and assess the accuracy of our approach at various levels of approximation. We also propose an alternative approach for slowly-chirping signals.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\subsection{The response model}\n\\label{subsec:modelLISA}\n\nWe begin by detailing the model that we use for the response of a LISA-like detector, together with the assumptions used and their limitations. Since our aim is to assess the accuracy of our direct Fourier-domain treatment of the response, we can focus on the gravitational-wave contribution to the basic single-link observables. We therefore use a somewhat simplified model for the time-domain response~\\cite{Krolak+04}, ignoring corrections that would be crucial from the point of view of noise cancellations, keeping in mind that the response model can be enriched later without affecting the conclusions of the present analysis.\n\nThe frequency-shift response for a single link~\\eqref{eq:yslr} was derived in Ref.~\\cite{EW75} (see also~\\cite{CR02, RCP04, Finn08, Cornish09}). Several assumptions enter the result as written in~\\eqref{eq:yslr}: (i) effects of the order $v/c$ are neglected, including for instance the special relativistic Doppler effect created by the relative speeds of the spacecraft on their orbits (ii) the propagation is assumed to take place in a flat spacetime, perturbed only by the gravitational wave; thus the gravitational redshift as well as the deflection of light created by the gravitational potential of the Sun is ignored (iii) all geometric factors are evaluated at a single time, whereas one should consider the beam as propagating from the position of the first spacecraft at the time of emission to the position of the second scapecraft at the time of reception, leading to a point-ahead effect.\n\nAdditionally, we limit ourselves to a rigid model for the orbits of the constellation, namely we assume that the constellation remains in an equilateral configuration with fixed armlengths. These simplified orbits neglect (iv) effects of order $e^{2}$ from the eccentricity of the individual Keplerian orbits, (v) the effect of gravitational perturbations coming from other celestial bodies, such as the Earth, the quadrupole of the Sun, and the other planets. Note that although we can neglect all the effects (i)-(v) for our present study, keeping track of these corrections is crucial for the purpose of laser noise cancellations, and led to the development of new generations of TDI observables~\\cite{Tintoliving}.\n\nIt is natural to split the response~\\eqref{eq:yslr} into two steps: first the orbital delay related to the orbit around the Sun of the whole constellation, and then the constellation response. The baselines for the delays are indeed very different in the two cases. Geometrical projection factors aside, we have for the orbit around the Sun $R=1\\text{au}=1.5\\times 10^{8} \\text{km}$, while the detector armlength is $L=2.5\\times 10^{6}\\text{km}$ (in the configuration proposed in~\\cite{LISA17}). It is natural to define two transfer frequencies for the two relevant length scales for the delays, defined such that a wavelength fits within this length scale, i.e. $2\\pi f d = 1$. This gives\n\\begin{subequations}\\label{eq:transferfrequencies}\n\\begin{align}\n\tf_{R} &= 3.2\\times10^{-4}\\Hz \\,,\\\\\n\tf_{L} &= 1.9\\times 10^{-2}\\Hz \\,.\n\\end{align}\n\\end{subequations}\nThe LISA response will behave qualitatively differently on the three frequency bands $f \\leq f_{R}$, $f_{R} \\leq f \\leq f_{L}$ and $f_{L} \\leq f$.\n\nThe first stage of the response, the orbital delay, consists simply in applying the varying time delay to bring the wavefront sampling point from the SSB reference to the center of the LISA triangular constellation, common to all $y_{slr}$ observables. For $h^{\\rm TT}$ the transverse-traceless gravitational waveform in matrix form, we write this orbital time delay as\n\\be\\label{eq:defresponse0}\n\th_{0}^{\\rm TT} (t) = h^{\\rm TT}(t-\\hatk\\cdot p_{0}) \\,,\n\\ee\nwith $p_{0}$ the position of the constellation center, which follows the Earth orbit around the Sun. The second stage of the response calculation comprises the remaining, constellation-centered response. For the single-link contribution to the response, for the laser link from spacecraft $s$ to spacecraft $r$ along a path in direction $n_l$, we write\n\\begin{align}\\label{eq:defresponseL}\n\ty_{slr} &= \\frac{1}{2} \\frac{1}{1 - \\hatk\\cdot n_{l}} \\nn\\\\\n\t& \\cdot n_{l}\\cdot \\left[ h_{0}^{\\rm TT}(t - L - \\hatk\\cdot p^{L}_{s}) - h_{0}^{\\rm TT}(t - \\hatk\\cdot p^{L}_{r}) \\right] \\cdot n_{l}\\,,\n\\end{align}\nwhere we reference the positions of the spacecraft relative to the center of the constellation, $p^{L}_{A} \\equiv p_{A} - p_{0}$.\n\nAs described in App.~\\ref{app:notation} We will decompose the full signal in the contributions of the individual spin-weighted spherical modes $h_{\\ell m}$, whose Fourier transforms are assumed to have a smooth amplitude and phase. First, we define the matrices $P_{+},P_{\\times}$ such that, in the sense of matrices,\n\\be\n\th^{\\rm TT} = h_{+}P_{+} + h_{\\times}P_{\\times} \\,.\n\\ee\nWe focus only on positive frequencies. Assuming that the approximation~\\eqref{eq:zeronegativef} applies, we consider a single mode contribution, $h=h_{\\ell m}$ with $m>0$. For each given mode we define a complex matrix $P_{\\ell m}$ incorporating the spin-weighted spherical harmonic constant factor as\n\\be\n\tP_{\\ell m} =\n\t\\begin{cases}\n\t\\frac{1}{2} {}_{-2}Y_{\\ell m} \\left( P_{+} + i P_{\\times} \\right) \\text{ for } m>0\\,,\\\\\n\t\\frac{1}{2} {}_{-2}Y_{\\ell m}^{*} \\left( P_{+} - i P_{\\times} \\right) \\text{ for } m<0\\,.\n\t\\end{cases}\n\\ee\n\nWe now turn to the transformation of~\\eqref{eq:defresponse0} and~\\eqref{eq:defresponseL} to the Fourier domain. Applying a pure delay as in~\\eqref{eq:defresponse0} translates into\n\\be\\label{eq:G0}\n\tG_{0}(f, t) = e^{-2i\\pi f d_{0}(t)} \\,,\n\\ee\nwith $d_{0} = -\\hatk \\cdot p_{0}$ the delay associated to the orbit around the Sun. For the leading-order response~\\eqref{eq:transferlocal}, this gives a Fourier-domain transfer function common to all modes, that is a pure phase factor, proportional to the frequency but also $t_{f}$-dependent:\n\\be\\label{eq:transfer0local}\n\t\\calT_{0}^{\\rm local}(f) = G_{0}(f, \\tf)\\,.\n\\ee\nIf $(\\lambda, \\beta)$ are the ecliptic longitude and latitude of the source in the sky, and if the orbital phase is set by convention to $0$ at $t=0$, the orbital delay has the simple expression\n\\be\\label{eq:delay0}\n\td_{0}(t) = -R \\cos\\beta \\cos\\left(\\Omega_{0}t - \\lambda\\right)\\,.\n\\ee\n\nFor the constellation part of response~\\eqref{eq:defresponseL}, treated separately from the delay~\\eqref{eq:delay0}, we write\n\\begin{align}\\label{eq:decomposeGslr}\n\tF_{slr}^{L}(t) &= \\frac{1}{2} \\frac{1}{1 - \\hatk\\cdot n_{l}(t)} n_{l}(t) \\cdot P_{\\ell m} \\cdot n_{l} (t) \\,,\\nn\\\\\n\td_{s}(t) &= - k\\cdot p_{s}^{L}(t) \\,, \\quad d_{r}(t) = - k\\cdot p_{r}^{L}(t) \\,,\\nn\\\\\n\tG_{slr}^{L}(f,t) &=  F_{slr}^{L}(t) \\left( e^{-2i\\pi f (d_{s,L}(t) + L)} - e^{-2i\\pi f d_{r}(t)} \\right) \\,.\n\\end{align}\nThe superscript $L$ indicates that the orbital delay~\\eqref{eq:delay0} is not included. Since we also assume the rigid approximation for the constellation, where the armlengths are fixed, a particular simplification occurs when combining these individual delays, thanks to the relation $p^{L}_{r} - p^{L}_{s} =  L n_{l}$:\n\\begin{align}\\label{eq:GslrL}\n\tG_{slr}^{L}(f,t) &= \\frac{i \\pi f L}{2} \\sinc \\left[ \\pi f L\\left(1-\\hatk\\cdot n_{l} \\right) \\right] \\nn\\\\\n\t& \\quad \\cdot \\exp\\left[ i \\pi f \\left( L + \\hatk\\cdot \\left( p_{1}^{L} + p_{2}^{L} \\right) \\right) \\right]  n_{l} \\cdot P_{\\ell m} \\cdot n_{l} \\,,\n\\end{align}\nwith all time-dependent vectors evaluated at $t$. This expression is well known as describing the frequency-dependency in the LISA response~\\cite{Larson+99, Cornish01, CR02, RCP04}. In the local approximation~\\eqref{eq:transferlocal}, the Fourier-domain transfer function then reads\n\\begin{align}\\label{eq:transferLlocal}\n\t\\calT_{slr}^{L, \\mathrm{local}}(f) &= G_{slr}^{L}(f, \\tf) \\,.\n\\end{align}\nFor plotting purposes, we will also define\n\\be\\label{eq:transferLenvelope}\n\t\\overline{\\calT}_{slr}^{L} (f) = \\frac{i \\pi f L}{2} n_{l} \\cdot P_{\\ell m} \\cdot n_{l} (\\tf)\n\\ee\nwhich will serve as an estimate for the enveloppe function of the response, devoid of the zero-crossings at high frequencies of the $\\sinc$ term in~\\eqref{eq:GslrL}.\n\nNote that, if the corrections of Sec.~\\ref{subsec:delays}, for non-negligible $\\dot d$, are included for the constellation delays, the transfer function will not have this simple form anymore, as $\\dot{d}$ will have a different velocity-dependent expression for the sending and receiving spacecraft. One must then separately handle $d_{s}$ and $d_{r}$ in~\\eqref{eq:decomposeGslr} to compute the corrections.\n\nThe orbital response~\\eqref{eq:transfer0local}-\\eqref{eq:delay0} takes a simple analytic form, but the phase contribution of this delay is significant across most of the frequency band and can be large for $f \\gg f_{R}$.\n\nThe constellation response~\\eqref{eq:GslrL}-\\eqref{eq:transferLlocal} can be interpreted as the Fourier-domain translation of a discrete derivative taken on the waveform. The leading factor in~\\eqref{eq:GslrL} shows that the amplitude of the response is proportional to $f$ in the low-frequency limit $f\\ll f_{L}$, where the other factors are essentially unity. For $f\\gtrsim f_{L}$, the $\\sinc$ and the phase of the exponential generate additional structure in the response, including zero-crossings when the projected armlength is an integer number of wavelengths. From~\\eqref{eq:transferLlocal}, an expansion for small $f\\ll f_{L}$ yields back a Fourier-domain analog of the low-frequency approximation of the response~\\cite{Cutler97, RCP04}, which is equivalent to having two LIGO-type interferometers turned by $\\pi/4$ and set in motion.\n\nFor analysis of the response we need a concrete set of gravitational waveforms. We will use the PhenomD model~\\cite{Khan+15,Husa+15}, which provides Fourier-domain inspiral-merger-ringdown waveforms for aligned spins. We refer to App.~\\ref{app:precLISA} for a brief discussion of the prospects for applying our formalism for the LISA response to precessing Fourier-domain waveforms.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\subsection{Estimates for the magnitude of higher-order corrections}\n\\label{subsec:lisafom}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=.99\\linewidth]{lisafom_Psi_McDeltat_py.pdf}\n  \\caption{Contour levels for the analytical estimate of the error measure $\\epsilon_{\\Psi 2}$ at the starting frequency, as a function of chirp mass $\\Mchirp$ and time to coalescence $\\Delta t$. Blue corresponds to the orbital response and red to the constellation response. The colored shaded areas indicate regions where $\\epsilon_{\\Psi 2} \\geq 1$, where the perturbative formalism is expected to break down. In the region to the right of the black line, $f_{\\rm start}$ given in~\\eqref{eq:fstartN} is lower than the lowest in-band frequency $f_{\\rm min} = 10^{-5}\\Hz$, so that the signal starts at $f_{\\rm min}$ and $\\epsilon_{\\Psi 2}$ becomes independent of $\\Delta t$.}\n  \\label{fig:lisafomPsiMcDeltat}\n\\end{figure}\n\n\\begin{figure*}\n  \\centering\n  \\includegraphics[width=.98\\linewidth]{lisafom_py.pdf}\n  \\caption{Error estimates as defined in~\\eqref{eq:deffom}, for an equal-mass, non-spinning system and for total masses $M=10^{7} \\Msol$, $10^{4} \\Msol$ and $10^{2} \\Msol$. The top row corresponds to the orbital delay part of the response~\\eqref{eq:defresponse0}, and the lower row shows the LISA-centered constellation response~\\eqref{eq:defresponseL}. The error measures $\\epsilon_{\\Psi 2}$ for the phase corrections, $\\epsilon_{A1}$ for the amplitude, $\\epsilon_{d}$ for the delay are shown from left to right. The central line and interval are the mean and $1\\sigma$ standard deviation of the logarithm of $\\epsilon$ computed with numerical derivatives over 400 random values for the position in the sky, inclination and polarization. The starting frequency is set by an observation time of $\\Delta t = 10 \\text{yrs}$ before merger. We overlay in dashed the analytical estimates obtained from from~\\eqref{eq:timescalesNfstart} and~\\eqref{eq:estimatederivorb}-\\eqref{eq:estimatederivconst}.}\n  \\label{fig:fomLISA}\n\\end{figure*}\n\nUsing the approximate error measures $\\epsilon$ introduced in~\\eqref{eq:deffom}, we will now estimate, for each type of correction (phase, amplitude, delay), the size of errors in the transfer function.\n\nTo obtain an order-of-magnitude estimate for the error measures $\\epsilon$~\\eqref{eq:deffom}, we will use the Newtonian-order expressions~\\eqref{eq:timescalesN} for the signal-dependent timescales $\\Tf$ and $T_{A1}$. Higher-order amplitude terms beyond the first one in~\\eqref{eq:resulttaylorA}, as well as phase terms beyond the second derivative in~\\eqref{eq:expandPsi}, will be negligible and we will ignore them in the following. It is useful to separate the orbital response~\\eqref{eq:transfer0local} and the constellation response~\\eqref{eq:transferLlocal}, as the different baseline of the delays (orbital radius $R$ or armlength $L$) as well as the presence of a time-varying prefactor $F(t)$ both affect the result. When estimating the magnitude of the relevant derivatives of $G$, we must also take into account dimensionless delay factors of the type $2\\pi f d$.\n\nWe start with the orbital response, which takes the form of a pure delay $G_{0}(f, t) = e^{-2 i \\pi f d_{0}(t)}$, and obtain\n\\begin{subequations}\n\\begin{align}\n\t\\frac{1}{G_{0}} \\partial_{t} G_{0} &= -2i\\pi f \\dot{d}_{0}\\,,\\\\\n\t\\frac{1}{G_{0}} \\partial_{tt} G_{0} &= -2i\\pi f \\ddot{d}_{0} - 4\\pi^{2} f^{2} \\dot{d}_{0}^{2} \\,,\\\\\n\t\\frac{1}{G_{0}} \\partial_{tf} G_{0} &= -2 i \\pi \\dot{d}_{0} - 4\\pi^{2} f d_{0} \\dot{d}_{0} \\,.\n\\end{align}\n\\end{subequations}\n\nSince the one-arm constellation response~\\eqref{eq:decomposeGslr}-\\eqref{eq:transferLlocal} is analogous to a discrete time derivative of the signal, it is appropriate to keep explicit an overall factor $f$ reflecting this structure. Hence we write symbolically $G_{L}(f,t) \\sim f F(t) e^{-2i \\pi f d_{L}(t)}$, where $d_{L}$ represents a delay term and $F(t)$ represents the rest of the geometric factors in~\\eqref{eq:transferLlocal}, for which we momentarily ignore the $f$-dependence. This gives\n\\begin{subequations}\n\\begin{align}\n\t\\frac{1}{G_{L}} \\partial_{t} G_{L} &\\sim -2i\\pi f \\dot{d}_{L} + \\frac{\\dot{F}}{F}\\,,\\\\\n\t\\frac{1}{G_{L}} \\partial_{tt} G_{L} &\\sim -2i\\pi f \\ddot{d}_{L} - 4\\pi^{2} f^{2} \\dot{d}_{L}^{2} - 2i\\pi f \\dot{d}_{L} \\frac{\\dot{F}}{F} - \\frac{\\dot{F}^{2}}{F^{2}} + \\frac{\\ddot{F}}{F} \\,,\\\\\n\t\\frac{1}{G_{L}} \\partial_{tf} G_{L} &\\sim -4 i \\pi \\dot{d}_{L} - 2i\\pi d_{L} \\frac{\\dot{F}}{F} - 4\\pi^{2} f d_{L} \\dot{d}_{L} + \\frac{1}{f}\\frac{\\dot{F}}{F}\\,.\n\\end{align}\n\\end{subequations}\n\nIn order to obtain simple scalings for the error estimates, we will make the replacements $\\partial_{t}^{n} d \\sim \\Omega_{0}^{n} d$ as well as $\\partial_{t}^{n} F \\sim \\Omega_{0}^{n} F$. These scalings are only approximate as different orientation angles can lead to significant variations. To represent the average of the geometric projection factor of the gravitational wave propagation vector on the plane of the orbit, we will take $d_{0} \\sim R/2 $. For the constellation delays, we simply take $d_{L} \\sim L$ as there projection effects can lead to variations in both ways. The resulting estimates for the magnitude of these derivatives are\n\\begin{subequations}\\label{eq:estimatederivorb}\n\\begin{align}\n\t\\left| \\frac{1}{G_{0}} \\partial_{t} G_{0} \\right| &\\sim \\pi f \\Omega_{0} R\\,,\\\\\n\t\\left| \\frac{1}{G_{0}} \\partial_{tt} G_{0} \\right| &\\sim \\text{max} \\left[ \\pi f \\Omega_{0}^{2} R, \\pi^{2} f^{2} \\Omega_{0}^{2} R^{2}\\right] \\,,\\\\\n\t\\left| \\frac{1}{G_{0}} \\partial_{tf} G_{0} \\right| &\\sim \\text{max} \\left[ \\pi  \\Omega_{0} R, \\pi^{2} f \\Omega_{0} R^{2} \\right] \\,,\n\\end{align}\n\\end{subequations}\nfor the orbital response and\n\\begin{subequations}\\label{eq:estimatederivconst}\n\\begin{align}\n\t\\left| \\frac{1}{G_{L}} \\partial_{t} G_{L} \\right| &\\sim \\text{max} \\left[ \\Omega_{0}, 2 \\pi f \\Omega_{0} L \\right] \\,,\\\\\n\t\\left| \\frac{1}{G_{L}} \\partial_{tt} G_{L} \\right| &\\sim \\text{max} \\left[ \\Omega_{0}^{2}, 4 \\pi f \\Omega_{0}^{2} L, 4\\pi^{2} f^{2} \\Omega_{0}^{2} L^{2} \\right] \\,,\\\\\n\t\\left| \\frac{1}{G_{L}} \\partial_{tf} G_{L} \\right| &\\sim \\text{max} \\left[ \\Omega_{0}/f, 6 \\pi \\Omega_{0} L, 4\\pi^{2} f \\Omega_{0}^{2} L^{2} \\right] \\,,\n\\end{align}\n\\end{subequations}\nfor the constellation response. In the presence of different terms, we simply take the maximum of their norms.\n\nAn important point in~\\eqref{eq:estimatederivorb} and~\\eqref{eq:estimatederivconst} above is the presence of delay factors in the forms of powers of $2\\pi f d$, so that we cannot use the simple replacement $\\partial_{t}^{n}G \\rightarrow \\Omega_{0}^{n}G$. Thus, the suitability of the leading-order treatment cannot be estimated by a mere separation between the signal timescales and the annual timescale for the response, but will also depend on the frequency being above or below the transfer frequencies $f_{R}$ and $f_{L}$ defined in~\\eqref{eq:transferfrequencies}. The error measure $\\epsilon_{d}$ does not depend on signal-dependent timescales and can be directly read off the estimates above, with $\\epsilon_{d} = |\\partial_{tf}G/(2\\pi G)|$. For the error measures $\\epsilon_{\\Psi 2}$ and $\\epsilon_{A1}$, we will combine the above derivatives with the Newtonian timescales given in~\\eqref{eq:timescalesN} for the inspiral phase of the signal.\n\nThe starting frequency of the signal will play an important role. As a function of the time remaining before merger $\\Delta t$, from the Newtonian relation~\\eqref{eq:omegaphiN} we have (using the chirp mass $\\Mchirp = M \\nu^{3/5}$):\n\\be\\label{eq:fstartN}\n\tf_{\\rm start} = 1.75\\times 10^{-5} \\Hz \\left( \\frac{\\Mchirp}{10^{6}M_{\\odot}} \\right)^{-5/8} \\left( \\frac{\\Delta t}{10 \\yr} \\right)^{-3/8} \\,.\n\\ee\nThis gives in turn for the Newtonian timescales~\\eqref{eq:timescalesN}\n\\begin{subequations}\\label{eq:timescalesNfstart}\n\\begin{align}\n\t\\Tf^{\\rm N} &= 8.78\\times10^{-2}\\yr \\left( \\frac{\\Mchirp}{10^{6}M_{\\odot}} \\right)^{5/16} \\left( \\frac{\\Delta t}{10 \\yr} \\right)^{11/16} \\,, \\\\\n\tT_{A1}^{\\rm N} &= 3.37\\times10^{-4}\\yr \\left( \\frac{\\Mchirp}{10^{6}M_{\\odot}} \\right)^{5/8} \\left( \\frac{\\Delta t}{10 \\yr} \\right)^{3/8} \\,.\n\\end{align}\n\\end{subequations}\nNote that if we think of LISA as effectively insensitive below some minimal frequency $f_{\\rm min}$, then for sufficiently high $\\Mchirp$ this point of entry in the sensitive band will mark the beginning of the signal, obviating the relevance of $f_{\\rm start}$. For $f_{\\rm min} = 10^{-5}\\Hz$ and $\\Delta t \\leq 10\\yr$, this is the case for $\\Mchirp \\geq 2.45\\times 10^{6}\\Msol $. Thus, our final analytical estimates for the $\\epsilon$ error measures are built by inserting~\\eqref{eq:timescalesNfstart} and~\\eqref{eq:estimatederivorb}-\\eqref{eq:estimatederivconst} in~\\eqref{eq:deffom}, while ensuring the frequency cut $10^{-5}\\Hz \\leq f \\leq 1\\Hz$.\n\nIt is useful to distinguish between what we will call merging binaries, systems close to coalescence that will merge during the LISA mission lifetime or a few years later, and slowly-chirping binaries still in the deep inspiral phase, of which we observe only a small snapshot in Fourier domain as they do not sweep to the end of the frequency band. The massive black hole binaries (MBH) that will be observed by LISA~\\cite{LISA17} fall within the first category, with their merger in band, while the proposed population of stellar-origin black hole binaries (SOBH)~\\cite{Sesana16}, with masses comparable to the LIGO/Virgo detections, will comprise both merging binaries, i.e. exiting the LISA band towards larger frequencies during observations, and slowly-chirping binaries hundreds or thousands of years away from merger.\n\nWe turn first to the slowly-chirping binaries. For these systems, we will focus on $\\epsilon_{\\Psi 2}$, which will be the most important error measure. Fig.~\\ref{fig:lisafomPsiMcDeltat} shows contour levels for the value of our simple analytical estimate for $\\epsilon_{\\Psi 2}$ at the beginning of the observations, as a function of the chirp mass and time to merger, for both the orbital and the constellation response. The limit $\\epsilon_{\\Psi 2} = 1$ is used to single out areas where the perturbative treatment of Sec.~\\ref{sec:formalism} is expected to break down, although the precise location of this boundary will vary, depending on the accuracy level required and on the orientation angles. We also single out the high-mass region where the start of the signal is set by its entry into the sensitive band at $f_{\\rm min}$, making the error measure independent of the time to merger. We find that, for binaries in the LIGO/Virgo mass range $10^{1}-10^{2} \\Msol$, we reach the limit $\\epsilon_{\\Psi 2}=1$ first for the orbital response, for time-to-merger values within the expected observed range~\\cite{Sesana16}. We will introduce in Sec~\\ref{subsec:comblisa} an alternative approach to deal with those signals. For completeness, we also show in Fig.~\\ref{fig:lisafomPsiMcDeltat} the result for intermediate and massive black hole systems, although we expect to observe merging systems for this mass range.\n\nWe now turn to the case of merging binaries. For these we compute the three error measures $\\epsilon_{\\Psi 2}$, $\\epsilon_{A1}$ and $\\epsilon_{d}$. To go beyond the crude analytical estimates built from~\\eqref{eq:timescalesNfstart} and~\\eqref{eq:estimatederivorb}-\\eqref{eq:estimatederivconst}, we use numerical derivatives for the timescales~\\eqref{eq:defTf}-\\eqref{eq:defTA} and for the derivatives in~\\eqref{eq:deffom}. We summarize the results in Fig.~\\ref{fig:fomLISA}, both for the orbital delay and the constellation response, considering equal-mass non-spinning systems with total masses of $M=10^{7} \\Msol$, $10^{4} \\Msol$ and $10^{2} \\Msol$ with a starting frequency corresponding to $\\Delta t =10 \\yr$ of observation. Since individual signals can show significant variation depending on the orientation parameters, for the full computation with numerical derivatives we show a geometric average of $\\epsilon$ over the sky position, inclination and polarization, together with $\\pm 1\\sigma$ geometric standard deviation. Here and in the following, for completeness we show results on the frequency band from $10^{-5}\\Hz$ to $1\\Hz$, while the signals are expected to have little signal-to-noise ratio outside of the band from $10^{-4}\\Hz$ to $10^{-1}\\Hz$, which is sometimes taken as a reference~\\cite{LISA17}.\n\nFor $\\epsilon_{\\Psi 2}$, as expected from~\\eqref{eq:TfN} we find a steep rise towards lower frequencies, which shows that considering merging binaries with a limited time to coalescence is crucial here. We note differences in behaviour between the orbital response, where for a fixed mass ratio the initial (10yr before merger) value of $\\epsilon_{\\Psi 2}$ grows towards lower masses, and the constellation response, where the initial $\\epsilon_{\\Psi 2}$ grows towards higher masses. Combining both parts of the response, for mergers with $10^2<M<10^7$, the error measure remains below $\\epsilon_{\\Psi 2} \\sim 0.1$, where the corrections are still well manageable by the perturbative formalism (as we will show in Sec.~\\ref{subsec:errorsLISA}).\n\nFor $\\epsilon_{A1}$, we find that the structure in the waveform close to merger does have a noticable but limited impact on the error measure. For the orbital response, the error measure remains small for all masses. For the constellation response, we find that $\\epsilon_{A1}$ can grow up to $\\sim 0.01$ at the lower end of the frequency band for high masses.\n\nThe $\\epsilon_{d}$ is signal-independent, and follows a quite different behaviour for the orbital and constellation responses. For the orbital response, $\\epsilon_{d}^{0}$ grows for higher frequencies, reaching $\\sim 0.1$ at around $1\\Hz$. For the constellation response, $\\epsilon_{d}^{L}$ is mainly important at lower frequencies, reaching $\\sim 0.01$ at around $10^{-5}\\Hz$.\n\nOverall, we find that for merging binaries the perturbative approach presented in Sec.~\\ref{sec:formalism} will be applicable on the whole LISA frequency band. The most relevant higher-order corrections are expected to be the phase corrections close to the starting frequency of the signal, and the delay correction at high frequencies for the orbital response. For slowly chirping binaries, we have identified regions in the parameter space where the perturbative formalism of Sec.~\\ref{sec:formalism} will break down, requiring an alternative approach presented below in Sec.~\\ref{subsec:comblisa}.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\subsection{Errors in the Fourier-domain response for merging binaries}\n\\label{subsec:errorsLISA}\n\nHaving at hand estimates for the relevance of higher-order corrections in the LISA response, we assess the performance of the leading-order treatment and we demonstrate that including higher-order corrections consistently reduces the reconstruction error of the Fourier-domain transfer function. We will consider two equal-mass and non-spinning systems for this illustration. The first will be a high-mass system with $M=10^{7} \\Msol$, entering the LISA band at $f=10^{-5}\\Hz$ and inspiralling for $\\Delta t = 3.8 \\yr$ before merging. The second will be a light system with $M=10^{2} \\Msol$, close to the mass range of SOBHs~\\cite{Sesana16}, starting at $\\Delta t = 10\\yr$ before merger and exiting the LISA band at $f=1\\Hz$. We will discuss SOBH systems farther away from merger in the next section. We will also focus on the orbital response and on the single-arm constellation response $y_{132}$, as TDI combinations will appear (within the approximations listed in Sec.~\\ref{subsec:modelLISA}) as linear combinations of these basic observables. The orientation angles chosen for these examples are $[\\lambda,\\beta,\\iota,\\psi] = [\\pi/4,\\pi/3,\\pi/3,0]$ for the ecliptic longitude, latitude, inclination and polarization respectively.\n\nOn one hand, we perform a numerical inverse Fourier transform (IFFT) of the Fourier-domain PhenomD waveform, process the signal through the time-domain response~\\eqref{eq:defresponse0} or~\\eqref{eq:defresponseL}, and perform a numerical Fourier transform (FFT). This gives us the target Fourier-domain waveform, considered to be exact but for possible numerical artifacts\\footnote{Numerical Fourier transforms include most notably oscillations induced by the necessary tapering of the signal. In the low-mass case, in practice we stitch together two frequency bands with different sampling rates, which leaves some visible residual in Figs.~\\ref{fig:LISAerrorM1e2orb} and~\\ref{fig:LISAerrorM1e2const}.}. On the other hand, we process the Fourier-domain signal through the response summarized in Sec.~\\ref{subsec:executivesummary}, including various higher-order corrections. We then compare the output of the two procedures.\n\nThe results for the orbital response~\\eqref{eq:defresponse0} are shown in Figs.~\\ref{fig:LISAerrorM1e7orb} and~\\ref{fig:LISAerrorM1e2orb} in amplitude and phase form. In both cases, in accordance with~\\eqref{eq:transfer0local}, the transfer function is essentially a phase, and contains many more cycles in the low-mass case in the higher frequency band. The leading-order treatment is accurate at $10^{-3}$ in the high-mass case, while in the low-mass case errors reach $10\\%$ at the start of observations and a few percent at high frequencies. In both cases, including higher-order corrections does reduce the reconstruction errors, with the distinctive feature that including only one of the amplitude and delay corrections can make the error actually worse, while including both does improve the accuracy down to $10^{-5}$ or better.\n\nFor the constellation response~\\eqref{eq:defresponseL}, we show the results in Figs.~\\ref{fig:LISAerrorM1e7const} and~\\ref{fig:LISAerrorM1e2const}, displaying the real and imaginary part of the transfer function. In the high-mass case, we rescale the response by the overall scaling $\\pi f L$ in~\\eqref{eq:GslrL}. The leading-order treatment reaches an inaccuracy of $\\sim 10\\%$ at the lowest frequencies of the high-mass case, while it is better than $10^{-3}$ for the low-mass case. Similarly to the orbital response, including all higher-corrections reduces the errors to better than $10^{-5}$, with the only exception of the high-mass case showing errors rising at the low-frequency end and beyond the ringdown frequency.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=.98\\linewidth]{LISAtransfererrorM1e7dO_py.pdf}\n  \\caption{Transfer function and residual for the orbital response~\\eqref{eq:defresponse0}, for an equal-mass system with $M=10^{7} \\Msol$. The first and second panels show the amplitude and phase of the transfer function. The bottom panel shows the relative modulus of the residual of the perturbative treatment~\\eqref{eq:summaryNAd}, with the color indicating the order of the approximation, compared to a numerical FFT. The starting frequency is set by the LISA sensitivity band at $10^{-5}\\mathrm{Hz}$, corresponding to $3.8\\mathrm{yr}$. The thick and thin vertical lines indicate the merger and ringdown frequencies.}\n  \\label{fig:LISAerrorM1e7orb}\n\\end{figure}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=.98\\linewidth]{LISAtransfererrorM1e2dO_py.pdf}\n  \\caption{Transfer function and residual for the orbital response~\\eqref{eq:defresponse0}, for an equal-mass system with $M=10^{2} \\Msol$. The panels are as in Fig.~\\ref{fig:LISAerrorM1e7orb}. The starting frequency corresponds to 10 years before merger. The ending frequency is set by the LISA sensitivity band at $1\\mathrm{Hz}$, and the merger is out of band. The jump in the residuals for $\\{N:3|A:1|d:1\\}$ is due to the fact that we split the band in two, with two different sampling rates, for the FFT; it shows that, at this level, the details of the conditioning for the FFT start to cause numerical errors in the reference transfer function.}\n  \\label{fig:LISAerrorM1e2orb}\n\\end{figure}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=.98\\linewidth]{LISAtransfererrorM1e7y12L_py.pdf}\n  \\caption{Transfer function and residual for the constellation response $y_{132}$~\\eqref{eq:defresponseL}, for an equal-mass system with $M=10^{7} \\Msol$. The top panel shows the real and imaginary parts of the transfer function, rescaled by the overall scaling $\\pi f L$ of the response at low frequencies, while the bottom panel shows the relative residuals compared to an FFT. The frequencies are the same as in Fig.~\\ref{fig:LISAerrorM1e7orb}.}\n  \\label{fig:LISAerrorM1e7const}\n\\end{figure}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=.98\\linewidth]{LISAtransfererrorM1e2y12L_py.pdf}\n  \\caption{Transfer function and residual for the constellation response $y_{132}$~\\eqref{eq:defresponseL}, for an equal-mass system with $M=10^{2} \\Msol$. The top panel shows the real and imaginary parts of the transfer function, without the rescaling of Fig.~\\ref{fig:LISAerrorM1e7const}. The bottom panels shows the residuals normalized by~\\eqref{eq:transferLenvelope} to avoid zero-crossings. The frequencies are the same as in Fig.~\\ref{fig:LISAerrorM1e2orb}, and the discontinuity in the residuals for $\\{N:3|A:1|d:1\\}$ is again due to the conditioning of the FFT.}\n  \\label{fig:LISAerrorM1e2const}\n\\end{figure}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\subsection{Slowly chirping binaries and direct approach for periodic modulations and delays}\\label{subsec:comblisa}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=.98\\linewidth]{LISACombExtent_py.pdf}\n  \\caption{Extent of the Fourier-domain comb entering the convolution~\\eqref{eq:transferdiscreteconvolution}, determined from the criterion~\\eqref{eq:criteriontruncationcomb} with truncation levels $\\eta=10^{-12}$, $10^{-6}$, $10^{-3}$. Blue corresponds to the orbital delay comb coefficients $c_{n}^{0}$ given by~\\eqref{eq:cn0}, and red to the constellation comb $c_{n}^{L}$ for the response~\\eqref{eq:GslrL}. The result is shown after averaging over 100 random orientation angles. Most of the slowly-chirping systems considered here will have $f \\lesssim 10^{-2}\\Hz$.}\n  \\label{fig:lisacombextent}\n\\end{figure}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=.98\\linewidth]{LISAtransfererrorSOBHepsPsi1d0corr_py.pdf}\n  \\caption{Transfer function and residual for the orbital delay $d_{0}$~\\eqref{eq:delay0}, for an SOBH with $\\epsilon_{\\Psi 2}\\sim 0.6$ for the orbital response. The frequency band corresponds to 4 years of observation for this system with $M=50\\Msol$, $\\Delta t = 200\\yr$ away from merger. The top panels show the transfer function amplitude and phase at various orders of approximation in~\\eqref{eq:summaryNAd}, with the numerical result of the FFT in black and the comb result~\\eqref{eq:transferdiscreteconvolution} in green. The bottom panel shows the relative residuals with respect ot the FFT.}\n  \\label{fig:LISAerrorSOBHepsPsi1d0}\n\\end{figure}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=.98\\linewidth]{LISAtransfererrorSOBHepsPsi10d0corr_py.pdf}\n  \\caption{Same as Fig.~\\ref{fig:LISAerrorSOBHepsPsi1d0}, but for an SOBH with $\\epsilon_{\\Psi 2}\\sim 4.5$ for the orbital response. The frequency band corresponds to 4 years of observation for this system with $M=15\\Msol$, $\\Delta t = 1500\\yr$ away from merger. The perturbative treatment breaks down in this case, with errors of order 1.}\n  \\label{fig:LISAerrorSOBHepsPsi10d0}\n\\end{figure}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=.98\\linewidth]{LISAtransfererrorSOBHepsPsi1y12L_py.pdf}\n  \\caption{Transfer function and residual for the constellation response $y_{132}$~\\eqref{eq:GslrL}, for the same SOBH as in Fig.~\\ref{fig:LISAerrorSOBHepsPsi1d0}. Here $\\epsilon_{\\Psi 2}\\sim 0.01$ for the constellation part of the response. The top panel shows the real and imaginary part of the transfer function.}\n  \\label{fig:LISAerrorSOBHepsPsi1const}\n\\end{figure}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=.98\\linewidth]{LISAtransfererrorSOBHepsPsi10y12L_py.pdf}\n  \\caption{Transfer function and residual for the constellation response $y_{132}$~\\eqref{eq:GslrL}, for the same SOBH as in Fig.~\\ref{fig:LISAerrorSOBHepsPsi10d0}. Here $\\epsilon_{\\Psi 2}\\sim 0.1$ for the constellation part of the response. The top panel shows the real and imaginary part of the transfer function.}\n  \\label{fig:LISAerrorSOBHepsPsi10const}\n\\end{figure}\n\nAs explained in Sec.~\\ref{subsec:lisafom}, slowly-chirping binaries can be problematic for the perturbative formalism of Sec.~\\ref{sec:formalism}. Indeed, when far enough from merger, SOBH systems~\\cite{Sesana16} can have error estimates $\\epsilon_{\\Psi 2}$ reaching and exceeding $1$, as shown in Fig.~\\ref{fig:lisafomPsiMcDeltat}. Here we investigate these sources in more details, and propose an alternative treatment for their instrument response.\n\nFirst, we should mention that these signals share similarities with the galactic binaries that will provide numerous quasi-monochromatic signals in the LISA band~\\cite{Nelemans+01, LISA17}. They are far from merger, slowly chirping, and span only a narrow frequency band over the course of the LISA mission lifetime, although being less monochromatic that galactic binaries. For the galactic binaries, an accurate and efficient numerical treatment of the response has been proposed and widely used in applications~\\cite{CL07}. This treatment is referred to as the fast-slow decomposition, or heterodyning approach. If the gravitational wave signal extends only on the narrow frequency band $f \\in [f_{*}, (1+\\eta) f_{*}]$ with $\\eta \\ll 1$, then scaling out a carrier frequency of the signal by multiplying by $e^{-2 i \\pi f_{*} t}$ will eliminate most of the time variability, allowing to process the signal through the time-domain response and to take a FFT with a Nyquist frequency shifted from $(1+\\eta) f_{*}$ to $\\eta f_{*}$, i.e. with a much smaller number of samples. This multiplication is simply equivalent to a shift in frequency domain, which can be restored after the numerical FFT has been computed. The efficiency of this approach is contingent to the smallness of $\\eta$. Galactic binaries are extremely close to monochromatic~\\cite{Nelemans+01}, and this quantity can be as low as $10^{-6}-10^{-7}$. For SOBH systems, however, $\\eta$ will take a continuous set of values from roughly $10^{-4}$ to $5$. Although the systems for which $\\eta$ is the largest are also the easiest to treat with the perturbative formalism of Sec~\\ref{sec:formalism}, we propose here yet a third method, based on a discrete Fourier comb, making sure we can cover the intermediate ground of slowly-chirping systems with a large $\\eta$. We leave for the future a more detailed study of SOBH systems as a population, and the investigation of the precise boundaries and overlap areas of the three methods (heterodyning, Fourier comb, perturbative) as well as their respective computational costs.\n\nThe Fourier comb approach we propose here exploits the fact that, in the LISA case, the modulations and delays entering~\\eqref{eq:yslr} are periodic, with a period of one year and a frequency $f_{0} = \\Omega_{0}/2\\pi = 1/\\mathrm{yr} \\simeq 3.2\\times 10^{-8}\\mathrm{Hz}$. For any given frequency $f$, $G(f,t)$ is periodic in time, so that~\\eqref{eq:defG} becomes a discrete Fourier series\n\\be\\label{eq:Gdiscretefourier}\n\tG(f,t) = \\sum_{n \\in \\mathbb{Z}} c_{n}(f) e^{-in\\Omega_{0}t} \\,,\n\\ee\nwith frequency-dependent discrete Fourier coefficients (that we will also call comb coefficients) given by the integrals (we recall our Fourier convention~\\eqref{eq:defFT})\n\\be\\label{eq:defcn}\n\tc_{n}(f) = \\frac{\\Omega_{0}}{2\\pi} \\int_{0}^{\\frac{2\\pi}{\\Omega_{0}}} \\ud t \\, e^{i n \\Omega_{0} t} G(f,t) \\,.\n\\ee\nFor slowly-chirping systems, the orbital-delay part of the response gives a transfer function that has significant structure, by contrast with fast-chirping systems where it reduces essentially to an extra phase contribution. Thus, in practice this approach is to be applied to $G(f,t)$ representing the full response, orbital delay and constellation modulation.\n\nFor illustration purposes, however, we will keep the orbital and constellation response separated in the following. In the case of the orbital delay, with $G_{0}(f,t)$ given by~\\eqref{eq:G0} and~\\eqref{eq:delay0}, the particularly simple expression of the delay gives an analytic expression for the coefficients $c_{n}^{0}$ in terms of Bessel functions of the first kind, as\n\\be\\label{eq:cn0}\n\tc_{n}^{0} = i^{n} e^{i n \\lambda} J_{n} \\left[ -2 \\pi f R \\cos \\beta \\right]\\,.\n\\ee\nBy contrast, for the constellation response (or for the full response), to our knowledge the coefficients $c_{n}^{L}$ do not admit such a simple close-form expression, and they must be computed numerically using the integrand given by~\\eqref{eq:GslrL}. Truncating~\\eqref{eq:Gdiscretefourier} to a finite order $N$, this computation reduces to an FFT and the $c_{n}$ coefficients are given by~\\eqref{eq:ykDFT} and~\\eqref{eq:ckyk}.\n\nInserting~\\eqref{eq:Gdiscretefourier} into the convolution~\\eqref{eq:FDkernel} leads to the following generalized discrete convolution:\n\\be\\label{eq:transferdiscreteconvolution}\n\t\\tilde{s}(f) = \\sum_{n \\in \\mathbb{Z}} c_{n}(f - n f_{0}) \\tilde{h} (f - n f_{0}) \\,.\n\\ee\nThus, computing the Fourier-domain response now requires to convolve the signal with a discrete comb with frequency-dependent coefficients $c_{n}$. In practice, this sum is to be truncated at $|n|\\leq N_{\\rm comb}$, for some finite order $N_{\\rm comb}$ determining the accuracy of the approximation. To assess the expected truncation error, we use a simple criterion based on the $L^{1}$-norm of the $\\{c_{n}\\}$ sequence. For a given target truncation error $\\eta$, we define the truncation $N_{\\rm comb}(f, \\eta)$ as the smallest integer such that\n\\be\\label{eq:criteriontruncationcomb}\n\t\\sum_{|n| > N(f, \\eta)} |c_{n}(f)| < \\eta \\,.\n\\ee\nThe truncation order $N_{\\rm comb}(f,\\eta)$ is frequency-dependent, and also depends on the orientation angles. For $c_{n}^{0}$, the expression~\\eqref{eq:cn0} can provide an asymptotic bound on the width of the comb. For large values of $n$ we have indeed the equivalent $| J_{n}[z] | \\sim (e z/2n)^{n}/\\sqrt{2\\pi n} \\; \\left[ n\\rightarrow + \\infty \\right]$ (see (10.19) in~\\cite{DLMF}), so that a conservative estimate for the truncation order (almost independent of $\\eta$) is given by $N_{\\rm comb} \\geq  |e \\pi f R \\cos \\beta|$. Fig.~\\ref{fig:lisacombextent} shows numerical computations for $N_{\\rm comb}(f,\\eta)$, averaged over orientation angles, for both the constellation and the orbital response and for the truncation levels  $\\eta=10^{-12}$, $10^{-6}$, $10^{-3}$. We see that, especially at high frequencies, the orbital response requires more coefficients than the constellation response due to the longer baseline of the delay. The majority of systems for which we wish to apply the comb method will have frequencies $\\lesssim 10^{-2}\\Hz$, where for the orbital response $N_{\\rm comb} \\simeq 40$.\n\nAn important point is that, since the signals from slowly-chirping binaries extend on a narrow frequency band, for both responses the frequency-dependence of $c_{n}^{0}(f)$, $c_{n}^{L}(f)$ will be very mild, so that the coefficients can be computed at two or three frequencies and interpolated in-between. The computational cost of this approach is then set by the convolution~\\eqref{eq:transferdiscreteconvolution} that must be evaluated at as many frequencies as necessary to interpolate the transfer functions as functions of frequency (for examples, see Figs.~\\ref{fig:LISAerrorSOBHepsPsi1d0}, \\ref{fig:LISAerrorSOBHepsPsi10d0}, \\ref{fig:LISAerrorSOBHepsPsi1const} and~\\ref{fig:LISAerrorSOBHepsPsi10const}). In general, this Fourier comb approach will be more expensive than the perturbative response of Sec.~\\ref{subsec:executivesummary}. We leave for future work a proper assessment of the computational performance of this method compared to the others.\n\nWe now illustrate this approach by considering two examples of equal-mass SOBH systems. The first has $M = 50\\Msol$ and is $\\Delta t = 200\\yr$ away from merger, and for the orbital response $\\epsilon_{\\Psi 2} \\simeq 0.6$. The second has $M = 15\\Msol$ and is $\\Delta t = 1500\\yr$ away from merger, and for the orbital response $\\epsilon_{\\Psi 2} \\simeq 4.5$. The phase error measures for the constellation response are smaller, $\\epsilon_{\\Psi_{2}} \\simeq 0.1$ and $0.01$ respectively. In keeping with the previous section, in our presentation we separate the orbital and the constellation response, keeping in mind that in practice the full response is to be handled in one step.\n\nThe transfer functions for the orbital response and residual errors are shown for the two systems in Figs.~\\ref{fig:LISAerrorSOBHepsPsi1d0} and~\\ref{fig:LISAerrorSOBHepsPsi10d0}. We see that, contrarily to Sec.~\\ref{subsec:errorsLISA}, the transfer function starts to develop more structure that just a phase contribution. The case $M=50\\Msol$ with $\\epsilon_{\\Psi 2} \\simeq 0.6$ shows that the leading-order treatment leads to relative errors of order $10\\%$, while increasing $N$ to 5 or 20 brings the errors back to $\\sim 10^{-4}$, with a marginal improvement from further amplitude and delay corrections. The case $M=50\\Msol$ with $\\epsilon_{\\Psi 2} \\simeq 4.5$, by contrast, is clearly outside the range of applicability of the perturbative formalism, as all orders of approximation give errors of order $100\\%$. In both cases, the comb treatment performs well, at better than $10^{-4}$.\n\nFor the constellation response, the transfer functions and residual errors are shown for the two systems in Figs.~\\ref{fig:LISAerrorSOBHepsPsi1const} and~\\ref{fig:LISAerrorSOBHepsPsi10const}. Here, with $\\epsilon_{\\Psi 2} \\sim 0.01$ and $0.1$, both systems are within reach of the perturbative formalism, although the case  $\\epsilon_{\\Psi 2} \\sim 0.1$ shows errors of $10\\%$ at leading order and requires a rather large $N=20$ to reach errors below $10^{-3}$. The comb treatment yields again errors below $10^{-4}$ in both cases.\n\nThus, we have shown that some slowly-chirping systems will be out of reach of the perturbative treatment of Sec.~\\ref{subsec:executivesummary}, and we have demonstrated that the Fourier comb approach presented here could be applied to these systems with a good accuracy.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Application to waveforms from precessing binaries}\n\\label{sec:precession}\n\nIn this Section, we illustrate the application of the formalism described in~\\ref{sec:formalism} to signals from precessing binaries, with modulations induced by the precession. We investigate how the separation of the relevant timescales evolves in the late inspiral and after the merger occurs. We will also give in App.~\\ref{app:precpreviousapproaches} a short overview of previous approaches to this problem of the Fourier-domain precession, and how they relate to our formalism.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\subsection{Precession and frame decomposition}\n\\label{subsec:precdef}\n\nAs we already discussed in Sec.~\\ref{subsec:modulationPrec}, in the presence of spin components that are not aligned with the orbital angular momentum, an inspiraling binary system will undergo precession of its orbital plane~\\cite{Apostolatos+94, Kidder95}. This is a crucial effect to be taken into account in the modelling of such signals.\n\nAs proposed by several authors~\\cite{BCV03b, BCPTV05, Schmidt+10, OShaughnessy+11, Boyle+11}, if one performs the mode decomposition of the waveform~\\eqref{eq:defmodes} not in a fixed inertial frame but rather in a time-dependent, rotating frame that follows the plane of the orbit, it is possible to restore much of the structure of a non-precessing waveform. In particular, one recovers qualitatively the hierarchy of mode amplitudes that prevails for non-precessing systems, with the modes $h_{22}$ and $h_{2,-2}$ being dominant, and with each harmonic mode characterized by a chirp with smoothly evolving amplitude and phase. In the following, we will identify the $z$-axis of the co-precessing frame as the dominant eigenvector of the matrix representing the action of the angular momentum operator acting on the waveform modes, as proposed in~\\cite{OShaughnessy+11} (see App.~\\ref{app:wigner} for more details).\n\nWe define $(\\alpha, \\beta, \\gamma)$ as the Euler angles of the active rotation from the inertial frame to the precessing frame, in the $(z,y,z)$ convention. The first two angles, $\\alpha$ and $\\beta$, are the two spherical angles tracking the direction of the radiation axis, which during the inspiral follows essentially the normal to the orbital plane. The last angle $\\gamma$ parametrizes the remaining freedom of rotation around this radiation axis. To fix this third degree of freedom, we use the minimal rotation condition~\\cite{Boyle+11}, enforcing the absence of rotation of the precessing frame around the radiation axis. In terms of Euler angles, this condition translates to\n\\be\\label{eq:gammadot}\n\t\\dot{\\gamma} = -\\dot{\\alpha}\\cos \\beta \\,.\n\\ee\nA natural choice for the $z$ axis of the inertial frame is the direction of $\\bm{J}$, the total angular momentum, which is almost constant\\footnote{Except in the cases of transitional precession~\\cite{Apostolatos+94}, where for high mass ratios and large antialigned spins the orbital angular momentum and the spin can almost cancel each other.}. Quite generically, and in particular in the case of simple precession~\\cite{Apostolatos+94, Kidder95} but also in the model we will take for the post-merger precession, the radiation axis precesses on a cone around the direction of $\\bm{J}$, with $\\alpha$ increasing, while $\\beta$, the opening angle of the precession cone, is slowly varying.\n\nThe modes in the inertial frame $h_{\\ell m}^{\\rm I}$ and the modes in the precessing frame $h_{\\ell m}^{\\rm P}$ are then related by~\\cite{Goldberg+67}\n\\begin{subequations}\n\\label{eq:wignerrot}\n\\begin{align}\n\th_{\\ell m}^{\\rm I} = \\sum\\limits_{m=-\\ell}^{\\ell} \\calD^{\\ell *}_{mm'} (\\alpha,\\beta,\\gamma) h_{\\ell m'}^{\\rm P} \\,, \\\\\n\th_{\\ell m}^{\\rm P} = \\sum\\limits_{m=-\\ell}^{\\ell} \\calD^{\\ell }_{m'm} (\\alpha,\\beta,\\gamma) h_{\\ell m'}^{\\rm I} \\,.\n\\end{align}\n\\end{subequations}\nNotice that there is no mixing of the modes with different values of $\\ell$. Here the coefficients $\\calD^{\\ell}_{mm'}$ are given by Wigner D-matrices~\\cite{Wigner59} as\n\\be\\label{eq:defWignerD}\n\t\\calD^{\\ell}_{mm'} (\\alpha, \\beta, \\gamma) = e^{im \\alpha} d^{\\ell}_{mm'}(\\beta) e^{im' \\gamma}\\,.\n\\ee\nHere, the real-valued Wigner d-matrix $d^{\\ell}_{mm'}(\\beta)$ takes the form of a polynomial in $\\cos (\\beta/2)$, $\\sin (\\beta/2)$, and acts as an amplitude for the modulation function. We refer to App.~\\ref{app:wigner} for explicit expressions.\n\nIn the following, our objective will be to compute mode-by-mode transfer functions $\\calT^{\\ell}_{mm'}$, defined as\n\\be\\label{eq:defprectransfer}\n\t\\mathrm{FT} \\left[ \\calD^{\\ell *}_{mm'} (\\alpha,\\beta,\\gamma) h_{\\ell m'}^{\\rm P} \\right] (f) \\equiv \\calT^{\\ell}_{mm'}(f) \\tilde{h}_{\\ell m'}^{\\rm P} (f)\n\\ee\nsuch that the complete Fourier-domain inertial-frame waveform will be given as the sum of these individual mode contributions,\n\\be\\label{eq:defprechIsum}\n\t\\tilde{h}_{\\ell m}^{\\rm I} (f) = \\sum\\limits_{m'=-\\ell}^{\\ell} \\calT^{\\ell}_{mm'}(f) \\tilde{h}_{\\ell m'}^{\\rm P} (f) \\,.\n\\ee\nIn the notation that we used in Sec.~\\ref{sec:formalism}, in the absence delays, we wish to compute the convolutions\n\\be\\label{eq:precconvolution}\n\t\\tilde{s} (f) = \\int df' \\; \\tilde{F}(f') \\tilde{h} (f-f') \\,,\n\\ee\nwith $\\tilde{s}(f)$ being one mode contribution to $\\tilde{h}_{\\ell m}^{\\rm I} (f)$ in~\\eqref{eq:defprechIsum}, $\\tilde{h}$ being one of the P-frame modes $\\tilde{h}_{\\ell m'}^{\\rm P} (f)$, and the modulation $F(t)$ being one of the time-dependent Wigner matrices $\\calD^{\\ell *}_{mm'}$.\n\nAn important qualitative observation is that the opening angle $\\beta$ is typically small. Large misalignments between $\\bm{J}$ and $\\bm{\\ell}$ can only be reached with large spins and large mass ratios. When $\\beta$ is small, from the explicit expression~\\eqref{eq:defWignerdapp}, one can see that $d^{\\ell}_{mm'}(\\beta)$ is greatly suppressed in the limit $\\beta \\rightarrow 0$ when increasing $|m-m'|$. Intuitively, this means that, in the limit of a small misalignment between frames, the rotation produces mainly mode contributions with the same mode number. Additionally, when $\\beta$ is constant or slowly varying, \\eqref{eq:gammadot} gives $\\gamma \\simeq - \\alpha \\cos\\beta$, and we have in that case\n\\be\\label{eq:wignerphasesimpleprec}\n\t\\calD^{\\ell *}_{mm'} (\\alpha, \\beta, \\gamma) \\propto e^{i(m' \\cos\\beta - m) \\alpha} \\,,\n\\ee\nwith $\\cos\\beta \\simeq 1$ for small $\\beta$. This shows that the modulation for $m=m'$ has a suppressed phase, while increasing $|m-m'|$ increases the magnitude of the modulation phase. Thus, modulation functions for distant mode contributions (for instance from the $h^{\\rm P}_{22}$ mode all the way to the $h^{\\rm I}_{2,-2}$ mode) have larger phase evolutions, but smaller amplitudes.\n\nThe relations~\\eqref{eq:wignerrot} do not mix different values of $\\ell$. Furthermore, rotations leave invariant the combined square amplitude $\\calA_{\\ell}$ for each $\\ell$, as well as the total square amplitude:\n\\be\\label{eq:defsumamplitude}\n\t\\calA^{2} = \\sum\\limits_{\\ell \\geq 2}\\calA_{\\ell}^{2} = \\sum\\limits_{\\ell \\geq 2}\\sum\\limits_{m=-\\ell}^{\\ell} |h_{\\ell m}|^{2} \\,.\n\\ee\nOne can therefore use these amplitudes (in our case, limited to $\\ell = 2$) to define a frame-independent peak amplitude of the precessing waveform.\n\nThe dominant features of the the precessing-frame waveform are approximately reflection symmetric about the orbital plane (exactly valid for non-precessing systems, see~\\eqref{eq:symmetryhlminusm}), implying\n\\be\\label{eq:approxsymmetryhlminusm}\n\th^{\\rm P}_{\\ell,-m} \\simeq (-1)^{\\ell} h^{\\rm P*}_{\\ell,m} \\,.\n\\ee\nSimilarly, in the Fourier domain, one can neglect either the negative or positive frequency band in the Fourier transform of precessing-frame modes (as in~\\eqref{eq:zeronegativef})\n\\begin{align}\\label{eq:approxzeronegativef}\n\t\\tilde{h}_{\\ell m}^{\\rm P} (f) &\\simeq 0 \\text{ for } f<0, \\; m>0 \\nn\\,,\\\\\n\t\\tilde{h}_{\\ell m}^{\\rm P} (f) &\\simeq 0 \\text{ for } f>0, \\; m<0 \\,,\n\\end{align}\nand neglect altogether the $m=0$ modes, $\\tilde{h}_{\\ell 0}^{\\rm P} (f) \\simeq 0$.\n\nWhen using the approximations~\\eqref{eq:approxsymmetryhlminusm}-\\eqref{eq:approxzeronegativef}, one can derive a symmetry relation in the transfer functions themselves. From the explicit expression of the Wigner matrices, we have indeed (see App.~\\ref{app:wigner})\n\\be\n\t\\calD^{\\ell *}_{-m,-m'} = (-1)^{m+m'}\\calD^{\\ell}_{mm'} \\,.\n\\ee\nSince for a function $g$ we have in general for its conjugate\n\\be\n\t\\mathrm{FT}[g^{*}](-f) = \\tilde{g}(f)^{*} \\,,\n\\ee\nwe can write, using~\\eqref{eq:approxsymmetryhlminusm},\n\\be\n\t\\mathrm{FT}[\\calD^{\\ell *}_{mm'} h_{\\ell m'}^{\\rm P}](-f)^{*} = (-1)^{\\ell+m+m'} \\mathrm{FT}[\\calD^{\\ell *}_{-m,-m'} h_{\\ell, -m'}^{\\rm P}](f) \\,,\n\\ee\nor, for transfer functions,\n\\be\n\t\\calT^{\\ell}_{mm'}(f) = (-1)^{m+m'} \\calT^{\\ell *}_{-m,-m'}(-f) \\,.\n\\ee\nThis means that such a model is required to cover only the positive frequency band and the values $m'>0$, since\n\\begin{align}\\label{eq:hIlmposnegfreq}\n\t\\tilde{h}^{\\rm I}_{\\ell m}(f) &= \\sum_{m'>0} \\calT^{\\ell}_{mm'}(f) \\tilde{h}^{\\rm P}_{\\ell, m'}(f) \\text{ for } f>0 \\,, \\nn\\\\\n\t\\tilde{h}^{\\rm I}_{\\ell m}(f) &= \\sum_{m'>0} (-1)^{\\ell+m+m'} \\calT^{\\ell *}_{-m,m'}(-f) \\tilde{h}^{\\rm P *}_{\\ell, m'}(-f) \\text{ for } f<0 \\,.\n\\end{align}\n\nFurther simplifications occur when including only the dominant harmonics $h^{\\rm P}_{22}$, $h^{\\rm P}_{2,-2}$ in the precessing-frame waveform (as is done for instance in PhenomP~\\cite{Hannam+13}, as well as in our toy model~\\ref{subsec:precmodel}), we have in this case for $f<0$\n\\be\n\t\\calT^{2}_{m,-2}(f) = (-1)^{m} \\calT^{2 *}_{-m,2}(-f) \\,,\n\\ee\nwhich for both $f>0$ and $f<0$ translates into\n\\be\\label{eq:symmetryhIfor22only}\n\t\\tilde{h}^{\\rm I}_{2 m}(f) = (-1)^{m} \\tilde{h}^{\\rm I *}_{2,-m}(-f) \\,.\n\\ee\nWhen reconstructing the polarizations $h_{+},h_{\\times}$ according to~\\eqref{eq:hpcfrommodes}, we have in this case\n\\be\n\t\\tilde{h}_{+,\\times} (f) = \\sum_{m = -2}^{2} L^{+,\\times}_{2 m} \\tilde{h}^{\\rm I}_{2 m}(f) \\,,\n\\ee\nwhere we defined\n\\begin{align}\n\tL^{+}_{\\ell m} &\\equiv \\frac{1}{2} \\left( {}_{-2}Y_{\\ell m} + (-1)^{m} {}_{-2}Y_{\\ell, -m}^{*} \\right) \\,, \\nn\\\\\n\tL^{\\times}_{\\ell m} &\\equiv \\frac{i}{2} \\left( {}_{-2}Y_{\\ell m} - (-1)^{m} {}_{-2}Y_{\\ell, -m}^{*} \\right) \\,.\n\\end{align}\n\nFinally, we note that with the restriction to $\\ell = 2$ and $m' = 2$, in the approximate phase given in Eq.~\\eqref{eq:wignerphasesimpleprec}, the coefficient of $\\alpha$ is close to $0$ for small $\\beta$ for $m=2$, and increasingly positive when going down from $m=1$ to $m=-2$. In our Fourier convention~\\eqref{eq:defFT}, the Fourier transforms $\\tilde{F}$ thus have most of their support on negative frequencies. This means that the support of the convolution integral~\\eqref{eq:precconvolution} extends to the right side for $\\tilde{h}$, i.e. $f-f' > f$. This point will become important when considering the high-frequency part of the signal in Sec.~\\ref{subsec:trigopoly}. Note, however, that this statement might not be true anymore when including more modes in our model, in particular modes $\\ell \\neq m$.\n\n\\subsection{Simplified model for precessing IMR waveforms}\n\\label{subsec:precmodel}\n\nWe wish to apply the formalism presented in Sec.~\\ref{sec:formalism} to IMR waveforms of precessing binaries, exploring the separation of the timescales involved through the inspiral and merger, and assessing the relevance of the higher-order corrections summarized in~\\ref{subsec:executivesummary}. To this end, we will use a simplified model for the precession, allowing a number of simplifications and idealizations.\n\nWe want to be able to investigate generic-spin signals with a long inspiral phase, beyond the range covered by numerical relativity simulations, and we want to include the merger and ringdown phase. We will use the following three ingredients for this simplified model:\n\\begin{itemize}\n\t\\item PhenomD~\\cite{Husa+15, Khan+15} for the IMR Fourier-domain waveform in the precessing frame;\n\t\\item SEOBNRv3~\\cite{Pan+13, BTB16} for the Euler angles during the inspiral;\n\t\\item an effective extension of the Euler angles post-merger based on~\\cite{OShaughnessy+12} (see~\\eqref{eq:OmegaframeQNM} below).\n\\end{itemize}\n\nFor the precessing-frame waveform, we make all the simplifying assumptions described above in Sec.~\\ref{subsec:precdef}: we approximate it as a non-precessing waveform, further enforcing the approximations~\\eqref{eq:approxsymmetryhlminusm} and~\\eqref{eq:approxzeronegativef}. Limiting our analysis to the dominant harmonics $h^{\\rm P}_{22}$ and $h^{\\rm P}_{2,-2}$, we will use the PhenomD waveform model~\\cite{Husa+15, Khan+15}, an aligned-spin Fourier-domain model publicly available in the LIGO Algorithm Library (LAL) that covers the inpiral, merger and ringdown for binaries with generic spin magnitude\\footnote{See~\\cite{London+17} for a recent extension of the model to include higher harmonics.}. The amplitude and phase of the waveform are produced as piecewise analytical functions of the frequency. Using a Fourier-domain approximant that is smooth by construction avoids the Gibbs oscillations induced by the tapering of of finite-length time-domain waveforms, and will allow us to easily take Fourier-domain derivatives of the waveform\\footnote{Note that the PhenomD amplitude and phase are smooth on three separate frequency bands (inspiral, intermediate, and ringdown) with junction conditions that are only of class $C^{1}$. To avoid spurious discontinuities, we introduce decaying corrective terms of the form $(f-f_{\\rm join})^{2} e^{-\\lambda(f-f_{\\rm join})^{2}}$ on each side of $f_{\\rm join}$, the junction frequency between any two given bands, resulting in functions of class $C^{2}$.}.\n\nFor the frame trajectory in the inspiral phase, we use an SEOBNRv3 waveform~\\cite{Pan+13, BTB16}, that incorporates all degrees of freedom of both spins. As the inspiral of the SEOBNRv3 waveform is constructed by using the instantaneous orbital plane of the dynamics as the precessing frame, the frame extraction procedure of~\\cite{OShaughnessy+11} simply returns the normal to the orbital plane as the radiation axis. The frame thus presents oscillatory features of small amplitude at the orbital timescale, due to the nutation of the orbital plane, which we smooth out using a Gaussian filtering with width based on the orbital phase as in~\\cite{Blackman+17a}.\n\nAn extension is required in specifying a model for the precession post-merger. After the merger occurs, the intuitive interpretation of the precessing frame as roughly following the orbital plane of the binary is lost. However, the prescription of~\\cite{OShaughnessy+11} to extract the radiation axis is based entirely on the waveform itself, and can be applied to the ringdown as well. For $\\ell=2$, analyzing numerical relativity waveforms, Ref.~\\cite{OShaughnessy+12} described a qualitative model where the radiation axis essentially keeps precessing around the final angular momentum $\\bm{J}$, but transitions to a faster precession rate, with an angular velocity determined by the quasinormal mode (QNM) frequencies of the remnant black hole as\n\\be\\label{eq:OmegaframeQNM}\n\t\\Omega_{\\rm frame} = \\omega_{220}^{\\rm QNM} - \\omega_{210}^{\\rm QNM} \\,.\n\\ee\nThis implies a significant acceleration of the precession post-merger with respect to the inspiral (see Fig.~\\ref{fig:precmodel}). For the opening angle of the precessing cone $\\beta$, Ref.~\\cite{OShaughnessy+12} proposes an exponential decay driven similarly by the difference between damping frequencies. We found by inspection of various precessing waveforms currently available in the SXS catalog (see e.g.~\\cite{SXScatalog, Mroue+12, Mroue+13}) that this picture is at least qualitatively correct for $\\ell=2$, with $\\beta$ appearing to transition to a lower value rather than decaying all the way to zero. By contrast, we found that the current ringdown prescription in the SEOBNRv3 model can cause a qualitatively different behaviour, with oscillations in $\\beta$.\n\nIn our model, after reaching the time of peak amplitude as defined in~\\eqref{eq:defsumamplitude}, we will use the prescription~\\eqref{eq:OmegaframeQNM} for the post-merger frame precession and simply keep $\\beta$ constant,\n\\begin{subequations}\\label{eq:eulerQNM}\n\\begin{align}\n\t\\alpha_{\\rm post-merger}(t) &= \\alpha(t_{\\rm peak}) + (\\omega_{220}^{\\rm QNM} - \\omega_{210}^{\\rm QNM})(t-t_{\\rm peak}) \\,, \\\\\n\t\\beta_{\\rm post-merger}(t) &= \\beta(t_{\\rm peak}) \\,, \\\\\n\t\\gamma_{\\rm post-merger}(t) &= \\gamma(t_{\\rm peak}) - (\\alpha(t) - \\alpha(t_{\\rm peak}) )\\cos \\beta \\,,\n\\end{align}\n\\end{subequations}\nwhere we use the minimal-rotation condition~\\eqref{eq:gammadot} for a constant $\\beta$. To compute the QNM frequencies as a function of the final spin $\\chi_{f}$, we use fits constructed in Ref.~\\cite{Berti+05}, illustrated in Fig.~\\ref{fig:QNM}. The final spin is taken to be the same as the one computed internally to the SEOBNRv3 code~\\cite{Pan+13, BTB16}, where the final-spin fit formula of Ref.~\\cite{BR09}, built for spin-aligned systems, is applied to the spin components projected on the orbital angular momentum $\\bm{L}$ at merger.\n\nFig.~\\ref{fig:precmodel} presents a comparison of the frame trajectory at merger for the SEOBNRv3, NR waveforms and for our model~\\eqref{eq:eulerQNM}. The example catalog waveform is SXS:BBH:0058, generated with SpEC~\\cite{SXScatalog, SpEC, Mroue+12, Mroue+13}, with a mass ratio of $q=5$, and a single in-plane spin of $\\chi_{1} = 0.5$. The NR and SEOB post-merger frames disagree mainly due to a different value of the final spin $\\chi_{f}$\\footnote{To compute $\\chi_{f}$, SEOBNRv3 uses fitting formulas from~\\cite{BR09}. Using updated formulas incorporating additional NR data (see e.g.~\\cite{HBR16}) would reduce or remove this disagreement.}, which leads to a different $\\Omega_{\\rm frame}$. Given their different value of $\\chi_{f}$, however, both agree with the qualitative description~\\eqref{eq:OmegaframeQNM}. The oscillations developing after $t\\sim 50 M$ occur in a regime where the overall waveform amplitude has decayed to small values. Our simple model~\\eqref{eq:eulerQNM} follows well the SEOBNRv3 behaviour for $\\alpha$ and $\\gamma$, but departs more for $\\beta$ as we do not model its variation at merger.\n\nIn this paper, we will need this model only as an example for demonstrating our frequency-domain precession response, and we only ask that it represents the qualitative features of a precessing waveform. In that context, we would like to underline a number of caveats and limitations of our simplified model. First, it is clear from Fig.~\\ref{fig:precmodel} that the acceleration of the precession post-merger is going to be the most challenging feature for the separation of timescales at the basis of Sec.~\\ref{sec:formalism}. While we checked the qualitative soundness of the decomposition outlined in Sec.~\\ref{subsec:precdef} and of the post-merger precession~\\eqref{eq:OmegaframeQNM} in some of the available numerical relativity waveforms~\\cite{SXScatalog}, it is important to stress that there is no guarantee that another prescription for the precessing frame would not yield a better separation of timescales. Secondly, approximating the precessing-frame waveform by a spin-aligned one comes with known limitations, ignoring for instance mode asymmetries departing from~\\eqref{eq:approxsymmetryhlminusm} as shown in~\\cite{Boyle+14}. Thirdly, more exploration of the parameter space would be needed, as the QNM frequencies entering~\\eqref{eq:OmegaframeQNM} vary rapidly for large $\\chi_{f}$. Finally, we ensure the smoothness both of the Fourier-domain precessing-frame waveform and of the time-domain modulation, allowing us to take the derivatives required by the formalism of Sec.~\\ref{sec:formalism}, which is an idealization.\n\nLeaving aside the question of a more in-depth investigation of the best representation of precessing waveforms in their post-merger phase, we will proceed to investigating the separation of timescales in three chosen examples. The parameters of these example cases are summarized in Table~\\ref{tab:precparams}. We consider a mass ratio of $q=4$, close-to-maximal spins of $\\chi_{1} = \\chi_{2} = 0.95$, and vary both spins misalignmnent angles to be $\\pi/6$ (case labeled $++$, close to aligned spins), $\\pi/2$ ($\\perp\\perp$, spins in the plane) and $5\\pi/6$ ($--$, close to anti-aligned spins). Table~\\ref{tab:precparams} also shows the remnant spins that are internally computed in both the SEOBNRv3 and the PhenomD/PhenomP codes, as well as the QNM frequencies and the resulting frame precession frequency $\\Omega_{\\rm frame}$. Note that the case $--$ shows a larger variation in the direction of $\\bm{J}$, and the spin of the remnant is almost 0, due to the fact that the spin is large and antialigned with a large mass ratio. This example therefore serves the purpose of lying at the edge of validity of the picture of standard precession along a cone around an almost-fixed direction, and the standard hierarchy between mode contributions is not valid in this case.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=.98\\linewidth]{eulerSXS0058_py.pdf}\n  \\caption{Evolution of Euler angles $(\\alpha, \\gamma)$ (top panel) and $\\beta$ (bottom panel) near merger for the example SpEC waveform SXS:BBH:0058~\\cite{SpEC, SXScatalog, Mroue+12, Mroue+13}. Full, dashed and dotted lines represent the NR, SEOB and extended SEOB waveforms respectively. The vertical line at $t=0$ indicates the time of merger. In the left panel the full and dashed black lines indicate the asymptotic behaviour~\\eqref{eq:OmegaframeQNM} for the rotation of the frame around the direction of the final $\\bm{J}$. The difference between NR and SEOB there is due to the value of the final spin, with $\\chi_{f}^{\\rm NR} = 0.54$ and $\\chi_{f}^{\\rm SEOB} = 0.42$, which leads to a different $\\Omega_{\\rm frame}$. In the right panel, $\\beta$ is asymptotically constant in our toy model.}\n  \\label{fig:precmodel}\n\\end{figure}\n\n\\begin{table}[t]\n\\begin{ruledtabular}\\caption{Parameters of of the three example cases that we use to illustrate our formalism. The three cases differ by their spin alignment angles $\\theta_{A} = \\bm{\\chi}_{A} \\cdot \\hat{\\bm{L}}_{i}$, the spins being almost aligned, in the orbital plane and almost anti-aligned. The table gives also the final spins magnitudes (for SEOB as well as PhenomD for comparison), angles between the initial and final angular momenta $\\theta(\\bm{J}_{i}, \\bm{J}_{f})$, as well as QNM frequencies and frame rotation velocity used for the post-merger extension.}\\label{tab:precparams}\n\\begin{tabular}{ccccccc}\\label{tab:precexamples}\n\t$f_{\\rm min}$ & $ M_{\\rm min} $ & $q$ & $\\chi_{1}$ & $\\chi_{2}$ & $ \\phi_{1} $ & $ \\phi_{2} $ \\\\\n\t\\hline\n\t$20\\mathrm{Hz}$ & $20\\Msol$ & $ 4.0 $ & $ 0.95 $ & $ 0.95 $ & $0$ & $\\pi/2$ \\\\\n\t\\hline\\hline\n\tCase && ++ && $\\perp\\perp$ && $--$ \\\\\n\t\\hline\n\t$\\theta_{1}$ && $\\pi/6$ && $\\pi/2$ && $5\\pi/6$ \\\\\n\t$\\theta_{2}$ && $\\pi/6$ && $\\pi/2$ && $5\\pi/6$ \\\\\n\t\\hline\n\t$\\chi_{f}$ && $0.89$ && $0.50$ && $0.02$ \\\\\n\t$\\chi_{f}^{\\rm Ph}$ && $0.90$ && $0.47$ && $0.002$ \\\\\n\t$\\theta(\\bm{J}_{i}, \\bm{J}_{f})$ && $0.02$ && $0.04$ && $0.27$ \\\\\n\t$M \\omega_{220}^{\\rm QNM}$ && $0.66$ && $0.47$ && $0.377$ \\\\\n\t$M \\omega_{210}^{\\rm QNM}$ && $0.51$ && $0.42$ && $0.375$ \\\\\n\t$M \\Omega_{\\rm frame}$ && $0.15$ && $0.04$ && $0.002$ \\\\\n\\end{tabular}\n\\end{ruledtabular}\n\\end{table}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\subsection{Estimates for the separation of timescales}\n\\label{subsec:sizecorrPrec}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=.98\\linewidth]{postmergeromega_py.pdf}\n  \\caption{Quasi-normal mode frequencies for the 0th overtone of the modes $22$ and $21$, as a function of the dimensionless spin of the final black hole $\\chi_{f}$, as well as their difference $\\Omega_{\\rm frame}$ (see~\\eqref{eq:OmegaframeQNM}). The lower panel shows the  ratio $\\Omega_{\\rm frame} / \\omega^{\\rm QNM}_{220}$ characteristic of the separation of timescales between the phase of the modulation~\\eqref{eq:wignerphasesimpleprec} and the P-frame waveform phase.}\n  \\label{fig:QNM}\n\\end{figure}\n\nWe now turn to the separation of timescales and to the magnitude of the higher-order corrections derived in Sec.~\\ref{sec:formalism} in the case of precessing binaries, as can be estimated by the quantities $\\epsilon_{\\Psi 2}$, $\\epsilon_{A1}$ and $\\epsilon_{A 2}$ introduced in~\\eqref{eq:deffom}.\n\nIn the inspiral phase, we can obtain a qualitative picture of the timescales involved by using well-known leading-order post-Newtonian results. To simplify things further, we will consider a single-spin system, and use orbit-averaging to ignore nutation features in the normal to the orbital plane. In this configuration, both the orbital angular momentum $\\bm{L}$ and the spin vector $\\bm{S}$ undergo simple precession on a cone around the total angular momentum $\\bm{J}$ (see e.g.~\\cite{Apostolatos+94, Kidder95}), with an opening angle of the cone and a precession velocity $\\Omega_{\\rm prec}$ that vary only on the radiation reaction timescale. In the general case, the presence of two spins complicates the evolution of the system, but the picture of a precession cone for $\\bm{L}$ remains approximately valid (see~\\cite{Kesden+14} for a classification of generic precession trajectories).\n\nWe will use the following notation: for $m_{1}$, $m_{2}$ the masses of the two bodies, we set $M=m_{1}+m_{2}$, $\\nu=m_{1}m_{2}/M^{2}$, $\\delta = (m_{1}-m_{2})/M$, and $|\\bm{S}_{A}|=Gm_{A}^{2} \\chi_{A}$ for $A=1,2$, with $\\chi$ the dimensionless spin between $0$ and $1$ for Kerr black holes. We define $\\bm{\\ell}$ as the unit vector normal to the orbital plane. We take the convention $m_{1} \\geq m_{2}$ and assume that only the more massive object has a spin, $\\bm{S}_{2} = 0$. As in Sec.~\\ref{subsec:SPA}, we will use the notation $v = (G M \\omega/c^{3})^{1/3}$ with $\\omega = \\dot{\\varphi}$ the orbital frequency, which translates to $v=(G \\pi M f/c^{3})^{1/3}$ for the 22 mode when the SPA applies. At the Newtonian order, the orbital angular momentum is $\\bm{L} = L_{N} \\bm{\\ell}$, with\n\\be\\label{eq:defLN}\n\tL_{N} = \\frac{G M^{2} \\nu}{c v} \\,.\n\\ee\nSince we neglect radiation reaction, $\\bm{J} = \\bm{L} + \\bm{S}_{1}/c$ is treated as a constant that we use to set the z-axis so that $\\bm{J} = J \\bm{e}_{z}$, and we decompose the spin in its aligned and perpendicular components as $\\bm{S}_{1} = S_{1}^{z} \\bm{e}_{z} + \\bm{S}_{1}^{\\perp}$. At leading order, the precession equations read\n\\begin{align}\n\t\\dot{\\bm{S}}_{1} &= \\bm{\\Omega}_{1} \\times \\bm{S}_{1} \\,, \\nn\\\\\n\t\\dot{\\bm{\\ell}} &= - \\frac{1}{c L_{N}}  \\dot{\\bm{S}}_{1}\\,,\n\\end{align}\nwith the spin precession velocity~\\cite{Kidder95}\n\\be\n\t\\bm{\\Omega}_{1} = \\Omega_{1} \\bm{\\ell} = \\frac{c^{3}}{G M} \\left( \\frac{3}{4} + \\frac{\\nu}{2} - \\frac{3\\delta}{4} \\right) v^{5} \\bm{\\ell} \\,.\n\\ee\nwhich is formally a 1PN quantity. Considering only the leading PN order, we ignore effects quadratic in the spin that would enter here at 1.5PN. Decomposing the vectors in their in-plane component and projection on $z$, and using $\\delta^{2} = 1-4\\nu$ to make explicit the overall scaling in $\\nu$, we obtain for the frame precession velocity~\\cite{Kidder95}\n\\be\n\t\\dot{\\alpha} \\equiv \\Omega_{\\rm prec} = \\frac{c^{4}}{G^{2} M^{3}} \\frac{7+\\delta}{2(1+\\delta)} v^{6} J\\,.\n\\ee\nSeparating the factors as\n\\be\\label{eq:defLambdaxi}\n\t\\Lambda \\equiv \\frac{7+\\delta}{4(1+\\delta)} \\,, \\quad\t\\xi \\equiv 1 + \\frac{v S_{1}^{z}}{G M^{2} \\nu} \\,,\n\\ee\nwe see that $\\Lambda$ is a mass ratio-dependent factor chosen to be always of order 1, varying from $7/4$ for equal masses to $1$ in the test-mass limit, while the factor $\\xi$ contains the contribution of the aligned component of the spin to the precession rate. With this notation,\n\\be\\label{eq:Omegaprec}\n\t\\Omega_{\\rm prec} = \\frac{2c^{3} \\nu}{G M} \\Lambda \\xi v^{5} \\,.\n\\ee\nIf precession effects are in general larger for larger mass ratios, as the precession cones widens, the overall scaling of $\\nu$ in~\\eqref{eq:Omegaprec} above shows that, as long as the orbital angular momentum still dominates the spin in $\\xi$, increasing the mass ratio yields a slower precession rate. For high mass ratios and spins, the correction to $\\xi$ in~\\eqref{eq:defLambdaxi} starts to become important. Here, $\\Omega_{\\rm prec}$ evolves only on the radiation-reaction timescale through its dependence in $v$; this is a consequence of our simple-precession assumption, as $\\Omega_{\\rm prec}$ varies on the precession timescale in the generic case (see e.g.~\\cite{Chatziioannou+17}).\n\nWe now turn to the Euler angles and modulation functions $\\calD^{\\ell *}_{mm'}(\\alpha, \\beta, \\gamma)$, given explicitly in~\\eqref{eq:defWignerD}. As explained in~\\ref{subsec:precdef}, in the case of simple precession, the opening angle of the precession cone $\\beta$ is essentially constant, so that the minimal rotation condition~\\eqref{eq:gammadot} gives $\\gamma  = -\\alpha \\cos \\beta$ (up to a constant), and the only variable part of the precession modulation functions in~\\eqref{eq:wignerrot} are the phases, according to~\\eqref{eq:wignerphasesimpleprec}. The constant rate of rotation around $\\bm{J}$ translates into $\\dot{\\alpha} = \\Omega_{\\rm prec}$. From the closure relation $\\bm{J} = \\bm{L} + \\bm{S}_{1}/c$, we have\n\\be\\label{eq:betaconst}\n\t\\cos \\beta = \\sqrt{1 - \\left( \\frac{vS_{1}^{\\perp}}{G M^{2}\\nu} \\right)^{2}}\\,.\n\\ee\nFor a given mode contribution $\\calD^{\\ell *}_{mm'}$, \\eqref{eq:wignerphasesimpleprec} shows that we will have factors of $(m' \\cos\\beta - m)$ when taking derivatives.\n\nWe have now everything we need to compute the error estimates~\\eqref{eq:deffom} for the transfer function $\\calT^{\\ell}_{mm'}$~\\eqref{eq:defprectransfer} with $m' \\neq 0$. Given our restrictive  assumptions of orbit-averaged leading-order PN and single-spin simple precession, the result will only be a crude order-of-magnitude estimate. Using the Fourier-domain leading-order timescales generalized for modes $h^{\\rm P}_{\\ell m'}$ in the text below~\\eqref{eq:timescalesN} yields:\n\\begin{subequations}\\label{eq:precfomPN}\n\\begin{align}\n\t\\epsilon_{\\Psi 2} &= \\left(\\frac{2}{m'}\\right)^{\\frac{2}{3}} \\frac{5\\nu}{96} \\Lambda^{2} \\xi^{2} (m' \\cos\\beta - m)^{2} v^{-1} \\,, \\\\\n\t\\epsilon_{A 1} &= \\left(\\frac{2}{m'}\\right)^{\\frac{5}{3}} \\frac{(7 - 2\\kappa_{\\ell m'})\\nu}{6} \\Lambda \\xi |m' \\cos\\beta - m| v^{2} \\,, \\\\\n\t\\epsilon_{A 2} &= \\left(\\frac{2}{m'}\\right)^{\\frac{10}{3}} \\frac{(7 - 2\\kappa_{\\ell m'}) (13 - 2\\kappa_{\\ell m'}) \\nu^{2}}{72} \\nn\\\\\n\t& \\quad\\quad\\quad \\cdot \\Lambda^{2} \\xi^{2} (m' \\cos\\beta - m)^{2} v^{4} \\,,\n\\end{align}\n\\end{subequations}\nwhere $v = (GM \\pi f/c^{3})^{1/3}$. It is worth noting that $\\epsilon_{\\Psi 2}$ has an overall frequency scaling of $v^{-1}$, formally at $-0.5$PN order, which means that the relative size of this correction grows towards smaller frequencies, away from merger. Remember however that the quantities $\\epsilon$ are meant to fractional errors, and the opening angle of the precession cone, giving the overall normalization for precession effects in the waveform, also goes to 0 as $v$ in that limit. The amplitude error estimates $\\epsilon_{A1}$, $\\epsilon_{A2}$, by contrast, have the more usual behaviour of PN corrections growing towards merger. The geometric factors $(m' \\cos\\beta - m)$ show that mode contributions with a larger $|m-m'|$ are harder to model, again in a relative sense, but those contributions are however suppressed in amplitude (see discussion below~\\eqref{eq:defprechIsum}).\n\nThe overall $\\nu$ scaling indicates a better separation of timescales when increasing the mass ratio away from equal mass. These expressions also show that, since the total angular momentum appears as a factor in $\\Omega_{\\rm prec}$, higher-order corrections will be larger for roughly spin-aligned systems than for anti-aligned spins, an effect that becomes significant for large mass ratios. Note that the regime where $\\xi$ gets close to 0 corresponds to the transitional precession range~\\cite{Apostolatos+94}, with the spin of the primary compensating the orbital angular momentum, and our analysis based on simple precession is not valid anymore.\n\nWe can somewhat complement this picture for the post-merger precession by considering the accelerated frame rotation rate described by the model~\\eqref{eq:OmegaframeQNM} and illustrated in Fig.~\\ref{fig:precmodel}. We show in Fig.~\\ref{fig:QNM} the dependency of the QNM frequencies $\\omega_{220}^{\\rm QNM}$, $\\omega_{210}^{\\rm QNM}$ with the final spin of the remnant black hole $\\chi_{f}$, together with the ratio $\\Omega_{\\rm frame} / \\omega^{\\rm QNM}_{220}$. This ratio is characteristic of the separation of timescales, in the ringdown regime, between the phase of the modulation~\\eqref{eq:wignerphasesimpleprec} and the P-frame waveform phase, and increases monotonically with $\\chi_{f}$, reaching $\\sim 0.4$ for $\\chi_{f} \\rightarrow 1$. We cannot translate readily the time-domain separation of timescales in the ringdown regime to the Fourier-domain error measures defined in~\\eqref{eq:deffom}, as the time-to-frequency correspondence~\\eqref{eq:deftf} does not reach times beyond the merger, as shown by Fig.~\\ref{fig:tf}. However, a faster frame rotation will yield a more extended Fourier transform of the modulation~\\eqref{eq:defG}, and will be more challenging to accomodate with the formalism of Sec.~\\ref{sec:formalism}.\n\nTo go beyond the above order-of-magnitude picture, we now present a numerical computation of the error estimates~\\eqref{eq:deffom} for our post-merger extended precession model presented in Sec.~\\ref{subsec:precmodel}, for the three examples summarized in Table.~\\ref{tab:precexamples}. Here and in the following we consider only the $h^{\\rm I}_{2 m}$ mode contributions induced by $h^{\\rm P}_{22}$ for positive frequencies, knowing that the ones induced by $h^{\\rm P}_{2,-2}$ for negative frequencies can be deduced using~\\eqref{eq:hIlmposnegfreq}. We use analytic derivatives of the PhenomD phase and amplitude for the Fourier-domain based timescales $\\Tf$, $T_{A1}$ and $T_{A2}$, and numerical derivatives for the time-domain modulation.\n\nThe results are shown in Fig.~\\ref{fig:fomprec}, using the merger frequency and the ringdown frequency, shown by the vertical lines, to give an idea of the separation between the inspiral and post-merger phases. The leading-order PN prediction for single-spin simple precession~\\eqref{eq:precfomPN} is overlayed for the cases $++$ and $\\perp\\perp$, but not for the case $--$ as it departs significantly from simple precession. We can take $\\epsilon \\sim 1$ as an order-of-magnitude indication of the breakdown of a perturbative treatment. An important point about Fig.~\\ref{fig:fomprec} is that the error estimates are relative for each mode, thus higher $|m-m'|$ modes, which are found to be the hardest to model precisely, can be very subdominant in the final waveform.\n\nThe magnitude of the error estimates for $++$ and $\\perp\\perp$ is roughly in agreement with the PN-inspired computation~\\eqref{eq:precfomPN} above for the inspiral part of the signal, with $\\epsilon_{\\Psi 2}$ showing a negative slope $v^{-1}=(Mf)^{-1/3}$, and with a hierarchy between modes due to the factors of $|m' \\cos \\beta - m|$. The PN estimates are missing oscillations on the precession timescale due to the double-spin precession. The case $--$ departs from the simple precession picture, and~\\eqref{eq:precfomPN} does not apply. Before merger, we see that amplitude corrections are within the perturbative regime, contrarily to $\\epsilon_{\\Psi 2}$ that can exceed $1$ for subdominant modes in the $++$ and $\\perp\\perp$ cases. The amplitude corrections are found to be in the perturbative regime for all cases during the inspiral, however both the $++$ and $\\perp\\perp$ cases show a sharp increase of $\\epsilon_{A1}$, $\\epsilon_{A2}$ post-merger. The case $--$, with its small remnant spin and mild post-merger frame rotation, shows no such increase.\n\nOverall, the conclusion to be drawn of Fig.~\\ref{fig:fomprec} is that for the $++$ and $\\perp\\perp$ cases we expect the perturbative approach to be applicable only during the inspiral, with a possible breakdown for the post-merger phase, especially for the case $++$ with its fast post-merger frame rotation. The higher $|m-m'|$ modes are expected to be more challenging for the perturbative formalism, including during the inspiral. To make this picture quantitative, we need a full comparison of the signals processed at different orders of approximation against a numerical Fourier transform, which will be presented in Sec.~\\ref{subsec:precerror} below.\n\n\\begin{figure*}\n  \\centering\n  \\includegraphics[width=.98\\linewidth]{precfom_py.pdf}\n  \\caption{Error estimates of the approximation as defined in~\\eqref{eq:deffom} for the precession modulations, for the three cases $++$, $\\perp\\perp$ and $--$ listed in Table~\\ref{tab:precexamples}. The thick and thin vertical lines show, respectively, the merger frequency and the asymptotic ringdown frequency. The colors correspond to different values of $m$ in $\\calT^{2}_{m 2}$ as defined in~\\eqref{eq:defprectransfer}. The full lines are computed with numerical derivatives for the full waveform and modulation, while in the cases $++$ and $\\perp\\perp$ the dashed lines show the leading-order PN estimates~\\eqref{eq:precfomPN} for single-spin simple precession. We show the three error estimates $\\epsilon_{\\Psi 2}$, $\\epsilon_{A1}$, $\\epsilon_{A2}$ defined in~\\eqref{eq:deffom}, and the range $\\epsilon \\gtrsim 1$ indicates a breakdown of the formalism of Sec.~\\ref{sec:formalism}.}\n  \\label{fig:fomprec}\n\\end{figure*}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\subsection{Direct convolution approach for the merger-ringdown phase}\n\\label{subsec:trigopoly}\n\n\\begin{figure*}\n  \\centering\n  \\includegraphics[width=.98\\linewidth]{trigopoly_py.pdf}\n  \\caption{Amplitude (left panel) and phase (right panel), compared to its trigonometric polynomial representation for the three cases listed in Table~\\ref{tab:precexamples}. The thick and thin vertical lines indicate the frequency of the merger and ringdown (the QNM frequency) respectively. The continuous line shows the target signal $\\tilde{h}(f)$, while the dashed line shows the artificially symmetrized trigonometric polynomial~\\eqref{eq:hsymtrigo}. The dots show the discrete samples entering~\\eqref{eq:ykDFTprec}. The lower panels show the amplitude and phase residuals of~\\eqref{eq:hsymtrigo} compared to the original $\\tilde{h}(f)$.}\n  \\label{fig:trigopoly}\n\\end{figure*}\n\nAs shown by Fig.~\\ref{fig:fomprec}, the faster evolution of the modulation functions in the post-merger phase and the resulting weaker separation of timescales can be expected to be challenging for the perturbative formalism layed out in Sec.~\\ref{sec:formalism}. Motivated by this forecasted shortcoming of the Taylor-like expansion approach, here we investigate an alternative way of handling the merger-ringdown part of the signal.\n\nIn the correspondence between the time and Fourier domain, sharp features in the time domain map to extended features in the Fourier domain, and vice versa. The merger and ringdown part of the Fourier-domain signal extends over a wide range of frequencies, while it corresponds to a short interval of times, much shorter than the inspiral part. A possible approach would be to separate the time-domain waveform between the inspiral and merger phase, build a Fourier-domain model for the inspiral part only, to which the formalism of Sec.~\\ref{sec:formalism} could be applied, while the merger and ringdown part could be handled by a direct FFT, which would be a cheap operation on a limited range in time. Although this approach should always be applicable, here we will use an alternative method, simpler to implement as it allows us to keep the setting of a Fourier-domain precessing-frame waveform combined with a time-domain precession modulation.\n\nAs argued in Sec.~\\ref{subsec:precdef}, the support of the convolution~\\eqref{eq:precconvolution} will be mainly one-sided towards the high-frequency part of $\\tilde{h}(f)$, which is featureless and slowly varying as a function of $f$. Taking advantage of this, we will adopt a one-sided trigonometric polynomial representation for $\\tilde{h}(f)$. For frequencies high enough that the support of the convolution~\\eqref{eq:precconvolution} does not extend beyond the range covered by this trigonometric representation, the result will be obtained directly as an FFT/IFFT with a limited number of samples. The limitation to the high-frequency range is crucial here: the Fourier-domain amplitude and phase diverge as $f^{-7/6}$ and $f^{-5/3}$ respectively for $f \\rightarrow 0$, and our procedure would require a much finer sampling to cover part of the inspiral, going back to being equivalent to an IFFT of the full signal if we were to cover all frequencies.\n\nWe consider the high-frequency part of the signal above some frequency $f_{0}$, above which the signal has limited amplitude and phase evolution, up to some maximal frequency $f_{\\rm max}$ where the Fourier-domain amplitude of the signal has decayed to a negligible level. In practice, we define $f_{\\rm knee}$ as the peak of $f^{2}A(f)$, representing the onset of the decay in amplitude, and roughly corresponding to $\\omega_{22}^{\\rm QNM}/\\pi$. We set $f_{0}\\equiv 2/3f_{\\rm knee}$, which is close in practice to the merger frequency, and $f_{\\rm max}$ is chosen so that the amplitude is $10^{-4}$ of the amplitude at $f_{\\rm knee}$. We also eliminate a constant and a linear term in the phase by choosing another frequency central to the high-frequency range we want to represent, which we take to be $f_{p} = f_{\\rm knee}^{2/3} f_{\\rm max}^{1/3}$ with corresponding time $t_{p}\\equiv \\tf(f_{p})$. Note that the method should only be weakly sensitive to the precise choice of $f_{p}$ and $t_{p}$.\n\nInstead of tapering the signal to $0$ below $f_{0}$, to limit the deviation from the original signal we take advantage of the one-sidedness and only flatten the amplitude\\footnote{In practice, this is implemented as the discrete integral of a cosine window function on just the first two samples. We also taper to 0 the last three samples before $f_{\\rm max}$, and $0$-pad by a factor of 2.}, and artificially symmetrize the signal. To ensure continuity, this artificial symmetrization to a fictitious range $f\\in [f_{0} - (f_{\\rm max} - f_{0}), f_{0}]$ is done by imposing symmetric amplitudes and phases about $f_{0}$. Defining $\\Delta f \\equiv 2 (f_{\\rm max} - f_{0})$, we write\n\\begin{widetext}\n\\be\\label{eq:defhsym}\n\t\\tilde{h}_{\\rm sym}(f) =\n\t\\begin{cases}\n\t\t\\exp\\left[i \\Psi(f_{0}) - 2i\\pi (f-f_{0}) t_{p} \\right] \\tilde{h}(f) \\,,  &\\text{ for } f \\in [f_{0}, f_{0} + \\Delta f /2] \\\\\n\t\\tilde{h}_{\\rm sym}(2 f_{0} - f)^{*} \\,,  &\\text{ for } f \\in [f_{0} - \\Delta f/2, f_{0}]\n\t\\end{cases}\n\\ee\n\\end{widetext}\n\nNext, we build a a trigonometric polynomial representation of $\\tilde{h}_{\\rm sym}$, a construction intimately related to the FFT, that we recall in App.~\\ref{app:notation}. Over the frequency range $f\\in [f_{0}, 2f_{\\rm max} - f_{0}]$, we can approximate\n\\be\\label{eq:hsymtrigo}\n\t\\tilde{h}(f) \\simeq \\tilde{h}_{\\rm sym } (f) \\simeq \\sum\\limits_{k=-M}^{+M} (-1)^{k} c_{k} e^{2i\\pi k \\frac{f-f_{0}}{\\Delta f}} \\,,\n\\ee\nwhere the factor $(-1)^{k}$ comes from the fact that $f_{0}$ is here at the center of the interval. The coefficients $c_{k}$ are built following the rules~\\eqref{eq:ckyk} from the IFFT coefficients\n\\be\\label{eq:ykDFTprec}\n\ty_{k} = \\frac{1}{N} \\sum\\limits_{j=0}^{N-1} \\tilde{h}_{\\rm sym}\\left( f_{0} + \\frac{2j - N}{N} \\Delta f \\right) \\omega^{jk} \\,.\n\\ee\nTaking the point of view of an interpolation problem, Fig~\\ref{fig:trigopoly} shows the accuracy of this representation of the high-frequency part of the signal, by comparing the orginal $\\tilde{h}(f)$ to its  trigonometric-polynomial representation~\\eqref{eq:hsymtrigo}, for the three cases listed in Table~\\ref{tab:precexamples}. We see that we can achieve a good agreement already for 32 samples (128 counting the symmetrization and 0-padding). Errors in the phase $\\Psi$ grow towards high frequencies because they are essentially errors in a relative sense, and amplitudes are decaying in this region.\n\nThe crucial point in this approach is that the convolution integral in~\\eqref{eq:precconvolution} has support mainly on $f'<0$, as discussed in Sec.~\\ref{subsec:precdef}, which means that when we try to compute the transfer function $\\calT(f)$ at a given frequency $f$, we only need the trigonometric-polynomial representation~\\eqref{eq:hsymtrigo} to be accurate for frequencies $>f$ in Fig.~\\ref{fig:trigopoly}. Thus, the trigonometric representation of $\\tilde{h}(f)$ can be used to compute the convolution almost all the way down to $f_{0}$, effects of the tapering aside. However, this statement is tied to our restriction to the $22$-mode, and extending the method to a precessing-frame waveform that includes more modes $h^{\\rm P}_{\\ell m}$ will require care.\n\nWhen inserting this representation~\\eqref{eq:defhsym} and~\\eqref{eq:hsymtrigo} into~\\eqref{eq:precconvolution}, we obtain\n\\begin{align}\\label{eq:resultdirectconvol}\n\t\\tilde{s}(f) &= e^{-i \\Psi(f_{0})} e^{2i\\pi (f-f_{0}) t_{p}} \\nn\\\\\n\t& \\qquad \\cdot\\sum\\limits_{k=-M}^{+M} (-1)^{k} c_{k} e^{2i\\pi k \\frac{f-f_{0}}{\\Delta f}} F(t_{p} + k\\delta t) \\,,\n\\end{align}\nwhere we defined the time sampling $\\delta t \\equiv 1/\\Delta f$. We see that we are left with an FFT-like expression to compute from $N+1$ time samples of the modulation function $F$, centered around $t_{p}$. We see that, apart from the conditioning described above with the artificial symmetrization, this is analogous to an FFT of the product of the modulation with the time-domain signal obtained through an IFFT.\n\nIn terms of computational performance, the implementation of this approach is expected to have a reasonable cost. In the following, we will use $M=64$ samples ($32$ useful samples before 0-padding, $N=128$ samples in total for the artificially symmetrized signal). The computation of~\\eqref{eq:ykDFTprec} and~\\eqref{eq:resultdirectconvol} amounts to two FFT/IFFT operations, and is done only once for a given waveform and modulation function. The number of samples is of the same order of magnitude as the one required to represent the Fourier-domain waveform with an interpolating cubic spline for its amplitude and phase (a few hundreds for the full frequency band, see e.g~\\cite{Puerrer14}), thus the cost should be comparable to the Taylor-like approach presented in Sec.~\\ref{subsec:executivesummary}.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\subsection{Error control for the Fourier-domain precession modulation}\n\\label{subsec:precerror}\n\nWe now assess the accuracy of the transfer function computation, applying the formalism of Secs.~\\ref{subsec:executivesummary} and~\\ref{subsec:trigopoly} to the three examples listed in Table~\\ref{tab:precexamples}, and comparing the result to a reference numerical computation.\n\nTo obtain the latter, we first have to perform an IFFT of our Fourier-domain P-frame waveform, to obtain $h^{\\rm P}_{22}$ as a function of time. To mitigate the effect of the necessary tapering of the waveform when computing this numerical inverse Fourier transform, we apply a Planck-window tapering on the range $f\\in 16-20 \\Hz$ for a total mass of $M=20 \\Msol$. In parallel, we generate an SEOB waveform with the appropriate length in time. Both are aligned to peak at $t=0$, we build the post-merger extended modulation functions as explained in Sec.~\\ref{subsec:precmodel}, compute the inertial-frame modes $h^{\\rm I}_{2m}$ following~\\eqref{eq:wignerrot} before computing their Fourier-domain counterparts $\\tilde{h}^{\\rm I}_{2m}$ with an FFT. The Fourier-domain transfer functions are then computed using~\\eqref{eq:defprectransfer}.\n\nThe figures Fig.~\\ref{fig:precerrors++}, Fig.~\\ref{fig:precerrorspp} and Fig.~\\ref{fig:precerrors--} show the result for the cases $++$, $\\perp\\perp$ and $--$ of Table~\\ref{tab:precexamples} at three successive approximations, following the notation of~\\eqref{eq:summaryNA}: $\\{N:0 | A:0 | \\mathrm{No \\; Conv.}\\}$, which is simply the leading-order transfer function~\\eqref{eq:transferlocal}, ignoring all the corrections; $\\{N:3 | A:2 | \\mathrm{No \\; Conv.}\\}$, which incorporates both the phase corrections~\\eqref{eq:stencilfresnel}, using a stencil size $N=3$, and the amplitude corrections up to second order in~\\eqref{eq:summaryNA}; and $\\{N:3 | A:2 | \\text{Conv.}\\}$, which is the same as the previous setting for the inspiral but uses the convolution formalism of Sec.~\\ref{subsec:trigopoly} to cover the high frequency range, with a smooth transition in the shaded range. The panels show the Fourier-domain amplitude for each of the modes, both exact and from the reconstruction, the fractional errors in amplitude, and the errors in phase. The errors here are relative to each mode, not to the dominant mode. Thus, the amplitude plots importantly allow to visualize the mode hierarchy, giving an idea of the impact of relative errors in the subdominant modes on the full waveform.\n\nThe $++$ case, shown in Fig.~\\ref{fig:precerrors++}, is the most challenging. As expected from the analysis of Sec.~\\ref{subsec:sizecorrPrec}, the presence of strong aligned spins and a large spin of the remnant degrades the separation of timescales, and the reconstruction shows large relative errors, at least in subdominant mode contributions. Applying the higher-order corrections of Sec.~\\ref{subsec:executivesummary} does improve the accuracy in the inspiral, but the most difficult modes $m=-1$ and $m=-2$ still show large errors. We also find that for this case higher-order corrections do not reduce the errors in the merger-ringdown region, consistently with the breakdown of the perturbative formalism indicated by Fig.~\\ref{fig:fomprec}. Using the convolution treatment improves the main modes $m=2$, $m=1$, but not the most challenging modes $m=-1$ and $m=-2$, which can be seen to depart from the perturbative treatment before the range covered by the convolution and for which the convolution~\\eqref{eq:precconvolution} extends to very high frequencies where our trigonometric polynomial representation of the signal is not accurate (see Fig.~\\ref{fig:trigopoly}). Note however that, as will be shown below by unfaithfulness computations, these large fractional errors for the subdominant modes do not affect much the full waveform.\n\nThe $\\perp\\perp$ case is shown in Fig.~\\ref{fig:precerrorspp}. Errors are increasing to larger $|m-m'|$, higher-order corrections improve the reconstruction but are unsufficient for the merger-ringdown, and the convolution works for all modes on the frequency range where it is applied. The errors at the very high end of the frequency band occur when the overall amplitudes are low, and are therefore unimportant.\n\nIn the case $--$, shown in Fig.~\\ref{fig:precerrors--}, the mode hierarchy is not respected, as the frame trajectory does not quite follow the picture of simple precession, and the estimates~\\eqref{eq:precfomPN} do not apply. The precession velocity is much milder, both in the inspiral and in the merger-ringdown range, thanks to a low remnant spin, and the separation of timescales is better, as shown in Fig.~\\ref{fig:fomprec}. This leads to smaller errors, and, apart from some amplitude errors in the merger-ringdown region, we find that in this case even the leading-order treatment gives good results.\n\nIn order to illustrate what these errors really mean for the analysis of GW signals, we also compute the unfaithfulness (or mismatch) between various orders of approximation and the exact, numerical result. This unfaithfulness figure, although giving a simplified view of waveform inaccuracies, is commonly used to quantify disagreements between template families and to compare them to numerical relativity waveforms. To define the unfaithfulness, different prescriptions are possible, taking into account or not the detector orientation and optimizing over different sets of parameters.\n\nHere, we will use directly the wave polarizations $h_{+}$, $h_{\\times}$, optimizing over time, phase, and polarization angle. For real or complex signals $a$, $b$, one introduces the usual Hermitian noise-weighted scalar product~\\cite{CF94}\n\\be\\label{eq:defoverlap}\n\t\\left( a | b \\right) = 2 \\int \\ud f \\frac{\\tilde{a}_{1}(f) \\tilde{b}_{2}(f)^{*}}{S_{n}(f)} \\,,\n\\ee\nwhere the integral extends over all frequencies (in practice, two intervals $[-f_{\\rm max}, -f_{\\rm min}]$ and $[f_{\\rm min}, f_{\\rm max}]$). In the above, $S_{n}(f)$ the noise power spectral density, for which we use the aLIGO ZDHP noise curve~\\cite{LIGOProspects13}. We use the notation $h \\equiv h_{+} - i h_{\\times}$ for the complex strain, and write $h[\\delta t, \\delta \\Phi, \\delta \\psi]$ to represent a signal where we shifted the time of coalescence, the phase of the line of sight to the observer and the polarization angle. The dependencies in time and polarization are given by~\\eqref{eq:shifttime} and $h[\\delta \\psi] = e^{2 i \\delta \\psi} h$, while the phase $\\delta \\Phi$ affects differently each waveform mode in~\\eqref{eq:defmodes}. In the norm $(h|h)$, only the dependence on $\\delta\\Phi$ remains. For two signals $h_{1}$ and $h_{2}$, the mismatch between them is then defined as\n\\be\\label{eq:defMM}\n\t\\mathrm{MM} \\equiv \\mathrm{Min}_{\\delta t, \\delta \\varphi, \\delta \\psi} \\left( 1 - \\frac{ \\mathrm{Re} \\left[ (h_{1}[\\delta t, \\delta \\Phi, \\delta \\psi] | h_{2}) \\right]}{\\sqrt{(h_{1}|h_{1})[\\delta\\Phi]}\\sqrt{(h_{2}|h_{2})}} \\right)\n\\ee\nwhere an optimization over a shift in time, phase and polarization is performed. This definition is the same as in~\\cite{Blackman+17a} (see App.~D there), except that we added the optimization over the phase. The target unfaithfulness for waveform models depends on the application. For ground-based detectors like advanced LIGO and Virgo, it is often set to 1\\% or 3\\%, while detectors of the next generations, including LISA, will require a lower unfaithfulness due to their higher signal-to-noise ratios.\n\nIn this unfaithfulness computation, we take our illustrative model of Sec.~\\ref{subsec:precmodel} as the reference waveform, thus ignoring all limitations of our model for precession and focusing only on the passage from time-domain to Fourier-domain for a given waveform. We show in Fig.~\\ref{fig:precunfaithfulness} the unfaithfulness obtained for three inclination angles between the line-of-sight and the direction of the final angular momentum $\\bm{J}$, $0$ (face-on), $\\pi/3$ and $\\pi/2$ (edge-on). Again, we use different approximation levels in~\\eqref{eq:summaryNA}, indicated by the color, including or not the treatment of Sec.~\\ref{subsec:trigopoly} for the high frequencies as indicated by a continuous or dashed line. The total mass ranges from $20\\Msol$ (where the inspiral dominates) to $400\\Msol$ (where the merger-ringdown phase dominates).\n\nAs discussed in App.~\\ref{app:precpreviousapproaches}, the approximation $\\{N:0 | A:0 | \\text{No Conv.}\\}$ corresponds to the leading-order formula~\\eqref{eq:transferlocal}, which is close to the treatment of PhenomP~\\cite{Hannam+13}, with the difference that this model uses effective Fourier-domain Euler angles instead of a time-domain modulation through merger and ringdown. The order of approximation $\\{N:3 | A:0\\}$ is equivalent to formalism of Ref.~\\cite{KCY14} with a stencil order of $N=3$, except that the latter formalism is based on an SPA representation of the P-frame waveform and limited to the inspiral, while our Fourier-domain approach is an attempt at covering the whole frequency band.\n\nFig.~\\ref{fig:precunfaithfulness} shows that, tor the $++$ case, the face-on case shows good agreement even at leading order, as the effects of precession on the full waveform are suppressed for a zero inclination. By contrast, with $\\pi/3$ or $\\pi/2$ inclination the mismatch can reach $10^{-2}$ for high masses above $M \\simeq 100 \\Msol$, even with the perturbative corrections. Using the convolution treatment of the merger and ringdown limits the mismatch, and including both phase (going from blue to red) and amplitude corrections (going from red to yellow and green) makes a clear improvement. Similarly, for the case $\\perp\\perp$, both the perturbative corrections and the convolution at high frequencies reduce the unfaithfulness. In both cases, one can see that, as expected, the high-frequency convolution becomes unimportant at low masses, where the inspiral dominates. The $--$ case does not show the same dependency on inclination as the other ones, as we measure the inclination angle with respect to the final direction of $\\bm{J}$, and this case is close to transitional precession and departs from the picture of simple precession on a cone. As expected from the error estimates and the transfer function errors shown in Figs.~\\ref{fig:fomprec} and~\\ref{fig:precerrors--}, the milder precession velocity means that the mismatches are small in this case already for the leading-order treatment. We note, however, that in all cases increasing the order of the amplitude corrections from $A:1$ to $A:2$ in~\\eqref{eq:summaryNA} does not yield an improvement, and gives even slightly worse errors in some cases. This points to a limitation of our analysis. Higher-order time derivatives are harder to extract numerically, and this might be an indication that, even in our smooth model of Sec.~\\ref{subsec:precmodel}, we should limit the formalism to first derivatives.\n\nOverall, we found that, although the configurations listed in Table~\\ref{tab:precexamples} are strongly spinning ($\\chi = 0.95$) with a quite high mass ratio ($q=4$), which both enhance precession effects, the unfaithfulness due to the leading-order Fourier-domain treatment of the precession remains mainly below 1\\%, except at larger masses. This indicates that this treatment (used in particular in PhenomP~\\cite{Hannam+13}, see the discussion of App.~\\ref{app:precpreviousapproaches}) should be good enough for current LIGO applications. All types of corrections we investigated, either perturbative in phase and amplitude from Sec.~\\ref{subsec:executivesummary}, or generated with the convolution treatment of Sec.~\\ref{subsec:trigopoly}, consistently lower the unfaithfulness below the 1\\% level. One exception are second-order amplitude corrections, which we found to make little or no difference. Using all the tools at our hands, we are able to keep the unfaithfulness of our three example waveforms below $2.10^{-3}$ for all masses and inclinations. We leave for future work the investigation of the full parameter space of spinning binaries, and of higher harmonics $\\ell \\neq 2$.\n\n\\begin{figure*}\n  \\centering\n  \\includegraphics[width=.98\\linewidth]{precerror_++_py.pdf}\n  \\caption{Fourier-domain amplitudes of the modes $\\tilde{h}^{\\rm I}_{\\ell m}$ (top panels), reconstruction errors in the transfer fonctions $\\calT^{2}_{m2}$ for the amplitudes (middle panels) and for the phases (bottom panels),  for the configuration $++$ of Table~\\ref{tab:precexamples}, with spins almost aligned. The thick and thin vertical lines show the merger and asymptotic ringdown frequencies respectively. For the solid curves in the top panel, transfer functions were computed from an FFT of the full time-domain precessing signal, while the dashed curves show the results of the Fourier-domain reconstruction techniques presented here. The columns show the orders of approximation $\\{N:0 | A:0 | \\text{No Conv.}\\}$, $\\{N:3 | A:2 | \\text{No Conv.}\\}$, $\\{N:3 | A:2 | \\text{Conv.}\\}$. In the right column, the region of transition between the perturbative treatment of Sec.~\\ref{subsec:executivesummary} and the high-frequency treatment of Sec.~\\ref{subsec:trigopoly} is shaded in grey. Note that the errors shown here are relative to a given mode, not to the leading mode, and the errors are largest in this sense for the most subdominant modes; the top panels illustrate the mode hierarchy.}\n  \\label{fig:precerrors++}\n\\end{figure*}\n\n\\begin{figure*}\n  \\centering\n  \\includegraphics[width=.98\\linewidth]{precerror_pp_py.pdf}\n  \\caption{Same as Fig.~\\ref{fig:precerrors++}, but for the configuration $\\perp\\perp$ of Table~\\ref{tab:precexamples}, with both spins in the orbital plane.}\n  \\label{fig:precerrorspp}\n\\end{figure*}\n\n\\begin{figure*}\n  \\centering\n  \\includegraphics[width=.98\\linewidth]{precerror_--_py.pdf}\n  \\caption{Same as Fig.~\\ref{fig:precerrors++}, but for the configuration $--$ of Table~\\ref{tab:precexamples}, with almost anti-aligned spins.}\n  \\label{fig:precerrors--}\n\\end{figure*}\n\n\\begin{figure*}\n  \\centering\n  \\includegraphics[width=.98\\linewidth]{precMM_py.pdf}\n  \\caption{Unfaithfulness at various orders of approximation as compared with an FFT of the full time-domain precessing signal, for the three precessing systems of Table~\\ref{tab:precexamples}. The color indicates the order of approximation of the perturbative treatment of Sec.~\\ref{subsec:executivesummary}. Dashed lines are obtained applying the treatment of Sec.~\\ref{subsec:executivesummary} to the whole frequency band, while full lines are obtained using Sec.~\\ref{subsec:trigopoly} for the high frequency range. The computation is done using~\\eqref{eq:defMM} with $f_{\\rm min} = 20\\mathrm{Hz}$, for masses between 20 and 400 $\\Msol$, and with the aLIGO ZDHP noise curve~\\cite{LIGOProspects13}. The inclination is defined here as the angle between the line of sight and the final $\\bm{J}$.}\n  \\label{fig:precunfaithfulness}\n\\end{figure*}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Summary and Conclusions}\n\\label{sec:discussion}\n\nWe presented a formalism to process gravitational-wave signals described in the Fourier domain through a time-domain modulation and delay of the type created by the motion and response of a LISA-type detector and by the precessing motion of spinning compact binaries. The natural leading-order of this perturbative formalism simply amounts to building a time-to-frequency correspondence~\\eqref{eq:deftf}, generalizing the SPA correspondence~\\eqref{eq:deftfSPA} through merger and ringdown.\n\nThis formalism is based on the separation of timescales between the modulation and the signal. By a Fourier-domain expansion of the integrand of convolution integrals, corrections beyond the leading order are straightforwardly generated. The most important are quadratic phase corrections, for which the formalism yields a natural extension of the results of~\\cite{KCY14} to IMR signals, thanks to the generalization of the radiation reaction timescale with a Fourier-domain expression~\\eqref{eq:defTf}. Other corrections include amplitude and delay terms. We provided order-of-magnitude error estimates~\\eqref{eq:deffom} allowing a simple diagnosis of the relevance of these various corrections, forecasting where the perturbative formalism will fail due to an insufficient separation of timescales.\n\nWe applied our approach to the case of non-precessing comparable-mass binary systems seen by LISA, investigating examples of supermassive black hole mergers as well as inspirals of stellar-mass black holes. The population of stellar-mass binary black hole signals seen in LISA will include chirping systems, merging within years of the LISA observations, as well as slowly-chirping systems hundreds or thousands of years away from merger. We found that our treatment is well applicable for both high-mass and chirping low-mass systems. The leading-order treatment performs quite well, with at most a localized $\\sim10\\%$ in amplitude or phase error, while the corrections we derived can reduce the errors in the transfer functions to much lower levels if needed. Quadratic phase corrections at the start of the waveform and delay corrections at the high end of the frequency band are the most relevant. On the other hand, the morphology of the slowest-chirping stellar-mass signals is close to quasi-monochromatic galactic binaries, and they cannot be handled by this perturbative formalism. We developed a separate method, using discrete Fourier coefficients, to compute the instrument response in this case.\n\nTo explore the application of the formalism to precessing binaries, we built a toy model for the precession of a two-spins system including a post-merger precessing-frame trajectory. For the high spin, moderate mass ratio examples we explored, we found that subdominant precessing mode contributions can be challenging for the formalism and have large fractional errors, although they are suppressed in amplitude in the complete waveform. For the inspiral, the most relevant corrections are the quadratic in phase ones that were already derived in~\\cite{KCY14}. Our formalism extends to the merger and ringdown, where our model for the post-merger precession gives a weaker separation of timescales. We developed an alternative method to handle the high-frequency, late-time part of the signal, with a direct convolution of the Fourier-domain signal. We showed that although the leading-order treatment is acceptable for our examples with an unfaithfulness at or below 1\\% for typical LIGO masses, including in the inspiral all the corrections we derived, as well as using the convolution treatment for the merger, both help lowering the unfaithfulness down to the $10^{-4}$-$10^{-3}$ range.\n\nOur investigation of the precession provides tools that will be potentially useful for the next generations of Fourier-domain waveform models for IMR precessing systems. Our treatment of the Fourier-domain LISA instrumental response will allow us to leverage modern, fast Fourier-domain codes producing IMR waveforms to accelerate computationally intensive data analysis applications, most notably Bayesian source parameter estimation on synthetic data, that have become urgent with the selection of LISA as a mission by ESA. The LISA response described in Sec.~\\ref{sec:LISA} has been implemented in the LISA Data Challenge~\\cite{LDC} software suite.\n\nOur results suggest a few straightforward extensions. First, we only considered the leading harmonic of non-spinning waveforms in the LISA response. The same approach is also well-suited to treating higher harmonics and aligned spin signals, but precession will leave a definite imprint on the Fourier-domain signal. One option in this case would be to handle the precession and response modulation together, as in~\\cite{Klein+15}. However, we present in App.~\\ref{app:precLISA} an argument showing that our formalism should apply straightforwardly to waveforms with simple precession. We leave the general case for future study.\n\nAnother natural application of our formalism developed for the LISA response is to third-generation ground-based detectors. For detectors like the Einstein Telescope, signals are sufficiently long for the rotation of the Earth to matter, and their arms are long enough that the long wavelength approximation is not valid at high frequencies and that the response becomes frequency-dependent~\\cite{Essick+17}. A preliminary order-of-magnitude analysis shows that the leading-order treatment should be applicable, but more investigation is needed.\n\nFinally, while we restricted ourselves to comparable-mass binary systems, Extreme Mass Ratio Inspirals (EMRI) will also be very important signals for LISA. Those signals generally include not only strong precession but also large eccentricity. An effective frequency-domain LISA response may be possible by applying our treatment separately to each of the numerous individual harmonics produced (see e.g.~\\cite{Chua+17}).\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\vspace{4.5mm}\n\n\\hspace{0.85in}\n{\\bf Acknowledgments}\n\n\\vspace{3.5mm}\n\nWe are indebted to Stanislav Babak, Alejandro Boh\\'{e}, Alessandra Buonanno, Tito Dal Canton, Scott Field, Philip Graff, Sebastian Khan, Antoine Klein, Serguei Ossokine, Michael P\\\"{u}rrer for useful discussions and comments. We used the software GWFrames~\\cite{Boyle13, Boyle+14} in our study. This work was supported by a NASA Astrophysics Theory Program grant 11-ATP-046.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\appendix\n\n\\section{Notation and conventions}\n\\label{app:notation}\n\nThe convention we will be using for the Fourier transform of a signal $h(t)$ and its inverse is\n\\begin{subequations}\n\\label{eq:defFT}\n\\begin{align}\n\t\\tilde{h}(f) &= \\mathrm{FT}[h](f) =  \\int \\ud t \\, e^{+2i\\pi f t} h(t) \\,, \\\\\n\th(t) &= \\mathrm{IFT}[\\tilde{h}](t) =  \\int \\ud f \\, e^{-2i\\pi f t} \\tilde{h}(f) \\,.\n\\end{align}\n\\end{subequations}\nNotice that this sign convention is not the most frequently used in the literature. We chose it to ensure that, with the conventions of~\\cite{BlanchetLiving}, spin-weighted spherical modes $h_{\\ell m}$ with $m>0$ will have support mostly for positive frequencies. One can revert to the more usual convention by taking $f\\rightarrow -f$.\n\nThe effect of a shift in time of the time-domain signal translates into a linear phase contribution added to the Fourier-domain signal. For $h_{\\Delta t}(t) \\equiv h(t+\\Delta t)$ with $\\Delta t$ a constant, in our convention we have\n\\be\\label{eq:shifttime}\n\t\\tilde{h}_{\\Delta t} (f) = e^{-2i\\pi f \\Delta t} \\tilde{h}(f) \\,.\n\\ee\n\nA useful representation of the gravitational waveform is given by its decomposition in spin-weighted spherical harmonics. The waveform emitted in the direction $(\\Theta, \\Phi)$, with its two polarizations $h_{+},h_{\\times}$, can be decomposed as a superposition of modes as~\\cite{Thorne80}\n\\be\\label{eq:defmodes}\n\th_{+} - i h_{\\times} = \\sum\\limits_{\\ell \\geq 2} \\sum\\limits_{m=-\\ell}^{\\ell} {}_{-2}Y_{\\ell m}(\\Theta,\\Phi) h_{\\ell m} \\,,\n\\ee\nwhere the ${}_{-2}Y_{\\ell m}(\\Theta,\\Phi)$ are spin-weighted spherical harmonics~\\cite{Goldberg+67}. Conversely, the individual polarizations are obtained from the individual modes as\n\\begin{subequations}\n\\begin{align}\n\th_{+} = \\frac{1}{2} \\sum\\limits_{\\ell, m} \\left[ {}_{-2}Y_{\\ell m}h_{\\ell m} + {}_{-2}Y_{\\ell m}^{*} h_{\\ell m}^{*} \\right] \\,,\\\\\n\th_{\\times} = \\frac{i}{2} \\sum\\limits_{\\ell, m} \\left[ {}_{-2}Y_{\\ell m}h_{\\ell m} - {}_{-2}Y_{\\ell m}^{*} h_{\\ell m}^{*} \\right] \\,.\n\\end{align}\n\\end{subequations}\n\nFor a non-precessing system, with a fixed orbital plane, the individual modes have the additional symmetry property\n\\be\\label{eq:symmetryhlminusm}\n\th_{\\ell, -m} = (-1)^{\\ell} h_{\\ell m}^{*} \\,.\n\\ee\nSince we will work in the Fourier domain, it will be useful to write the contributions of the individual modes to the Fourier transforms of the polarizations as\n\\begin{subequations}\\label{eq:hpcfrommodes}\n\\begin{align}\n\t\\tilde{h}_{+}(f) &= \\frac{1}{2} \\sum\\limits_{\\ell \\geq 2} \\sum\\limits_{m=-\\ell}^{\\ell} \\left[ {}_{-2}Y_{\\ell m} \\tilde{h}_{\\ell m}(f) + {}_{-2}Y_{\\ell m}^{*} \\tilde{h}_{\\ell m}(-f)^{*} \\right] \\,, \\\\\n\t\\tilde{h}_{\\times}(f) &= \\frac{i}{2} \\sum\\limits_{\\ell \\geq 2} \\sum\\limits_{m=-\\ell}^{\\ell} \\left[ {}_{-2}Y_{\\ell m} \\tilde{h}_{\\ell m}(f) - {}_{-2}Y_{\\ell m}^{*} \\tilde{h}_{\\ell m}(-f)^{*} \\right] \\,,\n\\end{align}\n\\end{subequations}\nwhere we used $\\widetilde{h_{\\ell m}^{*}}(f) = \\tilde{h}_{\\ell m}(-f)^{*}$. An additional approximation often used in waveform models consists in considering that the Fourier transforms $\\tilde{h}_{\\ell m}$ have support only on one side of the spectrum, either for positive of for negative frequencies depending on the sign of $m$. This holds in particular within the stationary phase approximation (see Sec.~\\ref{subsec:SPA}). With our sign convention~\\eqref{eq:defFT}, this approximation reads\n\\begin{align}\\label{eq:zeronegativef}\n\t\\tilde{h}_{\\ell m} (f) &\\simeq 0 \\text{ for } f<0, \\; m>0 \\nn\\,,\\\\\n\t\\tilde{h}_{\\ell m} (f) &\\simeq 0 \\text{ for } f>0, \\; m<0 \\,.\n\\end{align}\nWhen both and~\\eqref{eq:zeronegativef} apply, \\eqref{eq:hpcfrommodes} becomes simpler. For $f>0$, we have then\n\\be\n\t\\tilde{h}_{+,\\times} (f) = \\sum_{\\ell \\geq 2} \\sum_{m = 1}^{\\ell} K^{+,\\times}_{\\ell m} \\tilde{h}_{\\ell m}(f) \\,,\n\\ee\nwhere we set\n\\begin{align}\n\tK^{+}_{\\ell m} &\\equiv \\frac{1}{2} \\left( {}_{-2}Y_{\\ell m} + (-1)^{\\ell} {}_{-2}Y_{\\ell, -m}^{*} \\right) \\,, \\nn\\\\\n\tK^{\\times}_{\\ell m} &\\equiv \\frac{i}{2} \\left( {}_{-2}Y_{\\ell m} - (-1)^{\\ell} {}_{-2}Y_{\\ell, -m}^{*} \\right) \\,.\n\\end{align}\nThe range $f<0$ can be obtained readily, since $h_{+},h_{\\times}$ are real quantities, from $\\tilde{h}_{+,\\times} (-f) = \\tilde{h}_{+,\\times}(f)^{*}$.\n\nDropping the mode indices $\\ell$, $m$, we will decompose a given mode\\footnote{Not to be confused with the commonly used notation $h = h_{+} - i h_{\\times}$ for the complex strain.} $\\tilde{h}_{\\ell m} = \\tilde{h}$ into a Fourier-domain amplitude $A$ and a phase $\\Psi$ according to\n\\be\\label{eq:defAPsi}\n\t\\tilde{h}(f) \\equiv A(f) e^{-i\\Psi(f)} \\,.\n\\ee\n\nThroughout this paper we will refer to Discrete Fourier Transform (DFT) with the acronyms FFT/IFFT for the Fast Fourier Transform and its inverse. In our convention~\\eqref{eq:defFT}, the link between the DFT and the trigonometric polynomial representation of a function goes as follows. For a periodic function $F(x)$ defined on $x\\in [x_{0}, x_{0} + \\Delta x]$, and represented by $N$ samples $x_{j} = \\ov{x} + j \\Delta x/N$, $j=0,\\dots,N-1$, with $N$ large enough to satisfy, at least approximately, the Nyquist criterion, we can build a trigonometric interpolant $P(x)$ as\n\\be\n\tP(x) = \\sum\\limits_{k=-M}^{+M} c_{k} e^{2i\\pi k \\frac{x-x_{0}}{\\Delta x}} \\,,\n\\ee\nthat will satisfy the system $P(x_{j}) = F(x_{j})$ for $j=0,\\dots, N-1$. Here we set $M=N/2$, assuming N is even. This trigonometric polynomial representation is equivalent to truncating the formal Fourier series, representing the full signal, to a finite order $M$. The coefficients $c_{k}$, in the full series, are defined as\n\\be\\label{eq:defcnApp}\n\tc_{n}(F) = \\frac{1}{\\Delta x} \\int_{0}^{\\Delta x} \\ud x \\, e^{\\frac{2 i \\pi n x }{ \\Delta x}} F(x) \\,.\n\\ee\nIn both interpretations, either the truncated approximation of the Fourier series or  the trigonometric interpolation formulation, these coefficients are related to the coefficients of the IFFT. If we set $\\omega \\equiv e^{2i\\pi/N}$ and define\n\\be\\label{eq:ykDFT}\n\ty_{k} = \\frac{1}{N} \\sum\\limits_{j=0}^{N-1} F(x_{j}) \\omega^{jk} \\,,\n\\ee\nwhich is the expression of the IFFT in our sign convention~\\eqref{eq:defFT}, the coefficients $c_{k}$ are given by\n\\begin{align}\\label{eq:ckyk}\n\tc_{k} &= y_{k} \\text{ for } k=0,\\dots, M-1 \\,, \\nn\\\\\n\tc_{k} &= y_{k+N} \\text{ for } k=-M+1,\\dots, -1 \\,, \\nn\\\\\n\tc_{M} &= c_{-M} = \\frac{y_{M}}{2} \\,,\n\\end{align}\nwhere the condition $c_{M} = c_{-M}$ is an arbitrary condition enforced to match the number of degrees of freedom. In practice, a good representation of the Fourier series of the signal is achieved when the truncation order $M$ is sufficient so that the coefficients $c_{|n|\\geq M}$ become negligibly small.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Wigner matrices and precessing frame}\n\\label{app:wigner}\n\nIn this Appendix, we summarize our conventions for the Wigner matrices and give a brief description of the construction of a precessing-frame directly from the waveform.\n\nIf the $h_{\\ell m}^{\\rm I}$ are the spin-weighted spherical harmonics~\\eqref{eq:defmodes} of the waveform in a fixed inertial frame (I), and if the $h_{\\ell m}^{\\rm P}$ are the modes of the waveform in a time-dependent precessing frame (P) constructed from the inertial frame by an active rotation with Euler angles $(\\alpha, \\beta, \\gamma)$ (in the convention $(z,y,z)$), then the modes are related by\n\\begin{subequations}\n\\label{eq:wignerrotApp}\n\\begin{align}\n\th_{\\ell m}^{\\rm I} = \\sum\\limits_{m=-\\ell}^{\\ell} \\calD^{\\ell *}_{mm'} (\\alpha,\\beta,\\gamma) h_{\\ell m'}^{\\rm P} \\,, \\\\\n\th_{\\ell m}^{\\rm P} = \\sum\\limits_{m=-\\ell}^{\\ell} \\calD^{\\ell }_{m'm} (\\alpha,\\beta,\\gamma) h_{\\ell m'}^{\\rm I} \\,.\n\\end{align}\n\\end{subequations}\nHere we introduced Wigner $\\calD$-matrices\n\\be\\label{eq:defWignerDapp}\n\t\\calD^{\\ell}_{mm'} (\\alpha, \\beta, \\gamma) = e^{im \\alpha} d^{\\ell}_{mm'}(\\beta) e^{im' \\gamma}\\,,\n\\ee\nwith the real-valued Wigner $d$-matrix reading\n\\begin{widetext}\n\\be\\label{eq:defWignerdapp}\n\td^{\\ell}_{mm'}(\\beta) = \\sum\\limits_{k=k_{\\rm min}}^{k_{\\rm max}} \\frac{(-1)^{k}}{k!} \\frac{\\sqrt{(l+m)! (l-m)! (l+m')! (l-m')!}}{(l+m-k)! (l-m'-k)! (k-m+m')!} \\left( \\cos\\frac{\\beta}{2} \\right)^{2\\ell+m-m'-2k} \\left( \\sin\\frac{\\beta}{2} \\right)^{2k-m+m'}\\,,\n\\ee\n\\end{widetext}\nwhere the boundaries of the sum, $k_{\\rm min} = \\mathrm{max}(0, m-m')$ and $k_{\\rm max} = \\mathrm{min}(\\ell+m, \\ell-m')$, can also be read by enforcing that the arguments of the factorials must be non-negative. Note that our convention differs from the convention of~\\cite{ABFO09} by a transposition,\n\\be\n\t\\calD^{\\ell}_{m m'} (\\alpha, \\beta, \\gamma) = D^{\\ell \\, \\mathrm{ABFO}}_{m' m} (\\alpha, \\beta, \\gamma) \\,.\n\\ee\nIn Sec.~\\ref{sec:precession}, we considered only $\\ell = 2$ and we restricted ourselves to the contributions of the precessing-frame mode $h_{22}^{\\rm P}$. In that case, the relevant explicit expression for the $d$-matrix are\n\\begin{subequations}\n\\begin{align}\n\td^{2}_{22} (\\beta) &= \\cos^{4} \\frac{\\beta}{2}\\,, \\\\\n\td^{2}_{12} (\\beta) &= 2 \\cos^{3} \\frac{\\beta}{2} \\sin \\frac{\\beta}{2}\\,, \\\\\n\td^{2}_{02} (\\beta) &= \\sqrt{6} \\cos^{2} \\frac{\\beta}{2} \\sin^{2} \\frac{\\beta}{2} \\,, \\\\\n\td^{2}_{-12} (\\beta) &= 2 \\cos \\frac{\\beta}{2} \\sin^{3} \\frac{\\beta}{2} \\,, \\\\\n\td^{2}_{-22} (\\beta) &= \\sin^{4} \\frac{\\beta}{2} \\,.\n\\end{align}\n\\end{subequations}\n\nDifferent prescriptions have been proposed to construct a precessing frame. Intuitively, the frame follows the plane of the orbit as the spins force the latter to precess, so one could define the precessing frame from the trajectory during the inspiral. This is in fact what is done for SEOBNRv3~\\cite{Pan+13}, where a non-precessing waveform is generated in the orbital plane before being rotated back to an inertial frame. Alternatively, the precessing frame can be directly read off the waveform, an approach that is less coordinate-dependent and that can readily be extended through merger where there is no notion of an orbital plane. Proposals in this sense include a maximization of the modes $22$ and $2,-2$~\\cite{Schmidt+10}, and the construction of an angular velocity for the waveform~\\cite{Boyle13}.\n\nHere, we use the dominant eigenvector prescription of~\\cite{OShaughnessy+11}, to which we refer (as well as~\\cite{OOS12, Boyle13}) for more details. One defines the matrix\n\\be\n\t\\langle \\bm{L} \\bm{L} \\rangle_{ab} \\equiv \\frac{\\sum_{\\ell, m, m'} h^{*}_{\\ell m'} \\bra{\\ell, m'} L_{a} L_{b} \\ket{\\ell, m} h_{\\ell m} }{ \\sum_{\\ell, m, m'} h^{*}_{\\ell m'} h_{\\ell m} } \\,,\n\\ee\nwhere the $\\ket{\\ell, m}$ are a notation for the spin-weighted spherical harmonics ${}_{-2}Y_{\\ell m}$, the indices $a,b$ are ordinary spatial incides, and $L_{a}$ stands for the angular-momentum operator, acting on the bras and kets $\\ket{\\ell, m}$ in the usual fashion. Defining $L_{\\pm} = L_{x} \\pm i L_{y}$,\n\\begin{subequations}\n\\begin{align}\n\tL_{+} \\ket{\\ell, m} &= \\begin{cases}\\sqrt{\\ell (\\ell+1) - m (m+1)} \\ket{\\ell, m+1} \\;\\text{if} \\; m<\\ell, \\\\ \\;\\; 0 \\;\\;\\text{otherwise} \\end{cases} \\\\\n\tL_{-} \\ket{\\ell, m} &= \\begin{cases}\\sqrt{\\ell (\\ell+1) - m (m-1)} \\ket{\\ell, m-1} \\; \\text{if} \\; m>-\\ell, \\\\ \\;\\; 0 \\;\\;\\text{otherwise} \\end{cases} \\\\\n\tL_{z} \\ket{\\ell, m} &= m \\ket{\\ell, m} \\,.\n\\end{align}\n\\end{subequations}\nNote that in the original proposal~\\cite{OShaughnessy+11}, $\\psi_{4}$ was used instead of the strain. The $z$-axis of the precessing frame is then chosen to be the dominant eigenvetor of the matrix $\\langle \\bm{L} \\bm{L} \\rangle_{ab}$. The construction of the precessing frame is then supplemented by the minimal rotation condition~\\cite{Boyle+11}, see~\\eqref{eq:gammadot}.\n\n\\section{Explicit expression for the stencil coefficients}\n\\label{app:stencil}\n\n\\begin{table}[t]\n\\begin{ruledtabular}\\caption{Stencil coefficients $a_{N,k}^{\\epsilon}$ entering the formula~\\eqref{eq:stencilfresnel}, given here for $\\epsilon=1$. The case $\\epsilon=-1$ is obtained by complex conjugation.}\\label{tab:stencil}\n\\begin{tabular}{c|cccccc}\n\t$N \\backslash k$ & $0$ & $1$ & $2$ & $3$ & $4$ & $5$ \\\\\n\t\\hline\n\t$0$ & $1$ & - & - & - & - & - \\\\\n\t$1$ & $1+i$ & $-i$ & - & - & - & - \\\\\n\t$2$ & $\\frac{1+5i}{4}$ & $\\frac{3-4i}{3}$ & $\\frac{-3+i}{12}$ & - & - & - \\\\\n\t$3$ & $\\frac{17 i-3}{18}$ & $\\frac{13-7 i}{8}$ & $\\frac{-5-i}{10}$ & $\\frac{11 i+15}{360}$ & - & - \\\\\n\t$4$ & $\\frac{185 i-69}{288}$ & $\\frac{209-47 i}{120}$ & $\\frac{-41 i-67}{120}$ & $\\frac{251 i+147}{2520}$ & $\\frac{-29 i-7}{3360}$ & \\\\\n\t$5$ & $\\frac{1669 i-690}{3600}$ & $\\frac{2393-135 i}{1440}$ & $\\frac{-645 i-646}{1260}$ & $\\frac{3295 i+831}{20160}$ & $\\frac{26-345 i}{15120}$ & $\\frac{429 i-115}{302400}$ \\\\\n\\end{tabular}\n\\end{ruledtabular}\n\\end{table}\n\nIn this Appendix, we give explicit expressions for the stencil coefficients entering~\\eqref{eq:stencilfresnel}. In this work we used only low order stencils with $N\\leq 20$, and one can trivially invert of the system~\\eqref{eq:stencilsystem}, as this operation has to be done only once. One can also obtain closed-form expressions for these coefficients, thanks to the particular choice of samples at $\\pm kT$ that gives to the system~\\eqref{eq:stencilsystem} the form of a Vandermonde system. Defining the Vandermonde matrix $V(x_{0},\\dots,x_{N})$ as $V_{ij} = (x_{j})^{i}$, setting $x_{j} = j^{2}$, and $b_{p} \\equiv (-i\\epsilon)^{p}(2p-1)!!$, the linear system~\\eqref{eq:stencilsystem} becomes\n\\be\n\tb_{p} = \\sum\\limits_{k=0}^{N} V_{pk} a_{N,k}^{\\epsilon} \\,.\n\\ee\nThe expression of the inverse of a Vandermonde matrix in terms of symmetric polynomials then allows us to write the $a_{N,k}^{\\epsilon}$, for every finite order $N$, as:\n\\begin{align}\n\ta_{N,k}^{\\epsilon} &= \\frac{1}{\\prod\\limits_{\\substack{q=0 \\\\ q\\neq k}}^{N} (q^{2}-k^{2})} \\sum\\limits_{p=0}^{N} (i\\epsilon)^{p}(2p-1)!! \\nn\\\\ & \\quad \\cdot \\sum\\limits_{\\substack{ 0 \\leq j_{1} < \\dots < j_{N-p} \\leq N \\\\ j_{1}, \\dots, j_{N-p} \\neq k}} j_{1}^{2}\\dots j_{N-p}^{2}\n\\end{align}\nThe two cases $\\epsilon\\pm 1$ correspond simply to a complex conjugation of the coefficients $a_{N,k}^{\\epsilon}$. Table~\\ref{tab:stencil} gives the resulting complex rational values for these coefficients for $N\\leq 5$.\n\n\\section{Precession in current Fourier-domain waveform models}\n\\label{app:precpreviousapproaches}\n\nIn this Appendix, we give a more detailed overview of the treatment of precession in existing waveform models that generate signals directly in the Fourier domain. Our objective is not to give an exhaustive account of the various existing models, but rather to highlight how their treatment relates to ours.\n\nTo describe previous approaches to the problem of producing precessing waveforms directly in the Fourier domain, avoiding the use of a time-domain generation followed by an FFT, it is useful to introduce schematically four different approximations (dropping the mode indices):\n\\begin{itemize}\n\t\\item unstable SPA: $\\calT(f) \\tilde{h}^{\\rm P}(f) = \\mathrm{SPA}\\left[ \\calD^{*} h^{\\rm P} \\right](f)$,\n\t\\item $0^{\\text{th}}$-order SUA: $\\calT(f) = \\calD^{*}(\\tfSPA) $,\n\t\\item Fourier-domain $0^{\\text{th}}$-order SUA: $\\calT(f) = \\calD^{*}(\\omega = \\pi f ) $,\n\t\\item SUA: $\\calT(f) = \\frac{1}{2} \\sum\\limits_{k} a_{k} \\calD^{*}(\\tfSPA \\pm k \\Tf^{\\rm SPA})$.\n\\end{itemize}\n\nIn the first option, one applies directly the SPA, as described in Sec.~\\ref{subsec:SPA}, to the product of the modulation and the signal. This is known (see e.g.~\\cite{KCY13}) to lead to possible pathologies, since the prefactor $1/\\sqrt{\\ddot{\\phi} + \\ddot{\\Phi}_{\\rm prec}}$ can blow up due the precessing contributions to the phase of the inertial-frame waveform.\n\nThe second option corresponds to simply multiplying the Fourier-domain signal by the modulation function evaluated at the time $\\tfSPA$ as defined in~\\eqref{eq:deftfSPA}. In the SUA formalism of Ref.~\\cite{KCY14}, this treatment could be called the 0th order as it amounts to using a stencil reduced to a single point, i.e. using only one term with $a_{0,0} = 1$ in~\\eqref{eq:stencilfresnel}. It is equivalent to the leading order of our formalism ($\\{N:0 | A:0 | d:0 \\}$ in the terminology of Sec.~\\ref{subsec:executivesummary}), with the difference that we use a more general definition of $t_{f}$ (see~\\eqref{eq:deftf}) that extends through the merger and ringdown.\n\nWhile keeping implictly the same level of approximation, one can also use frequency-based expressions for the modulation, as in Refs.~\\cite{LOS13, Hannam+13}. The precessing-frame evolution is then modelled using post-Newtonian expressions for the Euler angles $(\\alpha^{\\rm PN}, \\beta^{\\rm PN}, \\gamma^{\\rm PN})$ as functions of the orbital frequency $\\omega$. Using the SPA-inspired correspondence~\\eqref{eq:deftfSPA} between the orbital and Fourier-domain frequency, one then writes\n\\be\\label{eq:precPhenomP}\n\t\\calT^{\\ell}_{mm'}(f) = \\calD^{\\ell *}_{mm'}(\\alpha^{\\rm PN}, \\beta^{\\rm PN}, \\gamma^{\\rm PN}) \\left( \\omega=\\pi f\\right) \\,.\n\\ee\nWhen the SPA is valid for the underlying signal $h^{\\rm P}_{\\ell m}$, the condition $\\omega(t) = \\pi f$ is equivalent by definition to $t=t^{\\rm SPA}_{f}$. In~\\cite{LOS13}, only the inspiral phase is modelled, and only single-spin configurations, for which the system undergoes simple precession~\\cite{Apostolatos+94, Kidder95}. The PhenomP model~\\cite{Hannam+13} maps the two spins to a single effective spin, and uses Euler angles computed in the limit of a small opening angle of the precession cone and at the spin-orbit level (see also~\\cite{BBF11, MBBB13}).\n\nIn the PhenomP model~\\cite{Hannam+13}, the frequency-based transfer function~\\eqref{eq:precPhenomP} is used as an effective prescription covering the whole Fourier-domain frequency band, including the merger and ringdown. Note that this procedure amounts to using PN results outside of their range of validity, since in the merger-ringdown phase both the PN perturbative treatment and the SPA approximation break down. In particular, when computed as a function of time from the balance equation between emitted flux and orbital energy $\\calF = -dE/dt$, the orbital $\\omega^{\\rm PN}(t)$ blows up and cannot be extended through merger. In practice, one finds however that the extended frequency-based expressions~\\eqref{eq:precPhenomP} are mildly varying when extrapolating to higher frequencies, and this approach has been validated by comparisons to numerical relativity waveforms~\\cite{Hannam+13}. Future versions of PhenomP~\\cite{PhenomPv3InPrep} will move beyond the single-spin approximation by incorporating analytic solutions for the precession trajectory of double-spin systems~\\cite{Chatziioannou+17}.\n\nIn the SUA formalism proposed in~\\cite{KCY13, KCY14}, one extends the SPA to incorporate the leading-order correction during the inspiral. The transfer function is then computed by evaluating the modulation on a stencil of times centered around the time-of-frequency given by the SPA, arriving at the formula~\\eqref{eq:stencilfresnel} with the times $t = \\tfSPA$ and $T = \\TfSPA$ as defined in~\\eqref{eq:deftfSPA} and~\\eqref{eq:TfSPA}. As described in Sec.~\\ref{sec:formalism}, our formalism reduces to the SUA when keeping only the quadratic phase correction, but the SUA is a priori limited to the inspiral phase of the signal through the definitions of the times $t^{\\rm SPA}_{f}$ and $T^{\\rm SPA}_{f}$. For inspiral waveforms, Ref.~\\cite{KCY14} showed that this treatment improves the accuracy with respect to the 0th-order approximation.\n\n\\section{Precessing waveform and the LISA Fourier-domain response}\n\\label{app:precLISA}\n\nIn this Appendix, we present an argument for the applicability of the treatment of Section~\\ref{sec:formalism} to a Fourier-domain waveform that already contains precession effects, thus combining our investigations of Secs.~\\ref{sec:LISA} and~\\ref{sec:precession}. Let us first note that one possible approach would be to incorporate both the precession modulation and the LISA modulation and delay in a single $G(f,t)$ kernel. This is what is done notably in~\\cite{Klein+15}, with inspiral-only precessing waveforms (and a low-frequency approximation for the response). In that approach, comparing the results of Secs.~\\ref{sec:LISA} and Sec.~\\ref{sec:precession}, it appears that the precession is more challenging to model than the LISA response -- thus the accuracy of the final result should depend mainly on the precession treatment. In the following, we take a different route and investigate wether we can directly process Fourier-domain precessing mode contributions of the form $\\calT^{\\ell}_{m m'}(f) \\tilde{h}_{\\ell m'}(f)$ through the LISA response. We will make simplifying assumptions, assuming simple precession and keeping to order-of-magnitude estimates only. We leave for future work a more thorough investigation of precessing waveforms for LISA beyond simple precession and for IMR waveforms.\n\nFor simplicity, we assume that the precession transfer function has been computed using the leading-order approximation, as including corrections should not change the timescales involved. Thus, we consider the signal\n\\be\\label{eq:htildeasaprecmodecontrib}\n\t\\tilde{h} (f) \\equiv \\calT^{\\ell}_{m m'}(f) \\tilde{h}_{\\ell m'}(f) = \\calD^{\\ell *}_{m m'}(\\alpha, \\beta, \\gamma)(\\tf) \\tilde{h}_{\\ell m'}(f)\n\\ee\nto be processed through the LISA response. If we assume simple precession, we can use the results of Sec.~\\ref{subsec:sizecorrPrec} for the behaviour of $(\\alpha, \\beta, \\gamma)$ as a function of $t$. Restricting ourselves to the inspiral part, we will also use the SPA expressions~\\eqref{eq:tfSPA} and~\\eqref{eq:TfSPA} for the times $\\tf$ and $\\Tf$. According to~\\eqref{eq:wignerphasesimpleprec}, the mode contribution~\\eqref{eq:htildeasaprecmodecontrib} above acquires a Fourier-domain phase $\\Psi \\rightarrow \\Psi + \\Phi_{\\rm prec}$ with\n\\be\\label{eq:additionalPhiprec}\n\t\\Phi_{\\rm prec} = -(m' \\cos \\beta(\\tf) - m) \\alpha(\\tf) \\,\n\\ee\nwith $\\beta(t)$ varying on the radiation-reaction timescale and $\\alpha(t)$ varying on the precession timescale with $\\dot{\\alpha} = \\Omega_{\\rm prec}$. The Fourier-domain amplitude becomes $A\\rightarrow A \\times d^{\\ell}_{mm'} (\\beta(\\tf))$. If $\\beta$ varies on the radiation-reaction timescale, this extra factor can be absorbed in a redefinition of the $a(\\tf)$ amplitude factor in~\\eqref{eq:ASPA}, so that it won't affect the separation of timescales.\n\nUsing the derivatives\n\\be\n\t\\frac{\\ud \\tf}{\\ud f} = 2\\pi \\Tf^{2}\n\\ee\nand\n\\be\n\t\\frac{\\ud \\Tf}{\\ud f} = -2\\pi \\Tf^{5} \\ddot{\\omega}(\\tf) = - 2\\pi \\frac{11}{12} \\frac{\\Tf}{\\pi f} \\,,\n\\ee\nwhere we have used $\\ddot{\\omega} = 11/3 (\\dot{\\omega})^{2}/\\omega$ following~\\eqref{eq:omegaphiN}, the extra Fourier-domain phase contribution~\\eqref{eq:additionalPhiprec} cause new contributions in~\\eqref{eq:deftf} and~\\eqref{eq:defTf} as\n\\begin{subequations}\n\\begin{align}\n\t-\\frac{1}{2\\pi} \\frac{\\ud \\Phi_{\\rm prec}}{\\ud f} &\\sim (m' \\cos \\beta - m) \\Tf^{2} \\Omega_{\\rm prec} \\,, \\label{eq:additionaltf}\\\\\n\t-\\frac{1}{4\\pi^{2}} \\frac{\\ud^{2} \\Phi_{\\rm prec}}{\\ud f^{2}} &\\sim (m' \\cos \\beta - m) \\Tf^{2} \\left[ \\frac{11}{6} \\frac{\\Omega_{\\rm prec}}{\\pi f} - \\Tf^{2} \\dot{\\Omega}_{\\rm prec} \\right] \\,, \\label{eq:additionalTf}\n\\end{align}\n\\end{subequations}\nwhere we ignored $\\dot{\\beta}$. The new term~\\eqref{eq:additionaltf} means that, when processing the signal through the LISA response, we would attribute a different $\\tf$ to each mode contribution.\n\nThe new term~\\eqref{eq:additionalTf} will enter $\\epsilon_{\\Psi 2}$ as defined in~\\eqref{eq:deffom}. Comparing to $\\Tf^{2}$, and ignoring the prefactor depending on the mode number (of order a few), we have two terms in the bracket. The first term is $\\Omega_{\\rm prec} / \\omega$, which is a quantity of order 1PN, and should remain well below 1. The second term is $\\dot{\\Omega}_{\\rm prec} / 2\\dot{\\omega}$. Under the simple precession assumption, \\eqref{eq:Omegaprec} gives $\\dot{\\Omega}_{\\rm prec} \\sim \\dot{\\omega}/\\omega \\Omega_{\\rm prec}$, and this term suppressed like the first term. Thus, in this case the contribution to $\\epsilon_{\\Psi 2}$ should be subdominant, the findings of Sec.~\\ref{sec:LISA} for non-spinning waveforms should apply.\n\nIn the generic case of double-spin precession, however, the above argument does not apply anymore as $\\Omega_{\\rm prec}$ varies itself on the precessional timescale and $\\Omega_{\\rm prec} / \\dot{\\omega}$ is not small in general. In fact, the cases where $\\dot{\\Omega}_{\\rm prec} \\sim \\dot{\\omega}$, with possible cancellations, are the ``catastrophes'' preventing the application of the SPA to the full time-domain precessing signal~\\cite{KCY13}. We leave to future work the question of wether this situation could be challenging for the perturbative formalism, after taking into account the appropriate factors for the error estimates as in Sec.~\\ref{subsec:lisafom}.\n\nNote that, if we were instead to incorporate the full precession transfer function $\\calT^{\\ell}_{mm'}$ as an envelope function multiplying $A(f)$, then applying the criterion~\\eqref{eq:deffom} for $\\epsilon_{A1}$ would show that, even in the case of simple precession, the perturbative analysis would be challenged at both ends of the mass spectrum, for low-mass and high-mass systems.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\bibliography{references.bib}\n\n\n\\end{document}\n", "meta": {"hexsha": "6a51f5a35eed6beeb9207fe1eb6f1002499eae0b", "size": 210337, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/paper_method.tex", "max_stars_repo_name": "titodalcanton/flare", "max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z", "max_issues_repo_path": "docs/paper_method.tex", "max_issues_repo_name": "titodalcanton/flare", "max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/paper_method.tex", "max_forks_repo_name": "titodalcanton/flare", "max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z", "avg_line_length": 134.143494898, "max_line_length": 2086, "alphanum_fraction": 0.7406590376, "num_tokens": 59921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3185153972401916}}
{"text": "\\documentclass[12pt,a4paper]{amsart}\n\\usepackage[margin=1in]{geometry}\n\\usepackage[latin1]{inputenc}\n\\usepackage{amsmath}\n\\usepackage{amsfonts}\n\\usepackage{amssymb}\n\\usepackage{graphicx}\n\\usepackage{listings}\n\\usepackage{hyperref}\n\\usepackage{url}\n\\begin{document}\n\t\\title{Deformable Objects Using Fast Lattice Shape Matching}\n\t\\author{Marwan Kallal}\n\t\\date{December 17, 2017}\n\t\\maketitle\n\t\n\t\\section{Introduction}\n\tI attempt to use the results of Rivers and James \\cite{rivers} on Fast Lattice Shape Matching (FLSM) to make our already fuzzy bunny deformable as well. I have omitted collision and other physics in the interest of time and am focusing on  deformations upon movements of single particle masses. I will also be using the unoptimized version SLSM (Slow LSM), to focus on the dynamics of these deformations.\n\t\n\t\\section{Explanation of FLSM}\n\t\\subsection{Constructing the Lattice}\n\tThe first step to FLSM is to build a lattice, or grid, that encloses the mesh. We start by creating a bounding box around the mesh. From here we round the dimensions of the bounding box up to fit an integral number of grid squares. Each grid square has an associated particle which will be used for movement and other calculations.  \n\t\n\t\\subsection{Creating Particles}\n\tFrom here we need to check which grid squares are actually in contact with the inside of the mesh. We can do this using a standard triangle mesh voxelization algorithm \\cite{rosen}. Each particle will have a mass associated with it to properly simulate physical responses. To differentiate between inner and outer particles, we can set the particle mass of outside particles to 0.\n\t\n\t\\subsubsection{Assigning Vertices}\n\tNow that we have our grid and particles, we can assign vertices to their associated particles. This allows us to move the vertices of the mesh as the particles move, essentially sharing the transform of the particle with that vertex. To do this, we can iterate through the vertices of the mesh, and calculate which grid square they lie in. We can then assign that vertex to the particle in that grid square.\n\t\n\t\\subsection{Creating Regions}\n\tShape matching regions make up the building blocks of the deformation system. We start by specifying a region half-width $w$. This region size will also change the dynamic properties of the mesh, with larger regions making the mesh stiffer. This is because the way that region center of mass is calculated, and therefore the final rotations of the regions will be smaller with the displaced particles having less weight relative to the total. Using masses of 0 for particles outside the mesh is important for making sure that their potential movement doesn't affect the deformation of the object. The regions will also overlap to make sure that the object doesn't flop around and fall apart. We can make a region centered around every particle as long as no part of the region exceeds the range of the bounding box (and thus the lattice we constructed).\n\t\n\t\\subsection{Dynamics}\n\t\n\t\\subsubsection{Particle Movement}\n\tParticles are affected by outside forces such as gravity and collisions. This creates movement among the particles, which will then move regions, affecting the final resting position of the particles for that timestep. \n\t\n\t\\subsubsection{Region Movement}\n\tWhen particles move, this changes the center of mass of the regions. In order to move the region properly and assign goal positions, we need to know both the original center of mass of the region $\\mathbf{c}_r^0$ and the newly deformed one $\\mathbf{c}_r$. We can calculate them both for each region using:\n\t\n\t\\[ \\frac{1}{Region Total Mass} \\sum_{i \\in Region Particles} \\tilde{m}_i \\mathbf{x}_i\\]\n\t\n\tNow we must find a way to rotate and translate the regions in a way that preserves the shape of the particles within the region as much as possible.\\cite{rivers} proposes an approximation of the least squares rotation given the position of the deformed particles relative to the original region. This method uses an intermediate matrix value $\\mathbf{A_r}$ (shown below) and then a polar decomposition to extract the rotational component.\n\t\n\t\\[ \\mathbf{A_r} = \\sum_{i \\in Region} \\tilde{m}_i ( \\mathbf{x}_i - \\mathbf{c}_r ) ( \\mathbf{x}_i^0 - \\mathbf{c}_r^0 )^\\top \\]\n\t\n\tFrom here we can take the polar decomposition of $\\mathbf{A_r}$ to obtain the rotational component, $\\mathbf{R_{r}}$. To get the final transformation we need for the region, we use the two centers of mass we found earlier, $\\mathbf{c}_r^0$ and $\\mathbf{c}_r$, and our newly obtained $\\mathbf{A_r}$, as shown below:\n\t\n\t\\[ \\mathbf{T}_r = [\\mathbf{R}_r (\\mathbf{c_r} - \\mathbf{R}_r \\mathbf{c}_r^0) ] \\]\n\t\n\t\\subsubsection{Setting Particle Positions}\n\t\n\tBecause we know the regions which each particle belongs to, we can place a goal position $\\mathbf{g}$ using the average of the transformations for the regions containing it. We can then use the relative distance between original and goal positions of the particles, as well as the outside forces mentioned above, to find the velocities and then final positions of the particles as shown below.\n\t\n\t\\[ \\mathbf{v}(t+h) = \\mathbf{v}(t) + \\frac{\\mathbf{g}(t) - \\mathbf{x}(t)}{h} + h \\frac{\\mathbf{Forces}(t)}{m} \\]\n\t\n\t\\[ \\mathbf{x}(t+h) = \\mathbf{x}(t) + h \\mathbf{v}(t + h) \\]\n\t\n\tNow that we have the final positions of the particles, we can move the associated vertices with the same transformations as the particles to make the mesh itself deform realistically.\n\t\n\t\\section{What I Learned}\n\tI learned quite a bit about graphics and deformable objects from this projects. Having worked with the bunny and the dynamic fur before this, I had an idea of how the dynamics might work, with spring like coefficients and the like. I had originally thought of doing a 3 dimensional grid of springs and point masses, like some of the cloth dynamics demos, but wanted to explore a deeper problem. I read through some other papers as well, such as \\cite{JamesDoug1999Aart} which described much more complicated, but realistic, ways of deforming objects with volume preservation and many tunable parameters. The problem was that I couldn't fully understand the math they were using, so I moved on. \\\\\n\t\\indent I finally found the \\cite{rivers} paper, which seemed to be much more in my reach mathematically. I first set out to understand the basic building blocks of the problem. It seems similar at first glance to the spring problem, with particles trying to stay within their regions, but it gives you more tunability for floppiness and area of effect when deformed than a straight up spring lattice will.\n\t\\indent One of the more interesting parts of the paper was the fast summation they used to precompute and reuse as many values as possible, and is why the paper is called FLSM. I will cover the way this works in Section 3. This was also good to learn, showing a way that we can significantly reduce processor time when doing summations by finding ways to reuse previously calculated values.\n\t\n\t\\section{Optimizations}\n\tThere are many potential optimizations we can make, many of them included in the \\cite{rivers} paper.\n\t\n\t\\subsection{Fast Summation}\n\tThe main breakthrough of the paper was the introduction of a fast summation algorithm that stores as much information as possible to be reused in future computations.\n\t\n\t\\section{My Implementation}\n\tI began by using the bunny mesh we had been using before. I generated a bounding box and rounded it up to the nearest grid square so that we could have integral particles. You can see this process in \\texttt{lattice.h::get\\_lattice\\_bounds()}. I then assigned each grid square a particle and to that particle a set of vertices to share their transforms with. This is done in \\texttt{Lattice::create\\_lattice()} which then calls \\texttt{Particle::setPosition()}. Next I started to assign regions. For simplicity I ignored the mesh when constructing particles and regions, and just used the expanded bounding box as our object. I created regions with half-width $\\mathbf{w} = 1$, as shown in \\texttt{particle.h:Region()}. All of the necessary values have been set in the particles. All that's left now is to find the centers of mass of the new regions, use the least squares rotation of the regions and apply those transforms to the particles and associated vertices.\n\t\\subsection{State of Affairs}\n\tThe code is not currently fully functional. I have created what I stated in Section 5, and have some comments detailing the approach for the rest in the code, marked with \\texttt{//TODO:}. The most important pieces of pseudocode can be found in \\texttt{Lattice::deform\\_timestep()}, detailing the procedures to take and values to set in order to deform the bunny.\n\t\n\t\\bibliographystyle{plainnat}\n\t\\bibliography{references}\n\t\n\\end{document}", "meta": {"hexsha": "d208912c1c609dfbfbbd12869491fb2a30f8965b", "size": 8803, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/README.tex", "max_stars_repo_name": "marwankallal/deformable-gl3", "max_stars_repo_head_hexsha": "9b5c7585079c8d8d7b565c1d6f42f5ac058cff66", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/README.tex", "max_issues_repo_name": "marwankallal/deformable-gl3", "max_issues_repo_head_hexsha": "9b5c7585079c8d8d7b565c1d6f42f5ac058cff66", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/README.tex", "max_forks_repo_name": "marwankallal/deformable-gl3", "max_forks_repo_head_hexsha": "9b5c7585079c8d8d7b565c1d6f42f5ac058cff66", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 110.0375, "max_line_length": 966, "alphanum_fraction": 0.7809837555, "num_tokens": 2076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3184632424367406}}
{"text": "% chap1.tex\n\n\\chapter{Introduction and Overview}\\label{chap:intro}\n\\noindent Deep neural networks have demonstrated excellent results in many machine learning tasks [REFERENCES:TBD] and became a default choice for machine learning researchers irrespective of the end result they achieved.\nComputer vision , Natural language and Speech processing tasks have scaled to the next level of accuracies using these networks.\n\\paragraph{Structure:} The core structure of Neural network is the Neurons arranged in a layer manner also known as hidden layer and stack of these layers with interconnected Neurons provides depth to the network. This arrangement of layers is known as network architecture. A simple Neural Network is shown in Figure~\\ref{fig:nn_simple_dep}.\nSeveral networks are proposed till date for the range of machine learning tasks.[REFERENCES:TBD]\n\\paragraph{Training:} Network architecture remains passive until it gets trained for the specific task for which network parameters are estimated for the desired level of prediction performance on data samples outside training data set, also known as Generalization performance.\nThe most important part is the training strategy which encompass choosing the hyper-parameters to intermediate updates along with learning algorithm.\nThe number of hyper-parameters termed as annoying knobs to be adjusted [Bengio 2012: Practical recommendations] and famously known as nuisance parameters are quite high. On top of this range of choices for these hyper-parameters make exhaustive search impractical.\nOnce these parameters are chosen, training can be proceed and the algorithm, which is more often than not is Stochastic gradient descent [References] along with Back propagation [Reference: Rumelhart] as a default choice allows network to evolve from untrained to train network. Each training process has stopping criterion, which is more intuition than rules which guides training progress including stopping point.\n\n\\begin{figure}[H]\n\\centering\n\t\\subfigure{\n\t\\centering\n\t\\includegraphics[scale=0.50]{Images/nn_simple_dep}\n}\n\t\\caption{\\label{fig:nn_simple_dep} A Simple Neural Network}\n\t\\medskip\n\t\\small\n\t\\begin{flushleft}\n\t\\textit{Four layer fully connected Neural network is shown in \\ref{fig:nn_simple_dep}. All Neurons in successive layers are connected to each other, while within layer they are not connected.\\\\ \n\tInput feeds the input features and propagation of features undergoes transformation or encoding as it passes via layers. \n\tIntermediate layers are known as hidden layers. Output layer gets the final output in desired format. \\\\\n\tIn case of classification task it could be class vector representing class probabilities, in case of regression task it is the numerical value and in case of unsupervised task it can be input vector itself. Network parameters gets updated via famous technique called back propagation formulating this problem as optimization problem in which loss occured is minimized iteratively.}\n\t\\end{flushleft}\n\t \n\\end{figure}\n\n\nConsidering all these background the \\textbf{Training Life Cycle} of DNN's has 3 main stages as shown in Figure~\\ref{fig:dnn_lifecycle}\n\n\\begin{enumerate}\n\t\\item Choosing network structure\n\t\\item Selection of hyper parameters and training algorithm\n\t\\item Network updates during training and stopping criterion\n\\end{enumerate}\n\n\\begin{figure}[H]\n\\centering\n\t\\subfigure{\n\t\\centering\n\t\\includegraphics[scale=0.50]{Images/dnn_training_lifecycle}\n}\n\t\\caption{\\label{fig:dnn_lifecycle} DNN Training Lifecycle} \n\t\\medskip\n\t\\small\n\t\\begin{flushleft}\n\t\\textit{Training lifecycle is shown in \\ref{fig:dnn_lifecycle}. Firstly network choice needs to be made, which would be type of network such as CNN, LSTM, ANN, RNN, Auto encoder and so on, once network type is finalized network configuration has to be decided, such as number of layers, number of neurons in layers, their interconnections, filter size in case of CNN and so on.\\\\\n\tsecondly comes choice of hyperparameters, which starts with some standard initial choices and during learning gets tuned for better performance.\\\\\nLastly choice of learning algorithm and update rule for back propagation is to be decided, Here stopping criterion also is crucial which governs the network final learnt parameters.\\\\\nThis also allows fine tuning of network structure or hyperparameters as more and more knowledge about underlying data and its performance in current selected environment is known.}\n\t\\end{flushleft}\n\t\t\n\\end{figure}\n\\section{Chapters Organization}\nThis study is divided into 6 chapters, Chapter 2, discusses \\textbf{Network architecture}, Chapter 3 discusses \\textbf{Hyper-parameters}, Chapter 4 discusses \\textbf{Training the Network}, Chapter 5 discusses the \\textbf{Insights and Recommendations} from this study. Chapter 6 \\textbf{concludes} and poses some \\textbf{open questions} for future work.\n\n\\subsection{Network types}\nChapter \\ref{chap:nwstruct} details different architectures, which can be seen as small survey on the state of the art networks used in deep learning.We will keep them for study purposes.\n\nAs we studied the details and interdependencies among the training parameters,so we have used our own network, we call it \\textbf{ GsNet}. We recommend to use them for comparative study of this kind.\nTable \\ref{tab:gsnet} shows the layers configuration of GsNet-2,GsNet-3 and GsNet-5.\n\\begin{table}[!htbp]\n\t\\centering\n\t\\caption{\\textbf{GsNet architectures}}\n\t\\label{tab:gsnet}\n\t\\vspace{2mm}\n\t\\begin{tabular}{|l|l|l|}\n\t\t\\hline\n\t\t\\hline\n\t\t\\textbf{GsNet-2} & \\textbf{GsNet-3} & \\textbf{GsNet-5} \t\t\\\\\n\t\t\\hline\n\t\t\\hline\n\t\tconv 3x3x64 & conv 3x3x64 \t& conv 3x3x64 \t\t\\\\\n\t\tpool 2x2    & pool 2x2 \t\t& pool 2x2\t\t\t\\\\\n\t\t\\hline \n\t\tconv 3x3x64 & conv 3x3x64 \t& conv 3x3x64 \t\t\\\\\n\t\tpool 2x2    & pool 2x2 \t\t& pool 2x2 \t\t\t\\\\\n\t\t\\hline\n\t\t\n\t\t& conv 3x3x64 \t& conv 3x3x64 \t\t\\\\\n\t\t& pool 2x2 \t\t& pool 2x2 \t\t\t\\\\\n\t\t\\hline\n\t\t&        \t\t& conv 3x3x64 \t\t\\\\\n\t\t&  \t\t\t\t& pool 2x2 \t\t\t\\\\\n\t\t\\hline\n\t\t&  \t\t\t\t& conv 3x3x64 \t\t\\\\\n\t\t&  \t\t\t\t& pool 2x2 \t\t\t\\\\\n\t\t\\hline\n\t\tdense,128 \t& dense,128 \t& dense,128  \t\t\\\\\n\t\t\\hline\n\t\tsoftmax,c \t& softmax,c \t& softmax,c  \t\t\\\\\n\t\t\\hline\n\t\t\\hline\n\t\\end{tabular}\n\\end{table}\n\nWe have used these networks for our experiments and their analysis. This may bring how depth affects learning. Different architectures in practice are described, which can be seen as small survey on state of the art network architectures in chapter \\ref{chap:nwstruct}.\n\n\\subsection{Hyper-parameters}\nHyper-parameters are discussed in chapter \\ref{chap:hyperparams}.Main parameters, which we studied are as following\n\\begin{enumerate}\n\t\\item Batch Size\n\t\\item Optimizations\n\t\\item Initializations\n\\end{enumerate} \n\nFirstly we describe all the different prescribed available techniques for these parameters which can be seen as a small survey of the available studies, experimental results and techniques.\n\nSecondly we present results of almost exhaustive set of parameters configuration. Then best of parameters and configurations are chosen for the next set of experiments.\n\n\\subsection{Training the network}\n\nChapter \\ref{chap:training} discusses training the network and study which describes different techniques used in training.We will also explain our training set up which is used for our experiments.\n\n\n\\subsection{Insights and Recommendations}\nChapter \\ref{chap:recommendations} provides all insights and analysis of our results. This includes well performing strategies as well as strategies which may didn't  perform well.\nBased on these we will describe our recommendations. Also we will explain novel technique which perform well and provide more stability to the learning system.\n\n\\subsection{Conclusion}\nChapter \\ref{chap:conclusions} concludes with the summary of our study and future direction of this work.\n\n%\\iffalse\n\\section{Notations used}\nThis section explains the notations used through out this study.\n\\subsection{DNN Setting}\nDNN goal is to approximate a target function $g^*$ for the unknown distribution input $X^*=(x_1,x_2,......x_d)^T \\in \\mathbb{R}^d$. The target value is $Y^*=(y_1,y_2,........y_s) \\in \\mathbb{R}^s$. if $\\theta^*$ is the parameters associated, then \n\\begin{equation}\nY^*=g^*(X^*, \\theta^*)\n\\end{equation}\t\t\t\t\t\t\t\t\n\n$X^*$ represents entire input data for the underlying input distribution. \nGetting $X^*$ is almost impossible, so generally $g^*$ is approximate using the representative input $X$ of size $N$ which is sampled from $X^*$ and hoped to have same distribution as the original input distribution. Let $Y$ is the target value for $X$.\n\nSo DNN problem reduces to approximating $ g^*$ using $(X,Y)$ of size $N$. $\\theta=(\\theta_1,\\theta_2...\\theta_m) \\in \\mathbb{R}^m$ represents the parameters which gives best approximation for target function. Finally the DNN has to learn the best $\\theta$  such that $g(X,\\theta) \\sim g^*$. \n\n$g$ represents a chained function in context of DNN as it flows from input to output via hidden layers as shown in \\ref{fig:nn_simple_dep}. $g$ as chained function flowing via hidden layers can  be written as\n\\begin{equation}\ng(X)=g^K(g^{K-1}(g^{K-2}......(g^2(g^1(X))).......)) \n\\end{equation}\nwhere $K$ represents total number of hidden layers and $\\{g^k, k=1....K\\}$ is output of $k^{th}$ layer.Let $\\hat{Y}=g(X)$ then lets define a loss function $\\mathcal{L}(\\hat{Y},Y)$ as the cost it incurs using $g(X)$ to approximate $g^*(X)$ and hence it is also known as cost function.\n\nThe gradient of $\\mathcal{L}$ with respect to $\\theta$ is denoted as $\\nabla_{\\theta_{t}}\\mathcal{L}(\\theta_{t})$ at $t^{th}$ iteration. For simplicity we denote this as $\\nabla_{\\theta_{t}}$, where $\\theta_{t}$ denotes the network parameters at iteration/time $t$.\n\n\\paragraph{Network Parameters}\n%\\fi\n%\\input{Results/cifar100results.tex}\n%\\input{Results/mnistresults.tex}\n%\\input{Results/cifar100results.tex}\n%\\input{Results/cifar10results.tex}\n\n\n\\section{Experimental set up}\nWe have performed exhaustive set of experiment using standard datasets on Nvidia-Tesla K80 GPU.Regularly results are analyzed to reduce the experiment space and become basis for the next set of experiments.\n\\subsection{Databases}\nFollowing is the list of datasets used in the experiments:\n\\begin{enumerate}\n\t\\item MNIST \\cite{lecun-mnisthandwrittendigit-2010}\n\t\\item CIFAR-10 \\cite{Krizhevsky09learningmultiple}\n\t\\item CIFAR 100 \\cite{Krizhevsky09learningmultiple}\n\\end{enumerate}\n\\subsection{MNIST}\nMNIST dataset has 60000 training samples and 10000 testing samples.It is database of handwritten digits. Sample examples are shown in fig.\\ref{fig:mnist_example}\n\n\\begin{figure}[H]\\label{fig:mnist_example}\n\t\\centering\n\t\\includegraphics[scale=1.0]{Images/mnist}\n\t\\caption{MNIST dataset input images example}\n\t\t\\medskip\n\t\t\\small\n\t\tMNIST sample images having handwritten digits from 0-9, image size is 28x28 and images are grayscale, shown samples are randomly chosen, 10 for each class.\n\\end{figure}\n\n\n\\subsection{CIFAR10}\nMNIST dataset has50000 training samples and 10000 testing samples.It is database of different objects present in the images. Sample examples are shown in fig.\\ref{fig:cifar10_example}\n\n\\begin{figure}[H]\\label{fig:cifar10_example}\n\t\\centering\n\t\\includegraphics[scale=0.8]{Images/cifar10}\n\t\\caption{CIFAR-10 dataset input images example}\n\t\\medskip\n\t\\small\n\tCIFAR-10 sample images having different objects present in the images, image size is 32x32 and images are color\n\\end{figure}\n\n\\subsection{CIFAR100}\nCIFAR100 dataset has 50000 training samples and 10000 testing samples.It is database of 100 different object classes. Sample examples are shown in fig.\\ref{fig:cif00_example}\n\n\\begin{figure}[H]\\label{fig:cif00_example}\n\t\\centering\n\t\\includegraphics[scale=0.8]{Images/cifar_100}\n\t\\caption{CIFAR-100 dataset input images example}\n\t\\medskip\n\t\\small\n\tCIFAR-100 sample images consist of database with 100 different object classes, image size is 32x32 and images are color \n\\end{figure}\n\n\\subsection{Software}\nKeras \\cite{chollet2015} is mainly used for almost all the experiments. Theano \\cite{2016arXiv160502688short} is used as main backend for Keras.Python is used as main programming language.\n\n%%%%%%%%%%%%%INITIALIZE VARIABLES%%%%%%%%%%%%%%%%%%\n\\input{init_variable.tex}\n\n\n", "meta": {"hexsha": "6c6ceb4ba2976674c251633e0facec9ad5ed89b1", "size": 12205, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapters/chap1.tex", "max_stars_repo_name": "gaurav-kjain/thesis_work", "max_stars_repo_head_hexsha": "a0c790b89af36d00bd020ff48db8b265ad02f3d7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapters/chap1.tex", "max_issues_repo_name": "gaurav-kjain/thesis_work", "max_issues_repo_head_hexsha": "a0c790b89af36d00bd020ff48db8b265ad02f3d7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapters/chap1.tex", "max_forks_repo_name": "gaurav-kjain/thesis_work", "max_forks_repo_head_hexsha": "a0c790b89af36d00bd020ff48db8b265ad02f3d7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 58.3971291866, "max_line_length": 416, "alphanum_fraction": 0.7730438345, "num_tokens": 3152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.31846323491861916}}
{"text": "\\section{Introduction}\n\\label{sec:introduction}\n\nGiven a mathematical description of a mathematical structure (constants,\nfunctions, relations, and axioms), what should a computer\nimplementation look like?\n\nFor simple cases,\n\\iflong\nthe answer is obvious. A\ngroup would have a type whose values represent group elements, as well\nas a binary operation that is associative, a constant \nneutral element, and a unary inverse operator.\n\n\\else % \\iflong\nlike groups, the answer is obvious.\n\\fi % \\iflong\n%\nBut for more interesting structures, especially those arising in\nconstructive mathematical analysis, the answer is less clear. How do we\nimplement the real numbers (a Cauchy-complete Archimedean ordered\nfield)? Or choose the operations for a compact metric\nspace or a space of smooth functions? Significant research goes into\nfinding satisfactory representations~\\cite{Wei00,TZ98,Bla97,edalat04:_domain_theor_differ_calcul_funct}, while\nimplementations of exact real arithmetic~\\cite{muller01,Lam05a} show that\ntheory can be put into practice quite successfully.\n\n\\iflong\nThe theory of realizability provides guidance in development of\ncomputable mathematics.  Our work shows that realizability is\nnot only  a\nfundamental tool in logic and computability, but also\nhas direct application to the design and implementation of programs:\nit can\n\\else % \\iflong\nRealizability theory can be used to \n\\fi % \\iflong\nproduce a description of the data structure (a code interface)\ndirectly corresponding to a mathematical specification.\n%\n\\iflong\n\n\\fi % \\iflong\n%\n\\iflong\nHowever, doing this by hand quickly grows tedious. \nWorse, different\nbut logically equivalent sets of axioms correspond to different,\nalthough interdefinable, interfaces for code. One might then want to\ncompare several variations, since some interfaces will be more useful\nthan others in practice.\n   % this line intentionally left blank\nAnd \n\\else\nBut\n\\fi % \\iflong \nfew programmers --- even those with strong backgrounds in\nmathematics and classical logic --- are familiar with constructive logic or\nrealizability. \n\\iflong\nProgrammers are used to language constructs\ndescribing interfaces (e.g., C++ header files, ML signatures, or Java\ninterfaces) and to using logical assertions (e.g., preconditions\nand postconditions).\n\\fi\n\n%\\bigskip\n\nWe have therefore implemented a system, called RZ, to serve as a\nbridge between the logical world and the programming\nworld.\\footnote{RZ is publicly available for download at\n  \\url{http://math.andrej.com/rz/}, together with \\iflong\n  the abridged\\else an extended\\fi\\ version of this paper\n  \\iflong presented at CiE 2007 \\cite{bauer+:cie07}\\fi.} RZ translates\nspecifications in constructive logic into standard interface code in a\nprogramming language (currently Objective Caml~\\cite{ocaml}, but other\nlanguages could be used).\n\nThe constructive part of the original specification turns into\ninterface code, listing types and values to be implemented. The rest\nbecomes assertions about these types and values. As these assertions have\nno computational content, so their constructive and classical meanings\nagree, and they can be understood by programmers and mathematicians\naccustomed to classical logic.\n\n%\\bigskip\n\nRZ was designed as a lightweight system\nsupporting a rich input language. Although transforming complete\nproofs into complete code is possible~\\cite{komagata+:tr95}, we have not\nimplemented this. Other excellent systems, including Coq~\\cite{coqart} and\nMinlog~\\cite{benl98:_proof_theor_work}, can\nextract programs from proofs. But they work best managing the entire\ntask, from specification to code generation. In contrast, interfaces generated by RZ can be\nimplemented in any fashion as long as the assertions are satisfied.\nCode can be written by hand, using imperative, concurrent, and other language features\nrather than a ``purely functional'' subset. \n\\iflong\nAt the other\nextreme, the output of RZ can be viewed as a possible \\emph{input} to\na program extraction tool, where the the distinction between\ncomputational and non-computational parts (in Coq these are\n$\\mathtt{Set}$ and $\\mathtt{Prop}$, respectively) has been\nautomatically determined; a corresponding implementation would then be\nprovided via theorem-proving and program extraction.\n\\else %\\iflong\nOr, the output can serve as a basis for theorem-proving and code\nextraction using another system.\n\\fi\n%\\bigskip\n\n\\iflong\nThe paper is organized as follows. In\nSection~\\ref{sec:typed-realizability} we present a version of\nrealizability which is most suitable for our purposes.\nSections~\\ref{sec:spec-sign-assert} and~\\ref{sec:input-language}\ndescribe the input and the output language of RZ, while in\nSection~\\ref{sec:translation} we explain how RZ translates from one to\nthe other. Various implementation issues are discussed in\nSection~\\ref{sec:implementation}, and examples of RZ at work are shown\nin Section~\\ref{sec:examples}. We conclude with remarks on related\nwork in Section~\\ref{sec:related-work}.\n\\fi %\\iflong\n\nAn earlier description of our RZ work appears in \\cite{bauer+:clase05};\nsince then, the input syntax and underlying implementation has been\nsignificantly revised and improved, and the support for dependent types and\nhoisting is completely new.\n\n%%% Local Variables: \n%%% mode: latex\n%%% TeX-master: \"cie\"\n%%% End: \n", "meta": {"hexsha": "7fa82d99af65a446bbe96535ec26759d61c04491", "size": 5326, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "private/cie/introduction.tex", "max_stars_repo_name": "andrejbauer/rz", "max_stars_repo_head_hexsha": "d92cacaf78fb50d61fc6712c74b8fdaf5d2c6d28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-08-28T10:12:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-07T21:04:22.000Z", "max_issues_repo_path": "private/cie/introduction.tex", "max_issues_repo_name": "andrejbauer/rz", "max_issues_repo_head_hexsha": "d92cacaf78fb50d61fc6712c74b8fdaf5d2c6d28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "private/cie/introduction.tex", "max_forks_repo_name": "andrejbauer/rz", "max_forks_repo_head_hexsha": "d92cacaf78fb50d61fc6712c74b8fdaf5d2c6d28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7462686567, "max_line_length": 110, "alphanum_fraction": 0.8009763425, "num_tokens": 1252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.31846323491861916}}
{"text": "%!TEX root = paper.tex\n%\n% GeoClaw\n%\n% Lead currently:  Randy LeVeque\n%\n\n\\subsection{\\geoclaw}\n\nThe \\geoclaw branch of \\clawpack was developed to solve the\ntwo-dimensional shallow water equations over topography\nfor modeling tsunami generation, propagation, and inundation.\nThe \\amrclaw code formed the starting point but it was necessary to make many\nmodifications to support the requirements of this application, as described\nbriefly below.  This code originated with the work of George\n\\cite{dgeorge:masters, dgeorge:phd, dgeorge:jcp}\nand was initially called\n{\\sc TsunamiClaw}.  Later it became clear that many other\ngeophysical flow applications have similar requirements and the code was\ngeneralized as \\geoclaw.\n\n\nOne of the major issues is the treatment of wetting and\ndrying of grid cells at the margins of the flow. The handling of dry\nstates in a Riemann solver is difficult to handle robustly, and has gone\nthrough several iterations.\n\\geoclaw must also be well-balanced in order to preserve steady states, in\nparticular the ``ocean at rest''.\nTo achieve this, the source terms in the momentum equations arising from\nvariations in topography are incorporated into the Riemann solver rather than\nusing a fractional step splitting approach. This is critical for modeling\nwaves that have very small amplitudes relative to the variations in the depth\nof the ocean.  \nSee \\cite{rjl:wbfwave10} for a general discussion of such methods and \n\\cite{dgeorge:phd, dgeorge:jcp} for details of the Riemann solver used in\n\\geoclaw.  Other features of\n\\geoclaw include the ability to solve the equations in latitude--longitude\ncoordinates on the surface of the sphere, and the incorporation of source terms\nmodeling bottom friction using a Manning formulation. More details about the\ncode and tsunami modeling applications can be found in\n\\cite{BergerGeorgeLeVequeMandli:awr11, LeVequeGeorgeBerger:an11}. In 2011, a\nsignificant effort took place to verify and validate \\geoclaw against the US\nNational Tsunami Hazard Mitigation Program (NTHMP) benchmarks\n\\cite{GonzalezLeVequeEtAl2011}.\nNTHMP approval of the code allows \\geoclaw to be used in hazard mapping\nprojects that are funded by this program or other federal and state agencies,\ne.g.\n\\cite{GonzalezLeVequeEtAl2013a,GonzalezLeVequeEtAl2014}.\nOne such project is illustrated in \\cref{fig:ocosta}.\n\nIn addition to a variety of tsunami modeling applications,\n\\geoclaw has been used to solve dam break problems in steep terrain\n\\cite{George:Malpasset}, storm surge problems \\cite{Mandli:ws} (see \\cref\n{fig:surge} and \\cref{tab:surge_timing}),\nand submarine landslides \\cite{jhkim:phd}.  The code also\nformed the basis for solving the\nmulti-layer shallow water equations for storm surge modeling\n\\cite{mandli:phd, Mandli:2013it},\nand is currently being extended further to handle debris flow modeling in the\npackages D-Claw\n\\cite{Iverson:2014dc,George:2014gh} (see \\cref{fig:meager,fig:oso}).\n\nNearly one quarter of the files in the \\amrclaw source library have to be\nmodified for \\geoclaw. There are currently 113 files in the \\amrclaw 2D\nlibrary, of which 26 are\nreplaced by a \\geoclaw-specific files of the same name\nin the \\geoclaw 2D library. For example, to preserve a flat sea surface when\ninterpolating, it is necessary to interpolate the surface elevation\n(topography plus water depth) rather than simply interpolating the depth\ncomponent of the solution vector as would normally be done in \\amrclaw.\nAn additional 24 files in the \\geoclaw shallow water equations\nlibrary handle other complications introduced by the need to model tsunamis\nand storm surge.\n\nSeveral other substantial improvements in the\nalgorithms implemented in \\geoclaw have been made between versions 4.6 and\n5.3.0, including:\n\n\\begin{itemize}\n\\item In depth-averaged flow, the wave speed and therefore the CFL\ncondition depends on the depth.  As a result, flows in shallow water\nthat have been refined spatially may not need to be refined in time.\nThis ``variable-time-stepping'' was easily added along with the anisotropic\ncapabilities that were added to \\amrclaw.\n\\item The ability to specify topography via a set of {\\tt\ntopo} files that may cover overlapping regions at different resolutions has been added.\n The finite volume method requires cell averages of topography, computed by\nintegrating a piecewise bilinear function constructed from the input {\\tt\ntopo} files over each grid cell.  In \\clawpack 5.1.0, this was improved to\nallow an arbitrary number of nested {\\tt topo} grids.\nWhen adaptive mesh refinement is used,\nregridding may take place every few time steps.  Improvements were made\nin 5.2.0 so that topography could be copied rather than always being\nrecomputed in regions where there is an existing old grid.\n\n\\item The user can now provide multiple  {\\tt dtopo} files that\nspecify changes to the\ninitial topography at a series of times.  This is used to specify sea-floor\nmotion during a tsunamigenic earthquake, but can also be used to specify\nsubmarine landslide motion or a failing dam, for example.\n%Major changes were\n%made to these algorithms in 5.1.0 to fix a problem in earlier versions that\n%resulted in incorrect topography motion in some cases, also resulting in a much\n%more robust handling of multiple  {\\tt dtopo} files.\n\n\\item A number of new Python modules has been developed to assist the user\nin working with {\\tt topo} and {\\tt dtopo} files.  These are documented in\nthe \\clawpack documentation and several of them are illustrated with Jupyter\nnotebooks found in the \\clawpack Gallery.\n\n\\item New capabilities were added in 5.0.0 to monitor the maximum of\nvarious flow quantities over a specified time range of a simulation.\nThis capability is crucial for many applications where the maximum\nflow depth at each point, maximum current velocities in a harbor, or\nmaximum momentum flux (a measure of the hydrodynamic force that would\nbe exerted by the flow on a structure) is desired.  Arrival time of\nthe first wave at each point can also be monitored.  Such\ncapabilities were included in the 4.x version of the code, but were\nmore limited and did not always perform properly near the edges of\nrefinement patches.  In Version 5.2 these routines were further\nimproved and extended.  The user can specify a grid of points on which\nto monitor values, and the new code is more flexible in allowing\none-dimensional grids (e.g. a transect), two-dimensional rectangular\ngrids, or an arbitrary set of points\\footnote{Described in\n\\url{http://www.clawpack.org/fgmax.html}}.\n\n\\end{itemize}\n\n\\begin{figure}\n\\hfil\\includegraphics[width=0.9\\textwidth]{final_submission/Fig4}\n\\caption{\\label{fig:ocosta}\nGray's Harbor showing Westport, WA on southern peninsula.\n\\revised{(Google map data and image, 2016.)}\n(b) Simulation of a potential magnitude 9\nCascadia Subduction Zone event, 40 minutes after the earthquake.\n(c) Design for new Ocosta Elementary School in Westport, based in part on\n\\geoclaw simulations \\cite{GonzalezLeVequeEtAl2013a}.\n\\revised{Image courtesy of TCF Architecture.}\n  }\n\\end{figure}\n\n\\begin{figure}[t]\n    \\centering\n    \\includegraphics[width=\\textwidth]{final_submission/Fig5}\n    \\caption{(a) A snapshot of a \\geoclaw storm surge simulation of\nHurricane Ike at landfall.  (b) Tide gauge data computed from \\geoclaw\nand {\\sc adcirc} along with observed data at the same location.\n(c) Computational effort and timings for \\geoclaw and {\\sc adcirc}.  From\n\\cite{Mandli:ws}. \\label{fig:surge}}\n\\end{figure}\n\n\\begin{table}\n    \\centering\n    \\begin{tabular}{|c|c|c|c|}\n        \\hline\n        {\\bf Package} & {\\bf Threads} & {\\bf Wall Time} & {\\bf Core Time} \\\\\n        \\hline\n        {\\sc ADCIRC} & 4000 & 35 minutes & 2333 hours \\\\\n        \\geoclaw & 4 & 2 hours & 8 hours \\\\\n        \\hline\n    \\end{tabular}\n    \\caption{\n    Computational effort and timings for \\geoclaw and {\\sc adcirc}.  From\n\\cite{Mandli:ws}.} \\label{tab:surge_timing}\n\\end{table}\n\n\\begin{figure}[t]\n\\hfil\\includegraphics[height=1.9in]{final_submission/Fig6}\n%\\hfil\\includegraphics[height=1.9in]{meagerview.png}\n%\\hskip 5pt\n%\\includegraphics[height=1.9in]{meager200_labeled.png}\\hfil\n\\caption{\\label{fig:meager}\n(a) Photograph of the 2010 Mt.\\ Meager debris-flow deposit, from \\cite{Allstadt2013}.\n(b) Simulated debris flow, from D.\\ George.\n}\n\\end{figure}\n\n\\begin{figure}[t]\n\\centerline{\\includegraphics[height=2.2in]{final_submission/Fig7}}\n\\caption{\\label{fig:oso}\nObserved (yellow line) and computed (blue) landslide at Oso, WA in\n2014 \\cite{IversonGeorgeEtAl2015}.}\n\\end{figure}\n", "meta": {"hexsha": "7234d1e40377b16876249201e2c98c28d874cd38", "size": 8532, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "papers/clawpack-5x/geoclaw.tex", "max_stars_repo_name": "kbarnhart/doc", "max_stars_repo_head_hexsha": "ede1e86c883ad9336f6334c967a89212d2b9cdc7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-01-08T12:17:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-15T21:17:44.000Z", "max_issues_repo_path": "papers/clawpack-5x/geoclaw.tex", "max_issues_repo_name": "kbarnhart/doc", "max_issues_repo_head_hexsha": "ede1e86c883ad9336f6334c967a89212d2b9cdc7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 76, "max_issues_repo_issues_event_min_datetime": "2015-01-31T20:22:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-05T16:55:53.000Z", "max_forks_repo_path": "papers/clawpack-5x/geoclaw.tex", "max_forks_repo_name": "kbarnhart/doc", "max_forks_repo_head_hexsha": "ede1e86c883ad9336f6334c967a89212d2b9cdc7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-03-01T08:26:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-06T02:59:13.000Z", "avg_line_length": 46.3695652174, "max_line_length": 87, "alphanum_fraction": 0.7827004219, "num_tokens": 2254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.31846323491861916}}
{"text": "\n\\chapter{Literature Review} \n\nIn induction machine, a power converter and a controller are the three major components of an induction motor drive system. Some of the disciplines related to these components are electric machine design, electric machine modeling, sensing and measurement techniques, signal processing, power electronic design and electric machine control. It is beyond the scope of this research to address all of these areas: it will primarily focus on the issue related to the induction machine control. A conventional low cost volts per hertz or a high performance field oriented controller can be used to control the machine. This chapter reviews the principles of the field orientation control of the induction machines and outline major problems in its design and implementation.\n\n\n\\section{Induction machine control}\n\nThe controllers required for induction motor drives can be divided into two major types: a conventional low cost volts per hertz v/f controller and torque controller \\cite{Vas}-\\cite{Lipo}. In v/f control, the magnitudes of the voltage and frequency are kept in proportion. The performance of the v/f control is not satisfactory, because the rate of change of voltage and frequency has to be low. A sudden acceleration or deceleration of the voltage and frequency can cause a transient change in the current, which can result in drastic problems. Some efforts were made to improve v/f control performance, but none of these improvements could yield a v/f torque controlled drive systems and this made DC motors a prominent choice for variable speed applications. This began to change when the theory of field orientation was introduced by Hasse and Blaschke. Field orientation control is considerably more complicated than DC motor control. The most popular class of the successful controllers uses the vector control technique because it controls both the amplitude and phase of AC excitation. This technique results in an orthogonal spatial orientation of the electromagnetic field and torque, commonly known as Field Oriented Control (FOC).\n\n\n\\section{Field orientation control (FOC) of induction machine}\n\n\nThe concept of field orientation control is used to accomplish a decoupled control of flux and torque. This concept is identical to a dc machine direct torque control that has following requirements \\cite{Lipo}:\n\\begin{itemize}\n\\item{An independent control of armature current to overcome the effects of armature winding resistance, leakage inductance and induced voltage}\n\\item{An independent control of constant value of flux}\n\\end{itemize}\n\nIf all of these requirements are met at every instant of time, the torque will follow the current, allowing an immediate torque control and decoupled flux and torque regulation.\\\\\n\nNext, a two phase d-q model of an induction machine rotating at the synchronous speed is introduced which will help to carry out this decoupled control concept to the induction machine. This model can be summarized by the following equations (see chapter 4 for detail):\n\n\\begin{align}\nV_{ds}^{\\omega}&=R_{s}i_{ds}^{\\omega}+\\frac{d}{dt}\\psi_{ds}^{\\omega}-\\omega_{e}\\psi_{qs}^{\\omega}\\\\\nV_{qs}^{\\omega}&=R_{s}i_{qs}^{\\omega}+\\frac{d}{dt}\\psi_{qs}^{\\omega}+\\omega_{e}\\psi_{qs}^{\\omega}\\\\\n0&=R_{r}i_{dr}^{\\omega}+\\frac{d}{dt}\\psi{dr}^{\\omega}-(\\omega_{e}-\\omega_{r})\\psi_{qr}^{\\omega}\\\\\n0&=R_{r}i_{qr}^{\\omega}+\\frac{d}{dt}\\psi{qr}^{\\omega}+(\\omega_{e}-\\omega_{r})\\psi_{dr}^{\\omega}\\\\\nT_{e}&=3p\\frac{L_{m}}{L_{r}}(\\psi_{dr}^{\\omega}i_{qs}^{\\omega}-\\psi_{qr}^{\\omega}i_{ds}^{\\omega})\n\\end{align}\n\n\\begin{figure}[h]\n\\centering\n\\includegraphics[scale=0.65]{chapter0/phasordig}\n\\caption{Phasor diagram of the field oriented drive system}\n\\label{phasor}\n\\end{figure}\n\nand it is quite significant to synthesize the concept of field-oriented control. In this model it can be seen from the torque expression (2.5) that, if the flux along the q-axis\ncan be made zero then all the flux is aligned along the d-axis and, therefore, the torque can be instantaneously controlled by controlling the current along q-axis. Then the question will be how it can be guaranteed that all the flux is aligned along the d-axis of the machine. When three-phase voltages are applied to the machine, they produce three-phase fluxes both in the stator and the rotor. The three phase fluxes can be represented in a two phase stationary ($\\alpha$-$\\beta$) frame. If these two phase fluxes along ($\\alpha$-$\\beta$) axes are represented by a single-vector then all the machine flux will be aligned along that vector. This vector is commonly specified as d-axis which makes an angle $\\theta_{e}$ with the stationary frame $\\alpha$-axis, as shown in \\autoref{phasor}. The q-axis is set perpendicular to the d-axis. The flux along the q-axis in this case will be obviously zero. The phasor diagram \\autoref{phasor} presents these axes. When the machine input currents change sinusoidally in time, the angle $\\theta_{e}$ keeps changing. Thus the problem is to know the angle $\\theta_{e}$ accurately, so that the d-axis of the d-q frame is locked with the flux vector.\\\\\n\n\nThe control inputs can be specified in two phase synchronously rotating d-q frame as $i_{ds}^{\\omega}$ and $i_{qs}^{\\omega}$ such that $i_{ds}^{\\omega}$ being aligned with the d-axis or the flux vector. These two phase synchronous control inputs are converted into two phase stationary quantities and then to three phase stationary control inputs. To accomplish this the flux angle $\\theta_{e}$ must be known precisely. The angle $\\theta_{e}$ can be found either by Direct Field Orientation control (DFO) or by Indirect Field Orientation control (IFO). The controller implemented in this fashion that can achieve a decoupled control of the flux and the torque is known as field oriented controller. The block diagram is shown in the \\autoref{foc} In the field-oriented controller the flux can be regulated in the stator, air-gap or rotor flux orientation \\cite{Vas}-\\cite{Lipo}.\n\n\n\\begin{figure}[h]\n\\centering\n\\includegraphics[scale=0.73]{chapter0/foc}\n\\caption{Field oriented induction motor drive system}\n\\label{foc}\n\\end{figure}\n\nThe control algorithm for calculation of the rotor flux angle $\\theta_{e}$ using IFO control is shown in the \\autoref{ifoc}. This algorithm is based on the assumption that, the flux along the q-axis is zero, which forces the command slip velocity to be $\\omega_{sl}=i_{qs}^{\\omega}/(\\tau_{r}i_{ds}^{\\omega})$ as a necessary and sufficient condition to guarantee that all the flux is aligned with d-axis and the flux along q-axis is zero. The angle $\\theta_{e}$ can then be determined as the sum of the slip and the rotor angles after integrating the respective velocities. This slip angle includes the necessary and sufficient condition for decoupled control of flux and torque. The rotor speed can be measured directly by using an encoder or can be estimated. In case the rotor speed is estimated, the control technique is known as sensorless control. This concept will be studied in detail in the following chapters. \\autoref{dfo} shows the control algorithm block diagram for DFO control. In this technique the flux angle $\\theta_{e}$ is classically calculated by sensing the air-gap flux through the use of flux sensing coils, or can be calculated by estimating the flux along the d-q axes using the voltage and current signals.\n\n\\begin{figure}[h]\n\\centering\n\\includegraphics[scale=0.85]{chapter0/ifoc}\n\\caption{Indirect field oriented drive system}\n\\label{ifoc}\n\\end{figure}\n\n\\begin{figure}[h]\n\\centering\n\\includegraphics[scale=0.8]{chapter0/dfo}\n\\caption{Direct field oriented drive system}\n\\label{dfo}\n\\end{figure}\n\n\\subsection{Direct field orientation (DFO)}\n\nThe DFO control and sensorless control rely heavily on accurate flux estimation. DFOC is most often used for sensorless control, because the flux observer used to estimate the synchronous speed or angle can also be used to estimate the machine speed. Investigation of ways to estimate the flux and speed of the induction machine has also been extensively studied in the past two decades. Classically, the rotor flux was measured by using a special sensing element, such as Hall effect sensors placed in the air-gap. An advantage of this method is that additional required parameters, $L_{lr}$, $L_{m}$, and $L_{r}$ are not significantly affected by changes in temperature and flux level. However, the disadvantage of this method is that a flux sensor is expensive and needs special installation and maintenance. Another flux and speed estimation technique is saliency based with fundamental or high frequency signal injection. One advantage of saliency technique is that the saliency is not sensitive to actual motor parameters, but this method fails at low and zero speed level. When applied with high frequency signal injection \\cite{jansen}, the method may cause torque ripples, and mechanical problems.\\\\\n\nGabriel \\cite{Gabrie} avoided the special flux sensors and coils by estimating the rotor flux from the terminal quantities (stator voltages and currents). This technique requires the knowledge of the stator resistance along with the stator, rotor leakage inductances and magnetizing inductance. This method is commonly known as the Voltage Model Flux Observer (VMFO). The stator flux in the stationary frame estimated by the equations:\n\n\n\\begin{align}\n\\psi_{ds}^s&=V_{ds}^s-R_{s}i_{ds}^s\\\\\n\\psi_{qs}^s&=V_{qs}^s-R_{s}i_{qs}^s\n\\end{align}\nThen the rotor flux can be expressed as:\n\\begin{align}\n\\psi_{dr}^s&=\\frac{L_{r}}{L_{m}}(\\psi_{ds}^s-\\sigma i_{ds}^s)\\\\\n\\psi_{qr}^s&=\\frac{L_{r}}{L_{m}}(\\psi_{qs}^s-\\sigma i_{qs}^s)\n\\end{align}\n\nIn this model, integration of the low frequency signals, dominance of stator resistance voltage drop at low speed and leakage inductance variation result in a less precise flux estimation. Integration at low frequency is studied by \\cite{jun} and three different alternatives are given. Estimation of rotor flux from the terminal quantities depends on parameters such as stator resistance and leakage inductance. The study of parameter sensitivity shows that the leakage inductance can significantly affect the system performance such as stability, dynamic response, and utilizations of the machine and the inverter.\\\\\n\n\nThe Current Model Flux Observer (CMFO) is an alternative approach to overcome the problems of leakage inductance and stator resistance at low speed. In this model flux can be estimated as:\n\\begin{align}\n\\psi_{dr}^s=-\\frac{1}{\\tau_{r}}\\psi_{dr}^s-\\omega_{r}\\psi_{qr}^s+\\frac{L_{m}}{\\tau_{r}}i_{ds}^s\\\\\n\\psi_{qr}^s=-\\frac{1}{\\tau_{r}}\\psi_{qr}^s-\\omega_{r}\\psi_{dr}^s+\\frac{L_{m}}{\\tau_{r}}i_{qs}^s\n\\end{align}\n\nHowever, it does not work well at high speed due to its sensitivity to the rotor resistance. Jansen \\cite{pl} did an extensive study on VMFO and CMFO based direct field orientation control, discussed the design and accuracy assessment of various flux observers, compared them, and analyzed the alternative flux observers. To further improve the observer performance, closed-loop rotor flux observers are proposed which use the estimated stator current error \\cite{pl,gc} or the estimated stator voltage error \\cite{gc} to estimate the rotor flux. Furthermore, Lennart \\cite{len} proposed reduced order observers for this task.\n\n\\subsection{Indirect field orientation control (IFOC)}\n\n\nIn indirect field orientation, the synchronous speed $\\omega_{e}$ is the same as the instantaneous speed of the rotor flux vector $\\psi_{dr}^{\\omega}$ and the d-axis of the d-q coordinate system is exactly locked on the rotor flux vector (rotor flux vector orientation). This facilities the flux control through the magnetizing current $i_{ds}^{\\omega}$ by aligning all the flux with the d-axis while aligning the torque producing component of the current with the q-axis. After decoupling the rotor flux and torque producing component of the current components, the torque can be instantaneously controlled by controlling the current $i_{qs}^{\\omega}$. The requirement to align the rotor flux with the d-axis of the d-q coordinate system means that the flux along the q-axis must be zero. This means that the current through the q-axis of the mutual inductance is zero.\\\\\n\nBased on this restriction $\\omega_{sl}$ is :\n\n\\begin{align}\n\\omega_{sl}=\\frac{i_{qs}^{\\omega}}{(\\tau_{r}i_{ds}^{\\omega})}\n\\end{align}\n\nThese relations suggest that flux and torque can be controlled independently by specifying d-q axis currents provided the slip frequency is satisfied (2.12) at all instants.\\\\\n\n\nThe concept of indirect field oriented control developed in the past has been widely studied by researchers during the last two decades. The rotor flux orientation is both the original and usual choice for the indirect orientation control. Also the IFO control can be implemented in the stator and air-gap flux orientation as well. De Doncker \\cite{doncker} introduced this concept in his universal field oriented controller. In the air-gap flux the slip and flux relations are coupled equations and the d-axis current does not independently control the flux as it does in the rotor flux orientation. For the constant air-gap flux orientation, the maximum of the produced torque is \\%20 less than that of the other two methods \\cite{sul}. In the stator flux orientation, the transient reactance is a coupling factor and it varies with the operating conditions of the machine. In addition, Mircea \\cite{mirc} shows that among these methods, rotor flux oriented control has linear torque curve. Therefore, the most commonly used choice for IFO is the rotor flux orientation.\\\\\n\nThe IFOC is an open loop, feed forward control in which the slip frequency is fed forward guaranteeing the field orientation. This feed forward control is very sensitive to the rotor open circuit time constant $\\tau_{r}$. Therefore, $\\tau_{r}$ must be known in order to achieve a decoupled control of torque and flux components by controlling $i_{ds}^{\\omega}$ and $i_{qs}^{\\omega}$ , respectively. When $\\tau_{r}$ is not set correctly, the machine is said to be detuned and the performance will become sluggish due to loss of decoupled control of torque and flux. The measurement of the rotor time constant, its effects on the system performance and its adaptive tuning to the variations resulting during the operation of the machine have been studied extensively in the literature \\cite{rl}-\\cite{krisn}. Lorenz, Krishnan and Novotny \\cite{rl}-\\cite{krisn} studied the effect of temperature and saturation level on the rotor time constant and concluded that it can reduce the torque capability of the machine and torque/amps of the machine. The detuning effect becomes more severe in the field-weakening region. Also, it results in a steady-state error and, transient oscillations in the rotor flux and torque. Some of the advanced control techniques such as estimation theory tools and adaptive control tools are also studied to estimate rotor time constant and other motor parameters \\cite{ca}-\\cite{jm}.\\\\\n\n\n\\section{Variable speed control using advance control algorithms}\n\nThere are two issues in motion control using field oriented controlled (FOC) induction machine drives. One is to make the resulting drive system and the controller robust against parameter deviations and disturbances. The other is to make the system intelligent to adjust the control system itself to environment changes and task requirements. If the speed regulation loop fails to produce the command current correctly, than the desired torque response will not be produced by the induction machine. In addition, such a failure may cause the degradation of slip command. As a result, a satisfactory speed regulation is extremely important not only to produce desired torque performance from the induction machine but also to guarantee the decoupling between control of torque and flux.\\\\\n\nConventionally, a PI controller has been used for the speed regulation to generate a command current for last two decades, and accepted by industry because of its simplicity. Even though, a well tuned PI controller performs satisfactorily for a field oriented induction machine during steady state. The speed response of the machine at transient, especially for the variable speed tracking, may sometimes be problematic. In last two decades, alternative control algorithms for the speed regulation were investigated. Among these, fuzzy logic, sliding mode, and adaptive nonlinear control algorithms gained much attention.\\\\\n\nA traditional rotor flux oriented induction machine drive offers a better control performance but it often requires additional sensors on the machine. This adds to the cost and complexity of the drive system. To avoid these sensors on the machine, many different algorithms are proposed for the last three decades to estimate the rotor flux vector and rotor shaft speed. The recent trend in field oriented control is to use such algorithms based on the terminal quantities of the machine for the estimation of the fluxes and speed. They can easily be applied to any induction machine. Therefore, our focus in this study is also on these algorithms.\\\\\n\n\nBefore looking into individual approaches, the common problems of the speed and flux estimation are discussed briefly for general field orientation and state estimation algorithms.\n \\begin{itemize}\n \\item{\\textbf{Parameter sensitivity:} One of the important problems of the sensorless control algorithms for the field oriented induction machine drives is the insufficient information about the machine parameters which yield the estimation of some machine parameters along with the sensorless structure. Among these parameters stator resistance, rotor resistance and rotor time constant play more important role than the other parameters since these values are more sensitive to temperature changes. The knowledge of the correct stator resistance $R_{s}$ is important to widen the\noperation region toward the lower speed range. Since at low speeds the induced voltage is low and stator resistance voltage drop becomes dominant, a mismatching stator resistance induces instability in the system. On the other hand, errors made in determining the actual value of the rotor resistance $R_{r}$, may cause both instability of the system and speed estimation error proportional to $R_{r}$ \\cite{gy}. Also, correct $\\tau_{r}$ value is vital decoupling factor in IFOC}\n \n\\item{\\textbf{Pure Integration:} The other important issue regarding many of the topologies is the integration process inherited from the induction machine dynamics where an integration process is needed to calculate the state variables of the system. However, it is difficult both to decide on the initial value, and prevent the drift of the output of a pure integrator. Usually, to overcome this problem a low-pass filter replaces the integrator.}\n\n\\item{\\textbf{Overlapping loop Problems:} In a sensorless control system, the control loop and the speed estimation loop may overlap and these loops influence each other. As a result, outputs of both of these loops may not be designed independently,  in some bad cases this dependency may influence the stability or performance of the overall system.}\n\\end{itemize}\n\\vspace{1cm}\nThe algorithms, where terminal quantities of the machine are used to estimate the fluxes and speed of the machine are categorized in two basic groups. First one is ``the open loop observers,\" in a sense that the on-line model of the machine does not use the feedback correction. Second one is ``the closed loop observers\" where the feedback correction is used along with the machine model itself to improve the estimation accuracy. These two basic groups can also be divided further into subgroups based on the control method used. These can be summarized as:\\\\\n\nOpen loop observers based on:\\\\\n- Current model\\\\\n- Voltage model\\\\\n- Full-order observer\\\\\n\n\nClosed loop observers based on:\\\\\n- Model Reference Adaptive Systems (MRAS)\\\\\n- Kalman filter techniques\\\\\n- Adaptive observers based on both voltage and current model\\\\\n- Neural network flux and speed estimators\\\\\n- Sliding mode flux and speed estimators\\\\\n\nCurrent model based open loop observers use the measured stator currents and rotor velocity. The velocity dependency of the current model is very important since this means that although using the estimated flux eliminates the flux sensor, the position sensor is still required. On the other hand, voltage model based open loop observers \\cite{M}-\\cite{gc} use the measured stator voltage and current as inputs. A full-order open loop observer can be formed using only the measured stator voltage and rotor velocity as inputs where the stator current appears as an estimated quantity. Because of its dependency on the stator current estimation, the full order observer will not exhibit better performance than the current model. Furthermore, parameter sensitivity and observer gain are the problems to be tuned in a full order observer design \\cite{br}. These open-loop observer structures are all based on the induction machine model, and they do not employ any feedback. Therefore, they are quite sensitive to parameter variations, which yield the estimation of some machine parameters along with the sensorless structure.\\\\\n\\vspace{1cm}\\\\\n\nTo produce more robust structures to parameter variations some kind of feedback may be helpful. For this purpose many closed loop topologies are proposed using different induction machine models and control methods. Among these MRAS attracts attention and several different algorithms are produced. In MRAS a comparison is made between the outputs of two estimators. The estimator which does not contain the quantity to be estimated can be considered as a reference model of the induction machine. The error between these two estimators is used as an input to an adaptation mechanism. The estimated rotor speed in the adjustable model is changed in such a way that the difference between two estimators converges to zero asymptotically, and the estimated rotor speed will be equal to actual rotor speed. The basics of the analysis and design of MRAS are discussed in \\cite{Vas, booksul}. In \\cite{gy, J}. In \\cite{cs} similar speed estimators are proposed based on the MRAS, and a secondary variable is introduced as the reference quantity by letting the rotor flux through a first-order delay instead of a pure integration to nullify the offset. However, their algorithms produce inaccurate estimated speed if the excitation frequency goes below certain level. In addition these algorithms suffer from the machine parameter uncertainties since the parameter variation in the reference model cannot be corrected. Zhen \\cite{lz} proposed an interesting MRAS structure that is built with two mutual MRAS schemes. In this structure, the reference model and the adjustable models are interchangeable. For rotor speed estimation, one model is used as reference model and other model is used as adjustable model. The pure integration is removed from reference model. \\cite{me} supported the MRAS scheme with ANN using its training and modeling of non-linear systems. MRAS scheme is also used for the on-line adaptation of the motor parameters in field oriented control techniques \\cite{ca, kubota}.\\\\\n\nKalman filter (KF) is another method employed to identify the speed and rotor flux of an induction machine based on the measured quantities such as stator current and voltage \\cite{kim}. Kalman filter approach is based on the system model and a mathematical model describing the induction motor dynamics for the use of Kalman filter application. Parameter deviations and measurement disturbance are taken into consideration in KF covariance matrices of the KF must be properly initialized. KF works for linear systems and for non linear induction motor model extended Kalman filter (EKF) is used. However, KF approach is computationally intensive and depends on the accuracy of the model of the motor. In the EKF model proposed by  one can estimate rotor fluxes and rotor speed which makes the field orientation. EKF is also used for online parameter estimation of induction motor \\cite{Vas, lcz}. Reduced order models are also proposed to shorten and speed up the complex EKF algorithm \\cite{ekf}. A new KF technique for non-linear systems, Unscented Kalman Filter (UKF), is applied to induction machine state estimatio, which is a derivative free KF technique which avoids costly calculation of Jacobian matrix, linearization of the estimates \\cite{ukf}.\\\\\n\n\nAnother method used for the sensorless control of induction motor is the neural network technique, which is based on a learning process. It has the advantage of tolerating machine parameter uncertainties. For speed estimation, a two-layered neural network, based on back propagation technique, is used and the neural network outputs are compared with the actual measurement values and error then back- propagated to adjust the weights such that the estimated speed converges to actual one. The neural network based sensorless control algorithms have the advantages of fault-tolerant characteristics. However, because of the neural network learning process these algorithms may suffer from the computational intensity.\\\\\n\nAnother approach is sliding mode control for FOC of induction machine. In the sliding mode technique, the control action is very strong and being switched into either ``on\" or ``off\" at high frequency. The command signals control directly the power devices. This type of control is also favorable because ``on-off\" is the only admissible mode of operation for the power converters. Therefore, it seems more natural to employ the algorithm towards discontinuous control.\\\\\n\nIn addition to the algorithms mentioned above, some of the proposed work is hard to classify because of their combined structure. In \\cite{J}, a nonlinear high- gain observer structure is proposed, and it is claimed that with the exact knowledge of stator resistance, flux and speed estimation convergence is guaranteed.\n\n\\section{Conclusion}\n\nThe literature review of DFOC, IFOC, flux, position and speed estimation and speed control can be summarized as:\n\\begin{itemize}\n\n\\item{The DFOC and IFOC are the methods for instantaneous torque and speed control of an induction motor drive system. These methods can be implemented with or without a speed sensor. An IFOC is synthesized by properly controlled slip frequency which is necessary for the field-orientation}\\\\\n\\item{The main problem of an IFO drive system is the rotor time constant deviation. The drive system torque control performance decreases if the rotor time constant is not set precisely. Therefore, on-line estimation is necessary and is one of the main challenges for better performance of an IFOC. Most of the techniques proposed so far either need some special hardware or are very complex with respect to the software and require intensive calculations which put extra burden on the processor.}\\\\\n%\\item{The main problem in DFO control is precise rotor flux or position observation. This observation from terminal quantities is more desirable than the one including additional hardware.}\\\\\n\\item{Voltage model and current model flux observers are the two most common ways to estimate the flux using the terminal quantities. The voltage model flux observer is dominated by stator IR drop at low speed, whereas the current model flux observer has problems of rotor time constant variations. Also the current model flux observer requires the rotor speed. Therefore, if the flux observer is being used for the sensorless control, an error in the estimated speed will be fed back in to the system. Thus will affect the observer accuracy.}\\\\\n\\item{The proposed open-loop observers can be simple in the structure but they are susceptible to variety of errors that become specially detrimental at low stator frequencies, including measurement, noise digital approximation errors, parameter detuning and DC offset in measurements, which ultimately may drive the observer instability.}\\\\\n\\item{For the time varying system model problems, closed-loop observers are proposed here feedback correction is used along with the machine model itself to improve the estimation accuracy. The algorithmic complexity and calculation intensity looks higher when compared with former solutions but the recent processors are fast enough to solve these algorithms in real-time applications. They also require a strong mathematical background to deal with.}\n\\end{itemize}\n", "meta": {"hexsha": "ab63d3299ba6e8725fd027227f5c8b82a1949bd5", "size": 28597, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "APS/APS2_4Sep/Chapter0/chapter0.tex", "max_stars_repo_name": "pranavn91/PhD", "max_stars_repo_head_hexsha": "ac44783a1c7c418cafcfc7eb35ef2fc9641688bc", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "APS/APS2_4Sep/Chapter0/chapter0.tex", "max_issues_repo_name": "pranavn91/PhD", "max_issues_repo_head_hexsha": "ac44783a1c7c418cafcfc7eb35ef2fc9641688bc", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "APS/APS2_4Sep/Chapter0/chapter0.tex", "max_forks_repo_name": "pranavn91/PhD", "max_forks_repo_head_hexsha": "ac44783a1c7c418cafcfc7eb35ef2fc9641688bc", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 161.5649717514, "max_line_length": 1994, "alphanum_fraction": 0.8002937371, "num_tokens": 6105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3184632349186191}}
{"text": "\n%% !TEX root = manual.tex\n\n\\section{Spyplot Diagrams}\n\\label{sec:tutorials:spyplot}\n\nSpyplots visualize communication matrices, showing either the number of messages or number of bytes sent between two network endpoints.\nThey are essentially contour diagrams, where instead of a continuous function $F(x,y)$ we are plotting the communication matrix $M(i,j)$.\nAn example spyplot is shown for a simple application that only executes an MPI\\_Allreduce (Figure \\ref{fig:spyplot}).\nLarger amounts of data (red) are sent to nearest neighbors while decreasing amounts (blue) are sent to MPI ranks further away.\n\n\\begin{figure}[h]\n\\centering\n\\includegraphics[width=0.4\\textwidth]{figures/spyplot/mpi_spyplot.png}\n\\caption{Spyplot of Bytes Transferred Between MPI Ranks for MPI\\_Allreduce}\n\\label{fig:spyplot}\n\\end{figure}\n\nVarious spyplots can be activated by boolean parameters in the input file.\nThe most commonly used are the MPI spyplots, for which you must add\n\n\\begin{ViFile}\nmpi_spyplot = <fileroot>\n\\end{ViFile}\n\nAfter running there will be a .csv and .png file in the folder, with e.g. \\inlineshell{fileroot = test}\n\n\\begin{ShellCmd}\nexample> ls \ntest.png\ntest.csv\n\\end{ShellCmd}\n\\inlineshell{test.png} shows the number of bytes exchanged between MPI ranks.\nTo extend the analysis you can specify\n\n\\begin{ViFile}\nnetwork_spyplot = <fileroot>\n\\end{ViFile}\nA new csv/png will appear showing the number of bytes exchanged between physical nodes, \naccumulating together all MPI ranks sharing the same node.\nThis gives a better sense of spatial locality when many MPI ranks are on the same node.\n\n\n", "meta": {"hexsha": "7919034a46232c30d2acd4da9dd1a927e2ec7c7f", "size": 1595, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/manual/SpyplotTutorial.tex", "max_stars_repo_name": "minyee/sst-macro", "max_stars_repo_head_hexsha": "fd2c52b3872b9c49af77f5f82b3177cc7bbe403c", "max_stars_repo_licenses": ["BSD-Source-Code"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-11-18T22:49:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-22T18:33:50.000Z", "max_issues_repo_path": "docs/manual/SpyplotTutorial.tex", "max_issues_repo_name": "minyee/sst-macro", "max_issues_repo_head_hexsha": "fd2c52b3872b9c49af77f5f82b3177cc7bbe403c", "max_issues_repo_licenses": ["BSD-Source-Code"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/manual/SpyplotTutorial.tex", "max_forks_repo_name": "minyee/sst-macro", "max_forks_repo_head_hexsha": "fd2c52b3872b9c49af77f5f82b3177cc7bbe403c", "max_forks_repo_licenses": ["BSD-Source-Code"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-02-21T11:39:08.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-21T11:39:08.000Z", "avg_line_length": 36.25, "max_line_length": 137, "alphanum_fraction": 0.7862068966, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3182023278569569}}
{"text": "\\documentclass[a4paper]{article}\n\n\\usepackage[english]{babel}\n\\usepackage[utf8]{inputenc}\n\\usepackage{amsmath}\n\\usepackage{graphicx}\n\\usepackage[colorinlistoftodos]{todonotes}\n\\usepackage{hyperref}\n\\usepackage{listings}\n\\usepackage[numbers]{natbib}\n\n\\usepackage{graphicx}\n\\usepackage{babel,blindtext}\n\n\\usepackage{algorithm}\n\\usepackage[noend]{algpseudocode}\n\n\\usepackage{booktabs} % To thicken table lines\n\n\\title{Train a Smartcab How to Drive}\n\n\\author{Uirá Caiado}\n\n\\date{\\today}\n\n\\begin{document}\n\n\\maketitle\n\n\\begin{abstract}\nA smartcab is a self-driving car from the not-so-distant future that ferries people from one arbitrary location to another. In this project, I will design the AI driving agent for the smartcab using reinforcement learning. This area of machine learning\\footnote{Source: \\url{https://en.wikipedia.org/wiki/Reinforcement_learning}} is inspired by behaviorist psychology and consists in training the agent by reward and punishment without needing to specify how the task is to be achieved. The agent should learn an optimal policy for driving on city roads, obeying traffic rules correctly, and trying to reach the destination within a goal time.\n\\end{abstract}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% INTRODUCTION\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Introduction}\n\\label{sec:introduction}\nIn this section, I will present a brief introduction to reinforcement learning and to the problem addressed by this project.\n\n\\subsection{Reinforcement Learning}\nAs explained by \\cite{Mohri_2012}, reinforcement learning is the study of planning and learning in a scenario where a learner (or agent) actively interacts with the environment to achieve a particular goal. The achievement of the agent's goal is typically measured by the reward he receives from the environment and which he seeks to maximize.\n\n\\cite{Kaelbling_1996} state that the most significant difference between reinforcement learning and supervised learning is that there is no presentation of input/output pairs. Instead, they explained that after choosing an action, the agent is told the immediate reward and the following state, but is not told which action would have been in its best long-term interests. It is necessary for the agent to gather useful experience about the possible system states, actions, transitions and rewards actively to act optimally.\n\nDefining a general formulation of the problem based on a Markov Decision Process (MDP), as proposed by \\cite{Mitchell}, the agent can perceive a set $S$ os distinct states of its environment and has a set $A$ of actions that it can perform. So, at each discrete time step $t$, the agent senses the current state $s_t$ and choose to take an action $a_t$. The environment responds by giving the agent a reward $r_t=r(s_t, a_t)$ and by producing the succeeding state $s_{t+1}=\\delta(s_t, a_t)$. The functions $r$ and $\\delta$ only depend on the current state and action (it is memoryless\\footnote{Source: \\url{https://en.wikipedia.org/wiki/Markov_process}}), are part of the environment and are not necessarily known to the agent.\n\nThe task of the agent is to learn a policy $\\pi$ that maps each state to an action ($\\pi: S \\rightarrow A$), selecting its next action $a_t$ based solely on the current observed state $s_t$, that is $\\pi(s_t)=a_t$. The optimal policy, or control strategy, is the one that produces the greatest possible cumulative reward over time. So, stating that:\n\n$$V^{\\pi}(s_t)= r_t + \\gamma r_{t+1} + \\gamma^2 r_{t+1} + ... = \\sum_{i=0}^{\\infty} \\gamma^{i} r_{t+i}$$\n\nWhere $V^{\\pi}(s_t)$ is also called the discounted cumulative reward and it represents the cumulative value achieved by following an policy $\\pi$ from an initial state $s_t$ and $\\gamma \\in [0, 1]$ is a constant that determines the relative value of delayed versus immediate rewards. If we set $\\gamma=0$, only immediate rewards is considered. As $\\gamma \\rightarrow 1$, future rewards are given greater emphasis relative to immediate reward. The optimal policy $\\pi^{*}$ that will maximizes $V^{\\pi}(s_t)$ for all states $s$ can be written as:\n\n$$\\pi^{*} = \\underset{\\pi}{\\arg \\max} \\, V^{\\pi} (s)\\,\\,\\,\\,\\,, \\,\\, \\forall s$$\n\nAs learning $\\pi^{*}: S \\rightarrow A$ directly is difficult because the available training data does not provide training examples of the form $(s, a)$, in the section \\ref{sec:implement_q_learning} I will implement the Q-learning algorithm for estimating the optimal policy.\n\n\\subsection{What Will Be Done}\n\nThe goal of this project\\footnote{Source: \\url{https://goo.gl/BZdyLo}} is to design the AI driving agent for the smartcab, that operates in an idealized grid-like city.\n\nThe smartcab is able to sense whether the traffic light is green for its direction of movement and whether there is a car at the intersection on each of the incoming roadways (and which direction they are trying to go). In addition to this, each trip has an associated timer that counts down every time step. If the timer is at 0 and the destination has not been reached, the trip is over, and a new one may start.\n\nIt should receive the inputs mentioned above at each time step t, and generate an output move, that consists on to stay put at the current intersection, move one block forward, one block left, or one block right (no backward movement).\n\nThe smartcab also should receive a reward for each successfully completed trip. A trip is considered “successfully completed” if the passenger is dropped off at the desired destination within a pre-specified time bound. It also gets a smaller reward for each correct move executed at an intersection. It gets a minor penalty for a wrong move and a larger penalty for violating traffic rules and/or causing an accident.\n\nBased on the rewards and penalties it gets, the agent should learn an optimal policy for driving on city roads, obeying traffic rules correctly, and trying to reach the destination within a goal time.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% IMPLEMENT A BASIC DRIVING AGENT\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Implement a Basic Driving Agent}\n\\label{sec:implement_driving_agent}\nIn this section, I will implement a basic driving agent that accepts specified inputs ans produces a valid output.\n\n\\subsection{My Grid-Like World}\nLet's start by testing the output produced by my current \\textit{'world'} that will be used to analyze the results of this project. This \\textit{'world'} is a grid-like city, with roads going North-South and East-West. Other vehicles may be present on the streets, but no pedestrians. There is a traffic light at each intersection that can be in one of two states: North-South open or East-West open. US right-of-way rules apply: On a green light, you can turn left only if there is no oncoming traffic at the intersection coming straight. On a red light, you can turn right if there is no oncoming traffic turning left or traffic from the left going straight.\n\nWe are told to assume that a higher-level planner assigns a route to the smartcab, splitting it into waypoints at each intersection. The time in this world is quantized and at any instant, the smartcab is at some intersection. Therefore, the next waypoint is always either one block straight ahead, one block left, one block right, one block back or exactly there (reached the destination).Below is a sample of the log file generated by the simulator.\n\n% code snipet\n\\begin{lstlisting}\n<Time>;Environment.reset():Trial set up with start=(4, 3)\n                      ,destination=(8, 4), deadline = 25\n<Time>;RoutePlanner.route_to(): destination = (8, 4)\n<Time>;LearningAgent.update(): deadline = 25,\n    inputs = {'light': 'green', 'oncoming': None,\n              'right': 'forward', 'left': None},\n    action = None, reward = 0.0\n...\n<Time>;Environment.step(): Primary agent ran out of time!\nTrial aborted.\n\\end{lstlisting}\n\n\\subsection{The Basic Agent}\nAs mentioned before, I am going to implement a Smartcab that processes the following inputs at each time step:\n\n\\begin{itemize}\n\\item \\textit{Next waypoint location}: about its current position and heading\n\\item \\textit{Intersection state}: traffic light and presence of cars\n\\item \\textit{Current deadline value}: time steps remaining\n\\end{itemize}\n\nFor the purposes of this project, the agent should produce just some random move, like \\textit{'None'}, \\textit{'forward'}, \\textit{'left'} and \\textit{'right'}. I will not implement the correct strategy because it is precisely what my agent is supposed to learn.\n\nFor the purposes of this project, the first implementation of the agent should produce just some random move at each time $t$, such that $a_t \\in (None,\\, forward,\\,$\n$ left,\\, right)$. I will not implement the correct strategy because it is precisely what my agent is supposed to learn. Below I am going to simulate $100$ different trials with the \\textit{'enforce\\_deadline'} set to False and will save the logs produced by the agent to observe how it performs. In this mode, the agent is given unlimited time to reach the destination.\n\n% code snipet\n\\begin{lstlisting}\nNumber of Trials: 100\nTimes that the agent reached the target location: 69\nTimes the agent reached the hard deadline: 31\nTimes the agent successfully reached the target: 21\n\\end{lstlisting}\n\nAs can be seen above, even using just random moves, the agent still was able to reach the target destination roughly $20\\%$ of the trials at the deadline stipulated by the Planner. If we considering all the times it reached the location, it was able to complete the route almost $70\\%$ of the trials. Now, I am going to produce same basic statistics about the times that it reached the target location.\n\n% \\begin{figure}[ht!]\n% \\centering\n% \\includegraphics[width=0.75\\textwidth]{images/steps_takes.png}\n% \\caption{\\label{fig:boxplot}Number of Steps Used to Reached The Destination}\n% \\end{figure}\n\n\\begin{table}[ht!]\n\\centering\n\\begin{tabular}{l|r}\n\\multicolumn{2}{ c }{Number Of Steps} \\\\\n\\midrule\nmean  &         59.00 \\\\\nstd   &         36.06 \\\\\nmin   &          2.00 \\\\\n25\\%   &         23.75 \\\\\n50\\%   &         60.00 \\\\\n75\\%   &         91.00 \\\\\nmax   &        130.00 \\\\\n\\end{tabular}\n\\caption{\\label{tab:basic_stats}Basic Agent Simulation Statistics}\n\\end{table}\n\nAccording to the table \\ref{tab:basic_stats}, It took 59 steps on average, and the variation was huge. The agent has taken from 2 steps to 130 to finish the route. In the section \\ref{sec:enhance_driving_agent}, I will try to improve that.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% IDENTIFY AND UPDATE STATE\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\subsection{Identify and Update State}\nTo complete the implementation of my Basic Agent, I still need to decide how it will represent its state internally. Considering the inputs that it receives before performs any action and, consequently, receives a reward, I initially will use a tuple using all of them to represent the current state of my agent, in the form $(inputs,\\, next\\_waypoint,\\, deadline)$. I believe that it will represent a reasonable set of states that my agent could use to gather more information from the environment.\n\n$Inputs$ is a dictionary with the state of the traffic light for the agents' direction of movement and the direction of the random agents on each of the incoming roadways (if any). $next\\_waypoint$ is the direction of the target location and $deadline$, a timer.\n\nI believe that $next\\_waypoint$ and $inputs$ are natural choices, given that the first gives the direction of the target and the second provides information about the environment state. The inclusion of $deadline$ might help the agent choose to explore the environment when it has more time available, for example. Later on, we will see how significant this single decision is when dealing with Reinforcement Learning problems.\n\nSo, let's count the number of stated that I get when I enforce deadline in my simulation on $100$ trials.\n\n\\begin{lstlisting}\nnumber of states in the state space: 891\n\\end{lstlisting}\n\n\\begin{figure}[ht!]\n\\centering\n\\includegraphics[width=0.75\\textwidth]{images/basic_agent_behaviour.png}\n\\caption{\\label{fig:hist_basic_agent}Count Of Times That Each State Appeared}\n\\end{figure}\n\nThe figure \\ref{fig:hist_basic_agent} presents the frequency of the counting of each state. For instance, around $600$ states appeared just two times, more than $100$ appeared four times and so on. Curiously the agent's behavior distribution looks like a log-normal distribution.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% IMPLEMENT Q-LEARNING\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Implement Q-Learning}\n\\label{sec:implement_q_learning}\nIn this section, I will briefly explained the concept of Q-learning and implement an algorithm to learn the Q function.\n\n\\subsection{The Q-Function}\nAs mention before, to learn an optimal policy $\\pi^{*}$, I can't learn a function $\\pi^{*}: S \\rightarrow A$ that maps a state to the optimal action directly. There is no such information upfront to be used as training data. Instead, as \\cite{Mitchell} explained, the only available information is the sequence of immediate rewards $r(s_i, a_i)$ for $i=1,\\, 2,\\, 3,\\,...$\n\nSo, as we are trying to maximize the cumulative rewards $V^{*}(s_t)$ for all states $s$, the agent should prefer $s_1$ over $s_2$ wherever $V^{*}(s_1) > V^{*}(s_2)$. Given that the agent must choose among actions and not states, and it isn't able to perfectly predict the immediate reward and immediate successor for every possible state-action transition, we also must learn $V^{*}$ indirectly.\n\nTo solve that, we define a function $Q(s, \\, a)$ such that its value is the maximum discounted cumulative reward that can be achieved starting from state $s$ and applying action $a$ as the first action. So, we can write:\n\n$$Q(s, \\, a) = r(s, a) + \\gamma V^{*}(\\delta(s, a))$$\n\nAs $\\delta(s, a)$ is the state resulting from applying action $a$ to state $s$ (the successor) chosen by following the optimal policy, $V^{*}$ is the cumulative value of the immediate successor state discounted by a factor $\\gamma$. Thus,  what we are trying to achieve is\n\n$$\\pi^{*}(s) = \\underset{a}{\\arg \\max} Q(s, \\, a)$$\n\nThus, the optimal policy can be obtained even if the agent just uses the current action $a$ and state $s$ and chooses the action that maximizes $Q(s,\\, a)$. Also, it is important to notice that the function above implies that the agent can select optimal actions even when it has no knowledge of the functions $r$ and $\\delta$. In the next subsection, we will see how \\cite{Mitchell} defined a reliable way to estimate training values for $Q$, given only a sequence of immediate rewards $r$.\n\n\n\\subsection{Learning Q}\nAs we have seen, learning the Q function corresponds to learning the optimal policy. According to \\cite{Mohri_2012}, the optimal state-action value function $Q^{*}$ is defined for all $(s, \\, a) \\in S \\times A$ as the expected return for taking the action $a \\in A$ at the state $s \\in S$, following the optimal policy. So, it can be written as \\cite{Mitchell} suggested:\n\n$$V^{*}(s) = \\underset{a'}{\\arg \\max} Q(s, \\, a')$$\n\nUsing this relationship, we can write a recursive definition of Q function, such that:\n\n$$Q(s, \\, a) = r(s, a) + \\gamma \\, \\underset{a'}{\\max} \\, Q(\\delta(s,\\, a), \\, a')$$\n\nThe recursive nature of the function above implies that our agent doesn't know the actual $Q$ function. It just can estimate $Q$, that we will refer as $\\hat{Q}$. It will represents is hypothesis $\\hat{Q}$ as a large table that attributes each pair $(s\\, , \\, a)$ to a value for $\\hat{Q}(s,\\, a)$ - the current hypothesis about the actual but unknown value $Q(s, \\, a)$. I will initialize this table with zeros, but it could be filled with random numbers, according to \\cite{Mitchell}. Still according to him, the agent repeatedly should do the following:\n\n\\begin{algorithm}\n\\caption{Update Q-table}\\label{alg:qtable}\n\\begin{algorithmic}[1]\n\\Loop{ Observe the current state $s$ and:}\n  \\State Choose some action $a$ and execute it\n  \\State Receive the immediate reward $r = r(s, a)$\n  \\State initialize the table entry $\\hat{Q}(s, \\, a)$ to zero if there is no entry $(s, \\, a)$\n  \\State Observe the new state $s' = \\delta(s, \\,a)$\n  \\State Updates the table entry for $\\hat{Q}(s, \\, a)$ following:\n\n    \\do $\\hat{Q}(s, \\, a) \\leftarrow r + \\gamma \\, \\underset{a'}{\\max}\\, \\hat{Q}(s', \\, a')$\n  \\State $s \\leftarrow s'$\n\\EndLoop\n\\end{algorithmic}\n\\end{algorithm}\n\nNote this training rule is suited to a deterministic Markov decision process (where $r(s,\\, a)$ and $\\delta(s,\\, a)$ are deterministic) and uses the agent's current $\\hat{Q}$ values for the new state $s'$ to refine its estimate of $\\hat{Q}(s, \\,a)$ for the previous state $s$. It is tricky. Let's take a look at its performance.\n\n\\begin{lstlisting}\nNumber of Trials: 100\nTimes that the agent reached the target location: 55\nTimes the agent reached the hard deadline: 45\nTimes the agent successfully reached the target: 55\n\\end{lstlisting}\n\nThe agent is reaching its destination much more frequently than before. When the agent selected its action randomly, it reached its destination just 21\\% of the times. Now, it is reaching 55\\%. Now the agent is always taking the \"safest action\":  takes the action with the biggest reward. It is not bad, but looking at the number of explored actions by state in the Q-table produced by this simulation, we can notice something curious\n\n\\begin{table}[ht!]\n\\centering\n\\begin{tabular}{l|r}\n\\multicolumn{2}{ c }{Number of Explored Actions} \\\\\n\\midrule\n1                          &  56.28\\% \\\\\n2                          &  21.10\\% \\\\\n3                          &  15.83\\% \\\\\n4                          &  6.78\\% \\\\\n\\end{tabular}\n\\caption{\\label{tab:explored_actions}Explored Actions in The Q-Table}\n\\end{table}\n\nThe agent explored just one possible action in $56\\%$ of the states in the Q-Table. According to \\cite{Mitchell}, there are some conditions to ensure that the algorithm converges toward a $\\hat{Q}$ equal to the true $Q$ function. One of them is that the system should be a deterministic MDP. Another is that the agent must select actions in a way that it visits every possible state-action pair infinitely often. Looking at the number of times this implementation of the agent explored all $4$ possibles actions (less than $7\\%$ of the states), I would say that it isn't true. In the next section, I will try to improve te agent's performance.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% ENHANCE DRIVING AGENT\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Enhance the Driving Agent}\n\\label{sec:enhance_driving_agent}\nIn this section, I will try to improve the driving agent to make it consistently reaches the destination within allotted time and the net reward positive.\n\n\\subsection{Experimentation Strategies}\nOne of the issues of the current strategy is that the agent could over-commit to actions that presented positive $\\hat{Q}$ values early in the simulation, failing to explore other actions that could present even higher values. \\cite{Mitchell} proposed to use a probabilistic approach to select actions, assigning higher probabilities to action with high $\\hat{Q}$ values, but given to every action at least a nonzero probability. So, I will implement the following relation:\n\n$$P(a_i\\, | \\,s ) = \\frac{k ^{\\hat{Q}(s, a_i)}}{\\sum_j k^{\\hat{Q}(s, a_j)}}$$\n\nWhere $P(a_i\\, | \\,s )$ is the probability of selecting the action $a_i$ given the state $s$. The constant $k$ is positive and determines how strongly the selection favors action with high $\\hat{Q}$ values. In the figure \\ref{fig:exploint_explore} we can see the number of times the algorithm choose to explore when we vary the value of the $k$.\n\nLarge values of $k$ assigned a higher probability of the agent exploits what it already has learned. Small values have made the agent favor the exploration of new actions. In the figure \\ref{fig:success_runs} we can check how the different values of $k$ impacted on the times the agent completed the routes.\n\n\\begin{figure}[ht!]\n\\minipage{0.49\\textwidth}\n  \\includegraphics[width=\\linewidth]{images/exploint_explore.png}\n  \\caption{\\label{fig:exploint_explore}Exploration vs Exploitation}\n\\endminipage\n\\minipage{0.49\\textwidth}\n  \\includegraphics[width=\\linewidth]{images/success_runs.png}\n  \\caption{\\label{fig:success_runs}On Time Ratio}\n\\endminipage\n\\end{figure}\n\nThe agent presented a very steep improvement as $k$ was approaching $3$. Above this value, the completed trips ratio just showed a slight growth. Now, let's check how the number of trials changed the average reward received by the agent.\n\n\\begin{figure}[ht!]\n\\centering\n\\includegraphics[width=0.75\\textwidth]{images/cum_reward_by_k.png}\n\\caption{\\label{fig:cum_reward_by_k}Average Cumulative Reward By Value of $k$}\n\\end{figure}\n\nClearly, small values of $k$ are worst than large values, as can be seen at the figure \\ref{fig:cum_reward_by_k}. As I want that my agent has some probability of exploring new actions, and it seems that $k=3$ is the best choice (the \"slope\" is not so steep, and the start value is pretty high), I will use this parameter to perform the next simulations.\n\n\\subsection{Non-deterministic Rewards and Actions}\nThe last modification that I want to introduce is when the environment is non-deterministic. As I said before, the algorithm used is appropriate to the deterministic case. On a nondeterministic environment, the reward function $r(s,\\,a)$ and action transition function $\\delta(s,\\,a)$ may have probabilistic outcomes. As there are other agents in the Smartcab world, I believe that it is a proper assumption.\n\nAs explained by \\cite{Mitchell}, to handle nondeterministic MDPs, it is needed to redefine the value $V^{*}$ to be expressed as a expected value. So, jumping to the $Q$ function, we can re-express $Q$ recursively as:\n\n\\begin{equation}\n\\begin{aligned}\nQ(s, \\, a) &= E \\left [r(s, a) \\right ] + E \\left [\\gamma \\, \\underset{a'}{\\max} \\, Q(\\delta(s,\\, a), \\, a')\\right ]\\\\\n&= E \\left [r(s, a) \\right ] + \\gamma \\,  E \\left [\\underset{a'}{\\max} \\, Q(\\delta(s,\\, a), \\, a')\\right ]\\\\\n&= E \\left [r(s, a) \\right ] + \\gamma \\,  \\sum_{s'} P\\left(s' \\,| \\,s, a   \\right) \\underset{a'}{\\max} \\, Q(\\delta(s,\\, a), \\, a')\n\\end{aligned}\n\\end{equation}\n\nWhere $P\\left(s' \\,| \\,s, a   \\right)$ is the probability that taking action $a$ in state $s$ will produce the next state $s'$. To implement that, we need to assume that the $\\hat{Q}$ values in our table may be wrong, due to the non-deterministic behavior of our environment. So, \\cite{Mitchell} suggested to modifying the training rule by introducing a decaying weighted average factor to the current $\\hat{Q}$ value and to the revised estimate, such that:\n\n$$\\hat{Q}(s, \\, a) \\leftarrow  (1 - \\alpha_{n})\\, \\hat{Q}_{n-1}(s, \\, a) +  \\alpha_{n}\\left[ r + \\gamma \\underset{a'}{\\max} \\hat{Q}_{n-1}(s', \\, a') \\right ]$$\n\nWhere $\\alpha_{n} = \\frac{1}{1 + visits_{n}(s, \\,a)}$ is the decaying factor and $visits_{n}$ is the total number of times this state-action $(s, \\, a)$ pair has been visited. So, let's put it in practice.\n\n\\begin{lstlisting}\nNumber of Trials: 100\nTimes that the agent reached the target location: 58\nTimes the agent reached the hard deadline: 42\nTimes the agent successfully reached the target: 58\n\\end{lstlisting}\n\nLooking just at the times the agent has completed the route, it doesn't look like we made much progress. I will compare the performance of all the agents created so far in the last section.\n\n\\newpage\n\\subsection{The last parameter to Tune: Gamma}\nThere is just one remain parameter of the model that was not explored yet:  the $\\gamma$. As already explained, the $\\gamma$ in the $\\hat{Q}$ function is a factor used to discount the immediate successor state to be used to update $\\hat{Q}$ table. As $\\gamma$ approaches $0$, less \"memory\" the agent has. So, let's check what happens when we vary this parameter about the average cumulative reward of the learning agent:\n\n\\begin{figure}[ht!]\n\\centering\n\\includegraphics[width=0.75\\textwidth]{images/cum_reward_by_gamma.png}\n\\caption{\\label{fig:avg_cum_rwd}Average Cumulative Reward By Value of $\\gamma$}\n\\end{figure}\n\nIn the last section, I will use $\\gamma = 0.5$ to perform the final tests.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% CONCLUSION\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Conclusion}\n\\label{sec:conclusion}\nIn this section, I will compare the performance of the algorithms implemented so far and then I will show how a little change can make a huge difference in a reinforcement learning problem.\n\n\\subsection{Final Remarks}\nThe goal of the whole project was to build an agent that obeys traffic rules correctly and reachs the destination within an allotted time. So, the \"perfect\" agent would be the one that always come to the destination in the goal time without any penalty.\n\nHowever, as our environment is non-deterministic, to always reach the destination on time is not reasonable. Also, as the environment penalizes the agent even when it makes a correct move, but in a distinct direction from the target location, it isn't fair to expect that the perfect agent never incurs any penalty.\n\nSo, the best one would be the one that learns a reasonable policy fast and receives the maximum average cumulative reward possible. Average because we should weight the rewards received by the number of steps used to avoid discrepancies. In this sense, let's first compare how the modifications made on this project reflected on our agent when we ensure deadline. The improved agent will be set with $\\gamma=0.5$ and $k=3$.\n\n\n\\begin{figure}[ht!]\n\\centering\n\\includegraphics[width=0.75\\textwidth]{images/performance_comparition.png}\n\\caption{\\label{fig:perf_compr}Cumulative Reward By Agent}\n\\end{figure}\n\nAs can be seen above, the improved agent did better than the other implementations. It reached the destination $64\\%$ of the trials on time and the final average reward by action was greater than the others. It was achieved by tuning the parameters, including an experimentation strategy and changing the $\\hat{Q}$ function to deal with the non-deterministic environment, as explained before. The random agent reached the destination on time just $42\\%$ of the trials and the agent that used the deterministic version of $\\hat{Q}$ function, $55\\%$. Although the final agent is still incurring penalties, it is closer to a perfect agent than it was when using just random moves. In the next subsection, I will show how to change the behavior of the agent radically.\n\n\\subsection{Blowing Up Everything: Changing The Intern State}\nAs pointed out by the Udacity Reviewer, something that I should have taken into account was the size of state space resulted by my choice of agents' intern state representation. I included an Experimentation Strategy and addressed a non-deterministic MDP environment exactly due to the number of states that the agent would need to learn. It turned out being the right choice, as demonstrated in the last subsection.\n\nHowever, I believe that I underestimated this single decision. My current state is represented by the tuple $(inputs,\\, next\\_waypoint,\\, deadline)$. The $deadline$ is assigned by the Environment in a non-deterministic way, what makes my state space unlikely to learn in $100$ trials. In the figure \\ref{fig:perf_compr_2} is possible to see what happens If I discard this single variable in the performance of all my $LearningAgent$.\n\n\\begin{figure}[ht!]\n\\centering\n\\includegraphics[width=0.75\\textwidth]{images/performance_comparition_2.png}\n\\caption{\\label{fig:perf_compr_2}Cumulative Reward By Agent}\n\\end{figure}\n\nUsing this inter-state representation, the final version of the agent is much closer to a perfect agent. It reached the destination at $90\\%$ of the trials and learned most of what need to learn in less than $60$ trials.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% REFLECTION\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Reflection}\n\\label{sec:reflection}\nSomething really valuable that I learned from reviewers is the importance of the state space representation and how it affects the performance of the learning agent.\n\nStill, it's hard to say how better would be the performance of a perfect agent to contrast to the current implementation, given the stochastic environment. An option would be to implement a learning agent that already knows the traffic rules and just need to learn how to find his way to the destination on time.\n\n\n\n\\bibliographystyle{plain}\n% or try abbrvnat or unsrtnat\n\\bibliography{bibliography/biblio.bib}\n\\end{document}\n", "meta": {"hexsha": "a950507ab344028cda24504612837ea8ab10389f", "size": 29304, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "main.tex", "max_stars_repo_name": "ucaiado/Smart_Cab", "max_stars_repo_head_hexsha": "b60358fd90dc511fe3e17aa886a8ddbd4a61f68d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-09-15T09:03:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-22T14:52:28.000Z", "max_issues_repo_path": "main.tex", "max_issues_repo_name": "ucaiado/Smart_Cab", "max_issues_repo_head_hexsha": "b60358fd90dc511fe3e17aa886a8ddbd4a61f68d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.tex", "max_forks_repo_name": "ucaiado/Smart_Cab", "max_forks_repo_head_hexsha": "b60358fd90dc511fe3e17aa886a8ddbd4a61f68d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-04-25T14:26:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-03T01:13:08.000Z", "avg_line_length": 77.3192612137, "max_line_length": 764, "alphanum_fraction": 0.7210960961, "num_tokens": 7050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.31820232778408764}}
{"text": "% chapter included in vclmanual.tex\n\\documentclass[vcl_manual.tex]{subfiles}\n\\begin{document}\n\n\n\\section{Floating point behavior details}\n\\label{FloatingPointBehavior}\n\nThe Vector Class Library is generally conforming to the new IEEE 754-2019 Standard for Floating-Point Arithmetic, but some compromises have been necessary for the purpose of vector processing and for better performance. The deviations from the standard are discussed below.\n\\vspacesmall\n\n\\begin{description}\n\n\\item[Subnormal numbers.]\nSubnormal numbers (also called denormal numbers) are numerically extremely small floating point numbers where the exponent is below the normal range. Some microprocessors are handling subnormal numbers in a very inefficient way that is more than a hundred times slower than for normal floating point numbers. You may call the function \\codei{no\\_subnormals()} to prevent this and treat subnormal numbers as zero. Some of the mathematical functions in VCL always treat subnormal numbers as zero for reasons of performance. This includes logarithm, exponential, and power functions.\n\n\\item[Signed zero.]\nSigned zero is a controversial issue. The floating point standard defines two different zeroes: +0.0 and -0.0.\nThe two zeroes are equal, but still distinguishable. Some of the functions may return +0.0 where the standard requires -0.0.\\\\\nYou may {} \\codei{\\#define SIGNED\\_ZERO} {} if you want the sign of zero to conform to the\nIEEE 754-2019 standard, though this may slow down performance a little.\n\\codei{SIGNED\\_ZERO} may affect several functions, including\n\\codei{round}, \\codei{truncate}, \\codei{floor}, \\codei{ceil}, \n\\codei{maximum}, \\codei{minimum}, \\codei{cbrt}, \\codei{pow\\_ratio}, \\codei{expm1}, \\codei{log1p}. \\\\\nThis feature is not supported in version 1.xx of VCL.\n\n\\item[No exception trapping.] \\label{NoExceptionTrapping}\nFloating point errors are traditionally detected by trapping errors or relying on an \\codei{errno} variable. These methods are not well suited for vector processing and out-of-order processing. This is explained in the document \\href{https://www.agner.org/optimize/nan_propagation.pdf}{\"NAN propagation versus fault trapping in floating point code\", Agner Fog, 2019}.\n\\vspacesmall\n\nThe Vector Class Library does not support fault trapping, and it does not indicate exceptions in a variable such as the traditional \\codei{errno}. It is not recommended to turn on floating point exceptions because this can cause inconsistent behavior, such as traps for exceptions in not-taken branches. Do not attempt to trap numerical errors in \\codei{try/catch} blocks.\n\\vspacesmall\n\nInstead, the vector class library indicates floating point exceptions by producing INF or NAN codes in the individual vector element that produced the fault.\nThe INF and NAN codes will propagate to the end result of a series of calculations when certain conditions are satisfied. The most efficient way of detecting floating point errors is to look for INF and NAN codes in the result.\n\\vspacesmall\n\nConditions where INF and NAN codes are not propagated are discussed at page  \\pageref{FloatingPointErrors}\n\\vspacesmall\n\nDo not use the compiler options -ffast-math, -ffinite-math-only, or /fp:fast because this may disable the detection of INF and NAN.\n\\vspacesmall\n\n\\item[No signaling NANs.]\nSignaling NANs are special codes that will raise an exception when they are loaded from memory. Signaling NANs are rarely used in modern software. Signaling NANs should not be used in VCL because exception trapping is not supported.\n\n\\item[NAN payload operations.]\nA NAN may contain additional information called a payload. This payload can propagate through a series of calculations to the end result. Some of the mathematical functions in VCL can put a payload into the NAN result in case of an error. This makes it possible to identify which function generated the NAN.\n\\vspacesmall\n\nThe \\codei{nan..} and \\codei{nan\\_code} functions make it possible to set and get NAN payloads. The IEEE 754 standard does not specify what happens to the payload when converting between single and double precision, but experiments show that all microprocessors that use the binary floating point format will left-justify the payload. The \\codei{nan..} and \\codei{nan\\_code} functions treat the NAN payload as a 22-bit left-justified unsigned integer in order to allow conversions between single and double precision. These functions deviate from the IEEE 754-2019 standard.\n\n\\item[NAN propagation in maximum and minimum functions.]\nThe \\codei{max} and \\codei{min} functions do not propagate NANs according to the 2008 version of the standard. This unfortunate situation is redressed in the  2019 revision of the standard. VCL offers two different versions of these functions:\nThe \\codei{max} and \\codei{min} functions are equivalent to \n\\codei{a > b ? a : b} and \n\\codei{a < b ? a : b}, respectively. These functions return \\codei{b} if \\codei{a} is NAN. The slightly less efficient functions \\codei{maximum} and \\codei{minimum} are sure to propagate NANs, in accordance with the 2019 revision of the standard.\n\n\\item[NAN propagation in pow function.]\nThe standard specifies that pow(NAN,0) and pow(1,NAN) will give the result 1.0. The VCL implementation deviates from this and produces a NAN output in all cases where an input is NAN, in order to support reliable NAN propagation.\n\n\\item[Function parameter range.]\nSome of the mathematical functions have internal overflow for extreme values of the input parameters. These functions have a limited input range because an extra branch to handle the extreme cases would reduce the overall performance. Limitations of the input range are mentioned in the listing of the individual functions.\n\n\n\\end{description}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\\vspacesmall\n\n\n\n\\end{document}\n", "meta": {"hexsha": "4c282c99b82305b1bffc2d3e24a69cfa57bc6c04", "size": 5799, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "vcl_float_behavior.tex", "max_stars_repo_name": "haferburg/manual", "max_stars_repo_head_hexsha": "c7b365e7a7bbd3c155ff85edf9c6084311b0c10d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2019-08-05T13:15:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T03:17:29.000Z", "max_issues_repo_path": "vcl_float_behavior.tex", "max_issues_repo_name": "haferburg/manual", "max_issues_repo_head_hexsha": "c7b365e7a7bbd3c155ff85edf9c6084311b0c10d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-03T05:13:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-03T05:13:02.000Z", "max_forks_repo_path": "vcl_float_behavior.tex", "max_forks_repo_name": "haferburg/manual", "max_forks_repo_head_hexsha": "c7b365e7a7bbd3c155ff85edf9c6084311b0c10d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-08-08T08:28:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T08:39:06.000Z", "avg_line_length": 68.2235294118, "max_line_length": 580, "alphanum_fraction": 0.7970339714, "num_tokens": 1322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.31820231124914156}}
{"text": "The horseshoe effect is a phenomenon that has long intrigued ecologists.  Commonly thought to be an artifact of dimensionality reduction, multiple techniques were developed to unravel this phenomenon and simplify interpretation.  Here, we provide evidence that horseshoes arise as a consequence of distance metrics that saturate - a familiar concept in other fields but new to microbial ecology.   This saturation property loses information about community dissimilarity, simply because it cannot discriminate between samples that do not share any common features. The phenomenon illuminates niche differentiation in microbial communities and indicates species turnover along environmental gradients.  Here we propose a rationale to the observed horseshoe effect from multiple dimensionality reduction techniques applied to simulations, soil samples, and samples from postmortem mice.   An intuitive-depth understanding of this phenomenon allows for the targeting of niche differentiation patterns from high-level ordination plots.\n\\section{Introduction}\nEcological datasets, particularly those observed in microbiome studies, are typically sparse and high-dimensional, frustrating most conventional statistical techniques.  Many numerical ecology software packages make use of distance-based statistics by calculating the distance between ecological communities, to compare various ecosystems to each other over space and time.  One of the most common exploratory analysis techniques is ordination, where the distances between the communities are embedded into a Euclidean space, and then visualized via Principal Components Analysis (\\gls{pca}) \\cite{numerical_ecology}.  A widely used extension of this technique, where the distance metric can be varied, is called Principal Coordinates Analysis (\\gls{pcoa}) \\cite{numerical_ecology}.  \\par\nOne phenomenon that commonly occurs in datasets containing ecological gradients is the horseshoe effect or Guttman effect \\cite{global_patterns}.  This phenomenon is typified by a linear gradient that appears as a curve in ordination space. The horseshoe effect, or its relative the arch effect \\cite{detrended_correspondence_analysis} (where the ends of the gradient do not attract each other along the first principal coordinate as they do in the horseshoe effect), is observed using multiple types of ordinations, including Principal Components Analysis, Principal Coordinates Analysis, Non-Metric Multidimensional Scaling, Correspondence Analysis, and many others \\cite{numerical_ecology}.  In 1982, the prevailing view of the horseshoe effect arose, when it was described by Gauch as a mathematical artifact that obscures the underlying ecological gradient.  Soon thereafter, Detrending Correspondence Analysis \\cite{detrended_correspondence_analysis} was invented to unbend the horseshoe using reciprocal averaging. Since then, detrending has become a commonly applied practice to ordinations in ecological datasets.   Although these detrending techniques appear to provide a more intuitive visualization, they have been criticized as providing a distorted perspective of the underlying data, relying on many parameter settings that cannot be chosen in a principled way, and obscuring true underlying patterns in the data \\cite{trust_dca}.\\par\n\\begin{figure}[H]\n        \\centering\n        \\includegraphics[width=1.1\\textwidth]{ch2/Figure1.pdf}\n        \\caption[An explanation of the horseshoe effect arising from distance saturation.]\n        {An explanation of the horseshoe effect arising from distance saturation. (a) A band table where the y axis encodes for individual \\gls{otu}s and the x axis encodes for samples.  Blocks that are colored black have a value of 1/10 while blocks that are colored white have a value of 0.  (b) The first 2 components from a \\gls{pca} of the band table, yielding the typical horseshoe shape.  (c) The Euclidean distance from the point 0 to all of the other points.  (d) An illustration of distance saturation property.\\index{SanDiego6}}\n        \\label{figb1}\n\\end{figure}\nFrom previous studies, it was shown that horseshoes can arise from band tables \\cite{horseshoe_kernel, guttman_effect}.  These tables consist of highly dense, non-zero values along the diagonal of the table, and sparse values everywhere else.  This pattern can be apparent when the rows and columns are sorted in the proper order. Although the idea that band tables lead to horseshoes is not a new idea, it is commonly misunderstood how this concept applies to microbial analyses.  Here we provide some intuition behind the mathematical structure of horseshoes.\\par\nIn Figure \\ref{figb1}a, we show a simulated band table, where each vertical band is represented by a sample, and contains 10 non-zero values.  In typical microbiome datasets, these values could reflect \\gls{otu} or species counts; for simplicity, here we will to refer to them as species counts, although this concept can also be generalized to multiple data types, such as gene counts, metabolite abundances.  Each sample in the table is shifted by 1 row, creating the band effect.  When \\gls{pca} is applied directly to this table, the first 2 eigenvectors yield a horseshoe pattern (Figure \\ref{figb1}b).  Here, the band table is parameterized with a band size of 10, since each sample has exactly 10 non-zero values.  \\par\nFor close local points, the Euclidean distance grows linearly along the gradient (Figure \\ref{figb1}c).  However, after a certain point, the distance completely saturates. This property has been previously noted with Euclidean distance \\cite{detrended_correspondence_analysis}.  The overlap between the first sample in the band table, and sample 10 and beyond disappears, and the distance between these samples is maximized. This can yield unintuitive properties, sample 10 could be less dissimilar than sample 1 compared to sample 20.  For instance, sample 10 could represent a medium pH environment, sample 1 could represent an acidic low pH environment and sample 20 could represent a high pHbasic environment. Sample 1 is expected to be a substantially more different microbial community to Sample 20 than Sample 10.  The acidophiles found in Sample 1 are typically not found in basic environments. Sample 20 is expected to be more different to sample 1 than sample 10, since it contains very different microbes that thrive in high pH environments.  But as far as Euclidean distance is concerned, sample 10 is just as dissimilar to sample 1 as sample 20, just because there are no common bacteria shared between these samples.  It is apparent that the saturation property of Euclidean distance does not capture all of the information about community dissimilarity along a gradient, simply because it cannot discriminate between samples that do not share any common features.  Once the distance is saturated, all samples that do not overlap lie within a ball of radius B where B is the band size lie within a ball of radius where B is the band size and the first point is the center of the ball as shown in Figure \\ref{figb1}d.\\par\nThis saturation property has been suggested to give rise to horseshoes in previous studies in other fields \\cite{horseshoe_kernel}, and is an unintuitive property that can confound ecological interpretations if not understood properly.  This property also restricts the possible trajectories of samples in the feature space, and gradients cannot be represented by linear trajectories in the real space (Supplemental proof 1). This means that communities in the original high dimensional space do not arrange into linear trajectories in the first place, and when projected to lower dimensions do not fall into linear trajectories.  These trajectories are what we refer to as horseshoes.  The horseshoe phenomenon is analogous to the familiar concept of saturation in molecular evolution, where two randomly evolving sequences saturate at 75\\% DNA sequence identity (assuming equal nucleotide frequencies), even if infinite time has elapsed \\cite{dna_saturation}. Consequently, distances that reflect a higher degree of molecular change need to be corrected for multiple substitutions in order to recover the molecular clock-like behavior obtained when comparing more similar sequences. This is why corrections according to models such as Jukes-Cantor or the Kimura 2-parameter model are required to obtain distances for reconstructing better phylogenetic trees. Analogous distance corrections are needed in microbial ecology for reconstructing better relationships among microbial communities \\cite{evolutionary_distances}.\\par\nIt is important to note that horseshoes do not only arise from \\gls{pca}, but also arise in \\gls{pcoa} with a variety of distance metrics.  Arch effects have plagued every multidimensional reduction technique we have applied to a wide range of microbial ecology datasets \\cite{microbial_patterns}. In the following case studies, we'll show that these distance metrics also have the saturation property.  In addition, if a distance doesn't have this saturation property, there won't be an observed horseshoe artifact (Figure S1).\\par\n\\section*{Case Study 1 - 88 Soils}\nIn this study, 88 soil samples were obtained from multiple locations across the United States having varying levels of pH \\cite{soil_pyro}.  The V4 region of the 16S rRNA gene (16S) within each organism was amplified and sequenced using 454 pyrosequencing to obtain relative abundances of microbial taxa.  A matrix representing abundance values for each taxonomic unit per soil sample was used as input in correspondence analysis (\\gls{ca}) \\cite{correspondence_analysis}. The resulting ordination showed clear separation of the communities based on pH (Figure \\ref{figb2}a), which led to the same conclusion that pH is a major driving factor in soil biogeography, i.e. pH has major impacts on the distribution of bacterial taxonomic units in soil \\cite{soil_pyro}.  The \\gls{ca} analysis in Figure \\ref{figb2}a also shows the classic horseshoe shape.   Here we revisited this study, to better understand the horseshoe shape behind this dataset.\\par\nTo test the effect of another commonly used distance metric on the sample distribution, we analyzed the same soil dataset applying Chi Squared distance (Figure \\ref{figb2}b). Similar to what was observed with Euclidean distance, which was applied in the simulation, the Chi Squared distance increased sharply at pH 3 and 4, but began to saturate at pH of 5.  Also the band table similar to what we have observed in Figure \\ref{figb2}a can be obtained when sorting.  Also, when the the \\gls{otu} table was sorted by sample pH and the mean pH of the samples that the \\gls{otu}s were observed in mean pH of the \\gls{otu}s (Equation 12), the same band table pattern appeared as we show in Figure \\ref{figb2}a.  While the diagonal isn't completely dense, there are more non-zero values compared to the corners of the heatmap. In line with the findings from the original study, this pattern is likely representative of niche differentiation of \\gls{otu}s with respect to pH. The organisms that thrive in low pH environments tend not to exist in high pH environments and vice versa.  Low pH and high pH samples are shown in Figure \\ref{figb2}c to have few overlapping species, a pattern not observed in the original study as membership was evaluated at coarser levels of taxonomic resolution\\cite{soil_pyro}.\\par\n\\begin{figure}[H]\n        \\centering\n        \\includegraphics[width=1\\textwidth]{ch2/Figure2.pdf}\n        \\caption[Two case studies show casing how horseshoes can appear in the context of\n          soil microbial communities and post-mortem microbial communities.]\n        {Two case studies show casing how horseshoes can appear in the context of soil microbial communities and post-mortem microbial communities. (a) Correspondence analysis of 88 soils.  (b) Distance saturation of chi-squared metric, plotting the chi squared distance of the first sample versus all of the other samples. (c) Heatmap of log transformed \\gls{otu} counts from the 88 soils with the samples sorted by pH and the \\gls{otu}s sorted by mean pH.  (d) Principal Coordinates Analysis of unweighted UniFrac distance.  (e) UniFrac distance of a samples from the last time point versus all of the samples. (f) Heatmap of centred log ratio transformed (Equation 2) \\gls{otu} counts sorted by harvest days.\\index{SanDiego8}}\n        \\label{figb2}\n\\end{figure}\n\\section*{Case Study 2 - Post Mortem Mice Study}\nIn this study, 120 mice were sacrificed and allowed to decompose on soil. Mice were destructively sampled over approximately 8 weeks\\cite{mammalian_corpse}. 16S sequencing libraries were generated from total DNA extracted from swabs of the skin on the head, and relative abundance values were calculated for each bacterial \\gls{otu}. A relative abundance matrix was generated for each library and used as input in \\gls{pca}. This analysis generated a clear horseshoe (Figure \\ref{figb2}d) using unweighted UniFrac distance \\cite{soil_pyro}, with a gradient with respect to the time since death, possibly reflecting a changing skin microbiome during decomposition of the mouse carcass. When the samples were sorted by time since death using a similar strategy as noted above, a band table emerges (Figure \\ref{figb2}f). Also, the unweighted UniFrac distance analysis appears to have the same saturation property as observed previously with Euclidean distance and Chi-squared distance.  It is important to note that highest possible UniFrac distance is 1, suggesting that this distance metric can also be saturated.  In Figure \\ref{figb2}e, while the distance hasn't completely saturated, these distances are quickly approaching the theoretical maximal UniFrac distance. \\par\nThe striking changes in microbial communities during decomposition are associated with dramatic environmental biochemical changes, including increased pH, ammonia, and total nitrogen, all measured in soil beneath the mice. Correspondingly, microbial communities are predicted to increase in gene abundance of important nitrogen cycling pathways such as amino acid degradation (e.g. glutamate dehydrogenase, lysine decarboxylase, ornithine decarboxylase) and nitrate reduction (e.g. nitrate and nitrite reductase). Bacterial taxa in the families Chromatiaceae (\\gls{otu} 46026, 4482362) and Rhizobiaceae (\\gls{otu} 4301099) are involved in nitrogen metabolism and become abundant as mouse bodies progress through the stages of decomposition (e.g. Fresh, Active Decay, Advanced Decay).  As shown in Figure S1, all of these \\gls{otu}s peak at specific timepoints. The two Chromatiaceae \\gls{otu}s peak during Active Decay (bloating and purge of fluids) at 15 days of decomposition. The Rhizobiaceae \\gls{otu} peaks during Advanced Decay (sinking and sagging flesh) at 30 days of decomposition and when pH, ammonia, and total nitrogen were measured at their highest levels \\cite{mammalian_corpse}.\\par\nTo further validate if saturation leads to horseshoes, a new distance metric \\gls{embad} (Earth Mover Band Aware Distance) was engineered to be non-saturating as a proof of concept (Supplemental Methods).  This distance metric uses prior knowledge about the ordering of the band table, and is determined by calculating the flow between two samples. As shown in Figure S1a, sample 1 and sample 2 each have 4 species proportions.  To calculate the distance between sample 1 and sample 2, the probability mass of species 1 and species 2 needs to be shuffled over to species 3 and species 4.  This concept is analogous to computing maximum flow along a pipe, and can be calculated using Earth Mover's distance \\cite{emd, unifrac_emd, unifrac}.\\par\nFor the 88 soils (Figure S1b), the \\gls{embad} was applied to the pH sorted table. Therefore, even if two samples are not overlapping, samples closer together will have a smaller distance than samples farther apart in the gradient.  This is because the distance is defined to be not saturating and explicitly accounts for the pH gradient.  The same strategy was employed for the postmortem interval mice (Figure S1c), sorting the table by decomposition days. The \\gls{pcoa} plots resulting from these applications of \\gls{embad} suggest that a non-saturating distance metric could remove the horseshoe effect from lower dimensional projections of these abundances.  This provides further evidence that this saturation property could explain the the horseshoe phenomenon.\\par\nFor the 88 soils study a \\gls{permanova} test investigating the difference between soils with a pH less than 3, and soils with a pH greater than 8.  With the \\gls{embad} distance metric the \\gls{permanova} gave a pseudo F-statistic of 650.5 and a p-value of 0.0003, which has a much larger effect size compared to the original Chi-squared distance metric with a pseudo F-statistic of 3.8 and a p-value of 0.0004 with 9999 permutations.  A similar trend was observed in the post mortem interval mice study when testing the first decomposition day to the last decomposition day using \\gls{permanova}.  The \\gls{embad} distance metric had a pseudo F-statistic of 439.8 and a p-value of 0.0001 with 9999 permutations, which has a larger effect size than the Unifrac distance metric, which had a pseudo F-statistic of 25.5 and a p-value of 0.0001. This method is relieved from misinterpretations of data due to horseshoes and arches and facilitates the interpretation of taxonomic units along biologically significant gradients that reflect the selective pressure of these factors on the distribution of microbes.  \\par\nIn light of the benefits of engineering a non-saturating distance metric, the \\gls{embad} distance metric requires the gradient to be known a priori.  Generalizing this approach in the absence of known gradients is a difficult problem would require an exhaustive using known algorithms.  Specifically, this problem falls under the category of NP-hard problems (Supplemental Proof 2).  In the 88 soils study and the post mortem mice study, we were fortunate to be able to infer the underlying band table with known metadata.  \\par\nThe band patterns we observe here are probably very common in ecology studies investigating species distribution patterns across spatial or temporal gradients. The pattern confirms microbial ecological fundamentals, i.e. bacteria have acquired unique adaptations to the environment and occupy either a broad range or very specific niches. In our case studies of the 88 soils - and the postmortem mice we confirmed that by using a band table pattern analysis approach, bacterial species show different adaptations to pH and bacterial diversity changes over time during decomposition of mice carcasses. The band pattern approach we apply here represents an additional method to visualize differences between microbial communities.\\par\nBased on our observations here, the horseshoe effect appears in dimensionality reduction techniques due to the saturation property of distance metrics.  While we have only tested a few distance metrics, it is suspected that a vast majority of these distance metrics exhibit the same property, which would also explain why horseshoes are encountered so frequently across many different fields. The saturation property has also been observed in multiple other fields, and other studies from different disciplines have come to similar conclusions \\cite{horseshoe_kernel}. In addition, multiple techniques such as self organizing maps \\cite{self_organizing_maps} and local linear embedding \\cite{local_linear_embedding} attempt to avoid this saturation phenomenon by focusing on distances of nearby points.\\par\nIn spite of the saturation property of distance metrics, identifying horseshoes is still highly useful for identifying patterns concerning niche differentiation.   Properly understanding this phenomenon will motivate the use and development of algorithms such as biclustering \\cite{biclustering} to uncover underlying band patterns.  These insights will in effect allow us to identify microbial niches along different environmental conditions.\\par\n\\section{Materials and Methods}\nAll analyses can be found below on github \\\\\n\\url{https://github.com/knightlab-analyses/horseshoe-analyses}.\nThe mean gradient used for the 2 case studies was calculated as follows.\n\\begin{equation}\n        \\overline{g}_{x}=\\sum_{i=1}^{N}g_{i}\\frac{x_{i}}{\\sum_{j=1}^{D}x_{j}}\n\\end{equation}\nWhere $x_{i}$ is the proportion of \\gls{otu} \\textit{x} in sample \\textit{i} , $\\overline{g}_{x}$ is the mean gradient of \\gls{otu} \\textit{x}, and $g_{i}$  is the sample gradient at sample i. This calculation can be found in the gneiss package under the function \\textbf{mean\\_niche\\_estimator}. The function used to sort the tables in Figure \\ref{figaS1}c used \\textbf{niche\\_sort}. In the 88 soils study, the table was sorted by sample pH and the mean pH of the samples that the organisms were observed in. In the post mortem mice study, the table was sorted by the days of decomposition and the mean day of the samples of that the organisms were observed in.\\par\nThe heatmap in Figure \\ref{figaS2}f and the abundances in Figure S2 were normalized using the centre log ratio \\gls{clr} transformation given by the following equation.\n\\begin{equation}\n        clr(x)=\\left [ \\log \\frac{x_{1}}{g(x)},...,\\log \\frac{x_{D}}{g(x)} \\right ]=\\log x-\\overline{\\log x}\n\\end{equation}\nWhere $g(x)=\\sqrt[n]{\\prod_{i=0}^{n}x_{i}}$ is the geometric mean and $\\overline{\\log x}=\\log g(x)=\\frac{1}{n}\\sum_{i=0}^{n}\\log x$ is the average of the log transformed values.  A pseudocount of 1 is added to all of the counts to prevent logarithms of zero occurring. \\par\nAnalyses were performed using Scipy, Numpy, Matplotlib, Seaborn, Scikit-bio and Gneiss.\n\\section{Acknowledgements}\nWe thank Noah Fierer for his input on the analysis of the 88 soil samples and Dan Knights for discussion on the \\gls{embad} metric. We also acknowledge Amnon Amir and Tomasz Kosciolek for their insights into the horseshoe effect. Finally, we thank Susan Holmes for her insights on previous work understanding the horseshoe effect.\n\nJ.T.M. was funded by NSF GRFP DGE-1144086. J.L.M. and R.K. were funded by the Office of Justice Programs National Institute of Justice (award NIJ-2011-DN-BX-K533).\n\nChapter 2, in full, is a reprint of the material as it appears in\n``Uncovering the Horseshoe Effect in Microbial Analyses''\nJames T. Morton, Liam Toran, Anna Edlund, Jessica L. Metcalf,\nChristian Lauber, Rob Knight \\emph{mSystems}, 2, 2017.  The dissertation author was the primary investigator and first author of this paper.\n", "meta": {"hexsha": "f487f3de78dd95a9d5efa6dd2b6d7f4f8be0351a", "size": 22656, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ch2_horseshoe.tex", "max_stars_repo_name": "mortonjt/phd-thesis", "max_stars_repo_head_hexsha": "f2b381322236b2591b51e4f9fca5899e0922654c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch2_horseshoe.tex", "max_issues_repo_name": "mortonjt/phd-thesis", "max_issues_repo_head_hexsha": "f2b381322236b2591b51e4f9fca5899e0922654c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch2_horseshoe.tex", "max_forks_repo_name": "mortonjt/phd-thesis", "max_forks_repo_head_hexsha": "f2b381322236b2591b51e4f9fca5899e0922654c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 371.4098360656, "max_line_length": 1734, "alphanum_fraction": 0.8054819915, "num_tokens": 5101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.3181641180781102}}
{"text": "%%\n%% Template abstract.tex\n%%\n\n\\chapter*{Abstract}\n\\label{cha:abstract}\n\\addcontentsline{toc}{chapter}{Abstract}\n\nRecent sky surveys such as the Sloan Digital Sky Survey and the VST ATLAS Survey have given us a large\namount of data to work with. Spectroscopic labelling, however, is quite expensive, so we only\nwant to manually label an object if doing so allows us to gain new information. This thesis\nexplores pool-based active learning and the novel application of prominent active learning heuristics to\nthe domain of photometric classification.\n\nWe begin by applying standard supervised machine learning techniques to two astronomical datasets.\nThe best-performing classifiers with reliable probability estimates, logistic regression and support\nvector machines, are then used to conduct the active learning experiment. Our key original\ncontribution is the application of Thompson sampling, a Bayesian solution to the exploration vs\nexploitation problem, to the selection of six active learning heuristics. To address the problem of\nclass imbalance, we derive an extension of the posterior balanced accuracy to the\nmulti-class setting. This is used to evaluate the performance of our algorithms.\n\nThe results are very promising. Even under simplistic assumptions like a normally distributed\nreward, Thompson sampling manages to automatically identify the optimal heuristic after only 50\nexamples. In particular, the margin minimisation technique is a clear winner, outperforming random\nsampling by as much as 9\\% in the VST ATLAS dataset after 300 examples. Being very\ncomputationally efficient, we recommend that astronomers use the margin heuristic with logistic\nregression to decide which objects to label next in future sky surveys. To help them with this task,\nwe have created an open-source and extendable Python package that allows others to easily apply\nactive learning routines to any dataset and make quick visualisation of photometric data.\n\n\n%%% Local Variables: \n%%% mode: latex\n%%% TeX-master: \"thesis\"\n%%% End: \n", "meta": {"hexsha": "7bd27619c84e61ae8f521794a22e52724ba2ad88", "size": 2033, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "projects/alasdair/thesis/0.5_abstract.tex", "max_stars_repo_name": "chengsoonong/mclass-sky", "max_stars_repo_head_hexsha": "98219221c233fa490e78246eda1ead05c6cf7c17", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2016-06-01T12:09:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-16T05:28:01.000Z", "max_issues_repo_path": "projects/alasdair/thesis/0.5_abstract.tex", "max_issues_repo_name": "alasdairtran/mclearn", "max_issues_repo_head_hexsha": "98219221c233fa490e78246eda1ead05c6cf7c17", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 165, "max_issues_repo_issues_event_min_datetime": "2015-01-28T10:37:34.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-23T06:55:13.000Z", "max_forks_repo_path": "projects/alasdair/thesis/0.5_abstract.tex", "max_forks_repo_name": "alasdairtran/mclearn", "max_forks_repo_head_hexsha": "98219221c233fa490e78246eda1ead05c6cf7c17", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2015-01-24T16:27:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-01T08:54:31.000Z", "avg_line_length": 54.9459459459, "max_line_length": 104, "alphanum_fraction": 0.8150516478, "num_tokens": 405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3181641180781102}}
{"text": "\\documentclass{article}\n\\usepackage{amsmath,mathtools,amssymb}\n\\usepackage{graphicx}\n\\usepackage{booktabs}\n\\usepackage{blkarray}\n\\usepackage{gensymb}\n\\usepackage{verbatim}\n\\usepackage{mathrsfs}\n\\usepackage{bbm}\n\\usepackage{braket}\n\\usepackage{hyperref}\n\\usepackage{verbatim}\n\\usepackage{cancel}\n\\usepackage[margin=1.0in]{geometry}\n\\newcommand{\\ol}{\\overline}\n\\newcommand{\\lp}{\\left(}\n\\newcommand{\\rp}{\\right)}\n\\newcommand{\\eps}{\\varepsilon}\n\\newcommand{\\lam}{\\lambda}\n\\newcommand{\\h}{\\circ}\n\\newcommand{\\p}{\\bullet}\n\n\\newcommand{\\Ezero}{E^{(0)}}\n\\newcommand{\\Phizero}{\\Phi^{(0)}}\n\\newcommand{\\Eone}{E^{(1)}}\n\\newcommand{\\Phione}{\\Phi^{(1)}}\n\n\\newcommand{\\Ecorr}{E_{\\mathrm{corr}}}\n\\newcommand{\\Hc}{H_{\\mathrm{c}}}\n\\newcommand{\\dg}{\\ensuremath{^\\dagger} }\n\\def\\*#1{\\mathbf{#1}}\n\\DeclarePairedDelimiter\\floor{\\lfloor}{\\rfloor}\n\n\\title{Lecture 5: Perturbation Theory I}\n\\date{April 1, 2020}\n\\begin{document}\n\\maketitle\n\\noindent\nTo remind you of the current task at hand, we are trying to find good quality approximations \n    to electronic wavefunctions in order to obtain the electronic energy of a molecular system. \nThat is, we seek to solve the Schr{\\\"o}dinger equation in the best way possible.\n\\[H \\ket{\\Psi} = E \\ket{\\Psi} \\]\nWe already learned that HF theory is a decent and cheap approximation, and full-CI is exact but very expensive. \nPerturbation theory is one of many approaches to finding wavefunctions and energies which are of \n    reasonable cost and reasonable accuracy.\nRecall, however, that the HF wavefunction $\\Phi$ gives us a very good starting point, so we are really just interested in solving for the correlation energy,\nwhich is obtained by shifting our Hamiltonian by the HF energy.\n\\[\\Hc \\ket{\\Psi} = \\Ecorr \\ket{\\Psi} \\]\nwhere \n\\[\\Hc = H - \\braket{\\Phi| H | \\Phi} \\]\n\\[\\Ecorr = E_{\\mathrm{exact}} - E_{\\mathrm{HF}}\\]\n\nWe will start by discussing Rayleigh-Schr{\\\"o}dinger perturbation theory (RSPT), which applies the ideas of PT to the time-independent \n    Schr{\\\"o}dinger equation.\nNext, we will apply the results of RSPT to derive M{\\o}ller-Plesset methods (MP$n$) for approximating the electronic correlation energy of molecular systems. \n\n\\section{Rayleigh-Schr{\\\"o}dinger Perturbation Theory}\nPerturbation theory (PT), in the most general sense, is applicable in nearly every domain of physics. \nIf a problem can be separated into some easily solvable piece A and not-so-easily solvable piece B \n    (``the perturbation''), one can approach the exact solution of the problem in terms of the solution to A \n    plus a series of corrections to account for the influence of perturbation.\nRayleigh-Schr{\\\"o}dinger Perturbation Theory (RSPT) applies the ideas of PT to the time-independent \n    Schr{\\\"o}dinger equation.\nThe Hamiltonian is decomposed into a sum of a simple (easy to solve) problem $H_0$ and a perturbation $V$:\n\\[H = H_0 + V \\]\nIf the perturbation is ``small'' (i.e., does not wildly shift the solutions of the problem) the \n    energy levels/eigenstates associated with the \\textit{perturbed system} described by $H$ can be expressed \n    as sum of the energy levels/eigenstates of  the \\textit{simple system} (described by $H_0$) and a series \n    of corrections obtained by considering the influence of the perturbation $V$ on the \n    energy levels/eigenstates of the simple system.\nEach of these corrections contain eigenvalues of $H_0$ and matrix elements of the perturbation \n    between the eigenfunctions of $H_0$, as we will see.\nIn summary, RSPT is applying age-old ideas of general perturbation theory to the\n    time independent Schr{\\\"o}dinger equation.\n\nThe eigenvalue problem we wish to solve is the following:\n\\[H \\ket{\\Psi_i} = (H_0 + V) \\ket{\\Psi_i} = E_i \\ket{\\Psi_i}\\]\nWe are assuming $H_0$ is a simple, easy-to-solve system, for which we have access to all the eigenstates \n    and eigenvalues.\n\\[H_0 \\ket{\\Phi_i^{(0)}} = E_i^{(0)} \\ket{\\Phi_i^{(0)}} \\]\nThese eigenstates $\\ket{\\Phi_i^{(0)}}$ and eigenvalues $E_i$ for the simple system are hopefully very close\n    to the exact results  $\\ket{\\Psi_i}$ and  $E_i$, that is, the perturbation $V$ is small.\nNow, we do something a bit weird.\nWe introduce a parameter $\\lam$ in front of $V$, which allows us to toggle the influence of the\n    perturbation on the energy levels and eigenstates. \nBefore saying much else about $\\lam$, let's write it down and see what it allows us to do.\n\\[(H_0 +  \\lam V) \\ket{\\Psi_i} = E_i \\ket{\\Psi_i}\\]\nWhen $\\lam = 0$, our Hamiltonian is just $H_0$, and our eigenstates and energy levels become that \n    of the simple system $\\ket{\\Phi_i^{(0)}}$ and $ E_i^{(0)}$.\nWhen $\\lam = 1$, our Hamiltonian is the full Hamiltonian $H$, and our eigenstates and energy levels \n    are the perturbed system $\\ket{\\Psi_i^{(0)}}$ and $E_i$.\nBy doing this, \\textit{the energy levels and eigenstates of the perturbed system are a function\n    of }$\\lam$.\nTo put it another way, our energy levels and eigenstates depend on lambda; \n    we might express this mathematically as  $E_i(\\lam)$ and $\\Psi_i(\\lam)$.\nSince these quantities are \\textit{functions of} $\\lam$, we can write down a Taylor series\nexpansion of the energy levels and eigenstates of $H$ in terms of $\\lam$:\n\\[E_i =  E_i^{(0)} +  \\lam E_i^{(1)} + \\lam^2 E_i^{(2)}  + \\cdots \\]\n\\[\\ket{\\Psi_i} =  \\Phi_i^{(0)} +  \\lam \\Phi_i^{(1)} + \\lam^2 \\Phi_i^{(2)} + \\cdots \\]\nwhere each term is,  \n\\[ E_i^{(k)} = \\left. \\frac{1}{k!} \\frac{d^k E_i}{d \\lam^k} \\right\\rvert_{\\lam = 0} \\]\n\\[ \\Phi_i^{(k)} = \\left. \\frac{1}{k!} \\frac{d^k \\ket{\\Psi_i}}{d \\lam^k} \\right\\rvert_{\\lam = 0} \\]\n\nWe call $E_i^{(0)}$ the 0$^{th}$ order energy, which is the energy of the simple system. \nEvery additional term in the energy expansion is the $n^{th}$ order energy correction, \n    and these are what we must solve for.\nLikewise terminology is used for the eigenstate corrections $\\ket{\\Phi_i^{(k)}}$\n\nMany textbooks and other resources simply say $\\lam$ is a \n    ``fictitious dummy parameter'' or ``book-keeping device'' that is \n    used to keep track of the  ``orders'' of the terms when working with the perturbation expansion.\nThis is a bit of an oversimplification. The parameter $\\lam$ has the utility of turning\nthe perturbation on/off, and motivates the use of a Taylor expansion in the first place.\nWithout $\\lam$, you have no Taylor expansion, and no perturbation theory. \nWhile it does serve as a useful label for the orders of each term, it's not just a ``dummy'' parameter. \nIt's the key to all of perturbation theory.\n\n\nWe have a form for the wavefunction and the energy. Plugging these \ninto the time-independent Schr{\\\"o}dinger equation, we get \n\\[\n(H_0 + \\lam V) (\\Phi_i^{(0)} +  \\lam \\Phi_i^{(1)} + \\lam^2 \\Phi_i^{(2)} + \\cdots)\n=  (E_i^{(0)} +  \\lam E_i^{(1)} + \\lam^2 E_i^{(2)}  + \\cdots ) (\\Phi_i^{(0)} +  \\lam \\Phi_i^{(1)} + \\lam^2 \\Phi_i^{(2)} + \\cdots)\n \\]\n\nSubtracting from each side so that the left is 0 and grouping like powers of $\\lam$ gives\n\\begin{align*}\n&  \\left(H_0 \\ket{\\Phi_i^{(0)}} - E_i^{(0)} \\ket{\\Phi_i^{(0)}}   \\right) \\\\\n&+ \\lam \\left( H_0\\ket{\\Phi_i^{(1)}} + V\\ket{\\Phi_i^{(0)}} - E_i^{(0)}\\ket{\\Phi_i^{(1)}} - E_i^{(1)}\\ket{\\Phi_i^{(0)}} \\right)  \\\\\n&+ \\lam^2 \\left( H_0 \\ket{\\Phi_i^{(2)}} + V \\ket{\\Phi_i^{(1)}} - E_i^{(0)} \\ket{\\Phi_i^{(2)}} - E_i^{(1)} \\ket{\\Phi_i^{(1)}} - E_i^{(2)} \\ket{\\Phi_i^{(0)}}  \\right)  \\\\\n&+ \\cdots \\\\ \n&= 0\n\\end{align*}\n\nThe only way the above equation can be satisfied for any arbitrary value of $\\lam$ is \n    if the coefficient in parentheses for each power of $\\lam$ is equal to 0.\nTherefore, since each term for each power of $\\lam$ is equal to 0,\n    this equation is fully separable into an infinite series of simultaneous equations\n\\begin{align*}\n&  H_0 \\ket{\\Phi_i^{(0)}} = E_i^{(0)} \\ket{\\Phi_i^{(0)}}   \\\\\n&  H_0\\ket{\\Phi_i^{(1)}} + V\\ket{\\Phi_i^{(0)}} = E_i^{(0)}\\ket{\\Phi_i^{(1)}} + E_i^{(1)}\\ket{\\Phi_i^{(0)}}  \\\\\n&  H_0 \\ket{\\Phi_i^{(2)}} + V \\ket{\\Phi_i^{(1)}} = E_i^{(0)} \\ket{\\Phi_i^{(2)}} + E_i^{(1)} \\ket{\\Phi_i^{(1)}} + E_i^{(2)} \\ket{\\Phi_i^{(0)}}  \\\\\n& \\cdots \\\\ \n\\end{align*}\nNotice we have now dropped the $\\lam$'s since each of the above equations hold whether or not $\\lam^n$ is applied to each term.\nYou could also interpret this as us setting $\\lam=1$, and fully ``turning on'' the perturbation.\n\nWe will assume henceforth that our reference state is normalized  $\\braket{\\Phizero_i | \\Phizero_i} = 1$\nand our exact wavefunction is intermediately normalized $\\braket{\\Phizero_i | \\Psi_i} = 1$.\nThis yields,\n\\[\\braket{\\Phizero_i | \\Psi_i} = 1 = \\braket{\\Phizero_i | \\Phizero_i} + \\lam \\braket{\\Phizero_i | \\Phione_i} + \\lam^2 \\braket{\\Phizero_i|\\Phi_i^{(2)}} + \\cdots \\]\nIn order for the above expression to be true for arbitrary $\\lam$,\nit must be the case that $\\braket{\\Phizero_i | \\Phi_i^{(k)}} = 0 \\space \\mathrm{for} \\space k = 1,2,3,...$\n\nWe can now project each equation in our system of equations on the left by $\\bra{\\Phi_i^{(0)}}$.\nWe can simplify quite a bit by noting $\\braket{\\Phizero_i | \\Phi_i^{(k)}} = 0 \\space \\mathrm{for} \\space k = 1,2,3,...$ \nand that since $H_0$ is Hermitian, we can act it act on the left to give \n$ \\braket{\\Phizero_i | H_0 | \\Phi_n^{(k)}   } = \\Ezero_i \\braket{\\Phizero_i | \\Phi_i^{(k)}}  $.\n\nThe final result is:\n\\begin{align*}\nE_i^{(0)} = \\braket{\\Phi_i^{(0)} | H_0 | \\Phi_i^{(0)}} \\\\\nE_i^{(1)} = \\braket{\\Phi_i^{(0)} | V | \\Phi_i^{(0)}} \\\\\nE_i^{(2)} = \\braket{\\Phi_i^{(0)} | V | \\Phi_i^{(1)}} \\\\\n\\end{align*}\n\nNotice that $E_i^{(1)}$ depends on $\\Phi_i^{(0)}$, and $E_i^{(2)}$ depends on $\\Phi_i^{(1)}$.\nThis trend continues on for higher order energy corrections: \n    the $n^{th}$ order correction to the wavefunction is required for finding the $(n+1)^{th}$ order energy correction.\n\n% Note, algebra in Szabo/Ostlund was archaic, instead used this https://www.lct.jussieu.fr/pagesperso/toulouse/enseignement/introduction_pt_cc.pdf\n% combined with some other sources\n\\subsection{The first-order wavefunction and second-order energy corrections}\nThe third equation above, the second-order energy ($E_i^{(2)}$) correction, requires you to know the 1st order correction to the wavefunction $\\Phione_i$.\nTo obtain it, we take the equation containing our 1st-order terms and rearrange:\n\n\\[ H_0\\ket{\\Phione_i} + V \\ket{\\Phizero_i} = \\Ezero_i \\ket{\\Phione_i} + \\Eone_i \\ket{\\Phizero_i} \\]\nProjecting by $\\bra{\\Phizero_n}$ for some $n \\neq i$ gives \n\n\\[ \\braket{\\Phizero_n | H_0 | \\Phione_i} + \\braket{ \\Phizero_n | V | \\Phizero_i} = \\Ezero_i \\braket{\\Phizero_n|\\Phione_i} + \\Eone_i \\braket{\\Phizero_n | \\Phizero_i} \\]\n\nTo simplify, note that $\\bra{\\Phizero_n} H_0 = \\Ezero_n \\bra{\\Phizero_n}$, so the first term on the left becomes $\\Ezero_n \\braket{\\Phizero_n | \\Phione_i} $\nThe second term on the right goes to 0 since $\\braket{\\Phizero_n|\\Phizero_i} = 0 $ when $n \\neq i$. \nThe reason is these are both eigenfunctions of $H_0$, which are orthonormal.\nWe are left with\n\\[ \\Ezero_n \\braket{ \\Phizero_n | \\Phione_i} + \\braket{ \\Phizero_n | V | \\Phizero_i} = \\Ezero_i \\braket{ \\Phizero_n | \\Phione_i }    \\]\nRearranging we get\n\\[ \\braket{\\Phizero_n | \\Phione_i } = -\\frac{ \\braket{ \\Phizero_n | V | \\Phizero_i} }{ \\Ezero_n - \\Ezero_i} \\]\n\nWe want to get $\\ket{\\Phione_i}$ by itself on the left side.\nThe left side above is the expansion coefficients of $ \\Phione_i$ in the basis of $\\Phizero_n$.\nTo see this, project each side by $ \\ket{\\Phizero_n} $ and sum over all $n \\neq i$\n\\[ \\sum_{n \\neq i} \\ket{ \\Phizero_n} \\braket{\\Phizero_n | \\Phione_i } = \\sum_{n \\neq i} -\\frac{ \\braket{ \\Phizero_n | V | \\Phizero_i} }{ \\Ezero_n - \\Ezero_i} \\ket{\\Phizero_n} \\]\n\nThe left side above would be equal to $\\ket{\\Phione_i}$ if the sum was over all $n$ (resolution of the identity), \n    but if we sum over all $n$, the energy denominator on the right will be 0 for $n = i$. \nFortunately, the expansion coefficient $\\braket{\\Phizero_n | \\Phione_i } $ for $n = i$ is necessarily 0.\nWhy? Because of intermediate normalization.\n\\[\\braket{\\Phizero_i | \\Psi_i} = 1 = \\braket{\\Phizero_i | \\Phizero_i} + \\lam \\braket{\\Phizero_i | \\Phione_i} + \\lam^2 \\braket{\\Phizero_i|\\Phi_i^{(2)}} + \\cdots \\]\n\nSince our reference wavefunction is normalized $\\braket{\\Phizero_i | \\Phizero_i} = 1$, in order for this expression to be true for arbitrary $\\lam$,\nit must be the case that $\\braket{\\Phizero_i | \\Phi_i^{(k)} = 0 \\mathrm{for k} = 1,2,3,...}   $\nThis implies that when $n = i$, the expansion coefficient is 0.\nTherefore, we can sum over all $n$ (rather than $n \\neq i$) on the left side of our expression for $\\ket{\\Phione_i}$ without penalty; it is the same as adding zero to both sides:\n\\[ \\sum_{n} \\ket{ \\Phizero_n} \\braket{\\Phizero_n | \\Phione_i } = \\sum_{n \\neq i} -\\frac{ \\braket{ \\Phizero_n | V | \\Phizero_i} }{ \\Ezero_n - \\Ezero_i} \\ket{\\Phizero_n} \\]\nNoting the left side contains the resolution of the identity, we can just remove it:\n\\[ \\ket{\\Phione_i} = \\sum_{n \\neq i} -\\frac{ \\braket{ \\Phizero_n | V | \\Phizero_i} }{ \\Ezero_n - \\Ezero_i} \\ket{\\Phizero_n} \\]\n\nThis now enables us to derive an evaluable expression for the second-order energy \n\\[ E_i^{(2)} = \\braket{\\Phi_i^{(0)} | V | \\Phi_i^{(1)}} \\]\nPlugging in the definition for $\\Phi_i^{(1)}$ above we obtain\n\\[ E_i^{(2)} = \\sum_{n \\neq i} -\\frac{ \\braket{ \\Phizero_n | V | \\Phizero_i} \\braket{ \\Phizero_i | V | \\Phizero_n} }{ \\Ezero_n - \\Ezero_i} \\ket{\\Phizero_n} \\]\n\\[ E_i^{(2)} = \\sum_{n \\neq i} \\frac{ |\\braket{ \\Phizero_i | V | \\Phizero_n} |^2  }{ \\Ezero_i - \\Ezero_n} \\]\n\nOne could keep working through the tedious algebra and derive the expressions for the second order wavefunction, third order wavefunction, etc, and\nin turn obtain energy corrections $E_i^{(3)}$, $E_i^{(4)}$, etc, but we will stop here.\nThe above results are sufficient for deriving second-order M{\\o}ller--Plesset perturbation theory.\n\nThere does exist a more advanced scheme which generalizes the results of all orders of perturbation theory using a mysterious new thing called ``resolvents''.\nWe will touch on this at the end of these notes and continue down that path after learning diagrams. \n\nRSPT, as described above, is a completely general scheme, applicable to any application of the time-independent Schrodinger equation.\nWe will use these ideas to come up with a way to obtain electronic energies with RSPT. \n\n\\section{M{\\o}ller--Plesset Perturbation Theory}\nM{\\o}ller--Plesset Perturbation Theory (MP$n$) is the direct application of time-independent RSPT to the problem of finding electronic wavefunctions and energies.\nIn this section, we will derive MP2 by applying the RSPT equations derived above for a specific partition of our electronic Hamiltonian into $H_0$ and $V$.\nThe MP2 energy which is correct up to second-order.\n\nWe first must divide our Hamiltonian into two parts, one which has a simple solution $H_0$ and the perturbation $V$.\n\\[H = H_0 + V \\]\nIn MP$n$ methods, the $H_0$ part of the Hamiltonian is taken to be the Hartree-Fock Hamiltonian,\n\\[H_0 = F = (h_p^q + \\bar{g}_{pi}^{qi}) a_q^p = f_p^q a_q^p  \\]\nNote here we are \\textbf{not} using the $\\Phi$-normal ordered Fock operator $f_p^q \\tilde{a}_q^p$.\nThe perturbation $V$ will just be everything not included in $H_0$. \n\\[V = H - F \\]\n\\[V =  \\frac{1}{4} \\bar{g}_{pq}^{rs} a_{rs}^{pq} - \\bar{g}_{pi}^{qi} a_{q}^{p}  \\]\nOne could interpret $V$, the perturbation, as being all of the two-electron interactions, except for the mean-field picture already given by the HF Hamiltonian.\n\nSuppose we seek the energy of the ground state of a system (which we will denote by a subscript 0).\nThe ground state 0th order wavefunction $\\Phi_0^{(0)}$ is the Hartree-Fock Slater determinant wavefunction. \nThe ground state 0th order energy is given by $E_0^{(0)} = \\braket{\\Phi_0^{(0)} | H_0 | \\Phi_0^{(0)}}$\n\\begin{align*}\nE_0^{(0)} &= \\braket{\\Phi_0^{(0)} | H_0 | \\Phi_0^{(0)}} \\\\\n          &= \\sum_i h_{ii} + \\sum_{ij} \\braket{ij||ij}  \n\\end{align*}\nWe note the above expression, from Hartree-Fock theory, is equal to the sum of the occupied orbital energies $\\sum_i \\eps_i$\n\\[E_0^{(0)} = \\sum_i h_{ii} + \\sum_{ij} \\braket{ij||ij} = \\sum_i \\eps_i  \\]\n\nThe 1st order energy correction is given by $E_0^{(1)} = \\braket{\\Phi_0^{(0)} | V | \\Phi_0^{(0)}}$\n\\begin{align*}\nE_0^{(1)} &= \\braket{\\Phi_0^{(0)} | V | \\Phi_0^{(0)}} \\\\\n          &= -\\frac{1}{2} \\sum_{ij} \\braket{ij||ij} \n\\end{align*}\n\nWe notice immediately that the sum of the 0th and 1st order energies is the Hartree-Fock energy.\n\\[ E_0^{(0)} + E_0^{(1)} = \\sum_i h_{ii} + \\frac{1}{2}\\sum_{ij} \\braket{ij||ij}   \\] \n\nThus, the first two terms of our energy perturbation expansion is the HF energy.\n\\[E_0 =  E_0^{(0)} +  E_0^{(1)} + E_0^{(2)} + \\cdots \\]\n\\[E_0 =  E_{\\mathrm{HF}} + E_0^{(2)} + \\cdots \\]\nIt must be that all higher-order terms constitute \\textit{correlation energies}, since in principle the expansion should approach the exact \n    energy so long as the perturbation is small.\n\nThe second-order energy correction to the ground state energy is given by \n\\[ E_0^{(2)} = \\sum_{n \\neq 0} \\frac{ |\\braket{ \\Phizero_0 | V | \\Phizero_n} |^2  }{ \\Ezero_0 - \\Ezero_n}  \\]\nWhat sort of states are $\\Phizero_n$? They can be any excitation from our ground state reference HF determinant $\\Phi_0$ (any determinant in our CI expansion).\nHowever, we find that single excitations do not survive:\n\\[ \\braket{\\Phi_0 | V | \\Phi_i^a } =  \\braket{\\Phi_0 | H - H_0 | \\Phi_i^a } = \\braket{\\Phi_0 | H | \\Phi_i^a } - \\braket{\\Phi_0 | H_0 | \\Phi_i^a }  = 0 \\]\nTriple and higher excitations do not survive because you cannot form complete contractions, so $\\Phizero_n$ can only be the set of unique doubly excited determinants. \nWhat about the $\\Ezero_0$ and $\\Ezero_n $?\nRecall $\\Ezero_0$ is the eigenvalue of $H_0$ acting on our Hartree-Fock determinant,\n\\[H_0 \\ket{\\Phi_0^{(0)}} = E_0^{(0)} \\ket{\\Phi_0^{(0)}} \\]\n which is just the sum of the occupied orbital energies $E_0^{(0)} = \\sum_k \\eps_k$,.\nThe same is true for $\\Ezero_n$, but it has a sum over occupied orbital energies which differs by two spin orbital occupations. Thus,\n\\[\\Ezero_0 - \\Ezero_n =  \\sum_k \\eps_k - ( \\sum_k \\eps_k - (\\eps_i + \\eps_j - \\eps_a - \\eps_b)) \\]\n\\[\\Ezero_0 - \\Ezero_n =  \\eps_i + \\eps_j - \\eps_a - \\eps_b \\]\n\nSo we finally obtain for the second order energy expression,\n\\[ E_0^{(2)} = \\sum_{n \\neq 0} \\frac{ |\\braket{ \\Phizero_0 | V | \\Phizero_n} |^2  }{ \\Ezero_0 - \\Ezero_n}  \\]\n\\[ E_0^{(2)} = \\sum_{\\substack{i < j \\\\ a < b}} \\frac{ |\\braket{ \\Phi_0 | V | \\Phi_{ij}^{ab}} |^2}{ \\eps_i + \\eps_j - \\eps_a - \\eps_b  }  \\]\nNoting that only the first term of $V$ yields a nonzero result,\n\\[ E_0^{(2)} = \\sum_{\\substack{i < j \\\\ a < b}} \\frac{ |\\braket{ \\Phi_0 | \\frac{1}{4} \\bar{g}_{pq}^{rs} a_{rs}^{pq} | \\Phi_{ij}^{ab}} |^2}{ \\eps_i + \\eps_j - \\eps_a - \\eps_b  }  \\]\n\\[ E_0^{(2)} = \\frac{1}{16} \\sum_{\\substack{i < j \\\\ a < b}}  \\frac{ |\\braket{ ij || ab}|^2}{ \\eps_i + \\eps_j - \\eps_a - \\eps_b}\\]\n\\[ E_0^{(2)} = \\frac{1}{4} \\sum_{ijab} \\frac{ |\\braket{ ij || ab}|^2}{ \\eps_i + \\eps_j - \\eps_a - \\eps_b}\\]\n\n\n\\end{document}\n", "meta": {"hexsha": "57de32c636cedf8a39f5d3c626a735ef5e21cd12", "size": 18966, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "2020/lecture_notes/tex/5_PT_1.tex", "max_stars_repo_name": "GQCG-edu/chem-8950", "max_stars_repo_head_hexsha": "a5f58a5feacbae16b02fddd2c74723da1486b8d2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2020/lecture_notes/tex/5_PT_1.tex", "max_issues_repo_name": "GQCG-edu/chem-8950", "max_issues_repo_head_hexsha": "a5f58a5feacbae16b02fddd2c74723da1486b8d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-07-13T12:11:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-13T15:31:47.000Z", "max_forks_repo_path": "2020/lecture_notes/tex/5_PT_1.tex", "max_forks_repo_name": "GQCG-edu/chem-8950", "max_forks_repo_head_hexsha": "a5f58a5feacbae16b02fddd2c74723da1486b8d2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 65.6262975779, "max_line_length": 180, "alphanum_fraction": 0.6790572604, "num_tokens": 6374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.3181641180781101}}
{"text": "\\section{Background}\n\\label{sec:background}\n\nTo give context for DSP-PBE, we first explain the traditional concept of programming by example~\\cite{cypher93,lieberman01,synasc12}.\nProgramming by example (PBE) is a synthesis technique that automatically generates programs that coincide with given examples.\nAn example is specified as a tuple of input and output values.\nGiven a set $S= \\{(i_1, o_1),\\ldots, (i_n, o_n)\\}$ of input/output examples, the goal is to automatically derive a program $P$ such that for every $j$, $P(i_j) = o_j$.\n\nPBE is in line with one of the often repeated high level goals of functional programming -- to describe \\textit{what} a program should do, and not \\textit{how} the program should do it.\nInstead of writing code, the user provides a list of relevant examples and the synthesis tool automatically generates a program.\nIn this way, the examples can be seen as an easily readable and understandable specification.\nHowever, even if the synthesized program satisfies all the provided examples, it still might not correspond to the user's intentions.\nExamples are, by nature, an incomplete specification.\n\nPBE is a promising research direction that enables easy manipulation of data even for non-programmers~\\cite{GulwaniHS12}.\nRecent work in this area has focused on manipulating fundamental data types such as strings~\\cite{vldb12,icml13} and lists~\\cite{FeserCD15,poseraZ15}.\nThe success and impact of this line of work can be estimated from the fact that PBE ships as part of the popular Flash Fill feature in Excel 2013~\\cite{flashfill}.\n\n\nThe core difference between traditional PBE and DSP-PBE is in the application domain of Digital Signal Processing.\nDigital Signal Processing (DSP) programming languages provide users with an interface to build signal processing programs in domain specific languages.\nSome of these languages provide their own implementations of signal processing primatives, such as SuperCollider~\\cite{supercollider}, CSound~\\cite{csound}, and PureData~\\cite{puredata}.\nOther DSP languages provide alternative front-ends to these languages, such as Vivid~\\cite{vivid}, which provides Haskell bindings to Supercollider.\n\nAlthough many DSP languages are full featured enough to write general purpose programs, in this work we focus on the construction of DSP filters.\nA DSP filter is, broadly speaking, any program that transforms a digital signal from one form to another.\nAn example of a DSP filter is a low-pass filter, which takes an input signal and generates an output signal that keeps frequencies below some frequency threshold, but removes frequencies above that threshold.\n\nThe most closely related work in audio signal processing is a technique called resynthesis~\\cite{masri1996improved}.\nResynthesis is the process of decomposing a sound into its spectrogram, and then building a synthesizer to recreate a similar sound.\nThe limitation here is that resynthesis builds a generative synthesizer, which does not take into account any information about the components used to create the original sound.\nThis limitation means that resynthesis cannot be applied in a new context, whereas DSP-PBE allows us to construct a DSP program that can be used with various new input samples to create novel sounds. \nFor example, DSP-PBE could be given a sample of a trumpet and a trombone, and the generated DSP program could be applied to a violin to hear what a violin sounds like if it was a trumpet that had been turned into a trombone.\nIn this case we can discover the analogy \\textit{trumpet:trombone :: violin:?}.\n\nFrom a machine learning perspective, the above example use case is closely related to work on learning analogies~\\cite{mikolov2013distributed}, where the goal is to discover relations such as \\textit{man:king :: woman:queen}.\nTo do this, words are embedded in a vector space, so that the transformation from \\textit{man} to \\textit{king}, can be directly applied to \\textit{woman}.\nThere are two keys differences between this approach and DSP-PBE.\nThe first is that DSP-PBE should produce a human readable transformation.\nWe would like to generate DSP programs that can be used verbatim, but also inspected and modified by the user.\nWhile program code provides this readability, vector transformations are not comprehensible in the same way. \nSecond, word embeddings require that the semantics of an object can be embedded into a vector space. \nAs we will see in Sec~\\ref{sec:distance}, a semantic representation of an audio file (what a human perceives) is not immediately recoverable from its direct representation.\n", "meta": {"hexsha": "767e058aad254825bced126df6d47e937e1a7af0", "size": 4594, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "papers/FARM-18/secs/background.tex", "max_stars_repo_name": "Yale-OMI/DSP-PBE", "max_stars_repo_head_hexsha": "073f366e8096004adeec5d2cde1cf3546c4690f5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-12-03T02:36:39.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-03T02:36:39.000Z", "max_issues_repo_path": "papers/FARM-18/secs/background.tex", "max_issues_repo_name": "Yale-OMI/DSP-PBE", "max_issues_repo_head_hexsha": "073f366e8096004adeec5d2cde1cf3546c4690f5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2018-11-16T21:50:44.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-16T18:57:19.000Z", "max_forks_repo_path": "papers/FARM-18/secs/background.tex", "max_forks_repo_name": "Yale-OMI/DSP-PBE", "max_forks_repo_head_hexsha": "073f366e8096004adeec5d2cde1cf3546c4690f5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 104.4090909091, "max_line_length": 225, "alphanum_fraction": 0.8058336961, "num_tokens": 996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.3181641099207703}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\marginpar{Friday\\\\ 2020-4-24, \\\\ compiled \\\\ \\today}\n\n\\section{The Zel'dovich approximation}\n\nSo far we have discussed perturbation in two ways: initially, we had a contribution on the RHS of the EFE given by the perturbations.\n\nDuring radiation dominance there is not much need to go beyond linear theory. \n\nNow we want to go full nonlinear.\n\nWe need to use a mixture of techniques: both the study of the 2-body problem and a continuous distribution of matter.\nThis is what we do if we use numerical techniques.\n\nOn the other hand, we can make some smart approximations.\n\nLast semester we mentioned the ``spherical top-hat solution'': we assume spherical symmetry, and work from there. \n\nThe Zel'dovich approximation gives an exact solution in the case of planar symmetry.\nWe can also get exact solutions with cylindrical symmetry. \n\nWe come back to the fluid equations: continuity, Euler, Poisson on a FRLW background. \n\nWhen you do linear perturbation theory, you perturb around the background value.\n\nHowever, in doing this we are assuming that all the perturbations have the same weight: this is not necessarily true. We should define an internal hierarchy. \n\nWhat we are doing is formal in the context of Lagrangian perturbation theory. \n\nWe define \n%\n\\begin{subequations}\n\\begin{align}\n\\eta &= \\frac{\\rho }{ \\rho_{b}}  = 1 + \\delta  \\\\\n\\vec{u} &= \\dv{\\vec{x}}{a} = \\frac{\\vec{v}}{a \\dot{a} }  \\\\\n\\varphi &= \\frac{3 t_{*}^2}{2 a_{*}^3} \\phi \n\\,.\n\\end{align}\n\\end{subequations}\n\nThis is because he wanted dependence on the growth factor. In EDS this is the scale factor, in general this could be a different thing.\n\nWe are referring to a more general background: there can be a growth suppression factor, such that the density perturbation \\(\\delta \\) does not scale with \\(a\\) but instead based on some function of \\(a\\). \nWe should use this function and not the scale factor in general.\nIn the matter-filled universe we are considering right now this is the same.\n\nThe new equations are \n%\n\\begin{subequations}\n\\begin{align}\n\\frac{ \\DD \\vec{u}}{\\DD a} + \\frac{3}{2a} \\vec{u} &= - \\frac{3}{2a} \\nabla \\varphi  \\\\\n\\frac{ \\DD \\eta }{\\DD a} + \\eta \\nabla \\cdot \\vec{u} &= 0  \\\\\n\\nabla^2 \\varphi &= \\frac{\\delta}{a}\n\\,,\n\\end{align}\n\\end{subequations}\n%\nwhere \n%\n\\begin{align}\n\\frac{\\DD }{\\DD a} = \\pdv{}{a} + \\vec{u} \\cdot \\nabla\n\\,\n\\end{align}\n%\nis the convective derivative.\n\nWe have chosen this variable \\(\\vec{u}\\) precisely because we want something which is almost constant in linear theory: we have \\(\\delta \\sim t^{2/3}\\) and \\(v \\sim t^{1/3}\\) and \\(\\phi \\sim \\const\\). \n\nSo, we get \n%\n\\begin{align}\n\\pdv{\\vec{u}}{a} = 0  \n\\,,\n\\end{align}\n%\nso then we can approximate:\n%\n\\begin{align}\n\\bigd{\\vec{u}}{a} = 0 \n\\,.\n\\end{align}\n\nAt the linear level, \\(\\vec{u} = - \\nabla \\varphi \\). \nThe argument is that we can \\emph{extend} the linear result beyond the linear level. This is because the velocity goes like \\(k\\), while the potential goes like \\(\\delta / k^2\\).\n\nThe system becomes more and more linear as we increase the scale.\n\nWhy don't we try to solve the equation by neglecting the nonlinearity in the velocity? \n\nThen the equation system reads: \n%\n\\begin{subequations}\n\\begin{align}\n\\bigd{\\vec{u}}{a} &= 0  \\\\\n\\bigd{\\eta }{a} + \\eta \\nabla \\cdot \\vec{u} &= 0 \n\\,.\n\\end{align}\n\\end{subequations}\n\nThis can be solved exactly, as we will now see.\n\nThis is describing the inertial motion of particles with no external force acting on them. \n\nIt is important to say that this is a total derivative: the variation is zero along the trajectories of the particles.\n\nThe velocity of a particle which has a velocity \\(\\vec{u}_{0}\\) at a position \\(\\vec{q}\\) is preserevd. We can integrate the position straightforwardly, since the relation we get is linear.\n\nThis, however, is in our weird variables: the real motion is more complicated, but we can map the new variables to the new ones.\n\nWe can solve the continuity equation in different ways: we can divide by \\(\\eta \\) to get logarithmic derivatives, so that \n%\n\\begin{align}\n\\bigd{\\log \\eta }{a} =  -\\nabla \\cdot \\vec{u}\n\\,.\n\\end{align}\n\nwhen we integrate, though, we should follow the trajectory: \n%\n\\begin{align}\n\\eta (\\vec{x}, a) = \\eta_0 (\\vec{q}) \\exp{ - \\int_{a_0 }^{a} \\dd{a'} \\nabla \\cdot \\vec{u} \\qty[\\vec{x}(\\vec{q}, a',), a']}\n\\,.\n\\end{align}\n\nThis calculation is done in `The large scale structure of the universe' by Peebles \\cite[]{peeblesLargescaleStructureUniverse1980}.\n\nAlso, we can use an approach in which we use the Jacobian of the change of coordinates between Lagrangian and Eulerian.\n\nThe tensor \n%\n\\begin{align}\nD_{ij} = \\pdv[2]{\\varphi_0}{q_{i}}{q^{j}}\n\\,\n\\end{align}\n%\nis called the deformation tensor.\nThe matrix \n%\n\\begin{align}\n\\pdv{x^{i}}{q_{j}} = \\delta^{i}_{j} - a \\pdv[2]{\\varphi_0}{q_{i}}{q^{j}}\n\\,\n\\end{align}\n%\ndefines the transformation between the old and new coordinates.\nThe eigenvalues of the transformation tensor are local. \n\nIt can be shown (Doroshevick 1970) that there is a \\SI{92}{\\percent} probability that at least one eigenvalue is positive.\n\nThis is computed using the assumption that \\(\\varphi_0 \\) has a gaussian distribution.\n\nThis is important since we can write \n%\n\\begin{align}\n\\eta (\\vec{x}, a) = \\frac{1}{\\prod_{i=1}^{3} (1 - \\lambda_{i}(\\vec{q}) a)}\n\\,.\n\\end{align}\n\nPancakes in terms of shapes, of course, not in terms of ingredients.\n\nThe jacobian of the change of coordinates is ill defined if two particles collide. \n\nAt that point, we get nonlinearities, which \\emph{are} structure formation.\nThis is a sort of non-gaussianity we get from this approximation.\n\n\\end{document}\n", "meta": {"hexsha": "db34b4daae122cb20f8835e942da86f805503770", "size": 5653, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ap_second_semester/theoretical_cosmology/apr24.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "ap_second_semester/theoretical_cosmology/apr24.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ap_second_semester/theoretical_cosmology/apr24.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 33.8502994012, "max_line_length": 207, "alphanum_fraction": 0.7109499381, "num_tokens": 1669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.3180877417649705}}
{"text": "\\pdfoutput=1\n\\documentclass[twocolumn]{aastex62}\n%%\\documentclass[]{emulateapj}\n\n%Accepted/received/... %%\n\n\\received{xxx}\n\\revised{yyy}\n\\accepted{zzz}\n\n%% Command to document which AAS Journal the manuscript was submitted to.\n\\submitjournal{AAS Journals}\n\n%% Short title/authors\n\n\\shorttitle{LXUV History of TRAPPIST-1}\n\\shortauthors{Fleming et al.}\n\n%% Begin document, title, packages %%\n\\usepackage{hyperref}\n\\usepackage{xspace}\n\\usepackage{graphicx}\n\\usepackage{amsmath}\n\\usepackage[caption=false]{subfig}\n\n%% Custom commands\n\\def\\mearth{{\\rm\\,M_\\oplus}}\n\\def\\rearth{{\\rm\\,R_\\oplus}}\n\\def\\msun{{\\rm\\,M_\\odot}}\n\\def\\rsun{{\\rm\\,R_\\odot}}\n\\def\\lsun{{\\rm\\,L_\\odot}}\n\\def\\gsim{~\\rlap{$>$}{\\lower 1.0ex\\hbox{$\\sim$}}}\n\\def\\lsim{~\\rlap{$<$}{\\lower 1.0ex\\hbox{$\\sim$}}}\n\n\\newcommand{\\xxx}[1]{{\\textbf{#1}}}\n\\newcommand{\\vplanet}[0]{\\texttt{VPLanet}\\xspace}\n\\newcommand{\\emcee}[0]{\\texttt{emcee}\\xspace}\n\\newcommand{\\approxposterior}[0]{\\texttt{approxposterior}\\xspace}\n\\newcommand{\\eqtide}[0]{\\texttt{EQTIDE}\\xspace}\n\\newcommand{\\stellar}[0]{\\texttt{STELLAR}\\xspace}\n\\newcommand{\\kepler}[0]{\\textit{Kepler}\\xspace}\n\\newcommand{\\jwst}[0]{\\textit{JWST}\\xspace}\n\n%% Begin doc %%\n\\begin{document}\n\n\\title{On The XUV Luminosity Evolution of TRAPPIST-1}\n\n%% AUTHORS %%\n\n%%\\correspondingauthor{David P. Fleming}\n%%\\email{dflemin3@uw.edu}\n\n%%\\author[0000-0001-9293-4043]{David P. Fleming}\n\\author[0000-0001-9293-4043]{David P. Fleming}\n\\affil{Astronomy Department, University of Washington \\\\\nBox 951580, Seattle, WA 98195}\n\\affil{NASA NExSS - Virtual Planetary Laboratory Lead Team, USA}\n% ORCID 0000-0001-9293-4043\n\n\\author{Rory Barnes}\n\\affiliation{Astronomy Department, University of Washington \\\\\nBox 951580, Seattle, WA 98195}\n\\affil{NASA NExSS - Virtual Planetary Laboratory Lead Team, USA}\n% no orcid\n\n\\author[0000-0002-0296-3826]{Rodrigo Luger}\n\\affil{NASA NExSS - Virtual Planetary Laboratory Lead Team, USA}\n\\affiliation{Center for Computational Astrophysics, Flatiron Institute \\\\\nNew York, NY 10010}\n% ORCIF 0000-0002-0296-3826\n\n\\author[0000-0002-9623-3401]{Jacob T. VanderPlas}\n\\affiliation{Google \\\\\n601 N 34th St, Seattle, WA 98103}\n% ORCID 0000-0002-9623-3401\n\n%% ABSTRACT %%\n\n\\begin{abstract}\n\nWe model the long-term XUV luminosity of TRAPPIST-1 to constrain the evolving high-energy radiation environment experienced by its planetary system. Using Markov Chain Monte Carlo (MCMC), we derive probabilistic constraints for TRAPPIST-1's stellar and XUV evolution that account for observational uncertainties, degeneracies between model parameters, and empirical data of low-mass stars. We constrain TRAPPIST-1's mass to $m_{\\star} = 0.089 \\pm{0.001}$ M$_{\\odot}$ and find that its early XUV luminosity likely saturated at $\\log_{10}(L_{XUV}/L_{bol}) = -3.05^{+0.24}_{-0.10}$. From our posterior distributions, we infer that there is a ${\\sim}43\\%$ chance that TRAPPIST-1 is still in the saturated phase today, suggesting that TRAPPIST-1 has maintained high activity and $L_{XUV}/L_{bol} \\approx 10^{-3}$ for several Gyrs. TRAPPIST-1's planetary system therefore likely experienced a persistent and extreme XUV flux environment, potentially driving significant atmospheric erosion and volatile loss. The inner planets likely received XUV fluxes ${\\sim}10^3 - 10^4\\times$ that of the modern Earth during TRAPPIST-1's 1 Gyr-long pre-main sequence phase. Deriving these constraints via MCMC is computationally non-trivial, so scaling our methods to constrain the XUV evolution of a larger number of M dwarfs that harbor terrestrial exoplanets would incur significant computational expenses. We demonstrate that \\approxposterior, a Python machine learning package for approximate Bayesian inference using Gaussian processes, can efficiently replicate our analysis. We find that it derives constraints that are in good agreement with our MCMC, although it underestimates the uncertainties for two parameters by $30\\%$. \\approxposterior requires $330\\times$ less computational time than traditional MCMC methods in this case, demonstrating its utility in efficient Bayesian inference.\n\n\\end{abstract}\n\n%% Keywords %%\n\n\\keywords{}\n\n%% Intro %%\n\n\\section{Introduction} \\label{sec:intro}\n\nThe James Webb Space Telescope (JWST) is poised to detect and characterize the first terrestrial exoplanet atmospheres via transmission spectroscopy. This search will likely focus on planets orbiting nearby M dwarfs given their favorable relative transit depths, the potential buildup of biosignature gases due to UV-driven photochemisty \\citep{Segura2005}, and the large occurrence rates of M dwarf planets \\citep{Dressing2015}. The correct interpretation of those observations, however, is predicated on understanding the system's long-term evolution, most importantly processes that could impact the planet's atmospheric state and habitability, such as atmospheric escape, water loss, and the potential buildup of an abiotic O$_2$ atmosphere \\citep{Watson1981,Lammer2003,MurrayClay2009,Luger2015}. These volatile escape mechanisms are partially driven by the host star's XUV luminosity (X-ray and EUV emission ranging over approximately 1-1000\\AA), and therefore characterizing the long-term stellar XUV evolution of late M-dwarfs is critical to assessing the present state of their planets, including habitability.\n\nHigh-energy stellar radiation originates from the corona via the heating of magnetically-confined plasma \\citep{Vaiana1981}. The stellar magnetic field is likely generated via differential rotation within the stellar convective envelope \\citep{Parker1955}, linking rotation to stellar activity and XUV emission. Stellar rotation rates slow over time due to magnetic braking \\citep{Skumanich1972}, causing XUV emission to decline with time. The X-ray luminosity ($L_{X}$) of FGK stars, for example, has been empirically shown to monotonically decrease with age \\citep{Jackson2012}. This trend has also been observed for commonly-used proxies for stellar age, rotation period and Rossby number \\citep[Ro = $P_{rot}/\\tau$ for convective turnover timescale $\\tau$,][]{Pizzolato2003,Wright2011}. Stellar activity evolution is characterized by two distinct phases. First, in the saturated phase, young, rapidly-rotating stars ($\\mathrm{Ro}\\lsim 0.1$) maintain a constant $L_{X}/L_{bol} \\approx 10^{-3}$ \\citep{Wright2011,Jackson2012}. Then, at longer rotation periods and larger Ro, stars transition to the unsaturated phase in which $L_{X}/L_{bol}$ exponentially decays over time \\citep{Pizzolato2003,Ribas2005}. Recent work has shown that the stellar dynamo processes that generate magnetic fields and drive XUV emission in fully-convective M dwarfs follow the same evolution with Ro as described above for solar-type stars \\citep{Wright2016,Wright2018}. We can therefore apply this model to examine the XUV evolution of individual fully-convective stars.\n\nTRAPPIST-1 \\citep{Gillon2016,Gillon2017}, an ultracool dwarf located 12 pc from Earth, harbors 7 approximately Earth-sized transiting planets that are prime targets for JWST transmission spectroscopy observations \\citep{Morley2017,Lincowski2018,Lustig2019}. TRAPPIST-1's high observed L$_{X}$ \\citep{Wheatley2017}, short photometric rotation period \\citep[3.3 d, ][]{Luger2017}, and low Rossby number \\citep[Ro $\\approx 0.01$, ][]{Roettenbacher2017} suggest that TRAPPIST-1 is still saturated today \\citep{Pizzolato2003,Wright2011,Wright2018}. Both \\citet{Roettenbacher2017} and \\citet{Morris2018} suggest that the photometrically-determined rotation period is inaccurate, with the latter study proposing that the 3.3 d period corresponds to a characteristic timescale for active regions on the stellar surface. TRAPPIST-1's $v \\sin i = 6$ km s$^{-1}$ \\citep{Barnes2014}, however, implies a rotation period of $\\approx 1$ d for $i = 90^{\\circ}$, providing evidence that TRAPPIST-1's rapid rotation is physical and consistent with saturation \\citep[$P_{rot} \\lsim 20$ d,][]{Wright2018}. The TRAPPIST-1 planetary system currently receives significant high-energy fluxes \\citep{Bourrier2017b,Wheatley2017,Peacock2019}, possibly a consequence of TRAPPIST-1 remaining in the saturated regime. These fluxes were likely more extreme during the pre-main sequence, driving significant water loss and potentially rendering the planets uninhabitable \\citep{Bolmont2017,Bourrier2017a}. \n\nHere, we model the long-term stellar and XUV evolution of TRAPPIST-1 to characterize the evolving XUV environment of its planetary system. We use MCMC to derive probability distributions for our model parameters that describe the XUV evolution and are consistent with TRAPPIST-1's observed properties and their uncertainties. TRAPPIST-1 is not the only system that merits this modelling, however, as the Transiting Exoplanet Survey Satellite will likely discover additional transiting planets orbiting in the habitable zone of nearby M dwarfs \\citep{Barclay2018}, some of which will likely be suitable targets for atmospheric characterization with JWST. \n\nIn this work, we show that stellar XUV histories can be accurately inferred using machine learning \\citep[\\approxposterior, ][]{FlemingVanderPlas2018}, but using $330\\times$ less computational resources than traditional MCMC methods. This massive speed-up enables our methods to scale to additional stars that host potential targets for atmospheric characterization. \n\nWe describe our model and statistical methods in $\\S$~\\ref{sec:methods} and $\\S$~\\ref{sec:mcmc}, respectively. We present our results in $\\S$~\\ref{sec:results}, demonstrate the ability of machine learning to reproduce our analysis in $\\S$~\\ref{sec:approx}, and discuss the implications of our results in $\\S$~\\ref{sec:discussion}.\n\n% extra\n% , so their dynamos likely differ, e.g. magnetic field generation via convective turbulence \\citep{Dobler2006} rather than the tachocline-driven generation theorized for late-type stars with radiative cores \\citep{Durney1993}. \n\n\\section{Methods} \\label{sec:methods}\n\n\\subsection{XUV Evolution} \\label{sec:model}\n\nWe simulate TRAPPIST-1's stellar evolution using the \\stellar module in \\vplanet\\footnote{\\vplanet is publicly available at \\href{https://github.com/VirtualPlanetaryLaboratory/vplanet}{https://github.com/VirtualPlanetaryLaboratory/vplanet}.} \\citep{Barnes2019}, which performs a bicubic interpolation over mass and age of the \\citet{Baraffe2015} stellar evolution tracks. The \\citet{Baraffe2015} models (also employed by both \\citet{Burgasser2017} and \\citet{vanGrootel2018} to constrain TRAPPIST-1's stellar properties) were computed for solar metallicity stars and hence are suitable for TRAPPIST-1 whose [Fe/H] is consistent with solar \\citep{Gillon2016}, although \\citet{Burgasser2017} argue TRAPPIST-1 has a slightly super-solar metallicity based on isochrone modeling.\n\nThe X-ray luminosity, L$_{X}$, evolution of fully-convective stars follows the same broken power law model examined for partially-convective FGK stars \\citep{Wright2016,Wright2018}. We assume TRAPPIST-1's L$_{XUV}$ evolution traces that of L$_{X}$ and use the model of \\citet{Ribas2005},\n\\begin{align}\n\\label{eqn:lxuv}\n\\frac{L_\\mathrm{XUV}}{L_\\mathrm{bol}} = \\left\\{\n\t\t\t\t\\begin{array}{lcr}\n\t\t\t\t\tf_\\mathrm{sat} &\\ & t \\leq t_\\mathrm{sat} \\\\\n\t\t\t\t\tf_\\mathrm{sat}\\left(\\frac{t}{t_\\mathrm{sat}}\\right)^{-\\beta_\\mathrm{XUV}} &\\ & t > t_\\mathrm{sat}\n\t\t\t\t\\end{array}\n\t\t\t\t\\right.,\n\\end{align}\nwhere $f_{sat}$ is the constant ratio of stellar XUV to bolometric luminosity during the saturated phase, $t_{sat}$ is the duration of the saturated phase, and $\\beta_{XUV}$ is the exponent that controls how steeply L$_{XUV}$ decays after saturation. \n\n\\subsection{Markov Chain Monte Carlo} \\label{sec:mcmc}\n\nWe use \\texttt{emcee}, a Python implementation of the affine-invariant Metropolis-Hastings MCMC sampling algorithm \\citep{ForemanMackey2013}, to infer posterior probability distributions for our model parameters. These distributions are conditioned on observations of TRAPPIST-1 and the activity evolution of late-type stars and account for both observational uncertainties and correlations between parameters. Our model parameters that we fit for via MCMC comprise the state vector\n\\begin{equation} \\label{eqn:state}\n    \\textbf{x} = \\{m_{\\star}, f_{sat}, t_{sat}, \\mathrm{age}, \\beta_{XUV}\\},\n\\end{equation}\nwhere $m_{\\star}$ and age are the stellar mass and age, respectively, and the other parameters are defined by Eqn.~\\ref{eqn:lxuv}. All of the code used to perform the simulations and analysis in this work is publicly available online.\\footnote{ \\href{https://github.com/dflemin3/trappist}{https://github.com/dflemin3/trappist}}\n\n\\subsection{Priors} \\label{sec:mcmc:priors}\n\nSince we have few available observable properties of TRAPPIST-1 to use to condition our analysis ($L_{bol}$ and $L_{XUV}$, see $\\S$~\\ref{sec:mcmc:like}), our prior probability distributions will strongly impact our results. We use previous studies and empirical data of late M dwarfs to assemble the best available constraints to serve as priors for our MCMC analysis. Following \\citet{vanGrootel2018}, we rely on TRAPPIST-1's luminosity and age to constrain its mass. We therefore adopt a simple uniform prior of $m_{\\star} \\sim \\mathcal{U}(0.07, 0.11)$. For the age, we use the empirical estimate for TRAPPIST-1 derived by \\citet{Burgasser2017}, age $\\sim \\mathcal{N}(7.6, 2.2^2)$ Gyr, as their thorough analysis considered both observations of TRAPPIST-1 and a host of empirical age indicators for ultracool dwarfs. We cap the maximum age we consider at 12 Gyr. Younger ages have been suggested based on TRAPPIST-1's activity \\citep[e.g.~$\\gsim 500$ Myr,][]{Bourrier2017b}, but here we argue that behavior is consistent with an extended saturation timescale.\n\nWe construct an empirical $f_{sat} = \\log_{10}(L_{XUV}/L_{bol})$ distribution from the sample of fully-convective, saturated M dwarfs with observed $L_{X}$ from \\citet{Wright2011}. For each star in the \\citet{Wright2011} sample, we follow \\citet{Wheatley2017} and estimate $L_{XUV}$ as a function of L$_{X}$ using Eqn.~(2) from \\citet{Chadney2015}. We find that the distribution is well-approximated by a normal distribution, $f_{sat} \\sim \\mathcal{N}(-2.92, 0.26^2)$, and we adopt it as our prior.  \n\nThe duration of the saturated phase is estimated to be $t_{sat} \\approx 100$ Myr for FGK stars \\citep{Jackson2012}. Studies of stellar activity of late type stars as a function of stellar age, or its proxy, rotation period, indicate that the activity lifetime, and hence duration of the saturated phase, is likely longer for later-type stars \\citep{Shkolnik2014,Wright2011,West2015}, with fully-convective M dwarfs potentially remaining active throughout their lifetimes \\citep[$t_{sat} \\gsim 7$ Gyr,][]{West2008,Schneider2018}. Furthermore, the spin-down timescales of late M dwarfs increases with decreasing stellar mass \\citep{Delfosse1998}, with late M dwarfs retaining rapid rotation longer than earlier-type stars and hence remaining active for up to $P_{rot} \\approx 86$ d \\citep{West2015}, well-beyond TRAPPIST-1's estimated rotation period. Given these constraints, we adopt a broad uniform $t_{sat}$ prior distribution capped by the maximum age we consider, $t_{sat} \\sim \\mathcal{U}(0.1, 12)$ Gyr. \n\nIn the unsaturated phase, $L_{X}$, and hence $L_{XUV}$, decay exponentially with powerlaw slope $\\beta_{XUV}$ \\citep{Ribas2005}. \\citet{Jackson2012} find that $\\beta_{XUV}$ does not significantly vary with stellar mass in their sample of FGK stars. Since \\citet{Wright2016} found that the X-ray evolution of fully-convective stars is qualitatively similar to that of partially-convective FGK stars, we adopt the $\\beta_{XUV}$ distribution of late K dwarfs from the \\citet{Jackson2012} sample as our prior, $\\beta_{XUV} \\sim \\mathcal{N}(-1.18, 0.31^2)$.\n\n%\\begin{deluxetable}{lcc}\n%\\tabletypesize{\\small}\n%\\tablecaption{Prior Distributions \\label{tab:priors}}\n%\\tablewidth{0pt}\n%\\tablehead{\n%\\colhead{Parameter [units]} & \\colhead{Prior} & \\colhead{Notes}\n%}\n%\\startdata\n%$m_\\star$ [$M_{\\odot}$] & $\\mathcal{U}(0.07, 0.11)$ & -- \\\\  \n%$f_{sat}$ & $\\mathcal{N}(-2.92, 0.26^2)$ & \\citet{Wright2011}  \\\\\n%$t_{sat}$ [Gyr] & $\\mathcal{U}(0.1, 12)$ & -- \\\\\n%age [Gyr] & $\\mathcal{N}(7.6, 2.2^2)$ & \\citet{Burgasser2017} \\\\\n%$\\beta_{XUV}$ & $\\mathcal{N}(-1.18, 0.31^2)$ & \\citet{Jackson2012}\n%\\enddata \\vspace*{0.1in}\n%\\end{deluxetable}\n\n\\subsection{Likelihood Function and Convergence} \\label{sec:mcmc:like}\n\nWe further condition our analysis on TRAPPIST-1's observed bolometric luminosity, $L_{bol} = 5.22 \\pm{0.19} \\times 10^{-4} \\ L_{\\odot}$ \\citep{vanGrootel2018}, and $L_{XUV}/L_{bol}$ \\citep{Wheatley2017}. We convolve the \\citet{vanGrootel2018} $L_{bol}$ measurement with the $L_{XUV}/L_{bol}$ constraints from \\citet{Wheatley2017}, finding $L_{XUV} = 3.9 \\pm{0.5} \\times 10^{-7} \\ L_{\\odot}$ today.\n\nFor a given state vector \\textbf{x}, we define our likelihood function, $\\mathcal{L}$, as\n\\small\n\\begin{equation} \\label{eqn:lnlike}\n    \\ln \\mathcal{L} \\propto -\\frac{1}{2} \\left[ \\frac{(L_{bol} - L_{bol}(\\textbf{x}))^2}{\\sigma_{L_{bol}}^2} + \\frac{(L_{XUV} - L_{XUV}(\\textbf{x}))^2}{\\sigma_{L_{XUV}}^2} \\right] \\\\\n\\end{equation}\n\\normalsize\nwhere $L_{bol}$, $L_{XUV}$ and $L_{bol}(\\textbf{x})$, $L_{XUV}(\\textbf{x})$ are the observed values and \\vplanet outputs given \\textbf{x}, respectively and $\\sigma_{L_{bol}}$ and $\\sigma_{L_{XUV}}$ are the observational uncertainties. We compute the total logprobability for each \\textbf{x} by summing $\\mathcal{L}$ and $\\ln \\mathrm{Prior}(\\textbf{x})$, the log prior probability of \\textbf{x}. We compute the log prior using the distributions described in $\\S$~\\ref{sec:mcmc:priors}. \n\nWe run our MCMC with 100 parallel chains for 10,000 iterations, initializing each chain by randomly sampling each element of \\textbf{x} from their respective prior distributions. During each step of the MCMC chain, \\vplanet takes \\textbf{x} as input and simulates TRAPPIST-1's evolution up to the age in \\textbf{x}, predicting $L_{bol}$ and $L_{XUV}$ to evaluate the likelihood function. We discard the first 500 iterations as burn-in and assess the convergence of our MCMC chains by computing the integrated autocorrelation length and acceptance fraction for each chain. We find a mean acceptance fraction of 0.45 and a minimum and mean number of iterations per integrated autocorrelation length of 75 and 110, respectively, indicating that our chains have converged \\citep{ForemanMackey2013}. Given our integrated autocorrelation lengths, our MCMC chain yielded about 10,000 effective samples from the posterior distribution.\n\n\\subsection{Inference with \\approxposterior} \\label{sec:methods:approx}\n\nThe methods presented above can be applied to any late-type star to constrain its $L_{XUV}$ history, given suitable priors and observational constraints. Our MCMC analysis, however, required 3,700 core hours on the University of Washington Hyak supercomputer to converge. The main computational cost is incurred by running a $10$~s \\vplanet simulation each MCMC step to evaluate the likelihood, requiring ${\\sim}1,000,000$ simulations in total for the full MCMC. Assuming similar convergence properties, repeating this analysis for even a modest sample of 30 stars would require~${\\sim} 110,000$ core-hours, a significant computational expense. Moreover, performing a similar analysis with a more computationally-expensive model, perhaps one that interpolates stellar models over metallicity to additionally fit for [Fe/H], would only exacerbate this issue.\n\nWe apply \\approxposterior\\footnote{\\approxposterior is publicly available at \\href{https://github.com/dflemin3/approxposterior}{https://github.com/dflemin3/approxposterior}.}, an open source Python machine learning package \\citep{FlemingVanderPlas2018}, to compute an accurate approximation to the true MCMC-derived posterior distribution for TRAPPIST-1's XUV evolution, while minimizing the computational cost. \\approxposterior, an implementation of the ``Bayesian Active Learning for Posterior Estimation\" (BAPE) algorithm of \\citet{Kandasamy2015}, trains a Gaussian process (GP) surrogate for the likelihood evaluation, learning on the results of \\vplanet simulations. The GP is then used within an MCMC sampling algorithm, e.g. \\emcee, to quickly obtain the posterior distribution. In our case, predicting the likelihood using the GP (${\\sim} 130 \\mu$s) is $80,000 \\times$ faster than running \\vplanet (10s) each likelihood evaluation, yielding a massive reduction in computational cost.\n\nFollowing \\citet{Kandasamy2015}, \\approxposterior iteratively improves the GP's predictive ability by identifying high-likelihood regions in parameter space where the GP predictions are uncertain. \\approxposterior then evaluates \\vplanet in those regions to supplement the training set, improving the GP's predictive ability in the relevant regions of parameter space, while minimizing the number of forward model evaluations required for suitable predictive accuracy. Similar techniques using a GP surrogate model have been shown to rapidly and accurately infer Bayesian posterior distributions for computationally-expensive cosmology studies \\citep[e.g.][]{Bird2019}.\n\nTo model the covariance between points in the GP training set, we use a squared exponential kernel,\n\\begin{equation} \\label{eqn:kernel}\nk(x_i, x_j) = \\exp \\left( - \\frac{(x_i - x_j)^2}{2l^2} \\right),\n\\end{equation}\nwhere $x_i$ and $x_j$ are two arbitrary points in parameter space and $l$ is a hyperparameter that controls the scale length of the correlations. We assume correlations in each dimension have different scale lengths and fit for each $l$ by optimizing the GP's marginal likelihood of the training set data using the Nelder-Mead algorithm, randomly restarting this optimization 25 times to mitigate the influence of local extrema. We run \\approxposterior for 10 iterations, initially training the GP on a set of 250 \\vplanet simulations with initial conditions sampled from our prior distributions. For each iteration, \\approxposterior selects 100 new training points, alternating between the \\citet{Kandasamy2015} and \\citet{Wang2017} selection criteria, both based on GP predictive uncertainty. \\approxposterior runs \\vplanet at each point for a total of 1,250 training samples. The trained GP is then used within \\emcee to quickly obtain the approximate posterior distribution following the same procedure described in $\\S$~\\ref{sec:mcmc}.\n\n%% Results %%\n\n\\section{Results} \\label{sec:results}\n\n\\subsection{The Evolution of TRAPPIST-1}\n\nIn Fig.~\\ref{fig:corner}, we display the posterior probability distributions for our model parameters derived via MCMC. We adopt the median values of the marginalized distributions as our best-fit solutions and derive the lower and upper uncertainties using the 16th and 84th percentiles, respectively. \n\nTRAPPIST-1 likely maintained a large $L_{XUV}$ throughout its lifetime as we find $f_{sat} = -3.05^{+0.24}_{-0.10}$ and $t_{sat} = 6.85^{+3.43}_{-3.15}$ Gyr, consistent with observed $L_{XUV}/L_{bol}$ and long activity lifetimes of late M dwarfs \\citep{West2008,Wright2018}. The long upper-tail in the marginalized $f_{sat}$ distribution arises from the combination of the degeneracy between $f_{sat}$ and $t_{sat}$ and from our strong empirical $f_{sat}$ prior that disfavors $f_{sat} \\gsim -2.5$. The degeneracy stems from our model attempting to match TRAPPIST-1's observed $L_{XUV}$. For example, larger values of $f_{sat}$ produce high initial $L_{XUV}$, requiring shorter $t_{sat}$, and hence an earlier transition to unsaturated $L_{XUV}$ decay, to decrease $L_{XUV}$ to its observed value, and vice versa. From the posterior distribution, we infer that there is a $43\\%$ chance that TRAPPIST-1 is still in the high-$L_{XUV}$ saturated phase today, suggesting that the TRAPPIST-1 planets could have undergone prolonged water loss. Our analysis strongly disfavors short saturation timescales, with only a $0.4\\%$ chance that $t_{sat} \\leq 1$ Gyr, the saturation timescale adopted by \\citet{Luger2015} in their analysis of water loss from exoplanets orbiting in the habitable zone of late M dwarfs.\n\n\\begin{figure*}[t]\n\\centering\n\t\\includegraphics[width=0.75\\textwidth]{trappist1Corner.pdf}\n   \\caption{Joint and marginal posterior probability distributions for the TRAPPIST-1 stellar parameters given in Eqn.~(\\ref{eqn:state}) made using \\texttt{corner} \\citep{ForemanMackey2016}. The black vertical dashed lines on the marginalized distributions indicate the median values and lower and upper uncertainties from the 16th and 84th percentiles, respectively. From the posterior, we infer that there is a $43\\%$ chance that TRAPPIST-1 is still in the saturated phase today, potentially driving significant volatile loss from its planets.}%\n    \\label{fig:corner}%\n\\end{figure*}\n\nWe constrain TRAPPIST-1's mass to $m_{\\star} = 0.089 \\pm{0.001}$ M$_{\\odot}$, in a good agreement with and $6\\times$ more precise than the value derived by \\citet{vanGrootel2018}. Our marginalized age and $\\beta_{XUV}$ posterior distributions reflect their prior distributions as for the former, $L_{bol}$ is not sufficient to further constrain TRAPPIST-1's age beyond our adopted prior since the luminosities of ultracool dwarfs do not significantly change during the main sequence \\citep{Baraffe2015}. The posterior for $\\beta_{XUV}$ does not vary from the prior because our XUV model is over-parameterized with 3 parameters to fit 2 observations, although all are motivated by empirical data and hence merit inclusion. Our model prefers to exploit the degeneracy between $f_{sat}$ and $t_{sat}$ to match TRAPPIST-1's observed $L_{XUV}$ in our MCMC instead of varying the slope of the unsaturated $L_{XUV}$ decay. Age and $\\beta_{XUV}$ weakly correlate with $f_{sat}$, requiring a narrow spread of $f_{sat} \\approx -3.05$ for young ages and steeper $\\beta_{XUV}$, respectively. $\\beta_{XUV}$ and $t_{sat}$ are uncorrelated, except at short $t_{sat}$ where steep $\\beta_{XUV}$ are disfavored as this evolution would underpredict the observed $L_{XUV}$.\n\n\\subsection{TRAPPIST-1's Evolutionary History}\n\nHere we consider plausible stellar evolutionary histories for TRAPPIST-1 by simulating 100 samples from the posterior distribution using \\vplanet. We plot the evolution of TRAPPIST-1's $L_{bol}$, $L_{XUV}$, and radius in Fig.~\\ref{fig:evol} and compare our models to the measured values. \n\n\\begin{figure*}[t]\n\t\\includegraphics[width=\\textwidth]{trappist1Evol.pdf}\n   \\caption{Plausible evolutionary histories of TRAPPIST-1's $L_{bol}$ (left), $L_{XUV}$ (center), and radius (right) using 100 samples drawn from the posterior distribution and simulated with \\vplanet. In each panel, the blue shaded regions display the 1, 2, and 3 $\\sigma$ uncertainties. The insets display the marginalized distributions (black) evaluated at the age of the system, with the blue dashed lines indicating the observed value and +/- 1 $\\sigma$ uncertainties. The radius, $L_{bol}$, and $L_{XUV}$ constraints are adopted from \\citet{vanGrootel2018} and \\citet{Wheatley2017}, respectively.}%\n    \\label{fig:evol}%\n\\end{figure*}\n\nTRAPPIST-1 remains saturated throughout its $1$ Gyr pre-main sequence, with both $L_{XUV}$ and $L_{bol}$ decreasing by a factor of ${\\sim}40$ before stabilizing on the main sequence. TRAPPIST-1's radius likely shrank by roughly a factor of 4 along the pre-main sequence. We derive a present-day radius $R_{\\star} = 0.112 \\pm{0.001} \\ R_{\\odot}$ from the posterior distribution, a value that is ${\\sim} 7\\%$ smaller than the \\citet{vanGrootel2018} constraint, $R_{\\star} = 0.121 \\pm {0.003} \\ R_{\\odot}$, that was computed from their inferred mass and TRAPPIST-1's density \\citep{Delrez2018}. This difference arises from the likely underprediction of TRAPPIST-1's radius by the \\citet{Baraffe2015} models, consistent with stellar evolution models often underestimating the radii of late M dwarfs \\citep{Reid2005,Spada2013}. An alternate explanation to account for its inflated radius is that TRAPPIST-1 has super-solar metallicity \\citep{Burgasser2017,vanGrootel2018}, but \\citet{vanGrootel2018} found in their modeling that [Fe/H] = 0.4, a $4.5\\sigma$ outlier, was required to reproduce TRAPPIST-1's density and radius. If we instead compute the radius from our marginalized stellar mass posterior distribution and the observed density \\citep{Delrez2018}, we obtain $R_{\\star} = 0.120 \\pm{0.002} \\ R_{\\odot}$, in agreement with \\citet{vanGrootel2018} who used the same procedure.\n\nSince TRAPPIST-1 could still be saturated today, its planetary system has likely experienced a persistent extreme XUV environment. In Fig.~\\ref{fig:fluxes}, we probe the distribution of XUV fluxes, $F_{XUV}$, derived from our posterior distributions for each TRAPPIST-1 planet when the system was 0.01, 0.1, and 1 Gyr old. We normalize these values by the $F_{XUV}$ received by Earth during the mean solar cycle \\citep[$F_{XUV,\\oplus} = 3.88$ erg s$^{-1}$cm$^{-2}$,][]{Ribas2005} and assume the planets remained near their current semi-major axes after migration in the natal protoplanetary disk halted \\citep{Luger2017}. We infer that TRAPPIST-1b likely received extreme $F_{XUV}/F_{XUV, \\oplus} \\gsim 10^4$ during the early pre-main sequence before decaying to the present-day $F_{XUV}/F_{XUV, \\oplus} \\approx 10^3$, consistent with estimates from \\citet{Wheatley2017}. The extended upper-tail of the $F_{XUV}$ distributions corresponds to the large $f_{sat}$ values permitted by the posterior distributions. The likely habitable zone planets, e, f, and g, similarly experienced severe XUV fluxes ranging from $F_{XUV}/F_{XUV, \\oplus} \\approx 10^2 - 10^{3.5}$ throughout the pre-main sequence. Even today, e, f, and g receive $F_{XUV}/F_{XUV, \\oplus} \\approx 10^2$, far in excess of the modern Earth, due to TRAPPIST-1's large present $L_{XUV}$, its extended saturated phase, and the close proximity of M dwarf HZ planets to their host star. These significant high energy fluxes likely drove an extended epoch of substantial atmospheric escape and water loss from the TRAPPIST-1 planets, potentially producing substantial abiotic O$_2$ atmospheres \\citep{Luger2015,Bolmont2017,Bourrier2017a}.\n\n\\begin{figure}\n\t\\includegraphics[width=\\columnwidth]{fluxes.pdf}\n   \\caption{$F_{XUV}/F_{XUV,\\oplus}$ for each TRAPPIST-1 planet derived from samples drawn from the posterior distribution and simulated using \\vplanet when the system was 0.01, 0.1, and 1 Gyr old. The latter age corresponds to the approximate age at which TRAPPIST-1 entered the main sequence.}%\n    \\label{fig:fluxes}%\n\\end{figure}\n\n%% approxposterior %%\n\n\\subsection{Comparison with \\approxposterior} \\label{sec:approx}\n\n% Extra\n%If using a slower model than ours, perhaps one that models stellar evolution by interpolating tracks over mass, age, and metallicity to additionally constrain [Fe/H], or if testing alternate models of $L_{XUV}$ evolution for model comparisons, the computational expense will grow, exacerbating this issue.\n\n\\begin{figure*}[t]\n\\centering\n\t\\includegraphics[width=0.75\\textwidth]{apCorner.pdf}\n   \\caption{Same format as Fig.~\\ref{fig:corner}, but derived by \\approxposterior.}%\n    \\label{fig:approx}%\n\\end{figure*}\n\nHere we compare the approximate posterior distribution derived using \\approxposterior with our previous results (referred to as the fiducial MCMC). We display the approximate joint and marginalized posterior distributions in Fig.~\\ref{fig:approx}. We find that \\approxposterior requires only 11 core hours to derive the approximate posterior distribution, a factor of $330\\times$ faster than our fiducial MCMC. \\approxposterior also used $800\\times$ fewer \\vplanet simulations to build its training set than the ${\\sim}10^6$ simulations ran by the fiducial MCMC for likelihood evaluations. This reduction in computational expense arises from \\approxposterior's GP-based likelihood predictions only taking ${\\sim}130\\mu$s, compared to the much longer $10$~s per \\vplanet simulation. Moreover, \\approxposterior's efficient selection of the GP's training set focuses on high-likelihood regions to improve the GP's predictive ability in relevant regions of parameter space while minimizing the training set size. \n\nIn Table~\\ref{tab:constraints}, we list the marginalized constraints derived by both methods and find that both the median values and magnitude of the uncertainties are in good agreement. Furthermore as seen in Fig.~\\ref{fig:approx}, \\approxposterior recovers the same non-trivial correlations between model parameters seen in the fiducial MCMC posterior distribution. \n\nThe posterior distribution derived by \\approxposterior, however, is not an exact match. \\approxposterior underestimates the magnitude of both the age and $\\beta_{XUV}$ uncertainties by ${\\sim}30\\%$ and predicts that there is a $39\\%$ chance that TRAPPIST-1 is still saturated today, $9\\%$ smaller than the fiducial MCMC-derived value. Our experiment demonstrates that \\approxposterior can be used to derive accurate approximations to the posterior probability distributions of the parameters that control stellar XUV evolution in late M dwarfs, but significantly faster than traditional MCMC methods.\n\n\\begin{deluxetable}{lcc}\n\\caption{Parameter Constraints} \\label{tab:constraints}\n\\tabletypesize{\\small}\n\\tablewidth{0pt}\n\\tablehead{\n\\colhead{Parameter [units]} & \\colhead{\\vplanet MCMC} & \\colhead{\\approxposterior MCMC}\n}\n\\startdata\n$m_\\star$ [$M_{\\odot}$] & $0.089 \\pm{0.001}$ & $0.089 \\pm{0.001}$ \\\\  \n$f_{sat}$ & $-3.05^{+0.24}_{-0.10}$ & $-3.03^{+0.20}_{-0.10}$,  \\\\\n$t_{sat}$ [Gyr] & $6.85^{+3.43}_{-3.15}$ & $6.62^{+3.56}_{-2.56}$ \\\\\nage [Gyr] & $7.44^{+2.04}_{-2.13}$ & $7.54^{+1.43}_{-1.51}$ \\\\\n$\\beta_{XUV}$ & $-1.16^{+0.31}_{-0.30}$ & $-1.16^{+0.21}_{-0.21}$ \\\\\nP$(\\mathrm{saturated})$ & $0.43$ & $0.39$ \\\\\n\\enddata \\vspace*{0.1in}\n\\tablecomments{Best fit values and uncertainties are derived using the medians, $16^{th}$, and $84^{th}$ percentiles from the marginalized posterior distributions, respectively.}\n\\end{deluxetable}\n\n%% Discussion %%\n\n\\section{Discussion and Conclusions} \\label{sec:discussion}\n\nHere, we used MCMC to derive probabilistic constraints for TRAPPIST-1's stellar and $L_{XUV}$ evolution to characterize the evolving XUV environment of its planetary system. We inferred that TRAPPIST-1 likely maintained high $L_{XUV}/L_{bol} \\approx 10^{-3}$ throughout its lifetime, with a $43\\%$ chance that TRAPPIST-1 is still in the saturated regime today. Our results indicate that ultracool dwarfs can sustain large $L_{XUV}$ in the saturated regime for Gyrs, consistent with activity lifetimes of late M dwarfs \\citep{West2008}. Our choice of prior distributions strongly impact our results as our inference hinges on only two measured properties of TRAPPIST-1, $L_{XUV}$ and $L_{bol}$. To mitigate this effect, we consulted previous studies and empirical observations of the activity evolution of late M dwarfs to construct realistic prior distributions.\n\nThe TRAPPIST-1 planets likely experienced significant XUV fluxes during the pre-main sequence, potentially driving extreme atmospheric erosion and water loss \\citep{Bolmont2017,Bourrier2017a}. The high-energy fluxes incident on the inner-most planets throughout this phase were probably large enough for atmospheric mass loss to be recombination-limited ($F_{UV} \\gsim 10^4$ g s$^{-1}$ cm$^{-2}$) and scale as $\\dot{m} \\sim F_{XUV}^{0.6}$ \\citep{MurrayClay2009}, as opposed to the oft-assumed energy-limited escape \\citep[$\\dot{m} \\sim F_{XUV}$,][]{Watson1981,Lammer2003}, potentially inhibiting volatile loss. If the TRAPPIST-1 planets did lose significant amounts of water as our estimates suggest, they must have formed with a large initial volatile inventory to account for their observed low densities \\citep{Grimm2018}.\n\nWe demonstrated that the machine learning Python package, \\approxposterior \\citep{FlemingVanderPlas2018}, can efficiently compute an approximation to the posterior distribution using an adaptive GP-based method, requiring $800\\times$ fewer \\vplanet simulations and a factor of $330\\times$ less core hours than traditional MCMC approaches for this application. The posterior distributions derived by \\approxposterior accurately reproduced the non-trivial parameter correlations and best-fit values uncovered by our fiducial MCMC analysis. The agreement is not perfect, however as \\approxposterior underestimated the magnitude of the uncertainties of two parameters by ${\\sim}30\\%$.  \n\nFinally, we note that our methodology constrains parameters that describe the long-term XUV evolution of the star, conditioned on measurements. In principle, this approach can be extended to obtain evolutionary histories of planetary systems in general.  For example, in Figures~\\ref{fig:evol} and \\ref{fig:fluxes}, we examined the long-term evolution of TRAPPIST-1 and the evolving XUV fluxes received by its planetary system, respectively, with samples drawn from the posterior distribution. Future research can combine those results with additional physical effects, e.g. water loss or tidal dissipation, to build a probabilistic model for the long-term evolution of the planetary system, given our model for the underlying physics, to characterize its present state. While simulating additional physical effects will inevitably increase the computational expense, we have demonstrated that \\approxposterior can enable such efforts and provide insight into the histories of stars and their planets.\n\n% extra\n% Applying these methods to other M dwarfs, however, requires measuring their current $L_{X}$ or $L_{XUV}$, a difficult task given that most M and ultracool dwarfs are faint and that much of the stellar EUV radiation is absorbed by neutral interstellar hydrogen \\citep{Airapetian2019}. These quantities, however, can be reconstructed via empirical scaling relations \\citep[e.g.][]{Linsky2014}. \n% The accuracy and massive reduction in compute time afforded by \\approxposterior enables our analysis to scale to a larger sample of late M dwarfs to constrain their XUV histories.\n\n\n%% ACKNOWLEDGEMENTS %%\n\\acknowledgments\nThis work was facilitated though the use of advanced computational, storage, and networking infrastructure provided by the Hyak supercomputer system and funded by the Student Technology Fund at the University of Washington. DPF was supported by NASA Headquarters under the NASA Earth and Space Science Fellowship Program - Grant 80NSSC17K0482.  This work was supported by the NASA Astrobiology Program Grant Number 80NSSC18K0829 and benefited from participation in the NASA Nexus for Exoplanet Systems Science research coordination network.\n\n%% SOFTWARE %%\n\\software{\\approxposterior: \\citet{FlemingVanderPlas2018}, \\texttt{corner}: \\citet{ForemanMackey2016}, \\texttt{emcee}: \\citet{ForemanMackey2013}, \\vplanet: \\citet{Barnes2019}} \n\n%% BIBLIOGRAPHY %%\n\n\\begin{thebibliography}{}\n\\expandafter\\ifx\\csname natexlab\\endcsname\\relax\\def\\natexlab#1{#1}\\fi\n\\providecommand{\\url}[1]{\\href{#1}{#1}}\n\n\\bibitem[{{Baraffe} {et~al.}(2015){Baraffe}, {Homeier}, {Allard}, \\&\n  {Chabrier}}]{Baraffe2015}\n{Baraffe}, I., {Homeier}, D., {Allard}, F., \\& {Chabrier}, G. 2015, \\aap, 577,\n  A42\n\n\\bibitem[{{Barclay} {et~al.}(2018){Barclay}, {Pepper}, \\&\n  {Quintana}}]{Barclay2018}\n{Barclay}, T., {Pepper}, J., \\& {Quintana}, E.~V. 2018, \\apjs, 239, 2\n\n\\bibitem[{{Barnes} {et~al.}(2014){Barnes}, {Jenkins}, {Jones}, {Jeffers},\n  {Rojo}, {Arriagada}, {Jord{\\'a}n}, {Minniti}, {Tuomi}, {Pinfield}, \\&\n  {Anglada-Escud{\\'e}}}]{Barnes2014}\n{Barnes}, J.~R., {Jenkins}, J.~S., {Jones}, H.~R.~A., {et~al.} 2014, \\mnras,\n  439, 3094\n\n\\bibitem[{{Barnes} {et~al.}(2019){Barnes}, {Luger}, {Deitrick}, {Driscoll},\n  {Quinn}, {Fleming}, {Smotherman}, {McDonald}, {Wilhelm}, {Garcia}, {Barth},\n  {Guyer}, {Meadows}, {Bitz}, {Gupta}, {Domagal-Goldman}, \\&\n  {Armstrong}}]{Barnes2019}\n{Barnes}, R., {Luger}, R., {Deitrick}, R., {et~al.} 2019, arXiv e-prints,\n  arXiv:1905.06367\n\n\\bibitem[{{Bird} {et~al.}(2019){Bird}, {Rogers}, {Peiris}, {Verde},\n  {Font-Ribera}, \\& {Pontzen}}]{Bird2019}\n{Bird}, S., {Rogers}, K.~K., {Peiris}, H.~V., {et~al.} 2019, \\jcap, 2, 050\n\n\\bibitem[{{Bolmont} {et~al.}(2017){Bolmont}, {Gallet}, {Mathis}, {Charbonnel},\n  {Amard}, \\& {Alibert}}]{Bolmont2017}\n{Bolmont}, E., {Gallet}, F., {Mathis}, S., {et~al.} 2017, \\aap, 604, A113\n\n\\bibitem[{{Bourrier} {et~al.}(2017{\\natexlab{a}}){Bourrier}, {Ehrenreich},\n  {Wheatley}, {Bolmont}, {Gillon}, {de Wit}, {Burgasser}, {Jehin}, {Queloz}, \\&\n  {Triaud}}]{Bourrier2017b}\n{Bourrier}, V., {Ehrenreich}, D., {Wheatley}, P.~J., {et~al.}\n  2017{\\natexlab{a}}, \\aap, 599, L3\n\n\\bibitem[{{Bourrier} {et~al.}(2017{\\natexlab{b}}){Bourrier}, {de Wit},\n  {Bolmont}, {Stamenkovi{\\'c}}, {Wheatley}, {Burgasser}, {Delrez}, {Demory},\n  {Ehrenreich}, {Gillon}, {Jehin}, {Leconte}, {Lederer}, {Lewis}, {Triaud}, \\&\n  {Van Grootel}}]{Bourrier2017a}\n{Bourrier}, V., {de Wit}, J., {Bolmont}, E., {et~al.} 2017{\\natexlab{b}}, \\aj,\n  154, 121\n\n\\bibitem[{{Burgasser} \\& {Mamajek}(2017)}]{Burgasser2017}\n{Burgasser}, A.~J., \\& {Mamajek}, E.~E. 2017, \\apj, 845, 110\n\n\\bibitem[{{Chadney} {et~al.}(2015){Chadney}, {Galand}, {Unruh}, {Koskinen}, \\&\n  {Sanz-Forcada}}]{Chadney2015}\n{Chadney}, J.~M., {Galand}, M., {Unruh}, Y.~C., {Koskinen}, T.~T., \\&\n  {Sanz-Forcada}, J. 2015, \\icarus, 250, 357\n\n\\bibitem[{Delfosse {et~al.}(1998)Delfosse, Forveille, Perrier, \\&\n  Mayor}]{Delfosse1998}\nDelfosse, X., Forveille, T., Perrier, C., \\& Mayor, M. 1998, Astronomy and\n  Astrophysics, 331, 581\n\n\\bibitem[{{Delrez} {et~al.}(2018){Delrez}, {Gillon}, {Triaud}, {Demory}, {de\n  Wit}, {Ingalls}, {Agol}, {Bolmont}, {Burdanov}, {Burgasser}, {Carey},\n  {Jehin}, {Leconte}, {Lederer}, {Queloz}, {Selsis}, \\& {Van\n  Grootel}}]{Delrez2018}\n{Delrez}, L., {Gillon}, M., {Triaud}, A.~H.~M.~J., {et~al.} 2018, \\mnras, 475,\n  3577\n\n\\bibitem[{{Dressing} \\& {Charbonneau}(2015)}]{Dressing2015}\n{Dressing}, C.~D., \\& {Charbonneau}, D. 2015, \\apj, 807, 45\n\n\\bibitem[{{Fleming} \\& {VanderPlas}(2018)}]{FlemingVanderPlas2018}\n{Fleming}, D.~P., \\& {VanderPlas}, J. 2018, The Journal of Open Source\n  Software, 3, 781\n\n\\bibitem[{{Foreman-Mackey}(2016)}]{ForemanMackey2016}\n{Foreman-Mackey}, D. 2016, The Journal of Open Source Software, 1,\n  doi:10.21105/joss.00024\n\n\\bibitem[{{Foreman-Mackey} {et~al.}(2013){Foreman-Mackey}, {Hogg}, {Lang}, \\&\n  {Goodman}}]{ForemanMackey2013}\n{Foreman-Mackey}, D., {Hogg}, D.~W., {Lang}, D., \\& {Goodman}, J. 2013, \\pasp,\n  125, 306\n\n\\bibitem[{{Gillon} {et~al.}(2016){Gillon}, {Jehin}, {Lederer}, {Delrez}, {de\n  Wit}, {Burdanov}, {Van Grootel}, {Burgasser}, {Triaud}, {Opitom}, {Demory},\n  {Sahu}, {Bardalez Gagliuffi}, {Magain}, \\& {Queloz}}]{Gillon2016}\n{Gillon}, M., {Jehin}, E., {Lederer}, S.~M., {et~al.} 2016, \\nat, 533, 221\n\n\\bibitem[{{Gillon} {et~al.}(2017){Gillon}, {Triaud}, {Demory}, {Jehin}, {Agol},\n  {Deck}, {Lederer}, {de Wit}, {Burdanov}, {Ingalls}, {Bolmont}, {Leconte},\n  {Raymond}, {Selsis}, {Turbet}, {Barkaoui}, {Burgasser}, {Burleigh}, {Carey},\n  {Chaushev}, {Copperwheat}, {Delrez}, {Fernandes}, {Holdsworth}, {Kotze}, {Van\n  Grootel}, {Almleaky}, {Benkhaldoun}, {Magain}, \\& {Queloz}}]{Gillon2017}\n{Gillon}, M., {Triaud}, A.~H.~M.~J., {Demory}, B.-O., {et~al.} 2017, \\nat, 542,\n  456\n\n\\bibitem[{{Grimm} {et~al.}(2018){Grimm}, {Demory}, {Gillon}, {Dorn}, {Agol},\n  {Burdanov}, {Delrez}, {Sestovic}, {Triaud}, {Turbet}, {Bolmont}, {Caldas},\n  {de Wit}, {Jehin}, {Leconte}, {Raymond}, {Van Grootel}, {Burgasser}, {Carey},\n  {Fabrycky}, {Heng}, {Hernandez}, {Ingalls}, {Lederer}, {Selsis}, \\&\n  {Queloz}}]{Grimm2018}\n{Grimm}, S.~L., {Demory}, B.-O., {Gillon}, M., {et~al.} 2018, \\aap, 613, A68\n\n\\bibitem[{{Jackson} {et~al.}(2012){Jackson}, {Davis}, \\&\n  {Wheatley}}]{Jackson2012}\n{Jackson}, A.~P., {Davis}, T.~A., \\& {Wheatley}, P.~J. 2012, \\mnras, 422, 2024\n\n\\bibitem[{Kandasamy {et~al.}(2015)Kandasamy, Schneider, \\&\n  Poczos}]{Kandasamy2015}\nKandasamy, K., Schneider, J., \\& Poczos, B. 2015, in {International Joint\n  Conference on Artificial Intelligence}\n\n\\bibitem[{{Lammer} {et~al.}(2003){Lammer}, {Selsis}, {Ribas}, {Guinan},\n  {Bauer}, \\& {Weiss}}]{Lammer2003}\n{Lammer}, H., {Selsis}, F., {Ribas}, I., {et~al.} 2003, \\apjl, 598, L121\n\n\\bibitem[{{Lincowski} {et~al.}(2018){Lincowski}, {Meadows}, {Crisp},\n  {Robinson}, {Luger}, {Lustig-Yaeger}, \\& {Arney}}]{Lincowski2018}\n{Lincowski}, A.~P., {Meadows}, V.~S., {Crisp}, D., {et~al.} 2018, \\apj, 867, 76\n\n\\bibitem[{{Luger} \\& {Barnes}(2015)}]{Luger2015}\n{Luger}, R., \\& {Barnes}, R. 2015, Astrobiology, 15, 119\n\n\\bibitem[{{Luger} {et~al.}(2017){Luger}, {Sestovic}, {Kruse}, {Grimm},\n  {Demory}, {Agol}, {Bolmont}, {Fabrycky}, {Fernandes}, {Van Grootel},\n  {Burgasser}, {Gillon}, {Ingalls}, {Jehin}, {Raymond}, {Selsis}, {Triaud},\n  {Barclay}, {Barentsen}, {Howell}, {Delrez}, {de Wit}, {Foreman-Mackey},\n  {Holdsworth}, {Leconte}, {Lederer}, {Turbet}, {Almleaky}, {Benkhaldoun},\n  {Magain}, {Morris}, {Heng}, \\& {Queloz}}]{Luger2017}\n{Luger}, R., {Sestovic}, M., {Kruse}, E., {et~al.} 2017, Nature Astronomy, 1,\n  0129\n\n\\bibitem[{{Lustig-Yaeger} {et~al.}(2019){Lustig-Yaeger}, {Meadows}, \\&\n  {Lincowski}}]{Lustig2019}\n{Lustig-Yaeger}, J., {Meadows}, V.~S., \\& {Lincowski}, A.~P. 2019, arXiv\n  e-prints, arXiv:1905.07070\n\n\\bibitem[{{Morley} {et~al.}(2017){Morley}, {Kreidberg}, {Rustamkulov},\n  {Robinson}, \\& {Fortney}}]{Morley2017}\n{Morley}, C.~V., {Kreidberg}, L., {Rustamkulov}, Z., {Robinson}, T., \\&\n  {Fortney}, J.~J. 2017, \\apj, 850, 121\n\n\\bibitem[{{Morris} {et~al.}(2018){Morris}, {Agol}, {Davenport}, \\&\n  {Hawley}}]{Morris2018}\n{Morris}, B.~M., {Agol}, E., {Davenport}, J.~R.~A., \\& {Hawley}, S.~L. 2018,\n  \\apj, 857, 39\n\n\\bibitem[{{Murray-Clay} {et~al.}(2009){Murray-Clay}, {Chiang}, \\&\n  {Murray}}]{MurrayClay2009}\n{Murray-Clay}, R.~A., {Chiang}, E.~I., \\& {Murray}, N. 2009, \\apj, 693, 23\n\n\\bibitem[{{Parker}(1955)}]{Parker1955}\n{Parker}, E.~N. 1955, \\apj, 122, 293\n\n\\bibitem[{{Peacock} {et~al.}(2019){Peacock}, {Barman}, {Shkolnik},\n  {Hauschildt}, \\& {Baron}}]{Peacock2019}\n{Peacock}, S., {Barman}, T., {Shkolnik}, E.~L., {Hauschildt}, P.~H., \\&\n  {Baron}, E. 2019, \\apj, 871, 235\n\n\\bibitem[{{Pizzolato} {et~al.}(2003){Pizzolato}, {Maggio}, {Micela},\n  {Sciortino}, \\& {Ventura}}]{Pizzolato2003}\n{Pizzolato}, N., {Maggio}, A., {Micela}, G., {Sciortino}, S., \\& {Ventura}, P.\n  2003, \\aap, 397, 147\n\n\\bibitem[{{Reid} \\& {Hawley}(2005)}]{Reid2005}\n{Reid}, I.~N., \\& {Hawley}, S.~L. 2005, {New light on dark stars : red dwarfs,\n  low-mass stars, brown dwarfs}, doi:10.1007/3-540-27610-6\n\n\\bibitem[{{Ribas} {et~al.}(2005){Ribas}, {Guinan}, {G{\\\"u}del}, \\&\n  {Audard}}]{Ribas2005}\n{Ribas}, I., {Guinan}, E.~F., {G{\\\"u}del}, M., \\& {Audard}, M. 2005, \\apj, 622,\n  680\n\n\\bibitem[{{Roettenbacher} \\& {Kane}(2017)}]{Roettenbacher2017}\n{Roettenbacher}, R.~M., \\& {Kane}, S.~R. 2017, \\apj, 851, 77\n\n\\bibitem[{{Schneider} \\& {Shkolnik}(2018)}]{Schneider2018}\n{Schneider}, A.~C., \\& {Shkolnik}, E.~L. 2018, \\aj, 155, 122\n\n\\bibitem[{{Segura} {et~al.}(2005){Segura}, {Kasting}, {Meadows}, {Cohen},\n  {Scalo}, {Crisp}, {Butler}, \\& {Tinetti}}]{Segura2005}\n{Segura}, A., {Kasting}, J.~F., {Meadows}, V., {et~al.} 2005, Astrobiology, 5,\n  706\n\n\\bibitem[{{Shkolnik} \\& {Barman}(2014)}]{Shkolnik2014}\n{Shkolnik}, E.~L., \\& {Barman}, T.~S. 2014, \\aj, 148, 64\n\n\\bibitem[{{Skumanich}(1972)}]{Skumanich1972}\n{Skumanich}, A. 1972, \\apj, 171, 565\n\n\\bibitem[{{Spada} {et~al.}(2013){Spada}, {Demarque}, {Kim}, \\&\n  {Sills}}]{Spada2013}\n{Spada}, F., {Demarque}, P., {Kim}, Y.-C., \\& {Sills}, A. 2013, \\apj, 776, 87\n\n\\bibitem[{{Vaiana} {et~al.}(1981){Vaiana}, {Cassinelli}, {Fabbiano},\n  {Giacconi}, {Golub}, {Gorenstein}, {Haisch}, {Harnden}, {Johnson}, {Linsky},\n  {Maxson}, {Mewe}, {Rosner}, {Seward}, {Topka}, \\& {Zwaan}}]{Vaiana1981}\n{Vaiana}, G.~S., {Cassinelli}, J.~P., {Fabbiano}, G., {et~al.} 1981, \\apj, 245,\n  163\n\n\\bibitem[{{Van Grootel} {et~al.}(2018){Van Grootel}, {Fernandes}, {Gillon},\n  {Jehin}, {Manfroid}, {Scuflaire}, {Burgasser}, {Barkaoui}, {Benkhaldoun},\n  {Burdanov}, {Delrez}, {Demory}, {de Wit}, {Queloz}, \\&\n  {Triaud}}]{vanGrootel2018}\n{Van Grootel}, V., {Fernandes}, C.~S., {Gillon}, M., {et~al.} 2018, \\apj, 853,\n  30\n\n\\bibitem[{{Wang} \\& {Li}(2017)}]{Wang2017}\n{Wang}, H., \\& {Li}, J. 2017, ArXiv e-prints, arXiv:1703.09930\n\n\\bibitem[{{Watson} {et~al.}(1981){Watson}, {Donahue}, \\& {Walker}}]{Watson1981}\n{Watson}, A.~J., {Donahue}, T.~M., \\& {Walker}, J.~C.~G. 1981, \\icarus, 48, 150\n\n\\bibitem[{{West} {et~al.}(2008){West}, {Hawley}, {Bochanski}, {Covey}, {Reid},\n  {Dhital}, {Hilton}, \\& {Masuda}}]{West2008}\n{West}, A.~A., {Hawley}, S.~L., {Bochanski}, J.~J., {et~al.} 2008, \\aj, 135,\n  785\n\n\\bibitem[{{West} {et~al.}(2015){West}, {Weisenburger}, {Irwin},\n  {Berta-Thompson}, {Charbonneau}, {Dittmann}, \\& {Pineda}}]{West2015}\n{West}, A.~A., {Weisenburger}, K.~L., {Irwin}, J., {et~al.} 2015, \\apj, 812, 3\n\n\\bibitem[{{Wheatley} {et~al.}(2017){Wheatley}, {Louden}, {Bourrier},\n  {Ehrenreich}, \\& {Gillon}}]{Wheatley2017}\n{Wheatley}, P.~J., {Louden}, T., {Bourrier}, V., {Ehrenreich}, D., \\& {Gillon},\n  M. 2017, \\mnras, 465, L74\n\n\\bibitem[{{Wright} \\& {Drake}(2016)}]{Wright2016}\n{Wright}, N.~J., \\& {Drake}, J.~J. 2016, \\nat, 535, 526\n\n\\bibitem[{{Wright} {et~al.}(2011){Wright}, {Drake}, {Mamajek}, \\&\n  {Henry}}]{Wright2011}\n{Wright}, N.~J., {Drake}, J.~J., {Mamajek}, E.~E., \\& {Henry}, G.~W. 2011,\n  \\apj, 743, 48\n\n\\bibitem[{{Wright} {et~al.}(2018){Wright}, {Newton}, {Williams}, {Drake}, \\&\n  {Yadav}}]{Wright2018}\n{Wright}, N.~J., {Newton}, E.~R., {Williams}, P.~K.~G., {Drake}, J.~J., \\&\n  {Yadav}, R.~K. 2018, \\mnras, 479, 2351\n\n\\end{thebibliography}\n\n% End of file\n\\end{document}", "meta": {"hexsha": "09e881aab6ee05f249b572fde168b8a15c4bac5d", "size": 49641, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Paper/Submitted/trappist.tex", "max_stars_repo_name": "dflemin3/trappist", "max_stars_repo_head_hexsha": "1aeb273f49678d685addc540cd4444ff045bc601", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-12T18:51:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-12T18:51:46.000Z", "max_issues_repo_path": "Paper/Submitted/trappist.tex", "max_issues_repo_name": "dflemin3/trappist", "max_issues_repo_head_hexsha": "1aeb273f49678d685addc540cd4444ff045bc601", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Paper/Submitted/trappist.tex", "max_forks_repo_name": "dflemin3/trappist", "max_forks_repo_head_hexsha": "1aeb273f49678d685addc540cd4444ff045bc601", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-08T18:49:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-08T18:49:03.000Z", "avg_line_length": 92.7869158879, "max_line_length": 1881, "alphanum_fraction": 0.7389859189, "num_tokens": 15700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.31808774140079743}}
{"text": "\\vssub\n\\subsubsection{~Rotated grids} \\label{sub:num_space_rotagrid}\n\\opthead{RTD}{\\ws\\ (MetOffice)}{J.-G. Li}\n\n\\noindent\nThe rotated grid is a latitude-longitude (lat-lon) grid and is obtained by\nrotating the North Pole to a new position at latitude $\\phi_{p}$ and\nlongitude $\\lambda_{p}$ in the standard latitude-longitude system.  The new\npole position is chosen so that the model domain of interest may be placed\naround the rotated equatorial area for a evenly-spaced lat-lon mesh. For this\nreason the rotated grid is also known as \\emph{Equatorial grid}. For instance,\nthe North Atlantic and European wave (NAEW) model used in the UK Met Office\nuses a rotated pole at 37.5N, 177.5E so that London, UK\n(\\textasciitilde{}51.5N 0.0E) is almost on the rotated equator. This rotated\ngrid allows a much more evenly spaced lat-lon mesh in the NAEW domain than the\nstandard lat-lon grid in the same area. \n\nIn \\ws\\, the rotated grid is implemented with minimum changes to the original\nlat-lon grid. In fact, the rotated grid is treated just like the standard \nlat-lon grid inside the model. To set up and run a rotated grid model configuration,\nusers should choose the regular lat-lon grid along with the {\\code RTD} switch.\nThe rotated pole position is set using the {\\code PLAT} and {\\code PLON} variables in the\n{\\bf ww3\\_grid.inp} namelist {\\code ROTD}. Model input files, like wind, current and ice files \nshould be mapped on to the rotated grid. For convenience of nesting in standard \nlat-lon grid frameworks, boundary conditions provided to and output from the \nrotated grid use spectra referenced to a standard grid north and standard lat-lon\ngrid points values, which are converted into rotated grid lat-lon inside \\ws\\.\nThe list of 2D spectral output locations in {\\bf ww3\\_shel.inp} are also specified in \nstandard lat-lon. \n\nModel directional and x-y vector outputs can be converted to a standard grid\nnorth reference by setting the UNROT variable in the {\\bf ww3\\_grid.inp} namelist\nROTD to True. With this set, for point outputs lat-lon locations all directional\nvalues such as wind direction, current direction and 2D spectra are converted\ninto standard lat-lon orientation. Functions to de-rotate gridded\nfields are applied in {\\bf ww3\\_ounf}, {\\bf ww3\\_outf} and {\\bf ww3\\_grib}. \nWhen running {\\bf ww3\\_ounf} and {\\bf ww3\\_ounp}, the resulting netCDF\nfiles will include a variable attribute direction\\_reference, which describes\nwhether a standard (True North) or rotated grid directional reference frame\nhas been used. Gridded netCDF files generated by {\\bf ww3\\_ounf} also include\n\\emph{standard\\_latitude} and \\emph{standard\\_longitude} two-dimensional arrays\nthat describe location of the rotated model cell centres in the standard lat-lon\nreference frame. \n\nSix subroutines are provided in module {\\bf w3servmd.ftn} for rotated grid\nconversion:\n\\begin{vlist}\n\\vit{w3spectn}{}{Turns wave spectrum anti-clockwise by AnglD}\n\\vit{w3acturn}{}{Turns wave action(k,nth) anti-clockwise by AnglD}\n\\vit{w3thrtn}{}{Turns direction parameters anti-clockwise by AnglD}\n\\vit{w3xyrtn}{}{Turns x-y vector parameters anti-clockwise by AnglD}\n\\vit{w3lltoeq}{}{Convert standard into rotated lat/lon plus AnglD}\n\\vit{w3eqtoll}{}{Reverse of w3lltoeq, but AnglD unchanged}\n\\end{vlist}\nThese subroutines are self-contained and can be extracted outside the model\nfor pre- or post-processing of rotated grid files.  Some conversion tools have\nbeen developed based on these subroutines but have not been included in \\ws\\\nyet. Refer to the regression test \\emph{regtests/ww3\\_tp2.11} for an example\nof a rotated grid model (NAEW).  Users may find more information in\n\\emph{smc\\_docs/Rotated\\_Grid.pdf} or contact Jian-Guo Li for help\n(\\url{Jian-Guo.Li@metoffice.gov.uk}).\n", "meta": {"hexsha": "60b58ef6d2e9594cfd2bba6b8b8d47685acad7b2", "size": 3766, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "WW3/manual/num/rotagrid.tex", "max_stars_repo_name": "pvelissariou1/ADC-WW3-NWM-SCHISM-NEMS", "max_stars_repo_head_hexsha": "707ddcd84417211e3a7c92aa15d8cd8ddfa080ab", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WW3/manual/num/rotagrid.tex", "max_issues_repo_name": "pvelissariou1/ADC-WW3-NWM-SCHISM-NEMS", "max_issues_repo_head_hexsha": "707ddcd84417211e3a7c92aa15d8cd8ddfa080ab", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-05-31T15:49:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-04T14:17:45.000Z", "max_forks_repo_path": "WW3/manual/num/rotagrid.tex", "max_forks_repo_name": "pvelissariou1/ADC-WW3-NWM-SCHISM-NEMS", "max_forks_repo_head_hexsha": "707ddcd84417211e3a7c92aa15d8cd8ddfa080ab", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-01T09:29:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T09:29:46.000Z", "avg_line_length": 60.7419354839, "max_line_length": 95, "alphanum_fraction": 0.7830589485, "num_tokens": 1019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.3180877333179505}}
{"text": "\\chapter{The unwind Library}\n\nThis document describes the facilities provided by the \\ml{unwind} library\nfor the HOL system~\\cite{description}. The library provides conversions and\nrules for unfolding, unwinding and pruning device implementations (logical\nrepresentations of hardware). For a detailed description of these techniques,\nsee~\\cite{HVusingHOL}.\n\nMost of the functions fall into one of five groups. The first group consists\nof conversions and inference rules for moving universal quantifiers up and\ndown through conjunctions; they have names beginning with either\n\\ml{CONJ\\_FORALL} or \\ml{FORALL\\_CONJ}. The second group of functions are for\nunfolding, that is expanding sub-components using their definitions. The names\nof these begin with \\ml{UNFOLD}. The functions in the third group perform\nunwinding and have names beginning with \\ml{UNWIND}. The fourth group of\nfunctions prune internal lines that have been unwound. Their names begin with\n\\ml{PRUNE}. The final group of functions combine unfolding, unwinding and\npruning. They have names beginning with \\ml{EXPAND}.\n\nI have tried to make the behaviour of the functions uniform. The conversions\napply to the smallest term possible, to provide maximum flexibility. The\ninference rules, on the other hand, are designed to apply to the definition\nof a hardware component. They expect to be given a theorem of the form:\n\n\\begin{small}\\begin{verbatim}\n   |- !x1 ... xn. DEVICE (x1,...,xn) = ?l1 ... lm. t1 /\\ ... /\\ tp\n\\end{verbatim}\\end{small}\n\n\n\\section{Using the library}\n\nThe \\ml{unwind} library can be loaded into a \\HOL\\ session using the function\n\\ml{load\\_library}\\index{load\\_library@{\\ptt load\\_library}} (see the \\HOL\\\nmanual for a general description of library loading). The first action in the\nload sequence initiated by \\ml{load\\_library} is to update the \\HOL\\\nhelp\\index{help!updating search path} search path. The help search path is\nupdated with a pathname to online help files for the \\ML\\ functions in the\nlibrary. After updating the help search path, the \\ML\\ functions in the\nlibrary are loaded into \\HOL.\n\nThe following session shows how the \\ml{unwind} library may be loaded using\n\\ml{load\\_library}:\n\n\\setcounter{sessioncount}{1}\n\\begin{session}\\begin{verbatim}\n#load_library `unwind`;;\nLoading library `unwind` ...\nUpdating help search path\n..................................\nLibrary `unwind` loaded.\n() : void\n\\end{verbatim}\\end{session}\n\nWe now illustrate the use of the library on the parity-checker example.\nFirstly, we begin a new theory:\n\n\\begin{session}\\begin{verbatim}\n#new_theory `PARITY`;;\n() : void\n\\end{verbatim}\\end{session}\n\n\\vfill\n\n\\noindent\nWe define the sub-components used:\n\n\\vfill\n\n\\begin{session}\\begin{verbatim}\n#let ONE_DEF =\n# new_definition\n#  (`ONE_DEF`, \"ONE(out:num->bool) = !t. out t = T\");;\nONE_DEF = |- !out. ONE out = (!t. out t = T)\n\\end{verbatim}\\end{session}\n\n\\vfill\n\n\\begin{session}\\begin{verbatim}\n#let NOT_DEF =\n# new_definition\n#  (`NOT_DEF`, \"NOT(in,out:num->bool) = !t. out t = ~(in t)\");;\nNOT_DEF = |- !in out. NOT(in,out) = (!t. out t = ~in t)\n\\end{verbatim}\\end{session}\n\n\\vfill\n\n\\begin{session}\\begin{verbatim}\n#let MUX_DEF =\n# new_definition\n#  (`MUX_DEF`,\n#   \"MUX(sw,in1,in2,out:num->bool) =\n#     !t. out t = (sw t => in1 t | in2 t)\");;\nMUX_DEF = \n|- !sw in1 in2 out.\n    MUX(sw,in1,in2,out) = (!t. out t = (sw t => in1 t | in2 t))\n\\end{verbatim}\\end{session}\n\n\\vfill\n\n\\begin{session}\\begin{verbatim}\n#let REG_DEF =\n# new_definition\n# (`REG_DEF`, \"REG(in,out:num->bool) =\n#              !t. out t = ((t=0) => F | in(t-1))\");;\nREG_DEF = \n|- !in out. REG(in,out) = (!t. out t = ((t = 0) => F | in(t - 1)))\n\\end{verbatim}\\end{session}\n\n\\vfill\n\n\\noindent\nNow we define the parity-checker implementation:\n\n\\begin{session}\\begin{verbatim}\n#let PARITY_IMP_DEF =\n# new_definition\n#  (`PARITY_IMP_DEF`,\n#   \"PARITY_IMP(in,out) =\n#    ?l1 l2 l3 l4 l5.\n#     NOT(l2,l1) /\\ MUX(in,l1,l2,l3) /\\ REG(out,l2) /\\\n#     ONE l4     /\\ REG(l4,l5)       /\\ MUX(l5,l3,l4,out)\");;\nPARITY_IMP_DEF = \n|- !in out.\n    PARITY_IMP(in,out) =\n    (?l1 l2 l3 l4 l5.\n      NOT(l2,l1) /\\\n      MUX(in,l1,l2,l3) /\\\n      REG(out,l2) /\\\n      ONE l4 /\\\n      REG(l4,l5) /\\\n      MUX(l5,l3,l4,out))\n\\end{verbatim}\\end{session}\n\n\\noindent\nThe function \\ml{EXPAND\\_AUTO\\_RIGHT\\_RULE} can be used to unfold, unwind and\nprune the body of this definition:\n\n\\begin{session}\\begin{verbatim}\n#EXPAND_AUTO_RIGHT_RULE [ONE_DEF;NOT_DEF;MUX_DEF;REG_DEF] PARITY_IMP_DEF;;\n|- !in out.\n    PARITY_IMP(in,out) =\n    (!t.\n      out t =\n      (((t = 0) => F | T) => \n       (in t => \n        ~((t = 0) => F | out(t - 1)) | \n        ((t = 0) => F | out(t - 1))) | \n       T))\n\\end{verbatim}\\end{session}\n\n\n\\section{Automatic unwinding}\n\n\\def\\putbox(#1,#2){\\put(#1,#2){\\framebox(2,2){}}}\n\nHardware implementations often contain feedbacks. This presents a problem\nwhen trying to unwind and prune the internal lines in the logical\nrepresentation. The mutual dependencies between lines can cause a brute-force\nunwind to loop indefinitely. To avoid this one has to be selective about\nwhich lines to unwind. The tools in the \\ml{unwind} library allow the user\nto be selective in this way. However, it is possible for the machine itself to\nbe selective. The function \\ml{UNWIND\\_AUTO\\_CONV} attempts to analyze the\ndependencies between lines and unwind as far as possible without looping.\n\nConsider the following term which arises in the parity-checker example:\n\n\\begin{small}\\begin{verbatim}\n   \"?l1 l2 l3 l4 l5.\n     (!t. l1 (t:num) = ~l2 t) /\\\n     (!t. l3 t = (in t => l1 t | l2 t)) /\\\n     (!t. l2 t = ((t = 0) => F | out (t - 1))) /\\\n     (!t. l4 t = T) /\\\n     (!t. l5 t = ((t = 0) => F | l4 (t - 1))) /\\\n     (!t. out t = (l5 t => l3 t | l4 t))\"\n\\end{verbatim}\\end{small}\n\n\\noindent\nWe can represent the dependencies of the lines using a directed graph:\n\n{\\setlength{\\unitlength}{4mm}\n\\begin{center}\n\\begin{picture}(14,10)(0,0)\n\\put(0,2){\\makebox(2,2){\\small{\\tt l2}}}\n\\put(4,2){\\makebox(2,2){\\small{\\tt l1}}}\n\\put(8,4){\\makebox(2,2){\\small{\\tt l3}}}\n\\put(12,6){\\makebox(2,2){\\small{\\tt out}}}\n\\put(2,8){\\makebox(2,2){\\small{\\tt l4}}}\n\\put(6,8){\\makebox(2,2){\\small{\\tt l5}}}\n\n\\put(2,3){\\vector(1,0){2}}\n\\put(2,3){\\vector(3,1){6}}\n\\put(6,3){\\vector(1,1){2}}\n\\put(10,5){\\vector(1,1){2}}\n\\put(4,9){\\vector(1,0){2}}\n\\put(4,9){\\vector(4,-1){8}}\n\\put(8,9){\\vector(2,-1){4}}\n\n\\put(13,6){\\line(0,-1){6}}\n\\put(13,0){\\line(-1,0){12}}\n\\put(1,0){\\vector(0,1){2}}\n\\end{picture}\n\\end{center}}\n\n\\noindent\nwhich can in turn be represented by the following list:\n\n\\begin{small}\\begin{verbatim}\n   l1, [l2]\n   l3, [l1;l2]\n   l2, [out]\n   l4, []\n   l5, [l4]\n   out,[l5;l3;l4]\n\\end{verbatim}\\end{small}\n\nSince we wish to eliminate the internal lines, we want to be left with a\nrecursive equation for {\\small\\verb%out%} in terms of itself. We can do this\nbe `breaking the loop' at {\\small\\verb%out%}, giving the following structure:\n\n\\begin{small}\\begin{verbatim}\n   l1, [l2]\n   l3, [l1;l2]\n   l2, []\n   l4, []\n   l5, [l4]\n\\end{verbatim}\\end{small}\n\n\\noindent\nNote that {\\small\\verb%out%} has been removed from the structure. From the\ngraph we can see that {\\small\\verb%l2%} and {\\small\\verb%l4%} do not depend\non any internal lines. They can therefore be used to unwind without any risk\nof looping. They can be recognized in the datastructure by the fact that their\ncorresponding dependency lists are empty.\n\nOnce we have unwound with {\\small\\verb%l2%} and {\\small\\verb%l4%} they can be\nremoved from the datastructure:\n\n\\begin{small}\\begin{verbatim}\n   l1, []\n   l3, [l1]\n   l5, []\n\\end{verbatim}\\end{small}\n\n\\noindent\nWe now see that {\\small\\verb%l1%} and {\\small\\verb%l5%} can be unwound to give:\n\n\\begin{small}\\begin{verbatim}\n   l3, []\n\\end{verbatim}\\end{small}\n\n\\noindent\nUnwinding {\\small\\verb%l3%} then leaves us with the required recursive\nequation for {\\small\\verb%out%}.\n\nThe problem with the approach just described is that it only unwinds fully if\nthere is at most one loop in the circuit, and the output is in that loop. We\ncan be a bit more general. Consider the circuit:\n\n\\vfill\n\n{\\setlength{\\unitlength}{4mm}\n\\begin{center}\n\\begin{picture}(4,18)(0,0)\n\\put(1,0){\\makebox(2,2){\\small{\\tt out}}}\n\\putbox(1,4)\n\\put(0,6){\\makebox(2,2){\\small{\\tt l2}}}\n\\putbox(1,8)\n\\put(0,10){\\makebox(2,2){\\small{\\tt l1}}}\n\\putbox(1,12)\n\\put(1,16){\\makebox(2,2){\\small{\\tt in}}}\n\n\\put(2,16){\\vector(0,-1){2}}\n\\put(2,12){\\vector(0,-1){2}}\n\\put(2,8){\\vector(0,-1){2}}\n\\put(2,4){\\vector(0,-1){2}}\n\n\\put(2,7){\\circle*{0.2}}\n\\put(2,7){\\line(1,0){2}}\n\\put(4,7){\\line(0,1){8}}\n\\put(4,15){\\line(-1,0){1}}\n\\put(3,15){\\vector(0,-1){1}}\n\\end{picture}\n\\end{center}}\n\n\\vfill\n\n\\noindent\nrepresented by the graph:\n\n\\vfill\n\n\\begin{small}\\begin{verbatim}\n   l1, [l2]\n   l2, [l1]\n   out,[l2]\n\\end{verbatim}\\end{small}\n\n\\vfill\n\n\\noindent\nThere are no lines with an empty dependency list, and eliminating\n{\\small\\verb%out%} will not help because it is not in the loop. However, if we\nbreak the loop at {\\small\\verb%l2%} we can unwind {\\small\\verb%l1%}. This will\nleave us with a recursive equation for {\\small\\verb%l2%} and an equation for\n{\\small\\verb%out%} in terms of {\\small\\verb%l2%}. This is the best that we can\ndo, and it is now up to the user to deal with the recursive equation.\n\nNow let's consider an example with more than one loop:\n\n{\\setlength{\\unitlength}{4mm}\n\\begin{center}\n\\begin{picture}(12,30)(0,0)\n\\put(1,0){\\makebox(2,2){\\small{\\tt out}}}\n\\putbox(1,4)\n\\put(0,6){\\makebox(2,2){\\small{\\tt l5}}}\n\\putbox(1,8)\n\\put(0,10){\\makebox(2,2){\\small{\\tt l4}}}\n\\putbox(1,12)\n\\put(0,14){\\makebox(2,2){\\small{\\tt l3}}}\n\\putbox(1,16)\n\\putbox(5,16)\n\\put(0,18){\\makebox(2,2){\\small{\\tt l2}}}\n\\put(6,18){\\makebox(2,2){\\small{\\tt l6}}}\n\\putbox(1,20)\n\\putbox(9,20)\n\\put(0,22){\\makebox(2,2){\\small{\\tt l1}}}\n\\put(10,22){\\makebox(2,2){\\small{\\tt l7}}}\n\\putbox(1,24)\n\\put(1,28){\\makebox(2,2){\\small{\\tt in}}}\n\n\\put(2,28){\\vector(0,-1){2}}\n\\put(2,24){\\vector(0,-1){2}}\n\\put(2,20){\\vector(0,-1){2}}\n\\put(2,16){\\vector(0,-1){2}}\n\\put(2,12){\\vector(0,-1){2}}\n\\put(2,8){\\vector(0,-1){2}}\n\\put(2,4){\\vector(0,-1){2}}\n\n\\put(2,11){\\circle*{0.2}}\n\\put(2,11){\\line(1,0){4}}\n\\put(6,11){\\vector(0,1){5}}\n\\put(6,18){\\line(0,1){1}}\n\\put(6,19){\\line(-1,0){3}}\n\\put(3,19){\\vector(0,-1){1}}\n\\put(2,7){\\circle*{0.2}}\n\\put(2,7){\\line(1,0){8}}\n\\put(10,7){\\vector(0,1){13}}\n\\put(10,22){\\line(0,1){1}}\n\\put(10,23){\\line(-1,0){7}}\n\\put(3,23){\\vector(0,-1){1}}\n\\end{picture}\n\\end{center}}\n\n\\noindent\nWe could unwind {\\small\\verb%l1%} but then we would get stuck. If we break at\n{\\small\\verb%l2%} or {\\small\\verb%l7%} we will still get stuck because of the\ninner loop. If we break at {\\small\\verb%l5%} we can unwind {\\small\\verb%l7%},\nbut then get stuck. If we break at {\\small\\verb%l6%} we get stuck because of\nthe outer loop. However, if we break at {\\small\\verb%l3%} or {\\small\\verb%l4%}\nboth loops are broken and we can unwind fully to leave a recursive equation\nfor either {\\small\\verb%l3%} or {\\small\\verb%l4%} and an equation for\n{\\small\\verb%out%} in terms of that line. So, the choice of where to break a\nloop may determine how far the unwinding can go.\n\n\\ml{UNWIND\\_AUTO\\_CONV} attempts to break every loop in the circuit using the\nminimum number of breaks, so that there are as few equations left as possible.\nThe function also gives priority to non-internal lines when determining where\nto break, so that if possible the recursive equations are in terms of these\nlines.\n\nThe algorithm used determines from the term a list of line variables. Each\nline variable has a right-hand side of an equation associated with it. The\nfree variables in each right-hand side are computed and those that are also\nline variables are placed in the dependency list for the corresponding line.\nFrom the dependency structure, the loops are determined. Lines are then\neliminated so that all loops are broken.\n\nA study of the following circuit reveals why {\\em all\\/} loops have to be\nbroken. If not all loops are broken, then a remaining loop can make the\nbreaking of other loops fruitless.\n\n{\\setlength{\\unitlength}{4mm}\n\\begin{center}\n\\begin{picture}(12,30)(0,0)\n\\put(1,0){\\makebox(2,2){\\small{\\tt out}}}\n\\putbox(1,4)\n\\put(0,6){\\makebox(2,2){\\small{\\tt l5}}}\n\\putbox(1,8)\n\\put(0,10){\\makebox(2,2){\\small{\\tt l4}}}\n\\putbox(1,12)\n\\putbox(9,12)\n\\put(0,14){\\makebox(2,2){\\small{\\tt l3}}}\n\\put(10,14){\\makebox(2,2){\\small{\\tt l7}}}\n\\putbox(1,16)\n\\putbox(5,16)\n\\put(0,18){\\makebox(2,2){\\small{\\tt l2}}}\n\\put(6,18){\\makebox(2,2){\\small{\\tt l6}}}\n\\putbox(1,20)\n\\put(0,22){\\makebox(2,2){\\small{\\tt l1}}}\n\\putbox(1,24)\n\\put(1,28){\\makebox(2,2){\\small{\\tt in}}}\n\n\\put(2,28){\\vector(0,-1){2}}\n\\put(2,24){\\vector(0,-1){2}}\n\\put(2,20){\\vector(0,-1){2}}\n\\put(2,16){\\vector(0,-1){2}}\n\\put(2,12){\\vector(0,-1){2}}\n\\put(2,8){\\vector(0,-1){2}}\n\\put(2,4){\\vector(0,-1){2}}\n\n\\put(2,11){\\circle*{0.2}}\n\\put(2,11){\\line(1,0){4}}\n\\put(6,11){\\vector(0,1){5}}\n\\put(6,18){\\line(0,1){1}}\n\\put(6,19){\\line(-1,0){3}}\n\\put(3,19){\\vector(0,-1){1}}\n\\put(2,7){\\circle*{0.2}}\n\\put(2,7){\\line(1,0){8}}\n\\put(10,7){\\vector(0,1){5}}\n\\put(10,14){\\line(0,1){1}}\n\\put(10,15){\\line(-1,0){7}}\n\\put(3,15){\\vector(0,-1){1}}\n\\end{picture}\n\\end{center}}\n\n\\noindent\nThe dependency structure for the circuit is:\n\n\\begin{small}\\begin{verbatim}\n   l1, []\n   l2, [l1]\n   l3, [l2;l6]\n   l4, [l3;l7]\n   l5, [l4]\n   l6, [l4]\n   l7, [l5]\n   out,[l5]\n\\end{verbatim}\\end{small}\n\n\\noindent\nThe loops for the circuit are:\n\n\\begin{small}\\begin{verbatim}\n   [l3;l4;l6]\n   [l4;l5;l7]\n\\end{verbatim}\\end{small}\n\n\\noindent\nBoth loops can be broken by eliminating {\\small\\verb%l4%}:\n\n\\begin{small}\\begin{verbatim}\n   l1, []\n   l2, [l1]\n   l3, [l2;l6]\n   l5, []\n   l6, []\n   l7, [l5]\n   out,[l5]\n\\end{verbatim}\\end{small}\n\n\\noindent\nWe can now unwind {\\small\\verb%l1%}, {\\small\\verb%l5%} and {\\small\\verb%l6%}:\n\n\\begin{small}\\begin{verbatim}\n   l2, []\n   l3, [l2]\n   l7, []\n   out,[]\n\\end{verbatim}\\end{small}\n\n\\noindent\nand then unwind {\\small\\verb%l2%}, {\\small\\verb%l7%} and {\\small\\verb%out%},\nfollowed by unwinding with {\\small\\verb%l3%} to yield a recursive equation for\n{\\small\\verb%l4%} and all other equations in terms of {\\small\\verb%l4%}. All\nthe internal lines except for {\\small\\verb%l4%} can be pruned. This leaves\nequations for {\\small\\verb%l4%} and {\\small\\verb%out%} only.\n\nThe technique does not always yield a single recursive equation. Mutual\nrecursion is also possible. This is illustrated by the following example:\n\n{\\setlength{\\unitlength}{4mm}\n\\begin{center}\n\\begin{picture}(10,30)(0,0)\n\\put(1,0){\\makebox(2,2){\\small{\\tt out}}}\n\\putbox(1,4)\n\\put(0,6){\\makebox(2,2){\\small{\\tt l5}}}\n\\putbox(1,8)\n\\put(0,10){\\makebox(2,2){\\small{\\tt l4}}}\n\\putbox(1,12)\n\\putbox(5,10)\n\\put(0,14){\\makebox(2,2){\\small{\\tt l3}}}\n\\put(6,12){\\makebox(2,2){\\small{\\tt l7}}}\n\\putbox(1,16)\n\\put(0,18){\\makebox(2,2){\\small{\\tt l2}}}\n\\putbox(1,20)\n\\putbox(5,18)\n\\put(0,22){\\makebox(2,2){\\small{\\tt l1}}}\n\\put(6,20){\\makebox(2,2){\\small{\\tt l6}}}\n\\putbox(1,24)\n\\put(1,28){\\makebox(2,2){\\small{\\tt in}}}\n\n\\put(2,28){\\vector(0,-1){2}}\n\\put(2,24){\\vector(0,-1){2}}\n\\put(2,20){\\vector(0,-1){2}}\n\\put(2,16){\\vector(0,-1){2}}\n\\put(2,12){\\vector(0,-1){2}}\n\\put(2,8){\\vector(0,-1){2}}\n\\put(2,4){\\vector(0,-1){2}}\n\n\\put(2,15){\\circle*{0.2}}\n\\put(2,15){\\line(1,0){4}}\n\\put(6,15){\\vector(0,1){3}}\n\\put(6,20){\\line(0,1){2}}\n\\put(6,22){\\vector(-1,0){3}}\n\\put(2,7){\\circle*{0.2}}\n\\put(2,7){\\line(1,0){4}}\n\\put(6,7){\\vector(0,1){3}}\n\\put(6,12){\\line(0,1){2}}\n\\put(6,14){\\vector(-1,0){3}}\n\\put(6,7){\\circle*{0.2}}\n\\put(6,7){\\line(1,0){4}}\n\\put(10,7){\\line(0,1){16}}\n\\put(10,23){\\line(-1,0){7}}\n\\put(3,23){\\vector(0,-1){1}}\n\\end{picture}\n\\end{center}}\n\nThere are three loops, but breaking at {\\small\\verb%l2%} and {\\small\\verb%l4%}\nis sufficient to break all the loops. The result is three equations: an\nequation for {\\small\\verb%l2%} in terms of itself and {\\small\\verb%l4%}, an\nequation for {\\small\\verb%l4%} in terms of itself and {\\small\\verb%l2%}, and\nan equation for {\\small\\verb%out%} in terms of {\\small\\verb%l4%}. So, it can\nbe seen that the loop analysis technique used by \\ml{UNWIND\\_AUTO\\_CONV} does\nnot eliminate loops; it simply `shrinks' them.\n", "meta": {"hexsha": "76eb65c5583a6e25f03036e0f60772b6ff92d3b0", "size": 16074, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/unwind/Manual/description.tex", "max_stars_repo_name": "LiLiming/HOL", "max_stars_repo_head_hexsha": "8de43bf3176993a37fb2f917fe978964c9d0591c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-12-27T07:51:47.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-27T07:51:47.000Z", "max_issues_repo_path": "src/unwind/Manual/description.tex", "max_issues_repo_name": "LiLiming/HOL", "max_issues_repo_head_hexsha": "8de43bf3176993a37fb2f917fe978964c9d0591c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/unwind/Manual/description.tex", "max_forks_repo_name": "LiLiming/HOL", "max_forks_repo_head_hexsha": "8de43bf3176993a37fb2f917fe978964c9d0591c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0448598131, "max_line_length": 79, "alphanum_fraction": 0.6580191614, "num_tokens": 5992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.3180877333179505}}
{"text": "%% LaTeX2e Template by Stephen Iota (https://stepheniota.com/)\n%% last updated: Feb. 2019\n%% for papers\n%\\documentclass[aps,preprint,notitlepage]{revtex4-1}\n%% https://www-d0.fnal.gov/Run2Physics/WWW/templates/revtex4.pdf\n%% https://cdn.journals.aps.org/files/revtex/auguide4-1.pdf\n%% ^^ revTeX4-1 class options\n\n%% for other\n\\documentclass[11pt]{article}\n\\usepackage[margin=2cm]{geometry}\n%%%%%%%%%%%%%%%%\n%%% Packages %%%\n%%%%%%%%%%%%%%%%\n\n\\usepackage[utf8]{inputenc}\n\\usepackage[noadjust]{cite}\n\\usepackage{lipsum}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{amsfonts}\n\\usepackage{mathtools}\n\\usepackage{physics} %http://ftp.math.purdue.edu/mirrors/ctan.org/macros/latex/contrib/physics/physics.pdf\n\\usepackage[thinc]{esdiff} % easy derivatives\n\\usepackage{graphicx} % \\includegraphics{ }\n\\usepackage[shortlabels]{enumitem} % change labels in enum/item environments\n\\usepackage[dvipsnames]{xcolor} % colored links=\n%\\usepackage{footmisc} % http://mirror.utexas.edu/ctan/macros/latex/contrib/footmisc/footmisc.pdf\n%\\usepackage[small]{titlesec} % [small,medium,big] << controls size of *section text\n%\\usepackage{fancyhdr} %http://tug.ctan.org/tex-archive/macros/latex/contrib/fancyhdr/fancyhdr.pdf\n% always put this at the end\n\\usepackage[\n\tcolorlinks=true,\n\tcitecolor=NavyBlue!90!black,\n\tlinkcolor=NavyBlue!75!black,\n\turlcolor=green!50!black,\n\thypertexnames=false]{hyperref}\n\n %%%%%%%%%%%%%%%%%%\n %% New Commands %%\n %%%%%%%%%%%%%%%%%%\n\\newcommand{\\email}[1]{\\texttt{\\href{mailto:#1}{#1}}}\n%\\newcommand{\\ave}[1]{$\\langle #1 \\rangle$}\n\\renewcommand{\\d}[1]{\\ensuremath{\\operatorname{d}\\!{#1}}}\n%%%%%%%%%%%%%%%%%%\n%% Front Matter %%\n%%%%%%%%%%%%%%%%%%\n\n%\\pagenumbering{gobble} % no page numbers\n\\graphicspath{{figures/}} % set directory for figures\n%\\setcounter{section}{-1} % start with section 0\n\n\n%%%%%%%%%%%%%\n%%% Title %%%\n%%%%%%%%%%%%%\n\\begin{document}\n\n\n\n\\begin{center}\n\n\\Large{\\textsc{Statistical Mechanics}: \\textbf{Problem Set 2}}\n\\end{center}\n\\vspace{.5mm}\n\n\n%%%%%%%%%%\n%% INFO %%\n%%%%%%%%%%\n\n\\begin{tabular}{rl}\n\\textsc{Name}:\n&\nStephen Iota (\\email{siota001@ucr.edu})\n\\\\\n\\textsc{Course}:\n&\nPhysics 133 (Spring 2019), Prof.~Kuhlman\n\\\\\n\\textsc{Date}:\n&\n\\today\n\\end{tabular}\n\\vspace{2mm}\n%%%%%%%%%%%%%%\n%% PROBLEMS %%\n%%%%%%%%%%%%%%\n\n\\noindent\nSethna problems 2.6, 3.5 and 3.9. Painstakingly typeset using \\LaTeX. All final answers are \\boxed{\\text{boxed.}}\n\n%%%%%%%%%%%%%%%%\n%% Sethna 2.6 %%\n%%%%%%%%%%%%%%%%\n\\section{Fourier and Green}\n\nAn initial denisty profile $\\rho(x,t=0)$ is perturbed slightly from $\\rho_0$. The density obeys the diffusion equation\n$\\pdv{\\rho}{t} = D \\pdv[2]{\\rho}{x}$,\nwhere $D = 0.001$ m/s$^2$.\n\n\\begin{figure}[h!]\n\\centering\n\\includegraphics[width=.5\\linewidth]{Pset2_Fig1}\n\\caption{Initial profile density deviation from average.\\label{density}}\n\\end{figure}\n\n\\vspace{2mm}\n\\noindent\n\\textbf{(a) Fourier}\n\\textit{Consider just a cosine wave. If the intial wave were\n$\\rho_\\text{cos}(x,0) = \\cos{10x}$, what would it be at $t = 10s$?}\n\n\\vspace{2mm}\n\\noindent\n\\textbf{Solution:}\nWe can decompose $\\rho$ into a superpostition of complex plane wave solutions using the Fourier method. We expect the solution to look like $\\rho_\\text{cos} = \\rho_k e^{ikx}$.\nWe can superimpose all different wave vectors to get a general solution.\n$$\n\\rho(x,t) = \\frac{1}{2\\pi} \\int_{-\\infty}^{\\infty} \\rho_k(0) e^{ikx} e^{-Dk^2t} \\text{d}k\n$$\nwhere the coefficients $\\rho_k(0)$ are the Fourier transform of the initial density profile\n$$\n\\rho_k(0) = \\int_{-\\infty}^{\\infty} \\rho(x,0) e^{-ikx} \\text{d}x\n$$\n\nPlugging in $\\rho_\\text{cos}(x,0) = \\cos{10x}$, we get\n\\begin{align*}\n\\rho_k &= \\int_{-\\infty}^{\\infty} \\cos{10x} \\ e^{-ikx} \\text{d}x\n\\\\\n       &= \\int_{-\\infty}^{\\infty} \\frac{e^{i10x} + e^{-i10x}}{2} \\ e^{-ikx} \\text{d}x\n\\\\\n\t\t\t &= \\frac{1}{2} \\Big[ \\delta(k-10) + \\delta(k+10) \\Big]\n\\end{align*}\nSo the initial distribution is composed of two frequencies.\nNow we solve for the time evolution in position space.\n\\begin{align*}\n\\rho(x,t) &= \\frac{1}{2\\pi} \\int_{-\\infty}^{\\infty} \\frac{1}{2} \\Big[ \\delta(k-10) + \\delta(k+10) \\Big] e^{ikx} e^{-Dk^2t} \\text{d}k\n\\\\\n          &= \\frac{1}{4\\pi} \\int_{-\\infty}^{\\infty} \\Big[ \\delta(k-10)e^{ikx} e^{-Dk^2t} + \\delta(k+10)e^{ikx} e^{-Dk^2t} \\Big] \\text{d}k\n\t\t\t\t\t\\\\\n\t\t\t\t\t&= \\frac{1}{4\\pi} \\Big[ (e^{i10x} + e^{-i10x}) e^{-D100t}  \\Big]\n\t\t\t\t\t\\\\\n\t\t\t\t\t&= \\frac{1}{8\\pi} \\cos{10x} \\ e^{-D100t}\n\\end{align*}\nThis is the general time evolution for $\\rho_\\text{cos}$. Solving for $t =0$ yields\n\\begin{align*}\n\\rho(x, t = 10s) &=  \\frac{1}{8\\pi} \\cos{10x}\\  e^{-(.001\\cdot100\\cdot10)}\n\\\\\n&=  \\boxed{ \\frac{1}{8\\pi} \\cos{10x}\\  e^{-1}}\n\\end{align*}\n\n\\vspace{2mm}\n\\noindent\n\\textbf{(b) Green}\n\\textit{If a wave at some earlier time $-t_0$ were a $\\delta$-function at $x = 0$, such that $\\rho(x,-t_0) = \\delta(x)$, what choice of time elapsed $t_0$ would yield a Gaussian $\\rho(x,0) = \\exp(-x^2/2)/\\sqrt{2\\pi}$ for the given diffusion constant $D$?}\n\n\\vspace{2mm}\n\\noindent\n\\textbf{Solution:}\nWe define Green's function $G(x,t)$ to be the time evolution of $G(x,t=-t_0) = \\delta(x)$. We follow the same steps as in part a to solve for $G(x,t).$\n\\begin{align*}\nG_k(-t_0) &= \\int G(x,-t_0) e^{-ikx}\\d{x}\n\\\\\n          &= \\int \\delta(x) e^{-ikx} = 1\n\\end{align*}\n$G_k$ is independent of $k$. The time evolved Fourier transform is $G_k(t) = e^{-Dk^2(t+t_0)}.$\nThe time evolution in position space is\n\\begin{align*}\nG(x,t) &= \\frac{1}{2\\pi} \\int e^{ikx} G_k(-t_0) e^{-Dk^2(t+t_0)} \\d{k}\n\\\\\n       &= \\frac{1}{2\\pi} \\int e^{ikx} e^{-Dk^2(t+t_0)} \\d{k}\n\\end{align*}\nThe answer to this integral is the well known Green's function for the diffusion equation\n$$\nG(x,t) = \\frac{1}{\\sqrt{4\\pi D(t+t_0)}} e^{-x^2/4D(t+t_0)}\n$$\nWe need to find a time $-t_0$ such that $G(x,0)$ looks like a Gaussian function centered about the origin for the given diffusion constant $D.$ By analysis, we see that a time of \\boxed{t_0 = 500 \\ \\text{seconds}} will give a Gaussian at $t=0$.\n\n\n\n\\vspace{2mm}\n\\noindent\n\\textbf{(c) Pictures}\n\\textit{Now consider time evolution for the next ten seconds. The initial density profile $\\rho(x,t = 0)$ is as shown in fig.~\\ref{density}.\nWhat figure represents the density at $t = 10s$?}\n\n\n\n\\vspace{2mm}\n\\noindent\n\\textbf{Solution:}\nThe density profile in fig.~\\ref{density} is a Gaussian centered at $x=5$ on the left,\nand a smooth envelope function multiplied by $\\cos{10x}$ centered at $x=15$ on the right. From the previous two parts, we know that the Gaussian function takes a much longer time to diffuse that the cosine function. Thus, in 10 seconds, we expect the function on the left to remain fairly similar. The short wavelength parts of the cosine function will be suppressed.\nWe expect the distribution at $t = 10$ sec to look like \\boxed{\\text{fig.~\\ref{10sec} (figure \\textbf{E} from the text).}}\n\n\\begin{figure}[h!]\n\\centering\n\\includegraphics[width=.4\\linewidth]{PSet2_Fig3}\n\\caption{Profile density at $t = 10$ seconds.}\n\\label{10sec}\n\\end{figure}\n\n%%%%%%%%%%%%%%%%\n%% Sentha 3.5 %%\n%%%%%%%%%%%%%%%%\n\\section{Hard sphere gas}\nA 2D $L \\cross L$ box with hard walls contains a gas of $N$ hard disks of radius $r \\ll L$, as shown in fig.~\\ref{sphere}.\nThe disks are dilute; the summed area $N\\pi r^2 \\ll L^2$.\nLet A be the effective area allowed for the disks in the box: $A = (L-2r)^2$.\n\\begin{figure}[h!]\n\t\\centering\n\t\\includegraphics[width=.3\\linewidth]{PSet2_Fig2}\n\t\\caption{Hard sphere gas.}\n\t\\label{sphere}\n\\end{figure}\n\n\\vspace{2mm}\n\\noindent\n\\textbf{(a)}\n\\textit{The area allowed for the second disk is approximately $A - \\pi(2r)^2$.\nWhat is the allowed 2N-dimensional volume in configuration space, of allowed zero-energy configurations of hard disks, in this dilute limit?}\n\n\\vspace{2mm}\n\\noindent\n\\textbf{Solution:}\nFor $N = 2$, $A_2 = A(A-4\\pi r^2)$; for $N = 3$, $A_3 = A(A_2)(A_2 - 4\\pi r^2)$, and so on. As $N$ increases, each disk will have a smaller area by $4\\pi r^2$ than the previous disk.\n\n$$\n\\boxed{A_N = \\frac{1}{N!}\\prod_{n = 0}^{N}A - n4\\pi r^2}\n$$\n\n\n\\vspace{2mm}\n\\noindent\n\\textbf{(b)}\n\\textit{\nWhat is the configuration entropy for the hard disks?}\n\n\\vspace{2mm}\n\\noindent\n\\textbf{Solution:}\nLet $S$ denote configuration entropy. Using answer from part a:\n\n\\begin{align*}\nS &= k_B \\log{A_N}\n\\\\\n  &= k_B \\log{\\Big( \\frac{1}{N!}\\prod_{n = 0}^{N}A - n4\\pi r^2 \\Big)}\n\t\\\\\n\t&= k_B \\Big( -\\log{N!} + \\sum_{n = 1}^{N} \\log{(A - (n-1)4\\pi r^2)} \\Big)\n\\end{align*}\nwhere in the last step we changed the starting index.\nIn the dilute limit, $N 4\\pi r^2 \\ll A$. We taylor expand $\\log{(A - n4\\pi r^2)}$:\n\\begin{align*}\n\\log{(A - (n-1)4\\pi r^2)} &= \\log{A} + \\log{(1 - (n-1)4\\pi r^2/A)}\n\\\\\n&\\approx \\log{A} - (n-1)\\frac{4\\pi r^2}{A}\n\\end{align*}\nPlugging in this approximation to the sum, we find a sum of the form $\\sum_{n = 1}^{N} = N(N-1)/2$.\nWe use Stirling's approximation $\\log{N!} \\approx N \\log{N} - N$.\n\\begin{align*}\nS &= k_B \\Bigg( - N \\log{N} - N + \\bigg( N\\log{A} - \\frac{N(N-1) 4\\pi r^2}{2A} \\bigg) \\Bigg)\n\\end{align*}\nSimplifying, we reach our result\n$$\n\\boxed{S = N k_B \\bigg( 1 + \\log{\\Big( \\frac{A}{N} - \\frac{4\\pi r^2}{N}\\frac{N - 1}{2} \\Big)} \\bigg)}\n$$\nwhere we might possibly be able to say $ \\frac{4\\pi r^2}{N}\\frac{N - 1}{2}$ is about $2\\pi r^2$.\n%%%%%%%%%%%%%%%%\n%% Sentha 3.9 %%\n%%%%%%%%%%%%%%%%\n\\section{Gauss and Poisson}\nCalculate the probability of having $n$ particles in a subvolume $V$, for a box with total volume $KV$ and a total number of particles $T = KN_0$.\n\n\\vspace{2mm}\n\\noindent\n\\textbf{(a)}\n\\textit{Find the exact formula for this probability; $n$ particles fall in the subvolume $V$, with a total of $T$ particles in $KV$.}\n\n\\vspace{2mm}\n\\noindent\n\\textbf{Solution:}\nSuppose $n$ particles are in subvolume $V$ and $T - n$ particles are outside of $V$, in subvolume $(K-1)V$, where the total volume is $KV$.\nIn configuration space, the available volume is $V^n ((K - 1)V)^{T - n} = V^T (K-1)^{T - n}$, and the total volume is $(KV)^T$. The probability is given by the ratio of these two volumes, where we need to be mindful about the different ways to pick the $n$ particles. The total probability is given by:\n\\begin{align*}\nP(n) &= \\binom{T}{n} \\frac{(K - 1)^{T - n}}{K^T}\n\\\\\n     &= \\boxed{\\frac{T!}{n!(T - n)!} \\frac{(K - 1)^{T - n}}{K^T}}\n\\end{align*}\n\n\n\\vspace{2mm}\n\\noindent\n\\textbf{(b)}\n\\textit{\nShow that the Poisson distribution in normalized: $\\sum_n \\rho_n = 1$.\nCalculate the mean of the distribution $\\langle n \\rangle$ in terms of $a$. Calculate the variance $\\langle(n - \\langle n\\rangle)^2\\rangle$.}\n\n\\vspace{2mm}\n\\noindent\n\\textbf{Solution:}\nFor normalization:\n\\begin{align*}\n\\sum_{n=0}^{\\infty} \\rho_n &= \\exp{-a} \\sum_{n=0}^{\\infty} \\frac{a^n}{n!}\n\\\\\n&= \\exp{-a} \\exp{a}\n\\\\\n&= \\boxed{1}\n\\end{align*}\nFor mean of Poisson distribution:\n\\begin{align*}\n\\langle n \\rangle &= \\sum_{n=0}^{\\infty} n \\frac{a^n}{n!} e^{-a}\n\\\\\n&= \\sum_{n=1}^{\\infty} n \\frac{a^n}{n!} e^{-a}\n\\\\\n&= \\sum_{n=1}^{\\infty} \\frac{aa^{n-1}}{(n-1)!} e^{-a}\n\\\\\n&= a \\sum_{n=0}^{\\infty} \\frac{a^n}{n!} e^{-a}\n\\\\\n&= a \\sum_{n=0}^{\\infty} \\frac{a^n}{n!} e^{-a}\n\\\\\n&= a \\sum_{n=0}^{\\infty} \\rho_n\n\\end{align*}\nwhich is equal to $\\boxed{a}$ because the distribution is normalized.\nFor the variace, we have\n$\n\\langle(n - \\langle n\\rangle)^2\\rangle = \\langle n^2 \\rangle - \\langle n \\rangle^2\n$.\n\\begin{align*}\n\\langle n\\rangle)^2 &= \\sum_{n=0}^{\\infty} n^2 \\frac{a^n}{n!} e^{-a}\n\\\\\n&= a \\sum_{n=0}^{\\infty} (n+1)\\rho_n\n\\\\\n&= a \\langle n+1 \\rangle\n\\\\\n&= a^2 + a\n\\end{align*}\nThis gives us a variance of $(a^2 + a) - (a^2) = \\boxed{a}$.\n\n\n\\vspace{2mm}\n\\noindent\n\\textbf{(c)}\n\\textit{As $K \\rightarrow \\infty$, show that the probability that $n$ particles fall in the subvolume $V$ has the Poisson distribution $\\rho_n = a^n e^{-a}/n!$. What is $a$?}\n\n\\vspace{2mm}\n\\noindent\n\\textbf{Solution:}\nRecall the answer to part a:\n$$\nP(n) = \\frac{T!}{n!(T - n)!} \\frac{(K - 1)^{T - n}}{K^T}\n$$\nAs we let $K \\text{and} T \\rightarrow \\infty, \\ (1 - 1/K)^(T-n) \\approx e^{\\frac{T}{K}}.$ Also $T! \\approx (T/e)^T$. We simplify:\n\n\\begin{align*}\n\\frac{T!}{n!(T - n)!}\n&\\approx \\frac{(T/e)^T}{((T-n)/e)^{T-n}}\n\\\\\n&= \\Big(\\frac{T-n}{T}\\Big)^{n-T}  \\ \\Big(\\frac{T}{e}\\Big) ^n\n\\\\\n&\\approx e^{\\frac{n}{T}(T-n)} \\Big(\\frac{T}{e}\\Big)^N\n\\\\\n&\\approx T^n\n\\end{align*}\nThe final result is a Poisson distribution where $a = T/K.$\n$$\n\\boxed{\nP(n) = \\frac{(T/K)^n}{n!} e^{-T/K}\n}\n$$\n\n\\end{document}\n", "meta": {"hexsha": "0c296df412613fffabb55ad5349629b29c2ef98e", "size": 12296, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "solved/P133_PSet2.tex", "max_stars_repo_name": "stepheniota/Physics133-UCR", "max_stars_repo_head_hexsha": "2018ae62e384205459175dbed525930e607f8956", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "solved/P133_PSet2.tex", "max_issues_repo_name": "stepheniota/Physics133-UCR", "max_issues_repo_head_hexsha": "2018ae62e384205459175dbed525930e607f8956", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solved/P133_PSet2.tex", "max_forks_repo_name": "stepheniota/Physics133-UCR", "max_forks_repo_head_hexsha": "2018ae62e384205459175dbed525930e607f8956", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9651474531, "max_line_length": 367, "alphanum_fraction": 0.6360605075, "num_tokens": 4596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3180877333179505}}
{"text": "%&context\n\n\\section[sct_trim]{Trimming trees}\n\n\nTrimming a tree means cutting the nodes whose depth is larger than a specified threshold. Here is what will happen if I cut the catarrhini tree at depth 30:\n\n\\midaligned{\\externalfigure[trim_1]}\n\nThe tree will be \"cut\" on the red line, and everything right of it will be discarded:\n\n\\svgCmdOutput{trim_2}\n\nBy default, depth is expressed in branch length units -- usually substitutions\nper site. By passing the \\code{-a} switch, it is measured in number of\nancestors, instead. Here are the first four levels of a huge tree (it has more than 1000 leaves):\n\n\\svgCmdOutput{trim_3}\n\nThe leaves with labels of the form \\id{ID *} are also leaves in\nthe original tree, the other leaves are former inner nodes whose children got\ntrimmed.  Their labels are the (absolute) bootstrap support values of those\nnodes. Note that the branch lengths are conserved. It is apparent that the\ningroup's lower half has very poor support. This would be harder to see without\ntrimming the tree, due to its huge size.\n\n\\subsubsection{Trimming cladograms}\n\nBy definition, cladograms do not have branch lengths, so you need to express depth in numbers of ancestors, and thus you want to pass \\code{-a}.\n", "meta": {"hexsha": "5fd06c3fcd4aa1eb73a78464562231e9d94f96cb", "size": 1223, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/c-trim.tex", "max_stars_repo_name": "Cactusolo/newick_utils", "max_stars_repo_head_hexsha": "da121155a977197cab9fbb15953ca1b40b11eb87", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 62, "max_stars_repo_stars_event_min_datetime": "2015-01-08T22:22:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T09:12:51.000Z", "max_issues_repo_path": "doc/c-trim.tex", "max_issues_repo_name": "Cactusolo/newick_utils", "max_issues_repo_head_hexsha": "da121155a977197cab9fbb15953ca1b40b11eb87", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 24, "max_issues_repo_issues_event_min_datetime": "2015-01-22T19:34:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-27T10:53:41.000Z", "max_forks_repo_path": "doc/c-trim.tex", "max_forks_repo_name": "Cactusolo/newick_utils", "max_forks_repo_head_hexsha": "da121155a977197cab9fbb15953ca1b40b11eb87", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2015-05-07T09:23:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T02:43:50.000Z", "avg_line_length": 40.7666666667, "max_line_length": 156, "alphanum_fraction": 0.7792313982, "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.31806326838968485}}
{"text": "\\section{Group based Behavior Modeling}\n\\label{sec:gm}\n\n%clear points\n%road map\n%detail of each step, with motivation\n\n\n\\par Recall the central problem of \\sys{}, where the \\retg{} behaviors of users are modeled.\nSpecifically, such model is built by the Group Modeling module for each user group and thus named as group model.\nTo avoid ambiguity, we shall use the term of \\textit{items} to denote the data for training the group model.\nA given \\textit{item} is either positive or negative.\n\n\\begin{definition}\n\\label{def:gm-it}\nAn item $E$ involves a microblog $b$ and a user $f$ such that $f\\ \\in R_{b.O}$, i.e., $f$ is a follower of  the owner of microblog $b$.\n\\begin{equation}\n\\label{eq:gm-it}\nE \\in\n  \\begin{cases}\n    \\text{positive items}       & \\quad \\text{if } f \\text{ \\retd{} } b\\\\\n    \\text{negative items}  \t\t& \\quad \\text{if } f \\text{ did not \\ret{} } b\n  \\end{cases}\n\\end{equation}\n\\end{definition}\n\nAnd the data of item $E$ consists of three parts.\n%\\begin{itemize}\n\n\t\\stab(1) \\stitle{User Info} contains a list of aforementioned metrics \\{$G_u$, $P_u$,\\#$R_u$, \\#$E_u$, $R_{ee,u}$\\}.\n\t\n%\t\\stab(2) \\stitle{Microblog Info} refers to metrics related to the microblog $b$. The number of times the $b$ be retweeted, be %commented, be liked and the length of the microblog contents are considered. What's more, we also considers the correlation between %microblog contents and recent events, where the latter is returned by Ring \\cite{IEEEexample:ring}. The correlation metric $C_h$ is in %the form of a normalized vector with each dimension represents one event (similar as $P_{f,u}$ in formula \\ref{eq:inte}). Each event %could be viewed as a topic $t$, over which the correlation of a microblog $b$ could be obtained by formula \\ref{eq:sim-tw1}.\n\n\\stab(2) \\stitle{Microblog Info} refers to metrics related to the microblog $b$.\n%The number of times the $b$ has been retweeted, commented, liked and the length of the microblog contents are considered.\nThe number that $b$ has been retweeted, commented, liked and the length of $b.M$ (microblog message) are considered.\nWhat is more, we consider the correlation between $b$ and recent event, where the latter is expressed as several core words returned by Ring \\cite{IEEEexample:ring}.\nHere we compute \\textit{TF-IDF weight} $W_f$ of $b.M$, and get correlation metric $C_h$ of $b$ and event by formula \\ref{eq:sim-tf1}.\n\n%\t\\stab(3) \\stitle{Interaction Info} includes seven correlation metrics. They are of \\#$B_u$, $R_{oc,u}$, \\#$W_{r,u}$, \\#$W_{t,u}$, %microblog $b$ versus the user $u$'s \\textit{Interest Feature} $P_f(u)$ (a.k.a. long-term/stable interest in this work), $b$ versus %$u$'s short-term interest $P_s(u)$ that is mined from $u$'s recent microblogs (e.g., within 30 days) in the same manner of $P_f(u)$, %and $b$'s timestamp versus the time distribution of $u$'s \\retg{} behavior $P_{rt,u}$.\n%\\end{itemize}\n\t\\stab(3) \\stitle{Interaction Info} includes seven correlation metrics: \\#$B_u$, $R_{oc,u}$, \\#$W_{r,u}$, \\#$W_{t,u}$, microblog $b$ versus the user $u$'s \\textit{Interest Feature} $P_u$ (a.k.a. long-term/stable interest in this work), and $b$'s timestamp versus the time distribution of $u$'s \\retg{} behavior $P_{rt,u}$.\n%In addition, the correlation between microblog contents and $u$'s short-term interest mined from $u$'s recent microblogs (e.g., within 30 days) is also taken in consideration.\n%In addition, the correlation between microblog contents and $u$'s short-term interest is also taken in consideration. The short-term %interest is expressed as\nIn addition, we consider $u$'s short-term interest, which is mined from $u$'s recent microblogs (e.g., within 30 days) and calculated by \\textit{TF-IDF}, namely $W_s$.\nThe correlation between microblog $b$ and $u$'s short-term interest is computed by $W_f$ and $W_s$ (using formula \\ref{eq:sim-tf1}).\n%%\n\nThe modeling of retweeting behavior of groups is treated as a classification problem, and we utilize the random forest classifier to address it. Details for random forest \\cite{IEEEexample:conf/icdar/Ho1995} are omitted here for space reason.\nThe advantage of this classification model lies in that it could integrate different features conveniently, and\n%The advantage of using classification model is that we can integrate different combinations of the features into the model conveniently.\nthe obtained group behavior model could learn what a positive/negative item looks like over each metric mentioned above. \\par\nHere we use accuracy to evaluate our model. To define accuracy, we set four variables: $E_{tp}$,$E_{fp}$,$E_{tn}$ and $E_{fn}$. For a given item $E$, if $E$ is a positive item and our model also determines it a positive item, then we set $E_{tp}$ to 1, else we set $E_{tp}$ to 0. If $E$ is a negative item and our model determines it a positive item, then we set $E_{fp}$ to 1, else we set $E_{fp}$ to 0. If $E$ is a negative item and our model determines it a negative item, then we set $E_{tn}$ to 1, else we set $E_{tn}$ to 0. If $E$ is a positive item and our model determines it a negative item, then we set $E_{fn}$ to 1, else we set $E_{fn}$ to 0. So the accuracy can be defined as:\n\n\\begin{equation}\n\\label{eq:def-precision1}\naccuracy = \\frac{\\sum_{\\substack{E}} (E_{tp} + E_{tn} )}{ \\sum_{\\substack{E}} (E_{tp} + E_{tn} + E_{fp} + E_{fn}) }\n\\end{equation}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "747be9336c9db36773807f4e2647436666b8b879", "size": 5353, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "DASFAA_2018/CR/Gruba_final/05-gm.tex", "max_stars_repo_name": "shuaima/GruBa", "max_stars_repo_head_hexsha": "0abfff6db2ee4ed5848810a835f1619b9384c4ce", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DASFAA_2018/CR/Gruba_final/05-gm.tex", "max_issues_repo_name": "shuaima/GruBa", "max_issues_repo_head_hexsha": "0abfff6db2ee4ed5848810a835f1619b9384c4ce", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DASFAA_2018/CR/Gruba_final/05-gm.tex", "max_forks_repo_name": "shuaima/GruBa", "max_forks_repo_head_hexsha": "0abfff6db2ee4ed5848810a835f1619b9384c4ce", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 69.5194805195, "max_line_length": 689, "alphanum_fraction": 0.7235195218, "num_tokens": 1557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.318039821949264}}
{"text": "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Copyright (c) 2003-2018 by The University of Queensland\n% http://www.uq.edu.au\n%\n% Primary Business: Queensland, Australia\n% Licensed under the Apache License, version 2.0\n% http://www.apache.org/licenses/LICENSE-2.0\n%\n% Development until 2012 by Earth Systems Science Computational Center (ESSCC)\n% Development 2012-2013 by School of Earth Sciences\n% Development from 2014 by Centre for Geoscience Computing (GeoComp)\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Level Set Method}\n\nThe Level Set Method is used for tracking interfaces between two different types of fluids, which may have different physical parameter values for density or viscosity. The interface is represented by a signed distance function, $\\phi(x)$, where the isocontour at $\\phi(x)=0$ is used to defined the interface. A point in the domain can then be determined on which side of the interface it resides, based on the local sign of $\\phi(x)$; for example positive $\\phi(x)$ on one side of the interface and negative $\\phi(x)$ on the other. Parameters values such as density and viscosity can then be defined for the two different mediums. The Level Set Method consists of two procedures, the advection and reinitialization of the signed distance function, $\\phi$. The LevelSet class can be used in conjunction with the StokesProblemCartesian class for solving computational fluid dynamics problems involving the tracking of the interface. The advantage of the Level Set Method is that it can be used to track surfaces that break apart or intersect. Also, the Level Set Method avoids the need for remeshing, which is required by the Lagrangian-Eulerian (ALE) method. \n\n% An example of using the Level Set Method is described in the tutorial Chapter, Section %\\ref{LEVELSET CHAP}.\n\n\\subsection{Solution Method}\n\nThe displacement of the interface at the zero isocontour of $\\phi(x)$ is calculated each time-step by using the velocity field. This is achieved my solving the advection equation:\n%\n\\begin{equation}\n\\frac{\\partial \\phi}{\\partial t} + \\vec{v} \\cdot \\nabla \\phi = 0,\n\\label{ADVECTION MODELS}\n\\end{equation}\n%\nwhere $\\vec{v}$ is the velocity field. The advection equation is solved using a Taylor-Galerkin scheme with the presence of diffusion; by expanding $\\phi$ into a Taylor series:\n%\n\\begin{equation}\n\\phi^{+} \\simeq \\phi^{-} + dt\\frac{\\partial \\phi^{-}}{\\partial t} + \\frac{dt^2}{2}\\frac{\\partial^{2}\\phi^{-}}{\\partial t^{2}},\n\\label{TAYLOR EXPANSION MODELS}\n\\end{equation}\n%\nthen by inserting\n%\n\\begin{equation}\n\\frac{\\partial \\phi^{-}}{\\partial t} = - \\vec{v} \\cdot \\nabla \\phi^{-},\n\\label{INSERT ADVECTION MODELS}\n\\end{equation}\n%\nand\n%\n\\begin{equation}\n\\frac{\\partial^{2} \\phi^{-}}{\\partial t^{2}} = \\frac{\\partial}{\\partial t}(-\\vec{v} \\cdot \\nabla \\phi^{-}) = \\vec{v}\\cdot \\nabla (\\vec{v}\\cdot \\nabla \\phi^{-}),\n\\label{SECOND ORDER MODELS}\n\\end{equation}\n%\ninto Equation (\\ref{TAYLOR EXPANSION MODELS}), the calculation of the level set function is given by:\n%\n\\begin{equation}\n\\phi^{+} = \\phi^{-} - dt\\vec{v}\\cdot \\nabla \\phi^{-} + \\frac{dt^2}{2}\\vec{v}\\cdot \\nabla (\\vec{v}\\cdot \\nabla \\phi^{-}).\n\\label{TAYLOR GALERKIN MODELS}\n\\end{equation}\n\nIf $\\nabla \\cdot \\vec{v}=0$ is assumed, then the calculation of the second order derivatives in Equation (\\ref{TAYLOR GALERKIN MODELS}) can be avoided.\n\nAs the computation of the distance function progresses, it becomes distorted, and so it needs to be updated in order to stay regular \\cite{SUSSMAN1994}. This process is known as the reinitialization procedure. The aim is to iteratively find a solution to the reinitialization equation:\n%\n\\begin{equation}\n\\frac{\\partial \\psi}{\\partial \\tau} + sign(\\phi)(1 - \\nabla \\psi) = 0.\n\\label{REINITIALISATION MODELS}\n\\end{equation}\n%\nwhere $\\psi$ shares the same level set with $\\phi$, $\\tau$ is pseudo time, and $sign(\\phi)$ is the smoothed sign function. This equation is solved to meet the definition of the level set function, $\\lvert \\nabla \\psi \\rvert = 1$; the normalization condition. Equation (\\ref{REINITIALISATION MODELS}) can be rewritten in a similar form to the advection equation:\n%\n\\begin{equation}\n\\frac{\\partial \\psi}{\\partial \\tau} + \\vec{w} \\cdot \\nabla \\psi = sign(\\phi),\n\\label{REINITIALISATION2 MODELS}\n\\end{equation}\n%\nwhere\n%\n\\begin{equation}\n\\vec{w} = sign(\\phi)\\frac{\\nabla \\psi}{|\\nabla \\psi|}.\n\\label{REINITIALISATION3 MODELS}\n\\end{equation}\n%\n$\\vec{w}$ is the characteristic velocity pointing outward from the free surface. Equation (\\ref{REINITIALISATION2 MODELS}) can be solved by a similar technique to what was used in the advection step, using the Taylor-Galerkin procedure.\nWhen the distance function, $\\phi$, is calculated, the physical parameters, density and viscosity, are updated using the sign of $\\phi$. The region along the interface is assumed to be of finite thickness of $\\alpha h$, where $h$ is the size of the elements in the computational mesh and $\\alpha$ is a smoothing parameter. The parameters are updated by the following expression:\n%\n\\begin{equation}\nP = \n\\left \\{ \\begin{array}{l}\nP_{1} \\hspace{5cm}  where \\ \\ \\psi < - \\alpha h \\\\\nP_{2} \\hspace{5cm}  where \\ \\ \\psi > \\alpha h \\\\\n(P_{2} - P_{1}) \\psi/2\\alpha h + (P_{1} + P_{2})/2 \\ \\ \\ \\ \\ \\ where \\ \\ |\\psi| < \\alpha h.\n\\end{array}\n\\right.\n\\label{UPDATE PARAMETERS MODELS}\n\\end{equation} \n%\nwhere the subscripts $1$ and $2$ denote the different fluids.\n\n\n\\subsection{Functions}\n\n\\begin{classdesc}{LevelSet}{domain, func, reinit\\_max, reinit\\_each, tolerance, smooth}\nopens the LevelSet \\index{Level Set} on the \\Domain domain. \\var{func} defines the initial Level Set function representing the interface between two fluids. \\var{reinit\\_max} sets the maximum number of iterations to satisfy the normal condition, $|\\nabla \\phi|=1$, during the reinitialization of the Level Set function. \\var{reinit\\_each} sets the frequency of reinitialization for a number of time-steps. \\var{tolerance} sets the convergence tolerance to satisfy the normal condition during the reinitialization of the Level Set function. \\var{smooth} sets the bandwidth of size 2$\\alpha h$ along the interface to smooth the physical parameters of density and viscosity; $h$ is the size of the elements in the mesh and $\\alpha$ is the smoothing parameter, usually set to 1.\n\\end{classdesc}\n\n\\begin{methoddesc}[LevelSet]{update\\_parameter}{par1, par2}\nupdates the physical parameters using the sign of $\\phi$. \\var{par1} and \\var{par2} are the physical parameter values for fluid1 and fluid2 respectively. Usually this method is called twice during each time-step to update the density and viscosity of the two fluids.\n\\end{methoddesc}\n\n\\begin{methoddesc}[LevelSet]{update\\_phi}{vel,  dt, t\\_step}\nupdates the Level Set function. It performs the advection and reinitialization procedures. \\var{vel} is the velocity field of the fluid domain, \\var{dt} is the time-step size, and \\var{t\\_step} is the current time-step to determine when to reinitialize.\n\\end{methoddesc}\n", "meta": {"hexsha": "166a297a6f1eb74d1833290b6b259478d53cb804", "size": 7060, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/user/levelsetmodel.tex", "max_stars_repo_name": "markendr/esys-escript.github.io", "max_stars_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/user/levelsetmodel.tex", "max_issues_repo_name": "markendr/esys-escript.github.io", "max_issues_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-01-14T03:07:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-14T03:07:43.000Z", "max_forks_repo_path": "doc/user/levelsetmodel.tex", "max_forks_repo_name": "markendr/esys-escript.github.io", "max_forks_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 63.0357142857, "max_line_length": 1159, "alphanum_fraction": 0.7283286119, "num_tokens": 1903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5506073802837477, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.31797321015096597}}
{"text": "%! Author = tstreule\n\n\\section{Fluorescent Probes}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Fluorescence Statistics}\n%\n\\textbf{Photobleaching}: A fluorescent molecule can emit a limited \\#photons by excitation before it irreversibly converts to a non-fluorescent molecule.\n\n\\begin{minipage}{.3\\columnwidth}\n    \\includegraphics[width=.9\\columnwidth]{Fluorescence_Statistics}\n\\end{minipage}%\n\\begin{minipage}{.7\\columnwidth}\n    \\formula{\\textbf{Quant. Yield}}{Q = \\frac{\\Gamma}{\\Gamma+k+K_b} \\sim 0-98\\%}\n    \\hfill (Efficiency)\n    \\formbox{Fluorescence \\textbf{Lifetime}}{\\tau = \\frac{1}{\\Gamma+k+K_b} \\sim \\unit[1]{ns}}\n    \\vspace{1mm}\n\n    Fluorescence emission is a statistical process that is characterized by exponential decays.\n    \\formula{Molecules in \\textit{excited} state}{\\deriv{N_e}{t} = -\\left(\\frac{1}{\\tau_1}+\\ldots+\\frac{1}{\\tau_n}\\right) N_e}\n\\end{minipage}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\columnbreak\n\\subsection{FRET \\textnormal{-- Fluorescence Resonance Energy Transfer}}\n%\n\\begin{minipage}{.25\\columnwidth}\n    \\includegraphics[width=.9\\columnwidth]{Fluorescence_FRET}\n\\end{minipage}%\n\\begin{minipage}{.75\\columnwidth}\n    Seeing a different $\\lambda\\ped{emission}$ tells us that two molecules are close.\n    \\formbox{Efficiency}{E = \\frac{R_0^2}{R_0^2+r^6} = 1\\!-\\!\\frac{\\tau\\ped{DA}}{\\tau\\ped{D}} = 1\\!-\\!\\frac{I\\ped{DA}}{I\\ped{D}}}\n    where\n    \\formtex{$\\tau\\ped{D(A)}$, $I\\ped{D(A)}$}{Lifetime/Intensity of donor emission}\n    \n    \\formtex{~}{in the absence/presence of acceptor.}\n\\end{minipage}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Calcium Imaging \\textnormal{\\hfill $\\to$ too slow for $t$ dependency meas.}}\n%\nCalcium ion cannot be visualized/tagged directly:\n$\\to$\nDesign molecules with optical properties that change upon calcium binding.\n\n\\begin{minipage}{.23\\columnwidth}\n    \\includegraphics[width=\\columnwidth]{Fluorescence_Calcium_Imaging}\n\\end{minipage}%\n\\hspace{\\columnsep}%\n\\begin{minipage}{.77\\columnwidth-\\columnsep}\n    \\textbf{Single \\& dual wavelength measurements}: \n    \\formbox{Concentration}{[\\ce{Ca^{2+}}]_i = K\\ped{d,eff} \\frac{R-R\\ped{min}}{R\\ped{max}-R}}\n    where\n    \\formula{for single}{\\scriptstyle R\\equiv F \\text{ and } K\\ped{d,eff} = \\frac{[\\ce{Ca^{2+}}]_i \\times(F\\ped{max}-F)}{F-F\\ped{min}}}\n    \\formula{for dual.}{R=F_1/F_2}\n    \\qquad ($F$: fluorescence)\n%\n%\t\twhere $R=F_1/F_2$ for dual wavelength and $R\\equiv F$ and $K\\ped{d,eff} = \\frac{[\\ce{Ca^{2+}}]_i \\times(F\\ped{max}-F)}{F-F\\ped{min}}$ for single wavelength\n\\end{minipage}\n\nThe binding of \\ce{Ca^{2+}} leads to\\ldots\n\\begin{itemize}\n    \\item change in fluorescence \\textbf{intensity} but not wavelength change\n    \\item a \\textbf{shift} in excitation (and/or emission) peaks (``dual wavelength'')\n    \\item changes in fluor. resonance energy transfer (\\textbf{FRET}) \\& life time\n\\end{itemize}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Delivery of Calcium Indicators}\n%\n\\formtex{\\textbf{Loading cells}}{Once the molecule got cleaved (spalten), it}\n\\formtex{~}{cannot go out and gets fluorescent.}\n\n\\formtex{Introduce \\textbf{fluoresc.}}{Proteins change emission rate when \\ce{Ca} binds.}\n\\formtex{\\textbf{proteins} or (natural)}{Relative change ($\\Delta F/F$) in fluorescence}\n\\formtex{\\textbf{FRET proteins}}{emission of EGFP can then be meas. directly.}\n\n\\underline{Note}: The dye responds \\textit{fast}, but it is \\textit{slow} to recover. \\ce{Ca} dissociation\\\\\n\\phantom{\\underline{Note}:} rate (i.e. recovery) depends on dye’s affinity for \\ce{Ca}.\n", "meta": {"hexsha": "f3b64a9e89f5ad24c52060ed7be2804140500d96", "size": 3645, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/BE18/sections/05_fluorescent.tex", "max_stars_repo_name": "tstreule/eth-cheat-sheets", "max_stars_repo_head_hexsha": "c61f9fd3b13edf405f790581b4d5eacb50b4f1c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-26T23:11:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T23:11:57.000Z", "max_issues_repo_path": "src/BE18/sections/05_fluorescent.tex", "max_issues_repo_name": "tstreule/eth-cheat-sheets", "max_issues_repo_head_hexsha": "c61f9fd3b13edf405f790581b4d5eacb50b4f1c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BE18/sections/05_fluorescent.tex", "max_forks_repo_name": "tstreule/eth-cheat-sheets", "max_forks_repo_head_hexsha": "c61f9fd3b13edf405f790581b4d5eacb50b4f1c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.3376623377, "max_line_length": 158, "alphanum_fraction": 0.6551440329, "num_tokens": 1170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.5506073655352403, "lm_q1q2_score": 0.31797320964136633}}
{"text": "\\chapter[Axiomatizing General Concept Inclusions with High Confidence]{Axiomatizing\n  General Concept Inclusions\\\\ with High Confidence}\n\\label{cha:axiom-conf-el}\n\nThe results obtained by Baader and Distel about computing finite bases of finite\ninterpretations are not only interesting from a theoretical point of view.  Although we\nhave skipped most of the details, all the relevant results are \\emph{effective} in the\nsense that the obtained bases can in principle be computed by computers.  Thus, these\nresults may also be interesting for practical applications.\n\nA possible application of the results of Baader and Distel is to compute bases from\n\\emph{Linked Open Data}~\\cite{Linked-Data}, a format for representing data as used by the\nsemantic web~\\cite{journal/sciam/BernersLeeHL01,DBLP:conf/dagstuhl/2003sweb,FOST}.  This\ndata format consists of RDF triples, and can thus be thought of as an edge-labeled graph.\nAs such, it is very similar to interpretations, and thus we can use the results by Baader\nand Distel here.\n\nAs a first contribution of this thesis we have implemented the major results on computing\nfinite bases as described previously, and applied them to a particular data set of the\n\\emph{Linked Open Data Cloud}, namely to a subset of the DBpedia data set~\\cite{DBpedia}.\nIn \\Cref{sec:computing-bases-from} we describe this experiment in detail and show what\nDistel's results yield when applied to this data set.  This experiment has also been\ndiscussed previously~\\cite{Borchmann:confident-GCIs,DBLP:conf/icdm/BorchmannD11}.\n\nOne conclusion from this experiment is that the results by Baader and Distel are very\nsensitive to \\emph{errors} in the data.  This is actually not surprising: bases of finite\ninterpretations only contain general concept inclusions which are valid in the data, and\nif there is as little as a single counterexample to a given general concept inclusion in\nthe data, it will not be contained in any base.\n\nIf those counterexamples are erroneous, however, then this can cause problems.  Not only\nthat otherwise valid general concept inclusions are not obtained by Distel's approach\nanymore.  Sporadic erroneous counterexamples may also cause GCIs found during the\ncomputation of bases to be rather complicated, because those GCIs have to avoid those\nerroneous counterexamples using complicated concept descriptions.\n\nTo remedy or at least to alleviate this effect of erroneous counterexamples we shall\nconsider an extension of Baader and Distel's results.  This extension tries to find bases\nof GCIs which are not necessarily valid in the given interpretation, but instead enjoy a\n\\emph{high confidence} therein.  The notion of \\emph{confidence} is borrowed from\ndata-mining~\\cite{arules:agrawal:association-rules}, more precisely from the theory of\n\\emph{association rules}, and allows to measure how much an association rule is allowed to\nignore counterexamples.  We shall transfer the notion of confidence to general concept\ninclusions, and shall then try to find bases for those \\emph{GCIs with high confidence}.\n\nFor this we shall make use of results obtained by Luxenburger from his work on\n\\emph{partial implications}~\\cite{diss:Luxenburger,Luxenburger91}, and extensions\nthereof~\\cite{DBLP:conf/ki/StummeTBPL01}.  Partial implications can be thought of as\nimplications considered together with their confidence in some particular formal context.\nWe shall discuss in \\Cref{Luxen-base} how these results allow us to obtain bases of all\nimplications which have \\emph{high confidence} in some given formal context.\n\nIn \\Cref{sec:first-base} then we show how these ideas can be simulated in \\ELgfpbot to\nfind bases for GCIs with high confidence.  Moreover, we shall show in\n\\Cref{sec:bases-confident-gcis} how bases of implications with high confidence yield bases\nof GCIs with high confidence.  We shall also discuss a way to \\emph{complete} sets of\nGCIs, \\ie how to obtain a set of valid GCIs that makes a given set of GCIs complete.  This\nresult is quite similar to \\Cref{thm:Felix-base-B3}, and we shall discuss it in\n\\Cref{sec:completing-sets-of-gcis}.  Finally, we shall see how to obtain \\ELbot bases from\n\\ELgfpbot bases for GCIs with high confidence, using the technique of unravelling\n\\ELgfpbot concept descriptions as discussed in \\Cref{sec:unrav-elgfpb-conc}.\n\nThe results thus obtained are again all effective, and we shall discuss some experiments\nin \\Cref{sec:exper-with-conf} that use the same data-set as the one used in\n\\Cref{sec:computing-bases-from}.  This allows us to directly compare the approaches of\ncomputing bases of valid GCIs on the one hand, and bases of GCIs with high confidence on\nthe other.  Moreover, we shall also discuss shortcomings of the approach of considering\nGCIs with high confidence, which will eventually lead us to considering extensions of the\nattribute exploration algorithm.  These will be discussed in \\Cref{cha:expl-conf} and\n\\Cref{cha:model-expl-conf}.\n\n\\section{Computing Bases from DBpedia}\n\\label{sec:computing-bases-from}\n\nWe want to evaluate the practicability of the results of Baader and Distel by applying\nthem to linked data extracted from the Linked Open Data Cloud.  In other words, given some\nlinked data, we want to extract a complete set of general concept inclusions that is valid\nwithin this data set.  The goal of this experiment is to see in how far Baader and\nDistel's approach is practical in learning terminological knowledge about some domain,\nthat is represented by linked data.\n\nOf course, before we can do so we first have to discuss how we can obtain an\ninterpretation from a given linked data set, and one which sufficiently reflects the\nlogical structure of the initial data set.\n\nRecall that a finite interpretation $\\mathcal{I} = (\\Delta^{\\mathcal{I}},\n\\cdot^{\\mathcal{I}})$ over $N_C$ and $N_R$ consists of a set $\\Delta^{\\mathcal{I}}$ and a\nmapping $\\cdot^{\\mathcal{I}}$ that maps every $A \\in N_C$ to a set $A^{\\mathcal{I}}\n\\subseteq \\Delta^{\\mathcal{I}}$, and every $r \\in N_R$ to a set of pairs $r^{\\mathcal{I}}\n\\subseteq \\Delta^{\\mathcal{I}} \\times \\Delta^{\\mathcal{I}}$.  We have also already seen\nsome examples of depicting interpretations as \\emph{graphs}, more precisely as\n\\emph{directed edge- and vertex-labeled graphs}.  Indeed, interpretations are essentially\nnothing else than those graphs, where the set of vertex labels is $N_C$ and the set of\nedge labels is $N_R$.\n\nLinked data is quite similar to labeled graphs.  More precisely, linked data is just an\nedge-labeled graph, represented by so-called \\emph{RDF-Triples} (where \\emph{RDF} stands\nfor \\emph{Resource Description Framework}).  Every triple consists of a \\emph{subject}, a\n\\emph{predicate}, and an \\emph{object} (in that order), each of them being an\n\\emph{uniform resource identifier} (URI).  The idea is that RDF-Triples encode the\ninformation that the subject is connected to the object by means of the predicate.  Two\nexamples of RDF-Triples, taken from the DBpedia data set~\\cite{DBpedia},\nare\\footnote{Indeed, these are \\emph{serializations} of RDF-Triples, in this case in the\n  so-called \\emph{N-Triples} format}\n\\begin{verbatim}\n  <http://dbpedia.org/resource/Aristotle>\n  <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>\n  <http://dbpedia.org/ontology/Philosopher> .\n\n  <http://dbpedia.org/resource/Aristotle>\n  <http://dbpedia.org/ontology/influenced>\n  <http://dbpedia.org/resource/Western_philosophy> .\n\\end{verbatim}\nIntuitively, these triples encode the facts that \\emph{Aristotle is (was) a philosopher}\nand that \\emph{Aristotle influenced Western Philosophy}.\n\nSince RDF-Triples constitute edge-labeled graphs, we can take them as they are and regard\nthem as interpretations over $N_C = \\emptyset$ and $N_R$, where $N_R$ is just the set of\nall predicates which appear in RDF-Triples in the data set.  This approach would work, but\nit would only yield GCIs where no concept names are present.  Such terminological\nknowledge may not be very interesting.\n\nTo alleviate this problem we make use of the special RDF predicate\n\\begin{equation}\n  \\label{eq:16}\n  \\verb|http://www.w3.org/1999/02/22-rdf-syntax-ns#type|\n\\end{equation}\nwhich expresses that a subject is an instance of a certain\nclass.\\footnote{\\url{http://www.w3.org/1999/02/22-rdf-syntax-ns}} If we consider triples\nwith this predicates not as edges in the linked graph, but instead as the information that\nthe subject is an instance of the object, then we indeed consider linked data as a vertex-\nand edge-labeled graph with vertex labels $N_C$ and edge-labels $N_R$, where $N_C$ is in\ngeneral not empty.\n\nThis view on linked data now allows us to consider it as an interpretation over some sets\n$N_C$ and $N_R$, and to apply Baader and Distel's results to such data sets.  For our\nexperiments, we have chosen a subset of the DBpedia data set as of March 2010 (Version\n3.5)\\footnote{\\url{http://wiki.dbpedia.org/Downloads35?v=pb8}}.  The linked data contained\nin the DBpedia data set has been extracted automatically from \\emph{Wikipedia Infoboxes},\nwhich mean to represent facts about the topic of the current page in a compact way.  An\nexample of such an Infobox is shown in \\Cref{fig:infobox-screenshot}.\n\n\\begin{figure}[tp]\n  \\centering\n  \\includegraphics[width=20em]{chapters/lincoln-infobox.png}\n  \\caption{Wikipedia Article about Abraham Lincoln with Infobox on its Right}\n  \\label{fig:infobox-screenshot}\n\\end{figure}\n\nThe subset of the DBpedia data set we use for our experiments arises by restricting our\nattention to the relation\n\\begin{equation*}\n  \\verb|http://dbpedia.org/ontology/child|.\n\\end{equation*}\nFrom this subset, we constructed an interpretation $\\Idbpedia = (\\Delta^{\\Idbpedia},\n\\cdot^{\\Idbpedia})$.  To make the considerations easier to read, we shall drop the prefix\n\\verb|http://dbpedia.org/ontology| in the following, and just write \\textsf{child} instead\nof \\texttt{http://dbpedia.org/ontology/child}, for example.\n\nTo construct $\\Idbpedia$ we first compute all triples $T_{\\mathsf{child}}$ from the\nDBpedia data set whose predicate is \\textsf{child}.  The subjects and objects of these\ntriples are collected into $\\Delta^{\\Idbpedia}$.  We then define\n\\begin{equation*}\n  \\mathsf{child}^{\\Idbpedia} := \\set{ (s, o) \\in \\Delta^\\Idbpedia \\times \\Delta^\\Idbpedia\n    \\mid (s, \\mathsf{child}, o) \\in T_{\\mathsf{child}} }.\n\\end{equation*}\nExamples for triples contained in $T_{\\mathsf{child}}$ are\n\\begin{verbatim}\n  <Abraham_Lincoln> <child> <Robert_Todd_Lincoln> .\n  <Abraham_Lincoln> <child> <Edward_Baker_Lincoln> .\n\\end{verbatim}\nTherefore,\n\\begin{align*}\n  (\\mathsf{Abraham\\_Lincoln}, \\mathsf{Robert\\_Todd\\_Lincoln}) &\\in \\mathsf{child}^{\\Idbpedia},\\\\\n  (\\mathsf{Abraham\\_Lincoln}, \\mathsf{Edward\\_Baker\\_Lincoln}) &\\in \\mathsf{child}^{\\Idbpedia}.\n\\end{align*}\n\nThen we consider all triples $T_{\\mathsf{type}}$ whose predicate is the special type\npredicate of \\Cref{eq:16} and whose subject is contained in $\\Delta^{\\Idbpedia}$.  The\nobjects of those triples are collected into a set $N_C$, \\ie they constitute the concept\nnames of $\\Idbpedia$.\\footnote{We omit \\texttt{http://www.w3.org/2002/07/owl\\#Thing} in\n  $N_C$, as it does not introduce any meaningful information.} Then, for an $A \\in N_C$,\nwe define $A^{\\Idbpedia}$ to be the set of all subjects that appear in a triple in\n$T_{\\mathsf{type}}$, \\ie\n\\begin{equation*}\n  A^{\\Idbpedia} := \\set{ s \\in \\Delta^{\\Idbpedia} \\mid (s, t, A) \\in\n    T_{\\mathsf{type}} }\n\\end{equation*}\nwhere $t$ stands for the special RDF type predicate of \\Cref{eq:16}.  Example triples from\n$T_{\\mathsf{type}}$ concerning \\verb|Abraham_Lincoln| are\n\\begin{verbatim}\n  <Abraham_Lincoln>\n  <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>\n  <Person> .\n\n  <Abraham_Lincoln>\n  <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>\n  <OfficeHolder> .\n\\end{verbatim}\nand therefore\n\\begin{align*}\n  \\mathsf{Abraham\\_Lincoln} &\\in \\mathsf{Person}^{\\Idbpedia}, \\\\\n  \\mathsf{Abraham\\_Lincoln} &\\in \\mathsf{OfficeHolder}^{\\Idbpedia}.\n\\end{align*}\n\nThe interpretation $\\Idbpedia$ then contains 5624 elements and 60 concept names, \\ie\n$\\abs{ N_C } = 60$.  By construction, there is only one role name in $\\Idbpedia$, namely\n\\textsf{child}.  To compute now bases of $\\Idbpedia$ means to extract all knowledge about\nthe child-relation present in DBpedia and expressible in \\ELbot.  Note that elements from\nDBpedia are only present in $\\Idbpedia$ if they have children, or are children of someone\nelse.  Moreover, as DBpedia extracts its information from Wikipedia, all elements in\n$\\Idbpedia$ correspond to articles in Wikipedia; in particular, if such elements\ncorrespond to persons, then those persons have to be \\enquote{sufficiently famous} in the\nsense that they deserve a Wikipedia article.  Therefore, $\\Idbpedia$ represent DBpedia's\nknowledge about famous persons and their famous children.\n\nWe have to note, however, that the \\textsf{child}-relation in DBpedia contains some false\ninformation, mostly due to the way this information is extracted from Wikipedia Infoboxes.\nMore precisely, our interpretation $\\Idbpedia$ not only contains elements which correspond\nto humans, but also contains elements which are instances of \\textsf{Work},\n\\textsf{Organisation} or \\textsf{PopulatedPlace}, among others.  However, those artifacts\nare comparably rare, and it is still reasonable to use $\\Idbpedia$ for our experiments.\n\nWe have implemented the algorithms devised by Baader and Distel to compute bases of finite\ninterpretations\\footnote{\\url{http://github.com/exot/EL-exploration}} on top of\n\\texttt{conexp-clj}\\footnote{\\url{http://github.com/exot/conexp-clj}}, a general purpose\ntool for formal concept analysis.  When computing a minimal base of $\\Idbpedia$ as\ndescribed in \\Cref{thm:Felix-5.18}, we obtain a base $\\mathcal{B}_{\\Idbpedia}$ containing\n1252 general concept inclusions.  In the following we want to examine the GCIs contained\nin this base, describe some observations we made, and discuss the usefulness of these\nGCIs.  Of course, we cannot do this formally, and shall therefore only argue intuitively.\n\nFirstly, some of the GCIs contained in $\\mathcal{B}_\\Idbpedia$ constitute knowledge about\nthe relationships among the concept names occurring in $\\Idbpedia$ only, for example\n\\begin{align*}\n  \\mathsf{Politician} &\\sqsubseteq \\mathsf{Person} \\\\\n  \\mathsf{MemberOfParliament} &\\sqsubseteq \\mathsf{Person \\sqcap Politician} \\\\\n  \\mathsf{Criminal \\sqcap Politician} &\\sqsubseteq \\bot\n\\end{align*}\nThis knowledge can indeed be useful to learn the hierarchy of concept names\n(\\emph{taxonomy}) of $\\Idbpedia$.  On the other hand, this does not yet show whether\ncomputing bases of $\\Idbpedia$ is useful, as the GCIs shown above could have easily been\nobtained by methods from formal concept analysis alone.\n\nThe last GCI states that there are no elements in $\\Idbpedia$ that are both criminal and\npoliticians.  GCIs of this form are called \\emph{disjointness constraints}, and they can\nbe useful in applications.  The disjointness constraints mentioned above contain only\nconcept names.  However, the approach by Baader and Distel enables us to find more\ndisjointness constraints than just those between concept names.  For example,\n$\\mathcal{B}_{\\Idbpedia}$ contains the GCI\n\\begin{equation*}\n   \\mathsf{Philosopher} \\sqcap \\exists \\mathsf{child}. \\top \\sqsubseteq \\bot\n\\end{equation*}\nexpressing that philosophers don't have children (or at least not children famous enough\nto occur in Wikipedia).  Indeed, since $\\mathcal{B}_{\\Idbpedia}$ is complete for\n$\\Idbpedia$, all disjointness constraints valid in $\\Idbpedia$ can either be found in this\nbase or are entailed by it.  Such information can be of practical relevance.\n\nThere are other GCIs contained in $\\mathcal{B}_\\Idbpedia$ which are not disjointness\nconstraints or only express knowledge about concept names.  Two of them for which we could\nargue that they can be useful are\n\\begin{align*}\n  \\mathsf{\\exists child. Person} &\\sqsubseteq \\mathsf{Person}, \\\\\n  \\mathsf{FictionalCharacter \\sqcap \\exists child. Person} &\\sqsubseteq \\mathsf{\\exists\n    child. FictionalCharacter}\n\\end{align*}\nwhere the second GCI can be seen as a certain kind of \\ELbot approximation of the fact\nthat fictional characters can only have fictional characters as their children.  These\nGCIs can indeed be seen as useful terminological knowledge for the domain represented by\n$\\Idbpedia$.\n\nThose GCIs, where one could say that they represent meaningful knowledge, are quite rare\nin $\\mathcal{B}_\\Idbpedia$.  On the other hand, $\\mathcal{B}_\\Idbpedia$ contains many GCIs\nwhose usefulness is highly doubtful, either because they combine otherwise unrelated\nconcepts, or they are too specific.\n\nAn example for the first case is\n\\begin{equation*}\n  \\mathsf{Person \\sqcap \\exists child. Book \\sqsubseteq FictionalCharacter}\n\\end{equation*}\nwhich does not really represent any meaningful knowledge.  On the other hand, this GCI\nindicates that DBpedia finds books as children only on Wikipedia pages on fictional\ncharacters.  Thus, such GCIs may help to find errors in the way DBpedia extracts\ninformation, but are not helpful as knowledge themselves.  Similar examples are\n\\begin{align*}\n  \\mathsf{\\exists child. Newspaper \\sqcap Person} &\\sqsubseteq \\mathsf{Writer}, \\\\\n  \\mathsf{\\exists child. MilitaryUnit} &\\sqsubseteq \\mathsf{Judge}, \\\\\n  \\mathsf{\\exists child. Settlement \\sqcap Politician} &\\sqsubseteq \\mathsf{Congressman}.\n\\end{align*}\n\nGCIs that can be considered as being too specific are the most common case among all GCIs\nin $\\mathcal{B}_{\\Idbpedia}$, examples of them being\n\\begin{gather*}\n  \\mathsf{\\exists child. Ambassador \\sqcap OfficeHolder} \\\\\n  \\sqsubseteq \\mathsf{\\exists child. (Ambassador \\sqcap \\exists child. Person) \\sqcap {}}\\\\\n  \\phantom{\\sqsubseteq{}} \\mathsf{\\exists child. (OfficeHolder \\sqcap \\exists child.\n  Congressman \\sqcap \\exists child. Actor \\sqcap \\exists child OfficeHolder)}.\n\\end{gather*}\nIndeed, this GCI only applies to the individual \\texttt{Joseph\\_P.\\_Kennedy\\%2C\\_Sr.}, and\nthus it states information only about this very individual and its children.  We can\nhandle such situations in principle by using \\emph{model exploration}, which allows for\nexpert interaction in a similar way as attribute exploration does: if during model\nexploration the expert would encounter such a GCI as shown above, she would reject it as\nbeing too specific, and would provide counterexamples for it.  We shall discuss this\nalgorithm in more detail in \\Cref{cha:model-expl-conf}.\n\nAnother approach to eliminating those over-specific GCIs could be to demand that the\nextracted GCIs apply to at least a certain number of different individuals.  See\n\\Cref{cha:conclusions} for more details on this.\n\nFinally, among the GCIs contained in $\\mathcal{B}_\\Idbpedia$ there exist some which convey\nthe impression of being redundant, like\n\\begin{equation*}\n  \\mathsf{\\exists child. \\exists child. \\top \\sqsubseteq \\exists child. (Person \\sqcap \\exists child. \\top)},\n\\end{equation*}\nbecause it should be quite clear from the construction of $\\Idbpedia$ that only persons\ncan have children, \\ie the following GCI\n\\begin{equation}\n  \\label{eq:23}\n  \\mathsf{\\exists child. \\top \\sqsubseteq Person}\n\\end{equation}\nshould hold in $\\Idbpedia$.  The reason for that is that only Wikipedia articles of human\nbeings should contain a child-entry within their Infobox.  Thus, even with all the errors\nin $\\Idbpedia$ concerning non-persons that we have discussed before, the GCI in\n\\Cref{eq:23} should hold in $\\Idbpedia$.\n\nHowever, this is not the case, since there are four counterexamples to this GCI in\n$\\Idbpedia$, \\ie elements $x \\in \\Delta^{\\Idbpedia}$ satisfying $x \\in (\\mathsf{\\exists\n  child. \\top})^{\\Idbpedia} \\setminus \\mathsf{Person}^{\\Idbpedia}$.  These\nare\\footnote{Coincidentally, all these are artists from Hong Kong.}\n\\begin{equation*}\n  \\mathtt{Teresa\\_Carpio},\\; \\mathtt{Charles\\_Heung},\\;\n  \\mathtt{Adam\\_Cheng}, \\; \\mathtt{Lydia\\_Shum}.\n\\end{equation*}\nHowever, these elements represent human beings, so they \\emph{should} actually be\ninstances of \\textsf{Person}.  In other words, these counterexamples are all\n\\emph{erroneous} counterexamples, but since they are present in $\\Idbpedia$, the approach\ndeveloped by Baader and Distel will not ignore them.  This not only inhibits finding the\nGCI $\\mathsf{\\exists child. \\top \\sqsubseteq Person}$, but also causes incomprehensible\nGCIs to be found, which are special cases of this GCI but somehow try to\n\\enquote{circumvent} the erroneous counterexamples. An example for this is\n\\begin{gather*}\n  \\mathsf{Person \\sqcap \\exists child. (Person \\sqcap \\exists child. (Person \\sqcap \\exists child.\n    (Person \\sqcap {}}\\\\\n  \\quad \\quad \\mathsf{\\exists child. \\exists child. (Person \\sqcap \\exists child. \\top))))}\n  \\\\\n  \\mathsf{ \\quad \\sqsubseteq\n    \\exists child. (Person \\sqcap \\exists child. (Person \\sqcap \\exists child. (Person \\sqcap\n    \\exists child. (Person \\sqcap {}}\\\\\n  \\mathsf{\\quad \\quad \\exists child. \\exists child. Person))))}.\n\\end{gather*}\n\n\\section{GCIs with High Confidence in Finite Interpretations}\n\\label{sec:confident-gcis}\n\nIt would certainly increase the applicability of Baader and Distel's approach if we could\nignore erroneous counterexamples in our data, as then we could extract simpler and more\ngeneral GCIs from this data.  However, we cannot expect to have an automatic procedure\nwhich achieves this goal, \\ie we cannot expect an algorithm that automatically ignores\nerroneous counterexamples.  The reason for that is that the algorithm would need to know\nhow to distinguish errors in the current domain of interest, and for this the algorithm\nwould need to possess knowledge about this domain, which however we are just about to\nlearn.\n\nOn the other hand, we can assume is our initially given interpretation $\\mathcal{I}$\ncontains only \\emph{few} errors, as otherwise learning GCIs from it would be futile.\nBased on this assumption we can approach the problem of erroneous counterexamples as\nfollows: in the case that $\\mathcal{I}$ contains much more \\emph{positive examples} for a\nGCI $C \\sqsubseteq D$ than \\emph{negative} ones, we assume that the negative\ncounterexamples are \\enquote{probably erroneous.}  Here, a \\emph{positive example} for $C\n\\sqsubseteq D$ would be an element $x \\in \\Delta^{\\mathcal{I}}$ satisfying $x \\in\nC^{\\mathcal{I}} \\cap D^{\\mathcal{I}}$, and a \\emph{negative example} for $C \\sqsubseteq D$\nwould be an element $y \\in \\Delta^{\\mathcal{I}}$ such that $y \\in C^{\\mathcal{I}}\n\\setminus D^{\\mathcal{I}}$.  We can consider a GCI to be \\enquote{almost valid} in\n$\\mathcal{I}$ if the number of positive examples is much higher than the number of\nnegative ones.  The approach to ignore erroneous counterexamples would then consider these\n\\enquote{almost valid} GCIs in addition to the valid ones, and try to find finite bases\nfor both of them.\n\nThis actually works quite well for our example interpretation $\\Idbpedia$, as\n$\\mathsf{\\exists child. \\top \\sqsubseteq Person}$ has much more positive than negative\nexamples: there are 2551 elements $x \\in \\Delta^{\\Idbpedia}$ to which $\\mathsf{\\exists\n  child. \\top \\sqsubseteq Person}$ applies, \\ie they satisfy $x \\in (\\mathsf{\\exists\n  child. \\top})^{\\Idbpedia}$, but only 4 of those (the ones mentioned above) fail to also\nsatisfy $x \\in \\mathsf{Person}^{\\Idbpedia}$.  Therefore, $\\mathsf{\\exists child. \\top\n  \\sqsubseteq Person}$ has 2547 positive examples, but only 4 negative ones.  By our\napproach, we can consider these negative examples as errors and ignore them.  Thus,\n$\\mathsf{\\exists child. \\top \\sqsubseteq Person}$ would be extracted from $\\Idbpedia$.\n\nOf course, this approach is highly heuristic: if valid counterexamples for a GCI $C\n\\sqsubseteq D$ are just \\emph{rare} in $\\mathcal{I}$, then the above sketched approach\nwould treat them as errors, which is incorrect.  On the other hand, it may be much more\ndesirable to extract GCIs which are \\emph{wrong} in some application domain, than to miss\nGCIs which are \\emph{correct}, as long as not too many wrong GCIs are being extracted.\nThis is because identifying wrong GCIs can be considered much easier than finding correct\nGCIs that are just invalidated by errors in the data.\n\nIt is the purpose of this section to give a formalization of the notion of a GCI to be\n\\enquote{almost valid} in some finite interpretation.  We shall base this formalization on\nthe notion of \\emph{confidence} as it is used in\ndata-mining~\\cite{arules:agrawal:association-rules}.  Our goal is then to find\n\\emph{finite bases} of all GCIs which enjoy a \\emph{high confidence} in the initially\ngiven interpretation.\n\n\\subsection{Confidence of GCIs and Confident Bases}\n\\label{sec:conf-gcis-conf}\n\nWe argued intuitively that the number of positive examples should be \\enquote{much higher}\nthan the number of negative examples.  To formalize this notion, we define the\n\\emph{confidence} of $C \\sqsubseteq D$ in $\\mathcal{I}$ as follows.\n\n\\begin{Definition}[Confidence of GCIs]\n  \\label{def:gci-confidence}\n  Let $\\mathcal{I} = (\\Delta^{\\mathcal{I}}, \\cdot^{\\mathcal{I}})$ be a finite\n  interpretation over $N_C$ and $N_R$, and let $C, D \\in \\ELgfpbot(N_C, N_R)$.  Then the\n  \\emph{confidence} of $C \\sqsubseteq D$ in $\\mathcal{I}$, written as\n  $\\conf_{\\mathcal{I}}(C \\sqsubseteq D)$, is defined as\n  \\begin{equation*}\n    \\conf_{\\mathcal{I}}( C \\sqsubseteq D ) =\n    \\begin{cases}\n      1 & C^{\\mathcal{I}} = \\emptyset \\\\\n      \\frac{\\abs{ (C \\sqcap D)^{\\mathcal{I}} }}{\\abs{ C^{\\mathcal{I}} }} & \\text{otherwise.}\n    \\end{cases}\n  \\end{equation*}\n\\end{Definition}\nNote that $(C \\sqcap D)^{\\mathcal{I}}$ is just the number of positive examples for $C\n\\sqsubseteq D$ in $\\mathcal{I}$, and that $\\abs{C^{\\mathcal{I}}}$ is just the number of\nall elements to which $C \\sqsubseteq D$ applies, \\ie the number of all positive and\nnegative examples.  Therefore, $\\conf_{\\mathcal{I}}(C \\sqsubseteq D)$ measures the amount\nof positive examples against the number of all elements to which $C \\sqsubseteq D$\napplies: the higher the confidence of $C \\sqsubseteq D$ in $\\mathcal{I}$, the more the\nnumber of positive examples is higher than the number of negative ones.\n\n\\begin{Example}\n  \\label{expl:Idbpedia-confidence}\n  Recall that $\\mathsf{\\exists child. \\top \\sqsubseteq Person}$ has 2547 positive and 4\n  negative examples in $\\Idbpedia$, thus\n  \\begin{equation*}\n    \\conf_\\Idbpedia( {\\mathsf{\\exists child. \\top \\sqsubseteq Person} } ) = \\frac{ 2547 }{\n      2551 } \\approx 0.998.\n  \\end{equation*}\n\\end{Example}\n\nTo use the confidence of GCIs in finite interpretations to formalize the notion of being\n\\enquote{almost true} we need to choose a \\emph{threshold} above which we can say that the\nnumber of positive examples is \\enquote{much higher} than the number of negative ones.\n\n\\begin{Definition}[Confidence-Based Theory of Finite Interpretations]\n  \\label{def:confident-theory-of-interpretations}\n  Let $\\mathcal{I}$ be a finite interpretation over $N_C$ and $N_R$, and let $c \\in [0,\n  1]$.  Then the \\emph{confidence-based theory} $\\Th_{c}(\\mathcal{I})$ of $\\mathcal{I}$\n  \\emph{with threshold $c$} is defined as\n  \\begin{equation*}\n    \\Th_c(\\mathcal{I}) := \\set{ C \\sqsubseteq D \\mid C, D \\in \\ELgfpbot(N_C, N_R),\n      \\conf_{\\mathcal{I}}( C \\sqsubseteq D ) \\ge c }.\n  \\end{equation*}\n  We say that GCIs in $\\Th_c(\\mathcal{I})$ have \\emph{high confidence} (with respect to\n  the threshold $c$).  Sometimes, we may call the elements of $\\Th_c(\\mathcal{I})$ just\n  \\emph{confident GCIs}.\n\\end{Definition}\n\nNote that in general the set $\\Th_c(\\mathcal{I})$ is not closed under entailment.\n\nNote that $C \\sqsubseteq D$ has confidence 1 in $\\mathcal{I}$ if and only if $C\n\\sqsubseteq D$ holds in $\\mathcal{I}$.  Therefore, $\\Th(\\mathcal{I}) \\subseteq\n\\Th_c(\\mathcal{I})$, and thus the set $\\Th_c(\\mathcal{I})$ is also infinite in general\n(\\ie when $N_R \\neq \\emptyset$).  Thus, again we want to find \\emph{finite bases}, this\ntime of the set $\\Th_c(\\mathcal{I})$.  Recall that a set $\\mathcal{B}$ of general concept\ninclusions is a base of $\\Th_c(\\mathcal{I})$ if it is sound and complete for\n$\\Th_c(\\mathcal{I})$, \\ie if all GCIs in $\\mathcal{B}$ are entailed by\n$\\Th_c(\\mathcal{I})$ and vice versa.\n\nNotice, however, that since $\\Th_c(\\mathcal{I})$ is not closed under entailment it may\nhappen that $\\mathcal{B} \\not\\subseteq \\Th_c(\\mathcal{I})$.  On the other hand, it may be\ndesirable to have bases $\\mathcal{B}$ of $\\Th_c(\\mathcal{I})$ where the GCIs contained in\nthis base have high confidence as well, \\ie they satisfy $\\mathcal{B} \\subseteq\n\\Th_c(\\mathcal{I})$.  We shall call such bases \\emph{confident bases} of\n$\\Th_c(\\mathcal{I})$.\n\n\\subsection{Luxenburger's Base}\n\\label{Luxen-base}\n\nBefore we consider finite bases and finite confident bases of $\\Th_c(\\mathcal{I})$, let us\nfirst consider the analogous problem in formal concept analysis, which is to find small\nbases of \\emph{implications with high confidence} in a given formal context.  The relevant\nresults of this discussion mainly go back to results by Luxenburger on \\emph{partial\n  implications}~\\cite{diss:Luxenburger,Luxenburger91}, and extensions\nthereof~\\cite{DBLP:conf/ki/StummeTBPL01}.  We shall first discuss these results, however\nnot in their original form, but instead in a way suitable for our considerations.\n\nWe have already defined the notion of confidence of a GCI in some given finite\ninterpretation.  The analogous notion in formal concept analysis is the confidence of an\nimplication in a formal context.\n\n\\begin{Definition}[Confidence of Implications]\n  \\label{def:confidence-of-implications}\n  Let $\\con K = (G, M, I)$ be a finite formal context, and let $(A \\to B) \\in \\Imp(M)$.\n  Then the \\emph{confidence} of $A \\to B$ in $\\con K$ is defined as\n  \\begin{equation*}\n    \\conf_{\\con K}(A \\to B) :=\n    \\begin{cases}\n      1 & A' = \\emptyset \\\\\n      \\frac{ \\abs{ (A \\cup B)' } } { \\abs{ A' } } & \\text{otherwise}.\n    \\end{cases}\n  \\end{equation*}\n\\end{Definition}\n\nWe can now consider an implication to have \\emph{high confidence} in a formal context if\nand only if it is above a certain threshold $c \\in [0,1]$.\n\n\\begin{Definition}[Confidence-Based Theory of Finite Formal Contexts]\n  \\label{def:theory-with-threshold-for-formal-contexts}\n  Let $\\con K = (G, M, I)$ be a finite formal context, and let $c \\in [0,1]$.  The\n  \\emph{confidence-based theory} of $\\con K$ \\emph{with threshold $c$} is defined as\n  \\begin{equation*}\n    \\Th_c(\\con K) := \\set{ (A \\to B) \\in \\Imp(M) \\mid \\conf_{\\con K}(A \\to B) \\ge c }.\n  \\end{equation*}\n  An implication $(A \\to B) \\in \\Imp(M)$ is said to have \\emph{high confidence} in $\\con\n  K$ if and only if $(A \\to B) \\in \\Th_c(\\con K)$.  Sometimes, those implications are also\n  called \\emph{confident implications}.\n\\end{Definition}\n\nWe now want to find small bases of $\\Th_c(\\con K)$ for finite formal contexts $\\con K =\n(G, M, I)$ and $c \\in [0,1]$.  Of course, the term \\enquote{small} is rather subjective\nhere, but recall that the main purpose of this discussion is to obtain a finite base of\n$\\Th_c(\\con K)$ which, when transferred to the side of description logics, stays finite.\nThe main idea in that direction is that, if an interpretation $\\mathcal{I}$ is finite,\nthen it only has finitely many model-based most-specific concept descriptions (up to\nequivalence).  Since model-based most-specific concept descriptions are in a one-to-one\ncorrespondence to the intents of the induced context $\\con K_{\\mathcal{I}}$ of\n$\\mathcal{I}$, finding a base of $\\Th_c(\\con K)$ which only contains intents of $\\con K$\nis likely suitable for our purpose.\n\nTo compute such a base of $\\Th_c(\\con K)$ we first observe that, as in the case of GCIs,\nan implication $(A \\to B)$ holds in $\\con K$ if and only if its confidence in $\\con K$ is\n1.  Therefore, $\\Th(\\con K) \\subseteq \\Th_c(\\con K)$ is true for all $c \\in [0,1]$.\nFurthermore, we already know how to compute bases of $\\Th(\\con K)$.  Thus, if\n$\\mathcal{L}$ is a base of $\\Th(\\con K)$, to find a base of $\\Th_c(\\con K)$ it is enough\nto compute bases of $\\Th_c(\\con K)$ with background knowledge $\\mathcal{L}$.\n\nThe first crucial observation now is the well-known fact that\n\\begin{equation*}\n  \\conf_{\\con K}(A \\to B) = \\conf_{\\con K}(A'' \\to B'')\n\\end{equation*}\nis always true for $(A \\to B) \\in \\Imp(M)$, because $A''' = A'$ and\n\\begin{align*}\n  (A \\cup B)' &= A' \\cap B' \\\\\n  &= A''' \\cap B'''\\\\\n  &= (A'' \\cup B'')'.\n\\end{align*}\nBut then $\\set{ A'' \\to B'' } \\models (A \\to B)$, so it is enough to consider only\nimplications where both premise and conclusion are intents of $\\con K$.  The following\nlemma makes use of this observation.\n\n\\begin{Lemma}\n  \\label{lem:confident-base-of-formal-context}\n  Let $\\con K = (G, M, I)$ be a formal context, let $c \\in [0,1]$ and let $\\mathcal{L}$ be\n  a base of $\\con K$.  Then the set\n  \\begin{equation*}\n    \\Conf(\\con K, c) := \\set{ A'' \\to B'' \\mid A \\subseteq B \\subseteq M, 1 > \\conf_{\\con\n        K}(A'' \\to B'') \\ge c}\n  \\end{equation*}\n  is a confident base of $\\Th_c(\\con K)$ with background knowledge $\\mathcal{L}$.\n\\end{Lemma}\n\\begin{Proof}\n  We first observe that for $A, B \\subseteq M$ it is true that\n  \\begin{equation*}\n    \\set{ A'' \\to (A \\cup B)'' } \\models (A'' \\to B''),\n  \\end{equation*}\n  because $B'' \\subseteq (A \\cup B)''$.  Then if $(X \\to Y) \\in \\Th_c(\\con K)$, then\n  \\begin{equation*}\n    \\mathcal{L} \\models (X \\to X''),\n  \\end{equation*}\n  and thus\n  \\begin{equation*}\n    \\mathcal{L} \\cup \\set{ X'' \\to (X \\cup Y)''} \\models (X \\to Y).\n  \\end{equation*}\n  Furthermore,\n  \\begin{equation*}\n    \\conf_{\\con K}(X'' \\to (X \\cup Y)'') = \\conf_{\\con K}(X \\to Y) \\ge c,\n  \\end{equation*}\n  therefore $(X'' \\to (X \\cup Y)'') \\in \\Conf(\\con K, c)$.  Thus\n  \\begin{equation*}\n    \\mathcal{L} \\cup \\Conf(\\con K, c) \\models (X \\to Y)\n  \\end{equation*}\n  and therefore $\\Conf(\\con K, c)$ is a base of $\\Th_c(\\con K)$ with background knowledge\n  $\\mathcal{L}$.\n\\end{Proof}\n\nThe set $\\Conf(\\con K, c)$ can be further reduced by the following, well-known\nobservation.\n\n\\begin{Lemma}\n  \\label{lem:chain-rule-for-confidence}\n  Let $\\con K = (G, M, I)$ be a finite formal context, and let $A \\subseteq B \\subseteq C\n  \\subseteq M$.  Then\n  \\begin{equation}\n    \\label{eq:24}\n    \\conf_{\\con K}(A \\to C) = \\conf_{\\con K}(A \\to B) \\cdot \\conf_{\\con K}(B \\to C).\n  \\end{equation}\n\\end{Lemma}\n\\begin{Proof}\n  If $A' = \\emptyset$, then $B' = C' = \\emptyset$, and both sides of the equation are 1.\n  If $A' \\neq \\emptyset$ but $B' = \\emptyset$, then $C' = \\emptyset$ and both sides of the\n  equation are 0.  In both cases, equality holds.\n\n  Now let $A' \\neq \\emptyset \\neq B'$.  Then we can easily compute\n  \\begin{align*}\n    \\conf_{\\con K}(A \\to C)\n    &= \\frac{ \\abs{ (A \\cup C)' } }{ \\abs{ A' } } \\\\\n    &= \\frac{ \\abs{ (A \\cup B)' } }{ \\abs{ A' } } \\cdot\n    \\frac{ \\abs{ (A \\cup C)' } }{ \\abs{ (A \\cup B)' } }\n  \\intertext{and since $A \\subseteq B \\subseteq C$ it is true that $A \\cup B = B$ and $A\n    \\cup C = C = B \\cup C$, thus we can continue}\n    \\conf_{\\con K}(A \\to C)\n    &= \\frac{ \\abs{ (A \\cup B)' } }{ \\abs{ A' } } \\cdot\n    \\frac{ \\abs{ (B \\cup C)' } }{ \\abs{ B' } } \\\\\n    &= \\conf_{\\con K}(A \\to B) \\cdot \\conf_{\\con K}(B \\to C)\n  \\end{align*}\n  and the claim is proven.\n\\end{Proof}\n\nA simple consequence of this lemma is that if $A'' \\subsetneq B'' \\subsetneq C''$ and\n$(A'' \\to C'') \\in \\Conf(\\con K, c)$, then $(A'' \\to B''), (B'' \\to C'') \\in \\Conf(\\con K,\nc)$ and since\n\\begin{equation*}\n  \\set{ A'' \\to B'', B'' \\to C'' } \\models (A'' \\to C'')\n\\end{equation*}\nthe implication $A'' \\to C''$ is dispensable in $\\Conf(\\con K, c)$, and can thus be\nremoved without any harm.\n\n\\begin{Theorem}\n  \\label{thm:luxenburger-base}\n  Let $\\con K = (G, M, I)$ be a finite formal context, and let $c \\in [0,1]$.  Let\n  $\\mathcal{L}$ be a base of $\\con K$.  Then\n  \\begin{multline*}\n    \\Lux(\\con K, c) := \\{\\, (A'' \\to C'') \\mid A \\subseteq C \\subseteq M, 1 > \\conf_{\\con\n      K}(A'' \\to C'') \\ge c, \\\\ \\nexists B \\subseteq M \\st A'' \\subsetneq B'' \\subsetneq\n    C'' \\,\\}\n  \\end{multline*}\n  is a confident base of $\\Th_c(\\con K)$ with background knowledge $\\mathcal{L}$.\n\\end{Theorem}\n\nThe proof of this theorem is inspired by a similar proof\nfrom~\\cite{DBLP:conf/ki/StummeTBPL01}.\n\n\\begin{Proof}\n  Let $(A'' \\to C'') \\in \\Conf(\\con K, c)$.  Then it is enough to show that\n  \\begin{equation*}\n    \\Lux(\\con K, c) \\models (A'' \\to C'').\n  \\end{equation*}\n  Because $(A'' \\to C'') \\in \\Conf(\\con K, c)$ it is true that $A'' \\subsetneq C''$.\n  Since $\\con K$ is finite, the lattice of all intents of $\\con K$ is finite, as well.\n  Therefore, there exists a chain of intents\n  \\begin{equation*}\n    B_0 = A'' \\subsetneq B_1 \\subsetneq B_2 \\subsetneq \\dots \\subsetneq B_{n-1} \\subsetneq B_n = C''\n  \\end{equation*}\n  such that for all $i \\in \\set{ 0, \\dots, n-1 }$ there is no intent $D$ satisfying $B_i\n  \\subsetneq D \\subsetneq B_{i+1}$.  Then, by induction,\n  \\Cref{lem:chain-rule-for-confidence} yields\n  \\begin{equation*}\n    \\conf_{\\con K}(A'' \\to C'') = \\prod_{i = 0}^{n-1} \\conf_{\\con K}(B_i \\to B_{i+1}).\n  \\end{equation*}\n  Since $\\conf_{\\con K}(B_i \\to B_{i+1}) \\in [0,1]$, this yields\n  \\begin{equation*}\n    \\conf_{\\con K}(B_i \\to B_{i+1}) \\ge \\conf_{\\con K}(A'' \\to C'') \\ge c\n  \\end{equation*}\n  and therefore $(B_i \\to B_{i+1}) \\in \\Lux(\\con K, c)$ for $i \\in \\set{0, \\dots, n-1}$.  Thus,\n  \\begin{equation*}\n    \\Lux(\\con K, c) \\models (A'' \\to C'')\n  \\end{equation*}\n  as required.\n\\end{Proof}\n\nClearly we can weaken the prerequisites of this theorem as follows: instead of considering\nthe whole set $\\Lux(\\con K, c)$, a subset $\\mathcal{B} \\subseteq \\Lux(\\con K, c)$ that is\ncomplete for $\\Lux(\\con K, c)$ is just sufficient.  Moreover, it is not necessary to\nconsider only bases $\\mathcal{L}$ of $\\con K$.  Instead, it is sufficient to take a set\n$\\mathcal{L} \\subseteq \\Th(\\con K)$ such that $\\mathcal{L} \\cup \\mathcal{B}$ is complete\nfor $\\con K$.\n\n\\begin{Corollary}\n  \\label{cor:weakened-luxenburger-base}\n  Let $\\con K = (G, M, I)$ be a finite formal context, and let $c \\in [0,1]$.  If\n  $\\mathcal{B} \\subseteq \\Th_c(\\con K)$ is complete for $\\Lux(\\con K, c)$, and if\n  $\\mathcal{L} \\subseteq \\Th(\\con K)$ satisfies that $\\mathcal{L} \\cup \\mathcal{B}$ is\n  complete for $\\Th(\\con K)$, then $\\mathcal{B}$ is a confident base of $\\Th_c(\\con K)$\n  with background knowledge $\\mathcal{L}$.\n\\end{Corollary}\n\n\\subsection{A Luxenburger-Style Base of all GCIs with High Confidence}\n\\label{sec:first-base}\n\nWe can now use the results about confident bases of implications with high confidence to\nobtain confident bases of GCIs with high confidence.  For this, we simply adapt the\nresults of the previous section and prove them again in the setting of description logics.\nNotice that because of this, the following section is very similar to the previous one.\n\nWe start with the observation that the confidence of GCIs does not change if we switch to\nmodel-based most-specific concept descriptions.\n\n\\begin{Lemma}\n  \\label{lem:confidence-stays-under-mmsc}\n  Let $\\mathcal{I} = (\\Delta^{\\mathcal{I}}, \\cdot^{\\mathcal{I}})$ be a finite\n  interpretation over $N_C$ and $N_R$, and let $C$ and $D$ be $\\ELgfpbot$ concept\n  descriptions over $N_{C}$ and $N_{R}$.  Then\n  \\begin{equation*}\n    \\conf_{\\mathcal{I}}( C \\sqsubseteq D ) = \\conf_{\\mathcal{I}}(\n    C^{\\mathcal{I}\\mathcal{I}} \\sqsubseteq D^{\\mathcal{I}\\mathcal{I}}).\n  \\end{equation*}\n\\end{Lemma}\n\\begin{Proof}\n  The idea is the same as in the case of confidence of implications, just with a different\n  notation.\n\n  Since $C^{\\mathcal{I}} = C^{\\mathcal{I}\\mathcal{I}\\mathcal{I}}$, we have that\n  $C^{\\mathcal{I}} = \\emptyset$ if and only if $C^{\\mathcal{I}\\mathcal{I}\\mathcal{I}} =\n  \\emptyset$.  In this case, both sides of the equation are 1 and equality holds.\n\n  Let $C^{\\mathcal{I}} \\neq \\emptyset$.  Then $C^{\\mathcal{I}\\mathcal{I}\\mathcal{I}} \\neq\n  \\emptyset$, and we can compute\n  \\begin{align*}\n    \\conf_{\\mathcal{I}}( C \\sqsubseteq D )\n    &= \\frac{ \\abs{ (C \\sqcap D)^{\\mathcal{I}} } }{ \\abs{ C^{\\mathcal{I}} } } \\\\\n    &= \\frac{ \\abs{ C^{\\mathcal{I}} \\cap D^{\\mathcal{I}} } }{ \\abs{ C^{\\mathcal{I}} } }\n    \\\\\n    &= \\frac{ \\abs{ C^{\\mathcal{I}\\mathcal{I}\\mathcal{I}} \\cap\n        D^{\\mathcal{I}\\mathcal{I}\\mathcal{I}} } }{ \\abs{\n        C^{\\mathcal{I}\\mathcal{I}\\mathcal{I}} } } \\\\\n    &= \\conf_{\\mathcal{I}}( C^{\\mathcal{I}\\mathcal{I}} \\sqsubseteq\n    D^{\\mathcal{I}\\mathcal{I}} )\n  \\end{align*}\n  as required.\n\\end{Proof}\n\nFrom this fact we can now derive the analog of \\Cref{lem:chain-rule-for-confidence}.\n\n\\begin{Theorem}\n  \\label{thm:conf-base}\n  Let $\\mathcal{I} = (\\Delta^{\\mathcal{I}}, \\cdot^{\\mathcal{I}})$ be a finite\n  interpretation over $N_C$ and $N_R$, and let $\\mathcal{B}$ be a finite base of\n  $\\mathcal{I}$.  Let $c \\in [0,1]$ and define\n  \\begin{equation*}\n    \\Conf(\\mathcal{I}, c) := \\set{ X^{\\mathcal{I}} \\sqsubseteq Y^{\\mathcal{I}} \\mid Y\n      \\subseteq X \\subseteq \\Delta^{\\mathcal{I}}, 1 > \\conf_{\\mathcal{I}}( X^{\\mathcal{I}}\n      \\sqsubseteq Y^{\\mathcal{I}} ) \\ge c }.\n  \\end{equation*}\n  Then the set $\\Conf(\\mathcal{I}, c) \\cup \\mathcal{B}$ is a finite confident base of\n  $\\Th_c(\\mathcal{I})$.\n\\end{Theorem}\n\nIn the definition of $\\Conf(\\mathcal{I}, c)$ we consider of course all GCIs only up to\nequivalence: if $(X^{\\mathcal{I}} \\sqsubseteq Y^{\\mathcal{I}}), (\\overline X^{\\mathcal{I}}\n\\sqsubseteq \\overline Y^{\\mathcal{I}}) \\in \\Conf(\\mathcal{I}, c)$ are such that\n$X^{\\mathcal{I}} \\equiv \\overline X^{\\mathcal{I}}, Y^{\\mathcal{I}} \\equiv \\overline\nY^{\\mathcal{I}}$, we only keep one of these GCIs in $\\Conf(\\mathcal{I}, c)$, and discard\nthe other one.\n\n\\begin{Proof}\n  Clearly, $\\Conf(\\mathcal{I}, c) \\cup \\mathcal{B} \\subseteq \\Th_c(\\mathcal{I})$.\n  Furthermore, since $\\Delta^{\\mathcal{I}}$ is finite, $\\Conf(\\mathcal{I}, c)$ is finite\n  as well.  Thus, it remains to show that $\\Conf(\\mathcal{I}, c) \\cup \\mathcal{B}$ is\n  complete for $\\Th_c(\\mathcal{I})$.\n\n  Let $(C \\sqsubseteq D) \\in \\Th_c(\\mathcal{I})$.  If $C \\sqsubseteq D$ is valid in\n  $\\mathcal{I}$, then it is entailed by $\\mathcal{B}$, and nothing remains to be shown.\n\n  Therefore, let $C \\sqsubseteq D$ be not valid in $\\mathcal{I}$.  Then observe that $C\n  \\sqsubseteq D$ is entailed by $C \\sqsubseteq C \\sqcap D$.  Furthermore, $\\mathcal{B}$\n  entails $C \\sqsubseteq C^{\\mathcal{I}\\mathcal{I}}$, and thus\n  \\begin{equation*}\n    \\conf_{\\mathcal{I}}( C \\sqsubseteq D ) = \\conf_{\\mathcal{I}}( C \\sqsubseteq C \\sqcap D\n    ) = \\conf_{\\mathcal{I}}( C^{\\mathcal{I}\\mathcal{I}} \\sqsubseteq (C \\sqcap\n    D)^{\\mathcal{I}\\mathcal{I}} )\n  \\end{equation*}\n  by \\Cref{lem:confidence-stays-under-mmsc}, and since $(C \\sqsubseteq D) \\in\n  \\Th_c(\\mathcal{I})$ we obtain\n  \\begin{equation*}\n    (C^{\\mathcal{I}\\mathcal{I}} \\sqsubseteq (C \\sqcap D)^{\\mathcal{I}\\mathcal{I}}) \\in\n    \\Conf(\\mathcal{I}, c)\n  \\end{equation*}\n  by choosing $X = C^{\\mathcal{I}}$ and $Y = (C \\sqcap D)^{\\mathcal{I}}$.  But then\n  \\begin{equation*}\n    \\Conf(\\mathcal{I}, c) \\cup \\mathcal{B} \\models (C \\sqsubseteq\n    C^{\\mathcal{I}\\mathcal{I}}), (C^{\\mathcal{I}\\mathcal{I}} \\sqsubseteq (C \\sqcap\n    D)^{\\mathcal{I}\\mathcal{I}})\n  \\end{equation*}\n  and since $(C \\sqcap D)^{\\mathcal{I}\\mathcal{I}} \\sqsubseteq D^{\\mathcal{I}\\mathcal{I}}\n  \\sqsubseteq D$, it follows that\n  \\begin{equation*}\n    \\Conf(\\mathcal{I}, c) \\cup \\mathcal{B} \\models (C \\sqsubseteq D)\n  \\end{equation*}\n  as required.\n\\end{Proof}\n\nIt is also possible to establish the analog to \\Cref{lem:chain-rule-for-confidence}.\n\n\\begin{Lemma}\n  \\label{lem:chain-rule-for-confidence-of-gcis}\n  Let $\\mathcal{I} = (\\Delta^{\\mathcal{I}}, \\cdot^{\\mathcal{I}})$ be a finite\n  interpretation, and let $Z \\subseteq Y \\subseteq X$.  Then\n  \\begin{equation*}\n    \\conf_{\\mathcal{I}}(X^{\\mathcal{I}} \\sqsubseteq Z^{\\mathcal{I}}) =\n    \\conf_{\\mathcal{I}}(X^{\\mathcal{I}} \\sqsubseteq Y^{\\mathcal{I}}) \\cdot\n    \\conf_{\\mathcal{I}}(Y^{\\mathcal{I}} \\sqsubseteq Z^{\\mathcal{I}}).\n  \\end{equation*}\n\\end{Lemma}\n\\begin{Proof}\n  If $X^{\\mathcal{I}\\mathcal{I}} = \\emptyset$, then because of $Z \\subseteq Y \\subseteq X$\n  we obtain $Z^{\\mathcal{I}\\mathcal{I}} \\subseteq Y^{\\mathcal{I}\\mathcal{I}} \\subseteq\n  X^{\\mathcal{I}\\mathcal{I}}$ and thus $Z^{\\mathcal{I}\\mathcal{I}} =\n  Y^{\\mathcal{I}\\mathcal{I}} = \\emptyset$.  In this case, both sides of the equation are\n  1.\n\n  If $X^{\\mathcal{I}\\mathcal{I}} \\neq \\emptyset$ but $Y^{\\mathcal{I}\\mathcal{I}} =\n  \\emptyset$, then $Z^{\\mathcal{I}\\mathcal{I}} = \\emptyset$ and both sides of the equation\n  are 0.  In both cases, equality holds.\n\n  Let $X^{\\mathcal{I}\\mathcal{I}} \\neq \\emptyset \\neq Y^{\\mathcal{I}\\mathcal{I}}$.  As in\n  the case of \\Cref{lem:chain-rule-for-confidence} we can compute\n  \\begin{align*}\n    \\conf_{\\mathcal{I}}(X^{\\mathcal{I}} \\sqsubseteq Z^{\\mathcal{I}})\n    &= \\frac\n    { \\abs{ (X^{\\mathcal{I}} \\sqcap Z^{\\mathcal{I}})^{\\mathcal{I}} }}\n    { \\abs{ X^{\\mathcal{I}\\mathcal{I}} }} \\\\\n    &= \\frac\n    { \\abs{ (X^{\\mathcal{I}} \\sqcap Y^{\\mathcal{I}})^{\\mathcal{I}} }}\n    { \\abs{ X^{\\mathcal{I}\\mathcal{I}} } }\n    \\cdot \\frac\n    { \\abs{ (X^{\\mathcal{I}} \\sqcap Z^{\\mathcal{I}})^{\\mathcal{I}} }}\n    { \\abs{ (X^{\\mathcal{I}} \\sqcap Y^{\\mathcal{I}})^{\\mathcal{I}} }} \\\\\n    &= \\frac\n    { \\abs{ (X^{\\mathcal{I}} \\sqcap Y^{\\mathcal{I}})^{\\mathcal{I}} }}\n    { \\abs{ X^{\\mathcal{I}\\mathcal{I}} } }\n    \\cdot \\frac\n    { \\abs{ (Y^{\\mathcal{I}} \\sqcap Z^{\\mathcal{I}})^{\\mathcal{I}} }}\n    { \\abs{ Y^{\\mathcal{I}\\mathcal{I}} }} \\\\\n    &= \\conf_{\\mathcal{I}}(X^{\\mathcal{I}} \\sqsubseteq Y^{\\mathcal{I}}) \\cdot\n    \\conf_{\\mathcal{I}}(Y^{\\mathcal{I}} \\sqsubseteq Z^{\\mathcal{I}})\n  \\end{align*}\n  because $Z^{\\mathcal{I}} \\sqsubseteq Y^{\\mathcal{I}} \\sqsubseteq X^{\\mathcal{I}}$.\n\\end{Proof}\n\n\\begin{Theorem}\n  \\label{thm:luxenbuger-base-for-gcis}\n  Let $\\mathcal{I} = (\\Delta^{\\mathcal{I}}, \\cdot^{\\mathcal{I}})$ be a finite\n  interpretation, and let $c \\in [0,1]$.  Let $\\mathcal{B}$ be a base of $\\mathcal{I}$.  Define\n  \\begin{multline*}\n    \\Lux(\\mathcal{I}, c) := \\{\\, X^{\\mathcal{I}} \\sqsubseteq Y^{\\mathcal{I}} \\mid Y\n      \\subseteq X \\subseteq \\Delta^{\\mathcal{I}}, \\\\\n      1 > \\conf_{\\mathcal{I}}( X^{\\mathcal{I}} \\sqsubseteq Y^{\\mathcal{I}} ) \\ge c,\n      \\nexists Z \\subseteq \\Delta^{\\mathcal{I}} \\st Y^{\\mathcal{I}} \\sqsubsetneq\n      Z^{\\mathcal{I}} \\sqsubsetneq X^{\\mathcal{I}} \\,\\}.\n  \\end{multline*}\n  Then $\\Lux(\\mathcal{I}, c) \\cup \\mathcal{B}$ is a finite confident base of\n  $\\Th_c(\\mathcal{I})$.\n\\end{Theorem}\n\\begin{Proof}\n  The proof is again analogous to the one of the corresponding\n  \\Cref{thm:luxenburger-base}.  To show the claim it is sufficient to just show that all\n  GCIs in $\\Conf(\\mathcal{I}, c)$ are entailed by $\\Lux(\\mathcal{I}, c)$.  To this end,\n  let $(X^{\\mathcal{I}} \\sqsubseteq Y^{\\mathcal{I}}) \\in \\Conf(\\mathcal{I}, c)$.  Then $Y\n  \\subseteq X \\subseteq \\Delta^{\\mathcal{I}}$, \\ie $Y^{\\mathcal{I}} \\sqsubseteq\n  X^{\\mathcal{I}}$.  Since $\\Delta^{\\mathcal{I}}$ is finite, there exist sets\n  $\\Delta^{\\mathcal{I}} \\supseteq Z_0 \\supseteq Z_1 \\supseteq \\dots \\supseteq Z_n$\n  satisfying\n  \\begin{equation*}\n    Y^{\\mathcal{I}} = Z_n^{\\mathcal{I}} \\sqsubsetneq Z_{n-1}^{\\mathcal{I}} \\sqsubsetneq\n    \\dots \\sqsubsetneq Z_1^{\\mathcal{I}} \\sqsubsetneq Z_0^{\\mathcal{I}} = X^{\\mathcal{I}}\n  \\end{equation*}\n  such that there do not exist sets $W \\subseteq \\Delta^{\\mathcal{I}}$ with\n  \\begin{equation}\n    \\label{eq:25}\n    Z_i^{\\mathcal{I}} \\sqsubsetneq W^{\\mathcal{I}} \\sqsubsetneq Z_{i-1}^{\\mathcal{I}}\n  \\end{equation}\n  for any $i \\in \\set{ 1, \\dots, n }$.  Then by\n  \\Cref{lem:chain-rule-for-confidence-of-gcis} it is true that\n  \\begin{equation*}\n    \\conf_{\\mathcal{I}}(X^{\\mathcal{I}} \\sqsubseteq Y^{\\mathcal{I}}) = \\prod_{i = 0}^{n-1}\n    \\conf_{\\mathcal{I}}(Z_i^{\\mathcal{I}} \\sqsubseteq Z_{i+1}^{\\mathcal{I}}).\n  \\end{equation*}\n  Since the confidence is always an element of $[0,1]$, we obtain from this equality that\n  \\begin{equation*}\n    \\conf_{\\mathcal{I}}(Z_i^{\\mathcal{I}} \\sqsubseteq Z_{i+1}^{\\mathcal{I}}) \\ge\n    \\conf_{\\mathcal{I}}(X^{\\mathcal{I}} \\sqsubseteq Y^{\\mathcal{I}}) \\ge c\n  \\end{equation*}\n  and because of \\Cref{eq:25} we obtain $(Z_i^{\\mathcal{I}} \\sqsubseteq\n  Z_{i+1}^{\\mathcal{I}}) \\in \\Lux(\\mathcal{I}, c)$ for all $i \\in \\set{ 0, \\dots, n-1}$.\n  Since $\\set{ Z_i^{\\mathcal{I}} \\sqsubseteq Z_{i+1}^{\\mathcal{I}} \\mid i \\in \\set{ 0,\n      \\dots, n-1} }$ entails $X^{\\mathcal{I}} \\sqsubseteq Y^{\\mathcal{I}}$ we obtain\n  \\begin{equation*}\n    \\Lux(\\mathcal{I}, c) \\models (X^{\\mathcal{I}} \\sqsubseteq Y^{\\mathcal{I}})\n  \\end{equation*}\n  as required.\n\\end{Proof}\n\nAnd finally, the analog of \\Cref{cor:weakened-luxenburger-base} of course holds as well.\n\n\\begin{Corollary}\n  \\label{cor:weakened-luxenburger-base-for-gcis}\n  Let $\\mathcal{I} = (\\Delta^{\\mathcal{I}}, \\cdot^{\\mathcal{I}})$ be a finite\n  interpretation, and let $c \\in [0,1]$.  If $\\mathcal{B} \\subseteq \\Th_c(\\mathcal{I})$ is\n  complete for $\\Lux(\\con K, c)$, and if $\\mathcal{L} \\subseteq \\Th(\\mathcal{I})$ is such\n  that $\\mathcal{B} \\cup \\mathcal{L}$ is complete for $\\Th(\\mathcal{I})$, then\n  $\\mathcal{B} \\cup \\mathcal{L}$ is a confident base of $\\Th_c(\\mathcal{I})$.\n\\end{Corollary}\n\nTo compute the sets $\\Conf(\\mathcal{I}, c)$ and $\\Lux(\\mathcal{I}, c)$ we can just compute\nall model-based most-specific concept descriptions, and compute for each two\n$X^{\\mathcal{I}}, Y^{\\mathcal{I}}$, $Y \\subseteq X \\subseteq \\Delta^{\\mathcal{I}}$ whether\n\\begin{equation*}\n  \\conf_{\\mathcal{I}}(X^{\\mathcal{I}} \\sqsubseteq Y^{\\mathcal{I}}) \\ge c.\n\\end{equation*}\nHowever, we can transfer the computation of these sets into a computation which can solely\nbe done in the induced formal context $\\con K_{\\mathcal{I}}$.  This may be desirable\nbecause the computations in $\\con K_{\\mathcal{I}}$ may be easier to conduct, since we only\nhave to work with subsets of $M_{\\mathcal{I}}$, and not with complex concept descriptions.\n\nThe actual transformation is quite simple: it is true that\n\\begin{equation}\n  \\label{eq:31}\n  \\begin{aligned}\n    \\Conf(\\mathcal{I}, c) &= \\bigsqcap \\Conf(\\con K_{\\mathcal{I}}, c) \\\\\n    \\Lux(\\mathcal{I}, c) &= \\bigsqcap \\Lux(\\con K_{\\mathcal{I}}, c)\n  \\end{aligned}\n\\end{equation}\nwhere the equality is meant up to equivalence, \\ie every GCI in the set on the left-hand\nside is equivalent to one in the right-hand side, and vice versa.\n\nEstablishing these equations is also not difficult.  We start with a simple connection\nbetween the confidence of GCIs in $\\mathcal{I}$ and the confidence of implications in\n$\\con K_{\\mathcal{I}}$.\n\n\\begin{Proposition}\n  \\label{prop:confidence-in-I-is-confidence-in-K_I}\n  Let $\\mathcal{I} = (\\Delta^{\\mathcal{I}}, \\cdot^{\\mathcal{I}})$ be a finite\n  interpretation, and let $X, Y \\subseteq \\Delta^{\\mathcal{I}}$.  Then\n  \\begin{equation*}\n    \\conf_{\\mathcal{I}}(X^{\\mathcal{I}} \\sqsubseteq Y^{\\mathcal{I}}) = \\conf_{\\con\n      K_{\\mathcal{I}}}(X' \\to Y').\n  \\end{equation*}\n\\end{Proposition}\n\\begin{Proof}\n  By \\Cref{prop:connection-I-prime-3} it is true that $X^{\\mathcal{I}\\mathcal{I}} = X''$.\n  Thus, if $X^{\\mathcal{I}\\mathcal{I}} = \\emptyset$, then $X'' = \\emptyset$ and\n  \\begin{equation*}\n    \\conf_{\\mathcal{I}}(X^{\\mathcal{I}} \\sqsubseteq Y^{\\mathcal{I}}) = 1 = \\conf_{\\con\n      K_{\\mathcal{I}}}(X' \\to Y').\n  \\end{equation*}\n  If $X^{\\mathcal{I}\\mathcal{I}} \\neq \\emptyset$, then $X'' \\neq \\emptyset$ and we can compute\n  \\begin{align*}\n    \\conf_{\\mathcal{I}}(X^{\\mathcal{I}} \\sqsubseteq Y^{\\mathcal{I}})\n    &= \\frac{ \\abs{ (X^{\\mathcal{I}} \\sqcap Y^{\\mathcal{I}})^{\\mathcal{I}} } }{ \\abs{\n        X^{\\mathcal{I}\\mathcal{I}} } }\\\\\n    &= \\frac{ \\abs{ X^{\\mathcal{I}\\mathcal{I}} \\cap Y^{\\mathcal{I}\\mathcal{I}} } }{ \\abs{\n        X^{\\mathcal{I}\\mathcal{I}} } } \\\\\n    &= \\frac{ \\abs{ X'' \\cap Y'' } }{ \\abs{ X'' } } \\\\\n    &= \\frac{ \\abs{ (X' \\cup Y')' } }{ \\abs{ X'' } } \\\\\n    &= \\conf_{\\con K_{\\mathcal{I}}}(X' \\to Y').\n  \\end{align*}\n\\end{Proof}\n\nThis already allows us to establish the first of \\Cref{eq:31}.\n\n\\begin{Corollary}\n  \\label{cor:Conf-from-K_I}\n  Let $\\mathcal{I}$ be a finite interpretation, and let $c \\in [0,1]$.  Then\n  \\begin{equation*}\n    \\Conf(\\mathcal{I}, c) = \\bigsqcap \\Conf(\\con K_{\\mathcal{I}}, c)\n  \\end{equation*}\n  up to equivalence.\n\\end{Corollary}\n\\begin{Proof}\n  Let $(X^{\\mathcal{I}} \\sqsubseteq Y^{\\mathcal{I}}) \\in \\Conf(\\mathcal{I}, c)$.  Then $Y\n  \\subseteq X \\subseteq \\Delta^{\\mathcal{I}}$ and $1 > \\conf_{\\mathcal{I}}(X^{\\mathcal{I}}\n  \\sqsubseteq Y^{\\mathcal{I}}) \\ge c$.  Thus, by\n  \\Cref{prop:confidence-in-I-is-confidence-in-K_I}, $1 > \\conf_{\\con K_{\\mathcal{I}}}(X'\n  \\to Y') \\ge c$.  Since $X' = X'''$, $Y' = Y'''$ and $X' \\subseteq Y'$ we obtain that\n  $(X' \\to Y') \\in \\Conf(\\con K_{\\mathcal{I}}, c)$.  By\n  \\Cref{prop:connection-I-prime-2}, $\\bigsqcap X' \\equiv X^{\\mathcal{I}}$ and\n  $\\bigsqcap Y' \\equiv Y^{\\mathcal{I}}$, thus $(X^{\\mathcal{I}} \\sqsubseteq\n  Y^{\\mathcal{I}}) \\in \\bigsqcap \\Conf(\\con K_{\\mathcal{I}}, c)$ up to equivalence.\n\n  Now let $(\\bigsqcap A'' \\sqsubseteq \\bigsqcap B'') \\in \\bigsqcap \\Conf(\\con\n  K_{\\mathcal{I}}, c)$.  Then $A \\subseteq B \\subseteq M_{\\mathcal{I}}$ and $1 >\n  \\conf_{\\con K_{\\mathcal{I}}}(A'' \\to B'') \\ge c$.  Define $X := A'$ and $Y := B'$.  Then\n  $1 > \\conf_{\\con K_{\\mathcal{I}}}(X' \\to Y') \\ge c$, and thus $1 >\n  \\conf_{\\mathcal{I}}(X^{\\mathcal{I}} \\sqsubseteq Y^{\\mathcal{I}}) \\ge c$.  Furthermore,\n  $Y \\subseteq X$, since $A \\subseteq B$ implies $Y = B' \\subseteq A' = X$.  Again by\n  \\Cref{prop:connection-I-prime-2} we have $\\bigsqcap A'' = \\bigsqcap X' \\equiv\n  X^{\\mathcal{I}}$ and $\\bigsqcap B'' = \\bigsqcap Y' \\equiv Y^{\\mathcal{I}}$, and thus\n  $(X^{\\mathcal{I}} \\sqsubseteq Y^{\\mathcal{I}}) \\in \\Conf(\\mathcal{I}, c)$ as required.\n\n  Let $A, \\bar A \\subseteq M_{\\mathcal{I}}$.  Then\n  \\begin{align*}\n    \\bigsqcap A'' \\equiv \\bigsqcap \\bar A''\n    &\\implies (\\bigsqcap A'')^{\\mathcal{I}} = (\\bigsqcap \\bar A'')^{\\mathcal{I}} \\\\\n    &\\implies (A')^{\\mathcal{I}\\mathcal{I}} = (\\bar A')^{\\mathcal{I}\\mathcal{I}} \\\\\n    &\\implies A''' = \\bar A''' \\\\\n    &\\implies A'' = \\bar A'',\n  \\end{align*}\n  using \\Cref{prop:connection-I-prime-2} and \\Cref{prop:connection-I-prime-3}.  Therefore,\n  no two GCIs in $\\bigsqcap \\Conf(\\con K_{\\mathcal{I}}, c)$ are equivalent, and the claim\n  follows.\n\\end{Proof}\n\nTo show the second equation of \\Cref{eq:31} we proceed with another technical result.\n\n\\begin{Proposition}\n  \\label{prop:non-equivalence-implies-non-equality-and-vv}\n  Let $\\mathcal{I} = (\\Delta^{\\mathcal{I}}, \\cdot^{\\mathcal{I}})$ be a finite\n  interpretation, and let $X, Y \\subseteq \\Delta^{\\mathcal{I}}$.  Then\n  \\begin{enumerate}[i. ]\n  \\item $X^{\\mathcal{I}} \\sqsubsetneq Y^{\\mathcal{I}}$ implies\n    $\\pr_{M_{\\mathcal{I}}}(X^{\\mathcal{I}}) \\supsetneq\n    \\pr_{M_{\\mathcal{I}}}(Y^{\\mathcal{I}})$, and\n  \\item $X' \\supsetneq Y'$ implies $\\bigsqcap X' \\sqsubsetneq \\bigsqcap Y'$\n  \\end{enumerate}\n  where the derivations are done in $\\con K_{\\mathcal{I}}$.\n\\end{Proposition}\n\\begin{Proof}\n  We already know from \\Cref{cor:mmsc-lattice} that $X^{\\mathcal{I}} \\sqsubsetneq\n  Y^{\\mathcal{I}}$ implies $\\pr_{M_{\\mathcal{I}}}(X^{\\mathcal{I}}) \\supseteq\n  \\pr_{M_{\\mathcal{I}}}(Y^{\\mathcal{I}})$ and that $X' \\supsetneq Y'$ implies $\\bigsqcap\n  X' \\sqsubseteq \\bigsqcap Y'$.\n\n  Let us assume that $\\pr_{M_{\\mathcal{I}}}(X^{\\mathcal{I}}) =\n  \\pr_{M_{\\mathcal{I}}}(Y^{\\mathcal{I}})$.  Then by\n  \\Cref{lem:mmsc-are-expressible-in-terms-of-M_I} and\n  \\Cref{lem:characterizing-expressible-in-terms-of}\n  \\begin{equation*}\n    X^{\\mathcal{I}} \\equiv \\bigsqcap \\pr_{M_{\\mathcal{I}}}(X^{\\mathcal{I}}) = \\bigsqcap\n    \\pr_{M_{\\mathcal{I}}}(Y^{\\mathcal{I}}) \\equiv Y^{\\mathcal{I}}.\n  \\end{equation*}\n  Conversely, if $\\bigsqcap X' \\equiv \\bigsqcap Y'$, then using\n  \\Cref{cor:mmsc-lattice} we obtain\n  \\begin{equation*}\n    X' = \\pr_{M_{\\mathcal{I}}}(\\bigsqcap X') = \\pr_{M_{\\mathcal{I}}}(\\bigsqcap Y') = Y'\n  \\end{equation*}\n  as required.\n\\end{Proof}\n\n\\begin{Corollary}\n  \\label{cor:Lux-from-K_I}\n  Let $\\mathcal{I}$ be a finite interpretation, and let $c \\in [0,1]$.  Then\n  \\begin{equation*}\n    \\Lux(\\mathcal{I}, c) = \\bigsqcap \\Lux(\\con K_{\\mathcal{I}}, c)\n  \\end{equation*}\n  up to equivalence.\n\\end{Corollary}\n\\begin{Proof}\n  Using the same argumentation as in the proof of \\Cref{cor:Conf-from-K_I} it suffices to\n  show that for $Y \\subseteq Z \\subseteq X \\subseteq \\Delta^{\\mathcal{I}}$ it is true that\n  \\begin{equation}\n    \\label{eq:32}\n    Y^{\\mathcal{I}} \\not\\equiv Z^{\\mathcal{I}} \\not\\equiv X^{\\mathcal{I}} \\iff Y' \\neq Z'\n    \\neq X'.\n  \\end{equation}\n  Suppose first that $Y^{\\mathcal{I}} \\not\\equiv Z^{\\mathcal{I}} \\not\\equiv\n  X^{\\mathcal{I}}$.  Then $Y^{\\mathcal{I}} \\sqsubsetneq Z^{\\mathcal{I}} \\sqsubsetneq\n  X^{\\mathcal{I}}$, and from \\Cref{prop:non-equivalence-implies-non-equality-and-vv} we\n  obtain $\\pr_{M_{\\mathcal{I}}}(Y^{\\mathcal{I}}) \\supsetneq \\pr_{M_{\\mathcal{I}}}(Z^{\\mathcal{I}})\n  \\supsetneq \\pr_{M_{\\mathcal{I}}}(X^{\\mathcal{I}})$.  \\Cref{prop:connection-I-prime-1}\n  then yields $Y' \\supsetneq Z' \\supsetneq X'$ as required.\n\n  Conversely, suppose $Y' \\supsetneq Z' \\supsetneq X'$.  Then using\n  \\Cref{prop:non-equivalence-implies-non-equality-and-vv} we obtain $\\bigsqcap Y'\n  \\sqsubsetneq \\bigsqcap Z' \\sqsubsetneq \\bigsqcap X'$, \\ie $Y^{\\mathcal{I}} \\sqsubsetneq\n  Z^{\\mathcal{I}} \\sqsubsetneq X^{\\mathcal{I}}$ by \\Cref{prop:connection-I-prime-2}.\n\\end{Proof}\n\n\\subsection{Bases of Confident GCIs from Bases of Confident Implications}\n\\label{sec:bases-confident-gcis}\n\nIn the previous section we have obtained some first finite confident bases of\n$\\Th_c(\\mathcal{I})$ by mimicking the argumentation of Luxenburger's results in the\nsetting of description logics.  In this section we want to take another approach to obtain\nfinite bases and finite confident bases, by directly transferring such bases of\nimplications with high confidence to corresponding bases of GCIs with high confidence.\nMore precisely, given a finite interpretation $\\mathcal{I}$ and $c \\in [0,1]$, we consider\nthe induced formal context $\\con K_{\\mathcal{I}}$ of $\\mathcal{I}$, compute a base\n$\\mathcal{L}$ of $\\Th_c(\\con K_{\\mathcal{I}})$ and transfer this base into a base for\n$\\Th_c(\\con K)$ by defining\n\\begin{equation*}\n  \\bigsqcap \\mathcal{L} := \\set{ \\bigsqcap X \\sqsubseteq \\bigsqcap Y \\mid (X \\to Y) \\in\n    \\mathcal{L} }.\n\\end{equation*}\n\nThis approach has a particular advantage over computing finite bases of\n$\\Th_c(\\mathcal{I})$ the way we described it in the previous section.  This advantage lies\nin the very close connection between formal concept analysis and data-mining, which\nextends to the level that formal concept analysis can be used as a framework for the\nlogical foundations of the theory of \\emph{association rules}~\\cite{arules:Zaki:1998}.\nAlthough we have not introduced association rules formally here, they can be thought of as\na generalization of implications with high confidence.  Association rules are a well\ninvestigated topic in data-mining, and there is extensive literature on algorithms that\nmine association rules from data, see~\\cite{arules:Hipp:2000} for an overview over some of\nthem.  Because of the close connection of formal concept analysis to data-mining, these\nalgorithms can be adapted quite easily to the problem of finding bases of implications\nwith high confidence.\n\nIf we now establish another link between bases of implications with high confidence on the\none hand, and bases of GCIs with high confidence on the other, then we can exploit the\nalgorithms from data-mining for extracting association rules from data to find bases for\nGCIs with high confidence in finite interpretations.  This link may be of particular\ninterest since these algorithms are usually tailored towards practical applications.  We\nshall not go into details here, see \\Cref{cha:conclusions}.\n\nThe results presented in this section have been published before in\n\\cite{Borchmann-LTCS-12-06}.\n\nWe start with an observation that connects entailment between implications and entailment\nbetween GCIs.\n\n\\begin{Lemma}\n  \\label{lem:implicational-entailment-implies-gci-entailment}\n  Let $M$ be a set of concept descriptions over $N_C$ and $N_R$, and let $\\mathcal{L}\n  \\subseteq \\Imp(M)$.  Then for all $(X \\to Y) \\in \\Imp(M)$ it is true that if\n  $\\mathcal{L} \\models (X \\to Y)$, then $\\bigsqcap \\mathcal{L} \\models (\\bigsqcap X\n  \\sqsubseteq \\bigsqcap Y)$.\n\\end{Lemma}\n\\begin{Proof}\n  Let $\\mathcal{J} = (\\Delta^{\\mathcal{J}}, \\cdot^{\\mathcal{J}})$ be an interpretation\n  over $N_C$ and $N_R$ such that $\\mathcal{J} \\models \\bigsqcap \\mathcal{L}$.  Recall that\n  we denote with $\\con K_{\\mathcal{J}, M}$ the induced context of $\\mathcal{J}$ and $M$.\n  \n  We shall first show that $\\con K_{\\mathcal{J}, M} \\models \\mathcal{L}$.  To this end,\n  let $(E \\to F) \\in \\mathcal{L}$.  Then $(\\bigsqcap E)^{\\mathcal{J}} \\sqsubseteq\n  (\\bigsqcap F)^{\\mathcal{J}}$, because $\\mathcal{J} \\models \\bigsqcap \\mathcal{L}$.  By\n  \\Cref{prop:connection-I-prime-2}, $(\\bigsqcap E)^{\\mathcal{J}} = E'$ and $(\\bigsqcap\n  F)^{\\mathcal{J}} = F'$, where the derivations are done in $\\con K_{\\mathcal{J}, M}$.\n  Thus $E' \\subseteq F'$, and $\\con K_{\\mathcal{J}, M} \\models (E \\to F)$.  Hence, $\\con\n  K_{\\mathcal{J}, M} \\models \\mathcal{L}$.\n\n  Since $\\mathcal{L} \\models (X \\to Y)$, $\\con K_{\\mathcal{J}, M} \\models (X \\to Y)$, \\ie\n  $X' \\subseteq Y'$.  By the same argument as before we obtain $(\\bigsqcap\n  X)^{\\mathcal{J}} \\subseteq (\\bigsqcap Y)^{\\mathcal{J}}$, and therefore $\\mathcal{J}\n  \\models (\\bigsqcap X \\sqsubseteq \\bigsqcap Y)$.\n\n  Since $\\mathcal{J}$ was chosen arbitrarily, we obtain $\\bigsqcap \\mathcal{L} \\models\n  (\\bigsqcap X \\sqsubseteq \\bigsqcap Y)$ as required.\n\\end{Proof}\n\nNote that we cannot expect the converse direction to hold in general as well.  The reason\nfor this is that entailment between implications does not \\enquote{look inside} the\nattributes in the implications, but entailment between GCIs is allowed to consider the\nstructure of concept descriptions.  This is illustrated by the following example.\n\n\\begin{Example}\n  \\label{expl:gci-entailment-does-not-impliy-implicational-entailment}\n  Let $N_C := \\set{ \\mathsf{A}, \\mathsf{B} }$, $N_R := \\set{ \\mathsf{r} }$ and $M := \\set{\n    \\mathsf{A}, \\mathsf{B}, \\mathsf{\\exists r. A}, \\mathsf{\\exists r. B} }$.  Consider\n  \\begin{align*}\n    \\mathcal{L} &:= \\set{ \\set{ \\mathsf{A} } \\to \\set{ \\mathsf{B} } }, \\\\\n    X &:= \\set{ \\mathsf{\\exists r. A} }, \\\\\n    Y &:= \\set{ \\mathsf{\\exists r. B} }.\n  \\end{align*}\n  Then clearly $\\mathcal{L} \\not\\models (X \\to Y)$, but $\\bigsqcap \\mathcal{L} \\models\n  (\\bigsqcap X \\sqsubseteq \\bigsqcap Y)$.\n\\end{Example}\n\nThe following proposition connects the notions of confidence of implications in finite\nformal contexts and confidence of GCIs in finite interpretations.\n\n\\begin{Proposition}\n  \\label{prop:confidence-in-interpretation-is-the-same-as-in-induced-context}\n  Let $\\mathcal{I}$ be a finite interpretation over $N_C$ and $N_R$, let $M$ be a set of\n  concept descriptions over $N_C$ and $N_R$ and let $(X \\to Y) \\in \\Imp(M)$.  Then\n  \\begin{equation*}\n    \\conf_{\\con K_{\\mathcal{I}}}( X \\to Y ) = \\conf_{\\mathcal{I}}( \\bigsqcap X \\sqsubseteq\n    \\bigsqcap Y ).\n  \\end{equation*}\n\\end{Proposition}\n\\begin{Proof}\n  In the following, all derivations are done in $\\con K_{\\mathcal{I}}$.\n  \n  By \\Cref{prop:connection-I-prime-2} we know that $X' = (\\bigsqcap X)^{\\mathcal{I}}$,\n  thus if $X' = \\emptyset$, then\n  \\begin{equation*}\n    \\conf_{\\con K_{\\mathcal{I}}}( X \\to Y ) = 1 = \\conf_{\\mathcal{I}}( \\bigsqcap X\n    \\sqsubseteq \\bigsqcap Y ).\n  \\end{equation*}\n\n  Now suppose that $X' \\neq \\emptyset$.  Then $(\\bigsqcap X)^{\\mathcal{I}} \\neq\n  \\emptyset$, and we can compute\n  \\begin{align*}\n    \\conf_{\\con K_{\\mathcal{I}}}( X \\to Y )\n    &= \\frac{ \\abs{ (X \\cup Y)' } }{ \\abs{ X' } } \\\\\n    &= \\frac{ \\abs{ X' \\cap Y' } }{ \\abs{ X' } } \\\\\n    &= \\frac{ \\abs{ (\\bigsqcap X)^{\\mathcal{I}} \\cap (\\bigsqcap Y)^{\\mathcal{I}} } }{\n      \\abs{ (\\bigsqcap X)^{\\mathcal{I}} } } \\\\\n    &= \\frac{ \\abs{ (\\bigsqcap X \\sqcap \\bigsqcap Y)^{\\mathcal{I}} } }{ \\abs{ (\\bigsqcap\n        X)^{\\mathcal{I}} } } \\\\\n    &= \\conf_{\\mathcal{I}} (\\bigsqcap X \\sqsubseteq \\bigsqcap Y)\n  \\end{align*}\n  again using \\Cref{prop:connection-I-prime-2}.\n\\end{Proof}\n\nThe main result of this section is now the following theorem.\n\n\\begin{Theorem}\n  \\label{thm:confident-bases-of-GCIs-from-confident-bases-of-implications}\n  Let $\\mathcal{I}$ be a finite interpretation over $N_C$ and $N_R$, and let $c \\in\n  [0,1]$.  Let $\\mathcal{L}$ be a confident base of $\\Th_c(\\con K_{\\mathcal{I}})$.  Then\n  $\\bigsqcap \\mathcal{L}$ is a confident base of $\\Th_c(\\mathcal{I})$.\n\\end{Theorem}\n\\begin{Proof}\n  We need to show that $\\bigsqcap \\mathcal{L} \\subseteq \\Th_c(\\mathcal{I})$ and that\n  $\\bigsqcap \\mathcal{L}$ is complete for $\\Th_c(\\mathcal{I})$.\n\n  To see that $\\bigsqcap \\mathcal{L}$ is sound for $\\Th_c(\\mathcal{I})$ let $(\\bigsqcap X\n  \\sqsubseteq \\bigsqcap Y) \\in \\bigsqcap \\mathcal{L}$.  Then $(X \\to Y) \\in \\mathcal{L}$,\n  and thus\n  \\begin{equation*}\n    \\conf_{\\mathcal{I}}(\\bigsqcap X \\sqsubseteq \\bigsqcap Y) = \\conf_{\\con K_{\\mathcal{I}}}(X \\to Y) \\ge c\n  \\end{equation*}\n  by \\Cref{prop:confidence-in-interpretation-is-the-same-as-in-induced-context}.  Thus\n  $(\\bigsqcap X \\sqsubseteq \\bigsqcap Y) \\in \\Th_c(\\mathcal{I})$ and hence $\\bigsqcap\n  \\mathcal{L} \\subseteq \\Th_c(\\mathcal{I})$ as required.\n\n  For the completeness of $\\bigsqcap \\mathcal{L}$ for $\\Th_c(\\mathcal{I})$ we show two\n  subclaims, namely\n  \\begin{enumerate}[i. ]\n  \\item\\label{item:16} $\\bigsqcap \\mathcal{L} \\models (\\bigsqcap U \\sqsubseteq (\\bigsqcap\n    U)^{\\mathcal{I}\\mathcal{I}})$ for all $U \\subseteq M_{\\mathcal{I}}$, and\n  \\item\\label{item:17} $\\bigsqcap \\mathcal{L} \\models (X^{\\mathcal{I}} \\sqsubseteq\n    Y^{\\mathcal{I}})$ for each $(X^{\\mathcal{I}} \\sqsubseteq Y^{\\mathcal{I}}) \\in\n    \\Conf(\\mathcal{I}, c)$.\n  \\end{enumerate}\n  The first claim then ensures that $\\bigsqcap \\mathcal{L}$ entails all GCIs from the set\n  \\begin{equation*}\n    \\set{ \\bigsqcap U \\sqsubseteq (\\bigsqcap U)^{\\mathcal{I}\\mathcal{I}} \\mid U \\subseteq\n      M_{\\mathcal{I}} }\n  \\end{equation*}\n  which by \\Cref{thm:Felix-base-B2} is a base of $\\mathcal{I}$.  Showing (\\ref{item:16})\n  entails that $\\bigsqcap \\mathcal{L}$ is complete for $\\Th(\\mathcal{I})$.  The claim\n  (\\ref{item:17}) states that $\\bigsqcap \\mathcal{L}$ is complete for $\\Conf(\\mathcal{I},\n  c)$.  Using \\Cref{cor:weakened-luxenburger-base-for-gcis} and the fact that $\\bigsqcap\n  \\mathcal{L}$ is sound for $\\Th_c(\\mathcal{I})$ then shows that $\\bigsqcap \\mathcal{L}$\n  is a confident base of $\\Th_c(\\mathcal{I})$.\n\n  We show (\\ref{item:16}).  Let $U \\subseteq M_{\\mathcal{I}}$.  Since $\\mathcal{L}$ is a\n  confident base for $\\Th_c(\\con K_{\\mathcal{I}})$ it is complete for $\\con\n  K_{\\mathcal{I}}$.  Thus\n  \\begin{equation*}\n    \\mathcal{L} \\models (U \\to U'').\n  \\end{equation*}\n  Then \\Cref{lem:implicational-entailment-implies-gci-entailment} yields\n  \\begin{equation*}\n    \\bigsqcap \\mathcal{L} \\models (\\bigsqcap U \\sqsubseteq \\bigsqcap (U'')),\n  \\end{equation*}\n  and by \\Cref{lem:double-II-gets-double-prime} we obtain\n  \\begin{equation*}\n    \\bigsqcap \\mathcal{L} \\models (\\bigsqcap U \\sqsubseteq (\\bigsqcap U)^{\\mathcal{I}\\mathcal{I}})\n  \\end{equation*}\n  as required.\n\n  For (\\ref{item:17}) let $(X^{\\mathcal{I}} \\sqsubseteq Y^{\\mathcal{I}}) \\in\n  \\Conf(\\mathcal{I}, c)$.  Then $X, Y \\subseteq \\Delta^{\\mathcal{I}}$ and $1 >\n  \\conf_{\\mathcal{I}}(X^{\\mathcal{I}} \\sqsubseteq Y^{\\mathcal{I}}) \\ge c$.  Since\n  $X^{\\mathcal{I}}$ and $Y^{\\mathcal{I}}$ are expressible in terms of $M_{\\mathcal{I}}$ by\n  \\Cref{lem:mmsc-are-expressible-in-terms-of-M_I}, we obtain from\n  \\Cref{prop:connection-I-prime-2} that $X^{\\mathcal{I}} \\equiv \\bigsqcap X'$ and\n  $Y^{\\mathcal{I}} \\equiv \\bigsqcap Y'$.  Thus,\n  \\begin{equation}\n    \\label{eq:27}\n    \\bigsqcap \\mathcal{L} \\models (X^{\\mathcal{I}} \\sqsubseteq Y^{\\mathcal{I}}) \\iff\n    \\bigsqcap \\mathcal{L} \\models (\\bigsqcap X' \\sqsubseteq \\bigsqcap Y').\n  \\end{equation}\n  By \\Cref{prop:confidence-in-interpretation-is-the-same-as-in-induced-context}\n  \\begin{equation*}\n    \\conf_{\\con K_{\\mathcal{I}}}(X' \\to Y') = \\conf_{\\mathcal{I}}(\\bigsqcap X' \\sqsubseteq\n    \\bigsqcap Y') \\ge c.\n  \\end{equation*}\n  Since $\\mathcal{L}$ is a base of $\\Th_c(\\con K_{\\mathcal{I}})$ we obtain $\\mathcal{L}\n  \\models (X' \\to Y')$, thus by \\Cref{lem:implicational-entailment-implies-gci-entailment}\n  \\begin{equation*}\n    \\bigsqcap \\mathcal{L} \\models (\\bigsqcap X' \\sqsubseteq \\bigsqcap Y')\n  \\end{equation*}\n  which together with \\Cref{eq:27} yields the claim.\n\\end{Proof}\n\nSince $\\Th_c(\\con K_{\\mathcal{I}})$ is a confident base of itself, the theorem immediately\nyields that $\\bigsqcap \\Th_c(\\con K_{\\mathcal{I}})$ is a finite confident base of\n$\\Th_c(\\mathcal{I})$.\n\n\\Cref{thm:confident-bases-of-GCIs-from-confident-bases-of-implications} has the drawback\nthat $\\bigsqcap \\mathcal{L}$ still contains trivial knowledge in the sense that whenever\n$C, D \\in M_{\\mathcal{I}}$ are such that $C \\sqsubseteq D$, then $\\mathcal{L}$ has to\nentail $\\set{ C } \\to \\set{ D }$, although the corresponding GCI $C \\sqsubseteq D$ is\ntrivially true.  We can remedy this redundancy by considering an appropriate background\nknowledge.  Recall that in \\Cref{eq:28} we defined the set\n\\begin{equation*}\n  \\mathcal{S}_{\\mathcal{I}} := \\set{ \\set{ C } \\to \\set{ D } \\mid C, D \\in\n    M_{\\mathcal{I}}, C \\sqsubseteq D }.\n\\end{equation*}\n\n\\begin{Corollary}\n  \\label{cor:using-background-knowledge-for-confident-bases}\n  Let $\\mathcal{I}$ be a finite interpretation over $N_C$ and $N_R$, let $c \\in [0,1]$ and\n  $\\mathcal{L} \\subseteq \\Th_c(\\con K_{\\mathcal{I}})$ be such that $\\mathcal{L} \\cup\n  \\mathcal{S}_{\\mathcal{I}}$ is a confident base of $\\Th_c(\\con K_{\\mathcal{I}})$.  Then\n  $\\bigsqcap \\mathcal{L}$ is a finite confident base of $\\Th_c(\\mathcal{I})$.\n\\end{Corollary}\n\\begin{Proof}\n  By \\Cref{thm:confident-bases-of-GCIs-from-confident-bases-of-implications} the set\n  $\\bigsqcap \\mathcal{L} \\cup \\bigsqcap \\mathcal{S}_{\\mathcal{I}}$ is a finite confident\n  base of $\\Th_c(\\mathcal{I})$.  Since $\\bigsqcap \\mathcal{S}_{\\mathcal{I}}$ is valid in\n  every interpretation, it is entailed by $\\bigsqcap \\mathcal{L}$, and thus the set\n  $\\bigsqcap \\mathcal{L}$ is already complete for $\\Th_c(\\mathcal{I})$.  Thus, $\\bigsqcap\n  \\mathcal{L}$ is a finite confident base of $\\Th_c(\\mathcal{I})$.\n\\end{Proof}\n\nWe can use \\Cref{lem:implicational-entailment-implies-gci-entailment} to further remove\nredundancies from bases obtained as in\n\\Cref{thm:confident-bases-of-GCIs-from-confident-bases-of-implications}.  More precisely,\nif $\\mathcal{L}$ is a base of $\\Th_c(\\con K_{\\mathcal{I}})$, and if $(X \\to Y) \\in\n\\mathcal{L}$ is such that\n\\begin{equation*}\n  \\mathcal{L} \\setminus \\set{ X \\to Y } \\models (X \\to Y),\n\\end{equation*}\nthen \\Cref{lem:implicational-entailment-implies-gci-entailment} yields that\n\\begin{equation*}\n  \\bigsqcap \\mathcal{L} \\setminus \\set{ \\bigsqcap X \\sqsubseteq \\bigsqcap Y } \\models (\n  \\bigsqcap X \\sqsubseteq \\bigsqcap Y).\n\\end{equation*}\nThus, redundancies in bases of $\\Th_c(\\con K_{\\mathcal{I}})$ always result in redundancies\nin bases of $\\Th_c(\\mathcal{I})$.  Thus, removing these redundancies is a good starting\npoint to obtain smaller bases of $\\Th_c(\\mathcal{I})$.\n\nIn particular, we can consider irredundant bases $\\mathcal{L}$ of $\\Th_c(\\con\nK_{\\mathcal{I}})$.  However, even if $\\mathcal{L}$ is irredundant, $\\bigsqcap \\mathcal{L}$\nmay contain redundancies, as the following example shows.\n\n\\begin{Example}\n  \\label{expl:nonredundant-implicational-base-yields-redundant-gci-base}\n  We are looking for a finite interpretation $\\mathcal{I}$, a $c \\in [0,1]$, and a\n  non-redundant set $\\mathcal{L}$ such that $\\mathcal{L} \\cup \\mathcal{S}_{\\mathcal{I}}$\n  is a confident base of $\\Th_c(\\con K_{\\mathcal{I}})$, but $\\bigsqcap \\mathcal{L}$\n  contains redundancies.\n\n  For this we employ a similar idea as we did in\n  \\Cref{expl:gci-entailment-does-not-impliy-implicational-entailment}.  More precisely, we\n  want to construct an interpretation $\\mathcal{I}$ such that for two concept names\n  $\\mathsf{A}, \\mathsf{B} \\in N_C$ and $\\mathsf{r} \\in N_R$, both implications $\\set{\n    \\mathsf{A} } \\to \\set{ \\mathsf{B} }$ and $\\set{ \\mathsf{\\exists r. A} } \\to \\set{\n    \\mathsf{\\exists r. (A \\sqcap B)} }$ have confidence at least $c$ in $\\con\n  K_{\\mathcal{I}}$.  Then by\n  \\Cref{prop:confidence-in-interpretation-is-the-same-as-in-induced-context}, $\\mathsf{A\n    \\sqsubseteq B}$ and $\\mathsf{\\exists r. A \\sqsubseteq \\exists r. (A \\sqcap B)}$ have\n  confidence at least $c$ in $\\mathcal{I}$.  If we can include these two implications in\n  an irredundant base $\\mathcal{L}$ of $\\Th_c(\\con K_{\\mathcal{I}})$ with background\n  knowledge $\\mathcal{S}_{\\mathcal{I}}$, then $\\bigsqcap \\mathcal{L}$ contains\n  redundancies, as desired.\n\n  \\begin{figure}[tp]\n    \\centering\n    \\begin{tikzpicture}\n      \\begin{scope}[every node/.style = {draw,circle}]\n        \\node[label=above:{$\\mathsf{A}$}] (1) at (-2,0) {\\small 1};\n        \\node[label=above:{$\\mathsf{A}$}] (2) at ( 0,0) {\\small 2};\n        \\node[label=above:{$\\mathsf{B}$}] (3) at ( 2,0) {\\small 3};\n        \\node[label=below:{$\\mathsf{A, B}$}] (4) at (-1.5,-2) {\\small 4};\n        \\node[label=below:{$\\mathsf{A, B}$}] (5) at (-0.5,-2) {\\small 5};\n        \\node[label=below:{$\\mathsf{A, B}$}] (6) at ( 0.5,-2) {\\small 6};\n        \\node[label=below:{$\\mathsf{A, B}$}] (7) at ( 1.5,-2) {\\small 7};\n      \\end{scope}\n      \\path[every edge/.style={draw,->}] {\n        \\foreach \\x in {1,2,3} {\n          \\foreach \\y in {4,5,6,7} {\n            (\\x) edge (\\y)\n          }\n        }\n      };\n    \\end{tikzpicture}\n    \\caption{Example interpretation $\\mathcal{I}$ for\n      \\Cref{expl:nonredundant-implicational-base-yields-redundant-gci-base}.}\n    \\label{fig:example-interpretation-1}\n  \\end{figure}\n\n  So let $N_C := \\set{ \\mathsf{A}, \\mathsf{B} }$ and $N_R := \\set{ \\mathsf{r} }$.\n  Consider the interpretation $\\mathcal{I}$ as given in\n  \\Cref{fig:example-interpretation-1}, where every edge is labeled with $\\mathsf{r}$.  Then\n  \\begin{align*}\n    \\conf_{\\mathcal{I}}(\\mathsf{A} \\sqsubseteq \\mathsf{B}) &= \\frac 2 3\\\\\n    \\conf_{\\mathcal{I}}(\\mathsf{\\exists r. A} \\sqsubseteq \\mathsf{\\exists r. B}) &= 1,\n  \\end{align*}\n  thus following our argumentation from above we can choose $c = \\frac 1 2$, say.  Then we\n  want to find a irredundant set $\\mathcal{L}$ of implications such that $\\mathcal{L} \\cup\n  \\mathcal{S}_{\\mathcal{I}}$ is a confident base of $\\Th_c(\\con K_{\\mathcal{I}})$ and\n  $\\mathcal{L}$ contains both $\\set{ \\mathsf{A} } \\to \\set{ \\mathsf{B} }$ and $\\set{\n    \\mathsf{\\exists r. A} } \\to \\set{ \\mathsf{\\exists r. (A \\sqcap B)} }$.  We find\n  \\begin{multline*}\n    M_{\\mathcal{I}} = \\{\\, \\mathsf{ \\bot, A, B, \\exists r.(A \\sqcap \\exists r.(A \\sqcap B)), }\\\\\n    \\mathsf{ \\exists r.(B \\sqcap \\exists r.(A \\sqcap B)), \\exists r.(A \\sqcap B), \\exists\n    r.\\exists r.(A \\sqcap B), \\exists r.A, \\exists r.B, \\exists r.\\top } \\,\\},\n  \\end{multline*}\n  and $\\con K_{\\mathcal{I}}$ is as shown in\n  \\Cref{fig:induced-formal-context-of-example-interpretation-1}.\n\n  \\begin{figure}[tp]\n    \\centering\n    \\newcommand{\\attbox}[1]{\\parbox[b][1ex][b]{1cm}{\n        \\rotatebox{45}{$\\mathsf{#1}$}}}\n    \\vspace*{1.5cm}\n    \\begin{equation*}\n      \\begin{array}[c]{c||*{3}{c}*{7}{>{}c<{}}}\n        \\con{K}_{\\mathcal{I}} & \\bot & \\mathsf{A} & \\mathsf{B} &\n        \\hbox to 1cm{\\attbox{\\exists r.(A \\sqcap \\exists r.(A \\sqcap B))}} &\n        \\attbox{\\exists r.(B \\sqcap \\exists r.(A \\sqcap B))} &\n        \\attbox{\\exists r.(A \\sqcap B)} &\n        \\attbox{\\exists r.\\exists r.(A \\sqcap B)} &\n        {\\mathsf{\\exists r.A}} &\n        {\\mathsf{\\exists r.B}} &\n        {\\mathsf{\\exists r.\\top}} \\\\\n        \\hline\n        1 &  & \\times &  &  &  & \\times &   & \\times & \\times & \\times \\\\\n        2 &  & \\times &  &  &  & \\times &   & \\times & \\times & \\times \\\\\n        3 &  &        & \\times &   &   & \\times &   & \\times & \\times & \\times \\\\\n        4 &  & \\times & \\times &   &   &   &   &   &   &   \\\\\n        5 &  & \\times & \\times &   &   &   &   &   &   &   \\\\\n        6 &  & \\times & \\times &   &   &   &   &   &   &   \\\\\n        7 &  & \\times & \\times &   &   &   &   &   &   &   \\\\\n      \\end{array}\n    \\end{equation*}\n    \\caption{Induced formal context of $\\mathcal{I}$ as in\n      \\Cref{expl:nonredundant-implicational-base-yields-redundant-gci-base}.}\n    \\label{fig:induced-formal-context-of-example-interpretation-1}\n  \\end{figure}\n\n  By \\Cref{thm:conf-base} the set $\\Can(\\con K_{\\mathcal{I}}) \\cup \\Conf(\\mathcal{I}, c)$\n  is a finite confident base of $\\Th_c(\\con K_{\\mathcal{I}})$.  An irredundant subset\n  $\\mathcal{L}$ of this base which is still a base of $\\Th_c(\\con K_{\\mathcal{I}})$ with\n  background knowledge $\\mathcal{S}_{\\mathcal{I}}$ is given by the following list of\n  implications:\n  \\begin{align*}\n    \\emptyset &\\to \\set{\\mathsf A},\\\\\n    \\set{\\mathsf A}    &\\to \\set{\\mathsf B},\\\\\n    \\set{\\mathsf{\\exists r.A}} &\\to \\set{\\mathsf{\\exists r.(A \\sqcap B)}},\\\\\n    \\set{\\mathsf{\\exists r.B}} &\\to \\set{\\mathsf{\\exists r.(A \\sqcap B)}},\\\\\n    \\set{\\mathsf{\\exists r.\\top}} &\\to \\set{\\mathsf{\\exists r.(A \\sqcap B)}},\\\\\n    \\set{\\mathsf{A, B, \\exists r.(A \\sqcap B)}} &\\to \\set{\\bot},\\\\\n    \\set{\\mathsf{\\exists r.\\exists r.(A \\sqcap B)}} &\\to \\set{\\bot},\\\\\n    \\set{\\mathsf{\\exists r.(B \\sqcap \\exists r.(A \\sqcap B))}} &\\to \\set{\\bot},\\\\\n    \\set{\\mathsf{\\exists r.(A \\sqcap \\exists r.(A \\sqcap B))}} &\\to \\set{\\bot}.\n  \\end{align*}\n  Then $\\mathcal{L}$ is irredundant and by\n  \\Cref{cor:using-background-knowledge-for-confident-bases} the set $\\bigsqcap\n  \\mathcal{L}$ is a base of $\\Th_c(\\mathcal{I})$.  But $\\bigsqcap \\mathcal{L}$ contains\n  the GCIs $\\mathsf{A \\sqsubseteq B}$ and $\\mathsf{\\exists r. A \\sqsubseteq \\exists r. (A\n    \\sqcap B)}$, and thus $\\bigsqcap \\mathcal{L}$ is not irredundant.\n\\end{Example}\n\nInstead of only considering irredundant bases of $\\Th_c(\\con K_{\\mathcal{I}})$, we can go\neven a step further and consider \\emph{minimal} bases of $\\Th_c(\\con K_{\\mathcal{I}})$.\nFor this we recall that if $\\mathcal{L}$ is a base of $\\Th_c(\\con K_{\\mathcal{I}})$, then\nthe canonical base $\\Can(\\mathcal{L})$ of $\\mathcal{L}$ is a minimal base of $\\Th_c(\\con\nK_{\\mathcal{I}})$.\\footnote{Note that we have only introduced the canonical base for\n  formal contexts, but by \\Cref{prop:context-model-for-implications} we can represent\n  every set $\\mathcal{L}$ as a base of a formal context $\\con K_{\\mathcal{L}}$.  Then\n  $\\Can(\\mathcal{L}) := \\Can(\\con K_{\\mathcal{L}})$.  Note that this definition is\n  independent from the context $\\con K_{\\mathcal{L}}$ we use.}  Since $\\Cn(\\mathcal{L}) =\n\\Cn(\\Can(\\mathcal{L}))$, we know that $\\Can(\\mathcal{L})$ is also a base of $\\Th_c(\\con\nK_{\\mathcal{I}})$.  In particular, if $\\mathcal{L} = \\Th_c(\\con K_{\\mathcal{I}})$ we can\nconsider $\\Can(\\Th_c(\\con K_{\\mathcal{I}}))$ as a minimal base of $\\Th_c(\\con\nK_{\\mathcal{I}})$.\\footnote{Also note that $\\Can(\\mathcal{L}) = \\Can(\\Th_c(\\con\n  K_{\\mathcal{I}}))$ for all bases $\\mathcal{L}$ of $\\Th_c(\\con K_{\\mathcal{I}})$.}  In\nthis case we also obtain that $\\bigsqcap \\Can(\\Th_c(\\con K_{\\mathcal{I}}))$ is a finite\nbase of $\\Th_c(\\mathcal{I})$, as the following argumentation shows.\n\n\\begin{Corollary}\n  \\label{cor:bases-of-implications-to-bases-of-gcis}\n  Let $\\mathcal{I}$ be a finite interpretation, let $c \\in [0,1]$ and let $\\mathcal{K}\n  \\subseteq \\Imp(M_{\\mathcal{I}})$ be a base of $\\Th_c(\\con K_{\\mathcal{I}})$.  Then\n  $\\bigsqcap \\mathcal{K}$ is a base of $\\Th_c(\\mathcal{I})$.\n\\end{Corollary}\n\\begin{Proof}\n  By \\Cref{thm:confident-bases-of-GCIs-from-confident-bases-of-implications} we know that\n  $\\bigsqcap \\Th_c(\\con K_{\\mathcal{I}})$ is a finite confident base of\n  $\\Th_c(\\mathcal{I})$.  As $\\mathcal{K}$ is a base of $\\Th_c(\\con K_{\\mathcal{I}})$ we\n  can infer from \\Cref{lem:implicational-entailment-implies-gci-entailment} that\n  $\\bigsqcap \\mathcal{K}$ is also complete for $\\bigsqcap \\Th_c(\\con K_{\\mathcal{I}})$.\n  We thus obtain that $\\bigsqcap \\mathcal{K}$ is complete for $\\Th_c(\\mathcal{I})$.\n\n  On the other hand, since $\\mathcal{K}$ is a base of $\\Th_c(\\con K_{\\mathcal{I}})$, it is\n  also true that $\\Th_c(\\con K_{\\mathcal{I}})$ is a base of $\\mathcal{K}$.  But then all\n  implications in $\\mathcal{K}$ are entailed by $\\Th_c(\\con K_{\\mathcal{I}})$, and\n  \\Cref{lem:implicational-entailment-implies-gci-entailment} yields that all GCIs in\n  $\\bigsqcap \\mathcal{K}$ are entailed by $\\bigsqcap \\Th_c(\\con K_{\\mathcal{I}}) \\subseteq\n  \\Th_c(\\mathcal{I})$.  Thus, $\\bigsqcap \\mathcal{K}$ is also sound for\n  $\\Th_c(\\mathcal{I})$, and in sum we obtain that $\\bigsqcap \\mathcal{K}$ is a finite base\n  of $\\Th_c(\\mathcal{I})$.\n\\end{Proof}\n\nThe approach of considering the canonical base of $\\Th_c(\\con K)$ has the potential\ndrawback, however, that we cannot guarantee anymore that the base itself is a confident\nbase, \\ie it can happen that $\\bigsqcap \\Can(\\Th_c(\\con K)) \\subseteq \\Th_c(\\mathcal{I})$\ndoes not hold.\n\n\\subsection{Completing Sets of GCIs}\n\\label{sec:completing-sets-of-gcis}\n\nThe bases we have obtained in \\Cref{cor:weakened-luxenburger-base-for-gcis} consisted of\ntwo parts, namely a complete subset $\\mathcal{B}$ of $\\Lux(\\mathcal{I}, c)$ and a set\n$\\mathcal{L}$ of valid GCIs such that $\\mathcal{L} \\cup \\mathcal{B}$ is complete for\n$\\mathcal{I}$.  In this section we are going to show that we can, given the set\n$\\mathcal{B}$, compute the set $\\mathcal{L}$ in such a way that $\\mathcal{L} \\cup\n\\mathcal{B}$ is complete for $\\Th(\\mathcal{I})$.\n\nThe results of this section have previously been published\nin~\\cite{Borchmann:confident-GCIs}.\n\nThe idea we want to exploit for this is borrowed from formal concept analysis: if\n$\\mathcal{B}$ is a set of implications, then we can find a set $\\mathcal{L}$ of\nimplications valid in a formal context $\\con K$ such that $\\mathcal{L}$ has minimal\ncardinality.  More precisely, the set\n\\begin{equation*}\n  \\mathcal{L} := \\Can(\\con K, \\mathcal{B})\n\\end{equation*}\nhas this property by \\Cref{thm:canonical-base-with-arbitrary-background-knowledge}.  What\nwe want to do in this section is to lift this result to the level of general concept\ninclusions.\n\nTo this end, we need to transform sets of general concept inclusions into sets of\nimplications.  For this, we make use of projections $\\pr_M$ as introduced in\n\\Cref{sec:induced-contexts}.  More precisely, if $M$ is a set of concept descriptions and\n$\\mathcal{B}$ is a set of GCIs, then we define\n\\begin{equation*}\n  \\pr_M(\\mathcal{B}) := \\set{ \\pr_M(C) \\to \\pr_M(D) \\mid (C \\sqsubseteq D) \\in \\mathcal{B} }.\n\\end{equation*}\nFor $M = M_{\\mathcal{I}}$, we can take the set $\\pr_{M_{\\mathcal{I}}}(\\mathcal{B})$ and\ncompute $\\Can(\\con K_{\\mathcal{I}}, \\pr_{M_{\\mathcal{I}}}(\\mathcal{B}))$.  It is then true\nthat\n\\begin{equation*}\n  \\mathcal{B} \\cup \\set{ \\bigsqcap U \\sqsubseteq (\\bigsqcap U)^{\\mathcal{I}\\mathcal{I}} \\mid (U \\to U'')\n    \\in \\Can(\\con K_{\\mathcal{I}}, \\pr_{M_{\\mathcal{I}}}(\\mathcal{B})) }\n\\end{equation*}\nis complete for $\\mathcal{I}$, provided that the concept descriptions in $\\mathcal{B}$ are\nall expressible in terms of $M_{\\mathcal{I}}$.\n\nThis result already appeared in \\cite[Theorem~5.12]{Diss-Felix}, however only for the case\nthat $\\mathcal{B}$ is empty.  We shall generalize this result to also cover the case that\n$\\mathcal{B}$ contains arbitrary GCIs.  The proof of this generalization is similar to the\none of \\cite[Theorem~5.12]{Diss-Felix}.\n\n\\begin{Theorem}\n  \\label{thm:gci-completion-simple-version}\n  Let $\\mathcal{I}$ be a finite interpretation over $N_C$ and $N_R$, and let $\\mathcal{B}$\n  be a set of GCIs over $N_C$ and $N_R$, where all concept descriptions appearing in\n  $\\mathcal{B}$ are expressible in terms of $M_{\\mathcal{I}}$.  Let $\\mathcal{L} \\subseteq\n  \\Th(\\con K_{\\mathcal{I}})$ such that\n  \\begin{enumerate}[i. ]\n  \\item\\label{item:18} $\\mathcal{L} \\cup \\pr_{M_{\\mathcal{I}}}(\\mathcal{B})$ is complete\n    for $\\con K_{\\mathcal{I}}$, and\n  \\item\\label{item:19} $\\mathcal{L}$ only contains implications of the form $A \\to A''$\n    with $A \\subseteq M_{\\mathcal{I}}$.\n  \\end{enumerate}\n  Then $\\bigsqcap \\mathcal{L} \\cup \\mathcal{B}$ is complete for $\\mathcal{I}$.\n\\end{Theorem}\n\\begin{Proof}\n  We show that for each $U \\subseteq M_{\\mathcal{I}}$ it is true that\n  \\begin{equation*}\n    \\bigsqcap \\mathcal{L} \\cup \\mathcal{B} \\models (\\bigsqcap U \\sqsubseteq (\\bigsqcap\n    U)^{\\mathcal{I}\\mathcal{I}}).\n  \\end{equation*}\n  If we establish this fact, then \\Cref{thm:Felix-base-B2} immediately yields that\n  $\\bigsqcap \\mathcal{L} \\cup \\mathcal{B}$ is complete for $\\Th(\\mathcal{I})$.\n\n  Let $\\mathcal{J}$ be a finite interpretation such that $\\mathcal{J} \\models (\\bigsqcap\n  \\mathcal{L} \\cup \\mathcal{B})$.  Let us write $\\cdot^{\\prime_{\\mathcal{I}}}$ for the\n  derivation operators in $\\con K_{\\mathcal{I}, M_{\\mathcal{I}}}$, and\n  $\\cdot^{\\prime_{\\mathcal{J}}}$ for the derivation operators in $\\con K_{\\mathcal{J},\n    M_{\\mathcal{I}}}$.  We shall then show the following claims\n  \\begin{enumerate}[i. ]\n  \\item\\label{item:20} $\\con K_{\\mathcal{J}, M_{\\mathcal{I}}} \\models (\\mathcal{L} \\cup\n    \\pr_{M_{\\mathcal{I}}}(\\mathcal{B}))$,\n  \\item $\\con K_{\\mathcal{J}, M_{\\mathcal{I}}} \\models (U \\to\n    U^{\\prime_{\\mathcal{I}}\\prime_{\\mathcal{I}}})$ for all $U \\subseteq M_{\\mathcal{I}}$,\n    and finally\n  \\item $\\mathcal{J} \\models (\\bigsqcap U \\sqsubseteq (\\bigsqcap\n    U)^{\\mathcal{I}\\mathcal{I}})$ for all $U \\subseteq M_{\\mathcal{I}}$.\n  \\end{enumerate}\n\n  To show the first claim we start with some preparations.  Let $U \\subseteq\n  M_{\\mathcal{I}}$.  Then by \\Cref{prop:connection-I-prime-2} it is true that\n  \\begin{equation}\n    \\label{eq:29}\n    (\\bigsqcap U)^{\\mathcal{J}} = U^{\\prime_{\\mathcal{J}}}.\n  \\end{equation}\n  Furthermore, the concept description $(\\bigsqcap U)^{\\mathcal{I}\\mathcal{I}}$ is\n  expressible in terms of $M_{\\mathcal{I}}$ by\n  \\Cref{lem:mmsc-are-expressible-in-terms-of-M_I}.  From this we can infer with\n  \\Cref{lem:characterizing-expressible-in-terms-of} that\n  \\begin{equation*}\n    (\\bigsqcap U)^{\\mathcal{I}\\mathcal{I}} \\equiv \\bigsqcap\n    \\pr_{M_{\\mathcal{I}}}((\\bigsqcap U)^{\\mathcal{I}\\mathcal{I}}).\n  \\end{equation*}\n  Then \\Cref{cor:mmsc-lattice} yields\n  \\begin{equation}\n    \\label{eq:30}\n    \\begin{aligned}\n      ((\\bigsqcap U)^{\\mathcal{I}\\mathcal{I}})^{\\mathcal{J}}\n      &= (\\bigsqcap \\pr_{M_{\\mathcal{I}}}((\\bigsqcap\n      U)^{\\mathcal{I}\\mathcal{I}}))^{\\mathcal{J}} \\\\\n      &= (\\pr_{M_{\\mathcal{I}}}((\\bigsqcap\n      U)^{\\mathcal{I}\\mathcal{I}}))^{\\prime_{\\mathcal{J}}} \\\\\n      &= U^{\\prime_{\\mathcal{I}}\\prime_{\\mathcal{I}}\\prime_{\\mathcal{J}}}.\n    \\end{aligned}\n  \\end{equation}\n  Now let $(U \\to U^{\\prime_{\\mathcal{I}}\\prime_{\\mathcal{I}}}) \\in \\mathcal{L}$.  Then\n  $\\mathcal{J} \\models (\\bigsqcap U \\sqsubseteq (\\bigsqcap U)^{\\mathcal{I}\\mathcal{I}})$,\n  and therefore\n  \\begin{equation*}\n    (\\bigsqcap U)^{\\mathcal{J}} \\subseteq ((\\bigsqcap U)^{\\mathcal{I}\\mathcal{I}})^{\\mathcal{J}},\n  \\end{equation*}\n  and \\Cref{eq:29} and \\Cref{eq:30} yield\n  \\begin{equation*}\n    U^{\\prime_{\\mathcal{J}}} \\subseteq U^{\\prime_{\\mathcal{I}}\\prime_{\\mathcal{I}}\\prime_{\\mathcal{J}}},\n  \\end{equation*}\n  \\ie $\\con K_{\\mathcal{J}, M_{\\mathcal{I}}} \\models (U \\to\n  U^{\\prime_{\\mathcal{I}}\\prime_{\\mathcal{I}}})$.  Thus, $\\con K_{\\mathcal{J},\n    M_{\\mathcal{I}}} \\models \\mathcal{L}$.\n\n  Let $(C \\sqsubseteq D) \\in \\mathcal{B}$.  It remains to show that\n  $\\pr_{M_{\\mathcal{I}}}(C) \\to \\pr_{M_{\\mathcal{I}}}(D)$ holds in $\\con K_{\\mathcal{J},\n    M_{\\mathcal{I}}}$.  It is true that $\\mathcal{J} \\models (C \\sqsubseteq D)$, \\ie\n  $C^{\\mathcal{J}} \\subseteq D^{\\mathcal{J}}$.  Since both $C, D$ are expressible in terms\n  of $M_{\\mathcal{I}}$, \\Cref{lem:characterizing-expressible-in-terms-of} yields\n  \\begin{equation*}\n    (\\bigsqcap \\pr_{M_{\\mathcal{I}}}(C))^{\\mathcal{J}} \\subseteq (\\bigsqcap\n    \\pr_{M_{\\mathcal{I}}}(D))^{\\mathcal{J}}\n  \\end{equation*}\n  and thus, using \\Cref{eq:29} again,\n  \\begin{equation*}\n    \\pr_{M_{\\mathcal{I}}}(C)^{\\prime_{\\mathcal{J}}} \\subseteq \\pr_{M_{\\mathcal{I}}}(D)^{\\prime_\\mathcal{J}},\n  \\end{equation*}\n  \\ie $\\con K_{\\mathcal{J}, M_{\\mathcal{I}}} \\models (\\pr_{M_{\\mathcal{I}}}(C) \\to\n  \\pr_{M_{\\mathcal{I}}}(D))$.  Thus we have shown that $\\con K_{\\mathcal{J},\n    M_{\\mathcal{I}}} \\models \\mathcal{B}$.  This proves the first claim.\n\n  Now let $U \\subseteq M_{\\mathcal{I}}$.  Then $\\con K_{\\mathcal{I}} \\models (U \\to\n  U^{\\prime_{\\mathcal{I}}\\prime_{\\mathcal{I}}})$.  Since $\\mathcal{L} \\cup\n  \\pr_{M_{\\mathcal{I}}}(\\mathcal{B})$ is complete for $\\con K_{\\mathcal{I}}$, we obtain\n  \\begin{equation*}\n    \\mathcal{L} \\cup \\pr_{M_{\\mathcal{I}}}(\\mathcal{B}) \\models (U \\to\n    U^{\\prime_{\\mathcal{I}}\\prime_{\\mathcal{I}}}).\n  \\end{equation*}\n  Since $\\con K_{\\mathcal{J}, M_{\\mathcal{I}}} \\models \\mathcal{L} \\cup\n  \\pr_{M_{\\mathcal{I}}}(\\mathcal{B})$, it is true that\n  \\begin{equation*}\n    \\con K_{\\mathcal{J}, M_{\\mathcal{I}}} \\models (U \\to U^{\\prime_{\\mathcal{I}}\\prime_{\\mathcal{I}}}),\n  \\end{equation*}\n  \\ie $U^{\\prime_{\\mathcal{J}}} \\subseteq\n  U^{\\prime_{\\mathcal{I}}\\prime_{\\mathcal{I}}\\prime_{\\mathcal{J}}}$.  Using \\Cref{eq:29}\n  and \\Cref{eq:30} again yields\n  \\begin{equation*}\n    (\\bigsqcap U)^{\\mathcal{J}} \\subseteq ((\\bigsqcap U)^{\\mathcal{I}\\mathcal{I}})^{\\mathcal{J}},\n  \\end{equation*}\n  \\ie $\\mathcal{J} \\models (\\bigsqcap U \\sqsubseteq (\\bigsqcap\n  U)^{\\mathcal{I}\\mathcal{I}})$.  Since $U \\subseteq M_{\\mathcal{I}}$ was chosen\n  arbitrarily, we have thus shown that $\\bigsqcap \\mathcal{L} \\cup \\mathcal{B}$ is\n  complete for $\\mathcal{I}$.\n\\end{Proof}\n\nWe can apply this theorem to our setting of computing finite confident bases as follows.\nLet $\\mathcal{C} \\subseteq \\Lux(\\mathcal{I}, c)$ be complete for $\\Lux(\\mathcal{I}, c)$.\nIf we compute $\\mathcal{L} := \\Can(\\con K_{\\mathcal{I}},\n\\pr_{M_{\\mathcal{I}}}(\\mathcal{B}))$, then $\\mathcal{L}$ is as required by the above\ntheorem, and thus $\\bigsqcap \\mathcal{L} \\cup \\mathcal{B}$ is complete for $\\mathcal{I}$.\nBy \\Cref{cor:weakened-luxenburger-base-for-gcis} the set $\\bigsqcap \\mathcal{L} \\cup\n\\mathcal{C}$ is a finite confident base of $\\Th_c(\\mathcal{I})$.\n\nOf course, we can also include the implications in $\\mathcal{S}_{\\mathcal{I}}$ as\nbackground knowledge when computing $\\mathcal{L}$.  To see this we observe that the proof\nof \\Cref{thm:gci-completion-simple-version} still works if we include\n$\\mathcal{S}_{\\mathcal{I}}$ in the computation of $\\mathcal{L}$.  Part(\\ref{item:20}) of\nthe proof would then be extended to also claim that $\\con K_{\\mathcal{J}, M_{\\mathcal{I}}}\n\\models \\mathcal{S}_{\\mathcal{I}}$, which is true for all induced contexts with attribute\nset $M_{\\mathcal{I}}$.\n\n\\begin{Corollary}\n  \\label{cor:gci-completion-with-S_I}\n  Let $\\mathcal{I}$ be a finite interpretation over $N_C$ and $N_R$, and let $\\mathcal{C}\n  \\subseteq \\Lux(\\mathcal{I}, c)$ be complete for $\\Lux(\\mathcal{I}, c)$.  Define\n  \\begin{equation*}\n    \\mathcal{L} := \\Can(\\con K_{\\mathcal{I}}, \\pr_{M_{\\mathcal{I}}}(\\mathcal{C}) \\cup \\mathcal{S}_{\\mathcal{I}}).\n  \\end{equation*}\n  Then $\\bigsqcap \\mathcal{L} \\cup \\mathcal{C}$ is a finite confident base of\n  $\\Th_c(\\mathcal{I})$.\n\\end{Corollary}\n\nFor $c = 0$ we obtain $\\Lux(\\mathcal{I}, c) = \\emptyset$, and thus we are back in the case\nof valid GCIs.  For this we know from \\Cref{thm:Felix-5.18} that the set $\\bigsqcap\n\\mathcal{L}$ in the previous corollary is \\emph{minimal} with respect to being a base of\n$\\mathcal{I}$.  A natural question is now to ask whether we can also expect such a\nminimality result to be true in the case of GCIs with high confidence, \\ie whether\n$\\bigsqcap \\mathcal{L}$ is minimal with respect to $\\bigsqcap \\mathcal{L} \\cup\n\\mathcal{B}$ being a finite confident base of $\\Th_c(\\mathcal{I})$.  The next example\nshows that this is not the case.\n\n\\begin{Example}\n  \\label{expl:no-minimality}\n  Let $N_C = \\set{ \\mathsf{A}, \\mathsf{B} }$ and $N_R = \\set{ \\mathsf{r} }$ and consider\n  the finite interpretation $\\mathcal{I} = (\\Delta^{\\mathcal{I}}, \\cdot^{\\mathcal{I}})$ as\n  given in \\Cref{fig:no-minimality}.\n\n  \\begin{figure}[tp]\n    \\centering\n    \\begin{tikzpicture}\n      \\node[draw, circle, label=above:{\\textsf{A,B}}] (1) at (0,0) {1};\n      \\node[draw, circle, label=above:{\\textsf{A,B}}] (2) at (1,0) {2};\n      \\node[draw, circle, label=above:{\\textsf{A,B}}] (3) at (2,0) {3};\n      \\node[draw, circle, label=above:{\\textsf{A,B}}] (4) at (3,0) {4};\n      \\node[draw, circle, label=above:{\\textsf{A}}] (5) at (4,0) {5};\n      \\draw[->] (2) edge[bend left=50] node[midway,below] {\\textsf{r}} (1);\n      \\draw[->] (3) edge[bend left=80] node[midway,below] {\\textsf{r}} (1);\n    \\end{tikzpicture}\n    \\caption{Interpretation for \\Cref{expl:no-minimality}}\n    \\label{fig:no-minimality}\n  \\end{figure}\n\n  If $X \\subseteq \\Delta^{\\mathcal{I}}$ is such that $5 \\in X$, then $X^{\\mathcal{I}} =\n  \\mathsf{A}$.  If $5 \\notin X$ but $1 \\in X$ or $4 \\in X$, then $X^{\\mathcal{I}} =\n  \\mathsf{A} \\sqcap \\mathsf{B}$.  Otherwise, $X^{\\mathcal{I}} = \\mathsf{A \\sqcap B \\sqcap\n    \\exists r.(A \\sqcap B)}$.  Thus the set of model-based most-specific concept\n  descriptions of $\\mathcal{I}$ is (up to equivalence)\n  \\begin{equation*}\n    \\set{ \\bot, \\mathsf{A}, \\mathsf{A \\sqcap B}, \\mathsf{A \\sqcap B \\sqcap \\exists\n        r.(A \\sqcap B)} }\n  \\end{equation*}\n  and thus we obtain\n  \\begin{equation*}\n    M_{\\mathcal{I}} := \\set{ \\bot, \\mathsf{A}, \\mathsf{B}, \\mathsf{\\exists r. A},\n      \\mathsf{\\exists r. (A \\sqcap B)}, \\mathsf{\\exists r. (A \\sqcap B \\sqcap \\exists\n        r. (A \\sqcap B))} }.\n  \\end{equation*}\n  The induced context is shown in \\Cref{fig:no-minimality-induced-context}.\n\n  \\begin{figure}[tp]\n    \\centering\n    \\begin{math}\n      \\begin{array}{c|*{6}{c}}\n        \\toprule\n        ~ & \\bot & \\mathsf{A} & \\mathsf{B} & \\mathsf{\\exists r. A} & \\mathsf{\\exists r. (A\n          \\sqcap B)} & \\mathsf{\\exists r. (A \\sqcap B \\sqcap \\exists r. (A \\sqcap B))} \\\\\n        \\midrule\n        1 & & \\times & \\times \\\\\n        2 & & \\times & \\times & \\times & \\times \\\\\n        3 & & \\times & \\times & \\times & \\times \\\\\n        4 & & \\times & \\times \\\\\n        5 & & \\times  \\\\\n        \\bottomrule\n      \\end{array}\n    \\end{math}\n    \\caption{Induced Context of \\Cref{fig:no-minimality}}\n    \\label{fig:no-minimality-induced-context}\n  \\end{figure}\n\n  Let $c = \\frac 4 5$.  Then $\\Conf(\\con K_{\\mathcal{I}}, c) = \\set{ \\set{ \\mathsf{A} }\n    \\to \\set{ \\mathsf{A}, \\mathsf{B} } }$, thus\n  \\begin{equation*}\n    \\Conf(\\mathcal{I}, c) = \\set{ \\mathsf{A} \\sqsubseteq \\mathsf{A \\sqcap B} }.\n  \\end{equation*}\n  Set $\\mathcal{B} := \\Conf(\\mathcal{I}, c)$.  Then $\\pr_{M_{\\mathcal{I}}}(\\mathcal{B}) =\n  \\Conf(\\con K_{\\mathcal{I}}, c)$.  Let\n  \\begin{equation*}\n    U := \\set{ \\mathsf{\\exists r. A}, \\mathsf{A}, \\mathsf{B} }.\n  \\end{equation*}\n  Then $U$ is closed under $\\mathcal{S}_{\\mathcal{I}}$.  Furthermore, $U$ is a\n  $\\pr_{M_{\\mathcal{I}}}(\\mathcal{B})$-pseudo-intent of $\\con K_{\\mathcal{I}}$:\n  $\\emptyset$ is a $\\pr_{M_{\\mathcal{I}}}(\\mathcal{B})$-pseudo-intent of $\\con\n  K_{\\mathcal{I}}$, and $\\emptyset'' = \\set{ \\mathsf{A} } \\subseteq U$.  The set $\\set{\n    \\mathsf{A} }$ is an intent of $\\con K_{\\mathcal{I}}$, and the sets $\\set{ \\mathsf{B}\n  }$ and $\\set{ \\mathsf{\\exists r. A} }$ are not supersets of $\\emptyset'' = \\set{\n    \\mathsf{A} }$.  The set $\\set{ \\mathsf{A}, \\mathsf{B} }$ is again an intent of $\\con\n  K_{\\mathcal{I}}$, $\\set{ \\mathsf{\\exists r. A}, \\mathsf{A} }$ is not closed under\n  $\\pr_{M_{\\mathcal{I}}}(\\mathcal{B})$ and $\\set{ \\mathsf{\\exists r. A}, \\mathsf{B} }$\n  does not contain $A$.  Thus, the only $\\pr_{M_{\\mathcal{I}}}(\\mathcal{B})$-pseudo-intent\n  of $\\con K_{\\mathcal{I}}$ contained in $U$ is $\\emptyset$, and its closure is again\n  contained in $U$.  Thus, $U$ is a $\\pr_{M_{\\mathcal{I}}}(\\mathcal{B})$-pseudo-intent of\n  $\\con K_{\\mathcal{I}}$.\n\n  Therefore, $(U \\to U'') \\in \\Can(\\con K_{\\mathcal{I}},\n  \\pr_{M_{\\mathcal{I}}}(\\mathcal{B}) \\cup \\mathcal{S}_{\\mathcal{I}})$, \\ie\n  \\begin{equation*}\n    (\\set{ \\mathsf{\\exists r. A}, \\mathsf{A}, \\mathsf{B} } \\to \\set{ \\mathsf{\\exists r. (A\n        \\sqcap B)} }) \\in \\Can(\\con K_{\\mathcal{I}}, \\pr_{M_{\\mathcal{I}}}(\\mathcal{B}) \\cup\n    \\mathcal{S}_{\\mathcal{I}}).\n  \\end{equation*}\n  This yields that\n  \\begin{equation*}\n    (\\mathsf{\\exists r. A \\sqcap A \\sqcap B} \\sqsubseteq \\mathsf{\\exists r. (A \\sqcap B)})\n    \\in \\bigsqcap \\Can(\\con K_{\\mathcal{I}}, \\pr_{M_{\\mathcal{I}}}(\\mathcal{B}) \\cup \\mathcal{S}_{\\mathcal{I}}).\n  \\end{equation*}\n  But this GCI is entailed by $\\mathcal{B}$, so the set $\\bigsqcap \\Can(\\con\n  K_{\\mathcal{I}}, \\pr_{M_{\\mathcal{I}}}(\\mathcal{B}) \\cup \\mathcal{S}_{\\mathcal{I}}) \\cup\n  \\mathcal{B}$ is not irredundant.  In particular, $\\bigsqcap \\Can(\\con K_{\\mathcal{I}},\n  \\pr_{M_{\\mathcal{I}}}(\\mathcal{B}) \\cup \\mathcal{S}_{\\mathcal{I}})$ is not minimal with\n  respect to the property that it forms together with $\\mathcal{B}$ a confident base of\n  $\\Th_c(\\mathcal{I})$.\n\\end{Example}\n\nThe main reason why the minimality statement fails is that entailment between GCIs can\nhappen \\enquote{behind the quantifier}: if $\\mathcal{B} = \\set{ \\mathsf{A} \\sqsubseteq\n  \\mathsf{B} }$, then $\\mathcal{B}$ entails $\\mathsf{\\exists r. A} \\sqsubseteq\n\\mathsf{\\exists r. B}$.  This entailment process can usually not be simulated by\nimplications, as they are not allowed to consider the structure of the attributes in a\nformal context.\n\nIt is possible to find a special case where entailment behind the quantifier cannot\nhappen: if $\\mathcal{B}$ is a set of \\emph{valid} GCIs of $\\mathcal{I}$, and if $C =\n\\bigsqcap U$ for $U \\subseteq M_{\\mathcal{I}}$ and $U \\neq \\emptyset$.  In this case, $C$\ncan be written as\n\\begin{equation*}\n  C = \\bigsqcap V \\sqcap \\bigsqcap_{(r, Z) \\in \\Pi} \\exists r. Z^{\\mathcal{I}}\n\\end{equation*}\nfor some $V \\subseteq N_C$ and some $\\Pi \\subseteq N_R \\times\n\\subsets{\\Delta^{\\mathcal{I}}}$.  Then one can argue that the concept descriptions\n$Z^{\\mathcal{I}}$ behind the quantifier are already \\enquote{closed under entailment} with\nrespect to $\\mathcal{B}$, because they are model-based most-specific concept descriptions\nand all GCIs in $\\mathcal{B}$ are valid in $\\mathcal{I}$.  Thus, if a GCI $C \\sqsubseteq\nD$ is entailed by $\\mathcal{B}$, it must happen on the top-level of the concept\ndescriptions, and this entailment can then be simulated by implications.\n\nA formal argumentation requires the notions of \\emph{simulations} between \\EL description\ngraphs, which have not been introduced in this work.  For more details on this we refer to\nLemma~5.16 and the proof of Theorem~5.18 in~\\cite{Diss-Felix}.\n\n\\subsection{Unravelling \\ELgfpbot Bases into \\ELbot Bases}\n\\label{sec:unrav-elgfpb-bases}\n\nSo far we have only considered finite bases of $\\Th_c(\\mathcal{I})$ which may contain\nproper \\ELgfpbot concept descriptions.  As we had argued before, those concept\ndescriptions may actually be hard to read, even for those trained in logics.  Therefore, it\nwould be desirable to obtain bases which contain \\ELbot concept descriptions only, as\nthese are potentially much easier to understand.  To show that this is indeed possible is\nthe purpose of this section.  The argumentation we want to employ is again similar to the\none used by~\\cite{Diss-Felix}; see \\Cref{sec:base-all-valid}.\n\nAs a first step, as already discussed in \\Cref{sec:base-all-valid}, we define an auxiliary\nset $\\mathcal{X}_{\\mathcal{I}}$ that only contains \\ELbot concept descriptions but\n\\enquote{captures} entailment between \\ELgfpbot concept descriptions.  For this, recall\nthat \\Cref{lem:Felix-lemma-5.5} states that for a finite interpretation $\\mathcal{I}$ and\nall \\ELgfpbot concept descriptions $C = (A, \\mathcal{T})$ it is true that\n\\begin{equation*}\n  C^{\\mathcal{I}} = (C_d)^{\\mathcal{I}},\n\\end{equation*}\nwhere $d = \\abs{ \\Delta^{\\mathcal{I}} } \\cdot \\abs{ N_D(\\mathcal{T}) } + 1$.  Note that\nthe constant $d$ depends on the concept description $C$.  To emphasize this dependency, we\nshall write $d_{C}$ instead of just $d$.\n\nThe set $\\mathcal{X}_{\\mathcal{I}}$ is now defined as\n\\begin{equation*}\n  \\mathcal{X}_{\\mathcal{I}} := \\set{ (X^{\\mathcal{I}})_{d_{\\mathcal{I}}} \\sqsubseteq\n    (X^{\\mathcal{I}})_{d_{\\mathcal{I}}+1} \\mid X \\subseteq \\Delta^{\\mathcal{I}}, X \\neq\n    \\emptyset },  \n\\end{equation*}\nwhere\n\\begin{equation*}\n  d_{\\mathcal{I}} := \\max_{Y \\subseteq \\Delta^{\\mathcal{I}}} d_{Y^{\\mathcal{I}}}.\n\\end{equation*}\nNote that $\\mathcal{X}_{\\mathcal{I}}$ is a set of valid GCIs of $\\mathcal{I}$, because\nfor each $X \\subseteq \\Delta^{\\mathcal{I}}, X \\neq \\emptyset$ it is true that\n\\begin{equation*}\n  ((X^{\\mathcal{I}})_{d_{\\mathcal{I}}})^{\\mathcal{I}} = X^{\\mathcal{I}\\mathcal{I}} =\n  ((X^{\\mathcal{I}})_{d_{\\mathcal{I}}+1})^{\\mathcal{I}}.\n\\end{equation*}\n\nAs already sketched in \\Cref{sec:base-all-valid} the following claims hold.\n\n\\begin{Lemma}\n  \\label{lem:X_I-properties}\n  Let $\\mathcal{I}$ be a finite interpretation.  Then for each $Y \\subseteq\n  \\Delta^{\\mathcal{I}}$\n  \\begin{enumerate}[i. ]\n  \\item $\\mathcal{X}_{\\mathcal{I}} \\models ((Y^{\\mathcal{I}})_k \\sqsubseteq\n    (Y^{\\mathcal{I}})_{k+1})$ is true for all $k \\geq d_{\\mathcal{I}}$, and\n  \\item $\\mathcal{X}_{\\mathcal{I}} \\models ((Y^{\\mathcal{I}})_{k} \\sqsubseteq\n    Y^{\\mathcal{I}})$ for all $k \\geq d_{\\mathcal{I}}$.\n  \\end{enumerate}\n\\end{Lemma}\n\\begin{Proof}\n  For the first claim we observe that if $Y = \\emptyset$, then $Y^{\\mathcal{I}} = \\bot$\n  and nothing remains to be shown.  Therefore, let $Y \\neq \\emptyset$.  We shall show the\n  claim by induction over $k$.\n\n  For $k = d_{\\mathcal{I}}$ the claim is trivial, as $((Y^{\\mathcal{I}})_{d_{\\mathcal{I}}}\n  \\sqsubseteq (Y^{\\mathcal{I}})_{d_{\\mathcal{I}}+1}) \\in \\mathcal{X}_{\\mathcal{I}}$.  For\n  the step-case $k > d_{\\mathcal{I}}$ assume that\n  \\begin{equation}\n    \\label{eq:34}\n    \\mathcal{X}_{\\mathcal{I}} \\models ((Z^{\\mathcal{I}})_{k-1} \\sqsubseteq (Z^{\\mathcal{I}})_k)\n  \\end{equation}\n  is true for all $Z \\subseteq \\Delta^{\\mathcal{I}}$.  Since $Y^{\\mathcal{I}}$ is\n  expressible in terms of $M_{\\mathcal{I}}$, and $Y \\neq \\emptyset$, there exist $U\n  \\subseteq N_C$ and $\\Pi \\subseteq N_R \\times \\subsets{\\Delta^{\\mathcal{I}}}$ such that\n  \\begin{equation*}\n    Y^{\\mathcal{I}} \\equiv \\bigsqcap U \\sqcap \\bigsqcap_{(r, Z) \\in \\Pi} \\exists r. Z^{\\mathcal{I}}.\n  \\end{equation*}\n  From \\Cref{lem:unravelling-is-homomorphism} we obtain\n  \\begin{equation*}\n    (Y^{\\mathcal{I}})_k \\equiv \\bigsqcap U \\sqcap \\bigsqcap_{(r, Z) \\in \\Pi} \\exists r.(Z^{\\mathcal{I}})_{k-1}.\n  \\end{equation*}\n  By the induction hypothesis~(\\ref{eq:34}) we obtain\n  \\begin{align*}\n    (Y^{\\mathcal{I}})_k\n    &\\sqsubseteq \\bigsqcap U \\sqcap \\bigsqcap_{(r, Z) \\in \\Pi} \\exists\n    r. (Z^{\\mathcal{I}})_k\\\\\n    &\\equiv (\\bigsqcap U \\sqcap \\bigsqcap_{(r, Z) \\in \\Pi} \\exists\n    r. Z^{\\mathcal{I}})_{k+1} \\\\\n    &\\equiv (Y^{\\mathcal{I}})_{k+1}\n  \\end{align*}\n  again using \\Cref{lem:unravelling-is-homomorphism}.  This completes the induction step\n  and the first claim is shown.\n\n  Let $k \\geq d_{\\mathcal{I}}$.  We now show the second claim, namely\n  \\begin{equation*}\n    \\mathcal{X}_{\\mathcal{I}} \\models ((Y^{\\mathcal{I}})_{k} \\sqsubseteq Y^{\\mathcal{I}})\n  \\end{equation*}\n  for $Y \\subseteq \\Delta^{\\mathcal{I}}$.  The case $Y = \\emptyset$ is again trivial, so\n  let $Y \\neq \\emptyset$.  Let $\\mathcal{J}$ be a finite interpretation such that\n  $\\mathcal{J} \\models \\mathcal{X}_{\\mathcal{I}}$.  Then the first claim yields\n  \\begin{equation}\n    \\label{eq:65}\n    ((Y^{\\mathcal{I}})_{k})^{\\mathcal{J}} \\subseteq\n    ((Y^{\\mathcal{I}})_{k+1})^{\\mathcal{J}} \\subseteq\n    ((Y^{\\mathcal{I}})_{k+2})^{\\mathcal{J}} \\subseteq \\dots\n  \\end{equation}\n  From \\Cref{lem:Felix-lemma-5.5} we obtain the existence of some $\\ell \\in \\NN_0$ such\n  that $((Y^{\\mathcal{I}})_\\ell)^{\\mathcal{J}} = (Y^{\\mathcal{I}})^{\\mathcal{J}}$ is true.\n  In particular, $((Y^{\\mathcal{I}})_{k + \\ell})^{\\mathcal{J}} =\n  (Y^{\\mathcal{I}})^{\\mathcal{J}}$, therefore $((Y^{\\mathcal{I}})_{k})^{\\mathcal{J}}\n  \\subseteq (Y^{\\mathcal{I}})^{\\mathcal{J}}$, and thus $\\mathcal{J} \\models\n  ((Y^{\\mathcal{I}})_{k} \\sqsubseteq Y^{\\mathcal{I}})$.  Since \\ELbot has the finite-model\n  property, we obtain $\\mathcal{X}_{\\mathcal{I}} \\models ((Y^{\\mathcal{I}})_{k}\n  \\sqsubseteq Y^{\\mathcal{I}})$ as required.\n\\end{Proof}\n\nNote that \\Cref{eq:65} can be sated more precisely as\n\\begin{equation*}\n  ((Y^{\\mathcal{I}})_{k})^{\\mathcal{J}} =\n  ((Y^{\\mathcal{I}})_{k+1})^{\\mathcal{J}} =\n  ((Y^{\\mathcal{I}})_{k+2})^{\\mathcal{J}} = \\dots\n\\end{equation*}\nbecause $(Y^{\\mathcal{I}})_{k+i+1} \\sqsubseteq (Y^{\\mathcal{I}})_{k+i}$ for all $i \\in\n\\NN_{>0}$.\n\nNow let $\\mathcal{D}$ be a confident base of $\\Th_c(\\mathcal{I})$.  We then can partition\n$\\mathcal{D} = \\mathcal{B} \\cup \\mathcal{C}$ such that $\\mathcal{B} \\subseteq\n\\Th(\\mathcal{I})$ and $\\mathcal{C} \\cap \\Th(\\mathcal{I}) = \\emptyset$, \\ie $\\mathcal{B}$\ncontains all valid GCIs of $\\mathcal{D}$, and $\\mathcal{C}$ contains everything else.\nWithout loss of generality we can assume that $\\mathcal{B}$ contains only GCIs of the form\n$E \\sqsubseteq E^{\\mathcal{I}\\mathcal{I}}$.  To construct an \\ELbot base out of\n$\\mathcal{D}$ we can now proceed as described in the following theorem.\n\n\\begin{Theorem}\n  \\label{thm:unravelling-confident-bases}\n  Let $\\mathcal{I}$ be a finite interpretation, let $c \\in [0,1]$ and let $\\mathcal{D} =\n  \\mathcal{B} \\cup \\mathcal{C}$ be a finite confident base of $\\Th_c(\\mathcal{I})$, such\n  that $\\mathcal{B} \\subseteq \\Th(\\mathcal{I})$, $\\mathcal{C} \\cap \\Th(\\mathcal{I}) =\n  \\emptyset$, and $\\mathcal{B}$ contains only GCIs of the form $E \\sqsubseteq\n  E^{\\mathcal{I}\\mathcal{I}}$. Define\n  \\begin{equation*}\n    d := \\max\\set{ d_{\\mathcal{I}}, \\max \\set{ d_{E} \\mid (E \\sqsubseteq F) \\in\n        \\mathcal{D} } },\n  \\end{equation*}\n  and\n  \\begin{align*}\n    \\mathcal{B}' &:= \\set{ E_{d} \\sqsubseteq (E^{\\mathcal{I}\\mathcal{I}})_{d} \\mid (E\n      \\sqsubseteq E^{\\mathcal{I}\\mathcal{I}}) \\in \\mathcal{B} } \\cup \\set{ C_{d}\n      \\sqsubseteq (C^{\\mathcal{I}\\mathcal{I}})_{d}\\mid (C \\sqsubseteq D) \\in \\mathcal{C} },\\\\\n    \\mathcal{C}' &:= \\set{ (C^{\\mathcal{I}\\mathcal{I}})_{d} \\sqsubseteq\n      (D^{\\mathcal{I}\\mathcal{I}})_{d} \\mid (C \\sqsubseteq D) \\in \\mathcal{C} }.\n  \\end{align*}\n  Then the following statements hold:\n  \\begin{enumerate}[i. ]\n  \\item $\\mathcal{B}' \\cup \\mathcal{X}_{\\mathcal{I}} \\subseteq \\Th(\\mathcal{I})$,\n    $\\mathcal{C}' \\subseteq \\Th_c(\\mathcal{I})$ and $\\mathcal{B}' \\cup \\mathcal{C}' \\cup\n    \\mathcal{X}_{\\mathcal{I}} \\models \\mathcal{C}$.\n  \\item $\\mathcal{B}' \\cup \\mathcal{C}' \\cup \\mathcal{X}_{\\mathcal{I}} \\models\n    \\mathcal{B}$.\n  \\end{enumerate}\n  In particular, $\\mathcal{B}' \\cup \\mathcal{C}' \\cup \\mathcal{X}_{\\mathcal{I}}$ is a\n  finite confident \\ELbot base of $\\Th_c(\\mathcal{I})$.\n\\end{Theorem}\n\n\\begin{Proof}\n  Clearly, $\\mathcal{B}' \\cup \\mathcal{X}_{\\mathcal{I}}$ is a set of valid GCIs.  To see\n  that $\\mathcal{C}'$ only contains GCIs with high confidence, let $(C \\sqsubseteq D) \\in\n  \\mathcal{C}$ with $\\abs{ C^{\\mathcal{I}} } \\neq \\emptyset$.  Then\n  \\begin{align*}\n    \\conf_{\\mathcal{I}}( C \\sqsubseteq D )\n    &= \\conf_{\\mathcal{I}}( C^{\\mathcal{I}\\mathcal{I}} \\sqsubseteq D^{\\mathcal{I}\\mathcal{I}} )\\\\\n    &= \\frac{ | ( C^{\\mathcal{I}\\mathcal{I}} \\sqcap D^{\\mathcal{I}\\mathcal{I}}\n      )^{\\mathcal{I}} | }{ | C^{\\mathcal{I}\\mathcal{I}\\mathcal{I}} | }\\\\\n    &= \\frac{ | ( (C^{\\mathcal{I}\\mathcal{I}})_d \\sqcap (D^{\\mathcal{I}\\mathcal{I}})_{d}\n      )^{\\mathcal{I}} | }{ | ((C^{\\mathcal{I}\\mathcal{I}})_{d})^{\\mathcal{I}} | }\\\\\n    &= \\conf_{\\mathcal{I}}( (C^{\\mathcal{I}\\mathcal{I}})_{d} \\sqsubseteq\n    (D^{\\mathcal{I}\\mathcal{I}})_{d} ).\n  \\end{align*}\n  Clearly, if $C^{\\mathcal{I}} = \\emptyset$, then\n  $((C^{\\mathcal{I}\\mathcal{I}})_{d})^{\\mathcal{I}} = \\emptyset$ and thus\n  \\begin{equation*}\n    \\conf_{\\mathcal{I}}( C \\sqsubseteq D ) = 1 = \\conf_{\\mathcal{I}}(\n    (C^{\\mathcal{I}\\mathcal{I}})_{d} \\sqsubseteq\n    (D^{\\mathcal{I}\\mathcal{I}})_{d} ).\n  \\end{equation*}\n  Since $\\mathcal{C} \\subseteq \\Th_c(\\mathcal{I})$, we therefore obtain $\\mathcal{C}'\n  \\subseteq \\Th_c(\\mathcal{I})$ as required.\n\n  We now show that $\\mathcal{B}' \\cup \\mathcal{C}' \\cup \\mathcal{X}_{\\mathcal{I}} \\models\n  \\mathcal{C}$.  For this let $(C \\sqsubseteq D) \\in \\mathcal{C}$.  Then we have\n  \\begin{align*}\n    \\emptyset &\\models (C \\sqsubseteq C_{d})\\\\\n    \\mathcal{B}' &\\models (C_{d} \\sqsubseteq (C^{\\mathcal{I}\\mathcal{I}})_{d})\\\\\n    \\mathcal{C}' &\\models ((C^{\\mathcal{I}\\mathcal{I}})_{d} \\sqsubseteq\n    (D^{\\mathcal{I}\\mathcal{I}})_{d})\\\\\n    \\mathcal{X}_{\\mathcal{I}} &\\models ((D^{\\mathcal{I}\\mathcal{I}})_{d} \\sqsubseteq\n    D^{\\mathcal{I}\\mathcal{I}})\\\\\n    \\emptyset &\\models (D^{\\mathcal{I}\\mathcal{I}} \\sqsubseteq D)\n  \\end{align*}\n  using \\Cref{lem:X_I-properties} for the second to last statement.  Therefore\n  $\\mathcal{B}' \\cup \\mathcal{C}' \\cup \\mathcal{X}_{\\mathcal{I}} \\models (C \\sqsubseteq\n  D)$ as required.\n\n  We consider the second claim, namely that $\\mathcal{B}' \\cup \\mathcal{C}' \\cup\n  \\mathcal{X}_{\\mathcal{I}} \\models \\mathcal{B}$.  To this end, let $(E \\sqsubseteq\n  E^{\\mathcal{I}\\mathcal{I}}) \\in \\mathcal{B}$.  Then\n  \\begin{align*}\n    \\emptyset &\\models (E \\sqsubseteq E_{d})\\\\\n    \\mathcal{B}' &\\models (E_{d} \\sqsubseteq (E^{\\mathcal{I}\\mathcal{I}})_{d})\\\\\n    \\mathcal{X}_{\\mathcal{I}} &\\models ((E^{\\mathcal{I}\\mathcal{I}})_{d}\n    \\sqsubseteq E^{\\mathcal{I}\\mathcal{I}})\n  \\end{align*}\n  using \\Cref{lem:X_I-properties} for the last statement.  Therefore,\n  \\begin{equation*}\n    \\mathcal{B}' \\cup \\mathcal{C}' \\cup \\mathcal{X}_{\\mathcal{I}} \\models (E \\sqsubseteq\n    E^{\\mathcal{I}\\mathcal{I}})\n  \\end{equation*}\n  as required.\n\\end{Proof}\n\nA drawback of this construction is that the set $\\mathcal{X}_{\\mathcal{I}}$ can be\nexponentially large in the size of $\\Delta^{\\mathcal{I}}$, and so can be the \\ELbot base\nas described above.  Therefore, even if the original base $\\mathcal{D}$ was small, the\ndescribed unravelling can transfer it into a much larger base.  It is not known to the\nauthor whether this blowup is intrinsic to the task of transferring \\ELgfpbot bases into\n\\ELbot bases, or whether it can be avoided by a different approach.\n\n\\section{GCIs with High Confidence from DBpedia}\n\\label{sec:exper-with-conf}\n\nWe have started this chapter by evaluating the results by Baader and Distel in a practical\nscenario.  During this evaluation we have found that the presence of errors in the data\ncan impair the usefulness of this approach, and from this we have motivated our study of\nGCIs with high confidence.  In this section, we want to apply our findings about finite\nconfident bases of $\\Th_c(\\mathcal{I})$ to the interpretation $\\Idbpedia$ we used before,\nand we want to see in how far the problem of errors in $\\Idbpedia$ can be alleviated by\nusing GCIs with high confidence.\n\nLet us assume that an ontology engineer wants to use the approach of considering GCIs with\nhigh confidence to extract GCIs from some finite interpretation $\\mathcal{I}$.  Then what\nshe has to do is to consider GCIs in $\\Lux(\\mathcal{I}, c)$ for a suitable choice of $c$\nand to decide whether these GCIs should be added to the knowledge base or not.  To make\nthis a practical approach, the set $\\Lux(\\mathcal{I}, c)$ should not be too large, and the\nGCIs contained in there should not be incomprehensible.\n\nWe want to examine how this approach performs for our data set $\\Idbpedia$.  To this end,\nwe want to conduct several experiments, namely\n\\begin{enumerate}[i. ]\n\\item We want to examine the set $\\Lux(\\Idbpedia, 0.95)$ in detail, \\ie we want to show\n  how large this set is and which GCIs are contained in it.  Moreover, we shall discuss\n  how the ontology engineer proceeds in deciding whether the GCIs contained in this set\n  are true or not.\n\\item We want to compare the sizes of the sets $\\Conf(\\Idbpedia, c)$ and $\\Lux(\\Idbpedia,\n  c)$ to see in how far we can remove redundancies from $\\Conf(\\Idbpedia, c)$ by using\n  $\\Lux(\\Idbpedia, c)$ instead.  To this end, we shall compute for all $c \\in \\set{ 0.0,\n    0.01, \\dots, 0.99}$ the size of the sets $\\Conf(\\Idbpedia, c)$ and $\\Lux(\\Idbpedia,\n  c)$ to see how the cardinalities of these sets depends on the choice of the parameter\n  $c$.\n\\item Finally, we want to consider the size of the canonical base of $\\Th_c(\\con\n  K_\\Idbpedia)$ for $c \\in \\set{ 0.0, 0.01, \\dots, 0.99 }$ to see how large this set can\n  be.  Recall that $\\bigsqcap \\Can(\\Th_c(\\con K_\\Idbpedia))$ is a finite base of\n  $\\Th_c(\\mathcal{I})$, and the number of GCIs in this base can be considered as a\n  \\enquote{small} upper limit of how many GCIs are needed to represent\n  $\\Th_c(\\mathcal{I})$.  Intuitively, if we decrease the value for $c$, we would expect\n  that the number of GCIs contained in the canonical base decreases as well.  We shall see\n  how far this is true for $\\Idbpedia$.\n\\end{enumerate}\n\nThe experimental results presented in this section have been published previously in\n\\cite{Borchmann-LTCS-12-06}.\n\n\\subsection{Computing Confident Bases of $\\Th_c(\\Idbpedia)$ for $c = 0.95$}\n\\label{sec:comp-conf-bases}\n\nRecall that we had constructed $\\Idbpedia$ from the DBpedia data set by extracting all\nindividuals that are in a \\textsf{child}-relationship in DBpedia, either as a parent or as\na child.  Recall that since Wikipedia (from which DBpedia extracts its data) only contains\narticles about \\enquote{famous} persons, we can consider $\\Idbpedia$ as an interpretation\nthat contains all properties about the child-relations between \\emph{famous} persons.  In\nparticular, if an element of $\\Idbpedia$ does not have a \\textsf{child}-successor in\n$\\Idbpedia$ (and this is not an error), then this does not necessarily mean that the\ncorresponding person does or did not have children -- it only means that the children were\nnot famous enough to deserve their own Wikipedia articles.\n\nIn the following we want to examine which GCIs we have to consider in addition to the base\n$\\mathcal{B}_{\\Idbpedia}$ of $\\Idbpedia$ we had computed in\n\\Cref{sec:computing-bases-from}, if we want to consider GCIs which have a confidence in\n$\\Idbpedia$ of at least 0.95.  Thus, let $c = 0.95$.  We then can compute\n$\\Conf(\\Idbpedia, c)$ to be\n\\begin{align*}\n  \\{\\,\n  & \\mathsf{\\exists child. \\top} \\sqsubseteq \\mathsf{Person}, \\\\\n  & \\mathsf{Place} \\sqsubseteq \\mathsf{PopulatedPlace},\\\\\n  & \\mathsf{\\exists child. \\exists child. \\top} \\sqcap \\mathsf{\\exists\n    child. OfficeHolder} \\\\\n  & \\quad \\sqsubseteq \\mathsf{\\exists child. (OfficeHolder \\sqcap \\exists child. \\top)}\n  \\,\\}\n\\end{align*}\nNote that the actual GCIs computed are much more complex, since all concept descriptions\ncontained in $\\Conf(\\Idbpedia, c)$ actually have to be model-based most-specific concept\ndescriptions.  For readability, we have removed parts of the concept descriptions which\nare already entailed by the base $\\mathcal{B}_\\Idbpedia$, so that the GCIs thus obtained\nare still equivalent to the original ones.  Also notice that $\\Lux(\\Idbpedia, c) =\n\\Conf(\\Idbpedia, c)$.\n\nThe first observation is that $\\Lux(\\Idbpedia, c)$ is small compared to the size of\n$\\mathcal{B}_\\Idbpedia$, which has 1252 elements.  Thus, our potential ontology engineer\nonly has to consider three more GCIs.  Moreover, as we shall see later, accepting some of\nthe above GCIs may even lead to other GCIs in $\\mathcal{B}_\\Idbpedia$ to become\ndispensable, and thus she does not have to consider those separately.\n\nLet us now consider these three GCIs in detail.  The first one we had already seen in\n\\Cref{sec:computing-bases-from}, and there we had argued that this is actually true, since\nthe 4 counterexamples contained in $\\Idbpedia$ were only due to errors.\n\nThe GCI $\\mathsf{Place} \\sqsubseteq \\mathsf{PopulatedPlace}$ also sounds convincing: note\nthat places appear in $\\Idbpedia$ only due to the fact that they are collected from\nWikipedia Infoboxes of articles which contain an entry for children, \\ie which are\npersons.  Since these places occur in the child-entries of infoboxes, they likely name the\nplaces of birth of the corresponding children, and those places are usually populated.\nIndeed, the only counterexamples for $\\mathsf{Place \\sqsubseteq PopulatedPlace}$ is\n\\textsf{Greenwich\\_Village}, representing the corresponding district of Manhattan, New\nYork, which is certainly populated.  Thus also this counterexample is erroneous and we\naccept the GCI as being true (in the domain represented by $\\Idbpedia$).\n\nOn the other hand, the last GCI\n\\begin{equation*}\n  \\mathsf{\\exists child. \\exists child. \\top \\sqcap \\exists child. OfficeHolder\n    \\sqsubseteq \\exists child. ( OfficeHolder \\sqcap \\exists child. \\top ) }\n\\end{equation*}\nlooks too specific.  The only counterexample contained in $\\Idbpedia$ is the element\n\\begin{quote}\n  \\textsf{Pierre\\_Samuel\\_du\\_Pont\\_de\\_Nemours}\n\\end{quote}\nrepresenting the french government official Pierre Samuel du Pont de Nemours.  He had two\nsons, namely Victor Marie du Pont and Eleuthère Irénée du Pont.  The former became a\nfrench diplomat and is therefore listed as \\textsf{OfficeHolder} in $\\Idbpedia$.  Although\nhe had four children, none of them were famous enough to receive their own Wikipedia\narticles.  On the other hand, Eleuthère Irénée du Pont became a famous american industrial\n(founder of the \\emph{DuPont} company) and had several famous children which are listed in\n$\\Idbpedia$.  Thus, given our understanding of the \\textsf{child}-relation in $\\Idbpedia$\nwe can accept this counterexample as being valid, and we therefore reject this GCI.\n\nWe have accepted the GCIs\n\\begin{equation*}\n  \\mathcal{B} := \\set{ \\mathsf{\\exists child. \\top \\sqsubseteq Person},\n    \\mathsf{Place \\sqsubseteq PopulatedPlace} }\n\\end{equation*}\nas being valid although $\\Idbpedia$ contains counterexamples for them.  It would now be\ninteresting to know what happened if we would include those two GCIs in a computation of a\nbase of $\\Idbpedia$.  For this, note that\n\\begin{equation*}\n  \\pr_{M_{\\Idbpedia}}(\\mathcal{B}) = \\set{ \\set{ \\mathsf{\\exists child. \\top} } \\to \\set{\n      \\mathsf{Person} }, \\set{ \\mathsf{Place} } \\to \\set{ \\mathsf{PopulatedPlace} } }.\n\\end{equation*}\nIf we now compute\n\\begin{equation*}\n  \\mathcal{L} := \\Can(\\con K_\\Idbpedia, \\pr_{M_{\\Idbpedia}}(\\mathcal{B}) \\cup\n  \\mathcal{S}_{\\Idbpedia} )\n\\end{equation*}\nthen we obtain by \\Cref{thm:gci-completion-simple-version} that $\\bigsqcap \\mathcal{L}\n\\cup \\mathcal{B}$ is complete for\n\\begin{equation*}\n  \\Th(\\Idbpedia) \\cup \\set{ \\mathsf{\\exists child. \\top \\sqsubseteq Person },\n    \\mathsf{Place \\sqsubseteq PopulatedPlace} },\n\\end{equation*}\nand is thus a base of it.  The set $\\mathcal{L}$ now contains 1245 GCIs, and thus\n$\\bigsqcap \\mathcal{L} \\cup \\mathcal{B}$ contains 1247 GCIs.  Comparing this to the 1252\nGCIs we can see that some of the GCIs in $\\mathcal{B}_\\Idbpedia$ indeed became\ndispensable, although it were not that many.\n\n\\subsection{Sizes of Finite Bases of $\\Th_c(\\Idbpedia)$}\n\\label{sec:sizes-finite-bases}\n\nWe have seen that $\\Conf(\\Idbpedia, 0.95)$ only contains three GCIs.  This suggests that\nthe overhead caused by the approach of considering GCIs with high confidence is rather\nnegligible.  Moreover, we have also seen that we can reduce the size of bases of\n$\\Idbpedia$ if we include GCIs from $\\Conf(\\Idbpedia, 0.95)$ as background knowledge, thus\neffectively reducing the number of GCIs our ontology engineer has to consider.\n\nIn this section we examine these observations on a larger scale.  For this we shall\ninvestigate the sizes of the sets $\\Conf(\\Idbpedia, c)$ and $\\Lux(\\Idbpedia, c)$ for\nvarying values of $c$.  From this we shall see how the overhead of considering GCIs with\nhigh confidence depends on the choice of the parameter $c$, and how much we can save by\nconsidering $\\Lux(\\Idbpedia, c)$ over $\\Conf(\\Idbpedia, c)$.\n\n\\subsubsection{The Sizes of $\\Conf(\\Idbpedia,c)$ and $\\Lux(\\Idbpedia, c)$}\n\\label{sec:size-confidbpedia-c}\n\nWe computed $\\abs{ \\Conf(\\Idbpedia, c) }$ and $\\abs{ \\Lux(\\Idbpedia, c) }$ for all $c \\in\n\\set{ 0.0, 0.01, \\dots, 0.99 }$.  To achieve this, we use\n\\begin{align*}\n  \\abs{ \\Conf(\\Idbpedia, c) } &= \\abs{ \\Conf(\\con K_\\Idbpedia, c) }, \\\\\n  \\abs{ \\Lux(\\Idbpedia, c) } &= \\abs{ \\Lux(\\con K_\\Idbpedia, c) }.\n\\end{align*}\nand can thus conduct the computations directly in $\\con K_\\Idbpedia$.  The results of\nthese computations are shown in \\Cref{fig:conf-size-behavior}.  Note that the y-axis is\nscaled logarithmically.\n\n\\begin{figure}[tp]\n  \\centering\n  \\begin{tikzpicture}\n    \\begin{semilogyaxis}[xlabel={$c$}, semithick]\n      \\addplot[blue, no marks] coordinates {\n        (0.00,  6439 )\n        (0.01,  3397 )\n        (0.02,  2835 )\n        (0.03,  2547 )\n        (0.04,  2323 )\n        (0.05,  2188 )\n        (0.06,  2043 )\n        (0.07,  1896 )\n        (0.08,  1787 )\n        (0.09,  1701 )\n        (0.10,  1633 )\n        (0.11,  1561 )\n        (0.12,  1454 )\n        (0.13,  1412 )\n        (0.14,  1356 )\n        (0.15,  1268 )\n        (0.16,  1234 )\n        (0.17,  1153 )\n        (0.18,  1128 )\n        (0.19,  1094 )\n        (0.20,   994 )\n        (0.21,   983 )\n        (0.22,   955 )\n        (0.23,   922 )\n        (0.24,   899 )\n        (0.25,   807 )\n        (0.26,   804 )\n        (0.27,   785 )\n        (0.28,   773 )\n        (0.29,   728 )\n        (0.30,   708 )\n        (0.31,   696 )\n        (0.32,   690 )\n        (0.33,   688 )\n        (0.34,   569 )\n        (0.35,   561 )\n        (0.36,   549 )\n        (0.37,   536 )\n        (0.38,   523 )\n        (0.39,   521 )\n        (0.40,   470 )\n        (0.41,   467 )\n        (0.42,   460 )\n        (0.43,   442 )\n        (0.44,   440 )\n        (0.45,   433 )\n        (0.46,   423 )\n        (0.47,   417 )\n        (0.48,   411 )\n        (0.49,   410 )\n        (0.50,   252 )\n        (0.51,   252 )\n        (0.52,   248 )\n        (0.53,   247 )\n        (0.54,   240 )\n        (0.55,   236 )\n        (0.56,   231 )\n        (0.57,   229 )\n        (0.58,   215 )\n        (0.59,   213 )\n        (0.60,   196 )\n        (0.61,   194 )\n        (0.62,   193 )\n        (0.63,   186 )\n        (0.64,   178 )\n        (0.65,   174 )\n        (0.66,   172 )\n        (0.67,   112 )\n        (0.68,   109 )\n        (0.69,   106 )\n        (0.70,   103 )\n        (0.71,   100 )\n        (0.72,    92 )\n        (0.73,    86 )\n        (0.74,    84 )\n        (0.75,    61 )\n        (0.76,    61 )\n        (0.77,    58 )\n        (0.78,    57 )\n        (0.79,    55 )\n        (0.80,    40 )\n        (0.81,    39 )\n        (0.82,    37 )\n        (0.83,    36 )\n        (0.84,    25 )\n        (0.85,    22 )\n        (0.86,    15 )\n        (0.87,    15 )\n        (0.88,    10 )\n        (0.89,    10 )\n        (0.90,     8 )\n        (0.91,     6 )\n        (0.92,     6 )\n        (0.93,     5 )\n        (0.94,     5 )\n        (0.95,     3 )\n        (0.96,     3 )\n        (0.97,     2 )\n        (0.98,     2 )\n        (0.99,     1 )\n        (1.00,     0 )\n      };\n      \\addlegendentry{$|\\Conf(\\Idbpedia, c)|$}\n\n      \\addplot[blue, no marks, densely dashed] coordinates {\n        (0.00, 1129)\n        (0.01,  891)\n        (0.02,  860)\n        (0.03,  841)\n        (0.04,  827)\n        (0.05,  809)\n        (0.06,  784)\n        (0.07,  760)\n        (0.08,  736)\n        (0.09,  716)\n        (0.10,  701)\n        (0.11,  685)\n        (0.12,  667)\n        (0.13,  654)\n        (0.14,  638)\n        (0.15,  622)\n        (0.16,  612)\n        (0.17,  598)\n        (0.18,  590)\n        (0.19,  579)\n        (0.20,  548)\n        (0.21,  543)\n        (0.22,  537)\n        (0.23,  527)\n        (0.24,  519)\n        (0.25,  492)\n        (0.26,  491)\n        (0.27,  486)\n        (0.28,  484)\n        (0.29,  471)\n        (0.30,  465)\n        (0.31,  461)\n        (0.32,  458)\n        (0.33,  457)\n        (0.34,  406)\n        (0.35,  402)\n        (0.36,  395)\n        (0.37,  391)\n        (0.38,  386)\n        (0.39,  385)\n        (0.40,  363)\n        (0.41,  362)\n        (0.42,  357)\n        (0.43,  347)\n        (0.44,  347)\n        (0.45,  342)\n        (0.46,  338)\n        (0.47,  334)\n        (0.48,  329)\n        (0.49,  328)\n        (0.50,  207)\n        (0.51,  207)\n        (0.52,  204)\n        (0.53,  204)\n        (0.54,  200)\n        (0.55,  199)\n        (0.56,  196)\n        (0.57,  194)\n        (0.58,  186)\n        (0.59,  184)\n        (0.60,  175)\n        (0.61,  175)\n        (0.62,  175)\n        (0.63,  172)\n        (0.64,  165)\n        (0.65,  163)\n        (0.66,  161)\n        (0.67,  106)\n        (0.68,  103)\n        (0.69,  101)\n        (0.70,   99)\n        (0.71,   97)\n        (0.72,   90)\n        (0.73,   86)\n        (0.74,   84)\n        (0.75,   61)\n        (0.76,   61)\n        (0.77,   58)\n        (0.78,   57)\n        (0.79,   55)\n        (0.80,   40)\n        (0.81,   39)\n        (0.82,   37)\n        (0.83,   36)\n        (0.84,   25)\n        (0.85,   22)\n        (0.86,   15)\n        (0.87,   15)\n        (0.88,   10)\n        (0.89,   10)\n        (0.90,    8)\n        (0.91,    6)\n        (0.92,    6)\n        (0.93,    5)\n        (0.94,    5)\n        (0.95,    3)\n        (0.96,    3)\n        (0.97,    2)\n        (0.98,    2)\n        (0.99,    1)\n        (1.00,    0)\n      };\n      \\addlegendentry{$|\\Lux(\\Idbpedia, c)|$}\n    \\end{semilogyaxis}\n  \\end{tikzpicture}\n  \\caption{Size of $\\Conf(\\Idbpedia,c)$ and $\\Lux(\\Idbpedia, c)$ for all $c \\in\n    V$}\n  \\label{fig:conf-size-behavior}\n\\end{figure}\n\nFrom this picture we can see that for high values of $c$ the amount of GCIs which have to\nbe considered in $\\Conf(\\Idbpedia, c)$ and $\\Lux(\\Idbpedia, c)$ is negligible.  Even for\n$c = 0.86$ the set $\\Conf(\\Idbpedia, c)$ contains only 15 GCIs.  Of course, this\nobservation is per se only valid for $\\Idbpedia$.  Since it originates from real-world\ndata one could assume that the same behavior of $\\abs{ \\Conf(\\Idbpedia, c) }$ and $\\abs{\n  \\Lux(\\Idbpedia, c) }$ can be expected for other non-artificial data-sets.\n\nWhat we also observe is that for values $c \\geq 0.73$, $\\Conf(\\Idbpedia, c)$ and\n$\\Lux(\\Idbpedia, c)$ are actually the same sets, \\ie the optimization provided by\n$\\Lux(\\Idbpedia, c)$ does not take effect for such values of $c$.  Since one usually\nconsiders only large values of $c$ the use of $\\Lux(\\Idbpedia, c)$ over $\\Conf(\\Idbpedia,\nc)$ seems questionable.\n\n\\subsubsection{The Size of $\\Can(\\Th_c(\\con K_{\\mathcal{I}}))$}\n\\label{sec:size-canth_cc-k_math}\n\nInstead of computing confident bases of $\\Th_c(\\Idbpedia)$ by independently computing\nbases of $\\Idbpedia$ and conjoining them to $\\Conf(\\Idbpedia, c)$ or $\\Lux(\\Idbpedia, c)$,\nwe can also utilize\n\\Cref{thm:confident-bases-of-GCIs-from-confident-bases-of-implications}.  In this theorem,\nwe compute confident bases $\\mathcal{L}$ of $\\Th_c(\\con K_{\\Idbpedia})$, and then\n$\\bigsqcap \\mathcal{L}$ is a finite confident base of $\\Th_c(\\Idbpedia)$.  An advantage of\nthis approach is that bases of $\\Th_c(\\con K_{\\Idbpedia})$ can be smaller then bases\n$\\mathcal{B}$ of $\\Th(\\Idbpedia)$ together with $\\Conf(\\Idbpedia, c)$, because in the\nlatter case GCIs from $\\mathcal{B}$ could already be entailed by GCIs from\n$\\Conf(\\Idbpedia, c)$.  Some of these redundancies could already exist on the level of\nimplications, and those could be removed if one computes bases of $\\Th_c(\\con\nK_{\\mathcal{I}})$.\n\nIn particular, if we compute the canonical base of $\\Th_c(\\con K_{\\mathcal{I}})$, then all\nthose redundancies are removed.  Of course, other dependencies may remain, but the size of\nthe canonical base of $\\Th_c(\\con K_{\\mathcal{I}})$ may serve as an upper bound on the\nnumber of GCIs one needs to represent $\\Th_c(\\con K_{\\mathcal{I}})$.  On the other hand,\nconsidering the canonical base of $\\Th_c(\\con K_{\\mathcal{I}})$ may result in bases which\nare not confident anymore, \\ie they contain GCIs whose confidence is not above $c$.\n\nLet us now see how the size of the canonical base changes for all $c \\in \\set{ 0, 0.01,\n  \\dots, 0.99 }$.  The results are shown in \\Cref{fig:can-Th_c-size-behavior}.\n\n\\begin{figure}[tp]\n  \\centering\n  \\begin{tikzpicture}\n    \\begin{axis}[xlabel={$c$}, ylabel={$|\\Can(\\Th_c(\\con{K}_\\Idbpedia))|$}, semithick]\n      \\addplot[blue, no marks] coordinates {\n        (0.00,    1)\n        (0.01,    1)\n        (0.02,    1)\n        (0.03,    1)\n        (0.04,    1)\n        (0.05,    1)\n        (0.06,    1)\n        (0.07,    1)\n        (0.08,    1)\n        (0.09,    1)\n        (0.10,    1)\n        (0.11,    1)\n        (0.12,    1)\n        (0.13,    1)\n        (0.14,    1)\n        (0.15,    1)\n        (0.16,    1)\n        (0.17,    1)\n        (0.18,    1)\n        (0.19,  114)\n        (0.20,  114)\n        (0.21,  128)\n        (0.22,  128)\n        (0.23,  128)\n        (0.24,  141)\n        (0.25,  154)\n        (0.26,  163)\n        (0.27,  212)\n        (0.28,  212)\n        (0.29,  212)\n        (0.30,  227)\n        (0.31,  227)\n        (0.32,  227)\n        (0.33,  227)\n        (0.34,  227)\n        (0.35,  227)\n        (0.36,  227)\n        (0.37,  246)\n        (0.38,  250)\n        (0.39,  250)\n        (0.40,  264)\n        (0.41,  264)\n        (0.42,  295)\n        (0.43,  319)\n        (0.44,  319)\n        (0.45,  319)\n        (0.46,  319)\n        (0.47,  335)\n        (0.48,  346)\n        (0.49,  357)\n        (0.50,  551)\n        (0.51,  551)\n        (0.52,  561)\n        (0.53,  561)\n        (0.54,  604)\n        (0.55,  604)\n        (0.56,  606)\n        (0.57,  606)\n        (0.58,  626)\n        (0.59,  632)\n        (0.60,  641)\n        (0.61,  641)\n        (0.62,  641)\n        (0.63,  645)\n        (0.64,  675)\n        (0.65,  688)\n        (0.66,  688)\n        (0.67,  772)\n        (0.68,  913)\n        (0.69,  943)\n        (0.70,  954)\n        (0.71,  970)\n        (0.72, 1014)\n        (0.73, 1036)\n        (0.74, 1040)\n        (0.75, 1099)\n        (0.76, 1099)\n        (0.77, 1110)\n        (0.78, 1110)\n        (0.79, 1110)\n        (0.80, 1139)\n        (0.81, 1142)\n        (0.82, 1144)\n        (0.83, 1145)\n        (0.84, 1167)\n        (0.85, 1171)\n        (0.86, 1192)\n        (0.87, 1192)\n        (0.88, 1216)\n        (0.89, 1216)\n        (0.90, 1239)\n        (0.91, 1240)\n        (0.92, 1240)\n        (0.93, 1242)\n        (0.94, 1242)\n        (0.95, 1241)\n        (0.96, 1241)\n        (0.97, 1245)\n        (0.98, 1245)\n        (0.99, 1245)\n        (1.00, 1252)\n      };\n    \\end{axis}\n  \\end{tikzpicture}\n  \\caption{Size of $\\Can(\\Th_c(\\con{K}_\\Idbpedia))$ for all $c \\in \\set{ 0, 0.01, \\dots,\n      0.99 }$}\n  \\label{fig:can-Th_c-size-behavior}\n\\end{figure}\n\nA first observation is that with decreasing values of $c$, the size of $\\Can(\\Th_c(\\con\nK_{\\Idbpedia}))$ seems to decrease as well.  This is indeed true, except for the case\n$\\abs{ \\Can(\\Th_{0.95}(\\con K_{\\Idbpedia})) } = 1241$ and $\\abs{ \\Can( \\Th_{0.94}(\\con\n  K_{\\Idbpedia})) } = 1242$.  Thus we can observe that with decreasing $c$, the sets\n$\\Th_c(\\con K_{\\Idbpedia})$ get \\enquote{simpler} in the sense that fewer implications are\nnecessary to represent them.  If the same is true for bases of $\\Th_c(\\Idbpedia)$ is not\nclear, though, as it is not quite clear how to compute finite bases of sets of GCIs.\n\nClearly, the farther away $c$ is from 1, the more the set $\\Th_c(\\Idbpedia)$ departs from\n$\\Th(\\Idbpedia)$.  There are three values for $c$ where this becomes especially apparent:\nfor $c \\in \\set{ 0.18, 0.54, 0.66 }$ the curve depicted in\n\\Cref{fig:can-Th_c-size-behavior} shows a rather steep decline.  Indeed, these values of\n$c$ are not arbitrary, since we can associate some special observations with them:\n\\begin{enumerate}[i. ]\n\\item For $c \\leq 0.18$ the implication $\\emptyset \\to M_{\\Idbpedia}$ is entailed by\n  $\\Th_c(\\con K_{\\Idbpedia})$, resulting in a singleton canonical base.\n\\item For $0.18 < c \\leq 0.54$ the implication $\\set{ \\mathsf{\\exists child. \\top} } \\to\n  \\set{ \\mathsf{\\exists child. Person} }$ is contained in $\\Th_c(\\con K_{\\Idbpedia})$,\n  eliminating a large number of special cases.\n\\item For $0.54 < c \\leq 0.66$ the implication $\\emptyset \\to \\set{ \\mathsf{Person} }$ is\n  contained in $\\Th_c(\\con K_{\\Idbpedia})$, also making a number of other GCIs\n  dispensable.\n\\end{enumerate}\n\nOne can observe that the implications found in the last two cases also account for a\nrather drastic decline of the size of the canonical base on their own: the canonical base\nof $\\Th(\\con K_{\\Idbpedia})$ contains 1252 elements, but the canonical base of\n\\begin{equation*}\n  \\Th(\\con K_{\\Idbpedia}) \\cup \\set{ \\emptyset \\to \\set{ \\mathsf{Person} } }\n\\end{equation*}\ncontains only 1210 implications.  If we also add the implication\n\\begin{equation*}\n  \\set{ \\mathsf{\\exists child. \\top} } \\to \\set{ \\mathsf{\\exists child. Person} }\n\\end{equation*}\nthen the size of the canonical base drops to 1163.\n\nNotice that this is actually not very surprising: the implications\n\\begin{equation*}\n  \\set{ \\mathsf{\\exists  child. \\top} \\to \\set{ \\mathsf{\\exists child. Person} } }, \\quad\n  \\emptyset \\to \\set{ \\mathsf{Person} }\n\\end{equation*}\ncan be considered rather \\emph{general}, because they are applicable to a lot of elements\nin $\\Idbpedia$.  Because of this generality they can make a lot of other implications\nredundant, causing the size of the canonical base to be reduced noticeably.\n\nIndeed, we could argue that whenever the size of the canonical base of $\\Th_c(\\con\nK_{\\Idbpedia})$ is reduced drastically, then it is very likely that a general GCI has been\nfound, in the sense that the confidence threshold is now so low that it is accepted.  To\nthis end recall that we had already noticed that the size of the canonical base of\n$\\Th_c(\\con K_{\\Idbpedia})$ can be seen as some kind of indication how \\emph{complex} this\nset is: the less implications are contained in the canonical base, the less implications\nare necessary to represent $\\Th_c(\\con K_\\Idbpedia)$ and thus the \\emph{simpler} this set\nis, from a logical point of view.  Therefore, if we can observe for $c_1 > c_2$ a steep\ndecline in the size of the canonical base of $\\Th_{c_2}(\\con K_{\\Idbpedia})$ compared to\nthe size of the canonical base of $\\Th_{c_1}(\\con K_{\\Idbpedia})$, it is legitimate to\nassume that then $\\Th_{c_2}(\\con K_{\\Idbpedia})$ contains new implications which make a\nlot of implications in the canonical base of $\\Th_{c_1}(\\con K_\\Idbpedia)$ dispensable.\nThose implications then can considered to be very general, since they need to account for\nthe entailment, which in $\\Th_{c_1}(\\con K_\\Idbpedia)$ has only been achieved by a larger\nnumber of implications.\n\nTherefore, the way the size of $\\Can(\\Th_c(\\con K_{\\mathcal{I}}))$ depends on the choice\nof $c$ can indicate which kinds of GCIs have been accepted with the current confidence\nthreshold $c$.  This can especially be interesting when looking for general patterns in\nthe interpretation $\\mathcal{I}$, or when it is not yet clear which value for the\nconfidence threshold to choose.  On the other hand, it is also quite obvious that the\npreceding argumentation is not formal, and that this approach should be seen as a\nheuristics.\n\n%%% Local Variables: \n%%% mode: latex\n%%% TeX-master: \"../main\"\n%%% End: \n%  LocalWords:  unintuitive Organisation PopulatedPlace OfficeHolder rdf ns Infobox conf\n%  LocalWords:  gcis DBpedia's Stumme du Pont de Nemours Eleuthère Irénée\n", "meta": {"hexsha": "5e7f02f71b9fab81fdac3382b33b2129b3060b87", "size": 135266, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/axiomatizing-confident-gcis.tex", "max_stars_repo_name": "exot/thesis", "max_stars_repo_head_hexsha": "5cda9bc3011e0c5697b8a5aede9525d0001058ca", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/axiomatizing-confident-gcis.tex", "max_issues_repo_name": "exot/thesis", "max_issues_repo_head_hexsha": "5cda9bc3011e0c5697b8a5aede9525d0001058ca", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/axiomatizing-confident-gcis.tex", "max_forks_repo_name": "exot/thesis", "max_forks_repo_head_hexsha": "5cda9bc3011e0c5697b8a5aede9525d0001058ca", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.661423221, "max_line_length": 113, "alphanum_fraction": 0.6614892138, "num_tokens": 47048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953797290152, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.31797320964136633}}
{"text": "\\subsection{Privacy Preserving C4.5}\\label{s:pp-c45}\nC4.5 is a decision tree generating algorithm developed by Ross Quinlan \\cite{quinlan1993c4}.\nThe C4.5 algorithm is an extension of the ID3 algorithm described in section \\ref{s:id3} also developed by Quinlan \\cite{quinlan1986induction}.\nIt was ranked \\#1 in the \\textit{Top 10 Algorithms in Data Mining} pre\\hyp eminent paper published by Springer Knowledge and Information Systems in 2008 \\cite{wu2008top}.\n\nThe main difference between C4.5 and ID3 is that the former has native support for both continuous (\\textit{i.e.} numerical) data and discrete (\\textit{i.e.} categorical) data. The idea behind C4.5 classification is to find the best splitting point for an attribute and split the dataset on that point.\nTransactions that are below that threshold belong to one branch and transaction above that threshold belong to the other branch.\nThe splitting criterion is based on the information gain \\ref{eq:gain} (difference in entropy \\ref{eq:entropy}) given by the splitting point.\nThe attribute that most efficiently splits the dataset is chosen by the algorithm at each level of the tree.\nAfter that the algorithm recurses on the two subsets created by that split.\n\n\nIn algorithm \\ref{a:c45-pp} we present the privacy\\hyp preserving \\f{C45} procedure.\nIt is quite similar to the \\f{ID3} one in algorithm \\ref{a:id3-pp}.\nThe main differences include that the call of \\f{Best} procedure (see algorithm \\ref{a:c45-best-pp}), now not only returns the ``best'' attribute, but also the ``best'' threshold that this attribute should split on, and the subsets that result from that split.\nIn case that the chosen attribute is categorical, then the $bestSplitted$ variable will contain the subsets resulting from each possible value $v_i$ of that attribute. ($\\{example \\in examples \\mid example[bestAttribute] = v_i\\}$ for each possible $v_i$), and the algorithm creates that many branches.\nIn case that $bestAttribute$ is a numerical attribute, then the $bestSplitted$ variable will contain the two subsets -- the set of transactions $t$ having $t[bestAttribute] <= bestThreshold$ ($less$), and the set of transactions $t$ having $t[bestAttribute] > bestThreshold$ ($greater$).\nAlso, in that case creates two branches one for each aforementioned subsets.\nSince the algorithm creates two branches for every split for numerical attributes) the output tree is a binary tree (branching factor $= 2$), unlike ID3 where the branching factor of the tree is equal to the number of possible values for every attribute.\n\n\\import{./}{algorithms/c45_pp.tex}\n\n% \\import{./}{algorithms/c45_gain_textbook.tex}\n% \\import{./}{algorithms/c45_best_textbook.tex}\n% \\import{./}{algorithms/c45_textbook.tex}\n\n\n\n\nHere we present the privacy\\hyp preserving algorithms for \\f{C45} and \\f{Best} procedures.\nAs in section \\ref{s:pp-id3} we face the same restrictions regarding the subset creation, for the same reasons as described before.\nWe omit the rest procedures, as well as their textbook equivalents, as they are similar to the ones presented in sections \\ref{s:id3} and \\ref{s:pp-id3}.\nOne difference for example is that the \\f{InformationGain} procedure takes the disjoint subsets that occur from a split as an argument instead of taking the attribute and computing the subsets inside.\nAlso, another argument is the current entropy of the dataset that gets computed once in the \\f{Best} procedure for optimization purposes.\n\n\\import{./}{algorithms/c45_best_pp.tex}\n", "meta": {"hexsha": "e3fe2d91b9842fe42034f41610cbf69a12606705", "size": 3496, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "c45.tex", "max_stars_repo_name": "jimouris/master-thesis", "max_stars_repo_head_hexsha": "e424cdd458cb7ff964bebcaaecfb7cad5b3ea525", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2018-08-29T07:51:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-09T12:09:24.000Z", "max_issues_repo_path": "c45.tex", "max_issues_repo_name": "jimouris/master-thesis", "max_issues_repo_head_hexsha": "e424cdd458cb7ff964bebcaaecfb7cad5b3ea525", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c45.tex", "max_forks_repo_name": "jimouris/master-thesis", "max_forks_repo_head_hexsha": "e424cdd458cb7ff964bebcaaecfb7cad5b3ea525", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-08-28T14:33:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-28T17:09:24.000Z", "avg_line_length": 94.4864864865, "max_line_length": 302, "alphanum_fraction": 0.7837528604, "num_tokens": 827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.3179732016337713}}
{"text": "\\subsubsection{Forward Rate Agreement}\n\nA forward rate agreement (trade type \\emph{ForwardRateAgreement} is set up using a \\\\\n{\\tt ForwardRateAgreementData} block as shown in listing \\ref{lst:ForwardRateAgreementdata}. The forward rate agreement specific elements\nare:\n\n\\begin{itemize}\n\\item StartDate: A FRA expires/settles on the startDate. \\\\\n\nAllowable values:  See \\lstinline!Date! in Table \\ref{tab:allow_stand_data}.\n\n\\item EndDate: EndDate is the date when the forward loan or deposit ends. It follows that (EndDate - StartDate) is the tenor/term of the underlying loan or deposit.\n\nAllowable values:  See \\lstinline!Date! in Table \\ref{tab:allow_stand_data}.\n\\item Currency: The currency of the FRA notional. \\\\\n\nAllowable values:  See \\lstinline!Currency! in Table \\ref{tab:allow_stand_data}.\t\n\\item Index: The name of the interest rate index the FRA is benchmarked against.\n\n  Allowable values: An alphanumeric string of the form CCY-INDEX-TERM. CCY, INDEX and TERM must be separated by dashes (-). CCY and INDEX must be among the supported currency and index combinations. TERM must be an integer followed by D, W,\n  M or Y. See Table \\ref{tab:indices}.\n  \n\\item LongShort: Specifies whether the FRA position is long (one receives the agreed rate) or short (one pays the agreed rate).\n\nAllowable values: \\emph{Long}, \\emph{Short}.\n\\item Strike: The agreed forward interest rate.\n\nAllowable values: Any  real number. The strike rate is\n  expressed in decimal form, e.g. 0.05 is a rate of 5\\%.\n\\item Notional: No accretion or amortisation, just a constant notional. \\\\\nAllowable values:  Any positive real number.\n\\end{itemize}\n\n\n\\begin{listing}[H]\n%\\hrule\\medskip\n\\begin{minted}[fontsize=\\footnotesize]{xml}\n    <ForwardRateAgreementData>\n        <StartDate>20161028</StartDate>\n        <EndDate>20351028</EndDate>\n        <Currency>EUR</Currency>\n        <Index>EUR-EURIBOR-6M</Index>\n        <LongShort>Long</LongShort>\n        <Strike>0.001</Strike>\n        <Notional>1000000000</Notional>\n    </ForwardRateAgreementData>\n\\end{minted}\n\\caption{Forward Rate Agreement Data}\n\\label{lst:ForwardRateAgreementdata}\n\\end{listing}", "meta": {"hexsha": "6318495a1b7a7a2109267b4bda9164af86821486", "size": 2137, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Docs/UserGuide/tradedata/forwardrateagreement.tex", "max_stars_repo_name": "mrslezak/Engine", "max_stars_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 335, "max_stars_repo_stars_event_min_datetime": "2016-10-07T16:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T07:12:03.000Z", "max_issues_repo_path": "Docs/UserGuide/tradedata/forwardrateagreement.tex", "max_issues_repo_name": "mrslezak/Engine", "max_issues_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 59, "max_issues_repo_issues_event_min_datetime": "2016-10-31T04:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T16:39:57.000Z", "max_forks_repo_path": "Docs/UserGuide/tradedata/forwardrateagreement.tex", "max_forks_repo_name": "mrslezak/Engine", "max_forks_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 180, "max_forks_repo_forks_event_min_datetime": "2016-10-08T14:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:43:05.000Z", "avg_line_length": 42.74, "max_line_length": 240, "alphanum_fraction": 0.7487131493, "num_tokens": 580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.31797319311657674}}
{"text": "\\documentclass[aps,nofootinbib,notitlepage,11pt]{revtex4-1}\n\n% linking references\n\\usepackage{hyperref}\n\\hypersetup{\n  breaklinks=true,\n  colorlinks=true,\n  linkcolor=blue,\n  filecolor=magenta,\n  urlcolor=cyan,\n}\n\n%%% symbols, notations, etc.\n\\usepackage{physics,braket,bm,amssymb} % physics and math\n\\renewcommand{\\t}{\\text} % text in math mode\n\\newcommand{\\f}[2]{\\dfrac{#1}{#2}} % shorthand for fractions\n\\newcommand{\\p}[1]{\\left(#1\\right)} % parenthesis\n\\renewcommand{\\sp}[1]{\\left[#1\\right]} % square parenthesis\n\\renewcommand{\\set}[1]{\\left\\{#1\\right\\}} % curly parenthesis\n\\renewcommand{\\v}{\\bm} % bold vectors\n\\newcommand{\\uv}[1]{\\hat{\\v{#1}}} % unit vectors\n\\newcommand{\\av}{\\vec} % arrow vectors\n\\newcommand{\\del}{\\nabla} % del operator\n\\renewcommand{\\d}{\\partial} % partial d\n\\renewcommand{\\c}{\\cdot} % inner product\n\\newcommand{\\w}{\\wedge} % wedge product\n\\newcommand{\\bk}{\\Braket} % shorthand for braket notation\n\n\\newcommand{\\up}{\\uparrow}\n\\newcommand{\\dn}{\\downarrow}\n\\newcommand{\\g}{\\text{g}}\n\\newcommand{\\e}{\\text{e}}\n\\renewcommand{\\L}{\\text{L}}\n\\newcommand{\\C}{\\text{C}}\n\\newcommand{\\R}{\\text{R}}\n\\newcommand{\\B}{\\text{B}}\n\\renewcommand{\\P}{\\text{P}}\n\\newcommand{\\T}{\\text{T}}\n\n\\usepackage{dsfont} % for \\1\n\\newcommand{\\1}{\\mathds{1}}\n\n\\usepackage{mathtools} % for coloneqq\n\\usepackage{tikz} % for energy level diagram\n\\tikzset{\n  baseline = (current bounding box.center),\n}\n\\usetikzlibrary{decorations.pathmorphing}\n\n\n\\usepackage[inline]{enumitem} % in-line lists\n\n% leave a note in the text, visible in the compiled document\n\\newcommand{\\note}[1]{\\textcolor{red}{#1}}\n\n\\begin{document}\n\n\\title{Basic operations for a quantum link model with ultracold\n  $^{87}$Sr on a lattice}\n\n\\author{Michael A. Perlin}\n\n\\maketitle\n\nWe consider loading ultracold $^{87}$Sr atoms into an isolated\nthree-site cell of a state-dependent 2-D optical superlattice, with\nreal on-sites wavefunctions $\\phi_\\L$ (left) and $\\phi_\\R$ (right) for\natoms in the ground electronic state ($^1S_0$), and $\\phi_\\C$ (center)\nfor atoms in the excited electronic state ($^3P_0$).  The\nsingle-particle Hamiltonian is then\n\\begin{align}\n  H_0 = \\sum_{s,\\mu} E_s c_{s\\mu}^\\dag c_{s\\mu},\n\\end{align}\nfor sites $r,s\\in\\set{\\L,\\C,\\R}$, nuclear spins\n$\\mu\\in\\set{-I,\\cdots,I}$, and fermionic annihilation operators\n$c_{s\\mu}$.  The energy mismatches $\\Delta_{pq}\\equiv E_p-E_q$ between\nsites $p\\ne q$ will generally set the largest energy scale throughout\nthis work.  If there are multiple atoms loaded within the same cell,\nthese atoms interact through the two-body Hamiltonian\n\\begin{align}\n  H_{\\t{int}} = \\f12 \\sum_{\\substack{p,q,r,s\\\\\\mu,\\nu}}\n  V^{pq}_{rs} c_{r\\mu}^\\dag c_{s\\nu}^\\dag c_{q\\nu} c_{p\\mu}\n  \\label{eq:H_int_full}\n\\end{align}\nfor interaction strengths $V^{pq}_{rs}$ which depend only on the sites\nand their associated electronic states; these interaction strengths do\nnot depend on the nuclear spin states involved.  Defining\n\\begin{align}\n  K^{pq}_{rs} \\equiv \\int d^3x~ \\phi_r^* \\phi_s^* \\phi_q \\phi_p,\n  &&\n  G_{\\sigma=\\g,\\e} \\equiv \\f{4\\pi}{m_A} a_{\\sigma\\sigma},\n  &&\n  G_\\pm \\equiv \\f{2\\pi}{m_A} \\p{a_{\\e\\g+} \\pm a_{\\e\\g-}},\n\\end{align}\n\\begin{align}\n  G^{\\alpha\\beta}_{\\gamma\\delta} \\equiv \\left\\{\n    \\begin{array}{ll}\n      G_\\alpha & ~ \\alpha = \\beta = \\gamma = \\delta \\\\\n      G_+ & ~ \\alpha \\ne \\beta ~ \\t{and} ~\n            (\\alpha,\\beta) = (\\gamma,\\delta) \\\\\n      G_- & ~ \\alpha \\ne \\beta ~ \\t{and} ~\n            (\\alpha,\\beta) = (\\delta,\\gamma) \\\\\n      0 & ~ \\t{otherwise}\n    \\end{array}\\right.,\n\\end{align}\nfor an atomic mass $m_A$ and scattering lengths $a_X$, the interaction\nstrengths in \\eqref{eq:H_int_full} are\n\\begin{align}\n  V^{pq}_{rs} = K^{pq}_{rs}\n  G^{\\varepsilon\\p{p}\\varepsilon\\p{q}}_{\\varepsilon\\p{r}\\varepsilon\\p{s}},\n\\end{align}\nwhere $\\varepsilon\\p{p}\\in\\set{\\g,\\e}$ selects the electronic state\nassociated with site $p$.  As a first approximation, we assume that\nthe two-body overlap integral $K^{pq}_{rs}$ is negligible unless\n$\\set{p,q}=\\set{r,s}$, i.e. we neglect interaction-assisted tunneling\nin $H_{\\t{int}}$.  In the presence of only $H_0$ and $H_{\\t{int}}$,\nthis approximation can also be justified by the secular approximation\ndue to mismatched single-particle on-site energies $E_s$.  The\ninteraction Hamiltonian then simplifies to\n\\begin{align}\n  H_{\\t{int}}\n  = \\f12 \\sum_{p,\\mu,\\nu} V_p c_{p\\mu}^\\dag c_{p\\nu}^\\dag c_{p\\nu} c_{p\\mu}\n  + \\f12 \\sum_{\\substack{p\\ne q\\\\\\mu,\\nu}} V_{pq}\n  \\p{c_{p\\mu}^\\dag c_{q\\nu}^\\dag c_{q\\nu} c_{p\\mu}\n    + c_{q\\mu}^\\dag c_{p\\nu}^\\dag c_{q\\nu} c_{p\\mu}},\n  \\label{eq:H_int_two}\n\\end{align}\nwhere\n\\begin{align}\n  V_p \\equiv V^{pp}_{pp},\n  &&\n  V_{pq} \\equiv V^{pq}_{pq} = V^{pq}_{qp},\n  &&\n  n_{p\\mu} \\equiv c_{p\\mu}^\\dag c_{p\\mu}.\n\\end{align}\nAs made clear by the form in \\eqref{eq:H_int_two}, the interaction\nHamiltonian $H_{\\t{int}}$ generally induces nuclear spin exchange\nbetween atoms in different orbitals.  In order to suppress nuclear\nspin exchange, we further restrict ourselves to a regime in which the\ntwo-body overlap integral $K^{pq}_{rs}$ is negligible unless all atoms\nare on the same site (i.e. unless $p=q=r=s$), such that\n\\begin{align}\n  H_{\\t{int}}\n  = \\f12 \\sum_{p,\\mu,\\nu} V_p c_{p\\mu}^\\dag c_{p\\nu}^\\dag c_{p\\nu} c_{p\\mu}\n  = \\sum_{\\substack{p\\\\\\mu<\\nu}} V_p n_{p\\mu} n_{p\\nu}.\n  \\label{eq:H_int}\n\\end{align}\nThroughout the remainder of this work, to simplify matters we\ngenerally assume that atoms initially in the electronic ground state\non site $\\L$ or $\\R$ lie in the nuclear spin manifold spanned by\n$\\set{\\ket{-I},\\ket{-I+1}}$, while atoms initially in an excited\nelectronic state on site $\\C$ lie in the nuclear spin manifold spanned\nby $\\set{\\ket{I},\\ket{I-1}}$.  We also assume that each site is\ninitially populated with at most one atom.\n\n\n\\section{Global control gates}\n\\label{sec:global_control}\n\nWe wish to build a toolkit of operations to manipulate atoms in our\nthree-site cell, with the long term goal of combining many such cells\nto simulate a quantum link model.  Before we discuss any multi-body\ngates, we first need to construct some basic, single-body global\ncontrol operations.  These basic operations together with the two-body\ninteraction Hamiltonian $H_{\\t{int}}$ in \\eqref{eq:H_int} will be our\nbuilding blocks for realizing more complicated gates.\n\nThe first simple operation we consider is the application of a static\nmagnetic field with strength $B$ along the nuclear spin quantization\naxis (which we will generally keep fixed), realizing the Hamiltonian\n\\begin{align}\n  H_\\B = -\\gamma_{\\text{n}} B \\sum_{s,\\mu} \\mu n_{s\\mu},\n\\end{align}\nwhere $\\gamma_{\\text{n}}$ is the nuclear gyromagnetic ratio.  Applying\nthis Hamiltonian for a time $t=\\theta/\\gamma_nB$ generates the phase\ngate\n\\begin{align}\n  U_\\B\\p{\\theta} = \\sum_{s,\\mu} e^{i \\theta \\mu} n_{s\\mu}.\n\\end{align}\nAs the nuclear spins $\\mu$ are half-integers, the operation\n$U_\\B\\p{\\theta}$ is periodic in $\\theta$ with period $4\\pi$.\n\nWe can also shine an auxiliary laser with angular frequency $\\omega$\nto apply the Hamiltonian\n\\begin{align}\n  H_\\Omega^{(\\sigma)}\n  = - \\sum_\\mu e^{i\\omega t}\n  \\p{\\Omega_{\\C,\\L,\\mu}^{(\\sigma)} c_{\\L,\\mu}^\\dag\n    + \\Omega_{\\C,\\R,\\mu}^{(\\sigma)} c_{\\R,\\mu}^\\dag} c_{\\C,\\mu+\\sigma}\n  + \\t{h.c.},\n\\end{align}\nwhere $\\sigma\\in\\set{-1,0,1}$ is determined by the clock laser\npolarization; $\\L\\leftrightarrow\\R$ coupling is forbidden because\n$H_\\Omega^{(\\sigma)}$ is strictly off-diagonal in electronic state;\nand $\\t{h.c.}$ denotes the Hermitian conjugate, i.e.\n$X+\\t{h.c.}\\equiv X+X^\\dag$.  By evaluating the Clebsch-Gordan\ncoefficients $\\bk{I,\\mu+\\sigma;1,-\\sigma|I,\\mu}$, we can extract the\n$\\mu,\\sigma,p,q$ dependence of $\\Omega_{pq\\mu}^{(\\sigma)}$ to find\n\\begin{align}\n  \\Omega_{pq\\mu}^{(0)} = \\Omega_{pq}^{(0)} \\mu,\n  &&\n  \\Omega_{pq\\mu}^{(\\pm1)} = \\pm \\Omega_{pq}^{(1)}\n  \\sqrt{\\p{I\\mp\\mu}\\p{I\\pm\\mu+1}},\n  &&\n  \\Omega_{pq}^{(\\sigma)} \\equiv \\Omega_\\sigma \\int d^3x~ \\phi_q^* \\phi_p,\n\\end{align}\nfor experimentally tunable intensities $\\Omega_0$ and $\\Omega_1$ which\nare independent of nuclear spin and lattice site.  In this section, we\nwill generally assume that these intensities are real and large\ncompared to all interaction energies,\ni.e. $\\Omega_0,\\Omega_1\\gg\\max_p\\abs{V_p}$.  We also consider the case\nof ${}^{87}$Sr with net nuclear spin $I=9/2$ in order to fix the\nrelative magnitudes of couplings $\\Omega_{pq\\mu}^{(\\sigma)}$ for\ndifferent nuclear spins $\\mu$.  The Hamiltonians $H_\\Omega^{(\\sigma)}$\ncan be thought of diagrammatically as\n\\begin{align}\n  H_\\Omega^{(0)} \\sim\n  \\begin{tikzpicture}[\n    scale=0.5,\n    trans/.style={thick,<->,shorten >=2pt,shorten <=2pt,>=stealth}\n    ]\n    \\draw (0,0) -- (1,0);\n    \\draw (2,0) -- (3,0);\n    \\draw[dotted] (3.5,0) -- (4.5,0);\n    \\draw (5,0) -- (6,0);\n    \\draw (7,0) -- (8,0);\n    \\draw (7,0) -- (8,0) node[right] {$\\C$};\n    \\draw (0,-2) -- (1,-2);\n    \\draw (2,-2) -- (3,-2);\n    \\draw[dotted] (3.5,-2) -- (4.5,-2);\n    \\draw (5,-2) -- (6,-2);\n    \\draw (7,-2) -- (8,-2);\n    \\draw (7,-2) -- (8,-2) node[right] {$s\\in\\set{\\L,\\R}$};\n    \\draw[trans] (0.5,0) -- (0.5,-2) node[midway,left] {$-9$};\n    \\draw[trans] (2.5,0) -- (2.5,-2) node[midway,left] {$-7$};\n    \\draw[trans] (5.5,0) -- (5.5,-2) node[midway,left] {$7$};\n    \\draw[trans] (7.5,0) -- (7.5,-2) node[midway,left] {$9$};\n  \\end{tikzpicture},\n\\end{align}\nwhere the horizontal lines represent nuclear spin levels from $-9/2$\nto $9/2$ (i.e. from left to right) within each orbital state $\\C$ or\n$s\\in\\set{\\L,\\R}$, and the double-headed arrows represent a coupling\nbetween two states.  The numbers next to the arrows represents the\nrelative magnitudes of the couplings.  Similarly,\n\\begin{align}\n  H_\\Omega^{(1)} \\sim\n  \\begin{tikzpicture}[\n    scale=0.5,\n    trans/.style={thick,<->,shorten >=2pt,shorten <=2pt,>=stealth}\n    ]\n    \\draw (0,0) -- (1,0);\n    \\draw (2,0) -- (3,0);\n    \\draw (4,0) -- (5,0);\n    \\draw[dotted] (5.5,0) -- (6.5,0);\n    \\draw (7,0) -- (8,0);\n    \\draw (9,0) -- (10,0);\n    \\draw (11,0) -- (12,0);\n    \\draw (11,0) -- (12,0) node[right] {$\\C$};\n    \\draw (0,-2) -- (1,-2);\n    \\draw (2,-2) -- (3,-2);\n    \\draw (4,-2) -- (5,-2);\n    \\draw[dotted] (5.5,-2) -- (6.5,-2);\n    \\draw (7,-2) -- (8,-2);\n    \\draw (9,-2) -- (10,-2);\n    \\draw (11,-2) -- (12,-2);\n    \\draw (11,-2) -- (12,-2) node[right] {$s\\in\\set{\\L,\\R}$};\n    \\draw[trans] (0.5,-2) -- (2.5,0) node[midway,left] {$3$};\n    \\draw[trans] (2.5,-2) -- (4.5,0) node[midway,left] {$4$};\n    \\draw[trans] (7.5,-2) -- (9.5,0) node[midway,left] {$4$};\n    \\draw[trans] (9.5,-2) -- (11.5,0) node[midway,left] {$3$};\n  \\end{tikzpicture},\n  \\label{eq:H_O_+}\n\\end{align}\nand\n\\begin{align}\n  H_\\Omega^{(-1)} \\sim\n  \\begin{tikzpicture}[\n    scale=0.5,\n    trans/.style={thick,<->,shorten >=2pt,shorten <=2pt,>=stealth}\n    ]\n    \\draw (0,0) -- (1,0);\n    \\draw (2,0) -- (3,0);\n    \\draw (4,0) -- (5,0);\n    \\draw[dotted] (5.5,0) -- (6.5,0);\n    \\draw (7,0) -- (8,0);\n    \\draw (9,0) -- (10,0);\n    \\draw (11,0) -- (12,0);\n    \\draw (11,0) -- (12,0) node[right] {$\\C$};\n    \\draw (0,-2) -- (1,-2);\n    \\draw (2,-2) -- (3,-2);\n    \\draw (4,-2) -- (5,-2);\n    \\draw[dotted] (5.5,-2) -- (6.5,-2);\n    \\draw (7,-2) -- (8,-2);\n    \\draw (9,-2) -- (10,-2);\n    \\draw (11,-2) -- (12,-2);\n    \\draw (11,-2) -- (12,-2) node[right] {$s\\in\\set{\\L,\\R}$};\n    \\draw[trans] (0.5,0) -- (2.5,-2) node[midway,right] {$3$};\n    \\draw[trans] (2.5,0) -- (4.5,-2) node[midway,right] {$4$};\n    \\draw[trans] (7.5,0) -- (9.5,-2) node[midway,right] {$4$};\n    \\draw[trans] (9.5,0) -- (11.5,-2) node[midway,right] {$3$};\n  \\end{tikzpicture},\n  \\label{eq:H_O_-}\n\\end{align}\nwhere we neglect couplings for nuclear spins $\\mu$ outside of\n$\\set{-I,-I+1,I-1,I}$.\n\nBy turning on $H_\\Omega^{(0)}$ for a time $t=\\pi/\\Omega^{(0)}_{\\C,s}$\nwith an angular frequency $\\omega$ resonant on the energy difference\n$\\Delta_{\\C,s}=E_C-E_s$ for $s\\in\\set{\\L,\\R}$, we can apply the\n$\\pi$-pulse gate\n\\begin{align}\n  U_{\\pi,s}\n  \\equiv \\sum_\\mu e^{i\\pi\\mu} c_{s\\mu}^\\dag c_{\\C,\\mu} + \\t{h.c}\n  \\coloneqq i \\times\n  \\begin{tikzpicture}[\n    scale=0.5,\n    trans/.style={thick,<->,shorten >=2pt,shorten <=2pt,>=stealth}\n    ]\n    \\draw (0,0) -- (1,0);\n    \\draw (2,0) -- (3,0);\n    \\draw[dotted] (3.5,0) -- (4.5,0);\n    \\draw (5,0) -- (6,0);\n    \\draw (7,0) -- (8,0);\n    \\draw (7,0) -- (8,0) node[right] {$\\C$};\n    \\draw (0,-2) -- (1,-2);\n    \\draw (2,-2) -- (3,-2);\n    \\draw[dotted] (3.5,-2) -- (4.5,-2);\n    \\draw (5,-2) -- (6,-2);\n    \\draw (7,-2) -- (8,-2);\n    \\draw (7,-2) -- (8,-2) node[right] {$s$};\n    \\draw[trans] (0.5,0) -- (0.5,-2) node[midway,left] {$-1$};\n    \\draw[trans] (2.5,0) -- (2.5,-2) node[midway,left] {$1$};\n    \\draw[trans] (5.5,0) -- (5.5,-2) node[midway,left] {$-1$};\n    \\draw[trans] (7.5,0) -- (7.5,-2) node[midway,left] {$1$};\n  \\end{tikzpicture},\n  \\label{eq:U_pi}\n\\end{align}\nwhich swaps atoms between orbitals $\\C$ and $s$ and applies a\nspin-dependent sign.\n\nThe relative magnitudes of the couplings $\\Omega_{pq\\mu}^{(\\pm1)}$ for\ndifferent nuclear spins $\\mu$ similarly allows us to turn on\n$H_\\Omega^{(\\pm1)}$ for an appropriately resonant angular frequency\n$\\omega$ and a time $t=\\p{\\pi/2}/\\Omega_{\\C,s}^{(1)}$, thereby\nrealizing the gates\n\\begin{align}\n  U_{\\pi,s}^+\n  \\equiv -i\\p{c_{s,-I+1} c_{\\C,-I+1}^\\dag + c_{s,I-1}^\\dag c_{\\C,I}}\n  + \\t{h.c.}\n  \\coloneqq -i \\times\n  \\begin{tikzpicture}[\n    scale=0.5,\n    trans/.style={thick,<->,shorten >=2pt,shorten <=2pt,>=stealth}\n    ]\n    \\draw (0,0) -- (1,0);\n    \\draw (2,0) -- (3,0);\n    \\draw[dotted] (3.5,0) -- (4.5,0);\n    \\draw (5,0) -- (6,0);\n    \\draw (7,0) -- (8,0);\n    \\draw (7,0) -- (8,0) node[right] {$\\C$};\n    \\draw (0,-2) -- (1,-2);\n    \\draw (2,-2) -- (3,-2);\n    \\draw[dotted] (3.5,-2) -- (4.5,-2);\n    \\draw (5,-2) -- (6,-2);\n    \\draw (7,-2) -- (8,-2);\n    \\draw (7,-2) -- (8,-2) node[right] {$s$};\n    \\draw[trans] (2.5,0) -- (0.5,-2);\n    \\draw[trans] (7.5,0) -- (5.5,-2);\n  \\end{tikzpicture},\n  \\label{eq:U_pi_+}\n\\end{align}\nand\n\\begin{align}\n  U_{\\pi,s}^-\n  \\equiv i\\p{c_{s,-I+1} c_{\\C,-I+1}^\\dag + c_{s,I}^\\dag c_{\\C,I-1}}\n  + \\t{h.c.}\n  \\coloneqq i \\times\n  \\begin{tikzpicture}[\n    scale=0.5,\n    trans/.style={thick,<->,shorten >=2pt,shorten <=2pt,>=stealth}\n    ]\n    \\draw (0,0) -- (1,0);\n    \\draw (2,0) -- (3,0);\n    \\draw[dotted] (3.5,0) -- (4.5,0);\n    \\draw (5,0) -- (6,0);\n    \\draw (7,0) -- (8,0);\n    \\draw (7,0) -- (8,0) node[right] {$\\C$};\n    \\draw (0,-2) -- (1,-2);\n    \\draw (2,-2) -- (3,-2);\n    \\draw[dotted] (3.5,-2) -- (4.5,-2);\n    \\draw (5,-2) -- (6,-2);\n    \\draw (7,-2) -- (8,-2);\n    \\draw (7,-2) -- (8,-2) node[right] {$s$};\n    \\draw[trans] (0.5,0) -- (2.5,-2);\n    \\draw[trans] (5.5,0) -- (7.5,-2);\n  \\end{tikzpicture},\n  \\label{eq:U_pi_-}\n\\end{align}\nwhere the remaining states addressed by $H_\\Omega^{(\\pm1)}$ in\n\\eqref{eq:H_O_+} and \\eqref{eq:H_O_-} are unaffected because they\nundergo Rabi cycles which bring them back to their initial states.\n\nAll of the above $\\pi$-pulse gates can be turned into $\\pi/2$-pulse\ngates $U_{\\pi/2,s}$, $U_{\\pi/2,s}^\\pm$ simply by applying the\nappropriate Hamiltonian for half of the specified time.  Furthermore,\nif we are guaranteed that only certain nuclear spin states are\noccupied, we can also apply $\\pi$-pulse gates by turning on\n$H_\\Omega^{(\\pm1)}$ for a time $t=\\p{\\pi/6}/\\Omega_{\\C,s}^{(1)}$,\ngiving us\n\\begin{align}\n  \\tilde U_{\\pi,s}^+\n  \\coloneqq i \\times\n  \\begin{tikzpicture}[\n    scale=0.5,\n    trans/.style={thick,<->,shorten >=2pt,shorten <=2pt,>=stealth}\n    ]\n    \\draw (0,0) -- (1,0);\n    \\draw (2,0) -- (3,0);\n    \\draw[dotted] (3.5,0) -- (5.5,0);\n    \\draw (6,0) -- (7,0);\n    \\draw (8,0) -- (9,0);\n    \\draw (8,0) -- (9,0) node[right] {$\\C$};\n    \\draw (0,-2) -- (1,-2);\n    \\draw (2,-2) -- (3,-2);\n    \\draw[dotted] (3.5,-2) -- (5.5,-2);\n    \\draw (6,-2) -- (7,-2);\n    \\draw (8,-2) -- (9,-2);\n    \\draw (8,-2) -- (9,-2) node[right] {$s$};\n    \\draw[trans] (2.5,0) -- (0.5,-2);\n    \\draw[trans, dashed] (4.5,0) -- (2.5,-2);\n    \\draw[trans, dashed] (6.5,0) -- (4.5,-2);\n    \\draw[trans] (8.5,0) -- (6.5,-2);\n  \\end{tikzpicture},\n  &&\n  \\tilde U_{\\pi,s}^-\n  \\coloneqq -i \\times\n  \\begin{tikzpicture}[\n    scale=0.5,\n    trans/.style={thick,<->,shorten >=2pt,shorten <=2pt,>=stealth}\n    ]\n    \\draw (0,0) -- (1,0);\n    \\draw (2,0) -- (3,0);\n    \\draw[dotted] (3.5,0) -- (5.5,0);\n    \\draw (6,0) -- (7,0);\n    \\draw (8,0) -- (9,0);\n    \\draw (8,0) -- (9,0) node[right] {$\\C$};\n    \\draw (0,-2) -- (1,-2);\n    \\draw (2,-2) -- (3,-2);\n    \\draw[dotted] (3.5,-2) -- (5.5,-2);\n    \\draw (6,-2) -- (7,-2);\n    \\draw (8,-2) -- (9,-2);\n    \\draw (8,-2) -- (9,-2) node[right] {$s$};\n    \\draw[trans] (2.5,-2) -- (0.5,0);\n    \\draw[trans, dashed] (4.5,-2) -- (2.5,0);\n    \\draw[trans, dashed] (6.5,-2) -- (4.5,0);\n    \\draw[trans] (8.5,-2) -- (6.5,0);\n  \\end{tikzpicture},\n\\end{align}\nwhere the dashed arrows indicate incomplete Rabi cycles that mix nuclear\nspin states in our target subspace with those outside it.  For\nsimplicity, we will work strictly with the cleaner $\\pi$-pulse gates\nin \\eqref{eq:U_pi}, \\eqref{eq:U_pi_+}, and \\eqref{eq:U_pi_-}.\n\n\n\\section{Tunneling gates}\n\\label{sec:tunneling}\n\nIn order to suppress nuclear spin exchange processes, we restricted\nourselves to a regime in which two-body overlap integrals for pairs of\natoms on different sites vanish.  The on-site wavefunctions $\\phi_p$\nare therefore fairly localized to site $p$, with some overlap in the\nsupport of $\\phi_\\C$ with $\\phi_s$ for $s\\in\\set{\\L,\\R}$ to allow for\nthe control gates $U_{\\pi,s}^\\pm$.  As a consequence, we expect\nvanishing mutual support of $\\phi_\\L$ and $\\phi_\\R$, which means that\nwe cannot induce $\\L\\leftrightarrow\\R$ tunneling directly.\nNonetheless, we can use the $\\pi$-pulse gates $U_{\\pi,s}$ in\n\\eqref{eq:U_pi} to induce indirect $\\L\\leftrightarrow\\R$ tunneling\nthrough the central site $\\C$ via\n\\begin{multline}\n  U_\\pi^\\T\n  \\equiv U_{\\pi,\\L} U_{\\pi,\\R} U_{\\pi,\\L}\n  \\cong U_{\\pi,\\R} U_{\\pi,\\L} U_{\\pi,\\R} \\\\\n  \\cong\n  \\sp{\\begin{tikzpicture}[\n      scale=0.5,\n      trans/.style={thick,<->,shorten >=2pt,shorten <=2pt,>=stealth}\n      ]\n      \\draw (0,0) -- (1,0);\n      \\draw (2,0) -- (3,0);\n      \\draw[dotted] (3.5,0) -- (4.5,0);\n      \\draw (5,0) -- (6,0);\n      \\draw (7,0) -- (8,0);\n      \\draw (7,0) -- (8,0) node[right] {$\\L$};\n      \\draw (0,-2) -- (1,-2);\n      \\draw (2,-2) -- (3,-2);\n      \\draw[dotted] (3.5,-2) -- (4.5,-2);\n      \\draw (5,-2) -- (6,-2);\n      \\draw (7,-2) -- (8,-2);\n      \\draw (7,-2) -- (8,-2) node[right] {$\\C$};\n      \\draw (0,-4) -- (1,-4);\n      \\draw (2,-4) -- (3,-4);\n      \\draw[dotted] (3.5,-4) -- (4.5,-4);\n      \\draw (5,-4) -- (6,-4);\n      \\draw (7,-4) -- (8,-4);\n      \\draw (7,-4) -- (8,-4) node[right] {$\\R$};\n      \\draw[trans] (0.5,0) -- (0.5,-2);\n      \\draw[trans] (2.5,0) -- (2.5,-2);\n      \\draw[trans] (5.5,0) -- (5.5,-2);\n      \\draw[trans] (7.5,0) -- (7.5,-2);\n    \\end{tikzpicture}}\n  \\sp{\\begin{tikzpicture}[\n      scale=0.5,\n      trans/.style={thick,<->,shorten >=2pt,shorten <=2pt,>=stealth}\n      ]\n      \\draw (0,0) -- (1,0);\n      \\draw (2,0) -- (3,0);\n      \\draw[dotted] (3.5,0) -- (4.5,0);\n      \\draw (5,0) -- (6,0);\n      \\draw (7,0) -- (8,0);\n      \\draw (7,0) -- (8,0) node[right] {$\\L$};\n      \\draw (0,-2) -- (1,-2);\n      \\draw (2,-2) -- (3,-2);\n      \\draw[dotted] (3.5,-2) -- (4.5,-2);\n      \\draw (5,-2) -- (6,-2);\n      \\draw (7,-2) -- (8,-2);\n      \\draw (7,-2) -- (8,-2) node[right] {$\\C$};\n      \\draw (0,-4) -- (1,-4);\n      \\draw (2,-4) -- (3,-4);\n      \\draw[dotted] (3.5,-4) -- (4.5,-4);\n      \\draw (5,-4) -- (6,-4);\n      \\draw (7,-4) -- (8,-4);\n      \\draw (7,-4) -- (8,-4) node[right] {$\\R$};\n      \\draw[trans] (0.5,-2) -- (0.5,-4);\n      \\draw[trans] (2.5,-2) -- (2.5,-4);\n      \\draw[trans] (5.5,-2) -- (5.5,-4);\n      \\draw[trans] (7.5,-2) -- (7.5,-4);\n    \\end{tikzpicture}}\n  \\sp{\\begin{tikzpicture}[\n      scale=0.5,\n      trans/.style={thick,<->,shorten >=2pt,shorten <=2pt,>=stealth}\n      ]\n      \\draw (0,0) -- (1,0);\n      \\draw (2,0) -- (3,0);\n      \\draw[dotted] (3.5,0) -- (4.5,0);\n      \\draw (5,0) -- (6,0);\n      \\draw (7,0) -- (8,0);\n      \\draw (7,0) -- (8,0) node[right] {$\\L$};\n      \\draw (0,-2) -- (1,-2);\n      \\draw (2,-2) -- (3,-2);\n      \\draw[dotted] (3.5,-2) -- (4.5,-2);\n      \\draw (5,-2) -- (6,-2);\n      \\draw (7,-2) -- (8,-2);\n      \\draw (7,-2) -- (8,-2) node[right] {$\\C$};\n      \\draw (0,-4) -- (1,-4);\n      \\draw (2,-4) -- (3,-4);\n      \\draw[dotted] (3.5,-4) -- (4.5,-4);\n      \\draw (5,-4) -- (6,-4);\n      \\draw (7,-4) -- (8,-4);\n      \\draw (7,-4) -- (8,-4) node[right] {$\\R$};\n      \\draw[trans] (0.5,0) -- (0.5,-2);\n      \\draw[trans] (2.5,0) -- (2.5,-2);\n      \\draw[trans] (5.5,0) -- (5.5,-2);\n      \\draw[trans] (7.5,0) -- (7.5,-2);\n    \\end{tikzpicture}} \\\\\n  \\cong\n  \\begin{tikzpicture}[\n    scale=0.5,\n    trans/.style={thick,<->,shorten >=2pt,shorten <=2pt,>=stealth}\n    ]\n    \\draw (0,0) -- (1,0);\n    \\draw (2,0) -- (3,0);\n    \\draw[dotted] (3.5,0) -- (4.5,0);\n    \\draw (5,0) -- (6,0);\n    \\draw (7,0) -- (8,0);\n    \\draw (7,0) -- (8,0) node[right] {$\\L$};\n    \\draw (0,-2) -- (1,-2);\n    \\draw (2,-2) -- (3,-2);\n    \\draw[dotted] (3.5,-2) -- (4.5,-2);\n    \\draw (5,-2) -- (6,-2);\n    \\draw (7,-2) -- (8,-2);\n    \\draw (7,-2) -- (8,-2) node[right] {$\\R$};\n    \\draw[trans] (0.5,0) -- (0.5,-2);\n    \\draw[trans] (2.5,0) -- (2.5,-2);\n    \\draw[trans] (5.5,0) -- (5.5,-2);\n    \\draw[trans] (7.5,0) -- (7.5,-2);\n  \\end{tikzpicture},\n  \\label{eq:U_pi_T}\n\\end{multline}\nwhere $\\cong$ denotes equality up to an overall phase.  Crucially,\n$U_\\pi^\\T$ swaps atoms between sites $\\L$ and $\\R$ while leaving atoms\non site $\\C$ unaffected.  We can also construct $\\pi/2$-pulse gates\nfor $\\L\\leftrightarrow\\R$ tunneling via\n\\begin{align}\n  U_{\\pi/2}^\\T\n  \\equiv U_{\\pi,\\L} U_{\\pi/2,\\R} U_{\\pi,\\L}\n  \\cong U_{\\pi,\\R} U_{\\pi/2,\\L} U_{\\pi,\\R},\n\\end{align}\nwhich is identical to the composite gate $U_\\pi^\\T$ in\n\\eqref{eq:U_pi_T}, but with a replacement of the second $\\pi$-pulse by\na $\\pi/2$ pulse.  Finally, we can make use of the\nnuclear-spin-selective properties of $U_{\\pi,s}^\\pm$ to construct\nnuclear-spin-selective $\\L\\leftrightarrow\\R$ tunneling gates, simply\nby replacing instances of $U_{\\pi,s}$ above by $U_{\\pi,s}^\\pm$.\n\n\n\\section{Controlled-phase gates}\n\\label{sec:controlled_phase}\n\nWe now construct a collisional controlled-phase gate on an atom in\nsite $\\C$, conditional on the presence of an atom in site $s$.  We\nfirst prepare an atom on site $\\C$ in the nuclear spin manifold\nspanned by $\\set{\\ket{I},\\ket{I-1}}$, and consider the possibility of\nan atom on site $s$ with nuclear spin state $\\ket{-I}$, preparing the\nstate\n\\begin{align}\n  \\ket{\\psi_{sm}}\n  = \\ket{s,-I;m} \\otimes \\p{\\alpha\\ket{\\C,I} + \\beta\\ket{\\C,I-1}}\n  \\sim\n  \\begin{tikzpicture}[\n    scale=0.5,\n    sim/.style={decorate, decoration=snake},\n    ]\n    \\draw (0,0) -- (1,0);\n    \\draw (2,0) -- (3,0);\n    \\draw[dotted] (3.5,0) -- (4.5,0);\n    \\draw (5,0) -- (6,0) node[midway, above] {$\\beta$};\n    \\draw (7,0) -- (8,0) node[midway, above] {$\\alpha$};\n    \\draw (7,0) -- (8,0) node[right] {$\\C$};\n    \\draw (0,-2) -- (1,-2) node[midway, above] {$m$};\n    \\draw (2,-2) -- (3,-2);\n    \\draw[dotted] (3.5,-2) -- (4.5,-2);\n    \\draw (5,-2) -- (6,-2);\n    \\draw (7,-2) -- (8,-2);\n    \\draw (7,-2) -- (8,-2) node[right] {$s$};\n    \\draw[sim] (6,0.5) -- (7,0.5);\n  \\end{tikzpicture}\n  \\label{eq:psi_sm}\n\\end{align}\nwhere $m=0$ ($m=1$) marks the absence (presence) of an atom on site\n$s$ with spin $-I$.  The above diagram is merely provided as a sketch\nof the state; we will make no attempt at making this sketch a formal\nrepresentation.\n\nApplying the gate $U_{\\pi,s}^-$ in \\eqref{eq:U_pi_-} to the state\n$\\ket{\\psi_{sm}}$ in \\eqref{eq:psi_sm} gives us\n\\begin{align}\n  U_{\\pi,s}^-\\ket{\\psi_{sm}}\n  \\cong \\ket{s,-I;m} \\otimes \\p{\\alpha\\ket{\\C,I} + \\beta\\ket{s,I}}\n  \\sim\n  \\begin{tikzpicture}[\n    scale=0.5,\n    sim/.style={decorate, decoration=snake},\n    ]\n    \\draw (0,0) -- (1,0);\n    \\draw (2,0) -- (3,0);\n    \\draw[dotted] (3.5,0) -- (4.5,0);\n    \\draw (5,0) -- (6,0);\n    \\draw (7,0) -- (8,0) node[midway, above] {$\\alpha$};\n    \\draw (7,0) -- (8,0) node[right] {$\\C$};\n    \\draw (0,-2) -- (1,-2) node[midway, above] {$m$};\n    \\draw (2,-2) -- (3,-2);\n    \\draw[dotted] (3.5,-2) -- (4.5,-2);\n    \\draw (5,-2) -- (6,-2);\n    \\draw (7,-2) -- (8,-2) node[midway, above] {$\\beta$};\n    \\draw (7,-2) -- (8,-2) node[right] {$s$};\n    \\draw[sim] (7.5,0.1) -- (7.5,-0.9);\n  \\end{tikzpicture}.\n\\end{align}\nHolding for a time $t$ (i.e. evolving under $H_0+H_{\\t{int}}$) now\nmakes $\\beta$ pick up a phase relative to $\\alpha$ as\n$\\beta\\to\\tilde\\beta_{sm}\\p{t}\\equiv\\beta e^{it\\Delta_{\\C,s}-itV_sm}$,\nwhere $\\Delta_{\\C,s}=E_\\C-E_s$ is the single-particle energy\ndifference between the orbitals $\\C$ and $s$, and $V_s$ is the\ninteraction energy of two atoms in orbital $s$.  Subsequently applying\n$U_{\\pi,s}^-$ then gives us the state\n\\begin{align}\n  U_{\\pi,s}^- U_{\\t{hold}}\\p{t} U_{\\pi,s}^- \\ket{\\psi_{sm}}\n  \\cong \\ket{s,-I;m} \\otimes\n  \\p{\\alpha\\ket{\\C,I} + \\tilde\\beta_{sm}\\p{t}\\ket{\\C,I-1}}\n  \\sim\n  \\begin{tikzpicture}[\n    scale=0.5,\n    sim/.style={decorate, decoration=snake},\n    ]\n    \\draw (0,0) -- (1,0);\n    \\draw (2,0) -- (3,0);\n    \\draw[dotted] (3.5,0) -- (4.5,0);\n    \\draw (5,0) -- (6,0) node[near start, above]\n    {$\\tilde\\beta_{sm}\\p{t}$};\n    \\draw (7,0) -- (8,0) node[midway, above] {$\\alpha$};\n    \\draw (7,0) -- (8,0) node[right] {$\\C$};\n    \\draw (0,-2) -- (1,-2) node[midway, above] {$m$};\n    \\draw (2,-2) -- (3,-2);\n    \\draw[dotted] (3.5,-2) -- (4.5,-2);\n    \\draw (5,-2) -- (6,-2);\n    \\draw (7,-2) -- (8,-2);\n    \\draw (7,-2) -- (8,-2) node[right] {$s$};\n    \\draw[sim] (6.5,0.5) -- (7,0.5);\n  \\end{tikzpicture}.\n\\end{align}\nThe extra relative phase $e^{it\\Delta_{\\C,s}}$ on\n$\\tilde\\beta_{sm}\\p{t}$ can be cancelled out by the application of a\nmagnetic field with $U_\\B\\p{t\\Delta_{\\C,s}}$. In the basis\n$\\ket{m}_s\\equiv\\ket{s,-I;m}$ for site $s$ and\n$\\ket{n}_\\C\\equiv\\ket{\\C,I-n}$ for site $\\C$, the net effect of our\nsequence is thus the controlled-phase gate\n\\begin{multline}\n  U_{\\P,s}^{(0)}\\p{t}\n  \\equiv U_\\B\\p{t\\Delta_{\\C,s}}\n  U_{\\pi,s}^- U_{\\t{hold}}\\p{t} U_{\\pi,s}^- \\\\\n  = \\sum_{m,n\\in\\set{0,1}} \\exp\\p{-itV_snm} \\op{m}_s\\otimes\\op{n}_\\C\n  = \\op{0}_s \\otimes \\1_\\C + \\op{1}_s \\otimes\n  \\begin{pmatrix}\n    1 & 0 \\\\ 0 & e^{-itV_s}\n  \\end{pmatrix}_\\C.\n  \\label{eq:U_P_0}\n\\end{multline}\nA similar controlled-phase gate $U_{\\P,s}^{(1)}\\p{t}$ can be realized\nconditional on the presence of an atom on site $s$ with nuclear spin\n$-I+1$ by using $U_{\\pi,s}^+$ in place of $U_{\\pi,s}^-$.  Note that if\nthe atom on site $s$ is in a nontrivial superposition of nuclear spin\nstates $\\ket{-I}$ and $\\ket{-I+1}$, there will be two atoms on site\n$\\C$ during the hold time of $U_{\\P,s}^{(0)}\\p{t}$ and\n$U_{\\P,s}^{(1)}\\p{t}$, resulting in atom losses from\n${}^3P_0$-${}^3P_0$ interactions.\n\nAs a final comment, we mention that if we are guaranteed a single atom\non e.g.  site $\\L$ and no atom on site $\\R$, we can use the\nnuclear-spin selective $\\L\\leftrightarrow\\R$ tunneling gates mentioned\nat the end of section \\ref{sec:tunneling} to construct a\ncontrolled-phase gate conditional on the nuclear spin of an atom on\nsite $s$, rather than on the mere presence of such an atom.  That is,\nwe can construct a gate similar to that in \\eqref{eq:U_P_0}, but with\nthe nuclear spin basis $\\set{\\ket{-I},\\ket{-I+1}}$ for site $s$.  We\ncan provide and explain this construction in more detail upon request;\nthe basic idea is to\n\\begin{enumerate*}[label=(\\roman*)]\n\\item move e.g. the $-I+1$ spin component of the electronic\n  ground-state atom in site $\\L$ to site $\\R$,\n\\item act with the controlled-phase gates $U_{\\P,s}^{(0)}$ in\n  \\eqref{eq:U_P_0}, and then\n\\item move the $-I+1$ spin component of the electronic ground-state\n  atom back to site $\\L$.\n\\end{enumerate*}\n\n\\end{document}\n", "meta": {"hexsha": "1397aad308a0e9134dfcc540a0d639605c2eb432", "size": 27781, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "link_model/link_model_notes.tex", "max_stars_repo_name": "perlinm/rey_research", "max_stars_repo_head_hexsha": "491d1d33cc8d20dc1b72de552ac7c1b65fb3ee63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "link_model/link_model_notes.tex", "max_issues_repo_name": "perlinm/rey_research", "max_issues_repo_head_hexsha": "491d1d33cc8d20dc1b72de552ac7c1b65fb3ee63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "link_model/link_model_notes.tex", "max_forks_repo_name": "perlinm/rey_research", "max_forks_repo_head_hexsha": "491d1d33cc8d20dc1b72de552ac7c1b65fb3ee63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1900937082, "max_line_length": 75, "alphanum_fraction": 0.5726215759, "num_tokens": 11185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3179532857085877}}
{"text": "% Dispersal cartoon\n% Rendering issues\n% Use \"excluded\" constant characters to avoid confusion with \"missing\"\n% Emphasize that dpp-msbayes is biased toward shared events in discussion\n\n\\section{Introduction}\n\nTo understand the distribution of Earth's biodiversity, we must consider the\ndegree to which environmental changes explain diversity within and among\nspecies.\nA major component of this is understanding how community-scale processes cause\nco-diversification across evolutionary lineages.\nSuch processes are expected to generate patterns of divergence times that are\ndifficult to explain by lineage-specific processes of diversification.\nSpecifically, finding that divergences are temporally clustered across\nmultiple evolutionary lineages provides compelling evidence that a shared\nprocess was responsible for the lineages diverging.\nFor example, the fragmentation of an environment, like an island, forest, or\nwatershed, can cause multiple taxa distributed across that environment to\nco-diverge over a short period relative to evolutionary timescales\n(Fig.~\\ref{fig:divCartoon}).\n% \\thought{Better word than ``environment?'' I don't like landscape, because\n%     it excludes aquatic systems.}\n% , such that a model that treats them as\n% simultaneous will be a better explanation of the genetic variation than a model\n% that treats the divergence of each lineage as independent \\figureNeeded.\nOne way to test the predictions of such processes of diversification is to\ninfer the temporal pattern of divergences across multiple taxa, and determine\nwhether any subsets of the taxa shared the same divergence times.\n% As a result, we stand to learn a lot about processes of diversification from\n% a robust method for inferring the temporal pattern of divergences across\n% multiple, independent lineages.\n\n\\ifembed{\n\\input{fig-div-cartoon.tex}\n}{}\n\n\\begin{linenomath}\nIf researchers are interested in comparing the divergence times among a number\nof pairs of populations,\nwe can approach this as a problem of model choice:\nHow many divergence events, and what assignment of taxa to those events, best\nexplain the genetic variation within and between the diverged populations of\neach pair (Fig.~\\ref{fig:divCartoon})?\nOne challenge of this inference problem is the number of possible models.\nIf we have \\ncomparisons{} pairs of populations, we would like to assign them to an\nunknown number of divergence events, \\nevents{}, which can range from one to\n\\ncomparisons{}.\nFor a given number of divergence events, the Stirling number of the second kind\ntells us the number of ways of assigning the taxa to the divergence times\n(i.e., the number of models with \\nevents{} divergence-time parameters):\n\\begin{equation}\n    S_2(\\ncomparisons, \\nevents) = \n    \\frac{1}{\\nevents!} \\sum_{i = 0}^{\\nevents - 1} (-1)^{i}\n    \\binom{\\nevents}{i} (\\nevents - i)^{\\ncomparisons}.\n    \\label{eq:stirling2}\n\\end{equation}\nWhen the number of divergence times is unknown, we need to sum over all\npossible values of \\nevents{} to get the total number of possible divergence\nmodels\n\\citep[the Bell number;][]{Bell1934}):\n\\begin{equation}\n    B_{\\ncomparisons} = \\sum_{\\nevents = 1}^{\\ncomparisons}\n    S_2(\\ncomparisons, \\nevents).\n    \\label{eq:bell}\n\\end{equation}\nAs the number of pairs we wish to compare grows, the prospect of comparing\nmaximum or marginal likelihoods among all possible models quickly becomes\ndaunting.\nAs a result, a Bayesian model-averaging approach is appealing, because it\nallows the data to determine which models are most relevant.\n\\end{linenomath}\n\nMethods have been developed to perform this model averaging using\napproximate-likelihood Bayesian computation (ABC)\n\\citep{Hickerson2006,Huang2011,Oaks2014dpp}.\nHowever, these methods often struggle to detect multiple divergence times\nacross pairs of populations \\citep{Oaks2012, Oaks2014reply} or have little\ninformation to update \\textit{a priori} expectations \\citep{Oaks2014dpp}.\nMore fundamentally, the loss of information inherent to ABC approaches can\nprevent them from discriminating among models\n\\citep{Robert2011,Marin2014,Green2015}.\n\nOne proposed solution is to focus the inference problem on whether or not all\npairs diverged at the same time (i.e., $\\nevents = 1$ versus\n$\\nevents > 1$) \\citep{Hickerson2013}.\nHowever, limiting the inference in this way is often not satisfactory, because\nbiogeographers rarely expect that all of the pairs of populations they wish\nto compare diverged at the same time.\nLimiting ourselves to the hypothesis of a single shared divergence would not\nrecognize situations where only a subset of taxa co-diverged, or where multiple\nshared divergences have occurred.\nThe latter is particularly relevant when multiple landscape changes are known\nto have occurred.\nMore fundamentally,\n\\citet{Papadopoulou2016}\nastutely point out that all of the pairs co-diverging is not the correct null\nhypothesis.\nIf we wish to test for shared divergences, it is more appropriate to consider\nall the pairs diverging independently as the null expectation.\n\nHere, our goal is to develop a new Bayesian model-choice approach to this\nproblem that\nhandles many more genetic loci,\ntakes full advantage of the information in those loci,\nand therefore more reliably\nestimates the number of divergence events and the assignment of taxa to those\nevents.\n% We introduce a new Bayesian model-choice method for inferring\n% shared divergence times across taxa.\nOur method leverages recent analytical work \\citep{Bryant2012} to efficiently\nand directly compute the full-likelihood of divergence models from genomic\ndata.\nBy efficiently using all of the information in the data, the new method is\nfaster,\nmore accurate,\nand more precise\nthan approximate-likelihood methods for\nestimating shared divergences.\nWe introduce the new method and its assumptions, assess its performance with\nsimulated data, and apply it to genomic data from geckos from the Philippine\nIslands.\n\n\n\\section{Methods}\n\n\\subsection{The data}\nWe assume we have genetic data from multiple pairs of populations, and our goal\nis to estimate the time at which the two populations of each pair diverged, and\ncompare these divergence times across the pairs.\nFor each pair of populations that we wish to compare, we assume that we have\ncollected orthologous genetic markers with at most two states.\nWe will refer to these as ``biallelic characters,'' but note that this includes\nconstant characters (i.e., characters for which all the samples\nfrom the two populations share the same state).\nWe follow \\citet{Bryant2012} in referring to the two possible\nstates as ``red'' and ``green.''\nWe assume each character is effectively unlinked, i.e., each marker evolved\nalong a gene tree that is independent of the others, conditional on the\npopulation history.\nExamples include well-spaced, single-nucleotide polymorphisms (SNPs) or\namplified fragment-length polymorphisms (AFLPs).\n\nFor each population and for each marker we sample \\allelecount\ncopies of the locus, \\redallelecount of which are copies of the red\nallele and the remaining $\\allelecount - \\redallelecount$ are\ncopies of the green allele;\n\\redallelecount can range from zero to \\allelecount.\nThus, for each population of a pair, and for each locus, we have a count of the\ntotal sampled gene copies and how many of those are the red allele.\n\n\\ifembed{\n\\input{../../tables/notation.tex}\n}{}\n\nWe will use \\leafallelecounts and \\leafredallelecounts to denote allele counts\nfor a locus from both populations of a pair; i.e., \n$\\leafallelecounts, \\leafredallelecounts = (\\allelecount[1], \\redallelecount[1]), \n(\\allelecount[2], \\redallelecount[2])$\n(Fig.~\\ref{fig:divCartoon}\nand\nTable~\\ref{table:notation}).\nWe will also use ``character pattern'' to refer to $\\leafallelecounts,\n\\leafredallelecounts$.\nWe will use \\comparisondata[i] to denote these counts across all the loci from\npopulation pair $i$.\nIn other words, \\comparisondata[i] is all the genetic data collected from\npopulation pair $i$.\nFinally, we use \\alldata to represent the data across all the pairs of\npopulations of which we wish to compare the divergence times.\nNote, because the pairs are unconnected\n(Fig.~\\ref{fig:divCartoon} \\& S\\ref{fig:dag}),\ndifferent characters can be collected for each pair (i.e., characters do not\nneed to be orthologous across the pairs).\n\n% \\ifembed{\n% \\input{fig-dag.tex}\n% }{}\n\n\\subsection{The model}\n\n\\subsubsection{The evolution of markers}\n\n% We begin unpacking our model by first focusing on a single pair of populations.\nWe assume a finite-sites, continuous-time Markov chain (CTMC) model for the\nevolution of the biallelic characters along a gene tree with branch lengths,\n\\genetree.\nAs the marker evolves along the gene tree, forward in time, there is an\ninstantaneous relative rate \\rgmurate of mutating from the red state to the\ngreen state, and a corresponding relative rate \\grmurate of mutation from green\nto red.\nThe stationary frequency of the red and green state is then\n$\\grmurate / (\\rgmurate + \\grmurate)$\nand\n$\\rgmurate / (\\rgmurate + \\grmurate)$, respectively.\nThus, if given the stationary frequency of the green allele, \\gfreq, we can\nobtain the relative rates of mutation between the two states.\nWe will denote the overall rate of mutation as \\murate.\nIf a mutation rate per site per unit time is given, then branch lengths are in\nabsolute time.\nAlternatively, if $\\murate = 1$, the branch lengths of the gene tree are in\nunits of expected substitutions per site.\nIn such a case, for a given pair of populations, the \\murate is \nredundant, because it can be incorporated into the branch lengths of the gene\ntree.\nHowever, we introduce the notation here, because it will be useful later when\nwe want to allow rate variation among pairs of populations.\n% For now, we will assume $\\murate = 1$ so that the gene tree branch lengths, and\n% time in general, is in units of the expected substitutions per site.\n\n\\subsubsection{The evolution of gene trees}\n\nWe assume that each marker sampled from a pair of populations evolved within a\nsimple ``species'' tree with one ancestral root population that diverged into\ntwo descendant (terminal) branches at time \\comparisondivtime\n(Fig.~\\ref{fig:divCartoon}).\nAgain, if the $\\murate$ is given, \\comparisondivtime is in units of absolute\ntime; however, if $\\murate$ is set to one, time is in units of expected\nsubstitutions per site.\nWe will use\n\\comparisonpopsizes{}\nto denote all three\neffective sizes of a population pair\n(\\epopsize[\\rootpopindex],\n\\epopsize[\\descendantpopindex{1}],\nand \\epopsize[\\descendantpopindex{2}]).\nWe will also use\n\\sptree{}\nas shorthand for the species tree, which comprises the population sizes and\ndivergence time of a pair\n(\\comparisonpopsizes{} and \\comparisondivtime{}).\n\n\\subsubsection{The likelihood}\n\n\\begin{linenomath}\n% Given \\murate, \\gfreq, \\comparisondivtime and \\comparisonpopsizes,\nGiven \\murate, \\gfreq, and \\sptree{},\nthe probability of the observed data at a locus (\\leafallelecounts and\n\\leafredallelecounts), is the probability of the character pattern given the\ngene tree multiplied by the probability of the gene tree given the species\ntree, summed over all possible gene tree topologies and integrated over all\npossible gene tree branch lengths,\n\\begin{equation}\n    \\pr(\\leafallelecounts, \\leafredallelecounts \\given \\sptree, \\murate, \\gfreq)\n    =\n    \\int_{\\genetree}\n    \\pr(\\leafallelecounts, \\leafredallelecounts \\given \\genetree, \\murate, \\gfreq)\n    \\pr(\\genetree, \\murate, \\gfreq \\given \\sptree)\n    \\diff{\\genetree}\n    \\label{eq:markerlikelihood}\n\\end{equation}\n\\citep{Felsenstein1988,Nielsen2001,Rannala2003}.\n% We take advantage of the mathematical work of \\citep{Bryant2012} to\n% analytically integrate over all possible gene trees and character\n% mutational histories along those gene trees.\nWe take advantage of the mathematical work of \\citep{Bryant2012} to\nanalytically integrate over all possible gene trees and all possible character\nsubstitution histories along those gene trees.\nThis allows us to compute the likelihood of the species tree directly from a\nbiallelic character pattern under a coalescent model,\ni.e.,\n$\\pr(\\leafallelecounts, \\leafredallelecounts \\given \\sptree, \\murate, \\gfreq)$.\nWe refer readers to\n\\citet{Bryant2012}\nfor the details of this likelihood and the algorithms to compute it.\n% \\thought{For completeness, should I lay out the math and algorithm for\n%     calculating the likelihood in the supplemental materials?}\n\\end{linenomath}\n\n\\begin{linenomath}\nAssuming independence among loci (conditional on the species tree), we can\ncalculate the probability of \\nloci{} loci given the species tree by\nsimply taking the product over them,\n\\begin{equation}\n    \\pr(\\comparisondata \\given \\sptree, \\murate, \\gfreq)\n    =\n    \\prod_{i=1}^{\\nloci}\n    \\pr(\\leafallelecounts[i], \\leafredallelecounts[i] \\given \\sptree, \\murate, \\gfreq).\n    \\label{eq:comparisonlikelihood}\n\\end{equation}\nFinally, \\jroedit{}{assuming our \\ncomparisons{} pairs are independent,} the\n\\jroedit{}{overall} likelihood \\jroedit{across all of our \\ncomparisons{}\npairs}{} is simply the\nproduct of the likelihood of each pair,\n\\begin{equation}\n    \\pr(\n    \\alldata\n    \\given\n    \\sptrees,\n    \\murates,\n    \\gfreqs)\n    =\n    \\prod_{i=1}^{\\ncomparisons}\n    \\pr(\\comparisondata[i] \\given \\sptree[i], \\murate[i], \\gfreq[i]),\n    \\label{eq:collectionlikelihood}\n\\end{equation}\nwhere\n$\\alldata = \\comparisondata[1], \\comparisondata[2], \\ldots, \\comparisondata[\\ncomparisons]$,\n$\\sptrees = \\sptree[1], \\sptree[2], \\ldots, \\sptree[\\ncomparisons]$,\n$\\murates = \\murate[1], \\murate[2], \\ldots, \\murate[\\ncomparisons]$,\nand\n$\\gfreqs = \\gfreq[1], \\gfreq[2], \\ldots, \\gfreq[\\ncomparisons]$.\n\\end{linenomath}\n\n\\subsubsection{Correcting for excluded constant characters}\n\n\\begin{linenomath}\nIf we exclude constant characters and only analyze variable characters, we need\nto correct the sample space for the excluded constant characters.\nWe can correct the likelihood by simply dividing by the probability of a\nvariable character, which is equal to one minus the probability of a constant\ncharacter,\n\\begin{equation}\n\\begin{split}\n    \\pr(\\leafallelecounts, \\leafredallelecounts \\given \\sptree, \\murate, \\gfreq, \\textrm{variable})\n    & =\n    \\frac{\n        \\pr(\\leafallelecounts, \\leafredallelecounts \\given \\sptree, \\murate, \\gfreq)\n    }{\n        \\pr(\\textrm{variable} \\given \\sptree, \\murate, \\gfreq)\n    } \\\\\n    & =\n    \\frac{\n        \\pr(\\leafallelecounts, \\leafredallelecounts \\given \\sptree, \\murate, \\gfreq)\n    }{\n        1 - \\pr(\\textrm{constant} \\given \\sptree, \\murate, \\gfreq)\n    } \\\\\n    & =\n    \\frac{\n        \\pr(\\leafallelecounts, \\leafredallelecounts \\given \\sptree, \\murate, \\gfreq)\n    }{\n        1 - \\pr(\\leafallelecounts \\textrm{ all red} \\given \\sptree, \\murate, \\gfreq)\n        - \\pr(\\leafallelecounts \\textrm{ all green} \\given \\sptree, \\murate, \\gfreq)\n    }.\n    \\label{eq:variablemarkerlikelihood}\n\\end{split}\n\\end{equation}\nWhen we take the product over loci to get the probability of all the variable\ndata collected from a pair of populations, we correct each character pattern to\nallow for different numbers of sampled gene copies among loci,\n\\begin{equation}\n    \\pr(\\comparisondata \\given \\sptree, \\murate, \\gfreq, \\textrm{variable})\n    =\n    \\prod_{i=1}^{\\nloci}\n    \\frac{\n        \\pr(\\leafallelecounts[i], \\leafredallelecounts[i] \\given \\sptree, \\murate, \\gfreq)\n    }{\n        1 - \\pr(\\leafallelecounts[i] \\textrm{ all red} \\given \\sptree, \\murate, \\gfreq)\n        - \\pr(\\leafallelecounts[i] \\textrm{ all green} \\given \\sptree, \\murate, \\gfreq)\n    }.\n    \\label{eq:variablecomparisonlikelihood}\n\\end{equation}\nThis is a bit different than the correction done in the software SNAPP\n\\citep{Bryant2012}.\nIf we use \\maxleafallelecounts to denote the maximum number of gene copies\nsampled from each population, then the correction in SNAPP is\n\\begin{equation}\n    \\pr_{\\tiny SNAPP}(\\comparisondata \\given \\sptree, \\murate, \\gfreq, \\textrm{variable})\n    =\n    \\frac{\n        \\prod_{i=1}^{\\nloci}\n        \\pr(\\leafallelecounts[i], \\leafredallelecounts[i] \\given \\sptree, \\murate, \\gfreq).\n    }{\n        (1 - \\pr(\\maxleafallelecounts \\textrm{ all red} \\given \\sptree, \\murate, \\gfreq)\n        - \\pr(\\maxleafallelecounts \\textrm{ all green} \\given \\sptree, \\murate, \\gfreq))^{\\nloci}\n    }.\n    \\label{eq:snappvariablecomparisonlikelihood}\n\\end{equation}\nThese are equivalent if the same number of samples are collected across all\nvariable loci for each population (i.e., no missing gene copies), but will\ndeviate if fewer copies are sampled for at least one locus.\nThus, identical likelihoods between SNAPP and our method should not be expected\nwhen analyzing variable-only data.\n\\end{linenomath}\n\n\\subsection{Bayesian inference}\n\n\\begin{linenomath}\nWe can obtain a posterior probability distribution by naively plugging the\nlikelihood in Equation~\\ref{eq:collectionlikelihood} into Bayes' rule,\n\\begin{equation}\n    \\pr(\n    \\sptrees,\n    \\murates,\n    \\gfreqs\n    \\given\n    \\alldata\n    )\n    =\n    \\frac{\n        \\pr(\n        \\alldata\n        \\given\n        \\sptrees, \\murates, \\gfreqs\n        )\n        \\pr(\n        \\sptrees,\n        \\murates,\n        \\gfreqs\n        )\n    }{\n        \\pr(\n        \\alldata\n        )\n    }.\n    \\label{eq:collectionindependentbayesrule}\n\\end{equation}\n% By expanding out the species trees into their component parts, the divergence\n% times and effective population sizes, we get\n% \\begin{equation}\n%     \\pr(\n%     \\comparisondivtimes,\n%     \\collectionpopsizes,\n%     \\murates,\n%     \\gfreqs\n%     \\given\n%     \\alldata\n%     )\n%     =\n%     \\frac{\n%         \\pr(\n%         \\alldata\n%         \\given\n%         \\comparisondivtimes,\n%         \\collectionpopsizes,\n%         \\murates,\n%         \\gfreqs\n%         )\n%         \\pr(\\comparisondivtimes, \\collectionpopsizes, \\murates, \\gfreqs)\n%     }{\n%         \\pr(\n%         \\alldata\n%         )\n%     }.\n%     \\label{eq:collectionindependentbayesruleexpanded}\n% \\end{equation}\nHowever, this assumes all pairs of populations diverged independently, not\nallowing us to learn about shared divergence times.\n% this would be the same as calculating the posterior of each pair\n% separately.\nWhat we want to do is relax this assumption and allow pairs to share divergence\ntimes.\n% We want to estimate how many divergences occurred, and which pairs, if any,\n% shared divergences.\n\\end{linenomath}\n\nLet's use \\divtimemodel to represent the divergence model, which comprises the\ndivergence times---the number of which (\\nevents{}) can range from 1 to\n\\ncomparisons{}---and the mapping of non-overlapping subsets of the population\npairs to these \\nevents{} divergence times.\nWe will separate out \\divtimemodel into two components,\n\\begin{enumerate}\n    \\item the partitioning of the \\ncomparisons{} population pairs to\n        divergence events, which we will denote as \\divtimesets, and\n    \\item the divergence times themselves,\n        $\\divtimes = \\divtime[1], \\ldots, \\divtime[\\nevents]$,\n        the number of which (\\nevents{}) is determined by \\divtimesets.\n\\end{enumerate}\nWe relax the assumption of independent divergence times by treating the number\nof divergence events and the assignment of population pairs to those events as\nrandom variables under a Dirichlet process \\citep{Ferguson1973,\n    Antoniak1974}.\nSpecifically, we use the Dirichlet process as a prior on divergence models,\n$\\divtimemodel \\sim \\dirp(\\basedistribution, \\concentration)$, where\n\\basedistribution is the base distribution of the process and \\concentration is\nconcentration parameter that controls how clustered the process is.\nThe concentration parameter determines the prior probability of\n\\divtimesets\n(the partitioning of the population pairs)\nand the base distribution determines the prior probability of the divergence\ntime of each subset.\n\n\\begin{linenomath}\nUnder the Dirichlet process prior, the posterior becomes\n\\begin{equation}\n    \\pr(\n    \\concentration,\n    \\divtimemodel,\n    \\collectionpopsizes,\n    \\murates,\n    \\gfreqs\n    \\given\n    \\alldata,\n    \\basedistribution\n    )\n    =\n    \\frac{\n        \\pr(\n        \\alldata\n        \\given\n        \\divtimemodel,\n        \\collectionpopsizes,\n        \\murates,\n        \\gfreqs\n        )\n        \\pr(\\divtimemodel \\given \\concentration, \\basedistribution)\n        \\pr(\\concentration)\n        \\pr(\\collectionpopsizes)\n        \\pr(\\murates)\n        \\pr(\\gfreqs)\n    }{\n        \\pr(\n        \\alldata,\n        \\basedistribution\n        )\n    },\n    \\label{eq:bayesrule}\n\\end{equation}\nwhere\n\\collectionpopsizes\nis the collection of the effective population sizes (\\comparisonpopsizes{})\nacross all of the pairs.\nBy expanding the divergence model\n(\\divtimemodel)\ninto the partitioning of the population pairs to divergence events\n(\\divtimesets)\nand the times of those events \n(\\divtimes),\nwe get\n\\begin{equation}\n    \\pr(\n    \\concentration,\n    \\divtimes,\n    \\divtimesets,\n    \\collectionpopsizes,\n    \\murates,\n    \\gfreqs\n    \\given\n    \\alldata,\n    \\basedistribution\n    )\n    =\n    \\frac{\n        \\pr(\n        \\alldata\n        \\given\n        \\divtimes,\n        \\divtimesets,\n        \\collectionpopsizes,\n        \\murates,\n        \\gfreqs\n        )\n        \\pr(\\divtimesets \\given \\concentration)\n        \\pr(\\divtimes \\given \\divtimesets, \\basedistribution)\n        \\pr(\\concentration)\n        \\pr(\\collectionpopsizes)\n        \\pr(\\murates)\n        \\pr(\\gfreqs)\n    }{\n        \\pr(\n        \\alldata,\n        \\basedistribution\n        )\n    }.\n    \\label{eq:bayesruleexpanded}\n\\end{equation}\n\\end{linenomath}\n\n\\subsubsection{Priors}\n\n% \\paragraph{Prior on divergence models}\n% As mentioned above, we treat the number of divergence events and the assignment\n% of population pairs to those events as random variables under a Dirichlet\n% process prior \\citep{Ferguson1973, Antoniak1974}.\n\n\\begin{linenomath}\n\\paragraph{Prior on the concentration parameter}\nGiven a single parameter, \\concentration, the Dirichlet process determines the\nprior probability of all the possible ways the \\ncomparisons{} pairs of\npopulations can be partitioned to $\\nevents = 1, 2, \\ldots \\ncomparisons$\ndivergence events.\nGiven \\concentration, the prior probability that two pairs of populations, $i$\nand $j$ (assuming $i \\neq j$), share the same divergence time is\n\\begin{equation}\n    \\pr(\\comparisondivtime[i] = \\comparisondivtime[j] \\given \\concentration)\n    =\n    \\frac{1}{1 + \\concentration}\n\\end{equation}\nThis illustrates that when \\concentration is small, the process tends to be\nmore clumped, and as it increases, the process tends to favor more independent\ndivergence times.\nOne option is to simply fix the concentration parameter to a particular value,\nwhich is likely sufficient when the number of pairs is small.\nAlternatively, we allow a hierarchical approach to accommodate uncertainty in\nthe concentration parameter by specifying a gamma distribution as a prior on\n\\concentration \\citep{Escobar1995,Heath2011}.\n\\end{linenomath}\n\n\\paragraph{Prior on the divergence times}\nGiven the partitioning of the pairs to divergence events, we use a gamma\ndistribution for the prior on the time of each event,\n$\\divtime \\given \\divtimesets \\sim \\distgamma(\\cdot, \\cdot)$.\nThis is the base distribution (\\basedistribution) of the Dirichlet process.\n\n\\paragraph{Prior on the effective population sizes}\nFor the two descendant populations of each pair, we use a gamma distribution as\nthe prior on the effective population sizes.\nFor the root population, we use a gamma distribution on the effective\npopulation size \\emph{relative} to the mean size of the two descendant\npopulations, which we denote as \\rootrelativepopsize.\nFor example, a value of one would mean the root population size is equal to \n$(\\epopsize[\\descendantpopindex{1}] + \\epopsize[\\descendantpopindex{2}]) / 2$.\nThe goal of this approach is to allow more informative priors on the root\npopulation size; we often have stronger prior expectations for the relative\nsize of the ancestral population than the absolute size.\nThis is important, because the effective size of the ancestral population is a\ndifficult nuisance parameter to estimate and can be strongly correlated with\nthe divergence time.\nFor example, if the divergence time is so old such that all the gene copies\nof a locus coalesce within the descendant populations, the locus\nprovides very little information about the size of the ancestral\npopulation.\nAs a result, a larger ancestral population and more recent divergence will have\na very similar likelihood to a small ancestral population and an older\ndivergence.\nThus, placing more prior density on reasonable values of the ancestral\npopulation size can help improve the precision of divergence-time estimates.\n\n\\paragraph{Prior on mutation rates}\nIn the model presented above, for each population pair, the divergence time\n(\\divtime) and mutation rate (\\murate) are inextricably linked.\nFor a single pair of populations, if little is known about the mutation rate,\nthis problem is easily solved by setting it to one ($\\murate[1] = 1$) such\nthat time is in units of expected substitutions per site and the effective\npopulation sizes are scaled by \\murate.\nHowever, what about the second pair of populations for which we wish to compare\nthe divergence time to the first?\nBecause the species trees in our model are disconnected\n(Fig.~\\ref{fig:divCartoon} \\& S\\ref{fig:dag}),\nwe cannot learn about\nthe relative rates of mutation across the population pairs from the data.\nAs a result, we need strong prior information about the relative rates of\nmutation across population pairs for this model to work.\n\nIf the second pair of populations is closely related to the first, and shares a\nsimilar life history, we could assume they share the same mutation rate and\nset the mutation rate of the second pair to one as well ($\\murate[1] = \\murate[2] = 1$).\nAlternatively, we could relax that assumption and put a prior on \\murate[2].\nHowever, this should be a strongly informative prior.\nPlacing a weakly informative prior on \\murate[2] would mean that we can no\nlonger estimate its divergence time relative to the first pair,\nwhich is our primary goal.\nSo, while it is possible to incorporate uncertainty in relative mutation rates,\nit is important to keep in mind that the data cannot inform these parameters,\nand thus the prior uncertainty in rates will be directly reflected in the\nposterior of divergence times.\n\n\\paragraph{Prior on the equilibrium-state frequency}\nOur method allows for a beta prior to be placed on the frequency of the green\nallele for each pair of populations,\n$\\gfreq[i] \\sim \\textrm{Beta}(\\cdot, \\cdot)$.\nHowever, if using SNP data, we advise fixing the frequency of the red and green\nstates to be equal (i.e., $\\gfreq = 0.5$).\nThe reason for this is that there is no natural way of re-coding four-state\nnucleotides to two states, and so the relative transition rates, \\rgmurate and\n\\grmurate, are not biologically meaningful.\nThere will always be arbitrariness associated with how one decides to perform\nthis re-coding, and unless $\\gfreq = 0.5$, this arbitrariness will affect the\nlikelihood and results.\nConstraining \\gfreq to 0.5 makes the CTMC model a two-state analog of the\n``JC69'' model \\citep{JC1969}.\nHowever, if the genetic markers are naturally biallelic, the frequencies of the\ntwo states can be meaningfully estimated, making the model a two-state general\ntime-reversible model \\citep{Tavare1986}.\n\n% \\input{mcmc.tex}\n\\subsubsection{Approximating the posterior with MCMC}\n\nWe use Markov chain Monte Carlo (MCMC) algorithms to \\jroedit{numerically\napproximate}{sample (approximately) from} the joint posterior in\nEquation~\\ref{eq:bayesruleexpanded}.\nTo update the divergence model (\\divtimemodel) during the chain, we use the\nGibbs sampling algorithm (Algorithm 8) of \\citet{Neal2000}.\nWe also use univariate Metropolis-Hastings algorithms\n\\citep{Metropolis1953,Hastings1970} to update each parameter of the model\nduring the MCMC.\nTo improve mixing of the chain when there are strong correlations between\ndivergence times, effective population sizes, and mutation rates we use\nmultivariate Metropolis-Hastings algorithms.\n\\jroedit{}{The details of these multivariate moves can be found in\nAppendix~\\ref{appendix:mcmc}.}\n\n\\subsection{Software implementation}\nThe method outlined above is implemented in the open-source software package,\n\\ecoevolity, written in the \\cpp language.\nThe source code is freely available from\n\\url{https://github.com/phyletica/ecoevolity}, and documentation is available\nat\n\\url{http://phyletica.org/ecoevolity/}.\nThe software package is accompanied by an extensive test suite, which, among\nother aspects,\nvalidates that the likelihood code returns the same values\nas\nSNAPP \\citep{Bryant2012},\nand all of our MCMC proposals sample from the expected prior distribution\nwhen data are ignored.\n\nThe \\ecoevolity package includes four programs:\n\\begin{enumerate}\n    \\item \\ecoevolity for performing Bayesian inference under the\n        model described above.\n    \\item \\sumcoevolity for summarizing posterior samples collected by\n        \\ecoevolity and performing simulations to calculate Bayes factors for\n        all possible numbers of divergence events.\n    \\item \\simcoevolity for simulating biallelic characters under the model\n        described above.\n    \\item \\dpprobs for Monte Carlo approximations of probabilities under the\n        Dirichlet process; this can be useful for choosing a prior on the\n        concentration parameter.\n\\end{enumerate}\nWe have also developed a Python package, \\pycoevolity, to help with\npreprocessing data and summarizing posterior samples collected by \\ecoevolity.\nThis includes assessing MCMC chain stationarity and convergence and plotting\nposterior distributions.\nThe source code for \\pycoevolity is available at\n\\url{https://github.com/phyletica/pycoevolity}.\n\nAll of our analyses were performed with\nVersion 0.1 \n(commit 1d688a3)\nof the \\ecoevolity software package.\nThe \\timerootsizemixer algorithm implemented in this version of the software\nonly updates one ancestral population size per proposal.\nIn Version 0.2 (commit 884780e), the default behavior is for the\n\\timerootsizemixer proposal to update the ancestral population size for all\nother pairs associated with the same divergence time (see above).\nWhile this tends to improve mixing slightly, it does not change the results we\npresent here in a meaningful way.\nOur results can be reproduced exactly with Version 0.1.\nTo help facilitate reproducibility, a detailed history of this\nproject is available at\n\\url{https://github.com/phyletica/ecoevolity-experiments},\nincluding all of the data and scripts needed to produce our results.\n\n\n\\subsection{Analyses of simulated data}\n\n\\subsubsection{Validation analyses}\nOur first step to validate the new method was to verify that it behaves as\nexpected when the model is correct (i.e., data are simulated and analyzed under\nthe same model).\nWe used the \\simcoevolity tool from the \\ecoevolity package, which simulates\ndata under the model described above.\nAll data were simulated under the following settings:\n\\begin{enumerate}\n    \\item $\\ncomparisons = 3$\n    \\item $\\allelecount = 10$ (i.e., 10 alleles---5 diploid\n        individuals---sampled from each population)\n    \\item $\\concentration = 1.414216$, which corresponds with a prior mean of\n        $\\nevents = 2$ divergence events\n    \\item $\\divtime \\sim \\dexponential{0.01}$\n    \\item $\\gfreq = 0.5$\n    \\item $\\murate = 1$\n\\end{enumerate}\nWe simulated data under five different settings for the effective population\nsizes.\nThe first setting was an idealized situation where all population sizes were\nknown and equal,\n$\\epopsize[\\rootpopindex] = \n\\epopsize[\\descendantpopindex{1}] =\n\\epopsize[\\descendantpopindex{2}] = 0.002$.\nThe four remaining scenarios differed in their distribution on the relative\neffective size of the root population:\n\\begin{enumerate}\n    \\item $\\rootrelativepopsize \\sim \\dgamma{2}{1}$\n    \\item $\\rootrelativepopsize \\sim \\dgamma{10}{1}$\n    \\item $\\rootrelativepopsize \\sim \\dgamma{100}{1}$\n    \\item $\\rootrelativepopsize \\sim \\dgamma{1000}{1}$\n\\end{enumerate}\nFor these four scenarios, the descendant populations were distributed as\n\\dgamma{5}{0.002}.\nThe most difficult nuisance parameter to estimate for a pair of populations is\nthe root population size, which can be correlated with the parameter of\ninterest, the divergence time.\nThus, our choice of simulation settings is designed to assess how uncertainty\nin the root population size affects inference.\n\nUnder each of the five scenarios we simulated 500 \\datasets of 100,000\ncharacters and 500 \\datasets of 500,000 characters.\nThis includes constant characters; the mean number of variable SNPs was\napproximately 5,500 and 27,500, respectively.\nWe then analyzed all 5,000 simulated \\datasets in \\ecoevolity both with and\nwithout constant characters included.\nFor all analyses, the prior for each parameter matched the distribution\nthe true value was drawn from when the data were simulated.\nFor analyses where \n$\\epopsize[\\rootpopindex] = \n\\epopsize[\\descendantpopindex{1}] =\n\\epopsize[\\descendantpopindex{2}] = 0.002$,\nwe ran\nthree independent MCMC chains for 37,500 generations, sampling every\n25th generation.\nFor all other analyses, we ran the three chains for 75,000 generations,\nsampling every 50th generation.\nAs a result, we collected 4503 samples for each analysis (1501 samples from\neach chain, including the initial state).\n\nIn order to assess the frequentist behavior of the posterior probabilities of\ndivergence models inferred by \\ecoevolity, we simulated an additional\n20,000 \\datasets of 100,000 characters under the setting where\n$\\rootrelativepopsize \\sim \\dgamma{100}{1}$.\nAll 20,500 \\datasets were analyzed with \\ecoevolity and binned based on the\ninferred posterior probability that $\\nevents{} = 1$.\nThe mean posterior probability that $\\nevents{} = 1$ for each bin was plotted\nagainst the proportion of \\datasets within the bin for which the true\ndivergence model was $\\nevents{} = 1$;\nthe latter approximates the true probability that $\\nevents{} = 1$.\nIf the new method is unbiased, in a frequentist sense, the inferred posterior\nprobabilities that $\\nevents{} = 1$ within a bin should approximately equal the\nproportion of the \\datasets for which that is true\n\\citep{Huelsenbeck2004,Oaks2012,Oaks2014dpp}.\n\n\\subsubsection{Assessing the effect of linked characters}\nThe characters of most \\datasets being collected by high-throughput technologies\ndo not all evolve along independent gene trees.\nMost consist of many putatively unlinked loci that each comprise sequences of\nlinked nucleotides.\nFor example, ``RADseq'' and ``sequence capture'' techniques generate thousands\nof loci that are approximately 50--300 nucleotides in length.\nThis creates a question when using methods like \\ecoevolity that assume each\ncharacter is independent:\nIs it better to violate the assumption of unlinked characters and use all of\nthe data, or throw away much of the data to avoid linked characters?\n\nTo better adhere to the unlinked-character assumption, we could retain only a\nsingle site per locus.\nHowever, this results in a very large loss of data.\nFurthermore, to try and maximize the informativeness of the retained\ncharacters, most researchers retain only one \\emph{variable} character per\nlocus.\nWhile this can be corrected for (see\nEquation~\\ref{eq:variablecomparisonlikelihood}), it still results in the loss\nof a very informative component of the data: The proportion of variable\ncharacters.\nBefore throwing away so much information, we should determine whether\nit is in our best interest.\nIn other words, does keeping all of the data and violating the assumption of\nunlinked characters result in better or worse inferences than throwing out much\nof our data?\n\nTo address this question, \nwe simulated \\datasets composed of loci of linked sites that were 100, 500, and\n1000 characters long.\nThe characters for each locus were simulated along the same gene tree (i.e., no\nintra-locus recombination).\nSimulated \\datasets were analyzed with \\ecoevolity in one of three ways:\n(1) All characters were included,\n(2) only variable characters were included,\nand\n(3) only a maximum of one variable character per locus was included.\nOnly the last option avoids violating the assumption of unlinked characters,\nbut throws out the most data.\n\nFor all three locus lengths, we simulated 500 \\datasets with a total of 100,000\nand 500,000 characters.\nThe settings of the simulations performed with \\simcoevolity, and subsequent\nanalyses with \\ecoevolity, correspond with the validation analyses described\nabove where the relative size of the root population was distributed as\n\\dgamma{100}{1}.\nFurthermore, to assess the affect of linked characters on the posterior\nprobabilities of divergence models, we simulated an additional 10,000 \\datasets\nwith 1,000, 100-character loci (100,000 total characters each).\nAs described above, to assess the frequentist behavior of the inferred\nposterior probabilities, we binned the results of the analyses of these 10,500\n\\datasets based on the posterior probability that $\\nevents{} = 1$ and plotted\nthe mean of each bin against the approximated true probability that $\\nevents{}\n= 1$.\n\n\\subsubsection{Assessing the effect of missing data}\nThe method should be robust to missing data, because it is simply treated as a\nsmaller sample of gene copies from a particular population for a particular\nlocus.\nBecause each character is assumed to have evolved along a coalescent\ngene tree, the identity of each gene copy within a population does not matter.\nThus, some loci having fewer sampled gene copies from some populations should\nresult in more variance in parameter estimates, but is not expected to create\nbias.\nTo confirm this behavior, we simulated \\datasets with different probabilities of\nsampling each gene copy.\nSpecifically, we simulated \\datasets for which the probability of sampling each\ngene copy was 90\\%, 75\\%, or 50\\%, which resulted in \\datasets with\napproximately 10\\%, 25\\%, or 50\\% missing data.\nFor each sampling probability, we simulated 100 \\datasets with 500,000 unlinked\ncharacters; the settings were the same as described for the validation analyses\nabove where $\\rootrelativepopsize \\sim \\dgamma{100}{1}$.\n\n\\subsubsection{Assessing the effect of biases in character-pattern acquisition}\nWhen analyzing the \\spp{Gekko} data (see below), we observed large\ndiscrepancies in the estimated divergence times depending on whether or not the\nconstant characters were removed from the analysis.\nThis was not observed in the analyses of simulated data, because the likelihood\nis appropriately corrected for the excluded constant characters.\nThis suggests that there are additional character-pattern acquisition biases in\nthe empirical data, for which are our method cannot correct.\nSuch acquisition biases have been documented during the \\textit{de novo}\nassembly of RADseq loci \\citep{Harvey2015,Linck2017}.\n\nThe loss of rare alleles during the acquisition and assembly of the data could\nexplain the much larger divergence times estimated from the empirical data when\nconstant characters are removed.\nAfter the constant characters, the rare alleles are ``next in line'' to inform\nthe model that the population divergence was recent.\nIf these patterns are being lost during data acquisition and assembly, and not\naccounted for in the likelihood calculation, this should create an upward bias\nin the divergence time estimates.\n\nTo explore whether data acquisition bias can explain the discrepancy we\nobserved for the \\spp{Gekko} data, we simulated \\datasets where the probability\nof sampling singleton character patterns (i.e., one gene copy is different from\nall the others) was 80\\%, 60\\%, and 40\\%.\nFor each, we simulated and analyzed 100 \\datasets with 500,000 unlinked\ncharacters; the settings were the same as described for the validation analyses\nabove where\n$\\rootrelativepopsize \\sim \\dgamma{100}{1}$.\n\n\n\\subsubsection{Comparison to ABC methods}\nWe wanted to compare the performance of the new method to the existing\napproximate-likelihood Bayesian computation (ABC) method \\dppmsbayes \n\\citep{Oaks2014dpp}.\nIn order to do this, we had to simulate relatively small \\datasets that the ABC\nmethod could handle in a reasonable amount of time.\nAccordingly, we simulated \\datasets with 200 loci, each with 200 linked\ncharacters (40,000 total characters).\nFor simulations and analyses of both \\ecoevolity and \\dppmsbayes, the settings\nwere\n\\begin{enumerate}\n    \\item $\\ncomparisons = 3$\n    \\item $\\allelecount = 10$ (i.e., 10 alleles---5 diploid\n        individuals---sampled from each population)\n    \\item $\\concentration = 1.414216$, which corresponds with a prior mean of\n        $\\nevents = 2$ divergence events\n    \\item $\\divtime \\sim \\dgamma{2}{0.05}$\n    \\item $\\murate = 1$\n    % \\item $\\epopsize[\\descendantpopindex{}] \\sim \\dgamma{5}{0.002}$\n\\end{enumerate}\n% For analyses with \\dppmsbayes, the effective size of the ancestral population,\n% \\epopsize[\\rootpopindex], was also distributed as \\dgamma{5}{0.002}, whereas\n% for \\ecoevolity, the relative effective size of the ancestral population,\n% \\rootrelativepopsize, was distributed as \\dgamma{100}{1};\n% the marginal prior on \\epopsize[\\rootpopindex] induced by the latter is similar\n% to the former.\n\\jroedit{}{For \\dppmsbayes,\nwe placed a \\dgamma{5}{0.008} distribution on $4\\epopsize{}\\murate{}$\nfor the ancestral and both descendant populations of each pair.\nAccordingly, for \\ecoevolity, we used a \\dgamma{5}{0.002} distribution on\n$\\epopsize{}\\murate{}$ for both descendant populations of each pair.\nFor the relative effective size of the ancestral population in \\ecoevolity,\nwe used a \\dgamma{100}{1} distribution;\nthis induces a marginal prior distribution on \\epopsize[\\rootpopindex] similar\nto that used for \\dppmsbayes.\n}\nFor analyses with \\dppmsbayes, we assumed a Jukes-Cantor model of nucleotide\nsubstitution, whereas for the \\ecoevolity, we assumed the two-state equivalent\n(i.e., $\\gfreq = 0.5$).\n\nEach method was applied to 500 \\datasets simulated under its own model.\nThus, there were no model violations, except for the new method, for which the\nassumption of unlinked characters was violated by the 200-character loci.\nFor the analysis of each simulated \\dataset with \\ecoevolity, three independent\nMCMC chains were run for 75,000 generations, sampling every 50th generation.\nFor the \\dppmsbayes analyses, 500,000 samples were simulated from the joint\nprior distribution.\nTo determine which samples to retain for the approximate posterior, for each\npair we used the mean of four summary statistics across all the loci:\n\\begin{enumerate}\n    \\item The number of segregating sites \\citep[$\\theta_W$;][]{Watterson1975},\n    \\item the average number of pairwise differences across all gene copies\n        \\citep[$\\pi$;][]{NeiLi1979},\n    \\item the net number of pairwise differences between the two populations\n        \\citep[Equation 25 in][]{NeiLi1979}, and\n    \\item the standard deviation in the difference between $\\pi$ and $\\theta_W$\n        \\citep{Tajima1989}.\n\\end{enumerate}\nAfter standardizing these statistics, the 2,000 prior samples that were closest\nto the same statistics calculated from a simulated \\dataset were retained as\nthe approximate posterior.\n\n\\subsection{Empirical application}\nPrevious methods for estimating shared divergence times often over-cluster taxa\n\\citep{Oaks2012,Oaks2014reply}.\nThus, a good empirical test of the new method would be pairs of populations\nthat we expect diverged independently of one another.\nWe analyzed restriction-site-associated sequence (RADseq) data from four pairs\nof populations of \\spp{Gekko} lizards\n(Table~\\ref{table:gekkocomparisons}).\nEach pair of populations inhabit two different oceanic islands in the\nPhilippines that were never connected during lower sea levels of glacial\nperiods.\nBecause these islands were never connected, the divergence between the\npopulations of each pair is likely due to over-water dispersal, the timing of\nwhich should be idiosyncratic to each pair.\n\\jroedit{}{We used previous phylogenetic results based on different genetic\ndata \\citep{Siler2012,Siler2014kikuchii} to help ensure that the pairs are\nindependent (i.e., they do not overlap each other in the phylogeny of\n\\emph{Gekko}).}\n   \n\n\\ifembed{\n\\input{../../tables/gekko-comparisons.tex}\n}{}\n\nWe analyzed the data with and without the constant characters.\nAlso, there were a small number of sites that had more than two nucleotides\nrepresented\n(Table~\\ref{table:gekkocomparisons}),\nwhich cannot be handled directly by our model of biallelic characters.\nWe explored two ways of handling these sites:\n(1) excluding them, and\n(2) coding the first nucleotide in the alignment as 0 (``green''), and all\nother nucleotides for that site as 1 (``red'').\nThus, between including/excluding the constant sites and removing/re-coding the\npolyallelic characters, we analyzed four versions of the RADseq data.\n\nTo be conservative in assessing the ability of the new method to distinguish\ndivergence times among the pairs, we set $\\concentration = 0.44$, which places\n50\\% of the prior probability on one divergence event (i.e., all four pairs\nsharing the same divergence).\nFurthermore, to assess the sensitivity of the results to \\concentration, we\nalso used $\\concentration = 3.77$, which corresponds with a prior mean number\nof divergence events of three.\nOther settings that were shared by all analyses of the \\spp{Gekko} RADseq data\ninclude:\n\\begin{itemize}\n    \\item $\\epopsize[\\descendantpopindex{}] \\sim \\dgamma{4}{0.004}$\n    \\item $\\rootrelativepopsize \\sim \\dgamma{100}{1}$\n    \\item $\\gfreq = 0.5$\n    \\item $\\murate = 1$ for all four pairs\n\\end{itemize}\n\nThe ABC methods of inferring shared divergence events are very sensitive to the\nprior on divergence times\n\\citep{Oaks2012,Hickerson2013,Oaks2014reply,Oaks2014dpp}.\nTo assess whether results of our new method are also sensitive to the\nprior on divergence times, we analyzed the \\datasets that included constant\ncharacters under the following priors:\n\\begin{enumerate}\n    \\item $\\divtime \\sim \\dexponential{0.005}$\n    \\item $\\divtime \\sim \\dexponential{0.01}$\n    \\item $\\divtime \\sim \\dexponential{0.05}$\n    \\item $\\divtime \\sim \\dexponential{0.1}$\n    \\item $\\divtime \\sim \\dexponential{0.2}$\n\\end{enumerate}\nFor the two versions of the \\spp{Gekko} data that lacked the constant\ncharacters, we used the following priors:\n\\begin{enumerate}\n    \\item $\\divtime \\sim \\dexponential{0.01}$\n    \\item $\\divtime \\sim \\dexponential{0.05}$\n    \\item $\\divtime \\sim \\dexponential{0.1}$\n    \\item $\\divtime \\sim \\dexponential{0.2}$\n    \\item $\\divtime \\sim \\dexponential{0.5}$\n\\end{enumerate}\n\nFor all analyses, we ran 10 independent MCMC chains for 150,000 generations,\nsampling every 100th generation.\nConvergence and mixing of the chains was assessed by the potential scale\nreduction factor\n\\citep[PSRF; the square root of Equation 1.1 in][]{Brooks1998}\nand effective sample size\n\\citep[ESS;][]{Gong2014}\nof the log-likelihood and all parameters.\nWe also inspected the chains visually with the program Tracer version 1.6\n\\citep{Tracer16}.\n\nThe collection and assembly of the \\spp{Gekko} RADseq data are detailed by\n\\citet{Oaks2018paic}.\nThe sequence reads are available on the NCBI Sequence Read Archive\n\\jroedit{}{(Bioproject PRJNA486413, SRA Study SRP158258)}\nand the assembled data matrices are available in our project repository\n(\\url{https://github.com/phyletica/ecoevolity-experiments}).\n\n\\subsubsection{Empirical comparison to ABC}\nThe \\spp{Gekko} \\dataset is much too large to analyze with existing ABC\nmethods for estimating co-divergences.\nIn order to compare the results of the new full-likelihood method, \\ecoevolity,\nto the ABC method, \\dppmsbayes, we randomly sampled (without replacement) 200\nloci from three of the pairs of \\spp{Gekko} populations.\nThe prior settings we used for the \\ecoevolity analysis of this reduced\n\\dataset was:\n\\begin{itemize}\n    \\item $\\concentration = 1.414216$, which corresponds with a prior mean\n        number of divergence events of two\n    \\item $\\divtime \\sim \\dexponential{0.1}$\n    \\item $\\epopsize[\\descendantpopindex{}] \\sim \\dgamma{5}{0.002}$\n    \\item $\\rootrelativepopsize \\sim \\dgamma{100}{1}$\n    \\item $\\gfreq = 0.5$\n    \\item $\\murate = 1$ for all three pairs\n\\end{itemize}\n\\jroedit{}{We used the same settings for the \\dppmsbayes analysis, except to\naccount for the different parameterization of effective population sizes, we\nused a\n\\dgamma{5}{0.008}\nprior on\n$4\\epopsize{}\\murate{}$\nfor the ancestral and descendant populations.\n}\n\nFor the \\ecoevolity analysis, we ran five independent MCMC chains for 12,000\ngenerations, sampling every 10th generation.\nWe assessed convergence and mixing using the same methods as we did for the\nanalyses of the full \\spp{Gekko} \\dataset, described above.\nFor the \\dppmsbayes analysis, we simulated 500,000 samples from the joint\nprior, and to get a sample from the approximate posterior, we retained the\n5,000 samples with summary statistics most similar to those calculated\nfrom the reduced \\spp{Gekko} \\dataset.\nFor each pair, we used two summary statistics:\nThe average number of pairwise differences across all gene copies ($\\pi$) and\nbetween the gene copies from the two populations ($\\pi_b$) \\citep{NeiLi1979}.\nFor each pair, we used the mean of both statistics across the 200 loci.\n\\jroedit{}{The results from simulated data demonstrate that additional\nstatistics that summarize information about effective population sizes are not\ninforming the ABC method (see below).}\n\n\n\\section{Results}\n\n\\subsection{Analyses of simulated data}\n\n\\subsubsection{Validation analyses}\n\nWhen there is no model misspecification, our new method has the desired\nfrequentist behavior wherein 95\\% of the time the true value of a parameter\nfalls within the 95\\% credible interval.\nWe see this for\ndivergence times\n(Fig.~\\ref{fig:valdivtimes})\nand the effective sizes of\ndescendant\n(Fig.~S\\ref{fig:valleafsizes})\nand ancestral\n(Fig.~S\\ref{fig:valrootsizes})\npopulations.\nOur results also show that the estimated posterior probability of the single\ndivergence model ($\\nevents{} = 1$) mirrors the probability that the model\nis correct \n(Fig.~\\ref{fig:valpostprobs}).\nWe see the same behaviors whether or not the constant characters are excluded,\ndemonstrating that our likelihood correction for excluded constant\ncharacters is working correctly\n(Equation~\\ref{eq:variablecomparisonlikelihood}).\n\n\\ifembed{\n\\input{fig-val-div-times.tex}\n\n\\input{fig-val-post-probs.tex}\n}{}\n\nAs expected, the precision of divergence time and population size estimates is\ngreater when the constant characters are included and when there is greater\nprior information about the ancestral population size\n(Fig.\\ \\ref{fig:valdivtimes}, S\\ref{fig:valleafsizes}, \\&\nS\\ref{fig:valrootsizes}).\nThe increase in precision associated with the fivefold increase in the number\nof sampled characters (100k to 500k) is relatively modest (Fig.\\ \n\\ref{fig:valdivtimes}, S\\ref{fig:valleafsizes}, \\& S\\ref{fig:valrootsizes}).\n% suggesting that the benefit of collecting more characters begins to plateau\n% when \\datasets are small relative to the number of characters commonly\n% collected via modern high-throughput sequencing technologies (i.e., the\n% simulated 100k \\datasets had only 5,500 SNPs on average).\nRetaining the constant characters results in a much larger increase in\nprecision than collecting five times more characters.\n\nThe true \\jroedit{}{model and} number of divergence events is included in the\n95\\% credible set greater than \\jroedit{98\\%}{97\\%} of the time for all the\nsimulation conditions\n(Fig.~\\ref{fig:valnevents} \\jroedit{}{\\& S\\ref{fig:valmodels}}).\nThe frequency at which the correct number of events has the largest posterior\nprobability, and the median posterior probability of the correct number of\nevents,\nincreases when constant characters are retained and as prior information about\nthe ancestral population size increases \n(Fig.~\\ref{fig:valnevents}).\n\\jroedit{}{We see the same patterns for inferring the correct divergence model\n(Fig.~S\\ref{fig:valmodels}).\n}\nAs with the parameter estimates, the performance increase associated with the\nincrease from 100k to 500k sampled characters is moderate; retaining the\nconstant characters has a much larger effect\n(Fig.~\\ref{fig:valnevents} \\jroedit{}{\\& S\\ref{fig:valmodels}}).\nWhen constant characters are used, the median posterior\nprobability of the correct number of divergence events is high (over 0.89\nfor all simulation conditions; \nFig.~\\ref{fig:valnevents}).\n\\jroedit{}{Likewise, the median posterior probability of the correct divergence\nmodel is greater than 0.887 across all simulation conditions when constant\ncharacters are used\n(Fig.~S\\ref{fig:valmodels}).}\n\n\\ifembed{\n\\input{fig-val-nevents.tex}\n}{}\n\nFor the \\datasets simulated with 100,000 and 500,000 characters, the number of\nvariable characters ranged from\n515--21,676 \nand\n4,670--105,373,\nrespectively, with an average of approximately\n5,500\nand \n27,500 variable characters, respectively\n(Fig.\\ S\\ref{fig:valnumberofvariablesites100k} \\&\nS\\ref{fig:valnumberofvariablesites500k}).\nAs expected, the variance in the number variable characters increases with the\nvariance in the prior distribution of the relative effective size of the root\npopulation\n(Fig.\\ S\\ref{fig:valnumberofvariablesites100k} \\&\nS\\ref{fig:valnumberofvariablesites500k}).\n\nThe MCMC chains for all analyses converged very quickly;\nwe conservatively removed the first 401 samples, resulting in 3300 samples from\nthe posterior (1100 samples from three chains) for each analysis.\nTo assess convergence and mixing, we plotted histograms of the potential scale\nreduction factor across the three independent chains and the effective sample\nsize for the log-likelihood and divergence times\n(Fig.\\ S\\ref{fig:valpsrflikelihood}, S\\ref{fig:valpsrfdivtimes},\nS\\ref{fig:valesslikelihood}, \\& S\\ref{fig:valessdivtimes}).\nMixing was poorer when there was more prior uncertainty in the root population\nsize\n(Fig.\\ S\\ref{fig:valesslikelihood} \\& S\\ref{fig:valessdivtimes}).\nHowever, given the expected frequentist behavior for how often the true\nparameter values were contained within the 95\\% confidence intervals (Fig.\\ \n\\ref{fig:valdivtimes}, S\\ref{fig:valleafsizes}, \\& S\\ref{fig:valrootsizes}),\nand the weak relationship between the ESS and estimation error\n(Fig.~S\\ref{fig:valessvserror}),\nwe do not expect MCMC mixing had a large effect on our simulation results under\nthe most extreme levels of uncertainty in the root population size that we\nsimulated.\n\n\n\n\\subsubsection{Assessing the effect of linked characters}\n\nThe accuracy of divergence time estimates did not appear to be affected by the\nmodel violation of linked characters\n(Fig.\\ \\ref{fig:linkagedivtimes500k}\n\\&\nS\\ref{fig:linkagedivtimes100k}).\nHowever,\nas the length of loci increases, we do see an underestimation\nof posterior uncertainty (i.e., the \ntrue divergence time is contained within the 95\\% credible interval\nless frequently than 95\\% of the time;\nFig.\\ \\ref{fig:linkagedivtimes500k}\n\\&\nS\\ref{fig:linkagedivtimes100k}).\nThis makes sense given that there is less coalescent variation in the data than\nthe model expects if all the characters had evolved along independent gene\ntrees.\nImportantly, this effect of underestimating posterior uncertainty is small\nfor \\datasets with 100bp loci, suggesting this violation of the model has little\nimpact for high-throughput \\datasets with short loci, like those collected via\nRADseq.\nAs expected, analyzing only one variable site per locus removes this underestimation\nof posterior uncertainty\n(see the last row of Fig.\\ \\ref{fig:linkagedivtimes500k}\n\\&\nS\\ref{fig:linkagedivtimes100k}),\nbut at a large cost of much greater posterior uncertainty in parameter\nestimates due to the loss of data.\nWe see the same behavior for estimating the effective sizes of the ancestral\nand descendant populations\n(Fig.\\ S\\labelcref{fig:linkageleafsizes100k,fig:linkageleafsizes500k,fig:linkagerootsizes100k,fig:linkagerootsizes500k}).\n\n\\ifembed{\n\\input{fig-linkage-div-times-500k.tex}\n}{}\n\nThe cost of removing data to avoid violating the assumption of unlinked\ncharacters is also very pronounced for estimating the \\jroedit{}{divergence\nmodel and} number of divergence events.\nThe method better estimates the correct \\jroedit{}{model and} number of events,\n\\jroedit{and}{both} with much higher posterior probability, when the constant\ncharacters are retained \n(Fig.\\ \n\\ref{fig:linkagenevents500k},\nS\\ref{fig:linkagemodels500k},\nS\\ref{fig:linkagenevents100k},\n\\&\nS\\ref{fig:linkagemodels100k}).\nThe median posterior probability of \\jroedit{}{both} the correct number of\ndivergence events \\jroedit{}{and the correct model} is over 0.95 for all\n500k-character \\datasets, even when loci were 1000bp long\n(Fig. \\ref{fig:linkagenevents500k}\n\\jroedit{}{\\& S\\ref{fig:linkagemodels500k}}).\nHowever, our results show that linked characters do introduce bias in the\nestimated posterior probability of the one divergence model ($\\nevents{} = 1$)\n(Fig.~\\ref{fig:linkagepostprobs}).\nHowever, the bias is moderate and makes the method conservative in the\nsense that it tends to underestimate the probability of shared\ndivergence (Fig.~\\ref{fig:linkagepostprobs}).\n\n\\ifembed{\n\\input{fig-linkage-nevents-500k.tex}\n\n\\input{fig-linkage-post-probs.tex}\n}{}\n\nFor simulated \\datasets with loci of length 100, 500, and 1000 base pairs, there\nwere an average of 5.4, 27.1, and 54.1 variable characters per locus,\nrespectively.\nAs expected, the number of variable characters per 100k and 500k \\dataset was\nvery similar to the simulated unlinked-character \\datasets, with an average of\nabout\n5,500 variable characters per 100k \\dataset\n(Fig.~S\\ref{fig:linkagenumberofvariablesites100k})\nand\n27,100 variable characters per 500k \\dataset\n(Fig.~S\\ref{fig:linkagenumberofvariablesites500k}).\nWhen at most one variable character is sampled per locus, the\nnumber of remaining characters is usually close or equal to the\nnumber of loci;\n1000, 200, and 100 characters for the 100k \\datasets\nwith 100, 500, and 1000 bp loci, respectively, and\n5000, 1000, and 500 characters for 500k \\datasets\nwith 100, 500, and 1000 bp loci, respectively\n(Fig.\\ \nS\\ref{fig:linkagenumberofvariablesites100k}\n\\&\nS\\ref{fig:linkagenumberofvariablesites500k}).\n\n\n\\subsubsection{Assessing the effect of missing data}\n\nAs predicted by coalescent theory, our results show that random missing data\nhas little effect on the performance of the method with respect to estimating\ndivergence times\n(Fig.~\\ref{fig:missingdivtimes}),\neffective population sizes\n(Fig.\\ \nS\\ref{fig:missingleafsizes}\n\\&\nS\\ref{fig:missingrootsizes}),\n\\jroedit{or}{} the number of divergence events\n(Fig.~\\ref{fig:missingnevents})\\jroedit{}{, or\nthe divergence model\n(Fig.~S\\ref{fig:missingmodels}).}\n\n\\ifembed{\n\\input{fig-missing-div-times.tex}\n\n\\input{fig-missing-nevents.tex}\n}{}\n\n\n\\subsubsection{Assessing the effect of biases in character-pattern acquisition}\n\nBiased character acquisition against singleton character patterns does create\nbias in estimates of divergence times\n(Fig.~\\ref{fig:filtereddivtimes}) and\npopulation sizes\n(Fig.\\ \nS\\ref{fig:filteredleafsizes}\n\\&\nS\\ref{fig:filteredrootsizes}), and the bias increases as the probability of\nmissing a character with a singleton pattern increases.\nNotably, this bias is smaller when the constant characters are retained in\nthe \\dataset\n(Fig.\\ \n\\ref{fig:filtereddivtimes},\nS\\ref{fig:filteredleafsizes}\n\\&\nS\\ref{fig:filteredrootsizes}).\n\n\\ifembed{\n\\input{fig-filtered-div-times.tex}\n}{}\n\nHowever, in the face of data-acquisition bias, the method still estimates the\nnumber of divergence events \\jroedit{}{and the divergence model} well,\nespecially when constant characters are used\n(Fig.~\\ref{fig:filterednevents}\n\\jroedit{}{\\&\nS\\ref{fig:filteredmodels}}).\nEven when the probability of sampling a character with a singleton pattern is\n0.4, the median posterior probability of the correct number of divergence\nevents is 0.948\n(Fig.~\\ref{fig:filterednevents})\\jroedit{}{,\nand the median posterior probability of the correct model is 0.945\n(Fig.~S\\ref{fig:filteredmodels}).}\n\n\\ifembed{\n\\input{fig-filtered-nevents.tex}\n}{}\n\n\\subsubsection{Comparison to ABC methods}\n\nThe new full-likelihood method, \\ecoevolity, does a much better job of\nestimating divergence times\n(Fig.~\\ref{fig:bakeoffdivtimes})\nand effective population sizes\n(Fig.\\ \nS\\ref{fig:bakeoffleafsizes}\n\\&\nS\\ref{fig:bakeoffrootsizes}),\nthan the approximate-likelihood Bayesian method, \\dppmsbayes.\nThis is despite the simulated \\datasets being ``tailored'' for the ABC method\n(i.e., loci of 200 linked base pairs).\nNotably, the new method does not underestimate the older divergence times like\nthe ABC method, which suffers from saturated population-genetic summary\nstatistics that assume an infinite-sites model of mutation\n(Fig.~\\ref{fig:bakeoffdivtimes}).\n\\jroedit{}{Also, the ABC approach gleans no information from the data about\neffective population sizes; the posterior distribution nearly matches the prior\nfor all analyses (Fig.\\ \nS\\ref{fig:bakeoffleafsizes}\n\\&\nS\\ref{fig:bakeoffrootsizes}).\nThis is despite the fact that three of the four statistics used for the ABC\napproach summarize information about population sizes.\n}\n\n\\ifembed{\n\\input{fig-bake-off-div-times.tex}\n}{}\n\nThe new method also does a better job of estimating the number of divergence\nevents (Fig.~\\ref{fig:bakeoffnevents}), with a median posterior probability\nof the correct number of events of 0.942, compared to 0.7 for the ABC method.\n\\jroedit{}{Similarly, the new method is better at estimating the divergence\nmodel (Fig.~S\\ref{fig:bakeoffmodels}), with a median posterior probability of\nthe correct model of 0.942, compared to 0.685 for the ABC method.}\nImportantly, the new method underestimates the number of events much less\nfrequently\n(Fig.~\\ref{fig:bakeoffnevents} \\jroedit{}{\\& S\\ref{fig:bakeoffmodels}}),\nwhich should lead to fewer erroneous interpretations of shared processes of\ndivergence.\n\n\\ifembed{\n\\input{fig-bake-off-nevents.tex}\n}{}\n\nIt is difficult to compare the computational effort between the two approaches,\ngiven that \\ecoevolity is collecting autocorrelated samples from\nthe full posterior, whereas \\dppmsbayes is collecting independent samples\nfrom a different distribution we hope is similar to the posterior.\nNonetheless, the comparison is aided by the fact that the heavy computation of\nboth methods is coded in \\clang/\\cpp.\nTo compare the overall amount of computation required by the two approaches\nwe look at the average time it takes to analyze a simulated \\dataset\non a single processor \n(2.6GHz Intel Xeon CPU E5-2660 v3).\nThis was 38.8 days for \\dppmsbayes (3,350,465 seconds)\nand only 33.4 minutes (2004.5 seconds) for \\ecoevolity.\nThe majority of the runtime for the ABC method is spent simulating samples\nfrom the prior distribution.\nWhile this step can be parallelized, the likelihood computations of \\ecoevolity\ncan also be multi-threaded.\nRegardless of the difficulties associated with comparing the approaches, the\n1,671-fold difference in computation time clearly demonstrates the\nfull-likelihood method is much more efficient than ABC.\n\n\n\\subsection{Empirical application}\n\nWhen the new method is applied to all of the RADseq sites from the\nfour pairs of \\spp{Gekko} populations, the results strongly\nsupport that all of the pairs diverged independently\n(Fig.~\\ref{fig:gekkonevents}).\nThe results are very robust to the priors on divergence times (\\divtime)\nand the concentration parameter (\\concentration) of the Dirichlet process, and\nto whether the polyallelic SNPs are recoded as binary\n(Fig.~\\ref{fig:gekkonevents})\nor removed\n(Fig.~S\\ref{fig:gekkonopolynevents}).\nLikewise, the estimates of divergence times and effective population sizes\nare nearly identical regardless of the prior on \\divtime or \\concentration,\nor whether polyallelic SNPs are recoded or removed\n(Fig.\\ \n\\ref{fig:gekkodivtimes},\nS\\ref{fig:gekkosizes},\nS\\ref{fig:gekkonopolydivtimes},\n\\&\nS\\ref{fig:gekkonopolysizes}).\n\n\\ifembed{\n\\input{fig-gekko-nevents.tex}\n\n\\input{fig-gekko-div-times.tex}\n}{}\n\nHowever, when only variable SNPs are analyzed, the behavior is much different.\nFirst, the estimated divergence times and population sizes are clearly far too\nlarge and more sensitive to the priors on the divergence times and the\nconcentration parameter\n(Fig.\\ \nS\\ref{fig:gekkovaronlydivtimes}\n\\&\nS\\ref{fig:gekkovaronlysizes}).\nWhile the true values of these parameters are obviously unknown, given the\nvariability of these data (Table~\\ref{table:gekkocomparisons}), and other data\nfrom these species \\citep{Siler2012, Siler2014kikuchii}, these values are\nclearly nonsensical.\nThe posterior probabilities of the number of divergences are also\nmuch more sensitive to the \\divtime and \\concentration priors,\nwith some combinations yielding results for which three divergence events\nare preferred, although Bayes factors always preferred four divergences\n(Fig.~S\\ref{fig:gekkovaronlynevents}).\nThese findings are similar when the polyallelic SNPs are removed\n(Fig.\\ \nS\\labelcref{fig:gekkonopolyvaronlydivtimes,fig:gekkonopolyvaronlysizes,fig:gekkonopolyvaronlynevents}).\n\nThe large overestimation of divergence times and population sizes is consistent\nwith our findings from the \\datasets simulated with an acquisition bias against\nrare allele patterns\n(Fig.\\ \n\\ref{fig:filtereddivtimes},\nS\\ref{fig:filteredleafsizes}\n\\&\nS\\ref{fig:filteredrootsizes}).\nIn these simulation-based analyses, we also saw dramatic overestimation of\nthese parameters when constant characters were excluded.\nIt appears that some variable character patterns are being lost during the\nacquisition and assembly of the RADseq data, and the model is sensitive to\nthese missing variable sites, especially when only variable characters are\nanalyzed.\n\n\\subsubsection{Empirical comparison to ABC}\n\nFigure~\\ref{fig:gekkobakeoff} shows the dramatic difference between the results\nof the new full-likelihood method, \\ecoevolity, and the ABC method,\n\\dppmsbayes, when analyzing a random subset of the \\spp{Gekko} data.\nFor \\dppmsbayes, there is strong support for a single, shared divergence\n(Fig.~\\ref{fig:gekkobakeoff}c),\nand the marginal posterior distributions of divergence times are almost\ncompletely overlapping among the three pairs of populations\n(Fig.~\\ref{fig:gekkobakeoff}d).\nIn contrast,\n\\ecoevolity strongly supports three independent divergences\n(Fig.~\\ref{fig:gekkobakeoff}a),\nand the marginal posterior divergence-time distributions are almost completely\nnon-overlapping\n(Fig.~\\ref{fig:gekkobakeoff}b).\nFurthermore, the computing time for \\ecoevolity and \\dppmsbayes was 7.6\nminutes and 49.3 days, respectively.\n\n\\ifembed{\n\\input{fig-gekko-bake-off.tex}\n}{}\n\n\n\\section{Discussion}\n\nPrevious approaches to estimating shared divergence times based on\napproximate-likelihood Bayesian computation (ABC) are very sensitive to prior\nassumptions about divergence times and often over-cluster divergences with\nstrong support\n\\citep{Oaks2012,Hickerson2013,Oaks2014reply,Oaks2014dpp}.\nHere, we introduced a new approach that increases the power and robustness of\nthese inferences by leveraging all of the information in genomic data within a\nfull-likelihood, Bayesian framework.\nThe full-likelihood approach is much better at estimating\ndivergence times\n(Fig.~\\ref{fig:bakeoffdivtimes})\nand nuisance parameters\n(Fig.\\ S\\ref{fig:bakeoffleafsizes} \\& S\\ref{fig:bakeoffrootsizes})\nthan ABC.\nIt is also better able to estimate the correct number of divergence events with\nmore confidence, and is much less biased toward underestimating the number of\ndivergence events\n(Fig.~\\ref{fig:bakeoffnevents}).\nThis is especially important, because most biogeographers that use these\nmethods are interested in testing for shared events.\nThe increased power of the method to detect variation in divergence times and\navoid spurious estimates of shared divergences will lead to fewer erroneous\ninterpretations of shared processes of divergence.\n\nThe efficiency associated with using all of the information in the data makes\nthe method very promising for empirical applications.\nFor example, increasing the number of characters from 100,000 to 500,000\nresulted in only modest improvements in precision\n(Fig.\\ \n\\ref{fig:valdivtimes}, S\\ref{fig:valleafsizes}, \\& S\\ref{fig:valrootsizes}).\nThis suggests that the benefit of collecting more characters begins to plateau\nwhen \\datasets are small relative to the number of characters commonly\ncollected via modern high-throughput sequencing technologies (e.g., the\nsimulated 100k \\datasets had only 5,500 SNPs on average).\nEven with only 200 short (200 bp) loci, the median posterior probability\nof the correct number of divergence events was 0.94\n(Fig.~\\ref{fig:bakeoffnevents}).\nAlso, directly calculating the likelihood of the population history from\ngenomic data avoids the computation necessary for approximating the likelihood\nvia simulations.\nAs a result, the new method, \\ecoevolity, provides better approximations of the\nposterior over 1000 times faster than the ABC method, \\dppmsbayes.\n\n\n\\subsection{To exclude linked characters, or not?}\n\nThe increased precision and robustness associated with retaining constant\ncharacters creates an interesting question when analyzing DNA sequence data\nfrom reduced-representation genomic libraries:\nIs it better to analyze all the data and violate the assumption that the\ncharacters are unlinked, or suffer a large loss of data to avoid violating that\nassumption?\nSeveral of our results suggest retaining all the data is preferable.\nFirst of all, the method is much better at estimating the divergence times,\neffective population sizes, and the correct number of events with high\nposterior probability when analyzing linked sequences of characters compared to\nwhen only one variable character per locus is analyzed\n(Fig.\\ \n\\labelcref{fig:linkagedivtimes500k,fig:linkagenevents500k},\nand\nFig.\\ \nS\\labelcref{fig:linkagedivtimes100k,fig:linkageleafsizes500k,fig:linkageleafsizes100k,fig:linkagerootsizes500k,fig:linkagerootsizes100k,fig:linkagenevents100k}).\nSecond, retaining all the data makes the method more robust to data-acquisition\nbiases\n(Fig.\\ \n\\labelcref{fig:filtereddivtimes,fig:filterednevents}\nand\nFig.\\ \nS\\labelcref{fig:filteredleafsizes,fig:filteredrootsizes}),\nwhich are common in alignments from reduced-representation genomic\nlibraries\n\\citep{Harvey2015,Linck2017}.\nThird, the results from the \\spp{Gekko} RADseq data are\nreasonable and robust to prior assumptions when all data are analyzed,\nbut nonsensical and sensitive to prior assumptions when only variable\ncharacters are analyzed.\nOur simulations suggest this is due to the filtering of the character patterns\nthat occurred when assembling these data.\n\nPerhaps most striking is how much better the method estimates the number\nof divergence events when all the data are used.\nFor example, across the 500,000-character \\datasets, the\nmedian posterior probability of the correct number of divergence events\nis over 0.94 regardless of the linked characters\nor pattern-acquisition biases we simulated\n(Fig.\\ \n\\ref{fig:valnevents},\n\\ref{fig:linkagenevents500k},\n\\&\n\\ref{fig:filterednevents}).\nFor comparison,\nthese values are as low as 0.41 when constant characters are removed\n(Fig.~\\ref{fig:filterednevents}).\n\nWe caution against generalizing our findings\nof favorable performance with linked loci\nto other methods that assume unlinked characters.\nHowever, \n\\citet{ChifmanKubatko2014}\nfound quartet inference of splits in multi-species coalescent trees\nfrom SNP data was also robust to the violation of unlinked characters.\nOur results show the amount of data that is discarded to avoid linked\ncharacters can far outweigh the effects of violating the assumption of\nunlinked characters.\nWhen analyzing linked loci with a method that assumes unlinked characters,\nusing simulations to assess the effect of linkage on the method may be worth\nthe effort in order to bring more data to bear.\n\n\n\\subsection{Philippine \\spp{Gekko}}\nWe purposefully selected a challenging empirical test case for the new method.\nEach of the four pairs of populations of \\spp{Gekko} occur on two different\noceanic islands that were never connected.\nThus, we do not expect shared divergence times across the pairs.\nHowever, based on previous findings \\citep{Siler2012, Siler2014kikuchii}, all\nof these pairs likely diverged very recently.\nThis is a challenging region of parameter space for this type of method: Very\nsimilar and recent divergence times that are nonetheless independent.\n% We used the new method to compare the divergence times of four pairs\n% of populations of \\spp{Gekko} inhabiting eight islands in the Philippines.\n% Each pair of populations inhabit two different oceanic islands that were never\n% connected, and thus never experienced the fragmentation associated with\n% Pleistocene sea-level fluctuations.\nOur results strongly support independent divergences, despite all four pairs\ndiverging very recently.\n(Fig.\\ \n\\ref{fig:gekkonevents}\n\\& \n\\ref{fig:gekkodivtimes}).\n\nWe found similar results when we analyzed a random subset of 200 loci from\nthree of the pairs of \\spp{Gekko} populations\n(Fig.~\\ref{fig:gekkobakeoff}a\\&b).\nIn contrast, when we analyzed these 200 loci with the ABC method, \\dppmsbayes,\nwe found strong support for the opposite conclusion that all three pairs\ndiverged at the same time\n(Fig.~\\ref{fig:gekkobakeoff}c\\&d).\nIn addition, \\ecoevolity took approximately 9,300-fold less computing time than\n\\dppmsbayes.\nThese results demonstrate that using the likelihood from genomic data provides\nenough information to efficiently and unambiguously separate divergences across\nvery narrow timescales, and avoids erroneous inferences of shared divergences.\n\n\\subsection{Caveats}\nThis method is subject to the caveats associated with all model-based\nstatistical methods,\nhowever, there are two caveats that are worth emphasizing with\nspecific reference to the types of models we explored here.\nFirst, it is important to keep in mind that when modeling the divergence of two\npopulations, the time of the divergence and the mutation rate are inextricably\nlinked.\nThus, we cannot learn about the relative rates of mutation among pairs of\npopulations when also trying to estimate their divergence times.\nUnlike previous methods \\citep{Hickerson2006,Huang2011,Oaks2014dpp},\nwe allow priors to be placed on mutation rates, to allow uncertainty\nto be incorporated into the model.\nHowever, the priors on the mutation rates need to be informative if one hopes\nto be able to estimate the divergence times.\n\nSecond, the new method does not allow migration after populations diverge.\nThis is a weakness compared to ABC approaches to this problem\n\\citep{Huang2011,Oaks2014dpp}.\nHowever, given the biases and sensitivity to priors exhibited by the ABC\nmethods even when migration is ignored\n\\citep{Oaks2012,Oaks2014reply,Oaks2014dpp},\nmodeling migration with these methods is not advisable without thorough\nsimulation-based analyses to assess their statistical behavior.\n\n\\section{Conclusions}\nWe introduced a new Bayesian model-choice method for estimating shared\ndivergence times across taxa.\nBy using the full likelihood and genome-scale data, the new method is more\naccurate, precise, robust, and efficient than existing methods based on\napproximate likelihoods.\nThis new tool will allow biologists to leverage comparative genomic data to\ntest hypotheses about the effects of environmental change on diversification.\n", "meta": {"hexsha": "f7dd03dac3229d3d94ffc61af55542621d8eeb83", "size": 75719, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/manuscript/ecoevolity/body.tex", "max_stars_repo_name": "phyletica/ecoevolity-experiments", "max_stars_repo_head_hexsha": "bb16e34c4c7495feaa68653df98d5fbead93cf44", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tex/manuscript/ecoevolity/body.tex", "max_issues_repo_name": "phyletica/ecoevolity-experiments", "max_issues_repo_head_hexsha": "bb16e34c4c7495feaa68653df98d5fbead93cf44", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/manuscript/ecoevolity/body.tex", "max_forks_repo_name": "phyletica/ecoevolity-experiments", "max_forks_repo_head_hexsha": "bb16e34c4c7495feaa68653df98d5fbead93cf44", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.0226744186, "max_line_length": 161, "alphanum_fraction": 0.7797118293, "num_tokens": 19129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3179532857085877}}
{"text": "\\chapter{Goal Directed Proof: Tactics and Tacticals}\n\n\\label{tactics-and-tacticals}\n\n\\index{tactics!purpose of|(}\nThere are three primary devices that together make theorem proving practical\nin \\HOL. All three originate with Milner\n\\index{Milner, R.}\\index{LCF@\\LCF!Edinburgh} for Edinburgh \\LCF.\nThe first is the theory as\na record of (among other things) facts already proved\nand thence available as lemmas\n\\index{lemmas}\nwithout having to be re-proved.  The second,\nthe subject of Chapter~\\ref{derived-rules}, is the\nderived rule of inference as a meta-language procedure that implements a\nbroad pattern of inference, but that also, at each application,\ngenerates every primitive step of the proof. The third device is\nthe tactic as a means of organizing the construction of proofs;\nand the use of tacticals for composing tactics.\n\nEven with recourse to derived inference rules,\nit is still surprisingly awkward to work forward,\n\\index{forward proof!compared to goal directed} to find a chain of\ntheorems that culminates in a desired theorem.  This is in part because\nchains have no structure, while `proof efforts' do.  For instance, if\nwithin one sequence, two chains of steps\nare to be combined in the end by conjunction, then\none chain must follow or be interspersed with\nthe other in the overall sequence.  It can also be difficult to direct\nthe proof toward its object when starting from\nonly hypotheses (if any), lemmas (if any),\naxioms, and theorems following from no hypotheses\n(\\eg\\ by \\ml{ASSUME} or \\ml{REFL}). Likewise, it can be equally difficult\nto reconstruct\n\\index{tactics!as documentation of proofs}\nthe plan of the proof effort after the fact, from the\nlinear sequence of theorems; the sequence is unhelpful as documentation.\n\nThe idea of goal directed proof\\index{goal directed proof search!reason for} is a simple one, well known in\nartificial intelligence: to organize the search\\index{proof construction!as tree search} as a tree, and to reverse\nthe process and {\\it begin\\/} with the objective. The goal is then\ndecomposed, successively if necessary,\ninto what one hopes are more tractable subgoals, each decomposition\naccompanied by a\nplan for translating the solution of subgoals into a solution of the goal.\nThe choice of decomposition is an explicit way of expressing a proof\n`strategy'.\n\\index{strategies, for proof}\n\nThus, for example, instead of\nthe linear sequencing of two branches of the proof of the conjunction,\neach branch starting from scratch, the proof task is organized\nas a tree search, starting with a conjunctive goal\nand decomposing it into the two conjunct subgoals (undertaken in optional\norder), with the intention of conjoining the two solutions when and if found.\nThe proof itself, as a sequence of steps, is the same however it is found;\nthe difference is in the search, and in the preservation, if required, of\nthe structured proof plan.\n\nThe representation of this idea in \\LCF\\ was Milner's inspiration;\nthe idea is similarly central to theorem proving in \\HOL.\nAlthough subgoaling theorem provers had already been built at the time,\nMilner's particular contribution was in formalizing the method for\ntranslating subgoals solutions to solutions of goals.\n\n\n\n%The tactics and tacticals in the \\HOL{} system are derived from those in the\n%Cambridge \\LCF\\ system \\cite{new-LCF-man} (which evolved\n%from the ones\n%in Edinburgh \\LCF\\ \\cite{Edinburgh-LCF}).\n\n\\section{Tactics, goals and justifications}\n\\label{tactics}\n\n\\index{goal directed proof search!concepts of|(}\nA \\emph{tactic}%\n\\index{proof steps, as ML function applications@proof steps, as \\ML{} function applications}\nis an \\ML{} function that when applied to a \\emph{goal}\n\\index{goals, in HOL system@goals, in \\HOL{} system}\nreduces it to (i) a list\\footnote{The ordering is necessary for selecting\na tree search strategy.} of\n(sub)goals, along with (ii) a \\emph{justification}\n\\index{justifications, in goal-directed proof search}\nfunction mapping a list of theorems to a theorem.  The idea is that\nthe function justifies the decomposition of the goal.\n%that respectively {\\it achieve\\/} the (sub)goals\n%to a theorem that achieves the goal.\nA goal is an \\ML{} value whose type is isomorphic\nto, but distinct from, the \\ML{} abstract type \\ml{thm} of theorems.\nThat is, a goal is\na list of terms ({\\it assumptions\\/})\n\\index{assumption list, of goal} paired with a term.\n\\index{term component, of goal}\nThese two components correspond, respectively, to the list of hypotheses\nand the conclusion of a theorem. The list of assumptions is a working\nrecord of facts that may be used in decomposing the goal.\n\nThe relation of theorems to goals is achievement:\n\\index{achievement, of goals}\na theorem achieves a goal if the conclusion of the theorem\nis equal to the term part of the goal (up to $\\alpha$-conversion), and\nif each hypothesis of the theorem is equal (up to $\\alpha$-conversion,\nagain) to some assumption of the goal. This definition assures that\nthe theorem purporting to satisfy a goal does not depend on\nassumptions beyond the working assumptions of the goal.\n\nA justification is (rather confusingly) called\na {\\it proof\\/}\n\\index{proofs, in HOL logic@proofs, in \\HOL{} logic!as ML function applications@as \\ML{} function applications}\n\\index{proof functions (same as justifications, validations)}\nin \\HOL{}, following the \\LCF{} usage; it is, as mentioned,\nan \\ML{} function\nfrom a theorem list to a theorem.  The \\ML{} `proof' function\ncorresponds to a proof\n\\index{proofs, in HOL logic@proofs, in \\HOL{} logic!as generated by tactics} in the\nlogical sense (of a sequence of theorems depending on inference\\index{inferences, in HOL logic@inferences, in \\HOL{} logic!in goal-directed proof search} rules)\nonly in that it must\nevaluate the \\ML{} function corresponding\nto each inference rule on which the sequence depends\nin order to compute its \\ml{thm}-valued result. (`Justification', or\n`validation',\n\\index{validations} as is sometimes used, are less confusing terms for\nthe \\ML{} function in question.)\nThe proof function, or justification, returned by a tactic is intended to map the\nlist of theorems respectively achieving the subgoals to the\ntheorem achieving the original goal; it justifies the decomposition\ninto subgoals.\n\nA tactic is said to {\\it solve\\/}\n\\index{solving, of goals} a goal if it reduces the goal to the\nempty set of subgoals.\nThis depends, obviously, on there being at least one\ntactic that maps a goal to the empty subgoal list.  The simplest\ntactic that does this is one that can recognize when a goal is\nachieved by an axiom or an existing theorem; in \\HOL, the function\n\\ml{ACCEPT\\_TAC}\\index{ACCEPT_TAC@\\ml{ACCEPT\\_TAC}}\n does this. \\ml{ACCEPT\\_TAC} takes a theorem $th$\nand produces a tactic that maps a value\nof type \\ml{thm} to the empty list of subgoals. It justifies this\n`decomposition' by a proof function that maps the empty list of theorems\nto the theorem $th$. The use of this technical device, or other\nsuch tactics, ends the decomposition of subgoals, and allows the proof\nto be built up.\\index{tactics!purpose of|)}\n\nUnlike theorems, goals need not be defined as an abstract type; they\nare transparent and can be constructed freely. Thus, an \\ML{} type\nabbreviation is introduced for goals.\\footnote{However, if goals were\n  an abstract type, the print abbreviation could be avoided where not\n  intended.}.  The operations on goals are therefore just the ordinary\npair selectors and constructor.\nLikewise, type abbreviations are introduced for justifications\n(proofs) and tactics. Conceptually, the following abbreviations are\nmade in \\HOL:\n\n\\begin{hol}\n\\index{goal@\\ml{goal}}\n\\index{tactic@\\ml{tactic}}\n\\index{proof@\\ml{proof}}\n\\index{tactics!ML type of@\\ML{} type of}\n\\begin{verbatim}\n   goal       = term list * term\n   tactic     = goal -> goal list * proof\n   proof      = thm list -> thm\n\\end{verbatim}\\end{hol}\n\n\\index{subgoals@\\ml{subgoals}} In fact, the type\n\\ml{goal~list~*~proof} is abbreviated in \\ML{} to \\ml{subgoals}, and\nthe abbreviation of \\ml{tactic} made indirectly through it.  Thus, if\n$T$ is a tactic and $g$ is a goal, then applying $T$ to $g$ (\\ie\\\nevaluating the \\ML\\ expression $T\\ g$) results in an \\ML{} value of\ntype \\ml{subgoals}, \\ie\\ a pair whose first component is a list of\ngoals and whose second component has \\ML{} type \\ml{proof}. (The word\n`tactic' is occasionally used loosely to mean a tactic-valued\nfunction.)\n\nIt does not follow, of course, from the type \\ml{tactic} that a\nparticular tactic is well-behaved. For example,\nsuppose that\n$T\\ g${\\small\\verb% = ([%}$g_1${\\small\\verb%;%}$\\ldots\n${\\small\\verb%;%}$g_n${\\small\\verb%],%}$p${\\small\\verb%)%}, and that\nthe subgoals $g_1$ , $\\dots$, $g_n$ have been solved.\nThat means that some\ntheorems $th_1$ , $\\dots$, $th_n$ have been proved\nsuch that each $th_i$ ($1\\leq i\\leq n$) achieves the goal $g_i$.\nThe justification $p$\nis intended to be a\nfunction that when applied to the list\n{\\small\\verb%[%}$th_1${\\small\\verb%;%}$\\ldots${\\small\\verb%;%}$th_n${\\small\\verb%]%},\nsucceeds in returning a theorem, $th$,\nachieving the original goal $g$; but, of course, it might sometimes\nnot succeed. If $p$\nsucceeds for every list of achieving theorems, then the tactic $T$ is\nsaid to be {\\it valid\\/}\\index{validity, of tactics|(}. This does not guarantee, however, that\nthe subgoals are solvable in the first place. If, in addition\nto being valid, a tactic always produces solvable subgoals from a\nsolvable goal, it is called {\\it strongly valid\\/}.\n\\index{strong validity, of tactics}\n\nTactics can be perfectly useful without being\nstrongly valid, or without\neven being valid;\nin fact, some of the most basic theorem proving strategies, expressed\nas tactics, are invalid or not strongly valid.\\footnote{The subgoal\n  package, discussed in Section~\\ref{sec:goalstack}, prevents the use of\n  invalid tactics when they are liable to result in unexpected\n  theorem results, but the \\HOL{} system used directly allows\n  it.}\nAn invalid tactic cannot result in the proof of false theorems;\n\\index{consistency, of HOL logic@consistency, of \\HOL{} logic|(}\n\\index{security, in goal directed proof|(}\ntheorems in \\HOL{} are always the result of performing a proof in the\nbasic logic, whether the proof is found by goal directed search\nor forward search.\\footnote{`Invalid' is perhaps a misleading term, since\n  there is nothing logically amiss in the use of invalid tactics\n  or the theorems produced thereby; but the term has stuck over time.}\nHowever, an invalid tactic may produce an unintended theorem---one\nthat does not achieve the original goal. The typical case is when a\ntheorem purporting to achieve a goal actually depends on hypotheses\nthat extend beyond the assumptions of the goal.  The inconvenience to\nthe \\HOL{} user in this case is that the problem may be not\nimmediately obvious; the default print format of theorems has\nhypotheses abbreviated as dots. Invalidity may also be the result of\nthe failure\n\\index{failure, of tactics|(}\nof the proof function, in the \\ML{} sense of failure, when\napplied to a list of theorems (if, for example, the function were\ndefined incorrectly); but again, no false theorems can result.\nLikewise, a tactic that is not strongly valid cannot result in a false\ntheorem; the worst outcome of applying such a tactic is the production\nof unsolvable subgoals\n\\index{consistency, of HOL logic@consistency, of \\HOL{} logic|)}\n\\index{security, in goal directed proof|)}\\index{validity, of tactics|)}.\n\nTactics are specified using the following notation:\n\\index{notation!for specification of tactics}\n\n\\begin{center}\n\\begin{tabular}{c} \\\\\n$\\mathit{goal}$ \\\\ \\hline \\hline\n$\\mathit{goal}_1\\ \\ \\ \\mathit{goal}_2 \\ \\ \\ \\ldots\\ \\ \\ \\mathit{goal}_n$ \\\\\n\\end{tabular}\n\\end{center}\n\n\\noindent For example, the\ntactic for decomposing conjunctions into\ntwo  conjunct subgoals is called {\\small\\verb%CONJ_TAC%}.\n\\index{CONJ_TAC@\\ml{CONJ\\_TAC}}  It is described by:\n\n\\begin{center}\n\\begin{tabular}{c} \\\\\n$ t_1${\\small\\verb% /\\ %}$t_2$ \\\\ \\hline \\hline\n$t_1\\ \\ \\ \\ \\ \\ \\ t_2$ \\\\\n\\end{tabular}\n\\end{center}\n\n\\noindent This indicates\nthat {\\small\\verb%CONJ_TAC%} reduces a goal of the form\n{\\small\\verb%(%}$\\Gamma${\\small\\verb%,%}$t_1${\\small\\verb%/\\%}$t_2${\\small\\verb%)%}\nto subgoals\n{\\small\\verb%(%}$\\Gamma${\\small\\verb%,%}$t_1${\\small\\verb%)%} and {\\small\\verb%(%}$\\Gamma${\\small\\verb%,%}$t_2${\\small\\verb%)%}.\nThe fact that the assumptions of the original goal\nare propagated unchanged to the two subgoals is indicated by the absence\nof assumptions in the notation. The notation gives no indication of the\nproof function.\n\nAnother example is {\\small\\verb%INDUCT_TAC%}\\index{INDUCT_TAC@\\ml{INDUCT\\_TAC}}\\index{induction tactics},\nthe tactic for performing mathematical induction\non the natural numbers:\n\n\\begin{center}\n\\begin{tabular}{c} \\\\\n{\\small\\verb%!%}$n${\\small\\verb%.%}$t[n]$ \\\\ \\hline \\hline\n$t[${\\small\\verb%0%}$]$ {\\small\\verb%     %} $\\{t[n]\\}\\ t[${\\small\\verb%SUC %}$n]$\n\\end{tabular}\n\\end{center}\n\n{\\small\\verb%INDUCT_TAC%} reduces a goal of the form\n{\\small\\verb%(%}$\\Gamma${\\small\\verb%,!%}$n${\\small\\verb%.%}$t[n]${\\small\\verb%)%} to a basis subgoal\n{\\small\\verb%(%}$\\Gamma${\\small\\verb%,%}$t[${\\small\\verb%0%}$]${\\small\\verb%)%}\nand an induction step subgoal\n{\\small\\verb%(%}$\\Gamma\\cup\\{${\\small\\verb%%}$t[n]${\\small\\verb%%}$\\}${\\small\\verb%,%}$t[${\\small\\verb%SUC %}$n]${\\small\\verb%)%}.\nThe induction assumption\nis indicated in the tactic notation with set brackets.\n\nTactics fail\n\\index{failure, of tactics|)}\n(in the \\ML{} sense) if they are applied to\ninappropriate\ngoals. For example, {\\small\\verb%CONJ_TAC%} will fail if it is applied to a goal whose\nconclusion is not a conjunction. Some tactics never fail; for example\n{\\small\\verb%ALL_TAC%}\\index{ALL_TAC@\\ml{ALL\\_TAC}}\n\n\\begin{center}\n\\begin{tabular}{c} \\\\\n$t$ \\\\ \\hline \\hline\n$t$\n\\end{tabular}\n\\end{center}\n\n\\noindent is the identity tactic;\n\\index{identity tactic} it reduces a goal\n{\\small\\verb%(%}$\\Gamma${\\small\\verb%,%}$t${\\small\\verb%)%}\nto the single\nsubgoal {\\small\\verb%(%}$\\Gamma${\\small\\verb%,%}$t${\\small\\verb%)%}---\\ie\\\nit has no effect. {\\small\\verb%ALL_TAC%} is useful for writing\ncompound tactics, as discussed later (see Section~\\ref{tacticals}).\n\nIn just the way that the derived rule \\ml{REWRITE\\_RULE}\n\\index{REWRITE_TAC@\\ml{REWRITE\\_TAC}|(}\n is central\nto forward proof (Section~\\ref{avra_rewrite}), the corresponding\nfunction \\ml{REWRITE\\_TAC}\n\\index{rewriting!main tactic for|(}\n\\index{rewriting!importance of, in goal directed proof|(}\nis central to goal\ndirected proof.  Given a goal and a list of equational theorems,\n\\ml{REWRITE\\_TAC} transforms the term component of the goal by\napplying the equations as left-to-right rewrites, recursively and\nto all depths, until no more changes can be made.  Unless not\nrequired, the function includes as rewrites the same\nstandard set of pre-proved tautologies\n\\index{tautologies, in rewriting tactic}\nthat \\ml{REWRITE\\_RULE} uses.\nBy use of the tautologies, some subgoals can be solved\ninternally by rewriting, and in that case, an empty list of subgoals\nis returned. The transformation of the goal is justified in each case by the\nappropriate chain of inferences.\nRewriting often does a large share of the work in goal directed proof searches.\\index{goal directed proof search!concepts of|)}\n\\index{REWRITE_TAC@\\ml{REWRITE\\_TAC}|)}\n\\index{rewriting!importance of, in goal directed proof|)}\n\\index{rewriting!main tactic for|)}\n\nA simple example from list theory (Section~\\ref{avra_list})\nillustrates the use of tactics.\nA conjunctive goal is declared, and \\ml{CONJ\\_TAC} applied to it:\n\n\\setcounter{sessioncount}{1}\n\\begin{session}\\begin{verbatim}\n- val g = ([]:term list,``(HD[1;2;3] = 1) /\\ (TL[1;2;3] = [2;3])``);\n> val g = ([], ``(HD[1;2;3] = 1) /\\ (TL[1;2;3] = [2;3])``) :\n  term list * term\n\n- val (gl1,p1) = CONJ_TAC g;\n> val gl1 = [([], ``HD[1;2;3] = 1``); ([], ``TL[1;2;3] = [2;3]``)] :\n  (term list * term) list\n  val p1 = fn : thm list -> thm\n\\end{verbatim}\\end{session}\n\n\\noindent The subgoals are each rewritten, using the definitions of\n\\ml{HD} and \\ml{TL}:\n\n\\begin{session}\\begin{verbatim}\n- open listTheory\n  [...]\n\n- HD;\n> val it = |- !h t. HD (h::t) = h : thm\n\n- TL;\n> val it = |- !h t. TL (h::t) = t : thm\n\n- val (gl1_1,p1_1) = REWRITE_TAC[HD,TL](hd gl1);\n> val gl1_1 = [] : (term list * term) list\n  val p1_1 = fn : thm list -> thm\n\n- val (gl1_2,p1_2) = REWRITE_TAC[HD,TL](hd(tl gl1));\n> val gl1_2 = [] : (term list * term) list\n  val p1_2 = fn : thm list -> thm\n\\end{verbatim}\\end{session}\n\n\\noindent Both of the two subgoals are now solved, so the\ndecomposition is complete and the proof can be built up in stages.\nFirst the theorems achieving the subgoals are proved, then from those,\nthe theorem achieving the original goal:\n\\vfill\n\\newpage\n\\begin{session}\\begin{verbatim}\n- val th1 = p1_1[];\n> val th1 = |- HD [1; 2; 3] = 1 : thm\n\n- val th2 = p1_2[];\n> val th2 = |- TL [1; 2; 3] = [2; 3] : thm\n\n- p1[th1,th2];\n> val it = |- (HD [1; 2; 3] = 1) /\\ (TL [1; 2; 3] = [2;3]) : thm\n\\end{verbatim}\\end{session}\n\n\\noindent Although only the theorems achieving the subgoals are `seen' here,\nthe proof functions of the three tactic applications together perform\nthe entire chain\\index{goal directed proof search!generation of proofs by}\\index{proofs, in HOL logic@proofs, in \\HOL{} logic!as generated by tactics}\n of inferences leading to the theorem achieving the goal.\nThe same proof could be constructed by forward search, starting from\nthe definitions of \\ml{HD} and \\ml{TL}, but not nearly as easily.\n\nThe \\HOL{} system provides a collection of pre-defined tactics (and\n\\ml{tactic}-valued functions) that includes\n\\ml{CONJ\\_TAC}, \\ml{INDUCT\\_TAC}, \\ml{ALL\\_TAC}  and\n\\ml{REWRITE\\_TAC}. The pre-defined tactics\nare adequate for many applications.  In addition, there are two means of\ndefining new tactics.\n\\index{tactics!definition of new}\nSince a tactic\\index{proof steps, as ML function applications@proof steps, as \\ML{} function applications} is an \\ML{} function, the user\ncan define a new tactic directly in \\ML.  Definitions of this sort\nuse \\ML{} functions to construct the term part of the subgoals from\nthe term part of the original goal (if any transformation is required);\nand they specify the justification,\nwhich expects a list of theorems achieving the subgoals and\nreturns the theorem achieving (one hopes) the goal.\nThe proof of the theorem is encoded in the definition of the justification\n function;\nthat is, the means for deriving the desired theorem from the theorems\ngiven. This typically involves references to axioms and\nprimitive and defined inference rules,\nand is usually the more difficult part of the project.\n\nA simple example of a tactic written in \\ML\\index{proofs, in HOL logic@proofs, in \\HOL{} logic!as ML function applications@as \\ML{} function applications}\\ is afforded by \\ml{CONJ\\_TAC},\nwhose definition in \\HOL{} is as follows:\n\n\\begin{hol}\n\\index{CONJ_TAC@\\ml{CONJ\\_TAC}!ML implementation of@\\ML{} implementation of}\n\\begin{verbatim}\n   fun CONJ_TAC (asl,w) =\n     let val (l,r) = dest_conj w\n     in\n         ([(asl,l), (asl,r)],(fn [th1, th2] => CONJ th1 th2))\n     end\n\\end{verbatim}\\end{hol}\n\n\\noindent This shows how the subgoals are constructed, and how the\nproof function is specified in terms of the derived rule \\ml{CONJ}\n(Section~\\ref{avra_conj}).\n\nThe second method is to compose\n\\index{tactics!indirect implementation of}\n\\index{tactics!compound}\n\\index{proof construction}\nexisting tactics by the use\nof \\ML{} functions called {\\it tacticals\\/}.\n\\index{tacticals}\nThe tacticals provided in \\HOL{} are listed in Section~\\ref{tacticals}.\nFor example, two existing tactics can be sequenced\n\\index{sequencing!of tactics}\n\\index{tactics!sequencing of}\n by use of the\ntactical \\ml{THEN}:\\index{THEN@\\ml{THEN}}\nif $T_1$ and\n$T_2$ are  tactics,  then the  \\ML{} expression  $T_1${\\small\\verb% THEN %}$T_2$\nevaluates to a  tactic that first applies  $T_1$ to  a goal  and then applies\n$T_2$ to each subgoal produced by $T_1$.   The  tactical {\\small\\verb%THEN%} is\nan infixed \\ML{} function. Complex and powerful tactics can be\nconstructed in this way; and new tacticals can also be defined, although\nthis is unusual.\n\nThe example from earlier\nis continued, to illustrate the use of the tactical \\ml{THEN}:\n\n\\begin{session}\\begin{verbatim}\n- val (gl2,p2) = (CONJ_TAC THEN REWRITE_TAC [HD, TL])g;\n> val gl2 = [] : (term list * term) list\n  val p2 = fn : thm list -> thm\n\n- p2 [];\n> val it = |- (HD [1; 2; 3] = 1) /\\ (TL [1; 2; 3] = [2; 3])\n\\end{verbatim}\\end{session}\n\n\\noindent The single tactic \\ml{CONJ\\_TAC THEN REWRITE\\_TAC[HD;TL]}\nsolves the goal in one single application. The chain of inference computed,\nhowever, is exactly the same as in the interactive proof; only the search is\ndifferent.\n\nIn general, the second method is both easier and more reliable.  It is\neasier because it does not involve writing \\ML{} procedures (usually\nrather complicated procedures); and more reliable because\nthe composed tactics are valid\n\\index{validity, of tactics} when the constituent tactics are valid,\nas a consequence of the way the tacticals are defined. Tactics written\ndirectly in \\ML{} may fail\n\\index{failure, of tactics!debugging}\n\\index{failure, of tactics|(}\n\\index{debugging, of tactics}\n\\index{tactics!debugging of}\nin a variety of ways, and although, as usual, they cannot cause false\ntheorems to appear, the failures can be difficult to understand and\ntrace.\\footnote{A possible extension to \\HOL\\ would be a `debugging\n  environment' for this class of tactic.} On the other hand, there are\nsome proof strategies that cannot be implemented as compositions of\nexisting tactics, and these have to be implemented directly in \\ML.\nCertain sorts of inductions are an example of this; as well as tactics\nto support some personal styles of proof.\n\nEither sort of tactic can be difficult to apply by hand, as shown in\nthe examples above.  There can be a lot of book-keeping required to\nsupport such an activity.  For this reason, most interactive\ntheorem-proving uses the subgoal or goalstack package described in\nSection~\\ref{sec:goalstack}.\n\n\n\\subsection{Details of proving theorems}\n\\label{using-tactics}\n\nWhen a theorem is proved that the user wishes to preserve for future use,\nit can be stored in the current theory\nby using the function \\ml{save\\_thm} (see Section~\\ref{theoryprims}).\n\nTo simplify the use of tactics there are three standard functions\n\n\\index{TAC_PROOF@\\ml{TAC\\_PROOF}|pin}\n\\index{prove_thm@\\ml{prove\\_thm}|pin}\n\\index{PROVE@\\ml{PROVE}|pin}\n\\begin{holboxed}\\begin{verbatim}\n   TAC_PROOF : (goal * tactic) -> thm\n   store_thm : (string * term * tactic) -> thm\n   prove     : (term * tactic) -> thm\n\\end{verbatim}\\end{holboxed}\n\n\\noindent \\ml{TAC\\_PROOF} takes a goal and a tactic, and applies the\ntactic to the goal; the goal can have assumptions.  Executing\n\\ml{store\\_thm(\"foo\",}$t$\\ml{,}$T$\\ml{)} proves the goal\n\\ml{([],}$t$\\ml{)} (\\ie\\ the goal with no assumptions and conclusion\n$t$) using tactic $T$ and saves the resulting theorem with name\n\\ml{foo} in the current theory.  Executing\n\\ml{prove(}$t$\\ml{,}$T$\\ml{)} proves the goal \\ml{([],}$t$\\ml{)} using\n$T$ and returns the result without saving it. In all cases the\nevaluation fails if $T$ does not solve the goal.\n\nIn short, \\HOL{} provides a very general framework in which proof\nstrategies can be designed, implemented, applied and tested.  Tactics\nrange from the very simple to the very advanced; in theory, a\nconventional automatic theorem prover could be expressed as a tactic or group\nof tactics.  In contrast, some users never have need to go beyond the\nbuilt in tactics of the system.  The vital support that \\HOL{} provides\nin all cases is the assurance that only theorems of the deductive system\ncan be represented as theorems of the \\HOL{} system---security is\nalways preserved.\n\n\\section{Some tactics built into HOL}\n\\label{avra_builtin}\n\nThis section contains a selection of the more commonly\n\\index{tactics!list of some|(}\nused tactics in the \\HOL{} system. (see \\REFERENCE\\\nfor the complete list, with fuller explanations.)\n\nIt should be recalled that the \\ML{} type \\ml{thm\\_tactic} abbreviates\n\\ml{thm->tactic}, and the type \\ml{conv} abbreviates \\ml{term->thm}.\n\n\\subsection{Acceptance of a theorem}\n\n\n\\begin{holboxed}\\index{ACCEPT_TAC@\\ml{ACCEPT\\_TAC}|pin}\n\\begin{verbatim}\n   ACCEPT_TAC : thm_tactic\n\\end{verbatim}\\end{holboxed}\n\n\\begin{itemize}\n\n\\item{\\bf Summary:} {\\small\\verb%ACCEPT_TAC %}$th$\nis a tactic that solves any goal that is\nachieved by $th$.\n\n\\index{forward proof!interfacing to goal directed}\n\\item{\\bf  Use:} Incorporating forward proofs, or theorems already\nproved, into goal directed proofs.\nFor example, one might reduce a goal $g$ to\nsubgoals $g_1$, $\\dots$, $g_n$\nusing a tactic $T$ and then prove theorems $th_1$ , $\\dots$, $th_n$\nrespectively achieving\nthese goals by forward proof. The tactic\n\n\\[\\ml{  T THENL[ACCEPT\\_TAC }th_1\\ml{;}\\ldots\\ml{;ACCEPT\\_TAC }th_n\\ml{]}\n\\]\n\nwould then solve $g$, where \\ml{THENL}\n\\index{THENL@\\ml{THENL}} is the tactical that applies\nthe respective elements of the tactic list to the subgoals produced\nby \\ml{T} (see Section~\\ref{avra_thenl}).\n\n\\end{itemize}\n\n\n\\subsection{Adding an assumption}\n\n\\index{ASSUME_TAC@\\ml{ASSUME\\_TAC}|pin}\n\\begin{holboxed}\\begin{verbatim}\n   ASSUME_TAC : thm_tactic\n\\end{verbatim}\\end{holboxed}\n\n\\begin{itemize}\n\n\\item {\\bf Summary:} {\\small\\verb%ASSUME_TAC |-%}$u$ adds $u$ as an assumption.\n\\index{assumptions!tactic for adding}\n\n\\begin{center}\n\\begin{tabular}{c} \\\\\n$t$\n\\\\ \\hline \\hline\n$\\{u\\}t$\n\\\\\n\\end{tabular}\n\\end{center}\n\n\\item{\\bf Use:} Enriching the assumptions of a goal\nwith definitions or previously proved theorems.\n\n\\end{itemize}\n\n\\subsection{Specialization}\\index{universal quantifier, in HOL logic@universal quantifier, in \\HOL{} logic!tactics for}\n\n\\index{GEN_TAC@\\ml{GEN\\_TAC}|pin}\n\\begin{holboxed}\\begin{verbatim}\n   GEN_TAC : tactic\n\\end{verbatim}\\end{holboxed}\n\n\\begin{itemize}\n\n\\index{specialization tactic}\n\\item{\\bf  Summary:} Specializes a universally quantified\ntheorem to an arbitrary value.\n\n\n\\begin{center}\n\\begin{tabular}{c} \\\\\n{\\small\\verb%!%}$x${\\small\\verb%.%}$t[x]$\n\\\\ \\hline \\hline\n$t[x']$\n\\\\\n\\end{tabular}\n\\end{center}\n\n\\noindent where $x'$ is a variant of $x$\nnot free in either goal or assumptions.\n\n\\item{\\bf   Use:} Solving universally quantified goals.\n\\ml{GEN\\_TAC} is often the first step of a goal directed proof.\n{\\small\\verb%STRIP_TAC%} (see below)\napplies {\\small\\verb%GEN_TAC%} to universally quantified goals.\n\\end{itemize}\n\n\\subsection{Conjunction}\n\n\\index{CONJ_TAC@\\ml{CONJ\\_TAC}|pin}\n\\begin{holboxed}\\begin{verbatim}\n   CONJ_TAC : tactic\n\\end{verbatim}\\end{holboxed}\n\n\\begin{itemize}\n\n\\index{conjunction, in HOL logic@conjunction, in \\HOL{} logic!tactic for splitting of}\n\\item{\\bf Summary:} Splits a\ngoal $t_1${\\small\\verb%/\\%}$t_2$ into two\nsubgoals, $t_1$ and $t_2$.\n\n\\begin{center}\n\\begin{tabular}{c} \\\\\n$t_1${\\small\\verb% /\\ %}$t_2$\n\\\\ \\hline \\hline\n$t_1\\ \\ \\ \\ \\ \\ t_2$\n\\\\\n\\end{tabular}\n\\end{center}\n\n\\item{\\bf Use:} Solving conjunctive goals.\n{\\small\\verb%CONJ_TAC%} is invoked by {\\small\\verb%STRIP_TAC%} (see below).\n\n\\end{itemize}\n\n\\subsection{Discharging an assumption}\n\\label{avradisch}\n\n\\index{implication, in HOL logic@implication, in \\HOL{} logic!tactics for}\n\\index{DISCH_TAC@\\ml{DISCH\\_TAC}|pin}\n\\begin{holboxed}\\begin{verbatim}\n   DISCH_TAC : tactic\n\\end{verbatim}\\end{holboxed}\n\n\\begin{itemize}\n\n\\item{\\bf Summary:} Moves the antecedant\nof an implicative goal into the assumptions, leaving the consequent\nas the term component.\n\n\\begin{center}\n\\begin{tabular}{c} \\\\\n$u${\\small\\verb% ==> %}$v$\n\\\\ \\hline \\hline\n$\\{u\\}v$\n\\\\\n\\end{tabular}\n\\end{center}\n\n\n\\item{\\bf Use:} Solving goals of the form\n$u${\\small\\verb% ==> %}$v$\nby assuming $u$  and then solving\n$v$ under the assumption.\n{\\small\\verb%STRIP_TAC%} (see below) invokes\n{\\small\\verb%DISCH_TAC%} on implicative goals.\n\\end{itemize}\n\n\\subsection{Combined simple decompositions}\n\n\\index{STRIP_TAC@\\ml{STRIP\\_TAC}|pin}\n\\begin{holboxed}\\begin{verbatim}\n   STRIP_TAC : tactic\n\\end{verbatim}\\end{holboxed}\n\n\\begin{itemize}\n\n\\item{\\bf Summary:} Breaks a goal apart.\n{\\small\\verb%STRIP_TAC%} removes one outer connective from the goal, using\n{\\small\\verb%CONJ_TAC%}, {\\small\\verb%DISCH_TAC%}, {\\small\\verb%GEN_TAC%},\nand other tactics.\nIf the goal has the form $t_1${\\small\\verb%/\\%}$\\cdots${\\small\\verb%/\\%}$t_n${\\small\\verb% ==> %}$t$\nthen {\\small\\verb%DISCH_TAC%} makes each $t_i$ into a separate assumption.\n\n\\item{\\bf Use:} Useful for splitting a goal up into manageable pieces.\nOften the best thing to do first is {\\small\\verb%REPEAT STRIP_TAC%},\nwhere \\ml{REPEAT} is the tactical that repeatedly applies a tactic\nuntil it fails (see Section~\\ref{avra_repeat}).\n\\end{itemize}\n\n\n\n\\subsection{Substitution}\n\n\\index{SUBST_TAC@\\ml{SUBST\\_TAC}|pin}\n\\begin{holboxed}\\begin{verbatim}\n   SUBST_TAC : thm list -> tactic\n\\end{verbatim}\\end{holboxed}\n\n\\begin{itemize}\n\n\\item{\\bf Summary:}\n{\\small\\verb%SUBST_TAC[|-%}$u_1${\\small\\verb%=%}$v_1${\\small\\verb%;%}$\\ldots${\\small\\verb%;|-%}$u_n${\\small\\verb%=%}$v_n${\\small\\verb%]%}\nchanges\\index{substitution, tactic for} each sub-term\n$t[u_1,\\ldots ,u_n]$ of the goal to\n$t[v_1,\\ldots ,v_n]$\nby substitution.\n\n\\item{\\bf Use:}\nUseful in situations where {\\small\\verb%REWRITE_TAC%}\n\\index{REWRITE_TAC@\\ml{REWRITE\\_TAC}} does too much,\nor would loop.\n\\end{itemize}\n\n\n\\subsection{Case analysis on a boolean term}\n\\index{case analysis, in HOL logic@case analysis, in \\HOL{} logic!tactics for|(}\n\n\\index{ASM_CASES_TAC@\\ml{ASM\\_CASES\\_TAC}|(}\n\\begin{holboxed}\\begin{verbatim}\n   ASM_CASES_TAC : term -> tactic\n\\end{verbatim}\\end{holboxed}\n\n\\begin{itemize}\n\n\\item{\\bf Summary:} \\ml{ASM\\_CASES\\_TAC} $u$ , where $u$ is a\nboolean-valued term, does case analysis on $u$.\n\n\\begin{center}\n\\begin{tabular}{c} \\\\\n$t$\n\\\\ \\hline \\hline\n$\\{u\\}t\\ \\ \\ \\ \\ \\{${\\small\\verb%~%}$u\\}t$\n\\\\\n\\end{tabular}\n\\end{center}\n\n\\item{\\bf Use:} Case analysis.\n\\end{itemize}\n\\index{ASM_CASES_TAC@\\ml{ASM\\_CASES\\_TAC}|)}\n\n\\subsection{Case analysis on a disjunction}\n\n\n\\begin{holboxed}\n\\index{DISJ_CASES_TAC@\\ml{DISJ\\_CASES\\_TAC}|pin}\n\\index{disjunction, in HOL logic@disjunction, in \\HOL{} logic!tactic for case splits on}\n\\begin{verbatim}\n   DISJ_CASES_TAC : thm_tactic\n\\end{verbatim}\\end{holboxed}\n\n\\begin{itemize}\n\n\\item{\\bf Summary:}\n{\\small\\verb%DISJ_CASES_TAC |- %}$u${\\small\\verb% \\/ %}$v$\nsplits a goal into two cases: one with $u$\nas an assumption\nand the other with $v$ as an assumption.\n\n\\begin{center}\n\\begin{tabular}{c} \\\\\n$t$\n\\\\ \\hline \\hline\n$\\{u\\}t\\ \\ \\ \\ \\ \\{v\\}t$\n\\\\\n\\end{tabular}\n\\end{center}\n\n\\item{\\bf Use:} Case analysis. The\ntactic {\\small\\verb%ASM_CASES_TAC%} is defined in \\ML{} by\n\n{\\small\\begin{verbatim}\n   let ASM_CASES_TAC t = DISJ_CASES_TAC(SPEC t EXCLUDED_MIDDLE)\n\\end{verbatim}}\n\n\n\\noindent where {\\small\\verb%EXCLUDED_MIDDLE%} is\nthe theorem {\\small\\verb%|- !t. t \\/ ~t%}.\n\n\\end{itemize}\n\\index{case analysis, in HOL logic@case analysis, in \\HOL{} logic!tactics for|)}\n\n\\subsection{Rewriting}\n\\label{rewrite}\n\n\\index{rewriting!main tactic for|(}\n\\begin{holboxed}\n\\index{REWRITE_TAC@\\ml{REWRITE\\_TAC}|pin}\n\\begin{verbatim}\n   REWRITE_TAC : thm list -> tactic\n\\end{verbatim}\\end{holboxed}\n\n\n\\begin{itemize}\n\\item{\\bf Summary:} {\\small\\verb%REWRITE_TAC[%}$th_1${\\small\\verb%;%}$\\ldots${\\small\\verb%;%}$th_n${\\small\\verb%]%}\ntransforms the term part of a goal by rewriting\nit with the given theorems $th_1$, $\\dots$, $th_n$,\nand the set of pre-proved standard tautologies\\index{tautologies, in rewriting tactic}.\n\n\n\\begin{center}\n\\begin{tabular}{c} \\\\\n$\\{t_1, \\ldots , t_m\\}t$\n\\\\ \\hline \\hline\n$\\{t_1, \\ldots , t_m\\}t'$\n\\\\\n\\end{tabular}\n\\end{center}\n\n\\noindent where $t'$ is obtained from $t$ as described.\n\n\\item{\\bf Use:} Advancing goals by using definitions and\npreviously proved theorems (lemmas).\\index{lemmas}\n\n\n\\item{\\bf Some other rewriting tactics} (based on {\\small\\verb%REWRITE_TAC%}) are:\n\\begin{enumerate}\n\\item {\\small\\verb%ASM_REWRITE_TAC%}\\index{ASM_REWRITE_TAC@\\ml{ASM\\_REWRITE\\_TAC}}\n adds the assumptions of the goal to the list of\ntheorems used for rewriting.\n\\index{PURE_ASM_REWRITE_TAC@\\ml{PURE\\_ASM\\_REWRITE\\_TAC}}\n\\item {\\small\\verb%PURE_ASM_REWRITE_TAC%} is like {\\small\\verb%ASM_REWRITE_TAC%}, but it\ndoesn't use any built-in rewrites.\n\\index{PURE_REWRITE_TAC@\\ml{PURE\\_REWRITE\\_TAC}}\n\\item {\\small\\verb%PURE_REWRITE_TAC%} uses neither the assumptions nor the built-in rewrites.\n\\index{FILTER_ASM_REWRITE_TAC@\\ml{FILTER\\_ASM\\_REWRITE\\_TAC}}\n\\item {\\small\\verb%FILTER_ASM_REWRITE_TAC %}$p${\\small\\verb% [%}$th_1${\\small\\verb%;%}$\\ldots${\\small\\verb%;%}$th_n${\\small\\verb%]%}\nsimplifies the goal by rewriting\nit with the explicitly given theorems $th_1$ , $\\dots$, $th_n$ ,\ntogether with those\nassumptions of the goal which satisfy the predicate $p$ and also\nthe standard rewrites.\n\n\\end{enumerate}\n\\end{itemize}\n\n\\index{rewriting!main tactic for|)}\n\n\n\\subsection{Resolution by Modus Ponens}\n\n\\index{implication, in HOL logic@implication, in \\HOL{} logic!tactics for}\n\\index{IMP_RES_TAC@\\ml{IMP\\_RES\\_TAC}|pin}\n\\begin{holboxed}\\begin{verbatim}\n   IMP_RES_TAC : thm -> tactic\n\\end{verbatim}\\end{holboxed}\n\n\\begin{itemize}\n\n\\index{resolution tactics}\n\\item{\\bf Summary:} {\\small\\verb%IMP_RES_TAC %}$th$ does a limited amount of\nautomated theorem proving in the form of forward inference; it\n`resolves' the theorem $th$ with the\nassumptions of the goal\nand adds any new results to the assumptions. The specification for\n\\ml{IMP\\_RES\\_TAC} is:\n\n\n\\begin{center}\n\\begin{tabular}{c} \\\\\n$\\{t_1,\\ldots,t_m\\}t$\n\\\\ \\hline \\hline\n$\\{t_1,\\ldots,t_m,u_1,\\ldots,u_n\\}t$\n\\\\\n\\end{tabular}\n\\end{center}\n\n\\noindent  where $u_1$, $\\dots$, $u_n$\nare derived by `resolving' the theorem $th$ with the existing assumptions\n$t_1$, $\\dots$, $t_m$.\nResolution in \\HOL{} is not classical resolution, but just Modus Ponens with\none-way pattern matching (not unification) and term and type instantiation. The\ngeneral case is where $th$ is of the canonical form\n\n$\\ \\ \\ ${\\small\\verb%|- !%}$x_1$$\\ldots x_p${\\small\\verb%.%}$v_1$ {\\small\\verb%==>%} $v_2$ {\\small\\verb%==>%} $\\ldots$ {\\small\\verb%==>%} $v_q$ {\\small\\verb%==>%} $v$\n\n\\noindent {\\small\\verb%IMP_RES_TAC %}$th$ then tries to specialize $x_1$,\n$\\dots$, $x_p$ in succession so that $v_1$, $\\dots$, $v_q$ match members of\n$\\{t_1,\\ldots ,t_m\\}$.  Each time a match is found for some antecedent $v_i$,\nfor $i$ successively equal to $1$, $2$, \\dots, $q$, a term and type\ninstantiation is made and the rule of Modus Ponens is applied.  If all the\nantecedents $v_i$ (for $1 \\leq i \\leq q$) can be dismissed in this way, then\nthe appropriate instance of $v$ is added to the assumptions. Otherwise, if only\nsome initial sequence $v_1$, \\dots, $v_k$ (for some $k$ where $1 < k < q$) of\nthe assumptions can be dismissed, then the remaining implication:\n\n$\\ \\ \\ ${\\small\\verb%|- %} $v_{k+1}$ {\\small\\verb%==>%} $\\ldots$ {\\small\\verb%==>%} $v_q$ {\\small\\verb%==>%} $v$\n\n\\noindent is added to the assumptions.\n\nFor a more detailed description of resolution and \\ml{IMP\\_RES\\_TAC}, see\n\\REFERENCE.  (See also the Cambridge \\LCF\\ Manual \\cite{new-LCF-man}.)\n\n\\item{\\bf Use:} Deriving new results from a previously proved implicative\ntheorem, in combination with the current assumptions, so that subsequent\ntactics can use these new results.\n\n\\end{itemize}\n\n\n\n\n\\subsection{Identity}\n\n\\index{ALL_TAC@\\ml{ALL\\_TAC}|pin}\n\\begin{holboxed}\\begin{verbatim}\n   ALL_TAC : tactic\n\\end{verbatim}\\end{holboxed}\n\n\\begin{itemize}\n\\index{identity tactic}\\index{tactics!identity for}\n\\index{THEN@\\ml{THEN}}\n\\item{\\bf Summary:} The identity tactic for the tactical {\\small\\verb%THEN%}\n(see Section~\\ref{tactics}). Useful for writing tactics.\n\n\\item{\\bf Use:}\n\\begin{enumerate}\n\\index{REPEAT@\\ml{REPEAT}}\n\\item Writing tacticals (see description of {\\small\\verb%REPEAT%}\nin Section~\\ref{tacticals}).\n\\index{THENL@\\ml{THENL}}\n\\item With {\\small\\verb%THENL%} (see Section~\\ref{avra_thenl});\nfor example, if tactic $T$ produces two subgoals\n$T_1$ is to be applied to the first while\nnothing is to be done to the second,\nthen $T${\\small\\verb% THENL[%}$T_1${\\small\\verb%;ALL_TAC]%} is the\ntactic required.\n\\end{enumerate}\n\\end{itemize}\n\n\\subsection{Null}\n\n\\index{NO_TAC@\\ml{NO\\_TAC}|pin}\n\\begin{holboxed}\\begin{verbatim}\n   NO_TAC : tactic\n\\end{verbatim}\\end{holboxed}\n\n\\begin{itemize}\n\\item{\\bf Summary:} Tactic that always fails.\n\n\\item{\\bf Use:} Writing tacticals.\n\\end{itemize}\n\n\n\\subsection{Splitting logical equivalences}\n\n\n\\begin{holboxed}\n\\index{EQ_TAC@\\ml{EQ\\_TAC}|pin}\n\\index{equality, in HOL logic@equality, in \\HOL{} logic!tactic for splitting}\n\\begin{verbatim}\n   EQ_TAC : tactic\n\\end{verbatim}\\end{holboxed}\n\n\\begin{itemize}\n\n\\item{\\bf Summary:}\n{\\small\\verb%EQ_TAC%}\nsplits an equational goal into two implications (the `if-case' and\nthe `only-if' case):\n\n\\begin{center}\n\n\n\n\\begin{tabular}{c} \\\\\n$u\\ \\ml{=}\\ v$\n\\\\ \\hline \\hline\n$u\\ \\ml{==>}\\ v\\ \\ \\ \\ \\ v\\ \\ml{==>}\\ u$\n\\\\\n\\end{tabular}\n\\end{center}\n\n\\item{\\bf Use:} Proving logical equivalences, \\ie\\ goals of the form\n``$u$\\ml{=}$v$'' where $u$ and $v$ are boolean terms.\n\n\\end{itemize}\n\n\\subsection{Solving existential goals}\n\n\n\\begin{holboxed}\n\\index{EXISTS_TAC@\\ml{EXISTS\\_TAC}|pin}\n\\index{existential quantifier, in HOL logic@existential quantifier, in \\HOL{} logic!tactic for}\n\\begin{verbatim}\n   EXISTS_TAC : term -> tactic\n\\end{verbatim}\\end{holboxed}\n\n\\begin{itemize}\n\n\\item{\\bf Summary:}\n{\\small\\verb%EXISTS_TAC \"%}$u${\\small\\verb%\"%}\nreduces an existential goal {\\small\\verb%!%}$x${\\small\\verb%. %}$t[x]$\nto the subgoal $t[u]$.\n\n\\begin{center}\n\\begin{tabular}{c} \\\\\n$\\ml{!}x\\ml{.} t[x]$\n\\\\ \\hline \\hline\n$t[u]$\n\\\\\n\\end{tabular}\n\\end{center}\n\n\\item{\\bf Use:} Proving existential goals.\n\n\\item{\\bf Comment:} \\ml{EXISTS\\_TAC} is a crude way of solving\nexistential goals, but it is the only built-in tactic for this\npurpose.  A more powerful approach uses Prolog-style `logic variables'\n(\\ie\\ meta-variables)\nthat can be progressively refined towards the eventual witness.\nImplementing this requires goals to contain an environment giving the binding\nof logic variables to terms. Details (in the context of \\LCF) are given\nin a  paper by Stefan Soko\\l owski \\cite{Stefan}.\n\n\\end{itemize}\n\\index{tactics!list of some|)}\n\n\\section{Tacticals}\n\\label{tacticals}\n\n\\index{tactics!tacticals for|(}\n\\index{tacticals|(}\n\\index{tacticals!list of some|(}\n\\index{tacticals!purpose of}\nA {\\it tactical\\/} is not represented by a single \\ML{} type,\nbut is in general\nan \\ML{} function that returns a tactic (or tactics) as result.\nTacticals may take parameters, and this is reflected in the variety of\n\\ML{} types that the built-in tacticals have.\nTacticals are used for building compound tactics.\\index{compound tactics, in HOL system@compound tactics, in \\HOL{} system}\n\\index{tactics!compound}\nSome important tacticals in\nthe \\HOL{} system\nare listed below.\nFor a complete list of the tacticals in \\HOL{} see \\REFERENCE.\n\n\\subsection{Alternation}\\index{alternation!of tactics|(}\\index{tactics!alternation of}\n\n\\index{ORELSE@\\ml{ORELSE}|pin}\n\\begin{holboxed}\\begin{verbatim}\n   ORELSE : tactic -> tactic -> tactic\n\\end{verbatim}\\end{holboxed}\n\n\nThe tactical {\\small\\verb%ORELSE%}\nis an \\ML{} infix. If $T_1$ and $T_2$ are tactics,\n\\index{tacticals!for alternation}\nthen the \\ML{} expression $T_1${\\small\\verb% ORELSE %}$T_2$\nevaluates to a tactic which applies $T_1$ unless that fails;\nif it fails,\nit applies $T_2$. \\ml{ORELSE} is defined in \\ML\\\nas a curried infix by\n\n\\begin{hol}\\begin{verbatim}\n   (T1 ORELSE T2) g =  T1 g ? T2 g\n\\end{verbatim}\\end{hol}\\index{alternation!of tactics|)}\n\n\n\\subsection{First success}\n\n\\index{FIRST@\\ml{FIRST}|pin}\n\\begin{holboxed}\\begin{verbatim}\n   FIRST : tactic list -> tactic\n\\end{verbatim}\\end{holboxed}\n\nThe tactical \\ml{FIRST} applies the first tactic, in a list\nof tactics, that succeeds.\n\n\\begin{hol}\\begin{alltt}\n   FIRST [\\(T\\sb{1}\\);\\(T\\sb{2}\\);\\(\\ldots\\);\\(T\\sb{n}\\)] = \\(T\\sb{1}\\) ORELSE \\(T\\sb{2}\\) ORELSE \\(\\ldots\\) ORELSE \\(T\\sb{n}\\)\n\\end{alltt}\\end{hol}\n\n\n\n\\subsection{Change detection}\n\n\\index{CHANGED_TAC@\\ml{CHANGED\\_TAC}|pin}\n\\begin{holboxed}\\begin{verbatim}\n   CHANGED_TAC : tactic -> tactic\n\\end{verbatim}\\end{holboxed}\n\n\n\\ml{CHANGED\\_TAC\\ $T$\\ $g$} fails if the subgoals\nproduced by $T$ are just \\ml{[$g$]}; otherwise it is equivalent\nto $T\\ g$. It is defined by the following, where\n{\\small\\verb%set_equal : * list -> * list -> bool%} tests whether two lists\ndenote the same set (\\ie\\ contain the same elements).\n\n\n\\begin{hol}\\begin{verbatim}\n   letrec CHANGED_TAC tac g =\n    let gl,p = tac g in\n    if set_equal gl [g] then fail else (gl,p)\n\\end{verbatim}\\end{hol}\n\n\n\n\\subsection{Sequencing}\n\\index{sequencing!of tactics|(}\n\\index{tacticals!for sequencing|(}\n\\index{tactics!sequencing of|(}\n\\index{THEN@\\ml{THEN}!ML implementation of@\\ML{} implementation of|(}\n\n\\begin{holboxed}\\index{THEN@\\ml{THEN}|pin}\n\\begin{verbatim}\n   THEN : tactic -> tactic -> tactic\n\\end{verbatim}\\end{holboxed}\n\n\nThe tactical {\\small\\verb%THEN%} is an \\ML{} infix. If $T_1$ and $T_2$ are tactics,\nthen the \\ML{} expression $T_1${\\small\\verb% THEN %}$T_2$ evaluates to a tactic\nwhich first applies $T_1$ and then applies $T_2$ to each subgoal produced by\n$T_1$. Its definition\n in \\ML{} is complex (and due to Milner)\\index{Milner, R.} but worth\nunderstanding as an exercise in \\ML.  It is an \\ML{} curried infix.\n\n\\begin{hol}\\begin{verbatim}\n   let ((T1:tactic) THEN (T2:tactic)) g =\n    let gl,p = T1 g\n    in\n    let gll,pl = split(map T2 gl)\n    in\n    (flat gll, (p o mapshape(map length gll)pl));;\n\\end{verbatim}\\end{hol}\n\n\\noindent Here are\nthe definitions of the \\ML{} functions \\ml{map}, \\ml{split}, \\ml{o},\n\\ml{length}, \\ml{flat} and \\ml{mapshape}:\n\n%\\begin{itemize}\n\\bigskip\n\n\\index{map@\\ml{map}}\n{\\small\\verb%map : (* -> **) -> * list -> ** list%}\n\n\\medskip\n\n\\begin{hol}\\begin{alltt}\n   map \\(f\\) [\\(x\\sb{1}\\);\\(\\ldots\\);\\(x\\sb{n}\\)]  =  [\\(f\\) \\(x\\sb{1}\\);\\(\\ldots\\);\\(f\\) \\(x\\sb{n}\\)]\n\\end{alltt}\\end{hol}\n\n\\medskip\n\n\\index{split@\\ml{split}}\n{\\small\\verb%split : (* # **) list -> (* list # ** list)%}\n\n\\medskip\n\n\\begin{hol}\\begin{alltt}\\   split[(\\(x\\sb{1}\\),\\(y\\sb{1}\\));\\(\\ldots\\);(\\(x\\sb{n}\\),\\(y\\sb{n}\\))]  =  ([\\(x\\sb{1}\\);\\(\\ldots\\);\\(x\\sb{n}\\)],[\\(y\\sb{1}\\);\\(\\ldots\\);\\(y\\sb{n}\\)])\n\\end{alltt}\\end{hol}\n\n\n\\medskip\n\n{\\small\\verb%$o : ((* -> **) # (*** -> *)) -> *** -> **$%}\n (an infix)\\index{function composition, in ML@function composition, in \\ML}\n\n\\medskip\n\n\\begin{hol}\n\\begin{alltt}\n   (\\(f\\) o \\(g\\)) \\(x\\)  =  \\(f\\)(\\(g\\) \\(x\\))\n\\end{alltt}\\end{hol}\n\\index{ function composition operator, in ML@{\\small\\verb+o+} (function composition operator, in \\ML)}\n\n\\medskip\n\n\\index{length@\\ml{length}}\n{\\small\\verb%length : * list -> int%}\n\n\\medskip\n\n\\begin{hol}\\begin{alltt}\n   length[\\(x\\sb{1}\\);\\(\\ldots\\);\\(x\\sb{n}\\)]  =  n\n\\end{alltt}\\end{hol}\n\n\\medskip\n\n\n{\\small\\verb%flat : (* list) list -> * list%}\\index{flat@\\ml{flat}}\n\n\n\\medskip\n\n\\begin{hol}\\begin{alltt}\n   flat[[\\({x\\sb{1}}\\sb{1}\\);\\(\\ldots\\);\\({x\\sb{1}}\\sb{m\\sb{1}}\\)];[\\({x\\sb{2}}\\sb{1}\\);\\(\\ldots\\);\\({x\\sb{2}}\\sb{m\\sb{2}}\\)];\\(\\ldots\\);[\\({x\\sb{n}}\\sb{1}\\);\\(\\ldots\\);\\({x\\sb{n}}\\sb{m\\sb{n}}\\)]] =\n    [\\({x\\sb{1}}\\sb{1}\\);\\(\\ldots\\);\\({x\\sb{1}}\\sb{m\\sb{1}}\\);\\({x\\sb{2}}\\sb{1}\\);\\(\\ldots\\);\\({x\\sb{2}}\\sb{m\\sb{2}}\\); \\(\\ldots\\) ;\\({x\\sb{n}}\\sb{1}\\);\\(\\ldots\\);\\({x\\sb{n}}\\sb{m\\sb{n}}\\)]\n\\end{alltt}\\end{hol}\n\n\\medskip\n\n{\\small\\verb%mapshape : int list -> (* list -> **) list -> * list -> ** list%}\\index{mapshape@\\ml{mapshape}}\n\n\n\\medskip\n\n\\begin{hol}\\begin{alltt}\n   mapshape\n    [\\(m\\sb{1}\\);\\(\\ldots\\);\\(m\\sb{n}\\)]\n    [\\(f\\sb{1}\\);\\(\\ldots\\);\\(f\\sb{n}\\)]\n    [\\({x\\sb{1}}\\sb{1}\\);\\(\\ldots\\);\\({x\\sb{1}}\\sb{m\\sb{1}}\\);\\({x\\sb{2}}\\sb{1}\\);\\(\\ldots\\);\\({x\\sb{2}}\\sb{m\\sb{2}}\\); \\(\\ldots\\) ;\\({x\\sb{n}}\\sb{1}\\);\\(\\ldots\\);\\({x\\sb{n}}\\sb{m\\sb{n}}\\)] =\n   [\\(f\\sb{1}\\)[\\({x\\sb{1}}\\sb{1}\\);\\(\\ldots\\);\\({x\\sb{1}}\\sb{m\\sb{1}}\\)];\\(f\\sb{2}\\)[\\({x\\sb{2}}\\sb{1}\\);\\(\\ldots\\);\\({x\\sb{2}}\\sb{m\\sb{2}}\\)]; \\(\\ldots\\) ;\\(f\\sb{n}\\)[\\({x\\sb{n}}\\sb{1}\\);\\(\\ldots\\);\\({x\\sb{n}}\\sb{m\\sb{n}}\\)]]\n\\end{alltt}\\end{hol}\n\n%\\end{itemize}\n\n\\bigskip\n\nSuppose \\ml{$T_1\\ g$ = ($gl$,$p$)} where \\ml{$gl$=[$g_1$;$\\ldots$;$g_n$]}.\nSuppose also that\nfor $i$ between $1$ and $n$ it is the case that\n\\ml{$T_2\\ g_i$ = ([${g_i}_1$;$\\ldots$;${g_i}_{m_i}$],$p_i$)}.\nThen \\ml{split(map $T_2$ $gl$)} will evaluate to the\npair \\ml{($gll$,$pl$)} of a subgoal list and a proof function, where\n\n\\bigskip\n\n\\ml{$gll$ = [[${g_1}_1$;$\\ldots$;${g_1}_{m_1}$];[${g_2}_1$;$\\ldots$;${g_2}_{m_2}$];\n$\\ \\ldots\\ $;[${g_n}_1$;$\\ldots$;${g_n}_{m_n}$]]}\n\n\\bigskip\n\n\\noindent and\n\\ml{$pl$ = [$p_1$;$\\ldots$;$p_n$]}. Note that\n\n\\bigskip\n\n\\ml{map length $gll$ = [$m_1$;$\\ldots$;$m_n$]}\n\n\\bigskip\n\n\\noindent and that\n\n\\bigskip\n\n\\ml{flat $gll$ = [${g_1}_1$;$\\ldots$;${g_1}_{m_1}$;${g_2}_1$;$\\ldots$;${g_2}_{m_2}$;\n$\\ \\ldots\\ $;${g_n}_1$;$\\ldots$;${g_n}_{m_n}$]}\n\n\\bigskip\n\nSuppose now that, for $i$ between $1$ and $n$, the theorems\n${th_i}_1$, $\\dots$, ${th_i}_{m_i}$ achieve\nthe goals ${g_i}_1$, $\\dots$, ${g_i}_{m_i}$, respectively.\nIt will follow that if $T_2$ is valid\nthen for $i$ between $1$ and $n$\nthe result of applying $p_i$ to the list of\ntheorems \\ml{[${th_i}_1$;$\\ldots$;${th_i}_{m_i}$]}\nwill be a theorem, $th_i$ say, which achieves\n$g_i$.\nNow if $T_1$ is valid then \\ml{$p$[$th_1$;$\\ldots$;$th_n$]}\nwill evaluate to a theorem,\n$th$ say,\nthat achieves the goal $g$. Thus\n\n\\begin{hol}\\begin{alltt}\n    \\(p\\)\n    (mapshape\n     (map length \\(gll\\))\n     \\(pl\\)\n     [\\({th\\sb{1}}\\sb{1}\\);\\(\\ldots\\);\\({th\\sb{1}}\\sb{m\\sb{1}}\\);\\({th\\sb{2}}\\sb{1}\\);\\(\\ldots\\);\\({th\\sb{2}}\\sb{m\\sb{2}}\\);\\(\\ \\ldots\\ \\) ;\\({th\\sb{n}}\\sb{1}\\);\\(\\ldots\\);\\({th\\sb{n}}\\sb{m\\sb{n}}\\)]) =\n\n    \\(p\\)([\\(p\\sb{1}\\)[\\({th\\sb{1}}\\sb{1}\\);\\(\\ldots\\);\\({th\\sb{1}}\\sb{m\\sb{1}}\\)];\\(p\\sb{2}\\)[\\({th\\sb{2}}\\sb{1}\\);\\(\\ldots\\);\\({th\\sb{2}}\\sb{m\\sb{2}}\\)];\\(\\ \\ldots\\ \\);\\(p\\sb{n}\\)[\\({th\\sb{n}}\\sb{1}\\);\\(\\ldots\\);\\({th\\sb{n}}\\sb{m\\sb{n}}\\)]]) =\n\n    \\(p\\)([\\(th\\sb{1}\\);\\(\\ldots\\);\\(th\\sb{n}\\)]) =\n\n    \\(th\\)\n\\end{alltt}\\end{hol}\n\nThis shows that\n\\index{justifications, in goal-directed proof search!THEN example of@\\ml{THEN} example of}\n\\index{proof functions (same as justifications, validations)!THEN example of@\\ml{THEN} example of}\n\\ml{$p$ o mapshape(map length $gll$)$pl$}\nis a function that, when\napplied to a list of theorems respectively\nachieving \\ml{flat $gll$}, returns a theorem\n(namely $th$) that achieves $g$.\\index{sequencing!of tactics|)}\n\\index{tacticals!for sequencing|)}\n\\index{THEN@\\ml{THEN}!ML implementation of@\\ML{} implementation of|)}\n\n\\subsection{Selective sequencing}\n\n\\index{THENL@\\ml{THENL}}\n\\begin{holboxed}\\begin{verbatim}\n   THENL : tactic -> tactic list -> tactic\n\\end{verbatim}\\end{holboxed}\n\\label{avra_thenl}\n\n\\index{selective sequencing tactical}\nIf tactic $T$ produces $n$ subgoals and $T_1$, $\\dots$,\n$T_n$ are tactics\nthen $T${\\small\\verb% THENL [%}$T_1${\\small\\verb%;%}$\\ldots${\\small\\verb%;%}$T_n${\\small\\verb%]%}\nis a tactic which first applies $T$ and then\napplies $T_i$ to the $i$th subgoal produced by $T$.\nThe tactical {\\small\\verb%THENL%} is useful if one wants to apply different\ntactics to different subgoals.\n\nHere is the definition of \\ml{THENL}:\n\n\\begin{hol}\\begin{verbatim}\n      let ((T:tactic) THENL (Tl:tactic list)) g =\n       let gl,p = T g\n       in\n       let gll,pl = (split(map (\\(T,g). T g) Tgl)\n                      where Tgl = combine(Tl,gl) ? failwith `THENL`)\n       in\n       (flat gll, (p o mapshape(map length gll)pl))\n\\end{verbatim}\\end{hol}\n\n\\noindent The understanding of this procedure is left as an exercise!\\index{tactics!sequencing of|)}\n\n\\subsection{Successive application}\n\n\n\n\\begin{holboxed}\n\\index{EVERY, the ML function@\\ml{EVERY}, the \\ML{} function|pin}\n\\begin{verbatim}\n   EVERY : tactic list -> tactic\n\\end{verbatim}\\end{holboxed}\n\n\\index{tacticals!for successive application}\n\\index{successive application!tactical for}\nThe tactical \\ml{EVERY} applies a list of tactics one after the other.\n\n\n\\begin{hol}\\begin{alltt}\n   EVERY [\\(T\\sb{1}\\);\\(T\\sb{2}\\);\\(\\ldots\\);\\(T\\sb{n}\\)] = \\(T\\sb{1}\\) THEN \\(T\\sb{2}\\) THEN \\(\\ldots\\) THEN \\(T\\sb{n}\\)\n\\end{alltt}\\end{hol}\n\n\n\n\\subsection{Repetition}\n\n\\begin{holboxed}\\index{REPEAT@\\ml{REPEAT}|pin}\n\\begin{verbatim}\n   REPEAT : tactic -> tactic\n\\end{verbatim}\\end{holboxed}\n\\label{avra_repeat}\n\nIf $T$ is a\ntactic then {\\small\\verb%REPEAT %}$T$ is a tactic\\index{tactics!repetition of}\n\\index{tacticals!for repetition}\\index{repetition!of tactics}\nthat repeatedly applies\n$T$ until it fails. It is defined in \\ML{} by:\n\n{\\small\\baselineskip\\HOLSpacing\\begin{verbatim}\n   letrec REPEAT T g = ((T THEN REPEAT T) ORELSE ALL_TAC) g\n\\end{verbatim}}\n\n\\noindent (The extra argument {\\small\\verb%g%} is needed because \\ML{} does not use\nlazy evaluation.)\n\\index{tacticals|)}\n\\index{tacticals!list of some|)}\n\\index{tactics!tacticals for|)}\n\n\\section{Tactics for manipulating assumptions}\n\\label{asm-manip}\n\n\\index{tactics!for manipulating assumptions|(}\nThere are in general two kinds of tactics\\index{tactics!term transforming}\\index{tactics!assumption transforming}\n in \\HOL: those that transform the\nconclusion of a goal without affecting the assumptions, and those that\ndo (also or only) affect the assumptions.  The various tactics that\nrewrite\\index{rewriting!main tactic for}\n are typical of the first class; those that do `resolution'\n\\index{resolution tactics} belong to\nthe second.  Often, many of the steps of a proof in \\HOL{} are carried\nout `behind the scenes' on the assumptions, by tactics of the second sort.\nA tactic that in some way changes the assumptions must also have a\njustification that `knows how' to restore the corresponding hypotheses of\nthe theorem achieving the subgoal. All of this is explicit, and can be\nexamined by a user moving about the subgoal-proof tree.\\footnote{The current\nsubgoal package makes this difficult, but the point still holds.}\nUsing these tactics in the most straightforward way, the assumptions at any\npoint in a goal-directed proof, \\ie\\ at any node in the subgoal tree,\n\\index{subgoal tree!in proof construction}\n\\index{tree of subgoals, in proof construction} form\nan unordered record of every assumption made, but not yet dismissed, up to that\npoint.\n\nIn practice, the straightforward use of assumption-changing\n\\index{assumptions!role of, in goal directed proof}\ntactics,\nwith the tools currently provided in \\HOL, presents at\nleast two difficulties.  The first is that assumption sets can grow to an\nunwieldy size, the number and/or length of terms making them difficult to\nread.  In addition, forward-search tactics such as resolution often add at least\nsome assumptions that are never subsequently used, and these have to be\ncarried along with the useful assumptions; the straightforward\nmethod provides no ready way of intercepting their arrival.\nLikewise, there is no straightforward way of discarding\n\\index{discarding assumptions}\n\\index{assumptions!discarding of, in proofs}\nassumptions after they have been used and are merely adding to the clutter.\nAlthough perhaps against the straightforward spirit, this is a perfectly valid\nstrategy, and\nrequires no more than a way of denoting\nthe specific assumptions to be discarded. That, however,\nraises the more general problem of denoting\\index{assumptions!denoting of, in proofs}\\index{denoting assumptions} assumptions in the first place.\nAssumptions are also denoted\nso that they can be\nmanipulated: given as parameters, combined to draw inferences, \\etc\\  The only\nstraightforward way to denote them in the existing system is to supply\ntheir quoted text.  Though adequate, this\nmethod may result in bulky \\ML{} expressions; and it may take some effort to present the text\ncorrectly (with necessary type information, \\etc).\n\nAs always in \\HOL, there are quite a few ways around the various difficulties.\nOne approach, of course, is the one intended in the original\ndesign of\\index{LCF@\\LCF!Edinburgh} Edinburgh \\LCF,\nand advocates the rationale for providing a full programming language, \\ML,\n\\index{ML@\\ML!purpose of, in HOL system@purpose of, in \\HOL{} system}\nrather than a simple proof command set: that is for the user to\nimplement new tactics in \\ML.  For example, resolution tactics can be adapted\nby the user to add new assumptions more selectively; and case analysis tactics\nto make direct replacements without adding case assumptions.\nThis, again, is adequate, but can involve the user in extensive amounts of\nprogramming, and in debugging exercises for which there is no\nsystem support.\n\nShort of implementing new tactics, two other standard\napproaches are reflected in the current system.  Both were originally\ndeveloped for Cambridge \\LCF\\ \\cite{lcp_rewrite,new-LCF-man}; both reflect\nfresh views of the assumptions; and both rely on tacticals\\index{tacticals!purpose of} that transform\ntactics.  The two approaches are\npartly but not completely complementary.\n\nThe first\napproach, described in this section, implicitly regards the assumption\nset, already represented as a list, as a stack, with a {\\it pop\\/}\noperation, so that the assumption at the top of the stack can be (i) discarded\nand (ii) denoted without explicit quotation.  (The corresponding {\\it push\\/}\nadds new assumptions at the head of the list.)\nThe stack can be generalized to an array to allow for access to\narbitrary assumptions.\n\nThe other approach, described in Section~\\ref{tacont},\ngives a way of intercepting and manipulating results without them necessarily\nbeing added as assumptions in the first place.  The two approaches can\nbe combined in \\HOL{} interactions.\n\n\n\\subsection{Theorem continuations with popping}\n\\label{avra_manip1}\n\nThe first proof style, that of popping assumptions\n\\index{popping, of assumptions}\nfrom the assumption `stack',\n\\index{assumptions!as stack}\n\\index{stack, of assumptions}\nis illustrated using its main tool: the tactical \\ml{POP\\_ASSUM}.\n\n\\index{POP_ASSUM@\\ml{POP\\_ASSUM}|pin}\n\\begin{holboxed}\\begin{verbatim}\n   POP_ASSUM : (thm -> tactic) -> tactic\n\\end{verbatim}\\end{holboxed}\n\n\\noindent Given a function $f$\\ml{:thm -> tactic}, the tactic\n\\ml{POP\\_ASSUM}\\ $f$ applies $f$ to the (assumed) first\nassumption of a goal (\\ie\\ to the top element of the assumption stack)\nand then applies the tactic created thereby to the original goal\nminus its top assumption:\n\n\\begin{hol}\\begin{alltt}\n   POP_ASSUM \\(f\\) ([\\(t\\sb{1}\\);\\(\\ldots\\);\\(t\\sb{n}\\)],\\(t\\)) = \\(f\\) (ASSUME \\(t\\sb{1}\\)) ([\\(t\\sb{2}\\);\\(\\ldots\\);\\(t\\sb{n}\\)],\\(t\\))\n\\end{alltt}\\end{hol}\n\n\\noindent \\ML{} functions such as $f$,\nwith type \\ml{thm -> tactic}, abbreviated to \\ml{thm\\_tactic},\n\\index{thm_tactic@\\ml{thm\\_tactic}}\nare called theorem continuations,\n\\index{theorem continuations} suggesting the fact that they\ntake theorems and then continue the proof.\\footnote{There is a superficial analogy\nwith continuations in denotational semantics.}\nThe use of \\ml{POP\\_ASSUM}\\ can be illustrated by applying it\nto a particular tactic, namely \\ml{DISCH\\_TAC} (Section~\\ref{avradisch}).\n\n\\index{DISCH_TAC@\\ml{DISCH\\_TAC}}\n\\begin{holboxed}\\begin{verbatim}\n   DISCH_TAC : tactic\n\\end{verbatim}\\end{holboxed}\n\n\\noindent On a goal whose conclusion is an implication $u \\imp v$,\n\\ml{DISCH\\_TAC} reflects the natural strategy of attempting to prove\n$v$ under the assumption $u$, the discharged antecedent.  For example,\nsuppose it were required to prove that $(n = 0) \\imp (n\\times n = n)$:\n\n\\setcounter{sessioncount}{1}\n\\begin{session}\\begin{verbatim}\n#g \"(n = 0) ==> (n * n = n)\";;\n\"(n = 0) ==> (n * n = n)\"\n\n() : void\n\n#e DISCH_TAC;;\nOK..\n\"n * n = n\"\n    [ \"n = 0\" ]\n\\end{verbatim}\\end{session}\n\n\\noindent Application of \\ml{DISCH\\_TAC} to the goal produces one subgoal,\nas shown, with the added assumption. To engage the assumption\nas a simple substitution, the tactic \\ml{SUBST1\\_TAC} is useful\n(see \\REFERENCE\\ for details).\n\n\n\\index{SUBST1_TAC@\\ml{SUBST1\\_TAC}|pin}\n\\begin{holboxed}\\begin{verbatim}\n   SUBST1_TAC : thm_tactic\n\\end{verbatim}\\end{holboxed}\n\n\\noindent \\ml{SUBST1\\_TAC} expects a theorem with an equational conclusion, and\nsubstitutes accordingly, into the conclusion of the goal. At this\npoint in the session, the tactical\n\\ml{POP\\_ASSUM} is applied to\n\\ml{SUBST1\\_TAC} to form a new tactic.\nThe new tactic is applied to the current subgoal.\n\n\\begin{session}\\begin{verbatim}\n#top_goal();;\n([\"n = 0\"], \"n * n = n\") : goal\n\n#e(POP_ASSUM SUBST1_TAC);;\nOK..\n\"0 * 0 = 0\"\n\\end{verbatim}\\end{session}\n\n\\noindent The result, as shown, is that the assumption is used as a\nsubstitution rule and then discarded.\n\\index{discarding assumptions}\n\\index{assumptions!discarding of, in proofs}\nThe one subgoal therefore has no\nassumptions on its stack.  The two tactics used thus far could be combined\ninto one using the tactical \\ml{THEN}:\\index{THEN@\\ml{THEN}}\n\n\\setcounter{sessioncount}{1}\n\\begin{session}\\begin{verbatim}\n#g \"(n = 0) ==> (n * n = n)\";;\n\"(n = 0) ==> (n * n = 0)\"\n\n() : void\n\n#e(DISCH_TAC THEN POP_ASSUM SUBST1_TAC);;\nOK..\n\"0 * 0 = 0\"\n\\end{verbatim}\\end{session}\n\n\\noindent The goal can now be solved by rewriting with a fact of arithmetic:\n\n\\begin{session}\\begin{verbatim}\n#e(REWRITE_TAC[MULT_CLAUSES]);;\nTheorem MULT_CLAUSES autoloaded from theory `arithmetic`.\nMULT_CLAUSES =\n|- !m n.\n    (0 * m = 0) /\\\n    (m * 0 = 0) /\\\n    (1 * m = m) /\\\n    (m * 1 = m) /\\\n    ((SUC m) * n = (m * n) + n) /\\\n    (m * (SUC n) = m + (m * n))\n\nOK..\ngoal proved\n|- 0 * 0 = 0\n|- (n = 0) ==> (n * n = n)\n\\end{verbatim}\\end{session}\n\n\\noindent A single tactic can, of course, be written to solve the goal:\n\n\\setcounter{sessioncount}{1}\n\\begin{session}\\begin{verbatim}\n#g \"(n = 0) ==> (n * n = n)\";;\n\"(n = 0) ==> (n * n = n)\"\n\n() : void\n\n#e(DISCH_TAC THEN POP_ASSUM SUBST1_TAC THEN REWRITE_TAC[MULT_CLAUSES]);;\nTheorem MULT_CLAUSES autoloaded from theory `arithmetic`.\nMULT_CLAUSES =\n|- !m n.\n    (0 * m = 0) /\\\n    (m * 0 = 0) /\\\n    (1 * m = m) /\\\n    (m * 1 = m) /\\\n    ((SUC m) * n = (m * n) + n) /\\\n    (m * (SUC n) = m + (m * n))\n\nOK..\ngoal proved\n|- (n = 0) ==> (n * n = n)\n\\end{verbatim}\\end{session}\n\nThis example illustrates how the tactical \\ml{POP\\_ASSUM} provides\naccess\\index{assumptions!denoting of, in proofs}\n\\index{denoting assumptions}\nto the top of the assumption `stack' (a capability that\nis useful, obviously, only when the\nmost recently pushed assumption is the very one required).\nTo accomplish this access in the straightforward way would\nrequire some more awkward\n\\index{assumptions!explicit} construct, with explicit assumptions:\n\n\\setcounter{sessioncount}{1}\n\\begin{session}\\begin{verbatim}\n#g \"(n = 0) ==> (n * n = n)\";;\n\"(n = 0) ==> (n * n = n)\"\n\n() : void\n\n#e(DISCH_TAC);;\nOK..\n\"n * n = n\"\n    [ \"n = 0\" ]\n\n() : void\n\n#e(SUBST1_TAC(ASSUME \"n = 0\"));;\nOK..\n\"0 * 0 = 0\"\n    [ \"n = 0\" ]\n\\end{verbatim}\\end{session}\n\nIn contrast to the above, the popping example also illustrates the\nconvenient disappearance of an assumption no longer required, by removing it\nfrom the stack at the moment when it is accessed and used. This is valid\nbecause any theorem that achieves the subgoal\nwill still achieve the original goal. Discarding\\index{discarding assumptions}\\index{assumptions!discarding of, in proofs} assumptions\nis a separate issue from accessing them;\nthere could, if one liked, be another\ntactical that produced a similar tactic on a theorem continuation\nto \\ml{POP\\_ASSUM} but which did not pop the\nstack.\n\nFinally, \\ml{POP\\_ASSUM} $f$ induces case splits where $f$ does.  To prove\n$(n=0 \\disj n=1) \\imp (n\\times n = n)$, the function \\ml{DISJ\\_CASES\\_TAC}\ncan be used. The tactic\n\n\\ \\ \\ml{DISJ\\_CASES\\_TAC\\ |- $p$}{\\small\\verb% \\/ %}\\ml{$q$}\n\n\\noindent splits a goal into two subgoals that have\n$p$ and $q$, respectively, as new assumptions.\n\n\n\\setcounter{sessioncount}{1}\n\\begin{session}\\begin{verbatim}\n#g \"((n = 0) \\/ (n = 1)) ==> (n * n = n)\";;\n\"(n = 0) \\/ (n = 1) ==> (n * n = n)\"\n\n() : void\n\n#e DISCH_TAC;;\nOK..\n\"n * n = n\"\n    [ \"(n = 0) \\/ (n = 1)\" ]\n\n() : void\n\n#backup();;\n\"(n = 0) \\/ (n = 1) ==> (n * n = n)\"\n\\end{verbatim}\\end{session}\n\\vfill\n\\newpage\n\\begin{session}\\begin{verbatim}\n#e(DISCH_TAC THEN POP_ASSUM DISJ_CASES_TAC);;\nOK..\n2 subgoals\n\"n * n = n\"\n    [ \"n = 1\" ]\n\n\"n * n = n\"\n    [ \"n = 0\" ]\n\n() : void\n\n#backup();;\n\"(n = 0) \\/ (n = 1) ==> (n * n = n)\"\n\n() : void\n\n#e(DISCH_TAC THEN POP_ASSUM DISJ_CASES_TAC THEN POP_ASSUM SUBST1_TAC);;\nOK..\n2 subgoals\n\"1 * 1 = 1\"\n\n\"0 * 0 = 0\"\n\\end{verbatim}\\end{session}\n\nAs noted earlier, \\ml{POP\\_ASSUM} is useful when an assumption\nis required that is still at the top of the stack,\nas in the examples.  However, it is often\nnecessary to access assumptions made at arbitrary previous times, in order to\ngive them as parameters, combine them, \\etc\\ The stack approach can be\nextended to such cases by re-conceiving the stack as an array\\index{assumptions!as array}\\index{array, of assumptions}, and by\nuse of the tactical \\ml{ASSUM\\_LIST}:\\index{ASSUM_LIST@\\ml{ASSUM\\_LIST}|(}\n\n\\begin{hol}\\begin{verbatim}\n   ASSUM_LIST : (thm list -> tactic ) -> tactic\n\\end{verbatim}\\end{hol}\n\n\\noindent where\n\n\\begin{hol}\\begin{alltt}\n   ASSUM_LIST \\m{f} ([\\m{t\\sb{1}};...;\\m{t\\sb{n}}],\\m{t}) = \\m{f}([ASSUME \\m{t\\sb{1}};...;ASSUME \\m{t\\sb{n}}])\n\\end{alltt}\\end{hol}\n\n\\noindent That is, given a function $f$, \\ml{ASSUM\\_LIST}$\\ f$ forms a new tactic\nby applying $f$ to the list of (assumed) assumptions of a goal, then applies\nthe resulting tactic to the goal.  For example, a tactic of the form\n{\\small\\verb%ASSUM_LIST (\\thl.%}$\\ f\\ $\\ml{(el\\ $i$\\ thl))} applies the\nfunction $f$ to the $i$th assumption of a goal to produce a new tactic, then\napplies the new tactic to the goal.\nAgain, \\ml{ASSUM\\_LIST REWRITE\\_TAC} is a tactic that engages all of the\ncurrent assumptions as rewrite rules.\nIn this way, the array approach\nenables arbitrary assumptions to be accessed; and in particular,\nspecific assumptions to be accessed by location using the function \\ml{el}.\n\nTo illustrate the use of \\ml{ASSUM\\_LIST}, suppose it were required to prove\nsomething different: \\index{ASSUM_LIST@\\ml{ASSUM\\_LIST}|)}\nthat $(\\forall m.\\ m + n = m) \\imp (n \\times n = n)$.  Suppose\nalso that the arithmetic fact \\ml{ADD\\_INV\\_{0}} is already known: namely, that\n$\\forall m\\ n.\\ (m + n = m) \\imp (n = 0)$. After discharging the assumption,\nthe conclusion of the theorem \\ml{ADD\\_INV\\_{0}} is imported as an\nassumption, occupying first place in the array.\n\n\\setcounter{sessioncount}{1}\n\\begin{session}\\begin{verbatim}\n#g \"(!m. m + n = m) ==> (n * n = n)\";;\n\"(!m. m + n = m) ==> (n * n = n)\"\n\n() : void\n\n#e(DISCH_TAC);;\nOK..\n\"n * n = n\"\n    [ \"!m. m + n = m\" ]\n\n() : void\n\n#e(ASSUME_TAC ADD_INV_0);;\nTheorem ADD_INV_0 autoloaded from theory `arithmetic`.\nADD_INV_0 = |- !m n. (m + n = m) ==> (n = 0)\n\nOK..\n\"n * n = n\"\n    [ \"!m. m + n = m\" ]\n    [ \"!m n. (m + n = m) ==> (n = 0)\" ]\n\\end{verbatim}\\end{session}\n\n\\noindent The problem is now to combine the two assumptions to produce the\nobvious conclusion. That requires denoting\n\\index{denoting assumptions}\n\\index{assumptions!denoting of, in proofs} them, for which \\ml{ASSUM\\_LIST}\nprovides the means. Finally,\n\\ml{ASSUME\\_TAC} places the conclusion of the new result in the assumptions.\n(The \\ML{} function \\ml{el: int -> * list -> *} is used here to select a\nnumbered element of a list.)\n\n\\begin{session}\\begin{verbatim}\n#e(ASSUM_LIST(\\thl. ASSUME_TAC\n                       (MP (SPECL [\"m:num\";\"n:num\"] (el 1 thl))\n                           (SPEC \"m:num\"(el 2 thl)))));;\n##OK..\n\"n * n = n\"\n    [ \"!m. m + n = m\" ]\n    [ \"!m n. (m + n = m) ==> (n = 0)\" ]\n    [ \"n = 0\" ]\n\\end{verbatim}\\end{session}\n\n\\noindent The goal can now be solved as in the previous example.\n\nTo access the\ntwo particular assumptions in the straightforward way would again require quoting\ntheir text. To access all of them (to pass to \\ml{REWRITE\\_TAC}, for\ninstance) would require quoting all of them.\n\n\\ml{ASSUM\\_LIST} addresses the issue of accessing assumptions,\nbut not the issue of discarding them.  A related function generalizes\n\\ml{POP\\_ASSUM} to discard them as well:\n\n\\begin{hol}\\begin{verbatim}\n   POP_ASSUM_LIST : (thm list -> tactic ) -> tactic\n\\end{verbatim}\\end{hol}\n\n\\noindent \\ml{POP\\_ASSUM\\_LIST}\n\\index{POP_ASSUM_LIST@\\ml{POP\\_ASSUM\\_LIST}}\nresembles \\ml{ASSUM\\_LIST} except in removing\nall of the old assumptions of the subgoal, the way that \\ml{POP\\_ASSUM}\nremoves the most recent.  (Thus \\ml{POP\\_ASSUM} is no more than a special case\nof \\ml{POP\\_ASSUM\\_LIST} that selects the first element of those supplied\nand re-assumes the others.)\n\n\\begin{hol}\\begin{alltt}\n   POP_ASSUM_LIST \\(f\\) ([\\(t\\sb{1}\\);\\(\\ \\ldots\\ \\);\\(t\\sb{n}\\)],\\(t\\)) =  \\(f\\) [ASSUME \\(t\\sb{1}\\);\\(\\ \\ldots\\ \\);ASSUME \\(t\\sb{n}\\)] ([],t)\n\\end{alltt}\\end{hol}\n\n\\noindent This is used when the existing assumptions have served\ntheir purpose and can be discarded, as in the current example:\n\n\\begin{session}\\begin{verbatim}\n#backup();;\n\"n * n = n\"\n    [ \"!m. m + n = m\" ]\n    [ \"!m n. (m + n = m) ==> (n = 0)\" ]\n\n() : void\n\n#e(POP_ASSUM_LIST(\\thl. ASSUME_TAC\n                           (MP (SPECL [\"m:num\";\"n:num\"] (el 1 thl))\n                               (SPEC \"m:num\"(el 2 thl)))));;\n##OK..\n\"n * n = n\"\n    [ \"n = 0\" ]\n\\end{verbatim}\\end{session}\n\n\\noindent This leaves only the one assumption vital to solving the goal,\nas before. In some contexts, the new result is required as an assumption,\nbut here it can be used immediately:\n\n\\begin{session}\\begin{verbatim}\n#backup();;\n\"n * n = n\"\n    [ \"!m. m + n = m\" ]\n    [ \"!m n. (m + n = m) ==> (n = 0)\" ]\n\n() : void\n\n#e(POP_ASSUM_LIST(\\thl. SUBST1_TAC\n                           (MP (SPECL [\"m:num\";\"n:num\"] (el 1 thl))\n                               (SPEC \"m:num\"(el 2 thl)))));;\n##OK..\n\"0 * 0 = 0\"\n\\end{verbatim}\\end{session}\n\n\\noindent \\ml{POP\\_ASSUM\\_LIST} can, of course,\ntake any function of appropriate\ntype, but is in fact often used in conjunction with the element-selecting\nfunctions. Function composition occasionally allows a more\ncompact expression to be written.\n\nThe array view (of which the stack view is a special case)\ngives a way in which unnecessary assumptions can\nbe dropped, and assumptions can be accessed, individually if necessary,\nusing tacticals.\nAlthough this approach can be effective, as illustrated, it does\ntend to rely on the ordering of the representation of the assumption\n\\index{assumptions!importance of ordering of} set.\n(That is, \\ml{POP\\_ASSUM} necessarily does, while the other two provide the\ntemptation!) A minor drawback of this reliance is that tactics are then\nsensitive to changes that alter the order or composition of the assumptions;\nfor example, changes in the implementation of \\HOL, modifications of\nexisting tactics, and so on.\nHowever, that sensitivity is not so serious in any one incarnation of \\HOL;\nthere is a logical viewpoint that regards the assumptions (sequents) as\nordered anyway.\nA more serious problem is that order-sensitive tactics are meaningful\nonly during interactive sessions; to reconstruct the assumptions from\nthe \\ML{} text and the original goal alone is generally difficult,\nand more so when assumptions are denoted by location.\nThis means that (i) the resulting tactics cannot easily be generalized\nfor use in other contexts, and (ii) the \\ML{} text does not supply\nuseful documentation\n\\index{tactics!as documentation of proofs} of the solution of the goal.\nAlso, as shown in the last example, it it slightly unsatisfactory\nto push and subsequently pop assumptions, especially in immediate succession,\nwhere this could be avoided.\n\nTwo other tacticals that can be used to manipulate the assumption list are\n{\\small\\verb%FIRST_ASSUM%} and {\\small\\verb%EVERY_ASSUM%}.\nThese are characterized by:\n\n\\index{FIRST_ASSUM@\\ml{FIRST\\_ASSUM}}\n\\index{EVERY_ASSUM@\\ml{EVERY\\_ASSUM}}\n\\begin{hol}\\begin{alltt}\n   FIRST_ASSUM \\(f\\) ([\\(t\\sb{1}\\); \\(\\ldots\\) ;\\(t\\sb{n}\\)], \\(t\\))  =\n    (\\(f\\)(ASSUME \\(t\\sb{1}\\)) ORELSE \\(\\ldots\\) ORELSE \\(f\\)(ASSUME \\(t\\sb{n}\\))) ([\\(t\\sb{1}\\); \\(\\ldots\\) ;\\(t\\sb{n}\\)], \\(t\\))\n\n   EVERY_ASSUM \\(f\\) ([\\(t\\sb{1}\\); \\(\\ldots\\) ;\\(t\\sb{n}\\)], \\(t\\))  =\n    (\\(f\\)(ASSUME \\(t\\sb{1}\\)) THEN \\(\\ldots\\) THEN  \\(f\\)(ASSUME \\(t\\sb{n}\\))) ([\\(t\\sb{1}\\); \\(\\ldots\\) ;\\(t\\sb{n}\\)], \\(t\\))\n\\end{alltt}\\end{hol}\n\n\n\\subsection{Theorem continuations without popping}\n\\label{tacont}\n\nThe idea of the second approach is suggested by the way the array-style\ntacticals\\index{tacticals!purpose of} supply a list of theorems (the assumed assumptions)\nto a function.  These tacticals use the function to\ninfer new\nresults from the list of theorems, and then to do something with the\nresults. In some cases,\n\\eg\\ the last example, the assumptions need never have been made in the\nfirst place, which suggests a different use of tacticals.\nThe original example for \\ml{POP\\_ASSUM}\nillustrates this: namely, to show that $(n = 0) \\imp (n\\times n = n)$.  Here,\ninstead of discharging the antecedent by applying\n\\ml{DISCH\\_TAC} to the goal, which adds the antecedent as an assumption\nand returns the consequent as the conclusion,\nand {\\it then\\/} supplying the (assumed) added assumption to the\ntheorem continuation \\ml{SUBST1\\_TAC} and\ndiscarding it at the same time,\na tactical called \\ml{DISCH\\_THEN} is applied to \\ml{SUBST1\\_TAC} directly.\n\\ml{DISCH\\_THEN} transforms \\ml{SUBST1\\_TAC} into\na new tactic: one that applies \\ml{SUBST1\\_TAC} directly to the (assumed)\nantecedent, and the resulting tactic to a subgoal with no new\nassumptions and the consequent as its conclusion:\n\\vfill\n\\newpage\n\n\\setcounter{sessioncount}{1}\n\\begin{session}\\begin{verbatim}\n#DISCH_THEN;;\n- : (thm_tactic -> tactic)\n\n#DISCH_THEN SUBST1_TAC;;\n- : tactic\n\n#g \"(n = 0) ==> (n * n = n)\";;\n\"(n = 0) ==> (n * n = n)\"\n\n() : void\n\n#e(DISCH_THEN SUBST1_TAC);;\nOK..\n\"0 * 0 = 0\"\n\\end{verbatim}\\end{session}\n\n\\noindent This gives the same result as the stack method, but more\ndirectly, with a more compact \\ML{} expression,\nand with the attractive feature that the term\n$n=0$ is never an assumption, even for an interval of one step.\nThis technique is often used at the moment when results are available;\nas above, where the result produced by discharging the antecedent can be\nimmediately passed to substitution. If the result were only needed\nlater, it {\\it would\\/} have to be held as an assumption. However, results\ncan be manipulated when they are available, and their results\neither held as assumptions or used immediately.\nFor example, to prove $(0=n) \\imp (n \\times n = n)$,\nthe result $n=0$ could be reversed\nimmediately:\n\n\\setcounter{sessioncount}{1}\n\\begin{session}\\begin{verbatim}\n#g \"(0 = n) ==> (n * n = n)\";;\n\"(0 = n) ==> (n * n = n)\"\n\n() : void\n\n#e(DISCH_THEN(SUBST1_TAC o SYM));;\nOK..\n\"0 * 0 = 0\"\n\\end{verbatim}\\end{session}\n\nThe justification of \\ml{DISCH\\_THEN SUBST1\\_TAC} is easily constructed\nfrom the justification of \\ml{DISCH\\_TAC} composed with the justification of\n\\ml{SUBST1\\_TAC}. \\index{assumptions!internal|(}\nThe term $n=0$ is assumed, to yield the\ntheorem that is passed to the theorem continuation \\ml{SUBST1\\_TAC},\nand it is accordingly discharged during the construction of the\nactual proof; but the assumption happens\nonly internally\n\\index{assumptions!internal|)} to the tactic \\ml{DISCH\\_THEN SUBST1\\_TAC}, and not\nas a step in the tactical proof.  In other words, the subgoal tree here\nhas one node fewer than before, when an explicit step (\\ml{DISCH\\_TAC})\nreflected the assumption.\n\nOn the goal with the disjunctive antecedent, this method again\nprovides a compact tactic:\n\n\\setcounter{sessioncount}{1}\n\\begin{session}\\begin{verbatim}\n#g \"((n = 0) \\/ (n = 1)) ==> (n * n = n)\";;\n\"(n = 0) \\/ (n = 1) ==> (n * n = n)\"\n\n() : void\n\n#e(DISCH_THEN(DISJ_CASES_THEN SUBST1_TAC));;\nOK..\n2 subgoals\n\"1 * 1 = 1\"\n\n\"0 * 0 = 0\"\n\\end{verbatim}\\end{session}\n\n\\noindent This avoids the repeated popping and pushing of the stack\nsolution, and likewise, gives a shorter \\ML{} expression. Both give\na shorter expression than the direct method, which is:\n\n\\begin{hol}\\begin{verbatim}\n   DISCH_TAC\n    THEN DISJ_CASES_TAC(ASSUME \"(n = 0) \\/ (n = 1)\")\n    THENL[SUBST1_TAC(ASSUME \"n = 0\");\n          SUBST1_TAC(ASSUME \"n = 1\")]\n\\end{verbatim}\\end{hol}\n\nTo summarize, there are so far at least five ways to solve a goal\n(and these are often combined in one interaction):\ndirectly, using the stack view of the assumptions,\nusing the array view with or without discarding assumptions, and using a\ntactical to intercept an assumption step.  All of the following work\n\\index{assumptions!compared methods of handling}\non the goal $(n=0) \\imp (n \\times n = n)$:\n\n\\begin{hol}\\index{ASSUM_LIST@\\ml{ASSUM\\_LIST}}\n\\begin{verbatim}\n   DISCH_TAC\n    THEN SUBST1_TAC(ASSUME \"n = 0\")\n    THEN REWRITE_TAC[MULT_CLAUSES]\n\n   DISCH_TAC\n    THEN POP_ASSUM SUBST1_TAC\n    THEN REWRITE_TAC[MULT_CLAUSES]\n\n   DISCH_TAC\n    THEN ASSUM_LIST (SUBST1_TAC o el 1)\n    THEN REWRITE_TAC[MULT_CLAUSES]\n\n   DISCH_TAC\n    THEN POP_ASSUM_LIST (SUBST1_TAC o el 1)\n    THEN REWRITE_TAC[MULT_CLAUSES]\n\n   DISCH_THEN SUBST1_TAC\n    THEN REWRITE_TAC[MULT_CLAUSES]\n\\end{verbatim}\\end{hol}\n\n\\noindent Furthermore, all five induce the\nsame sequence of inferences leading to\nthe desired theorem; internally, no inference steps are saved by the\neconomies in the \\ML{} text or the subgoal tree.  In this sense,\nthe choice is entirely one of style and taste;\nof how to organize the decomposition into subgoals.\nThe first expression illustrates the verbosity of denoting\nassumptions by text (the goal with the\ndisjunctive antecedent gave a clearer\nexample); but also\nthe intelligibility of the resulting expression, which, of course, is all\nthat is saved of the interaction, aside from the final theorem.\nThe last expression\nillustrates both the elegance and the inscrutibility of\nusing functions to manipulate intermediate results directly, rather than\nas assumptions.\nThe middle three expressions\nshow how results can be used as assumptions (discarded when\nredundant, if desired); and how\nassumptions can be denoted without\nrecourse to their text.\nIt is a strength of the \\LCF\\ approach\n\\index{LCF@\\LCF} to\ntheorem proving that many different proof styles are supported,\n(all in a secure way) and indeed, can be studied in their own\nright.\n\n\\HOL{} provides several other theorem continuation functions analogous to\n\\ml{DISCH\\_THEN} and \\ml{DISJ\\_CASES\\_THEN}.\n(Their names always end with\n`\\ml{\\_THEN}', `\\ml{\\_THENL} or `\\ml{\\_THEN2}'.)\nSome of these do convenient inferences for the user.\nFor example:\n\n\\index{CHOOSE_THEN@\\ml{CHOOSE\\_THEN}|pin}\n\\begin{holboxed}\\begin{verbatim}\n   CHOOSE_THEN : thm_tactical\n\\end{verbatim}\\end{holboxed}\n\n\\noindent Where \\ml{thm\\_tactical} abbreviates\n{\\small\\verb%thm_tactic -> tactic%}.\n\\ml{CHOOSE\\_THEN\\ $f$\\ (|-\\ ?$x$.$t[x]$)}\nis a tactic that, given a goal, generates the subgoal\nobtained\nby applying $f$ to \\ml{($t[x]$|-$t[x]$)}.  The intuition is that if\n\\ml{|-\\ ?$x$.$t[x]$} holds then \\ml{|-\\ $t[x]$}\nholds for some value of $x$ (as long as the\nvariable $x$ is not free elsewhere in the theorem or current goal).\n%(The choice of the witness is `understood' by the justification function.)\nThis gives an easy way of using existentially quantified theorems,\nsomething that is otherwise awkward.\n\nThe new method has other applications as well, including as an\nimplementation technique.\nFor example,\n\\index{tactics!indirect implementation of}\ntaking \\ml{DISJ\\_CASES\\_THEN} as basic, \\ml{DISJ\\_CASES\\_TAC}\ncan be defined by:\n\n\\begin{hol}\\begin{verbatim}\n   let DISJ_CASES_TAC = DISJ_CASES_THEN ASSUME_TAC\n\\end{verbatim}\\end{hol}\n\n\\noindent Similarly, the method is useful for modifying existing tactics\n(\\eg\\ resolution tactics) without\nhaving to re-program them in \\ML.  This avoids the danger of\nintroducing tactics\nwhose justifications may fail,\n\\index{failure, of tactics} a particularly difficult problem to\ntrack down; it is also much easier than starting from scratch.\n\nThe main theorem continuation functions in the system are:\n\n\\begin{hol}\\begin{verbatim}\n   ANTE_RES_THEN\n   CHOOSE_THEN      X_CHOOSE_THEN\n   CONJUNCTS_THEN   CONJUNCTS_THEN2\n   DISJ_CASES_THEN  DISJ_CASES_THEN2   DISJ_CASES_THENL\n   DISCH_THEN\n   IMP_RES_THEN\n   RES_THEN\n   STRIP_THM_THEN\n   STRIP_GOAL_THEN\n\\end{verbatim}\\end{hol}\n\n\\noindent See \\REFERENCE\\ for full details.\n\\index{tactics!for manipulating assumptions|)}\n\n\n\n\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: \"description\"\n%%% End:\n", "meta": {"hexsha": "c740e834471754dc442e476252afd8b37dbc20e6", "size": 76241, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Manual/Description/tactics.tex", "max_stars_repo_name": "LiLiming/HOL", "max_stars_repo_head_hexsha": "8de43bf3176993a37fb2f917fe978964c9d0591c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-12-27T07:51:47.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-27T07:51:47.000Z", "max_issues_repo_path": "Manual/Description/tactics.tex", "max_issues_repo_name": "LiLiming/HOL", "max_issues_repo_head_hexsha": "8de43bf3176993a37fb2f917fe978964c9d0591c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Manual/Description/tactics.tex", "max_forks_repo_name": "LiLiming/HOL", "max_forks_repo_head_hexsha": "8de43bf3176993a37fb2f917fe978964c9d0591c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3786542923, "max_line_length": 245, "alphanum_fraction": 0.7097886964, "num_tokens": 23722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.3179532857085877}}
{"text": "\\section{Programming and Proving in Cubical Agda} \\label{agda-intro} Agda \\citep{norellDependentlyTypedProgramming2008} is a dependently-typed, pure,\nfunctional programming language and proof assistant.\nIn this section we will introduce the language with some basic examples, and\nexplain a little about how to program and prove in Agda.\nSome Haskell knowledge will help, as much of the syntax (any many concepts) are\nsimilar, but it is possible to struggle through without it.\nIt is recommended to try out the code examples in your own editor, or to look at\nthem in the real Agda files in the source.\nThe source is rendered and structured to be read alongside this document: it can\nbe found at \\mbox{\\url{https://doisinkidney.com/code/masters-thesis/README.html}}.\n\nAgda is first and foremost a functional programming language, similar in syntax\nand design to Haskell.\nIt is pure, meaning that it doesn't allow undeclared side effects, and\n\\emph{lazy}, meaning that expressions are not evaluated until they are needed\n(although this has no effect on Agda's semantics: since Agda is total, both lazy\nand strict evaluation will result in the same output).\n\nWhile Agda can be compiled (to Haskell, or to JavaScript), it is usually just\ntype-checked: this is because Agda is also a \\emph{proof assistant}.\nPrograms written in Agda correspond to proofs in the formal language of\nMartin-Löf Type Theory \\citep{martin-lofIntuitionisticTypeTheory1980}, in the\nstyle of ``Propositions as Types'' \\citep{wadlerPropositionsTypes2015}.\nTypes in Agda correspond to formal propositions; the programs which inhabit\nthose types correspond to proofs of those propositions.\n\\begin{figure}\n  \\centering\n  \\begin{tikzcd}\n    \\text{Proposition} \\ar[r, leftrightsquigarrow] & \\text{Type} \\\\\n    \\text{Proof} \\ar[r, leftrightsquigarrow] \\ar[u, \"\\text{proves}\"\n    description]& \\text{Program} \\ar[u, \"\\text{inhabits}\" description]\n  \\end{tikzcd}\n\\end{figure}\n\\subsection{Basic Functional Programming in Agda}\nThe basic unit of functionality in Agda is the \\emph{type}.\nLet's define a type: the type of booleans (we include the equivalent code in\nHaskell on the right).\n\\begin{agdalisting} \\label{bool-def}\n  \\begin{multicols}{2} \\centering\n    \\ExecuteMetaDataInline[agda/Snippets/Bool.tex]{bool-def} \\columnbreak\n    \\ExecuteMetaDataInline[haskell/Bool.tex]{bool-def}\n  \\end{multicols}\\vspace{-2\\baselineskip}\n\\end{agdalisting}\nThere's a lot of syntax wrapped up in this small snippet.\nIn prose, it provides four basic pieces of information:\n\\begin{samepage}\n\\begin{enumerate}\n  \\item We are defining a new \\AgdaKeyword{data} type.\n  \\item Its name is \\AgdaDatatype{Bool}.\n  \\item \\AgdaDatatype{Bool} is a \\AgdaFunction{\\(\\text{Type}_0\\)} kind of thing.\n  \\item There are two ways to construct values of type \\AgdaDatatype{Bool}:\n    \\AgdaInductiveConstructor{false} and \\AgdaInductiveConstructor{true}.\n\\end{enumerate}\n\\end{samepage}\nLet's explain each piece one by one.\n\n\\paragraph{Data Types}\nWe first say that we're defining a new \\AgdaKeyword{data} type.\nUsing the ``\\AgdaKeyword{data}'' keyword is just one of the many ways of\ndefining types: it basically means that we are going to define the type by\nlisting all of its constructors (all of the ways to construct values of the\ntype).\nThere are other ways to define types: with the \\AgdaKeyword{record} keyword, for\ninstance, which we'll see later; or we can define types by referencing other\ntypes, creating a synonym.\nHere, for instance, we define the \\AgdaFunction{Boolean} type:\n\\begin{agdalisting*}\n  \\begin{multicols}{2} \\centering\n    \\ExecuteMetaDataInline[agda/Snippets/Bool.tex]{boolean} \\columnbreak\n    \\ExecuteMetaDataInline[haskell/Bool.tex]{boolean-synonym}\n  \\end{multicols}\\vspace{-\\baselineskip}\n\\end{agdalisting*}\nThis snippet says ``I am defining a new thing called \\AgdaFunction{Boolean}, it\nis a \\AgdaFunction{\\(\\text{Type}_0\\)}, and it is equal to \\AgdaDatatype{Bool}''.\nOf course this isn't a very interesting declaration: as the equals sign implies,\n\\AgdaFunction{Boolean} is the same as \\AgdaFunction{Bool} (other than the\nspelling).\nWe've basically defined a synonym for the old type.\n\nNotice that in Haskell we needed a special keyword in order to define this type\nsynonym: in Agda, types are first-class values, which we can manipulate just as\nwe would functions or numbers.\nAs such, defining a type synonym is exactly the same as defining a new variable:\nit doesn't need any special syntax.\n\\paragraph{Type Names}\nThe second point is pretty straightforward: the name of the type we've defined\nis \\AgdaDatatype{Bool}.\nThe only thing to watch out for here is that Agda has relatively few\nrestrictions on type names, unlike, say, Haskell.\nThis type could have included Unicode symbols (Agda supports roughly 50 Unicode\nmathematical symbols), it could have started with a lowercase letter, etc.\n\n\\paragraph{Type\\textsubscript{0}}\nThe third point is the most interesting: we say that \\AgdaDatatype{Bool} is a\n``\\AgdaFunction{\\(\\text{Type}_0\\)}'' kind of thing.\nWhat does this mean?\n\nWell, we've seen that we can assign types to variables just as easily as we\nmight assign values to variables: this is what was happening in the\n\\AgdaFunction{Boolean} example.\nIn fact, in Agda, there is no real distinction between ``types'' and ``values'':\ntypes like \\AgdaDatatype{Bool} \\emph{are} values, just as much as\n\\AgdaInductiveConstructor{true} or \\AgdaInductiveConstructor{false}!\nThis means that our types must themselves have types: hence we say that\n\\AgdaFunction{Boolean} has type \\AgdaFunction{\\(\\text{Type}_0\\)}.\n\nBut why the subscript 0?\nWell we know that types are values in Agda, and so they themselves have types.\nWe know that the type of \\AgdaDatatype{Bool} is\n\\AgdaFunction{\\(\\text{Type}_0\\)}.\nBut what's the type of \\AgdaFunction{\\(\\text{Type}_0\\)}?\nIt turns out that if we say:\n\\begin{agdalisting*}\n  \\(\\AgdaFunction{\\(\\text{Type}_0\\)} :  \\AgdaFunction{\\(\\text{Type}_0\\)}\\)\n\\end{agdalisting*}\nWe actually introduce a paradox into the language: Girard's paradox\n\\citep{girardInterpretationFonctionelleElimination1972}.\nThis is the type-theoretic analogue of Russell's paradox, and, if present, it\nwould allow us to prove things that are not true.\nSo we disallow it.\n\nDependently-types programming languages have many different ways of resolving\nthe issue: Agda's approach is called \\emph{universe polymorphism}.\nBasically, we say that the type of \\AgdaInductiveConstructor{true} is\n\\AgdaDatatype{Bool}, the type of \\AgdaDatatype{Bool} is\n\\AgdaFunction{\\(\\text{Type}_0\\)}, the type of \\AgdaFunction{\\(\\text{Type}_0\\)}\nis \\AgdaFunction{\\(\\text{Type}_1\\)}, the type of \\AgdaFunction{\\(\\text{Type}_1\\)}\nis \\AgdaFunction{\\(\\text{Type}_2\\)}, and so on.\n\nTo be honest, avoiding Girard's paradox is one of things that isn't done\nespecially well in dependently-typed languages: most approaches require quite a\nbit of tedious busywork from the programmer, and it's quite rare that a\nprogrammer would run into a genuine universe size issue that exposes a deep\nlogical impossibility (we will run into one of the few cases in this paper).\nMost of the time, managing universe levels amounts to bookkeeping.\nFor that reason, and also because the current system of universe polymorphism in\nAgda is quite under flux and likely to be changed soon, we won't spend too much\ntime on the topic.\nEvery code example provided is as universe-polymorphic as possible, though.\n\n\\paragraph{Constructors}\nThe last point is the simplest: we have listed the ways to construct values of\ntype \\AgdaDatatype{Bool}.\nTwo ways, in fact, \\AgdaInductiveConstructor{true} and\n\\AgdaInductiveConstructor{false}, and they're called the constructors.\nWe can use these constructors in programs by (for instance) assigning them to\nvariables.\n\\begin{multicols}{2}\\centering\n  \\ExecuteMetaDataInline[agda/Snippets/Bool.tex]{bool-val}\\columnbreak\n  \\ExecuteMetaDataInline[haskell/Bool.tex]{bool-val}\n\\end{multicols}\\vspace{-2\\baselineskip}\\noindent\nHere we've declared a variable\\footnotemark\\;called \\AgdaFunction{a-boolean} with\nthe type \\AgdaDatatype{Bool}, and said it is equal to the value\n\\AgdaInductiveConstructor{true}.\n\n\\footnotetext{Note that although we use the term ``variable'', the value of the\n  variable \\AgdaFunction{a-boolean} can not change.\n  We couldn't reassign it on the following line.}\n\n\\subsection{Some Functions}\nThat's quite a lot of information on how to define things in Agda: let's look a\nlittle about how to do computation.\nWhat we need is a function:\n\\begin{multicols}{2}\\centering\n  \\ExecuteMetaDataInline[agda/Snippets/Bool.tex]{not-def}\\columnbreak\n  \\ExecuteMetaDataInline[haskell/Bool.tex]{not-func}\n\\end{multicols}\\vspace{-2\\baselineskip}\\noindent\nThis function is defined by pattern-matching: when the clause on the\nleft-hand-side of the equals sign is seen, the right-hand-side is what's\ncomputed.\n\nThis syntax with the equals sign is actually just syntactic sugar for a \\(\\lambda\\).\nThe identity function, for instance, could be written as follows:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Implicits.tex]{id-lambda}\n\\end{agdalisting*}\nThe \\AgdaFunction{not} function could also have been written with a \\(\\lambda\\).\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Bool.tex]{lambda-not}\n\\end{agdalisting*}\n\n\nFor a more complex example, we're going to need a more complex type:\n\\begin{agdalisting}\n  \\ExecuteMetaDataInline[agda/Snippets/Nat.tex]{nat-def}\n\\end{agdalisting}\nThis is the type of the natural numbers.\nWith \\AgdaDatatype{Bool} (\\Cref{bool-def}) we were able to list all the\nactual values in the type: doing so for the natural numbers would somewhat bloat\nthe page count of this paper.\nInstead, we list the two ways to construct natural numbers: first,\n\\AgdaInductiveConstructor{zero} is a natural number.\nNext, if you have a natural number, its successor\n(\\AgdaInductiveConstructor{suc}) is a natural number.\n\nAgda has special syntax for constructing natural numbers: we can write\n\\AgdaNumber{3} instead of\n\\(\\AgdaInductiveConstructor{suc}\\;(\\AgdaInductiveConstructor{suc}\\;(\\AgdaInductiveConstructor{suc}\\;\\AgdaInductiveConstructor{zero}))\\).\n\nThere are several small pieces of information we'll need to understand in order\nto write functions in Agda.\nWe'll go through them one by one.\n\\paragraph{Multi-Argument Functions}\nAgda, like Haskell, doesn't really have a built-in notion of ``multi-argument''\nfunctions.\nInstead, multiple arguments are kind of simulated with \\emph{currying}.\n\nHere's how we define the addition of two natural numbers:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Nat.tex]{text-add}\n\\end{agdalisting*}\nInstead of taking two \\Nat s and returning a third, this function takes a\n\\Nat, and returns a function which takes a \\Nat and returns a\n\\Nat.\n\\AgdaFunction{add}\\;\\AgdaNumber{0} returns a function which\nadds \\AgdaNumber{0} to a number; \\AgdaFunction{add}\\;\\AgdaNumber{2} returns a\nfunction which adds \\AgdaNumber{2} to a number.\n\\paragraph{Operators}\nHere's a function on the natural numbers:\n\\begin{agdalisting} \\label{sub-def}\n  \\ExecuteMetaDataInline[agda/Snippets/Nat.tex]{sub-def}\n\\end{agdalisting}\nWe've defined subtraction.\n\nNotice that this function is defined as an operator: for the function\ndeclaration (the line with the type signature), we put underscores where we\nexpect the arguments to the operator to go.\n\nWe can also specify the precedence and fixity of the operator:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Nat.tex]{sub-fix}\n\\end{agdalisting*}\n\\paragraph{Total Functions}\nIn the introduction, we described Agda as a ``total'' programming language.\nThis means that if we give a function the type \\(A \\rightarrow B\\), then we have\nalso \\emph{proven} that, given an \\(A\\), it will produce a \\(B\\) (in finite\ntime).\n\nPractically speaking, this means that Agda will perform some checks on our\ncode to ensure that every function is indeed total.\nThere are three checks that Agda performs that we will run into in this paper:\ncoverage, termination, and productivity.\n\\subparagraph{Coverage}\nThis is the simplest check that Agda performs: it's also performed by GHC (if\n\\verb+-Wall+ is turned on).\nThis check ensures that functions are defined for all inputs.\n\nOur definition of subtraction above (\\Cref{sub-def}), for instance,\ntruncates to zero when there's arithmetic underflow.\nIn other words \\(5 - 6 = 0\\), according to our definition.\nWe could have removed the clause which allows for this:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Nat.tex]{bad-sub}\n\\end{agdalisting*}\nBut now the expression \\(5 - 6\\) is undefined.\n\\subparagraph{Termination}\nThe other major check that Agda will preform on our function definitions is for\n\\emph{termination} (or productivity, which we will see later).\nThis checks that no function we write accidentally contains an infinite loop.\nMost of the time, we won't butt heads with the\ntermination checker, but it does happen occasionally, so it's helpful to\nunderstand a little how it works. When we define the following function\n(addition on the natural numbers):\n\\begin{agdalisting} \\label{add-def}\n  \\ExecuteMetaDataInline[agda/Snippets/Nat.tex]{add-def}\n\\end{agdalisting}\nAgda checks that the argument to the recursive call is \\emph{structurally\n  smaller} than the argument given to the outer function.\n``Structurally smaller'' effectively means that the smaller thing must be a\nsubexpression of the larger: here, \\(n\\) is subexpression of\n\\(\\AgdaInductiveConstructor{suc}\\;n\\).\n\nStructural recursion is actually surprisingly powerful: a great many algorithms\ncan be converted to forms where the recursive calls recurse on some substructure\nof their arguments.\nIt does require careful definitions, though.\nFor instance, the following will \\emph{not} pass the termination checker:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Nat.tex]{bad-add}\n\\end{agdalisting*}\nThough it defines the same function as \\Cref{add-def}, it doesn't make\nit absolutely obvious to the termination checker that the first argument to the\nrecursive call (\\(n - 1\\)) is structurally smaller than the outer argument\n(\\(n\\)).\n\nOccasionally a function can't be refactored to the extent where it will be\nobviously structurally terminating to Agda.\nIn those cases, there are facilities to describe more complex termination\nconditions (although we should stress that these facilities are not\nbuilt in to the compiler or anything: they're actually just extremely clever\nways to express structural recursion), but if you have to reach for those\nfacilities it's usually a sign you've gone wrong.\nWe won't use them here.\n\\subparagraph{Productivity}\nProductivity isn't something we'll describe just yet, but we will give a hint as\nto its purpose.\nOften when describing total programming languages like Agda people make the\nmistake of saying that they are ``not Turing complete''.\nThis is in fact not true, partly because Agda has the ability to describe non\nterminating (and infinite) computations.\nThis allows us to implement, for instance, a Turing machine or\n\\(\\lambda\\)-calculus interpreter\n\\citep{mcbrideTuringCompletenessTotallyFree2015}, or more prosaic things like a\nweb server or repl.\n\nWhile these things don't ``terminate'', Agda still needs to check that they are\nvalid with regards to computation in another sense.\nThis sense is \\emph{productivity}: they need to always be able to produce\nanother piece of information in finite time, even if they never ``finish''\nproducing pieces of information.\n\\subparagraph{What's it all For?}\nOne thing we haven't answered is \\emph{why} we bother checking for termination\nor totality.\nThe answer is that it's necessary for Agda to be a valid proof assistant.\nImagine if we could construct a type for ``proofs of the Riemann hypothesis''.\nWe might call it \\AgdaFunction{RiemannIsTrue}.\nIn a language like Haskell, the following is a completely valid program:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Nat.tex]{riemann-proof}\n\\end{agdalisting*}\nBut of course we \\emph{haven't} provided a proof of the Riemann hypothesis (and\nif we had we certainly wouldn't have buried the lead to this extent).\nThe termination checker is vital to rule out these kinds of ``proofs'': that's\nwhy it's an integral part of Agda.\n\\subsection{An Expression Evaluator}\nLet's put all of the different things we've learned into a more complex example.\nWe're going to write a small evaluator for arithmetic expressions.\nLater, we'll use this to help us solve the Countdown problem\n\\citep{huttonCountdownProblem2002}.\n\nWe want to define a language of arithmetic expressions.\nWith countdown in mind, we'll only need to support four operators, which we can\ndefine in a simple data type:\n\\begin{agdalisting}\n  \\ExecuteMetaDataInline[agda/Snippets/Expr.tex]{op-def}\n\\end{agdalisting}\nNext, we'll define the actual type of expressions.\n\\begin{agdalisting}\n  \\ExecuteMetaDataInline[agda/Snippets/Expr.tex]{expr-def}\n\\end{agdalisting}\nWhat we've defined here is actually a simple leafy binary tree.\nThe syntax for the second constructor is not so simple, however: it defines a\n\\emph{mixfix} operator.\nEach underscore in \\AgdaInductiveConstructor{\\(\\_\\langle \\_ \\rangle\\_\\)}\nrepresents a hole which expressions can be put into.\nThis allows us to use the constructor like so:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Expr.tex]{example-expr}\n\\end{agdalisting*}\n\nEvaluation of an expression is done by the following function:\n\\begin{agdalisting}\n  \\ExecuteMetaDataInline[agda/Snippets/Expr.tex]{incorrect-eval}\n\\end{agdalisting}\nWe've introduced the \\AgdaKeyword{with} syntax here: it functions somewhat like\na case expression in Haskell.\nBasically, it allows us to pattern-match on the result of applying a function to\none of the input arguments without defining a new function.\n\\subsection{Safe Evaluation With Maybe}\nThe evaluator we have written isn't exactly correct.\nIt implies things like \\(4 - 5 = 0\\), or \\(10 \\div 3 = 3\\), or \\(2 \\div 0 = 0\\);\nthis doesn't make the function ``wrong'' per se, but it might be more desirable\nto have expressions like \\(2 \\div 0\\) be undefined.\nIt's especially important for countdown, as division by zero (or any of the\nother equations) isn't permitted.\n\nTo remedy the problem we're going to introduce a new type.\n\\begin{agdalisting}\n  \\ExecuteMetaDataInline[agda/Data/Maybe/Base.tex]{maybe-def}\n\\end{agdalisting}\n\\AgdaDatatype{Maybe} is a container that can contain at most one item.\nIt's the first \\emph{parameterised} type we have seen: \\AgdaDatatype{Maybe} can\ncontain an item of any type.\nHere, for instance, is a \\AgdaDatatype{Maybe} which contains the number 2:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Maybe.tex]{maybe-two}\n\\end{agdalisting*}\nOr here is a \\AgdaDatatype{Maybe} which doesn't contain anything, but whose type\nsays it could contain a function from \\Nat to \\Nat:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Maybe.tex]{maybe-nat-to-nat}\n\\end{agdalisting*}\n\nMaybe is used often in functional programming to represent partiality: if you\nhave a function which is undefined for certain inputs, you can wrap\n\\AgdaDatatype{Maybe} around its return type, and return\n\\AgdaInductiveConstructor{nothing} for the cases where those inputs are given.\nWe can use it here, for instance, to define a version of subtraction which\ndoesn't truncate arithmetic underflow:\n\\begin{agdalisting}\n  \\ExecuteMetaDataInline[agda/Snippets/Expr.tex]{safe-sub}\n\\end{agdalisting}\nIt's often also used for similar purposes as \\verb+null+ is in imperative\nprogramming, although it is of course far safer since it's impossible to forget\nto check for \\AgdaInductiveConstructor{nothing} by definition.\n\nWe can use \\AgdaDatatype{Maybe} in our evaluator for expressions, so that we\nreturn \\AgdaInductiveConstructor{nothing} on expressions which evaluate to\nundefined values.\nThat changes the type to the following:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Expr.tex]{eval-ty}\n\\end{agdalisting*}\nThe first case is relatively simple:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Expr.tex]{lit-case}\n\\end{agdalisting*}\n\nThe second two cases are slightly more complex: the result of evaluating each\nsub-tree is \\(\\AgdaDatatype{Maybe}\\;\\Nat\\), not \\Nat, so we will\nhave to pattern-match on the outputs to check for\n\\AgdaInductiveConstructor{nothing}.\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Expr.tex]{add-helper}\n\\end{agdalisting*}\nCode like this is quite tedious.\nLuckily, there's a common pattern we can abstract out: whenever we have a\nmulti-argument function, we can apply it to arguments wrapped in\n\\AgdaDatatype{Maybe} using the following two functions.\n\\begin{multicols}{2} \\null \\vfill\n  \\begin{agdalisting*}\n    \\ExecuteMetaDataInline[agda/Data/Maybe/Sugar.tex]{pure}\n  \\end{agdalisting*} \\vfill \\null \\columnbreak\n  \\begin{agdalisting*}\n    \\ExecuteMetaDataInline[agda/Data/Maybe/Sugar.tex]{ap}\n  \\end{agdalisting*}\n\\end{multicols} \\noindent\nAny type which implements these functions (in a certain law-abiding way) is said\nto be an ``Applicative Functor''\n\\citep{mcbrideApplicativeProgrammingEffects2008}, a full explanation of which is\nbeyond the scope of this paper.\n\nIt might not be immediately clear how those two functions can help us.\nBasically, we can replace the \\AgdaFunction{add-helper} function with the\nfollowing:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Expr.tex]{add-helper-app}\n\\end{agdalisting*}\nAnd, as it happens, Agda has special syntax which will automatically insert the\n\\AgdaFunction{pure} and \\AgdaFunction{\\_<*>\\_} operators for us, making both the\naddition and multiplication cases the following:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Expr.tex]{appl-cases}\n\\end{agdalisting*}\n\nNext, we have to handle subtraction.\nIn contrast to addition and multiplication, subtraction itself can produce a\n\\AgdaInductiveConstructor{nothing}: instead of having type\n\\(\\Nat\\rightarrow\\Nat\\rightarrow\\Nat\\), it has type \n\\(\\Nat\\rightarrow\\Nat\\rightarrow\\AgdaDatatype{Maybe}\\;\\Nat\\).\nTo construct multi-argument functions of this particular type, we'll need\nanother function:\n\\begin{agdalisting}\n  \\ExecuteMetaDataInline[agda/Data/Maybe/Sugar.tex]{bind}\n\\end{agdalisting}\nTypes which implement this function (along with \\AgdaFunction{pure}), modulo\nsome laws, are called Monads \\citep{moggiNotionsComputationMonads1991a}.\nThis function will allow us to easily chain together several maybes even with\nfunctions that return \\AgdaDatatype{Maybe}.\nIt's used like this:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Expr.tex]{sub-bind}\n\\end{agdalisting*}\nAnd of course Agda also provides a syntax (do notation, just like Haskell) to\nexpress the same:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Expr.tex]{sub-case}\n\\end{agdalisting*}\n\nFinally, we will handle the division case.\nHere, we want to pattern-match on the returned value of the recursive call.\nAgda also provides syntax for that:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Expr.tex]{div-case}\n\\end{agdalisting*}\nThe \\AgdaKeyword{where} keyword here lets us match on zero within the\n\\AgdaKeyword{do}-notation.\n\\subsection{Statically Proving the Evaluation is Safe}\nUsing this evaluator in practice can be a little annoying:\nbecause it always returns a \\AgdaDatatype{Maybe}, simple expressions which are\nobviously valid still need to be checked at run-time.\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Expr.tex]{example-eval}\n\\end{agdalisting*}\nThis is where Agda can add a little to the usual example for monads of an\nexpression evaluator: using dependent types, we can actually statically (and\nautomatically) prove that a given expression is valid, and evaluate it without\nchecking for \\AgdaInductiveConstructor{nothing} safely.\n\nFirst, we will need the following function:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Expr.tex]{is-just}\n\\end{agdalisting*}\nThis simple function can tell us if the result of evaluating an expression is\nsuccessful or not.\nIn other words, it can test if an expression is valid.\n\nTo use this statically, however, we will need to employ the following\n\\emph{dependent} function:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Expr.tex]{tee}\n\\end{agdalisting*}\nThis function turns our boolean values into types: \\agdatop\\;(tautology), or\n\\agdabot\\;(impossibility).\nThese types are defined like so:\n\\begin{multicols}{2}\n  \\begin{agdalisting*}\n    \\ExecuteMetaDataInline[agda/Snippets/Introduction.tex]{bot}\n  \\end{agdalisting*}  \\columnbreak\n  \\begin{agdalisting*}\n    \\ExecuteMetaDataInline[agda/Snippets/Introduction.tex]{top}\n  \\end{agdalisting*}\n\\end{multicols}\nThe first type here, \\agdabot, has no constructors: there are no values which\ninhabit the type \\agdabot.\nLogically speaking, it is the type of falsehoods.\nIt is quite useful in practice: any function of type \\(A \\rightarrow \\agdabot\\)\nwe know can never return, so we know that it must be impossible to call such a\nfunction.\nIn other words, the type \\(A\\) must not have any values which inhabit it.\nAs such, we can use \\agdabot\\;to define a notion of ``not'' for types:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Introduction.tex]{not}\n\\end{agdalisting*}\n\nThe second type, \\agdatop, is a \\AgdaKeyword{record}.\nTypes defined using \\AgdaKeyword{record} are quite like classes or structs\nin an imperative programming language: instead of listing the constructors, we list\nthe \\emph{fields} of these types.\n\nOf course, in this case, our type doesn't have any fields.\nPerhaps a more instructive example of a record is the following:\n\\begin{agdalisting} \\label{pair-def}\n  \\ExecuteMetaDataInline[agda/Snippets/Expr.tex]{pair}\n\\end{agdalisting}\nHere we've defined the type of \\emph{pairs}.\n\nTypes defined with \\AgdaKeyword{data} and types defined with\n\\AgdaKeyword{record} are in some sense duals of each other: to \\emph{consume} a\n\\AgdaKeyword{data} type, we have to handle each of the constructors; to\n\\emph{construct} a \\AgdaKeyword{record} type, we have to handle each of the\nfields.\nAnother way to say this same thing is that \\AgdaKeyword{data} types are sum\ntypes, and \\AgdaKeyword{record} types are products.\nWhat we have in \\agdabot\\;and \\agdatop\\;is the identity for sums and products,\nrespectively.\n\nNow, to be completely clear, we could absolutely have defined \\agdatop\\;as a\n\\AgdaKeyword{data} type with one constructor:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Expr.tex]{data-top}\n\\end{agdalisting*}\nWe use the \\AgdaKeyword{record} definition simply because it tends to work a\nlittle better in terms of ergonomics: basically, to construct a\n\\AgdaKeyword{record} type automatically, Agda attempts to construct all of its\n\\emph{fields} one by one.\nSince \\agdatop\\;has no fields, this is an easy task, and hence Agda will be able\nto automatically construct a value of type \\agdatop\\;in many situations\n(We can ask Agda to construct something for us automatically by supplying an\nunderscore in place of where the value should go).\nAgda is more conservative about automatically constructing \\AgdaKeyword{data}\ntypes, so there are fewer situations where it will do it automatically.\n\nSo, now that we have a way of turning booleans into their logical equivalents\nwe can define a type for proofs that a given\nexpression is valid:\n\\begin{agdalisting}\n  \\ExecuteMetaDataInline[agda/Snippets/Expr.tex]{valid}\n\\end{agdalisting}\nA value of type \\(\\AgdaFunction{Valid}\\;e\\), for some expression \\(e\\), is a\nproof that \\(e\\) doesn't have (for example) any divisions by zero, or\narithmetic underflows.\n\nNow we can write a function that takes an expression \\(e\\) and a proof that that\nexpression is valid; then, when we pattern-match on evaluating the expression\nAgda will automatically rule out the case where it evaluates to\n\\AgdaInductiveConstructor{nothing}.\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Expr.tex]{static-eval-explicit}\n\\end{agdalisting*}\n\nA way to make calling this function a little cleaner (syntactically speaking) is\nto use an implicit argument: \n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Expr.tex]{static-eval}\n\\end{agdalisting*}\nBy surrounding the argument here in braces we are basically going to pass around\nthe argument invisibly and automatically (as much as is possible).\nThough it's invisible, it's clearly still usable as a variable: in this case the\nproof still rules out the clause where the evaluation returns\n\\AgdaInductiveConstructor{nothing}.\nThe real use of this feature, however, is that the argument is \\emph{passed}\ninvisibly.\n\\begin{agdalisting} \\label{example-static-eval}\n  \\ExecuteMetaDataInline[agda/Snippets/Expr.tex]{example-static-eval}\n\\end{agdalisting}\nWhat's happened here is that the type of \\(\\AgdaFunction{Valid}\\;e\\) uniquely\ndetermines one value: Agda can derive this, and it can also derive the value\ndetermined.\nAs a result, it provides it automatically.\nThe precise rules for when Agda can ``provide something automatically'' are\nactually a little tricky (it's quite important that we defined \\agdatop\\;as a\n\\AgdaKeyword{record}, for instance): a fuller explanation is available in the\nAgda manual.\n\nTwo more things about implicit arguments: first, it is possible to retrieve an\nargument even when it's supplied implicitly, with the following syntax:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Expr.tex]{retrieve-implicit}\n\\end{agdalisting*}\nHere we have bound the proof that the expression is valid to the variable\n\\AgdaBound{valid}.\n\nSecondly, we have actually been using implicit arguments throughout the paper,\nin combination with automatically generalised variables.\nThese two features are quite natural to most programmers (especially to\nHaskellers), so it might come as a surprise that we've been using them, but it's\ntrue.\nTake the following definition of the identity function:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Implicits.tex]{id-def}\n\\end{agdalisting*}\nThis is the same function with all implicit arguments made explicit:\n\\begin{agdalisting} \\label{id-expl}\n  \\ExecuteMetaDataInline[agda/Snippets/Implicits.tex]{id-expl}\n\\end{agdalisting}\nWe have hidden the universe level of the type (\\(a\\)) and the type itself\n(\\(A\\)).\n\nFurthermore, not only have we made these things implicit, we haven't actually\nspecified them in the type at all!\nWe're able to do this because at the top of our Agda file we say the following:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Level.tex]{level-var-decl}\n\\end{agdalisting*}\nThis \\AgdaKeyword{variable} declaration means that if we ever refer to  \\(A\\) in\na function signature without defining it beforehand, Agda will automatically\ninsert the implicit arguments present in \\Cref{id-expl}.\n\\subsection{Equalities}\nWe actually have encountered our first ``proof'' with dependent types: we have\nproven that a given expression is valid or not.\nNow we're going to look at another kind of proof: one that shows that an\nexpression is \\emph{equal} to something.\nTo do so we'll first have to explore path types in Cubical Agda.\n\\begin{definition}[Path Types]\n  A proof that two values are equal in Cubical Agda is represented by a\n  \\emph{path}.\n  This path will be denoted with the symbol \\AgdaFunction{\\(\\equiv\\)}.\n  In other words, a value of type \\(x\\;\\AgdaFunction{\\(\\equiv\\)}\\;y\\) is a proof\n  that \\(x\\) equals \\(y\\).\n\\end{definition}\n\nEqualities as paths is the first topic we have reached where Cubical Type Theory\nbegins to differ from traditional Martin-Löf Type Theory.\nThere, we would usually define the type of proofs of equality like so:\n\\begin{agdalisting}\n  \\ExecuteMetaDataInline[agda/Snippets/Equality.tex]{equality-def}\n\\end{agdalisting}\nThis is an inductive \\AgdaKeyword{data} type, with one constructor: the\nconstructor can only be used when the two parameters to the type are the same,\nmeaning a value of this type contains a proof that they are the same.\nWe can retrieve this proof by pattern-matching on that constructor.\n\nThis is actually a perfectly usable equality type in CuTT, although the\nelimination rule is a little complex and we won't look into it just yet.\nHowever we prefer to represent equalities in a slightly more primitive way, as\nit turns out to be a little more flexible.\nThis is the \\emph{path} representation.\n\nWhen represented as a path, an equality between two values of type \\(A\\)\nactually behaves more like a function from \\AgdaDatatype{I} to \\(A\\).\n\\AgdaDatatype{I} here is the type of the interval: it ranges from\n\\AgdaInductiveConstructor{i0} to \\AgdaInductiveConstructor{i1}.\nSo, as a function then, when the path \\(x\\;\\AgdaFunction{\\(\\equiv\\)}\\;y\\) is\napplied to \\AgdaInductiveConstructor{i0}, it returns \\(x\\), and when it is\napplied to \\AgdaInductiveConstructor{i1}, it returns \\(y\\).\n\n\\begin{marginfigure}\n  \\begin{tikzpicture}\n    \\node [anchor=base] at (-1.5 , 2.7) {$p :$};\n    \\node [anchor=base] at (-1   , 2.7) {$x$};\n    \\node [anchor=base] at ( 0   , 2.7) {\\AgdaFunction{\\(\\equiv\\)}};\n    \\node [anchor=base] at ( 1   , 2.7) {$y$};\n    \\node [anchor=base] at (-1.15, 2.1) {\\footnotesize$p\\;\\AgdaFunction{i0} = x$};\n    \\node [anchor=base] at ( 0.85, 2.1) {\\footnotesize$p\\;\\AgdaFunction{i1} = y$};\n    \\draw (-1,2.5) -- (1,2.5);\n    \\filldraw[black] (-1,2.5) circle (2pt);\n    \\filldraw[black] ( 1,2.5) circle (2pt);\n\n    \\node [anchor=base] at (-1.8, 0.2) {$\\AgdaFunction{sym}\\;p :$};\n    \\node [anchor=base] at (-1  , 0.2) {$y$};\n    \\node [anchor=base] at ( 0  , 0.2) {\\AgdaFunction{\\(\\equiv\\)}};\n    \\node [anchor=base] at ( 1  , 0.2) {$x$};\n    \\node [anchor=base] at (-1.4,-0.8) {\\linespread{0}\\footnotesize\n      $\\begin{aligned}\n        \\AgdaFunction{sym}\\;p\\;\\AgdaFunction{i0} &= \\\\\n        p\\;(\\AgdaOperator{\\AgdaPrimitive{\\textasciitilde{}}}\\;\\AgdaFunction{i0}) &= \\\\\n        p\\;\\AgdaFunction{i1} &= y\n      \\end{aligned}$\n    };\n    \\node [anchor=base] at ( 0.6,-0.8) {\\linespread{0}\\footnotesize\n      $\\begin{aligned}\n        \\AgdaFunction{sym}\\;p\\;\\AgdaFunction{i1} &= \\\\\n        p\\;(\\AgdaOperator{\\AgdaPrimitive{\\textasciitilde{}}}\\;\\AgdaFunction{i1}) &= \\\\\n        p\\;\\AgdaFunction{i0} &= x\n      \\end{aligned}$\n    };\n    \\draw (-1  ,0) -- ( 1,0);\n    \\filldraw[black] (-1,0) circle (2pt);\n    \\filldraw[black] (1,0) circle (2pt);\n\n    \\draw[-stealth] ( 1,2) to[out=-90, in=90] (-1,0.5);\n    \\draw[-stealth] (-1,2) to[out=-90, in=90] ( 1,0.5);\n  \\end{tikzpicture}\n  \\caption{Diagram of \\(\\AgdaFunction{sym}\\;p\\)}\n  \\label{sym-diagram}\n\\end{marginfigure}\n\nAlready we can manipulate paths in some interesting ways.\nFirst, we can manipulate values in the interval: we can take the inverse of a\npoint in the interval, for instance.\nIt's worth thinking about what this ``inverse'' corresponds to in the equality:\nwe will name it in the next listing.\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Equality.tex]{sym-def}\n\\end{agdalisting*}\nWe will see some more intricate ways to manipulate paths later on, but for now\nthe ``function from an interval'' intuition is enough to understand the basics.\n\n\\subsection{Some Proofs of Equality}\nSo now that we know something about the equality type, let's put it to some use.\nWe can construct equality proofs of things which are ``obviously equal'' with\nthe following function:\n\\begin{agdalisting}\n  \\ExecuteMetaDataInline[agda/Snippets/Equality.tex]{refl-def}\n\\end{agdalisting}\nWith this we can prove that the output from Equation.~\\ref{example-static-eval}\nis 8:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Expr.tex]{example-static-proof}\n\\end{agdalisting*}\n\nOf course, these proofs aren't very interesting.\nSomething a little more complex might be the following:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Data/Nat/Properties.tex]{plus-assoc}\n\\end{agdalisting*}\nUnfortunately we can't look at much more complex proofs without building up some\nmore machinery around path types: we can't currently compose paths, for\ninstance.\n\\subsection{Quotients}\nWe've seen that data types can be defined by listing their constructors, where\neach constructor is just a function whose return type is the type being defined.\nHowever, we've also seen that equalities are just functions from the interval.\nIf we combine these two notions, we can actually define a \\emph{higher\n  inductive} type.\n\\begin{definition}[Higher Inductive Type]\n  A normal inductive type (like \\AgdaDatatype{Bool}, or \\Nat) is a type\n  where its \\emph{point} constructors are listed.\n  A higher inductive type can have point constructors, but it can also have\n  \\emph{path} constructors: instead of adding new values to the type, these\n  constructors add new equalities to the type.\n\\end{definition}\n\nOne of the nice aspects of CuTT is that higher inductive types arise naturally\nfrom the ``function from an interval'' interpretation of path types.\nExpand out the definition of \\AgdaFunction{\\(\\equiv\\)} in the following type,\nfor instance:\n\\begin{agdalisting}\n  \\ExecuteMetaDataInline[agda/Snippets/Circle.tex]{circle-def}\n\\end{agdalisting}\nWe see that the \\AgdaInductiveConstructor{loop} constructor, though odd looking,\nstill does represent a function whose return value is\n\\AgdaDatatype{\\(\\text{S}^1\\)}.\n\nJust with regards to this \\AgdaDatatype{\\(\\text{S}^1\\)} type: it's actually the\nHoTT representation of the \\emph{circle}.\nWe won't examine its more interesting properties all that much: however it is a\ngood example of the simplest type with complex homotopy, so we will use it to\ndemonstrate several HoTT principles.\n\\subsection{Basic Type Formers}\nSo far a lot of our descriptions of Agda have mixed Agda's type theory with its\nsyntax.\nIf this were a paper presenting the core type theory of Agda to an audience of\ntype theorists we probably would describe things in a slightly different way,\nwhich has a lot less fancy syntax: we would instead present the core \\emph{type\n  formers} in Agda, and describe their semantics.\nThese type formers are basic types from which all other types can be built\n(although it's usually much more ergonomic to use the syntax that we have been\nusing up until now: working with these type formers exclusively can feel a\nlittle low-level at times).\n\nWe're going to explore them a little here: as the kind of basic subatomic\nparticles that make up every other type, they reveal a lot about the way types\nwork in general in Agda.\nAlso they can be useful in their own right: we've actually used all but one of\nthese types already.\n\nThe types \\agdabot, \\agdatop, and \\AgdaDatatype{Bool} are three of the basic\ntype formers in MLTT.\nOften they're called 0, 1, and 2; they're named for the number of elements which\ninhabit them.\n\nThe next basic type is usually called \\(\\Pi\\): it's the type of \\emph{dependent\n  functions}.\nWe've seen this type already, but here we should define it in a little more\ndepth.\n\\begin{definition}[Dependent Functions]\n  A dependent function is one where the return type \\emph{depends} on the value\n  of the input.\n  Here's a silly example:\n  \\begin{agdalisting*}\n    \\ExecuteMetaDataInline[agda/Snippets/Formers.tex]{nat-or-string}\n  \\end{agdalisting*}\n  When supplied with \\AgdaInductiveConstructor{true}, the return type of this\n  function is \\Nat; when given \\AgdaInductiveConstructor{false}, the\n  return type is \\AgdaDatatype{String}.\n\\end{definition}\n\nDependent functions are a built-in type in Agda, and they get the built-in\nsyntax that looks like the following:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Introduction.tex]{pi-syntax-2}\n\\end{agdalisting*}\nIf the \\(A\\) can be inferred, we could alternatively use the following syntax:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Introduction.tex]{pi-syntax-3}\n\\end{agdalisting*}\nFinally, if we wanted to avoid syntactic sugar altogether, we can use the\n\\(\\Pi\\) symbol:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Introduction.tex]{pi-syntax-1}\n\\end{agdalisting*}\nAll three of these expressions denote the same type.\n\nAs the symbol suggests, \\AgdaFunction{\\(\\Pi\\)} types are \\emph{product} types.\nThis might seem strange at first: a product type is usually a tuple,\ni.e. the pair type we saw in \\Cref{pair-def}.\nAs it happens, given the basic type formers we've defined so far, we can\nactually make the pair type:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Formers.tex]{pair-def}\n\\end{agdalisting*}\nThis type has all the functions we might need on a standard pair:\n\\begin{multicols}{3}\n  \\begin{agdalisting*}\n    \\ExecuteMetaDataInline[agda/Snippets/Formers.tex]{fst-def}\n  \\end{agdalisting*} \\columnbreak\n  \\begin{agdalisting*}\n    \\ExecuteMetaDataInline[agda/Snippets/Formers.tex]{snd-def}\n  \\end{agdalisting*} \\columnbreak\n  \\begin{agdalisting*}\n    \\ExecuteMetaDataInline[agda/Snippets/Formers.tex]{mk-pair}\n  \\end{agdalisting*}\n\\end{multicols}\n\nNow that we have the type of dependent products, it's natural to ask if we have\na type for dependent sums.\nThis is a type we \\emph{haven't} seen before, although we have all the pieces\nneeded to define it.\n\\begin{definition}[The Dependent Sum]\n  Dependent sums are denoted with the usual \\(\\Sigma\\) symbol, and has the\n  following definition in Agda:\n  \\begin{agdalisting*}\n    \\ExecuteMetaDataInline[agda/Snippets/Introduction.tex]{sigma}\n  \\end{agdalisting*}\n  The dependent sum is like the constructive version of the existential\n  quantifier: the expression \\(\\AgdaDatatype{\\(\\Sigma\\)}\\;A\\;B\\) can be\n  interpreted as ``there exists an \\(A\\) such that \\(B\\)''.\n\\end{definition}\n\nThere are a number of different syntactic ways to express\n\\(\\AgdaDatatype{\\(\\Sigma\\)}\\;A\\;B\\).\nThe following are all equivalent:\n\\begin{multicols}{4}\n  \\begin{agdalisting*}\n    \\ExecuteMetaDataInline[agda/Snippets/Introduction.tex]{sigma-syntax-1}\n  \\end{agdalisting*} \\columnbreak\n  \\begin{agdalisting*}\n    \\ExecuteMetaDataInline[agda/Snippets/Introduction.tex]{sigma-syntax-3}\n  \\end{agdalisting*} \\columnbreak\n  \\begin{agdalisting*}\n    \\ExecuteMetaDataInline[agda/Snippets/Introduction.tex]{sigma-syntax-4}\n  \\end{agdalisting*} \\columnbreak\n  \\begin{agdalisting*}\n    \\ExecuteMetaDataInline[agda/Snippets/Introduction.tex]{sigma-syntax-2}\n  \\end{agdalisting*}\n\\end{multicols} \\vspace{-1\\baselineskip}\n\nThough we have shown that the dependent function type is suitable as a pair\ntype, \\AgdaDatatype{\\(\\Sigma\\)} is actually a little easier to use as our basic\npair type.\n\\begin{agdalisting}\n  \\ExecuteMetaDataInline[agda/Snippets/Formers.tex]{pair-sigma}\n\\end{agdalisting}\nSo how, then, is \\AgdaDatatype{\\(\\Sigma\\)} a sum type?\nSum types in non-dependent type theory are the disjoint unions:\n\\begin{agdalisting}\n  \\ExecuteMetaDataInline[agda/Snippets/Introduction.tex]{disj-union}\n\\end{agdalisting}\nIt turns out that we can actually use a quite similar trick to how we got the\npair from \\AgdaDatatype{\\(\\Pi\\)}:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Introduction.tex]{sigma-disj-union}\n\\end{agdalisting*}\n\\subsection{The Menagerie of Foundational Theories}\nSo far we have mentioned four different foundational theories: Martin-Löf Type\nTheory, Homotopy Type Theory, Cubical Type Theory, and Zermelo-Fraenkel set theory.\nWe have given some hints as to the differences between these theories, but now\nWe have enough background information to give a fuller explanation as to their\ndifference and historical context.\n\nFirstly we have Zermelo-Fraenkel set theory, or ZFC, where the C stands for\n``choice'', i.e. the axiom of choice.\nThis is the standard foundational system for most mathematics these days: it's a\nset theoretic foundation, and it's \\emph{classical}, by which we mean\nnon-constructive.\nThis means that it has the law of the excluded middle (for any given\nproposition, the proposition is either true or false), and the axiom of choice\n(the product of a collection of non-empty sets is non-empty).\n\nWe won't describe ZFC in much detail here, we only mention it to contrast it\nwith type theory.\nType theory is less extensional than set theory: in set theory we construct sets\nby saying which things they contain.\nThese things exist ambiently, independent of the set (or sets) which contain\nthem.\nTo define the set of the natural numbers, for example, we first need there to\nexist objects which represent each of the numbers. \nBefore defining \\(\\mathbb{N}\\), we need to have defined 1 and 2.\n\nType theory is quite different in this sense.\nThe analogous construct to the set (the type) constructs its contents in its\ndefinition.\nSo the type of the natural numbers contains the definition (or construction) of\nits contents.\nIt doesn't make sense to define a type which contains items in other types: in\nfact it's not possible.\n\nSo that is the difference in mechanics between type theory and set theory: other\nthan the non-constructive components of set theory, though, the two theories are\nequivalent.\n\nWithin type theory then we have three different systems: MLTT, HoTT, and CuTT\n(of course there are many more type theories than just these three: these are\nonly the theories we will study here).\nThe first of these was one of the first type theories to be defined: Per\nMartin-Löf's intuitionistic type theory\n\\citep{martin-lofIntuitionisticTypeTheory1980} defined the basics of dependent\ntypes as we use them in Agda today.\nThis early theory had the \\(\\Sigma\\) and \\(\\Pi\\) types we have above, as\nwell as the boolean types, and \\(\\top\\) and \\(\\bot\\).\nWith some changes to the system (the addition of universe levels prompted by\nGirard's paradox), it's basically the core of Agda today.\n\nHoTT \\citep{hottbook} is a type theory which stems in many ways from MLTT, but\nmixes it with homotopy theory.\nThe fundamental addition of HoTT is the univalence axiom, which allows for\nisomorphic types to be treated as equivalent.\nCuTT \\citep{cohenCubicalTypeTheory2016} is closely related to HoTT: it is the\ntheory which allows us to use univalence in Agda while retaining the\ncomputational properties that we would expect in a constructive system.\n\\subsection{Comparing Classical And Constructive Proofs in Agda}\nThe dependent sum is a great example of the difference between ``classical'' and\n``constructive'' mathematics: the closest analogue in classical mathematics to\n\\AgdaDatatype{\\(\\Sigma\\)} is \\(\\exists\\), but the semantics of the two\nconstructs are subtly different.\nIf I say ``there exists an integer larger than 10'' I'm making a rather\ntrivially true statement; to provide a proof that\n\\(\\AgdaDatatype{\\(\\Sigma\\)}\\;\\Nat\\;\\lambda\\;\\AgdaBound{n}\\rightarrow\n\\AgdaNumber{10}\\;\\AgdaFunction{<}\\;\\AgdaBound{n}\\) is more akin to providing a\nnatural number, and proving that it's bigger than 10.\n\nMore formally speaking, there are a number of axioms which we don't have access\nto constructively.\nOne such axiom is double negation elimination:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Classical.tex]{doubleneg-elim}\n\\end{agdalisting*}\nOne way to ``do'' classical mathematics within Agda, then, would be to write all\nof the proofs assuming these axioms.\nWe don't have to break the guarantees Agda provides, either: we could say\n``given the axiom of choice, law of the excluded middle, etc., the following is\ntrue\\textellipsis'', although this is a little clunky.\n\nInstead, using this axiom of double negation, we can actually provide a type for\nclassical computation.\n\\begin{agdalisting}\n  \\ExecuteMetaDataInline[agda/Snippets/Classical.tex]{classical-def}\n\\end{agdalisting}\nIn the ``propositions-as-types'' sense, a value of type\n\\(\\AgdaFunction{Classical}\\;A\\) is a classical proof of the proposition \\(A\\).\nThis translation between classical and constructive proofs using double negation\nis sometimes called the double-negation translation.\n\nWe can prove, inside this type, things like the law of the excluded middle:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Classical.tex]{lem-proof}\n\\end{agdalisting*}\nThis type forms a monad, meaning that it implements the following functions:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Classical.tex]{monad}\n\\end{agdalisting*}\nThis gives us a convenient syntax to work with classical proofs.\n\nFinally, in HoTT we have a notion of \\emph{stability}.\nCertain types do support double-negation elimination:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Relation/Nullary/Stable.tex]{stable-def}\n\\end{agdalisting*}\nWe will see a use for this notion later on, but we mention it here to point out\nthat we do have a way of describing types which can be pulled out of classical\nproofs.\n\nThe purpose of this last subsection was to demonstrate that constructive\nmathematics, far from being constrained in comparison to classical, are\ntechnically \\emph{more} capable.\nWe can actually use systems to Agda to check and verify classical proofs just as\nmuch as we can constructive.\n\\subsection{Computational Behaviour}\nUp until this point we have been suspiciously quiet on the issue of performance\nor efficiency.\nWhile everything we're doing is absolutely valid as a purely theoretical\nexercise, it is nonetheless interesting to ask what these proofs and programs\nperform like on a computer.\n\nThe first thing to note is that Agda is a \\emph{lazy} language.\nThis means that expressions are not evaluated until they're needed.\nTake the following function:\n\\begin{agdalisting*}\n  \\ExecuteMetaDataInline[agda/Snippets/Complexity.tex]{f-def}\n\\end{agdalisting*}\nSince this function ignores its argument, Agda won't \\emph{compute} its\nargument.\nIf we called, for instance,\n\\(\\AgdaFunction{f}\\;(\\AgdaNumber{1000}\\;\\AgdaFunction{+}\\;\\AgdaNumber{1000})\\),\nwe wouldn't ever have to pay the cost of computing\n\\(\\AgdaNumber{1000}\\;\\AgdaFunction{+}\\;\\AgdaNumber{1000}\\).\n\nIt's important to note that this difference in performance is usually \\emph{not}\nobservable in actual computation.\nUnless we are working with coinductive types (which we will not do in this\nthesis), Agda's semantics are agnostic as to evaluation strategy.\nA program that terminates with lazy evaluation will also terminate with strict.\nIt's just that one might take a much longer (but still finite!) amount of time\nto do so.\n\nThe second thing to note is that, in order to make proofs easier, we often work\nwith inefficient forms of certain data types.\nThe natural numbers, for instance, we represent as basically a singly-linked\nlist; there are no flat arrays to be found anywhere in Agda; and recursion\n(albeit tail-call optimised recursion) is the tool of choice for iterative\ncomputation.\nThere is some help: in certain cases Agda will optimise the natural numbers to\nactual binary numbers (arbitrary precision Haskell integers), and Agda's purity\nallows for a certain degree of optimisation.\nOverall, though, unfortunately Agda is quite slow.\nComputing an expression like \\(\\AgdaBound{n}\\;\\AgdaFunction{+}\\;\\AgdaBound{m}\\)\nwill usually take \\(\\mathcal{O}(\\AgdaBound{n})\\) time, and there's not really a\ngreat way to get around it.\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: \"../paper\"\n%%% End:\n", "meta": {"hexsha": "5cd57bc14f89403ab7566ee803326ac4730860e9", "size": 51068, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "sections/agda-intro.tex", "max_stars_repo_name": "oisdk/masters-thesis", "max_stars_repo_head_hexsha": "9c5e8b6f546bee952e92db0b73bfc12592bf3152", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-01-05T14:07:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T15:32:14.000Z", "max_issues_repo_path": "sections/agda-intro.tex", "max_issues_repo_name": "oisdk/masters-thesis", "max_issues_repo_head_hexsha": "9c5e8b6f546bee952e92db0b73bfc12592bf3152", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sections/agda-intro.tex", "max_forks_repo_name": "oisdk/masters-thesis", "max_forks_repo_head_hexsha": "9c5e8b6f546bee952e92db0b73bfc12592bf3152", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-05T14:05:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-05T14:05:30.000Z", "avg_line_length": 47.9061913696, "max_line_length": 149, "alphanum_fraction": 0.774457586, "num_tokens": 13548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.31795327862308276}}
{"text": "\n\\documentclass[11pt,paper=a4]{report}\n\n\\usepackage[a4paper,landscape]{geometry}\n\n\n%Chapter caption is somewhere in the center of the page, so move the shit ;)\n%\\renewcommand*\\chapterheadstartvskip{\\vspace*{-1cm}}\n\n%If you have a new chapter, the pagestyle will be plain (only pagenumber) according to koma\n%To use ur setting redefine the chaperstyle\n%\\renewcommand*{\\chapterpagestyle}{scrheadings} \n\n%Settings for head and foot\n\n%\\usepackage[myheadings]{fullpage}\n%\\pagestyle{myheadings}\n\n\\usepackage{fancyhdr}\n%\\fancyhead{}\n%\\fancyhead[CO,CE]{---Draft---}\n\\pagestyle{fancy}\n\\rhead{}\n\n\n%\\usepackage{scrpage2} \n%\\clearscrheadfoot\n%\\pagestyle{scrheadings}\n\n%\\ihead{top left}\n%\\chead{top center}\n%\\ohead{top right}       \n\n%\\ifoot{bottom left} \n%\\cfoot{bottom center}\n%\\ofoot{bottom right}\n\n\\usepackage{amsmath}\n\\usepackage{color}\n\\usepackage{graphicx}\n\\usepackage{cancel}\n\\usepackage[usenames,dvipsnames]{xcolor}\n\\usepackage{chngcntr}\n\\usepackage{natbib}\n\n\\usepackage{hyperref}\n\\hypersetup{\n        colorlinks = true,\n        linkcolor = blue,\n        anchorcolor = red,\n        citecolor = blue,\n        filecolor = red,\n        urlcolor = red\n} \n\n\n\\newcommand{\\Msun}{\\mbox{M$_\\odot$\\,}}         % M_sun \n\n\\newcommand{\\eht}{\\overline}    \n\\newcommand{\\fht}{\\widetilde}    \n\\newcommand{\\dr}{\\frac{\\partial}{\\partial r}}\n\\newcommand{\\dt}{\\frac{\\partial}{\\partial t}}\n\\newcommand{\\dth}{\\frac{\\partial}{\\partial \\theta}}\n\\newcommand{\\dph}{\\frac{\\partial}{\\partial \\phi}}\n\n\\newcommand{\\fav}{\\widetilde}    \n\\newcommand{\\av}{\\overline}  \n\n\\def\\ef#1{#1'}\n\\def\\ff#1{#1''}\n\\def\\fhtc#1{\\left\\{#1\\right\\}}\n\\def\\erho{\\eht{\\rho}}\n\n\\newcommand{\\dgr}{\\mbox{$^\\circ$}}           % degrees \n\n\\counterwithout{section}{chapter}\n\n\\usepackage{titling}\n\\newcommand{\\subtitle}[1]{%\n  \\posttitle{%\n    \\par\\end{center}\n    \\begin{center}\\large#1\\end{center}\n    \\vskip0.5em}%\n}\n\n\\title{{\\bf ransX framework}}\n\\subtitle{Implementation Guide}\n\\author{\n        Miroslav Moc\\'ak, Casey Meakin, Simon Campbell, Cyril Georgy, Maxime Viallet, Dave Arnett\n}\n\n\\date{\\today}\n\n\\begin{document}\n\n\\bibliographystyle{plainnat}\n%\\begin{landscape}\n\\maketitle\n\n\\tableofcontents\n\n\\newpage\n\n\\section{Introduction}\n\nThis implementation guide describes all parts of our analysis framework for multi-fluid compressible hydrodynamic simulation targeted at all of you, who wants to implement it to your hydrodynamic codes and use our post-processing software to display its results.\\\\\n\nransX or rans(eXtreme) framework is a theoretical and programmatic suite allowing for comprehensive analysis of statistical averages of all sort of hydrodynamic properties from 3D simulations in spherical and Cartesian geometry. It consists of three main parts:\n\n\\begin{itemize}\n\\item theoretical derivation of 1D Reynolds-averaged Navier-Stokes (RANS) mean-field equations for transport/flux/variance of mass, momenta, kinetic/internal/total energy, temperature, enthalpy, pressure and chemical composition (see ransXtheoryGuide.pdf for more details)\n\\item calculation of required mean-fields for construction of terms in the RANS equations at runtime of hydrodynamic simulations\n\\item construction of terms in the RANS equations and their plotting  \n\\end{itemize}\n\n\\par We obtain our 1D RANS equations by introducing two types of averaging:  statistical averaging and  horizontal averaging \\citep{Besnard1992,VialletMeakin2013}. In practice, statistical averages are computed by performing a time average. Therefore, the combined average of a quantity $q$ is defined for spherical geometry as\n\n\\begin{align}\\label{eq:eht}\n\\eht{q}(r,t) = \\frac{1}{T\\Delta\\Omega}\\int_{t- T/2}^{t+T/2} q(r,\\theta,\\phi,t')~d\\Omega~dt'\n\\end{align}\n\n\\noindent where $d \\Omega = \\sin \\theta d \\theta d \\phi$ is the solid angle in spherical coordinates, $T$ is the averaging time period, and $\\Delta\\Omega$ is total solid angle being averaged over. The quantity $q$ is defined for cartesian geometry as\n\n\\begin{align}\\label{eq:eht}\n\\eht{q}(x,t) = \\frac{1}{T \\Delta y \\Delta z}\\int_{t- T/2}^{t+T/2} q(x,y,z,t')~dy~dz~dt'\n\\end{align}\n\n\\noindent where $\\Delta y$ and $\\Delta z$ is total number of grid zones in $y$ and $z$ direction.\\\\\n\n\\par The flow variables are then decomposed into mean and fluctuation $q = \\eht{q} + q'$, noting that $\\eht{q'} = 0$ by construction. Similarly, we introduce Favre (or density weighted) averaged quantities by \n\n\\begin{align}\n\\fht{q} = \\frac{\\eht{\\rho q}}{\\eht{\\rho}}\n\\end{align}\n\n\\noindent which defines a complimentary decomposition of the flow into mean and fluctuations according to $q = \\fht{q} + \\ff{q}$. Here, $\\ff{q}$ is the Favrian fluctuation and its mean is zero when Favre averaged $\\fht{\\ff{q}} = 0$. For a more complete elaboration on the algebra of these averaging procedures we refer the reader to \\citet{Chassaing2010}\n\n\\section{Calculation of ransX mean fields}\n\nWe perform the calculation of required mean-fields at runtime of hydrodynamic simulations and exploit various identities between terms in our RANS equations and space-time averaged thermodynamic quantities or their products. For example, mass flux $\\eht{\\rho'u'_r} = \\eht{\\rho u_r} - \\eht{\\rho} \\ \\eht{u_r} $, so in order to calculate the mass flux, we need $\\eht{\\rho u_r}$, $\\eht{\\rho}$, $\\eht{u_r}$. The following subsections describe this methodology implemented to the multi-fluid compressible hydrodynamic code PROMPI of \\citep{MeakinArnett2007} and post-processing tool tailored for its output written in Python \\href{https://github.com/mmicromegas/ransX}{https://github.com/mmicromegas/ransX}. This github repository contains also PROMPI's subroutines that deal with RANS averaging and storage located in directory UTILS/FOR\\_YOUR\\_HYDRO. {\\bf Feel free to use them in your hydrodynamic codes as well. We hope it speeds up integration of our ransX framework to your research projects.} The directory contains also README file, that will provide you with more details about how and where we use the subroutines in PROMPI.  \n\n\\subsection{Initialization and calculation in hydrodynamic code PROMPI}\n\nOur main array for storage of space-time averages between two consecutives data dumps is called $havg$. It is a three dimensional array declared as $havg(4,nrans,qqx)$. First index referes to identification position of horizontal averages of three-dimensional thermodynamic quantities required either at initialization or update stage of hydrodynamic simulation. The seconds index is the number of RANS mean-fields we calculate. The third index is number of grid points in radial or $x$ direction (depending on geometry).\n\nThe main subroutine, where we calculate $havg$ is called {\\bf rans\\_avg.f90}. It requires an input of one parameter called $imode$, which tells it where in hydrodynamic simulation it is being called and whether it should be initializing $havg$ or updating it (Fig.\\ref{havg:init}). If in initialization mode ($imode.eq.0$), it initializes also an array called $ransname$ (Fig.\\ref{havg:calc}), which holds names of horizontally-averaged variables. The $havg$ data is stored in a binary file with extension ransdat, whether variables like $ransname$ to a text file with extension ranshead together with other variables like resolution and dump times. \n\n\\begin{figure}[!h]\n\\centerline{\n\\includegraphics{initialize_havg.png}}\n\\caption{Initialization of $havg$ array in {\\bf rans\\_avg.f90}}\n\\label{havg:init}\n\\end{figure}\n\nAfter the initialization, horizontal averages are being computed as show in the example in Fig.\\ref{havg:calc} according to Equation \\ref{eq:horizontal}  and stored in the $havg$ array where the identification position index is set to 2 i.e. $havg(2,ifield,i)$. The scaling factor in case of spherical geometry $\\sin \\theta d \\theta d \\phi / \\Delta \\Omega$ is the variable $fsteradjk$. In case of cartesian geometry, this factor will be equal to one.  \n\n\\begin{align}\n\\label{eq:horizontal}\n\\langle q \\rangle (r,t) = \\frac{1}{\\Delta \\Omega} \\int \\int q(r,\\theta,\\phi,t)~\\sin \\theta d \\theta d \\phi\n\\end{align}\n\n\\begin{figure}[!h]\n\\centerline{\n\\includegraphics{rans_avg_snippet.png}}\n\\caption{Demonstration loop of horizontal averaging (Eq.\\ref{eq:horizontal}), where $\\langle q \\rangle$(r,t) is $havg(2,ifield,i)$ taking geometry into account with scaling variable $fsteradjk$}\n\\label{havg:calc}\n\\end{figure}\n\nAfter calculation of these horizontal averages, they are turned into a variable that we call running averages defined in Equation \\ref{eq:runaverage} and stored in $havg$ array with identification position index set to 3 i.e. $havg(3,ifield,i)$ (Fig.\\ref{fig:runaverage}). These running averages are horizontal averages, that are additionally averaged further taking into account previous hydro sweep stored in $havg$ with identification position index set to 1 and updated as shown in Fig.\\ref{havg:init}. \n%\\begin{figure}[!h]\n%\\centerline{\n%\\includegraphics{prompi_havg_detail.png}}\n%\\caption{Calculation of running average }\n%\\end{figure}\n\n\\begin{align}\n  q_{\\mbox{run}} = \\sum_i \\left(\\langle q^n \\rangle_i + \\langle q^n \\rangle_{i-1} \\right) \\ 0.5 \\ \\Delta t_i\n\\label{eq:runaverage}  \n\\end{align}  \n\n\\begin{figure}[!h]\n\\centerline{\n\\includegraphics{update_running_average.png}}\n\\caption{Calculation of running averages (Eq.\\ref{eq:runaverage}), where $q_{\\mbox{run}}$ is $havg(3,n,i)$.}\n\\label{fig:runaverage}\n\\end{figure}\n\nThe running averages are later used in a subroutine {\\bf write\\_rans\\_data.f90} to calculate statistical average according to Equation \\ref{eq:stataverage} at the time of data dump as show in the Figure \\ref{fig:stataverage}.  \n\n\\begin{align}\n  \\overline{q} =  \\frac{q_{\\mbox{run}}}{\\sum_i \\Delta t_i}\n\\label{eq:stataverage}  \n\\end{align}  \n\n\\begin{figure}[!h]\n\\centerline{\n\\includegraphics{prompi_havg.png}}\n\\caption{Calculation of statistical average (Eq.\\ref{eq:stataverage}), where $\\overline{q}$ is $havg\\_sum\\_tot\\_global(3,k,i)$. $rans\\_tavg$ calculation is shown in Figure \\ref{fig:runaverage}.}\n\\label{fig:stataverage}\n\\end{figure}\n\n\n\\subsection{Post-processing in Python}\n\nThe statistical averages calculated according to Eq.\\ref{eq:stataverage} are only between two consecutives data dumps, that typically cover time much shorter than a convective turnover timescale (TO). In order to get robust statistical averages, we need to calculate the averages over at least three TOs. For that we use python script called $rans\\_tseries.py$, that is using calculated $q$s stored in ransdat files according to Equation \\ref{eq:tseries} shown in Figure \\ref{fig:tseries}. \n\nThe script takes advantage of ranshead files, that contain names of the RANS mean fields in exact order as they are stored in $havg$ array and stores the final mean fields in a dictionary variable called $eht$. The dictionary is at the end stored in python's $npy$ file, that can be easily read by RANS equations classes, which calculate and plot terms of ransX framework equations.\n\n\\begin{align}\n  \\overline{Q} = \\frac{\\overline{q} \\ \\Delta t_{\\mbox{dumps}}}{\\sum_{\\mbox{dumps}} \\Delta t_{\\mbox{dumps}}}\n\\label{eq:tseries}  \n\\end{align}\n\n\\begin{figure}[!h]\n\\centerline{\n\\includegraphics{tseries_averaging.png}}\n\\caption{Statistical averages as calculated by {\\bf ransx\\_tseries.py} and Eq.\\ref{eq:tseries} over time interval between $timec[i]-tavg/2$ and $timec[i]+tavg/2$. The $timec[i]$ is central time around which we can calculate statistical average over time specified by $tavg$. The $eht$ is $\\overline{Q}$, the $q$ is loaded into a list called $eh$, the time between consecutives dumps is $dt$, the total time over which we need the statistical average is $sumdt$.}\n\\label{fig:tseries}\n\\end{figure}\n\n\\section{Implementation of ransX equations}\n\nMean-fields RANS equations are in our framework implemented using python classes each dedicated to one equation. All the classes are stored in directory EQUATIONS. Every class has almost the same structure inheriting some methods from classes CALCULUS.py and ALIMIT.py and consisting of a constructor method $\\_init\\_$, where we initialize whole class with data read from the $npy$ file and use them to construct all terms in RANS equations using various identities as shown in Section \\ref{sect:usefulidentities} at the end of this document. The second method plots mean-field thermodynamic quantity for which we want to see RANS equation implemented in the class. Terms in these equations are then shown by third method \\footnote{Warning: Labels of plot lines are not adjusted for simulation in Cartesian geometry yet.}. Sometimes, such a class contains fourth method, that calculates integral budget for each of the mean-field of the equations according to volume integral Equation \\ref{eq:integralbudget}\n\n\\begin{align}\n  I_{\\mbox{budget}} = \\int_r 4 \\pi r^2 \\ \\overline{Q}_{\\mbox{RANS}} / dr\n\\label{eq:integralbudget}  \n\\end{align}\n\nNext subsections contain description of some EQUATIONs classes and implementation/calculation of RANS equations terms for hydrodynamic simulation in spherical geometry.  The folder EQUATIONS contain also classes for plotting of some background quantities like temperature gradient, degeneracy or Brunt-Vaisalla frequency, but we skip those for now.\n\n\\subsection{Continuity Equation with Mass FLux}\n\nFollowing lines describe exact mapping between actual physical mean-fields and their counterparts in the ContinuityEquationWithMassFlux.py. A snippet of the code is shown in Figure \\ref{fig:cont_mass_flux}.\n\n\\begin{align}\n  \\fht{D}_t \\eht{\\rho} = & - \\nabla_r f_\\rho + (f_\\rho / \\eht{\\rho})\\partial_r \\eht{\\rho} - \\eht{\\rho}\\eht{d} \\\\\n  \\partial_t \\eht{\\rho} + \\fht{u}_r \\partial_r \\eht{\\rho} = & -\\nabla_r \\eht{\\rho'u'_r} + ( \\eht{\\rho'u'_r}/\\eht{\\rho})\\partial_r \\eht{\\rho} - \\eht{\\rho} \\nabla_r \\eht{u}_r) \\nonumber \\\\\n  \\partial_t t\\_dd + ddux/dd \\partial_r dd = & -\\nabla_r (ddux - dd*ux) + ((ddux-dd*ux)/dd) \\partial_r dd - dd \\nabla_r ux) \\nonumber  \\\\\n  \\partial_t t\\_dd + fht\\_ux \\ \\partial_r dd = & -\\nabla_r fdd + (fdd/dd) \\ \\partial_r dd - dd \\nabla_r ux) \\nonumber   \n\\end{align}\n\n\\begin{figure}[!h]\n\\centerline{\n\\includegraphics{ransx_continuity_with_mass_flux.png}}\n\\caption{Continuity equation with mass flux $f_\\rho$ as programmed into ContinuityEquationWithMassFlux.py}\n\\label{fig:cont_mass_flux}\n\\end{figure}\n\n\\subsection{Continuity Equation with Favrian Dilatation}\n\nFollowing lines describe exact mapping between actual physical mean-fields and their counterparts in the ContinuityEquationWithFavrianDilatation.py. A snippet of the code is shown in Figure \\ref{fig:cont_dil}.\n\n\\begin{table}[!h]\n\\label{tab:rans-xtrans}\n\\begin{align}\n% continuity equation\n  \\fht{D}_t \\eht{\\rho} = & -\\eht{\\rho}\\fht{d} \\\\\n  \\partial_t \\eht{\\rho} + \\fht{u}_r \\partial_r \\eht{\\rho} = & -\\eht{\\rho}\\fht{d} \\nonumber \\\\\n  \\partial_t t\\_dd + ddux/dd \\ \\partial_r dd = & -dd * \\nabla_r \\ ddux/dd \\nonumber \\\\\n  \\partial_t t\\_dd + fht\\_ux \\ \\partial_r dd = & -dd * \\nabla_r \\ fht\\_ux \\nonumber   \n\\end{align}\n\\end{table}\n\n\\begin{figure}[!h]\n\\centerline{\n\\includegraphics{ransx_continuity_with_favrian_dilatation.png}}\n\\caption{Continuity equation with favrian dilatation $\\fht{q}$ as programmed into ContinuityEquationWithFavrianDilatation.py}\n\\label{fig:cont_dil}\n\\end{figure}\n\n\n%\\subsection{Momentum Equation X}\n\n%\\subsection{Momentum Equation Y}\n\n%\\subsection{Momentum Equation Z}\n\n%\\subsection{Reynolds Stress XX}\n\n%\\subsection{Reynolds Stress YY}\n\n%\\subsection{Reynolds Stress ZZ}\n\n%\\subsection{Turbulent Kinetic Energy Equation}\n\n%\\subsection{Radial Turbulent Kinetic Energy Equation}\n\n%\\subsection{Horizontal Turbulent Kinetic Energy Equation}\n\n%\\subsection{Internal Energy Equation}\n\n%\\subsection{Internal Energy Flux Equation}\n\n%\\subsection{Internal Energy Variance Equation}\n\n%\\subsection{Kinetic Energy Equation}\n\n%\\subsection{Total Energy Equation}\n\n%\\subsection{Entropy Equation}\n\n%\\subsection{Entropy Flux Equation}\n\n%\\subsection{Entropy Variance Equation}\n\n%\\subsection{Pressure Equation}\n\n%\\subsection{Pressure Flux Equation}\n\n%\\subsection{Pressure Variance Equation}\n\n%\\subsection{Temperature Equation}\n\n%\\subsection{Temperature Flux Equation}\n\n%\\subsection{Temperature Variance Equation}\n\n%\\subsection{Enthalpy Equation}\n\n%\\subsection{Enthalpy Flux Equation}\n\n%\\subsection{Enthalpy Variance Equation}\n\n%\\subsection{Density Variance Equation}\n\n%\\subsection{Turbulent Mass Flux Equation}\n\n%\\subsection{Density-specific Volume Covariance Equation}\n\n\n\\subsection{Composition Transport Equation}\n\\label{sect:xtranseq}\n\nXtransportEquation.py\n\n\\begin{align}\n% composition transport\n\\erho\\fav{D}_t \\fav{X}_i = & -\\nabla_r f_i + \\erho \\fav{\\dot{X}}_i^{\\rm nuc} \\\\\n\\erho\\partial_t \\fav{X}_i + \\erho \\fav{u}_r \\partial_r \\fav{X}_i = & -\\nabla_r \\erho \\fav{X''_i u''_r} +  \\erho \\fav{\\dot{X}}_i^{\\rm nuc} \\nonumber \\\\\n\\partial_t \\erho \\fav{X}_i + \\partial_r \\erho \\fav{u}_r \\fav{X}_i = & -\\nabla_r \\erho \\fav{X''_i u''_r} +  \\erho \\fav{\\dot{X}}_i^{\\rm nuc} \\nonumber \\\\\n\\partial_t \\erho \\fav{X}_i + \\partial_r \\erho \\fav{u}_r \\fav{X}_i = & -\\nabla_r \\erho (\\fav{X_i u_r} - \\fav{X_i}\\fav{u_r}) +  \\erho \\fav{\\dot{X}}_i^{\\rm nuc} \\nonumber \\\\\n\\partial_t \\ \\erho \\ \\eht{\\rho X_i}/\\eht{\\rho} + \\partial_r \\ \\erho \\ \\eht{\\rho u_r}/\\eht{\\rho} \\ \\eht{\\rho X_i}/\\eht{\\rho} = & -\\nabla_r \\left(\\eht{\\rho X_i u_r} - \\eht{\\rho X_i}\\eht{\\rho u_r}/\\eht{\\rho} \\right) +  \\eht{\\rho \\dot{X}_i^{\\rm nuc}} \\nonumber \\\\\n\\partial_t \\left( t\\_dd * t\\_ddxi/t\\_dd \\right) + \\partial_r \\left( dd * ddux/dd * ddxi/dd \\right) = & -\\nabla_r \\left(ddxiux - ddxi*ddux/dd  \\right) + ddxidot \\nonumber \\\\\n\\partial_t \\left( t\\_dd * t\\_fht\\_xi \\right) + \\partial_r \\left( dd * fht\\_ux * fht\\_xi \\right) = & -\\nabla_r fxi + ddxidot \\nonumber\n\\end{align}\n\n\n%\\subsection{Composition Flux Equation}\n%\\label{sect:xflxeq}\n\n%\\begin{align}\n  % composition flux\n%\\erho \\fav{D}_t (f_i / \\eht{\\rho}) = &  -\\nabla_r f_i^r  - f_i \\partial_r \\fht{u}_r - \\fht{R}_{rr} \\partial_r \\fht{X}_i -\\eht{X''_i} \\partial_r \\eht{P} - \\eht{X''_i \\partial_r P'} + \\overline{u''_r \\rho \\dot{X}_i^{\\rm nuc}} + {\\mathcal G_i} \\\\\n%\\eht{\\rho} \\partial_t \\fht{X''_i u''_r} + \\eht{\\rho}\\fht{u}_r \\partial_r \\fht{X''_i u''_r} = &  -\\nabla_r \\eht{\\rho} \\fht{X''_i u''_r u''_r} - \\eht{\\rho}\\fht{X''_i u''_r}\\partial_r \\fht{u_r} - \\eht{\\rho}\\fht{u''_r u''_r}\\partial_r \\fht{X}_i - \\eht{X''_i} \\partial_r \\eht{P} - \\eht{X''_i \\partial_r P'} + \\eht{u''_r \\rho \\dot{X}_i^{\\rm nuc}} + \\eht{G_r^i} - \\eht{X''_i G_r^M} \\nonumber \\\\\n%\\eht{\\rho} \\partial_t \\fht{X''_i u''_r} + \\eht{\\rho}\\fht{u}_r \\partial_r \\fht{X''_i u''_r} = &  -\\nabla_r \\eht{\\rho} \\fht{X''_i u''_r u''_r} - \\eht{\\rho}\\fht{X''_i u''_r}\\partial_r \\fht{u_r} - \\eht{\\rho}\\fht{u''_r u''_r}\\partial_r \\fht{X}_i - \\eht{X''_i} \\partial_r \\eht{P} - \\eht{X''_i \\partial_r P'} + \\eht{u''_r \\rho \\dot{X}_i^{\\rm nuc}} \\nonumber \\\\\n%& - \\eht{\\rho X''_i u''_\\theta u''_\\theta/r} - \\eht{\\rho X''_i u''_\\phi u''_\\phi/r} + \\eht{\\rho X''_i u_\\theta u_\\theta/r} + \\eht{\\rho X''_i u_\\phi u_\\phi/r} \\nonumber \\\\\n%\\eht{\\rho} \\partial_t (\\fht{X_i u_r} - \\fht{X_i} \\fht{u}_r) + \\eht{\\rho}\\fht{u}_r \\partial_r (\\fht{X_i u_r} - \\fht{X_i} \\fht{u_r})  = &  -\\nabla_r (\\eht{\\rho X_i u_r u_r} -\\fht{X_i}\\eht{\\rho u_r u_r} - 2 \\fht{u_r} \\eht{\\rho X_i u_r} + 2\\eht{\\rho}\\fht{X_i}\\fht{u_r}\\fht{u_r}) \\nonumber \\\\\n%& - \\eht{\\rho}(\\fht{X_i u_r} -\\fht{X_i}\\fht{u}_r)\\partial_r \\fht{u}_r - \\eht{\\rho}(\\fht{u_r u_r} - \\fht{u}_r \\fht{u}_r)\\partial_r \\fht{X}_i \\nonumber \\\\\n%& - (\\eht{X_i} \\partial_r \\eht{P} - \\fht{X_i} \\partial_r \\eht{P}) - (\\eht{X_i \\partial_r P} - \\eht{X_i}\\partial_r \\eht{P})  + (\\eht{u_r \\rho \\dot{X}_i^{\\rm nuc}} - \\fht{u_r} \\eht{\\rho \\dot{X}_i^{\\rm nuc}}) \\nonumber \\\\\n%& - (\\eht{\\rho X_i u_\\theta u_\\theta} -\\fht{X_i}\\eht{\\rho u_\\theta u_\\theta} - 2 \\fht{u}_\\theta \\eht{\\rho X_i u_\\theta} + 2\\eht{\\rho}\\fht{X_i}\\fht{u}_\\theta\\fht{u}_\\theta)/r \\nonumber \\\\\n%& - (\\eht{\\rho X_i u_\\phi u_\\phi} -\\fht{X_i}\\eht{\\rho u_\\phi u_\\phi} - 2 \\fht{u}_\\phi \\eht{\\rho X_i u_\\phi} + 2\\eht{\\rho}\\fht{X_\\phi}\\fht{u}_\\phi\\fht{u}_\\phi)/r \\nonumber \\\\\n%& + (\\eht{\\rho X_i u_\\theta u_\\theta} - \\fht{X_i} \\eht{\\rho u_\\theta u_\\theta})/r \\nonumber \\\\\n%& + (\\eht{\\rho X_i u_\\phi u_\\phi} - \\fht{X_i} \\eht{\\rho u_\\phi u_\\phi})/r \\nonumber\n%\\end{align}\n\n%\\begin{align}\n%dd \\ \\partial_t (ddxiux/dd - ddxi*ddux/dd*dd) + ddux \\ \\partial_r (ddxiux/dd - ddxi*ddux/dd*dd) = \\nonumber \\\\\n%- \\nabla_r (ddxiuxux - ddxi/dd*dduxux - 2*ddux/dd*ddxiux +2*ddxi*ddux*ddux/dd*dd) \\nonumber \\\\\n%- (ddxiux - ddxi*ddux/dd) * \\partial_r ddux/dd - (dduxux - ddux*ddux/dd) * \\partial_r ddxi/dd \\nonumber \\\\\n%- (xi \\ \\partial_r \\ pp - ddxi/dd \\ \\partial_r \\ pp) - (xigradxpp - xi \\ \\partial_r \\ pp) + (ddxidotux - ddux/dd * ddxidot) \\nonumber \\\\\n%- (ddxiuyuy - ddxi/dd*dduyuy - 2*dduy/dd*ddxiuy + 2*ddxi*dduy*dduy/dd*dd)/r \\nonumber \\\\\n%- (ddxiuzuz - ddxi/dd*dduzuz - 2*dduz/dd*ddxiuz + 2*ddxi*dduz*dduz/dd*dd)/r \\nonumber \\\\\n%+ (ddxiuyuy - ddxi/dd*dduyuy)/r \\nonumber \\\\\n%+ (ddxiuzuz - ddxi/dd*dduzuz)/r \\nonumber\n%\\end{align}\n\n\n%\\subsection{Composition Variance Equation}\n%\\label{sect:xvareq}\n\n%\\begin{table}[!h]\n%\\label{tab:rans-xvar}\n  \n%\\begin{align}\n% composition sigma\n%\\eht{\\rho} \\fht{D}_t \\sigma_i = & -\\nabla_r f_i^r - 2 f_i \\partial_r \\fht{X}_i + 2 \\eht{X''_i \\rho \\dot{X}_i^{\\rm nuc}} \\\\\n%\\eht{\\rho} \\fht{D}_t \\fht{X''_i X''_i} = & -\\nabla_r (\\eht{\\rho X''_i X''_i u''_r} ) - 2 \\eht{\\rho}\\fht{X''_i u''_r} \\partial_r \\fht{X}_i + 2 \\eht{X''_i \\rho \\dot{X}_i^{\\rm nuc}} \\nonumber \\\\\n%\\eht{\\rho} \\partial_t (\\fht{X_i X_i} - \\fht{X_i}\\fht{X_i}) + \\eht{\\rho}\\fht{u}_r \\partial_r (\\fht{X_i X_i} - \\fht{X_i}\\fht{X_i}) = &  -\\nabla_r (\\eht{\\rho X_i X_i u_r} - 2 \\fht{X_i} \\eht{\\rho X_i u_r} - \\fht{u}_r \\eht{\\rho X_i X_i} + 2 \\fht{X}_i \\fht{X}_i \\eht{\\rho u_r} ) \\nonumber \\\\\n%& - 2 \\eht{\\rho} (\\fht{X_i u_r} - \\fht{X}_i \\fht{u}_r) \\partial_r \\fht{X}_i + (\\eht{X_i \\rho \\dot{X}_i} - \\fht{X}_i \\eht{\\rho \\dot{X}_i}) \\nonumber \\\\\n%dd \\ \\partial_t \\ (ddxisq/dd - ddxi*ddxi/dd*dd) & \\nonumber \\\\\n%+ \\ ddux \\ \\partial_r \\ (ddxisq/dd - ddxi*ddxi/dd*dd) = & -\\nabla_r (ddxisqux - 2*ddxi/dd*ddxiux - ddux/dd*ddxisq + 2*ddxi*ddxi*ddux/dd*dd) \\nonumber \\\\\n%& - \\ 2*dd \\ (ddxiux/dd - ddxi*ddux/dd*dd) * \\partial_r \\ ddxi/dd \\nonumber \\\\\n%& + 2 * (ddxixidot - ddxi/dd * ddxidot) \\nonumber\n%\\end{align}\n%\\end{table}\n\n\n\\subsection{Density-specific Volume Covariance}\n\nDensitySpecificVolumeCovarianceEquation.py \n\n\\begin{align}\n  \\eht{D}_t b = &  +\\eht{v} \\nabla_r \\eht{\\rho} \\eht{u''_r} -\\eht{\\rho}\\nabla_r (\\eht{u'_r v'}) + 2\\eht{\\rho}\\eht{v'd'} \\label{eq:rans_b}  \\\\\n  \\partial_t b + \\eht{u}_r \\partial_r b = & \\ \\eht{v} \\nabla_r \\eht{\\rho}(\\eht{u}_r - \\fht{u}_r) - \\eht{\\rho} \\nabla_r (\\eht{u_r v} - \\eht{u}_r \\eht{v}) + 2 \\eht{\\rho} (\\eht{vd} -\\eht{v}\\eht{d}) \\nonumber \\\\\n  \\partial_t \\eht{v'\\rho'} + \\eht{u}_r \\partial_r (\\eht{v'\\rho'}) = & \\ \\eht{v} \\nabla_r \\eht{\\rho}(\\eht{u}_r - \\fht{u}_r) - \\eht{\\rho} \\nabla_r (\\eht{u_r v} - \\eht{u}_r \\eht{v}) + 2 \\eht{\\rho} (\\eht{vd} -\\eht{v}\\eht{d})  \\nonumber \\\\\n  \\partial_t (\\underbrace{\\eht{v \\rho}}_\\text{1} - \\eht{v} \\ \\eht{\\rho}) + \\eht{u}_r \\partial_r (\\underbrace{\\eht{v \\rho}}_\\text{1} - \\eht{v} \\ \\eht{\\rho}) = & \\ \\eht{v} \\nabla_r \\eht{\\rho}(\\eht{u}_r - \\fht{u}_r) - \\eht{\\rho} \\nabla_r (\\eht{u_r v} - \\eht{u}_r \\eht{v}) + 2 \\eht{\\rho} (\\eht{vd} -\\eht{v}\\eht{d})   \\nonumber \\\\\n  -\\partial_t (\\eht{v} \\ \\eht{\\rho}) - \\eht{u}_r \\partial_r (\\eht{v} \\ \\eht{\\rho}) = & \\ \\eht{v} \\nabla_r \\eht{\\rho}(\\eht{u}_r - \\fht{u}_r) - \\eht{\\rho} \\nabla_r (\\eht{u_r v} - \\eht{u}_r \\eht{v}) + 2 \\eht{\\rho} (\\eht{vd} -\\eht{v}\\eht{d})  \\nonumber \\\\\n  \\partial_t (1-t\\_sv*t\\_dd) - ux \\ \\partial_r (1-sv*dd) = & \\ sv * \\nabla_r dd*(ux - ddux/dd) - dd \\ \\nabla_r (svux - sv*ux) + 2*dd*(svdivu - sv*divu)  \\nonumber \\\\\n  \\partial_t \\ t\\_b - ux \\ \\partial_r \\ b = & \\ sv * \\nabla_r \\ dd*(ux - ddux/dd) - dd \\ \\nabla_r (svux - sv*ux) + 2*dd*(svdivu - sv*divu)  \\nonumber \\\\\n   \\partial_t \\ t\\_b - ux \\ \\partial_r \\ b = & \\ sv * \\nabla_r \\ dd*(ux - fht\\_ux) - dd \\ \\nabla_r (svux - sv*ux) + 2*dd*(svdivu - sv*divu)  \\nonumber  \n\\end{align}  \n\n\n\n%\\subsection{Density Variance Equation}\n\n%\\begin{align}\n% sigma density\n%  \\fht{D}_t \\sigma_\\rho =  &  - \\nabla_r \\eht{(\\rho' \\rho ' u''_r)}  - 2\\eht{\\rho} \\ \\eht{\\rho'd''} - 2 \\eht{\\rho'u''_r} \\partial_r \\eht{\\rho} - 2 \\fht{d} \\ \\sigma_\\rho - \\eht{\\rho'\\rho'd''} \\\\\n%  \\partial_t \\eht{\\rho'\\rho'} + \\fht{u}_r \\partial_r \\eht{\\rho'\\rho'} =  &  - \\nabla_r \\eht{(\\rho' \\rho ' u''_r)}  - 2\\eht{\\rho} \\ \\eht{\\rho'd''} - 2 \\eht{\\rho'u''_r} \\partial_r \\eht{\\rho} - 2 \\fht{d}\\eht{\\rho'\\rho'}  - \\eht{\\rho'\\rho'd''} \\\\\n%  \\partial_t (\\eht{\\rho\\rho} - \\eht{\\rho} \\ \\eht{\\rho}) + \\fht{u}_r \\partial_r (\\eht{\\rho\\rho} - \\eht{\\rho} \\ \\eht{\\rho}) = & -\\nabla_r (\\eht{\\rho \\rho u_r} - 2\\eht{\\rho u_r} \\ \\eht{\\rho} + \\eht{\\rho} \\eht{\\rho} \\ \\eht{u_r} - \\eht{\\rho \\rho}\\fht{u}_r + \\eht{\\rho} \\ \\eht{\\rho} \\fht{d}) \\\\\n%  & -2\\eht{\\rho}(\\eht{\\rho d} - \\eht{\\rho}\\fht{d} - \\eht{\\rho} \\ \\eht{d} + \\eht{\\rho}\\fht{d}) \\\\\n%  & -2(\\eht{\\rho u_r} - \\eht{\\rho}\\fht{u}_r - \\eht{\\rho} \\ \\eht{u}_r + \\eht{\\rho}\\fht{u}_r)\\partial_r \\eht{\\rho} \\\\\n%  & -2 \\fht{d} (\\eht{\\rho \\rho} - \\eht{\\rho} \\ \\eht{\\rho}) - (\\eht{\\rho \\rho u_r} - 2\\eht{\\rho u_r} \\ \\eht{\\rho}+ \\eht{\\rho} \\ \\eht{\\rho} \\eht{u}_r -\\eht{\\rho \\rho}\\fht{u}_r + \\eht{\\rho} \\ \\eht{\\rho} \\fht{d}) \\\\\n%  \\partial_t (ddsq - dd*dd) & \\\\\n%  + ddux/dd \\partial_r (ddsq - dd*dd) = & \\nonumber \\\\\n%  & - \\nabla_r (ddddux - 2*ddux*dd + ddsq*ux - ddsq*ddux/dd + dd*dd*ddux/dd) \\nonumber \\\\\n%  & -2*dd*(-dd*divu + dddivu) -2*(-dd*ux + ddux) \\partial_r dd \\nonumber \\\\\n%  & -2*dddivu/dd * (ddsq - dd*dd) \\nonumber \\\\\n%  & -(dddddivu - 2*dddivu*dd + ddsq*divu - ddsq*dddivu/dd + dd*dddivu) \\nonumber\n%\\end{align}  \n  \n%\\subsection{Internal Energy Variance Equation}\n\n%\\begin{align}\n% sigma internal energy\n%  \\eht{\\rho} \\fht{D}_t \\sigma_{\\epsilon I} = &  -\\nabla_r (\\eht{\\rho \\epsilon''_I \\epsilon''_I u''_r} ) - 2 f_I \\partial_r \\fht{\\epsilon_I} - 2\\overline{\\epsilon''_I}\\ \\eht{P} \\ \\fht{d} - 2\\eht{P} \\ \\eht{\\epsilon''_I d''} - 2\\fht{d} \\ \\eht{\\epsilon''_I P'} - 2\\overline{\\epsilon''_I P' d''} + 2\\eht{\\epsilon''_I {\\mathcal S}} \\\\\n%  \\eht{\\rho} \\fht{D}_t \\fht{\\epsilon''_I \\epsilon''_I} = &  -\\nabla_r (\\eht{\\rho \\epsilon''_I \\epsilon''_I u''_r} ) - 2 \\eht{\\rho} \\fht{\\epsilon''_I u''_r} \\partial_r \\fht{\\epsilon_I} - 2\\overline{\\epsilon''_I}\\ \\eht{P} \\ \\fht{d} - 2\\eht{P} \\ \\eht{\\epsilon''_I d''} - 2\\fht{d} \\ \\eht{\\epsilon''_I P'} - 2\\overline{\\epsilon''_I P' d''} + 2\\eht{\\epsilon''_I \\rho \\varepsilon_{nuc}} \\\\\n%  \\eht{\\rho} \\partial_t \\fht{\\epsilon''_I \\epsilon''_I} + \\eht{\\rho} \\fht{u_r} \\nabla_r (\\fht{\\epsilon''_I \\epsilon''_I})  = &  -\\nabla_r (\\eht{\\rho \\epsilon''_I \\epsilon''_I u''_r} ) - 2 \\eht{\\rho} \\fht{\\epsilon''_I u''_r} \\partial_r \\fht{\\epsilon_I} - 2\\overline{\\epsilon''_I}\\ \\eht{P} \\ \\fht{d} - 2\\eht{P} \\ \\eht{\\epsilon''_I d''} - 2\\fht{d} \\ \\eht{\\epsilon''_I P'} - 2\\overline{\\epsilon''_I P' d''} + 2\\eht{\\epsilon''_I \\rho \\varepsilon_{nuc}}\n%\\end{align}\n\n%\\begin{align}  \n%  dd*\\partial_t (ddeiei/dd - ddei*ddei/(dd*dd)) + & \\nonumber \\\\\n%  ddux*\\nabla_r  (ddeiei/dd - ddei*ddei/(dd*dd)) & = \\nonumber \\\\\n%  & -\\nabla_r (ddeieiux/dd - 2 * ddei/dd * ddeiux/dd - ddux/dd*ddeiei/dd \\nonumber \\\\\n%  & + 2*ddei*ddei*ddux/(dd*dd*dd)) \\nonumber \\\\\n%  & -2*dd*(ddeiux/dd - ddei*ddux/(dd*dd))\\partial_r ddei/dd \\nonumber \\\\\n%  & -2*(ei - ddei/dd)*pp*dddivu/dd \\nonumber \\\\\n%  & -2*pp*(eidd - ei*dddivu/dd - ddei/dd*divu + ddei*dddivu/dd) \\nonumber \\\\\n%  & -2*dddivu/dd*(eippdivu - eidivu*pp - ddei/dd*ppdivu \\nonumber \\\\\n%  & + ddei/dd*pp*dd - eipp*dddivu/dd + ei*pp*dddivu/dd) \\nonumber \\\\\n%  & + 2*(eiddenuc - ddei/dd*(ddenuc1+ddenuc2))\n%\\end{align}\n\n\n%\\subsection{Mean Number of Nucleon per Isotope a.k.a Abar Equation}\n\n%\\subsection{Mean Number of Nucleon per Isotope Flux a.k.a Abar Flux Equation}\n\n%\\subsection{Mean Charge per Isotope a.k.a Zbar Equation}\n\n%\\subsection{Mean Charge per Isotope Flux a.k.a Zbar Flux Equation}\n\n%\\subsection{Hydrodynamic Stellar Structure Equations}\n\n%\\subsubsection{Continuity Equation}\n\n%\\subsubsection{Momentum Equation}\n\n%\\subsubsection{Luminosity Equation}\n\n%\\subsubsection{Temperature Equation}\n\n%\\subsubsection{Composition Equation}\n\n\n%\\subsection{MLT Velocity}\n\n%\\begin{align}\n%u_{MLT} \\equiv (u'_{rms}) & = \\frac{F_c}{\\alpha_E c_P (T'_{rms})} = \\frac{\\erho \\fht{h''u''_r}}{\\alpha_E \\fht{c_P} (\\fht{TT} - \\fht{T}\\fht{T})^{1/2}} \\sim \\frac{\\erho \\eht{h'u'_r}}{\\alpha_E \\eht{c_P} (\\eht{TT} - \\eht{T} \\ \\eht{T})^{1/2}} \\mbox{?} \\\\\n%u_{MLT} \\equiv (u'_{rms}) & = \\frac{\\erho (\\fht{h u_r} - \\fht{h}\\fht{u_r})}{\\alpha_E \\fht{c_P} (\\fht{TT} - \\fht{T}\\fht{T})^{1/2}} \\sim \\frac{\\erho (\\eht{h u_r} -\\eht{h} \\eht{u_r})}{\\alpha_E \\eht{c_P} (\\eht{TT} - \\eht{T} \\ \\eht{T})^{1/2}} \\nonumber \\\\\n%u_{MLT} \\equiv (u'_{rms}) & = \\frac{ddhhux - ddhh*ddux/dd}{\\alpha_E * ddcp/dd \\ (ddttsq/dd - ddtt*ddtt/dd*dd)^{1/2}} \\sim \\frac{dd*hhux - dd*hh*ux}{\\alpha_E * cp \\ (ttsq - tt*tt)^{1/2}} \\nonumber\n%\\end{align}\n\n\\subsection{Usefull Identities}\n\\label{sect:usefulidentities}\n\n\\begin{align}\n\\eht{a''} = & \\ \\eht{a - \\fht{a}} = \\eht{a} - \\fht{a}   \\\\\n\\fht{a''b''} = & \\ \\fht{(a-\\fht{a})*(b-\\fht{b})} = \\fht{ab} - \\fht{a}\\fht{b} \\\\\n\\eht{a'b'} = & \\ \\eht{(a - \\eht{a})*(b-\\eht{b})} = \\eht{ab}-\\eht{a}\\eht{b} = \\eht{a'b''}\\\\\n\\fht{a''b''c''} = & \\ \\fht{(a-\\fht{a})*(b-\\fht{b})*(c-\\fht{c})} = \\fht{abc} - \\fht{a}\\fht{bc} - \\fht{b}\\fht{ac} - \\fht{c}\\fht{ab} + 2\\fht{a}\\fht{b}\\fht{c} \\\\\n\\eht{a'b'c''} = & \\eht{(a-\\eht{a})*(b-\\eht{b})*(c-\\fht{c})} = \\eht{abc} - \\eht{ac} \\ \\eht{b} - \\eht{a} \\ \\eht{bc} + \\eht{a} \\ \\eht{b} \\ \\eht{c} - \\eht{ab} \\ \\fht{c} + \\eht{a} \\ \\eht{b} \\fht{c} \\\\\n\\eht{a''b'c''} = & \\eht{(a-\\fht{a})*(b-\\eht{b})*(c-\\fht{c})} = \\eht{abc} - \\eht{ac}\\eht{b} - \\fht{a}\\eht{bc} + \\fht{a}\\eht{b}\\eht{c} - \\eht{ab}\\fht{c} + \\eht{a}\\eht{b}\\fht{c} \\\\\n\\eht{a''bc} = & \\ \\eht{(a-\\fht{a})bc} = \\eht{abc} - \\fht{a}\\eht{bc} \\\\\n\\eht{a''\\partial_r b'} = & \\ \\eht{(a-\\fht{a})\\partial_r b'} = \\eht{a \\partial_r b'} - \\cancelto{0}{\\fht{a}\\partial_r \\eht{b'}} = \\eht{a \\partial_r b} - \\eht{a}\\partial_r\\eht{b}   \n\\end{align}\n\n%\\section{Definitions}\n\n%- only for basic quantities, without overbar e.g dd is density, ux is x velocity, ei internal energy etc. \n\n\n\\bibliography{referenc}\n\n\\end{document}\n\n\n", "meta": {"hexsha": "dfd1c85f104f2e46047e7bc8fa2cda2184d6683f", "size": 30028, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "DOCS/TEX/ransXimplementationGuide.tex", "max_stars_repo_name": "mmicromegas/ransX", "max_stars_repo_head_hexsha": "2faaa786e00cfd14dce0e18f0793cd0252428d2a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-04-22T11:43:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-16T00:28:15.000Z", "max_issues_repo_path": "DOCS/TEX/ransXimplementationGuide.tex", "max_issues_repo_name": "mmicromegas/ransX", "max_issues_repo_head_hexsha": "2faaa786e00cfd14dce0e18f0793cd0252428d2a", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 34, "max_issues_repo_issues_event_min_datetime": "2019-07-01T09:11:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T13:35:43.000Z", "max_forks_repo_path": "DOCS/TEX/ransXimplementationGuide.tex", "max_forks_repo_name": "mmicromegas/ransX", "max_forks_repo_head_hexsha": "2faaa786e00cfd14dce0e18f0793cd0252428d2a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-16T00:28:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-16T00:28:17.000Z", "avg_line_length": 58.8784313725, "max_line_length": 1130, "alphanum_fraction": 0.6773344878, "num_tokens": 11245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.31795327862308276}}
{"text": "\\documentclass[RNAAS]{aastex631}\n\\usepackage{hyperref}\n\\let\\tablenum\\relax\n\\usepackage[output-exponent-marker = \\text{e}]{siunitx}\n\n%% Define new commands here\n\\newcommand\\latex{La\\TeX}\n\n\\graphicspath{{./}{figures/}}\n\\shortauthors{Lucas et al.}\n\n\\begin{document}\n\n\\title{Yeehaw: A Roundup of Probabilistic Transit Modeling Packages}\n\n\\correspondingauthor{Miles Lucas}\n\\email{mdlucas@hawaii.edu}\n\n\\author[0000-0001-6341-310X]{Miles Lucas}\n\\affiliation{Institute for Astronomy, University of Hawai'i, USA}\n\n\n\\begin{abstract}\nIn this research note we report on the statistical outputs of popular transit modeling packages: \\texttt{exoplanet}, \\texttt{BATMAN}, \\texttt{PyTransit}, \\texttt{Juliet}, and \\texttt{EXOFASTv2}. We use a circular Keplerian orbit with a quadratic limb-darkening law to generate data with additive white noise and then perform statistical inference using the packages' implementations of transit curves and statistical models. Our results show that none of the packages we tested significantly biases the posterior results away from the true value, although \\texttt{EXOFASTv2} had slightly different posteriors due to different prior parameterizations.\n\\end{abstract}\n\n\\section{Introduction} \n\nThe method of transit photometry has proven indispensable in the detection and characterization of thousands of exoplanets over the past few decades \\citep{2007prpl.conf..701C,2009IAUS..253...99W,2010exop.book...55W,2010trex.book.....H}. These quantities all have to be inferred using a computed model of the planetary transit. Model accuracy directly affects the inference of these parameters and a recent study by \\citet{2020AJ....159..123A} has improved numerical accuracy of the popular quadratic limb-darkening law \\citep{2002ApJ...580L.171M} to within $\\mathcal{O}(10^{-15})$ along with analytical derivatives. The rapid growth of the exoplanet community means not every user who uses a given package will understand, in full, the statistical implications of their choices, and it is important to make sure the transit modeling ecosystem is not imparting bias into exoplanet studies. We seek to improve upon the work by \\citet{2020AJ....159..123A} and study how different packages affect the statistical inference of astrophysical parameters.\n\nThe following packages provide limb-darkened transit curves: \\texttt{exoplanet} \\citep{2019ascl.soft10005F}, \\texttt{BATMAN} \\citep{2015PASP..127.1161K}, \\texttt{PyTransit} \\citep{Parviainen2015}, and \\texttt{EXOFASTv2} \\citep{2019arXiv190709480E}. From these packages we use the quadratic limb-darkening law from \\citet{2002ApJ...580L.171M}. In addition, \\texttt{exoplanet} and \\texttt{EXOFASTv2} have entire statistical modeling frameworks built into or on top of the transit curves. We also test \\texttt{Juliet} \\citep{2019MNRAS.490.2262E}, which adds a statistical modeling framework to the \\texttt{BATMAN} transit models.\n\n\\section{Modeling}\n\nTo begin, we used the highly accurate \\citet{2020AJ....159..123A} transit models to simulate a light curve. The ground truth parameters were chosen to roughly mock the Kepler-101b transit \\citep{2014A&A...572A...2B} and are shown in \\autoref{table}. We built a hierarchical model using \\texttt{PyMC3} \\citep{2016ascl.soft10016S} and \\texttt{exoplanet} with the following parameters: the semi-major axis ($aR_*$), orbital period ($P$), time of inferior conjunction ($t_0$), ratio of planet to stellar radii ($R_P/R_*$), limb-darkening coefficients ($u_1,u_2$), and out-of-transit noise ($\\sigma$). This parameterization is supported (at least indirectly) by all packages tested and has the benefit of no correlations in the orbital parameters, which can degrade accuracy and performance of inference methods. We built this model in a generic way that could substitute different limb-darkening laws between \\texttt{exoplanet}, \\texttt{BATMAN}, and \\texttt{PyTransit}.\n\nThe prior parameterization is chosen to be slightly uninformative, but some tuning was done to ensure consistent outputs. For the period and semi-major axis we use log-Normal priors, for the time of inferior conjunction we use a Normal prior, for the limb-darkening coefficients we use uninformative triangular sampling \\citep{2013MNRAS.435.2152K} provided by \\texttt{exoplanet}, and finally for the noise term we use a half-Cauchy distribution. The simulated data is compared to the models using a Gaussian likelihood without any additional noise model. For performing statistical inference with \\texttt{PyMC3}, we use both the No-U-Turn Sampler (NUTS; \\citealp{2011arXiv1111.4246H}) and Metropolis-Hastings (MH). Analytical derivatives are required for NUTS, and therefore we only tested it with the \\texttt{exoplanet} light curve models.\n\nFor \\texttt{Juliet} we needed to change the parameterization slightly-- in the previous models the error is completely modeled by the noise term inside the Gaussian likelihood, but we had to skip modeling this term for \\texttt{Juliet} because it fails to evaluate a finite likelihood if the error in its data model is 0. We followed the \\texttt{Juliet} documentation for building our model-- the main differences are that period and semi-major axis are sampled using a Normal distribution rather than a log-Normal. For inference, \\texttt{Juliet} uses \\texttt{DYNESTY} \\citep{2020MNRAS.493.3132S} to perform nested sampling (NS; \\citealp{2004AIPC..735..395S}) providing both posterior samples and an estimate of the Bayesian evidence for our model.\n\nFor \\texttt{EXOFASTv2} we also had to alter the parameterization slightly; rather than fitting the semi-major axis directly, we had to fit the stellar mass and fix the planetary mass. Similar to our \\texttt{Juliet} setup, we use a Normal prior for period and time of inferior conjunction rather than log-Normal priors, and we also use a Uniform prior for the noise \\textit{variance}. Importantly, the limb-darkening coefficients use an informative prior from \\citet{2011A&A...529A..75C}. For inference \\texttt{EXOFASTv2} uses a differential evolution Metropolis-Hastings algorithm (DEMH; \\citealp{2006S&C....16..239T}) which uses an ensemble of walkers which query each other between steps to temper their proposal scales.\n\n\\section{Results}\n\nWe performed inference on all of our models, starting with a numerical optimization to decrease the time taken to converge on a solution during the MCMC inference. For the NUTS sampler we used \\num{5,000} tuning steps and \\num{5,000} samples. For the MH sampler we used \\num{5,000} burn-in steps and \\num{10,000} samples. In all cases this was enough samples to produce a Gelman-Rubin statistic close to 1.0, which implies that the chains are \\textit{well-mixed}, Nested sampling samples until convergence \\citep[see][\\S 2.4]{2020MNRAS.493.3132S}, which produced \\num{29,000} samples which were equally resampled using their statistical weights. \\texttt{EXOFASTv2} was set to sample until the Gelman-Rubin statistic for the DEMH walkers was below 1.01, which generated \\num{50,500} samples.\n\nThe posteriors from all of our inferences are tabulated in \\autoref{table}. The table shows the median value of all posterior samples along with the 68\\% highest-posterior-density interval (HDI). This is similar to a ``1-sigma confidence interval\" but in a Bayesian context. Every model and inference combination \\textit{except} for \\texttt{EXOFASTv2} was consistent with each other and fits the data very well. A key parameter, the relative radius ($R_P/R_*$) is recovered and almost identically distributed for all our models. We believe the differences in posteriors from \\texttt{EXOFASTv2} are from the different limb-darkening prior used.\n\n\\input{table.tex}\n\n% \\acknowledgments\n\n% \\software{\n% astropy \\citep{2013A&A...558A..33A,2018AJ....156..123A},\n% numpy \\citep{harris2020array},\n% scikit-image \\citep{2014arXiv1407.6245V},\n% }\n\n\\bibliography{references}{}\n\\bibliographystyle{aasjournal}\n\n\\end{document}\n", "meta": {"hexsha": "1a668c33ca1f96543a152f84d6da987bad202264", "size": 7919, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/paper.tex", "max_stars_repo_name": "mileslucas/yeehaw", "max_stars_repo_head_hexsha": "dfad00208b251ffeace74d2e44e8dd2558bb8b7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-27T05:41:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T05:41:38.000Z", "max_issues_repo_path": "paper/paper.tex", "max_issues_repo_name": "mileslucas/yeehaw", "max_issues_repo_head_hexsha": "dfad00208b251ffeace74d2e44e8dd2558bb8b7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/paper.tex", "max_forks_repo_name": "mileslucas/yeehaw", "max_forks_repo_head_hexsha": "dfad00208b251ffeace74d2e44e8dd2558bb8b7d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 125.6984126984, "max_line_length": 1048, "alphanum_fraction": 0.7937870943, "num_tokens": 2059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3178205854534358}}
{"text": "\\par\n\\chapter{{\\tt Pencil}: Matrix pencil}\n\\par\nThis object stores a matrix pencil $A + \\sigma B$.\n$A$ and $B$ are both stored as {\\tt InpMtx} objects.\nMany of the {\\tt Pencil} methods simply call the equivalent {\\tt\nInpMtx} method.\n", "meta": {"hexsha": "576b773d819aafb3be24936689e9dc383f484e1f", "size": 233, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ccx_prool/SPOOLES.2.2/Pencil/doc/intro.tex", "max_stars_repo_name": "alleindrach/calculix-desktop", "max_stars_repo_head_hexsha": "2cb2c434b536eb668ff88bdf82538d22f4f0f711", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ccx_prool/SPOOLES.2.2/Pencil/doc/intro.tex", "max_issues_repo_name": "alleindrach/calculix-desktop", "max_issues_repo_head_hexsha": "2cb2c434b536eb668ff88bdf82538d22f4f0f711", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-09-21T17:03:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-25T16:08:31.000Z", "max_forks_repo_path": "ccx_prool/SPOOLES.2.2/Pencil/doc/intro.tex", "max_forks_repo_name": "alleindrach/calculix-desktop", "max_forks_repo_head_hexsha": "2cb2c434b536eb668ff88bdf82538d22f4f0f711", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-08-29T18:41:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-29T18:41:28.000Z", "avg_line_length": 29.125, "max_line_length": 64, "alphanum_fraction": 0.7081545064, "num_tokens": 74, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3178205775218163}}
{"text": "\\documentstyle[11pt]{article}\n\\title{REDUCE Meets CAMAL}\n\\author{J. P. Fitch \\\\\nSchool of Mathematical Sciences\\\\\nUniversity of Bath\\\\\nBATH, BA2 7AY, United Kingdom}\n\\def\\today{}\n\\begin{document}\\maketitle\n\n\\begin{abstract}\n{\\em It is generally accepted that special purpose algebraic systems\nare more efficient than general purpose ones, but as machines get\nfaster this does not matter.  An experiment has been performed to see\nif using the ideas of the special purpose algebra system CAMAL(F) it\nis possible to make the general purpose system REDUCE perform\ncalculations in celestial mechanics as efficiently as CAMAL did twenty\nyears ago.  To this end a prototype Fourier module is created for\nREDUCE, and it is tested on some small and medium-sized problems taken\nfrom the CAMAL test suite. The largest calculation is the\ndetermination of the Lunar Disturbing Function to the sixth order.  An\nassessment is made as to the progress, or lack of it, which computer\nalgebra has made, and how efficiently we are using modern hardware.\n}\n\\end{abstract}\n\n\\section{Introduction}\n\nA number of years ago there emerged the divide between general-purpose\nalgebra systems and special purpose one.  Here we investigate how far\nthe improvements in software and more predominantly hardware have\nenabled the general systems to perform as well as the earlier special\nones.  It is similar in some respects to the Possion program for\nMACSYMA \\cite{Fateman} which was written in response to a similar\nchallenge.\n\nThe particular subject for investigation is the Fourier series\nmanipulator which had its origins in the Cambridge University\nInstitute for Theoretical Astronomy, and later became the F subsystem\nof CAMAL \\cite{Barton67b,CAMALF}.  In the late 1960s this system was\nused for both the Delaunay Lunar Theory \\cite{Delaunay,Barton67a} and\nthe Hill Lunar Theory \\cite{Bourne}, as well as other related\ncalculations.  Its particular area of application had a number of\npeculiar operations on which the general speed depended.  These are\noutlined below in the section describing how CAMAL worked.  There have\nbeen a number of subsequent special systems for celestial mechanics,\nbut these tend to be restricted to the group of the originator.\n\nThe main body of the paper describes an experiment to create within\nthe REDUCE system a sub-system for the efficient manipulation of\nFourier series.  This prototype program is then assessed against both\nthe normal (general) REDUCE and the extant CAMAL results.  The tests\nare run on a number of small problems typical of those for which CAMAL\nwas used, and one medium-sized problem, the calculation of the Lunar\nDisturbing Function.  The mathematical background to this problem is\nalso presented for completeness.  It is important as a problem as it\nis the first stage in the development of a Delaunay Lunar Theory.\n\nThe paper ends with an assessment of how close the performance of a\nmodern REDUCE on modern equipment is to the (almost) defunct CAMAL of\neighteen years ago.\n\n\\section{How CAMAL Worked}\n\nThe Cambridge Algebra System was initially written in assembler for\nthe Titan computer, but later was rewritten a number of times, and\nmatured in BCPL, a version which was ported to IBM mainframes and a\nnumber of microcomputers.  In this section a brief review of the main\ndata structures and special algorithms is presented.\n\n\\subsection{CAMAL Data Structures}\n\nCAMAL is a hierarchical system, with the representation of polynomials\nbeing completely independent of the representations of the angular\nparts.  \n\nThe angular part had to represent a polynomial coefficient, either a\nsine or cosine function and a linear sum of angles.  In the problems\nfor which CAMAL was designed there are 6 angles only, and so the\ndesign restricted the number, initially to six on the 24 bit-halfword\nTITAN, and later to eight angles on the 32-bit IBM 370, each with\nfixed names (usually u through z).  All that is needed is to remember\nthe coefficients of the linear sum.  As typical problems are\nperturbations, it was reasonable to restrict the coefficients to small\nintegers, as could be represented in a byte with a guard bit.  This\nallowed the representation to pack everything into four words.\n\\begin{verbatim}\n    [ NextTerm, Coefficient, Angles0-3, Angles4-7 ]\n\\end{verbatim}\nThe function was coded by a single bit in the {\\tt Coefficient} field.  This\ngives a particularly compact representation.  For example the Fourier\nterm $\\sin(u-2v+w-3x)$ would be represented as\n\\begin{verbatim}\n    [ NULL, \"1\"|0x1, 0x017e017d, 0x00000000 ]\nor\n    [ NULL, \"1\"|0x1, 1:-2:1:-3, 0:0:0:0 ]\n\\end{verbatim}\nwhere {\\tt \"1\"} is a pointer to the representation of the polynomial\n1.  In all this representation of the term took 48 bytes.  As the\ncomplexity of a term increased the store requirements to no grow much;\nthe expression $(7/4) a e^3 f^5 \\cos(u-2v+3w-4x+5y+6z)$ also takes 48\nbytes.  There is a canonicalisation operation to ensure that the\nleading angle is positive, and $\\sin(0)$ gets removed.  It should be\nnoted that $\\cos(0)$ is a valid and necessary representation.\n\nThe polynomial part was similarly represented, as a chain of terms\nwith packed exponents for a fixed number of variables.  There is no\nparticular significance in this except that the terms were held in\n{\\em increasing} total order, rather than the decreasing order which\nis normal in general purpose systems.  This had a number of important\neffects on the efficiency of polynomial multiplication in the presence\nof a truncation to a certain order.  We will return to this point\nlater.  Full details of the representation can be found in\n\\cite{LectureNotes}.\n\nThe space administration system was based on explicit return rather\nthan garbage collection.  This meant that the system was sometimes\nharder to write, but it did mean that much attention was focussed on\nefficient reuse of space.  It was possible for the user to assist in\nthis by marking when an expression was needed no longer, and the\ncompiler then arranged to recycle the space as part of the actual\noperation.  This degree of control was another assistance in running\nof large problems on relatively small machines.\n\n\\subsection{Automatic Linearisation}\n\nIn order to maintain Fourier series in a canonical form it is\nnecessary to apply the transformations for linearising products of\nsine and cosines.  These will be familiar to readers of the REDUCE\ntest program as\n\\begin{eqnarray}\n\\cos \\theta \\cos \\phi & \\Rightarrow & \n                (\\cos(\\theta+\\phi)+\\cos(\\theta-\\phi))/2, \\\\\n\\cos \\theta \\sin \\phi & \\Rightarrow & \n                (\\sin(\\theta+\\phi)-\\sin(\\theta-\\phi))/2, \\\\\n\\sin \\theta \\sin \\phi & \\Rightarrow & \n                (\\cos(\\theta-\\phi)-\\cos(\\theta+\\phi))/2, \\\\\n\\cos^2 \\theta & \\Rightarrow & (1+\\cos(2\\theta))/2,      \\\\\n\\sin^2 \\theta & \\Rightarrow & (1-\\cos(2\\theta))/2.\n\\end{eqnarray}\nIn CAMAL these transformations are coded directly into the\nmultiplication routines, and no action is necessary on the part of the\nuser to invoke them.  Of course they cannot be turned off either.\n\n\\subsection{Differentiation and Integration}\n\nThe differentiation of a Fourier series with respect to an angle is\nparticularly simple.  The integration of a Fourier series is a little\nmore interesting.  The terms like $\\cos(n u + \\ldots)$ are easily\nintegrated with respect to $u$, but the treatment of terms independent\nof the angle would normally introduce a secular term.  By convention\nin Fourier series these secular terms are ignored, and the constant of\nintegration is taken as just the terms independent of the angle in the\nintegrand.  This is equivalent to the substitution rules\n\\begin{eqnarray*}\n\\sin(n \\theta) & \\Rightarrow & -(1/n) \\cos(n \\theta) \\\\\n\\cos(n \\theta) & \\Rightarrow & (1/n) \\sin(n \\theta)\n\\end{eqnarray*}\n\nIn CAMAL these operations were coded directly, and independently of\nthe differentiation and integration of the polynomial coefficients.\n\n\\subsection{Harmonic Substitution}\n\nAn operation which is of great importance in Fourier operations is the\n{\\em harmonic substitution}.  This is the substitution of the sum of\nsome angles and a general expression for an angle.  In order to\npreserve the format, the mechanism uses the translations\n\\begin{eqnarray*}\n\\sin(\\theta + A) & \\Rightarrow & \\sin(\\theta) \\cos(A) + \n                                 \\cos(\\theta) \\sin(A) \\\\\n\\cos(\\theta + A) & \\Rightarrow & \\cos(\\theta) \\cos(A) -\n                                 \\sin(\\theta) \\sin(A) \\\\\n\\end{eqnarray*}\nand then assuming that the value $A$ is small it can be replaced by\nits expansion:\n\\begin{eqnarray*}\n\\sin(\\theta + A) & \\Rightarrow & \\sin(\\theta) \\{1 - A^2/2! + A^4/4!\\ldots\\} +\\\\\n                 &             & \\cos(\\theta) \\{A - A^3/3! + A^5/5!\\ldots\\} \\\\\n\\cos(\\theta + A) & \\Rightarrow & \\cos(\\theta) \\{1 - A^2/2! + A^4/4!\\ldots\\} -\\\\\n                 &             & \\sin(\\theta) \\{A - A^3/3! + A^5/5! \\ldots\\} \\\\\n\\end{eqnarray*}\nIf a truncation is set for large powers of the polynomial variables\nthen the series will terminate.  In CAMAL the {\\tt HSUB} operation\ntook five arguments; the original expression, the angle for which\nthere is a substitution, the new angular part, the expression part\n($A$ in the above), and the number of terms required.\n\nThe actual coding of the operation was not as expressed above, but by\nthe use of Taylor's theorem.  As has been noted above the\ndifferentiation of a harmonic series is particularly easy.\n\n\\subsection{Truncation of Series}\n\nThe main use of Fourier series systems is in generating perturbation\nexpansions, and this implies that the calculations are performed to\nsome degree of the small quantities.  In the original CAMAL all\nvariables were assumed to be equally small (a restriction removed in\nlater versions).  By maintaining polynomials in increasing maximum\norder it is possible to truncate the multiplication of two\npolynomials.  Assume that we are multiplying the two polynomials\n\\begin{eqnarray*}\n        A = a_0 + a_1 + a_2 + \\ldots \\\\\n        B = b_0 + b_1 + b_2 + \\ldots\n\\end{eqnarray*}\nIf we are generating the partial answer\n\\[\n        a_i (b_0 + b_1 + b_2 + \\ldots)\n\\]\nthen if for some $j$ the product $a_i b_j$ vanishes, then so will all\nproducts $a_i b_k$ for $k>j$.  This means that the later terms need\nnot be generated.  In the product of $1+x+x^2+x^3+\\ldots+x^{10}$ and\n$1+y+y^2+y^3+\\ldots+y^10$ to a total order of 10 instead of generating\n100 term products only 55 are needed.  The ordering can also make the\nmerging of the new terms into the answer easier.\n\n\\section{Towards a CAMAL Module}\n\nFor the purposes of this work it was necessary to reproduce as many of\nthe ideas of CAMAL as feasible within the REDUCE framework and\nphilosophy.  It was not intended at this stage to produce a complete\nproduct, and so for simplicity a number of compromises were made with\nthe ``no restrictions'' principle in REDUCE and the space and time\nefficiency of CAMAL.  This section describes the basic design\ndecisions. \n\n\\subsection{Data Structures}\n\nIn a fashion similar to CAMAL a two level data representation is used.\nThe coefficients are the standard quotients of REDUCE, and their\nrepresentation need not concern us further.  The angular part is\nsimilar to that of CAMAL, but the ability to pack angle multipliers\nand use a single bit for the function are not readily available in\nStandard LISP, so instead a longer vector is used.  Two versions were\nwritten.  One used a balanced tree rather than a linear list for the\nFourier terms, this being a feature of CAMAL which was considered but\nnever coded.  The other uses a simple linear representation for sums.\nThe angle multipliers are held in a separate vector in order to allow\nfor future flexibility.  This leads to a representation as a vector of\nlength 6 or 4;\n\\begin{verbatim}\nVersion1:  [ BalanceBits, Coeff, Function, Angles, LeftTree, RightTree ]\nVersion2:  [ Coeff, Function, Angles, Next ]\n\\end{verbatim}\nwhere the {\\tt Angles} field is a vector of length 8, for the\nmultipliers.  It was decided to forego packing as for portability we\ndo not know how many to pack into a small integer.  The tree system\nused is AVL, which needs 2 bits to maintain balance information, but\nthese are coded as a complete integer field in the vector.  We can\nexpect the improvements implicit in a binary tree to be advantageous\nfor large expressions, but the additional overhead may reduce its\nutility for smaller expressions.\n\nA separate vector is kept relating the position of an angle to its\nprint name, and on the property list of each angle the allocation of\nits position is kept.  So long as the user declares which variables\nare to be treated as angles this mechanism gives flexibility which was\nlacking in CAMAL.\n\n\\subsection{Linearisation}\n\nAs in the CAMAL system the linearisation of products of sines and\ncosines is done not by pattern matching but by direct calculation at\nthe heart of the product function, where the transformations (1)\nthrough (3) are made in the product of terms function.  A side effect\nof this is that there are no simple relations which can be used from\nwithin the Fourier multiplication, and so a full addition of partial\nproducts is required.  There is no need to apply linearisations\nelsewhere as a special case.  Addition, differentiation and\nintegration cannot generate such products, and where they can occur in\nsubstitution the natural algorithm uses the internal multiplication\nfunction anyway.\n\n\\subsection{Substitution}\n\nSubstitution is the main operation of Fourier series.  It is useful to\nconsider three different cases of substitutions.\n\\begin{enumerate}\n\\item Angle Expression for Angle:\n\\item Angle Expression + Fourier Expression for Angle:\n\\item Fourier Expression for Polynomial Variable.\n\\end{enumerate}\n\nThe first of these is straightforward, and does not require any\nfurther comment.  The second substitution requires a little more care,\nbut is not significantly difficult to implement.  The method follows\nthe algorithm used in CAMAL, using TAYLOR series.  Indeed this is the\nmain special case for substitution.\n\nThe problem is the last case.  Typically many variables used in a\nFourier series program have had a WEIGHT assigned to them.  This means\nthat substitution must take account of any possible WEIGHTs for\nvariables.  The standard code in REDUCE does this in effect by\ntranslating the expression to prefix form, and recalculating the value.\nA Fourier series has a large number of coefficients, and so this\noperations are repeated rather too often.  At present this is the\nlargest problem area with the internal code, as will be seen in the\ndiscussion of the Disturbing Function calculation.\n\n\\section{Integration with REDUCE}\n\nThe Fourier module needs to be seen as part of REDUCE rather than as a\nseparate language.  This can be seen as having internal and external\nparts.\n\n\\subsection{Internal Interface}\n\nThe Fourier expressions need to co-exist with the normal REDUCE syntax\nand semantics.  The prototype version does this by (ab)using the\nmodule method, based in part on the TPS code \\cite{Barnes}.  Of course\nFourier series are not constant, and so are not really domain\nelements.  However by asserting that Fourier series form a ring of\nconstants REDUCE can arrange to direct basic operations to the Fourier\ncode for addition, subtraction, multiplication and the like.\n\nThe main interface which needs to be provided is a simplification\nfunction for Fourier expressions.  This needs to provide compilation\nfor linear sums of angles, as well as constructing sine and cosine\nfunctions, and creating canonical forms.\n\n\\subsection{User Interface}\n\nThe creation of {\\tt HDIFF} and {\\tt HINT} functions for\ndifferentiation disguises this.  An unsatisfactory aspect of the\ninterface is that the tokens {\\tt SIN} and {\\tt COS} are already in\nuse.  The prototype uses the operator form\n\\begin{verbatim}\n        fourier sin(u)\n\\end{verbatim}\nto introduce harmonically represented sine functions.  An alternative of\nusing the tokens {\\tt F\\_SIN} and {\\tt F\\_COS} is also available.  \n\nIt is necessary to declare the names of the angles, which is achieved\nwith the declaration \n\\begin{verbatim}\n        harmonic theta, phi;\n\\end{verbatim}\n\nAt present there is no protection against using a variable as both an\nangle and a polynomial varaible.  This will nooed to be done in a\nuser-oriented version.\n\n\\section{The Simple Experiments}\n\nThe REDUCE test file contains a simple example of a Fourier\ncalculation, determining the value of $(a_1 \\cos({wt}) + a_3\n\\cos(3{wt}) + b_1 \\sin({wt}) + b_3 \\sin(3{wt}))^3$.  For the purposes\nof this system this is too trivial to do more than confirm the correct\nanswers. \n\nThe simplest non-trivial calculation for a Fourier series manipulator\nis to solve Kepler's equation for the eccentric anomoly E in terms of\nthe mean anomoly u, and the eccentricity of an orbit e, considered as a\nsmall quantity\n\\[\n        E = u + e \\sin E\n\\]\nThe solution procedes by repeated approximation.  Clearly the initial\napproximation is $E_0 = u$.  The $n^{th}$ approximation can be written\nas $u + A_n$, and so $A_n$ can be calculated by\n\\[\n        A_k = e \\sin (u + A_{k-1})\n\\]\nThis is of course precisely the case for which the HSUB operation is\ndesigned, and so in order to calculate $E_n - u$ all one requires is\nthe code\n\\begin{verbatim}\n        bige := fourier 0;\n        for k:=1:n do <<\n          wtlevel k;\n          bige:=fourier e * hsub(fourier(sin u), u, u, bige, k);\n        >>;\n        write \"Kepler Eqn solution:\", bige$\n\\end{verbatim}\n\nIt is possible to create a regular REDUCE program to simulate this (as\nis done for example in Barton and Fitch\\cite{Barton72}, page 254).\nComparing these two programs indicates substantial advantages to the\nFourier module, as could be expected.\n\\medskip\n\\begin{center}\n\\begin{tabular}{ | c | l l |}\n\\multicolumn{3}{c}{\\bf Solving Kepler's Equation} \\\\\n\\hline\nOrder   &       REDUCE  &       Fourier Module \\\\\n5       &       9.16    &       2.48    \\\\\n6       &       17.40   &       4.56    \\\\\n7       &       33.48   &       8.06    \\\\\n8       &       62.76   &       13.54   \\\\\n9       &       116.06  &       21.84   \\\\\n10      &       212.12  &       34.54   \\\\\n11      &       381.78  &       53.94   \\\\\n12      &       692.56  &       82.96   \\\\\n13      &       1247.54 &       125.86  \\\\\n14      &       2298.08 &       187.20  \\\\\n15      &       4176.04 &       275.60  \\\\\n16      &       7504.80 &       398.62  \\\\\n17      &       13459.80        &       569.26  \\\\\n18      &       ***     &       800.00  \\\\\n19      &       ***     &       1116.92 \\\\\n20      &       ***     &       1536.40 \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\medskip\nThese results were with the linear representation of Fourier series.\nThe tree representation was slightly slower.  The ten-fold speed-up\nfor the 13th order is most satisfactory.\n\n\\section{A Medium-Sized Problem}\n\nFourier series manipulators are primarily designed for large-scale\ncalculations, but for the demonstration purposes of this project a\nmedium problem is considered.  The first stage in calculating the\norbit of the Moon using the Delaunay theory (of perturbed elliptic\nmotion for the restricted 3-body problem) is to calculate the energy\nof the Moon's motion about the Earth --- the Hamiltonian of the\nsystem.   This is the calculation we use for comparisons.\n\n\\subsection{Mathematical Background}\n\nThe full calculation is described in detail in \\cite{Brown}, but a\nbrief description is given here for completeness, and to grasp the\nextent of the calculation.\n\nReferring to the figure 1 which gives the cordinate system, the basic\nequations are \n\\begin{eqnarray}\nS  & = & (1-\\gamma ^2)\\cos(f + g +h -f' -g' -h')\n+ \\gamma ^2 cos(f + g -h +f' +g' +h') \\\\\nr & = & a (1 - e \\cos E) \\\\\nl & = & E - e \\sin E \\\\\na & = & r {{\\bf d} E} \\over {{\\bf d} l} \\\\\nr ^2 {{\\bf d} f} \\over {{\\bf d} l} & = & a^2 (1 - e^2)^{1 \\over 2}\\\\\nR & = & m' {a^2 \\over {a'} ^3} {{a'}\\over {r\n'}} \\left \\{ \\left ({r \\over a}\\right )^2\n\\left ({{a'} \\over {r'}}\\right )^2 P_2(S) +\n\\left ({a \\over {a'}}\\right )\\left\n({r \\over a}\\right )^3 \\left ({{a'} \\over {r'}}\\right )^3 P_3(S)\n+ \\ldots \\right \\}\n\\end{eqnarray}\n\nThere are similar equations to (7) to (10) for the quantities $r'$,\n$a'$, $e'$, $l'$, $E'$ and $f'$ which refer to the position of the Sun\nrather than the Moon.  The problem is to calculate the expression $R$\nas an expansion in terms of the quantities $e$, $e'$, $\\gamma$,\n$a/a'$, $l$, $g$, $h$, $l'$, $g'$ and $h'$.  The first three\nquantities are small quantities of the first order, and $a/a'$ is of\nsecond order.\n\nThe steps required are\n\\begin{enumerate}\n\\item Solve the Kepler equation (8)\n\\item Substiture into (7) to give $r/a$ in terms of $e$ and $l$.\n\\item Calculate $a/r$ from (9) and $f$ from (10)\n\\item Substitute for $f$ and $f'$ into $S$ using (6)\n\\item Calculate $R$ from $S$, $a'/r'$ and $r/a$\n\\end{enumerate}\n\nThe program is given in the Appendix.\n\n\\subsection{Results}\n\nThe Lunar Disturbing function was calculated by a direct coding of the\nprevious sections' mathematics.  The program was taken from Barton\nand Fitch \\cite{Barton72} with just small changes to generalise it for\nany order, and to make it acceptable for Reduce3.4.  The Fourier\nprogram followed the same pattern, but obviously used the {\\tt HSUB}\noperation as appropriate and the harmonic integration.  It is very\nsimilar to the CAMAL program in \\cite{Barton72}.   \n\nThe disturbing function was calculated to orders 2, 4 and 6 using\nCambridge LISP on an HLH Orion 1/05 (Intergraph Clipper), with the\nthree programs $\\alpha$) Reduce3.4, $\\beta$) Reduce3.4 + Camal Linear\nModule and $\\gamma$) Reduce3.4 + Camal AVL Module.  The timings for\nCPU seconds (excluding garbage collection time) are summarised the\nfollowing table:\n\\medskip\n\\begin{center}\n\\begin{tabular}{ | c || l | l | l |}\n\\hline\nOrder of DDF    & Reduce        & Camal Linear  & Camal Tree \\\\\n\\hline\n2       &       23.68   &       11.22   &       12.9    \\\\\n4       &       429.44  &       213.56  &       260.64  \\\\\n6       &       $>$7500 &       3084.62 &       3445.54 \\\\\n\\hline\n%%% Linear n=4 138.72 (4Mb + unsafe vector access + recurrance)\n%%% Linear n=6 1870.10 (4Mb + unsafe vector access + recurrance)\n\\end{tabular}\n\\end{center}\n\\medskip\n\nIf these numbers are normalised so REDUCE calculating the DDF is 100\nunits for each order the table becomes\n\\medskip\n\\begin{center}\n\\begin{tabular}{ | c || l | l | l |}\n\\hline\nOrder of DDF    & Reduce        & Camal Linear  & Camal Tree \\\\ \\hline\n2       &       100     &       47.38   &       54.48   \\\\\n4       &       100     &       49.73   &       60.69   \\\\\n6       &       100     &       $<$41.13        &       $<$45.94 \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\medskip\n\nFrom this we conclude that a doubling of speed is about correct, and\nalthough the balanced tree system is slower as the problem size\nincreases the gap between it and the simpler linear system is\nnarrowing. \n\nIt is disappointing that the ratio is not better, nor the absolute\ntime less.  It is worth noting in this context that Jefferys claimed\nthat the sixth order DDF took 30s on a CDC6600 with TRIGMAN in 1970\n\\cite{Jefferys}, and Barton and Fitch took about 1s for the second\norder DDF on TITAN with CAMAL \\cite{Barton72}.  A closer look at the\nrelative times for individual sections of the program shows that the\nsubstitution case of replacing a polynomial variable by a Fourier\nseries is only marginally faster than the simple REDUCE program.  In\nthe DDF program this operation is only used once in a major form,\nsubstituting into the Legendre polynomials, which have been previously\ncalculated by Rodrigues formula.  This suggests that we replace this\nwith the recurrence relationship.\n\nMaking this change actually slows down the normal REDUCE by a small\namount but makes a significant change to the Fourier module; it\nreduces the run time for the 6th order DDF from 3084.62s to 2002.02s.\nThis gives some indication of the problems with benchmarks.  What is\nclear is that the current implementation of substitution of a Fourier\nseries for a polynomial variable is inadequate.\n\n\\section{Conclusion}\n\nThe Fourier module is far from complete.  The operations necessary for\nthe solution of Duffing's and Hill's equations are not yet written,\nalthough they should not cause much problem.  The main defficiency is\nthe treatment of series truncation; at present it relies on the REDUCE\nWTLEVEL mechanism, and this seems too coarse for efficient truncation.\nIt would be possible to re-write the polynomial manipulator as well,\nwhile retaining the REDUCE syntax, but that seems rather more than one\nwould hope.\n\nThe real failure so far is the large time lag between the REDUCE-based\nsystem on a modern workstation against a mainframe of 25 years ago\nrunning a special system.  The CAMAL Disturbing function program could\ncalculate the tenth order with a maximum of 32K words (about\n192Kbytes) whereas this system failed to calculate the eigth order in\n4Mbytes (taking 2000s before failing).  I have in my archives the\noutput from the standard CAMAL test suite, which includes a sixth\norder DDF on an IBM 370/165 run on 2 June 1978, taking 22.50s and\nusing a maximum of 15459 words of memory for heap --- or about\n62Kbytes.  A rough estimate is that the Orion 1/05 is comparable in\nspeed to the 360/165, but with more real memory and virtual memory.\n\nHowever, a simple Fourier manipulator has been created for REDUCE which\nperforms between twice and three times the speed of REDUCE using\npattern matching.  It has been shown that this system is capable of\nperforming the calculations of celestial mechanics, but it still\nseriously lags behind the efficiency of the specialist systems of\ntwenty years before.  It is perhaps fortunate that it was not been\npossible to compare it with a modern specialist system.\n\nThere is still work to do to provide a convenient user interface, but\nit is intended to develop the system in this direction.  It would be\npleasant to have again a system of the efficiency of CAMAL(F).\n\nI would like to thank Codemist Ltd for the provision of computing\nresources for this project, and David Barton who taught be so much\nabout Fourier series and celstial mechanics.  Thank are also due to\nthe National Health Service, without whom this work and paper could not\nhave been produced.\n\n\\section*{Appendix: The DDF Function}\n\\begin{verbatim}\narray p(n/2+2);\nharmonic u,v,w,x,y,z;\nweight e=1, b=1, d=1, a=1;\n\n%% Generate Legendre Polynomials to sufficient order\nfor i:=2:n/2+2 do <<\n  p(i):=(h*h-1)^i;\n  for j:=1:i do p(i):=df(p(i),h)/(2j)\n>>;\n\n%%%%%%%%%%%%%%%% Step1: Solve Kepler equation\nbige := fourier 0;\nfor k:=1:n do <<\n  wtlevel k;\n  bige:=fourier e * hsub(fourier(sin u), u, u, bige, k);\n>>;\n\n%% Ensure we do not calculate things of too high an order\nwtlevel n;\n\n%%%%%%%%%%%%%%%% Step 2: Calculate r/a in terms of e and l\ndd:=-e*e; hh:=3/2; j:=1; cc := 1;\nfor i:=1:n/2 do <<\n  j:=i*j; hh:=hh-1; cc:=cc+hh*(dd^i)/j\n>>;\nbb:=hsub(fourier(1-e*cos u), u, u, bige, n);\naa:=fourier 1+hdiff(bige,u); ff:=hint(aa*aa*fourier cc,u);\n\n%%%%%%%%%%%%%%%% Step 3: a/r and f\nuu := hsub(bb,u,v); uu:=hsub(uu,e,b);\nvv := hsub(aa,u,v); vv:=hsub(vv,e,b);\nww := hsub(ff,u,v); ww:=hsub(ww,e,b);\n\n%%%%%%%%%%%%%%%% Step 4: Substitute f and f' into S\nyy:=ff-ww; zz:=ff+ww;\nxx:=hsub(fourier((1-d*d)*cos(u)),u,u-v+w-x-y+z,yy,n)+\n    hsub(fourier(d*d*cos(v)),v,u+v+w+x+y-z,zz,n);\n\n%%%%%%%%%%%%%%%% Step 5: Calculate R\nzz:=bb*vv; yy:=zz*zz*vv;\n\non fourier;\nfor i := 2:n/2+2 do <<\n  wtlevel n+4-2i; p(i) := hsub(p(i), h, xx) >>;\n\nwtlevel n;\nfor i:=n/2+2 step -1 until 3 do\n    p(n/2+2):=fourier(a*a)*zz*p(n/2+2)+p(i-1);\nyy*p(n/2+2);\n\n\\end{verbatim}\n\\newpage\n\\bibliographystyle{plain}\n\\bibliography{camal}\n\n\\end{document}\n", "meta": {"hexsha": "e2b4d3eed68b0f02a2f34f4a8ecd98f3b3ec8ae3", "size": 27757, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "packages/camal/camal.tex", "max_stars_repo_name": "arthurcnorman/general", "max_stars_repo_head_hexsha": "5e8fef0cc7999fa8ab75d8fdf79ad5488047282b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "packages/camal/camal.tex", "max_issues_repo_name": "arthurcnorman/general", "max_issues_repo_head_hexsha": "5e8fef0cc7999fa8ab75d8fdf79ad5488047282b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "packages/camal/camal.tex", "max_forks_repo_name": "arthurcnorman/general", "max_forks_repo_head_hexsha": "5e8fef0cc7999fa8ab75d8fdf79ad5488047282b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.9193037975, "max_line_length": 79, "alphanum_fraction": 0.7283568109, "num_tokens": 7384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3178205775218163}}
{"text": "\\chapter*{Introduction}\n\\addcontentsline{toc}{chapter}{Introduction}\n\nClustering is a commonly used technique for simplifying the work with complex data\\-sets.\nThe main principle is to represent a dataset composed of a huge number of elements by a simplified (and significantly smaller) set of element groups which are commonly called clusters.\nThere are many various ways of constructing the clustering algorithms because each discipline typically requires a different kind of cluster similarity, it manipulates completely different data (texts, sequences, vectors) and it has different expectations about the organizing of the resulting data.\n\nClustering is commonly used to analyze datasets originating in single-cell cytometry~\\cite{shapiro2005practical}, where grouping the cells by similar measured features often corresponds to creating clusters of all individual biological types of the cells. This greatly simplifies a data analysis and a distinction of different cell types. Many customized approaches for clustering cytometry data have been developed, including FlowSOM~\\cite{van2015flowsom}, PhenoGraph~\\cite{levine2015data}, SPADE~\\cite{qiu2011extracting} or FlowGrid~\\cite{ye2019ultrafast}. This thesis focuses on agglomerative hierarchical clustering with the Mahalanobis metric, originally developed by \\citet{fivser2012detection} for the purpose of monitoring minimal residual decease in patients with leukemia. \n\nThe Mahalanobis clustering is, however, seriously restricted by the performance and complexity of the current implementation, which can cluster tens of thousands of cells on a common hardware.\nThe computation of these clusters is time demanding and consumes a lot of computer memory. Spe\\-cifically for the Mahalanobis clustering, the maximum size of a dataset that can be processed on common hardware varies at about 100,000 cells. As a result, the performance of the Mahalanobis clustering is unsuitable for processing data from modern cytometers used in current experiments, which often produce datasets of more than several million cells.\n\nThe primary goal of this thesis is to research possibilities of accelerating the Mahalanobis clustering on a GPU, develop the implementation of the clustering accelerated on a GPU and measure its results. Many clustering algorithms have been already ported to a GPU device, eg.~DBSCAN~\\cite{andrade2013g}, UPGMA~\\cite{hua2017mgupgma}, etc.. The Mahalanobis clustering is extremely suitable for cytometry because it naturally forms elliptical clusters. A GPU-accelerated implementation that could improve the performance on large datasets has not been developed yet.\n\nThe thesis first discusses the hierarchical clustering (section~\\ref{sec01:hierarch_clust}) and variations of algorithms that can be used (section~\\ref{sec01:hca}). Then, an overview of the programming for the GPU is introduced (section~\\ref{sec02:cuda}). Using this information, the thesis designs a parallelized algorithm of MHCA which can be run on a GPU; therefore, it is significantly faster. The combination of simple metric spaces with Minkowski distance specialization and enormous GPU throughput allows for a major memory requirements reduction. The total acceleration gain of the implementation varies from 20 times to 5000 times. The quality and speed of the result is demonstrated on flow and mass cytometry datasets. We hope that the results of the thesis will be possible to package and use for biologically relevant purposes.\n\n\n", "meta": {"hexsha": "b98c6ee6e41e9188799a4c7b82d66704c5f5e6fa", "size": 3485, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/preface.tex", "max_stars_repo_name": "asmelko/gmhc", "max_stars_repo_head_hexsha": "f728aea146de8a3accbf051b0c7b2d1333bb6f8c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-04-01T08:37:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T21:50:31.000Z", "max_issues_repo_path": "thesis/preface.tex", "max_issues_repo_name": "asmelko/gmhc", "max_issues_repo_head_hexsha": "f728aea146de8a3accbf051b0c7b2d1333bb6f8c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis/preface.tex", "max_forks_repo_name": "asmelko/gmhc", "max_forks_repo_head_hexsha": "f728aea146de8a3accbf051b0c7b2d1333bb6f8c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-01T08:38:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-01T08:38:02.000Z", "avg_line_length": 193.6111111111, "max_line_length": 840, "alphanum_fraction": 0.8286944046, "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3178205775218163}}
{"text": "\\chapter{Machine Learning and \\mbox{uncertainties}}\n\\label{methods_ML}\n\n\\vspace{-15pt} % one line spacing corresponds approx to 15 pts\n\\begin{tcolorbox}[enhanced,width=\\textwidth,size=fbox,\n        sharp corners,colframe=black!5!white,drop fuzzy shadow southeast,\n        boxrule=3mm, parbox=false] \n        \nThis chapter borrows from the article \\citep{walch_big_2020}:\n\n\\qquad %\\bibentry{walch_big_2020}\nA. Walch, R. Castello, N. Mohajeri, and J.-L. Scartezzini (2020).   \nBig data mining for the estimation of hourly rooftop photovoltaic potential and its uncertainty.\n\\textit{Applied Energy}, 262:114404. \n\\href{https://doi.org/10.1016/j.apenergy.2019.114404}{doi:10.1016/j.apenergy.2019.114404}\n\nand the conference proceedings \\cite{walch_spatio-temporal_2019, walch_fast_2019}:\n\n\\quad A. Walch, R. Castello, N. Mohajeri, F. Guignard, M. Kanevski, and J.-L. Scartezzini (2019). \nSpatio-temporal modelling and uncertainty estimation of hourly global solar irradianceusing Extreme Learning Machines.\n\\textit{Energy Procedia}, 158:6378–6383.\\\\\n\\href{https://doi.org/10.1016/j.egypro.2019.01.219}{doi:10.1016/j.egypro.2019.01.219}\n% \\quad \\bibentry{walch_spatio-temporal_2019} \n\n\\quad % \\bibentry{walch_fast_2019}\nA. Walch, R. Castello, N. Mohajeri, and J.-L. Scartezzini (2019).\nA Fast Machine Learning Model for Large-Scale Estimation of Annual Solar Irradiation on Rooftops. \n\\textit{ISES SWC2019 / SHC2019 Conference Proceedings}.\n\\href{https://doi.org/10.18086/swc.2019.45.12}{doi:10.18086/swc.2019.45.12}\n\n\\end{tcolorbox}\n\nThe large-scale estimation of RE potential at high spatial and temporal resolution challenges the analytical and geospatial models from Chapter~\\ref{methods_physical}, for three main reasons.\nFirst, some data required to perform the analytical and geospatial modelling may not be available across the entire region for which the potential is computed.\nSecond, the resolution or quality of some of the input datasets may be insufficient to assure a high-resolution potential estimation, but it could be improved through the use of additional information.\nThird, these physics-based approaches may be too computationally intensive, inhibiting their application at the large scale.\nThe use of Machine Learning (ML) as a method to address these limitations of \"classical\" physics-based models has attracted increasing attention in recent years \\cite{willard_integrating_2020}. \n\nIn this thesis, ML is used to address the above-mentioned limitations for the national-scale estimation of RPV (Chapter~\\ref{solar}) and GSHP (Chaper~\\ref{geothermal}) potential. \nThe ML models hereby learn and predict the relationship between a set of input data (\\textit{features}) and output variables (\\textit{targets}), known as \\textit{supervised learning}, as summarized in Section~\\ref{ML_supervised}.\nFor an in-depth introduction to Machine Learning, interested readers may refer for example to \\citet{bishop_pattern_2006}.\n\nThe use of data-driven methods further requires the estimation of \\textit{uncertainties} related to the ML predictions, which are essential for decision-making processes \\cite{knusel_argument-based_2020}. \nUncertainties may arise for example from noise in input data sources or from the modelling approaches themselves, and their quantification is a vast field of research \\cite{willard_integrating_2020,knusel_argument-based_2020}.\nUncertainties arising from data noise and from ML models are modelled here in the form of standard deviations, which are propagated through the analytical models presented in Chapter~\\ref{methods_physical}. \nSection~\\ref{unc_ML} provides an overview of the applied methods for a systematic quantification of uncertainties through combined physics-based and data-driven modelling approaches. \n\n\\section{Supervised learning}\n\\label{ML_supervised}\n\nSupervised learning algorithms are trained on a set of input features and corresponding output targets. The training procedure aims to minimise the error between an algorithm's prediction and the known (\"true\") target.\nSeveral design choices can influence the performance of supervised learning algorithms: (i) the choice of the input features, (ii) the choice of an appropriate ML model for a given problem, (iii) the\nchoice of the parameters defining the model structure (hyper-parameters), and (iv) the size of the training data.\nThe selection of suitable input features varies largely between different ML applications and is often based on expert knowledge. \nThe full set of available features, obtained using expert knowledge or otherwise, may however contain features which are redundant or even detrimental to the ML model's performance.\nFeature exploration and selection techniques may hence be used to enhance the quality of the feature set (see Section~\\ref{ML_features}).\n\nThe choice of an appropriate ML model depends on the structure of the problem and the available data. Regression algorithms are used to model continuous targets, while classification algorithms are used for binary or multi-class targets (see Section~\\ref{ML_models}). Furthermore, some algorithms such as Support Vector Machines (SVM) may be better suited for high-dimensional feature sets (i.e. many features), while other algorithms such as Extreme Learning Machines (ELM) are optimized for very large datasets (i.e. many samples). For image or natural language processing, convolutional neural networks (CNN) and recursive neural networks (RNN) have gained high popularity in recent years.\n\nFor any ML model, the optimization of its hyper-parameters (referred to as model \\textit{tuning}) is performed during the training phase. For model training, the labelled data (all data samples for which both features and targets are known) are divided into three random subsets: \n(i) The \\textit{training} set, which is used to fit the model, (ii) the \\textit{validation} set, which is used to assess the model's performance and to select the hyper-parameters, and (iii) the \\textit{test} set, which is excluded from the tuning procedure and used for evaluating the general performance of the model.\nThe test set usually contains $20 - 33\\%$ of the labelled data. The remaining data is then split again, keeping another $20 - 33\\%$ for model validation.\nTo avoid biases in the choice of the training and validation sets, a $k$-fold cross-validation (CV) procedure is widely applied in the literature. \nFor this, the training data is randomly split into $k$ subsets (folds), from which $k$ ML models are trained. Each model uses ($k$ – 1) folds for training and the last fold for validation. \nUnless mentioned otherwise, a 5-fold cross-validation ($k$ = 5) is used throughout this work.\n\n\\subsection{Feature exploration and selection techniques}\n\\label{ML_features}\n\nA vast variety of methods exist in the literature for the exploration, analysis and selection of appropriate features for ML models, which are often highly dependent on the application. In this section, five concepts for designing ML feature sets are introduced, which have proven useful for the ML applications presented in this thesis.\n\n\\textbf{Correlation analysis} provides insights into potential redundancies between different features, and allows to obtain a first quantitative measure of the relevance of each feature towards predicting the target variable(s).\nIn addition to the widely used Pearson correlation coefficient, which measures linear correlations, other measures of non-linear dependencies between variables may be used, such as Spearman's rank correlation coefficient \\cite{kokoska_crc_1999} or mutual information \\cite{kozachenko_statistical_1987}. While low correlations are desirable between the different features, indicating low redundancy within the feature set, high correlations between the features and the target suggest a high importance towards predicting this target.\n\n\\textbf{Feature transformation} includes the normalisation of the features, typically to zero mean and unit variance, but it may further refer to non-linear transformations of the features or the target. While normalisation is standard practice and required for many ML algorithms, the suitability of non-linear transformations depends on the data. For example, log-transformations may significantly improve the predictions for features and targets at exponential scale. Visualisations like histograms or scatterplots can provide insights into suitable transformations.\n\n\\textbf{Principal Component Analysis (PCA)} \\cite{tipping_probabilistic_1999} is an advanced feature transformation technique which yields a set of independent (principal) components. These components are ranked according to the percentage of explained variance in each component. To select features using PCA, the minimum percentage of explained variance may be defined, such that the last-ranked components up to the required percentage of explained variance are discarded. \nThe advantage of this method is that it yields only independent components, which is favourable for the performance of many ML models, and it can drastically reduce the number of features in high-dimensional problems. However, the PCA is based on the features only and contains no information on the relevance of the features to predicting the target. It further requires all available features as input, so it cannot be used to reduce the number of input variables.\n\n\\textbf{Sequential backward selection (SBS) }\\cite{ferri_comparative_1994} is one method that can be applied to reduce the number of input variables. Its advantage is that it can be applied to any ML algorithm, using any metric of evaluation. \nStarting from the complete feature set, the SBS iteratively excludes one feature at a time and computes the error for the prediction using the reduced feature set. The feature whose exclusion causes the lowest change in prediction error ($\\Delta_{err}$) is permanently removed from the set of features. This procedure is repeated until only one feature remains, and the $\\Delta_{err}$ is recorded for each iteration.\nTo reduce the number of features, a threshold for $\\Delta_{err}$ can be applied, selecting all features that keep $\\Delta_{err}$ below the threshold.\nAs the number of iterations increases exponentially with the number of features, this procedure may not be applicable for high-dimensional problems.\n%\nIn this work, SBS is performed using the k-Nearest Neighbour algorithm (see Section~\\ref{ML_models}) due to its fast computational time, in combination with a 5-fold CV (see above).\n\n\\textbf{Feature importance.} In addition to the above methods, which provide some insights into the importance of the features towards predicting the target, some ML algorithms provide a measure of feature importance as part of their algorithm's design.\nNotably, decision tree algorithms (e.g. Random Forests) provide such a measure of feature importance. As the dataset is split at each node of the decision tree (see Fig.~\\ref{fig:rf}) based on a threshold for one feature, the reduction of the impurity (or variance) in the targets due to each feature can be quantified \\cite{breiman_random_2001}.\nAs redundancy between features may lead to misleading importance scores, this method should be combined with other analysis techniques.\n\n\\subsection{Regression and classification models}\n\\label{ML_models}\n\\label{RF}\n\n\\subsubsection{Regression}\n\n\\begin{table}[b]\n\\footnotesize\n\\centering\n\\caption[Error metrics in regression problems]{Error metrics in regression tasks for a dataset of $n$ samples, where $y_i$ is the target corresponding to the features $\\mathbf{x}_i$, $\\hat{y}_i$ is the prediction, $\\bar{y}$ is the mean of $y_i$ and $\\epsilon$ is a small positive number to avoid undefined MAPEs.} %  ($\\bar{y}=\\frac{1}{n} \\sum_{i=0}^{n-1} y_{i}$)\n\\label{tab:error_metrics}\n% \\resizebox{\\textwidth}{!}{%\n\\begin{tabular}{lllcl}\n\\hline\n\\textbf{Metric} & & \\textbf{Acronym} & & \\textbf{Definition} \\\\ \\hline\n&& &&\\\\[-2ex]\n\\begin{tabular}[c]{@{}l@{}}R$^2$-coefficient\\\\ of determination\\end{tabular} & & \\textit{R$^2$} &=& $\\displaystyle 1-\\frac{\\sum_{i=0}^{n-1}\\left(y_{i}-\\hat{y}_{i}\\right)^{2}}{\\sum_{i=0}^{n-1}\\left(y_{i}-\\bar{y}\\right)^{2}}$ \\\\[3ex]\n\\begin{tabular}[c]{@{}l@{}}Mean squared \\\\ error\\end{tabular} &  & \\textit{MSE} &=& $\\displaystyle \\frac{1}{n} \\sum_{i=0}^{n-1}\\left( y_i - \\hat{y}_i \\right)^2$ \\\\[3ex]\n\\begin{tabular}[c]{@{}l@{}}Root mean \\\\ squared error\\end{tabular} & & \\textit{RMSE} &=& $\\displaystyle \\left(\\frac{1}{n} \\sum_{i=0}^{n-1}\\left( y_i - \\hat{y}_i \\right)^2\\right)^{1/2}$ \\\\[3ex]\n\\begin{tabular}[c]{@{}l@{}}Mean absolute\\\\ error\\end{tabular} & & \\textit{MAE} &=& $\\displaystyle \\frac{1}{n} \\sum_{i=0}^{n-1}\\left| y_i - \\hat{y}_i \\right| $ \\\\[3ex]\n\\begin{tabular}[c]{@{}l@{}}Mean absolute \\\\ percentage error\\end{tabular} & & \\textit{MAPE} &=& $\\displaystyle \\frac{1}{n} \\sum_{i=0}^{n-1} \\frac{\\left| y_i - \\hat{y}_i \\right|}{\\max(\\epsilon,y_i)}$ \\\\[3ex]\nMean bias error & & \\textit{MBE} &=& $\\displaystyle \\frac{1}{n} \\sum_{i=0}^{n-1}\\left( y_i - \\hat{y}_i \\right) $\\\\[3ex]\n\\begin{tabular}[c]{@{}l@{}}Mean squared\\\\ logarithmic error\\end{tabular} & & \\textit{logMSE} &=& $\\displaystyle \\frac{1}{n} \\sum_{i=0}^{n-1}\\left( \\log(1 + y_i) - \\log(1 + \\hat{y}_i) \\right)^2$ \\\\[2ex] \\hline\n\\end{tabular}\n% }\n\\end{table}\n\nRegression algorithms are used to predict continuous variables, such as solar radiation or shallow geothermal heat potential. \nDuring model training, the (internal) parameters of the regression algorithms are optimized with the aim to minimise the error between the continuous targets and the model predictions.\nThis error (also referred to as the loss function) is often defined as the mean squared error (MSE), i.e. the mean of the squared difference between the predictions and the targets.\n%\nFor tuning and performance evaluation, the error metrics shown in Table~\\ref{tab:error_metrics} are used.\nThese are (i) the R$^2$-coefficient of determination, measuring the goodness of fit between predictions and targets, (ii) the MSE, (iii) the root-mean-squared error (RMSE), which has the same unit as the target, (iv) the mean average error (MAE), (v) the mean average percentage error (MAPE), (vi) the mean bias error (MBE), and (vii) the mean squared logarithmic error (logMSE), which is useful for targets with exponential growth \\cite{pedregosa_scikit-learn:_2011}.\n\n\\subsubsection{Classification}\nClassification algorithms are used for predicting discrete targets, either in a binary format (0 or 1) or as multiple classes, for example to differentiate between roof shapes \\cite{mohajeri_city-scale_2018}.\nThe discrete nature of the targets requires different metrics to assess the prediction results. \nIn classification tasks, common loss functions used in the training procedure include cross-entropy, also known as negative log-loss \\cite{bishop_pattern_2006}, and the gini impurity \\cite{breiman_classification_1984}, among others. These measures are designed to maximise the likelihood of a correct classification result, whereby the gini impurity is primarily used in classification trees. \n\nFor model tuning and performance evaluation, the number of correct and incorrect predictions is evaluated and displayed in a so-called confusion matrix, shown in Table~\\ref{tab:conf_matrix} for the case of binary classification. From this confusion matrix, several evaluation scores can be derived. These include (i) the overall accuracy (OA), namely the total number of correct classifications over the total number of samples, (ii) the precision, namely the correct predictions over the total predictions of a given class, (iii) the recall, i.e. the correct predictions over all true labels in a given class, and (iv) the f1-score, which is the weighted average of precision and recall ($2*\\text{\\textit{precision}}*\\text{\\textit{recall}}/(\\text{\\textit{precision}}+\\text{\\textit{recall}})$).\nAssessing the ensemble of these error metrics is particularly relevant for cases of imbalanced classification, where the number of samples in one class is very small compared to the other class. \n\n\\begin{table}[hb]\n\\footnotesize\n\\centering\n\\caption[Structure of confusion matrix for binary classification and evaluation metrics]{Structure of confusion matrix for binary classification and evaluation metrics derived from the confusion matrix, namely precision, recall and accuracy (italic font), with $\\sum = TN+TP+FN+FP$.}\n\\label{tab:conf_matrix}\n\\begin{tabular}{llccc}\n\\hline\n &  & \\multicolumn{2}{c}{\\textbf{Predicted class}} & \\multirow{2}{*}{\\textit{\\textbf{Recall}}} \\\\\n &  & \\textbf{0} & \\textbf{1} &  \\\\ \\hline\n\\multirow{2}{*}{\\textbf{True class}} & \\textbf{0} & True negatives (TN) & False positives (FP) & $TN/(TN + FP)$ \\\\\n & \\textbf{1} & False negatives (FN) & True positives (TP) & $TP/(TP + FN)$ \\\\ \\hline\n\\textit{\\textbf{Precision}} & \\textit{} & $TN/(TN + FN)$ & $TP/(TP + FP)$ & \\textit{\\textbf{OA} $= TP+TN/\\sum$} \\\\ \\hline\n\\end{tabular}\n\\end{table}\n\n\\subsubsection{ML model architectures}\n\nThroughout this work, I use and compare the performance of six supervised ML models from different families of algorithms: (i) Linear Regression (LIN), (ii) K-Nearest Neighbors (KNN), (iii) Support Vector Machines (SVM), (iv) Random Forests (RF), Artificial Neural Networks (ANN), and (iv) Extreme Learning Machine Ensembles (ELM-E). The description of the algorithms provided below focuses on regression problems, which dominate in the use of ML throughout this thesis. All algorithms can however be equally applied to classification problems. The architecture of the six considered algorithms is shown in Fig. \\ref{fig:ml_algorithms}.\n\n\\begin{figure}[tb] % !\n\\centering\n\\makebox[\\linewidth][c]{\n\\begin{subfigure}[t]{.3\\textwidth}\n  \\centering\n  \\fbox{\\includegraphics[width=.9\\linewidth]{images/Figs/lin.pdf} } \n  \\subcaption{\\textbf{LIN}}\n  \\label{fig:lin}\n\\end{subfigure}\n\\begin{subfigure}[t]{.35\\textwidth}\n  \\centering\n  \\includegraphics[width=.9\\linewidth]{images/Figs/SVM.pdf} \n  \\subcaption{\\textbf{SVM}}\n  \\label{fig:svm}\n\\end{subfigure}\n\\begin{subfigure}[t]{.35\\textwidth}\n  \\centering\n  \\includegraphics[width=.95\\linewidth]{images/Figs/ANN.pdf}\n  \\subcaption{\\textbf{ANN}}\n  \\label{fig:ann}\n\\end{subfigure}\n} \\\\ \\vspace{.25cm}\n\\makebox[\\linewidth][c]{\n\\begin{subfigure}[t]{.3\\textwidth}\n  \\centering\n  \\fbox{\\includegraphics[width=.9\\linewidth]{images/Figs/knn.pdf} }\n  \\subcaption{\\textbf{KNN}}\n  \\label{fig:knn}\n\\end{subfigure}\n\\begin{subfigure}[t]{.35\\textwidth}\n  \\centering\n  \\includegraphics[width=.95\\linewidth]{images/Figs/RF.pdf}\n  \\subcaption{\\textbf{RF}}\n  \\label{fig:rf}\n\\end{subfigure}\n\\begin{subfigure}[t]{.35\\textwidth}\n  \\centering\n  \\includegraphics[width=.95\\linewidth]{images/Figs/ELM_E.pdf}\n  \\subcaption{\\textbf{ELM-E}}\n  \\label{fig:elme}\n\\end{subfigure}\n}\n\\caption[Visualisation of ML algorithms used in this work]{Visualisation of ML algorithms used in this work. The selected algorithms are (a) Linear regression (LIN), (b) K-Nearest Neighbor Regression (KNN), (c) Support Vector Machine (SVM), (d) Random Forest (RF), (e) Artificial Neural Network (ANN), (f) Extreme Learning Machine Ensemble (ELM-E).}\n\\label{fig:ml_algorithms}\n\\end{figure}\n\n\\textbf{Linear Regression }(Fig. \\ref{fig:lin}) assumes that the target is a linear function of the inputs. The prediction is obtained from the linear combination of the features which minimizes the residual sum of squares between the target and predicted values \\cite{scikit-learn_developers_11_2020}. It is fast and requires no tuning of hyper-parameters but shows a low accuracy for non-linear problems. The equivalent classification approach for the linear regression is logistic regression, which estimates the probability of a data sample to belong to a specific class.\n\n\\textbf{K-nearest Neighbor Regression} (Fig. \\ref{fig:knn}) is an interpolation algorithm, which computes a prediction as the average of the targets of the $k$ training samples whose features are closest to the given inputs. In classification, the average is replaced by a \"majority voting\" of the $k$ neighbours \\cite{scikit-learn_developers_16_2020}. The training dataset works as a look-up table for the predictions, which makes it effective for low-dimensional problems but inefficient for large datasets. I use the Euclidean distance as a measure of “closeness” and tune the number of neighbors ($k_{nn}$).\n\n\\textbf{Support Vector Machine} (Fig. \\ref{fig:svm}), introduced by \\citet{cortes_support-vector_1995}, is the most popular algorithm in the family of kernel methods. It exploits the \\textit{kernel trick}, which projects the features to a higher-dimensional space that allows for linear modelling. Its structure makes it particularly effective for high-dimensional problems, but it does not scale well with the number of samples. In this work, I use $\\varepsilon$-Support Vector Regression with a radial basis function as kernel and tune the kernel coefficient ($\\gamma$), the penalty parameter (C) and the error tolerance ($\\varepsilon$).\n\n\\textbf{Random Forest} (Fig. \\ref{fig:rf}) is an ensemble (i.e. an aggregation) of decision trees, which was proposed by \\citet{breiman_random_2001}. Each of the decision trees in the ensemble pass a training sample along a set of nodes based on a threshold (defined during training) until a leaf node is reached. The prediction of each tree is obtained by averaging (or majority voting) the target values in the respective leaves. It is a popular algorithm due to its good predictive power and high robustness. Its main hyper-parameters are the number of features considered for the optimization of each threshold ($m_\\mathit{ftrs}$), the minimum number of samples in each leaf ($m_\\mathit{leaf}$) and the number of trees in the ensemble ($n_{est}$).\n\n\\textbf{Artificial Neural Networks} (Fig. \\ref{fig:ann}) consist of multiple layers of neurons, which are connected to the previous and the next layer through edges \\cite{rumelhart_learning_1986}. From the input layer, which contains one neuron for each input, the data samples are passed through one or more hidden layers to the output layer with one neuron for each output. Each neuron computes a weighted linear combination of all nodes of the previous layer (for fully connected networks), which is then passed through a non-linear activation function. The weights within the network are optimised using a backpropagation procedure \\cite{lecun_efficient_2012}. The hyperparameters of the ANN include the network architecture, namely the number of hidden layers and the number of neurons in each layer, the selected nonlinear activation function and a regularisation term.  \n\n\\textbf{Extreme Learning Machine Ensemble }(Fig. \\ref{fig:elme}) is a collection of single-layer neural networks (ELMs), which were developed by \\citet{huang_extreme_2006}. Each ELM consists of a single hidden layer, which is trained a more efficient way than traditional neural networks (see above) by a single-step optimization using a least-squares approach. This avoids the need for back-propagation, resulting in a faster training time and a low number of hyper-parameters. The aggregation of $n$ ELMs in an ensemble further increases the robustness of the model, reduces the risk of overfitting and enables the estimation of uncertainties \\cite{huang_trends_2015, guignard_uncertainty_2021}.\nThe main hyper-parameters to tune in the ELM-E are the size of the hidden layer ($m_{ELM}$) and the number of ELMs in the ensemble ($n_{ELM}$). Throughout this work, I use a sigmoid activation function, which is a common choice for regression problems \\cite{huang_trends_2015}.\n\n\\textbf{ML ensemble models}, like the RF and the ELM-E, have a specific architecture which increases the robustness of these models and enables the estimation of uncertainty, as described in Section~\\ref{unc_ML}. The ML ensembles are aggregates of ML models (e.g. decision trees or ELMs) - referred to as \"ensemble members\" - which are trained by applying a bootstrap-aggregating (bagging) approach \\cite{breiman_bagging_1996}. \nThe bagging approach introduces randomness into the model, by training each ensemble member on one bootstrapped resample of the training data.\nEach bootstrap replicate is obtained by resampling the $N$ training samples $N$ times uniformly and with replacement.\nOn average, every such resample contains 63.2\\% of the original data, with some duplicated samples \\cite{breiman_bagging_1996}. \nThe ensemble prediction is obtained by averaging the predictions of each ensemble member (regression) or by majority voting (classification).\n\nThe ML implementations of the \\texttt{scikit-learn} library for python \\cite{pedregosa_scikit-learn:_2011} are used for all models except the ELM-E. As no functional open-source code for the ELM-E was available when this work was carried out, I have implemented the ELM-E myself using the ML ensemble architecture described above (regression only). For this, I use the ELM model of the \\texttt{HPELM} package for python \\cite{akusok_high-performance_2015}, which supports acceleration on graphical processing units (GPUs). \n\n\\section{Uncertainties}\n\\subsection{Uncertainty estimation for ensemble models}\n\\label{unc_ML}\n\nThe architecture of ML ensemble models, described in Section~\\ref{ML_models}, permits the estimation of the uncertainty arising from the modelling process (the model uncertainty, $\\hat{\\sigma}_M$).  \nThe model uncertainty is quantified as the standard deviation of the predictions of all models in an ensemble, which is computed as \\cite{heskes_practical_1997}:\n\n\\begin{equation}\n\\label{eq:model_unc}\n  \\hat{\\sigma}_M^2 (\\mathbf{x}_i) = \\frac{1}{N} \\sum_{n=1}^N (\\hat{y}_i^n - \\hat{y}_i)^2, \\quad i=1,...,L\n\\end{equation}\n\nwhere $\\hat{\\sigma}_M$ denotes the model standard deviation, referred to as model uncertainty, $N$ denotes the ensemble length, $\\hat{y}_i$ is the ensemble prediction for sample $\\mathbf{x}_i$ and $\\hat{y}_i^n$ is the prediction of the $n$-th ensemble member.\n\nThe remaining residuals after the subtraction of the model variance are further used to estimate the uncertainty related to the data noise (the data uncertainty, $\\hat{\\sigma}_D$) \\cite{akusok_per-sample_2019,guignard_uncertainty_2021}. \nThey are derived by subtracting the model variance from the squared difference between $\\hat{y}_i$ and the targets $y_i$, as shown in Eq.~\\eqref{eq:data_unc} below.\nIn order to reduce bias, the out-of-bag (OOB) model output is used, which is the mean of the ensemble members for which a given training data point was not considered (due to bootstrapping) \\cite{heskes_practical_1997}. \n\n\n\\begin{equation}\n\\label{eq:data_unc}\n  \\hat{\\sigma}_D^2 (\\mathbf{x}_i) = \\max \\left\\{ (y_i - \\hat{y}_i)^2 - \\hat{\\sigma}_M^2 (\\mathbf{x}_i) , 0 \\right\\}, \\quad i=1,...,L\n\\end{equation}\n \n where $\\hat{\\sigma}_D$ denotes the standard deviation of data noise, referred to as data uncertainty, and $y_i$ is the target value for sample $\\mathbf{x}_i$. \n$\\hat{\\sigma}_D$ can only be computed if $y_i$ is known. Thus, a second ML model is trained from the residuals to predict $\\hat{\\sigma}_D$ for points with unknown targets. Unless mentioned otherwise, the same hyper-parameters are used in both models.\n\nThe total variance of a variable that is estimated using a ML model is the squared sum of its model uncertainty and its data uncertainty: \n\n\\begin{equation}\n\\label{eq:total_unc}\n\\sigma^2 (\\mathbf{x}_i) = \\hat{\\sigma}_M^2 (\\mathbf{x}_i) + \\hat{\\sigma}_D^2 (\\mathbf{x}_i), \\quad i=1,...,L\n\\end{equation}\nThis approach to estimate both the model and the data uncertainty enables a specific characterization of the uncertainty for each spatio-temporal point. It has been previously used to estimate for example wind speeds for wind power generation~\\cite{wan_probabilistic_2014}.\n\n\\subsection{Uncertainty propagation}\n\\label{method_unc_prop}\n\nFor the estimation of renewable resource potential, different sources of uncertainties must be combined and propagated through physicals models. \nFor this propagation of uncertainties, the correlation among the random variables (RVs) plays a key role.\n%\nIf statistical independence can be assumed, the mean and variance of the resulting variables can be computed from the mean and variance of each parameter only, which greatly simplifies the uncertainty propagation.\nHowever, this assumption does not always hold, in which case correlations between RVs must be taken into account.\nIn the context of this thesis, the propagation of uncertainties over a set of sums and products of RVs is considered using error propagation theory \\cite{jcgm_evaluation_2008, goodman_variance_1962}. This section summarises the error propagation formulas for summations and multiplications, applied in the following chapters, in their general form. \n\nIn error analysis, the variance of the sum of $N$ randomly distributed variables $X_i$ is obtained from the variances of each RV and their pairwise covariances, such that (cf. \\cite{jcgm_evaluation_2008}):\n\n\\begin{equation}\n\\label{eq:unc_sum}\n\\mathrm{Var}\\left(\\sum_{i=1}^N X_i\\right) = \\sum_{i=1}^N\\mathrm{Var}(X_i) + 2\\sum_{i < j}\\mathrm{Cov}(X_i, X_j)\n\\end{equation}\nwhich simplifies to the sum of the variances of $X_i$ if the RVs are statistically independent.\n%\nThe variance of the product of two RVs $X$ and $Y$ is defined as (cf. \\cite{goodman_variance_1962}):\n\n\\begin{align}\n\\label{eq:var_mult_corr}\n\\mathrm{Var}(X Y)&=\\mathrm{E}\\left(X^{2} Y^{2}\\right)-\\mathrm{E}(X Y)^{2} \\\\\n&= \\mathrm{Cov}\\left(X^{2}, Y^{2}\\right)+\\left[\\mathrm{Var}(X)+\\mathrm{E}(X)^{2}\\right] \\left[\\mathrm{Var}(Y)+\\mathrm{E}(Y)^{2}\\right]-[\\mathrm{Cov}\\left(X, Y\\right)+\\mathrm{E}(X)  \\mathrm{E}(Y)]^{2} \\nonumber\n\\end{align}\n\nIf statistical independence between $X$ and $Y$ can be assumed, the covariance terms $\\mathrm{Cov}\\left(X^{2}, Y^{2}\\right)$and $\\mathrm{Cov}\\left(X, Y\\right)$ can be omitted, such that Eq.~\\eqref{eq:var_mult_corr} becomes a function of the variances of $X$ and $Y$ and their expected value (cf. \\cite{goodman_variance_1962}):\n\\begin{equation}\n\\label{eq:unc_prod}\n\\mathrm{Var}(XY) = \\mathrm{Var}(X)\\mathrm{Var}(Y) + \\mathrm{Var}(X) \\mathrm{E}(Y)^2 + \\mathrm{Var}(Y) \\mathrm{E}(X)^2\n\\end{equation}", "meta": {"hexsha": "8c50fa9e32f34b3ed567e4e45c5df32f94626269", "size": 30179, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "main/ch2_ML.tex", "max_stars_repo_name": "aw1513/EPFL_thesis_template", "max_stars_repo_head_hexsha": "88a13da49d9a851e00e19f83914bb7709b78bb86", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main/ch2_ML.tex", "max_issues_repo_name": "aw1513/EPFL_thesis_template", "max_issues_repo_head_hexsha": "88a13da49d9a851e00e19f83914bb7709b78bb86", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main/ch2_ML.tex", "max_forks_repo_name": "aw1513/EPFL_thesis_template", "max_forks_repo_head_hexsha": "88a13da49d9a851e00e19f83914bb7709b78bb86", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 106.264084507, "max_line_length": 877, "alphanum_fraction": 0.775207926, "num_tokens": 7656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030761371502, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3178205695901968}}
{"text": "\\section{Static Semantics for Modules}\n\\label{statmod-sec}\n\\subsection{Semantic Objects}\n\\label{statmod-sem-obj-sec}\nThe\\index{34.1} simple \nobjects for Modules static semantics are exactly as for the Core.\nThe compound objects are those for the Core,\naugmented by those in Figure~\\ref{module-objects}.\n\n\n\\begin{figure}[h]\n%\\vspace{2pt}\n\\adhocreplacementl{\\thenostrsharing}{0mm}{\n\\begin{displaymath}\n\\begin{array}{rcl}\n\\M              & \\in   & \\StrNameSets = \\Fin(\\StrNames)\\\\\n\\N\\ {\\rm or}\\ (\\M,\\T)\n                & \\in   & \\NameSets = \\StrNameSets\\times\\TyNameSets\\\\\n\\sig\\ {\\rm or}\\ \\longsig{}\n                & \\in   & \\Sig =  \\NameSets\\times\\Str \\\\\n\\funsig\\ {\\rm or}\\ \\longfunsig{}\n                & \\in   & \\FunSig = \\NameSets\\times\n                                         (\\Str\\times\\Sig)\\\\\n\\G              & \\in   & \\SigEnv        =       \\finfun{\\SigId}{\\Sig} \\\\\n\\F              & \\in   & \\FunEnv        =       \\finfun{\\FunId}{\\FunSig} \\\\\n\\B\\ {\\rm or}\\ \\N,\\F,\\G,\\E\n                & \\in   & \\Basis = \\NameSets\\times\n                                              \\FunEnv\\times\\SigEnv\\times\\Env\\\\\n\\end{array}\n\\end{displaymath}}{\\begin{displaymath}\n\\begin{array}{rcl}\n\\sig\\ {\\rm or}\\ \\newlongsig{}\n                & \\in   & \\Sig =  \\TyNameSets\\times\\Env \\\\\n\\funsig\\ {\\rm or}\\ \\newlongfunsig{}\n                & \\in   & \\FunSig = \\TyNameSets\\times\n                                         (\\Env\\times\\Sig)\\\\\n\\G              & \\in   & \\SigEnv        =       \\finfun{\\SigId}{\\Sig} \\\\\n\\F              & \\in   & \\FunEnv        =       \\finfun{\\FunId}{\\FunSig} \\\\\n\\B\\ {\\rm or}\\ \\T,\\F,\\G,\\E\n                & \\in   & \\Basis = \\TyNameSets\\times\n                                              \\FunEnv\\times\\SigEnv\\times\\Env\\\\\n\\end{array}\n\\end{displaymath}}\n\\caption{Further Compound Semantic Objects}\n\\label{module-objects}\n%\\vspace{3pt}\n\\end{figure}\n%\n\\replacement{\\thenostrsharing}{\nThe prefix $(\\N)$, in signatures and functor signatures, binds both type names\nand structure names. We shall always consider a set $\\N$ of names as\npartitioned into a pair $(\\M,\\T)$ of sets of the two kinds of name.}{The \nprefix $(\\T)$, in signatures and functor signatures, binds  type names.}\n\\deletion{\\thenostrsharing}{It is sometimes convenient to work with an arbitrary semantic object $A$, or\nassembly $A$ of such objects.\nAs with the function $\\TyNamesFcn$,\n$\\StrNamesFcn(A)$ and $\\NamesFcn(A)$ denote respectively the set of structure names\nand the set of names occurring free in $A$.}\nCertain operations require a change of bound names in semantic objects;\nsee for example \\replacement{\\thenostrsharing}{Section~\\ref{realisation-sec}}{Section~\\ref{tyrea.sec}}. When bound type names are\nchanged, we demand that all of their attributes (i.e. \\deletion{\\thenoimptypes}{imperative, }equality\nand arity) are preserved.\\index{34.2}\n\n\\deletion{\\thenotypexplication}{For any structure $\\S=\\longS{}$ we call $m$ the {\\sl structure name} or\n{\\sl name} of $\\S$; also, the {\\sl proper substructures} of $\\S$ are\nthe members of $\\Ran\\SE$ and their proper substructures.  The \n{\\sl substructures} of\n$\\S$ are $\\S$ itself and its proper substructures.  The structures\n{\\sl occurring in}\nan object or assembly $A$ are the structures and\nsubstructures from which it is built.}\n\nThe operations of projection, injection and modification are as for the\nCore. Moreover, we define $\\of{\\C}{\\B}$ to be the context\n$(\\of{\\T}{\\B},\\emptyset,\\of{\\E}{\\B})$, i.e.~with an empty set of\nexplicit type variables.\nAlso,\nwe frequently need to modify a basis $\\B$ by an environment $\\E$\n(or a structure environment $\\SE$ say),\nat the same time extending \\replacement{\\thenostrsharing}{$\\of{\\N}{\\B}$}{$\\of{\\T}{\\B}$} to include the type names \n\\deletion{\\thenostrsharing}{and\nstructure names }of $\\E$ (or of $\\SE$ say).\nWe therefore define $\\B\\oplus\\SE$, for example, to mean\n\\replacement{\\thenostrsharing}{$\\B+(\\NamesFcn\\SE,\\SE)$}{$\\B+(\\TyNamesFcn\\SE,\\SE)$}.\n\\index{34.3}\n \n\\insertion{\\thenostrsharing}{\nThere is no separate kind of semantic object to represent structures: \nstructure expressions elaborate to environments, just as structure-level\ndeclarations do. Thus, notions which are commonly associated with structures\n(for example the notion of matching a structure against a signature) are defined\nin terms of environments.}\n\n\\deletion{\\thenostrsharing}{\n\\subsection{Consistency}\n\\label{consistency-sec}\nA\\index{35.1} set of type structures is said to be {\\sl consistent} if, for all\n$(\\theta_1,\\CE_1)$ and $(\\theta_2,\\CE_2)$ in the set, if $\\theta_1 = \\theta_2$\nthen\n\\[\\CE_1=\\emptymap\\ {\\rm or}\\ \n\\CE_2=\\emptymap\\ {\\rm or}\\ \\Dom\\CE_1=\\Dom\\CE_2\\]\nA semantic object $A$ or assembly $A$ of objects is said to be\n{\\sl consistent} if (after changing bound names to make all nameset prefixes\nin $A$ disjoint) \nfor all $\\S_1$ and\n$\\S_2$ occurring in $A$ and for every $\\longstrid$ \nand every $\\longtycon$\n\\begin{enumerate}\n\\item If $\\of{\\m}{\\S_1}=\\of{\\m}{\\S_2}$, and both\n      $\\S_1(\\longstrid)$ and $\\S_2(\\longstrid)$ exist, then\n      \\[ \\of{\\m}{\\S_1(\\longstrid)}\\ =\\ \\of{\\m}{\\S_2(\\longstrid)}\\]\n\n\\item If $\\of{\\m}{\\S_1}=\\of{\\m}{\\S_2}$, and both\n      $\\S_1(\\longtycon)$ and $\\S_2(\\longtycon)$ exist, then\n      \\[ \\of{\\theta}{\\S_1(\\longtycon)}\\ =\\ \\of{\\theta}{\\S_2(\\longtycon)}\\]\n\n\\item The set of all type structures in $A$ is consistent\n\\end{enumerate}\n\nAs an example, a functor signature \n$\\longfunsig{}$ is\nconsistent if, assuming first that \n$\\N\\cap\\N'=\\emptyset$,\nthe assembly $A=\\{\\S,\\S'\\}$ is consistent.\n\nWe may loosely say that two \nstructures $\\S_1$ and $\\S_2$\nare consistent if\n$\\{\\S_1,\\S_2\\}$ is consistent, but must remember that this is stronger than\nthe assertion that $\\S_1$ is consistent and $\\S_2$ is consistent.\n\nNote that if $A$ is a consistent assembly and $A'\\subset A$ then $A'$ is\nalso a consistent assembly.\n}\n\n\\deletion{\\thenostrsharing}{\n\\subsection{Well-formedness}\nA signature\\index{35.2} $\\longsig{}$ is {\\sl well-formed} \nif $\\N\\subseteq\\NamesFcn\\S$,\nand also, whenever $(\\m,\\E)$ is a\nsubstructure of $\\S$ and $\\m\\notin\\N$, then $\\N\\cap(\\NamesFcn\\E)=\\emptyset$.\nA functor signature $\\longfunsig{}$ is {\\sl well-formed} if\n$\\longsig{}$ and  $(\\N')\\S'$ are well-formed, and also, whenever\n$(\\m',\\E')$ is a substructure of $\\S'$ and $\\m'\\notin\\N\\cup\\N'$,\nthen $(\\N\\cup\\N')\\cap(\\NamesFcn\\E')=\\emptyset$.\n\nAn object or assembly $A$ is {\\sl well-formed} if every type environment,\nsignature and functor signature occurring in $A$ is well-formed.}\n\n\\deletion{\\thenostrsharing}{\\subsection{Cycle-freedom}\nAn\\index{35.3} object or assembly $A$ is {\\sl cycle-free} if it contains no\ncycle of structure names; that is, there is no sequence\n\\[\\m_0,\\cdots,\\m_{k-1},\\m_k=m_0\\ \\ (k>0)\\]\nof structure names such that, for each $i\\ (0\\leq i<k)$ some structure\nwith name $m_i$ occurring in $A$ has a proper substructure with name\n$m_{i+1}$.\n}\n\n\\deletion{\\thenostrsharing}{\n\\subsection{Admissibility}\n\\label{admis-sec}\nAn\\index{36.1} object or assembly $A$ is {\\sl admissible} if it is\nconsistent, well-formed and cycle-free. \nHenceforth it is assumed\nthat\nall objects mentioned are admissible.  \nWe also require that\n\\begin{enumerate}\n\\item In every sentence $A\\ts\\phrase\\ra A'$  inferred by the rules\ngiven in Section~\\ref{statmod-rules-sec}, the assembly $\\{A,A'\\}$ is\nadmissible.  \n\\item In the special case of a sentence $\\B\\ts\\sigexp\\ra\\S$,\nwe further require that the assembly consisting of all semantic\nobjects occurring in the entire inference of this sentence be\nadmissible. This  is important for the definition of principal\nsignatures in Section~\\ref{prinsig-sec}.\n\\end{enumerate}\nIn our semantic definition we have not undertaken to\nindicate how admissibility should be checked in an implementation.\n}\n\n\\subsection{Type Realisation}\n\\label{tyrea.sec}\n\\replacement{\\thenostrsharing}{\nA {\\sl type realisation}\\index{36.2} is a map\n$\\tyrea:\\TyNames\\to\\TypeFcn$\nsuch that\n$\\t$ and $\\tyrea(\\t)$ have the same arity, and\nif $t$ admits equality then so does $\\tyrea(\\t)$.\n\nThe {\\sl support} $\\Supp\\tyrea$ of a type realisation $\\tyrea$ is the set of\ntype names $\\t$ for which $\\tyrea(\\t)\\ne\\t$.}{A \n{\\sl (type) realisation}\\index{36.2} is a map\n$\\rea:\\TyNames\\to\\TypeFcn$\nsuch that\n$\\t$ and $\\rea(\\t)$ have the same arity, and\nif $t$ admits equality then so does $\\rea(\\t)$.\n\nThe {\\sl support} $\\Supp\\rea$ of a type realisation $\\rea$ is the set of\ntype names $\\t$ for which $\\rea(\\t)\\ne\\t$.}\n%\n\\deletion{\\thenostrsharing}{\\subsection{Realisation}\n\\label{realisation-sec}\nA {\\sl realisation}\\index{36.3} is a function $\\rea$ of names,\npartitioned into a type realisation $\\tyrea:\\TyNames\\to\\TypeFcn$\nand a function $\\strrea : \\StrNames\\to\\StrNames$.\nThe {\\sl support} $\\Supp\\rea$\nof a realisation $\\rea$ is the set of\nnames $\\n$ for which $\\rea(\\n)\\ne\\n$.}\\replacement{\\thenostrsharing}{The {\\sl yield}\n$\\Yield\\rea$ of a realisation $\\rea$ is the set of\nnames which occur in some $\\rea(\\n)$ for which $\\n\\in\\Supp\\rea$.}{The\n{\\sl yield} $\\Yield\\rea$ of a realisation $\\rea$ is the set of\ntype names which occur in some $\\rea(\\t)$ for which $\\t\\in\\Supp\\rea$.}\n\nRealisations $\\rea$ are extended to apply to all semantic objects; their\neffect is to\nreplace each name \\replacement{\\thenostrsharing}{$n$ by $\\rea(\\n)$}{$\\t$ by $\\rea(\\t)$}.  In applying $\\rea$ to an object with\nbound names, such as a signature \\replacement{\\thenostrsharing}{$\\longsig{}$}{$\\newlongsig{}$}, first bound names must be\nchanged so that, for each binding prefix \\replacement{\\thenostrsharing}{$(\\N)$}{$(\\T)$},\n\\replacement{\\thenostrsharing}{\n\\[\\N\\cap(\\Supp\\rea\\cup\\Yield\\rea)=\\emptyset\\ .\\]}{\\[\\T\\cap(\\Supp\\rea\\cup\\Yield\\rea)=\\emptyset\\ .\\]}\n%\n\\deletion{\\thenotypexplication}{\n\\subsection{Type Explication}\n\\label{type-explication-sec}\nA\\index{36.35} signature $(\\N)\\S$ is {\\sl type-explicit\\/} if,\nwhenever $\\t\\in\\N$ and occurs free in $\\S$, then some substructure of\n$\\S$ contains a type environment $\\TE$ such that\n$\\TE(\\tycon)=(\\t,\\CE)$ for some $\\tycon$ and some $\\CE$.} \n%\n\\subsection{Signature Instantiation}\n\\replacement{\\thenostrsharing}{\nA\\index{36.4} structure $\\S_2$ {\\sl is an instance of} a signature\n$\\sig_1=\\longsig{1}$,\nwritten $\\siginst{\\sig_1}{}{\\S_2}$, if there exists a realisation\n$\\rea$\nsuch that $\\rea(\\S_1)=\\S_2$ and $\\Supp\\rea\\subseteq\\N_1$.}{An\\index{36.4} environment $\\E_2$ {\\sl is an instance of} a signature\n$\\sig_1=\\newlongsig{1}$,\nwritten $\\siginst{\\sig_1}{}{\\E_2}$, if there exists a realisation\n$\\rea$\nsuch that $\\rea(\\E_1)=\\E_2$ and $\\Supp\\rea\\subseteq\\T_1$.}\n\\deletion{\\thenotypexplication}{(Note that if $\\sig_1$ is type-explicit then there is at most one\nsuch $\\rea$.)}\\ \n\\deletion{\\thenostrsharing}{A signature\n$\\sig_2=\\longsig{2}$ {\\sl is an instance of}\n$\\sig_1 =\\longsig{1}$,\nwritten $\\siginst{\\sig_1}{}{\\sig_2}$, if\n$\\siginst{\\sig_1}{}{\\S_2}$ and $\\N_2\\cap(\\NamesFcn\\sig_1)=\\emptyset$.\nIt can be shown that $\\siginst{\\sig_1}{}{\\sig_2}$ iff, for all $\\S$,\nwhenever $\\siginst{\\sig_2}{}{\\S}$ then $\\siginst{\\sig_1}{}{\\S}$.}\n\n\\subsection{Functor Signature Instantiation}\n\\replacement{\\thenostrsharing}{\nA\\index{36.5} pair $(\\S,(\\N')\\S')$ is called a {\\sl functor instance}.\nGiven $\\funsig=\\longfunsig{1}$,\na functor instance $(\\S_2,(\\N_2')\\S_2')$ is an {\\sl instance} of\n$\\funsig$,\nwritten $\\funsiginst{\\funsig}{}{(\\S_2,(\\N_2')\\S_2')}$,\nif there exists a realisation $\\rea$\nsuch that\n$\\rea(\\S_1,(\\N_1')\\S_1')=(\\S_2,(\\N_2')\\S_2')$ and\n$\\Supp\\rea\\subseteq\\N_1$.}{\nA\\index{36.5} pair $(\\E,(\\T')\\E')$ is called a {\\sl functor instance}.\nGiven $\\funsig=\\newlongfunsig{1}$,\na functor instance $(\\E_2,(\\T_2')\\E_2')$ is an {\\sl instance} of\n$\\funsig$,\nwritten $\\funsiginst{\\funsig}{}{(\\E_2,(\\T_2')\\E_2')}$,\nif there exists a realisation $\\rea$\nsuch that\n$\\rea(\\E_1,(\\T_1')\\E_1')=(\\E_2,(\\T_2')\\E_2')$ and\n$\\Supp\\rea\\subseteq\\T_1$.}\n%\n\\subsection{Enrichment}\n\\label{enrichment-sec}\nIn\\index{37.1} matching \\replacement{\\thenostrsharing}{a structure}{an environment} to a signature, the \\replacement{\\thenostrsharing}{structure}{environment} will be allowed both to\nhave more components, and to be more polymorphic, than (an instance of) the\nsignature.  Precisely, we  define enrichment of \\deletion{\\thenostrsharing}{structures, }environments and\ntype structures \\replacement{\\thenostrsharing}{by mutual recursion}{recursively} as follows.\n\n\\deletion{\\thenostrsharing}{A structure $\\S_1=(\\m_1,\\E_1)$\n{\\sl enriches} another structure\n$\\S_2=(\\m_2,\\E_2)$, written $\\S_1\\succ\\S_2$, if\n\\begin{enumerate}\n\\item $\\m_1=\\m_2$\n\\item $\\E_1\\succ\\E_2$\n\\end{enumerate}}\nAn environment \\replacement{\\theidstatus}{$\\E_1=\\longE{1}$}{$\\E_1=\\newlongE{1}$}\n{\\sl enriches} another environment \\replacement{\\theidstatus}{$\\E_2=$ $\\longE{2}$}{$\\E_2=\n( \\SE_2,$\\linebreak$\\TE_2,\\VE_2)$},\nwritten $\\E_1\\succ\\E_2$,\nif\n\\begin{enumerate}\n\\item $\\Dom\\SE_1\\supseteq\\Dom\\SE_2$, and $\\SE_1(\\strid)\\succ\\SE_2(\\strid)$\n                                               for all $\\strid\\in\\Dom\\SE_2$\n\\item $\\Dom\\TE_1\\supseteq\\Dom\\TE_2$, and $\\TE_1(\\tycon)\\succ\\TE_2(\\tycon)$\n                                               for all $\\tycon\\in\\Dom\\TE_2$\n\\item \\replacement{\\theidstatus}{$\\Dom\\VE_1\\supseteq\\Dom\\VE_2$, and $\\VE_1(\\id)\\succ\\VE_2(\\id)$\n                                               for all $\\id\\in\\Dom\\VE_2$}{$\\Dom\\VE_1\\supseteq\\Dom\\VE_2$, and $\\VE_1(\\vid)\\succ\\VE_2(\\vid)$\n                                               for all $\\vid\\in\\Dom\\VE_2$,\nwhere $(\\sigma_1,\\is_1)\\succ(\\sigma_2,\\is_2)$ means $\\sigma_1\\succ\\sigma_2$ and\n$$\\is_1 = \\is_2\\quad\\hbox{or}\\quad \\is_2 = \\isv$$}\n\\deletion{\\theidstatus}{\n\\item $\\Dom\\EE_1\\supseteq\\Dom\\EE_2$, and $\\EE_1(\\exn)=\\EE_2(\\exn)$\n                                               for all $\\exn\\in\\Dom\\EE_2$}\n\\end{enumerate}\nFinally, a type structure $(\\theta_1,\\adhocreplacementl{\\thece}{6cm}{\\CE}{\\VE}_1)$\n{\\sl enriches} another type structure $(\\theta_2,\\adhocreplacementl{\\thece}{-4cm}{\\CE}{\\VE}_2)$,\nwritten $(\\theta_1,\\adhocreplacementl{\\thece}{10mm}{\\CE}{\\VE}_1)\\succ(\\theta_2,\\adhocreplacementl{\\thece}{-12cm}{\\CE}{\\VE}_2)$,\nif\n\\begin{enumerate}\n\\item $\\theta_1=\\theta_2$\n\\item Either $\\adhocreplacementl{\\thece}{3cm}{\\CE}{\\VE}_1=\\adhocreplacementl{\\thece}{-8cm}{\\CE}{\\VE}_2$ or $\\adhocreplacementl{\\thece}{-11cm}{\\CE}{\\VE}_2=\\emptymap$\n\\end{enumerate}\n\n\\oldpagebreak\n\\subsection{Signature Matching}\n\\label{sigmatch-sec}\n\\replacement{\\thenostrsharing}{\nA\\index{37.2} structure $\\S$ {\\sl matches} a signature $\\sig_1$ if there exists\na structure $\\S^-$ such that $\\sig_1\\geq\\S^-\\prec\\S$. Thus matching\nis a combination of instantiation and enrichment. There is at most\none such $\\S^-$, given $\\sig_1$ and $\\S$.}{An\\index{37.2} environment $\\E$ {\\sl matches} a signature $\\sig_1$ if there exists\nan environment $\\E^-$ such that $\\sig_1\\geq\\E^-\\prec\\E$. Thus matching\nis a combination of instantiation and enrichment. There is at most\none such $\\E^-$, given $\\sig_1$ and $\\E$.} \\deletion{\\thenotypexplication}{Moreover, writing $\\sig_1=\n\\longsig{1}$, if $\\sig_1\\geq\\S^-$ then there exists a realisation $\\rea$\nwith $\\Supp\\rea\\subseteq\\N_1$ and $\\rea(\\S_1)=\\S^-$.\nWe shall then say that $\\S$ matches $\\sig_1$ {\\em via} $\\rea$.\n(Note that if $\\sig_1$ is type-explicit \nthen $\\rea$ is uniquely determined by $\\sig_1$ and $\\S$.)}\n\n\\deletion{\\thenostrsharing}{A\\index{37.2.5} signature $\\sig_2$ {\\em matches} a signature $\\sig_1$\nif for all structures $\\S$, if $\\S$ matches $\\sig_2$ then $\\S$\nmatches $\\sig_1$. It can be shown that $\\sig_2=\\longsig{2}$ matches\n$\\sig_1=\\longsig{1}$ if and only if there exists a realisation\n$\\rea$ with $\\Supp\\rea\\subseteq\\N_1$ and $\\rea(\\S_1)\\prec\\S_2$\nand $\\N_2\\cap\\NamesFcn\\sig_1=\\emptyset$.}\n\n\\deletion{\\thenostrsharing}{\\subsection{Principal Signatures}\n\\label{prinsig-sec}\nThe definitions in this section concern the elaboration of signature\nexpressions; more precisely they concern inferences of sentences of the\nform $\\B\\ts\\sigexp\\ra\\S$, where $\\S$ is a structure and $\\B$ is a basis.\nRecall, from Section~\\ref{admis-sec}, that the assembly of all semantic\nobjects in such an inference must be admissible.\n\nFor any basis $\\B$ and any structure $\\S$, \nwe say that $\\B$ {\\sl covers} $\\S$\nif for every substructure $(m,E)$ of $\\S$ such that\n$m\\in\\of{\\N}{\\B}$:\n\\begin{enumerate}\n\\item\nFor every structure identifier $\\strid\\in\\Dom\\E$,\n$\\B$ contains a substructure $(m,\\E')$ with $m$\nfree and $\\strid\\in\\Dom\\E'$\n\\item\nFor every type constructor $\\tycon\\in\\Dom\\E$,\n$\\B$ contains a substructure $(m,\\E')$ with $m$ free\nand $\\tycon\\in\\Dom\\E'$\n\\end{enumerate}\n(This condition is not a consequence of consistency of $\\{\\B,\\S\\}$; \ninformally, it states that if $\\S$ shares a substructure with $\\B$,\nthen $\\S$ mentions no more components of the substructure than\n$\\B$ does.)\n\n\n\nWe\\index{38.1} say that a signature\n$\\longsig{}$ is {\\sl principal for $\\sigexp$ in $\\B$} if, choosing $\\N$\nso that $(\\of{\\N}{\\B})\\cap\\N=\\emptyset$,\n\\begin{enumerate}\n\\item $\\B$ covers $\\S$ \n\\item $\\B\\vdash\\sigexp\\ra\\S$\n\\item Whenever $\\B\\vdash\\sigexp\\ra\\S'$, then $\\sigord{\\longsig{}}{}{\\S'}$\n\\end{enumerate}\nWe claim that if $\\sigexp$ elaborates in $\\B$ to some structure covered\nby $\\B$, then it possesses a principal signature in $\\B$.\n\nAnalogous to the definition given for type environments in\nSection~\\ref{typeenv-wf-sec}, we say that a semantic object $A$\n{\\sl respects equality} if every type environment occurring in \n$A$ respects equality. \n%\n%\n%Further, let $T$ be the set of type names\n%$\\t$ such that $(\\t,\\CE)$ occurs in $A$ for some\n%$\\CE\\neq\\emptymap$.  Then $A$ is said to {\\sl maximise equality}\n%if (a) $A$ respects equality, and also (b) if any larger subset of\n%$T$ were to admit equality (without any change in the equality\n%attribute of any type names not in $T$) then $A$ would cease to\n%respect equality.\n%\n\\oldpagebreak\nNow\\index{38.5} let us assume that $\\sigexp$ possesses a principal signature\n$\\sig_0=\\longsig{0}$ in $B$. We wish to\ndefine, in terms of $\\sig_0$, another signature $\\sig$ which provides more\ninformation about the equality attributes of structures which will\nmatch $\\sig_0$. To this end, let $\\T_0$ be the set of type names $\\t\\in\\N_0$\nwhich do not admit equality, and such that $(\\t,\\CE)$ occurs in $\\S_0$\nfor some $\\CE\\neq\\emptymap$.  Then we say $\\sig$ is \n{\\sl equality-principal for $\\sigexp$ in $\\B$} if\n\\begin{enumerate}\n\\item\n$\\sig$ respects equality\n\\item\n$\\sig$ is obtained from $\\sig_0$ just by making as many\nmembers of $\\T_0$ admit equality as possible, subject to 1.~above\n\\end{enumerate}\nIt is easy to show that, if any such $\\sig$ exists, it is determined\nuniquely by $\\sig_0$; moreover, $\\sig$ exists if $\\sig_0$ itself\nrespects equality.\n\\bigskip}\n\n\n%\n%\\clearpage\n\n%                   Inference Rules\n%\n\\subsection{Inference Rules}\n\\label{statmod-rules-sec}\nAs\\index{39.1} for the Core, the rules of the Modules static semantics allow\nsentences of the form\n\\[ A\\ts\\phrase\\ra A'\\]\nto be inferred, where in this case $A$ is either a basis, a context or\nan environment and $A'$ is a semantic object.  The convention for options\nis as in the Core semantics. \n\nAlthough not assumed in our definitions, it is intended that every basis\n\\replacement{\\thenostrsharing}{$\\B=\\N,\\F,\\G,\\E$}{$\\B=\\T,\\F,\\G,\\E$} in which a $\\topdec$ is elaborated has the property\nthat \n\\replacement{\\thenostrsharing}{$\\NamesFcn\\F\\ \\cup\\NamesFcn\\G\\cup\\NamesFcn\\E\\subseteq\\N$}{$\\TyNamesFcn\\F\n\\ \\cup\\TyNamesFcn\\G\\cup\\TyNamesFcn\\E\\subseteq\\T$}. \n\\replacement{\\thenostrsharing}{\nThis is not\nthe case for bases in which signature expressions and specifications are\nelaborated, but the following Theorem can be proved:}{\nThe following Theorem can be proved:}\n\\begin{quote}\nLet S be an inferred sentence $\\B\\ts\\topdec\\ra\\B'$ in which $\\B$ satisfies\nthe above condition. Then $\\B'$ also satisfies the condition.\n\n\\replacement{\\thenostrsharing}{\nMoreover, if S$'$ is a sentence of the form\n$\\B''\\ts\\phrase\\ra A$ occurring in a proof of S, where $\\phrase$ is\neither a structure expression or a structure-level declaration, then $\\B''$\nalso satisfies the condition.}{\nMoreover, if S$'$ is a sentence of the form\n$\\B''\\ts\\phrase\\ra A$ occurring in a proof of S, where $\\phrase$ is\nany Modules phrase, then $\\B''$ also satisfies the condition.}\n\n\\replacement{\\thenostrsharing}{Finally, if $\\T,\\U,\\E\\ts\\phrase\\ra A$ occurs\nin a proof of S, where $\\phrase$ is a phrase of the Core, then\n$\\TyNamesFcn\\E\\subseteq\\T$.}{Finally, if $\\T,\\U,\\E\\ts\\phrase\\ra A$ occurs\nin a proof of S, where $\\phrase$ is a phrase of Modules or of the Core, then\n$\\TyNamesFcn\\E\\subseteq\\T$.}\n\\end{quote}\n\n\n\n%               SEMANTICS\n%\n%                       Structure Expressions\n%\n\\replacement{\\thenostrsharing}{\n\\rulesec{Structure Expressions}{\\B\\ts\\strexp\\ra \\S}}\n{\\rulesec{Structure Expressions}{\\B\\ts\\strexp\\ra \\E}}\n\\replacement{\\thenostrsharing}{\\begin{equation}        % generative strexp\n\\label{generative-strexp-rule}\n\\frac{\\B\\ts\\strdec\\ra\\E\\qquad\\m\\notin(\\of{\\N}{\\B})\\cup\\NamesFcn\\E}\n     {\\B\\ts\\encstrexp\\ra(\\m,\\E)}\\index{39.2}\n\\end{equation}}{\\begin{equation}        % generative strexp\n\\label{generative-strexp-rule}\n\\frac{\\B\\ts\\strdec\\ra\\E}\n     {\\B\\ts\\encstrexp\\ra \\E }\\index{39.2}\n\\end{equation}}\n\\replacement{\\thenostrsharing}{\n\\begin{equation}        % longstrid\n%\\label{longstrid-strexp-rule}\n\\frac{\\B(\\longstrid)=\\S}\n     {\\B\\ts\\longstrid\\ra\\S}\n\\end{equation}}{\\begin{equation}        % longstrid\n%\\label{longstrid-strexp-rule}\n\\frac{\\B(\\longstrid)=\\E}\n     {\\B\\ts\\longstrid\\ra\\E}\n\\end{equation}}\n\n\\insertion{\\thenostrsharing}{\n\\begin{equation}\n\\label{transparent-constraint-rule}\n\\frac{B\\ts\\strexp\\ra\\E\\quad\\B\\ts\\sigexp\\ra\\Sigma\\quad\\Sigma\\geq\\E'\\prec\\E}\n     {\\B\\ts\\transpconstraint\\ra\\E'}\n\\end{equation}\n}\n\n\\insertion{\\thenostrsharing}{\n\\begin{equation}\n\\label{opaque-constraint-rule}\n\\frac{\\begin{array}{c}\n   B\\ts\\strexp\\ra\\E\\quad\\B\\ts\\sigexp\\ra(\\T')\\E'\\\\\n   (\\T')\\E'\\geq\\E''\\prec\\E\\quad \\T' \\cap(\\of{\\T}{\\B}) = \\emptyset\n      \\end{array}}\n     {\\B\\ts\\opaqueconstraint\\ra\\E'}\n\\end{equation}\n}\n\n\\vspace{6pt}\n\\replacement{\\thenostrsharing}{\n\\begin{equation}                % functor application\n\\label{functor-application-rule}\n\\frac{ \\begin{array}{c}\n        \\B\\ts\\strexp\\ra\\S\\\\\n        \\funsiginst{\\B(\\funid)}{}{(\\S'',(\\N')\\S')}\\ ,\n                                                    \\ \\S\\succ\\S''\\\\\n        (\\of{\\N}{\\B})\\cap\\N'=\\emptyset\n       \\end{array}\n     }\n     {\\B\\ts\\funappstr\\ra\\S'}\n\\end{equation}}{\\begin{equation}                % functor application\n\\label{functor-application-rule}\n\\frac{ \\begin{array}{c}\n        \\B\\ts\\strexp\\ra\\E\\\\\n        \\funsiginst{\\B(\\funid)}{}{(\\E'',(\\T')\\E')}\\ ,\n                                                    \\ \\E\\succ\\E''\\\\\n        (\\TyNamesFcn \\E\\; \\cup\\; \\of{\\T}{\\B})\\cap\\T'=\\emptyset\n       \\end{array}\n     }\n     {\\B\\ts\\funappstr\\ra\\E'}\n\\end{equation}}\n\n\\vspace{6pt}\n\\replacement{\\thenostrsharing}{\n\\begin{equation}        % let strexp\n\\label{letstrexp-rule}\n\\frac{\\B\\ts\\strdec\\ra\\E\\qquad\\B\\oplus\\E\\ts\\strexp\\ra\\S}\n     {\\B\\ts\\letstrexp\\ra\\S}\n\\end{equation}}{\\begin{equation}        % let strexp\n\\label{letstrexp-rule}\n\\frac{\\B\\ts\\strdec\\ra\\E_1\\qquad\\B\\oplus\\E_1\\ts\\strexp\\ra\\E_2}\n     {\\B\\ts\\letstrexp\\ra\\E_2}\n\\end{equation}}\n\\comments\n\\begin{description}\n\\deletion{\\thenostrsharing}{\n\\item{(\\ref{generative-strexp-rule})}\n   The side condition ensures that each generative structure\nexpression receives a new name. If the expression occurs in\na functor body the structure name will be bound by $(\\N')$ in\nrule~\\ref{funbind-rule}; this will ensure that for each application of the \nfunctor, by rule~\\ref{functor-application-rule}, a new distinct name\nwill be chosen for the structure generated.}\n%\n\\oldpagebreak\n\\item{(\\ref{functor-application-rule})}\n   The side condition \n\\replacement{\\thenostrsharing}{$ (\\of{\\N}{\\B})\\cap\\N'=\\emptyset$}{$(\\TyNamesFcn\\E \\cup \\of{\\T}{\\B})\\cap\\T'=\\emptyset$}\n  can always\nbe satisfied by renaming bound names in \\replacement{\\thenostrsharing}{$(\\N')S'$}{$(\\T')E'$}; it ensures that the\ngenerated \\replacement{\\thenostrsharing}{structures}{datatypes} receive new names.\\index{40.1}\n\n\\replacement{\\thenostrsharing}{Let $\\B(\\funid)=(N)(\\S_f,(N')\\S_f')$.}{Let $\\B(\\funid)=(\\T)(\\E_f,(T')\\E_f')$.} \n\\replacement{\\thenotypexplication}{Assuming that $(\\N)\\S_f$ is\ntype-explicit, the realisation $\\rea$ for which\n$\\rea(\\S_f,(N')\\S_f')=(\\S'',(\\N')\\S')$ is uniquely determined by $\\S$,\nsince $\\S\\succ\\S''$ can only hold if the type names and structure\nnames in $\\S$ and $\\S''$ agree.  Recall that enrichment $\\succ$ allows\nmore components and more polymorphism, while instantiation $\\geq$ does\nnot.\\par}{Let $\\rea$ be a realisation such that\\linebreak\n$\\rea(\\E_f,(T')\\E_f')=(\\E'',(\\T')\\E')$.}\n\\replacement{\\thenostrsharing}{\nSharing between argument and result specified in the declaration of\nthe functor $\\funid$ is represented by the occurrence of the same name\nin both $\\S_f$ and $\\S_f'$, and this repeated occurrence is preserved\nby $\\rea$, yielding sharing between the argument structure $\\S$ and\nthe result structure $\\S'$ of this functor application.}{\nSharing between argument and result specified in the declaration of\nthe functor $\\funid$ is represented by the occurrence of the same name\nin both $\\E_f$ and $\\E_f'$, and this repeated occurrence is preserved\nby $\\rea$, yielding sharing between the argument structure $\\E$ and\nthe result structure $\\E'$ of this functor application.}\n%\n\\item{(\\ref{letstrexp-rule})}\n   The use of $\\oplus$, here and elsewhere, ensures that \\deletion{\\thenostrsharing}{structure\nand }type names generated by\nthe first sub-phrase\nare distinct from names generated by the second\nsub-phrase.\n\\end{description}\n\n%                              declarations\n\\rulesec{Structure-level Declarations}{\\B\\ts\\strdec\\ra\\E}               \n\\replacement{\\thenostrsharing}{\n\\begin{equation}                % core declaration\n\\label{dec-rule}\n\\frac{ \\of{\\C}{\\B}\\ts\\dec\\ra\\E\n       \\quad\\E\\ {\\rm principal\\ for\\ \\dec\\ in\\ } (\\of{\\C}{\\B})\n}\n     { \\B\\ts\\dec\\ra\\E }\\index{40.2}\n\\end{equation}}{\\begin{equation}                % core declaration\n\\label{dec-rule}\n\\frac{ \\of{\\C}{\\B}\\ts\\dec\\ra\\E\n}\n     { \\B\\ts\\dec\\ra\\E }\\index{40.2}\n\\end{equation}}\n\n\\vspace{6pt}\n\\begin{equation}                % structure declaration\n%\\label{structure-decl-rule}\n\\frac{ \\B\\ts\\strbind\\ra\\SE }\n     { \\B\\ts\\singstrdec\\ra\\SE\\ \\In\\ \\Env }\n\\end{equation}\n\n\\vspace{6pt}\n\\begin{equation}                % local structure-level declaration\n%\\label{local structure-level declaration}\n\\frac{ \\B\\ts\\strdec_1\\ra\\E_1\\qquad\n       \\B\\oplus\\E_1\\ts\\strdec_2\\ra\\E_2 }\n     { \\B\\ts\\localstrdec\\ra\\E_2 }\n\\end{equation}\n\n\\vspace{6pt}\n\\begin{equation}                % empty declaration\n%\\label{empty-strdec-rule}\n\\frac{}\n     {\\B\\ts\\emptystrdec\\ra \\emptymap{\\rm\\ in}\\ \\Env}\n\\end{equation}\n\n\\vspace{6pt}\n\\begin{equation}                % sequential declaration\n%\\label{sequential-strdec-rule}\n\\frac{ \\B\\ts\\strdec_1\\ra\\E_1\\qquad\n       \\B\\oplus\\E_1\\ts\\strdec_2\\ra\\E_2 }\n     { \\B\\ts\\seqstrdec\\ra\\plusmap{\\E_1}{\\E_2} }\n\\end{equation}\n\\deletion{\\thenostrsharing}{\n\\comments\n\\begin{description}\n\\item{(\\ref{dec-rule})}\nThe side condition ensures that all type schemes in $\\E$ are as\ngeneral as possible.\n% and that no imperative type variables occur\n%free in $\\E$.\n%from version 1:\n%   The side condition ensures that all type schemes in $\\E$ are as\n%general as possible and that all new type names in $\\E$ admit\n%equality, if possible.\n\\end{description}}\n\\oldpagebreak\n\\rulesec{Structure Bindings}{\\B\\ts\\strbind\\ra\\SE}\n\\replacement{\\thenostrsharing}{\n\\begin{equation}                % structure binding\n\\label{structure-binding-rule}\n\\frac{ \\begin{array}{cl}\n       \\B\\ts\\strexp\\ra\\S\\qquad\\langle\\B\\ts\\sigexp\\ra\\sig\\ ,\n                                      \\ \\sig\\geq\\S'\\prec\\S\\rangle\\\\\n       \\langle\\langle\\plusmap{\\B}{\\TyNamesFcn\\S}\\ts\n                                      \\strbind\\ra\\SE\\rangle\\rangle\n       \\end{array}\n     }\n     { \\B\\ts\\strbinder\\ra\\{\\strid\\mapsto\\S\\langle'\\rangle\\}\n       \\ \\langle\\langle +\\ \\SE\\rangle\\rangle }\\index{41.1}\n\\end{equation}}{\\begin{equation}                % structure binding\n\\label{structure-binding-rule}\n\\frac{ \n       \\B\\ts\\strexp\\ra\\E\\quad\n       \\langle\\plusmap{\\B}{\\TyNamesFcn\\E}\\ts\n                                      \\strbind\\ra\\SE\\rangle\n     }\n     { \\B\\ts\\barestrbindera\\ra\\{\\strid\\mapsto\\E\\}\n       \\ \\langle +\\ \\SE\\rangle}\\index{41.1}\n\\end{equation}}\n\\deletion{\\thenostrsharing}{ \n\\comment If present, $\\sigexp$ has the effect of restricting the\nview which $\\strid$ provides of $\\S$ while retaining sharing of names.\nThe notation $\\S\\langle'\\rangle$ means $\\S'$, if the first option is present,\nand $\\S$ if not.}\n%\n%                   Signature Rules\n%\n\\replacement{\\thenostrsharing}{\n\\rulesec{Signature Expressions}{\\B\\ts\\sigexp\\ra\\S}\n\\begin{equation}                % encapsulation sigexp\n\\label{encapsulating-sigexp-rule}\n\\frac{\\B\\ts\\spec\\ra\\E }\n     {\\B\\ts\\encsigexp\\ra  (\\m,\\E) }\\index{41.2}\n\\end{equation}}{\\rulesec{Signature Expressions}{\\B\\ts\\sigexp\\ra\\E}\n\\begin{equation}                % encapsulation sigexp\n\\label{encapsulating-sigexp-rule}\n\\frac{\\B\\ts\\spec\\ra\\E }\n     {\\B\\ts\\encsigexp\\ra  \\E }\\index{41.2}\n\\end{equation}}\n\n\\replacement{\\thenostrsharing}{\\begin{equation}                % signature identifier\n\\label{signature-identifier-rule}\n\\frac{ \\sigord{\\B(\\sigid)}{}{\\S} }\n     { \\B\\ts\\sigid\\ra\\S }\n\\end{equation}}{\\begin{equation}                % signature identifier\n\\label{signature-identifier-rule}\n\\frac{  \\B(\\sigid) = (\\T)\\E \\quad \\T\\cap (\\of{\\T}{\\B}) = \\emptyset}\n     { \\B\\ts\\sigid\\ra\\E }\n\\end{equation}}\n\\insertion{\\thenostrsharing}{\n\\begin{equation}\n\\label{wheretype-rule}\n\\frac{\n  \\begin{array}{c}\n     \\B\\ts\\sigexp\\ra \\E\\quad \\tyvarseq = \\alphak\\quad \\of{\\C}{\\B}\\ts\\ty\\ra \\tau\\\\\n     \\E(\\longtycon) = (\\t, \\VE)\\quad t\\notin\\of{\\T}{\\B}\\\\\n     \\rea = \\{\\t\\mapsto \\Lambda\\alphak.\\tau\\}\\quad\n     \\hbox{$\\Lambda\\alphak.\\tau$ admits equality, if $\\t$ does\\quad $\\rea(\\E)$ well-formed}\n  \\end{array}\n }\n {\\B\\ts\\wheretypesigexp\\ra\\rea(\\E)}\n\\end{equation}}\n\\comments\n\\begin{description}\n\\deletion{\\thenostrsharing}{\n\\item{(\\ref{encapsulating-sigexp-rule})}\n   In contrast to rule~\\ref{generative-strexp-rule}, $m$ is not here \nrequired to be new. \nThe name $m$ may be chosen to achieve the sharing required\nin rule~\\ref{strshareq-rule}, or to achieve the enrichment side conditions\nof rule~\\ref{structure-binding-rule} or \\ref{funbind-rule}. \nThe choice of $m$ must result in an admissible object.}\n\\item{(\\ref{signature-identifier-rule})}\n   \\replacement{\\thenostrsharing}{The instance $\\S$ of $\\B(\\sigid)$ is not determined by this rule,\nbut -- as in rule~\\ref{encapsulating-sigexp-rule} -- the instance\nmay  be chosen to achieve sharing properties or enrichment\nconditions.}{The bound names of $\\B(\\sigid)$ can always be renamed to satisfy $\\T\\cap(\\of{\\T}{\\B}) = \\emptyset$,\nif necessary.}\n\\end{description}\n\n\\rulesec{}{\\B\\ts\\sigexp\\ra\\sig}\n\\replacement{\\thenostrsharing}{\\begin{equation}                % any sigexp\n\\label{topmost-sigexp-rule}\n\\frac{\\begin{array}{c}\n\\B\\ts\\sigexp\\ra\\S\\quad\\mbox{$(\\N)\\S$ equality-principal for $\\sigexp$ in $\\B$}\\\\\n\\mbox{$(\\N)\\S$ type-explicit}\n      \\end{array}}\n     {\\B\\ts\\sigexp\\ra (\\N)\\S}\\index{41.25}\n\\end{equation}}{\\begin{equation}                % any sigexp\n\\label{topmost-sigexp-rule}\n\\frac{\n\\B\\ts\\sigexp\\ra\\E\\quad\\T= \\TyNamesFcn\\E\\setminus(\\of{\\T}{\\B})\n}\n     {\\B\\ts\\sigexp\\ra (\\T)\\E}\\index{41.25}\n\\end{equation}}\\noindent\\comment\nA signature expression $\\sigexp$ which is an immediate constituent of\n\\deletion{\\thenostrsharing}{a structure binding, } a signature binding\\replacement{\\thenostrsharing}{, a \nfunctor binding or a\nfunctor signature}{, a signature constraint, or a\nfunctor binding }is elaborated to \\replacement{\\thenostrsharing}{an equality-principal and type-explicit }{a }signature,\n see rules~\\replacement{\\thenostrsharing}{\\ref{structure-binding-rule}, }{\n\\ref{transparent-constraint-rule}, \\ref{opaque-constraint-rule}, }\\ref{sigbind-rule}\\deletion{\\thenostrsharing}{, \n\\ref{funsigexp-rule}} and \\ref{funbind-rule}.  \\deletion{\\thenostrsharing}{By contrast, signature \nexpressions occurring in structure descriptions are elaborated to\nstructures using the liberal rules\n\\ref{encapsulating-sigexp-rule} and \\ref{signature-identifier-rule}, \nsee rule~\\ref{strdesc-rule}, so that names can be chosen to achieve\nsharing, when necessary.}\n\\oldpagebreak\n\n\\rulesec{Signature Declarations}{\\B\\ts\\sigdec\\ra\\G}\n\\begin{equation}        % single signature declaration\n\\label{single-sigdec-rule}\n\\frac{ \\B\\ts\\sigbind\\ra\\G }\n     { \\B\\ts\\singsigdec\\ra\\G }\\index{41.3}\n\\end{equation}\n\\deletion{\\thenostrsharing}{\n\\begin{equation}        % empty signature declaration\n%\\label{empty-sigdec-rule}\n\\frac{}\n     { \\B\\ts\\emptysigdec\\ra\\emptymap }\n\\end{equation}\n\n\\begin{equation}        % sequential signature declaration\n\\label{sequence-sigdec-rule}\n\\frac{ \\B\\ts\\sigdec_1\\ra\\G_1 \\qquad \\plusmap{\\B}{\\G_1}\\ts\\sigdec_2\\ra\\G_2 }\n     { \\B\\ts\\seqsigdec\\ra\\plusmap{\\G_1}{\\G_2} }\n\\end{equation}}\n\\deletion{\\thenostrsharing}{\\comments\n\\begin{description}\n%\n\\item{(\\ref{single-sigdec-rule})}\nThe first closure restriction of Section~\\ref{closure-restr-sec}\ncan be  enforced by replacing the $\\B$ in the premise by $\\B_0+\\of{\\G}{\\B}$.\n\\item{(\\ref{sequence-sigdec-rule})}\n   A signature declaration does not create any new structures\nor types; hence the use of $+$ instead of $\\oplus$.\n\\end{description}\n}\n\n\\rulesec{Signature Bindings}{\\B\\ts\\sigbind\\ra\\G}\n\\begin{equation}        % signature binding\n\\label{sigbind-rule}\n\\frac{ \\B\\ts\\sigexp\\ra\\sig\n        \\qquad\\langle\\B\\ts\\sigbind\\ra\\G\\rangle }\n     { \\B\\ts\\sigbinder\\ra\\{\\sigid\\mapsto\\sig\\}\n       \\ \\langle +\\ \\G\\rangle }\\index{42.1}\n\\end{equation}\n\\deletion{\\thenostrsharing}{\\comment The  condition that $\\sig$ be equality-principal,\nimplicit in the first premise, ensures that the\nsignature found is as general as possible given the sharing\nconstraints present in $\\sigexp$.}\n%\n                     % Specifications\n\\rulesec{Specifications}{\\B\\ts\\spec\\ra\\E}\n\\begin{equation}        % value specification\n\\label{valspec-rule}\n\\frac{ \\of{\\C}{\\B}\\ts\\valdesc\\ra\\VE }\n     { \\B\\ts\\valspec\\ra\\cl{}{\\VE}\\ \\In\\ \\Env }\\index{42.2}\n\\end{equation}\n\n\\replacement{\\thenostrsharing}{\n\\begin{equation}        % type specification\n\\label{typespec-rule}\n\\frac{ \\of{\\C}{\\B}\\ts\\typdesc\\ra\\TE }\n     { \\B\\ts\\typespec\\ra\\TE\\ \\In\\ \\Env }\n\\end{equation}}{\\begin{equation}        % type specification\n\\label{typespec-rule}\n\\frac{ \n         \\of{\\C}{\\B}\\ts\\typdesc\\ra\\TE \\quad\n         \\forall(\\t,\\VE)\\in\\Ran\\TE,\\hbox{\\ $t$ does not admit equality}\n     }\n     { \\B\\ts\\typespec\\ra\\TE\\ \\In\\ \\Env }\n\\end{equation}}\n\n\\replacement{\\thenostrsharing}{\n\\begin{equation}        % eqtype specification\n\\label{eqtypspec-rule}\n\\frac{ \\of{\\C}{\\B}\\ts\\typdesc\\ra\\TE \\qquad\n       \\forall(\\theta,\\CE)\\in \\Ran\\TE,\\ \\theta {\\rm\\ admits\\ equality} }\n     { \\B\\ts\\eqtypespec\\ra\\TE\\ \\In\\ \\Env }\n\\end{equation}}{\\begin{equation}        % eqtype specification\n\\label{eqtypspec-rule}\n\\frac{ \\of{\\C}{\\B}\\ts\\typdesc\\ra\\TE \\qquad\n       \\forall(\\t,\\VE)\\in \\Ran\\TE,\\ \\t {\\rm\\ admits\\ equality} }\n     { \\B\\ts\\eqtypespec\\ra\\TE\\ \\In\\ \\Env }\n\\end{equation}}\n\n\\replacement{\\thenostrsharing}{\n\\begin{equation}        % data specification\n\\label{datatypespec-rule}\n\\frac{ \\plusmap{\\of{\\C}{\\B}}{\\TE}\\ts\\datdesc\\ra\\VE,\\TE }\n     { \\B\\ts\\datatypespec\\ra(\\VE,\\TE)\\ \\In\\ \\Env }\n\\end{equation}}{\n\\begin{equation}        % data specification\n\\label{datatypespec-rule}\n\\frac{ \\begin{array}{c}\n       \\of{\\C}{\\B}\\oplus\\TE\\ts\\datdesc\\ra\\VE,\\TE \n       \\quad \\forall(\\t,\\VE')\\in\\Ran\\TE, \\t\\notin\\of{\\T}{\\B}\\\\\n       \\hbox{$\\TE$ maximises equality}\n       \\end{array}}\n     { \\B\\ts\\datatypespec\\ra(\\VE,\\TE)\\ \\In\\ \\Env }\n\\end{equation}}\n\n\\insertion{\\thedatatyperepl}{\\begin{equation}\n\\label{datatypereplspec-rule}\n\\frac{ \\B(\\longtycon) = (\\typefcn,\\VE)\\qquad\n       \\TE = \\{\\tycon\\mapsto(\\typefcn,\\VE)\\}\n     }\n     {\\B\\ts\\datatypereplspec\\ra (\\VE,\\TE)\\ \\In\\ \\Env}\n\\end{equation}}\n\n\\replacement{\\theidstatus}{\n\\begin{equation}        % exception specification\n\\label{exceptionspec-rule}\n\\frac{ \\of{\\C}{\\B}\\ts\\exndesc\\ra\\EE\\quad\\VE=\\EE }\n     { \\B\\ts\\exceptionspec\\ra(\\VE,\\EE)\\ \\In\\ \\Env }\n\\end{equation}}{\\begin{equation}        % exception specification\n\\label{exceptionspec-rule}\n\\frac{ \\of{\\C}{\\B}\\ts\\exndesc\\ra\\VE }\n     { \\B\\ts\\exceptionspec\\ra\\VE\\ \\In\\ \\Env }\n\\end{equation}}\n\n\\begin{equation}        % structure specification\n%\\label{structurespec-rule}\n\\frac{ \\B\\ts\\strdesc\\ra\\SE }\n     { \\B\\ts\\structurespec\\ra\\SE\\ \\In\\ \\Env }\n\\end{equation}\n\\oldpagebreak\n\n\\deletion{\\thetypabbr}{\n\\begin{equation}        % sharing specification\n%\\label{sharingspec-rule}\n\\frac{ \\B\\ts\\shareq\\ra\\emptymap }\n     { \\B\\ts\\sharingspec\\ra\\emptymap\\ \\In\\ \\Env }\\index{42.3}\n\\end{equation}}\n\n\\deletion{\\thenolocalspec}{\\begin{equation}        % local specification\n%\\label{localspec-rule}\n\\frac{ \\B\\ts\\spec_1\\ra\\E_1 \\qquad \\plusmap{\\B}{\\E_1}\\ts\\spec_2\\ra\\E_2 }\n     { \\B\\ts\\localspec\\ra\\E_2 }\n\\end{equation}}\n\n\\deletion{\\thenoopenspec}{\\begin{equation}        % open specification\n%\\label{openspec-rule}\n\\frac{ \\B(\\longstrid_1)=(\\m_1,\\E_1)\\quad\\cdots\\quad\n       \\B(\\longstrid_n)=(\\m_n,\\E_n) }\n     { \\B\\ts\\openspec\\ra\\E_1 + \\cdots +\\E_n }\n\\end{equation}}\n\n\\replacement{\\thesingleincludespec}{\\begin{equation}        % include signature specification\n\\label{inclspec-rule}\n\\frac{ \\sigord{\\B(\\sigid_1)}{}{(\\m_1,\\E_1)} \\quad\\cdots\\quad\n       \\sigord{\\B(\\sigid_n)}{}{(\\m_n,\\E_n)} }\n     { \\B\\ts\\inclspec\\ra\\E_1 + \\cdots +\\E_n }\n\\end{equation}}{\\begin{equation}        % include signature specification\n\\label{inclspec-rule}\n\\frac{  \\B\\ts\\sigexp\\ra\\E}\n     { \\B\\ts\\singleinclspec\\ra\\E }\n\\end{equation}}\n\n\\begin{equation}        % empty specification\n%\\label{emptyspec-rule}\n\\frac{}\n     { \\B\\ts\\emptyspec\\ra\\emptymap{\\rm\\ in}\\ \\Env }\n\\end{equation}\n\n\\replacement{\\thenostrsharing}{\n\\begin{equation}        % sequential specification\n%\\label{seqspec-rule}\n\\frac{ \\B\\ts\\spec_1\\ra\\E_1 \\qquad \\plusmap{\\B}{\\E_1}\\ts\\spec_2\\ra\\E_2 }\n     { \\B\\ts\\seqspec\\ra\\plusmap{\\E_1}{\\E_2} }\n\\end{equation}}{\\begin{equation}        % sequential specification\n\\label{seqspec-rule}\n\\frac{ \\B\\ts\\spec_1\\ra\\E_1 \\qquad \\B\\oplus\\E_1\\ts\\spec_2\\ra\\E_2\\qquad\\Dom(\\E_1)\\cap\\Dom(\\E_2) = \\emptyset }\n     { \\B\\ts\\seqspec\\ra\\plusmap{\\E_1}{\\E_2} }\n\\end{equation}}\n\\insertion{\\thetypabbr}{\n\\begin{equation}\n\\label{sharspec-rule}\n\\frac{\\begin{array}{c}\n        \\B\\ts \\spec \\ra \\E\\quad \\E(\\longtycon_i) = (\\t_i,\\VE_i), \\;i = 1..n\\\\\n        t\\in\\{\\t_1,\\ldots,\\t_n\\}\\quad\\hbox{$\\t$ admits equality, if some $\\t_i$ does}\\\\\n        \\{\\t_1,\\ldots,\\t_n\\}\\cap\\of{\\T}{\\B} = \\emptyset\\quad\n           \\rea = \\{\\t_1\\mapsto\\t,\\ldots,\\t_n\\mapsto \\t\\}\n      \\end{array}\n     }\n     {\\B\\ts \\newsharingspec\\ra \\rea(\\E)}\n\\end{equation}}\n\n\\comments\n\\begin{description}\n\\item{(\\ref{valspec-rule})}\n   $\\VE$ is determined by $\\B$ and $\\valdesc$.\n\\item{(\\ref{typespec-rule})--(\\ref{datatypespec-rule})}\n   \\replacement{\\thenostrsharing}{The type functions in $\\TE$ may be chosen to achieve the sharing hypothesis\nof rule~\\ref{typshareq-rule} or the enrichment conditions of \nrules~\\ref{structure-binding-rule} and~\\ref{funbind-rule}. In particular, the type\nnames in $\\TE$ in rule~\\ref{datatypespec-rule} need not be new.\nAlso, in rule~\\ref{typespec-rule} the type functions in $\\TE$ may admit\nequality.}{The type\nnames in $\\TE$ are new.}\n%\n\\item{(\\ref{exceptionspec-rule})}\n   \\replacement{\\theidstatus}{$\\EE$}{$\\VE$} is determined by $\\B$ and $\\exndesc$ and contains monotypes only.\n\\deletion{\\thenostrsharing}{\\item{(\\ref{inclspec-rule})}\n   The names $\\m_i$ in the instances may be chosen to achieve sharing or\nenrichment conditions.\\index{43.0}}\n\\insertion{\\thenostrsharing}{\\item{(\\ref{seqspec-rule})}\n   Note that no sequential specification is allowed to specify the\n   same identifier twice.}\n\\end{description} \n\n                  % Descriptions\n\\rulesec{Value Descriptions}{\\C\\ts\\valdesc\\ra\\VE}\n\\replacement{\\theidstatus}{\n\\begin{equation}         % value description\n%\\label{valdesc-rule}\n\\frac{ \\C\\ts\\ty\\ra\\tau\\qquad\n       \\langle\\C\\ts\\valdesc\\ra\\VE\\rangle }\n     { \\C\\ts\\valdescription\\ra\\{\\var\\mapsto\\tau\\}\n       \\ \\langle +\\ \\VE\\rangle }\\index{43.1}\n\\end{equation}}{\\begin{equation}         % value description\n%\\label{valdesc-rule}\n\\frac{ \\C\\ts\\ty\\ra\\tau\\qquad\n       \\langle\\C\\ts\\valdesc\\ra\\VE\\rangle }\n     { \\C\\ts\\valviddescription\\ra\\{\\vid\\mapsto(\\tau,\\isv)\\}\n       \\ \\langle +\\ \\VE\\rangle }\\index{43.1}\n\\end{equation}}\n\n\\rulesec{Type Descriptions}{\\C\\ts\\typdesc\\ra\\TE}\n\\replacement{\\thenostrsharing}{\n\\begin{equation}         % type description\n\\label{typdesc-rule}\n\\frac{ \\tyvarseq = \\alphak\n       \\qquad\\langle \\C\\ts\\typdesc\\ra\\TE\\rangle\\qquad\\arity\\theta=k }\n     { \\C\\ts\\typdescription\\ra\\{\\tycon\\mapsto(\\theta,\\emptymap)\\}\n       \\ \\langle +\\ \\TE\\rangle }\\index{43.2}\n\\end{equation}}{\\begin{equation}         % type description\n\\label{typdesc-rule}\n\\frac{ \\begin{array}{c}\n         \\tyvarseq = \\alphak\\quad\\t\\notin\\of{\\T}{\\C}\\quad\\arity\\t=k \\\\\n       \\langle \\C\\ts\\typdesc\\ra\\TE\\qquad\\t\\notin\\TyNamesFcn\\TE\\rangle\n      \\end{array}}\n     { \\C\\ts\\typdescription\\ra\\{\\tycon\\mapsto(\\t,\\emptymap)\\}\n       \\ \\langle +\\ \\TE\\rangle }\\index{43.2}\n\\end{equation}}\n\\comment Note that \\deletion{\\thenostrsharing}{any $\\theta$ of arity $k$ may be chosen but that}\nthe \\replacement{\\thece}{constructor}{value} environment in the resulting type structure must be\nempty. \\replacement{\\thefixtypos}{For example, \\mbox{\\ml{datatype s=c type t sharing s=t}}\\  }{For example, \\mbox{\\ml{datatype s=C type t}} \\mbox{\\ml{sharing type t=s}}\\  }\nis a legal specification, but the type structure bound to \\ml{t}\ndoes not bind any value constructors.\n\\oldpagebreak\n\n\\rulesec{Datatype Descriptions}{\\C\\ts\\datdesc\\ra\\VE,\\TE}\n\\replacement{\\thenostrsharing}{\\begin{equation}         % datatype description\n\\label{datdesc-rule}\n\\frac{ \\tyvarseq = \\alphak\\qquad\\C,\\alphakt\\ts\\condesc\\ra\\CE\n       \\qquad\\langle\\C\\ts\\datdesc\\ra\\VE,\\TE\\rangle }\n     { \\begin{array}{cl}\n       \\C\\ts\\datdescription\\ra\\\\\n       \\qquad\\qquad\\cl{}{\\CE}\\langle +\\ \\VE\\rangle,\\\n       \\{\\tycon\\mapsto(t,\\cl{}{\\CE})\\}\\ \\langle +\\ \\TE\\rangle\n       \\end{array}\n     }\\index{43.3}\n\\end{equation}}{\\begin{equation}         % datatype description\n\\label{datdesc-rule}\n\\frac{ \\begin{array}{c}\n        \\tyvarseq = \\alphak\\qquad\\C,\\alphakt\\ts\\condesc\\ra\\VE\n           \\quad\\arity \\t  =  k\\\\\n        \\langle\\C\\ts\\datdesc'\\ra\\VE',\\TE'\\qquad \\forall(\\t',\\VE'')\\in\\Ran\\TE',\\,\\t\\neq\\t'\\rangle \n       \\end{array}}\n     { \\begin{array}{l}\n       \\C\\ts\\newdatdescription\\ra\\\\\n       \\qquad\\cl{}{\\VE} \\langle +\\ \\VE'\\rangle,\\\n       \\{\\tycon\\mapsto(t,\\cl{}{\\VE})\\}\\ \\langle +\\ \\TE'\\rangle\n       \\end{array}\n     }\\index{43.3}\n\\end{equation}}\n\n\\replacement{\\thece}{\\rulesec{Constructor Descriptions}{\\C,\\tau\\ts\\condesc\\ra\\CE}}{\\rulesec{Constructor Descriptions}{\\C,\\tau\\ts\\condesc\\ra\\VE}}\n\\replacement{\\theidstatus}{\\begin{equation}         % constructor description\n%\\label{condesc-rule}\n\\frac{\\langle\\C\\ts\\ty\\ra\\tau'\\rangle\\qquad\n      \\langle\\langle\\C,\\tau\\ts\\condesc\\ra\\CE\\rangle\\rangle }\n     {\\begin{array}{l}\n      \\C,\\tau\\ts\\longcondescription\\ra\\\\\n      \\qquad\\{\\con\\mapsto\\tau\\}\\\n     \\langle +\\ \\{\\con\\mapsto\\tau'\\to\\tau\\}\\ \\rangle\\\n      \\langle\\langle +\\ \\CE\\rangle\\rangle\n      \\end{array}\n     }\\index{43.35}\n\\end{equation}}{\\begin{equation}         % constructor description\n%\\label{condesc-rule}\n\\frac{\\langle\\C\\ts\\ty\\ra\\tau'\\rangle\\qquad\n      \\langle\\langle\\C,\\tau\\ts\\condesc\\ra\\VE\\rangle\\rangle }\n     {\\begin{array}{l}\n      \\C,\\tau\\ts\\longconviddescription\\ra\\\\\n      \\qquad\\{\\vid\\mapsto(\\tau,\\isc)\\}\\\n     \\langle +\\ \\{\\vid\\mapsto(\\tau'\\to\\tau,\\isc)\\}\\ \\rangle\\\n      \\langle\\langle +\\ \\VE\\rangle\\rangle\n      \\end{array}\n     }\\index{43.35}\n\\end{equation}}\n\n\\replacement{\\theidstatus}{\n\\rulesec{Exception Descriptions}{\\C\\ts\\exndesc\\ra\\EE}}{\\rulesec{Exception \nDescriptions}{\\C\\ts\\exndesc\\ra\\VE}}\n\\replacement{\\theidstatus}{\n\\begin{equation}         % exception description\n\\label{exndesc-rule}\n\\frac{ \\langle\\C\\ts\\ty\\ra\\tau\\qquad\\TyVarsFcn(\\tau)=\\emptyset\\rangle\\qquad\n       \\langle\\langle\\C\\ts\\exndesc\\ra\\EE\\rangle\\rangle }\n     { \\begin{array}{l}\n        \\C\\ts\\exndescriptiona\\ra\\\\\n        \\quad\\quad\\{\\exn\\mapsto\\EXCN\\}\\ \\langle +\\ \\{\\exn\\mapsto\\tau\\rightarrow\\EXCN\\}\\rangle\\ \\langle\\langle +\\ \\EE\\rangle\\rangle \n       \\end{array}\n     }\\index{43.4}\n\\end{equation}}{\\begin{equation}         % exception description\n\\label{exndesc-rule}\n\\frac{ \\langle\\C\\ts\\ty\\ra\\tau\\qquad\\TyVarsFcn(\\tau)=\\emptyset\\rangle\\qquad\n       \\langle\\langle\\C\\ts\\exndesc\\ra\\VE\\rangle\\rangle }\n     { \\begin{array}{l}\n        \\C\\ts\\exnviddescriptiona\\ra\\\\\n        \\quad\\quad\\{\\vid\\mapsto(\\EXCN,\\ise)\\}\\ \\langle +\\ \\{\\vid\\mapsto(\\tau\\rightarrow\\EXCN,\\ise)\\}\\rangle\\ \\langle\\langle +\\ \\VE\\rangle\\rangle \n       \\end{array}\n     }\\index{43.4}\n\\end{equation}}\n\n\n\\rulesec{Structure Descriptions}{\\B\\ts\\strdesc\\ra\\SE}\n\\replacement{\\thenostrsharing}{\n\\begin{equation}\n\\label{strdesc-rule}\n\\frac{ \\B\\ts\\sigexp\\ra\\S\\qquad\\langle\\B\\ts\\strdesc\\ra\\SE\\rangle }\n     { \\B\\ts\\strdescription\\ra\\{\\strid\\mapsto\\S\\}\\ \\langle +\\ \\SE\\rangle }\\index{43.5}\n\\end{equation}}{\\begin{equation}\n\\label{strdesc-rule}\n\\frac{ \\B\\ts\\sigexp\\ra\\E\\qquad\\langle\\B + \\TyNamesFcn\\E\\ts\\strdesc\\ra\\SE\\rangle }\n     { \\B\\ts\\strdescription\\ra\\{\\strid\\mapsto\\E\\}\\ \\langle +\\ \\SE\\rangle }\\index{43.5}\n\\end{equation}}\n\n\n\\deletion{\\thenostrsharing}{\n\\rulesec{Sharing Equations}{\\B\\ts\\shareq\\ra\\emptymap}\n\\begin{equation}          % structure sharing equation\n\\label{strshareq-rule}\n\\frac{ \\of{\\m}{\\B(\\longstrid_1)}=\\cdots =\\of{\\m}{\\B(\\longstrid_n)} }\n     { \\B\\ts\\strshareq\\ra\\E,\\emptymap }\\index{44.1}\n\\end{equation}\n\\vspace{6pt}\n\\begin{equation}          % type sharing equation\n\\label{typshareq-rule}\n\\frac{ \\of{\\typefcn}{\\B(\\longtycon_1)}=\\cdots=\\of{\\typefcn}{\\B(\\longtycon_n)} }\n     { \\B\\ts\\typshareq\\ra\\emptymap }\n\\end{equation}\n\n\\vspace{6pt}\n\\begin{equation}          % multiple sharing equation\n%\\label{multshareq-rule}\n\\frac{ \\B\\ts\\shareq_1\\ra\\emptymap\\qquad\\B\\ts\\shareq_2\\ra\\emptymap }\n     { \\B\\ts\\multshareq\\ra\\emptymap }\n\\end{equation}\n\n%\n\\comments\n\\begin{description}\n\\item{(\\ref{strshareq-rule})}\n   By the definition of consistency the premise is weaker than\\linebreak\n$\\B(\\longstrid_1) = \\cdots = \\B(\\longstrid_n)$.\nTwo different structures with the same name may be thought of\nas representing different views. The requirement that $\\B$ is \nconsistent forces different views to be consistent.\n\\end{description}\n%\n\\oldpagebreak\n\\begin{description}\n\\item{(\\ref{typshareq-rule})}\n   By\\index{44.1.5} \nthe definition of consistency the premise is weaker than\\linebreak\n$\\B(\\longtycon_1) = \\cdots = \\B(\\longtycon_n)$.\nA type structure with empty constructor environment may have the\nsame type name as one with a non-empty constructor environment;\nthe former could arise from a type description, and the latter\nfrom a datatype description. \nHowever, the requirement that $\\B$ is\nconsistent will prevent two type structures with constructor\nenvironments which have different \nnon-empty domains from sharing the same type name.\nend{description}\n}\n%\n%\n%                       Type abbreviation rules\n%\n%\n%\n\\deletion{\\thenofuncspec}{\n%\n%                       Functor Specification rules\n%\n\\rulesec{Functor Specifications}{\\B\\ts\\funspec\\ra\\F}\n\\begin{equation}        % single functor specification\n\\label{singfunspec-rule}\n\\frac{ \\B\\ts\\fundesc\\ra\\F }\n     { \\B\\ts\\singfunspec\\ra\\F }\\index{44.2}\n\\end{equation}\n\n\\vspace{6pt}\n\\begin{equation}        % empty functor specification\n%\\label{emptyfunspec-rule}\n\\frac{}\n     { \\B\\ts\\emptyfunspec\\ra\\emptymap }\n\\end{equation}\n\n\\vspace{6pt}\n\\begin{equation}        % sequential functor specification\n%\\label{seqfunspec-rule}\n\\frac{ \\B\\ts\\funspec_1\\ra\\F_1\\qquad\n       \\B+\\F_1\\ts\\funspec_2\\ra\\F_2 }\n     { \\B\\ts\\seqfunspec\\ra\\plusmap{\\F_1}{\\F_2} }\n\\end{equation}\n\\comments\n\\begin{description}\n\\item{(\\ref{singfunspec-rule})}\nThe second closure restriction of Section~\\ref{closure-restr-sec}\ncan be enforced by replacing the $\\B$ in the premise by $\\B_0+\\of{\\G}{\\B}$.\n\\end{description}\n\\rulesec{Functor Descriptions}{\\B\\ts\\fundesc\\ra\\F}\n\\begin{equation}        % functor description\n%\\label{fundesc-rule}\n\\frac{ \\B\\ts\\funsigexp\\ra\\funsig\\qquad\n       \\langle\\B\\ts\\fundesc\\ra\\F\\rangle}\n     { \\B\\ts\\longfundesc\\ra\\{\\funid\\mapsto\\funsig\\}\n       \\langle +\\ \\F\\rangle}\\index{44.3}\n\\end{equation}\n\n\\rulesec{Functor Signature Expressions}{\\B\\ts\\funsigexp\\ra\\funsig}\n\\begin{equation}        % functor signature\n\\label{funsigexp-rule}\n%version 1:\n%\\frac{\n%      \\begin{array}{c}\n%      \\B\\ts\\sigexp\\ra\\S\\qquad\\longsig{}{\\rm\\ principal\\ in\\ }\\B\\\\\n%      \\B\\oplus\\{\\strid\\mapsto\\S\\} \\ts\\sigexp'\\ra\\S'\\\\\n%      \\N' = \\NamesFcn\\S'\\setminus((\\of{\\N}{\\B})\\cup\\N) \n%      \\end{array}\n%     }\n%     {\\B\\ts\\longfunsigexpa\\ra(\\N)(\\S,(\\N')\\S')}\\index{44.4}\n%version2: \\frac{\\begin{array}{rl}\n%      \\B\\ts\\sigexp\\ra\\S&\\mbox{$(N)S$ principal in $\\B$}\\\\\n%      \\B\\oplus\\{\\strid\\mapsto\\S\\}\\ts\\sigexp'\\ra\\S'&\n%      \\mbox{$(N')S'$ principal in $\\B\\oplus\\{\\strid\\mapsto\\S\\}$}\n%      \\end{array}}\n%     {\\B\\ts\\longfunsigexpa\\ra(N)(S,(N')S')}\\index{44.4}\n%\\end{equation}\n\\frac{\\B\\ts\\sigexp\\ra(\\N)\\S\\qquad\n      \\B\\oplus\\{\\strid\\mapsto\\S\\}\\ts\\sigexp'\\ra(\\N')\\S'}\n     {\\B\\ts\\longfunsigexpa\\ra(N)(S,(N')S')}\\index{44.4}\n\\end{equation}\n\\comment\nThe signatures $(\\N)\\S$ and $(\\N')\\S'$ are equality-principal \nand type-explicit, see rule~\\ref{topmost-sigexp-rule}.\n} %deletion\n%                       Functor and Program rules\n\n\\rulesec{Functor Declarations}{\\B\\ts\\fundec\\ra\\F}\n\\begin{equation}        % single functor declaration\n\\label{singfundec-rule}\n\\frac{ \\B\\ts\\funbind\\ra\\F }\n     { \\B\\ts\\singfundec\\ra\\F }\\index{45.1}\n\\end{equation}\n\n\\deletion{\\thenostrsharing}{\n\\vspace{6pt}\n\\begin{equation}        % empty functor declaration\n%\\label{emptyfundec-rule}\n\\frac{}\n     { \\B\\ts\\emptyfundec\\ra\\emptymap }\n\\end{equation}\n\n\\vspace{6pt}\n\\oldpagebreak\n\n\\begin{equation}        % sequential functor declaration\n%\\label{seqfundec-rule}\n\\frac{ \\B\\ts\\fundec_1\\ra\\F_1\\qquad\n       \\B+\\F_1\\ts\\fundec_2\\ra\\F_2 }\n     { \\B\\ts\\seqfundec\\ra\\plusmap{\\F_1}{\\F_2} }\\index{45.1.5}\n\\end{equation}}\n\\deletion{\\thenoclosurerestriction}{\\comments\n\\begin{description}\n\\item{(\\ref{singfundec-rule})}\nThe third closure restriction of Section~\\ref{closure-restr-sec}\ncan be enforced by replacing the $\\B$ in the premise \nby $\\B_0+(\\of{\\G}{\\B})+(\\of{\\F}{\\B})$.\n\\end{description}}\n\\rulesec{Functor Bindings}{\\B\\ts\\funbind\\ra\\F}\n\\replacement{\\thenostrsharing}{\\begin{equation}        % functor binding\n\\label{funbind-rule}\n\\frac{\n      \\begin{array}{c}\n      \\B\\ts\\sigexp\\ra(\\N)\\S\\qquad\n      \\B\\oplus\\{\\strid\\mapsto\\S\\} \\ts\\strexp\\ra\\S' \\\\\n       \\langle\n      \\B\\oplus\\{\\strid\\mapsto\\S\\} \\ts\\sigexp'\\ra\\sig',\\ \\sig'\\geq\\S''\\prec\\S'\n       \\rangle\\\\\n      \\N' = \\NamesFcn\\S'\\setminus((\\of{\\N}{\\B})\\cup\\N) \\\\\n       \\langle\\langle\\B\\ts\\funbind\\ra\\F\\rangle\\rangle\n      \\end{array}\n     }\n     {\n      \\begin{array}{c}\n       \\B\\ts\\funstrbinder\\ \\optfunbind\\ra\\\\\n       \\qquad\\qquad \\qquad\n              \\{\\funid\\mapsto(\\N)(\\S,(\\N')\\S'\\langle'\\rangle)\\}\n              \\ \\langle\\langle +\\ \\F\\rangle\\rangle\n      \\end{array}\n     }\\index{45.2}\n\\end{equation}}{\\begin{equation}        % functor binding\n\\label{funbind-rule}\n\\frac{\n      \\begin{array}{c}\n      \\B\\ts\\sigexp\\ra(\\T)\\E\\qquad\n      \\B\\oplus\\{\\strid\\mapsto\\E\\} \\ts\\strexp\\ra\\E' \n      \\\\\n      \\T\\cap(\\of{\\T}{\\B}) = \\emptyset\\quad \\T' = \\TyNamesFcn\\E'\\setminus((\\of{\\T}{\\B})\\cup\\T) \\\\\n       \\langle\\B\\ts\\funbind\\ra\\F\\rangle\n      \\end{array}\n     }\n     {\n      \\begin{array}{c}\n       \\B\\ts\\barefunstrbinder\\ \\langle\\boxml{and \\funbind}\\rangle\\ra\\\\\n       \\qquad\\qquad \\qquad\n              \\{\\funid\\mapsto(\\T)(\\E,(\\T')\\E')\\}\n              \\ \\langle +\\ \\F\\rangle\n      \\end{array}\n     }\\index{45.2}\n\\end{equation}\n}\\comment \\deletion{\\thenostrsharing}{The  requirement that $(\\N)\\S$ be equality-principal,\nimplicit in the first premise, forces $(\\N)\\S$ to be\nas general as possible given the sharing constraints in $\\sigexp$.\nThe requirement that $(\\N)\\S$ be type-explicit ensures that there is\nat most one realisation via which an actual argument can match\n$(\\N)\\S$.}Since $\\oplus$ is used, any \\deletion{\\thenostrsharing}{structure name $\\m$ and}type name $\\t$ in\n\\replacement{\\thenostrsharing}{$\\S$ }{$\\E$ }acts like a constant in the functor body; in particular,\nit ensures that further names generated during elaboration of the\nbody are distinct from \\deletion{\\thenostrsharing}{$\\m$ and }$\\t$. \n\\replacement{\\thenostrsharing}{The set $\\N'$ is\nchosen such that every  name free\nin $(\\N)\\S$ or $(\\N)(\\S,(\\N')\\S')$ is free in $\\B$.}{The set $\\T'$ is\nchosen such that every  name free\nin $(\\T)\\E$ or $(\\T)(\\E,(\\T')\\E')$ is free in $\\B$.}\n\\rulesec{Top-level Declarations}{\\B\\ts\\topdec\\ra\\B'}\n%\\rulesec{Programs}{\\B\\ts\\program\\ra\\B'}\n\\replacement{\\thenostrsharing}{\\begin{equation}\t% structure-level declaration\n\\label{strdectopdec-rule}\n\\frac{\\B\\ts\\strdec\\ra\\E \\quad\\imptyvars\\E=\\emptyset}\n     {\\B\\ts\\strdec\\ra\n      (\\NamesFcn\\E,\\E)\\ \\In\\ \\Basis\n     }\\index{45.3}\n\\end{equation}}{\\begin{equation}        % structure-level declaration\n\\label{strdectopdec-rule}\n\\frac{\\begin{array}{c}\n        \\B\\ts\\strdec\\ra\\E \\quad \\langle \\B\\oplus \\E\\ts \\topdec\\ra \\B'\\rangle\\\\\n        B'' = (\\TyNamesFcn\\E,\\E)\\In\\ \\Basis\\; \\langle + \\B'\\rangle\\quad\\TyVarFcn\\B''=\\emptyset\n      \\end{array}}\n     {\\B\\ts\\strdecintopdec\\ra\\B''}\n\\end{equation}}\n\n\\vspace{6pt}\n\\replacement{\\thenostrsharing}{\\begin{equation}\t% signature declaration\n%\\label{sigdectopdec-rule}\n\\frac{\\B\\ts\\sigdec\\ra\\G \\quad\\imptyvars\\G=\\emptyset}\n     {\\B\\ts\\sigdec\\ra\n      (\\NamesFcn\\G,\\G)\\ \\In\\ \\Basis\n     }\\index{46.0}\n\\end{equation}}{\\begin{equation}        % signature declaration\n\\frac{\\begin{array}{c}\n        \\B\\ts\\sigdec\\ra \\G\\quad \\langle\\B\\oplus\\G\\ts\\topdec\\ra\\B'\\rangle\\\\\n        \\B'' = (\\TyNamesFcn\\G,G)\\ \\In\\ \\Basis\\;\\langle + \\B'\\rangle\n      \\end{array}}\n     {\\B\\ts\\sigdecintopdec\\ra \\B''\n     }\\index{46.0}\n\\end{equation}}\n\n\\vspace{6pt}\n\\replacement{\\thenostrsharing}{\\begin{equation}\t% functor declaration\n\\label{fundectopdec-rule}\n\\frac{\\B\\ts\\fundec\\ra\\F \\quad\\imptyvars\\F=\\emptyset}\n     {\\B\\ts\\fundec\\ra\n      (\\NamesFcn\\F,\\F)\\ \\In\\ \\Basis\n     }\n\\end{equation}}{\\begin{equation}        % functor declaration\n\\label{fundectopdec-rule}\n\\frac{\\begin{array}{c}\n          \\B\\ts\\fundec\\ra\\F\\quad\\langle\\B\\oplus\\F\\ts\\topdec\\ra\\B'\\rangle\\\\\n          B'' = (\\TyNamesFcn\\F,\\F)\\ \\In\\ \\Basis\\; \\langle+\\B'\\rangle\\quad \\TyVarsFcn\\B''=\\emptyset\n      \\end{array}}\n     {\\B\\ts\\fundecintopdec\\ra\\B''}\n\\end{equation}}\n  \n\\comments\n\\replacement{\\thenostrsharing}{\n\\begin{description}\n\\item{(\\ref{strdectopdec-rule})--(\\ref{fundectopdec-rule})} The side\nconditions ensure that no free imperative \ntype variables enter the \nbasis.\\index{46.01}\n\\end{description}}{\n\\begin{description}\n\\item{(\\ref{strdectopdec-rule})--(\\ref{fundectopdec-rule})} \nNo free type variables enter the  basis: if $\\B\\ts\\topdec\\ra\\B'$\nthen $\\TyVarsFcn(\\B') = \\emptyset$.\\index{46.01}\n\\end{description}}\n\\oldpagebreak\n\n\\deletion{\\thenofuncspec}{\\subsection{Functor Signature Matching}\n\\label{fun-sig-match-sec}\nAs\\index{46} pointed out in Section~\\ref{mod-gram-sec} on the \ngrammar for Modules, there is no phrase class whose elaboration \nrequires matching one functor signature to another functor signature.\nBut a precise definition of this matching is needed, since a \nfunctor $g$ may only be separately compiled in the presence of \nspecification of any functor $f$ to which $g$ refers, and then a \nreal functor $f$ must match this specification.\nIn the case, then, that $f$ has been specified by a functor signature\n\\[\\funsig_1\\ =\\ \\longfunsig{1}\\]\nand that later $f$ is declared with functor signature\n\\[\\funsig_2\\ =\\ \\longfunsig{2}\\]\nthe following matching rule will be employed:\n\nA functor signature\n$\\funsig_2\\ =\\ \\longfunsig{2}$ {\\sl matches} another functor signature,\n$\\funsig_1\\ =\\ \\longfunsig{1}$, if there exists a realisation $\\rea$ \nsuch that\n\\begin{enumerate}\n\\item $\\longsig{1}$ matches $\\longsig{2}$ via $\\rea$, and\n\\item $\\rea((\\N_2')\\S_2')$ matches $(\\N_1')\\S_1'$.\n\\end{enumerate}\nThe first condition ensures that the real functor signature $\\funsig_2$\nfor $f$ requires the argument $\\strexp$ of any application $\\f(\\strexp)$\nto have no more sharing, and no more richness, than was predicted by\nthe specified signature $\\funsig_1$.\nThe second condition ensures that the real functor signature $\\funsig_2$,\ninstantiated to $(\\rea\\S_2,\\rea((\\N_2')\\S_2'))$, provides in the result of\nthe application $\\f(\\strexp)$\nno less sharing, and no less richness, than was predicted by\nthe specified signature $\\funsig_1$.\n\n%We claim that any phrase -- e.g. the declaration of the functor $g$ above --\n%which elaborates successfully in a basis $\\B$ with $\\B(f)=\\funsig_1$ will\n%also elaborate successfully in the basis $\\B+\\{f\\mapsto\\funsig_2\\}$.  This\n%claim justifies our definition of functor matching.\n% -- this claim is false because of open.\n\n} % deletion\n", "meta": {"hexsha": "c836719ab56ac5b121990727825d740c2cb5d397", "size": 56776, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/definition/statmod.tex", "max_stars_repo_name": "baguette/emblem-sandbox", "max_stars_repo_head_hexsha": "8aaa3f3c23be43210be064cd0c0bf4c56c6c50cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-01-11T20:01:15.000Z", "max_stars_repo_stars_event_max_datetime": "2016-01-11T20:01:15.000Z", "max_issues_repo_path": "doc/definition/statmod.tex", "max_issues_repo_name": "baguette/emblem-sandbox", "max_issues_repo_head_hexsha": "8aaa3f3c23be43210be064cd0c0bf4c56c6c50cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/definition/statmod.tex", "max_forks_repo_name": "baguette/emblem-sandbox", "max_forks_repo_head_hexsha": "8aaa3f3c23be43210be064cd0c0bf4c56c6c50cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.2666666667, "max_line_length": 182, "alphanum_fraction": 0.66582711, "num_tokens": 19243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3178154945239011}}
{"text": "\\section*{Discussion}\n\nBuilding on Shannon's formulation of information theory, there have been\nsignificant efforts using this theoretical framework to understand the\ninformation processing capabilities of biological systems, and the evolutionary\nconsequences for organisms harboring signal transduction systems\n\\cite{Bergstrom2004, Taylor2007, Tkacik2008, Polani2009, Nemenman2010,\nRivoire2011}. Recently, with the mechanistic dissection of molecular signaling\npathways, significant progress has been made on the question of the physical\nlimits of cellular detection and the role that features such as feedback loops\nplay in this task \\cite{Bialek2005, Libby2007, Tkacik2011, Rhee2012a,\nVoliotis2014a}. But the field still lacks a rigorous experimental test of these\nideas with precision measurements on a system that is tractable both\nexperimentally and theoretically.\n\nIn this paper we take advantage of the recent progress on the quantitative\nmodeling of input-output functions of genetic circuits to build a minimal model\nof the simple repression motif \\cite{Phillips2019}. By combining a series of\nstudies on this circuit spanning diverse experimental methods for measuring gene\nexpression under a myriad of different conditions, for the first time we possess\ncomplete \\textit{a priori} parametric knowledge -- allowing us to generate\nparameter-free predictions for processes related to information processing. Some\nof the model parameters for our kinetic formulation of the input-output function\nare informed by inferences made from equilibrium models. We use the fact that if\nboth kinetic and thermodynamic languages describe the same system, the\npredictions must be self-consistent. In other words, if the equilibrium model\ncan only make statements about the mean mRNA and mean protein copy number\nbecause of the way these models are constructed, those predictions must be\nequivalent to what the kinetic model has to say about these same quantities.\nThis condition therefore constrains the values that the kinetic rates in the\nmodel can take. To test whether or not the equilibrium picture can reproduce the\npredictions made by the kinetic model we compare the experimental and\ntheoretical fold-change in protein copy number for a suite of biophysical\nparameters and environmental conditions (\\fref{fig3_cell_cycle}(C) upper row).\nThe agreement between theory and experiment demonstrates that these two\nframeworks can indeed make consistent predictions.\n\nThe kinetic treatment of the system brings with it increasing predictive power\ncompared to the equilibrium picture. Under the kinetic formulation, the\npredictions are not limited only to the mean but to any of the moments of the\nmRNA and protein distributions. Furthermore, our formulation in terms of\ndynamical equations allows us to account for the time-varying nature of the\nmoments of the mRNA and protein copy numbers. Specifically, since the protein\nmean lifetime is comparable with the cell cycle length, the protein copy number\ndoes not reach a steady state over the duration of the cell cycle. Accounting\nfor this effect increases the expected cell-to-cell variability when measuring\nnon-synchronized cells. We first test these novel predictions by comparing the\nnoise in protein copy number (standard deviation / mean) with experimental data.\nOur minimal model predicts the noise up to a systematic deviation. The physical\nor biological origins of this discrepancy remain an open question. In that way\nthe work presented here exposes the status quo of our understanding of gene\nregulation in bacteria, posing new questions to be answered with future\nrefinements of the model. We then extend our analysis to infer entire protein\ndistributions at different input signal concentrations by using the maximum\nentropy principle. What this means is that we compute moments of the protein\ndistribution, and then use these moments to build an approximation to the full\ndistribution. These predicted distributions are then compared with experimental\nsingle-cell distributions as shown in \\fref{fig4_maxent}(B) and\n\\siref{supp_maxent}. Again, here although our minimal model systematically\nunderestimates the width of the distributions, it informs how changes in\nparameters such as protein copy number or protein-DNA binding affinity will\naffect the full probabilistic input-output function of the genetic circuit, up\nto a multiplicative constant. We then use our model to predict the information\nprocessing capacity.\n\nBy maximizing the mutual information between input signal concentration and\noutput protein distribution over all possible input distributions, we predict\nthe channel capacity of the system over a suite of biophysical parameters such\nas varying repressor protein copy number and repressor-DNA binding affinity.\nAlthough there is no reason to assume the the simplified synthetic circuit we\nused as an experimental model operates optimally given the distribution of\ninputs, the relevance of the channel capacity comes from its interpretation as a\nmetric of the physical limit of how precise an inference cells can make about\nwhat the state of the environment is. Our model, despite the systematic\ndeviations, makes non-trivial predictions such as the existence of an optimal\nrepressor copy number for a given repressor-DNA binding energy, predicting the\nchannel capacity up to an additive constant (See \\fref{fig5_channcap}). The\norigin of this optimal combination of repressor copy number and binding energy\ndiffers from previous publications in which an extra term associated with the\ncost of producing protein was included in the model \\cite{Tkacik2011}. This\noptimal parameter combination is a direct consequence of the fact that the LacI\nrepressor cannot be fully deactivated \\cite{Razo-Mejia2018}. This implies that\nas the number of repressors increases, a significant number of them are still\nable to bind to the promoter even at saturating concentrations of inducer. This\ncauses all of the input-output functions to be shift towards low expression\nlevels, regardless of the inducer concentration, decreasing the amount of\ninformation that the circuit is able to process. Interestingly, the number of\nbits predicted and measured in our system is similar to that of the gap genes in\nthe \\textit{Drosophila} embryo \\cite{Dubuis2013}. Although this is a suggestive\nnumerical correspondence that sets current experimental data on information\nprocessing capacity of genetic circuits between 1 and 2 bits, more work is\nrequired to fully understand the effect that different regulatory architectures\nhave on the ability to resolve different signals. \n\nWe consider it important to highlight the limitations of the work presented\nhere. The previously discussed systematic deviation for the noise and skewness\nof the predicted distributions (See \\siref{supp_multi_gene}), and therefore of\nthe predicted distributions and channel capacity, remains an unresolved\nquestion. Our current best hypothesis for the origin of this unaccounted noise\npertains to cell-to-cell variability in the central dogma machinery. More\nspecifically, our model does not account for changes in RNAP and sigma factor\ncopy numbers, changes in ribosome numbers, and even the variability in the\nrepressor copy number. This possibility deserves to be addressed in further\niterations of our minimal model. Also, as first reported in\n\\cite{Razo-Mejia2018}, our model fails to capture the steepness of the\nfold-change induction curve for the weakest repressor binding site (See\n\\fref{fig3_cell_cycle}(B)). Furthermore the minimal model in\n\\fref{fig2_minimal_model}(A), despite being widely used, is an\noversimplification of the physical picture of how the transcriptional machinery\nworks. The coarse-graining of all the kinetic steps involved in transcription\ninitiation into two effective promoter states -- active and inactive -- ignores\npotential kinetic regulatory mechanisms of intermediate states\n\\cite{Scholes2017}. Moreover it has been argued that despite the fact that the\nmRNA count distribution does not follow a Poisson distribution, this effect\ncould be caused by unknown factors not at the level of transcriptional\nregulation \\cite{Choubey2018}.\n\nThe findings of this work open the opportunity to accurately test intriguing\nideas that connect Shannon's metric of how accurately a signaling system can\ninfer the state of the environment, with Darwinian fitness \\cite{Taylor2007}.\nBeautiful work along these lines has been done in the context of the\ndevelopmental program of the early {\\it Drosophila} embryo \\cite{Tkacik2008,\nPetkova2019}. These studies demonstrated that the input-output function of the\npair-rule genes works at channel capacity, suggesting that selection has acted\non these signaling pathways, pushing them to operate at the limit of what the\nphysics of these systems allows. Our system differs from the early embryo in\nthe sense that we have a tunable circuit with variable amounts of information\nprocessing capabilities. Furthermore, compared with the fly embryo in which the\norganism tunes both the input and output distributions over evolutionary time,\nwe have experimental control of the distribution of inputs that the cells are\nexposed to. Consequently this means that instead of seeing the final result of\nthe evolutionary process, we would be able to set different environmental\nchallenges, and track over time the evolution of the population. These\nexperiments could shed light into the suggestive hypothesis of information bits\nas a trait on which natural selection acts. We see this exciting direction as\npart of the overall effort in quantitative biology of predicting evolution\n\\cite{Lassig2017}.", "meta": {"hexsha": "5079f4fb0b1dcdb05f0bf82dc0db9f5da74e0941", "size": 9686, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/section_06_discussion.tex", "max_stars_repo_name": "RPGroup-PBoC/chann_cap", "max_stars_repo_head_hexsha": "f2a826166fc2d47c424951c616c46d497ed74b39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-08-21T04:06:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T07:36:58.000Z", "max_issues_repo_path": "doc/section_06_discussion.tex", "max_issues_repo_name": "RPGroup-PBoC/chann_cap", "max_issues_repo_head_hexsha": "f2a826166fc2d47c424951c616c46d497ed74b39", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/section_06_discussion.tex", "max_forks_repo_name": "RPGroup-PBoC/chann_cap", "max_forks_repo_head_hexsha": "f2a826166fc2d47c424951c616c46d497ed74b39", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-04-29T17:43:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-09T00:20:16.000Z", "avg_line_length": 70.700729927, "max_line_length": 80, "alphanum_fraction": 0.8304769771, "num_tokens": 1954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.3177814554123158}}
{"text": "\\input{../header_class}\r\n\r\n%---------- start document ---------- %\r\n \\section{poly.hensel -- Hensel lift}\\linkedzero{poly.hensel}\r\n \\begin{itemize}\r\n   \\item {\\bf Classes}\r\n   \\begin{itemize}\r\n     \\item \\negok \\linkingone{poly.hensel}{HenselLiftPair}\r\n     \\item \\negok \\linkingone{poly.hensel}{HenselLiftMulti}\r\n     \\item \\negok \\linkingone{poly.hensel}{HenselLiftSimultaneously}\r\n   \\end{itemize}\r\n   \\item {\\bf Functions}\r\n     \\begin{itemize}\r\n       \\item \\linkingone{poly.hensel}{lift\\_upto}\r\n     \\end{itemize}\r\n \\end{itemize}\r\n\r\n In this module document, {\\em polynomial} means integer polynomial.\r\n\\C\r\n\r\n \\subsection{HenselLiftPair -- Hensel lift for a pair}\\linkedone{poly.hensel}{HenselLiftPair}\r\n \\initialize\r\n  \\func{HenselLiftPair}{%\r\n    \\hiki{f}{polynomial},\r\n    \\hiki{a1}{polynomial},\r\n    \\hiki{a2}{polynomial},\r\n    \\hiki{u1}{polynomial},\r\n    \\hiki{u2}{polynomial},\r\n    \\hiki{p}{integer},\r\n    \\hikiopt{q}{integer}{p}}{\\out{HenselLiftPair}}\\\\\r\n  \\spacing\r\n  % document of basic document\r\n  \\quad This object keeps integer polynomial pair which will be lifted by Hensel's lemma.\r\n  % added document\r\n  %\r\n  \\spacing\r\n  % input, output document\r\n  \\quad The argument should satisfy the following preconditions:\r\n  \\begin{itemize}\r\n  \\item \\param{f}, \\param{a1} and \\param{a2} are monic\r\n  \\item {\\tt \\param{f} == \\param{a1}*\\param{a2} (mod \\param{q})}\r\n  \\item {\\tt \\param{a1}*\\param{u1} + \\param{a2}*\\param{u2} == 1 (mod \\param{p})}\r\n  \\item \\param{p} divides \\param{q} and both are positive\r\n  \\end{itemize}\r\n  \\func{from\\_factors}{%\r\n    \\hiki{f}{polynomial},\r\n    \\hiki{a1}{polynomial},\r\n    \\hiki{a2}{polynomial},\r\n    \\hiki{p}{integer}}{\\out{HenselLiftPair}}\\\\\r\n  \\spacing\r\n  \\quad This is a class method to create and return an instance of {\\tt HenselLiftPair}.\r\n  You do not have to precompute {\\tt u1} and {\\tt u2} for the default constructor; they will be prepared for you from other arguments.\\\\\r\n  \\spacing\r\n  % input, output document\r\n  \\quad The argument should satisfy the following preconditions:\r\n  \\begin{itemize}\r\n  \\item \\param{f}, \\param{a1} and \\param{a2} are monic\r\n  \\item {\\tt \\param{f} == \\param{a1}*\\param{a2} (mod \\param{p})}\r\n  \\item \\param{p} is prime\r\n  \\end{itemize}\r\n  \\begin{at}\r\n    \\item[point]\\linkedtwo{poly.hensel}{HenselLiftPair}{factors}:\\\\\r\n      factors {\\tt a1} and {\\tt a2} as a list.\r\n  \\end{at}\r\n  \\method\r\n  \\subsubsection{lift -- lift one step}\\linkedtwo{poly.hensel}{HenselLiftPair}{lift}\r\n  \\func{lift}{\\param{self}}{}\\\\\r\n  \\spacing\r\n  \\quad Lift polynomials by so-called the quadratic method.\r\n  \\subsubsection{lift\\_factors -- lift {\\tt a1} and {\\tt a2}}\\linkedtwo{poly.hensel}{HenselLiftPair}{lift\\_factors}\r\n   \\func{lift\\_factors}{\\param{self}}{}\\\\\r\n   \\spacing\r\n   % document of basic document\r\n   \\quad Update factors by lifted integer coefficient polynomials {\\tt Ai}'s:\r\n   \\begin{itemize}\r\n   \\item {\\tt f == A1 * A2 (mod p * q)}\r\n   \\item {\\tt Ai == ai (mod q)} \\((i = 1, 2)\\)\r\n   \\end{itemize}\r\n   Moreover, {\\tt q} is updated to {\\tt p * q}.\r\n   \\spacing\r\n   % added document\r\n   \\quad \\negok The preconditions which should be automatically satisfied:\r\n   \\begin{itemize}\r\n   \\item {\\tt f == a1*a2 (mod q)}\r\n   \\item {\\tt a1*u1 + a2*u2 == 1 (mod p)}\r\n   \\item {\\tt p} divides {\\tt q}\r\n   \\end{itemize}\r\n   \\subsubsection{lift\\_ladder -- lift {\\tt u1} and {\\tt u2}}\\linkedtwo{poly.hensel}{HenselLiftPair}{lift\\_ladder}\r\n   \\func{lift\\_ladder}{\\param{self}}{}\\\\\r\n   \\spacing\r\n   % document of basic document\r\n   \\quad Update {\\tt u1} and {\\tt u2} with {\\tt U1} and {\\tt U2}:\r\n   \\begin{itemize}\r\n   \\item {\\tt a1*U1 + a2*U2 == 1 (mod p**2)}\r\n   \\item {\\tt Ui == ui (mod p)} \\((i = 1, 2)\\)\r\n   \\end{itemize}\r\n   Then, update {\\tt p} to {\\tt p**2}.\r\n   \\spacing\r\n   % added document\r\n   \\quad \\negok The preconditions which should be automatically satisfied:\r\n   \\begin{itemize}\r\n   \\item {\\tt a1*u1 + a2*u2 == 1 (mod p)}\r\n   \\end{itemize}\r\n\r\n\\subsection{HenselLiftMulti -- Hensel lift for multiple polynomials}\\linkedone{poly.hensel}{HenselLiftMulti}\r\n \\initialize\r\n  \\func{HenselLiftMulti}{%\r\n    \\hiki{f}{polynomial},\r\n    \\hiki{factors}{list},\r\n    \\hiki{ladder}{tuple},\r\n    \\hiki{p}{integer},\r\n    \\hikiopt{q}{integer}{p}}{\\out{HenselLiftMulti}}\\\\\r\n  \\spacing\r\n  % document of basic document\r\n  \\quad This object keeps integer polynomial factors which will be lifted by Hensel's lemma.\r\n  If the number of factors is just two, then you should use \\linkingone{poly.hensel}{HenselLiftPair}.\r\n  % added document\r\n  %\r\n  \\spacing\r\n  % input, output document\r\n  \\quad \\param{factors} is a list of polynomials;\r\n  we refer those polynomials as {\\tt a1}, {\\tt a2}, \\(\\ldots\\)\r\n  \\param{ladder} is a tuple of two lists {\\tt sis} and {\\tt tis},\r\n  both lists consist polynomials.\r\n  We refer polynomials in {\\tt sis} as {\\tt s1}, {\\tt s2}, \\(\\ldots\\),\r\n  and those in {\\tt tis} as {\\tt t1}, {\\tt t2}, \\(\\ldots\\)\r\n  Moreover, we define {\\tt bi} as the product of {\\tt aj}'s for\r\n  \\(i < j\\).\r\n  \\quad The argument should satisfy the following preconditions:\r\n  \\begin{itemize}\r\n  \\item \\param{f} and all of \\param{factors} are monic\r\n  \\item {\\tt \\param{f} == \\param{a1}*...*\\param{ar} (mod \\param{q})}\r\n  \\item {\\tt ai*si + bi*ti == 1 (mod \\param{p})} \\((i = 1,2,\\ldots,r)\\)\r\n  \\item \\param{p} divides \\param{q} and both are positive\r\n  \\end{itemize}\r\n%\r\n  \\func{from\\_factors}{%\r\n    \\hiki{f}{polynomial},\r\n    \\hiki{factors}{list},\r\n    \\hiki{p}{integer}}{\\out{HenselLiftMulti}}\\\\\r\n  \\spacing\r\n  \\quad This is a class method to create and return an instance of {\\tt HenselLiftMulti}.\r\n  You do not have to precompute {\\tt ladder} for the default constructor; they will be prepared for you from other arguments.\\\\\r\n  \\spacing\r\n  % input, output document\r\n  \\quad The argument should satisfy the following preconditions:\r\n  \\begin{itemize}\r\n  \\item \\param{f} and all of \\param{factors} are monic\r\n  \\item {\\tt \\param{f} == \\param{a1}*...*\\param{ar} (mod \\param{q})}\r\n  \\item \\param{p} is prime\r\n  \\end{itemize}\r\n  \\begin{at}\r\n    \\item[point]\\linkedtwo{poly.hensel}{HenselLiftMulti}{factors}:\\\\\r\n      factors {\\tt ai}s as a list.\r\n  \\end{at}\r\n  \\method\r\n  \\subsubsection{lift -- lift one step}\\linkedtwo{poly.hensel}{HenselLiftMulti}{lift}\r\n  \\func{lift}{\\param{self}}{}\\\\\r\n  \\spacing\r\n  \\quad Lift polynomials by so-called the quadratic method.\r\n  \\subsubsection{lift\\_factors -- lift factors}\\linkedtwo{poly.hensel}{HenselLiftMulti}{lift\\_factors}\r\n  \\func{lift\\_factors}{\\param{self}}{}\\\\\r\n  \\spacing\r\n  % document of basic document\r\n  \\quad Update factors by lifted integer coefficient polynomials {\\tt Ai}s:\r\n  \\begin{itemize}\r\n  \\item {\\tt f == A1*...*Ar (mod p * q)}\r\n  \\item {\\tt Ai == ai (mod q)} \\((i = 1, \\ldots, r)\\)\r\n  \\end{itemize}\r\n  Moreover, {\\tt q} is updated to {\\tt p * q}.\r\n  \\spacing\r\n  % added document\r\n  \\quad \\negok The preconditions which should be automatically satisfied:\r\n  \\begin{itemize}\r\n  \\item {\\tt f == a1*...*ar (mod q)}\r\n  \\item {\\tt ai*si + bi*ti == 1 (mod p)} \\((i = 1,\\ldots, r)\\)\r\n  \\item {\\tt p} divides {\\tt q}\r\n  \\end{itemize}\r\n  \\subsubsection{lift\\_ladder -- lift {\\tt u1} and {\\tt u2}}\\linkedtwo{poly.hensel}{HenselLiftMulti}{lift\\_ladder}\r\n  \\func{lift\\_ladder}{\\param{self}}{}\\\\\r\n  \\spacing\r\n  % document of basic document\r\n  \\quad Update {\\tt si}s and {\\tt ti}s with {\\tt Si}s and {\\tt Ti}s:\r\n  \\begin{itemize}\r\n  \\item {\\tt a1*Si + bi*Ti == 1 (mod p**2)}\r\n  \\item {\\tt Si == si (mod p)} \\((i = 1, \\ldots, r)\\)\r\n  \\item {\\tt Ti == ti (mod p)} \\((i = 1, \\ldots, r)\\)\r\n  \\end{itemize}\r\n  Then, update {\\tt p} to {\\tt p**2}.\r\n  \\spacing\r\n  % added document\r\n  \\quad \\negok The preconditions which should be automatically satisfied:\r\n  \\begin{itemize}\r\n  \\item {\\tt ai*si + bi*ti == 1 (mod p)} \\((i = 1,\\ldots, r)\\)\r\n  \\end{itemize}\r\n%\r\n\r\n\\subsection{HenselLiftSimultaneously}\\linkedone{poly.hensel}{HenselLiftSimultaneously}\r\n\r\n  The method explained in~\\cite{ColEnc}.\\\\\r\n  \\quad \\negok Keep these invariants:\r\n  \\begin{itemize}\r\n  \\item     {\\tt ai}s, {\\tt pi} and {\\tt gi}s are monic\r\n  \\item     {\\tt f == g1*...*gr (mod p)}\r\n  \\item     {\\tt f == d0 + d1*p + d2*p**2 +...+ dk*p**k}\r\n  \\item     {\\tt hi == g(i+1)*...*gr}\r\n  \\item     {\\tt 1 == gi*si + hi*ti (mod p)} \\((i = 1 ,\\ldots, r)\\)\r\n  \\item     \\(\\deg\\)({\\tt si}) \\(<\\) \\(\\deg\\)({\\tt hi}),\r\n    \\(\\deg\\)({\\tt ti}) \\(<\\) \\(\\deg\\)({\\tt gi}) \\((i = 1 ,\\ldots, r)\\)\r\n  \\item     {\\tt p} divides {\\tt q}\r\n  \\item     {\\tt f == l1*...*lr (mod q/p)}\r\n  \\item     {\\tt f == a1*...*ar (mod q)}\r\n  \\item     {\\tt ui == ai*yi + bi*zi (mod p)} \\((i = 1, \\ldots, r)\\)\r\n  \\end{itemize}\r\n\r\n \\initialize\r\n  \\func{HenselLiftSimultaneously}{%\r\n    \\hiki{target}{polynomial},\r\n    \\hiki{factors}{list},\r\n    \\hiki{cofactors}{list},\r\n    \\hiki{bases}{list},\r\n    \\hiki{p}{integer}}{\\out{HenselLiftSimultaneously}}\\\\\r\n  \\spacing\r\n  % document of basic document\r\n  \\quad This object keeps integer polynomial factors which will be lifted by Hensel's lemma.\\\\\r\n  \\spacing\r\n  \\quad {\\tt f = \\param{target}}, {\\tt gi} in \\param{factors},\r\n  {\\tt hi}s in \\param{cofactors} and {\\tt si}s and {\\tt ti}s are in \\param{bases}.\r\n%\r\n  \\func{from\\_factors}{%\r\n    \\hiki{target}{polynomial},\\ %\r\n    \\hiki{factors}{list},\\ %\r\n    \\hiki{p}{integer},\\ %\r\n    \\hikiopt{ubound}{integer}{\\linklibraryone{sys\\#maxint}{sys.maxint}}}{%\r\n    \\out{HenselLiftSimultaneously}}\r\n  \\spacing\r\n  % document of basic document\r\n  \\quad This is a class method to create and return an instance of {\\tt HenselLiftSimultaneously}, whose factors are lifted by \\linkingone{poly.hensel}{HenselLiftMulti} upto \\param{ubound} if it is smaller than {\\tt sys.maxint}, or upto {\\tt sys.maxint} otherwise.\r\n  You do not have to precompute auxiliary polynomials for the default\r\n  constructor; they will be prepared for you from other arguments.\\\\\r\n  \\spacing\r\n  \\quad {\\tt f = \\param{target}}, {\\tt gi}s in \\param{factors}.\r\n%\r\n  \\method\r\n  \\subsubsection{lift -- lift one step}\\linkedtwo{poly.hensel}{HenselLiftSimultaneously}{lift}\r\n  \\func{lift}{\\param{self}}{}\\\\\r\n  \\spacing\r\n  The lift. You should call this method only.\r\n  \\subsubsection{first\\_lift -- the first step}\\linkedtwo{poly.hensel}{HenselLiftSimultaneously}{first\\_lift}\r\n  \\func{first\\_lift}{\\param{self}}{}\\\\\r\n  \\spacing\r\n  \\quad Start lifting.\\\\\r\n  {\\tt f == l1*l2*...*lr (mod p**2)}\\\\\r\n  Initialize {\\tt di}s, {\\tt ui}s, {\\tt yi}s and {\\tt zi}s.\r\n  Update {\\tt ai}s, {\\tt bi}s.\r\n  Then, update {\\tt q} with {\\tt p**2}.\r\n  \\subsubsection{general\\_lift -- next step}\\linkedtwo{poly.hensel}{HenselLiftSimultaneously}{general\\_lift}\r\n  \\func{general\\_lift}{\\param{self}}{}\\\\\r\n  \\spacing\r\n  \\quad Continue lifting.\\\\\r\n  {\\tt f == a1*a2*...*ar (mod p*q)}\\\\\r\n  Initialize {\\tt ai}s, {\\tt ubi}s, {\\tt yi}s and {\\tt zi}s.\r\n  Then, update {\\tt q} with {\\tt p*q.}\r\n\r\n  \\subsection{lift\\_upto -- main function}\\linkedone{poly.hensel}{lift\\_upto}\r\n  \\func{lift\\_upto}{\\param{self},\\ %\r\n  \\hiki{target}{polynomial},\\  %\r\n  \\hiki{factors}{list},\\ %\r\n  \\hiki{p}{integer},\\ %\r\n  \\hiki{bound}{integer}}{\\out{tuple}}\\\\\r\n\\spacing\r\n\\quad Hensel lift \\param{factors} mod \\param{p} of \\param{target} upto \\param{bound}\r\nand return {\\tt factors} mod {\\tt q} and the {\\tt q} itself.\\\\\r\n\\quad These preconditions should be satisfied:\r\n\\begin{itemize}\r\n\\item \\param{target} is monic.\r\n\\item {\\tt \\param{target} == product(\\param{factors}) mod \\param{p}}\r\n\\end{itemize}\r\n\\quad The result {\\tt (factors, q)} satisfies the following postconditions:\r\n\\begin{itemize}\r\n\\item there exist \\(k\\) s.t. {\\tt q == \\param{p}**k >= \\param{bound}} and\r\n\\item {\\tt \\param{target} == product(factors) mod q}\r\n\\end{itemize}\r\n\r\n\\C\r\n\r\n%---------- end document ---------- %\r\n\r\n\\input{../footer}\r\n", "meta": {"hexsha": "b75e4696233b7c6a94e968e53c8f5a41dd94246a", "size": 11643, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "manual/en/poly.hensel.tex", "max_stars_repo_name": "turkeydonkey/nzmath3", "max_stars_repo_head_hexsha": "a48ae9efcf0d9ad1485c2e9863c948a7f1b20311", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-26T19:22:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-26T19:22:17.000Z", "max_issues_repo_path": "manual/en/poly.hensel.tex", "max_issues_repo_name": "turkeydonkey/nzmath3", "max_issues_repo_head_hexsha": "a48ae9efcf0d9ad1485c2e9863c948a7f1b20311", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "manual/en/poly.hensel.tex", "max_forks_repo_name": "turkeydonkey/nzmath3", "max_forks_repo_head_hexsha": "a48ae9efcf0d9ad1485c2e9863c948a7f1b20311", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1482758621, "max_line_length": 265, "alphanum_fraction": 0.6264708408, "num_tokens": 4027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3176299335587883}}
{"text": "\\chapter*{Preface}\n\\addcontentsline{toc}{part}{Preface}\n\nHow much mathematics does one need to understand artificial intelligence?\nOn Tuesday, 28th February 2017, I set out to answer that.\nI wanted to learn about artificial intelligence as fast as possible,\nand I thought that the best way to do that was to dive cold turkey into the mathematics.\n\nI write this book for myself\nto find out whether I understand things;\nI understand something when I can explain it.\n\nThe approach is formal, but not rigorous.\nWrong-but-useful is preferred to correct-but-irrelevant.\nProofs that can be found on the Internet are omitted.\n\nI believe that definitions\nare keys that open doors to theorems.\n\nThis book only covers a very small part of mathematics.\nFor an overview of how big mathematics is,\nsee the Mathematics Subject Classification.\n", "meta": {"hexsha": "f857fc25d6854edd0efea2459040716e8c381735", "size": 828, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "research/preface.tex", "max_stars_repo_name": "edom/work", "max_stars_repo_head_hexsha": "df55868caa436efc631e145a43e833220b8da1d0", "max_stars_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "research/preface.tex", "max_issues_repo_name": "edom/work", "max_issues_repo_head_hexsha": "df55868caa436efc631e145a43e833220b8da1d0", "max_issues_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-12-02T18:37:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T00:55:32.000Z", "max_forks_repo_path": "research/preface.tex", "max_forks_repo_name": "edom/work", "max_forks_repo_head_hexsha": "df55868caa436efc631e145a43e833220b8da1d0", "max_forks_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-10-02T15:20:22.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T15:20:22.000Z", "avg_line_length": 36.0, "max_line_length": 88, "alphanum_fraction": 0.8007246377, "num_tokens": 178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3176299335587883}}
{"text": "\\label{ch:qg}\n\\chapter{Quark Gluon Tagging in $\\ell\\nu qq$ Diboson Resonance Search}\nThe jets produced in diboson resonances in $\\ell \\nu qq$ final states below $\\sim 700$ GeV are well separated and may be reconstructed separately. The background jets of this diboson resonance search are gluon dominated, while signal jets are quark enriched. By classifying jets in events as quark or gluon initiated, background contamination in the signal region may be reduced. \n\nFigure~\\ref{fig:diag_pdgid} shows the flavor distributions of the truth parton matched to the jet (meaning the highest energy parton in the jet catchment area) in events passing the resolved signal region selections. From this Figure, it is evident that a notable fraction of the background (all background events that passed the resolved SR are used) that contaminates the signal region contains gluon jets, especially for the sub-leading jet. \n\nAs gluons jets have more constituents and therefore more tracks ($n_{trk}$), background jets generally have more tracks than the signal jets. This is shown in Figure~\\ref{fig:diag_ntrk}. Therefore $n_{trk}$, provides discrimination between quark and gluon jets (i.e. jets with less than a specified $n_{trk}$ value could be classified as a quark-initiated jet, otherwise the jet would be classified as gluon-initiated.). Moreover, as the momentum of the jet increases the number of tracks also increases logarithmically and improves tagging efficiency by about 10\\% relative to a constant cut on the number of tracks \\cite{nachman}. Figures \\ref{fig:bkg_heatmap}-\\ref{fig:sig700_heatmap} show normalized heat maps of $\\ln(p_{T})$ vs $n_{trk}$ for the background and HVT $Z'$ signals. This information is also shown in table \\ref{tbl:qgtable}. In these plots it is evident that $n_{trk}$ in the background jets grows more quickly with $\\ln(p_{T})$ than for the signal jets. This is expected given that the signal is quark dominated and the background is gluon dominated. \n\nIn Figure~\\ref{fig:quark_gluon_roc} is the ROC Curve for quark gluon tagging with cut on $n_{trk}$ in a jet that depends on $\\ln(p_{T})$. Here the quark tagging efficiency is the ratio of quarks tagged as quarks to the total number of quarks in the signal region. The gluon rejection is calculated as the reciprocal of the gluon tagging efficiency. For example, choosing a 90\\% efficient working point with a rejection of 1.4 corresponds to a slope of 4 and intercept of -5. Tagging both jets in this analysis would yield an efficiency of $81\\%$. Focusing on the background in Figure~\\ref{fig:qg_s_root_b}, this cut helps minimize gluon contamination in the signal region.\n\\pagebreak\n\n\\begin{figure}[h!]\n  \\centering\n  \\includegraphics[width=0.45\\hsize]{figures/QGT/sigWJ1_pdgid_Pass_Res_GGF_WW_SR.pdf}\n \\includegraphics[width=0.45\\hsize]{figures/QGT/sigWJ2_pdgid_Pass_Res_GGF_WW_SR.pdf}\n  \\caption{PDGID of the truth-level parton matched to the small-R jets passing the Resolved GGF WW Signal Region selections for the (a) Leading (b) Sub-Leading jets . These distributions are shown for 300, 500, and 700GeV Z' signals and the background (all simulated backgrounds that pass SR selections). PDGID = -1 corresponds to pileup jets, 0 < PDGID < 6 correspond to quarks and PDGID = 21 corresponds to gluons.}\n  \\label{fig:diag_pdgid}\n\\end{figure}\n\\FloatBarrier\n\n\n\n\\begin{figure}[h!]\n  \\centering\n  \\includegraphics[width=0.45\\hsize]{figures/QGT/sigWJ1_nTrk_Pass_Res_GGF_WW_SR.pdf}\n \\includegraphics[width=0.45\\hsize]{figures/QGT/sigWJ2_nTrk_Pass_Res_GGF_WW_SR.pdf}\n  \\caption{The number of tracks in small-R jets in events passing the Resolved GGF WW Signal Region selections for the (a) Leading (b) Sub-Leading jets. These distributions are shown for 300, 500, and 700GeV Z' signals and the background.}\n  \\label{fig:diag_ntrk}\n\\end{figure}\n\\FloatBarrier\n\n\n\\begin{figure}[h!]\n  \\centering\n  \\includegraphics[width=0.45\\hsize]{figures/QGT/allbkg-ade_Pass_Res_GGF_WW_SR_sigWJ1_nTrk.pdf}\n \\includegraphics[width=0.45\\hsize]{figures/QGT/allbkg-ade_Pass_Res_GGF_WW_SR_sigWJ2_nTrk.pdf}\n  \\caption{The number of tracks in background small-R jets in events passing the Resolved GGF WW Signal region selection vs. $\\ln(p_{T})$ for (a)Leading (b) Sub-Leading jets. The best fit line for the distribution is also shown, as well as the percentage of jets that pass a cut of number of tracks $< 4\\times \\ln(p_{T}) -5$. Note the number of total entries in these plots has been normalized to one.}\n  \\label{fig:bkg_heatmap}\n\\end{figure}\n\\FloatBarrier\n\n\n\\begin{figure}[h!]\n  \\centering\n  \\includegraphics[width=0.45\\hsize]{figures/QGT/HVTWW_300_1lep_Pass_Res_GGF_WW_SR_sigWJ1_nTrk.pdf}\n \\includegraphics[width=0.45\\hsize]{figures/QGT/HVTWW_300_1lep_Pass_Res_GGF_WW_SR_sigWJ2_nTrk.pdf}\n  \\caption{The number of tracks in small-R jets in 300GeV Z' events passing the Resolved GGF WW Signal region selection vs. $\\ln(p_{T})$ for (a)Leading (b) Sub-Leading jets. The best fit line for the distribution is also shown, as well as the percentage of jets that pass a cut of number of tracks $< 4\\times \\ln(p_{T}) -5$.Note the number of total entries in these plots has been normalized to one.}\n  \\label{fig:sig300_heatmap}\n\\end{figure}\n\\FloatBarrier\n\n\n\\begin{figure}[h!]\n  \\centering\n  \\includegraphics[width=0.45\\hsize]{figures/QGT/HVTWW_500_1lep_Pass_Res_GGF_WW_SR_sigWJ1_nTrk.pdf}\n \\includegraphics[width=0.45\\hsize]{figures/QGT/HVTWW_500_1lep_Pass_Res_GGF_WW_SR_sigWJ2_nTrk.pdf}\n  \\caption{The number of tracks in small-R jets in 500GeV Z' events passing the Resolved GGF WW Signal region selection vs. $\\ln(p_{T})$ for (a)Leading (b) Sub-Leading jets. The best fit line for the distribution is also shown, as well as the percentage of jets that pass a cut of number of tracks $< 4\\times \\ln(p_{T}) -5$.Note the number of total entries in these plots has been normalized to one.}\n  \\label{fig:sig500_heatmap}\n\\end{figure}\n\\FloatBarrier\n\n\n\\begin{figure}[h!]\n  \\centering\n  \\includegraphics[width=0.45\\hsize]{figures/QGT/HVTWW_700_1lep_Pass_Res_GGF_WW_SR_sigWJ1_nTrk.pdf}\n \\includegraphics[width=0.45\\hsize]{figures/QGT/HVTWW_700_1lep_Pass_Res_GGF_WW_SR_sigWJ2_nTrk.pdf}\n  \\caption{The number of tracks in small-R jets in 700GeV Z' events passing the Resolved GGF WW Signal region selection vs. $\\ln(p_{T})$ for (a)Leading (b) Sub-Leading jets. The best fit line for the distribution is also shown, as well as the percentage of jets that pass a cut of number of tracks $< 4\\times \\ln(p_{T}) -5$.Note the number of total entries in these plots has been normalized to one.}\n  \\label{fig:sig700_heatmap}\n\\end{figure}\n\\FloatBarrier\n\n\n\\begin{table}\n\\begin{tabular}{|l|c|c|c|}\n\\hline\nSample & Best Fit Slope & Best Fit Intercept & QG Tag Yield \\\\\\hline\nBackgrounds & 3.7 & -7.9 & 86\\% \\\\\\hline\nHVT $Z'$ 300 GeV &  2.9 & -5.2 & 95\\% \\\\\\hline\nHVT $Z'$ 500 GeV & 3.9 & -9.7 & 92\\% \\\\\\hline\n\\end{tabular}\n\\caption{This table shows the best fit slope and intercept for the 2-d distribution of $n_{trk}$ vs. jet $\\ln(p_{T})$ for the leading jet in the background and HVT $Z'$ samples. The tagging efficiency is shown for the 90\\% working point in the last column. The background jets contain more gluons than the signal jets. Consequently, the best fit line for the background predicts larger values of the number of tracks in jets for the background than the considered signals.}\n\\label{tbl:qgtable}\n\\end{table}\n\n\\begin{figure}[h!]\n  \\centering\n  \\includegraphics[width=\\hsize]{figures/QGT/finalroc.pdf}\n  \\caption{ROC Curve for Quark and Gluon Tagging with a cut on the number of tracks that depends on the $\\ln(p_{T})$.}\n  \\label{fig:quark_gluon_roc}\n\\end{figure}\n\\FloatBarrier\n\n\n\\begin{figure}[h!]\n  \\centering\n  \\includegraphics[width=\\hsize]{figures/QGT/s_root_b_recotag.pdf}\n  \\caption{The top panel shows the distribution of $m_{lvqq}$ with and without quark gluon tagging. The middle panel shows the ratio of the signals and backgrounds with and without quark gluon tagging. The bottom panel shows the change in $S/\\sqrt{B}$ with quark gluon tagging.}\n  \\label{fig:qg_s_root_b}\n\\end{figure}\n\\FloatBarrier\n\n\n\\pagebreak\n\\pagebreak\n\\pagebreak\n\\chapter{Quark Gluon Tagger Calibration}\nThe number of tracks in jets depends on modeling and experimental systematics. Consequently, the efficiency of a $n_{trk}$ based quark-gluon tagger would have associated uncertainties. In the context of the resonance search discussed, these uncertainties would be treated as systematics that impact the $m_{WV}$ distributions used for discovery tests.\n\nThe $n_{trk}$ modeling uncertainties are obtained by assessing PDF and ME variations on the number of charged particles ($n_{c}$) in particle-level jets from a dijet sample. The distribution of $n_{c}$ as a function of jet $p_{T}$  is calculated using an Iterative Bayesian (IB) technique \\cite{ib_unfolding}.\n\nThis measurement detailed in \\cite{Unfolding}, uses the ATLAS 2012 $pp$ collision dataset, corresponding to 20.3$^{-1}$~fb at center-of-mass energy $\\sqrt{s}=8$ TeV. The number of charged constituents depends on fragmentation modeling and matrix elements, which do not depend on $s$. For this reason, it is safe to use these uncertainties for $\\sqrt{s}=13$ TeV. Monte Carlo (MC) samples are used to determine the response matrix. The MC sample is a dijet sample generated with Pythia 8.175 using CT10 PDF and AU2 tune.  The anti-$k_{t}$ algorithm is used to cluster jets with a radius parameter R = 0.4. Jets are required to have $|\\eta| < 2.1$. Tracks in jets are required to have $p_{T}>500$ MeV, $|\\eta|<2.5$, track-fit $\\chi^{2} < 3.0$ and originate from the primary vertex. Matching tracks to jets is accomplished using ghost-association \\cite{ghost_association}. In this technique, jets are re-clustered with the track collection augmented with \"ghost\" versions of tracks.  These \"ghosts\" tracks have the same direction as their parent track, but infinitesimal track $p_{T}$. This insures meta-jet properties (e.g. $\\eta$, $p_{T}$, etc) are unchanged. A track is matched to a jet if it's ghost version remains in the jet after re-clustering. \n\nTo select dijet topologies events are required to have at least two jets with $p_{T} > 50GeV$ that are relatively well-balanced ($p_{T}^{lead}/p_{T}^{sub-lead} < 1.5$). \n\nIn the IB technique, the prior distribution and number of iterations are the inputs \\cite{ib_unfolding}. The IB response matrix connects $n_{c}$ to $n_{trk}$ using the simulated samples. This response matrix is used to unfold data to extract the $n_{c}$. Before applying the response matrix a fake factor is applied. This accounts for jets that pass detector level selections, but not particle level selections. Following this, the IB method iteratively applies the response matrix using the nominal Pythia 8.175 sample as a prior. The number of IB iterations is chosen to minimize unfolding bias and statistical fluctuations. For this measurement four iterations was found to be optimal by minimizing the unfolding bias from pseudodata simulated with Herwig++ with a prior from Pythia 8 AU2. Finally, the inefficiency factor is applied to account for events passing particle level selection but not detector level, yielding the unfolded $n_{c}$ distribution.\n \nThis process is prone to three main sources of bias: response matrix, correction factor, and unfolding procedure uncertainties. The response matrix is sensitive to experimental uncertainties impacting jet track reconstruction and calorimeter jet $p_{T}$. Correction factors are also sensitive to experimental uncertainties (e.g. JES) as such uncertainties modify detector level acceptance. Sensitivity to particle level acceptance is calculated by comparing Pythia and Herwig. Finally, the bias from the IB prior choice is determined by reweighting the particle-level spectrum, so the simulated detector level spectrum more closely matches the uncorrected data. Unfolding this modified detector-level simulation and comparing it to the re-weighted particle-level spectrum indicates bias from the prior distribution choice.\n\nA summary of all the systematic uncertainties associated with this unfolding may be found in \\cite{Unfolding}. Total uncertainties are < 7\\% for the number of charged particles in jets. The unfolded distribution of the $n_{c}$ in jets from data are further analyzed to extract the quark and gluon $n_{c}$ distributions. In dijet events, the jet with a larger $\\eta$ is more energetic and therefore more likely to be a quark. This is due to the quarks in protons generally having a larger fraction of the total momentum of the proton constituents. The more central jet is more likely to be a gluon-initiated jet. This correlation between jet $\\eta$ and flavor may then be used to extract $n_{c}$ in $p_{T}$ bins using:\n\n\\begin{equation}\n<n_{c}^{f}> = f_{q}^{f}<n_{c}^{q}> + f^{f}_{g}<n_{c}^{g}>\n\\end{equation}\n\\begin{equation}\n<n_{c}^{c}> = f_{q}^{c}<n_{c}^{q}> + f^{c}_{g}<n_{c}^{g}> \n\\end{equation}\n\n\nIn this equation the $f$ and $c$ subscripts denote the more forward and central jets, respectively. The $q$ and $g$ subscripts denote quark and gluon. The fraction of more forward jets that are say, gluons, is denoted by $f_{g}^{f}$. The other relevant jet fractions are denoted with the same naming scheme. Finally, $<n_{c}>$ is the average number of charged particles in a jet in a given $p_{T}$ bin. To show these equations may be used to extract quark and gluon $n_{c}$ distributions, the extracted distributions are compared to $n_{c}$ distributions determined using the jet flavor in simulation. Figure \\ref{fig:closure_qg} shows that the extracted and true distributions differ by < 1\\% over the $p_{T}$ range probed for this study. Moreover, this implies that $n_{c}$ depends only on the flavor of the initiating parton and jet $p_{T}$. \n\nThese extracted distributions are prone to PDF and ME biases. The bias from the choice of the CT10 PDF for the Pythia sample is accounted for by comparing quark/gluon fractions for the nominal CT10 sample with its eigenvector variations. Comparing the quark/gluon fractions from Pythia 8 and Herwig++ quantify the uncertainty from the ME calculation. These uncertainties are added in quadrature with the unfolding uncertainty to give the total modeling uncertainty on the extracted $n_{c}$ distribution. This is shown in Figure~\\ref{fig:extracted_qg}.\n\nTo apply these uncertainties in $n_{c}$ distributions in data, per-jet event weights are associated with each uncertainty according to:\n\n\\begin{equation}\nw_{i}(n_{c}) = \\frac{P(n_{c}|<n_{c}> \\pm \\sigma^{i}_{n_{c}})} {P(n_{c}|<n_{c}>)}\n\\label{QG_uncer}\n\\end{equation}\n\nIn Eq. \\ref{QG_uncer}, $i$ denotes the uncertainty considered, P is the Poisson probability, and $\\sigma^{i}_{n_{c}}$ represents the average impact of the uncertainty on $n_{c}$. \n\n%DETECTOR LEVEL UNCERTAINTIES \n%(mc16_13TeV.361020.Pythia8EvtGen_A14NNPDF23LO_jetjet_JZ0W.merge.DAOD_JETM1.e3569_s2997_r8903_r8906_p2996).\n\n\nThe previous uncertainties described accounted for modeling uncertainty associated with the number of charged particles in a jet. However, $n_{c}$ is not a measurable quantity. Instead the number of tracks in a jet is measured, which is a proxy for $n_{c}$. Therefore the uncertainties associated with the measurement of $n_{trk}$ must also be considered \\cite{JetFrag}. These uncertainties were calculated using a Pythia 8 dijet sample with NNPDF 23 and Run 2 data. Track reconstruction efficiency and fake rates are the dominant sources of $n_{trk}$ uncertainties. \n\nThe track reconstruction efficiency is affected by the uncertainty of the description of the ID material in simulation and the modeling of charged-particle interactions with this material. These uncertainties are accounted for by varying the ID material by 5-25\\% (dependent on the region of the detector considered). The difference in the tracking efficiency between the nominal and varied simulation give the uncertainty on the track reconstruction efficiency. Another important source of track reconstruction inefficiency arises in the core of jets. The high density of tracks in the jet cores can cause ID clusters to merge. The fraction of lost tracks due to merging is given by the fraction of tracks that have a charge of two minimum ionizing particles. This quantity is compared between data and simulation resulting in an uncertainty of 0.4\\% on tracks with $\\Delta R < 0.1$. Combining these effects gives a total uncertainty as a function of $p_{T}$ and $\\eta$ that is generally < 2\\% \\cite{JetFrag}. \n\nFake tracks are the other dominant source of $n_{trk}$ uncertainty. Fake tracks are tracks that cannot be associated to a single particle. Often these tracks are a result of random combinations of hits from charged particles that overlap in space. In dense environments, such as the core of jets or high-pileup environments, fake tracks are more likely. Fake tracks are estimated with a control region method which is briefly summarized here \\cite{FakeTracks}. By applying a series of track selections to enrich the fraction of fake tracks (e.g. {$|d_{0}| > 0.1$, track $\\chi^{2}>1.4$, etc) in simulation, templates for fake track parameters are calculated. These templates are then fit to data to determine the fraction of fake tracks. On average the fake rate is found to be 30\\% (independent of $p_{T}$ and $\\eta$).\n\nTo assess the impact of these two detector level uncertainties, tracks are randomly dropped according to the rates described above. Reconstruction and fake uncertainties both lower the number of tracks, hence these uncertainties are one-sided. By dropping tracks in this way a varied $n_{trk}$ distribution is calculated for both uncertainties. The associated per-jet event weights are then calculated in the same way as the modeling weights as:\n\n\\begin{equation}\nw_{i}(n_{c}) = \\frac{P(n_{trk}|<n_{trk}> \\pm \\sigma^{i}_{n_{trk}})} {P(n_{trk}|<n_{trk}>)}\n\\end{equation}\n\n\nAdding the modeling and detector level uncertainties in quadrature gives the overall $n_{trk}$ uncertainty. The effects of the individual uncertainties on the $n_{trk}$ distributions can be seen in Fig ~\\ref{fig:qg_calib}. Fig ~\\ref{fig:qg_calib_ntrk_indiv} shows the $m_{lvqq}$ and $n_{trk}$ distributions for the WCR and TCR before the final likelihood fit. In these plots the $n_{trk}$ uncertainties improve agreement between data and MC. The remaining differences are likely covered by the likelihood fit and improving the analysis itself.  \n\n\\begin{figure}[h!]\n  \\centering\n  \\includegraphics[width=\\hsize]{figures/QGT/extracted_qg.png}\n  \\caption{Unfolded and extracted $n_{c}$ quark and gluon distributions.}\n  \\label{fig:extracted_qg}\n\\end{figure}\n\\FloatBarrier\n\n\\begin{figure}[h!]\n  \\centering\n  \\includegraphics[width=0.45\\hsize]{figures/QGT/C_0ptag2pjet_0ptv_ResolvedWWWCR_lvjj_m_Log.png}\n \\includegraphics[width=0.45\\hsize]{figures/QGT/C_0ptag2pjet_0ptv_ResolvedWWWCR_sigJ1_nTrk_Log.png}\\\\\n   \\includegraphics[width=0.45\\hsize]{figures/QGT/C_0ptag2pjet_0ptv_ResolvedWWTCR_lvjj_m_Log.png}\n \\includegraphics[width=0.45\\hsize]{figures/QGT/C_0ptag2pjet_0ptv_ResolvedWWTCR_sigJ1_nTrk_Log.png}\n \n  \\caption{The distribution of $n_{trk}$ and $m_{WV}$ for the resolved WCR and TCR including systematics from the quark gluon tagger calibration. }\n  \\label{fig:qg_calib}\n\\end{figure}\n\\FloatBarrier\n\n\\begin{figure}[h!]\n  \\centering\n  \\includegraphics[width=0.45\\hsize]{figures/QGT/sigWJ1_nTrkQG_trackeff.png}\n \\includegraphics[width=0.45\\hsize]{figures/QGT/sigWJ1_nTrkQG_fake.png}\\\\\n   \\includegraphics[width=0.45\\hsize]{figures/QGT/sigWJ1_nTrkQG_pdf_up.png}\n \\includegraphics[width=0.45\\hsize]{figures/QGT/sigWJ1_nTrkQG_me_up.png}\\\\\n  \\includegraphics[width=0.45\\hsize]{figures/QGT/sigWJ1_nTrkQG_exp_up.png}\n \n  \\caption{These figures show the impact of the uncertainties on the number of tracks in the leading jet in the sum of the background sample in the Resolved ggF $WW$ SR (a) tracking efficiency (b) fake (c) PDF (d) ME (e) unfolding uncertainties.}\n  \\label{fig:qg_calib_ntrk_indiv}\n\\end{figure}\n\\FloatBarrier\n\n\n\\begin{figure}[h!]\n  \\centering\n  \\includegraphics[width=\\hsize]{figures/QGT/closure_qg.pdf}\n  \\caption{An illustration of the closure test from the central-forward method. Filled squares and circles in the upper panel are the value of $<n_{charged}^{c,f}>$. The open blue points show $<n_{charged}^{q,g}>$ extracted. Open red and black points show $<n_{charged}^{q,g}>$ for the more forward and more central jets extracted from labels directly in simulation. The middle panel shows the ratio of $<n_{charged}^{q,g}>$ for the forward versus central jets and the lower panel shows the ratio for the values extracted and the ones taken directly from simulation for the more forward jets. The extraction method used is possible because the filled red squares and circles are slightly displaced from each other. Closure is given by the fact that the open stars, circles, and up triangles overlap and the open crosses, squares, and down triangles also overlap \\cite{Unfolding}. }\n  \\label{fig:closure_qg}\n\\end{figure}\n\\FloatBarrier\n\\chapter{Quark Gluon Tagger Impact in Diboson Resonance Search}\nUsing the 90\\% WP of the $n_{trk}$ tagger improves $S/\\sqrt{B}$ is $\\sim 3$\\% as shown in Figure \\ref{fig:qg_s_root_b}. Although, $n_{trk}$ is the single most powerful discriminating variable for quark and gluon jets, the addition of other jet variables would improve the classification efficiency. Figure \\ref{fig:quark_gluon_roc_truth} shows the possible improvement of 10\\%  in jet classification using the truth label of the jets to classify jets.  This type of improvement is possible by using variables such as jet width, and energy correlatators. Figure \\ref{fig:qgbdt} shows for a 90\\% quark tagging efficiency for a 200 GeV jet, using a boosted decision tree improves the gluon rejection by $\\sim 10$. Once this tagger is calibrated it would improve the analysis sensitivity of this search.\n\n\\begin{figure}[h!]\n  \\centering\n  \\includegraphics[width=\\hsize]{figures/QGT/s_root_b_truthtag.pdf}\n  \\caption{The top panel shows the distribution of $m_{lvqq}$ with and without requiring jets to be true quarks. The middle panel shows the ratio of the signals and backgrounds with and without requiring jets to be true quarks. The bottom panel shows the change in $S/\\sqrt{B}$ when requiring jets to be true quarks.}\n  \\label{fig:quark_gluon_roc_truth}\n\\end{figure}\n\\FloatBarrier\n\n\\begin{figure}[h!]\n  \\centering\n  \\includegraphics[width=\\hsize]{figures/QGT/bdt.pdf}\n  \\caption{ROC curves for quark gluon tagging BDT (trained using jet substructure variables) and convolutional neural networks (trained using jet images) on (left) 200 GeV and (right) 1000 GeV Pythia jets using jet substructure variables \\cite{qgbdt}. }\n  \\label{fig:qgbdt}\n\\end{figure}\n\\FloatBarrier\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "a7fccd9d8e8bbf9ed3144e0b293778ae9c55a486", "size": 22768, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "quarkgluontagging.tex", "max_stars_repo_name": "tashwoods/thesis2", "max_stars_repo_head_hexsha": "9f0793704f2d0a785a9296cfadd74fdbda79c979", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "quarkgluontagging.tex", "max_issues_repo_name": "tashwoods/thesis2", "max_issues_repo_head_hexsha": "9f0793704f2d0a785a9296cfadd74fdbda79c979", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "quarkgluontagging.tex", "max_forks_repo_name": "tashwoods/thesis2", "max_forks_repo_head_hexsha": "9f0793704f2d0a785a9296cfadd74fdbda79c979", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 99.8596491228, "max_line_length": 1248, "alphanum_fraction": 0.7770115952, "num_tokens": 6169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3176299335587883}}
{"text": "\\section{Introduction}\nComputational models in neuroscience have advanced to the point where untangling neural signals observed at the macroscopic scale in terms of underlying complex neural mechanisms and their values is now possible \\cite{wilson_is_2015}). As nonlinear behavior is inevitably encountered at the microscopic scale of individual neurons, nonlinear neural mass models (NMMs) have emerged as a powerful approach to balance interpretability and biological relevance of computational models. Such models summarize the state of locally interacting neuronal populations with few parameters and a conversion from mean excitation level to mean population response \\cite{freeman_tutorial_1992}. The conversion is typically performed via a nonlinear sigmoid function, whereas the mean firing rates, connection profiles, and membrane potentials are parameterized mathematically to model the lumped activity of particular brain regions\\cite{LopesdaSilva1974, robinson_prediction_2001, Valdes1999}. The Wilson-Cowan single oscillator model \\cite{Wilson1972} has evolved into a family of macroscopic NMMs in recent literature; with derivations for neocortical dynamics \\cite{cowan_wilsoncowan_2016}, controllability of brain networks \\cite{muldoon_stimulation-based_2016}, biomarkers in disease \\cite{Zimmermann2018}, and second order statistics of observed brain signals \\cite{Deco2009, abeysuriya_biophysical_2018, singh_estimation_2020, byrne_next-generation_2019, wang_inversion_2019}.\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.75\\textwidth]{../figures/chapter3/oscillator_unit.png}\n    \\caption{Illustration of a Wilson-Cowan oscillator unit.}\n    \\caption*{\\textbf{A}: Local excitatory-inhibitory subpopulation structure with long range excitation only to the excitatory population. \\textbf{B}: Oscillatory time course with default parameter settings as listed in Table \\ref{tab:oscillator_parameters}, showing inhibitory population slightly lagging behind excitatory activity. \\textbf{C}: Numerical simulation showing that the model is a single frequency oscillator, and at the current parameter regime, there exists a limit cycle stationary point at $E = 0.2$ and $ I = 0.1$. The number of stationary points and their behavior is subject to change depending on the initial conditions of the system.}\n    \\label{fig:unit}\n\\end{figure}\n\n% Removed and merged with next paragraph\n%In a rare occurrence of public introspection amongst computational neuroscientists, Wilson and Niv's work \\cite{wilson_is_2015} questioned whether model fitting is necessary for model-based analysis of fMRI. They addressed the weakness of models having free parameters, and the results of the analysis depend on how free parameters are set. While their work was limited to the context of reinforcement learning and a single learning rate parameter, their conclusion is generalizable to the wider model-based neuroscience field: precise identification of parameters is not always necessary, and it is hard to identify neural correlates with model-based analysis due to sensitivity to parameters. More recently, Hartoyo et al. \\cite{hartoyo_parameter_2019} disseminated the problem of unidentifiabiliy in whole brain models, where different parameters combinations can generate similar model predictions, especially in higher order multi-parameter dynamical systems. It has long been known that fitting of an unidentifiable model to data results in large uncertainties, out of the 22 unknown parameters from the linearized network model implemented by Hartoyo et al., only one parameter was found to be identifiable when fitted to EEG data. Nonetheless, the computational neuroscience field pushed the limit of neuron population level mean field models and extended them to describe neural activity at the whole brain scale.\n\n% Unsolved problem and why is this a problem? \nDespite the prolific use of NMMs for whole brain model-based analysis and the promise of inferring biophysical parameters from observed macroscopic signals, they are still not widely used in practical settings. An introspective  study by some of the leaders in the field questioned whether model fitting is necessary for model-based analysis of fMRI \\cite{wilson_is_2015}. In this study, Wilson and Niv addressed the weakness of models having free parameters, and noted that the results depend on how free parameters are set. While their work was limited to the context of reinforcement learning and a single learning rate parameter, their conclusion is generalizable to the wider model-based neuroscience field: precise identification of parameters is not always necessary, but it is hard to identify neural correlates with model-based analysis due to sensitivity to parameters. More recently, Hartoyo et al. \\cite{hartoyo_parameter_2019} disseminated the problem of unidentifiabiliy in whole brain models, where different parameter combinations can generate similar model predictions, especially in higher order multi-parameter dynamical systems. It has long been known that fitting of an unidentifiable model to data results in large uncertainties; indeed, out of the 22 unknown parameters from the linearized network model implemented by Hartoyo et al., only one parameter was found to be identifiable when fitted to EEG data. \n\nThe essential factor underlying the challenge of inference is the nonlinear nature of NMMs, whose coupling via the connectome leads to well characterized chaotic behavior. This then leads to difficulties in parameter inference and generalizable decoding of neural mechanisms. The saddle point and Hopf bifurcation behavior of the Wilson-Cowan model were described by the original work of Wilson \\& Cowan \\cite{Wilson1972}, the Virtual Brain \\cite{sanz-leon_mathematical_2015} and in reviews \\cite{breakspear_dynamic_2017}. A common observation in such nonlinear systems is that large parameter regimes give uninteresting steady-state behavior, but exhibit discontinuous and abrupt shits to interesting oscillating, unstable or chaotic behavior when network coupling or external driving force parameters push the system over the Hopf bifurcation. During parameter inference, discontinuous switching between regimes and model behavior leads to a non-convex cost function with many local minima. One way to avoid these issues is to set all biophysiological parameters for local populations in a NMM to be near an appropriate Hopf bifurcation point that gives the correct frequency (e.g. alpha band). This is then followed by optimization of the remaining few (global) parameters to fit the second order functional connectivity (FC) metrics such as pairwise correlation or synchrony \\cite{Zimmermann2018, Deco2009, abeysuriya_biophysical_2018, wang_inversion_2019, demirtas_hierarchical_2019, honey_predicting_2009}. Frequently the last piece is achieved via manual grid search. Table \\ref{tab:nmm_pubs} summarizes relevant recent studies that follow this approach.\n\n\\begin{table}\n \\caption{Whole Brain Neural Mass Model Parameter Inference Publications and their performance.}\n \\caption*{This table does not include publications with whole brain mean field models or mechanistic models of neural activity.}\n  \\centering\n  \\begin{tabular*}{\\textwidth}{llll}\n    \\toprule\n    \\cmidrule(r){1-2}\n    Name & Modality  & Target  & Accuracy \\\\\n    \\midrule\n    Zimmerman et al. \\cite{Zimmermann2018} & fMRI & Correlation FC & $r=0.57$  \\\\\n    Honey et al. \\cite{honey_predicting_2009} & fMRI & Correlation FC & $ r=0.48$ \\\\\n    Demirtas et al. \\cite{demirtas_hierarchical_2019} & fMRI & Correlation FC & $r=0.743$ \\\\\n    Wang et al. \\cite{wang_inversion_2019} & fMRI & Correlation FC & $r=0.46$ \\\\\n    Schirner et al. \\cite{schirner_inferring_2018} & fMRI & BOLD Time series & $r=0.50$ \\\\\n    Falcon et al. \\cite{falcon_virtual_2015} & fMRI  & Correlation FC  &  $r = 0.29$  \\\\\n    Abeysuriya et al. \\cite{abeysuriya_biophysical_2018} & MEG & Synchrony FC & $r = 0.48$ \\\\\n    Deco et al. (2017) \\cite{deco_single_2017}  & MEG & Envelope FC & $r=0.45$ \\\\\n    Deco et al. (2009) \\cite{Deco2009} & fMRI & Kuramoto order parameter & Not reported \\\\\n    Hadida et al. \\cite{hadida_bayesian_2018} & MEG & Envelope FC & $r=0.42$ \\\\\n    \\bottomrule\n  \\end{tabular*}\n  \\label{tab:nmm_pubs}\n\\end{table}\n\nNotwithstanding these challenges, recent NMM approaches have proliferated and demonstrated inference in healthy and diseased brains \\cite{honey_dynamical_2008,alstott_modeling_2009,haan_activity_2012,yang_functional_2016,Zimmermann2018,singh_estimation_2020}. Therefore it is opportune and topical to ask, in which respects such methods may be considered useful, and where would they fail? Is it sufficient to select parameters that can only reproduce 2nd order covariances rather than the primary signal? In that case, what can the manually selected parameters of the local mass tell us about biological mechanisms and processes in play? Can the above 2-step optimization (local neural masses fit to desired brain rhythm, and coupling parameters to FC) give a good or even unique solution? Finally and most importantly, current methods ignore the regional variations in frequency spectra of brain activity; hence it would be necessary to understand whether the model parameters optimized for FC metrics translate well to the frequency spectrum?\n\nIn this work, we will investigate the difficulties faced in gradient descent based approaches to parameter inference of current networked NMMs. We present a systematic examination of the Wilson-Cowan model, chosen as a canonical exemplar of the approach taken by most recent models. First, we examine the performance of a single Wilson-Cowan oscillator unit when fitting to broadband spectra. We implemented Markov Chain Monte Carlo (MCMC) sampling to perform all inference. Our first goal is to test whether MCMC sampling of the local Wilson-Cowan model can converge to a reasonable posterior distribution for its parameters. We then implement the whole-brain networked Wilson-Cowan model, where local neural masses are coupled to each other via fiber connectivity, with a global coupling constant that controls the weight given to local versus remote signal.  Again we use MCMC to sample the posterior distribution of the parameters. The likelihood function here is based, like prior studies, on 2nd order statistics of MEG data, like  coherence-based functional connectivity (COH) and amplitude envelope correlation (AEC). Our second goal is to verify whether the global parameters can be appropriately optimized in order to reproduce these FC matrices, and whether those inferred parameters also then produce the correct set of regional power spectra spanning the entire frequency range, from delta to gamma.\n\n\\section{Methods}\n\n\\subsection{Experimental Procedure}\n\n\\subsubsection{Study Cohort}\nWe acquired MEG, anatomical MRI, and diffusion MRI for 36 healthy adult subjects (23 males, 13 females; 26 left-handed, 10 right-handed; mean age 21.75 years (range: 7–51 years). All study procedures were approved by the institutional review board at the University of California at San Francisco (UCSF) and are in accordance with the ethics standards of the Helsinki Declaration of 1975 as revised in 2008.\n\n\\subsubsection{MRI}\nA 3 Tesla TIM Trio MR scanner (Siemens, Erlangen, Germany) was used to perform MRI using a 32-channel phased-array radiofrequency head coil. High-resolution MRI of each subject's brain was collected using an axial 3D magnetization prepared rapid-acquisition gradient-echo (MPRAGE) T1-weighted sequence (echo time [TE] = 1.64 ms, repetition time [TR] = 2,530 ms, TI = 1,200 ms, flip angle of 7°) with a 256-mm field of view (FOV), and 160 1.0-mm contiguous partitions at a 256×256 matrix. Whole-brain diffusion weighted images were collected at b = 1000s/mm2 with 30 directions using 2-mm voxel resolution in-plane and through-plane. The T1-weighted images were then parcellated into 68 cortical and 18 subcortical regions using the Desikan-Killiany atlas available in Freesurfer \\cite{Fischl2012, Desikan2006}, the voxel labels were used to identify modeled dipoles in MEG source Reconstruction.\n\n\\subsubsection{Structural Connectivity Network}\nTo construct high resolution average connectivity matrices with the same Desikan-Killiany parcellations, we obtained openly available data from the Human Connectome Project \\cite{McNab2013}. Subject specific structural connectivity was computed using diffusion MRI data: \\emph{Bedpostx} was used to determine the orientation of brain fibers in conjunction witht \\emph{flirt}, as implemented in the FSL software \\cite{jenkinson_fsl_2012}. In order to determine the elements of the adjacency matrix, we performed tractography using \\emph{probtrackx2}. We initiated 4,000 streamlines from each seed voxel corresponding to a cortical or subcortical gray matter structure and tracked how many of these streamlines reached a target gray matter structure. The weighted connection between the two structures $c_{j,k}$ was defined as the number of streamlines initiated by voxels in region $j$ that reach any voxels in region $k$, normalized by the sum of the source and target region volumes ($c_{j,k} = \\frac{streamlines}{v_j + v_k}$). This normalization prevents large brain regions from having high connectivity simply due to having initiated or received many streamlines.\n\n\\begin{figure}[ht]\n    \\centering\n    \\captionsetup{justification=centerlast}\n    \\includegraphics[width=\\textwidth]{../figures/chapter3/oscillator_full_10hz.png}\n    \\caption{MCMC sampling of posterior distribution when maximizing likelihood to average MEG power spectrum ($L_{\\textrm{PSD}}$).}\n    \\caption*{Corner plot of the posterior marginal distributions for parameters $\\tau_e$, $\\tau_i$, and $P$ when initiating from default values (\\textbf{A}) or Hopf bifurcation point (\\textbf{B}) showing the probability densities of accepted parameter samples. The mean, and bounds for 95\\% confidence intervals are shown on top of each column for each parameter. \\textbf{C} and \\textbf{D} illustrates the average MEG spectrum (green) alongside the oscillator model spectra (blue) simulated with the posterior mean values shown from the corner plots above.}\n    \\label{fig:oscillator_full}\n\\end{figure}\n\n\\subsubsection{MEG Acquisition and Source Reconstruction}\nMEG recordings were acquired at UCSF using a 275-channel CTF Omega 2000 whole-head MEG system from VSM MedTech (Coquitlam, BC, Canada). All subjects were instructed to keep their eyes closed for 5 min while their MEGs were recorded at a sampling frequency of 1,200 Hz. Then, all recordings were downsampled to 600 Hz and digitally filtered to remove DC offset and other noisy artifact outside of the 1 to 160Hz bandpass range prior to source reconstructions. To \"invert\" our sensor space recordings to the MRI voxels, we used an adaptive spatial filtering algorithm from the NUTMEG software tool \\cite{dalal_nutmeg:_2004}. To prepare for source localization, all MEG sensor locations were co-registered to each subject's anatomical MRI scans. The lead field (forward model) for each subject was calculated in NUTMEG using a multiple local-spheres head model (three-orientation lead field) and an 8mm voxel grid which generated more than 5,000 dipole sources, all sources were normalized to have a norm of 1. Finally, the MEG recordings were projected into source space using a beamformer spatial filter. Source estimates tend to have a bias towards superficial currents and the estimates are more error-prone when we approach subcortical regions, therefore, only the sources belonging to the 68 cortical regions were selected to be averaged around the centroid.\n\n\\subsubsection{Functional Connectivity}\nTo analyze static functional connectivity in the MEG data and in the model, we computed both $\\alpha$ band coherence (COH) and amplitude envelope correlation (AEC) with MNE Python's connectivity module implementations \\cite{GramfortEtAl2013a}. First, multi-taper power spectrum densities were computed with digital prolate spheroidal sequences (DPSS) windows, and adaptive weights were used to combine the tapered spectra into full power spectral densities (PSDs). Finally for data in parcellated brain regions $i$ and $j$, with estimated cross- and power spectral densities $S_{ij}$ and $S_{ii}$, $S_{jj}$, the coherence between regions $i$ and $j$ is given by: \n\n\\begin{equation}\n    C_{ij} = \\frac{|E[S_{ij}]|}{\\sqrt{E[S_{ii}] * E[S_{jj}]}}\n\\end{equation}\n\nTo compute the amplitude envelope correlation (AEC), narrow band MEG time courses were obtained by bandpass filtering between 8 and 12 Hz. Hilbert transformed analytic signal corresponding to the orthogonalized narrow band time courses were computed to account for spatial leakage and zero-lag correlations. As recommended by \\cite{hipp_large-scale_2012, brookes_measuring_2011, deco_single_2017}, MEG resting-state FC is maximized by solely considering ultra-slow fluctuations of the amplitude envelope. Therefore, a 4th order low-pass Butterworth filter at 0.2Hz is implemented, obtaining an envelope time course with alpha band carrier frequency, Finally, the Pearson correlation between every pair of envelope time courses were computed.\n\n\\subsubsection{Model Parameter Inference with Markov Chain Monte Carlo Sampler}\nMarkov Chain Monte Carlo (MCMC) sampling is a valuable tool in modern machine learning techniques, with Metropolis-Hasting \\cite{hastings_monte_1970} and Gibbs \\cite{geman_stochastic_1984, gelfand_sampling-based_1990} samplers being the most widely used algorithms. Such algorithms allow marginalization over parameters and use a Bayesian inference framework to estimate the full posterior distribution of model parameters. Specifically, the samplers are initialized at a chosen initial parameter value and is allowed to randomly step to nearby new values. The Markov chain over the sampling process evaluates whether the random steps should be accepted as potential solutions, with the goal of accepting samples based on a probability distribution that resembles the true stationary distribution resembling some data, and the mean of our accepted samples converging to the true expected value given enough Markov chain steps. To condition a probability distribution over model parameters $\\theta$, we define a conditional likelihood function based on a Gaussian:\n\n\\begin{equation}\n\\label{eq:ll}\n    L_{\\Psi} = \\log P(y | \\theta)_{\\Psi} = - \\frac{1}{2} \\sum_n [\\frac{(\\Psi_{\\textrm{MEG}} - \\Psi_{\\textrm{model}})^2}{\\sigma_n^2} + \\log \\sigma_n^2] \\\\\n\\end{equation}\n\nwhere the log likelihood function $L_{\\Psi}$ evaluates the difference between the observed data and the model's output for a metric $\\Psi$: $L_{\\textrm{PSD}}$, $L_{\\textrm{C}}$, and $L_{\\textrm{AEC}}$, corresponding to power spectral density, coherence, and amplitude envelope correlation, respectively.\n\nFor all model parameters $\\theta$, we will use uniform (\"uninformative\") distributions as prior distributions, which will allow samplers to randomly explore the nearby parameters from its initial positions. As the samplers accept and reject newly sampled parameters, a full posterior probability distribution will be constructed, and the mean of this posterior distribution will be the most probable model parameters given the observed data.\n\n\\subsection{Wilson-Cowan Local Oscillator Model}\n\n\\begin{table}[]\n    \\centering\n    \\caption{Default parameters for the Wilson-Cowan oscillator model.}\n    \\caption*{The excitatory driving force $P$ and time constants $\\tau_e$ and $\\tau_i$ are inferred during our experimentation, and their initial values are shown here. All default values are set such that small inputs would cause the system to oscillate (near the Hopf bifurcation point).}\n    \\begin{tabular}{lll}\n    \\toprule\n    \\cmidrule(r){1-2}\n    Symbol                 &  Physiological Parameter     & Value \\\\\n    \\midrule\n    $a_e$, $a_i$           &  Response function max slope & 1.3, 2 \\\\\n    $\\theta_e$, $\\theta_i$ &  Response function threshold & 4, 3.7 \\\\\n    $c_1$, $c_2$           &  Excitatory coupling         & 16, 12 \\\\\n    $c_3$, $c_4$           &  Inhibitory coupling         & 15, 3  \\\\\n    $r_e$, $r_i$           &  Refractory periods          & 1, 1 \\\\\n    $\\tau_e$, $\\tau_i$     &  Time constants              & 8 ms \\\\\n    $P$                    &  External driving force      & 1.25 \\\\\n    \\bottomrule\n    \\end{tabular}\n    \\label{tab:oscillator_parameters}\n\\end{table}\n\nThe original derivation of the single oscillator Wilson-Cowan model is illustrated in \\cite{Wilson1972}. This model is capable of producing oscillations of the excitatory and inhibitory populations typically seen in MEG. Many variants of this model exist; here we employ an extremely simplified model described in (\\cite{Deco2009}), to highlight the importance of delays and coupling in the brain. For local oscillations, two subpopulation of neurons are considered: an excitatory subpopulation ($E$), and an inhibitory subpopulation ($I$) that tends to drive the system towards quiescence. Given static local subpopulation couplings, varying firing amongst the two subpopulation of neurons, and an external driving force controlling the excitation, the model is able to describe the temporal dynamics of a mean field of neurons. Additionally, Wilson \\& Cowan introduced \"response functions\" where local firing-thresholds within each subpopulation control the response of initially quiescent neurons to excitation. They are modeled as sigmoidal functions:   \n\n\\begin{equation}\n\\label{eq:sigmoid}\nS(x) = \\frac{1}{1+e^{-a(x-b)}} - \\frac{1}{1+e^{a b}}\n\\end{equation}\n\nWhere $a$ and $b$ are parameters detailing the sigmoidal response function's maximum slope and the position of maximum slope respectively. Finally, with $E(t)$ and $I(t)$ representing the ratio of neurons firing for the two subpopulations respectively, the original Wilson-Cowan model is defined as:\n\n\\begin{equation}\n    \\label{eq:wco_ex}\n\\tau_e \\frac{dE_{j}(t)}{dt} = -E_{j}(t) + (1 - r_e E_{j}(t)) \\, S_e(c_1 E_{j}(t) - c_2 I_{j}(t) + P) + \\epsilon_{j} (t)\n\\end{equation}\n\n\\begin{equation}\n\\label{eq:wco_in}\n\\tau_i \\frac{dI_{j}(t)}{dt} = -I_{j}(t) + (1 - r_i I_{j}(t)) \\, S_i(c_3 E_{j}(t) - c_4 I_{j}(t)) + \\epsilon_{j} (t)\n\\end{equation}\n\nWhere $\\tau_e$ and $\\tau_i$ are time constants, the length of the refractory periods are parameterized by $r_e$ and $r_i$, $c_{1,2,3,4}$ are parameters representing the strength of excitatory-excitatory, inhibitory-excitatory, excitatory-inhibitory, and inhibitory-inhibitory connections respectively. The quantity $\\epsilon_{j} (t)$ is Gaussian noise; following Muldoon et al. \\cite{muldoon_stimulation-based_2016}, the noise is scaled by $0.00001$ to ensure accuracy in step-wise integration of the differential equations. Lastly, $P$ is the external driving force pushing neurons out of quiescence. In this formulation, the time constants $\\tau_e$ and $\\tau_i$ together with the external drive parameter $P$ controls the Hopf bifucation point of this model, and all local connection strengths are held constant during inference. A summary of all model parameters is listed in Table \\ref{tab:oscillator_parameters} and the model's time course and stationary points are illustrated in Figure \\ref{fig:unit}. The parameter settings listed here are consistent with the limit cycle settings as published originally by Wilson \\& Cowan \\cite{Wilson1972} and the network controllability work by Muldoon et al.  \\cite{muldoon_stimulation-based_2016}.\n\n\\subsection{Network Extension of Wilson-Cowan Model}\nTo extend this single frequency oscillator model to the whole brain network, a term resembling long range white matter connections given by the connectivity matrix $A$ is introduced:\n\n\\begin{equation}\n    \\label{eq:wcn_ex}\n\\tau_e \\frac{dE_{j}(t)}{dt} = -E_{j}(t) + (1 - r_e E_{j}(t)) \\, S_e(c_1 E_{j}(t) - c_2 I_{j}(t) + c_5 \\sum_{k} A_{jk} E_{k}(t - \\tau_d^k) + P) + \\epsilon_{j} (t)\n\\end{equation}\n\n\\begin{equation}\n\\label{eq:wcn_in}\n\\tau_i \\frac{dI_{j}(t)}{dt} = -I_{j}(t) + (1 - r_i I_{j}(t)) \\, S_i(c_3 E_{j}(t) - c_4 I_{j}(t)) + \\epsilon_{j} (t)\n\\end{equation}\n\nHere, the connectome delay term $\\tau_d^k$ accounts for propagation time between distant brain regions, and is proportional to the fiber distance between them. Following prior literature \\cite{muldoon_stimulation-based_2016} the model is pushed into an oscillatory regime by setting either $P$ or coupling strength ($c_5$) beyond the Hopf bifurcation point. Therefore,  like all pre-existing literature, only the global parameters that affect the dynamics in the default local parameter regime are inferred. \n\nThe network model's simulation is complicated by the delay introduced by long range connections at each time step. In (\\cite{hadida_bayesian_2018}), this problem was simplified by simulating without noise and the use of an average propagation delay. However, they still encountered quadratic increases in complexity and doubling in computation time. Specifically, at each time step size $h$, the sum of delay terms in each equation needs to be computed at time $t$ and $t+h$, and interpolated for each unique delay values between the current time step and the maximum delay. This step size is subject to further decrease if a noise term is introduced to the equations, which further increases computational cost. Additionally, initialization of delayed nonlinear system of equations is a sensitive operation. Delayed systems require a smooth function for initialization to be defined over $[t_0 - \\tau_{max} t_0]$, where $t_0$ is the initial time and $\\tau_{max}$ is the largest delay. Additionally, the history before time point $t_0$ should itself be a solution of the system, which makes this circular and impossible. There are no good work-arounds to this problem, hence following \\cite{hadida_bayesian_2018}, we set the initial conditions for all brain regions to be constant and nodes are initially disconnected from the network for a period of time equal to maximum delay. Additionally in our implementation, we interpolate past solutions for all unique delays in our network and the full solution with an adaptive-step Runge-Kutta integrater of order 8 \\cite{hairer_analysis_2008}.\n\n\\section{Results}\n\n\\subsection{Oscillator Model Performance}\n\n\\begin{figure}[htbp]\n    \\centering\n    \\includegraphics[width=\\textwidth]{../figures/chapter3/gridsearch_fullfit.png}\n    \\caption{Exhaustive grid search of the local oscillator model.}\n    \\caption*{Parameters affecting Hopf bifurcation point and oscillatory frequency were iteratively computed over a 3-dimensional grid to look for an optimal solution that matches closely with the observed average MEG spectra, and the parameters resulting in the highest Pearson's correlation between power spectra are shown here.}\n    \\label{fig:grid_search}\n\\end{figure}\n\nFigure \\ref{fig:oscillator_full} shows the oscillator model solutions with MCMC sampler's posterior means for each parameter. Here, we only focused on the three parameters affecting oscillatory frequency and Hopf bifurcation point. While all parameters received non-informative flat priors, the samplers arrived at posterior distributions based on the log likelihood function in \\ref{eq:ll} for average MEG power spectrum. We initiated our samplers under two conditions: default parameter values as described in \\cite{muldoon_stimulation-based_2016} ($\\tau_{e/i} = 8$ and $P=1.25$) or near a 10Hz oscillatory Hopf bifurcation point ($\\tau_e = 3.0$, $\\tau_i = 3.6$, and $P=1.1$). Under both scenarios, we see wide confidence intervals for both $\\tau_i$ and $P$, despite $\\tau_e$ having a narrower distribution, the samplers for both $\\tau_e$ and $\\tau_i$ did not accept parameters far away from their initial positions. Moreover, $\\tau_i$ seems to have more than one highly probable value. Using the posterior means as model parameter inputs, the simulation produced a power spectrum with 15Hz peak and subsequent harmonic peaks at 30 and 45 Hz when initiated from default values. While the most notable peak in a human MEG spectrum is the alpha peak around 10Hz, the likelihood maximization mechanism arrived at a solution that captured the 10Hz alpha peak only when initiated near a 10Hz oscillatory regime. This model realization also produces many secondary higher harmonics which are not present in empirical spectra.\n\nStates of quiescence, transience, steady-state, and limit cycle in dynamical systems used by NMMs are clearly illustrated and reviewed in (\\cite{breakspear_dynamic_2017}) and (\\cite{sanz-leon_mathematical_2015}), where small changes in model parameters or initial conditions can affect the behavior of the model output - indicating the model's excessive sensitivity to parameters. Accordingly, our samplers also appeared to be stuck in a certain regime and reject samples that are outside of the preset limit cycle regime as set by default parameters. Figure \\ref{fig:grid_search} shows the 6 most closely-matching spectra found by exhaustive grid search. These results suggest that there exist different sets of parameters that can produce oscillations at any of the notable frequency peaks, and highlight the problem of identifiability. We see two sets of parameters producing notable peaks at 20Hz, and a set of parameter producing a 15Hz oscillation that is different from the set obtained from MCMC sampling. \n\nThese results highlight two different problems in inference: the inability to escape initial regime or local minimum; and the presence of several equally good local minima that produce widely divergent behavior.\n\n\\begin{figure}\n    \\centering\n    \\captionsetup{justification=centerlast}\n    \\includegraphics[width=\\textwidth]{../figures/chapter3/oscillator_periodic_10hz.png}\n   \\caption{MCMC sampling of posterior distribution when maximizing likelihood to average periodic power spectrum ($L_{\\textrm{PSD}}$).}\n    \\caption*{Corner plot of the posterior distributions for parameters $\\tau_e$, $\\tau_i$, and $P$ when initiating from default values (\\textbf{A}) or Hopf bifurcation point (\\textbf{B}) showing the probability densities of accepted parameter samples. \\textbf{C} and \\textbf{D} illustrates the average MEG spectrum (green) alongside the oscillator model spectra (blue) simulated with the posterior mean values shown from the corner plots above.}\n    \\label{fig:oscillator_periodic}\n\\end{figure}\n\n\\subsubsection{Fitting to spectral peaks instead of wideband spectra}\nA broadband frequency spectrum contains a mixture of both a periodic component, and an aperiodic component ($\\frac{1}{f}$-like fall off) that does not contribute to frequency-specific features \\cite{donoghue_parameterizing_2020}. Since our oscillator model can only produce one principal frequency, we implemented the \\emph{fitting oscillations \\& one over f} (FOOOF) algorithm from Donoghue et al. \\cite{donoghue_parameterizing_2020} to obtain a periodic frequency power spectrum. Figure \\ref{fig:oscillator_periodic} shows the same posterior sampling procedure's results when maximizing likelihood to only the principal periodic component of the spectrum, and the bottom panels show the average MEG and model-simulated spectrum without the aperiodic component. Changing the objective function from the full frequency spectrum to the periodic frequency spectrum changed the parameter space landscape. In this periodic frequency spectrum objective function sampling regime, we see that the samplers were able to explore a much wider parameter range and did not get stuck in the initial regime. However, the $95\\%$ confidence intervals around the posterior means for both time constant parameters are large, with upper bounds of about $+4$ and lower bounds of about $-3$. Suggesting there is still large uncertainty even if a point estimate method for parameter inference was implemented, especially with parameters $\\tau_i$ and $P$ showing hints of bimodal distributions. Lastly, despite a smoother surface for the samplers, the final posterior means did not produce spectra that reproduced most notable frequency peaks in the observed MEG spectrum for either initial condition. Similar to previous results, all inferred local models appear to show very high level of secondary harmonics which are not observed in empirical spectra. \n\n\n\\begin{figure}[htbp]\n    \\centering\n    \\includegraphics[scale=0.6]{../figures/chapter3/p_behavior.png}\n    \\caption{Network model behavior in response to external driving force}\n    \\caption*{Panels showing network model's time course, frequency spectrum, and coherence functional connectivity from top to bottom with increasing external driving force parameter $P$. Simulations are performed with default parameter values and $c_5 = 1.5$, the model is dominated by noise at low $P$, but switches to an oscillatory regime when $P$ crosses the Hopf bifurcation value. The example time course is shown for one brain region only, whereas the frequency spectrum is shown for all brain regions.}\n    \\label{fig:p_behavior}\n\\end{figure}\n\n\\begin{figure}[htbp]\n    \\caption{Network Wilson Cowan model sampling results for one representative subject.}\n    \\caption*{Top row shows the results for coherence maximum likelihood sampling, broadband AEC sampling in the middle, and bottom row shows the results for narrowband AEC maximum likelihood sampling. Left column shows the sampled posterior distributions for the global coupling parameter $c_5$, with the sampled mean and 95\\% confidence intervals displayed. The middle column shows the network model simulated FC matrices with the posterior mean, and right column shows the scatter plot and linear regression line for the FC matrix entries. Both parameter posteriors achieved near zero slope for the linear fit.}\n    \\label{fig:networkc5}\n\\end{figure}\n\\clearpage\n\\begin{figure}[h!]\n\t\\ContinuedFloat\n\t\\captionsetup{labelformat=adja-page}\n    \\centering\n    \\includegraphics[width=\\textwidth]{../figures/chapter3/network_c5_fits.png}\n    \\caption[]{}\n\\end{figure}\n\n\n\\subsection{Network Model Performance}\nExisting literature expanding neural mass models to the network level fixes the local parameters of neural masses ($c_1$, $c_2$, $c_3$, and $c_4$) to be equal at all nodes in the network. Hence these identical oscillators can only produce diverse dynamics because of noisy input, heterogeneous connectome coupling and concomitant delays. For fMRI modeling, a Balloon-Windkessel hemodynamic model \\cite{buxton_dynamics_1998, friston_nonlinear_2000} is usually layered on top of the NMMs for parameter optimization (For example, see \\cite{Zimmermann2018}). This adds another set of model parameters and abstractions to describing observed functional phenomenon with mean field models. On the other hand, encephalography based modeling wraps another metric on top of the NMM outputs, such as kuramoto coupling parameters in \\cite{Deco2009}.  Here we will focus on the Wilson-Cowan model only, examining whether they are good basis for network mdoeling.\n\n\\subsubsection{Effect of global parameters}\nFirst we demonstrate the effect of external driving force $P$ on the networked model's time course, spectra and network structure (FC) in Figure \\ref{fig:p_behavior}, using default values for all parameters. With increasing $P$, the networked system transitions from uncorrelated activity to oscillatory behavior. The latter point is better observed in the coherence FC matrices shown at the bottom. Interestingly, FC became over-saturated if the value of $P$ deviated far from the default operating range (e.g. $P>1.5$). Next, we show a similar set of analysis in Figure \\ref{fig:c5_behavior}, where we vary global coupling $c_5$ while holding all other parameters constant and $P$ is kept at the Hopf bifurcation point. Surprisingly, varying $c_5$ does not change the time course or shift the dominant oscillatory component of the spectra at all. But as the connectomes' connections contributes more to the model dynamics, coherence FC drastically changes despite minuscule detectable changes to the underlying dynamics.\n\n\\begin{figure}[htbp]\n    \\centering\n    \\captionsetup{justification=centerlast}\n    \\includegraphics[width=\\textwidth]{../figures/chapter3/individual_c5_spectra.png}\n    \\caption{Comparison between MEG spectra and network model simulated spectra for 4 subjects.}\n    \\caption*{Model simulated spectra were computed with the posterior mean for global coupling parameter $c_5$ after MCMC sampling. The average spectra from all cortical brain regions is shown as lines, and the standard deviation summarized from all regions is shown as shaded fillings. Source localized MEG spectra is shown in blue, coherence parameter simulated spectra is shown in red, narrowband and broadband AEC parameter simulated spectra are shown in black and green respectively. All spectras were normalized by their minimum and maximum values to be between 0 and 1 for equal visualization scale.}\n    \\label{fig:c5_spectra}\n\\end{figure}\n\n\\subsubsection{Inference of global coupling $c_5$ depends on objective function}\n\nFollowing existing network modeling publications, we first performed inference of the global coupling parameter $c_5$ with MCMC. We fixed the time constants $\\tau_e$ and $\\tau_i$ so that each oscillator has a base oscillating frequency of near 10Hz, and we fixed $P = 1.1$ to be right below the Hopf bifurcation point so the network's dynamics is purely driven by connectivity. The top panel of Figure \\ref{fig:networkc5} shows the second order statistics - coherence and AEC - of source localized MEG in the $\\alpha$ band for the $68$ cortical regions parcellated according to the Desikan-Killiany atlas \\cite{Desikan2006}. Bottom of Figure \\ref{fig:networkc5} shows the posterior distributions of $c_5$ under three likelihood functions associated with fitting for COH (top) and AEC (middle) and alpha band AEC (bottom). While MCMC produced reasonably concentrated posteriors with narrow confidence intervals in all three cases, the resulting FC matrices do not resemble empirical FC matrices. The hemispheric block structure and sparsity seen in MEG coherence FC are absent in model COH. Simulated AEC is appropriately sparse but also does not resemble MEG AEC. The scatter plots shown alongside also do not support successful prediction of either COH or AEC. Note also that the objective being fit - AEC vs COH dramatically changes the optimal value of inferred $c_5$. Coherence and narrowband AEC fitting led to a lower estimated global coupling value, $c_5 \\approx 1.5-1.6$ , whereas fitting to AEC (green) led to higher $c_5 \\approx 9$. This is highly problematic, and further highlights the extreme parameter sensitivity of coupled NMMs - this time under differing objective functions.\n\n\\subsubsection{Networked metric derived frequency spectrum}\nAt its essence, FC matrices are second order statistics computed from time course activity over time, whether recordings like MEG or simulated activity with our network NMM. And here we see that changing the maximum likelihood definition or objective function in parameter inference drastically affects the gradients and eventual posterior parameter values. For modeling based analysis to claim its parameters describe the full relationship between some phenomenon and brain activity, we believe the network model should reproduce characteristic spectral patterns as observed in MEG recordings.\n\nWe explored whether the networked model inferred to fit the second order FC is capable of reproducing the primary first order statistics, i.e. node-evel power spectra. As shown in the four individual cases of Figure \\ref{fig:c5_spectra}, connectome coupling with delays and noise certainly expanded the networked model's spectral repertoire. Recall that the local time constants were previously fixed to produce oscillations of 10Hz, hence the networked spectra using global coupling $c_5$ inferred using FC also produces an alpha peak. Interestingly, optimal $c_5$ fit to $\\alpha$-band AEC produced nearly identical spectra up to $\\alpha$ frequencies in all brain regions, and only showed regional diversity in the $\\beta$ band. Unfortunately, none of the models inferred on FC can be said to properly reproduce regional wideband power spectra. The only one that looks remotely plausible is the one fitted to COH.\n\n\\subsubsection{Full inference of networked NMM}\nThe above results demonstrate that the inference approach adopted in current literature, of fixing some parameters to produce the correct oscillation frequency, and others to match second order FC, is problematic, and does not in fact reproduce first order statistics of node-level wideband spectra. Therefore we now attempt a full inference of all model parameters starting from their default values as listed in the Table \\ref{tab:oscillator_parameters}. We expect that increasing the dimensionality of the parameter space can improve model performance, but traversing between oscillatory, quiescence, and transience activity regimes during sampling may cause the samplers to be stuck in local minima. We first initialize $\\tau_e$ and $\\tau_i$ to $8$ms with a small variation for each sampler, and repeated MCMC. These initial model parameter values are those used in \\cite{muldoon_stimulation-based_2016}, where a 20Hz limit cycle regime occurs. In this high dimensional non-linear network model, inferring high number of parameters with a non-convex objective function gradient is difficult, and was not performed in \\cite{muldoon_stimulation-based_2016}, who assumed the 20Hz limit cycle parameter regime to be \"biophysiological\". Here we want to check if the MCMC samplers can find posterior parameter distributions that resemble observed MEG data.\n\nFigure \\ref{fig:coh_hopf} and Figure \\ref{fig:aec_hopf} illustrates the sampler's inability to survey the 4 dimensional parameter space set by the network model for alpha band coherence or AEC. In Figure \\ref{fig:coh_hopf}, neither $\\tau_e$ or $\\tau_i$ escaped their initial positions near 8ms. Global coupling $c_5$ and external driving force $P$ had high uncertainties as indicated by their 95\\% confidence intervals. As mentioned above, the initialization puts the model into a 20Hz oscillatory regime, and the samplers were not able to arrive at a viable solution for $\\alpha$ band coherence. The simulated coherence shown in Figure \\ref{fig:coh_hopf} in combination with the spectra shown in Figure \\ref{fig:psd_hopf} shows that there was no oscillations or variability near 10Hz.\n\nSimilarly, Figure \\ref{fig:aec_hopf} shows the same failure of samplers escaping its initial positions. However, in this case, the posterior distributions for all parameters had extremely narrow 95\\% confidence intervals. Despite this certainty, the simulated AEC matrix had much higher values than, and little to no significant correlation with, empirical AEC. The corresponding power spectra (green in Figure \\ref{fig:psd_hopf}) show no $\\alpha$ peak, being unable to move away from the initial 20Hz oscillations. Two subjects' model spectra showed no variability between regions and no obvious peaks whatsoever. Lastly, the spectra produced by parameters sampled for alpha band AEC were also stuck near the initial values, producing similarly implausible spectra as other fits described above. \n\n\\begin{figure}[htbp]\n    \\centering\n    \\captionsetup{justification=centerlast}\n    \\includegraphics[width=\\textwidth]{../figures/chapter3/individual_hopf_spectra.png}\n   \\caption{Comparison between MEG spectra and posterior mean global parameters simulated spectra for 4 subjects.}\n    \\caption*{Model simulated spectra were computed with the posterior means for ${\\tau_e, \\tau_i, c_5, P}$ after MCMC sampling. The average spectra from all cortical brain regions is shown as lines, and the standard deviation summarized from all regions is shown as shaded fillings. Source localized MEG spectra is shown in blue, coherence parameters simulated spectra is shown in red, narrowband and broadbanc AEC parameters simulated spectra is shown in black and green respectively. All spectras were normalized by their minimum and maximum values to be between 0 and 1 for equal visualization scale.}\n    \\label{fig:psd_hopf}\n\\end{figure}\n\nBased on the existing literature's avoidance of this parameter fitting procedure for network NMMs, and the fact that we are implementing a barebones approach with no adjustments to the mean firing rate model, we did not expect the network NMM to perform well in capturing neural activity statistics. Typically, a more specified model is required to produce any meaningful statistics. We've shown that a typical oscillator unit produces limit cycle activity at a single frequency as specified by the model parameters, and adding a network component to the model does not easily translate to network metrics being produced by the network model. Furthermore, the existing practice of setting model parameters near an oscillatory regime and searching for parameters that fits some neural activity metric well doesn't take into account the problem of unidentifiable parameters. Lastly, network models are high in dimensionality, making parameter posterior sampling a consuming and unpredictable exercise. And by limiting every node to have identical parameter values to decrease parameter inference complexity is not biologically realistic and produces irrelevant results. \n\n\\section{Discussion}\n\\subsection{NMM Based Analysis}\nParameter inference of a full brain network neural mass model is rarely attempted in the computational neuroscience field. The complexity due to their nonlinearity and network size with numerous delays, combined with the tangled nature of neurological recordings, makes the optimization of these NMMs a nearly impossible task. The first thing we've shown here is that an oscillating Wilson-Cowan neural population has a limit cycle activity for a specific frequency given a specific set of parameters. Extending this model to the network scale by introducing delays and connectivity, but fixing all nodes to have identical parameters for computational tractability does not necessarily provide the broadband spectrum that is characteristic of observed encephalography recordings.\n\nIn most NMM analysis (see Table \\ref{tab:nmm_pubs}), the comparisons are made to fMRI BOLD functional connectivity, which has limited temporal resolution, and recorded neural dynamics are limited to below 1Hz. Whereas NMMs mean firing rate outputs are simulated with millisecond time-steps, to compensate for the mismatch in data type and temporal resolution, a Balloon-Windkessel hemodynamics model \\cite{friston_nonlinear_2000, deco_resting-state_2013} is used to transform the model outputs to BOLD signals (For example, see \\cite{deco_resting-state_2013, deco_how_2014}) for functional connectivity comparison. Practically, parameters for the NMM is first fitted either by exhaustive grid search or constrained optimization, followed by another model fitting for the BOLD signal transformation. The two layers or model fitting leads to low interpretability of final parameters, and low correlations with high variances in parameter distribution on the group level leads to uncertainties about any result.\n\nIn other publications, for the sake of computational tractability, a more simplistic Wilson Cowan model variant with more varied model behavior is used as an alternative (For example, see \\cite{Deco2009}, where an additional Kuramoto coupling parameter is required for spectrum computation). In this model, the sigmoidal activation function is simplified to one term, and its inputs are generalized to include network level driving forces and noise. Bringing into question the meaning behind a nonlinear sub-population neuron activation function for network level inputs. In Muldoon et al.'s work on network controllability \\cite{muldoon_stimulation-based_2016}, the original network model was made to oscillate at 20Hz, and no model fitting was performed, only changes in functional network properties based on a single nodal stimulation with the driving force parameter was measured. Again, based on our results with the same model implementation and identical parameter regimes, a network of identical oscillators will not provide simulated functional network metrics that closely resemble those of a realistic brain. Functional connectivity metrics and network activity will undoubtedly change according to network connections, but the parameters producing the accepted functional outputs may not produce an acceptable spectra. Moreover, it is unclear if there is an optimal parameter regime that is suitable for a given brain state due to parameter unidentifiability issues as discussed by numerous works \\cite{hartoyo_parameter_2019, chis_relationship_2016, villaverde_observability_2019}.\n\nOverall, it is no surprise that the promise of personalized diagnosis with model based analysis has been overtaken by the capabilities of deep learning or the analytical efficiencies of linear models \\cite{Becker2018, raj_spectral_2020}. Deep learning neural networks takes advantage of repeated and chained linear regression units with rectified linear activation units (ReLu) to make extremely fast classifications of data, and it has already been shown to produce high accuracy for biological phenomenon \\cite{pulvermuller_biological_2021, parmar_spatiotemporal_2020}. In this framework, interpolating high dimensional data for a given classification or embedding is made possible by the massive flexibility of layered linear units, and is already superior than any nonlinear NMMs in terms of training speed and prediction power. In fact, finding a global minimum to the massive parameter space of deep neural networks is frowned upon due to generalizability, and training of complex parameter spaces is made efficient by backpropagation of gradients. On the other hand, Linear models such as the works cited above transforms dynamical systems to the Fourier domain and uses structural eigen basis to relate functional patterns to a given structural connectome. These efforts provide models that are low-dimensisonal, hierarchical across spatial scales, and efficient to compute as the analytical models do not require step adaptive integrators. The trade offs over linear and nonlinear macroscopic models was recently examined by Nozari et al. \\cite{nozari_is_2020}, whom also reported on the performance of nonlinear NMMs to fit neurodynamic time course data. In addition to reporting linear models outperforming nonlinear models on the macroscopic scale, their work also commented on the macroscopic brain properties that masks nonlinear dynamics. Together with our results, we believe it is evident that nonlinear NMMs are not the optimal model of choice for model-based macroscopic neurophysiological data analysis.\n\n\\subsection{MCMC Convergence \\& Other Approaches}\nIn our results, we avoided the topic of convergence for our samplers. Convergence is often a difficult topic to discuss for MCMC sampling based analysis, because convergence can only be guaranteed for sample statistical problems with a high number of samples. For high dimensional model parameter inference, quality of the sampled posterior is often evaluated by acceptance ratio of samples and inspection of the posterior as compared to the prior. Additionally, statistics like the Gelman-Rubin statistic \\cite{gelman_inference_1992} are not applicable to modern MCMC algorithms as the multi-samplers used for parallelization are not independent from each other. On the other hand, integrated autocorrelation time \\cite{goodman_ensemble_2010} quantifies the effective number of independent samples needed and sampler efficiency. However, our sampling chains for all scenarios produced high acceptance rates and integrated autocorrelation times that required extremely large amounts of MCMC samples and weeks long computation times. This implies that the log likelihood ratios conditioning our parameter inference problem is not sufficently exploring the entirety of the parameter space. Our resulting weak fits with the fact that majority of accepted samples have low likelihoods suggest global sampling methods are not the proper approach for NMM parameter optimization. Secondly, the Wilson-Cowan network model parameters are not capable of describing the high dimensional features of functional neural recordings.\n\nOne may suggest that global parameter optimization methods with multiple local searches may improve our model fits. Approaches such as simulated annealing \\cite{Kirkpatrick1983} or basin hopping \\cite{Wales1997} may arrive at inferred parameters that provide better fits, but has their short comings. Firstly, these approaches provide point estimates of model parameters, ignoring any uncertainty in the case of complex parameter spaces that may have more than one possible solutions. In addition, while convergence for these algorithms can be determined by consecutive visits to the current  optimal solution, the solution is still sensitive to initialization, and there is no formal way of selecting optimization hyper-parameters such as tolerances, iterations, temperature, or cooling schedule (exploration scheme). Furthermore, these approaches do not provide any formalism for an objective function, and does not have the advantage of using a Bayesian framework which provides a set framework and a model evidence metric. \n\n\n\\subsection{Dynamic Causal Modeling}\nOne popular model based analysis is dynamic causal modeling (DCM), these approaches focus on discovery of effective network connectivity, and the emphasis is placed on a few nodes of interest \\cite{friston_network_2011}. Typically used for determining causality in fMRI data, this method aims to find the causal network that best supports the observed data as measured by Bayesian model evidence \\cite{stephan_nonlinear_2008}. While the goal of DCM based studies are different from model based analysis of neural recordings, the insights gained from causality in small subnetworks of the brain with a formal framework is extremely valuable. However, this approach is made impractical for whole brain studies due to the number of evaluations and possible networks required to be considered. Furthermore, in the case of NMMs, the nonlinear nature of the model makes the model inversion problem extremely inefficient. Whereas DCM works typically takes advantage of fully connected network models that are easily invertable. \n\n\\subsection{Variational Inference}\nVariational inference is a statistical method used to approximate parameter posterior densities in Bayesian models, where parameters and their uncertainties are obtained through optimization rather than expensive sampling. The optimization is theoretically performed based on the gradients of a posterior distribution obtained through Baye's theorem. However, the partial derivatives culminating in the full parameter space gradient is intractable for macroscopic network NMMs, and current implementations of variational inference such as \\emph{Edward2} \\cite{tran2018simple} and \\emph{PyMC3} \\cite{Salvatier2016} uses a \"black box\" inference approach. While these approaches seem effective for simpler problems, the need to fully sample the posterior hinders the usage of these tools for network NMMs. In particular, a network model such as the Wilson Cowan model requires the integration of two sets of derivatives for every brain region. And additionally for each brain region, the algorithm is required to remember past solutions at all nodes, and interpolate the past solutions based on unique distance induced delays as assigned by the connectomes. This makes computation of one realization with minimal time steps extremely slow on CPU backends (several minutes), needing to sample thousands of solutions for the likelihood estimation per iteration is simply impossible when taking into account computing time. Moreover, efficient parameter optmization relies on convex structural properties of the problem to guarantee rapid convergence to a solution. But in the case of NMMs and their black-box objective functions, these properties cannot be theoretically determined. In our case of expensive objective functions, the strategy needs to restrict the exploration of the search space to remain computationally tractable, further crippling network model based approaches to exploring neural data.\n\n\\subsection{Challenges and Limitations}\nWe've already addressed the problem of MCMC requiring large numbers of samples for diversity and statistical validity, which is computationally expensive and often times not practical to achieve with network scale NMMs. To further add to the challenges, reliable estimations of functional connectivity maps require on the order of a minute worth of data. This finite data problem in source localized encephalography recordings is comprehensively explored by Sommariva et al. \\cite{sommariva_comparative_2019}, concluding unsurprisingly that estimating functional connectivity is prone to errors with less data. Our numerical network NMM simulations of 2 seconds is on the low end of data length, and is certainly prone to unreliable functional connectivity outputs. This effect is further amplified if initialization of the delayed dynamical systems are not properly selected, as initial values affect the stationary points and stability of the oscillating system. We limited our simulation time to 2 seconds for the simple reason of practical computation time. Numerical integration of NMMs require time-steps below the millisecond to ensure accuracy at every time step. When more uncertainties from delayed inputs and noises at every network node is introduced, the integrators usually takes even smaller time steps, exponentially increasing the time needed to simulate one realization of the NMM. Therefore, parameter exploration poses immediate impossibilities, which is often commented on by published NMM works or avoided by simplifying the problem. \n\n\\section{Conclusion}\nThe dimensionality and nonlinearity of network NMMs leads to low confidence for a given system to produce functional dynamics with desired properties, and subsequently compare these models for effective analysis. Additionally, there is no formal methodology for selecting initial values of the delayed dynamics or the initial positions of parameters. In the case of the Wilson-Cowan model, the mean firing rates of neuron sub-populations output is simply not appropriate for encephalography modality data modeling. Recordings of neural activity involves excitation driven currents or blood-oxygen dependent activity, the sensor level average activity we observe in data is not simply explained by firing rate models and more mechanistic details are required. In our work, we show that one of the widely adapted NMMs is specified for neuron population level firing rate studies of a specified frequency, extending such a model to the network scale does not allow accurate, reliable, or efficient optimization. Furthermore, second order connectivity statistics often does not encapsulate sufficient evidence for tuning of network model parameters. Overall, we believe claims of unidentifiable network NMM parameters as low dimensional descriptors of biophysiological data should be carefully examined. More effective alternatives in linear models and deep learning has already surpassed NMMs, and offers more insight into the embeddings of functional brain recordings.", "meta": {"hexsha": "6ddb890ade82dcb430d1be4b30148eb10a5fda57", "size": 59623, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapter3/wcnmm.tex", "max_stars_repo_name": "axiezai/dissertation", "max_stars_repo_head_hexsha": "03152be2d8f704c58c2df46fec0fdacb61a260e3", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-07T20:27:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T20:27:15.000Z", "max_issues_repo_path": "chapter3/wcnmm.tex", "max_issues_repo_name": "axiezai/dissertation", "max_issues_repo_head_hexsha": "03152be2d8f704c58c2df46fec0fdacb61a260e3", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-11-02T19:16:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-08T21:52:29.000Z", "max_forks_repo_path": "chapter3/wcnmm.tex", "max_forks_repo_name": "axiezai/dissertation", "max_forks_repo_head_hexsha": "03152be2d8f704c58c2df46fec0fdacb61a260e3", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 215.2454873646, "max_line_length": 2023, "alphanum_fraction": 0.8075407142, "num_tokens": 12947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3176299249041757}}
{"text": "\\documentclass{article}\n\\usepackage{amsmath}\n\\usepackage{cite}\n\\setlength{\\textwidth}{7.0in}\n\\setlength{\\oddsidemargin}{0.0in}\n\\setlength{\\evensidemargin}{0.0in}\n\n\\title{Tutte Activities Based on More General Element Orders}\n\\author{Seth Chaiken\\\\\nGary Gordon\\\\\nElizabeth McMahon}\n\\begin{document}\n\\maketitle\nIn 1997 Gordon and McMahon\\cite{GordonMcMachonGreedoid} \nextended from matroids to greedoids\nthe internal and external \nelement activities and the resulting subset-interval \npartition analysis for the Tutte polynomial.  They found it necessary\nto abandon the traditional definition of activities based on a \nsingle (but arbitrary) linear element order.  Instead, the internal and \nexternal, active versus inactive element classification was based on \nproperties of each individual root-to-leaf path down any computation tree\nfor the Tutte polynomial.  Independence of element order was generalized to\nindependence of the computation tree.\n\nWe report that these results (for matroids) naturally generalize when both (1) \nthe deletion/contraction and loop/coloop removal operations, for each element,\nare \\textbf{parametrized} or \n\\textbf{colored}, and (2) a subset of \\textbf{port} elements \n$P$ is given and the resulting \\textbf{restricted} or \\textbf{ported}\nTutte functions satisfy $T(M) = g_e T(M/e) + r_e T(M\\backslash e)$ \n\\textbf{only for} $e\\not\\in P$.\n\nAfter they are extended to involve the initial values $T(M')$ for \nthe \\textbf{$P$-minors} $M'$, the Bollobas/Riordan/Zaslavsky \nconditions on the parameters are quite easily \nshown to be necessary and sufficient for the Tutte polynomial to be\nwell-defined.\n\n\\newpage\n\n\\LARGE\n\n\\section{Brief History of Tutte Functions}\n\\begin{enumerate}\n\\item Well-defined invariants like the chromatic (poly.) function \nand the count of spanning trees were shown to satisfy\n\\[\nT(G) = T(G/e) \\pm T(G\\setminus e).\n\\]\n\\item\nAlternative expansions for some Tutte functions, like Whitney's\n\\[\n\\chi(G,\\lambda) = \\sum_{A\\subseteq E(G)}(-1)^{|A|}\\lambda^{k(G|A)}\\text{\\ \\ \\ }2^{|E|}\n\\text{ terms}\n\\]\n$\\sum$ could be SHORTENED to ``broken-circut-free'' subsets $A$, based on\nan \\textit{arbitrary linear ordering of }$E(G)$\n\\item\nTutte and Brylawski's universal 2-variable solution to \n\\[\nT(G) = T(G/e) + T(G\\setminus e).\n\\]\nexpressed by\n\\[\nT(G) = \\sum_{\\text{Bases}B\\subseteq E}x^{|IA(B)|}y^{|EA(B)|}\n\\]\n\\textit{ internally ($IA$) and externally ($EA$)\nactive elements based on a arbitrary linear ordering of $E$}\n\\end{enumerate}\n\nTutte's and others proved\n\\textbf{every computation tree} computes every Tutte function\nvalue \\textbf{correctly BECAUSE} the Tutte eq. have a unique solution.\n\nBut \\textit{independence of the linear ordering defining the activities} \nHAD TO BE PROVED FIRST.\n\n\\newpage\n\n\\section{GM's Computation Tree Approach}\n\nSets $IA$ and $EA$ are assoc. to \\textbf{leaves} of an \n\\textbf{arbitrary computation tree} $\\mathcal{T}_j$\n\n\\noindent\n$IA(\\text{leaf}) = $ isthmuses at leaf's graph or matroid.\n\n\\noindent\n$EA(\\text{leaf}) = $ loops at leaf's graph or matroid.\n\n\\noindent Routine induction (``Let $\\mathcal{T}_1$, \n$\\mathcal{T}_2$ be two trees of a smallest \ncounterexample. ... Contradiction!\\footnote{Technical lemmas \nabout series and parallel elements are applied.}'') proves:\n\n\\[\n\\sum_{\\text{leaf of }\\mathcal{T}_1}\nx^{IA_1(\\text{leaf})}y^{EA_1(\\text{leaf})}\n=\n\\sum_{\\text{leaf of }\\mathcal{T}_2}\nx^{IA_2(\\text{leaf})}y^{EA_2(\\text{leaf})}\n\\]\n\n\n\n\\newpage\n\\section{What generalizes to GM computation tree approach}\n\n\\noindent \\textbf{Greedoids (GM 1997)}\n\n\\noindent Sometimes the \\textbf{only computation trees\nthat exist} are NOT BASED ON A LINEAR element ORDER!\n\n\\vfill\n\n\n\\noindent 2 Interval partitions of the boolean lattice\n$2^{E}$ defined using \\textbf{one part for each computation tree leaf}.\n\n\\vfill\n\n\n\\noindent \\textbf{Zaslavsky-Riordan-Bollobas, Traldi}\non weight (or color) pairs ($x_e,y_e$) on labelled edges\nand initial values ($X_e,Y_e$) on loops and insthuses -- necessary and \nsufficient for the weighted or colored Tutte equations to have a \nsolution.\n\n\\vfill\n\n\n\\noindent \\textbf{$P$-ported or restricted or set-pointed} Tutte functions\n$T$ with weights or colors.  \n(Diao-Hetyei, computation tree proofs by sdc)  \nTWO more ZBR-type conditions re. \\textbf{initial values of $T$ on \nthe $P$-quotients} are needed besides ZBR's original three.\n\n\\vfill\n\n\n\\noindent \\textbf{ORIENTED matroids}\n INCLUDING DISTINCT $P$-quotients.(sdc)\n\n\\newpage\n\\section{What DOES NOT Go Through}\n\nGiven a linear element order, $B\\subset E$ is a broken-circuit if there\nexists $e\\not\\in E$ so $B\\cup e$ is a circuit and $e$ is the (FOR US!) \nGREATEST element in $B\\cup e$.\n\n\\textbf{Given a computation tree} (unless it's from a linear order) \n``$B\\subseteq E$ is a broken-circuit'' \\textbf{is not well-defined}.  \n\n\n\n\\vfill\n\n\\section{What does go through}\n\n\nWhat's a broken circuit $B$, COMPUTATIONALLY?  ANSWER:  There is a \nroot-to-leaf path down which which each element of $B$ is contracted, and\na \\textbf{LOOP IS PRODUCED} when contracting the last element of $B$.\n\n\n\nWhen the tree is from a linear order, \n``$A\\subseteq E$ is broken-circuit free'' \\textbf{if and only if}\n``the leaf of $\\mathcal{T}$ gotten to by searching for $A$ has no loops\n(ie., $EA(\\text{leaf})=\\emptyset$).\n\nAND Whitney's expansion generalizes to those sets $A$ leading to loop-free\nleaves in an arbitrary computation tree.\n\n\n\n\n\n\n\n\n\n\n\n%}%Large\n\\newpage\n\\bibliographystyle{plain}\n\\bibliography{../../bib/MathOfElec}\n\\end{document}\n\n", "meta": {"hexsha": "005d62f87e124a7aafc2a98d06520c1efebbbf03", "size": 5481, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "drafts/activities/poster.tex", "max_stars_repo_name": "chaikens/MathOfElec", "max_stars_repo_head_hexsha": "6292a8cffe1441a557212b0fd23f3fd7769975a7", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "drafts/activities/poster.tex", "max_issues_repo_name": "chaikens/MathOfElec", "max_issues_repo_head_hexsha": "6292a8cffe1441a557212b0fd23f3fd7769975a7", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "drafts/activities/poster.tex", "max_forks_repo_name": "chaikens/MathOfElec", "max_forks_repo_head_hexsha": "6292a8cffe1441a557212b0fd23f3fd7769975a7", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.546875, "max_line_length": 86, "alphanum_fraction": 0.7400109469, "num_tokens": 1618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.31762597098345663}}
{"text": "%!TEX root = ../gronskiy_phd_thesis.tex \r\n\\chapter[Does the Free Energy Define the Model Behavior?]{Does the Free Energy Define \\\\ the Model Behavior?}\r\n\\label{ch:smbp_and_rem}\r\n\r\n\\hfill\r\n\\begin{minipage}[t]{.75\\textwidth}\r\n\\textit{``When I see a bird that walks like a duck and swims like a duck and\r\n  quacks like a duck, I call that bird a duck.''} \\\\\r\n  \\hrule\r\n  \\vspace{.2cm}\r\n  \\hfill\r\n  \\textsc{---  James Whitcomb RILEY} (attr.)\r\n\\end{minipage}\r\n\r\n\\section{Introduction}\r\n\r\n\\subsection{Motivation}\r\n\r\nRandom combinatorial optimization problems exhibit a highly complex structure\r\nwith a spin glass behavior~\\citep{Mezard87,SK:CG:MV:Science1983}. Optimization\r\nalgorithms for these problems are slowed down by fluctuations in the problem\r\ninstances when they search for solutions with low costs. Conceptually, we\r\nconsider an optimization algorithm as a mapping from an input space of random\r\ninstances to an output space of solutions and such algorithms should sample\r\n``typical'' solutions from appropriate posterior distributions. In this chapter,\r\nwe concentrate on maximum entropy sampling principles guided by Gibbs\r\ndistributions to study information theoretic properties of random combinatorial\r\noptimization problems and their search landscape.  Analytical computation of\r\nfree energy, entropy and other macroscopic thermodynamical properties enables us\r\nto understand the solution structure of a large system, but~--- as already\r\nclarified in~Chapter~\\ref{ch:free_energy},~--- this goal has been\r\nknown to be notoriously difficult and challenging from a mathematical\r\nstandpoint~\\citep{talagrand03}. \r\n\r\nWhile we solved this problem for specific cases (Chapter~\\ref{ch:free_energy})\r\nwith the purpose of applying in to robust optimization (Chapters~\\ref{ch:gen_appch}\r\nand~\\ref{ch:mst}), here we will be interested in a more general consequence of\r\nsuch results: a relation between the Random Energy Model (REM;\r\nsee~\\citealp{derrida81}) and the Sparse Minimum Bisection Problem (sMBP;\r\nsee~Section~\\ref{sec:free_mbp-problem}).\r\n\r\n% Why are we interested in the relations between REM and sMBP? \\\\\r\n\r\nWhy are the relations between REM and sMBP of interest?  The REM does not\r\nintroduce any statistical dependencies between solutions. Therefore,\r\noptimization algorithms have to exhaustively inspect all exponentially many\r\nsolutions of REM to find the one with minimal costs. Sparse Minimum Bisection\r\nintroduces correlations between solutions but they are asymptotically so weak\r\nthat they do not change the free energy. Since the free energy is the moment\r\ngenerating function of the Gibbs distribution we hypothesize that the Gibbs\r\ndistributions of both problems are equivalent in terms of Kullback-Leibler\r\ndivergences. If this claim would hold then we would not be able to efficiently\r\nsearch for low cost solutions of sMBP.\r\n\r\n\\subsection{Contributions and Outline of the Chapter}\r\n\\label{sec:smbp_and_rem_contribs}\r\n\r\nIn this chapter, we revisit the idea of characterizing structural\r\ninformation in solutions for combinatorial problems by \r\ninformation theoretic properties. \r\n\r\nMore specifically:\r\n%\r\n\\begin{itemize}\r\n  \\item we revisit results on the asymptotic behavior of the free\r\n    energy~(Chapter~\\ref{ch:free_energy}) on obtaining bounds on the free energy of\r\n    solutions for the sMBP with random edge weights;\r\n\r\n  \\item these results reveal a remarkable phenomenon that the\r\n    free energy of sMBP behaves very similarly to that of REM. Specifically, we\r\n    show that the free energy of sMBP with random edge weights exhibits phase\r\n    transitions equivalent to Derrida's REM;\r\n\r\n  \\item in order to deeper understand this observation and solution structure for\r\n    dependent and independent solutions, we then make and prove statements about\r\n    various ways sMBP and REM can be quantitatively related to each other: we show\r\n    that the Kullback-Leibler divergence between Gibbs distributions induced by sMBP\r\n    and REM are bounded, but not zero, which allows to make a conjecture about their\r\n    complexity relations.\r\n\\end{itemize}\r\n\r\nThe chapter is organized as follows. As usual, we start with describing some of\r\nrelated work in Section~\\ref{sec:smbp_rem_related_work}. We then present and\r\ndiscuss our results about the similar behavior of REM and sMBP in\r\nSection~\\ref{sec:smbp_rem_similar}. We speculate on the ways to interpret these\r\nresults in Sections~\\ref{sec:mbp_and_rem_how_similar}\r\nand~\\ref{sec:rem_conclusion}.\r\n\r\n\r\n\\section{Background and Related Work Overview}\r\n\\label{sec:smbp_rem_related_work}\r\n\r\nInformation theory, statistical mechanics and combinatorial optimization in\r\nlarge disordered systems have been disciplines enjoying several waves of\r\nintensive research. The first wave, associated exclusively with the statistical\r\nmechanics, was marked by the works of~\\citet{sk75spinb} or~\\citet{derrida81} on\r\nmean-field models of spin glasses. For the reasons stated in the introduction,\r\nwe concentrate on Derrida's solvable REM. In short, REM is the simplest\r\nexample of a disordered system, whose configurations have i.i.d. energies and,\r\ntherefore, are not efficiently ``searchable''. It will become important in the\r\nrest of the chapter that REM reflects the situation with no stochastic\r\ndependencies between solutions. This work inspired several continuations, of\r\nwhich we can mention, e.g., \\citep{derrida86} as a generalization of REM,\r\nor~\\citep{Aizenman1987} as exact solution of Sherrington-Kirkpatrick\r\nmodel~\\citep{sk75spin}.\r\n\r\n\\index{Traveling Salesman Problem}\r\n\\index{TSP|see{Traveling Salesman Problem}} \r\nThe second wave of interest was associated not exclusively with statistical\r\nmechanics, but also researched its connection to combinatorial optimization.\r\nInspired by the work of Derrida, \\citet{mezard84tsp} considered the Traveling\r\nSalesman Problem (TSP) as a large disordered system which seeks to optimize its\r\nenergy defined by respective \\textit{Hamiltonians}\\index{Hamiltonian} (see\r\nSection~\\ref{sec:background_disordered_systems}). This approach to view a\r\ncombinatorial optimization problem from the statistical mechanics prospective\r\nturned out to be extremely fruitful: we recommend the book~\\citep{LUCZAK1994} as\r\na good overview of the results. We should also mention here the\r\nwork~\\citep{Auffinger2014} who studied algorithmic complexity from the\r\nstatistical mechanics viewpoint.\r\n\\index{Complexity}\r\n\\index{Algorithmic complexity}\r\n\r\nFinally, in the last two decades, many attempts have been made to systematize\r\napproaches traditionally used in statistical mechanics and render them rigorous\r\nin a mathematical sense. Here, we point out the work by\r\n\\citet{Bovier2002FreeEnergyFluct}, as well as extensive\r\nreviews by \\citet{talagrand03,bovier2012statistical}.\r\n\r\n\\section{Comparison of REM and sMBP}\r\n\r\n\\subsection{Random Energy Model (REM)}\r\n\r\n\\index{Random Energy Model}\r\n\\index{REM|see{Random Energy Model}}\r\n\r\nThe REM introduced by~\\citet{derrida81} is a model $\\mathcal{P}^\\mathrm{rem} =\r\n(\\mathcal{X}, \\C^\\mathrm{rem}, R^\\mathrm{rem})$ \r\n\\nomenclature[F, 50]{$(\\mathcal{X}, \\C^\\mathrm{rem}, R^\\mathrm{rem})$}{definition of REM\\nomnorefeq}%\r\nwhere the following conditions apply:\r\n\\begin{enumerate}\r\n  \\item Number of solutions (in the original terminology,\r\n    \\textit{configurations}) equals \r\n    \\begin{equation}\r\n      |\\C^\\mathrm{rem}| = 2^K.\r\n    \\end{equation}\r\n  \\item Here, the data source $X \\in \\mathcal{X}$ is a vector of $2^K$ Gaussian\r\n    random variables (for the notation, see\r\n    Definition~\\ref{def:optimization_problem_definition}), and all solutions\r\n    $c_i\r\n    \\in \\C^\\mathrm{rem}$ carry costs (in the original terminology,\r\n    \\textit{Hamiltonians} or \\textit{energy levels})\r\n    \\begin{equation}\r\n      R^\\mathrm{rem}(c_i, X) = X_i, \\;\\; \\text{where} \\;\\; X_i \\sim \\mathcal{N}(0, \\sigma^2)\r\n    \\end{equation}\r\n    \\item The costs $X_i$ are i.i.d.\r\n\\end{enumerate}\r\n\r\nAs Derrida noted in his paper, ``the third property is specific to this model.\r\nIt simplifies the model enough to allow us to solve it exactly''. While it is\r\ntrue for REM, such independence is not characteristic for the most of the\r\nmodels. The next section which discusses dependencies in sMBP.\r\n\r\n\\subsection{Similar Behavior of REM and sMBP}\r\n\\label{sec:smbp_rem_similar}\r\nEarlier, we introduced the sparsity constraint on $d$ in\r\nTheorem~\\ref{thm:sparse_mbp_tight_bound} because without it, the stochastic\r\ndependency between two random solutions for original MBP~\\citep{garey79} is very\r\nhigh. Indeed, in original MBP, any two bisections \\textit{always} share edges.\r\nBy introducing $d$ we: a) substantially reduce such dependency, but on the other\r\nhand b) do not eliminate it at all, like in REM~\\citep{derrida81}. \r\n\r\nBut by introducing sparsity, didn't we essentially \\textit{transform} MBP into\r\nREM? E.g. one can observe that for classical dependency-free REM, the free\r\nenergy asymptotics looks just the same, in particular exhibits the same phase\r\ntransition and same phase shapes:\r\n\r\n\\begin{theorem}[adapted formulation from~\\citep{talagrand03}] \\label{thm:rem}\r\n  Assume $m = 2^K$ is the number of configurations for the REM model with\r\n  Gaussian cost values, with parameters $\\mathcal{N}(0, \\tau^2)$. Then the\r\n  free energy rate is (asymptotically in $n \\to \\infty$) equal to\r\n    \\begin{equation} \\label{eq:talagrand_rem_with_tau}\r\n      \\lim_{n \\to \\infty} \\frac{\\E[\\log Z]}{\\log m}=\r\n      \\left\\{ \\begin{array}{ll}\r\n      \\frac{\\beta^2 \\tau^2}{2 \\log m} + 1 & \r\n      \\beta < \\sqrt{2 \\log m}/\\tau,\\\\\r\n      \\frac{\\beta \\tau \\sqrt{2}}{\\sqrt{\\log m}} & \\beta \\ge \\sqrt{2 \\log m}/\\tau.\r\n      \\end{array}\r\n      \\right.\r\n    \\end{equation}\r\n\\end{theorem}\r\nWe note that Talagrand formulated it in a more general setting~\\citep[cf.][Prop.\r\n1.1.3]{talagrand03}, which is adapted here for clarity. Choosing $\\tau = \\sigma\r\n\\sqrt{N}$ and applying $\\beta$ rescaling from~\\ref{def:cts}, we arrive at an\r\nequivalent formulation: for Gaussian cost values with parameters $(0, \\sigma^2\r\nN)$, we derive\r\n\\begin{equation} \\label{eq:talagrand_rem_adapted}\r\n  \\lim_{n \\to \\infty} \\frac{\\E[\\log Z]}{\\log m}=\r\n  \\left\\{ \r\n    \\begin{array}{ll}\r\n      1+\\frac{\\hat \\beta^2\\sigma^2}{2}, &\r\n        \\hat \\beta< \\frac{\\sqrt{2}}{\\sigma},\\\\\r\n      \\hat \\beta \\sigma \\sqrt{2}, & \r\n        \\hat \\beta \\ge \\frac{\\sqrt{2}}{\\sigma}\r\n    \\end{array}\r\n  \\right.\r\n\\end{equation}\r\n\\myremark For non-centered cost values, the necessary\r\ncorrection similar to the one of~\\eqref{eq:sparse_mbp_tight_bound} should be\r\nmade on the left-hand side which is trivial.\r\n\r\nWe are now going to sketch an answer to the following question: how much does\r\nsMBP look like REM? We give the following result and then discuss it. First,\r\nlet's make some definitions.\r\n\r\n\\begin{definition}\r\n  For an sMBP setting stated in Theorem~\\ref{thm:sparse_mbp_tight_bound},\r\n  we will call equivalent such a REM, for which the number\r\n  of configurations is equal to $m$ and the cost values are Gaussian with\r\n  parameters $(\\mu N,\r\n  \\sigma^2 N)$.\r\n\\end{definition}\r\nFor convenience of the following explanation, let us denote the random source\r\nbehind such a REM as $Y$ (analogically to $X$ in case of sMBP). Hence for REM,\r\nthe cost values $R(c, Y) \\sim \\mathcal{N}(\\mu N, \\sigma^2 N)$ and all are\r\nindependent. We denote the respective Gibbs distributions $\\psmbp_\\beta(c | X)$ and\r\n$\\prem_\\beta(c | Y)$.\r\n\\index{Kullback-Leibler divergence}\r\n\\begin{theorem}\\label{thm:kl_divergence}\r\n  The rate of the KL-divergence between configurations' Gibbs distributions for sMBP \r\n  and equivalent REM is non-zero and exhibits a phase transition.\r\n  \\begin{equation}\r\n    \\frac{\\Expct_{X, Y}[\\KL(\\prem_\\beta \\| \\psmbp_\\beta)]}{\\log m} = \r\n      \\left\\{ \r\n        \\begin{array}{ll}\r\n          \\hat\\beta^2 \\sigma^2 &\r\n            \\hat \\beta< \\frac{\\sqrt{2}}{\\sigma},\\\\\r\n          \\hat \\beta \\sigma \\sqrt{2}, & \r\n            \\hat \\beta \\ge \\frac{\\sqrt{2}}{\\sigma}\r\n        \\end{array}\r\n      \\right.\r\n  \\end{equation}\r\n  \\nomenclature[F, 50a]{$\\prem_\\beta(c \"| X)$}{Gibbs distribution of REM model}%\r\n  \\nomenclature[F, 50c]{$\\psmbp_\\beta(c \"| X)$}{Gibbs distribution of sMBP}%\r\n\\end{theorem}\r\n\r\n\\paragraph{Proof}\r\nIn the first part of the proof, we will omit the expectation for the sake of\r\nbrevity.\r\n%\r\n\\begin{align}\r\n\\MoveEqLeft \\KL(\\prem_\\beta \\| \\psmbp_\\beta) = \\sum_c \\prem_\\beta(c\\vert Y) \\log\r\n  \\frac{\\prem_\\beta(c\\vert Y)}{\\psmbp_\\beta(c\\vert X)} = \\notag \\\\\r\n  &= \\sum_c \\prem_\\beta(c\\vert Y) \r\n    \\left(  \r\n      \\log \\frac{e^{-\\beta \\Rrem(c,Y)}}{\\Zrem(Y)} \\right. \\notag \\\\\r\n      &\\qquad\\qquad\\qquad\\qquad\r\n      \\left. - \\log \\frac{e^{-\\beta \\Rsmbp(c,X)}}{\\Zsmbp(X)}\r\n    \\right) \\notag \\\\\r\n  &=  \\sum_c \\prem_\\beta(c\\vert Y) \r\n    \\left(  \\vphantom{\\sum}\r\n      \\log e^{-\\beta \\Rrem(c,Y)}   \\right. \\notag \\\\\r\n      &\\qquad\\qquad\\qquad - \\log e^{-\\beta \\Rsmbp(c,X)} \\notag \\\\\r\n      &\\qquad\\qquad\\qquad \\left. - \\log \\Zrem(Y) + \\log \\Zsmbp(X)\r\n      \\vphantom{\\sum}\\right) \\notag \\\\\r\n  &= -\\beta \\sum_c \\prem_\\beta(c\\vert Y) \r\n    \\Bigl( \\Rrem(c,Y) - \\Rsmbp(c,X) \\Bigr) \\notag \\\\\r\n      &\\qquad\\qquad\\qquad  - \\log \\Zrem(Y) + \\log \\Zsmbp(X) \r\n\\end{align}\r\nReturning to the expectation $\\Expct_{X,Y}$ and recalling that all the\r\nsMBP-related terms depend on $X$ and all the REM-related terms depend on $Y$, we can continue:\r\n\\begin{align}\r\n  \\MoveEqLeft -\\beta \\Expct_{X,Y} \\biggl[\\sum_c \\prem_\\beta(c\\vert Y) \r\n    \\Bigl( \\Rrem(c,Y) - \\Rsmbp(c,X) \\Bigr) \\biggr] \\notag \\\\\r\n      &\\qquad\\qquad  \r\n        \\underbrace{\r\n            {} - \\Expct_Y [\\log \\Zrem(Y) ]\r\n            + \\Expct_X [\\log \\Zsmbp(X)]\r\n          }_{\r\n          \\text{\r\n            cancel out due to Thm.~\\ref{thm:sparse_mbp_tight_bound} and \\ref{thm:rem}}\r\n          } \\notag \\\\\r\n  &= -\\beta  \r\n    \\Bigl( \\Expct_{Y} \\Bigl[\\sum_c \\prem_\\beta(c\\vert Y) \\Rrem(c,Y) \\Bigr] \\notag \\\\\r\n        &\\qquad\\qquad - \\Expct_Y \r\n          \\underbrace{\\sum_c \\prem_\\beta(c\\vert Y)}_{1} \\cdot \r\n          \\underbrace{\\vphantom{\\sum_c}\\Expct_X \\Rsmbp(c,X)}_{\\mu N} \\Bigr) \\notag \\\\\r\n  &= \\beta \\mu N + \\beta \\Expct_Y \\Bigl[\\frac{d}{d\\beta} \\log \\Zrem(Y)\\Bigr].\r\n\\end{align}\r\nBy the argument of dominated convergence theorem, we can under mild conditions\r\ninterchange expectation and differentiation, which together\r\nwith~\\eqref{eq:talagrand_rem_with_tau} and~\\eqref{eq:talagrand_rem_adapted}\r\nleads to\r\n\\begin{equation}\r\n  \\Expct_{X, Y}[\\KL(\\prem_\\beta \\| \\psmbp_\\beta)] = \r\n    \\left\\{ \r\n      \\begin{array}{ll}\r\n        \\hat\\beta^2 \\sigma^2 \\log m &\r\n          \\hat \\beta< \\frac{\\sqrt{2}}{\\sigma},\\\\\r\n        \\hat \\beta \\sigma \\log m \\sqrt{2}, & \r\n          \\hat \\beta \\ge \\frac{\\sqrt{2}}{\\sigma},\r\n      \\end{array}\r\n    \\right.\r\n\\end{equation}\r\nwhich completes the proof of theorem.\r\n\\QEDA\r\n\r\n\\subsection{Consequences of Similar Behavior of REM and sMBP}\r\n\r\nWe now discuss this result. There are several observations to be made about the\r\nwhole line of research reflected in\r\nTheorems~\\ref{thm:sparse_mbp_tight_bound},~\\ref{thm:rem}\r\nand~\\ref{thm:kl_divergence}.\r\n\r\n\\begin{figure}[th!]\r\n  \\centering\r\n  \\begin{subfigure}[b]{.48\\textwidth}\r\n      \\includegraphics[width=\\linewidth]{figures/ch_smbp_and_rem/different_solution_overlaps}\r\n      \\caption{Solution to an sMBP problem}\r\n      \\label{fig:ch_rem_smbp_illustration-0}\r\n  \\end{subfigure}\r\n  \\hfill\r\n  \\begin{subfigure}[b]{.48\\textwidth}\r\n      \\includegraphics[width=\\linewidth]{figures/ch_smbp_and_rem/different_solution_overlaps_1}\r\n      \\caption{No overlap at all}\r\n      \\label{fig:ch_rem_smbp_illustration-1}\r\n  \\end{subfigure}\r\n  \\\\[.5cm]\r\n  \\begin{subfigure}[b]{.48\\textwidth}\r\n      \\includegraphics[width=\\linewidth]{figures/ch_smbp_and_rem/different_solution_overlaps_2}\r\n      \\caption{Vertex overlap, but no edge overlap}\r\n      \\label{fig:ch_rem_smbp_illustration-2}\r\n  \\end{subfigure}\r\n  \\hfill\r\n  \\begin{subfigure}[b]{.48\\textwidth}\r\n      \\includegraphics[width=\\linewidth]{figures/ch_smbp_and_rem/different_solution_overlaps_3}\r\n      \\caption{Only edge overlap counts}\r\n      \\label{fig:ch_rem_smbp_illustration-3}\r\n  \\end{subfigure}\r\n  \\\\[.5cm]\r\n  \\caption{Illustration of various types of overlaps. Only case \\textbf{(d)}\r\n  contributes to statistical dependence between costs of solutions. Carefully\r\n  computing edge overlap can make a huge step forward in understanding higher\r\n  moments of $\\log Z$ (in Lemma~\\ref{lem:expct_d_asymptotics} we computed only\r\n  expected value).}\r\n  \\label{fig:ch_rem_smbp_illustration}\r\n\\end{figure}\r\n\r\nFirst, Theorems~\\ref{thm:sparse_mbp_tight_bound},~\\ref{thm:rem}\r\nand~\\ref{thm:kl_divergence} can be interpreted as follows: they yield the\r\nsimilarity of both problems in terms of macroscopic thermodynamical properties\r\nlike free energy rate, but at the same time they convey their difference in\r\nterms of KL-divergence rate: by definition of $\\KL$, it measures the amount of\r\ninformation one might gain (or lose) by assuming $\\prem$ instead of $\\psmbp$ or\r\nvice versa. The fact that the expected KL-divergence rate is non-zero allows us\r\nto say that sMBP and REM are still different in terms of their distributions.\r\n\r\nSecond, and probably most importantly, due to the same line of reasoning as in\r\nTheorem~\\ref{thm:kl_divergence}, we can conclude that a KL-divergence between\r\nevery pair $({\\prem}', {\\prem}'')$ of independent (that is, with independent\r\n$Y'$ and $Y''$) equivalent REMs is identical to that of $(\\prem, \\psmbp)$. This\r\nhighlights the fact that for full understanding of relations (similarities and\r\ndifferences) between them one needs to properly quantify this difference in\r\nterms of higher moments and not only \\textit{expectation} of KL-divergence rate.\r\n\r\nIt is important to realize that the higher moments of the KL-divergence can be\r\nmost likely controlled by the higher moments of $\\log Z$, i.e. $\\Var[\\log Z]$\r\nand so on. \r\n\r\nThe necessary understanding of the behavior of $\\Var[\\log Z]$, in turn, can be\r\nreached via careful computing of higher moments of edge overlap $D$ of the two\r\nsolutions $c_1$ and $c_2$ (illustrated in\r\nFigure~\\ref{fig:ch_rem_smbp_illustration}): one can see this, for example,\r\nfrom the proof of Theorem~\\ref{thm:sparse_mbp_tight_bound}, where we have \r\n\\begin{equation*}\r\n  \\Var Z \\sim (\\Expct Z)^2 \\bigl( \\sigma^2 \\beta^2 \\Expct_\\D D \\bigr)\r\n\\end{equation*}\r\nas an intermediate result. There exists evidence of a possibility to use \r\nTaylor expansions to express higher moments of $\\log Z$ via those of $Z$.\r\n\r\n\\section{Comparison of REM and non-sparse MBP}\r\n\\label{sec:mbp_and_rem_how_similar}\r\n\r\nInteresting question arises: can we say anything about non-sparse (i.e. case\r\nwhen $d \\not \\ll n$) MBP? Note that in Section~\\ref{sec:free_energy_in_general_case}\r\nof Chapter~\\ref{ch:free_energy} we made a conjecture which is backed up by\r\nextensive simulations, which we restate here:\r\n\r\n\\newtheorem*{adhocconj}{Conjecture~\\ref{ad-hoc}}\r\n\\begin{adhocconj}[see Section~\\ref{sec:free_energy_in_general_case}]\r\nConsider a class of combinatorial optimization problems complying with Common\r\nTheorem Setting, weights $W_i$ having mean $\\mu$ and variance $\\sigma^2$. Then\r\nthe free energy satisfies\r\n\\begin{equation*}\r\n    \\lim_{n\\to \\infty} \\frac{\\E[\\log Z(\\beta, X)] +\\hat \\beta \\mu \\sqrt{N\\log m}}{\\log m}\r\n    =\r\n    \\begin{cases}\r\n        1 + \\alpha^2\\frac{\\hat{\\beta}^2\\sigma^2}{2},\r\n            &\\hat{\\beta} < \\frac{\\sqrt{2}}{\\alpha\\sigma} \\\\\r\n\\alpha\\hat{\\beta}\\sigma\\sqrt{2}, &\\hat{\\beta} \\geq \\frac{\\sqrt{2}}\r\n{\\alpha\\sigma}\r\n    \\end{cases}\r\n\\end{equation*}\r\nfor some $\\alpha \\ge 1$,\r\nwhere $\\alpha$ is well approximated by\r\n\\begin{equation*}\r\n    \\alpha \r\n      = \\sqrt{\\frac{\\E_X\\Var_{\\mathcal{D}} R(c,X)}{\\E_{\\mathcal{D}}\\Var_X R(c,X)}} \r\n      = \\sqrt{\\frac{\\E_X\\Var_{\\mathcal{D}} R(c,X)}{N\\sigma^2}}\r\n\\end{equation*}\r\n\\end{adhocconj}\r\n\r\nIt is instructive to note here that, loosely speaking, parameter $\\alpha$\r\nrepresents the ratio variability across solutions (nominator) and the\r\nvariability inside each solution (denominator). The higher the dependence is, the \r\nless variability across solutions exists. \r\n\r\nApparently $\\alpha = 1$ corresponds to a case of no dependencies (sMBP), while\r\nlower alpha corresponds to higher levels of dependencies. And again, to further\r\nback up this conjecture, one has to develop the understanding of\r\n$\\Var_{\\mathcal{D}} R(c, X)$, i.e. variance of costs for uniformly chosen\r\nsolutions, which boils down to taking overlaps under control (computing\r\n$\\Var_\\mathcal{D} [D]$ analogically to $\\Expct_\\mathcal{D}[D]$ as we did in\r\nLemma~\\ref{lem:expct_d_asymptotics}.\r\n\r\n\\section{Discussion and Conclusion}\r\n\\label{sec:rem_conclusion}\r\n\r\nThe geometry of random combinatorial optimization problems is often\r\ncharacterized by exponentially many local minima which prevent an\r\nefficient search for low cost solutions. In this chapter, we have\r\nstudied random instances of sparse Minimum Bisection Problem which\r\nexhibit a statistical behavior very similar to that of the Random Energy\r\nModel. This similarity between the Gibbs distributions for REM\r\ninstances and for sMBP instances is documented by identical values for\r\nthe free energies and for the Kullback-Leibler divergences between\r\npairs of distributions. \r\n\r\nFurthermore, this equivalence also suggests that the computational complexity of\r\nREM and sMBP might be the same and, consequently, random instances of sMBP might\r\nnot be efficiently optimized due to the lack of search information as in REM. As\r\na future research direction we plan to analyze the finite $\\log m$ corrections\r\nto estimate the convergence rate of the free energy toward its asymptotic limit.\r\nAnother open question remains if there exist REM instances that are arbitrarily\r\nclose (w.r.t. KL-divergence) to sMBP instances in the asymptotic limit,\r\nexplaining why we cannot find efficient optimization schemes for sparse Minimum\r\nBisection.\r\n\r\nFor answering the last question, we have highlighted the importance of developing a better\r\nunderstanding of the higher moments of the solutions overlap\r\n(Figure~\\ref{fig:ch_rem_smbp_illustration}), since the proofs we gave earlier\r\nyield that controlling the dependency between the solutions gives us the essential \r\ninformation about the problem's (dis)similarity from REM, where such dependencies\r\ndon't exist at all.\r\n", "meta": {"hexsha": "f4bdaa3e881fceb1b14c5e1840ad511232913a5c", "size": 22258, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/ch_smbp_and_rem/ch_smbp_and_rem.tex", "max_stars_repo_name": "agronskiy/phd-thesis", "max_stars_repo_head_hexsha": "182fcc5c09c8aa20df54cf536eb87766bfb6c353", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thesis/ch_smbp_and_rem/ch_smbp_and_rem.tex", "max_issues_repo_name": "agronskiy/phd-thesis", "max_issues_repo_head_hexsha": "182fcc5c09c8aa20df54cf536eb87766bfb6c353", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis/ch_smbp_and_rem/ch_smbp_and_rem.tex", "max_forks_repo_name": "agronskiy/phd-thesis", "max_forks_repo_head_hexsha": "182fcc5c09c8aa20df54cf536eb87766bfb6c353", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.0264317181, "max_line_length": 110, "alphanum_fraction": 0.7251774643, "num_tokens": 6250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.3176259709834566}}
{"text": "\\section{Introduction} \\label{sec:intro}\n%\nThe untyped lambda calculus presents itself as an interesting\ntarget for synthesis.\n%\nOn one hand, it is described by a very simple grammar\ndefining a very unstructured program space for which it is\nhard to guide a search.\n%\nOn the other hand, this same lack of structure makes it\nunclear what should be used as behavioral constraints.\n%\nIn this work we explore the possibility of synthesizing\nexpressions in the untyped lambda calculus focusing mainly\non the second problem.\n%\nMore specifically, we focus on the problem of synthesizing\nfunctions over data encodings.\n\nData encodings in the lambda calculus are interesting\nbecause the same basic construct, lambda abstractions, is\nused to describe both functions and data.\n%\nThis produces a tension which makes it hard to reason about\nlambda expressions because the distinction between data and\nfunction gets blurred.\n\nWe recognize this as one of the main problems making it\nhard to specify behavioral constraints for lambda\nexpressions.\n%\nBecause of this lack of distinction, it is not enough, in\ngeneral to just specify the extensional behavior of\nfunctions, and we examine the possibility of constraining\ntheir evaluation.\n%\nOne of our key insights is that using free variables give us\nenough expressiveness to talk about the evaluation of\nfunctions.\n\nBased on this idea we note that by looking at the\nintroduction and elimination rules of data types we are able\nto specify their meaning precisely by giving a specification\nof their behavior in relation to some functions operating on\nthem.\n%\nWe call this a \\emph{co-specification} of an encoding.\n%\nThis opens the possibility of automatically deriving the\nencoding for some data type as a product of synthesis in a\nprocess we dubbed \\emph{co-synthesis}.\n\nFinally, we proved these ideas in practice by implementing a\nprototype enumerative synthesizer.\n%\nDespite its naive implementation we were able to apply it in\npractice to synthesize a series of interesting functions.\n%\nUsing this technique, our implementation was able to derive\nthe standard encoding for booleans.\n%\nThe code for our implementation can be found at \\\\\n\\href{https://github.com/DavidThien/elsa}\n{\\texttt{https://github.com/DavidThien/elsa}}.\n\n% ; the meaning for a function only exists\n% in the context of a specific encoding of your chosen terms.\n\n\n% This makes it hard to\n\n% defining a very particular search space.\n% %\n\n% for two major reasons:\n%   \\begin{enumerate}\n%     \\item The grammar describing the language is very small, meaning that\n%       small optimizations in the search process are very important to\n%       constrain the search space as much as possible\n%       %% TODO: This isn't quite the right description\n%     \\item Untyped lambda calculus uses the exact same grammar to describe\n%       both terms, and functions; the meaning for a function only exists\n%       in the context of a specific encoding of your chosen terms.\n%   \\end {enumerate}\n% The second reason in particular is interesting, because it begs the\n%   question of creating a specification for the behavior of functions\n%   independently of a given encoding.\n% This would allow users of the synthesizer to either pre-specify a\n%   particular encoding of terms they are interested in synthesizing\n%   functions for, or to specify the behavior of terms in the context of\n%   function applications, and have the synthesizer synthesize both\n%   an encoding for the terms, and the functions requested.\n% We call synthesis of terms and functions from a single unified encoding\n%   \\emph{co-synthesis}.\n\n% \\subsection{Grammar}\n\n% The grammar for untyped lambda calculus is simply defined as:\n%   \\begin{grammar}\n%     <expr> ::= x\n%       \\alt <expr> <expr>\n%       \\alt $\\lambda$ x <expr>\n%   \\end{grammar}\n%   where $x$ is a variable.\n% Note that variables need not necessarily be bound by the immediately\n%   preceeding lambda to be referenced.\n% For our purposes, variables only need be bound in the ultimate term\n%   that we eventually produce, as we can assume without loss of\n%   generality that there is no outside environment that we reference\n%   for synthesized terms or functions.\n\n% This grammar is very compact, which means that our search space tends to\n%   blow up because of the necessary depth of the search, rather than\n%   because the number of possible terms enumerable at a given depth\n%   is large.\n\n% \\subsection{Evaluation Strategy}\n\n% The meaning of a term in Lambda calculus, as in other programming languages,\n%   depends on the evaluation strategy used to assign meaning to that term.\n% For our purposes, we use normal order evaluation.\n% Normal order evaluation evaluates the leftmost outtermost reducible\n%   expression first.\n% Although this will generate different terms than another strategy like\n%   applicative order, there is nothing specialized about this synthesis\n%   that requires normal order to be used above anything else.\n% We have simply chosen normal order for consistency.\n", "meta": {"hexsha": "835e57b655b4f816636443bcca14923f943c86eb", "size": 5020, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/introduction.tex", "max_stars_repo_name": "DavidThien/elsa", "max_stars_repo_head_hexsha": "2bf97839d1fc210d12dac919b34ec4e0143f80e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "report/introduction.tex", "max_issues_repo_name": "DavidThien/elsa", "max_issues_repo_head_hexsha": "2bf97839d1fc210d12dac919b34ec4e0143f80e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/introduction.tex", "max_forks_repo_name": "DavidThien/elsa", "max_forks_repo_head_hexsha": "2bf97839d1fc210d12dac919b34ec4e0143f80e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.21875, "max_line_length": 78, "alphanum_fraction": 0.7752988048, "num_tokens": 1087, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3176259636261466}}
{"text": "\\documentclass{beamer}\n\n\\usetheme{Madrid}\n\\usecolortheme{default}\n\n\\definecolor{THUpurple}{RGB}{102,8,116}\n\n\\usepackage{amsmath}\n\\usepackage{mathtools}\n\\usepackage{caption}\n\\usepackage{listings}\n\\usepackage{lmodern}\n\\usepackage{xcolor}\n\\lstset{language=Python,keywordstyle={\\bfseries \\color{blue}}}\n\\usepackage{pdfpages}\n\\usepackage{makecell}\n\\usepackage[EULERGREEK]{sansmath}\n\\usepackage{float}\n\\usepackage{hyperref}\n\\usepackage{tikz}\n\\usetikzlibrary{shapes,arrows,positioning}\n\\usepackage[subrefformat=parens]{subcaption}\n\\usepackage[none]{hyphenat}\n\\usepackage[binary-units=true,per-mode=symbol]{siunitx}\n\\usepackage{CJK}\n\\usepackage{textcomp}\n\\usepackage{adjustbox}\n\\usepackage{pgfplots}\n\\usepackage{bm}\n\\usepackage{tablefootnote}\n\\DeclareMathOperator{\\erf}{erf}\n\\usefonttheme[onlymath]{serif}\n\n\\newcommand{\\dd}{\\mathrm{d}}\n\\newcommand{\\mev}{\\mathrm{MeV}}\n\\newcommand{\\gev}{\\mathrm{GeV}}\n\n\\setbeamercolor{structure}{fg=THUpurple}\n\\setbeamersize{text margin left=10mm,text margin right=10mm}\n% \\setlength{\\belowcaptionskip}{-2mm}\n\\title[Waveform Analysis]{Accurate PMT waveform analysis \\\\ with fast Bayesian matching pursuit}\n\\date[JUNO]{August 13, 2021}\n\n\\AtBeginSection[]\n{\n    \\begin{frame}[noframenumbering]\n        \\frametitle{Outline}\n        \\thispagestyle{empty}\n        \\tableofcontents[currentsection]\n    \\end{frame}\n}\n\n\\begin{document}\n\\captionsetup[figure]{labelfont={bf},name={Fig}}\n\\setbeamertemplate{frametitle}\n{\\begin{beamercolorbox}[wd=\\paperwidth]{frametitle}\n    \\strut\\hspace{0.5em}\\insertframetitle\\strut\n    \\hfill\n    \\raisebox{-2mm}{\\includegraphics[width=1cm]{img/180px-Junologo.jpg}}\n\\end{beamercolorbox}\n}\n\\tikzstyle{every picture}+=[remember picture]\n\n\\begin{CJK*}{UTF8}{gbsn}\n\\author[Dacheng Xu]{Dacheng~Xu~(徐大成) \\and Erjin~Bao~(宝尔金) \\and Yiyang~Wu~(武益阳) \\and Benda~Xu~(续本达) \\and Yu~Xu~(徐宇) \\and Geliang~Zhang~(张戈亮) et.al \\\\ [4mm] \\includegraphics[height=2cm]{img/Tsinghua_University_Logo.png}}\n\n\\frame{\\titlepage}\n\n\\begin{frame}[noframenumbering]\n\\frametitle{Outline}\n\\thispagestyle{empty}\n\\tableofcontents\n\\end{frame}\n\n\\section{Motivation}\n\n\\begin{frame}\n\\frametitle{Motivation}\n\\begin{columns}\n\\column{0.425\\textwidth}\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=1.0\\linewidth]{img/10-Figure7-1.png}\n    \\caption{An Event in JUNO Detector\\cite{zhu_method_2019}}\n\\end{figure}\n\\column{0.575\\textwidth}\n\\begin{figure}\n    \\centering\n    \\resizebox{\\textwidth}{!}{\\input{img/junowave.pgf}}\n    \\caption{A PMT Waveform}\n\\end{figure}\n\\end{columns}\n\\begin{block}{}\nWaveform analysis, which means extracting time and charge information from PMT waveforms, is the bedrock of subsequent analysis such as event reconstruction. \n\\end{block}\n\\end{frame}\n\n\\section{Dataset}\n\n\\begin{frame}\n\\frametitle{Simulation setup: Time profile}\n\\begin{figure}\n    \\centering\n    \\resizebox{0.6\\textwidth}{!}{\\input{img/profile.pgf}}\n    \\caption{Time Profile of Events}\n\\end{figure}\n\\begin{align*}\n    \\phi(t) &= \\mathcal{N}(t|\\sigma_l^2)\\otimes \\mathrm{Exp}(t|\\tau_l) \\\\\n    &= \\frac{1}{2\\tau_l} \\exp\\left(\\frac{\\sigma_l^2}{2\\tau_l^2}-\\frac{t}{\\tau_l}\\right) \\left[1 - \\erf\\left( \\frac{\\sigma_l}{\\sqrt{2}\\tau_l} - \\frac{t}{\\sqrt{2}\\sigma_l} \\right)\\right]\n\\end{align*}\n\\end{frame}\n\n\\begin{frame}\n\\frametitle{Simulation setup: Single PE response}\n\\begin{figure}\n    \\centering\n    \\resizebox{0.6\\textwidth}{!}{\\input{img/spe.pgf}}\n    \\caption{Single PE response\\cite{jetter_pmt_2012}}\n\\end{figure}\n\\begin{align*}\n  V_\\mathrm{PE}(t) &= V_{0}\\exp\\left[-\\frac{1}{2}\\left(\\frac{\\log(t/\\tau_\\mathrm{PE})}{\\sigma_\\mathrm{PE}}\\right)^{2}\\right]\n\\end{align*}\n\\end{frame}\n\n\\begin{frame}\n\\frametitle{Data input \\& output}\n\\begin{columns}\n\\column{0.5\\textwidth}\n\\begin{figure}\n    \\centering\n    \\resizebox{1.0\\textwidth}{!}{\\input{img/wave.pgf}}\n    \\caption{Input Waveform (Pedestal free)}\n\\end{figure}\n\\column{0.5\\textwidth}\n\\begin{figure}\n    \\centering\n    \\resizebox{1.0\\textwidth}{!}{\\input{img/charge.pgf}}\n    \\caption{Output Time and Charge $\\hat\\phi(t)$}\n\\end{figure}\n\\end{columns}\n\\begin{align*}\n  \\tilde{\\phi}(t) &= \\sum_{i=1}^{N_{\\mathrm{PE}}} q_i \\delta(t-t_i), \\ N_{\\mathrm{PE}}\\sim \\mathrm{Poisson}(\\mu) \\\\\n  w(t) &= \\tilde{\\phi}(t) \\otimes V_\\mathrm{PE}(t) + \\epsilon(t) = \\sum_{i=1}^{N_\\mathrm{PE}} q_i V_\\mathrm{PE}(t-t_i) + \\epsilon(t)\n\\end{align*}\n\\end{frame}\n\n\\section{Evaluation criteria}\n\n\\begin{frame}\n\\frametitle{Evaluation criteria}\n$\\tilde{\\phi}(t)$ (simulation result) is an approximation of $\\phi(t)$ (time profile). \n\n$\\hat{\\phi}(t)$ (reconstruction result) should be consistent with $\\tilde{\\phi}(t)$. \n\nSeveral evaluation criteria are needed. \n\\begin{block}{}\n\\begin{equation*}\n    \\hat{\\phi}(t) \\leftrightarrow \\tilde{\\phi}(t)\n\\end{equation*}\n\\end{block}\n\\begin{itemize}\n    \\item Residual sum square between $\\hat{w}(t)$ and $w(t)$\n    \\item Wasserstein distance between $\\hat{\\phi}(t)$ and $\\tilde{\\phi}(t)$\n\\end{itemize}\n\\end{frame}\n\n\\section{Fourier deconvolution}\n\n\\begin{frame}\n\\frametitle{Fourier deconvolution}\n\\begin{align*}\n  \\mathcal{F}[w] &= \\mathcal{F}[\\tilde{\\phi}]\\mathcal{F}[V_\\mathrm{PE}] + \\mathcal{F}[\\epsilon],\\Rightarrow \\hat{\\phi}'(t) = \\mathcal{F}^{-1}\\left[\\frac{R \\mathcal{F}[w]}{\\mathcal{F}[V_\\mathrm{PE}]}\\right](t) \\\\\n  \\hat{\\phi}(t) &= \\hat{\\alpha}\\hat{\\phi}'(t),\\hat{\\alpha} = \\arg \\underset{\\alpha'}{\\min}\\mathrm{RSS}\\left[\\alpha'\\hat{\\phi}'(t)\\otimes V_\\mathrm{PE}(t),w(t)\\right]\n\\end{align*}\n\\begin{figure}\n    \\centering\n    \\resizebox{0.55\\textwidth}{!}{\\input{img/fftrans.pgf}}\n    \\caption{$\\mathrm{RSS}=\\SI{124.7}{mV^2},D_w=\\SI{2.03}{ns},\\Delta t_0=\\SI{-1.16}{ns}$}\n\\end{figure}\n\\end{frame}\n\n\\section{Fast Bayesian matching pursuit}\n\n\\begin{frame}\n\\frametitle{Model definition}\n\\begin{itemize}\n    \\item Time in DAQ window is divided into time bins: $\\vec{t}$, whose length is $N$\n    \\item Model vector: $\\vec{z}$. $z_i=0\\implies q_i=0$ and $\\ z_i=1\\implies q_i\\neq0$\n    \\item Linear Model: $\\vec{w} = \\bm{V}_\\mathrm{PE}\\vec{z} + \\vec{\\epsilon}$\n    \\item \n        \\begin{align*}\n            \\left.\n            \\begin{bmatrix}\n                \\vec{w} \\\\\n                \\vec{q}\n            \\end{bmatrix}\n            \\right\\vert\\vec{z}\n            &\\sim \\mathrm{Normal}\\left(\n            \\begin{bmatrix}\n                \\bm{V}_\\mathrm{PE}\\vec{z} \\\\\n                \\vec{z}\n            \\end{bmatrix}, \n            \\begin{bmatrix}\n                \\bm{\\Sigma}_z & \\bm{V}_\\mathrm{PE}\\bm{Z} \\\\\n                \\bm{Z}\\bm{V}_\\mathrm{PE}^\\intercal & \\bm{Z}\n            \\end{bmatrix}\n            \\right) \\\\\n            \\bm{\\Sigma}_z &= \\bm{V}_\\mathrm{PE}\\bm{Z}\\bm{V}_\\mathrm{PE}^\\intercal+\\sigma_\\epsilon^2\\bm{I}\n        \\end{align*}\n    where $\\bm{Z}$ is the diagonal matrix of vector $\\vec{z}$ controlling $q_i$ \n    \\item $\\mathcal{Z}=\\{\\vec{z}_j\\}$ contains \\textcolor{red}{$2^{N}$} model vectors\n    \\item A \\textcolor{red}{repeated greedy search}(RGS) is performed to construct the target set $\\mathcal{Z}'$, which contains only the $\\vec{z}$ giving large $p(\\vec{w}|\\vec{z})$. \n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}\n\\frametitle{Model definition}\n\\tikzstyle{na} = [baseline=-.5ex]\n\\begin{columns}\n\\column{0.5\\textwidth}\n\\begin{figure}\n    \\centering\n    \\resizebox{0.8\\textwidth}{!}{\\input{img/model0.pgf}}\n\\end{figure}\n\\begin{figure}\n    \\centering\n    \\resizebox{0.8\\textwidth}{!}{\\input{img/model3.pgf}}\n\\end{figure}\n\\column{0.5\\textwidth}\n\\begin{figure}\n    \\centering\n    \\resizebox{0.8\\textwidth}{!}{\\input{img/model1.pgf}}\n\\end{figure}\n\\begin{figure}\n    \\centering\n    \\resizebox{0.8\\textwidth}{!}{\\input{img/model2.pgf}}\n\\end{figure}\n\\end{columns}\n\\end{frame}\n\n\\begin{frame}\n\\frametitle{Model selection}\n\\begin{itemize}\n    \\item Calculation of \\textcolor{red}{$2^{N}$} model vectors is impossible!\n    \\item Most of $p(\\vec{w}|\\vec{z}) \\rightarrow 0$!\n\\end{itemize}\n\\noindent\\begin{minipage}[c]{0.33\\textwidth}\n    \\begin{figure}[H]\n        \\centering\n            \\includegraphics[width=0.95\\textwidth]{img/perfect_PE.pdf}\n        \\caption{perfect PE matching waveform, $p(\\vec{z}|\\vec{w})$ hit maximum}\n        \\label{fig:perfect PE}\n    \\end{figure}\n\\end{minipage}\\begin{minipage}[c]{0.33\\textwidth}\n    \\begin{figure}[H]\n        \\centering\n            \\includegraphics[width=0.95\\textwidth]{img/not_so_perfect_PE.pdf}\n        \\caption{not so perfect, $p(\\vec{z}|\\vec{w})$ is smaller but still $>0$}\n        \\label{fig:not so perfect PE}\n    \\end{figure}\n\\end{minipage}\\begin{minipage}[c]{0.33\\textwidth}\n    \\begin{figure}[H]\n        \\centering\n            \\includegraphics[width=0.95\\textwidth]{img/nonsense_PE.pdf}\n        \\caption{Completely mismatch the waveform, $p(\\vec{z}|\\vec{w}) \\rightarrow 0$}\n        \\label{fig:nonsense PE}\n    \\end{figure}\n\\end{minipage}\n\\begin{align*}\n    \\mathcal{Z}' &\\subseteq \\mathcal{Z} \\\\\n    p(\\vec{z}|\\vec{w}) &= \\frac{p(\\vec{w}|\\vec{z})p(\\vec{z})}{\\sum_{\\vec{z}'\\in\\mathcal{Z}}p(\\vec{w}|\\vec{z'})p(\\vec{z'})} \\approx \\frac{p(\\vec{w}|\\vec{z})p(\\vec{z})}{\\sum_{\\vec{z}'\\in\\mathcal{Z}'}p(\\vec{w}|\\vec{z'})p(\\vec{z'})}\n\\end{align*}\n\\end{frame}\n\n\\begin{frame}\n\\frametitle{FBMP's result: Bayesian interface}\n\\begin{itemize}\n    \\item PE Time: $\\vec{t}$\n    \\item Models: $\\mathcal{Z}'=\\{\\vec{z}_j\\}$\n    \\item Charge: \\begin{align*}\n        \\hat{\\vec{q}}_z = E(\\vec{q}|\\vec{w},\\vec{z}) &= \\vec{z} + \\bm{Z}\\bm{V}_\\mathrm{PE}^\\intercal\\bm{\\Sigma}_z^{-1}(\\vec{w}-\\bm{V}_\\mathrm{PE}\\vec{z})\n        \\end{align*}\n    \\item Model's posterior probability: $p(\\vec{z}|\\vec{w})$\n\\end{itemize}\n\\begin{center}\n    Provides opportunity for subsequent Bayesian analysis! \n\\end{center}\n\\end{frame}\n\n\\begin{frame}\n\\frametitle{FBMP demonstration}\n\\begin{figure}\n    \\centering\n    \\resizebox{0.6\\textwidth}{!}{\\input{img/demoe2c0.pgf}}\n    \\caption{$\\mathrm{RSS}=\\SI{15.8}{mV^2},D_w=\\SI{0.59}{ns},\\Delta t_0=\\SI{-3.51}{ns}$}\n\\end{figure}\n\\end{frame}\n\n\\begin{frame}\n\\frametitle{Kullback-Leibler divergence}\n\\begin{align*}\n  \\hat{t}_\\mathrm{KL} &= \\arg\\underset{t_0}{\\max} \\prod_{i=1}^{\\hat{N}} \\left[\\phi(\\hat{t}_i-t_0)\\right]^{\\hat{q}_i} ,\\ \\Delta t = \\hat{t}_\\mathrm{KL} - t_0\n\\end{align*}\n\\begin{figure}\n    \\centering\n    \\resizebox{0.6\\textwidth}{!}{\\input{img/twoprofile.pgf}}\n    \\caption{Time translation between time profiles}\n\\end{figure}\n\\end{frame}\n\n\\begin{frame}\n\\frametitle{$\\mu$ estimation}\nFor Fourier deconvolution, \n\\begin{align*}\n    \\hat{\\mu} &= \\sum_i \\hat{q}_i\n\\end{align*}\nFor FBMP,\n\\begin{align*}\n    \\left(\\hat{t}_0, \\hat{\\mu}\\right) &= \\arg\\underset{t_0,\\mu}{\\max} p(\\vec{w} | t_0, \\mu) \\\\\n    p(\\vec{w}|t_0, \\mu) &= \\sum_{\\vec{z}'\\in\\mathcal{Z}'}p(\\vec{w}|\\vec{z}',t_0,\\mu)p(\\vec{z}'|t_0,\\mu) \\\\\n    &= \\sum_{\\vec{z}'\\in\\mathcal{Z}'}p(\\vec{w}|\\vec{z}')p(\\vec{z}'|t_0,\\mu)\n\\end{align*}\n\\end{frame}\n\n\\begin{frame}\n\\frametitle{FBMP's performance of evaluation criteria}\nFor dataset: $(\\mu, \\tau_l, \\sigma_l)/\\si{ns}=(4, 20, 5)$: \n\\begin{figure}\n    \\centering\n    \\resizebox{\\textwidth}{!}{\\input{img/vs.pgf}}\n    \\caption{$D_w$ and $\\mathrm{RSS}$ of methods}\n\\end{figure}\n\\end{frame}\n\n\\begin{frame}\n\\frametitle{Charge posterior}\n\\begin{figure}\n    \\centering\n    \\resizebox{0.7\\textwidth}{!}{\\input{img/chargehist.pgf}}\n    \\caption{$\\hat{q}$ histogram of methods}\n\\end{figure}\n\\begin{block}{}\nFBMP retains charge distribution of PE. \n\\end{block}\n\\end{frame}\n\n\\begin{frame}\n\\frametitle{Timing \\& charge resolution}\nFor dataset: $(\\tau_l, \\sigma_l)/\\si{ns}=(20, 5)$:\n\\begin{figure}\n    \\centering\n    \\resizebox{\\textwidth}{!}{\\input{img/vs-reso.pgf}}\n    \\caption{Timing \\& charge resolution}\n\\end{figure}\n\\begin{block}{}\nFBMP will have better timing \\& charge resolution. \n\\end{block}\n\\end{frame}\n\n\\section{Summary \\& outlook}\n\n\\begin{frame}\n\\frametitle{Summary}\n\\begin{itemize}\n    \\item Waveform analysis is the first step for any data analysis on JUNO. \n    \\item FBMP restore information of PE most completely, with a Bayesian interface. \n    \\item FBMP will provide better timing and charge resolution. \n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}\n\\frametitle{Outlook}\nFBMP @ JUNO\n\\begin{itemize}\n    \\item Test Hamamatsu PMTs based on their SPE. \n    \\item Test NNVT MCP PMTs based on their SPE. \n    \\item Integrate FBMP with event reconstruction methods. \n\\end{itemize}\n\\end{frame}\n\n\\section{Backup}\n\n\\begin{frame}\n\\frametitle{Residual sum square}\n\\begin{align*}\n  \\mathrm{RSS} &\\coloneqq \\int\\left[\\hat{w}(t) - w(t)\\right]^2\\mathrm{d}t\n\\end{align*}\n\\begin{figure}\n    \\centering\n    \\resizebox{1.0\\textwidth}{!}{\\input{img/tab.pgf}}\n    \\caption{$b_1$ and $b_2$ have the same $\\mathrm{RSS}=0.25$ to $a$, but $b_1$ is closer in timing to $a$}\n\\end{figure}\n\\end{frame}\n\n\\begin{frame}\n\\frametitle{Wasserstein distance}\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=1.0\\linewidth]{img/WD.png}\n    \\caption{Wasserstein Distance when $p=1$: Earth Mover Distance}  \n\\end{figure}\n\\begin{align*}\n  D_w\\left[\\hat{\\phi}_*, \\tilde{\\phi}_*\\right] &= \\inf_{\\gamma \\in \\Gamma} \\left[\\int \\left\\vert t_1 - t_2 \\right\\vert^p \\gamma(t_1, t_2)\\mathrm{d}t_1\\mathrm{d}t_2\\right]^{\\frac{1}{p}}\n\\end{align*}\n\\begin{align*}\n  \\Gamma &= \\left\\{\\gamma(t_1, t_2) ~\\middle\\vert~ \\int\\gamma(t_1,t_2)\\mathrm{d}t_1 = \\tilde{\\phi}_*(t_2) , \\int\\gamma(t_1,t_2)\\mathrm{d}t_2 = \\hat{\\phi}_*(t_1) \\right\\}\n\\end{align*}\nwhen $p=1$, CDF of $\\phi(t)$ is $\\Phi(t)$, $D_w$ is a $\\ell_1$-distance:\n\\begin{align*}\n  D_w\\left[\\hat{\\phi}_*, \\tilde{\\phi}_*\\right] &= \\int\\left|\\hat{\\Phi}(t) - \\tilde{\\Phi}(t)\\right| \\mathrm{d}t\n\\end{align*}\n\\end{frame}\n\n\\begin{frame}\n\\frametitle{Repeated greedy search}\n\\begin{align*}\n    \\log[\\textcolor{red}{p(\\vec{w},\\vec{z})}] =& \\log[p(\\vec{w}|\\vec{z})p(\\vec{z})] \\\\\n    =& -\\frac{1}{2}(\\vec{w}-\\bm{V}_\\mathrm{PE}\\vec{z})^\\intercal\\bm{\\Sigma}_z^{-1}(\\vec{w}-\\bm{V}_\\mathrm{PE}\\vec{z})-\\frac{1}{2}\\log\\det\\bm{\\Sigma}_z \\\\ \n    &-\\frac{N}{2}\\log2\\pi -\\mu + \\sum_{i|z_i=1}\\log \\frac{\\mu \\phi(t'_i - t_0) \\Delta t'}{1-\\mu \\phi(t'_i - t_0) \\Delta t'}\n\\end{align*}\n\\end{frame}\n\n\\begin{frame}\n\\bibliographystyle{unsrt}\n\\bibliography{ref.bib}\n\\end{frame}\n\\end{CJK*}\n\\end{document}", "meta": {"hexsha": "8c589f40a920928fbe412f445cdca0a3b4d51193", "size": 13927, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "junobeamer210813/main.tex", "max_stars_repo_name": "mhy12345/waveform-analysis", "max_stars_repo_head_hexsha": "b71cd456f024eda3ecc04f5f6a69910ce229e86e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-08-03T19:59:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T08:11:31.000Z", "max_issues_repo_path": "junobeamer210813/main.tex", "max_issues_repo_name": "mhy12345/waveform-analysis", "max_issues_repo_head_hexsha": "b71cd456f024eda3ecc04f5f6a69910ce229e86e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 114, "max_issues_repo_issues_event_min_datetime": "2020-08-15T07:56:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T07:26:34.000Z", "max_forks_repo_path": "junobeamer210813/main.tex", "max_forks_repo_name": "mhy12345/waveform-analysis", "max_forks_repo_head_hexsha": "b71cd456f024eda3ecc04f5f6a69910ce229e86e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-08-03T20:01:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-20T01:50:02.000Z", "avg_line_length": 32.5397196262, "max_line_length": 228, "alphanum_fraction": 0.6557765491, "num_tokens": 5196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.31740136032921684}}
{"text": "\\section{Experiments}\n\\label{sec:experiments}\n\nWe present experiments on \\MNIST \\citep{LecunIEEE1998} and \\Cifar \\citep{Krizhevsky2009}. We first analyze the impact of fixed-point quantization schemes on robustness (\\secref{subsec:experiments-quantization}). Subsequently, we discuss weight clipping (\\Clipping, \\secref{subsec:experiments-clipping}), showing that improved robustness originates from increased redundancy in the weight distribution. Then, we focus on random bit error training (\\Random, \\secref{subsec:experiments-randbet}). We show that related work \\cite{KimDATE2018,KoppulaMICRO2019} does not generalize, while \\Random generalizes across chips and voltages, as demonstrated on profiled bit error patterns from different chips. \\secref{subsec:experiments-discussion} summarizes our results for various precisions $m$.\n\n\\begin{table}\n\t\\centering\n\t\\small \n\t\\caption{\\textbf{Robust Quantization}. \\RTE for random bit errors at $p = 0.05\\%$ and $p = 0.5\\%$\n\tfor different quantization schemes, \\cf \\secref{subsec:robustness-quantization}. Minor differences\n\tcan have large impact on \\RTE while clean test error is unaffected. For $8$ bit the second row shows \\Normal quantization (symmetric/per-layer) whereas the last row is our \\Quant.\n\t*\\Clipping[$0.1$]+\\Quant with and without rounding.\n\t}\n\t\\label{tab:quantization-robustness}\n\t\\vspace*{-0.25cm}\n\t\\hspace*{-0.2cm}\n\t\\begin{tabular}{| c | l | c | c | c |}\n\t\t\\hline\n\t\t\\multicolumn{2}{|c|}{Quantization Schemes} & \\multirow{2}{*}{\\begin{tabular}{@{}c@{}}\\TE\\\\in \\%\\end{tabular}}& \\multicolumn{2}{c|}{\\RTE in \\%}\\\\\n\t\t\\cline{4-5} \n\t\t\\multicolumn{2}{|c|}{(%\\Normal on \n\t\t\\CifarT)} && $p{=}0.05$ & $p{=}0.5$\\\\\n\t\t\\hline\n\t\t\\hline\n\t\t\\multirow{5}{*}{\\rotatebox{90}{$8$ bit}} & \\eqnref{eq:quantization}, global & 4.63 & 86.01 {\\color{gray}\\scriptsize ${\\pm}$3.65} & 90.71 {\\color{gray}\\scriptsize ${\\pm}$0.49}\\\\\n\t\t& \\eqnref{eq:quantization}, per-layer & 4.36 & 5.51 {\\color{gray}\\scriptsize ${\\pm}$0.19} & 24.76 {\\color{gray}\\scriptsize ${\\pm}$4.71}\\\\\n\t\t& +asymmetric & 4.36 & 6.47 {\\color{gray}\\scriptsize ${\\pm}$0.22} & {\\color{colorbrewer1}40.78} {\\color{gray}\\scriptsize ${\\pm}$7.56}\\\\\n\t\t& +unsigned & 4.42 & 6.97 {\\color{gray}\\scriptsize ${\\pm}$0.28} & 17.00 {\\color{gray}\\scriptsize ${\\pm}$2.77}\\\\\n\t\t& +rounding (=\\Quant) & 4.32 & \\bfseries 5.10 {\\color{gray}\\scriptsize ${\\pm}$0.13} & \\bfseries 11.28 {\\color{gray}\\scriptsize ${\\pm}$1.47}\\\\\n\t\t\\hline\n\t\t\\hline\n\t\t\\multirow{2}{*}{\\rotatebox{90}{$4$ bit}} & w/o rounding* & 5.81 & 90.40 {\\color{gray}\\tiny ${\\pm}$0.21} & 90.36 {\\color{gray}\\tiny ${\\pm}$0.2}\\\\\n\t\t& w/ rounding* & \\bfseries 5.29 & \\bfseries 5.75 {\\color{gray}\\tiny ${\\pm}$0.06} & \\bfseries 7.71 {\\color{gray}\\tiny ${\\pm}$0.36}\\\\\n\t\t\\hline\n\t\\end{tabular}\n\t\\vspace*{-0.2cm}\n\\end{table}\n\n\\textbf{Metrics:} We report (clean) test error \\TE (lower is better, $\\downarrow$), corresponding to \\emph{clean} weights, and \\textbf{robust test error \\RTE} ($\\downarrow$) which is the \n\\textbf{test error after injecting bit errors into the weights}. As the\nbit errors are random we report the \\emph{average} \\RTE and its standard deviation for $50$ samples of random bit errors with rate $p$ as detailed in \\secref{sec:errors}.\n\n\\textbf{Architecture:} We use SimpleNet \\citep{HasanpourARXIV2016}, providing comparable performance to ResNets \\cite{HeCVPR2016} with only $W{=}5.5\\text{Mio}$ weights on \\CifarT. On \\MNIST, we halve all channel widths, resulting in roughly $1\\text{Mio}$ weights. On \\CifarH, we use a Wide ResNet (WRN) \\cite{ZagoruykoBMVC2016}. As batch normalization (BN) \\cite{IoffeICML2015} yields\nconsistently worse robustness against bit errors we use group normalization (GN) \\cite{WuECCV2018}, see \n\\appref{subsec:supp-experiments-bn}.\n\n\\textbf{Training:} We use stochastic gradient descent with an initial learning rate of $0.05$, multiplied by $0.1$ after $\\nicefrac{2}{5}$, $\\nicefrac{3}{5}$ and $\\nicefrac{4}{5}$ of $100$/$250$ epochs on \\MNIST/\\Cifar. On \\Cifar, we whiten the input images and use AutoAugment \\cite{CubukARXIV2018} with Cutout \\cite{DevriesARXIV2017}. For \\Random, random bit error injection starts when the loss is below 1.75 on \\MNIST/\\CifarT or 3.5 on \\CifarH. Normal training with the standard and our robust quantization are denoted \\Normal and \\Quant, respectively. Weight clipping with $\\wmax$ is referred to as \\Clipping[\\wmax] or together with \\Random as \\Random[\\wmax]. \nFor \\Quant, $m = 8$, we obtain $4.3\\%$ on \\CifarT and $18.5\\%$ \\TE on \\CifarH. On \\MNIST, $0.47\\%$ are possible even for $m = 2$. \n\n\\begin{table}\n\t\\centering\n\t\\caption{\\textbf{Weight Clipping Robustness.} Clean \\TE and \\RTE as well as clean confidence and confidence at $p{=}1\\%$ bit errors (in \\%, higher is better, $\\uparrow$) for \\Clipping and \\Clipping with label smoothing (+LS). \\TE increases for $\\wmax = 0.025$ where the DNN is not able to produce large (clean) confidences. LS consistently reduces robustness, indicating that robustness is due to enforcing high confidence during training \\emph{and} weight clipping.}\n\t\\label{tab:clipping-robustness}\n\t\\vspace*{-0.25cm} \n\t\\small \n\t\\hspace*{-0.2cm}\n\t\\begin{tabular}{| l | c | c | c | c | c |}\n\t\t\\hline\n\t\tModel & \\multirow{2}{*}{\\begin{tabular}{@{}c@{}}\\TE\\\\in \\%\\end{tabular}} & \\multirow{2}{*}{\\begin{tabular}{@{}c@{}}Conf\\\\in \\%\\end{tabular}} & \\multirow{2}{*}{\\begin{tabular}{@{}c@{}}Conf\\\\$p{=}1$\\end{tabular}} & \\multicolumn{2}{c|}{\\RTE in \\%}\\\\\n\t\t\\cline{5-6}\n\t\t(\\CifarT) & & & & $p{=}0.1$ & $p{=}1$\\\\\n\t\t\\hline \n\t\t\\hline\n\t\t\\Quant & \\bfseries 4.32 & \\bfseries 97.42 & 78.43 & 5.54 & 32.05\\\\\n\t\t\\hline\n\t\t\\Clipping[$0.15$] & 4.42 & 96.90 & 88.41 & \\bfseries  5.31 & 13.08\\\\\n\t\t\\Clipping[$0.1$] & 4.82 & 96.66 & 92.97 & 5.58 & 8.93\\\\\n\t\t\\Clipping[$0.05$] & 5.44 & 95.90 & \\bfseries 94.73 & 5.90 & \\bfseries 7.18\\\\\n\t\t\\Clipping[$0.025$] & 7.10 & {\\color{colorbrewer1}84.69} & 83.28 & 7.40 & 8.18\\\\\n\t\t\\hline\n\t\t\\Clipping[$0.15$]+LS & 4.67 & 88.22 & 47.55 & 5.83 & {\\color{colorbrewer2}29.40}\\\\\n\t\t\\Clipping[$0.1$]+LS & 4.82 & 87.90 & 78.89 & 6.10 & 10.59\\\\\n\t\t\\Clipping[$0.05$]+LS & 5.30 & 87.41 & 85.04 & 6.43 & 7.30\\\\\n\t\t\\hline\n\t\\end{tabular}\n\t\\vspace*{-0.2cm}\n\\end{table}\n\nOur \\textbf{appendix} includes implementation details (\\appref{sec:supp-implementation}), more information on our experimental setup (\\appref{subsec:supp-experiments-setup}), and complementary experiments (\\appref{sec:supp-experiments}). Among others, we discuss the robustness of BN (\\appref{subsec:supp-experiments-bn}), other architectures such as ResNet-50 (\\appref{subsec:supp-experiments-bn}), qualitative results for \\Clipping (\\appref{subsec:supp-experiments-clipping}) and complete results for $m = 4,3,2$ bits precision (\\appref{subsec:supp-experiments-summary}). Also, we discuss a simple guarantee how the average \\RTE relates\nto the true expected robust error (\\appref{subsec:supp-bound}). Our \\textbf{code} will be made publicly available.\n\n\\subsection{Quantization Choice Impacts Robustness}\n\\label{subsec:experiments-quantization}\n\nQuantization schemes affect robustness significantly, even when not affecting accuracy. \n\\tabref{tab:quantization-robustness} shows that per-layer quantization reduces \\RTE significantly for small bit error rates, \\eg, $p = 0.05\\%$. While asymmetric quantization further reduces the quantization range, \\RTE increases, especially for large bit error rates, \\eg, $p = 0.5\\%$ (marked in {\\color{colorbrewer1}red}). This is despite \\figref{fig:quantization} showing a slightly smaller impact of bit errors. This is caused by an asymmetric quantization into \\emph{signed} integers: Bit flips in the most significant bit (MSB, \\ie, sign bit) are not meaningful if the quantized range is not symmetric as the sign bit does not reflect the sign of the represented weight value, see \\appref{subsec:supp-experiments-quantization}. Similarly, replacing integer conversion of $\\nicefrac{w_i}{\\Delta}$ by proper rounding, $\\lceil\\nicefrac{w_i}{\\Delta}\\rfloor$, reduces \\RTE significantly (resulting in our \\Quant).\nThis becomes particularly important for $m = 4$. Here, rounding also improves clean \\TE slightly, but the effect is significantly less pronounced. Proper rounding generally reduces the quantization error. However, it is striking that this has little impact on \\TE but tremendous effect on \\RTE.\nFor $m = 4$ or lower, we also found weight clipping to help training, obtaining lower \\TE.\nOverall, random bit errors induce unique error distributions, \\cf \\figref{fig:quantization}, heavily dependent on quantization details.\n\n\\begin{table}[t]\n\t\\centering\n\t\\caption{\\textbf{Fixed Pattern Bit Error Training.} \\RTE for training on an entirely fixed bit error pattern (\\Pattern). \\emph{Top:} Evaluation on the same pattern; \\Pattern trained on $p = 2.5\\%$ does not generalize to $p = 1\\%$ even though the bit errors for $p = 1\\%$ are a subset of those seen during training for $p = 2.5\\%$ (in {\\color{colorbrewer1}red}). \\emph{Bottom:} \\Pattern also fails to generalize to completely random bit errors. This can be confirmed on profiled bit errors in \\appref{subsec:supp-randbet-baselines}.}\n\t\\label{tab:randbet-baselines}\n\t\\vspace*{-0.25cm}\n\t\\small\n\t\\begin{tabular}{| l | c | c |}\n\t\t\\hline\n\t\tModel (\\CifarT) & \\multicolumn{2}{c|}{\\RTE in \\%, $p$ in \\%}\\\\\n\t\t\\hline\n\t\t\\hline\n\t\t\\textbf{Evaluation on Fixed Pattern} & $p{=}1$ & $p{=}2.5$\\\\\n\t\t\\hline\n\t\t\\Pattern $p{=}2.5$ & {\\color{colorbrewer1}14.14} & 7.87\\\\\n\t\t\\Pattern[$0.15$] $p{=}2.5$ & {\\color{colorbrewer1}8.50} & 7.41\\\\\n\t\t\\hline\\hline\n\t\t\\textbf{Evaluation on \\emph{Random} Patterns} & $p{=}1$ & $p{=}2.5$\\\\\n\t\t\\hline\n\t\t\\Pattern[$0.15$] $p{=}2.5$ & 12.09 & 61.59\\\\\n\t\t\\hline\n\t\\end{tabular}\n\t\\vspace*{-0.2cm}\n\\end{table}\n\n\\subsection{Weight Clipping Improves Robustness}\n\\label{subsec:experiments-clipping}\nWhile the quantization range adapts to the weight range\nafter every update during training, weight clipping explicitly constraints the weights to $[-\\wmax, \\wmax]$.\n\\tabref{tab:clipping-robustness} shows the effect of\ndifferent $\\wmax$ for \\CifarT with 8 bit precision. The clean test error is not affected for \\Clipping[$\\mathbf{\\wmax{=}0.15}$] but\none has already strong robustness improvements for $p=1\\%$\ncompared to \\Quant (\\RTE of 13.18\\% vs 32.05\\%). Further reducing $\\wmax$ leads to a slow increase in clean \\TE and decrease in average clean confidence, while significantly\nimproving \\RTE to $7.18\\%$ for $p=1\\%$ at $\\wmax=0.05$. For $\\wmax=0.025$\nthe DNN is no longer able to achieve high confidence (marked in {\\color{colorbrewer1}red}) which leads to stronger loss of clean \\TE. Interestingly, the gap between clean and perturbed confidences under bit errors for $p=1\\%$ is (almost) monotonically decreasing. These findings generalize to other datasets and precisions, see \\appref{subsec:supp-experiments-summary}. However, for low precision $m\\leq 4$ the effects are stronger \nas \\Quant alone does not yield any robust models and weight clipping is essential for achieving robustness. \n\nAs discussed in \\secref{subsec:robustness-clipping} the robustness of the DNN originates in the cross-entropy loss enforcing high confidences on the training set and, thus, large logits while weight clipping works against having large logits. Therefore, the network has to utilize more weights with larger absolute values (compared to $\\wmax$).\nIn order to test this hypothesis, we limit the confidences that need to be achieved via label smoothing \\cite{SzegedyCVPR2016}, targeting $0.9$ for the true class and $\\nicefrac{0.1}{9}$ for the other classes. According to \\secref{subsec:robustness-clipping}, this should lead to less robustness, as the DNN has to use ``fewer'' weights. Indeed, in \\tabref{tab:clipping-robustness}, \\RTE at $p=1\\%$ increases from $13.08\\%$ for \\Clipping[$0.15$] to $29.4\\%$ when using label smoothing (marked in {\\color{colorbrewer2}blue}). Moreover, the difference between average clean and perturbed confidence is significantly larger for DNNs trained with label smoothing. \n\nIn \\appref{subsec:supp-experiments-clipping} we show that robustness against bit errors also leads to robustness against $L_\\infty$ perturbations which generally affect all weights in contrast to random bit errors, and provide more qualitative results about the change of the weight distribution induced by clipping in \\figref{fig:supp-clipping}.\n\n\\begin{table}[t]\n\t\\centering\n\t\\small\n\t\\caption{\\textbf{Random Bit Error Training (\\Random).} Average \\RTE (and standard deviation) of \\Random evaluated at various bit error rates $p$ and using $m = 8$ or $4$ bit precision. For low $p$, weight clipping provides sufficient robustness. However for $p \\geq 0.5$, \\Random increases robustness significantly. This is pronounced for lower precisions.}\n\t\\label{tab:randbet-robustness}\n\t\\vspace*{-0.25cm}\n\t\\hspace*{-0.25cm}\n\t\\begin{tabular}{|@{\\hskip 3px}c@{\\hskip 3px}|@{\\hskip 3px}l@{\\hskip 3px}|@{\\hskip 3px}c@{\\hskip 3px}|@{\\hskip 3px}c@{\\hskip 3px}|@{\\hskip 3px}c@{\\hskip 3px}|@{\\hskip 3px}c@{\\hskip 3px}|}\n\t\t\\hline\n\t\t& Model (\\CifarT) & \\multirow{2}{*}{\\begin{tabular}{@{}c@{}}\\TE\\\\in \\%\\end{tabular}} &\\multicolumn{3}{c|}{\\RTE in \\%}\\\\\n\t\t\\cline{4-6}\n\t\t& $\\mathbf{\\wmax{=}0.1}$, $p$ in \\% && $p{=}0.5$ & $p{=}1$ & $p{=}1.5$\\\\\n\t\t\\hline\n\t\t\\hline\n\t\t\\multirow{5}{*}{\\rotatebox{90}{$8$bit}} & \\Quant & \\bfseries 4.32 & 11.28 {\\color{gray}\\tiny ${\\pm}$1.47} & 32.05 {\\color{gray}\\tiny ${\\pm}$6} & 68.65 {\\color{gray}\\tiny ${\\pm}$9.23}\\\\\n\t\t& \\Clipping & 4.82 & 6.95 {\\color{gray}\\tiny ${\\pm}$0.24} & 8.93 {\\color{gray}\\tiny ${\\pm}$0.46} & 12.22 {\\color{gray}\\tiny ${\\pm}$1.29}\\\\\n\t\t& \\Random $p{=}1$ & 4.90 & \\bfseries 6.36 {\\color{gray}\\tiny ${\\pm}$0.17} & \\bfseries 7.41 {\\color{gray}\\tiny ${\\pm}$0.29} & \\bfseries 8.65 {\\color{gray}\\tiny ${\\pm}$0.37}\\\\\n\t\t\\hline\n\t\t\\multirow{2}{*}{\\rotatebox{90}{$4$bit}} & \\Clipping & \\bfseries 5.29 & 7.71 {\\color{gray}\\tiny ${\\pm}$0.36} & 10.62 {\\color{gray}\\tiny ${\\pm}$1.08} & 15.79 {\\color{gray}\\tiny ${\\pm}$2.54}\\\\\n\t\t& \\Random $p{=}1$ & 5.39 & \\bfseries 7.04 {\\color{gray}\\tiny ${\\pm}$0.21} & \\bfseries 8.34 {\\color{gray}\\tiny ${\\pm}$0.42} & \\bfseries 9.77 {\\color{gray}\\tiny ${\\pm}$0.81}\\\\\n\t\t\\hline\n\t\\end{tabular}\n\t\\vspace*{-0.2cm}\n\\end{table}\n\n\\subsection{\\Random Yields Generalizable Robustness}\n\\label{subsec:experiments-randbet}\n\n\\textbf{Training on Profiled Errors Does Not Generalize:}\n%\\label{subsec:experiments-baselines}\n%\nCo-design approaches such as \\cite{KimDATE2018,KoppulaMICRO2019} combine training DNNs on profiled SRAM or DRAM bit errors with hardware-approaches to limit the errors' impact.\nHowever, profiling SRAM or DRAM requires expensive infrastructure, expert knowledge and time. \nMore importantly, training on profiled bit errors does not generalize to previously unseen bit error distributions (\\eg, other chips or voltages): \\tabref{tab:randbet-baselines} (top) shows \\RTE of \\Pattern, \\ie, pattern-specific bit error training. The main problem is that \\Pattern does \\emph{not} even generalize to lower bit error rates (\\ie, higher voltages) of the same pattern as trained on (marked in {\\color{colorbrewer1}red}). This is striking as, following \\figref{fig:errors}, the bit errors form a subset of the bit errors seen during training: training with $p = 2.5\\%$ bit errors does not provide robustness for $p = 1\\%$, \\RTE increases $7.9\\%$ to $14.1\\%$. It is not surprising, that \\tabref{tab:randbet-baselines} (bottom) also demonstrates that \\Pattern does not generalize to random bit error patterns: \\RTE increases from $7.4\\%$ to $61.6\\%$ at $p = 2.5\\%$. The same observations can be made when training on real, profiled bit errors corresponding to the chips in \\figref{fig:errors}, see \\appref{subsec:supp-randbet-baselines}.\nOverall, obtaining robustness that generalizes across voltages \\emph{and} chips is crucial for low-voltage operation to become practical.\n\n\\begin{table}[t]\n\t\\centering\n\t\\small\n\t\\caption{\\textbf{Generalization to Profiled Bit Errors.} \\RTE for \\Random on two different profiled chips. The bit error rates differ across chips due to measurements at different voltages, also see \\figref{fig:errors}. Chip 2 exhibits a bit error distribution significantly different from uniform random bit errors: bit errors are strongly aligned along columns and biased towards $0$-to-$1$ flips, \\cf \\figref{fig:errors}. Nevertheless, \\Random generalizes surprisingly well.}\n\t\\label{tab:randbet-generalization}\n\t\\vspace*{-0.25cm}\n\t\\hspace*{-0.15cm}\n\t\\begin{tabular}{| l | l | c | c |}\n\t\t\\hline\n\t\tChip (\\figref{fig:errors}) & Model (\\CifarT)& \\multicolumn{2}{c|}{\\RTE in \\%}\\\\\n\t\t\\hline\n\t\t\\hline\n\t\t\\bfseries Chip 1 && $p{\\approx}0.86$ & {\\color{colorbrewer1}$p{\\approx}2.75$}\\\\\n\t\t\\hline\n\t\t& \\Random[$0.05$] $p{=}1.5$ & 7.04 & 9.37\\\\\n\t\t\\hline\n\t\t\\hline\n\t\t\\bfseries Chip 2 && $p{\\approx}0.14$ & {\\color{colorbrewer1}$p{\\approx}1.08$}\\\\\n\t\t\\hline\n\t\t& \\Random[$0.05$] $p{=}1.5$ & 6.00 & 9.00\\\\\n\t\t\\hline\n\t\\end{tabular}\n\t\\vspace*{-0.2cm}\n\\end{table}\n\\begin{figure*}[t]\n\t\\centering\n\t\\vspace*{-0.1cm}\n\t\\hspace*{-0.3cm}\n\t\\begin{subfigure}{0.32\\textwidth}\n\t\t\\centering\n\t\t\\includegraphics[width=5.75cm]{c10_pareto_8bit}\n\t\\end{subfigure}\n\t\\hfill\n\t\\begin{subfigure}{0.32\\textwidth}\n\t\t\\centering\n\t\t\\includegraphics[width=5.75cm]{c100_pareto_8bit}\n\t\\end{subfigure}\n\t\\hfill\n\t\\begin{subfigure}{0.32\\textwidth}\n\t\t\\centering\n\t\t\\includegraphics[width=5.75cm]{m_pareto_8bit}\n\t\\end{subfigure}\n\t\n\t\\hspace*{-0.1cm}\n\t\\fbox{\n\t\\begin{subfigure}{0.98\\textwidth}\n\t\t\\centering\n\t\t\\includegraphics[width=1\\textwidth]{c10_legend}\n\t\\end{subfigure}\n\t}\n\t\\vspace*{-14px}\n\t\\caption{\\textbf{Bit Error Robustness on \\CifarT, \\CifarH and \\MNIST.} Average \\RTE plotted against bit error rate $p$, both in \\%. We considered various models (in {\\color{gray}$\\bullet$ gray}), corresponding to different $\\wmax$ and $p$ during training. We explicitly plot the best model for each bit error rate: for \\Normal ({\\color{colorbrewer5}orange}), \\Quant ({\\color{colorbrewer1}red}), \\Clipping ({\\color{colorbrewer2}blue}) and \\Random ({\\color{colorbrewer4}violet}). Note that these might correspond to different $\\wmax$ and $p$ (also across datasets). Across all approaches, we plot the per-error-rate best model in black: for $m = 8,4,3,2$ bits, depending on dataset. For $8$ bit and low bit error rates, \\Clipping is often sufficient. However, for $4$ bit or higher bit error rates, \\Random is crucial to keep \\RTE low.}\n\t\\label{fig:summary}\n\t\\vspace*{-0.2cm}\n\\end{figure*}\n\n\\textbf{\\Random Improves Robustness:}\n%\\label{subsec:experiments-randbet}\n%\n\\Random, with weight clipping, further improves robustness and additionally generalizes across chips and voltages. \\tabref{tab:randbet-robustness} shows results for weight clipping and \\Random with $\\wmax = 0.1$ and $m = 8,4$ bits precision. \\Random is particularly effective against large bit error rates, \\eg, $p = 1.5\\%$, reducing \\RTE from $12.22\\%$ to $8.65\\%$ ($m = 8$ bits). The effect is pronounced for $4$ bits or even lower precision, where models are generally less robust. The optimal combination of weight clipping and \\Random depends on the bit error rate. For example, in \\tabref{tab:clipping-robustness}, lowering $\\wmax$ to $0.05$ reduces \\RTE below \\Random[$0.1$] with $p{=}1\\%$ for some bit error rates.\nWe emphasize that \\Random generalizes to lower bit errors than trained on, in stark contrast to the fixed-pattern training \\Pattern. In \\appref{subsec:supp-experiments-architectures}, we also show that \\Random works on other architectures such as ResNet-50. On other datasets, \\eg,\\MNIST, \\Random allows to operate at $p = 12.5\\%$ bit error rate with $0.9\\%$ \\RTE and only $m = 2$ bits. At this point, weight clipping alone yields $90\\%$ \\RTE.\n\n\\textbf{\\Random Generalizes to Profiled Bit Errors:}\n%\\label{subsec:experiments-generalization}\n% \n\\Random also generalizes to profiled bit errors from real chips. \\tabref{tab:randbet-generalization} shows results on the two profiled chips of \\figref{fig:errors}. Profiling was done at various voltage levels, resulting in different bit error rates. To simulate various weights to memory mappings, we apply various offsets before linearly mapping weights to the profiled SRAM arrays. \\tabref{tab:randbet-generalization} reports average \\RTE, showing that \\Random generalizes quite well to these profiled bit errors. Regarding chip 1, \\Random performs very well, even for large $p\\approx 2.75$, as the bit error distribution of chip 1 largely matches our error model in \\secref{sec:errors}, \\cf \\figref{fig:errors} (left). In contrast, with chip 2 we picked a more difficult bit error distribution which is strongly aligned along columns, potentially hitting many MSBs simultaneously. Thus, \\RTE increases for chip 2 even for a lower bit error rate $p \\approx 1.08$ (marked in {\\color{colorbrewer1}red})\nbut energy savings are still possible without degrading prediction performance. \n\n\\subsection{Summary and Discussion}\n\\label{subsec:experiments-discussion}\n \nOur experiments are summarized in \\figref{fig:summary}. We consider \\Normal quantization vs. our robust quantization \\Quant, various \\Clipping and \\Random models with different $\\wmax$ and $p$ during training (indicated in {\\color{gray}$\\bullet$ gray}) and plot \\RTE against bit error rate $p$ at test time. On all datasets \\Quant outperforms \\Normal. On \\CifarT (left), \\RTE increases significantly for \\Quant ({\\color{colorbrewer1}red}) starting at $p \\approx 0.25\\%$ bit error rate. While \\Clipping ({\\color{colorbrewer2}blue}) generally reduces \\RTE, only \\Random ({\\color{colorbrewer4}violet}) can keep \\RTE around $6\\%$ or lower for a bit error rate of $p \\approx 0.5\\%$. The best model for each bit error rate $p$ (black and solid for $m = 8$) might vary. \\CifarH is generally more difficult, while significantly higher bit error rates are possible on \\MNIST. On \\CifarT, \\RTE increases slightly for $m = 4$. However, for $m = 3,2$ \\RTE increases more significantly as clean \\TE increases by $1-2\\%$. % which likely due to our simple quantization. \nNevertheless, \\RTE only increases slightly for larger bit error rates $p$. It remains future work whether \\Random with a more sophisticated (but robust) quantization scheme can enable low-voltage operation even for $m = 2$ bits. In all cases, \\RTE increases monotonically, ensuring safe operation at higher voltages. The best trade-off between robustness and accuracy depends on the application: higher energy savings require a larger ``sacrifice'' in terms of \\RTE.\nFinally, \\appref{subsec:supp-bound} provides a\nconfidence-interval based guarantee on how strongly \\RTE is expected to deviate from the empirical results in \\figref{fig:summary}.\n\nOverall, the results in \\figref{fig:summary} enable robust low-voltage operation \\emph{without} requiring expensive error correcting codes (ECCs) or other circuit techniques \\cite{ReagenISCA2016,ChandramoorthyHPCA2019}. Furthermore, our analysis applies both to DRAM, commonly off-chip, and SRAM, usually used as scratchpads on-chip of DNN accelerators. Compared to co-design \\cite{KimDATE2018,KoppulaMICRO2019}, we do not require expensive expert knowledge or profiling infrastructure. Moreover, \\Random improves over these approaches by generalizing across chips and voltages.\nBesides \\Random, we show that robust fixed-point quantization \\emph{only with} weight clipping can provide reasonable robustness, \\eg, for $p = 0.1\\%$ on \\CifarT. This is without sophisticated quantization scheme, \\eg, with special treatment for outliers \\cite{ZhuangCVPR2018,SungARXIV2015,ParkISCA2018}, and complementary to  \\cite{MurthyARXIV2019,MerollaARXIV2016,SungARXIV2015,AlizadehICLR2020}, focusing merely on robustness \\emph{to} quantization.\n", "meta": {"hexsha": "a00b3ad26390804b15899c1a1ab90fb0d2728a27", "size": 23543, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/sec_experiments.tex", "max_stars_repo_name": "davidstutz/mlsys2021-bit-error-robustness", "max_stars_repo_head_hexsha": "3d9c4d6c3bab61c75201f758a40937768ea18b99", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paper/sec_experiments.tex", "max_issues_repo_name": "davidstutz/mlsys2021-bit-error-robustness", "max_issues_repo_head_hexsha": "3d9c4d6c3bab61c75201f758a40937768ea18b99", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/sec_experiments.tex", "max_forks_repo_name": "davidstutz/mlsys2021-bit-error-robustness", "max_forks_repo_head_hexsha": "3d9c4d6c3bab61c75201f758a40937768ea18b99", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 95.7032520325, "max_line_length": 1055, "alphanum_fraction": 0.7260332158, "num_tokens": 7688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.31740136032921684}}
{"text": "\\documentclass{article} % For LaTeX2e\n\\usepackage{nips13submit_e,times}\n\\usepackage{hyperref}\n\\usepackage{url}\n\\usepackage{mathtools}\n%\\documentstyle[nips13submit_09,times,art10]{article} % For LaTeX 2.09\n\n\\title{Traffic Counting with Kalman Filters}\n\n\n\\author{\nAnthony M Lozano\\\\\nDepartment of Computer Science\\\\\nGeorgia Institute of Technology\\\\\n\\texttt{amlozano1@gmail.com} \\\\\n}\n\n% The \\author macro works with any number of authors. There are two commands\n% used to separate the names and addresses of multiple authors: \\And and \\AND.\n%\n% Using \\And between authors leaves it to \\LaTeX{} to determine where to break\n% the lines. Using \\AND forces a linebreak at that point. So, if \\LaTeX{}\n% puts 3 of 4 authors names on the first line, and the last on the second\n% line, try using \\AND instead of \\And before the third author name.\n\n\\newcommand{\\fix}{\\marginpar{FIX}}\n\\newcommand{\\new}{\\marginpar{NEW}}\n\n\\nipsfinalcopy % Uncomment for camera-ready version\n\n\\begin{document}\n\n\\maketitle\n\n\\begin{abstract}\nCounting vehicles is an important function for traffic video data analysis. This paper examines an approach using a Shi-Tomasi corner detector with a Lucas Kanade Optical flow pyramid to create data measurements. After clustering tracked data measurements, a Kalman Filter is used to process the data in order to finally determine if a vehicle passes through the video. Our implementation of this method shows some success, but needs refinement.\n\\end{abstract}\n\n\\section{Background/Problem Description}\n\\label{sec:background}\n\nAccurate traffic data has diverse applications; Civil Engineers use it to design, construct, and maintain roadways.  It is utilized by Policy Makers to allocate funding for such projects, and business owners may need it to make sound decisions about location. In addition, this information can be used to estimate the environmental impact of roadways and to perform other similar usage based calculations.\n\nWhile the data is certainly useful, extant methods of collecting it are more expensive and cumbersome than necessary. The chief problems of current solutions are portability, setup time, and need for humans to process the data. Portability might not be an issue for areas where traffic data will need to be collected permanently, but usually agencies want a system that can move easily to take measurements from many sites. Some examples of less portable systems include inductive loop sensors installed into the roadway itself, or the TRAX Stealth Stud, which is another device that needs to be installed into the pavement.  Installing these devices requires closing the road, which is not ideal in situations where even a relatively short road closure may cause major disruptions, such as urban areas. Pneumatic loop sensors, which look like small black tubes that are laid perpendicularly over the road, are an effective solution, but some jurisdictions in the United States require that workers close the road when they are putting these up anyway for safety reasons. Other systems use a camera to record video and a human later counts the cars going by, producing very accurate data at the cost of being labor intensive and time consuming. These systems and devices are also expensive, costing thousands of dollars for a single unit or many man hours of labor to operate a single unit\n\nThis paper attempts to create a software analysis tool that can perform one of the most basic tasks for traffic data collection; counting how many cars have gone in a particular direction in a video. This software tool would enable anyone with a camera to collect traffic data. \n\n\\section{Hypothesis and Project Approach}\n\\label{sec:hypothesis}\n\nComputer vision techniques for tracking motion in video combined with a Kalman Filter should be able to track vehicles and plot their movements. The software will then record the starting and ending points of each successfully tracked vehicle, thus establishing counts for each origin and destination. \n\n\\section{Implementation Details}\n\\label{sec:implementation}\n\nThe Kalman Car Counter program will need to perform six major tasks to count vehicles. These tasks are background subtraction (or foreground detection), feature detection, optical flow estimation, optical flow clustering, and finally Kalman Filtering.\n\n\\subsection{Background Subtraction}\n\\label{subsec:back_subract}\n\nBackground subtraction is the process of removing noise and unmoving sections of an image.  The Kalman Car Counter uses the simple process of frame differencing to remove the background for speed. Frame difference at a time $t$ can be calculated as \n$ D(t+1) = V(x,y,t+1) - V(x,y,t) $ for each pixel $(x,y)$~\\cite{Birgi09}.\nThis calculation will allow the subsequent algorithms to focus solely on areas of the video that contain motion, helping isolate vehicles and removing image noise.\n\n\\subsection{Feature Detection}\n\\label{subsec:feature_detec}\n\nFeature detection is the process of finding good features of an image for tracking. For vehicle tracking, Shi-Tomasi corner detection is a solid algorithm choice that expands on standard Harris corner detection, and will allow us to zero in on the \"corners\" of vehicles. Briefly, the algorithm works as follows: If we can assume the time between frames is small, we can describe the changes between them as image motion. If we take a patch of an image defined by $(u,v)$ and shift it by $(x,y)$, the weighted sum of squared differences between the two patches, $S$ is given by \\\\*\n\n{\\centering\n$ S(x,y) = \\sum\\limits_{u}\\sum\\limits_{v}w(u,v)(I(u+x, v+y) - I(u,v))^2$\\linebreak\\newline\\\\*}\n$I(u+x,v+y)$ can be approximated bu a Taylor expansion with $I_x,$ and $I_y$ being the partial derivatives of $I$ such that:\\\\*\n\n{\\centering\n$I(u+x,v+y)) \\approx I(u,v) (I_x(u,v) x+I_y(u,v) y)^2$\\linebreak\\newline\\\\*}\nwhich produces the approximation\\\\*\n\n{\\centering\n$S(x,y) \\approx \\sum\\limits_{u}\\sum\\limits_{v}w(u,v) (I_x(u,v) x+I_y(u,v) y)^2$\\linebreak\\newline\\\\*}\nwhich in matrix form is\\\\*\n\n{\\centering\n$S(x,y) \\approx \\left(\\begin{smallmatrix}\nx & y\n\\end{smallmatrix}\\right) A\n\\left(\\begin{smallmatrix}\nx\\\\\ny\n\\end{smallmatrix}\\right)$\\linebreak\\newline\\\\*}\nwhere $A$ is the structure tensor\\\\*\n\\\\*\n\n{\\centering\n$\nA = \\sum_u \\sum_v w(u,v) \n\\begin{bmatrix}\nI_x^2 & I_x I_y \\\\\nI_x I_y & I_y^2 \n\\end{bmatrix}\n=\n\\begin{bmatrix}\n\\langle I_x^2 \\rangle & \\langle I_x I_y \\rangle\\\\\n\\langle I_x I_y \\rangle & \\langle I_y^2 \\rangle\n\\end{bmatrix}$\\linebreak\\newline\\\\*}\nA corner is then found if $S$ has a large variation in all directions of the vector $\\begin{pmatrix} x & y \\end{pmatrix}$. Thus, if $A$ has two positive eigenvalues that are large in comparison to other eigenvalues, a corner is found~\\cite{tommasini1998making}. The Shi-Tomasi corner detector takes a practical shortcut and only calculates $min(\\lambda_1, \\lambda_2)$ rather than doing a complete eigenvalue decomposition in the interest of speed and because this is sufficient to find features with great accuracy~\\cite{Shi94}.\n\n\\subsection{Optical Flow}\nOnce we have determined what features in the image to track, we actually need to track them. To accomplish this, the Kalman Car Counter will use another well known algorithm, the Lucas-Kanade method. This method assumes that pixels move a small amount between frames, and the movement of the pixels is approximatly the same for all pixels in the neighborhood of a point $p$~\\cite{lucas1981iterative}. Therefore, the optical flow equation should hold for all pixels in a window centered at $p$. This means the local velocity of a feature $(V_x,V_y)$ must satisfy the equations:\\\\*\n\n{\\centering\n$I_x(q_1) V_x + I_y (q_1) V_y = -I_t(q_1)$\\\\*\n$I_x(q_2) V_x + I_y (q_2) V_y = -I_t(q_2)$\\\\*\n$\\vdots$\\\\*\n$I_x(q_n) V_x + I_y (q_n) V_y = -I_t(q_n)$\\linebreak\\newline\\\\\n}\nwhere $q_1,q_2,\\dots,q_n$ are the pixels around a feature inside the window and $I_x(q_i),I_y(q_i),I_t(q_i)$ are the partial derivatives if the image $I$ with respect to position and time $x,y,$ and $t$\n\nThis system of equations can be written in the matrix form:\\\\*\n\n{\\centering\n$A = \\begin{bmatrix}\nI_x(q_1) & I_y(q_1) \\\\[10pt]\nI_x(q_2) & I_y(q_2) \\\\[10pt]\n\\vdots  & \\vdots  \\\\[10pt]\nI_x(q_n) & I_y(q_n) \n\\end{bmatrix},\n\\quad\\quad\nv = \n\\begin{bmatrix}\nV_x\\\\[10pt]\nV_y\n\\end{bmatrix},\n\\quad \\mbox{and}\\quad\nb = \n\\begin{bmatrix}\n-I_t(q_1) \\\\[10pt]\n-I_t(q_2) \\\\[10pt]\n\\vdots  \\\\[10pt]\n-I_t(q_n)\n\\end{bmatrix}\n$\\linebreak\\newline\\\\*}\nThis overdetermined system is solved with a compromise solution by the least squares principle, solving the 2x2 system:\\\\*\n\n{\\centering\n$A^T A v=A^T b$\\linebreak\\newline\\\\*}\nBouguet presents a pyramidal implementation of the Lucase Kanade tracker~\\cite{bouguet2001pyramidal}, which is the particular implementation that the Kalman Car Counter uses. If the Lucas-Kanade tracker tracks the features detected in the previous step successfully, we can use those features as data points for our Kalman Filter.\n\n\\subsection{Optical Flow Data Clustering}\n\\label{subsec:optical_flow}\n\nThe Lucas-Kande tracker can return many successfully tracked features for a single vehicle. We can leverage this by clustering the tracked features to combine them into a single point. Because we cannot predict how many vehicles will be in a frame, we use a agglomerative hierarchical clustering scheme. We use cophenetic distance $t$ as a criterion for automatic clustering of the data, expecting different vehicle feature clusters to have a large distance between them. Once the data is clustered, the means of each cluster that has at least $n$ elements is assigned to a Kalman Filter.\n\n\\subsection{Hungarian Algorithm}\n\\label{subsec:hungarian_algo}\n\nOnce each cluster's mean has been established, we intend to again track each cluster, but this time using a Kalman Filter (described in Section~\\ref{subsec:kalman_filter}) in order to be more tolerant to noise, occlusion, and merged clusters. Thus, each cluster must be assigned to a Kalman filter. For each existing Kalman filter, we attempt to assign the nearest cluster to that filter for measurement updates. In order so solve the assignment problem we use the Kuhn-Munkres or, simply, Munkres algorithm~\\cite{munkres1957algorithms}. It solves a cost matrix where $a1$ would be the distance from a cluster mean $a$ to a filter's next prediction $1$:\\\\*\n\n{\\centering\n$\\begin{bmatrix}\na1 & a2 & a3 & a4\\\\\nb1 & b2 & b3 & b4\\\\\nc1 & c2 & c3 & c4\\\\\nd1 & d2 & d3 & d4\\end{bmatrix}$\\linebreak\\newline\\\\*}\nSolving this cost matrix for the minimum cost produces assignments for each cluster. If the algorithm assigns a cluster to a Kalman filter, it is used as a measurement update for that Kalman filter for the frame. Note that this matrix can be rectangular; there could be more clusters than Kalman filters or more filters than clusters. If there are more Kalman filters than clusters, Kalman filters that do not get an assignment are marked as \"Lost\" and do not receive a measurement update. Lost Kalman filters accumulate a Loss Counter each subsequent frame they are lost in until they are either deleted or are again assigned to a cluster. A filter can also be lost if it's best assignment is to far away.  On the other hand, if there are more clusters than Kalman Filters, a new filter is created for each new cluster, instantiated with initial position equal to the cluster mean.\n\n\\subsection{Kalman Filter}\n\\label{subsec:kalman_filter}\n\nThe final step solves a practical problem: even with all the previous steps, our measurements are still somewhat noisy measurements of the vehicles location in the video. In order to better track the vehicles, we pass the measurements through a Kalman filter. The filter allows us to track vehicles even if vehicles' measurements are noisy, vehicles are temporarily occluded, or vehicles' clusters merge.\n\nThe Kalman filter requires several matrices, the most important of which is the next state function. This Kalman filter will model the motion of the vehicles using a simple system $F$ of $(x,y)$ position and velocity. \\\\*\n\n{\\centering\n$F = \\begin{bmatrix}\n1 & 0 & dt & 0\\\\\n0 & 1 & 0 & dt\\\\\n0 & 0 & 1 & 0\\\\\n0 & 0 & 0 & 1\\end{bmatrix}$\\linebreak\\newline\\\\*}\nRead in simple English, this matrix means that the next state's position should be estimated using the prior position and velocity multiplied by the change in time. The change in time is set to the number of seconds between each frame of the video. For example, in a 30 frames-per-second video, $dt$ would be .5 seconds.\nEach Kalman filter will have it's initial state $X$ set to the mean of the cluster $(x,y)$ that created it with no initial velocity, that is $V_x = 0$ and $V_y = 0$. \\\\*\n\n{\\centering\n$X = \\begin{bmatrix}\nx \\\\\ny \\\\\n0 \\\\\n0 \\end{bmatrix}$\\linebreak\\newline\\\\*}\nour measurement update function will be\\\\*\n\n{\\centering\n$H = \\begin{bmatrix}\n1 & 0 \\\\\n0 & 1 \\\\\n0 & 0 \\\\\n0 & 0 \\end{bmatrix}$\\linebreak\\newline\\\\*}\nSince we can measure $x$ and $y$ but not $V_x$ or $V_y$ the uncertainty for the velocity will be set very high, while the uncertainty for position will be set relatively low.\\\\*\n\n{\\centering\n$R = \\begin{bmatrix}\n 1 & 0 & 0 & 0\\\\\n 0 & 1 & 0 & 0\\\\\n 0 & 0 & 1000 & 0\\\\\n 0 & 0 & 0 & 1000\\end{bmatrix}$\\linebreak\\newline\\\\*}\n\nThe Kalman filter performs prediction step and calculates the posterior position $X'$:\\\\*\n\n{\\centering\n$X' = FX+u$\\linebreak\\newline\\\\*}\nand it updates uncertainty by:\\\\*\n\n{\\centering\n$P' = F \\cdot P \\cdot F^T$\\linebreak\\newline\\\\*}\nSimilarly, after each prediction step, a measurement update step must be performed with a new measurement $Z$.\\\\*\n\n{\\centering\n$Y = Z - H \\cdot X$\\\\*\n $S = H \\cdot P \\cdot H^T + R$\\\\*\n $K = P \\cdot H^T \\cdot S^{-1}$\\\\*\n $X' = X + (K\\cdot Y)$\\\\*\n $P' = (I - K \\cdot H) \\cdot P $\\linebreak\\newline\\\\*}\n With these two steps iterating every frame, we track each vehicle's starting location to ending location. With the tracked vehicle starting and ending positions in hand, we can count vehicles entering the scene and leaving the scene.\n \n\\section{Technical Specifications}\n\\label{sec:technical_specs}\n\nThe Kalman Car Tracker has been implemented in the Python programming language. This implementation uses several technologies to accomplish it's task. The foremost is \\texttt{OpenCV} (Open Source Computer Vision Library), an open source computer vision and machine learning software library. \\cite{wiki:opencv} It contains many optimized and state-of-the art algorithms of use to this project with Python bindings. In particular, the background subtraction, Shi-Tomasi corner detection, Lucas-Kanade optical flow tracking, and Kalman filteings all come from the \\texttt{OpenCV} library. The hierarchical data clustering algorithm comes from another powerful Python library known as \\texttt{SciPy}. Munkres linear assignment comes from a additional \\texttt{(Scipy)} library by Lars Buitinck.\\cite{scipy}\n\nTo test this method, a dataset was captured with a cellphone camera on a highway overpass. A video was recorded from the center of the overpass overlooking the freeway at a resolution of 1080p for three minutes. The overpass vibrated, introducing much noise for our particular background subtraction method. In addition, the camera was held in hand; no tripod or other stabilization was used to record video.\n\nThe video processing took approximately 15 minutes for 3 minutes of video on a Intel i7 960 CPU @ 3.20 GHz.\n\n\n\n\\section{Analysis of Results}\n\\label{sec:analysis}\n\nIn the first half of the sample video on the left (oncoming) lanes of traffic, $24/35$ , or about 68\\%, of vehicles were successfully tracked. Our definition of successfully tracked is that Kalman filter tracking the car was assigned for at least the last 6 frames of the car being in the image. Having the car successfully tracked when it leaves the frame would be sufficient to count the car as having flowed under the overpass.  While clearly there is room for improvement, this shows the method implemented in this tool can successfully track vehicles and perform the counting task. The parameters for various methods were not optimized, and the tool is far from complete, but these preliminary results seem promising. Perhaps with optimization and refinement this method could be used as envisioned to enabled simple unattended capture of traffic data.\n\n\n\\section{Conclusion}\n\\label{sec:conclusion}\n\nIn this paper, we present a method for collecting traffic data using a simple camera and computer vision processing, even in the presence of occlusion. The method needs refinement, but can successfully track vehicles. This method seems to have trouble differentiating between clusters of tracked optical flows when they are tightly packed, which could prove a large problem for dense traffic flows. This problem might be solved with a better camera perspective, but the best camera perspectives, such as top down, make the detection process much more trivial and come with disadvantages similar to those provided in the introduction: they are costly and hard to set up. Future research could explore other options for clustering that may help alleviate this issue. \n\n\\section{Presentation and Github}\n\\label{sec:presentation}\nA quick 5 minute presentation of this implementation is available at \\url{https://www.youtube.com/watch?v=CMG_3c9UbsE}.\n\\\\*\\\\*\nA longer, more complete presentation is also available at \\url{http://youtu.be/lEuYAGPUJWk}\n\\\\*\\\\*\nThe implementation source code is available at \\url{https://github.com/amlozano1/kalman_car_counter} under the MIT License. \n\n\\nocite{*}\n\\bibliographystyle{plain}\n\\bibliography{KalmanBib}\n\\end{document}\n", "meta": {"hexsha": "42bde57bd1155086c5c0c81131ba3c7d68cbed67", "size": 17569, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Paper/KalmanCarCounter.tex", "max_stars_repo_name": "amlozano1/kalman_car_counter", "max_stars_repo_head_hexsha": "0804a476e1b767365415d41cddf9d5946dd871ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2015-05-01T12:51:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-06T11:45:47.000Z", "max_issues_repo_path": "Paper/KalmanCarCounter.tex", "max_issues_repo_name": "amlozano1/kalman_car_counter", "max_issues_repo_head_hexsha": "0804a476e1b767365415d41cddf9d5946dd871ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Paper/KalmanCarCounter.tex", "max_forks_repo_name": "amlozano1/kalman_car_counter", "max_forks_repo_head_hexsha": "0804a476e1b767365415d41cddf9d5946dd871ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2015-04-27T07:33:54.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-22T13:33:59.000Z", "avg_line_length": 68.3618677043, "max_line_length": 1389, "alphanum_fraction": 0.7703910297, "num_tokens": 4369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5389832058771035, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3174013516074269}}
{"text": "\\section{Example}\n\n\\begin{lstlisting}[style=default]\nProgram {\n  [ GridDimension {ncol}, GridDimension {nlay}, GridDimension {ngpt}],\n  Domain {\n    parallel_domain_dim : ncol,\n    vertical_dim : nlay,\n    parallel_dim : ngpt\n  },\n  FieldDecl {\n    real, [GridDimension {ncol}],\n    name : mu0\n  },\n  FieldDecl {\n    real, [GridDimension {ncol}, GridDimension{nlay}, GridDimension{ngpt}],\n    name : tau\n  },\n  FieldDecl {\n    real, [GridDimension {ncol}, GridDimension {nlay}, GridDimension{ngpt}]\n    name : w0\n  },\n  FieldDecl {\n    real, [GridDimension {ncol}, GridDimension {nlay}, GridDimension {ngpt}],\n    name : g\n  },\n  FieldDecl {\n    real, [GridDimension {ncol}, GridDimension{nlay}],\n    name : Rdif\n  },\n  FieldDecl {\n    real, [GridDimension {ncol}, GridDimension {nlay}],\n    name : Tdif\n  },\n  FieldDecl {\n    real, [GridDimension {ncol}, GridDimension {nlay}],\n    name : Rdir\n  },\n  FieldDecl {\n    real, [GridDimension {ncol}, GridDimension {nlay}],\n    name : Tdir\n  },\n  FieldDecl {\n    real, [GridDimension {ncol}, GridDimension {nlay}],\n    name : Tnoscat\n  },\n  VarDecl {\n    int,\n    name : ncolbounds,\n    isarg : true\n  },\n  VarDecl {\n    int,\n    name : nlaybounds,\n    isarg : true\n  },  \n  ScopedProgram {\n    // two_stream (Missing arg list, name of what is called, shouldn't inline stuff at this point)\n    // adding_sw (same as up)\n    // additional_step (same as up)\n    // two_stream\n    VarDecl {\n      real,\n      name : mu0_inv\n    },\n    VarDecl {\n      real,\n      name : mu0_inv\n    },\n    VarDecl {\n      real,\n      name : gamma1\n    },\n    VarDecl {\n      real,\n      name : gamma2\n    },\n    VarDecl {\n      real,\n      name : gamma3\n    },\n    VarDecl {\n      real,\n      name : gamma4\n    },\n    VarDecl {\n      real,\n      name : alpha1\n    },\n    VarDecl {\n      real,\n      name : alpha2\n    },\n    VarDecl {\n      real,\n      name : k\n    },\n    VarDecl {\n      real,\n      name : RT_term\n    },\n    VarDecl {\n      real,\n      name : exp_minusktau\n    },\n    VarDecl {\n      real,\n      name : exp_minus2ktau\n    },\n    VarDecl {\n      real,\n      name : k_mu\n    },\n    VarDecl {\n      real,\n      name : k_gamma3\n    },\n    VarDecl {\n      real,\n      name : k_gamma4\n    },\n    BlockStmt {\n      // Computation, this is the only stmt that we will express as a tree. \n      // From this on, pseudocode for the statements will be used\n      AssignmentStmt {\n        VarAccess {\n          name : mu0_inv\n        },\n        divOp {\n          VarAccess {\n            name : mu0\n          },\n          Literal {\n            real,\n            value : 1.0\n          }\n        }\n      },\n      Computation {\n        [ GridDimension {name: ngpt}, GridDimension {name: ncol} ],\n        DimensionInterval {\n          GridDimension {name : nlay},\n          DimensionLevel {\n            VarAccess { \n              Literal {0},\n\t      name : nlaybounds\n            },\n            offset : 0\n          },\n          DimensionLevel {\n            VarAccess { \n              Literal {1},\n\t      name : nlaybounds\n            },\n            offset : 0\n          }\n        },\n        BlockStmt {\n          AssignmentStmt {\n            VarAccess {\n              name : gamma1\n            },\n            mulOp {\n              minusOp {\n                Literal { 8.0 },\n                mulOp {\n                  VarAccess { name : w0 },\n                  addOp {\n                    Literal { 5.0 },\n                    mulOp {\n                      Literal { 3.0 },\n                      VarAccess { name : g }\n                    }\n                  }\n                }\n              },\n              Literal { 0.25 }\n            },\n            lineno : 654,\n            file : sw_solver.f90\n          },\n          AssignmentStmt {\n            VarAccess { name : gamma2},\n            mulOp {\n              Literal { 3.0 },\n              mulOp {\n                mulOp {\n                  VarAccess { name : w0 },\n                  minusOp {\n                    Literal { 1.0 },\n                    VarAccess { name : g }\n                  }\n                },\n                Literal { 0.25 }\n              }\n            },\n            lineno : 655,\n            file : sw_solver.f90\n          },\n          AssignmentStmt {\n            VarAccess { name : gamma3 },\n            mulOp {\n              minusOp {\n                Literal { 2.0 },\n                mulOp {\n                  mulOp {\n                    Literal { 3.0 },\n                    VarAccess { name : mu0 }\n                  },\n                  VarAccess { name : g }\n                }                  \n              },\n              Literal { 0.25 }\n            }\n          }\n          AssignmentStmt {\n            VarAccess { name : gamma4 },\n            minusOp {\n              Literal { 1.0 },\n              VarAccess { name : gamma3 }\n            }\n          }\n\n          % Rest of the program not represented as HIR\n          % alpha1 = gamma1 * gamma4 + gamma2 * gamma3 \n          % alpha2 = gamma1 * gamma3 + gamma2 * gamma4 \n          % k = sqrt(max((gamma1 - gamma2) * (gamma1 + gamma2), 1.e-12_wp))\n          % exp_minusktau = exp(-tau * k)\n          % exp_minus2ktau = exp_minusktau * exp_minusktau\n          % RT_term = 1._wp / (k * (1._wp + exp_minus2ktau)  + gamma1 * (1._wp - exp_minus2ktau) )\n          % Rdif = RT_term * gamma2 * (1._wp - exp_minus2ktau)\n          % Tdif = RT_term * 2._wp * k * exp_minusktau\n          % Tnoscat = exp(-tau * mu0_inv)\n          % k_mu     = k * mu0\n          % k_gamma3 = k * gamma3\n          % k_gamma4 = k * gamma4\n          % RT_term =  w0 * RT_term/merge(1._wp - k_mu*k_mu, epsilon(1._wp), abs(1._wp - k_mu*k_mu) >= epsilon(1._wp))\n          % Rdir = RT_term  * ((1._wp - k_mu) * (alpha2 + k_gamma3) -  (1._wp + k_mu) * (alpha2 - k_gamma3) * exp_minus2ktau - 2.0_wp * (k_gamma3 - alpha2 * k_mu)  * exp_minusktau  * Tnoscat)\n          % Tdir = Tnoscat - RT_term * ((1._wp + k_mu) * (alpha1 + k_gamma4) * Tnoscat - (1._wp - k_mu) * (alpha1 - k_gamma4) * exp_minus2ktau * Tnoscat - 2.0_wp * (k_gamma4 + alpha1 * k_mu)  * exp_minusktau)\n          % Tdir -= Tnoscat\n        }   \n      }\n    }\n  }\n}\n\\end{lstlisting}\n", "meta": {"hexsha": "549de1d14d15e2182096587ed8931fa074d25ab2", "size": 6167, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/example.tex", "max_stars_repo_name": "MeteoSwiss-APN/HIR", "max_stars_repo_head_hexsha": "70c9031f9e72da160e1e933cf464027201a04140", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-16T21:39:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T21:39:53.000Z", "max_issues_repo_path": "doc/example.tex", "max_issues_repo_name": "MeteoSwiss-APN/HIR", "max_issues_repo_head_hexsha": "70c9031f9e72da160e1e933cf464027201a04140", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2018-05-28T10:10:07.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-30T10:39:22.000Z", "max_forks_repo_path": "doc/example.tex", "max_forks_repo_name": "MeteoSwiss-APN/HIR", "max_forks_repo_head_hexsha": "70c9031f9e72da160e1e933cf464027201a04140", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-04-06T12:08:41.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-01T14:05:02.000Z", "avg_line_length": 24.967611336, "max_line_length": 208, "alphanum_fraction": 0.4493270634, "num_tokens": 1645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.31736523551513973}}
{"text": "\\chapter{Attack Design}\n\nIn this section, we describe the overall design of our automatic feature generation models, outline the attack strategy and explain certain design decisions.\nMost of this section will be split into two different parts.\nFirst, we describe the feature generation processes and then the overall attack.\n\n\\section{Stacked Autoencoder}\n\nA stacked autoencoder takes a fixed-length input vector and tries to learn a function that compresses that vector.\nThus if we were to use it for a fingerprinting extraction task, we will need to preprocess the variable-length traces into a fixed-length input.\nThere are various different manners of doing this.\nOne of the most naive ones is to find the longest length trace and pad all of the other traces up to that length.\nHowever, in Greschbach et al.'s dataset, this length is around $250,000$ \\cite{greschbach2016effect}, which means that our network will need to be incredibly deep to extract a short trace.\n\nInstead, we can pick the average or median length of the traces and cut or pad traces which are longer or shorter.\nIn this work we will investigate the average length, which is around $3,000$.\nBut the median length might be slightly more appropriate, as the length is positively skewed.\nOn top of that, we deal with the fact that each packet is represented by a tuple, by just multiplying the time by the direction.\nTherefore, all of the outgoing packets are positive whilst the incoming ones will be negative.\n\nFinally, since the output of the activation functions used is either between 0 and 1 or -1 and 1, we will scale the inputs accordingly.\n\n\\section{Sequence-to-Sequence Model}\n\nAs described in section \\ref{sec:seq2seq}, a sequence-to-sequence model is able to learn how to construct a fixed-length representation from a variable-length sequence, which means that we will not have to perform as much preprocessing as for our autoencoder.\n\nAlthough we already know the overall structure, there are still a couple of design decisions that had to be made specifically for our attack.\nThese decisions are outlined in the following section.\n\nOne of the first parameters which we will examine is the \\textit{amount of hidden states} in the RNN cells.\nThis number affects the amount of neurons for each layer with the cells.\nFor instance if the amount of hidden states is set to $100$, the state of an LSTM cell is represented by vector of length $200$ (two vectors of length $100$).\nThe higher this number, the easier it should be to learn a representation, as the compression factor is lower.\nBut we also need to consider the fact that the higher the amount of hidden neurons, the more variables the model needs to learn and thus the more complex the model will be are.\n\nEach value in a trace can be represented by a vector of length two (timestamp and direction), as seen in table \\ref{table:cell-extract}.\nTherefore, if the amount of hidden cells is not equal to two, we will also need to \\textit{project} the input and output vectors into the necessary dimensions.\n\n\\begin{figure}[ht]\n  \\centering\n  \\includegraphics[width=0.7\\textwidth]{lstm-projection}\n  \\caption{Example of projection within a LSTM cell with 4 hidden states.}\n  \\label{fig:lstm-projection}\n\\end{figure}\n\n\\newpage\n\nSome of the traces can be particularly long and therefore the network needs to be unrolled to extreme lengths \\cite{greschbach2016effect}.\nIn fact, given memory constraints, this becomes a major problem.\nBut it can be solved by cutting the traces after a couple seconds since it has been shown that the first part of a trace carries more information than the latter.\n\n\\begin{figure}[ht]\n  \\centering\n  \\includegraphics[width=\\textwidth]{full-seq2seq}\n  \\caption{Overal structure of our sequence-to-sequence model.}\n  \\label{fig:full-seq2seq}\n\\end{figure}\n\nBased on the above, we can construct our \\textit{computational graph} in Tensorflow as outlined in figure \\ref{fig:full-seq2seq}.\n\n\\section{Attack Strategy}\n\nHere we consider an adversary that relies on deep learning to extract fingerprints for a website fingerprinting attack.\nThis adversary can have two different goals in mind, as previously stated in section \\ref{sec:threat-model}.\nThe full attack, however, can be split up into four different stages, namely \\textit{data collection}, \\textit{fingerprint extraction training}, \\textit{classifier training} and \\textit{the attack}.\n\n\\noindent\n\\textbf{Data Collection}\n\\begin{enumerate}\n  \\item Choose web pages that the attacker wishes to monitor.\n  \\item Collect traffic for a set of monitored and unmonitored sites.\n  \\item Convert the raw TCP data into Tor cells.\n  \\item Remove SENDMEs and other noise.\n\\end{enumerate}\n\n\\noindent\n\\textbf{Fingerprint Extraction Training}\n\\begin{enumerate}[resume]\n  \\item Further process the data into batches and perform any other preprocessing required by the model such as cutting or padding the traces.\n  \\item Prepare the fingerprint extraction model.\n  \\item Train the fingerprint extraction model on a copy task for monitored and some unmonitored web pages.\n  \\item Extract fingerprints from data by using the trained model.\n\\end{enumerate}\n\n\\noindent\n\\textbf{Classifier Training}\n\\begin{enumerate}[resume]\n  \\item Given a classifier, train it using the extracted fingerprints.\n  \\item Measure performance of classifier.\n\\end{enumerate}\n\n\\noindent\n\\textbf{The Attack}\n\\begin{enumerate}[resume]\n  \\item Passively capture traffic from Tor users.\n  \\item Pre-process the collected data.\n  \\item Extract fingerprints using the trained fingerprint extraction model.\n  \\item Classification via the trained classifier.\n\\end{enumerate}\n\n\\begin{figure}[ht]\n  \\centering\n  \\includegraphics[width=0.7\\textwidth]{overall-structure}\n  \\caption{Attack strategy.}\n  \\label{fig:attack-strategy}\n\\end{figure}\n\n\\subsection{Data Collection} \\label{sec:data_collection1}\n\nAs previously mentioned, the data collection process first requires the adversary to choose a set of $n$ websites to monitor.\nNext, the adversary crawls these pages a total of $i$ iterations to ensure that a classifier has enough data to generalize.\nAs suggested by Wang et al. when performing page loads, browser caching should be disabled since Tor does not allow caching to disk and therefore the browser cache should be cleared every time a web page is loaded \\cite{wang_goldberg_2013}.\nAfter the collection, the TCP data is converted into Tor cells and probabilistic algorithms, designed by Wang et al. \\cite{wang_goldberg_2013}, are used to remove SENDMEs from the data.\nThis data can be processed further, however we chose not to since the model should be able to learn how to perform this processing.\n\nMost of our analysis will be done using the dataset provided by Greschbach et al. \\cite{greschbach2016effect}, which can be used for open-world analysis since it provides us with $100$ samples for Alexa's top $9000$ websites and one sample of one sample for $909,000$ unmonitored sites.\nFor the rest of this paper, we will refer to this dataset as \\texttt{GRESCHBACH}.\nNext, to see how our model performs on data, which was recorded at a different time and under different circumstances, we will also be using the dataset provided by Wang et al. \\cite{wang_cai_johnson_nithyanand_goldberg_2014}, which we will call \\texttt{WANG14} \\cite{panchenko2}.\nThis set is slightly smaller with $100$ monitored websites with $90$ instances each and $8400$ unmonitored sites.\n\n\\subsection{Fingerprint Extraction Training} \\label{sec:fingerprint-extraction-training}\n\nIn order to truly evaluate the model, we need to split the data up into a training and a validation set.\nWe do not train the model on any data in the validation set but instead use it to see how well the model performs on unseen data.\nFor this split, we use a \\textit{stratified shuffle split}, meaning that we shuffle the data and then perform the split, whilst preserving the class distributions.\nOn top of training the feature extractor with monitored pages, we also train it on unmonitored pages, as it needs to be able to extract features effectively from both sets.\n\nDuring training and extracting the fingerprints, \\textit{mini-batch processing} will always be used.\nThis will allow us to gain a performance boost and perhaps even have a faster convergence.\nWhen dividing the data up into these batches, we also need to determine how big they will be.\nThe bigger they are, the larger the performance gain will be but the lower the accuracy might be.\nAdditionally, the size of the batches also depend on the amount of available memory since we cannot have the VM run out of memory whilst training.\n\nOn top of determining the batch size, the individual models require different preprocessing steps and tuning of different parameters.\n\n\\subsubsection{Stacked Autoencoder}\n\nAs previously mentioned, after dividing the data up into batches, we either need to cut or pad the traces such that they all are of a fixed-length.\nNext, we know that the first layer needs to have the same amount of neurons than the length of the input.\nBut after that, there are a variety of different architectures that need to be chosen.\nSome of which are outlined below:\n\n\\newpage\n\n\\begin{itemize}\n  \\item How many hidden layers we want.\n    The more there are, the more complex the function that can be modeled but also the harder it becomes to train the model.\n\n  \\item The amount of hidden neurons in each layer.\n    This number should gradually decrease to the number of features we would like to extract.\n\n  \\item The activation function of the neurons.\n    The most popular ones being \\textit{sigmoid}, \\textit{ReLu} and an \\textit{atan}.\n\n  \\item Whether or not to include batch normalization at every step.\n\\end{itemize}\n\nAfter that the model has been constructed, there are still several learning parameters that need to be tuned:\n\n\\begin{itemize}\n    \\item The optimizer to use (\\textit{adam}, \\textit{gradient descent} or \\textit{RMSProp}) \\cite{tensorflow}.\n    \\item Learning rate ($\\gamma$) for the previously chosen optimizer.\n    \\item Amount of traces within a single mini-batch ($m$).\n    \\item Cost, or loss function ($f$) to minimize (\\textit{mean squared error} (MSE), \\textit{absolute loss} (AL) or \\textit{cross-entropy}) \\cite{tensorflow}.\n\\end{itemize}\n\n\\subsubsection{Sequence-to-Sequence Model}\n\nEach batch can either be presented in \\textit{batch-major} or \\textit{time-major} form.\nAlthough time-major is slightly more efficient \\cite{tensorflow}, we opt for a batch-major form, since it makes the fingerprint extraction process easier.\nNext, after the data has been divided into mini-batches, we perform some further processing such as cutting the traces after several seconds.\nFinally, since all of the traces within a batch need to be of the same length, padding is performed as a final preprocessing step.\n\nAfter collecting and fully preprocessing the data, the adversary can start to construct the sequence-to-sequence model.\nHowever, in order to do so, there are a variety of different architectures that need to be considered, some of which are outlined below:\n\n\\begin{itemize}\n  \\item Which sort or RNN cells to use. The most popular ones being GRU or LSTM cells.\n    We could also potentially investigate the usefulness of multilayered RNN cells but we expect the performance gain to be limited, which is why we do not consider them in our evaluation.\n\n  \\item Whether or not to use a bidirectional encoder to ensure that the output at time $t$ is not only affected by past information but also on future information.\n\n  \\item The amount of hidden states within a RNN cell, which affects the size of the fingerprints.\n\\end{itemize}\n\nNow that the model has been constructed, the adversary again has to chose various learning parameters such as:\n\n\\newpage\n\n\\begin{itemize}\n  \\item The optimizer to use (\\textit{adam}, \\textit{gradient descent} or \\textit{RMSProp}) \\cite{tensorflow}.\n  \\item Learning rate ($\\gamma$) for the previously chosen optimizer.\n  \\item Amount of traces within a single mini-batch ($m$).\n  \\item Cost, or loss function ($f$) to minimize (\\textit{mean squared error} (MSE), \\textit{absolute loss} (AL) or \\textit{cross-entropy}) \\cite{tensorflow}.\n  \\item After how much time the traces are cut.\n\\end{itemize}\n\nAfter these parameters have been tuned, the computational graph can be constructed in Tensorflow and the model can be trained.\nWhen this training has been completed, fingerprints can finally be extracted for all the traces in the test set.\n\n\\subsection{Classifier Training} \\label{sec:classifier-training}\n\nWhen the adversary has extracted the fingerprints for websites within the test set, they need to train a classifier on those fingerprints.\nMost works so far rely on some sort of \\textit{supervised machine learning} techniques such as \\textit{support vector classifiers} (SVC), \\textit{k-nearest neighbours} (kNN), \\textit{random forests} (RF) or \\textit{naive bayes} (NB) \\cite{panchenko1,panchenko2,wang_cai_johnson_nithyanand_goldberg_2014,kfingerprinting,naivebayes}.\nAll of these algorithms rely on different techniques but an explanation of their inner workings is outside the scope of this paper.\nInstead, we will consider them as \\textit{black box models}.\nThis means that all we know is that we can apply a \\texttt{fit} function to the models, which causes them to learn how to classify the fingerprints and a \\texttt{predict} function, which predicts the classes of given inputs.\n\nTo measure the performance of our black-box models, we use a similar technique as we did in the previous section.\nWe split our test set up into two more sets, a \\textit{classifier training set} and a \\textit{classifier test set}.\nBut since training a classifier, requires less time, we can use another technique, called \\textit{stratified k-fold validation}.\nHere we split our original test set up into $k$, mutually exclusive, folds.\nNext, one of the folds is chosen to be the classifier test set and all of the other folds form the classifier training set.\nThis process is repeated for $k$ iterations, where at each iteration, a different fold is chosen to be the test set.\nBut again, we preserve the class distributions within all of the folds.\n\n\\begin{figure}[ht]\n  \\centering\n  \\includegraphics[width=0.6\\textwidth]{kfold}\n  \\caption{Example of one iterations in a k-fold validation $(k = 7)$.}\n  \\label{fig:kfold}\n\\end{figure}\n\nFor each iteration of the validation process, several statistics can be recorded and then averaged over all iterations.\nThe k-fold validation process ensures that every data point will be in the test set at least once and therefore giving us an accurate measure of these statistics.\n\nSome of the performance measures that we will use in the evaluation stage are outlined below.\nPlease note that we describe them within the context of a WF attack:\n\\begin{itemize}\n  \\item \\textbf{True Positive Rate (TPR)} is the probability that a monitored page is classified as the correct monitored page \\cite{kfingerprinting}.\n\n  \\item \\textbf{False Positive Rate (FPR)} is the probability that an unmonitored page is incorrectly classified as a monitored page \\cite{kfingerprinting}\n\n  \\item \\textbf{Bayesian Detection Rate (BDR)} is the probability that a page corresponds to the correct monitored page, given that the classifier recognized it as that monitored page \\cite{kfingerprinting}.\n    This can be calculated as follows:\n    $$\\text{BDR} = \\frac{\\textit{TPR} \\times \\Pr(M)}{\\textit{TPR} \\times \\Pr(M) + \\textit{FPR} \\times \\Pr(U)}$$\n    where\n    $$\\Pr(M) = \\frac{|\\text{Monitored}|}{|\\text{Total Pages}|}, \\quad \\Pr(U) = 1 - \\Pr(M)$$\n\n    This measure essentially indicates the practical feasibility of the attack, as the adversary is mainly concerned with this specific measure \\cite{kfingerprinting}.\n\n  \\item \\textbf{Accuracy (A)} is the percentage of correctly classified instances.\n    Although it can be used as a rough indicator, it will not be used in the final conclusions because of the \\textit{accuracy paradox}, which arises due to class imbalance.\n\n  \\item \\textbf{F1-Score (F1)} measures the harmonic mean between precision and recall \\cite{scikitlearn}.\n    \\begin{align*}\n      \\text{F1} &= 2 \\times \\frac{\\text{precision} \\times \\text{recall}}{\\text{precision} + \\text{recall}}\\\\\n                &= \\frac{2 \\times \\textit{TP}}{2 \\times \\textit{TP} + \\textit{FP} + \\textit{FN}}\n    \\end{align*}\n    where\n    $$\\text{recall} = \\frac{\\textit{TP}}{\\textit{TP} + \\textit{FN}}, \\quad \\text{precision} = \\frac{\\textit{TP}}{\\textit{TP} + \\textit{FP}}$$\n\n    This measure is particularly useful since it is not affected by class imbalance.\n\\end{itemize}\n\nRather than using another classifier, we could potentially add a \\textit{softmax layer} on top of our encoder, like V. Rimmer uses on top of her stacked autoencoder \\cite{deeplearningthesis}.\nWe could use this idea for both our autoencoder and the sequence-to-sequence model.\n\nThis process would involve first training the sequence-to-sequence model, then stacking the softmax layer on top of each unrolled cell in the encoder and using it for classification.\nWhat would be interesting about this approach is that the adversary can analyse how certain the classifier is, as it analyses packets more and more packets from the trace.\nBut unfortunately this is outside the scope of this paper, as we are solely focusing on the feature extraction process.\n\n\\begin{figure}[ht]\n  \\centering\n  \\includegraphics[width=0.55\\textwidth]{softmax}\n  \\caption{Example of encoder with softmax layer for 3 web pages.}\n  \\label{fig:softmax}\n\\end{figure}\n\n\\newpage\n\n\\subsection{The Attack}\n\nFinally, after the adversary has trained the required models, the real WF attack can start.\nFirst, the adversary starts capturing web traffic data between the user and the entry guard, as shown in figure \\ref{fig:threat_model}.\nNext, the data is preprocessed for the fingerprint extraction process, as described in section \\ref{sec:fingerprint-extraction-training}.\nAfter all the preprocessing has finished, fingerprints are extracted using the previously trained model.\nFinally, those fingerprints are used as features for a classifier, which classifies the traffic into web pages.\n\nThe time between data collection for training and performing the WF has to be kept as small as possible since Juarez et al.'s experiments show that web pages' content changes greatly over time, therefore affecting the accuracy of the attack \\cite{wfpevaluation}.\n\n\\section{Code Structure} \\label{sec:code-structure}\n\nIn this work, we will not be conducting the final stage of a WF attack.\nInstead, we will be reporting the results on the test sets.\nAll of this is reflected in the overall structure of the code, which consists of four main components, as can be seen in figure \\ref{fig:code-structure}.\n\n\\begin{figure}[ht]\n  \\centering\n  \\includegraphics[width=\\textwidth]{code-structure}\n  \\caption{Diagram of how different components are related.}\n  \\label{fig:code-structure}\n\\end{figure}\n\nAll of the data that is used within this work has already been preprocessed into Tor cells with SENDMEs removed, as described in section \\ref{sec:data_collection1}.\nThe \\texttt{feature\\_generation} module contains all of the code to further preprocess the data, train the fingerprint extraction models and to extract the fingerprints using the respective model.\n\nThe classifiers that will be used for the attacks are defined in the \\texttt{attacks} module.\nWe tried to pick a variety of existing models to measure how well our extracted fingerprints work on different classifiers.\nThe code to actually test the attacks is defined in the \\texttt{run\\_models} module, which also does some data preprocessing, defines the logic for the stratified k-fold validation and the different scoring methods.\n\n\\newpage\n\nFinally, there is also the \\texttt{feature\\_extraction} module, which is used to extract hand-picked features from the raw data.\n\nAs can be seen, all of the code is written in Python, due to the wide availability of machine learning tools.\nExcept for the \\texttt{kNN.go} file, in the \\texttt{feature\\_extraction} module, which is adapted from Pylls and written in \\textit{Golang} to gain a performance boost \\cite{gokNN}.\n", "meta": {"hexsha": "cab2491575b267883c7c11da2aa50ad7a3712a0b", "size": 20260, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/chapters/implementation.tex", "max_stars_repo_name": "AxelGoetz/website-fingerprinting", "max_stars_repo_head_hexsha": "17b1c8d485c48fee2d1f963eeba7a03ddf8e4fc6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 26, "max_stars_repo_stars_event_min_datetime": "2017-08-26T15:54:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T03:38:07.000Z", "max_issues_repo_path": "report/chapters/implementation.tex", "max_issues_repo_name": "henghengxiong/website-fingerprinting", "max_issues_repo_head_hexsha": "17b1c8d485c48fee2d1f963eeba7a03ddf8e4fc6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/chapters/implementation.tex", "max_forks_repo_name": "henghengxiong/website-fingerprinting", "max_forks_repo_head_hexsha": "17b1c8d485c48fee2d1f963eeba7a03ddf8e4fc6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2017-12-30T14:23:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T11:33:01.000Z", "avg_line_length": 65.7792207792, "max_line_length": 331, "alphanum_fraction": 0.7828232971, "num_tokens": 4673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.629774621301746, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3173473177165647}}
{"text": "\\chapter{\\label{chap:Appendix A}Model parameters: Chapters 1--4}\n\nFor each of the basic exemplar models for which simulations were run,\nthe following parameter values were used:\n\n\\begin{table}[H]\\footnotesize\n\\caption{Simulation parameter values}\n\\begin{tabular}{lS[table-format=1.1]cS[table-format=1.1]S[table-format=1.1]S[table-format=1.1]cc}\n\\lsptoprule\n & {$\\varepsilon$} & {$\\sigma_{\\text{error}}$} & $\\alpha$ & {p} & {$\\beta$} & $\\sigma$ & {N}\\tabularnewline\n\\midrule\nBaseline Model (\\chapref{ch:The-Exemplar-Model}) & .3 & $\\sigma$ & .1 & – & – & 2 & –\\tabularnewline\nModel 1: Context-Free (\\sectref{subsec:Model-1:-Context-Free}) & .3 & $\\sigma$ & .5$\\sigma$ & – & – & 2 & –\\tabularnewline\nModel 2: Context-Dep. (Gradient) (\\sectref{subsec:Phrase-Final Lengthening}) & .3 & $\\sigma$ & .1 & .25 & – & 2 & –\\tabularnewline\nModel 3: Context-Dep. (Discrete) (\\sectref{subsec:Model-3:-Categorical}) & .3 & $\\sigma$ & – & .5 & – & 2 & –\\tabularnewline\nSoft-Target Model (\\sectref{subsec:Soft-Targets}) & .3 & $\\sigma$ & .1 & .25 & .6 & 2 & 50\\tabularnewline\n\\lspbottomrule\n\\end{tabular}\n\n\\end{table}\n\n\n\\chapter{\\label{chap:Appendix B}The frequency effect}\n\nThis material is supplemental to Chapters \\ref{subsec:Model-1:-Context-Free}\nand \\ref{subsec:Word-Frequency} of the main text.\n\nThe iterative model implies that the frequency effect must arise in\nthe lifetime of the speaker, and only after they have had sufficient\nexposure to a given (high frequency) category. This may happen very\nquickly. However, the less time it takes, the more opportunities there\nwill be for lower-frequency categories to “catch up”. Therefore,\nin order to give the best chance to the basic model, we will assume\nthe largest possible time period in which the effect could arise:\nthe age of the experimental population for which frequency effects\nare found. As the pool of participants for psychology and linguistics\nexperiments is most often university undergraduates, we will take\n20 years to be the maximum amount of time necessary to produce a reduction\nin duration comparable to what has been reported in the literature.\n\nWe don't know how many model iterations correspond to 20 years. But\nwe will define the number of productions during this time, for a word\nof frequency \\emph{f}, as $n_{f}$, and the proportion by which it\nis reduced, as $\\delta_{n_{f}}$, from an initial average duration\nof $\\overline{d_{0}}$. This period of time will be called an epoch\n(\\emph{e}). \n\\begin{equation}\n\\overline{d_{n_{f}}}=\\overline{d_{0}}-\\delta_{n_{f}}\\overline{d_{0}}\\label{eq:epoch-dur}\n\\end{equation}\nTo simplify the problem, we will consider a scenario in which there\nis only a single token belonging to each category, located at the\ncategory mean, which is replaced, each time production occurs, by\na token reduced by a fixed proportion of the current duration. With\nthis simplification all categories will reduce faster, since it is\nalways the most reduced token that is chosen in production. However,\nsince all measures are comparisons between categories of different\nfrequencies (rather than absolute values), this should not affect\nthe result. Low and high frequency categories are also of exactly\nthe same size token-wise in this simplified scenario, and only update-rate\ndifferentiates them. Equalizing low- and high -frequency categories\nin this way does affect the outcome, as we saw in \\sectref{subsec:Model-1:-Context-Free},\nbut it advantages the basic model by ensuring that higher-frequency\nwords are always shorter than lower-frequency ones.\n\nIn the simplified scenario, each generation is exponentially more\nreduced than the last. From Eq (\\ref{eq:linear bias}): $x_{o(+n)}=x_{o}\\left(1-\\alpha\\right)^{n}$,\nwe can derive Eq. (\\ref{eq:Reduction}), which expresses the duration,\nafter 1 epoch, for a word category of frequency \\emph{f}, and an\ninitial average duration of $\\overline{d_{0}}$. Rewriting Eq. (\\ref{eq:linear bias})\nin terms of these variables:\n\\begin{equation}\n\\overline{d_{n_{f}}}=\\overline{d_{0}}(1-\\alpha)^{n_{f}}\n\\end{equation}\nSubstituting in from Eq. (\\ref{eq:epoch-dur}):\n\\begin{equation}\n\\overline{d_{0}}-\\delta_{n_{f}}\\overline{d_{0}}=\\overline{d_{0}}(1-\\alpha)^{n_{f}}\n\\end{equation}\nAnd, \n\\begin{equation}\n\\delta_{n_{f}}=1-(1-\\alpha)^{n_{f}}\\label{eq:Reduction}\n\\end{equation}\n\nWe don't know what the amount of reduction over 1 epoch is. But we\ndo have an idea of the size of the frequency effect: word duration\nas a function of frequency (log frequency is typically what is plotted\nin order to make the frequency distribution closer to Normal (see\ne.g. \\citet{gahl2012reduce})). If we assume a linear relation between\nword duration and log frequency, then for each unit change in log\nfrequency, the difference in word duration should be equal to a constant\nvalue (\\emph{b}). Thus, the predicted difference in duration between\na low frequency and high frequency word is related to the difference\nin frequencies by the following formula: \n\\begin{equation}\n\\frac{\\Delta d_{e}}{\\log(f_{L})-\\log(f_{H})}=b\\label{eq:log-linear}\n\\end{equation}\nIf speakers/listeners begin at birth with equal experience of all words\n– meaning, none – then the differences in duration that accrue over\nthe course of an epoch will be due entirely to the amount of reduction\nthat occurs over that epoch. By the time that one epoch has passed,\nthe higher frequency word of any pair will have reduced more than\nits counterpart. Assuming that the two words in question are otherwise\nidentical, for our purposes, that they have the same original duration,\nthen the difference in absolute duration at that time will be given\nby:\n\\begin{equation}\n\\Delta d_{e}=\\delta_{n_{L}}-\\delta_{n_{H}}\\label{eq:duration-diff}\n\\end{equation}\nCombining (\\ref{eq:log-linear}) and (\\ref{eq:duration-diff}),\n\\begin{equation}\n\\delta_{n_{L}}-\\delta_{n_{H}}=b\\left[\\log\\left(\\frac{f_{L}}{f_{H}}\\right)\\right]\n\\end{equation}\nSubstituting in Eq. (\\ref{eq:Reduction}):\n\\begin{equation}\n1-(1-\\alpha)^{n_{L}}-[1-(1-\\alpha)^{n_{H}}]=b\\left[\\log\\left(\\frac{f_{L}}{f_{H}}\\right)\\right]\n\\end{equation}\nSimplifying:\n\\begin{equation}\n(1-\\alpha)^{n_{H}}-(1-\\alpha)^{n_{L}}=b\\left[\\log\\left(\\frac{f_{L}}{f_{H}}\\right)\\right]\\label{eq:reduction-to-freq}\n\\end{equation}\n\nThe higher the frequency of a given word, the more times it should\nbe produced within a given time period. And if reduction is proportional\nto the log frequency, with every production resulting in a given amount\nof reduction, then the number of productions should also be proportional\nto log frequency. \n\\begin{equation}\nn_{f}=\\rlog(f)\\label{eq:n-productions}\n\\end{equation}\nSubstituting (\\ref{eq:n-productions}) into (\\ref{eq:reduction-to-freq}):\n\\begin{equation}\n(1-\\alpha)^{\\rlog(f_{H})}-(1-\\alpha)^{\\rlog(f_{L})}=b\\left[\\log\\left(\\frac{f_{L}}{f_{H}}\\right)\\right]\\label{eq:boundary cond}\n\\end{equation}\nAssuming that it is possible to find values for $\\alpha$ and \\emph{r}\nthat satisfy Eq. (\\ref{eq:boundary cond}) for all frequencies, the\nadditional reduction that will occur over the lifetime of the speaker\ncan then be determined. \n\nIf 1 epoch corresponds to about 20 years, then there will be about\n4 over the lifetime of an individual. If we assume a constant rate\nof production for each category proportional to its frequency, then\nlifetime (\\emph{E}) average reduction is given by $\\delta_{E_{f}}=1-(1-\\alpha)^{4n_{f}}$,\nwhich can be rewritten as:\n\\begin{equation}\n\\delta_{E_{f}}=1-(1-\\alpha)^{4\\rlog(f)}\n\\end{equation}\n\nWith the necessary constants, we can now determine the difference\nin reduction between the same two word categories after 4 epochs.\nIf we assume that there exists a floor beyond which words cannot reduce\nfurther, then we will need to determine if any words are predicted\nto reach floor in the lifetime of the speaker, and what effect that\nwill have on the behavior of the frequency dependence – either entirely\nneutralizing the duration difference between certain words, or decreasing\nthat difference to some extent. \n\nThe exact predictions of the linearly biased frequency model will\ndepend on a host of implementational details. As already discussed\nin the text, the choice of whether lower-frequency categories should\nhave proportionally fewer tokens than higher-frequency categories\nwill affect the outcome. Other parameters that have the potential\nto alter the outcome include whether or not each individual experience\nis automatically added to memory – or only a certain minimum number,\nor some average of recent experience – and how quickly older memories\ndecay, being replaced by new experiences. It may be possible, if unlikely,\nthat at least one set of parameter values exists that will prevent\nany words reaching floor within the lifetime of the speaker. However,\nunder any parameter settings, all words are predicted to continue\nreducing over the lifetime of the speaker. This prediction is empirically\ntestable.\n\n\\chapter{\\label{chap:Appendix C}Derivation of State Model}\n\nThis material is supplemental to \\sectref{subsec:Lengthening-as-State}\nof the main text.\n\nFor the Pure State Model (G), with 2-targets, each sub-category is\nsubject to two forces: entrenchment, and inertia. Under the simplifying\nassumption that each sub-category can be treated as a Normal distribution\nwith constant variance, the equilibrium locations of the sub-category\nmeans can be derived in the following way. At equilibrium the entrenchment\nforce is balanced by the inertial force due to each sub-category's\nattractor. The location of the sub-category mean is the location at\nwhich the displacement that would occur due to the entrenchment force\nis exactly counteracted by the displacement that would occur due\nto the inertia force. For the non-biased sub-category this equilibrium\noccurs under the following conditions:\n\\begin{equation}\n\\beta\\left(\\overline{x_{E}^{NB}}-N\\right)=\\varepsilon\\left(\\overline{x_{E}}-\\overline{x_{E}^{NB}}\\right)\\label{eq:xNB-state}\n\\end{equation}\nFor the biased sub-category, equilibrium occurs when:\n\\begin{equation}\n\\alpha\\left(\\overline{x_{E}^{B}}-L\\right)=\\varepsilon\\left(\\overline{x_{E}}-\\overline{x_{E}^{B}}\\right)\\label{eq:xB-State}\n\\end{equation}\nBecause the entrenchment force depends on the global mean, so too\ndo the two equilibrium equations. In turn, the global mean can be\nexpressed as a function of the sub-category means (where the proportion\nof biased tokens is given by \\emph{p}): \n\\begin{equation}\n\\overline{x_{E}}=(1-p)\\overline{x_{E}^{NB}}+p\\overline{x_{E}^{B}}\\label{eq:weighted-means}\n\\end{equation}\nWith three equations, we can solve for the three distribution means.\nSolving for $\\overline{x_{E}^{NB}}$ in Eq. (\\ref{eq:xNB-state}):\n\\begin{equation}\n\\overline{x_{E}^{NB}}=\\frac{\\beta N+\\varepsilon\\overline{x_{E}}}{\\beta+\\varepsilon}\n\\end{equation}\nSolving for $\\overline{x_{E}^{B}}$ in Eq. (\\ref{eq:xB-State}):\n\\begin{equation}\n\\overline{x_{E}^{B}}=\\frac{\\alpha L+\\varepsilon\\overline{x_{E}}}{\\alpha+\\varepsilon}\n\\end{equation}\nSubstituting these two values into Eq. (\\ref{eq:weighted-means}):\n\\begin{equation}\n\\overline{x_{E}}=(1-p)\\frac{\\beta N+\\varepsilon\\overline{x_{E}}}{\\beta+\\varepsilon}+p\\frac{\\alpha L+\\varepsilon\\overline{x_{E}}}{\\alpha+\\varepsilon}\n\\end{equation}\nSolving for $\\overline{x_{E}}$ as a function of \\emph{p, }and collecting\nterms:\n\\begin{equation}\n\\overline{x_{E}}=\\frac{(1-p)\\beta N}{\\beta+\\varepsilon}+\\frac{(1-p)\\varepsilon\\overline{x_{E}}}{\\beta+\\varepsilon}+\\frac{p\\alpha L}{\\alpha+\\varepsilon}+\\frac{p\\varepsilon\\overline{x_{E}}}{\\alpha+\\varepsilon}\n\\end{equation}\n\n\\begin{equation}\n\\overline{x_{E}}-\\frac{(1-p)\\varepsilon\\overline{x_{E}}}{\\beta+\\varepsilon}-\\frac{p\\varepsilon\\overline{x_{E}}}{\\alpha+\\varepsilon}=\\frac{(1-p)\\beta N}{\\beta+\\varepsilon}+\\frac{p\\alpha L}{\\alpha+\\varepsilon}\n\\end{equation}\n\n\\begin{equation}\n\\frac{\\overline{x_{E}}(\\beta+\\varepsilon)(\\alpha+\\varepsilon)-(\\alpha+\\varepsilon)(1-p)\\varepsilon\\overline{x_{E}}-(\\beta+\\varepsilon)p\\varepsilon\\overline{x_{E}}}{(\\beta+\\varepsilon)(\\alpha+\\varepsilon)}=\\frac{(1-p)\\beta N}{\\beta+\\varepsilon}+\\frac{p\\alpha L}{\\alpha+\\varepsilon}\n\\end{equation}\n\n\\begin{equation}\n\\begin{aligned}[t]\n& \\frac{\\overline{x_{E}}(\\beta+\\varepsilon)(\\alpha+\\varepsilon)-(\\alpha+\\varepsilon)(1-p)\\varepsilon\\overline{x_{E}}-(\\beta+\\varepsilon)p\\varepsilon\\overline{x_{E}}}{(\\beta+\\varepsilon)(\\alpha+\\varepsilon)}\\\\\n= &\\frac{(1-p)\\beta N(\\alpha+\\varepsilon)+p\\alpha L(\\beta+\\varepsilon)}{(\\alpha+\\varepsilon)(\\beta+\\varepsilon)}\n\\end{aligned}\n\\end{equation}\n\n\\begin{equation}\n\\overline{x_{E}}[(\\beta+\\varepsilon)(\\alpha+\\varepsilon)-(\\alpha+\\varepsilon)(1-p)\\varepsilon-(\\beta+\\varepsilon)p\\varepsilon]=(1-p)\\beta N(\\alpha+\\varepsilon)+p\\alpha L(\\beta+\\varepsilon)\n\\end{equation}\n\n\\begin{equation}\n\\overline{x_{E}}=\\frac{(1-p)\\beta N(\\alpha+\\varepsilon)+p\\alpha L(\\beta+\\varepsilon)}{(\\beta+\\varepsilon)(\\alpha+\\varepsilon)-(\\alpha+\\varepsilon)(1-p)\\varepsilon-(\\beta+\\varepsilon)p\\varepsilon}\\label{eq:Model G-eq}\n\\end{equation}\nEq. (\\ref{eq:Model G-eq}) is a complex function of $\\alpha,\\beta,\\varepsilon,N,L$,\nand \\emph{p}, the derivative of which is not trivially calculated.\nFor known values of $\\alpha,\\beta,\\varepsilon,N$, and \\emph{L} ,\n$\\overline{x_{E}}(p)$ can be determined exactly. The general behavior\nof this function, however, can be understood via the following chain\nof reasoning. \n\nFor a given $p=p_{i}$ (for $p_{i}<1$), the equilibrium location\nof the global mean can be found using Eq. (\\ref{eq:Model G-eq}).\nNow imagine that \\emph{p} increases from $p_{i}$ to $p_{j}$. This will\nresult in the global mean moving closer to the biased sub-category\n(Eq. (\\ref{eq:weighted-means})). A change in the global mean will\ncause a change in the entrenchment force for both sub-categories.\nIt will increase for the non-biased sub-category, which is now farther\nfrom the global mean; and it will decrease in exactly the same degree\nfor the biased sub-category, which is now closer to the global mean.\n\nBecause inertia does not depend on \\emph{p}, the lefthand sides of\nEqs. (\\ref{eq:xNB-state}) and (\\ref{eq:xB-State}) will remain constant.\nThus, the non-biased sub-category will shift in the direction of the\nmean – rightward – as a result of the increase in \\emph{p}. The decrease\nin the entrenchment force on the biased sub-category, conversely,\nwill cause a shift away from the mean, and towards the attractor at\n\\emph{L}. This is also a rightward shift, however. The net effect\nwill be to perturb the sub-categories from their former equilibrium\nlocations to points farther to the right, and closer to \\emph{L}.\nAs \\emph{p} increases, $\\overline{x_{E}}$ will always increase (as\nlong as both sub-categories are located between \\emph{N} and \\emph{L}).\n\nThe distance between the means of the two sub-categories can also\nbe written as a function of \\emph{p}. Once equilibrium has been reached,\nthe separation can be derived from Eqs. (\\ref{eq:xNB-state}) and\n(\\ref{eq:xB-State}):\n\\begin{equation}\n\\Delta\\overline{x_{E}}\\equiv\\overline{x_{E}^{B}}-\\overline{x_{E}^{NB}}=\\frac{\\alpha L+\\varepsilon\\overline{x_{E}}}{\\alpha+\\varepsilon}-\\frac{\\beta N+\\varepsilon\\overline{x_{E}}}{\\beta+\\varepsilon}\n\\end{equation}\nCollecting terms and simplifying:\n\n\\begin{equation}\n=\\frac{\\alpha L}{\\alpha+\\varepsilon}-\\frac{\\beta N}{\\beta+\\varepsilon}+\\frac{\\varepsilon\\overline{x_{E}}}{\\alpha+\\varepsilon}-\\frac{\\varepsilon\\overline{x_{E}}}{\\beta+\\varepsilon}\n\\end{equation}\n\n\\begin{equation}\n=\\frac{\\alpha L}{\\alpha+\\varepsilon}-\\frac{\\beta N}{\\beta+\\varepsilon}+\\varepsilon\\overline{x_{E}}\\left[\\frac{1}{\\alpha+\\varepsilon}-\\frac{1}{\\beta+\\varepsilon}\\right]\n\\end{equation}\nThe change in sub-category separation as a function of changing \\emph{p}\nis thus given by:\n\\begin{equation}\n\\frac{\\partial\\Delta\\overline{x_{E}}}{\\partial p}=\\frac{\\partial\\overline{x_{E}}}{\\partial p}\\varepsilon\\left[\\frac{1}{\\alpha+\\varepsilon}-\\frac{1}{\\beta+\\varepsilon}\\right]\\label{eq:Model G-sep}\n\\end{equation}\nIn order to determine $\\frac{\\partial\\Delta\\overline{x_{E}}}{\\partial p}$,\nwe must be able to calculate $\\frac{\\partial\\overline{x_{E}}}{\\partial p}$.\nFor the special case in which all forces have the same strength ($\\alpha=\\beta=\\varepsilon$),\nit is straightforward to calculate the derivative of Eq. (\\ref{eq:Model G-eq}):\n\\begin{equation}\n\\overline{x_{E}}=\\frac{2\\alpha^{2}N+p(2\\alpha^{2}L-2\\alpha^{2}N)}{4\\alpha^{2}-2\\alpha^{2}}\n\\end{equation}\nCollecting terms and simplifying:\n\\begin{equation}\n\\overline{x_{E}}=\\frac{2\\alpha^{2}[N+pL-pN]}{2\\alpha^{2}[2-1]}\n\\end{equation}\n\n\\begin{equation}\n\\overline{x_{E}}=N+p(L-N)\\label{eq: State-special case}\n\\end{equation}\nThis gives the expected behavior; for $p=0$, there is only the non-biased\ndistribution, which is stable at \\emph{N}, and for $p=1$, there is\nonly the biased distribution, which is stable at \\emph{L}. For equal\nnumbers of biased and non-biased variants, each sub-category stabilizes\nat the same distance from its attractor, and the global mean is halfway\nbetween the two. The change in the global category mean as a function\nof \\emph{p} is a positive, fixed value: $L-N$, the derivative of\n(\\ref{eq: State-special case}). Plugging this value for $\\frac{\\partial\\overline{x_{E}}}{\\partial p}$\ninto Eq. (\\ref{eq:Model G-sep}) gives:\n\\begin{equation}\n\\frac{\\partial\\Delta\\overline{x_{E}}}{\\partial p}=(L-N)\\alpha\\left[\\frac{1}{2\\alpha}-\\frac{1}{2\\alpha}\\right]=0\\label{eq:separation-special case}\n\\end{equation}\nThus, while the overall category mean gets larger as \\emph{p} increases,\nthe separation between the categories remains constant. \n\nIn the general case, the separation between the two sub-categories\nwill show different behavior for different parameter values. Because\n${\\partial\\overline{x_{E}}}/{\\partial p}>0$, the sign of ${\\partial\\Delta\\overline{x_{E}}}/{\\partial p}$\ndepends on the $\\varepsilon[{1}/({\\alpha+\\varepsilon})-{1}/({\\beta+\\varepsilon})]$\nterm. When $\\alpha<\\beta$, the separation increases with increasing\n\\emph{p}. This follows from the fact that ${\\partial\\Delta\\overline{x_{E}}}/{\\partial p}$\nis positive only when $\\varepsilon[{1}/({\\alpha+\\varepsilon})-{1}/({\\beta+\\varepsilon})]>0$.\nFor $\\varepsilon[{1}/({\\alpha+\\varepsilon})-{1}/({\\beta+\\varepsilon})]$\nto be greater than zero it must be the case that ${1}/({\\alpha+\\varepsilon})>{1}/({\\beta+\\varepsilon})$.\nThis, in turn, requires that $\\alpha<\\beta$. By the same reasoning,\nthe separation decreases as a function of increasing \\emph{p} when\n$\\alpha>\\beta$. Finally, the separation remains constant when $\\alpha=\\beta$,\nbecause this entails that $\\varepsilon[{1}/({\\alpha+\\varepsilon})-{1}/({\\beta+\\varepsilon})]=0$,\nverifying the result in Eq. (\\ref{eq:separation-special case}).\n\n\\chapter{\\label{chap:Appendix D}Derivation of Process Model}\n\nThis material is supplemental to \\sectref{subsec:Model-B:-Lengthening}\nof the main text.\n\nFor the Pure Process Model, there is a single category, and all tokens\nare subject to the same inertial force, in proportion to their distance\nfrom the single attractor at \\emph{N}. Additionally, a proportion\n\\emph{p} of randomly selected tokens undergo a lengthening process,\nmoving away from the rest of the distribution during production. The\nsimplifying assumption, that each sub-distribution can be treated\nas a Normal distribution with constant variance, is adopted. To derive\nthe model behavior we will look at the contribution of the different\nforces in stages. This derivation references the stages depicted in\nFigure \\ref{fig:Derivation}.\n\nFirst we apply the lengthening process, at time $t$, to tokens drawn\nfrom a distribution with a global mean of $\\overline{x_{t}}$. These\ntokens are simultaneously subjected to an inertial force. Eq. (\\ref{eq:Model-B B-Prime})\ngives the mean of the biased sub-distribution at time \\emph{t,}\n\\begin{equation}\n\\overline{x_{t}^{B}}^{\\prime}=\\overline{x_{t}}(1+\\alpha)+\\beta(N-\\overline{x_{t}})\\label{eq:Model-B B-Prime}\n\\end{equation}\nand Eq. (\\ref{eq:Model-B NB-Prime}) gives the means of the non-biased\nsub-distribution at time \\emph{t}.\n\n\\begin{equation}\n\\overline{x_{t}^{NB}}^{\\prime}=\\overline{x_{t}}+\\beta(N-\\overline{x_{t}})\\label{eq:Model-B NB-Prime}\n\\end{equation}\nOn average, a proportion \\emph{p} of the distribution will be lengthened,\nthus the location of the global mean, after lengthening and inertia\napply, can be expressed as\n\\begin{equation}\n\\overline{x_{t}}^{\\prime}=(1-p)\\overline{x_{t}^{NB}}^{\\prime}+p\\overline{x_{t}^{B}}^{\\prime}\\label{eq:Model-B weight mean}\n\\end{equation}\nEntrenchment must also be applied in order to determine the final\noutcome, but entrenchment does not affect the location of the global\nmean, only the locations of the sub-distribution means, and their\nseparation. To see this, we can compare the global mean before and\nafter entrenchment applies. After entrenchment, the means of each\nsub-distribution are given by:\n\\begin{equation}\n\\overline{x_{t}^{B}}^{\\prime\\prime}=\\overline{x_{t}^{B}}^{\\prime}-\\varepsilon\\left(\\overline{x_{t}}^{\\prime}-\\overline{x_{t}^{B}}^{\\prime}\\right)\n\\end{equation}\n\n\\begin{equation}\n\\overline{x_{t}^{NB}}^{\\prime\\prime}=\\overline{x_{t}^{NB}}^{\\prime}-\\varepsilon\\left(\\overline{x_{t}}^{\\prime}-\\overline{x_{t}^{NB}}^{\\prime}\\right)\n\\end{equation}\nSubstituting into Eq. (\\ref{eq:Model-B weight mean}), gives\n\\begin{equation}\n\\overline{x}_{t}^{''}=(1-p)\\left[\\overline{x_{t}^{NB}}^{\\prime}-\\varepsilon\\left(\\overline{x_{t}}^{\\prime}-\\overline{x_{t}^{NB}}^{\\prime}\\right)\\right]+p\\left[\\overline{x_{t}^{B}}^{\\prime}-\\varepsilon\\left(\\overline{x}_{t}^{\\prime}-\\overline{x_{t}^{B}}^{\\prime}\\right)\\right]\n\\end{equation}\nSimplifying and collecting terms:\n\\begin{equation}\n=\\overline{x_{t}}^{\\prime}-\\varepsilon(1-p)\\left(\\overline{x_{t}}^{\\prime}-\\overline{x_{t}^{NB}}^{\\prime}\\right)-p\\varepsilon\\left(\\overline{x_{t}}^{\\prime}-\\overline{x_{t}^{B}}^{\\prime}\\right)\n\\end{equation}\n\n\\begin{equation}\n=\\overline{x_{t}}^{\\prime}+\\varepsilon(1-p)\\overline{x_{t}^{NB}}^{\\prime}-\\left[\\varepsilon(1-p)+p\\varepsilon\\right]\\overline{x_{t}}^{\\prime}+p\\varepsilon\\overline{x_{t}^{B}}^{\\prime}\n\\end{equation}\n\n\\begin{equation}\n=\\overline{x_{t}}^{\\prime}-\\varepsilon\\overline{x_{t}}^{\\prime}+\\varepsilon\\left[(1-p)\\overline{x_{t}^{NB}}^{\\prime}+p\\overline{x_{t}^{B}}^{\\prime}\\right]\n\\end{equation}\nThe term $(1-p)\\overline{x_{t}^{NB}}^{\\prime}+p\\overline{x_{t}^{B}}^{\\prime}$\nis equivalent to $\\overline{x_{t}}^{\\prime}$ by Eq. (\\ref{eq:Model-B weight mean}).\nTherefore\n\\begin{equation}\n\\overline{x_{t}}^{\\prime\\prime}=\\overline{x_{t}}^{\\prime}-\\varepsilon\\overline{x_{t}}^{\\prime}+\\varepsilon\\overline{x_{t}}^{\\prime}=\\overline{x_{t}}^{\\prime}\n\\end{equation}\nBecause it does not depend on entrenchment, the global mean at equilibrium\ncan be determined directly from (\\ref{eq:Model-B B-Prime}) and (\\ref{eq:Model-B NB-Prime}).\nEquilibrium occurs when the two sub-distributions are also at equilibrium,\nand the global mean stops changing: $\\overline{x_{E}}=\\overline{x_{E}}^{\\prime}$,\n$\\overline{x_{E}^{NB}}^{\\prime}=\\overline{x_{E}^{NB}}$, and $\\overline{x_{E}^{B}}^{\\prime}=\\overline{x_{E}^{B}}$.\nTherefore,\n\\begin{equation}\n\\overline{x_{E}}=(1-p)\\overline{x_{E}^{NB}}^{\\prime}+p\\overline{x_{E}^{B}}^{\\prime}\n\\end{equation}\nSubstituting in Eqs. (\\ref{eq:Model-B B-Prime}) and (\\ref{eq:Model-B NB-Prime}):\n\n\\begin{equation}\n\\overline{x_{E}}=[\\overline{x_{E}}+\\beta(N-\\overline{x_{E}})]-p[\\overline{x_{E}}+\\beta(N-\\overline{x_{E}})]+p[\\overline{x_{E}}+\\overline{x_{E}}\\alpha+\\beta(N-\\overline{x_{E}})]\n\\end{equation}\nSimplifying and collecting terms:\n\n\\begin{equation}\n\\overline{x_{E}}=\\overline{x_{E}}+\\beta(N-\\overline{x_{E}})+p\\overline{x_{E}}\\alpha-p[\\overline{x_{E}}+\\beta(N-\\overline{x_{E}})]+p[\\overline{x_{E}}-\\beta(N-\\overline{x_{E}})]\n\\end{equation}\n\n\\begin{equation}\n\\overline{x_{E}}=\\overline{x_{E}}+\\beta(N-\\overline{x_{E}})+p\\overline{x_{E}}\\alpha\n\\end{equation}\n\n\\begin{equation}\n\\overline{x_{E}}=\\overline{x_{E}}(1-\\beta+p\\alpha)+\\beta N\n\\end{equation}\n\n\\begin{equation}\n\\overline{x_{E}}(1-1+\\beta-p\\alpha)=\\beta N\n\\end{equation}\n\n\\begin{equation}\n\\overline{x_{E}}=\\frac{\\beta N}{\\beta-p\\alpha}\\label{eq:equ-mean-state}\n\\end{equation}\nFor the case when $p\\alpha<\\beta$, the denominator in (\\ref{eq:equ-mean-state})\nis positive. As \\emph{p} increases (but $p\\alpha$ remains smaller\nthan $\\beta$), the denominator decreases, and the global mean increases.\nAs $p\\alpha$ approaches $\\beta$, the global mean goes to infinity;\nlengthening is unbounded. For $p\\alpha>\\beta$ the only stable point\nis negative, and thus there is no well-defined equilibrium. The \\noun{process}\nmodel is thus only stable if the lengthening strength is not too great,\nand the percentage of biasing contexts is not too large. \n\nTo calculate the dependence of the sub-distribution separation on\n\\emph{p,} the effect of entrenchment must be included. The equilibrium\nseparation is defined as: \n\\begin{equation}\n\\Delta\\overline{x_{E}}^{\\prime\\prime}\\equiv\\overline{x_{E}^{B}}^{\\prime\\prime}-\\overline{x_{E}^{NB}}^{\\prime\\prime}\n\\end{equation}\nAnd \n\n\\begin{equation}\n\\overline{x_{E}^{B}}^{\\prime\\prime}=\\overline{x_{E}^{B}}^{\\prime}+\\varepsilon\\left(\\overline{x_{E}}^{\\prime}-\\overline{x_{E}^{B}}^{\\prime}\\right)\n\\end{equation}\n\n\\begin{equation}\n\\overline{x_{E}^{NB}}^{\\prime\\prime}=\\overline{x_{E}^{NB}}^{\\prime}+\\varepsilon\\left(\\overline{x_{E}}^{\\prime}-\\overline{x_{E}^{NB}}^{\\prime}\\right)\n\\end{equation}\nTherefore, \n\\begin{equation}\n\\overline{x_{E}^{B}}^{\\prime\\prime}-\\overline{x_{E}^{NB}}^{\\prime\\prime}=\\overline{x_{E}^{B}}^{\\prime}-\\overline{x_{E}^{NB}}^{\\prime}+\\varepsilon\\left(\\overline{x_{E}}^{\\prime}-\\overline{x_{E}^{B}}^{\\prime}\\right)-\\varepsilon\\left(\\overline{x_{E}}^{\\prime}-\\overline{x_{E}^{NB}}^{\\prime}\\right)\n\\end{equation}\nCollecting terms:\n\\begin{equation}\n=\\overline{x_{E}^{B}}^{\\prime}-\\overline{x_{E}^{NB}}^{\\prime}-\\varepsilon\\left(\\overline{x_{E}^{B}}^{\\prime}-\\overline{x_{E}^{NB}}^{\\prime}\\right)\n\\end{equation}\nand\n\\begin{equation}\n\\Delta\\overline{x_{E}}^{\\prime\\prime}=(1-\\varepsilon)\\left(\\overline{x_{E}^{B}}^{\\prime}-\\overline{x_{E}^{NB}}^{\\prime}\\right)\n\\end{equation}\nThe observed separation at equilibrium depends on the separation due\nto prior model forces. From Eqs. (\\ref{eq:Model-B B-Prime}) and (\\ref{eq:Model-B NB-Prime}), \n\\begin{equation}\n\\overline{x_{E}^{B}}^{\\prime}-\\overline{x_{E}^{NB}}^{\\prime}=\\overline{x_{E}}(1+\\alpha)+\\beta(N-\\overline{x_{E}})-[\\overline{x_{E}}+\\beta(N-\\overline{x_{E}})]\n\\end{equation}\nThis reduces to $\\alpha\\overline{x_{E}}$. Note that this is exactly\nthe amount that biased tokens are shifted away from the mean at equilibrium.\nBecause this is a \\noun{process} model, the separation created by\nthe lengthening bias only exists transiently, and it is not possible\nfor any specific subset of tokens to continue to increase their separation\nfrom the rest of the distribution. Therefore, the prior separation\nbetween the sub-distribution means is always given by the lengthening\nbias applied to that mean. And the total separation, by \n\\begin{equation}\n\\Delta\\overline{x_{E}}=(1-\\epsilon)(\\alpha\\overline{x_{E}}).\\label{eq:Cat Sep-1}\n\\end{equation}\nIn the stable parameter range, where $\\overline{x_{E}}$ increases\nas \\emph{p} increases, the separation of the sub-distributions also\nincreases, but more slowly, by a factor of $\\alpha(1-\\epsilon)$.\n\n\\chapter{\\label{chap:Appendix E}Nasalization model parameters}\n\nThe following parameters were identical for the two models:\n\\begin{itemize}\n\\item The entrenchment strength is set to $\\varepsilon=.2$\n\\item The production error on each articulatory dimension is drawn from\nthe distribution $\\mathcal{\\mathscr{N}}\\left(0,.25\\sigma_{x^{Z}}\\right)$,\nwhere $\\sigma_{x^{Z}}$ indicates the standard deviation of the current\ndistribution of stored tokens on dimension $x^{Z}$\n\\item Speaking Rate:\n\\begin{itemize}\n\\item Expansion force (\\emph{E}) is a random variable distributed according\nto $\\mathcal{\\mathscr{N}\\left(\\mathrm{0,.25}\\right)}$. \n\\item The speaking rate transformation lengthens or shortens a given duration\nparameter, according to the following dependence on \\emph{E:}\n\\begin{equation}\nx_{i}^{O^{\\prime}}=\\frac{2x_{i}^{O}}{(1+e^{k_{O}E})}\\label{eq:Speaking rate transform-1}\n\\end{equation}\n\n\\begin{equation}\nx_{i}^{V^{\\prime}}=\\frac{2x_{i}^{V}}{(1+e^{-k_{V}E})}\\label{eq:Speaking rate transform-1-1}\n\\end{equation}\n\n\\begin{equation}\nx_{i}^{N^\\prime}=\\frac{2x_{i}^{N}}{(1+e^{-k_{N}E})}\\label{eq:Speaking rate transform-1-1-1}\n\\end{equation}\n\n\\end{itemize}\nFor these simulations all gestures are set to the same elasticity\n($k_{O}=k_{N}=k_{V}=1$). \n\\item Model outputs are reported after 10,000 iterations\n\\item $x_{i}^{O}$ is never allowed to fall below 0, or to exceed the shorter\nof the two values $(x_{i}^{N},x_{i}^{V})$\n\\item The duration of $x_{i}^{V}$ is never allowed to fall below 50 ms,\nor to exceed 600 ms\n\\item The duration of $x_{i}^{N}$ is never allowed to fall below 25 ms,\nor to exceed 500 ms\n\\end{itemize}\n\n\\section{No-Phoneme Model}\nThe fluency attractor affects overlap duration according to the following\nformula:\n\n\\begin{equation}\nx_{i}^{O^{\\prime}}=x_{i}^{O}+\\beta(T-x_{i}^{O})\\label{eq:Frequency attractor-1}\n\\end{equation}\nThe target overlap duration for these simulations is set at $T=x_{i}^{N}$.\n$\\beta$ parameterizes frequency on a scale between 0 and 1. \n\n\\section{Multiple-Parse Model}\n\\begin{itemize}\n\\item Resting activation acts as a perturbation to the expansion force,\n\\emph{E}. The mean of the expansion function is shifted ${1}/{4}$\nof a standard deviation for each unit of \\emph{f}, where \\emph{f} parameterizes\nfrequency:\n\\end{itemize}\n\\[\n\\overline{E}^{\\prime}=\\overline{E}-f(.25\\sigma_{E})\n\\]\n\n\\begin{itemize}\n\\item The overlap duration for Analysis 2 tokens is a random variable distributed\naccording to $\\mathcal{\\mathscr{N}}\\left(.25\\overline{x^{N}},\\sigma_{x^{N}}\\right)$\n\\item The probability of Analysis 1 is given by:\n\\begin{equation}\nP(a=1)=Ae^{-b(1-Q)}-C\\label{eq:segmentation-1-1}\n\\end{equation}\nwhere $Q={x_{i}^{O}}/{x_{i}^{N}}$\\emph{ }. For all simulations,\nthe constants are set to: $A=1$, $b=2$, and $C=0$.\n\\end{itemize}\n", "meta": {"hexsha": "90811df3d887f3e4bb605191603896a8aa795dd1", "size": 29944, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters.old/appendix.tex", "max_stars_repo_name": "langsci/251", "max_stars_repo_head_hexsha": "18908f64122d676abb48115b0600339e4dc7fa2e", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters.old/appendix.tex", "max_issues_repo_name": "langsci/251", "max_issues_repo_head_hexsha": "18908f64122d676abb48115b0600339e4dc7fa2e", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters.old/appendix.tex", "max_forks_repo_name": "langsci/251", "max_forks_repo_head_hexsha": "18908f64122d676abb48115b0600339e4dc7fa2e", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.7183098592, "max_line_length": 294, "alphanum_fraction": 0.7320665242, "num_tokens": 9319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.31734731071361305}}
{"text": "\\chapter{Machine Learning}\r\nMachine learning is playing a fundamental role in natural language processing\r\nand computational linguistics. The impact is so significant that one of key note\r\nspeakers of ACL 2012, Mark Johnson, predicted that in 50 years from now NLP/CL\r\nwill not exist as a research field and will be emerged as two different\r\nfields:(1) machine learning and (2) logic. This chapter is dedicated  to subset\r\nof models in machine learning that can play a role of bridge between logic and\r\nmachine learning. This chapter provides the building material for a new\r\ndirection of research so called \\textit{Representation Learning} which enables\r\nus to transfer information from logical forms such as predicate-argument form to\r\nvector space (beside many other advantages which we will discuss).\r\nMost of current models in machine learning are designed to work in vector space\r\ntherefore it is an important achievement to be able to work with type of\r\ninformation which is in other forms or representations by first transferring\r\nthem to vector space. Working with logical forms in vector space helps us to use\r\nmany available knowledge bases and lexicons with available machine learning\r\nmodels which is crucial for relation discovery. I will skip discussing classical\r\nmachine learning problems to emphasis more on new relevant topics. \r\nI will first briefly review artificial neural networks and then motivate and\r\ndefine the task of representation learning. In next chapters, we will\r\nneed the materials provided in this chapter to understand the undergoing\r\nresearch about relation discovery.\r\n\\section{Artificial Neural Networks}\r\n\\label{sec:ml-ann}\r\nBefore diving into different methods of representation learning, it would be\r\nuseful to briefly review the architecture, applications and learning algorithms\r\nof artificial neural networks (ANN). ANNs can be used for variety of\r\napplications in machine learning: classification, clustering, dimensionality\r\nreduction,\\ldots ~. What makes ANN important for us is their ability to do many\r\nof mentioned tasks jointly. Its layer-wised architecture very well fits to the\r\nidea of multi-task learning \\cite{Bengio2012a}. Different layers of an ANN can\r\nhave different objectives and can share information with other layers through parameter\r\nsharing. First I discuss about elements and architecture of ANNs and then we\r\nwill very briefly review \\textit{backpropagation} and \\textit{stochastic\r\ngradient descent} as we need them to understand the mechanism of learning in\r\nANNs.\r\n\r\nArtificial neural networks have old history in the domain of machine learning.\r\nThey are inspired from the mechanism humans learn via their neural networks. The\r\nbasic element of this network is a neuron which takes a weighted input signals and by applying an activation function\r\non this input, the neuron will output a signal. \r\n Neurons are usually arranged in\r\nlayers and receive input from the neurons from the previous layer and send their\r\noutputs to the next layer. The combination of different layers and using\r\ndifferent activation function with different degree of non-linearity is enabling\r\nANNs to learn non-linear functions.\\cite{Braspenning1995}\r\nA common mathematical model for neuron in ANNs is shown in\r\n\\eqref{eq:neuron} and visually in \\autoref{fig:neuron-model}.\r\n\\begin{equation}\r\n\\label{eq:neuron}\r\n\\begin{split}\r\nx^{l-1} \\mbox{~: input vector of size~}n  \\mbox{~and layer~}l-1\r\n\\\\\r\nw^{l,l-1} \\mbox{~: weight vector of size}~n~ \\text{from layer}~l-1 \\text{~to\r\nlayer}~l\r\n\\\\\r\ny_{j}^{l} \\mbox{~: output value of neuron~}j  \\mbox{~at layer}~l\\\\\r\ny_{j}^{l} = f(\\sum_{i=0}^{n} w_{i,j}x_{i}^{l-1})\\\\\r\n\\end{split}\r\n\\end{equation} \r\nActivation functions can be\r\nusually either of functions in the list below:\r\n\\begin{description}\r\n\\item[linear function] ~~ $f(x)=ax+b \\mbox{~where}~ a,b \\in \\mathbb{R}$\r\n\\item[step function] ~~ $ f(x)=1 \\mbox{~if~} x > \\theta \\mbox{~else~} f(x)=0\r\n\\mbox{~where~}\\theta \\in \\mathbb{~R} \\mbox{~is a constant threshold} $\r\n\\item[tangent hyperbolic] ~~ $f(x)=tanh(x)$\r\n\\item[Log-sigmoid] ~~ $f(x)=\\frac{1}{1+e^{-x}}$\r\n\\end{description}\r\n\r\n    \\begin{figure}[h!]\r\n  \\caption{A model of neuron}\r\n  \\centering\r\n    \\includegraphics[width=0.8\\textwidth]{neuron-model.eps}\r\n    \\label{fig:neuron-model}\r\n\\end{figure} \r\n\r\nThe type of ANNs matters mostly for us in this research are\r\nnetworks which neurons are arranged in ordered layers and there is no feedback\r\nfrom a deeper layer  to the layers in the back. The first layer is usually for\r\nunsupervised pre-training of objects, then a layer for adding non-linearity\r\ncomes and finally we have an axillary classification or ranking task.\\cite{Bengio2003}\r\n \\begin{figure}[h!]\r\n  \\caption{A Neural Language Model proposed by Bengio et al.}\r\n  \\centering\r\n    \\includegraphics[width=1\\textwidth]{ann.eps}\r\n    \\label{fig:ann}\r\n\\end{figure} \r\n In \\autoref{fig:ann}\r\n we can see a neural architecture proposed by Bengio et al. \\cite{Bengio2003}\r\n which works as language model. This model takes n-grams as input and predict\r\n the probability of the next word. The first layer is hot-one representation of\r\n sequence words, $w_{t-n+1}, \\ldots ,w_{t-2}, w_{t-1}$ and then the layer for\r\n unsupervised pre-training of words comes.\r\n Learned features of words will be combined together with \\textit{tanh} layer\r\n and finally we will have a \\textit{softmax} layer which outputs probability of\r\n all words as the next word, $w_t$, in the sequence. Later we will see more details about \r\n different layers of this ANN but\r\n the main question that arises here is how to learn parameters of such a network\r\n in order to make good predictions and induce meaningful features for words.\r\n\r\nThere are two main approaches for learning parameters of a single supervised\r\nlayer. By supervised layer we mean that true outputs/predictions are available\r\nfor training the parameter of the layer. :\r\n\\begin{description}\r\n  \\item[Online learning] \\hfil \\\\\r\n    To optimize the parameters, we\r\n    iterate over all points in the training dataset and calculate the layer\r\n    predictions for input. In each iteration, we update the weights in order to\r\n    decrease the difference between the predicted output and the true output for\r\n    each point. This forms an objective function (error function) which can be\r\n    minimized by gradient descent, by calculating error derivatives and update\r\n    weights to decrease them.\\cite{Bengio2012}\r\n    Since each data point can change the parameters, we call this algorithm an online learning algorithm.\r\n  \\item[Batch learning] \\hfil \\\\\r\n  In this approach, unlike the previous approach, first we calculate the\r\n  predicted outputs of whole dataset and form the error function and try to\r\n  minimize the error derivative for whole dataset. Since we update the\r\n  parameters after observing all points in the training dataset we call this\r\n  approach batch learning.\\cite{Braspenning1995}\r\n  \r\n  \\item[Stochastic Gradient Descent] \\hfil \\\\\r\n  The idea of SGD \\cite{Bottou2010},~\\cite{Bengio2012} is to make best out of both\r\n  previous ideas.\r\n  Neither updating after each datapoint nor after all points, SGD makes small batches in each\r\n  iteration, each usually contains only 100 datapoints, and calculate error\r\n  derivatives and update parameters for each batch.\r\n  \r\n  \r\n\\end{description} \r\n\r\nSince we now know how to train a single supervised layer, other layers of a\r\nnetwork can be trained using \\textit{backpropagation}. Parameters of the network\r\nwill be randomly initialized and then by choosing one of the approaches above we\r\ncan start by learning the last layer, since we have the output for that. After\r\nupdating the last layer, it works as the output of the layer before it and we\r\ncan use the same strategy to train its parameters. Likewise, we continue\r\ntraining of other layers. The criteria for stopping the algorithm can be either\r\nmaximum number of iterations or when parameters don't change from after some\r\niterations.\r\n\r\nAfter introducing ANNs we will focus more on the idea of unsupervised\r\npre-training in the next section. I show the generalization of this idea using\r\nother methods and motivates it as a very crucial step in many NLP tasks.\r\n\r\n\\section{Representation Learning}\r\n\\label {sec:repr-learning}\r\n\r\nIn this chapter, we will define and justify the task of\r\n\\emph{Representation Learning} and we will see different families of methods for\r\ninducing word representation and its application in NLP.\r\n\r\nIn machine learning specially in industry, most of the labor is dedicated to\r\n\\emph{Feature Engineering}. Extracting informative features is the crucial part\r\nof most supervised methods and it is done mostly manually. While many different\r\napplications share common learning models and classifiers, the difference in\r\nperformance of competing methods mostly goes to the data representation and\r\nhand-crafted features that they use. This observation reveals an important\r\nweakness in current models, namely their inability to extract and organize\r\ndiscriminative features from data. Representation learning is an umbrella term\r\nfor a family of unsupervised methods to learn features from data. Most of recent\r\nworks on the application of this idea in NLP focus on inducing word\r\nrepresentations. \\emph{Word representation} is a mathematical object, usually a\r\nvector, which each dimension in this vector represents a grammatical or\r\nsemantical feature to identify this word and is induced automatically from data\r\n\\cite{Turian2010b}. Recently, it has been shown in \\cite{Turian2010b} and \\cite{Collobert2011} that using\r\n induced features can be helpful to improve state-of-the-art methods in \r\ndifferent NLP tasks. It seems that relation extraction can also benefit from such features since similar tasks like \r\nsemantic role labeling has been shown to benefit from\r\ninduced word representations. In ~\\autoref{ch:text-kb} and\r\n~\\autoref{ch:ent-link} I will show two applications of it, (1) direct usage for relation discovery and\r\n(2) word feature generation which can be used in current relation discovery\r\nsystems as well as other NLP applications.\r\nIn the next two sections, two major families of representation learning methods\r\nwill be shortly reviewed.\r\n\r\n\\subsection{Distributional Representation}\r\n\\label{sec:distl-repr}\r\nIn distributional semantics, the meaning of a word is expressed by the context\r\nthat it appears in it \\cite{Harris1981}. Features that are used to represent the\r\nmeaning of a word are other words in its neighborhood as it is so called the\r\ncontext. In some approaches like LDA and latent semantic analysis (LSA), \r\nthe context is defined in the scope of a document rather than a window around a\r\nword. To represent word meanings in via distributional approach, one should\r\nstart from count matrix (or zero-one co-occurrence matrix) which each row\r\nrepresents a word and each column is a context. The representation can be\r\nlimited to raw usage of the very same matrix or some transforms like\r\n\\emph{tf-idf} will be applied first. A further analysis over this matrix to\r\nextract more meaningful features is applying dimensionality reduction methods or\r\nclustering models to induce latent distributional representations. A similar\r\nclustering method to k-means is used in \\cite{Lin2009} to represent phrase and\r\nword meanings and brown clustering algorithm \\cite{Brown1992} has been shown to\r\nhave impact on near to state-of-the-art NLP tasks \\cite{Turian2010b}. \r\n\r\n\r\n\\subsection{Distributed Representation}\r\n\\label{sec:disted-repr}\r\nDistributed representation has been introduced in the literature for the first\r\ntime in \\cite{Bengio2003} where Bengio et al. introduced a first language\r\nmodel based on deep learning methods\\cite{Bengio2009b}. Deep learning is\r\nlearning through several layers of neural networks which each layer is\r\nresponsible to learn a different concept and each concept is built over other\r\nmore abstract concepts. In the deep learning society, any word representation\r\nthat is induced with a neural network is called \\emph{Word Embedding}. \r\nIn contrast to raw count matrix in distributional representations, word embeddings are low-dimensional, dense and real-valued vectors.\r\n The term, \\textbf{`Distributed'}, in this context refers to the fact that\r\n exponential number of objects (clusters) can be modeled by word embeddings.\r\n Here we will see two famous models to induce for such representations. One\r\n family will use n-grams to learn word representation jointly with a language\r\n model and the other family learns the embedding from structured resources.\r\nIn \\cite{Collobert2008a}, Weston and Collobert use a non-probabilistic and\r\ndiscriminative model to jointly learn word embeddings and a language model that\r\ncan separate plausible n-grams from noisy ones. For each word in a n-gram, they\r\ncombine the word embeddings and use it as positive example. They put noise in\r\nthe n-gram to make negative examples and then train a neural network to learn to\r\nclassify positive labels from negative ones. The parameters of neural network\r\n(neural language model) and word embedding values will be learned jointly by an\r\noptimization method called \\emph{Stochastic Gradient Descent} \\cite{Bottou2010}.\r\n\r\nA hierarchical distributed language model (HLBL) proposed by Mnih and\r\nHinton in \\cite{Mnih2009} is another influential work on word embeddings. In\r\nthis model a probabilistic linear neural network(LBL) will be trained to \r\ncombine word embeddings in first $n-1$ words of a n-gram to predict the $n_{th}$\r\nword.\r\n\r\nWeston-Collobert model and HLBL by Mnih and Hinton are evaluated in\r\n\\cite{Turian2010b} in two NLP tasks: chunking and named entity recognition. With\r\nusing word embeddings from these models combined with hand-crafted features, the\r\nperformance of both tasks are shown to be improved.\r\n \r\n\\subsection{Representation Learning of Knowledge Bases}\r\n\\label{sec: repr-learning-kb}\r\nBordes et al. in \\cite{Bordes2011} and \\cite{Bordes2012} have attempted to use\r\na neural distributed model to induce word representations from lexical resources\r\nsuch as WordNet ~\\cite{Fellbaum1998} and knowledge bases (KB) like Freebase\r\n~\\cite{Bollacker2008} .\r\nIn Freebase for example, each named entity is related to another entity by an instance of a specific type of relation. In\r\n\\cite{Bordes2011}, each entity is represented as a vector and each relation is decomposed to two\r\nmatrices. Each of these matrices transform left and right-hand-side entities\r\nto a semantic space. Similarity of transformed entities indicates that the\r\nrelation holds between the entities.  A prediction task is defined to evaluate\r\nthe embeddings. Given a relation and one of the entities, the task is to predict\r\nthe missing entity. The high accuracy (99.2\\%) of the model on prediciton\r\nof training data shows that learned representation highly captures attributes of\r\nthe entities and relations in Freebase.\r\n\r\nTwo major models are proposed in \\cite{Bordes2011} and \\cite{Bordes2012} to\r\nlearn features in continuous  vector space from a Knowledge Bases(KB) which information is\r\nusually represented in form of triples of $(e_{i},r_{k} , e_{j} )$ where $e_{i}$ and $e_{j}$ are $i_{th}$ and $j_{th}$ entities related\r\n by a binary relation of type $r_{k}$. The purpose of the models is to induce a vector space and associate\r\n  each entity or relation to an embedding vector or a matrix.\r\n  The dimensions of such an embedding vector are supposed to reflect a set of informative features of entities and relations.\r\n   \r\n   In the first model, \\textbf{structured embeddings(SE)}, entities are modeled as \\textit{d}-dimensional vectors.\r\n    An associated vector to the $i_{th}$ entity, $e_{i}$, is $E_{i} \\in \\mathbb{R}^{d}$. Each relation $r_{k}$  \r\n    is decomposed to two operators each represented as $d \\times d$ matrix, $ R_k = (R_{k}^{left}, R_{k}^{right})$. \r\n    These operators transform the left and right entities to a new space induced by each relation and by using \r\n    a $p$-norm measure  (L1 norm in this work) they associate a similarity value or a score to each triple. \r\n    This similarity value is being calculated by\r\n    Equation ~\\eqref{eq:sim}. \r\n    \\begin{equation}\r\n    \\label{eq:sim}Sim(E_{i}, E_{j}, R) = ||R_{k}^{left}E_{i} - R_{k}^{right}E_{j} ||_{1}\r\n    \\end{equation}\r\n    The similarity between transformed entities works as a score to measure the strength of a relation holds between two entities. \r\n      \r\n    Using the idea of contrastive learning , the model will be trained to increase similarity of \r\n    embeddings for a positive triple (a triple which exists in the KB) or lowering its rank among other training samples\r\n    and decrease the similarity of embeddings when the relation doesn't hold (negative triple) or raising its rank . \r\n    For each positive triple, two negative triples will be generated by randomly alternating the right entity or left entity with other entities.\r\n    Inspired from large margin methods a constraint is introduced on the model\r\n    that forces negative triples to have lower associated similarity value  than correspondent \r\n    positive triples by a large margin. In \\autoref{fig:bordes2011} a schematic\r\n    view of model is presented.\r\n    \r\n    \\begin{figure}[h!]\r\n  \\caption{Neural Distributed Model to Learn Structured Embeddings (SE)}\r\n  \\centering\r\n    \\includegraphics[width=0.5\\textwidth]{bordes2011.eps}\r\n    \\label{fig:bordes2011}\r\n\\end{figure} \r\n    The second model, \\textbf{Semantic Matching Energy using Bilinear layers(SME-Bil)}, \r\n    is using a different representation for relations,weighted bilinear\r\n    transformation of embeddings and  dot product similarity function instead of L1 norm. \r\n    In this model, each relation is represented by a \\textit{d}-dimensional vector $R_{k}$ same as entities. \r\n    For triple $(e_{i},r_{k} , e_{j} )$ , the model combines the weighted transformation of each entity embedding with \r\n    the weighted embedding of relation using element-wise vector product. as it is shown in Equation ~\\eqref{eq:bil}.\r\n    \\begin{equation}\r\n    \\label{eq:bil} E'_{left} = (W_{i} E_{i}) \\odot (W_{k} R_{k}) + b_{left}\r\n    \\end{equation}\r\n    $W_{i}$ and $W_{k}$ are $d \\times d$ weight matrices and $b_{left}$ is a $d$-dimensional bias vector. \r\n    The same equation holds for transforming the right entity embeddings to $E'_{right}$. Finally, the associated score for the triple\r\n     can be calculated by dot product of $E'_{left}$ and $E'_{right}$ which is\r\n     shown in Equation ~\\ref{eq:dot}. \\autoref{fig:bordes2012} is used by Bordes\r\n     et al. to sketch SME-Bil model. Similar constraints to the first model are also applied to this model and \r\n     both models can be trained by stochastic gradient descent (SGD) which we\r\n     introduced in \\autoref{sec:ml-ann}. \r\n    \r\n   \\begin{equation}\r\n    \\label{eq:dot} Sim(E_{i}, E_{j}, R_{k}) = -E'_{left}E'_{right}\r\n   \\end{equation}\r\n     \\begin{figure}[h!]\r\n  \\caption{Neural Distributed Model to Learn Structured Embeddings (SME)}\r\n  \\centering\r\n    \\includegraphics[width=0.5\\textwidth]{bordes2012.eps}\r\n    \\label{fig:bordes2012}\r\n\\end{figure} \r\n   \r\n\r\n\\iffalse\r\n\\section{Bayesian Non-Parametric Models}\r\n\\label {sec:bnp}\r\n\r\n\\subsection{Introduction}\r\n\\label{ssec:intro}\r\nOne of the most important contributions of Machine Learning to Natural Language\r\nProcessing and Computational Linguistics is to provide variety of statistical frameworks for modeling\r\n different aspects of language. Modeling makes the data more interpretable and is trying to represent \r\n it in a compact way. From language modeling to syntax and semantics, \r\n computational models are needed to first describe and then predict the certain phenomena in language. \r\n Here we address a family of models which are trying to be less dependent on human choice or \r\n trial and error schema for choosing best parameters and are called Bayesian nonparametric models (BNP).\r\n \r\n\\subsection{Model Selection with BNP Models}\r\n\\label{ssec:model-sel}\r\nA traditional approach for model selection is to have a set of models and then try to fit \r\nthese models on the linguistic data by tuning and inferring the parameters of them [2]. \r\nIt is more like a search in possible space of models and their parameters to find the best setting. \r\nTherefore, it is necessary to have a criterion to select the models to see which one is better \r\nexplaining the data and have the prediction power. There are two main features that any criterion \r\nshould consider necessarily. First is the accuracy of prediction (model fitness) and it ensures that \r\nthe model is well-defined and second is the complexity of model [1,2]. \r\nLet us define these terms in a mathematical language so we can introduce a Bayesian framework for modeling. \r\nThe data is often a set of data points which could be represented as vectors or is in more \r\ncomplex structure like a graph or an ordered sequence. For simplicity we first start with \r\ndata point or vector representation of data. Let us define the data as:\r\n\\begin{equation}\r\n\\label{eq:data}\r\nD = y_1,y_2,\\ldots,y_n\r\n\\end{equation}\r\n\r\n\r\nThe model could express predictions by the likelihood which is in this form:\r\n\\begin{equation}\r\nP(D|\\theta,m)\r\n\\end{equation}\r\n\r\nYou see that the predictions are conditioned on the model and a specific parameter in this way. \r\nIn a fully Bayesian model, one should specify the range of parameters or more precisely \r\na distribution over possible parameters should be determined beforehand [2]. \r\nThis could be done by adjusting the prior and then we can incorporate the role of all possible parameters \r\nto predictions weighted by their importance. Here one can notice that the set of parameters are fixed.\r\n\\begin{equation}\r\nP(D|m) = \\int \\! P(D,\\theta|m) \\, \\mathrm{d}\\theta = \\int \\!\r\nP(D|\\theta,m)P(\\theta|m) \\, \\mathrm{d}\\theta.\r\n\\end{equation} \r\n\r\nOne can see in this formula that the prediction is average over all parameters weighted by prior. \r\nEach model is a generative process of data which gives us a joint distribution of hidden and observable variables. \r\nEach data point is drawn from a distribution of observable variables conditioned on \r\nhidden variables (parameters of model) and hidden variables are drawn from a prior distribution [1]. \r\nTo infer the posterior distribution (distribution of hidden variables conditioned on observable variables) \r\nwe can reverse the generative process. \r\nInstead of generating a data point from the distribution we look for the model that more likely explains \r\nthe generation of the data. [1,4]\r\nThe second important aspect of model selection is measuring the complexity of the model. \r\nIf we have two models with about same level of fitting, we favor the one that is simpler since it \r\nperforms better generalization for unseen data. Knowingly as Occam’s razor rule having \r\nless complex model helps avoiding overfitting to the observed data. Bayesian \r\nframework naturally favors simpler models by putting prior over parameters \r\nand penalizing unnecessary complexity of the model [2]. \r\nOne can cleverly ask how much complexity is required for a particular data and how can \r\nwe adapt our modeling to change predictions in the case of having new unseen data? \r\nThe answer of Bayesian nonparametric modelling (BPN) to this problem differs to all previous models \r\nin a way that instead of comparing different models with different complexities it tries to fit \r\na single model on the data which changes its complexity by seeing new data. \r\nWhile previous methods have fixed set of parameters, BNP assumes an infinite number of parameters. \r\nIt is like that BNP has infinite amount of money (parameters) in the bank and whenever \r\nthe data is more expensive (more complex) it spends more money to model the data. \r\nActually \\textit{nonparametric} could be misleading  since they have infinite number of parameters \r\nbut only activate a finite subset of them in the learning phase.  \r\nAnother point of view is to see a BNP model as information channel which parameters are bandwidth of this channel. \r\nAs data grows bigger, more information should be captured by the model so it increase its bandwidth \r\n(uses more parameters) [2].\r\nThere are several families of BNP models available due to different tasks and structure of data and \r\nhidden variables. In following, we enumerate these families shortly and then we\r\ngo more in depth for one of them.\r\n\r\nThese groups of models are [1,4,2]:\r\n\\begin{enumerate}\r\n  \\item Classification and Regression task (Gaussian processes)\r\n\\item Clustering (Dirichlet processes and Chinese restaurant processes)\r\n\\item Density estimation (closed link to clustering)\r\n\\item Ordered discrete sequences data (infinite HMM)\r\n\\item Tree structured data or Hierarchical data (Adaptor grammar, infinite PCFG,\r\nKingman’s coalescent, HDP)\r\n\\item Overlapping clusters and factor analysis (Indian Buffet processes)\r\n\\end{enumerate}\r\n\r\n\\subsection{Clustering (Dirichlet processes and Chinese restaurant processes)}\r\n\\label{ssec:bnp-chinese}\r\n\r\n\\fi\r\n\r\n    ", "meta": {"hexsha": "8712bf2f48197167f661ff6efe982b46a99cc67e", "size": 25074, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis-docs/thesis-writing/src/ml.tex", "max_stars_repo_name": "ehsankddm/thesis", "max_stars_repo_head_hexsha": "737585b592dfb25a4faa9610011f7e90870cbf32", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thesis-docs/thesis-writing/src/ml.tex", "max_issues_repo_name": "ehsankddm/thesis", "max_issues_repo_head_hexsha": "737585b592dfb25a4faa9610011f7e90870cbf32", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis-docs/thesis-writing/src/ml.tex", "max_forks_repo_name": "ehsankddm/thesis", "max_forks_repo_head_hexsha": "737585b592dfb25a4faa9610011f7e90870cbf32", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 62.0643564356, "max_line_length": 146, "alphanum_fraction": 0.7715960756, "num_tokens": 5789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.31732960170649144}}
{"text": "\\iffalse\nThis is a big-ish template that I've been using for years now.\nA lot of the includes are redundant, so if you're reading this and have no idea why\nI've included most things, don't worry - I don't either.\nAlso, compiling this (to PDF, for instance) relies on CSS files present on my\ncomputer (coming from the packages). So it might not look as nice if you\ndo it on yours (especially if you don't have all the packages).\n\nYa'll've been warned.\n\\fi\n\n\\documentclass{article}\n    \\usepackage{subcaption}\n    \\usepackage{amsmath}\n    \\usepackage{amssymb}\n    \\usepackage{color}\n    \\usepackage[dvipsnames]{xcolor}\n    \\usepackage{graphicx}\n    \\usepackage{caption}\n    \\usepackage{float}\n    \\usepackage[hidelinks]{hyperref}\n    \\usepackage{enumitem}\n    \\usepackage[bottom]{footmisc}\n    \\usepackage{flexisym}\n    \\usepackage{cancel}\n    \\usepackage[braket]{qcircuit}\n    \\usepackage[margin=.8in, tmargin=.3in]{geometry}\n    \\renewcommand{\\baselinestretch}{1.2}\n    \\newcommand{\\eps}{\\epsilon}\n    % \\newcommand{\\tens}{\\otimes}\n\n\n    % Fancy comments from Gutmann\n\\newcommand{\\comment}[1][]{#1} % Turn on color comments\n% \\newcommand{\\comment}[1]{} % Turn off color comments\n\\newcommand{\\todo}[1]{\\comment{\\textcolor{Red}{\\textit{\\lbrack TODO: #1 \\rbrack}}}}\n\\newcommand{\\note}[1]{\\comment{\\textcolor{Blue}{\\textit{\\lbrack NOTE: #1 \\rbrack}}}}\n\n\\newcommand{\\tens}[1]{%\n  \\mathbin{\\mathop{\\otimes}\\limits_{#1}}%\n}\n\n    \\setlength{\\parskip}{\\baselineskip}\n    % \\newcommand{\\l}{\\left(}\n    \n    \\usepackage{titlesec}\n    \\usepackage{physics}\n    \n    \\setlength\\parindent{0pt}\n    \\captionsetup{justification=centering}\n    \n    \\title{Quantum Computation and Universal Quantum Computing}\n    \\date{\\today}\n    \\author{Traiko Dinev \\textless traiko.dinev@gmail.com\\textgreater}\n\n\\begin{document}\n\\maketitle\n\\textit{NOTE: This partially follows Introduction to Quantum Computing, a masters level course at the University of Edinburgh.}\n\n\\textit{NOTE: Note this \"summary\" is NOT a reproduction of the course materials nor is it copied from the corresponding courses. It was entirely written and typeset from scratch.}\n\n\\textit{License: Creative Commons public license; See README.md of repository}\n\n\\newcommand{\\epsplus}{\\left( \\frac{1}{2} + \\eps \\right)^{1/2}}\n\\newcommand{\\epsminus}{\\left( \\frac{1}{2} - \\eps \\right)^{1/2}}\n\n\\section{Quantum Systems}\nThe state of a binary quantum system is described by a vector (a ket) in 2 dimensions:\n\\begin{gather}\n    \\ket{0} = \\begin{pmatrix}1 \\\\ 0\\end{pmatrix} \\qquad\n    \\ket{1} = \\begin{pmatrix}0 \\\\ 1\\end{pmatrix} \\\\\n\\end{gather}\n% \nPhysically these can be any differentiable states. In digital computing we often use thresholding to distinguish the \"1\"s from the \"0\"s. Here we use naturally quantized states such as energy levels, spin or (equivalently) polarization. We can extend this to continuous spaces where the discrete quantum states become continuous and sums become integrals. This is the basis of infinite-dimensional Hilbert spaces, which are discussed at the end of this [todo].\n\n\\section{Double Slit Experiment and Superposition}\n\\todo{Motivate why the system collapses when a measurement is performed, etc.} \\todo{Motivate superposition, motivate probabilistic view of QM} \n\\todo{normalization of wavefunctions}\n\n\\section{Postulates of Quantum Mechanics in Bra-Ket Notation}\n\\textbf{System State}\nThe state of a system is captured by its wavefunction $\\psi(x)$. A wavefuncton describes the state of the system as a probability distribution over possible states.\n\\vskip 0.15in\n\n\\textbf{Observables and Wavefunction Collapse}\nEvery observable in classical mechanics (e.g. position, velocity, moment) has a corresponding \\textbf{operator} in quantum mechanics. The operators correspond to observables. Observables are matrices and are Hermitian.\n\\vskip 0.15in\n\nThe most basic observable will be for given state $\\ket{\\alpha}$. If a system is in state $\\ket{\\psi}$ the inner product $\\bra{\\alpha}\\ket{\\psi}$ yields the probability of obtaining $\\bra{\\alpha}$ when measuing in a binary basis. The observable is the matrix that has eigenvalues $\\ket{\\alpha}$ and $\\ket{\\alpha}^\\top$, i.e. not-$\\ket{\\alpha}$.\n\nWhen we perform a measurement, the wavefunction is \\textbf{collapsed} to one of the underlying states we are measuring. We will only consider orthogonal states in this note. So if we measure in the $\\ket{0}$, $\\ket{1}$ basis, we will collapse \\textbf{every quantum state} to either $\\ket{0}$ or $\\ket{1}$. Different states only differ in the probability between the basis vectors. \\textit{This is the essence of quantum mechanics.}\n\nFor example, position vectors are orthogonal states, which means we can measure (infinitely-small) the position of a particle. An operator, the observable, will have for eigenvectors (eigen-\"states\" in QM) each separate position.\n\n\\textbf{Superposition} Given the above observation, we can treat quantum states as a superposition of all possible \\textbf{orthogonal} eigenstates. We can do all sorts of magic by measuring in clever states. Think of it as de-composing a signal into basic frequencies. \\textit{Note: the following is my interpretation}. It's not that the signal itself \\textbf{is built this way by nature}, it's a by-product of how we perceive and measure the world. \\textit{If we can only treat an object as there and not there, we can treat it as being there AND not there at the same time with some probability.}\n\n\\textbf{Time-evolution} Schr{\\\"o}dinger \\todo{add}\nNote this is a wave equation. C.f. \"the\" wave equation (\\todo{add rope wave equation}):\n\n\\begin{equation}\n    H(t) \\ket{\\psi(t)} = i \\hbar \\frac{\\partial}{\\partial t} \\ket{\\psi(t)}\n\\end{equation}\n\n$H$ is the hamiltonian, providing the total energy in the system. This is what we will have to find ourselves for different systems.\n\n\\subsection{Example in a discrete system}\nLet's assume we have the state:\n\\begin{equation}\n    \\ket{\\psi} = \\alpha_0 \\ket{\\phi_0} + \\dots \\alpha_{k - 1} \\ket{\\phi_{K - 1}}\n\\end{equation}\n\nThis is a superposition of $K$ different states with varying amplitudes. This corresponds to the state having a distribution according to these amplitudes. Now let's say we have a device that can measure each of those states $\\phi_i$. This assumes the states are orthogonal, because otherwise we wouldn't be able to perfectly distinguish those states. Then our \\textbf{observable} is:\n\n\\begin{equation*}\n    \\textbf{M} = \\sum_{j = 0}^{K - 1} \\lambda_j\n        \\ket{\\phi_j}\\bra{\\phi_j} = \\text{diag}(\\lambda_1, \\dots, \\lambda_{K - 1})\n\\end{equation*}\n\nWe take the outer product of the vectors, giving us a diagonal matrix over all states. The $\\lambda_j$ correspond to the outcomes, i.e. the \n\\textbf{numbers we read off of the measurement device}. \n\nLet's consider an example. Set $K = 3$ and assume the following quantum state:\n\n\\begin{equation*}\n    \\ket{\\psi} = \\frac{1}{\\sqrt{2}}\\ket{\\phi_0} + \\frac{1}{\\sqrt{2}} \\ket{\\phi_2}\n\\end{equation*}\n\nThe operator for the four states could be:\n\\begin{gather*}\n    \\textbf{M} = \\begin{pmatrix}\n        1 & 0 & 0 & 0 \\\\\n        0 & -1 & 0 & 0 \\\\\n        0 & 0 & 2 & 0\n    \\end{pmatrix} = \\\\ 1 \\times \\ket{\\phi_0}\\bra{\\phi_0} - 1 \\times \\ket{\\phi_1}\\bra{\\phi_1} + 2 \\times \\ket{\\phi_2}\\bra{\\phi_2}\n\\end{gather*}\n\nThe average measurement result would be $\\bra{\\psi} M \\ket{\\psi}$: \n\\begin{gather*}\n    (\\frac{1}{\\sqrt{2}}\\bra{\\phi_0} + \\frac{1}{\\sqrt{2}} \\bra{\\phi_2}) \\times 1 \\times \\ket{\\phi_0}\\bra{\\phi_0} - 1 \\times \\ket{\\phi_1}\\bra{\\phi_1} + 2 \\times \\ket{\\phi_2}\\bra{\\phi_2} \\times (\\frac{1}{\\sqrt{2}}\\ket{\\phi_0} + \\frac{1}{\\sqrt{2}} \\ket{\\phi_2}) \\\\\n    = \\frac{1}{2} (\\ket{\\phi_0} \\bra{\\phi_0} + 2 \\times \\ket{\\phi_2}\\bra{\\phi_2}) = \\frac{3}{2}\n\\end{gather*}\n\nTo understand why this makes sense, consider that $1/2$ of the time we will observe $\\ket{\\phi_0}$, i.e. the number (measurement) $1$. The other half we will observe $\\ket{\\phi_2}$ and $2$. Which adds up to the same figure.\n\n\\subsection{Projective Measurements}\n\\subsection{Density Matrices and Mixed Quantum Probabilitic States}\n\\textit{NOTE: This is a combination of quantum uncertainty and classical uncertainty (noise)}\n\\subsection{Tensors and Tensor Products (Systems of Multiple Quantum States)}\n\n\\section{No-cloning Theorem}\nAssume there exists an operator $U$ such that:\n\\begin{gather*}\n    U \\ket{\\psi} \\tens{} \\ket{0} = \\ket{\\psi} \\tens{} \\ket{\\psi} \\\\\n    U \\ket{\\phi} \\tens{} \\ket{0} = \\ket{\\phi} \\tens{} \\ket{\\phi}\n\\end{gather*}\n\nThen:\n\\begin{gather*}\n    \\ket{00} \\xrightarrow{U} \\ket{00} \\\\\n    \\ket{10} \\xrightarrow{U} \\ket{11}\n\\end{gather*}\n\nHence:\n\\begin{gather*}\n    \\alpha \\ket{00} + \\beta \\ket{10} \\xrightarrow{U} \n        \\alpha U \\ket{00} + \\beta U \\ket{10} \\\\\n        = \\alpha \\ket{00} + \\beta \\ket{11}\n\\end{gather*}\n\nHowever, at the same time:\n\\begin{gather*}\n    \\alpha \\ket{00} + \\beta \\ket{10} = (\\alpha \\ket{0} + \\beta \\ket{1}) \\tens{} \\ket{0} \\xrightarrow{U}\n        (\\alpha \\ket{0} + \\beta \\ket{1}) \\tens{} (\\alpha \\ket{0} + \\beta \\ket{1})\n\\end{gather*}\n\nWhich are trivialy not the same on the right side, but are the same on the left side. Q.e.d.\n\n\\section{Entanglement and Bell States}\nEntanglement is a phenomenon that exists only in quantum systems and it's at the core of quantum computing. Mathematically, consider the following operation on two quantum states:\n\n\\begin{align*}\n    \\ket{+} &= H \\ket{0} =\n        \\frac{1}{\\sqrt{2}}\n        \\begin{pmatrix}\n            1 & 1 \\\\\n            1 & -1\n        \\end{pmatrix} \\begin{pmatrix} 1 \\\\ 0 \\end{pmatrix} =\n        \\frac{1}{\\sqrt{2}} \\begin{pmatrix} 1 \\\\ 1 \\end{pmatrix}\n            = \\frac{1}{\\sqrt{2}} (\\ket{0} + \\ket{1})  \\\\\n    \\ket{-} &= H \\ket{1} = \\frac{1}{\\sqrt{2}} (\\ket{0} - \\ket{1})\n\\end{align*}\n\nwhere $H$ is the hadamard gate. These are a superposition of states. Now let's use $\\ket{+}$ as a control for a CNOT on a $\\ket{0}$. I.e. this circuit:\n\n\\[\n    \\Qcircuit @C=1em @R=.7em {\n        & \\lstick{\\ket{0}} & \\gate{H} & \\ctrl{1} \\\\\n        & \\lstick{\\ket{0}} &  \\qw     & \\targ\n    }\n\\]\n\nThe resulting quantum state (of both qubits) is:\n\\begin{align*}\n    \\frac{1}{\\sqrt{2}}(\\ket{0} + \\ket{1})\\ \\text{CNOT}\\ \\ket{0} =\n        \\frac{1}{\\sqrt{2}} (\\ket{00} + \\ket{11})\n\\end{align*}\n\nwhere $\\ket{00} = \\ket{0} \\tens{} \\ket{1}$ is shorthand for a tensor product. This is known as a \\textbf{maximally entangled} state. This system cannot be separated into two distinct systems (i.e. two tensor-ed quantum states $\\ket{\\alpha} \\tens{} \\ket{\\beta}$). Another way to look at it is that if these qubits were separated (to Alice and Bob's labs), then measurements depend on each other. If Alice measures $\\ket{0}$, then the state collapses to $\\ket{00}$ and Bob also measures $\\ket{0}$ (and vice-versa).\n\nThis is a profound result that holds true in reality. In fact, observation even after the fact causes the system to collapse. Key words are \\textbf{quantum eraser} and \\textbf{delayed-choice quantum eraser} experiments.\n\n\\section{Superdense Coding}\n\\[\n  \\Qcircuit @C=1em @R=.7em {\n    &                  &          &          & b_1 \\qquad \\cwx[1]   & b_2 \\qquad \\cwx[1] & \\\\\n    & \\lstick{\\ket{0}} & \\gate{H} & \\ctrl{1} & \\targ                & \\targ              & \\ctrl{1} & \\gate{H} & \\meter & \\rstick{b_1} \\cw\\\\\n    & \\lstick{\\ket{0}} &  \\qw     & \\targ    & \\qw                  &  \\qw               & \\targ    & \\qw      & \\meter & \\rstick{b_2} \\cw\n  }\n\\]\n\n\\begin{align*}\n    b_1 b_2 ; \\quad\n            & \\text{if}\\ b_1 = 1, \\text{then}\\ Z \\\\\n            & \\text{if}\\ b_2 = 1, \\text{then}\\ X \n\\end{align*}\n\n\n\\end{document}\n", "meta": {"hexsha": "afb2f07c17f79ac4d0bdb4a7c899294df3e6fc87", "size": 11539, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "physics/quantum_computing/summary.tex", "max_stars_repo_name": "include4eto/topic_summaries", "max_stars_repo_head_hexsha": "8eca11d3544fc3c79f328051f170a42227f6c84c", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-13T20:04:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T20:57:56.000Z", "max_issues_repo_path": "physics/quantum_computing/summary.tex", "max_issues_repo_name": "include4eto/topic_summaries", "max_issues_repo_head_hexsha": "8eca11d3544fc3c79f328051f170a42227f6c84c", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "physics/quantum_computing/summary.tex", "max_forks_repo_name": "include4eto/topic_summaries", "max_forks_repo_head_hexsha": "8eca11d3544fc3c79f328051f170a42227f6c84c", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.3886462882, "max_line_length": 598, "alphanum_fraction": 0.6800415981, "num_tokens": 3562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3172179640459786}}
{"text": "\\documentclass[fleqn,10pt]{SelfArx} % Document font size and equations flushed left\n\n\n\\definecolor{color1}{RGB}{0,0,90} % Color of the article title and sections\n\\definecolor{color2}{RGB}{0,20,20} % Color of the boxes behind the abstract and headings\n\n\\JournalInfo{Supplementary Text} % Journal information ``Journal, Vol. XXI, No. 1, 1-5, 2015''\n\\Archive{ } % Additional notes (e.g. copyright, DOI, review/research article)\n\n\\PaperTitle{Technical details for: A profile-based method for measuring the impact of genetic variation} % Article title\n\n\\Authors{Nicole E. Wheeler\\textsuperscript{1}*, Lars Barquist\\textsuperscript{2}, Fatemeh Ashari Ghomi\\textsuperscript{1}, Robert Kingsley\\textsuperscript{3}, Paul P. Gardner\\textsuperscript{1,4}} % Authors\n\\affiliation{\\textsuperscript{1}\\textit{School of Biological Sciences, University of Canterbury, Christchurch, New Zealand.}} % Author affiliation\n\\affiliation{\\textsuperscript{2}\\textit{Institute for Molecular Infection Biology, University of Wuerzburg, Wuerzburg, Germany.}} % Author affiliation\n\\affiliation{\\textsuperscript{3}\\textit{Institute of Food Research, Norwich Research Park, Norwich, Norfolk, United Kingdom.}}\n\\affiliation{\\textsuperscript{4}\\textit{Biomolecular Interaction Centre and the Bio-Protection Research Centre, University of Canterbury, Christchurch, New Zealand.}}\n\\affiliation{*\\textbf{Corresponding author}: nicole.wheeler@pg.canterbury.ac.nz} % Corresponding author\n\n\\Keywords{genome variation --- genotype --- phenotype} % Keywords - if you don't want any simply remove all the text between the curly brackets\n\\newcommand{\\keywordname}{Keywords} % Defines the keywords heading name\n\n%----------------------------------------------------------------------------------------\n%\tABSTRACT\n%----------------------------------------------------------------------------------------\n\n\\Abstract{In the following we provide some mathematical justification\n  for the Delta bitscore metric that we evaluate in the accompanying\n  manuscript.}\n\n\\begin{document}\n\n\\flushbottom % Makes all text pages the same height\n\\maketitle % Print the title and abstract box\n%\\tableofcontents % Print the contents section\n\n\\thispagestyle{empty} % Removes page numbering from the first page\n\n%----------------------------------------------------------------------------------------\n%\tARTICLE CONTENTS\n%----------------------------------------------------------------------------------------\n\n\\section*{Introduction} % The \\section*{} command stops section numbering\n\nIn this document we compare the mathematics motivating profile HMM\n\\cite{Krogh:1994,BSA1998} based methods for quantifying the likely\nphenotypic significance of genetic variation. We focus on methods\nthat compare a reference ($ref$) sequence to a variant ($var$)\n\\cite{Clifford:2004,Shihab:2013,Shihab:2013a,Shihab:2014,Liu:2014,Liu:2015}\nThese methods are the \\emph{logR.E-value} approach\n\\cite{Clifford:2004}, \\emph{FATHMM}\n\\cite{Shihab:2013,Shihab:2013a,Shihab:2014}, HMMvar\n\\cite{Liu:2014,Liu:2015} and \\emph{DBS} (this study).\n\n\\section{Methods}\n\n\n\n\\subsection{Delta bitscore (DBS)}\n\nWe define delta bitscore (DBS) as: \n\n\\begin{eqnarray} \n\\label{eq:dbs}\nDBS &=& \\left(x_{ref} - x_{var}\\right)\n\\end{eqnarray}\n\nThe bitscore ($x$) for an HMM is defined as a $\\log$ of probability\nratios \\cite{BSA1998}:\n\n\\begin{eqnarray} \n\\label{eq:bs}\nx &=& \\log_2\\left(\\frac{P(seq|M)}{P(seq|N)} \\right)\n\\end{eqnarray}\n\nWhere $M$ is a profile model derived from a sequence alignment. $M$\ncan generate and score sequences based upon how likely they are to\nhave been produced by the same process as those in the sequence\nalignment.  $N$ is a null model, that generates and scores sequences\nbased upon how likely they are to have produced by a random process.\n\nTherefore, $DBS$ can be re-written as:\n\n\\begin{eqnarray} \n\\label{eq:dbs}\nDBS(seq_{ref}, seq_{var}) &=&      \\log_2\\left(\\frac{P(seq_{ref}|M)}{P(seq_{ref}|N)}\\right) \\nonumber\\\\ \n\\label{eq:dbs1}\n                                & - & \\log_2\\left(\\frac{P(seq_{var}|M)}{P(seq_{var}|N)}\\right)\\\\\n\\label{eq:dbs2}\n                               &\\approx& \\log_2\\left(\\frac{P(seq_{ref}|M)}{P(seq_{var}|M)} \\right)\n\\end{eqnarray}\n\nIf we make the simplifying assumption that the null models for\n$P(seq_{ref}|N)$ and $P(seq_{var}|N)$ are approximately equal\n(i.e. equal length and amino acid composition).  Therefore, the first\nterm of Equation~\\ref{eq:fathmm1} and Equation~\\ref{eq:dbs2} are, in\nmost situations, equivalent. \n\n\n\n\\subsection{logR.E-value}\n\nClifford \\emph{et al.} (2004) suggest using the following measure to\nestimate the significance of a genetic variant:\n\n\\begin{equation} \n\\label{eq:logre}\n\\log R.E = \\log_{10}\\left(\\frac{E-value_{var}}{E-value_{ref}}\\right)\n\\end{equation}\n\nWhere $E-value_{var}$ and $E-value_{ref}$ correspond to the\nexpectation value derived from HMMER matches (to the same model) for a\nvariant ($var$) and canonical ($can$) protein sequence. \n\n$E-values$ are generally estimated by fitting an exponential\ndistribution to an empirical (usually simulated)\ndistribution. I.e. \n\n\\begin{equation} \n\\label{eq:eval}\nE-value = \\kappa MN e^{\\lambda x}\n\\end{equation}\n\nWhere $x$ is the bit-score for a match between a profile HMM and a\nsequence, $MN$ is the product of the database size and the model length\nand, finally $\\kappa$ and $\\lambda$ are parameters that ensure the\nintercept with the y-axis is correct and that the curve matches an\nempirical distribution .\n\nIn a breakthrough theoretical paper by Sean Eddy \\cite{Eddy:2008}, he\nshowed that the most computationally expensive parameter to estimate\n($\\lambda$) is a constant i.e.  $\\lambda=\\ln(2)$.\n\nThus Equation~\\ref{eq:logre} can be rewritten as: \n\n\\begin{eqnarray}\n%\\begin{align*}\n\\label{eq:logre2}\n\\log R.E %&=& \\log_{10}\\left(E-value_{var}\\right) - \\log_{10}\\left(E-value_{ref}\\right)\\\\\n       &=& \\log_{10} \\left( e^{\\lambda x_{var}} \\right) - \\log_{10} \\left( e^{\\lambda x_{ref}} \\right)  \\\\\n       &=& \\left(x_{var}-x_{ref}\\right)*\\log_{10}(e^{\\lambda})                                   \\nonumber \\\\\n       &=& -DBS*constant \\nonumber \n%\\end{align*}\n\\end{eqnarray}\n\nIf the base for the exponential and the logarithms had been equal,\nthen $constant$ the constant would equal $\\lambda$. In either case, a\nconstant multiplied by the difference between two bitscores is all\nthat remains.\n\n\\subsection{FATHMM}\n\nShihab \\emph{et al} (2013) define the following unweighted measure for\nestimating the significance of a single non-synonymous SNP (the\nweighted version is trained to discriminate human disease from\npolymorphic variation, therefore is not directly comparable to our\ngeneral approach) \\cite{Shihab:2013}. Their metric is a logit or log-odds value, comparing the\nemission probability of the wild-type variant ($P_{ref}$) and a mutant\nvariant ($P_{var}$) when the mutant is a single, non-synonymous point\nmutation (i.e. not multiple point mutations or indels):\n\n\\begin{eqnarray}\n%\\begin{align*}\n\\label{eq:fathmm}\nunweighted &=& \\ln \\left( \\frac{P_{var}/(1-P_{var})}{P_{ref}/(1-P_{ref})} \\right)\\\\\n\\label{eq:fathmm1}\n           &=& \\ln \\left( \\frac{P_{var}}{P_{ref}} \\right) + \\ln \\left( \\frac{1-P_{ref}}{1-P_{var}} \\right) \\\\ %\\nonumber \\\\\n\\label{eq:fathmm2}\n           &\\approx& -DBS + \\ln \\left( \\frac{1-P_{ref}}{1-P_{var}} \\right)                                \n%\\end{align*}\n\\end{eqnarray}\n\nThe value $1-P_{ref}$ and  $1-P_{var}$ can be re-written as the following summation: \n\n\\begin{eqnarray} \n\\label{eq:logitw}\n1-P_{ref}=\\sum_{i\\in{amino-acids},i\\ne ref} P_i\\\\\n\\label{eq:logitm}\n1-P_{var}=\\sum_{j\\in{amino-acids},j\\ne var} P_j\n\\end{eqnarray}\n\nEquations~\\ref{eq:logitw}\\&\\ref{eq:logitm} share 18 terms (for each of\nthe 20 amino acids, less the ones corresponding to the wild-type (w)\nand mutant (m) variants. Therefore, $1-P_{ref} \\approx 1-P_{var}$ for most\nrealistic biological results. As a consequence, the second term of\nEquation~\\ref{eq:fathmm2} is approximately zero (or at least, modest\nin comparison to the first term when there is a large difference\nbetween $P_{ref}$ and $P_{var}$). Therefore a difference between bitscores is\nthe term that dominates Equation~\\ref{eq:fathmm}.% (see the discussion below). \n\n\\subsection{HMMvar}\n\nLiu \\emph{et al} (2014\\&2015) present a similar metric to \\emph{FATHMM}\nfor estimating the significance of variation using a profile-HMM based\napproach, with some important differences in the implementation\n\\cite{Liu:2014,Liu:2015}.  The authors calculate the probability of\neach sequence directly from \\emph{HMMER3} bitscores using $P =\nP_{null} *e^B$, where $P_{null} = exp(l*\\log(P_1)+\\log(1-P_1))$, the\nsequence length is $l$ and $P_1 = \\frac{350}{351}$.\n\n\\begin{eqnarray}\n%\\begin{align*}\n\\label{eq:hmmvar}\nS &=&  \\frac{P_{ref}/(1-P_{ref})}{P_{var}/(1-P_{var})} \\\\\n\\log_2\\left(S\\right) &=&  \\log_2\\left(\\frac{P_{ref}/(1-P_{ref})}{P_{var}/(1-P_{var})}\\right) \\\\\n                     &=&  \\log_2\\left(\\frac{P_{ref}}{P_{var}}\\right) - \\\\ \n                     & &  \\log_2\\left(\\frac{1-P_{var}}{1-P_{ref}}\\right) \\\\\n                     &\\approx& -\\log_2\\left(\\frac{1-P_{var}}{1-P_{ref}}\\right) - DBS\n%\\end{align*}\n\\end{eqnarray}\n\nLiu \\emph{et al} do discuss the possibility of using $DBS$, which they\ncall $D$, they conclude that ``prediction results using $D$ were not\nbetter than for $S$, and hence are not reported here''.\n\n\\section{Discussion}\n\nAs a consequence, the measures used by the \\emph{$\\log$R.E-value}\n(Equation~\\ref{eq:logre2}) and the \\emph{FATHMM}\n(Equation~\\ref{eq:fathmm2}) approach are approximations to the more\ndirect estimation of significance, $DBS$. In the case of\n\\emph{FATHMM}, only single point mutations are considered, missing the\nwealth of variation due to insertions, deletions, multiple SNPs and\nand other larger-scale variants.\n\nThe \\emph{HMMvar} approach is similar to DBS, this method employs full\nlength HMMs (including indel states), just like $DBS$. \n\nConsequently, $DBS$ is a direct measure of the potential impact of\ngenetic variation, that can be used on small as well as large and\ncomplex variants. We propose that this metric can be used to evaluate\nboth population variation as well as variation between species. The\nmean of the distribution should be approximately zero, while the\nvariance will increase with increasing phylogenetic distance (and\ndifferent levels of selection). \n\nOne factor that may have an undue influence on $DBS$ is in the rare\ncases where the optimal alignment between a the profile and the\nvariant and the profile and the canonical sequence differ. For\nexample, \\emph{HMMER3} currently only has a local mode (i.e. no\n``glocal'' option). As a result, split matches can occur, and\nalignment slippage is also possible, particularly for repetitive\nsequences.\n\nOne way to mitigate these possibilities is to use \\emph{Forward\n  Scores}, which rather than reporting just the value for an optimal\nalignment, reports instead the sum of all possible alignments between\na query sequence and the profile model. \n\n%----------------------------------------------------------------------------------------\n%\tREFERENCE LIST\n%----------------------------------------------------------------------------------------\n\\bibliographystyle{unsrt}\n\\bibliography{paulall}\n\n\\end{document}\n\n\n", "meta": {"hexsha": "3a9c6ee9fead0c7b7baff178000c2dfc849d5eb2", "size": 11237, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "manuscript/supplementary-text.tex", "max_stars_repo_name": "UCanCompBio/deltaBS", "max_stars_repo_head_hexsha": "91006b11137a49521d22d1080ab7ff3eb39c791a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2016-07-19T15:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-28T03:04:21.000Z", "max_issues_repo_path": "manuscript/supplementary-text.tex", "max_issues_repo_name": "UCanCompBio/deltaBS", "max_issues_repo_head_hexsha": "91006b11137a49521d22d1080ab7ff3eb39c791a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2016-10-19T12:43:55.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-20T08:42:41.000Z", "max_forks_repo_path": "manuscript/supplementary-text.tex", "max_forks_repo_name": "Gardner-BinfLab/deltaBS", "max_forks_repo_head_hexsha": "91006b11137a49521d22d1080ab7ff3eb39c791a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-10-19T11:29:34.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T11:29:34.000Z", "avg_line_length": 43.5542635659, "max_line_length": 206, "alphanum_fraction": 0.6927115778, "num_tokens": 3200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947155710234, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.31721795752084403}}
{"text": "\\section{Project Description}\n\nOne of the focus areas for DIANA~\\cite{DIANA-proposal-2014} is to ``establish infrastructure for a higher-level of collaborative analysis, building on the successful patterns used for the Higgs boson discovery''.\nA large component of this focus is statistical software.\n\\code{RooFit}~\\cite{Verkerke:2003ir} is one of the primary tools used now, but it is facing scalability challenges.\nIn addition to processing speed, which is being addressed with GPU-based fitting approaches, we also face memory limitations as the combined statistical models grow in size.\nThus, it is critical to investigate more distributed models.\\\\\n\nWithin only a couple of years, the rapid development of software libraries for numerical computations through data flow graphs (e.g., \\code{TensorFlow}~\\cite{tensorflow2015-whitepaper}, \\code{Theano}~\\cite{theano-full}, and \\code{MXNet}~\\cite{DBLP:journals/corr/ChenLLLWWXXZZ15}) has led to a fundamental change of paradigm in machine learning software.\nThese libraries are designed around the concept that a numerical program can often equivalently be expressed as a graph --- where nodes represent mathematical operations and edges represent the data communicated between them.\nMost notably, these libraries allow one to automatically deploy computation over one or more CPUs or GPUs within a single API. This makes it easy to maximize performance without specialized software expertise.\\\\\n\nWhile these frameworks were originally developed for the purpose of deep learning research, they are usually general enough to be applicable in a wide variety of other domains.\nFor this reason, the objective of this DIANA project --- conducted by Matthew Feickert under the mentorship of Gilles Louppe and Vince Croft --- is to investigate the pros and cons of implementing the statistical models used in particle physics with a different computational graph framework.\nAs these models are typically built with \\code{RooFit} and \\code{HistFactory}~\\cite{Cranmer:2012sba}, we first wish to establish reference benchmarks in these frameworks.\nLater in the project, we will assess the capabilities and limits of different frameworks and determine how they would scale in terms of data and model parallelism.\nIn addition, the study should also determine whether existing probabilistic programming framework based data flow graphs (e.g., \\code{Edward}~\\cite{tran2016edward} and \\code{tensorprob}~\\cite{tensorprob2016}) are applicable for particle physics statistical models.\nWhere appropriate, the study should finally identify shortcomings on which further software efforts could be dedicated.\\\\\n\nChien-Chin Huang is a computer science Ph.D. student supported via DIANA.\nHe is investigating the model and data parallelism in systems such as \\code{TensorFlow}.\nA bottle neck in the current work is a set of benchmark physics problems that he can use for these scalability tests.\nThis DIANA fellowship would help remove that bottleneck and accelerate work to connect other DIANA projects like \\code{Histogrammar}~\\cite{histogrammar2017}.\n", "meta": {"hexsha": "439cc088d9e7a383bbd02c02d0671b325b10700a", "size": 3080, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/proposal.tex", "max_stars_repo_name": "matthewfeickert/DIANA-Proposal-Feickert", "max_stars_repo_head_hexsha": "dac5181e7e87e747fbdb3c5a6d0201f723fa4670", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/proposal.tex", "max_issues_repo_name": "matthewfeickert/DIANA-Proposal-Feickert", "max_issues_repo_head_hexsha": "dac5181e7e87e747fbdb3c5a6d0201f723fa4670", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-04-10T20:42:05.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-11T14:33:40.000Z", "max_forks_repo_path": "src/proposal.tex", "max_forks_repo_name": "matthewfeickert/DIANA-Proposal-Feickert", "max_forks_repo_head_hexsha": "dac5181e7e87e747fbdb3c5a6d0201f723fa4670", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 128.3333333333, "max_line_length": 353, "alphanum_fraction": 0.8155844156, "num_tokens": 642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3171515554997103}}
{"text": "% Copyright 2011, 2013 David W. Hogg (NYU).\n% All rights reserved (for now).\n\n% to-do\n% -----\n% - write\n% - edit\n% - post\n\n\\documentclass[12pt, letterpaper]{article}\n\\input{../hogg_style}\n\n\\newcommand{\\data}{D}\n\\newcommand{\\alldata}{\\{D_i\\}_{{\\mathrm{all}}\\,i}}\n\\newcommand{\\galpars}{\\theta}\n\\newcommand{\\hyperpars}{\\alpha}\n\\newcommand{\\amplitude}{C}\n\n\\begin{document}\n\\section*{Data analysis recipes:\\\\\n          Classification at low signal-to-noise}\n\n\\begin{abstract}\nIn classification problems of interest to physicists and astronomers,\nit is not usually appropriate to use ``black-box'' classifiers (SVMs,\nneural nets, and the like) trained on well-classified training sets.\nThis is because training data tend to be different---in selection,\ncalibration, signal-to-noise, or other important properties---from the\ndata on which the classification is to be performed.  Furthermore, the\ndata set to be classified is usually itself the best source of data\nabout the classification; if it weren't, the investigator wouldn't be\nwanting to classify it!  Furthermore, the investigator usually wants\n(whether or not he or she knows it) probabilistic classifications, for\nuse in subsequent utility-based hard classification or\nforward-modeling projects.  Here we show that if the investigator has\ngenerally useful information about the different classes and a noise\nmodel for the data, hierarchical probabilistic inference can be used\nto construct extremely successful classifiers even with no training\ndata whatsoever.  The method works by building a mixture-of-classes\nmodel for the observed data, finding class probabilities and parameter\ndistributions that optimize the probability of the data under the\nmodel (the marginalized likelihood), and then competing the classes\n(mixture components) probabilistically.\n\\end{abstract}\n\nThe general problem of classification with noisy data has generated an\nenormous literature, and a wide range of very capable and useful\ntechniques.  Most of these techniques are useless for the kind of\nproblems and objectives that physical scientists encounter: These are\nproblems where there are not extremely reliable training sets, where\nthe noise in the data is at least partially understood, and where the\nobjective is to propagate uncertainty through the classification\nprocess.\n\nFor example, consider the astronomical problem of star--galaxy\nseparation: The goal is to take a set of images of the sky through\ndifferent filter bandpasses, and determine which of the astronomical\nsources in the image are stars and which are galaxies.\n\nEquations we will encounter include the following:\n\\begin{eqnarray}\\displaystyle\np(\\data_i|S,I) &=& \\normal(\\data_i|0,\\sigma_i^2) \\\\\np(\\data_i|G,\\galpars,I) &=& \\normal(\\data_i|\\galpars_i,\\sigma_i^2) \\\\\np(\\data_i|G,I,\\hyperpars) &=& \\int p(\\data_i|G,\\galpars,I)\\,p(\\galpars|G,\\hyperpars)\\,\\dd \\galpars \\\\\np(\\data_i|I,\\hyperpars) &=& \\sum_{q=S}^G p(\\data_i|q,I,\\hyperpars)\\,P_q \\\\\n1 &=& \\sum_{q=S}^G P_q \\\\\np(\\alldata|I,\\hyperpars) &=& \\prod_i p(\\data_i|I,\\hyperpars) \\\\\np(\\data_i|k,\\amplitude_{ki},I) &=& \\normal(\\data_i|\\amplitude_{ki},\\Sigma_i^2) \\\\\np(\\data_i|k,I,\\hyperpars) &=& \\int p(\\data_i|k,\\amplitude_{ki},I)\\,p(\\amplitude_{ki}|k,\\hyperpars)\\,\\dd \\amplitude_{ki} \\\\\np(\\data_i|I,\\hyperpars) &=& \\sum_k p(\\data_i|k,I,\\hyperpars)\\,P_k \\\\\n1 &=& \\sum_k P_k \\\\\np(\\alldata|I,\\hyperpars) &=& \\prod_i p(\\data_i|I,\\hyperpars) \\\\\n\\end{eqnarray}\n\n\\end{document}\n", "meta": {"hexsha": "71a4139bedfbd1744bba34f21464925b23fb0ab6", "size": 3427, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "AstroSeminar2019Spring/Data_analysis_recipe/DataAnalysisRecipe/hierarchical/classification.tex", "max_stars_repo_name": "bhishanpdl/AstroSeminar_OU", "max_stars_repo_head_hexsha": "3181fb74b3ac67a86c37683ddb0d48355a084495", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AstroSeminar2019Spring/Data_analysis_recipe/DataAnalysisRecipe/hierarchical/classification.tex", "max_issues_repo_name": "bhishanpdl/AstroSeminar_OU", "max_issues_repo_head_hexsha": "3181fb74b3ac67a86c37683ddb0d48355a084495", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AstroSeminar2019Spring/Data_analysis_recipe/DataAnalysisRecipe/hierarchical/classification.tex", "max_forks_repo_name": "bhishanpdl/AstroSeminar_OU", "max_forks_repo_head_hexsha": "3181fb74b3ac67a86c37683ddb0d48355a084495", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.0921052632, "max_line_length": 122, "alphanum_fraction": 0.7557630581, "num_tokens": 916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.31715154822344466}}
{"text": "\\section{An error in Hickerson et al.'s re-analysis of the Philippines data}\n\\citet{Hickerson2013} re-analyzed the dataset of \\citet{Oaks2012} using a\nmodel-averaging approach, where they placed a discrete uniform prior over eight\ndifferent prior models (see Table 1 of \\citet{Hickerson2013}).\nHowever, there was an error in their methodology; their model mixes different\nunits of time.\n\nEach of the eight prior models used in the re-analysis by \\citet{Hickerson2013}\nhas one of two priors on the mean size of the descendant populations of each\ntaxon pair:\n$\\meanDescendantTheta{} \\sim U(0.0001, 0.1)$ or\n$\\meanDescendantTheta{} \\sim U(0.0005, 0.04)$.\nAs described in \\citet{Oaks2012}, the divergence-time parameters in the model\nimplemented in \\msb are in generations scaled relative to a constant\nreference-population size, \\myTheta{C}.\nThis reference-population size is defined in terms of the upper limit of the\nuniform prior on the mean size of the descendant populations,\n\\meanDescendantTheta{}, such that for the prior $\\meanDescendantTheta{} \\sim\nU(\\uniformMin{\\meanDescendantTheta{}},\\uniformMax{\\meanDescendantTheta{}})$,\nthe size of the constant reference population is $\\myTheta{C} =\n\\uniformMax{\\meanDescendantTheta{}}/2$.\nThus, the model used by \\citet{Hickerson2013} mixes two different units of\ntime.\nIn other words, some of their prior and posterior samples are in units of\n$0.05/\\mutationRate$ generations, whereas others are in units of\n$0.02/\\mutationRate$ generations.\n\nA fundamental assumption of the \\msb model and post hoc regression adjustment\nis that all possible values of the parameter of interest (divergence times) are\nin the same units.\nThus, the results in sections ``Using ABC Model Comparison to Weight\nAlternative Priors for the Philippine Vertebrate Data'' and ``Improved Sampling\nEfficiency by Prior Weighting Supports Asynchronous and Recent Divergence for\nthe Philippines Vertebrate Data'' and presented in Figure 2 of\n\\citet{Hickerson2013} are invalid and should be disregarded.\nThe error is easily illustrated by re-plotting their results with the different\ntime units indicated (Figure~S\\ref{figJointPosteriorHickerson}).\n\n\\section{Theoretical implications of empirical priors for Bayesian model\nchoice---A simple example}\n\\begin{linenomath}\nThe distinctions between Bayesian parameter estimation and model choice\ndiscussed in the main text can be illustrated with a simple example.\nLet us say we are interested in the fairness of a particular coin, and we\ndenote the unknown probability of it landing heads as \\myTheta{}.\nMore specifically, we are interested in the probability of two models, $M_1$\nand $M_2$.\nIn both models the outcomes of flipping the coin are assumed to be binomially\ndistributed, but under $M_1$ the coin is weighted toward landing heads (i.e.,\n$\\myTheta{} > 0.5)$), whereas under $M_2$, the coin is weighted toward landing\ntails (i.e., $\\myTheta{} < 0.5$).\nWe already have data from flipping a different coin 20 times that landed both\nheads and tails 10 times each, and so we decide to use these data in specifying\na beta prior on fairness of the new coin of $beta(a=10, b=10)$\n(Figure~S\\ref{figCoinFlip}).\nWe collect data by flipping the coin of interest $N=10$ times, $y=3$ of which\nland heads.\nGiven the beta distribution is a conjugate prior for a binomial likelihood, the\nposterior distribution has the nice analytical form $\\theta \\given y,N \\sim\nbeta(a + y, b + N - y)$, which for the new dataset is simply $beta(13, 17)$\n(Figure~S\\ref{figCoinFlip}).\nThe maximum a posteriori (MAP) estimate of the probability of heads is 0.429,\nand following Equation~\\ref{eq:marginallikelhiood} in the main text the\nmarginal likelihoods of our models of interest are\n\\begin{equation}\n    p(y=3, N=10 \\given M_1) = \\int_{0.5}^{1} p(y=3, N=10 \\given\n    \\myTheta{}, M_1)p(\\myTheta{} \\given M_1) d\\myTheta{} \\approx 0.029,\n\\end{equation}\nand\n\\begin{equation}\n    p(y=3, N=10 \\given M_2) = \\int_{0}^{0.5} p(y=3, N=10 \\given\n    \\myTheta{}, M_2)p(\\myTheta{} \\given M_2) d\\myTheta{} \\approx 0.097.\n\\end{equation}\nGiven the models have equal probability under our prior, we can calculate the\nposterior probability of Model 1 as\n\\begin{equation}\n    p(M_1 \\given y=3, N=10) = \\frac{p(y=3, N=10 \\given M_1)}{p(y=3, N=10 \\given\n    M_1) + p(y=3, N=10 \\given M_2)} \\approx 0.23.\n\\end{equation}\nThis is the correct posterior probability of Model 1 given our prior\nand data.\n\\end{linenomath}\n\nTo give the data more weight relative to the prior, we could use it twice, and\ncalculate an empirical Bayes estimate using a prior of $beta(13,17)$.  This\nresults in a ``posterior'' distribution of $beta(16, 24)$\n(Figure~S\\ref{figCoinFlip}), with a MAP estimate of 0.395, and $p(M_1 \\given\ny=3, N=10) = 0.10$.\nThe estimated posterior distribution of the parameter, and resulting MAP\nestimate, is similar whether or not an empirically informed prior is used.\nHowever, the posterior probability of Model 1 is very sensitive to the\nempirical prior, decreasing by 56\\%.\nBy using the empirically informed prior, we ignored prior uncertainty, leading\nto an underestimate of our posterior uncertainty (Figure~S\\ref{figCoinFlip}).\nWhile this did not greatly affect our estimate of \\myTheta{}, it misled us\nto be overconfident in Model 2.\n% Our mode estimate of \\myTheta{} under the empirical prior might be closer\n% to the true value than our posterior mode.\n% Let us assume the truth of the matter is that the coin under study has a broad\n% flat edge, and as a result lands on its edge at a certain frequency.\n% Hence, both of our models are incorrect (i.e., the outcomes of flipping the\n% coin are not binomially distributed).\n\n\n\n% This can be demonstrated with a simple, albeit contrived, example.\n% Let us say that principal investigator Mary and her new postdoc Will are\n% interested in the hypothesis that the mass of George Washington's periwig\n% renders the quarter dollar of the United States unfair.\n% That is to say their null hypothesis is that the probability of a US\n% quarter landing heads when tossed is less than 0.5 ($\\theta < 0.5$).\n% They can certainly evaluate this hypothesis, they can have undergraduate\n% worker, Joe, flip the coin for them while they tabulate the results.\n% But being Bayesians, before they call Joe into the lab, they agree on a\n% prior probability to place on the set of all possible probabilities that\n% the quarter will land heads when it is flipped.\n% Given that neither of them have a quarter, and their prior knowledge that Joe\n% moonlights as a magician, and is notorious for performing coin and card tricks\n% in the lab, they suspect there is a good chance that the quarter Joe uses will\n% be either two-headed or two-tailed.\n% So, knowing that the beta distribution is the conjugate prior for a binomial\n% likelihood, they decide to use a $beta(a=0.5, b=0.5)$ prior distribution\n% (Figure~\\ref{figCoinFlip}).\n\n% Mary calls Joe into the lab, confirms that he has a quarter, and tells him to\n% begin flipping it.\n% After five tosses, four of which was heads, Joe decides that academics are\n% crazy and leaves the lab to pursue a major in theatre.  Mary and Will, both\n% being computational biologists, are satisfied with their\n% empirical dataset of $y = 4$ heads out of $N = 5$ trials.\n% They know from the conjugacy of the beta prior, that the posterior distribution\n% has the nice analytical form $\\theta|y,N \\sim beta(a + y, b + N - y)$, which\n% in this case is simply $beta(4.5, 1.5)$; this is the true posterior distribution\n% of $\\theta$ given their prior belief and data (Figure~\\ref{figCoinFlip}).\n% This allows them to plug these values into the beta cumulative distribution\n% function to determine that the posterior probability of their hypothesis is\n% $p(\\theta < 0.5 | y=1, N=5) = 0.088$.\n% Given their prior belief and dataset, this indeed is the correct posterior\n% probability of the hypothesis, and Mary and Will should now update their\n% posterior belief accordingly.\n\n% However, reflecting upon the results of their experiment\n% (Figure~\\ref{figCoinFlip}), Mary and Will regret their choice of prior.\n% Their prior looks very ``poorly selected,'' and if they had only known that the\n% coin was fair before the data were collected, they would have selected a much\n% better prior.\n% Clearly, from their results, they should have used a prior centered\n% around 0.2; their data suggest a prior of $beta(4.5, 1.5)$ would have been\n% much ``better.''\n% Rather than resort to flipping the coin five more times, Mary and Will decide\n% to redo their analysis using the much better ``prior'' of $p(\\theta) \\sim\n% beta(4.5, 1.5)$.\n% This gives a ``posterior'' of $\\theta|y,N \\sim beta(8.5, 2.5)$, and a\n% probability of their hypothesis of $p(\\theta < 0.5 | y=1, N=5) = 0.026$.\n% Now convinced that the US quarter is unfair, albeit not due to the mass of\n% President Washington's head as they hypothesized, Will begins composing an\n% e-mail of complaint addressed to the U.S.\\ Mint.\n\n% If Joe's flips were a representative sample, Mary and Will's empirical Bayes\n% estimate might very well be a better point estimate for the parameter\n% \\myTheta{}.\n% However, their empirical Bayes estimate of the probability of their hypothesis\n% is incorrect and biased.\n% This simple example shows how parameter estimation is fundamentally different\n% from estimating the probability of a model.\n% While empirically informed priors can be used to obtain well-behaved parameter\n% estimators, using them for model choice is much less certain.\n\n\n\\section{Validation analyses}\nFollowing \\citet{Oaks2012}, we characterize the model-choice behavior of the\nmodel-averaging approach of \\citet{Hickerson2013} under the ideal conditions\nwhere the prior is correct (i.e., the data are generated from parameters drawn\nfrom the same prior distributions used in the analysis).\nWe used the same prior models as above ($M_1$--$M_5$;\nTable~\\ref{tabModelChoiceEmpirical}), and simulated 50,000 datasets under this\nprior (10,000 from each model).\nWe used a simulated data structure of eight population pairs, with a single\n1000 base-pair locus sampled from 10 individuals from each population.\nWe then analyzed each of these replicate datasets using the same prior with 2.5\nmillion samples (500,000 from each of the five prior models), retaining 1000\nposterior samples.\nOur results are very similar to \\citet{Oaks2012}, but we note that they\nare not directly comparable as our simulations contained eight population\npairs rather than 10 (Figure~\\ref{figValidationMCBehavior}).\nWe find that the approach of \\citet{Hickerson2013} estimates the posterior\nprobability of divergence models reasonably well when all assumptions of the\nmethod are met (i.e., the prior is correct) and the unadjusted posterior\nestimates are used.\nSimilar to \\cite{Oaks2012}, we find that the regression-adjusted estimates of\nthe model probabilities are biased.\n\n\\section{A difficult inference problem}\nIn the main text, we discuss how the prior assumption of uniformly distributed\ndivergence times in \\msb leads to posteriors that are difficult to interpret.\nHowever, it is also important to consider the difficult inference problem with\nwhich \\msb is faced.\nWhen applying \\msb to the dataset of \\citet{Oaks2012} with 22 taxon\npairs, there are 581--602 free parameters that model highly stochastic\ncoalescent and mutational processes.\nUnder this rich stochastic model, the method is estimating the\nprobability of 1002 divergence models \\citep[i.e., the number of integer\npartitions of $Y=22$;][]{Oaks2012}.\nFurthermore, all the information in the sequence alignment of each taxon pair\nis distilled into four summary statistics.\nThis gives us a total of 88 summary statistics (four from each of the 22 taxon\npairs) that contain minimal information about many of the $\\approx 600$\nparameters in the model.\nMore summary statistics can be used in \\msb, but most are highly correlated\nwith the four default statistics, and thus contribute little additional\ninformation about the parameters from the sequence data.\nThe large number of parameters and divergence models relative to the amount of\ninformation in the data is undoubtedly another reason the method lacks\nrobustness to prior conditions.\n\n\\section{Additional clarifications from \\citet{Hickerson2013}}\n\n\\subsection{Saturation of summary statistics}\n\\citet{Hickerson2013} claim the priors used by \\citet{Oaks2012} ``cause much of\nthe explored parameter space to be beyond the threshold of saturation in most\nmtDNA genes.'' To explore this possibility, we simulated datasets under prior\nsettings that match two of the three priors used by \\citet{Oaks2012}:\n$\\meanDescendantTheta{} \\sim U(0.0005, 0.04)$ and $\\ancestralTheta{} \\sim\nU(0.0005, 0.02)$.\nUnder this prior, we randomly sample divergence-time parameters from a uniform\ndistribution of $U(0, 20)$ coalescent units, simulate datasets, and plot the\n\\divt{} values against the summary statistics calculated from the resulting\ndatasets (Figure~\\ref{figSaturationPlot}).\nClearly, the priors used by \\citet{Oaks2012} with upper limits on \\divt{} of five\nand 10 coalescent units suffered little to no effect from saturation.\nEven at divergence times of 20 coalescent units, there is still signal in the\nsummary statistics used by \\msb (Figure~\\ref{figSaturationPlot}).\nThus, the assertion of \\citet{Hickerson2013} that the priors used by\n\\citet{Oaks2012} sample parameter space in which the mtDNA alignments are\nsaturated by substitutions is incorrect and, as a result, does not explain the\nbias they found.\n\n\\subsection{Graphical prior comparisons}\n\\citet{Hickerson2013} advocate the use graphical checks of prior models.\nThis prior-predictive approach entails generating a small number (1000) of\nrandom samples from the prior and plotting the resulting summary statistics in\ncomparison to the observed statistics to see if they coincide (see Figure 1 of\n\\citet{Hickerson2013}).\n% As we show above, this strategy can be misleading, because the resulting plots\n% of this approach have little correlation with the appropriateness of priors.\nGiven the richness of the \\msb model ($\\approx 600$ parameters for the Philippine\ndataset analyzed by \\citet{Hickerson2013}), we do not expect that 1000\n\\emph{random} draws from the vast prior parameter space will yield data and\nsummary statistics consistent with the observed data.\nIn fact, when such random draws are tightly clustered around the observed\nstatistics, this can be an indication that the prior is over-fit, as we show in\nthe main text (Table~\\ref{tabModelChoiceEmpirical} and Figure~S\\ref{figPCA}).\nThus, using such plots to select priors should be avoided, and the use of\nposterior-predictive analyses would be much more informative about the overall\nfit of models.\n\n\\subsection{Differing utilities of \\numt{} and \\vmratio{} in \\texttt{msBayes}}\nThe primary component of the \\msb model is the vector of divergence\ntimes for each of the taxon pairs,\n$\\divtvector = \\{\\divt{1}, \\ldots, \\divt{Y}\\}$\n\\citep{Oaks2012}.\n\\citet{Hickerson2013} argue that the dispersion index of this vector,\n\\vmratio{}, is a better model-choice estimator than the number of \ndivergence-time parameters within the vector,\n\\numt{}.\nThey present a plot of \\numt{} against \\vmratio{} (Fig.~S1 of\n\\citet{Hickerson2013}), which is essentially a plot of sample size versus\nvariance.\nThis plot shows that \\vmratio{} has very little information\nabout the number of divergences among taxa.\nNonetheless, \\citet{Hickerson2013} conclude \\vmratio{} is more informative and\nbiogeographically relevant than \\numt{}.\n% We struggle to follow this logic.\nHowever, the number of divergence-time parameters within the vector and their\nvalues contains all of the information about the temporal distribution of\ndivergences, and is much more informative than the variance (i.e., the\ndispersion index is not a sufficient statistic for \\divtvector).\n\\citet{Hickerson2013} also argue that \\msb can estimate \\vmratio{} much better\nthan \\numt{}.\nHowever, \\citet{Oaks2012} demonstrate that even when all assumptions of the\nmodel are met, \\vmratio{} is a poor model-choice estimator (see plots B, D \\& F\nof Figure 4 in \\citet{Oaks2012}), whereas \\numt{} performs better.\n\nImportantly, \\vmratio{} is limited to estimating the probability of only a\nsingle model (the one-divergence model), and thus its utility for model-choice\nis very limited.\nI.e., it can only be informative about the probability of whether there is one\ndivergence shared among the taxa ($\\vmratio{} = 0.0$) or there is greater than\none divergence ($\\vmratio{} > 0.0$).\nAs a result, not only is its model-choice utility limited, but it is also\nvery difficult to estimate.\n\\vmratio{} can range from zero to infinity, and the point density that it is\nat its lower limit of zero will always be zero.\nThus, an arbitrary threshold (0.01 is used throughout the \\msb literature) must\nbe chosen to make the probability of ``simultaneous'' divergence estimable.\nEven with this arbitrary threshold, it is still not surprising to see that it\nis numerically difficult to obtain reliable estimates of the probability that\n\\vmratio{} is ``near'' its lower limit of zero.\nIt is easier, less subjective, and more interpretable to estimate the\nprobability of the model with one divergence-time parameter (i.e., $\\numt{} =\n1$).\nThus, it is not surprising that \\citet{Oaks2012} find that \\numt{} is a better\nestimator of model probability than \\vmratio{}.\n\n", "meta": {"hexsha": "02d6e79793a5b8dd1747023bf9121844e12f7680", "size": 17441, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "manuscripts/reply/reply-si-main.tex", "max_stars_repo_name": "joaks1/msbayes-experiments", "max_stars_repo_head_hexsha": "72fcf3c26f6d92bdcc39343372552f45d72d8f7f", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "manuscripts/reply/reply-si-main.tex", "max_issues_repo_name": "joaks1/msbayes-experiments", "max_issues_repo_head_hexsha": "72fcf3c26f6d92bdcc39343372552f45d72d8f7f", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "manuscripts/reply/reply-si-main.tex", "max_forks_repo_name": "joaks1/msbayes-experiments", "max_forks_repo_head_hexsha": "72fcf3c26f6d92bdcc39343372552f45d72d8f7f", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 57.1836065574, "max_line_length": 82, "alphanum_fraction": 0.776560977, "num_tokens": 4465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3171515482234446}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\section{Covariant quantization of the electromagnetic field}\n\n\\marginpar{Saturday\\\\ 2020-6-20, \\\\ compiled \\\\ \\today}\n\nWe try to apply the canonical quantization procedure with commutators to our massless vector field theory, with the gauge fixing term in the Feynman gauge \\(\\xi = 1\\). \n\nFrom the Poisson brackets we derived from the fields we obtain the quantization conditions: \n%\n\\begin{align}\n\\qty[A^{\\mu }(\\vec{x}, t), \\pi^{\\prime, \\nu }(\\vec{y}, t)] = i \\eta^{\\mu \\nu } \\delta^{(3)} (\\vec{x}-\\vec{y})\n\\,,\n\\end{align}\n%\nwhile the commutators of \\(\\qty[A, A]\\) and \\(\\qty[\\pi , \\pi ]\\) vanish. \nHere we have \\(\\pi^{\\prime \\nu } = - \\partial_0 A^{\\mu }\\): so, we can write everything in terms of \\(A\\),\n%\n\\begin{align}\n\\qty[A^{0} (\\vec{x}, t), \\partial_0 A^{0} (\\vec{y}, t)] &= - i \\delta^{(3)} (\\vec{x} - \\vec{y}) \\\\\n\\qty[A^{i} (\\vec{x}, t), \\partial_0 A^{i} (\\vec{y}, t)] &= + i \\delta^{(3)} (\\vec{x} - \\vec{y})\n\\,,\n\\end{align}\n%\nso the spatial components \\(A^{i}\\) obey the same quantization conditions as the \\emph{real scalar field}, while the temporal component has an extra minus sign. \nThis is a qualitative indication of the fact that something will be wrong with the quantization of \\(A^{0}\\). \n\n\\begin{claim}\nThe creation and annihilation operators for the massless vector field can be written as \n%\n\\begin{align}\na_0 (k) &= - \\frac{1}{(2 \\pi )^{3/2}} \\int \\frac{ \\dd[3]{x}}{\\sqrt{2 \\omega_{k}}}\n\\epsilon^{\\mu }_{(0)} (k) \\qty(\\omega_{k} A_{\\mu } (x) + i \\partial_0 A_{\\mu }(x))\\eval{e^{ikx}}_{k_0 = \\abs{\\vec{k}}} \\\\\na_i (k) &= + \\frac{1}{(2 \\pi )^{3/2}} \\int \\frac{ \\dd[3]{x}}{\\sqrt{2 \\omega_{k}}}\n\\epsilon^{\\mu }_{(i)} (k) \\qty(\\omega_{k} A_{\\mu } (x) + i \\partial_i A_{\\mu }(x))\\eval{e^{ikx}}_{k_0 = \\abs{\\vec{k}}}\n\\,.\n\\end{align}\n\\end{claim}\n\n\\begin{proof}\n\\todo[inline]{To do.}\n\\end{proof}\n\nWith this, the canonical quantization conditions needed to recover the harmonic oscillator algebra with these creation and annihilation operators read: \n%\n\\begin{align}\n\\qty[a_{\\lambda } (k), a ^\\dag_{\\lambda '} (p)] = - \\eta_{\\lambda \\lambda'} \\delta^{(3)} (\\vec{k} - \\vec{p})\n\\,,\n\\end{align}\n%\nwhile the \\(\\qty[a, a]\\) and \\(\\qty[a ^\\dag, a ^\\dag]\\) commutators vanish. So, we have \\textbf{four} sets of harmonic oscillators, parametrized by \\(\\lambda \\). \nOnce again the \\(\\lambda = 0\\) polarization has the wrong sign (\\(- \\eta_{00 } = -1\\)). \n\nLet us now try and define the observables of this theory. \n\n\\subsubsection{Number density operator}\n\nLet us define \n%\n\\begin{align}\n\\mathscr{N}_{0}(k) = - a_0  ^\\dag (k) a_0 (k)\n\\qquad \\text{and} \\qquad\n\\mathscr{N}_{i}(k) = + a_i  ^\\dag (k) a_i (k)\n\\,,\n\\end{align}\n%\nand the corresponding number operators \\(N_{\\mu } = \\int \\dd[3]{k} \\mathscr{N}_{\\mu } (k) \\).\n\nThe different sign for \\(a_0 \\) is needed in order to ensure the correct commutation relations, which read: \n%\n\\begin{align}\n\\qty[N_{\\mu }, a_\\mu^{(\\dag)}(k)] = \\mp a_{\\mu }^{(\\dag)}(k)\n\\,,\n\\end{align}\n%\nwhere we have the \\(+\\) if the dagger is present, \\(-\\) if it is not present. \n\n\\subsubsection{Hamiltonian and momentum density}\n\nSince we have defined the number density \\(\\mathscr{N}_{\\lambda } (k)\\), we can also define the Hamiltonian as \n%\n\\begin{align}\nH = \\int \\dd[3]{x} \\mathscr{H}' = \n\\int \\dd[3]{k} \\omega_{k} \\sum _{\\lambda } \\mathscr{N}_{\\lambda } (k)\n\\,.\n\\end{align}\n\nAs usual, normal ordering is implied. Similarly, the momentum operator is \n%\n\\begin{align}\nP_{i} = - \\int \\dd[3]{x} \\eta^{\\mu \\nu } \\qty(\\partial_0 A_{\\mu } \\partial_{i} A_{\\nu }) \n= \\int \\dd[3]{k} k_i \\sum _{\\lambda=0}^{3} \\mathscr{N}_{\\lambda } (k)\n\\,.\n\\end{align}\n\nThese look sensible: however, the issue lies in the definition of the number density operator. \n\n\\begin{claim}\nThe Heisenberg-picture evolution equations read \n%\n\\begin{align}\n\\dv{A_{\\mu }}{t} (\\vec{x}, t) &= -i \\qty[A_{\\mu }(\\vec{x}, t), H] \\\\\n\\dv{\\pi'_{\\mu }}{t} (\\vec{x}, t) &= -i \\qty[\\pi '_{\\mu }(\\vec{x}, t), H]\n\\,,\n\\end{align}\n%\nwhere the Hamiltonian can be found by integrating the Hamiltonian density \n%\n\\begin{align}\n\\mathscr{H}' = \\frac{1}{2} \\qty(\\pi^{\\prime 2}_i + \\qty(\\partial_{i} A_{j})^2 - \\pi_0^2 - \\qty(\\partial_{i} A_0 )^2)\n\\,,\n\\end{align}\n%\nso we can see again that the issue lies in the \\(0\\)-index part. \n\\end{claim}\n\n\\subsection{Fock space and indefinite metric} \n\nWe want to discuss how the Fock space for a vector field can be defined. \n\nThe definition of the \\textbf{vacuum}, as usual, is \\(a_{\\lambda } (k) \\ket{0} = 0\\) for all \\(k\\).\n\nFor \\(\\lambda \\in (1, 2, 3)\\) there are no issues, we proceed as in the scalar case by populating the vacuum with particles. The unphysical behaviour comes out for \\(\\lambda = 0\\): then, we would try to define a 1-particle state by \n%\n\\begin{align}\n\\ket{1(k, 0)} \\propto a ^\\dag_{0} (k) \\ket{0}\n\\,,\n\\end{align}\n%\nbut then we can see that the norm of this state is negative: \n%\n\\begin{align}\n\\braket{1(k, 0)}{1(p, 0)} &\\propto \\bra{0} a_0 (k) a_0 ^\\dag (p) \\ket{0}  \\\\\n&= \\bra{0} \\qty[ a_0 (k),  a_0 ^\\dag (p)] \\ket{0} - \\underbrace{\\bra{0} a_0 ^\\dag (p) a_0 (k)  \\ket{0}}_{= 0}  \\\\\n&= - \\delta^{(3)} (k-p) \\leq 0\n\\,,\n\\end{align}\n%\nwhich means that the metric on the Hilbert space of states is \\textbf{not positive definite}!\nThis is a problem: it directly leads to negative probabilities. \nWe have the expectation values: \n%\n\\begin{align}\n\\bra{1(k, 0)} N_{0} \\ket{1(k, 0)} = - 1 \n\\qquad \\text{and} \\qquad\n\\bra{1(k, 0)} H_{0} \\ket{1(k, 0)} = - \\omega_{k} \n\\,.\n\\end{align}\n\nSo, this new gauge-fixing theory we are trying to quantize leads to inconsistent results! We surely will need to throw it out, right?\n\n\\subsection{The Gupta-Bleuer condition}\n\nThe Fock space we have constructed contains unphysical states. However, we also know that the theory we have quantized is not electromagnetism, and in fact it is larger, since it has 4 degrees of freedom. \n\nRight now the equations of motion for our theory (with \\(\\xi = 1\\)) read \\(\\square A^{\\mu } = 0\\); however in classical electromagnetism this condition only holds as long as \\(\\partial_{\\mu } A^{\\mu } = 0\\). \n\nSo, we need a way to enforce this condition. We have seen that we \\emph{cannot impose \\(\\partial_{\\mu } A^{\\mu } = 0\\) in an operatorial sense}, since the condition it leads to is not a covariant one. \n\nThe \\textbf{Gupta-Bleuer} condition is a workaround: instead of imposing the condition on operators, we impose it by restricting the Fock space: if \\(\\ket{\\text{phys}}\\) is any physical state, we ask that \n%\n\\begin{align}\n\\bra{\\text{phys}'} \\partial_{\\mu } A^{\\mu } \\ket{\\text{phys}} =0\n\\,.\n\\end{align}\n\nThe set of states \\(\\qty{\\ket{\\text{phys}}}\\) which satisfy this condition is a subset of the Fock space. \n\n\\begin{claim}\nWe can state the GB condition equivalently as \n%\n\\begin{align}\n\\partial_{\\mu }A^{\\mu }_{+ } \\ket{\\text{phys}} = 0 \n\\qquad \\text{or} \\qquad\n\\bra{\\text{phys}} \\partial_{\\mu }A^{\\mu }_{- }  = 0 \n\\,.\n\\end{align}\n\\end{claim}\n\nThe \\(+\\) solution for the EM field gives us \n%\n\\begin{align}\n\\partial_{\\mu } A^{\\mu }_{+} (x) = \\frac{- i}{(2 \\pi )^{3/2}} \n\\int \\frac{ \\dd[3]{k}}{\\sqrt{2 \\omega_{k}}} \n\\underbrace{k_\\mu \\sum _{\\lambda = 0 }^{3} \\epsilon^{\\mu }_{\\lambda }(k) a_\\lambda (k) \\eval{e^{-ikx}}_{k_0 = \\abs{\\vec{k}.}}}_{L(k)} \n\\,.\n\\end{align}\n\nWe can use the operator \\(L(k)\\) in order to understand what the Gupta-Bleuer condition tells us in momentum space: it is \n%\n\\begin{align}\nL(k) \\ket{\\text{phys}} = 0 \n\\qquad \\text{or} \\qquad\n\\bra{\\text{phys}} L ^\\dag (k) = 0\n\\,.\n\\end{align}\n\nThis can be understood better if it is expressed in terms of the polarization vectors: recall that \\(\\epsilon^{\\mu }_{(0)} = n^{\\mu }\\), \\(\\epsilon^{\\mu }_{(3)} = (k^{\\mu } - (n \\cdot k) n^{\\mu }) / (n \\cdot k)\\) while the other two polarizations are orthogonal: \\(\\epsilon^{\\mu }_{(1, 2)} k_\\mu =0 \\). \n\nIn terms of these, we have \n%\n\\begin{align}\nL(k) &= k_{\\mu } \\qty(n^{\\mu } a_0 (k) + \\qty(\\frac{k^{\\mu }}{(n \\cdot k)} - n^{\\mu } ) a_3(k))   \\\\\n&= (k \\cdot n) \\qty(a_0 (k ) - a_3 (k))\n\\,,\n\\end{align}\n%\nsince \\(k^2=0\\). \nThen, we can explicitly write that \\(L (k) \\ket{\\text{phys}} =0 \\) means:\n%\n\\begin{align}\na_0 (k) \\ket{\\text{phys}} = \na_3 (k) \\ket{\\text{phys}} \n\\,,\n\\end{align}\n%\nwhile \\(\\bra{\\text{phys}} L ^\\dag (k) = 0\\) means:\n%\n\\begin{align}\n\\bra{\\text{phys}} a_0 ^\\dag (k) = \n\\bra{\\text{phys}} a_3 ^\\dag (k) \n\\,.\n\\end{align}\n\nLet us see what this means in terms of actual measurable properties of these physical states: first of all, it means that \n%\n\\begin{align}\n\\expval{\\mathscr{N}_{0} + \\mathscr{N}_{3}} _{\\text{phys}} &= \n\\expval{\n    a ^\\dag_{3} (k) a_3 (k ) - \n    a ^\\dag_{0} (k) a_0 (k )\n    }\n_{\\text{phys}}  \\\\\n&= \n\\expval{\n    a ^\\dag_{3} (k) a_3 (k ) +\n    L ^\\dag (k) a_0(k) -\n    a ^\\dag_{0} (k) a_0 (k )\n    }\n_{\\text{phys}}   \\\\\n&= \n\\expval{\n    a ^\\dag_{3} (k) a_3 (k ) +\n    a ^\\dag_{0}(k) a_0(k) -\n    a ^\\dag_{3} (k) a_0 (k) - \n    a ^\\dag_{0} (k) a_0 (k )\n    }\n_{\\text{phys}}  \\\\\n&= \n\\expval{\n    a ^\\dag_{3} (k) a_3 (k ) -\n    a ^\\dag_{3} (k) a_0 (k) \n    }\n_{\\text{phys}}   \\\\\n&= - \\expval{\n    a ^\\dag_{3} (k) L(k)\n    }\n_{\\text{phys}}  = 0\n\\,,\n\\end{align}\n%\ntherefore when we compute the expectation of \\(\\sum _{\\lambda } \\mathscr{N}_{\\lambda }(k)\\) on physical states we find only the contributions from the transverse (\\(1\\) and \\(2\\)) polarizations. \nThis also applies to the Hamiltonian, since in momentum space it is proportional to \\(\\sum _{\\lambda } \\mathscr{N}_{\\lambda }\\). \n\nSo, if we require the Gupta-Blauer condition the observables do not depend on the 0 and 3 polarizations; so we can only consider the two transverse ones and be left with a theory that now corresponds to a true quantization of classical electromagnetism, since we have the three conditions\n\\begin{enumerate}\n    \\item \\(\\square A^{\\mu } = 0\\);\n    \\item \\(\\partial_{\\mu } A^{\\mu } = 0\\) for physical states;\n    \\item two polarizations.\n\\end{enumerate}\n\nWe define \\textbf{pseudophoton states} as ones which are obtained by applying \\(L ^\\dag\\) to a physical state (note: the vacuum is a physical state, since \\(a_{\\mu } \\ket{0} = 0\\) for any \\(\\mu \\)). \n\n\\begin{claim}\nA pseudophoton state \\(\\ket{\\psi }\\) satisfies the following properties: \n\\begin{enumerate}\n    \\item \\(\\braket{\\psi }{\\psi } = 0\\): zero norm;\n    \\item \\(\\braket{\\psi }{\\text{phys}} = 0\\): orthogonality to physical states;\n    \\item \\(\\ev{H}{\\psi } = 0\\): zero energy. \n\\end{enumerate}\n\nAlso, the operator \\(L(k)\\) has the following properties: \n\\begin{enumerate}\n    \\item \\(\\qty[L(k), L ^\\dag(p)] = 0\\);\n    \\item \\(\\qty[L(k), H] = \\omega_{k} L(k)\\). \n\\end{enumerate}\n\\end{claim}\n\n\\begin{proof}\n\\todo[inline]{To do.}\n\\end{proof}\n\n\n\\begin{claim}\nIf \\(\\ket{P}\\) is a physical state, and \\(\\ket{Q} = \\ket{P} + \\ket{\\psi }\\) where \\(\\psi \\) is a pseudophoton state then we have \n%\n\\begin{align}\n\\braket{Q}{Q} = \\braket{P}{P} \n\\qquad \\text{and} \\qquad\n\\bra{Q} H \\ket{Q} = \\bra{P} H \\ket{P}\n\\,.\n\\end{align}\n\\end{claim}\n\n\\begin{proof}\nThe first statement is proven using the facts that pseudophoton states are orthogonal to physical ones and have zero norm: \n%\n\\begin{align}\n\\braket{Q}{Q} = \\braket{P}{P} +\n\\underbrace{\\braket{P}{\\psi } +\\braket{\\psi }{P} + \\braket{\\psi }{\\psi }}_{0}\n\\,.\n\\end{align}\n\nThe second statement is similarly proven: if can be expressed in terms of \\emph{physical} energy eigenvectors as \\(\\ket{P} = \\sum _{n} a_n\\ket{n}\\)\n%\n\\begin{align}\n\\bra{Q} H \\ket{Q} &= \n\\bra{P} H \\ket{P} \n+ \\bra{P} H \\ket{\\psi }\n+ \\bra{\\psi } H \\ket{P }\n+ \\underbrace{\\bra{\\psi } H \\ket{\\psi }}_{0}  \\\\\n&= \n\\bra{P} H \\ket{P} \n+ \\qty(\\sum _{n} a_n \\bra{n}) H \\ket{\\psi }\n+ \\bra{\\psi } H \\qty(\\sum _{n} a_n \\ket{n})  \\\\\n&= \\bra{P} H \\ket{P} \n+ \\sum _{n} a_n E_n \\underbrace{\\braket{n}{\\psi }}_{0}\n+ \\sum _{n} a_n E_n \\underbrace{\\braket{\\psi }{n }}_{0}\n\\,.\n\\end{align}\n\\end{proof}\n\nSo, we can take as our states \\textbf{equivalence classes} of states, up to addition of pseudophoton states. \n\nWe generate physical Fock states by repeatedly applying the transverse polarization creation operators to them; and then add an arbitrary amout of pseudophoton states. \n\n\\begin{claim}\nThese equivalence classes are related to residual gauge invariance.  \n\\end{claim} \n\n\\subsection{Covariant commutators for the photon}\n\nThe covariant commutator can be calculated as \n%\n\\begin{align}\nD^{\\mu \\nu } (x-y) &= \\qty[A^{\\mu  }(x), A^{\\nu }(y)]  = D^{\\mu \\nu }_{+}(x-y) + D^{\\mu \\nu }_{-} (x-y)  \\\\\n&= \\qty[A^{\\mu }_{+} (x), A^{\\nu }_{-}(y)]\n+ \\qty[A^{\\mu }_{-} (x), A^{\\nu }_{+}(y)]\n\\,,\n\\end{align}\n%\nand if we plug in the solution to the Maxwell equations \\(\\square A^{\\mu } = 0\\) we find \n%\n\\begin{align}\n\\qty[A^{\\mu }_{+} (x), A^{\\nu }_{-}(y)] &= - \\eta^{\\mu \\nu } D_{+}(x-y) \\\\\n\\qty[A^{\\mu }_{-} (x), A^{\\nu }_{+}(y)] &= - \\eta^{\\mu \\nu } D_{-}(x-y)\n\\,,\n\\end{align}\n%\nso their sum is \n%\n\\begin{align}\nD^{\\mu \\nu } (x-y) = - \\eta^{\\mu \\nu } D_F(x-y)\n\\,,\n\\end{align}\n%\nand all the good results from the scalar case generalize. \n\n\\subsubsection{Summary}\n\nWe can quantize electromagnetism in a non-covariant way in either the Coulomb or Lorentz gauge. \n\nIn order to quantize it \\textbf{covariantly} we need a different theory: we quantize a theory with an additional \\textbf{gauge-fixing} term in the Lagrangian. \nThis theory's Fock space includes unphysical states, with negative norm and negative energy. \n\nIf we \\emph{select} a subset of the Fock space with the \\textbf{Gupta-Bleuer} condition we recover electromagnetism. \nDifferent choices for the gauge-fixing Lagrangian give rise to different gauge choices. \n\nOne may ask: are the observables actually independent of the choice of \\(\\xi \\) in the gauge-fixing Lagrangian? In fact they are, but this is not trivial to show; it depends on the \\textbf{Ward identities} \\eqref{eq:ward-identities}, which we will treat in a later chapter.\n\n\\end{document}", "meta": {"hexsha": "803a1253ca317f358f06ff7a04bc755e9ced4bb8", "size": 13757, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ap_second_semester/theoretical_physics/sheet11b.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "ap_second_semester/theoretical_physics/sheet11b.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ap_second_semester/theoretical_physics/sheet11b.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 36.0130890052, "max_line_length": 303, "alphanum_fraction": 0.6316784183, "num_tokens": 4964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3171515482234446}}
{"text": "\\documentclass[12pt,a4paper]{article}\n\n\\usepackage{amssymb,amsmath,color,enumitem,fancyvrb,hyperref,xspace}\n\\usepackage[affil-it]{authblk}\n\n\\bibliographystyle{alphaurl}\n%\\bibliographystyle{JHEP}\n\n\\setcounter{tocdepth}{2}\n\\fvset{fontsize=\\small,commandchars=\\\\\\{\\}}\n\n\\definecolor{fuchsia}{RGB}{236,0,140}\n\\definecolor{prompt}{RGB}{245,124,0}\n\\definecolor{command}{RGB}{48,63,159}\n\n\\hypersetup{\n    colorlinks,\n    urlcolor={fuchsia},\n    citecolor={blue}\n}\n\n\\input include/commands.tex\n\n\\input include/layout.tex\n\\input include/title.tex\n\n\\begin{document}\n\n\\maketitle\n\\thispagestyle{empty}\n\n\\begin{abstract}\nWe present \\fuchsia\\xspace --- an implementation of the Lee algorithm, which for a given system of ordinary differential equations with rational coefficients $\\partial_x\\,\\V J(x,\\eps) = \\M A(x,\\eps)\\,\\V J(x,\\eps)$ finds a basis transformation $\\M T(x,\\eps)$, i.e., $\\V J(x,\\eps) = \\M T(x,\\eps)\\,\\V J'(x,\\eps)$, such that the system turns into the \\textit{epsilon form}: $\\partial_x\\, \\V J'(x,\\eps) = \\eps\\,\\M S(x)\\,\\V J'(x,\\eps)$, where $\\M S(x)$ is a Fuchsian matrix.\nA system of this form can be trivially solved in terms of polylogarithms as a Laurent series in the dimensional regulator $\\eps$.\nThat makes the construction of the transformation $\\M T(x,\\eps)$ crucial for obtaining solutions of the initial system.\n\nIn principle, \\fuchsia can deal with any regular systems, however its primary task is to reduce differential equations for Feynman master integrals.\nIt ensures that solutions contain only regular singularities due to the properties of Feynman integrals.\n\\end{abstract}\n\\newpage\n\n\\input include/summary.tex\n\\newpage\n\n\\tableofcontents\n\n\\section{Introduction}\n\nMore than 60 years have passed since Richard Feynman proposed a diagrammatic approach for calculating perturbative processes in quantum field theories.\nSince then Feynman integrals calculus has grown to a separate branch of mathematical physics with a big community of scientists conducting research in this exciting field.\nWith no doubt we can say that none of the recent discoveries in the high-energy particle physics could happen without precise theoretical calculations, which are based on the Feynman integrals calculation techniques. \nIt is also clear that such techniques will play a key role for discoveries at the present and future high-energy colliders, hence their development and further improvement are a very important task.\n\nRecent progress in computational techniques has made it possible to automate the calculation of Feynman integrals; problems which seemed impossible 10 years ago now are successfully solved with state-of-the-art computer algorithms.\nAmong the most popular are integration-by-parts (IBP) reduction~\\cite{CT81} and the method of differential equations (DE)~\\cite{Kot91a,Kot91b,Kot91c}; for a detailed overview of these and other methods see~\\cite{Smi06}.\n\nIn this paper we discuss the method of differential equations.\nIn particular, we focus on the fact that a solution to the system of DEs may be easily found as an $\\eps$-series when an epsilon form of this system is known~\\cite{Henn13}.\nWe consider a general algorithm to find an epsilon form of a given system of differential equations in one variable developed by Lee~\\cite{Lee15}, for the review of the subject see~\\cite{Henn14} and \\cite{Pap14,Tan15,ABB15}.\nThe Lee algorithm allows\n\\begin{enumerate}\n  \\item To find a Fuchsian form of the system using improved Moser reduction algorithm \\cite{Mos59}; and then\n  \\item To normalize eigenvalues of the Fuchsian system in all singular points.\n\\end{enumerate}\nIf these two steps are successfully completed%\n\\footnote{In principle, the first step can always be done because Feynman integrals contain only logarithmic singularities. For the discussion of potential complications in the second step see Section~\\ref{sec:2}.}\nthen a transformation which puts the initial system into the epsilon form may be easily found.\nAlthough this method is focused on systems for Feynman integrals, it also may be successfully used for different problems provided that the requirements on particular properties of the initial system are satisfied.\nFor another method for finding the epsilon form of a given system with multiple scales see \\cite{Mey16a,Mey16b}.\n\nUntil recently, no implementation of the Lee method was made publicly available.\nThis fact motivated us to develop \\fuchsia \\ --- the first public implementation of the Lee algorithm~\\cite{Lee15} which was presented in \\cite{GM16}.\nAnother implementation of this method, called \\texttt{Epsilon}, was recently presented in \\cite{Pra17}.\nIn this paper we provide a description of some implementation and usage details of \\fuchsia which together with algorithms and tools for the integration-by-parts reduction~\\cite{Lap00,Smi08,MS12,Lee12,Lee13,SS13,Smi14,GLZ16} form a powerful tandem for evaluating Feynman integrals.\n\nThis paper is organized as follows: in Section \\ref{sec:2} we introduce notation and definitions followed by a brief review of the Lee method and related algorithms implemented in \\fuchsia.\nIn Section~\\ref{sec:3} we describe how to install and how to use \\fuchsia from different environments, depending on your goal and programming experience.\n\n\n\\section{Overview of the Lee method}\n\\label{sec:2}\n\n\\subsection{Notation and definitions}\n\nLet us consider a system of ordinary differential equations (ODEs) of this form:\n\\begin{equation}\n\\label{eq:dj}\n    \\partial_x \\V J(x,\\eps) = \\M A(x,\\eps)\\,\\V J,\n\\end{equation}\nwhere $\\V J(x,\\eps)$ is a column-vector of $n$ unknown functions (e.g., master integrals);\n$x$ is a free variable;\n$\\eps$ is an infinitesimally small parameter (e.g., a dimensional regulator in $d=4-2\\eps$ dimensions);\n$\\M A(x,\\eps)$ is an $n \\times n$ matrix, rational in both $x$ and $\\eps$.\n\nIn the general case $\\M A(x,\\eps)$ may have a finite number of poles in $x$ at $x\\in\\{x_k\\}$, including a pole at infinity.\nThe asymptotic behavior of $\\M A(x,\\eps)$ around these poles can be described as:\n\\begin{equation}\n\\label{eq:axeps}\n    \\M A(x \\to x_k,\\eps) =\n    \\begin{cases}\n        (\\M A_{k0}(\\eps) + \\M A_{k1}(\\eps)\\,(x - x_k) + \\dots)/(x - x_k)^{1+p_k} & \\text{if $x_k\\neq\\infty$}, \\\\\n        -(\\M A_{k0}(\\eps) + \\M A_{k1}(\\eps)\\,x^{-1} + \\dots)\\,x^{-1 + p_k} & \\text{if $x_k=\\infty$},\n    \\end{cases}\n\\end{equation}\n\nwhere $p_k$ is the \\textit{Poincar\\'e rank} of $\\M A(x,\\eps)$ at the singular point $x=x_k$.\nIf $p_k=0$, we call $\\M A(x,\\eps)$ \\textit{Fuchsian in $x=x_k$}, and $\\M A_{k0}$ \\textit{matrix residue} of $\\M A(x,\\eps)$ at $x=x_k$.\nIf all $p_k=0$, we call $\\M A(x,\\eps)$ \\textit{Fuchsian}.\n\nThe behavior of the system at $x=\\infty$ is a bit of a special case, but it is essential in the overall reduction process.\nOne must always keep in mind the $x=\\infty$ point, and treat it on the same footing as other singular points.\n\n\\paragraph{Equivalent systems.}\nWe are interested in transforming system~\\eqref{eq:dj} into a simpler form.\nFor this purpose let us consider a change of basis from $\\V J$ into $\\V J'$ using the linear transformation $\\M T(x,\\eps)$:\n\\begin{equation}\n  \\V J = \\M T(x,\\eps)\\, \\V J'.\n\\end{equation}\n\nThis leads to the {\\em equivalent system} of ODEs\n\\begin{equation}\n  \\partial_x \\V J' = \\M A'(x,\\eps)\\,\\V J',\n\\end{equation}\nwith the new matrix being\n\\begin{equation}\n\\label{eq:ta}\n  \\M A'(x,\\eps) = \\M T^{-1} \\left( \\M A \\M T - \\partial_x \\M T \\right).\n\\end{equation}\n\nGenerally speaking, the transformations $\\M T(x,\\eps)$ may have an arbitrary form.\nHowever in the scope of this paper we will require the transformation matrices to be rational in both $x$ and $\\eps$.\nThis restriction guarantees that the equivalent matrix $\\M A'(x,\\eps)$ and hence all equivalent systems are in rational form, thus making the expansion~\\eqref{eq:axeps} possible.\n\nIn particular, we will be using the transformation constructed by stepwise application of a \\textit{$\\M P$-balance between $x=x_1$ and $x=x_2$}, defined as:\n\\begin{equation}\n\\label{eq:bal}\n    \\mathcal{B}(\\M P(\\eps), x_1, x_2; x) = \\M I - \\M P(\\eps) + c \\frac{x-x_2}{x-x_1} \\M P(\\eps),\n\\end{equation}\n\\begin{equation*}\n    c \\equiv\n    \\begin{cases}\n        1/x_2 & \\text{if $x_2=\\infty$}, \\\\\n        x_1 & \\text{if $x_1=\\infty$}, \\\\\n        1 & \\text{otherwise},\n    \\end{cases}\n\\end{equation*}\nwhere $\\M P(\\eps)$ is a projector matrix (that is, $\\M P^2=\\M P$).\n\n\\paragraph{Classification of singularities.}\nFollowing \\cite{Mos59}, for a system \\eqref{eq:dj} and its Laurent expansion~\\eqref{eq:axeps} we define a rational number\n\\begin{equation}\n\\label{eq:mk}\n    m_k(\\M A) = p_k + \\frac{rank(\\M A_{k0})}{n}\n\\end{equation}\nas the {\\em Moser order} of $\\M A(x,\\eps)$ at point $x=x_k$.\n\nEquivalent systems do not necessarily have identical Moser orders.\nIn fact, \\cite{Mos59} introduces an algorithm that constructs a transformation decreasing $rank(\\M A_{k0})$ by at least one (thus reducing $m_k(\\M A)$),\\footnote{Note, that if $rank(\\M A_{k0})$ reaches zero, this means that $\\M A_{k0}$ is now zero itself, and thus the Poincar\\'e rank $p_k$ was decreased by at least one.} or certifies that no further order reduction can be achieved.\n\nLet us then denote the {\\em minimal order} of $\\M A(x,\\eps)$ at $x=x_k$ as:\n\\begin{equation}\n\\label{eq:muk}\n  \\mu_k(\\M A) = \\min m_k(\\M A'), \\text{ for } \\forall \\; \\M T.\n\\end{equation}\n\nIf $\\mu_k(\\M A) < m_k(\\M A)$ we say that the matrix $\\M A(x,\\eps)$ is {\\em Moser-reducible} at $x=x_k$.\n\nWith this in mind we can classify a pole $x=x_k$ of $\\M A(x,\\eps)$ as:\n\\begin{itemize}\n  \\item {\\em apparent singularity}, if $m_k(\\M A) > 0$ and $\\mu_k(\\M A) = 0$;\n  \\item {\\em regular singularity}, if $0 < \\mu_k(\\M A) \\le 1$;\n  \\item {\\em irregular singularity}, if $\\mu_k(\\M A) > 1$.\n\\end{itemize}\nThe matrix $\\M A(x,\\eps)$ is called {\\em Fuchsian} if it does not contain irregular singularities at any value of $x$ including $\\infty$.\n\n\n\\subsection{Reduction to epsilon form}\n\nIn the previous section we have introduced the notation and key definitions related to the Fuchsian theory of ODEs.\nNow we are ready to review the reduction method proposed by Lee in~\\cite{Lee15}.\nWith its help we can construct a rational transformation $\\M T(x,\\eps)$ which converts a system of ordinary differential equations with rational coefficients given by the matrix $\\M A(x,\\eps)$ to an equivalent system given by the matrix $\\M M(x,\\eps)$ which is Fuchsian and has an \\textit{epsilon form} (also called {\\em canonical} in \\cite{Henn13}), i.e., $\\M M(x,\\eps) = \\eps\\, \\M S(x)$.\nWhen the epsilon form $\\M M(x,\\eps)$ of the initial system $\\M A(x,\\eps)$ is found we can easily solve it as a Laurent series in $\\eps$ and restore solutions for the initial system $\\M A(x,\\eps)$ --- which is our ultimate goal --- by solving a linear system of equations.\n\nThe whole method is performed in the following three steps:\n\n\\begin{enumerate}\n    \\item Given a matrix $\\M A(x,\\eps)$, find an equivalent system $\\M A'(x,\\eps)$ and a corresponding transformation $\\M T(x,\\eps)$, such that $\\M A'(x,\\eps)$ is Fuchsian. We call this step \\textit{fuchsification}.\n    \\item Given a Fuchsian matrix $\\M A(x,\\eps)$ with eigenvalues of all its residues of the form $n+m\\,\\eps$, where $n$ is integer, find an equivalent system (along with the transformation) which is still Fuchsian, but with residue eigenvalues being all of the form $k\\,\\eps$. We call this step \\textit{normalization}.\n    \\item Given a normalized matrix $\\M A(x,\\eps)$, find an equivalent matrix $\\M A'(x)$ in epsilon form, i.e. such that $\\M A'(x,\\eps) = \\eps \\, \\M S'(x)$. We call this step \\textit{factorization}.\n\\end{enumerate}\n\n\n\\subsubsection{Fuchsification}\n\\label{sec:fuchs}\n\nTo \\textit{fuchsify} a system~\\eqref{eq:dj} means to find an equivalent Fuchsian system.\nThis, of course, is only possible if $\\M A(x,\\eps)$ has no irregular singularities, or in other words $\\mu_k(\\M A)\\le1$ for all $k$.\\footnote{\n    We expect this to be often the case in practice, in particular for ODEs corresponding to Feynman integrals which are known to have only logarithmic singularities, hence be solutions of some Fuchsian ODEs.\n}\n\nIn the case of a single ODE of order~$n$, the minimal Moser order can be computed explicitly from power counting analysis of its coefficients (see the generalization of Fuchs' theorem in~\\cite{Mos59}).\nThis is not possible for ODE systems like~\\eqref{eq:dj}.\nInstead, we have a criterion for Moser-reducibility of the form:\n\n\\textbf{Theorem 1.}\n{\\em If $m_k(\\M A) > 1$ then the system \\eqref{eq:dj} is Moser-reducible at $x=x_k$ if and only if the polynomial}\n\\begin{equation}\n\\label{eq:red_cond}\n    \\Delta^{r_k} \\det\\left(\\frac{\\M A_{k0}}{\\Delta} + \\M A_{k1} - \\lambda \\,\\M I\\right),\n\\end{equation}\n{\\em vanishes identically in $\\lambda$ at $x=x_k$, where $r_k=\\rank(\\M A_{k0})$ and $\\Delta=x-x_k$ if $x_k\\ne\\infty$, or $\\Delta=1/x$ if $x_k=\\infty$.}\n\nWhen this condition fails the singularity in $x=x_k$ is {\\em irregular}.\n\nIn addition to this criterion we have a method for constructing a transformation that lowers the Moser order at $x_i$, provided that the system is Moser-reducible at that point (possibly at the expense of increasing the Poincar\\'e rank $p_j$ at another point $x=x_j$ by one).\nThis is done by selecting a projector matrix $\\M P$ equal to a sum of products of a particular subset of (generalized) eigenvectors of $\\M A_{i0}$ and $\\M A_{j0}$, and constructing a $\\M P$-balance between $x_i$ and~$x_j$.\n\nThe reader can find the details of this construction in \\cite{Lee15}, but it is important to note that even if the system is Moser-reducible at $x_i$, it is only sometimes possible to construct a transformation that lowers $m_i(\\M A)$ without increasing Poincar\\'e rank at $x_j$.\nSometimes the best we can do is to choose $x_j$ to be some arbitrary regular point, and use a transformation that decreases $m_i(\\M A)$ at the expense of turning $x_j$ into a pole (with $p_j=0$), effectively introducing an apparent singularity where there was none before.\\footnote{\n    In practice these apparent singularities are not a major problem, since they are subsequently removed during the normalization step.\n    Still, we try not to introduce them if possible in order to decrease the intermediate expression sizes and to increase the overall performance.\n}\n\nWith this in mind, to reduce a system to Fuchsian form we need to combine the reducibility check with the Moser rank-lowering transformation in stepwise fashion, as follows:\n\n\\begin{enumerate}\n    \\item Select some point $x_k$ with $m_k(\\M A) > 1$. If none exist, reduction is complete.\n    \\item Check if $\\M A(x,\\eps)$ is reducible at $x=x_k$. If not, fail.\n    \\item Find a transformation $\\M T(x,\\eps) = \\mathcal{B}(\\M P(\\eps), x_k, x_j; x)$ that lowers $m_k(\\M A)$.\n    \\item Apply $\\M T(x,\\eps)$ and repeat from Step 1.\n\\end{enumerate}\n\nIn \\fuchsia, this process is implemented by function \\code{fuchsify}; see Section~\\ref{sec:usage_py} for its usage.\n\nFinally, let us mention that a similar problem of reducing Poincar\\'e ranks and Moser orders of rational matrices was actively studied by Barkatou and co-authors, e.g., see~\\cite{BP99}.\nThey developed algorithms implementing their method~\\cite{BP99} which is available in the standard \\texttt{Maple} package \\texttt{DEtools} as \\code{moser\\_reduce} and \\code{super\\_reduce} routines.\n\n\n\\subsubsection{Normalization}\n\\label{sec:norm}\n\nTo \\textit{normalize} a Fuchsian system \\eqref{eq:dj} with matrix residue eigenvalues of the form $n+m\\,\\eps$ (where $n$ is integer), implies to find an equivalent Fuchsian system with residue eigenvalues of the form $m\\,\\eps$.\n\nJust like in the previous step, the normalizing transformations are found by stepwise application of balance transformations~\\eqref{eq:bal}.\nWe refer the reader to~\\cite[p.~11]{Lee15} for the description of how such balances are constructed, but we will note that this transformation is possible due to these two facts:\n\\begin{itemize}\n    \\item Given a properly selected projector matrix $\\M P(\\eps)$, the balance $\\mathcal{B}(\\M P(\\eps), x_i, x_j; x)$ shifts one of the eigenvalues of $\\M A_{i0}$ by $\\pm1$, shifts one of the eigenvalues of $\\M A_{j0}$ by $\\mp1$, and does not change the Poincar\\'e ranks at any point.\n    \\item Since the system is Fuchsian, the sum of all its matrix residues is zero, and thus, the sum of all residue eigenvalues is zero as well.\n\\end{itemize}\nCombining these two facts, we perform the normalization by shifting the residue eigenvalues by $1$ at each step, until a state is reached where the integer parts of all the eigenvalues are zero.\n\nIn \\fuchsia, the normalization step is implemented by the function \\code{normalize}.\nSee Section~\\ref{sec:usage_py} for its usage.\n\nIt may happen that after fuchsification we obtain a system for which the residue eigenvalues do not fit to the $n+m\\,\\eps$ form neatly.\nIn this case it is sometimes possible to rectify the problem by using some non-linear change of variables.\nUnfortunately we do not have an automated solution for such cases, and users are expected to find transformations appropriate for their system manually.\n\n\n\\subsubsection{Factorization}\n\\label{sec:fact}\nAfter the normalization we have obtained a matrix $\\M A(x,\\eps)$ with all residue eigenvalues of the form $m\\,\\eps$.\nThe final step is to \\textit{factorize} it by finding an equivalent matrix which is by itself proportional to $\\eps$, so $\\M A'(x,\\eps)=\\eps\\,\\M S(x)$.\n\nA transformation which is constant in $x$ is sufficient for this task.\nLet $\\M T(\\eps)$ be such a transformation, then according to \\eqref{eq:ta}, we have:\n\\begin{equation}\n  \\M A'(x,\\eps) \\equiv \\eps\\, \\sum_i \\frac{\\M S_i}{x-x_i} = \\sum_i \\M T^{-1}(\\eps) \\frac{\\M A_{i0}(\\eps)}{x-x_i} \\M T(\\eps),\n\\end{equation}\nor explicitly\n\\begin{equation}\n\\label{eq:seps}\n  \\M S_i = \\M T^{-1}(\\eps) \\frac{\\M A_{i0}(\\eps)}{\\eps} \\M T(\\eps).\n\\end{equation}\nSince $\\M S_i$ in \\eqref{eq:seps} is the same no matter what values $\\eps$ takes, we can say that:\n\\begin{equation}\n  \\M S_i = \\M T^{-1}(\\eps) \\frac{\\M A_{i0}(\\eps)}{\\eps} \\M T(\\eps) =\n    \\M T^{-1}(\\mu) \\frac{\\M A_{i0}(\\mu)}{\\eps} \\M T(\\mu),\n\\end{equation}\nfrom where we obtain a system of linear equations for $\\M T(\\eps,\\mu) \\equiv \\M T(\\eps) \\, \\M T^{-1}(\\mu)$:\n\\begin{equation}\n  \\frac{\\M A_{i0}(\\eps)}{\\eps} \\M T(\\eps,\\mu) = \\M T(\\eps,\\mu) \\frac{\\M A_{i0}(\\mu)}{\\mu}, \\text{for all $i$.}\n\\end{equation}\nSolving this system for $\\M T(\\eps,\\mu)$ we can reconstruct the initial transformation as $\\M T(\\eps) = \\M T(\\eps,\\mu_0)$, where $\\mu_0$ can be chosen arbitrary as long as $\\M T(\\eps)$ will come out invertible.\n\nIn general, the solution for $\\M T(\\eps,\\mu)$ can have multiple free variables aside from just $\\mu$.\nWe choose to set all of them to random small integers, preferably zeros, which keeps the resulting matrix $\\M S(\\eps)$ simple.\n\nIn \\fuchsia the factorization step is implemented as the \\code{factorize} routine (again, see Section~\\ref{sec:usage_py} for its usage).\n\n\\subsubsection{Block-triangular form}\n\\label{sec:blockreduce}\n\nIt often happens that a matrix which defines an ODEs is sparse, i.e. it has many zeros, and can be shuffled into block-triangular form with small blocks.\nIt is possible to exploit this fact to considerably speed up fuchsification and normalization.\n\nLet us consider a block-triangular matrix of this form:\n\\begin{equation}\n\\label{eq:bdiag}\n\\M A(x,\\eps)=\n\\left(\n\\begin{matrix}\n  \\M A^{(11)} & 0 & 0 & 0\n\\\\\n  \\M A^{(21)} & \\M A^{(22)} & 0 & 0\n\\\\\n  \\vdots & \\cdots & \\ddots & 0\n\\\\\n  \\M A^{(m1)} & \\M A^{(m2)} & \\cdots & \\M A^{(mm)}\n\\end{matrix}\n\\right),\n\\end{equation}\nwhere $\\M A^{(ba)}(x,\\eps)$ is a sub-matrix of size $n_b \\times n_a$.\n\nWe start by reducing {\\bf diagonal blocks} of this matrix, $\\M A^{(ba)}(x,\\eps)$, to epsilon form.\nThis can be done by treating each diagonal block as an independent matrix, and proceeding as described in the previous sections.\nSince the characteristic polynomial of a block-triangular matrix is a product of characteristic polynomials of its diagonal blocks, i.e.,\n\\begin{equation}\n  \\det(\\M A(x,\\eps)-\\lambda \\M I) =\n    \\det(\\M A^{(11)}(x,\\eps) - \\lambda\\M I) \\cdot \\ldots \\cdot\n    \\det(\\M A^{(mm)}(x,\\eps) - \\lambda \\M I),\n\\end{equation}\nonce we have normalized the diagonal blocks, the whole matrix becomes normalized as well (but not necessarily Fuchsian yet).\n\nNext, we fuchsify {\\bf off-diagonal blocks} given by rectangular matrices $\\M A^{(ba)}(x,\\eps)$, $b > a$.\nTo do this, let us look at the parts of \\eqref{eq:dj} related to such a block:\n\\begin{equation}\n  \\begin{cases}\n  \\partial_x \\V J^{(a)} =\n    \\M A^{(aa)}\\,\\V J^{(a)} + \\ldots \\\\\n  \\partial_x \\V J^{(b)} =\n    \\M A^{(ba)}\\,\\V J^{(a)} +\n    \\M A^{(bb)}\\,\\V J^{(b)} + \\ldots\n  \\end{cases}\n\\end{equation}\nIf $\\M A^{(ba)}(x,\\eps)$ has a singularity of Poincar\\'e rank $r>0$ at $x=x_k$, then to reduce $r$ we can apply this basis transformation:\n\\begin{equation}\n  \\label{eq:offdiagt}\n  \\V J^{(b)} = \\V J'^{(b)} + \\Delta^{-r} \\M D\\, \\V J^{(a)},\n\\end{equation}\nwhere $\\M D$ is some constant matrix, and $\\Delta=x-x_k$ if $x_k\\ne\\infty$, or $\\Delta=1/x$ if $x_k=\\infty$.\nThis transformation changes $\\M A^{(ba)}_{k0}(\\eps)$ into\n\\begin{equation}\n  \\M A'^{(ba)}_{k0}(\\eps) = \\M A^{(ba)}_{k0}\\!(\\eps) + r\\,\\M D + \\M A^{(bb)}_{k0}\\!(\\eps) \\, \\M D - \\M D\\, \\M A^{(aa)}_{k0}(\\eps)\n\\end{equation}\n\nIf both $\\M A^{(aa)}_{k0}(\\eps)$ and $\\M A^{(bb)}_{k0}(\\eps)$ have been factorized then it is always possible to solve the right-hand side of this equation for $\\M D$, thus reducing the Poincar\\'e rank of $\\M A'^{(ba)}$ by one.\nMoreover, this transformation only affects $\\M A^{(bi)}$ for $i \\le a$ and $\\M A^{(ia)}$ for $i > b$, therefore if we will sequentially apply the transformation \\eqref{eq:offdiagt} for each off-diagonal block, starting from the first row to the last, and from the last column to the first, we will obtain a fully Fuchsian (and still normalized) matrix.\n\nFinally, we factorize the whole matrix as described in Section~\\ref{sec:fact}, thus completing the transformation to epsilon form.\n\nIn \\fuchsia the process of shuffling a matrix to its shortest lower block-diagonal form is performed by the \\code{block\\_triangular\\_form} routine; fuchsification and normalization of diagonal blocks is done by the \\code{reduce\\_diagonal\\_blocks}; fuchsification of the remaining off-diagonal blocks is done by the \\code{fuchsify\\_off\\_diagonal\\_blocks}.\n\n\n\\section{Using \\fuchsia}\n\\label{sec:3}\n\n\\subsection{Installation}\n\nTo run \\fuchsia one needs \\sage~\\cite{sagemath} version 7.0 or higher to be installed on the computer.\nThis task can be accomplished by following installation instructions available at the website \\url{http://www.sagemath.org}.\n\\footnote{\n    Some \\linux distributions have \\sage available in their package repositories; we do not recommend using those.\n    A number of \\maxima releases contain bugs which \\fuchsia is sensitive to, and so far the official \\sage builds have avoided those releases (unlike some \\linux distributions).\n}\n\n\\sage is a free and open-source Computer Algebra System licensed under GPL.\nIt is written in \\python~2.7 and combines together a number of existing open-source mathematical systems and libraries like \\texttt{Maxima}, \\texttt{Singular}, and others with the goal of providing the best free CAS.\nIn particular our code heavily relies on the interface to \\maxima~\\cite{maxima}.\n\nNext, source file \\code{fuchsia.py} should be downloaded from the website \\url{https://github.com/gituliar/fuchsia} (additional materials like examples of reduced matrices and the up-to-date documentation is located there as well).\n\n\n\\vspace{10mm}\n\n\\subsection{Usage from the command line}\n\nTo run \\fuchsia use the command\\footnote{For brevity, we use a shortcut \\code{fuchsia} which is equivalent to \\code{sage -python fuchsia.py}.}\n\\begin{Verbatim}\n    \\prompt{$}{sage -python fuchsia.py <action> <options>}\n\\end{Verbatim}\nwhere\n\\begin{itemize}\n  \\item \\code{<action>} is one of the algorithms described in the previous section, i.e., \\code{fuchsify}, \\code{normalize}, \\code{factorize}, or auxiliary action \\code{transform}, which applies a user-defined transformation to the given matrix.\n  \\item \\code{<options>} are action-dependent options described in the help message printed with the help of \\code{fuchsia -h} command.\n\\end{itemize}\n\nIn the following we provide a complete help information printed by \\code{fuchsia~-h}:\n\\begin{Verbatim}\nFuchsia v17.01.19\nAuthors: Oleksandr Gituliar, Vitaly Magerya\n\nUsage:\n    fuchsia [-hv] [--use-maple] [-f <fmt>] [-l <path>] [-P <path>]\n            <command> <args>...\n\nCommands:\n    reduce [-x <name>] [-e <name>] [-m <path>] [-t <path>] <matrix>\n        find an epsilon form of the given matrix\n\n    fuchsify [-x <name>] [-m <path>] [-t <path>] <matrix>\n        find a transformation that will transform a given matrix\n        into Fuchsian form\n\n    normalize [-x <name>] [-e <name>] [-m <path>] [-t <path>] <matrix>\n        find a transformation that will transform a given Fuchsian\n        matrix into normalized form\n\n    factorize [-x <name>] [-e <name>] [-m <path>] [-t <path>] <matrix>\n        find a transformation that will make a given normalized\n        matrix proportional to the infinitesimal parameter\n\n    sort [-m <path>] [-t <path>] <matrix>\n        find a block-triangular form of the given matrix\n\n    transform [-x <name>] [-m <path>] <matrix> <transform>\n        transform a given matrix using a given transformation\n\n    changevar [-x <name>] [-y <name>] [-m <path>] <matrix> <expr>\n        transform a given matrix by susbtituting free variable\n        by a given expression\n\nOptions:\n    -h          show this help message\n    -f <fmt>    matrix file format: mtx or m (default: m)\n    -l <path>   write log to this file\n    -v          produce a more verbose log\n    -P <path>   save profile report into this file\n    -x <name>   use this name for the free variable (default: x)\n    -y <name>   use this name for the new free variable (default: y)\n    -e <name>   use this name for the infinitesimal parameter (default: eps)\n    -m <path>   save the resulting matrix into this file\n    -t <path>   save the resulting transformation into this file\n    --use-maple speed up calculations by using Maple when possible\n\nArguments:\n    <matrix>    read the input matrix from this file\n    <transform> read the transformation matrix from this file\n    <expr>      arbitrary expression\n\\end{Verbatim}\n\nSimple and more advanced results obtained with the help of \\fuchsia are located in the directory \\code{examples}.\nThere you will find many examples of original matrices together with generated transformations which lead to the epsilon form of corresponding matrices.\nAnother example of applying \\fuchsia to find master integrals for next-to-leading order contributions to splitting functions in QCD were discussed in \\cite{GM16}.\n\n\\subsection{Usage from \\sage or \\python}\n\\label{sec:usage_py}\n\nYou can also use \\fuchsia as a library by starting the \\sage prompt and importing the \\texttt{fuchsia} module like this:\n\n\\begin{Verbatim}\n    \\prompt{$}{sage}\n    ┌────────────────────────────────────────────────────────────────────┐\n    │ SageMath Version 7.1, Release Date: 2016-03-20                     │\n    │ Type \"notebook()\" for the browser-based notebook interface.        │\n    │ Type \"help()\" for help.                                            │\n    └────────────────────────────────────────────────────────────────────┘\n    \\prompt{sage:}{from fuchsia import *}\n\\end{Verbatim}\n\nIn order to give an example for the API, let us try to reduce a simple matrix.\nFor the list of functions available after import, please, read the next section.\n\n\\begin{Verbatim}\n    \\prompt{sage:}{x, eps = var(\"x eps\")}\n    \\prompt{sage:}{M = matrix([}\n    \\prompt{....:}{  [(2-eps)/x, 0, 0],}\n    \\prompt{....:}{  [x/(x-1), eps/x, 0],}\n    \\prompt{....:}{  [(1+2*eps)/x**3, 0, (1+eps)/x/(x+1)]}\n    \\prompt{....:}{])}\n\\end{Verbatim}\n\nFirst, let us see where the singularities of this matrix are located:\n\n\\begin{Verbatim}[commandchars=\\\\!|]\n    \\prompt!sage:|!singularities(M, x)|\n    {-1: 0, 0: 2, 1: 0, +Infinity: 1}\n\\end{Verbatim}\n\nSo, 4 singularities in total, with the Poincar\\'e rank being 2 at $\\code{x}=0$, 1 at $\\code{x}=\\infty$ and 0 everywhere else.\nTo get rid of non-zero ranks (thus transforming the system into Fuchsian form) we will need to \\textit{fuchsify} this matrix as:\n\n\\begin{Verbatim}[commandchars=\\\\!|]\n    \\prompt!sage:|!Mf, Tf = fuchsify(M, x)|\n    \\prompt!sage:|!Mf|\n    [ -(eps - 2)/x           0                          0]\n    [   -1/(x - 1)  (eps -1)/x                          0]\n    [(2*eps + 1)/x           0  (eps + 2*x + 3)/(x^2 + x)]\n    \\prompt!sage:|!singularities(Mf, x)|\n    {-1: 0, 0: 0, 1: 0, +Infinity: 0}\n\\end{Verbatim}\n\nNow, let us take a look at the eigenvalues of \\code{Mf} residues:\n\n\\begin{Verbatim}\n    \\prompt{sage:}{[matrix_residue(Mf, x, x0).eigenvalues()}\n    \\prompt{....:}{  for x0 in [-1, 0, 1, Infinity]]}\n    [[-eps - 1, 0, 0],\n     [-eps + 2, eps - 1, eps + 3],\n     [0, 0, 0],\n     [-eps + 1, eps - 2, -2]]\n\\end{Verbatim}\n\nMany of these eigenvalues are not equal to zero in the limit $\\code{eps}\\to0$, so \\code{Mf} is not normalized.\nIt is, however, the case that all of the eigenvalues are of the form $n + m*\\code{eps}$, so there is a chance that we will be able to normalize \\code{Mf}.\nLet us try:\n\n\\begin{Verbatim}\n    \\prompt{sage:}{Mn, Tn = normalize(Mf, x, eps)}\n    \\prompt{sage:}{Mn}\n    [-eps/x                                                            ...\n    [(4*eps^3 - 8*eps^2 - (4*eps^2 - 6*eps + 3)*x + 5*eps)/((4*eps^3 - ...\n    [((2*eps + 1)*x + 3*eps + 1)/(x^2 + x)                             ...\n    \\prompt{sage:}{[matrix_residue(Mn, x, x0).eigenvalues()}\n    \\prompt{....:}{  for x0 in [-1, 0, 1, Infinity]]}\n    [[-eps, 0, 0],\n     [-eps, eps, eps],\n     [0, 0, 0],\n     [-eps, eps, 0]]\n\\end{Verbatim}\n\nSo, the matrix is normalized, but it grew quite a bit larger.\nThis happens.\nSometimes it is possible to simplify it a bit:\n\n\\begin{Verbatim}\n    \\prompt{sage:}{Ms, Ts = simplify_by_jordanification(Mn, x)}\n    \\prompt{sage:}{Ms}\n    [               -eps/x      0              0]\n    [            1/(x - 1)  eps/x              0]\n    [1/2*(eps + 1)/(x + 1)      0  eps/(x^2 + x)]\n\\end{Verbatim}\n\nThat is much better.\n\nFinally, we need to \\textit{factorize} \\code{Ms} to complete the reduction:\n\n\\begin{Verbatim}\n    \\prompt{sage:}{Mr, Tr = factorize(Ms, x, eps)}\n    \\prompt{sage:}{Mr}\n    [         -eps/x      0              0]\n    [1/4*eps/(x - 1)  eps/x              0]\n    [5/8*eps/(x + 1)      0  eps/(x^2 + x)]\n\\end{Verbatim}\n\nThis is the fully transformed matrix.\nAs you can see, it is both proportional to \\code{eps} and Fuchsian.\nTo make sure we got everything right, we can double-check the full transformation:\n\n\\begin{Verbatim}\n    \\prompt{sage:}{T = (Tf*Tn*Ts*Tr).simplify_rational()}\n    \\prompt{sage:}{(Mr - transform(M, x, T)).is_zero()}\n    True\n\\end{Verbatim}\n\nNote that we have used the construct \\code{(A - B).is\\_zero()} to compare matrices instead of the more obvious \\code{bool(A == B)}.\nThis is a \\sage idiosyncrasy; the more obvious way compares symbolic matrices only structurally.\n\nOf course, you do not need to walk through all these steps yourself every time.\nNormally, you just need to call this one function to do all the reduction work:\n\n\\begin{Verbatim}\n    \\prompt{sage:}{MM, TT = epsilon_form(M, x, eps)}\n    \\prompt{sage:}{MM}\n    [                          -eps/x      0              0]\n    [                 1/4*eps/(x - 1)  eps/x              0]\n    [1/4*(9*eps*x + 13*eps)/(x^2 + x)      0  eps/(x^2 + x)]\n    \\prompt{sage:}{(MM - transform(M, x, TT)).is_zero()}\n    True\n\\end{Verbatim}\n\nNotice that this matrix is slightly more complex than the one we have obtained step by step above.\nThis also happens.\nThe final form we are computing is not unique, and it will be different depending on the precise sequence of reduction steps you have taken.\n\nAdditionally, many of the transformations take a special $seed$ parameter to control the order of operations they perform internally.\nBy supplying different seeds, you will obtain different results as well.\n\n\\subsubsection{Function reference}\n\n\\begin{description}[style=nextline]\n\n\\functionitem{epsilon\\_form}{\\M M, x, epsilon, seed=0}\nFully reduces a system of equations defined by a matrix $\\M M$, an independent variable $x$, and an infinitesimal parameter $epsilon$.\nReturns a pair of values: the transformed matrix $\\M M'$ and the transformation matrix $\\M T$.\nRaises $FuchsiaError$, if the system is irreducible.\n\nThe reduction is performed by first converting $\\M M$ to block-triangular form, then reducing the diagonal blocks via $\\F{fuchsify}$, $\\F{normalize}$ and $\\F{factorize}$, reducing off-diagonal blocks as described in Section~\\ref{sec:blockreduce}, and finally factorizing $epsilon$ via $\\F{factorize}$.\n\n\\functionitem{fuchsify}{\\M M, x, seed=0}\nReduces a system defined by a matrix $\\M M$ and an independent variable $x$ to Fuchsian form.\nThat is, it makes sure that the Poincar\\'e ranks of all singularities of the transformed matrix $\\M M'$ are $0$.\nReturns a pair of values: the transformed matrix $\\M M'$ and the transformation $\\M T$.\nIf the system is irreducible, it raises $FuchsiaError$.\n\n\\functionitem{normalize}{\\M M, x, epsilon, seed=0}\nTransforms a Fuchsian system defined by a matrix $\\M M$, an independent variable $x$ and, an infinitesimal parameter $epsilon$ to a normalized form.\nThat is, it makes sure that real parts of the eigenvalues of all matrix residues of the transformed matrix $\\M M'$ lie in the range $[-1/2, 1/2)$ in the limit $epsilon\\to0$.\nReturns a pair of values: the transformed matrix $\\M M'$ and the transformation $\\M T$.\nIf such a transformation can not be found, it raises $FuchsiaError$.\n\n\\functionitem{factorize}{\\M M, x, epsilon, seed=0}\nTransforms a normalized system defined by a matrix $\\M M$, an independent variable $x$, and an infinitesimal parameter $epsilon$ so that the\ntransformed matrix $\\M M'$ is proportional to $epsilon$.\nReturns a pair of values: the transformed matrix $\\M M'$ and the transformation $\\M T$.\nIf such a transformation can not be found, it raises $FuchsiaError$.\n\n\\functionitem{block\\_triangular\\_form}{\\M M}\nTransforms a matrix $\\M M$ into a lower block-triangular form.\n\nReturns three values: a transformed matrix $\\M M'$, a transformation matrix $\\M T$, and a list of tuples $(m_i, n_i)$, where $n_i$ is the size of $i$-th diagonal block, and $m_i = \\sum_{j=1}^{i-1} n_j$.\nThe tuple list represents block structure of $\\M M'$; it is used by the next two functions, where it is passed as the argument $B$.\n\n\\functionitem{reduce\\_diagonal\\_blocks}{\\M M, x, epsilon, B=None, seed=0}\nFinds a transformation that reduces diagonal blocks of $\\M M$ into epsilon form.\nIf $B$ is not provided, it transforms $\\M M$ into lower triangual form before reduction.\nOtherwise it assumes $\\M M$ blocks are described by $B$.\n\nReturns two values: a transformed matrix $\\M M$ and a transformation matrix $\\M T$.\n\n\\functionitem{fuchsify\\_off\\_diagonal\\_blocks}{\\M M, x, epsilon, r=None}\nGiven a matrix $M$ with diagonal blocks in epsilon form, it transforms off-diagonal blocks in to Fuchsian form.\nIf $B$ is not provided, it transforms $\\M M$ into lower triangual form before reduction.\nOtherwise it assumes that blocks of $\\M M$ are described by $B$.\n\nReturns two values: a transformed matrix $\\M M$ and a transformation matrix $\\M T$.\n\n\\functionitem{simplify\\_by\\_jordanification}{\\M M, x}\nTries to simplify a system defined by a matrix $\\M M$ and an independent variable $x$ by constant transformations that transform leading expansion coefficients of $\\M M$ into their Jordan forms.\nReturns a pair of values: the simplified matrix $\\M M'$ and the transformation $\\M T$.\nIf none of the attempted transformations reduces the complexity of $\\M M$ (as measured by $\\F{matrix\\_complexity}$), it returns the original matrix and the identity transformation.\n\n\\functionitem{simplify\\_by\\_factorization}{\\M M, x}\nTries to simplify a system defined by a matrix $\\M M$ and an independent variable $x$ by a constant transformation that extracts common factors found in $\\M M$ (if any).\nReturns a pair of values: the simplified matrix $\\M M'$ and the transformation $\\M T$.\n\n\\functionitem{matrix\\_complexity}{\\M M}\nThis function is used as a measure of matrix complexity by $\\F{fuchsify}$ and simplification functions.\nCurrently it is defined as the length of textual representation of matrix $\\M M$.\n\n\\functionitem{balance}{\\M P, x_1, x_2, x}\nReturns a \\textit{balance} transformation between points $x=x_1$ and $x=x_2$ using the projector matrix $\\M P$.\nSee eq.~\\eqref{eq:bal} for the definition of a \\textit{balance}.\n\n\\functionitem{transform}{\\M M, x, \\M T}\nTransforms a system defined by a matrix $\\M M$ and an independent variable $x$ using the transformation matrix $\\M T$ as specified by eq.~\\eqref{eq:ta}.\nReturns the transformed matrix $\\M M'$.\n\n\\functionitem{balance\\_transform}{\\M M, \\M P, x_1, x_2, x}\nSame as $\\F{transform}(\\M M, x, \\F{balance}(\\M P, x_1, x_2, x))$, but implemented more efficiently: since the inverse of $\\F{balance}(\\M P, x_1, x_2, x)$ is $\\F{balance}(\\M P, x_2, x_1, x)$, this function can avoid a time-consuming matrix inversion operation that $\\F{transform}$ must perform.\n\n\\functionitem{singularities}{\\M M, x}\nFinds values of $x$ around which the matrix $\\M M$ has a singularity in $x$.\nReturns a dictionary with $\\{x_i: p_i\\}$ entries, where $p_i$ is the Poincar\\'e rank of $\\M M$ at $x=x_i$.\nThe set of singular points can include \\code{Infinity}, if $\\M M$ has a singularity at $x\\to\\infty$.\n\n\\functionitem{matrix\\_c0}{\\M M, x, x_0, p}\nReturns the 0-th coefficient of the series expansion of a matrix $\\M M$ around $x=x_0$, assuming the Poincar\\'e rank of $\\M M$ at that point is $p$.\nIf $x_0$ is \\code{Infinity}, it returns minus the coefficient at the highest power of $x$.\nIn other words, it returns $\\M A_{k0}$ from eq.~\\eqref{eq:axeps}.\n\n\\functionitem{matrix\\_c1}{\\M M, x, x_0, p}\nReturns the 1-th coefficient of the series expansion of a matrix $\\M M$ around $x=x_0$, assuming the Poincar\\'e rank of $\\M M$ at that point is $p$.\nIf $x_0$ is \\code{Infinity}, it returns minus the coefficient at the second-to-highest power of $x$.\nIn other words, it returns $\\M A_{k1}$ from eq.~\\eqref{eq:axeps}.\n\n\\functionitem{matrix\\_residue}{\\M M, x, x_0}\nReturns a residue of a matrix $\\M M$ at $x=x_0$, assuming that the Poincar\\'e rank of $\\M M$ at $x=x_0$ is $0$.\nReturns matrix residue at infinity if $x_0$ is \\code{Infinity}.\n\nThis is the same as $\\F{matrix\\_c0}(\\M M, x, x_0, 0)$.\n\n\\functionitem{export\\_matrix\\_to\\_file}{filename, \\M M, fmt=\\code{\"m\"}}\nWrites a matrix $\\M M$ to a file $filename$ using MatrixMarket array format if $fmt$ is \\code{\"mtx\"}, or Mathematica format if $fmt$ is \\code{\"m\"} (which is the default).\n\n\\functionitem{import\\_matrix\\_from\\_file}{filename}\nReads a symbolic matrix from a file $filename$.\nBoth Mathematica and MatrixMarket array formats are supported.\nThe exact format will be autodetected.\n\n\\functionitem{setup\\_fuchsia}{verbosity=0, use\\_maple=\\code{False}}\nModifies some of the \\fuchsia inner workings.\nIn particular, it sets $verbosity$ to $2$ to enable verbose logging, $1$ to enable normal logging, and $0$ to only log errors.\n\nSet $use\\_maple$ to \\code{True} to enable usage of \\texttt{Maple} to speed up calculations when possible; this may be particularly beneficial for big matrices, and for matrices with singularities at complex points.\n\n\\classitem{FuchsiaError}\nThis is the class of exceptions raised by the \\fuchsia routines.\nIt indicates the inability to perform the requested reduction. \n\n\\end{description}\n\n\n\\section{Summary}\n\\label{sec:4}\n\nIn this paper we have presented \\fuchsia, a program for reducing differential equations for Feynman master integrals to the epsilon form based on the Lee algorithm \\cite{Lee15} which consists of three main computational steps: fuchsification, normalization, and factorization.\n\\fuchsia is open-source in its nature and depends on free software tools only: the programming language \\python and the computer algebra system \\maximasage, which makes it available for everyone.\n\nUnfortunately in some cases \\fuchsia may exhibit poor performance: complex and/or irrational coefficients (or singular point locations) are particularly known to lead to a slowdown (or a complete halt) due to difficulty of working with those numbers symbolically.\nIn many such cases switching from \\maxima to \\maple will help, speeding up the calculations and preventing resource exhaustion, hence the access to latter is desirable.\nIn other cases, even \\maple is not powerful enough.\n\nDespite such limitation \\fuchsia shows great performance in many cases.\nIt is possible due to the optimization for block-triangular (or sparse) matrices, which allows to reduce relatively large matrices: the reduction of ${74\\times74}$ matrix with 20 rational and complex singular points and at most $3\\times3$ coupled blocks takes about an hour on a laptop with Intel i5 CPU.\n\n\\section*{Acknowledgment}\n\nWe are gratefully thankful for advanced examples of differential equations provided by Roman Lee and Costas Papadopolous.\nWe also appreciate useful suggestions from Sven Moch during writing of this paper.\n\nThis work has been supported by the Deutsche Forschungsgemeinschaft in Sonderforschungs\\-be\\-reich 676 {\\it Particles, Strings, and the Early Universe} and by the Narodowe Centrum Nauki with the Sonata Bis grant DEC-2013/10/E/ST2/00656.\n\n\n\n\n\\bibliography{fuchsia}\n\n\\end{document}\n", "meta": {"hexsha": "e7240d7938bc6c03237b8b92cc25c547fa07864b", "size": 41650, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/fuchsia.tex", "max_stars_repo_name": "fchapoton/fuchsia", "max_stars_repo_head_hexsha": "f3ce0d7d5d372311fc6681613d1fa71a7125b1ac", "max_stars_repo_licenses": ["ISC"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2016-09-28T14:50:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T20:24:34.000Z", "max_issues_repo_path": "doc/fuchsia.tex", "max_issues_repo_name": "fchapoton/fuchsia", "max_issues_repo_head_hexsha": "f3ce0d7d5d372311fc6681613d1fa71a7125b1ac", "max_issues_repo_licenses": ["ISC"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2016-02-18T12:45:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-15T13:53:02.000Z", "max_forks_repo_path": "doc/fuchsia.tex", "max_forks_repo_name": "gituliar/delirium", "max_forks_repo_head_hexsha": "19e16fdd736ad4731b087f372770a21bfc7093bf", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-08-28T05:21:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-25T10:24:00.000Z", "avg_line_length": 57.8472222222, "max_line_length": 468, "alphanum_fraction": 0.7071788715, "num_tokens": 11925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878414043816, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.31715154094717884}}
{"text": "%%\n%%  chapter07.tex - Obstacle Detection and Planning for Autonomous Vehicles based on Computer Vision Techniques\n%%\n%%  Copyright 2014 Néstor Morales <nestor@isaatc.ull.es>\n%%\n%%  This work is licensed under a Creative Commons Attribution 4.0 International License.\n%%\n\n\\graphicspath{{./images/chapter07/bmps/}{./images/chapter07/vects/}{./images/chapter07/}}\n\n\\chapter{Local Planning}\\label{ch:chapter07}\n\nBy using the methods described in previous chapters, the vehicle is able to detect the obstacles in the surrounding area, and knows how to reach a certain point in the map given its current position. Now we want the vehicle to drive by itself along a trajectory, avoiding the obstacles in the way.\nDespite the global path tell us the safest and shortest path to the goal, we can not use it to directly compute the commands the vehicle needs to start driving, as this global path does not model the long term unpredictability of the environment. Due to the presence of dynamic obstacles, this environment is constantly changing. So we need to follow the trajectory using an intermediate mechanism that introduces this short-term information.\n\n\\section{Method}\\label{ch:chapter07_01}\n\nThe way in which we solved this problem is based on the method described in \\cite{chu2012local} and also some ideas are taken from \\cite{thrun2006stanley}, modified in order to adapt it to our system requirements and the specific characteristics of Verdino. Other changes have been introduced with the aim of improving the behavior of the whole system. Based on these methods, we first transform the current euclidean coordinate system to a new system based on the Frenét space, which is computed as follows: we consider the global path  as the base frame of a curvilinear coordinate system, which will be the path generation space. The directional information of the path is included, so:\n\\begin{itemize}\n \\item The nearest point (where the distance is computed perpendicular to the global path) to the main trajectory will be the origin of the curvilinear coordinate system.\n \\item The horizontal axis will be represented by the distance over global path, in its direction.\n \\item The vertical axis is represented by the vector perpendicular to the origin point, which is pointing to the left respect to the path direction.\n\\end{itemize}\nWith this schema, we can compute easily the trajectories in the curvilinear space (that is, maneuvering information is generated). These are then transformed to the original euclidean space, in which the obstacles information is added by assigning costs to each path.\n\nInspired in \\cite{chu2012local}, we based our cost function in the path smoothness and in the cost of the collision with the obstacles (computed as a function of the distance). This cost is computed by blurring the binary map of the obstacles. For that, we use a exponential function relative to the distance to obstacles and the footprint of the car (See section \\ref{ch:chapter07_01_01}).\nWe also use length and path curvatures as cost functions. Distance to the center of the path is also used, based on the work of \\cite{thrun2006stanley}, so we can ensure that the car is able to return to the center of the trajectory. However, as explained in the previous section, our path calculation is different to adapt the costs to the environments in which Verdino will travel. Cost functions will be explained in more detail in section \\ref{ch:chapter07_01_04}. Both approaches \\citep{chu2012local, thrun2006stanley} use a base frame relative to the global path as tool for an easy and efficient computation of the paths.\n\nThe method, in which a big part of the Robotics Group from Universidad de La Laguna (GRULL) participated, has been successfully tested on Verdino. In section \\ref{ch:chapter07_02}, some experimental results are shown. Also, there are a set of videos showing the proper behavior of the vehicle in real situations, which can be seen at \\url{http://verdino.webs.ull.es/node/109}, \\url{http://verdino.webs.ull.es/node/103}, \\url{http://verdino.webs.ull.es/node/105}, and \\url{http://verdino.webs.ull.es/node/102}.\n\nThis method can be divided in five stages, shown at figure \\ref{fig:cp07_pipeline}.\n\\begin{enumerate}\n \\item \\emph{Generation of the costmap.} Using the information generated by the sensors or by the methods described in previous chapters, the system constructs a costmap in which costs are related to the distance to obstacles.\n \\item \\emph{Base frame construction.} Based on the global path constructed in the previous section (see \\ref{ch:chapter07_01_02}), we construct the base frame of the curvilinear coordinate system.\n \\item \\emph{Candidate paths generation.} Candidate paths are generated into the curvilinear space. Then, they are transformed to the euclidean space.\n \\item \\emph{Selection of the winner path.} Costs for all the paths are assigned, and that with the lowest value is selected.\n \\item \\emph{Computation of the vehicle commands.} Vehicle speed and steering angles are computed based on the characteristics of the winner path.\n\\end{enumerate}\n\n\\begin{figure*}[h!]\n        \\centering\n        \\includegraphics[width=\\textwidth]{pipeline}\n        \\caption{Pipeline of the method described on this chapter.}\\label{fig:cp07_pipeline}\n\\end{figure*}\n\n\\subsection{Generation of the costmap}\\label{ch:chapter07_01_01}\n\nThe costmap maintains information about occupied/free areas in the map in the form of an occupancy grid. It uses sensor data and information from the static map to store and update information about obstacles in the world, which are marked in the map (or cleared , if they are no longer there).\n\nEach cell in the map can have $255$ different cost values:\n\\begin{itemize}\n \\item A value of $255$ means that we do not have information about an specific cell in the map.\n \\item $254$ means that a sensor has marked this specific cell as occupied. This is considered as a lethal cell, so the vehicle should never enter there.\n \\item The rest of cells are considered as free, but with different cost levels depending on an inflation method relative to the size of the vehicle and its distance to the obstacle.\n\\end{itemize}\n\nCost values out from occupied cells decrease with distance using the following expression:\n\n\\begin{equation}\\label{eq:cp07_costmap_inflation}\n \\mathcal{C}(i, j) = \\exp (-1.0 \\cdot \\alpha \\cdot ( \\|c_{ij}-\\vec{o}\\| - \\rho_{inscribed})) \\cdot 253\n\\end{equation}\n\nIn this expression, which is the same we used in section \\ref{ch:chapter06_01_01_01} of chapter \\ref{ch:chapter06}, $\\alpha$ is a scaling factor that allows increasing or decreasing the decay rate of the cost of the obstacle. $\\|c_{ij}-\\vec{o}\\|$ is the distance between the cell $c_{ij} \\in \\mathcal{C}$ (where $\\mathcal{C}$ is the set of cells in the costmap) and the obstacle. Finally, $\\rho_{inscribed}$ is the inscribed radius, which is the inner circle of the limits of the car. This radius is depicted in the figure \\ref{fig:cp07_costmap_concepts}.\n\n\\begin{figure}[p]\n\\centering\n\\begin{tabular}{c}\n  \\begin{subfigure}[b]{\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{cost_levels}\n    \\caption{Cost levels.}\n    \\label{fig:cp07_cost_levels}\n  \\end{subfigure}\\\\ \n  \\begin{subfigure}[b]{\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{inscribed_circumscribed}\n    \\caption{$\\rho_{inscribed}$ and $\\rho_{circumscribed}$.}\n    \\label{fig:cp07_inscribed_circumscribed}\n  \\end{subfigure}\n\\end{tabular}\n\\caption{Costmap computation concepts.}\\label{fig:cp07_costmap_concepts}\n\\end{figure}\n\nDespite all of them are free cells, we define four different distance thresholds in order to set different danger levels in the map, depicted in figure \\ref{fig:cp07_costmap_concepts}:\n\n\\begin{itemize}\n \\item $\\tau_{lethal}$: There is an obstacle in this cell, so the vehicle is in collision. It is represented by the cost level $254$.\n \\item $\\tau_{inscribed}$: Cell distance to the nearest obstacle is below $\\rho_{inscribed}$. If the center of the vehicle is in this cell, it is also in collision, so areas below this distance threshold should be avoided. Cost level is always $253$.\n \\item $\\tau_{circumscribed}$: If the vehicle center is on this cell, it is very likely that the car collided with an obstacle, depending on its orientation. A cell with a distance to an obstacle below this threshold should be avoided, but there are still chances of being in one of them without colliding an obstacle. \n \\item The rest of cells are assumed to be safe (except from those with \\emph{unknown} cost, for which we do not know if they are occupied or not, so we think on them as if they were lethal).\n\\end{itemize}\n\nIn our approach, we just consider those paths passing through cells with a cost below $\\tau_{circumscribed}$, which is obtained obtained using the equation \\ref{eq:cp07_costmap_inflation} and other cost factors that will be explained later. Paths passing trough the cells over this threshold will be truncated at the last safe point.\n\nFor optimization reasons, we do not compute the costmap for the whole map at each iteration. Instead, we just compute the cells in a $40 \\times 40\\,m$ area centered into the current car position. \n\nFor the computation of the costmap and of the costs associated to each cell, we used the \\ROS plugin \\program{costmap\\_2d}\\footnote{\\url{http://wiki.ros.org/costmap\\_2d}}, which implements the functionalities described in this section.\n\n\\subsection{Base frame construction}\\label{ch:chapter07_01_02}\n\nIn this stage, we will define the base frame of the curvilinear coordinate system, so the algorithm will be able to compute the trajectories in this space as if the global plan were a rectilinear trajectory. At this point, we will not care about the presence of obstacles or the restrictions associated to the vehicle's motion model, since we will focus in the generation of trajectories. The geometric relationship between the path in euclidean and curvilinear coordinates is shown at figure \\ref{fig:cp07_euclidean_frenet_conversion}.\n\nBefore the construction of the base frame, we must find the point we want to use as origin of coordinates. For this purpose, we iterate over the points of the trajectory until we reach the point which is the nearest to the current position of the vehicle. This will be the origin of coordinates of the base frame. If the trajectory is valid (that is, it is different from zero), we can start with the base frame construction.\n\n\\begin{figure}[h!]\n\\centering\n\\begin{tabular}{cc}\n  \\begin{subfigure}[b]{0.45\\textwidth}\n      \\centering\n      \\includegraphics[width=\\textwidth, trim=50 30 80 60,clip]{justOneCartesian45}\n      \\caption{Euclidean space.}\n      \\label{fig:cp07_justOneCartesian45}\n  \\end{subfigure} &\n  \\begin{subfigure}[b]{0.45\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth, trim=50 30 80 60,clip]{justOneFrenet45}\n    \\caption{Curvilinear space.}\n    \\label{fig:cp07_justOneFrenet45}\n  \\end{subfigure}%   \n\\end{tabular}\n\\caption{Conversion of a trajectory between the Cartesian and Frenét spaces.}\\label{fig:cp07_euclidean_frenet_conversion}\n\\end{figure}\n\nBase frame's arc length ($s$, on the right image) is obtained as the distance of each point along the global plan (represented as a green line) to the origin of coordinates. This distance is represented in the \\emph{x-axis} of the curvilinear system. \\emph{y-axis}, $q$, represents the perpendicular lateral distance respect to the path. Left side is represented by positive values and the right by the negatives.\n\nFor the computation of the transformation between the euclidean and the curvilinear coordinate system, we need to compute path curvature $\\kappa$. This value is computed as follows \\citep{chu2012local, werling2010optimal, barfoot2004motion}:\n\n\\begin{equation}\\label{eq:cp07_path_curvature}\n \\kappa = {S \\over Q} \\cdot \\left ( \\kappa_b \\cdot { \n {(1 - q \\cdot \\kappa_b) \\cdot (\\partial^2q / \\partial s^2) +\n \\kappa_b \\cdot (\\partial q / \\partial s )^2\n } \n \\over {Q^2} } \\right )\n\\end{equation}\n\n,where \n\n\\begin{equation}\\label{eq:cp07_path_curvature_s_and_q}\n\\begin{cases}\nS=sign(1 - q \\cdot \\kappa_b)\\\\\nQ=\\sqrt{\\left ( { {\\partial q} \\over {\\partial s}} \\right ) ^2+ (1 - q \\cdot \\kappa_b)^2}\n\\end{cases}\n\\end{equation}\n\nA generated path will be rejected if $q > {1 \\over \\kappa_b}$. In this case, the generated path curvature and sense is opposed to that of the base frame. The path violates the non-holonomic condition of the movement of the vehicle, so it is discarded.\n\nWe are just able to accept paths in which the lateral offset $q$ is similar or smaller to the curvature radius of the base frame $1 / \\kappa_b$. If $q = 1 / \\kappa_b$, that means that the path passes through the center of curvature of the base frame. Also, the maximal curvature a path can have in order to be feasible by the vehicle is limited by the maximal steering angle. If this restriction is violated, the corresponding path is rejected. Curvature is directly related to the movement of the vehicle, which can be described through several models. A simplified version  \\citep{chu2012local, barfoot2004motion}, which ignores the related physical effects (like inertia or mass), is:\n\n\\begin{equation}\\label{eq:cp07_simplified_motion_model}\n\\begin{cases}\n\\dot{x} = |\\vec{v}| \\cdot cos(\\theta) \\\\\n\\dot{y} = |\\vec{v}| \\cdot sin(\\theta) \\\\\n\\dot{\\theta} = |\\vec{v}| \\cdot \\kappa\n\\end{cases}\n\\end{equation}\n\nAs these physical effects do not affect to the geometric shape of the path, we can ignore them in the path generation step. At this point, we are neither considering other physical restrictions like the maximal curvature that the vehicle is able to follow or the maximal speed, since it will be done in the next steps. In equation \\ref{eq:cp07_simplified_motion_model}, $[\\dot{x} ~ \\dot{y} ~ \\dot{\\theta} ]^T$ are the estimated position and orientation of the vehicle and $|\\vec{v}|$ is speed magnitude. Considering this simplified model, we assume that the vehicle just have two degrees of freedom, represented by the speed $\\vec{v}$ and $\\kappa$. As we are just interested into the geometric generation of the path, it is possible to remove the speed of the vehicle $\\vec{v}$ from the model. This is done by expressing the movement of the vehicle in terms of the traveled distance. So the following relation is established \\citep{chu2012local}:\n\n\\begin{equation}\\label{eq:cp07_speed_to_distance}\n|\\vec{v}| = S \\cdot Q \\cdot { {\\partial s} \\over {\\partial t}}\n\\end{equation}\n\nIf the speed of the vehicle is substituted into the model described in equation \\ref{eq:cp07_simplified_motion_model}, the differential equation of the movement can be represented in terms of the base frame's arc length $s$:\n\n\\begin{equation}\\label{eq:cp07_motion_model_in_distance_terms}\n\\begin{cases}\n{{\\partial x} \\over {\\partial s}} = Q \\cdot cos(\\theta) \\\\\n{{\\partial y} \\over {\\partial s}} = Q \\cdot sin(\\theta) \\\\\n{{\\partial \\theta} \\over {\\partial s}} = Q \\cdot \\kappa\n\\end{cases}\n\\end{equation}\n\n\\subsection{Candidate paths generation}\\label{ch:chapter07_01_03}\n\nAs seen, path generation is performed in the curvilinear space, without considering the obstacles in the environment. These will be taken into account later, once the tentative trajectories are transformed to the euclidean space.\n\n\\subsubsection{Maneuvering paths generation}\\label{ch:chapter07_01_03_01}\n\nThe curvature of the generated paths is defined by the lateral offset $q$ respect to the base frame. First and second order derivatives of $q$ are needed if we want to compute $\\kappa$ (see equations \\ref{eq:cp07_path_curvature} and \\ref{eq:cp07_path_curvature_s_and_q}), so we need a function dependent on the lateral offset if we want to compute a smooth lateral change.\n\n$q$ can be defined by a sequence of a cubic polynomial and a set of constants \\citep{chu2012local}:\n\n\\begin{equation}\\label{eq:cp07_function_q}\n\\begin{align*}\nq(s) &=\n  \\begin{cases}\n   a \\cdot \\Delta s^3 + b \\cdot \\Delta s^2 + c \\cdot \\Delta s + q_i & \\text{if } s_i \\le s < s_f \\\\\n   q_f        & \\text{if } s_f \\le s\n  \\end{cases}\\\\\n{{\\partial q} \\over {\\partial s}}(s) &=\n  \\begin{cases}\n   3 \\cdot a \\cdot \\Delta s^2 + 2 \\cdot b \\cdot \\Delta s + c & ~~~~~~~\\text{if } s_i \\le s < s_f \\\\\n   0        & ~~~~~~~\\text{if } s_f \\le s\n  \\end{cases}\\\\\n{{\\partial^2 q} \\over {\\partial s^2}}(s) &=\n  \\begin{cases}\n   6 \\cdot a \\cdot \\Delta s + 2 \\cdot b & ~~~~~~~~~~~~~~~~~~~~~~~\\text{if } s_i \\le s < s_f \\\\\n   0        & ~~~~~~~~~~~~~~~~~~~~~~~\\text{if } s_f \\le s\n  \\end{cases}\n\\end{align*}\n\\end{equation}\n\n, where $\\Delta s = s - s_i$.\n\nIn figure \\ref{fig:cp07_justOneFrenet45}, the components involved in this process are depicted.\n\\begin{itemize}\n \\item The initial lenght $s_i$ is zero, due to the process performed at the beginning of each iteration (section \\ref{ch:chapter07_01_02}). Lateral offset $q_i$ is also known, which is the lateral offset respect to the global path's origin.\n \\item Angle $\\theta$ defines the difference between the vehicle heading angle and the tangent angle of the base frame at the current position.\n \\item $s_f$ is a parameter that allows controlling the longitudinal distance needed to reach the offset $q_f$. This distance should be dependent from the speed. However, as the maximal speed of the prototype is not too hight, we can think on $\\Delta s_f$ as the distance needed to go from $q_i$ to the biggest $q_f$ at the maximal speed.\n \\item The different $q_f$ are computed separately for each path attending to the parameters defined by the user. $s_f$ is also a free parameter.\n\\end{itemize}\n\nParameters $s_i$, $q_i$, and $s_f$ are shared by all candidate paths. By modifying the value of $q_f$ we get different tentative trajectories, so the only difference between all them is the lateral offset we want to reach at the end of paths. This lateral offset will give us flexibility in the way in which we avoid obstacles. To do that, we divide the width of the road into as many segments as paths are desired. $q_f$ will be the perpendicular distance between the base frame and the corresponding road width division. Using this technique, the desired number of paths is created. The set of paths should cover the whole road width, ensuring the vehicle is able to avoid the obstacles, if it is possible.\n\nIn our tests, we have considered a maximal width of 4\\,m (a little bit above the width of the roads in our testing area), and an horizon of 10\\,m in the direction of the global path. This horizon gives us a prediction of 2\\,seconds at the maximal speed of the vehicle. We evaluate a total of 21 paths, with a distance between them ($\\Delta q_f$) of 20\\,cm.\n\n\\subsubsection{Candidate paths generation}\\label{ch:chapter07_01_03_02}\n\nOnce we have computed the paths in the curvilinear coordinate system, we transform them so we can work in the euclidean space. In this new space, we will be able to evaluate their associated costs, as those related to the distance to obstacles, smoothness, etc. In figures \\ref{fig:cp07_frenet0} and \\ref{fig:cp07_frenet45}, we can see two examples of this process.\n\nIn figure \\ref{fig:cp07_frenet0}, an example in which the vehicle is at a lateral distance of 1\\,m respect to the base frame, and there is no difference in the orientation of the vehicle regarding to this base frame is shown. That is, $q_i = 1$, $s_i = 0$ and $\\theta = 0$. In the left image, we see that the set of paths is symmetric, being the central path completely parallel to the axis $s$. These trajectories are then projected to the euclidean space, obtaining the paths represented in the right image. There, green line represents the global path, and blue lines are the projected candidate paths. As shown, they fit properly to the global path.\n\n\\begin{figure}[h!]\n\\centering\n\\begin{tabular}{cc}\n  \\begin{subfigure}[b]{0.45\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth, trim=50 40 80 60,clip]{frenet0}\n    \\caption{Curvilinear space.}\n    \\label{fig:cp07_frenet_space0}\n  \\end{subfigure} &\n  \\begin{subfigure}[b]{0.45\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth, trim=50 40 80 60,clip]{cartesian0}\n    \\caption{Euclidean space.}\n    \\label{fig:cp07_cartesian0}\n  \\end{subfigure}%\n\\end{tabular}\n\\caption{Example in which the vehicle is oriented parallel to the path.}\\label{fig:cp07_frenet0}\n\\end{figure}\n\nIn figure \\ref{fig:cp07_frenet45}, a similar example is shown. The only difference is that, this time, the vehicle is oriented $45^\\circ$ away from the base frame orientation. This causes the paths in the curvilinear space to move away from the $s$ axis until they start converging. As shown, same effect occurs in the transformed euclidean paths: they move away from the global path but, after a few meters, they start approaching to it.\n\n\\begin{figure}[h!]\n\\centering\n\\begin{tabular}{cc}\n  \\begin{subfigure}[b]{0.45\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth, trim=50 40 80 60,clip]{frenet45}\n    \\caption{Curvilinear space.}\n    \\label{fig:cp07_frenet_space45}\n  \\end{subfigure} &\n  \\begin{subfigure}[b]{0.45\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth, trim=50 40 80 60,clip]{cartesian45}\n    \\caption{Euclidean space.}\n    \\label{fig:cp07_cartesian45}\n    \\end{subfigure}\n\\end{tabular}\n\\caption{Example in which the vehicle is rotated with respect to the path.}\\label{fig:cp07_frenet45}\n\\end{figure}\n\nNow the paths are in euclidean coordinates, we can evaluate which is the maximal distance they can reach individually if obstacles are considered. To do that, we iterate over the points in the trajectory, and check the cost associated to each cell $c_{ij}$ containing the point in the costmap computed in section \\ref{ch:chapter07_01_01}. If this cost is over the value associated to the threshold $\\tau_{circumscribed}$, the path is truncated at this point, as shown in figure \\ref{fig:cp07_path_truncation}, where the generated paths are shown together with a colored costmap representation. There, blue means a low value, while the red color is used for the higher costs. Yellow and cyan correspond to cells in lethal and inscribed cells, respectively. The points iterated before reaching this cost will be kept, but it is very unlikely that this will be the winner path, as the occlusion cost will be maximal, and the length of the path shorter (see section \\ref{ch:chapter07_01_04}). \nAs shown, when a path collides with an obstacle, we do not remove the path completely. The reason for that is that there are certain situations in which we can not reach the maximal distance with none of the paths. However, we still want to approach slowly towards the maximal reachable point, with the hope that the obstacles that are blocking the way will disappear in the next iterations. In crowded areas with many pedestrians this is a typical situation: the way is blocked, but when pedestrians see a vehicle that is approaching, they move away. However, if the vehicle reaches a point in which it can not move for a long time, we generate a new trajectory and try to go through a different way.\nThe problem with this strategy is that one of the colliding paths could win even if there is a path able to go through a clear area. In order to avoid that, we have implemented a weighted cost functions based schema, explained in the next section, that allows a smart selection of the winner path.\n\n\\begin{figure}[h!]\n\\centering\n\\includegraphics{example15}\n\\caption{Paths truncation example.}\\label{fig:cp07_path_truncation}\n\\end{figure}\n\n\\subsection{Selection of the winner path}\\label{ch:chapter07_01_04}\n\nThe winner path is selected through the use of a linear combination $J[i]$ of weighted cost functions, related to the following parameters: occlusion, length, distance to the global path, curvature and consistency of the path. $J[i]$ is evaluated as follows:\n\n\\begin{equation}\\label{eq:cp07_cost_function}\nJ[i] = \\omega_o C_o[i] + \\omega_l C_l[i] + \\omega_d C_d[i] + \\omega_{\\kappa} C_{\\kappa}[i] + \\omega_c C_c[i]\n\\end{equation}\n\nHere, $i$ is the path index, and $C_o$, $C_l$, $C_d$, $C_{\\kappa}$ and $C_c$ are the costs of occlusion, length, distance to the global path, curvature and consistency, respectively. Their relatives $\\omega_k$, $k \\in \\{o, l, d, \\kappa, c\\}$ are the associate weights that allow to adjust the influence of each of the costs to the final cost value. All these costs are normalized to $1.0$, and \n\n\\begin{equation}\\label{eq:cp07_weights_sum}\n\\sum_{{i \\in \\{o, l, d, \\kappa, c\\}}} w_i= 1.0\n\\end{equation}\n\n, so it is easy to determine the proportional influence of each weight. Based on this, the value of $J[i]$ will be always inside the interval $[0\\dots1]$.\n\nThe following costs will be computed for each candidate path independently from the euclidean space.\n\n\\paragraph{Occlusion}\\label{ch:chapter07_01_04_00_01}\n\nThe occlusion cost is related to the safety of the path. This cost estimates the goodness of a path, being the bests paths those that pass far enough from the obstacles. To do that, we iterate along the path, simulating the footprint of the car at each position. The occlusion cost corresponding to the trajectory point $i$ will be the maximal cost of each of the cells $c_{ij} \\in \\mathcal{C}$ under the footprint of the car at that position. Based on this, the occlusion cost will be\n\n\\begin{equation}\\label{eq:cp07_occlusion_cost}\nC_o = {{max\\{c_i\\}} \\over 255}, ~~~~~~ i=1 \\dots L\n\\end{equation}\n\nIn this expression, $L$ is the length of the current path being evaluated. $max\\{c_i\\}$ is the maximal value of all the costs, associated to a point in the path. As we saw in section \\ref{ch:chapter07_01_01}, the maximal value of each cost is $255$, so we divide the cost by this value, in order to normalize it to $1$.\n\n\\paragraph{Length}\\label{ch:chapter07_01_04_00_02}\n\nThis cost represents the length of the current path. By iterating along the points in the path, we accumulate the distance between them, so we know the real distance traveled in euclidean coordinates. The longer that a path is, the better, as we assume that it means that paths are able to travel a longer distance. However, we are want to minimize the costs, so we must invert the length of each path in the way that longer paths give us smaller values. This is done through the expression:\n\n\\begin{equation}\\label{eq:cp07_length_cost}\nC_l = 1- {{\\sum\\limits_{i=1}^{L}\\|p_i - p_{i - 1}\\|} \\over {q_{f_{max}} + s_f}}\n\\end{equation}\n\nHere, $p_i$ is a certain point inside the evaluated path. $q_{f_{max}}$ is the maximal value that a $q_f$ can have for a certain path. Lengths are normalized to a value that a path will never reach. In our case, we decided that the sum of the maximal expected offset for $s$ and for $q$ is good enough (lengths will never trespass this value, while being small enough to allow an easy discrimination between paths). We subtract this cost from $1.0$, in order to make it comparable to the rest of costs (as said, lower values are preferred respect to the higher ones).\n\n\\paragraph{Distance to the global path}\\label{ch:chapter07_01_04_00_03}\n\nIn our implementation, we included information about the average lateral offset respect to the global path. The use of this cost will benefit the choice of those paths that allow coming back to the global path after an occasional obstacle is avoided. It is computed as follows:\n\n\\begin{equation}\\label{eq:cp07_lateral_cost}\nC_d = {{\\sum\\limits_{i=1}^{L}\\|p_i - nearest(p_i, g)\\|} \\over {L \\cdot q_{f_{max}}}}\n\\end{equation}\n\n, where $nearest(p, g)$ is the nearest point in the global path $g$ to the point $p$. This cost is normalized with respect to the maximal expected offset, $q_{f_{max}}$.\n\n\\paragraph{Curvature}\\label{ch:chapter07_01_04_00_04}\n\nThis cost allows giving priority to the smoother paths. Let $p(x_i, y_i), ~ i=1\\cdots L$, be a point in the path. Then, \n\n\\begin{equation}\\label{eq:cp07_curvature_cost}\nC_{\\kappa} = max \\left \\{ {{x_i' \\cdot y_i'' - x_i'' \\cdot y_i'} \\over {(x_i' + y_i')^{3/2}}} \\right \\}, ~~~~~~ i=1 \\dots L\n\\end{equation}\n\n\\paragraph{Consistency}\\label{ch:chapter07_01_04_00_05}\n\nThis cost avoids the continuous changes in the winner paths between iterations. Once the vehicle starts a maneuver, the idea is keeping this behavior in the following iterations.\n\nThis is done through the following expression:\n\n\\begin{equation}\\label{eq:cp07_consistency_cost}\nC_c = {1 \\over {s_2 - s_1}} \\int \\limits_{s_1}^{s_2} l_i ~ ds\n\\end{equation}\n\nThis equation is better understood if we look at figure \\ref{fig:cp07_consistency_cost}. There, the lateral cost $l_i(s)$ is the distance between the current and the previous winner path at the same longitudinal position $s$; $s_1$ and $s_2$ are the first and last positions over $s$ for which there are points in common in both trajectories.\n\n\\begin{figure}[h!]\n  \\centering\n  \\includegraphics[width=\\textwidth]{consistency_cost}\n  \\caption{Representation of the way in which the consistency cost is computed.}\\label{fig:cp07_consistency_cost}\n\\end{figure}\n\n\\subsubsection{Selection of the winner path}\\label{ch:chapter07_01_04_01}\n\nOnce all costs are computed, we just apply the expression described in equation \\ref{eq:cp07_cost_function}. In those paths for which it is impossible to advance due to the presence of a nearby obstacle because the car is bad oriented to the global path (meaning that no valid paths can be generated in this situation), the cost will be negative (invalid path).\n\nFrom all paths, we select that with the smallest cost (winner path $W$). If for any reason there are not valid paths, the vehicle is stopped until the road is clear. If this situation does not change for a while, a new global plan is computed, so the vehicle is able to reach the goal using a different way.\n\nIf no valid paths are found because the vehicle has a bad orientation respect to the global plan, a recovery behavior process is started.\n\n\\subsection{Computation of the vehicle commands}\\label{ch:chapter07_01_05}\n\nThe last step required in order to follow the trajectory obtained from the global planner is the computation of the steering angle and speed commands that will be sent to the built-in controller of the vehicle. The way in which this is done is quite simple. Over the winner path, we apply a \\ac{PID} controller in which we try to minimize the distance and heading of the vehicle respect to that trajectory. Using this controller and a model of the vehicle, we can compute the proper values, which are finally sent to the vehicle.\n\n\\subsection{Recovery behavior}\\label{ch:chapter07_01_06}\n\nWhen the lateral offset of a path is bigger than the radius of curvature of the base frame, paths can not be generated using the approach described before. Because of that, we propose to compute the paths in a different way, so the vehicle can advance towards the global plan until this restriction is satisfied again. The way in which we do that is through the use of a model of the behavior of the vehicle. This model is the same Ackerman model used in \\cite{espelosin2013path}.\n\nFour paths are evolved in a parameterized time $t$, considering a low speed. Two of these paths are generated considering a positive speed (forward movement) and the top left and top right steering position, and the other two are similar, but using a negative speed. All these four paths are weighted following the same process described in in \\ref{ch:chapter07_01_04}, and the winner is selected. Resulting speed and steering commands for the recovery behavior process will be those used to evolve the winner path.\n\n% \\section{Putting all together}\\label{ch:chapter08_08}\n% \\comment{No tengo muy claro si esto debería ir aquí o en las conclusiones}\n% \n% Using the methods described in this thesis, we are now able to detect the obstacles existing in the environment and track them along the frames. Also, we are able to generate trajectories that can be followed by our vehicle in order to reach a certain point, and we know how to compute the commands that the vehicle need to follow these trajectories. Now it is time to put everything together.\n% \n% In the images shown at figure \\ref{fig:cp07_whole_pipeline}, we can see an integration of some of the methods described in this thesis. These images have been extracted from the videos available at \\url{http://youtu.be/08mAOD6bT9w} (for the Stixels based example); and \\url{http://youtu.be/SCQ6_GYjbJs} and \\url{http://youtu.be/rn4iIafBFZc} (for the Particle Filter based one). In these methods, we have included the obstacles detected using the methods described in chapters \\ref{ch:chapter04} and \\ref{ch:chapter05}, which are incorporated to the costmap described in section \\ref{ch:chapter07_01_01}. Unfortunately, at this time the described implementation of the costmap do not accept temporal information, so we just can include the detected obstacles, but not the information about their future movement that could be obtained thanks to the tracks detected. Also, as we said before, the global planner described in section \\ref{ch:chapter06} was discarded as it is not longer needed in this form, but we think on it as a solution for the fast generation of \\acp{RNDF}.\n% \n% \\begin{figure*}[h!]\n%   \\begin{subfigure}[b]{\\textwidth}\n%     \\centering\n%     \\includegraphics[width=\\textwidth, height=0.75\\textwidth]{stixels_whole_pipeline}\n%     \\caption{Integration of the whole pipeline of the application, including the stixel based method, described in chapter \\ref{ch:chapter04}.}\\label{fig:cp07_stixels_whole_pipeline}\n%   \\end{subfigure}\n%   ~\n%   \\begin{subfigure}[b]{\\textwidth}\n%     \\centering\n%     \\includegraphics[width=\\textwidth, height=0.75\\textwidth]{particle_filter_whole_pipeline}\n%     \\caption{Integration of the whole pipeline of the application, including the particle filter based method, described in chapter \\ref{ch:chapter05}.}\\label{fig:cp07_particle_filter_whole_pipeline}\n%   \\end{subfigure}\n%   \\caption{Integration of the full pipeline of the application described in this thesis. Frames have been extracted from the videos available at \\url{http://youtu.be/08mAOD6bT9w}, \\url{http://youtu.be/SCQ6_GYjbJs} and \\url{http://youtu.be/rn4iIafBFZc}.}\\label{fig:cp07_whole_pipeline}\n% \\end{figure*}\n% \n% Anyway, the integration of the method with the planner described in this chapter is quite good. We can see in both images that the planner reacts properly to the objects detected and that, given a pair images, both methods are able to detect the obstacles, allowing a safe trip. In general, both methods are suitable for the evaluated scenarios, being the most limiting features those inherent to the methods, which were described in chapters \\ref{ch:chapter04} and \\ref{ch:chapter05}.\n\n\\section{Summary}\\label{ch:chapter07_07}\n\nIn this chapter, we have seen a method able to efficiently follow a given trajectory, while avoiding the potential obstacles in the way. The use of a curvilinear coordinate system for the generation of a set of candidate trajectories simplifies the calculations while allows creating soft paths that makes the vehicle to converge to the followed track in a way as smooth as possible. Moreover, these paths are generated with different lateral offsets regarding to the global plan, so we are able to avoid an obstacle even if it is in the middle of the path. Finally, as speed is out of the model used for the generation of the tracks, this generation step is reduced to the computation of a set of parameters that define a third order polynomial. Speed and steering angle are then computed, using a \\ac{PID} controller over the winner path, which is chosen based on a cost function.\n\nThere are some videos in which the good behavior of this method is available, as those in \\url{http://verdino.webs.ull.es/node/109}, \\url{http://verdino.webs.ull.es/node/103}, \\url{http://verdino.webs.ull.es/node/105} and \\url{http://verdino.webs.ull.es/node/102}. Also, the videos available at \\url{http://youtu.be/08mAOD6bT9w}, \\url{http://youtu.be/rn4iIafBFZc} and \\url{http://youtu.be/SCQ6_GYjbJs}, show how the integration of the method with the algorithm described in chapters \\ref{ch:chapter04} and \\ref{ch:chapter05} is possible (This process is better explained at section \\ref{ch:chapter08_08}).\n\nAs future work, we can study the inclusion of new cost functions in order to improve the choice of the right path or long-term control strategies, as those used in \\cite{werling2010optimal}. Furthermore, the computation of the steering angle based on the winner path could be improved through the use of a predictive controller.\n\nIn the next chapter, we will see the results obtained for all the methods described until now, which will give us a clear idea of their performance, and the advantages and disadvantages of using such methods.\n\n\n", "meta": {"hexsha": "7a9c7be7ad0197c762478d6fc121a95e20a74739", "size": 36826, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapter07.tex", "max_stars_repo_name": "nestormh/thesis", "max_stars_repo_head_hexsha": "7e1d9c79d6cb456d98bb156ff2750ed70b179db2", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-11-21T08:28:23.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-21T08:28:23.000Z", "max_issues_repo_path": "chapter07.tex", "max_issues_repo_name": "nestormh/thesis", "max_issues_repo_head_hexsha": "7e1d9c79d6cb456d98bb156ff2750ed70b179db2", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter07.tex", "max_forks_repo_name": "nestormh/thesis", "max_forks_repo_head_hexsha": "7e1d9c79d6cb456d98bb156ff2750ed70b179db2", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 92.065, "max_line_length": 1077, "alphanum_fraction": 0.7680443165, "num_tokens": 9369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3171349663348993}}
{"text": "\\XtoCBlock{DT1}\r\n\\label{block:DT1}\r\n\\begin{figure}[H]\\includegraphics{DT1}\\end{figure} \r\n\r\n\\begin{XtoCtabular}{Inports}\r\nIn & Input In(k)\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n\r\n\\begin{XtoCtabular}{Outports}\r\nOut & Output Out(k)\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n\\begin{XtoCtabular}{Mask Parameters}\r\nV & Gain\\tabularnewline\r\n\\hline\r\nfc & Cut off frequency of low pass filter\\tabularnewline\r\n\\hline\r\nts\\_fact & Multiplication factor of base sampling time (in integer format)\\tabularnewline\r\n\\hline\r\nmethod & Discretization method\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n\\subsubsection*{Description:}\r\nFirst order high pass:\n\n    G(s) = V*s/(s/w + 1)\r\n\n% include optional documentation file\r\n\\InputIfFileExists{\\XcHomePath/Library/Control/Doc/DT1_Info.tex}{\\vspace{1ex}}{}\r\n\r\n\\subsubsection*{Implementations:}\r\n\\begin{tabular}{l l}\r\n\\textbf{FiP8} & 8 Bit Fixed Point Implementation\\tabularnewline\r\n\\textbf{FiP16} & 16 Bit Fixed Point Implementation\\tabularnewline\r\n\\textbf{FiP32} & 32 Bit Fixed Point Implementation\\tabularnewline\r\n\\textbf{Float32} & 32 Bit Floating Point Implementation\\tabularnewline\r\n\\textbf{Float64} & 64 Bit Floating Point Implementation\\tabularnewline\r\n\\end{tabular}\r\n\r\n\\XtoCImplementation{FiP8}\r\n\\index{Block ID!3328}\r\n\\nopagebreak[0]\r\n% Implementation details\r\n\\begin{tabular}{l l}\r\n\\textbf{Name} & FiP8 \\tabularnewline\r\n\\textbf{ID} & 3328 \\tabularnewline\r\n\\textbf{Revision} & 0.1 \\tabularnewline\r\n\\textbf{C filename} & DT1\\_FiP8.c \\tabularnewline\r\n\\textbf{H filename} & DT1\\_FiP8.h \\tabularnewline\r\n\\end{tabular}\r\n\\vspace{1ex}\r\n\r\n8 Bit Fixed Point Implementation\r\n\r\n\\begin{XtoCtabular}{Controller Parameters}\r\nb0 & \\tabularnewline\r\n\\hline\r\nb1 & \\tabularnewline\r\n\\hline\r\na0 & \\tabularnewline\r\n\\hline\r\nsfrb & \\tabularnewline\r\n\\hline\r\nsfra & \\tabularnewline\r\n\\hline\r\nin\\_old & In(k-1)\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n% Implementation data structure\r\n\\XtoCDataStruct{Data Structure:}\r\n\\begin{lstlisting}\r\ntypedef struct {\r\n     uint16        ID;\r\n     int8          *In;\r\n     int8          Out;\r\n     int8          b0;\r\n     int8          b1;\r\n     int8          a0;\r\n     int8          sfrb;\r\n     int8          sfra;\r\n     int8          in_old;\r\n} DT1_FIP8;\r\n\\end{lstlisting}\r\n\r\n\\ifdefined \\AddTestReports\r\n\\InputIfFileExists{\\XcHomePath/Library/Control/Doc/Test_DT1_FiP8.tex}{}{}\r\n\\fi\r\n\\XtoCImplementation{FiP16}\r\n\\index{Block ID!3329}\r\n\\nopagebreak[0]\r\n% Implementation details\r\n\\begin{tabular}{l l}\r\n\\textbf{Name} & FiP16 \\tabularnewline\r\n\\textbf{ID} & 3329 \\tabularnewline\r\n\\textbf{Revision} & 0.1 \\tabularnewline\r\n\\textbf{C filename} & DT1\\_FiP16.c \\tabularnewline\r\n\\textbf{H filename} & DT1\\_FiP16.h \\tabularnewline\r\n\\end{tabular}\r\n\\vspace{1ex}\r\n\r\n16 Bit Fixed Point Implementation\r\n\r\n\\begin{XtoCtabular}{Controller Parameters}\r\nb0 & \\tabularnewline\r\n\\hline\r\nb1 & \\tabularnewline\r\n\\hline\r\na0 & \\tabularnewline\r\n\\hline\r\nsfrb & \\tabularnewline\r\n\\hline\r\nsfra & \\tabularnewline\r\n\\hline\r\nin\\_old & In(k-1)\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n% Implementation data structure\r\n\\XtoCDataStruct{Data Structure:}\r\n\\begin{lstlisting}\r\ntypedef struct {\r\n     uint16        ID;\r\n     int16         *In;\r\n     int16         Out;\r\n     int16         b0;\r\n     int16         b1;\r\n     int16         a0;\r\n     int8          sfrb;\r\n     int8          sfra;\r\n     int16         in_old;\r\n} DT1_FIP16;\r\n\\end{lstlisting}\r\n\r\n\\ifdefined \\AddTestReports\r\n\\InputIfFileExists{\\XcHomePath/Library/Control/Doc/Test_DT1_FiP16.tex}{}{}\r\n\\fi\r\n\\XtoCImplementation{FiP32}\r\n\\index{Block ID!3330}\r\n\\nopagebreak[0]\r\n% Implementation details\r\n\\begin{tabular}{l l}\r\n\\textbf{Name} & FiP32 \\tabularnewline\r\n\\textbf{ID} & 3330 \\tabularnewline\r\n\\textbf{Revision} & 0.1 \\tabularnewline\r\n\\textbf{C filename} & DT1\\_FiP32.c \\tabularnewline\r\n\\textbf{H filename} & DT1\\_FiP32.h \\tabularnewline\r\n\\end{tabular}\r\n\\vspace{1ex}\r\n\r\n32 Bit Fixed Point Implementation\r\n\r\n\\begin{XtoCtabular}{Controller Parameters}\r\nb0 & \\tabularnewline\r\n\\hline\r\nb1 & \\tabularnewline\r\n\\hline\r\na0 & \\tabularnewline\r\n\\hline\r\nsfrb & \\tabularnewline\r\n\\hline\r\nsfra & \\tabularnewline\r\n\\hline\r\nin\\_old & In(k-1)\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n% Implementation data structure\r\n\\XtoCDataStruct{Data Structure:}\r\n\\begin{lstlisting}\r\ntypedef struct {\r\n     uint16        ID;\r\n     int32         *In;\r\n     int32         Out;\r\n     int32         b0;\r\n     int32         b1;\r\n     int32         a0;\r\n     int8          sfrb;\r\n     int8          sfra;\r\n     int32         in_old;\r\n} DT1_FIP32;\r\n\\end{lstlisting}\r\n\r\n\\ifdefined \\AddTestReports\r\n\\InputIfFileExists{\\XcHomePath/Library/Control/Doc/Test_DT1_FiP32.tex}{}{}\r\n\\fi\r\n\\XtoCImplementation{Float32}\r\n\\index{Block ID!3331}\r\n\\nopagebreak[0]\r\n% Implementation details\r\n\\begin{tabular}{l l}\r\n\\textbf{Name} & Float32 \\tabularnewline\r\n\\textbf{ID} & 3331 \\tabularnewline\r\n\\textbf{Revision} & 0.1 \\tabularnewline\r\n\\textbf{C filename} & DT1\\_Float32.c \\tabularnewline\r\n\\textbf{H filename} & DT1\\_Float32.h \\tabularnewline\r\n\\end{tabular}\r\n\\vspace{1ex}\r\n\r\n32 Bit Floating Point Implementation\r\n\r\n\\begin{XtoCtabular}{Controller Parameters}\r\nb0 & Coefficient b0\\tabularnewline\r\n\\hline\r\nb1 & Coefficient b1\\tabularnewline\r\n\\hline\r\na0 & Coefficient a0\\tabularnewline\r\n\\hline\r\nin\\_old & In(k-1)\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n% Implementation data structure\r\n\\XtoCDataStruct{Data Structure:}\r\n\\begin{lstlisting}\r\ntypedef struct {\r\n     uint16        ID;\r\n     float32       *In;\r\n     float32       Out;\r\n     float32       b0;\r\n     float32       b1;\r\n     float32       a0;\r\n     float32       in_old;\r\n} DT1_FLOAT32;\r\n\\end{lstlisting}\r\n\r\n\\ifdefined \\AddTestReports\r\n\\InputIfFileExists{\\XcHomePath/Library/Control/Doc/Test_DT1_Float32.tex}{}{}\r\n\\fi\r\n\\XtoCImplementation{Float64}\r\n\\index{Block ID!3332}\r\n\\nopagebreak[0]\r\n% Implementation details\r\n\\begin{tabular}{l l}\r\n\\textbf{Name} & Float64 \\tabularnewline\r\n\\textbf{ID} & 3332 \\tabularnewline\r\n\\textbf{Revision} & 0.1 \\tabularnewline\r\n\\textbf{C filename} & DT1\\_Float64.c \\tabularnewline\r\n\\textbf{H filename} & DT1\\_Float64.h \\tabularnewline\r\n\\end{tabular}\r\n\\vspace{1ex}\r\n\r\n64 Bit Floating Point Implementation\r\n\r\n\\begin{XtoCtabular}{Controller Parameters}\r\nb0 & Coefficient b0\\tabularnewline\r\n\\hline\r\nb1 & Coefficient b1\\tabularnewline\r\n\\hline\r\na0 & Coefficient a0\\tabularnewline\r\n\\hline\r\nin\\_old & In(k-1)\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n% Implementation data structure\r\n\\XtoCDataStruct{Data Structure:}\r\n\\begin{lstlisting}\r\ntypedef struct {\r\n     uint16        ID;\r\n     float64       *In;\r\n     float64       Out;\r\n     float64       b0;\r\n     float64       b1;\r\n     float64       a0;\r\n     float64       in_old;\r\n} DT1_FLOAT64;\r\n\\end{lstlisting}\r\n\r\n\\ifdefined \\AddTestReports\r\n\\InputIfFileExists{\\XcHomePath/Library/Control/Doc/Test_DT1_Float64.tex}{}{}\r\n\\fi\r\n", "meta": {"hexsha": "34b3adb6bbc0a530f0a2cb5464d9fa56f0d19b3c", "size": 6785, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Library/Control/Doc/DT1.tex", "max_stars_repo_name": "AlexisTM/X2C", "max_stars_repo_head_hexsha": "31f39b598afe271a7fd46ef1ee9e06c410b1120c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Library/Control/Doc/DT1.tex", "max_issues_repo_name": "AlexisTM/X2C", "max_issues_repo_head_hexsha": "31f39b598afe271a7fd46ef1ee9e06c410b1120c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Library/Control/Doc/DT1.tex", "max_forks_repo_name": "AlexisTM/X2C", "max_forks_repo_head_hexsha": "31f39b598afe271a7fd46ef1ee9e06c410b1120c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4945848375, "max_line_length": 90, "alphanum_fraction": 0.6843036109, "num_tokens": 2200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665855647394, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.31713495863519126}}
{"text": "\\documentclass[12pt]{article}\n\\usepackage{graphics}\n\\newcounter{problem}\n\\newcommand{\\kg}{\\mathrm{kg}}\n\\newcommand{\\m}{\\mathrm{m}}\n\\newcommand{\\s}{\\mathrm{s}}\n\\newcommand{\\mps}{\\m\\,\\s^{-1}}\n\\newcommand{\\hp}{\\mathrm{hp}}\n\\begin{document}\n\\thispagestyle{empty}\n\n\\section*{NYU Physics 1---Problem set 7}\n\nDue Tuesday 2009 November 3 at the beginning of lecture.\n\n\\paragraph{Problem~\\theproblem:}\\refstepcounter{problem}%\nA Japanese Shinkansen (bullet train) (of mass $M=10^6~\\mathrm{kg}$),\nmoving at $v_S=300~\\mathrm{km\\,h^{-1}}$ with respect to the tracks,\nhits and collides elastically with a superball (of mass\n$m=30~\\mathrm{g}$), which is initially at rest.  The front face of the\ntrain is inclined at an angle of $\\theta=45~\\mathrm{deg}$ to the\nhorizontal, as shown here in the rest frame of the tracks.\\\\\n\\rule{0.1\\textwidth}{0pt}\n\\resizebox{0.8\\textwidth}{!}{\\includegraphics{../mp/shinkansen.eps}}\n\n\\textsl{(a)}~Draw a diagram of the ball--train system, just before the\ncollision, in the center-of-mass rest frame.  Clearly show the\nvelocities of the ball and train in this frame.\n\n\\textsl{(b)}~Draw a diagram, just after the collision, in the\ncenter-of-mass frame.  Clearly show the velocities.\n\n\\textsl{(c)}~Draw a diagram, just after, back in the rest frame of the\ntracks.  What is the final speed and direction of the ball,\nimmediately after the collision, in the rest frame of the tracks?\n\n\\paragraph{Problem~\\theproblem:}\\refstepcounter{problem}%\nWhat is the peak force between two pool balls in a pool shot?\nEstimate the momentum transferred to the object ball in a hard pool\nshot.  Estimate (or look up) masses and velocities.  For how long are\ntwo pool balls in contact?  The time can be approximated by the length\nof time it takes a sound wave to cross a pool ball.  Put it all\ntogether and compare it to the force of gravity or the normal force\nfrom the table on each ball.\n\n\\paragraph{Problem~\\theproblem:}\\refstepcounter{problem}%\n\\textsl{(a)}~Imagine an ideal car of mass $1000\\,\\kg$ with a\ncross-sectional area $A=3\\,\\m^2$, drag coefficient $1$ (so the\nair-resistance force is exactly $(1/2)\\,\\rho\\,A\\,v^2$) producing total\nmechanical power of $P=130\\,\\hp$.  At time $t=0$, the car is traveling\nat $5\\,\\mps$ in the $x$ direction.  Use a spreadsheet to compute the\nvelocity as a function of time if the driver puts ``petal to the\nmetal'' for the next $20\\,\\s$ (with a $0.1\\,\\s$ time-step) on a flat,\nstraight, $x$-direction road.  You will have to use the fact that the\nforce accelerating the car is the power over the velocity (why?) but\nsubtracting off the air resistance force.  Make a plot of the velocity\nof the car as a function of time, with axes clearly labeled.  Note\nthat this is only a ``first-order'' integration: You only need to keep\ntrack of the velocity, not the position.\n\n\\textsl{(b)}~Why did I not have you start at a velocity of $0\\,\\mps$?\nWhat would limit the acceleration in the first fraction of a second in\nthis case---for a car starting from rest?  It isn't the power of the\nengine!\n\n\\end{document}\n", "meta": {"hexsha": "ef34f4e55879aa091ebf6d083c20ff60021271de", "size": 3043, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/old/ps07.tex", "max_stars_repo_name": "davidwhogg/Physics1", "max_stars_repo_head_hexsha": "6723ce2a5088f17b13d3cd6b64c24f67b70e3bda", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-11-13T03:48:56.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-13T03:48:56.000Z", "max_issues_repo_path": "tex/old/ps07.tex", "max_issues_repo_name": "davidwhogg/Physics1", "max_issues_repo_head_hexsha": "6723ce2a5088f17b13d3cd6b64c24f67b70e3bda", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2016-10-07T19:48:57.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-29T22:47:25.000Z", "max_forks_repo_path": "tex/old/ps07.tex", "max_forks_repo_name": "davidwhogg/Physics1", "max_forks_repo_head_hexsha": "6723ce2a5088f17b13d3cd6b64c24f67b70e3bda", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.4179104478, "max_line_length": 70, "alphanum_fraction": 0.7390732829, "num_tokens": 891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984137988773, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.3171349575469965}}
{"text": "\\subsection{Value Alignment} \\label{sec:value_alignment}\nAIAs operate autonomously in delegated tasks, with the expectation that they behave according to users' intent frames. \nOptimization-based algorithms are arguably among the most common and direct approaches for accomplishing this. \nThe general idea is to define a \\emph{utility function} that normatively governs the AIA's abilities so that desirable behaviors are elicited through maximization of the utility, i.e. such that the AIA behaves rationally in accordance with the user's intent frame. \nA utility function describes the `long-term desirability' of taking certain actions in certain conditions, i.e. beyond immediate benefits or penalties, and should coherently reflect user preferences about the state of the world and AIA behaviors ~\\cite{Russell2010-wv}. \nSuch mapping of user intent frames to utility functions has two positive benefits. \nFirstly, it ensures that AIA behaviors can themselves be used as assurances: users will tend to trust AIA's more if they are `well-behaved' and acting in accordance with their desired intent than if they are not. \nSecondly, an AIA can generate assurances via auxiliary behaviors that help ensure its utility function is aligned with the user's intent frame.  Since it is practically quite challenging to encode user preferences and intent frames into utility functions, the process of \\emph{value alignment}\\footnote{Value alignment is more commonly known as `AI Alignment' in AI research~\\cite{Yudkowsky2001-hb,Bensinger2014-ul}.} leads to many different algorithmic strategies for generating assurances. \n\nConsider a generic decision-making problem where an AIA that must make choice $a \\in {\\mathcal A}$ given some task state $s \\in {\\mathcal S}$, with scalar utility function $U_A(a,s)$. %and possible sets of actions and states ${\\mathcal A}$ and ${\\mathcal S}$. \nIf a user's true utility is represented by scalar function $U_H(a,s)$, then in the ideal situation the AIA seeks the optimal decision $a^* \\in {\\mathcal A}$ such that, for any $s \\in {\\mathcal S}$,\n\\begin{align*}\n    a* = \\arg\\max_{\\mathcal A} U_A(a,s) = \\arg \\max_{\\mathcal A} U_H(a,s). \n\\end{align*}\nHence, value alignment tries to minimize the difference between the utilities of the AIA and the user. When the utility of the robot $U_A(a,s)$ and the human $U_H(a,s)$ are approximately equivalent (within some tolerance) then the values of the AIA are \\emph{aligned} with those of the human. An AIA with aligned values will be considered by users to be more predictable (and thus more competent), because the AIA will be more likely to act in desirable ways. \n% \n\\citet{Bostrom2014-fz} provides a well-known example of an AIA whose value is \\emph{not} aligned: an autonomous robot is designed, and deployed, with the intent that it make paper clips. To maximize $U_A(s,a)$, the robot then decides to take over the world in order to maximize its resources and ability to make more paper clips. To reasonable human users, this was clearly \\emph{not} the intended behavior; the utilities that the robot used for making decisions did not match those that the human must have had. Therefore the robot's resulting behavior was intrinsically an assurance that reduced trust. On the other hand, if the robot were to try to learn from its mistakes and improve (i.e. make $U_A(s,a)$ closer to $U_h(s,a)$) that could be perceived as an assurance that increases trust---the robot can be `forgiven' for making honest mistakes in trying to optimize an ill-posed/under-specified utility function, as long as it is able to recognize and remedy this. \n\n\\subsubsection{Common Approaches:}\nThere are two algorithmic strategies for value alignment: (i) indirect: approximate $U_H(a,s)$ explicitly via $U_A(a,s)$, and then use this approximation to find $a^*$; (ii) direct: identify $a^* = \\arg \\max U_H(a,s)$ directly via the use of optimal state-action value functions $Q^*(s,a)$ (which give the utility to be gained if the AIA were to proceed optimally starting from $s$, regardless of its past states or actions). \nThese strategies closely resemble techniques used for reinforcement learning problems and their variants (especially inverse reinforcement learning); not surprisingly, most value alignment techniques are rooted in this domain. \nValue alignment research tends to focus on several different issues \\cite{Gordon_Worley2018-xy,Amodei2016-xi}; some of the more directly applicable topics and associated methods that point to useful assurance strategies are described below. \nThe solutions to these problems are assurances because they afford opportunities for  users to better understand the actual intentions and goals of the AIA, as well as understand how the AIA actually interprets intent frames. \n\n\\paragraph{Reward Hacking and Human-Guided Learning}\nThe reward hacking problem deals with avoiding and removing unintended consequences in AIA behaviors that arise from imperfections in the specification of $U_A(s,a)$ (as in the paper clip-making robot example above). \nThe most popular solution strategies use some form of offline supervisory human guidance or training data feedback in the utility function learning process. \nThis approach recognizes the intrinsic difficulty of mapping user preferences to a single scalar utility $U_H(s,a)$ for complex tasks, and leverages sophisticated machine learning and reasoning strategies to identify relevant preferences within $U_A(s,a)$ or $Q^*(s,a)$, depending on the kinds of tasks considered. For instance, one-shot/non-sequential decision-making tasks like image recognition or object perception do not necessarily have dynamical state considerations, but may require potential expansion of the action space for sensible labeling of new object categories. \n\nIn the context of sequential decision making problems, \\citet{Hadfield-Menell2017-tl}, \\citet{Hadfield-Menell2016-ws}, and \\citet{Huang2017-lk} all consider variations of the `inverse reward design' problem using inverse reinforcement learning techniques. In these works, discounted cumulative rewards are used to model utility functions $U_A(s,a)$ and $U_H(s,a)$, where the actual reward factors contributing to $U_H(s,a)$ are unknown but can be inferred from user-generated contextual information at design time. Specifically, \\cite{Hadfield-Menell2017-tl} notes that reward factors provided by users in limited training contexts serve as `noisy evidence of intent'. Hence, to avoid situations where an AIA trainee demonstrates desirable behaviors in specific training scenarios but later demonstrates undesirable behaviors in novel scenarios, the AIA must be able to reason over the uncertainty in the user's intent in order to fully capture the context in which it was trained. \nIn a different task setting, \\citet{Freitas2006-qo} compared two approaches to discovering `interesting' knowledge from large data sets, based on the idea that human users require assistance from complex systems in order to find useful patterns and other interesting insights. He mentions `user-driven' methods that involve a user suggesting interesting templates or providing general impressions in the form of IF-THEN rules. A subsequent comparison to different `data-driven' methods suggests that the latter are not very effective in practice. \nHaving said that, user-driven approaches may not fare any better when compared over many users, as each user will likely have different preferences. Other scaled up user-driven approaches, e.g. based on crowd-sourcing~\\citet{Chang2017-kl}, can also achieve better accuracy for labeling tasks while also exploring new or ambiguous classes that can be ignored with traditional approaches (especially if training data sets are biased or very limited). \\citet{Chang2017-kl} also consider a similar, scaled up, `user-driven' approach called `Revolt' that crowd-sources the labeling of images. It is able to attain high accuracy labeling, while also exploring new or ambiguous classes that might be ignored with traditional approaches. \n\nSome other methods for designing, learning and eliciting appropriate utility functions are also discussed in \\cite{Hadfield-Menell2016-ws,Da_Veiga2012-gh,Garcia2015-rs}.\nDespite the differences in AIA application contexts, these methods all provide the user with better context for what \\emph{should} be known by system, and for how well it can interpolate/extrapolate. \nThese processes allow users to refine their own intent in complex settings, e.g. to reveal or resolve subtle low-level inconsistencies in desired task requirements that would otherwise lead a rational AIA to undesirable behaviors. \n\n\\paragraph{Safe learning and correct-by-construction synthesis:}\nIn many applications, $U_H(s,a)$ must be safely approximated when certain combinations of $(s,a)$ lead to irreversibly bad consequences. \nHence, as AIAs try to learn what a user's utility is, they must do so in a safe manner. \nFor instance, humans do not learn about the dangers of heights from falling off of skyscrapers. \nInstead we have to do so cautiously over time, and extrapolate from much less drastic experience (i.e. tripping on a curb). \nSafe reinforcement learning (safe RL) methods offer formal strategies and assurances for AIAs to learn in similar ways.\nSafe RL has been defined as the process of avoiding ``unintended and harmful behavior that [emerges] from machine learning systems''~\\cite{Amodei2016-xi}. Two ways to approach safe RL are: (i) modification of the optimality criterion with a safety factor, and (ii) modification of the exploration process through the incorporation of external knowledge~\\cite{Garcia2015-rs}. \n\nFor example, \\citet{Lipton2016-dq} design an `intrinsic fear' RL approach that uses a deep Q-network and a `supervised danger model'. The danger model stores the likelihood of entering a catastrophe state within a `short number of steps'. This model can be learned by detecting catastrophes through experience and can be improved over time. \\citet{Curran2016-ij}, in a more specific application, asks how a robot can learn when a task is too risky, and then avoid those situations, or ask for help. \nSimilarly, \\citet{Kahn2017-vy} use Bayesian Deep Neural Nets (using bootstrapping and dropout) to learn about the probability (with uncertainty) of an autonomous vehicle colliding in an environment given its current state, observations, and sequence of controls. Using this model they formulate a `velocity-dependent collision cost' that is used for model-based reinforcement learning. With this approach the vehicle naturally proceeds slowly when there is an elevated risk of collision. This `safety-aware' behavior provides an assurance signal to the user. \n\nAside from purely learning-based approaches, we can also consider Validation and Verification (V\\&V) methods. \nNot all practitioners are aware that V\\&V techniques can generate soft assurances for users. \nThis is because V\\&V typically refers to the use of formal methods to guarantee the behavior of a system within some set of specifications, which are handed down by a certification authority as requirements to system designers to generate `hard assurances' (formal proofs of the functionality of the system). \nAlthough these `hard assurances' are not primarily designed for user consumption, they could in principle be exposed to and interpreted for users in certain contexts. \nA prime example is given by \\citet{Raman2013-mz}, who developed a formal way for non-expert users to provide structured natural language task specifications to a robot, such that a `correct-by-construction' controller will be built if the specification is valid. \nOtherwise, the robot will provide an explanation about which specification(s) are unrealizable/inconsistent and will cause failure. \nIn the context of a practical self-driving car application, \\citet{Ghosh2016-dl} presents a framework called Trusted Machine Learning (TML) for learning models from dynamically generated data that fit pre-determined `trustworthiness' constraints. \nThese approaches are promising in that they not only present a way to communicate when and why specified tasks cannot be performed or certain actions cannot be taken, but also provide positive assurances in the form of guaranteed, formally verified, AIA processes for performing desired tasks (plans, models, etc.). \nWhile this directly addresses the competence and predictability components of AIA trust, the `raw' expression of these assurances does not formally account for effects on user trust or TRBs in formulating explanations. \n\n\\paragraph{Robustness to context shifts}\nHow can an AIA determine when the basis and provenance of its approximation to $U_H(s,a)$ or $Q^*(s,a)$ is no longer valid for a particular task? \nThis problem has attracted much recent attention in the learning literature under the guise of `nonstationary' learning. \nNonstationarity refers to the complex challenge of training a model based on data from one distribution $D$ while taking into account that the test distribution $D^\\prime$ will likely shift through time~\\cite{Quinonero-Candela2009-fj}. \nFor instance, in the context of classification problems, \\citet{Sugiyama2013-ci} propose using importance sampling Monte Carlo to formally detect events related to `covariate shift' (training and test input data follow different distributions) and `class-balance change' (where the class-prior probabilities are different in training and test phases, but where there is no covariate shift). \nSimilarly, \\citet{Charikar2017-kr} address learning from `untrusted' data, which could be subject to adversarial attack or unknown nonstationarity. \n\nThese methods can be more generally adapted and developed beyond learning tasks, in order to evaluate the sensitivity of as-designed AIA's capabilities to possible changes in task context not captured/considered at design time (an example of coping with `unknown unknowns').  \nIf the sensitivities imply a significant deviation in $U_A(s,a)$ or $a^*$ from expected values (i.e. from user intent frame as initially understood), or indicate the presence of new $(s,a)$ pairs that are not accounted for by $U(s,a)$ (e.g. test data that is very far from the training set), then the AIA can inform the user accordingly and thus possibly opt out of performing tasks that are now potentially `out of scope'. This provides direct low-level behavioral assurances about changes in predictability, competence, and situation normality, though these may not be immediately understood by non-expert users. \n\n\\subsubsection{Grounding Example:}\nIn the case of the `VIP Escort' problem (described in Section~\\ref{sec:mot_example}), value alignment might be used as an assurance in the following way, starting with the assumptions that:\n\n\\begin{itemize}\n    \\item The UGV has just begun an attempt to escape the road-network\n    \\item The UGV uses safe RL to learn its escape policy\n    \\item The operator is able to observe the UGV during its entire escape attempt\n\\end{itemize}\n\nThe operator has used several different UGVs for similar tasks. This newer model uses `safe RL' to learn its policy. When observing the UGV's attempt at escape the operator notices a difference in how the UGV operates. Whereas the older UGV models would sometimes do risky things, this UGV seems to navigate dangerous situations much better. \n\n\\paragraph{\\textbf{Discussion of Example:}} In this case, safe RL enabled the UGV to treat situations that an operator might classify as `dangerous' with more care. With this integral capability the UGV assures the operator that it is more competent.\n", "meta": {"hexsha": "b385dfdecce07266ae28da936efa83fa6e486c5b", "size": 15640, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "value_alignment.tex", "max_stars_repo_name": "bisraelsen/OnAssurances", "max_stars_repo_head_hexsha": "4411dda583ba35cb688105c274f40d329548ec94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "value_alignment.tex", "max_issues_repo_name": "bisraelsen/OnAssurances", "max_issues_repo_head_hexsha": "4411dda583ba35cb688105c274f40d329548ec94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "value_alignment.tex", "max_forks_repo_name": "bisraelsen/OnAssurances", "max_forks_repo_head_hexsha": "4411dda583ba35cb688105c274f40d329548ec94", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 193.0864197531, "max_line_length": 982, "alphanum_fraction": 0.8021099744, "num_tokens": 3376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.4921881357207955, "lm_q1q2_score": 0.3170799541460572}}
{"text": "\\documentclass{article}\n\\usepackage{fullpage}\n\\usepackage{amsmath}\n\\usepackage{graphicx}\n\\usepackage{natbib}\n\n\n% \\DeclareMathOperator{\\Sample}{Sample}\n\\let\\vaccent=\\v % rename builtin command \\v{} to \\vaccent{}\n\\renewcommand{\\v}[1]{\\ensuremath{\\mathbf{#1}}} % for vectors\n%\\renewcommand{\\v}[1]{\\ensuremath{\\mbox{\\boldmath$ #1 $}}}\n\\newcommand{\\gv}[1]{\\ensuremath{\\mbox{\\boldmath$ #1 $}}}\n% for vectors of Greek letters\n\\newcommand{\\uv}[1]{\\hat{\\ensuremath{\\mathbf{ #1 }}}} % for unit vector\n\\newcommand{\\abs}[1]{\\left| #1 \\right|} % for absolute value\n\\newcommand{\\avg}[1]{\\left< #1 \\right>} % for average\n\\let\\underdot=\\d % rename builtin command \\d{} to \\underdot{}\n\\renewcommand{\\d}[2]{\\frac{d #1}{d #2}} % for derivatives\n\\newcommand{\\dd}[2]{\\frac{d^2 #1}{d #2^2}} % for double derivatives\n\\newcommand{\\pd}[2]{\\frac{\\partial #1}{\\partial #2}}\n% for partial derivatives\n\\newcommand{\\pp}[2]{\\frac{\\partial^2 #1}{\\partial #2^2}}\n% for double partial derivatives\n\\newcommand{\\grad}[1]{\\v{\\nabla} #1} % for gradient\n\\let\\divsymb=\\div % rename builtin command \\div to \\divsymb\n\\renewcommand{\\div}[1]{\\v{\\nabla} \\cdot #1} % for divergence\n\\newcommand{\\curl}[1]{\\v{\\nabla} \\times #1} % for curl\n\n\n\n\\title{A Fully Lagrangian Dynamical Core for the Met Office NERC Cloud Model}\n\\author{G. Gibb, S. Boeing, D. Dritschel}\n\n\n\\begin{document}\n\\maketitle\n\\abstract{We describe the technical work carried out in the eCSE project `A fully Lagrangian Dynamical Core for the Met Office NERC Cloud Model', whose aim is to incorporate the `Moist Parcel in Cell` (MPIC) code into the Met Office NERC Cloud Model (MONC), thereby granting it MPI parallelism and the ability to scaly beyond a single node. First we describe the modifications to MONC in order for it to be parcel-aware, then we outline the implementation of MPIC's physics into MONC. We then provide an in-depth comparison of MPIC with the newly developed code, and investigate how it scales to many thousands of MPI processes. Finally we discuss the limitations of the code, and future work to be carried out to mitigate these limitations. We found that the code can scale up to many thousands of cores for large problem sizes, although the main limiter of performance at scale are the Fourier Transform routines. Despite good MPI performance from the code, OpenMP performance is poor, achieving a speedup of only 3 on 12 threads. Overall, on a single node the new code performs better than MPIC does, carrying out more parcel operations per core per second. Crucially, the work carried out in this project allows considerably larger problem sizes to be simulated than was possible with the original implementation of MPIC.}\n%\\tableofcontents\n\n\n\n\\section{Introduction}\n\nThis report documents the technical work carried out in the eCSE project entitled `A fully Lagrangian dynamical core for the Met Office NERC Cloud Model'. The aim of this project was to implement the functionality of the `Moist parcel in cell' code developed by \\citet{Dritschel2018} into the `Met Office NERC Cloud Model' \\citep{Brown2015}. In this section we will describe the two aforementioned codes and the original proposed work. In the following section (Section \\ref{development}) we will describe the development work carried out. We then describe scaling tests and comparisons with the original code in Section \\ref{performance}. Finally, we summarise the outputs from the project and discuss future work in Section \\ref{discussion}.\n\n\\subsection{Moist Parcel in Cell}\n\nThe `Moist Parcel in Cell' code (hereby MPIC) is a Lagrangian fluid dynamics code which models moist convection and cloud development. It achieves this by representing the fluid as a large number of `moist parcels' containing various properties such as buoyancy, vorticity and humidity. Whilst the code is Lagrangian, a gridded approach is used in order to solve for the parcel velocity and vorticity tendency. This is achieved by trilinearly interpolating the parcel properties onto grids, solving for the velocity and vorticity tendency on these grids, then trlinearly interpolating these gridded values back onto the parcels. The parcel-based approach has many benefits over a purely grid-based approach, such as allowing for explicit sub-grid representation, a velocity field that is undamped by numerical diffusion down to the grid scale and it is exactly conservative. The approach also allows for a natural description of mixing, whereby parcels can split into two and merge together.\n\nMPIC is written in Fortran and is parallelised using OpenMP. This imposes a limitation on both the scalability of the code (due to it being limited to only a small number of cores), and more crucially on the number of parcels (and thus indirectly the grid resolution) that can be used due to the memory limitations of a single node. MPIC at present uses dimensionless (normalised) units. MPIC evolves the parcels via a fourth-order Runge Kutta integrator (RK4). Figure \\ref{flowchart} shows a flowchart for the basic structure of MPIC.\n\n\n\\subsection{Met Office NERC Cloud Model}\n\nThe `Met Office NERC Cloud Model' (hereby MONC) is an Eulerian fluid dynamics code that simulates cloud microphysics. MONC was designed to supersede the older Met Office Large Eddy Model (LEM), which did not scale beyond 512 cores. As such it can be regarded as a complete re-write of the LEM. It was designed to be easy to modify and implement new functionality into. It employs a ``plug-in'' architecture whereby it consists of a number of independent `components' which can be selected and run in a specific order at runtime. Components can be switched on/off to add/remove functionality, or swapped out with other components to provide - for example - different solvers. This allows for a highly customisable code that is easy to develop new functionalty for.\n\nMONC is organised into three different parts, the \\emph{Model Core}, the \\emph{Model State} and the \\emph{Components}. The Model Core consists of the core functionality of MONC, including how it handles components, reading in configuration files, and functions/subroutines common to all components (e.g. haloswapping). The Model State contains the data describing the state of the simulation, such as the grids, as well as various other variables such as the time, timestep and other runtime-specific quantities. The components, which are called once per timestep in a user-defined order, perform actions on the data contained within the Model State. MONC is parallelised using MPI, and scales up to 32,768 cores. It is spatially decomposed in the $x$ and $y$ directions. Unlike MPIC, it uses an Eulerian integrator to evolve its Model State.\n\nMONC also has an \\emph{I/O server} which permits real-time in-situ analysis of the simulation data. This works by having a number of processes set aside (typically one per node) for analytics and I/O. The compute processes periodically asynchronously send data to the I/O Servers, which then perform any necessary reduction operations on the data and write the results to disk. This setup allows the compute processes to concentrate on carrying out the simulation work, whilst the I/O servers can take on the burden of analysis and I/O. Figure \\ref{flowchart} shows a flowchart for the basic struture of MONC.\n\n\\begin{figure}\n  \\begin{center}\n    \\includegraphics[scale=0.9]{pmpic_images/flowchart.pdf}\n  \\end{center}\n  \\caption{Flowcharts showing the structure of MPIC (left) and MONC (right).}\n  \\label{flowchart}\n\\end{figure}\n\n\\subsection{Proposed Technical Work}\nThe proposed work was to incorporate the parcel-based MPIC into MONC, producing a so called `Parallel Moist Parcel in Cell' (PMPIC) code, which scales beyond one node, permitting larger simulations to be carried out than are possible with MPIC. Incorporating MPIC into MONC is beneficial as MONC's layout makes it easy to implement new functionality into, and much of its functionality can be used with minimal modifications to permit the MPI parallelisation of MPIC.\nThis also broadens the scope of MONC as it adds Lagrangian functionality, complimenting its existing Eulerian functionality.\n\nThe proposed work was split into four Work Packages:\n\\begin{itemize}\n  \\item WP1: MONC Model Extensions\\\\\n  Modify the Model Core so that it is parcel-aware by implementing parcel-specific functionality. Additionally modify the Model State to contain parcel data. This work includes interpolation routines to interpolate to/from grids from/to parcels, haloswapping parcels between processes, Fourier transforms, operations on spectral variables and functionality to use the RK4 integrator.\n  \\item WP2: Dynamical Core implementation\\\\\n  Implement various MONC components to provide the existing MPIC functionality. These components include a RK4 integrator, parcel splitting and merging, velocity inversion, and velocity tendency.\n  \\item WP3: Diagnostics\\\\\n  Implement parcel awareness into the I/O Server and some basic parcel data analysis operations.\n  \\item WP4: Testing, Validation and Training\\\\\n  Testing and validation of the work carried out in WP1 to WP3. This Work Package will be carried out in parallel with WPs 1-3 where necessary. Additionally, provide an ARCHER Webinar to publicise the work carried out in the eCSE and advise potential users in PMPIC's use.\n\\end{itemize}\nThroughout the project we aimed to include OpenMP functionality into PMPIC, making it a hybrid OpenMP/MPI code.\nIn the following sections we will refer to left/right as the -ve/+ve $x$ direction, down/up as the -ve/+ve $y$ direction, and bottom/top as the -ve/+ve $z$ direction.\n\n\\section{Technical Work Carried Out} \\label{development}\nWe will now describe the technical work carried out in this project. It broadly falls under four categories: adding parcel properties into the Model State, implementing parcel functionality into the Model Core, writing components, and diagnostic routines. In the following subsections we will describe the work carried out in the four aforementioned categories, and will describe testing and validation applied to the code.\n\n\\subsection{Model State}\n\\subsubsection{Arrays vs Derived Datatypes}\n\\begin{figure}\n  \\begin{center}\n    \\includegraphics[scale=0.5]{pmpic_images/grid2par.png}\n    \\caption{Comparison of the mean time per par2grid and grid2par operation for both \\emph{array} and \\emph{derived datatype} parcel descriptions.\\label{grid2par_comp}}\n  \\end{center}\n\\end{figure}\nFirstly, it is important to determine how to best represent parcels in PMPIC. There are two main ways this could be done: an array of a `parcel' derived data type containing all the parcel properties (hereby the \\emph{derived datatype} approach), or several arrays, one for each parcel property (hereby the \\emph{array} approach). The \\emph{derived datatype} approach simplifies haloswaping, as one can simply send arrays of the $n$ parcel datatypes. If in future extra parcel properties are added, other than re-defining the parcel datatype, little to no work has to be done to change the existing parcel haloswapping routines. On the other hand, the \\emph{array} approach allows a single parcel property for all the parcels (e.g. buoyancy) to be contiguous in memory, which may result in performance gains when acting on a single parcel property, although parcel haloswapping is not so easy to implement.\n\nPerformance analysis of MPIC showed that a significant amount of the runtime is spent in the parcel interpolation routines. We therefore wish to choose a parcel representation that gives the best performance in these routines. In order to determine the optimal parcel representation we wrote basic parcel to grid (par2grid) and grid to parcel (grid2par) routines that could handle the \\emph{array} approach and the \\emph{derived datatype} parcel descriptions, and determined the mean time per operation for each interpolation. A graph of the times per operation for a gridsize of $128^3$ using $2^3$ parcels per cell is displayed in Figure \\ref{grid2par_comp}. It shows that grid2par takes roughly the same time using either method, but that par2grid is significantly faster using the \\emph{array} description. On average the \\emph{array} description is $6\\%$ faster for the par2grid operation, and $70\\%$ faster for the grid2par operation. We therefore chose the \\emph{array} parcel representation method due to its better performance.\n\n\n\n\\subsubsection{MPIC Data Representation}\nIn order to minimise the alterations to existing MONC code, we chose to place all the parcel related data into a \\verb|parcels| derived datatype inside the model core so that they were separated from the rest of the data, and also clearly labelled as belonging to parcels. The various grids used by MPIC were chosen to be the existing \\verb|prognostic_field_type| datatype and were simply added as additional members of this type into the model state.\n\nIn order to facilitate the possibility of adding additional parcel properties in the future, we implemented a two dimensional array of parcel properties in the \\verb|parcels| datatype, indexed by parcel number, and the index of the property. This array is implemented into the parcel haloswapping routines (Section \\ref{parcel_haloswapping}) so that newly added parcel properties are automatically haloswapped, and no additional work is needed to implement haloswapping for these new properties.\n\n\\subsection{Model Core}\nWith a description of the parcel data in the Model State, we could then move onto developing functionality into the Model Core.\n\n\\subsubsection{Parcel Interpolation}\nThe parcel interpolation routines form the backbone of MPIC, as they allow parcel properties to be interpolated onto the grid and vice versa. For par2grid/grid2par, a parcel's properties are trilinearly interpolated to/from the eight gridpoints surrounding that parcel. For par2grid, a grid point's value is derived from the weighted sum of \\emph{all} the parcels in the eight cells surrounding it, whilst in grid2par a parcel's value is determined from the weighted sum of the values of the eight grid points surrounding it.\n\nIn MONC, where the domain in spatially decomposed, parcels on the edge of a domain will require to pass/retrieve values to/from a gridpoint belonging to a neighbouring process. For grid2par we perform a normal haloswap (adjacent processes' edge cells to the halo) and we can then interpolate onto parcels. This is not so simple in par2grid however, as we are moving parcel properties onto grid points via a sum. A \\emph{reverse haloswap} is required, where we send a process' halo cells to adjacent processes, who then add it to the values in their own cells. This differs from regular haloswapping, which send regular cells to halo cells.\n\nDue to the parallel decomposition of MONC (in the $x$ and $y$ directions), parcels are only influencers/influenced by halo cells in the right and upward edges of the process' domain. We hence only need to haloswap the right and upper edges of the grids as halo values in the downward and left edges are not needed. With this, and the fact that par2grid requires a special kind of haloswapping, we implemented our own grid haloswapping rather than try to modify MONC's existing haloswapping functionality. We produced two haloswapping routines, \\verb|grid2par_haloswap| and \\verb|par2grid_haloswap| for use in grid2par and par2grid respectively.\n\nIn order to validate our par2grid and grid2par routines, we constructed test cases consisting of linear profiles in $x$, $y$ and $z$ (or a combination of two or more directions) and ensured that we could recover the correct parcel/grid values from the interpolations. We chose linear profiles as the trilinear method is only guaranteed to produce the correct result for linear profiles.\n\n\\subsubsection{Parcel Haloswapping}\\label{parcel_haloswapping}\nAs parcels are evolved in time they will move about the computational domain, and we therefore need to be able to pass these between individual processes' domains. In order to do this we carry out the following operations:\n\\begin{enumerate}\n  \\item Loop over all parcels in the process and flag the parcels that need to be transferred to neighbouring processes.\n  \\item For each neighbouring process, construct buffer arrays where the parcels that need to be sent to that process are stored.\n  \\item Send these buffers to each neighbour via a non-blocking send.\n  \\item Receive buffers from each neighbouring process, and unpack the parcels into the parcel arrays, backfilling into gaps left by sent parcels where applicable.\n  \\item Backfill parcels into any remaining holes left by sent parcels.\n\\end{enumerate}\n\nIn order to test parcel haloswapping, we implemented a basic Eulerian integrator component and a component to prescribe the parcel velocities, $\\v{u} = f(x,y,z)$. We tagged parcels according to their starting position and integrated parcel trajectories for a number of timesteps and ensured that the end solution was identical regardless of the number of processes used. Velocity profiles tested included a constant velocity in various directions and a rotational velocity profile. An example of a test is shown in Figure \\ref{parcel_haloswap}, where a series of parcels split between four processes is advected according to a rotational velocity field. The parcels are colour-coded by their initial process, and are successfully transferred between processes as they move around the computational domain.\n\n\\begin{figure}\n  \\begin{center}\n    \\includegraphics[scale=0.45]{pmpic_images/vel0.png}\n    \\includegraphics[scale=0.45]{pmpic_images/vel1.png}\n  \\end{center}\n  \\caption{Parcels coloured according to their initial process before (left) and after (right) being advected by a rotational velocity profile, demonstrating that the parcels have been successfully haloswapped between processes. \\label{parcel_haloswap}}\n\\end{figure}\n\n\\subsubsection{Implementing functionality for a RK4 integrator}\nMONC uses an Eulerian integrator, so per timestep each component is called once, and the model state is evolved at the end. In MPIC, which uses a RK4 integrator, several components would need to be called four times in sequence, corresponding to each of the four steps in the RK4 integration. We thus had to modify the Model Core so that it knew to call a group of components a fixed number of times per timestep.\n\n\\subsubsection{Fast Fourier Transforms and Spectral Derivatives}\nA number of MPIC's solvers use Fast Fourier Transforms (hereby FFTs) when calculating quantities. An existing MONC component also uses FFTs for a calculation, so we used the pre-existing FFT functionality from this component, but built it into the model core. MONC's FFT routines perform FFTs in the $x$ and $y$ directions using the FFTW library, leaving the $z$ direction in positional space. The grids are therefore transformed into semi-spectral space. MONC stores the complex output in double precision (real) arrays, where odd-numbered indices are the real part, and even-numbered indices are the imaginary part. As a real to complex FFT of $N$ points produces $N/2+1$ complex numbers, the resultant (global) transformed grids contain $N_x+2$, $N_y+2$ and $N_z$ cells in the $x$, $y$ and $z$ directions respectively. This means that for certain grid decompositions, a complex number (pair of reals in the array representation) can be split between two processes.\n\nMPIC's solvers use spectral derivatives, that is, differentiation is carried out on a spectral variable. Mathematically, to do this we compute:\n\\begin{equation}\n  F'(k) = 2\\pi i k F(k),\n\\end{equation}\nwhere $F(k)$ is the Fourier transformed quantity, $F'(k)$ is the derivative of the quantity and $k$ is the wavenumber. To compute the second derivative we simply have\n\\begin{equation}\n  F''(k) = -4\\pi^2 k^2 F(k).\n\\end{equation}\nIn order to implement the first derivative we simply need to multiply each entry in the array by $2 \\pi k$ and swap the real and imaginary parts in each pair around to represent multiplying by $i$. As these pairs can be split between processes we need to send messages to swap these values. As the second derivative requires no swapping, this is simple to implement as all we do is multiply each entry in the array by $4 \\pi^2 k$.\n\nIn order to verify the FFT routines we got them to compute FFTs functions with known Fourier transforms, and compare the values. Similarly, we tested the spectral derivatives by taking the FFT of a known function, differentiating it, then taking the inverse FFT and ensuring it matched the analytical derivatives.\n\n\\emph{We note here that MPIC differs from MONC in that it takes FFTs in the $x$, $y$ and $z$. We however adopt the MONC approach in PMPIC and use a tridiagonal solver in the $z$ direction rather than a FFT solver. Please see Section \\ref{inversion} for more details on the solver.}\n\n\\subsubsection{Timing routines}\nIn order to better quantify the performance of PMPIC, it was decided to implement timing functionality into the code. In order to do this we added a timing subroutine into the model core which components could register with, and report when they were entered and exited. This timing component could then report timing statistics at the end of the run so the user (and developer!) can get an indication of which parts of the code are the most time consuming.\n\n\\subsection{Components}\nWith the Model Core fully parcel-aware, and general functionality required MPIC in place, components could then be implemented.\n\n\\subsubsection{Parcel/Grid Setup}\nWe first wrote some basic components that read in a config file and allocated memory for the parcels and grids. These used much of the existing MONC Model Core functionality for determining the parallel decomposition and grid properties. It was also important to produce a component that set up the parcels according to the initial condition. It was decided that this component would be user-supplied, and would set up the parcels as needed for the simulation. For the eCSE project we wrote a component that produces the initial condition for the spherical thermal described in \\citet{Dritschel2018}.\n\n\\subsubsection{Basic I/O Routines}\nBefore work on WP3 where more sophisticated I/O would be developed, we wrote two basic I/O components. The first component was a parcel and grid writing routine, which would produce binary files for the grid and parcels, one file per process. The user could choose how often these files were created, and select whether they wanted to write files every $n$ timesteps, or every fixed time interval $dt$. The user could choose different writing frequencies for parcels and grids.\nThe second component was a component that read parcel files into memory, allowing a restart functionality for PMPIC. We designed this so that parcel files written by $m$ processes could be read in by $n$ processes so that a subsequent simulation could use a different number of processes from the previous one. Mindful to minimise stress on ARCHER's Lustre filessystem, the process with rank 0 opens each file sequentially and reads \\emph{only} the creating process's location in the global domain from the file. It then broadcasts this to every other process which then open and read parcels in from \\emph{only} the required files.\n\n\n\\subsubsection{RK4 Integrator}\n First we implemented a RK4 integrator. In order to do this we required storage for temporary arrays during the integration process. The quantities that are evolved are the vorticity and the parcel positions, whilst the gradients used are the velocities and vorticity tendencies. In total twelve temporary arrays are needed, six for the initial values of the parcel positions and vorticities, and six for the cumulative values for the positions and vorticity.\n\n\\subsubsection{Velocity Inversion}\\label{inversion}\nIn order to solve for the velocity, we use the definition of vorticity,\n$\n  \\gv{\\omega} = \\curl{\\v{u}}.\n$\nImposing that the flow is incompressible, $\\div{\\v{u}} = 0$, we can write $\\v{u} = - \\curl{\\v{A}}$, where $\\v{A} = (A,B,C)$, $\\div{\\v{A}} = 0$, is a vector potential. We can hence represent the vorticity as\n\\begin{equation}\n  \\gv{\\omega} = \\v{\\nabla}^2 \\v{A}.\n\\end{equation}\nIn semi-spectral space this equation becomes\n\\begin{equation} \\label{vort2vel_eq}\n  \\pp{\\v{A}}{z} - 4\\pi^2 \\v{K}^2 \\hat{\\v{A}}= \\gv{\\omega},\n\\end{equation}\nWhere $\\hat{\\v{A}}$ is the semi-spectral transform of $\\v{A}$. This above equation when using finite difference derivatives in the $z$ direction, reduces to a tridiagonal problem that can be easily solved. We hence implemented a tridiagonal solver into PMPIC to be able to solve this equation.\n\nBefore we do this, however, we wish to correct the parcel vorticity, $\\gv{\\omega}_p$, to ensure that $\\div{\\gv{\\omega}} = 0$. This formulation allows us to calculate the vorticity tendency in Section \\ref{tendency}. To correct the vorticity we define a scalar $\\chi$ where\n$\n  \\gv{\\omega} = \\gv{\\omega}_p - \\grad{\\chi}\n$\nTaking the divergence of this equation and setting it to zero we obtain\n\\begin{equation} \\label{chi}\n  \\div{\\gv{\\omega}}_p = \\nabla^2 \\chi.\n\\end{equation}\nThis equation also reduces to a tridiagonal problem that can be solved with the tridiagonal solver.\n\nThe computational steps to invert the vorticity to produce the velocity field are:\n\\begin{enumerate}\n  \\item Apply the par2grid operation to the three components of the vorticity.\n  \\item Take FFTs of the three gridded components of the vorticity.\n  \\item Calculate $\\div{\\gv{\\omega}}$ using spectral derivatives (in $x$ and $y$) and finite difference derivatives (in $z$).\n  \\item Obtain $\\hat{\\chi}$ by solving Equation \\ref{chi} using the tridiagonal solver.\n  \\item Determine $\\grad{\\hat{\\chi}}$ using spectral and finite difference derivatives (as required) and correct the vorticity.\n  \\item Use the tridiagonal solver to obtain $\\hat{\\v{A}}$ from Equation \\ref{vort2vel_eq}.\n  \\item Calculate the semi-spectral velocity field from $\\hat{\\v{A}}$ and interse-FFT to obtain the velocity field.\n  \\item Inverse-FFT the corrected vorticity.\n  \\item Apply grid2par for the corrected vorticity and velocity.\n\\end{enumerate}\n\nIn order to test the velocity solver, we constructed an analytical form of $\\gv{\\omega}$ with a known $\\v{A}$, and compared this to $\\v{A}$ determined from the solver. Figure \\ref{inversion_fig} displays graphs of the analytical solution of $\\v{A}$ with the numerically determined $\\v{A}$ for horizontal wavenumbers $(k_x,k_y)=(1,2)$.\n\n\\begin{figure}\n  \\begin{center}\n    \\includegraphics[scale=0.6]{pmpic_images/solution.png}\n  \\end{center}\n  \\caption{Comparison of reference (analytical) values of the velocity potential field against those determined from the solver.}\n  \\label{inversion_fig}\n\\end{figure}\n\n\n\\subsubsection{Vorticity Tendency}\\label{tendency}\nThe vorticity tendency is defined by\n\\begin{equation}\n  \\pd{\\gv{\\omega}}{t} = ( \\div{\\v{F}},\\div{\\v{G}},\\div{\\v{H}}),\n\\end{equation}\nwhere $\\v{F} = \\gv{\\omega}u + b \\uv{y} $, $\\v{G}=\\gv{\\omega}v - b \\uv{x}$ and $\\v{H}=\\gv{\\omega}w$, where $b$ is the buoyancy, $(u,v,w) = \\v{u}$, and $\\uv{x}$, $\\uv{y}$ are unit vectors in the $x$ and $y$ directions respectively.\n\nThe steps to calculate the vorticity tendency are as follows:\n\\begin{enumerate}\n  \\item Apply the par2grid operation on the buoyancy.\n  \\item Calculate the FFT of the buoyancy.\n  \\item For $\\v{F}$, $\\v{G}$ and $\\v{H}$, determine their components in semi-spectral space.\n  \\item  Calculate the divergences of $\\v{F}$, $\\v{G}$ and $\\v{H}$ using spectral derivatives to determine the vorticity tendency.\n  \\item Inverse-FFT the components of the vorticity tendency, then apply the grid2par to interpolate this onto the parcels.\n\\end{enumerate}\n\n\\subsubsection{Parcel Splitting and Mixing}\nIn order to simulate the cascade of energy to smaller scales which occurs during turbulence, MPIC splits parcels into smaller ones, then eventually merges them into surrounding parcels. We implemented this into PMPIC via two components, a splitting component and a mixing component.\n\nEvery parcel carries a quantity called the stretch, defined by\n\\begin{equation}\n  \\gamma_i(t) = \\int_{t_i}^{t} \\left(\\gv{\\omega}_i \\cdot \\d{\\gv{\\omega}_i}{t} \\right)^{\\frac{1}{3}} dt,\n\\end{equation}\nwhere $t_i$ is the time the parcel came into existence. Parcels are split into two parcels when the stretch exceeds a value of 4. Upon splitting, the two child parcels have half the volume of their parent, their stretch is reset to zero, but their other quantities remain identical to the parent's. The two child parcels are separated by a distance $d = (2V_i/\\pi)^{1/3}$ (where $V_i$ is the volume of the parent parcel) along the direction of the parent's vorticity vector. The PMPIC implementation of this is identical to the MPIC implementation save for a parcel haloswap operation which is applied at the end of the process to ensure that any child parcels that end out outside of the process' domain are sent to the appropriate process. In order to test this component we created a set of parcels, and for some set their stretch to a value above 4, then ensured that the child parcels had correct positioning and values.\n\nOnce a parcel's volume has been reduced (through multiple splittings) below a threshold value (chosen to be $(1/6)^3$ of the volume of a grid cell), this parcel is removed and its properties are added to surrounding parcels to ensure conservation of mass. This merging process prevents a runaway increase in the number of parcels in the simulation, and limits the number of parcels per gridcell to $6^3$. In addition to removal of small parcels, if a grid cell has too few parcels inside it, a new parcel is created in the centre of the cell, and `absorbs' the properties of adjacent parcels (once again to conserve mass and other fluid properties). The mixing procedure is very similar to a par2grid followed by a grid2par operation, with some intermediate steps:\n\\begin{enumerate}\n  \\item Loop through each parcel and determine which parcels are smaller than the threshold volume for splitting and hence need to be removed.\n  \\item Carry out a par2grid operation on the parcels that are to be kept. Also perform a par2grid operation on the parcels to be removed, creating grids of the \\emph{residual} variables.\n  \\item Perform a par2grid and grid2par haloswap on the gridded values for parcels to be kept.\n  \\item If there are fewer than three parcels in a grid cell, create a new parcel in the centre of the cell and assign to it a volume of twice the minimum volume for a parcel, assigning properties to it proportional to a weighted sum of the gridded properties (from kept parcels) of the eight corner points of that cell. Adjust the residual grids to compensate for the transferred grid properties to the new parcel.\n  \\item Backfill parcels into positions of parcels that were removed.\n  \\item Now perform a par2grid and grid2par haloswap on the residual grid properties\n  \\item Finally perform a modified grid2par operation where the quantities from the residual grids are added to the existing parcel properties.\n\\end{enumerate}\nIt is important that both a par2grid and grid2par haloswap is performed on the grids of kept parcels \\emph{before} the creation of new parcels in Stage 4. This ensures that grid cells on the edge of the computational domain have the correct grid values for interpolating onto the new parcels. Similarly, once the new parcels have been added, par2grid and grid2par haloswaps of the residual grids are required to ensure that these grids are correct for interpolation back onto the existing parcels.\n\nIn order to test parcel removal a number of parcels at random had their volumes reduced below the minimum volume threshold. Global volume-integrated quantities were determined for the grid and stored. After the mixing process was complete, the global volume-integrated quantities were re-computed, and compared against the original values to ensure that they were the comparable. In order to test adding in new parcels, a number of parcels were removed from a number of cells at random to reduce the parcel count below three in these cells. Then the global volume-integrated quantities were determined, the parcel creation process was carried out, then the new volume-integrated properties were compared to the old ones. For both methods it was found that the global quantities were conserved to a factor of $10^{-13}$ when half of the parcels were shrunk/removed.\n\n\\subsection{Diagnostics}\n\nThe original intention was to use the MONC I/O server to reduce parcel data from the simulations and write parcel/grid information to file. Unfortunately it became evident that parcels consume a large amount of memory and so allocating memory for parcels in an I/O server on a node would potentially require half of all the memory of that node, meaning we would need to run a simulation with a given number of compute processes on twice as many nodes if we were to use an I/O server. Without any I/O server, for simulations with grid resolutions of $256$, $512$ and $864$, we found a minimum of $3$, $43$ and $216$ nodes respectively were required to successfully run simulations. These node counts (especially for the larger gridsizes) are non-trivial, so using an I/O server would double this minimum number, and potentially double kAU usage. We therefore decided against using MONC's I/O server as its use could significantly increase the cost of running PMPIC simulations.\n\nWe instead focused on writing a parallel NetCDF writer component for the grids (one file per timestep collectively written by every process). This has been based on the existing functionality in MONC to write checkpoint files outside the IO-server. In MONC, these checkpoint files contain prognostic 3D fields as well as some 1D fields and metadata. Here, we only create a number of 3D fields at current. As parallel NetCDF functionality requires a specific version of the NetCDF libraries, compilation of the NetCDF routines has been made optional: a version of the code without NetCDF can be compiled by invoking \\verb|make nonetcdf| or \\verb|make nonetcdf-debug|. The global grid coordinates are calculated in the NetCDF output routine, so that the output data includes these. A difference with the checkpoint output in MONC is that both a time variable and a time dimension are included, which makes it easier to further process the data (this means the output fields are actually 4-dimensional, rather than 3-dimensional, even though they only contain 1 time step). A guide to compiling the NetCDF libraries has been included as part of the model wiki on the website. \n\nDue to the size of parcel checkpoint files (up to 2GB per process) we decided against creating an equivalent parallel NetCDF writing component for parcels, as the resultant files could be very large and therefore difficult to transfer (though a non-parallel NetCDF output component will be one of our priorities for future development). We instead focused on writing a visualisation script that could visualise a quantity (e.g. buoyancy) in a plane from the parcel properties. This is beneficial over simply obtaining this from the gridded variables as a higher resolution can be obtained using parcels. To do this, our script determines which files correspond to the regions in the global domain that are needed to construct the plane. Each required file is then read in and the relevant parcel properties are interpolated onto the plane to produce the image. For information on the specific interpolation method employed, please see \\citet{Boeing2018}. An example of an image produced by the parcel visualisation script (and the corresponding image constructed from the grid variables) from a simulation with $32^3$ gridpoints is shown in Figure \\ref{lowres}.\n\n\\begin{figure}\n  \\begin{center}\n    \\includegraphics[scale=0.5]{pmpic_images/32grid.png}\n    \\includegraphics[scale=0.5]{pmpic_images/32parcels.png}\n  \\end{center}\n  \\caption{Comparison of the buoyancy in the $z-y$ plane for a $32^3$ grid cell simulation constructed from the gridded values (left) and from the parcels (right). It can be seen that images constructed from the parcels have considerably more detail as they are able to resolve sub-gridcell structure. \\label{lowres}}\n\\end{figure}\n\n\\section{Performance Comparisons with MPIC and Scaling Tests} \\label{performance}\nIn this section we will compare PMPIC performance with MPIC, and then go onto investigating how PMPIC performs at scale.\n\n\\subsection{Single Node Performance}\n\n\\begin{figure}\n  \\begin{center}\n    \\includegraphics{pmpic_images/singleNode.png}\n  \\end{center}\n  \\caption{Speedup comparisons between MPIC and PMPIC using MPI processes and OpenMP threads.}\n  \\label{MPI-OMP-comp}\n\\end{figure}\nIn order to compare PMPIC with MPIC, we consider the performance of PMPIC on a single node, as MPIC (being parallelised solely with OpenMP) can only scale to one node. We ran a $128^3$ simulation for 8 time units, using 1, 2, 4, 8 and 16 MPI processes, and 1, 2, 4, 8 and 12 OpenMP threads. Figure \\ref{MPI-OMP-comp} displays speedup graphs for MPIC, and PMPIC using MPI processes and OpenMP threads. PMPIC (using only MPI processes) produces the best speedup, with near ideal speedup to 4 MPI processes, then sub-ideal speedup to 16 processes. At 16 processes a speedup of 9.09 is achieved (parallel efficiency of 57\\%). MPIC achieves the second best speedup, with a speedup of 6.68 with 12 cores (parallel efficiency of 56\\%). PMPIC's OpenMP performance is the worst, with a peak speedup of 3.05 at 12 cores (parallel efficiency of 25\\%).\n\n\\begin{figure}\n  \\begin{center}\n    \\includegraphics{pmpic_images/pie.png}\n  \\end{center}\n  \\caption{Fraction of the total runtime of each operation in PMPIC for a simulation using 1 core with $128^3$ gridcells.}\n  \\label{pie chart}\n\\end{figure}\n\n\\begin{figure}\n  \\begin{center}\n    \\includegraphics[scale=0.8]{pmpic_images/MPISingle.png}\n    \\includegraphics[scale=0.8]{pmpic_images/openmpSingle.png}\n  \\end{center}\n  \\caption{The speedup of the operations for MPI (left) and OpenMP (right)}\n  \\label{1 node operations}\n\\end{figure}\n\nIn order to determine the causes of the bad OpenMP scaling and poor MPI scaling beyond 4 processes in PMPIC, we consider the timings for each of the main operations carried out in PMPIC. First of all, let us consider the single-core case, and look at the relative times for each operation. Figure \\ref{pie chart} displays the proportion of the runtime taken up by each operation. The single largest operation (by time) is the FFT operation, followed by par2grid and mixing. Parcel splitting is the least significant operation at only 3\\% of the total runtime. Figure \\ref{1 node operations} displays the speedups for OpenMP and MPI for each operation. For OpenMP, we find that parcel splitting and the FFT routines have the worst speedups. The mixing routines cannot be parallelised with OpenMP so the lack of a speedup is to be expected here. Also they take up a small proportion of the total runtime of a simulation so their poor scaling is of little concern. With the FFT routines - which consume the largest proportion of the runtime - although the execution of the FFTs and some data transposition is parallelised, the required \\verb|MPI_Alltoall| communication step is not parallelisable, and so acts as a bottleneck in OpenMP. The next two poor performing operations are par2grid and the RK4 integrator. It is unclear why OpenMP performance is so poor here as these are completely parallelised via OpenMP. We suspect we need to tune the chunk size in the OpenMP \\verb|DO| loops. Considering the MPI performance, we see that all operations scale well to 4 processes, and then scale less well beyond this, with the notable exception of the FFT routines. This performance drop above 4 processes can be attributed to a load imbalance being introduced due to the domain decomposition, whereby some processes contain fewer parcels, so any operation involving parcels will have a load imbalance introduced. This is why the FFT operations, which are purely grid-based scales better than the other operations, which involve parcels. Figure \\ref{parcel imbalance} displays the number of parcels per process as a function of timestep for 4 and 8 processes.\n\n\\begin{figure}\n  \\begin{center}\n    \\includegraphics[scale=0.35]{pmpic_images/4p.png}\n    \\includegraphics[scale=0.35]{pmpic_images/8p.png}\n  \\end{center}\n  \\caption{Number of parcels per process as a function of timestep for simulations with 4 (left) and 8 (right) processes, demonstrating that an imbalance of a factor of 1.6 between the number of parcels per process for the simulation with 8 processes.}\n  \\label{parcel imbalance}\n\\end{figure}\n\nIn terms of overall performance, MPIC was found to achieve 353,000 parcels operations per core per second, and 198,000 on 12 OpenMP threads. For a single core, PMPIC achieves 563,000 parcel operations per core per second and on 12 OpenMP threads it achieves 131,000 parcel operations per core per second (slightly less than MPIC), however on 16 MPI processes achieves 412,000 parcel operations per core per second, which is better performance than MPIC. Overall, despite achieving poorer OpenMP performance, using MPI PMPIC has better scaling and performance than MPIC.\n\n\\subsection{Performance at Scale}\n\n\\begin{figure}\n  \\begin{center}\n    \\includegraphics{pmpic_images/512.png}\n  \\end{center}\n  \\caption{Speedup of $512^3$ gridcell simulations with 1, 2 and 4 OpenMP threads.}\n  \\label{512 scaling}\n\\end{figure}\nWe now shall consider the performance of PMPIC for large simulations. We consider simulations with $512^3$ and $864^3$ gridcells respectively. Figure \\ref{512 scaling} displays the speedup graph for the simulation with $512^3$ gridcells for 1, 2 and 4 OpenMP threads per process. With 1 thread per process, we find good scaling from 1024 to 8192 cores, and the scaling deteriorates from this point. Considering the speedup of the operations (Figure \\ref{512 op}) we find that all the operations scale ideally up to 32768 processes except for the FFT operations, which do not scale beyond 2048 processes. It is clear therefore that the FFT routines (in particular the \\verb|MPI_Alltoall| call) are a bottleneck for the simulations at this scale. In order to determine if OpenMP can help alleviate this (by reducing the number of MPI processes for a given number of nodes) we investigated some simulations with multiple OpenMP threads per process for larger core counts, which gave similar performance to the pure MPI simulations.\n\n\\begin{figure}\n  \\begin{center}\n    \\includegraphics{pmpic_images/512ops.png}\n  \\end{center}\n  \\caption{Speedup of operations in $512^3$ gridcell simulations demonstrating that all the operations save for FFTs scale ideally.}\n  \\label{512 op}\n\\end{figure}\n\nFigure \\ref{864 speedup} displays the speedup for simulations with $864^3$ gridcells. It shows that we achieve good scaling to 20,736 MPI processes. Similar to the $512^3$ gridcell case, we find that all operations scale ideally for all core counts except for the FFT routines, which achieve a speedup of only 2.2 at 46,656 cores. We would have liked to have investigated the effects of OpenMP threads on the scaling of these simulations, however we had run out of budget on ARCHER so were unable to run further simulations. For $5184$ processes, we found that PMPIC achieved 140,000 parcel operations per core per second. We note that the load imbalance mentioned above - caused by processes having different numbers of parcels - is still present in these simulations, however as it is present in all simulations its effects are not visible in the speedup graphs. In these simulations the imbalance is typically a factor of 5. Given that the single core performance of PMPIC is 563,000 parcel operations per core per second, and the performance at scale is approximately 5 times lower, we believe that this load imbalance is the main contributing factor in the performance decrease. Figure \\ref{864} displays the buoyancy in the $y-z$ plane for the a simulation with $864^3$ gridcells at $t=2, 4, 6$ and $8$.\n\n\\begin{figure}\n  \\begin{center}\n    \\includegraphics{pmpic_images/864.png}\n  \\end{center}\n  \\caption{Speedup of operations in $864^3$ gridcell simulations. Like shown in Figure \\ref{512 op}, all operations scale ideally except for the FFTs.}\n  \\label{864 speedup}\n\\end{figure}\n\n\n\n\n\\begin{figure}\n  \\includegraphics[scale=0.4]{pmpic_images/2.png}\n  \\includegraphics[scale=0.4]{pmpic_images/4.png}\n  \\includegraphics[scale=0.4]{pmpic_images/6.png}\n  \\includegraphics[scale=0.4]{pmpic_images/8.png}\n  \\caption{Example evolution of the buoyancy in a simulation with $864^3$ grid cells at t=2,4,6 and 8.}\n  \\label{864}\n\\end{figure}\n\n\n\\section{Discussion and Conclusions} \\label{discussion}\nIn this project we implemented the `Moist Parcel In Cell' (MPIC) code into the `Met Office NERC Cloud Model' (MONC), allowing MPIC to benefit from MPI parallelisation, and making MONC parcel (particle) aware. We call this new code the `Parallel Moist Parcel In Cell' (PMPIC) code. The work involved modifying the MONC Model Core to include the basic parcel operations required for MPIC's functionality. This work included implementing grid-to-parcel and parcel-to-grid interpolation operations, as well as permitting MONC to use a 4th Order Runge Kutta integrator. We then wrote various MONC components to implement the physics of MPIC. Initially we had planned to modify MONC's I/O server to do in-situ analysis of the simulation data during a simulation, however due to memory limitations we decided against this as it could possibly double the computational cost of a simulation.\n\nComparing the single-node performance of PMPIC and MPIC, we found that the PMPIC (using MPI processes) scaled better than MPIC, however its OpenMP performance was poor, achieving a speedup of only 3 using 12 cores. MPI performance was limited by an imbalance in the number of parcels per process, due to the spatial decomposition of the simulation. Considering large simulations, we found that the PMPIC's performance was limited by the Fast Fourier Transform (FFT) routines, which did not scale well beyond a few thousand MPI processes. Other operations scaled ideally. Despite these limitations, we obtained good scaling (greater than 70\\% parallel efficiency) of up to 8192 MPI processes (using a $512^3$ grid) and 20,736 processes (using a $864^3$ grid).\n\nWe note that although we did not implement the I/O server functionality, we did implement parallel NetCDF functionality for writing the grids to file. Although we did not have time to look into further work on in-situ analysis, we believe the way forward would be to write a MONC component (or series of components) that carries out analysis and I/O on the parcel data.\n\nThe load imbalance between processes affects the performance of PMPIC beyond 4 cores. This is due to the test simulation having a sphere of parcels in the centre with a higher number density ($4^3$ per cell compared to $2^3$ in the background), with most parcels being split in this central region. This results in some processes having many (up to 5$\\times$) more parcels than other processes. Choice of a different initial condition with a more spatially uniform parcel distribution would help alleviate this issue, although our choice of initial condition here was constrained by the existing MPIC data which we wished to compare against. Future work could include implementing dynamic load balancing into PMPIC, although we note that this would be a major undertaking, as much of MONC's model core would need to be re-written to deal with dynamically changing each process' local grid size during runtime.\n\nOpenMP performance was found to be poor in PMPIC. The worst performing operations were the FFTs (un-parallelisable), the Runge Kutta integrator and the grid2par interpolation. Future work would be to investigate if re-factoring these operations, or by changing chunk sizes can lead to better performance. With better OpenMP performance, we may be able to partially overcome MPIC's FFT scalability issues by using fewer MPI processes per node, hence decreasing the number of processes involved in the all-to-all communications.\n\nFor large simulations, are by far the most significant cause of poor scaling. Minimising the use of FFTs should therefore improve PMPIC's scaling. In PMPIC, FFTs are used in two different places. In the velocity inversion, the velocity is calculated using a FFT solver, whereby the solution is determined in semi-spectral space and then transformed back into positional space. Many spatial derivatives are also calculated in Fourier space, then transformed back into positional space. Implementing a solver that does not use Fourier transforms, and/or swapping Fourier derivatives with finite difference derivatives should therefore aid scalability to many tens of thousands of MPI processes.\n\nIn summary, the work in this eCSE project has allowed the Moist Parcel In Cell method to scale beyond one node, up to many thousands of cores, and allows more detailed simulations to be carried out, allowing better science to be carried out.\n\n\n\\section*{Acknowledgements}\nThis work was funded under the embedded CSE programme of the ARCHER UK National Supercomputing Service (http://www.archer.ac.uk)\n\n\n\\bibliographystyle{agsm}\n\\bibliography{refs}\n\n\\end{document}\n", "meta": {"hexsha": "8b720c3ef7dc90a7d6d3c823ecc83ac14d4d05d6", "size": 49495, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/report.tex", "max_stars_repo_name": "sjboeing/pmpic", "max_stars_repo_head_hexsha": "4a77642ef82096a770324f5f1dc587ce121065ab", "max_stars_repo_licenses": ["BSD-3-Clause-Clear", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "report/report.tex", "max_issues_repo_name": "sjboeing/pmpic", "max_issues_repo_head_hexsha": "4a77642ef82096a770324f5f1dc587ce121065ab", "max_issues_repo_licenses": ["BSD-3-Clause-Clear", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/report.tex", "max_forks_repo_name": "sjboeing/pmpic", "max_forks_repo_head_hexsha": "4a77642ef82096a770324f5f1dc587ce121065ab", "max_forks_repo_licenses": ["BSD-3-Clause-Clear", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 126.262755102, "max_line_length": 2152, "alphanum_fraction": 0.7901808263, "num_tokens": 11500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544210587586, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.3169453511220219}}
{"text": "\\documentclass{article}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{amsthm}\n\\theoremstyle{definition}\n\\newtheorem{thm}{Theorem}\n\\newtheorem{axiom}{Axiom}\n\\renewcommand{\\qedsymbol}{Q.E.D.}\n\\title{Reasons for Using Haskell}\n\\author{Varik Valefor}\n\\begin{document}\n\t\\maketitle\n\t\\section{Definitions}\n\t\t\\[\n\t\t\th := \\textrm{Haskell}.\n\t\t\\]\n\t\tWhere $l$ denotes an arbitrary programming language,\n\t\t\\[\n\t\t\tA := \\left\\{l: \\textrm{VARIK HAS USED } l\\right\\} - h.\n\t\t\\]\n\t\\section{Arguments}\n\t\\begin{axiom}[The Fundamental Rule of Language Superiority]\n\t\tFor all programming languages $a$, for all programming languages $b$, $a$ is superior to $b$ if each following condition is met:\n\t\t\\begin{itemize}\n\t\t\t\\item The readability of $a$ source code is greater than the readability of $b$ source code.\n\t\t\t\\item The ease of writing $a$ source code is greater than the ease of writing $b$ source code.\n\t\t\t\\item The efficiency of $a$'s best compiler is greater than or approximately equal to the efficiency of $b$'s best compiler.\n\t\t\t\\item The ease of searching for security vulnerabilities in $a$ programs is greater than the ease of searching for security vulnerabilities in $b$ programs.\n\t\t\t\\item The documentation of $a$ is superior to the documentation of $b$.\n\t\t\t\\item The ease of maintaining $a$ programs is greater than the ease of maintaining $b$ programs.\n\t\t\\end{itemize}\n\t\\end{axiom}\n\t\\begin{axiom}\n\t\tFor all $a \\in A$, the ease of reading $h$ source code is greater than\n\t\tthe ease of reading $a$ source code.\n\t\\end{axiom}\n\t\\begin{axiom}\n\t\tFor all $a \\in A$, the ease of writing $h$ source code is greater than\n\t\tthe ease of reading $a$ source code.\n\t\\end{axiom}\n\t\\begin{axiom}\n\t\tFor all $a \\in A$, the efficiency of the best $a$ compiler is less than\n\t\tor approximately equal to the efficiency of the best $h$ compiler.\n\t\\end{axiom}\n\t\\begin{thm}\n\t\tFor all $a \\in A$, the ease of searching for\n\t\tsecurity vulnerabilities in $h$ programs is greater than the\n\t\tease of searching for security vulnerabilities in $a$ programs.\n\t\\end{thm}\n\t\\begin{proof}\n\t\tFor all $a \\in A$, the ease of reading $a$ source code is\n\t\tless than the ease of reading $h$ source code.\n\n\t\tFor any computer program $p$ which is written in a programming language\n\t\t$l$, the ease of searching for security vulnerabilities in $p$ is\n\t\tproportional to the ease of reading $l$ source code.\n\n\t\tTherefore, for all $a \\in A$, the ease of searching for security\n\t\tvulnerabilities in $h$ programs is greater than the ease of searching\n\t\tfor security vulnerabilities in $a$ programs.\n\t\\end{proof}\n\t\\begin{thm}\n\t\tFor all $a \\in A$, the documentation of $h$ is superior to the\n\t\tdocumentation of $a$.\n\t\\end{thm}\n\t\\begin{proof}\n\t\tAssume that for all programming languages $a$, for all programming\n\t\tlanguages $b$, $a$'s documentation is superior to $b$'s documentation\n\t\tif there exists a well-written, mathematics-based specification of $a$\n\t\tand there does not exist a well-written, mathematics-based\n\t\tspecification of $b$.\n\n\t\tThere exists a well-written, mathematics-based specification of $h$.\n\n\t\tFor all $a \\in A$, there does not exist a well-written,\n\t\tmathematics-based specification of $a$.\n\n\t\tTherefore, for all $a \\in A$, the documentation of $h$ is superior to\n\t\tthe documentation of $a$.\n\t\\end{proof}\n\t\\begin{thm}\n\t\t%For all $a \\in A$, the ease of maintaining $h$ programs is greater than\n\t\t%the ease of maintaining $a$ programs.\n\t\t$\\forall a \\in A, \\ x(h) > x(a)$, where for all programming languages\n\t\t$a$, $x(a)$ denotes the ease of maintaining $a$ programs.\n\t\\end{thm}\n\t\\begin{proof}\n\t\tFor all computer programming languages $a$, let $w(a)$ denote the ease\n\t\tof writing $a$ programs, let $r(a)$ denote the ease of reading $a$\n\t\tprograms, and let $x(a)$ denote the ease of maintaining $a$ programs.\n\n\t\tFor all programming languages $a$, for all programming languages $b$,\n\t\t\\[\n\t\t\tx(a) > x(b) \\iff \\Big(r(a) > r(b)\\Big) \\land \\Big(w(a) > w(b)\\Big).\n\t\t\\]\n\n\t\t\\[\n\t\t\t\\forall a \\in A, \\ r(h) > r(a).\n\t\t\\]\n\n\t\t\\[\n\t\t\t\\forall a \\in A, \\ w(h) > w(a).\n\t\t\\]\n\n\t\t\\[\n\t\t\t\\therefore \\forall a \\in A, \\ x(h) > x(a).\n\t\t\\]\n\t\\end{proof}\n\\end{document}\n", "meta": {"hexsha": "5a89e3b71c1f6467f547b320b2bde643a0a4ac19", "size": 4103, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "reasons-for-using-haskell.tex", "max_stars_repo_name": "varikvalefor/reasons-for-using-haskell", "max_stars_repo_head_hexsha": "95b68f64532acf29476a389327061a509c73f468", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "reasons-for-using-haskell.tex", "max_issues_repo_name": "varikvalefor/reasons-for-using-haskell", "max_issues_repo_head_hexsha": "95b68f64532acf29476a389327061a509c73f468", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-09-01T08:57:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-01T08:57:12.000Z", "max_forks_repo_path": "reasons-for-using-haskell.tex", "max_forks_repo_name": "varikvalefor/reasons-for-using-haskell", "max_forks_repo_head_hexsha": "95b68f64532acf29476a389327061a509c73f468", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3, "max_line_length": 159, "alphanum_fraction": 0.698513283, "num_tokens": 1264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.31694535112202177}}
{"text": "\\section{Systematic uncertainties}\n\\label{sec:systematics}\n\nThe analysis includes both the statistical fit to MD distribution to search the EW-$ZZjj$ process,\nas well as the cross section measurement of inclusive EW and QCD $ZZjj$ process in fiducial volume.\nTherefore, theoretical and experimental uncertainties may affect the predicted background yields and shapes, \nthe correction factors from detector-level to particle-level measurement, as well as the $ZZjj$ MD shapes and so on.\nMoreover, the statistical uncertainties of simulated samples are also taken into account.\nDue to the extremely low cross section of \\llll channel, the analysis is still data statistic dominant.\nThis section describes the measurement of both theoretical and experimental systematics for $ZZjj$ productions.\nThe systematics for fake backgrounds have been elaborated in section~\\ref{sec:fake_syst}.\n\n\\subsection{Theoretical systematics}\n\nThe theoretical systematics on EW- and QCD-$ZZjj$ processes including the uncertainties from PDF, QCD scale, $\\alpha_{S}$ and parton showering variations are summarized in table~\\ref{tab:syst_theo_uncer}.\nThe PDF uncertainty is estimated from the envelop of NNPDF internal variations and the difference between nominal and alternative PDF sets, following the PDF4LHC as introduced in section~\\ref{hadroniccollision}.\nThe QCD scale uncertainty is estimated by varying the nominal renormalization scale ($\\mu_{R}$) and factorisation scale ($\\mu_{F}$) by a factor of 0.5 or 2.0.\nThere are seven different configurations being considered, where the maximum of variations is chosen as final uncertainty.\nThe parton showering uncertainty is estimated by comparing events with different parton showering setting between the nominal \\textsc{Pythia8} and the alternative \\textsc{Herwig7}\\cite{Bellm:2015jjp, Bahr:2008pv} algorithm.\nThe $\\alpha_{S}$ uncertainty is estimated by varying the value of $\\alpha_{S}$ within \\pm 0.001.\nDue to the lack of simulation sample for alternative parton showering on QCD-$ZZjj$ process, \nthe value of parton showering component is taken from the measurement of EW process.\n\\begin{table}[!htb]\n\\small\n\\begin{center}\n\\begin{tabular}{p{5cm}p{5cm}p{5cm}} \n\\hline\\hline\nProcess     & EW-$ZZjj$   & QCD-$ZZjj$ \\\\\n\\hline\nPDFs        & NNPDF30lo (nominal), CT14lo & NNPDF30nnlo (nominal), MMHT2014nnlo68cl, CT14nnlo \\\\\n\\hline\n$\\alpha_{S}$ & 0.118 & 0.117, 0.118 (nominal), 0.119 \\\\\n\\hline\nQCD scale ([$\\mu_{R}$, $\\mu_{F}$]) & [0.5,0.5], [0.5,1], [1,0.5], [1,1], [1,2], [2,1], [2,2] & [0.5,0.5], [0.5,1], [1,0.5], [1,1], [1,2], [2,1], [2,2] \\\\\n\\hline \nParton showering algorithm & \\textsc{Pythia8}, \\textsc{Herwig7} & - \\\\\n\\hline\\hline\n\\end{tabular}\n\\caption{\nSummary of different variations for EW- and QCD-$ZZjj$ theoretical uncertainties measurement.\n}\n\\label{tab:syst_theo_uncer}\n\\end{center}\n\\end{table}\n\nTable~\\ref{tab:syst_theo_sr} summarizes the normalization uncertainties of each theoretical components in fiducial volume of SR.\n%while table~\\ref{tab:syst_theo_cr} shows the numbers in QCD-enriched CR region.\nFor QCD process, the uncertainty is QCD scale variations dominant.\n%Both of them are taken as inputs for statistical fit.\nThe normalization uncertainties are only taken into account in the measurement of $ZZ$ process cross section.\nAs in the search of EW-$ZZjj$ process, the QCD-$ZZjj$ backgrounds are constrained by data during statistical fit, and only shape variations are considered.\n\\begin{table}[!htb]\n\\small\n\\begin{center}\n\\begin{tabular}{lllll} \n\\hline\\hline\nProcess     & PDF (\\%)  & $\\alpha_{S}$ (\\%) & QCD scale (\\%) & Parton shower (\\%) \\\\\n\\hline\nEW         & +5.9 -5.9 &                   & +6.1 -5.6      & +3.3 -3.3          \\\\\nqqQCD      & +2.0 -1.0 & +2.6 -2.6         & +34.2 -22.8    &                    \\\\\n\\hline\\hline\n\\end{tabular}\n\\caption{\nSummary of theoretical uncertainties for the fiducial volume (SR) for both EW and QCD $qq$-initial processes.\n}\n\\label{tab:syst_theo_sr}\n\\end{center}\n\\end{table}\n\n%\\begin{table}[!htb]\n%\\small\n%\\begin{center}\n%\\begin{tabular}{lllll} \n%\\hline\\hline\n%Process      &  PDF (\\%)                    & $\\alpha_{S}$ (\\%)    & QCD scale (\\%)                     & Parton shower (\\%)  \\\\\n%\\hline\n%EW \\llll     &  +6.1 -6.1                   &                      & +0.8 -1.1                          & +10.1 -10.1           \\\\\n%qqQCD \\llll  &  +2.0 -1.0                   & +2.6 -2.6            & +31.5 -22.0                        &                     \\\\\n%\\hline\\hline\n%\\end{tabular}\n%\\caption{\n%Summary of theoretical uncertainties for the control region for EW and qqQCD processes.\n%}\n%\\label{tab:syst_theo_cr}\n%\\end{center}\n%\\end{table}\nThe uncertainties of QCD $gg$-induced process ($gg \\rightarrow ZZ$) as the function of MD discriminant is shown in figure~\\ref{fig:syst_theo_gg} for both fiducial volume (SR) and QCD CR.\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=0.42\\textwidth]{figures/VBSZZ/syst/BDT_SR_linear.pdf}\n  \\includegraphics[width=0.42\\textwidth]{figures/VBSZZ/syst/BDT_CR_linear.pdf}\n  \\caption{The theoretical uncertainties for \\ggZZ background in particle-level SR (left) and CR (right).}\n  \\label{fig:syst_theo_gg}\n\\end{figure}\n\n\\subsection{Experimental systematics}\n\\label{sec:vbszz_exp_uncer}\n\nThe dominant experimental uncertainties are from the luminosity uncertainty, the momentum scale and resolution of leptons and jets, as well as the lepton reconstruction and selection efficiency.\nSome smaller uncertainties, such as trigger efficiency and pile-up correction, are also considered.\nTable~\\ref{tab:syst_exp_num} lists the major systematic components from leptons and jets for signal and major background processes in \\llll channel.\nThe total uncertainties for sources from electron, muon and jet respectively, as well as the sum (quadratic sum) of them are also summarized in this table.\n\\begin{table}[H]\n\\begin{center}\n\\small\n\\begin{tabular}{|c|c|c|c|}\n\\hline\nname&EW-$ZZjj$&QCD $qq$-initial&QCD $gg$\\\\\n\\hline\nnominal yield&20.61&76.69&13.10\\\\\n\\hline\nEG\\_RESOLUTION\\_ALL&$\\pm^{0.00\\%}_{0.03\\%}$&$\\pm_{0.04\\%}^{0.02\\%}$&$\\pm^{0.01\\%}_{1.41\\%}$\\\\\n\\hline\nEG\\_SCALE\\_ALL&$\\pm^{0.03\\%}_{0.05\\%}$&-0.04\\%&$\\pm^{0.01\\%}_{0.06\\%}$\\\\\n\\hline\nEL\\_EFF\\_ID\\_TOTAL\\_1NPCOR\\_PLUS\\_UNCOR&$\\pm^{2.66\\%}_{2.58\\%}$&$\\pm^{2.60\\%}_{2.53\\%}$&$\\pm^{2.65\\%}_{2.57\\%}$\\\\\n\\hline\nEL\\_EFF\\_Iso\\_TOTAL\\_1NPCOR\\_PLUS\\_UNCOR&$\\pm$0.70\\%&$\\pm$0.47\\%&$\\pm$0.42\\%\\\\\n\\hline\nEL\\_EFF\\_Reco\\_TOTAL\\_1NPCOR\\_PLUS\\_UNCOR&$\\pm$0.55\\%&$\\pm$0.55\\%&$\\pm$0.63\\%\\\\\n\\hline\nJET\\_EtaIntercalibration\\_NonClosure&-0.01\\%&-0.03\\%&0\\%\\\\\n\\hline\nJET\\_GroupedNP\\_1&$\\pm$1.97\\%&$\\pm^{11.82\\%}_{10.14\\%}$&$\\pm^{16.21\\%}_{12.92\\%}$\\\\\n\\hline\nJET\\_GroupedNP\\_2&$\\pm$0.23\\%&$\\pm$1.26\\%&+5.3\\%\\\\\n\\hline\nJET\\_GroupedNP\\_3&$\\pm$0.55\\%&$\\pm$2.94\\%&$\\pm^{3.14\\%}_{0.12\\%}$\\\\\n\\hline\nJET\\_JER\\_SINGLE\\_NP&0.11\\%&+5.47\\%&+6.31\\%\\\\\n\\hline\nJET\\_JvtEfficiency&$\\pm$0.04\\%&$\\pm$0.12\\%&$\\pm$0.15\\%\\\\\n\\hline\nMUON\\_EFF\\_ISO\\_STAT&$\\pm$0.09\\%&$\\pm$0.08\\%&$\\pm$0.07\\%\\\\\n\\hline\nMUON\\_EFF\\_ISO\\_SYS&$\\pm$0.54\\%&$\\pm$0.55\\%&$\\pm$0.56\\%\\\\\n\\hline\nMUON\\_EFF\\_RECO\\_STAT&$\\pm$0.15\\%&$\\pm$0.19\\%&$\\pm$0.15\\%\\\\\n\\hline\nMUON\\_EFF\\_RECO\\_STAT\\_LOWPT&$\\pm$0.06\\%&$\\pm$0.02\\%&$\\pm$0.03\\%\\\\\n\\hline\nMUON\\_EFF\\_TTVA\\_STAT&$\\pm$0.06\\%&$\\pm$0.07\\%&$\\pm$0.06\\%\\\\\n\\hline\nMUON\\_EFF\\_TTVA\\_SYS&$\\pm$0.03\\%&$\\pm$0.4\\%&$\\pm$0.03\\%\\\\\n\\hline\nMUON\\_ID&$\\pm$0.03\\%&$\\pm$0.02\\%&$<$0.001\\%\\\\\n\\hline\nMUON\\_MS&-0.05\\%&$\\pm^{0.04\\%}_{0.01\\%}$&$<$0.001\\%\\\\\n\\hline\nMUON\\_SAGITTA\\_RESBIAS&$\\pm$0.01\\%&$\\pm$0.02\\%&$<$0.001\\%\\\\\n\\hline\nMUON\\_SAGITTA\\_RHO&+1.13\\%&-0.73\\%&$\\pm$1.00\\%\\\\\n\\hline\nMUON\\_SCALE&$\\pm$0.02\\%&$\\pm^{0.03\\%}_{0.02\\%}$&$<$0.001\\%\\\\\n\\hline\nPRW\\_DATASF&$\\pm$0.5\\%&$\\pm^{0.42\\%}_{1.02\\%}$&$\\pm^{2.17\\%}_{1.46\\%}$\\\\\n\\hline\n\\hline\nElectron Exp.&$\\pm^{2.8\\%}_{2.7\\%}$&$\\pm^{2.70\\%}_{2.62\\%}$&$\\pm^{2.75\\%}_{2.64\\%}$\\\\\n\\hline\nMuon Exp.&$\\pm$1.3\\%&$\\pm$1.3\\%&$\\pm$1.04\\%\\\\\n\\hline\nJet Exp.&$\\pm$2.0\\%&$\\pm^{13.39\\%}_{10.64\\%}$&$\\pm^{18.54\\%}_{13.57\\%}$\\\\\n\\hline\n\\hline\nTotal experimental uncertainties &$\\pm^{3.7\\%}_{4.0\\%}$&$\\pm^{13.72\\%}_{11.11\\%}$&$\\pm^{18.90\\%}_{13.57\\%}$\\\\\n\\hline\n\\end{tabular}\n\\caption{\nExperimental systematic uncertainties in \\llll channel with the luminosity of 139~\\ifb.\nThe ``Electron Exp.\", ``Muon Exp.\" and ``Jet Exp.\" represent the quadrature of the respective sources from electron, muon, and jets.\n}\n\\label{tab:syst_exp_num}\n\\end{center}\n\\end{table}\n\nIn addition, the uncertainty of the combined 2015 to 2018 integrated luminosity is 1.7\\%~\\cite{ATLAS-CONF-2019-021} in ATLAS experiment,\nobtained using the LUCID-2 detector~\\cite{Avoni_2018} for the primary luminosity measurements.\n\nOn top of them, a systematic uncertainty for MD distribution with different pile-up (<$\\mu$>) is also considered for QCD-$ZZjj$ background\nby comparing the distributions between events with low and high pile-up conditions.\nA boundary of <$\\mu$> = 33 is used to defined low/high pile-up according to the average <$\\mu$> for signal (about 34.5) and QCD background (about 33).\nFigure~\\ref{fig:syst_exp_pu} shows the MD distribution in SR (left) and QCD CR (right) in two different PU conditions, \nthe difference as function of MD is then taken into account as additional shape uncertainty for statistical fit.\n\\begin{figure}[H]\n  \\centering\n  \\includegraphics[width=0.42\\textwidth]{figures/VBSZZ/syst/pu_uncer_BDT_SR.pdf}\n  \\includegraphics[width=0.42\\textwidth]{figures/VBSZZ/syst/pu_uncer_BDT_CR.pdf}\n  \\caption{MD distribution for QCD-$ZZjj$ process in low and high pile-up events for SR (left) and CR (right).}\n  \\label{fig:syst_exp_pu}\n\\end{figure}\n\nMoreover, a conservative uncertainty is assigned to QCD-$ZZjj$ process by comparing the sample modelled by \\textsc{Sherpa} generator (nominal) with \\MGMCatNLO.\nThe MD shape difference for both SR (left) and QCD CR (right) are shown in figure~\\ref{fig:sys_exp_shmg}.\nThe modelling uncertainty is then calculated from the envelop between nominal and alternative samples as function of MD as one additional shape uncertainty.\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=0.42\\textwidth]{figures/VBSZZ/syst/BDT_shape_nor_linear_SR.pdf}\n  \\includegraphics[width=0.42\\textwidth]{figures/VBSZZ/syst/BDT_shape_nor_linear_CR.pdf}\n  \\caption{MD shape difference for QCD \\qqZZ background between different \\textsc{Sherpa} theoretical uncertainties and sample from \\MGMCatNLO on SR (left) and CR (right).}\n  \\label{fig:sys_exp_shmg}\n\\end{figure}\n\n", "meta": {"hexsha": "3b1eb9c63d5463a68dc66df3f632c9d2c62a9208", "size": 10361, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/VBSZZ/syst.tex", "max_stars_repo_name": "zhuhel/PhDthesis", "max_stars_repo_head_hexsha": "55ec32affb5c105143798989d78043467c88da8e", "max_stars_repo_licenses": ["LPPL-1.3c"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/VBSZZ/syst.tex", "max_issues_repo_name": "zhuhel/PhDthesis", "max_issues_repo_head_hexsha": "55ec32affb5c105143798989d78043467c88da8e", "max_issues_repo_licenses": ["LPPL-1.3c"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/VBSZZ/syst.tex", "max_forks_repo_name": "zhuhel/PhDthesis", "max_forks_repo_head_hexsha": "55ec32affb5c105143798989d78043467c88da8e", "max_forks_repo_licenses": ["LPPL-1.3c"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.7892156863, "max_line_length": 223, "alphanum_fraction": 0.6943345237, "num_tokens": 3619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.31694534544051217}}
{"text": "\\documentclass[conference]{IEEEtran}\n\n\\usepackage{cite}\n\\usepackage{graphicx}\n\\usepackage[cmex10]{amsmath}\n\\usepackage{array}\n\\usepackage[font=footnotesize,caption=false]{subfig}\n\\usepackage[hyphens]{url}\n\\usepackage{cprotect}\n\\usepackage{comment}\n\\usepackage{color}\n\\usepackage{amsfonts,amssymb,amsmath}\n\\usepackage{tikz}\n\\usetikzlibrary{calc}\n\\usepackage{booktabs}\n\\usepackage{footmisc}\n\\usepackage{hyperref}\n\\hypersetup{colorlinks=true,linkcolor=blue}\n\n\\newcommand{\\TODO}{{\\color{red} TODO}}\n\\newcommand{\\Z}{\\mathbb{Z}}\n\\newcommand{\\wrt}{w.\\thinspace r.\\thinspace t.\\ }\n\\DeclareMathOperator{\\rmax}{rmax}\n\n\\begin{document}\n\n\\title{Pentago is a First Player Win: Strongly Solving a Game Using Parallel In-Core Retrograde Analysis}\n\\author{\\IEEEauthorblockN{Geoffrey Irving}\\IEEEauthorblockA{Otherlab\\\\San Francisco, CA\\\\irving@naml.us}}\n\n\\maketitle\n\n\\begin{abstract}\n\\boldmath\nWe present a strong solution of the board game pentago, computed using exhaustive parallel\nretrograde analysis in 4 hours on 98304 ($3 \\times 2^{15}$) threads of NERSC's Cray Edison.\nAt $3.0 \\times 10^{15}$ states, pentago is the largest divergent game solved to date by\ntwo orders of magnitude, and the only example of a nontrivial divergent game solved\nusing retrograde analysis.\nUnlike previous retrograde analyses, our computation was performed entirely in-core,\nwriting only a small portion of the results to disk; an out-of-core implementation would\nhave been much slower.  Symmetry was used to reduce branching factor\nand exploit instruction level parallelism.  Despite a theoretically\nembarrassingly parallel structure, asynchronous message passing was required to fit the\ncomputation into available RAM, causing latency problems\non an older Cray machine.  All code and data for the project are\nopen source, together with a website which combines database lookup and on-the-fly computation\nto interactively explore the strong solution.\n\\end{abstract}\n\n\\IEEEpeerreviewmaketitle\n\n\\vspace{-.02in}\n\\section{Introduction}\n\nComputer play of combinatorial games such as chess, checkers, and go has been an active area of research\nsince the early days of computer science \\cite{shannon1950chess}.  The limit of computer play is a solved\ngame, when a computer can play perfectly either from the start position (weakly solved) or from any\nposition (strongly solved).  The first nontrivial weakly solved game was Connect-Four in 1988 by both\nAllen and Allis \\cite{allis1988connectfour}, later strongly solved by Tromp \\cite{tromp1995}.  Many games\nhave been solved since, the most challenging being the weak solution of checkers \\cite{schaeffer2007checkers}.\nThe checkers solution involved 18 years of parallel out-of-core retrograde analysis culminating in a\n$3.9 \\times 10^{13}$ position endgame database together with a $10^{14}$ operation forward search.\n\nTo date, all solved games have been either convergent (fewer positions near the end of the game) or amenable\nto knowledge-based strategies.  Checkers is an example of a convergent game: while the\nentire $10^{20}$ state space is too large to explore fully, the set of positions with 10 or fewer pieces\nhas a more manageable $3.9 \\times 10^{13}$ positions.  Pieces are removed but never added, so a database\nof $\\le 10$ piece positions can be computed via retrograde (backward) analysis starting with 1 piece, then 2 pieces,\nand so on up to 10 pieces.  The computed database is then used to prune a forward search starting from the\nbeginning of the game.\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=.45\\columnwidth]{move-0.pdf}\n\\hspace{.1in}\n\\includegraphics[width=.45\\columnwidth]{move-4.pdf} \\\\\n\\vspace{.1in}\n\\begin{tikzpicture}\n  \\definecolor{win} {rgb}{0,1,0};\n  \\definecolor{tie} {rgb}{0,0,1};\n  \\definecolor{loss}{rgb}{1,0,0};\n  \\tikzstyle{kind}=[circle,draw=gray,inner sep=0pt,minimum size=15]\n  \\node at (-2,0) [kind,label=below:win, fill=win] {};\n  \\node at ( 0,0) [kind,label=below:tie, fill=tie] {};\n  \\node at ( 2,0) [kind,label=below:loss,fill=loss] {};\n\\end{tikzpicture}\n\\end{center}\n\\vspace{-.14in}\n\\cprotect\\caption{(Left) With perfect play, the first player wins with any opening move except the\ncorners, which tie.  (Right) A more delicate position with black to play.\nThe full strong solution can be explored at \\url{http://perfect-pentago.net}.}\n\\label{opening}\n\\vspace{-.04in}\n\\end{figure}\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=\\columnwidth]{counts.pdf}\n\\end{center}\n\\vspace{-.1in}\n\\cprotect\\caption{Counts of pentago positions vs.\\ stones on the board, with symmetries removed.\nRun \\verb+web/counts+ in the source repository to reproduce.}\n\\label{counts}\n\\vspace{-.1in}\n\\end{figure}\n\nIn contrast to convergent games, the number of positions in a divergent game increases with time\n(typically as more stones are added to the board), making traditional retrograde analysis plus forward\nsearch impractical.  Thus, all nontrivial\ndivergent games solved to date have game-specific knowledge based strategies which can be used to avoid brute\nforce: zuzgwang control in Connect-Four \\cite{allis1988connectfour}, threat-space search for gomoku and renju\n\\cite{allis1993gomoku,wagner2001renju}, and H-search in hex \\cite{arneson2011hex}.  For discussion\non the characteristic of various solved games, see \\cite{van2002games}.\n\nPentago is a divergent game designed by Tomas Flod\\'en and sold by Mindtwister \\cite{mindtwister2013pentago}.\nWe reproduce the rules here for completeness.  Pentago is played on a $6 \\times 6$ board, divided into four\n$3 \\times 3$ quadrants. There are two players, black and white, who alternate turns. The goal of each\nplayer is to get five stones of their color in a row, either horizontally, vertically, or diagonally.\nEach turn, a player places a stone in an empty space in some quadrant, then chooses a possibly different\nquadrant to rotate 90 degrees left or right. If both players get five in a row at the same time, or the\nlast move is played with no five in a row, the game is a tie. If a player makes five a row by placing a\nstone, there is no need to rotate a quadrant: the player wins immediately.\n\nUnlike divergent games solved to date, no strong knowledge based strategies are known for pentago, and\nexisting programs are capable of searching only to fairly low depths \\cite{buescher2009pentago,ewalds2012havannah}.\nThis is primarily a consequence of the high branching factor of pentago: there are\n$36 \\cdot 8 = 288$ possible first moves including rotation and an average branching factor of $97.3$ over all\nstates.\\cprotect\\footnote{To reproduce the branching factor average, run \\verb+bin/analyze branch+ in\n\\url{https://github.com/girving/pentago}.  For the rest of the paper, only the command will be given.}\nTo reduce the branching factor to a manageable level, our solver performs all computations in terms of\n\\emph{rotation abstracted positions} consisting of all 256 ways to rotate the quadrants of a given board;\nthis eliminates the factor of 8 due to rotation for an average branching factor of only $12.2$.  Operating\non more than one board at a time lets us take full advantage of SSE acceleration.\n\nUnfortunately, symmetry techniques alone are insufficient to solve pentago on commodity hardware.  The game has\n3,009,081,623,421,558 ($3 \\times 10^{15}$) states with symmetries removed, all but $0.3\\%$ of which are reachable\nwith valid play;\\cprotect\\footnote{Run \\verb+analyze counts+ and \\verb+analyze reachable+, respectively.} the number of\nstates over time is shown in \\autoref{counts}.  To solve the game using retrograde analysis, we traverse all\npositions in reverse order of the number of stones, starting from the 35 stone \\emph{slice} (the 36th is computed\non demand) and iteratively computing the $n$-stone slice from the $(n+1)$-stone slice up to the beginning of the game.\nThis requires storing two adjacent slices at a time, requiring $213$ TB at peak before compression.  Our initial\ntarget was to fit into half of the NERSC Cray Hopper's $217$ TB, which was plausible using fast but weak compression\nonly if minimal memory was wasted communication buffers and working storage.\n\nIn order to minimize working memory, our parallel solver grabs inputs from other processes immediately before\nthey are used, overlapping a small number of work chunks to hide latency.  Since computing each chunk takes a variable\namount of time (see below), we opted for a fully asynchronous communication\npattern: when a process needs an input block, it sends a message to the owner of that block, and the owner\nreplies asynchronously with the data.\n\nThe solver was run exactly once at full scale, generating\na $3.7$ TB database of perfect results with $0$ through $18$ stones and establishing that pentago is a win for\nthe first player to move (\\autoref{opening}).  The full strong solution can be explored online at\n\\url{http://perfect-pentago.net}.\n\nAt $3.0 \\times 10^{15}$ states, pentago is the largest divergent game computation by a factor of\n150 (vs.\\ $2 \\times 10^{13}$ for $9 \\times 6$ Connect-Four), and the largest strongly solved game by a factor of\n660 (vs.\\ $4.5 \\times 10^{12}$ for $7 \\times 6$ Connect-Four).  Among retrograde analyses used to solve games,\nit is the largest by state space by a factor of 77 (vs.\\ $3.9 \\times 10^{13}$ in the solution of Checkers).\nHowever, it is not the largest endgame database over any game: the 7-piece Lomonosov Endgame Tablebases for\nchess are 140 TB in size, and were computed over six months at Moscow State's Lomonosov supercomputer\n\\cite{makhnychev2012chess}.  Unfortunately, the technical details of the Lomonosov computation are unpublished,\nso a detailed comparison is difficult.\n\n\\section{Problem definition}\n\nLet $S$ be the set of arrangements of black and white stones on a $6 \\times 6$ board.  Only some of these are\nvalid pentago positions: if we let black play first, we have equal numbers of black and white stones on black's\nturn and one extra black stone on white's turn.  Define predicates $f_b,f_w : S \\to \\{0,1\\}$ by $f_c(s) = 1$\nif color $c$ has a five in a row.  Given color $c$, let $\\bar{c}$ be the other color.  For $s \\in S$, let\n$p_c(s) \\subset S$ be the positions reached by placing a stone of color $c$, $r(s)$ the positions reached by\nrotating exactly one quadrant $90^\\circ$ left or right.  Let $v_c(s)$ be the value of position $s$ with $c$\nto play: $v_c(s) = -1,0,1$ if $c$ loses, ties, or wins, respectively.  If $f_b(s)$, $f_w(s)$, or $s$ has 36 stones,\nthe game is over and $v_c(s) = f_c(s) - f_{\\bar{c}}(s)$.  Otherwise\n\\begin{align*}\nv_c(s) = \\max_{a \\in p_c(s)} \\begin{cases}\n  1 & \\mbox{if } f_c(a) \\\\\n  \\max_{b \\in r(a)} h_c(b) & \\mbox{otherwise}\n\\end{cases}\n\\end{align*}\nwhere\n\\begin{align*}\nh_c(s) &= \\begin{cases} f_c(s) - f_{\\bar{c}}(s) & \\mbox{if } f_c(s) \\lor f_{\\bar{c}}(s) \\\\\n                        -v_{\\bar{c}}(s) & \\mbox{otherwise} \\end{cases}\n\\end{align*}\n\n\\begin{figure*}[ht!]\n\\begin{center}\n\\begin{tikzpicture}[scale=.7]\n% Show slices\n\\usetikzlibrary[decorations.pathreplacing]\n\\draw [decoration={brace,amplitude=7},decorate] (-13.5,4) -- node [above,yshift=6] {Slice $n+1$} (-6.5,4);\n\\draw [decoration={brace,amplitude=7},decorate] (0,4)     -- node [above,yshift=6] {Slice $n$} (9,4);\n% Horizontal compute\n\\begin{scope}[shift={(-5,0)}]\n  \\filldraw[draw=black,fill=red!10!white,rounded corners=10] (-.5-3.5,-.5) rectangle (4+5,3.5);\n  \\node at (3.5/2,3) {Compute};\n  \\filldraw[draw=black,fill=green!50!white] (0,1.5) rectangle (3.5,1+1.5);\n  \\filldraw[draw=black,fill=blue!30!white] (.5,0) rectangle (2.5+.5,1);\n  \\pgfmathsetseed{1138};\n  \\foreach \\y in {1/3,2/3}\n    \\foreach \\i in {0,...,3}\n      \\foreach \\j in {0,1}{\n        \\pgfmathrnd \\pgfmathsetmacro{\\v}{\\pgfmathresult};\n        \\draw[->] (2.5*\\v+.5,\\y) -- (3.5*\\i/4+3.5*.5/4,\\y+1.5);\n      }\n\\end{scope}\n\\draw[->,very thick] (3.5-5,1.5+.5) -- (0,1.5);\n% Output block with contributing lines\n\\fill[white] (0,0) rectangle (3.5,2.5);\n\\fill[green!50!white] (0,1) rectangle (3.5,2);\n%\\fill[green!50!black] (1,1) rectangle (2,2);\n% Output section\n\\node at (3.5/2,3) {Scatter};\n\\draw[step=1] (0,0) grid (3.5,2.5);\n\\draw (0,2.5) -- (3.5,2.5) -- (3.5,0);\n\\foreach \\x in {.5,2.5,3.25}{\n  \\draw[->,very thick] (\\x,1) -- (\\x,1-1.75);\n  \\node at (\\x,1-1.75-.125) {$\\vdots$};\n}\n% Horizontal input section\n\\begin{scope}[shift={(-8.5,0)}]\n  % Rotated line\n  \\fill[white] (0,0) rectangle (1,2.5);\n  \\fill[blue!30!white] (1,0) rectangle (2,2.5);\n  \\draw[->,very thick] (2,1.25) -- node [above] {$\\curvearrowright$} node [below,sloped] {rotate} (3.5+.5,.5);\n  % Section\n  \\node at (2/2,3) {Gather};\n  \\draw[step=1] (0,0) grid (2,2.5);\n  \\draw (0,2.5) -- (2,2.5);\n\\end{scope}\n% Input blocks\n\\pgfmathsetmacro{\\sx}{3.75}\n\\pgfmathsetmacro{\\sy}{.4}\n\\begin{scope}[shift={(-\\sx-8.5,-\\sy)}]\n  \\begin{scope}[shift={(0,2.5)}]\n    \\filldraw[draw=black,fill=red!10!white,rounded corners=5] (-.25,-.25) rectangle (1.25,1.5) ;\n    \\node at (.5,1) {Input};\n    \\filldraw[draw=black,fill=blue!30!white] (0,0) rectangle +(1,.5);\n  \\end{scope}\n  \\begin{scope}[shift={(1,0)}]\n    \\filldraw[draw=black,fill=red!10!white,rounded corners=5] (-.25,-.25) rectangle (1.25,2);\n    \\node at (.5,1.5) {Input};\n    \\filldraw[draw=black,fill=blue!30!white] (0,0) rectangle +(1,1);\n  \\end{scope}\n  \\begin{scope}[shift={(-1,0)}]\n    \\filldraw[draw=black,fill=red!10!white,rounded corners=5] (-.25,-.25) rectangle (1.25,2);\n    \\node at (.5,1.5) {Input};\n    \\filldraw[draw=black,fill=blue!30!white] (0,0) rectangle +(1,1);\n  \\end{scope}\n  \\draw[->,very thick] (1-1,.5) -- (1-1+\\sx+1,1+.5+\\sy);\n  \\draw[->,very thick] (1+1,.5) -- (1-1+\\sx+1,.5+\\sy);\n  \\draw[->,very thick] (1,.5+2.25) -- (1-1+\\sx+1,2+.25+\\sy);\n\\end{scope}\n\\pgfmathsetmacro{\\sx}{4.5}\n\\pgfmathsetmacro{\\sy}{0}\n\\begin{scope}[shift={(\\sx,\\sy)}]\n  \\begin{scope}[shift={(1,0)}]\n    \\filldraw[draw=black,fill=red!10!white,rounded corners=10] (-.5,-.5) rectangle (4,3.5);\n    \\node at (3.5/2,3) {Combine};\n    \\fill[white] (0,0) rectangle (3.5,2.5);\n    \\fill[green!50!black] (1,1) rectangle (2,2);\n    \\draw[step=1] (0,0) grid (3.5,2.5);\n    \\draw (0,2.5) -- (3.5,2.5) -- (3.5,0);\n  \\end{scope}\n  \\draw[->,very thick] (2-\\sx,1.5) -- (2,1.5);\n  \\draw[->,very thick] (2.5,1-1.75) -- (2.5,1);\n  \\node at (2.5,1-1.75-.175) {$\\vdots$};\n\\end{scope}\n\\end{tikzpicture}\n\\end{center}\n\\vspace{-.2in}\n\\caption{We decompose the set of pentago position into sections, each a 4D array of blocks (shown here as\n2D).  The results for a given block are the combination of results from each block line that contains it,\nwith each such block line depending on exactly one block line from a different section.  Each computation\nfrom input line to output line can be performed on a different processor, first gathering the input blocks\ntogether into a complete line, and finally scattering the output blocks to their owners.  Each pink rounded\nrectangle lies in a possibly different process.  Since we compute only those sections which\nare unique with symmetries removed, some input lines must be rotated before computation.}\n\\label{lines}\n\\vspace{-.1in}\n\\end{figure*}\n\n\\section{Abstracting over rotations}\n\nThe exact symmetry group of pentago is the 8 element dihedral group $D_4$ with 4 global reflections and\n4 global rotations.  Computing only one element from each $D_4$ equivalence class saves a factor of $8$,\nbut does nothing for the large branching factor of the game.  Thus, we consider the \\emph{local} group of\nall 256 ways to rotate the four quadrants, which has the abelian group structure\n$L = \\Z_4 \\times \\Z_4 \\times \\Z_4 \\times \\Z_4$.\nCombined with the group of global symmetries, the full group of \\emph{approximate symmetries} is a semidirect product\n$G = \\Z_4^4 \\rtimes D_4$ with $2048$ elements.\n\nComputing one board $b$ from each equivalence class \\wrt $G$ is not enough; we must compute a function\n$$f_b : L \\to \\{-1,0,1\\}$$\nmapping $g \\in L$ to the result of the quadrant rotated board $gb$.  Each board is a win,\nloss, or tie, so there are $3^{256}$ such functions.  To avoid ternary arithmetic we use 2 bits per value for\nuncompressed data: one bit for win vs. loss/tie and one for win/tie vs. loss.  Thus, for each board we have two\nfunctions $\\Z_4^4 \\to \\{0,1\\}$, each a $4 \\times 4 \\times 4 \\times 4$ array of bits.  Each such function\n$L \\to \\{0,1\\}$ is packed into a 256 bit table.\n\nSince quadrant rotations do not change the equivalence class \\wrt $G$, operating on these functions $f_b$ removes\nthe branching factor due to rotations.  In its place, we have the mixing operation\n\\begin{align*}\n\\rmax &: \\left(L \\to \\{0,1\\}\\right) \\to \\left(L \\to \\{0,1\\}\\right) \\\\\n\\rmax&(f)(g) = \\max_{r \\in R} f(g+r)\n\\end{align*}\nwhere $R \\subset L$ is the set of $90^\\circ$ degree rotations left or right, and we use $+$ because the\ngroup $L$ is abelian.  In addition to $\\rmax$, two other rotation abstracted routines are needed.\nFirst, given the position of stones of one color, we must be able to compute the set of rotations\n$g \\in L$ which produce five in a row.  Second, our equivalence class representative \\wrt $G$ can change\nwhen we add a stone, so we must be able to transform $f_b$ into $f_{gb}$ for any $g \\in G$; this\ninvolves cyclic shifts, dimension transpositions, and reflections of $4 \\times 4 \\times 4 \\times 4$ bit tables.\n\nAlthough the code required for these operations is complex, verifying their correctness was a\nstraightforward process of checking group theoretic definitions against the much simpler routines\noperating on one board at a time.  The ease of verification frees us to make the routines as complicated as required\nfor speed without reducing confidence in the code.\n\n\\section{Data layout and distribution}\n\nGiven a board $b$, we must choose a unique representative out of the equivalence class $Gb$.  This choice\nshould be made such that adding a stone changes the representative choice in as few ways as possible, so\nthat the effective branching factor will be smaller once we take data layout into account.\nConcretely, since we have eliminated\nbranching factor due to rotation, an average board has $12.2$ child boards which are needed as input; if\nrepresentatives were chosen arbitrarily, the representatives of the child equivalent classes \\wrt $G$\nmight be located in up to $12.2$ processes depending on how data is distributed.\n\n\\begin{figure}\n\\begin{center}\n\\input{section.tex}\n\\end{center}\n\\vspace{-.15in}\n\\caption{Each section is a 4D array of functions $f_{abcd} : L \\to \\{-1,0,1\\}$.  Each dimension\ncorresponds to all patterns of stones in one of the four quadrants with fixed counts of black and white\nstones, including only patterns lexicographically minimal under rotation.  For each $(a,b,c,d)$\ndescribing the four quadrants of a board, $f_{abcd}$ gives the loss/tie/win values for all 256 ways to rotate the\nfour quadrants.  The order is chosen so that reflected pairs are adjacent so that\nreflection preserves the block structure.  The figure shows 2D slices of the full 4D array.}\n\\label{section}\n\\vspace{-.1in}\n\\end{figure}\n\nTherefore, we partition all boards in a given slice (fixed number of stones) into \\emph{sections} defined by the\nnumbers of stones of each color in the four quadrants, computing only sections whose counts are lexicographically\nminimal under $D_4$ symmetry.  Within a given section, we consider only boards whose quadrants are lexicographically\nminimal under per-quadrant rotations; each quadrant is independent under this requirement, so the section becomes\na four dimensional rectangular array where each dimension defines the stones in one quadrant.  We precompute an\nordering of these rotation minimal quadrant states so that we can convert from a position in the four dimensional\nsection array to a board state using table lookup.  The structure of one such section is shown in \\autoref{section}.\nThere are at most four quadrants to chose from when placing a stone (some may be full near the end of the game),\nso at most four child sections contribute to the results for a given parent.  In other words, we have reduced the\neffective branching factor from $12.2$ to $4$.\n\nSections alone provide insufficiently fine parallelism (the largest is $1.8$ TB uncompressed), so we\ndivide each 4D section array into $8 \\times 8 \\times 8 \\times 8$ blocks and partition the blocks for all\nsections among the different processes.  When a stone is added in a quadrant, we move to a child section with\nindex layout different from the parent only for the quadrant where the stone was added\nsince the other quadrants have the same pattern of stones.  Therefore, a single block in a parent section depends\non inputs from one \\emph{line} of blocks in up to four child sections.  Since the different input lines for a block\ncorrespond to moves in different quadrants, we can compute each line contribution separately on different processes\nand combine them with $\\max$ on whichever process owns the output block.\n\nThe structure of the computation is illustrated in \\autoref{lines}.  Say we want to compute an output block line\nin section $n$, which is a $k \\times 1 \\times 1 \\times 1$ grid of blocks (possibly transposed) corresponding to\nan $8k \\times 8 \\times 8 \\times 5$ grid of boards (block sizes may differ from $8$ at section boundaries).\nOur output block line depends on a single input block line in section $n+1$, which (possibly after rotation) is an\n$8k' \\times 8 \\times 8 \\times 5$ grid of nodes.  The input and output block lines differ in size only along the\nlong dimension, since the long dimension corresponds to the quadrant where we will place a stone.  When we\ncompute index $(a,b,c,d)$ of the output line, we mix together several indices $(a',b,c,d)$ with different $a'$\ncorresponding to the different places to put a stone in the lines' quadrant.  Since the map from\n$a$ to $a'$ is many to many, computing the entire block line on a single processor gives an effective\nbranching factor of $4$ for communication cost even though the underlying branching factor is $12.2$.\nOnce the block line is computed, its component blocks are scattered to their owners to be merged together\nvia $\\max$ with other contributions (each block needs up to four such block line contributions).\n\nSince our block structure is symmetric \\wrt dimension and our quadrant positions are always minimal with respect\nto rotation, the block structure of sections is preserved when the board is rotated.  However, the ordering of\nquadrant states does change when a quadrant is reflected, since a lexicographically least quadrant may no longer\nbe lexicographically least after reflection.  To maintain the block structure, we require even sized blocks\n(8 in our case) and adjust our precomputed quadrant state ordering so that reflected pairs occur next to each\nother in the same block.  With this trick, the block structure is invariant to all symmetries.\n\nThe relatively simple structure of sections, blocks, and rotation-abstracted values within blocks does have\na cost: if a position or section is preserved by a symmetry it will be double counted in the data layout.\nAbstracting over rotations increases the number of effective positions by 5.4\\% and removing symmetries only\nat the section level costs an additional 9.3\\%, for a total overcounting of 15.2\\% relative to storing each\nsymmetry-unique position once.\\cprotect\\footnote{Run \\verb+analyze ratio+.}\n\n\\subsection{Deterministic pseudorandom partitioning}\n\nIn parallel, we must partition the set of blocks across processes to balance memory usage and the\nset of block lines across processes to balance compute.  Ideally, the process computing a given block line\nwould also own many of the input and output blocks in order to minimize communication.  Unfortunately, these\ndesires couple together the partition for all slices.  Over all slices, there are 3,654,002,393 blocks and\n996,084,744 block lines.\\cprotect\\footnote{Run \\verb+analyze approx+.}  Thus, we have a graph partitioning\nproblem with 4,650,087,137 nodes divided into 72 clusters, each cluster defining a load balancing constraint.\nAlthough existing graph partitioning codes such as ParMETIS\\cite{schloegel2002parmetis} might be sufficient\nfor our problem, we have sufficient computation to hide communication latency and opt for a\nsimple randomized partitioning scheme instead.\n\nWe partition each slice independently.  Since there are at most 8239 sections to a slice, and\neach section is a regular 4D grid of blocks, we can define an ordering of all block lines\nby arranging the sections back to back.  We choose a pseudorandom permutation of the ordered block\nlines and give each process a contiguous chunk of the scrambled ordering.  Each block is then randomly\nassigned to one of its four lines, and given to the process which owns that line.  In both cases, these choices\ncan be made consistently with only an $O(1)$ size random seed shared between processes: we use the arbitrary size\ncipher technique of \\cite{black2002ciphers} for random access random permutations and the Threefry generator\nof \\cite{salmon2011parallel} for conventional random numbers.  Since the cipher permutations are invertible,\nwe can find the process owning a given block or block line in $O(1)$ time.\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=\\columnwidth]{balance.pdf}\n\\end{center}\n\\vspace{-.1in}\n\\cprotect\\caption{Load balance ratio ($\\max/\\min$) for various quantities as a function of stones on the board using\ndeterministic pseudorandom partitioning.  89\\% of the computation occurs from slice $20$ to $28$, where\nall quantities balance to within 20\\%.  Run \\verb+paper/numbers load+ to reproduce.}\n\\label{balance}\n\\vspace{-.1in}\n\\end{figure}\n\nAt scale, a pseudorandom partitioning scheme automatically balances any quantity where the central limit\ntheorem applies.  In particular, though our scheme does not explicitly account for the different amounts of\nwork required to compute different block lines, or the different sizes of blocks at the boundary of sections,\nthere are enough blocks and block lines to keep the $\\max/\\min$ ratio to within 10-20\\% for all large slices and\nall relevant quantities (\\autoref{balance}).\n\n\\subsection{Compression}\n\nSince our uncompressed memory usage would be at least $213$ TB, we compress all data in memory until needed\nusing the fast but weak compression library Snappy \\cite{snappy2014}.  Most blocks are $256$ KB\n($64 \\cdot 8^4$ bytes) uncompressed, large enough to compress each block separately without harming compression ratio.\nDespite its speed relative to stronger compression such as ZLIB or LZMA\\cite{deutsch1996zlib,xz2014}, Snappy still consumed about 29\\% of our\ncompute time ignoring I/O.\\cprotect\\footnote{See \\verb+snappy fraction+ in \\verb+paper/numbers+.}  Stronger\ncompression is thus out of reach for in memory purposes, although we do use LZMA when writing\nout the smaller final data set.\n\nWith compression the memory usage varies unpredictably, with two consequences.  First, repeatedly\nallocating and deallocating irregular block sizes results in significant fragmentation.  During early testing on\nBlueGene, which has no virtual memory system, fragmentation caused the code to run out of memory much earlier\nthan necessary.  We solved this with a manual compacting garbage collector for bulk data storage, which is\nstraightforward in our case due to the lack of pointers.  Second, estimates from slices near the end of the game\ngave a compression ratio of roughly $1/3$.  Since we were uncertain whether this ratio should grow or shrink at\nthe peak of the computation, and wanted a high probability of solving the game in a single run, we used a\nconservative estimate of $0.4$ when determining how many nodes to use.  However, the actual average compression\nratio was $0.26$.\\cprotect\\footnote{See \\verb+total data+ in \\verb+paper/numbers+.}  Taking advantage\nof the unexpectedly good compression would have required dynamic partitioning, or even (ideally) a dynamic\nnumber of MPI nodes.\n\n\\section{Asynchronous control flow}\n\n\\begin{figure*}\n\\begin{center}\n\\begin{tikzpicture}\n  \\node[anchor=south west,inner sep=0] (full) at (0,0) {\\includegraphics[height=2.0in]{tiny-history.png}};\n  \\begin{scope}[x={(full.south east)},y={(full.north west)}]\n    \\foreach \\i in {0,...,15}{\n      \\node at (0,\\i/16+1/32) [left,scale=.5] {\\i};\n    }\n    \\node at (-.04,.5) [rotate=90,scale=.8] {Process rank}; \n    \\foreach \\j in {0,20,...,260}{\n      \\draw (\\j/263.473,0) -- +(0,-.01);\n      \\node at (\\j/263.473,-.01) [below,scale=.5] {\\j};\n    }\n    \\node at (.5,-.1) [scale=.8] {Time (s)}; \n    % Legend (generated by paper/history)\n    \\begin{scope}[shift={(.4,0)}]\n      \\filldraw[draw=black,fill=white] (0,1) rectangle +(0.16,-0.260417);\n      \\definecolor{compute}{rgb}{0,1,0.571429};\n      \\fill[compute] (0.0025,1-0.00520833) rectangle +(0.05,-0.03125);\n      \\node [right,scale=.5,anchor=base west] at (0.0525,1-0.0302083) {compute};\n      \\definecolor{snappy}{rgb}{1,0.857143,0};\n      \\fill[snappy] (0.0025,1-0.0364583) rectangle +(0.05,-0.03125);\n      \\node [right,scale=.5,anchor=base west] at (0.0525,1-0.0614583) {snappy};\n      \\definecolor{wait}{rgb}{1,0,0};\n      \\fill[wait] (0.0025,1-0.0677083) rectangle +(0.05,-0.03125);\n      \\node [right,scale=.5,anchor=base west] at (0.0525,1-0.0927083) {wait};\n      \\definecolor{unsnappy}{rgb}{0,0.571429,1};\n      \\fill[unsnappy] (0.0025,1-0.0989583) rectangle +(0.05,-0.03125);\n      \\node [right,scale=.5,anchor=base west] at (0.0525,1-0.123958) {unsnappy};\n      \\definecolor{compact}{rgb}{0.285714,0,1};\n      \\fill[compact] (0.0025,1-0.130208) rectangle +(0.05,-0.03125);\n      \\node [right,scale=.5,anchor=base west] at (0.0525,1-0.155208) {compact};\n      \\definecolor{count}{rgb}{0.285714,1,0};\n      \\fill[count] (0.0025,1-0.161458) rectangle +(0.05,-0.03125);\n      \\node [right,scale=.5,anchor=base west] at (0.0525,1-0.186458) {count};\n      \\definecolor{accumulate}{rgb}{1,0,0.857143};\n      \\fill[accumulate] (0.0025,1-0.192708) rectangle +(0.05,-0.03125);\n      \\node [right,scale=.5,anchor=base west] at (0.0525,1-0.217708) {accumulate};\n      \\definecolor{other}{rgb}{0.5,0.5,0.5};\n      \\fill[other] (0.0025,1-0.223958) rectangle +(0.05,-0.03125);\n      \\node [right,scale=.5,anchor=base west] at (0.0525,1-0.248958) {other};\n    \\end{scope}\n    % Draw zoom rectangle\n    \\filldraw[draw=black,fill=white] (0.8730960728423784,0) rectangle (0.8752302148607257,1);\n    \\coordinate (fromleft) at (0.8730960728423784,1);\n    \\coordinate (fromright) at (0.8752302148607257,1);\n  \\end{scope}\n  % full sizes = 263.473 96\n  % box = Box((230.03724159999999,0),(230.59953039999999,96))\n  \\begin{scope}[shift={(11.5,0)}]\n    \\node[anchor=south west,inner sep=0] (image) at (0,0) {\\includegraphics[height=2.0in]{tiny-history-graph.png}};\n    \\begin{scope}[x={(image.south east)},y={(image.north west)}]\n      \\draw (0,0) rectangle (1,1);\n      \\draw (0.498646,0.536458) -- (0.428306,0.536458); \\draw (0.428306,0.536458) -- (0.211131,0.505208); \\draw (0.428306,0.536458) -- (0.339567,0.505208); \\draw (0.428306,0.536458) -- (0.338751,0.505208); \\draw (0.428306,0.536458) -- (0.210792,0.505208); \\draw (0.428306,0.536458) -- (0.211169,0.505208); \\draw (0.211169,0.505208) -- (0.18248,0.880208); \\draw (0.18248,0.880208) -- (0.0833778,0.505208); \\draw (0.0833778,0.505208) -- (0.0833333,0.505208); \\draw (0.210792,0.505208) -- (0.128093,0.817708); \\draw (0.128093,0.817708) -- (0.0833716,0.505208); \\draw (0.0833716,0.505208) -- (0.0833333,0.505208); \\draw (0.338751,0.505208) -- (0.121249,0.0677083); \\draw (0.121249,0.0677083) -- (0.0833653,0.505208); \\draw (0.0833653,0.505208) -- (0.0833333,0.505208); \\draw (0.339567,0.505208) -- (0.143496,0.317708); \\draw (0.143496,0.317708) -- (0.0833556,0.505208); \\draw (0.0833556,0.505208) -- (0.0833333,0.505208); \\draw (0.211131,0.505208) -- (0.182467,0.880208); \\draw (0.182467,0.880208) -- (0.0833449,0.505208); \\draw (0.0833449,0.505208) -- (0.0833333,0.505208); \\draw (0.498646,0.536458) -- (0.658716,0.515625); \\draw (0.658716,0.515625) -- (0.722719,0.505208); \\draw (0.658716,0.515625) -- (0.722741,0.505208); \\draw (0.658716,0.515625) -- (0.722758,0.505208); \\draw (0.658716,0.515625) -- (0.722817,0.505208); \\draw (0.658716,0.515625) -- (0.722873,0.505208); \\draw (0.658716,0.515625) -- (0.722928,0.505208); \\draw (0.658716,0.515625) -- (0.723026,0.505208); \\draw (0.658716,0.515625) -- (0.723078,0.505208); \\draw (0.658716,0.515625) -- (0.723085,0.505208); \\draw (0.658716,0.515625) -- (0.723096,0.505208); \\draw (0.658716,0.515625) -- (0.723151,0.505208); \\draw (0.658716,0.515625) -- (0.723251,0.505208); \\draw (0.658716,0.515625) -- (0.723351,0.505208); \\draw (0.658716,0.515625) -- (0.723405,0.505208); \\draw (0.658716,0.515625) -- (0.723461,0.505208); \\draw (0.658716,0.515625) -- (0.723518,0.505208); \\draw (0.658716,0.515625) -- (0.723526,0.505208); \\draw (0.658716,0.515625) -- (0.723577,0.505208); \\draw (0.658716,0.515625) -- (0.723631,0.505208); \\draw (0.658716,0.515625) -- (0.723639,0.505208); \\draw (0.723639,0.505208) -- (0.777085,0.880208); \\draw (0.777085,0.880208) -- (0.826283,0.901042); \\draw (0.723631,0.505208) -- (0.782422,0.380208); \\draw (0.782422,0.380208) -- (0.8089,0.432292); \\draw (0.723577,0.505208) -- (0.72372,0.505208); \\draw (0.72372,0.505208) -- (0.789167,0.515625); \\draw (0.723526,0.505208) -- (0.811573,0.942708); \\draw (0.811573,0.942708) -- (0.863152,0.953125); \\draw (0.723518,0.505208) -- (0.811551,0.442708); \\draw (0.811551,0.442708) -- (0.884799,0.484375); \\draw (0.723461,0.505208) -- (0.723717,0.505208); \\draw (0.723717,0.505208) -- (0.792687,0.515625); \\draw (0.723405,0.505208) -- (0.811528,0.442708); \\draw (0.811528,0.442708) -- (0.888,0.484375); \\draw (0.723351,0.505208) -- (0.723712,0.505208); \\draw (0.723712,0.505208) -- (0.795999,0.515625); \\draw (0.723251,0.505208) -- (0.723674,0.505208); \\draw (0.723674,0.505208) -- (0.810391,0.536458); \\draw (0.723151,0.505208) -- (0.7237,0.505208); \\draw (0.7237,0.505208) -- (0.806281,0.515625); \\draw (0.723096,0.505208) -- (0.811523,0.442708); \\draw (0.811523,0.442708) -- (0.891369,0.484375); \\draw (0.723085,0.505208) -- (0.782361,0.380208); \\draw (0.782361,0.380208) -- (0.812741,0.432292); \\draw (0.723078,0.505208) -- (0.774176,0.880208); \\draw (0.774176,0.880208) -- (0.843946,0.890625); \\draw (0.723026,0.505208) -- (0.723705,0.505208); \\draw (0.723705,0.505208) -- (0.802709,0.515625); \\draw (0.722928,0.505208) -- (0.723708,0.505208); \\draw (0.723708,0.505208) -- (0.799383,0.515625); \\draw (0.722873,0.505208) -- (0.780705,0.0677083); \\draw (0.780705,0.0677083) -- (0.794775,0.119792); \\draw (0.722817,0.505208) -- (0.723695,0.505208); \\draw (0.723695,0.505208) -- (0.916667,0.515625); \\draw (0.722758,0.505208) -- (0.761403,0.192708); \\draw (0.761403,0.192708) -- (0.795137,0.203125); \\draw (0.722741,0.505208) -- (0.732447,0.255208); \\draw (0.732447,0.255208) -- (0.739917,0.296875); \\draw (0.722719,0.505208) -- (0.811442,0.942708); \\draw (0.811442,0.942708) -- (0.86977,0.994792);\n      \\coordinate (toleft) at (0,1);\n      \\coordinate (toright) at (1,1);\n      \\foreach \\i in {230.1,230.2,230.3,230.4,230.5}{\n        \\draw (\\i/.5622888-409.1087026809,0) -- +(0,-.015);\n        \\node at (\\i/.5622888-409.1087026809,-.015) [below,scale=.5] {\\i};\n      }\n      \\node at (.5,-.1) [scale=.8] {Time (s)};\n    \\end{scope}\n  \\end{scope}\n  \\draw plot [smooth,tension=1] coordinates { (fromleft) ($ .5*(fromleft) + .5*(toleft) + (0,.12) $) (toleft) };\n  \\draw plot [smooth,tension=1] coordinates { (fromright) ($ .5*(fromright) + .5*(toright) + (0,.5) $) (toright) };\n\\end{tikzpicture}\n\\end{center}\n\\vspace{-.15in}\n\\cprotect\\caption{Images from a trace visualization tool used to diagnose performance problems in asynchronous\ncode.  (Left) The history of a 16 process, 96 thread run computing the section with four stones of\neach color in each quadrant.  Each process has one communication thread (mostly red for waiting) and five worker\nthreads performing computation, with colors showing the type of computation performed.  (Right) A zoom showing the\ninformation flow related to part of a block line computation.  At the leftmost point in the graph shown, the process\ndecides to compute a given block line, and sends out requests for input data to other processes.\nOnce all responses arrive, the computation begins.  When the computation finishes, the results are scattered to\nother processes and compressed for storage.  To reproduce, run \\verb+paper/history+.}\n\\label{history}\n\\vspace{-.1in}\n\\end{figure*}\n\nWithin slice $n$, each process can compute its allocation of block lines in any order, since all inputs\nare from slice $n+1$ which has already been computed.  However, most of these inputs are stored on other\nprocesses, and due to memory limitations only a small fraction of them can be stored locally at any given time.\nMoreover, the time to compute a given block line varies with size, ruling out a lockstep\ncommunication/compute cycle.  Instead, we use an asynchronous control flow where each process sends\nrequests for input data for at most five block lines at time, begins computing as soon as all inputs for a\nblock line are in place, sends out output data when ready, and listens for incoming output data from other\nprocesses to be merged.\n\nWe emphasize that asynchrony is needed only because of the memory constraint: if we had 4 times as much memory\nin order to store all inputs locally, we could split the computation into communication / compute epochs and\nuse an embarrassingly parallel control flow during compute.\n\nWe use a hybrid MPI/Pthread model where each 6 thread process has 1 communication thread and 5 worker threads\n(with 8 processes per 48-hyperthread Edison node).\nA hybrid structure reduces the memory usage by allowing several threads to share the same temporary storage\nrequired when computing a block line.  The communication thread must simultaneously listen for\nincoming remote messages and completed tasks from the worker threads; this can be done with self-to-self MPI\nmessages in environments which support \\verb+MPI_THREAD_MULTIPLE+ but requires alternatively polling between\n\\verb+MPI_Testsome+ and \\verb+pthread_spin_trylock+ if only \\verb+MPI_THREAD_FUNNELED+ is available.\n\nAt the time the code was written, the MPI 3 standard was not yet available on the target machine, and the\none sided communication primitives in MPI 2 were not sufficient for our communication\npattern.\\footnote{For more discussion, see \\url{http://scicomp.stackexchange.com/questions/2846/simulating-the-mpi-isend-irecv-wait-model-with-one-sided-communication}.}\nSpecifically, the MPI 2 one sided primitives provide no asynchronous way to know when a request completes; and\nour only synchronization points are between entire slices.  MPI 3 solves this problem:\nafter an initial communication phase exchanging pointers to the required compressed slice $n+1$ blocks, all\ninput requests during slice $n$ computation could be handled with \\verb+MPI_Rget+\\cite{mpi-3:2012}.\nUnfortunately, MPI 3 does\nnot solve the reverse problem of output messages: when an output block arrives, any previous data for that\nblock must be uncompressed, combined with the new data, and recompressed for storage.  \\verb+MPI_Accumulate+ has\nno support for user defined operations, so output messages would still be limited to two sided communication.\nFinally, MPI 3 provides the useful \\verb+MPI_Ibarrier+ primitive which is exactly what we need to know when\nall processes have finished computing and thus when the previous slice can be deallocated; since we use MPI 2\nwe must simulate \\verb+MPI_Ibarrier+ using a manual tree reduction.\n\nThe asynchronous control flow was tricky to write but straightforward to debug,\nsince most bugs manifested as deadlocks.  Each message and response is labeled with a unique global id,\nso deadlocks were easy to eliminate by reading traces of events.  However, the performance\ncharacteristics of the code were harder to understand, since high latency might be a result of\nunrelated communication at the same time.  Existing profiling tools such as TAU\n\\cite{shende2006tau} were insufficient for tracing the dependencies between asynchronous messages\ncombined with control flow across threads.  Thus, we wrote a custom trace visualizer with\nknowledge of the information flow between inputs through compute to output; an example visualization is\nshown in \\autoref{history}.  On NERSC's Cray XE6 Hopper, this tool confirmed that long idle periods\nwere due to high latency, but was not sufficient to diagnose the underlying cause of the problem.\nUnfortunately, we still do not know the cause of this latency.  Testing on the Argonne's BlueGene/Q Vesta\nwas inconclusive since the code easily saturated BlueGene's poor integer performance.  On the newer Cray\nEdison used for the final production run, the problem went away: worker threads were idle only\n16.4\\% of the time with I/O excluded.\\cprotect\\footnote{See \\verb+Idle vs. total time+ in\n\\verb+paper/numbers+\\label{idle}.}\n\n\\section{Performance}\n\nOur final production job ran on NERSC's Cray XC30 Edison, using 98304 ($3 \\times 2^{15}$) threads\nincluding hyperthreading (49152 cores, 2048 nodes).  The bulk of the computation from slice $35$ down\nto $19$ took $2.7$ hours.  Starting at slice $18$ we began writing output results to disk, though our\nfirst computation finished writing only slices $17$ and $18$ before hitting an unfortunately chosen\nwall clock limit of $4$ hours.  Two smaller jobs on 192 and 128 nodes were used to finish the computation\ndown to slice $0$, the start of the game.\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=\\columnwidth]{profile.pdf}\n\\end{center}\n\\vspace{-.1in}\n\\cprotect\\caption{Time profile of the main production run, showing total worker thread time usage over\nall processes.  All game logic is contained in the \\emph{compute} (green) section; the other sections are\noverhead due to load imbalance, non-hidden communication latency, compression/decompression, and I/O.\nSlices 17 and 18 include LZMA compression and final I/O.  During I/O, all workers are idle and the communication\nthread on each process is inside MPI/IO.}\n\\label{profile}\n\\vspace{-.12in}\n\\end{figure}\n\nThe time profile of the computation is shown in \\autoref{profile}.  Excluding I/O, only 16.4\\% of the\ntotal worker thread time is spent idle,\\footref{idle}\nconfirming that our random load balancing scheme is sufficient for near peak performance.  Since only 5\nout of 6 threads per rank are workers, we could theoretically speed up the computation by up to 6/5 if\nthe communication thread performed useful work.  Unfortunately, existing MPI implementations do not\nimplement performant asynchronous progress, even ignoring our need for active responses to messages\n(see \\cite{squyres2012progress} for a good discussion).\n\nIncluding I/O, our performance is further from optimal: 51.0\\% of worker thread time is\nidle, with 34.6\\% due entirely to I/O.  This is due to both very high latency when\nwriting small files during every slice (around 200 seconds independent of file size) and low bandwidth\nwhen writing file results in slices 17 and 18.  The high latency was a consequence of\nusing \\verb+MPI_File_write_ordered+ when writing small files, since MPICH and thus Cray MPI\nimplement this routine using shared files for synchronization rather than fast network collectives.\nUnfortunately, the low bandwidth is likely user error: we accidentally wrote to NERSC's\nglobal scratch filesystem rather than the special filesystem optimized for Edison.\n\nSince much of the complexity of our implementation derives from the memory constrained in core\nstructure, it is important to estimate how much slower the computation would have been if run out of core.\nEdison's peak I/O bandwidth is 168 GB/s, or 66 GB/s on our 2048 out of 5192 nodes if bandwidth is shared\nproportionally.  An out of core version of our algorithm would write each block once and read each block\nfour times, for a total of 3.6 PB of I/O uncompressed or 0.94 PB with Snappy compression.  Thus, at peak I/O\nbandwidth, a Snappy compressed out of core version of our code would take 4.0 hours for\nI/O.\\cprotect\\footnote{See \\verb+Total I/O time estimates+ in \\verb+paper/numbers+.}  In contrast,\nthe non-I/O portion of our main run took 1.8 hours, for a speedup of 2.25.  If peak I/O performance could\nnot be achieved, or I/O and compute could not be fully overlapped, the speedup would be larger.\n\nThe rotation abstracted compute kernel uses SSE for instruction level parallelism, packing\neach 256-bit $L \\to \\{0,1\\}$ function into two 128 bit SSE registers.  $\\rmax$ can be computed for one such\ntable in $152$ SSE instructions, or $3/5$ths of an instruction per position since each function\nencodes $256$ positions.  Computing which of the 256 quadrant rotations of a board give five in\na row takes $190$ instructions and $640$ bytes of cache coherent table lookup, and transforming a\nfunction $f_b$ into $f_{gb}$ takes between $60$ and $200$ instructions dependent on the particular $g \\in G$.\nAlthough bit-level representations of board state are standard in computational games,\nwe believe this is the first instance where values of many distinct positions are evaluated in parallel\nusing bit twiddling.\n\nMeasuring over the entire compute kernel (which excludes idle time, communication, and (de)compression),\nour SSE routines achieve a $1.81\\times$ speedup on Edison over 64-bit versions and a $2.25\\times$ speedup on\nan Intel Core i7, compared to a naive speedup of $2$ for twice as many bits per\ninstruction.\\cprotect\\footnote{See \\verb+SSE vs. non-SSE speedup+ in \\verb+paper/numbers+.}  We are not sure what\ncaused the superlinear speedup in the $2.25$ case; one possibility is reduced register pressure.\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=\\columnwidth]{request-latency.pdf}\n\\end{center}\n\\vspace{-.1in}\n\\cprotect\\caption{Latency for 8-byte request-for-input messages between different nodes in a 96-thread test run\non Edison.  Around 20\\% of the messages complete in under $10$ ms, but the tail is quite long.  To reproduce,\nrun \\verb+paper/numbers messages 0,2+.}\n\\label{latency}\n\\vspace{-.1in}\n\\end{figure}\n\nEven on Edison's faster network, our typical message latency is still quite high as shown in \\autoref{latency}.\nHere latency is measured from immediately before \\verb+MPI_Isend+ to the time we start responding to the finished\nmessage when \\verb+MPI_Testsome+ succeeds.  The large latencies may be due to interference between small messages\nand larger messages, as the communication thread processes different types of messages asynchronously.  Since\nthe latency on Edison is low enough for our purposes, we have not investigated in detail.\n\n\\begin{comment}\n\\begin{table}\n\\begin{center}\n\\begin{tabular}{l|SSS}\n\\toprule & {instructions/cycle} & {bandwidth (GB/s)} & {misprediction rate} \\\\\ncompute  & 1.206 & 0.014 & 0.002 \\\\\nsnappy   & 1.049 & 0.002 & 0.064 \\\\\nunsnappy & 1.394 & 0.004 & 0.070\n\\end{tabular}\n\\end{center}\n\\cprotect\\caption{Issue rate (instructions/cycle), bandwidth, and misprediction rate\n(mispredicted branches / conditional branches) for a 96-thread test run on Edison.\nTo reproduce, run \\verb+paper/numbers papi+.}\n\\label{papi}\n\\end{table}\n\\end{comment}\n\nWithin each node, we used the PAPI hardware counter library \\cite{mucci1999papi} to measure instruction issue,\ncache misses, and branch mispredications.  The results show that our workload has minimal memory\nbandwidth requirements (under $15$ MB/s per core in performance critical sections), mispredicts branches mostly\nduring Snappy (de)compression, and makes significant use of dual instruction issue only for the one out of five\nworker threads that share a core with the less active communication thread; if hyperthreading is turned off, the\nissue rate jumps from $1.21$ to $1.89$ instructions per cycle.\\cprotect\\footnote{Run \\verb+paper/numbers papi+.}\n\n\\section{Correctness and fault detection}\n\nSince our goal is a database of perfect play, it is important to consider the possible sources of error in the\ncomputation.  We are interested only in undetected errors, since empirically the code ran\nwithout crashing or failing an assertion.\n\nOn the software side, we make heavy use of unit tests throughout the code, including simple tests\nfor correctness of simple routines, bootstrap tests comparing simple routines to more complicated variants\n(such as when abstracting over rotations), and comparison tests between different algorithms.\nIn particular, we compare our parallel backward code against the results of forward search, both at the\nbeginning and end of the game.  Near the end of the game this is easy, as forward search can quickly compute\nperfect play.  Near the beginning, our tests replace all values at slice 4 or 5 with random values,\ncompute optimal play up to the random slice with both backward and forward algorithms, and compare.\n\nOn the hardware side, the main failure points are DRAM, CPU, network, and disk.  Undetected disk errors are unlikely\nsince the primary output files are checksummed as part of LZMA compression.  Of DRAM, CPU, and network, DRAM errors\ndominate according to \\cite{bergman2008exascale} (Tables 6.11 and 6.12), at least on BlueGene.  Edison memory\nand network are SECDED (single error correct, double error detect), so an undetectable error would require three\nsimultaneous failures.  Unfortunately, we do not know a reliable method to estimate this probability conditional\non an apparently successful run, since DRAM errors are far from uncorrelated events \\cite{schroeder2009dram}.\nHowever, we believe the probability is quite small, and in particular that undetected hardware errors are less\nlikely than software errors.\n\nAs a test on software errors when running the code at scale, we write out small sample files with the\nresults of randomly chosen boards during each slice.  Large numbers of samples generated by the main run were\nvalidated against forward search for slices 20 and up, so any remaining software errors in the parallel code\nmust manifest only on a small set of positions.  We also write out win/loss/tie counts for each slice.\nBoth sample and count files would be useful for cross-validation should someone reproduce the calculation\nin the future.\n\nUnfortunately, the sample files are insufficient to detect rare software bugs or hardware failures, and indeed\nwe know of no cheap method for detecting this kind of unlikely error without rerunning or rewriting the code.\nSolving pentago falls most naturally into the complexity class PSPACE (polynomial space), and indeed the similar\nfive-in-a-row game gomoku has been proven PSPACE-complete \\cite{reisch1980gobang}.  Unless\n$\\textrm{NP}=\\textrm{PSPACE}$, it is unlikely that a short certificate exists proving that pentago is\na first player win, especially if we require a strong solution with perfect play known from all positions.\n\n\\section{Open source and data}\n\nAll code for this project is open source, and is available online at \\url{https://github.com/girving/pentago}.\nThe repository includes the paper source and all log files used to generate timing and other numbers.\nTo regenerate any reported number from the data, run either\n\\verb+bin/analyze <command>+ or \\verb+paper/numbers+; see the footnotes and figure captions.\n\nThe 3.7 TB strong solution is hosted on Rackspace Cloud Files; see the download instructions at\n\\url{https://github.com/girving/pentago/#data}.  We store small sparse sample and count files in\nNumpy's \\verb+.npy+ format \\cite{kern2007npy}, and the main solution files in a custom \\verb+.pentago+ format\nusing the described block structure with LZMA compression per block.  The format is described\nat \\url{https://github.com/girving/pentago/blob/master/pentago/data/supertensor.h}.  Both \\verb+.npy+ and\n\\verb+.pentago+ formats are easy to write in parallel using MPI I/O.\n\nThe strong solution is useless without a convenient method for exploring the data, so we have built a website\nshowing which moves win, lose, or tie from any position: \\url{http://perfect-pentago.net}.  The frontend\nJavascript uses a backend server at \\url{http://backend.perfect-pentago.net:2048} to look up the value of\npositions.  Any position with 18 or fewer stones is fetched from the database using an HTTP range request\nto download the surrounding compressed block.  As in the parallel algorithm, the children of a position\nfall into at most four blocks; we cache the uncompressed blocks to take advantage of this locality.\n\nPositions with more than 18 stones fall outside the database and are recomputed from scratch using a specialized\nserial retrograde solver.  Since there are at least 18 stones already on the board, usually in an asymmetric\nconfiguration, this solver rotates the board only through the $\\rmax$ function, avoiding the complexity of\nstandardizing positions into rotation minimal configurations.  In addition, we use the fact that $\\rmax$ flips\nthe parity of the $\\Z_4^4$ symmetry group to store half the required bits, reducing the storage per rotation\nabstracted position from 64 bytes to 32.  With these optimizations, evaluating all child values of an 18\nstone position takes 16 seconds on a single 2.6 GHz Intel Xeon thread, fast enough for interactive use.\n\nBoth remote lookups and from-scratch computation have significant latency, so the backend server is written\nin Javascript using Node.js \\cite{dahl2014nodejs} for asynchronous use by multiple clients.  The Javascript\nhandles asynchronous logic and I/O, but calls down to C++ for performance intensive computation.  The backend\nserver has a simple JSON API, and anyone wishing to develop their own frontend is welcome to query it directly.\n\n\\section{Conclusion}\n\nWe have strongly solved the board game pentago using retrograde analysis on 98304 threads of Edison, a\nCray XC30 machine at NERSC.  Symmetry techniques were used to improve the branching factor of the game\nand take advantage of SSE instruction level parallelism.  Unlike previous retrograde analysis, the computation\nwas almost entirely in-core, writing results to disk only near the end.  To fit safely into\nmemory, we use a fully asynchronous communication structure where each process requests data from other\nprocesses as needed, performs computation, and scatters results to their destinations.\n\nThe asynchronous control flow was a primary complicating factor during development and optimization of the\ncode, and runs against several limitations of MPI including difficulties in synchronizing between MPI and threads,\nlack of support for asynchronous progress in existing implementations, poor one-sided communication in MPI 2\n(fixed in MPI 3 too late for use in this project), and lack of user defined operations in one-sided\n\\verb+MPI_Accumulate+.  Unfortunately, the latter would require both strong asynchronous progress and careful\nconsideration of threading semantics.  Profiling tools were also a significant limitation, leading us to implement\nour own tracing and visualization tool to understand the flow of information across processes and between threads\nwithout one process.  Although our custom tool helped localize the problem to high latency, we were unable to\ndiagnose the underlying cause; further analysis would likely require network profiling and visualization tools\nincorporating knowledge of network topology.\n\nCompression was a requirement to fit into memory, but we were limited to the fast and weak Snappy library to\nprevent compression from becoming a compute bottleneck.  Compression also makes memory usage difficult to\npredict in advance, causing us to overestimate memory requirements and use more Edison nodes than required.\nAvoiding such overestimate without the I/O cost of checkpointing would require a dynamic number of MPI nodes.\n\nOur computation shares many characteristics with other irregularly structured, data intensive HPC workloads.\nThese characteristics include multiple levels of structure (slices, sections, block lines, blocks, boards,\nbits), memory restrictions, asynchronous control flow, reliance on integer performance (compression and game\nlogic), and reliance on both fast compute and fast communication.  Multiple levels of structure are important\nin many applications (e.g., domains, pages, paragraphs, sentences, words for web search) and often warrant\ndifferent parallelism strategies at different levels.  In addition to allowing larger problem sizes either\nin RAM or on-package RAM, the ability to operate near a memory limit improves performance for codes with\nimperfect parallel scaling and eases the scheduling problem for shared clusters, increasing both latency and\nbandwidth for users.  Asynchronous control flow adds flexibility which can be spent on memory constraints or\nirregular work chunk sizes (common with multiple levels of structure).  Poor integer performance ruled out\nBlueGene for our purposes, which is problematic even for floating point codes if compression is required.\nFinally, traditional Big Data applications often have less tightly coupled communication patterns such as\nMapReduce \\cite{dean2008mapreduce}; our application is sufficiently latency-critical to obtain clear benefit\nfrom the faster network on Edison compared to Hopper, and serves as an intermediate example between traditional\nHPC and Big Data (see the Graph 500 benchmark suite for other examples \\cite{murphy2010graph500}).\n\n\\section*{Acknowledgments}\n\nI am grateful to Jeff Hammond for valuable advice throughout the project, and to Jed Brown for numerous helpful\nsuggestions including the initial suggestion that supercomputer time might be a possibility.\nHosting for the 3.7 TB data set and compute servers for \\url{http://perfect-pentago.net} were generously donated\nby Rackspace; thanks especially to Jesse Noller at Rackspace for offering to host this open source project.\nSince a primary goal of this project is open data, accessible hosting for the final results is essential.\nThis research used resources of the National Energy Research Scientific Computing Center, which is supported by\nthe Office of Science of the U.S. Department of Energy under Contract No.\\ DE-AC02-05CH11231.  This research also\nused resources of the Argonne Leadership Computing Facility at Argonne National Laboratory, which is supported by\nthe Office of Science of the U.S. Department of Energy under contract DE-AC02-06CH11357.\n\n\\bibliography{references}\n\\bibliographystyle{IEEEtran}\n\\end{document}\n", "meta": {"hexsha": "469db9da176aa9c4f18a6a0d56c816db87564a5c", "size": 58456, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/pentago.tex", "max_stars_repo_name": "girving/pentago-learn", "max_stars_repo_head_hexsha": "b28399aed8a77152786e97e62ee3e3a8c384af2a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 41, "max_stars_repo_stars_event_min_datetime": "2015-01-25T14:37:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T16:29:18.000Z", "max_issues_repo_path": "paper/pentago.tex", "max_issues_repo_name": "girving/pentago-learn", "max_issues_repo_head_hexsha": "b28399aed8a77152786e97e62ee3e3a8c384af2a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-07-12T22:35:53.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-12T22:35:53.000Z", "max_forks_repo_path": "paper/pentago.tex", "max_forks_repo_name": "girving/pentago-learn", "max_forks_repo_head_hexsha": "b28399aed8a77152786e97e62ee3e3a8c384af2a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2015-05-06T11:04:40.000Z", "max_forks_repo_forks_event_max_datetime": "2017-04-18T00:22:11.000Z", "avg_line_length": 71.1143552311, "max_line_length": 4110, "alphanum_fraction": 0.7562440126, "num_tokens": 16441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.31683088550776484}}
{"text": "\n\n    \\filetitle{regen}{Regeneration time MCMC Metropolis posterior simulator}{poster/regen}\n\n\t\\paragraph{Syntax}\\label{syntax}\n\n\\begin{verbatim}\n[Theta,LogPost,AR,Scale,FinalCov] = regen(Pos,NDraw,...)\n\\end{verbatim}\n\n\\paragraph{Input arguments}\\label{input-arguments}\n\n\\begin{itemize}\n\\item\n  \\texttt{Pos} {[} poster {]} - Initialised posterior simulator object.\n\\item\n  \\texttt{NDraw} {[} numeric {]} - Length of the chain not including\n  burn-in.\n\\end{itemize}\n\n\\paragraph{Output arguments}\\label{output-arguments}\n\n\\begin{itemize}\n\\item\n  \\texttt{Theta} {[} numeric {]} - MCMC chain with individual parameters\n  in rows.\n\\item\n  \\texttt{LogPost} {[} numeric {]} - Vector of log posterior density (up\n  to a constant) in each draw.\n\\item\n  \\texttt{AR} {[} numeric {]} - Vector of cumulative acceptance ratios\n  in each draw.\n\\item\n  \\texttt{Scale} {[} numeric {]} - Vector of proposal scale factors in\n  each draw.\n\\item\n  \\texttt{FinalCov} {[} numeric {]} - Final proposal covariance matrix;\n  the final covariance matrix of the random walk step is\n  \\texttt{Scale(end)\\^{}2*FinalCov}.\n\\end{itemize}\n\n\\paragraph{Options}\\label{options}\n\n\\paragraph{References}\\label{references}\n\n\\paragraph{Brockwell, A.E., and Kadane, J.B., 2004. ``Identification of\nRegeneration Times in MCMC Simulation, with Application to Adaptive\nSchemes,'' mimeo, Carnegie Mellon\nUniversity.}\\label{brockwell-a.e.-and-kadane-j.b.-2004.-identification-of-regeneration-times-in-mcmc-simulation-with-application-to-adaptive-schemes-mimeo-carnegie-mellon-university.}\n\n\\paragraph{Example}\\label{example}\n\n\n", "meta": {"hexsha": "eaf1f11eebdd0494e52faa1ab91032e4a51ba63c", "size": 1580, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "-help/poster/regen.tex", "max_stars_repo_name": "OGResearch/IRIS-Toolbox-For-Octave", "max_stars_repo_head_hexsha": "682ea1960229dc701e446137623b120688953cef", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-12-06T13:38:38.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-06T13:38:38.000Z", "max_issues_repo_path": "-help/poster/regen.tex", "max_issues_repo_name": "OGResearch/IRIS-Toolbox-For-Octave", "max_issues_repo_head_hexsha": "682ea1960229dc701e446137623b120688953cef", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-03-28T08:13:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-02T10:40:25.000Z", "max_forks_repo_path": "-help/poster/regen.tex", "max_forks_repo_name": "OGResearch/IRIS-Toolbox-For-Octave", "max_forks_repo_head_hexsha": "682ea1960229dc701e446137623b120688953cef", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-17T07:06:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T07:06:39.000Z", "avg_line_length": 29.2592592593, "max_line_length": 183, "alphanum_fraction": 0.7335443038, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.31683087788656955}}
{"text": "\\documentclass[../../main]{subfiles}\n\\graphicspath{{images/rubiks-exp/}}\n\n\\begin{document}\n\nAt this point, there was an idea to use planes as an alternative to contours approach. \\ac{PTAM} was chosen for finding planes and in future it could become the mechanism for an object tracking due to its nature \\cite{puzzle_games_solver_q3_zakharov}.\n\n\\subsubsection{Bootstrapping}\n\nThis step is the first one and the most important. It, firstly, stores initial data, for instance, extracted key points from the first image, gray-scale representation of the first image and sets the pipeline to move on. Next it should analyze images from a video stream or an image sequence by comparing it to the first image stored in memory. As a result 3D point cloud is created, actually its simplified version. In addition, \\ac{PTAM} is the algorithm for augmented reality thus it is possible to project different objects onto the detected surface.\n\n\\paragraph*{Optical flow and homography filtering.}\n\nOptical flow algorithm is used within this solution in order to detect key points location in the next view using previous views. After that the algorithm checks if 80\\% of the points have survived and if not it stops bootstrapping and says that tracking has failed. If this condition is satisfied and more than the specified number of points are tracked then algorithm homography is used for filtering. Using the mask it checks how many points have survived homography in order to filter the bootstrapped and tracked key points again. This is done to achieve the most precise computations using only the most effective key points. Afterwards, it checks camera motion by comparing key points stored in memory with the currently tracked ones. To analyze if the motion is sufficient it uses \\ac{OpenCV}'s function $estimateRigidTransform$. If all the conditions are met it moves to the next step.\n\n\\paragraph*{Extracting essential matrix from fundamental.}\n\nDuring this step it finds fundamental matrix using the bootstrapped and tracked key points. In computer vision, the fundamental matrix is a 3 by 3 matrix that relates corresponding points in stereo images. Then it filters key points again. The next step is computing essential matrix. In computer vision, the essential matrix is a 3 by 3 matrix, with some additional properties, which relates corresponding points in stereo images assuming that the cameras satisfy the pinhole camera model. The algorithm needs to have intrinsic parameters of the camera before it starts the work because it does not include calibration part. Intrinsic parameters are physical camera parameters like focal length and etc. To compute essential matrix it multiplies transposed intrinsic matrix by fundamental matrix and multiplies this by intrinsic matrix, not transposed. This matrix is needed to extract camera rotation and translation in relative perspective from the bootstrapped image to the current one. In order to do this it decomposes essential matrix with \\ac{SVD}. Decomposition results into 2 possible rotation matrices and 2 possible translation vectors. If the determinant of the first rotation matrix plus $1.0f$ is less than $1e-09$ than algorithm changes signs of all numbers of the essential matrix and computes decomposition again. Then it proceeds to the next step.\n\n\\paragraph*{Triangulation of points.}\n\nAt this stage the assumption is made. Its essence is that the both views (images) extrinsic parameters matrix are composed of the rotation matrices and translation vectors. The constructed matrix is 3 by 4. However, \\ac{SVD} generates 2 rotation matrices and 2 translation vectors. Thus the algorithm has to create four possible extrinsic matrices for the second view (camera) in order to triangulate until the correct one is found. It might happen that algorithm fails if the triangulation results will be wrong for all 4 tries.  In order to triangulate, it normalizes bootstrapped and tracked key points coordinates. Afterwards, it proceeds triangulation and computes status by checking $z$ component of the points. Key points are filtered by this status array. After that the reprojection error is computed. If the error is not acceptable it runs triangulation again with different set of rotation and translation components. However, if the error is acceptable it goes to the next step where it finds the plane.\n\n\\paragraph*{Finding a plane using 3d point cloud.}\n\nThis step contains \\ac{PCA}. This analysis is necessary because it allows to get 3D structure information. It is used for plane's normal extraction in order to proceed key points filtering again. If more than 75\\% of key points belong to the same plane the bootstrap tracking is considered to be finished.\n\n\\subsubsection{Tracking}\n\nThis stage is final for the \\ac{PTAM} part of this solution. It computes optical flow for the key points that passed triangulation. \\ac{PTAM} is the augmented reality algorithm hence it requires the logic to compute projection matrix in order to render something on the plane. In order to do this it solves \\ac{PnP}.\nThe main difference between the real \\ac{PTAM} and this simplified version is that the real one can track all captured key points even if they are out of the camera view. On the contrary, the described approach just removes all unseen key points until the minimal amount exists and in the end it terminates. The suggested simplification significantly reduced time for implementation and understanding of the algorithm work flow.\n\n\\subsubsection{Planes for a corner detection}\n\nThe idea behind the \\ac{PTAM} usage was to find all contiguous planes where every 3 of them with 90 degrees angle between each other create a Rubik's cube angle. For this purpose, this triplets are used to find planes intersections (cube's corners). Using the triangulated data it is possible to find 3D coordinate for any 2D point in the specific view.\n\n\\begin{figure} [ht]\n    \\begin{center}\n        \\includegraphics[width=190pt]{planes_intersection}\n        \\caption{Example of planes intersection, cube's corner.}\n        \\label{fig:planes_intersection}\n    \\end{center}\n\\end{figure}\n\n\\newpage\n\nThese manipulations are useful in two senses, they allow to find a Rubik's cube corners and to track those corners in the 3D space, however it requires algorithm modification. Figure \\ref{fig:planes_intersection} illustrates 3 planes intersection with the underlined corner point.\n\n\\subsubsection{Conclusion}\n\nAlgorithm performed very well for finding and tracking a single Rubik's cube face but it showed pretty bad results for the continuous running of the algorithm to find contiguous planes. The reason for that is illumination. The algorithm was able to find one, two or three random planes in a row but it definitely brakes somewhere in the middle. This causes problems for triangulation stage, since the algorithm world space is relative to the first bootstrap thus if the algorithm fails the next bootstrap will become new first bootstrap. In simple words, algorithm is lost and it has to start from the beginning. It is possible to modify this algorithm to handle such type of problems but this topic is out of thesis scope.\n\n\\end{document}", "meta": {"hexsha": "cbd94001ceb816194d89987448284b57cf4405da", "size": 7192, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/Master Thesis/sections/experiments/rubiks-cube-plane-inter-experiment.tex", "max_stars_repo_name": "Lewis945/RubiksCubeSolver", "max_stars_repo_head_hexsha": "30926412ef0fce764c9d737940a757ec4f55d3ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/Master Thesis/sections/experiments/rubiks-cube-plane-inter-experiment.tex", "max_issues_repo_name": "Lewis945/RubiksCubeSolver", "max_issues_repo_head_hexsha": "30926412ef0fce764c9d737940a757ec4f55d3ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/Master Thesis/sections/experiments/rubiks-cube-plane-inter-experiment.tex", "max_forks_repo_name": "Lewis945/RubiksCubeSolver", "max_forks_repo_head_hexsha": "30926412ef0fce764c9d737940a757ec4f55d3ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 135.6981132075, "max_line_length": 1366, "alphanum_fraction": 0.8064516129, "num_tokens": 1485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.3167921107635529}}
{"text": "\\section{Introduction}\n\nThe {\\Python} library consists of three parts, with different levels of\nintegration with the interpreter.\nClosest to the interpreter are built-in types, exceptions and functions.\nNext are built-in modules, which are written in C and linked statically\nwith the interpreter.\nFinally there are standard modules that are implemented entirely in\n{\\Python}, but are always available.\nFor efficiency, some standard modules may become built-in modules in\nfuture versions of the interpreter.\n\n\\section{Built-in Types, Exceptions and Functions}\n\nNames for built-in exceptions and functions are found in a separate\nread-only symbol table which cannot be modified.\nThis table is searched last, so local and global user-defined names can\noverride built-in names.\nBuilt-in types have no names but are created by syntactic constructs\n(such as constants) or built-in functions.\nThey are described together here for easy reference.%\n\\footnote{\nThe descriptions sorely lack explanations of the exceptions that\nmay be raised---this will be fixed in a future version of this\ndocument.\n}\n\n\\subsection{Built-in Types}\n\nThe following sections describe the standard types that are built into the\ninterpreter.\n\\subsubsection{Numeric Types}\n\nThere are two numeric types: integers and floating point numbers.\nIntegers are implemented using {\\tt long} in C, so they have at least 32\nbits of precision.\nFloating point numbers are implemented using {\\tt double} in C.\nAll bets on precision are off.\nNumbers are created by numeric constants or as the result of built-in\nfunctions and operators.\n\nNumeric types support the following operations:\n\n\\begin{center}\n\\begin{tabular}{|c|l|c|}\n\\hline\nOperation & Result & Notes \\\\\n\\hline\n{\\tt abs}({\\em x}) & absolute value of {\\em x} & \\\\\n{\\tt int}({\\em x}) & {\\em x} converted to integer & (1) \\\\\n{\\tt float}({\\em x}) & {\\em x} converted to floating point & \\\\\n{\\tt -}{\\em x} & {\\em x} negated & \\\\\n{\\tt +}{\\em x} & {\\em x} unchanged & \\\\\n{\\em x}{\\tt +}{\\em y} & sum of {\\em x} and {\\em y} & \\\\\n{\\em x}{\\tt -}{\\em y} & difference of {\\em x} and {\\em y} & \\\\\n{\\em x}{\\tt *}{\\em y} & product of {\\em x} and {\\em y} & \\\\\n{\\em x}{\\tt /}{\\em y} & quotient of {\\em x} and {\\em y} & (2) \\\\\n{\\em x}{\\tt \\%}{\\em y} & remainder of {\\em x}{\\tt /}{\\em y} & (3) \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\n\\noindent\nNotes:\n\\begin{description}\n\\item[(1)]\nThis may round or truncate as in C; see functions {\\tt floor} and\n{\\tt ceil} in module {\\tt math}.\n\\item[(2)]\nInteger division is defined as in C: the result is an integer; with\npositive operands, it truncates towards zero; with a negative operand,\nthe result is unspecified.\n\\item[(3)]\nOnly defined for integers.\n\\end{description}\n\nMixed arithmetic is not supported; both operands must have the same type.\nMixed comparisons return the wrong result (floats always compare smaller\nthan integers).%\n\\footnote{\nThese restrictions are bugs in the language definitions and will be\nfixed in the future.\n}\n\\subsubsection{Sequence Types}\n\nThere are three sequence types: strings, lists and tuples.\nStrings constants are written in single quotes: {\\tt 'xyzzy'}.\nLists are constructed with square brackets: {\\tt [a,~b,~c]}.\nTuples are constructed by the comma operator or with an empty set of\nparentheses: {\\tt a,~b,~c} or {\\tt ()}.\n\nSequence types support the following operations ({\\em s} and {\\em t} are\nsequences of the same type; {\\em n}, {\\em i} and {\\em j} are integers):\n\n\\begin{center}\n\\begin{tabular}{|c|l|c|}\n\\hline\nOperation & Result & Notes \\\\\n\\hline\n{\\tt len}({\\em s}) & length of {\\em s} & \\\\\n{\\tt min}({\\em s}) & smallest item of {\\em s} & \\\\\n{\\tt max}({\\em s}) & largest item of {\\em s} & \\\\\n{\\em x} {\\tt in} {\\em s} &\n\ttrue if an item of {\\em s} is equal to {\\em x} & \\\\\n{\\em x} {\\tt not} {\\tt in} {\\em s} &\n\tfalse if an item of {\\em s} is equal to {\\em x} & \\\\\n{\\em s}{\\tt +}{\\em t} & the concatenation of {\\em s} and {\\em t} & \\\\\n{\\em s}{\\tt *}{\\em n}, {\\em n}*{\\em s} &\n\t{\\em n} copies of {\\em s} concatenated & (1) \\\\\n{\\em s}[{\\em i}] & {\\em i}'th item of {\\em s} & \\\\\n{\\em s}[{\\em i}:{\\em j}] &\n\tslice of {\\em s} from {\\em i} to {\\em j} & (2) \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\n\\noindent\nNotes:\n\\begin{description}\n\\item[(1)]\nSequence repetition is only supported for strings.\n\\item[(2)]\nThe slice of $s$ from $i$ to $j$ is defined as the sequence\nof items with index $k$ such that $i \\leq k < j$.\nSpecial rules apply for negative and omitted indices; see the Tutorial\nor the Reference Manual.\n\\end{description}\n\n\\paragraph{Mutable Sequence Types.}\n\nList objects support additional operations that allow in-place\nmodification of the object.\nThese operations would be supported by other mutable sequence types\n(when added to the language) as well.\nStrings and tuples are immutable sequence types and such objects cannot\nbe modified once created.\nThe following operations are defined on mutable sequence types (where\n{\\em x} is an arbitrary object):\n\n\\begin{center}\n\\begin{tabular}{|c|l|}\n\\hline\nOperation & Result \\\\\n\\hline\n{\\em s}[{\\em i}] = {\\em x} &\n\titem {\\em i} of {\\em s} is replaced by {\\em x} \\\\\n{\\em s}[{\\em i}:{\\em j}] = {\\em t} &\n\tslice of {\\em s} from {\\em i} to {\\em j} is replaced by {\\em t} \\\\\n{\\tt del} {\\em s}[{\\em i}:{\\em j}] &\n\tsame as {\\em s}[{\\em i}:{\\em j}] = [] \\\\\n{\\em s}.{\\tt append}({\\em x}) &\n\tsame as {\\em s}[{\\tt len}({\\em x}):{\\tt len}({\\em x})] = [{\\em x}] \\\\\n{\\em s}.{\\tt insert}({\\em i}, {\\em x}) &\n\tsame as {\\em s}[{\\em i}:{\\em i}] = [{\\em x}] \\\\\n{\\em s}.{\\tt sort}() &\n\tthe items of {\\em s} are permuted to satisfy \\\\\n\t&\n\t$s[i] \\leq s[j]$ for $i < j$\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\n\\subsubsection{Mapping Types}\n\nA\n{\\em mapping}\nobject maps values of one type (the key type) to arbitrary objects.\nMappings are mutable objects.\nThere is currently only one mapping type, the\n{\\em dictionary}.\nA dictionary's keys are strings.\nAn empty dictionary is created by the expression \\verb\"{}\".\nAn extension of this notation is used to display dictionaries when\nwritten (see the example below).\n\nThe following operations are defined on mappings (where {\\em a} is a\nmapping, {\\em k} is a key and {\\em x} is an arbitrary object):\n\n\\begin{center}\n\\begin{tabular}{|c|l|c|}\n\\hline\nOperation & Result & Notes\\\\\n\\hline\n{\\tt len}({\\em a}) & the number of elements in {\\em a} & \\\\\n{\\em a}[{\\em k}] & the item of {\\em a} with key {\\em k} & \\\\\n{\\em a}[{\\em k}] = {\\em x} & set {\\em a}[{\\em k}] to {\\em x} & \\\\\n{\\tt del} {\\em a}[{\\em k}] & remove {\\em a}[{\\em k}] from {\\em a} & \\\\\n{\\em a}.{\\tt keys}() & a copy of {\\em a}'s list of keys & (1) \\\\\n{\\em a}.{\\tt has\\_key}({\\em k}) & true if {\\em a} has a key {\\em k} & \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\n\\noindent\nNotes:\n\\begin{description}\n\\item[(1)]\nKeys are listed in random order.\n\\end{description}\n\nA small example using a dictionary:\n\\bcode\\begin{verbatim}\n>>> tel = {}\n>>> tel['jack'] = 4098\n>>> tel['sape'] = 4139\n>>> tel['guido'] = 4127\n>>> tel['jack']\n4098\n>>> tel\n{'sape': 4139; 'guido': 4127; 'jack': 4098}\n>>> del tel['sape']\n>>> tel['irv'] = 4127\n>>> tel\n{'guido': 4127; 'irv': 4127; 'jack': 4098}\n>>> tel.keys()\n['guido', 'irv', 'jack']\n>>> tel.has_key('guido')\n1\n>>> \n\\end{verbatim}\\ecode\n\\subsubsection{Other Built-in Types}\n\nThe interpreter supports several other kinds of objects.\nMost of these support only one or two operations.\n\n\\paragraph{Modules.}\n\nThe only operation on a module is member acces: {\\em m}{\\tt .}{\\em name},\nwhere {\\em m} is a module and {\\em name} accesses a name defined in\n{\\em m}'s symbol table.\nModule members can be assigned to.\n\n\\paragraph{Classes and Class Objects.}\n\nXXX Classes will be explained at length in a later version of this\ndocument.\n\n\\paragraph{Functions.}\n\nFunction objects are created by function definitions.\nThe only operation on a function object is to call it:\n{\\em func}({\\em optional-arguments}).\n\nBuilt-in functions have a different type than user-defined functions,\nbut they support the same operation.\n\n\\paragraph{Methods.}\n\nMethods are functions that are called using the member acces notation.\nThere are two flavors: built-in methods (such as {\\tt append()} on\nlists) and class member methods.\nBuilt-in methods are described with the types that support them.\nXXX Class member methods will be described in a later version of this\ndocument.\n\n\\paragraph{Type Objects.}\n\nType objects represent the various object types.\nAn object's type is accessed by the built-in function\n{\\tt type()}.\nThere are no operations on type objects.\n\n\\paragraph{The Null Object.}\n\nThis object is returned by functions that don't explicitly return a\nvalue.\nIt supports no operations.\nThere is exactly one null object, named {\\tt None}\n(a built-in name).\n\n\\paragraph{File Objects.}\n\nFile objects are implemented using C's\n{\\em stdio}\npackage and can be created with the built-in function\n{\\tt open()}.\nThey have the following methods:\n\\begin{description}\n\\funcitem{close}{}\nCloses the file.\nA closed file cannot be read or written anymore.\n\\funcitem{read}{size}\nReads at most\n{\\tt size}\nbytes from the file (less if the read hits EOF).\nThe bytes are returned as a string object.\nAn empty string is returned when EOF is hit immediately.\n(For certain files, like ttys, it makes sense to continue reading after\nan EOF is hit.)\n\\funcitem{readline}{size}\nReads a line of at most\n{\\tt size}\nbytes from the file.\nA trailing newline character, if present, is kept in the string.\nThe size is optional and defaults to a large number (but not infinity).\nEOF is reported as by\n{\\tt read().}\n\\funcitem{write}{str}\nWrites a string to the file.\nReturns no value.\n\\end{description}\n\n\\subsection{Built-in Exceptions}\n\nThe following exceptions can be generated by the interpreter or\nbuilt-in functions.\nExcept where mentioned, they have a string argument (also known as the\n`associated value' of an exception) indicating the detailed cause of the\nerror.\nThe strings listed with the exception names are their values when used\nin an expression or printed.\n\\begin{description}\n\\excitem{EOFError}{end-of-file read}\n(No argument.)\nRaised when a built-in function ({\\tt input()} or {\\tt raw\\_input()})\nhits an end-of-file condition (EOF) without reading any data.\n(N.B.: the {\\tt read()} and {\\tt readline()} methods of file objects\nreturn an empty string when they hit EOF.)\n\\excitem{KeyboardInterrupt}{end-of-file read}\n(No argument.)\nRaised when the user hits the interrupt key (normally Control-C or DEL).\nDuring execution, a check for interrupts is made regularly.\nInterrupts typed when a built-in function ({\\tt input()} or\n{\\tt raw\\_input()}) is waiting for input also raise this exception.\n\\excitem{MemoryError}{out of memory}\n%.br\nRaised when an operation runs out of memory but the situation\nmay still be rescued (by deleting some objects).\n\\excitem{NameError}{undefined name}\n%.br\nRaised when a name is not found.\nThis applies to unqualified names, module names (on {\\tt import}),\nmodule members and object methods.\nThe string argument is the name that could not be found.\n\\excitem{RuntimeError}{run-time error}\n%.br\nRaised for a variety of reasons, e.g., division by zero or index out of\nrange.\n\\excitem{SystemError}{system error}\n%.br\nRaised when the interpreter finds an internal error, but the situation\ndoes not look so serious to cause it to abandon all hope.\n\\excitem{TypeError}{type error}\n%.br\nRaised when an operation or built-in function is applied to an object of\ninappropriate type.\n\\end{description}\n\n\\subsection{Built-in Functions}\n\nThe {\\Python} interpreter has a small number of functions built into it that\nare always available.\nThey are listed here in alphabetical order.\n\\begin{description}\n\\funcitem{abs}{x}\nReturns the absolute value of a number.\nThe argument may be an integer or floating point number.\n\\funcitem{chr}{i}\nReturns a string of one character\nwhose ASCII code is the integer {\\tt i},\ne.g., {\\tt chr(97)} returns the string {\\tt 'a'}.\nThis is the inverse of {\\tt ord()}.\n\\funcitem{dir}{}\nWithout arguments, this function returns the list of names in the\ncurrent local symbol table, sorted alphabetically.\nWith a module object as argument, it returns the sorted list of names in\nthat module's global symbol table.\nFor example:\n\\bcode\\begin{verbatim}\n>>> import sys\n>>> dir()\n['sys']\n>>> dir(sys)\n['argv', 'exit', 'modules', 'path', 'stderr', 'stdin', 'stdout']\n>>> \n\\end{verbatim}\\ecode\n\\funcitem{divmod}{a, b}\n%.br\nTakes two integers as arguments and returns a pair of integers\nconsisting of their quotient and remainder.\nFor\n\\bcode\\begin{verbatim}\nq, r = divmod(a, b)\n\\end{verbatim}\\ecode\nthe invariants are:\n\\bcode\\begin{verbatim}\na = q*b + r\nabs(r) < abs(b)\nr has the same sign as b\n\\end{verbatim}\\ecode\nFor example:\n\\bcode\\begin{verbatim}\n>>> divmod(100, 7)\n(14, 2)\n>>> divmod(-100, 7)\n(-15, 5)\n>>> divmod(100, -7)\n(-15, -5)\n>>> divmod(-100, -7)\n(14, -2)\n>>> \n\\end{verbatim}\\ecode\n\\funcitem{eval}{s}\nTakes a string as argument and parses and evaluates it as a {\\Python}\nexpression.\nThe expression is executed using the current local and global symbol\ntables.\nSyntax errors are reported as exceptions.\nFor example:\n\\bcode\\begin{verbatim}\n>>> x = 1\n>>> eval('x+1')\n2\n>>> \n\\end{verbatim}\\ecode\n\\funcitem{exec}{s}\nTakes a string as argument and parses and evaluates it as a sequence of\n{\\Python} statements.\nThe string should end with a newline (\\verb\"'\\n'\").\nThe statement is executed using the current local and global symbol\ntables.\nSyntax errors are reported as exceptions.\nFor example:\n\\bcode\\begin{verbatim}\n>>> x = 1\n>>> exec('x = x+1\\n')\n>>> x\n2\n>>> \n\\end{verbatim}\\ecode\n\\funcitem{float}{x}\nConverts a number to floating point.\nThe argument may be an integer or floating point number.\n\\funcitem{input}{s}\nEquivalent to\n{\\tt eval(raw\\_input(s))}.\nAs for\n{\\tt raw\\_input()},\nthe argument is optional.\n\\funcitem{int}{x}\nConverts a number to integer.\nThe argument may be an integer or floating point number.\n\\funcitem{len}{s}\nReturns the length (the number of items) of an object.\nThe argument may be a sequence (string, tuple or list) or a mapping\n(dictionary).\n\\funcitem{max}{s}\nReturns the largest item of a non-empty sequence (string, tuple or list).\n\\funcitem{min}{s}\nReturns the smallest item of a non-empty sequence (string, tuple or list).\n\\funcitem{open}{name, mode}\n%.br\nReturns a file object (described earlier under Built-in Types).\nThe string arguments are the same as for stdio's\n{\\tt fopen()}:\n{\\tt 'r'}\nopens the file for reading,\n{\\tt 'w'}\nopens it for writing (truncating an existing file),\n{\\tt 'a'}\nopens it for appending.%\n\\footnote{\nThis function should go into a built-in module\n{\\tt io}.\n}\n\\funcitem{ord}{c}\nTakes a string of one character and returns its\nASCII value, e.g., {\\tt ord('a')} returns the integer {\\tt 97}.\nThis is the inverse of {\\tt chr()}.\n\\funcitem{range}{}\nThis is a versatile function to create lists containing arithmetic\nprogressions of integers.\nWith two integer arguments, it returns the ascending sequence of\nintegers starting at the first and ending one before the second\nargument.\nA single argument is used as the end point of the sequence, with 0 used\nas the starting point.\nA third argument specifies the step size; negative steps are allowed and\nwork as expected, but don't specify a zero step.\nThe resulting list may be empty.\nFor example:\n\\bcode\\begin{verbatim}\n>>> range(10)\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> range(1, 1+10)\n[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n>>> range(0, 30, 5)\n[0, 5, 10, 15, 20, 25]\n>>> range(0, 10, 3)\n[0, 3, 6, 9]\n>>> range(0, -10, -1)\n[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]\n>>> range(0)\n[]\n>>> range(1, 0)\n[]\n>>> \n\\end{verbatim}\\ecode\n\\funcitem{raw\\_input}{s}\n%.br\nThe argument is optional; if present, it is written to standard output\nwithout a trailing newline.\nThe function then reads a line from input, converts it to a string\n(stripping a trailing newline), and returns that.\nEOF is reported as an exception.\nFor example:\n\\bcode\\begin{verbatim}\n>>> raw_input('Type anything: ')\nType anything: Mutant Teenage Ninja Turtles\n'Mutant Teenage Ninja Turtles'\n>>> \n\\end{verbatim}\\ecode\n\\funcitem{reload}{module}\nCauses an already imported module to be re-parsed and re-initialized.\nThis is useful if you have edited the module source file and want to\ntry out the new version without leaving {\\Python}.\n\\funcitem{type}{x}\nReturns the type of an object.\nTypes are objects themselves:\nthe type of a type object is its own type.\n\\end{description}\n", "meta": {"hexsha": "37abc5017713a6c7790743d40b41a5816f0daef3", "size": 16344, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/mod1.tex", "max_stars_repo_name": "aganders3/python-0.9.1", "max_stars_repo_head_hexsha": "5e62c7310e123cf5684a1db9d7eac745e7d713cb", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": 116, "max_stars_repo_stars_event_min_datetime": "2021-02-16T22:09:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T23:29:24.000Z", "max_issues_repo_path": "doc/mod1.tex", "max_issues_repo_name": "aganders3/python-0.9.1", "max_issues_repo_head_hexsha": "5e62c7310e123cf5684a1db9d7eac745e7d713cb", "max_issues_repo_licenses": ["FSFAP"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-02-18T08:34:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-18T08:34:11.000Z", "max_forks_repo_path": "doc/mod1.tex", "max_forks_repo_name": "aganders3/python-0.9.1", "max_forks_repo_head_hexsha": "5e62c7310e123cf5684a1db9d7eac745e7d713cb", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2021-02-17T07:17:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T09:24:05.000Z", "avg_line_length": 31.3103448276, "max_line_length": 76, "alphanum_fraction": 0.7060695056, "num_tokens": 4564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3166402226127737}}
{"text": "\\input{permve-ntnu-latex-assignment.tex}\n\n\\usepackage{float}\n\n\\title{\t\n\\normalfont \\normalsize \n\\textsc{Norwegian University of Science and Technology\\\\IT3105 -- Artificial Intelligence Programming}\n\\horrule{0.5pt} \\\\[0.4cm]\n\\huge Module 2:\\\\Combining Constraint-Satisfaction Problem-Solving with Best-First\nSearch\\\\\n\\horrule{2pt} \\\\[0.5cm]\n}\n\n\\author{Per Magnus Veierland\\\\permve@stud.ntnu.no}\n\n\\date{\\normalsize\\today}\n\n\\newacro{CSP}{Constraint Satisfaction Problem}\n\\newacro{GAC}{General Arc Consistency}\n\n\\begin{document}\n\n\\maketitle\n\n\\section*{Generality of A* implementation}\n\nThe \\ac{CSP} and \\ac{GAC} related code is implemented in the \\texttt{vi.csp} namespace. A \\texttt{Network} object holds all \\texttt{Variable} and \\texttt{Constraint} objects, as well as a \\texttt{domains} mapping from \\texttt{Variable} objects to the domains of the variables. The values within a domain can be of any type. Also within the \\texttt{vi.csp} namespace are the functions implementing \\textsc{REVISE*} and \\ac{GAC}. None of this code is tied to search code; and it can be used in full isolation where needed.\n\nA \\texttt{Constraint} holds the list of variables it is linked to, as well as a condition which can be evaluated. A \\texttt{Variable} has an identity which can be of any type suiting the problem, as well as the list of contraints it is involved in.\n\nFusing the \\ac{GAC} algorithm with A* is done by the \\texttt{vi.search.gac.Problem} class, which is constructed from a \\texttt{vi.csp.Network} object -- see Figure~\\ref{figure:vi_astar_gac}. The \\texttt{Network} object serves as the state of each search node. The \\texttt{Problem} class provides the methods \\texttt{goal\\_test}, \\texttt{heuristic}, \\texttt{initial\\_node}, and \\texttt{successors} -- which forms the interface to the A* search class.\n\nNo problem specific code exists in the \\texttt{vi.search.gac.Problem} class. It has a goal test which checks that all domains in the current state has a size of one. It has a heuristic which returns the sum of the length of all domains minus one. The initial search node returned from the \\texttt{Problem} class is simply the initial network passed through one iteration of the \\texttt{general\\_arc\\_consistency} function.\n\nThe crucial part of the \\texttt{Problem} class implementation lies in the \\texttt{successors} method. All successors generated from a search node is based on assumptions made about a single variable. The implementation selects the variable which has the smallest domain which contains more than one value. A successor state is generated for each value in the assumed variable's domain. The \\ac{GAC} domain filtering loop is then warm rebooted to revise the domains of all variables which share a constraint with the assumed variable.\n\n\\begin{figure}[H]\n\\centering\n\\includegraphics[scale=0.7]{images/vi_astar_gac}\n\\caption{VI CSP and A*-GAC classes}\n\\label{figure:vi_astar_gac}\n\\end{figure}\n\n\\section*{Generality of A*-GAC implementation}\n\nThe input to the vertex coloring problem is a pure graph description; with no direct relation to the vertex coloring problem. The file input is parsed and used to construct a graph using the \\texttt{vi.graph.Vertex}, \\texttt{vi.graph.Edge} and \\texttt{vi.graph.Graph} classes; which are fully problem independent.\n\nA single function in the \\texttt{vi.app.vertex\\_coloring} namespace takes the \\texttt{vi.graph.Graph} object constructed from the file input, together with a $K$-value describing the number of colors -- and builds a \\texttt{vi.csp.Network} which contains the variables, constraints and domains which describes the vertex coloring problem. It simply generates one \\texttt{Variable} for each \\texttt{Vertex} object; with the \\texttt{Vertex} object as the variable's identity. For each \\texttt{Edge} object a \\texttt{Constraint} object is built which binds the two \\texttt{Variable} objects associated with each \\texttt{Vertex} in the edge together. The condition assigned to each constraint simply verifies that the values assigned to each of the two variables are different.\n\n\\section*{Constraint network}\n\nA constraint network consists of constraints, variables, and domains. Much of this information is identical between search states. The assignment specifies that the variables and constraints will be the same in all states. The difference between the states is the sizes of the domains belonging to the different variables.\n\nThe constraint network is represented with the \\texttt{vi.csp.Network} class. It holds a all variables involved in the network; a list of all constraints involved in the network; and it holds the mapping from variables to their respective domains. It is important to note that there is no direct connection from a \\texttt{Variable} instance to its domain; this connection is only made by the mapping which exists in each \\texttt{Network} instance. A \\texttt{Network} instance is the state for each search node in the A*-GAC implementation. However importance is place on how the \\texttt{Network} object is copied and which data is shared between states.\n\nAll \\texttt{vi.csp.Network} instances which belong to the same problem share the list of variables and the list of constraints. There is only a single list of variables and a single list of constraints; and each instance of the \\texttt{Network} class points to the same two lists. It is still important that each instance contains these two pointers since \\texttt{Network} objects belonging to different problems will necessarily maintain different lists of variables and constraints.\n\nThe \\texttt{Network.copy()} member function returns a new instance of the class which points to the same lists of variables and constraints; but which takes a shallow copy of the domains mapping. This means that no actual domains are copied, only the mapping from variables to domains. When applying the GAC algorithm to a \\texttt{Network} instance, the relevant mappings of revised domains is updated to point at the new revised domain for the involved variables. This ensures high reuse in representation and avoids redundant information, without increasing the complexity of the implementation.\n\n\\section*{Code chunks}\n\nIn the given implementation a \\texttt{Constraint} class instance holds a single condition and a list of variables involved in the condition. The condition must be callable and must accept one parameter. The parameter passed to a condition is a mapping of variables to specific values for all variables involved in the constraint. This makes the \\texttt{Constraint} interface very general and allows any hashable type to be used as the \\texttt{Variable} identity and in variable domains.\n\nSince all variables involved in a \\texttt{Constraint} is explicitly specified it is easy to generate the required permutations of values from variable domains in the \\textsc{REVISE*} algorithm.\n\nThe interface was chosen for its semantical purity and generality. It can be used with both interpreters parsing user input as well as direct \\texttt{eval} approaches simply by adding code to build the necessary \\texttt{Constraint} objects and callable conditions. Since no parsing of user input was necessary for the given problem; only a simple lambda verifying the inequality of two variable values in the given value set was used.\n\n\\end{document}\n\n", "meta": {"hexsha": "0d9f8a068f24a21cc1f78bbe3080e71681d110c7", "size": 7313, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "module_2/report/permve-ntnu-it3105-module-2.tex", "max_stars_repo_name": "pveierland/permve-ntnu-it3105", "max_stars_repo_head_hexsha": "6a7e4751de47b091c1c9c59560c19a8452698d81", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "module_2/report/permve-ntnu-it3105-module-2.tex", "max_issues_repo_name": "pveierland/permve-ntnu-it3105", "max_issues_repo_head_hexsha": "6a7e4751de47b091c1c9c59560c19a8452698d81", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "module_2/report/permve-ntnu-it3105-module-2.tex", "max_forks_repo_name": "pveierland/permve-ntnu-it3105", "max_forks_repo_head_hexsha": "6a7e4751de47b091c1c9c59560c19a8452698d81", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 104.4714285714, "max_line_length": 773, "alphanum_fraction": 0.7980309039, "num_tokens": 1670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.31664022261277364}}
{"text": "\\chapter{Background information}\n\\label{chap:Background}\nHydroDyn is currently undergoing a conversion to the FAST modularization framework. During this conversion, some additional capabilities are being added to HydroDyn including jacket platforms. At present, HydroDyn does not account for second order wave forces: those forces that arise from the sum and difference of the frequencies of incident waves. HydroDyn also only includes uni-directional waves where all waves are incident from the same direction.\n\nAt the start of a FAST simulation, HydroDyn is initialized and calculates the wave spectrum\\footnote{\n      The wave spectrum is complex-valued and therefore includes all the phase information, so the time history of the wave can be found easily through an FFT.}\nand time history using the \\emph{waves} sub-module.  This information is then used by the \\emph{WAMIT} sub-module and a few other sub-modules to calculate the first order wave foreces on the platform.  Because the frequency, direction, and phase of each of the wave components is known at initialization, a time series of the second order forces can be calculated using the \\emph{WAMIT2} sub-module before the simulations begins. This requires that the following assumptions are made:\n\\begin{itemize}\n   \\item{the wave information in frequency space is known before the start of the simulation (the time series can be found through an FFT),}\n   \\item{the time series of second order forces will act on a single point at the origin (as the first order forces do),}\n   \\item{wave forces and moments are fixed to a reference frame that translates (but does not rotate) with the platform,}\n   \\item{Wavelengths are large compared to the motion of the platform.}\n\\end{itemize}\n\n\\section{Platform Displacement and Rotation}\nThe complete timeseries for the forces and moments comprising the loads from the first and second order waves are calculated during the initialization of a FAST simulation.  These calculated loads are given at the platform origin in the platform rest reference frame and applied during the simulation.  During the simulation, the platform will translate and rotate as a result of these loads, aerodynamic loads, and other real time loads (mooring lines etc.).\nThe calculation of the first and second order wave loads do not take into account this displacement.  \n\nDuring the simulation, the FAST glue code calls \\HD to calculate the platform loads at each timestep.  Since the first- and second-order wave load timeseries were calculated during the initialization, these values are looked up at each timestep and reported back to the glue code on a point mesh (includes translation and rotation).\n\n\n\n\\endinput\n\nThe implication of this is that as the platform translates and rotates, the wave field and resulting loads are in effect translated and rotated with it.  For translation, this is not problematic since the translation is slow in comparison with the wave velocity.  However, it is not desirable to have the wave directionality also changing as the platform yaws, so an additional step is taken within \\HD to compensate for the platform rotation before returning the forces and moments to the glue code.  This keeps the wave directionality and resulting moments in the inertial (non-rotated) reference frame of the platform.  This could potentially result in inaccuracies in response if the pitch and roll responses were dramatically different for waves incident along $x$ or $y$ respectively.\n\n\n\n\n\\endinput\nFIXME: add figure from page 141 of notebook\n\n\n\nEffectively means that the wave field and resulting loads move with the platform.  This is not likely to cause problems for surge and sway translation since the platform surge response tends to be slow in comparison with the wave velocity. There may be potential for issues with large heave displacements since WAMIT assumes the translational motions are \\emph{small} compared to the wavelength during response force calculations.\n", "meta": {"hexsha": "f4552c154358f15fc759a78befbd32edaf9465ef", "size": 3988, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Documentation/2nd_order_implementation/chaps/Chap.Background.tex", "max_stars_repo_name": "NWTC/HydroDyn", "max_stars_repo_head_hexsha": "816705503bc3c9d31988f424caf551ded7b5c5eb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-28T21:32:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-28T21:32:25.000Z", "max_issues_repo_path": "Documentation/2nd_order_implementation/chaps/Chap.Background.tex", "max_issues_repo_name": "NWTC/HydroDyn", "max_issues_repo_head_hexsha": "816705503bc3c9d31988f424caf551ded7b5c5eb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-18T11:49:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-22T08:33:26.000Z", "max_forks_repo_path": "Documentation/2nd_order_implementation/chaps/Chap.Background.tex", "max_forks_repo_name": "NWTC/HydroDyn", "max_forks_repo_head_hexsha": "816705503bc3c9d31988f424caf551ded7b5c5eb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-03-20T02:57:07.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-20T02:57:07.000Z", "avg_line_length": 110.7777777778, "max_line_length": 790, "alphanum_fraction": 0.8071715145, "num_tokens": 800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.31664021541792986}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\section*{Fri Dec 20 2019}\n\n\\section{Gravitational waves}\n\nThey are solutions of the linearized EFE on a given fixed background. Today we only treat GW on a Minkowski background, but we could do it for any number of other (cosmological) background. \n\nSo, we say: \n%\n\\begin{align}\ng_{\\mu \\nu } = \\eta_{\\mu \\nu } + h_{\\mu \\nu }\n\\,,\n\\end{align}\n%\nwith \\(h_{\\mu \\nu } \\ll 1\\), so we neglect anything which is \\(\\mathcal{O}(h^2)\\). \n\nGW are very topical today: they could allow us to see beyond the last scattering surface, when the universe stopped being opaque to EM radiation: then, it had been transparent to gravitational radiation from a long time before. \n\nWe can do statistics to the stochastic GW background, for now however we have only detected GW from localized event. \n\nWe must start to write down the EFE from the Christoffel symbols: in general they are \n%\n\\begin{align}\n\\Gamma^{\\alpha }_{\\mu \\nu } = \\frac{1}{2} g^{\\alpha \\lambda } \\qty(g_{\\lambda \\nu , \\mu } + g_{\\mu \\lambda , \\nu } - g_{\\mu \\nu , \\lambda })\n\\,,\n\\end{align}\n%\nbut in the derivatives of the metric we only have \\(\\mathcal{O}(h)\\) terms, so in the inverse metric we neglect all the \\(\\mathcal{O}(h)\\) terms since their global contribution would be \\(\\mathcal{O}(h^2)\\): so we get \n%\n\\begin{align}\n    \\Gamma^{\\alpha }_{\\mu \\nu } = \\frac{1}{2} \\eta ^{\\alpha \\lambda } \\qty(h_{\\lambda \\nu , \\mu } + h_{\\mu \\lambda , \\nu } - h_{\\mu \\nu , \\lambda })\n\\,,\n\\end{align}\n%\nand when we compute the Ricci tensor we will only keep the \\(\\partial \\Gamma \\) terms, since the \\(\\Gamma \\Gamma \\) terms are \\(\\mathcal{O}(h^2)\\). So our expression becomes \n%\n\\begin{subequations}\n\\begin{align}\nR_{\\mu \\nu } &= \\partial_{\\alpha } \\Gamma^{\\alpha }_{\\mu \\nu } - \\partial_{\\nu } \\Gamma^{\\alpha }_{\\mu \\alpha }  \\\\\n&= \\frac{1}{2} \\eta^{\\alpha \\lambda } \\partial_{\\alpha } \\qty(h_{\\lambda \\nu , \\mu } + \\cancelto{}{h_{\\mu \\lambda , \\nu }} - h_{\\mu \\nu , \\lambda }) - \\frac{1}{2} \\eta^{\\alpha \\lambda } \\partial_{\\nu  }\\qty(h_{\\lambda \\alpha , \\mu } + \\cancelto{}{h_{\\mu \\lambda , \\alpha }} - h_{\\mu \\alpha , \\lambda })  \\\\\n&= \\frac{1}{2} \\eta^{\\alpha \\lambda } \\qty(h_{\\lambda \\nu , \\mu \\alpha } - h_{\\mu \\nu , \\alpha \\lambda } - \\frac{1}{2} h_{\\lambda \\alpha , \\mu \\nu } - \\frac{1}{2} h_{\\lambda \\alpha , \\mu \\nu } + h_{\\mu \\alpha , \\lambda \\nu } )\n\\,,\n\\end{align}\n\\end{subequations}\n%\nwhere we split a term in two in order to collect, so we get \n%\n\\begin{align}\nR_{\\mu \\nu } = \\frac{1}{2} \\eta^{\\alpha \\lambda } \\partial_{\\mu } \\qty(h_{\\lambda \\nu , \\alpha } - \\frac{1}{2} h_{\\lambda \\alpha , \\nu })\n+ \\frac{1}{2} \\eta^{\\alpha \\lambda } \\partial_{\\nu } \n\\qty(h_{\\mu \\alpha , \\lambda } - \\frac{1}{2} h_{\\lambda \\alpha , \\mu })- \\frac{1}{2} \\eta^{\\alpha \\lambda } \\partial_{\\alpha } \\partial_{\\lambda } h_{\\mu \\nu }\n\\,,\n\\end{align}\n%\nwhere we recognize the Dalambertian \\(\\square = \\eta^{\\alpha \\lambda  }  \\partial_{\\alpha } \\partial_{\\lambda }\\) and the trace of \\(h_{\\mu \\nu }\\): \\(h \\equiv h^{\\mu }_{\\mu }\\). So we get \n%\n\\begin{align}\nR_{\\mu \\nu } = - \\frac{1}{2} \\square h_{\\mu \\nu } \n+ \\frac{1}{2} \\partial_{\\mu } \\qty(\\partial_{\\lambda } h^{\\lambda }_{\\nu } - \\frac{1}{2} \\partial_{\\nu }h)\n+ \\frac{1}{2} \\partial_{\\nu }\\qty(\\partial_{\\lambda}  h^{\\lambda }_{\\mu } - \\frac{1}{2} \\partial_{\\mu} h)\n\\,,\n\\end{align}\n%\nso we need to solve \\(R_{\\mu \\nu }  =0 \\) with some initial conditions, since we need to solve the EFE \\(G_{\\mu \\nu } = M_P^{-2} T_{\\mu \\nu } = 0\\), which implies \\(R_{\\mu \\nu }= 0 \\). \nThe problem is that the solution is not unique: we have the freedom of choosing a gauge, since different metrics connected to each other through changes of coordinates represent the same physical scenario: \\(h_{\\mu \\nu } \\) \\emph{has no direct physical meaning}. \n\nIn general we have a change of coordinates \\(x \\to \\widetilde{x}\\), and if we do this \n%\n\\begin{align}\ng_{\\mu \\nu } \\to \\widetilde{g}_{\\mu \\nu } = \\pdv{x^{\\alpha }}{\\widetilde{x}^{\\mu  }} \\pdv{x^{\\beta }}{\\widetilde{x}^{\\nu }} g_{\\alpha \\beta }\n\\,,\n\\end{align}\n%\nbut we can only do changes of coordinates which leave the Minkowski part of the metric invariant, that is \\(\\widetilde{g}_{\\mu \\nu } = \\eta_{\\mu \\nu } + \\widetilde{h}_{\\mu \\nu }\\). We can actually restrict ourselves to infinitesimal changes of coordinates: \\(x \\to \\widetilde{x} = x + \\epsilon \\). So we do \n%\n\\begin{align}\n\\pdv{\\widetilde{x}^{\\mu }}{x^{\\alpha }} = \\partial_{\\alpha } \\qty( x^{ \\mu } + \\epsilon^{\\mu })\n= \\delta_{\\alpha }^{\\mu } + \\pdv{\\epsilon^{\\mu }}{x^{\\alpha }} = \\delta_{\\mu }^{\\alpha } + \\partial_{\\alpha } \\epsilon^{\\mu }\n\\,.\n\\end{align}\n\nInserting this inside the inverse change of coordinates formula for the metric (the one for \\(g_{\\mu \\nu }\\) in terms of \\(\\widetilde{g}_{\\mu \\nu }\\), the inverse of the one we wrote down before) we get \n%\n\\begin{subequations}\n\\begin{align}\n\\qty(\\delta^{\\mu}_{\\alpha } + \\partial_{\\alpha } \\epsilon^{\\mu }) \n\\qty(\\delta^{\\nu }_{\\beta } + \\partial_{\\beta } \\epsilon^{\\nu }) \n\\qty(\\eta_{\\mu \\nu } + \\widetilde{h}_{\\mu \\nu }) \n&= \\eta_{\\alpha \\beta } \n+h_{\\alpha \\beta }  \\\\\n\\qty(\\delta^{\\mu }_{\\alpha } \\delta^{\\nu }_{\\beta } + \\delta^{\\mu }_{\\alpha } \\partial_{\\beta } \\epsilon^{\\nu } \n+ \\delta^{\\nu  }_{\\beta  } \\partial_{\\alpha  } \\epsilon^{\\mu  } + \\mathcal{O} (\\epsilon^2))  \\qty(\\eta_{\\mu \\nu } + \\widetilde{h}_{\\mu \\nu }) &= \\eta_{\\alpha \\beta }  + h_{\\alpha \\beta }  \\\\\n\\widetilde{h}_{\\alpha \\beta }+\n\\partial_{\\alpha } \\epsilon_{\\beta } + \\partial_{\\beta } \\epsilon_{\\alpha } &= h_{\\alpha \\beta } \n\\,.\n\\end{align}\n\\end{subequations}\n\nThis freedom of changing \\(h_{\\mu \\nu }\\) is called gauge freedom: if \\(h_{\\alpha \\beta }\\) solves the linearized EFE, then \\(\\widetilde{h}_{\\alpha \\beta } = h_{\\alpha \\beta } + \\partial_{(\\alpha } \\epsilon_{\\beta )}\\) also does (there is a factor 2 missing, but it does not matter since \\(\\epsilon \\) is generic and still infinitesimal). \n\nWe can solve \\(R_{\\mu \\nu } \\) together with some extra conditions: this means \\emph{choosing a gauge}. \nWe can do this as long as, starting from a generic \\(h_{\\mu \\nu }\\), we can find a transformation \\(\\epsilon_{\\mu }\\) which leaves \\(\\eta_{\\mu \\nu } \\) invariant and for which \\(\\widetilde{h}_{\\mu \\nu } = h_{\\mu \\nu } - \\partial_{(\\mu } \\epsilon_{\\nu )}\\). \n\nFor example, a condition which cannot be imposed is \\(h_{\\mu \\nu } =0\\): if we could impose it, then it would be equivalent to have a wave or not to have it. \nThis can be shown from degrees of freedom: we only have 4 degrees of gauge freedom. \n\nSo when we set a condition we must prove that we \\emph{can actually} do so. \n\nThen, any gauge we are actually allowed to impose will give the same results for any physical experiment. \n\nAn electromagnetic analogy: since \\(\\vec{\\nabla} \\cdot \\vec{B} = 0\\), we know that we can locally choose a potential \\(\\vec{A} \\) such that \\(\\vec{B} = \\vec{\\nabla} \\times \\vec{A}\\). This has no intrinsic physical meaning, as any \\(\\vec{A}' = \\vec{A} + \\vec{\\nabla} \\lambda \\) for a scalar function \\(\\lambda \\) also gives the exact same magnetic field. \nSome gauge fixing choices are \\(\\vec{\\nabla} \\cdot \\vec{A} = 0\\) (Coulomb), \\(A_{3} = 0\\) (axial). \n\nWe do, however, use potentials since they are convenient. \nAnalogously, \\(h_{\\mu \\nu }\\) is convenient to use but it is not measurable nor unique. \n\n\\todo[inline]{Is there a gauge-independent tensorial quantity we can define starting from \\(h_{\\mu \\nu }\\), a gravitational ``field strength''?}\n\nThe last parentheses in the expression for \\(R_{\\mu \\nu } \\) is annoying: so we choose the gauge \n%\n\\begin{align}\n\\partial_{\\lambda } h^{\\lambda  }_{\\nu } - \\frac{1}{2} \\partial_{\\nu } h = 0\n\\,,\n\\end{align}\n%\nand then in this gauge we have \\(R_{\\mu \\nu } = - \\frac{1}{2}  \\square h_{\\mu \\nu }\\). \n\n\\begin{bluebox}\nThis gauge choice can also be written in terms of the Christoffel symbols: \n%\n\\begin{align}\ng^{\\mu \\nu } \\Gamma^{\\rho }_{\\mu \\nu } = 0\n\\,.\n\\end{align}\n%\n\\end{bluebox}\n\nThere are two questions we must ask: can we actually impose this condition, and why is it called harmonic? \n% The answers are yes, and because it gives a harmonic equation \\(\\square h_{\\mu \\nu } = 0\\). \n\nLet us prove the first one: \n%\n\\begin{subequations}\n\\begin{align}\n0 \\overset{?}{=} \\partial_{\\lambda } \\widetilde{h}^{\\lambda }_{\\nu } - \\frac{1}{2} \\partial_{\\nu }\\widetilde{h}\n&= \\partial_{\\lambda } \\qty( h^{\\lambda }_{\\nu } - \\partial^{\\lambda } \\epsilon_{\\nu } - \\cancelto{}{\\partial^{\\nu } \\epsilon_{\\lambda }} ) - \\frac{1}{2} \\partial_{\\nu } \\qty(h - 2 \\cancelto{}{\\partial_{\\lambda } \\epsilon^{\\lambda }})  \\\\\n&= \\partial_{\\lambda } h^{\\lambda }_{\\nu } - \\frac{1}{2} \\partial_{\\nu } h  - \\square \\epsilon_{\\nu }\n\\,,\n\\end{align}\n\\end{subequations}\n%\nwhich can be solved by setting an \\(\\epsilon_{\\nu }\\) such that:\n%\n\\begin{align}\n  \\square  \\epsilon_{\\nu } = \\partial_{\\lambda } h^{\\lambda }_{\\nu } - \\frac{1}{2} \\partial_{\\nu } h\n\\,.\n\\end{align}\n\nNotice that in this gauge \\(\\square \\widetilde{h}_{\\mu \\nu } = 0 \\): the wave equation, for a wave which propagates with velocity 1. \n\nWe have residual gauge freedom! As long as \\(\\square \\widetilde{\\epsilon}_{\\mu} = 0\\), we can still change \\(h_{\\mu \\nu }\\).\nSo the solution is not unique. The gauge is called harmonic because we can do harmonic residual gauge fixing. \nWe have 4 more degrees of freedom: we choose \\(h_{0 \\mu } \\equiv 0\\). Now we prove that this can be done. \n\nWe do not prove this in general (although it can be done), because we want to move towards a more specific example. \n\nWe then consider plane wave solutions: waves that only depend on one spatial coordinate, and are constant with respect to both other spatial coordinates. \n\nIf the direction of motion is the \\(z\\) axis, then the solution looks like \n%\n\\begin{align}\nh_{\\mu \\nu } (t, x, y, z) = C_{\\mu \\nu } \\exp(-i (k t - k z ))\n\\,.\n\\end{align}\n\nFor a wave propagating in a generic direction we will have \n%\n\\begin{align}\nh_{\\mu \\nu } (t, \\vec{x}) = C_{\\mu \\nu } \\exp(i k_{\\alpha } x^{\\alpha })\n\\,,\n\\end{align}\n%\nwhere \\(k^{\\alpha } k_{\\alpha } = 0\\) (which comes from the Fourier expression of the Dalambertian: \\(\\square = -k^{\\alpha } k_{\\alpha }\\)) is a constant vector. The scalar product in the exponent must be computed with the Minkowski metric since we are working at  first order in \\(h\\) and \\(C_{\\mu \\nu }\\) is already first order.  \n%\n\\begin{subequations}\n\\begin{align}\n\\square h_{\\mu \\nu } &= \\eta^{\\alpha \\beta } \\partial_{\\alpha } \\partial_{\\beta } \\qty(C_{\\mu \\nu } \\exp(i k_{\\alpha }x^{\\alpha }))  \\\\\n&= \\eta^{\\alpha  \\beta } C_{\\mu \\nu } \\partial_{\\alpha } \\qty(\\exp(i k_{\\alpha } x^{\\alpha }) \\partial_{\\beta } \\qty(i k_{\\alpha } x^{\\alpha }))  \\\\\n&= \\eta^{\\alpha  \\beta } C_{\\mu \\nu } i k_{ \\beta } \\partial_{\\alpha } \\qty(\\exp(i k \\cdot x )) \\\\\n&= \\eta^{\\alpha \\beta } (i k_{ \\beta }) (ik_{\\alpha }) C_{\\mu \\nu } \\exp(i k \\cdot x) = - k^2 C_{\\mu \\nu } \\exp(i k \\cdot x)\n\\,,\n\\end{align}\n\\end{subequations}\n%\nthen we see that this is always zero as long as \\(k^2=0\\), which is what we impsed for \\(k^{\\alpha }\\). \n\nWhat is the particle analog of a gravitational wave? it is a so-called \\emph{graviton}. \nFor it we will have a momentum operator \\(\\vec{p} = - i \\hbar \\vec{\\nabla}\\) and an energy operator \\(E = i \\hbar \\partial_{t}\\). We can apply both of these to our wave to find that it is an eigenvector of both: \n%\n\\begin{align}\nE h_{\\mu \\nu } = i \\hbar \\partial_{t} \\qty(C_{\\mu \\nu } \\exp(i k \\cdot x))= \\hbar k^{t} h_{\\mu \\nu } \n\\,,\n\\end{align}\n%\nand we know that \\(k^{t} = \\abs{\\vec{k}}\\). \n\nIf we compute the momentum, analogously we find \\(\\vec{p} h_{\\mu \\nu } = \\hbar \\vec{k}\\). \n\nThis means that \\(p \\cdot p  = 0\\), which means that the mass of the graviton is equal to zero. \n\n\n\n\\end{document}", "meta": {"hexsha": "08da1cdb52c94426440a401ce3a83b78188933ca", "size": 11679, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ap_first_semester/general_relativity/20dec.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "ap_first_semester/general_relativity/20dec.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ap_first_semester/general_relativity/20dec.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 54.3209302326, "max_line_length": 354, "alphanum_fraction": 0.6385820704, "num_tokens": 4000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6001883735630722, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3164892465201161}}
{"text": "\n\n\\section{Related Work}\n\nQuantum algorithms have drawn much attention and there are many problems for which specialized algorithms have been designed, such as searching \\cite{Grover96} \\cite{BoyerBHT98}, Element Distinctness \\cite{Santha08}, Minimum-Finding \\cite{DurrH96} and many others (e.g., \\cite{DurrHHM04} \\cite{BerzinaDFLS04}, \\cite{Zhangthesis06}).\n\nEvolutionary Algorithms (EA) aim not to look specifically into a certain problem, but rather provide some wide-applicable algorithms which may be used if it is not possible to analyze the problem thoroughly - either because the problem complexity is too high, or because the algorithm designer can not spend much time and resources into investigating the problem.\n\nQuantum Evolutionary Algorithms (QEA) have the same objective, but are algorithms that run on a quantum computer. They are not to be confused with Quantum-Inspired Evolutionary Algorithms (QIEA), which use ideas from quantum computing, but are algorithms that run on a classical machine.\n\nIt is difficult to test QEAs in practice, because quantum computers do not exist apart from proof-of-concept machines. It is possible to run QEAs by simulating a quantum computer on a classical machine (e.g., \\cite{SpectorBBS99}), but this approach is cumbersome since such simulations have exponential running time.\n\nSantha and Szegedy have shown \\cite{SanthaS09} that quantum and classical query complexities of local search are polynomially related. Moreover, Magniez et al. have shown \\cite{MagniezNRS09} that the speed-up in terms of hitting times is exactly quadratic for a large class of algorithms (``quantum random walks'' in the sense of \\cite{Szegedy04} - note that there are different notions of quantum random walks, cf. \\cite{MagniezNRS07} for an overview).\n\nFor some classes of local search problems, more specific and superior algorithms are available: In particular for search spaces with transition probabilities that are symmetric \\cite{Szegedy04}, or ergodic \\cite{MagniezNRS07}.\n\nIn our paper, we do not prove lower bounds. Conjectures of Aaronson \\cite{Aaronson06} imply that the EA-algorithms considered in our paper are asymptotically optimal.  He has shown his conjecture for hypercubes, and Zhang \\cite{Zhang06} has generalized the result to product graphs.\n\n\n%\\cite{MagniezNRS09}, \\cite{Aaronson06}, \\cite{DurrHHM04},\n%\\cite{DurrH96}, \\cite{DurrHHM06}, \\cite{HoyerNS02}, \\cite{SanthaS04},\n%\\cite{MagniezNRS07}, \\cite{Santha08}, \\cite{SanthaS09},\n%\\cite{SpectorBBS99}, \\cite{Zhang06}, \\cite{LiR07}, \\cite{ZhouZHW05},\n%\\cite{NarayananM96}, \\cite{HanK02}, \\cite{LiLR07}, \\cite{XiaoYLYZ08},\n%\\cite{ZhangZPW08}, \\cite{AraujoNM08}, \\cite{MahdabiJA08},\n%\\cite{ZhangGW08}, \\cite{LiSGS09}, \\cite{WangWF09}, \\cite{XingJBLQW09},\n%\\cite{ZhangS06}, \\cite{Ambainis06}, \\cite{Ambainis08},\n%\\cite{AmbainisSW09}, \\cite{AmbainisCGT09}, \\cite{HoyerNS01}\n\n\n", "meta": {"hexsha": "951aa6db73bbc03b988d0216bd43d231c49f2656", "size": 2878, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "contents/research/publication/Journal/2014-01-01-Evolutionary-Algorithms-For-Quantum-Computers/relatedwork.tex", "max_stars_repo_name": "piyush-kurur-pages/website", "max_stars_repo_head_hexsha": "246dfa730328b45b65840ebed3293e96c497aa86", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-04-16T09:55:17.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-16T09:55:17.000Z", "max_issues_repo_path": "contents/research/publication/Journal/2014-01-01-Evolutionary-Algorithms-For-Quantum-Computers/relatedwork.tex", "max_issues_repo_name": "piyush-kurur-pages/website", "max_issues_repo_head_hexsha": "246dfa730328b45b65840ebed3293e96c497aa86", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "contents/research/publication/Journal/2014-01-01-Evolutionary-Algorithms-For-Quantum-Computers/relatedwork.tex", "max_forks_repo_name": "piyush-kurur-pages/website", "max_forks_repo_head_hexsha": "246dfa730328b45b65840ebed3293e96c497aa86", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-10T22:18:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T22:18:56.000Z", "avg_line_length": 92.8387096774, "max_line_length": 453, "alphanum_fraction": 0.7876997915, "num_tokens": 787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.3164892389779779}}
{"text": "\\input{header.tex}\n\\begin{document}\n\n\\frame{\\maketitle}\n\n\n%\\begin{frame}\n%\\tableofcontents\n%\\end{frame}\n\n\n\\begin{frame}{ $IV$ curve: $0$ to $\\SI{130}{\\volt}$}\n\n  \\begin{columns}\n\n   \\begin{column}{0.48\\textwidth}\n     \\begin{figure}\n       \\centering\n       \\includegraphics[width=1.05\\textwidth]{./iv_curve_reverse_bias_pixel_detectors.png}\n       \\caption{ Theoretical $IV$ curve \\cite{pixel_detectors}. }\n       \\label{ fig: iv_curve_theoretical}\n     \\end{figure}\n   \\end{column}\n\n   \\begin{column}{0.48\\textwidth}\n     \\begin{figure}\n       \\centering\n       \\includegraphics[width=1.05\\textwidth]{./iv_curve_0_130_V.pdf}\n       \\caption{Measured $IV$ curve. }\n       \\label{ fig: iv_curve_measured}\n     \\end{figure}\n   \\end{column}\n\n  \\end{columns}\n\n\\end{frame}\n\n\\section{Laserwidth}\n\n\\begin{frame}{ Measurment - $\\SI{5}{\\milli\\meter}$ }\n\n  \\begin{figure}\n    \\centering\n    \\includegraphics[width=\\textwidth]{./5_mm_measurment_plot.pdf}\n    \\caption{Measured Laserbeam }\n    \\label{ fig: 5_mm }\n  \\end{figure}\n\n\\end{frame}\n\n\n\\begin{frame}{ Fit - $\\SI{5}{\\milli\\meter}$ }\n  \\begin{columns}\n\n   \\begin{column}{0.48\\textwidth}\n     \\begin{figure}\n       \\centering\n       \\includegraphics[width=1.05\\textwidth]{./5_mm_erorbar_plot_col.pdf}\n       \\caption{ Fit Columns }\n       \\label{ fig: iv_curve_theoretical}\n     \\end{figure}\n   \\end{column}\n\n   \\begin{column}{0.48\\textwidth}\n     \\begin{figure}\n       \\centering\n       \\includegraphics[width=1.05\\textwidth]{./5_mm_erorbar_plot_row.pdf}\n       \\caption{ Fit Rows }\n       \\label{ fig: iv_curve_measured}\n     \\end{figure}\n   \\end{column}\n\n  \\end{columns}\n\n\\end{frame}\n\n\\begin{frame}{ Measurment - $\\SI{9}{\\milli\\meter}$ }\n\n  \\begin{figure}\n    \\centering\n    \\includegraphics[width=\\textwidth]{./9_mm_measurment_plot.pdf}\n    \\caption{Measured Laserbeam }\n    \\label{ fig: 5_mm }\n  \\end{figure}\n\n\\end{frame}\n\n\n\\begin{frame}{ Fit - $\\SI{9}{\\milli\\meter}$ }\n  \\begin{columns}\n\n   \\begin{column}{0.48\\textwidth}\n     \\begin{figure}\n       \\centering\n       \\includegraphics[width=1.05\\textwidth]{./9_mm_erorbar_plot_col.pdf}\n       \\caption{ Fit Columns }\n       \\label{ fig: iv_curve_theoretical}\n     \\end{figure}\n   \\end{column}\n\n   \\begin{column}{0.48\\textwidth}\n     \\begin{figure}\n       \\centering\n       \\includegraphics[width=1.05\\textwidth]{./9_mm_erorbar_plot_row.pdf}\n       \\caption{ Fit Rows }\n       \\label{ fig: iv_curve_measured}\n     \\end{figure}\n   \\end{column}\n\n  \\end{columns}\n\n\\end{frame}\n\n\n\\begin{frame}{ Measurment - $\\SI{15}{\\milli\\meter}$ }\n\n  \\begin{figure}\n    \\centering\n    \\includegraphics[width=\\textwidth]{./15_mm_measurment_plot.pdf}\n    \\caption{Measured Laserbeam }\n    \\label{ fig: 5_mm }\n  \\end{figure}\n\n\\end{frame}\n\n\n\\begin{frame}{ Fit - $\\SI{15}{\\milli\\meter}$ }\n\n  \\begin{columns}\n\n   \\begin{column}{0.48\\textwidth}\n     \\begin{figure}\n       \\centering\n       \\includegraphics[width=1.05\\textwidth]{./15_mm_erorbar_plot_col.pdf}\n       \\caption{ Fit Columns }\n       \\label{ fig: iv_curve_theoretical}\n     \\end{figure}\n   \\end{column}\n\n   \\begin{column}{0.48\\textwidth}\n     \\begin{figure}\n       \\centering\n       \\includegraphics[width=1.05\\textwidth]{./15_mm_erorbar_plot_row.pdf}\n       \\caption{ Fit Rows }\n       \\label{ fig: iv_curve_measured}\n     \\end{figure}\n   \\end{column}\n\n  \\end{columns}\n\n\\end{frame}\n\n\\begin{frame}{ First Result }\n\n     \\begin{figure}\n       \\centering\n       \\includegraphics[width=0.8\\textwidth]{./perfect_height.pdf}\n       \\caption{ Sigma against height }\n       \\label{ fig: iv_curve_theoretical}\n     \\end{figure}\n\n\\end{frame}\n\n\n\\end{document}\n", "meta": {"hexsha": "1918aefbaecde3a9af5fd2db64942709bf1aa6de", "size": 3585, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "results_meeting/presentation.tex", "max_stars_repo_name": "beckstev/purdue_laser_box", "max_stars_repo_head_hexsha": "aa4fbf2f3cf6a43fea0a8939d2b22005ffae9bc0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "results_meeting/presentation.tex", "max_issues_repo_name": "beckstev/purdue_laser_box", "max_issues_repo_head_hexsha": "aa4fbf2f3cf6a43fea0a8939d2b22005ffae9bc0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "results_meeting/presentation.tex", "max_forks_repo_name": "beckstev/purdue_laser_box", "max_forks_repo_head_hexsha": "aa4fbf2f3cf6a43fea0a8939d2b22005ffae9bc0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5963855422, "max_line_length": 90, "alphanum_fraction": 0.6373779637, "num_tokens": 1143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.3164892389779779}}
{"text": "\\chapter{Introduction}\n\\section{Introduction}\nThe \\textit{algorithm selection} (AS) problem presents the question, \"Given a set of algorithms, how to choose one that best solves a given problem?\" AS is best applied in solving intractable problems, whose solutions often require brute-force or heuristic approaches. An effective method of performing AS has broad implications on solving real-world problems which often are intractable in nature.\n\n\\section{Problem Background}\nA survey of AS techniques \\citep{kotthoff2016algorithm} reported a majority of approaches that used supervised learning in training an AS model. Can reinforcement learning (RL) techniques be used? Recently, RL emerged as a superior approach to learning as demonstrated in applications such as automatic design of neural network architecture \\citep{zoph2016neural} and board game AI exhibiting superhuman performance \\citep{silver2016mastering}. This study explores the potential of RL in training AS models with superior performance. The AS models in this study focus on solving a set of hard computational tasks called subgraph isomorphism problems. This is an NP-complete problem under graph theory where the objective is to determine if a graph contains a pattern of a much smaller graph. A recent study tackled this problem by building and training an AS model using pairwise random forest regression \\citep{kotthoff2016portfolios}. This study tries to improve upon the results of the previous study by proposing RL as an alternative to training AS models.\n\n\\section{Problem Statement}\nThis study addresses how reinforcement learning can be applied to algorithm selection for subgraph isomorphism problems. Specifically, it attempts to answer the following questions:\n\\begin{itemize}\n\t\\item How can the algorithm selection problem be viewed from the perspective of reinforcement learning?\n\t\\item Can reinforcement learning be used to train an algorithm selection model in solving subgraph isomorphism problems?\n\t\\item Does an algorithm selection model perform better when trained using reinforcement learning as compared to supervised learning?\n\\end{itemize}\n\n\\section{Research Objectives}\nThis study aims to use reinforcement learning in training an algorithm selection model for subgraph isomorphism problems. Specifically, it attempts to meet the following objectives:\n\\begin{itemize}\n\t\\item To prepare the subgraph isomorphism dataset for training the algorithm selection model.\n\t\\item To implement a reinforcement learning algorithm for training an algorithm selection model.\n\t\\item To evaluate whether reinforcement learning can improve the performance of the algorithm selection model as compared to supervised learning.\n\\end{itemize}\n\n\\section{Scope of the Study}\nThe constraints observed in this study are outlined below:\n\\begin{itemize}\n\t\\item The AS models are trained and tested using the subgraph isomorphism dataset generated from a previous related study by Kotthoff \\citep{kotthoff2016portfolios}\n\t\\item The characteristics of the dataset impose restrictions on how training and testing can proceed.\n\t\\begin{itemize}\n\t\t\\item The problems focus only on subgraph isomorphism problems.\n\t\t\\item The set of algorithms are predefined and fixed.\n\t\t\\item The model can only be trained to match one algorithm to one problem at a time.\n\t\\end{itemize}\n\t\\item Only one RL algorithm is considered in this study.\n\\end{itemize}\n\n\\section{Significance of the Study}\nThis study contributes to the following:\n\n\\begin{itemize}\n\t\\item Investigates the feasibility of training algorithm selection models using reinforcement learning.\n\t\\item Provides insights on how reinforcement learning algorithms can be applied to algorithm selection.\n\t\\item Introduces the potential of reinforcement learning in training effective algorithm selection models.\n\\end{itemize}\n", "meta": {"hexsha": "3e86431e94ded5ebfb86f9e8be7d78f6e14b828d", "size": 3835, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/tex/ch1_introduction.tex", "max_stars_repo_name": "kvrigor/algosel-rl", "max_stars_repo_head_hexsha": "c8a32d071325ec455e4bf1019e94cce0c304ad3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-28T21:47:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-28T21:47:36.000Z", "max_issues_repo_path": "paper/tex/ch1_introduction.tex", "max_issues_repo_name": "kvrigor/algosel-rl", "max_issues_repo_head_hexsha": "c8a32d071325ec455e4bf1019e94cce0c304ad3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/tex/ch1_introduction.tex", "max_forks_repo_name": "kvrigor/algosel-rl", "max_forks_repo_head_hexsha": "c8a32d071325ec455e4bf1019e94cce0c304ad3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-18T06:06:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-18T06:06:01.000Z", "avg_line_length": 85.2222222222, "max_line_length": 1060, "alphanum_fraction": 0.8234680574, "num_tokens": 766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.31648923006116875}}
{"text": "\\documentclass[12]{scrartcl}\n\\usepackage{amssymb,amsmath,gensymb,dsfont,calc,multicol,fullpage}\n\\makeatletter\n\\newcommand\\Aboxed[1]{\n   \\@Aboxed#1\\ENDDNE}\n\\def\\@Aboxed#1&#2\\ENDDNE{%\n   &\n   \\settowidth\\@tempdima{$\\displaystyle#1{}$}\n   \\setlength\\@tempdima{\\@tempdima+\\fboxsep+\\fboxrule}\n   \\kern-\\@tempdima\n   \\boxed{#1#2}\n}\n\\makeatother\n\n\\begin{document}\n\n\\title{Homework 21, Section 4.3: 3, 4, 7, 10, 15, 25}\n\\author{Alex Gordon}\n\\date{\\today}\n\\maketitle\n\\section*{Homework}\n\\subsection*{3.}\nThis set does not form a basis for $R^3$. The set is linearly dependent and does not span $R^3$\n\\subsection*{4.}\nThe determinant equals 1, so these vectors are linearly independent. These vectors form a basis for $R^3$. \n\\subsection*{7. }\nThis set does not form a basis for $R^3$ because it is linearly independent and  $m \\geq n$. \n\\subsection*{10.}\nThe RREF is $ \\begin{bmatrix}  1 & 0 & 0 & 2 & 3 & 0 \\\\ 0 & 1 & 0 & -1 & -2 & 0 \\\\ 0 & 0 & 1 & 0 & -2 & 0  \\end{bmatrix} $. The span is then $ \\begin{bmatrix}  -2 \\\\ 1 \\\\ 0 \\\\ 1 \\\\ 0  \\end{bmatrix} $, $ \\begin{bmatrix}  -3 \\\\ 2 \\\\ 2 \\\\ 0 \\\\ 1  \\end{bmatrix} $\n\\subsection*{15.}\nThe RREF is $ \\begin{bmatrix}  1 & 0 & 2 & 2 & 3 \\\\ 0 & 1 & -2 & -1 & -1 \\\\ -2 & 2 & -8 & 10 & -6 \\\\ 3 & 3 & 0 & 3 & 9   \\end{bmatrix} $. This reduces to \\\\\n$ \\begin{bmatrix}  1 & 0 & 2 & 2 & 3 \\\\ 0 & 1 & -2 & 0 & 0 \\\\ 0 & 0 & 0 & 1 & 0 \\\\ 0 & 0 & 0 & 0 & 1 \\end{bmatrix}    $\n\\subsection*{25.}\nYes it is a basis a typical element in H is $sv1 + (t-s)v2 + sv3$. \n\nwe can re-write this as $s(v1+v3) + (t-s)(v2), so \\{v1+v3,v2\\}$ is a basis for H. \n\nthe problem is that the span of \\{v1,v2,v3\\} is much bigger than H, it is all of $R^3$. \nThis means that just because it is linearly independent, it is not the basis for H. Since the basis of the subspace is not isomorphic to R or $R^2$, it's too big for the span. \n\n\\end{document}", "meta": {"hexsha": "e679ecb86a81bb17dd493f20ef6189bd32dae66c", "size": 1853, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "LinearAlgebra/Homework21.tex", "max_stars_repo_name": "alexggordon/latex", "max_stars_repo_head_hexsha": "7dd945f33490e6585e26cff39d9cf6ad8f582a0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LinearAlgebra/Homework21.tex", "max_issues_repo_name": "alexggordon/latex", "max_issues_repo_head_hexsha": "7dd945f33490e6585e26cff39d9cf6ad8f582a0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LinearAlgebra/Homework21.tex", "max_forks_repo_name": "alexggordon/latex", "max_forks_repo_head_hexsha": "7dd945f33490e6585e26cff39d9cf6ad8f582a0e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.1951219512, "max_line_length": 259, "alphanum_fraction": 0.6157582299, "num_tokens": 777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.31648923006116875}}
{"text": "\n\\typeout{new file: Band_Models_Chapter.tex}\n\n\\chapter{Narrow Band Models and Approximations}\n\\label{chap:SNB}\n\nThis chapter briefly presents the models and their formulations that are used in RadCal. The reader seeking further details on the rather complex theory behind these models is invited to read the exhaustive monographs from Penner~\\cite{Penner1959}, Tien~\\cite{Tien1968}, and Modest~\\cite{Modest2013}, the reviews from De Ris~\\cite{DeRis1979} and from Viskanta and Menguc~\\cite{vm_87}, and the report from Ludwig \\textit{et al.}~\\cite{Ludwig1973}. Most of the equations used in RadCal can be found in the latter.\n\nRadCal was designed for uses at moderate gas pressure (near atmospheric pressure) and for ambient to high gas temperatures (typically from around 300~K to 2500~K). As such, collision broadening is the main broadening mechanism considered. However, the effects of Doppler line broadening, which are common at low pressure (typically less than 0.01 atm) and/or at high temperature, are still accounted for in the overall expression of narrow-band transmissivity. The Doppler broadening effect is accounted using the method presented in Ludwig \\textit{et al.}~\\cite{Ludwig1973}. The Voigt profile, commonly used in atmospheric sciences~\\cite{Chu1994}, is not considered here. Unlike the Lorentz profile the Voigt profile does not have a closed analytical expression. Effects of scattering or reflection are not included in RadCal; as such, RadCal considers only absorption and emission.\n\nRadCal can be used to model homogeneous and non-homogeneous conditions. Following Ludwig~\\cite{Ludwig1973}, the Curtis-Godson approximation is then used with the assumption of Single Line Group. In the case of a mixture of different radiative participating gases, the contribution for each species is calculated independently and their contribution on the total spectral optical depth is assumed to be additive. Finally, it is important to recall the important assumption of local thermodynamic equilibrium used in establishing the Radiative Transfer Equation as solved by RadCal. This justifies consideration of the Planck blackbody distribution law for the emission term.\n\n\\section{Introduction}\n\n\\subsection{Radiative Transfer Equation (RTE)}\nThe expression of the equation of transfer in non-scattering, participating media in local thermodynamic equilibrium is recalled. This equation is the mathematical foundation of RadCal. The Eulerian point of view is adopted here. The assumption of local thermodynamic equilibrium has for consequences that the spectral blackbody emission can be modeled with the Planck blackbody distribution - denoted from here and in the rest of this manuscript $I_b$, and that the Kirchoff law applies at the spectral level, \\textit{i.e.} for a monochromatic light the absorption and emission coefficients are equal. The amount of radiative energy emitted by a participating medium of local thermodynamic temperature $T$, over an infinitesimal spectrum $\\d\\nu$, in an arbitrary direction $\\hat{\\textbf{s}}$, and along an infinitesimal length $\\d s$, is expressed by:\n\\begin{equation}\\label{eq:emission}\n j_{e,\\nu} \\d s \\d\\nu = \\kappa_{\\nu} I_{\\rm b,\\nu}(T)\\d\\nu \\d s\n\\end{equation}\nwhere $j_{e,\\nu}$ is the emission at the frequency $\\nu$, $\\kappa_{\\nu}$ is the absorption coefficient at the considered frequency, $I_{b,\\nu}$ denotes the spectral intensity emitted by a blackbody of temperature $T$. Naturally, the absorption coefficient $\\kappa_{\\nu}$ is proportional to the amount of local participating molecule.\n\n\nNote: it is common in spectroscopy to use $B_b$ and $\\tilde{\\nu}$ as the Planck function and wavenumber, respectively. However in the continuation of the previous work on RadCal, we keep the previously used nomenclature. In the rest of the manuscript, $\\omega$ denotes the wavenumber. A common units employs to characterize radiative spectrum is the wavelength, denoted $\\la$. Wavelength $\\la$ represents the distance traveled during one cycle when propagating at the speed of light in vacuum. When dealing with infrared radiation, its units are commonly expressed in ${\\rm \\mu m}$. Wavenumber $\\om$ is the reciprocal of the wavelength. It represents the number of cycles per unit of length. It is expressed in units of ${\\rm cm^{-1}}$. It is convenient to use wavelength $\\la$ or wavenumber $\\om$ instead of frequency $\\nu$ when dealing with thermal radiation. Wavenumber and wavelength are related to frequency through:\n\\be\n \\la = c/\\nu \\: \\: \\rm{and} \\: \\: \\om = \\nu /c,\n\\ee\n and one can easily switch from wavenumber in units of ${\\rm cm^{-1}}$ to wavelength in units of ${\\rm \\mu m}$ with:\n\\be\n  \\la \\; {\\rm \\mu m}  \\; = 10000/\\om \\; \\; {\\rm cm^{-1}}.\n\\ee\n\nSimilarly to Eq.~\\ref{eq:emission}, an expression characterizing the amount of energy of an incident beam, of propagating direction $\\hat{\\textbf{s}}$ absorbed by local participating molecules over an infinitesimal spectrum $\\d\\nu$ and along an infinitesimal length $\\d s$ can be derived:\n\\begin{equation}\\label{eq:absorption}\n  j_{a,\\nu} \\d\\nu \\d \\rm s = - \\kappa_{\\nu} I_{\\nu} \\d\\nu \\d \\rm s\n\\end{equation}\nwhere $I_{\\nu}$ is the spectral intensity at frequency $\\nu$ of the incident beam of direction $\\vec{\\textbf{s}}$.\n\nUsing Eqs.~\\ref{eq:emission} and \\ref{eq:absorption}, the change in the spectral intensity of an incident beam of direction $\\hat{\\textbf{s}}$ penetrating a participating medium over a distance $\\d s$ is then expressed by:\n\\be\n\\d I_{\\nu}\\d \\nu = (j_{e,\\nu} + j_{a,\\nu}) \\d s \\d\\nu.\n\\ee\nThe local Radiative Transfer Equation (neglecting scattering) is then expressed as:\n\\begin{equation}\\label{eq:localRTE}\n \\dfrac{\\d I_{\\nu}}{\\d s}\\d \\nu = \\kappa_{\\nu} (I_{\\rm b,\\nu}(T) - I_{\\nu}) \\d \\nu.\n\\end{equation}\nEquation~\\ref{eq:localRTE} is a first-order ordinary differential equation; it is assumed here that the speed of light is very large compared to local time and length scales involved. The functional form of the spectral intensity $I_{\\nu}(s)$ at an arbitrary depth $s$ within the participating medium, assuming that the participating medium starts at $s=0$, is expressed as:\n\\begin{equation}\\label{eq:RTE_Kappa}\nI_{\\nu}(s) =  I_{\\nu}(0) \\exp\\left(-\\displaystyle\\int_{0}^{s}{\\kappa_{\\nu}\\d s}'\\right) + \\displaystyle\\int_0^{s}{I_{\\rm b,\\nu}\\left(T(s')\\right)\\exp\\left(-\\displaystyle\\int_{s'}^{s}{\\kappa_{\\nu}\\d s''}  \\right)\\kappa_{\\nu} \\d s'}.\n\\end{equation}\nNote that $\\kappa_{\\nu}$ is a function of the local thermodynamic conditions and hence is an implicit function of $s$.\n\nThe first right-hand side term of Eq.~\\ref{eq:RTE_Kappa} represents the fraction of the incident spectral intensity that is transmitted unto the depth $s$. The second right-hand side term corresponds to the contribution of the local emission and accounts for self-absorption.\nThe spectral transmissivity, denoted $\\tau(\\nu; 0 \\rightarrow s)$, is defined as the fraction of the spectral energy of frequency $\\nu$ incident upon a participating medium which is transmitted by it. It can be seen from Eq.~\\ref{eq:RTE_Kappa}, that an explicit formulation of the spectral transmissivity is:\n\\begin{equation}\\label{eq:tau_definition}\n \\tau(\\nu; 0 \\rightarrow s) = \\exp\\left(-\\displaystyle\\int_{0}^{s}{\\kappa_{\\nu}\\d s'}\\right).\n\\end{equation}\nIt can be shown that:\n\\be\n\\exp\\left(-\\displaystyle\\int_{s'}^{s}{\\kappa_{\\nu}\\d s''}\\right) \\kappa_{\\nu} = \\dfrac{\\partial \\tau}{\\partial s'}(\\nu; s' \\rightarrow s).\n\\ee\nTherefore, the RTE can be rewritten as:\n\\be\\label{eq:RTE_Final}\nI_{\\nu}(s) =  I_{\\nu}(0) \\tau(\\nu; 0 \\rightarrow s) + \\displaystyle\\int_0^{s}{I_{\\rm b,\\nu}\\left(T(s')\\right)\\dfrac{\\partial \\tau  }{\\partial s'}(\\nu; s' \\rightarrow s) \\d s'}.\n\\ee\n\nEquation~\\ref{eq:RTE_Final} represents the fundamental governing equation for the radiative transfer into a non-scattering, non-reflective participating medium at local thermodynamic equilibrium. This equation is valid regardless whether the model is homogeneous or not. It is of course assumed here that the spectral distribution of the incident intensity, $I_{\\nu}(s=0)$, is known. In RadCal, $I_{\\nu}(0)$ is the spectral distribution of a blackbody at a temperature defined by the user. This temperature is referred to as the \\textit{wall} temperature, denoted $T_w$.\n\nEquation~\\ref{eq:RTE_Final} can be used to calculate the incident energy at the location $s$ comprised in a spectral range $\\Delta \\nu$:\n\n\\be\\label{eq:RTE_Final_int}\n\\displaystyle\\int_{\\Delta \\nu }{I_{\\nu}(s) \\d \\nu}  = \\displaystyle\\int_{\\Delta \\nu}{I_{\\nu}(0) \\tau(\\nu; 0 \\rightarrow s)}\\d \\nu + \\displaystyle\\int_{\\Delta \\nu}{\\displaystyle\\int_0^{s}{I_{\\rm b,\\nu}\\left(T(s')\\right)\\dfrac{\\partial \\tau  }{\\partial s'}(\\nu; s' \\rightarrow s) \\d s'} \\d \\nu}.\n\\ee\nSome simplifications can be made if one assumes that $\\Delta \\nu$ is small enough so that $I_{\\nu}$ and $I_{\\rm b,\\nu}$ can satisfactorily be assumed constant over $\\Delta \\nu$. In this case, Eq.~\\ref{eq:RTE_Final_int} can be written as:\n\\be\nI_{\\nu_0}(s)  = {I_{\\nu_0}(0) \\bar{\\tau}(\\nu_0; 0 \\rightarrow s)} + {\\displaystyle\\int_0^{s}{I_{\\rm b,\\nu_0}\\left(T(s')\\right)\\dfrac{\\partial \\bar{\\tau}  }{\\partial s'}(\\nu_0; s' \\rightarrow s) \\d s'}},\n\\ee\nwhere $\\nu_0$ is the center of the narrow-band $\\Delta \\nu$ and with\n\\be\n\\bar{\\tau} = \\dfrac{1}{\\Delta \\nu}\\displaystyle\\int_{\\Delta \\nu}{\\tau \\d \\nu} = \\dfrac{1}{\\Delta \\nu} \\displaystyle\\int_{\\Delta \\nu}{\\exp \\left( -\\displaystyle\\int{\\kappa_{\\nu} \\d s'} \\right) \\d \\nu}.\n\\ee\nIt is very important, in the narrow-band framework, to note that in general:\n\\be\\label{eq:NB_frame_work}\n\\bar{\\tau} \\neq \\exp\\left(-\\displaystyle\\int{\\bar{\\kappa}_{\\nu} \\d s'} \\right),\n\\ee\nwhere the mean absorption coefficient $\\kappa_{\\nu}$ is defined as the average of the spectral absorption coefficient over the spectral range $\\Delta \\nu$:\n\\be\n\\bar{\\kappa}_{\\nu} = \\dfrac{1}{\\Delta \\nu} \\displaystyle\\int_{\\Delta \\nu}{{\\kappa}_{\\nu} \\d \\nu}.\n\\ee\nEquation~\\ref{eq:NB_frame_work} arises from:\n\\be\n\\displaystyle\\int_{\\Delta}{\\exp f(x) \\d x} \\neq  \\exp\\left(\\displaystyle\\int_{\\Delta}{f(x) \\d x} \\right),\n\\ee\nwhere the equality is only verified for some particular functions and integration domain.\n\n\nOne of the main difficulties in calculating the incident radiative intensity over a given spectral range is the rapid variation of $\\kappa_{\\nu}$ with $\\nu$ for all gas phase species. Indeed, the spectroscopic study of participating species in gas-phase shows that their infrared spectrum consists of millions of narrow peaks. The discrete nature of the infrared spectrum is a direct consequence of the quantification of the energy associated with a species molecular vibration and rotation motions. Figure~\\ref{fig:H2O_Detailed_spectrum} below plots the spectral absorption coefficient for $\\rm H_2O$ in the spectral range 1050 -- 1100~cm$^{\\rm -1}$. This spectrum was generated using $\\rm H_2O$ line specifications from the HITRAN 2012 database \\cite{Rothman2013}.\n\n\\begin{figure}\n\\begin{center}\n \\includegraphics[width=4.0in]{Figures/H20_Line_Strength.png}\n\\end{center}\n \\caption{Spectral $\\rm H_2O$ absorption coefficient $\\kappa_{\\om}$ for the spectral range 1000 -- 1050~cm$^{\\rm -1}$. This synthetic spectrum calculated using HITRAN 2012 line specifications assumes a temperature of 296~K and 10\\% of water in a total pressure of 1~atm.\\label{fig:H2O_Detailed_spectrum}}\n\\end{figure}\n\n\\subsection{Planck blackbody distribution law}\n\nThe Planck blackbody distribution law, sometime called the Planck function, but the term is misleading as it is a distribution, describes the spectral distribution of the equilibrium rate of radiant energy emitted from a blackbody at temperature $T$. Its expression is given, as a function of frequency $\\nu$ and for an unit of solid angle, by:\n\\begin{equation}\\label{eq:Plank_freqency}\nI_{\\rm b,\\nu}(T) = \\displaystyle\\frac{2 h\\nu^3}{c^2}\\displaystyle\\frac{1}{\\exp\\left(\\displaystyle\\frac{h\\nu}{k_{\\rm B}T}\\right)-1}.\n\\end{equation}\nHere, $h$ is the Planck constant ($6.626 \\times 10^{-34}$~J$\\cdot$s), and $k_{\\rm B}$ is the Boltzmann constant ($1.381 \\times 10^{-23}$~J/K). $I_{\\rm b,\\nu}(T)$ is in units of $\\rm{W/m^{2}/str/s^{-1}}$.\n\nIn terms of wavenumber, the Planck blackbody distribution law, $I_{\\rm b,\\om}$, is written:\n\\be\\label{eq:Planck_WN}\nI_{\\rm b,\\om}(T) = \\dfrac{2 \\, h \\, c^2 \\, \\om^{3}}{\\exp\\left(\\dfrac{h \\, c\\, \\om}{k_{\\rm B} \\, T }\\right)-1} .\n\\ee\n$I_{\\rm b,\\om}(T)$ is in units of $\\rm{W/m^2/str/m^{-1}}$; the wavenumber $\\om$ in Eq.~\\ref{eq:Planck_WN} is in units of $\\rm{m^{-1}}$.\n\nThe user who wishes to express the Planck blackbody distribution law as a function of wavelength should take caution when performing the change of variables. One should start by expressing that the radiant energy emitted at a wavelength $\\la$ over an infinitesimal spectral range $\\d\\la$ is the same as the radiant energy emitted at the corresponding wavenumber $\\om$ over an infinitesimal spectral range $\\d\\om$:\n\\be \\label{eq:Planck_WN_WL}\nI_{\\rm b,\\la}(T) \\d \\la = -I_{\\rm b,\\om}(T)\\d \\om,\n\\ee\nthe negative sign is introduced because $\\om$ is the reciprocal of $\\la$. Since $\\la$ = 1/$\\om$, it comes:\n\\be\n\\dfrac{\\d \\la}{\\d \\om} = -\\dfrac{1}{\\om^2}.\n\\ee\nEquation \\ref{eq:Planck_WN_WL} can be rewritten, after the appropriate change of variables:\n\\be \\label{eq:Planck_WL}\nI_{\\rm b,\\la}(T) = \\dfrac{2 \\, h \\, c^2}{\\la^5}\\dfrac{1}{\\exp\\left(\\dfrac{h \\, c}{\\la \\, k_{\\rm B} \\, T }\\right)-1},\n\\ee\nwhere $I_{\\rm b,\\la}$ is in units of $\\rm{W/m^2/str/m}$; the wavelength $\\la$ in Eq.~\\ref{eq:Planck_WL} is in unit of $\\rm m$.\n\n\\begin{figure}\n\\begin{center}\n \\includegraphics[width=6.5in]{Figures/Black_body.png}\n\\end{center}\n \\caption{Normalized spectral Blackbody distributions at T = 500~K (blue line) and T = 1800~K (red line) with the wavelength in units of $\\mu m$ (left) and with the wavenumber in units of $\\rm cm^{-1}$ (right). \\label{fig:bb_spectrum}}\n\\end{figure}\n\nFigure~\\ref{fig:bb_spectrum} plots profiles of normalized spectral Blackbody distribution for temperatures of 500~K and 1800~K using wavelength and wavenumber. It can be seen that an increase of temperature will shift the mode of the distribution toward lower wavelength and higher wavenumber. Figure~\\ref{fig:bb_spectrum} indicates that the shape of the distribution is not invariant with the units chosen to characterize the spectrum. Indeed, while an elevation of blackbody temperature corresponds to a narrowing of the normalized distribution when using wavelength, the same elevation of blackbody temperature leads to a spreading of the profile when using wavelength. Finally, an important remark is that the location of the distribution mode (corresponding to the location of maximum emission) does not relate between wavelength and wavenumber. This location can be calculated using the Wien's displacement law. Using wavelength, the Wien's displacement law is expressed by:\n\\begin{equation}\\label{eq:Wien_WL}\n\\la_{\\rm max} T = 2898 \\; \\mu \\rm m . \\rm K,\n\\end{equation}\nwhile using wavenumber, the Wien's displacement law is expressed by:\n\\begin{equation}\\label{eq:Wien_WN}\n \\dfrac{\\om_{\\rm max}}{T} = 1.961 \\; \\rm cm^{-1}.K^{-1}.\n\\end{equation}\nUsing Eq.~\\ref{eq:Wien_WL}, the maximum of emission at 500~K is located at $\\la_{\\rm max} = \\rm 5.8 \\; \\mu m$. The same calculation using Eq.~\\ref{eq:Wien_WN} gives $\\om_{\\rm max} =  980 \\; \\rm cm^{-1}$. It is crucial to note that $10000/\\la_{\\rm max} = 1725 \\; \\rm cm^{-1} \\; \\neq \\om_{\\rm max}$. Hence caution must me taken when converting spectral variable from wavenumber to wavelength and vice versa. In RadCal, the wavenumber is the variable of choice for spectral quantities.\n\n\\section{Single line emission}\nThis section briefly recalls the characteristics of a single line emission. The expression for an isolated line with pressure broadening mechanism (also called Lorentz lines) is recalled along with the expression of lines broadened by Doppler effects. Note that RadCal mixes both lines expression in the calculation of the RTE. Hence, it is important to recall some of their properties. The underlying mechanisms responsible for the emission and/or absorption of electromagnetic radiation by a molecule or atom are not recalled here as they are out of the scope of this work. It is just recalled here that the discrete nature of a species spectrum in the infrared region is a direct consequence of the discretization of the vibrational and rotational energy level admissible for a given species. The location and intensity of these lines can be obtained from the solution of the time-dependent Schr\\\"{o}dinger wave equation of a molecule with an incident radiation field. The lines location and intensity depend on the molecule geometry, mass, and its electric dipole moments. For further details, see Chapter 7 of Penner, Ref.~\\cite{Penner1959}; Herzberg Ref.~\\cite{Herzberg1949}; Chapter 11 of Modest, Ref.~\\cite{Modest2013}; and Tien monograph Ref.~\\cite{Tien1968}.\n\n\\subsection{Lorentz lines}\nA spectral line is never truly monochromatic as different line broadening mechanisms are present. The most fundamental one is the natural line broadening which is a consequence of the Heisenberg's uncertainty principle. While this effects is always present, it is usually omitted in engineering applications as the collision broadening and the Doppler broadening mechanisms are much more important.\n\nThe collision broadening mechanism originates from disruptions during the emission or absorption of energy due to the collision between molecules. The broadening of the line increases as the collision frequency increases, hence as the local pressure is increased. The shape of such broadened lines can be calculated using the electron theory of Lorentz or from quantum mechanism. The shape of the line is given by:\n\\begin{equation}\\label{eq:lorentz_line}\n \\kappa_{\\om} = \\dfrac{S}{\\pi}\\dfrac{\\gamma_c}{\\left( \\om - \\om_o\\right)^2 + \\gamma_c^2},\n\\end{equation}\nwhere $\\gamma_c$ is the collision broadening half-width at half the maximum (HWHM), $\\omega_0$ is the wavenumber at the line center, and $S$ is called the line intensity or line strength and is defined as:\n\\begin{equation}\n S = \\displaystyle\\int{\\kappa_{\\om} \\d \\om}.\n\\end{equation}\nNote that $S$ is a function of the temperature alone while $\\gamma_c$ is a function of the temperature, pressure, and mixture composition. Because the effects of collision depend on the molecular diameters of the colliding species, the quantity $\\gamma_c$ varies with the collisional partner. Among the collision broadening, distinction is made between the foreign gas broadening, \\textit{i.e.} due to collisions among dissimilar species, and self-broadening, \\textit{i.e} due to collisions among like species. The self-broadening collisions can be further differentiated between resonant and non-resonant collisions. Resonant collisions are more effective than non-resonant collisions but they have a different temperature dependence than non-resonant collisions. Non-resonant collisions are similar to collisions with a foreign gas. In RadCal, when not tabulated, the Lorentz HWHM $\\gamma_{c,i}$ of a given species $i$ belonging to a mixture, is calculated according to:\n\\begin{equation}\\label{eq:gamma_L}\n \\gamma_{c,i} = \\displaystyle\\sum_{j} \\gamma_{c0,(i,j)} \\left(\\dfrac{P_j}{P_0}\\right)\\displaystyle\\sqrt{\\dfrac{T_0}{T}} + \\gamma^*_{c0,i}\\dfrac{P_i}{P_0}\\left(\\dfrac{T_0}{T}\\right),\n\\end{equation}\nwhere $\\gamma_{c0,(i,j)}$ denotes the value of non-resonant collision broadening HWHM with species $j$ at conditions of standard pressure (denoted $P_0$) and temperature (denoted $T_0$), and $\\gamma^*_{c0,i}$ demotes the value of resonant self-collision broadening HWHM at conditions of standard pressure and temperature. Note that Eq.~\\ref{eq:gamma_L} first right-hand side term includes the effects of foreign gas collision and non-resonant self-collision.\n\nProfile of a normalized Lorentz line ($\\kappa_{\\omega} (\\pi \\gamma_c)/S$ as a function of $(\\omega-\\omega_0)/\\gamma_c $) is plotted in Fig.~\\ref{fig:Lorentz_line} together with the profile of a normalized Doppler line.\n\n\\begin{figure}\n\\begin{center}\n \\includegraphics[width=4.0in]{Figures/Lorentz_Doppler.png}\n\\end{center}\n \\caption{Profiles of a normalized Lorentz line (in red) and a normalized Doppler line (in blue). \\label{fig:Lorentz_line}}\n\\end{figure}\n\n\\subsection{Doppler lines}\nThe motion of radiating particles in the line of sight may change the apparent frequency due to the Doppler effect. The apparent frequency increases when the particle moves toward the observer and decreases when it moves away. The Doppler line profile is calculated considering the Maxwell velocity distribution (which is a consequence of the local thermodynamic equilibrium assumption). The absorption coefficient is then expressed as:\n\\begin{equation}\n\\kappa_{\\omega} = S \\dfrac{\\displaystyle\\sqrt{\\rm ln(2) }}{ \\gamma_D \\displaystyle\\sqrt{\\pi} } \\exp{\\left[- \\rm ln(2) \\left( \\dfrac{\\omega-\\omega_0}{\\gamma_D} \\right)^2 \\right]},\n\\end{equation}\nwhere $S$ and $\\omega_0$ are the line strength and the wavenumber at the line center, respectively. The quantity $\\gamma_D$ is the Doppler HWHM. It is calculated from:\n\\begin{equation}\\label{eq::DopplerHWHM}\n  \\gamma_D = \\displaystyle\\frac{\\omega_0}{c} \\displaystyle\\sqrt{\\rm{ ln(2)} \\displaystyle\\frac{2 k_B T}{m} },\n\\end{equation}\nwhere $m$ is the mass of the radiating species. Note that the Doppler HWHM depends linearly on the wavenumber; it increases with elevated wavenumber.\nThe Doppler broadening mechanism is important at high temperature ($T > 2000\\;K$) \\cite{Modest2013} and/or low pressure, typically lower than 0.01 atm.\nIn RadCal both broadening mechanisms are included in the calculation of the RTE; see Section~\\ref{sec:RTE_NB}.\n\n\\subsection{Emission from an isolated line}\nThis subsection recalls the results of the emission and absorption of radiation for an isolated Lorentz line. This ideal case helps to bring an understanding of a single line absorption variation with the pressure path length as it is a very fundamental concept.\n\nThe spectral variation of the absorption coefficient $\\kappa_{\\om}$ of a single line centered in $\\om_0$, of line strength $S$, and of HWHM $\\gamma_c$ with the wavenumber $\\om$ is recalled:\n\\begin{equation}\n \\kappa_{\\om} = \\dfrac{S}{\\pi}\\dfrac{\\gamma_c}{\\left( \\om - \\om_o\\right)^2 + \\gamma_c^2}. \\tag{\\ref{eq:lorentz_line}}\n\\end{equation}\nThe shape of the line is plotted in Fig.~\\ref{fig:Lorentz_line}.\n\nAssuming a path going through an isothermal gas, of temperature $T_g$, and homogeneous layer of participating species of partial pressure $P_i$, and of physical thickness $L$, the RTE, Eq.~\\ref{eq:RTE_Final}, can be simplified as:\n\\begin{equation}\n I_{\\om}(L) =  I_{\\om}(0) \\exp\\left( -\\kappa_{\\om} P_i L\\right) + I_{\\rm b,\\om}\\left(T_g\\right) \\left(1-\\exp\\left(-\\kappa_{\\om} P_i L\\right)\\right).\n\\end{equation}\nNote that in this equation, the local amount of participating species is expressed by the partial pressure $P_i$; hence in the equation above, $\\kappa_{\\om}$ has the dimension of an inverse pressure times an inverse length. In RadCal, $\\kappa_{\\om}$ is expressed in $\\rm (cm^{-1} \\cdot atm^{-1})$, while $P_i$ is in $\\rm atm$ and the path physical length $L$ is in $\\rm cm$. The product $P_i\\;L$, the pressure path length, is referred to in RadCal as a species optical thickness and is also denoted $U$, and the product $\\kappa_{\\om}\\;P_i\\;L$ is referred to as the optical depth.\n\nConsidering only the emission term (\\textit{i.e.} $I_{\\om}(0)$ = 0), the exiting intensity integrated over the whole spectrum, emitted by a single line, denoted $I(L)$, is expressed as:\n\\begin{equation}\nI(L) =  I_{\\rm b,\\om}\\left(T_g\\right) \\displaystyle\\int_{\\Delta \\om}\\left( 1-\\exp\\left(-\\kappa_{\\om'} P_i L\\right)\\d \\om'\\right),\n\\end{equation}\nthis assumes that $I_{\\rm b,\\om}$ does not vary much over the $\\Delta \\om$ range. The integrand is often called the equivalent line width \\cite{Modest2013} and is usually denoted $W$,\n\\be\nW = \\displaystyle\\int_{\\Delta \\om}\\left( 1-\\exp\\left(-\\kappa_{\\om'} P_i L\\right)\\d \\om'\\right).\n\\ee\n\nThe analytical expression of $W$ for a Lorentz line can be derived, see for example Penner, \\cite{Penner1959}:\n\\be\nW(P_i L) = 2 \\pi \\gamma_c L(x) = 2  \\pi \\gamma_c x \\;\\exp\\left( -x\\right) \\left(I_0(x) + I_1(x)\\right), \\; x = \\dfrac{SP_iL}{2 \\pi \\;\\gamma_c}.\n\\ee\nThe function $L(x)$ is named the Ladenburg-Reiche function, and $I_0$ and $I_1$ are the modified Bessel functions of the first kind. The graph of the Ladenburg-Reiche function is\ngiven in Fig.~\\ref{fig:Ladenburg}. Note that for small and large values of $x$, the equivalent line has the following asymptotic forms:\n\\begin{align}\nW(x) \\sim SP_iL ,\\: {\\rm for}\\: x \\ll 1 \\\\\nW(x) \\sim 2\\sqrt{S\\gamma_c P_iL} ,\\: {\\rm for}\\: x \\gg 1.\n\\end{align}\n\n\\begin{figure}\n\\begin{center}\n \\includegraphics[width=4.0in]{Figures/Ladenburg.png}\n\\end{center}\n \\caption{Profile the Ladenburg-Reiche function. \\label{fig:Ladenburg}}\n\\end{figure}\n\nIt is worth noting that the parameter $x$ gives an indication of the optical thickness of the gas layer for a single line. When $x$ is small, this indicates that the medium is weakly participating (either $S$ or the product $P_iL$ is small) and the absorption and emission of a single line is linear with the product $P_iL$. On the contrary, when $x$ is much greater than unity, the absorption or emission of a single line is not linear anymore but has a square-root dependency.\n\n\\section{Narrow band models}\\label{Sec::SNBM}\nThis section briefly describes the different models used to obtain most of the tabulated species IR spectral mean absorption coefficients at different temperatures, $\\bar{\\kappa}_i(\\om,T)$. Narrow band models are used in lieu of line-by-line models to represent the IR spectra of radiating species in engineering applications. In the narrow-band approach, the whole spectrum is divided into small spectral bands (typically several $\\rm cm^{-1}$), and different statistical approaches are used to compute the average radiative properties over these narrow-bands. What is of interest is to give functional expression of the integrand:\n\\be\n\\bar{\\tau}_{\\om} = \\displaystyle\\int_{\\Delta \\om}\\left( \\exp\\left(-\\kappa_{\\om'} P_i L\\right)\\d \\om'\\right),\n\\ee\nwhen $\\Delta \\om$ is large enough so it includes hundreds, even thousands, of single lines, but small enough to assume $I_{\\rm b,\\om}\\left(T_g\\right)$ and the incident spectral intensity $I_{\\om}(0)$ constant over it. It is important to state that generally:\n\\be\n\\bar{\\tau}_{\\om} \\neq \\displaystyle\\int_{\\Delta \\om}\\left( \\exp\\left(-\\bar{\\kappa}_{\\om'} P_i L\\right)\\d \\om'\\right).\n\\ee\nEquality is verified only is some specific situations (\\textit{e.g.} $P_iL \\ll 1$). An important assumption to recall is that it is assumed that the Kirchoff law, \\textit{i.e.} $\\bar{\\alpha} = \\bar{\\epsilon}$, holds over a narrow-band.\n\nThree main narrow-band models are presented below: the Elsasser model, the Goody model, and the Malkmus model. All assume Lorentz lines.\n\n\\subsection{Elsasser model}\n\nThe Elsasser model assumes all the lines to have the same HWHM $\\gamma_c$, the same line strength $S$, and to be equally spaced every $d$ wavenumber from each other.\nAs a consequence, the absorption coefficient can be expressed by the infinite sequence:\n\\be\\label{eq:kappa_El}\n\\kappa_{\\om} = \\displaystyle\\sum_{n = -\\infty}^{\\infty}{\\dfrac{S}{\\pi}\\dfrac{\\gamma_c}{\\left(\\om - \\left(\\om_0+n\\,d\\right)\\right)^2 + \\gamma_c^2}}.\n\\ee\nThis function is periodic, with a period $d$. Following Elsasser derivation (see Ref.~\\cite{Penner1959}), Eq.~\\ref{eq:kappa_El} can be expressed as:\n\\be\\label{eq:Elsasser_periodic}\n\\kappa_{\\om}  = \\dfrac{S}{d} \\dfrac{\\rm sinh (8\\beta)}{{\\rm cosh (8\\beta)} - \\cos(\\frac{2\\pi}{d}(\\om-\\om_0))},\n\\ee\nwhere the overlap parameter $\\beta$, which is also called the (Lorentz) fine structure parameter and denoted $a_c$ in Ref.~\\cite{Ludwig1973} and in the code, is defined here as:\n\\be\\label{eq::beta}\n\\beta = \\dfrac{\\pi}{4}\\dfrac{\\gamma_c}{d}.\n\\ee\nThe mean absorption coefficient $\\bar{\\kappa}$ over the narrow-band centered in $\\om$ is:\n\\be\\label{eq:kappa_def}\n\\bar{\\kappa}_{\\om} = \\dfrac{S}{d}.\n\\ee\nFigure~\\ref{fig:Elsasser_profile} plots the variations of the Elsasser absorption coefficient $\\kappa_{\\om}$ normalized by $\\bar{\\kappa}$ as a function of the ratio $\\om/d$ for two different values of the overlap parameter $\\beta$. Strong overlap effects are seen for the largest value of $\\beta$.\n\n\\begin{figure}\n\\begin{center}\n \\includegraphics[width=4.0in]{Figures/Elsasser_profile.png}\n\\end{center}\n \\caption{Variations of the Elsasser absorption coefficient normalized by $\\bar{\\kappa}$ plotted as a function of the ratio $\\om/d$ for two different values of the overlap parameter $\\beta = 0.05$ (in green) and $\\beta = 0.5$ (in red). \\label{fig:Elsasser_profile}}\n\\end{figure}\nThe mean transmissivity $\\bar{\\tau}_{\\om}$ of the narrow-band centered in $\\om$ can be calculated using Eq.~\\ref{eq:Elsasser_periodic}, averaging over one period $d$:\n\\be\n\\bar{\\tau}_{\\om} = \\frac{1}{d}\\displaystyle\\int_{-\\frac{d}{2}}^{\\frac{d}{2}}{\\exp\\left(-\\bar{\\kappa}_{\\om} P_i L\\dfrac{\\rm sinh (8\\beta)}{{\\rm cosh (8\\beta)} - \\cos\\left(\\frac{2\\pi}{d}(\\om'-\\om)\\right)} \\right)\\d\\om'}.\n\\ee\nThis expression can be assessed using the Godson and Tien approximations \\cite{Brosmer1985b,Kunitomo1975}:\n\\be\\label{eq::Elsasser}\n    \\bar{\\tau}_{\\om} = 1- \\erf \\left( \\dfrac{\\sqrt{\\pi}}{2} \\, \\frac{\\bar{\\kappa}_{\\om} \\, U }{\\displaystyle \\sqrt{1 + \\frac{\\pi \\, \\bar{\\kappa}_{\\om} \\, U}{16 \\, \\beta}}}  \\right),\n\\ee\nwhere $U = P_iL$ is the optical thickness. Equation~\\ref{eq::Elsasser} is used in RadCal to compute $\\bar{\\tau}_{\\om}$ when using the Elsasser narrow-band model, which is only used for Methane. Note that the Godson and Tien approximation is reasonably accurate for values of the overlap parameter lower or of the order of unity, \\textit{i.e.} $\\beta < 1$.\nFigure~\\ref{fig::Elsasser_curve_growth} plots the quantity $-\\ln(\\bar{\\tau}_{\\om})$ (this quantity is also referred to as the curved of growth) versus the product $\\bar{\\kappa}_{\\om} U$ for two different values of the overlap parameter: $\\beta = 0.05$ (in green) and $\\beta = 0.5$ (in red). The back dashed curve corresponds to the ``linear'' behavior, \\textit{i.e.} $\\bar{\\tau}_{\\om} = \\exp\\left(\\bar{\\kappa} U\\right)$. It is noteworthy that this linear behavior corresponds to either ``weak lines regimes'' (situations with small product $\\bar{\\kappa} U$) or to situations with a strong overlap, $\\beta > 1$). Outside of these regimes, assuming linear behavior might lead to overestimation of the curve of growth. Figure~\\ref{fig::Elsasser_curve_growth} also illustrates a case where the Godson and Tien approximation looses its accuracy and leads to unphysical results, as seen for the case $\\beta=0.5$, which overestimates the absorption.\n\nIt can be seen from Eq.~\\ref{eq::Elsasser} that $\\bar{\\tau}_{\\om}$ is fully characterized once the narrow-band parameters $\\bar{\\kappa}_{\\om}$ and $\\beta$ are known. Note that these two parameters are by construction independent of the physical length of radiation propagation but depend on the local temperature, pressure, and local mixture composition.\n\n\\begin{figure}\n\\begin{center}\n \\includegraphics[width=4.0in]{Figures/Elsasser_curve_of_growth.png}\n\\end{center}\n \\caption{Elsasser model curve of growth ($\\ln \\bar{\\tau}$) as a function of the product $\\bar{\\kappa}_{\\om} U$. Two different values of the overlap parameter are plotted: $\\beta = 0.05$ (in green) and $\\beta = 0.5$ (in red). The curve of growth for the ``weak line regime'' is plotted in the bash dashed curve.\\label{fig::Elsasser_curve_growth}}\n\\end{figure}\n\n\\subsection{Generalities on statistical narrow-band models}\nThe Goody and Malkmus models have been developed to provide a better modeling of the narrow-band spectral properties than that predicted by the Elsasser model, which is based on strong assumptions: uniformity of the line strength and of line spacing. While the Elsasser model works fine for some light, diatomic  species (\\textit{i.e} HCl), most of the more complex polyatomic species cannot be modeled appropriately with the Elsasser model, since the very detailed experimental characterization of their spectral lines does not exhibit regularity \\cite{Modest2013}.\n\nThe Goody and Malkmus models are statistical narrow-band models, the former preceding the latter by a couple of decades and was first developed by Mayer and Goody \\cite{Penner1959}. Statistical narrow-band models are based on two main assumptions: first, there is no correlation between lines position and line intensities, and the location of the line can be modeled by any random arrangement~\\cite{Penner1959,Young1977d}; second, while all the lines have the same shape, their line strength within the narrow-band of spectral range $\\Delta \\nu$ is a random variable assigned to a continuous probability density function $P(\\bar{S},S)$, with $\\bar{S}$ the mean value of the line strength, \\textit{i.e.} $\\bar{S} = \\displaystyle\\int_{0}^{+\\infty}{S P(\\bar{S},S)\\d S}$.\n\nA consequence of these assumptions for a very large number of lines contained within the narrow-band is that the transmissivity of a narrow-band $\\bar{\\tau}_{\\om}$, and of optical thickness $U$, is expressed by:\n\\be\\label{eq:SNB_tau_equiline}\n\\bar{\\tau}_{\\om}(U) = \\exp\\left(-\\displaystyle\\frac{\\bar{W}(U)}{d}\\right),\n\\ee\nwhere $d$ is the average line spacing and $\\bar{W}(U)$ is the average equivalent line width of the narrow-band considered and is calculated as:\n\\begin{align}\\label{eq::SNB_Equiline}\n\\bar{W}(U) &= \\displaystyle\\int_{0}^{+\\infty}{P(\\bar{S},S)W(S,U) \\d S} \\nonumber \\\\\n           &= \\displaystyle\\int_{0}^{+\\infty}{P(\\bar{S},S)\\displaystyle\\int_{-\\infty}^{+\\infty}{1 - \\exp\\left(-\\kappa_{\\om} P_i L\\right) \\d\\om} \\d S}\n\\end{align}\nwhere $\\kappa_{\\om}$ is the absorption coefficient of a Lorentz line, given by Eq.~\\ref{eq:lorentz_line}. An example of the derivation of Eq.~\\ref{eq::SNB_Equiline} is presented in Penner's book~\\cite{Penner1959}. By their different choice of the probability density function $P(\\bar{S},S)$, the Goody and Malkmus models provide an explicit and simple evaluation of the average equivalent line width of a narrow-band, $\\dfrac{\\bar{W}}{d}$.\n\n\\subsection{Goody model}\\label{sec:goody_model}\n\nThe Goody model assumes an exponential distribution of the line strength:\n\\begin{align}\n P(\\bar{S},S) &= \\dfrac{1}{\\bar{S}}\\exp\\left(-\\dfrac{S}{\\bar{S}} \\right) \\\\\n              &= \\dfrac{4}{\\pi S_E}\\exp\\left(-\\dfrac{4S}{\\pi S_E} \\right),\n\\end{align}\nwhere $S_E$ is an effective equivalent line strength which relates to the average line strength $\\bar{S}$ with \\cite{Malkmus1967,Ludwig1973}:\n\\be\\label{eq::S_E_barS}\n\\bar{S} = \\dfrac{\\pi}{4} S_E.\n\\ee\nSolving Eq.~\\ref{eq:SNB_tau_equiline} and introducing the effective average lines spacing $d_E = \\dfrac{4}{\\pi}d$, Ref.~\\cite{Malkmus1967}, it comes:\n\\begin{align}\\label{eq::Goody}\n    \\bar{\\tau}_{\\om} = \\exp\\left(-\\dfrac{S_E}{d_E} \\dfrac{U}{\\displaystyle \\sqrt{1+\\frac{S_E U}{4 \\, \\gamma_c }}}\\right) \\nonumber \\\\\n    \\bar{\\tau}_{\\om} = \\exp\\left(-\\frac{\\bar{\\kappa}_{\\om} \\, U} {\\displaystyle \\sqrt{1+\\frac{\\bar{\\kappa}_{\\om} \\, U}{4 \\, \\beta}}}\\right)\n\\end{align}\nwhere the band overlap parameter $\\beta$ is here defined as:\n\\be\n\\beta = \\dfrac{\\gamma}{d_E} = \\dfrac{\\pi}{4}\\dfrac{\\gamma}{d}.\n\\ee\nIt is important to remark that the band overlap parameter $\\beta$, while constant over a narrow-band, varies with the wavenumber. In addition, it has a strong dependence on the total pressure. This dependence varies from species to species. The mean absorption coefficient $\\bar{\\kappa}$ in Eq.~\\ref{eq::Goody} keeps the same definition as given in Eq.~\\ref{eq:kappa_def}. It is noteworthy to realize that:\n\\be\n\\bar{\\kappa} = \\dfrac{S}{d} = \\dfrac{S_E}{d_E},\n\\ee\nfrom the definition of $d_E$ and $S_E$. The effective parameter has been introduced to be consistent with the definition from Ludwig \\textit{et al.}, Ref.~\\cite{Ludwig1973}, from which most of RadCal is formulated after.\n\nFigure~\\ref{fig::Goody_curve_growth} plots the curve of growth, $-\\ln(\\bar{\\tau}_{\\om})$, versus the product $\\bar{\\kappa}_{\\om} U$ for two different values of the overlap parameter: $\\beta = 0.05$ (in green) and $\\beta = 0.5$ (in red) using the Goody model. The back dashed curve corresponds to the ``linear'' behavior, \\textit{i.e.} $\\bar{\\tau}_{\\om} = \\exp\\left(\\bar{\\kappa} U\\right)$.\n\nAgain, it can be seen from Eq.~\\ref{eq::Goody} that $\\bar{\\tau}_{\\om}$ is fully characterized once the narrow-band parameters $\\bar{\\kappa}_{\\om}$ and $\\beta$ are known.\n\n\\begin{figure}\n\\begin{center}\n \\includegraphics[width=4.0in]{Figures/Goody_curve_of_growth.png}\n\\end{center}\n \\caption{Goody model curve of growth ($\\ln \\bar{\\tau}$) as a function of the product $\\bar{\\kappa}_{\\om}\\;U$. Two different values of the overlap parameter are plotted: $\\beta = 0.05$ (in green) and $\\beta = 0.5$ (in red). The curve of growth for the ``weak line regime'' is also plotted (dashed curve).\\label{fig::Goody_curve_growth}}\n\\end{figure}\n\n\\subsection{Malkmus model}\\label{sec:malkmus_model}\n\nLike the Goody model, the Malkmus model assumes the line strength of all the lines in a given narrow-band model follows a particular distribution. This model was developed because the exponential distribution assumed in the Goody model substantially underestimates the number of low-intensity lines. The Malkmus model is based on a more physical approach that assumes that the line strength distribution $P(S)$ varies proportionally to $S^{-1}$. This assumption is based on physical arguments and is empirically verified for some molecules, see Malkmus~\\cite{Malkmus1967} for more details.\n\nThe problem of non-normalization of the $S^{-1}$ distribution is circumvented by cutting-off the $S^{-1}$ distribution below some very small and above some very large values of $S$. A continuous distribution can then be constructed based on some assumptions relating the energy of a transition with the line strength and assuming that the ratio between the maximum and the minimum line strengths considered is very large. The line strength probability distribution used in the Malkmus model is expressed by an exponential-tailed $S^{-1}$ distribution \\cite{Malkmus1967,Young1977d}:\n\\begin{equation}\n P(S_E,S) = \\dfrac{1}{S}\\exp\\left(-\\dfrac{4}{\\pi}\\dfrac{S}{S_E} \\right),\n\\end{equation}\nwhere the effective line strength $S_E$ relates to the average line strength $\\bar{S}$ through Eq.~\\ref{eq::S_E_barS}. Solving Eq.~\\ref{eq:SNB_tau_equiline}, and using the same definition for the effective average lines spacing $d_E$ as given in the above section, it comes:\n\\begin{align}\\label{eq::Malkmus}\n    \\bar{\\tau}_{\\om} = \\exp\\left( -2 \\dfrac{\\gamma_c}{d_E} {\\displaystyle \\sqrt{1+\\frac{S_E U}{\\gamma_c }} -1 }\\right) \\nonumber \\\\\n    \\bar{\\tau}_{\\om} =  \\exp\\left(-2  \\beta \\left[\\sqrt{1+\\dfrac{\\bar{\\kappa}_{\\omega}U}{\\beta} }- 1\\right] \\right)\n\\end{align}\nwhere the band overlap parameter $\\beta$ is here again defined as:\n\\be\n\\beta = \\dfrac{\\gamma}{d_E} = \\dfrac{\\pi}{4}\\dfrac{\\gamma}{d}.\n\\ee\n\nThe Malkmus band model is recognized as the most suitable statistical narrow-band model for polyatomic gases \\cite{Modest2013}. In this new version of RadCal, this model has been introduced to model the newly implemented fuel species. Note that the Malkmus and Goody models do not differ when considering the extreme cases of optically thin and optically thick medium. In such cases, both models asymptote to:\n\\begin{align}\n\\lim_{U \\to 0} \\dfrac{\\bar{W}}{d}/U &= \\bar{\\kappa} \\\\\n\\lim_{U \\to +\\infty} \\dfrac{\\bar{W}}{d}/\\sqrt{U} &= 2\\displaystyle\\sqrt{\\bar{\\kappa}\\beta}\n\\end{align}\n\nFigure~\\ref{fig::Malkmus_curve_growth} plots the curve of growth, $-\\ln(\\bar{\\tau}_{\\om})$, versus the product $\\bar{\\kappa}_{\\om} U$ for two different values of the overlap parameter: $\\beta = 0.05$ (in green) and $\\beta = 0.5$ (in red) using the Malkmus model. The back dashed curve corresponds to the ``linear'' behavior, \\textit{i.e.} $\\bar{\\tau}_{\\om} = \\exp\\left(-\\bar{\\kappa} U\\right)$.\n\nAgain, it can be seen from Eq.~\\ref{eq::Malkmus} that $\\bar{\\tau}_{\\om}$ is fully characterized once the narrow-band parameters $\\bar{\\kappa}_{\\om}$ and $\\beta$ are known. These two narrow-band spectral quantities can be obtained either from line-by-line calculations, by fitting experimental data, or by physical considerations.\n\n\\begin{figure}\n\\begin{center}\n \\includegraphics[width=4.0in]{Figures/Malkmus_curve_of_growth.png}\n\\end{center}\n \\caption{Malkmus model curve of growth ($-\\ln \\bar{\\tau}$) as a function of the product $\\bar{\\kappa}_{\\om} U$. Two different values of the overlap parameter are plotted: $\\beta = 0.05$ (in green) and $\\beta = 0.5$ (in red). The curve of growth for the ``weak line regime'' is also plotted (dashed curve).\\label{fig::Malkmus_curve_growth}}\n\\end{figure}\n\n\\textbf{Note}: For all the tabulated data, a linear interpolation of $\\bar{\\kappa}_{\\om}$ and $\\beta_{\\om}$ in temperature and/or in wavenumber is performed by RadCal when necessary. If the temperature sought is out of the tabulated data range, then the data at the nearest temperature are used.\n\n\\section{Treatment of the RTE in the scope of narrow-band model}\\label{sec:RTE_NB}\nThis section presents the expression of the different calculations performed by RadCal to numerically solve the Radiative Transfer Equation for a narrow-band. The Radiative Transfer Equation for a narrow-band is recalled below using wavenumbers:\n\\be\\label{eq::RTE_Wavenumber}\n\\underbrace{I_{\\om_0}(s)}_{\\rm Received\\:intensity\\:in\\:s}  = \\underbrace{{I_{\\rm b,\\om_o}(T_w) \\bar{\\tau}(\\om_0; 0 \\rightarrow s)}}_{\\rm transmitted\\:incident\\:intensity} + \\underbrace{{\\displaystyle\\int_0^{s}{I_{\\rm b,\\om_0}\\left(T(s')\\right)\\dfrac{\\partial \\bar{\\tau}  }{\\partial s'}(\\om_0; s' \\rightarrow s) \\d s'}}}_{\\rm intensity\\:emitted\\:by\\:the\\:medium\\:between\\:0\\:and\\:s}.\n\\ee\nwhere $\\Delta \\om$ is the narrow-band centered in $\\om_0$, $I_{\\om_0}(s)$ is the received flux at the location $s$, $I_{b,\\om_o}(T_w)$ is the incident flux penetrating the participating medium and which is modeled in RadCal as a flux from a blackbody of temperature $T_w$ ($T_w$ is an user input). The second term of the equation right-hand side accounts for the medium radiative emission and self-absorption.\n\n\\subsection{Treatment of Homogeneous pressure-path}\n\\label{sec::homogeneous_path}\nIf the participating medium is homogeneous -- \\textit{i.e.} of constant composition, temperature $T$, and total pressure $P_T$ -- Eq.~\\ref{eq::RTE_Wavenumber} can be simplified as:\n\\be\\label{eq::RTE_wavenumber_H}\nI_{\\om_0}(s) = I_{\\rm b,\\om_o}(T_w) \\bar{\\tau}(\\om_0; 0 \\rightarrow s) + I_{\\rm b,\\om_o}(T)(1-\\bar{\\tau}(\\om_0; 0 \\rightarrow s)).\n\\ee\nRadCal computes the value of $\\bar{\\tau}(\\om_0; 0 \\rightarrow s)$ combining Lorentz and Doppler lines. While usually for cases at atmospheric pressure and at moderate temperature the Doppler lines are not important, they are however included for the sake of completeness. The different steps of the calculation of $\\bar{\\tau}(\\om_0; 0 \\rightarrow s)$ are presented below.\n\nFor each participating species present in the medium, RadCal first retrieve the band mean absorption coefficient $\\bar{\\kappa}_{\\om}$, the band overlap parameter $\\beta$ (for Lorentz lines), and the Doppler fine structure parameter, denoted $a_D$, which is defined as the ratio of the Doppler HWHM $\\gamma_D$, given by Eq.~\\ref{eq::DopplerHWHM}, over the mean line spacing $d$.\n\nThen RadCal computes the optical depth from Lorentz lines, denoted $X_C$, using Eqs.~\\ref{eq::Elsasser}, \\ref{eq::Goody}, and \\ref{eq::Malkmus}, depending on the species appropriate model, using  $\\bar{\\kappa}_{\\om}$ and $\\beta$. Note that:\n\\be\\label{eq::Collision_optical_depth}\nX_C = \\dfrac{\\bar{W}}{d}\n\\ee\n\nRadCal computes the optical depth from Doppler lines, denoted $X_D$. The expression of $X_D$ depends of the model chosen to compute $X_C$. If the Elsasser or Goody model is used to compute $X_C$, then the optical depth from Doppler lines is calculated by \\cite{Ludwig1973}:\n\\be\\label{eq::Doppler_optical_path_Goody}\nX_D = \\sqrt{\\dfrac{2}{\\ln 2}} a_D \\sqrt{\\ln \\left(1+\\dfrac{\\ln 2}{2} \\left(\\dfrac{\\bar{\\kappa}_{\\om_0}U}{a_D}\\right)^2\\right)},\n\\ee\nwhere $U$ is the optical thickness defined by $U = P_i\\,s$, with $P_i$ the partial pressure (in atm) of the participating species considered and $s$ is the distance given in cm.\nIf the Malkmus model is used to compute $X_C$, then the optical depth from Doppler lines is calculated by \\cite{Ludwig1973}:\n\\be\\label{eq::Doppler_optical_path_Malkmus}\nX_D = \\sqrt{\\dfrac{3}{2 \\ln 2}} a_D \\left[ \\ln\\left(1 + \\left(\\sqrt{\\dfrac{2 \\ln 2}{3}} \\dfrac{\\bar{\\kappa}_{\\om_0}U}{a_D} \\right)^{2/3} \\right)\\right]^{3/2}.\n\\ee\nThe combined optical depth, $Y$, is then calculated:\n\\be\\label{eq::combined_optical_path}\nY  = \\left(1 - \\left(\\dfrac{X_C}{\\bar{\\kappa}_{\\om_0}U}\\right)^2 \\right)^{-2} + \\left(1 - \\left(\\dfrac{X_D}{\\bar{\\kappa}_{\\om_0}U}\\right)^2 \\right)^{-2} - 1.\n\\ee\nFinally, the narrow-band transmissivity, $\\bar{\\tau}(\\om_0; 0 \\rightarrow s)$, is obtained by:\n\\be\\label{eq::trans_HPP_final}\n\\bar{\\tau}(\\om_0; 0 \\rightarrow s) = \\exp\\left(-\\bar{\\kappa}_{\\om_0}U \\sqrt{1 - \\dfrac{1}{\\sqrt{Y}}}\\right).\n\\ee\nIf there are more than one participating species, then $\\bar{\\tau}(\\om_0; 0 \\rightarrow s)$ is calculated from:\n\\be\\label{eq::trans_HPP_final_multispecies}\n\\bar{\\tau}(\\om_0; 0 \\rightarrow s) = \\exp\\left(-\\displaystyle\\sum_i{\\bar{\\kappa}_{i,\\om_0}U \\sqrt{1 - \\dfrac{1}{\\sqrt{Y_{i}}}}}\\right),\n\\ee\nthe optical depth for each species $i$ is first calculated separately, and then summed altogether.\n\n\\subsection{Treatment of non-Homogeneous pressure-path - Curtis-Godson approximation}\n\\label{sec::Curtis_Godson}\nThe treatment of the RTE in the case of non-homogeneous medium (where gradients of species, temperature, or pressure are present) is explicitly detailed below. The non-homogeneous case is first treated by discretizing the depth of penetration of the incident beam of direction $\\hat{\\textbf{s}}$ into a set of $n$ smaller segments $\\{[s_{i-1};s_i]\\}_n$ over which the local composition, temperature, and pressure can reasonably be assumed constant. Hence, the expression of the RTE over a narrow-band $\\Delta \\om$, centered in $\\om_0$ and given by Eq.~\\ref{eq::RTE_Wavenumber} can be simplified as:\n\\begin{equation}\\label{eq::RTE_wavenumber_NH}\nI_{\\om_0}(s) = I_{\\rm b,\\om_o}(T_w) \\bar{\\tau}(\\om_0; 0 \\rightarrow s) + \\displaystyle\\sum_{i=1}^n{I_{\\rm b,\\om_o}(T_i)\\left(\\bar{\\tau}(\\om_0; s_i \\rightarrow s)-\\bar{\\tau}(\\om_0; s_{i-1} \\rightarrow s)\\right)}.\n\\end{equation}\nIn the expression, it assumed that $s_0 = 0$, which is coincided with the location of the blackbody wall of temperature $T_w$, and $s_n = s$. The temperature $T_i$ is the temperature of the small segment $\\{[s_{i-1};s_i]\\}_n$. The difficulty in solving Eq.~\\ref{eq::RTE_Wavenumber} lies in evaluating  $\\bar{\\tau}(\\om_0; s_i \\rightarrow s)$ as it is correlated with the cells crossed by the beam $\\widehat{\\textbf{sis}}$.\n\nTo circumvent this difficulty, the Curtis-Godson approach is used. In this approach, it is assumed that\neach $\\bar{\\tau}(\\om_0; s_i \\rightarrow s)$ for a given species can still be calculated using Eqs.~\\ref{eq::Doppler_optical_path_Goody}, \\ref{eq::Doppler_optical_path_Malkmus}, \\ref{eq::combined_optical_path}, \\ref{eq::trans_HPP_final}, and the models presented in Section~\\ref{Sec::SNBM} but their parameters $\\bar{\\kappa}$, $\\beta$, and $a_D$ are replaced by some effective parameters, $\\bar{\\kappa}^*$, $\\beta^*$, $a_{D}^*$, respectively. See Young \\cite{Young1977d} and Ludwig \\textit{et al.} \\cite{Ludwig1973} for additional details on the Curtis-Godson approach. It was found that using path-averaged parameters as effective parameters work best \\cite{Young1977d} to calculate the transmissivity of non-homogeneous medium. These parameters are defined as:\n\\begin{align}\n\\bar{\\kappa}^* &= \\dfrac{\\displaystyle\\int_{s_i}^{s} \\bar{\\kappa}(s')P_i(s')\\d s'}{\\displaystyle\\int_{s_i}^{s} P_i(s')\\d s'}, \\label{eq::effective_kappa} \\\\\n\\beta^* &= \\dfrac{\\displaystyle\\int_{s_i}^{s} \\beta(s')\\bar{\\kappa}(s')P_i(s')\\d s'}{\\displaystyle\\int_{s_i}^{s} \\bar{\\kappa}(s')P_i(s')\\d s'}, \\label{eq::effective_beta}\\\\\na_D^* &= \\dfrac{\\displaystyle\\int_{s_i}^{s} a_D(s')\\bar{\\kappa}(s')P_i(s')\\d s'}{\\displaystyle\\int_{s_i}^{s}, \\bar{\\kappa}(s')P_i(s')\\d s'},\\label{eq::effective_ad}\n\\end{align}\nwith $P_i$ is the partial pressure of the participating gas considered. The quantity:\n\\be\nU = \\displaystyle\\int_{s_i}^{s}{P_i(s')\\d s'},\n\\ee\nis the optical thickness, in {\\rm atm.cm}, between the points $s_i$ and $s$.\n\n\\section{Output quantities: effective coefficients and integrated quantities}\\label{sec::Output}\nRadCal solves the RTE based on the input parameters found in the input file \\verb=RADCAL.in= and returns in a Tecplot file (\\verb=<CASE ID>.tec=, where \\verb=<CASE ID>= is an user input defined in the input file) the spectral profile of the spectral transmissivity of the medium $\\bar{\\tau}(\\om_0; 0 \\rightarrow s)$ and the incident spectral intensity $I_{\\om_0}(s)$ calculated using either Eq.~\\ref{eq::RTE_wavenumber_H} or \\ref{eq::RTE_wavenumber_NH}.\n\nIn addition to the Tecplot file, RadCal also generates an output file \\verb=RADCAL.out=, that contains several effective coefficients and integrated quantities. Some of these integrated quantities were already included in the previous version of RadCal. This is the case of the effective absorption coefficient, the Planck mean absorption coefficient, and the received total directional radiative energy flux (or received total intensity). Two new integrated quantities have been added: the total emissivity, and the total transmissivity. These effective coefficients and integrated quantities are described formally in this section. Note that the integration is performed using a Simpson rule over non regular abscissa using a 3-point Lagrangian interpolation (quadratic interpolation).\n\n\\subsection{Effective absorption coefficient}\nThe path-averaged or effective absorption coefficient, denoted here $\\kappa_{\\rm e}$ and denoted \\verb=Amean= in the output file, is defined such that the received total intensity in $s = L$ can be expressed as a sum of a transmitted total intensity coming from the blackbody wall, set at temperature $T_w$, and a total intensity emitted by the gas at the local temperature $T_g$:\n\\be\\label{eq:effective_epsilon1}\n   \\int_{\\om_{\\rm min}}^{\\om_{\\rm max}}{I_{\\om}(L) \\; \\d \\om} = \\exp\\left(-\\kappa_{\\rm e}\\, L\\right) \\int_{\\om_{\\rm min}}^{\\om_{\\rm max}}{ I_{\\rm b,\\om}(T_w) \\; \\d \\om} + \\left(1-\\exp\\left(-\\kappa_{\\rm e} \\, L\\right)\\right) \\int_{\\om_{\\rm min}}^{\\om_{\\rm max}}{I_{\\rm b,\\om}(T_g) \\; \\d \\om}\n\\ee\nwhere $L$ is the total path length given in cm. The bounds of integration in Eq.~\\ref{eq:effective_epsilon1} are fixed, with $\\om_{min} = 5$ cm$^{\\rm -1}$, and $\\om_{max} = 25000$ cm$^{\\rm -1}$. However, the bounds of the integration for the gas-phase species are specified by the user. The remain outside spectral domain is integrated then considering only the contribution of soot (if present). See Eq.~\\ref{eq::received_flux}. The large bounds of integration (5 -- 25000 cm$^{\\rm -1}$) is large enought such that:\n\\be\n\\int_{\\om_{\\rm min}}^{\\om_{\\rm max}}{I_{b,\\om}(T) \\; \\d \\om} \\approx \\dfrac{\\sigma}{\\pi}T^4.\n\\ee\n\nFormally, $\\kappa_{\\rm e}$ is calculated from:\n\\be\\label{eq:effective_epsilon}\n   \\kappa_{\\rm e} = -\\dfrac{1}{L} \\ln\\left(\\dfrac{\\displaystyle\\int_{\\om_{\\rm min}}^{\\om_{\\rm max}}{I_{\\om}(L)  - I_{\\rm b,\\om}(T_g)\\; \\d \\om}   }{\\displaystyle\\int_{\\om_{\\rm min}}^{\\om_{\\rm max}}{ I_{\\rm b,\\om}(T_w)-I_{\\rm b,\\om}(T_w) \\; \\d \\om}  } \\right).\n\\ee\nNote that $\\kappa_{\\rm e}$ has the units of cm$^{-1}$. The effective absorption coefficient is calculated for homogeneous and non-homogeneous cases. For the latter, the gas temperature $T_g$ used in Eq.~\\ref{eq:effective_epsilon} is the path-average temperature:\n\\be\\label{eq::Path_avg_temp}\nT_g = \\dfrac{\\displaystyle\\int_{0}^{L}{T(s) \\d s }}{L}.\n\\ee\nWhile the effective absorption coefficient works well for a given length $L$, one has to be careful when using it to estimate the received total intensity from a similar homogeneous isothermal medium but with a different thickness as the calculated results using Eq.~\\ref{eq:effective_epsilon} might deviate significantly from the actual results unless the medium considered is gray (no spectral variation of the absorption coefficient).\n\n\\subsection{Planck mean absorption coefficient}\nThe Planck mean coefficient, denoted here $\\kappa_{\\rm Planck}$, is calculated by:\n\\begin{equation}\\label{eq::planck_mean}\n\\kappa_{\\rm Planck} = \\dfrac{\\pi}{\\sigma {T_g}^4}\n\\displaystyle\\int_{\\om_{\\min}}^{\\om_{\\max}}{I_{\\rm b,\\om}(T_g)\n\\displaystyle\\sum_i \\bar{\\kappa}_{i,\\om} \\, P_i \\; \\d \\om}\n\\end{equation}\nwhere $P_i$ is the partial pressure of participating species $i$, in units of ${\\rm atm}$; and $\\bar{\\kappa}_{\\om}$ is the narrow-band mean absorption coefficient of participating species $i$, in units of ${\\rm atm^{-1}.cm^{-1}}$. Note that the temperature used in this expression is the local gas temperature; thus, $\\kappa_{\\rm Planck}$ is a function of the gas phase temperature and of the species partial pressure. It is independent of the path physical length. Its units are in ${\\rm cm^{-1}}$. The integration bounds, $\\om_{min}$, and $\\om_{max}$ are defined by the user in the input file.\n\nThe Planck mean absorption coefficient is calculated for homogeneous and non-homogeneous cases. For the latter, the gas temperature used to calculate $I_{\\rm b,\\om}(T_g)$ is the path-average temperature as defined by Eq.~\\ref{eq::Path_avg_temp}. The term $T_g^4$ is also calculated using a path-average value:\n\\be\nT_g^4 = \\dfrac{\\displaystyle\\int_{0}^L{ T(s)^4 \\d s}}{L},\n\\ee\nwhere $L$ is the total path length given in cm.\n\nFor non-homogeneous cases, the mean absorption coefficient used in Eq.~\\ref{eq::planck_mean}, $\\bar{\\kappa}_{i,\\om}$, corresponds to the effective mean absorption coefficient $\\bar{\\kappa}^*$ defined by Eq.~\\ref{eq::effective_kappa}. The partial pressure used is a path-average partial pressure:\n\\be\nP_i = \\dfrac{\\displaystyle\\int_{0}^L{P_i(s)\\d s}}{L}.\n\\ee\n\n\\subsection{Total transmissivity}\n\nRadcal returns the total transmissivity, denoted $\\tau_{T}$, of the spectral range bounded between the user defined $\\omega_{min}$ and $\\omega_{max}$. The total transmissivity is calculated as:\n\\begin{equation}\\label{eq::total_transmissivity}\n \\tau_{T} = \\dfrac{\\displaystyle\\int_{\\omega_{min}}^{\\omega_{max}}\\tau(0 \\rightarrow s;\\omega)I_{\\rm b,\\om}(T_w) \\d \\omega }{\\displaystyle\\int_{\\omega_{min}}^{\\omega_{max}}I_{\\rm b,\\om}(T_w)\\d \\omega }.\n\\end{equation}\nThis quantity is dimensionless. It represents the fraction of transmitted incident intensity from the blackbody wall set at temperature $T_w$. It is worth noting that since it depends on $T_w$, changing $T_w$ while keeping constant all the other simulation parameters will yield different values of $\\tau_{T}$.\n\n\\subsection{Total emissivity}\n\nRadcal returns the total emissivity, denoted $\\varepsilon_{T}$, for the spectral range bounded by the user defined $\\omega_{min}$ and $\\omega_{max}$. It is derived from the effective absorption coefficient $\\kappa_{\\rm e}$ through:\n\\begin{equation}\\label{eq:total_emissivity}\n\\varepsilon_{T} = 1 - \\exp\\left(- \\kappa_{\\rm e} L \\right),\n\\end{equation}\nwhere $L$ is the total physical length of the participating layer, given in $\\rm cm$. The total emissivity is dimensionless.\n\n\\subsection{Received flux}\nRadCal returns the integrated value of the received total directional radiative energy flux (or received total intensity), denoted \\verb=Received Flux= in \\verb=RADCAL.out= file. The integration is performed between the user defined bounds $\\omega_{min}$ and $\\omega_{max}$. Note that contribution of soot (if present) is added in the ranges 5~$\\rm cm^{-1}$ to $\\om_{min}$ and $\\om_{\\max}$ to 25,000~$\\rm cm^{-1}$. Its units are in $\\rm W.m^{-2}.str^{-1}$. The received total intensity, denoted $I(L)$, is calculated by:\n\\be\\label{eq::received_flux}\nI(L) = \\underbrace{\\displaystyle\\int_{\\om_{min}}^{\\om_{max}}{I_{\\om}(L)\\d \\om}}_{\\rm All\\:species} + \\underbrace{\\displaystyle\\int_{5}^{\\om_{min}}{I_{\\om}(L)\\d \\om}}_{\\rm Soot\\:only} +  \\underbrace{\\displaystyle\\int_{\\om_{max}}^{25,000}{I_{\\om}(L)\\d \\om}}_{\\rm Soot\\:only},\n\\ee\nwhere $I_{\\om}(L)$ is obtained from Eq.~\\ref{eq::RTE_wavenumber_H} for homogeneous cases, and Eq.~\\ref{eq::RTE_wavenumber_NH} for non-homogeneous cases.\n", "meta": {"hexsha": "210a19c2e40e158aab3bd8b6bc9e2442f288b4c1", "size": 56587, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Documentation/Band_Models_Chapter.tex", "max_stars_repo_name": "mcgratta/radcal", "max_stars_repo_head_hexsha": "83cb42ec8f43f243fe3b0b7640f62071b8482129", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Documentation/Band_Models_Chapter.tex", "max_issues_repo_name": "mcgratta/radcal", "max_issues_repo_head_hexsha": "83cb42ec8f43f243fe3b0b7640f62071b8482129", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Documentation/Band_Models_Chapter.tex", "max_forks_repo_name": "mcgratta/radcal", "max_forks_repo_head_hexsha": "83cb42ec8f43f243fe3b0b7640f62071b8482129", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 109.0308285164, "max_line_length": 1268, "alphanum_fraction": 0.7388622829, "num_tokens": 16607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.4726834766204329, "lm_q1q2_score": 0.3161686406749574}}
{"text": "% !TEX root = ../bachlor-arbeit.tex\n\\begin{tabular}{ll}\n    \\toprule\n    Input: &\n    \\begin{tabular}[t]{@{}l@{}}\n        transmission spectrum $I=(I_\\s{x}, \\,I_\\s{y})$ a $\\lambda \\times 2$ array\\\\\n        $I_\\s{x/y}$ ... X- and Y-transmission spectra,\n        $\\lambda$ ... number of wavelengths\n    \\end{tabular}\\\\\n    Output: &\n    two sets layer parameters $\\mc L_1$ and $\\mc L_2$,\n    stack parameters $\\mc S$ \\\\\n    \\bottomrule\n\\end{tabular}\n\n\\paragraph{Network Architecture}\nThis module is a 1D Convolutional Neural Network instead of the basic Multi Layer Perceptron. It was chosen to utilize the translational invariance of ConvNets. For example the concept \"peak\" should be learned independent of its position in the spectrum. As described in section \\ref{sec:NN_bg}, a ConvNet provides this functionality. Another constraint on the network architecture arises from the different kind of outputs.\nMost of the outputs are continuous but the choices about material $m$ and geometry $g$ are discrete/categorical.\nThese need different activation functions $\\sigma$ to reach the different value ranges. The continuous outputs are mostly bounded by physical constraints and $m, \\, g \\in [0, \\, 1]$ as they are \\textit{one hot encoded}, meaning $1 \\rightarrow$ \"The layer has this property\" and\n$0 \\rightarrow$ \"The layer does not have this property\".\n\n\n\\indent The different outputs also need different cost functions $C(y, y')$ during training where $y'$ is the networks output and $y$ is the known solution. For the continuous output one can simply use the mean squared error\n\\begin{equation}\n    C_\\s{mse}(\\vb y, \\, \\vb y') = \\sum_i \\qty(y_i - y_i')^2\n\\end{equation}\n\n\\noindent\nas all outputs are equally important and the cost function should be indifferent on whether the networks prediction is over or under target. For the categorical output the network learns quicker with the \\textit{Categorical Cross-Entropy} error\n\n\\begin{equation}\n    C_\\s{ce}(\\vb y, \\, \\vb y') = - \\sum_i y_i \\log y'_i.\n\\end{equation}\n\n\\noindent\nThis error treats false positives ($y_i = 0, \\, y_i' = 1$) and false negatives ($y_i = 1, \\, y_i' = 0$) differently. A false positive does not increase the overall cost as $y_i = 0 \\Rightarrow C_\\s{ce} = 0$ but for a false negative $C_\\s{ce} \\rightarrow \\infty$. This is favorable behavior because it does not matter if the network outputs some probability for a wrong class as long as it outputs a higher probability for the correct class. The final architecture, seen in figure \\ref{fig:al:NN_architecture}, is similar to the example given in figure \\ref{fig:bg:NN_example} while meeting the above-mentioned constraints.\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=\\linewidth]{al_NN_architecture}\n    \\caption{The network starts with 4 pairs of convolutional and pooling layers $C^i P^i   $. The convolutions are characterized by (\\textit{number of kernels}, \\textit{kernel size}). The kernel size is always 5 and the number of kernels is gradually increased. Then the Network splits into a discrete and a continuous branch via two Dense layers with (\\textit{number of neurons}). In the discrete branch a dropout is applied to the dense layer where (0.5) is (\\textit{fraction of neurons to drop}).\n    All the internal activations $\\sigma_\\s{r}$ are ReLu's and the final activations $\\sigma_\\s{s}$ and $\\sigma_{l}$ are a sigmoid and a linear function.}\n    \\label{fig:al:NN_architecture}\n\\end{figure}\n\n\\newpage\n\\paragraph{Network Training}~\\\\\nTo train a Neural Network, one needs a training set $(X, \\, Y)$ of known input output pairs. In this case they are generated using the pre-simulated single layers in the database which are randomly combined into stacks. Then the stacks X- and Y-transmission spectra $(I_x, \\, I_y)$ are calculated via SASA.\nThis means $I = (I_x, \\, I_y) \\in X$ are the networks input and the random design parameters ${\\mc D = (\\mc S, \\mc L_1, \\mc L_2) \\in Y}$ are the output. For the first test we used squares and square holes of Aluminum and Gold. During the training one epoch is defined as one loop over all training samples. After every epoch the network is validated on a data set $(X_\\s v, \\, Y_\\s v)$ of samples it has not seen before. This is done to check wether the network actually learns something rather than just memorizing the input data. It is common to rely on the cost function for training but use a separate function called \\textit{metric} to evaluate the Network. This is done because there are occasions when the cost of a network drops but the performance does not increase. The metric should be a function where the output can be easily understood by the human evaluating the network. For discrete outputs we are going to use the metric \\textit{accuracy}, that is what fraction of choices were correct and for the continuous outputs we will use the \\textit{mean absolute error}\n\n\\begin{equation} \\label{eq:al:mae}\n    M_\\s{mae}(\\vb y, \\vb y') = \\sum_i \\qty|y_i - y'_i|.\n\\end{equation}\n\n\\indent\nThe results of this first training on the square geometry can be seen in figure \\ref{fig:al:square_results}.\nTraining and validation results are very similar which indicates that there is no overfitting or memorization. The discrete accuracy quickly reaches a maximum of $\\sim 76\\%$ which is less than expected and also the speed at which this value is reached is suspicious. The network does not improve much after the fourth epoch and this does not change by tuning the network architecture. This is because the issue lies not within the architecture but in the training data. In section \\ref{sec:SASA} we have shown that for the used two layer stacks the transmission spectrum is reciprocal, that is the same for both directions. Therefor the data generation can result in two different stacks which produce the same spectrum. Consider a stack where one layer is Aluminum and the other is Gold as seen in figure \\ref{fig:al:same_spec}. As both of them produce the same spectrum, one time the network is taught that the first layer is Gold and the second is Aluminum but another time it is taught the complete opposite. Actually, if the network is trained this way it only ever predicts stacks with layers of equal materials because this is the only setup it can get right.\n\\begin{figure}[H]\n    \\centering\n    \\captionsetup[subfigure]{position=b}\n    \\begin{subfigure}{.5\\textwidth}\n        \\centering\n        \\includegraphics[width=\\linewidth]{al_square_dis}\n        \\caption{}\n    \\end{subfigure}%\n    \\begin{subfigure}{.5\\textwidth}\n        \\centering\n        \\includegraphics[width=\\linewidth]{al_square_mae}\n        \\caption{}\n    \\end{subfigure}\n    \n    \\caption{Training only with squares. (a) shows the accuracy of the discrete branch. That is, what percentage of choices for material and geometry were correct. In (b) we can see the performance of the continuous branch evaluated using the mean absolute error \\ref{eq:al:mae}.}\n    \\label{fig:al:square_results}\n    \\end{figure}\n\n\n\n\\newpage\nThis is a well known problem when trying to solve an inverse problem.\nIn this case the function $\\mc D \\rightarrow I$ is well defined as one stack can only produce one spectrum but for the inverse problem we are trying to solve $I \\rightarrow \\mc D$ and there might be multiple designs which produce the same spectrum. We can solve the issue simply by allowing only one of the orientations into the training data. By doing this the training  results change as seen in figure \\ref{fig:al:squares_fix}.\nThe discrete accuracy is much better at $\\sim 98 \\%$ and the training curve looks more natural in the sense that improvements diminish over time but do not hit a sudden barrier as they did in figure \\ref{fig:al:square_results}.\nHaving resolved this issue, we can train the model on the more complex rectangle geometry reaching 94\\% accuracy and 11 mae.\n\n\\begin{figure}[H]\n    \\floatbox[{\\capbeside\\thisfloatsetup{capbesideposition={right,top}}}]{figure}[\\FBwidth]\n    {\\caption{A stack of one Gold and one Aluminium layer separated by a glass spacer. Both stacks produce the same spectrum which leads to issues when using completely random stacks to train the network.}\n    \\label{fig:al:same_spec}}\n    {\\includegraphics[width=.36\\textwidth]{al_flipped_stack}}\n\\end{figure}\n\n\n\\begin{figure}[H]\n\\centering\n\\begin{subfigure}{.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\linewidth]{al_square_fix_dis}\n    \\caption{}\n    \\label{}\n\\end{subfigure}%\n\\begin{subfigure}{.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\linewidth]{al_square_fix_mae}\n    \\caption{}\n    \\label{}\n\\end{subfigure}\n\\caption{Training on the square geometry after only allowing one of the equivalent stacks shown in figure \\ref{fig:al:same_spec} into the training data.\nAgain, (a) shows the accuracy of the discrete branch and (b) the average cost of the continuous branch. The discrete accuracy has improved significantly compared to figure \\ref{fig:al:square_results} but the continuous loss remains similar.}\n\\label{fig:al:squares_fix}\n\\end{figure}\n\n", "meta": {"hexsha": "998eec7963ac7f3c7118440a62291d998388cba2", "size": 9042, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/algorithm/network.tex", "max_stars_repo_name": "TimLucaTuran/bachlor-arbeit", "max_stars_repo_head_hexsha": "f6c1eb502d7e99a4fdf2f3b0110677578f8eff95", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tex/algorithm/network.tex", "max_issues_repo_name": "TimLucaTuran/bachlor-arbeit", "max_issues_repo_head_hexsha": "f6c1eb502d7e99a4fdf2f3b0110677578f8eff95", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-17T15:04:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-17T15:04:05.000Z", "max_forks_repo_path": "tex/algorithm/network.tex", "max_forks_repo_name": "TimLucaTuran/bachlor-arbeit", "max_forks_repo_head_hexsha": "f6c1eb502d7e99a4fdf2f3b0110677578f8eff95", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 81.4594594595, "max_line_length": 1166, "alphanum_fraction": 0.7523777925, "num_tokens": 2247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.31616864067495737}}
{"text": "%!TEX root = ./jctt.tex\n\n\\section{Conclusions and Future Work}\nWe have presented a VEF method for the one-group slab-geometry neutron transport equation coupling \\SN equations having a Lumped Linear Discontinuous Galerkin spatial discretization with a drift-diffusion equation having a constant-linear Mixed Finite-Element discretization. We have numerically demonstrated that our LLDG/MFEM VEF method is as effective as consistently-differenced S$_2$SA; \nthat both the \\SN and drift-diffusion equations exhibit second-order accuracy and thus approach each other with second-order accuracy as the spatial mesh is refined; and that the thick diffusion limit is preserved.  We also investigated two methods for updating the \\SN scattering source given the drift-diffusion solution for the scalar flux. The first was to simply use the flat scalar flux dependence of the drift-diffusion solution in the \\SN scattering source.  The other was to reconstruct a linear discontinuous scattering source \nusing the flat or cell-average MFEM fluxes together with standard slope reconstruction methods. For a homogeneous problems, the linear update was more accurate, but there was little difference between the flat and linear updates for a highly inhomogeneous problem.  All of the desired VEF properties such as order accuracy and preservation of the diffusion limit were obtained independent of the scattering source update procedure. Most importantly, it is clear that \\SN and and drift-diffusion solutions that differ in proportion to truncation \nerror is a small price to pay for the versatility afforded by the VEF method for multiphysics calculations. The conservative drift-diffusion equation can be coupled to the other physics equations and discretized in a manner compatible with those equations.  Furthermore, the difference between the \\SN and drift-diffusion equations is a measure of the truncation error of the drift-diffusion solution, which is a very useful error estimator naturally provided by the VEF method.  \n\n% add rational polynomial conclusions: expected to be important in rad transfer \n% mfem is conservative and can be paired to multiphysics \n% take out consistency talk \n\nIn the future we intend to extend the VEF method presented in this paper to the radiative transfer equations, with higher order discretizations in 2-D and 3-D geometries.  A major question that we intend to address in the near term is the impact of the linear \nscattering source update technique in radiative transfer calculations, particularly in Marshak wave problems, where slope reconstruction \nfor the emission source is known to be important to mitigate a numerical artifact referred to as the ``teleportation'' effect  \\cite{tele}. ", "meta": {"hexsha": "168f3b12e484ec2b86c358aae94968169831cbd9", "size": 2730, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/paper/conclusions.tex", "max_stars_repo_name": "smsolivier/rh", "max_stars_repo_head_hexsha": "a12da9464328b0fd1af0878a1f55aaf961f47e05", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-30T15:24:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-30T15:24:42.000Z", "max_issues_repo_path": "tex/paper/conclusions.tex", "max_issues_repo_name": "smsolivier/rh", "max_issues_repo_head_hexsha": "a12da9464328b0fd1af0878a1f55aaf961f47e05", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/paper/conclusions.tex", "max_forks_repo_name": "smsolivier/rh", "max_forks_repo_head_hexsha": "a12da9464328b0fd1af0878a1f55aaf961f47e05", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-10-22T00:02:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-02T08:58:46.000Z", "avg_line_length": 182.0, "max_line_length": 545, "alphanum_fraction": 0.8208791209, "num_tokens": 545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.31611021860516764}}
{"text": "\\documentclass[11pt]{article}\n\\usepackage{palatino}\n\\usepackage{amsmath}\n\\usepackage{pdflscape}\n\\usepackage[margin=2cm]{geometry}\n\\begin{document}\n\n\\title{Prettyprinting Intermediate Computations from a Bytecode}\n\\maketitle\n\n\\noindent Reference: \\textit{Functional programming languages Part II: abstract machines, Xavier Leroy, INRIA Rocquencourt, MPRI 2-4-2, 2007}\n\n\\section{Programs}\n\nPrograms are defined like this. Variable accesses have been converted to deBruijn indices when the program was converted from an OCaml one.\n\n{\\small\\begin{verbatim}\ntype op = Add | Sub | Mul | Div\n\ntype prog =\n  Int of int\n| Bool of bool\n| Var of int\n| Eq of prog * prog\n| Op of prog * op * prog\n| Apply of prog * prog\n| Lambda of prog\n| Let of prog * prog\n| If of prog * prog * prog\\end{verbatim}}\n\n\\noindent For example, the OCaml program\n\n\\medskip\n\\noindent\\texttt{let x = 5 in if x = 4 then 1 else (fun x -> x + 1) 2}\n\\medskip\n\n\\noindent may be represented as:\n\n\\medskip\n{\\small\n\\begin{verbatim}Let(Int 5,\n    If(Eq(Var 1, Int 4),\n       Int 1,\n       Apply(Lambda(Op(Var 1, Add, Int 1), Int 2))))\\end{verbatim}}\n\n\n\\section{Compilation Scheme}\n\nThe abstract machine instructions are as followed (Leroy plus BOOL, IF, EQ)\n\n\\medskip\n\n\\noindent\nEMPTY\\\\\nINT(integer)\\\\\nBOOL(boolean)\\\\\nOP(op)\\\\\nEQ\\\\\nACCESS(integer)\\\\\nCLOSURE(instructions)\\\\\nLET\\\\\nENDLET\\\\\nAPPLY\\\\\nRETURN\\\\\nIF\n\\medskip\n\n\\noindent Here is the compilation scheme, again extended from Leroy:\n\n\\begin{align*}\n\\mathcal{C}(\\texttt{Int}(i)) &= \\text{INT}(i)\\\\\n\\mathcal{C}(\\texttt{Bool}(b)) &= \\text{BOOL}(b)\\\\\n\\mathcal{C}(\\texttt{Op}(a, \\oplus, b)) &= \\mathcal{C}(a); \\mathcal{C}(b); \\text{OP}(\\oplus)\\\\\n\\mathcal{C}(\\texttt{Eq}(a, b)) &= \\mathcal{C}(a); \\mathcal{C}(b); \\text{EQ}\\\\\n\\mathcal{C}(\\texttt{Var}(n)) &= \\text{ACCESS}(n)\\\\\n\\mathcal{C}(\\texttt{Lambda}(a)) &= \\text{CLOSURE}(\\mathcal{C}(a); \\text{RETURN})\\\\\n\\mathcal{C}(\\texttt{Let}(a, b)) &= \\mathcal{C}(a); \\text{LET}; \\mathcal{C}(b); \\text{ENDLET}\\\\\n\\mathcal{C}(\\texttt{Apply}(a, b)) &= \\mathcal{C}(a); \\mathcal{C}(b); \\text{APPLY}\\\\\n\\mathcal{C}(\\texttt{If}(a, b, c)) &= \\mathcal{C}(\\texttt{Lambda}(b)); \\mathcal{C}(\\texttt{Lambda}(c)); \\mathcal{C}(a); \\text{IF}\n\\end{align*}\n\n\\noindent So our example\n\n\n\\medskip\n\\noindent\\texttt{let x = 5 in if x = 4 then 1 else (fun x -> x + 1) 2}\n\\medskip\n\n\n\\noindent compiles to (including an EMPTY at the end):\n\n\\medskip\n\n\\noindent INT 5\\\\\nLET\\\\\nCLOSURE\\\\\n\\phantom{\\ \\ }\\ INT 1\\\\\n\\phantom{\\ \\ }\\ RETURN\\\\\nCLOSURE\\\\\n\\phantom{\\ \\ } CLOSURE\\\\\n\\phantom{\\ \\ \\ \\ } ACCESS 1\\\\\n\\phantom{\\ \\ \\ \\ } INT 1\\\\\n\\phantom{\\ \\ \\ \\ } OP +\\\\\n\\phantom{\\ \\ \\ \\ } RETURN\\\\\n\\phantom{\\ \\ } INT 2\\\\\n\\phantom{\\ \\ } APPLY\\\\\n\\phantom{\\ \\ } RETURN\\\\\nACCESS 1\\\\\nINT 4\\\\\nEQ\\\\\nBRANCH\\\\\nENDLET\\\\\nEMPTY\n\n\\medskip\n\n\\section{Evaluation Scheme}\n\nHere is the evaluation scheme $\\mathcal{E}$, again extended from Leroy.\n\n\\bigskip\n\n\\begin{tabular}{l|l|l||l|l|l}\n\\multicolumn{3}{c}{Machine state before}&\\multicolumn{3}{c}{Machine state after}                       \\\\\nCode                    & Env   & Stack                          & Code   & Env    & Stack             \\\\\n$\\text{INT}(i);c$       & $e$   & $s$                            & $c$    & $e$    & $i.s$             \\\\\n$\\text{BOOL}(b);c$      & $e$   & $s$                            & $c$    & $e$    & $b.s$             \\\\\n$\\text{OP}(\\oplus);c$   & $e$   & $i.i'.s$                       & $c$    & $e$    & $\\oplus(i, i').s$ \\\\\n$\\text{EQ};c$           & $e$   & $i.i'.s$                       & $c$    & $e$    & $(i = i').s$      \\\\\n$\\text{ACCESS}(n);c$    & $e$   & $s$                            & $c$    & $e$    & $e(n).s$          \\\\\n$\\text{CLOSURE}(c');c$  & $e$   & $s$                            & $c$    & $e$    & $c'[e].s$         \\\\\n$\\text{LET};c$          & $e$   & $v.s$                          & $c$    & $v.e$  & $s$               \\\\\n$\\text{ENDLET};c$       & $v.e$ & $s$                            & $c$    & $e$    & $s$               \\\\\n$\\text{APPLY;c}$        & $e$   & $v.c'[e'].s$                   & $c'$   & $v.e'$ & $c.e.s$           \\\\\n$\\text{RETURN;c}$       & $e$   & $v.c'.e'.s$                    & $c'$   & $e'$   & $v.s$             \\\\\n$\\text{IF;c}$           & $e$   & $\\textsf{T}.c'[e'].c''[e''].s$ & $c'$   & $e'$   & $c[e].s$          \\\\\n$\\text{IF;c}$           & $e$   & $\\textsf{F}.c'[e'].c''[e''].s$ & $c''$  & $e''$  & $c[e].s$          \\\\\n\\end{tabular}\n\n\\bigskip\n\n\\noindent The final result is at the top of the stack when the code is EMPTY.\n\n\\section{Decompilation Scheme}\n\nWe need to be able to decompile:\n\n\\begin{itemize}\n\\item Any program which has been compiled by the compilation scheme above.\n\\item Certain incomplete evaluations under the evaluation scheme above. That is to say, given $(c, s)$ we can decompile a program which represents the evaluation at that stage. We need not be able to decompile arbitrary $(c, e, s)$ triples.\n\\end{itemize}\n\n\\noindent  We add names to \\texttt{VarAccess}, \\texttt{Lambda} and \\texttt{Let}:\n\n\\begin{verbatim}\ntype prog =\n  Int of int\n| Bool of bool\n| VarAccess of name * int\n| Eq of prog * prog\n| Op of prog * op * prog\n| Apply of prog * prog\n| Lambda of name * prog\n| Let of name * prog * prog\n| If of prog * prog * prog\\end{verbatim}\n\n\\noindent Similarly, we add names to the ACCESS, CLOSURE and LET instructions (not required for evaluation, but only for decompilation).\n\n\\bigskip\n\n\\noindent\nEMPTY\\\\\nINT(integer)\\\\\nBOOL(boolean)\\\\\\\nOP(op)\\\\\nEQ\\\\\nACCESS(name, integer)\\\\\nCLOSURE(name, instructions)\\\\\nLET(name)\\\\\nENDLET\\\\\nAPPLY\\\\\nRETURN\\\\\nIF\n\\medskip\n\n\\noindent Decompilation is performed by going through the instructions in order, holding a stack a little like the evaluation stack, but which may also contain decompiled program fragments -- the empty stack is written $\\{\\}$. When we have gone through all the instructions, the final program is at the top of the stack. We do not need the environment, since we are not running the code, just decompiling it.\n\n\\begin{align*}\n\\mathcal{D}(\\text{EMPTY}, v.s) &= v\\\\\n\\mathcal{D}(\\text{INT}(i); c, s) &= \\mathcal{D}(c, \\texttt{Int}(i).s)\\\\\n\\mathcal{D}(\\text{BOOL}(i); c, s) &= \\mathcal{D}(c, \\texttt{Bool}(b).s)\\\\\n\\mathcal{D}(\\text{OP}(\\oplus); c, i.i'.s) &= \\mathcal{D}(c, \\texttt{Op}(i, \\oplus, i').s) \\\\\n\\mathcal{D}(\\text{EQ}; c, i.i'.s) &= \\mathcal{D}(c, \\texttt{Eq}(i, i').s)\\\\\n\\mathcal{D}(\\text{ACCESS}(n, l); c, s) &= \\mathcal{D}(c, \\texttt{VarAccess}(n, l).s)\\\\\n\\mathcal{D}(\\text{CLOSURE}(n, c'); c, s) &= \\mathcal{D}(c, c'[n, \\{\\}].s)\\\\\n\\mathcal{D}(\\text{LET}(n); c, v.s) &= \\texttt{Let}(n, v, \\mathcal{D}(c, s))\\\\\n\\mathcal{D}(\\text{ENDLET}; c, s) &= \\mathcal{D}(c, s)\\\\\n\\mathcal{D}(\\text{APPLY}; c, v.c'[n, e'].s) &= \\texttt{Apply}(\\texttt{Lambda(n}, \\mathcal{D}(c', \\{\\}\\texttt{))}, v)\\\\\n\\mathcal{D}(\\text{RETURN}; c, v.c'.e'.s) &= \\mathcal{D}(c', v.s)\\\\\n\\mathcal{D}(\\text{RETURN}; c, s) &= \\mathcal{D}(c, s)\\\\\n\\mathcal{D}(\\text{IF}; c, e.c'[e'].c''[e''].s) &= \\mathcal{D}(c, \\texttt{If}(e, \\mathcal{D}(c', s), \\mathcal{D}(c'', s)).s)\n\\end{align*}\n\n\\noindent This decompiler works for:\n\n\\begin{itemize}\n\\item Any program-stack pair (P, \\{\\}) where P was compiled by $\\mathcal{C}$ above.\n\\item program,stack pair (P, S) which is an intermediate state of the evaluation procedure $\\mathcal{E}$ (minus the environment) where P begins with OP or APPLY.\n\\end{itemize}\n\n\\noindent Our example program decompiles properly from bytecode.\n\n\\section{Worked examples}\n\nThe following pages contain a worked example of the compilation $\\mathcal{C}$, the evaluation $\\mathcal{E}$, and full-program and partial-evaluation invocations of the decompiler $\\mathcal{D}$.\n\n\n\\begin{landscape}\n\n\\noindent Compilation under $\\mathcal{C}$:\n\n\\bigskip\n\n{\\small\n\n\\noindent$\\mathcal{C}$(\\texttt{Let(Int 5, If(Eq(Var 1, Int 4), Int 1, Apply(Lambda(Op(Var 1, Add, Int 1), Int 2))))})\n\n\\smallskip\n\\noindent Rule $\\mathcal{C}$-\\texttt{Let}\n\\smallskip\n\n\\noindent $\\mathcal{C}$(\\texttt{Int 5}); LET; $\\mathcal{C}$(\\texttt{If(Eq(Var 1, Int 4), Int 1, Apply(Lambda(Op(Var 1, Add, Int 1), Int 2)))}); ENDLET\n\n\\smallskip\n\\noindent Rule $\\mathcal{C}$-\\texttt{Int}\n\\smallskip\n\n\\noindent INT 5; LET; $\\mathcal{C}$(\\texttt{If(Eq(Var 1, Int 4), Int 1, Apply(Lambda(Op(Var 1, Add, Int 1), Int 2)))}); ENDLET\n\n\\smallskip\n\\noindent Rule $\\mathcal{C}$-\\texttt{If}\n\\smallskip\n\n\\noindent INT 5; LET; $\\mathcal{C}$(\\texttt{Lambda (Int 1)}); $\\mathcal{C}$(\\texttt{Lambda(Apply(Lambda(Op(Var 1, Add, Int 1), Int 2)))}); $\\mathcal{C}$(\\texttt{Eq(Var 1, Int 4)}); IF; ENDLET\n\n\n\\smallskip\n\\noindent Rule $\\mathcal{C}$-\\texttt{Eq} then Rule $\\mathcal{C}$-\\texttt{Eq} then Rule $\\mathcal{C}$-\\texttt{Eq}\n\\smallskip\n\n\\noindent INT 5; LET; $\\mathcal{C}$(\\texttt{Lambda (Int 1)}); $\\mathcal{C}$(\\texttt{Lambda(Apply(Lambda(Op(Var 1, Add, Int 1), Int 2)))}); ACCESS 1; INT 4; EQ; IF; ENDLET\n\n\\smallskip\n\\noindent Rule $\\mathcal{C}$-\\texttt{Lambda} then Rule $\\mathcal{C}$-\\texttt{Int}\n\\smallskip\n\n\\noindent INT 5; LET; CLOSURE [INT 1; RETURN]; $\\mathcal{C}$(\\texttt{Lambda(Apply(Lambda(Op(Var 1, Add, Int 1), Int 2)))}); ACCESS 1; INT 4; EQ; IF; ENDLET\n\n\\smallskip\n\\noindent Rule $\\mathcal{C}$-\\texttt{Lambda}\n\\smallskip\n\n\\noindent INT 5; LET; CLOSURE [INT 1; RETURN]; CLOSURE [$\\mathcal{C}$(\\texttt{Apply(Lambda(Op(Var 1, Add, Int 1), Int 2))}); RETURN]; ACCESS 1; INT 4; EQ; IF; ENDLET\n\n\\smallskip\n\\noindent Rule $\\mathcal{C}$-\\texttt{Apply}\n\\smallskip\n\n\\noindent INT 5; LET; CLOSURE [INT 1; RETURN]; CLOSURE [$\\mathcal{C}$(\\texttt{Lambda(Op(Var 1, Add, Int 1))}; $\\mathcal{C}$(\\texttt{Int 2}); APPLY; RETURN]; ACCESS 1; INT 4; EQ; IF; ENDLET\n\n\n\\smallskip\n\\noindent Rule $\\mathcal{C}$-\\texttt{Int} then Rule $\\mathcal{C}$-\\texttt{Lambda} then Rule $\\mathcal{C}$-\\texttt{Op} then Rule $\\mathcal{C}$-\\texttt{Var} then Rule $\\mathcal{C}$-\\texttt{Int}\n\\smallskip\n\n\\noindent INT 5; LET; CLOSURE [INT 1; RETURN]; CLOSURE [CLOSURE [ACCESS 1; INT 1; OP +; RETURN]; INT 2; APPLY; RETURN]; ACCESS 1; INT 4; EQ; IF; ENDLET\n\n\n}\n\n\\newpage\n\n\\noindent Evaluation under $\\mathcal{E}$. Stacks and environments are written \\{items\\}, and a closure on the stack is written [instructions]\\{environment\\}. Environments may be put on the stack.\n\n\\bigskip\n\n{\\small\n\\begin{tabular}{l||p{9.5cm}|l|p{9.5cm}}\n& \\multicolumn{3}{c}{Machine state after}                       \\\\\nInstruction & Code      & Env   & Stack\\\\\n   -        & INT 5; LET; CLOSURE [INT 1; RETURN]; CLOSURE [CLOSURE [ACCESS 1; INT 1; OP +; RETURN]; INT 2; APPLY; RETURN]; ACCESS 1; INT 4; EQ; IF; ENDLET & \\{\\}  & \\{\\}\\\\\n\nINT & LET; CLOSURE [INT 1; RETURN]; CLOSURE [CLOSURE [ACCESS 1; INT 1; OP +; RETURN]; INT 2; APPLY; RETURN]; ACCESS 1; INT 4; EQ; IF; ENDLET& \\{\\}   & \\{5\\}\\\\\n\nLET & CLOSURE [INT 1; RETURN]; CLOSURE [CLOSURE [ACCESS 1; INT 1; OP +; RETURN]; INT 2; APPLY; RETURN]; ACCESS 1; INT 4; EQ; IF; ENDLET & \\{5\\}   & \\{\\}\\\\\n\nCLOSURE & CLOSURE [CLOSURE [ACCESS 1; INT 1; OP +; RETURN]; INT 2; APPLY; RETURN]; ACCESS 1; INT 4; EQ; IF; ENDLET & \\{5\\}   & \\{[INT 1; RETURN]\\{5\\}\\}\\\\\n\nCLOSURE & ACCESS 1; INT 4; EQ; IF; ENDLET & \\{5\\} & \\{[CLOSURE [ACCESS 1; INT 1; OP +; RETURN]\\{5\\}; INT 2; APPLY; RETURN]; [INT 1; RETURN]\\{5\\}\\}\\\\\n\nACCESS & INT 4; EQ; IF; ENDLET & \\{5\\}   & \\{5; [CLOSURE [ACCESS 1; INT 1; OP +; RETURN]\\{5\\}; INT 2; APPLY; RETURN]; [INT 1; RETURN]\\{5\\}\\}\\\\\n\nINT & EQ; IF; ENDLET & \\{5\\}   & \\{4; 5; [CLOSURE [ACCESS 1; INT 1; OP +; RETURN]\\{5\\}; INT 2; APPLY; RETURN]; [INT 1; RETURN]\\{5\\}\\}\\\\\n\nEQ & IF; ENDLET & \\{5\\}   & \\{false; [CLOSURE [ACCESS 1; INT 1; OP +; RETURN]\\{5\\}; INT 2; APPLY; RETURN]; [INT 1; RETURN]\\{5\\}\\}\\\\\n\nIF & CLOSURE [ACCESS 1; INT 1; OP +; RETURN]; INT 2; APPLY; RETURN & \\{5\\} & \\{[ENDLET]; \\{5\\}\\}\\\\\n\nCLOSURE & INT 2; APPLY; RETURN & \\{5\\} & \\{[ACCESS 1; INT 1; OP +; RETURN]\\{5\\}; [ENDLET]; \\{5\\}\\}\\\\\n\nINT & APPLY; RETURN & \\{5\\} & \\{2; [ACCESS 1; INT 1; OP +; RETURN]\\{5\\}; [ENDLET]; \\{5\\}\\}\\\\\n\nAPPLY & ACCESS 1; INT 1; OP +; RETURN & \\{2; 5\\} & \\{[RETURN]; \\{5\\}; [ENDLET]; \\{5\\}\\}\\\\\n\nACCESS & INT 1; OP +; RETURN & \\{2; 5\\} & \\{2; [RETURN]; \\{5\\}; [ENDLET]; \\{5\\}\\}\\\\\n\nINT & OP +; RETURN & \\{2; 5\\} & \\{1; 2; [RETURN]; \\{5\\}; [ENDLET]; \\{5\\}\\}\\\\\n\nOP & RETURN & \\{2; 5\\} & \\{3; [RETURN]; \\{5\\}; [ENDLET]; \\{5\\}\\}\\\\\n\nRETURN & EMPTY & \\{2; 5\\} & \\{3; [RETURN]; \\{5\\}; [ENDLET]; \\{5\\}\\}\\\\\n\nRETURN & EMPTY & \\{5\\} & \\{3; [ENDLET]; \\{5\\}\\}\\\\\n\nENDLET & EMPTY & \\{\\} & \\{3\\}\\\\\nEMPTY\n\\end{tabular}\n}\n\n\\newpage\n\n{\\small\n\n\\noindent Decompilation under $\\mathcal{D}$ of a program compiled under $\\mathcal{C}$, with an empty stack to begin, since the program is unexecuted.\n\n\\bigskip\n\n\\noindent $\\mathcal{D}$(INT 5; LET x; CLOSURE [INT 1; RETURN]; CLOSURE [CLOSURE [ACCESS (x, 1); INT 1; OP +; RETURN]; INT 2; APPLY; RETURN]; ACCESS (x, 1); INT 4; EQ; IF; ENDLET, \\{\\})\n\n\\smallskip\n\\noindent Rule $\\mathcal{D}$-CONST\n\\smallskip\n\n\\noindent $\\mathcal{D}$(LET x; CLOSURE [INT 1; RETURN]; CLOSURE [CLOSURE [ACCESS (x, 1); INT 1; OP +; RETURN]; INT 2; APPLY; RETURN]; ACCESS (x, 1); INT 4; EQ; IF; ENDLET, \\{\\texttt{Int 5}\\})\n\n\\smallskip\n\\noindent Rule $\\mathcal{D}$-LET\n\\smallskip\n\n\\noindent \\texttt{Let(x, }\\texttt{Int 5}, $\\mathcal{D}$(CLOSURE [INT 1; RETURN]; CLOSURE [CLOSURE [ACCESS (x, 1); INT 1; OP +; RETURN]; INT 2; APPLY; RETURN]; ACCESS (x, 1); INT 4; EQ; IF; ENDLET, \\{\\})\\texttt{)}\n\n\\smallskip\n\\noindent Rule $\\mathcal{D}$-CLOSURE\n\\smallskip\n\n\\noindent \\texttt{Let(x, }\\texttt{Int 5}, $\\mathcal{D}$(CLOSURE [CLOSURE [ACCESS (x, 1); INT 1; OP +; RETURN]; INT 2; APPLY; RETURN]; ACCESS (x, 1); INT 4; EQ; IF; ENDLET, \\{CLOSURE [INT 1; RETURN]\\})\\texttt{)}\n\n\\smallskip\n\\noindent Rule $\\mathcal{D}$-CLOSURE\n\\smallskip\n\n\\noindent \\texttt{Let(x, }\\texttt{Int 5}, $\\mathcal{D}$(ACCESS (x, 1); INT 4; EQ; IF; ENDLET, \\{ CLOSURE [ACCESS (x, 1); INT 1; OP +; RETURN; INT 2; APPLY; RETURN]; CLOSURE [INT 1; RETURN]\\})\\texttt{)}\n\n\\smallskip\n\\noindent Rule $\\mathcal{D}$-ACCESS\n\\smallskip\n\n\\noindent \\texttt{Let(x, }\\texttt{Int 5}, $\\mathcal{D}$(INT 4; EQ; IF; ENDLET, \\{\\texttt{VarAccess(x, 1)}; CLOSURE [ACCESS (x, 1); INT 1; OP +; RETURN; INT 2; APPLY; RETURN]; CLOSURE [INT 1; RETURN]\\})\\texttt{)}\n\n\\smallskip\n\\noindent Rule $\\mathcal{D}$-INT\n\\smallskip\n\n\\noindent \\texttt{Let(x, }\\texttt{Int 5}, $\\mathcal{D}$(EQ; IF; ENDLET, \\{\\texttt{Int 4}; \\texttt{VarAccess(x, 1)}; CLOSURE [ACCESS (x, 1); INT 1; OP +; RETURN]; INT 2; APPLY; RETURN; CLOSURE [INT 1; RETURN]\\})\\texttt{)}\n\n\\smallskip\n\\noindent Rule $\\mathcal{D}$-EQ\n\\smallskip\n\n\\noindent \\texttt{Let(x, }\\texttt{Int 5}, $\\mathcal{D}$(IF; ENDLET, \\{\\texttt{Eq(VarAccess (x, 1), Int 4)};  CLOSURE [ACCESS (x, 1); INT 1; OP +; RETURN]; INT 2; APPLY; RETURN; CLOSURE [INT 1; RETURN]\\})\\texttt{)}\n\n\\smallskip\n\\noindent Rule $\\mathcal{D}$-IF\n\\smallskip\n\n\\noindent \\texttt{Let(x, }\\texttt{Int 5}, $\\mathcal{D}$(ENDLET, \\{\\texttt{If(Eq(VarAccess (x, 1), Int 4)}, $\\mathcal{D}$(CLOSURE [ACCESS (x, 1); INT 1; OP +; RETURN]; INT 2; APPLY; RETURN, \\{\\}), $\\mathcal{D}$(CLOSURE [INT 1; RETURN], \\{\\})\\texttt{)}\n\n\n\\smallskip\n\\noindent Rule $\\mathcal{D}$-ENDLET\n\\smallskip\n\n\\noindent \\texttt{Let(x, Int 5, If(Eq(VarAccess (x, 1), Int 4)}, $\\mathcal{D}$(CLOSURE [ACCESS (x, 1); INT 1; OP +; RETURN]; INT 2; APPLY; RETURN, \\{\\}), $\\mathcal{D}$(CLOSURE [INT 1; RETURN], \\{\\})\\texttt{)}\n\n\\smallskip\n\\noindent Rule $\\mathcal{D}$-CLOSURE then $\\mathcal{D}$-INT then $\\mathcal{D}$-RETURN\n\\smallskip\n\n\\noindent \\texttt{Let(x, Int 5, If(Eq(VarAccess (x, 1), Int 4)}, $\\mathcal{D}$(CLOSURE [ACCESS (x, 1); INT 1; OP +; RETURN]; INT 2; APPLY; RETURN, \\{\\}), \\texttt{Int 1})\\texttt{)}\n\n\\smallskip\n\\noindent Rule $\\mathcal{D}$-CLOSURE\n\\smallskip\n\n\\noindent \\texttt{Let(x, Int 5, If(Eq(VarAccess (x, 1), Int 4)}, $\\mathcal{D}$(INT 2; APPLY; RETURN, \\{CLOSURE [ACCESS (x, 1); INT 1; OP +; RETURN]\\}), \\texttt{Int 1})\\texttt{)}\n\n\\smallskip\n\\noindent Rule $\\mathcal{D}$-INT\n\\smallskip\n\n\\noindent \\texttt{Let(x, Int 5, If(Eq(VarAccess (x, 1), Int 4)}, $\\mathcal{D}$(APPLY; RETURN, \\{\\texttt{Int 2}; CLOSURE [ACCESS (x, 1); INT 1; OP +; RETURN]\\}), \\texttt{Int 1})\\texttt{)}\n\n\\smallskip\n\\noindent Rule $\\mathcal{D}$-APPLY\n\\smallskip\n\n\\noindent \\texttt{Let(x, Int 5, If(Eq(VarAccess (x, 1), Int 4)}, \\ \\texttt{Apply(}$\\mathcal{D}$(ACCESS (x, 1); INT 1; OP +; RETURN, \\{\\}), \\texttt{Int 2)}, \\texttt{Int 1})\\texttt{)}\n\n\\smallskip\n\\noindent Rule $\\mathcal{D}$-ACCESS then $\\mathcal{D}$-INT then $\\mathcal{D}$-OP then $\\mathcal{D}$-RETURN\n\\smallskip\n\n\\noindent \\texttt{Let(x, Int 5, If(Eq(VarAccess (x, 1), Int 4)}, \\ \\texttt{Apply(Lambda(Op(Var 1, Add, Int 1)), \\texttt{Int 2)}, \\texttt{Int 1})\\texttt{)}}\n\n}\n\n\\newpage\n\n{\\small\n\n\\noindent Decompilation under $\\mathcal{D}$ of a program compiled under $\\mathcal{C}$ and partially evaluated with $\\mathcal{D}$.\n\n\\bigskip\n\n\\noindent $\\mathcal{D}$(IF; ENDLET, {false; [CLOSURE [ACCESS(x, 1); INT 1; OP +; RETURN]; INT 2; APPLY; RETURN]; [INT 1; RETURN]})\n\n\\smallskip\n\\noindent Rule $\\mathcal{D}$-IF\n\\smallskip\n\n\\noindent $\\mathcal{D}$(ENDLET, \\texttt{If (false,} $\\mathcal{D}$([INT 1; RETURN], \\{\\})) $\\mathcal{D}$([CLOSURE [ACCESS(x, 1); INT 1; OP +: RETURN]; INT 2; APPLY; RETURN], \\{\\}), \\{\\})\n\n\\smallskip\n\\noindent Rule $\\mathcal{D}$-ENDLET\n\\smallskip\n\n\\noindent \\texttt{If (Bool false,} $\\mathcal{D}$([INT 1; RETURN], \\{\\}), $\\mathcal{D}$([CLOSURE [ACCESS(x, 1); INT 1; OP +: RETURN]; INT 2; APPLY; RETURN]\\{\\}), \\texttt{)}\n\n\\smallskip\n\\noindent Rule $\\mathcal{D}$-INT then $\\mathcal{D}$-RETURN\n\\smallskip\n\n\n\\noindent \\texttt{If (Bool false,} \\texttt{Int 1}, $\\mathcal{D}$([CLOSURE [ACCESS(x, 1); INT 1; OP +: RETURN]; INT 2; APPLY; RETURN]\\{\\}),\\texttt{)}\n\n\\smallskip\n\\noindent Rule $\\mathcal{D}$-CLOSURE\n\\smallskip\n\n\n\\noindent \\texttt{If (Bool false,} \\texttt{Int 1}, $\\mathcal{D}$([INT 2; APPLY; RETURN], \\{[ACCESS(x, 1); INT 1; OP +: RETURN]\\})\\texttt{)}\n\n\\smallskip\n\\noindent Rule $\\mathcal{D}$-INT\n\\smallskip\n\n\\noindent \\texttt{If (Bool false,} \\texttt{Int 1}, $\\mathcal{D}$([APPLY; RETURN], \\{\\texttt{Int 2}; [ACCESS(x, 1); INT 1; OP +: RETURN]\\})\\texttt{)}\n\n\\smallskip\n\\noindent Rule $\\mathcal{D}$-APPLY\n\\smallskip\n\n\\noindent \\texttt{If (Bool false,}, \\texttt{Int 1}, \\texttt{Apply (Lambda(x, }$\\mathcal{D}$(ACCESS(x, 1); INT 1; OP +: RETURN, \\{\\}), \\texttt{Int 2))}\\texttt{)}\n\n\\smallskip\n\\noindent Rule $\\mathcal{D}$-ACCESS\n\\smallskip\n\n\\noindent \\texttt{If (Bool false,} \\texttt{Int 1}, \\texttt{Apply (Lambda(x, }$\\mathcal{D}$(INT 1; OP +; RETURN, \\{\\texttt{VarAccess(x, 1)}\\}), \\texttt{Int 2))}\\texttt{)}\n\n\\smallskip\n\\noindent Rule $\\mathcal{D}$-INT\n\\smallskip\n\n\\noindent \\texttt{If (Bool false,} \\texttt{Int 1}, \\texttt{Apply (Lambda(x, }$\\mathcal{D}$(OP +; RETURN, \\{\\texttt{Int 1; VarAccess(x, 1)}\\}), \\texttt{Int 2))}\\texttt{)}\n\n\\smallskip\n\\noindent Rule $\\mathcal{D}$-OP\n\\smallskip\n\n\\noindent \\texttt{If (Bool false,} \\texttt{Int 1}, \\texttt{Apply (Lambda(x, }$\\mathcal{D}$(RETURN, \\{\\texttt{Op(VarAccess(x, 1), Add, Int 1)}\\}), \\texttt{Int 2))}\\texttt{)}\n\n\\smallskip\n\\noindent Rule $\\mathcal{D}$-RETURN\n\\smallskip\n\n\\noindent \\texttt{If (Bool false,} \\texttt{Int 1}, \\texttt{Apply (Lambda(x, Op(VarAccess(x, 1), Add, Int 1)}, \\texttt{Int 2))}\\texttt{)}\n\n\\bigskip\n\n\\noindent This is the program \\texttt{if false then 1 else (fun x -> x + 1) 2}, as required.\n\n}\\end{landscape}\n\n\\end{document}\n", "meta": {"hexsha": "4c3afc32be781df3aaea7dae2260d8723c17788e", "size": 19025, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/abstract-prettyprinting.tex", "max_stars_repo_name": "johnwhitington/ocamli", "max_stars_repo_head_hexsha": "28da5d87478a51583a6cb792bf3a8ee44b990e9f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 100, "max_stars_repo_stars_event_min_datetime": "2017-09-08T09:49:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T12:12:50.000Z", "max_issues_repo_path": "docs/abstract-prettyprinting.tex", "max_issues_repo_name": "johnwhitington/ocamli", "max_issues_repo_head_hexsha": "28da5d87478a51583a6cb792bf3a8ee44b990e9f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-01-31T15:47:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-01T11:54:44.000Z", "max_forks_repo_path": "docs/abstract-prettyprinting.tex", "max_forks_repo_name": "johnwhitington/ocamli", "max_forks_repo_head_hexsha": "28da5d87478a51583a6cb792bf3a8ee44b990e9f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5988142292, "max_line_length": 408, "alphanum_fraction": 0.6031011827, "num_tokens": 7488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.3161102111425952}}
{"text": "\\section{Introduction}\n\n% --------------------------------------------------------------------------------------------------------------\n\\begin{frame}\n\\frametitle{Pagerank}\n\\begin{figure}\n\t\\centering\n\t\\includegraphics[width=0.8\\textwidth]{pagerank1.png}\n\t\\caption{PageRank example 1 \\cite{prsigner}}\n\\end{figure}\n\\begin{itemize}\n  \\item A page has a high PageRank $R$ if\n  \\begin{itemize}\n    \\item there are many pages linking to it\n    \\item or, if there are some pages with a high PageRank\nlinking to it\n  \\end{itemize}\n\\end{itemize}\n\\end{frame}\n% --------------------------------------------------------------------------------------------------------------\n\n% --------------------------------------------------------------------------------------------------------------\n\\begin{frame}\n\\frametitle{PageRank}\n\n\\begin{minipage}[l]{0.5\\textwidth}\n\\textbf{$$ \nR(P_i)= \\sum_{P_j \\in B_i}\\frac{R(P_j)}{L_j}\n$$}\n\\begin{itemize}\n  \\item where\n  \\begin{itemize}\n    \\item $B_i$ is the set of pages that link to page $P_i$\n    \\item $L_j$ is the number of outgoing links for page $P_j$\nlinking to it\n  \\end{itemize}\n\\end{itemize}\n\\end{minipage}\n\\begin{minipage}[l]{0.49\\textwidth}\n\\begin{figure}\n\t\\centering\n\t\\includegraphics[width=\\textwidth]{pagerank2.png}\n\t\\caption{PageRank example 2 \\cite{prsigner}}\n\\end{figure}\n\\end{minipage}\n\n\\end{frame}\n% --------------------------------------------------------------------------------------------------------------\n\n% --------------------------------------------------------------------------------------------------------------\n\\begin{frame}\n\\begin{figure}\n\t\\centering\n\t\\includegraphics[width=0.65\\textwidth]{squirrel.png}\n\t\\caption*{\\cite{squirrel}}\n\\end{figure}\n\\end{frame}\n% --------------------------------------------------------------------------------------------------------------\n\n% --------------------------------------------------------------------------------------------------------------\n\\begin{frame}\n\\frametitle{Apache Flink}\n\\begin{itemize}\n\\item Open source framework for distributed Big Data Analytics\n\\item Exploits:\n\t\\begin{itemize}\n\t\\item data streaming\n\t\\item in-memory processing\n\t\\item iteration operators\n\t\\end{itemize}\nto improve performance\n\\item Formerly Stratosphere (Flink means agile)\n\\item Developed here at TU Berlin\n\\end{itemize}\n\\end{frame}\n% --------------------------------------------------------------------------------------------------------------\n\n% --------------------------------------------------------------------------------------------------------------\n\\begin{frame}\n\\begin{figure}\n\t\\centering\n\t\\includegraphics[width=0.9\\textwidth]{repetition.jpg}\n\t\\caption*{\\cite{repetition}}\n\\end{figure}\n\\end{frame}\n% --------------------------------------------------------------------------------------------------------------\n\n% --------------------------------------------------------------------------------------------------------------\n\\begin{frame}\n\\frametitle{Apache Flink: 2 possible setups}\n\n\\begin{minipage}[l]{0.5\\textwidth}\n\\begin{figure}\n\t\\centering\n\t\\includegraphics[width=0.9\\textwidth]{pomxml.png}\n\t\\caption{Maven}\n\\end{figure}\n\\end{minipage}\n\\begin{minipage}[l]{0.49\\textwidth}\n\\begin{figure}\n\t\\centering\n\t\\includegraphics[width=\\textwidth]{dashboard.png}\n\t\\caption{Binary version (self compiled)}\n\\end{figure}\n\\end{minipage}\n\\end{frame}\n% --------------------------------------------------------------------------------------------------------------\n\n\\begin{frame}\n\\frametitle{Demo}\n\\begin{figure}\n\t\\centering\n\t\\includegraphics[width=0.9\\textwidth]{job.png}\n\t\\caption{Visualisation of a Flink job}\n\\end{figure}\n\\end{frame}\n\n% --------------------------------------------------------------------------------------------------------------\n\\begin{frame}\n\\frametitle{Apache Flink: Gelly}\n\n\\begin{figure}\n\t\\centering\n\t\\includegraphics[width=\\textwidth]{gelly.png}\n\t\\caption{Gelly}\n\\end{figure}\n\n\\end{frame}\n% --------------------------------------------------------------------------------------------------------------\n\n% --------------------------------------------------------------------------------------------------------------\n\\begin{frame}\n\\frametitle{Apache Flink: Gelly}\n\\begin{itemize}\n\\item Large-scale graph processing API\n\\item On top of Flink's Java API\n\\item Off-the shelf library methods (e.g. PageRank)\n\\item Iterative algorithms\n\\end{itemize}\n\n\n\\end{frame}\n% --------------------------------------------------------------------------------------------------------------\n", "meta": {"hexsha": "724f053a39c5ab95c04f777cbac1da2c27f2527d", "size": 4483, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "presentation/chapters/intro.tex", "max_stars_repo_name": "warreee/apache-flink_vs_dato-graphlab", "max_stars_repo_head_hexsha": "cd01cee208461479d3f27489ab45df439b8b9820", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "presentation/chapters/intro.tex", "max_issues_repo_name": "warreee/apache-flink_vs_dato-graphlab", "max_issues_repo_head_hexsha": "cd01cee208461479d3f27489ab45df439b8b9820", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "presentation/chapters/intro.tex", "max_forks_repo_name": "warreee/apache-flink_vs_dato-graphlab", "max_forks_repo_head_hexsha": "cd01cee208461479d3f27489ab45df439b8b9820", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1319444444, "max_line_length": 112, "alphanum_fraction": 0.4401070712, "num_tokens": 970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.31611021114259513}}
{"text": "\\documentclass[12pt,letter,notitlepage]{article}\n\\usepackage{url,graphicx,bm,latexsym,amsmath,amssymb,comment,diagbox}\n\\pagestyle{plain}\n\\textwidth 6in\n\\textheight 9in\n\\topmargin -0.75in\n\\oddsidemargin 0.25in\n\n%-----------------------\n\\begin{document}\n\n\\title{Perceived Randomness: Pseudo-Random Number Generators \\& Human Interpretation}\n\n\\author{Kyle Carson \\\\\n\\url{kylecarson@cs.ucsb.edu} \\\\\nDepartment of Computer Science \\\\\nUniversity of California Santa Barbara\n}\n\n\\date{June 17, 2017}\n\n\\maketitle % \\thispagestyle{plain} \\thispagestyle{empty}\n\n\\begin{abstract}\nRandom number generators represent a core building block within cryptography, in some cases forming the basis of software and hardware encryption. While true randomness requires specially designed hardware, many software implementations, known \"pseudo-random\" or \"deterministic\" number generators, exist. From efficiency of computation to the level of precision, these software-implemented algorithms differ along many vectors. In applied cryptography and beyond, there exist instances where humans directly interacting with the results of these generators may interpret them with their own concept of what is considered random. In this paper, we compare various DRNGs in terms of multiple quality metrics. As an additional exercise, we analyze the shortcomings of these algorithms against human interpretation, and design a method which introduces various types of biasing to these generators with the intent of improving the \"perceived randomness\".\n\\end{abstract}\n\n\\section{Introduction}\n\nWhile many deterministic number generators, or \"DRNGs\", share a basis in modular arithmetic of primes, the finer details of their implementation tend to play a crucial role in their overall performance. Contrary to \"true\" random number generators which are designed at the hardware level around some source of classical or quantum physical entropy, the randomness of DRNGs is backed by certain assumptions about the complexity or irreversible nature of the building blocks used to form the algorithms.\n\nFor a DRNG algorithm to be considered for all intents and purposes cryptographically secure, there exists a general set of properties and behaviors that need to be met. The algorithm should take some k-bit input as a seed, preferably from a source of true randomness, and should output some n-bit random value. Some part of this output should then contribute to the seeding of the next call to the algorithm, in a way that produces a statistically uniform distribution of random values over multiple calls. Of important note here is that, for a given seed, successive calls to a DRNG algorithm will produce some statics stream of values. That is, if one were to make successive calls again to the algorithm with the same initial seed as before, the stream of values produced will be exactly the same as before. \n\nSome tests used to quantify the algorithms include the polynomial-time statistical test, which holds if no polynomial-time approach can distinguish the statistical difference of randomness between a DRNG and a truly random generator with probability greater than 0.5. Another test, the next-bit test, holds true if for the first m-bits of some output O, the m+1 bit cannot be predicted with statistical probability greater than 0.5. Following the basic model for structuring the algorithm and passing these tests quantifies a DRNG algorithm as cryptographically secure.\n\n\\section{DRNGs}\n\nTo attain a more applied understanding of these algorithms as described above, we've implemented seven different approaches including LCG, BBS, RSA, MSRSA, RAB, PG, and NR. Below we discuss the general principles for each algorithm, and anything of interest regarding each algorithms' actual implementation. All of the code was written in C, and can be found at \\url{https://github.com/carsonkk/drngs}.\n\n\\subsection{LCG}\n\nLinear Congruential Generator is a simple deterministic algorithm based on modular arithmetic of the previous output to produce the next output: \n\\[x_{\\text{i+1}} = a * x_i + b ({\\text{mod n}})\\]\nDepending on the values used to seed the algorithm, a sequence of some static window size is formed, such that once all of the values in the window have been produced, the sequence will wrap back around and repeat itself. There's many different options for what values to set the multiplicative and adder factors too depending on the application, however going by ANSI standard we set $a = 1103515245, b = 12345, n = 0x80000000$.\n\n\\subsection{BBS}\n\nBlum-Blum-Shub is based on the following equation, where the modulus value is the multiplication of two large primes:\n\\[x_{\\text{i+1}} = x_i^2 ({\\text{mod n}})\\]\n\\[n = p*q\\]\nSome important properties must hold for the algorithm to behave as desired, including the seed value and n being co-prime and the primes $p, q$ should both be congruent to $3{\\text{mod 4}}$. The actual output of the single pass is used to seed the next pass, however the only information used from an output towards the generated value is a singular bit of the output. Common bit outputs include even parity, odd parity, and the least significant bit. Therefore to actually generate a value, one must define some desired level of precision and run the algorithm that many times to fully form a generated value. \n\nThis pattern of using a single bit and doing multiple passes for some level of precision is quite common, and ends up being used in all of the following algorithms\n\n\\subsection{RAB}\n\nThe Rabin algorithm is a modified form of the the BBS algorithm:\n\\[x'_{\\text{i+1}} = x_i^2 ({\\text{mod n}})\\]\n\\[x_{\\text{i+1}} = (x'_{\\text{i+1}} < n/2) \\text{ ? } x'_{\\text{i+1}} \\text{ : } n - x'_{\\text{i+1}}\\]\n\\[n = p*q\\]\n\n\\subsection{RSA}\n\nRSA like many of these algorithms is based on the factoring problem, using a much more involved series of equations to generate its asymmetric results:\n\\[x_{\\text{i+1}} = x_i^e ({\\text{mod n}})\\]\n\\[e \\in [2,\\phi-1] {\\text{ with }} gcd(e,\\phi) = 1\\]\n\\[\\phi = (p-1)*(q-1)\\]\n\\[n = p*q\\]\n\n\\subsection{MSRSA}\n\nA modified version of RSA, in this case referred to as Micali-Schnorr RSA, improves the overall efficiency of traditional RSA. Simply speaking, this is done by extracting more bits from each exponentiation, making modifications to both the range for the exponent $e$ and how the bits for both successive seeding and output are chosen.\n\n\n\\subsection{PG}\n\nThe Power Generator algorithm derives its strength from using primitive elements of a set for a given primes to perform modular exponentiation. Due to how expensive it is to compute primitive elements for significantly large primes, we pre-computed a set of primes and associated primitives and used them to drive the algorithm. While this greatly increased the efficiency of the computation, a less than desirable result of this was a significant limit on the range of values that could be generated, particularly when using smaller primes. A better approach would be to invest the computational power to generate primitives for large primes and index them for future use, however this would take a non-trivial amount of time to complete.\n\\[x_{\\text{i+1}} = g^{x_i} ({\\text{mod p}})\\]\n\n\\subsection{NR}\n\nThe Naor-Reingold algorithm is similar to the Blum-Blum-Shub algorithm in that tis complexity is dependent upon the inability of an attacker to factor large prime integers. It uses a few building blocks of its own for it's computation, including a binary vectoring function, a modular product function, and a integer vector comparison function. The binary vectoring function ($bin_k(u)$) takes two integer parameters, $k$ and $u$, and translates the $k$-least-significant-bits of $u$ into a binary vector array. If $u$ has less bits than the value of $k$, the vector array's most-significant-bits are padded with 0's. The modular product function ($dot$) takes two binary vectors of the same length and takes the summation of the products of each bit from the two vectors, applying a modulus of 2 to the result. Finally the vector comparison function ($f(A,b)$) takes two vector parameters, $A$ which is of integers and length $2k$, and b which is a binary vector of length $k$. The values in $A$ are in pairs, where the first value is relevant if the corresponding bit in $b$ is 0, or the second value is relevant if the bit is 1. Thus the function selects each of the relevant integers from $A$ using $b$, then returns their summation. These functions are then used in the actual computation of the generated value:\n\\[b = {\\text{bin}}_k(i)\\]\n\\[u = f(A,b)\\]\n\\[v = g^u ({\\text{mod n}})\\]\n\\[x_{\\text{i+1}} = x_i {\\text{ dot }} {\\text{bin}}_{2k}(v)\\]\n\n\\section{Testing}\n\n\\subsection{Setup}\n\nThe test setup for measuring the quality of each algorithm was based on two inter-related metrics: CPU cycles and real-world time of execution. To somewhat normalize the precision between each algorithm, each one's random function call uses the same methodology as LCG in which the upper-order magnitude of bits is used when returning the actual output. The experiment was performed multiple times, varying the number of successive calls made to each algorithm as outlined below in Table 1 and Table 2.\n\n\\begin{table}\n\\centering\n\\begin{tabular}{|l||*{7}{c|}}\\hline\n\\backslashbox{Algo}{Calls}\n&\\makebox[3em]{10}&\\makebox[3em]{25}&\\makebox[3em]{100}&\\makebox[3em]{250}\n&\\makebox[3em]{10000}&\\makebox[3em]{100000}&\\makebox[3em]{1000000}\\\\\\hline\\hline\nLCG&0.0&0.0&0.0&0.0&0.0&0.001&0.012\\\\\\hline\nBBS&0.0&0.0&0.0&0.0&0.006&0.064&0.468\\\\\\hline\nRAB&0.0&0.0&0.0&0.0&0.008&0.077&0.524\\\\\\hline\nRSA&2.53&6.242&26.536&70.27&-&-&-\\\\\\hline\nMSRSA&0.0&0.0&0.0&0.0&0.051&0.275&2.432\\\\\\hline\nPG&0.0&0.0&0.0&0.0&0.033&0.276&2.206\\\\\\hline\nNR&4.89&28.934&444.311&504.85&-&-&-\\\\\\hline\n\\end{tabular}\n\\caption{\\label{tab:table-name}Algorithm speed in terms of real-world computation time (seconds)}\n\\end{table}\n\n\\begin{table}\n\\centering\n\\begin{tabular}{|l||*{7}{c|}}\\hline\n\\backslashbox{Algo}{Calls}\n&\\makebox[3em]{10}&\\makebox[3em]{25}&\\makebox[3em]{100}&\\makebox[3em]{250}\n&\\makebox[3em]{10000}&\\makebox[3em]{100000}&\\makebox[3em]{1000000}\\\\\\hline\\hline\nLCG&1&1&2&3&100&1126&21486\\\\\\hline\nBBS&4&11&41&105&6750&60364&453863\\\\\\hline\nRAB&6&14&53&132&8616&68644&538605\\\\\\hline\nRSA&2044421&7107596&25926498&66659430&-&-&-\\\\\\hline\nMSRSA&41&32&243&607&37529&287388&2544693\\\\\\hline\nPG&29&55&214&533&37895&283791&2154358\\\\\\hline\nNR&4177409&27015995&416989667&2652261381&-&-&-\\\\\\hline\n\\end{tabular}\n\\caption{\\label{tab:table-name}Algorithm speed in terms of CPU cycles}\n\\end{table}\n\n\\subsection{Results}\n\nFrom the data above we can see a massive disparity in the performance of RSA and NR compared to the rest of the algorithms. RSA's inefficiency in the case is do to the large size of $e$ as a result of the values used to seed the algorithm, requiring each pass to loop a non-trivial number of times. MSRSA avoids this by using a commonly agreed upon static value of $e$, greatly reducing the runtime. The results of PG are also a bit skewed, as it uses a relatively small index of prime/primitive pairs, where the primes themselves are quite small. This becomes more evident when using the $print$ test in the repository and observing the values output by each algorithm side-by-side, as the resolution of PG's output is noticeably more limited.\n\n\\section{BRAND}\n\nWhile each of the aforementioned algorithms strives to produce a uniformly distributed set of seemingly random variables, they tend to have some shortcomings when used in applications. The range of values they produce are often limited to some {[}$0, RAND\\_MAX${)}, which may be problematic in that both the desired range size may too big or too small, or the min and max values themselves aren't ideal. If a user wants to use one of these algorithms in an applied manner for a range they control, a naive solution is often something along the lines of:\n\\[val = min + rand() \\% (max - min)\\]\nThe problem with this is it introduces a statistically detectable bias when the modulus doesn't perfectly divide into the $RAND\\_MAX$ of the $rand()$ function.\n\nAs a solution to this, we provide $brand$, a set of wrapper functions around C's implementation of $rand()$, which is fundamentally based upon LCG. With this library, the default $min$ and $max$ for the range of random values is still $0$ and $RAND\\_MAX$, however now the user can set the limits of the range, then use the wrapper functions to generate a statistically uniform distribution of random variables within the given range. \n\nThe standard flow for using $brand$ is to first seed C's built in $rand()$ function however you like; typically this is done through a call to $srand(time(NULL))$. Next, the user can use $brand$'s limit setting functions $bsetn()$, $bsetx()$, and $bsetnx()$ to define the desired range. Next the user simply calls $brand()$ as many times as they want to get the desired value, and finally when they're done using the library call $bcln()$ to clean up dynamically allocated memory. An additional function $brandd()$ is also available, which uses $brand()$ internally to generate a random value in the range {[}$0.0,1.0${)}, with the resolution of the result controlled by the limits set.\n\nWith this we now have a well functioning RNG library based on LCG in which we can control the range, but now we want to add one more piece of functionality. When it comes to human perception of randomness, people tend to apply their own biases to what they perceive as random, sometimes without even realizing it. A prime example of this is the \"shuffle\" button in any sort of music or media software. The expectation when listening to a library of music with the shuffle button enabled is that the software will cycle through the music and select the order to play songs in at random. If, for example, a user has a library of 1,000 songs being shuffled, and the RNG function happens to select the same song twice back to back before playing any other song, the user will likely be annoyed by hearing a repeat, breaking their biased perception of \"randomness\".\n\nThus $brand$ has an additional wrapper function, $brandus()$, that aims to produce a uniquely random stream of values for a given range. For a given range of size $N$, it achieves this by allocating an array of length $N$ and setting each value of the array to be the corresponding value in the range. It then generates a random value within the range, removing the minimum offset, and uses that as an index into the array to find the value to return. With that value saved, it then shifts all values beyond the output value down in the array, effectively removing it from the set of available values, and decreases the maximum range value by one. Some performance implications of this include the cache array must be $O(N)$, an $O(1)$ lookup time as the random value generated is just an index, and a $(N/2)$ average update time factor.\n\nWhile this works great for smaller ranges and always ensures a unique stream of random values for $N$ passes on a range of size $N$, it has two shortcomings. The first being that, when all $N$ values have been generated, it's behavior is that it will reset the values in the array and begin a new unique stream. This is fine, except that say in our previous example song 1000 plays at the very end in the first full pass, and the very beginning in the second full pass, then we'll have two back-to-back instances of the same object and will have again broken our notion of \"perceived randomness\". The second shortcoming is the memory footprint of this method. For any non-trivial range of values, the method will take up a substantial amount of memory as it needs to index every single value (at least initially).\n\nSome potential future work for this cached indexing approach could include an alternative cache method which only caches the most recent $X$ amount of values out of the total $N$ range, where $X << N$. Some potential issues with this include lookup failures and having to do multiple retries, however these could likely be mitigated by [placing a strict limit on the size of the local cache relative to the overall size of the range.\n\n\\section{Conclusion}\n\nDRNGs can vary widely in both the approaches they take to achieve cryptographic security and statistical randomness, and the actual performance that comes as a result. Some are much more specialized, such as RSA for asymmetric key encryption, while others are much more broad in their applications, like LCG. Beyond the algorithms themselves, ensuring statistical uniformity in a random distribution where the range or uniqueness of a value matters is surprisingly non-trivial to implement, however in applications that interface directly with users or use cases such as procedural generation, these properties can be invaluable.\n\n\\end{document}\n", "meta": {"hexsha": "698f45ba5f24b5cb00fa105969f5e1d31031a624", "size": 16828, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/paper.tex", "max_stars_repo_name": "carsonkk/drngs", "max_stars_repo_head_hexsha": "6a4b86ed0b3534cece8d0be34ecaa98856f0304e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/paper.tex", "max_issues_repo_name": "carsonkk/drngs", "max_issues_repo_head_hexsha": "6a4b86ed0b3534cece8d0be34ecaa98856f0304e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/paper.tex", "max_forks_repo_name": "carsonkk/drngs", "max_forks_repo_head_hexsha": "6a4b86ed0b3534cece8d0be34ecaa98856f0304e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 108.5677419355, "max_line_length": 1317, "alphanum_fraction": 0.7741858807, "num_tokens": 4121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118791767282, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.31609224268870323}}
{"text": "\\documentclass[a4paper]{article}\r\n\\usepackage{amsmath,amssymb,amsthm,tikz,parskip,lplfitch}\r\n\\usetikzlibrary{decorations.text,trees,positioning}\r\n\r\n\\title{Semantic Tableaux}\r\n\\author{Blat Blatnik}\r\n\\date{July, 2020}\r\n\r\n\\begin{document}\r\n\\maketitle\r\n\r\n\\tikzset{% \r\n\tl/.style={%\r\n\t\tbaseline, level distance = 2em\r\n\t}\r\n}\r\n\r\n\\section{First Order Logic (FOL)}\r\n\\begin{center}\r\n\t\\renewcommand{\\arraystretch}{2.5}\r\n\t\\begin{tabular}{cc}\r\n\t\t\\multicolumn{2}{c}{\r\n\t\t \t\\begin{tikzpicture}[l]\r\n\t\t \t\\node {$\\lnot\\lnot$ A}\r\n\t\t \t[->]\r\n\t\t \tchild {node[below]{A}};\r\n\t\t \t\\end{tikzpicture}\r\n\t\t}\r\n\t\t\\\\\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\land$ B}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{A\\\\[4]B}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\land$ B)}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{$\\lnot$A}}\r\n\t\t\tchild {node[below]{$\\lnot$B}};\r\n\t\t\\end{tikzpicture}\r\n\t\t\\\\\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\lor$ B}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{A}}\r\n\t\t\tchild {node[below]{B}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\lor$ B)}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{$\\lnot$A\\\\[4]$\\lnot$B}};\r\n\t\t\\end{tikzpicture}\r\n\t\t\\\\\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\supset$ B}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{$\\lnot$A}}\r\n\t\t\tchild {node[below]{B}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\supset$ B)}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{A\\\\[4]$\\lnot$B}};\r\n\t\t\\end{tikzpicture}\r\n\t\t\\\\\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\equiv$ B}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{A\\\\[4]B}}\r\n\t\t\tchild {node[below,align=center]{$\\lnot$A\\\\[4]$\\lnot$B}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\equiv$ B)}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{$\\lnot$A\\\\[4]B}}\r\n\t\t\tchild {node[below,align=center]{A\\\\[4]$\\lnot$B}};\r\n\t\t\\end{tikzpicture}\r\n\t\t\\\\\r\n\t\\end{tabular}\r\n\\end{center}\r\n\r\n\\vspace{2.0em}\r\n\\textbf{Closure condition}: A branch of closes if it contains both A and $\\lnot$A.\r\n\r\n\\textbf{Counter-model procedure}: Take any open branch, if P occurs at any node in the branch, assign it 1, and if $\\lnot$P occurs on any node, assign it 0.\r\n\r\n\\textbf{Designated values}: $1$\r\n\r\n\\pagebreak\r\n\r\n\\section{First Degree Entailment (FDE)}\r\n\\begin{center}\r\n\t\\renewcommand{\\arraystretch}{2.5}\r\n\t\\begin{tabular}{cccc}\r\n\t\t\\multicolumn{2}{c}{\r\n\t\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\t\\node {$\\lnot\\lnot$ A, +}\r\n\t\t\t\t[->]\r\n\t\t\t\tchild {node[below]{A, +}};\r\n\t\t\t\\end{tikzpicture}\r\n\t\t}\r\n\t\t&\r\n\t\t\\multicolumn{2}{c}{\r\n\t\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot\\lnot$ A, --}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{A, --}};\r\n\t\t\t\\end{tikzpicture}\r\n\t\t}\r\n\t\t\\\\\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\land$ B, +}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{A, +\\\\[4]B, +}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\land$ B), +}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{$\\lnot$A, +}}\r\n\t\t\tchild {node[below]{$\\lnot$B, +}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\land$ B, --}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{A, --}}\r\n\t\t\tchild {node[below]{B, --}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\land$ B), --}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{$\\lnot$A, --}}\r\n\t\t\tchild {node[below]{$\\lnot$B, --}};\r\n\t\t\\end{tikzpicture}\r\n\t\t\\\\\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\lor$ B, +}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{A, +}}\r\n\t\t\tchild {node[below]{B, +}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\lor$ B), +}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{$\\lnot$A, +\\\\[4]$\\lnot$B, +}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\lor$ B, --}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{A, --\\\\[4]B, --}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\lor$ B), --}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{$\\lnot$A, --\\\\[4]$\\lnot$B, --}};\r\n\t\t\\end{tikzpicture}\r\n\t\\end{tabular}\r\n\\end{center}\r\n\r\n\\vspace{3em}\r\n\\textbf{Closure condition}: A branch closes if it contains both A, + and A, --.\r\n\r\n\\textbf{Counter-model procedure}: Take any open branch, if P, + occurs at any node in the branch assign it P$\\rho$1, and if $\\lnot$P, + occurs on any node, assign it P$\\rho$0.\r\n\r\n\\textbf{Truth table}:\r\n\\begin{center}\r\n\t\\renewcommand{\\arraystretch}{1.2}\r\n\t\\begin{tabular}{|c|c|}\r\n\t\t\\hline\r\n\t\t$\\lnot$ & \\\\\\hline\r\n\t\t$0$ & $1$ \\\\\r\n\t\t$n$ & $n$ \\\\\r\n\t\t$b$ & $b$ \\\\\r\n\t\t$1$ & $0$ \\\\\\hline\r\n\t\\end{tabular}\r\n\t\\quad\r\n\t\\begin{tabular}{|c|cccc|}\r\n\t\t\\hline\r\n\t\t$\\land$ & $0$ & $n$ & $b$ & $1$ \\\\\\hline\r\n\t\t$0$ & $0$ & $0$ & $0$ & $0$ \\\\\r\n\t\t$n$ & $0$ & $n$ & $0$ & $n$ \\\\\r\n\t\t$b$ & $0$ & $0$ & $b$ & $b$ \\\\\r\n\t\t$1$ & $0$ & $n$ & $b$ & $1$ \\\\\\hline\r\n\t\\end{tabular}\r\n\t\\quad\r\n\t\\begin{tabular}{|c|cccc|}\r\n\t\t\\hline\r\n\t\t$\\lor$ & $0$ & $n$ & $b$ & $1$ \\\\\\hline\r\n\t\t$0$ & $0$ & $n$ & $b$ & $1$ \\\\\r\n\t\t$n$ & $n$ & $n$ & $1$ & $1$ \\\\\r\n\t\t$b$ & $b$ & $1$ & $b$ & $1$ \\\\\r\n\t\t$1$ & $1$ & $1$ & $1$ & $1$ \\\\\\hline\r\n\t\\end{tabular}\r\n\\end{center}\r\n\r\n\\textbf{Designated values}: $1, b$\r\n\r\n\\pagebreak\r\n\r\n\\section{Kleene 3-valued logic (K$_3$)}\r\n\\begin{center}\r\n\t\\renewcommand{\\arraystretch}{2.5}\r\n\t\\begin{tabular}{cccc}\r\n\t\t\\multicolumn{2}{c}{\r\n\t\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\t\\node {$\\lnot\\lnot$ A, +}\r\n\t\t\t\t[->]\r\n\t\t\t\tchild {node[below]{A, +}};\r\n\t\t\t\\end{tikzpicture}\r\n\t\t}\r\n\t\t&\r\n\t\t\\multicolumn{2}{c}{\r\n\t\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\t\\node {$\\lnot\\lnot$ A, --}\r\n\t\t\t\t[->]\r\n\t\t\t\tchild {node[below]{A, --}};\r\n\t\t\t\\end{tikzpicture}\r\n\t\t}\r\n\t\t\\\\\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\land$ B, +}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{A, +\\\\[4]B, +}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\land$ B), +}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{$\\lnot$A, +}}\r\n\t\t\tchild {node[below]{$\\lnot$B, +}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\land$ B, --}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{A, --}}\r\n\t\t\tchild {node[below]{B, --}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\land$ B), --}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{$\\lnot$A, --}}\r\n\t\t\tchild {node[below]{$\\lnot$B, --}};\r\n\t\t\\end{tikzpicture}\r\n\t\t\\\\\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\lor$ B, +}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{A, +}}\r\n\t\t\tchild {node[below]{B, +}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\lor$ B), +}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{$\\lnot$A, +\\\\[4]$\\lnot$B, +}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\lor$ B, --}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{A, --\\\\[4]B, --}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\lor$ B), --}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{$\\lnot$A, --\\\\[4]$\\lnot$B, --}};\r\n\t\t\\end{tikzpicture}\r\n\t\t\\\\\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\supset$ B, +}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{$\\lnot$A, +}}\r\n\t\t\tchild {node[below]{B, +}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\supset$ B), +}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{A, +\\\\[4]$\\lnot$B, +}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\supset$ B, --}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{$\\lnot$A, --\\\\[4]B, --}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\supset$ B), --}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{A, --\\\\[4]$\\lnot$B, --}};\r\n\t\t\\end{tikzpicture}\r\n\t\\end{tabular}\r\n\\end{center}\r\n\r\n\\vspace{3em}\r\n\\textbf{Closure condition}: A branch closes if it contains both A, + and A, -- or both A, + and $\\lnot$A, +.\r\n\r\n\\textbf{Counter-model procedure}: Take any open branch, if P, + occurs at any node in the branch assign it P$\\rho$1, and if $\\lnot$P, + occurs on any node, assign it P$\\rho$0.\r\n\r\n\\textbf{Truth table}:\r\n\\begin{center}\r\n\t\\renewcommand{\\arraystretch}{1.2}\r\n\t\\begin{tabular}{|c|c|}\r\n\t\t\\hline\r\n\t\t$\\lnot$ & \\\\\\hline\r\n\t\t$0$ & $1$ \\\\\r\n\t\t$i$ & $i$ \\\\\r\n\t\t$1$ & $0$ \\\\\\hline\r\n\t\\end{tabular}\r\n\t\\quad\r\n\t\\begin{tabular}{|c|ccc|}\r\n\t\t\\hline\r\n\t\t$\\land$ & $0$ & $i$ & $1$ \\\\\\hline\r\n\t\t$0$ & $0$ & $0$ & $0$ \\\\\r\n\t\t$i$ & $0$ & $i$ & $i$ \\\\\r\n\t\t$1$ & $0$ & $i$ & $1$ \\\\\\hline\r\n\t\\end{tabular}\r\n\t\\quad\r\n\t\\begin{tabular}{|c|ccc|}\r\n\t\t\\hline\r\n\t\t$\\lor$ & $0$ & $i$ & $1$ \\\\\\hline\r\n\t\t$0$ & $0$ & $i$ & $1$ \\\\\r\n\t\t$i$ & $i$ & $i$ & $1$ \\\\\r\n\t\t$1$ & $1$ & $1$ & $1$ \\\\\\hline\r\n\t\\end{tabular}\r\n\t\\quad\r\n\t\\begin{tabular}{|c|ccc|}\r\n\t\t\\hline\r\n\t\t$\\supset$ & $0$ & $i$ & $1$ \\\\\\hline\r\n\t\t$0$ & $1$ & $1$ & $1$ \\\\\r\n\t\t$i$ & $i$ & $i$ & $1$ \\\\\r\n\t\t$1$ & $0$ & $i$ & $1$ \\\\\\hline\r\n\t\\end{tabular}\r\n\\end{center}\r\n\r\n\\textbf{Designated values}: $1$\r\n\r\n\\pagebreak\r\n\r\n\\section{{\\L}ukasiewicz 3-valued logic (\\L$_3$)}\r\n\\begin{center}\r\n\t\\renewcommand{\\arraystretch}{2.5}\r\n\t\\begin{tabular}{cccc}\r\n\t\t\\multicolumn{2}{c}{\r\n\t\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\t\\node {$\\lnot\\lnot$ A, +}\r\n\t\t\t\t[->]\r\n\t\t\t\tchild {node[below]{A, +}};\r\n\t\t\t\\end{tikzpicture}\r\n\t\t}\r\n\t\t&\r\n\t\t\\multicolumn{2}{c}{\r\n\t\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\t\\node {$\\lnot\\lnot$ A, --}\r\n\t\t\t\t[->]\r\n\t\t\t\tchild {node[below]{A, --}};\r\n\t\t\t\\end{tikzpicture}\r\n\t\t}\r\n\t\t\\\\\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\land$ B, +}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{A, +\\\\[4]B, +}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\land$ B), +}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{$\\lnot$A, +}}\r\n\t\t\tchild {node[below]{$\\lnot$B, +}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\land$ B, --}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{A, --}}\r\n\t\t\tchild {node[below]{B, --}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\land$ B), --}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{$\\lnot$A, --}}\r\n\t\t\tchild {node[below]{$\\lnot$B, --}};\r\n\t\t\\end{tikzpicture}\r\n\t\t\\\\\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\lor$ B, +}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{A, +}}\r\n\t\t\tchild {node[below]{B, +}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\lor$ B), +}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{$\\lnot$A, +\\\\[4]$\\lnot$B, +}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\lor$ B, --}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{A, --\\\\[4]B, --}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\lor$ B), --}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{$\\lnot$A, --\\\\[4]$\\lnot$B, --}};\r\n\t\t\\end{tikzpicture}\r\n\t\t\\\\\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\supset$ B, +}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{$\\lnot$A, +}}\r\n\t\t\tchild {node[below]{B, +}}\r\n\t\t\tchild {node[below,align=center]{A $\\lor$ $\\lnot$A, -\\\\[4]B $\\lor$ $\\lnot$B, -}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\supset$ B), +}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{A, +\\\\[4]$\\lnot$B, +}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\supset$ B, --}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{A, +\\\\[4]B, --}}\r\n\t\t\tchild {node[below,align=center]{$\\lnot$A, --\\\\[4]$\\lnot$B, +}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\supset$ B), --}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{A, --}}\r\n\t\t\tchild {node[below]{$\\lnot$B, --}};\r\n\t\t\\end{tikzpicture}\r\n\t\t\\\\\r\n\t\\end{tabular}\r\n\\end{center}\r\n\r\n\\vspace{3em}\r\n\\textbf{Closure condition}: A branch closes if it contains both A, + and A, -- or both A, + and $\\lnot$A, +.\r\n\r\n\\textbf{Counter-model procedure}: Take any open branch, if P, + occurs at any node in the branch assign it P$\\rho$1, and if $\\lnot$P, + occurs on any node, assign it P$\\rho$0.\r\n\r\n\\textbf{Designated values}: $1$\r\n\r\n\\textbf{Truth table}:\r\n\\begin{center}\r\n\t\\renewcommand{\\arraystretch}{1.2}\r\n\t\\begin{tabular}{|c|c|}\r\n\t\t\\hline\r\n\t\t$\\lnot$ & \\\\\\hline\r\n\t\t$0$ & $1$ \\\\\r\n\t\t$i$ & $i$ \\\\\r\n\t\t$1$ & $0$ \\\\\\hline\r\n\t\\end{tabular}\r\n\t\\quad\r\n\t\\begin{tabular}{|c|ccc|}\r\n\t\t\\hline\r\n\t\t$\\land$ & $0$ & $i$ & $1$ \\\\\\hline\r\n\t\t$0$ & $0$ & $0$ & $0$ \\\\\r\n\t\t$i$ & $0$ & $i$ & $i$ \\\\\r\n\t\t$1$ & $0$ & $i$ & $1$ \\\\\\hline\r\n\t\\end{tabular}\r\n\t\\quad\r\n\t\\begin{tabular}{|c|ccc|}\r\n\t\t\\hline\r\n\t\t$\\lor$ & $0$ & $i$ & $1$ \\\\\\hline\r\n\t\t$0$ & $0$ & $i$ & $1$ \\\\\r\n\t\t$i$ & $i$ & $i$ & $1$ \\\\\r\n\t\t$1$ & $1$ & $1$ & $1$ \\\\\\hline\r\n\t\\end{tabular}\r\n\t\\quad\r\n\t\\begin{tabular}{|c|ccc|}\r\n\t\t\\hline\r\n\t\t$\\supset$ & $0$ & $i$ & $1$ \\\\\\hline\r\n\t\t$0$ & $1$ & $1$ & $1$ \\\\\r\n\t\t$i$ & $i$ & $1$ & $1$ \\\\\r\n\t\t$1$ & $0$ & $i$ & $1$ \\\\\\hline\r\n\t\\end{tabular}\r\n\\end{center}\r\n\r\n\\pagebreak\r\n\r\n\\section{Logic of Paradox (LP)}\r\n\\begin{center}\r\n\t\\renewcommand{\\arraystretch}{2.5}\r\n\t\\begin{tabular}{cccc}\r\n\t\t\\multicolumn{2}{c}{\r\n\t\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\t\\node {$\\lnot\\lnot$ A, +}\r\n\t\t\t\t[->]\r\n\t\t\t\tchild {node[below]{A, +}};\r\n\t\t\t\\end{tikzpicture}\r\n\t\t}\r\n\t\t&\r\n\t\t\\multicolumn{2}{c}{\r\n\t\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\t\\node {$\\lnot\\lnot$ A, --}\r\n\t\t\t\t[->]\r\n\t\t\t\tchild {node[below]{A, --}};\r\n\t\t\t\\end{tikzpicture}\r\n\t\t}\r\n\t\t\\\\\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\land$ B, +}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{A, +\\\\[4]B, +}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\land$ B), +}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{$\\lnot$A, +}}\r\n\t\t\tchild {node[below]{$\\lnot$B, +}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\land$ B, --}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{A, --}}\r\n\t\t\tchild {node[below]{B, --}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\land$ B), --}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{$\\lnot$A, --}}\r\n\t\t\tchild {node[below]{$\\lnot$B, --}};\r\n\t\t\\end{tikzpicture}\r\n\t\t\\\\\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\lor$ B, +}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{A, +}}\r\n\t\t\tchild {node[below]{B, +}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\lor$ B), +}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{$\\lnot$A, +\\\\[4]$\\lnot$B, +}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\lor$ B, --}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{A, --\\\\[4]B, --}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\lor$ B), --}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{$\\lnot$A, --\\\\[4]$\\lnot$B, --}};\r\n\t\t\\end{tikzpicture}\r\n\t\t\\\\\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\supset$ B, +}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{$\\lnot$A, +}}\r\n\t\t\tchild {node[below]{B, +}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\supset$ B), +}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{A, +\\\\[4]$\\lnot$B, +}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\supset$ B, --}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{$\\lnot$A, --\\\\[4]B, --}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\supset$ B), --}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{A, --\\\\[4]$\\lnot$B, --}};\r\n\t\t\\end{tikzpicture}\r\n\t\t\\\\\r\n\t\\end{tabular}\r\n\\end{center}\r\n\r\n\\vspace{3em}\r\n\\textbf{Closure condition}: A branch closes if it contains both A, + and A, -- or both A, -- and $\\lnot$A, --.\r\n\r\n\\textbf{Counter-model procedure}: Take any open branch, if P, -- \\emph{does not} occur on any node of the branch assign it P$\\rho$1, and if $\\lnot$P, -- \\emph{does not} occur on any node, assign it P$\\rho$0.\r\n\r\n\\textbf{Designated values}: $1, i$\r\n\r\n\\textbf{Truth table}:\r\n\\begin{center}\r\n\t\\renewcommand{\\arraystretch}{1.2}\r\n\t\\begin{tabular}{|c|c|}\r\n\t\t\\hline\r\n\t\t$\\lnot$ & \\\\\\hline\r\n\t\t$0$ & $1$ \\\\\r\n\t\t$i$ & $i$ \\\\\r\n\t\t$1$ & $0$ \\\\\\hline\r\n\t\\end{tabular}\r\n\t\\quad\r\n\t\\begin{tabular}{|c|ccc|}\r\n\t\t\\hline\r\n\t\t$\\land$ & $0$ & $i$ & $1$ \\\\\\hline\r\n\t\t$0$ & $0$ & $0$ & $0$ \\\\\r\n\t\t$i$ & $0$ & $i$ & $i$ \\\\\r\n\t\t$1$ & $0$ & $i$ & $1$ \\\\\\hline\r\n\t\\end{tabular}\r\n\t\\quad\r\n\t\\begin{tabular}{|c|ccc|}\r\n\t\t\\hline\r\n\t\t$\\lor$ & $0$ & $i$ & $1$ \\\\\\hline\r\n\t\t$0$ & $0$ & $i$ & $1$ \\\\\r\n\t\t$i$ & $i$ & $i$ & $1$ \\\\\r\n\t\t$1$ & $1$ & $1$ & $1$ \\\\\\hline\r\n\t\\end{tabular}\r\n\t\\quad\r\n\t\\begin{tabular}{|c|ccc|}\r\n\t\t\\hline\r\n\t\t$\\supset$ & $0$ & $i$ & $1$ \\\\\\hline\r\n\t\t$0$ & $1$ & $1$ & $1$ \\\\\r\n\t\t$i$ & $i$ & $i$ & $1$ \\\\\r\n\t\t$1$ & $0$ & $i$ & $1$ \\\\\\hline\r\n\t\\end{tabular}\r\n\\end{center}\r\n\r\n\\pagebreak\r\n\r\n\\section{Mix 3-valued logic (RM$_3$)}\r\n\\begin{center}\r\n\t\\renewcommand{\\arraystretch}{2.5}\r\n\t\\begin{tabular}{cccc}\r\n\t\t\\multicolumn{2}{c}{\r\n\t\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\t\\node {$\\lnot\\lnot$ A, +}\r\n\t\t\t\t[->]\r\n\t\t\t\tchild {node[below]{A, +}};\r\n\t\t\t\\end{tikzpicture}\r\n\t\t}\r\n\t\t&\r\n\t\t\\multicolumn{2}{c}{\r\n\t\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\t\\node {$\\lnot\\lnot$ A, --}\r\n\t\t\t\t[->]\r\n\t\t\t\tchild {node[below]{A, --}};\r\n\t\t\t\\end{tikzpicture}\r\n\t\t}\r\n\t\t\\\\\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\land$ B, +}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{A, +\\\\[4]B, +}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\land$ B), +}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{$\\lnot$A, +}}\r\n\t\t\tchild {node[below]{$\\lnot$B, +}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\land$ B, --}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{A, --}}\r\n\t\t\tchild {node[below]{B, --}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\land$ B), --}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{$\\lnot$A, --}}\r\n\t\t\tchild {node[below]{$\\lnot$B, --}};\r\n\t\t\\end{tikzpicture}\r\n\t\t\\\\\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\lor$ B, +}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{A, +}}\r\n\t\t\tchild {node[below]{B, +}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\lor$ B), +}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{$\\lnot$A, +\\\\[4]$\\lnot$B, +}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\lor$ B, --}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{A, --\\\\[4]B, --}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\lor$ B), --}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{$\\lnot$A, --\\\\[4]$\\lnot$B, --}};\r\n\t\t\\end{tikzpicture}\r\n\t\t\\\\\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\supset$ B, +}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{A, --}}\r\n\t\t\tchild {node[below]{$\\lnot$B, --}}\r\n\t\t\tchild {node[below,align=center]{A $\\land$ $\\lnot$A, +\\\\[4]B $\\land$ $\\lnot$B, +}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\supset$ B), +}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{A, +\\\\[4]$\\lnot$B, +}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\supset$ B, --}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{A, +\\\\[4]B, --}}\r\n\t\t\tchild {node[below,align=center]{$\\lnot$A, --\\\\[4]$\\lnot$B, +}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\supset$ B), --}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{A, --}}\r\n\t\t\tchild {node[below]{$\\lnot$B, --}};\r\n\t\t\\end{tikzpicture}\r\n\t\t\\\\\r\n\t\\end{tabular}\r\n\\end{center}\r\n\r\n\\vspace{3em}\r\n\\textbf{Closure condition}: A branch closes if it contains both A, + and A, -- or both A, -- and $\\lnot$A, --.\r\n\r\n\\textbf{Counter-model procedure}: Take any open branch, if P, -- \\emph{does not} occur on any node of the branch assign it P$\\rho$1, and if $\\lnot$P, -- \\emph{does not} occur on any node, assign it P$\\rho$0.\r\n\r\n\\textbf{Designated values}: $1, i$\r\n\r\n\\textbf{Truth table}:\r\n\\begin{center}\r\n\t\\renewcommand{\\arraystretch}{1.2}\r\n\t\\begin{tabular}{|c|c|}\r\n\t\t\\hline\r\n\t\t$\\lnot$ & \\\\\\hline\r\n\t\t$0$ & $1$ \\\\\r\n\t\t$i$ & $i$ \\\\\r\n\t\t$1$ & $0$ \\\\\\hline\r\n\t\\end{tabular}\r\n\t\\quad\r\n\t\\begin{tabular}{|c|ccc|}\r\n\t\t\\hline\r\n\t\t$\\land$ & $0$ & $i$ & $1$ \\\\\\hline\r\n\t\t$0$ & $0$ & $0$ & $0$ \\\\\r\n\t\t$i$ & $0$ & $i$ & $i$ \\\\\r\n\t\t$1$ & $0$ & $i$ & $1$ \\\\\\hline\r\n\t\\end{tabular}\r\n\t\\quad\r\n\t\\begin{tabular}{|c|ccc|}\r\n\t\t\\hline\r\n\t\t$\\lor$ & $0$ & $i$ & $1$ \\\\\\hline\r\n\t\t$0$ & $0$ & $i$ & $1$ \\\\\r\n\t\t$i$ & $i$ & $i$ & $1$ \\\\\r\n\t\t$1$ & $1$ & $1$ & $1$ \\\\\\hline\r\n\t\\end{tabular}\r\n\t\\quad\r\n\t\\begin{tabular}{|c|ccc|}\r\n\t\t\\hline\r\n\t\t$\\supset$ & $0$ & $i$ & $1$ \\\\\\hline\r\n\t\t$0$ & $1$ & $1$ & $1$ \\\\\r\n\t\t$i$ & $0$ & $i$ & $1$ \\\\\r\n\t\t$1$ & $0$ & $0$ & $1$ \\\\\\hline\r\n\t\\end{tabular}\r\n\\end{center}\r\n\r\n\\pagebreak\r\n\r\n\\section{Basic Modal Logic}\r\n\\begin{center}\r\n\t\\renewcommand{\\arraystretch}{2.5}\r\n\t\\begin{tabular}{cccc}\r\n\t\t\\multicolumn{4}{c}{\r\n\t\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\t\\node {$\\lnot\\lnot$ A, $i$}\r\n\t\t\t\t[->]\r\n\t\t\t\tchild {node[below]{A, $i$}};\r\n\t\t\t\\end{tikzpicture}\r\n\t\t}\r\n\t\t\\\\\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\land$ B, $i$}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{A, $i$\\\\[4] B, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\land$ B), $i$}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{$\\lnot$A, $i$}}\r\n\t\t\tchild {node[below]{$\\lnot$B, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\lor$ B, $i$}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{A, $i$}}\r\n\t\t\tchild {node[below]{B, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\lor$ B), $i$}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{$\\lnot$A, $i$\\\\[4] $\\lnot$B, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t\\\\\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\supset$ B, $i$}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{$\\lnot$A, $i$}}\r\n\t\t\tchild {node[below]{B, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\supset$ B), $i$}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{A, $i$\\\\[4] $\\lnot$B, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\equiv$ B, $i$}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{A, $i$\\\\[4] B, $i$}}\r\n\t\t\tchild {node[below,align=center]{$\\lnot$A, $i$\\\\[4] $\\lnot$B, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\equiv$ B), $i$}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{$\\lnot$A, $i$\\\\[4] B, $i$}}\r\n\t\t\tchild {node[below,align=center]{A, $i$\\\\[4] $\\lnot$B, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t\\\\\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node[align=center] {$\\Box$ A, $i$\\\\[4]$i$ r $j$}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{A, $j$\\\\[4](every $j$)}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot \\Box$ A, $i$}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{$\\Diamond \\lnot$ A, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\Diamond$ A, $i$}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{$i$ r $j$\\\\[4] A, $j$\\\\[4](new $j$)}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot \\Diamond$ A, $i$}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{$\\Box \\lnot$ A, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\\end{tabular}\r\n\\end{center}\r\n\r\n\\vspace{2.5em}\r\n\\textbf{Closure condition}: A branch of closes if it for some $i$, A, $i$ and $\\lnot$ A, $i$ occur on the same branch.\r\n\r\n\\textbf{Counter-model procedure}: For each $i$ that occurs the word $w_i$ exists. If $i$ r $j$ occurs on the branch then $w_i$ R $w_j$. If P, $i$ occurs on the branch then $v_{w_i}$(P) = 1, if $\\lnot$ P, i occurs on the branch then $v_{w_i}$(P) = 0. \r\n\r\n\\textbf{Extensions}\r\n\\begin{description}\r\n\t\\item[$\\rho$] reflexivity: for all $w$, $wRw$\r\n\t\\item[$\\sigma$] symmetry: for all $w_1$, $w_2$, if $w_1Rw_2$, then $w_2Rw_1$\r\n\t\\item[$\\tau$] transitivity: for all $w_1$, $w_2$, $w_3$, if $w_1Rw_2$ and $w_2Rw_3$, then $w_1Rw_3$\r\n\t\\item[$\\eta$] extendability: for all $w_1$, there is a $w_2$ such that $w_1Rw_2$\r\n\\end{description}\r\n\r\n\\section{Tense Logic}\r\n\\begin{center}\r\n\t\\renewcommand{\\arraystretch}{2.5}\r\n\t\\begin{tabular}{cccc}\r\n\t\t\\multicolumn{4}{c}{\r\n\t\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\t\\node {$\\lnot\\lnot$ A, $i$}\r\n\t\t\t\t[->]\r\n\t\t\t\tchild {node[below]{A, $i$}};\r\n\t\t\t\\end{tikzpicture}\r\n\t\t}\r\n\t\t\\\\\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\land$ B, $i$}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{A, $i$ \\\\[4] B, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\land$ B), $i$}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{$\\lnot$A, $i$}}\r\n\t\t\tchild {node[below]{$\\lnot$B, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\lor$ B, $i$}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{A, $i$}}\r\n\t\t\tchild {node[below]{B, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\lor$ B), $i$}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{$\\lnot$A, $i$\\\\[4] $\\lnot$B, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t\\\\\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\supset$ B, $i$}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{$\\lnot$A, $i$}}\r\n\t\t\tchild {node[below]{B, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\supset$ B), $i$}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{A, $i$\\\\[4] $\\lnot$B, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {A $\\equiv$ B, $i$}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{A, $i$\\\\[4] B, $i$}}\r\n\t\t\tchild {node[below,align=center]{$\\lnot$A, $i$\\\\[4] $\\lnot$B, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$(A $\\equiv$ B), $i$}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{$\\lnot$A, $i$\\\\[4] B, $i$}}\r\n\t\t\tchild {node[below,align=center]{A, $i$\\\\[4] $\\lnot$B, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t\\\\\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node[align=center] {[F]A, $i$\\\\[4]$i$ r $j$}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{A, $j$\\\\[4](every $j$)}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$[F]A, $i$}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{$\\langle$F$\\rangle$$\\lnot$ A, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\langle$F$\\rangle$A, $i$}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{$i$ r $j$\\\\[4] A, $j$\\\\[4] (new $j$)}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$$\\langle$F$\\rangle$A, $i$}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{[F]$\\lnot$ A, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t\\\\\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node[align=center] {[P]A, $i$\\\\[4]$j$ r $i$}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{A, $j$\\\\[4] (every $j$)}};\r\n\t\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$[P]A, $i$}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{$\\langle$P$\\rangle$$\\lnot$ A, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\langle$P$\\rangle$A, $i$}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below,align=center]{$j$ r $i$\\\\[4] A, $j$\\\\[4] (new $j$)}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot$$\\langle$P$\\rangle$A, $i$}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{[P]$\\lnot$ A, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\\end{tabular}\r\n\\end{center}\r\n\r\n\\vspace{3em}\r\n\\textbf{Closure condition}: A branch of closes if it for some $i$, A, $i$ and $\\lnot$ A, $i$ occur on the same branch.\r\n\r\n\\textbf{Counter-model procedure}: For each $i$ that occurs the word $w_i$ exists. If $i$ r $j$ occurs on the branch then $w_i$ R $w_j$. If P, $i$ occurs on the branch then $v_{w_i}$(P) = 1, if $\\lnot$ P, i occurs on the branch then $v_{w_i}$(P) = 0. If there are lines of the form $i = j$, $j = k$, $...$, we only chose one of them, like $i$, and ignore the others.\r\n\r\n\\textbf{Extensions}\r\n\\begin{description}\r\n\t\\item[$\\delta$] denseness: if $iRj$ then for some $k$, $iRk$ and $kRj$ \r\n\t\\item[$\\phi$] forward convergence: if $iRj$ and $iRk$ then $jRk$ or $j = k$ or $kRj$\r\n\t\\item[$\\beta$] backward convergence: if $jRi$ and $kRi$ then $jRk$ or $j = k$ or $kRj$\r\n\\end{description}\r\n\r\n\\pagebreak\r\n\r\n\\section{First Order Modal Logic}\r\n\r\n\\begin{center}\r\n\t\\renewcommand{\\arraystretch}{2.5}\r\n\t\\begin{tabular}{cccc}\r\n\t\t\t\t\\multicolumn{4}{c}{\r\n\t\t\t\\begin{tikzpicture}[l]\r\n\t\t\t\\node {$\\lnot\\lnot$ A, $i$}\r\n\t\t\t[->]\r\n\t\t\tchild {node[below]{A, $i$}};\r\n\t\t\t\\end{tikzpicture}\r\n\t\t}\r\n\t\t\\\\\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\\node {A $\\land$ B, $i$}\r\n\t\t[->]\r\n\t\tchild {node[below,align=center]{A, $i$\\\\[4] B, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\\node {$\\lnot$(A $\\land$ B), $i$}\r\n\t\t[->]\r\n\t\tchild {node[below]{$\\lnot$A, $i$}}\r\n\t\tchild {node[below]{$\\lnot$B, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\\node {A $\\lor$ B, $i$}\r\n\t\t[->]\r\n\t\tchild {node[below]{A, $i$}}\r\n\t\tchild {node[below]{B, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\\node {$\\lnot$(A $\\lor$ B), $i$}\r\n\t\t[->]\r\n\t\tchild {node[below,align=center]{$\\lnot$A, $i$\\\\[4] $\\lnot$B, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t\\\\\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\\node {A $\\supset$ B, $i$}\r\n\t\t[->]\r\n\t\tchild {node[below]{$\\lnot$A, $i$}}\r\n\t\tchild {node[below]{B, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\\node {$\\lnot$(A $\\supset$ B), $i$}\r\n\t\t[->]\r\n\t\tchild {node[below,align=center]{A, $i$\\\\[4] $\\lnot$B, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\\node {A $\\equiv$ B, $i$}\r\n\t\t[->]\r\n\t\tchild {node[below,align=center]{A, $i$\\\\[4] B, $i$}}\r\n\t\tchild {node[below,align=center]{$\\lnot$A, $i$\\\\[4] $\\lnot$B, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\\node {$\\lnot$(A $\\equiv$ B), $i$}\r\n\t\t[->]\r\n\t\tchild {node[below,align=center]{$\\lnot$A, $i$\\\\[4] B, $i$}}\r\n\t\tchild {node[below,align=center]{A, $i$\\\\[4] $\\lnot$B, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t\\\\\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\\node[align=center] {$\\Box$ A, $i$\\\\[4]$i$ r $j$}\r\n\t\t[->]\r\n\t\tchild {node[below,align=center]{A, $j$\\\\[4](every $j$)}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\\node {$\\lnot \\Box$ A, $i$}\r\n\t\t[->]\r\n\t\tchild {node[below]{$\\Diamond \\lnot$ A, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\\node {$\\Diamond$ A, $i$}\r\n\t\t[->]\r\n\t\tchild {node[below,align=center]{$i$ r $j$\\\\[4] A, $j$\\\\[4](new $j$)}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\\node {$\\lnot \\Diamond$ A, $i$}\r\n\t\t[->]\r\n\t\tchild {node[below]{$\\Box \\lnot$ A, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t\\\\\r\n\t\t\\multicolumn{4}{c}{\\textbf{Variable Domain}}\r\n\t\t\\\\\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\\node {$\\forall x$ A, $i$}\r\n\t\t[->]\r\n\t\tchild {node[below]{$A_x(a)$, $i$}}\r\n\t\tchild {node[below,align=center]{$\\lnot$ $\\mathfrak{E}a$, $i$\\\\[4](old $a$ if possible)}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\\node {$\\lnot \\forall x$ A, $i$}\r\n\t\t[->]\r\n\t\tchild {node[below]{$\\exists x$ $\\lnot$A, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\\node {$\\exists x$ A, $i$}\r\n\t\t[->]\r\n\t\tchild {node[align=center,below]{$\\mathfrak{E}a$, $i$\\\\[4]$A_x(a)$, $i$\\\\[4](new $a$)}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\\node {$\\lnot \\exists x$ A, $i$}\r\n\t\t[->]\r\n\t\tchild {node[below]{$\\forall x$ $\\lnot$A, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t\\\\\r\n\t\t\\multicolumn{4}{c}{\\textbf{Constant Domain}}\r\n\t\t\\\\\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\\node {$\\forall x$ A, $i$}\r\n\t\t[->]\r\n\t\tchild {node[align=center, below]{$A_x(a)$, $i$\\\\[4](old $a$ if possible)}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\\node {$\\lnot \\forall x$ A, $i$}\r\n\t\t[->]\r\n\t\tchild {node[below]{$\\exists x$ $\\lnot$A, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\\node {$\\exists x$ A, $i$}\r\n\t\t[->]\r\n\t\tchild {node[align=center, below]{$A_x(a)$, $i$\\\\[4](new $a$)}};\r\n\t\t\\end{tikzpicture}\r\n\t\t&\r\n\t\t\\begin{tikzpicture}[l]\r\n\t\t\\node {$\\lnot \\exists x$ A, $i$}\r\n\t\t[->]\r\n\t\tchild {node[below]{$\\forall x$ $\\lnot$A, $i$}};\r\n\t\t\\end{tikzpicture}\r\n\t\\end{tabular}\r\n\\end{center}\r\n\r\n\\textbf{Counter-models}:\r\nNeed to define:\r\n\\begin{itemize}\r\n\t\\item which objects exist in which worlds: e.g. $D(w_1) = \\lbrace \\partial_a, \\partial_b \\rbrace$\r\n\t\\item which predicates hold for which objects: e.g. $v_{w_1}(P) = \\lbrace \\partial_c \\rbrace$\r\n\\end{itemize}\r\n\r\n\\pagebreak\r\n\r\n\\section{Fuzzy Logic}\r\n\r\n\\begin{align*}\r\n\t\\lnot x   &= 1 - x\\\\\r\n\tx \\land y &= \\min(x, y)\\\\\r\n\tx \\lor y  &= \\max(x, y)\\\\\r\n\tx \\lif y  &= \\min(1, 1 - x + y)\r\n\\end{align*}\r\n\r\n\\textbf{Designated values}:\r\n$A \\models_{\\textrm{\\L}_{0.5}}$ if $v(A) \\geq 0.5$ then $v(B) \\geq 0.5$\\\\\r\nSpecial case: \\L$_{\\aleph}$ - the only designated value is 1.\r\n\r\n\\section{Default Logic}\r\n\r\n\\[\r\n\t\\beta = \\frac{\\phi : \\psi_1, ..., \\psi_n}{\\chi}\r\n\t\\textrm{ \\quad for example \\quad }\r\n\t\\frac{bird(X) : flies(X)}{flies(X)}\r\n\\]\r\n\r\nwhere:\r\n\\begin{description}\r\n\t\\item $pre(\\delta) = \\phi$ (the prerequisites of $\\delta$)\r\n\t\\item $just(\\delta) = \\lbrace \\psi_1, ..., \\psi_n \\rbrace$ (the justification of $\\delta$)\r\n\t\\item $cons(\\delta) = \\chi$ (the consequence of $\\delta$)\r\n\\end{description}\r\n\r\n\\subsection{Processes}\r\n\r\n\\begin{description}\r\n\t\\item $\\prod = (\\delta_0, \\delta_1, ...)$ \\quad can also be empty: $()$\r\n\t\\item $Th(X) = $ all formulas that can be deduced from $X$.\r\n\t\\item $In(\\prod) = Th(M)$, where $M = W \\cup \\lbrace\\, cons(\\delta) \\;|\\; \\delta \\in \\prod \\,\\rbrace$\r\n\t\\item $Out(\\prod) = Th(N)$, where $N = \\lbrace\\, \\lnot just(\\delta) \\;|\\; \\delta \\in \\prod \\,\\rbrace$\r\n\t\\item $\\prod$ is \\emph{closed} iff every $\\delta \\in D$ that is applicable to $In(\\prod)$ is also in $\\prod$.\r\n\t\\item $\\prod$ is \\emph{successful} iff $In(\\prod) \\cap Out(\\prod) = \\emptyset$\r\n\t\\item[Extensions] A set of formulas $E$ is an extension of the default theory $T$ iff there is some closed and successful process $\\prod$ of $T$ such that $E = In(\\prod)$\r\n\t\\item[Skeptical consequence] $(W, D) \\vdash_s \\phi$ iff $\\phi$ is in all extensions of $(W, D)$.\r\n\t\\item[Credulous consequence] $(W, D) \\vdash_c \\phi$ iff $\\phi$ is in at least one extension of $(W, D)$.\r\n\\end{description}\r\n\r\n\\section{Soundness and Completeness}\r\n\r\n\\subsection{Propositional Logic}\r\n\r\n$\\Sigma \\models A$ iff for all valuations $v$, for all $B \\in \\Sigma$, $v(B) = 1$, then $v(A) = 1$.\r\n\r\n$\\Sigma \\vdash A$ iff there is a closed tree whose initial list comprises the members of $\\Sigma$ and the negation of $A$.\r\n\r\n\\begin{description}\r\n\t\\item[Faithful] A valuation $v$ is \\emph{faithful} to branch $b$ iff for every formula $D$ that occurs on $b$, $v(D) = 1$.\r\n\t\\item[Induced] A valuation $v$ is \\emph{induced} by branch $b$, iff for every propositional parameter $p$ that occurs on $b$, $v(p) = 1$ iff $p$ is a node on $b$, and $v(p) = 0$ iff $\\lnot p$ is a node on $b$.\r\n\t\\item[Soundness lemma] If $v$ is \\emph{faithful} to a branch $b$, and a tableau rule is applied to $b$, then $v$ is faithful to at least \\emph{one} of of the branches generated by the application of the rule.\r\n\t\\item[Completeness lemma] If branch $b$ is \\emph{complete} and \\emph{open}, and if $v$ is the valuation \\emph{induced} by $b$, then for all formulas $D$: if $D$ is on $b$, then $v(D) = 1$, and if $\\lnot D$ is on $b$, then $v(D) = 0$. \r\n\\end{description}\r\n\r\n\\subsection{Modal Logic}\r\n\r\nBasic modal logic, extensions $K_{\\rho}$, $K_{\\sigma}$, $K_{\\tau}$, $K_{\\eta}$, and any combination of extensions are all sound \\emph{and} complete.\r\n\r\n$\\Sigma \\models A$ iff for all valuations $v$, for all $B \\in \\Sigma$, $v(B) = 1$, then $v(A) = 1$.\r\n\r\n$\\Sigma \\vdash A$ iff there is a closed tree whose initial list comprises the members of $\\Sigma$ and the negation of $A$.\r\n\r\n\\begin{description}\r\n\t\r\n\t\\item[Faithful] An interpretation $I = \\langle W, R, v \\rangle$ is \\emph{faithful} to branch $b$ iff there is a map $f$ from $\\mathbb{N}$ to $W$ such that:\r\n\t\\begin{itemize}\r\n\t\t\\item For every node $D, i$ on $b$, $D$ is true at world $f(i)$ in $I$.\r\n\t\t\\item If $i$ r $j$ is on $b$, then $f(i)Rf(j)$ is in $R$.\r\n\t\\end{itemize}\r\n\r\n\t\\item[Induced]  If branch $b$ is \\emph{complete} and \\emph{open}, $I = \\langle W, R, v \\rangle$ is \\emph{induced} by $b$ iff:\r\n\t\\begin{itemize}\r\n\t\t\\item $W$ = the set of all worlds $w_i$ such that $i$ appears on b.\r\n\t\t\\item $w_iRw_j$ iff $i$ r $j$ occurs on b.\r\n\t\t\\item If $p, i$ occurs on $b$, then $v_{w_i}(p) = 1$, and if $\\lnot p, i$ occurs on  $b$, then $v_{w_i}(p) = 0$.\r\n\t\\end{itemize}\r\n\t\r\n\t\\item[Soundness lemma] If $I = \\langle W, R, v \\rangle$ is \\emph{faithful} to branch $b$, and a tableau rule is applied to $b$, then $I$ is faithful to at least \\emph{one} of of the branches generated by the application of the rule.\r\n\t\r\n\t\\item[Completeness lemma] If branch $b$ is \\emph{complete} and \\emph{open}, and $I = \\langle W, R, v \\rangle$ is \\emph{induced} by $b$, then for all formulas $D$ and for all $i$: if $D, i$ is on $b$, then $v_{w_i}(D) = 1$, and if $\\lnot D, i$ is on $b$, then $v_{w_i}(D) = 0$. \r\n\\end{description}\r\n\r\n\\end{document}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "2b59eda37a7b317baf643bd47bda0d2940b558d1", "size": 35036, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "logic-notes.tex", "max_stars_repo_name": "blat-blatnik/Logic-Notes", "max_stars_repo_head_hexsha": "6fc2ed1d44e12e7ecea87243f291968c51cbed1e", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "logic-notes.tex", "max_issues_repo_name": "blat-blatnik/Logic-Notes", "max_issues_repo_head_hexsha": "6fc2ed1d44e12e7ecea87243f291968c51cbed1e", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "logic-notes.tex", "max_forks_repo_name": "blat-blatnik/Logic-Notes", "max_forks_repo_head_hexsha": "6fc2ed1d44e12e7ecea87243f291968c51cbed1e", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6433460076, "max_line_length": 366, "alphanum_fraction": 0.5228621989, "num_tokens": 15687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.31609223341560055}}
{"text": "\\documentclass[fleqn, 10pt, twocolumn]{SelfArx}\r\n\\usepackage[english]{babel} \r\n\\usepackage[utf8]{inputenc}\r\n\r\n\r\n\r\n\\setlength{\\columnsep}{0.55cm} % Distance between the two columns of text\r\n\\setlength{\\fboxrule}{0.75pt} % Width of the border around the abstract\r\n\r\n\\usepackage[version=4]{mhchem}\r\n\r\n\\usepackage{fancyhdr}\r\n\\usepackage{here}\r\n\\usepackage{relsize}\r\n\r\n\\usepackage[locale=DE,output-decimal-marker={.}]{siunitx}\r\n\\usepackage{amsmath}\r\n\\sisetup{separate-uncertainty, per-mode=fraction,}\r\n\\usepackage{tikz}\r\n\\usepackage{pgfplots,pgfplotstable}\r\n\\usetikzlibrary{external}\r\n\\tikzexternalize[prefix=tikz/]\r\n\r\n\\usepackage{hyperref}\r\n\r\n\r\n\\pagestyle{fancy}\r\n\\fancyhf{}\r\n\\lhead{Felix Wechsler}\r\n\\rhead{Topic 3 \\textit{Photonic crystal fibers}}\r\n\\definecolor{color1}{RGB}{0,0,90} % Color of the article title and sections\r\n\\definecolor{color2}{RGB}{0,20,20} % Color of the boxes behind the abstract and headings\r\n\r\n\r\n\\usepackage[%\r\n  backend=biber,\r\n  url=false,\r\n  %style=alphabetic,\r\n  % citestyle=authoryear,\r\n  citestyle=numeric,\r\n  maxnames=1,\r\n  minnames=1,\r\n  maxbibnames=99,\r\n  giveninits,\r\n  uniquename=init]{biblatex}\r\n\\DeclareSourcemap{\r\n  \\maps[datatype=bibtex]{\r\n    \\map{\r\n      \\step[fieldset=issn, null]\r\n    }\r\n  }\r\n}\r\n\\DeclareSourcemap{\r\n  \\maps[datatype=bibtex]{\r\n    \\map{\r\n      \\step[fieldset=doi, null]\r\n    }\r\n  }\r\n}\r\n\\DeclareSourcemap{\r\n  \\maps[datatype=bibtex]{\r\n    \\map{\r\n      \\step[fieldset=isbn, null]\r\n    }\r\n  }\r\n}\r\n\r\n\r\n\\addbibresource{references.bib}\r\n\\usepackage[symbol]{footmisc}\r\n\\renewcommand{\\thefootnote}{\\fnsymbol{footnote}}\r\n\r\n\\begin{document}%\r\n\\begin{center}\r\n\\colorbox{color2!10}{\\large\\relscale{1.13}\\textcolor{color1}{\\sffamily\\bfseries Entrance Exam for MPSP Applicants}}\r\n\\end{center}\r\n    \\textit{Third harmonics can be generated by pumping Ti:sapphire laser femtosecond pulses into an Ar-filled hollow-core photonics crystal fiber (HC-PCF) \\cite{Nold2010}. \r\n        In this work\\footnote{For more details about the numerical calculations see this GitHub repository \\url{https://git.io/JtHKW}} we discuss several aspects of their generation and analysis.}\r\n\r\n    \\section{Derivation of Effective Refractive Index}\r\n    The effective refractive index of the generated modes within the HC-PCF can by approximated by:\r\n    \\begin{align}\r\n        n^{mn}(\\lambda, p) = \\sqrt{n^2_{\\text{Ar}}(\\lambda, p ) - \\frac{u_{mn}^2}{k_0^2 a^2}} \r\n        \\label{eq1}\r\n    \\end{align}\r\n    where $k_0=2\\pi/\\lambda$ is the wave number, $\\lambda$ is the vacuum wavelength, $p_0$ and $p$ are a reference and the present pressure, respectively. $a$ is the \r\n    effective radius of the fiber. $u_{mn}$ is the $n$th zero of a $m$th order Bessel function of the first kind. Since the fiber used in \\cite{Nold2010} has a hexagonal core, \\eqref{eq1} is only an approximation.\r\n    \\eqref{eq1} originates from two principles: a $\\lambda$ dependent refractive index and an effective refractive index due to the present mode in a circular fiber.\r\n    Firstly, we discuss the overall structure of the equation coming from the mode formed within the fiber. The field in the fiber is generated by a laser pulse. Once the laser is launched, Maxwell's equation and hence the Helmholtz equation have to be valid.\r\n    % \\begin{align}\r\n    %     \\left(\\nabla^2 + k(\\omega)\\right) \\mathbf E = 0\r\n    %     \\label{eq:helmholtz}\r\n    % \\end{align}\r\n    It is known that the Helmholtz equation within a fiber with circular cross section is solved by Bessel functions \\cite{Nickelson2019}. \r\n    Numerically, a Finite Difference Mode Solver can be used to obtain the eigenvectors $\\mathbf E$ representing the field and the eigenvalues $k^{mn}$ representing the wave number for more complex shapes. The analytical solution for cylindrical symmetries is \r\n    \\begin{align}\r\n        k^{mn} = \\sqrt{(n k_0)^2 - \\left( \\frac{u_{mn}}{a}\\right)^2}\r\n    \\end{align}\r\n    where $n$ is the refractive index of the medium.\r\n    From the wave number we obtain the effective refractive index \r\n    \\begin{align}\r\n        n^{mn} = \\sqrt{n^2 - \\left( \\frac{u_{mn}}{a k_0}\\right)^2}.\r\n        \\label{eq:mode}\r\n    \\end{align}\r\n    Secondly, we can now introduce a wavelength and a pressure dependency to the equation. To describe the $\\lambda$ dependency, several empirical approaches are possible. \r\n    In the case of noble gases, the following Sellmeier equation turned out to be convenient \\cite{Borzsonyi2008}\r\n    \\begin{align}\r\n       n^2(\\lambda, p_0)  = 1 + \\frac{T_0}{T} \\left(\\frac{B_1}{1- (\\lambda_1/\\lambda)^2} + \\frac{B_2}{1- (\\lambda_2/\\lambda)^2}  \\right)\r\n        \\label{eq:wvl}\r\n    \\end{align}\r\n    where $B_{1/2}$ and $\\lambda_{1/2}$ are fitting parameters being gas specific.\r\n    Furthermore, from the Lorentz-Lorenz theory\r\n    we know that there is a linear relation between the squared refractive index and the pressure $p$ \\cite{Borzsonyi2008}.\r\n    Knowing $n^2(p_0) \\sim p_0$ it is straightforward to see that\r\n    \\begin{align}\r\n        n_{\\text{Ar}}^2(\\lambda, p) = \\frac{p}{p_0} n^2(\\lambda, p_0)\r\n        \\label{eq:p}\r\n    \\end{align}\r\n    and therefore by measuring the Sellmeier parameters for a pressure $p_0$ we can plug Equation \\ref{eq:wvl}, \\ref{eq:p} into \\ref{eq:mode} to obtain \\eqref{eq1}. \r\n    By introducing a first order Taylor approximation of $\\sqrt{1+x} \\approx 1 + \\frac{x}{2}$, we can further simplify to obtain the equation below.\r\n    \\begin{align}\r\n        n^{mn}(\\lambda, p) \\approx 1 + n^2(\\lambda, p_0) \\frac{p}{2p_0} -  \\frac{u_{mn}^2}{2 k_0^2 a^2}\r\n        \\label{eq1a}\r\n    \\end{align}\r\n\r\n    \\section{Phase Matching}\r\n    In third harmonics generation, two fundamental conditions need to hold: energy and momentum conservation. \r\n    In the wave picture, momentum conservation is a phase matching condition and can be in the fiber mode expressed as\r\n    \\begin{align}\r\n        \\mathbf{k}^{mn} = 3 \\cdot \\mathbf k^{11} \r\n    \\end{align}\r\n    and hence\r\n    \\begin{align}\r\n        n^{11}(\\lambda, p) - n^{mn}(\\lambda / 3, p)= 0\r\n        \\label{eq:pm}\r\n    \\end{align}\r\n    where $mn$ is the generated third harmonic mode and $11$ the pump mode. \r\n    The left hand side of \\eqref{eq:pm} can be visualized to find all possible solutions. \r\n    We believe\\footnote{Despite \\citeauthor{Travers2011} state differently \\cite{Travers2011}, we could only reproduce the results of \\citeauthor{Nold2010} by decrementing $m$. This decrementation is mentioned by \\citeauthor{Marcatili1964} \\cite{Marcatili1964}.} that the hybrid mode $\\text{HE}_{mn}$ corresponds to Bessel coefficients $u_{(m-1)n}$. \r\n    Accordingly, $\\text{HE}_{11}$ has the Bessel coefficients $u_{01}$.\r\n    \\begin{figure}[h]\r\n        \\centering\r\n        \\begin{tikzpicture}\r\n            \\begin{axis}[\r\n                xmin = 400, xmax = 1000,\r\n                ymin = -5, ymax = 7.5,\r\n                ytick = {-2.5, 0, ..., 7.5},\r\n                height=5.5cm, width=8cm,\r\n                xlabel = {$\\lambda$ in \\si{\\nano\\meter}}, \r\n                ylabel = {$(n^{11}(\\lambda, p) - n^{mn}(\\lambda/3, p)) \\cdot 10^4$},\r\n                legend pos = {north west},\r\n                legend entries = {$\\ce{Ar}-\\text{HE}_{11}$, $\\ce{Ar}-\\text{HE}_{12}$, $\\ce{Ar}-\\text{HE}_{13}$, $\\ce{Ar}-\\text{HE}_{23}$, $\\ce{Ar}-\\text{HE}_{33}$}\r\n                ]\r\n                \\draw[dashed] (axis cs:0,0) -- (axis cs:1200, 0);\r\n                \\draw[dashed] (axis cs:800,10) -- (axis cs:800, -10);\r\n                \\node at (axis cs:860, 5) {\\footnotesize pump $\\lambda$};\r\n                \\addplot[color=blue]\r\n                    table[x index = 0, y index = 1]{../data/argon.txt};\r\n                \\addplot[color=red]\r\n                    table[x index = 0, y index = 2]{../data/argon.txt};\r\n                \\addplot[color=green]\r\n                    table[x index = 0, y index = 3]{../data/argon.txt};\r\n                \\addplot[color=orange]\r\n                    table[x index = 0, y index = 4]{../data/argon.txt};\r\n                \\addplot[color=black!50!white]\r\n                    table[x index = 0, y index = 5]{../data/argon.txt};\r\n                \\addplot[color=blue, dotted]\r\n                    table[x index = 0, y index = 1]{../data/argon_low_pressure.txt};\r\n            \\end{axis}\r\n        \\end{tikzpicture}\r\n        \\caption{Refractive index difference of \\ce{Ar} for different \\text{HE} modes and $\\text{HE}_{11}$ at $T=\\SI{293}{\\kelvin}$, $p=\\SI{5000}{\\milli\\bar}$.}\r\n        \\label{plt:pm}\r\n    \\end{figure}\r\n    From \\autoref{plt:pm} it follows that intra-modal phase matching ($mn = 11$) is not possible since the $\\text{HE}_{11}$ curve does not reach values where the refractive index difference is approximately 0.\r\n    Even, at a low pressure of $p=\\SI{100}{\\milli\\bar}$ the dotted blue line does not reach 0. \r\n    Also mathematically it is clear that \\eqref{eq:pm} cannot be solved for intra-modal phase matching because the only variable is $\\lambda$ and since $n(\\lambda)$ is a monotonic decreasing function, there is no solution for $\\lambda$ and $\\lambda/3$. \r\n    However, $\\text{HE}_{13}$ has a solution to the phase matching condition identifiable at $\\lambda=\\SI{800}{\\nano\\meter}$.\r\n    Mathematically, $\\lambda/3$ leads to a decrease in \\eqref{eq:pm} which is then compensated by an increase of $u_{03}>u_{01}$.\\\\\r\n    Instead of using \\ce{Ar}-filled HC-PCF, third harmonics can be generated with \\ce{Kr} as well. \r\n    Using the Sellmeier coefficients for \\ce{Kr}, we apply the phase matching condition to \r\n    solve for the required pressure.\r\n    \\begin{figure}[h]\r\n        \\centering\r\n        \\begin{tikzpicture}\r\n            \\begin{axis}[\r\n                xmin = 0, xmax = 9,\r\n                ymin = -3, ymax = 5.5,\r\n                ytick = {-2, 0, 2, 4, 6},\r\n                height=5.5cm, width=8cm,\r\n                xlabel = {$p$ in \\si{\\bar}}, \r\n                ylabel = {$(n^{11}(\\lambda, p) - n^{mn}(\\lambda/3, p)) \\cdot 10^4$ },\r\n                legend pos = {north west},\r\n                legend entries = {$\\ce{Kr}-\\text{HE}_{13}$, $\\ce{Kr}-\\text{HE}_{23}$, $\\ce{Kr}-\\text{HE}_{33}$}\r\n                ]\r\n                \\draw[dashed] (axis cs:0,0) -- (axis cs:12, 0);\r\n                \\addplot[color=blue]\r\n                    table[x index = 0, y index = 1]{../data/krypton.txt};\r\n                \\addplot[color=red]\r\n                    table[x index = 0, y index = 2]{../data/krypton.txt};\r\n                \\addplot[color=green]\r\n                    table[x index = 0, y index = 3]{../data/krypton.txt};\r\n            \\end{axis}\r\n        \\end{tikzpicture}\r\n        \\caption{Refractive index difference of \\ce{Kr} for different \\text{HE} modes and $\\text{HE}_{11}$ at $T=\\SI{293}{\\kelvin}$,  $\\lambda=\\SI{800}{\\nano\\meter}$.}\r\n        \\label{plt:pressure}\r\n    \\end{figure}\r\n    In \\autoref{plt:pressure} we can see that for $p^{13}=\\SI{2.4}{\\bar}$, $p^{23}=\\SI{5.3}{\\bar}$ and $p^{33}=\\SI{8.5}{\\bar}$ the phase matching is fulfilled. \r\n\\section{\\ce{Xe}-filled HC-PCF}\r\n    \\autoref{plt:pmxenon} shows the refractive index difference for a \\ce{Xe}-filled HC-PCF\\footnote{Note, there is a typo in \\cite{Borzsonyi2008}. $C_1$ should be \\SI{12.75e-3}{\\micro\\meter\\squared} instead of \\SI{12.75e-6}{\\micro\\meter\\squared}. See \\url{https://refractiveindex.info/?shelf=main&book=Xe&page=Borzsonyi}}.\r\n    \\begin{figure}[h]\r\n        \\centering\r\n        \\begin{tikzpicture}\r\n            \\begin{axis}[\r\n                xmin = 400, xmax = 1000,\r\n                ymin = -5, ymax = 7.5,\r\n                ytick = {-2.5, 0, ..., 7.5},\r\n                height=5.5cm, width=8cm,\r\n                xlabel = {$\\lambda$ in \\si{\\nano\\meter}}, \r\n                ylabel = {$(n^{11}(\\lambda, p) - n^{mn}(\\lambda/3, p)) \\cdot 10^4$},\r\n                legend pos = {north west},\r\n                legend entries = {$\\ce{Xe}-\\text{HE}_{11}$, $\\ce{Xe}-\\text{HE}_{12}$,$\\ce{Xe}-\\text{HE}_{13}$, $\\ce{Xe}-\\text{HE}_{23}$, $\\ce{Xe}-\\text{HE}_{33}$}\r\n                ]\r\n                \\draw[dashed] (axis cs:0,0) -- (axis cs:1200, 0);\r\n                \\draw[dashed] (axis cs:800,10) -- (axis cs:800, -10);\r\n                \\node at (axis cs:860, 5) {\\footnotesize pump $\\lambda$};\r\n                \\addplot[color=blue]\r\n                    table[x index = 0, y index = 1]{../data/xenon.txt};\r\n                \\addplot[color=red]\r\n                    table[x index = 0, y index = 2]{../data/xenon.txt};\r\n                \\addplot[color=green]\r\n                    table[x index = 0, y index = 3]{../data/xenon.txt};\r\n                \\addplot[color=orange]\r\n                    table[x index = 0, y index = 4]{../data/xenon.txt};\r\n                \\addplot[color=black!50!white]\r\n                    table[x index = 0, y index = 5]{../data/xenon.txt};\r\n            \\end{axis}\r\n        \\end{tikzpicture}\r\n        \\caption{Refractive index difference of \\ce{Xe} for different \\text{HE} modes and $\\text{HE}_{11}$ at $T=\\SI{293}{\\kelvin}$, $p=\\SI{960}{\\milli\\bar}$.}\r\n        \\label{plt:pmxenon}\r\n    \\end{figure}\r\n    It follows that third harmonic generation is possible for \\ce{Xe} at lower pressures but even higher harmonics have been observed in \\ce{Xe}\r\n    \\cite{Heckl2009}. Among the investigated noble gases, \\ce{Xe} has the lowest absolute pressure and \\ce{Ar} the highest required for third harmonic generation. \r\n    The reason for the lower pressure is that \\ce{Xe} has the largest dispersion \\cite{Borzsonyi2008} leading to a smaller $p$ needed to compensate for the larger $u_{mn}$ in \\eqref{eq:pm}.\r\n    Consequently \\ce{Ar} shows the lowest dispersion.\r\n    It is worth to mention that the opportunity to use different gases enhances the use in practical applications of higher harmonics generation with HC-PCFs. \r\n    \\ce{Xe} and \\ce{Ar} allow to vary the presssure by almost one order of magnitude but still generating third harmonics. Also, the linear pressure dependency in the phase matching condition\r\n    allows to fine-tune efficiently for certain higher order modes.\r\n    Furthermore, combining \\eqref{eq1a} together with the ideal gas law, gas-filled HC-PCFs are robust against temperature induced pressure variations. For moderate gas chamber dimensions temperature changes due to absorption of radiation are negligible \\cite{Serebryannikov2004}.\r\n    In conclusion, noble gas-filled HC-PCFs allow for setups to be small, nonhazardous and insensitive to environmental changes and are therefore \r\n    suitable candidates for generation of light in UV or EUV regimes.\r\n    It can be conjectured, that other noble gases like Helium and Neon are also promising candidates since their Sellmeier coefficients are in the same order of magnitudes and the physical properties of noble gases are similar. \r\n\r\n    \\printbibliography\r\n\r\n\\end{document}\r\n", "meta": {"hexsha": "582cc7c72b74db4d121b594b79c7572310ac2c11", "size": 14684, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "article/MPSP_Felix_Wechsler.tex", "max_stars_repo_name": "roflmaostc/Calculations-for-Higher-Harmonics-Generation-in-Hollow-Core-Photonic-Crystal-Fibers", "max_stars_repo_head_hexsha": "62064ae5ffc103cd2696679a72078e0b0ac04dc1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "article/MPSP_Felix_Wechsler.tex", "max_issues_repo_name": "roflmaostc/Calculations-for-Higher-Harmonics-Generation-in-Hollow-Core-Photonic-Crystal-Fibers", "max_issues_repo_head_hexsha": "62064ae5ffc103cd2696679a72078e0b0ac04dc1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "article/MPSP_Felix_Wechsler.tex", "max_forks_repo_name": "roflmaostc/Calculations-for-Higher-Harmonics-Generation-in-Hollow-Core-Photonic-Crystal-Fibers", "max_forks_repo_head_hexsha": "62064ae5ffc103cd2696679a72078e0b0ac04dc1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 57.359375, "max_line_length": 351, "alphanum_fraction": 0.6227867066, "num_tokens": 4336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.31609223341560055}}
{"text": "\\section{Point Group Theory}\r\n\\index{Groups|(} \\index{Point-group!theory} \\index{Symmetry!in group theory}\r\nThis Section is based on the original work of Peter Bischof in the UMNDO\r\nprogram, and made available to me by Dr David Danovich.\r\n\r\nSome point-group theory has been added to MOPAC.  The main functionalities\r\nadded are: \\index{AUTOSYM}\\index{Bischof@{\\bf Bischof, Peter}}\r\n\\index{UMNDO}\\index{Danovich@{\\bf Danovich, David}}\r\n\r\n\\begin{itemize}\r\n\\item `Normal' symmetry relationships are now automatically recognized if\r\n\\comp{AUTOSYM} is specified.\r\n\r\n\\item The symmetry of the system is printed both at the start of the run and at\r\nthe end.  If the point-group changes, the change will be shown in the different\r\npoint-group symbols.\r\n\r\n\\item Molecular orbitals will be characterized by Irreducible Representation \r\n(I.R.). \r\n\r\n\\item Normal coordinates generated in the vibrational calculation will be\r\ncharacterized by I.R.\r\n\r\n\\item State functions will be characterized by I.R.\r\n\r\n\\item All rotation groups up to order 8, except D$_{8d}$, are available.\r\n\r\n\\item The cubic groups T, T$_h$, T$_d$, O, O$_h$, I, and I$_h$ are available.\r\n\r\n\\item The infinite groups C$_{\\infty v}$, D$_{\\infty h}$ and R$_3$ are\r\navailable.\r\n\r\n\\item In \\comp{FORCE} or vibrational frequency calculations, symmetry will be\r\nused to accelerate the calculation, thus a calculation of benzene would involve\r\ntwo atoms, a C and a H atom, to be calculated, rather than the normal 12 atoms.\r\n\r\n\\item In vibrational frequency calculations, the Hessian or force matrix\r\nwill be symmetrized.  \\index{sym\\_force} \\label{sym_force}\r\n$$\r\nF_{ij}=\\frac{1}{h}\\sum_hR(h)^TF_{ij}'R(h)\r\n$$\r\n\r\nThis eliminates the normal small deviations from exact symmetry\r\n\\begin{htmlonly}\r\n(\\htmlref{a qualification appears\r\nelsewhere}{fc})\r\n\\end{htmlonly}\r\n\\begin{latexonly}\r\n(see also p.~\\pageref{fc}\r\nfor a qualification)\r\n\\end{latexonly}.\r\n\r\n\\end{itemize}\r\n\r\n\r\n\\subsection*{Limitations}\r\n\\begin{itemize}\r\n\\index{Point Group D$_{8d}$ missing}\\index{D$_{8d}$ missing}\r\n\\item Group D$_{8d}$ is missing.  This group is characterized by the presence\r\nof a 16-fold S$_n$ axis.  Only S$_n$ operations up to S$_{12}$  are  checked\r\nfor.  As a  result, D$_{8d}$ would not be recognized.  However, this is a rare\r\npoint-group, and its loss should not be important.\r\n\r\n\\item Some systems which are insufficiently near to a given point group will be\r\nassigned to the nearest sub-group.  For example, if SF$_6$ is distorted so that\r\ntwo opposite F atoms are at a different distance to the other four, the system\r\nmight be classified as O$_h$ or D$_{4h}$, depending on the degree of\r\ndistortion.  This shows up mainly in methyl groups, e.g.\\ neopentane, in which\r\noptimization normally stops before the angles of the hydrogens are fully\r\noptimized.\r\n\\end{itemize}\r\n\r\n\r\n\\subsection{Representation of Point Groups}\r\nThe 57 groups recognized in MOPAC are given in Table~\\ref{pgs}.\r\n\\begin{table}\r\n\\caption{\\label{pgs} Point Groups available within Symmetry Code}\r\n\\begin{center}\r\n\\begin{tabular}{lllllllll} \\hline\r\n C$_1$&C$_{s} $ & C$_{i }$   &       &      &      &     &  O             \\\\\r\n C$_2$&C$_{2v}$ & C$_{2h}$   & D$_2$ & D$_{2d}$  & D$_{2h}$  &     &  T   \\\\\r\n C$_3$&C$_{3v}$ & C$_{3h}$   & D$_3$ & D$_{3d}$  & D$_{3h}$  &     &  T$_d$   \\\\\r\n C$_4$&C$_{4v}$ & C$_{4h}$   & D$_4$ & D$_{4d}$  & D$_{4h}$  & S$_4$  &  T$_h$   \\\\\r\n C$_5$&C$_{5v}$ & C$_{5h}$   & D$_5$ & D$_{5d}$  & D$_{5h}$  &     &  O$_h$   \\\\\r\n C$_6$&C$_{6v}$ & C$_{6h}$   & D$_6$ & D$_{6d}$  & D$_{6h}$  & S$_6$  &  I & I$_h$   \\\\\r\n C$_7$&C$_{7v}$ & C$_{7h}$   & D$_7$ & D$_{7d}$  & D$_{7h}$  &  &   C$_{\\infty v}$  \r\n& D$_{\\infty h}$ \\\\\r\n C$_8$&C$_{8v}$ & C$_{8h}$   & D$_8$ &      & D$_{8h}$ & S$_8$  &   R$_3$   \\\\ \\hline\r\n\\end{tabular}\r\n\\end{center}\r\n\\end{table}\r\n\r\nEach point group is represented by a subset of the associated point-group\r\ntable. For example, the group D$_{2h}$ is represented by the subset shown in\r\nTable~\\ref{d2h}. The operations selected for the subgroup are the identity, E,\r\nand that minimum set of operations which is sufficient to allow all the\r\noperations to be generated as products of these operations.  Thus, for the\r\nhighest finite point group, I$_h$, the generating operations are: E, I, C$_3$,\r\nand C$_5$.  Although it is not obvious, all 120 operations of the group can be\r\ngenerated as products of these four operations.\r\n\r\n\\begin{table} \r\n\\caption{\\label{d2h}Subset of Group D$_{2h}$}\r\n\\begin{center}\r\n\\begin{tabular}{lrrrr} \\\\ \\hline\r\n  $\\Gamma$ &  E  &  C$_{2y}$ & C$_{2z}$& I \\\\ \\hline\r\nA$_g$   \\\\\r\nB$_{1g}$ &1 &  1  &-1  &  1  \\\\\r\nB$_{2g}$ &1 & -1  & 1  &  1  \\\\\r\nB$_{3g}$ &1 & -1  &-1  &  1  \\\\\r\nA$_{u} $ &1 &  1  & 1  & -1  \\\\\r\nB$_{1u}$ &1 &  1  &-1  & -1  \\\\\r\nB$_{2u}$ &1 & -1  & 1  & -1  \\\\\r\nB$_{3u}$ &1 & -1  &-1  & -1  \\\\ \\hline\r\n\\end{tabular}\\end{center}\r\n\\end{table}\r\n\r\nEach point-group is assumed to contain the totally symmetric representation,\r\nhere \\index{Euler matrices} A$_{1g}$.  Operations are represented as $3\\times3$\r\nEuler matrices, thus C$_{2x}$, C$_{2y}$  and C$_{2z}$  would be represented as\r\nin Figure~\\ref{c2op} \\ All operations not given can be generated as products of\r\noperations already known, thus C$_{2x}$ = C$_{2y}$ $\\times$ C$_{2z}$.\r\n\r\n% 9 lines, including this line\r\n\\begin{figure}\r\n\\begin{makeimage}\r\n\\end{makeimage}\r\n\\begin{center}\\hfil\r\nC$_{2x}$: \\begin{tabular}{|rrr|}1&0&0\\\\0&-1&0\\\\0&0&-1\\end{tabular}\\hfil\r\nC$_{2y}$: \\begin{tabular}{|rrr|}-1&0&0\\\\0&1&0\\\\0&0&-1\\end{tabular}\\hfil\r\nC$_{2z}$: \\begin{tabular}{|rrr|}-1&0&0\\\\0&-1&0\\\\0&0&1\\end{tabular}\\hfil\r\n\\end{center}\r\n\\caption{\\label{c2op} Representation of Symmetry Operations}\r\n\\end{figure}\r\n\r\nIn order to minimize storage, the characters in  character tables are stored\r\nseparately from the point groups.  This allows, e.g., C$_{2v}$, C$_{2h}$, and\r\nD$_{2}$ to use the same character table. \r\n\r\n\\subsection{Identification of Point-Groups}\r\n\\index{Infinite groups}\r\n\\subsubsection*{Infinite Groups}\r\nIn order to identify the molecular point-group the system must be oriented in a\r\nspecific way.  Four families of point-groups are checked for: (1) the infinite\r\ngroups, (2) the cubic groups, (3)  groups with one high-symmetry axis, and (4)\r\nthe Abelian groups. Each family is treated differently.  First, the moments of\r\ninertia are calculated.  If all are zero, the system is a single atom, and the\r\nassociated group is R$_3$.  If two moments are zero, the system is  either\r\nC$_{\\infty v}$ or D$_{\\infty h}$; the presence of a horizontal plane of\r\nsymmetry distinguishes between them.\r\n\r\n\\index{Cubic Groups}\r\n\\subsubsection*{Cubic Groups}\r\nHaving eliminated the infinite groups, the three moments of inertia are checked\r\nto see if they are all the same.  If they are, then the system is cubic.  Cubic\r\nsystems are oriented by identifying atoms of the set nearest to the center of\r\nsymmetry.  If there are 4, 6, 8, 12, or 20 of these, and the number of\r\nequidistant nearest neighbors  is 3, 4, 3, 5, or 3, respectively, then the\r\natoms are \r\n%probably \r\nat the vertices of one of the Platonic solids (tetrahedron, octahedron, cube,\r\nicosahedron, dodecahedron),\r\n%Platonic solids (tetrahedron, octahedron, cube, icosahedron, dodecahedron).\r\n%There are a few cases in which these two conditions are true, but the\r\n%solid is nevertheless not platonic.\r\n%To exclude thses rare case, use is made of the ratio of the edge distance \r\n%to the (vertex to center) distance.  This ratio is unique for each of the \r\n%platonic solids, if the\r\n%computed value is correct the solid is unambiguously platonic,\r\nand therefore all atoms of the set lie on high-symmetry axes.  The first  atom\r\nis selected and used to define the $z$ axis.\r\n\r\n\\index{Platonic solids} \\index{Buckminsterfullerene} If the number of atoms in\r\nthe set does not correspond to any of the Platonic solids, then the set is\r\nchecked for the existence of a equilateral triangle, a square, or a regular\r\npentagon.  When one of these is found, the center of the polygon is used to\r\ndefine the $z$ axis.  An example of this type of system is C$_{60}$,\r\nBuckminsterfullerene, which has a five-fold axis going through the center of a\r\npentagonal face.\r\n\r\nOnce the $z$ axis is identified, the system is checked for C$_n$ axes, $n$=3 to\r\n$n$=8.  To complete the orientation, the system is rotated about the $z$ axis\r\nso that two atoms, having equal $z$ coordinates, have equal $y$ coordinates.\r\nThe existence of rotation axes which are not coincidental with the $z$ axis and\r\nthe presence or absence of a center of inversion are then used to identify\r\nwhich cubic group the system belongs to.\r\n\r\n\\index{Degenerate groups}\r\n\\subsubsection*{Other Degenerate Groups}\r\nIf the system has still not been identified, then the two equal moments of\r\ninertia indicate a degenerate point group.  As with the cubic groups, the $y$ and\r\n$z$ axes (and, by implication, the $x$ axis) are identified. The system is\r\noriented, and the C$_n$ and S$_n$ axes identified.\r\n\r\nThe degenerate groups, C$_n$, C$_{nv}$, C$_{nh}$, D$_n$, D$_{nd}$, D$_{nh}$, \r\nS$_n$, are distinguished by the existence or absence of C$_2$ axes\r\nperpendicular to the $z$ axis, and by planes of symmetry.\r\n\r\n\\index{Abelian groups}\\index{Orientation!for symmetry}\r\n\\index{Symmetry!orientation of molecules}\r\n\r\n\\subsubsection*{Abelian Groups}\r\nAll that remains are the Abelian groups, C$_1$, C$_2$, C$_i$, C$_s$,  C$_{2v}$,\r\nC$_{2h}$, D$_2$,  and D$_{2h}$.  After orienting the molecule, the axes are\r\nswapped around so that the normal convention for orienting Abelian systems is\r\nobeyed.  For groups C$_1$, C$_2$, C$_i$, and C$_s$, there is no possibility for\r\nambiguity.  For C$_{2v}$ and D$_2$, however, the orientation of the system\r\naffects the labels of the irreducible representations.  To prevent ambiguity,\r\nthe convention for orienting Abelian molecules is:\r\n\\begin{itemize}\r\n\\item The axis with the largest number of atoms is the $z$  axis.\r\n\\item The plane with the largest number of atoms that includes the $z$ axis is \r\nthe $yz$  plane.\r\n\\end{itemize}\r\nThus for ethylene, the $\\pi$ orbitals point along the $x$  axis.\r\n\r\n\\subsubsection*{Tolerance}\r\nNormally, molecular geometries do not exactly correspond to the idealized\r\npoint-group.  Thus benzene might have slightly different bond-lengths and\r\nangles.  Of course, symmetry could be used to prevent this, but in the\r\ndiscussion here we assume that the symmetry of the system is unknown.  To allow\r\nfor these slight distortions, a small tolerance is built in to the tests for\r\nsymmetry elements. This starts off at 0.1\\AA\\ , but may be tightened\r\nautomatically if ambiguities are detected.  An example of such an ambiguity is\r\nfound in tropylium, C$_7$H$_7^+$ ion, where the C-C distance is 1.4 \\AA .\r\nRotating the ring by 45 degrees (a C$_8$ operation) would place the atoms at a\r\ndistance of only 0.18\\AA\\  from equivalent positions.  C$_7$ and C$_8$ would\r\nthus  give almost identical results.  To resolve such ambiguities, when they\r\narise, the tolerance is reduced, and the test re-run.\r\n\r\nEven with this feature, some systems still resist classification.   A distorted\r\ngeometry might have some, but not all, elements of a high point group.  Perhaps\r\na distorted benzene has a C$_2$(z) and a C$_3$(z), but  not a C$_6$(z), \r\nimpossible in a real system.  As such it would appear to be different from all\r\nreal point groups.  To accommodate such defects a descent in symmetry is\r\ncarried out.  This consists of checking each point-group in turn, in order of\r\ndecreasing symmetry.  Once all of the elements of a point group are satisfied,\r\nthe system is assigned to that point group, even if the system contains more\r\nsymmetry than the point group.\r\n\r\nBy these two devices, a variable tolerance and the descent in symmetry, most\r\nsystems should be identified correctly, or at least as a sub-group of the full\r\npoint group.\r\n\r\n\\subsection{Orientation of the Abelian groups C$_{2v}$ and D$_{2h}$}\r\nUnlike all other groups, two of the Abelian groups, C$_{2v}$ and  D$_{2h}$,\r\npresent novel problems in assigning the irreducible representations.  For most\r\ngroups, the symmetry axis is obvious, or of there are several axes, the\r\nprincipal axis is obvious.  For C$_{2v}$ and D$_{2h}$ an ambiguity exists. \r\nConsider, for example, ethylene, a system of point-group D$_{2h}$.  Should the\r\n$z$ axis be perpendicular to the plane of the molecule---that is the unique\r\ndirection, or should it go through the two carbon atoms---that is also a unique\r\ndirection, but for a different reason, or should it be the third orthogonal\r\ndirection---which is also unique.  The choice of $z$ axis is important in order\r\nto correctly assign the B$_{1g}$ and B$_{1u}$ of point-group D$_{2h}$.  For\r\nboth C$_{2v}$ and D$_{2h}$ the $x$ and $y$ axes must also be unambiguously\r\ndefined in order to distinguish  between B$_{2g}$ and B$_{3g}$ and between\r\nB$_{2u}$ and B$_{3u}$ of  D$_{2h}$, and between B$_{1}$ and B$_{2}$ of\r\nC$_{2v}$. Clearly a convention has to be decided upon, otherwise one persons\r\nB$_{1g}$ might be a second persons B$_{2g}$ and a third persons B$_{3g}$.\r\n\r\nThe convention used in MOPAC is the following:\r\n\r\nIf there are three C$_2$ axes, the one with the largest number of atoms unmoved\r\nby a C$_2$ operation is $z$.  If there is only one C$_2$ axis, that is $z$.\r\n\r\nOnce $z$ is defined, the $y$ axis is defined as the axis of the remaining two\r\naxes which has the larger number of atoms unmoved by  the $\\sigma$ symmetry\r\noperations.  \r\n\r\nThe $x$ axis is the remaining axis.\r\n\r\nTo see how this works, consider ethylene, with the C--C axis being along the\r\n$x$ direction, and the plane of the system being $xy$. Under the eight\r\noperations of D$_{2h}$, E, C$_{2z}$, C$_{2y}$, C$_{2x}$, $\\sigma_{xy}$,\r\n$\\sigma_{xz}$, $\\sigma _{yz}$, and $i$, the number of atoms unmoved are 6, 0,\r\n0, 2, 6, 2, 0, and 0 respectively.\r\n\r\nFrom this it follows that the old $x$ axis is now re-defined as the $z$ axis. \r\nThe new $y$ axis has to be chosen based on the number of atoms unmoved under\r\nthe $\\sigma_{xy}$ and $\\sigma_{xz}$ operations (6 and 2). The new $y$ axis is\r\ndefined as being the old $y$ axis.  The remaining new axis $x$ therefore is the\r\nold $z$ axis.\r\n\r\nThe overall result is that the symmetry axes in ethylene are defined as: $z$ -\r\nalong the C--C bond; $y$ - in the molecular plane, perpendicular to the C--C\r\nbond, and $x$ - out-of-plane.\r\n\r\nIn MOPAC the orientation of the molecule is defined by the user, therefore the\r\nassignment of the symmetry axes might be confusing.  If the irreducible\r\nrepresentations of ethylene are assigned, and the atoms are defined  using\r\ninternal coordinates in the order C, C, H, H, H, H, then the $p$ orbitals will\r\nreflect the orientation used in the previous discussion, but the\r\nrepresentations will be correct according to the conventions just defined.\r\n\r\n\\subsection{Molecular Orbitals}\r\nEach M.O.\\ is subjected to the operation\r\n$$\r\n\\psi' = |R|\\psi>\r\n$$\r\nfrom which the expectation value\r\n$$\r\n\\chi=<\\psi'|\\psi>\r\n$$\r\ncan readily be calculated.\r\n\r\n\\index{Degenerate M.O.s}\r\nAll $\\chi$'s within a given degenerate manifold are summed:\r\n$$\r\n\\chi_i = \\sum_j\\chi_j^{(i)}\r\n$$\r\nwhere $j$ runs over all components of the degenerate manifold $i$.\r\n\r\nThis results in a set of characters which can be compared to those stored in\r\nthe character tables.  \r\n\r\nSince molecular orbitals involve single electrons, the irreducible\r\nrepresentations \\index{Irreducible representations} are rendered into lower\r\ncase before printing. \r\n\r\n\\subsection{Normal Coordinates}\r\n\\index{States!vibration} \\index{Normal coordinates}\\index{Coordinates!normal}\r\nAnalysis of normal coordinates is a little simpler than that of molecular\r\norbitals in that every atom contributes precisely three components to each\r\nnormal coordinate, an $x$, $y$, and $z$ component.  These transform in the same\r\nway as the p$_x$, p$_y$, and p$_z$ atomic orbitals.\r\n\r\nBecause normal coordinates are states, the first letter of the irreducible\r\nrepresentation is capitalized.\r\n\r\n\\subsection{States}\r\n\\index{States!electronic}\\index{States!symmetry of}\r\nCalculating the characters for electronic states is much more complicated than\r\nthat for M.O.s or normal coordinates.  \r\n\r\nConsider the effect of an operation, $R$, on a state, $\\Phi_a$.  The \r\ncharacter of the operation is given by\r\n$$\r\n\\chi_{R,a} = <\\Phi_a|R|\\Phi_a>.\r\n$$\r\nA state function can be expressed as a linear combination of microstates:\r\n$$\r\n\\Phi_a = \\sum_jC_{ja}\\Psi_j,\r\n$$\r\nso the character of the operation on the state function can be written in \r\nterms of microstates as\r\n$$\r\n\\chi_{R,a} =\\sum_i\\sum_jC_{ia}C_{ja}<\\Psi_i|R|\\Psi_j>.\r\n$$\r\nEach microstate, $\\Psi_j$, can be represented by a \\mi{Slater determinant}\r\nof $N$ molecular orbitals\r\n:\r\n$$\r\n\\Psi_j = \\frac{1}{\\sqrt{N!}}\\sum_{P=1}^{N!}(-1)^PP(\\prod_{k=1}^N\\psi_k^j)\r\n$$\r\n\\index{Microstates} where the molecular orbitals in the microstate consist of a\r\nselection of the M.O.s in the  active space\\index{Active space!in C.I.}. \r\nBefore we continue, let us examine this idea:\r\n\r\nConsider a full set of M.O.s:\r\n$$\r\n\\psi_1\\psi_2\\psi_3\\psi_4 \\psi_5 \\psi_6 \\psi_7 \\psi_8 \\psi_9 \r\n\\psi_{10}\\psi_{11}\\psi_{12}\\psi_{13}\\psi_{14}\\psi_{15}\\psi_{16}.\r\n$$\r\nLet the active space be the M.O.s  from 8 to 11.  Then microstates containing\r\ntwo electrons would be:\r\n\\begin{center}\r\n\\hfil\r\n$\\psi_8\\psi_9$\r\n\\hfil\r\n$\\psi_8\\psi_{10}$\r\n\\hfil\r\n$\\psi_8\\psi_{11}$\r\n\\hfil\r\n$\\psi_9\\psi_{10}$\r\n\\hfil\r\n$\\psi_9\\psi_{11}$\r\n\\hfil\r\n$\\psi_{10}\\psi_{11}$.\r\n\\hfil\r\n\\end{center}\r\nThese microstates could be represented by M.O.\\ orbital occupancies.\r\n\\begin{center}\r\n\\hfil\r\n1100\r\n\\hfil\r\n1010\r\n\\hfil\r\n1001\r\n\\hfil\r\n0110\r\n\\hfil\r\n0101\r\n\\hfil\r\n0011.\r\n\\hfil\r\n\\end{center}\r\nRemember that the M.O.s here can be of either $\\alpha$ or $\\beta$ spin.\r\n\r\nTo continue, we need to evaluate $<\\Psi_i|R|\\Psi_j>$.  This can be expressed\r\nin terms of M.O.s as:\r\n$$\r\n<\\Psi_i|R|\\Psi_j> = \\frac{1}{N!}\\sum_{P=1}^{N!}(-1)^PP(<\\prod_{k=1}^N\\psi_k^i)|\r\nR|\r\n\\sum_{Q=1}^{N!}(-1)^QQ(\\prod_{l=1}^N\\psi_l^j)>.\r\n$$\r\n\r\nFor convenience, we will represent the integral $<\\psi_k^i|R|\\psi_l^j>$ by \r\n$\\chi_{kl}^{ij}$.  This integral can be described as ``The integral over M.O.\\\r\n$\\psi_k$ in microstate $\\Psi_i$ with the result of operator $R$ acting\r\non M.O.\\ $\\psi_l$ in microstate $\\Psi_j$.''\r\n\r\nUsing this abbreviation, $<\\Psi_i|R|\\Psi_j>$ can be written as:\r\n$$\r\n<\\Psi_i|R|\\Psi_j> =\\frac{1}{N!}\\sum_{P=1}^{N!} \\sum_{Q=1}^{N!}(-1)^P(-1)^Q\r\nP\\prod_{k=1}^{N!}Q\\prod_{l=1}^{N!}\\chi_{kl}^{ij}.\r\n$$\r\nAlthough it is not immediately obvious, the right-hand term is a determinant,\r\nof order $N$:\r\n$$\r\n<\\Psi_i|R|\\Psi_j> =\\left|\r\n\\begin{array}{cccc}\r\n\\chi_{11}^{ij} & \\chi_{21}^{ij} & \\chi_{31}^{ij} & \\ldots \\\\\r\n\\chi_{12}^{ij} & \\chi_{22}^{ij} & \\chi_{32}^{ij} & \\ldots \\\\\r\n\\chi_{13}^{ij} & \\chi_{23}^{ij} & \\chi_{33}^{ij} & \\ldots \\\\\r\n \\ldots           &  \\ldots           &   \\ldots          & \\ldots \r\n\\end{array}\r\n\\right|.\r\n$$\r\n\r\nFor our purposes, solution of the determinant is best done explicitly. To see\r\nwhy, note that the number of M.O.s involved in the C.I.\\ (the active space) is\r\nvery small.  Because of this, the number of electrons, $N$, in the Slater\r\ndeterminants is also small; $N$ has a maximum value of  20.  Next, use can be\r\nmade of the fact that no point-group operation can mix $\\alpha$ and $\\beta$\r\nelectrons.  This allows the integral to be split into two parts, each of which\r\nhas a maximum value  of $N$=10. Finally, remember that $N$ is the number of\r\nelectrons, not M.O.s, used in the active space.  A system of $N$ electrons has\r\nthe same symmetry as a system in which all the M.O.s which were occupied were\r\nreplaced with all the M.O.s which were not occupied (the positron\r\nequivalent)\\index{Positron equivalent}. (This assumes that if every M.O.\\ were\r\noccupied, then the state of the system would be totally symmetric.)   Using\r\nthis fact, we can replace the $N$ occupied M.O.s with $N'$ unoccupied M.O.s, if\r\n$N' < N$.\r\n\r\nWhen these three points are considered, we see that $N$ has a maximum value  of\r\n5 (for a system of 10 M.O.s).  Each case can be considered separately.\r\n\\begin{description}\r\n\\item{For $N$ = 1:}\r\n$$\r\n<\\Psi_i|R|\\Psi_i> = \\frac{1}{1}\\sum_{P=1}^{1} \\sum_{Q=1}^{1}(-1)^P(-1)^Q\r\nP\\prod_{k=1}^{1}Q\\prod_{l=1}^{1}\\chi_{kl}^{ii}\r\n$$\r\nor\r\n$$\r\n<\\Psi_i|R|\\Psi_i> = <\\psi_1^i|R|\\psi_1^i> = \\chi_{11}^{ii}.\r\n$$\r\n\\item{For $N$=2:}\r\n$$\r\n<\\Psi_i|R|\\Psi_j> = \\frac{1}{2!}\\sum_{P=1}^{2!} \\sum_{Q=1}^{2!}(-1)^P(-1)^Q\r\nP\\prod_{k=1}^{2}Q\\prod_{l=1}^{2}\\chi_{kl}^{ij}\r\n$$\r\nor \r\n$$\r\n<\\Psi_i|R|\\Psi_j> = <\\psi_1^i|R|\\psi_1^j>-<\\psi_2^i|R|\\psi_2^j>\r\n<\\psi_1^i|R|\\psi_2^j><\\psi_1^i|R|\\psi_2^j>\r\n$$\r\nor\r\n$$\r\n<\\Psi_a|R|\\Psi_a> = \\chi_{11}^{ij}\\chi_{22}^{ij}-\\chi_{12}^{ij}\\chi_{21}^{ij}.\r\n$$        \r\n\\item{For $N$=3:}\r\n$$\r\n<\\Psi_i|R|\\Psi_j> = \\frac{1}{3!}\\sum_{P=1}^{3!} \\sum_{Q=1}^{3!}(-1)^P(-1)^Q\r\n$$\r\n\\begin{eqnarray}\r\n<\\Psi_i|R|\\Psi_j>& = &\\ <\\psi_1^i|R|\\psi_1^j><\\psi_2^i|R|\\psi_2^j><\\psi_3^i|R|\\psi_3^j> \\nonumber   \\\\\r\n&&-<\\psi_1^i|R|\\psi_1^j><\\psi_2^i|R|\\psi_3^j><\\psi_3^i|R|\\psi_2^j> \\nonumber  \\\\\r\n&&-<\\psi_1^i|R|\\psi_2^j><\\psi_2^i|R|\\psi_1^j><\\psi_3^i|R|\\psi_3^j> \\nonumber  \\\\\r\n&&+<\\psi_1^i|R|\\psi_2^j><\\psi_2^i|R|\\psi_3^j><\\psi_3^i|R|\\psi_1^j> \\nonumber  \\\\\r\n&&+<\\psi_1^i|R|\\psi_3^j><\\psi_2^i|R|\\psi_1^j><\\psi_3^i|R|\\psi_2^j> \\nonumber  \\\\\r\n&&-<\\psi_1^i|R|\\psi_3^j><\\psi_2^i|R|\\psi_2^j><\\psi_3^i|R|\\psi_1^j>  \\nonumber\r\n\\end{eqnarray}\r\nor\r\n\\begin{eqnarray}\r\n<\\Psi_i|R|\\Psi_j>&=&\\chi_{11}^{ij}\\chi_{22}^{ij}\\chi_{33}^{ij}+\r\n                            \\chi_{12}^{ij}\\chi_{23}^{ij}\\chi_{31}^{ij}+\r\n                            \\chi_{13}^{ij}\\chi_{21}^{ij}\\chi_{32}^{ij} \\nonumber \\\\\r\n&&-\\chi_{11}^{ij}\\chi_{23}^{ij}\\chi_{32}^{ij}\r\n-\\chi_{12}^{ij}\\chi_{21}^{ij}\\chi_{33}^{ij}\r\n-\\chi_{13}^{ij}\\chi_{22}^{ij}\\chi_{31}^{ij}). \\nonumber\r\n\\end{eqnarray}\r\n\\end{description}\r\n\r\nFor higher numbers of electrons, the associated determinant is solved using\r\nstandard methods. \r\n\r\nThe total character, $<\\Psi_a|R|\\Psi_a>$, is obtained by multiplying the\r\ncharacters for the $\\alpha$ and $\\beta$ parts together:\r\n$$\r\n<\\Psi_a|R|\\Psi_a> = <\\Psi_a^{\\alpha}|R|\\Psi_a^{\\alpha}>\r\n<\\Psi_a^{\\beta}|R|\\Psi_a^{\\beta}>.\r\n$$\r\nIf the positron equivalent is taken for only one set of electrons, e.g.\\ either\r\nthe $\\alpha$ or the $\\beta$ set, but not both, then the  character has  to be\r\nmultiplied by the determinant of the M.O.\\ transform.\r\n\r\nThese expressions can then be used in \r\n$$\r\n\\chi_{R,a} =\\sum_i\\sum_jC_{ia}C_{ja}<\\Psi_i|R|\\Psi_j>.\r\n$$\r\nto give the expectation value for the state. Finally, if the state is\r\ndegenerate, the character is given by summing the components of the state.\r\n\r\nFor the atom, the \\mi{Russell-Saunders} coupling scheme can be reproduced. \r\nStates allowed are $S$, $P$, $D$, $F$, $G$, $H$, $I$, $K$, $L$, and $M$. This\r\nset is more than sufficient to allow all possible Russell-Saunders states\r\nspanned by a basis set of $s$, $p$, and $d$ orbitals to be represented. The\r\nhighest angular momentum achievable with such a basis set is 8, i.e. $L$. For\r\nsimpler atoms (ones with only a $s-p$ basis set) the allowed states are\r\n$p^0,p^6$: $^1S_g$,  $p^1,p^5$: $^2P_u$, $p^2,p^4$: $^1S_g + ^3\\!\\!P_g +\r\n^1\\!\\!D_g$,  $p^3$: $^4\\!S_u +^2\\!\\!P_u + ^2\\!\\!D_u$.\r\n\r\nFor the axial infinite groups, allowed states are: $\\Sigma$, $\\Pi$, $\\Delta$,\r\n$\\Phi$, and $\\Gamma$.  Even quite simple systems can achieve quite high angular\r\nmomentum, \\index{Angular momentum} thus acetylene, with a \\comp{C.I.=4}  (the\r\nHOMO $\\pi$ and LUMO $\\pi^*$) will contain a $^1\\Gamma_g$ state,  i.e., the\r\nangular momentum will be 4.\r\n\r\nAt present J-J coupling is not supported.\r\n\\index{Groups|)}\r\n", "meta": {"hexsha": "762a77092418175618880e2a5a88c6d2359efe42", "size": 23570, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "manuals/MOPAC2000_manual/t_symmetry.tex", "max_stars_repo_name": "openmopac/MOPAC-archive", "max_stars_repo_head_hexsha": "01510e44246de34a991529297a10bcf831336038", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-16T20:53:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T20:54:11.000Z", "max_issues_repo_path": "manuals/MOPAC2000_manual/t_symmetry.tex", "max_issues_repo_name": "openmopac/MOPAC-archive", "max_issues_repo_head_hexsha": "01510e44246de34a991529297a10bcf831336038", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "manuals/MOPAC2000_manual/t_symmetry.tex", "max_forks_repo_name": "openmopac/MOPAC-archive", "max_forks_repo_head_hexsha": "01510e44246de34a991529297a10bcf831336038", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.3045112782, "max_line_length": 103, "alphanum_fraction": 0.6834959695, "num_tokens": 7664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3160922334156005}}
{"text": "\\chapter[The Module System]{The Module System\\label{chapter:Modules}}\n\nThe module system extends the Calculus of Inductive Constructions\nproviding a convenient way to structure large developments as well as\na means of massive abstraction.\n%It is described in details in Judicael's thesis and Jacek's thesis\n\n\\section{Modules and module types}\n\n\\paragraph{Access path.} It is denoted by $p$, it can be either a module \nvariable $X$ or, if $p'$ is an access path and $id$ an identifier, then\n$p'.id$ is an access path.\n\n\\paragraph{Structure element.} It is denoted by \\elem\\ and is either a\ndefinition of a constant, an assumption, a definition of an inductive,\n a definition of a module, an alias of module or a module type abbreviation.\n\n\\paragraph{Structure expression.} It is denoted by $S$ and can be:\n\\begin{itemize}\n\\item an access path $p$\n\\item a plain structure $\\struct{\\nelist{\\elem}{;}}$\n\\item a functor $\\functor{X}{S}{S'}$, where $X$ is a module variable,\n  $S$ and $S'$ are structure expression\n\\item an application $S\\,p$, where $S$ is a structure expression and $p$ \nan access path \n\\item a refined structure $\\with{S}{p}{p'}$ or $\\with{S}{p}{t:T}$ where $S$\nis a structure expression, $p$ and $p'$ are access paths, $t$ is a term \nand $T$ is the type of $t$.\n\\end{itemize}\n\n\\paragraph{Module definition,} is written $\\Mod{X}{S}{S'}$ and\n consists of a module variable $X$, a module type\n$S$ which can be any structure expression and optionally a module implementation $S'$ \n which can be any structure expression except a refined structure.\n\n\\paragraph{Module alias,} is written $\\ModA{X}{p}$ and\n consists of a module variable $X$ and a module path $p$. \n\n\\paragraph{Module type abbreviation,} is written $\\ModType{Y}{S}$, where\n$Y$ is an identifier and $S$ is any structure expression .\n\n\n\\section{Typing Modules}\n\nIn order to introduce the typing system we first slightly extend\nthe syntactic class of terms and environments given in\nsection~\\ref{Terms}. The environments, apart from definitions of\nconstants and inductive types now also hold any other structure elements.\nTerms, apart from variables, constants and complex terms, \ninclude also access paths.\n\nWe also need additional typing judgments: \n\\begin{itemize}\n\\item \\WFT{E}{S}, denoting that a structure $S$ is well-formed, \n\n\\item \\WTM{E}{p}{S}, denoting that the module pointed by $p$ has type $S$ in\nenvironment $E$.\n\n\\item \\WEV{E}{S}{\\overline{S}}, denoting that a structure $S$ is evaluated to \na structure $\\overline{S}$ in weak head normal form.\n\n\\item \\WS{E}{S_1}{S_2}, denoting that a structure $S_1$ is a subtype of a\nstructure $S_2$.\n\n\\item \\WS{E}{\\elem_1}{\\elem_2}, denoting that a structure element\n  $\\elem_1$ is more precise that a structure element $\\elem_2$.\n\\end{itemize}\nThe rules for forming structures are the following:\n\\begin{description}\n\\item[WF-STR]\n\\inference{%\n  \\frac{\n    \\WF{E;E'}{}\n  }{%%%%%%%%%%%%%%%%%%%%%\n    \\WFT{E}{\\struct{E'}}\n  }\n}\n\\item[WF-FUN]\n\\inference{%\n  \\frac{\n    \\WFT{E;\\ModS{X}{S}}{\\overline{S'}}\n  }{%%%%%%%%%%%%%%%%%%%%%%%%%%\n    \\WFT{E}{\\functor{X}{S}{S'}}\n  }\n}\n\\end{description}\nEvaluation of structures to weak head normal form:\n\\begin{description}\n\\item[WEVAL-APP]\n\\inference{%\n  \\frac{\n    \\begin{array}{c}\n    \\WEV{E}{S}{\\functor{X}{S_1}{S_2}}~~~~~\\WEV{E}{S_1}{\\overline{S_1}}\\\\\n    \\WTM{E}{p}{S_3}\\qquad \\WS{E}{S_3}{\\overline{S_1}}\n    \\end{array}\n  }{%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    \\WEV{E}{S\\,p}{S_2\\{p/X,t_1/p_1.c_1,\\ldots,t_n/p_n.c_n\\}}\n  }\n}\n\\end{description}\nIn the last rule, $\\{t_1/p_1.c_1,\\ldots,t_n/p_n.c_n\\}$ is the resulting\n substitution from the inlining mechanism. We substitute in $S$ the\n inlined fields $p_i.c_i$ form $\\ModS{X}{S_1}$ by the corresponding delta-reduced term $t_i$ in $p$.\n\\begin{description}\n\\item[WEVAL-WITH-MOD]\n\\inference{%\n  \\frac{\n    \\begin{array}{c}\n    \\WEV{E}{S}{\\structe{\\ModS{X}{S_1}}}~~~~~\\WEV{E;\\elem_1;\\ldots;\\elem_i}{S_1}{\\overline{S_1}}\\\\\n    \\WTM{E}{p}{S_2}\\qquad \\WS{E;\\elem_1;\\ldots;\\elem_i}{S_2}{\\overline{S_1}}\n    \\end{array}\n  }{%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    \\begin{array}{c}\n    \\WEVT{E}{\\with{S}{x}{p}}{\\structes{\\ModA{X}{p}}{p/X}}\n    \\end{array}\n  }\n}\n\\item[WEVAL-WITH-MOD-REC]\n\\inference{%\n  \\frac{\n    \\begin{array}{c}\n    \\WEV{E}{S}{\\structe{\\ModS{X_1}{S_1}}}\\\\\n    \\WEV{E;\\elem_1;\\ldots;\\elem_i}{\\with{S_1}{p}{p_1}}{\\overline{S_2}}\n    \\end{array}\n  }{%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    \\begin{array}{c}\n    \\WEVT{E}{\\with{S}{X_1.p}{p_1}}{\\structes{\\ModS{X}{\\overline{S_2}}}{p_1/X_1.p}}\n    \\end{array}\n  }\n}\n\\item[WEVAL-WITH-DEF]\n\\inference{%\n  \\frac{\n    \\begin{array}{c}\n    \\WEV{E}{S}{\\structe{\\Assum{}{c}{T_1}}}\\\\\n    \\WS{E;\\elem_1;\\ldots;\\elem_i}{\\Def{}{c}{t}{T}}{\\Assum{}{c}{T_1}}\n    \\end{array}\n  }{%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    \\begin{array}{c}\n    \\WEVT{E}{\\with{S}{c}{t:T}}{\\structe{\\Def{}{c}{t}{T}}}\n    \\end{array}\n  }\n}\n\\item[WEVAL-WITH-DEF-REC]\n\\inference{%\n  \\frac{\n    \\begin{array}{c}\n    \\WEV{E}{S}{\\structe{\\ModS{X_1}{S_1}}}\\\\\n    \\WEV{E;\\elem_1;\\ldots;\\elem_i}{\\with{S_1}{p}{p_1}}{\\overline{S_2}}\n    \\end{array}\n  }{%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    \\begin{array}{c}\n    \\WEVT{E}{\\with{S}{X_1.p}{t:T}}{\\structe{\\ModS{X}{\\overline{S_2}}}}\n    \\end{array}\n  }\n}\n\n\\item[WEVAL-PATH-MOD]\n\\inference{%\n  \\frac{\n    \\begin{array}{c}\n    \\WEV{E}{p}{\\structe{ \\Mod{X}{S}{S_1}}}\\\\\n    \\WEV{E;\\elem_1;\\ldots;\\elem_i}{S}{\\overline{S}}\n   \\end{array}\n  }{%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    \\WEV{E}{p.X}{\\overline{S}}\n  }\n}\n\\inference{%\n  \\frac{\n    \\begin{array}{c}\n    \\WF{E}{}~~~~~~\\Mod{X}{S}{S_1}\\in E\\\\\n    \\WEV{E}{S}{\\overline{S}}\n   \\end{array}\n  }{%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    \\WEV{E}{X}{\\overline{S}}\n  }\n}\n\\item[WEVAL-PATH-ALIAS]\n\\inference{%\n  \\frac{\n    \\begin{array}{c}\n    \\WEV{E}{p}{\\structe{\\ModA{X}{p_1}}}\\\\\n    \\WEV{E;\\elem_1;\\ldots;\\elem_i}{p_1}{\\overline{S}}\n    \\end{array}\n  }{%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    \\WEV{E}{p.X}{\\overline{S}}\n  }\n}\n\\inference{%\n  \\frac{\n    \\begin{array}{c}\n      \\WF{E}{}~~~~~~~\\ModA{X}{p_1}\\in E\\\\\n      \\WEV{E}{p_1}{\\overline{S}}\n    \\end{array}\n  }{%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    \\WEV{E}{X}{\\overline{S}}\n  }\n}\n\\item[WEVAL-PATH-TYPE]\n\\inference{%\n  \\frac{\n    \\begin{array}{c}\n    \\WEV{E}{p}{\\structe{\\ModType{Y}{S}}}\\\\\n    \\WEV{E;\\elem_1;\\ldots;\\elem_i}{S}{\\overline{S}}\n    \\end{array}\n  }{%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    \\WEV{E}{p.Y}{\\overline{S}}\n  }\n}\n\\item[WEVAL-PATH-TYPE]\n\\inference{%\n  \\frac{\n    \\begin{array}{c}\n    \\WF{E}{}~~~~~~~\\ModType{Y}{S}\\in E\\\\\n    \\WEV{E}{S}{\\overline{S}}\n    \\end{array}\n  }{%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    \\WEV{E}{Y}{\\overline{S}}\n  }\n}\n\\end{description}\n Rules for typing module:\n\\begin{description}\n\\item[MT-EVAL]\n\\inference{%\n  \\frac{\n \\WEV{E}{p}{\\overline{S}}\n  }{%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    \\WTM{E}{p}{\\overline{S}}\n  }\n}\n\\item[MT-STR]\n\\inference{%\n  \\frac{\n    \\WTM{E}{p}{S}\n  }{%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    \\WTM{E}{p}{S/p}\n  }\n}\n\\end{description}\nThe last rule, called strengthening is used to make all module fields\nmanifestly equal to themselves. The notation $S/p$ has the following\nmeaning:\n\\begin{itemize}\n\\item if $S\\lra\\struct{\\elem_1;\\dots;\\elem_n}$ then\n  $S/p=\\struct{\\elem_1/p;\\dots;\\elem_n/p}$ where $\\elem/p$ is defined as\n  follows:\n  \\begin{itemize}\n  \\item $\\Def{}{c}{t}{T}/p\\footnote{Opaque definitions are processed as assumptions.} ~=~ \\Def{}{c}{t}{T}$\n  \\item $\\Assum{}{c}{U}/p ~=~ \\Def{}{c}{p.c}{U}$\n  \\item $\\ModS{X}{S}/p ~=~ \\ModA{X}{p.X}$\n  \\item $\\ModA{X}{p'}/p ~=~ \\ModA{X}{p'}$\n  \\item $\\Ind{}{\\Gamma_P}{\\Gamma_C}{\\Gamma_I}/p ~=~ \\Indp{}{\\Gamma_P}{\\Gamma_C}{\\Gamma_I}{p}$\n  \\item $\\Indpstr{}{\\Gamma_P}{\\Gamma_C}{\\Gamma_I}{p'}{p} ~=~ \\Indp{}{\\Gamma_P}{\\Gamma_C}{\\Gamma_I}{p'}$\n  \\end{itemize}\n\\item if $S\\lra\\functor{X}{S'}{S''}$ then $S/p=S$\n\\end{itemize}\nThe notation $\\Indp{}{\\Gamma_P}{\\Gamma_C}{\\Gamma_I}{p}$ denotes an\ninductive definition that is definitionally equal to the inductive\ndefinition in the module denoted by the path $p$. All rules which have\n$\\Ind{}{\\Gamma_P}{\\Gamma_C}{\\Gamma_I}$ as premises are also valid for \n$\\Indp{}{\\Gamma_P}{\\Gamma_C}{\\Gamma_I}{p}$. We give the formation rule\nfor $\\Indp{}{\\Gamma_P}{\\Gamma_C}{\\Gamma_I}{p}$ below as well as\nthe equality rules on inductive types and constructors. \\\\\n\nThe module subtyping rules:\n\\begin{description}\n\\item[MSUB-STR]\n\\inference{%\n  \\frac{\n    \\begin{array}{c}\n      \\WS{E;\\elem_1;\\dots;\\elem_n}{\\elem_{\\sigma(i)}}{\\elem'_i}\n                                  \\textrm{ \\ for } i=1..m \\\\\n      \\sigma : \\{1\\dots m\\} \\ra \\{1\\dots n\\} \\textrm{ \\ injective}\n    \\end{array}\n  }{\n    \\WS{E}{\\struct{\\elem_1;\\dots;\\elem_n}}{\\struct{\\elem'_1;\\dots;\\elem'_m}}\n  }\n}\n\\item[MSUB-FUN]\n\\inference{%       T_1 -> T_2 <: T_1' -> T_2'\n  \\frac{\n    \\WS{E}{\\overline{S_1'}}{\\overline{S_1}}~~~~~~~~~~\\WS{E;\\ModS{X}{S_1'}}{\\overline{S_2}}{\\overline{S_2'}}\n  }{%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    \\WS{E}{\\functor{X}{S_1}{S_2}}{\\functor{X}{S_1'}{S_2'}}\n  }\n}\n% these are derived rules\n% \\item[MSUB-EQ]\n% \\inference{%\n%   \\frac{\n%     \\WS{E}{T_1}{T_2}~~~~~~~~~~\\WTERED{}{T_1}{=}{T_1'}~~~~~~~~~~\\WTERED{}{T_2}{=}{T_2'}\n%   }{%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%     \\WS{E}{T_1'}{T_2'}\n%   }\n% }\n% \\item[MSUB-REFL]\n% \\inference{%\n%   \\frac{\n%     \\WFT{E}{T}\n%   }{\n%     \\WS{E}{T}{T}\n%   }\n% }\n\\end{description}\nStructure element subtyping rules:\n\\begin{description}\n\\item[ASSUM-ASSUM]\n\\inference{%\n  \\frac{\n    \\WTELECONV{}{T_1}{T_2}\n  }{\n    \\WSE{\\Assum{}{c}{T_1}}{\\Assum{}{c}{T_2}}\n  }\n}\n\\item[DEF-ASSUM]\n\\inference{%\n  \\frac{\n    \\WTELECONV{}{T_1}{T_2}\n  }{\n    \\WSE{\\Def{}{c}{t}{T_1}}{\\Assum{}{c}{T_2}}\n  }\n}\n\\item[ASSUM-DEF]\n\\inference{%\n  \\frac{\n    \\WTELECONV{}{T_1}{T_2}~~~~~~~~\\WTECONV{}{c}{t_2}\n  }{\n    \\WSE{\\Assum{}{c}{T_1}}{\\Def{}{c}{t_2}{T_2}}\n  }\n}\n\\item[DEF-DEF]\n\\inference{%\n  \\frac{\n    \\WTELECONV{}{T_1}{T_2}~~~~~~~~\\WTECONV{}{t_1}{t_2}\n  }{\n    \\WSE{\\Def{}{c}{t_1}{T_1}}{\\Def{}{c}{t_2}{T_2}}\n  }\n}\n\\item[IND-IND]\n\\inference{%\n  \\frac{\n    \\WTECONV{}{\\Gamma_P}{\\Gamma_P'}%\n    ~~~~~~~~\\WTECONV{\\Gamma_P}{\\Gamma_C}{\\Gamma_C'}%\n    ~~~~~~~~\\WTECONV{\\Gamma_P;\\Gamma_C}{\\Gamma_I}{\\Gamma_I'}%\n  }{\n    \\WSE{\\Ind{}{\\Gamma_P}{\\Gamma_C}{\\Gamma_I}}%\n        {\\Ind{}{\\Gamma_P'}{\\Gamma_C'}{\\Gamma_I'}}\n  }\n}\n\\item[INDP-IND]\n\\inference{%\n  \\frac{\n    \\WTECONV{}{\\Gamma_P}{\\Gamma_P'}%\n    ~~~~~~~~\\WTECONV{\\Gamma_P}{\\Gamma_C}{\\Gamma_C'}%\n    ~~~~~~~~\\WTECONV{\\Gamma_P;\\Gamma_C}{\\Gamma_I}{\\Gamma_I'}%\n  }{\n    \\WSE{\\Indp{}{\\Gamma_P}{\\Gamma_C}{\\Gamma_I}{p}}%\n        {\\Ind{}{\\Gamma_P'}{\\Gamma_C'}{\\Gamma_I'}}\n  }\n}\n\\item[INDP-INDP]\n\\inference{%\n  \\frac{\n    \\WTECONV{}{\\Gamma_P}{\\Gamma_P'}%\n    ~~~~~~\\WTECONV{\\Gamma_P}{\\Gamma_C}{\\Gamma_C'}%\n    ~~~~~~\\WTECONV{\\Gamma_P;\\Gamma_C}{\\Gamma_I}{\\Gamma_I'}%\n    ~~~~~~\\WTECONV{}{p}{p'}\n  }{\n    \\WSE{\\Indp{}{\\Gamma_P}{\\Gamma_C}{\\Gamma_I}{p}}%\n        {\\Indp{}{\\Gamma_P'}{\\Gamma_C'}{\\Gamma_I'}{p'}}\n  }\n}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\item[MOD-MOD]\n\\inference{%\n  \\frac{\n    \\WSE{S_1}{S_2}\n  }{\n    \\WSE{\\ModS{X}{S_1}}{\\ModS{X}{S_2}}\n  }\n}\n\\item[ALIAS-MOD]\n\\inference{%\n  \\frac{\n    \\WTM{E}{p}{S_1}~~~~~~~~\\WSE{S_1}{S_2}\n  }{\n    \\WSE{\\ModA{X}{p}}{\\ModS{X}{S_2}}\n  }\n}\n\\item[MOD-ALIAS]\n\\inference{%\n  \\frac{\n      \\WTM{E}{p}{S_2}~~~~~~~~\n      \\WSE{S_1}{S_2}~~~~~~~~\\WTECONV{}{X}{p}\n  }{\n    \\WSE{\\ModS{X}{S_1}}{\\ModA{X}{p}}\n  }\n}\n\\item[ALIAS-ALIAS]\n\\inference{%\n  \\frac{\n    \\WTECONV{}{p_1}{p_2}\n  }{\n    \\WSE{\\ModA{X}{p_1}}{\\ModA{X}{p_2}}\n  }\n}\n\\item[MODTYPE-MODTYPE]\n\\inference{%\n  \\frac{\n    \\WSE{S_1}{S_2}~~~~~~~~\\WSE{S_2}{S_1}\n  }{\n    \\WSE{\\ModType{Y}{S_1}}{\\ModType{Y}{S_2}}\n  }\n}\n\\end{description}\nNew environment formation rules\n\\begin{description}\n\\item[WF-MOD]\n\\inference{%\n  \\frac{\n    \\WF{E}{}~~~~~~~~\\WFT{E}{S}\n  }{\n    \\WF{E;\\ModS{X}{S}}{}\n  }\n}\n\\item[WF-MOD]\n\\inference{%\n  \\frac{\n\\begin{array}{c}\n  \\WS{E}{S_2}{S_1}\\\\\n  \\WF{E}{}~~~~~\\WFT{E}{S_1}~~~~~\\WFT{E}{S_2}\n\\end{array}\n  }{\n    \\WF{E;\\Mod{X}{S_1}{S_2}}{}\n  }\n}\n\n\\item[WF-ALIAS]\n\\inference{%\n  \\frac{\n    \\WF{E}{}~~~~~~~~~~~\\WTE{}{p}{S}\n  }{\n    \\WF{E,\\ModA{X}{p}}{}\n  }\n}\n\\item[WF-MODTYPE]\n\\inference{%\n  \\frac{\n    \\WF{E}{}~~~~~~~~~~~\\WFT{E}{S}\n  }{\n    \\WF{E,\\ModType{Y}{S}}{}\n  }\n}\n\\item[WF-IND]\n\\inference{%\n  \\frac{\n    \\begin{array}{c}\n      \\WF{E;\\Ind{}{\\Gamma_P}{\\Gamma_C}{\\Gamma_I}}{}\\\\\n      \\WT{E}{}{p:\\struct{\\elem_1;\\dots;\\elem_n;\\Ind{}{\\Gamma_P'}{\\Gamma_C'}{\\Gamma_I'};\\dots}}\\\\\n      \\WS{E}{\\Ind{}{\\Gamma_P'}{\\Gamma_C'}{\\Gamma_I'}}{\\Ind{}{\\Gamma_P}{\\Gamma_C}{\\Gamma_I}}\n    \\end{array}\n  }{%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n    \\WF{E;\\Indp{}{\\Gamma_P}{\\Gamma_C}{\\Gamma_I}{p}}{}\n  }\n}\n\\end{description}\nComponent access rules\n\\begin{description}\n\\item[ACC-TYPE]\n\\inference{%\n  \\frac{\n    \\WTEG{p}{\\struct{\\elem_1;\\dots;\\elem_i;\\Assum{}{c}{T};\\dots}}\n  }{\n    \\WTEG{p.c}{T}\n  }\n}\n\\\\\n\\inference{%\n  \\frac{\n    \\WTEG{p}{\\struct{\\elem_1;\\dots;\\elem_i;\\Def{}{c}{t}{T};\\dots}}\n  }{\n    \\WTEG{p.c}{T}\n  }\n}\n\\item[ACC-DELTA]\nNotice that the following rule extends the delta rule defined in\nsection~\\ref{delta}\n\\inference{%\n  \\frac{\n    \\WTEG{p}{\\struct{\\elem_1;\\dots;\\elem_i;\\Def{}{c}{t}{U};\\dots}}\n  }{\n    \\WTEGRED{p.c}{\\triangleright_\\delta}{t}\n  }\n}\n\\\\\nIn the rules below we assume $\\Gamma_P$ is $[p_1:P_1;\\ldots;p_r:P_r]$,\n  $\\Gamma_I$ is $[I_1:A_1;\\ldots;I_k:A_k]$, and $\\Gamma_C$ is\n  $[c_1:C_1;\\ldots;c_n:C_n]$\n\\item[ACC-IND]\n\\inference{%\n  \\frac{\n    \\WTEG{p}{\\struct{\\elem_1;\\dots;\\elem_i;\\Ind{}{\\Gamma_P}{\\Gamma_C}{\\Gamma_I};\\dots}}\n  }{\n    \\WTEG{p.I_j}{(p_1:P_1)\\ldots(p_r:P_r)A_j}\n  }\n}\n\\inference{%\n  \\frac{\n    \\WTEG{p}{\\struct{\\elem_1;\\dots;\\elem_i;\\Ind{}{\\Gamma_P}{\\Gamma_C}{\\Gamma_I};\\dots}}\n  }{\n    \\WTEG{p.c_m}{(p_1:P_1)\\ldots(p_r:P_r){C_m}{I_j}{(I_j~p_1\\ldots\n       p_r)}_{j=1\\ldots k}}\n  }\n}\n\\item[ACC-INDP]\n\\inference{%\n  \\frac{\n    \\WT{E}{}{p}{\\struct{\\elem_1;\\dots;\\elem_i;\\Indp{}{\\Gamma_P}{\\Gamma_C}{\\Gamma_I}{p'};\\dots}}\n  }{\n    \\WTRED{E}{}{p.I_i}{\\triangleright_\\delta}{p'.I_i}\n  }\n}\n\\inference{%\n  \\frac{\n    \\WT{E}{}{p}{\\struct{\\elem_1;\\dots;\\elem_i;\\Indp{}{\\Gamma_P}{\\Gamma_C}{\\Gamma_I}{p'};\\dots}}\n  }{\n    \\WTRED{E}{}{p.c_i}{\\triangleright_\\delta}{p'.c_i}\n  }\n}\n\n\\end{description}\n\n% %%% replaced by \\triangle_\\delta\n% Module path equality is a transitive and reflexive closure of the\n% relation generated by ACC-MODEQ and ENV-MODEQ.\n% \\begin{itemize}\n% \\item []MP-EQ-REFL\n% \\inference{%\n%   \\frac{\n%     \\WTEG{p}{T}\n%   }{\n%     \\WTEG{p}{p}\n%   }\n% }\n% \\item []MP-EQ-TRANS\n% \\inference{%\n%   \\frac{\n%     \\WTEGRED{p}{=}{p'}~~~~~~\\WTEGRED{p'}{=}{p''}\n%   }{\n%     \\WTEGRED{p'}{=}{p''}\n%   }\n% }\n\n% \\end{itemize}\n\n\n%%% Local Variables: \n%%% mode: latex\n%%% TeX-master: \"Reference-Manual\"\n%%% End: \n\n", "meta": {"hexsha": "2019a529fe11c6ad1c1aaa5992afe42d78ba8650", "size": 14781, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "presentations/coq-workshop-2014-coq/doc/refman/RefMan-modr.tex", "max_stars_repo_name": "JasonGross/test-broken-tar", "max_stars_repo_head_hexsha": "6b52b8532879df53386b0f5413485888a1aa886a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "presentations/coq-workshop-2014-coq/doc/refman/RefMan-modr.tex", "max_issues_repo_name": "JasonGross/test-broken-tar", "max_issues_repo_head_hexsha": "6b52b8532879df53386b0f5413485888a1aa886a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "presentations/coq-workshop-2014-coq/doc/refman/RefMan-modr.tex", "max_forks_repo_name": "JasonGross/test-broken-tar", "max_forks_repo_head_hexsha": "6b52b8532879df53386b0f5413485888a1aa886a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2074468085, "max_line_length": 107, "alphanum_fraction": 0.5508422975, "num_tokens": 5879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.3160424181481998}}
{"text": "\\documentclass{article}\r\n%\\usepackage[a4paper,margin=2.2cm,footskip=.5cm]{geometry}\r\n\\usepackage{fullpage}\r\n%-----------------Hyperlink Packages--------------------\r\n\\usepackage{hyperref}\r\n\\hypersetup{\r\n\t colorlinks   = true,\r\n     citecolor    = black,\r\n     linkcolor    = black,\r\n     urlcolor     = black\r\n}\r\n%-----------------Figure Packages--------------------\r\n\\usepackage{graphicx}                       % For figures\r\n\\usepackage{stfloats}\r\n\\usepackage{caption}\r\n\\usepackage[export]{adjustbox}\r\n\\usepackage[tight,footnotesize]{subfigure}  % Create subfigures, ie 1A, 1B\r\n%\\usepackage{epsfig} % for postscript graphics files\r\n%------------------Math Packages------------------------\r\n\\usepackage{amssymb,amsmath}\r\n\\usepackage{textcomp}\r\n\\usepackage{mdwmath}\r\n\\usepackage{mdwtab}\r\n\\usepackage{eqparbox}\r\n%------------------Table Packages-----------------------\r\n\\usepackage{rotating}                     % Used to rotate tables\r\n\\usepackage{array}                        % Fixed column widths for tables\r\n%-----------------Algorithm Packages--------------------\r\n\\usepackage{listings}                     % Source code\r\n\\usepackage{algorithm}                    % Pseudo Code\r\n\\usepackage[noend]{algpseudocode}\r\n%---------------------------------------------------------\r\n\r\n\\begin{document}\r\n\r\n\\title {\r\n\tDIP Final Project \\\\\r\n\tHaze Removal\r\n}\r\n\r\n\\author {\r\n\tQiuyi Zhang 12330402 \\\\\r\n\t\\href{mailto:joyeec9h3@gmail.com}{joyeec9h3@gmail.com}\r\n}\r\n\r\n\\date {\r\n\t\\today\r\n}\r\n\r\n\\maketitle\r\n\\tableofcontents\r\n\r\n\r\n\\section{Introduction}\r\n\r\n\\subsection{Haze Removal Using Dark Channel Prior}\r\nIn computer vision and computer graphics, the formation of a hazy image is usually described by the following model:\r\n\r\n$$\r\n\\mathbf{I}(\\mathbf{x}) = \\mathbf{J}(\\mathbf{x})t(\\mathbf{x}) + \\mathbf{A}(1 - t(\\mathbf{x}))\r\n$$\r\n\r\nwhere $\\mathbf{I}$ is the observed intensity, $\\mathbf{J}$ is the scene radiance, $\\mathbf{A}$ is the global atmospheric light, and $t$ is the medium transmission. With this model, the goal of haze removal is to recover $\\mathbf{J}$, $\\mathbf{A}$, and $t$ when $\\mathbf{I}$ is given.\r\n\r\nIn \\cite{he2009single}, He proposed an approach to use the dark channel prior for haze removal. For an image $\\mathbf{J}$, the dark channel of $\\mathbf{J}$ is defined as\r\n\r\n$$\r\nJ^{dark}(\\mathbf{x}) = min_{c \\in \\{r,g,b\\}}( min_{\\mathbf{y} \\in \\Omega(\\mathbf{x})}(J^c(\\mathbf{y})))\r\n$$\r\n\r\nWhen $\\mathbf{J}$ is a haze-free outdoor image, the intensity of $J^{dark}$ in the non-sky region is close to zero. Using this prior, the transmission can be estimated by:\r\n\r\n$$\r\n\\tilde{t}(\\mathbf{x}) = 1 - \\omega min_{c}( min_{\\mathbf{y} \\in \\Omega(\\mathbf{x})}(\\frac{I^c(\\mathbf{y})}{A^c}))\r\n$$\r\n\r\nwhere $\\omega \\in (0, 1]$ is a constant parameter for keeping a certain amount of haze to make the output more natural Here $min_{c}( min_{\\mathbf{y} \\in \\Omega(\\mathbf{x})}(\\frac{I^c(\\mathbf{y})}{A^c}))$ is actually the dark channel of the normalized haze image $\\frac{I^c(\\mathbf{y})}{A^c}$.\r\n\r\nTo automatically obtain $\\mathbf{A}$ from the input image, we can first pick the top $p\\%$ brightest pixels in the dark channel, then, for each color channel, we chose the one with the highest intensity in the input image $\\mathbf{I}$ as its atmospheric light.\r\n\r\nNow that we have $\\tilde{t}(\\mathbf{x})$, $\\mathbf{A}$ and $\\mathbf{I}$, we can recover the haze-free image with:\r\n\r\n$$\r\n\\mathbf{J}(\\mathbf{x}) = \\frac{\\mathbf{I}(\\mathbf{x}) - \\mathbf{A}}{max(\\tilde{t}(\\mathbf{x}),t_0)} + \\mathbf{A}\r\n$$\r\n\r\nwhere $t_0$ is a lower bound for $t$ to preserve a certain amount of haze in dense haze regions.\r\n\r\n\\subsection{Guided filter}\r\n\r\nSince a transmission map is just an alpha map, we can apply soft matting to refine the estimated transmission. An efficient approach, as proposed in \\cite{he2010guided}, is to use the input image $\\mathbf{I}$ to guide the filter $\\tilde{t}(\\mathbf{x})$.\r\n\r\nDefine $q$ as a linear transform of a color image $\\mathbf{I}$ in a window $\\omega_k$ with radius $r$ centered at the pixel $k$:\r\n\r\n$$\r\nq_i = \\mathbf{a}_k^T\\mathbf{I}_i + b_k, \\forall i \\in \\omega_k\r\n$$\r\n\r\nwhere $\\mathbf{I}_k$ is a $3 \\times 1$ color vector, $\\mathbf{a}_k$ is a $3 \\times 1$ coefficient vector, $b_k$ is a scalar coefficient. For a filter $p$, the coefficients $\\mathbf{a}$ and $b$ can be computed with:\r\n\r\n\\begin{align*}\r\n\\mathbf{a}_k &= (\\Sigma_k + \\epsilon U)^{-1}(\\frac{1}{|\\omega|}\\sum_{i \\in \\omega_k}\\mathbf{I}_i p_i - \\mu_k \\bar{p}_k) \\\\\r\nb_k &= \\bar{p}_k - \\mathbf{a}_k^T\\mu_k \\\\\r\nq_i &= \\bar{\\mathbf{a}}_i^T\\mathbf{I}_i + \\bar{b}_i\r\n\\end{align*}\r\n\r\nwhere $\\Sigma_k$ is the covariance matrix of $\\mathbf{I}$ in $\\omega_k$, $\\epsilon$ is regularization parameter preventing $\\mathbf{a}_k$ from being too large, $U$ is the $3 \\times 3$ identity matrix, $\\mu_k$ is the mean of $\\mathbf{I}$ in $\\omega_k$, $|\\omega|$ is the number of pixels in $\\omega_k$, and $\\bar{p}_k$ is the mean of $p$ in $\\omega_k$. Then, the resulting $q$ is the desired filter under the guidance of $\\mathbf{I}$.\r\n\r\n\\section{Implementation}\r\n\r\nAlgorithm~\\ref{alg:hr} describes how to remove the haze from the image using the dark channel prior. To refine the transmission map, we implement Algorithm~\\ref{alg:gf}.\r\n\r\n\\begin{algorithm}[H]\r\n\\centering\r\n\\caption{Haze Removal Using Dark Channel Prior}\r\n\\label{alg:hr}\r\n  \\begin{algorithmic}[1]\r\n    \\Function{Dehaze}{$\\mathbf{I}$, $t_{min}$, $A_{max}$, $w$, $p$, $\\omega$, $r$, $\\epsilon$}\r\n        \\Comment{$\\mathbf{I}$ is the hazy image}\r\n        \\State Compute $\\mathbf{I}^{dark}$ with $\\mathbf{I}^{dark}(\\mathbf{x}) = min_{c \\in \\{r,g,b\\}}( min_{\\mathbf{y} \\in \\Omega(\\mathbf{x})}(I^c(\\mathbf{y})))$\r\n        \\State Find the indexes $\\mathbf{D}$ for highest $p\\%$  pixels in $\\mathbf{I}^{dark}$\r\n        \\State Compute atmosphere light $\\mathbf{A}$ with $\\mathbf{A}_c = max_{\\mathbf{d} \\in  \\mathbf{D}}(\\mathbf{I}_c(\\mathbf{d}))$\r\n        \\State Threshold $\\mathbf{A}$ with $A_{max}$\r\n        \\State Estimate transmission $\\tilde{t}$ with $\\tilde{t}(\\mathbf{x}) \\gets 1 - \\omega min_{c}( min_{\\mathbf{y} \\in \\Omega(\\mathbf{x})}(\\frac{I^c(\\mathbf{y})}{A^c}))$\r\n        \\State $\\tilde{t} \\gets$ \\Call{Guided Filter}{$\\mathbf{I}$, $\\tilde{t}$, $r$, $\\epsilon$}\r\n        \\State Recover $\\mathbf{J}$ with $\\mathbf{J}(\\mathbf{x}) = \\frac{\\mathbf{I}(\\mathbf{x}) - \\mathbf{A}}{max(\\tilde{t}(\\mathbf{x}),t_0)} + \\mathbf{A}$\r\n      \\State \\Return $\\mathbf{J}$\r\n    \\EndFunction\r\n  \\end{algorithmic}\r\n\\end{algorithm}\r\n\r\n\\begin{algorithm}[H]\r\n\\centering\r\n\\caption{Guided Filter}\r\n\\label{alg:gf}\r\n  \\begin{algorithmic}[1]\r\n    \\Function{Guided Filter}{$\\mathbf{I}$, $p$, $r$, $\\epsilon$}\r\n        \\For{each pixel $k$ in $p$}\r\n\t        \\State $\\omega_k$ is the window with radius $r$ for pixel $k$\r\n\t        \\State Compute $\\Sigma_k$, the convariance matrix of $\\mathbf{I}$ in $\\omega_k$\r\n\t        \\State Compute $|\\omega|$, the number of pixels in $omega_k$\r\n\t        \\State Compute $\\mu_k$, the mean of $\\mathbf{I}$ in $\\omega_k$ \r\n\t        \\State Compute $\\bar{p}_k$, the mean of $p$ in $\\omega_k$\r\n\t        \\State $\\mathbf{a}_k = (\\Sigma_k + \\epsilon U)^{-1}(\\frac{1}{|\\omega|}\\sum_{i \\in \\omega_k}\\mathbf{I}_i p_i - \\mu_k \\bar{p}_k)$\r\n\t        \\State $b_k = \\bar{p}_k - \\mathbf{a}_k^T\\mu_k$\r\n\t        \\State $q_k = \\bar{\\mathbf{a}}_k^T\\mathbf{I}_k + \\bar{b}_k$\r\n        \\EndFor\r\n      \\Return $\\mathbf{q}$\r\n    \\EndFunction\r\n  \\end{algorithmic}\r\n\\end{algorithm}\r\n\r\n\r\n\\section{Results and Analysis}\r\n\r\nThe results in Figure~\\ref{fig:result1} -~\\ref{fig:result4} are generated with $t_{min} = 0.2, A_{max} = 220, w = 15, p=0.1, \\omega=0.95,r=40, \\epsilon=10^{-3}$. From top to bottom are the input hazy image, the dark channel, the estimated transmission map, the refined transmission map, the image dehazed with raw transmission map, and the image dehazed with refined transmission map.\r\n\r\nFrom the results, it is easy to see that this approach can remove most of the haze in the image. The refined transmission map, however, can lead to much better results than the raw estimates.\r\n\r\nSince generating the dark channel is somewhat similar to applying a min filter to the image, areas with low intensity in the dark channel will greatly affect its neighboring pixels. Therefore, when there are drastic transitions in the dark channel (e.g. between the sky/fog and salient objects), the area with low intensities will ``expand''. For example, in Figure~\\ref{fig:result1}, the twigs in the dark channel of the forest are much thicker than in the original image. The leaves with good visibility in the front have low values in the dark channel, resulting in those small squares (usually with the same size as the window) in the dark channel map. Since the raw transmission map is actually calculated with the dark channel of the normalized image, this effect directly leads to the translucent borders around the twigs in the image dehazed with this raw estimate. Other images with this kind of drastic transitions in the dark channel also have the same problems. For example, the distant cones in the second image and the leaves in the last image of Figure~\\ref{fig:result1}, the tall buildings in the first three images of Figure~\\ref{fig:result2}, the roofs in the first image and the trunk in the second image of Figure~\\ref{fig:result3}, etc. all have this kind of borders around them.\r\n\r\nFrom the results it is obvious to see that after guiding the transmission map with the original image, the refined transmission map preserves much more detail than the raw estimate. Most objects become distinguishable in this refined map, and the edges in the tranmission map are closer to those in the original image. Therefore, the images dehazed with this refined transmission map no longer have the weird borders as in those dehazed with the raw estimate.\r\n\r\nSince the haze will usually increase the brightness of the image (because they are usually white or gray-ish), the images with a large amount of haze will become relatively darker after dehazing, e.g. the first image in Figure~\\ref{fig:result1}, the first two images in Figure~\\ref{fig:result2},  the last image in Figure~\\ref{fig:result4}. The images with just a thin layer of haze will have a better contrast after dehazing, e.g. the fourth image in Figure~\\ref{fig:result1}, the fourth image in Figure~\\ref{fig:result2}, the second and the third image in Figure~\\ref{fig:result3}, and the first image in Figure~\\ref{fig:result4}\r\n\r\nDuring the experiment, we discover that the choice of parameters is crutial in the quality of haze removal. When there are sky regions in the image, $\\mathbf{A}$ tends to be large. In this case, we need a higher $t_{min}$ or lower $A_{min}$ to threshold the computation so as to restrict the recovered $\\mathbf{J}$ in a reasonable range. To make the guidance more accurate, $r$ should be larger than $w/2$. Larger $r$ can lead to better results, but it will also slow down the process.\r\n\r\n\\begin{figure}[H]\r\n    \\centering\r\n    \\begin{minipage}[b]{\\linewidth}\r\n        \\centering\r\n        \\includegraphics[height=0.18\\linewidth]{../img/canon7.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../img/cones.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../img/forest.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../img/flag.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../img/house-input.png}\r\n    \\end{minipage}\r\n    \\begin{minipage}[b]{\\linewidth}\r\n        \\centering\r\n        \\includegraphics[height=0.18\\linewidth]{../result/canon7-dark.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/cones-dark.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/forest-dark.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/flag-dark.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/house-input-dark.png}\r\n    \\end{minipage}\r\n    \\begin{minipage}[b]{\\linewidth}\r\n        \\centering\r\n        \\includegraphics[height=0.18\\linewidth]{../result/canon7-rawt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/cones-rawt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/forest-rawt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/flag-rawt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/house-input-rawt.png}\r\n    \\end{minipage}\r\n    \\begin{minipage}[b]{\\linewidth}\r\n        \\centering\r\n        \\includegraphics[height=0.18\\linewidth]{../result/canon7-refinedt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/cones-refinedt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/forest-refinedt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/flag-refinedt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/house-input-refinedt.png}\r\n    \\end{minipage}\r\n    \\begin{minipage}[b]{\\linewidth}\r\n        \\centering\r\n        \\includegraphics[height=0.18\\linewidth]{../result/canon7-radiance-rawt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/cones-radiance-rawt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/forest-radiance-rawt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/flag-radiance-rawt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/house-input-radiance-rawt.png}\r\n    \\end{minipage}\r\n    \\begin{minipage}[b]{\\linewidth}\r\n        \\centering\r\n        \\includegraphics[height=0.18\\linewidth]{../result/canon7-radiance-refinedt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/cones-radiance-refinedt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/forest-radiance-refinedt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/flag-radiance-refinedt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/house-input-radiance-refinedt.png}\r\n    \\end{minipage}\r\n    \\caption{From top to bottom: input hazy image, dark channel, estimated transmission map, refined transmission map, image dehazed with raw estimate, image dehazed with refined estimate}\r\n    \\label{fig:result1}\r\n\\end{figure}\r\n\r\n\\begin{figure}[H]\r\n    \\centering\r\n    \\begin{minipage}[b]{\\linewidth}\r\n        \\centering\r\n        \\includegraphics[height=0.18\\linewidth]{../img/IMG_8763.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../img/IMG_8766.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../img/ny17_photo.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../img/pumpkins.jpg}\r\n    \\end{minipage}\r\n    \\begin{minipage}[b]{\\linewidth}\r\n        \\centering\r\n        \\includegraphics[height=0.18\\linewidth]{../result/IMG_8763-dark.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/IMG_8766-dark.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/ny17_photo-dark.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/pumpkins-dark.jpg}\r\n    \\end{minipage}\r\n    \\begin{minipage}[b]{\\linewidth}\r\n        \\centering\r\n        \\includegraphics[height=0.18\\linewidth]{../result/IMG_8763-rawt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/IMG_8766-rawt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/ny17_photo-rawt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/pumpkins-rawt.jpg}\r\n    \\end{minipage}\r\n    \\begin{minipage}[b]{\\linewidth}\r\n        \\centering\r\n        \\includegraphics[height=0.18\\linewidth]{../result/IMG_8763-refinedt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/IMG_8766-refinedt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/ny17_photo-refinedt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/pumpkins-refinedt.jpg}\r\n    \\end{minipage}\r\n    \\begin{minipage}[b]{\\linewidth}\r\n        \\centering\r\n        \\includegraphics[height=0.18\\linewidth]{../result/IMG_8763-radiance-rawt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/IMG_8766-radiance-rawt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/ny17_photo-radiance-rawt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/pumpkins-radiance-rawt.jpg}\r\n    \\end{minipage}\r\n    \\begin{minipage}[b]{\\linewidth}\r\n        \\centering\r\n        \\includegraphics[height=0.18\\linewidth]{../result/IMG_8763-radiance-refinedt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/IMG_8766-radiance-refinedt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/ny17_photo-radiance-refinedt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/pumpkins-radiance-refinedt.jpg}\r\n    \\end{minipage}\r\n    \\caption{From top to bottom: input hazy image, dark channel, estimated transmission map, refined transmission map, image dehazed with raw estimate, image dehazed with refined estimate}\r\n    \\label{fig:result2}\r\n\\end{figure}\r\n\r\n\\begin{figure}[H]\r\n    \\centering\r\n    \\begin{minipage}[b]{\\linewidth}\r\n        \\centering\r\n        \\includegraphics[height=0.18\\linewidth]{../img/tiananmen1.png}\r\n        \\includegraphics[height=0.18\\linewidth]{../img/swan.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../img/toys.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../img/ny12_photo.jpg}\r\n    \\end{minipage}\r\n    \\begin{minipage}[b]{\\linewidth}\r\n        \\centering\r\n        \\includegraphics[height=0.18\\linewidth]{../result/tiananmen1-dark.png}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/swan-dark.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/toys-dark.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/ny12_photo-dark.jpg}\r\n    \\end{minipage}\r\n    \\begin{minipage}[b]{\\linewidth}\r\n        \\centering\r\n        \\includegraphics[height=0.18\\linewidth]{../result/tiananmen1-rawt.png}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/swan-rawt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/toys-rawt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/ny12_photo-rawt.jpg}\r\n    \\end{minipage}\r\n    \\begin{minipage}[b]{\\linewidth}\r\n        \\centering\r\n        \\includegraphics[height=0.18\\linewidth]{../result/tiananmen1-refinedt.png}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/swan-refinedt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/toys-refinedt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/ny12_photo-refinedt.jpg}\r\n    \\end{minipage}\r\n    \\begin{minipage}[b]{\\linewidth}\r\n        \\centering\r\n        \\includegraphics[height=0.18\\linewidth]{../result/tiananmen1-radiance-rawt.png}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/swan-radiance-rawt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/toys-radiance-rawt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/ny12_photo-radiance-rawt.jpg}\r\n    \\end{minipage}\r\n    \\begin{minipage}[b]{\\linewidth}\r\n        \\centering\r\n        \\includegraphics[height=0.18\\linewidth]{../result/tiananmen1-radiance-refinedt.png}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/swan-radiance-refinedt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/toys-radiance-refinedt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/ny12_photo-radiance-refinedt.jpg}\r\n    \\end{minipage}\r\n    \\caption{From top to bottom: input hazy image, dark channel, estimated transmission map, refined transmission map, image dehazed with raw estimate, image dehazed with refined estimate}\r\n    \\label{fig:result3}\r\n\r\n\\end{figure}\r\n\r\n\r\n\\begin{figure}[H]\r\n    \\centering\r\n    \\begin{minipage}[b]{\\linewidth}\r\n        \\centering\r\n        \\includegraphics[height=0.18\\linewidth]{../img/stadium1.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../img/yellowmountain.jpg}\r\n    \\end{minipage}\r\n    \\begin{minipage}[b]{\\linewidth}\r\n        \\centering\r\n        \\includegraphics[height=0.18\\linewidth]{../result/stadium1-dark.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/yellowmountain-dark.jpg}\r\n    \\end{minipage}\r\n    \\begin{minipage}[b]{\\linewidth}\r\n        \\centering\r\n        \\includegraphics[height=0.18\\linewidth]{../result/stadium1-rawt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/yellowmountain-rawt.jpg}\r\n    \\end{minipage}\r\n    \\begin{minipage}[b]{\\linewidth}\r\n        \\centering\r\n        \\includegraphics[height=0.18\\linewidth]{../result/stadium1-refinedt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/yellowmountain-refinedt.jpg}\r\n    \\end{minipage}\r\n    \\begin{minipage}[b]{\\linewidth}\r\n        \\centering\r\n        \\includegraphics[height=0.18\\linewidth]{../result/stadium1-radiance-rawt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/yellowmountain-radiance-rawt.jpg}\r\n    \\end{minipage}\r\n    \\begin{minipage}[b]{\\linewidth}\r\n        \\centering\r\n        \\includegraphics[height=0.18\\linewidth]{../result/stadium1-radiance-refinedt.jpg}\r\n        \\includegraphics[height=0.18\\linewidth]{../result/yellowmountain-radiance-refinedt.jpg}\r\n    \\end{minipage}\r\n    \\caption{From top to bottom: input hazy image, dark channel, estimated transmission map, refined transmission map, image dehazed with raw estimate, image dehazed with refined estimate}\r\n    \\label{fig:result4}\r\n\\end{figure}\r\n\r\n\\section{Discussion}\r\n\r\nIn the sky region, $\\tilde{t} \\to 0$ and $A^c \\to L - 1$. Therefore the equation:\r\n\r\n$$\r\n\\mathbf{J}(\\mathbf{x}) = \\frac{\\mathbf{I}(\\mathbf{x}) - \\mathbf{A}}{max(\\tilde{t}(\\mathbf{x}),t_0)} + \\mathbf{A}\r\n$$\r\n\r\nis prone to error in images with sky regions. One possible solution is to set a higher $t_0$ than the one ($0.1$) suggested in \\cite{he2009single}. Another solution is to set a lower $A_max$ (which is not mentioned in \\cite{he2009single}). For different images, we need different $t_0$ and $A_max$ to produce ideal results. Some results with different configuration of  $t_0$ and $A_max$ are listed in Figure~\\ref{fig:sp1} -\\ref{fig:sp4}.\r\n\r\n\\begin{figure}[htp]\r\n    \\centering\r\n    \\begin{minipage}[b]{0.319\\linewidth}\r\n        \\centering\r\n        \\includegraphics[width=\\linewidth]{../img/IMG_8763.jpg}\r\n    \\end{minipage}\r\n    \\begin{minipage}[b]{0.66\\linewidth}\r\n       \\centering\r\n        \\includegraphics[width=0.24\\linewidth]{../result/IMG_8763-refinedt.jpg}\r\n        \\includegraphics[width=0.24\\linewidth]{../result/IMG_8763-refinedt-20-170-15-40.jpg}\r\n        \\includegraphics[width=0.24\\linewidth]{../result/IMG_8763-refinedt-50-190-15-40.jpg}\r\n        \\includegraphics[width=0.24\\linewidth]{../result/IMG_8763-refinedt-50-220-15-40.jpg}\r\n        \\\\\r\n        \\includegraphics[width=0.24\\linewidth]{../result/IMG_8763-radiance-refinedt.jpg}\r\n        \\includegraphics[width=0.24\\linewidth]{../result/IMG_8763-radiance-refinedt-20-170-15-40.jpg}\r\n        \\includegraphics[width=0.24\\linewidth]{../result/IMG_8763-radiance-refinedt-50-190-15-40.jpg}\r\n        \\includegraphics[width=0.24\\linewidth]{../result/IMG_8763-radiance-refinedt-50-220-15-40.jpg}\r\n    \\end{minipage}\r\n    \r\n    \\captionsetup{singlelinecheck=off}\r\n    \\caption{Leftmost image: the input hazy image. On the right side, the top row are tranmission maps with\r\n        $t_{min} = 0.2, A_{max} = 220$;\r\n        $t_{min} = 0.2, A_{max} = 170$;\r\n        $t_{min} = 0.5, A_{max} = 190$;\r\n        $t_{min} = 0.5, A_{max} = 220$;\r\n        the bottom row are corresponding dehazed images.\r\n    }\r\n    \\label{fig:sp1}\r\n\\end{figure}\r\n\r\n\\begin{figure}[h]\r\n    \\centering\r\n    \\begin{minipage}[b]{0.319\\linewidth}\r\n        \\centering\r\n        \\includegraphics[width=\\linewidth]{../img/IMG_8766.jpg}\r\n    \\end{minipage}\r\n    \\begin{minipage}[b]{0.66\\linewidth}\r\n       \\centering\r\n        \\includegraphics[width=0.24\\linewidth]{../result/IMG_8766-refinedt.jpg}\r\n        \\includegraphics[width=0.24\\linewidth]{../result/IMG_8766-refinedt-20-170-15-40.jpg}\r\n        \\includegraphics[width=0.24\\linewidth]{../result/IMG_8766-refinedt-50-190-15-40.jpg}\r\n        \\includegraphics[width=0.24\\linewidth]{../result/IMG_8766-refinedt-50-220-15-40.jpg}\r\n        \\\\\r\n        \\includegraphics[width=0.24\\linewidth]{../result/IMG_8766-radiance-refinedt.jpg}\r\n        \\includegraphics[width=0.24\\linewidth]{../result/IMG_8766-radiance-refinedt-20-170-15-40.jpg}\r\n        \\includegraphics[width=0.24\\linewidth]{../result/IMG_8766-radiance-refinedt-50-190-15-40.jpg}\r\n        \\includegraphics[width=0.24\\linewidth]{../result/IMG_8766-radiance-refinedt-50-220-15-40.jpg}\r\n    \\end{minipage}\r\n    \r\n    \\captionsetup{singlelinecheck=off}\r\n    \\caption{Leftmost image: the input hazy image. On the right side, the top row are tranmission maps with\r\n        $t_{min} = 0.2, A_{max} = 220$;\r\n        $t_{min} = 0.2, A_{max} = 170$;\r\n        $t_{min} = 0.5, A_{max} = 190$;\r\n        $t_{min} = 0.5, A_{max} = 220$;\r\n        the bottom row are corresponding dehazed images.\r\n    }\r\n    \\label{fig:sp2}\r\n\\end{figure}\r\n\r\n\\begin{figure}[H]\r\n    \\centering\r\n    \\begin{minipage}[b]{0.319\\linewidth}\r\n        \\centering\r\n        \\includegraphics[width=\\linewidth]{../img/ny17_photo.jpg}\r\n    \\end{minipage}\r\n    \\begin{minipage}[b]{0.66\\linewidth}\r\n       \\centering\r\n        \\includegraphics[width=0.24\\linewidth]{../result/ny17_photo-refinedt.jpg}\r\n        \\includegraphics[width=0.24\\linewidth]{../result/ny17_photo-refinedt-20-170-15-40.jpg}\r\n        \\includegraphics[width=0.24\\linewidth]{../result/ny17_photo-refinedt-50-190-15-40.jpg}\r\n        \\includegraphics[width=0.24\\linewidth]{../result/ny17_photo-refinedt-50-220-15-40.jpg}\r\n        \\\\\r\n        \\includegraphics[width=0.24\\linewidth]{../result/ny17_photo-radiance-refinedt.jpg}\r\n        \\includegraphics[width=0.24\\linewidth]{../result/ny17_photo-radiance-refinedt-20-170-15-40.jpg}\r\n        \\includegraphics[width=0.24\\linewidth]{../result/ny17_photo-radiance-refinedt-50-190-15-40.jpg}\r\n        \\includegraphics[width=0.24\\linewidth]{../result/ny17_photo-radiance-refinedt-50-220-15-40.jpg}\r\n    \\end{minipage}\r\n    \r\n    \\captionsetup{singlelinecheck=off}\r\n    \\caption{Leftmost image: the input hazy image. On the right side, the top row are tranmission maps with\r\n        $t_{min} = 0.2, A_{max} = 220$;\r\n        $t_{min} = 0.2, A_{max} = 170$;\r\n        $t_{min} = 0.5, A_{max} = 190$;\r\n        $t_{min} = 0.5, A_{max} = 220$;\r\n        the bottom row are corresponding dehazed images.\r\n    }\r\n    \\label{fig:sp3}\r\n\\end{figure}\r\n\r\n\\begin{figure}[H]\r\n    \\centering\r\n    \\begin{minipage}[b]{0.319\\linewidth}\r\n        \\centering\r\n        \\includegraphics[width=\\linewidth]{../img/tiananmen1.png}\r\n    \\end{minipage}\r\n    \\begin{minipage}[b]{0.66\\linewidth}\r\n       \\centering\r\n        \\includegraphics[width=0.24\\linewidth]{../result/tiananmen1-refinedt.png}\r\n        \\includegraphics[width=0.24\\linewidth]{../result/tiananmen1-refinedt-20-170-15-40.png}\r\n        \\includegraphics[width=0.24\\linewidth]{../result/tiananmen1-refinedt-50-190-15-40.png}\r\n        \\includegraphics[width=0.24\\linewidth]{../result/tiananmen1-refinedt-50-220-15-40.png}\r\n        \\\\\r\n        \\includegraphics[width=0.24\\linewidth]{../result/tiananmen1-radiance-refinedt.png}\r\n        \\includegraphics[width=0.24\\linewidth]{../result/tiananmen1-radiance-refinedt-20-170-15-40.png}\r\n        \\includegraphics[width=0.24\\linewidth]{../result/tiananmen1-radiance-refinedt-50-190-15-40.png}\r\n        \\includegraphics[width=0.24\\linewidth]{../result/tiananmen1-radiance-refinedt-50-220-15-40.png}\r\n    \\end{minipage}\r\n   \r\n    \\captionsetup{singlelinecheck=off}\r\n    \\caption{Leftmost image: the input hazy image. On the right side, the top row are tranmission maps with\r\n        $t_{min} = 0.2, A_{max} = 220$;\r\n        $t_{min} = 0.2, A_{max} = 170$;\r\n        $t_{min} = 0.5, A_{max} = 190$;\r\n        $t_{min} = 0.5, A_{max} = 220$;\r\n        the bottom row are corresponding dehazed images.\r\n    }\r\n     \\label{fig:sp4}\r\n\\end{figure}\r\n\\bibliography{dehaze}\r\n\r\n\\bibliographystyle{acm}\r\n\r\n\\end{document}", "meta": {"hexsha": "1293274b8448f661756d74ae87152c6afd76865a", "size": 27677, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "code/iodh/combined/dark-channel-prior-dehazing/doc/report.tex", "max_stars_repo_name": "guanlongzhao/dehaze", "max_stars_repo_head_hexsha": "c76346584f8d76502aa854ad9d7e06135ca77bcf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2018-07-05T01:15:24.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-23T12:03:51.000Z", "max_issues_repo_path": "code/iodh/combined/dark-channel-prior-dehazing/doc/report.tex", "max_issues_repo_name": "TAMU-VITA/dehaze", "max_issues_repo_head_hexsha": "c76346584f8d76502aa854ad9d7e06135ca77bcf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-01-12T07:08:20.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-02T11:13:58.000Z", "max_forks_repo_path": "code/iodh/combined/dark-channel-prior-dehazing/doc/report.tex", "max_forks_repo_name": "guanlongzhao/dehaze", "max_forks_repo_head_hexsha": "c76346584f8d76502aa854ad9d7e06135ca77bcf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-07-06T02:19:31.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-02T15:21:43.000Z", "avg_line_length": 56.5991820041, "max_line_length": 1301, "alphanum_fraction": 0.6682082596, "num_tokens": 8426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621764862150636, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3160424099006575}}
{"text": "\\chapter{Efficient solution of the linear systems}\n\\chaptermark{Solution of linear systems}\n\\label{sec:solution-strategies}\n\nWhen we apply implicit time integration schemes, a FEM spatial discretisation and the Newton-Raphson method for linearisation (as discussed in \\cref{sec:time-discretisation,sec:galerk-meth-llg}) to the LLG equation we are left with the problem of solving a sequence of large sparse linear systems to obtain the approximate solution.\nWith the addition of FEM/BEM for calculation of magnetostatic fields (as discussed in \\cref{sec:hybr-finit-elem}), the linear systems to be solved become larger and more complex.\nIn this \\thisref{sec:solution-strategies} we discuss solution strategies for these systems.\n\nIn \\cref{sec:llg-only-system} we first discuss the solution of the systems required in the calculation of the magnetostatic field assuming the magnetisation is known.\nWe then discuss methods of solving the linear systems for the LLG equation assuming the magnetostatic field is known.\nThis is non-trivial because of the inclusion of the dense BEM matrix.\n\nIn \\cref{sec:solut-coupl-syst} we describe two efficient methods for the solution of the LLG equation with magnetostatics: a ``monolithic'' (\\ie fully coupled) approach and a semi-implicit approach.\nThe semi-implicit approach breaks the problem into a sequence of easily solved linear systems but at the cost of modifying the time integration scheme.\nThe monolithic approach uses efficient iterative methods to solve the full linear system and preserves all properties of the time integration scheme, such as stability and geometric integration properties.\nIn particular the energy conservation property of IMR requires the use of a monolithic approach (see \\cref{sec:proof-energy-prop}).\nExcept for the simplest preconditioner, \\cref{eq:90}, the preconditioners for the monolithic approach are novel.\n\nFinally, in \\cref{sec:numer-exper-fem-bem-systems}, we present some numerical experiments demonstrating the effectiveness of the proposed linear solvers for the systems resulting from both the semi-implicit and monolithic approaches.\n\n\n\n\\section{Solution of decoupled systems}\n\\label{sec:llg-only-system}\n\nIn \\thisref{sec:llg-only-system} we consider the solution of the magnetostatic and LLG problems in isolation (\\ie the LLG problem is solved assuming that the magnetostatic field is a known function and vice-versa).\nSuch methods are important building blocks for the solution of the coupled system.\n\nFirstly we consider the two linear systems solved in the magnetostatic field calculations: these are both Poisson systems (see \\cref{eq:phi-bem-continuous} and \\cref{eq:poisson-jacobian}), which are well studied.\nOne efficent and robust method for solving Poisson systems on unstructured grids is to use the method of conjugate gradients (CG) with algebraic multigrid (AMG) as a preconditioner \\cite{Henson2002}.\n\nNote that the matrices involved in the Poisson systems do not depend on $\\phim$, $\\phione$ or $\\mv$ (\\ie the Poisson problems are linear).\nThis means that when solving these parts of the problem the Newton-Raphson iteration is not required (or if used it will converge in a single iteration assuming that the linear solve is sufficiently accurate).\nAlso the Poisson matrices only depend on the geometry and so can be computed once and stored for reuse throughout the duration of the simulation (and similarly for the coarsening information required by the AMG preconditioner).\n\n\nNow we focus on the sequence of linear systems resulting from solving the LLG equation with the Newton-Raphson method, \\cref{eq:llg-jacobian}.\nThere do not appear to be any solvers which are efficient, robust and scale optimally with matrix size in the literature.\nWe try two solvers in our implementation, unfortunately neither are expected to be efficient for large matrix sizes and large time steps.\n\nThe first method used is a direct solve by LU decomposition.\nAs discussed in \\cref{sec:direct-methods} this method is extremely robust but is very slow for large matrices, particularly for problems in three spatial dimensions.\n\nThe second method is to use a Krylov solver preconditioned by an incomplete LU decomposition (ILU), inspired by \\cite{Suess2002}.\nThis method is expected to be efficient for medium sized problems and/or small time steps, especially in 2D or thin film problems where the FEM nodes are less coupled.\nHowever the effectiveness is strongly dependent on the diagonal dominance of the matrix.\nAs the volume of the elements decreases or the time step size increases the matrix becomes less diagonally dominant and the effectiveness of the preconditioner will decrease.\nHence this method is not expected to scale optimally to fine meshes or to be very robust with respect to varying parameters.\nThis method is used by both \\nmag \\cite{fangor-in-viva} and \\magpar.\\footnote{See \\texttt{src/llg/precond.c} line 271 in the \\magpar version 0.9 source code.}\n\n\\section[Solution of the coupled system]{Solution of the coupled LLG-magnetostatics system}\n\\label{sec:solut-coupl-syst}\n\nWe now consider the solution of the combined LLG and FEM/BEM magnetostatics system.\nUnlike typical FEM computations, these linear systems are not entirely sparse: the BEM matrix, $\\bm$, (derived in \\cref{sec:discretisation}, \\cref{eq:17}) appears as a dense block in the Jacobian.\nIn this \\thisref{sec:solut-coupl-syst} we describe two approaches to efficiently solve the resulting non-linear system despite this issue.\n\nIn \\cref{sec:semi-implicit-bem} we describe the first approach which involves replacing our implicit time integration scheme with an ad-hoc semi-implicit version which handles the magnetostatic calculation explicitly.\nThis means that only decoupled solves for $\\phione$, $\\phi$ and $\\mv$ are required at each time step, and the dense block, $\\bm$, only appears as a matrix-vector multiply.\nHowever it also means that we are no longer using the time integration methods discussed in \\cref{sec:some-implicit-time-integrators}, instead we are using some new scheme.\n\nThe second approach, described in \\cref{sec:fully-implicit-bem}, is to construct a linear solver which can efficiently handle the dense block.\nWe present a novel solver which consists of a Krylov solver combined with a preconditioner and an efficient representation of the BEM block.\nThis approach has the benefit that all of the properties of the original time integration schemes carry over to the coupled problem.\nIn particular when using this approach the IMR retains the energy property described in \\cref{sec:proof-energy-prop}, which is the most interesting of its geometrical integration properties.\\footnote{A number of integration schemes can obtain length conservation: Cayley transform methods \\cite{Lewis2003}, semi-analytical methods \\cite{Wiele2010} and various types of semi-implicit midpoint rule methods \\cite{Spargo2003,Serpico2001,Mentink2010} (including the one described in \\cref{sec:semi-implicit-bem}).}\nAdditionally it may be useful for stochastic problems (\\ie when thermal fields are involved, see \\cref{sec:temperature-effects}), since in this case only a few time integration schemes are known to converge to the correct solution.\nThe implicit midpoint rule is one of these schemes, but any semi-implicit modification is likely to remove this property \\cite{DAquino2006}.\n\nBefore describing these approaches in more detail, we briefly discuss the implementation of the monolithic coupling between the LLG and magnetostatic problems, and the structure of the resulting Jacobian.\n\n\\subsection{Residuals and Jacobian for the monolithically coupled system}\n\\label{sec:bem-jacobian-structure}\n\nAs mentioned in \\cref{sec:discretisation} the pair of potentials used in the FEM/BEM method is similar to that of the simplified magnetostatic potential discussed in \\cref{sec:galerk-meth-llg}.\nThere are two differences: the first is that there is no coupling from the auxiliary potential $\\phione$ to the LLG equation, and hence no corresponding block in the full Jacobian.\n\nThe second difference is that there is an additional coupling between the boundary values of $\\phione$ and the boundary values of $\\phim$.\nThis coupling between the BEM part (a collocation method) and the FEM part (a Galerkin method) is implemented using the following residual vector:\n\\newcommand{\\rphimb}{\\rphi_\\boundd}\n\\begin{equation}\n  \\rphimb(\\phimdis_\\boundd, \\phionedis_\\boundd) = \\bm \\phionedis_\\boundd - \\phimdis_\\boundd,\n  \\label{eq:89}\n\\end{equation}\nwhere $\\mydiscrete{x}_\\boundd$ denotes the vector of values of $x$ at the boundary nodes.\nThis residual is included as normal in the non-linear solve and simply enforces the condition $\\phimdis_\\boundd = \\bm \\phionedis_\\boundd$ from \\cref{eq:10}.\nNote that we cannot enforce the condition in the standard way for Dirichlet boundary conditions (by pinning the values at the boundary nodes to the appropriate values) because the condition is obtained as part of the solve.\n\nA natural consequence of \\cref{eq:89} is that the BEM matrix is a block of the Jacobian:\n\\begin{equation}\n  \\pd{\\rphimb}{\\phionedis_\\boundd} = \\bm,\n  \\label{eq:92}\n\\end{equation}\nwhere we have again used the notation that $\\pd{\\av}{\\bv}$ is the Jacobian of the derivatives of $\\av$ with respect to $\\bv$, as in \\cref{eq:jac-def}.\nAlso note that the diagonal Jacobian block for the boundary values of $\\phim$ is simply the negative of the identity matrix\n\\begin{equation}\n  \\pd{\\rphimb}{\\phimdis_\\boundd} = -\\Idm.\n  \\label{eq:91}\n\\end{equation}\n\n\\newcommand{\\Amm}{\\Am_\\phim}\n\\newcommand{\\Amu}{\\Am_\\phione}\n\\newcommand{\\zm}{0}\n\\newcommand{\\Abound}{\\Am_{\\phim\\boundd}}\n\n\\newcommand{\\scalemath}[2]{\\scalebox{#1}{\\begin{math} {#2} \\end{math}}}\n\n\\newcommand{\\Aprime}{\\scalemath{0.5}{\\begin{matrix} \\Amm     & \\Abound \\\\ \\zm      & -\\Idm \\end{matrix}}}\n\\newcommand{\\Gprime}{\\scalemath{0.5}{\\begin{matrix} \\zm  & \\zm \\\\ \\zm  & \\bm \\end{matrix}}}\n\\newcommand{\\Qprime}{\\scalemath{0.5}{\\begin{matrix} \\Qm \\\\ \\zm \\end{matrix}}}\n\n\nCombining the above with the Jacobian matrix as derived in \\cref{sec:llg-magn-coupl}, the complete Jacobian is\n\\begin{equation}\n  \\Jm =\n  \\scalemath{2}{\n    \\begin{pmatrix}\n      \\Fm        & \\Pm     &  \\zm \\\\\n      \\Qprime &   \\Aprime &  \\Gprime  \\\\\n      \\Qm       &  \\zm       &   \\Amu\n    \\end{pmatrix}\n  },\n  \\label{eq:16}\n\\end{equation}\nwhere $\\Abound = \\pd{\\phimh}{\\phimdis_\\boundd}$ is the Jacobian of the bulk $\\phim$ values with respect to the boundary values.\nThe order of blocks is $\\mv$, $\\phim$, $\\phione$.\nThe blocks corresponding to derivatives of the $\\phim$ residual are broken into sub-blocks for the bulk and boundary values due to the BEM coupling.\nThe overall Jacobian is a square matrix with number of rows $\\nrow = 5\\Nn$, where $\\Nn$ is the number of nodes.\nThe LLG block, $\\Fm$, is of size $3\\Nn\\times 3\\Nn$, the Poisson block, $\\Amu$, is of size $\\Nn \\times \\Nn$.\nThe smaller Poisson block, $\\Amm$, is of size $\\Nbul \\times \\Nbul$, where $\\Nbul$ is the number of bulk nodes.\nThe identity and BEM matrices are of size $\\Nb \\times \\Nb$, where $\\Nb$ is the number of boundary nodes.\nIf the singularity in the pure-Neumann Poisson problem for $\\phione$ is handled by pinning a single value of $\\phione$ (as mentioned in \\cref{sec:strong-form}) then the corresponding matrices are one row/column smaller.\n\nFor brevity we write the Jacobian, \\cref{eq:16}, as\n\\begin{equation}\n  \\Jm =\n  \\begin{pmatrix}\n    \\Fm       & \\Pm     &  \\zm \\\\\n    \\Qm' &   \\Amm' &  \\Gm'  \\\\\n    \\Qm       &  \\zm       &   \\Amu\n  \\end{pmatrix}.\n\\end{equation}\n\n\nIt is worth noting that a slightly different Jacobian struture could be obtained by modifying the derivation in \\cref{sec:appl-magn-calc}.\nInstead of using $\\phim = \\phione + \\phitwo$ to eliminate $\\phitwo$, we could use $\\hms = - \\grad ( \\phione + \\phitwo)$ and eliminate $\\phim$.\nThis would result in both of the potentials having a $\\Pm$ block, but only one of them having a $\\Qm$ block.\nIt would also reduce the diagonal dominance of $\\bm$.\nWe have not experimented with this alternative formulation.\n\nThe linear system to be solved at each Newton step is (see \\cref{sec:newt-raph})\n\\begin{equation}\n  \\jac \\corr = -\\resi,\n  \\label{eq:87}\n\\end{equation}\nwhere $\\resi$ is the vector of the current discrete Newton residuals for $\\mv$, $\\phim$ and $\\phione$; and we need to find the Newton update $\\corr = [\\corr\\mvdis, \\corr\\phimdis, \\corr\\phionedis]^T$.\n\n\n\\subsection{The semi-implicit (decoupled) approach}\n\\label{sec:semi-implicit-bem}\n\nOne approach, which avoids solving the complete non-linear system, is to break the monolithic system into three coupled but simpler problems.\nThis can be achieved by using implicit calculations for the LLG parts as normal, but treating the magnetostatic calculations explicitly.\nThe resulting scheme then only requires independent calculations of the magnetostatic field and the magnetisation as described in \\cref{sec:llg-only-system}.\nSince the magnetostatic fields are typically much weaker than the exchange field we hope that the stability of the scheme will not be greatly reduced.\n\nAn outline of the algorithm to compute the step from time $t_n$ to $t_{n+1}$ is as follows:\n\\begin{algorithm}[H]\n  Extrapolate the magnetostatic potential (using $\\phim_n$, $\\phim_{n-1}$) to time $t_{n+1}$, call the result $\\hat{\\phim}_{n+1}$\\;\n  Use $\\hat{\\phim}_{n+1}$ to calculate $\\mv_{n+1}$ using an implicit time integration scheme (a non-linear solve of the $\\Fm$ block)\\;\n  Calculate $\\phione_{n+1}$ using $\\mv_{n+1}$ (a Poisson solve)\\;\n  Use boundary values of $\\phione_{n+1}$ to calculate the boundary values of $\\phim_{n+1}$ (a matrix-vector multiply with the BEM matrix)\\;\n  Calculate $\\phim_{n+1}$ everywhere using these Dirichlet boundary conditions and $\\mv_{n+1}$ (a Poisson solve)\\;\n\\end{algorithm}\nA similar method without the extrapolation step been used previously, see \\eg \\cite{Schrefl1997}.\n\nNote that we use an extrapolation of the magnetostatic potential, $\\phim$, to $t_{n+1}$ rather than computing it using a step of an explicit time integration scheme because there is no time derivative in the equations for $\\phim$.\n\n% Alternatively we could take an explicit step of the LLG and use the result to calculate $\\hat{\\phim}_{n+1}$.\n% Inside an adaptive time integration scheme the explicit step used to estimate the local truncation error could be reused for this purpose.\n% We have not experimented with this idea.\n\nFor step 1 of the algorithm we require a second order accurate extrapolation in order to ensure that the local truncation error of the overall time integration scheme remains second order.\nA simple second order extrapolation formula (based on Lagrange interpolation \\cite[312]{Kincaid2002}) is\n\\begin{equation}\n  \\label{eq:65}\n  f(t_{n+1}) = \\frac{t_{n+1} - t_n}{t_{n-1} - t_n}f(t_{n-1}) + \\frac{t_{n+1} - t_{n-1}}{t_n - t_{n-1}}f(t_n),\n\\end{equation}\nreplacing differences in time with the appropriate time steps gives:\n\\begin{equation}\n  \\label{eq:66}\n  \\hat{\\phim}_{n+1} = \\frac{-\\dtx{n+1}}{\\dtn} \\phim_{n-1} + \\frac{\\dtx{n+1} + \\dtn}{\\dtn} \\phim_n.\n\\end{equation}\nNote that if we are using the implicit midpoint rule we need to extrapolate $\\phim$ to the midpoint rather than $t_{n+1}$, hence in this case we replace $\\dtx{n+1}$ by $\\dtx{n+1} /2$ in the above equation.\n\n%  write out LTE for this scheme somehow?\n\nUnfortunately this method requires two initial values for the magnetostatic potential values, and is not self starting.\nThe additional value can be generated by directly calculating the potential if the magnetisation values at two initial times are known.\nOtherwise the first can be calculated from the initial condition and the potential at a second time can be calculated by taking one step of a monolithic method or a (much smaller) time step using a first order extrapolation formula.\n\nThe linear and non-linear systems resulting from the application of this algorithm are exactly those discussed in \\cref{sec:llg-only-system}.\n\n\n% could mention semi-implicit + fixed point iteration approach? No one's ever used it in micromagnetics as far as I know.\n\n\n\\subsection{The monolithic approach}\n\\label{sec:fully-implicit-bem}\n\nThe alternative to the semi-implicit approach described above is to find an efficient way to solve the full system \\cref{eq:16,eq:87}, this is referred to as a fully coupled or monolithic approach.\nThe major difficulty is that the system contains a dense block, meaning that any operations (\\eg LU decomposition, multiplication) on J will be significantly slower than for a sparse Jacobian.\\footnote{Dense matrix-vector multiplication takes $\\order{\\nrow^2}$ operations (since all $\\nrow^2$ matrix entries are used), while LU decomposition takes $\\order{\\nrow^3}$ operations \\cite[223]{Iserles2009}.}\nWe use a combination of techniques to reduce this negative effect of the BEM block.\n\nThe first and most important technique is the use of a Krylov solver, this has two benefits.\nFirstly, as mentioned in \\cref{sec:krylov-solvers}, a Krylov solver (with an effective preconditioner) is typically significantly faster and more memory efficient than a direct solver.\nSecondly, using a Krylov solver rather than a direct solve or a multigrid-based solver means that all that is required of $\\jac$ is the computation of matrix-vector products.\nThis allows us to split $\\jac$ into separate matrices as\n\\begin{equation}\n  \\begin{aligned}\n    \\jac &=\n    \\begin{pmatrix}\n      \\Fm       & \\Pm     &  \\zm \\\\\n      \\Qm' &   \\Amm' &  \\zm  \\\\\n      \\Qm       &  \\zm       &   \\Amu\n    \\end{pmatrix}\n    +\n    \\begin{pmatrix}\n      \\zm       & \\zm     &  \\zm \\\\\n      \\zm       &  \\zm    &  \\Gm'  \\\\\n      \\zm       &  \\zm    &  \\zm\n    \\end{pmatrix},\n    \\\\\n    &= \\jac_S + \\jac_D.\n  \\end{aligned}\n\\end{equation}\nThe matrix-vector product can be computed as\n\\begin{equation}\n  \\jac \\xv = \\jac_S \\xv + \\jac_D \\xv,\n\\end{equation}\n\\ie the dense and sparse parts can be stored and used completely independently.\n\nThis leads us to the second component of our method: the use of a hierarchical matrix format for the BEM block \\cite{Borm2003,Forster2003,Knittel2011}.\nThis format uses ideas similar to the fast multipole method to use computationally cheap (in both time and memory) but less accurate approximations to the matrix where possible, without compromising overall accuracy.\nIt reduces the computational cost for a matrix-vector product with the dense block to $\\order{\\Nb \\log \\Nb}$.\nSince the number of boundary nodes $\\Nb$ is typically less than the total number of nodes in the problem this can allow the cost of matrix-vector products of $\\jac$ to be optimal (\\ie $\\order{\\nrow}$) depending on the geometry.\nIt also reduces the memory requirements for the block to $\\order{\\Nb \\log \\Nb}$.\nThis introduces a small additional error, but it has been shown that the size of the error can be made significantly less than the FEM approximation error by choosing appropriate parameters \\cite[77]{Knittel2011}.\nThe use of such formats has recently become fairly common in the application of the hybrid FEM/BEM method to micromagnetics problems.\n\nThe third and final component in our efficient solver is a cheap and effective preconditioner for the linear system.\nSome approaches to constructing such a preconditioner will be discussed in the following section.\n\n\n\\subsubsection{Preconditioning strategies}\n\\label{sec:bem-solver-strategies}\n\n\nIn this section we give a number preconditioning approaches for the monolithic system with the Jacobian \\cref{eq:16}.\nThe aim is to construct a preconditioner which gives an approximately constant number of Krylov solver iterations independently of all problem and discretisation parameters but which is also quick to set up and does not consume a large quantity of memory.\n\nThe first preconditioner is very simple: we use a direct solve (using LU decomposition) of the sparse part of $\\Jm$, \\ie\n\\begin{equation}\n  \\preca = \\jac_S =\n  \\begin{pmatrix}\n    \\Fm       & \\Pm     &  \\\\\n    \\Qm'       & \\Amm'    &   \\\\\n    \\Qm       &         &   \\Amu\n  \\end{pmatrix}.\n\\label{eq:90}\n\\end{equation}\nThis preconditioner, while much more efficient than a direct solve including the dense block, still suffers from all the usual problems associated with a direct solver (\\ie expensive in both memory and computation time when $\\Nn$ is large).\nHowever, we are interested in its properties as a test of the effectiveness of dropping the $\\Gm'$ block from the preconditioner.\n\nA number of other FEM/BEM based models use an approach similar to preconditioner $\\preca$ \\cite{Suess2002}, except that the preconditioner is applied using an inner Krylov solver rather than an LU decomposition.\nThis makes the computational cost feasible for realistic problems, but has two issues:\nThe first is that technically an inner Krylov solve cannot be used as a preconditioner because it does not apply the same operation at each step of the outer solve (since they iterate to convergence rather than using a fixed number of steps) \\cite{Saad1993}.\nThis issue can be resolved by using an outer Krylov solver known as Flexible GMRES which accounts for this.\nThe second issue is that a full inner Krylov solve is run at \\emph{every iteration} of the outer Krylov solve, which is computationally expensive compared to more standard preconditioning approaches (but still cheaper than a direct solve for sufficiently large problems).\nHowever we are only interested in $\\preca$ as a test of the effect of dropping the dense matrix on the iteration counts, hence we do not pursue this further.\n\nOur second and third preconditioners are more ambitious: motivated again by the fact that the magnetostatic field is usually significantly weaker than the exchange effective field we drop LLG-magnetostatics coupling blocks in order to make the preconditioner block triangular.\nIt can then be applied by inverting only the diagonal blocks (exactly or approximately) and using block back/forward substitution.\nThe two preconditioners, resulting from dropping different LLG-magnetostatics blocks, are:\n\\begin{equation}\n  \\precb =\n  \\begin{pmatrix}\n    \\Fm       &           &  \\\\\n    \\Qm'       & \\Amm'&   \\\\\n    \\Qm       &           &   \\Amu\n  \\end{pmatrix},\n  \\qquad\n  \\precc =\n  \\begin{pmatrix}\n    \\Fm       & \\Pm       &  \\\\\n    & \\Amm' &   \\\\\n    \\Qm       &           &   \\Amu\n  \\end{pmatrix},\n  \\label{eq:ms-block-prec-drop-p}\n\\end{equation}\nwhere the blocks in $\\precc$ can be reordered to give a block triangular matrix but we continue to write them in this order for consistency.\nHowever, inverting $\\precb$ or $\\precc$ directly would still require an expensive, in terms of both setup time and memory, direct solve of the three diagonal blocks $\\Fm$, $\\Amm'$ and $\\Amu$.\nIdeally we want to approximate these inverses by some cheap iterative process instead.\n\nBased on the fact that AMG is known to be an optimal preconditioner for Krylov solves of Poisson problems, we apply an AMG approximation for the $\\Am$ blocks.\nUsing this approximation we define two ``semi-inexact'' preconditioners (\\ie preconditioners where some of the blocks are approximated using iterative methods)\n\\begin{equation}\n  \\parinexact{\\precb} =\n  \\begin{pmatrix}\n    \\Fm       &           &  \\\\\n    \\Qm'       & \\inexact{\\Amm'} &   \\\\\n    \\Qm       &           &   \\inexact{\\Amu}\n  \\end{pmatrix},\n  \\qquad\n  \\parinexact{\\precc} =\n  \\begin{pmatrix}\n    \\Fm       & \\Pm       &  \\\\\n    & \\inexact{\\Amm'} &   \\\\\n    \\Qm       &           &  \\inexact{\\Amu}\n  \\end{pmatrix},\n  \\label{eq:ms-block-prec-drop-p}\n\\end{equation}\nwhere we use $\\inexact{x}$ to denote that the block is approximated iteratively and\n\\begin{equation}\n  \\inexact{\\Amm'} =\n  \\begin{pmatrix}\n    \\inexact{\\Amm}     & \\Abound \\\\\n    \\zm      & -\\Idm\n  \\end{pmatrix},\n\\end{equation}\n\\ie only the Poisson block of $\\Amm'$ is approximated by AMG, the rest can be applied by block back/forward substitution.\n\nAs a final fully-inexact (\\ie using only cheap approximations with iterative methods) preconditioner we try approximating the $\\Fm$ block using ILU.\nHowever we should expect poor performance for large matrix sizes and time steps, similar to the case of pure-LLG solves preconditioned with ILU as discussed in \\cref{sec:llg-only-system}.\nWe define two fully-inexact preconditioners using this approximation in addition to the AMG approximation for the Poisson blocks discussed above:\n\\begin{equation}\n  \\inexact{\\precb} =\n  \\begin{pmatrix}\n    \\inexact{\\Fm} &           &  \\\\\n    \\Qm'       & \\inexact{\\Amm'} &   \\\\\n    \\Qm       &           &   \\inexact{\\Amu}\n  \\end{pmatrix},\n  \\qquad\n  \\inexact{\\precc} =\n  \\begin{pmatrix}\n   \\inexact{\\Fm}       & \\Pm       &  \\\\\n    & \\inexact{\\Amm'} &   \\\\\n    \\Qm       &           &  \\inexact{\\Amu}\n  \\end{pmatrix}.\n  \\label{eq:ms-block-prec-drop-p}\n\\end{equation}\n\n\n\\section{Numerical experiments}\n\\label{sec:numer-exper-fem-bem-systems}\n\n% linear scale for problem size for Milan?\n% show full solver times? -- probably not interesting in general, but would be good to show at least one hlib vs dense...\n\nWe now test the performance and robustness of the linear solvers described in \\thisref{sec:solution-strategies}.\nA test of the accuracy and stability of the monolithic and semi-implicit approaches (using the solvers developed here) will be performed in \\cref{cha:numer-experiments}.\n\n\n\\subsection{Problem specification}\n\\label{sec:linear-systems-probl-spec}\n\nIn order to perform these experiments we need a representative example problem.\nWe do not use the \\mumag standard problem \\#4 because the hybrid FEM/BEM method for magnetostatic calculations is particularly ill-suited for such thin film problems (as discussed in \\cref{sec:bound-elem-meth}).\nHence the performance on the standard problem would be irrelevant for typical problems using this method and the computational cost would be unnecessarily large.\n\nSince the majority of practical FEM micromagnetics calculations are in three dimensions our test case should also be 3D.\nIt also must have sharp corners or edges, in order to include any effect of near singular integrals in the FEM/BEM method.\nBased on these considerations we choose to test the solvers on an $L\\times L \\times L$ cube with $L=1$ exchange length.\n\nWhen testing solvers it is convenient to chose the initial condition such that non-trivial dynamics occur immediately and relevant results can be obtained with only a single time step.\nAs such the initial magnetisation is chosen to be\n\\begin{equation}\n  \\mv_0(x, y, z) = \\threevec{\\sin(2\\pi x/50) + \\sin(2\\pi y/50)}{\\cos(2\\pi x/50) + \\cos(2 \\pi y/50)}{1.0 - m_y - m_z}.\n\\end{equation}\nNote that a wavelength of $50$ was chosen to ensure that even meshes with very low refinement are able to resolve the initial state well.\nThe problem geometry and initial conditions are illustrated in \\cref{fig:cube-initial-condition}.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=0.8\\textwidth]{images/itsacube}\n  \\caption{The test problem used for the linear solvers in the state at time $t=0$.\n    The arrows represent the magnetisation direction at each node of the finite element mesh.\n    Colour represents the magnitude of $m_x$.\n    The semi-transparent pale green grid shows the finite element mesh.\n  }\n  \\label{fig:cube-initial-condition}\n\\end{figure}\n\n\nWe use a range of damping and anisotropy parameters: $\\dampc = 0, 0.01, 1$, $\\kone = 0, 0.1$.\n % I should really have done $L=1,10,100$ (equivalent to varying exchange coeff), do it if there's time.\nWe use zero applied field to avoid inducing accidental symmetries.\n\n\\subsection{Implementation details}\n\nTime steps of sizes $\\dtn = 0.01, 0.1, 0.5, 1.0$ are chosen, and meshes with $\\Nn= 71, 791, 5631, 42461$ nodes (note that the number of rows/columns in the Jacobian is roughly 5 times the number of nodes).\nWe use both the nodal quadrature discussed in \\cref{sec:local-nodal-integr} and a standard Gaussian quadrature.\nSince the only effect of changing the time integration methods on the linear systems is a small change to the constant in the time derivative terms we only run experiments using IMR.\n\nThe solvers are run both with and without the use of a hierarchical matrix representation for the dense $\\Gm$ block.\nWe use the \\hlib library \\cite{hlib-website} with patches from \\nmag \\cite{nmag-website} allowing a collocation BEM approach.\nFor compatibility with this library we use a tetrahedral mesh.\nWe use the HCA II algorithm with parameters based on those used by Knittel \\cite{Knittel2011}:\n$\\epsilon_{ACA} = 10^{-5}$,\nminimum leaf matrix size $n_{\\text{min}}= 30$,\nadmissibility criterion $\\eta = 0.25$,\npolynomial interpolation order $p=4$, and\nnumerical quadrature order $q=3$.\nWe also use adaptive recompression with $\\epsilon = 10^{-3}$.\n\nThe CG and GMRES solvers used are \\oomph's built-in implementations with relative convergence tolerances of $10^{-8}$.\nGMRES with no restarts and left preconditioning is used for to ensure reliable convergence and reliable residual norms.\nLU decomposition is implemented using the \\superlu package \\cite{superlu}.\nThe AMG implementation used as a preconditioner for Poisson matrices/blocks is \\hypre's BoomerAMG \\cite{hypre}.\nOne V(1,1) cycle with Gauss-Seidel smoothing, CLJP coarsening and a connection strength threshold of $0.7$ is used.\nThe ILU preconditioner used for LLG matrices/blocks is \\hypre's Euclid with one level of fill in and no drop tolerance (ILU without fill-in was also tried but was extremely ineffective).\n\n\nAll experiments are run on a single core (\\ie no parallelism is used) of a desktop computer with an Intel Core i7-3820 processor running at 3.6GHz and 16GB of RAM.\n\n\n\\subsection{Results}\n\nBefore presenting the results we note that, unless otherwise specified, all figures in this section show data points for all values of $\\dtn$, $N$, $\\dampc$ and $\\kone$; both the nodal and Gaussian quadrature schemes; and both the dense and hierarchical BEM block formats.\nHowever, where there appear to be no interesting differences caused by a parameter we do not distinguish between data points with different values of that parameter (\\ie we use the same symbol and colour).\nAlso note that occasionally data points overlap, giving the appearance of fewer points.\n\n\\Cref{fig:its-ilu-decoupled} shows the mean (over the linear solves required within a single Newton solve) number of GMRES iterations required to solve the LLG-only system, \\cref{eq:llg-jacobian}, using ILU(1) preconditioning (\\ie with magnetostatics handled by the semi-implicit approach).\nAs is expected for a general-purpose preconditioner it is effective for small matrix sizes, but becomes less effective for large problems and as the time step size increases.\n% In fact for the largest $\\Nn$ with the largest time steps ($\\dtn = 1.0$) the solver does not converge with 400 iterations for some parameters.\nThe parameters $\\dampc$ and $\\kone$, along with the BEM block format and quadrature type do not appear to have a major impact on the effectiveness of the ILU(1) preconditioner in this example.\nThe mean preconditioner setup times this preconditioner are shown in \\cref{fig:times-ilu-decoupled}.\nAs with the iteration counts, the setup times become significantly larger as $\\Nn$ grows.\n\n\\newcommand{\\manydatapointsTimeStepLegend}{Data points for all values of $\\dampc$ and $\\kone$; both types of quadrature; and both formats of the BEM block are shown but are not distinguished.}\n\\newcommand{\\manydatapointsPrecLegend}{Data points for all values of $\\dampc$, $\\kone$, and for both formats of the BEM block are shown but are not distinguished.}\n\n\\newcommand{\\newtonmean}{Mean (over a single Newton solve) of the}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=0.8\\textwidth]{plots/linear_solvers/ilu-1decoupleddummy-meanofnsolveritersvsinitialnnode.pdf}\n  \\caption{\n    \\newtonmean{}\n    GMRES iterations to converge against problem size for the decoupled LLG preconditioned by ILU(1).\n    The legend indicates the time step size.\n    \\manydatapointsTimeStepLegend{}\n  }\n  \\label{fig:its-ilu-decoupled}\n\\end{figure}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=0.8\\textwidth]{plots/linear_solvers/ilu-1decoupleddummy-meanofpreconditionersetuptimesvsinitialnnode.pdf}\n  \\caption{\n    \\newtonmean{}\n    time in seconds to set up an ILU(1) preconditioner against problem size for the decoupled LLG block.\n    The legend indicates the time step size.\n    \\manydatapointsTimeStepLegend{}\n  }\n  \\label{fig:times-ilu-decoupled}\n\\end{figure}\n\n\nNext we consider the monolithic system \\cref{eq:16} solved using preconditioner $\\preca$, recall that this uses a direct solve of the sparse part of the Jacobian.\nThe iteration counts are shown in \\cref{fig:its-p1-exact}.\nNote that they are roughly independent of the number of nodes and vary only slightly with time step and the various other parameters.\nHowever the preconditioner setup times, shown in \\cref{fig:times-p1-exact}, rapidly increase with increasing matrix size as would be expected from a direct solve.\nAlso, due to the direct solve, the memory usage of this preconditioner is large.\nNote that some data for the largest $\\Nn$ are missing, this is because the memory required was more than the 16GB available.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=0.8\\textwidth]{plots/linear_solvers/som-main-exactimplicitdummy-meanofnsolveritersvsinitialnnode.pdf}\n  \\caption{\n    \\newtonmean{}\nGMRES iterations to converge against problem size for the monolithic system preconditioned by $\\preca$ (inverted by LU decomposition).\n    The legend indicates the time step size.\n    \\manydatapointsTimeStepLegend{}\nSome data points for the largest $\\Nn$ are missing due the LU factors requiring more than 16GB of memory.\n}\n  \\label{fig:its-p1-exact}\n\\end{figure}\n\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=0.8\\textwidth]{plots/linear_solvers/som-main-exactimplicitdummy-meanofpreconditionersetuptimesvsinitialnnode.pdf}\n  \\caption{\n    \\newtonmean{}\n    time in seconds to set up $\\preca$ (inverted by LU decomposition) against problem size for the monolithic system.\n    The legend indicates the time step size.\n    \\manydatapointsTimeStepLegend{}\n    Some data points for the largest $\\Nn$ are missing due the LU factors requiring more than 16GB of memory.\n}\n  \\label{fig:times-p1-exact}\n\\end{figure}\n\n\nNow we consider the partially-inexact preconditioners $\\parinexact{\\precb}$ and $\\parinexact{\\precc}$, which were designed to reduce the setup time and memory issues of $\\preca$ by inverting part of the preconditioner approximately using iterative methods.\nThe iteration counts are shown in \\cref{fig:its-p23-exact}, we see that for both preconditioners the number of iterations increases only slightly as the number of nodes increases and that the various other parameters have little impact on their effectiveness.\nAlso note that the iteration counts are not much larger than those of $\\preca$.\nThe preconditioner setup times are shown in \\cref{fig:times-p23-exact}.\nThey are significantly smaller than those in \\cref{fig:times-p1-exact} but still grow unacceptably large due to the direct solve of the $\\Fm$ block.\nInterestingly the use of nodal integration decreases the time required for the setup of the preconditioner.\nThis is likely due to the ``mass-lumping'' effect discussed in \\cref{sec:local-nodal-integr}.\nHowever it does not decrease the time sufficiently for the preconditioner to be viable for practical usage on problems with number of nodes $\\Nn \\gtrsim 10^4$.\nAlso of note is that, unlike $\\preca$, the required LU decomposition fits within the 16GB of available memory for all parameters.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=0.8\\textwidth]{plots/linear_solvers_p2p3/implicitexact-meanofnsolveritersvsinitialnnode.pdf}\n  \\caption{\n    \\newtonmean{}\n    GMRES iterations to converge against problem size for the monolithic system using the partially-inexact preconditioners $\\parinexact{\\precb}$, $\\parinexact{\\precc}$ with $\\dtn=0.1$.\nThe legend indicates the preconditioner and quadrature scheme used.\n\\manydatapointsPrecLegend{}\n}\n  \\label{fig:its-p23-exact}\n\\end{figure}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=0.8\\textwidth]{plots/linear_solvers_p2p3/implicitexact-meanofpreconditionersetuptimesvsinitialnnode.pdf}\n  \\caption{\n    \\newtonmean{}\n    time in seconds to set up the partially-inexact preconditioners $\\parinexact{\\precb}$, $\\parinexact{\\precc}$ against problem size for the monolithic system with $\\dtn=0.1$.\n    The legend indicates the preconditioner and quadrature scheme used.\n    \\manydatapointsPrecLegend{}\n}\n  \\label{fig:times-p23-exact}\n\\end{figure}\n\n\nFinally we show iteration counts for the fully-inexact preconditioners $\\inexact{\\precb}$ and $\\inexact{\\precc}$ where the $\\Fm$ block is approximated using ILU(1).\nWe cannot expect $\\Nn$-independent results here, since even the simpler case of the solution of the $\\Fm$ block alone with GMRES preconditioned by ILU(1) does not display such behaviour.\nThe iteration counts shown in \\cref{fig:its-p23-ilu1}, are as expected: low at first but ineffective for large number of nodes $\\Nn$.\nIn particular, for the largest number of nodes GMRES did not converge within 400 iterations for any of the parameter sets.\nAlso of note is the much larger variation of the iteration counts with the problem parameters even for the same problem size.\nHowever the preconditioner setup times, as shown in \\cref{fig:times-p23-ilu1} are much better than when using the LU decomposition of the $\\Fm$ block.\n\n% could try to find/show parameter dependency: some iteration counts are ok!\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=0.8\\textwidth]{plots/linear_solvers_p2p3/implicitilu-1-meanofnsolveritersvsinitialnnode.pdf}\n  \\caption{\n    \\newtonmean{}\n    GMRES iterations to converge against problem size for the monolithic system using the inexact preconditioners $\\inexact{\\precb}$, $\\inexact{\\precc}$ with $\\dtn=0.1$.\n    The legend indicates the preconditioner and quadrature scheme used.\n    \\manydatapointsPrecLegend{}\n    Some data points are missing for the largest $\\Nn$ due to a lack of convergence.\n  }\n  \\label{fig:its-p23-ilu1}\n\\end{figure}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=0.8\\textwidth]{plots/linear_solvers_p2p3/implicitilu-1-meanofpreconditionersetuptimesvsinitialnnode.pdf}\n  \\caption{\n    \\newtonmean{}\n    time in seconds to set up the inexact preconditioners $\\inexact{\\precb}$, $\\inexact{\\precc}$ against problem size for the monolithic system with $\\dtn=0.1$.\n    The legend indicates the preconditioner and quadrature scheme used.\n    \\manydatapointsPrecLegend{}\n    Some data points are missing for the largest $\\Nn$ due to a lack of convergence.\n  }\n  \\label{fig:times-p23-ilu1}\n\\end{figure}\n\n% Effect of HLib? If time do this later\n\n\n% if I get inner iteration preconditioner working then compare the total solve time for the semi-implicit method (with GMRES and ILU-1 preconditioning) and fully implicit method (with $\\precb$, ILU-1 for the $\\Fm$ block or maybe using BiCGstab for F?), both using HLib.\n% No chance of this now...\n\n\\section{Outlook}\n\\label{sec:furth-optim-opport}\n\nWe now compare the \\emph{expected} performance of the monolithic and semi-implicit approaches with the assumption that a ``sufficiently good'' preconditioner for the $\\Fm$ block can be found and discuss further improvements that could be made.\n\nFirst we examine the relative cost of the assembly of the Jacobian matrices and Newton residuals.\nAs mentioned above the Jacobian matrices corresponding to linear equations are only dependent  on the geometry and so do not need to be recomputed at each Newton step.\nSo the Poisson Jacobians and the LLG-Poisson coupling blocks ($\\Qm$ and $\\Pm$ from \\cref{eq:16}) do not need to be recomputed.\nThis means that for both methods only assembly of the $\\Fm$ block is required, and the computation time is identical.\n\nAs an aside: the mass matrix blocks on the diagonal of $\\Fm$ ($\\Mm$ of \\cref{eq:llg-jacobian}) are also linear.\nAdditionally the skew symmetric structure of \\cref{eq:llg-jacobian} can be exploited so that the calculation of $\\Km_x$ is reused for $-\\Km_x$, and similarly for $\\Km_y$ and $\\Km_z$.\nApplying these additional optimisations reduces the Jacobian calculations to the assembly of three $\\Nn \\times \\Nn$ Jacobian blocks and the magnetocrystalline anisotropy block (which will typically be either a single $\\Nn \\times \\Nn$ block or empty, see \\cref{sec:llg-jacobian}).\n\nIn practice the Newton residual assembly time is extremely small compared to the solve and Jacobian assembly times ($\\sim 99 \\%$ of the time in the non-linear solver is spent in the Jacobian assembly and linear solves).\nSo the computation time difference due to assembling additional $\\phim$ and $\\phione$ residual components in Newton steps after the first can be ignored.\n\nWe now examine the cost per Krylov iteration (or per set of Krylov iterations for the decoupled case).\nThe monolithic approach has more non-zeros in the Jacobian (the P, Q, G blocks), giving approximately $4 \\Nn$ extra matrix elements, compared to a base of $11 \\Nn$, hence approximately one third as much time again is taken for each Krylov step.\nAlso our fully coupled method uses GMRES for all blocks rather than GMRES for $\\Fm$ and CG for the two Poisson blocks.\nSince GMRES requires a more computationally expensive orthogonalisation process than CG this will increase the cost of the monolithic approach as compared to the semi-implicit approach.\nThis increase could possibly be reduced by using BiCGStab or a restarted GMRES method instead of GMRES.\nFinally it is likely that the monolithic method will require more Krylov iterations to converge, but with a good preconditioner for the $\\Fm$ block this difference should be fairly small.\n\nBased on all these factors we speculate that, with an effective preconditioner for the LLG block, the computational time for a monolithic time step should be within a factor of 2 of the time for a semi-implicit step.\n\n\n\\section{Conclusions and future work}\n\nMonolithic (fully implicit) solvers are required for the energy property of IMR, as well as for other properties of implicit time integration schemes including stability and properties important in stochastic problems.\nWe have demonstrated that a monolithic LLG-magnetostatics solver using GMRES with an effective preconditioner can result in a reasonable computational cost per linear solve.\nThe partially-inexact preconditioners $\\parinexact{\\precb}$ and $\\parinexact{\\precc}$ are able to reduce the iteration count of GMRES extremely effectively and almost independently of the number of nodes, but the set up cost is high for large matrices.\nHowever the fully-inexact equivalents, $\\inexact{\\precb}$ and  $\\inexact{\\preca}$, which use ILU(1) to approximate the LLG block are ineffective for more than a few thousand nodes (\\ie matrices of size $\\sim 10,000$).\nHence cheap, effective and mesh independent preconditioning methods for the LLG block, $\\Fm$, are still needed for the monolithic block-preconditioned method discussed here to be effective on general large problems.\n\nWe have also demonstrated solvers for a decoupled LLG block solve, for medium numbers of nodes it appears that ILU(1) is a good preconditioner for this case.\nHowever, the time integration properties of the semi-implicit scheme using this solve have yet to be seen.\n\n\nFor granular or bit patterned media a domain-decomposition preconditioner exploiting the low/zero exchange coupling between grains/islands could make for a simple but effective domain decomposition preconditioner.\nFor example, such a preconditioner could be implemented by performing an independent direct solve on the matrix block associated with each grain/island and using this diagonal block solution as the preconditioner.\nSince the number of nodes in a single grain/island is small and fixed this would remain effective even for very large numbers of grains/islands.\n\nReordering of the degrees of freedom, scaling, drop tolerance, fill-in level in the ILU preconditioner could be experimented with further to allow the solution of larger systems or alternative parameters \\cite[287]{Saad2000}.\nHowever, ILU preconditioning is unlikely to ever give $\\Nn$-independent or parameter-independent results, so it may not be the best path towards more general efficient preconditioners.\n\n\n\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: \"main\"\n%%% End:\n", "meta": {"hexsha": "07d61c7f8e54565c3efcde1dfc6a468b1505a4d3", "size": 44531, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "fem-bem-linear-systems.tex", "max_stars_repo_name": "davidshepherd7/thesis", "max_stars_repo_head_hexsha": "c4f1e903fa74e8fbc0667538e808fd7e3c947783", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-02-13T10:36:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T21:11:27.000Z", "max_issues_repo_path": "fem-bem-linear-systems.tex", "max_issues_repo_name": "davidshepherd7/thesis", "max_issues_repo_head_hexsha": "c4f1e903fa74e8fbc0667538e808fd7e3c947783", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fem-bem-linear-systems.tex", "max_forks_repo_name": "davidshepherd7/thesis", "max_forks_repo_head_hexsha": "c4f1e903fa74e8fbc0667538e808fd7e3c947783", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 70.3491311216, "max_line_length": 510, "alphanum_fraction": 0.7651074532, "num_tokens": 11197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.31602705316181023}}
{"text": "%% LyX 1.3 created this file.  For more info, see http://www.lyx.org/.\n%% Do not edit unless you really know what you are doing.\n\\documentclass[english]{report}\n\\usepackage[T1]{fontenc}\n\\usepackage[latin1]{inputenc}\n\\setcounter{secnumdepth}{3}\n\\setcounter{tocdepth}{3}\n\\usepackage{makeidx}\n\\makeindex\n\\usepackage{graphicx}\n\n\\makeatletter\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LyX specific LaTeX commands.\n%% Bold symbol macro for standard LaTeX users\n\\providecommand{\\boldsymbol}[1]{\\mbox{\\boldmath $#1$}}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Textclass specific LaTeX commands.\n \\newenvironment{lyxcode}\n   {\\begin{list}{}{\n     \\setlength{\\rightmargin}{\\leftmargin}\n     \\setlength{\\listparindent}{0pt}% needed for AMS classes\n     \\raggedright\n     \\setlength{\\itemsep}{0pt}\n     \\setlength{\\parsep}{0pt}\n     \\normalfont\\ttfamily}%\n    \\item[]}\n   {\\end{list}}\n\n\\usepackage{babel}\n\\makeatother\n\\begin{document}\n\n\\newcommand{\\erfc}{\\mathop{\\mathrm{{erfc}}}}\n\n\n\n\\title{Custom Math Functions for Molecular Dynamics}\n\n\n\\author{Robert Enenkel \\and  Blake Fitch \\and  Bob Germain \\and Fred Gustavson\n\\and Allan Martin \\and Mark Mendell \\and Jed Pitera \\and  Mike\nPitman \\and  Alex Rayshubski \\and Frank Suits \\and  Bill Swope\n\\and  T J Chris Ward}\n\n\\maketitle\nIBM T J Watson Research Centre, Yorktown Heights, New York\n\n(c) Copyright IBM Corp. 2006. CPL\n\n\\begin{abstract}\nWhile developing the protein folding application for IBM's BlueGene/L\nsupercomputer, some frequently-executed computational kernels were\nencountered. These were significantly more complex than the linear\nalgebra kernels that are normally provided as tuned libraries with\nmodern machines. Using regular library functions for these would have\nresulted in an application which exploited only 5-10\\% of the potential\nfloating-point throughput of the machine.\n\nThis is a tour of the functions encountered; they have been expressed\nin C++ (and could be expressed in other languages such as Fortran\nor C); with the help of a good optimising compiler, floating-point\nefficiency is much closer to 100\\%.\n\nThe implementations are offered in the hope that they may help in\nother implementations of Molecular Dynamics; in other fields of endeavour;\nand in the hope that others may adapt the ideas presented here to\ndeliver additional mathematical functions at high throughput.\n\\end{abstract}\n\\tableofcontents{}\n\n\n\\section{Custom Math Functions}\n\n\n\\subsection{Vectorisable Math Functions}\n\nThe IBM XLC compiler can schedule instructions flexibly within a basic\nblock, that is, a sequence of code with no conditional branches.\n\nThis document explains how to exploit this for functions commonly\nused in Molecular Dynamics; if you can enable the compiler to see\nenough independent work, it will schedule instructions to avoid stalls\nin the floating-point execution pipeline; and the hardware will run\nat a high fraction of peak throughput.\n\nTo exploit this, it is generally necessary to avoid special cases\nand error handling; all of these math functions will return a scalar\nresult, will not set errno, and will not signal a NaN in any useful\nway. They can be wrapped to produce conventional results for out-of-domain\ncases; for example to produce NaN for $\\log(-1)$; but for Molecular\nDynamics we are generally confident that they will not be asked to\nprocess out-of-domain cases, and so the extra computation involved\nin getting conventional answers might best be skipped.\n\nOne way to let the compiler see independent work is to write it explicitly\nin the source code. Another way is to enclose the basic block in a\ncounted loop and verify that the compiler can see that loop iterations\nare independent; then the compiler will apply loop transformation\noptimisations such as unrolling and modulo scheduling to construct\nthe appropriate work itself.\n\n\n\\subsection{Vectorisable log}\n\nlog is vectorised by appreciating that a floating-point number is\nrepresented as an exponent and a mantissa; i.e. as $m\\times2^{k}$,\nfor some $m$ in $[1.0,2.0)$ and for integer $k$,\n\n\\[\n\\ln(m\\times2^{k})=\\ln(m)+\\ln(2^{k})\\]\n\n\nThe approximation is produced as three terms, which are added together\nto give the result.\n\n$k$ is extracted as the exponent part of the argument, giving the\nfirst term of the result as $k\\times\\ln(2)$\n\nm is expressed as $m0\\times m1$, where $m0$ is $1+\\frac{a}{16}$\nfor integer $a$ in $(0,15)$, and $m1$ is $\\frac{m}{1+\\frac{a}{16}}$.\n\n$a$ is determined by extracting the first 4 bits after the binary\npoint from $m$.\n\n$\\frac{1}{1+\\frac{a}{16}}$ is looked up in a 16-element table; and\nthis gives a value for $m1$ roughly between $1$ and $1+\\frac{1}{16}$\n.\n\nThe second term of the result is $\\ln(m0)$ , which comes from another\n16-element table.\n\nThe third term of the result comes from a Taylor series for $\\ln(1+x)$;\nthis converges quite rapidly for $x<\\frac{1}{16}$.\n\nThe full result is then\n\n\\[\n\\ln(a)\\simeq k\\times\\ln(2)+\\mathop{\\mathrm{{Lookup}}}(a)+\\mathop{\\mathrm{{TaylorSeries}}}(x)\\]\n\n\nAn improvement comes from a slight modification, where $m1$ is arranged\nto be in the domain $[1-\\frac{1}{32},1+\\frac{1}{32})$, and so the\nTaylor series is used for $|x|<\\frac{1}{32}$.\n\n\n\\subsection{Vectorisable exp}\n\n$\\exp$ is vectorised by appreciating that \\[\n\\exp(a0+a1+a2+a3)=\\exp(a0)\\times\\exp(a1)\\times\\exp(a2)\\times\\exp(a3)\\]\n\n\n$a0$ is extracted as the integer part of the argument. $a1$ is the\nnext 4 bits; $a2$ is the subsequent 4 bits; and $a3$ is the remaining\nbits. $a3$ is a number between $0$ and $\\frac{1}{256}$.\n\n$a0$ is shifted in to the exponent of the resulting floating-point\nnumber. $\\exp(a1)$ and $\\exp(a2)$ are looked up in 16-element tables.\n$\\exp(a3)$ is estimated by a Taylor series, which converges quite\nrapidly for $0<a3<\\frac{1}{256}$.\n\nAgain an improvement comes from a slight modification, setting a3\nin the domain $[-\\frac{1}{512},+\\frac{1}{512})$.\n\nIBM PowerPC hardware supports a floating-point select instruction,\nwhich performs the equivalent of\n\n\\begin{lyxcode}\ndouble~fsel(double~a,double~b,~double~c)\n\n\\{\n\n~~if~(a>=0.0)~return~b~;~return~c\n\n\\}\n\\end{lyxcode}\nas a single hardware instruction. This can be used to arrange that\n$\\exp(x)$ returns $0$ for a sufficiently-large negative argument,and\nInf for a sufficiently-large positive argument, without causing a\nbranch in the generated code.\n\n\n\\subsection{Vectorisable erf/erfc - Piecewise Chebyshev}\n\nTraditionally in molecular dynamics codes, erfc(x) has been approximated\nby the formula in \\cite[Abramowitz and Stegun]{key-1}\n\n\\includegraphics[%\n  scale=0.5,bb = 0 0 200 100, draft, type=eps]{absteg-erf.png not found!}\n\n\\begin{lyxcode}\n\n\\end{lyxcode}\nVectorisable $\\exp(x)$ can be used to form vectorisable erfc in the\nobvious way; but there is an alternative which can be used to form\na more accurate result. A more accurate result is desirable in Molecular\nDynamics because it should give better energy conservation for a given\ntime-step size; or alternatively will allow a larger time-step size\nbefore numerical instability sets in.\n\nThe reciprocal required above is a special case; for molecular dynamics\ncodes, the dividend will be in the single-precision range, and there\nis no point returning a result much more accurate than the 1 part\nin $10^{5}$of the complete approximation. This leads to a faster\nexpression of reciprocal than the hardware double-precision divide\nwill give; more on this later.\n\nFor molecular dynamics, we are interested in erfc to support electrostatics,\nerfc(x) for a limited domain of x, typically $(-4,4)$.\n\nWe partition the domain into equal-sized sub-domains, say $[-4,-3)$,$[-3,-2)$\n, .. , $[3,4)$. Represent $x$ as $x0+x1$, where $x1$ is in $[-0.5,0.5)$\nand $x0$ is an integer which identifies the sub-domain. Each sub-domain\nis associated with a polynomial approximator; a set of 8 Chebyshev\npolynomials works well.\n\nSelect the appropriate polynomial by using $x0$ to index an array,\nand erfc(x) follows.\n\nIt is relatively easy to set the polynomials up to give erfc(x) accurate\nwithin 1 machine ulp (least significant bit) over the whole domain.\nIt is desirable to use fsel to avoid travesties in case someone passes\nin a value of x outside the designed domain.\n\nIt is possible to exploit the symmetry between erfc(x) and erfc(-x)\nto halve the number of tables required.\n\nThe required table for Chebyshev coefficients is machine generated;\n\\cite[Numerical Recipes]{key-2} shows the algorithm. First the Chebyshev\ncoefficients for $\\frac{d}{dx}\\erfc(x)$are generated using the analytic\nexpression $\\frac{-2}{\\sqrt{\\pi}}\\exp(-x^{2})$; then the coefficients\nfor $\\erfc(x)$are generated by applying the appropriate transformation\non these.\n\n\n\\subsection{Vectorisable derivative erfc}\n\nDerivative erfc is $\\frac{-2}{\\sqrt{\\pi}}\\exp(-x^{2})$, and may be\nvectorised using vectorisable $\\exp(x)$.\n\nHowever, for molecular dynamics,it is desirable to have derivative\nerfc and erfc related accurately as derivative and integral of each\nother; this results in better reported energy conservation, and better\naccuracy when switch or soft force cutoff is in use.\n\nWhen the Abramowitz and Stegun approximation for $\\erfc(x)$ is in\nuse, we can differentiate the expression analytically. The derivative\nhas an exponential term of the same form as the original, i.e. $\\exp(-x^{2})$,\nso a single evaluation of $\\exp(X)$ will do duty for both functions\nwhen erfc and its derivative are both required in a computation.\n\nWhen the multiple Chebyshev approach is in use, another set of Chebyshev\npolynomials can be used to deliver derivative erfc; if these are on\nthe same sub-domains, there is a computational economy.\n\n\n\\subsection{Vectorisable erfc and derivative - Piecewise Cubic Spline}\n\nIn Molecular Dynamics, erfc and its derivative are used in the evaluation\nof electrostatic forces. Another approximation (particle mesh) means\nthat it is not useful to get $\\erfc(x)$ more precise than a relative\nerror of about $10^{-5}$; the imprecision due to the 'particle mesh'\napproximation dominates.\n\nHowever, it is important for the values returned for $\\erfc(x)$and\nits derivative to be continuous, and an analytic integral/derivative\npair.\n\nThis can be satisfied by approximating $\\frac{d}{dx}\\erfc(x)$with\na set of cubic splines, matching the$\\frac{-2}{\\sqrt{\\pi}}\\exp(-x^{2})$\nfunction and its derivative at the piecewise endpoints; and integrating\nthese polynomials to give piecewise-quartic approximations for $\\erfc(x)$.\n\nA set of 64 piecewise cubic polynomials and their integrals, for domains\n{[}0,1/16), {[}1/16-2/16), .. , {[}63/16,64/16), gives the ability\nto approximate $\\erfc(x)$and its derivative to the required precision\nin the domain {[}0-4).\n\n\n\\subsection{Vectorisable sin/cos}\n\nIt is convenient to use a multiple-Chebyshev-polynomial approach for\nthis, too. Divide $\\sin(x)$ into domains $[-45,45)$,$[45,135)$,$[135,225)$,\nand $[225,315)$ degrees, and repeat cyclically.\n\nIn domains $[-45,45)$ degrees and $[135,225)$ degrees, use a Chebyshev\npolynomial for $\\frac{\\sin(x)}{x}$, and multiply the result by $x$.\nThis arranges that the result for small $|x|$ can be within an ulp,\nwithout requiring an excessive number of terms in the polynomial.\n\nIn domains $[45,135)$ and $[225,315)$, use a Chebyshev polynomial\nfor $\\cos(x)$.\n\nThe required Chebyshev polynomials are always even, which economises\non the computation.\n\nAfter the polynomial evaluation, fix up the result by a suitable multiply\nand add according to the sub-domain.\n\ncos and sin are related since $\\cos(x)$= $\\sin(x+90)$ with angles\nin degrees.\n\nThe tables are machine-generated offline, using extended-precision\n$\\sin$and $\\cos$functions and the algorithm in \\cite[Numerical Recipes]{key-2}.\n\n\n\\subsection{Vectorisable inverse cos and sin}\n\nSometimes an application will know the sin and cos of an angle, and\nwill want to evaluate the angle. Traditional arcsin will involve an\nambiguity as to the angle (80 degrees or 120 degrees, for example),\nis ill-conditioned in ranges near 90 and 270 degrees; and usually\ninvolves a conditional branch and a square root.\n\nBy expressing as\n\n\\begin{lyxcode}\ndouble~acossin(double~cos\\_angle,~double~sin\\_angle)~\n\\end{lyxcode}\nwe can get over these limitations and produce an implementation without\nbranches.\n\nFirst, we take the absolute value of each of the parameters. Next,\nwe use fsel to take whichever is smaller, and whichever is larger;\ngiving a value between $0$ and $\\sqrt{0.5}$ representing the sin\nof an angle between 0 and 45 degrees, and a value between $\\sqrt{0.5}$\nand $1$, representing the cos of the same angle.\n\nThen we use the compound angle formula\n\n\\[\n\\sin(a-b)=\\sin(a)\\cos(b)-\\cos(a)\\sin(b)\\]\n\n\nto form the sine of an angle in $[-22.5,22.5)$ degrees, a value in\nthe domain $[-0.38,0.38)$ approximately.\n\nNext, we use the Taylor expansion for $\\arcsin(x)$ which converges\nquite rapidly over this domain; and we multiply by and add suitable\nconstants (according as whether the original parameters were negated,\nand which was smaller) to evaluate the angle called for.\n\n\n\\subsection{Vectorisable reciprocal square root}\n\nThe natural way to express this is like\n\n\\begin{lyxcode}\ndouble~a=1.0/sqrt(x);\n\\end{lyxcode}\nWith -qnostrict, the compiler knows about this. There is a hardware\nreciprocal square root estimate instruction which gives a result accurate\nto 5 bits (Power3) or 13 bits (BG/L) using lookup tables in the same\namount of time that a multiply-add instruction would take; and the\ncompiler generates a suitable number of iterations of Newton's method,\nor a suitable Taylor correction polynomial, to bring the result to\ndouble-precision accuracy.\n\nNewton's iteration is expressed in terms of multiplies and adds; the\n'divide by $b$' which seems to be required is replaced with 'multiply\nby estimate of $\\frac{1}{b}$'.\n\n\n\\subsection{Vectorisable square root}\n\nThe compiler knows about \n\n\\begin{lyxcode}\ndouble~a=sqrt(x)\n\\end{lyxcode}\nand can use the hardware instruction for this on Power3, and generate\na sequence something like $\\frac{x}{\\sqrt{x}}$ on BG/L. However,\n$\\frac{x}{\\sqrt{x}}$ on its own will give 'not-a-number' for $x=0$;\nthe compiler generates code to fix this up, but it is computationally\nexpensive.\n\nIf the algorithm doesn't care about the result for $x=0$, then it\nwill run better on both Power3 and BG/L if coded as\n\n\\begin{lyxcode}\ndouble~a=x/sqrt(x)\n\\end{lyxcode}\n\n\\subsection{Vectorisable NearestImageInPeriodicVolume}\n\nMolecular dynamics is frequently run with 'periodic boundary conditions';\ni.e. where we imagine that the simulation volume is surrounded by\na never-ending sequence of matching simulation volumes; and the interaction\nforce between a pair of atoms is calculated as if one of the atoms\nis influenced by the nearest of the 27 images of the other atom.\n\nThe 'nearest' image of an atom can be calculated without divisions\nor branches; map the simulation volume to a unit cube, by multiplying\ncoordinates by the reciprocal of the simulation box. Then find the\n'nearest integer' in each dimension, and subtract it off. Then multiply\nback up to the real simulation volume size.\n\n\n\\subsection{Vectorisable nearest\\_integer}\n\nThis relies on the IEEE floating-point representation. Double precision\ntakes 64 bits. The top bit is a sign bit; the next 11 bits are a binary\nexponent; and the remaining 52 bits are a binary mantissa, with an\nimplied leading '1'.\n\nIEEE addition, with the hardware in its usual mode, is specified to\nround to the nearest integer. So if you take a double-precision floating-point\nnumber and add $(2^{52}+2^{51})$, the fractional part will be dropped.\nThen you can subtract the$(2^{52}+2^{51})$, and you will get the\nnearest integer to the number you started with.\n\nThere is a range around $2^{52}$where you will get the nearest even\ninteger; so this is not applicable in all cases; but is OK for molecular\ndynamics.\n\nThe compiler is being asked to generate code for $(x+k)-k$ ; it is\nimportant to prevent the optimiser from re-associating this to $x+(k-k)$\nand then optimising this to $x+0$, i.e. $x$. \n\nThe sample code does this by expressing $(x+k\\times k1)\\times k1-k$,\nwhere $k1$ is $1.0$ but the compiler is unable to tell that $k1$\nis a constant. IBM POWER family architectures support a 'multiply-add'\ninstruction, so this does not cause any extra processing cycles.\n\n\n\\subsection{Vectorisable 'Fragment In Range'}\n\nMolecular Dynamics is generally concerned with forces between atoms\nin an imagined simulation box with periodic boundary conditions. Computation\nof the force between a pair of atoms is skipped if the atoms are more\nthan a threshold distance apart.\n\nFor computational convenience, the atoms are grouped into fragments;\ntypically a water molecule, or a covalently-bonded set of atoms within\na larger molecule. The question arises, 'given fragment $a$, what\nis the set of fragments $\\{ b_{0},b_{1},...\\}$such that an atom in\n$a$ is in range of an atom in each $b_{i}$, accounting for the periodic\nboundary'. The simulation will be functionally correct if extra fragments\n$b$ are in the set; the forces involved will evaluate to zero; but\nthe simulation is more efficient with fewer extra fragments.\n\nThere is an algorithm for this which makes 100\\% use of the floating-point\nunits, successively slicing for slab, cylinder, and sphere. \n\nThere is another algorithm which doesn't use the floating-point units;\ninstead it uses the integer units with wrap at $2^{32}$, successively\nslicing for slab, square prism, and cube; then uses the floating-point\nunits to slice for sphere. \n\nOn Power3 and BG/L, the integer algorithm is faster; and either algorithm\nis sufficiently fast that the BlueMatter code does not need to maintain\nlists of fragments found to be in range in previous simulation time\nsteps (known as Verlet lists) of fragments previously known to be\nin range, for system sizes of interest.\n\nThese algorithms show how to do 'vector compress'; i.e. producing\na vector which is a subset of a starting vector, including only those\nelements matching a selection criterion, without requiring a conditional\nbranch.\n\n\n\\section{A practical example - reciprocal square roots}\n\nThe function presented evaluates 'reciprocal square root' for each\nof 9 values, as would be needed to support the calculation of distances\nbetween atoms in a pair of 3-site water molecules.\n\nSource code is given, then compiler intermediate code with cycle counts,\nthen compiler assembly listing, for Power3 and BG/L machine architectures.\n\nValues are copied into local variables, to make it clear to the compiler\nwhat is intended if the function is called with source and target\noverlapping in memory.\n\nPower3 requires a vector of length at least 6 to keep the floating-point\nunits fully busy on this algorithm; BG/L requires a vector of length\n10. The compiler finds an optimal instruction sequence in each case;\n100\\% floating-point utilisation for Power3, and 90\\% utilisation\n(4 'parallel' ops then a 'primary' op) for BG/L.\n\nThe 'reciprocal square root estimate' instruction of Power3 gives\n5 bits of precision; that of BG/L gives 13 bits of precision. BG/L\nrequires fewer follow-on instructions to converge the estimate to\ndouble precision. Power3 uses a Newton-Raphson algorithm for convergence;\nBG/L uses a Taylor expansion.\n\nThe theoretical peak rate for BG/L hardware is 10 double-precision\nsquare roots per 40 clock cycles; by enclosing similar code in a 'for'\nloop, it is possible to get the IBM VisualAge compiler to generate\ncode which achieves within a few cycles of this rate.\n\n\n\\subsection{Power3}\n\n\\begin{lyxcode}\nVisualAge~C++~for~AIX~Compiler~(DEVELOPMENT/BETA)~Version~6.0~-{}-{}-~\n\n>\\,{}>\\,{}>\\,{}>\\,{}>~OPTIONS~SECTION~<\\,{}<\\,{}<\\,{}<\\,{}<\n\nIGNERRNO~~~~~~~~THREADED~~~~~~~~ARCH=PWR3~~~~~~~OPT=3~~~~~~~~~~~ALIAS=ANSI~~~~~~\n\nALIGN=NATURAL~~~NOROPTR~~~~~~~~~NODIRECTSTORAGE~PREFETCH~~~~~~~~\n\nFLOAT=NOHSFLT:NORNDSNGL:NOHSSNGL:MAF:NORRM:FOLD:NONANS:RSQRT:FLTINT:NOEMULATE~~~\n\nMAXMEM=-1~~~~~~~NOSTRICT~~~~~~~~NOSTRICT\\_INDUCTION~~~TBTABLE=SMALL~~~LIST~~~~~~~~~~~~\n\nSHOWINC=NOSYS:NOUSR~~~~~~~~~~~~~SOURCE~~~~~~~~~~STATICINLINE~~~~TMPLPARSE=NO~~~~\n\nNOEH~~~~~~~~~~~~\n\n>\\,{}>\\,{}>\\,{}>\\,{}>~SOURCE~SECTION~<\\,{}<\\,{}<\\,{}<\\,{}<\n\n~\n\n~~~~~~~~~~~~1~|~\\#include~<math.h>\n\n~~~~~~~~~~~~2~|~void~nineroot(double{*}~f,~const~double{*}~x)\n\n~~~~~~~~~~~~3~|~\\{\n\n~~~~~~~~~~~~4~|~~~~double~x0~=~x{[}0{]}~;\n\n~~~~~~~~~~~~5~|~~~~double~x1~=~x{[}1{]}~;\n\n~~~~~~~~~~~~6~|~~~~double~x2~=~x{[}2{]}~;\n\n~~~~~~~~~~~~7~|~~~~double~x3~=~x{[}3{]}~;\n\n~~~~~~~~~~~~8~|~~~~double~x4~=~x{[}4{]}~;\n\n~~~~~~~~~~~~9~|~~~~double~x5~=~x{[}5{]}~;\n\n~~~~~~~~~~~10~|~~~~double~x6~=~x{[}6{]}~;\n\n~~~~~~~~~~~11~|~~~~double~x7~=~x{[}7{]}~;\n\n~~~~~~~~~~~12~|~~~~double~x8~=~x{[}8{]}~;\n\n~~~~~~~~~~~13~|~~~~double~r0~=~1.0/sqrt(x0)~;\n\n~~~~~~~~~~~14~|~~~~double~r1~=~1.0/sqrt(x1)~;\n\n~~~~~~~~~~~15~|~~~~double~r2~=~1.0/sqrt(x2)~;\n\n~~~~~~~~~~~16~|~~~~double~r3~=~1.0/sqrt(x3)~;\n\n~~~~~~~~~~~17~|~~~~double~r4~=~1.0/sqrt(x4)~;\n\n~~~~~~~~~~~18~|~~~~double~r5~=~1.0/sqrt(x5)~;\n\n~~~~~~~~~~~19~|~~~~double~r6~=~1.0/sqrt(x6)~;\n\n~~~~~~~~~~~20~|~~~~double~r7~=~1.0/sqrt(x7)~;\n\n~~~~~~~~~~~21~|~~~~double~r8~=~1.0/sqrt(x8)~;\n\n~~~~~~~~~~~22~|~~~~f{[}0{]}~=~r0~;\n\n~~~~~~~~~~~23~|~~~~f{[}1{]}~=~r1~;\n\n~~~~~~~~~~~24~|~~~~f{[}2{]}~=~r2~;\n\n~~~~~~~~~~~25~|~~~~f{[}3{]}~=~r3~;\n\n~~~~~~~~~~~26~|~~~~f{[}4{]}~=~r4~;\n\n~~~~~~~~~~~27~|~~~~f{[}5{]}~=~r5~;\n\n~~~~~~~~~~~28~|~~~~f{[}6{]}~=~r6~;\n\n~~~~~~~~~~~29~|~~~~f{[}7{]}~=~r7~;\n\n~~~~~~~~~~~30~|~~~~f{[}8{]}~=~r8~;\n\n~~~~~~~~~~~31~|~\\}\n\n\n\n>\\,{}>\\,{}>\\,{}>\\,{}>~OBJECT~SECTION,~OPTIMIZATION~<\\,{}<\\,{}<\\,{}<\\,{}<\n\n{*}{*}~Procedure~List~for~Proc~\\#~~~1:~nineroot\\_\\_FPdPCd~End~of~Phase~3~{*}{*}\n\n~~~~0:~~~~~~HDR~~~~~~\n\n~~~~3:~~~~~~BB\\_BEGIN~~~~2~/~~~~0\n\n~~~~0:~~~~~~PROC~~~~~f,x,gr3,gr4\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,0\n\n~~~~0:~~~~~~LFLR~~~~~gr0=lr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,3\n\n~~~~0:~~~~~~CALLNR~~~\\_savef18,gr1,fp18-fp31,lr\\char`\\\"{}\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,4\n\n~~~~0:~~~~~~LLR~~~~~~lr=gr0\n\n~~~~4:~~~~~~LFL~~~~~~fp1=(double)(gr4,0)\n\n~~~~5:~~~~~~LFL~~~~~~fp2=(double)(gr4,8)\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,5\n\n~~~~6:~~~~~~LFL~~~~~~fp3=(double)(gr4,16)\n\n~~~~7:~~~~~~LFL~~~~~~fp4=(double)(gr4,24)\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,6\n\n~~~~8:~~~~~~LFL~~~~~~fp5=(double)(gr4,32)\n\n~~~~9:~~~~~~LFL~~~~~~fp6=(double)(gr4,40)\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,7\n\n~~~10:~~~~~~LFL~~~~~~fp7=(double)(gr4,48)\n\n~~~11:~~~~~~LFL~~~~~~fp8=(double)(gr4,56)\n\n~~645:~~~~~~FRSQRE~~~fp9=fp1\n\n~~645:~~~~~~FRSQRE~~~fp10=fp2\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,8\n\n~~~12:~~~~~~LFL~~~~~~fp21=(double)(gr4,64)\n\n~~645:~~~~~~L4A~~~~~~gr4=.+CONSTANT\\_AREA(gr2,0)\n\n~~645:~~~~~~FRSQRE~~~fp11=fp3\n\n~~645:~~~~~~FRSQRE~~~fp12=fp4\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,9\n\n~~645:~~~~~~FRSQRE~~~fp13=fp5\n\n~~645:~~~~~~FRSQRE~~~fp31=fp6\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,10\n\n~~645:~~~~~~LFS~~~~~~fp0=+CONSTANT\\_AREA(gr4,0)\n\n~~645:~~~~~~FRSQRE~~~fp30=fp7\n\n~~645:~~~~~~FRSQRE~~~fp29=fp8\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,11\n\n~~645:~~~~~~MFL~~~~~~fp20=fp9,fp9,fcr\n\n~~645:~~~~~~FRSQRE~~~fp28=fp21\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,12\n\n~~645:~~~~~~MFL~~~~~~fp27=fp10,fp10,fcr\n\n~~645:~~~~~~MFL~~~~~~fp26=fp11,fp11,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,13\n\n~~645:~~~~~~FMS~~~~~~fp1=fp1,fp1,fp0,fcr\n\n~~645:~~~~~~FMS~~~~~~fp2=fp2,fp2,fp0,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,14\n\n~~645:~~~~~~FMS~~~~~~fp3=fp3,fp3,fp0,fcr\n\n~~645:~~~~~~FMS~~~~~~fp18=fp21,fp21,fp0,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,15\n\n~~645:~~~~~~FMS~~~~~~fp4=fp4,fp4,fp0,fcr\n\n~~645:~~~~~~MFL~~~~~~fp25=fp12,fp12,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,16\n\n~~645:~~~~~~FMS~~~~~~fp5=fp5,fp5,fp0,fcr\n\n~~645:~~~~~~MFL~~~~~~fp24=fp13,fp13,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,17\n\n~~645:~~~~~~FMS~~~~~~fp6=fp6,fp6,fp0,fcr\n\n~~645:~~~~~~FMS~~~~~~fp7=fp7,fp7,fp0,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,18\n\n~~645:~~~~~~MFL~~~~~~fp23=fp31,fp31,fcr\n\n~~645:~~~~~~FMS~~~~~~fp8=fp8,fp8,fp0,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,19\n\n~~645:~~~~~~MFL~~~~~~fp22=fp30,fp30,fcr\n\n~~645:~~~~~~MFL~~~~~~fp21=fp29,fp29,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,20\n\n~~645:~~~~~~FNMS~~~~~fp20=fp0,fp20,fp1,fcr\n\n~~645:~~~~~~MFL~~~~~~fp19=fp28,fp28,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,21\n\n~~645:~~~~~~FNMS~~~~~fp27=fp0,fp27,fp2,fcr\n\n~~645:~~~~~~FNMS~~~~~fp26=fp0,fp26,fp3,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,22\n\n~~645:~~~~~~FNMS~~~~~fp25=fp0,fp25,fp4,fcr\n\n~~645:~~~~~~FNMS~~~~~fp24=fp0,fp24,fp5,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,23\n\n~~645:~~~~~~FNMS~~~~~fp23=fp0,fp23,fp6,fcr\n\n~~645:~~~~~~FNMS~~~~~fp22=fp0,fp22,fp7,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,24\n\n~~645:~~~~~~MFL~~~~~~fp9=fp9,fp20,fcr\n\n~~645:~~~~~~FNMS~~~~~fp21=fp0,fp21,fp8,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,25\n\n~~645:~~~~~~FNMS~~~~~fp19=fp0,fp19,fp18,fcr\n\n~~645:~~~~~~MFL~~~~~~fp10=fp10,fp27,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,26\n\n~~645:~~~~~~MFL~~~~~~fp11=fp11,fp26,fcr\n\n~~645:~~~~~~MFL~~~~~~fp12=fp12,fp25,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,27\n\n~~645:~~~~~~MFL~~~~~~fp13=fp13,fp24,fcr\n\n~~645:~~~~~~MFL~~~~~~fp31=fp31,fp23,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,28\n\n~~645:~~~~~~MFL~~~~~~fp30=fp30,fp22,fcr\n\n~~645:~~~~~~MFL~~~~~~fp29=fp29,fp21,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,29\n\n~~645:~~~~~~MFL~~~~~~fp27=fp9,fp9,fcr\n\n~~645:~~~~~~MFL~~~~~~fp28=fp28,fp19,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,30\n\n~~645:~~~~~~MFL~~~~~~fp26=fp10,fp10,fcr\n\n~~645:~~~~~~MFL~~~~~~fp25=fp11,fp11,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,31\n\n~~645:~~~~~~MFL~~~~~~fp24=fp12,fp12,fcr\n\n~~645:~~~~~~MFL~~~~~~fp23=fp13,fp13,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,32\n\n~~645:~~~~~~MFL~~~~~~fp22=fp31,fp31,fcr\n\n~~645:~~~~~~MFL~~~~~~fp21=fp30,fp30,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,33\n\n~~645:~~~~~~FNMS~~~~~fp27=fp0,fp27,fp1,fcr\n\n~~645:~~~~~~MFL~~~~~~fp19=fp29,fp29,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,34\n\n~~645:~~~~~~MFL~~~~~~fp20=fp28,fp28,fcr\n\n~~645:~~~~~~FNMS~~~~~fp26=fp0,fp26,fp2,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,35\n\n~~645:~~~~~~FNMS~~~~~fp25=fp0,fp25,fp3,fcr\n\n~~645:~~~~~~FNMS~~~~~fp24=fp0,fp24,fp4,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,36\n\n~~645:~~~~~~FNMS~~~~~fp23=fp0,fp23,fp5,fcr\n\n~~645:~~~~~~FNMS~~~~~fp22=fp0,fp22,fp6,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,37\n\n~~645:~~~~~~FNMS~~~~~fp21=fp0,fp21,fp7,fcr\n\n~~645:~~~~~~FNMS~~~~~fp19=fp0,fp19,fp8,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,38\n\n~~645:~~~~~~MFL~~~~~~fp9=fp9,fp27,fcr\n\n~~645:~~~~~~FNMS~~~~~fp27=fp0,fp20,fp18,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,39\n\n~~645:~~~~~~MFL~~~~~~fp10=fp10,fp26,fcr\n\n~~645:~~~~~~MFL~~~~~~fp11=fp11,fp25,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,40\n\n~~645:~~~~~~MFL~~~~~~fp12=fp12,fp24,fcr\n\n~~645:~~~~~~MFL~~~~~~fp13=fp13,fp23,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,41\n\n~~645:~~~~~~MFL~~~~~~fp31=fp31,fp22,fcr\n\n~~645:~~~~~~MFL~~~~~~fp30=fp30,fp21,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,42\n\n~~645:~~~~~~MFL~~~~~~fp26=fp9,fp9,fcr\n\n~~645:~~~~~~MFL~~~~~~fp29=fp29,fp19,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,43\n\n~~645:~~~~~~MFL~~~~~~fp27=fp28,fp27,fcr\n\n~~645:~~~~~~MFL~~~~~~fp20=fp10,fp10,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,44\n\n~~645:~~~~~~MFL~~~~~~fp21=fp11,fp11,fcr\n\n~~645:~~~~~~MFL~~~~~~fp22=fp12,fp12,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,45\n\n~~645:~~~~~~MFL~~~~~~fp23=fp13,fp13,fcr\n\n~~645:~~~~~~MFL~~~~~~fp24=fp31,fp31,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,46\n\n~~645:~~~~~~MFL~~~~~~fp25=fp30,fp30,fcr\n\n~~645:~~~~~~MFL~~~~~~fp28=fp29,fp29,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,47\n\n~~645:~~~~~~FNMS~~~~~fp19=fp0,fp26,fp1,fcr\n\n~~645:~~~~~~MFL~~~~~~fp26=fp27,fp27,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,48\n\n~~645:~~~~~~FNMS~~~~~fp20=fp0,fp20,fp2,fcr\n\n~~645:~~~~~~FNMS~~~~~fp21=fp0,fp21,fp3,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,49\n\n~~645:~~~~~~FNMS~~~~~fp22=fp0,fp22,fp4,fcr\n\n~~645:~~~~~~FNMS~~~~~fp23=fp0,fp23,fp5,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,50\n\n~~645:~~~~~~FNMS~~~~~fp24=fp0,fp24,fp6,fcr\n\n~~645:~~~~~~FNMS~~~~~fp25=fp0,fp25,fp7,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,51\n\n~~645:~~~~~~FNMS~~~~~fp26=fp0,fp26,fp18,fcr\n\n~~645:~~~~~~FNMS~~~~~fp28=fp0,fp28,fp8,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,52\n\n~~645:~~~~~~MFL~~~~~~fp9=fp9,fp19,fcr\n\n~~645:~~~~~~MFL~~~~~~fp10=fp10,fp20,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,53\n\n~~645:~~~~~~MFL~~~~~~fp11=fp11,fp21,fcr\n\n~~645:~~~~~~MFL~~~~~~fp12=fp12,fp22,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,54\n\n~~645:~~~~~~MFL~~~~~~fp13=fp13,fp23,fcr\n\n~~645:~~~~~~MFL~~~~~~fp31=fp31,fp24,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,55\n\n~~645:~~~~~~MFL~~~~~~fp30=fp30,fp25,fcr\n\n~~645:~~~~~~MFL~~~~~~fp29=fp29,fp28,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,56\n\n~~645:~~~~~~MFL~~~~~~fp28=fp9,fp9,fcr\n\n~~645:~~~~~~MFL~~~~~~fp27=fp27,fp26,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,57\n\n~~645:~~~~~~MFL~~~~~~fp26=fp10,fp10,fcr\n\n~~645:~~~~~~MFL~~~~~~fp25=fp11,fp11,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,58\n\n~~645:~~~~~~MFL~~~~~~fp24=fp12,fp12,fcr\n\n~~645:~~~~~~MFL~~~~~~fp23=fp13,fp13,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,59\n\n~~645:~~~~~~MFL~~~~~~fp22=fp31,fp31,fcr\n\n~~645:~~~~~~MFL~~~~~~fp21=fp30,fp30,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,60\n\n~~645:~~~~~~MFL~~~~~~fp20=fp27,fp27,fcr\n\n~~645:~~~~~~MFL~~~~~~fp19=fp29,fp29,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,61\n\n~~~31:~~~~~~CONSUME~~gr1,gr2,lr,gr13-gr31,fp14-fp31,cr{[}234{]},fsr,fcr,ctr\n\n~~645:~~~~~~FNMS~~~~~fp1=fp0,fp28,fp1,fcr\n\n~~645:~~~~~~FNMS~~~~~fp2=fp0,fp26,fp2,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,62\n\n~~645:~~~~~~FNMS~~~~~fp3=fp0,fp25,fp3,fcr\n\n~~645:~~~~~~FNMS~~~~~fp4=fp0,fp24,fp4,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,63\n\n~~645:~~~~~~FNMS~~~~~fp5=fp0,fp23,fp5,fcr\n\n~~645:~~~~~~FNMS~~~~~fp6=fp0,fp22,fp6,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,64\n\n~~645:~~~~~~FNMS~~~~~fp7=fp0,fp21,fp7,fcr\n\n~~645:~~~~~~FNMS~~~~~fp8=fp0,fp19,fp8,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,65\n\n~~645:~~~~~~MFL~~~~~~fp1=fp9,fp1,fcr\n\n~~645:~~~~~~FNMS~~~~~fp0=fp0,fp20,fp18,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,66\n\n~~645:~~~~~~MFL~~~~~~fp2=fp10,fp2,fcr\n\n~~645:~~~~~~MFL~~~~~~fp3=fp11,fp3,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,67\n\n~~645:~~~~~~MFL~~~~~~fp4=fp12,fp4,fcr\n\n~~645:~~~~~~MFL~~~~~~fp5=fp13,fp5,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,68\n\n~~645:~~~~~~MFL~~~~~~fp6=fp31,fp6,fcr\n\n~~645:~~~~~~MFL~~~~~~fp7=fp30,fp7,fcr\n\n~~~22:~~~~~~STFL~~~~~(double)(gr3,0)=fp1\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,69\n\n~~645:~~~~~~MFL~~~~~~fp1=fp29,fp8,fcr\n\n~~645:~~~~~~MFL~~~~~~fp0=fp27,fp0,fcr\n\n~~~23:~~~~~~STFL~~~~~(double)(gr3,8)=fp2\n\n~~~24:~~~~~~STFL~~~~~(double)(gr3,16)=fp3\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,70\n\n~~~25:~~~~~~STFL~~~~~(double)(gr3,24)=fp4\n\n~~~26:~~~~~~STFL~~~~~(double)(gr3,32)=fp5\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,71\n\n~~~27:~~~~~~STFL~~~~~(double)(gr3,40)=fp6\n\n~~~28:~~~~~~STFL~~~~~(double)(gr3,48)=fp7\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,72\n\n~~~29:~~~~~~STFL~~~~~(double)(gr3,56)=fp1\n\n~~~30:~~~~~~STFL~~~~~(double)(gr3,64)=fp0\n\n~~~~0:~~~~~~FENCE~~~~\n\n~~~31:~~~~~~CALLF~~~~\\_restf18\n\n~~~~3:~~~~~~BB\\_END~~~\n\n~~~~4:~~~~~~BB\\_BEGIN~~~~3~/~~~~0\n\n~~~31:~~~~~~PEND~~~~~\n\n~~~~4:~~~~~~BB\\_END~~~\n\n{*}{*}~End~of~Procedure~List~for~Proc~\\#~~~1:~nineroot\\_\\_FPdPCd~End~of~Phase~3~{*}{*}\n\n-qdebug=PLST3:CYCLES:PLST3:CYCLES:PLSTHUMM:HUMMDBG:RECIPF:MAXGRIDICULOUS:NEWSCHED1:NEWSCHED2:EBBPASS1:EBBPASS2:\n\n~GPR's~set/used:~~~s-uu~s-{}-{}-~-{}-{}-{}-~-{}-{}-{}-~~-{}-{}-{}-~-{}-{}-{}-~-{}-{}-{}-~-{}-{}-{}-\n\n~FPR's~set/used:~~~ssss~ssss~ssss~ss-{}-~~-{}-ss~ssss~ssss~ssss\n\n~CCR's~set/used:~~~-{}-{}-{}-~-{}-{}-{}-\n\n~~~~~|~000000~~~~~~~~~~~~~~~~~~~~~~~~~~~PDEF~~~~~nineroot(double~{*},~const~double~{*})\n\n~~~~0|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~PROC~~~~~f,x,gr3,gr4\n\n~~~~0|~000000~mfspr~~~~7C0802A6~~~1~~~~~LFLR~~~~~gr0=lr\n\n~~~~0|~000004~bl~~~~~~~4BFFFFFD~~~0~~~~~CALLNR~~~\\_savef18,gr1,fp18-fp31,lr\\char`\\\"{}\n\n~~~~0|~000008~mtspr~~~~7C0803A6~~~1~~~~~LLR~~~~~~lr=gr0\n\n~~~~4|~00000C~lfd~~~~~~C8240000~~~1~~~~~LFL~~~~~~fp1=(double)(gr4,0)\n\n~~~~5|~000010~lfd~~~~~~C8440008~~~1~~~~~LFL~~~~~~fp2=(double)(gr4,8)\n\n~~~~6|~000014~lfd~~~~~~C8640010~~~1~~~~~LFL~~~~~~fp3=(double)(gr4,16)\n\n~~~~7|~000018~lfd~~~~~~C8840018~~~1~~~~~LFL~~~~~~fp4=(double)(gr4,24)\n\n~~~~8|~00001C~lfd~~~~~~C8A40020~~~1~~~~~LFL~~~~~~fp5=(double)(gr4,32)\n\n~~~~9|~000020~lfd~~~~~~C8C40028~~~1~~~~~LFL~~~~~~fp6=(double)(gr4,40)\n\n~~~10|~000024~lfd~~~~~~C8E40030~~~1~~~~~LFL~~~~~~fp7=(double)(gr4,48)\n\n~~~11|~000028~lfd~~~~~~C9040038~~~1~~~~~LFL~~~~~~fp8=(double)(gr4,56)\n\n~~645|~00002C~frsqrte~~FD200834~~~1~~~~~FRSQRE~~~fp9=fp1\n\n~~645|~000030~frsqrte~~FD401034~~~1~~~~~FRSQRE~~~fp10=fp2\n\n~~~12|~000034~lfd~~~~~~CAA40040~~~1~~~~~LFL~~~~~~fp21=(double)(gr4,64)\n\n~~645|~000038~lwz~~~~~~80820004~~~1~~~~~L4A~~~~~~gr4=.+CONSTANT\\_AREA(gr2,0)\n\n~~645|~00003C~frsqrte~~FD601834~~~1~~~~~FRSQRE~~~fp11=fp3\n\n~~645|~000040~frsqrte~~FD802034~~~1~~~~~FRSQRE~~~fp12=fp4\n\n~~645|~000044~frsqrte~~FDA02834~~~1~~~~~FRSQRE~~~fp13=fp5\n\n~~645|~000048~frsqrte~~FFE03034~~~1~~~~~FRSQRE~~~fp31=fp6\n\n~~645|~00004C~lfs~~~~~~C0040000~~~1~~~~~LFS~~~~~~fp0=+CONSTANT\\_AREA(gr4,0)\n\n~~645|~000050~frsqrte~~FFC03834~~~1~~~~~FRSQRE~~~fp30=fp7\n\n~~645|~000054~frsqrte~~FFA04034~~~1~~~~~FRSQRE~~~fp29=fp8\n\n~~645|~000058~fmul~~~~~FE890272~~~1~~~~~MFL~~~~~~fp20=fp9,fp9,fcr\n\n~~645|~00005C~frsqrte~~FF80A834~~~1~~~~~FRSQRE~~~fp28=fp21\n\n~~645|~000060~fmul~~~~~FF6A02B2~~~1~~~~~MFL~~~~~~fp27=fp10,fp10,fcr\n\n~~645|~000064~fmul~~~~~FF4B02F2~~~1~~~~~MFL~~~~~~fp26=fp11,fp11,fcr\n\n~~645|~000068~fmsub~~~~FC210838~~~1~~~~~FMS~~~~~~fp1=fp1,fp1,fp0,fcr\n\n~~645|~00006C~fmsub~~~~FC421038~~~1~~~~~FMS~~~~~~fp2=fp2,fp2,fp0,fcr\n\n~~645|~000070~fmsub~~~~FC631838~~~1~~~~~FMS~~~~~~fp3=fp3,fp3,fp0,fcr\n\n~~645|~000074~fmsub~~~~FE55A838~~~1~~~~~FMS~~~~~~fp18=fp21,fp21,fp0,fcr\n\n~~645|~000078~fmsub~~~~FC842038~~~1~~~~~FMS~~~~~~fp4=fp4,fp4,fp0,fcr\n\n~~645|~00007C~fmul~~~~~FF2C0332~~~1~~~~~MFL~~~~~~fp25=fp12,fp12,fcr\n\n~~645|~000080~fmsub~~~~FCA52838~~~1~~~~~FMS~~~~~~fp5=fp5,fp5,fp0,fcr\n\n~~645|~000084~fmul~~~~~FF0D0372~~~1~~~~~MFL~~~~~~fp24=fp13,fp13,fcr\n\n~~645|~000088~fmsub~~~~FCC63038~~~1~~~~~FMS~~~~~~fp6=fp6,fp6,fp0,fcr\n\n~~645|~00008C~fmsub~~~~FCE73838~~~1~~~~~FMS~~~~~~fp7=fp7,fp7,fp0,fcr\n\n~~645|~000090~fmul~~~~~FEFF07F2~~~1~~~~~MFL~~~~~~fp23=fp31,fp31,fcr\n\n~~645|~000094~fmsub~~~~FD084038~~~1~~~~~FMS~~~~~~fp8=fp8,fp8,fp0,fcr\n\n~~645|~000098~fmul~~~~~FEDE07B2~~~1~~~~~MFL~~~~~~fp22=fp30,fp30,fcr\n\n~~645|~00009C~fmul~~~~~FEBD0772~~~1~~~~~MFL~~~~~~fp21=fp29,fp29,fcr\n\n~~645|~0000A0~fnmsub~~~FE94007C~~~1~~~~~FNMS~~~~~fp20=fp0,fp20,fp1,fcr\n\n~~645|~0000A4~fmul~~~~~FE7C0732~~~1~~~~~MFL~~~~~~fp19=fp28,fp28,fcr\n\n~~645|~0000A8~fnmsub~~~FF7B00BC~~~1~~~~~FNMS~~~~~fp27=fp0,fp27,fp2,fcr\n\n~~645|~0000AC~fnmsub~~~FF5A00FC~~~1~~~~~FNMS~~~~~fp26=fp0,fp26,fp3,fcr\n\n~~645|~0000B0~fnmsub~~~FF39013C~~~1~~~~~FNMS~~~~~fp25=fp0,fp25,fp4,fcr\n\n~~645|~0000B4~fnmsub~~~FF18017C~~~1~~~~~FNMS~~~~~fp24=fp0,fp24,fp5,fcr\n\n~~645|~0000B8~fnmsub~~~FEF701BC~~~1~~~~~FNMS~~~~~fp23=fp0,fp23,fp6,fcr\n\n~~645|~0000BC~fnmsub~~~FED601FC~~~1~~~~~FNMS~~~~~fp22=fp0,fp22,fp7,fcr\n\n~~645|~0000C0~fmul~~~~~FD290532~~~1~~~~~MFL~~~~~~fp9=fp9,fp20,fcr\n\n~~645|~0000C4~fnmsub~~~FEB5023C~~~1~~~~~FNMS~~~~~fp21=fp0,fp21,fp8,fcr\n\n~~645|~0000C8~fnmsub~~~FE7304BC~~~1~~~~~FNMS~~~~~fp19=fp0,fp19,fp18,fcr\n\n~~645|~0000CC~fmul~~~~~FD4A06F2~~~1~~~~~MFL~~~~~~fp10=fp10,fp27,fcr\n\n~~645|~0000D0~fmul~~~~~FD6B06B2~~~1~~~~~MFL~~~~~~fp11=fp11,fp26,fcr\n\n~~645|~0000D4~fmul~~~~~FD8C0672~~~1~~~~~MFL~~~~~~fp12=fp12,fp25,fcr\n\n~~645|~0000D8~fmul~~~~~FDAD0632~~~1~~~~~MFL~~~~~~fp13=fp13,fp24,fcr\n\n~~645|~0000DC~fmul~~~~~FFFF05F2~~~1~~~~~MFL~~~~~~fp31=fp31,fp23,fcr\n\n~~645|~0000E0~fmul~~~~~FFDE05B2~~~1~~~~~MFL~~~~~~fp30=fp30,fp22,fcr\n\n~~645|~0000E4~fmul~~~~~FFBD0572~~~1~~~~~MFL~~~~~~fp29=fp29,fp21,fcr\n\n~~645|~0000E8~fmul~~~~~FF690272~~~1~~~~~MFL~~~~~~fp27=fp9,fp9,fcr\n\n~~645|~0000EC~fmul~~~~~FF9C04F2~~~1~~~~~MFL~~~~~~fp28=fp28,fp19,fcr\n\n~~645|~0000F0~fmul~~~~~FF4A02B2~~~1~~~~~MFL~~~~~~fp26=fp10,fp10,fcr\n\n~~645|~0000F4~fmul~~~~~FF2B02F2~~~1~~~~~MFL~~~~~~fp25=fp11,fp11,fcr\n\n~~645|~0000F8~fmul~~~~~FF0C0332~~~1~~~~~MFL~~~~~~fp24=fp12,fp12,fcr\n\n~~645|~0000FC~fmul~~~~~FEED0372~~~1~~~~~MFL~~~~~~fp23=fp13,fp13,fcr\n\n~~645|~000100~fmul~~~~~FEDF07F2~~~1~~~~~MFL~~~~~~fp22=fp31,fp31,fcr\n\n~~645|~000104~fmul~~~~~FEBE07B2~~~1~~~~~MFL~~~~~~fp21=fp30,fp30,fcr\n\n~~645|~000108~fnmsub~~~FF7B007C~~~1~~~~~FNMS~~~~~fp27=fp0,fp27,fp1,fcr\n\n~~645|~00010C~fmul~~~~~FE7D0772~~~1~~~~~MFL~~~~~~fp19=fp29,fp29,fcr\n\n~~645|~000110~fmul~~~~~FE9C0732~~~1~~~~~MFL~~~~~~fp20=fp28,fp28,fcr\n\n~~645|~000114~fnmsub~~~FF5A00BC~~~1~~~~~FNMS~~~~~fp26=fp0,fp26,fp2,fcr\n\n~~645|~000118~fnmsub~~~FF3900FC~~~1~~~~~FNMS~~~~~fp25=fp0,fp25,fp3,fcr\n\n~~645|~00011C~fnmsub~~~FF18013C~~~1~~~~~FNMS~~~~~fp24=fp0,fp24,fp4,fcr\n\n~~645|~000120~fnmsub~~~FEF7017C~~~1~~~~~FNMS~~~~~fp23=fp0,fp23,fp5,fcr\n\n~~645|~000124~fnmsub~~~FED601BC~~~1~~~~~FNMS~~~~~fp22=fp0,fp22,fp6,fcr\n\n~~645|~000128~fnmsub~~~FEB501FC~~~1~~~~~FNMS~~~~~fp21=fp0,fp21,fp7,fcr\n\n~~645|~00012C~fnmsub~~~FE73023C~~~1~~~~~FNMS~~~~~fp19=fp0,fp19,fp8,fcr\n\n~~645|~000130~fmul~~~~~FD2906F2~~~1~~~~~MFL~~~~~~fp9=fp9,fp27,fcr\n\n~~645|~000134~fnmsub~~~FF7404BC~~~1~~~~~FNMS~~~~~fp27=fp0,fp20,fp18,fcr\n\n~~645|~000138~fmul~~~~~FD4A06B2~~~1~~~~~MFL~~~~~~fp10=fp10,fp26,fcr\n\n~~645|~00013C~fmul~~~~~FD6B0672~~~1~~~~~MFL~~~~~~fp11=fp11,fp25,fcr\n\n~~645|~000140~fmul~~~~~FD8C0632~~~1~~~~~MFL~~~~~~fp12=fp12,fp24,fcr\n\n~~645|~000144~fmul~~~~~FDAD05F2~~~1~~~~~MFL~~~~~~fp13=fp13,fp23,fcr\n\n~~645|~000148~fmul~~~~~FFFF05B2~~~1~~~~~MFL~~~~~~fp31=fp31,fp22,fcr\n\n~~645|~00014C~fmul~~~~~FFDE0572~~~1~~~~~MFL~~~~~~fp30=fp30,fp21,fcr\n\n~~645|~000150~fmul~~~~~FF490272~~~1~~~~~MFL~~~~~~fp26=fp9,fp9,fcr\n\n~~645|~000154~fmul~~~~~FFBD04F2~~~1~~~~~MFL~~~~~~fp29=fp29,fp19,fcr\n\n~~645|~000158~fmul~~~~~FF7C06F2~~~1~~~~~MFL~~~~~~fp27=fp28,fp27,fcr\n\n~~645|~00015C~fmul~~~~~FE8A02B2~~~1~~~~~MFL~~~~~~fp20=fp10,fp10,fcr\n\n~~645|~000160~fmul~~~~~FEAB02F2~~~1~~~~~MFL~~~~~~fp21=fp11,fp11,fcr\n\n~~645|~000164~fmul~~~~~FECC0332~~~1~~~~~MFL~~~~~~fp22=fp12,fp12,fcr\n\n~~645|~000168~fmul~~~~~FEED0372~~~1~~~~~MFL~~~~~~fp23=fp13,fp13,fcr\n\n~~645|~00016C~fmul~~~~~FF1F07F2~~~1~~~~~MFL~~~~~~fp24=fp31,fp31,fcr\n\n~~645|~000170~fmul~~~~~FF3E07B2~~~1~~~~~MFL~~~~~~fp25=fp30,fp30,fcr\n\n~~645|~000174~fmul~~~~~FF9D0772~~~1~~~~~MFL~~~~~~fp28=fp29,fp29,fcr\n\n~~645|~000178~fnmsub~~~FE7A007C~~~1~~~~~FNMS~~~~~fp19=fp0,fp26,fp1,fcr\n\n~~645|~00017C~fmul~~~~~FF5B06F2~~~1~~~~~MFL~~~~~~fp26=fp27,fp27,fcr\n\n~~645|~000180~fnmsub~~~FE9400BC~~~1~~~~~FNMS~~~~~fp20=fp0,fp20,fp2,fcr\n\n~~645|~000184~fnmsub~~~FEB500FC~~~1~~~~~FNMS~~~~~fp21=fp0,fp21,fp3,fcr\n\n~~645|~000188~fnmsub~~~FED6013C~~~1~~~~~FNMS~~~~~fp22=fp0,fp22,fp4,fcr\n\n~~645|~00018C~fnmsub~~~FEF7017C~~~1~~~~~FNMS~~~~~fp23=fp0,fp23,fp5,fcr\n\n~~645|~000190~fnmsub~~~FF1801BC~~~1~~~~~FNMS~~~~~fp24=fp0,fp24,fp6,fcr\n\n~~645|~000194~fnmsub~~~FF3901FC~~~1~~~~~FNMS~~~~~fp25=fp0,fp25,fp7,fcr\n\n~~645|~000198~fnmsub~~~FF5A04BC~~~1~~~~~FNMS~~~~~fp26=fp0,fp26,fp18,fcr\n\n~~645|~00019C~fnmsub~~~FF9C023C~~~1~~~~~FNMS~~~~~fp28=fp0,fp28,fp8,fcr\n\n~~645|~0001A0~fmul~~~~~FD2904F2~~~1~~~~~MFL~~~~~~fp9=fp9,fp19,fcr\n\n~~645|~0001A4~fmul~~~~~FD4A0532~~~1~~~~~MFL~~~~~~fp10=fp10,fp20,fcr\n\n~~645|~0001A8~fmul~~~~~FD6B0572~~~1~~~~~MFL~~~~~~fp11=fp11,fp21,fcr\n\n~~645|~0001AC~fmul~~~~~FD8C05B2~~~1~~~~~MFL~~~~~~fp12=fp12,fp22,fcr\n\n~~645|~0001B0~fmul~~~~~FDAD05F2~~~1~~~~~MFL~~~~~~fp13=fp13,fp23,fcr\n\n~~645|~0001B4~fmul~~~~~FFFF0632~~~1~~~~~MFL~~~~~~fp31=fp31,fp24,fcr\n\n~~645|~0001B8~fmul~~~~~FFDE0672~~~1~~~~~MFL~~~~~~fp30=fp30,fp25,fcr\n\n~~645|~0001BC~fmul~~~~~FFBD0732~~~1~~~~~MFL~~~~~~fp29=fp29,fp28,fcr\n\n~~645|~0001C0~fmul~~~~~FF890272~~~1~~~~~MFL~~~~~~fp28=fp9,fp9,fcr\n\n~~645|~0001C4~fmul~~~~~FF7B06B2~~~1~~~~~MFL~~~~~~fp27=fp27,fp26,fcr\n\n~~645|~0001C8~fmul~~~~~FF4A02B2~~~1~~~~~MFL~~~~~~fp26=fp10,fp10,fcr\n\n~~645|~0001CC~fmul~~~~~FF2B02F2~~~1~~~~~MFL~~~~~~fp25=fp11,fp11,fcr\n\n~~645|~0001D0~fmul~~~~~FF0C0332~~~1~~~~~MFL~~~~~~fp24=fp12,fp12,fcr\n\n~~645|~0001D4~fmul~~~~~FEED0372~~~1~~~~~MFL~~~~~~fp23=fp13,fp13,fcr\n\n~~645|~0001D8~fmul~~~~~FEDF07F2~~~1~~~~~MFL~~~~~~fp22=fp31,fp31,fcr\n\n~~645|~0001DC~fmul~~~~~FEBE07B2~~~1~~~~~MFL~~~~~~fp21=fp30,fp30,fcr\n\n~~645|~0001E0~fmul~~~~~FE9B06F2~~~1~~~~~MFL~~~~~~fp20=fp27,fp27,fcr\n\n~~645|~0001E4~fmul~~~~~FE7D0772~~~1~~~~~MFL~~~~~~fp19=fp29,fp29,fcr\n\n~~645|~0001E8~fnmsub~~~FC3C007C~~~1~~~~~FNMS~~~~~fp1=fp0,fp28,fp1,fcr\n\n~~645|~0001EC~fnmsub~~~FC5A00BC~~~1~~~~~FNMS~~~~~fp2=fp0,fp26,fp2,fcr\n\n~~645|~0001F0~fnmsub~~~FC7900FC~~~1~~~~~FNMS~~~~~fp3=fp0,fp25,fp3,fcr\n\n~~645|~0001F4~fnmsub~~~FC98013C~~~1~~~~~FNMS~~~~~fp4=fp0,fp24,fp4,fcr\n\n~~645|~0001F8~fnmsub~~~FCB7017C~~~1~~~~~FNMS~~~~~fp5=fp0,fp23,fp5,fcr\n\n~~645|~0001FC~fnmsub~~~FCD601BC~~~1~~~~~FNMS~~~~~fp6=fp0,fp22,fp6,fcr\n\n~~645|~000200~fnmsub~~~FCF501FC~~~1~~~~~FNMS~~~~~fp7=fp0,fp21,fp7,fcr\n\n~~645|~000204~fnmsub~~~FD13023C~~~1~~~~~FNMS~~~~~fp8=fp0,fp19,fp8,fcr\n\n~~645|~000208~fmul~~~~~FC290072~~~1~~~~~MFL~~~~~~fp1=fp9,fp1,fcr\n\n~~645|~00020C~fnmsub~~~FC1404BC~~~1~~~~~FNMS~~~~~fp0=fp0,fp20,fp18,fcr\n\n~~645|~000210~fmul~~~~~FC4A00B2~~~1~~~~~MFL~~~~~~fp2=fp10,fp2,fcr\n\n~~645|~000214~fmul~~~~~FC6B00F2~~~1~~~~~MFL~~~~~~fp3=fp11,fp3,fcr\n\n~~645|~000218~fmul~~~~~FC8C0132~~~1~~~~~MFL~~~~~~fp4=fp12,fp4,fcr\n\n~~645|~00021C~fmul~~~~~FCAD0172~~~1~~~~~MFL~~~~~~fp5=fp13,fp5,fcr\n\n~~645|~000220~fmul~~~~~FCDF01B2~~~1~~~~~MFL~~~~~~fp6=fp31,fp6,fcr\n\n~~645|~000224~fmul~~~~~FCFE01F2~~~1~~~~~MFL~~~~~~fp7=fp30,fp7,fcr\n\n~~~22|~000228~stfd~~~~~D8230000~~~1~~~~~STFL~~~~~(double)(gr3,0)=fp1\n\n~~645|~00022C~fmul~~~~~FC3D0232~~~1~~~~~MFL~~~~~~fp1=fp29,fp8,fcr\n\n~~645|~000230~fmul~~~~~FC1B0032~~~1~~~~~MFL~~~~~~fp0=fp27,fp0,fcr\n\n~~~23|~000234~stfd~~~~~D8430008~~~1~~~~~STFL~~~~~(double)(gr3,8)=fp2\n\n~~~24|~000238~stfd~~~~~D8630010~~~1~~~~~STFL~~~~~(double)(gr3,16)=fp3\n\n~~~25|~00023C~stfd~~~~~D8830018~~~1~~~~~STFL~~~~~(double)(gr3,24)=fp4\n\n~~~26|~000240~stfd~~~~~D8A30020~~~1~~~~~STFL~~~~~(double)(gr3,32)=fp5\n\n~~~27|~000244~stfd~~~~~D8C30028~~~1~~~~~STFL~~~~~(double)(gr3,40)=fp6\n\n~~~28|~000248~stfd~~~~~D8E30030~~~1~~~~~STFL~~~~~(double)(gr3,48)=fp7\n\n~~~29|~00024C~stfd~~~~~D8230038~~~1~~~~~STFL~~~~~(double)(gr3,56)=fp1\n\n~~~30|~000250~stfd~~~~~D8030040~~~1~~~~~STFL~~~~~(double)(gr3,64)=fp0\n\n~~~31|~000254~b~~~~~~~~4BFFFDAC~~~0~~~~~CALLF~~~~\\_restf18\n\n~~~~~|~~~~~~~~~~~~~~~Tag~Table\n\n~~~~~|~000258~~~~~~~~00000000~00092200~0E000000~00000258\n\n~~~~~|~~~~~~~~~~~~~~~Instruction~count~~~~~~~~~~150\n\n~~~~~|~~~~~~~~~~~~~~~Constant~Area\n\n~~~~~|~000000~~~~~~~~3FC00000\n\n\n\\end{lyxcode}\n\n\\subsection{BG/L}\n\n\\begin{lyxcode}\nIBM(R)~VisualAge~C++~Version~6.0.0.3~for~Linux~on~pSeries~-{}-{}-~\n\n>\\,{}>\\,{}>\\,{}>\\,{}>~OPTIONS~SECTION~<\\,{}<\\,{}<\\,{}<\\,{}<\n\nIGNERRNO~~~~~~~~ARCH=440D~~~~~~~OPT=3~~~~~~~~~~~ALIAS=ANSI~~~~~~ALIGN=LINUXPPC\n\nFLOAT=NOHSFLT:NORNDSNGL:NOHSSNGL:MAF:NORRM:FOLD:NONANS:RSQRT:FLTINT:NOEMULATE\n\nMAXMEM=-1~~~~~~~NOSTRICT~~~~~~~~NOSTRICT\\_INDUCTION~~~TBTABLE=SMALL~~~LIST\n\nSHOWINC=NOSYS:NOUSR~~~~~~~~~~~~~SOURCE~~~~~~~~~~STATICINLINE~~~~TMPLPARSE=NO\n\nNOEH\n\n>\\,{}>\\,{}>\\,{}>\\,{}>~SOURCE~SECTION~<\\,{}<\\,{}<\\,{}<\\,{}<\n\n~~~~~~~~~~~~1~|~\\#include~<math.h>\n\n~~~~~~~~~~~~2~|~void~nineroot(double{*}~f,~const~double{*}~x)\n\n~~~~~~~~~~~~3~|~\\{\n\n~~~~~~~~~~~~4~|~~~~double~x0~=~x{[}0{]}~;\n\n~~~~~~~~~~~~5~|~~~~double~x1~=~x{[}1{]}~;\n\n~~~~~~~~~~~~6~|~~~~double~x2~=~x{[}2{]}~;\n\n~~~~~~~~~~~~7~|~~~~double~x3~=~x{[}3{]}~;\n\n~~~~~~~~~~~~8~|~~~~double~x4~=~x{[}4{]}~;\n\n~~~~~~~~~~~~9~|~~~~double~x5~=~x{[}5{]}~;\n\n~~~~~~~~~~~10~|~~~~double~x6~=~x{[}6{]}~;\n\n~~~~~~~~~~~11~|~~~~double~x7~=~x{[}7{]}~;\n\n~~~~~~~~~~~12~|~~~~double~x8~=~x{[}8{]}~;\n\n~~~~~~~~~~~13~|~~~~double~r0~=~1.0/sqrt(x0)~;\n\n~~~~~~~~~~~14~|~~~~double~r1~=~1.0/sqrt(x1)~;\n\n~~~~~~~~~~~15~|~~~~double~r2~=~1.0/sqrt(x2)~;\n\n~~~~~~~~~~~16~|~~~~double~r3~=~1.0/sqrt(x3)~;\n\n~~~~~~~~~~~17~|~~~~double~r4~=~1.0/sqrt(x4)~;\n\n~~~~~~~~~~~18~|~~~~double~r5~=~1.0/sqrt(x5)~;\n\n~~~~~~~~~~~19~|~~~~double~r6~=~1.0/sqrt(x6)~;\n\n~~~~~~~~~~~20~|~~~~double~r7~=~1.0/sqrt(x7)~;\n\n~~~~~~~~~~~21~|~~~~double~r8~=~1.0/sqrt(x8)~;\n\n~~~~~~~~~~~22~|~~~~f{[}0{]}~=~r0~;\n\n~~~~~~~~~~~23~|~~~~f{[}1{]}~=~r1~;\n\n~~~~~~~~~~~24~|~~~~f{[}2{]}~=~r2~;\n\n~~~~~~~~~~~25~|~~~~f{[}3{]}~=~r3~;\n\n~~~~~~~~~~~26~|~~~~f{[}4{]}~=~r4~;\n\n~~~~~~~~~~~27~|~~~~f{[}5{]}~=~r5~;\n\n~~~~~~~~~~~28~|~~~~f{[}6{]}~=~r6~;\n\n~~~~~~~~~~~29~|~~~~f{[}7{]}~=~r7~;\n\n~~~~~~~~~~~30~|~~~~f{[}8{]}~=~r8~;\n\n~~~~~~~~~~~31~|~\\}\n\n{*}{*}~Procedure~List~for~Proc~\\#~~~1:~\\_Z8ninerootPdPKd~End~of~Phase~3~{*}{*}\n\n~~~~0:~~~~~~HDR\n\n~~~~4:~~~~~~BB\\_BEGIN~~~~2~/~~~~0\n\n~~~~3:~~~~~~PROC~~~~~f,x,gr3,gr4\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,0\n\n~~~~0:~~~~~~LR~~~~~~~gr12=gr1\n\n~~~~0:~~~~~~LI~~~~~~~gr0=-16\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,1\n\n~~~~0:~~~~~~ST4U~~~~~gr1,\\#stack(gr1,-96)=gr1\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,2\n\n~~~~0:~~~~~~SFPLU~~~~gr12,\\#stack(gr12,gr0,0)=fp31,fp63\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,3\n\n~~~~0:~~~~~~SFPLU~~~~gr12,\\#stack(gr12,gr0,0)=fp30,fp62\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,4\n\n~~~~0:~~~~~~SFPLU~~~~gr12,\\#stack(gr12,gr0,0)=fp29,fp61\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,5\n\n~~~~0:~~~~~~SFPLU~~~~gr12,\\#stack(gr12,gr0,0)=fp28,fp60\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,6\n\n~~~~0:~~~~~~SFPLU~~~~gr12,\\#stack(gr12,gr0,0)=fp27,fp59\n\n~~~~0:~~~~~~FENCE\n\n~~~~0:~~~~~~DIRCTIV~~end\\_prologue\n\n~~~~0:~~~~~~FENCE\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,0\n\n~~~31:~~~~~~DIRCTIV~~start\\_epilogue\n\n~~~~4:~~~~~~LFL~~~~~~fp13=(double)(gr4,0)\n\n~~~~5:~~~~~~LI~~~~~~~gr6=8\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,1\n\n~~~~7:~~~~~~LI~~~~~~~gr5=24\n\n~~~~5:~~~~~~LFL~~~~~~fp45=(double)(gr4,gr6,0,trap=8)\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,2\n\n~~~~9:~~~~~~LI~~~~~~~gr8=40\n\n~~~11:~~~~~~LI~~~~~~~gr6=56\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,3\n\n~~~13:~~~~~~LA~~~~~~~gr7=.+CONSTANT\\_AREA\\%HI(gr2,0)\n\n~~~~6:~~~~~~LFL~~~~~~fp11=(double)(gr4,16)\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,4\n\n~~~13:~~~~~~LA~~~~~~~gr7=+CONSTANT\\_AREA\\%LO(gr7,0)\n\n~~~~7:~~~~~~LFL~~~~~~fp43=(double)(gr4,gr5,0,trap=24)\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,5\n\n~~~~8:~~~~~~LFL~~~~~~fp10=(double)(gr4,32)\n\n~~~13:~~~~~~FPRSQRE~~fp9,fp41=fp13,fp45\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,6\n\n~~~~9:~~~~~~LFL~~~~~~fp42=(double)(gr4,gr8,0,trap=40)\n\n~~~31:~~~~~~LR~~~~~~~gr12=gr1\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,7\n\n~~~10:~~~~~~LFL~~~~~~fp8=(double)(gr4,48)\n\n~~~31:~~~~~~LI~~~~~~~gr0=16\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,8\n\n~~~11:~~~~~~LFL~~~~~~fp40=(double)(gr4,gr6,0,trap=56)\n\n~~~15:~~~~~~FPRSQRE~~fp7,fp39=fp11,fp43\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,9\n\n~~~13:~~~~~~LI~~~~~~~gr6=32\n\n~~~12:~~~~~~LFL~~~~~~fp31=(double)(gr4,64)\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,10\n\n~~~13:~~~~~~LFPS~~~~~fp27,fp59=+CONSTANT\\_AREA(gr7,gr5,0,trap=24)\n\n~~~13:~~~~~~FPMUL~~~~fp12,fp44=fp9,fp41,fp9,fp41,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,11\n\n~~~17:~~~~~~FPRSQRE~~fp6,fp38=fp10,fp42\n\n~~~13:~~~~~~LFS~~~~~~fp30=+CONSTANT\\_AREA(gr7,4)\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,12\n\n~~~19:~~~~~~FPRSQRE~~fp4,fp36=fp8,fp40\n\n~~~13:~~~~~~LFPS~~~~~fp5,fp37=+CONSTANT\\_AREA(gr7,gr6,0,trap=32)\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,13\n\n~~~21:~~~~~~FRSQRE~~~fp29=fp31\n\n~~~13:~~~~~~LFPS~~~~~fp3,fp35=+CONSTANT\\_AREA(gr7,gr8,0,trap=40)\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,14\n\n~~~13:~~~~~~LI~~~~~~~gr4=48\n\n~~~15:~~~~~~FPMUL~~~~fp1,fp33=fp7,fp39,fp7,fp39,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,15\n\n~~~13:~~~~~~LFPS~~~~~fp2,fp34=+CONSTANT\\_AREA(gr7,gr4,0,trap=48)\n\n~~~13:~~~~~~FPMADD~~~fp13,fp45=fp27,fp59,fp13,fp45,fp12,fp44,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,16\n\n~~~17:~~~~~~FPMUL~~~~fp0,fp32=fp6,fp38,fp6,fp38,fcr\n\n~~~23:~~~~~~LI~~~~~~~gr6=8\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,17\n\n~~~19:~~~~~~FPMUL~~~~fp12,fp44=fp4,fp36,fp4,fp36,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,18\n\n~~~21:~~~~~~MFL~~~~~~fp28=fp29,fp29,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,19\n\n~~~15:~~~~~~FPMADD~~~fp1,fp33=fp27,fp59,fp11,fp43,fp1,fp33,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,21\n\n~~~17:~~~~~~FPMADD~~~fp10,fp42=fp27,fp59,fp10,fp42,fp0,fp32,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,22\n\n~~~19:~~~~~~FPMADD~~~fp8,fp40=fp27,fp59,fp8,fp40,fp12,fp44,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,23\n\n~~~21:~~~~~~FMA~~~~~~fp31=fp27,fp31,fp28,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,24\n\n~~~13:~~~~~~FXPMADD~~fp0,fp32=fp5,fp37,fp13,fp45,fp30,fp30,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,25\n\n~~~15:~~~~~~FXPMADD~~fp12,fp44=fp5,fp37,fp1,fp33,fp30,fp30,fcr\n\n~~~31:~~~~~~LFPLU~~~~fp27,fp59,gr12=\\#stack(gr12,gr0,0)\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,26\n\n~~~17:~~~~~~FXPMADD~~fp11,fp43=fp5,fp37,fp10,fp42,fp30,fp30,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,27\n\n~~~19:~~~~~~FXPMADD~~fp28,fp60=fp5,fp37,fp8,fp40,fp30,fp30,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,28\n\n~~~21:~~~~~~FMA~~~~~~fp5=fp5,fp31,fp30,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,29\n\n~~~13:~~~~~~FPMADD~~~fp0,fp32=fp3,fp35,fp13,fp45,fp0,fp32,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,30\n\n~~~15:~~~~~~FPMADD~~~fp12,fp44=fp3,fp35,fp1,fp33,fp12,fp44,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,31\n\n~~~17:~~~~~~FPMADD~~~fp11,fp43=fp3,fp35,fp10,fp42,fp11,fp43,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,32\n\n~~~19:~~~~~~FPMADD~~~fp30,fp62=fp3,fp35,fp8,fp40,fp28,fp60,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,33\n\n~~~21:~~~~~~FMA~~~~~~fp5=fp3,fp31,fp5,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,34\n\n~~~13:~~~~~~FPMADD~~~fp0,fp32=fp2,fp34,fp13,fp45,fp0,fp32,fcr\n\n~~~31:~~~~~~LFPLU~~~~fp28,fp60,gr12=\\#stack(gr12,gr0,0)\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,35\n\n~~~15:~~~~~~FPMADD~~~fp3,fp35=fp2,fp34,fp1,fp33,fp12,fp44,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,36\n\n~~~17:~~~~~~FPMADD~~~fp11,fp43=fp2,fp34,fp10,fp42,fp11,fp43,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,37\n\n~~~19:~~~~~~FPMADD~~~fp12,fp44=fp2,fp34,fp8,fp40,fp30,fp62,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,38\n\n~~~21:~~~~~~FMA~~~~~~fp5=fp2,fp31,fp5,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,39\n\n~~~13:~~~~~~FPMUL~~~~fp0,fp32=fp13,fp45,fp0,fp32,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,40\n\n~~~15:~~~~~~FPMUL~~~~fp1,fp33=fp1,fp33,fp3,fp35,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,41\n\n~~~17:~~~~~~FPMUL~~~~fp2,fp34=fp10,fp42,fp11,fp43,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,42\n\n~~~19:~~~~~~FPMUL~~~~fp3,fp35=fp8,fp40,fp12,fp44,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,43\n\n~~~21:~~~~~~MFL~~~~~~fp5=fp31,fp5,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,44\n\n~~~13:~~~~~~FPMADD~~~fp0,fp32=fp9,fp41,fp9,fp41,fp0,fp32,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,45\n\n~~~15:~~~~~~FPMADD~~~fp1,fp33=fp7,fp39,fp7,fp39,fp1,fp33,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,46\n\n~~~17:~~~~~~FPMADD~~~fp2,fp34=fp6,fp38,fp6,fp38,fp2,fp34,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,47\n\n~~~19:~~~~~~FPMADD~~~fp3,fp35=fp4,fp36,fp4,fp36,fp3,fp35,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,48\n\n~~~21:~~~~~~FMA~~~~~~fp4=fp29,fp29,fp5,fcr\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,49\n\n~~~22:~~~~~~STFL~~~~~(double)(gr3,0)=fp0\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,50\n\n~~~23:~~~~~~STFL~~~~~(double)(gr3,gr6,0,trap=8)=fp32\n\n~~~29:~~~~~~LI~~~~~~~gr6=56\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,51\n\n~~~31:~~~~~~LFPLU~~~~fp29,fp61,gr12=\\#stack(gr12,gr0,0)\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,52\n\n~~~24:~~~~~~STFL~~~~~(double)(gr3,16)=fp1\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,53\n\n~~~25:~~~~~~STFL~~~~~(double)(gr3,gr5,0,trap=24)=fp33\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,54\n\n~~~31:~~~~~~LFPLU~~~~fp30,fp62,gr12=\\#stack(gr12,gr0,0)\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,55\n\n~~~26:~~~~~~STFL~~~~~(double)(gr3,32)=fp2\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,56\n\n~~~27:~~~~~~STFL~~~~~(double)(gr3,gr8,0,trap=40)=fp34\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,57\n\n~~~31:~~~~~~LFPLU~~~~fp31,fp63,gr12=\\#stack(gr12,gr0,0)\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,58\n\n~~~28:~~~~~~STFL~~~~~(double)(gr3,48)=fp3\n\n~~~31:~~~~~~AI~~~~~~~gr1=gr1,96,gr12\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,59\n\n~~~31:~~~~~~CONSUME~~gr1,gr2,lr,gr14-gr31,fp14-fp31,fp46-fp63,cr{[}234{]},fsr,fcr,ctr\n\n~~~29:~~~~~~STFL~~~~~(double)(gr3,gr6,0,trap=56)=fp35\n\n~~~~0:~~~~~~DIRCTIV~~issue\\_cycle,60\n\n~~~30:~~~~~~STFL~~~~~(double)(gr3,64)=fp4\n\n~~~31:~~~~~~BA~~~~~~~lr\n\n~~~~4:~~~~~~BB\\_END\n\n~~~~5:~~~~~~BB\\_BEGIN~~~~3~/~~~~0\n\n~~~31:~~~~~~PEND\n\n~~~~5:~~~~~~BB\\_END\n\n{*}{*}~End~of~Procedure~List~for~Proc~\\#~~~1:~\\_Z8ninerootPdPKd~End~of~Phase~3~{*}{*}\n\n-qdebug=BGL:PLST3:CYCLES:SHUTUP:HUMMER:LINUX:NEWSCHED1:NEWSCHED2:REGPRES:ADRA:ANTIDEP:MAXGRIDICULOUS:HUMSQRT:NOPIC:PLST3:CYCLES:PLSTHUMM:HUMMDBG:RECIPF:\n\n~GPR's~set/used:~~~ssuu~ssss~s-{}-{}-~s-{}-{}-~~-{}-{}-{}-~-{}-{}-{}-~-{}-{}-{}-~-{}-{}-{}-\n\n~FPR's~set/used:~~~ssss~ssss~ssss~ss-{}-~~-{}-{}-{}-~-{}-{}-{}-~-{}-{}-s~ssss\n\n~~~~~~~~~~~~~~~~~~~ssss~ssss~ssss~ss-{}-~~-{}-{}-{}-~-{}-{}-{}-~-{}-{}-s~s-s-\n\n~CCR's~set/used:~~~-{}-{}-{}-~-{}-{}-{}-\n\n~~|~000000~~~~~~~~~~~~~~~~~~~~~PDEF~~~~~nineroot(double~{*},~const~double~{*})\n\n~3|~~~~~~~~~~~~~~~~~~~~~~~~~~~~PROC~~~~~f,x,gr3,gr4\n\n~0|~000000~ori~~~~~~602C0000~1~LR~~~~~~~gr12=gr1\n\n~0|~000004~addi~~~~~3800FFF0~1~LI~~~~~~~gr0=-16\n\n~0|~000008~stwu~~~~~9421FFA0~1~ST4U~~~~~gr1,\\#stack(gr1,-96)=gr1\n\n~0|~00000C~stfpdux~~7FEC07DC~1~SFPLU~~~~gr12,\\#stack(gr12,gr0,0)=fp31,fp63\n\n~0|~000010~stfpdux~~7FCC07DC~1~SFPLU~~~~gr12,\\#stack(gr12,gr0,0)=fp30,fp62\n\n~0|~000014~stfpdux~~7FAC07DC~1~SFPLU~~~~gr12,\\#stack(gr12,gr0,0)=fp29,fp61\n\n~0|~000018~stfpdux~~7F8C07DC~1~SFPLU~~~~gr12,\\#stack(gr12,gr0,0)=fp28,fp60\n\n~0|~00001C~stfpdux~~7F6C07DC~1~SFPLU~~~~gr12,\\#stack(gr12,gr0,0)=fp27,fp59\n\n~4|~000020~lfd~~~~~~C9A40000~1~LFL~~~~~~fp13=(double)(gr4,0)\n\n~5|~000024~addi~~~~~38C00008~1~LI~~~~~~~gr6=8\n\n~7|~000028~addi~~~~~38A00018~1~LI~~~~~~~gr5=24\n\n~5|~00002C~lfsdx~~~~7DA4319C~1~LFL~~~~~~fp45=(double)(gr4,gr6,0,trap=8)\n\n~9|~000030~addi~~~~~39000028~1~LI~~~~~~~gr8=40\n\n11|~000034~addi~~~~~38C00038~1~LI~~~~~~~gr6=56\n\n13|~000038~addis~~~~3CE00000~1~LA~~~~~~~gr7=.+CONSTANT\\_AREA\\%HI(gr2,0)\n\n~6|~00003C~lfd~~~~~~C9640010~1~LFL~~~~~~fp11=(double)(gr4,16)\n\n13|~000040~addi~~~~~38E70000~1~LA~~~~~~~gr7=+CONSTANT\\_AREA\\%LO(gr7,0)\n\n~7|~000044~lfsdx~~~~7D64299C~1~LFL~~~~~~fp43=(double)(gr4,gr5,0,trap=24)\n\n~8|~000048~lfd~~~~~~C9440020~1~LFL~~~~~~fp10=(double)(gr4,32)\n\n13|~00004C~fprsqrte~0120681E~1~FPRSQRE~~fp9,fp41=fp13,fp45\n\n~9|~000050~lfsdx~~~~7D44419C~1~LFL~~~~~~fp42=(double)(gr4,gr8,0,trap=40)\n\n31|~000054~ori~~~~~~602C0000~1~LR~~~~~~~gr12=gr1\n\n10|~000058~lfd~~~~~~C9040030~1~LFL~~~~~~fp8=(double)(gr4,48)\n\n31|~00005C~addi~~~~~38000010~1~LI~~~~~~~gr0=16\n\n11|~000060~lfsdx~~~~7D04319C~1~LFL~~~~~~fp40=(double)(gr4,gr6,0,trap=56)\n\n15|~000064~fprsqrte~00E0581E~1~FPRSQRE~~fp7,fp39=fp11,fp43\n\n13|~000068~addi~~~~~38C00020~1~LI~~~~~~~gr6=32\n\n12|~00006C~lfd~~~~~~CBE40040~1~LFL~~~~~~fp31=(double)(gr4,64)\n\n13|~000070~lfpsx~~~~7F672B1C~1~LFPS~~~~~fp27,fp59=+CONSTANT\\_AREA(gr7,gr5,0,trap=24)\n\n13|~000074~fpmul~~~~01890250~1~FPMUL~~~~fp12,fp44=fp9,fp41,fp9,fp41,fcr\n\n17|~000078~fprsqrte~00C0501E~1~FPRSQRE~~fp6,fp38=fp10,fp42\n\n13|~00007C~lfs~~~~~~C3C70004~1~LFS~~~~~~fp30=+CONSTANT\\_AREA(gr7,4)\n\n19|~000080~fprsqrte~0080401E~1~FPRSQRE~~fp4,fp36=fp8,fp40\n\n13|~000084~lfpsx~~~~7CA7331C~1~LFPS~~~~~fp5,fp37=+CONSTANT\\_AREA(gr7,gr6,0,trap=32)\n\n21|~000088~frsqrte~~FFA0F834~1~FRSQRE~~~fp29=fp31\n\n13|~00008C~lfpsx~~~~7C67431C~1~LFPS~~~~~fp3,fp35=+CONSTANT\\_AREA(gr7,gr8,0,trap=40)\n\n13|~000090~addi~~~~~38800030~1~LI~~~~~~~gr4=48\n\n15|~000094~fpmul~~~~002701D0~1~FPMUL~~~~fp1,fp33=fp7,fp39,fp7,fp39,fcr\n\n13|~000098~lfpsx~~~~7C47231C~1~LFPS~~~~~fp2,fp34=+CONSTANT\\_AREA(gr7,gr4,0,trap=48)\n\n13|~00009C~fpmadd~~~01ADDB20~1~FPMADD~~~fp13,fp45=fp27,fp59,fp13,fp45,fp12,fp44,fcr\n\n17|~0000A0~fpmul~~~~00060190~1~FPMUL~~~~fp0,fp32=fp6,fp38,fp6,fp38,fcr\n\n23|~0000A4~addi~~~~~38C00008~1~LI~~~~~~~gr6=8\n\n19|~0000A8~fpmul~~~~01840110~1~FPMUL~~~~fp12,fp44=fp4,fp36,fp4,fp36,fcr\n\n21|~0000AC~fmul~~~~~FF9D0772~1~MFL~~~~~~fp28=fp29,fp29,fcr\n\n15|~0000B0~fpmadd~~~002BD860~1~FPMADD~~~fp1,fp33=fp27,fp59,fp11,fp43,fp1,fp33,fcr\n\n17|~0000B4~fpmadd~~~014AD820~1~FPMADD~~~fp10,fp42=fp27,fp59,fp10,fp42,fp0,fp32,fcr\n\n19|~0000B8~fpmadd~~~0108DB20~1~FPMADD~~~fp8,fp40=fp27,fp59,fp8,fp40,fp12,fp44,fcr\n\n21|~0000BC~fmadd~~~~FFFFDF3A~1~FMA~~~~~~fp31=fp27,fp31,fp28,fcr\n\n13|~0000C0~fxcpmadd~001E2B64~1~FXPMADD~~fp0,fp32=fp5,fp37,fp13,fp45,fp30,fp30,fcr\n\n15|~0000C4~fxcpmadd~019E2864~1~FXPMADD~~fp12,fp44=fp5,fp37,fp1,fp33,fp30,fp30,fcr\n\n31|~0000C8~lfpdux~~~7F6C03DC~1~LFPLU~~~~fp27,fp59,gr12=\\#stack(gr12,gr0,0)\n\n17|~0000CC~fxcpmadd~017E2AA4~1~FXPMADD~~fp11,fp43=fp5,fp37,fp10,fp42,fp30,fp30,fcr\n\n19|~0000D0~fxcpmadd~039E2A24~1~FXPMADD~~fp28,fp60=fp5,fp37,fp8,fp40,fp30,fp30,fcr\n\n21|~0000D4~fmadd~~~~FCBF2FBA~1~FMA~~~~~~fp5=fp5,fp31,fp30,fcr\n\n13|~0000D8~fpmadd~~~000D1820~1~FPMADD~~~fp0,fp32=fp3,fp35,fp13,fp45,fp0,fp32,fcr\n\n15|~0000DC~fpmadd~~~01811B20~1~FPMADD~~~fp12,fp44=fp3,fp35,fp1,fp33,fp12,fp44,fcr\n\n17|~0000E0~fpmadd~~~016A1AE0~1~FPMADD~~~fp11,fp43=fp3,fp35,fp10,fp42,fp11,fp43,fcr\n\n19|~0000E4~fpmadd~~~03C81F20~1~FPMADD~~~fp30,fp62=fp3,fp35,fp8,fp40,fp28,fp60,fcr\n\n21|~0000E8~fmadd~~~~FCBF197A~1~FMA~~~~~~fp5=fp3,fp31,fp5,fcr\n\n13|~0000EC~fpmadd~~~000D1020~1~FPMADD~~~fp0,fp32=fp2,fp34,fp13,fp45,fp0,fp32,fcr\n\n31|~0000F0~lfpdux~~~7F8C03DC~1~LFPLU~~~~fp28,fp60,gr12=\\#stack(gr12,gr0,0)\n\n15|~0000F4~fpmadd~~~00611320~1~FPMADD~~~fp3,fp35=fp2,fp34,fp1,fp33,fp12,fp44,fcr\n\n17|~0000F8~fpmadd~~~016A12E0~1~FPMADD~~~fp11,fp43=fp2,fp34,fp10,fp42,fp11,fp43,fcr\n\n19|~0000FC~fpmadd~~~018817A0~1~FPMADD~~~fp12,fp44=fp2,fp34,fp8,fp40,fp30,fp62,fcr\n\n21|~000100~fmadd~~~~FCBF117A~1~FMA~~~~~~fp5=fp2,fp31,fp5,fcr\n\n13|~000104~fpmul~~~~000D0010~1~FPMUL~~~~fp0,fp32=fp13,fp45,fp0,fp32,fcr\n\n15|~000108~fpmul~~~~002100D0~1~FPMUL~~~~fp1,fp33=fp1,fp33,fp3,fp35,fcr\n\n17|~00010C~fpmul~~~~004A02D0~1~FPMUL~~~~fp2,fp34=fp10,fp42,fp11,fp43,fcr\n\n19|~000110~fpmul~~~~00680310~1~FPMUL~~~~fp3,fp35=fp8,fp40,fp12,fp44,fcr\n\n21|~000114~fmul~~~~~FCBF0172~1~MFL~~~~~~fp5=fp31,fp5,fcr\n\n13|~000118~fpmadd~~~00094820~1~FPMADD~~~fp0,fp32=fp9,fp41,fp9,fp41,fp0,fp32,fcr\n\n15|~00011C~fpmadd~~~00273860~1~FPMADD~~~fp1,fp33=fp7,fp39,fp7,fp39,fp1,fp33,fcr\n\n17|~000120~fpmadd~~~004630A0~1~FPMADD~~~fp2,fp34=fp6,fp38,fp6,fp38,fp2,fp34,fcr\n\n19|~000124~fpmadd~~~006420E0~1~FPMADD~~~fp3,fp35=fp4,fp36,fp4,fp36,fp3,fp35,fcr\n\n21|~000128~fmadd~~~~FC9DE97A~1~FMA~~~~~~fp4=fp29,fp29,fp5,fcr\n\n22|~00012C~stfd~~~~~D8030000~1~STFL~~~~~(double)(gr3,0)=fp0\n\n23|~000130~stfsdx~~~7C03359C~1~STFL~~~~~(double)(gr3,gr6,0,trap=8)=fp32\n\n29|~000134~addi~~~~~38C00038~1~LI~~~~~~~gr6=56\n\n31|~000138~lfpdux~~~7FAC03DC~1~LFPLU~~~~fp29,fp61,gr12=\\#stack(gr12,gr0,0)\n\n24|~00013C~stfd~~~~~D8230010~1~STFL~~~~~(double)(gr3,16)=fp1\n\n25|~000140~stfsdx~~~7C232D9C~1~STFL~~~~~(double)(gr3,gr5,0,trap=24)=fp33\n\n31|~000144~lfpdux~~~7FCC03DC~1~LFPLU~~~~fp30,fp62,gr12=\\#stack(gr12,gr0,0)\n\n26|~000148~stfd~~~~~D8430020~1~STFL~~~~~(double)(gr3,32)=fp2\n\n27|~00014C~stfsdx~~~7C43459C~1~STFL~~~~~(double)(gr3,gr8,0,trap=40)=fp34\n\n31|~000150~lfpdux~~~7FEC03DC~1~LFPLU~~~~fp31,fp63,gr12=\\#stack(gr12,gr0,0)\n\n28|~000154~stfd~~~~~D8630030~1~STFL~~~~~(double)(gr3,48)=fp3\n\n31|~000158~addi~~~~~38210060~1~AI~~~~~~~gr1=gr1,96,gr12\n\n29|~00015C~stfsdx~~~7C63359C~1~STFL~~~~~(double)(gr3,gr6,0,trap=56)=fp35\n\n30|~000160~stfd~~~~~D8830040~1~STFL~~~~~(double)(gr3,64)=fp4\n\n31|~000164~bclr~~~~~4E800020~0~BA~~~~~~~lr\n\n~~|~~~~~~~~~~~~~~~Instruction~count~~~~~~~~~~~90\n\n~~|~~~~~~~~~~~~~~~Constant~Area\n\n~~|~000000~~~~~~~~BF800000~3E8C0000~BEA00000~3EC00000~BF000000~49424D20\n\n~~|~000018~~~~~~~~BF800000~BF800000~BEA00000~BEA00000~3EC00000~3EC00000\n\n~~|~000030~~~~~~~~BF000000~BF000000\n\n~1500-036:~(I)~The~NOSTRICT~option~(default~at~OPT(3))~has~the~potential~to~\n\n~~~~~~~~~~~~~~~alter~the~semantics~of~a~program.~~\n\n~~~~~~~~~~~~~~~Please~refer~to~documentation~on~the~STRICT/NOSTRICT~option~\n\n~~~~~~~~~~~~~~~for~more~information.\n\n\n\\end{lyxcode}\n\n\\section{Source code}\n\n\n\\subsection{Utilities}\n\n\\begin{lyxcode}\n//~'fsel'~is~a~built-in~instruction~on~PPCGR~and~above,~\n\n//~sometimes~we~want~to~force~its~use\n\n\\#if~defined(ARCH\\_HAS\\_FSEL)\n\n\\#include~<builtins.h>\n\n\\#define~fsel(a,~x,~y)~\\_\\_fsel((a),(x),(y))\n\n\\#else\n\n\\#define~fsel(a,~x,~y)~(~(a)~>=~0.0~?~(x)~:~(y)~)\n\n\\#endif\n\n/{*}\n\n~{*}~Storage~mapping~of~an~IEEE~double-precision~number,~for~access~to\n\n~{*}~parts~of~it~as~integers~or~bits\n\n~{*}~This~is~big-endian~specific,~for~little-endian~you~have~to~swap\n\n~{*}~m\\_hi~and~m\\_lo,~then~test~it~!\n\n~{*}~The~intended~use~of~this~is~in~calculating~exp(x)\n\n~{*}/\n\nclass~DoubleMap\n\n\\{\n\n~~public:\n\n~~class~UIntPair\n\n~~\\{\n\n~~~~~public:\n\n~~~~unsigned~int~m\\_hi~;\n\n~~~~unsigned~int~m\\_lo~;\n\n~~\\}~;\n\n~~~union~\\{\n\n~~~~~~double~m\\_d~;\n\n~~~~~~UIntPair~m\\_u~;\n\n~~~~~~\\}~m\\_value~;\n\n~~DoubleMap(void)~\\{~\\}~;\n\n~~DoubleMap(double~X)~\\{~m\\_value.m\\_d~=~X~;~\\}~;\n\n~~DoubleMap(\n\n~~~~unsigned~int~Xsign~,~~~//~0~for~positive,~1~for~negative\n\n~~~~unsigned~int~Xexponent~,\n\n~~~~unsigned~int~Xsignificand\\_hi~,~~//~The~0x00100000~bit~had~\n\n~~~~~~~~~~~~~~~~~~~~//~better~be~set,~to~get~the~right~answer\n\n~~~~unsigned~int~Xsignificand\\_lo\n\n~~~~)~\\{\n\n~~~~~~~m\\_value.m\\_u.m\\_hi~=~(~(~Xsign~<\\,{}<~31~)\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\&~0x80000000~)\n\n~~~~~~~~~~~~~~~~~~~~~~~~|~(~(~(Xexponent~+~1023~)~~<\\,{}<~20~)~\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\&~0x7ff00000~)\n\n~~~~~~~~~~~~~~~~~~~~~~~~|~(~Xsignificand\\_hi~\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\&~0x000fffff~)~;\n\n~~~~~~~m\\_value.m\\_u.m\\_lo~=~Xsignificand\\_lo~;\n\n~~~\\}~;\n\n~~double~GetValue(void)~const~\\{~return~m\\_value.m\\_d~;~\\}~;\n\n~~void~SetValue(double~X)~\\{~m\\_value.m\\_d~=~X~;~\\}~;\n\n~~void~SetValue(\n\n~~~~unsigned~int~Xsign~,~~~//~0~for~positive,~1~for~negative\n\n~~~~unsigned~int~Xexponent~,\n\n~~~~unsigned~int~Xsignificand\\_hi~,~~//~The~0x00100000~bit~had~better~be\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//~set,~to~get~the~right~answer\n\n~~~~unsigned~int~Xsignificand\\_lo\n\n~~~~)~\\{\n\n~~~~~~~m\\_value.m\\_u.m\\_hi~=~(~(~Xsign~<\\,{}<~31~)\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\&~0x80000000~)\n\n~~~~~~~~~~~~~~~~~~~~~~~~|~(~(~(Xexponent~+~1023~)~~<\\,{}<~20~)~\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\&~0x7ff00000~)\n\n~~~~~~~~~~~~~~~~~~~~~~~~|~(~Xsignificand\\_hi~~~\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\&~0x000fffff~)~;\n\n~~~~~~~m\\_value.m\\_u.m\\_lo~=~Xsignificand\\_lo~;\n\n~~~\\}~;\n\n~~unsigned~int~HiWord(void)~const~\\{~return~m\\_value.m\\_u.m\\_hi~;~\\}~;\n\n~~unsigned~int~LoWord(void)~const~\\{~return~m\\_value.m\\_u.m\\_lo~;~\\}~;\n\n~~unsigned~int~SignBit(void)~const~\\{~return~HiWord()~\\&~0x80000000~;~\\}~;\n\n~~unsigned~int~ExponentBits(void)~const~\\{~return~HiWord()~\\&~0x7ff00000~;~\\}~;\n\n~~unsigned~int~SignificandHiBits(void)~const~\\{~return~HiWord()~\\&~0x000fffff~;~\\}~;\n\n~~unsigned~int~SignificandLoBits(void)~const~\\{~return~LoWord()~;~\\}~;\n\n~~void~SetSignificandHiBits(unsigned~int~new\\_hi\\_bits)~\\{~\n\n~~~~~~~~~~~~~~~~~~m\\_value.m\\_u.m\\_hi~=~(~m\\_value.m\\_u.m\\_hi~\\&~0xfff00000~)\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|~(~new\\_hi\\_bits~\\&~0x000fffff~)~;~\\}\n\n~~int~Exponent(void)~const~\\{~return~(~ExponentBits()~>\\,{}>~20~)~-~1023~;~\\}~;\n\n~~unsigned~int~SignificandHi(void)~const~\\{~\n\n~~~~~~~~~~~~~~~return~SignificandHiBits()~|~0x00100000~;~\\}~;\n\n~~unsigned~int~SignificandLo(void)~const~\\{~return~SignificandLoBits()~;~\\}~;\n\n~~bool~IsNegative(void)~const~\\{~return~~0~!=~SignBit()~;~\\}~;\n\n\\}~;\n\\end{lyxcode}\n\n\\subsection{Nearest Integer}\n\n\\begin{lyxcode}\n~~~~~~~~static~double~dk1~;~//~The~compiler~does~not~know~this~is\n\n~~~~~~~~~~//~constant,~so~should~not~'optimise'~away~the~rounding~below\n\n~~~~~~~~static~inline~double~NearestInteger(const~double~x)\n\n~~~~~~~~\\{\n\n~~~~~~~~~~~const~double~two10~=~1024.0~;\n\n~~~~~~~~~~~const~double~two50~=~two10~{*}~two10~{*}~two10~{*}~two10~{*}~two10~;\n\n~~~~~~~~~~~const~double~two52~=~two50~{*}~4.0~;\n\n~~~~~~~~~~~const~double~two51~=~two50~{*}~2.0~;\n\n~~~~~~~~~~~const~double~offset~=~two52~+~two51~;\n\n~~~~~~~~~~~//~Force~add~and~subtract~of~appropriate~constant~\n\n~~~~~~~~~~~//~to~drop~~fractional~part\n\n~~~~~~~~~~~//~..~hide~it~from~the~compiler~so~the~optimiser~won't\n\n~~~~~~~~~~~//~reassociate~things~..\n\n~~~~~~~~~~~const~double~losebits~=~(dk1{*}x)~+~offset~;\n\n~~~~~~~~~~~const~double~result~=~(dk1{*}losebits)~-~offset~;\n\n~~~~~~~~~~~return~result~;\n\n~~~~~~~~\\}\n\\end{lyxcode}\n\n\\subsection{Reciprocal}\n\nThis is useful for POWER3; the hardware 'floating-point divide' instruction\nblocks the floating-point pipeline and causes relatively low througput\nfor code which is vectorisable. However, it only applies where the\napplication is such that 'a' is in the single-precision range; the\nhardware 'fres' instruction does not give a useful result for double-precision\nnumbers which cause overflow or underflow when converted to single\nprecision. \n\nFor BG/L, the hardware 'parallel floating point reciprocal estimate'\ninstruction gives a useful result for the whole double-precision range,\nand the compiler knows how to use it; this code sequence is therefore\nrelatively less useful.\n\n\\begin{lyxcode}\n\\#include~<builtins.h>\n\nstatic~inline~double~better\\_reciprocal(double~a,~double~x0)\n\n\\{\n\n~~~double~f0~=~a{*}x0~-~1.0~;\n\n~~~double~x1~=~x0~-~x0~{*}~f0~;\n\n~~~return~x1~;\n\n\\}\n\nstatic~inline~double~recip(double~a)\n\n\\{\n\n~~~double~x0~=~\\_\\_fres(a)~;~//~take~it~as~read~that~a~is~in\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~//~single-precision~range\n\n~~~double~x1~=~better\\_reciprocal(a,x0)~;\n\n~~~double~x2~=~better\\_reciprocal(a,x1)~;\n\n~~~double~x3~=~better\\_reciprocal(a,x2)~;\n\n~~~return~x3~;\n\n\\}\n\\end{lyxcode}\n\n\\subsection{Complementary error function and derivative (Chebyshev)}\n\n\\begin{lyxcode}\nclass~ChebyshevPairEvaluator\n\n\\{\n\n~~public:\n\n~~enum~\\{\n\n~~~~~k\\_Terms~=~16\n\n~~~~~\\}~;\n\n~~~~~~~~class~DoublePair\n\n~~~~~~~~\\{\n\n~~~~~~~~~~~~~~~~public:\n\n~~~~~~~~~~~~~~~~double~pa~;\n\n~~~~~~~~~~~~~~~~double~pb~;\n\n~~~~~~~~\\}~;\n\n~~~~~~~~class~DoublePairArray\n\n~~~~~~~~\\{\n\n~~~~~~~~~~~~~~~~public:\n\n~~~~~~~~~~~~~~~~DoublePair~c{[}k\\_Terms{]}~;\n\n~~~~~~~~\\}~;\n\n~~static~void~RawEvaluatePair(double\\&~f,~double\\&~df,~double~x,\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~const~DoublePairArray\\&~cp)\n\n~~\\{\n\n~~~~~double~dppa~=~0.0~;\n\n~~~~~double~dpa~=~0.0~;\n\n~~~~~double~dppb~=~0.0~;\n\n~~~~~double~dpb~=~0.0~;\n\n~~~~~for~(int~j=0;~j<k\\_Terms-1;~j+=1)\n\n~~~~~\\{\n\n~~~~~~~~double~da=(2.0{*}x){*}dpa~-~dppa~+~cp.c{[}j{]}.pa~;\n\n~~~~~~~~double~db=(2.0{*}x){*}dpb~-~dppb~+~cp.c{[}j{]}.pb~;\n\n~~~~~~~~dppa~=~dpa~;\n\n~~~~~~~~dppb~=~dpb~;\n\n~~~~~~~~dpa~=~da~;\n\n~~~~~~~~dpb~=~db~;\n\n~~~~~\\}~/{*}~endfor~{*}/\n\n~~~~~//~Term~0~is~a~special~case;~POWER~'multiply-add'~makes~\n\n~~~~~//~this~same~efficiency~as~rewriting~the~table\n\n~~~~~double~resulta~=~x{*}dpa~-~dppa~+~0.5{*}(cp.c{[}k\\_Terms-1{]}).pa~;\n\n~~~~~double~resultb~=~x{*}dpb~-~dppb~+~0.5{*}(cp.c{[}k\\_Terms-1{]}).pb~;\n\n~~~~~f~=~resulta~;\n\n~~~~~df~=~resultb~;\n\n~~\\}\n\n\\}~;\n\nclass~ErfEvaluator:~public~ChebyshevPairEvaluator\n\n\\{\n\n~~~public:\n\n~~~enum~\\{\n\n~~~~~~k\\_Slices~=~8~,\n\n~~~~~~\\}~;\n\n~~~~~~~~class~CTable~\\{\n\n~~~~~~~~~~~~~~~~public:\n\n~~~~~~~~~~~~~~~~DoublePairArray~SliceTable{[}k\\_Slices{]}~;\n\n~~~~~~~~\\}~;\n\n~~~~~~~~static~const~CTable~ChebyshevTable~;\n\n~~~~~~~~static~double~dk1~;~//~The~compiler~does~not~know~this~is\n\n~~~~~~~~~//~constant,~so~should~not~'optimise'~away~the~rounding~below\n\n~~~~~~~~static~inline~double~NearestInteger(const~double~x)\n\n~~~~~~~~\\{\n\n~~~~~~~~~~~const~double~two10~=~1024.0~;\n\n~~~~~~~~~~~const~double~two50~=~two10~{*}~two10~{*}~two10~{*}~two10~{*}~two10~;\n\n~~~~~~~~~~~const~double~two52~=~two50~{*}~4.0~;\n\n~~~~~~~~~~~const~double~two51~=~two50~{*}~2.0~;\n\n~~~~~~~~~~~const~double~offset~=~two52~+~two51~;\n\n~~~~~~~~~~~//~Force~add~and~subtract~of~appropriate~constant~to~drop\n\n~~~~~~~~~~~//~fractional~part\n\n~~~~~~~~~~~//~..~hide~it~from~the~compiler~so~the~optimiser~won't\n\n~~~~~~~~~~~//~reassociate~things~..\n\n~~~~~~~~~~~const~double~losebits~=~(dk1{*}x)~+~offset~;\n\n~~~~~~~~~~~const~double~result~=~(dk1{*}losebits)~-~offset~;\n\n~~~~~~~~~~~return~result~;\n\n~~~~~~~~\\}\n\n~~~~~~~~static~void~Evaluate(const~double~x,~double\\&~f,~double\\&~df)\n\n~~~~~~~~\\{\n\n~~~~~~~~~~~double~xam~=~fabs(x)~-~0.5~;\n\n~~~~~~~~~~~double~xi~=~NearestInteger(xam)~;\n\n~~~~~~~~~~~double~xf~=~xam-xi~;~~~~~~~~~~~~~~~~~//~-0.5~<~x~<~0.5\n\n~~~~~~~~~~~int~ix~=~(int)~xi~;\n\n~~~~~~~~~~~int~ixmask~=~ix~\\&~7~;\n\n~~~~~~~~~~~double~r0~;\n\n~~~~~~~~~~~double~dr0~;\n\n~~~~~~~~~~~RawEvaluatePair(r0,~dr0,~2.0{*}xf,~~~\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~ChebyshevTable.SliceTable{[}ixmask{]})~;\n\n~~~~~~~~~~~double~~r1~=~fsel(xi-7.5,-1.0,~~r0)~;\n\n~~~~~~~~~~~double~dr1~=~fsel(xi-7.5,~0.0,~dr0)~;\n\n~~~~~~~~~~~double~~~m~=~fsel(x,1.0,~-1.0)~;\n\n~~~~~~~~~~~double~~r2~=~1.0+m{*}r1~;\n\n~~~~~~~~~~~f~=~r2~~~~;\n\n~~~~~~~~~~~df~=~dr1~;\n\n~~~~~~~~\\}\n\n\\}~;\n\n\\#ifndef~MSD\\_COMPILE\\_DATA\\_ONLY\n\nconst~ErfEvaluator::CTable~ErfEvaluator::ChebyshevTable~=~\\{\n\n~~~~~~~~\\{\n\n~~~~~~~~~~~~~~~~\\{\n\n~\\{~~\\{~~~~~~~~~~~~-1.9514453114346613e-14~,\n\n~~~~~~~~~~~~~~~~~-4.3962027206143962e-14~\\}\n\n,~~~\\{~~~~~~~~~~~~~1.3625665209647924e-13~,\n\n~~~~~~~~~~~~~~~~~-1.1610210709915711e-12~\\}\n\n,~~~\\{~~~~~~~~~~~~~2.229902591391045e-12~,\n\n~~~~~~~~~~~~~~~~~~7.5864104901966937e-12~\\}\n\n,~~~\\{~~~~~~~~~~~~-2.1427408195614467e-11~,\n\n~~~~~~~~~~~~~~~~~~1.1479391368134277e-10~\\}\n\n,~~~\\{~~~~~~~~~~~~-2.0634390485502084e-10~,\n\n~~~~~~~~~~~~~~~~~-1.0209291828992976e-09~\\}\n\n,~~~\\{~~~~~~~~~~~~~2.7257129691783295e-09~,\n\n~~~~~~~~~~~~~~~~~-8.9643378999395747e-09~\\}\n\n,~~~\\{~~~~~~~~~~~~~1.4115809274810406e-08~,\n\n~~~~~~~~~~~~~~~~~~1.0800758958423388e-07~\\}\n\n,~~~\\{~~~~~~~~~~~~-2.7818478883356451e-07~,\n\n~~~~~~~~~~~~~~~~~~4.9920479599323502e-07~\\}\n\n,~~~\\{~~~~~~~~~~~~-5.2333748523420065e-07~,\n\n~~~~~~~~~~~~~~~~~-8.7939056530898302e-06~\\}\n\n,~~~\\{~~~~~~~~~~~~~2.211114704099522e-05~,\n\n~~~~~~~~~~~~~~~~~-1.4154244790564384e-05~\\}\n\n,~~~\\{~~~~~~~~~~~~-1.8363892921493974e-05~,\n\n~~~~~~~~~~~~~~~~~~0.00052187362333079546~\\}\n\n,~~~\\{~~~~~~~~~~~~~-0.0012919410465849694~,\n\n~~~~~~~~~~~~~~~~~-0.00038143210322044387~\\}\n\n,~~~\\{~~~~~~~~~~~~~~~0.004492934887683828~,\n\n~~~~~~~~~~~~~~~~~~~-0.020149183122028715~\\}\n\n,~~~\\{~~~~~~~~~~~~~~~0.049552626796204341~,\n\n~~~~~~~~~~~~~~~~~~~~0.053533786548985489~\\}\n\n,~~~\\{~~~~~~~~~~~~~~-0.42582445804381047~,\n\n~~~~~~~~~~~~~~~~~~~~~0.37627183124760605~\\}\n\n,~~~\\{~~~~~~~~~~~~~~~-0.93926583578230194~,\n\n~~~~~~~~~~~~~~~~~~~~~-1.6497640456262563~\\}\n\n\\}~\\}\n\n,\\{~\\{~~\\{~~~~~~~~~~-5.0317730474937121e-16~,\n\n~~~~~~~~~~~~~~~~~-4.2117485562976088e-14~\\}\n\n,~~~~~\\{~~~~~~~~~~~9.4040069643033129e-14~,\n\n~~~~~~~~~~~~~~~~~-2.7959038508193287e-14~\\}\n\n,~~~~~\\{~~~~~~~~~~-5.4676286926192122e-13~,\n\n~~~~~~~~~~~~~~~~~~5.2241264144468789e-12~\\}\n\n,~~~~~\\{~~~~~~~~~~-7.8746039930688689e-12~,\n\n~~~~~~~~~~~~~~~~~-2.8459628240128098e-11~\\}\n\n,~~~~~\\{~~~~~~~~~~~1.1428281965722648e-10~,\n\n~~~~~~~~~~~~~~~~~-3.7275686525285883e-10~\\}\n\n,~~~~~\\{~~~~~~~~~~~7.5247753102189958e-11~,\n\n~~~~~~~~~~~~~~~~~~~4.999984436677837e-09~\\}\n\n,~~~~~\\{~~~~~~~~~~-1.1752407126361825e-08~,\n\n~~~~~~~~~~~~~~~~~~2.6371532588347393e-09~\\}\n\n,~~~~~\\{~~~~~~~~~~~7.3301093509556885e-08~,\n\n~~~~~~~~~~~~~~~~~-4.1808667211234786e-07~\\}\n\n,~~~~~\\{~~~~~~~~~~~4.6810084713974775e-07~,\n\n~~~~~~~~~~~~~~~~~~2.3482721455646551e-06~\\}\n\n,~~~~~\\{~~~~~~~~~~-8.8537423943830358e-06~,~\n\n~~~~~~~~~~~~~~~~~1.2688737047800589e-05~\\}\n\n,~~~~~\\{~~~~~~~~~~~3.2638635138919629e-05~,\n\n~~~~~~~~~~~~~~~~~-0.00021014154531962822~\\}\n\n,~~~~~\\{~~~~~~~~~~~0.00029384471334866456~,\n\n~~~~~~~~~~~~~~~~~~0.00066546143982619316~\\}\n\n,~~~~~\\{~~~~~~~~~~~-0.0041797192715572768~,\n\n~~~~~~~~~~~~~~~~~~~0.0044913738682590045~\\}\n\n,~~~~~\\{~~~~~~~~~~~~~0.023555662412541055~,\n\n~~~~~~~~~~~~~~~~~~~-0.049491169818861133~\\}\n\n,~~~~~\\{~~~~~~~~~~~~-0.072164111860376176~,\n\n~~~~~~~~~~~~~~~~~~~~~0.19293667316858745~\\}\n\n,~~~~~\\{~~~~~~~~~~~~~~-1.8857045114727804~,\n\n~~~~~~~~~~~~~~~~~~~~-0.33814761726036585~\\}\n\n\\}~\\}\n\n,\\{~\\{~~\\{~~~~~~~~~~~1.1536030588919383e-15~,\n\n~~~~~~~~~~~~~~~~~-4.5290945318974183e-15~\\}\n\n,~~~~~\\{~~~~~~~~~~-2.5831909518634811e-15~,\n\n~~~~~~~~~~~~~~~~~~6.9035600532037278e-14~\\}\n\n,~~~~~\\{~~~~~~~~~~-1.2219969549456367e-13~,~\n\n~~~~~~~~~~~~~~~~-1.4918778783625236e-13~\\}\n\n,~~~~~\\{~~~~~~~~~~~~1.650088654139529e-12~,~\n\n~~~~~~~~~~~~~~~~-6.2853485651852727e-12~\\}\n\n,~~~~~\\{~~~~~~~~~~-4.1430599274545238e-12~,~\n\n~~~~~~~~~~~~~~~~~7.9055067610861132e-11~\\}\n\n,~~~~~\\{~~~~~~~~~~~-1.303276091975957e-10~,~\n\n~~~~~~~~~~~~~~~~-1.8857998537318434e-10~\\}\n\n,~~~~~\\{~~~~~~~~~~~1.8722149256193656e-09~,~\n\n~~~~~~~~~~~~~~~~-5.1340493002929665e-09~\\}\n\n,~~~~~\\{~~~~~~~~~~-9.3478974795511597e-09~,~\n\n~~~~~~~~~~~~~~~~~~6.721115733692397e-08~\\}\n\n,~~~~~\\{~~~~~~~~~~-4.9199521904598378e-08~,~\n\n~~~~~~~~~~~~~~~~-3.0426676864593005e-07~\\}\n\n,~~~~~\\{~~~~~~~~~~~1.2964140790298608e-06~,\n\n~~~~~~~~~~~~~~~~~-1.3103754559918305e-06~\\}\n\n,~~~~~\\{~~~~~~~~~~-1.2343188523307585e-05~,~\n\n~~~~~~~~~~~~~~~~~3.0809671128070729e-05~\\}\n\n,~~~~~\\{~~~~~~~~~~~7.5321057602619065e-05~,~\n\n~~~~~~~~~~~~~~~~-0.00024817414592214355~\\}\n\n,~~~~~\\{~~~~~~~~~~-0.00032191106470368769~,\n\n~~~~~~~~~~~~~~~~~~~0.0012359465927699756~\\}\n\n,~~~~~\\{~~~~~~~~~~~0.00097018407704014555~,\n\n~~~~~~~~~~~~~~~~~~-0.0041111069223663957~\\}\n\n,~~~~~\\{~~~~~~~~~~~-0.0019935206572262573~,~\n\n~~~~~~~~~~~~~~~~~~0.0089974192090911398~\\}\n\n,~~~~~\\{~~~~~~~~~~~~~~-1.9973937586662434~,~\n\n~~~~~~~~~~~~~~~~~~-0.012085189551271426~\\}\n\n\\}~\\}\n\n,\\{~\\{~~\\{~~~~~~~~~~~2.8811019587551389e-18~,\n\n~~~~~~~~~~~~~~~~~~~2.684646603916068e-16~\\}\n\n,~~~~~\\{~~~~~~~~~~-6.2333922975783146e-16~,\n\n~~~~~~~~~~~~~~~~~~1.4252468434090293e-16~\\}\n\n,~~~~~\\{~~~~~~~~~~~9.0877705975533128e-15~,\n\n~~~~~~~~~~~~~~~~~-3.4638532206046957e-14~\\}\n\n,~~~~~\\{~~~~~~~~~~-6.2053772915893235e-14~,\n\n~~~~~~~~~~~~~~~~~~4.7270659575711313e-13~\\}\n\n,~~~~~\\{~~~~~~~~~~-9.4369582503557563e-14~,~\n\n~~~~~~~~~~~~~~~~-3.0132196321689225e-12~\\}\n\n,~~~~~\\{~~~~~~~~~~~8.1568391992615411e-12~,\n\n~~~~~~~~~~~~~~~~~-3.6795550343994194e-12~\\}\n\n,~~~~~\\{~~~~~~~~~~-1.1859203571949966e-10~,\n\n~~~~~~~~~~~~~~~~~~3.2326034833829272e-10~\\}\n\n,~~~~~\\{~~~~~~~~~~~1.1302927297982895e-09~,\n\n~~~~~~~~~~~~~~~~~-4.2729928409363866e-09~\\}\n\n,~~~~~\\{~~~~~~~~~~-8.1653674229686321e-09~,\n\n~~~~~~~~~~~~~~~~~~~3.649262770188356e-08~\\}\n\n,~~~~~\\{~~~~~~~~~~~4.6711146297670056e-08~,~\n\n~~~~~~~~~~~~~~~~-2.3290328068405808e-07~\\}\n\n,~~~~~\\{~~~~~~~~~~-2.1434786976693524e-07~,~\n\n~~~~~~~~~~~~~~~~~~1.157560138845965e-06~\\}\n\n,~~~~~\\{~~~~~~~~~~~7.8712065435992157e-07~,~\n\n~~~~~~~~~~~~~~~~-4.5198606760227629e-06~\\}\n\n,~~~~~\\{~~~~~~~~~~-2.2827106290462468e-06~,~\n\n~~~~~~~~~~~~~~~~~1.3751490608604711e-05~\\}\n\n,~~~~~\\{~~~~~~~~~~~~5.108210075437179e-06~,~\n\n~~~~~~~~~~~~~~~~-3.1912388224577725e-05~\\}\n\n,~~~~~\\{~~~~~~~~~~~-8.532197326791333e-06~,~\n\n~~~~~~~~~~~~~~~~~5.4617171212102142e-05~\\}\n\n,~~~~~\\{~~~~~~~~~~~~~~-1.9999897804462703~,~\n\n~~~~~~~~~~~~~~~-6.6041177531743063e-05~\\}\n\n\\}~\\}\n\n,\\{~\\{~~\\{~~~~~~~~~~-7.4993123127081172e-19~,~\n\n~~~~~~~~~~~~~~~~-9.2154967085056884e-19~\\}\n\n,~~~~~\\{~~~~~~~~~~~1.6453122028975649e-17~,\n\n~~~~~~~~~~~~~~~~~-4.4526109981603194e-17~\\}\n\n,~~~~~\\{~~~~~~~~~~-2.2216971245348065e-16~,\n\n~~~~~~~~~~~~~~~~~~9.2045328395178569e-16~\\}\n\n,~~~~~\\{~~~~~~~~~~~2.3187986651361246e-15~,~\n\n~~~~~~~~~~~~~~~~-1.1597351157562596e-14~\\}\n\n,~~~~~\\{~~~~~~~~~~-1.9966897966189304e-14~,~\n\n~~~~~~~~~~~~~~~~~1.1222278921048576e-13~\\}\n\n,~~~~~\\{~~~~~~~~~~~1.4567188498750867e-13~,\n\n~~~~~~~~~~~~~~~~~-8.9014086166989192e-13~\\}\n\n,~~~~~\\{~~~~~~~~~~-9.1094290960037775e-13~,\n\n~~~~~~~~~~~~~~~~~~5.9390981887108318e-12~\\}\n\n,~~~~~\\{~~~~~~~~~~~4.9015331385524046e-12~,~\n\n~~~~~~~~~~~~~~~~~-3.3684085607283493e-11~\\}\n\n,~~~~~\\{~~~~~~~~~~-2.2668130864064367e-11~,\n\n~~~~~~~~~~~~~~~~~~1.6278815862238778e-10~\\}\n\n,~~~~~\\{~~~~~~~~~~~8.9656333841687577e-11~,\n\n~~~~~~~~~~~~~~~~~-6.6839174980108575e-10~\\}\n\n,~~~~~\\{~~~~~~~~~~-3.0070122824813192e-10~,\n\n~~~~~~~~~~~~~~~~~~2.3145401708228895e-09~\\}\n\n,~~~~~\\{~~~~~~~~~~~8.4494270776318715e-10~,\n\n~~~~~~~~~~~~~~~~~-6.6824163147637241e-09~\\}\n\n,~~~~~\\{~~~~~~~~~~-1.9576794331996479e-09~,\n\n~~~~~~~~~~~~~~~~~~1.5833623495033884e-08~\\}\n\n,~~~~~\\{~~~~~~~~~~~3.6665887957624338e-09~,\n\n~~~~~~~~~~~~~~~~~-3.0174569513159495e-08~\\}\n\n,~~~~~\\{~~~~~~~~~~-5.4258802952106441e-09~,\n\n~~~~~~~~~~~~~~~~~~4.5166333861133352e-08~\\}\n\n,~~~~~\\{~~~~~~~~~~~~~~-1.9999999937936801~,\n\n~~~~~~~~~~~~~~~~~-5.1878090694002071e-08~\\}\n\n\\}~\\}\n\n,\\{~\\{~~\\{~~~~~~~~~~-7.3128123766095007e-21~,\n\n~~~~~~~~~~~~~~~~~~5.2783768964163724e-20~\\}\n\n,~~~~~\\{~~~~~~~~~~~5.8331678204505884e-20~,\n\n~~~~~~~~~~~~~~~~~-4.4428465693890153e-19~\\}\n\n,~~~~~\\{~~~~~~~~~~-4.1665340361792927e-19~,\n\n~~~~~~~~~~~~~~~~~~3.3193577484164931e-18~\\}\n\n,~~~~~\\{~~~~~~~~~~~2.6702440438238306e-18~,\n\n~~~~~~~~~~~~~~~~~-2.2110261645071223e-17~\\}\n\n,~~~~~\\{~~~~~~~~~~-1.5352877622533002e-17~,\n\n~~~~~~~~~~~~~~~~~~1.3149107185196035e-16~\\}\n\n,~~~~~\\{~~~~~~~~~~~7.9054987528274155e-17~,\n\n~~~~~~~~~~~~~~~~~-6.9763687703652322e-16~\\}\n\n,~~~~~\\{~~~~~~~~~~-3.6338645128878323e-16~,\n\n~~~~~~~~~~~~~~~~~~3.2936905729829264e-15~\\}\n\n,~~~~~\\{~~~~~~~~~~~1.4841921457728194e-15~,\n\n~~~~~~~~~~~~~~~~~-1.3779549123432719e-14~\\}\n\n,~~~~~\\{~~~~~~~~~~-5.3535076599248966e-15~,\n\n~~~~~~~~~~~~~~~~~~5.0787839237713144e-14~\\}\n\n,~~~~~\\{~~~~~~~~~~~1.6922815522375102e-14~,\n\n~~~~~~~~~~~~~~~~~-1.6367776360132983e-13~\\}\n\n,~~~~~\\{~~~~~~~~~~-4.6440786423613345e-14~,\n\n~~~~~~~~~~~~~~~~~~4.5693541177471563e-13~\\}\n\n,~~~~~\\{~~~~~~~~~~~1.0939887392901224e-13~,\n\n~~~~~~~~~~~~~~~~~-1.0924934920735968e-12~\\}\n\n,~~~~~\\{~~~~~~~~~~-2.1831634568207554e-13~,\n\n~~~~~~~~~~~~~~~~~~2.2073173946389116e-12~\\}\n\n,~~~~~\\{~~~~~~~~~~~3.6368947573372969e-13~,\n\n~~~~~~~~~~~~~~~~~-3.7122896402585035e-12~\\}\n\n,~~~~~\\{~~~~~~~~~~-4.9822933420386177e-13~,\n\n~~~~~~~~~~~~~~~~~~5.1168332005087491e-12~\\}\n\n,~~~~~\\{~~~~~~~~~~~~~~-1.9999999999994464~,\n\n~~~~~~~~~~~~~~~~~-5.7052069770739506e-12~\\}\n\n\\}~\\}\n\n,\\{~\\{~~\\{~~~~~~~~~~-1.1581263794211803e-24~,\n\n~~~~~~~~~~~~~~~~~~1.1756024314709261e-23~\\}\n\n,~~~~~\\{~~~~~~~~~~~6.8651109138591869e-24~,\n\n~~~~~~~~~~~~~~~~~-7.1268610401803094e-23~\\}\n\n,~~~~~\\{~~~~~~~~~~~-3.738518343124306e-23~,\n\n~~~~~~~~~~~~~~~~~~3.9620223549082376e-22~\\}\n\n,~~~~~\\{~~~~~~~~~~~1.8656852708023271e-22~,\n\n~~~~~~~~~~~~~~~~~-2.0152981488264423e-21~\\}\n\n,~~~~~\\{~~~~~~~~~~-8.5056522662053255e-22~,\n\n~~~~~~~~~~~~~~~~~~9.3514915353419952e-21~\\}\n\n,~~~~~\\{~~~~~~~~~~~3.5290018709287991e-21~,\n\n~~~~~~~~~~~~~~~~~-3.9440168120129876e-20~\\}\n\n,~~~~~\\{~~~~~~~~~~-1.3264545171699188e-20~,~\n\n~~~~~~~~~~~~~~~~~1.5051156637249394e-19~\\}\n\n,~~~~~\\{~~~~~~~~~~~4.4925669595385181e-20~,\n\n~~~~~~~~~~~~~~~~~-5.1696379430130061e-19~\\}\n\n,~~~~~\\{~~~~~~~~~~-1.3624823721052732e-19~,\n\n~~~~~~~~~~~~~~~~~~1.5881329934248198e-18~\\}\n\n,~~~~~\\{~~~~~~~~~~~3.6731865126752203e-19~,\n\n~~~~~~~~~~~~~~~~~-4.3319144361960655e-18~\\}\n\n,~~~~~\\{~~~~~~~~~~-8.7299974058134151e-19~,\n\n~~~~~~~~~~~~~~~~~~1.0403780623845348e-17~\\}\n\n,~~~~~\\{~~~~~~~~~~~1.8120620323788916e-18~,\n\n~~~~~~~~~~~~~~~~~-2.1791909247822896e-17~\\}\n\n,~~~~~\\{~~~~~~~~~~~-3.251392893971571e-18~,\n\n~~~~~~~~~~~~~~~~~3.9396773141907617e-17~\\}\n\n,~~~~~\\{~~~~~~~~~~~4.9898793744105705e-18~,\n\n~~~~~~~~~~~~~~~~~-6.0808623975481749e-17~\\}\n\n,~~~~~\\{~~~~~~~~~~-6.4850528855079053e-18~,\n\n~~~~~~~~~~~~~~~~~~7.9315808137192181e-17~\\}\n\n,~~~~~\\{~~~~~~~~~~~~~~-2.0000000000000009~,\n\n~~~~~~~~~~~~~~~~~-8.6748835517513367e-17~\\}\n\n\\}~\\}\n\n,\\{~\\{~~\\{~~~~~~~~~~~-1.286993020143186e-29~,\n\n~~~~~~~~~~~~~~~~~~1.6244908657170241e-28~\\}\n\n,~~~~~\\{~~~~~~~~~~~6.2765862086305583e-29~,\n\n~~~~~~~~~~~~~~~~~-8.0275046304822356e-28~\\}\n\n,~~~~~\\{~~~~~~~~~~~-2.839692427061988e-28~,\n\n~~~~~~~~~~~~~~~~~~3.6773373634048155e-27~\\}\n\n,~~~~~\\{~~~~~~~~~~~1.1882092616181199e-27~,\n\n~~~~~~~~~~~~~~~~~-1.5569151083770561e-26~\\}\n\n,~~~~~\\{~~~~~~~~~~~-4.582191637967378e-27~,\n\n~~~~~~~~~~~~~~~~~~6.0711381921074574e-26~\\}\n\n,~~~~~\\{~~~~~~~~~~~1.6221432712231815e-26~,\n\n~~~~~~~~~~~~~~~~~-2.1718558315433516e-25~\\}\n\n,~~~~~\\{~~~~~~~~~~~-5.247933806259193e-26~,\n\n~~~~~~~~~~~~~~~~~~7.0956869041034713e-25~\\}\n\n,~~~~~\\{~~~~~~~~~~~1.5437131529880892e-25~,\n\n~~~~~~~~~~~~~~~~~-2.1064417534076447e-24~\\}\n\n,~~~~~\\{~~~~~~~~~~-4.1053336780396758e-25~,\n\n~~~~~~~~~~~~~~~~~~5.6494507799722326e-24~\\}\n\n,~~~~~\\{~~~~~~~~~~~~9.807876328051367e-25~,\n\n~~~~~~~~~~~~~~~~~-1.3601376051918737e-23~\\}\n\n,~~~~~\\{~~~~~~~~~~-2.0903055414542895e-24~,\n\n~~~~~~~~~~~~~~~~~~2.9188353967295514e-23~\\}\n\n,~~~~~\\{~~~~~~~~~~~3.9443914370892561e-24~,\n\n~~~~~~~~~~~~~~~~~-5.5407486881004531e-23~\\}\n\n,~~~~~\\{~~~~~~~~~~-6.5385165651342071e-24~,\n\n~~~~~~~~~~~~~~~~~~9.2298616960723605e-23~\\}\n\n,~~~~~\\{~~~~~~~~~~~9.4486116746898621e-24~,\n\n~~~~~~~~~~~~~~~~~-1.3386968566261501e-22~\\}\n\n,~~~~~\\{~~~~~~~~~~-1.1822408135528828e-23~,\n\n~~~~~~~~~~~~~~~~~~1.6788751035824249e-22~\\}\n\n,~~~~~\\{~~~~~~~~~~~~~~-2.0000000000000009~,\n\n~~~~~~~~~~~~~~~~~-1.8115931820473034e-22~\\}\n\n\\}~\\}\n\n~~~~~~~~~~~~~~~~\\}\n\n~~~~~~~~\\}\n\n~;\n\n\n\\end{lyxcode}\n\n\\subsection{Complementary error function and derivative (Spline)}\n\n\\begin{lyxcode}\nclass~ErfEvaluator\n\n\\{\n\n~~~public:\n\n~~~class~doublepair\n\n~~~\\{\n\n~~~~~~~~~~~public:\n\n~~~~~~~~~~~double~ca~;\n\n~~~~~~~~~~~double~cb~;\n\n~~~\\}~;\n\n~~~class~polypairlist\n\n~~~\\{\n\n~~~~~~~~~~~public:\n\n~~~~~~~~~~~enum~\\{\n\n~~~~~~~~~~~~~~k\\_Terms~=~4\n\n~~~~~~~~~~~\\}~;\n\n~~~~~~~~~~~doublepair~dp{[}k\\_Terms{]}~;\n\n~~~\\}~;\n\n~~~enum~\\{\n\n~~~~~~~~~~~k\\_Slices~=~64\n\n~~~\\}~;\n\n~~~static~const~polypairlist~p{[}k\\_Slices{]}~;\n\n~~~static~const~float~WholeNumbers{[}k\\_Slices{]}~;\n\n~~~static~const~double~IntegrationConstants{[}k\\_Slices{]}~;\n\n~~~static~void~Evaluate~(double~xRaw,~double\\&~f,~double\\&~df)\n\n~~~\\{\n\n~~~~~~assert(xRaw~>=~0.0)~;~~~~~~~~~~~~~~~~//~This~version~only\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//~defined~for~positive~argument\n\n~~~~~~xRaw~=~fsel(xRaw-3.999,3.999,xRaw)~;~//~Pinned~if~out~of~range\n\n~~~~~~double~xScale~=~xRaw~{*}~16.0~;\n\n~~~~~~int~a~=~xScale~;\n\n~~~~~~double~xWhole~=~WholeNumbers{[}a{]}~;\n\n~~~~~~double~xFrac~=~xScale-xWhole~;\n\n~~~~~~double~x~=~(xFrac{*}2.0)~-~1.0~;\n\n~~~~~~double~rf~=~\n\n((((p{[}a{]}.dp{[}0{]}.ca){*}x+p{[}a{]}.dp{[}1{]}.ca){*}x+p{[}a{]}.dp{[}2{]}.ca){*}x+p{[}a{]}.dp{[}3{]}.ca)~;\n\n~~~~~~double~rdf~=\n\n((((p{[}a{]}.dp{[}0{]}.cb){*}x+p{[}a{]}.dp{[}1{]}.cb){*}x+p{[}a{]}.dp{[}2{]}.cb){*}x+p{[}a{]}.dp{[}3{]}.cb)~;\n\n~~~~~~f~=~rf~{*}~x~+~IntegrationConstants{[}a{]};\n\n~~~~~~df~=~rdf~~;\n\n~~~\\}\n\n\\}~;\n\n\\#ifndef~MSD\\_COMPILE\\_DATA\\_ONLY\n\nconst~float~ErfEvaluator::WholeNumbers{[}ErfEvaluator::k\\_Slices{]}~=\n\n\\{\n\n~~~~~~~~0.0,~1.0,~2.0,~3.0,~4.0,~5.0,~6.0,~7.0,~8.0,~9.0\n\n~~~~~~~~,10.0,~11.0,~12.0,~13.0,~14.0,~15.0,~16.0,~17.0,~18.0,~19.0\n\n~~~~~~~~,20.0,~21.0,~22.0,~23.0,~24.0,~25.0,~26.0,~27.0,~28.0,~29.0\n\n~~~~~~~~,30.0,~31.0,~32.0,~33.0,~34.0,~35.0,~36.0,~37.0,~38.0,~39.0\n\n~~~~~~~~,40.0,~41.0,~42.0,~43.0,~44.0,~45.0,~46.0,~47.0,~48.0,~49.0\n\n~~~~~~~~,50.0,~51.0,~52.0,~53.0,~54.0,~55.0,~56.0,~57.0,~58.0,~59.0\n\n~~~~~~~~,60.0,~61.0,~62.0,~63.0\n\n\\}~;\n\nconst~ErfEvaluator::polypairlist~ErfEvaluator::p{[}ErfEvaluator::k\\_Slices{]}~=~\\{\n\n~\\{~\\{\n\n~~\\{~-1.677043705606067e-08,-2.146615943175766e-06~\\}\n\n~~,\\{~1.143371616236766e-05,0.001097636751587296~\\}\n\n~~,\\{~3.440177110943935e-05,0.002201713351004118~\\}\n\n~~,\\{~-0.03522741365975122,~~-1.127277237112039~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~-4.965987042014532e-08,-6.356463413778601e-06~\\}\n\n~~,\\{~1.116730250618423e-05,0.001072061040593686~\\}\n\n~~,\\{~0.0001024021637152795,~0.00655373847777789~\\}\n\n~~,\\{~-0.03495327227036313,~~~-1.11850471265162~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~-8.063031663779123e-08,-1.032068052963728e-05~\\}\n\n~~,\\{~1.06447944258563e-05,0.001021900264882204~\\}\n\n~~,\\{~0.000168024277188707,~0.01075355374007725~\\}\n\n~~,\\{~-0.03441137302506241,~~-1.101163936801997~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~-1.085177767547462e-07,-1.389027542460751e-05~\\}\n\n~~,\\{~9.886272248044382e-06,0.0009490821358122607~\\}\n\n~~,\\{~0.0002297848019711107,~0.01470622732615109~\\}\n\n~~,\\{~~-0.0336142358925829,~~-1.075655548562653~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~-1.323228464452476e-07,-1.693732434499169e-05~\\}\n\n~~,\\{~8.920499832118013e-06,0.0008563679838833292~\\}\n\n~~,\\{~0.0002863479486297409,~0.01832626871230342~\\}\n\n~~,\\{~-0.03258003643662622,~~-1.042561165972039~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~-1.512604951606179e-07,-1.936134338055909e-05~\\}\n\n~~,\\{~7.783401736190406e-06,0.0007472065666742789~\\}\n\n~~,\\{~0.0003365732792269584,~0.02154068987052534~\\}\n\n~~,\\{~-0.03133191701999147,~~-1.002621344639727~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~-1.647954146847001e-07,-2.109381307964162e-05~\\}\n\n~~,\\{~6.51619848252759e-06,0.0006255550543226487~\\}\n\n~~,\\{~0.0003795532894002569,~0.02429141052161644~\\}\n\n~~,\\{~-0.02989712649661543,~-0.9567080478916936~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~-1.726609582696268e-07,-2.210060265851223e-05~\\}\n\n~~,\\{~5.163323960181864e-06,0.0004956791001774589~\\}\n\n~~,\\{~0.0004146390499898948,~0.02653689919935327~\\}\n\n~~,\\{~-0.02830603301975991,~~-0.905793056632317~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~-1.748610042477048e-07,-2.238220854370622e-05~\\}\n\n~~,\\{~3.77025961848157e-06,0.0003619449233742307~\\}\n\n~~,\\{~0.0004414530010017535,~0.02825299206411223~\\}\n\n~~,\\{~-0.02659105981260158,~-0.8509139140032504~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~-1.716553961417857e-07,-2.197189070614856e-05~\\}\n\n~~,\\{~2.381420131299626e-06,0.0002286163326047641~\\}\n\n~~,\\{~0.0004598888066024617,~0.02943288362255755~\\}\n\n~~,\\{~-0.02478559574453316,~-0.7931390638250611~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~-1.63530815350447e-07,-2.093194436485722e-05~\\}\n\n~~,\\{~1.03821508918815e-06,9.966864856206237e-05~\\}\n\n~~,\\{~0.000470098964779177,~0.03008633374586733~\\}\n\n~~,\\{~-0.02292293133148951,~-0.7335338026076644~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~-1.511599296296717e-07,-1.934847099259798e-05~\\}\n\n~~,\\{~-2.22607659821702e-07,-2.137033534288339e-05~\\}\n\n~~,\\{~0.0004724715617529516,~~0.0302381799521889~\\}\n\n~~,\\{~-0.02103526657315815,~-0.6731285303410608~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~-1.353523545145142e-07,-1.732510137785782e-05~\\}\n\n~~,\\{~-1.370257092802229e-06,-0.000131544680909014~\\}\n\n~~,\\{~0.0004675981220443889,~0.02992627981084089~\\}\n\n~~,\\{~-0.01915283030640111,~-0.6128905698048354~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~-1.170013221461676e-07,-1.497616923470946e-05~\\}\n\n~~,\\{~-2.380782501521628e-06,-0.0002285551201460763~\\}\n\n~~,\\{~0.0004562348970672072,~0.02919903341230126~\\}\n\n~~,\\{~-0.01730314210665839,~-0.5537005474130686~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~-9.702996492746713e-08,-1.241983551071579e-05~\\}\n\n~~,\\{~-3.237526760163412e-06,-0.0003108025689756875~\\}\n\n~~,\\{~0.0004392601411388399,~0.02811264903288575~\\}\n\n~~,\\{~-0.01551043792261867,~-0.4963340135237975~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~-7.634081565236948e-08,-9.771624403503293e-06~\\}\n\n~~,\\{~-3.931160936497558e-06,-0.0003773914499037656~\\}\n\n~~,\\{~0.0004176299431532064,~0.02672831636180521~\\}\n\n~~,\\{~-0.01379527033462789,~-0.4414486507080926~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~-5.577155569193423e-08,-7.138759128567582e-06~\\}\n\n~~,\\{~-4.459338467442303e-06,-0.0004280964928744611~\\}\n\n~~,\\{~0.0003923350293816243,~0.02510944188042395~\\}\n\n~~,\\{~-0.01217428430645078,~-0.3895770978064249~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~-3.605928292969135e-08,-4.615588215000493e-06~\\}\n\n~~,\\{~-4.826028411989542e-06,-0.000463298727550996~\\}\n\n~~,\\{~0.0003643606551067552,~0.02331908192683234~\\}\n\n~~,\\{~-0.01066016019099486,~-0.3411251261118356~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~-1.781470707992619e-08,-2.280282506230552e-06~\\}\n\n~~,\\{~-5.040602043929432e-06,-0.0004838977962172255~\\}\n\n~~,\\{~0.0003346512962838997,~0.02141768296216958~\\}\n\n~~,\\{~-0.009261708063277772,~-0.2963746580248887~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~-1.506798321843929e-09,-1.928701851960229e-07~\\}\n\n~~,\\{~-5.116754768286062e-06,-0.0004912084577554619~\\}\n\n~~,\\{~0.0003040813783947048,~0.01946120821726111~\\}\n\n~~,\\{~-0.007984091541769101,~-0.2554909293366112~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~1.254240539445633e-08,1.60542789049041e-06~\\}\n\n~~,\\{~-5.071346219164424e-06,-0.0004868492370397846~\\}\n\n~~,\\{~0.0002734327802100555,~0.01749969793344355~\\}\n\n~~,\\{~-0.006829155307778654,~-0.2185329698489169~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~2.415382265476675e-08,3.091689299810144e-06~\\}\n\n~~,\\{~-4.923236176470265e-06,-0.0004726306729411454~\\}\n\n~~,\\{~0.0002433793645195896,~0.01557627932925373~\\}\n\n~~,\\{~-0.00579582856353525,~~-0.185466514033128~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~3.327970129438388e-08,4.259801765681137e-06~\\}\n\n~~,\\{~-4.692183812243332e-06,-0.0004504496459753599~\\}\n\n~~,\\{~0.0002144783492816111,~0.01372661435402311~\\}\n\n~~,\\{~-0.004880576558929733,~-0.1561784498857515~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~3.998619096881058e-08,5.118232444007755e-06~\\}\n\n~~,\\{~-4.397864199620254e-06,-0.0004221949631635444~\\}\n\n~~,\\{~0.0001871679663079738,~0.01197874984371032~\\}\n\n~~,\\{~-0.004077873823019379,~-0.1304919623366201~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~4.443210814183816e-08,5.687309842155285e-06~\\}\n\n~~,\\{~-4.059040540924509e-06,-0.0003896678919287529~\\}\n\n~~,\\{~0.0001617705765833013,~0.01035331690133128~\\}\n\n~~,\\{~-0.003380675535016474,~-0.1081816171205272~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~4.684585000529841e-08,5.996268800678196e-06~\\}\n\n~~,\\{~-3.692914687568888e-06,-0.0003545198100066132~\\}\n\n~~,\\{~0.0001385002284466404,0.008864014620584983~\\}\n\n~~,\\{~-0.002780867190684069,-0.08898775010189021~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~4.750223096564192e-08,6.080285563602166e-06~\\}\n\n~~,\\{~-3.314663535346774e-06,-0.0003182076993932903~\\}\n\n~~,\\{~0.0001174735554921313,0.007518307551496402~\\}\n\n~~,\\{~-0.002269676983939308,-0.07262966348605786~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~4.670072464852188e-08,~5.9776927550108e-06~\\}\n\n~~,\\{~-2.937155806094876e-06,-0.0002819669573851081~\\}\n\n~~,\\{~9.872290650570907e-05,0.006318266016365381~\\}\n\n~~,\\{~-0.001838039771308927,-0.05881727268188565~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~4.474623841270917e-08,5.727518516826773e-06~\\}\n\n~~,\\{~-2.570833263466638e-06,-0.0002467999932927972~\\}\n\n~~,\\{~8.22106662144394e-05,0.005261482637724121~\\}\n\n~~,\\{~-0.00147690580564427,-0.04726098578061663~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~4.193316738169349e-08,5.367445424856766e-06~\\}\n\n~~,\\{~-2.223732912047361e-06,-0.0002134783595565467~\\}\n\n~~,\\{~6.784384611408351e-05,0.004342006151301345~\\}\n\n~~,\\{~-0.001177491364418304,-0.03767972366138573~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~3.853310716189559e-08,4.932237716722635e-06~\\}\n\n~~,\\{~-1.901622239253096e-06,-0.0001825557349682972~\\}\n\n~~,\\{~5.548818102150092e-05,0.003551243585376059~\\}\n\n~~,\\{~-0.0009314717770673435,-0.02980709686615499~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~3.478627717320908e-08,4.452643478170763e-06~\\}\n\n~~,\\{~-1.608217862833661e-06,-0.0001543889148320314~\\}\n\n~~,\\{~4.498114169517277e-05,0.002878793068491057~\\}\n\n~~,\\{~-0.000731120067225914,-0.02339584215122925~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~3.089643929408761e-08,3.954744229643214e-06~\\}\n\n~~,\\{~-1.345458635910959e-06,-0.000129164029047452~\\}\n\n~~,\\{~3.614345122621364e-05,0.002313180878477673~\\}\n\n~~,\\{~-0.0005693964281980402,-0.01822068570233729~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~2.702889954915076e-08,3.459699142291297e-06~\\}\n\n~~,\\{~-1.113806810496106e-06,-0.0001069254538076262~\\}\n\n~~,\\{~2.878886012546207e-05,0.001842487048029572~\\}\n\n~~,\\{~-0.0004399950596155604,-0.01407984190769793~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~2.331105572966068e-08,2.983815133396567e-06~\\}\n\n~~,\\{~-9.125546956961835e-07,-8.760525078683361e-05~\\}\n\n~~,\\{~2.273208266980214e-05,0.001454853290867337~\\}\n\n~~,\\{~-0.0003373555705483165,-0.01079537825754613~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~1.983489619315291e-08,2.538866712723572e-06~\\}\n\n~~,\\{~-7.40118807871303e-07,-7.105140555564509e-05~\\}\n\n~~,\\{~1.779491911631872e-05,0.001138874823444398~\\}\n\n~~,\\{~-0.0002566462908318581,-0.00821268130661946~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~1.66608547873407e-08,2.13258941277961e-06~\\}\n\n~~,\\{~-5.943082966062757e-07,-5.705359647420247e-05~\\}\n\n~~,\\{~1.381068205132086e-05,0.0008838836512845352~\\}\n\n~~,\\{~-0.0001937265370264521,-0.006199249184846466~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~1.382247111915601e-08,1.769276303251969e-06~\\}\n\n~~,\\{~-4.725590338093643e-07,-4.536566724569897e-05~\\}\n\n~~,\\{~1.062711036208305e-05,0.0006801350631733152~\\}\n\n~~,\\{~-0.000145094266684409,-0.004643016533901087~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~1.133138043388216e-08,1.450416695536916e-06~\\}\n\n~~,\\{~-3.721288720513465e-07,-3.572437171692926e-05~\\}\n\n~~,\\{~8.107993188612562e-06,0.000518911564071204~\\}\n\n~~,\\{~-0.0001078247346620797,-0.003450391509186549~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~9.182249868241103e-09,1.175327983134861e-06~\\}\n\n~~,\\{~-2.902530201337116e-07,-2.786428993283631e-05~\\}\n\n~~,\\{~6.133742295451233e-06,0.0003925595069088789~\\}\n\n~~,\\{~-7.950483672849648e-05,-0.002544154775311887~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~7.357376121771672e-09,9.41744143586774e-07~\\}\n\n~~,\\{~-2.242611569820876e-07,-2.152907107028042e-05~\\}\n\n~~,\\{~4.601149006582652e-06,0.0002944735364212897~\\}\n\n~~,\\{~-5.816687120992353e-05,-0.001861339878717553~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~5.830754319011006e-09,7.463365528334088e-07~\\}\n\n~~,\\{~-1.716598017483407e-07,-1.647934096784071e-05~\\}\n\n~~,\\{~3.422545861207931e-06,0.0002190429351173076~\\}\n\n~~,\\{~-4.222453301828047e-05,-0.001351185056584975~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~4.571512315677453e-09,5.85153576406714e-07~\\}\n\n~~,\\{~-1.301846350963824e-07,-1.249772496925271e-05~\\}\n\n~~,\\{~2.524568002693763e-06,0.0001615723521724008~\\}\n\n~~,\\{~-3.041312172389421e-05,-0.0009732198951646148~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~3.546674836120153e-09,4.539743790233795e-07~\\}\n\n~~,\\{~-9.782802374705724e-08,-9.391490279717495e-06~\\}\n\n~~,\\{~1.846679051040788e-06,0.0001181874592666104~\\}\n\n~~,\\{~-2.173522470186589e-05,-0.0006955271904597086~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~2.723275825780344e-09,3.48579305699884e-07~\\}\n\n~~,\\{~-7.284706052621752e-08,-6.993317810516882e-06~\\}\n\n~~,\\{~1.339594192283002e-06,8.573402830611214e-05~\\}\n\n~~,\\{~-1.541254130223323e-05,-0.0004932013216714634~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~2.069875334693146e-09,2.649440428407226e-07~\\}\n\n~~,\\{~-5.375712506594504e-08,-5.160684006330723e-06~\\}\n\n~~,\\{~9.637020384530377e-07,6.167693046099441e-05~\\}\n\n~~,\\{~-1.084404604250008e-05,-0.0003470094733600024~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~1.557560545084242e-09,1.99367749770783e-07~\\}\n\n~~,\\{~-3.931541933447623e-08,-3.774280256109718e-06~\\}\n\n~~,\\{~6.875582939894272e-07,4.400373081532334e-05~\\}\n\n~~,\\{~-7.570340751290444e-06,-0.0002422509040412942~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~1.160521497792107e-09,1.485467517173897e-07~\\}\n\n~~,\\{~-2.849824560521101e-08,-2.735831578100257e-06~\\}\n\n~~,\\{~4.864995334541183e-07,3.113597014106357e-05~\\}\n\n~~,\\{~-5.243804289419642e-06,-0.0001678017372614286~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~8.562933419045533e-10,1.096055477637828e-07~\\}\n\n~~,\\{~-2.04750605380212e-08,-1.965605811650035e-06~\\}\n\n~~,\\{~3.41404983959747e-07,2.184991897342381e-05~\\}\n\n~~,\\{~-3.603997550434695e-06,-0.0001153279216139102~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~6.25751255928244e-10,8.009616075881524e-08~\\}\n\n~~,\\{~-1.458162415139377e-08,-1.399835918533802e-06~\\}\n\n~~,\\{~~2.3761818240736e-07,1.520756367407104e-05~\\}\n\n~~,\\{~-2.457703348469032e-06,-7.864650715100903e-05~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~4.529340758609023e-10,5.79755617101955e-08~\\}\n\n~~,\\{~-1.029391197359319e-08,-9.882155494649466e-07~\\}\n\n~~,\\{~1.640284771128031e-07,1.04978225352194e-05~\\}\n\n~~,\\{~-1.662958424634951e-06,-5.321466958831844e-05~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~3.247602445078765e-10,4.15693112970082e-08~\\}\n\n~~,\\{~-7.203899323906403e-09,-6.915743350950147e-07~\\}\n\n~~,\\{~1.123040862084225e-07,7.187461517339037e-06~\\}\n\n~~,\\{~-1.116452558660085e-06,-3.572648187712273e-05~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~2.30686638875616e-10,2.952788977607884e-08~\\}\n\n~~,\\{~-4.997870017311665e-09,-4.797955216619198e-07~\\}\n\n~~,\\{~7.626321981856181e-08,4.880846068387956e-06~\\}\n\n~~,\\{~-7.43714246992367e-07,-2.379885590375575e-05~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~1.62348343465352e-10,2.078058796356506e-08~\\}\n\n~~,\\{~-3.437547837088295e-09,-3.300045923604763e-07~\\}\n\n~~,\\{~5.136699602782352e-08,3.287487745780705e-06~\\}\n\n~~,\\{~-4.915626419109025e-07,-1.573000454114888e-05~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~1.132062933665611e-10,1.449040555091982e-08~\\}\n\n~~,\\{~-2.344090013092694e-09,-2.250326412568986e-07~\\}\n\n~~,\\{~3.43169347778733e-08,2.196283825783891e-06~\\}\n\n~~,\\{~-3.223729352241681e-07,-1.031593392717338e-05~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~7.822032766619364e-11,1.001220194127279e-08~\\}\n\n~~,\\{~-1.5848050842967e-09,-1.521412880924832e-07~\\}\n\n~~,\\{~2.274016527990733e-08,1.455370577914069e-06~\\}\n\n~~,\\{~-2.097708834108638e-07,-6.71266826914764e-06~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~5.355770518520448e-11,6.855386263706173e-09~\\}\n\n~~,\\{~-1.062348163068451e-09,-1.019854236545713e-07~\\}\n\n~~,\\{~1.494668127269781e-08,~9.5658760145266e-07~\\}\n\n~~,\\{~-1.354374489379326e-07,-4.333998366013844e-06~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~3.634147481032868e-11,4.651708775722071e-09~\\}\n\n~~,\\{~-7.060897746027254e-10,-6.778461836186165e-08~\\}\n\n~~,\\{~9.74466484193354e-09,6.236585498837466e-07~\\}\n\n~~,\\{~-8.676393515408498e-08,-2.776445924930719e-06~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~2.443906800145819e-11,3.128200704186648e-09~\\}\n\n~~,\\{~-4.653362120425529e-10,-4.467227635608508e-08~\\}\n\n~~,\\{~6.301801322850928e-09,4.033152846624594e-07~\\}\n\n~~,\\{~-5.515014134094942e-08,-1.764804522910381e-06~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~1.628883049763073e-11,2.084970303696734e-09~\\}\n\n~~,\\{~-3.04087667299206e-10,-2.919241606072378e-08~\\}\n\n~~,\\{~4.042431109848616e-09,2.587155910303114e-07~\\}\n\n~~,\\{~-3.478251051578401e-08,-1.113040336505088e-06~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~1.076065172092256e-11,1.377363420278088e-09~\\}\n\n~~,\\{~-1.970454032946794e-10,-1.891635871628923e-08~\\}\n\n~~,\\{~2.572200970727208e-09,1.646208621265413e-07~\\}\n\n~~,\\{~-2.176617521777173e-08,-6.965176069686953e-07~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~7.046112666236051e-12,9.019024212782145e-10~\\}\n\n~~,\\{~-1.266132861125826e-10,-1.215487546680793e-08~\\}\n\n~~,\\{~1.623512136833541e-09,1.039047767573466e-07~\\}\n\n~~,\\{~-1.351481829664788e-08,-4.324741854927323e-07~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~4.573415576263572e-12,5.853971937617372e-10~\\}\n\n~~,\\{~-8.067651102423245e-11,-7.744945058326315e-09~\\}\n\n~~,\\{~1.016478927962931e-09,6.505465138962761e-08~\\}\n\n~~,\\{~-8.326168379349991e-09,-2.664373881391997e-07~\\}\n\n\\}~\\}\n\n,\\{~\\{\n\n~~\\{~2.942581325108452e-12,3.766504096138819e-10~\\}\n\n~~,\\{~-5.097751607967133e-11,-4.893841543648448e-09~\\}\n\n~~,\\{~6.313018521581508e-10,4.040331853812165e-08~\\}\n\n~~,\\{~-5.08963981633602e-09,-1.628684741227526e-07~\\}\n\n\\}~\\}\n\n\\}~;\n\nconst~double~~ErfEvaluator::IntegrationConstants{[}ErfEvaluator::k\\_Slices{]}\n\n=~\\{\n\n~~0.9647496350557387\n\n~,0.8945235826411205\n\n~,0.8251151582995999\n\n~,0.7570483478113061\n\n~,0.6908163429125882\n\n~,0.6268708869645903\n\n~,0.5656131765729484\n\n~,0.5073866186839697\n\n~,0.452471647684221\n\n~,0.4010827047956272\n\n~,0.3533673790720676\n\n~,0.3094076118069897\n\n~,0.2692227796948113\n\n~,0.2327744011161023\n\n~,0.1999721575621347\n\n~,0.1706808901260279\n\n~,0.1447282193300569\n\n~,0.1219124441277339\n\n~,0.1020104003572524\n\n~,0.0847849970053737\n\n~,0.06999219660381942\n\n~,0.05738725995438308\n\n~,0.04673013130128872\n\n~,0.03778989454781171\n\n~,0.03034828122884282\n\n~,0.02420225448230857\n\n~,0.01916572874603583\n\n~,0.01507051162193889\n\n~,0.01176657225069364\n\n~,0.00912175014762694\n\n~,0.007021020716142793\n\n~,0.005365429817903765\n\n~,0.004070801226287904\n\n~,0.003066308931668393\n\n~,0.002292992435297803\n\n~,0.001702278540127081\n\n~,0.001254558696270697\n\n~,0.0009178574353023258\n\n~,0.0006666153543141322\n\n~,0.000480599801055098\n\n~,0.0003439479971021772\n\n~,0.0002443408016824203\n\n~,0.0001723005396039184\n\n~,0.0001206030943084474\n\n~,8.379256147784313e-05\n\n~,5.778591550183871e-05\n\n~,3.955511222290099e-05\n\n~,2.687460931683381e-05\n\n~,1.81232329484865e-05\n\n~,1.213049270853172e-05\n\n~,8.058717921777377e-06\n\n~,5.313661691920574e-06\n\n~,3.477428056922396e-06\n\n~,2.258680312250875e-06\n\n~,1.456062300565673e-06\n\n~,9.316013422969179e-07\n\n~,5.915640033304468e-07\n\n~,3.728134139618971e-07\n\n~,2.33182677406109e-07\n\n~,1.447481221205399e-07\n\n~,8.91740616342884e-08\n\n~,5.452181280340989e-08\n\n~,3.308304223623579e-08\n\n~,1.99223879235018e-08\n\n\\}~;\n\\end{lyxcode}\n\n\\subsection{Logarithm}\n\n\\begin{lyxcode}\nconst~double~Math::hlogTable{[}16{]}~=~\\{\n\n~~0.0~//~::log(1.0)~,\n\n~~,~0.06062462181643484~//~::log(1.0~+~1.0/16.0),\n\n~~,~0.11778303565638346~//~::log(1.0~+~2.0/16.0),\n\n~~,~0.17185025692665923~//~::log(1.0~+~3.0/16.0),\n\n~~,~0.22314355131420976~//~::log(1.0~+~4.0/16.0),\n\n~~,~0.27193371548364176~//~::log(1.0~+~5.0/16.0),\n\n~~,~0.31845373111853459~//~::log(1.0~+~6.0/16.0),\n\n~~,~0.36290549368936847~//~::log(1.0~+~7.0/16.0),\n\n~~,~0.40546510810816438~//~::log(1.0~+~8.0/16.0),\n\n~~,~0.44628710262841953~//~::log(1.0~+~9.0/16.0),\n\n~~,~0.48550781578170082~//~::log(1.0~+~10.0/16.0),\n\n~~,~0.52324814376454787~//~::log(1.0~+~11.0/16.0),\n\n~~,~0.55961578793542266~//~::log(1.0~+~12.0/16.0),\n\n~~,~0.59470710774669278~//~::log(1.0~+~13.0/16.0),\n\n~~,~0.62860865942237409~//~::log(1.0~+~14.0/16.0),\n\n~~,~0.66139848224536502~//~::log(1.0~+~15.0/16.0)\n\n\\}~;\n\nconst~double~Math::hlogComp{[}16{]}~=~\\{\n\n~~1.0~/~(~1.0~+~0.0/16.0~)~,\n\n~~1.0~/~(~1.0~+~1.0/16.0~)~,\n\n~~1.0~/~(~1.0~+~2.0/16.0~)~,\n\n~~1.0~/~(~1.0~+~3.0/16.0~)~,\n\n~~1.0~/~(~1.0~+~4.0/16.0~)~,\n\n~~1.0~/~(~1.0~+~5.0/16.0~)~,\n\n~~1.0~/~(~1.0~+~6.0/16.0~)~,\n\n~~1.0~/~(~1.0~+~7.0/16.0~)~,\n\n~~1.0~/~(~1.0~+~8.0/16.0~)~,\n\n~~1.0~/~(~1.0~+~9.0/16.0~)~,\n\n~~1.0~/~(~1.0~+~10.0/16.0~)~,\n\n~~1.0~/~(~1.0~+~11.0/16.0~)~,\n\n~~1.0~/~(~1.0~+~12.0/16.0~)~,\n\n~~1.0~/~(~1.0~+~13.0/16.0~)~,\n\n~~1.0~/~(~1.0~+~14.0/16.0~)~,\n\n~~1.0~/~(~1.0~+~15.0/16.0~)\n\n\\}~;\n\n~//~Log~base~e,~along~similar~lines\n\n~//~(actually~computes~log(abs(x)),~gives~a~large~negative~number~for\n\n~//~f(0),~gives~a~large~positive\n\n~//~~number~if~fed~Inf~or~Nan)\n\n~static~inline~double~hlog(double~x)\n\n~\\{\n\n~~~const~DoubleMap~m(x)~;\n\n~~~int~exponent~=~m.Exponent()~;\n\n~~~unsigned~int~sig\\_hi~=~m.SignificandHiBits()~;\n\n~~~DoubleMap~m1(0,0,sig\\_hi,~m.SignificandLoBits())~;\n\n~~~unsigned~int~tableIndex~=~sig\\_hi~>\\,{}>~16~;\n\n~~~double~xx=m1.GetValue(){*}hlogComp{[}tableIndex{]}~-~1.0~;\n\n~~~//~There~should~be~scope~for~shortening~this~polynomial\n\n~~~//~(1)~rescale~for~'xx'~to~be~in~(-1/32,~1/32)~rather~than~(0,1/16)\n\n~~~//~(2)~have~a~larger~table,~and~take~more~bits~to~index~it\n\n~~~//~(actually,~not~sure~this~is~large~enough~for~double~precision)\n\n~~~double~p10~=~~~~~~~~~(-1.0/10.0)~;\n\n~~~double~p9~~=~p10~{*}~xx~+~(~~1.0~/~9.0~)~;\n\n~~~double~p8~~=~p9~{*}~xx~+~(~-1.0~/~8.0~)~;\n\n~~~double~p7~~=~p8~{*}~xx~+~(~~1.0~/~7.0~)~;\n\n~~~double~p6~~=~p7~{*}~xx~+~(~-1.0~/~6.0~)~;\n\n~~~double~p5~~=~p6~{*}~xx~+~(~~1.0~/~5.0~)~;\n\n~~~double~p4~~=~p5~{*}~xx~+~(~-1.0~/~4.0~)~;\n\n~~~double~p3~~=~p4~{*}~xx~+~(~~1.0~/~3.0~)~;\n\n~~~double~p2~~=~p3~{*}~xx~+~(~-1.0~/~2.0~)~;\n\n~~~double~p1~~=~p2~{*}~xx~+~(~~1.0~)~~;\n\n~~~double~p0~~=~p1~{*}~xx~;\n\n~~~double~result=~exponent{*}M\\_LN2~+~hlogTable{[}tableIndex{]}~+~p0~;\n\n/{*}\n\n~{*}~BegLogLine(1)\n\n~{*}~~~<\\,{}<~\\char`\\\"{}hlog~x=\\char`\\\"{}~<\\,{}<~x\n\n~{*}~~~<\\,{}<~\\char`\\\"{}~exponent=\\char`\\\"{}~<\\,{}<~exponent\n\n~{*}~~~<\\,{}<~\\char`\\\"{}~tableIndex=\\char`\\\"{}~<\\,{}<~tableIndex\n\n~{*}~~~<\\,{}<~\\char`\\\"{}~xx=\\char`\\\"{}~<\\,{}<~xx\n\n~{*}~~~<\\,{}<~\\char`\\\"{}~p0=\\char`\\\"{}~<\\,{}<~p0\n\n~{*}~~~<\\,{}<~\\char`\\\"{}~result=\\char`\\\"{}~<\\,{}<~result\n\n~{*}~~~<\\,{}<~EndLogLine~;\n\n~{*}/\n\n~~~return~result~;\n\n~\\}\n\\end{lyxcode}\n\n\\subsection{Exponential}\n\n\\begin{lyxcode}\n\\#ifdef~DBL\\_MAX\n\nconst~double~Math::Infinity~=~DBL\\_MAX~{*}~2.0~;~~//~Intended~to~overflow;\n\n~~~~~~~~~~~~~~~~~~~~~~~~//~will~be~used~as~result~of~hexp(x)~for~x~>~709\n\n\\#else\n\n\\#if~defined(PK\\_BGL)\n\n//~BG/L~compiler~doesn't~support~HUGE\\_VAL~quite~the~way~we~want~...\n\nconst~double~Math::Infinity~=~(1e200{*}1e200)~;~//~Intended~to~overflow\n\n\\#else\n\nconst~double~Math::Infinity~=~HUGE\\_VAL~{*}~HUGE\\_VAL~;\n\n\\#endif\n\n\\#endif\n\nconst~double~ExpK1~=~M\\_LN2/16.0~;\n\nconst~double~ExpK2~=~M\\_LN2/256.0~;\n\nconst~double~Math::ExpTable1{[}16{]}~=~\\{\n\n//~~~~~~::exp(~0.0{*}ExpK1)~,~~~~~~~::exp(~1.0{*}ExpK1)~,\n\n//~~~~~~::exp(~2.0{*}ExpK1)~,~~~~~~~::exp(~3.0{*}ExpK1)~,\n\n~~~~~~~~1.00000000000000000000~,~~1.04427378242741383881~,~\n\n~~~~~~~~1.09050773266525765605~,~~1.13878863475669164875\n\n//~~~~~~::exp(~4.0{*}ExpK1)~,~~~~~~~::exp(~5.0{*}ExpK1)~,\n\n//~~~~~~::exp(~6.0{*}ExpK1)~,~~~~~~~::exp(~7.0{*}ExpK1)~,\n\n~~~~~,~~1.18920711500272105982~,~~1.24185781207348403959~,~\n\n~~~~~~~~1.29683955465100965466~,~~1.35425554693689271456\n\n//~~~~~~::exp(~8.0{*}ExpK1)~,~~~~~~~::exp(~9.0{*}ExpK1)~,~~~~~~\n\n//~~~~~~::exp(10.0{*}ExpK1)~,~~~~~~~::exp(11.0{*}ExpK1)~,\n\n~~~~~,~~1.41421356237309503240~,~~1.47682614593949929212~,~\n\n~~~~~~~~1.54221082540794080126~,~~1.61049033194925428250\n\n//~~~~~~::exp(12.0{*}ExpK1)~,~~~~~~~::exp(13.0{*}ExpK1)~,~~~~~~\n\n//~~~~~~::exp(14.0{*}ExpK1)~,~~~~~~~::exp(15.0{*}ExpK1)~,\n\n~~~~~,~~1.68179283050742905681~,~~1.75625216037329945002~,~\n\n~~~~~~~~1.83400808640934242627~,~~1.91520656139714725223\n\n~~~\\}~;\n\nconst~double~Math::ExpTable2{[}16{]}~=~\\{\n\n//~~~~~~::exp(~0.0{*}ExpK2)~,~~~~~~~::exp(~1.0{*}ExpK2)~,\n\n//~~~~~~::exp(~2.0{*}ExpK2)~,~~~~~~~::exp(~3.0{*}ExpK2)~,\n\n~~~~~~~~1.00000000000000000000~,~~1.00271127505020248534~,~\n\n~~~~~~~~1.00542990111280282117~,~~1.00815589811841751551\n\n//~~~~~~::exp(~4.0{*}ExpK2)~,~~~~~~~::exp(~5.0{*}ExpK2)~,\n\n//~~~~~~::exp(~6.0{*}ExpK2)~,~~~~~~~::exp(~7.0{*}ExpK2)~,\n\n~~~~~,~~1.01088928605170045965~,~~1.01363008495148943838~,~\n\n~~~~~~~~1.01637831491095303739~,~~1.01913399607773794904\n\n//~~~~~~::exp(~8.0{*}ExpK2)~,~~~~~~~::exp(~9.0{*}ExpK2)~,\n\n//~~~~~~::exp(10.0{*}ExpK2)~,~~~~~~~::exp(11.0{*}ExpK2)~,\n\n~~~~~,~~1.02189714865411667749~,~~1.02466779289713564431~,~\n\n~~~~~~~~1.02744594911876369561~,~~1.03023163768604101185\n\n//~~~~~~::exp(12.0{*}ExpK2)~,~~~~~~~::exp(13.0{*}ExpK2)~,\n\n//~~~~~~::exp(14.0{*}ExpK2)~,~~~~~~~::exp(15.0{*}ExpK2)~,\n\n~~~~~,~~1.03302487902122842138~,~~1.03582569360195711881~,~\n\n~~~~~~~~1.03863410196137878930~,~~1.04145012468831613985\n\n~~~\\}~;\n\n~~/{*}\n\n~~~{*}~Branchless~exp(x),~with~a~view~to~vectorising~on~Double~Hummer\n\n~~~{*}/\n\n~~static~inline~double~hexp(double~x)\n\n~~\\{\n\n~~~~const~double~tp10~=~1024.0~;\n\n~~~~const~double~tp20~=~tp10{*}tp10~;\n\n~~~~const~double~tp40~=~tp20{*}tp20~;\n\n~~~~~//~Dividing~by~ln(2)~gives~a~value~such~that~we~can~put~the~\n\n~~~~~//~integer~part~into~an~exponent.\n\n~~~~~//~Adding~(2{*}{*}44+2{*}{*}43)~aligns~and~rounds~this~so~that\n\n~~~~~//~bottom~8~bits~can~be~used~for~lookup\n\n~~~~~//~higher~bits~can~be~stuffed~into~exponent\n\n~~~~~//~truncated~bits~(recovered~by~subtraction)~can~be~fed~to~\n\n~~~~~//~power~series\n\n~~~~const~double~x1~=~x~{*}~(~1.0~/~M\\_LN2~)~+~(~tp40~{*}~(~16.0~+~8.0~)~)~;\n\n~~~~const~DoubleMap~m1(x1)~;\n\n~~~~//~Figure~the~appropriate~power~of~2~from~the~significand~high~bits\n\n~~~~const~unsigned~int~sig\\_lo~=~m1.SignificandLoBits()~;\n\n~~~~const~DoubleMap~m2(0,sig\\_lo~>\\,{}>~8,~0,~0)~;\n\n~~~~//~Recover~the~number~that~we~will~have~'exponentiated'~by~the~bit\n\n~~~~//~twiddling\n\n~~~~const~double~xl2~=~~x1~-~(~tp40~{*}~(~16.0~+~8.0~)~)~;\n\n~~~~//~Can~range-check~xl2~to~see~if~sig\\_lo~put~a~sensible~value~in~m2\n\n~~~~const~double~xx4~=~xl2~{*}~M\\_LN2~;\n\n~~~~//~Look~up~the~next~several~bits~(4)~in~a~multiplication~table\n\n~~~~const~unsigned~int~tabits~=(sig\\_lo~>\\,{}>~4)~\\&~0x0f~;\n\n~~~~const~double~x31~=~ExpTable1{[}tabits{]}~;\n\n~~~~//~And~the~next~4~bits~in~another~table\n\n~~~~const~unsigned~int~tabits2=sig\\_lo~\\&~0x0f~;\n\n~~~~const~double~x32~=~ExpTable2{[}tabits2{]}~;\n\n~~~~const~double~x3~=~x31{*}x32~;\n\n~~~~//~Figure~the~remaining~part~of~the~original~number\n\n~~~~const~double~z~=~x~-~xx4~;\n\n~~~~//~z~should~be~between~+-~(2{*}{*}-8);~feed~in~to~polynomial~for~exp(z)\n\n~~~~const~double~f5~=~~~~~~~~~~1.0/(2.0{*}3.0{*}4.0{*}5.0)~;\n\n~~~~const~double~f4~=~z~{*}~f5~+~1.0/(2.0{*}3.0{*}4.0)~;\n\n~~~~const~double~f3~=~z~{*}~f4~+~1.0/(2.0{*}3.0)~;\n\n~~~~const~double~f2~=~z~{*}~f3~+~1.0/2.0~;\n\n~~~~const~double~f1~=~z~{*}~f2~+~1.0~;\n\n~~~~const~double~f0~=~z~{*}~f1~+~1.0~;\n\n~~~~const~double~p0~=~f0~{*}~x3~;\n\n~~~~const~double~x2=m2.GetValue()~;\n\n~~~~const~double~r0~=~p0~{*}~x2~;\n\n~~~~//~Fixup~for~out-of-range~parameter\n\n~~~~const~double~resultl~=~fsel(x+709.0,~r0,~0.0)~;\n\n~~~~const~double~resulth~=~fsel(x-709.0,~Infinity,~resultl)~;\n\n~~~~return~resulth~;\n\n~~\\}\n\\end{lyxcode}\n\n\\subsection{'acossin' (inverse sin/cos)}\n\n\\begin{lyxcode}\n~~template~<class~T>~static~inline~T~asin\\_small(T~x)\n\n~~~~\\{\n\n~~~~~~~const~double~ap0~=~1.0~~~~~~~~~~~,~aq0~=~1.0~~~~~~~;\n\n~~~~~~~const~double~ap1~=~ap0~{*}~1.0~~~~~,~aq1~=~aq0~{*}~2.0~;\n\n~~~~~~~const~double~ap2~=~ap1~{*}~3.0~~~~~,~aq2~=~aq1~{*}~4.0~;\n\n~~~~~~~const~double~ap3~=~ap2~{*}~5.0~~~~~,~aq3~=~aq2~{*}~6.0~;\n\n~~~~~~~const~double~ap4~=~ap3~{*}~7.0~~~~~,~aq4~=~aq3~{*}~8.0~;\n\n~~~~~~~const~double~ap5~=~ap4~{*}~9.0~~~~~,~aq5~=~aq4~{*}~10.0~;\n\n~~~~~~~const~double~ap6~=~ap5~{*}~11.0~~~~,~aq6~=~aq5~{*}~12.0~;\n\n~~~~~~~const~double~ap7~=~ap6~{*}~13.0~~~~,~aq7~=~aq6~{*}~14.0~;\n\n~~~~~~~const~double~ap8~=~ap7~{*}~15.0~~~~,~aq8~=~aq7~{*}~16.0~;\n\n~~~~~~~const~double~ap9~=~ap8~{*}~17.0~~~~,~aq9~=~aq8~{*}~18.0~;\n\n~~~~~~~const~double~apa~=~ap9~{*}~19.0~~~~,~aqa~=~aq9~{*}~20.0~;\n\n~~~~~~~const~double~apb~=~apa~{*}~21.0~~~~,~aqb~=~aqa~{*}~22.0~;\n\n~~~~~~~const~double~apc~=~apb~{*}~23.0~~~~,~aqc~=~aqb~{*}~24.0~;\n\n~~~~~~~const~double~apd~=~apc~{*}~25.0~~~~,~aqd~=~aqc~{*}~26.0~;\n\n~~~~~~~const~double~ape~=~apd~{*}~27.0~~~~,~aqe~=~aqd~{*}~28.0~;\n\n~~~~~~~const~double~apf~=~ape~{*}~29.0~~~~,~aqf~=~aqe~{*}~30.0~;\n\n~~~~~~~const~double~a14~=~~apf~/~(~aqf~{*}~31.0~)~;\n\n~~~~~~~const~double~a13~=~~ape~/~(~aqe~{*}~29.0~)~;\n\n~~~~~~~const~double~a12~=~~apd~/~(~aqd~{*}~27.0~)~;\n\n~~~~~~~const~double~a11~=~~apc~/~(~aqc~{*}~25.0~)~;~~~~~~;\n\n~~~~~~~const~double~a10~=~~apb~/~(~aqb~{*}~23.0~)~;\n\n~~~~~~~const~double~a9~~=~~apa~/~(~aqa~{*}~21.0~)~;\n\n~~~~~~~const~double~a8~~=~~ap9~/~(~aq9~{*}~19.0~)~;\n\n~~~~~~~const~double~a7~~=~~ap8~/~(~aq8~{*}~17.0~)~;\n\n~~~~~~~const~double~a6~~=~~ap7~/~(~aq7~{*}~15.0~)~;\n\n~~~~~~~const~double~a5~~=~~ap6~/~(~aq6~{*}~13.0~)~;\n\n~~~~~~~const~double~a4~~=~~ap5~/~(~aq5~{*}~11.0~)~;\n\n~~~~~~~const~double~a3~~=~~ap4~/~(~aq4~{*}~9.0~)~;\n\n~~~~~~~const~double~a2~~=~~ap3~/~(~aq3~{*}~7.0~)~;\n\n~~~~~~~const~double~a1~~=~~ap2~/~(~aq2~{*}~5.0~)~;\n\n~~~~~~~const~double~a0~~=~~ap1~/~(~aq1~{*}~3.0~)~;\n\n~~~~~~double~b,~s,~t1,~t0;\n\n~~~~~~s~=~~a14~+~a13~;\n\n~~~~~~b~=~x{*}x;\n\n~~~~~~t0~=~a14~{*}~b~+~a13;\n\n~~~~~~s~=~b~{*}~b;\n\n~~~~~~t0~=~(((((t0{*}s~+~a11){*}s~+~a9){*}s~+~a7){*}s~+~a5){*}s~+a3){*}s\n\n~~~~~~~~+~a1;\n\n~~~~~~t1~=~(((((a12{*}s~+~a10){*}s~+~a8){*}s~+~a6){*}s~+~a4){*}s~+~a2);\n\n~~~~~~return~(~x~+~(x{*}b){*}(a0~+~b{*}(t0~+~b{*}t1)));\n\n~~~~\\}\n\n~~~~//~Given~the~sin~and~cos~of~an~angle,~return~the~angle.\n\n~~~~//~Returns~an~angle~in~(-PI,~PI)\n\n~~~~inline~static~double~acossin~(~double~sinang,~double~cosang~)\n\n~~~~\\{\n\n~~~~~~const~double~piby8~=~M\\_PI~/~8.0~;~//~22.5~degrees,~in~radians;\n\n~~~~~~const~double~pi3by8~=~M\\_PI~{*}~(~3.0~/~8.0~)~;~//~3{*}22.5~degrees,~\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//~in~radians;\n\n~~~~~~const~double~pi5by8~=~M\\_PI~{*}~(~5.0~/~8.0~)~;~//~5{*}22.5~degrees,\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//~in~radians;\n\n~~~~~~const~double~pi7by8~=~M\\_PI~{*}~(~7.0~/~8.0~)~;~//~7{*}22.5~degrees,~\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//~in~radians;\n\n~~~~~~const~double~cospiby4~=~sqrt(2.0)~{*}~0.5~;\n\n~~~~~~const~double~cospiby8~=~sqrt((1+cospiby4)~{*}~0.5)~;\n\n~~~~~~const~double~sinpiby8~=~sqrt(1-cospiby8{*}cospiby8)~;\n\n~~~~~~double~abscos~=~fabs(cosang)~;~//~abscos~in~(0,1)\n\n~~~~~~double~abssin~=~fabs(sinang)~;~//~abssin~in~(0,1)\n\n~~~~~~double~coslarge~=~abscos~-~abssin~;\n\n~~~~~~//~Now~we~have~the~sin~and~cos~of~an~angle~between~0~and~90~degrees\n\n~~~~~~double~sincand1~=~abssin~{*}~cospiby8~-~abscos~{*}~sinpiby8~;~\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//~sin~of~an~angle~in~(-22.5,+67.5~degrees)\n\n~~~~~~double~coscand2~=~abscos~{*}~cospiby8~-~abssin~{*}~sinpiby8~;~\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//~cos~of~an~angle~in~(+22.5,~112.5~degrees)\n\n~~~~~~~~~~~~~~~~~~~~//~which~is~sin~of~an~angle~in~(+67.5,~-22.5~degrees)\n\n~~~~~~double~trigang~=~fsel(~coslarge~,~sincand1~,~coscand2~);~\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~//~reduced-range~item~ready~for~'arcsin'\n\n~~~~~~double~ang~=~asin\\_small(trigang)~;\n\n~~~~~~//~Now~we~have~an~angle~which~is~piecewise-linear~related~to~\n\n~~~~~~//~the~wanted~one,~over~the~whole~circle\n\n~~~~~~//~Compute~the~multiplier~and~addend~to~stitch~the~angle~back\n\n~~~~~~//~together\n\n~~~~~~//~according~as~which~octant~we~are~in;~this~computation~is\n\n~~~~~~//~interleavable\n\n~~~~~~//~since~both~are~branchless\n\n~~~~~~double~km0~=~fsel(~sinang,~1.0,~-1.0~)~;\n\n~~~~~~double~km1~=~fsel(~sinang,~-1.0,~1.0~)~;\n\n~~~~~~double~kma~=~fsel(~~coslarge~,~km0~,~km1~~)~;\n\n~~~~~~double~kmb~=~fsel(~~coslarge~,~km1~,~km0~)~;\n\n~~~~~~double~km~~=~fsel(~cosang~,~kma~,~kmb~)~;\n\n~~~~~~double~kaa~=~fsel(~coslarge~,~piby8,~pi3by8~)~;\n\n~~~~~~double~kab~=~fsel(~coslarge~,~pi7by8,~pi5by8~)~;\n\n~~~~~~double~ka~~=~fsel(~cosang~,~kaa~,~kab~)~{*}~km0~;\n\n~~~~~~//~And~stitch~the~angle~back~together\n\n~~~~~~return~(ang{*}km)~+~ka~;\n\n~~~~\\}\n\\end{lyxcode}\n\n\\subsection{Sin and Cos}\n\n\\begin{lyxcode}\n\\#if~!defined(INCLUDE\\_SINCOS\\_HPP)\n\n\\#define~INCLUDE\\_SINCOS\\_HPP\n\n/{*}\n\n~{*}~This~evaluates~'sin'~or~'cos'~of~an~angle,~as~a~single~basic~block~\n\n~{*}~(no~branches)\n\n~{*}~so~the~compiler~can~schedule~the~evaluation~interleaved~with~other\n\n~{*}~work.\n\n~{*}\n\n~{*}~The~angle~range~is~split~into~\n\n~{*}~(-45,~45),~(45,~135),~(135,~225),~(225,~315)~degrees\n\n~{*}~and~repeating.~According~as~the~range~and~whether~we~want~\n\n~{*}~'sin'~or~'cos',~a\n\n~{*}~suitable~even~function~(sin(x)/x~or~cos(x))~is~evaluated~as~a\n\n~{*}~Chebyshev~polynomial.~\n\n~{*}~This~is~then~compensated~by~multiplication~by~the\n\n~{*}~appropriate~one~of\n\n~{*}~+1,~+x,~-1,~or~-x,~giving~the~required~result\n\n~{*}\n\n~{*}~As~convenional,~the~argument~is~taken~in~radians.\n\n~{*}\n\n~{*}~The~tables~for~the~coefficients~of~the~Chebyshev~polynomials\n\n~{*}~are~set~up~separately\n\n~{*}\n\n~{*}~These~tables~are~good~for~8~coefficients,~but~only~the~first~7~\n\n~{*}~are~used~to~get~to\n\n~{*}~double~precision\n\n~{*}/\n\n\\#define~A\\_PI~3.14159265358979323846264338327950288\n\nclass~TrigConstants\n\n\\{\n\n~~~public:\n\n~~~~~~~~enum~\\{\n\n~~~~~~~~~~~~~~~~k\\_Diagnose~=~0~,\n\n~~~~~~~~~~~~~~~~k\\_ChebSize~=~7\n\n~~~~~~~~\\}~;\n\n\\}~;\n\n\\#if~defined(UNINIT\\_SINCOSTABLE)\n\nstatic~long~double~SinCosChebTable~{[}2{]}{[}TrigConstants::k\\_ChebSize+1{]}~;\n\n\\#else\n\nstatic~const~double~SinCosChebTable~{[}2{]}{[}TrigConstants::k\\_ChebSize+1{]}~=~\\{\n\n\\{\n\n~~-0.0789004058803453350315181615833139406341584620305671897936151525\n\n~,-0.0391445675270819570174285389007398988869386583741731420316625604\n\n~,+0.0003045094206789444055815695590884452454366695761311146250488983\n\n~,-0.0000011235749767964159582142036241454977987906529477530843654213\n\n~,+0.0000000024140399724137496071057892543727134506131049276895890590\n\n~,-0.0000000000033916367050375354740011828074494768576077765801943509\n\n~,+0.0000000000000033580876185142034466964844195879864668971641022093\n\n~,-0.0000000000000000024689833209931834105086652046149581936814955209\n\n\\}~,~\\{\n\n~~-0.2967361725903839745991879698781526954590354296709458772475200482\n\n~,-0.1464366443908368633207963601399962102709746936143883813474659270\n\n~,+0.0019214493118146467969071454374523876476540840033801859035372729\n\n~,-0.0000099649684898293000686691061850349099578334955892601473193098\n\n~,+0.0000000275765956071873951864383928564160302546849325446961470666\n\n~,-0.0000000000473994980816484403744256516400929203293229935948172038\n\n~,+0.0000000000000554954854148518274108762542315929735058906972782761\n\n~,-0.0000000000000000470970490651755595726933928753403549933019035260\n\n\\}\n\n\\}\n\n;\n\n\\#endif\n\n\\#if~defined(EXTERN\\_DK1)\n\nextern~double~dk1~;\n\n\\#else\n\ndouble~dk1~=~1.0~;\n\n\\#endif\n\nstatic~const~double~TrigK0table{[}4{]}~=~\\{~0.0,~1.0,~0.0,~-1.0~\\}~;\n\nstatic~const~double~TrigK1table{[}4{]}~=~\\{~1.0,~0.0,~-1.0,~0.0~\\}~;\n\nclass~Trig:~public~TrigConstants\n\n\\{\n\n~~~~~~~~public:\n\n~~~~~~~~/{*}\n\n~~~~~~~~~{*}~ChebyshevEvaluate~is~based~on~'CSEVL'~from~the~freely-redistributable~SLATEC~library~http://www.netlib.org/slatec\n\n~~~~~~~~~{*}~Further~references~are~in~'Numerical~Recipes'~http://www.nr.com/~and~'gsl\\_cheb\\_eval'~from~the\n\n~~~~~~~~~{*}~GNU~Scientific~Library~at~http://www.gnu.org/software/gsl/\n\n~~~~~~~~~{*}~The~compiler~unrolls~the~loop~fully,~for~reasonable~'m'\n\n~~~~~~~~~{*}/\n\n~~~~~~~~template~<int~m>\n\n~~~~~~~~static~inline~double~ChebyshevEvaluate(\n\n\\#if~defined(UNINIT\\_SINCOSTABLE)\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~long~double~c{[}m{]}\n\n\\#else\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~const~double~c{[}m{]}\n\n\\#endif\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~,double~x)\n\n~~~~~~~~\\{\n\n~~~~~~~~~~~~~~~~double~d=0.0~;\n\n~~~~~~~~~~~~~~~~double~dd=0.0~;\n\n~~~~~~~~~~~~~~~~double~x2=2.0{*}x;\n\n~~~~~~~~~~~~~~~~for~(int~j=m-1;j>=1;j~-=~1)~\\{\n\n~~~~~~~~~~~~~~~~~~~~~~~~double~sv=d;\n\n~~~~~~~~~~~~~~~~~~~~~~~~d=x2{*}d-dd+c{[}j{]};\n\n~~~~~~~~~~~~~~~~~~~~~~~~dd=sv;\n\n~~~~~~~~~~~~~~~~\\}\n\n~~~~~~~~~~~~~~~~return~x{*}d-dd+0.5{*}c{[}0{]};\n\n~~~~~~~~\\}\n\n~~~~~~~~static~inline~double~NearestInteger(const~double~x)\n\n~~~~~~~~\\{\n\n~~~~~~~~~~~const~double~two10~=~1024.0~;\n\n~~~~~~~~~~~const~double~two50~=~two10~{*}~two10~{*}~two10~{*}~two10~{*}~two10~;\n\n~~~~~~~~~~~const~double~two52~=~two50~{*}~4.0~;\n\n~~~~~~~~~~~const~double~two51~=~two50~{*}~2.0~;\n\n~~~~~~~~~~~const~double~offset~=~two52~+~two51~;\n\n~~~~~~~~~~~//~Force~add~and~subtract~of~appropriate~constant~to~drop~\n\n~~~~~~~~~~~//~fractional~part\n\n~~~~~~~~~~~//~..~hide~it~from~the~compiler~so~the~optimiser~won't\n\n~~~~~~~~~~~//~reassociate~things~..\n\n~~~~~~~~~~~const~double~losebits~=~(dk1{*}x)~+~offset~;\n\n~~~~~~~~~~~const~double~result~=~(dk1{*}losebits)~-~offset~;\n\n~~~~~~~~~~~return~result~;\n\n~~~~~~~~\\}\n\n~~~~~~~~static~double~Sin(double~Angle)\n\n~~~~~~~~\\{\n\n~~~~~~~~~~~~~~~~/{*}~Separate~domain~into\n\n~~~~~~~~~~~~~~~~~{*}~-0.5~..~0.5~:~-45~degree~to~+45~degrees\n\n~~~~~~~~~~~~~~~~~{*}~0.5~..~1.5~:~45~degrees~to~135~degrees\n\n~~~~~~~~~~~~~~~~~{*}~and~so~on\n\n~~~~~~~~~~~~~~~~~{*}/\n\n~~~~~~~~~~~~~~~~double~Quadrant~=~Angle~{*}~(2.0/A\\_PI)~;\n\n~~~~~~~~~~~~~~~~double~NearestInt~=~NearestInteger(Quadrant)~;\n\n~~~~~~~~~~~~~~~~int~iQuadrant~=~NearestInt;\n\n~~~~~~~~~~~~~~~~double~Remainder~=~Quadrant~-~NearestInt~;\n\n~~~~~~~~~~~~~~~~int~iTable~=~(iQuadrant~\\&~1)~;\n\n~~~~~~~~~~~~~~~~double~ChebVariable~=~Remainder~{*}~2.0~;\n\n~~~~~~~~~~~~~~~~double~f~=~ChebyshevEvaluate<k\\_ChebSize>\n\n~~~~~~~~~~~~~(SinCosChebTable{[}iTable{]},2.0{*}ChebVariable{*}ChebVariable-1.0);\n\n~~~~~~~~~~~~~~~~double~k0te~=~TrigK0table{[}iQuadrant~\\&~3{]}~;\n\n~~~~~~~~~~~~~~~~double~k1te~=~TrigK1table{[}iQuadrant~\\&~3{]}~;\n\n~~~~~~~~~~~~~~~~double~pt~=~k0te~+~ChebVariable~{*}~k1te~;~~~~~~~~~~~~~~~~\n\n~~~~~~~~~~~~~~~~double~st~=~k0te~+~(~Angle~-~NearestInt{*}(A\\_PI/2.0)~)~\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{*}~k1te~;~~~~~~~~~~~~~\n\n~~~~~~~~~~~~~~~~double~result~=~f{*}pt~+~~st~;\n\n//~~~~~~~~~~~~~~if~(~k\\_Diagnose~)\n\n//~~~~~~~~~~~~~~\\{\n\n//~~~~~~~~~~~~~~~~~~~~~~cout~<\\,{}<~\\char`\\\"{}Trig::Sin(\\char`\\\"{}~<\\,{}<~Angle~<\\,{}<~\\char`\\\"{})~\\char`\\\"{}\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~<\\,{}<~\\char`\\\"{}Remainder=\\char`\\\"{}~<\\,{}<~Remainder\n\n//~~~~~~~~~~~~~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~iTable=\\char`\\\"{}~<\\,{}<~iTable\n\n//~~~~~~~~~~~~~~~~~~~~~~~<\\,{}<~~~~~\\char`\\\"{}~iSign=\\char`\\\"{}~<\\,{}<~iSign\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~ChebVariable=\\char`\\\"{}~<\\,{}<~ChebVariable\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~f=\\char`\\\"{}~<\\,{}<~f\n\n//~~~~~~~~~~~~~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~result=\\char`\\\"{}~<\\,{}<~result\n\n//~~~~~~~~~~~~~~~~~~~~~~~<\\,{}<~endl~;\n\n//~~~~~~~~~~~~~~\\}\n\n~~~~~~~~~~~~~~~~return~result~;\n\n~~~~~~~~\\}\n\n~~~~~~~~static~double~Cos(double~Angle)\n\n~~~~~~~~\\{\n\n~~~~~~~~~~~~~~~~/{*}~Separate~domain~into\n\n~~~~~~~~~~~~~~~~~{*}~-0.5~..~0.5~:~-45~degree~to~+45~degrees\n\n~~~~~~~~~~~~~~~~~{*}~0.5~..~1.5~:~45~degrees~to~135~degrees\n\n~~~~~~~~~~~~~~~~~{*}~and~so~on\n\n~~~~~~~~~~~~~~~~~{*}/\n\n~~~~~~~~~~~~~~~~double~Quadrant~=~Angle~{*}~(2.0/A\\_PI)~;\n\n~~~~~~~~~~~~~~~~double~NearestInt~=~NearestInteger(Quadrant)~;\n\n~~~~~~~~~~~~~~~~int~iQuadrant~=~NearestInt;\n\n~~~~~~~~~~~~~~~~double~Remainder~=~Quadrant~-~NearestInt~;\n\n~~~~~~~~~~~~~~~~int~iTable~=~(iQuadrant~\\&~1)~;\n\n~~~~~~~~~~~~~~~~double~ChebVariable~=~Remainder~{*}~2.0~;\n\n~~~~~~~~~~~~~~~~double~f~=~ChebyshevEvaluate<k\\_ChebSize>\n\n~~~~~~~~~~~(SinCosChebTable{[}1-iTable{]},2.0{*}ChebVariable{*}ChebVariable-1.0);\n\n~~~~~~~~~~~~~~~~double~k0te~=~TrigK0table{[}iQuadrant~\\&~3{]}~;\n\n~~~~~~~~~~~~~~~~double~k1te~=~TrigK1table{[}iQuadrant~\\&~3{]}~;\n\n~~~~~~~~~~~~~~~~double~pt~=~k1te~-~ChebVariable~{*}~k0te~;\n\n~~~~~~~~~~~~~~~~double~st~=~k1te~-~(~~Angle~-~NearestInt{*}(A\\_PI/2.0)~)~\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{*}~~k0te~;~~~~~~~~~~~~\n\n~~~~~~~~~~~~~~~~double~result~=~f{*}pt~+~st~;\n\n//~~~~~~~~~~~~~~if~(~k\\_Diagnose~)\n\n//~~~~~~~~~~~~~~\\{\n\n//~~~~~~~~~~~~~~~~~~~~~~cout~<\\,{}<~\\char`\\\"{}Trig::Cos(\\char`\\\"{}~<\\,{}<~Angle~<\\,{}<~\\char`\\\"{})~\\char`\\\"{}\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~<\\,{}<~\\char`\\\"{}Remainder=\\char`\\\"{}~<\\,{}<~Remainder\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~iTable=\\char`\\\"{}~<\\,{}<~iTable\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~iSign=\\char`\\\"{}~<\\,{}<~iSign\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~ChebVariable=\\char`\\\"{}~<\\,{}<~ChebVariable\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~f=\\char`\\\"{}~<\\,{}<~f\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~result=\\char`\\\"{}~<\\,{}<~result\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~<\\,{}<~endl~;\n\n//~~~~~~~~~~~~~~\\}\n\n~~~~~~~~~~~~~~~~return~result~;\n\n~~~~~~~~\\}\n\n\\}~;\n\n\\#endif\n\\end{lyxcode}\n\n\\subsection{Nearest image in periodic volume}\n\n\\begin{lyxcode}\ndouble~dk1~=~1.0~;~//~The~compiler~does~not~know~this~is~\n\n~~//~constant,~so~should~not~'optimise'~away~the~rounding~below\n\nstatic~inline~double~NearestInteger(const~double~x)\n\n\\{\n\n~~~const~double~two10~=~1024.0~;\n\n~~~const~double~two50~=~two10~{*}~two10~{*}~two10~{*}~two10~{*}~two10~;\n\n~~~const~double~two52~=~two50~{*}~4.0~;\n\n~~~const~double~two51~=~two50~{*}~2.0~;\n\n~~~const~double~offset~=~two52~+~two51~;\n\n~~~//~Force~add~and~subtract~of~appropriate~constant~to~drop~\n\n~~~//~fractional~part\n\n~~~//~..~hide~it~from~the~compiler~so~the~optimiser~won't~\\textbackslash{}\n\n~~~//~reassociate~things~..\n\n~~~const~double~losebits~=~(dk1{*}x)~+~offset~;\n\n~~~const~double~result~=~(dk1{*}losebits)~-~offset~;\n\n~~~return~result~;\n\n\\}\n\nstatic~inline~double~NearestImageInFullyPeriodicLine(\n\n~~const~double~a\n\n~~,~const~double~b\n\n~~,~const~double~Period\n\n~~,~const~double~ReciprocalPeriod\n\n~~)\n\n\\{\n\n~~~const~double~d~=~b-a~;~//~'Regular'~distance~between~them,~\n\n~~~~~~~~~~~~~~~~~~~~~~//~if~small~enough~the~result~will~be~'b'\n\n~~~const~double~d\\_unit~=~d~{*}~ReciprocalPeriod~;~//~express~with~respect\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//~to~unit~periodicity,\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~//~for~-0.5~<~d\\_unit~<~0.5~result~will~be~'b'\n\n~~~const~double~d\\_unit\\_rounded~=~NearestInteger(~d\\_unit~)~;\n\n~~~const~double~result~=~b~-~d\\_unit\\_rounded~{*}~Period~;\n\n~~~return~result~;\n\n\\}\n\nstatic~inline~double~NearestDistanceInFullyPeriodicLine(\n\n~~const~double~a\n\n~~,~const~double~b\n\n~~,~const~double~Period\n\n~~,~const~double~ReciprocalPeriod\n\n~~)\n\n\\{\n\n~~~~~~const~double~d~=~b-a~;~//~'Regular'~distance~between~them,~\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//~if~small~enough~the~result~will~be~'b'\n\n~~~const~double~d\\_unit~=~d~{*}~ReciprocalPeriod~;~//~express~with~respect\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//~to~unit~periodicity,\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~//~for~-0.5~<~d\\_unit~<~0.5~result~will~be~'b'\n\n~~~const~double~d\\_unit\\_rounded~=~NearestInteger(d\\_unit)~;\n\n~~~const~double~result~=~d~-~d\\_unit\\_rounded~{*}~Period~;\n\n~~~return~result~;\n\n\\}\n\nstatic~inline~double~NearestVectorInFullyPeriodicLine(\n\n~~const~double~a\n\n~~,~const~double~b\n\n~~,~const~double~Period\n\n~~,~const~double~ReciprocalPeriod\n\n~~)\n\n\\{\n\n~~~return~a-NearestImageInFullyPeriodicLine(a,b,Period,ReciprocalPeriod);\n\n\\}\n\ninline\n\nvoid\n\nNearestImageInPeriodicVolume(const~XYZ~\\&PositionA,~const~XYZ~\\&PositionB,\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~XYZ~\\&Nearest)\n\n~~\\{\n\n~~double~mX~=~NearestImageInFullyPeriodicLine(PositionA.mX,~\n\n~~~~~~~~~~~~~~~~PositionB.mX,~DynVarMgrIF.mDynamicBoxDimensionVector.mX,~\n\n~~~~~~~~~~~~~~~~DynVarMgrIF.mDynamicBoxInverseDimensionVector.mX~)~;\n\n~~double~mY~=~NearestImageInFullyPeriodicLine(PositionA.mY,~\n\n~~~~~~~~~~~~~~~~PositionB.mY,~DynVarMgrIF.mDynamicBoxDimensionVector.mY,~\n\n~~~~~~~~~~~~~~~~DynVarMgrIF.mDynamicBoxInverseDimensionVector.mY~)~;\n\n~~double~mZ~=~NearestImageInFullyPeriodicLine(PositionA.mZ,~\n\n~~~~~~~~~~~~~~~~PositionB.mZ,~DynVarMgrIF.mDynamicBoxDimensionVector.mZ,~\n\n~~~~~~~~~~~~~~~~DynVarMgrIF.mDynamicBoxInverseDimensionVector.mZ~)~;\n\n~~Nearest.mX~=~mX~;\n\n~~Nearest.mY~=~mY~;\n\n~~Nearest.mZ~=~mZ~;\n\n~~\\}\n\ninline\n\nvoid\n\nNearestVectorInPeriodicVolume(const~XYZ~\\&PositionA,~const~XYZ~\\&PositionB,\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~XYZ~\\&Nearest)\n\n~~\\{\n\n~~double~mX~=~NearestVectorInFullyPeriodicLine(PositionA.mX,\n\n~~~~~~~~~~~~~~~~PositionB.mX,~DynVarMgrIF.mDynamicBoxDimensionVector.mX,\n\n~~~~~~~~~~~~~~~~DynVarMgrIF.mDynamicBoxInverseDimensionVector.mX~)~;\n\n~~double~mY~=~NearestVectorInFullyPeriodicLine(PositionA.mY,\n\n~~~~~~~~~~~~~~~~PositionB.mY,~DynVarMgrIF.mDynamicBoxDimensionVector.mY,\n\n~~~~~~~~~~~~~~~~DynVarMgrIF.mDynamicBoxInverseDimensionVector.mY~)~;\n\n~~double~mZ~=~NearestVectorInFullyPeriodicLine(PositionA.mZ,\n\n~~~~~~~~~~~~~~~~PositionB.mZ,~DynVarMgrIF.mDynamicBoxDimensionVector.mZ,\n\n~~~~~~~~~~~~~~~~DynVarMgrIF.mDynamicBoxInverseDimensionVector.mZ~)~;\n\n~~Nearest.mX~=~mX~;\n\n~~Nearest.mY~=~mY~;\n\n~~Nearest.mZ~=~mZ~;\n\n~~\\}\n\ninline\n\ndouble\n\nNearestSquareDistanceInPeriodicVolume(const~XYZ~\\&PositionA,~const~XYZ~\\&PositionB)\n\n~~\\{\n\n~~double~mX~=~NearestVectorInFullyPeriodicLine(PositionA.mX,\n\n~~~~~~~~~~~~~~~~PositionB.mX,~DynVarMgrIF.mDynamicBoxDimensionVector.mX,\n\n~~~~~~~~~~~~~~~~DynVarMgrIF.mDynamicBoxInverseDimensionVector.mX~)~;\n\n~~double~mY~=~NearestVectorInFullyPeriodicLine(PositionA.mY,\n\n~~~~~~~~~~~~~~~~PositionB.mY,~DynVarMgrIF.mDynamicBoxDimensionVector.mY,\n\n~~~~~~~~~~~~~~~~DynVarMgrIF.mDynamicBoxInverseDimensionVector.mY~)~;\n\n~~double~mZ~=~NearestVectorInFullyPeriodicLine(PositionA.mZ,\n\n~~~~~~~~~~~~~~~~PositionB.mZ,~DynVarMgrIF.mDynamicBoxDimensionVector.mZ,\n\n~~~~~~~~~~~~~~~~DynVarMgrIF.mDynamicBoxInverseDimensionVector.mZ~)~;\n\n~~return~~mX{*}mX~+~mY{*}mY~+~mZ{*}mZ~;\n\n~~\\}\n\n\n\\end{lyxcode}\n\n\\subsection{Fragment in range}\n\n\\begin{lyxcode}\ndouble~dk1~=~1.0~;~//~The~compiler~does~not~know~this~is~\n\n~~//~constant,~so~should~not~'optimise'~away~the~rounding~below\n\nstatic~inline~double~NearestInteger(const~double~x)\n\n\\{\n\n~~~const~double~two10~=~1024.0~;\n\n~~~const~double~two50~=~two10~{*}~two10~{*}~two10~{*}~two10~{*}~two10~;\n\n~~~const~double~two52~=~two50~{*}~4.0~;\n\n~~~const~double~two51~=~two50~{*}~2.0~;\n\n~~~const~double~offset~=~two52~+~two51~;\n\n~~~//~Force~add~and~subtract~of~appropriate~constant~to~drop~\n\n~~~//~fractional~part\n\n~~~//~..~hide~it~from~the~compiler~so~the~optimiser~won't~\n\n~~~//~reassociate~things~..\n\n~~~const~double~losebits~=~(dk1{*}x)~+~offset~;\n\n~~~const~double~result~=~(dk1{*}losebits)~-~offset~;\n\n~~~return~result~;\n\n\\}\n\n//~note~...~'FracScale'~returns~unsigned\n\nstatic~inline~unsigned~int~FracScale(double~n,~double~rd)\n\n\\{\n\n~~~double~t~=~n{*}rd~;\n\n~~~double~ti~=~NearestInteger(t)~;\n\n~~~double~tr~=~t-ti~;~~~~~~~~~~~~~~~~~~//~tr~should~be~in~(-0.5,~0.5)\n\n~~~const~double~two10~=~1024.0~;\n\n~~~const~double~two32~=~two10~{*}~two10~{*}~two10~{*}~4.0~;\n\n~~~double~tri~=~tr{*}two32~;\n\n~~~int~itri=tri~;\n\n~~~unsigned~int~utri~=~itri~;\n\n~~~return~utri~;~~~~~~~~~~~~~//~should~be~a~32-bit~integer~\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//~representing~the~fractional~position\n\n~\\}\n\nclass~NeighbourList\n\n\\{\n\n~~~public:\n\n~~~class~remainder\n\n~~~\\{\n\n~~~~~~public:\n\n~~~~~~~double~e2~;\n\n~~~~~~~int~~~~a~~;\n\n~~~~~~~int~dummy~;\n\n~~~\\}~;\n\n~~~enum~\\{\n\n~~~~~~k\\_FragCount~=~NUMBER\\_OF\\_FRAGMENTS\n\n~~~~~~\\}~;\n\n~~~enum~\\{\n\n~~~~~~k\\_ScaleShift~=~8\n\n~~~~~~\\}~;\n\n~~~const~XYZ~p~;\n\n~~~const~XYZ~k~;\n\n~~~double~x{[}k\\_FragCount{]}~;\n\n~~~double~y{[}k\\_FragCount{]}~;\n\n~~~double~z{[}k\\_FragCount{]}~;\n\n~~~double~e{[}k\\_FragCount{]}~;\n\n~~~double~ex{[}k\\_FragCount{]}~;\n\n~~~double~ey{[}k\\_FragCount{]}~;\n\n~~~double~ez{[}k\\_FragCount{]}~;\n\n~~~int~ix{[}k\\_FragCount{]}~;\n\n~~~int~iy{[}k\\_FragCount{]}~;\n\n~~~int~iz{[}k\\_FragCount{]}~;\n\n~~~int~iex{[}k\\_FragCount{]}~;\n\n~~~int~iey{[}k\\_FragCount{]}~;\n\n~~~int~iez{[}k\\_FragCount{]}~;\n\n~~~int~result{[}k\\_FragCount{]}~;\n\n~~~NeighbourList(const~XYZ\\&~ap,~const~XYZ\\&~ak):~p(ap),~k(ak)~\\{\n\n~~~~~~BegLogLine(PKFXLOG\\_NSQSOURCEFRAG\\_SUMMARY)\n\n~~~~~~~~~<\\,{}<~\\char`\\\"{}NeighbourList(~p=\\char`\\\"{}~<\\,{}<~p\n\n~~~~~~~~~<\\,{}<~\\char`\\\"{}~k=\\char`\\\"{}~<\\,{}<~k\n\n~~~~~~~~~<\\,{}<~EndLogLine~;\n\n~~~\\}~;\n\n~~~int~ProduceAll(\n\n~~~~~const~XYZ\\&~aXYZ\n\n~~~~~,~const~XYZ\\&~eXYZ\n\n~~~~~,~double~e0\n\n~~~~~,~int~qstart\n\n~~~~~,~int~qend\n\n~~~)~\\{\n\n~~~~~~int~q0~=~0~;\n\n~~~~~~for~(int~a0=qstart;~a0<qend;~a0+=1~)\n\n~~~~~~\\{\n\n~~~~~~~~~result{[}q0{]}~=~a0~;\n\n~~~~~~~~~q0~+=~1~;\n\n~~~~~~\\}\n\n~~~~~~return~q0~;\n\n~~~~~\\}\n\n~~~int~Produce(\n\n~~~~~const~XYZ\\&~aXYZ\n\n~~~~~,~const~XYZ\\&~eXYZ\n\n~~~~~,~double~e0\n\n~~~~~,~int~qstart\n\n~~~~~,~int~qend\n\n~~~)~\\{\n\n~~~~~~~double~x0~=~aXYZ.mX~;\n\n~~~~~~~double~px~=~p.mX~;\n\n~~~~~~~double~kx~=~k.mX~;\n\n~~~~~~/{*}\n\n~~~~~~~{*}~Slice~for~slab\n\n~~~~~~~{*}/\n\n~~~~~~remainder~xr{[}k\\_FragCount{]}~;\n\n~~~~~~remainder~yr{[}k\\_FragCount{]}~;\n\n~~~~~~int~q1~=~0~;\n\n~~~~~~for~(int~a0=qstart;~a0<qend;~a0+=1~)\n\n~~~~~~\\{\n\n~~~~~~~~~double~dx~=~NearestDistanceInFullyPeriodicLine(x0,x{[}a0{]},px,kx)~;\n\n~~~~~~~~~double~em~=~e0~+~e{[}a0{]}~;\n\n~~~~~~~~~double~ex2~=~em{*}em~-~dx{*}dx~;\n\n~~~~~~~~~xr{[}q1{]}.e2~=~ex2~;\n\n~~~~~~~~~xr{[}q1{]}.a~=~a0~;\n\n~~~~~~~~~double~FragmentIndexAdd~=~fsel(ex2,1.0,0.0)~;\n\n~~~~~~~~~int~IndexAdd~=~FragmentIndexAdd~;\n\n~~~~~~~~~q1~+=~IndexAdd~;\n\n~~~~~~~~~BegLogLine(~PKFXLOG\\_NSQSOURCEFRAG~)\n\n~~~~~~~~~~~<\\,{}<~\\char`\\\"{}NeighbourList::Produce~X\\char`\\\"{}\n\n~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~IndexAdd~\\char`\\\"{}~<\\,{}<~IndexAdd\n\n~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~a0~\\char`\\\"{}~<\\,{}<~a0\n\n~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~x0~\\char`\\\"{}~<\\,{}<~x0\n\n~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~x~\\char`\\\"{}~<\\,{}<~x{[}a0{]}\n\n~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~dx~\\char`\\\"{}~<\\,{}<~dx\n\n~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~e0~\\char`\\\"{}~<\\,{}<~e0\n\n~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~ex2~\\char`\\\"{}~<\\,{}<~ex2\n\n~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~q1~\\char`\\\"{}~<\\,{}<~q1\n\n~~~~~~~~~~~<\\,{}<~EndLogLine;\n\n~~~~~~\\}~/{*}~endfor~{*}/\n\n~~~~~~BegLogLine(~PKFXLOG\\_NSQSOURCEFRAG\\_SUMMARY1~)\n\n~~~~~~~~<\\,{}<~\\char`\\\"{}NeighbourList::Produce~X~Summary\\char`\\\"{}\n\n~~~~~~~~<\\,{}<~\\char`\\\"{}~q1~\\char`\\\"{}~<\\,{}<~q1\n\n~~~~~~~~<\\,{}<~EndLogLine~;\n\n~~~~~double~y0~=~aXYZ.mY~;\n\n~~~~~~~double~py~=~p.mY~;\n\n~~~~~~~double~ky~=~k.mY~;\n\n~~~~~~/{*}\n\n~~~~~~~{*}~Slice~for~cylinder\n\n~~~~~~~{*}/\n\n~~~~~~int~q2~=~0~;\n\n~~~~~~for~(int~b1=0;~b1<q1;~b1+=1~)\n\n~~~~~~\\{\n\n~~~~~~~~~int~a1~=~xr{[}b1{]}.a~;\n\n~~~~~~~~~double~dy~=~NearestDistanceInFullyPeriodicLine(y0,y{[}a1{]},py,ky)~;\n\n~~~~~~~~~double~ey2~=~xr{[}b1{]}.e2~-~dy{*}dy~;\n\n~~~~~~~~~yr{[}q2{]}.e2~=~ey2~;\n\n~~~~~~~~~yr{[}q2{]}.a~=~a1~;\n\n~~~~~~~~~double~FragmentIndexAdd~=~fsel(ey2,1.0,0.0)~;\n\n~~~~~~~~~int~IndexAdd~=~FragmentIndexAdd~;\n\n~~~~~~~~~q2~+=~IndexAdd~;\n\n~~~~~~~~~BegLogLine(~PKFXLOG\\_NSQSOURCEFRAG~)\n\n~~~~~~~~~~~<\\,{}<~\\char`\\\"{}NeighbourList::Produce~Y\\char`\\\"{}\n\n~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~IndexAdd~\\char`\\\"{}~<\\,{}<~IndexAdd\n\n~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~a1~\\char`\\\"{}~<\\,{}<~a1\n\n~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~y0~\\char`\\\"{}~<\\,{}<~y0\n\n~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~y~\\char`\\\"{}~<\\,{}<~y{[}a1{]}\n\n~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~dy~\\char`\\\"{}~<\\,{}<~dy\n\n~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~e2~\\char`\\\"{}~<\\,{}<~xr{[}b1{]}.e2\n\n~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~ey2~\\char`\\\"{}~<\\,{}<~ey2\n\n~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~q2~\\char`\\\"{}~<\\,{}<~q2\n\n~~~~~~~~~~~<\\,{}<~EndLogLine;\n\n~~~~~~\\}~/{*}~endfor~{*}/\n\n//~~~~BegLogLine(~PKFXLOG\\_NSQSOURCEFRAG\\_SUMMARY~)\n\n//~~~~~~<\\,{}<~\\char`\\\"{}NeighbourList::Produce~Y~Summary\\char`\\\"{}\n\n//~~~~~~<\\,{}<~\\char`\\\"{}~q2~\\char`\\\"{}~<\\,{}<~q2\n\n//~~~~~~<\\,{}<~EndLogLine~;\n\n~~~~~double~z0~=~aXYZ.mZ~;\n\n~~~~~~~double~pz~=~p.mZ~;\n\n~~~~~~~double~kz~=~k.mZ~;\n\n~~~~~~/{*}\n\n~~~~~~~{*}~Slice~for~sphere\n\n~~~~~~~{*}/\n\n~~~~~~int~q3~=~0~;\n\n~~~~~~for~(int~b2=0;~b2<q2;~b2+=1~)\n\n~~~~~~\\{\n\n~~~~~~~~~int~a2~=~yr{[}b2{]}.a~;\n\n~~~~~~~~~double~dz~=~NearestDistanceInFullyPeriodicLine(z0,z{[}a2{]},pz,kz)~;\n\n~~~~~~~~~double~ez2~=~yr{[}b2{]}.e2~-~dz{*}dz~;\n\n~~~~~~~~~result{[}q3{]}~=~a2~;\n\n~~~~~~~~~double~FragmentIndexAdd~=~fsel(ez2,1.0,0.0)~;\n\n~~~~~~~~~int~IndexAdd~=~FragmentIndexAdd~;\n\n~~~~~~~~~q3~+=~IndexAdd~;\n\n~~~~~~~~~BegLogLine(~PKFXLOG\\_NSQSOURCEFRAG~)\n\n~~~~~~~~~~~<\\,{}<~\\char`\\\"{}NeighbourList::Produce~Z\\char`\\\"{}\n\n~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~IndexAdd~\\char`\\\"{}~<\\,{}<~IndexAdd\n\n~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~a2~\\char`\\\"{}~<\\,{}<~a2\n\n~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~z0~\\char`\\\"{}~<\\,{}<~z0\n\n~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~z~\\char`\\\"{}~<\\,{}<~z{[}a2{]}\n\n~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~dz~\\char`\\\"{}~<\\,{}<~dz\n\n~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~e2~\\char`\\\"{}~<\\,{}<~xr{[}b2{]}.e2\n\n~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~ez2~\\char`\\\"{}~<\\,{}<~ez2\n\n~~~~~~~~~~~<\\,{}<~\\char`\\\"{}~q3~\\char`\\\"{}~<\\,{}<~q3\n\n~~~~~~~~~~~<\\,{}<~EndLogLine;\n\n~~~~~~\\}~/{*}~endfor~{*}/\n\n~~~~~~BegLogLine(~PKFXLOG\\_NSQSOURCEFRAG\\_SUMMARY1~)\n\n~~~~~~~~<\\,{}<~\\char`\\\"{}NeighbourList::Produce~Z~Summary\\char`\\\"{}\n\n~~~~~~~~<\\,{}<~\\char`\\\"{}~q3~\\char`\\\"{}~<\\,{}<~q3\n\n~~~~~~~~<\\,{}<~EndLogLine~;\n\n~~~~~~return~q3~;\n\n~~~~~~\\}~;\n\n~~~int~iProduce(\n\n~~~~~const~XYZ\\&~aXYZ\n\n~~~~~,~const~XYZ\\&~eXYZ\n\n~~~~~,~double~e0\n\n~~~~~,~int~qstart\n\n~~~~~,~int~qend\n\n~~~)~\\{\n\n~~~~~~const~double~tp32~=~1024.0{*}1024.0{*}1024.0{*}4.0~;\n\n~~~~~~int~aix~=~FracScale(aXYZ.mX,k.mX)~;\n\n~~~~~~int~aiy~=~FracScale(aXYZ.mY,k.mY)~;\n\n~~~~~~int~aiz~=~FracScale(aXYZ.mZ,k.mZ)~;\n\n~~~~~~int~aiex~=~FracScale(eXYZ.mX,k.mX/(1<\\,{}<k\\_ScaleShift))~~;\n\n~~~~~~int~aiey~=~FracScale(eXYZ.mY,k.mY/(1<\\,{}<k\\_ScaleShift))~~;\n\n~~~~~~int~aiez~=~FracScale(eXYZ.mZ,k.mZ/(1<\\,{}<k\\_ScaleShift))~~;\n\n~~~~~~/{*}\n\n~~~~~~~{*}~Slice~for~slab\n\n~~~~~~~{*}/\n\n~~~~~~int~xr{[}k\\_FragCount{]}~;\n\n~~~~~~int~q1~=~0~;\n\n~~~~~~for~(int~a0=qstart;~a0<qend;~a0+=1~)\n\n~~~~~~\\{\n\n~~~~~~~~~int~idx~=~aix~-~ix{[}a0{]}~;~~~~//~Difference~in~'x'~coordinate,\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//~scaled~on~full~integer~range\n\n~~~~~~~~~int~idxq~=~idx~>\\,{}>~k\\_ScaleShift~;~//~Difference~in~'x'\n\n~~~~~~~~~~~~~~~~~~~//~coordinate,~scaled~down~to~keep~away~from~overflows\n\n~~~~~~~~~int~iem~=~(-aiex)~-~iex{[}a0{]}~;~//~Max~difference~for~things~to~be\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//~worth~computing,~scaled~like~idxq\n\n~~~~~~~~~int~nexp~=~iem~+~idxq~~;\n\n~~~~~~~~~int~nexn~=~iem~-~idxq~~;\n\n~~~~~~~~~unsigned~int~nex~=~nexp~\\&~nexn~;~~//~Negative~if~both~of~the\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//~above~are~negative,~i.e.~in~range\n\n~~~~~~~~~int~IndexAdd~=~nex~>\\,{}>~31~;\n\n~~~~~~~~~xr{[}q1{]}~=~a0~;\n\n~~~~~~~~~q1~+=~IndexAdd~;\n\n~~~~~~\\}\n\n~~~~~~BegLogLine(~PKFXLOG\\_NSQSOURCEFRAG\\_SUMMARY1~)\n\n~~~~~~~~<\\,{}<~\\char`\\\"{}NeighbourList::Produce~X~Summary\\char`\\\"{}\n\n~~~~~~~~<\\,{}<~\\char`\\\"{}~q1~\\char`\\\"{}~<\\,{}<~q1\n\n~~~~~~~~<\\,{}<~EndLogLine~;\n\n~~~~~~/{*}\n\n~~~~~~~{*}~Slice~for~square~prism\n\n~~~~~~~{*}/\n\n~~~~~~int~yr{[}k\\_FragCount{]}~;\n\n~~~~~~int~q2~=~0~;\n\n~~~~~~for~(int~b1=0;~b1<q1;~b1+=1~)\n\n~~~~~~\\{\n\n~~~~~~~~~int~a1~=~xr{[}b1{]}~;\n\n~~~~~~~~~int~idy~=~aiy~-~iy{[}a1{]}~;\n\n~~~~~~~~~int~idyq~=~idy~>\\,{}>~k\\_ScaleShift~;~//~Difference~in~'y'\n\n~~~~~~~~~~~~~~~~~~~//~coordinate,~scaled~down~to~keep~away~from~overflows\n\n~~~~~~~~~int~iem~=~(-aiey)~-~iey{[}a1{]}~;\n\n~~~~~~~~~int~neyp~=~iem~-~idyq~;\n\n~~~~~~~~~int~neyn~=~iem~+~idyq~;\n\n~~~~~~~~~unsigned~int~ney~=~neyp~\\&~neyn~;\n\n~~~~~~~~~int~IndexAdd~=~ney~>\\,{}>~31~;\n\n~~~~~~~~~yr{[}q2{]}~=~a1~;\n\n~~~~~~~~~q2~+=~IndexAdd~;\n\n~~~~~~\\}~/{*}~endfor~{*}/\n\n~~~~~~/{*}\n\n~~~~~~~{*}~Slice~for~cube\n\n~~~~~~~{*}/\n\n~~~~~~int~zr{[}k\\_FragCount{]}~;\n\n~~~~~~int~q3~=~0~;\n\n~~~~~~for~(int~b2=0;~b2<q2;~b2+=1~)\n\n~~~~~~\\{\n\n~~~~~~~~~int~a2~=~yr{[}b2{]}~;\n\n~~~~~~~~~int~idz~=~aiz~-~iz{[}a2{]}~;\n\n~~~~~~~~~int~idzq~=~idz~>\\,{}>~k\\_ScaleShift~;~//~Difference~in~'z'\n\n~~~~~~~~~~~~~~~~~~~//~coordinate,~scaled~down~to~keep~away~from~overflows\n\n~~~~~~~~~int~iem~=~(-aiez)~-~iez{[}a2{]}~;\n\n~~~~~~~~~int~nezp~=~iem~-~idzq~;\n\n~~~~~~~~~int~nezn~=~iem~+~idzq~;\n\n~~~~~~~~~unsigned~int~nez~=~nezp~\\&~nezn~;\n\n~~~~~~~~~int~IndexAdd~=~nez~>\\,{}>~31~;\n\n~~~~~~~~~zr{[}q3{]}~=~a2~;\n\n~~~~~~~~~q3~+=~IndexAdd~;\n\n~~~~~~\\}~/{*}~endfor~{*}/\n\n~~~~~~/{*}\n\n~~~~~~~{*}~Examine~cuboid~for~sphere\n\n~~~~~~~{*}/\n\n~~~~~~int~q4~=~0~;\n\n~~~~~~double~x0=aXYZ.mX~;\n\n~~~~~~double~y0=aXYZ.mY~;\n\n~~~~~~double~z0=aXYZ.mZ~;\n\n~~~~~~double~px~=~p.mX~;\n\n~~~~~~double~py~=~p.mY~;\n\n~~~~~~double~pz~=~p.mZ~;\n\n~~~~~~double~kx~=~k.mX~;\n\n~~~~~~double~ky~=~k.mY~;\n\n~~~~~~double~kz~=~k.mZ~;\n\n~~~~~~for~(int~b3=0;~b3<q3~;~b3+=1)\n\n~~~~~~\\{\n\n~~~~~~~~~int~a3~=~zr{[}b3{]}~;\n\n~~~~~~~~~double~dx~=~NearestDistanceInFullyPeriodicLine(x0,x{[}a3{]},px,kx)~;\n\n~~~~~~~~~double~dy~=~NearestDistanceInFullyPeriodicLine(y0,y{[}a3{]},py,ky)~;\n\n~~~~~~~~~double~dz~=~NearestDistanceInFullyPeriodicLine(z0,z{[}a3{]},pz,kz)~;\n\n~~~~~~~~~double~em~=~e0~+~e{[}a3{]}~;\n\n~~~~~~~~~double~ex2~=~em{*}em~-~dx{*}dx~-~dy{*}dy~-~dz{*}dz~;\n\n~~~~~~~~~result{[}q4{]}~=~a3~;\n\n~~~~~~~~~double~FragmentIndexAdd~=~fsel(ex2,1.0,0.0)~;\n\n~~~~~~~~~int~IndexAdd~=~FragmentIndexAdd~;\n\n~~~~~~~~~q4~+=~IndexAdd~;\n\n~~~~~~\\}~/{*}~endfor~{*}/\n\n~~~~~~BegLogLine(~PKFXLOG\\_NSQSOURCEFRAG\\_SUMMARY1~)\n\n~~~~~~~~<\\,{}<~\\char`\\\"{}NeighbourList::Produce~S~Summary\\char`\\\"{}\n\n~~~~~~~~<\\,{}<~\\char`\\\"{}~q4~\\char`\\\"{}~<\\,{}<~q4\n\n~~~~~~~~<\\,{}<~EndLogLine~;\n\n~~~~~~return~q4~;\n\n~~~~~\\}~;\n\n~~~int~iProduce\\_logged(\n\n~~~~~const~XYZ\\&~aXYZ\n\n~~~~~,~const~XYZ\\&~eXYZ\n\n~~~~~,~double~e0\n\n~~~~~,~int~qstart\n\n~~~~~,~int~qend\n\n~~~)~\\{\n\n~~~~~~const~double~tp32~=~1024.0{*}1024.0{*}1024.0{*}4.0~;\n\n~~~~~~int~aix~=~FracScale\\_logged(aXYZ.mX,k.mX)~;\n\n~~~~~~int~aiy~=~FracScale\\_logged(aXYZ.mY,k.mY)~;\n\n~~~~~~int~aiz~=~FracScale\\_logged(aXYZ.mZ,k.mZ)~;\n\n~~~~~~int~aiex~=~FracScale\\_logged(eXYZ.mX,k.mX/(1<\\,{}<k\\_ScaleShift))~~;\n\n~~~~~~int~aiey~=~FracScale\\_logged(eXYZ.mY,k.mY/(1<\\,{}<k\\_ScaleShift))~~;\n\n~~~~~~int~aiez~=~FracScale\\_logged(eXYZ.mZ,k.mZ/(1<\\,{}<k\\_ScaleShift))~~;\n\n~~~~~~BegLogLine(~1~)\n\n~~~~~~~~<\\,{}<~\\char`\\\"{}iProduce~aXYZ=\\char`\\\"{}~<\\,{}<~aXYZ\n\n~~~~~~~~<\\,{}<~\\char`\\\"{}~k=\\char`\\\"{}~<\\,{}<~k\n\n~~~~~~~~<\\,{}<~\\char`\\\"{}~eXYZ=\\char`\\\"{}~<\\,{}<~eXYZ\n\n~~~~~~~~<\\,{}<~\\char`\\\"{}~aix=\\char`\\\"{}~<\\,{}<~hex~<\\,{}<~aix\n\n~~~~~~~~<\\,{}<~\\char`\\\"{}~aiy=\\char`\\\"{}~<\\,{}<~hex~<\\,{}<~aiy\n\n~~~~~~~~<\\,{}<~\\char`\\\"{}~aiz=\\char`\\\"{}~<\\,{}<~hex~<\\,{}<~aiz\n\n~~~~~~~~<\\,{}<~\\char`\\\"{}~aiex=\\char`\\\"{}~<\\,{}<~hex~<\\,{}<~aiex\n\n~~~~~~~~<\\,{}<~\\char`\\\"{}~aiey=\\char`\\\"{}~<\\,{}<~hex~<\\,{}<~aiey\n\n~~~~~~~~<\\,{}<~\\char`\\\"{}~aiez=\\char`\\\"{}~<\\,{}<~hex~<\\,{}<~aiez\n\n~~~~~~~~<\\,{}<~dec\n\n~~~~~~~~<\\,{}<~EndLogLine~;\n\n~~~~~~/{*}\n\n~~~~~~~{*}~Slice~for~slab\n\n~~~~~~~{*}/\n\n~~~~~~int~xr{[}k\\_FragCount{]}~;\n\n~~~~~~int~q1~=~0~;\n\n~~~~~~for~(int~a0=qstart;~a0<qend;~a0+=1~)\n\n~~~~~~\\{\n\n~~~~~~~~~int~idx~=~aix~-~ix{[}a0{]}~;~~~~//~Difference~in~'x'~coordinate,\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//~scaled~on~full~integer~range\n\n~~~~~~~~~int~idxq~=~idx~>\\,{}>~k\\_ScaleShift~;~//~Difference~in~'x'\n\n~~~~~~~~~~~~~~//~coordinate,~scaled~down~to~keep~away~from~overflows\n\n~~~~~~~~~int~iem~=~(-aiex)~-~iex{[}a0{]}~;~//~Max~difference~for~things~to~be\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//~worth~computing,~scaled~like~idxq\n\n~~~~~~~~~int~nexp~=~iem~+~idxq~~;\n\n~~~~~~~~~int~nexn~=~iem~-~idxq~~;\n\n~~~~~~~~~unsigned~int~nex~=~nexp~\\&~nexn~;~~//~Negative~if~both~of~the\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//~above~are~negative,~i.e.~in~range\n\n~~~~~~~~~int~IndexAdd~=~nex~>\\,{}>~31~;\n\n~~~~~~~~~xr{[}q1{]}~=~a0~;\n\n~~~~~~~~~q1~+=~IndexAdd~;\n\n~~~~~~\\}\n\n~~~~~~/{*}\n\n~~~~~~~{*}~Slice~for~square~prism\n\n~~~~~~~{*}/\n\n~~~~~~int~yr{[}k\\_FragCount{]}~;\n\n~~~~~~int~q2~=~0~;\n\n~~~~~~for~(int~b1=0;~b1<q1;~b1+=1~)\n\n~~~~~~\\{\n\n~~~~~~~~~int~a1~=~xr{[}b1{]}~;\n\n~~~~~~~~~int~idy~=~aiy~-~iy{[}a1{]}~;\n\n~~~~~~~~~int~idyq~=~idy~>\\,{}>~k\\_ScaleShift~;~//~Difference~in~'y'\n\n~~~~~~~~~~~~~~~~~~~//~coordinate,~scaled~down~to~keep~away~from~overflows\n\n~~~~~~~~~int~iem~=~(-aiey)~-~iey{[}a1{]}~;\n\n~~~~~~~~~int~neyp~=~iem~-~idyq~;\n\n~~~~~~~~~int~neyn~=~iem~+~idyq~;\n\n~~~~~~~~~unsigned~int~ney~=~neyp~\\&~neyn~;\n\n~~~~~~~~~int~IndexAdd~=~ney~>\\,{}>~31~;\n\n~~~~~~~~~yr{[}q2{]}~=~a1~;\n\n~~~~~~~~~q2~+=~IndexAdd~;\n\n~~~~~~\\}~/{*}~endfor~{*}/\n\n~~~~~~/{*}\n\n~~~~~~~{*}~Slice~for~cube\n\n~~~~~~~{*}/\n\n~~~~~~int~zr{[}k\\_FragCount{]}~;\n\n~~~~~~int~q3~=~0~;\n\n~~~~~~for~(int~b2=0;~b2<q2;~b2+=1~)\n\n~~~~~~\\{\n\n~~~~~~~~~int~a2~=~yr{[}b2{]}~;\n\n~~~~~~~~~int~idz~=~aiz~-~iz{[}a2{]}~;\n\n~~~~~~~~~int~idzq~=~idz~>\\,{}>~k\\_ScaleShift~;~//~Difference~in~'z'\n\n~~~~~~~~~~~~~~~~~~~//~coordinate,~scaled~down~to~keep~away~from~overflows\n\n~~~~~~~~~int~iem~=~(-aiez)~-~iez{[}a2{]}~;\n\n~~~~~~~~~int~nezp~=~iem~-~idzq~;\n\n~~~~~~~~~int~nezn~=~iem~+~idzq~;\n\n~~~~~~~~~unsigned~int~nez~=~nezp~\\&~nezn~;\n\n~~~~~~~~~int~IndexAdd~=~nez~>\\,{}>~31~;\n\n~~~~~~~~~zr{[}q3{]}~=~a2~;\n\n~~~~~~~~~q3~+=~IndexAdd~;\n\n~~~~~~\\}~/{*}~endfor~{*}/\n\n~~~~~~/{*}\n\n~~~~~~~{*}~Examine~cuboid~for~sphere\n\n~~~~~~~{*}/\n\n~~~~~~int~q4~=~0~;\n\n~~~~~~double~x0=aXYZ.mX~;\n\n~~~~~~double~y0=aXYZ.mY~;\n\n~~~~~~double~z0=aXYZ.mZ~;\n\n~~~~~~double~px~=~p.mX~;\n\n~~~~~~double~py~=~p.mY~;\n\n~~~~~~double~pz~=~p.mZ~;\n\n~~~~~~double~kx~=~k.mX~;\n\n~~~~~~double~ky~=~k.mY~;\n\n~~~~~~double~kz~=~k.mZ~;\n\n~~~~~~for~(int~b3=0;~b3<q3~;~b3+=1)\n\n~~~~~~\\{\n\n~~~~~~~~~int~a3~=~zr{[}b3{]}~;\n\n~~~~~~~~~double~dx~=~NearestDistanceInFullyPeriodicLine(x0,x{[}a3{]},px,kx)~;\n\n~~~~~~~~~double~dy~=~NearestDistanceInFullyPeriodicLine(y0,y{[}a3{]},py,ky)~;\n\n~~~~~~~~~double~dz~=~NearestDistanceInFullyPeriodicLine(z0,z{[}a3{]},pz,kz)~;\n\n~~~~~~~~~double~em~=~e0~+~e{[}a3{]}~;\n\n~~~~~~~~~double~ex2~=~em{*}em~-~dx{*}dx~-~dy{*}dy~-~dz{*}dz~;\n\n~~~~~~~~~result{[}q4{]}~=~a3~;\n\n~~~~~~~~~double~FragmentIndexAdd~=~fsel(ex2,1.0,0.0)~;\n\n~~~~~~~~~int~IndexAdd~=~FragmentIndexAdd~;\n\n~~~~~~~~~q4~+=~IndexAdd~;\n\n~~~~~~\\}~/{*}~endfor~{*}/\n\n~~~~~~BegLogLine(~1~)\n\n~~~~~~~~<\\,{}<~\\char`\\\"{}NeighbourList::Produce~S~Summary\\char`\\\"{}\n\n~~~~~~~~<\\,{}<~\\char`\\\"{}~q4~\\char`\\\"{}~<\\,{}<~q4\n\n~~~~~~~~<\\,{}<~EndLogLine~;\n\n~~~~~~return~q4~;\n\n~~~~~\\}~;\n\n~~~void~SetXYZE(\n\n~~~~~~~int~q\n\n~~~~~,~const~XYZ\\&~aXYZ\n\n~~~~~,~double~ae\n\n~~~~~,~const~XYZ\\&~eXYZ\n\n~~~)~\\{\n\n~~~~~~~~x{[}q{]}~=~aXYZ.mX~;\n\n~~~~~~~~y{[}q{]}~=~aXYZ.mY~;\n\n~~~~~~~~z{[}q{]}~=~aXYZ.mZ~;\n\n~~~~~~~~ex{[}q{]}~=~eXYZ.mX~;\n\n~~~~~~~~ey{[}q{]}~=~eXYZ.mY~;\n\n~~~~~~~~ez{[}q{]}~=~eXYZ.mZ~;\n\n~~~~~~~~e{[}q{]}~=~ae;\n\n~~~~~~~~ix{[}q{]}~=~FracScale(aXYZ.mX,k.mX)~;\n\n~~~~~~~~iy{[}q{]}~=~FracScale(aXYZ.mY,k.mY)~;\n\n~~~~~~~~iz{[}q{]}~=~FracScale(aXYZ.mZ,k.mZ)~;\n\n~~~~~~~~iex{[}q{]}~=~FracScale(eXYZ.mX,k.mX/(1<\\,{}<k\\_ScaleShift))~;\n\n~~~~~~~~iey{[}q{]}~=~FracScale(eXYZ.mY,k.mY/(1<\\,{}<k\\_ScaleShift))~;\n\n~~~~~~~~iez{[}q{]}~=~FracScale(eXYZ.mZ,k.mZ/(1<\\,{}<k\\_ScaleShift))~;\n\n~~~~~~~~BegLogLine(~PKFXLOG\\_NSQSOURCEFRAG\\_SUMMARY~)\n\n~~~~~~~~~~<\\,{}<~\\char`\\\"{}NeighbourList::SetXYZE~q=\\char`\\\"{}~<\\,{}<~q\n\n~~~~~~~~~~<\\,{}<~\\char`\\\"{}~aXYZ=\\char`\\\"{}~<\\,{}<~aXYZ\n\n~~~~~~~~~~<\\,{}<~\\char`\\\"{}~ae=\\char`\\\"{}~<\\,{}<~ae\n\n~~~~~~~~~~<\\,{}<~\\char`\\\"{}~eXYZ=\\char`\\\"{}~<\\,{}<~eXYZ\n\n~~~~~~~~~~<\\,{}<~EndLogLine~;\n\n~~~~~~\\}~;\n\n~~~~double~GetFragmentExtent(int~q)~const\n\n~~~~\\{\n\n~~~~~~~return~e{[}q{]}~;\n\n~~~~\\}~;\n\n~~~~XYZ~GetCorner(int~q)~const\n\n~~~~\\{\n\n~~~~~~~XYZ~r~;\n\n~~~~~~~r.mX~=~ex{[}q{]}~;\n\n~~~~~~~r.mY~=~ey{[}q{]}~;\n\n~~~~~~~r.mZ~=~ez{[}q{]}~;\n\n~~~~~~~return~r~;\n\n~~~~\\}~;\n\n~~~~XYZ~GetFragmentCentre(int~q)~const\n\n~~~~\\{\n\n~~~~~~~XYZ~r~;\n\n~~~~~~~r.mX~=~x{[}q{]}~;\n\n~~~~~~~r.mY~=~y{[}q{]}~;\n\n~~~~~~~r.mZ~=~z{[}q{]}~;\n\n~~~~~~~return~r~;\n\n~~~~\\}~;\n\nint~Get(int~q)~const~\\{~return~result{[}q{]}~;~\\}~;\n\n\\}~;\n\n\n\\end{lyxcode}\n\\begin{thebibliography}{1}\n\\bibitem[1]{key-1}Handbook of Mathematical Functions (with Formulas, Graphs, and Mathematical\nTables), M. Abramowitz and I.A. Stegun, US Government 1972 , http://dlmf.nist.gov/\n\\bibitem[2]{key-2}Numerical Recipes in C, Press Teukolsky Vetterling and Flannery, Cambridge\nUniversity Press 1992, http://www.nr.com/\\printindex{}\n\\end{thebibliography}\n\n\\end{document}\n", "meta": {"hexsha": "2585fbfe23fad995d19da88d484cd7baf3fe9b17", "size": 141027, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "svntrunk/src/jrdmath/cust-math.tex", "max_stars_repo_name": "Bhaskers-Blu-Org1/BlueMatter", "max_stars_repo_head_hexsha": "1ab2c41af870c19e2e1b1095edd1d5c85eeb9b5e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-02-25T15:46:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T07:04:47.000Z", "max_issues_repo_path": "svntrunk/src/jrdmath/cust-math.tex", "max_issues_repo_name": "IBM/BlueMatter", "max_issues_repo_head_hexsha": "5243c0ef119e599fc3e9b7c4213ecfe837de59f3", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "svntrunk/src/jrdmath/cust-math.tex", "max_forks_repo_name": "IBM/BlueMatter", "max_forks_repo_head_hexsha": "5243c0ef119e599fc3e9b7c4213ecfe837de59f3", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-06-06T16:30:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-16T19:43:01.000Z", "avg_line_length": 23.2372713791, "max_line_length": 152, "alphanum_fraction": 0.5649769193, "num_tokens": 61887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.31602704632467554}}
{"text": "\n\\typeout{new file: New_Species_RadCal_Chapter.tex}\n\n\\chapter{The New Fuel Species in RadCal}\n\\label{chap:new_species}\n\nThe original RadCal data have been supplemented with new tabulated experimental data for the following fuels: Ethylene ($\\rm C_2H_4$), Ethane ($\\rm C_2H_6$), Propylene ($\\rm C_3H_6$), Propane ($\\rm C_3H_8$), Toluene ($\\rm C_7H_8$), \\textit{n}-Heptane ($\\rm C_7H_{16}$), Methanol ($\\rm CH_3OH$), Methyl Methacrylate ($\\rm C_5H_8O_2$). These new data have been obtained through Wakatsuki Fourier Transform Infra-Red (FTIR) measurements for wavenumbers between 700--4000~cm$\\rm ^{-1}$. See Ref.~\\cite{Wakatsuki2005b} for a detailed description of the experimental methodology.\n\nThe sections below briefly describe the molecules and their IR active molecular bands. Bands bounds used in RadCal are tabulated with a brief description of the band assignment and their integrated band intensity (see definition below) at the lowest temperature is also included. Unlike the data previously included in RadCal that contained a mix of tabulated and modeled data, the species data presented here in the chapter are all tabulated.\n\n\\section{Integrated band intensity}\n\\label{sec:integrated_intensity}\n\nA useful quantity to compare the relative importance of the different IR bands is provided by the integrated band intensity, $\\alpha_i$, defined for the $i$th participating species as:\n\\be\\label{eq:alpha}\n  \\alpha_i(T) = \\displaystyle\\int_{\\om_{\\min}}^{\\om_{\\max}} \\bar{\\kappa}_i(\\om',T) \\; \\d \\om'\n\\ee\nwhose units are $\\rm {atm^{-1} cm^{-2}}$. The integrated band intensity is an intrinsic property of a molecule directly related to its geometry, its elements, and the nature of the chemical bonds. It is proportional to the amplitude of the electric moment variations for a vibration-rotation transition \\cite{Matheson1932}. It is usually referred to as the coefficient $C_1$ in the exponential wide-band model.\n\nThe value of the spectral absorption coefficient, $\\bar{\\kappa}_i$, is averaged over a narrow band whose spectral width, $\\Delta \\om$, varies from 5~cm$^{-1}$ for $\\om < $ 1100~cm$^{-1}$, to 25~cm$^{-1}$ for 1100~cm$^{-1} \\leq \\om < $ 5000~cm$^{\\rm -1}$, and to 50~cm$^{\\rm -1}$ for 5000~cm$^{\\rm -1}\\leq \\om$. In the sections below, value were obtained by integrated the narrow band absorption coefficients over the band of interest.\n\n\\section{Fitting procedure}\n\nIn Section~\\ref{Sec::SNBM}, expressions for the Elsasser, Goody, and Malkmus narrow band models were presented, see Eqs.~\\ref{eq::Elsasser}, \\ref{eq::Goody}, and \\ref{eq::Malkmus}. Each gives a functional expression of the spectral transmissivity over narrow bands in the form:\n\\be\n \\bar{\\tau}_{\\omega} = f(\\bar{\\kappa}_{\\omega},\\beta_{\\omega},U),\n\\ee\nwhere the expression of $f$ depends on the model chosen; the pressure-path $U =  P_i L$ is known from the experimental configuration; the experimental spectral transmissivity $\\bar{\\tau}_{\\omega}$ is obtained by FTIR measurements; and the couple $\\bar{\\kappa}_{\\omega},\\beta_{\\omega}$ are the sought parameters. In the following, the subscript $_\\omega$ denoting the spectral dependence of the quantities is omitted for ease of reading.\n\nTo find the optimal narrow band model parameters for each model, at a given temperature and at a given wavenumber, a fitting objective function was minimized using a least-square fitting approach. The objective function $\\mathcal{F}$ was defined as:\n\\be\n \\mathcal{F}_i = \\dfrac{|\\bar{\\tau}_{exp,i}-f(\\bar{\\kappa},\\beta,U_i)|}{\\bar{\\tau}_{exp,i}},\n\\ee\nwhere the subscript $_{exp}$ denotes experimentally measured values, and $_i$ denotes an experimental condition of  pressure-path. The experimental transmissivity relative to the $i^{th}$ pressure-path is denoted $\\bar{\\tau}_{exp,i}$. This is an averaged value over the narrow band interval at the desired resolution. Typically three different pressure-paths were used for each temperature and fuel. The narrow band parameters $\\left(\\bar{\\kappa},\\beta\\right)$ hence found minimize the square of the \\textit{l}$\\rm ^2$-norm of the objective function $\\mathcal{F}$:\n\\be\n \\min\\limits_{\\left(\\bar{\\kappa},\\beta\\right)}\\|\\mathcal{F}\\|_2^2 = \\min\\limits_{\\left(\\bar{\\kappa},\\beta\\right)}\\left(\\displaystyle\\sum \\limits_i \\left(\\dfrac{\\bar{\\tau}_{exp,i}-f(\\bar{\\kappa},\\beta,U_i)}{\\bar{\\tau}_{exp,i}}\\right)^2\\right).\n\\ee\n\nThe spectral narrow band parameters were obtained for all the fuels presented in this section, for the three aforementioned narrow band models. As a verification test, the experimental transmissivities obtained were reconstructed using the narrow band models and compared with the measured values. For each experimental condition, very good agreements were observed between the synthetic and the experimental transmissivity profiles regardless of the narrow band model. No model stands out nor performs better than the other two.\n\nThe similar accuracy of three different narrow band models is likely a result of the small number of pressure-paths used to fit the data;  the fitted narrow-band parameters were obtained by fitting only three experimental pressure-paths. In previous works, the appropriate band narrow band model was selected based on the value of the model deviation from the experimental data, see Ref.~\\cite{Kunitomo1975}. This is an valid method as long as the experimental data has lower error than that associated with any narrow band models. Here, the experimental error associated with the mean absorption coefficient is 5\\% \\cite{Wakatsuki2008}, which is higher than the difference between experimental and synthetic data for each model.\n\nIt is customary to validate the choice of the assumed narrow band model or to derive its parameters from the knowledge of the integrated band intensities, $\\alpha$, defined by Eq.~\\ref{eq:alpha}. Experimentally, $\\alpha$ is computed from the extrapolation technique first proposed by Wilson and Wells \\cite{Wilson1946,Thorndike1947} and further explained in Penner~\\cite{Penner1959}. The technique is briefly recalled. A parameter $B$ is defined as:\n\\be\n B = \\dfrac{1}{P_iL} \\displaystyle\\int\\limits_{band} -\\ln(\\tau_{\\omega}) {\\rm d} \\omega.\n\\ee\nThe apparent integrated band intensity, $\\mathcal{A}$, defined as:\n\\be\n \\mathcal{A} = \\displaystyle\\int\\limits_{band}{-\\ln{\\tau_{\\omega}}} {\\rm d} \\omega\n\\ee\nrelates with $B$ through the relation:\n\\be\n\\label{eq:LineofGrowth}\n\\mathcal{A} = P_iL B.\n\\ee\nThe work by Wilson and Wells \\cite{Wilson1946,Thorndike1947} showed that the $\\alpha$ relates with the parameter $B$ through:\n\\be\n\\label{eq:Exp_alpha}\n \\alpha = \\lim\\limits_{P_iL\\rightarrow 0} B\n\\ee\n\nHence, the experimental value for $\\alpha$ can be obtained through extrapolation of $A$ to the origin and\nmeasuring the slope at the origin. While a direct extrapolation is not recommended as it may be subject to significant error as mentioned by Kaplan \\textit{et al.}, \\cite{Kaplan1956a}, a extrapolation using an educated curve-of-growth procedure \\cite{Kaplan1956a} can help alleviate this problem. The functional relation between the absorption and the pressure-path can be assumed to be a function of the unknown $\\alpha$ and some characteristic line width. Fitting the experimental data is required to obtain the unknown parameters and it provides a more rigorous evaluation of $\\alpha$.\n\nWhile a representative functional relation can be derived for a fundamental band, \\textit{i.e.} a band associated with only one vibration transition mode, it is more difficult to do so for bands that are the results of multiple vibration modes. This is the case for all the species presented here. Hence, no extrapolation was performed as they could lead to bias depending on the extrapolation method used. Instead, following comments presented in Modest~\\cite{Modest2013}, the Malkmus model was chosen as it is recognized as the best for polyatomic molecules. Verification tests for each species are presented in Section~\\ref{sec:verification}. Some of the data, ethane, ethylene, and propane, have been carefully examined and some species were compared with the HITRAN 2012 edition. See Lecoustre \\textit{et al.} \\cite{Lecoustre2014} for more details.\n\n\\clearpage\n\n\\section{Ethylene: $\\rm C_2H_4$}\n\n\\subsection{Integrated Band Intensity}\n\nEthylene, $\\rm C_2H_4$, is a plane symmetrical molecule and belongs to the point group $D_{2h}$. It has 12 vibrational modes. In RadCal, its IR spectrum is divided into four distinct bands that are associated with different vibrational modes, see Table \\ref{Table::C2H4}. The bands from 750 - 1250~cm$^{-1}$ and 1300 - 1600~cm$^{-1}$ are associated with the bending motion of the $\\rm CH_2$ groups. The band between 1750 and 2075~cm$^{-1}$ is associated with the stretching motion of the carbon double bond, $\\rm C=C$. The fourth band from 2800 - 3400~cm$^{-1}$ is associated with the stretching of the CH groups. The strongest absorption band is located at lower wavenumbers, between 780 and 1250~cm$^{-1}$. This indicates the propensity of ethylene to strong participation to the radiative heat exchange corresponding to low to moderate temperatures. This spectral range corresponds to the highest blackbody spectral emittance at temperatures ranging between 400 to 700~K which are characteristic of cooler regions of the fuel rich cores for liquid and solid fires.\n\\begin{table}[ht]\n    \\centering\n    \\caption{Spectral bands of $\\rm C_2H_4$ included in RadCal.}\n    \\vspace{0.1in}\n    \\label{Table::C2H4}\n    \\begin{tabular}{|c|c|c|c|c|}\n      \\hline\n      Band \\# & \\multicolumn{2}{|l|}{Bounds (cm$\\rm ^{-1}$) } & Assignment & $\\alpha(T=296 \\; {\\rm K}) \\; (\\rm {atm^{-1} cm^{-2}})$\\\\\n      \\cline{1-5}\n      1 & 750  & 1250 &  $\\rm CH_2$ Bend      & 371 \\\\\n      2 & 1300 & 1600 &  $\\rm CH_2$ Bend      & 42  \\\\\n      3 & 1750 & 2075 &  $\\rm C=C$  Stretch   & 20  \\\\\n      4 & 2800 & 3400 &  $\\rm C-H$  Stretch   & 198 \\\\\n      \\hline\n    \\end{tabular}\n\\end{table}\nBand~1 is the strongest absorbing band. All the ethylene IR spectral absorption data were obtained from high resolution FTIR experiments with temperatures varying from 296~K to 1000~K. See Wakatsuki \\cite{Wakatsuki2005b} for more details about the experimental process followed to obtain the experimental data.\n\n\\subsection{Malkmus Narrow Band Parameters}\n\nThe spectral absorption coefficients were obtained by least square fitting of the experimental transmissivity using the Malkmus model. The ethylene narrow band parameters, $\\bar{\\kappa}$ and $\\beta$, for temperatures ranging from 296~K to 1000~K are plotted in Figures~\\ref{fig:ethylene_kappa_beta1}--\\ref{fig:ethylene_kappa_beta4} for Bands 1 to 4.\n\n\\newpage\n\n\\begin{figure}[p]\n\\begin{center}\n\\includegraphics[width=5.0in]{Figures/Ethylene_Kappa_Band1_MALKMUS.pdf}\n\\includegraphics[width=5.0in]{Figures/Ethylene_Beta_Band1_MALKMUS.pdf}\n\\end{center}\n\\caption{Ethylene narrow band parameters $\\bar{\\kappa}$ and $\\beta$ obtained for the 750--1250~cm$^{-1}$ band corresponding to the bending motion of the $\\rm CH_2$ chemical group. Temperatures plotted are: 296, 400, 450, 500, 601, 801, and 1000~K. The narrow band resolution $\\Delta \\om$ is 5~cm$^{-1}$.\\label{fig:ethylene_kappa_beta1}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\begin{center}\n\\includegraphics[width=5.0in]{Figures/Ethylene_Kappa_Band2_MALKMUS.pdf}\n\\includegraphics[width=5.0in]{Figures/Ethylene_Beta_Band2_MALKMUS.pdf}\n\\end{center}\n\\caption{Ethylene narrow band parameters $\\bar{\\kappa}$ and $\\beta$ obtained for the 1300--1600~cm$^{-1}$ band corresponding to the bending motion of the $\\rm CH_2$ chemical group. Temperatures plotted are: 296, 400, 450, 500, 601, 801, and 1000~K. The narrow band resolution $\\Delta \\om$ is 25~cm$^{-1}$.\\label{fig:ethylene_kappa_beta2}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\begin{center}\n\\includegraphics[width=5.0in]{Figures/Ethylene_Kappa_Band3_MALKMUS.pdf}\n\\includegraphics[width=5.0in]{Figures/Ethylene_Beta_Band3_MALKMUS.pdf}\n\\end{center}\n\\caption{Ethylene narrow band parameters $\\bar{\\kappa}$ and $\\beta$ obtained for the 1750--2075~cm$^{-1}$ band corresponding to the stretching motion of the $\\rm C=C$ chemical group. Temperatures plotted are: 296, 400, 450, 500, 601, 801, and 1000~K. The narrow band resolution $\\Delta \\om$ is 25~cm$^{-1}$.\\label{fig:ethylene_kappa_beta3}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\begin{center}\n\\includegraphics[width=5.0in]{Figures/Ethylene_Kappa_Band4_MALKMUS.pdf}\n\\includegraphics[width=5.0in]{Figures/Ethylene_Beta_Band4_MALKMUS.pdf}\n\\end{center}\n\\caption{Ethylene narrow band parameters $\\bar{\\kappa}$ and $\\beta$ obtained for the 2800--3400~cm$^{-1}$ band corresponding to the stretching motion of the $\\rm C-H$ chemical group. Temperatures plotted are: 296, 400, 450, 500, 601, 801, and 1000~K. The narrow band resolution $\\Delta \\om$ is 25~cm$^{-1}$.\\label{fig:ethylene_kappa_beta4}}\n\\end{figure}\n\n\\FloatBarrier\n\n\\subsection{Verification SNB Parameters}\n\nTo assess the accuracy of the narrow band parameters $\\bar{\\kappa}$ and $\\beta$, synthetic transmissivities were constructed for the same experimental conditions as the FTIR data and compare with it. This subsection plots the comparison and the relative error in transmissivity (relative to FTIR measurements) using the ethylene parameters presented in Figs.~\\ref{fig:ethylene_kappa_beta1} to \\ref{fig:ethylene_kappa_beta4}.\n\n\n\\begin{figure}[!h]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Ethylene_MALKMUS_Temp296K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of ethylene. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:ethylene_kappa_beta1} to \\ref{fig:ethylene_kappa_beta4}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.304, 0.179 and 0.0782 atm.cm. The gas temperature is set at 296~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:ethylene_SNBVerify_296K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Ethylene_MALKMUS_Temp400K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of ethylene. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:ethylene_kappa_beta1} to \\ref{fig:ethylene_kappa_beta4}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.304, 0.179 and 0.0782 atm.cm. The gas temperature is set at 400~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:ethylene_SNBVerify_400K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Ethylene_MALKMUS_Temp450K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of ethylene. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:ethylene_kappa_beta1} to \\ref{fig:ethylene_kappa_beta4}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.304, 0.179 and 0.0782 atm.cm. The gas temperature is set at 450~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:ethylene_SNBVerify_450K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Ethylene_MALKMUS_Temp500K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of ethylene. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:ethylene_kappa_beta1} to \\ref{fig:ethylene_kappa_beta4}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.304, 0.179 and 0.0782 atm.cm. The gas temperature is set at 500~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:ethylene_SNBVerify_500K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Ethylene_MALKMUS_Temp601K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of ethylene. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:ethylene_kappa_beta1} to \\ref{fig:ethylene_kappa_beta4}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.304, 0.179 and 0.0782 atm.cm. The gas temperature is set at 601~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:ethylene_SNBVerify_601K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Ethylene_MALKMUS_Temp801K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of ethylene. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:ethylene_kappa_beta1} to \\ref{fig:ethylene_kappa_beta4}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.304, 0.179 and 0.0782 atm.cm. The gas temperature is set at 801~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:ethylene_SNBVerify_801K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Ethylene_MALKMUS_Temp1000K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of ethylene. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:ethylene_kappa_beta1} to \\ref{fig:ethylene_kappa_beta4}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.304, 0.179 and 0.0782 atm.cm. The gas temperature is set at 1000~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:ethylene_SNBVerify_1000K}}\n\\end{figure}\n\n\n\\clearpage\n\n\\section{Ethane: $\\rm C_2H_6$}\n\n\\subsection{Integrated Band Intensity}\n\nEthane, $\\rm C_2H_6$, has a three-fold axis of symmetry and belongs to the point group $D_{3d}$, \\cite{Herzberg1949}. Being a non-linear molecule, it has 18 vibrational modes, but due to its symmetry, some modes are identical, and the number of distinct vibrational modes is reduced to 12. In RadCal, its spectra are defined by 3 distinct bands associated with different vibrational modes, see Table \\ref{Table::C2H6}. The band from 730--1095~cm$^{-1}$ is associated with the rocking motion of the $\\rm CH_3$ groups, the band from 1250--1700~cm$^{-1}$ is associated with the bending motion of the CH groups, and the main band between 2550--3375~cm$^{-1}$ is associated with the stretching of the CH groups.\n\nThe CH stretching band located from 2550--3375~cm$^{-1}$ has the lowest transmissivity, \\textit{i.e.} highest absorption, and dominates absorption due to ethane for blackbody emissions at typical combustion temperatures between 1300~K and 1800~K, characteristic of sooting flames. At standard temperature and pressure, its integrated band intensity is more than 10 times the value of Band~2, and more than 20 times the value of Band~1.\n\n\\begin{table} [ht]\n    \\centering\n    \\caption{Spectral bands of $\\rm C_2H_6$ included in RadCal.}\n    \\vspace{0.1in}\n    \\label{Table::C2H6}\n    \\begin{tabular}{|c|c|c|c|c|}\n      \\hline\n      Band \\# & \\multicolumn{2}{|l|}{Bounds (cm$\\rm ^{-1}$) } & Assignment & $\\alpha(T=296 \\; {\\rm K}) \\; (\\rm {atm^{-1} cm^{-2}})$\\\\\n      \\cline{1-5}\n      1 & 730  & 1095 &  $\\rm CH_3$ Rock   &  30  \\\\\n      2 & 1250 & 1700 &  $\\rm CH$  Bend    &  64  \\\\\n      3 & 2550 & 3375 &  $\\rm CH$  Stretch &  774 \\\\\n      \\hline\n    \\end{tabular}\n\\end{table}\n\n\\subsection{Malkmus Narrow Band Parameters}\n\nAll the ethane IR spectral absorption data were obtained from high resolution FTIR experiments with temperatures varying from 296~K to 1000~K. The spectral absorption coefficients were obtained by fitting the experimental spectral transmissivity of a homogeneous column of isothermal ethane with a total pressure of 1~atm using the Malkmus model.\n\nThe ethane narrow band parameters, $\\bar{\\kappa}$ and $\\beta$, for temperatures ranging from 296~K to 1000~K are plotted in Figures~\\ref{fig:ethane_kappa_beta1}--\\ref{fig:ethane_kappa_beta3} for Bands 1 to 3.\n\n\\newpage\n\n\\begin{figure}[p]\n\\begin{center}\n\\includegraphics[width=5.0in]{Figures/Ethane_Kappa_Band1_MALKMUS.pdf}\n\\includegraphics[width=5.0in]{Figures/Ethane_Beta_Band1_MALKMUS.pdf}\n\\end{center}\n\\caption{Ethane narrow band parameters $\\bar{\\kappa}$ and $\\beta$ obtained for the 730--1095~cm$^{-1}$ band corresponding to the rocking motion of the $\\rm CH_3$ chemical group. Temperatures plotted are: 296, 400, 450, 500, 600, 800, and 1000~K. The narrow band resolution $\\Delta \\om$ is 5~cm$^{-1}$.\\label{fig:ethane_kappa_beta1}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\begin{center}\n\\includegraphics[width=5.0in]{Figures/Ethane_Kappa_Band2_MALKMUS.pdf}\n\\includegraphics[width=5.0in]{Figures/Ethane_Beta_Band2_MALKMUS.pdf}\n\\end{center}\n\\caption{Ethane narrow band parameters $\\bar{\\kappa}$ and $\\beta$ obtained for the 1250--1700~cm$^{-1}$ band corresponding to the bending motion of the $\\rm CH$ chemical group. Temperatures plotted are: 296, 400, 450, 500, 600, 800, and 1000~K. The narrow band resolution $\\Delta \\om$ is 25~cm$^{-1}$.\\label{fig:ethane_kappa_beta2}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\begin{center}\n\\includegraphics[width=5.0in]{Figures/Ethane_Kappa_Band3_MALKMUS.pdf}\n\\includegraphics[width=5.0in]{Figures/Ethane_Beta_Band3_MALKMUS.pdf}\n\\end{center}\n\\caption{Ethane narrow band parameters $\\bar{\\kappa}$ and $\\beta$ obtained for the 2550--3375~cm$^{-1}$ band corresponding to the stretching motion of the $\\rm C-H$ chemical group. Temperatures plotted are: 296, 400, 450, 500, 600, 800, and 1000~K. The narrow band resolution $\\Delta \\om$ is 25~cm$^{-1}$.\\label{fig:ethane_kappa_beta3}}\n\\end{figure}\n\n\\FloatBarrier\n\n\\subsection{Verification SNB Parameters}\n\nTo assess the accuracy of the narrow band parameters $\\bar{\\kappa}$ and $\\beta$, synthetic transmissivities were constructed for the same experimental conditions as the FTIR data and compare with it. This subsection plots the comparison and the relative error in transmissivity (relative to FTIR measurements) using the ethane parameters presented in Figs.~\\ref{fig:ethane_kappa_beta1} to \\ref{fig:ethane_kappa_beta3}.\n\n\\begin{figure}[!h]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Ethane_MALKMUS_Temp296K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of ethane. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:ethane_kappa_beta1} to \\ref{fig:ethane_kappa_beta3}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.338, 0.21 and 0.081 atm.cm. The gas temperature is set at 296~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:ethane_SNBVerify_296K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Ethane_MALKMUS_Temp400K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of ethane. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:ethane_kappa_beta1} to \\ref{fig:ethane_kappa_beta3}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.338, 0.21 and 0.081 atm.cm. The gas temperature is set at 400~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:ethane_SNBVerify_400K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Ethane_MALKMUS_Temp450K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of ethane. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:ethane_kappa_beta1} to \\ref{fig:ethane_kappa_beta3}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.338, 0.21 and 0.081 atm.cm. The gas temperature is set at 450~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:ethane_SNBVerify_450K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Ethane_MALKMUS_Temp500K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of ethane. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:ethane_kappa_beta1} to \\ref{fig:ethane_kappa_beta3}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.338, 0.21 and 0.081 atm.cm. The gas temperature is set at 500~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:ethane_SNBVerify_500K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Ethane_MALKMUS_Temp600K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of ethane. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:ethane_kappa_beta1} to \\ref{fig:ethane_kappa_beta3}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.338, 0.21 and 0.081 atm.cm. The gas temperature is set at 600~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:ethane_SNBVerify_600K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Ethane_MALKMUS_Temp800K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of ethane. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:ethane_kappa_beta1} to \\ref{fig:ethane_kappa_beta3}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.338, 0.21 and 0.081 atm.cm. The gas temperature is set at 800~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:ethane_SNBVerify_800K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Ethane_MALKMUS_Temp1000K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of ethane. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:ethane_kappa_beta1} to \\ref{fig:ethane_kappa_beta3}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.338, 0.21 and 0.081 atm.cm. The gas temperature is set at 1000~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:ethane_SNBVerify_1000K}}\n\\end{figure}\n\n\n\\clearpage\n\n\\section{Propylene: $\\rm C_3H_6$}\n\n\\subsection{Integrated Band Intensity}\n\nPropylene, $\\rm C_3H_6$, has only one plane of symmetry and belongs to the point group $C_s$, \\cite{Herzberg1949}. It has 21 vibrational modes. In RadCal, its spectrum is divided into three distinct bands, associated with different vibrational modes, see Table \\ref{Table::C3H6}. The first band from 775--1150~cm$^{-1}$ is associated with the stretching motion of the carbon simple bond $\\rm C-C$, the rocking motion of the $\\rm CH_3$ group, and the out-of-plane bending motion of the $\\rm = CH_2$ group. The second band from 1225--1975~cm$^{-1}$ is derived from the stretching motion of the carbon double bond $\\rm C=C$ and the bending motion of the CH group. Finally, the third band from 2650--3275~cm$^{-1}$ is due to the stretching motion of the CH and $\\rm = CH_2$ groups.\n\nThe strongest absorption bands for propylene are the 775--1150~cm$^{-1}$ (Band 1) and the 2650--3275~cm$^{-1}$ bands (Band 3). The 775--1150~cm$^{-1}$ band corresponds to radiation absorption and emission at near ambient temperature. The 2650--3275~cm$^{-1}$ band gives propylene strong absorption of radiation emitted by blackbody at high temperatures characteristic of sooting flames.\n\n\\begin{table}[ht]\n   \\centering\n   \\caption{Spectral bands of $\\rm C_3H_6$ included in RadCal.}\n   \\vspace{0.1in}\n   \\label{Table::C3H6}\n   \\begin{tabular}{|c|c|c|c|c|}\n    \\hline\n    Band \\# & \\multicolumn{2}{|l|}{Bounds (cm$\\rm ^{-1}$) } & Assignment & $\\alpha(T=296 \\; {\\rm K}) \\; (\\rm {atm^{-1} cm^{-2}})$\\\\\n    \\cline{1-5}\n    1 & 775  & 1150 &  $\\rm C-C$ Stretch, $\\rm CH_3$ Rock & 296 \\\\\n    2 & 1225 & 1975 &  $\\rm C=C$ Stretch, $\\rm CH$ Bend   & 271 \\\\\n    3 & 2650 & 3275 &  $\\rm CH$ \\& $\\rm CH_2$ Stretch      & 509 \\\\\n    \\hline\n   \\end{tabular}\n\\end{table}\n\n\\subsection{Malkmus Narrow Band Parameters}\n\nAll the propylene IR spectral absorption data were obtained from high resolution FTIR experiments with temperatures varying from 296~K to 1003~K. The spectral absorption coefficients were obtained by fitting the experimental spectral transmissivity of a homogeneous column of isothermal propylene with a total pressure of 1~atm using the Malkmus model.\n\nThe propylene narrow band parameters, $\\bar{\\kappa}$ and $\\beta$, for temperatures ranging from 296~K to 1003~K are plotted in Figures~\\ref{fig:propylene_kappa_beta1}--\\ref{fig:propylene_kappa_beta3} for Bands 1 to 3.\n\n\\newpage\n\n\\begin{figure}[p]\n\\begin{center}\n\\includegraphics[width=5.0in]{Figures/Propylene_Kappa_Band1_MALKMUS.pdf}\n\\includegraphics[width=5.0in]{Figures/Propylene_Beta_Band1_MALKMUS.pdf}\n\\end{center}\n\\caption{Propylene narrow band parameters $\\bar{\\kappa}$ and $\\beta$ obtained for the 775--1150~cm$^{-1}$ band corresponding to the rocking motion of the $\\rm CH_3$ chemical group. Temperatures plotted are: 296, 390, 444, 491, 594, 793, and 1003~K. The narrow band resolution $\\Delta \\om$ is 5~cm$^{-1}$.\\label{fig:propylene_kappa_beta1}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\begin{center}\n\\includegraphics[width=5.0in]{Figures/Propylene_Kappa_Band2_MALKMUS.pdf}\n\\includegraphics[width=5.0in]{Figures/Propylene_Beta_Band2_MALKMUS.pdf}\n\\end{center}\n\\caption{Propylene narrow band parameters $\\bar{\\kappa}$ and $\\beta$ obtained for the 1225--1975~cm$^{-1}$ band corresponding to the bending motion of the $\\rm CH$ chemical group. Temperatures plotted are: 296, 390, 444, 491, 594, 793, and 1003~K. The narrow band resolution $\\Delta \\om$ is 25~cm$^{-1}$.\\label{fig:propylene_kappa_beta2}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\begin{center}\n\\includegraphics[width=5.0in]{Figures/Propylene_Kappa_Band3_MALKMUS.pdf}\n\\includegraphics[width=5.0in]{Figures/Propylene_Beta_Band3_MALKMUS.pdf}\n\\end{center}\n\\caption{Propylene narrow band parameters $\\bar{\\kappa}$ and $\\beta$ obtained for the 2650--3275~cm$^{-1}$ band corresponding to the stretching motion of the $\\rm C-H$ chemical group. Temperatures plotted are: 296, 390, 444, 491, 594, 793, and 1003~K. The narrow band resolution $\\Delta \\om$ is 25~cm$^{-1}$.\\label{fig:propylene_kappa_beta3}}\n\\end{figure}\n\n\\FloatBarrier\n\n\\subsection{Verification SNB Parameters}\n\nTo assess the accuracy of the narrow band parameters $\\bar{\\kappa}$ and $\\beta$, synthetic transmissivities were constructed for the same experimental conditions as the FTIR data and compare with it. This subsection plots the comparison and the relative error in transmissivity (relative to FTIR measurements) using the propylene parameters presented in Figs.~\\ref{fig:propylene_kappa_beta1} to \\ref{fig:propylene_kappa_beta3}.\n\n\\begin{figure}[!h]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Propylene_MALKMUS_Temp296K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of propylene. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:propylene_kappa_beta1} to \\ref{fig:propylene_kappa_beta3}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.475, 0.316 and 0.158 atm.cm. The gas temperature is set at 296~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:propylene_SNBVerify_296K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Propylene_MALKMUS_Temp390K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of propylene. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:propylene_kappa_beta1} to \\ref{fig:propylene_kappa_beta3}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.475, 0.316 and 0.158 atm.cm. The gas temperature is set at 390~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:propylene_SNBVerify_390K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Propylene_MALKMUS_Temp444K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of propylene. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:propylene_kappa_beta1} to \\ref{fig:propylene_kappa_beta3}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.475, 0.316 and 0.158 atm.cm. The gas temperature is set at 444~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:propylene_SNBVerify_444K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Propylene_MALKMUS_Temp491K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of propylene. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:propylene_kappa_beta1} to \\ref{fig:propylene_kappa_beta3}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.475, 0.316 and 0.158 atm.cm. The gas temperature is set at 491~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:propylene_SNBVerify_491K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Propylene_MALKMUS_Temp594K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of propylene. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:propylene_kappa_beta1} to \\ref{fig:propylene_kappa_beta3}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.475, 0.316 and 0.158 atm.cm. The gas temperature is set at 594~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:propylene_SNBVerify_594K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Propylene_MALKMUS_Temp793K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of propylene. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:propylene_kappa_beta1} to \\ref{fig:propylene_kappa_beta3}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.475, 0.316 and 0.158 atm.cm. The gas temperature is set at 793~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:propylene_SNBVerify_793K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Propylene_MALKMUS_Temp1003K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of propylene. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:propylene_kappa_beta1} to \\ref{fig:propylene_kappa_beta3}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.475, 0.316 and 0.158 atm.cm. The gas temperature is set at 1003~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:propylene_SNBVerify_1003K}}\n\\end{figure}\n\n\n\\clearpage\n\n\\section{Propane: $\\rm C_3H_8$}\n\n\\subsection{Integrated Band Intensity}\n\nPropane, $\\rm C_3H_8$, has two planes of symmetry and two axes of rotation and belongs to the point group $C_{2v}$ \\cite{Herzberg1949}. It has 27 vibrational modes. In RadCal, its spectrum is divided into two distinct bands, associated with different vibrational modes, see Table \\ref{Table::C3H8}. The propane IR spectrum is the result of the vibration-rotation modes of the $\\rm C-C$, $\\rm CH_2$, $\\rm CH_3$ groups.\nThe first band from 1175--1675~cm$\\rm ^{-1}$ is associated with the bending motion of the $\\rm CH_3$ chemical group. The second band from 2550--3375~cm$\\rm ^{-1}$ is associated with the stretching motion of the chemical groups $\\rm CH_3$ and $\\rm CH_2$. It is the strongest band; its integrated band intensity is about 10 times that of the 1175--1675~cm$\\rm ^{-1}$ band.\n\n\\begin{table}[ht]\n   \\centering\n   \\caption{Spectral bands of $\\rm C_3H_8$ included in RadCal.}\n   \\vspace{0.1in}\n   \\label{Table::C3H8}\n   \\begin{tabular}{|c|c|c|c|c|}\n    \\hline\n    Band \\# & \\multicolumn{2}{|l|}{Bounds (cm$\\rm ^{-1}$) } & Assignment & $\\alpha(T=295 \\; {\\rm K}) \\; (\\rm {atm^{-1} cm^{-2}})$ \\\\\n    \\cline{1-5}\n    1 & 1175 & 1675 &  $\\rm CH_3$ Bending        & 122 \\\\\n    2 & 2550 & 3375 &  $\\rm CH_3, CH_2$ Stretch  & 1191 \\\\\n    \\hline\n   \\end{tabular}\n\\end{table}\n\n\\subsection{Malkmus Narrow Band Parameters}\n\nAll the propane IR spectral absorption data were obtained from high resolution FTIR experiments with temperatures varying from 295~K to 1009~K. The spectral absorption coefficients were obtained by fitting the experimental spectral transmissivity of a homogeneous column of isothermal propane with a total pressure of 1~atm using the Malkmus model.\n\nThe propane narrow band parameters, $\\bar{\\kappa}$ and $\\beta$, for temperatures ranging from 295~K to 1009~K are plotted in Figures~\\ref{fig:propane_kappa_beta1}--\\ref{fig:propane_kappa_beta2} for Bands 1 to 2.\n\n\\newpage\n\n\\begin{figure}[p]\n\\begin{center}\n\\includegraphics[width=5.0in]{Figures/Propane_Kappa_Band1_MALKMUS.pdf}\n\\includegraphics[width=5.0in]{Figures/Propane_Beta_Band1_MALKMUS.pdf}\n\\end{center}\n\\caption{Propane narrow band parameters $\\bar{\\kappa}$ and $\\beta$ obtained for the 1175--1675~cm$^{-1}$ band corresponding to the bending motion of the $\\rm CH_3$ chemical group. Temperatures plotted are: 295, 396, 435, 513, 578, 790, and 1009~K. The narrow band resolution $\\Delta \\om$ is 5~cm$^{-1}$.\\label{fig:propane_kappa_beta1}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\begin{center}\n\\includegraphics[width=5.0in]{Figures/Propane_Kappa_Band2_MALKMUS.pdf}\n\\includegraphics[width=5.0in]{Figures/Propane_Beta_Band2_MALKMUS.pdf}\n\\end{center}\n\\caption{Propane narrow band parameters $\\bar{\\kappa}$ and $\\beta$ obtained for the 2550--3375~cm$^{-1}$ band corresponding to the bending motion of the $\\rm CH$ chemical group. Temperatures plotted are: 295, 396, 435, 513, 578, 790, and 1009~K. The narrow band resolution $\\Delta \\om$ is 25~cm$^{-1}$.\\label{fig:propane_kappa_beta2}}\n\\end{figure}\n\n\\FloatBarrier\n\n\\subsection{Verification SNB Parameters}\n\nTo assess the accuracy of the narrow band parameters $\\bar{\\kappa}$ and $\\beta$, synthetic transmissivities were constructed for the same experimental conditions as the FTIR data and compare with it. This subsection plots the comparison and the relative error in transmissivity (relative to FTIR measurements) using the propane parameters presented in Figs.~\\ref{fig:propane_kappa_beta1} to \\ref{fig:propane_kappa_beta2}.\n\n\\begin{figure}[!h]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Propane_MALKMUS_Temp295K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of propane. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:propane_kappa_beta1} to \\ref{fig:propane_kappa_beta2}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.127, 0.0791 and 0.0316 atm.cm. The gas temperature is set at 295~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:propane_SNBVerify_295K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Propane_MALKMUS_Temp396K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of propane. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:propane_kappa_beta1} to \\ref{fig:propane_kappa_beta2}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.127, 0.0791 and 0.0316 atm.cm. The gas temperature is set at 396~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:propane_SNBVerify_396K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Propane_MALKMUS_Temp435K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of propane. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:propane_kappa_beta1} to \\ref{fig:propane_kappa_beta2}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.127, 0.0791 and 0.0316 atm.cm. The gas temperature is set at 435~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:propane_SNBVerify_435K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Propane_MALKMUS_Temp513K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of propane. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:propane_kappa_beta1} to \\ref{fig:propane_kappa_beta2}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.127, 0.0791 and 0.0316 atm.cm. The gas temperature is set at 513~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:propane_SNBVerify_513K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Propane_MALKMUS_Temp578K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of propane. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:propane_kappa_beta1} to \\ref{fig:propane_kappa_beta2}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.127, 0.0791 and 0.0316 atm.cm. The gas temperature is set at 578~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:propane_SNBVerify_578K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Propane_MALKMUS_Temp790K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of propane. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:propane_kappa_beta1} to \\ref{fig:propane_kappa_beta2}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.127, 0.0791 and 0.0316 atm.cm. The gas temperature is set at 790~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:propane_SNBVerify_790K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Propane_MALKMUS_Temp1009K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of propane. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:propane_kappa_beta1} to \\ref{fig:propane_kappa_beta2}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.127, 0.0791 and 0.0316 atm.cm. The gas temperature is set at 1009~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:propane_SNBVerify_1009K}}\n\\end{figure}\n\n\n\\clearpage\n\n\\section{Toluene: $\\rm C_7H_8$}\n\n\\subsection{Integrated Band Intensity}\n\nToluene, $\\rm C_7H_8$, has only one plane of symmetry; it belongs to the point group $C_{s}$~\\cite{Herzberg1949}. Its IR spectrum is the result of the vibration-rotation modes of the $\\rm C=C$, $\\rm CH$, and $\\rm CH_3$ groups. It has 39 vibrational modes. In RadCal, its IR spectrum has been divided into five distinct bands. The first band from 700--805~cm$\\rm^{-1}$ is associated with the bending motion of the $\\rm CH$ chemical group. The second band from 975--1175~cm$\\rm^{-1}$ is associated with the bending motion of the $\\rm CH$ chemical group. The third band from 1275--1650~cm$\\rm^{-1}$ is associated with the bending motion of the $\\rm CH_3$ chemical group. The fourth band from 1650--2075~cm$\\rm^{-1}$ is associated with the stretching motion of the $\\rm C=C$ chemical group. The fifth band from 2675--3225~cm$\\rm^{-1}$ is associated with the stretching motion of the $\\rm CH_3$ and $\\rm CH$ chemical groups. The first and fifth bands have the highest integrated band intensity. See Table \\ref{Table::C7H8}.\n\\begin{table}[ht]\n   \\centering\n   \\caption{Spectral bands of $\\rm C_7H_8$ included in RadCal.}\n   \\vspace{0.1in}\n   \\label{Table::C7H8}\n   \\begin{tabular}{|c|c|c|c|c|}\n    \\hline\n    Band \\# & \\multicolumn{2}{|l|}{Bounds (cm$\\rm ^{-1}$) } & Assignment & $\\alpha(T=300 \\; {\\rm K}) \\; (\\rm {atm^{-1} cm^{-2}})$\\\\\n    \\cline{1-5}\n    1 & 700  & 805  &  $\\rm CH$ Bending      & 234 \\\\\n    2 & 975  & 1175 &  $\\rm CH$ Bending      & 40  \\\\\n    3 & 1275 & 1650 &  $\\rm CH_3$ Bending    & 166 \\\\\n    4 & 1650 & 2075 &  $\\rm C=C$ Stretching  & 205 \\\\\n    5 & 2675 & 3225 &  $\\rm CH_3$, $\\rm CH$  Stretching & 507  \\\\\n    \\hline\n   \\end{tabular}\n\\end{table}\n\n\\subsection{Malkmus Narrow Band Parameters}\n\nAll the toluene IR spectral absorption data were obtained from high resolution FTIR experiments with temperatures varying from 300~K to 999~K. The spectral absorption coefficients were obtained by fitting the experimental spectral transmissivity of a homogeneous column of isothermal toluene with a total pressure of 1~atm using the Malkmus model.\n\nThe toluene narrow band parameters, $\\bar{\\kappa}$ and $\\beta$, for temperatures ranging from 300~K to 999~K are plotted in Figures~\\ref{fig:toluene_kappa_beta1}--\\ref{fig:toluene_kappa_beta5} for Bands 1 to 5.\n\n\\newpage\n\n\\begin{figure}[p]\n\\begin{center}\n\\includegraphics[width=5.0in]{Figures/Toluene_Kappa_Band1_MALKMUS.pdf}\n\\includegraphics[width=5.0in]{Figures/Toluene_Beta_Band1_MALKMUS.pdf}\n\\end{center}\n\\caption{Toluene narrow band parameters $\\bar{\\kappa}$ and $\\beta$ obtained for the 700--805~cm$^{-1}$ band corresponding to the bending motion of the $\\rm CH$ chemical group. Temperatures plotted are: 300, 396, 440, 477, 587, 795, and 999~K. The narrow band resolution $\\Delta \\om$ is 5~cm$^{-1}$.\\label{fig:toluene_kappa_beta1}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\begin{center}\n\\includegraphics[width=5.0in]{Figures/Toluene_Kappa_Band2_MALKMUS.pdf}\n\\includegraphics[width=5.0in]{Figures/Toluene_Beta_Band2_MALKMUS.pdf}\n\\end{center}\n\\caption{Toluene narrow band parameters $\\bar{\\kappa}$ and $\\beta$ obtained for the 975--1175~cm$^{-1}$ band corresponding to the bending motion of the $\\rm CH$ chemical group. Temperatures plotted are: 300, 396, 440, 477, 587, 795, and 999~K. The narrow band resolution $\\Delta \\om$ is 5~cm$^{-1}$.\\label{fig:toluene_kappa_beta2}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\begin{center}\n\\includegraphics[width=5.0in]{Figures/Toluene_Kappa_Band3_MALKMUS.pdf}\n\\includegraphics[width=5.0in]{Figures/Toluene_Beta_Band3_MALKMUS.pdf}\n\\end{center}\n\\caption{Toluene narrow band parameters $\\bar{\\kappa}$ and $\\beta$ obtained for the 1275--1650~cm$^{-1}$ band corresponding to the bending motion of the $\\rm CH_3$ chemical group. Temperatures plotted are: 300, 396, 440, 477, 587, 795, and 999~K. The narrow band resolution $\\Delta \\om$ is 25~cm$^{-1}$.\\label{fig:toluene_kappa_beta3}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\begin{center}\n\\includegraphics[width=5.0in]{Figures/Toluene_Kappa_Band4_MALKMUS.pdf}\n\\includegraphics[width=5.0in]{Figures/Toluene_Beta_Band4_MALKMUS.pdf}\n\\end{center}\n\\caption{Toluene narrow band parameters $\\bar{\\kappa}$ and $\\beta$ obtained for the 1650--2075~cm$^{-1}$ band corresponding to the stretching motion of the $\\rm C=C$ chemical group. Temperatures plotted are: 300, 396, 440, 477, 587, 795, and 999~K. The narrow band resolution $\\Delta \\om$ is 25~cm$^{-1}$.\\label{fig:toluene_kappa_beta4}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\begin{center}\n\\includegraphics[width=5.0in]{Figures/Toluene_Kappa_Band5_MALKMUS.pdf}\n\\includegraphics[width=5.0in]{Figures/Toluene_Beta_Band5_MALKMUS.pdf}\n\\end{center}\n\\caption{Toluene narrow band parameters $\\bar{\\kappa}$ and $\\beta$ obtained for the 2675--3225~cm$^{-1}$ band corresponding to the bending motion of the $\\rm CH_3$ and $\\rm CH$ chemical groups. Temperatures plotted are: 300, 396, 440, 477, 587, 795, and 999~K. The narrow band resolution $\\Delta \\om$ is 25~cm$^{-1}$.\\label{fig:toluene_kappa_beta5}}\n\\end{figure}\n\n\\FloatBarrier\n\n\\subsection{Verification SNB Parameters}\n\nTo assess the accuracy of the narrow band parameters $\\bar{\\kappa}$ and $\\beta$, synthetic transmissivities were constructed for the same experimental conditions as the FTIR data and compare with it. This subsection plots the comparison and the relative error in transmissivity (relative to FTIR measurements) using the toluene parameters presented in Figs.~\\ref{fig:toluene_kappa_beta1} to \\ref{fig:toluene_kappa_beta5}.\n\n\\begin{figure}[!h]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Toluene_MALKMUS_Temp300K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of toluene. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:toluene_kappa_beta1} to \\ref{fig:toluene_kappa_beta5}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.135, 0.101 and 0.0806 atm.cm. The gas temperature is set at 300~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:toluene_SNBVerify_300K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Toluene_MALKMUS_Temp396K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of toluene. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:toluene_kappa_beta1} to \\ref{fig:toluene_kappa_beta5}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.124, 0.0956 and 0.0808 atm.cm. The gas temperature is set at 396~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:toluene_SNBVerify_396K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Toluene_MALKMUS_Temp440K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of toluene. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:toluene_kappa_beta1} to \\ref{fig:toluene_kappa_beta5}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered:0.109, 0.0844 and 0.0741. The gas temperature is set at 440~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:toluene_SNBVerify_440K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Toluene_MALKMUS_Temp477K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of toluene. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:toluene_kappa_beta1} to \\ref{fig:toluene_kappa_beta5}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.125, 0.096 and 0.0828 atm.cm. The gas temperature is set at 477~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:toluene_SNBVerify_477K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Toluene_MALKMUS_Temp587K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of toluene. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:toluene_kappa_beta1} to \\ref{fig:toluene_kappa_beta5}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.118, 0.0958 and 0.0809 atm.cm. The gas temperature is set at 587~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:toluene_SNBVerify_587K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Toluene_MALKMUS_Temp795K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of toluene. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:toluene_kappa_beta1} to \\ref{fig:toluene_kappa_beta5}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.127, 0.0963 and 0.0831 atm.cm. The gas temperature is set at 795~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:toluene_SNBVerify_795K}}\n\\end{figure}\n\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Toluene_MALKMUS_Temp999K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of toluene. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:toluene_kappa_beta1} to \\ref{fig:toluene_kappa_beta5}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.138, 0.103 and 0.0893 atm.cm. The gas temperature is set at 999~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:toluene_SNBVerify_999K}}\n\\end{figure}\n\n\n\\clearpage\n\n\\section{\\textit{n}-Heptane: $\\rm C_7H_{16}$}\n\n\\subsection{Integrated Band Intensity}\n\n\\textit{n}-heptane, $\\rm C_7H_16$, has two planes of symmetry and two axes of rotation. It belongs to the point group $C_{2v}$~\\cite{Herzberg1949}. The \\textit{n}-heptane IR spectrum results from the vibration-rotation modes of the $\\rm C-C$, $\\rm CH_2$, and $\\rm CH_3$ groups. It has 63 vibrational modes. In RadCal, its IR spectrum has been divided into two distinct bands. The first band from 1100--1800~cm$\\rm^{-1}$ is associated with the bending motion of the $\\rm CH_2$ and $\\rm CH_3$ chemical groups. The second band from 2250--3275~cm$\\rm^{-1}$ is associated with the stretching motion of the $\\rm CH_2$ and $\\rm CH_3$ chemical groups. This band has the highest integrated band intensity. Its value is more than 10 times that of the first band, see Table \\ref{Table::C7H16}.\n\\begin{table}[ht]\n   \\centering\n   \\caption{Spectral bands of $\\rm C_7H_{16}$ included in RadCal.}\n   \\vspace{0.1in}\n   \\label{Table::C7H16}\n   \\begin{tabular}{|c|c|c|c|c|}\n    \\hline\n    Band \\# & \\multicolumn{2}{|l|}{Bounds (cm$\\rm ^{-1}$) } & Assignment & $\\alpha(T=293 \\; {\\rm K}) \\; (\\rm {atm^{-1} cm^{-2}})$\\\\\n    \\cline{1-5}\n    1 & 1100  & 1800 &  $\\rm CH_2, CH_3$ Bending    & 304 \\\\\n    2 & 2250  & 3275 &  $\\rm CH_2, CH_3$ Stretching & 3165 \\\\\n    \\hline\n   \\end{tabular}\n\\end{table}\n\n\\subsection{Malkmus Narrow Band Parameters}\n\nAll the \\textit{n}-heptane IR spectral absorption data were obtained from high resolution FTIR experiments with temperatures varying from 293~K to 794~K. The spectral absorption coefficients were obtained by fitting the experimental spectral transmissivity of a homogeneous column of isothermal \\textit{n}-heptane with a total pressure of 1~atm using the Malkmus model.\n\nThe \\textit{n}-heptane narrow band parameters, $\\bar{\\kappa}$ and $\\beta$, for temperatures ranging from 293~K to 1000~K are plotted in Figures~\\ref{fig:nheptane_kappa_beta1}--\\ref{fig:nheptane_kappa_beta2} for Bands 1 and 2.\n\n\\newpage\n\n\\begin{figure}[p]\n\\begin{center}\n\\includegraphics[width=5.0in]{Figures/Heptane_Kappa_Band1_MALKMUS.pdf}\n\\includegraphics[width=5.0in]{Figures/Heptane_Beta_Band1_MALKMUS.pdf}\n\\end{center}\n\\caption{\\textit{n}-heptane narrow band parameters $\\bar{\\kappa}$ and $\\beta$ obtained for the 1100--1800~cm$^{-1}$ band corresponding to the bending motion of the $\\rm CH_2$ and $\\rm CH_3$ chemical groups. Temperatures plotted are: 293, 400, 450, 490, 593, 794, and 1000~K. The narrow band resolution $\\Delta \\om$ is 25~cm$^{-1}$.\\label{fig:nheptane_kappa_beta1}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\begin{center}\n\\includegraphics[width=5.0in]{Figures/Heptane_Kappa_Band2_MALKMUS.pdf}\n\\includegraphics[width=5.0in]{Figures/Heptane_Beta_Band2_MALKMUS.pdf}\n\\end{center}\n\\caption{\\textit{n}-heptane narrow band parameters $\\bar{\\kappa}$ and $\\beta$ obtained for the 2250--3275~cm$^{-1}$ band corresponding to the stretching motion of the $\\rm CH_2$ and $\\rm CH_3$ chemical groups. Temperatures plotted are: 293, 400, 450, 490, 593, 794, and 1000~K. The narrow band resolution $\\Delta \\om$ is 25~cm$^{-1}$.\\label{fig:nheptane_kappa_beta2}}\n\\end{figure}\n\n\\FloatBarrier\n\n\\subsection{Verification SNB Parameters}\n\nTo assess the accuracy of the narrow band parameters $\\bar{\\kappa}$ and $\\beta$, synthetic transmissivities were constructed for the same experimental conditions as the FTIR data and compare with it. This subsection plots the comparison and the relative error in transmissivity (relative to FTIR measurements) using the \\textit{n}-heptane parameters presented in Figs.~\\ref{fig:nheptane_kappa_beta1} to \\ref{fig:nheptane_kappa_beta2}.\n\n\\begin{figure}[!h]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Heptane_MALKMUS_Temp293K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of \\textit{n}-heptane. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:nheptane_kappa_beta1} to \\ref{fig:nheptane_kappa_beta2}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.0492, 0.0312 and 0.015 atm.cm. The gas temperature is set at 293~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:nheptane_SNBVerify_293K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Heptane_MALKMUS_Temp400K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of \\textit{n}-heptane. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:nheptane_kappa_beta1} to \\ref{fig:nheptane_kappa_beta2}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.0475, 0.0301 and 0.0145 atm.cm. The gas temperature is set at 400~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:nheptane_SNBVerify_400K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Heptane_MALKMUS_Temp450K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of \\textit{n}-heptane. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:nheptane_kappa_beta1} to \\ref{fig:nheptane_kappa_beta2}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered:0.0495, 0.0311 and 0.0152. The gas temperature is set at 450~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:nheptane_SNBVerify_450K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Heptane_MALKMUS_Temp490K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of \\textit{n}-heptane. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:nheptane_kappa_beta1} to \\ref{fig:nheptane_kappa_beta2}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.0494, 0.0305 and 0.015 atm.cm. The gas temperature is set at 490~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:nheptane_SNBVerify_490K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Heptane_MALKMUS_Temp593K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of \\textit{n}-heptane. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:nheptane_kappa_beta1} to \\ref{fig:nheptane_kappa_beta2}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.0503, 0.0314 and 0.0152 atm.cm. The gas temperature is set at 593~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:nheptane_SNBVerify_593K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Heptane_MALKMUS_Temp794K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of \\textit{n}-heptane. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:nheptane_kappa_beta1} to \\ref{fig:nheptane_kappa_beta2}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.044, 0.0301, and 0.0148 atm.cm. The gas temperature is set at 794~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:nheptane_SNBVerify_794K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Heptane_MALKMUS_Temp1000K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of \\textit{n}-heptane. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:nheptane_kappa_beta1} to \\ref{fig:nheptane_kappa_beta2}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.0364, 0.0307 and 0.0173 atm.cm. The gas temperature is set at 1000~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:nheptane_SNBVerify_1000K}}\n\\end{figure}\n\n\n\\clearpage\n\n\\section{Methanol: $\\rm CH_3OH$}\n\n\\subsection{Integrated Band Intensity}\n\nMethanol, $\\rm CH_3OH$, has only one plane of symmetry. It belongs to the point group $C_{s}$~\\cite{Herzberg1949}. Its IR spectrum results from the vibration-rotation modes of the $\\rm C-O$, $\\rm OH$, and $\\rm CH_3$ groups. It has 12 vibrational modes. In RadCal, its IR spectrum has been divided into four distinct bands. The first band from 825--1125~cm$\\rm^{-1}$ is associated with the stretching motion of the $\\rm C-O$ chemical group. The second band from 1125--1700~cm$^{-1}$ is associated with the bending motion of the $\\rm CH_3$ and $\\rm OH$ chemical groups. The third band from 2600--3225~cm$\\rm^{-1}$ is associated with the stretching motion of the $\\rm CH_3$ chemical group. The fourth and last band from 3525--3850~cm$\\rm^{-1}$ is associated with the stretching motion of the $\\rm OH$ chemical group. The strongest absorbing bands are the third band (2600--3225~cm$\\rm^{-1}$) and the first band (825--1125~cm$\\rm^{-1}$). See Table \\ref{Table::CH3OH}.\n\\begin{table}[ht]\n   \\centering\n   \\caption{Spectral bands of $\\rm CH_3OH$ included in RadCal.}\n   \\vspace{0.1in}\n   \\label{Table::CH3OH}\n   \\begin{tabular}{|c|c|c|c|c|}\n    \\hline\n    Band \\# & \\multicolumn{2}{|l|}{Bounds (cm$\\rm ^{-1}$) } & Assignment &  $\\alpha(T=293 \\; {\\rm K}) \\; (\\rm {atm^{-1} cm^{-2}})$ \\\\\n    \\cline{1-5}\n    1 & 825  & 1125 & $\\rm C-O$ Stretching   & 598 \\\\\n    2 & 1125 & 1700 & $\\rm CH_3, OH$ Bending & 199 \\\\\n    3 & 2600 & 3225 & $\\rm CH_3$ Stretching  & 680 \\\\\n    4 & 3525 & 3850 & $\\rm OH$ Stretching    & 112 \\\\\n    \\hline\n   \\end{tabular}\n\\end{table}\n\n\\subsection{Malkmus Narrow Band Parameters}\n\nAll the methanol IR spectral absorption data were obtained from high resolution FTIR experiments with temperatures varying from 293~K to 804~K. The spectral absorption coefficients were obtained by fitting the experimental spectral transmissivity of a homogeneous column of isothermal methanol with a total pressure of 1~atm using the Malkmus model.\n\nThe methanol narrow band parameters, $\\bar{\\kappa}$ and $\\beta$, for temperatures ranging from 293~K to 1000~K are plotted in Figures~\\ref{fig:methanol_kappa_beta1}--\\ref{fig:methanol_kappa_beta4} for Bands 1 to 4.\n\n\\newpage\n\n\\begin{figure}[p]\n\\begin{center}\n\\includegraphics[width=5.0in]{Figures/Methanol_Kappa_Band1_MALKMUS.pdf}\n\\includegraphics[width=5.0in]{Figures/Methanol_Beta_Band1_MALKMUS.pdf}\n\\end{center}\n\\caption{Methanol narrow band parameters $\\bar{\\kappa}$ and $\\beta$ obtained for the 825--1125~cm$^{-1}$ band corresponding to the stretching motion of the $\\rm C-O$ chemical group. Temperatures plotted are: 293, 396, 443, 483, 570, 804, and 1000~K. The narrow band resolution $\\Delta \\om$ is 5~cm$^{-1}$.\\label{fig:methanol_kappa_beta1}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\begin{center}\n\\includegraphics[width=5.0in]{Figures/Methanol_Kappa_Band2_MALKMUS.pdf}\n\\includegraphics[width=5.0in]{Figures/Methanol_Beta_Band2_MALKMUS.pdf}\n\\end{center}\n\\caption{Methanol narrow band parameters $\\bar{\\kappa}$ and $\\beta$ obtained for the 1125--1700~cm$^{-1}$ band corresponding to the bending motion of the $\\rm CH_3$ and $\\rm OH$ chemical groups. Temperatures plotted are: 293, 396, 443, 483, 570, 804, and 1000~K. The narrow band resolution $\\Delta \\om$ is 25~cm$^{-1}$.\\label{fig:methanol_kappa_beta2}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\begin{center}\n\\includegraphics[width=5.0in]{Figures/Methanol_Kappa_Band3_MALKMUS.pdf}\n\\includegraphics[width=5.0in]{Figures/Methanol_Beta_Band3_MALKMUS.pdf}\n\\end{center}\n\\caption{Methanol narrow band parameters $\\bar{\\kappa}$ and $\\beta$ obtained for the 2600--3225~cm$^{-1}$ band corresponding to the stretching motion of the $\\rm CH_3$ chemical groups. Temperatures plotted are: 293, 396, 443, 483, 570, 804, and 1000~K. The narrow band resolution $\\Delta \\om$ is 25~cm$^{-1}$.\\label{fig:methanol_kappa_beta3}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\begin{center}\n\\includegraphics[width=5.0in]{Figures/Methanol_Kappa_Band4_MALKMUS.pdf}\n\\includegraphics[width=5.0in]{Figures/Methanol_Beta_Band4_MALKMUS.pdf}\n\\end{center}\n \\caption{Methanol narrow band parameters $\\bar{\\kappa}$ and $\\beta$ obtained for the 3525--3850~cm$^{-1}$ band corresponding to the stretching motion of the $\\rm OH$ chemical groups. Temperatures plotted are: 293, 396, 443, 483, 570, 804, and 1000~K. The narrow band resolution $\\Delta \\om$ is 25~cm$^{-1}$.\\label{fig:methanol_kappa_beta4}}\n\\end{figure}\n\n\\FloatBarrier\n\n\\subsection{Verification SNB Parameters}\n\nTo assess the accuracy of the narrow band parameters $\\bar{\\kappa}$ and $\\beta$, synthetic transmissivities were constructed for the same experimental conditions as the FTIR data and compare with it. This subsection plots the comparison and the relative error in transmissivity (relative to FTIR measurements) using the methanol parameters presented in Figs.~\\ref{fig:methanol_kappa_beta1} to \\ref{fig:methanol_kappa_beta4}.\n\n\\begin{figure}[!h]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Methanol_MALKMUS_Temp293K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of methanol. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:methanol_kappa_beta1} to \\ref{fig:methanol_kappa_beta4}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.0922, 0.0714 and 0.0497 atm.cm. The gas temperature is set at 293~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:methanol_SNBVerify_293K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Methanol_MALKMUS_Temp396K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of methanol. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:methanol_kappa_beta1} to \\ref{fig:methanol_kappa_beta4}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.0929, 0.0735 and 0.0503 atm.cm. The gas temperature is set at 396~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:methanol_SNBVerify_396K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Methanol_MALKMUS_Temp443K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of methanol. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:methanol_kappa_beta1} to \\ref{fig:methanol_kappa_beta4}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered:0.0937, 0.0707 and 0.0457. The gas temperature is set at 443~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:methanol_SNBVerify_443K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Methanol_MALKMUS_Temp483K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of methanol. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:methanol_kappa_beta1} to \\ref{fig:methanol_kappa_beta4}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.0904, 0.07 and 0.0487 atm.cm. The gas temperature is set at 483~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:methanol_SNBVerify_483K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Methanol_MALKMUS_Temp570K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of methanol. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:methanol_kappa_beta1} to \\ref{fig:methanol_kappa_beta4}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.0919, 0.0498 and 0.0723 atm.cm. The gas temperature is set at 570~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:methanol_SNBVerify_570K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Methanol_MALKMUS_Temp804K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of methanol. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:methanol_kappa_beta1} to \\ref{fig:methanol_kappa_beta4}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.101, 0.0782 and 0.0535 atm.cm. The gas temperature is set at 804~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:methanol_SNBVerify_804K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_Methanol_MALKMUS_Temp1000K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of methanol. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:methanol_kappa_beta1} to \\ref{fig:methanol_kappa_beta4}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.0967, 0.0729 and 0.0488 atm.cm. The gas temperature is set at 1000~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:methanol_SNBVerify_1000K}}\n\\end{figure}\n\n\n\\clearpage\n\n\\section{Methyl Methacrylate: $\\rm C_5H_8O_2$}\n\n\\subsection{Integrated Band Intensity}\n\nMethyl Methacrylate, $\\rm C_5H_8O_2$, or MMA, has the most complex IR spectrum of all the fuels presented above. With 15 atoms, it has 39 vibrational modes. The MMA IR spectrum results from the vibration-rotation modes of the $\\rm C-O$, $\\rm C=O$, $\\rm C=C$, $\\rm CH_2$, and $\\rm CH_3$ groups. In RadCal, its IR spectrum has been divided into six distinct bands. The first band from 750--875~cm$\\rm^{-1}$ is associated with the bending motion of the $\\rm CH_2$ chemical group. The second band from 875--1050~cm$\\rm^{-1}$ is associated with the bending motion of the $\\rm CH_2$ chemical group. The third band from 1050--1250~cm$\\rm^{-1}$ is associated with the stretching motion of the $\\rm C-O$ chemical group. The fourth band from 1250--1550~cm$\\rm^{-1}$ is associated with the bending motion of the $\\rm CH_3$ chemical group. The fifth band from 1550-1975~cm$\\rm^{-1}$ is associated with the stretching motion of the $\\rm C=C$ and $\\rm C=O$ chemical groups. Finally, the sixth and last band from 2650--3275~cm$\\rm^{-1}$ is associated with the stretching motion of the $\\rm CH_2$ and $\\rm CH_3$ chemical groups. The band with the strongest absorption is the third band (1050--1250~cm$\\rm^{-1}$), see Table \\ref{Table::C5H8O2}.\n\\begin{table}[ht]\n   \\centering\n   \\caption{Spectral bands of $\\rm C_5H_8O_2$ included in RadCal.}\n   \\vspace{0.1in}\n   \\label{Table::C5H8O2}\n    \\begin{tabular}{|c|c|c|c|c|}\n    \\hline\n    Band \\# & \\multicolumn{2}{|l|}{Bounds (cm$\\rm ^{-1}$) } & Assignment &  $\\alpha(T=396 \\; {\\rm K}) \\; (\\rm {atm^{-1} cm^{-2}})$ \\\\\n    \\cline{1-5}\n    1 & 750  & 875  & $\\rm CH_2$ Bending          & 42   \\\\\n    2 & 875  & 1050 & $\\rm CH_2$ Bending          & 134  \\\\\n    3 & 1050 & 1250 & $\\rm C-O$ Stretching        & 805  \\\\\n    4 & 1250 & 1550 & $\\rm CH_3$ Bending          & 492  \\\\\n    5 & 1550 & 1975 & $\\rm C=C, C=O$ Stretching   & 542  \\\\\n    6 & 2650 & 3275 & $\\rm CH_2, CH_3$ Stretching & 295  \\\\\n    \\hline\n   \\end{tabular}\n\\end{table}\n\n\\subsection{Malkmus Narrow Band Parameters}\n\nAll the MMA IR spectral absorption data were obtained from high resolution FTIR experiments with temperatures varying from 297~K to 1014~K. The spectral absorption coefficients were obtained by fitting the experimental spectral transmissivity of a homogeneous column of isothermal MMA with a total pressure of 1~atm using the Malkmus model.\n\nThe MMA narrow band parameters, $\\bar{\\kappa}$ and $\\beta$, for temperatures ranging from 297~K to 1014~K are plotted in Figures~\\ref{fig:MMA_kappa_beta1}--\\ref{fig:MMA_kappa_beta6} for Bands 1 to 6. Note, while we have included data fr temperatures up to 1014~K, it is recommended to use caution when interpreting data for temperatures higher than 803~K as the stability of the component at high temperature is questionable.\n\n\\newpage\n\n\\begin{figure}[p]\n\\begin{center}\n\\includegraphics[width=5.0in]{Figures/MMA_Kappa_Band1_MALKMUS.pdf}\n\\includegraphics[width=5.0in]{Figures/MMA_Beta_Band1_MALKMUS.pdf}\n\\end{center}\n\\caption{MMA narrow band parameters $\\bar{\\kappa}$ and $\\beta$ obtained for the 750--875~cm$\\rm^{-1}$ band corresponding to the bending motion of the $\\rm CH_2$ chemical group. Temperatures plotted are: 297, 396, 441, 483, 597, 803, and 1014~K. The narrow band resolution $\\Delta \\om$ is 5~cm$^{-1}$.\\label{fig:MMA_kappa_beta1}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\begin{center}\n\\includegraphics[width=5.0in]{Figures/MMA_Kappa_Band2_MALKMUS.pdf}\n\\includegraphics[width=5.0in]{Figures/MMA_Beta_Band2_MALKMUS.pdf}\n\\end{center}\n\\caption{MMA narrow band parameters $\\bar{\\kappa}$ and $\\beta$ obtained for the 875--1050~cm$\\rm^{-1}$ band corresponding to the bending motion of the $\\rm CH_2$ chemical group. Temperatures plotted are: 297, 396, 441, 483, 597, 803, and 1014~K. The narrow band resolution $\\Delta \\om$ is 5~cm$^{-1}$.\\label{fig:MMA_kappa_beta2}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\begin{center}\n\\includegraphics[width=5.0in]{Figures/MMA_Kappa_Band3_MALKMUS.pdf}\n\\includegraphics[width=5.0in]{Figures/MMA_Beta_Band3_MALKMUS.pdf}\n\\end{center}\n\\caption{MMA narrow band parameters $\\bar{\\kappa}$ and $\\beta$ obtained for the 1050--1250~cm$\\rm^{-1}$ band corresponding to the stretching motion of the $\\rm C-O$ chemical group. Temperatures plotted are: 297, 396, 441, 483, 597, 803, and 1014~K. The narrow band resolution $\\Delta \\om$ is 25~cm$^{-1}$ below 1100~cm$\\rm ^{-1}$ and 25~cm$^{-1}$ above.\\label{fig:MMA_kappa_beta3}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\begin{center}\n\\includegraphics[width=5.0in]{Figures/MMA_Kappa_Band4_MALKMUS.pdf}\n\\includegraphics[width=5.0in]{Figures/MMA_Beta_Band4_MALKMUS.pdf}\n\\end{center}\n\\caption{MMA narrow band parameters $\\bar{\\kappa}$ and $\\beta$ obtained for the 1250--1550~cm$^{-1}$ band corresponding to the bending motion of the $\\rm CH_3$ chemical group. Temperatures plotted are: 297, 396, 441, 483, 597, 803, and 1014~K. The narrow band resolution $\\Delta \\om$ is 25~cm$^{-1}$.\\label{fig:MMA_kappa_beta4}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\begin{center}\n\\includegraphics[width=5.0in]{Figures/MMA_Kappa_Band5_MALKMUS.pdf}\n\\includegraphics[width=5.0in]{Figures/MMA_Beta_Band5_MALKMUS.pdf}\n\\end{center}\n\\caption{MMA narrow band parameters $\\bar{\\kappa}$ and $\\beta$ obtained for the 1550-1975~cm$^{-1}$ band corresponding to the stretching motion of the $\\rm C=C$ and $\\rm C=O$ chemical groups. Temperatures plotted are: 297, 396, 441, 483, 597, 803, and 1014~K. The narrow band resolution $\\Delta \\om$ is 25~cm$^{-1}$.\\label{fig:MMA_kappa_beta5}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\begin{center}\n\\includegraphics[width=5.0in]{Figures/MMA_Kappa_Band6_MALKMUS.pdf}\n\\includegraphics[width=5.0in]{Figures/MMA_Beta_Band6_MALKMUS.pdf}\n\\end{center}\n\\caption{MMA narrow band parameters $\\bar{\\kappa}$ and $\\beta$ obtained for the 2650--3275~cm$^{-1}$ band corresponding to the stretching motion of the $\\rm CH_2$ and $\\rm CH_3$ chemical groups. Temperatures plotted are: 297, 396, 441, 483, 597, 803, and 1014~K. The narrow band resolution $\\Delta \\om$ is 25~cm$^{-1}$.\\label{fig:MMA_kappa_beta6}}\n\\end{figure}\n\n\\FloatBarrier\n\n\\subsection{Verification SNB Parameters}\n\nTo assess the accuracy of the narrow band parameters $\\bar{\\kappa}$ and $\\beta$, synthetic transmissivities were constructed for the same experimental conditions as the FTIR data and compare with it. This subsection plots the comparison and the relative error in transmissivity (relative to FTIR measurements) using the MMA parameters presented in Figs.~\\ref{fig:MMA_kappa_beta1} to \\ref{fig:MMA_kappa_beta6}.\n\n\\begin{figure}[!h]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_MMA_MALKMUS_Temp297K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of MMA. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:MMA_kappa_beta1} to \\ref{fig:MMA_kappa_beta6}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.1, 0.0783 and 0.0543 atm.cm. The gas temperature is set at 297~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:MMA_SNBVerify_297K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_MMA_MALKMUS_Temp396K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of MMA. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:MMA_kappa_beta1} to \\ref{fig:MMA_kappa_beta6}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.102, 0.0764 and 0.0529 atm.cm. The gas temperature is set at 396~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:MMA_SNBVerify_396K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_MMA_MALKMUS_Temp441K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of MMA. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:MMA_kappa_beta1} to \\ref{fig:MMA_kappa_beta6}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered:0.0942, 0.0737 and 0.0506. The gas temperature is set at 441~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:MMA_SNBVerify_441K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_MMA_MALKMUS_Temp483K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of MMA. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:MMA_kappa_beta1} to \\ref{fig:MMA_kappa_beta6}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.0953, 0.074 and 0.051 atm.cm. The gas temperature is set at 483~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:MMA_SNBVerify_483K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_MMA_MALKMUS_Temp597K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of MMA. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:MMA_kappa_beta1} to \\ref{fig:MMA_kappa_beta6}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.0963, 0.0744 and 0.0515 atm.cm. The gas temperature is set at 597~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:MMA_SNBVerify_597K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_MMA_MALKMUS_Temp803K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of MMA. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:MMA_kappa_beta1} to \\ref{fig:MMA_kappa_beta6}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.105, 0.0807 and 0.0553 atm.cm. The gas temperature is set at 803~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:MMA_SNBVerify_803K}}\n\\end{figure}\n\n\\begin{figure}[p]\n\\includegraphics[width=\\textwidth]{Figures/Comparison_Fit_MMA_MALKMUS_Temp1014K.pdf}\n\\caption{Top: comparison between the experimental (FTIR, in solid lines) and the synthetic (dashed lines) spectral transmissivity profiles, denoted $\\tau_{\\omega}$, of an isothermal homogeneous column of MMA. The synthetic profiles was generated using the Malkmus narrow band parameters presented in Figs.~\\ref{fig:MMA_kappa_beta1} to \\ref{fig:MMA_kappa_beta6}. Bottom: relative transmissivity error, denoted $\\epsilon{(\\tau_{\\omega})}$, between the experiment and the synthetic profiles presented on the top figure. Three different pressure-paths are considered: 0.114, 0.0876 and 0.0596 atm.cm. The gas temperature is set at 1014~K and the total pressure is 101 kPa. Note: the experimental data resolution has been changed to match that of the narrow band model. \\label{fig:MMA_SNBVerify_1014K}}\n\\end{figure}\n", "meta": {"hexsha": "9653a75691cfecba9a968955551448efa81c6227", "size": 98791, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Documentation/New_Species_RADCAL_Chapter.tex", "max_stars_repo_name": "mcgratta/radcal", "max_stars_repo_head_hexsha": "83cb42ec8f43f243fe3b0b7640f62071b8482129", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Documentation/New_Species_RADCAL_Chapter.tex", "max_issues_repo_name": "mcgratta/radcal", "max_issues_repo_head_hexsha": "83cb42ec8f43f243fe3b0b7640f62071b8482129", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Documentation/New_Species_RADCAL_Chapter.tex", "max_forks_repo_name": "mcgratta/radcal", "max_forks_repo_head_hexsha": "83cb42ec8f43f243fe3b0b7640f62071b8482129", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 110.3810055866, "max_line_length": 1227, "alphanum_fraction": 0.7751819498, "num_tokens": 28068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3160234358137084}}
{"text": "\\documentclass[a4paper]{article}\n\n\n\\input{../preambles/preamble}\n\\setdefaultlanguage{english}\n%\\setotherlanguages{german,greek}\n\n\\input{../preambles/mathematics}\n\\input{../preambles/physics}\n\n%\\newcommand{\\RomaN}[1]{%\n%  \\textup{\\uppercase\\expandafter{\\romannumeral#1}}%\n%}\n\n\n%\\addbibresource{main.bib}\n\\title{Unruh effect}\n\\author{YiFan Wang}\n\n\n\\begin{document}\n\\maketitle\n\n%\\begin{abstract}\n%Your abstract.\n%\\end{abstract}\n\n\\tableofcontents\n\nDefining\n\\begin{equation}\nx_- = t-x,\\qquad x_+ = t+x.\n\\end{equation}\n\n\\section{Two-dimensional classical field by Unruh construction}\n\n\\begin{equation}\n\\Ld = -\\sqrt{-g}\\rbr{g_{\\mu\\nu}\\partial_\\mu \\partial_\\nu \\Phi}.\n\\end{equation}\n\nIn flat space-time with Minkowski metric,\n\\begin{equation}\n\\rbr{\\partial_t^2 - \\partial_x^2}\\Phi = 0.\n\\label{eq:eom-Minkowski}\n\\end{equation}\nSolve \\cref{eq:eom-Minkowski} simultaneously with \n\\begin{equation}\n\\ii\\what{\\mscrB}_x \\Phi = \\frac{\\kappa}{a}\\Psi\n\\end{equation}\nto find a complete set of basis of solution, where\n\\begin{equation}\n\\what{\\mscrB}_x = x\\partial_t + t \\partial_x\n\\end{equation}\nis the Lorentz boost generator in the $x$ direction, and is time-like in $L$ \nand $R$ region. \n\nOne finds the basis of solutions in $R$ region to be\n\\begin{equation}\n\\sbr{N\\rbr{\\frac{-x_-}{x_{-0}}}^{+\\ii\\kappa/a}, \nN\\rbr{\\frac{x_+}{x_{+0}}}^{-\\ii\\kappa/a}},\n\\end{equation}\nWhich are named as \\emph{boost modes}. Requiring phase at $\\rbr{t, x} = \\rbr{0, \n1/a}$ to be zero yields $x_{-0} = x_{+0}$.\n\n\n\n\n\n\n% Let's print the overall heading of the bibliography first:\n%\\printbibheading\n%\\printbibliography\n\n\\end{document}", "meta": {"hexsha": "5f4d32c45ed30da1e8a1b6aa9d245dacb85d9ac0", "size": 1593, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "old/Unruh/main.tex", "max_stars_repo_name": "cmp0xff/Notes", "max_stars_repo_head_hexsha": "afd712c1e42275bf781a030d6c5f1b7f4c6ec57b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "old/Unruh/main.tex", "max_issues_repo_name": "cmp0xff/Notes", "max_issues_repo_head_hexsha": "afd712c1e42275bf781a030d6c5f1b7f4c6ec57b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "old/Unruh/main.tex", "max_forks_repo_name": "cmp0xff/Notes", "max_forks_repo_head_hexsha": "afd712c1e42275bf781a030d6c5f1b7f4c6ec57b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.527027027, "max_line_length": 80, "alphanum_fraction": 0.7068424357, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.3160234274941507}}
{"text": "\\documentclass{article}\n\\usepackage{listings}\n\\lstloadlanguages{Haskell}\n\\lstnewenvironment{code}\n    {\\lstset{}%\n      \\csname lst@SetFirstLabel\\endcsname}\n    {\\csname lst@SaveFirstLabel\\endcsname}\n    \\lstset{\n      basicstyle=\\small\\ttfamily,\n      flexiblecolumns=false,\n      basewidth={0.5em,0.45em},\n      literate={+}{{$+$}}1 {/}{{$/$}}1 {*}{{$*$}}1 {=}{{$=$}}1\n               {>}{{$>$}}1 {<}{{$<$}}1 {\\\\}{{$\\lambda$}}1\n               {\\\\\\\\}{{\\char`\\\\\\char`\\\\}}1\n               {->}{{$\\rightarrow$}}2 {>=}{{$\\geq$}}2 {<-}{{$\\leftarrow$}}2\n               {<=}{{$\\leq$}}2 {=>}{{$\\Rightarrow$}}2\n               {\\ .}{{$\\circ$}}2 {\\ .\\ }{{$\\circ$}}2\n               {>>}{{>>}}2 {>>=}{{>>=}}2\n               {|}{{$\\mid$}}1\n    }\n\\begin{document}\n\n\\section{The specification}\n\nWe shall give a specification for fixed point arithmetic in two\nsteps.  First, we shall specify unbounded exact arithmetic, and\nthen we shall specify a framework for converting fixed point\nnumbers to ``fixed point frames''.  The specification is executable\ncode in the programming language Haskell [ref].\n\nOne specification covers both binary and decimal fixed point\narithmetic.  The base is part of the type of a fixed point number.\nThe LANGUAGE pragmas enable lanuage features added since the\nHaskell 2010 report.  The import declarations make the (named)\nfunctions available, these will be used in text$\\leftrightarrow$number\nconversion.\n\\begin{code}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\nimport Numeric (showSigned)\nimport Data.Char (isDigit)\n\\end{code}\nBinary and Decimal are ``empty types'' with no values other\nthan $\\bot$ used as compile-time marks.  The type class\nHas\\_Radix exists to convert these marks to run-time values.\n\\begin{code}\ndata Binary\ndata Decimal\n\nclass Has_Radix t\n  where radix :: t -> Integer\n\ninstance Has_Radix Binary\n  where radix _ = 2\n\ninstance Has_Radix Decimal\n  where radix _ = 10\n\\end{code}\n\nA fixed point number representation contains two unbounded integers.\nTo avoid confusing them, we give scales a different type.  The\nScale $t$ type has exactly the same representation as the Integer type;\nit has the same integer literals; and it has (some of) the same\noperations.  But it is a different type, which helps us avoid errors.\nIt is a ``phantom type'', so called because it\ncontains no run-time value of type $t$.  The ScopeTypeVariables\nfeature means that the type variable $t$ is available in the body\nof the `shift' function, so that we can extract the radix without\nstoring it anywhere.  The `shift' function shifts a number left or\nright by some number of digits; it is exactly what a shift instruction\nwould do on a binary or decimal sign-and-magnitude machine.\n\n\\begin{code}\nnewtype Scale t = Scale Integer\n                  deriving (Eq, Ord, Show, Num)\n\nshift :: forall t . Has_Radix t => Integer -> Scale t -> Integer\nshift m (Scale p) =\n  if p >= 0 then m * radix (undefined :: t) ^ p\n  else m `quot` radix (undefined :: t) ^ negate p\n\\end{code}\n% ERROR: shift was not defined for negative p.\n\nA Fixed $t$ contains an integer $m$ and a scale $s$ so that it represents\nthe value $m\\times r^s$ where $r$ is the radix determined by $t$.\nThese integers are unbounded; we are dealing with exact arithmetic\nat this point.\n\\begin{code}\ndata Fixed t = FP !Integer !(Scale t)\n\\end{code}\n\nFor testing we want to be able to create an integral Fixed $t$\nvalue with a given scale.\n\n\\begin{code}\ntoFixed :: Has_Radix t => Integer -> Scale t -> Fixed t\ntoFixed n s = FP (shift n s) s\n\\end{code}\n\nThe :: line for the toFixed function says ``for any type $t$,\nprovided that $t$ belongs to the Has\\_Radix class (that is,\n`radix' is defined on it), toFixed a function with an\nInteger argument and a Scale t argument that delivers a Fixed t\nresult.\n\nFrom an FP value we can extract its scale and base, even though\nthe base is not stored.  We can also provide the LIA function\n{\\it ulp} (unit in last place).\n\n\\begin{code}\nscale :: forall t . Has_Radix t => Fixed t -> Integer\nscale (FP _ s) = s\n\nbase :: forall t . Has_Radix t => Fixed t -> Integer\nbase _ = radix (undefined :: t)\n\nulp :: Has_Radix t => Fixed t -> Fixed t\nulp (FP _ s) = FP 1 s\n\\end{code}\n\n\\subsection{Comparison}\n\nWhat does it mean for (FP $m_1$ $s_1$) to equal (FP $m_2$ $s_2$)?\nConsider (FP 0 0) and (FP 0 1).  They both represent 0.  But they\nare behaviourally different.  For example, (FP 0 0) should print\nas \\verb|\"0\"| while (FP 0 1) should print as \\verb|\"0.0\"|.  If we\nwant equality to satisfy Leibniz' law, we have to regard these as\ndistinct.  On the other hand, it would be difficult to do numeric\ncalculations if zero wasn't equal to zero.\n\nThe standard mathematical way to deal with this is to distinguish\ntwo spaces:  a space $X$ of $(m,s)$ pairs which are equal if and\nonly if identity and a quotient space $F = X/\\equiv$ where\n$(m_1,s_1) \\equiv (m_2,s_2)$ if and only if $m_1\\times r^{s_2} =\nm_2 \\times r^{s_1}$.  Haskell's \\verb|==|, which we are about to\ndefine, should be thought of as $\\equiv$ rather than $=$.\n\nIn order to compare two numbers, it helps to align them so they\nhave their radix points in the same place.  This is also useful\nfor addition and subtraction.\n\n\\begin{code}\nalign :: forall t a . Has_Radix t =>\n    Fixed t -> Fixed t -> (Integer -> Integer -> a) -> a\n\nalign (FP m1 s1) (FP m2 s2) f\n  | s1 > s2 = f m1 (shift m2 (s1-s2))\n  | s1 < s2 = f (shift m1 (s2-s1)) m2\n  | True    = f m1 m2\n\\end{code}\n\nThis takes two fixed-point numbers in the same base, aligns them,\nand passes the aligned values to a function of integers.\n\nBy plugging Fixed into Haskell's Eq type class and\ndefining \\verb|==|, we get \\verb|/=| for free, correct by\nconstruction (if \\verb|==| is).  This provides\nthe LIA operations {\\it eq} and {\\it neq}.\n\n\\begin{code}\ninstance (Has_Radix t) => Eq (Fixed t)\n  where x1 == x2 = align x1 x2 (==)\n\\end{code}\n\nBy plugging Fixed into Haskell's Ord type-class and\ndefining three-way comparison, we get $<$, $\\le$, $>$, $>=$,\nmax, and min for free, correct by construction.\nThis provides the LIA-1 operations {\\it lss},\n{\\it leq}, {\\it gtr}, and {\\it geq} and the LIA-2 operations\n{\\it max} and {\\it min}, and since `maximum' and `minimum' are\npredefined folds derived from `max' and `min', the LIA-2\noperations {\\it max\\_seq} and {\\it min\\_seq}.\n\n\\begin{code}\ninstance (Has_Radix t) => Ord (Fixed t)\n  where compare x1 x2 = align x1 x2 compare\n\\end{code}\n\nThis is all we need to extend LIA-2's divisibility test to\nfixed-point numbers:\n\\begin{code}\nlia_divides :: Has_Radix t => Fixed t -> Fixed t -> Bool\nlia_divides x y = align x y (\\m n -> m /= 0 && n`rem`m == 0)\n\\end{code}\n\n% We can even define\n% lia_gcd :: Has_Radix t => Fixed t -> Fixed t -> Fixed t\n% lia_gcd x y = FP (align x y gcd) (scale x`max`scale y)\n% lia_lcm :: Has_Radix t => Fixed t -> Fixed t -> Fixed t\n% lia_lcm x y = FP (align x y lcm) (scale x `max` scale y)\n\n\\subsection{Converting numbers to text}\n\nFor general use, we would need a function to convert a\nnumber to a specified number of decimal digits according\nto a given rounding mode.  Here we simply specify conversion\nto decimal.  Numbers with scale $s \\le 0$ have no decimal\npoint; if $s > 0$ the number of decimal digits required is\n$s$ whether the base is Binary or Decimal.  If we supported\nbases that were not a multiple of 2, fixed-point numbers in\nsuch a base might not have a finite decimal representation.\n\nPlugging into Haskell's Show type-class takes care of\ninserting a negative sign (and if the context demands it,\nenclosing parentheses), and avoiding excess concatenation.\n\n\\begin{code}\ninstance (Has_Radix t) => Show (Fixed t)\n  where\n    showsPrec p x = showSigned showPos p x\n      where showPos x@(FP m s) rest =\n              if s <= 0 then shows (shift m (negate s)) rest\n              else shows i ('.' : show_fract s r)\n              where p = shift 1 s\n                    (i,r) = quotRem m p\n                    show_fract 0 _ = rest\n                    show_fract d f = shows h (show_fract (d-1) l)\n                      where (h,l) = quotRem (10 * f) p\n\\end{code}\n\nConverting from text to numbers runs into the problem that\n0.1 has no finite representation as a Fixed Binary.\nWe'll deal with that after considering rounding.\n\n\\subsection{Ring arithmetic}\n\nNumbers of the form $m\\times r^s$ form a ring under the usual\narithmetic operations, but they are \\emph{not} a field, see\nsubsection Division.\nWe can convert a fixed-point number to an exact Rational number and\nthose \\emph{are} a field.  None of the ring operations can fail.\nThis provides the LIA operations {\\it add}, {\\it sub}, {\\it mul},\n{\\it neg}, {\\it abs}, and {\\it sign}.  The 2012 revision of LIA-1\ndefines {\\it signum} instead of {\\it sign}.  One possible confusion\nis that LIA's {\\it sign} is Haskell's {\\it signum}; testing is\nadvisible to catch mistakes there.  The LIA-2 {\\it dim}\nfunction can also be defined for any ordered numeric type.\n\n\\begin{code}\ninstance (Has_Radix t) => Num (Fixed t)\n  where\n    x + y = FP (align x y (+)) (scale x `max` scale y)\n    x - y = FP (align x y (-)) (scale x `max` scale y)\n    negate (FP m s) = FP (negate m) s\n    abs    (FP m s) = FP (abs    m) s\n    signum (FP m s) = FP (signum m) 0\n    fromInteger n   = FP n 0\n    (FP m1 s1) * (FP m2 s2)  = FP (m1*m2) (s1+s2)\n\nlia_signum :: (Ord t, Num t) => t -> t\nlia_signum x = if x < 0 then -1 else 1\n\nlia_dim :: (Ord t, Num t) => t -> t -> t\nlia_dim x y = if x < y then fromInteger 0 else x - y\n\ninstance (Has_Radix t) => Real (Fixed t)\n  where\n    toRational (FP m s) =\n      if s >= 0 then m % (shift 1 s)\n      else (shift m (negate s)) % 1\n\\end{code}\n% ERROR: the else part was missing here.\nThe \\% operator divides two integers to make a rational number.\n\nSince raising to a non-negative power requires only the unit\n(fromInteger 1) and multiplication, we get the power operation\n$x$\\verb|^|$n$ free.  This operation fails if $n<0$, aligning\nit with the LIA-2 {\\it power${}_I$} function, but without the\nbreakage of making $0^0$ an error.  For example,\n\\begin{verbatim}\n> (1234 2 :: Fixed Decimal) ^ 4\n23187.85835536\n\\end{verbatim}\n\n\\subsection{Conversion to integer}\n\nThe fromInteger function converts integers to fixed-point;\ngoing the other way loses information so we need to say how.\n\nIn [section Rounding] we identified 14 rounding modes.\nWe have three options for naming them:\n\\begin{itemize}\n\\item They could be {\\it values}, as done in this section.\n\\item They could be {\\it functions}, {\\it e.g.},\n\\begin{code}% don't copy\ndown :: Real t => Integer\ndown x = floor (toRational x)\n\\end{code}\nWe can construct these functions if we want them:\n\\begin{code}% don't copy\ndown = convert Down\n\\end{code}\n\\item They could be {\\it types} like Binary and Decimal,\nwhich would mean that the Fixed\\_Frame type defined in a\nlater section would have less run-time content.\n\\end{itemize}\n\n\\begin{code}\ndata Rounding_Mode\n   = Down\n   | Up\n   | In\n   | Out\n   | Exact\n   | Even\n   | Nearest Rounding_Mode\n\\end{code}\n\nThis is very nearly an enumeration type, except that it\nallows constructions like Nearest Out.  (It also allows\nNearest (Nearest Odd), which is useless but harmless.)\n\nWe're going to define a single ``convert'' function that has\na rounding mode and a rational number and returns an integer.\nThis depends on the standard function `properFraction',\nwhich splits a rational number into an integer part and\na fractional part of the same type as its argument, such\nthat both parts are non-negative or both parts are non-positive.\nRealFrac is the class of numeric types on which it is defined.\n\n\\begin{code}\nconvert :: RealFrac t => Rounding_Mode -> t -> Integer\n\nconvert round x =\n  case round of\n    Down      -> if d < 0 then i-1 else i\n    Up        -> if d > 0 then i+1 else i\n    In        -> i\n    Out       -> i + d\n    Exact     -> if d == 0 then i else error \"inexact\"\n    Even      -> if even i then i else\n                 if d /= 0 then i + d else\n                 if (i + 1 `mod` 4) == 0 then i+1 else i-1\n    Nearest h -> if d == 0 then i else\n                 case compare (2*abs f) 1 of\n                   LT -> i\n                   GT -> i + d\n                   EQ -> i + convert h f\n  where (i,f) = properFraction x\n        d     = if f < 0 then -1 else if f > 0 then 1 else 0\n\\end{code}\n\nWe can't plug Fixed into RealFrac that because numeric types\nin Haskell can only belong to RealFrac if they also belong to\nFractional, which requires them to have division, reciprocal,\nand conversion from arbitrary rationals.\n\nThis is an occasion where Haskell proves to be inconvenient,\nbecause the properFraction, truncate, round, ceiling, and floor\nfunctions of the RealFrac class make perfect sense for\nfixed-point numbers.  However, we can compose convert with\ntoRational, making it possible to convert fixed-point numbers\nto different scales and different radices in the spirit of LIA,\nbeing like  the LIA functions {\\it round} and {\\it trunc}.\n\n\\begin{code}\nrescale :: forall t r . (Has_Radix t, Real r) =>\n          Rounding_Mode -> Integer -> r -> Fixed t\n\nrescale round digits x = FP (convert round y) digits\n  where y = toRational x * toRational (radix (undefined :: t) ^ digits)\n\\end{code}\n\nThe (convertFixed In) function provides the\nLIA (floating-point) operations {\\it intpart}, and {\\it fractpart}.\n\n\\begin{code}\nconvertFixed :: Has_Radix t =>\n    Rounding_Mode -> Fixed t -> (Integer, Fixed t)\n\nconvertFixed round x = (q, x - fromInteger q)\n  where q = convert round (toRational x)\n\\end{code}\n% ERROR: if the argument is already an (odd, even) integer,\n% it's returned unchanged instead of rounding to (even, odd).\n\nGiven this operation, we can define division with an\ninteger quotient and fixed-point remainder, supporting\nthe LIA-2 {\\it quot}, {\\it mod}, {\\it ratio}, {\\it residue},\n{\\it group}, and {\\it pad} functions.\n\n\\begin{code}\nquotient :: Has_Radix t =>\n    Rounding_Mode -> Fixed t -> Fixed t ->\n    (Integer, Fixed t)\nquotient round x y = (q, x - fromInteger q * y)\n  where q = convert round (toRational x / toRational y)\n\\end{code}\n% Error: was convertFixed round x   -- TWO errors!\n\nThe Haskell type-class Integral provides integer quotient\nand remainder in the type-class Integral.  This is arguably\nthe wrong place, which explains why we have\n\\begin{code}%don't copy\nquotient Floor -- instead of divMod\nquotient In    -- instead of quotRem\n\\end{code}\n\n\\subsection{Frames}\n\nIn a language like COBOL or PL/I, the result of a calculation\nmust fit into the declared type of a variable, while the way\nthat the exact result is rounded to fit may be separately\nspecified.  In other languages, like C$\\sharp$, the scale is\npart of the value, but there is a maximum scale.  We shall\ncall the combination of radix (carried in the type),\na desired or maximal scale, a rounding\nmode, and optional bounds a Fixed\\_Frame, and the operation\nof taking an exact result and coercing it into a frame ``fitting''.\nA programming language standard could for example say that\n``BINARY FIXED ($p,s$) corresponds to\nFixed\\_Frame Binary (Exact\\_Scale $s$) (Nearest Out)\n(Just (-($2^p)$, $2^p-1$))''.\n\n\\begin{code}\ndata Result_Scale\n   = Exact_Scale   !Integer\n   | Maximum_Scale !Integer\n\ndata Fixed_Frame t\n   = Fixed_Frame !Result_Scale !Rounding_Mode\n                 !Maybe (Integer, Integer)\n\nfit :: Has_Radix t =>\n       Fixed_Frame t -> Fixed t -> Fixed t\n\nfit (Fixed_Frame rs round bounds) x@(FP m s)\n  = check_bounds bounds m' y\n  where\n    y@(FP m' _) =\n      case rs of\n        Exact_Scale e   -> if e == s then x else\n                           rescale round e x\n        Maximum_Scale e -> if e >= s then x else\n                           rescale round e x\n\ncheck_bounds :: Ord t => Maybe (t,t) -> t -> r -> r\n\ncheck_bounds Nothing      _ y = y\ncheck_bounds (Just (l,u)) x y =\n  if l <= x && x <= u then y else error \"overflow\"\n\n\\end{code}\n\n\\subsection{Division}\n\nCOBOL, PL/I, SQL, Java, C$\\sharp$, Swift, and most libraries\ninspected for this work provide division.  The COBOL\nDIVIDE statement can be given a satisfactory definition because\nthe destination and the rounding option provide a Fixed\\_Frame.\nPL/I's DIVIDE function also provides a Fixed\\_Frame for the\nanswer (with only one rounding mode available).\n\nHowever, no language or library has a satisfactory definition of\n``/'' delivering an intermediate result without constraints\nprovided by a destination.  That is because no satisfactory\ndefinition exists.\n\nThe set of fixed-point numbers is not closed under division.\nConsider 0.1/0.3.  This has an exact rational result, 1/3,\nbut there is no $s$ such that $1/3 \\times 10^s$ is an integer.\nSo unlike addition, subtraction, and multiplication, it is not\npossible for division to provide an answer that is both fixed\npoint and exact.\n\nThe best that can be one is to specify division given a frame.\n\n\\begin{code}\ndivide :: forall t u v . (Has_Radix t, Real u, Real v) =>\n          Fixed_Frame t -> u -> v -> Fixed t\ndivide (Fixed_Frame rs round bounds) x y\n  = check_bounds bounds m (FP m s)\n  where\n    s = case rs of\n          (Exact_Scale   z) -> z\n          (Maximum_Scale z) -> z\n    p = radix (undefined :: t) ^ s\n    q = toRational x / toRational y\n    m = convert round (q * fromInteger p)\n\\end{code}\n\nThe same problem arises when trying to define a square root\nfunction on fixed-point numbers, as some libraries do.  The\nsame solution, of requiring an explicit frame.  LIA-2 extends\n{\\it sqrt} to integers, but only with the In rounding mode.\n\n\\subsection{Converting from text to number}\n\nSpecifying conversion for Fixed Decimal numbers\nwith their natural scale is tedious rather than difficult.\nThe code that follows is a finite state automaton that\naccumulates an integer and counts digits after the decimal point.\nThis follows the convention of the Haskell Read class that\na string is mapped to a list of (value,residue) pairs with a\npair for each legal way to parse a prefix of the string.  In\nthis case there is either one way or none.\n\n\\begin{code}\nreadDecimalFixed :: String -> [(Fixed Decimal,String)]\nreadDecimalFixed ('-':cs) = after_sign negate cs\nreadDecimalFixed cs       = after_sign id     cs\n\nafter_sign f (c:cs)\n  | isDigit c = after_digit f (add_digit 0 c) cs\nafter_sign _ _ = []\n\nafter_digit f n (c:cs)\n  | isDigit c = after_digit f (add_digit n c) cs\nafter_digit f n ('.':c:cs)\n  | isDigit c = after_dot f 1 (add_digit n c) cs\nafter_digit f n ('.':_) = []\nafter_digit f n cs = [(FP (f n) 0, cs)]\n\nafter_dot f s n (c:cs)\n  | isDigit c = after_dot f (s+1) (add_digit n c) cs\nafter_dot f s n cs = [(FP (f n) s, cs)]\n\nadd_digit :: Integer -> Char -> Integer\n\nadd_digit n c =\n   n * 10 + fromIntegral (fromEnum c - fromEnum '0')\n\\end{code}\n%ERROR: add_digit had - fromEnum c\n%ERROR: after_dot had n and s swapped.\n\nHowever, \\verb|\"0.1\"| has no exact representation as a\nFixed Binary, nor is the natural scale what a\nprogram necessarily needs.  What is needed is precisely\na Fixed\\_Frame.\n\n\\begin{code}\nreadFixed :: Has_Radix t =>\n             Fixed\\_Frame t -> String ->\n             [(Fixed t, String)]\n\nreadFixed frame cs =\n   [ (fix frame num,rest) | (num,read) <- readDecimalFixed cs ]\n\\end{code}\n\n\n\\end{document}\n", "meta": {"hexsha": "e2b786d2eeaf40db3aa248a9cd6a2a738af19c29", "size": 19171, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "3-spec.tex", "max_stars_repo_name": "nzok/decimal", "max_stars_repo_head_hexsha": "939e3403d706a2ab9dfa9fd24c17f2953e074b52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "3-spec.tex", "max_issues_repo_name": "nzok/decimal", "max_issues_repo_head_hexsha": "939e3403d706a2ab9dfa9fd24c17f2953e074b52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3-spec.tex", "max_forks_repo_name": "nzok/decimal", "max_forks_repo_head_hexsha": "939e3403d706a2ab9dfa9fd24c17f2953e074b52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3708487085, "max_line_length": 75, "alphanum_fraction": 0.683636743, "num_tokens": 5434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.31602342749415063}}
{"text": "\\chapter{Evaluation metrics for quantization and rating}\n\\label{chap:eval}\nEvaluating the collected data is one of the key responsibilities of the application. From a set of rated faces, a policy is to be learned that can quantize the user's subjective perception of attractiveness. Depending on the circumstances, different approaches exist to achieve this. Given the \\textit{CelebA} dataset, which is already annotated with facial attributes, there is no image processing neccessary. All policies can be learned from the combination of attribute labels and user decision. However, the goal is to make the system applicable to unknown images. Serving as a plug-in for existing applications as it is targeted in chapter \\ref{chap:plugin}, images are not labeled. Therefore, the next step of \\textit{Quantinder} is to extract relevant attributes from images by its own. This would, however, probably not be executed on the client's phone, as the images are available on servers anyway. Section \\ref{sec:celebadesc} explains the structure of the \\textit{CelebA} dataset. Section \\ref{sec:straightfwd} describes the evaluation approach implemented in \\textit{Quantinder} with the labeled images from \\textit{CelebA}, whereas section \\ref{sec:unlabeled} discusses possibilites to handle unlabeled image datasets by extracting the attributes from the images.\n\\section{Formal description of the \\textit{CelebA} dataset}\n\\label{sec:celebadesc}\nThe \\textit{CelebA} dataset consists of over 200.000 images from 10.000 celebrities. All images display the face of the identity. Parts of the body are optional. The backgrounds of the images are divergent, there are faces on a magazine's front page as well as well as indoor and outdoor portrais. The main contribution of the \\textit{CelebA} dataset are the annotations of each image. They define whether or not a face exhibits a certain attribute. Formally we can describe \\textit{CelebA} as a set of images $S_{I}$, where $\\lvert S_{I}\\rvert=202.599$ and a set of attributes $S_{A}$, where $\\lvert S_{A}\\rvert=40$. The set $S_{V}$ of all ordered pairs ($i$,$a$), $i\\in S_{I}$, $a\\in S_{A}$, is obtained by the Cartesian product of the two sets as\n\\begin{equation}\nS_{V}=S_{I}\\times S_{A}.\n\\end{equation}\nA mapping fuction\n\\begin{equation}\n\\label{eq:f}\nf:S_{V}\\mapsto Y_V,\\quad where\\ Y_V = \\{1,-1\\}\n\\end{equation}\nassigns either $1$ or $-1$ to each element $v=(i,a) \\in S_{V}$.  Function $f$ is specified by humans who decided for each image attribute pair $v=(i,a)$ whether the face in the image $i$ exhibits the attribute $a$. If so, $f(v)=1$, otherwise $f(v)=-1$.\n\\section{Formal description of the data gathered from user input}\n\\label{sec:userinput}\nThrough swiping through the images, the user gives either a positive or negative feedback for each image. Thus, the feedback function is defined as\n\\begin{equation}\n\\label{eq:g}\ng:S_{I}\\mapsto Y_S,\\quad where\\ Y_S\\ = \\{1,-1\\}.\n\\end{equation}\nFunction $g(i)$ yields $1$ as its value if the user liked the face in image $i$ and $-1$ if the user disliked the face.\n\\section{Rating the attributes given the labeled images from \\textit{CelebA} and the user's decision}\n\\label{sec:straightfwd}\nGiven the labeled dataset according to equation \\ref{eq:f} and the user input as defined in equation \\ref{eq:g}, a policy should be learned that represents the user's subective perception of attractiveness. To this end, different metrics can be applied to generate an expressive and realistic policy. Both the information sources from equation \\ref{eq:f} and \\ref{eq:g} are to be combined. For each attribute $a\\in S_A$, the user's approval rating $h(a)$ is to be determined by the function\n\\begin{equation}\nh:S_A\\mapsto \\mathds{R}\n\\end{equation}\nThe approval rating value $h(a)$ respresents the subjective attractiveness of the attribute $a$ and is positive if the user likes the attribute and negative if he dislikes $a$. Therefore, the function $h(a)$ is to be specified. Various approaches are envisaged in the following subsections.\n\\subsection{Increment and decrement scheme}\nOn account of the simplicity of $f$ and $g$ with binary codomains, the evaluation function $h$ can be defined without complex calculation schemes. Let us consider a case where the user rated one face only. We want to formulate $h$ in a way so that in yields the approval rating for every attribute in $S_A$. The straight-forward solution for the formulation of $h$ for the case of a single image $i$ would be an equality check of the binary attribute value $f(i,a)$ and the binary user decision $g(i)$ as follows:\n\\begin{equation}\n\\label{eq:oneface}\nh_i(a) = f(i,a)\\ XNOR\\ g(i).\n\\end{equation}\nSemantically, this means that the approval rating of an attribute is positive either when the user liked the face and the face exhibits this attribute or when the user disliked the face and the face does not exhibit the attribute. Otherwise, the approval rating $h(a)$ is negative. For mathematical convenience and expandability to non-binary values, the codomains $Y_V$ and $Y_S$ of $f$ and $g$ have been defined as $1$ for logic true and $-1$ for logic false. This allows implementing the XNOR operation as an integer multiplication, since\n\\begin{equation}\n\\label{eq:verysmall101}\n\\begin{split}\n-1\\cdot(-1) = 1\\\\\n-1\\cdot1 = -1,\\\\\n1\\cdot(-1) = -1,\\\\\n1\\cdot1=1.\n\\end{split}\n\\end{equation}\nWhen trying to evaluate the results from more than one face, the formulation from equation \\ref{eq:oneface} is not sufficient. However, we can iterate over the image set $S_I$ and, apply the logic from equation \\ref{eq:oneface} and \\ref{eq:verysmall101} and associate the values from the single iterations by summation:\n\\begin{equation}\n\\label{eq:morethanoneface}\nh(a) = \\sum_{i\\in S_I} f(i,a) \\cdot g(i)\n\\end{equation}\nFunction $h(a)$ is calculated for all forty $a\\in S_A$. It can be updated incrementally while the user is swiping through the faces. Suppose the user has swiped through a hundred images. Equation \\ref{eq:morethanoneface} says, for a further face the user swipes to the right, implying a like and $g(i)=1$, the attribute approval rating $h(a)$ increases by 1 if the face exhibits attribute $a$, implying $f(i,a)=1$. All other attributes, that are not present in the face, are rated down by 1. Through the simple combination of $f$ and $g$, the system is already able to quantize the user's preferences. If the independent application of equation \\ref{eq:morethanoneface} for every attribute is merged, then the output can be depicted as the attribute approval rating vector $v_h$, which is obtained by\n\\begin{equation}\n\\label{eq:vec}\nv_h = [h(a_0), h(a_1) ... h(a_{39})].\n\\end{equation}\nThe elements of $v_h$ can be sorted in a way that assigns the highest value the lowest index. Thereafter, a list from the best rated attributes to the worst rated attributes can be printed. This information corresponds to the user's preferences.\n\nGiven the attribute approval rating vector $v_h$, it is possible to make a prior guess about the posterior event of the user's decision for the next image. If there are many attributes in the face which have a high value in $v_h$, the user is probably going to like this face as well. This idea is implemented as\n\\begin{equation}\n\\label{eq:posteriorguess}\nl(i) = \\sum_{a\\in S_A} v_h[a] \\cdot g(i),\n\\end{equation}\nwhere $l(i)$ is the prior guess value. Increasing positive values of $l(i)$ correspond to an increasing probability that the user is going to like the face. This prior guess value can be converted to a percentage by dividing through the highest possible match.\n\\subsection{Normalization based on like ratio}\nThe rating approach based on equations \\ref{eq:morethanoneface}, \\ref{eq:posteriorguess} is already capable of elaborating preferences and distastes, however, it suffers from being dependent on a balanced like ratio. For instance, when the user swipes all the images to the right, actually it should not be possible to make any assumptions. But a system solely based on the logic from equations \\ref{eq:morethanoneface}, \\ref{eq:posteriorguess} will still generate an output. The attributes which are exhibited by the most faces will have the highest rating. This violates the validity, which was one of the requirements to the evaluation logic. Therefore, the attribute approval rating $h(a)$ is normalized with respect to the like/dislike ratio.\n\nGiven the like ratio, the normalization is achieved by weighting the users's feedback lower for all faces which have been swiped in the direction where the majority of the faces has been swiped to. The influence of liked and disliked faces should thus become equally balanced. Normalization is conducted for each attribute $a$ as\n\\begin{equation}\n\\label{eq:basicnormaliz}\nh_\\eta(a) = h(a) - \\eta(a),\n\\end{equation}\nwhere $\\eta(a)$ is the normalization term informally defined as\n\\begin{equation}\n\\label{eq:infmleta}\n\\eta(a) = \\frac{diff(\\texttt{liked}, \\texttt{disliked}) \\cdot diff(\\texttt{faces with } a, \\texttt{faces without } a)}{\\texttt{\\# rated faces}}.\n\\end{equation}\nEquation \\ref{eq:infmleta} expressed more formally, it could be denoted as\n\\begin{equation}\n\\label{eq:fmleta}\n\\eta(a) = \\frac{\\delta_g\\cdot\\delta_f(a)}{n},\n\\end{equation}\nwhere the total number of rated faces $n$ in the denominator can be obtained by\n\\begin{equation}\nn = \\lvert \\{i\\in S_I\\ \\lvert\\ \\exists\\ g(i)\\}\\rvert,\n\\end{equation}\nthe gap between liked and disliked faces $\\delta_g$ by\n\\begin{equation}\n\\delta_g = 2\\cdot n_{liked} - n,\\quad \\texttt{where}\\ n_{liked}= \\{i\\in S_{I}\\ \\lvert\\ g(i)=1\\},\n\\end{equation}\nand the gap between faces exhibiting $a$ and faces not exhibiting $a$ by\n\\begin{equation}\n\\delta_f(a) = 2\\cdot n_{exhibits} - n,\\quad \\texttt{where}\\ n_{exhibits}= \\{i \\in S_{I}\\ \\lvert\\ f(i,a)=1\\}.\n\\end{equation}\n\nLet us consider some cases for $\\delta_g$ and $\\delta_f$. The normalization term $\\eta(a)$ is positive when the like ratio is over 50\\% and more than 50\\% of the rated faces exhibit $a$. $\\eta(a)$ is also positive if both aforementioned conditions do not hold. Semantically, this means the normalized attribute approval rating $h_\\eta(a)$ will be less than the original $h(a)$. In general, the normalization term always decreases $h(a)$ with respect to the absolute value. If $\\delta_g$ and $\\delta_f$ have different signs, $\\eta(a)$ is negative, however, in this case $h(a)$ is also negative because of equation \\ref{eq:morethanoneface}. If either the number of likes matches the number of dislikes or there is the same number of faces with and without $a$, $\\eta(a)$ will be zero. No normalization is applied. To understand the purpose of including $\\delta_g$, the example from above is regarded where the user swipes all faces to the right. When the attribute values are equally distributed among $1$ and $-1$, $h(a)$ is already zero. The desired result is also zero because based on the user's input there cannot be made any assumption. So in this case, the normalization should have no effect on $h(a)$. But if the attribute $a$ were present in, for instance, 80 of 100 rated faces, $h(a)$ attains $+60$ according to equation \\ref{eq:morethanoneface}. Now, the difference between liked and disliked images $\\delta_g$ is $+100$ and the difference $\\delta_f$ between faces with $a$ and faces without $a$ is thus $+60$. Following equation \\ref{eq:fmleta}, the resulting normalization term is $\\eta(a)=+60$. After inserting $\\eta(a)$ in equation \\ref{eq:basicnormaliz}, it becomes apparent how the consequences of a unbalanced like ratio can be cancelled out by normalization.\n\n\\subsection{Normalization based on stochastical dependency among attributes}\nThe normalization scheme described above is a decisive factor for a evaluation logic that yields relevant results. However, there is still a problem with stochastical dependency among the attributes. This issue originates in the human behaviour to dress and style depending on sex and age as combined with the setup of \\textit{CelebA}, where attributes have been chosen in a way they are partially redundant. For instance, experiments have shown that for most of the heterosexual men, the attributes \\textit{Heavy Makeup} and \\textit{Wearing Lipstick} are among the best rated attributes. Most of the subjects were suprised about the results since they actually do not consider these attributes attractive. However, since the number of women with makeup and lipstick is sharply higher, the attributes have a strong positive rating when the user swipes every women to the right and every men to the left. Therefore, the issue can be defined as follows: Some attributes are continuously rated either positive or negative, although the user is not really interested in this attribute. This is caused by the dependency of this attribute to one or more other attributes which are the real reason for the user to like the face.\n\nRemoving this dependency is a further step to obtain valuable results which represent the real subjective perception of attractiveness. Therefore, all attributes are scanned for their dependency on each other. The result is a undirected complete graph, visualized in Figure \\ref{pic:complgraph}.\n\n\\FG{complgraph.png}{8cm}{Complete undirected graph showing the dependencies among six selected attributes. Dark red edges indicate negative correlation, dark green edges positive correlation and black edges indifferences.}{complgraph}\n\nThe dependencies from Figure \\ref{pic:complgraph} are to be balanced out in a way so that redundancy is cancelled out in the rating results. Weights are introduced for each rated face and attribute. Faces which do not comply with the general dependency rule are more interesting and thus get a higher weight. For instance, if there is a male(1) person with beard(2), no lipstick(3) but makeup(4), the \\textit{Beard} and \\textit{Wearing Lipstick} attributes are assigned a lower weight because three out of four edges comply with the general rule based on the dependencies. People wearing beards wear in most cases no lipstick. In the same way, male persons wear almost never lipsticks, but often beards. These general rules based on the dependencies are visualized by the edge colors in Figure \\ref{pic:complgraph}. In contrast to the three aforementioned attributes, the makeup attribute occurs more often together with non-male persons with no beard, but lipstick. The makeup attribute is, thus, in the example some kind of the odd one out. Hence the beard attribute is weighted stronger for this face than for faces of women with lipstick and makeup. The beard and lipstick attributes are thus of less interest than the makeup attribute, which is very rare for male people with beard and no lipstick. This rareness makes this particular face a more decisive face with respect to the makeup attribute. Thus, applying this weights in the calculation of the attribute approval rating, the desired effect of removing implicit dependencies can be achieved.\n\nTo illustrate the mathematical principle behind the balancing, let us consider a dataset with only two attributes instead of forty. These two attributes are \\textit{Male} and \\textit{Heavy Makeup}. Table \\ref{tab:pairs} shows the attribute values in the example dataset.\n\n\\begin{table}\n\\centering\n\\begin{tabular}{l | c c}\n              & Male & Heavy_Makeup\\\\\n\\hline\nFace1  & -1 & 1   \\\\\nFace2  & -1 & 1   \\\\\nFace3  & -1 & -1   \\\\\nFace4  & 1 & 1   \\\\\nFace5  & 1 & -1 \\\\\nFace6 & 1 & -1   \n\\end{tabular}\n\\caption{The example dataset contains images from thre male and three female persons. Two third of the female wear heavy makeup, two third of the male do not.}\n\\label{tab:pairs}\n\\end{table}\n\nStarting with the dataset from Table \\ref{tab:pairs}, the number of pairs with equal values are counted. There are $n_{tot}=6$ images $i \\in S_I$ in the dataset and two attributes $a \\in S_A$. Both attributes are equally often present and absent, but they are dependent on each other because more female than male persons wear heavy makeup. The pair for \\textit{Face1} is denoted as \n\\begin{equation}\n\\label{eq:pair}\np_{i1}=(a_1(i),a_2(i)),\n\\end{equation} \nwhere $a_1$ corresponds to the male attribute and $a_2$ to the heavy makeup attribute. The number of pairs with equal values is determined by\n\\begin{equation}\nn_{eq}=\\lvert (i \\in S_I, a \\in S_A\\ \\lvert\\ a_1(i) = a_2(i)) \\rvert\n\\end{equation}\nAiming for a balanced ratio between equal and distinct pairs, the weight for all equal pairs is determined as\n\\begin{equation}\n\\label{eq:weight}\nw_{eq} = \\frac{n_{tot}}{2\\cdot n_{eq}}.\n\\end{equation}\nLikewise, the weight $n_{dst}$ for the distinct pairs is calculated by replacing $n_{eq}$ in equation \\ref{eq:weight} with $n_{tot}-n_{eq}$. In the estimation process of an attribute's approval rating, the weights are multiplied with the binary feedback value obtained from the user. The weight $n_{eq}$ is multiplied to all faces $S_{I,eq}$ for which equation \\ref{eq:pair} holds and $n_{dst}$ is multiplied to all faces $S_{I,dst}$ that exhibit dinstinct attribute values, meaning equation \\ref{eq:pair} does not hold.\nContemplating the example from Table \\ref{tab:pairs}, $w_{eq}$ is calculated as $6/(2 \\cdot 2)=1.5$ and $w_{dst}$ is $6/(2\\cdot 4)=0.75$. Extending equation \\ref{eq:morethanoneface} with the weight term, an $h_n(a)$ can be obtained as\n\\begin{equation}\n\\label{eq:weightedsum}\nh_n(a) = \\sum_{i\\in S_I} f(i,a)\\cdot g(i) \\cdot w(i),\n\\end{equation}\n\\begin{equation}\n\\label{eq:weightseqdst}\nwhere\\quad w(i) = \\left\\{\\begin{array}{lr}\n        w_{eq} & \\text{if }  i \\in S_{I,eq}\\\\\n        w_{dist} & \\text{otherwise } \\\\\n        \\end{array}\\right.\n\\end{equation}\nLet the user like all female faces and dislike all male faces. By plugging in the values from Table \\ref{tab:pairs} into equation \\ref{eq:weightedsum}, the resulting attribute approval ratings are $h_n(\\textit{Male}) = +6$ and $h_n(\\textit{Heavy Makeup}) = 0$. This is exactly the wanted behaviour. When comparing this to the results without the weighting term by simply plugging into equation \\ref{eq:morethanoneface}, we obtain $h(\\textit{Male}) = +6$ and $h(\\textit{Heavy Makeup}) = +2$. The weighting term has thus successfully removed the dependency of the \\textit{Heavy Makeup} attribute from the \\textit{Male} attribute.\n\nUnfortunately, this logic becomes more difficult when there are more than two attributes. In the real implementation, there are 780 edges as this is the number of possible pairs out of 40 nodes, given by the n chooses k formula, where n = 40 and k=2:\n\\begin{equation}\nn_{pairs} = \\frac{40!}{2! \\cdot 38!} = 780.\n\\end{equation}\nHowever, to achieve a balanced graph, this effort must be taken. For a given attribute, the weights to each of the other 39 attributes are calculated according to equation \\ref{eq:weight}. Subsequently, the attribute approval vector $h_n(a)$ can be determined by equation \\ref{eq:weightedsum}, where the weight term $w(i)$ is more complicated than in equation \\ref{eq:weightseqdst}. For every face, one of the two weights is selected for all pairs containing $a$ and then multiplied together. The selection is executed as per equation \\ref{eq:weightseqdst}. After the products of the multiplication has been determined for each face, $h_n(a)$ is finally obtained by summing up the products, where each product has the sign given by $h_i(a)$ from equation \\ref{eq:oneface}. Thus the stochastical dependency among the attributes has been removed.\n\n\\section{Preparing for unlabeled images by extracting attributes from images}\n\\label{sec:unlabeled}\nIn an environment where real images are to be processed, there are no annotations about facial attributes available. Knowledge about the facial attributes are essential for \\textit{Quantinder} and the metrics discussed in chapter \\ref{chap:eval}. In order to transfer \\textit{Quantinder} to the real world, it is neccessary to extract these attributes from the images. Fortunately, this is possible. Either a foreign library or service can be used or an own network is established. The former method is discussed in subsection \\ref{subsec:pretrained} and the latter one is contemplated in subsection \\ref{subsec:usingdeepl}.\n\n\\subsection{Using Deep Learning}\n\\label{subsec:usingdeepl}\n\\FG{anetlnetflow.png}{7cm}{Pipeline of the system from Liu \\etAl \\cite{deeplfaceattr}.}{anetlnetflow}\nGiven a large annotated dataset like \\textit{CelebA}, it is possible to train a network which first learns the attributes from the training images and later on, it is able to infer the presence or absence for each attribute. Liu \\etAl use the CelebA data set in their work \\cite{deeplfaceattr} to train two \\gls{CNN}s. The first \\gls{CNN}, called \\gls{LNet} addresses the problem of recognizing and localizing a face in images with natural background. \\gls{LNet} is repeated once in a coarse to fine scheme, meaning the larger region of face is determined in the first iteration, and the second iteration determines the exact shape of the face. The \\gls{ANet}, the second \\gls{CNN}, is responsible for extracting discriminative face features from a given face. By installing a linear \\gls{SVM}, which is trained with the feature vectors output from \\gls{ANet}, attribute prediction can be achieved. Thus the training pipeline for predicting facial attributes from any image is repeated \\gls{LNet} followed by \\gls{ANet} followed by the \\gls{SVM}. For the training of \\gls{LNet} the \\gls{ILSVR-C} dataset \\cite{ilsvrc} is used. It contains 1.2 million annotated images of objects in natural backgrounds, with humans and other objects mixed. The annotation gives information about the object category, such as vehicle, dog, or human face. The annotation is only at image-level, which means \\gls{ILSVR-C}'s annotations do not provide information about the object's location in the image. This means \\gls{LNet} must learn the location of a face in an image implicitly. On account of the object category labels, \\gls{LNet} knows in the training phase which images are a face and which are not, and by learning from the differences, the parts that belong to the face can thus be identified. For fine tuning \\gls{LNet}, the CelebA dataset is also considered, but the main purpose of CelebA is to train the \\gls{ANet}, which is responsible of extracting distinctive facial features that can subsequently be consulted to determine the binary value of each of the forty attributes.\n\n\\subsection{Using foreign pre-trained face attribute extractors}\n\\label{subsec:pretrained}\nThe complexity of building an own \\gls{CNN} could be avoided by utilizing the knowledge from a trained model which is, however, trained for a different purpose. This is known as transfer learning \\cite{transferl}. More specifically, transfer learning means to transfer the learned features from a network to a target network. The target network should learn different features which are related to the features from the reused network. This process will tend to work if the features from the frist network are general with respect to the target network. When trying to learn facial attributes, a network having been trained for general object classification is a good starting point. For object classification, there are many trained \\gls{CNN}s available, for instance the \\textit{RsNet-50} network, which has been trained on millions of images from the \\textit{ImageNet} dataset. Libraries such as \\textit{fast.ai} simplify the process of imlementing transfer learning significantly. The first convolutional network, for instance \\textit{RsNet-50} can be easily extended by a number of layers which are responsible to fulfill the task of attribute detection. These additional layers still have to be trained, however, effort is less since tasks as face localization are already handled by the \\textit{RsNet-50} network.\n\nA further option for extracting facial attributes is to use attribute detection services from foreign providers such as the \\textit{Google Cloud Vision} API or the \\textit{Haystack.ai} API. Both work by sending images to the provider and receiving a response where the attribute values are listed. In Haystack, the response exhibits information about predicted age, objective attractiveness, race, gender, emotion and nudity. They easily oould be transformed into a set of binary attributes as in \\textit{CelebA}. \\textit{Google Cloud Vision}'s face recognition software is capable of predicting the likelihood of the presence of certain emotions as well as of attributes such as size and color of facial features. Services like these have in common that all detection algorithms are implemented server-sided. They are based on being trained with large image datasets. Simply using one of these services would simplify the implementation significantly, however, there are a few drawbacks coming along with this method. First, \\textit{Google Vision} and \\textit{Haystack.ai} are paid services, where a fee is paid for the processing of each image. For a larger scaled application, costs would sour up. Second, no customization of the algorithms is possible. Both response format and the inference method is fixed and cannot be adapted to specific needs. Third, as the services are proprietary, there is no information published about the functionality of the network behind the services. This prevents conducting a suitability analysis.", "meta": {"hexsha": "ee5d47fdc4bd05a43b8de8bbda35a3341d195417", "size": 25331, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "quantinder/doc/chapters/chapter3.tex", "max_stars_repo_name": "JonGitti/Quantinder", "max_stars_repo_head_hexsha": "08d8e103a9e82b19ef569a8f6fc7f0120091291f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "quantinder/doc/chapters/chapter3.tex", "max_issues_repo_name": "JonGitti/Quantinder", "max_issues_repo_head_hexsha": "08d8e103a9e82b19ef569a8f6fc7f0120091291f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "quantinder/doc/chapters/chapter3.tex", "max_forks_repo_name": "JonGitti/Quantinder", "max_forks_repo_head_hexsha": "08d8e103a9e82b19ef569a8f6fc7f0120091291f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 146.4219653179, "max_line_length": 2071, "alphanum_fraction": 0.7759662074, "num_tokens": 6271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.31602342749415063}}
{"text": "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Copyright (c) 2003-2018 by The University of Queensland\n% http://www.uq.edu.au\n%\n% Primary Business: Queensland, Australia\n% Licensed under the Apache License, version 2.0\n% http://www.apache.org/licenses/LICENSE-2.0\n%\n% Development until 2012 by Earth Systems Science Computational Center (ESSCC)\n% Development 2012-2013 by School of Earth Sciences\n% Development from 2014 by Centre for Geoscience Computing (GeoComp)\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\chapter{The \\escript Module}\\label{ESCRIPT CHAP}\n\n\\section{Concepts}\n\\escript is a \\PYTHON module that allows you to represent the values of\na function at points in a \\Domain in such a way that the function will\nbe useful for the Finite Element Method (FEM) simulation. It also\nprovides what we call a function space that describes how the data is\nused in the simulation. Stored along with the data is information\nabout the elements and nodes which will be used by the domain (e.g. \\finley).\n\n\\subsection{Function spaces}\nIn order to understand what we mean by the term 'function space',\nconsider that the solution of a partial differential\nequation\\index{partial differential equation} (PDE) is a function on a domain\n$\\Omega$.  When solving a PDE using FEM, the solution is\npiecewise-differentiable but, in general, its gradient is discontinuous.\nTo reflect these different degrees of smoothness, different function spaces\nare used.\nFor instance, in FEM, the displacement field is represented by its values at\nthe nodes of the mesh, and so is continuous.\nThe strain, which is the symmetric part of the gradient of the displacement\nfield, is stored on the element centers, and so is considered to be\ndiscontinuous.\n\nA function space is described by a \\FunctionSpace object.\nThe following statement generates the object \\var{solution_space} which is\na \\FunctionSpace object and provides access to the function space of\nPDE solutions on the \\Domain \\var{mydomain}:\n\n\\begin{python}\n  solution_space=Solution(mydomain)\n\\end{python}\nThe following generators for function spaces on a \\Domain \\var{mydomain} are commonly used:\n\\begin{itemize}\n\\item \\var{Solution(mydomain)}: solutions of a PDE\n\\item \\var{ReducedSolution(mydomain)}: solutions of a PDE with a reduced\n    smoothness requirement, e.g. using a lower order approximation on the same\n    element or using macro elements\\index{macro elements}\n\\item \\var{ContinuousFunction(mydomain)}: continuous functions, e.g. a temperature distribution\n\\item \\var{Function(mydomain)}: general functions which are not necessarily continuous, e.g. a stress field\n\\item \\var{FunctionOnBoundary(mydomain)}: functions on the boundary of the domain, e.g. a surface pressure\n\\item \\var{DiracDeltaFunctions(mydomain)}: functions defined on a set of points\n\\item \\var{FunctionOnContact0(mydomain)}: functions on side $0$ of a discontinuity\n\\item \\var{FunctionOnContact1(mydomain)}: functions on side $1$ of a discontinuity\n\\end{itemize}\nIn some cases under-integration is used. For these cases the user may use a\n\\FunctionSpace from the following list:\n\\begin{itemize}\n\\item \\var{ReducedFunction(mydomain)}\n\\item \\var{ReducedFunctionOnBoundary(mydomain)}\n\\item \\var{ReducedFunctionOnContact0(mydomain)}\n\\item \\var{ReducedFunctionOnContact1(mydomain)}\n\\end{itemize}\nIn comparison to the corresponding full version they use a reduced number of\nintegration nodes (typically one only) to represent values.\n\n\\begin{figure}\n\\centering\n\\scalebox{0.97}{\\includegraphics{EscriptDiagram1}}\n\\caption{\\label{ESCRIPT DEP}Dependency of function spaces in \\finley.\nAn arrow indicates that a function in the \\FunctionSpace at the starting point\ncan be interpolated to the \\FunctionSpace of the arrow target.\nAll function spaces above the dotted line can be interpolated to any of\nthe function spaces below the line. See also \\Sec{SEC Projection}.}\n\\end{figure}\n\nThe reduced smoothness for a PDE solution is often used to fulfill the\nLadyzhenskaya-Babuska-Brezzi condition~\\cite{LBB} when solving saddle point\nproblems\\index{saddle point problems}, e.g. the Stokes equation.\nA discontinuity\\index{discontinuity} is a region within the domain across\nwhich functions may be discontinuous.\nThe location of a discontinuity is defined in the \\Domain object.\n\\fig{ESCRIPT DEP} shows the dependency between the types of function spaces\nin \\finley (other libraries may have different relationships).\n\nThe solution of a PDE is a continuous function. Any continuous function can\nbe seen as a general function on the domain and can be restricted to the\nboundary as well as to one side of a discontinuity (the result will be\ndifferent depending on which side is chosen). Functions on any side of the\ndiscontinuity can be seen as a function on the corresponding other side.\n\nA function on the boundary or on one side of the discontinuity cannot be seen\nas a general function on the domain as there are no values defined for the\ninterior. For most PDE solver libraries the space of the solution and\ncontinuous functions is identical, however in some cases, for example when\nperiodic boundary conditions are used in \\finley, a solution fulfills periodic\nboundary conditions while a continuous function does not have to be periodic.\n\nThe concept of function spaces describes the properties of functions and\nallows abstraction from the actual representation of the function in the\ncontext of a particular application. For instance, in the FEM context a\nfunction of the \\Function type (written as \\emph{Function()} in \\fig{ESCRIPT DEP})\nis usually represented by its values at the element center,\nbut in a finite difference scheme the edge midpoint of cells is preferred.\nBy changing its function space you can use the same function in a Finite\nDifference scheme instead of Finite Element scheme.\nChanging the function space of a particular function will typically lead to\na change of its representation.\nSo, when seen as a general function, a continuous function which is typically\nrepresented by its values on the nodes of the FEM mesh or finite difference\ngrid must be interpolated to the element centers or the cell edges,\nrespectively. Interpolation happens automatically in \\escript whenever it is\nrequired\\index{interpolation}. The user needs to be aware that an\ninterpolation is not always possible, see \\fig{ESCRIPT DEP} for \\finley.\nAn alternative approach to change the representation (=\\FunctionSpace) is\nprojection\\index{projection}, see \\Sec{SEC Projection}.\n\n\\subsection{\\Data Objects}\nIn \\escript the class that stores these functions is called \\Data.\nThe function is represented through its values on \\DataSamplePoints where\nthe \\DataSamplePoints are chosen according to the function space of the\nfunction.\n\\Data class objects are used to define the coefficients of the PDEs to be\nsolved by a PDE solver library and also to store the solutions of the PDE.\n\nThe values of the function have a rank which gives the number of indices,\nand a \\Shape defining the range of each index.\nThe rank in \\escript is limited to the range 0 through 4 and it is assumed\nthat the rank and \\Shape is the same for all \\DataSamplePoints.\nThe \\Shape of a \\Data object is a tuple (list) \\var{s} of integers.\nThe length of \\var{s} is the rank of the \\Data object and the \\var{i}-th\nindex ranges between 0 and $\\var{s[i]}-1$.\nFor instance, a stress field has rank 2 and \\Shape $(d,d)$ where $d$ is the\nnumber of spatial dimensions.\nThe following statement creates the \\Data object \\var{mydat} representing a\ncontinuous function with values of \\Shape $(2,3)$ and rank $2$:\n\\begin{python}\n  mydat=Data(value=1, what=ContinuousFunction(myDomain), shape=(2,3))\n\\end{python}\nThe initial value is the constant 1 for all \\DataSamplePoints and all\ncomponents.\n\n\\Data objects can also be created from any \\numpy array or any object, such\nas a list of floating point numbers, that can be converted into\na \\numpyNDA\\cite{NUMPY}.\nThe following two statements create objects which are equivalent\nto \\var{mydat}:\n\\begin{python}\n  mydat1=Data(value=numpy.ones((2,3)), what=ContinuousFunction(myDomain))\n  mydat2=Data(value=[[1,1], [1,1], [1,1]], what=ContinuousFunction(myDomain))\n\\end{python}\nIn the first case the initial value is \\var{numpy.ones((2,3))} which generates\na $2 \\times 3$ matrix as an instance of \\numpyNDA filled with ones.\nThe \\Shape of the created \\Data object is taken from the \\Shape of the array.\nIn the second case, the creator converts the initial value, which is a list of\nlists, into a \\numpyNDA before creating the actual \\Data object.\n\nFor convenience \\escript provides creators for the most common types\nof \\Data objects in the following forms (\\var{d} defines the spatial\ndimensionality):\n\\begin{itemize}\n\\item \\code{Scalar(0, Function(mydomain))} is the same as \\code{Data(0, Function(myDomain),(,))}\\\\\n    (each value is a scalar), e.g. a temperature field\n\\item \\code{Vector(0, Function(mydomain))} is the same as \\code{Data(0, Function(myDomain),(d,))}\\\\\n    (each value is a vector), e.g. a velocity field\n\\item \\code{Tensor(0, Function(mydomain))} equals \\code{Data(0, Function(myDomain), (d,d))},\n    e.g. a stress field\n\\item \\code{Tensor4(0,Function(mydomain))} equals \\code{Data(0,Function(myDomain), (d,d,d,d))},\n    e.g. a Hook tensor field\n\\item \\code{ComplexScalar(0+0j, Function(mydomain))} is the same as \\\\\n    \\code{ComplexData(0+0j, Function(myDomain),(,))}\n    (each value is a complex scalar), e.g. a temperature field\n\\item \\code{ComplexVector(0+0j, Function(mydomain))} is the same as \\\\\n    \\code{ComplexData(0+0j, Function(myDomain),(d,))}\n    (each value is a complex vector), e.g. a velocity field\n\\item \\code{ComplexTensor(0+0j, Function(mydomain))} is the same as \\\\\n\\code{ComplexData(0+0j, Function(myDomain), (d,d))}, e.g. a stress field\n\\item \\code{ComplexTensor4(0+0j,Function(mydomain))} is the same as \\\\\n\\code{ComplexData(0+0j,Function(myDomain), (d,d,d,d))}, e.g. a Hook tensor field\n\\end{itemize}\nHere the initial value is 0 but any object that can be converted into\na \\numpyNDA and whose \\Shape is consistent with \\Shape of the \\Data object to\nbe created can be used as the initial value.\n\n\\Data objects can be manipulated by applying unary operations (e.g. cos, sin,\nlog), and they can be combined point-wise by applying arithmetic operations\n(e.g. +, - ,* , /).\nWe emphasize that \\escript itself does not handle any spatial dependencies as\nit does not know how values are interpreted by the processing PDE solver library.\nHowever \\escript invokes interpolation if this is needed during data manipulations.\nTypically, this occurs in binary operations when the arguments belong to\ndifferent function spaces or when data are handed over to a PDE solver library\nwhich requires functions to be represented in a particular way.\n\nThe following example shows the usage of \\Data objects. Assume we have a\ndisplacement field $u$ and we want to calculate the corresponding stress field\n$\\sigma$ using the linear-elastic isotropic material model\n\\begin{eqnarray}\\label{eq: linear elastic stress}\n\\sigma_{ij}=\\lambda u_{k,k} \\delta_{ij} + \\mu ( u_{i,j} + u_{j,i})\n\\end{eqnarray}\nwhere $\\delta_{ij}$ is the Kronecker symbol and\n$\\lambda$ and $\\mu$ are the Lam\\'e coefficients. The following function\ntakes the displacement \\var{u} and the Lam\\'e coefficients \\var{lam} and \\var{mu}\nas arguments and returns the corresponding stress:\n\\begin{python}\n  from esys.escript import *\n  def getStress(u, lam, mu):\n    d=u.getDomain().getDim()\n    g=grad(u)\n    stress=lam*trace(g)*kronecker(d)+mu*(g+transpose(g))\n    return stress\n\\end{python}\nThe variable \\var{d} gives the spatial dimensionality of the domain on which\nthe displacements are defined.\nThe \\code{kronecker(d)} call, returns the Kronecker symbol with indices $i$ and $j$ running\nfrom 0 to \\var{d}-1.\nThe \\var{grad(u)} call, requires the displacement field \\var{u} to be in\nthe \\var{Solution} or \\ContinuousFunction.\nThe result \\var{g} as well as the returned stress will be in the \\Function.\nIf, for example, \\var{u} is the solution of a PDE then \\code{getStress} might\nbe called in the following way:\n\\begin{python}\n  s=getStress(u, 1., 2.)\n\\end{python}\nHowever \\code{getStress} can also be called with \\Data objects as values for\n\\var{lam} and \\var{mu} which, for instance in the case of a temperature\ndependency, are calculated by an expression.\nThe following call is equivalent to the previous example:\n\\begin{python}\n  lam=Scalar(1., ContinuousFunction(mydomain))\n  mu=Scalar(2., Function(mydomain))\n  s=getStress(u, lam, mu)\n\\end{python}\n%\nThe function \\var{lam} belongs to the \\ContinuousFunction but with \\var{g} the\nfunction \\var{trace(g)} is in the \\Function.\nIn the evaluation of the product \\var{lam*trace(g)} we have different function\nspaces (on the nodes versus in the centers) and at first glance we have incompatible data.\n\\escript converts the arguments into an appropriate function space according\nto \\fig{ESCRIPT DEP}.\nIn this example that means \\escript sees \\var{lam} as a function of the \\Function.\nIn the context of FEM this means the nodal values of \\var{lam} are\ninterpolated to the element centers.\nThe interpolation is automatic and requires no special handling.\n\n\\begin{figure}\n\\centering\n\\includegraphics{EscriptDiagram2}\n\\caption{\\label{Figure: tag}Element Tagging. A rectangular mesh over a region\nwith two rock types {\\it white} and {\\it gray} is shown.\nThe number in each cell refers to the major rock type present in the cell\n($1$ for {\\it white} and $2$ for {\\it gray}).}\n\\end{figure}\n\n\\subsection{Tagged, Expanded and Constant Data}\nMaterial parameters such as the Lam\\'e coefficients are typically dependent on\nrock types present in the area of interest.\nA common technique to handle these kinds of material parameters is\n\\emph{tagging}\\index{tagging}, which uses storage efficiently.\n\\fig{Figure: tag} shows an example. In this case two rock types {\\it white}\nand {\\it gray} can be found in the domain.\nThe domain is subdivided into triangular shaped cells.\nEach cell has a tag indicating the rock type predominantly found in this cell.\nHere $1$ is used to indicate rock type {\\it white} and $2$ for rock type {\\it gray}.\nThe tags are assigned at the time when the cells are generated and stored in\nthe \\Domain class object. To allow easier usage of tags, names can be used\ninstead of numbers. These names are typically defined at the time when the\ngeometry is generated.\n\nThe following statements show how to use tagged values for \\var{lam} as shown\nin \\fig{Figure: tag} for the stress calculation discussed above:\n\\begin{python}\n  lam=Scalar(value=2., what=Function(mydomain))\n  insertTaggedValue(lam, white=30., gray=5000.)\n  s=getStress(u, lam, 2.)\n\\end{python}\nIn this example \\var{lam} is set to $30$ for those cells with tag {\\it white}\n(=$1$) and to $5000$ for cells with tag {\\it gray} (=$2$).\nThe initial value $2$ of \\var{lam} is used as a default value for the case\nwhen a tag is encountered which has not been linked with a value.\nThe \\code{getStress} method does not need to be changed now that we are using tags.\n\\escript resolves the tags when \\var{lam*trace(g)} is calculated.\n\nThis brings us to a very important point about \\escript.\nYou can develop a simulation with constant Lam\\'e coefficients, and then later\nswitch to tagged Lam\\'e coefficients without otherwise changing your \\PYTHON script.\nIn short, you can use the same script for models with different domains and\ndifferent types of input data.\n\nThere are three main ways in which \\Data objects are represented internally --\nconstant, tagged, and expanded.\nIn the constant case, the same value is used at each sample point while only a\nsingle value is stored to save memory.\nIn the expanded case, each sample point has an individual value (such as for the solution of a PDE).\nThis is where your largest data sets will be created because the values are\nstored as a complete array.\nThe tagged case has already been discussed above.\nExpanded data is created when specifying \\code{expanded=True} in the \\Data\nobject constructor, while tagged data requires calling the \\member{insertTaggedValue}\nmethod as shown above.\n\nValues are accessed through a sample reference number.\nOperations on expanded \\Data objects have to be performed for each sample\npoint individually.\nWhen tagged values are used, the values are held in a dictionary.\nOperations on tagged data require processing the set of tagged values only,\nrather than processing the value for each individual sample point.\n\\escript allows any mixture of constant, tagged and expanded data in a single expression.\n\n\\subsection{Saving and Restoring Simulation Data}\n\\Data objects can be written to disk files with the \\member{dump} method and\nread back using the \\member{load} method, both of which use the\n\\netCDF\\cite{NETCDF} file format.\nUse these to save data for checkpoint/restart or simply to save and reuse data\nthat was expensive to compute.\nFor instance, to save the coordinates of the data points of a\n\\ContinuousFunction to the file \\file{x.nc} use\n\\begin{python}\n  x=ContinuousFunction(mydomain).getX()\n  x.dump(\"x.nc\")\n  mydomain.dump(\"dom.nc\")\n\\end{python}\nTo recover the object \\var{x}, and you know that \\var{mydomain} was an \\finley\nmesh, use\n\\begin{python}\n  from esys.finley import LoadMesh\n  mydomain=LoadMesh(\"dom.nc\")\n  x=load(\"x.nc\", mydomain)\n\\end{python}\nObviously, it is possible to execute the same steps that were originally used\nto generate \\var{mydomain} to recreate it. However, in most cases using\n\\member{dump} and \\member{load} is faster, particularly if optimization has\nbeen applied.\nIf \\escript is running on more than one \\MPI process \\member{dump} will create\nan individual file for each process containing the local data.\nIn order to avoid conflicts the \\MPI processor\nrank is appended to the file names.\nThat is instead of one file \\file{dom.nc} you would get\n\\file{dom.nc.0000}, \\file{dom.nc.0001}, etc.\nYou still call \\code{LoadMesh(\"dom.nc\")} to load the domain but you have to\nmake sure that the appropriate file is accessible from the corresponding rank,\nand loading will only succeed if you run with as many processes as were used\nwhen calling \\member{dump}.\n\nThe function space of the \\Data is stored in \\file{x.nc}.\nIf the \\Data object is expanded, the number of data points in the file and of\nthe \\Domain for the particular \\FunctionSpace must match.\nMoreover, the ordering of the values is checked using the reference\nidentifiers provided by the \\FunctionSpace on the \\Domain.\nIn some cases, data points will be reordered so be aware and confirm that you\nget what you wanted.\n\nA more flexible way of saving and restoring \\escript simulation data\nis through an instance of the \\class{DataManager} class.\nIt has the advantage of allowing to save and load not only a \\Domain and\n\\Data objects but also other values\\footnote{The \\PYTHON \\emph{pickle} module\nis used for other types.} you compute in your simulation script.\nFurther, \\class{DataManager} objects can simultaneously create files for\nvisualization so no extra calls to \\code{saveVTK} etc. are needed.\n\nThe following example shows how the \\class{DataManager} class can be used.\nFor an explanation of all member functions and options see the class reference\nSection \\ref{sec:datamanager}.\n\\begin{python}\n  from esys.escript import DataManager, Scalar, Function\n  from esys.finley import Rectangle\n\n  dm = DataManager(formats=[DataManager.RESTART, DataManager.VTK])\n  if dm.hasData():\n    mydomain=dm.getDomain()\n    val=dm.getValue(\"val\")\n    t=dm.getValue(\"t\")\n    t_max=dm.getValue(\"t_max\")\n  else:\n    mydomain=Rectangle()\n    val=Function(mydomain).getX()\n    t=0.\n    t_max=2.5\n\n  while t<t_max:\n    t+=.01\n    val=val+t/2\n    dm.addData(val=val, t=t, t_max=t_max)\n    dm.export()\n\\end{python}\nIn the constructor we specify that we want \\code{RESTART} (i.e. dump) files\nand \\code{VTK} files to be saved.\nBy default, the constructor will look for previously saved \\code{RESTART}\nfiles under the current directory and load them.\nWe can then enquire if such files were found by calling the \\member{hasData}\nmethod. If it returns \\True we retrieve the domain and values into local\nvariables. Otherwise the same variables are initialized with appropriate\nvalues to start a new simulation.\nNote, that \\var{t} and \\var{t_max} are regular floating point values and not\n\\Data objects. Yet they are treated the same way by the \\class{DataManager}.\n\nAfter this initialization step the script enters the main simulation loop\nwhere calculations are performed.\nWhen these are finalized for a time step we call the \\member{addData} method\nto let the manager know which variables to store on disk.\nThis does not actually save the data yet and it is allowed to call\n\\member{addData} more than once to add information incrementally, e.g. from\nseparate functions that have access to the \\class{DataManager} instance.\nOnce all variables have been added the \\member{export} method has to be called\nto flush all data to disk and clear the manager.\nIn this example, this call dumps \\var{mydomain} and \\var{val} to files\nin a restart directory and also stores \\var{t} and \\var{t_max} on disk.\nAdditionally, it generates a \\VTK file for visualization of the data.\nIf the script would stop running before its completion for some reason (e.g.\nbecause its runtime limit was exceeded in a batch job environment), you could\nsimply run it again and it would resume at the point it stopped before.\n\n\\section{\\escript Classes}\n\n\\subsection{The \\Domain class}\n\\begin{classdesc}{Domain}{}\nA \\Domain object is used to describe a geometric region together with\na way of representing functions over this region.\nThe \\Domain class provides an abstract interface to the domain of \\FunctionSpace and \\Data objects.\n\\Domain needs to be subclassed in order to provide a complete implementation.\n\\end{classdesc}\n\n\\vspace{1em}\\noindent The following methods are available:\n\\begin{methoddesc}[Domain]{getDim}{}\n    returns the number of spatial dimensions of the \\Domain.\n\\end{methoddesc}\n%\n\\begin{methoddesc}[Domain]{dump}{filename}\n    writes the \\Domain to the file \\var{filename} using the \\netCDF file format.\n\\end{methoddesc}\n%\n\\begin{methoddesc}[Domain]{getX}{}\n    returns the locations in the \\Domain. The \\FunctionSpace of the returned\n    \\Data object is chosen by the \\Domain implementation. Typically it will be\n    in the \\ContinuousFunction.\n\\end{methoddesc}\n\n\\begin{methoddesc}[Domain]{getNumpyX}{}\n    returns the locations in the \\Domain as a \\numpy ndarray. The \\FunctionSpace\n    of the returned \\Data object is chosen by the \\Domain implementation.\n    Typically it will be in the \\ContinuousFunction.\n\n    Note that it is necessary to load \\numpy first in the escript.\n\\end{methoddesc}\n%\n\\begin{methoddesc}[Domain]{setX}{newX}\n    assigns new locations to the \\Domain. \\var{newX} has to have \\Shape $(d,)$\n    where $d$ is the spatial dimensionality of the domain. Typically \\var{newX}\n    must be in the \\ContinuousFunction but the space actually to be used\n    depends on the \\Domain implementation. Not all domain families support\n    setting locations.\n\\end{methoddesc}\n%\n\\begin{methoddesc}[Domain]{getNormal}{}\n    returns the surface normals on the boundary of the \\Domain as a \\Data object.\n\\end{methoddesc}\n%\n\\begin{methoddesc}[Domain]{getSize}{}\n    returns the local sample size, i.e. the element diameter, as a \\Data object.\n\\end{methoddesc}\n%\n\\begin{methoddesc}[Domain]{setTagMap}{tag_name, tag}\n    defines a mapping of the tag name \\var{tag_name} to the \\var{tag}.\n\\end{methoddesc}\n%\n\\begin{methoddesc}[Domain]{getTag}{tag_name}\n    returns the tag associated with the tag name \\var{tag_name}.\n\\end{methoddesc}\n%\n\\begin{methoddesc}[Domain]{isValidTagName}{tag_name}\n    returns \\True if \\var{tag_name} is a valid tag name.\n\\end{methoddesc}\n%\n\\begin{methoddesc}[Domain]{__eq__}{arg}\n    (\\PYTHON \\var{==} operator) returns \\True if the \\Domain \\var{arg}\n    describes the same domain, \\False otherwise.\n\\end{methoddesc}\n%\n\\begin{methoddesc}[Domain]{__ne__}{arg}\n    (\\PYTHON \\var{!=} operator) returns \\True if the \\Domain \\var{arg} does\n    not describe the same domain, \\False otherwise.\n\\end{methoddesc}\n%\n\\begin{methoddesc}[Domain]{__str__}{}\n    (\\PYTHON \\var{str()} function) returns a string representation of the\n    \\Domain.\n\\end{methoddesc}\n%\n\\begin{methoddesc}[Domain]{onMasterProcessor}{}\n    returns \\True if the process is the master process within the \\MPI\n    process group used by the \\Domain. This is the process with rank 0.\n    If \\MPI support is not enabled the return value is always \\True.\n\\end{methoddesc}\n%\n\\begin{methoddesc}[Domain]{getMPISize}{}\n    returns the number of \\MPI processes used for this \\Domain. If \\MPI\n    support is not enabled 1 is returned.\n\\end{methoddesc}\n%\n\\begin{methoddesc}[Domain]{getMPIRank}{}\n    returns the rank of the process executing the statement within the\n    \\MPI process group used by the \\Domain. If \\MPI support is not enabled\n    0 is returned.\n\\end{methoddesc}\n%\n\\begin{methoddesc}[Domain]{MPIBarrier}{}\n    executes barrier synchronization within the \\MPI process group used by\n    the \\Domain. If \\MPI support is not enabled, this command does nothing.\n\\end{methoddesc}\n\n\\subsection{The \\FunctionSpace class}\n\\begin{classdesc}{FunctionSpace}{}\n\\FunctionSpace objects, which are instantiated by generator functions, are\nused to define properties of \\Data objects such as continuity.\nA \\Data object in a particular \\FunctionSpace is represented by its values at\n\\DataSamplePoints which are defined by the type and the \\Domain of the \\FunctionSpace.\n\\end{classdesc}\n\n\\vspace{1em}\\noindent The following methods are available:\n%\n\\begin{methoddesc}[FunctionSpace]{getDim}{}\n    returns the spatial dimensionality of the \\Domain of the \\FunctionSpace.\n\\end{methoddesc}\n%\n\\begin{methoddesc}[FunctionSpace]{getX}{}\n    returns the location of the \\DataSamplePoints.\n\\end{methoddesc}\n%\n\\begin{methoddesc}[FunctionSpace]{getNormal}{}\n    If the domain of functions in the \\FunctionSpace is a hyper-manifold (e.g.\n    the boundary of a domain) the method returns the outer normal at each of\n    the \\DataSamplePoints. Otherwise an exception is raised.\n\\end{methoddesc}\n%\n\\begin{methoddesc}[FunctionSpace]{getSize}{}\n    returns a \\Data object measuring the spacing of the \\DataSamplePoints.\n    The size may be zero.\n\\end{methoddesc}\n%\n\\begin{methoddesc}[FunctionSpace]{getDomain}{}\n    returns the \\Domain of the \\FunctionSpace.\n\\end{methoddesc}\n%\n\\begin{methoddesc}[FunctionSpace]{setTags}{new_tag, mask}\n    assigns a new tag \\var{new_tag} to all data samples where \\var{mask} is\n    positive for a least one data point.\n    \\var{mask} must be defined on this \\FunctionSpace.\n    Use the \\var{setTagMap} to assign a tag name to \\var{new_tag}.\n\\end{methoddesc}\n%\n\\begin{methoddesc}[FunctionSpace]{__eq__}{arg}\n    (\\PYTHON \\var{==} operator) returns \\True if the \\FunctionSpace \\var{arg}\n    describes the same function space, \\False otherwise.\n\\end{methoddesc}\n%\n\\begin{methoddesc}[FunctionSpace]{__ne__}{arg}\n    (\\PYTHON \\var{!=} operator) returns \\True if the \\FunctionSpace \\var{arg}\n    does not describe the same function space, \\False otherwise.\n\\end{methoddesc}\n\n\\begin{methoddesc}[Domain]{__str__}{}\n    (\\PYTHON \\var{str()} function) returns a string representation of the\n    \\FunctionSpace.\n\\end{methoddesc}\n\n\\noindent The following functions provide generators for \\FunctionSpace objects:\n\n\\begin{funcdesc}{Function}{domain}\n    returns the \\Function on the \\Domain \\var{domain}. \\Data objects in this\n    type of \\Function are defined over the whole geometric region defined by\n    \\var{domain}.\n\\end{funcdesc}\n%\n\\begin{funcdesc}{ContinuousFunction}{domain}\n    returns the \\ContinuousFunction on the \\Domain domain. \\Data objects in\n    this type of \\Function are defined over the whole geometric region defined\n    by \\var{domain} and assumed to represent a continuous function.\n\\end{funcdesc}\n%\n\\begin{funcdesc}{FunctionOnBoundary}{domain}\n    returns the \\FunctionOnBoundary on the \\Domain domain. \\Data objects in\n    this type of \\Function are defined on the boundary of the geometric region\n    defined by \\var{domain}.\n\\end{funcdesc}\n%\n\\begin{funcdesc}{FunctionOnContactZero}{domain}\n    returns the \\FunctionOnContactZero the \\Domain domain. \\Data objects in\n    this type of \\Function are defined on side 0 of a discontinuity  within\n    the geometric region defined by \\var{domain}.\n    The discontinuity is defined when \\var{domain} is instantiated.\n\\end{funcdesc}\n%\n\\begin{funcdesc}{FunctionOnContactOne}{domain}\n    returns the \\FunctionOnContactOne on the \\Domain domain. \\Data objects in\n    this type of \\Function are defined on side 1 of a discontinuity within\n    the geometric region defined by \\var{domain}.\n    The discontinuity is defined when \\var{domain} is instantiated.\n\\end{funcdesc}\n%\n\\begin{funcdesc}{Solution}{domain}\n    returns the \\SolutionFS on the \\Domain domain. \\Data objects in this type\n    of \\Function are defined on the geometric region defined by \\var{domain}\n    and are solutions of partial differential equations\\index{partial differential equation}.\n\\end{funcdesc}\n%\n\\begin{funcdesc}{ReducedSolution}{domain}\n    returns the \\ReducedSolutionFS on the \\Domain domain. \\Data objects in\n    this type of \\Function are defined on the geometric region defined by\n    \\var{domain} and are solutions of partial differential\n    equations\\index{partial differential equation} with a reduced smoothness\n    for the solution approximation.\n\\end{funcdesc}\n\n\\subsection{The \\Data Class}\n\\label{SEC ESCRIPT DATA}\n\nThe following table shows arithmetic operations that can be performed\npoint-wise on \\Data objects:\n\\begin{center}\n    \\begin{tabular}{l|l}\n        \\textbf{Expression} & \\textbf{Description}\\\\\n        \\hline\n        \\code{+arg} & identical to \\var{arg}\\index{+}\\\\\n        \\code{-arg} & negation of \\var{arg}\\index{-}\\\\\n        \\code{arg0+arg1} & adds \\var{arg0} and \\var{arg1}\\index{+}\\\\\n        \\code{arg0*arg1} & multiplies \\var{arg0} and \\var{arg1}\\index{*}\\\\\n        \\code{arg0-arg1} & subtracts \\var{arg1} from \\var{arg0}\\index{-}\\\\\n        \\code{arg0/arg1} & divides \\var{arg0} by \\var{arg1}\\index{/}\\\\\n        \\code{arg0**arg1} & raises \\var{arg0} to the power of \\var{arg1}\\index{**}\\\\\n    \\end{tabular}\n\\end{center}\nAt least one of the arguments \\var{arg0} or \\var{arg1} must be a \\Data object.\nEither of the arguments may be a \\Data object, a \\PYTHON number or a \\numpy\nobject.\nIf \\var{arg0} or \\var{arg1} are not defined on the same \\FunctionSpace, then\nan attempt is made to convert \\var{arg0} to the \\FunctionSpace of \\var{arg1}\nor to convert \\var{arg1} to \\var{arg0}'s \\FunctionSpace.\nBoth arguments must have the same \\Shape or one of the arguments may be of\nrank 0 (a constant).\nThe returned \\Data object has the same \\Shape and is defined on\nthe \\DataSamplePoints as \\var{arg0} or \\var{arg1}.\n\nThe following table shows the update operations that can be applied to\n\\Data objects:\n\\begin{center}\n    \\begin{tabular}{l|l}\n        \\textbf{Expression} & \\textbf{Description}\\\\\n        \\hline\n        \\code{arg0+=arg1} & adds \\var{arg1} to \\var{arg0}\\index{+}\\\\\n        \\code{arg0*=arg1} & multiplies \\var{arg0} by \\var{arg1}\\index{*}\\\\\n        \\code{arg0-=arg1} & subtracts \\var{arg1} from\\var{arg0}\\index{-}\\\\\n        \\code{arg0/=arg1} & divides \\var{arg0} by \\var{arg1}\\index{/}\\\\\n        \\code{arg0**=arg1} & raises \\var{arg0} to the power of \\var{arg1}\\index{**}\\\\\n    \\end{tabular}\n\\end{center}\n\\var{arg0} must be a \\Data object. \\var{arg1} must be a \\Data object or an\nobject that can be converted into a \\Data object.\n\\var{arg1} must have the same \\Shape as \\var{arg0} or have rank 0.\nIn the latter case it is assumed that the values of \\var{arg1} are constant\nfor all components. \\var{arg1} must be defined in the same \\FunctionSpace as\n\\var{arg0} or it must be possible to interpolate \\var{arg1} onto the\n\\FunctionSpace of \\var{arg0}.\n\nThe \\Data class supports taking slices as well as assigning new values to a\nslice of an existing \\Data object\\index{slicing}.\nThe following expressions for taking and setting slices are valid:\n\\begin{center}\n    \\begin{tabular}{l|ll}\n        \\textbf{Rank of \\var{arg}} & \\textbf{Slicing expression} & \\textbf{\\Shape of returned and assigned object}\\\\\n        \\hline\n        0 & no slicing & N/A\\\\\n        1 & \\var{arg[l0:u0]} & (\\var{u0}-\\var{l0},)\\\\\n        2 & \\var{arg[l0:u0,l1:u1]} & (\\var{u0}-\\var{l0},\\var{u1}-\\var{l1})\\\\\n        3 & \\var{arg[l0:u0,l1:u1,l2:u2]} & (\\var{u0}-\\var{l0},\\var{u1}-\\var{l1},\\var{u2}-\\var{l2})\\\\\n        4 & \\var{arg[l0:u0,l1:u1,l2:u2,l3:u3]} & (\\var{u0}-\\var{l0},\\var{u1}-\\var{l1},\\var{u2}-\\var{l2},\\var{u3}-\\var{l3})\\\\\n    \\end{tabular}\n\\end{center}\nLet \\var{s} be the \\Shape of \\var{arg}, then\n\\begin{align*}\n0 \\le \\var{l0} \\le \\var{u0} \\le \\var{s[0]},\\\\\n0 \\le \\var{l1} \\le \\var{u1} \\le \\var{s[1]},\\\\\n0 \\le \\var{l2} \\le \\var{u2} \\le \\var{s[2]},\\\\\n0 \\le \\var{l3} \\le \\var{u3} \\le \\var{s[3]}.\n\\end{align*}\nAny of the lower indexes \\var{l0}, \\var{l1}, \\var{l2} and \\var{l3} may not be\npresent in which case $0$ is assumed.\nAny of the upper indexes \\var{u0}, \\var{u1}, \\var{u2} and \\var{u3} may be\nomitted, in which case the upper limit for that dimension is assumed.\nThe lower and upper index may be identical in which case the column and the\nlower or upper index may be dropped.\nIn the returned or in the object assigned to a slice, the corresponding\ncomponent is dropped, i.e. the rank is reduced by one in comparison to \\var{arg}.\nThe following examples show slicing in action:\n\\begin{python}\n  t=Data(1., (4,4,6,6), Function(mydomain))\n  t[1,1,1,0]=9.\n  s=t[:2,:,2:6,5] # s has rank 3\n  s[:,:,1]=1.\n  t[:2,:2,5,5]=s[2:4,1,:2]\n\\end{python}\n\n\n\\subsection{Generation of \\Data objects}\n\\begin{classdesc}{Data}{value=0, shape=(,), what=FunctionSpace(), expanded=\\False}\ncreates a \\Data object with \\Shape \\var{shape} in the \\FunctionSpace \\var{what}.\nThe values at all \\DataSamplePoints are set to the double value \\var{value}.\nIf \\var{expanded} is \\True the \\Data object is represented in expanded form.\n\\end{classdesc}\n\n\\begin{classdesc}{Data}{value, what=FunctionSpace(), expanded=\\False}\ncreates a \\Data object in the \\FunctionSpace \\var{what}.\nThe value for each data sample point is set to \\var{value}, which could be a\n\\numpy object, \\Data object or a dictionary of \\numpy or floating point\nnumbers. In the latter case the keys must be integers and are used as tags.\nThe \\Shape of the returned object is equal to the \\Shape of \\var{value}.\nIf \\var{expanded} is \\True the \\Data object is represented in expanded form.\n\\end{classdesc}\n\n\\begin{classdesc}{Data}{}\ncreates an \\EmptyData object. The \\EmptyData object is used to indicate that\nan argument is not present where a \\Data object is required.\n\\end{classdesc}\n\n\\begin{funcdesc}{Scalar}{value=0., what=FunctionSpace(), expanded=\\False}\nreturns a \\Data object of rank 0 (a constant) in the \\FunctionSpace \\var{what}.\nValues are initialized with \\var{value}, a double precision quantity.\nIf \\var{expanded} is \\True the \\Data object is represented in expanded form.\n\\end{funcdesc}\n\n\\begin{funcdesc}{Vector}{value=0., what=FunctionSpace(), expanded=\\False}\nreturns a \\Data object of \\Shape \\var{(d,)} in the \\FunctionSpace \\var{what},\nwhere \\var{d} is the spatial dimension of the \\Domain of \\var{what}.\nValues are initialized with \\var{value}, a double precision quantity.\nIf \\var{expanded} is \\True the \\Data object is represented in expanded form.\n\\end{funcdesc}\n\n\\begin{funcdesc}{Tensor}{value=0., what=FunctionSpace(), expanded=\\False}\nreturns a \\Data object of \\Shape \\var{(d,d)} in the \\FunctionSpace \\var{what},\nwhere \\var{d} is the spatial dimension of the \\Domain of \\var{what}.\nValues are initialized with \\var{value}, a double precision quantity.\nIf \\var{expanded} is \\True the \\Data object is represented in expanded form.\n\\end{funcdesc}\n\n\\begin{funcdesc}{Tensor3}{value=0., what=FunctionSpace(), expanded=\\False}\nreturns a \\Data object of \\Shape \\var{(d,d,d)} in the \\FunctionSpace \\var{what},\nwhere \\var{d} is the spatial dimension of the \\Domain of \\var{what}.\nValues are initialized with \\var{value}, a double precision quantity.\nIf \\var{expanded} is \\True the \\Data object is represented in expanded form.\n\\end{funcdesc}\n\n\\begin{funcdesc}{Tensor4}{value=0., what=FunctionSpace(), expanded=\\False}\nreturns a \\Data object of \\Shape \\var{(d,d,d,d)} in the \\FunctionSpace \\var{what},\nwhere \\var{d} is the spatial dimension of the \\Domain of \\var{what}.\nValues are initialized with \\var{value}, a double precision quantity.\nIf \\var{expanded} is \\True the \\Data object is represented in expanded form.\n\\end{funcdesc}\n\n\\begin{funcdesc}{ComplexData}{value, what=FunctionSpace(), expanded=\\False}\ncreates a \\Data object in the \\FunctionSpace \\var{what}.\nThe value for each data sample point is set to the complex value \\var{value}, which could be a\n\\numpy object, \\Data object or a dictionary of \\numpy or floating point\nnumbers. In the latter case the keys must be integers and are used as tags.\nThe \\Shape of the returned object is equal to the \\Shape of \\var{value}.\nIf \\var{expanded} is \\True the \\Data object is represented in expanded form.\n\\end{funcdesc}\n\n\\begin{funcdesc}{ComplexData}{value=0, shape=(,), what=FunctionSpace(), expanded=\\False}\ncreates a \\Data object with \\Shape \\var{shape} in the \\FunctionSpace \\var{what}.\nThe values at all \\DataSamplePoints are set to the complex value \\var{value}.\nIf \\var{expanded} is \\True the \\Data object is represented in expanded form.\n\\end{funcdesc}\n\n\\begin{funcdesc}{ComplexData}{}\ncreates an \\EmptyData object with complex values (i.e. with memory allocated to\nstore a complex number). The \\EmptyData object is used to indicate that\nan argument is not present where a \\Data object is required.\n\\end{funcdesc}\n\n\\begin{funcdesc}{ComplexScalar}{value=0.+0.j, what=FunctionSpace(), expanded=\\False}\nreturns a \\Data object of rank 0 (a constant) in the \\FunctionSpace \\var{what}.\nValues are initialized with complex \\var{value}, a double precision quantity.\nIf \\var{expanded} is \\True the \\Data object is represented in expanded form.\n\\end{funcdesc}\n\n\\begin{funcdesc}{ComplexData}{value=0.+0.j, what=FunctionSpace(), expanded=\\False}\nreturns a \\Data object of \\Shape \\var{(d,)} in the \\FunctionSpace \\var{what},\nwhere \\var{d} is the spatial dimension of the \\Domain of \\var{what}.\nValues are initialized with complex \\var{value}, a double precision quantity.\nIf \\var{expanded} is \\True the \\Data object is represented in expanded form.\n\\end{funcdesc}\n\n\\begin{funcdesc}{ComplexTensor}{value=0.+0.j, what=FunctionSpace(), expanded=\\False}\nreturns a \\Data object of \\Shape \\var{(d,d)} in the \\FunctionSpace \\var{what},\nwhere \\var{d} is the spatial dimension of the \\Domain of \\var{what}.\nValues are initialized with complex \\var{value}, a double precision quantity.\nIf \\var{expanded} is \\True the \\Data object is represented in expanded form.\n\\end{funcdesc}\n\n\\begin{funcdesc}{ComplexTensor3}{value=0.+0.j, what=FunctionSpace(), expanded=\\False}\nreturns a \\Data object of \\Shape \\var{(d,d,d)} in the \\FunctionSpace \\var{what},\nwhere \\var{d} is the spatial dimension of the \\Domain of \\var{what}.\nValues are initialized with complex \\var{value}, a double precision quantity.\nIf \\var{expanded} is \\True the \\Data object is represented in expanded form.\n\\end{funcdesc}\n\n\\begin{funcdesc}{ComplexTensor4}{value=0.+0.j, what=FunctionSpace(), expanded=\\False}\nreturns a \\Data object of \\Shape \\var{(d,d,d,d)} in the \\FunctionSpace \\var{what},\nwhere \\var{d} is the spatial dimension of the \\Domain of \\var{what}.\nValues are initialized with complex \\var{value}, a double precision quantity.\nIf \\var{expanded} is \\True the \\Data object is represented in expanded form.\n\\end{funcdesc}\n\n\\begin{funcdesc}{load}{filename, domain}\nrecovers a \\Data object on \\Domain \\var{domain} from the file \\var{filename},\nwhich was created by \\function{dump}.\n\\end{funcdesc}\n\n\\subsection{Generating random \\Data objects}\nA \\Data object filled with random values can be produced using the\n\\function{RandomData} function.\nBy default values are drawn uniformly at random from the interval $[0,1]$ (i.e.\nincluding end points).\nThe function takes a shape for the data points and a \\FunctionSpace for the new\n\\Data as arguments.\nFor example:\n\\begin{python}\nfrom esys.finley import *\nfrom esys.escript import *\n\ndomain=Rectangle(11,11)\nfs=ContinuousFunction(domain)\nd=RandomData((), fs)\n\\end{python}\nwould result in \\var{d} being filled with scalar random data since \\texttt{()}\nis an empty tuple.\n\n\\begin{python}\nfrom esys.finley import *\nfrom esys.escript import *\n\ndomain=Rectangle(11,11)\nfs=ContinuousFunction(domain)\nd=RandomData((2,2), fs)\n\\end{python}\nwould give \\var{d} the same number of data points, but each point would be a\n$2\\times 2$ matrix instead of a scalar.\n\nBy default, the seed used to generate the random values will be different each\ntime.\nIf required, you can specify a seed to ensure the same sequence is produced.\n\\begin{python}\nfrom esys.dudley import *\nfrom esys.escript import *\n\nseed=-17171717\ndomain=Brick(10,10,10)\nfs=Function(domain)\nd=RandomData((2,2), fs, seed)\n\\end{python}\n\nThe \\var{seed} can be any integer value\\footnote{which can be converted to a\nC++ long} but 0 is special.\nA seed of zero will cause \\escript to use a different seed each time.\nAlso, note that the mechanism used to produce the random values could be\ndifferent in different releases.\n\n\\noindent\\textbf{Note for MPI users:}\n\\textsl{\nEven if you specify a seed, you will only get the same results if you are running with the same\nnumber of ranks.\nIf you change the number of ranks, you will get different values for the same seed.\n}\n\n\\subsubsection{Smoothed randoms}\nThe \\ripley domains (see Chapter \\ref{chap:ripley}) support generating random\nscalars which are smoothed using Gaussian blur.\nTo use this, you need to supply the radius of the filter kernel (in elements)\nand the \\var{sigma} value used in the filter.\nFor example:\n\\begin{python}\nfrom esys.ripley import *\nfrom esys.escript import *\n\nfs=ContinuousFunction(Rectangle(11,11, d1=2,d0=2))\nd=RandomData((), fs, 0, ('gaussian', 1, 0.5))\n\\end{python}\nwill use a filter that uses the immediate neighbours of each point with a sigma\nvalue of $0.5$.\nThe random values will be different each time this code is executed due to the\nseed of $0$.\n\nRipley's Gaussian smoothing has the following requirements:\n\\begin{enumerate}\n    \\item If \\MPI is in use, then each rank must have at least $5$ elements in\n          it \\emph{in each dimension}. This value increases as the radius of\n          the blur increases.\n    \\item The data being generated must be scalar. (You can generate random\n          data objects for \\ripley domains with whatever shape you require, you\n          just can't smooth them unless that shape is scalar).\n\\end{enumerate}\nAn exception will be raised if either of these requirements is not met.\n\nThe components of the matrix used in the kernal for the 2D case are\ndefined\\cite{gaussfilter} by:\n\n\\[ G(x,y) = \\frac{1}{2\\pi\\sigma^2} e^{-\\frac{x^2+y^2}{2\\sigma^2}} \\]\n\n\\noindent For the 3D case, we use:\n\n\\[ G(x,y) = \\frac{1}{(\\sqrt{2\\pi\\sigma^2})^3} e^{-\\frac{x^2+y^2+z^2}{2\\sigma^2}} \\]\n\nAll distances ($x$,$y$,$z$) refer to the number of points from the centre point.\nThat is, the closest neighbours have at least one distance of $1$, the next\n``ring'' of neighbours have at least one $2$ and so on.\nThe matrix is normalised before use.\n\n\\subsection{\\Data methods}\nThese are the most frequently used methods of the \\Data class.\nA complete list of methods can be found in the reference guide,\nsee \\ReferenceGuide.\n\n\\begin{methoddesc}[Data]{getFunctionSpace}{}\nreturns the \\FunctionSpace of the object.\n\\end{methoddesc}\n\n\\begin{methoddesc}[Data]{getDomain}{}\nreturns the \\Domain of the object.\n\\end{methoddesc}\n\n\\begin{methoddesc}[Data]{getShape}{}\nreturns the \\Shape of the object as a \\class{tuple} of integers.\n\\end{methoddesc}\n\n\\begin{methoddesc}[Data]{getRank}{}\nreturns the rank of the data on each data point\\index{rank}.\n\\end{methoddesc}\n\n\\begin{methoddesc}[Data]{isEmpty}{}\nreturns \\True if the \\Data object is the \\EmptyData object, \\False otherwise.\nNote that this is not the same as asking if the object contains no \\DataSamplePoints.\n\\end{methoddesc}\n\n\\begin{methoddesc}[Data]{setTaggedValue}{tag_name, value}\nassigns the \\var{value} to all \\DataSamplePoints which have the tag\nassigned to \\var{tag_name}. \\var{value} must be an object of class\n\\class{numpy.ndarray} or must be convertible into a \\class{numpy.ndarray} object.\n\\var{value} (or the corresponding \\class{numpy.ndarray} object) must be of\nrank $0$ or must have the same rank as the object.\nIf a value has already been defined for tag \\var{tag_name} within the object\nit is overwritten by the new \\var{value}. If the object is expanded,\nthe value assigned to \\DataSamplePoints with tag \\var{tag_name} is replaced by\n\\var{value}. If no value is assigned the tag name \\var{tag_name}, no value is set.\n\\end{methoddesc}\n\n\\begin{methoddesc}[Data]{dump}{filename}\ndumps the \\Data object to the file \\var{filename}. The file stores the\nfunction space but not the \\Domain. It is the responsibility of the user to\nsave the \\Domain in order to be able to recover the \\Data object.\n\\end{methoddesc}\n\n\\begin{methoddesc}[Data]{__str__}{}\nreturns a string representation of the object.\n\\end{methoddesc}\n\n\\subsection{Functions of \\Data objects}\nThis section lists the most important functions for \\Data class objects.\nA complete list and a more detailed description of the functionality can be\nfound on \\ReferenceGuide.\n\n\\begin{funcdesc}{kronecker}{d}\nreturns a \\RankTwo in \\FunctionSpace \\var{d} such that\n\\begin{equation}\n\\code{kronecker(d)}\\left[ i,j\\right] = \\left\\{\n\\begin{array}{l l}\n    1 & \\quad \\text{if $i=j$}\\\\\n    0 & \\quad \\text{otherwise}\n\\end{array}\n\\right.\n\\end{equation}\nIf \\var{d} is an integer a $(d,d)$ \\numpy array is returned.\n\\end{funcdesc}\n\n\\begin{funcdesc}{identityTensor}{d}\nis a synonym for \\code{kronecker} (see above).\n\\end{funcdesc}\n\n\\begin{funcdesc}{identityTensor4}{d}\nreturns a \\RankFour in \\FunctionSpace \\var{d} such that\n\\begin{equation}\n\\code{identityTensor(d)}\\left[ i,j,k,l\\right] = \\left\\{\n\\begin{array}{l l}\n    1 & \\quad \\text{if $i=k$ and $j=l$}\\\\\n    0 & \\quad \\text{otherwise}\n\\end{array}\n\\right.\n\\end{equation}\nIf \\var{d} is an integer a $(d,d,d,d)$ \\numpy array is returned.\n\\end{funcdesc}\n\n\\begin{funcdesc}{unitVector}{i,d}\nreturns a \\RankOne in \\FunctionSpace \\var{d} such that\n\\begin{equation}\n\\code{identityTensor(d)}\\left[ j \\right] = \\left\\{\n\\begin{array}{l l}\n    1 & \\quad \\text{if $j=i$}\\\\\n    0 & \\quad \\text{otherwise}\n\\end{array}\n\\right.\n\\end{equation}\nIf \\var{d} is an integer a $(d,)$ \\numpy array is returned.\n\\end{funcdesc}\n\n\\begin{funcdesc}{Lsup}{a}\nreturns the $L^{sup}$ norm of \\var{arg}. This is the maximum of the absolute\nvalues over all components and all \\DataSamplePoints of \\var{a}.\n\\end{funcdesc}\n\n\\begin{funcdesc}{sup}{a}\nreturns the maximum value over all components and all \\DataSamplePoints of \\var{a}.\n\\end{funcdesc}\n\n\\begin{funcdesc}{inf}{a}\nreturns the minimum value over all components and all \\DataSamplePoints of \\var{a}\n\\end{funcdesc}\n\n\\begin{funcdesc}{minval}{a}\nreturns at each data sample point the minimum value over all components.\n\\end{funcdesc}\n\n\\begin{funcdesc}{maxval}{a}\nreturns at each data sample point the maximum value over all components.\n\\end{funcdesc}\n\n\\begin{funcdesc}{length}{a}\nreturns the Euclidean norm at each data sample point.\nFor a \\RankFour \\var{a} this is\n\\begin{equation}\n\\code{length(a)}=\\sqrt{\\sum_{ijkl} \\var{a} \\left[i,j,k,l\\right]^2}\n\\end{equation}\n\\end{funcdesc}\n\n\\begin{funcdesc}{trace}{a\\optional{, axis_offset=0}}\nreturns the trace of \\var{a}. This is the sum over components \\var{axis_offset}\nand \\var{axis_offset+1} with the same index.\nFor instance, in the case of a \\RankTwo this is\n\\begin{equation}\n\\code{trace(a)}=\\sum_{i} \\var{a} \\left[i,i\\right]\n\\end{equation}\nand for a \\RankFour and \\code{axis_offset=1} this is\n\\begin{equation}\n\\code{trace(a,1)}\\left[i,j\\right]=\\sum_{k} \\var{a} \\left[i,k,k,j\\right]\n\\end{equation}\n\\end{funcdesc}\n\n\\begin{funcdesc}{transpose}{a\\optional{, axis_offset=None}}\nreturns the transpose of \\var{a}. This swaps the first \\var{axis_offset}\ncomponents of \\var{a} with the rest. If \\var{axis_offset} is not\npresent \\code{int(r/2)} is used where \\var{r} is the rank of \\var{a}.\nFor instance, in the case of a \\RankTwo this is\n\\begin{equation}\n\\code{transpose(a)}\\left[i,j\\right]=\\var{a} \\left[j,i\\right]\n\\end{equation}\nand for a \\RankFour and \\code{axis_offset=1} this is\n\\begin{equation}\n\\code{transpose(a,1)}\\left[i,j,k,l\\right]=\\var{a} \\left[j,k,l,i\\right]\n\\end{equation}\n\\end{funcdesc}\n\n\\begin{funcdesc}{swap_axes}{a\\optional{, axis0=0 \\optional{, axis1=1 }}}\nreturns \\var{a} but with swapped components \\var{axis0} and \\var{axis1}.\nThe argument \\var{a} must be at least of rank 2. For instance, if \\var{a}\nis a \\RankFour, \\code{axis0=1} and \\code{axis1=2}, the result is\n\\begin{equation}\n\\code{swap_axes(a,1,2)}\\left[i,j,k,l\\right]=\\var{a} \\left[i,k,j,l\\right]\n\\end{equation}\n\\end{funcdesc}\n\n\\begin{funcdesc}{symmetric}{a}\nreturns the symmetric part of \\var{a}. This is \\code{(a+transpose(a))/2}.\n\\end{funcdesc}\n\n\\begin{funcdesc}{nonsymmetric}{a}\nreturns the non-symmetric part of \\var{a}. This is \\code{(a-transpose(a))/2}.\n\\end{funcdesc}\n\n\\begin{funcdesc}{inverse}{a}\nreturn the inverse of \\var{a} so that\n\\begin{equation}\n\\code{matrix_mult(inverse(a),a)=kronecker(d)}\n\\end{equation}\nif \\var{a} has shape \\code{(d,d)}. The current implementation is restricted to\narguments of shape \\code{(2,2)} and \\code{(3,3)}.\n\\end{funcdesc}\n\n\\begin{funcdesc}{eigenvalues}{a}\nreturns the eigenvalues of \\var{a} so that\n\\begin{equation}\n\\code{matrix_mult(a,V)=e[i]*V}\n\\end{equation}\nwhere \\code{e=eigenvalues(a)} and \\var{V} is a suitable non-zero vector.\nThe eigenvalues are ordered in increasing size.\nThe argument \\var{a} has to be symmetric, i.e. \\code{a=symmetric(a)}.\nThe current implementation is restricted to arguments of shape \\code{(2,2)}\nand \\code{(3,3)}.\n\\end{funcdesc}\n\n\\begin{funcdesc}{eigenvalues_and_eigenvectors}{a}\nreturns the eigenvalues and eigenvectors of \\var{a}.\n\\begin{equation}\n\\code{matrix_mult(a,V[:,i])=e[i]*V[:,i]}\n\\end{equation}\nwhere \\code{e,V=eigenvalues_and_eigenvectors(a)}. The eigenvectors \\var{V} are\northogonal and normalized, i.e.\n\\begin{equation}\n\\code{matrix_mult(transpose(V),V)=kronecker(d)}\n\\end{equation}\nif \\var{a} has shape \\code{(d,d)}. The eigenvalues are ordered in increasing\nsize. The argument \\var{a} has to be the symmetric, i.e. \\code{a=symmetric(a)}.\nThe current implementation is restricted to arguments of shape \\code{(2,2)}\nand \\code{(3,3)}.\n\\end{funcdesc}\n\n\\begin{funcdesc}{maximum}{*a}\nreturns the maximum value over all arguments at all \\DataSamplePoints and for each component.\n\\begin{equation}\n\\code{maximum(a0,a1)}\\left[i,j\\right]=max(\\var{a0} \\left[i,j\\right],\\var{a1} \\left[i,j\\right])\n\\end{equation}\nat all \\DataSamplePoints.\n\\end{funcdesc}\n\n\\begin{funcdesc}{minimum}{*a}\nreturns the minimum value over all arguments at all \\DataSamplePoints and for each component.\n\\begin{equation}\n\\code{minimum(a0,a1)}\\left[i,j\\right]=min(\\var{a0} \\left[i,j\\right],\\var{a1} \\left[i,j\\right])\n\\end{equation}\nat all \\DataSamplePoints.\n\\end{funcdesc}\n\n\\begin{funcdesc}{clip}{a\\optional{, minval=0.}\\optional{, maxval=1.}}\ncuts back \\var{a} into the range between \\var{minval} and \\var{maxval}.\nA value in the returned object equals \\var{minval} if the corresponding value\nof \\var{a} is less than \\var{minval}, equals \\var{maxval} if the corresponding\nvalue of \\var{a} is greater than \\var{maxval}, or corresponding value of\n\\var{a} otherwise.\n\\end{funcdesc}\n\n\\begin{funcdesc}{inner}{a0, a1}\nreturns the inner product of \\var{a0} and \\var{a1}. For instance in the\ncase of a \\RankTwo:\n\\begin{equation}\n\\code{inner(a)}=\\sum_{ij}\\var{a0} \\left[j,i\\right]  \\cdot \\var{a1} \\left[j,i\\right]\n\\end{equation}\nand for a \\RankFour:\n\\begin{equation}\n\\code{inner(a)}=\\sum_{ijkl}\\var{a0} \\left[i,j,k,l\\right]  \\cdot \\var{a1} \\left[j,i,k,l\\right]\n\\end{equation}\n\\end{funcdesc}\n\n\\begin{funcdesc}{matrix_mult}{a0, a1}\nreturns the matrix product of \\var{a0} and \\var{a1}.\nIf \\var{a1} is a \\RankOne this is\n\\begin{equation}\n\\code{matrix_mult(a)}\\left[i\\right]=\\sum_{k}\\var{a0}  \\cdot \\left[i,k\\right]\\var{a1} \\left[k\\right]\n\\end{equation}\nand if \\var{a1} is a \\RankTwo this is\n\\begin{equation}\n\\code{matrix_mult(a)}\\left[i,j\\right]=\\sum_{k}\\var{a0}  \\cdot \\left[i,k\\right]\\var{a1} \\left[k,j\\right]\n\\end{equation}\n\\end{funcdesc}\n\n\\begin{funcdesc}{transposed_matrix_mult}{a0, a1}\nreturns the matrix product of the transposed of \\var{a0} and \\var{a1}.\nThe function is equivalent to \\code{matrix_mult(transpose(a0),a1)}.\nIf \\var{a1} is a \\RankOne this is\n\\begin{equation}\n\\code{transposed_matrix_mult(a)}\\left[i\\right]=\\sum_{k}\\var{a0}  \\cdot \\left[k,i\\right]\\var{a1} \\left[k\\right]\n\\end{equation}\nand if \\var{a1} is a \\RankTwo this is\n\\begin{equation}\n\\code{transposed_matrix_mult(a)}\\left[i,j\\right]=\\sum_{k}\\var{a0}  \\cdot \\left[k,i\\right]\\var{a1} \\left[k,j\\right]\n\\end{equation}\n\\end{funcdesc}\n\n\\begin{funcdesc}{matrix_transposed_mult}{a0, a1}\nreturns the matrix product of \\var{a0} and the transposed of \\var{a1}.\nThe function is equivalent to \\code{matrix_mult(a0,transpose(a1))}.\nIf \\var{a1} is a \\RankTwo this is\n\\begin{equation}\n\\code{matrix_transposed_mult(a)}\\left[i,j\\right]=\\sum_{k}\\var{a0}  \\cdot \\left[i,k\\right]\\var{a1} \\left[j,k\\right]\n\\end{equation}\n\\end{funcdesc}\n\n\\begin{funcdesc}{outer}{a0, a1}\nreturns the outer product of \\var{a0} and \\var{a1}.\nFor instance, if both, \\var{a0} and \\var{a1} is a \\RankOne then\n\\begin{equation}\n\\code{outer(a)}\\left[i,j\\right]=\\var{a0} \\left[i\\right]  \\cdot  \\var{a1}\\left[j\\right]\n\\end{equation}\nand if \\var{a0} is a \\RankOne and \\var{a1} is a \\RankThree:\n\\begin{equation}\n\\code{outer(a)}\\left[i,j,k\\right]=\\var{a0} \\left[i\\right] \\cdot \\var{a1}\\left[j,k\\right]\n\\end{equation}\n\\end{funcdesc}\n\n\\begin{funcdesc}{tensor_mult}{a0, a1}\nreturns the tensor product of \\var{a0} and \\var{a1}.\nIf \\var{a1} is a \\RankTwo this is\n\\begin{equation}\n\\code{tensor_mult(a)}\\left[i,j\\right]=\\sum_{kl}\\var{a0}\\left[i,j,k,l\\right] \\cdot \\var{a1} \\left[k,l\\right]\n\\end{equation}\nand if \\var{a1} is a \\RankFour this is\n\\begin{equation}\n\\code{tensor_mult(a)}\\left[i,j,k,l\\right]=\\sum_{mn}\\var{a0} \\left[i,j,m,n\\right] \\cdot \\var{a1} \\left[m,n,k,l\\right]\n\\end{equation}\n\\end{funcdesc}\n\n\\begin{funcdesc}{transposed_tensor_mult}{a0, a1}\nreturns the tensor product of the transposed of \\var{a0} and \\var{a1}.\nThe function is equivalent to \\code{tensor_mult(transpose(a0),a1)}.\nIf \\var{a1} is a \\RankTwo this is\n\\begin{equation}\n\\code{transposed_tensor_mult(a)}\\left[i,j\\right]=\\sum_{kl}\\var{a0}\\left[k,l,i,j\\right] \\cdot \\var{a1} \\left[k,l\\right]\n\\end{equation}\nand if \\var{a1} is a \\RankFour this is\n\\begin{equation}\n\\code{transposed_tensor_mult(a)}\\left[i,j,k,l\\right]=\\sum_{mn}\\var{a0} \\left[m,n,i,j\\right] \\cdot \\var{a1} \\left[m,n,k,l\\right]\n\\end{equation}\n\\end{funcdesc}\n\n\\begin{funcdesc}{tensor_transposed_mult}{a0, a1}\nreturns the tensor product of \\var{a0} and the transposed of \\var{a1}.\nThe function is equivalent to \\code{tensor_mult(a0,transpose(a1))}.\nIf \\var{a1} is a \\RankTwo this is\n\\begin{equation}\n\\code{tensor_transposed_mult(a)}\\left[i,j\\right]=\\sum_{kl}\\var{a0}\\left[i,j,k,l\\right] \\cdot \\var{a1} \\left[l,k\\right]\n\\end{equation}\nand if \\var{a1} is a \\RankFour this is\n\\begin{equation}\n\\code{tensor_transposed_mult(a)}\\left[i,j,k,l\\right]=\\sum_{mn}\\var{a0} \\left[i,j,m,n\\right] \\cdot \\var{a1} \\left[k,l,m,n\\right]\n\\end{equation}\n\\end{funcdesc}\n\n\\begin{funcdesc}{grad}{a\\optional{, where=None}}\nreturns the gradient of \\var{a}. If \\var{where} is present the gradient will\nbe calculated in the \\FunctionSpace \\var{where}, otherwise a default\n\\FunctionSpace is used. In case that \\var{a} is a \\RankTwo one has\n\\begin{equation}\n\\code{grad(a)}\\left[i,j,k\\right]=\\frac{\\partial \\var{a} \\left[i,j\\right]}{\\partial x_{k}}\n\\end{equation}\n\\end{funcdesc}\n\n\\begin{funcdesc}{integrate}{a\\optional{, where=None}}\nreturns the integral of \\var{a} where the domain of integration is defined by\nthe \\FunctionSpace of \\var{a}. If \\var{where} is present the argument is\ninterpolated into \\FunctionSpace \\var{where} before integration.\nFor instance in the case of a \\RankTwo in \\ContinuousFunction it is\n\\begin{equation}\n\\code{integrate(a)}\\left[i,j\\right]=\\int_{\\Omega}\\var{a} \\left[i,j\\right] \\; d\\Omega\n\\end{equation}\nwhere $\\Omega$ is the spatial domain and $d\\Omega$ volume integration.\nTo integrate over the boundary of the domain one uses\n\\begin{equation}\n\\code{integrate(a,where=FunctionOnBoundary(a.getDomain))}\\left[i,j\\right]=\\int_{\\partial \\Omega} a\\left[i,j\\right] \\; ds\n\\end{equation}\nwhere $\\partial \\Omega$ is the surface of the spatial domain and $ds$ area or\nline integration.\n\\end{funcdesc}\n\n\\begin{funcdesc}{interpolate}{a, where}\ninterpolates argument \\var{a} into the \\FunctionSpace \\var{where}.\n\\end{funcdesc}\n\n\\begin{funcdesc}{div}{a\\optional{, where=None}}\nreturns the divergence of \\var{a}:\n\\begin{equation}\n    \\code{div(a)=trace(grad(a),where)}\n\\end{equation}\n\\end{funcdesc}\n\n\\begin{funcdesc}{jump}{a\\optional{, domain=None}}\nreturns the jump of \\var{a} over the discontinuity in its domain or if\n\\Domain \\var{domain} is present in \\var{domain}.\n\\begin{equation}\n\\begin{array}{rcl}\n\\code{jump(a)}& = &\\code{interpolate(a,FunctionOnContactOne(domain))} \\\\\n              &   & \\hfill - \\code{interpolate(a,FunctionOnContactZero(domain))}\n\\end{array}\n\\end{equation}\n\\end{funcdesc}\n\n\\begin{funcdesc}{L2}{a}\nreturns the $L^2$-norm of \\var{a} in its \\FunctionSpace. This is\n\\begin{equation}\n\\code{L2(a)=integrate(length(a)}^2\\code{)} \\; .\n\\end{equation}\n\\end{funcdesc}\n\n\\noindent The following functions operate ``point-wise''.\nThat is, the operation is applied to each component of each point individually.\n\n\\begin{funcdesc}{sin}{a}\napplies the sine function to \\var{a}.\n\\end{funcdesc}\n\n\\begin{funcdesc}{cos}{a}\napplies the cosine function to \\var{a}.\n\\end{funcdesc}\n\n\\begin{funcdesc}{tan}{a}\napplies the tangent function to \\var{a}.\n\\end{funcdesc}\n\n\\begin{funcdesc}{asin}{a}\napplies the arc (inverse) sine function to \\var{a}.\n\\end{funcdesc}\n\n\\begin{funcdesc}{acos}{a}\napplies the arc (inverse) cosine function to \\var{a}.\n\\end{funcdesc}\n\n\\begin{funcdesc}{atan}{a}\napplies the arc (inverse) tangent function to \\var{a}.\n\\end{funcdesc}\n\n\\begin{funcdesc}{sinh}{a}\napplies the hyperbolic sine function to \\var{a}.\n\\end{funcdesc}\n\n\\begin{funcdesc}{cosh}{a}\napplies the hyperbolic cosine function to \\var{a}.\n\\end{funcdesc}\n\n\\begin{funcdesc}{tanh}{a}\napplies the hyperbolic tangent function to \\var{a}.\n\\end{funcdesc}\n\n\\begin{funcdesc}{asinh}{a}\napplies the arc (inverse) hyperbolic sine function to \\var{a}.\n\\end{funcdesc}\n\n\\begin{funcdesc}{acosh}{a}\napplies the arc (inverse) hyperbolic cosine function to \\var{a}.\n\\end{funcdesc}\n\n\\begin{funcdesc}{atanh}{a}\napplies the arc (inverse) hyperbolic tangent function to \\var{a}.\n\\end{funcdesc}\n\n\\begin{funcdesc}{exp}{a}\napplies the exponential function to \\var{a}.\n\\end{funcdesc}\n\n\\begin{funcdesc}{sqrt}{a}\napplies the square root function to \\var{a}.\n\\end{funcdesc}\n\n\\begin{funcdesc}{log}{a}\ntakes the natural logarithm of \\var{a}.\n\\end{funcdesc}\n\n\\begin{funcdesc}{log10}{a}\ntakes the base-$10$ logarithm of \\var{a}.\n\\end{funcdesc}\n\n\\begin{funcdesc}{sign}{a}\napplies the sign function to \\var{a}. The result is $1$ where \\var{a} is\npositive, $-1$ where \\var{a} is negative, and $0$ otherwise.\n\\end{funcdesc}\n\n\\begin{funcdesc}{wherePositive}{a}\nreturns a function which is $1$ where \\var{a} is positive and $0$ otherwise.\n\\end{funcdesc}\n\n\\begin{funcdesc}{whereNegative}{a}\nreturns a function which is $1$ where \\var{a} is negative and $0$ otherwise.\n\\end{funcdesc}\n\n\\begin{funcdesc}{whereNonNegative}{a}\nreturns a function which is $1$ where \\var{a} is non-negative and $0$ otherwise.\n\\end{funcdesc}\n\n\\begin{funcdesc}{whereNonPositive}{a}\nreturns a function which is $1$ where \\var{a} is non-positive and $0$ otherwise.\n\\end{funcdesc}\n\n\\begin{funcdesc}{whereZero}{a\\optional{, tol=None\\optional{, rtol=1.e-8}}}\nreturns a function which is $1$ where \\var{a} equals zero with tolerance\n\\var{tol} and $0$ otherwise. If \\var{tol} is not present, the absolute maximum\nvalue of \\var{a} times \\var{rtol} is used.\n\\end{funcdesc}\n\n\\begin{funcdesc}{whereNonZero}{a\\optional{, tol=None\\optional{, rtol=1.e-8}}}\nreturns a function which is $1$ where \\var{a} is non-zero with tolerance\n\\var{tol} and $0$ otherwise. If \\var{tol} is not present, the absolute maximum\nvalue of \\var{a} times \\var{rtol} is used.\n\\end{funcdesc}\n\n\\subsection{Interpolating Data}\n\\index{interpolateTable}\n\\label{sec:interpolation}\nIn some cases, it may be useful to produce Data objects which fit some user\ndefined function.\nManually modifying each value in the Data object is not a good idea since it\ndepends on knowing the location and order of each data point in the domain.\nInstead, \\escript can use an interpolation table to produce a \\Data object.\n\nThe following example is available as \\file{int_save.py} in the \\ExampleDirectory.\nWe will produce a \\Data object which approximates a sine curve.\n\n\\begin{python}\n  from esys.escript import saveDataCSV, sup, interpolateTable\n  import numpy\n  from esys.finley import Rectangle\n\n  n=4\n  r=Rectangle(n,n)\n  x=r.getX()\n  toobig=100\n\\end{python}\n\n\\noindent First we produce an interpolation table:\n\\begin{python}\n  sine_table=[0, 0.70710678118654746, 1, 0.70710678118654746, 0,\n             -0.70710678118654746, -1, -0.70710678118654746, 0]\n\\end{python}\n%\nWe wish to identify $0$ and $1$ with the ends of the curve, that is\nwith the first and eighth value in the table.\n\n\\begin{python}\n  numslices=len(sine_table)-1\n  minval=0.\n  maxval=1.\n  step=sup(maxval-minval)/numslices\n\\end{python}\n%\nSo the values $v$ from the input lie in the interval\n\\var{minval} $\\leq v <$ \\var{maxval}.\n\\var{step} represents the gap (in the input range) between entries in the table.\nBy default, values of $v$ outside the table argument range (minval, maxval)\nwill be pushed back into the range, i.e. if $v <$ \\var{minval} the value\n\\var{minval} will be used to evaluate the table.\nSimilarly, for values $v>$ \\var{maxval} the value \\var{maxval} is used.\n\nNow we produce our new \\Data object:\n\n\\begin{python}\n  result=interpolateTable(sine_table, x[0], minval, step, toobig)\n\\end{python}\nAny values which interpolate to larger than \\var{toobig} will raise an\nexception. You can switch on boundary checking by adding\n\\code{check_boundaries=True} to the argument list.\n\nNow consider a 2D example. We will interpolate from a plane where $\\forall x,y\\in[0,9]:(x,y)=x+y\\cdot10$.\n\n\\begin{python}\nfrom esys.escript import whereZero\ntable2=[]\nfor y in range(0,10):\n      r=[]\n      for x in range(0,10):\n\t r.append(x+y*10)\n      table2.append(r)\nxstep=(maxval-minval)/(10-1)\nystep=(maxval-minval)/(10-1)\n\nxmin=minval\nymin=minval\n\nresult2=interpolateTable(table2, x2, (xmin, ymin), (xstep, ystep), toobig)\n\\end{python}\n\nWe can check the values using \\function{whereZero}.\nFor example, for $x=0$:\n\\begin{python}\nprint(result2*whereZero(x[0]))\n\\end{python}\n\nFinally let us look at a 3D example. Note that the parameter tuples should be\n$(x,y,z)$ but that in the interpolation table, $x$ is the innermost dimension.\n\\begin{python}\nb=Brick(n,n,n)\nx3=b.getX()\ntoobig=1000000\n\ntable3=[]\nfor z in range(0,10):\n   face=[]\n   for y in range(0,10):\n      r=[]\n      for x in range(0,10):\n\t r.append(x+y*10+z*100)\n      face.append(r)\n   table3.append(face);\n\nzstep=(maxval-minval)/(10-1)\n\nzmin=minval\n\nresult3=interpolateTable(table3, x3, (xmin, ymin, zmin),\n    (xstep, ystep, zstep), toobig)\n\\end{python}\n\n\n\\subsubsection{Non-uniform Interpolation}\nNon-uniform interpolation is also supported for the one dimensional case.\n\\begin{python}\nData.nonuniformInterpolate(in, out, check_boundaries)\nData.nonuniformSlope(in, out, check_boundaries)\n\\end{python}\n\nWill produce a new \\Data object by mapping the given \\Data object through the user-defined function\nspecified by \\texttt{in} and \\texttt{out}.\nThe \\ldots Interpolate version gives the value of the function at the specified point and the\n\\ldots Slope version gives the slope at those points.\nThe check_boundaries boolean argument specifies what the function should do if the \\Data object contains\nvalues outside the range specified by the \\texttt{in} parameter.\nIf the argument is \\texttt{False}, then those datapoints will be interpolated to the value of the edge\nthey are closest to (or assigned a slope of zero).\nIf the argument is \\texttt{True}, then an exception will be thrown if out of bounds values are detected.\nNote that the values given by the \\texttt{in} parameter must be monotonically increasing.\n\n\\noindent For example:\\\\\nIf \\texttt{d} contains the values \\texttt{\\{1,2,3,4,5\\}}, then\n\\begin{python}\nd.nonuniformInterpolate([1.5, 2, 2.8, 4.6], [4, 5, -1, 1], False)\n\\end{python}\nwould produce a \\Data object containing \\texttt{\\{4, 5, -0.7777, 0.3333, 1\\}}.\\\\\nA similar call to \\texttt{nonuniformSlope} would produce a \\Data object containing \\texttt{\\{0, 2, 1.1111, 1.1111, 0\\}}.\n%\n%\n% We will interpolate a surface such that the bottom\n% edge is the sine curve described above.\n% The amplitude of the curve decreases as we move towards the top edge.\n% Our interpolation table will have three rows:\n%\n% \\begin{python}\n%   st=numpy.array(sine_table)\n%   table=[st, 0.5*st, 0*st]\n% \\end{python}\n% %\n% The use of \\numpy and multiplication here is just to save typing.\n%\n% %  result2=x1.interpolateTable(table, 0, 0.55, x0, minval, step, toobig)\n% \\begin{python}\n%   result=interpolateTable(table, x (minval,0), (0.55, step), toobig)\n% \\end{python}\n%\n% In the 2D case the start and step parameters are tuples $(x,y)$.\n% By default, if a point is specified which is outside the boundary, then\n% \\var{interpolateTable} will operate as if the point was on the boundary.\n% Passing \\code{check_boundaries=True} will lead to the rejection of any points\n% outside the boundaries by \\var{interpolateTable}.\n%\n% This method can also be called with three dimensional tables and \\Data objects.\n% Tuples should be ordered $(x,y,z)$.\n\n\\subsection{The \\var{DataManager} Class}\n\\label{sec:datamanager}\n\nThe \\var{DataManager} class can be used to conveniently add checkpoint/restart\nfunctionality to \\escript simulations.\nOnce an instance is created \\Data objects and other values can be added and\ndumped to disk by a single method call.\nIf required the object can be set up to also save the data in a format suitable\nfor visualization.\nInternally the \\var{DataManager} interfaces with \\weipa for this.\n\n\\begin{classdesc}{DataManager}{formats=[RESTART], work_dir=\".\", restart_prefix=\"restart\", do_restart=\\True}\n    initializes a new \\var{DataManager} object which can be used to save,\n    restore and export simulation data in a number of formats.\n    All files and directories saved or restored by this object are located\n    under the directory specified by \\var{work_dir}.\n    If \\var{RESTART} is specified in \\var{formats}, the \\var{DataManager} will\n    look for directories whose name starts with \\var{restart_prefix}.\n    In case \\var{do_restart} is \\True, the last of these directories is used\n    to restore simulation data while all others are deleted.\n    If \\var{do_restart} is \\False, then all of those directories are deleted.\n    The \\var{restart_prefix} and \\var{do_restart} parameters are ignored if\n    \\var{RESTART} is not specified in \\var{formats}.\n\\end{classdesc}\n\n\\noindent Valid values for the \\var{formats} parameter are:\n\\begin{memberdesc}[DataManager]{RESTART}\n    enables writing of checkpoint files to be able to continue simulations\n    as explained in the class description.\n\\end{memberdesc}\n\\begin{memberdesc}[DataManager]{SILO}\n    exports simulation data in the \\SILO file format. \\escript must have\n    been compiled with \\SILO support for this to work.\n\\end{memberdesc}\n\\begin{memberdesc}[DataManager]{VISIT}\n    enables the \\VisIt simulation interface which allows connecting to and\n    interacting with the running simulation from a compatible \\VisIt client.\n    \\escript must have been compiled with \\VisIt (version 2) support and the\n    version of the client has to match the version used at compile time.\n    In order to connect to the simulation the client needs to have access and\n    load the file \\file{escriptsim.sim2} located under the work directory.\n\\end{memberdesc}\n\\begin{memberdesc}[DataManager]{VTK}\n    exports simulation data in the \\VTK file format.\n\\end{memberdesc}\n\n\\noindent The \\var{DataManager} class has the following methods:\n\\begin{methoddesc}[DataManager]{addData}{**data}\n    adds \\Data objects and other data to the manager. Calling this method does\n    not save or export the data yet so it is allowed to incrementally add data\n    at various points in the simulation script if required.\n    Note, that only a single domain is supported so all \\Data objects have to\n    be defined on the same one or an exception is raised.\n\\end{methoddesc}\n\n\\begin{methoddesc}[DataManager]{setDomain}{domain}\n    explicitly sets the domain for this manager.\n    It is generally not required to call this method directly.\n    Instead, the \\var{addData} method will set the domain used by the \\Data\n    objects.\n    An exception is raised if the domain was set to a different domain before\n    (explicitly or implicitly).\n\\end{methoddesc}\n\n\\begin{methoddesc}[DataManager]{hasData}{}\n    returns \\True if the manager has loaded simulation data for a restart.\n\\end{methoddesc}\n\n\\begin{methoddesc}[DataManager]{getDomain}{}\n    returns the domain as recovered from a restart.\n\\end{methoddesc}\n\n\\begin{methoddesc}[DataManager]{getValue}{value_name}\n    returns a \\Data object or other value with the name \\var{value_name} that\n    has been recovered after a restart.\n\\end{methoddesc}\n\n\\begin{methoddesc}[DataManager]{getCycle}{}\n    returns the export cycle, i.e. the number of times \\var{export()} has been\n    called.\n\\end{methoddesc}\n\n\\begin{methoddesc}[DataManager]{setCheckpointFrequency}{freq}\n    sets the frequency with which checkpoint files are created. This is only\n    useful if the \\var{DataManager} object was created with at least one other\n    format next to \\var{RESTART}. The frequency is 1 by default which means\n    that checkpoint files are created every time \\var{export()} is called.\n    Unlike visualization output, a simulation checkpoint is usually not\n    required at every time step. Thus, the frequency can be decreased by\n    calling this method with $\\var{freq}>1$ which would then create restart\n    files every \\var{freq} times \\var{export()} is called.\n\\end{methoddesc}\n\n\\begin{methoddesc}[DataManager]{setTime}{time}\n    sets the simulation time stamp. This floating point number is stored in\n    the metadata of exported data but not used by \\var{RESTART}.\n\\end{methoddesc}\n\n\\begin{methoddesc}[DataManager]{setMeshLabels}{x, y, z=\"\"}\n    sets labels for the mesh axes. These are currently only used by the \\SILO\n    exporter.\n\\end{methoddesc}\n\n\\begin{methoddesc}[DataManager]{setMeshUnits}{x, y, z=\"\"}\n    sets units for the mesh axes. These are currently only used by the \\SILO\n    exporter.\n\\end{methoddesc}\n\n\\begin{methoddesc}[DataManager]{setMetadataSchemaString}{schema, metadata=\"\"}\n    sets metadata namespaces and the corresponding metadata. These are\n    currently only used by the \\VTK exporter.\n    \\var{schema} is a dictionary that maps prefixes to namespace names, e.g.\\\\\n    \\code{\\{\"gml\": \"http://www.opengis.net/gml\"\\}} and \\var{metadata} is a\n    string with the actual content which will be enclosed in \\var{<MetaData>}\n    tags.\n\\end{methoddesc}\n\n\\begin{methoddesc}[DataManager]{export}{}\n    executes the actual data export. Depending on the \\var{formats} parameter\n    used in the constructor all data added by \\var{addData()} is written to\n    disk (\\var{RESTART,SILO,VTK}) or made available through the \\VisIt\n    simulation interface (\\var{VISIT}).\n    At least the domain must be set for something to be exported.\n\\end{methoddesc}\n\n\\subsection{Saving Data as CSV}\n\\label{sec:savedatacsv}\n\\index{saveDataCSV}\\index{CSV}\nFor simple post-processing, \\Data objects can be saved in comma separated\nvalue (\\emph{CSV}) format.\nIf \\var{mydata1} and \\var{mydata2} are scalar data, the command\n\\begin{python}\n  saveDataCSV('output.csv', U=mydata1, V=mydata2)\n\\end{python}\nwill record the values in \\file{output.csv} in the following format:\n\\begin{verbatim}\nU, V\n1.0000000e+0, 2.0000000e-1\n5.0000000e-0, 1.0000000e+1\n...\n\\end{verbatim}\n\nThe names of the keyword parameters form the names of columns in the output.\nIf the data objects are over different function spaces, then \\var{saveDataCSV}\nwill attempt to interpolate to a common function space.\nIf this is not possible, then an exception is raised.\n\nOutput can be restricted using a scalar mask as follows:\n\\begin{python}\n  saveDataCSV('outfile.csv', U=mydata1, V=mydata2, mask=myscalar)\n\\end{python}\nThis command will only output those rows which correspond to to positive\nvalues of \\var{myscalar}.\nSome aspects of the output can be tuned using additional parameters:\n\\begin{python}\n  saveDataCSV('data.csv', refid=True, append=True, sep=' ', csep='/', mask=mymask, e=mat1)\n\\end{python}\n\n\\begin{itemize}\n \\item \\var{refid} -- specifies that the output should include the reference IDs of the elements or nodes\n \\item \\var{append} -- specifies that the output should be written to the end of an existing file\n \\item \\var{sep} -- defines the separator between fields\n \\item \\var{csep} -- defines the separator between components in the header\n     line. For example between the components of a matrix.\n\\end{itemize}\n%\nThe above command would produce output like this:\n\\begin{verbatim}\nrefid e/0/0 e/1/0 e/0/1 e/1/1\n0 1.0000000000e+00 2.0000000000e+00 3.0000000000e+00 4.0000000000e+00\n...\n\\end{verbatim}\n\nNote that while the order in which rows are output can vary, all the elements\nin a given row always correspond to the same input.\n\n\\subsection{Converting \\Data to a Numpy Array}\n\\label{sec:getnumpy}\n\\index{getNumpy}\\index{GN}\n\\Data objects can be converted into a numpy structured array using the commands \\var{getNumpy} and \\var{convertNumpy}.\n\\subsubsection{getNumpy}\nIf \\var{mydata1} and \\var{mydata2} are scalar \\Data, then the command\n\\begin{python}\n  a,b = getNumpy(U=mydata1, V=mydata2)\n\\end{python}\nwill return two structured ndarrays with the names '\\emph{U}' and '\\emph{V}'.\n\\begin{verbatim}\na['U'] = [1.0000000e+0, 2.0000000e-1, ...\nb['V'] = [2.0000000e+0, 3.0000000e-1, ...\n\\end{verbatim}\n\nUp to five \\Data objects can be passed to \\var{getNumpy} at the time. These objects can be scalar, vector or tensor \\Data objects. The names of the keyword parameters form the names of the returned arrays.\nIf the data objects are over different function spaces, then \\var{getNumpy}\nwill attempt to interpolate to a common function space.\nIf this is not possible, then an exception is raised.\n\nOutput can be restricted using a scalar mask as follows:\n\\begin{python}\n  a,b,c = getNumpy(U=mydata1, V=mydata2, W=mydata3, mask=myscalar)\n\\end{python}\nThis command will only output those rows which correspond to to positive\nvalues of \\var{myscalar}.\n\nNote that while the order in which output rows are output can vary, all the elements\nin a given row always correspond to the same input.\n\n\\subsubsection{convertNumpy}\n\\Data objects can also be converted into a numpy structured array using the command \\var{convertNumpy}.\nIf \\var{mydata1} is a \\Data object, then the command\n\\begin{python}\n  a = convertNumpy(mydata1)\n\\end{python}\nwill return a structured ndarray containing all of the data in \\var{mydata1}. Unlike \\var{getNumpy}, this function\ndoes not support the use of masks and does not use MPI.\n\n\\subsection{The \\Operator Class}\nThe \\Operator class provides an abstract access to operators built\nwithin the \\LinearPDE class. \\Operator objects are created\nwhen a PDE is handed over to a PDE solver library and handled\nby the \\LinearPDE object defining the PDE. The user can gain access\nto the \\Operator of a \\LinearPDE object through the \\var{getOperator}\nmethod.\n\n\\begin{classdesc}{Operator}{}\ncreates an empty \\Operator object.\n\\end{classdesc}\n\n\\begin{methoddesc}[Operator]{isEmpty}{fileName}\nreturns \\True is the object is empty, \\False otherwise.\n\\end{methoddesc}\n\n\\begin{methoddesc}[Operator]{resetValues}{}\nresets all entries in the operator.\n\\end{methoddesc}\n\n\\begin{methoddesc}[Operator]{solve}{rhs}\n    returns the solution \\var{u} of: operator * \\var{u} = \\var{rhs}.\n\\end{methoddesc}\n\n\\begin{methoddesc}[Operator]{of}{u}\napplies the operator to the \\Data object \\var{u}, i.e. performs a matrix-vector\nmultiplication.\n\\end{methoddesc}\n\n\\begin{methoddesc}[Operator]{saveMM}{fileName}\\index{Matrix Market}\nsaves the object to a Matrix Market format file with name \\var{fileName}, see\n\\url{http://math.nist.gov/MatrixMarket}\n\\end{methoddesc}\n\n\\section{Physical Units}\n\\escript provides support for physical units in the SI system\\index{SI units}\nincluding unit conversion. So the user can define variables in the form\n\\begin{python}\n  from esys.escript.unitsSI import *\n  l=20*m\n  w=30*kg\n  w2=40*lb\n  T=100*Celsius\n\\end{python}\nIn the two latter cases a conversion from pounds\\index{pounds} and degrees\nCelsius\\index{Celsius} is performed into the appropriate SI units \\emph{kg}\nand \\emph{Kelvin}.\nIn addition, composed units can be used, for instance\n\\begin{python}\n  from esys.escript.unitsSI import *\n  rho=40*lb/cm**3\n\\end{python}\ndefines the density in the units of pounds per cubic centimeter.\nThe value $40$ will be converted into SI units, in this case kg per cubic\nmeter. Moreover unit prefixes are supported:\n\\begin{python}\n  from esys.escript.unitsSI import *\n  p=40*Mega*Pa\n\\end{python}\nThe pressure \\var{p} is set to 40 Mega Pascal. Units can also be converted\nback from the SI system into a desired unit, e.g.\n\\begin{python}\n  from esys.escript.unitsSI import *\n  print(p/atm)\n\\end{python}\ncan be used print the pressure in units of atmosphere\\index{atmosphere}.\n\nThe following is an incomplete list of supported physical units:\n\n\\begin{datadesc}{km}\nunit of kilometer\n\\end{datadesc}\n\n\\begin{datadesc}{m}\nunit of meter\n\\end{datadesc}\n\n\\begin{datadesc}{cm}\nunit of centimeter\n\\end{datadesc}\n\n\\begin{datadesc}{mm}\nunit of millimeter\n\\end{datadesc}\n\n\\begin{datadesc}{sec}\nunit of second\n\\end{datadesc}\n\n\\begin{datadesc}{minute}\nunit of minute\n\\end{datadesc}\n\n\\begin{datadesc}{h}\nunit of hour\n\\end{datadesc}\n\n\\begin{datadesc}{day}\nunit of day\n\\end{datadesc}\n\n\\begin{datadesc}{yr}\nunit of year\n\\end{datadesc}\n\n\\begin{datadesc}{gram}\nunit of gram\n\\end{datadesc}\n\n\\begin{datadesc}{kg}\nunit of kilogram\n\\end{datadesc}\n\n\\begin{datadesc}{lb}\nunit of pound\n\\end{datadesc}\n\n\\begin{datadesc}{ton}\nmetric ton\n\\end{datadesc}\n\n\\begin{datadesc}{A}\nunit of Ampere\n\\end{datadesc}\n\n\\begin{datadesc}{Hz}\nunit of Hertz\n\\end{datadesc}\n\n\\begin{datadesc}{N}\nunit of Newton\n\\end{datadesc}\n\n\\begin{datadesc}{Pa}\nunit of Pascal\n\\end{datadesc}\n\n\\begin{datadesc}{atm}\nunit of atmosphere\n\\end{datadesc}\n\n\\begin{datadesc}{J}\nunit of Joule\n\\end{datadesc}\n\n\\begin{datadesc}{W}\nunit of Watt\n\\end{datadesc}\n\n\\begin{datadesc}{C}\nunit of Coulomb\n\\end{datadesc}\n\n\\begin{datadesc}{V}\nunit of Volt\n\\end{datadesc}\n\n\\begin{datadesc}{F}\nunit of Farad\n\\end{datadesc}\n\n\\begin{datadesc}{Ohm}\nunit of Ohm\n\\end{datadesc}\n\n\\begin{datadesc}{K}\nunit of degrees Kelvin\n\\end{datadesc}\n\n\\begin{datadesc}{Celsius}\nunit of degrees Celsius\n\\end{datadesc}\n\n\\begin{datadesc}{Fahrenheit}\nunit of degrees Fahrenheit\n\\end{datadesc}\n\n\\noindent Supported unit prefixes:\n\n\\begin{datadesc}{Yotta}\nprefix yotta = $10^{24}$\n\\end{datadesc}\n\n\\begin{datadesc}{Zetta}\nprefix zetta = $10^{21}$\n\\end{datadesc}\n\n\\begin{datadesc}{Exa}\nprefix exa = $10^{18}$\n\\end{datadesc}\n\n\\begin{datadesc}{Peta}\nprefix peta = $10^{15}$\n\\end{datadesc}\n\n\\begin{datadesc}{Tera}\nprefix tera = $10^{12}$\n\\end{datadesc}\n\n\\begin{datadesc}{Giga}\nprefix giga = $10^9$\n\\end{datadesc}\n\n\\begin{datadesc}{Mega}\nprefix mega = $10^6$\n\\end{datadesc}\n\n\\begin{datadesc}{Kilo}\nprefix kilo = $10^3$\n\\end{datadesc}\n\n\\begin{datadesc}{Hecto}\nprefix hecto = $10^2$\n\\end{datadesc}\n\n\\begin{datadesc}{Deca}\nprefix deca = $10^1$\n\\end{datadesc}\n\n\\begin{datadesc}{Deci}\nprefix deci = $10^{-1}$\n\\end{datadesc}\n\n\\begin{datadesc}{Centi}\nprefix centi = $10^{-2}$\n\\end{datadesc}\n\n\\begin{datadesc}{Milli}\nprefix milli = $10^{-3}$\n\\end{datadesc}\n\n\\begin{datadesc}{Micro}\nprefix micro = $10^{-6}$\n\\end{datadesc}\n\n\\begin{datadesc}{Nano}\nprefix nano = $10^{-9}$\n\\end{datadesc}\n\n\\begin{datadesc}{Pico}\nprefix pico = $10^{-12}$\n\\end{datadesc}\n\n\\begin{datadesc}{Femto}\nprefix femto = $10^{-15}$\n\\end{datadesc}\n\n\\begin{datadesc}{Atto}\nprefix atto = $10^{-18}$\n\\end{datadesc}\n\n\\begin{datadesc}{Zepto}\nprefix zepto = $10^{-21}$\n\\end{datadesc}\n\n\\begin{datadesc}{Yocto}\nprefix yocto = $10^{-24}$\n\\end{datadesc}\n\n\\section{Utilities}\nThe \\class{FileWriter} class provides a mechanism to write data to a file.\nIn essence, this class wraps the standard \\PYTHON \\class{file} class to write\ndata that are global in \\MPI to a file. In fact, data are written on the\nprocessor with \\MPI rank 0 only. It is recommended to use \\class{FileWriter}\nrather than \\class{open} in order to write code that will run with and without\n\\MPI. It is safe to use \\class{open} under \\MPI to \\emph{read} data which are\nglobal under \\MPI.\n\n\\begin{classdesc}{FileWriter}{fn\\optional{,append=\\False, \\optional{createLocalFiles=\\False}})}\nOpens a file with name \\var{fn} for writing. If \\var{append} is set to \\True\ndata are appended at the end of the file.\nIf running under \\MPI, only the first processor (rank==0) will open the file\nand write to it.\nIf \\var{createLocalFiles} is set each individual processor will create a file\nwhere for any processor with rank $> 0$ the file name is extended by its rank.\nThis option is normally used for debugging purposes only.\n\\end{classdesc}\n\n\\vspace{1em}\\noindent The following methods are available:\n\\begin{methoddesc}[FileWriter]{close}{}\ncloses the file.\n\\end{methoddesc}\n\\begin{methoddesc}[FileWriter]{flush}{}\nflushes the internal buffer to disk.\n\\end{methoddesc}\n\\begin{methoddesc}[FileWriter]{write}{txt}\nwrites string \\var{txt} to the file. Note that a newline is not added.\n\\end{methoddesc}\n\\begin{methoddesc}[FileWriter]{writelines}{txts}\nwrites the list \\var{txts} of strings to the file.\nNote that newlines are not added.\nThis method is equivalent to calling \\var{write()} for each string.\n\\end{methoddesc}\n\\begin{memberdesc}[FileWriter]{closed}\nthis member is \\True if the file is closed.\n\\end{memberdesc}\n\\begin{memberdesc}[FileWriter]{mode}\nholds the access mode.\n\\end{memberdesc}\n\\begin{memberdesc}[FileWriter]{name}\nholds the file name.\n\\end{memberdesc}\n\\begin{memberdesc}[FileWriter]{newlines}\nholds the line separator.\n\\end{memberdesc}\n\n\\noindent The following additional functions are available in the \\escript\nmodule:\n\\begin{funcdesc}{setEscriptParamInt}{name,value}\nassigns the integer value \\var{value} to the internal Escript parameter\n\\var{name}. This should be considered an advanced feature and it is generally\nnot required to call this function. One parameter worth mentioning is\n\\var{name}=\"TOO_MANY_LINES\" which affects the conversion of \\Data objects to a\nstring. If more than \\var{value} lines would be created, a condensed format is\nused instead which reports the minimum and maximum values and general\ninformation about the \\Data object rather than all values.\n\\end{funcdesc}\n\n\\begin{funcdesc}{getEscriptParamInt}{name}\nreturns the current value of internal Escript parameter \\var{name}.\n\\end{funcdesc}\n\n\\begin{funcdesc}{listEscriptParams}{a}\nreturns a list of valid Escript parameters and their description.\n\\end{funcdesc}\n\n\\begin{funcdesc}{getMPISizeWorld}{}\nreturns the number of \\MPI processes in use in the \\env{MPI_COMM_WORLD}\nprocess group. If \\MPI is not used 1 is returned.\n\\end{funcdesc}\n\n\\begin{funcdesc}{getMPIRankWorld}{}\nreturns the rank of the current process within the \\env{MPI_COMM_WORLD}\nprocess group. If \\MPI is not used 0 is returned.\n\\end{funcdesc}\n\n\\begin{funcdesc}{MPIBarrierWorld}{}\nperforms a barrier synchronization across all processes within the\n\\env{MPI_COMM_WORLD} process group.\n\\end{funcdesc}\n\n\\begin{funcdesc}{getMPIWorldMax}{a}\nreturns the maximum value of the integer \\var{a} across all processes within\n\\env{MPI_COMM_WORLD}.\n\\end{funcdesc}\n\n\\section{Lazy Evaluation of Data}\n\\label{sec:lazy}\nConstant and Tagged representations of Data are relatively small but Expanded\\footnote{Separate values stored for each point of the FunctionSpace.} are larger and\nwill not entirely fit in CPU cache.\n\nEscript's lazy evaluation features record operations performed on Data objects but do not actually carry them out until the Data is ``resolved''.\n\nConsider the following code:\n\\begin{python}\nfrom esys.escript import *\nfrom esys.dudley import Rectangle\nx=Rectangle(3,3)\nx=Rectangle(3,3).getX()\nc=Data((1.5, 1), x.getFunctionSpace())\nt=Data(((1,1),(0,1)), x.getFunctionSpace())\nt.tag()\n\\end{python}\n\nThe variables \\var{c}, \\var{t}, \\var{x} are stored as \\texttt{constant}, \\texttt{tagged} and \\texttt{expanded} Data respectively.\nPrinting those variables will show the values stored (or if we were to use a larger Rectangle, a summary).\n\n\\begin{python}\nv = matrix_mult(t,x) + c\nprint(v.isExpanded())\nprint(v)\n\\end{python}\n\nWill output \\texttt{True} followed by all of the values for \\var{v}.\nNow we'll introduce lazy evaluation:\n\n\\begin{python}\nxx = x.delay()\nprint(xx.isExpanded(), xx.isLazy())\nprint(x.isExpanded(), x.isLazy())\nprint(xx)\n\\end{python}\n\nThe first print will show that \\var{xx} is not considered to be ``expanded'', while the second print shows that \\var{x} is unaffected.\nThe last print will produce something like:\n\\begin{python}\nLazy Data: [depth=0] E@0x55ed512ad760\n\\end{python}\nThe \\texttt{E} before the \\verb|@| shows that this lazy Data is wrapping ``expanded'' Data.\nCalling \\texttt{.delay()} on constant or tagged Data results in \\verb|C@...| and \\verb|T@...| respectively.\n\nIf an input to an operation is lazy, then the result will be lazy as well\\footnote{Matrix inverse is an exception to this.}:\n\\begin{python}\nres = matrix_mult(t,-xx) + c\nprint(res)\n\\end{python}\nWill produce:\n\\begin{python}\nLazy Data: [depth=3] (prod(T@0x..., neg(E@...)) + C@0x...)\n\\end{python}\nDepth indicates the largest number of operators from the top of the expression to the bottom.\n\nTo actually find the value of this lazy Data object, we need to resolve it:\n\\begin{python}\nres.resolve()\n\\end{python}\nNote that \\texttt{resolve()} doesn't return a new object, but transforms the object it is called on.\nPrinting, \\var{res} now will show the values at each point.\n\n\\subsection{Lazyness and non-expanded Data}\nWhile it is possible to call delay on constant or tagged Data, escript will not build expressions consisting solely of such Data.\n\\begin{python}\ncx=c.delay()\nres=cx+cx\nprint(res)\n\\end{python}\nwould output:\n\\begin{python}\nLazy Data: [depth=0] C@0x55ed512cc7c0\n# Not\nLazy Data: [depth=1] (C@0x... + C@0x...)\n\\end{python}\n\n\n\\subsection{When to resolve}\n\nYou are never \\emph{required} to manually resolve lazy Data in \\texttt{escript}.\nAny operations which need the actual values of an expression will either\n\\begin{itemize}\n \\item compute the values without resolving the whole Data object at once (solvers assembling FEM matrices)\n \\item resolve the data automatically (everthing else)\n\\end{itemize}\n\n\\noindent Escript will automatically resolve lazy Data:\n\\begin{enumerate}\n \\item If a matrix inversion operation is applied to the Data.\n \\item If the expression tree becomes too deep\\footnote{At time of writing, this threshold is somewhat arbitrarily set at \\texttt{depth>9}, but this is configurable.}.\n\\end{enumerate}\nNote, the second point is important when writing loops like this:\n\\begin{python}\n# x is initial guess\nwhile err > tol:\n  construct PDE coefficients involving x\n  solve PDE\n  calculate err\n  update x\n\\end{python}\n\nAfter a few iterations of the loop, \\var{x} may be something like \\texttt{x=F(F(F(F(originalX))))}.\nSo it will probably be better to \\texttt{resolve} \\var{x} at the end of each loop iteration.\nAlternatively, if \\var{x} is included in many expressions in the loop, it may be better to resolve it earlier.\n\n\\subsection{Options for using lazy evaluation}\n\nThere are two ways to enable lazy evaluation:\n\\begin{enumerate}\n \\item Any escript script can make use of lazy evaluation by \\texttt{delay()}-ing one of its expanded Data variables.\nAny expressions including that delayed variable (directly or indirectly) will be lazy until resolved.\n \\item Setting the \\texttt{AUTOLAZY} parameter for \\texttt{escript} to \\texttt{1}.\n In this case, most escript operation which would normally produce extended Data, will produce lazy Data instead.\n In general, this option is not recommended for two reasons:\n \\begin{itemize}\n  \\item AUTOLAZY uses the \\texttt{setEscriptParamInt()} which is not guaranteed to have continued support.\n  \\item Making everything lazy instead of just more complex objects is not likely to give significant efficiency improvements.\n \\end{itemize}\n\\end{enumerate}\n\n\\subsection{When to use lazy evaluation?}\nExactly when using lazy evaluation will be more efficient is still an open question.\nWhen the objects being manipulated are large (eg 4-Tensors in Drucker-Prager), significant memory and runtime improvements can be achieved.\nSee~\\cite{lazyauspdc}.\n\nOur best advice is to experiment with it.\n", "meta": {"hexsha": "1a698c33cc4714a8cfa9bc7f0d0e2e3a873a0337", "size": 89629, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/user/escript.tex", "max_stars_repo_name": "markendr/esys-escript.github.io", "max_stars_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/user/escript.tex", "max_issues_repo_name": "markendr/esys-escript.github.io", "max_issues_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/user/escript.tex", "max_forks_repo_name": "markendr/esys-escript.github.io", "max_forks_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8174144825, "max_line_length": 205, "alphanum_fraction": 0.7446808511, "num_tokens": 25335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3160234191745929}}
{"text": "\\documentclass[]{article}\n\\usepackage{amsmath}\n\\usepackage[a4paper]{geometry}\n\\usepackage{graphicx}\n\\usepackage{microtype}\n\\usepackage{siunitx}\n\\usepackage{booktabs}\n\\usepackage[colorlinks=false, pdfborder={0 0 0}]{hyperref}\n\\usepackage{cleveref}\n\\usepackage{caption}\n\\usepackage{subcaption}\n\\usepackage{float}\n\n\\begin{document}\n\n\\title{Kepler Pixel Model}\n\\author{Dun Wang}\n\\maketitle\n\n\\section{Target Selection}\n\nIn this model, targets are restricted to some GK-type stars that has a Earth-radius planet. The definition of GK-type stars is stars with surface temperatures $T_{eff}=4100-6100K$ and gravities $\\log g= 4.0-4.9$ ($\\log g$ is the base 10 logarithm of a star’s surface gravity measured in cm $s^{-2}$) (1). I set the planetary radius to be 0.8-1.2 earth radii to make sure that the star has a Earth-radius planet. With the selection criteria described above, the Confirmed Exoplanet Archive(2) gives 56 potential targets and finally KIC 5088536 is chosen to be the target that will be used in this model\\\\\nHere is the basic information of the KIC 5088536 from the Exoplanet Archive:\n\\begin{center}\n    \\begin{tabular}{ |c| c | c | c |  p{5cm} |}\n    \\hline\n    \\multicolumn{4}{|c|}{Steller Information}\\\\\n    \\hline\n    Effective Temperature & Stellar Radius & Surface Gravity & Kepler-band  Magnitude \\\\ \\hline\n    5884 $\\pm$ 75 [K] & 1.127 $\\pm$ 0.033 [Solar radii] & 4.304 $\\pm$0.053 [$cm/s^{2}$] & 11.529 [mags]\\\\ \\hline\n    \\end{tabular}\n\\end{center}\n\n\\section{Pixels Plot}\nFor the target KIC 5088536, I plot the flux-time plot for the whole target pixel file of  quarter 5:\\\\\n\\url{http://physics.nyu.edu/~dw1519/kepler/plot/5088536/tpf-5.png}\\\\\nand the associated pixel grid plot:\\\\\n\\url{http://physics.nyu.edu/~dw1519/kepler/plot/5088536/5088536-5.png}\n\n\\section{Neighors in Kepler magnitude}\nUsing the kplr interface, I write code to find the neighors in terms of Kepler magnitude on the same CCD as the target and plot the pixel grid plot of the 16 closest stars(in Kepler magnitude)\\\\\nHere are all the plots:\\\\\n\\url{http://physics.nyu.edu/~dw1519/kepler/plot/5088536/ccd25kmag16}\n\n\\section{Pixel-level Linear Model}\nFinally, Linear model is applied to the target pixel, and the N pixels of the closest star  (in terms Kepler magnitude) on the same CCD and quarter are used to fit the target pixel:\n\n\\begin{align*}\nI_{mn}^{*}=\\sum_{m' \\in M_{m}} a_{mnm'}I_{m'n'}\n\\end{align*}\n\\\\\nwhere $I_{mn}$ is the flux(using data from the Target Pixel Files) of pixel m at time $t_{n}$, $I_{mn}^{*}$ is the prediction for data point $I_{mn}$ of the target and $a_{mnm'}$  is the linear coefficients of the prediction. $M_{m}$ is set of pixels of the closest star (in terms Kepler magnitude)\n\\\\\n\\\\\nTo get the best fit coefficient, the $\\chi$ square should be minimised, Variance $\\sigma _{mn}^{2}$ is treated to be the same for different time $t_{n}$\n\\begin{align*}\n\\chi_{m}^{2}=\\sum_{n' \\in N_{n}} \\frac{[I_{mn}-I_{mn}^{*}]^{2}}{\\sigma _{mn}^{2}}\n\\end{align*}\n\\\\\nThe model is used to fit the pixel (2,4) of the KIC 5088536, here is the result of the best fit\\\\\nThe flux-time plot of the origin data and the fit prediction:\\\\\n\\url{http://physics.nyu.edu/~dw1519/kepler/plot/5088536/fit/normal/fit(2,4)_1_1_ccdTrue.png}\\\\\nBest fit coefficient of Pixel (2,4) in KIC 5088536:\\\\\n\\url{http://physics.nyu.edu/~dw1519/kepler/plot/5088536/fit/normal/coe(2,4)_1_1_ccdTrue.dat}\\\\\n\n\\section{Reference}\n1. Erik A. Petigura, et al. (2013) Prevalence of Earth-size planets orbiting Sun-like stars\\\\\n2. \\url{http://exoplanetarchive.ipac.caltech.edu/cgi-bin/ExoTables/nph-exotbls?dataset=planets}\n\n\\end{document}", "meta": {"hexsha": "225a8be08b128d613e407c80907e26adeec60e32", "size": 3604, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "documents/notes/kpm/kpm.tex", "max_stars_repo_name": "jvc2688/cpm", "max_stars_repo_head_hexsha": "409e9ada39fc6238a63a75fb8474a3af70410347", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-08-13T19:26:23.000Z", "max_stars_repo_stars_event_max_datetime": "2015-08-13T19:26:23.000Z", "max_issues_repo_path": "documents/notes/kpm/kpm.tex", "max_issues_repo_name": "jvc2688/cpm", "max_issues_repo_head_hexsha": "409e9ada39fc6238a63a75fb8474a3af70410347", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "documents/notes/kpm/kpm.tex", "max_forks_repo_name": "jvc2688/cpm", "max_forks_repo_head_hexsha": "409e9ada39fc6238a63a75fb8474a3af70410347", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.4857142857, "max_line_length": 603, "alphanum_fraction": 0.7283573807, "num_tokens": 1160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.31602341917459287}}
{"text": "%!TEX root = ../../main.tex\n\n\n%%%%%%% Begin table industrial damage detection\n\\begin{table*}\n\\begin{center}\n\\caption{Examples of  Hybrid DAD techniques.\n        \\\\CNN: Convolution Neural Networks, LSTM : Long Short Term Memory Networks\n        \\\\DBN: Deep Belief Networks, DNN : Deep Neural Networks.\n        \\\\AE: Autoencoders, DAE: Denoising Autoencoders, SVM: Support Vector Machines~\\cite{cortes1995support}\n        \\\\SVDD: Support Vector Data Description, RNN : Recurrent Neural Networks\n        \\\\Relief: Feature selection Algorithm~\\cite{kira1992feature}, KNN: K- Nearest Neighbours~\\cite{altman1992introduction}\n        \\\\CSI: Capture, Score, and Integrate~\\cite{ruchansky2017csi}. }\n    \\captionsetup{justification=centering}\n    \\label{tab:hybridModels}\n    \\scalebox{0.85}{\n    \\begin{tabular}{ | p{3cm} | p{2cm} | p{6cm} |}\n    \\hline\n     \\textbf{Techniques}  & \\textbf{Section} & \\textbf{References} \\\\ \\hline\n     AE-OCSVM, AE-SVM & Section ~\\ref{sec:ae}, & ~\\cite{andrews2016detecting} \\\\\\hline\n     DBN-SVDD, AE-SVDD & Section ~\\ref{sec:dnn}, & ~\\cite{erfani2016high},~\\cite{kim2015deep} \\\\\\hline\n     DNN-SVM & 21D & ~\\cite{inoue2017anomaly} \\\\\\hline\n     DAE-KNN, DBN-Random Forest~\\cite{ho1995random},CNN-Relief,CNN-SVM & Section ~\\ref{sec:dnn},\\ref{sec:ae} & ~\\cite{song2017hybrid},~\\cite{shi2017semi},~\\cite{zhu2018hybrid,urbanowicz2018relief} \\\\\\hline\n     AE-CNN, AE-DBN & Section ~\\ref{sec:dnn},~\\ref{sec:cnn},\\ref{sec:ae} &  ~\\cite{wang2018effective},~\\cite{li2015hybrid} \\\\\\hline\n     AE+ KNN & Section \\ref{sec:ae} & ~\\cite{song2017hybrid} \\\\\\hline\n     CNN-LSTM-SVM & Section ~\\ref{sec:cnn},\\ref{sec:rnn_lstm_gru}  & ~\\cite{wei2017new}\\\\\n     RNN-CSI & Section ~\\ref{sec:rnn_lstm_gru} & ~\\cite{ruchansky2017csi}\\\\\n     CAE-OCSVM & Section \\ref{sec:ae} & ~\\cite{gutoskidetection}, ~\\cite{dotti2017unsupervised}\\\\\\hline\n    \\end{tabular}}\n\\end{center}\n\\end{table*}\n\n\\subsection{Hybrid deep anomaly detection}\n\\label{sec:hybridModels}\nDeep learning models are widely used as feature extractors to learn robust features~\\cite{andrews2016detecting}. In hybrid deep models, the representative features learnt within deep models are input to traditional algorithms like one-class Radial Basis Function (RBF) , Support Vector Machine (SVM) classifiers. The hybrid models employ two step learning and are shown to produce state-of-the-art results~\\cite{erfani2016high,erfani2016robust,wu2015harvesting}.  Deep hybrid architectures used in anomaly detection are illustrated in Table ~\\ref{tab:hybridModels}.\n\n%%%%%%%%% End of Hybrid Models\n\n% OCSVM~\\cite{scholkopf2002support}, SVDD~\\cite{scholkopf2002support}\n% SVM~\\cite{cortes1995support}\n% KNN~\\cite{altman1992introduction}\n% Random Forest~\\cite{ho1995random}\n% Relief~\\cite{kira1992feature}\n% CSI~\\cite{ruchansky2017csi}\n% Section ~\\ref{sec:ae}\n% Section ~\\ref{sec:rnn_lstm_gru}\n% Section ~\\ref{sec:gan_adversarial}\n% Section ~\\ref{sec:dnn}\n% Section ~\\ref{sec:cnn}\n% Section ~\\ref{sec:stn}\n% Section ~\\ref{sec:hybridModels}\n\n\n\n\\textbf{Assumptions : } \\\\\nThe deep hybrid models proposed for anomaly detection rely on one the following assumptions to detect outliers:\n\\begin{itemize}\n  \\item Robust features are extracted within hidden layers of deep neural network, aid in separating out the irrelevant features which can conceal the presence of anomalies.\n  \\item Building a robust anomaly detection model on complex, high-dimensional spaces require feature extractor and an anomaly detector. Various anomaly detectors used alongwith are illustrated in Table ~\\ref{tab:hybridModels}\n\\end{itemize}\n\n\\textbf{Computational Complexity :} \\\\\nComputational complexity of an hybrid model includes complexity of both deep architectures as well as traditional algorithms used within.  Additionally  an inherent issue of non-trivial choice of deep network architecture and parameters which involves searching optimized parameters in a considerably larger space introduces the computational complexity of using deep layers within hybrid models. Furthermore considering the classical algorithms such as  linear SVM which has prediction complexity  of $O(d)$ with d the number of input dimensions. For most kernels, including polynomial and RBF, the complexity is $O(nd)$ where $n$ is the number of support vectors although an approximation $O(d^2)$ is considered for SVMs with an RBF kernel.\n\n\\textbf{Advantages and Disadvantages }\\\\\nThe advantages of hybrid DAD techniques are as follows:\n\\begin{itemize}\n\\item  The feature extractor greatly reduce the ‘curse of dimensionality’ especially in high dimensional domain.\n\\item  Hybrid models are  more scalable and computationally efficient since the linear or nonlinear kernel models operate on reduced input dimension.\n\\end{itemize}\nThe significant disadvantages of hybrid DAD techniques are:\n\\begin{itemize}\n\\item  The hybrid approach is suboptimal because it is unable to influence representational learning within the hidden layers of feature extractor, since generic loss functions are employed instead of  customised objective for anomaly detection.\n\\item The deeper hybrid models tend to perform better, if the individual layers are pre-trained ~\\cite{saxe2011random} which introduces computational expenditure.\n\\end{itemize}\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "669c7ebe9bb882cb19c1bb63651e1dcc4b22477d", "size": 5257, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ARXIV_DAD_Survey/sections/models/hybrid.tex", "max_stars_repo_name": "raghavchalapathy/Deep-Learning-for-Anomaly-Detection-A-Survey", "max_stars_repo_head_hexsha": "aa775990a4b23306885979c4ef8e8cb3ed00441b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 107, "max_stars_repo_stars_event_min_datetime": "2019-01-11T12:06:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T12:03:57.000Z", "max_issues_repo_path": "ARXIV_DAD_Survey/sections/models/hybrid.tex", "max_issues_repo_name": "raghavchalapathy/Deep-Learning-for-Anomaly-Detection-A-Survey_Arxiv_WorkingDocument", "max_issues_repo_head_hexsha": "aa775990a4b23306885979c4ef8e8cb3ed00441b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ARXIV_DAD_Survey/sections/models/hybrid.tex", "max_forks_repo_name": "raghavchalapathy/Deep-Learning-for-Anomaly-Detection-A-Survey_Arxiv_WorkingDocument", "max_forks_repo_head_hexsha": "aa775990a4b23306885979c4ef8e8cb3ed00441b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2019-01-15T02:42:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-06T07:59:29.000Z", "avg_line_length": 59.7386363636, "max_line_length": 742, "alphanum_fraction": 0.7584173483, "num_tokens": 1462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.31596646458854}}
{"text": "\\section{The Generic Solver}\n\nSolving a parity game is done by a central module called the \\emph{generic solver}.\nIt combines the universal optimisations described above with any of the implemented\nalgorithms of heuristics described above. This is realised by taking a solver, i.e.\\\none of these algorithms or heuristics as a parameter. Then it roughly works as follows.\n\\begin{enumerate}\n\\item Self-cycles are eliminated from the game, and attractors of nodes for which the\n      self-cycle is part of a winning strategy are computed and removed. \n\\item The entire game is decomposed into SCCs.\n\\item Terminal SCCs are solved as follows.\n      \\begin{enumerate}\n        \\item Priorities are compressed.\n        \\item The SCC is checked for being a special case of a game.\n              \\begin{itemize}\n                 \\item If it is, winning regions and strategies are constructed accordingly.\n                 \\item Otherwise, the solver given as the parameter is used to solve this\n                       SCC.\n              \\end{itemize}\n        \\item Attractors of the computed winning regions are also computed, together with \n              corresponding strategies which are added to the winning regions and strategies.\n        \\item The computed winning regions are removed from the game.\n        \\item All non-terminal SCCs which have lost some nodes in the removal of these\n              attractors are again decomposed into more fine-grained SCCs.\n      \\end{enumerate}\n\\item Step 3 is repeated until the entire game is solved.\n\\end{enumerate}\nNote that the removal of terminal SCCs will make other, previously non-terminal SCCs terminal.\nAlso, note that this scheme is sound -- the regions and strategies it computes are\nin fact winning regions and winning strategies for the corresponding players on the given\ngame -- if the parameter solver is sound. Hence, it can also be used with sound heuristics.\nFurthermore, it is complete if it is guaranteed that the parameter solver solves at least \none node of every SCC that it is given. Hence, the solvers used as backends need not be \ncomplete for the generic solver to be complete. This is why this scheme can solve whole games\nusing heuristics that are incomplete themselves.\n\nWe also note that the features SCC decomposition, detection of special cases, and priority\ncompression can be switched off via command-line options. This may be useful when the performance \nof an algorithm on its own is to be measured. In addition, it is possible to turn the feature \npriority propagation on in which case it is done before priority compression. However, in general \nthis does not seem to be an optimisation since it slows down virtually any backend.  \n\n\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: \"main\"\n%%% End:\n", "meta": {"hexsha": "7819f0b70d2424523880004824256fa745dc1bba", "size": 2781, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/gensolv.tex", "max_stars_repo_name": "tcsprojects/pgsolver", "max_stars_repo_head_hexsha": "88202c9452ccdcd4092280b4e76c31a16085d14c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2016-04-03T22:53:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T20:53:38.000Z", "max_issues_repo_path": "doc/gensolv.tex", "max_issues_repo_name": "tcsprojects/pgsolver", "max_issues_repo_head_hexsha": "88202c9452ccdcd4092280b4e76c31a16085d14c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2015-03-28T15:29:29.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-22T16:48:34.000Z", "max_forks_repo_path": "doc/gensolv.tex", "max_forks_repo_name": "tcsprojects/pgsolver", "max_forks_repo_head_hexsha": "88202c9452ccdcd4092280b4e76c31a16085d14c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2015-01-06T10:32:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T15:58:23.000Z", "avg_line_length": 56.7551020408, "max_line_length": 98, "alphanum_fraction": 0.7457749011, "num_tokens": 580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.5506073655352403, "lm_q1q2_score": 0.31587155659187854}}
{"text": "\\chapter{Engineering NOON states in one-dimensional quantum gases}\n\\label{ch:1d}\n\nUntil recently, simulating dynamic control protocols to engineer specific quantum states have been difficult to perform on GPU devices without full control of the software, itself.\nThis meant that researchers wishing to engineer specific quantum states by using GPU simulations would be required to have domain-specific knowledge in both software design and quantum mechanics, neither of which are trivial to understand.\nThis chapter serves as motivation for several methods to be discussed in Chapter~\\ref{ch:gpu} to allow for the simulation of quantum control methods on GPU devices, with a particular focus on quantum optimal control~\\cite{werschnik2007} and Shortcuts To Adiabaticity (STA)~\\cite{guery2019}.\nBoth of these control protocols will be used in a physical example for the non-adiabatic generation of superposition states in a one-dimensional Tonks--Girardeau (TG) gas~\\cite{schloss2016}.\nBetween the two methods, the drawbacks to STA methods are the strengths of quantum optimal control.\nWhere shortcuts can only be used on a specific subset of problems to evolve adiabatically and that are amenable to the analytical methods used, quantum optimal control is a more general tool for a wider variety of systems.\nOn the other hand, STA protocols are semi-analytical and if such protocols can be found, they greatly reduce the computational cost to engineering particular quantum states.\nTo start, I will discuss the field of optimization algorithms before moving to STA protocols and a physical system using both in practice.\n\nThe work in this chapter has been published in \\textit{New Journal of Physics}~\\cite{schloss2016}, and in this publication, I performed all calculations for all the figures generated and focused primarily on optimal control methods.\nThe STA protocol was devised by J\\'er\\'emie Gillet, and the research was supervised by Albert Benseny and Thomas Busch.\n\n\\section{Optimization methods}\n\nOptimization algorithms have become essential to many areas of modern computing and focus on either minimizing or maximizing a cost function by modifying several control parameters~\\cite{lewis2012}.\nThe number of control parameters create an $n$-dimensional space to traverse, and optimization algorithms are tasked at finding the global minimum or maximum of this domain.\nFor certain domains, it is difficult to find a global optimization strategy and many methods instead get caught in local minima while attempting to find the appropriate solution.\nBecause generalized optimization is such a fundamental problem, there are many known optimization methods, such as gradient descent~\\cite{ruder2016}, the Nelder--Mead or simplex method~\\cite{nelder1965}, genetic algorithms~\\cite{koza1997}, and many more~\\cite{lewis2012}.\nOf these, gradient descent is often considered to be one of the easiest to implement with favorable complexity and convergence guarantees, and because of this, it has become ubiquitous in many areas such as machine learning, which is of particular interest for GPU engineering. \nEven so, there are limitations to gradient descent, such as its dependence on calculating the gradient of the cost function's solution domain along with lengthy convergence times for high-precision solutions.\n\nFor this work, I am primarily interested in the area of quantum optimal control, which is a method typically used to determine the optimal time-dependent control parameters necessary to transform an initial state to a final, desired state~\\cite{werschnik2007}.\nThis means that one will often be maximizing the fidelity between states, defined as $\\mathcal{F} = |\\braket{\\psi|\\phi}|^2$, where $\\psi$ is the engineered quantum state and $\\phi$ is the state one is attempting to replicate.\nThis problem can be re-framed as an attempt to find the maximum of a fidelity \\textit{landscape}, where each point in the domain is a calculation of the fidelity.\nThis means that each point in the fidelity landscape necessarily involves solving the Schr\\\"odinger equation for chosen control parameters.\nFor this reason, I will be introducing a gradient-less (derivative-free) optimization algorithm, the Nelder--Mead (simplex) method, which is often used as a heuristic approach to this problem and there are several known optimizations for this method~\\cite{nelder1965,kolda2003,lewis2007}.\nThe Nelder--Mead method is also the recommended optimization algorithm for the chosen quantum optimal control method of the physical example that will be discussed in Section~\\ref{sec:CRAB}, Chopped RAndom Basis (CRAB) optimal control.\n\n\\subsection{Nelder--Mead}\n\\label{sec:NM}\n\nThe Nelder--Mead method is one of the most commonly implemented gradient-less optimization algorithms to-date and relies heavily on the concept of a simplex, which is a generalization of the three-dimensional tetrahedron to $n$-dimensions.\nFor example, a 0-simplex is a point, a 1-simplex is a line, a 2-simplex is a triangle, a 3-simplex is a tetrahedron, and so on.\nIf the Nelder--Mead method is attempting to optimize a cost function with $n$ control parameters, an $n+1$ point simplex will be created, and the points of this simplex will be manipulated until they have converged to a minimum or maximum in the domain.\nFor this section, I will focus on the method introduced in the original work by Nelder and Mead in 1965 while working at the National Vegetable Research Station in Warwick, England~\\cite{nelder1965}.\nFor this method, one is attempting to find the minimum value in some $n$-dimensional space.\nIn Nelder and Mead's original notation, a ``height'' is defined as the value of the cost function with provided input parameters, often depicted as the an elevation out of the plane.\n\nFor $P_i \\in i=\\{0,...,n\\}$ simplex points with heights of $y_i \\in i=\\{0,...,n\\}$, the Nelder--Mead method is tasked at minimizing all points such that $\\sqrt{\\sum(y_i-\\bar y)^2/n} < \\eta$, where $\\bar y$ denotes the height of the centroid location of the simplex, and $\\eta$ is some pre-defined convergence threshold value.\nThis convergence criteria assumes that if all points have converged with this method, the final location must be the minimum of the optimization domain; however, as mentioned in the previous section, this method may become trapped in a local minimum.\nAt every step in the Nelder--Mead method, the points with the highest and lowest values are determined and denoted as $P_h$ and $P_l$, respectively.\nIn addition, the centroid location is found as $\\bar P$.\nThis method then performs up to three basic operations on the simplex, itself:\n\n\\begin{description}\n\n\\item[Reflection] For this operation, $P_h$ is flipped across $\\bar P$, such that the new location,\n\\begin{equation}\nP^* = (1+\\alpha)\\bar P - \\alpha P_h.\n\\end{equation}\n\\noindent Here, $\\alpha > 0$ is a constant known as the reflection coefficient.\nAfter this operation, the new height is compared to $y_l$.\nIf it is lower, the method proceeds to an expansion step.\nOtherwise, the method checks whether the new height is lower than some other $y_i \\in \\{0,...,n\\},n\\neq \\{l,h\\}$, and if it is, the point is kept and the method continues to find the new simplex ordering.\nIf it is found that the reflected point, $P^*$, is higher in value than all other points, the method then keeps whichever point corresponds to the lowest height between the reflected and previous highest point and proceeds to the contraction step.\n\n\\item[Expansion] For this operation, an expansion is performed, such that the new location,\n\\begin{equation}\nP^{**} = \\gamma P^* + (1-\\gamma)\\bar P.\n\\end{equation}\n\\noindent Here, $\\gamma > 1$ is a constant known as the expansion coefficient.\nIf the new height is less than the previously lowest point, the expanded point, $P^{**}$, is kept, otherwise the reflected point is kept.\n\n\\item[Contraction] For this operation, a contraction is performed, such that the new location,\n\\begin{equation}\nP^{**} = \\beta P_h + (1-\\beta)\\bar P.\n\\end{equation}\n\\noindent Here, $0 < \\beta < 1$ is a constant known as the contraction coefficient.\nIf the contracted point, $P^{**}$, is lower than the previous highest point, the contracted point is kept, otherwise, the entire simplex is contracted closer to the lowest point with $P_i = (P_i + P_l)/2$.\n\\end{description}\n\nEach step in the Nelder--Mead method begins with a proposed reflection of the least optimal point about its centroid position.\nFrom there, the method follows the protocol described above.\nThe choice of $\\alpha$, $\\beta$, and $\\gamma$ is somewhat arbitrary and should be optimized by-hand.\nAn example of the centroid locations for minimization using this method with the Rosenbrock banana function~\\cite{pohlheim2007} can be seen in Figure~\\ref{fig:minimize_NM}.\n\n\\begin{figure}\n\\center \\includegraphics[width=0.75\\textwidth]{data/1d/NM/NM.pdf}\n\\caption{Plot of the centroid locations (green dots connected with white line) for the Nelder--Mead method while optimizing the Rosenbrock banana function, $f(x,y)=(a-x)^2+b(y-x^2)^2$, with $a=1$ and $b=100$.\nHere, centroid locations start at $(-0.851,-1.553)$ and end at the known minimum of $(1,1)$ in 19 iterations.\nHere, $\\alpha = 1$, $\\beta = 0.5$, and $\\gamma = 1.5$.}\n\\label{fig:minimize_NM}\n\\end{figure}\n\nEven though the Nelder--Mead method is a heuristic approach and can become stuck in a local minimum, as long as a sufficient number of random simplexes are chosen at the start of the simulation, it can be used to find an adequately optimal solution.\nUltimately, any gradient-less optimization algorithm can be used to traverse the fidelity landscape for quantum optimal control, and in the next section, I will discuss a common method used in the field: the CRAB optimal control method.\n\n\\subsection{Chopped random basis optimal control}\n\\label{sec:CRAB}\n\nThe CRAB technique works by modifying a control parameter for a given system, $\\Gamma$, with a multiplicative term as\n\\begin{equation}\n\\Gamma^{\\text{CRAB}}(t) = \\Gamma^0(t)\\gamma(t),\n\\end{equation}\n\n\\noindent where $\\Gamma^0(t)$ is an initial guess, and the function $\\gamma(t)$ is written as a sum of $2J$ sinusoidal functions,\n\\begin{equation}\n\\gamma(t)=1+\\frac{1}{\\lambda(t)}\\sum_{j=1}^J(A_j \\sin(\\nu_jt) + B_j\\cos(\\nu_jt)).\n\\end{equation}\n\n\\noindent Here, $\\lambda(t)$ is usually defined by the system, such that $\\Gamma^{\\text{CRAB}}$ and $\\Gamma^0$ coincide at initial and final times.\nThis means that $\\lim_{t\\rightarrow 0} \\lambda(t) = \\lim_{t\\rightarrow T}\\lambda(t) = \\infty$, where $T$ is the final time of evolution.\nAs such, any smooth function may be chosen with these constraints.\nFor example, one might use\n\\begin{equation}\n\\lambda(t) = \\frac{T^2}{4t(t-T)},\n\\end{equation}\n\\noindent which satisfies the provided conditions.\nThis then transforms the optimization problem into an optimization of the space spanning $\\{A_j, B_j, \\nu_j\\}$, which can be done by using Nelder--Mead with a simplex of random initial points.\nAs an example, if $J = 10$, a thirty-dimensional space would be created and a thirty-one simplex would be formed to traverse this space.\nIt is important to remember that each new simplex and simplex-operation requires re-solving the Schr\\\"odinger equation for those values, and as such, this is a computational costly technique.\nEven though higher $J$ values will produce a more accurate result, lower values should be chosen, if possible.\n\nThis method is a general-purpose computational tool for determining the optimal pulse to ensure the generated state is as close to the desired state as possible, and I will show an example of it being used later in this chapter.\nEven so, it is sometimes worthwhile to attempt to devise analytical frameworks that serve a similar purpose, and for certain systems, this can be done with STA protocols.\n\n\\section{Shortcuts to adiabaticity}\n\nSTA protocols are semi-analytical methods that allow for quantum state generation while retaining the effects of adiabatic movement.\nHere, adiabatic processes are defined as actions by which slow changes in the control parameters leave particular properties invariant, such as the quantum number~\\cite{guery2019}.\nThe ultimate goal of STA protocols is to achieve adiabatic motion in sub-adiabatic time, and this can be done in a number of ways; however, in this section, I will introduce only the invariant-based inverse-engineering approach using Lewis--Riesenfeld invariants~\\cite{torrontegui2013}.\nIn particular, I will focus on the specific methods necessary for the example to be introduced later in this chapter and much of this section will follow traditional derivations from various sources~\\cite{torrontegui2013,guery2019, schloss2016}.\n\nWith the method of Lewis-Riesenfeld invariants, the theory for relating different eigenstates of a time-dependent, Hermitian invariant to the solutions to the Schr\\\"odinger equation~\\cite{lewis1969} can be applied to systems with time-dependent Hamiltonians, such that\n\\begin{equation}\ni\\hbar \\frac{\\partial I(t)}{\\partial t} - \\left[\\mathcal{\\hat H},I(t)\\right] = 0,\n\\end{equation}\n\\noindent where $I(t)$ is the invariant.\nThis ensures that the expectation values for the states driven by $\\mathcal{\\hat H}$ are constant in time.\nIt is possible to expand the state of the system $\\ket{\\Psi(t)}$ into the orthonormal basis of the invariant with,\n\\begin{equation}\n\\ket{\\Psi(t)} =\\sum_{n=1}^\\infty c_n e^{i\\alpha_n(t)} \\ket{\\phi_n(t)},\n\\end{equation}\n\\noindent where $c_n$ are time-independent amplitudes for each state, and $\\ket{\\phi_n(t)}$ are orthonormal eigenvectors of the invariant, such that\n\\begin{equation}\nI(t) = \\sum_n^\\infty\\ket{\\phi_n(t)}\\lambda_n\\bra{\\phi_n(t)}.\n\\end{equation}\n\\noindent Here, the $\\lambda_n$ are real constants, and the phase is defined as ~\\cite{lewis1969}\n\\begin{equation}\n\\alpha_n(t) = \\frac{1}{\\hbar}\\int_0^t\\braket{\\phi_n(t')|i\\hbar\\frac{\\partial}{\\partial t'} - \\mathcal{\\hat H}(t')|\\phi_n(t')}dt'.\n\\end{equation}\n\nFrom here, inverse engineering can be used to create the desired time-dependent Hamiltonian, by imposing some dynamics on the system.\nThe phases, $\\alpha_n(t)$ may be chosen as arbitrary functions to create a time-dependent, unitary evolution operator,\n\\begin{equation}\nU = \\sum_n^\\infty e^{i\\alpha_n(t)}\\ket{\\phi_n(t)}\\bra{\\phi_n(0)},\n\\end{equation}\n\\noindent that obeys $i\\hbar \\dot U = \\mathcal{\\hat H}(t)U$ and the dot is a time-derivative.\nIf one considers Hamiltonians of the Lewis and Leach variety~\\cite{lewis1982},\n\\begin{equation}\n\\mathcal{\\hat H} = \\frac{p^2}{2m}  -F(t)x + \\frac{m}{2}\\omega^2(t)x^2 + \\frac{1}{\\rho(t)^2}U\\left[\\frac{x-x_c}{\\rho(t)}\\right] + f(t),\n\\label{eqn:HSTA}\n\\end{equation}\nthere will be an invariant that is quadratic in momentum,\n\\begin{equation}\nI = \\frac{1}{2m}[\\rho(p-m\\dot x_c)-m\\dot \\rho(x-x_c)]2 + \\frac{1}{2}m\\omega_0^2\\left( \\frac{x-x_c}{\\rho} \\right)^2 + U\\left( \\frac{x-x_c}{\\rho}\\right).\n\\end{equation}\n\\noindent These equations are valid so long as $\\rho$, $x_c$, $\\omega$, and $F$ satisfy\n\\begin{align}\n\\ddot \\rho + \\omega^2(t)\\rho &= \\frac{\\omega_0^2}{\\rho^3} \\label{eqn:rho}\\\\\n\\ddot x_c + \\omega^2(t)x_c &= F(t)/m \\label{eqn:xc},\n\\end{align}\n\\noindent with $\\omega_0$ as a constant whose physical interpretation depends on the system.\nAs in the case of quantum optimal control, additional constraints must be considered to ensure the Hamiltonian and its invariant commute at initial and final times $t_0$ and $T$.\n\nNow that I have provided specific examples of methods used in quantum engineering, it is time to put them into practice with an example of creating large-scale superposition states non-adiabatically in the highly-correlated TG gas regime.\n\n\\section{Non-adiabatic generation of NOON states in a Tonks--Girardeau gas}\n\nFor this example application of quantum optimal control and STA protocols, I am interested in generating the maximally entangled $\\ket{N,0} + \\ket{0,N}$ (NOON) state, which is composed of two modes where all particles can be found exclusively in one or the other.\nRecently, Hallwood \\textit{et al.} proposed an experimentally realistic method to generate NOON states in a gas of strongly interacting, neutral bosons on a one-dimensional ring.\nIn this system, different rotational states can be coupled by breaking the rotational symmetry and it is possible to create superposition states with rotating and non-rotating components.\nBecause the atoms are considered to be in the strongly correlated TG gas regime, this process results in a macroscopically-entangled state.\nIt is worth discussing the TG gas in further detail before moving to the precise method of NOON state generation for this example.\n\n\\subsection{Tonks--Girardeau gas}\n\nAs mentioned in Chapter~\\ref{ch:splitop}, the TG gas consists of a number of bosons that have the properties of spinless, non-interacting fermions.\nThis is a particular case of the one-dimensional Schr\\\"odinger equation where the repulsive interaction strength $g\\rightarrow\\infty$.\nIn this case, the bosons cannot be at the same location, which acts formally similar to the Pauli-exclusion principle for fermionic systems.\nIn this case, the bosonic Hamiltonian can be solved by the Bose--Fermi mapping theorem \\cite{girardeau2001ground, girardeau2001measurement}, which replaces the interaction terms in the Hamiltonian with a boundary condition on the many-body bosonic wavefunction,\n\\begin{equation}\n\\Psi_B(x_1, x_2, \\ldots, x_N) = 0,\\qquad \\mathrm{if}\\qquad x_i - x_j = 0 \\quad\\textrm{with}\\quad i \\ne j,\n\\end{equation}\n\n\\noindent following the many-body Hamiltonian,\n\\begin{equation}\n\\mathcal{\\hat H} = \\sum_{n=1}^N\\left(\\frac{p_n^2}{2m} + V_n + b\\delta(x_n)\\right) + \\sum_{j<k}V(|x_j - x_k|).\n\\end{equation}\n\n\\noindent Here, $p_n = -i\\hbar\\frac{\\partial}{\\partial x_n}$, $V_n = \\frac{1}{2}m\\omega^2x_n^2$, $b\\delta(x_n)$ is a delta barrier with strength $b$, and $V$ is an interaction potential between bosonic particles.\nThis allows us to treat strongly interacting bosons as spinless, non-interacting fermions, for which the many-body wavefunction can be calculated using the Slater determinant~\\cite{slater1929},\n\\begin{equation}\n\\Psi_F (x_1, x_2, \\ldots, x_N) = \\frac{1}{\\sqrt{N}} \\det\\Big[\\psi_n(x_j)\\Big]_{n,j=1}^N,\n\\end{equation}\n\\noindent where $\\psi_n(x_j)$ are the single-particle eigenstates of the trapping potential $V_n$.\nBecause the fermionic many-body wavefunction is anti-symmetric, it needs to be symmetrized for bosonic states as, \n\\begin{equation}\n\\Psi_B(x_1, x_2, \\ldots, x_N) =\n\\prod_{i < j}\n\\mathrm{sgn}(x_i - x_j)\\Psi_F(x_1, x_2, \\ldots, x_N),\n\\end{equation}\n\\noindent which means that calculating the time evolution of a TG gas requires evolving single-particle states, governed by a much simpler Hamiltonian.\n\n\\subsection{NOON states in a TG gas}\n\\label{sec:controltro}\n\nSimilar to other ring systems introduced in the literature~\\cite{das2002,girardeau2009}, the system suggested by Hallwood \\textit{et al.} considers a gas of $N$ interacting bosons of mass $m$ on a one-dimensional ring with circumference $L$~\\cite{hallwood2010}.\nIn addition, this system includes a potential barrier, modeled by a Dirac $\\delta$-function that rotates with an angular frequency $\\Omega$, as shown in Figure~\\ref{fig:ring_scheme}.\nIn the rotating frame, the scaled Hamiltonian of the system in the rotating frame is given by \\cite{hallwood2010}\n\\begin{equation}H^{(N)} = \\sum_{n=1} ^{N} \\left[{\\frac{1}{2}\\bigg(-i\\frac{\\partial}{\\partial x_n}-\\Omega}\\bigg)^2 + b\\delta(x_n) +g \\sum_{j<k} ^{N} \\delta (x_j - x_k )\\right],\n\\end{equation}\n\\noindent where $b$ is the height of the barrier (in units of $\\hbar^2/mL^2$), $x_n \\in \\left[-1/2,1/2\\right]$ is the position of the $n$--th particle (in units of $L$) and $g$ (in units of $\\hbar^2/mL^2$) is the effective interaction strength between the atoms.\nAs discussed in the previous section, the evolution of the full TG gas can be calculated from the evolution of single-particle states, and in the case of this system, the Hamiltonian in the laboratory frame becomes,\n\n\\begin{equation}\nH = -\\frac{1}{2} \\frac{\\partial^2}{\\partial x} + b\\delta \\left[ x-x_0(t) \\right], \n\\end{equation}\nwhere $x_0$ is the position of the barrier at time $t$. \n\n\\begin{figure}\n\\center \\includegraphics[width = 0.5\\textwidth]{data/1d/scheme.pdf}\n\\caption{Schematic of the system.\nHere, the density profile for five atoms in a TG gas is shown being stirred by a highly localized potential, indicated by the vertical line.}\n\\label{fig:ring_scheme}\n\\end{figure}\n\nThe energy spectrum of this system is shown in Figure~\\ref{fig:avoid} as a function of the rotational frequency $\\Omega \\equiv \\dot x_0 /L$ of the system.\nIn Figure~\\ref{fig:avoid}(a) it is shown that in the absence of a barrier, when the eigenstates of $\\mathcal{\\hat H}$ are plane waves with quantized angular momentum in integer multiples of $2 \\pi$, each angular momentum manifold exists separately such that the energy levels cross; however when $b>0$ (Figure~\\ref{fig:avoid}(b)), the rotational symmetry is broken and avoided crossings appear in the energy spectrum.\nThis makes transitions between different manifolds possible~\\cite{schenke2012}.\n\n\\begin{figure}\n\n \\centering\n \\subfigure{\n \\centering\n \\includegraphics[width = 0.4\\linewidth]{data/1d/cross.png}} \n \\subfigure{\n \\centering\n \\includegraphics[width = 0.4\\linewidth]{data/1d/nocross.png}}\n\n\\caption{Single-particle energy spectrum as a function of $\\Omega$ for a barrier height of (a) $b = 0$ and (b) $b=2$.\nWhen a barrier is present in the system, avoided crossings appear in the energy spectrum which grow as the barrier strength increases.}\n\\label{fig:avoid}\n\\end{figure}\n\nBy adiabatically accelerating the barrier's rotational frequency from 0 to $\\pi$, a particle will enter a superposition between two rotational states, and in the case of the TG gas, this will create a macroscopic NOON superposition state between successive values of angular momentum~\\cite{hallwood2010}.\nThis means that the manifolds will have an angular momentum of 0, 1, 2, $\\ldots$, $N$, where $N$ is the number of particles in the system.\nAny non-adiabatic behavior around the rotational frequencies of the avoided crossings can lead to a transition to a higher energy state and destroy the NOON state.\nFor this reason, the condition for adiabaticity must depend on the gap size, which is dictated by the barrier strength~\\cite{nunnenkamp2008}; however, for a constant delta barrier, the gap size stays constant to first-order approximation~\\cite{hallwood2007}.\n\nBecause this system requires adiabatic movement to properly generate the NOON state, it is difficult to efficiently generate it experimentally.\nFor this reason, it is a perfect example of a system where quantum optimal control and STA protocols can be used to rapidly engineer the appropriate states.\nFor quantum optimal control in this system, a non-adiabatic rotational frequency $\\Omega(t)$ must be found, for which I will use the CRAB technique with an initial condition of $\\Omega = 0$ and final condition of $\\Omega = \\pi$.\nFor each simulation in the fidelity landscape, this pulse will be modified with procedurally generated sinusoidal functions, the fidelity will be calculated, and then the Nelder--Mead method will be used to optimize the result.\nThis will allow one to determine an optimal pulse that maximizes the fidelity of the generated state when compared to the expected NOON state in a pre-set amount of time.\nFor this system, I will show the optimal pulse for the cases where I manipulate the rotational velocity, the barrier height, and both.\n\nFor STA protocols, the acceleration process will be split into two, one that breaks the rotational symmetry and another that accelerates the atoms.\nAt the end of the protocol, the potential is lowered to restore rotational symmetry.\nHere, it is worth mentioning that a FAst, QUasi-ADiabatic (FAQUAD) shortcut for the creation of superposition states in a TG gas has also been created with some similarities~\\cite{garaot2015}.\n\nFor both of these methods, instead of calculating the fidelity I calculate the \\textit{infidelity}, which is simply $1-\\mathcal{F} = 1-|\\braket{\\Psi|\\Phi}|^2$, as the function to minimize.\nIt is also worth mentioning that the fidelity between two many-particle states in a TG gas can be calculated by using the method of mode projections~\\cite{campo2011,lelas2011},\n\\begin{eqnarray}\n\\braket{\\Psi | \\Phi} &=& \\frac1{N!} \\sum_{\\eta, \\mu \\in P} \\epsilon_\\eta \\epsilon_\\mu \\braket{\\psi_{\\eta_1}(x_1) | \\phi_{\\mu_1}(x_1) } \\cdots \\braket{ \\psi_{\\eta_N}(x_N) | \\phi_{\\mu_N}(x_N) } \\nonumber \\\\\n\\label{eq:fid}\n&=&\n\\det \\Big[ \\braket{\\psi_i | \\phi_j }\\Big]_{i,j=1}^N\n\\end{eqnarray}\nwhich follows directly from the form of the TG state~\\cite{girardeau1960}\n\\begin{equation}\n\\Psi(x_1,x_2,\\ldots, x_N)= \\frac1{\\sqrt{N!}} \\prod_{i<j}\\textnormal{sign}(x_i-x_j) \\sum_{\\eta \\in P} \\epsilon_\\eta \\psi_{\\eta_1}(x_1)\\cdots\\psi_{\\eta_N}(x_N).\n\\label{eq:TG}\n\\end{equation}\nHere $P$ represents the set of all permutations of $N$ elements, $\\epsilon_\\eta$ represents the anti-symmetric tensor of the permutation $\\eta$, and $\\psi_i$ represent the orbitals.\nNow I will discuss the findings with both quantum optimal control and STA protocols.\n\n\n\\subsection{Quantum optimal control protocols}\n\n\\begin{figure}\n \\centering\n \\subfigure{\n \\centering\n \\includegraphics[width=0.45\\textwidth]{data/1d/figR0.pdf}}\n \\subfigure{\n \\centering\n \\includegraphics[width=0.45\\textwidth]{data/1d/figB0.pdf}}\n \\caption{Accelerating a single particle from the ground state with $J=15$.\n (a) Optimal rotational velocity pulses for $T = 1$, 10, and 100 for fixed barrier height $b=1$.\n (b) Optimal barrier height for a linearly increasing rotational velocity, $\\Omega = \\pi t/T$ for $T=1$, 10, and 100.}\n \\label{fig:pulses}\n\\end{figure}\n\nFirst, I will focus on the acceleration of a single particle, initially in the ground state of the system.\nFigure~\\ref{fig:pulses} (a) shows the results of this simulation if the barrier height is kept constant and one assumes an initial unmodified pulse that corresponds to a linear ramp from $\\Omega = 0$ to $\\pi$ for a preset total time, $T$.\nFor longer evolution times, there are many local maxima for the fidelity, and \nas such, longer evolution times effectively produce noisy signals and the Nelder--Mead method converges on one of many local minima.\nFor shorter evolution times, the pulse greatly affects the system and the shapes vary greatly from the initial linear ramp.\nThe infidelities for the linear guess pulse and its corresponding optimized pulse can be found in Figure~\\ref{fig:lfid}, and one can see an improvement of several orders of magnitude.\nHere, for longer evolution times, the initial linear pulse is a reasonable method to generate NOON states with an infidelity of $10^{-2}$ because it is already close to adiabatic; however, even in this case, the NOON state generation fidelity is better with optimization.\nFor all quantum optimal control results in this chapter, the CRAB method was run 100 times and the data with the highest fidelity was kept.\n\nFor optimizations of the barrier strength, a simple linear ramp for $\\Omega$ and an initial and final height for the barrier of $b = 1$ were chosen.\nThe optimal pulses for the barrier height for $T=1$, 10, and 100 are shown in Figure~\\ref{fig:pulses}(b) and shorter evolution times similarly produce larger deviations from the initial pulse.\nAgain these pulses lead to significant improvements in the fidelity shown in Figure~\\ref{fig:lfid}.\n\n\\begin{figure} \n\\centering\n \\subfigure{\n \\centering\n \\includegraphics[width=0.45\\textwidth]{data/1d/figR1.pdf}\n }\n \\subfigure{\n \\centering\n \\includegraphics[width=0.45\\textwidth]{data/1d/figB1.pdf}\n }\n \\caption{\n Optimal pulses to accelerate a single particle initially in the ground state of the trap\n for $T = 1$, 10, and 100 for the (a) rotational velocity and (b) barrier height when optimizing over both simultaneously. }\n \\label{fig:pulses_pair}\n\\end{figure}\n\nWith the CRAB method, it is possible to optimize over as many control parameters as one would like, and as such, it is possible to optimize over both the barrier strength and rotational frequency.\nThe results can be seen in Figure~\\ref{fig:pulses_pair}, where (a) is the modified rotational frequency and (b) is the barrier height.\nWhen comparing to the previous cases, similar trends emerge.\nIn particular, shorter evolution times result in less noisy optimizations when compared to longer evolution.\nEven so, all sets of pulses are radically different when compared to optimizations over a single variable.\nWhen comparing the fidelities in Figure~\\ref{fig:lfid}, it is clear that optimizations over rotation alone provide the simplest method to optimize the fidelity.\nIt is likely that each run of the CRAB method is stuck in a local minimum in the fidelity landscape at some point and that optimization over both variables can provide the same optimization as rotating, alone.\n\n\\begin{figure}\n \\centering \\includegraphics[width=0.5\\textwidth]{data/1d/figlfid.pdf}\n\\caption{ Infidelities as a function of the overall process time for optimally controlled rotational acceleration, barrier height, or both.\nHere, `linear' refers to an unoptimized linear acceleration from $\\Omega = 0$ to $\\pi$ while keeping the barrier height fixed at $b=1$.\n}\n\\label{fig:lfid}\n\\end{figure}\n\n\\begin{figure}[t]\n \\centering\n \\subfigure{\n \\centering\n \\includegraphics[width=0.45\\textwidth]{data/1d/figTG3.pdf}\n }\n \\subfigure{\n \\centering\n \\includegraphics[width=0.45\\textwidth]{data/1d/figTG5.pdf}\n }\n \\caption{\nInfidelities for the evolution of a TG gas with (a) $N=3$ and (b) $N=5$ particles using the CRAB optimal control technique.\nThe infidelities for optimized pulses with the particle at the Fermi edge is shown as blue crosses, and for the full TG gas as red circles.\nHere, the green squares show the fidelity of a linear pulse for the atom closest to the Fermi edge.\nA clear range where the CRAB algorithm is effective for generating NOON states with multiple particles can be clearly identified.}\n \\label{fig:TGOC}\n\\end{figure} \n\n\nAs such, when discussing the dynamics of a TG gas with 3 and 5 particles, I have only optimized over rotation.\nBecause of the Bose--Fermi mapping theorem, the evolution of an $N$-particle TG gas can be calculated by evolving a gas of $N$ spinless fermions.\nIn the zero-temperature limit, the fermions in the initial and target state create a Fermi sea by filling the lowest $N$ energy levels.\nIn this case, only atoms near the Fermi edge can transition into empty states and it is thus crucial to optimize the dynamics of the overall gas with respect to the particle with highest energy~\\cite{garaot2015}.\nIn Figure~\\ref{fig:TGOC}, I show the fidelity for the particle closest to the Fermi edge and the entire TG gas for $N=3$ and 5.\nIn this figure, one can see that by performing the optimization for the atoms near the Fermi edge, one can increase the fidelity of the entire gas for certain regimes; however, in contrast to Figure~\\ref{fig:lfid}, there seems to be no fidelity increase from a linear pulse for short evolution times.\nOne can also observe what appears to be a crossover regime where optimizations of the particle at the Fermi edge seem to fail, but evolution of the entire gas is still slightly better than the linear pulse.\nIt is clear that the CRAB method creates highly effective pulses; however, for very short and long evolution times, the fidelity increase from a linear pulse is not as drastic.\n\n\\subsection{Results with STA protocols}\n\n\\begin{figure}\n\\centering\n\\includegraphics[width=0.8\\textwidth]{data/1d/STAscheme.png} \n\\caption{Scheme for the acceleration of a single atom using STA.\n In this example, the homogeneous ground state gets localized, accelerated and released at the angular velocity of $\\Omega=\\pi$ into the state\n $\\left( \\exp(i 2\\pi x) +1 \\right) /\\sqrt 2$.\n The atomic density is indicated in blue and the potential is in red.}\n\\label{fig:STA-scheme}\n\\end{figure}\n\n\nIn this section, I will describe an STA protocol to generate NOON states in this system non-adiabatically, and though this was mentioned briefly in Section~\\ref{sec:controltro}, it will be described more rigorously here.\nIn this case, I will start with rotational symmetry and break break this symmetry by introducing a time-dependent external potential at $t=0$ and removing it in the end.\nFor this, we do not choose a $\\delta$ function, but instead a harmonic or sinusoidal potential along the ring.\n\nThe protocol consists of five steps:\n\\begin{enumerate}\n\\item Adiabatic raising of a weak harmonic or sinusoidal potential around the ring.\n\\item Fast tightening of this potential to localize the particles.\n\\item Accelerating the particles by moving the center of the potential.\n\\item Loosening the potential by reversing step 2.\n\\item Adiabatic lowering of the harmonic or sinusoidal potential.\n\\end{enumerate}\nA schematic of this process is shown in Figure~\\ref{fig:STA-scheme}.\nFor steps 2-4, pre-existing STA protocols can be used, and these will be discussed in this section.\nThe full protocol for the TG ring example will follow the STA methods outlined above with Lewis--Riesenfeld invariants and in this case, one needs to fulfill boundary conditions such that $\\mathcal{\\hat H}(t_0) = \\mathcal{\\hat H}(T)=p^2/2m$.\nTo be clear, the NOON states created with the STA protocol are slightly different those generated with quantum optimal control, as the STA variant does not rely on a $\\delta$ barrier.\n\nOne of the two shortcuts explored for this system involves raising and lowering a harmonic potential~\\cite{chen2010,chen20102}.\nFor this shortcut, a stationary harmonic potential is required and $F$, $x_c$, and $U$ from Equation~\\eqref{eqn:HSTA} can all be set to zero, leading to\n\\begin{equation}\n \\mathcal{\\hat H}= -\\frac{1}{2} \\frac{\\partial^2}{\\partial x}+ \\frac 1 2 \\omega^2(t) x^2.\n\\end{equation}\n\\noindent To change the frequency while keeping the commutation relations and $\\omega(t)$ continuous, one must impose the following conditions:\n\\begin{equation}\n \\begin{array}{lcl}\n\\rho(t_0)=1, && \\rho(t_f)=\\gamma=\\sqrt{\\omega_0 / \\omega_f},\\\\\n\\dot \\rho(t_0)=0, && \\dot \\rho(t_f) =0, \\\\\n\\ddot \\rho(t_0)=0, && \\ddot \\rho(t_f)=0.\n\\end{array} \\label{eqn:squeeze}\n\\end{equation}\n\n\\noindent \\noindent Which, together with Equations~\\eqref{eqn:rho} and \\eqref{eqn:squeeze} allow one to choose any form of $\\rho$.\nA good choice is the polynomial,\n\\begin{equation}\n \\rho (s) = 6 \\left(\\gamma -1\\right) s^5 -15 \\left(\\gamma-1\\right) s^4 +10 \\left(\\gamma-1\\right)s^3 + 1, \\label{eq:rho_pol}\n\\end{equation}\n\\noindent where $s=(t-t_0)/(t_f-t_0)$ allows one to numerically find a solution for $\\omega(t)$ that leads to the squeezing or expansion of the particle wavefunction with high fidelity in a short time.\nAs an important note, for small values of $\\omega_0$, Equation~\\eqref{eqn:rho} leads to purely imaginary values for $\\omega(t)$, corresponding to repulsive potentials.\nIn order to avoid this and because the final states of this protocol require the external potential to be absent, the first and final steps in the protocol for this system involve adiabatically raising and lowering a potential to a suitable $\\omega_0$ value. \n\nOnce the potential has been raised, the particles are then accelerated to the chosen frequency, and a shortcut for this process with a harmonic trap exists~\\cite{masuda2009,torrontegui2011,masuda2012}.\nIn the rotational shortcut, the trapping frequency is held constant and the position of the potential is modified.\nThis means that $U=0$, $F=\\omega_0^2 x_0(t)$, and\n\\begin{equation}\n H= -\\frac{1}{2} \\frac{\\partial^2}{\\partial x}+ \\frac 1 2 \\omega^2_0 (x-x_0(t))^2.\n\\end{equation}\n\\noindent Here, Equation~\\eqref{eqn:xc} becomes the only relevant auxiliary equation,\n\\begin{equation}\n \\ddot{x}_c+\\omega^2_0 (x_c-x_0)=0,\n\\end{equation}\nand the conditions that must be imposed on $x_c$, are such that\n\\begin{equation}\n \\begin{array}{lcl}\nx_c(t_0)=x_0(t_0), && x_c(t_f)=d,\\\\\n\\dot x_c(t_0)=0, && \\dot x_c(t_f) =\\Omega_f, \\\\\n\\ddot x_c(t_0)=0, && \\ddot x_c(t_f)=0,\n\\end{array}\n\\end{equation}\n\\noindent where $d$ is the final position of the potential minimum and $\\Omega_f$ is its final velocity. \nFor most applications of this shortcut, $d$ is important, and $\\Omega_f$ is set to zero; however, this case is the opposite.\n\nLike for the shortcut for raising the potential, the exact form of $x_c$ can be chosen somewhat arbitrarily, and a convenient choice is\n\\begin{equation}\n x_c(s)= (6 d -3 \\Omega_f )s^5 - (15 d-7 \\Omega_f )s^4+(10d-4 \\Omega_f) s^3 + x_0(t_0),\n\\end{equation}\nwhere, as above, $s$ is the normalized time.\nThe value of $\\Omega_f$ can then be chosen to be odd multiples of $\\pi$ to generate the desired NOON states based on the energy spectrum shown in Figure~\\ref{fig:avoid}.\n\nUnlike the shortcut to raise the potential, this shortcut is only approximate and works best when $\\omega$ is large so that the particles are highly localized.\nBoth of these shortcuts rely on the presence of a harmonic potential of the form\n\\begin{equation}\n V_{H}(x,t)=\\frac 1 2 \\omega^2(t) \\left( x-x_0(t)\\right)^2, \n\\end{equation}\nwhere  $\\omega$ is the frequency of the trap (in units of $\\hbar/mL^2$) and $x_0$ the position of its minimum.\nIn the case of the TG ring, the potential must be symmetric around $x_0$, such that it is continuous at $x=\\pm 1/2$; therefore, the real form of $(x-x_0)$ must be $(x-x_0+1/2)(\\mathrm{mod~} 1)-1/2$.\nThe potential $V_H$ is then continuous everywhere on the ring, but its derivative is discontinuous at $x=x_0+1/2$ because this position is diametrically opposite to $x_0$.\nThough $V_H$ is easy to work with theoretically, it is not necessarily experimentally realistic, and for this reason, we also consider a sinusoidal potential of the form~\\cite{phelan2013,masuda2014},\n\\begin{equation}\n V_{S}(x,t)= \\frac{\\omega^2(t)}{2 \\pi^2} \\sin^2 \\left(\\pi \\left( x-x_0(t)\\right) \\right) ,\n\\end{equation}\nwhere the notation is the same as before. \nHere, prefactors are chosen such that $V_{H}$ is an approximation of $V_S$ around $x_0$.\n\n\\begin{figure}\n\\centering\n\\subfigure{\n\\centering\n\\includegraphics[width=0.48\\linewidth]{data/1d/fig1.png}}\n\\subfigure{\n\\centering\n\\includegraphics[width=0.48\\linewidth]{data/1d/fig2.png}}\n\n\\caption{ Energy eigenspectrum of the system with (a) a harmonic or (b) a sinusoidal potential as a function of $\\omega$. \nThe eigenstates continuously change from angular momentum states of energy $E_k=2\\pi^2 k^2$ (with $k=0,\\pm1,\\ldots$) at $\\omega=0$, towards harmonic-oscillator states of energy $E_n=\\omega(n+1/2)$ (with $n=0,1,\\ldots$) for large $\\omega$.\nFor comparison, the horizontal lines on the right vertical axis give the energy levels in a harmonic potential with $\\omega=200$.}\n\\label{fig:spectrum}\n\\end{figure}\n\nIn Figure~\\ref{fig:spectrum}, I show the difference between the two potentials by computing the energy spectra of both Hamiltonians.\nHere, the eigenstates at $\\omega=0$ are the angular momentum states $e^{i 2 \\pi k x}$, with degenerate clockwise and counterclockwise momentum states of opposite quantum number $k$.\nAs $\\omega$ is increased, the degeneracy ceases and the spectrum asymptotically approaches that of a harmonic oscillator.\nFor the sinusoidal case, the difference with the harmonic spectrum increases with the quantum number $n$.\n\n\\begin{figure}\n\\centering\n\\includegraphics[width=0.45\\linewidth]{data/1d/fig5.png}\n\\includegraphics[width= 0.45\\linewidth]{data/1d/fig6.png}\n\\caption{\n(a) Plot of the parameters $\\omega(t)$ and the angular velocity $\\Omega(t)$ for the entire protocol.\nThe parameters are $\\omega_0=2$, $\\omega_f=100$, $d=100$, each step is executed in $t_f-t_0=10$, and $\\Omega_f$ is picked depending on the desired output state (here, $\\Omega_f=5 \\times 2\\pi$).\n(b) Final infidelities for $\\Omega_f=1,2,\\ldots,10 \\times 2\\pi$ for $V_H$ (dotted blue line) and $V_S$ (solid red line).\nThe rest of parameters are as shown in (a).\n}\n\\label{fig:final+param}\n\\end{figure}\n\nLike the case of quantum optimal control, I will first show the single-particle results.\nIn Figure~\\ref{fig:final+param}(a), the values for $\\omega(t)$ and $\\Omega(t)$ are shown, and\nin Figure~\\ref{fig:final+param}(b), the infidelities for the state preparation of plane waves $e^{i \\Omega_f x}$ with $\\Omega_f=1\\ldots10 \\times 2 \\pi$ are shown.\nHere, it is clear that even for a large amount of angular momentum, the fidelities remain high for both the harmonic and sinusoidal potentials.\n\nFor a multi-particle case in the TG regime, the initial states for the particles will be eigenstates of free space, which are simply plane waves $e^{i 2 \\pi k x}$ with integer $k$.\nBecause the states with $\\pm k$ are degenerate, it is equally valid to consider the initial eigenstates\n\\begin{align}\n\\phi^i_0(x)&=1,\\\\\n\\phi^i_{2l-1}(x)&=\\frac{1}{\\sqrt 2} \\left( e^{i 2 \\pi l x}-e^{-i 2 \\pi l x} \\right)= i \\sqrt{2} \\sin(2 l \\pi x), \\\\\n\\phi^i_{2l}(x)&= \\frac{1}{\\sqrt 2}\\left( e^{i 2 \\pi l x}+e^{-i 2 \\pi l x} \\right) = \\sqrt{2} \\cos(2 l \\pi x),\n\\end{align}\nfor $l=\\{1,2,\\ldots\\}$.\nThese states have a total angular momentum of zero and are well-suited for the provided STA protocol because when an odd number of particles occupies the lower eigenstates, the sine and cosine pairs are guaranteed to be populated.\n\nFor $\\Omega_f=\\pi$, the plane wave of quantum numbers $k+1$ and $-k$ are degenerate and one can construct the target states\n\\begin{align}\n\\phi^t_{2l}(x)&=\\frac{1}{\\sqrt 2} \\left( e^{i 2 \\pi (l+1) x} + e^{-i 2 \\pi l x} \\right) = \\sqrt{2} \\cos[(2l+1) \\pi x] e^{i \\pi x} , \\\\\n\\phi^t_{2l+1}(x)&=\\frac{1}{\\sqrt 2} \\left( e^{i 2 \\pi (l+1) x}-e^{-i 2 \\pi l x} \\right) = i \\sqrt{2} \\sin[(2l+1) \\pi x]e^{i \\pi x} ,\n\\end{align}\nfor $l=\\{0,1,2,\\ldots\\}$.\nThe states with total angular momentum $\\pi$ are similar to NOON states.\n\n\\begin{figure}\n\\centering\n\\subfigure{\n\\centering\n\\includegraphics[width= 0.45\\linewidth]{data/1d/fig7a.png} }\n\\subfigure{\n\\centering\n\\includegraphics[width= 0.45\\linewidth]{data/1d/fig7b.png}}\n\\caption{ Final fidelities $F$ of TG states of increasing particle number for the protocol shown in Figure \\ref{fig:final+param}(a) with $\\Omega_f = \\pi$ for $V_H$ (red circle) and $V_S$ (blue cross). Plot (a) shows the fidelity of the protocol with $\\omega_f = 100$ and (b) with $\\omega_f = 200$.}\n\\label{fig:TG-STA}\n\\end{figure}\n\nAny initial state $\\ket{\\phi^i_l}$ can be brought to the target state $\\ket{\\phi^t_l}$ with high fidelity with the proposed protocol, and the process also works for TG gases.\nIn Figure~\\ref{fig:TG-STA}(a), the harmonic potential fidelities are shown to remain high for $N \\leq 11$ after which they decrease due to a finite maximum height of the potential enforced by periodic boundary conditions.\nThe fidelities can be improved by increasing the maximum trapping frequency $\\omega_f$ as was demonstrated in Figure \\ref{fig:TG-STA}(b) where the value of $\\omega_f$ is doubled and the fidelities remain high until $N \\leq 21$.\nWhen using the sinusoidal potential, the fidelity drops for smaller particle numbers compared to the  harmonic potential (although it also increases with $\\omega_f$), due to the lower height $V_S$ has compared to $V_H$.\n\n\\section{Outlook}\n\nIn this chapter, quantum optimal control and STA protocols were introduced to optimize quantum engineering tasks in cold atomic gases.\nI have introduced a physical system to generate NOON states in a TG gas non-adiabatically with both methods, and they were shown to be highly effective.\nSuch dynamical evolution techniques require time-dependent control parameters, such as rotation frequency or barrier height, and allowing for these dynamic operations has hitherto been a difficult task on GPU hardware.\nIn the following chapter, I will discuss GPU hardware in-depth and also tackle this issue, along with several others noted in Chapter~\\ref{ch:splitop}.\n\n", "meta": {"hexsha": "ade0019a173a9202ebcf37a441c993e061e1f403", "size": 43890, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "MainText/1d.tex", "max_stars_repo_name": "leios/thesis", "max_stars_repo_head_hexsha": "0fdbfdc9b42a967a9b3492be4ab788bdf76d4ce5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2019-02-12T02:41:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-03T09:46:28.000Z", "max_issues_repo_path": "MainText/1d.tex", "max_issues_repo_name": "leios/thesis", "max_issues_repo_head_hexsha": "0fdbfdc9b42a967a9b3492be4ab788bdf76d4ce5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-02-07T08:22:21.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-07T08:22:21.000Z", "max_forks_repo_path": "MainText/1d.tex", "max_forks_repo_name": "leios/thesis", "max_forks_repo_head_hexsha": "0fdbfdc9b42a967a9b3492be4ab788bdf76d4ce5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-02-07T08:07:50.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-07T08:07:50.000Z", "avg_line_length": 80.0912408759, "max_line_length": 417, "alphanum_fraction": 0.7647983595, "num_tokens": 11688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.31575125052790814}}
{"text": "\\section{Modal pomsets}\nIn order to perform a sharper analysis of dependency, we present an alternate\nsemantics using modal pomsets defined below.  Modal pomsets make a formal\ndistinction between strong order and weak order.\n\\begin{definition}\n  A \\emph{modal (memory model) pomset} is a tuple\n  $(\\Event, {\\sle}, {\\gtN},\n  \\labeling)$, such that\n  \\begin{itemize}\n   \\item $(\\Event, {\\gtN},\n  \\labeling)$ is a (memory model) pomset, and \n\\item ${\\sle} \\subseteq {\\gtN}$ is a partial order. \n  \\end{itemize}\n\\end{definition}\nWe write $\\bEv\\slt\\aEv$ when $\\bEv\\sle\\aEv$ and $\\bEv\\neq\\aEv$, and similarly for $\\gtN$.   Thus, $(\\sle \\cup \\reco)^{*} \\subseteq {\\gtN}$.  \n\nWe list out a few observations to illustrate the relationship between \\tvalpom s and pomsets.  We are given a  \\tvalpom, \n  $(\\Event, {\\sle}, {\\gtN}, \\labeling)$.  Then:\n\\begin{itemize}\n\\item $(\\Event, {\\gtN},\\labeling)$ is a pomset with the same reads-from relation.  \n\n\\item Let $\\reco$ be the restriction of $\\gtN$ to conflicting actions on the same location.  Then, $(\\Event, {\\sle}, (\\sle \\cup \\reco)^{*}, \\labeling)$ is a \\tvalpom, and $(\\sle \\cup \\reco)^{*} \\subseteq {\\gtN}$.\n\\end{itemize}\n\n\\paragraph*{Changes to definitions}\nThe definition of the semantics of programs using \\tvalpom\\ largely follows the one using pomsets.  We sketch the changes to definitions below.\n\n\\begin{itemize}\n\\item\n  We say that $\\bEv$ \\emph{fulfills $\\aEv$ on $\\aLoc$} if $\\bEv$ writes\n  $\\aVal$ to $\\aLoc$, $\\aEv$ reads $\\aVal$ from $\\aLoc$,\n  \\begin{itemize}\n  \\item $\\bEv \\slt \\aEv$, and\n  \\item if an event $\\cEv$ writes to $\\aLoc$ then either $\\cEv \\gtN \\bEv$ or $\\aEv \\gtN \\cEv$.\n  \\end{itemize}\n\n\\item \nAugmentation has to include ${\\slt}$. i.e \n$\\aPS'$ is an \\emph{augmentation} of $\\aPS$ if $\\Event'=\\Event$,\n  ${\\labeling'}={\\labeling}$, ${\\sle'}\\supseteq{\\sle}$, and\n  ${\\gtN'}\\supseteq{\\gtN}$.\n\n\\item The definitions of substitution, restriction and the filtering\n  operations  stay the same, with $\\sle$ carried over unchanged.  For\n  example, substitution is defined as follows:\n\nLet $\\aPSS\\aSub$ be the set $\\aPSS'$ where $\\aPS'\\in\\aPSS'$ whenever\nthere is $\\aPS\\in\\aPSS$ such that:\n$\\Event' = \\Event$,\n${\\sle'} = {\\sle}$, \n${\\gtN'} = {\\gtN}$,\nand\n$\\labeling'(\\aEv) = (\\bForm\\aSub \\mid \\aAct)$ when $\\labeling(\\aEv) = (\\bForm \\mid \\aAct)$.\n\n\n\\item In composition,we require ${\\sle'}\\supseteq{\\sle^1}\\cup{\\sle^2}$\n\n\\item The changes to the definition \\ref{def:prefix} of prefixing are as follows.  The key changes are that synchronization and dependency enforce $\\slt$ whereas coherence only enforces $\\gtN$. \n\\begin{itemize}\n\\item ${\\sle'}\\supseteq{\\sle}$.\n\n% \\item Item 5b changes to: if $\\aEv$ is a write then either $\\cEv\\slt'\\aEv$\n% or $\\labelingForm'(\\aEv)$ implies $\\labelingForm(\\aEv)$.\n\n\\item 5b changes to: if $\\bEv$ and $\\aEv$ are \\external actions in conflict, then $\\bEv \\gtN' \\aEv$,\n% \\item Item \\ref{pre-coherence} changes to:\n%  if $\\aAct$ is a write that conflicts with $\\labelingAct(\\aEv)$ \n%     then $\\cEv \\gtN' \\aEv$,\n\n\\item Item 5a, 5c, 5d, 5e 5c change to impose $\\slt$ order: eg. if $\\aAct$ is an acquire or $\\labelingAct(\\aEv)$ is a release then $\\cEv \\slt' \\aEv$.\n\\end{itemize}\n\\end{itemize}\nWe use $\\tsem{\\aCmd}$ to stand for the \\tvalpom\\ semantics of $\\aCmd$.  \n\n\\subsection{Generators. } Modal pomsets provide a characterization of generators from section~\\ref{sec:sc}.  \n\nRecall that \\emph{generators} in the pomset semantics are pomsets that are minimal with respect to augmentation and implication.  These generators are induced by pomsets  that are minimal with respect to augmentation and implication in the \\tvalpom\\ semantics  in the following sense.  \n\n$(\\Event, {\\gtN},\\labeling)$ is a generator for $\\sem{\\aCmd}$ \nif there exists  $(\\Event, \\slt, {\\gtN},\\labeling) \\in \\tsem{\\aCmd}$ minimal w.r.t.~augmentation and implication, and  $\\gtN = (\\sle \\cup \\reco)^{*}$.\n\nFurthermore, any strong order that is outside of program order must be induced by a reads-from.  In the two-thread case, we can state the latter\nproperty as follows: suppose $\\aEv$ and $\\bEv$ are not related by program\norder and $\\aEv\\slt\\bEv$; then there exist $\\bEv'$ that reads-from $\\aEv'$\nsuch that $\\aEv\\xpox\\aEv'$, $\\bEv'\\xpox\\bEv$ and\n$\\aEv \\slt \\aEv' \\slt \\bEv' \\slt \\bEv$.\n\n\\subsection{Closure properties}\nThe fine grain analysis of dependency in the modal semantics allows us to establish some closure properties of the semantics of programs.  \n\nWe consider programs of the\nform $\\vec{\\aLoc}\\GETS\\vec{0}\\SEMI\\FENCE\\SEMI\\aCmd$, where $\\aCmd$ is\nrestriction-free.  Thus, all memory locations are initialized to $0$,\ninitialization happens-before the execution of any command, \n\nWe say that $\\aPS' = \\aPS\\restrict{\\Event'}$ when \n $\\Event' \\subseteq \\Event$,\n ${\\labeling'} = {\\labeling}\\restrict{\\Event'}$,   and\n ${\\le'} = {\\le}\\restrict{\\Event'}$.\n% ${\\gtN'} = {\\gtN}\\restrict{\\Event'}$.\n\n\\begin{definition}\nLet $(\\aPS \\after \\aEv) = {\\{ \\bEv\\in\\Event \\mid \\aEv \\le \\bEv\n  \\}}$ be the set of events that follow $\\aEv$ in $\\aPS$.\n\\end{definition}\n\nThe semantics of read is ``input''-enabled, since it permits the read of any visible value.   Thus, any racy read in a program can be replaced by a read of a earlier value (w.r.t.~$\\reco$), even while  the races with existing independent writes are maintained.   A canonical example to keep in mind for this lemma is the program:\n\\begin{align*}\n  (y\\GETS 0 \\SEMI \\aReg \\GETS y  \\SEMI x \\GETS 1)\n  \\PAR\n  (x\\GETS 0 \\SEMI \\bReg \\GETS x \\SEMI y \\GETS 1)\n\\end{align*}\nwith both registers getting value $1$ via the execution:\n\\begin{tikzdisplay}[node distance=1em]\n\\event{wy0}{\\DW{y}{0}}{}\n\\event{ry1}{\\DR{y}{1}}{right=of wy0}\n\\event{wx1}{\\DW{x}{1}}{right=of ry1}\n\\event{wx0}{\\DW{x}{0}}{below=of wy0}\n\\event{rx1}{\\DR{x}{1}}{right=of wx0}\n\\event{wy1}{\\DW{y}{1}}{right=of rx1}\n\\rf{wx1}{rx1}\n\\rf{wy1}{ry1}\n\\wk{wx0}{rx1}\n\\wk{wy0}{ry1}\n\\end{tikzdisplay}\nThe lemma constructs the execution:\n\\begin{tikzdisplay}[node distance=1em]\n\\event{wy0}{\\DW{y}{0}}{}\n\\event{ry1}{\\DR{y}{0}}{right=of wy0}\n\\event{wx1}{\\DW{x}{1}}{right=of ry1}\n\\event{wx0}{\\DW{x}{0}}{below=of wy0}\n\\event{rx1}{\\DR{x}{0}}{right=of wx0}\n\\event{wy1}{\\DW{y}{1}}{right=of rx1}\n\\rf{wx0}{rx1}\n\\rf{wy0}{ry1}\n\\wk{rx1}{wx1}\n\\wk{ry1}{wy1}\n\\end{tikzdisplay}\n\n\n\\begin{lemma}\\label{inputen}\n%Let $\\aCmd = \\vec{\\aLoc}\\GETS\\vec{0}\\SEMI \\FENCE\\SEMI (\\aCmd^1 \\PAR \\cdots \\PAR \\aCmd^n)$.\nLet $\\aPS \\in \\tsem{\\aCmd}$ be a top level pomset.  \nLet $\\aEv \\in \\aPS$ read from write event $\\bEv$  on $\\aLoc$,  $\\neg(\\bEv \\xhb \\aEv)$.\nThen, there exists $\\bPS \\in \\tsem{\\aCmd}$ such that:\n\\begin{itemize}\n%\\item $(\\exists \\aEv' \\in \\Event_{\\bPS})$ such that $\n%\\Event_{\\bPS}$ is the disjoint union of  $\\Event_{\\aPS} \\setminus  \n%(\\aPS \\after \\aEv))$ and $(\\bPS \\after \\aEv')$.\n\\item $\\aEv'$ reads from $\\aLoc$, with matching write event $\\bEv'$, such that $\\bEv' \\xeco \\bEv$ in $\\bPS$\n\\item The restriction of $\\sle$  in $\\aPS$ to $\\Event_{\\aPS} \\setminus  (\\aPS \\after \\aEv)$ agrees with the restriction of $\\sle$ in $\\bPS$ to $\\Event_{\\bPS} \\setminus  (\\aPS \\after \\aEv)$  in  $\\bPS$.  \n\\item The restriction of $\\le$  in $\\aPS$ to $\\Event_{\\aPS} \\setminus  (\\aPS \\after \\aEv)$ agrees with the restriction of $\\le$ in $\\bPS$ to $\\Event_{\\bPS} \\setminus  (\\aPS \\after \\aEv)$  in  $\\bPS$.  \n\\end{itemize}\n\\end{lemma}\n\\begin{proof}\nThe form of $\\aCmd$ ensures that there is always a write to $\\aLoc$ that is related by $\\xhb$ to any read.  Thus, there is at least one other write than can satisfy the read recorded as  $\\aEv$.  \n\nThe key observation behind the proof is that change in a  prefixing read action can only affect the events that are dependent, ie. in the $\\slt$ order to the read action.  \n\\end{proof}\n\n\nIn the following lemma,  invert the $\\reco$ relationship between a read and a write.   A canonical example to keep in mind for this lemma is the program:\n\\begin{align*}\n(y\\GETS 0 \\SEMI   x \\GETS 1  \\SEMI \\aReg \\GETS y)\n\\PAR (x\\GETS 0 \\SEMI  y \\GETS 1  \\SEMI  \\bReg \\GETS x)\n\\end{align*}\nwith both registers getting value $0$ via the execution:\n\\begin{tikzdisplay}[node distance=1em]\n\\event{wy0}{\\DW{y}{0}}{}\n\\event{wx1}{\\DW{x}{1}}{right=of wy0}\n\\event{ry0}{\\DR{y}{0}}{right=of wx1}\n\\event{wx0}{\\DW{x}{0}}{below=of wy0}\n\\event{wy1}{\\DW{y}{1}}{right=of wx0}\n\\event{rx0}{\\DR{x}{0}}{right=of wy1}\n\\rf[bend right]{wx0}{rx0}\n\\rf[bend left]{wy0}{ry0}\n\\wk{rx0}{wx1}\n\\wk{ry0}{wy1}\n\\wk{wx0}{wx1}\n\\wk{wy0}{wy1}\n\\end{tikzdisplay}\nThe lemma constructs the execution:\n\\begin{tikzdisplay}[node distance=1em]\n\\event{wy0}{\\DW{y}{0}}{}\n\\event{wx1}{\\DW{x}{1}}{right=of wy0}\n\\event{ry0}{\\DR{y}{1}}{right=of wx1}\n\\event{wx0}{\\DW{x}{0}}{below=of wy0}\n\\event{wy1}{\\DW{y}{1}}{right=of wx0}\n\\event{rx0}{\\DR{x}{1}}{right=of wy1}\n\\rf{wx1}{rx0}\n\\rf{wy1}{ry0}\n\\wk{wx0}{wx1}\n\\wk{wy0}{wy1}\n\\end{tikzdisplay}\n\n\\begin{lemma}\\label{removerw}\nLet $\\aPS \\in \\tsem{\\aCmd}$ be a top-level pomset.   \nLet $\\bEv \\in \\aPS$ be a write on $\\aLoc$. \nLet $\\aEv \\in \\aPS$ read from $\\aLoc$ such that $\\aEv \\xeco \\bEv$ and $\\neg(\\aEv \\slt \\bEv)$.  Then, there exists $\\bPS \\in \\tsem{\\aCmd}$ such that:\n\\begin{itemize}\n\\item $\\aEv' \\in \\bPS \\setminus \\aPS$ reads from $\\aLoc$, with matching write $\\bEv$.\n\\item The restriction of $\\sle$ in $\\aPS$ to $\\Event_{\\aPS} \\setminus (\\aPS\\ \\after\\ \\aEv)$ agrees with the restriction of $\\sle$ in $\\bPS$ to $\\Event_{\\bPS} \\setminus  (\\aPS\\ \\after\\ \\aEv)$.  \n\\end{itemize}\n\\end{lemma}\n\\begin{proof}\nThe proof proceeds similar to the above proof; in this case, replace the value read in $\\aEv$ to come from $\\bEv$.  \n\\end{proof}\nAny new  event $\\bEv'$ in $\\bPS \\after \\aEv'$ reading from $\\aLoc$ cannot have a matching write event $\\bEv'' \\xeco \\bEv$ since that  implies $\\bEv' \\xeco \\bEv$ and a $\\reco$ cycle $\\bEv \\slt \\aEv \\slt \\aEv' \\xeco \\bEv$.  Thus, the above lemma can be iterated if the new pomset is has any further reads that precede $\\bEv$ in $\\reco$, so we can finally derive a pomset with no reads and writes satisfying the hypothesis of the lemma.   \n\n\n\nThe $\\reco$ order between writes that are not related by $\\lt$ can be reversed. \nA canonical example to keep in mind for this lemma is the program:\n\\begin{align*}\n(x\\GETS 1)\n\\PAR (x\\GETS 0)\n\\end{align*}\n\\begin{tikzdisplay}[node distance=1em]\n\\event{wy0}{\\DW{x}{1}}{}\n\\event{wx0}{\\DW{x}{0}}{right=of wy0}\n\\wk{wy0}{wx0}\n\\end{tikzdisplay}\nThe lemma constructs the execution:\n\\begin{tikzdisplay}[node distance=1em]\n\\event{wy0}{\\DW{x}{1}}{}\n\\event{wx0}{\\DW{x}{0}}{right=of wy0}\n\\wk{wx0}{wy0}\n\\end{tikzdisplay}\n\\begin{lemma}\\label{cohww}\nLet $\\aPS \\in \\tsem{\\aCmd}$ be a top level pomset.  Let $\\bEv, \\aEv$ be a writes to $\\aLoc$ such that:\n\\begin{itemize}\n\\item $\\bEv\\gtN \\aEv$  \n\\item for all writes $\\cEv$ to $\\aLoc$ such that  $ \\bEv \\gtN \\cEv \\gtN  \\aEv$,  it is the case that  $ \\neg(\\cEv \\slt \\aEv)$ and $\\neg(\\cEv \\xpox \\aEv)$\n\\end{itemize}\n\nThen, there exists $\\bPS \\in \\tsem{\\aCmd}$ such that $\\Event_{\\aPS} = \\Event_{\\bPS}$, $\\sle_{\\aPS} = \\sle_{\\bPS}$, and \n$\\aEv \\gtN \\bEv$ in $\\bPS$. \n\\end{lemma}\n\\begin{proof}\nWe show how to interchange $\\aEv, \\bEv$ adjacent in $\\gtN$, ie. we assume that  $\\neg(\\exists \\cEv) \\  \\bEv \\gtN \\cEv \\gtN \\aEv$.  The full proof follows by induction.\n\nSince  $\\sem{\\aCmd}$ is augmentation closed, it suffices to show that we can build $\\bPS$ while satisfying the constraints between $\\slt,\\gtN$.  We list the changes below.\n\\begin{itemize}\n\\item $\\aEv \\gtN \\bEv$ in $\\bPS$\n\\item For all reads $\\cEv$ matched to $\\aEv$, change from $\\bEv \\gtN \\cEv$ in $\\aPS$ to $\\cEv \\gtN \\bEv$ in $\\bPS$\n\\item For all reads $\\cEv$ matched to $\\bEv$, change from $\\cEv \\gtN \\aEv$ in $\\aPS$ to $\\aEv \\gtN \\cEv$ in $\\bPS$\n\\popQED\n\\end{itemize}\n\\end{proof}\n\n\\section{Proof of DRF}\\label{drfproof}\n\nIn this section of the appendix, we develop a proof of DRF for \\tvalpom s.  By the results in the earlier section, it yields DRF for the pomset semantics, since the races are identical in both models.\n\nIn the rest of this section, we assume that $\\aPS$ is a generator for\n$\\tsem{\\aCmd}$.\n\nWe prove:\n\\begin{description}\n\\item[DRF1: ] If $\\aPS$ does not have a race, $\\aPS \\in \\tsemsc{\\aCmd}$. \n\\item[DRF2: ] If $\\aPS$ has a race, then there exists $\\bPS\\in \\tsemClosed{\\aCmd}$ such that $\\bPS \\in \\tsemsc{\\aCmd}$ and has a race.\n\\end{description}\n\n\\paragraph*{Proof of DRF1}\nWe first show that if $\\aPS \\in \\tsem{\\aCmd} \\setminus \\tsemsc{\\aCmd}$, then $\\aPS$ has a race.  By assumption, there is a cycle in  $\\rpox \\cup \\slt \\cup \\xeco$.  Let this cycle be $\\aEv_0, \\aEv'_0, \\aEv_1, \\aEv'_1, \\ldots, \\aEv_n, \\aEv'_n, \\aEv_0$ where for all $i$, $\\aEv_i \\xpox \\aEv'_i$ and $\\aEv'_i  \\not\\xpox \\aEv'_{i+1}$.\nIf for all $i$, $\\aEv'_i  \\xhb \\aEv'_{i+1}$, then the above is a cycle in $\\rhb$, which is a contradiction.\nSo, there is at least one $i$ such that $\\aEv'_i  \\not\\xhb \\aEv'_{i+1}$.  There are two cases to consider.\n\\begin{itemize}\n\\item $\\aEv'_i  \\xeco \\aEv'_{i+1}$.   In this case, there is a race.\n\\item  $\\aEv'_i  \\slt \\aEv'_{i+1}$.  In this case, $\\aEv'_i$ is a write and $\\aEv'_{i+1}$ is a conflicting read, so there is a race. \n\\end{itemize}\n\n\n\\paragraph*{Proof of DRF2}\n\nWe define a size $|\\aPS|$ as follows: $\\size(\\aPS)$ is the number of events in $\\aPS$.    Since we are considering loop free programs, there is an $\\aPS \\in \\tsemsc{\\aCmd}$ with maximum size, which we identify as $\\size(\\aCmd)$.  \n\nWe prove by induction on $\\size(\\aCmd) - \\size(\\bPS)$ that given $(\\aPS, \\bPS)$ such that:\n\\begin{itemize}\n\\item $\\bPS$ is a prefix of some $\\aPS' \\in \\tsemsc{\\aCmd}$\n\\item $\\bPS$ is a prefix of $\\aPS$ under all of $\\xpox,\\gtN,\\lt$ \n\\item $\\aPS$ has a race\n\\end{itemize}\nthere exists $\\bPS\\in \\tsem{\\aCmd}$ that demonstrates the race.\n\nThe required theorem follows by setting $\\bPS$ to be the empty pomset.\n\nFor the base case, $\\bPS = |\\aPS|$.  In this case, $\\aPS$ is the required witness.\n\nOtherwise, consider a maximal sequential prefix, extending $\\bPS$, w.r.t.~all of  $\\rpox,\\reco,\\slt$.  If it strictly contains $\\bPS$, result follows from induction hypothesis.  \n\nIf not, $\\bPS$ is already maximal.  Consider the set of all events in $\\aPS \\setminus \\bPS$ that are minimal w.r.t.~$\\rhb$.  In particular, these events will also be minimal w.r.t.~$\\rpox$.  \n\nIf one of these events, say $\\aEv$  is a write, we proceed as follows.   Using $\\rhb$-minimality of $\\aEv$, we deduce $\\rpox$ minimality of $\\aEv$.  Using the generator properties, we deduce that $\\aEv$ is $\\slt$-minimal .  Using lemma~\\ref{removerw}, we build $\\aPS_1$ from $\\aPS$ without changing $\\bPS$ to ensure that there are is no read $\\bEv \\in \\aPS_1 \\setminus \\bPS$ such that $\\bEv \\xeco \\aEv$.  Using lemma~\\ref{cohww}, we build $\\aPS_2$ from $\\aPS_1$ without changing $\\bPS$ to ensure that there are is no write $\\bEv \\in \\aPS_2 \\setminus \\bPS$ such that $\\bEv \\xeco \\aEv$.  Thus, $\\aEv$ is $\\reco$-minimal in $\\aPS_2 \\setminus \\bPS$.  Result follows from induction hypothesis by considering $(\\aPS_2,\\bPS_1)$ where $\\bPS_1$ is got from $\\bPS$ by adding $\\aEv$.  \n\n\nSo, we can assume that  all events in $\\aPS \\setminus \\bPS$, say $\\aEv_0, \\ldots, \\aEv_n$  that are minimal w.r.t.~$\\rhb$ are reads, and we have  events \n$\\aEv'_0, \\aEv'_1, \\ldots, \\aEv'_n, \\aEv_0$ such that:\n\\[\n\\begin{array}{lrl}\n\\aEv_i \\xpox\\ \\aEv'_i \\\\\n\\aEv'_i \\  (\\reco\\ \\cup \\slt)  \\ \\aEv_{(i+1)\\mod n}\n\\end{array}\n\\]\nLet $\\bEv$ be the matching write for $\\aEv_{(i+1)\\mod n}$. If $\\bEv_i \\in \\bPS$bEv , then by $\\reco$ prefix closure of $\\bPS$, $\\bEv \\xeco\\ \\aEv'_i$ and $\\aEv_{(i+1)\\mod n} \\reco\\ \\aEv'_i$, which is a contradiction to $\\reco$ being a partial order per location.  So, we can assume that $\\aEv'_i \\  \\slt  \\ \\aEv_{(i+1)\\mod n}$. \n\nWe proceed as follows.  We use lemma~\\ref{inputen} on the  pomset $\\aPS$ and read $\\aEv_{(i+1)\\mod n}$ and write $\\aEv'_i$ to construct $\\cPS$ that changes the value read in $\\aEv_{j}$ to a value from $\\bPS$.  $\\dPS$  is derived adding the modified read yielded by lemma~\\ref{inputen} to $\\bPS$.  Result follows by induction hypothesis since $\\dPS$ is a prefix of $\\cPS$ under all of $\\xpox,\\lt, \\reco$,  $\\cPS$ has a race, and $\\size(\\dPS) = \\size(\\bPS) + 1$. \n\n\n\n\n\\endinput \n\n\n\n\n\n\n\n\n\\begin{comment}\nOperation        Implementation\nRelaxed read     ldr                     \nRelaxed write    str             \nAcquiring read   ldar            \nReleasing write  stlr\nFence            dmb.sy\n\\end{comment}\n\n\\begin{comment}\nob does not contradict eco\n\nob does not contradict (co cap po):\n\nSuppose that wx1 po wx2 then it cannot be that wx2 ob wx1.\nWe know that wx1 co wx2 by SC-PER-LOC\n\n% Case 1. w1 is read externally, then we have\n%   wx1 rfe r\n% and\n%   r fre w2\n% so\n%   wx1 obs+ wx2\n% which contradicts EXTERNAL\n\n% Case 2. wx1 is not read externally.\nWe show this by contradiction\nAssume\n  wx1 co wx2\nand\n  wx2 ob wx1\n\nNote that\n  po supseteq dob cup aob cup bob\nSo in order to get order into wx1, we must have\n  wx2 (ob?; obs; ob?; obs; ob?) wx1\n\nNote that we cannot have dob or bob into wx1 after obs, since then we would\nalso have it into wx2, creating a cycle in EXTERNAL.  This holds because both\ndob and bob are closed on the right w.r.t. coi\n\nSo it must be that \n  wx2 (ob?; obs; ob?; wx0; coe) wx1, \nin which case we also have wx0 coe wx2, contradicting EXTERNAL\nor \n  wx2 (ob?; obs; ob?; rx0; fre) wx1\nin which case we also have rx0 fre wx2, contradicting EXTERNAL\n\n\n\n\nInternal reads do not need to respect ob:\nArm allows the following:\n\n  Ra1 -ctrl-> Wx1 -rfi-> Rx1 ---> Wb1    if(a){x=1}; b=x\n   |                               |\n  Wa1 <-------------------------- Rb1    a=b\n\n\nSuppose that wx1 po rx2 and rx2 is read externally.\nThen it cannot be that rx2 ob wx1.\n\nCase 1: if wx1 co wx2, then we have wx1 coe wx2 rfe rx2, contradicting EXTERNAL\nCase 2: if wx2 co wx1, then we have rx2 fr wx1, contradicting SC-PER-LOC\n\n\n\nSuppose that rx1 po wx2 and rx1 is read externally.\nThen it cannot be that wx2 ob rx1.\n\nCase 1: if wx2 co wx1, then wx2 co wx1 rf rx1 po wx2, contradicting SC-PER-LOC \nCase 2: if wx1 co wx2, for a contradiction, suppose wx2 ob rx1.\nthen we need another thread involved to get order from wx2 to rx1.\nTo get order into the read, there are several options:\n- use cross thread read, then dob; but dob does not include reads in it's domain.\n  An attempt to do this is something like:\n\n              Wx1                 x=1\n               |\n  Ra2 -ctrl-> Rx1 - - -> Wx2      if(a){r=x}; x=2\n   |                      |\n  Wa2 <----------------- Rx2      a=x\n\n  But the ctrl dependency is not included in ob between reads.\n- use cross thread read then barrier, but then you contradict EXTERNAL\n- create and ob edge from Rx2 to Wx1.\n  An attempt to do this is, \n\n  Wx1 <-------------- Ra1       \n   |                   |        But cannot get Wx2 --> Wa1 without a barrier\n  Rx1 - - -> Wx2 ---> Wa1       \n\n  Wx1 <----- Rx2                         \n   |          |                 contradicts SC-PER-LOC \n  Rx1 - - -> Wx2                         \n\n\nOther examples to type in:\nAllowed:\nRx1 -> Wy0  Wy1\nRy1 -> Wz0  Wz1\nRz1 -> Wx0  Wx1\n\nForbidden:\nRx1 -> Wy0 Wy1\nRy1 -> Wx0 Wx1\n\n\\end{comment}\n\n\n\n\\begin{comment}\n\\citet{DBLP:journals/pacmpl/PodkopaevLV19} define the \\emph{Intermediate\n  Memory Model (IMM)} and provide efficient implementations of the IMM into\nseveral processor architectures, including TSO, ARMv8 and Power.\n\nIn this section, we show that any execution allowed by a sublanguage of the\nIMM is also allowed by our semantics.  The sublanguage we consider bans\nloops, read-modify-write (RMW) operations, and fences.  In addition, we take\nthe set of memory locations, $\\Loc$, to be finite.  Syntactically, we drop\nthe superscript \\textsf{rlx} on relaxed reads and writes; in addition, we use\nstructured conditionals rather than the more general \\textsf{goto}.  We refer\nto this sublanguage as $\\muIMM$.\n\n$\\muIMM$ programs sit in the restriction-free fragment of our language, where\nall memory locations are initialized to $0$ and parallel-composition occurs\nonly at top level.  In other words, $\\muIMM$ programs have the form\n\\begin{displaymath}\n  {\\aLoc_1}\\GETS{0}\\SEMI\n  \\cdots\\SEMI\n  {\\aLoc_m}\\GETS{0}\\SEMI\n  (\\aCmd^1 \\PAR \\cdots \\PAR \\aCmd^n)\n\\end{displaymath}\nwhere $\\aCmd^1$, \\ldots, $\\aCmd^n$ do not include either composition or\nrestriction.\n\nDue to space limitations, we do not include a full description of the IMM.\nThe broad strokes of the argument given here should be clear, but interested\nreaders will need to refer to \\citep{DBLP:journals/pacmpl/PodkopaevLV19} for\ndetails.\n\\end{comment}\n\n\n\n\\endinput\n\n\\section{Proof of DRF}\n\nFor any $\\aPS$, then $\\closed(\\aPS)$ is set enriched with useless reads\n(preserving augmentation closure) and where we remove any event whose\nprecondition is not a tautology.\n\nFor top level programs:\n\\begin{displaymath}\n  \\semClosed{\\VAR\\vec{\\aLoc}\\SEMI\n    \\vec{\\aLoc}\\GETS\\vec{0}\\SEMI\n    \\vec{\\bLoc}\\GETS\\vec{0}\\SEMI\n    \\FENCE\\SEMI\n    (\\aCmd^1 \\PAR \\cdots \\PAR \\aCmd^n)}\n  =\n  \\VAR\\vec{\\aLoc}\\SEMI\n    \\vec{\\aLoc}\\GETS\\vec{0}\\SEMI\n    \\vec{\\bLoc}\\GETS\\vec{0}\\SEMI\n    \\FENCE\\SEMI\n    (\\semClosed{\\aCmd^1} \\PAR \\cdots \\PAR \\semClosed{\\aCmd^n})\n\\end{displaymath}\n\n\\begin{definition}\nA thread: top level component of a parallel composition\n\\end{definition}\n\n\\begin{definition}\n$\\aPS$ is a generator of  $\\semClosed{\\aCmd}$ if for all $\\bPS \\in \\semClosed{\\aCmd}$ such that $\\aPS$ augments $\\bPS$, $\\aPS = \\bPS$.\n\\end{definition}\n\n\nSince the program we consider are loop free, for any command $\\aCmd$, the size of the pomsets in $\\aCmd$ are bounded by a constant, that we denote by $\\size(\\aCmd)$.  \n \n\n\\section{Generators for semantics of programs with parallel composition}\nAll generators $\\aPS$  satisfy the following factorization of cross-thread $\\lt$.  \n\n\\begin{lemma}\\label{pargen}\nConsider the subset of pomsets of $\\semClosed{\\aCmd \\PAR \\bCmd}$ that are  $\\aLoc$-closed for all $\\aLoc$.  \n\nLet $\\aPS$  be any generator.  \n%\\begin{itemize}\n% \\item\n Let $\\aEv\\lt\\bEv$ and $\\aEv \\in \\semClosed{\\aCmd}$ and  $\\bEv \\in \\semClosed{\\bCmd} $.\n  \nThen there is a write  $\\aEv' \\in \\semClosed{\\aCmd}$, and  a read $\\bEv' \\in \\semClosed{\\bCmd}$ such that  $\\bEv'$ reads-from $\\aEv'$ and $\\aEv \\lt \\aEv' \\lt \\bEv' \\lt \\bEv$. \n\n%\\item $\\aEv \\gtN \\bEv$ only if $ \\aEv  [\\lt \\cup (\\le; \\reco;\\le)^{\\star}]  \n%\\bEv$.\n\n% \\item If $\\aEv\\lt\\bEv$ and $\\aEv, \\bEv \\in \\semClosed{\\aCmd}$, \n%then there exists \n\n%There exists a release action $\\aEv'$ in $\\sem{\\aCmd}$, a \n%matching acquire action $\\bEv'$ in $\\sem{\\bCmd}$ such that $\n%\\aEv \\lt \\aEv'$, $\\bEv' \\lt \\bEv$ and $\\aEv' \\lt \\bEv'$.\n\n\\end{lemma}\n\n\n\n\n\n\n\n\nThe proof of lemma~\\ref{cohsat} yields the following two corollaries.\n\\begin{corollary}\\label{cohrw}\nLet $\\aPS \\in \\sem{\\aCmd}$ be a generator. Let \n\\begin{itemize}\n\\item $\\bEv'$ be a read from $\\aLoc$ with matching write $\\bEv$.  \\item $\\aEv$ be a write to $\\aLoc$ such that  $\\bEv' \\gtN \\aEv$.   \\item Forall writes $\\cEv$ to $\\aLoc$ such that  $ \\bEv \\gtN \\cEv \\gtN  \\aEv$,  it is the case that  $ \\neg(\\bEv' \\lt \\cEv)$ and $\\neg(\\bEv \\xpox \\cEv) ]$\n\\end{itemize}\n\nThen, there exists $\\bPS \\in \\sem{\\aCmd}$, also a generator, such that $\\Event_{\\aPS} = \\Event_{\\bPS}$, $\\le_{\\aPS} = \\le_{\\bPS}$, and $\\aEv \\gtN \\bEv'$ in $\\bPS$.\n\\end{corollary}\n\\begin{corollary}\\label{cohwr}\nLet $\\aPS \\in \\sem{\\aCmd}$ be a generator. Let \n\\begin{itemize}\n\\item $\\aEv'$  read from $\\aLoc$ with matching write $\\aEv$. \n\\item $\\bEv$ be a  write to $\\aLoc$ such that  $\\bEv \\gtN \\aEv'$.  \\item Forall writes $\\cEv$ to $\\aLoc$ such that  $ \\bEv \\gtN \\cEv \\gtN  \\aEv$ and $\\cEv \\not= \\aEv$,  it is the case that  $ \\neg(\\cEv \\lt \\aEv')$ and $\\neg(\\cEv \\xpox \\aEv) ]$. \n\\end{itemize}\n\nThen, there exists $\\bPS \\in \\sem{\\aCmd}$, also a generator, such that:\n$\\Event_{\\aPS} = \\Event_{\\bPS}$, $\\le_{\\aPS} = \\le_{\\bPS}$, and \n$\\aEv' \\gtN \\bEv$ in $\\bPS$.  \n\n\\end{corollary}\n        \n\n===============good lemma. Not used. ==================\n\n\n\n\n\\begin{definition}\n$ \\aEv \\xeco  \\bEv$ if both $\\aEv$ and $\\bEv$ touch the same location, at least one is a write, and $\\aEv \\xird \\bEv$  or $\\aEv \\xrb \\bEv$ or $\\aEv\\xird \\bEv$ or $\\bEv \\gtN \\aEv$.\n\\end{definition}\n\n\n\n\n\n\n\nBy lemma~\\ref{extendob}, if $\\aEv \\not=\\aEv'$, we deduce $\\aEv \\xob \\bEv'$, and thus $\\aEv \\xob \\bEv$.  If $\\bEv \\not=\\bEv'$, we deduce $\\aEv' \\xob \\bEv$ and thus $\\aEv \\xob \\bEv$.\n\nThus, if $\\aEv \\not=\\aEv'$ or $\\bEv \\not=\\bEv'$, then there is a cycle $\\aEv \\xob \\bEv \\xob \\cEv \\xob \\cEv' \\xob \\aEv$.  \n\nSo we can assume that  $\\aEv' = \\aEv$, $\\bEv' = \\bEv$ and \n\\[ \\aEv  \\xeco \\bEv \\xob \\cEv \\xob \\cEv' \\xeco \\aEv \\]\nwhere all of $\\aEv, \\bEv, \\cEv, \\cEv'$ access the same location and at least one of $\\aEv,\\bEv$ is a write, at least one of $\\aEv,\\cEv'$ is a write, and at least one of $\\bEv,\\cEv$ is a write.\n\nWe reason by cases.\n\\begin{itemize}\n\\item If $\\cEv'$ is a write or both $(\\aEv, \\bEv)$ are writes.\n\nWe deduce that $\\bEv \\xeco \\cEv' \\xeco \\aEv$ and thus $\\bEv \\xeco \\aEv$.\n\n\\item $\\cEv'$ is a read.  $\\aEv$ is a write.  $\\bEv$ is a read.\n\nIn this case $\\cEv$ is a write.  From $\\cEv \\xob \\aEv$, we deduce $\\cEv \\xeco \\aEv$. Combining with $\\bEv \\xeco \\cEv$, we deduce that $\\bEv \\xeco \\aEv$.  \n\n\n\\end{itemize}\nIn either case, there is a contradiction $\\aEv \\xeco \\bEv \\xeco \\aEv$.\n\n\n\n\n Consider the write $\\cEv'$ fulfilling $\\aEv$.  \n\n\n $\\cEv' (\\xobi \\cap \\xeco) \\aEv$.  Since $\\aEv$ not $\\rrfi$ event.\nAlso,\n\nSo, we can assume that $\\aEv \\xpox \\bEv$, and the situation is:\n\\[ \\cEv' \\xobi \\cEv (\\xpox \\cap \\xobi) \\aEv (\\xeco \\cap \\xpox)  \\bEv  (\\xpox \\cap \\xobi) \\cEv'' \\xobi \\cEv' \\]\n\n\nBy lemma~\\ref{extendob}, if $\\cEv \\not= \\aEv$, $\\cEv \\xob \\bEv$, and we have a cycle in $\\xob$.\nSimilarly, if $\\bEv \\not= \\cEv''$, $\\aEv \\xob \\cEv''$, and we have a cycle in $\\xob$.  So, the situation is:\n\\[ \\cEv' \\xobi \\aEv (\\xeco \\cap \\xpox)  \\bEv \\xobi \\cEv' \\]\n$\\cEv',\\aEv,\\bEv$ are events on same variable.  The above is a cycle in $\\xeco$.\n\n\n\n", "meta": {"hexsha": "82cb4609778b8971fbcad66f82cde7d5f54642d1", "size": 25732, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "drf-proof.tex", "max_stars_repo_name": "chicago-relaxed-memory/memory-model", "max_stars_repo_head_hexsha": "fd606fdb6a04685d9bb0bee61a5641e4623b10be", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-08-13T02:36:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-25T12:46:13.000Z", "max_issues_repo_path": "drf-proof.tex", "max_issues_repo_name": "chicago-relaxed-memory/memory-model", "max_issues_repo_head_hexsha": "fd606fdb6a04685d9bb0bee61a5641e4623b10be", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "drf-proof.tex", "max_forks_repo_name": "chicago-relaxed-memory/memory-model", "max_forks_repo_head_hexsha": "fd606fdb6a04685d9bb0bee61a5641e4623b10be", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.045751634, "max_line_length": 774, "alphanum_fraction": 0.6574304368, "num_tokens": 9238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6791786991753931, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.31575124448997416}}
{"text": "\\documentclass{report}\n\\usepackage{graphicx}\n\n\\usepackage{amsmath}\n\\DeclareMathOperator*{\\argmax}{argmax}\n\n\\usepackage{hyperref}\n\\hypersetup{\n    colorlinks=true,\n    linkcolor=blue,\n    filecolor=magenta,      \n    urlcolor=cyan,\n}\n\n\\begin{document}\n\n\\title{Banana World Project Report}\n\\author{Denis Sergeev}\n\n\n\\section*{Problem definition}\n\nThe goal of the project was to create a RL Agent which is able to train from scratch by interacting with the Banana World environment for a series of episodes. During the episode the agent receives the environment state. The agent is able to perform some actions which may change the environment state.\n\n\\subsection*{Environment description}\nThe \\textbf{state space} has \\(37\\) dimensions each of which is a continuous variable. It includes the agent's velocity, along with ray-based perception of objects around the agent's forward direction. The \\textbf{action space} contains the following \\(4\\) legal actions:\n\\begin{itemize}\n  \\item move forward \\(0\\)\n  \\item move backward \\(1\\)\n  \\item turn left \\(2\\)\n  \\item turn right \\(3\\)\n\\end{itemize}\nA reward of \\(+1\\) is provided for collecting a yellow banana, and a reward of \\(-1\\)` is provided for collecting a blue banana. Thus, the goal of the agent is to collect as many yellow bananas as possible while avoiding blue bananas. The task is episodic, and in order to solve the environment, the agent must get an average score of \\(+13\\) over \\(100\\) consecutive episodes.\n\n\n\\section*{Solution}\n\\subsection*{Deep Q-Network Architecture}\n\\subsubsection*{Network}\nSince the agent should act upon environment state provided as vector of size \\(37\\), I decided to build simple network with \\(3\\) fully connected layers, which should predict the Q-value for each action given the input state. The input has size 37, output 4. I tried 64x64, 64x32, 32x32, 32x16 hidden layers configuration. The best one was 32x32, since it was able to reach the training goal faster and it has less internal parameters then 64x64 and 64x32.\n\n\\subsection*{Training}\n\\subsubsection*{Loss function and optimizing method}\n\nI tried 2 loss functions \\ref{loss}: Simple DQN loss \\ref{dqn-loss} and \\href{https://arxiv.org/pdf/1509.06461.pdf}{Double DQN loss} \\ref{ddqn-loss}\n\\begin{equation} \\label{loss}\nL \\equiv (Y_{t} - Q(S_{t}, a; \\theta_{t}))^{2}\n\\end{equation}\n\\begin{equation} \\label{dqn-loss}\nY_t \\equiv R_{t+1} + \\gamma \\max_a Q(S_t, a; \\theta'_t)\n\\end{equation}\n\\begin{equation} \\label{ddqn-loss}\nY_t \\equiv R_{t+1} + \\gamma Q(S_{t+1}, \\argmax_a Q(S_t, a; \\theta_t); \\theta'_t)\n\\end{equation}\nWhere \\(Q(S_t, a, \\theta_t)\\) is output (value of action \\(a\\)) of the network with internal parameters \\(\\theta_t\\) given input \\(S_t\\). Both loss functions used 2 sets of network parameters: target \\(\\theta'_t\\) and local \\(\\theta_t\\). Target network parameters was updating through soft update \\(\\theta'_t = (1 - \\tau) \\theta'_t + \\tau \\theta_t\\).\nAs optimizing method for \\(\\theta_t\\) I used Adam with learning rate \\(\\alpha\\).\n\n\\subsubsection*{Experience replay}\n\nThe input for training did not come directly from episodes. Instead I used experience replay technique (see \\href{https://storage.googleapis.com/deepmind-media/dqn/DQNNaturePaper.pdf}{Human-level control through deep reinforcement learning}).\n\n\n\\section*{Results}\n\nI came up using following training hyper parameters:\n\\begin{itemize}\n\t\\item \\(\\epsilon_{start}\\): 1.0, \\(\\epsilon_{end}\\): 0.01, \\(\\epsilon_{decay}\\): 0.97\n\t\\item Buffer size: 100000\n\t\\item Batch size: 64\n\t\\item \\(\\gamma\\): 0.99\n\t\\item \\(\\tau\\): 0.005\n\t\\item \\(\\alpha\\): 0.0005\n\\end{itemize}\nThey were used across all training experiments below.\n\n\n\\subsection*{Training DDQN 32x16}\n\nDQN architecture: fully connected with bias 37x32x16x4. Loss \\ref{ddqn-loss}.\n\nTraining history:\n\nEpisode 100.\tAverage Score: 4.88.\tTime elapsed: 4:35\n\nEpisode 200.\tAverage Score: 12.21.\tTime elapsed: 9:11\n\nEnvironment solved in 170 episodes!\tAverage Score: 13.12. Time elapsed: 12:31s. See \\ref{fig:DDQN_32x16}.\n\n\\begin{figure}\n\t\\includegraphics[width=0.9\\linewidth]{res/DDQN_32x16/score.png}\n\t\\caption{DDQN 32x16: Rewards per episode}\n\t\\label{fig:DDQN_32x16}\n\\end{figure}\n\n\n\\subsection*{Training DDQN 32x32}\n\nDQN architecture: fully connected with bias 37x32x32x4. Loss \\ref{ddqn-loss}.\n\nTraining history:\n\nEpisode 100.\tAverage Score: 6.50.\tTime elapsed: 3:26\n\nEpisode 200.\tAverage Score: 12.66.\tTime elapsed: 6:51\n\nEnvironment solved in 109 episodes!\tAverage Score: 13.08. Time elapsed: 7:09s. See \\ref{fig:DDQN_32x32}.\n\n\\begin{figure}\n\\includegraphics[width=0.9\\linewidth]{res/DDQN_32x32/score.png}\n\\caption{DDQN 32x32: Rewards per episode}\n\\label{fig:DDQN_32x32}\n\\end{figure}\n\n\n\\subsection*{Training DDQN 64x32}\n\nDQN architecture: fully connected with bias 37x64x32x4. Loss \\ref{ddqn-loss}.\n\nTraining history:\n\nEpisode 100.\tAverage Score: 5.69.\tTime elapsed: 3:25\n\nEpisode 200.\tAverage Score: 12.38.\tTime elapsed: 6:52\n\nEnvironment solved in 118 episodes!\tAverage Score: 13.06. Time elapsed: 7:33s. See \\ref{fig:DDQN_64x32}.\n\n\\begin{figure}\n\\includegraphics[width=0.9\\linewidth]{res/DDQN_64x32/score.png}\n\\caption{DDQN 64x32: Rewards per episode}\n\\label{fig:DDQN_64x32}\n\\end{figure}\n\n\n\\subsection*{Training DQN 64x32}\n\nDQN architecture: fully connected with bias 37x64x32x4. Loss \\ref{dqn-loss}.\n\nTraining history:\n\nEpisode 100.\tAverage Score: 4.75.\tTime elapsed: 3:10\n\nEpisode 200.\tAverage Score: 11.97.\tTime elapsed: 6:22\n\nEnvironment solved in 136 episodes!\tAverage Score: 13.02. Time elapsed: 7:31s. See \\ref{fig:DQN_64x32}.\n\n\\begin{figure}\n\\includegraphics[width=0.9\\linewidth]{res/DQN_64x32/score.png}\n\\caption{DQN 64x32: Rewards per episode}\n\\label{fig:DQN_64x32}\n\\end{figure}\n\n\n\\subsection*{Training DQN 64x64}\n\nDQN architecture: fully connected with bias 37x64x64x4. Loss \\ref{dqn-loss}.\n\nTraining history:\n\nEpisode 100.\tAverage Score: 4.75.\tTime elapsed: 3:21\n\nEpisode 200.\tAverage Score: 10.90.\tTime elapsed: 6:39\n\nEnvironment solved in 130 episodes!\tAverage Score: 13.03. Time elapsed: 7:38s. See \\ref{fig:DQN_64x64}.\n\n\\begin{figure}\n\\includegraphics[width=0.9\\linewidth]{res/DQN_64x64/score.png}\n\\caption{DQN 64x64: Rewards per episode}\n\\label{fig:DQN_64x64}\n\\end{figure}\n\n\\subsection*{Conclusion}\n\nFrom the above results we can summarize, that DDQN has slightly better training performance. Also 32x32 hidden layer configuration is the best. It was trained faster and has few internal parameters.\n\n\n\\section*{Areas of improvement}\n\nDuring evaluation of the trained agent I noticed, that in some cases the agent hangs up. It begins alternating between 2 positions. You may see it at the end of the video I uploaded on \\href{https://youtu.be/PPSJ2k9RBq0}{youtube}. This is caused by the fact, that the agent makes its decision based only on instant state. It does not take into account previous states and actions. Intuitively is clear that the agent needs some memory to store previous actions and states. This could be achieved by \\href{http://cs229.stanford.edu/proj2016/report/ChenYingLaird-DeepQLearningWithRecurrentNeuralNetwords-report.pdf}{adding recurrent unit to the network}, like LSTM, GRU or just simple RNN.\nAnother improvement could be implementing \\href{https://arxiv.org/abs/1511.05952}{prioritized experience replay}.\n\n\\end{document}\n", "meta": {"hexsha": "61c657f0297e6e6707c9ea787d35743343453264", "size": 7257, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "banana_world/report.tex", "max_stars_repo_name": "denmatfoton/reinforcement_learning", "max_stars_repo_head_hexsha": "788f95fca0b3cb67370539aaad7c5b28710d58a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-01T01:30:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-01T01:30:04.000Z", "max_issues_repo_path": "banana_world/report.tex", "max_issues_repo_name": "denmatfoton/reinforcement_learning", "max_issues_repo_head_hexsha": "788f95fca0b3cb67370539aaad7c5b28710d58a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "banana_world/report.tex", "max_forks_repo_name": "denmatfoton/reinforcement_learning", "max_forks_repo_head_hexsha": "788f95fca0b3cb67370539aaad7c5b28710d58a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0939226519, "max_line_length": 687, "alphanum_fraction": 0.755959763, "num_tokens": 2175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3157387566926947}}
{"text": "\\section{Modifying and applying RISE (single pixel)}\n\\nblink{brats/06\\_rise.ipynb}\n\nThe approach how to apply RISE on a segmentation task is the same as with Grad-CAM. Pixels in the output of a segmentation model are equivalent to classes of a classification model.\nAs a first version, we only analyze a single pixel. We chsose the first pixel in the tumor ground truth segment by iterating over the segment linearly until the first active pixel is found.\n\nIn the standard implementation, RISE analyzes every class that is returned by the network. Our segmentation model returns $ image\\_height \\cdot image\\_width $ count classes. This produces too many classes and the algorithm crashes with an out of memory error. We modified the code to only analyze the output neuron for our selected pixel.\n\n\\subsection{Results}\n\n\\begin{figure}[H]\n\\centering\n\\includegraphics[width=8cm]{chapters/04_segmentation/images/rise_single_pixel.png}\n\\caption{RISE saliency map analyzing the topmost pixel in the scan, overlaid on the binarized network output and the T1 contrast enhanced input modality.}\n\\label{rise_single_pixel_result}\n\\end{figure}\n\n\\subsection{Discussion}\nThe produced output in Figure \\ref{rise_single_pixel_result} looks correct, the color blob is at the expected position. It clearly shows that the neural network looks at the correct location to generate the segmentation.\nApart from this basic correctness verification, no further insight is provided by the saliency map, because the resolution generated by RISE is too low.\n\n\\subsection{Conclusion}\nThe generated output is low resolution but still helpful. We therefore decided to build a version of RISE which works on all pixels of the segmentation.\n\n\\section{Modifying and applying RISE (multi pixel)}\n\\nblink{brats/17\\_rise\\_multipixel.ipynb}\n\nAs written in the previous section, RISE crashes when running on all the pixels in the output of the model. We already modified the algorithm to work on a single pixel. For this multi pixel variant, we extend the algorithm to work on all pixels in the segmentation ground truth. We batched the pixels into groups of 1000 pixels each, because depending on the size of the output segment the algorithm still crashed.\n\nWith this changed algorithm, we generate a saliency map like in Figure \\ref{rise_single_pixel_result} for every single pixel in the output segment.\n\nTo have a single saliency map for all pixels, we use the max and mean functions of numpy on the whole set of saliency maps.\n\n\\subsection{Results}\n\n\\begin{figure}[H]\n    \\centering\n    \\begin{subfigure}[t]{.4\\textwidth}\n        \\centering\n        \\includegraphics[width=\\linewidth]{chapters/04_segmentation/images/rise_multipixel_max_1-0.png}\n        \\caption{Saliency map created by the max function}\n    \\end{subfigure}\\hspace{1cm}%\n    \\begin{subfigure}[t]{.4\\textwidth}\n        \\centering\n        \\includegraphics[width=\\linewidth]{chapters/04_segmentation/images/rise_multipixel_max_1-1.png}\n        \\caption{Saliency map created by the max function, overlaid on the binarized network output}\n    \\end{subfigure}\n    \\caption{Single saliency map over all output pixels generated by applying the max function on the set of all saliency maps.}\n    \\label{rise_multipixel_max}\n\\end{figure}\n\n\\begin{figure}[H]\n    \\centering\n    \\begin{subfigure}[t]{.4\\textwidth}\n        \\centering\n        \\includegraphics[width=\\linewidth]{chapters/04_segmentation/images/rise_multipixel_mean_2-0.png}\n        \\caption{Saliency map created by the mean function}\n    \\end{subfigure}\\hspace{1cm}%\n    \\begin{subfigure}[t]{.4\\textwidth}\n        \\centering\n        \\includegraphics[width=\\linewidth]{chapters/04_segmentation/images/rise_multipixel_mean_2-1.png}\n        \\caption{Saliency map created by the mean function, overlaid on the binarized network output}\n    \\end{subfigure}\n    \\caption{Single saliency map over all output pixels generated by applying the mean function on the set of all saliency maps.}\n    \\label{rise_multipixel_mean}\n\\end{figure}\n\n\\subsection{Discussion}\nFigure \\ref{rise_multipixel_max} shows a single saliency map matching quite well with the binarized network output. The map was generated with the numpy max function on all generated saliency maps. This means the highest pixel value in any of the saliency map is copied into the final saliency map. The resolution of the generated saliency map is quite low, and not many insights can be gathered from it.\n\nFigure \\ref{rise_multipixel_mean}, which was generated with the mean function, also shows a heat map matching the binarized network output, although with much less detail than the map generated with the max function.\n\n\\subsection{Conclusion}\nThe modified RISE method provides useful insight into the correctness of the model. It clearly marks the important regions the neural network uses to generate the segmentation output. However, the generated saliency map is of low resolution and does only provide a coarse look into the inner workins of the model. Increasing the quantity of used masks by RISE is possible, but generating a single RISE output already takes around 30 seconds on a high-end consumer GPU with 6000 masks. To generate a higher resolution saliency map, many more masks would be required.\n", "meta": {"hexsha": "8d9fa17c7601a5031241eda28741add1f7b7ae11", "size": 5251, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/04_segmentation/08_rise.tex", "max_stars_repo_name": "andef4/thesis-doc", "max_stars_repo_head_hexsha": "a94ecd7cff9f00ecd23ecee319076b78bef79a8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/04_segmentation/08_rise.tex", "max_issues_repo_name": "andef4/thesis-doc", "max_issues_repo_head_hexsha": "a94ecd7cff9f00ecd23ecee319076b78bef79a8e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/04_segmentation/08_rise.tex", "max_forks_repo_name": "andef4/thesis-doc", "max_forks_repo_head_hexsha": "a94ecd7cff9f00ecd23ecee319076b78bef79a8e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 70.0133333333, "max_line_length": 565, "alphanum_fraction": 0.7867072938, "num_tokens": 1225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.3157387487413705}}
{"text": "% ******************************* Thesis Appendix B ********************************\n\n\\chapter{Supporting information: Chapter 5}\n\n\\graphicspath{{Appendix4/Figures/}}\n\n\\section{Supplementary figures and tables}\n\\newpage\n\\begin{figure}[H]\n\\flushleft{\\textbf{Figure S5.1.} Positive pairwise species correlations to the environment derived from single-predictor LVMs for the full dataset. Connecting lines between species nodes denote positive mean posterior correlations with credible intervals excluding zero. Line colour and thickness indicates the strength of the positive correlation where darker and thicker lines are closer to 1. Species node labels combine the first letters of the genus and specific epiphet.}\n\\includegraphics[width=1.0\\linewidth]{networkplots-positive-unshrink}\\\\\n\\end{figure}\n\n\\begin{figure}[H]\n\\flushleft{\\textbf{Figure S5.2.} Abundance of each species (excl. \\textit{Empodisma minus}) through time. Trend lines obtained with thin-plate splines in a GAMM framework (see main text for model fitting). Shaded region represents 95\\% confidence intervals.}\n\\includegraphics[width=1.0\\linewidth]{timeplots}\\\\   \n\\end{figure}\n\n\n\\begin{table}[H]\n  \\centering\n  \\flushleft\\textbf{Table S5.1.} Negative and positive pairwise environmental and residual correlations in each of the four plot clusters. \n    \\begin{tabular}{lllll}\n    \\toprule\n          & \\multicolumn{2}{l}{No. sig. env. correlations} & \\multicolumn{2}{l}{No. sig. res. correlations} \\\\\n    \\midrule\n          & -ve   & +ve   & -ve   & +ve \\\\\n    deep soil-moisture & 6,0,1,0 & 12,2,4,13 & 8,11,7,0 & 10,14,30,41 \\\\\n    shallow soil-moisture & 2,0,4,0 & 3,3,2,0 & 10,10,5,0 & 17,9,16,42 \\\\\n    pH    & 0,0,3,0 & 1,1,11,0 & 7,10,6,0 & 11,13,23,41 \\\\\n    total iron & 2,0,2,0 & 2,1,3,1 & 10,11,7,0 & 6,8,17,41 \\\\\n    phosphorous & 4,0,9,3 & 3,5,7,3 & 12,11,4,0 & 7,10,26,34 \\\\\n    organic carbon & 1,0,6,0 & 0,0,10,16 & 8,10,6,0 & 6,12,27,39 \\\\\n    exchangeable aluminium & 2,0,2,6 & 4,8,2,12 & 10,16,5,0 & 15,20,25,41 \\\\\n    exchangeable magnesium & 3,0,5,1 & 3,1,9,8 & 10,11,6,0 & 11,13,28,41 \\\\\n    cation exchange capacity & 1,0,5,1 & 2,3,6,0 & 8,13,5,0 & 14,10,21,43 \\\\\n    \\bottomrule\n    \\end{tabular}%\n  \\label{tab:addlabel}%\n\\end{table}%\n\n\\includepdf[pages={-}, offset=0.4cm 0cm,  addtotoc= {1,section,1,LVM Primer,hlabel}]{Appendix4/LVM-primer.pdf}\n\n\\subsection{fitLVM-auxiliaryfunctions.R}\n\n\\begin{verbatim}\n##########################################\n## Auxilary functions for fitting LVMs  ##\n##########################################\n\n## Calculate the correlation between spp due to shared/diverging env responses\nextract.env.cor <- function(fit.mod, X, y) {\t\t\n\tn.species <- ncol(y)\n\tfit.mcmcBase <- fit.mod$BUGSoutput\n\tmcmc.runs <- mcmc(fit.mcmcBase$sims.matrix, start = 1, \n                    thin = fit.mcmcBase$n.thin) \n\trm(fit.mcmcBase)\n\t\t\n\tall.shared.env.mat <- matrix(0,nrow(mcmc.runs),n.species^2)\n\n\t## For each MCMC sample, find the correlation between spp responses\n\tfor(t in 1:nrow(mcmc.runs)) { \n\t\tcw.spp.coef <- matrix(mcmc.runs[t,grep(\"spp.coef\\\\[\",colnames(mcmc.runs))],\n                          n.species,byrow=F)\n\t\teta.mat <- X%*%t(cw.spp.coef) ## On linear predictor scale\n\t\tall.shared.env.mat[t,] <- as.vector(cor(eta.mat))\n\t\t}\n\n\t## Average/Median over the MCMC samples\n\tenv.mat.mean <- sig.env.mat.mean <- matrix(apply(all.shared.env.mat,2,mean),\n                                             n.species,byrow=F)\n\tenv.mat.median <- sig.env.mat.median <- matrix(apply(all.shared.env.mat,2,median),\n                                                 n.species,byrow=F)\n\t\t\n\tget.cor.intervals <- HPDinterval(as.mcmc(all.shared.env.mat), prob = 0.95)\t\n\tid.sign.cors <- which(get.cor.intervals[,1] > 0 | get.cor.intervals[,2] < 0)\t\n\tsig.env.mat.mean[-id.sign.cors] <- 0\n\tsig.env.mat.median[-id.sign.cors] <- 0\n\t\n\treturn(list(envcor.mean = env.mat.mean, \n              envcor.median = env.mat.median, \n              sig.envcor.mean = sig.env.mat.mean, \n              sig.envcor.median = sig.env.mat.median))\n\t}\n\t\n## Produce the residual correlation\nextract.residual.cor <- function(fit.mod, X, y) {\n\tfit.mcmcBase <- fit.mod$BUGSoutput\n\tmcmc.runs <- mcmc(fit.mcmcBase$sims.matrix, \n                    start = 1, \n                    thin = fit.mcmcBase$n.thin)\n\trm(fit.mcmcBase)\n\n\tn.species <- ncol(y)\n\tn.sites <- nrow(y)\n\tTau.arr <- matrix(NA,nrow(mcmc.runs),n.species^2)\n\tfor(t in 1:nrow(mcmc.runs)) { \n\t\tlvs <- matrix(mcmc.runs[t,grep(\"LV\",colnames(mcmc.runs))],\n                  n.sites,byrow=F)\n\t\tlv.coefs <- matrix(mcmc.runs[t,grep(\"lv.coef\",colnames(mcmc.runs))],\n                       n.species,byrow=F)\n\t\tTau.arr[t,] <- as.vector(cor(lvs%*%t(lv.coefs))) }\n\t\t\n\t## Average/Median over the MCMC samples\n\tTau.mat.mean <- sig.Tau.mat.mean <- matrix(apply(Tau.arr,2,mean),\n                                             n.species,byrow=F)\n\tTau.mat.median <- sig.Tau.mat.median <- matrix(apply(Tau.arr,2,median),\n                                                 n.species,byrow=F)\n\t\t\n\tget.cor.intervals <- HPDinterval(as.mcmc(Tau.arr), prob = 0.95)\t\n\tid.sign.cors <- which(get.cor.intervals[,1] > 0 | get.cor.intervals[,2] < 0)\t\n\tsig.Tau.mat.mean[-id.sign.cors] <- 0\n\tsig.Tau.mat.median[-id.sign.cors] <- 0\n\t\t\n\treturn(list(rescor.mean = Tau.mat.mean, \n              rescor.median = Tau.mat.median, \n              sig.rescor.mean = sig.Tau.mat.mean, \n              sig.rescor.median = sig.Tau.mat.median))\n\t}\n\t\n## Produce mean and median point estimates from fit\nextract.params <- function(fit.mod) {\n\tfit.mcmcBase <- fit.mod$BUGSoutput\n\tmcmc.runs <- mcmc(fit.mcmcBase$sims.matrix, start = 1, \n                    thin = fit.mcmcBase$n.thin) \n\trm(fit.mcmcBase)\n\tn.species <-  length(grep(\"spp.int\",colnames(mcmc.runs)))\n\n\tall.spp.coef <- mcmc.runs[,grep(\"spp.coef\",colnames(mcmc.runs))]\n\tspp.coef.mean <- matrix(apply(all.spp.coef,2,mean),n.species,byrow=F)\t\n\tspp.coef.median <- matrix(apply(all.spp.coef,2,median),n.species,byrow=F)\t\n\t\n\tall.spp.int <- mcmc.runs[,grep(\"spp.int\",colnames(mcmc.runs))]\n\tspp.int.mean <- apply(all.spp.int,2,mean)\n  spp.int.median <- apply(all.spp.int,2,median)\t\n\t\n\tall.spp.phi <- mcmc.runs[,grep(\"spp.phi\",colnames(mcmc.runs))]\n\tspp.phi.mean <- apply(all.spp.phi,2,mean)\n  spp.phi.median <- apply(all.spp.phi,2,median)\t\n\n\tall.mu.beta <- mcmc.runs[,grep(\"mu.beta\",colnames(mcmc.runs))]\n\tmu.beta.mean <- apply(all.mu.beta,2,mean)\n  mu.beta.median <- apply(all.mu.beta,2,median)\t\n\n\tall.tau.beta <- mcmc.runs[,grep(\"tau.beta\",colnames(mcmc.runs))]\n\ttau.beta.mean <- apply(all.tau.beta,2,mean)\n  tau.beta.median <- apply(all.tau.beta,2,median)\t\n\n\treturn(list(spp.coef.mean = spp.coef.mean, spp.coef.median = spp.coef.median, \n              spp.int.mean = spp.int.mean, spp.int.median = spp.int.median, \n              spp.phi.mean = spp.phi.mean, spp.phi.median = spp.phi.median, \n              mu.beta.mean = mu.beta.mean, mu.beta.median = mu.beta.median, \n              tau.beta.mean = tau.beta.mean, tau.beta.median = tau.beta.median))\n\t}\n\\end{verbatim}", "meta": {"hexsha": "60503edb763f24713aa67aed047312d844726929", "size": 6987, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Appendix4/appendix4.tex", "max_stars_repo_name": "andrewletten/LettenPhdThesis2015", "max_stars_repo_head_hexsha": "9d13275747f193f3d73ff18dc79113d3fd968af1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Appendix4/appendix4.tex", "max_issues_repo_name": "andrewletten/LettenPhdThesis2015", "max_issues_repo_head_hexsha": "9d13275747f193f3d73ff18dc79113d3fd968af1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Appendix4/appendix4.tex", "max_forks_repo_name": "andrewletten/LettenPhdThesis2015", "max_forks_repo_head_hexsha": "9d13275747f193f3d73ff18dc79113d3fd968af1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.0774193548, "max_line_length": 477, "alphanum_fraction": 0.6237297839, "num_tokens": 2186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.3157387487413705}}
{"text": "%!TEX root = ../copatterns-thesis.tex\n\\chapter{Related Work}\n\\label{cha:related-work}\n\n% \\section{Copatterns}\n% \\label{sec:related_work_copatterns}\n% \\todo{Relate to 'Unnesting of Copatterns' by Setzer et al.}\n\n\\section{Size-change Termination}\nThe termination checker in Idris uses the size-change\nprinciple\\,\\citep{BradyIdrisImpl13}. Where the productivity checking procedure\npresented in Chapter~\\ref{cha:infer-guard-recurs} is essentially a type check\nwith intermediate term inference, the size-change principle is purely based on\nsyntactic analysis. The size-change principle for termination was first proposed\nfor a strict first-order functional language (without loop constructs) by Lee,\nJones, and Ben-Amram\\,\\citep{LeeJones01SizeChange}. The principle essentially\nstates that if infinitely many recursive calls to a function would lead to\ninfinite decrease in some parameter value, then the function must be\nterminating, since any value of an inductive type must have finite size. This\nlast condition is of particular importance, as the size-change principle cannot\nin general recognize functions as being terminating if they have parameters that\ndo not exhibit a well-founded order. Lee, Jones, and Ben-Amram present two\nrealizations of the principle, one using automata and one using a call graph. In\nthe graph formulation, termination is approximated by identifying any recursive\ncalls (both direct and indirect) through cycles in the call graph, and then\nconstructing a ``size-change graph'' for each of these. The size-change graphs\nare then used to discover whether infinite descent in some parameter value is\npresent. One of the limitations of this approach is that parameter values must\ndecrease monotonically: Values cannot at any point become structurally larger,\neven though the total change in size in a call chain would ultimately lead a to\na decreasing value. Two examples of size-change terminating functions are shown\nin Figure~\\ref{fig:sizechange_plus_map}. In both examples, the recursive call\nhappens on structurally smaller input.\n\n\\begin{figure}\n\\begin{lstlisting}[mathescape,title=\\idrisBlock]\nplus : Nat $\\to$ Nat $\\to$ Nat\nplus Z      m = m\nplus (S n$'$) m = plus n$'$ m\n\nmap : (a $\\to$ b) $\\to$ Vect n a $\\to$ Vect n b\nmap f []        = []\nmap f (x :: xs) = f x :: map f xs\n\\end{lstlisting}\n\\caption{Two size-change terminating functions.}\n\\label{fig:sizechange_plus_map}\n\\end{figure}\n\nSince its first-order formulation, the principle has been proven to be applicable to more expressive cases. Jones and Bohr\\,\\citep{Jones04Untyped} showed that size-change termination can be applied to the untyped lambda calculus using abstract interpretation\\,\\citep{Jones:1995}. A set of safe size-change graphs for a program is generated by defining evaluation rules without an environment component, thus overapproximating the number of possible values for any given variable. Given these rules, a corresponding overapproximated set of safe size-change graphs is generated for further termination analysis. Note that due to the undecidability of the halting problem, it is impossible in general to compute the exact set of safe size-change graphs for a given function call.\n\nFollowing the work on the untyped lambda calculus, Sereni and Jones generalized the size-change principle to handle a higher-order functional language with user-defined data types and general recursion\\,\\citep{Sereni05terminationanalysis,Sereni06Phd}. Here, a termination criterion is presented which works for arbitrary control-flow graphs, and in turn is able to give an approximation of termination for both strict and lazy functional programs. A key point in this work is how different approaches to control-flow and call graph construction may influence the preciseness of the termination analysis.\n\nAll of the previously mentioned implementations of the size-change principle can\nonly approximate termination for programs involving data which exhibits some\nwell-founded order. Nevertheless, Avery\\,\\citep{Avery06} presented a formulation\nin which it is possible to detect size-change termination for non-well-founded\ndata types --- in particular, this formulation is shown to work for a language\nwith a non-well-founded integer type. Instead of identifying infinite descent using a well-founded partial order on parameter, as proposed by Lee at al., Avery's analysis is based on a decrease in invariants which are found to hold for each program point. The idea is that if the value of some invariant (which can involve arbitrarily many values) can be shown to decrease on every passage of a program point, then the program terminates. A simple example of a size-change terminating program in Avery's implementation is given in Figure~\\ref{fig:avery_example}. The invariant for the inner loop is \\texttt{n - j + i}, while the one for the outer loop is \\texttt{n - i}. These cannot decrease indefinitely, and therefore the program is size-change terminating.\n\n\\begin{figure}\n\\begin{lstlisting}\nfor (i = 0; i <= n; i++) {\n  for (j = 0; j-i <= n; j++);\n}\nreturn;\n\\end{lstlisting}\n\\caption{An example program involving integers written in a subset of C, which is size-change terminating in Avery's formulation.}\n\\label{fig:avery_example}\n\\end{figure}\n\nWhile size-change termination for non-well-founded data could be a step towards\nusing a size-change approach for an approximation of productivity, it is unclear\nwhich invariants one would have to infer for corecursive programs. In our\nsolution, we do not directly establish invariants, but instead encode constraints\nin the types of guarded recursive programs using the guardedness type\nconstructor ($\\laterkappa$) and quantification over clocks. Together with a\nuser-supplied modality (either causal or non-causal) we can then establish\nwhether a guarded recursive version of a user-written complies with these constraints.\n\nIn more recent work, Hyvernat\\,\\citep{Hyvernat13} has proposed a formulation of the size-change principle for functional languages which to a certain degree solves the problem of non-monotonic decrease in parameter values. The motivation behind this work is to incorporate size-change termination into the PML language\\,\\cite{PMLLanguage}. Non-monotonic decrease is detected by tracking the size of a parameter throughout the entire control-flow graph, instead of merely recording whether each call in isolation leads to a decrease in some value.\n\nThe termination criterion most similar to the size-change principle predates the original article by Lee, Jones, and Ben-Amram\\,\\citep{LeeJones01SizeChange}. This criterion was developed by Abel for the \\texttt{foetus} termination checker\\,\\citep{Abel98foetus}, and forms the basis of the totality checker implemented in Agda\\,\\citep{Norell:thesis}. Analogous to the size-change principle, Abel identifies recursive calls in a call graph and performs a termination analysis by tracking changes in parameter sizes. This initial presentation of \\texttt{foetus} makes no mention of productivity for corecursive programs, although such an extension has since been presented by Altenkirch and Danielsson\\,\\citep{AltenkirchNAD10}.\n\n\\section{Syntactic Guardedness}\n\\label{sec:synt-guard}\n% Telford and Turner nævnes mere\n% Hyvernat flyttes herned\n\n% Due to the duality between inductive and coinductive types, it may be compelling to imagine a productivity analysis which, dual to the size-change principle, works by identifying structurally larger values. Such a dual notion of ``size-change productivity'' is exactly the idea behind the syntactic guardedness checkers found in Idris, Agda, and Coq\\,\\citep{Coq:manual}. Where values become structurally smaller by pattern matching, they become structurally larger by constructor application. Therefore, the \\emph{guardedness principle} states that a coinductive definition is guarded if all corecursive calls appear directly under a coinductive constructor. This has the implication that the productivity of corecursive functions can be detected by a purely syntactic check.\n\nThe syntactic guardedness principle was first proposed by Coquand\\,\\citep{Coquand94} as a tool for constructive reasoning about infinite objects. Coquand argues that previous coinductive proof methods rely on impredicative definitions, which he deems to be ``unsatisfactory'' for constructive reasoning. Based on Milner's work on process calculi\\,\\citep{Milner:1989}, Coquand defines an infinite object to be productive if a (not necessarily well-founded) computation tree can be associated with it, through an analogy between infinite proof objects and processes. This observation is then synthesized into a ``guarded induction principle''. In practice, the guarded induction principle can be used for constructive proofs through a syntactic check, which verifies that all corecursive references appear directly under a coinductive constructor.\n\nIn continuation of Coquand's efforts, Gim\\'{e}nez\\,\\citep{Gimenez95} formalized an extension of the Calculus of Constructions\\,\\citep{Coquand:1988}, in which a modification of Coquand's original formulation of the guarded induction principle is provided. In particular, the guarded induction principle is modified such that it can be applied to types with second-order quantification.\n\nThe guarded induction principle described by Coquand and Gim\\'{e}nez was\nintended to be used within a proof system (e.g. Coq) for easier reasoning about\ninfinite objects. Confirming Coquand's own observation, Telford and\nTurner\\,\\citep{Telford98ensuringthe} argue that the guarded induction principle\nis too conservative in a programming setting. In their system of\n\\emph{Elementary Strong Functional Programming}\n(ESFP)\\,\\citep{Telford97ensuringstreams,Telford98ensuringthe,Telford:jucs_6_4:ensuring_termination_in_esfp},\nTelford and Turner therefore extend practical use of the guarded induction\nprinciple to detect a wider range of function as productive. They achieve this\nby considering guardedness more abstractly over a domain of ``guardedness\nlevels'', such that productive corecursion is bounded by a given\n``depth''. Intuitively, their system works by detecting that a program produces\nmore elements that it consumes, i.e. that recursive references are subject to\nmore introduction forms (constructor applications) than elimination forms (case\nanalysis). Since any program can be higher-order, the guardedness level of a\nfunction is calculated by a ``guardedness function'',  where the guardedness\nlevels of both bound and free variables are taken into account. As an advanced\nexample, Telford and Turner show that the program generating the Hamming numbers\n(a problem first discussed by Dijkstra\\,\\citep{Dijkstra:1997}) is accepted as a\nproductive program by their system. Just as Telford and Turner, one of our goals\nwith the implementation of an inference system for guarded recursion was to\novercome the restrictive nature of the syntactic guardedness principle. Where\nthe approach taken by Telford and Turner is essentially an extension of the\nunderlying idea of syntactic guardedness, our approach provides productivity\nchecking by guarded recursion through term inference and type\nchecking. Consequently, our productivity analysis is bounded by the type\nconstraints for which we can infer guarded recursive programs, and not by the\nsyntactic structure of the program written by the user.\n\nIn the same work, Hyvernat\\,\\citep{Hyvernat13} discusses an approach similar to\nthe idea behind the work of Telford and Turner. He proposes that productivity\ncan be detected by counting the number of abstractions and applications in a\nprogram, respectively. Given that one does not reduce under abstractions, a\nfunction can then be considered productive if it has more abstractions than\napplications, since this necessarily means that the program will not diverge.\n\nAnother approach to coping with the conservative nature of the original\nsyntactic guardedness principle is to consider alternative programming styles, making productive definitions easier to write. Following the incorporation of the guardedness condition into the Agda totality checker as described by Altenkirch and Danielsson (they attribute their approach to Abel)\\,\\citep{AltenkirchNAD10}, Danielsson\\,\\citep{Danielsson10beatingthe} described a method for working around the guardedness condition whenever it rejects a productive program. When a corecursive reference appears under a call to a function which is not a constructor, he designs an embedded domain-specific language in which said function is implemented as a constructor, making the guarded induction principle applicable. He is then able to define an interpreter for this language, such that the original program is ultimately accepted as productive. None of these steps happen automatically, but must be done manually. Although useful, Danielsson argues that efficiency is a concern, and that the best solution might be to entirely move away from using guardedness for productivity. Sized types have since been implemented in Agda.\n\n%\\section{Guarded Recursion}\n%Nakano\n%neelk\n%Atkey and McBride\n%Flere papers fra Aarhus + Mogel\n\n% As presented in Section~\\ref{sec:guarded-recursion}, guarded recursive type\n% systems can be used to define necessarily productive programs. The general\n% notion underlying guarded recursion was introduced by\n% Nakano\\,\\citep{Nakano:2000}, although he does not himself use the term ``guarded\n% recursion''. He introduces a modal typing system with recursive types,\n% $\\lambda\\!\\bullet\\!\\mu$ (called ``lambda-later-mu''), in which it is possible to encode provably non-diverging programs. This is achieved partly by giving a modal type to the Y-combinator (see Figure~\\ref{fig:nakano_Y}), and partly by defining types such that recursive occurrences are only available in the context of a modality $\\bullet$, e.g. infinite binary trees as a type $\\mu X.A\\times\\bullet X\\times\\bullet X$. Nakano suggests that his system could be related to temporal logic, where the $\\bullet$ modality reprensents notions of ``future time''. Additionally, he notes that the system is not intended to be used as a type system for programming languages, but serves to widen the range of programs to which the idea of proofs-as-programs can be applied.\n\n% \\begin{figure}\n% \\[\n% \\vdash \\lambda f. (\\lambda x. f (x x)) (\\lambda x. f (x x)) : (\\bullet X \\to X) \\to X\n% \\]\n% \\caption{The Y-combinator as derived in Nakano's $\\lambda\\!\\bullet\\!\\mu$ system\\,\\citep{Nakano:2000}.}\n% \\label{fig:nakano_Y}\n% \\end{figure}\n\n% Inspired by Nakano's approach, Atkey and McBride\\,\\citep{Atkey:2013} present a similar typing discipline based on the simply typed lambda calculus, paving the way for a more practical use of guarded recursion. They introduce applicative programming\\,\\citep{Mcbride:2008} over modalities, which coupled with Nakano's fixed point combinator makes programming with modalities more accessible, and provides a more compositional system for productivity checking. Their main contribution is the introduction of clock variables into a type system with guarded recursion, such that it is possible to distinguish between values that are in the process of construction and values that are fully constructed. Fully constructed values can be identified by universal quantification over clock variables, enabling the user to extract values from the modal world of guarded recursion.\n\n% Following the work by Atkey and McBride, M\\o gelberg\\,\\citep{Mogelberg:2014} extends the idea of a type system with guarded recursion and clock variables to a dependently typed setting. Based on work by Birkedal and M\\o gelberg\\,\\citep{BirkedalL:sgdtuniverse-conf} and Birkedal, M\\o gelberg, Schwinghammer, and St\\o vring\\,\\citep{BirkedalL:sgdt-journal}, he models a dependently typed lambda calculus with guarded recursion and clocks using the topos of trees model. This results in an extensional type theory for reasoning about guarded recursive types. Although no intensional formulation of the model is given, it is expected that such a formulation exists.\n\n% % In extensional type theory, definitional and propositional equality is the same\n% Typing systems with modalities on types as introduced by Nakano has also been applied in the field of functional reactive programming. Krishnaswami\\,\\citep{Krishnaswami13} presents a typing system where both time leaks (depending on past values for arbitrary intervals of time) and space leaks (non-permanent memory leaks from capturing too much history) are prevented by construction. This is accomplished by typing all values with \\emph{temporal recursive types}, using modalities on types to indicate the time at which a value becomes available. In the context of a global clock, programs are then evaluated according to two operational semantics: one giving the semantics for a program at the current clock tick, and one for advancing the global clock. Whenever the global clock is advanced, all values which can no longer be referenced due to time constraints are discarded from the environment, thus eliminating space leaks. Accompanying this mechanism are rules which make references to unavailable data impossible. Time leaks are prevented by unfolding all values at the moment they become available. Since Krishnaswami's approach enforces causality (that the first \\emph{n} outputs only depend on the first \\emph{n} input values), it can essentially be used to encode guarded recursion, at least in the simply typed formulation by Atkey and McBride. But where Atkey and McBride emphasize that clock variables localize the encoding of productivity, Krishnaswami introduces a global clock to which all programs must adhere.\n\n\\section{Sized Types}\nAn alternative type-based approach to totality checking is sized types. Where the intuitive abstraction of guarded recursion is time, sized types attach sizes to values at the type level. The motivation behind sized types is to express totality proofs using induction on sizes, such that the structure of the term in question can be disregarded. With size-change termination, termination proofs are constructed by ensuring that all recursive arguments happen on structurally smaller terms. Analogously, totality proofs using sized types are constructed by ensuring that all values are defined in terms of data with a structurally smaller \\emph{size}.  Hence, the term ``size'' implies no specific term structure on the data involved in the totality proof.\n\nSized types for totality checking were first proposed by Hughes, Pareto, and Sabry\\,\\citep{Hughes96} for reactive systems, where each data type introduced into a program is associated with a family of sized types indicating the bounds of a value of that type. A similar idea was developed by Amadio and Coupet-Grimal\\,\\citep{Amadio98}, where guard conditions are introduced into the type system to ensure the productivity of coinductive data, following the work of Coquand\\,\\citep{Coquand94} and Gim\\'{e}nez\\,\\citep{Gimenez95}.\n\nEduarde Gim\\'{e}nez also presented a system for typing recursive definitions in an extension of the Calculus of Constructions using sized types\\,\\citep{Gimenez98structuralrecursive}. A notable result of this work is that any well-typed term in the proposed extension is normalizing with respect to lazy evaluation, substantially widening the domain of functions to which type-based termination is applicable. In the wake of this extension, Abel\\,\\citep{Abel99terminationchecking} wrote a quite accessible paper on using sized types for totality checking, showing that bidirectional type checking\\,\\citep{Pierce00} is suitable for a system with sized types. In addition, Abel described how infinite streams defined as coinductive types can be encoded in a language as functions on natural numbers, and that the productivity of a stream can be understood in terms of its \\emph{definedness}, meaning the number of times it can safely be unfolded.\n\nThe notion of definedness is also an important part of Abel and Pientka's work\non applying sized types to a system with copatterns\\,\\citep{Abel13Wellfounded},\nalthough here it is defined more precisely as the \\emph{depth} of a value of\ncoinductive type. By directly using the notion of depth in the type system, they\nshow that totality proofs for both coinductive definitions with copatterns and\ninductive definitions (as well as mixed inductive-coinductive definitions) can\nbe constructed by well-founded induction on sizes within the type system. The\nmethod is shown to work for System F\\textsubscript{$\\omega$}, and has later been\nimplemented in Agda along with copatterns.\n\nFrom the perspective of automation, sized types are similar to\nguarded recursion. Presently, there does not seem to exist a procedure for\ninferring all sizes for a given definition, so these must be given manually by\nther user. The same holds for guarded recursion. While we have no knowledge of\nthe existence of a\ngeneral procedure for inferring all kinds of guarded recursive definitions, the\nsystem presented in Chapter~\\ref{cha:infer-guard-recurs} paves the way for\nfurther investigation into this area.\n\n%structurally smaller\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: \"../copatterns-thesis\"\n%%% End:\n", "meta": {"hexsha": "c56daf304ffdfce098503e70a19fab6e0619a156", "size": 21245, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "sections/related_work.tex", "max_stars_repo_name": "sualitu/thesis", "max_stars_repo_head_hexsha": "22d2cb4f21dc7c2dab011da5bb560c003650a2bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sections/related_work.tex", "max_issues_repo_name": "sualitu/thesis", "max_issues_repo_head_hexsha": "22d2cb4f21dc7c2dab011da5bb560c003650a2bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sections/related_work.tex", "max_forks_repo_name": "sualitu/thesis", "max_forks_repo_head_hexsha": "22d2cb4f21dc7c2dab011da5bb560c003650a2bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 109.5103092784, "max_line_length": 1532, "alphanum_fraction": 0.8091315604, "num_tokens": 4673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.3157387487413704}}
{"text": "\\chapter{Adding Memory to the Agents}\n\\section{Overview}\nIn the previous chapters, we have assumed that the agents interact in fully observable problems, which are modeled as MDPs. This means that the observation that the agent receives from the environment is sufficient to fully understand its state. Thus:\n\n\\begin{equation}\n    s_{t} = o_{t}\n\\end{equation}\n\nHowever, this is not always true. In robotics problems, robots observe their environment through sensors, and, commonly, the data obtained from them gives partial information about the robot's state. So, a significant set of real-world problems is better described by Partially Observable Markov Decision Processes (POMDPs).\n\nThere are different reasons why a problem could be partially observed. One of them is when a state is described by time-dependent phenomena, and the current observations only get partial information about them. For instance, an agent may need to estimate the velocity of a flying drone using instantaneous RGB images that capture its position. Unless observations from different time steps are combined, the agent is not going to be able to make the estimation of the drone's velocity. Other examples of time-dependent phenomena are temporary occlusions or corrupted communication systems between the sensors and the agent.\n\nAll of these scenarios are not covered by the variations of D-COACH proposed so far. In this chapter, we aim to add memory to the policies trained with D-COACH, in order to have a system capable of solving sequential decision-making problems with partially observed $\\text{time-dependent}$ states. The idea is to validate this approach through simulations, establishing a baseline for further research in memory-based deep interactive learning.\n\\newpage\n\n\\section{Methodology}\nThere are two well-known approaches for adding memory to agents in sequential decision-making problems when using DNNs as function approximators:\n\n\\begin{enumerate}\n    \\item \\textbf{Observation stacking \\cite{atari}}: This approach consists in stacking a fixed number of past observations to the current one, and using this stack as the input of the policy. \n    \\item \\textbf{Recurrent models \\cite{hausknecht2015deep}:} This approach uses policies that incorporate RNN layers into its neural network architecture. Given that these models have an internal state, they can store information from the past (i.e. they have memory), and use it in future inferences. \n\\end{enumerate}\n\nOne of the main issues of observation stacking is that the memory of these models is determined by the number of stacked observations. Problems that need to remember events in medium or large sequences would require larger stacks. In high-dimensional state problems, the size of the input can increase considerably as the number of stacked observations increments, generating high overheads. In contrast, RNN-based models have the ability to model information for an arbitrarily long amount of time \\cite{lample2017playing}. Also, they have no input-related overheads because when these models are evaluated they use as input one observation at a time. In RNNs, the memory-related overhead is determined by the size of their hidden states and the length of the sequences used when updating the weights of the models, so the latter is only effective when training.\n\nFrom an engineering point of view, using RNNs in products for real-world applications with long or medium time dependencies could lower their costs in comparison to using observation stacking. The input overhead of approaches based on stacked observations would be too high in these scenarios; thus, more powerful (expensive) computers would be needed. \n\nGiven the more practical usage of recurrent models and their capability of representing arbitrarily long sequences, in this chapter we use RNN-based policies (with LSTM layers) to test the viability of D-COACH for solving problems in POMDP settings. \n\n\\subsection{Learning to Remember}\nEven though RNNs are networks with the capability of storing information from past observations, they have to learn to do this. Commonly, in DRL approaches this is implicitly learned when backpropagating the error that aims to maximize the expected return. This gives the intuition that when using D-COACH, backpropagating the correction error through the recurrent layers should be enough for learning well-performing policies. Nevertheless, preliminary tests showed that shaping recurrent models with corrective feedback made the agents to rapidly overfit to the first set of corrections, loosing the capability of learning interesting behaviors and, as a consequence, failing to solve the tasks. \n\nTo overcome this problem, we propose to have DNNs separated into two parts: (1) transition model and (2) policy. The transition model is in charge of learning the dynamics of the environment in a supervised manner using samples collected by the agent while the policy part is shaped using corrective feedback. \n\nIn MDPs, a transition model is capable of predicting the next state of the environment as a function of the current state and the taken action $M(s_{t},a_{t}) = s_{t+1}$ (as in Equation \\ref{eq:model}). In contrast, in POMDPs the agent does not have direct access to its state, so, instead, the transition model can be trained to predict the next observation $o_{t+1}$. To achieve this, the neural network architecture must include recurrent layers (LSTMs in this case). LSTMs can represent in their hidden state $h_{t}$ information from past observations, which is crucial to predict the next observation when the environment is partially observed. Thus, the objective of the first part of the DNN is to learn $M(o_{t},a_{t}, h_{t-1}) = \\widetilde o_{t+1}$, which, as a consequence, learns to embed past observations in $h_{t}$.\n\nThe second part of the DNN, the policy, takes as input the concatenation of the hidden state of the transition model computed in the last time step $h_{t-1}$ with the current observation of the environment $o_{t}$ and uses this information as if it were the state. D-COACH is used to update the weights of this part as it is done in fully-observable low-dimensional state problems with D-COACH OFF. In this chapter, we are assuming that a representation of past observations combined with the current observation is a good approximation of $s_{t}$:\n\n\\begin{equation}\ns_{t}\\approx (h_{t-1}, o_{t})    \n\\end{equation}\n\nWe call this approach Memoryful ONline state representation learning D-COACH (D-COACH MON). A summary of this approach is presented in Figure \\ref{fig:mb_dcoach}.\n\n\\begin{figure}[h]\n    \\centering\n    \\includegraphics[width=0.4\\linewidth]{imagenes/cap4/model_based_dcoach.pdf}\n    \\caption{D-COACH MON general structure.}\n    \\label{fig:mb_dcoach}\n\\end{figure}\n\n\\newpage\n\n\\subsection{Low-dimensional State with Memory}\n\\label{sec:ld_memory}\nAs it has been done previously in this work, we first study the low-dimensional state case. The objective is to learn the dynamics of the environment online i.e. as the policy is shaped interactively. \n\nIf we look back to the approach taken in Chapter 3, the idea was similar. In that case the objective was to learn a low-dimensional representation of a high-dimensional input online. The strategy was to share the encoder layers of an autoencoder between the policy and the autoencoder, and to update them using both the cost of the policy and the one of the autoencoder. In this case, the hidden state of the LSTM could be interpreted as a representation of past observations. So, this recurrent layers could be shared between the policy and the model, updating them using both costs. A simplified version of this approach is shown in Figure \\ref{fig:ld_model_rip}.\n\n\\begin{figure}[h]\n    \\centering\n    \\includegraphics[width=0.6\\linewidth]{imagenes/cap4/ld_model_rip.pdf}\n    \\caption{Low-dimensional observations general neural network architecture for POMDPs (option 1).}\n    \\label{fig:ld_model_rip}\n\\end{figure}\n\nThe shortcoming presented in the approach shown in Figure \\ref{fig:ld_model_rip} is that in this case the same problem that we found in the preliminary tests appears. The error of the policy does not work well when updating the weights of recurrent layers using the D-COACH strategy, even when using the auxiliary cost of the model. \n\nAlternatively, the approach that was finally taken was to update the model and the policy separately and simultaneously. If we go back to Figure \\ref{fig:mb_dcoach}, this would mean that the \\textbf{Transition Model} box is updated with transitions collected by the agent, and, separately, the \\textbf{Policy} box is updated with corrective feedback. The proposed transition model architecture (\\textbf{Transition Model} box in Figure \\ref{fig:mb_dcoach}) consists of LSTM and FNN layers, as shown in Figure \\ref{fig:ld_model_win}. The policy architecture (\\textbf{Policy} box) is simply a composition of FNN layers, as it is done in the other variations of D-COACH.\n\n\\newpage\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=0.5\\linewidth]{imagenes/cap4/ld_model.pdf}\n    \\caption{Low-dimensional observations general neural network architecture for POMDPs (option 2).}\n    \\label{fig:ld_model_win}\n\\end{figure}\n\nFigure \\ref{fig:ld_model_win} presents the general structure of the neural network architecture that is proposed for problems with low-dimensional observations. A detailed version of the network architecture is provided in Figure \\ref{fig:detailed_ld}.\n\n\\begin{figure}[h]\n    \\centering\n    \\includegraphics[width=0.8\\linewidth]{imagenes/cap4/ld_model_det.pdf}\n    \\caption{D-COACH MON low-dimensional observations neural network architecture.}\n    \\label{fig:detailed_ld}\n\\end{figure}\n\nAs mentioned before, the transition model and the policy are trained as two separate networks. These networks depend on each other. The policy uses as part of its input $h_{t-1}$, which is a vector that the transition model outputs. Similarly, the transition model uses the last taken action as part of its input, which is a vector generated by the policy. When an update of the architecture is done, the transition model is first updated, and, consecutively, the policy is updated. A summary of this process is presented in Figure \\ref{fig:ld_mon_train}.\n\n\\begin{figure}[h]\n\\centering\n\\subfloat[][Transition model update step.]{\\includegraphics[width=0.49\\linewidth]{imagenes/cap4/ld_mon1.pdf}}\n\\subfloat[][Policy update step.]{\\includegraphics[width=0.45\\linewidth]{imagenes/cap4/ld_mon2.pdf}}\n\\caption[Update step of D-COACH MON neural network for low-dimensional observations.]{Update step of D-COACH MON neural network for low-dimensional observations. First (a), the transition model is updated in a supervised manner using as input a batch with sequences of observations and actions where the labels correspond to $o_{t+1}$. Consecutively (b), the policy is updated using human corrective feedback using as input $o_{t}$ and $h_{t-1}$.} \n\\label{fig:ld_mon_train} \n\\end{figure}\n\n\\subsection{High-dimensional State with Memory}\nIn the high-dimensional case, agents need to learn two representations: (1) spatial and (2) temporal. Spatial representation are understood as a low-dimensional representation of high-dimensional data, which is what it has been covered in the former chapters using autoencoders. In contrast, temporal representations refer to encapsulating previous observations in a memory, which is what it has been done in Section \\ref{sec:ld_memory} using LSTMs. \n\nIn preliminary tests, we found that the most effective way of doing this under the setting of D-COACH is to treat the autoencoder and the recurrent layers as one architecture to represents the transition function model. A model with the capability of learning from high-dimensional states, as it can be seen in Figure \\ref{fig:rnn_hd}. \n\n\\begin{figure}[h]\n    \\centering\n    \\includegraphics[width=0.5\\linewidth]{imagenes/cap4/hd_model.pdf}\n    \\caption{High-dimensional observations general neural network architecture for POMDPs.}\n    \\label{fig:rnn_hd}\n\\end{figure}\n\nInstead of using separate costs for the model and the autoencoder, the autoencoding cost for reconstructing $o_{t+1}$ is used. So, Equation \\ref{eq:ae} instead of being $L(x_{t},\\widetilde x_{t})$ it would be  $L(x_{t},\\widetilde x_{t+1})$. By doing this, the hidden state of the LSTM represents both the high-dimensional input and past observations, given that the autoencoder tries to reconstruct and predict $o_{t+1}$. As it was done for the low-dimensional observation case, Figure \\ref{fig:detailed_hd} introduces the detailed neural network architecture for the high-dimensional observation case.\n\n\\begin{figure}[h]\n    \\centering\n    \\includegraphics[width=\\linewidth]{imagenes/cap4/hd_model_det.pdf}\n    \\caption{D-COACH MON high-dimensional observations neural network architecture.}\n    \\label{fig:detailed_hd}\n\\end{figure}\n\nIn the same way as in the low-dimensional observation case, the transition model and the policy are trained separately and simultaneously. The only difference is that in this case, when the policy is updated it uses the encoding layers to generate an encoded low-dimensional representation of the observation $e(o_{t})$ that the policy uses as input, but only the policy layers are updated. This is also different from what is done in D-COACH OFF, where the encoding layers are also updated when training the policy. Figures \\ref{fig:hd_mon_train1} and \\ref{fig:hd_mon_train2} summarize a D-COACH MON update step for high-dimensional observations.\n\n\\begin{figure}[h]\n    \\centering\n    \\includegraphics[width=0.93\\linewidth]{imagenes/cap4/hd_mon1.pdf}\n    \\caption{Transition model update step.}\n    \\label{fig:hd_mon_train1}\n\\end{figure}\n\n\\begin{figure}[h]\n    \\centering\n    \\vspace{1.5cm}\n    \\includegraphics[width=0.93\\linewidth]{imagenes/cap4/hd_mon2.pdf}\n    \\caption{Policy update step.}\n    \\label{fig:hd_mon_train2}\n    \\vspace{1.5cm}\n\\end{figure}\n\n\n\\subsection{The Algorithm}\n\nIn Algorithm \\ref{algorithm:DeepCOACH-M}, the pseudocode of D-COACH MON is presented. The hidden state of the LSTM is denoted as  $h^{\\mathrm{LSTM}}$ and the human corrective feedback as $h$.\n\nIn every time step, the agent executes an action based on its last observation and in the current hidden state of the LSTM (line 5). This hidden state is updated using its previous value and the most recent observation and action (line 7). In this occasion, a buffer in charge of storing the samples of the transition function model ($\\mathcal{D}$) is incorporated. In both buffers, $\\mathcal{B}$ and $\\mathcal{D}$, sequences with length $\\tau$ are stored (lines 8 and 18), which is necessary for training the LSTM. This is done following the \\emph{bootstrapped random updates} \\cite{hausknecht2015deep} strategy. As in the former versions of D-COACH, $\\mathcal{B}$ is used for updating the policy (lines 16 and 22) by replaying past corrections. In contrast, $\\mathcal{D}$ replays past transitions of the environment in order to update the transition function model (lines 17 and 24). The transition model is updated every time feedback is given (lines 15 and 17), in the same way as it is done with the policy in all of the variations of D-COACH, including this one (lines 14 and 16). \n\n\\newpage\n\n\\begin{algorithm}[H]\n\\caption{D-COACH MON: Memoryful Online State Representation Learning}\\label{algorithm:DeepCOACH-M}\n\\begin{algorithmic}[1]\n\\State \\textbf{Require:} error magnitude $e$, policy buffer update interval $b$, policy buffer sampling size $N$, policy buffer min. size $k$, policy buffer max. size $K$, model buffer update interval $d$, transition function model buffer sampling size $M$, transition function model buffer min. size $l$, transition function model buffer max. size $L$, training sequence length $\\tau$.\n\\State \\textbf{Init:} $\\mathcal{B} = []$, $\\mathcal{D} = []$\n\\For{t = 1,2,...}{}\n\\State \\textbf{observe} observation $o_{t}$\n\\State \\textbf{execute} action $a_{t}=\\pi(o_{t}, h^{\\mathrm{LSTM}}_{t-1})$\n\\State \\textbf{feedback} human corrective advice $h_{t}$\n\\State \\textbf{compute} $h^{\\mathrm{LSTM}}_{t}$ from $M(o_{t}, a_{t},h^{\\mathrm{LSTM}}_{t-1})$\n\\State \\textbf{append} $(o_{t-1},...,o_{t-\\tau},a_{t-1},...,a_{t-\\tau},o_{t})$ to $\\mathcal{D}$\n\\If{length($\\mathcal{D}$) $> L$ }\n\\State $\\mathcal{D} = \\mathcal{D}[2:L+1]$\n\\EndIf\n\\If{$h_{t}$ is not \\textbf{0}}\n\\State $\\mathit{error}_{t} = h_{t}\\cdot e$\n\\State $y_{label(t)} = a_{t} + \\mathit{error}_{t}$ \n\\State \\textbf{update} $\\pi$ using SGD with $(o_{t}, h^{\\mathrm{LSTM}}_{t-1}, y_{\\mathit{label}(t)})$ \n\\State \\textbf{update} $M$ using SGD with $(o_{t-1},...,o_{t-\\tau},a_{t-1},...,a_{t-\\tau},o_{t})$\n\\State \\textbf{update} $\\pi$ using SGD with a mini-batch of sequences sampled from $\\mathcal{B}$\n\\State \\textbf{update} $M$ using SGD with a mini-batch of sequences sampled from $\\mathcal{D}$\n\\State \\textbf{append} $(o_{t},...,o_{t-\\tau},a_{t-1},...,a_{t-\\tau}, y_{\\mathit{label}(t)})$ to $\\mathcal{B}$\n\\If{length($\\mathcal{B}$) $> K$ }\n\\State $\\mathcal{B} = \\mathcal{B}[2:K+1]$\n\\EndIf\n\\EndIf\n\\If{mod(t, b) is 0 and length($\\mathcal{B}$) $\\geq$ $k$}\n\\State \\textbf{update} $\\pi$ using SGD with a mini-batch of sequences sampled from $\\mathcal{B}$\n\\EndIf\n\\If{mod(t, d) is 0 and length($\\mathcal{D}$) $\\geq$ $l$}\n\\State \\textbf{update} $M$ using SGD with a mini-batch of sequences sampled from $\\mathcal{D}$\n\\EndIf\n\\EndFor\n\\end{algorithmic}\n\\end{algorithm}\n\n\n\\section{Experiments and Results}\nSimulated teachers were used in three different problems for validating D-COACH MON. The main idea behind these experiments is to compare D-COACH MON with D-COACH ON in partially observable problems.\n\n\\begin{enumerate}\n    \\item \\textbf{Partially Observed Cart-Pole:} A partially observed low-dimensional observation scenario. This is the same environment used in Chapter 3 with a modification in the observation space of the agent. In the standard fully-observable Cart-Pole the state has four dimensions, which consists of the position $x$ and velocity $\\dot x$ of the cart and the angle $\\theta$ and angular velocity $\\dot \\theta$ of the pole, such that $s=(x, \\dot x, \\theta, \\dot \\theta)$. In this case, we take out the derivatives present in the state, such that $s=(x, \\theta)$.\n    \n    \\item \\textbf{Partially Observed Cart-Pole from Pixels:} The Cart-Pole environment is modified to use as input raw pixels from an image. The size of the Cart-Pole with respect to the background is incremented to make it easier to learn a low-dimensional representation of the input. The image dimensions are $(600 \\times 400 \\times 3)$, which is then cropped to $(400 \\times 400 \\times 3)$ and finally downsampled to $(32 \\times 32 \\times 1)$ (see Figure \\ref{fig:cartpoles}).\n    \n    \\begin{figure}[H]\n    \\centering\n    \\hspace{0.4cm}\n    \\subfloat[][Original Cart-Pole environment.]\n    {\n    \\setlength{\\fboxsep}{0pt}%\n    \\setlength{\\fboxrule}{1pt}%\n    {\\fbox{\\includegraphics[width=0.35\\linewidth]{imagenes/cap4/cartpole_LD.png}}} \n    }\n    \\hspace{1.3cm}\n    \\captionsetup{justification=centering}\n    {\n    \\setlength{\\fboxsep}{0pt}%\n    \\setlength{\\fboxrule}{1pt}%\n    \\subfloat[][Cart-Pole from pixels \\\\ $(600 \\times 400 \\times 3)$.]{\\fbox{\\includegraphics[width=0.35\\linewidth]{imagenes/cap4/cartpole_HD.png}}}\n    }\n    \\newline\n    {\n    \\setlength{\\fboxsep}{0pt}%\n    \\setlength{\\fboxrule}{1pt}%\n    \\subfloat[][Cart-Pole from pixels neural network input \\\\ $(32 \\times 32 \\times 1)$. ]{\\fbox{\\includegraphics[width=0.25\\linewidth]{imagenes/cap4/cartpole_hd2.png}}}\n    }\n    \\caption{Cart-Pole environment comparison.} \n    \\label{fig:cartpoles} \n    \\end{figure}    \n    \n    \\item \\textbf{Partially Observed Car Racing:} A partially observed high-dimensional state scenario. The Car Racing problem presented in Chapter 3 is modified such that the indicators at the bottom of the image are no longer available (see Figure \\ref{fig:no_inds_car_racing}). \n\\end{enumerate}\n\n\\begin{figure}[h]\n    \\centering\n    \\includegraphics[width=0.7\\linewidth]{imagenes/cap4/car_racing_no_inds.PNG}\n    \\caption[Partially observed Car Racing.]{Partially observed Car Racing: indicators at the bottom of the observation are removed.}\n    \\label{fig:no_inds_car_racing}\n\\end{figure}\n\nAll the results that present averaged data in the form of a curve have confidence intervals that represent the $60^{th}$ percentile of the data. For problems with low-dimensional observations, the neural network architecture presented in Figure \\ref{fig:detailed_ld} was used, and the hyper-parameters values are shown in Table \\ref{table:mon_ld_hyp}. For the high-dimensional observation case, the neural network architecture introduced in \\ref{fig:detailed_ld} was used, and the hyper-parameters shown in Tables \\ref{table:mon_hypers1}, \\ref{table:mon_hypers2} and \\ref{table:mon_hypers3} were used. The rows in the tables with no values were not used i.e. replace FC with identity. In the same way as in Chapter 3, the hyper-parameters of the neural networks used in these experiments were tuned with preliminary experiments.\n\n\\begin{table}[]\n\\centering\n\\caption[Low-dimensional observation D-COACH MON neural network hyper-parameters.]{D-COACH MON low-dimensional observation neural network hyper-parameters.}\n\\label{table:mon_ld_hyp}\n\\begin{tabular}{lcc}\n\\textbf{Layer}                                              & \\multicolumn{1}{l}{\\textbf{Activation}} & \\multicolumn{1}{l}{\\textbf{$N^{\\circ}$ neurons}}                \\\\ \\hline \\hline\nFC1                                                         & ---                                     & ---                                                    \\\\ \\hline\nFC2                                                         & ---                                     & ---                                                    \\\\ \\hline\nFC3                                                         & ReLU                                    & 300                                                    \\\\ \\hline\n\\begin{tabular}[c]{@{}l@{}}FC4\\\\ (size obs.)\\end{tabular}   & tanh                                    & Part. Cart-Pole: 2                                     \\\\ \\hline\nFC5                                                         & ---                                     & ---                                                    \\\\ \\hline\nFC6                                                         & ReLU                                    & 150                                                    \\\\ \\hline\nFC7                                                         & ReLU                                    & 64                                                     \\\\ \\hline\nFC8                                                         & ReLU                                    & 64                                                     \\\\ \\hline\n\\begin{tabular}[c]{@{}l@{}}FC9\\\\ (size action)\\end{tabular} & tanh                                    & Part. Cart-Pole: 1                                     \\\\ \\hline\nR1                                                          & LSTM                                    & \\begin{tabular}[c]{@{}c@{}}150\\\\ (size h)\\end{tabular} \\\\ \\hline\n\\end{tabular}\n\\end{table}\n\n\\begin{table}[H]\n\\vspace{1cm}\n\\parbox{\\linewidth}{\n\\centering\n\\caption[High-dimensional observation D-COACH MON convolutional and deconvolutional layers hyper-parameters]{D-COACH MON high-dimensional observations convolutional and deconvolutional layers hyper-parameters. Autoencoder latent space size: $8\\times8\\times4$ (Car Racing) and $4\\times4\\times4$ (HD Cart-Pole).}\n\\label{table:mon_hypers1}\n\\begin{tabular}{lcccc}\n\\textbf{Layer} & \\multicolumn{1}{l}{\\textbf{Activation}} & \\multicolumn{1}{l}{\\textbf{Filters}} & \\multicolumn{1}{l}{\\textbf{Filter size}} & \\multicolumn{1}{l}{\\textbf{Stride}} \\\\ \\hline \\hline\nC1             & ReLU                                    & 16                                   & $3\\times3$                                    & 2                                   \\\\ \\hline\nC2             & ReLU                                    & 8                                    & $3\\times3$                                    & 2                                   \\\\ \\hline\nC3             & ReLU                                    & 4                                    & $3\\times3$                                    & 2                                   \\\\ \\hline\nDC1            & ReLU                                    & 8                                    & $3\\times3$                                    & 2                                   \\\\ \\hline\nDC2            & ReLU                                    & 16                                   & $3\\times3$                                    & 2                                   \\\\ \\hline\nDC3            & ReLU                                    & 1                                    & $3\\times3$                                    & 2                                   \\\\ \\hline\n\\vspace{0.2cm}\n\\end{tabular}}\n\\end{table}\n\n\\begin{table}[H]\n\\centering\n\\caption{High-dimensional observation D-COACH MON observation spaces sizes.}\n\\label{table:mon_hypers3}\n\\begin{tabular}{lc}\n\\textbf{Problem}     & \\textbf{Input size} \\\\ \\hline \\hline\nCar Racing     & $64\\times64\\times1$                   \\\\ \\hline\nHD Cart-Pole    & $32\\times32\\times1$  \\\\ \\hline\n\\end{tabular}\n\\vspace{1cm}\n\\end{table}\n\n\\begin{table}[H]\n\\centering\n\\caption{High-dimensional observation D-COACH MON fully-connected and LSTM layers hyper-parameters.}\n\\label{table:mon_hypers2}\n\\begin{tabular}{lcc}\n\\textbf{Layer}                                              & \\multicolumn{1}{l}{\\textbf{Activation}} & \\multicolumn{1}{l}{\\textbf{$N^{\\circ}$ neurons}}                                        \\\\ \\hline\nFC1                                                         & ---                                     & ---                                                                                     \\\\ \\hline\nFC2                                                         & ---                                     & \\begin{tabular}[c]{@{}c@{}}Car Racing: 256\\\\ HD Cart-Pole: 64\\end{tabular} \\\\ \\hline \\hline\nFC3                                                         & ReLU                                    & 300                                                                                     \\\\ \\hline\nFC4                                                         & ReLU                                    & \\begin{tabular}[c]{@{}c@{}}Car Racing: 256\\\\ HD Cart-Pole: 64\\end{tabular} \\\\ \\hline\nFC5                                                         & ReLU                                    & 150                                                                                     \\\\ \\hline\nFC6                                                         & ReLU                                    & 150                                                                                     \\\\ \\hline\nFC7                                                         & ReLU                                    & 64                                                                                      \\\\ \\hline\nFC8                                                         & ReLU                                    & 64                                                                                      \\\\ \\hline\n\\begin{tabular}[c]{@{}l@{}}FC9\\\\ (action size)\\end{tabular} & tanh                                    & \\begin{tabular}[c]{@{}c@{}}Car Racing: 3\\\\ HD Cart-Pole: 1\\end{tabular}     \\\\ \\hline\nR1                                                          & LSTM                                    & \\begin{tabular}[c]{@{}c@{}}150\\\\ (size h)\\end{tabular}                                  \\\\ \\hline\n\\end{tabular}\n\\end{table}\n\n\\subsection{Validation Low-Dimensional State}\n\nD-COACH MON is tested in the partially observed cart-pole because it is a way of validating if the proposed methodology works in a simple setting. Figure \\ref{fig:ld_cartpole_model} shows the learning curves of D-COACH MON and D-COACH ON. The same strategy used in Chapter 3 for training policies with a simulated teacher is employed in this section.\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=0.7\\linewidth]{imagenes/cap3/cartpole_LD_model.pdf}\n    \\caption[Partially observed Cart-Pole results for simulated teacher comparing D-COACH ON and D-COACH MON.]{Partially observed cart-pole results for simulated teacher comparing D-COACH ON and D-COACH MON.  Buffer: $K = 200$; $k=5$; $b = 10$; $N = 50$; $L=1\\mathrm{e}5$; $l=5$; $d=1$; $M=50$; $\\tau=8$; $P_{h}$: $\\alpha = 0.35$; $\\tau = 0.0003$; $\\emph{e}=1$. Simulated teacher network learning rate: $0.005$; Transition model learning rate: $0.0005$.}\n    \\label{fig:ld_cartpole_model}\n\\end{figure}\n\nD-COACH ON is not able to learn a well performing policy in this case. This was expected, since the velocities of both the cart and the pole are essential for making good decisions in a problem of these characteristics. Figure \\ref{fig:cp_ex} shows an example of two scenarios wherein at time step 2 the observation would be the same in the partially observed cart-pole (if we only focus on the angle of the pole). In this example the angular velocity of the pole changes direction between scenarios, but an agent without memory is not able to tell the difference. As a consequence, in $t=2$, it would make the same decision in two opposite scenarios.\n\n\\begin{figure}[h]\n    \\centering\n    \\includegraphics[width=0.65\\linewidth]{imagenes/cap4/cartpole_ex.pdf}\n    \\caption{Cart-pole partial observability example.}\n    \\label{fig:cp_ex}\n    \\vspace{-0.2cm}\n\\end{figure}\n\nIn contrast, if the agent makes decisions based on previous observations it can understand that these two scenarios are different and take better decisions. This is shown in the blue curve of Figure \\ref{fig:ld_cartpole_model}, where the agent is able to learn a well performing policy in about 12 minutes. \n\n\\subsection{Validation High-Dimensional State}\nIn this section, we validate D-COACH MON in two different problems (once again, the simulated teacher training strategy introduced in Chapter 3 is used). Cart-pole is a problem that was not originally designed to be solved using as input raw pixels of an image, so we do not expect to obtain a perfect performance (500 score average). The main goal of testing D-COACH with this problem is to observe if the proposed model (autoencoder + LSTM) is able to embed both the past and high-dimensional inputs adequately.\n\n\\begin{figure}[h]\n    \\centering\n    \\includegraphics[width=0.7\\linewidth]{imagenes/cap3/cartpole_HD_model.pdf}\n    \\vspace{-0.2cm}\n    \\caption[Partially observed Cart-Pole from pixels results for simulated teacher comparing D-COACH ON and D-COACH MON.]{Partially observed cart-pole from pixels results for simulated teacher comparing D-COACH ON and D-COACH MON.  Buffer: $K = 1000$; $k=20$; $b = 1$; $N = 20$; $L=1\\mathrm{e}5$; $l=20$; $d=1$; $M=50$; $\\tau=4$; $P_{h}$: $\\alpha = 0.35$; $\\tau = 0.00003$; $\\emph{e}=1$; $m=50$; $\\epsilon=0.0011$. Simulated teacher network learning rate: $0.0003$; Transition model learning rate: $0.0005$; Autoencoder learning rate: $0.0003$.}\n    \\label{fig:cp_hd}\n\\end{figure}\n\nFigure \\ref{fig:cp_hd} shows a slower learning speed and a less successful convergence of D-COACH MON if we compare its performance with the one obtained in the low-dimensional observation partially observed Cart-Pole (see Figure \\ref{fig:ld_cartpole_model}). This is expected, since in this case the agent must also learn to extract features from the image. Also, D-COACH ON is not able to learn a well performing policy for this problem. So, even though D-COACH MON is not able to achieve the score of 500, a considerable improvement is made over its memoryless version, showing the importance of using recurrence in this type of problems.\n\nFinally, D-COACH MON was validated in the partially observed Car Racing problem. Figure \\ref{fig:po_cr} shows that D-COACH ON (orange curve) is able to learn a policy that achieves an average return of $\\sim700$ after $\\sim15$ minutes of training, which is an acceptable score for this problem. Nevertheless, D-COACH MON (blue curve) shows that it is possible to obtain an even better performance if memory is added to the neural network, achieving an average return of $\\sim800$ after $\\sim15$ minutes of training (problem is considered to be solved with a score of 900), which is similar to the performance of $\\text{D-COACH}$ ON in the fully observable Car Racing (see Figure \\ref{fig:simulatedteachers}). The difference between both curves shows that D-COACH MON is a more robust and powerful approach than $\\text{D-COACH}$ ON, capable of enhancing the performance of the agent in problems where $\\text{D-COACH}$ ON could appear to be sufficient.\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=0.7\\linewidth]{imagenes/cap3/car_racing_lstm.pdf}\n    \\caption[Partially observed Car Racing results for simulated teacher comparing D-COACH ON and D-COACH MON.]{Partially observed Car Racing results for simulated teacher comparing D-COACH ON and D-COACH MON.  Buffer: $K = 2000$; $k=20$; $b=10$; $N = 8$; $L=1\\mathrm{e}5$; $l=20$; $d=1$; $M=8$; $\\tau=10$; $P_{h}$: $\\alpha = 0.9$; $\\tau = 0.000015$; $\\emph{e}=(1, 1, 1)$; $m=50$; $\\epsilon=0.0011$. Simulated teacher network learning rate: $0.003$; Transition model learning rate: $0.0005$; Autoencoder learning rate: $0.003$.}\n    \\label{fig:po_cr}\n\\end{figure}\n\n\\section{Discussion}\nIn this chapter we introduced a variation of D-COACH with memory, D-COACH MON. The main objective was to extend D-COACH in order for it to work in POMDPs where the state is described by time-dependent phenomena. Low-dimensional and high-dimensional problems were covered, introducing a different model architecture for each case. \n\nD-COACH MON offers a framework that learns both the policy and the model online. This makes it easy for humans to interact in the learning process of the agents, given that no human effort is needed in extra learning steps as in the offline state representation learning version of D-COACH (Chapter 3). The experiments show that the proposed method is effective for enhancing the performance of agents in POMDPs. As discussed previously, memory-based approaches may be key to solve problems in real-world scenarios, where is common to face problems with partial observability. \n\nAs it is stated in the overview of this chapter, RNNs have an extra overhead when training, because sequences must be used for updating the weights of the recurrent layers. Given that D-COACH is an IML approach, updates are done in real-time while the teacher is providing feedback. We found that the overhead produced when updating the recurrent layers is too high for running this approach in CPU; thus, a GPU was used. This is a disadvantage with respect to the previously proposed variations of D-COACH, given that those models are able to run in real-time using CPUs. ", "meta": {"hexsha": "241f5db0a2bb3676b749bcbd9595e55ead7038e3", "size": 35058, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "cap4.tex", "max_stars_repo_name": "rperezdattari/thesis-document-latex", "max_stars_repo_head_hexsha": "3ad39caaf927dceeb0460912ebef26576493ee36", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cap4.tex", "max_issues_repo_name": "rperezdattari/thesis-document-latex", "max_issues_repo_head_hexsha": "3ad39caaf927dceeb0460912ebef26576493ee36", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cap4.tex", "max_forks_repo_name": "rperezdattari/thesis-document-latex", "max_forks_repo_head_hexsha": "3ad39caaf927dceeb0460912ebef26576493ee36", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 100.7413793103, "max_line_length": 1087, "alphanum_fraction": 0.6763648811, "num_tokens": 8480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953506426082, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.31573874079004616}}
{"text": "\\chapter{Clock Drift}\\label{chap:6}\n\\minitoc\n\nIn the previous section, we introduced a timed automata model that \ndescribes a high level representation of systems execution. \nHowever, this type of model assumes that components clocks are perfectly synchronous which is \nhardly the case in practice.\nEffectively, clocks are able to measure time up to a certain precision and will be likely\nto drift since they are implemented based on oscillators that are not perfect: the oscillator \nfrequency is not constant, it changes depending on environmental conditions such as \ntemperature, humidity and aging.\nFigure~\\ref{fig:drift_exp} illustrates an example of two clocks $x$ and $y$ having different rate\nwith respect to an implicit perfect reference time. Figure (a) shows the case\nwhere clock $x$ evolves steadily faster than clock $y$. Whereas, in Figure (b) \nclock $y$ is initially faster than clock $x$, then the trend is inverted after some time.\n\n\\begin{figure}[ht] \n\\begin{minipage}[b]{0.5\\linewidth}\n\\centering\n\\includegraphics[scale=.55]{Figures/drift1}\\\\ \n  \\vspace*{5mm} \\small{(a)} \n\\vspace{4ex}\n\\end{minipage}%%\n\\begin{minipage}[b]{0.5\\linewidth}\n\\centering\n\\includegraphics[scale=.55]{Figures/drift2}\\\\ \n  \\vspace*{5mm} \\small{(b)}\n\\vspace{4ex}\n\\end{minipage} \n\\caption{Example of Clocks with Different Rates}\n\\label{fig:drift_exp}\n\\end{figure}\n\nIn this chapter, we present a distributed timed automata model where clocks advance at \ndifferent rates and we study the resulting effect on the system behavior.\n\n\\section{Distributed Timed Systems with Independent Clock Rates}\n\n\\subsection{Expressing Clock Constraints Using Local Clock}\n\nWhen building distributed real-time systems, a common practice is to use \nlocal clocks as time references as explained in Chapter~\\ref{chap:3}.\nThese clocks measure the absolute time elapsed since the system startup and are never reset. \nThis approach reduces the effort of keeping track of the actual time progress in components\nand enable to have a common time scale. \n\nThe idea consists in mapping each clock of a component to a (unique) local clock.\nThus, the value of component clocks are obtained by simply shifting their corespondent local \nclock by a constant amount of time as soon as the clocks are not reset.\nEffectively, for each clock $x$ of a component, we introduce a real variable $\\rho_x$ that \nstores the absolute time of its last reset (with respect to its local clock), that is, if $x$ \nis mapped to a local clock $g$, then each time $x$ is reset, $\\rho_x$ is update to the current \nvalue of g.\nNotice that the value of $x$ can be found by the equality $x=g-\\rho_x$.\nAs a result, any timing constraints $c$ of a component $B_i$ can be expressed using a \nlocal clock $g$ as follows:\n\\begin{equation}\n  \\label{eq:glob}\n  c = \\bigwedge_{x_i\\in\\X_i} l\\triangleleft x_i\\triangleright u\n    =\\bigwedge_{x_i\\in\\X_i} l+\\rho_{x_i}\\triangleleft g\\triangleright u+\\rho_{x_i}\n\\end{equation}\n\nwhere $\\triangleleft\\in\\{<,\\le\\}$ and $\\triangleright\\in\\{>,\\ge\\}$.\nNotice any timing constraints of Definition~\\ref{eq:cc} can be written on the form of \ninequalities. \n\n\n\\subsection{Distributed Timed System}\n\nLet $S=(\\Loc,\\loc_0,\\X,\\D,\\gamma,\\E_{\\gamma},\\{f_e\\}_{e\\in\\gamma},\\I)$ be a timed system of $n$ \ncomponents synchronizing through the interaction set $\\gamma$. \nFor an interaction $\\alpha$, we denote by $\\clock{\\alpha}$ the set of clocks appearing in its\ntiming constraints, that is, $\\clock{\\alpha}=\\{x\\in\\X|\\forall (\\loc,\\alpha,g,r,\\loc')\\in\n\\E_{\\gamma}, x \\ \\circlled{$\\in$} \\ g \\}$, with \\circlled{$\\in$} denoting the presence of\n$x$ in the guard $g$.\n\nGiven an interaction partition $\\{\\gamma_k\\}_{k=1}^m$, we put $\\clock{\\gamma_k}$ to denote\nthe set of clocks appearing in the timing constraints of interactions of $\\gamma_k$, that is,\n$\\clock{\\gamma_k}=\\{\\cup_{\\alpha\\in\\gamma_k}\\clock{\\alpha}\\}$.\nWe formalize the independent evolution of clocks by defining an \\emph{ownership map} that assigns\na set of clocks to a unique local clock based on interaction partitioning . \nParticularly, we assign to each class of interaction a unique local clock. \nWe require additionally that clock of each components is mapped only to a unique local clock.\nThis avoid timing inconsistency and ensure that each clock of a component is evaluated using \na unique local \nclock. This constraints immediately the interaction partitioning as follows:\n\\begin{equation}\\label{eq:tcf}\n  \\bigwedge_{\\substack{i,j\\in\\{0,\\cdots,m\\}\\\\i\\neq j}}\\clock{\\gamma_i}\\cap\\clock{\\gamma_j}=\n  \\emptyset\n\\end{equation}\n\n\\begin{definition}[Distributed Timed System]\\label{def:drft}\nGiven a timed system $S=(\\Loc,\\loc_0,\\X,\\D,\\gamma,\\E,$\\\\$\\{f_e\\}_{e\\in\\gamma},\\I)$\nand an interaction partitioning satisfying the constraint~\\ref{eq:tcf}. \nWe define the corresponding distributed timed system with independent local clock rates\nas the tuple  \n  $S^{dt}=(\\Loc,\\loc_0,\\X^{dt},\\D^{dt},\\gamma,\\E^{dt},\\{f_e^{dt}\\}_{e\\in\\gamma},\\I^{dt},\\pi)$ \nsuch that:\n\\begin{itemize}\n  \\item $\\X^{dt}$ is the set of local clocks (a unique clock per class of interaction) \n  \\item $\\pi:\\X\\lto\\X^{dt}$ is a many to one mapping between clocks $\\X$ of $S$ and local clocks \n    $\\X^{dt}$\n  \\item $\\D^{dt}=\\D\\cup\\{\\cup_{x\\in\\X}\\rho_x|\\rho_x\\in\\realpoz\\}$ is the set of data with \n    $\\rho_x$ being real valued variables storing absolute reset times\n  \\item $\\E^{dt}$ is such that for every $(\\loc,\\alpha,g,r,\\loc')\\in\\E$, $\\alpha\\in\\gamma$, we \n    have the corresponding transition $(\\loc,\\alpha,g^{dt},\\emptyset,\\loc')\\in\\E^{dt}$ where:\n  \\begin{itemize}\n    \\item $g^{dt}$ is the guard $g$ expressed using the local clock $x^{dt}\\in\\X^{dt}$ where\n      $\\forall x_i,x_j\\in\\clock{\\alpha},i\\neq j,\\pi(x_i)=\\pi(x_j)=x^{dt}$\n    \\item $f_e^{dt}=f_e\\cup\\{\\rho_x:=x^{dt}|\\forall x\\in r\\}$ is the transfer function updating \n      reset variables in addition to data variables of $\\D$\n  \\end{itemize}\n  \\item $\\I^{dt}$ is the set of location invariants expressed using local clocks \n\\end{itemize}\n\\end{definition}\n\nNotice that clocks appearing in location invariants appear necessarily in at least an \ninteraction since we assume timed system with well formed guard.\n\n\\begin{property}[Semantics]\n  The semantics of a distributed timed system $S^{dt}=(\\Loc,\\loc_0,\\X^{dt},\\D^{dt},$\\\\$\\gamma,\n  \\E^{dt},\\{f_e^{dt}\\}_{e\\in\\gamma},\\I^{dt},\\pi)$ is defined by the timed transition system \n  $\\ttsb{dt}=(\\Q^{dt},q_0^{dt},\\gamma,\\lto_{\\gamma})$ where:\n  \\begin{itemize}\n    \\item $\\Q^{dt}=\\Loc\\times\\V(\\X_{dt}\\cup\\tcal{D}_{dt})\\times\\Delta$ where $\\Loc$ is \n      the set of global locations, $\\V(\\X_{dt}\\cup\\tcal{D}_{dt})$ is the set of clock and \n      data valuations, and $\\Delta=\\real$ is the set offsets of local clocks in \n      $\\X_{dt}$ with respect to an implicit (perfect) reference clock \n    \\item $q_0^{dt}=(\\loc_0,0,0)$ is the initial state.\n    \\item $\\lto_{\\gamma}\\subseteq\\Q^{dt}\\times(\\gamma\\cup\\realpos)\\times\\Q^{dt}$ is the set of \n      labeled transitions defined by the rules:\n    \\begin{itemize}\n      \\item $(\\loc,\\val,\\delta)\\transit{\\alpha}_{\\gamma}(\\loc',\\val[r],\\delta)$ for \n        $\\alpha\\in\\gamma$, if\n      $(\\loc,\\alpha,g,r,\\loc')\\in\\E^{dt}\\wedge \\val\\models g$\n    \\item $(\\loc,\\val,\\delta)\\transit{d}_{\\gamma}(\\loc,\\val',\\delta')$ for $d\\in\\realpos$, \n      such that $\\val'=\\val+d-\\delta+\\delta'\\wedge \\val'\\models\\I^{dt}(\\loc)\\wedge\\val'\\ge\\val$\n    \\end{itemize}\n  \\end{itemize}\n\\end{property}\n\nThe above semantics models drifting clocks by introducing an offset variable $\\delta$ that \nstores for each clock in $x^{dt}$ its actual drift value with respect to an implicit \nreference time. The common practice when clocks are subject to drift is to\n\\emph{regularly resynchronize} the clocks using different methods, such as bit-stuffing \nor any other clock synchronization scheme.\nConsequently, we consider a more realistic model where clocks can drift up\nto a certain value $\\epsilon$ with respect to a reference clock. This value is generally \ncomputed based on three parameters: \\emph{(i)} the post-synchronization gap, \\emph{(ii)} \nthe longest gap between synchronizations, and \\emph{(iii)} the clock precision parameter \nusually given by the constructor.\nThis induces that $\\delta\\in[-\\epsilon,\\epsilon]^{|\\X^{dt}|}$.\n\n\n\\subsection{Properties}\n\n\\begin{property}\\label{pr:rd}\n  $\\forall x,y\\in\\X^{dt},x\\neq y,\\delta=(\\cdots,\\delta_x,\\cdots,\\delta_y,\\cdots)$\n  where $|\\delta|=|\\X^{dt}|$, we have $\\delta_x-\\delta_y\\in[-2\\epsilon,2\\epsilon]$\n\\end{property}\n\nProperty~\\ref{pr:rd} states that the relative drift between local partitions \nclock is bounded by $2\\epsilon$. This results from the fact that all local\nclocks are kept within $\\epsilon$ of a reference clock.\n\nIn order to attest the correctness of the distributed semantics, we compare\nits corresponding time transition system ($\\ttsb{dt}$) and the timed transition system \nof the standard semantics ($\\ttsb{g}$).\n\nLet $R$ be the relation:\n\\begin{align*}\n  R=\\{(q^{dt},q)\\in\\Q_{dt}\\times\\Q|q^{dt}=(\\loc^{dt},\\val^{dt},\\delta), q=(\\loc,\\val) \\\\\n  \\text{ such that: }  \n  \\begin{cases}\n  \\loc^{dt}=\\loc,\\\\\n  \\forall x\\in\\X,\\val(x)=\\valdt(\\pi(x))-\\rho_x-\\delta_x  \n\\end{cases}\n\\end{align*}\n\nThe relation $R$ relates states of the distributed semantics with\nstates of the standard semantics having the same location configuration,\nand whose clock valuations expressed on local clocks are $\\delta\\in[-\\epsilon,\\epsilon]$ close. \nWe call such states $\\epsilon-$similar.\n\n\\begin{lemma}\\label{lem:equiv}\n  For $\\epsilon=0$, we have $\\ttsb{dt}\\sim_{R}\\ttsb{g}$ \n\\end{lemma}\n\nLemma~\\ref{lem:equiv} describes the fact that a given system and its corresponding \ndistributed model are bisimilar when $\\Delta=0$, that is, when clocks advance at the same \nrate (perfect clocks). \n\n\\begin{property}\\label{pr:enabled1}\n  Let $(\\qdt,q)\\in \\RS$ such that $\\qdt$ satisfies $\\enabled{\\alpha}$, then\n  $q$ satisfies \\\\$\\enabledbackwardb{\\alpha}{0}{\\epsilon}\\vee\\enabled{\\alpha}\n  \\vee\\enabledforwardb{\\alpha}{0}{\\epsilon}$.\n\\end{property}\n\nProperty~\\ref{pr:enabled1} expresses that for states $(\\qdt,q)\\in\\RS$ if it exists\nan interaction enabled at $\\qdt$ then this interaction is either enabled at $q$, \nwill be enabled after a time progress of $\\epsilon$ or is up to $\\epsilon$ after \nthe deadline of $\\alpha$. This property flows directly from the $\\epsilon-$similarity\nof states $(\\qdt,q)\\in\\RS$, the form of interactions timing constraints \n(conjunction of intervals)\nand the fact that clocks involved in the same interaction advance at the same rate. \nIt points out that any execution from\nstate $\\qdt$ might not be always possible from state $q$ or any of its time successor.\n\n\\begin{lemma}\\label{lm:enabled1}\n  Let $(\\qdt,q)\\in\\RS$ such that $\\qdt$ satisfies $\\enabled{\\alpha}\\wedge\n  \\enabledbackwardb{\\alpha}{\\epsilon}{\\epsilon}$, then\n  $q$ satisfies $\\enabledbackwardb{\\alpha}{0}{\\epsilon}$.\n\\end{lemma}\nLemma~\\ref{lm:enabled1} can be deduced straightforwardly from property~\\ref{pr:enabled1}.\nIt expresses that for states $(\\qdt,q)\\in\\RS$, if it exists an interaction $\\alpha\\in\\gamma$\nsuch that $\\alpha$ is enabled at $\\qdt$ and that clock valuations are up to $\\epsilon$ \nbefore the deadline of this interaction then, $\\alpha$ can be executed from $q$ or any of its \n$\\epsilon-$time successors (by doing a time progress up to $\\epsilon$).\n\nThe usual notion of simulation as defined in~\\ref{def:sim} is too precises. \nIt requires that each trace in one system\ncan be matched~\\emph{exactly} by a trace in the other system, that is, \ntwo states can be distinguished even for an infinitesimally\nsmall mismatch between timings ($\\epsilon\\neq0$). \nThus, we rely on the following quantitative variant of simulation~\\cite{drift:esim}. \n\n\\begin{definition}[$\\epsilon-$simulation]\\label{def:esim}\n  Given two TTS, $\\TTSc{1}$ and $\\TTSc{2}$, a relation $R\\subseteq\\Q_1\\times\\Q_2$ is a:\n  \\begin{itemize}\n    \\item Strong timed $\\epsilon-$simulation, if for any $(q_1,q_2)\\in R$, $\\sigma\\in\\sum$, \n      $d,\\epsilon\\in\\realpoz$\n    \\begin{itemize}\n      \\item $q_1\\transit{\\sigma}\\q_1'$ implies $q_2\\transit{\\sigma}q_2'$ for some $q_2'\\in\\Q_2$ \n        with $(q_1',q_2')\\in R$\n      \\item $q_1\\transit{d}\\q_1'$ implies $q_2\\transit{d'}q_2'$ for some $q_2'\\in\\Q_2$ and \n        $d'\\in\\realpoz$ with $|d'-d|\\le\\epsilon$ and $(q_1',q_2')\\in R$\n    \\end{itemize}\n    \\item Timed action $\\epsilon-$simulation, if for any $(q_1,q_2)\\in R$, $\\sigma\\in\\sum$, \n      $d,\\epsilon\\in\\realpoz$\n    \\begin{itemize}\n      \\item $q_1\\transit{d,\\sigma}\\q_1'$ implies $q_2\\transit{d',\\sigma}q_2'$ for some $q_2'\n        \\in\\Q_2$ and $d'\\in\\realpoz$ with $|d'-d|\\le\\epsilon$ and $(q_1',q_2')\\in R$\n    \\end{itemize}\n  \\end{itemize}\n  If there exists a strong timed (resp. timed action) $\\epsilon-$simulation\n  between $\\ttsb{1}$ and $\\ttsb{2}$ w.r.t $R$, then we write\n  $\\ttsb{1}\\sqsubseteq^{\\epsilon}_{R}\\ttsb{2}$ (resp. $\\tts{1}\\sqsubseteq^{\\epsilon*}_{R}\n  \\ttsb{2})$\n\\end{definition}\n\n\nThis approach characterizes\nthe degree of closeness between timed systems: it generalizes the (boolean) \nnotions of timed simulation\n(yes or no) to metrics over timed system. Formally, for a positive real number\n$\\epsilon$, a state $q_1$ is \ntold $\\epsilon-$similar to another state $q_2$ if there is a time-abstract simulation \nthat can relates both states in\nthe sense that the difference between the delays of time-step transitions is at most $\\epsilon$.\n\nAlthough this definition of simulation is less \nrestrictive, Property~\\ref{pr:enabled1} gives the intuition that for some states\n$(\\qdt,q)\\in\\RS$ there may be interactions that can be executed from $\\qdt$ but not from\n$q$, which make the $\\epsilon-$simulation impossible.\n\n\\section{Robust Distributed Semantics}\nAs explained in previous sections, the distributed semantics may \nexhibit new behavior with respect to the standard semantics.  \nIn this section, we identify the problematical states of the \ndistributed semantics and provide sufficient conditions\nthat will guarantee timed action $\\epsilon-$simulation. \n\n\\begin{definition}[Potentially Bad States]\\label{def:pbss}\n  We denote by $\\Upsilon$ the set of potentially bad states of the \n  distributed semantics characterized as follows:\n  \\[\\Upsilon=\\{q=(\\loc,\\val)|\\exists\\alpha\\in\\gamma,\\val\\models g_{\\alpha}\\wedge\n  \\val+\\epsilon\\not\\models g_{\\alpha} \\} \\]\n\\end{definition}\n\nThe intuition behind this characterization results form Property~\\ref{pr:enabled1}.\nThese states may yield possible execution of interactions in the distributed semantics that\nare not possible in the related states of the standard semantics (states that are \n$\\epsilon-$similar). \n\n\\begin{proposition}\\label{prop:esim}\n  Let $\\ttsb{dt}$ be the timed transition system of the distributed semantics. \n  We have: \n  \\[\\Upsilon\\cap\\reach^*(\\ttsb{dt})=\\emptyset\\implies\\ttsb{dt}\\sqsubseteq^{\\epsilon*}_{\\RS}\n  \\ttsb{g}\\]\n  where $\\reach^*(\\ttsb{dt})$ is the projection of states of the distributed semantics \n  on state variables of the standard semantics, that is, by considering only locations, clocks,\n  and data variables.\n\\end{proposition}\n\n\\begin{proof}[Proof of Proposition~\\ref{prop:esim}]\n  \n  In order to prove proposition~\\ref{prop:esim}, we need to show that if for any \n  $(\\qdt,q)\\in\\RS$, $\\sigma\\in\\gamma$ and $d\\in\\realpoz$:\n      \\begin{displaymath}\n        \\qdt\\transit{d,\\sigma}\\qdtb \\implies \\exists q'\\in\\Q^g, q\\transit{d',\\sigma}q',\n        \\text{ with } \n        d'\\in\\realpoz, \\ |d'-d|\\le\\epsilon \\text{ and } (\\qdtb,q')\\in\\RS\n      \\end{displaymath}\n       \n      Let $(\\qdt,q)\\in\\RS$ such that $\\Upsilon\\cap\\reach^*(\\ttsb{dt})=\\emptyset$ and \n      $\\exists\\sigma\\in\\gamma,\\exists d\\in\\realpoz,$ \n  $\\qdt\\transit{d,\\sigma}\\qdtb$. We distinguish two cases:\n  \\paragraph{\\textbf{Case 1: $d > 0$}\\\\}\n  We have $\\qdt \\transit{d,\\sigma}\\qdtb$. This means:\n    \\[\n    \\begin{cases}{}\n      \\valdtb=(\\valdt+d-\\delta+\\delta')[r^{dt},f_{\\sigma}] \\\\  \n      \\valdt +d-\\delta+\\delta'\\models\\I^{dt}(\\loc)\\wedge g_{\\sigma}^{dt} \\\\ \n      \\valdt +d-\\delta+\\delta'+\\epsilon\\models\\I^{dt}(\\loc)\\wedge g_{\\sigma}^{dt}& \n      \\qdt\\notin\\Upsilon \n    \\end{cases}\\]\n  where $[r^{dt},f_{\\sigma}]$ means after applying reset and transfer function.\n  When expressed on original clocks the above becomes:\n    \\[\\begin{cases}{}\n      \\valdtb=(\\val+\\rho+d+\\delta')[r^{dt},f_{\\sigma}]\\\\ \n      \\val+d+\\delta'\\models\\I(\\loc)\\wedge g_{\\sigma} \\\\ \n      \\val+d+\\delta'+\\epsilon\\models\\I(\\loc)\\wedge g_{\\sigma} \n    \\end{cases}\\]\n  We also have $\\delta'\\in[-\\epsilon,\\epsilon]$. Consequently we have: \n  \n  \\begin{enumerate}\n    \\item $\\delta'\\in[0,\\epsilon]$, then:\\\\\n      \\[\\begin{cases}{}\n        \\valdtb=\\val+d+\\delta'+(\\rho)[r^{dt},f_{\\sigma}]\\\\ \n      \\val+d+\\epsilon\\models\\I(\\loc)\\wedge g_{\\sigma} \\label{1} \n    \\end{cases}\\]\n    By putting $d'=d$, and  since $r^{dt}=\\emptyset$ (Definition~\\ref{def:drft}) and \n      $f_{\\sigma}$ applies only on $\\rho$ we obtain: \n      \\[\\begin{cases}\n        \\valdtb=\\val+d'+\\delta'+(\\rho)[r^{dt}] \\\\ \n      \\val+d'+\\epsilon\\models\\I(\\loc)\\wedge g_{\\sigma} \\label{1} \n      \\end{cases}\\]%%%%%\n      Consequently, we can conclude that $q\\transit{d',\\sigma}q'$ such $(\\qdtb,q')\\in\\RS$\n    \\item $\\delta'\\in[-\\epsilon,0]$, then:\\\\\n      \\[\\begin{cases}{}\n        \\valdtb=\\val+d+\\delta'+(\\rho)[r^{dt},f_{\\sigma}]\\\\ \n      \\val+d-\\epsilon+\\epsilon\\models\\I(\\loc)\\wedge g_{\\sigma} \\label{1} \n    \\end{cases}\\]\n    By putting $d'=d$, and  since $r^{dt}=\\emptyset$ (Definition~\\ref{def:drft}) and \n      $f_{\\sigma}$ applies only on $\\rho$ we obtain: \n      \\[\\begin{cases}\n        \\valdtb=\\val+d'+\\delta'-\\epsilon+(\\rho)[r^{dt}] \\\\ \n      \\val+d'\\models\\I(\\loc)\\wedge g_{\\sigma} \\label{1} \n      \\end{cases}\\]%%%%%\n      Consequently, we can conclude that $q\\transit{d',\\sigma}q'$ such $(\\qdtb,q')\\in\\RS$\n  \\end{enumerate}\n  \n  \\paragraph{\\textbf{Case 2: $d = 0$}\\\\}\n   Since $\\Upsilon\\cap\\reach^*(\\ttsb{dt})=\\emptyset$, using the same methodology of case 1, \n   we can conclude that $\\exists q'\\in\\Q^g, q\\transit{d',\\sigma}q',\\text{ with } \n        d'\\in\\realpoz, \\ |d'-d|\\le\\epsilon \\text{ and } (\\qdtb,q')\\in\\RS$.\n\\end{proof}\n\nProposition~\\ref{prop:esim} highlights an interesting property on the reachable states of the \ndistributed semantics. It states that if all the reachable states of the \ndistributed semantics are not potential bad states, i.e, $\\Upsilon\\cap\\reach^*(\\ttsb{dt})=\n\\emptyset $, then there exists a timed action $\\epsilon-$simulation between the timed transition \nsystems of the standard semantics and the distributed semantics.\n\nConsequently, the idea is to restrict the distributed semantics in order to\navoid such states. \nThis can be achieved by shrinking the upper bound of every transition timing constraints, if it \nexists, by $\\epsilon$.   \nLet $\\ttsb{\\dte}$ be the timed transition system after shrinking every existing upper bound timing\nconstraints by an amount of $\\epsilon$. Then, we have the following lemma:\n\\begin{lemma}\n  $\\ttsb{\\dte}\\subseteq\\ttsb{dt}$\n\\end{lemma}\nThe above lemma derives straightforwardly from the fact that shrinking does not introduce new\nbehavior. Conversely, it just restrains the set of states from which interactions can be \nexecuted.\n\n\\begin{lemma}\\label{lem:shrink}\n  $\\Upsilon\\cap\\reach^*(\\ttsb{\\dte})=\\emptyset$.\n\\end{lemma}\nThe above lemma is a direct consequence of the shrinking operation.   \nIn fact, since clocks of the distributed semantics an those of the standard semantics can have\nat most $\\epsilon$ difference in values, by shrinking upper bound timing constraints we avoid\nall possible execution of interactions for clock values that are $\\epsilon$ before its due date.\nConsequently, this ensures that $\\Upsilon\\cap\\reach*(\\ttsb{\\dte})=\\emptyset$ and allows for any \nrelated state of the standard semantics to execute the same interaction\ndirectly or after doing a timed step. \n%This can be effectively achieved by restricting the progress of time based to \n%$\\epsilon$ before the due date of interactions.\n%Preventing the progress of time $\\epsilon$ time units\n%before any interaction deadline will prevent any execution not possible \n%in the corresponding state of the standard semantics.\n%Formally, this restriction can be written as follows:\n%\\begin{equation}\\label{eq:res}\n% (\\loc,\\val,\\delta)\\transit{d}_{\\gamma}(\\loc,\\val',\\delta') \\text{ for } d\\in\\realpos, \n%      \\text{ such that }\\val'=\\val+d-\\delta+\\delta'\\wedge \\val'\\models\\I(\\loc)\\wedge\n%      (\\loc,\\val',\\delta')\\notin\\Upsilon\n%\\end{equation}\n\n%The above restriction of time progress helps to avoid reaching the potential bad states\n%characterized by Definition~\\ref{def:pbss}. However, this restriction does not guarantee \n%the non-reachability of such states. In fact, interaction executions may as well lead \n%to state of $\\Upsilon$. Consequently, to prove that any reachable state of the distributed\n%semantics is not a potentially bad state, we need to ensure that any \\emph{arrival state},\n%that is, state reachable immediately after the execution of an interaction is not a potentially\n%bad state.\nThe following lemma is a direct consequence of Proposition~\\ref{prop:esim} and Lemma~\\ref{lem:shrink}.\n\\begin{lemma}\n  $\\ttsb{\\dte}\\sqsubseteq^{\\epsilon*}_{\\RS}\\ttsb{g}$\n\\end{lemma}\n\n\\begin{definition}[Robustness]\\label{def:rob}\n  For a given timed system S, we say that S is robust to clock drifts iff $\\reach(\\ttsb{\\dte})$ \n  is deadlock free.\n\\end{definition}\n\nRestricting the distributed semantics through shrinking allows to avoid the reachability of some states \n(the potential bad states). This enforces the timed action $\\epsilon-$simulation between states\nof the standard semantics and those of the restricted distributed semantics.\nHowever, since shrinking reduces the set of reachable states, the timed action $\\epsilon-$simulation\nalone is not enough. We must also ensure that shrinking does not introduce any deadlocks. \nThe two aforementioned point together form our definition of robustness.\n\n\\section{Discussion}\n\nIn this chapter, we revisited the robustness concept usually used to check whether a given\nsystem still satisfies the specification (a set of properties) when subject to different\nperturbations such as clock drift. We first modeled the behavior of a timed system with \nindependent clock rates and subject to a resynchronization scheme. Thereafter, we used\na variant of simulation that relates states with a timing difference up to a certain $\\epsilon$,\nand provide a characterization of potential bad states that may invalidate this variant of \nsimulation. Then, we suggested a strategy based on shrinking upper bound timing constraints\nin order to avoid such states which allows to attest the timed action $\\epsilon-$simulation.\n\nSankur et al.~\\cite{ocan} studied the robustness problem in timed automata against guards\nshrinking. They provided a method for deciding whether shrinking all timing constraints (guards)\nof a timed automaton, by possibly different amounts, results in a timed automaton that \npreserves some time-abstract behaviors, and is not blocking. The latter represents their\nrobustness notion.\nIt was proven that if the automaton is shrinkable, then several properties established on the \ninitial automaton are preserved in the implementation (when clocks are not perfect). \nOtherwise, then the conclusion is that the model is vulnerable to the slightest variations in the \nmeasure of time and should thus be considered as non-robust, and the design should be reviewed.\nFrom a theoretical aspect, the proposed analysis was formulated as a parameter synthesis\nproblem. \\texttt{Shrinktech}~\\cite{ocan2} is a tool that implements the simulation-shrinkability \nalgorithm presented in~\\cite{ocan}. It is compatible with the Kronos~\\cite{kronos} model checker,\nthat can minimize the region graph of a timed automaton~\\cite{tl} needed by the tool.\nThe tool has been used to attest the shrinkability of several case studies, such as \nthe Philips Audio Retransmission protocol, Fischer's Mutual\nExclusion protocol (up to 4 agents), and some other asynchronous circuit models.\nThese experiments showed that the tool is capable of treating shrinkability of timed automata \nwith thousands of edges (w.r.t graphs with more than sixty thousand transitions).\nThe bottleneck of the tool was also identified as being the size of the full bisimilarity graph,\nwhich is often costly to compute, and that may require long processing time for shrinkability analysis. \nMoreover, the non-shrinkability of most models was mainly due equality constraints, or to the fact\nthat some models was designed at a high level of abstraction where imprecisions were\nnot taken into account.\n\n\n\n\n", "meta": {"hexsha": "04c21dd22a355bd9da92c7c4745fcd1bdb966ed1", "size": 24633, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapter6/chapter6.tex", "max_stars_repo_name": "dellabam/Thesis", "max_stars_repo_head_hexsha": "52b63cf522fa2e35535ae31a90f75a56d449b841", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter6/chapter6.tex", "max_issues_repo_name": "dellabam/Thesis", "max_issues_repo_head_hexsha": "52b63cf522fa2e35535ae31a90f75a56d449b841", "max_issues_repo_licenses": ["MIT", "Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter6/chapter6.tex", "max_forks_repo_name": "dellabam/Thesis", "max_forks_repo_head_hexsha": "52b63cf522fa2e35535ae31a90f75a56d449b841", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.3181818182, "max_line_length": 104, "alphanum_fraction": 0.7218365607, "num_tokens": 7044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3157387407900461}}
{"text": "\\documentclass[10pt]{article}\n\n%% ODER: format ==         = \"\\mathrel{==}\"\n%% ODER: format /=         = \"\\neq \"\n\\makeatletter\n\n\\usepackage{amstext}\n\\usepackage{amssymb}\n\\usepackage{stmaryrd}\n\\DeclareFontFamily{OT1}{cmtex}{}\n\\DeclareFontShape{OT1}{cmtex}{m}{n}\n  {<5><6><7><8>cmtex8\n   <9>cmtex9\n   <10><10.95><12><14.4><17.28><20.74><24.88>cmtex10}{}\n\\DeclareFontShape{OT1}{cmtex}{m}{it}\n  {<-> ssub * cmtt/m/it}{}\n\\newcommand{\\texfamily}{\\fontfamily{cmtex}\\selectfont}\n\\DeclareFontShape{OT1}{cmtt}{bx}{n}\n  {<5><6><7><8>cmtt8\n   <9>cmbtt9\n   <10><10.95><12><14.4><17.28><20.74><24.88>cmbtt10}{}\n\\DeclareFontShape{OT1}{cmtex}{bx}{n}\n  {<-> ssub * cmtt/bx/n}{}\n\\newcommand{\\tex}[1]{\\text{\\texfamily#1}}\t% NEU\n\n\\newcommand{\\Sp}{\\hskip.33334em\\relax}\n\n\\newlength{\\lwidth}\\setlength{\\lwidth}{4.5cm}\n\\newlength{\\cwidth}\\setlength{\\cwidth}{8mm} % 3mm\n\n\\newcommand{\\Conid}[1]{\\mathit{#1}}\n\\newcommand{\\Varid}[1]{\\mathit{#1}}\n\\newcommand{\\anonymous}{\\kern0.06em \\vbox{\\hrule\\@width.5em}}\n\\newcommand{\\plus}{\\mathbin{+\\!\\!\\!+}}\n\\newcommand{\\bind}{\\mathbin{>\\!\\!\\!>\\mkern-6.7mu=}}\n\\newcommand{\\sequ}{\\mathbin{>\\!\\!\\!>}}\n\\renewcommand{\\leq}{\\leqslant}\n\\renewcommand{\\geq}{\\geqslant}\n\\newcommand{\\NB}{\\textbf{NB}}\n\\newcommand{\\Todo}[1]{$\\langle$\\textbf{To do:}~#1$\\rangle$}\n\n\\makeatother\n\n\\usepackage{fullpage}\n\\usepackage{alltt}\n\n\\bibliographystyle{plain}\n\n\\parskip=\\medskipamount\n\\parindent=0pt\n\n\\title{A Haskell Companion for ``Using catamorphisms, subtypes and\n  monad transformers for writing modular functional interpreters''}\n\\author{\\emph{Uk'taad B'mal} \\\\\n  The University of Kansas - ITTC \\\\\n  2335 Irving Hill Rd, Lawrence, KS 66045 \\\\\n  \\texttt{lambda@ittc.ku.edu}}\n\n\\begin{document}\n\n\\maketitle\n\n\\begin{abstract}\n\n  This document is a primer to accompany the paper ``Using\n  catamorphisms, subtypes, and monad transformers for writing modular\n  functional interpreters'' by Luc Duponcheel.  It attempts to\n  re-implement in \\texttt{Haskell} the interpreters written in\n  \\texttt{Gopher}.  In addition to the interpreters, examples\n  expressions are provided for each interpreter to help readers\n  understand the abstract syntax interpreted.  Each interpreter is\n  also extended to demonstrate how well the modular interpreter\n  achieves its modularity goal.\n\\end{abstract}\n\n\\section{Introduction}\n\nAmong them most accessible papers on composable interpreters is\nDuponcheel's ``Using catamorphisms, subtypes and monad transformers\nfor writing modular functional interpreters.''  Unfortunately, the\ncode examples are written in \\texttt{Gopher} rather than\n\\texttt{Haskell} and there are no examples of actual expressions or\nexpression evaluation.  This document attempts to address this problem\nby providing \\texttt{Haskell} source in literal script as well as\nexample expressions for the several interpreters.  Three different\ninterpreters are defined based on Duponcheel's examples.  In addition,\nexamples of extension are included for the two modular interpreters.\n\n\\section{First Try}\n\nModule \\ensuremath{\\Conid{FirstTry}} presents a Haskell encoding of Duponcheel's First\nTry at building a modular interpreter:\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{module}\\;\\Conid{FirstTry}\\;\\mathbf{where}}$\n\\end{tabbing}\nThe interpreter defined is a simple implementation of a language that\nsupports adding and dividing integer numbers.  The approach is to\nfirst define an interpreter for numbers and addition (\\ensuremath{\\Varid{eval}_1}), then\nextend the interpreter to include division (\\ensuremath{\\Varid{eval}_2}).\n\nFirst, we define data structures for \\ensuremath{\\Varid{Expr}_1} representing numbers and\naddition:\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{data}\\;\\Varid{Expr}_1}$\\\\\n${\\hskip2.00em\\relax\\mathrel{=}\\Conid{Num1}\\;\\Conid{Int}}$\\\\\n${\\hskip2.00em\\relax\\mid \\Conid{Add1}\\;\\Varid{Expr}_1\\;\\Varid{Expr}_1}$\\\\\n${\\hskip2.00em\\relax\\phantom{\\mid \\mbox{}}\\mathbf{deriving}\\;(\\Conid{Eq},\\Conid{Show})}$\n\\end{tabbing}\nNext, define semantic functions associated with the two operations.\n\\ensuremath{\\Varid{num}} simply returns the number encapsulated buy \\ensuremath{\\Conid{Num}} while \\ensuremath{\\Varid{add}}\nsums the numbers associated with an \\ensuremath{\\Conid{Add}} term.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\Varid{num}\\mathrel{=}\\Varid{id}\\mbox{\\qquad-{}-  Num1 Int}}$\\\\\n${\\Varid{add}\\;\\Varid{x}\\;\\Varid{y}\\mathrel{=}\\Varid{x}\\mathbin{+}\\Varid{y}\\mbox{\\qquad-{}-  Add1 Expr1 Expr1}}$\n\\end{tabbing}\nThe \\ensuremath{\\Varid{eval}_1} function associates semantics with abstract syntax.  For\neach term defined in \\ensuremath{\\Varid{Expr}_1}, \\ensuremath{\\Varid{eval}_1} generates a semantic\ninterpretation:\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\Varid{eval}_1\\mathbin{::}\\Varid{Expr}_1\\to \\Conid{Int}}$\\\\\n${\\Varid{eval}_1\\;(\\Conid{Num1}\\;\\Varid{x})\\mathrel{=}\\Varid{num}\\;\\Varid{x}\\mbox{\\qquad-{}-  Num1 x}}$\\\\\n${\\Varid{eval}_1\\;(\\Conid{Add1}\\;\\Varid{x}\\;\\Varid{y})\\mathrel{=}\\Varid{eval}_1\\;\\Varid{x}\\mathbin{`\\Varid{add}`}\\Varid{eval}_1\\;\\Varid{y}\\mbox{\\qquad-{}-  Add1 x y}}$\n\\end{tabbing}\nWe now have an interpreter defined for numbers and addition operations\nwhere both are defined as constructors in a single data type.  What we\nare attempting to demonstrate is that such interpreters can be\nextended by adding further operations and types.  In this case, we'll\nadd a division operation to the initial interpreter.\n\nBecause the initial interpreter is not particularly modular, the\nextension requires us to touch almost all of the original code.\nFirst, the \\ensuremath{\\Varid{Expr}_1} data type is modified to include a division\noperation and becomes \\ensuremath{\\Conid{Expr}}:\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{data}\\;\\Conid{Expr}}$\\\\\n${\\hskip2.00em\\relax\\mathrel{=}\\Conid{Num}\\;\\Conid{Int}}$\\\\\n${\\hskip2.00em\\relax\\mid \\Conid{Add}\\;\\Conid{Expr}\\;\\Conid{Expr}}$\\\\\n${\\hskip2.00em\\relax\\mid \\Conid{Dvd}\\;\\Conid{Expr}\\;\\Conid{Expr}}$\\\\\n${\\hskip2.00em\\relax\\phantom{\\mid \\mbox{}}\\mathbf{deriving}\\;(\\Conid{Show},\\Conid{Eq})}$\n\\end{tabbing}\nWe can reuse the semantic definitions for \\ensuremath{\\Conid{Num}} and \\ensuremath{\\Conid{Add}}, but we need\na semantic definition for \\ensuremath{\\Conid{Dvd}}:\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\Varid{dvd}\\;\\Varid{x}\\;\\Varid{y}\\mathrel{=}\\mathbf{if}\\;\\Varid{y}\\equiv \\mathrm{0}\\;\\mathbf{then}\\;\\Varid{error}\\;\\text{\\tt \\char34 Divide~by~zero\\char34}\\;\\mathbf{else}\\;\\Varid{x}\\mathbin{\\Varid{`div`}}\\Varid{y}}$\n\\end{tabbing}\nThe new \\ensuremath{\\Varid{eval}} function extends \\ensuremath{\\Varid{eval}_1} by adding a case for the\ndivision operation.  Note that the function must be rewritten and\ncannot simply be extended.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\Varid{eval}\\mathbin{::}\\Conid{Expr}\\to \\Conid{Int}}$\\\\\n${\\Varid{eval}\\;(\\Conid{Num}\\;\\Varid{x})\\mathrel{=}\\Varid{id}\\;\\Varid{x}}$\\\\\n${\\Varid{eval}\\;(\\Conid{Add}\\;\\Varid{x}\\;\\Varid{y})\\mathrel{=}\\Varid{eval}\\;\\Varid{x}\\mathbin{`\\Varid{add}`}\\Varid{eval}\\;\\Varid{y}}$\\\\\n${\\Varid{eval}\\;(\\Conid{Dvd}\\;\\Varid{x}\\;\\Varid{y})\\mathrel{=}\\Varid{eval}\\;\\Varid{x}\\mathbin{`\\Varid{dvd}`}\\Varid{eval}\\;\\Varid{y}}$\n\\end{tabbing}\nWith this, we have an interpreter for an expression language that\nallows numbers, addition and division.  Each new type or operation\nrequires the same effort of rewriting expression syntax, adding\nsemantics and modifying the evaluation function.  With the exception\nof the semantic functions, virtually none of the existing code goes\nunmodified.  For small interpreters, this is not a problem.  For\nlarger, more complex interpreters extension becomes more difficult.\n\n\\section{Second Try}\n\nModule \\ensuremath{\\Conid{SecondTry}} presents a Haskell encoding of Duponcheel's Second\nTry and building a modular interpreter:\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{module}\\;\\Conid{SecondTry}\\;\\mathbf{where}}$\n\\end{tabbing}\nAgain, we define data structures for \\ensuremath{\\Varid{E}_1} representing the abstract\nsyntax of numbers and addition, and \\ensuremath{\\Varid{E}_2} representing the abstract\nsyntax of division.  Unlike First Try, these data structures are\nseparate types::\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{data}\\;\\Varid{E}_1\\;\\Varid{x}}$\\\\\n${\\hskip2.00em\\relax\\mathrel{=}\\Conid{Num}\\;\\Conid{Int}}$\\\\\n${\\hskip2.00em\\relax\\mid \\Conid{Add}\\;\\Varid{x}\\;\\Varid{x}}$\\\\\n${\\hskip2.00em\\relax\\phantom{\\mid \\mbox{}}\\mathbf{deriving}\\;(\\Conid{Eq},\\Conid{Show})}$\\\\\n${}$\\\\\n${\\mathbf{data}\\;\\Varid{E}_2\\;\\Varid{x}\\mathrel{=}\\Conid{Dvd}\\;\\Varid{x}\\;\\Varid{x}\\;\\mathbf{deriving}\\;(\\Conid{Eq},\\Conid{Show})}$\n\\end{tabbing}\nThe difficult with expressions as defined in First Try is their\nrecursive nature.  Because of this, the single data structure\nrepresenting expression must be modified each time the language is\nupdated.  Here, we use \\ensuremath{\\Varid{E}_1} and \\ensuremath{\\Varid{E}_2} to define expressions that are not\ndirectly recursive.  The data constructors \\ensuremath{\\Conid{In1}} and \\ensuremath{\\Conid{In2}} prevent\ngeneral recursion in the data types:\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{data}\\;\\Varid{Expr}_1\\mathrel{=}\\Conid{In1}\\;(\\Varid{E}_1\\;\\Varid{Expr}_1)\\;\\mathbf{deriving}\\;(\\Conid{Eq},\\Conid{Show})}$\\\\\n${}$\\\\\n${\\mathbf{data}\\;\\Varid{Expr}_2\\mathrel{=}\\Conid{In2}\\;(\\Varid{E}_2\\;\\Varid{Expr}_2)\\;\\mathbf{deriving}\\;(\\Conid{Eq},\\Conid{Show})}$\n\\end{tabbing}\nSemantic functions for each of the operations remain unchanged and\nwill remain unchanged in all our interpreters:\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\Varid{num}\\mathrel{=}\\Varid{id}\\mbox{\\qquad-{}-  Num1 Int}}$\\\\\n${\\Varid{add}\\;\\Varid{x}\\;\\Varid{y}\\mathrel{=}\\Varid{x}\\mathbin{+}\\Varid{y}\\mbox{\\qquad-{}-  Add1 Expr1 Expr1}}$\\\\\n${\\Varid{dvd}\\;\\Varid{x}\\;\\Varid{y}\\mathrel{=}\\mathbf{if}\\;\\Varid{y}\\equiv \\mathrm{0}\\;\\mathbf{then}\\;\\Varid{error}\\;\\text{\\tt \\char34 Divide~by~zero\\char34}\\;\\mathbf{else}\\;\\Varid{x}\\mathbin{\\Varid{`div`}}\\Varid{y}}$\n\\end{tabbing}\n%% Working here...\n\nTwo helper functions are used to define evaluation functions for each\nof the data types.  A \\ensuremath{\\Varid{map}} function distributes a function across an\nexpression.  Specifically, if \\ensuremath{\\Varid{g}} is a function, then mapping \\ensuremath{\\Varid{g}} onto\n\\ensuremath{\\Conid{Add}\\;\\Varid{x}\\;\\Varid{y}} is equal to \\ensuremath{\\Conid{Add}\\;(\\Varid{g}\\;\\Varid{x})\\;(\\Varid{g}\\;\\Varid{y})}.  The \\ensuremath{\\Varid{map}} function will be\nused to map \\ensuremath{\\Varid{eval}} functions onto language terms.  The \\ensuremath{\\Varid{\\phi}} functions\nmap syntax to semantics.  Each \\ensuremath{\\Varid{\\phi}} function maps a term to its\nsemantic interpretation.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\Varid{map1}\\mathbin{::}(\\Varid{x}\\to \\Varid{y})\\to (\\Varid{E}_1\\;\\Varid{x}\\to \\Varid{E}_1\\;\\Varid{y})}$\\\\\n${\\Varid{map1}\\;\\Varid{g}\\;(\\Conid{Num}\\;\\Varid{n})\\mathrel{=}\\Conid{Num}\\;\\Varid{n}}$\\\\\n${\\Varid{map1}\\;\\Varid{g}\\;(\\Conid{Add}\\;\\Varid{e}\\;\\Varid{f})\\mathrel{=}(\\Conid{Add}\\;(\\Varid{g}\\;\\Varid{e})\\;(\\Varid{g}\\;\\Varid{f}))}$\\\\\n${}$\\\\\n${\\Varid{map2}\\mathbin{::}(\\Varid{x}\\to \\Varid{y})\\to (\\Varid{E}_2\\;\\Varid{x}\\to \\Varid{E}_2\\;\\Varid{y})}$\\\\\n${\\Varid{map2}\\;\\Varid{g}\\;(\\Conid{Dvd}\\;\\Varid{e}\\;\\Varid{f})\\mathrel{=}(\\Conid{Dvd}\\;(\\Varid{g}\\;\\Varid{e})\\;(\\Varid{g}\\;\\Varid{f}))}$\\\\\n${}$\\\\\n${\\Varid{\\phi_1}\\mathbin{::}\\Varid{E}_1\\;\\Conid{Int}\\to \\Conid{Int}}$\\\\\n${\\Varid{\\phi_1}\\;(\\Conid{Num}\\;\\Varid{n})\\mathrel{=}\\Varid{num}\\;\\Varid{n}}$\\\\\n${\\Varid{\\phi_1}\\;(\\Conid{Add}\\;\\Varid{e}\\;\\Varid{f})\\mathrel{=}\\Varid{e}\\mathbin{`\\Varid{add}`}\\Varid{f}}$\\\\\n${}$\\\\\n${\\Varid{\\phi_2}\\mathbin{::}\\Varid{E}_2\\;\\Conid{Int}\\to \\Conid{Int}}$\\\\\n${\\Varid{\\phi_2}\\;(\\Conid{Dvd}\\;\\Varid{e}\\;\\Varid{f})\\mathrel{=}\\Varid{e}\\mathbin{`\\Varid{dvd}`}\\Varid{f}}$\n\\end{tabbing}\nAn evaluation function becomes mapping the evaluation function onto a\nterm and semantically interpreting the result.  The functions \\ensuremath{\\Varid{eval}_1}\nand \\ensuremath{\\Varid{eval}_2} separately evaluate expressions \\ensuremath{\\Varid{Expr}_1} and \\ensuremath{\\Varid{Expr}_2} and\nare included as examples of writing evaluation functions. They will\nnot be used to write the composite evaluation function for both terms.\nInstead, \\ensuremath{\\Varid{map}} and \\ensuremath{\\Varid{psi}} functions will be composed to form a new\nevaluation function.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\Varid{eval}_1\\mathbin{::}\\Varid{Expr}_1\\to \\Conid{Int}}$\\\\\n${\\Varid{eval}_1\\;(\\Conid{In1}\\;\\Varid{e1})\\mathrel{=}\\Varid{\\phi_1}\\;(\\Varid{map1}\\;\\Varid{eval}_1\\;\\Varid{e1})}$\\\\\n${}$\\\\\n${\\Varid{eval}_2\\mathbin{::}\\Varid{Expr}_2\\to \\Conid{Int}}$\\\\\n${\\Varid{eval}_2\\;(\\Conid{In2}\\;\\Varid{e2})\\mathrel{=}\\Varid{\\phi_2}\\;(\\Varid{map2}\\;\\Varid{eval}_2\\;\\Varid{e2})}$\n\\end{tabbing}\nThe \\ensuremath{\\Conid{Sum}} data type is a general purpose data structure that defines\nthe disjoint union of two other data types.  The union is disjoint\nbecause the constructors \\ensuremath{\\Conid{L}} and \\ensuremath{\\Conid{R}} identify the original type any\nelement of the sum must come from.  (In a real implementation, the\nbuilt-in \\ensuremath{\\Conid{Either}} type would be used rather than writing our own\n\\ensuremath{\\Conid{Sum}}.)\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{data}\\;\\Conid{Sum}\\;\\Varid{x}\\;\\Varid{y}\\mathrel{=}\\Conid{L}\\;\\Varid{x}\\mid \\Conid{R}\\;\\Varid{y}\\;\\mathbf{deriving}\\;(\\Conid{Show},\\Conid{Eq})}$\\\\\n${}$\\\\\n${(\\mathbin{<+>})\\mathbin{::}(\\Varid{x}\\to \\Varid{z})\\to (\\Varid{y}\\to \\Varid{z})\\to (\\Conid{Sum}\\;\\Varid{x}\\;\\Varid{y}\\to \\Varid{z})}$\\\\\n${\\Varid{l}\\mathbin{<+>}\\Varid{r}\\mathrel{=}\\lambda \\Varid{s}\\to \\mathbf{case}\\;\\Varid{s}\\;\\mathbf{of}}$\\\\\n${\\phantom{\\Varid{l}\\mathbin{<+>}\\Varid{r}\\mathrel{=}\\lambda \\Varid{s}\\to \\mathbf{case}\\;\\Varid{s}\\;\\mbox{}}\\Conid{L}\\;\\Varid{x}\\to \\Varid{l}\\;\\Varid{x}}$\\\\\n${\\phantom{\\Varid{l}\\mathbin{<+>}\\Varid{r}\\mathrel{=}\\lambda \\Varid{s}\\to \\mathbf{case}\\;\\Varid{s}\\;\\mbox{}}\\Conid{R}\\;\\Varid{x}\\to \\Varid{r}\\;\\Varid{x}}$\n\\end{tabbing}\nThe type synonym, \\ensuremath{\\Conid{E}}, represents the sum of the abstract syntax data\ntypes for numbers and addition (\\ensuremath{\\Varid{E}_1}) and division (\\ensuremath{\\Varid{E}_2}).  The \\ensuremath{\\Conid{L}}\nconstructor will encapsulate numbers and addition while the \\ensuremath{\\Conid{R}}\nconstructor will encapsulate division.  The type \\ensuremath{\\Conid{E}} is the disjoint\nunion and may thus be constructed with \\ensuremath{\\Conid{L}} or \\ensuremath{\\Conid{R}} and may therefore\nbe either of the expression types.  Thus, we now have a type that\nencapsulates both terms.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{type}\\;\\Conid{E}\\;\\Varid{x}\\mathrel{=}\\Conid{Sum}\\;(\\Varid{E}_1\\;\\Varid{x})\\;(\\Varid{E}_2\\;\\Varid{x})}$\n\\end{tabbing}\nThe \\ensuremath{\\Conid{Expr}} data type represents an individual expression encapsulated\nby the \\ensuremath{\\Conid{InE}} constructor.  This is necessary to identify both \\ensuremath{\\Conid{L}} and\n\\ensuremath{\\Conid{R}} constructs from \\ensuremath{\\Conid{Sum}} as expressions.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{data}\\;\\Conid{Expr}\\mathrel{=}\\Conid{InE}\\;(\\Conid{E}\\;\\Conid{Expr})}$\n\\end{tabbing}\nWith expressions defined, we can now define \\ensuremath{\\Varid{map}}, \\ensuremath{\\Varid{\\phi}} and \\ensuremath{\\Varid{eval}}\nfunctions using the same technique as for individual terms.  The\ncomposite \\ensuremath{\\Varid{map}} function, \\ensuremath{\\Varid{map}_E}, uses \\ensuremath{\\Varid{map1}} and \\ensuremath{\\Varid{map2}} to define a\ncomposite map function.  The construction is fascinating and is worth\nsome investigation.\n\nThe signature of \\ensuremath{\\Conid{MapE}} indicates that we will take a function between\ntwo seemingly arbitrary types, \\ensuremath{\\Varid{x}} and \\ensuremath{\\Varid{y}}, and produces a function\nthat maps the encapsulation of \\ensuremath{\\Varid{x}} as a term into the encapsulation\nof \\ensuremath{\\Varid{y}} as a term.  This implies that \\ensuremath{\\Varid{x}} and \\ensuremath{\\Varid{y}} are not arbitrary at\nall.  Because \\ensuremath{\\Conid{E}} is defined as the \\ensuremath{\\Conid{Sum}} of \\ensuremath{\\Varid{E}_1} and \\ensuremath{\\Varid{E}_2}, we know\nthat \\ensuremath{\\Varid{x}} and \\ensuremath{\\Varid{y}} must be terms from our abstract syntax.\n\nTo form the definition of \\ensuremath{\\Conid{MapE}}, we simply build a function for\nmapping \\ensuremath{\\Varid{g}} onto each expression type and encapsulate the result\nappropriately using the \\ensuremath{\\Conid{L}} and \\ensuremath{\\Conid{R}} constructors.  \\ensuremath{\\Varid{map1}} and \\ensuremath{\\Varid{map2}}\nprovide the appropriate mapping functions for each expression type and\nwe know that expressions of type \\ensuremath{\\Varid{E}_1} should be encapsulated with \\ensuremath{\\Conid{L}}\nand those of type \\ensuremath{\\Varid{E}_2} with \\ensuremath{\\Conid{R}}.  Thus, it is simple to build a\nfunction for each element of the abstract syntax by composing\nencapsulation and map functions.  \\ensuremath{\\Conid{L}\\mathbin{\\circ}\\Varid{map1}\\;\\Varid{g}} is a function that maps\n\\ensuremath{\\Varid{g}} onto its argument of type \\ensuremath{\\Varid{E}_1} and encapsulates the result with\n\\ensuremath{\\Conid{L}}.  Similarly, \\ensuremath{\\Conid{R}\\mathbin{\\circ}\\Varid{map2}\\;\\Varid{g}} is a function that operates on\nexpressions of type \\ensuremath{\\Varid{E}_2}.\n\nAssembling the functions is easily achieved using the \\ensuremath{\\mathbin{<+>}} operation\nfrom \\ensuremath{\\Conid{Sum}}.  This operation simply examines its argument and\ndetermines whether it is encapsulated with \\ensuremath{\\Conid{L}} or \\ensuremath{\\Conid{R}}. If \\ensuremath{\\Conid{L}}, the\nfirst function argument is selected and applied.  If \\ensuremath{\\Conid{R}}, the second.\nThus, \\ensuremath{\\Varid{map}_E} composes \\ensuremath{\\Varid{map1}} and \\ensuremath{\\Varid{map2}} to form a mapping function\nthat works on all term types.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\Varid{map}_E\\mathbin{::}(\\Varid{x}\\to \\Varid{y})\\to (\\Conid{E}\\;\\Varid{x}\\to \\Conid{E}\\;\\Varid{y})}$\\\\\n${\\Varid{map}_E\\;\\Varid{g}\\mathrel{=}(\\Conid{L}\\mathbin{\\circ}\\Varid{map1}\\;\\Varid{g})\\mathbin{<+>}(\\Conid{R}\\mathbin{\\circ}\\Varid{map2}\\;\\Varid{g})}$\n\\end{tabbing}\nBuilding \\ensuremath{\\Conid{PhiE}} is analogous to building \\ensuremath{\\Varid{map}_E}, except that the\ndomain argument is already encapsulated with \\ensuremath{\\Conid{L}} or \\ensuremath{\\Conid{R}}.  This, the\ncomposition operator is used directly to compose \\ensuremath{\\Varid{\\phi_1}} and \\ensuremath{\\Varid{\\phi_2}}.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\Varid{\\phi}_E\\mathbin{::}\\Conid{E}\\;\\Conid{Int}\\to \\Conid{Int}}$\\\\\n${\\Varid{\\phi}_E\\mathrel{=}\\Varid{\\phi_1}\\mathbin{<+>}\\Varid{\\phi_2}}$\n\\end{tabbing}\nBuilding \\ensuremath{\\Conid{EvalE}} is exactly analogous to building \\ensuremath{\\Conid{Eval1}} or \\ensuremath{\\Conid{Eval2}}.\n\\ensuremath{\\Conid{EvalE}} is first mapped onto the expression to evaluate sub-terms and\n\\ensuremath{\\Varid{\\phi}_E} associates the result with its operational semantics.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\Varid{eval}_E\\mathbin{::}\\Conid{Expr}\\to \\Conid{Int}}$\\\\\n${\\Varid{eval}_E\\;(\\Conid{InE}\\;\\Varid{e})\\mathrel{=}\\Varid{\\phi}_E\\;(\\Varid{map}_E\\;\\Varid{eval}_E\\;\\Varid{e})}$\n\\end{tabbing}\nFollowing are some examples of expressions being evaluated.  These\nthings aren't trivial to figure out from the paper because there are\nno example expressions.  Note that the constructors for the sum type\nmust be specified along with the actual value.  Further, the\nconstructor for the outermost expression must also be present as well.\nI didn't anticipate this when I went through the examples the first\ntime.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mbox{\\qquad-{}-  Return the value 1}}$\\\\\n${\\Varid{test}_0\\mathrel{=}\\Varid{eval}_E\\;(\\Conid{InE}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{1})))}$\\\\\n${}$\\\\\n${\\mbox{\\qquad-{}-  Add 1 and 1}}$\\\\\n${\\Varid{test}_1\\mathrel{=}\\Varid{eval}_E\\;(\\Conid{InE}\\;(\\Conid{L}\\;(\\Conid{Add}\\;(\\Conid{InE}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{1})))\\;(\\Conid{InE}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{1}))))))}$\\\\\n${}$\\\\\n${\\mbox{\\qquad-{}-  Divide 1 by 1}}$\\\\\n${\\Varid{test}_2\\mathrel{=}\\Varid{eval}_E\\;(\\Conid{InE}}$\\\\\n${\\phantom{\\Varid{test}_2\\mathrel{=}\\Varid{eval}_E\\;(\\mbox{}}(\\Conid{R}\\;(\\Conid{Dvd}}$\\\\\n${\\phantom{\\Varid{test}_2\\mathrel{=}\\Varid{eval}_E\\;(\\mbox{}}\\phantom{(\\Conid{R}\\;(\\mbox{}}(\\Conid{InE}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{1})))}$\\\\\n${\\phantom{\\Varid{test}_2\\mathrel{=}\\Varid{eval}_E\\;(\\mbox{}}\\phantom{(\\Conid{R}\\;(\\mbox{}}(\\Conid{InE}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{1}))))))}$\\\\\n${}$\\\\\n${\\mbox{\\qquad-{}-  Divide 1 by 0}}$\\\\\n${\\Varid{test}_3\\mathrel{=}\\Varid{eval}_E\\;(\\Conid{InE}}$\\\\\n${\\phantom{\\Varid{test}_3\\mathrel{=}\\Varid{eval}_E\\;(\\mbox{}}(\\Conid{R}\\;(\\Conid{Dvd}}$\\\\\n${\\phantom{\\Varid{test}_3\\mathrel{=}\\Varid{eval}_E\\;(\\mbox{}}\\phantom{(\\Conid{R}\\;(\\mbox{}}(\\Conid{InE}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{1})))}$\\\\\n${\\phantom{\\Varid{test}_3\\mathrel{=}\\Varid{eval}_E\\;(\\mbox{}}\\phantom{(\\Conid{R}\\;(\\mbox{}}(\\Conid{InE}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{0}))))))}$\\\\\n${}$\\\\\n${\\mbox{\\qquad-{}-  Divide 1 by 1 and add 1}}$\\\\\n${\\Varid{test}_4\\mathrel{=}\\Varid{eval}_E\\;(\\Conid{InE}}$\\\\\n${\\phantom{\\Varid{test}_4\\mathrel{=}\\Varid{eval}_E\\;(\\mbox{}}(\\Conid{L}\\;(\\Conid{Add}}$\\\\\n${\\phantom{\\Varid{test}_4\\mathrel{=}\\Varid{eval}_E\\;(\\mbox{}}\\phantom{(\\Conid{L}\\;(\\mbox{}}(\\Conid{InE}\\;(\\Conid{R}\\;(\\Conid{Dvd}}$\\\\\n${\\phantom{\\Varid{test}_4\\mathrel{=}\\Varid{eval}_E\\;(\\mbox{}}\\phantom{(\\Conid{L}\\;(\\mbox{}}\\phantom{(\\Conid{InE}\\;(\\Conid{R}\\;(\\mbox{}}(\\Conid{InE}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{1})))}$\\\\\n${\\phantom{\\Varid{test}_4\\mathrel{=}\\Varid{eval}_E\\;(\\mbox{}}\\phantom{(\\Conid{L}\\;(\\mbox{}}\\phantom{(\\Conid{InE}\\;(\\Conid{R}\\;(\\mbox{}}(\\Conid{InE}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{1}))))))}$\\\\\n${\\phantom{\\Varid{test}_4\\mathrel{=}\\Varid{eval}_E\\;(\\mbox{}}\\phantom{(\\Conid{L}\\;(\\mbox{}}(\\Conid{InE}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{1}))))))}$\n\\end{tabbing}\n\\section{Second Try Plus Multiplication}\n\nSo what's the point?  Duponcheel has taken a pretty simple interpreter\nand obfuscated it to give us an interpreter that uses what will become\nfixed point types.  To demonstrate the point, we'll extend the Second\nTry interpreter to include a new term that performs multiplication.\nAlthough all the code is repeated here, it is surprising how little is\nmodified.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{module}\\;\\Conid{SecondTryPlus}\\;\\mathbf{where}}$\n\\end{tabbing}\nThe definitions for \\ensuremath{\\Varid{E}_1} and \\ensuremath{\\Varid{E}_2} are unchanged.  A new, separate\ndefinition is added for \\ensuremath{\\Varid{E}_3} to represent multiplication terms:\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{data}\\;\\Varid{E}_1\\;\\Varid{x}}$\\\\\n${\\hskip2.00em\\relax\\mathrel{=}\\Conid{Num}\\;\\Conid{Int}}$\\\\\n${\\hskip2.00em\\relax\\mid \\Conid{Add}\\;\\Varid{x}\\;\\Varid{x}}$\\\\\n${\\hskip2.00em\\relax\\phantom{\\mid \\mbox{}}\\mathbf{deriving}\\;(\\Conid{Eq},\\Conid{Show})}$\\\\\n${}$\\\\\n${\\mathbf{data}\\;\\Varid{E}_2\\;\\Varid{x}\\mathrel{=}\\Conid{Dvd}\\;\\Varid{x}\\;\\Varid{x}\\;\\mathbf{deriving}\\;(\\Conid{Eq},\\Conid{Show})}$\\\\\n${}$\\\\\n${\\mathbf{data}\\;\\Varid{E}_3\\;\\Varid{x}\\mathrel{=}\\Conid{Mul}\\;\\Varid{x}\\;\\Varid{x}\\;\\mathbf{deriving}\\;(\\Conid{Eq},\\Conid{Show})}$\n\\end{tabbing}\nThe definitions for \\ensuremath{\\Varid{Expr}_1} and \\ensuremath{\\Varid{Expr}_2} are unchanged.  A new\ndefinition for \\ensuremath{\\Varid{Expr}_3} representing multiplication is added.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{data}\\;\\Varid{Expr}_1\\mathrel{=}\\Conid{In1}\\;(\\Varid{E}_1\\;\\Varid{Expr}_1)\\;\\mathbf{deriving}\\;(\\Conid{Eq},\\Conid{Show})}$\\\\\n${}$\\\\\n${\\mathbf{data}\\;\\Varid{Expr}_2\\mathrel{=}\\Conid{In2}\\;(\\Varid{E}_2\\;\\Varid{Expr}_2)\\;\\mathbf{deriving}\\;(\\Conid{Eq},\\Conid{Show})}$\\\\\n${}$\\\\\n${\\mathbf{data}\\;\\Varid{Expr}_3\\mathrel{=}\\Conid{In3}\\;(\\Varid{E}_3\\;\\Varid{Expr}_3)\\;\\mathbf{deriving}\\;(\\Conid{Eq},\\Conid{Show})}$\n\\end{tabbing}\nSemantic functions also remain unchanged.  A function for\nmultiplication is added:\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\Varid{num}\\mathrel{=}\\Varid{id}\\mbox{\\qquad-{}-  Define semantics of num}}$\\\\\n${\\Varid{add}\\;\\Varid{x}\\;\\Varid{y}\\mathrel{=}\\Varid{x}\\mathbin{+}\\Varid{y}\\mbox{\\qquad-{}-  Define semantics of add}}$\\\\\n${\\Varid{dvd}\\;\\Varid{x}\\;\\Varid{y}\\mathrel{=}\\mathbf{if}\\;\\Varid{y}\\equiv \\mathrm{0}\\mbox{\\qquad-{}-  Define semantics of divide}}$\\\\\n${\\phantom{\\Varid{dvd}\\;\\Varid{x}\\;\\Varid{y}\\mathrel{=}\\mbox{}}\\mathbf{then}\\;\\Varid{error}\\;\\text{\\tt \\char34 Divide~by~zero\\char34}}$\\\\\n${\\phantom{\\Varid{dvd}\\;\\Varid{x}\\;\\Varid{y}\\mathrel{=}\\mbox{}}\\mathbf{else}\\;\\Varid{x}\\mathbin{\\Varid{`div`}}\\Varid{y}}$\\\\\n${\\Varid{mul}\\;\\Varid{x}\\;\\Varid{y}\\mathrel{=}\\Varid{x}\\mathbin{*}\\Varid{y}\\mbox{\\qquad-{}-  Define semantics of times}}$\n\\end{tabbing}\nThe original \\ensuremath{\\Varid{map}} and \\ensuremath{\\Varid{\\phi}} functions again remain unmodified.\n\\ensuremath{\\Varid{map3}} and \\ensuremath{\\Varid{\\phi_3}} are added for multiplication operations.  \\ensuremath{\\Varid{eval}_3} is\nalso added to show that we can build an interpreter separately for\nmultiplication.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\Varid{map1}\\mathbin{::}(\\Varid{x}\\to \\Varid{y})\\to (\\Varid{E}_1\\;\\Varid{x}\\to \\Varid{E}_1\\;\\Varid{y})}$\\\\\n${\\Varid{map1}\\;\\Varid{g}\\;(\\Conid{Num}\\;\\Varid{n})\\mathrel{=}\\Conid{Num}\\;\\Varid{n}}$\\\\\n${\\Varid{map1}\\;\\Varid{g}\\;(\\Conid{Add}\\;\\Varid{e}\\;\\Varid{f})\\mathrel{=}(\\Conid{Add}\\;(\\Varid{g}\\;\\Varid{e})\\;(\\Varid{g}\\;\\Varid{f}))}$\\\\\n${}$\\\\\n${\\Varid{map2}\\mathbin{::}(\\Varid{x}\\to \\Varid{y})\\to (\\Varid{E}_2\\;\\Varid{x}\\to \\Varid{E}_2\\;\\Varid{y})}$\\\\\n${\\Varid{map2}\\;\\Varid{g}\\;(\\Conid{Dvd}\\;\\Varid{e}\\;\\Varid{f})\\mathrel{=}(\\Conid{Dvd}\\;(\\Varid{g}\\;\\Varid{e})\\;(\\Varid{g}\\;\\Varid{f}))}$\\\\\n${}$\\\\\n${\\Varid{map3}\\mathbin{::}(\\Varid{x}\\to \\Varid{y})\\to (\\Varid{E}_3\\;\\Varid{x}\\to \\Varid{E}_3\\;\\Varid{y})}$\\\\\n${\\Varid{map3}\\;\\Varid{g}\\;(\\Conid{Mul}\\;\\Varid{e}\\;\\Varid{f})\\mathrel{=}(\\Conid{Mul}\\;(\\Varid{g}\\;\\Varid{e})\\;(\\Varid{g}\\;\\Varid{f}))}$\\\\\n${}$\\\\\n${\\Varid{\\phi_1}\\mathbin{::}\\Varid{E}_1\\;\\Conid{Int}\\to \\Conid{Int}}$\\\\\n${\\Varid{\\phi_1}\\;(\\Conid{Num}\\;\\Varid{n})\\mathrel{=}\\Varid{num}\\;\\Varid{n}}$\\\\\n${\\Varid{\\phi_1}\\;(\\Conid{Add}\\;\\Varid{e}\\;\\Varid{f})\\mathrel{=}\\Varid{e}\\mathbin{`\\Varid{add}`}\\Varid{f}}$\\\\\n${}$\\\\\n${\\Varid{\\phi_2}\\mathbin{::}\\Varid{E}_2\\;\\Conid{Int}\\to \\Conid{Int}}$\\\\\n${\\Varid{\\phi_2}\\;(\\Conid{Dvd}\\;\\Varid{e}\\;\\Varid{f})\\mathrel{=}\\Varid{e}\\mathbin{`\\Varid{dvd}`}\\Varid{f}}$\\\\\n${}$\\\\\n${\\Varid{\\phi_3}\\mathbin{::}\\Varid{E}_3\\;\\Conid{Int}\\to \\Conid{Int}}$\\\\\n${\\Varid{\\phi_3}\\;(\\Conid{Mul}\\;\\Varid{e}\\;\\Varid{f})\\mathrel{=}\\Varid{e}\\mathbin{`\\Varid{mul}`}\\Varid{f}}$\\\\\n${}$\\\\\n${\\Varid{eval}_1\\mathbin{::}\\Varid{Expr}_1\\to \\Conid{Int}}$\\\\\n${\\Varid{eval}_1\\;(\\Conid{In1}\\;\\Varid{e1})\\mathrel{=}\\Varid{\\phi_1}\\;(\\Varid{map1}\\;\\Varid{eval}_1\\;\\Varid{e1})}$\\\\\n${}$\\\\\n${\\Varid{eval}_2\\mathbin{::}\\Varid{Expr}_2\\to \\Conid{Int}}$\\\\\n${\\Varid{eval}_2\\;(\\Conid{In2}\\;\\Varid{e2})\\mathrel{=}\\Varid{\\phi_2}\\;(\\Varid{map2}\\;\\Varid{eval}_2\\;\\Varid{e2})}$\\\\\n${}$\\\\\n${\\Varid{eval}_3\\mathbin{::}\\Varid{Expr}_3\\to \\Conid{Int}}$\\\\\n${\\Varid{eval}_3\\;(\\Conid{In3}\\;\\Varid{e3})\\mathrel{=}\\Varid{\\phi_3}\\;(\\Varid{map3}\\;\\Varid{eval}_3\\;\\Varid{e3})}$\n\\end{tabbing}\nThe definition for sum does not change.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{data}\\;\\Conid{Sum}\\;\\Varid{x}\\;\\Varid{y}\\mathrel{=}\\Conid{L}\\;\\Varid{x}\\mid \\Conid{R}\\;\\Varid{y}\\;\\mathbf{deriving}\\;(\\Conid{Show},\\Conid{Eq})}$\\\\\n${}$\\\\\n${(\\mathbin{<+>})\\mathbin{::}(\\Varid{x}\\to \\Varid{z})\\to (\\Varid{y}\\to \\Varid{z})\\to (\\Conid{Sum}\\;\\Varid{x}\\;\\Varid{y}\\to \\Varid{z})}$\\\\\n${\\Varid{l}\\mathbin{<+>}\\Varid{r}\\mathrel{=}\\lambda \\Varid{s}\\to \\mathbf{case}\\;\\Varid{s}\\;\\mathbf{of}}$\\\\\n${\\phantom{\\Varid{l}\\mathbin{<+>}\\Varid{r}\\mathrel{=}\\lambda \\Varid{s}\\to \\mathbf{case}\\;\\Varid{s}\\;\\mbox{}}\\Conid{L}\\;\\Varid{x}\\to \\Varid{l}\\;\\Varid{x}}$\\\\\n${\\phantom{\\Varid{l}\\mathbin{<+>}\\Varid{r}\\mathrel{=}\\lambda \\Varid{s}\\to \\mathbf{case}\\;\\Varid{s}\\;\\mbox{}}\\Conid{R}\\;\\Varid{x}\\to \\Varid{r}\\;\\Varid{x}}$\n\\end{tabbing}\nAll we have done to this point is define an interpreter for\nmultiplication operations by defining \\ensuremath{\\Varid{map}}, \\ensuremath{\\Varid{\\phi}} and \\ensuremath{\\Varid{eval}} for the\nnew abstract syntax.  None of the previous definitions have been\nmodified in any way.  We will now integrate the multiplication syntax\ninto the abstract syntax for the entire language and integrate the\ninterpreters.\n\nFirst, define a type shorthand that adds E3 to the expression.\nEffectively, the abstract syntax for expressions becomes:\n\n\\begin{alltt}\n  (Sum multiplication (Sum division addition)) \n\\end{alltt}\n\nThe \\ensuremath{\\Conid{Expr}} data structure does not change.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{type}\\;\\Conid{E}\\;\\Varid{x}\\mathrel{=}\\Conid{Sum}\\;(\\Varid{E}_3\\;\\Varid{x})\\;(\\Conid{Sum}\\;(\\Varid{E}_1\\;\\Varid{x})\\;(\\Varid{E}_2\\;\\Varid{x}))}$\\\\\n${}$\\\\\n${\\mathbf{data}\\;\\Conid{Expr}\\mathrel{=}\\Conid{InE}\\;(\\Conid{E}\\;\\Conid{Expr})}$\n\\end{tabbing}\n\\ensuremath{\\Varid{map}_E} uses the sum composition operator to map an operation across\nthe entire expression abstract syntax.  The signature does not change.\nThe function body rebuilds the expression around the application of\nmap to each possible expression type.  Note the use of \\ensuremath{\\Conid{R}} and \\ensuremath{\\Conid{L}} to\nbuild what is in effect a tree containing possible expressions.  Any\nnumber of expressions can be added in this way.  \\ensuremath{\\Varid{\\phi}_E} is similarly\nmodified and \\ensuremath{\\Varid{eval}_E} remains unchanged.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\Varid{map}_E\\mathbin{::}(\\Varid{x}\\to \\Varid{y})\\to (\\Conid{E}\\;\\Varid{x}\\to \\Conid{E}\\;\\Varid{y})}$\\\\\n${\\Varid{map}_E\\;\\Varid{g}\\mathrel{=}(\\Conid{L}\\mathbin{\\circ}\\Varid{map3}\\;\\Varid{g})\\mathbin{<+>}((\\Conid{R}\\mathbin{\\circ}\\Conid{L}\\mathbin{\\circ}\\Varid{map1}\\;\\Varid{g})\\mathbin{<+>}(\\Conid{R}\\mathbin{\\circ}\\Conid{R}\\mathbin{\\circ}\\Varid{map2}\\;\\Varid{g}))}$\\\\\n${}$\\\\\n${\\Varid{\\phi}_E\\mathbin{::}\\Conid{E}\\;\\Conid{Int}\\to \\Conid{Int}}$\\\\\n${\\Varid{\\phi}_E\\mathrel{=}\\Varid{\\phi_3}\\mathbin{<+>}(\\Varid{\\phi_1}\\mathbin{<+>}\\Varid{\\phi_2})}$\\\\\n${}$\\\\\n${\\Varid{eval}_E\\mathbin{::}\\Conid{Expr}\\to \\Conid{Int}}$\\\\\n${\\Varid{eval}_E\\;(\\Conid{InE}\\;\\Varid{e})\\mathrel{=}\\Varid{\\phi}_E\\;(\\Varid{map}_E\\;\\Varid{eval}_E\\;\\Varid{e})}$\n\\end{tabbing}\nFollowing are more examples the integrate multiplication.  Note how\n\\ensuremath{\\Conid{R}} and \\ensuremath{\\Conid{L}} must be used together to construct some terms.  This is\npainful without a concrete syntax to compile from, but simple when\nwriting compilers that automatically generate structures.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mbox{\\qquad-{}-  Return the value 1}}$\\\\\n${\\Varid{test}_0\\mathrel{=}\\Varid{eval}_E\\;(\\Conid{InE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{1}))))}$\\\\\n${}$\\\\\n${\\mbox{\\qquad-{}-  Add 1 and 1}}$\\\\\n${\\Varid{test}_1\\mathrel{=}\\Varid{eval}_E\\;(\\Conid{InE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\Conid{Add}\\;(\\Conid{InE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{1}))))\\;(\\Conid{InE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{1}))))))))}$\\\\\n${}$\\\\\n${\\mbox{\\qquad-{}-  Divide 1 by 1}}$\\\\\n${\\Varid{test}_2\\mathrel{=}\\Varid{eval}_E\\;(\\Conid{InE}\\;(\\Conid{R}\\;(\\Conid{R}\\;(\\Conid{Dvd}\\;(\\Conid{InE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{1}))))\\;(\\Conid{InE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{1}))))))))}$\\\\\n${}$\\\\\n${\\Varid{test}_3\\mathrel{=}\\Varid{eval}_E\\;(\\Conid{InE}\\;(\\Conid{L}\\;(\\Conid{Mul}\\;(\\Conid{InE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{2}))))\\;(\\Conid{InE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{2})))))))}$\\\\\n${}$\\\\\n${\\Varid{test}_4\\mathrel{=}\\Varid{eval}_E\\;(\\Conid{InE}\\;(\\Conid{R}\\;(\\Conid{R}\\;(\\Conid{Dvd}\\;(\\Conid{InE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{1}))))\\;(\\Conid{InE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{1}))))))))}$\n\\end{tabbing}\nNow that we've done it the hard way, let's make things easier by\ndefining names for operators and operands.  Define some useful\nvariables and functions that provide a kind of ad hoc syntax that we'll use\nto define expressions.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\Varid{num1}\\mathrel{=}(\\Conid{InE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{1}))))}$\\\\\n${\\Varid{num2}\\mathrel{=}(\\Conid{InE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{2}))))}$\\\\\n${\\Varid{num3}\\mathrel{=}(\\Conid{InE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{3}))))}$\\\\\n${\\Varid{numx}\\;\\Varid{x}\\mathrel{=}(\\Conid{InE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\Varid{x}))))}$\\\\\n${\\Varid{divide}\\;\\Varid{x}\\;\\Varid{y}\\mathrel{=}(\\Conid{InE}\\;(\\Conid{R}\\;(\\Conid{R}\\;(\\Conid{Dvd}\\;\\Varid{x}\\;\\Varid{y}))))}$\\\\\n${\\Varid{times}\\;\\Varid{x}\\;\\Varid{y}\\mathrel{=}(\\Conid{InE}\\;(\\Conid{L}\\;(\\Conid{Mul}\\;\\Varid{x}\\;\\Varid{y})))}$\\\\\n${\\Varid{plus}\\;\\Varid{x}\\;\\Varid{y}\\mathrel{=}(\\Conid{InE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\Conid{Add}\\;\\Varid{x}\\;\\Varid{y}))))}$\n\\end{tabbing}\nWe can now write expressions that look much more like we think they\nshould.  Use evalE to evaluate the following examples:\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\Varid{test}_5\\mathrel{=}(\\Varid{num2}\\mathbin{`\\Varid{times}`}\\Varid{num3})}$\\\\\n${}$\\\\\n${\\Varid{test}_6\\mathrel{=}(\\Varid{num1}\\mathbin{`\\Varid{plus}`}(\\Varid{num2}\\mathbin{`\\Varid{divide}`}\\Varid{num3}))}$\\\\\n${}$\\\\\n${\\Varid{test}_7\\mathrel{=}(\\Varid{num1}\\mathbin{`\\Varid{plus}`}(\\Varid{num3}\\mathbin{`\\Varid{divide}`}\\Varid{num2}))}$\\\\\n${}$\\\\\n${\\Varid{test}_8\\mathrel{=}(\\Varid{num2}\\mathbin{`\\Varid{times}`}(\\Varid{numx}\\;\\mathrm{100}))}$\\\\\n${}$\\\\\n${\\Varid{test}_9\\mathrel{=}(\\Varid{num2}\\mathbin{`\\Varid{divide}`}(\\Varid{numx}\\;\\mathrm{0}))}$\n\\end{tabbing}\nAny reasonable assessment of this interpreter reveals that to add a\nnew term type to the interpreter, we simply need to define an\ninterpreter for that term type and compose it with those that already\nexist.  Composing the new evaluation function is quite systematic and\nachieved using features of the \\ensuremath{\\Conid{Sum}} type constructor.  No\nmodification is required for existing interpreter modules.  In\naddition to dramatically simplifying interpreter construction,\ndebugging becomes much simpler as the new interpreter can be tested\nand debugged in a modular fashion.\n\\section{Third Try}\n\nThe Third Try from Duponcheel attempts to abstract common structures\nfrom individual interpreters and syntax into a common form.  The\nresult is a parameterized data structure that forms fixed point forms\nin a common, consistent manner.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{module}\\;\\Conid{ThirdTry}\\;\\mathbf{where}}$\n\\end{tabbing}\nAll the \\ensuremath{\\Conid{Expr}} types from \\ensuremath{\\Conid{SecondTry}} share a common form that can be\nabstracted and parameterized as \\ensuremath{\\Conid{Rec}}:\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{data}\\;\\Conid{Rec}\\;\\Varid{f}\\mathrel{=}\\Conid{In}\\;(\\Varid{f}\\;(\\Conid{Rec}\\;\\Varid{f}))}$\n\\end{tabbing}\nThe \\ensuremath{\\Conid{Rec}} type creates a fixed point data type from some element \\ensuremath{\\Varid{f}}.\nNote the constructor \\ensuremath{\\Conid{In}} that accomplishes the same task as \\ensuremath{\\Conid{In1}},\n\\ensuremath{\\Conid{In2}}, and \\ensuremath{\\Conid{InE}} from previous examples.\n\nWe will need to define abstract syntax for each expression type.\nThese definitions do not change from earlier examples, they will\nsimply be packaged differently for the interpreter.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{data}\\;\\Varid{E}_1\\;\\Varid{x}}$\\\\\n${\\hskip2.00em\\relax\\mathrel{=}\\Conid{Num}\\;\\Conid{Int}}$\\\\\n${\\hskip2.00em\\relax\\mid \\Conid{Add}\\;\\Varid{x}\\;\\Varid{x}}$\\\\\n${\\hskip2.00em\\relax\\phantom{\\mid \\mbox{}}\\mathbf{deriving}\\;(\\Conid{Eq},\\Conid{Show})}$\\\\\n${}$\\\\\n${\\mathbf{data}\\;\\Varid{E}_2\\;\\Varid{x}\\mathrel{=}\\Conid{Dvd}\\;\\Varid{x}\\;\\Varid{x}\\;\\mathbf{deriving}\\;(\\Conid{Eq},\\Conid{Show})}$\n\\end{tabbing}\nNow use \\ensuremath{\\Conid{Rec}} to define fixed point types for \\ensuremath{\\Varid{Expr}_1} and \\ensuremath{\\Varid{Expr}_2}.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{type}\\;\\Varid{Expr}_1\\mathrel{=}\\Conid{Rec}\\;\\Varid{E}_1}$\\\\\n${\\mathbf{type}\\;\\Varid{Expr}_2\\mathrel{=}\\Conid{Rec}\\;\\Varid{E}_2}$\n\\end{tabbing}\nThe definitions for semantic functions, \\ensuremath{\\Varid{map}}, \\ensuremath{\\Varid{\\phi}}, and \\ensuremath{\\Varid{eval}}\nfunctions for each expression do not change.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\Varid{num}\\mathrel{=}\\Varid{id}\\mbox{\\qquad-{}-  Num1 Int}}$\\\\\n${\\Varid{add}\\;\\Varid{x}\\;\\Varid{y}\\mathrel{=}\\Varid{x}\\mathbin{+}\\Varid{y}\\mbox{\\qquad-{}-  Add1 Expr1 Expr1}}$\\\\\n${\\Varid{dvd}\\;\\Varid{x}\\;\\Varid{y}\\mathrel{=}\\mathbf{if}\\;\\Varid{y}\\equiv \\mathrm{0}\\;\\mathbf{then}\\;\\Varid{error}\\;\\text{\\tt \\char34 Divide~by~zero\\char34}\\;\\mathbf{else}\\;\\Varid{x}\\mathbin{\\Varid{`div`}}\\Varid{y}}$\\\\\n${}$\\\\\n${\\Varid{map1}\\mathbin{::}(\\Varid{x}\\to \\Varid{y})\\to (\\Varid{E}_1\\;\\Varid{x}\\to \\Varid{E}_1\\;\\Varid{y})}$\\\\\n${\\Varid{map1}\\;\\Varid{g}\\;(\\Conid{Num}\\;\\Varid{n})\\mathrel{=}\\Conid{Num}\\;\\Varid{n}}$\\\\\n${\\Varid{map1}\\;\\Varid{g}\\;(\\Conid{Add}\\;\\Varid{e}\\;\\Varid{f})\\mathrel{=}(\\Conid{Add}\\;(\\Varid{g}\\;\\Varid{e})\\;(\\Varid{g}\\;\\Varid{f}))}$\\\\\n${}$\\\\\n${\\Varid{map2}\\mathbin{::}(\\Varid{x}\\to \\Varid{y})\\to (\\Varid{E}_2\\;\\Varid{x}\\to \\Varid{E}_2\\;\\Varid{y})}$\\\\\n${\\Varid{map2}\\;\\Varid{g}\\;(\\Conid{Dvd}\\;\\Varid{e}\\;\\Varid{f})\\mathrel{=}(\\Conid{Dvd}\\;(\\Varid{g}\\;\\Varid{e})\\;(\\Varid{g}\\;\\Varid{f}))}$\\\\\n${}$\\\\\n${\\Varid{\\phi_1}\\mathbin{::}\\Varid{E}_1\\;\\Conid{Int}\\to \\Conid{Int}}$\\\\\n${\\Varid{\\phi_1}\\;(\\Conid{Num}\\;\\Varid{n})\\mathrel{=}\\Varid{num}\\;\\Varid{n}}$\\\\\n${\\Varid{\\phi_1}\\;(\\Conid{Add}\\;\\Varid{e}\\;\\Varid{f})\\mathrel{=}\\Varid{e}\\mathbin{`\\Varid{add}`}\\Varid{f}}$\\\\\n${}$\\\\\n${\\Varid{\\phi_2}\\mathbin{::}\\Varid{E}_2\\;\\Conid{Int}\\to \\Conid{Int}}$\\\\\n${\\Varid{\\phi_2}\\;(\\Conid{Dvd}\\;\\Varid{e}\\;\\Varid{f})\\mathrel{=}\\Varid{e}\\mathbin{`\\Varid{dvd}`}\\Varid{f}}$\\\\\n${}$\\\\\n${\\Varid{eval}_1\\mathbin{::}\\Varid{Expr}_1\\to \\Conid{Int}}$\\\\\n${\\Varid{eval}_1\\;(\\Conid{In}\\;\\Varid{e1})\\mathrel{=}\\Varid{\\phi_1}\\;(\\Varid{map1}\\;\\Varid{eval}_1\\;\\Varid{e1})}$\\\\\n${}$\\\\\n${\\Varid{eval}_2\\mathbin{::}\\Varid{Expr}_2\\to \\Conid{Int}}$\\\\\n${\\Varid{eval}_2\\;(\\Conid{In}\\;\\Varid{e2})\\mathrel{=}\\Varid{\\phi_2}\\;(\\Varid{map2}\\;\\Varid{eval}_2\\;\\Varid{e2})}$\n\\end{tabbing}\nThe definition of \\ensuremath{\\Conid{Sum}} remains unchanged:\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{data}\\;\\Conid{Sum}\\;\\Varid{x}\\;\\Varid{y}\\mathrel{=}\\Conid{L}\\;\\Varid{x}\\mid \\Conid{R}\\;\\Varid{y}\\;\\mathbf{deriving}\\;(\\Conid{Show},\\Conid{Eq})}$\\\\\n${}$\\\\\n${(\\mathbin{<+>})\\mathbin{::}(\\Varid{x}\\to \\Varid{z})\\to (\\Varid{y}\\to \\Varid{z})\\to (\\Conid{Sum}\\;\\Varid{x}\\;\\Varid{y}\\to \\Varid{z})}$\\\\\n${\\Varid{l}\\mathbin{<+>}\\Varid{r}\\mathrel{=}\\lambda \\Varid{s}\\to \\mathbf{case}\\;\\Varid{s}\\;\\mathbf{of}}$\\\\\n${\\phantom{\\Varid{l}\\mathbin{<+>}\\Varid{r}\\mathrel{=}\\lambda \\Varid{s}\\to \\mathbf{case}\\;\\Varid{s}\\;\\mbox{}}\\Conid{L}\\;\\Varid{x}\\to \\Varid{l}\\;\\Varid{x}}$\\\\\n${\\phantom{\\Varid{l}\\mathbin{<+>}\\Varid{r}\\mathrel{=}\\lambda \\Varid{s}\\to \\mathbf{case}\\;\\Varid{s}\\;\\mbox{}}\\Conid{R}\\;\\Varid{x}\\to \\Varid{r}\\;\\Varid{x}}$\n\\end{tabbing}\nNow the fun begins.  An expression in our language is the sum of the\nexpression for addition and division.  Thus, we use the \\ensuremath{\\Conid{Sum}} type to\ndo our composition.  In Gopher, the \\ensuremath{\\mathbf{type}} constructor behaves\ndifferently than the \\ensuremath{\\mathbf{type}} synonym definition operator in Haskell.\nThus, the definition is altered to use \\ensuremath{\\mathbf{newtype}} requiring the\ninsertion of a new type constructor, \\ensuremath{\\Conid{MkE}}.  In addition, an\nun-constructor is defined to pull data out of \\ensuremath{\\Conid{MkE}}.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{newtype}\\;\\Conid{E}\\;\\Varid{x}\\mathrel{=}\\Conid{MkE}\\;(\\Conid{Sum}\\;(\\Varid{E}_1\\;\\Varid{x})\\;(\\Varid{E}_2\\;\\Varid{x}))}$\\\\\n${}$\\\\\n${\\Varid{unE}\\;(\\Conid{MkE}\\;\\Varid{x})\\mathrel{=}\\Varid{x}}$\n\\end{tabbing}\nThe composite \\ensuremath{\\Conid{Expr}} definition is the fixed point type created from\n\\ensuremath{\\Conid{E}} that we just defined.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{type}\\;\\Conid{Expr}\\mathrel{=}\\Conid{Rec}\\;\\Conid{E}}$\n\\end{tabbing}\nThe map function for the composite expression, \\ensuremath{\\Conid{E}}, is basically the\nsame function with the addition of functions to accommodate the \\ensuremath{\\Conid{MkE}}\nconstructor we had to introduce earlier. Specifically, \\ensuremath{\\Varid{map}_E} must\nfirst extract the expression from the \\ensuremath{\\Conid{MkE}} constructor because the\nindividual map functions aren't aware of the need to package the\nexpression.  Once processed, the expression is repackaged.  Similarly,\n\\ensuremath{\\Varid{\\phi}_E} must un-package its argument.  Because it is making a semantic\nmapping, its result should not be repackaged.  \\ensuremath{\\Varid{eval}_E} does not\nchange.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\Varid{map}_E\\mathbin{::}(\\Varid{x}\\to \\Varid{y})\\to (\\Conid{E}\\;\\Varid{x}\\to \\Conid{E}\\;\\Varid{y})}$\\\\\n${\\Varid{map}_E\\;\\Varid{g}\\mathrel{=}\\Conid{MkE}\\mathbin{\\circ}((\\Conid{L}\\mathbin{\\circ}\\Varid{map1}\\;\\Varid{g})\\mathbin{<+>}(\\Conid{R}\\mathbin{\\circ}\\Varid{map2}\\;\\Varid{g}))\\mathbin{\\circ}\\Varid{unE}}$\\\\\n${}$\\\\\n${\\Varid{\\phi}_E\\mathbin{::}\\Conid{E}\\;\\Conid{Int}\\to \\Conid{Int}}$\\\\\n${\\Varid{\\phi}_E\\mathrel{=}(\\Varid{\\phi_1}\\mathbin{<+>}\\Varid{\\phi_2})\\mathbin{\\circ}\\Varid{unE}}$\\\\\n${}$\\\\\n${\\Varid{eval}_E\\mathbin{::}\\Conid{Expr}\\to \\Conid{Int}}$\\\\\n${\\Varid{eval}_E\\;(\\Conid{In}\\;\\Varid{e})\\mathrel{=}\\Varid{\\phi}_E\\;(\\Varid{map}_E\\;\\Varid{eval}_E\\;\\Varid{e})}$\n\\end{tabbing}\nAgain, some examples to try out.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mbox{\\qquad-{}-  Return the value 1}}$\\\\\n${\\Varid{test}_0\\mathrel{=}\\Varid{eval}_E\\;(\\Conid{In}\\;(\\Conid{MkE}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{1}))))}$\\\\\n${}$\\\\\n${\\mbox{\\qquad-{}-  Add 1 and 1}}$\\\\\n${\\Varid{test}_1\\mathrel{=}\\Varid{eval}_E\\;(\\Conid{In}\\;(\\Conid{MkE}}$\\\\\n${\\phantom{\\Varid{test}_1\\mathrel{=}\\Varid{eval}_E\\;(\\Conid{In}\\;(\\mbox{}}(\\Conid{L}\\;(\\Conid{Add}}$\\\\\n${\\phantom{\\Varid{test}_1\\mathrel{=}\\Varid{eval}_E\\;(\\Conid{In}\\;(\\mbox{}}\\phantom{(\\Conid{L}\\;(\\mbox{}}(\\Conid{In}\\;(\\Conid{MkE}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{1}))))}$\\\\\n${\\phantom{\\Varid{test}_1\\mathrel{=}\\Varid{eval}_E\\;(\\Conid{In}\\;(\\mbox{}}\\phantom{(\\Conid{L}\\;(\\mbox{}}(\\Conid{In}\\;(\\Conid{MkE}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{1}))))))))}$\\\\\n${}$\\\\\n${\\mbox{\\qquad-{}-  Divide 1 by 1}}$\\\\\n${\\Varid{test}_2\\mathrel{=}\\Varid{eval}_E\\;(\\Conid{In}\\;(\\Conid{MkE}}$\\\\\n${\\phantom{\\Varid{test}_2\\mathrel{=}\\Varid{eval}_E\\;(\\Conid{In}\\;(\\mbox{}}(\\Conid{R}\\;(\\Conid{Dvd}}$\\\\\n${\\phantom{\\Varid{test}_2\\mathrel{=}\\Varid{eval}_E\\;(\\Conid{In}\\;(\\mbox{}}\\phantom{(\\Conid{R}\\;(\\mbox{}}(\\Conid{In}\\;(\\Conid{MkE}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{1}))))}$\\\\\n${\\phantom{\\Varid{test}_2\\mathrel{=}\\Varid{eval}_E\\;(\\Conid{In}\\;(\\mbox{}}\\phantom{(\\Conid{R}\\;(\\mbox{}}(\\Conid{In}\\;(\\Conid{MkE}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{1}))))))))}$\n\\end{tabbing}\n\\section{Third Try Plus Multiplication}\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{module}\\;\\Conid{ThirdTryPlus}\\;\\mathbf{where}}$\n\\end{tabbing}\nThe \\ensuremath{\\Conid{Rec}} type remains unchanged.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{data}\\;\\Conid{Rec}\\;\\Varid{f}\\mathrel{=}\\Conid{In}\\;(\\Varid{f}\\;(\\Conid{Rec}\\;\\Varid{f}))}$\n\\end{tabbing}\nAbstract syntax is added for multiplication.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{data}\\;\\Varid{E}_1\\;\\Varid{x}}$\\\\\n${\\hskip2.00em\\relax\\mathrel{=}\\Conid{Num}\\;\\Conid{Int}}$\\\\\n${\\hskip2.00em\\relax\\mid \\Conid{Add}\\;\\Varid{x}\\;\\Varid{x}}$\\\\\n${\\hskip2.00em\\relax\\phantom{\\mid \\mbox{}}\\mathbf{deriving}\\;(\\Conid{Eq},\\Conid{Show})}$\\\\\n${}$\\\\\n${\\mathbf{data}\\;\\Varid{E}_2\\;\\Varid{x}\\mathrel{=}\\Conid{Dvd}\\;\\Varid{x}\\;\\Varid{x}\\;\\mathbf{deriving}\\;(\\Conid{Eq},\\Conid{Show})}$\\\\\n${}$\\\\\n${\\mathbf{data}\\;\\Varid{E}_3\\;\\Varid{x}\\mathrel{=}\\Conid{Mul}\\;\\Varid{x}\\;\\Varid{x}\\;\\mathbf{deriving}\\;(\\Conid{Eq},\\Conid{Show})}$\n\\end{tabbing}\nAn expression type is added for multiplication using \\ensuremath{\\Conid{Rec}}.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{type}\\;\\Varid{Expr}_1\\mathrel{=}\\Conid{Rec}\\;\\Varid{E}_1}$\\\\\n${\\mathbf{type}\\;\\Varid{Expr}_2\\mathrel{=}\\Conid{Rec}\\;\\Varid{E}_2}$\\\\\n${\\mathbf{type}\\;\\Varid{Expr}_3\\mathrel{=}\\Conid{Rec}\\;\\Varid{E}_3}$\n\\end{tabbing}\nThe definitions for semantic functions, \\ensuremath{\\Varid{map}}, \\ensuremath{\\Varid{\\phi}}, and \\ensuremath{\\Varid{eval}}\nfunctions for each expression do not change.  New instances are added\nfor multiplication.  These are identical to those added for Second Try\nPlus Multiplication.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\Varid{num}\\mathrel{=}\\Varid{id}\\mbox{\\qquad-{}-  Num1 Int}}$\\\\\n${\\Varid{add}\\;\\Varid{x}\\;\\Varid{y}\\mathrel{=}\\Varid{x}\\mathbin{+}\\Varid{y}\\mbox{\\qquad-{}-  Add1 Expr1 Expr1}}$\\\\\n${\\Varid{dvd}\\;\\Varid{x}\\;\\Varid{y}\\mathrel{=}\\mathbf{if}\\;\\Varid{y}\\equiv \\mathrm{0}\\;\\mathbf{then}\\;\\Varid{error}\\;\\text{\\tt \\char34 Divide~by~zero\\char34}\\;\\mathbf{else}\\;\\Varid{x}\\mathbin{\\Varid{`div`}}\\Varid{y}}$\\\\\n${\\Varid{mul}\\;\\Varid{x}\\;\\Varid{y}\\mathrel{=}\\Varid{x}\\mathbin{*}\\Varid{y}\\mbox{\\qquad-{}-  Define semantics of times}}$\\\\\n${}$\\\\\n${\\Varid{map1}\\mathbin{::}(\\Varid{x}\\to \\Varid{y})\\to (\\Varid{E}_1\\;\\Varid{x}\\to \\Varid{E}_1\\;\\Varid{y})}$\\\\\n${\\Varid{map1}\\;\\Varid{g}\\;(\\Conid{Num}\\;\\Varid{n})\\mathrel{=}\\Conid{Num}\\;\\Varid{n}}$\\\\\n${\\Varid{map1}\\;\\Varid{g}\\;(\\Conid{Add}\\;\\Varid{e}\\;\\Varid{f})\\mathrel{=}(\\Conid{Add}\\;(\\Varid{g}\\;\\Varid{e})\\;(\\Varid{g}\\;\\Varid{f}))}$\\\\\n${}$\\\\\n${\\Varid{map2}\\mathbin{::}(\\Varid{x}\\to \\Varid{y})\\to (\\Varid{E}_2\\;\\Varid{x}\\to \\Varid{E}_2\\;\\Varid{y})}$\\\\\n${\\Varid{map2}\\;\\Varid{g}\\;(\\Conid{Dvd}\\;\\Varid{e}\\;\\Varid{f})\\mathrel{=}(\\Conid{Dvd}\\;(\\Varid{g}\\;\\Varid{e})\\;(\\Varid{g}\\;\\Varid{f}))}$\\\\\n${}$\\\\\n${\\Varid{map3}\\mathbin{::}(\\Varid{x}\\to \\Varid{y})\\to (\\Varid{E}_3\\;\\Varid{x}\\to \\Varid{E}_3\\;\\Varid{y})}$\\\\\n${\\Varid{map3}\\;\\Varid{g}\\;(\\Conid{Mul}\\;\\Varid{e}\\;\\Varid{f})\\mathrel{=}(\\Conid{Mul}\\;(\\Varid{g}\\;\\Varid{e})\\;(\\Varid{g}\\;\\Varid{f}))}$\\\\\n${}$\\\\\n${\\Varid{\\phi_1}\\mathbin{::}\\Varid{E}_1\\;\\Conid{Int}\\to \\Conid{Int}}$\\\\\n${\\Varid{\\phi_1}\\;(\\Conid{Num}\\;\\Varid{n})\\mathrel{=}\\Varid{num}\\;\\Varid{n}}$\\\\\n${\\Varid{\\phi_1}\\;(\\Conid{Add}\\;\\Varid{e}\\;\\Varid{f})\\mathrel{=}\\Varid{e}\\mathbin{`\\Varid{add}`}\\Varid{f}}$\\\\\n${}$\\\\\n${\\Varid{\\phi_2}\\mathbin{::}\\Varid{E}_2\\;\\Conid{Int}\\to \\Conid{Int}}$\\\\\n${\\Varid{\\phi_2}\\;(\\Conid{Dvd}\\;\\Varid{e}\\;\\Varid{f})\\mathrel{=}\\Varid{e}\\mathbin{`\\Varid{dvd}`}\\Varid{f}}$\\\\\n${}$\\\\\n${\\Varid{\\phi_3}\\mathbin{::}\\Varid{E}_3\\;\\Conid{Int}\\to \\Conid{Int}}$\\\\\n${\\Varid{\\phi_3}\\;(\\Conid{Mul}\\;\\Varid{e}\\;\\Varid{f})\\mathrel{=}\\Varid{e}\\mathbin{`\\Varid{mul}`}\\Varid{f}}$\\\\\n${}$\\\\\n${\\Varid{eval}_1\\mathbin{::}\\Varid{Expr}_1\\to \\Conid{Int}}$\\\\\n${\\Varid{eval}_1\\;(\\Conid{In}\\;\\Varid{e1})\\mathrel{=}\\Varid{\\phi_1}\\;(\\Varid{map1}\\;\\Varid{eval}_1\\;\\Varid{e1})}$\\\\\n${}$\\\\\n${\\Varid{eval}_2\\mathbin{::}\\Varid{Expr}_2\\to \\Conid{Int}}$\\\\\n${\\Varid{eval}_2\\;(\\Conid{In}\\;\\Varid{e2})\\mathrel{=}\\Varid{\\phi_2}\\;(\\Varid{map2}\\;\\Varid{eval}_2\\;\\Varid{e2})}$\\\\\n${}$\\\\\n${\\Varid{eval}_3\\mathbin{::}\\Varid{Expr}_3\\to \\Conid{Int}}$\\\\\n${\\Varid{eval}_3\\;(\\Conid{In}\\;\\Varid{e3})\\mathrel{=}\\Varid{\\phi_3}\\;(\\Varid{map3}\\;\\Varid{eval}_3\\;\\Varid{e3})}$\n\\end{tabbing}\nThe definition of \\ensuremath{\\Conid{Sum}} remains unchanged:\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{data}\\;\\Conid{Sum}\\;\\Varid{x}\\;\\Varid{y}\\mathrel{=}\\Conid{L}\\;\\Varid{x}\\mid \\Conid{R}\\;\\Varid{y}\\;\\mathbf{deriving}\\;(\\Conid{Show},\\Conid{Eq})}$\\\\\n${}$\\\\\n${(\\mathbin{<+>})\\mathbin{::}(\\Varid{x}\\to \\Varid{z})\\to (\\Varid{y}\\to \\Varid{z})\\to (\\Conid{Sum}\\;\\Varid{x}\\;\\Varid{y}\\to \\Varid{z})}$\\\\\n${\\Varid{l}\\mathbin{<+>}\\Varid{r}\\mathrel{=}\\lambda \\Varid{s}\\to \\mathbf{case}\\;\\Varid{s}\\;\\mathbf{of}}$\\\\\n${\\phantom{\\Varid{l}\\mathbin{<+>}\\Varid{r}\\mathrel{=}\\lambda \\Varid{s}\\to \\mathbf{case}\\;\\Varid{s}\\;\\mbox{}}\\Conid{L}\\;\\Varid{x}\\to \\Varid{l}\\;\\Varid{x}}$\\\\\n${\\phantom{\\Varid{l}\\mathbin{<+>}\\Varid{r}\\mathrel{=}\\lambda \\Varid{s}\\to \\mathbf{case}\\;\\Varid{s}\\;\\mbox{}}\\Conid{R}\\;\\Varid{x}\\to \\Varid{r}\\;\\Varid{x}}$\n\\end{tabbing}\nThe changes to the composite structure mimic those done to extend try.\nNothing else changes.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{newtype}\\;\\Conid{E}\\;\\Varid{x}\\mathrel{=}\\Conid{MkE}\\;(\\Conid{Sum}\\;(\\Varid{E}_3\\;\\Varid{x})\\;(\\Conid{Sum}\\;(\\Varid{E}_1\\;\\Varid{x})\\;(\\Varid{E}_2\\;\\Varid{x})))}$\\\\\n${}$\\\\\n${\\Varid{unE}\\;(\\Conid{MkE}\\;\\Varid{x})\\mathrel{=}\\Varid{x}}$\\\\\n${}$\\\\\n${\\mathbf{type}\\;\\Conid{Expr}\\mathrel{=}\\Conid{Rec}\\;\\Conid{E}}$\\\\\n${}$\\\\\n${\\Varid{map}_E\\mathbin{::}(\\Varid{x}\\to \\Varid{y})\\to (\\Conid{E}\\;\\Varid{x}\\to \\Conid{E}\\;\\Varid{y})}$\\\\\n${\\Varid{map}_E\\;\\Varid{g}}$\\\\\n${\\hskip2.00em\\relax\\mathrel{=}\\Conid{MkE}\\mathbin{\\circ}((\\Conid{L}\\mathbin{\\circ}\\Varid{map3}\\;\\Varid{g})\\mathbin{<+>}((\\Conid{R}\\mathbin{\\circ}\\Conid{L}\\mathbin{\\circ}\\Varid{map1}\\;\\Varid{g})\\mathbin{<+>}(\\Conid{R}\\mathbin{\\circ}\\Conid{R}\\mathbin{\\circ}\\Varid{map2}\\;\\Varid{g})))\\mathbin{\\circ}\\Varid{unE}}$\\\\\n${}$\\\\\n${\\Varid{\\phi}_E\\mathbin{::}\\Conid{E}\\;\\Conid{Int}\\to \\Conid{Int}}$\\\\\n${\\Varid{\\phi}_E\\mathrel{=}(\\Varid{\\phi_3}\\mathbin{<+>}(\\Varid{\\phi_1}\\mathbin{<+>}\\Varid{\\phi_2}))\\mathbin{\\circ}\\Varid{unE}}$\\\\\n${}$\\\\\n${\\Varid{eval}_E\\mathbin{::}\\Conid{Expr}\\to \\Conid{Int}}$\\\\\n${\\Varid{eval}_E\\;(\\Conid{In}\\;\\Varid{e})\\mathrel{=}\\Varid{\\phi}_E\\;(\\Varid{map}_E\\;\\Varid{eval}_E\\;\\Varid{e})}$\n\\end{tabbing}\nAgain, some examples to try out.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mbox{\\qquad-{}-  Return the value 1}}$\\\\\n${\\Varid{test}_0\\mathrel{=}\\Varid{eval}_E\\;(\\Conid{In}\\;(\\Conid{MkE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{1})))))}$\\\\\n${}$\\\\\n${\\mbox{\\qquad-{}-  Add 1 and 1}}$\\\\\n${\\Varid{test}_1\\mathrel{=}\\Varid{eval}_E\\;(\\Conid{In}}$\\\\\n${\\phantom{\\Varid{test}_1\\mathrel{=}\\Varid{eval}_E\\;(\\mbox{}}(\\Conid{MkE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\Conid{Add}}$\\\\\n${\\phantom{\\Varid{test}_1\\mathrel{=}\\Varid{eval}_E\\;(\\mbox{}}\\phantom{(\\Conid{MkE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\mbox{}}(\\Conid{In}\\;(\\Conid{MkE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{1})))))}$\\\\\n${\\phantom{\\Varid{test}_1\\mathrel{=}\\Varid{eval}_E\\;(\\mbox{}}\\phantom{(\\Conid{MkE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\mbox{}}(\\Conid{In}\\;(\\Conid{MkE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{1}))))))))))}$\\\\\n${}$\\\\\n${\\mbox{\\qquad-{}-  Divide 1 by 1}}$\\\\\n${\\Varid{test}_2\\mathrel{=}\\Varid{eval}_E\\;(\\Conid{In}}$\\\\\n${\\phantom{\\Varid{test}_2\\mathrel{=}\\Varid{eval}_E\\;(\\mbox{}}(\\Conid{MkE}\\;(\\Conid{R}\\;(\\Conid{R}\\;(\\Conid{Dvd}}$\\\\\n${\\phantom{\\Varid{test}_2\\mathrel{=}\\Varid{eval}_E\\;(\\mbox{}}\\phantom{(\\Conid{MkE}\\;(\\Conid{R}\\;(\\Conid{R}\\;(\\mbox{}}(\\Conid{In}\\;(\\Conid{MkE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{1})))))}$\\\\\n${\\phantom{\\Varid{test}_2\\mathrel{=}\\Varid{eval}_E\\;(\\mbox{}}\\phantom{(\\Conid{MkE}\\;(\\Conid{R}\\;(\\Conid{R}\\;(\\mbox{}}(\\Conid{In}\\;(\\Conid{MkE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{1}))))))))))}$\\\\\n${}$\\\\\n${\\Varid{test}_3\\mathrel{=}\\Varid{eval}_E\\;(\\Conid{In}\\;(\\Conid{MkE}\\;(\\Conid{L}\\;(\\Conid{Mul}}$\\\\\n${\\phantom{\\Varid{test}_3\\mathrel{=}\\Varid{eval}_E\\;(\\Conid{In}\\;(\\Conid{MkE}\\;(\\Conid{L}\\;(\\mbox{}}(\\Conid{In}\\;(\\Conid{MkE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{2})))))}$\\\\\n${\\phantom{\\Varid{test}_3\\mathrel{=}\\Varid{eval}_E\\;(\\Conid{In}\\;(\\Conid{MkE}\\;(\\Conid{L}\\;(\\mbox{}}(\\Conid{In}\\;(\\Conid{MkE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{2})))))))))}$\\\\\n${}$\\\\\n${\\Varid{test}_4\\mathrel{=}\\Varid{eval}_E\\;(\\Conid{In}\\;(\\Conid{MkE}\\;(\\Conid{R}\\;(\\Conid{R}\\;(\\Conid{Dvd}}$\\\\\n${\\phantom{\\Varid{test}_4\\mathrel{=}\\Varid{eval}_E\\;(\\Conid{In}\\;(\\Conid{MkE}\\;(\\Conid{R}\\;(\\Conid{R}\\;(\\mbox{}}(\\Conid{In}\\;(\\Conid{MkE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{1})))))}$\\\\\n${\\phantom{\\Varid{test}_4\\mathrel{=}\\Varid{eval}_E\\;(\\Conid{In}\\;(\\Conid{MkE}\\;(\\Conid{R}\\;(\\Conid{R}\\;(\\mbox{}}(\\Conid{In}\\;(\\Conid{MkE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{1}))))))))))}$\n\\end{tabbing}\nAgain, adding some trivial syntax:\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\Varid{num1}\\mathrel{=}(\\Conid{In}\\;(\\Conid{MkE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{1})))))}$\\\\\n${\\Varid{num2}\\mathrel{=}(\\Conid{In}\\;(\\Conid{MkE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{2})))))}$\\\\\n${\\Varid{num3}\\mathrel{=}(\\Conid{In}\\;(\\Conid{MkE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\mathrm{3})))))}$\\\\\n${\\Varid{numx}\\;\\Varid{x}\\mathrel{=}(\\Conid{In}\\;(\\Conid{MkE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\Conid{Num}\\;\\Varid{x})))))}$\\\\\n${\\Varid{divide}\\;\\Varid{x}\\;\\Varid{y}\\mathrel{=}(\\Conid{In}\\;(\\Conid{MkE}\\;(\\Conid{R}\\;(\\Conid{R}\\;(\\Conid{Dvd}\\;\\Varid{x}\\;\\Varid{y})))))}$\\\\\n${\\Varid{times}\\;\\Varid{x}\\;\\Varid{y}\\mathrel{=}(\\Conid{In}\\;(\\Conid{MkE}\\;(\\Conid{L}\\;(\\Conid{Mul}\\;\\Varid{x}\\;\\Varid{y}))))}$\\\\\n${\\Varid{plus}\\;\\Varid{x}\\;\\Varid{y}\\mathrel{=}(\\Conid{In}\\;(\\Conid{MkE}\\;(\\Conid{R}\\;(\\Conid{L}\\;(\\Conid{Add}\\;\\Varid{x}\\;\\Varid{y})))))}$\\\\\n${}$\\\\\n${\\Varid{test}_5\\mathrel{=}(\\Varid{num2}\\mathbin{`\\Varid{times}`}\\Varid{num3})}$\\\\\n${}$\\\\\n${\\Varid{test}_6\\mathrel{=}(\\Varid{num1}\\mathbin{`\\Varid{plus}`}(\\Varid{num2}\\mathbin{`\\Varid{divide}`}\\Varid{num3}))}$\\\\\n${}$\\\\\n${\\Varid{test}_7\\mathrel{=}(\\Varid{num1}\\mathbin{`\\Varid{plus}`}(\\Varid{num3}\\mathbin{`\\Varid{divide}`}\\Varid{num2}))}$\\\\\n${}$\\\\\n${\\Varid{test}_8\\mathrel{=}(\\Varid{num2}\\mathbin{`\\Varid{times}`}(\\Varid{numx}\\;\\mathrm{100}))}$\\\\\n${}$\\\\\n${\\Varid{test}_9\\mathrel{=}(\\Varid{num2}\\mathbin{`\\Varid{divide}`}(\\Varid{numx}\\;\\mathrm{0}))}$\n\\end{tabbing}\nOnce again, we find that extending the interpreter is reasonably easy\nby defining a new interpreter for the new abstract syntax constructs.\nThe \\ensuremath{\\Conid{Rec}} type simplifies this process somewhat and makes the common\nstructure of terms clear.  Furthermore, in unequivocally shows that\nthe expression data types are in fact fixed point data types.\n\n\\section{Functors and Algebras}\n\nThe structure of \\ensuremath{\\Varid{map}} and \\ensuremath{\\Varid{\\phi}} functions have a common form that can\nbe abstracted into \\ensuremath{\\mathbf{class}} definitions.  A \\ensuremath{\\Conid{Functor}} must define a\n\\ensuremath{\\Varid{map}} function that takes a function \\ensuremath{\\Varid{f}} and maps it over a function\ndefinition.  Definitions for \\ensuremath{\\Varid{E}_1}, \\ensuremath{\\Varid{E}_2}, \\ensuremath{\\Varid{E}_3}, and \\ensuremath{\\Conid{E}} are all\nfunctors whose \\ensuremath{\\Varid{map}} functions are already defined as \\ensuremath{\\Varid{map1}}, \\ensuremath{\\Varid{map2}},\n\\ensuremath{\\Varid{map3}}, and \\ensuremath{\\Varid{map}_E}.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{class}\\;\\Conid{Functor}\\;\\Varid{f}\\;\\mathbf{where}}$\\\\\n${\\hskip2.00em\\relax\\Varid{map}\\mathbin{::}(\\Varid{x}\\to \\Varid{y})\\to (\\Varid{f}\\;\\Varid{x}\\to \\Varid{f}\\;\\Varid{y})}$\\\\\n${}$\\\\\n${\\mathbf{instance}\\;\\Conid{\\Conid{ThirdTryPlus}.Functor}\\;\\Varid{E}_1\\;\\mathbf{where}}$\\\\\n${\\hskip2.00em\\relax\\Varid{map}\\mathrel{=}\\Varid{map1}}$\\\\\n${}$\\\\\n${\\mathbf{instance}\\;\\Conid{\\Conid{ThirdTryPlus}.Functor}\\;\\Varid{E}_2\\;\\mathbf{where}}$\\\\\n${\\hskip2.00em\\relax\\Varid{map}\\mathrel{=}\\Varid{map2}}$\\\\\n${}$\\\\\n${\\mathbf{instance}\\;\\Conid{\\Conid{ThirdTryPlus}.Functor}\\;\\Varid{E}_3\\;\\mathbf{where}}$\\\\\n${\\hskip2.00em\\relax\\Varid{map}\\mathrel{=}\\Varid{map3}}$\\\\\n${}$\\\\\n${\\mathbf{instance}\\;\\Conid{\\Conid{ThirdTryPlus}.Functor}\\;\\Conid{E}\\;\\mathbf{where}}$\\\\\n${\\hskip2.00em\\relax\\Varid{map}\\mathrel{=}\\Varid{map}_E}$\n\\end{tabbing}\nThe common structure for \\ensuremath{\\Varid{\\phi}} functions is abstracted as an \\ensuremath{\\Conid{Algebra}}\nthat defines a function, \\ensuremath{\\Varid{\\phi}}, that maps a \\ensuremath{\\Conid{Functor}}, \\ensuremath{\\Varid{f}}, and\nargument of type \\ensuremath{\\Varid{a}} to a value of type \\ensuremath{\\Varid{a}}.  The \\ensuremath{\\Varid{\\phi}} functions\ndefine algebras for each expression type.\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\mathbf{class}\\;\\Conid{\\Conid{ThirdTryPlus}.Functor}\\;\\Varid{f}\\Rightarrow \\Conid{Algebra}\\;\\Varid{f}\\;\\Varid{a}\\;\\mathbf{where}}$\\\\\n${\\hskip2.00em\\relax\\Varid{\\phi}\\mathbin{::}\\Varid{f}\\;\\Varid{a}\\to \\Varid{a}}$\\\\\n${}$\\\\\n${\\mathbf{instance}\\;\\Conid{Algebra}\\;\\Varid{E}_1\\;\\Conid{Int}\\;\\mathbf{where}}$\\\\\n${\\hskip2.00em\\relax\\Varid{\\phi}\\mathrel{=}\\Varid{\\phi_1}}$\\\\\n${}$\\\\\n${\\mathbf{instance}\\;\\Conid{Algebra}\\;\\Varid{E}_2\\;\\Conid{Int}\\;\\mathbf{where}}$\\\\\n${\\hskip2.00em\\relax\\Varid{\\phi}\\mathrel{=}\\Varid{\\phi_2}}$\\\\\n${}$\\\\\n${\\mathbf{instance}\\;\\Conid{Algebra}\\;\\Varid{E}_3\\;\\Conid{Int}\\;\\mathbf{where}}$\\\\\n${\\hskip2.00em\\relax\\Varid{\\phi}\\mathrel{=}\\Varid{\\phi_3}}$\\\\\n${}$\\\\\n${\\mathbf{instance}\\;\\Conid{Algebra}\\;\\Conid{E}\\;\\Conid{Int}\\;\\mathbf{where}}$\\\\\n${\\hskip2.00em\\relax\\Varid{\\phi}\\mathrel{=}\\Varid{\\phi}_E}$\n\\end{tabbing}\nWe can now define a general \\ensuremath{\\Varid{eval}} function for all algebras.  Given\n\\ensuremath{\\Conid{Algebra}\\;\\Varid{f}\\;\\Varid{a}}, an \\ensuremath{\\Varid{eval}} function is directly defined as follows:\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\Varid{eval}\\mathbin{::}\\Conid{Algebra}\\;\\Varid{f}\\;\\Varid{a}\\Rightarrow \\Conid{Rec}\\;\\Varid{f}\\to \\Varid{a}}$\\\\\n${\\Varid{eval}\\;(\\Conid{In}\\;\\Varid{e})\\mathrel{=}\\Varid{\\phi}\\;(\\Varid{\\Conid{ThirdTryPlus}.map}\\;\\Varid{eval}\\;\\Varid{e})}$\n\\end{tabbing}\nUnfortunately, the general \\ensuremath{\\Varid{eval}} function doesn't enable enough type\ninference to find a type value for \\ensuremath{\\Varid{a}}.  Thus, the following \\ensuremath{\\Varid{evalInt}}\nfunction is generally defined for evaluation functions that return\n\\ensuremath{\\Conid{Int}} types:\n\n\\begin{tabbing}\n\\qquad\\=\\hspace{\\lwidth}\\=\\hspace{\\cwidth}\\=\\+\\kill\n${\\Varid{evalInt}\\mathbin{::}\\Conid{Algebra}\\;\\Varid{f}\\;\\Conid{Int}\\Rightarrow \\Conid{Rec}\\;\\Varid{f}\\to \\Conid{Int}}$\\\\\n${\\Varid{evalInt}\\;(\\Conid{In}\\;\\Varid{e})\\mathrel{=}\\Varid{\\phi}\\;(\\Varid{\\Conid{ThirdTryPlus}.map}\\;\\Varid{eval}\\;\\Varid{e})}$\n\\end{tabbing}\n\\section{Usage}\n\nThis file is a template for transforming literate script into \\LaTeX\nand is not actually a \\texttt{Haskell} interpreter implementation.\nEach section in this file is a separate module that can be loaded\nindividually for experimentation.\n\n\nNote that the interpreters have been developed under GHC and some\nrequire turning on the Glasgow Extensions.  Your mileage may vary if\nyou're using HUGS.\n\nTo build a \\LaTeX document from the interpreter files, use:\n\n\\begin{alltt}\n   lhs2TeX --math Duponcheel.lhs > Duponcheel.tex\n\\end{alltt}\n\nand run \\LaTeX on the result.  The individual interpreters cannot be\ntransformed to \\LaTeX directly.\n\n\\end{document}", "meta": {"hexsha": "4fea4cdff1b5352932d182e71d54878fb2e6279b", "size": 59637, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Duponcheel/Duponcheel.tex", "max_stars_repo_name": "palexand/interpreters", "max_stars_repo_head_hexsha": "c5ff4e644fce1e97f1823321710dd082aa79aa72", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2015-02-05T13:24:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T18:39:05.000Z", "max_issues_repo_path": "Duponcheel/Duponcheel.tex", "max_issues_repo_name": "palexand/interpreters", "max_issues_repo_head_hexsha": "c5ff4e644fce1e97f1823321710dd082aa79aa72", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Duponcheel/Duponcheel.tex", "max_forks_repo_name": "palexand/interpreters", "max_forks_repo_head_hexsha": "c5ff4e644fce1e97f1823321710dd082aa79aa72", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-09T10:16:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-09T10:16:44.000Z", "avg_line_length": 60.9162410623, "max_line_length": 312, "alphanum_fraction": 0.6604121602, "num_tokens": 24186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213368305398, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.3156939823342672}}
{"text": "%\n% revised in Jan, 18th, 2008\n% problems left behind:\n% 1   whether we can have such extension:\n% \\begin{equation}\\label{GROUPeq:8}\n%     \\hat{O}_{R}[\\Psi\\Phi] = (\\hat{O}_{R}\\Psi)(\\hat{O}_{R}\\Phi)\n%     \\end{equation}\n%     I am not sure that whether it's correct.  2 vanishing integrals\n%     is not fully finished, something is still missing; perhaps\n%     better to rewrite some of the content\n%\n%\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\chapter{Group Theory in Quantum Chemistry}\n%\n% introduction: what's the group theory origin.\n%\n%\nGroup theory is a branch of pure mathematics, but it plays an\nimportant role in quantum mechanics. Qualitative information about\nmolecular wave function and its property can always be obtained from\nthe symmetry of molecule. In essence, the symmetry of molecule is one\nof its fundamental property, which is originated from the uncertainty\nprinciple of the quantum particles.\n\nBefore stepping in the detailed discussion, it's very interesting to\ntake a general view about the comparison between classic mechanics and\nquantum mechanics. In the macroscopic world, there never has two\nobjects that are exactly same with each other; but in the quantum\nworld, because of the uncertainty principle, if the particles belongs\nto the same type, for example, two electrons, and two hydrogen atoms;\nit's impossible to distinguish them between each other. So two\nelectrons actually are the same, and so as the atoms.  Thus the\nsymmetry of the molecule is a result of the uncertainty principle. In\na sense, the symmetry is some kind of inherent and fundamental\nproperty embedded in the molecule. The description here in this\nchapter is basically taken from two books given by Bishop\\cite{Bishop}\nand Cotton\\cite{Cotton}.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{The concept of symmetry operation}\\label{GROUP13}\n% 1 definition of the symmetry operation and symmetry element as well\n% as their difference 2 how to understand the symmetry operation\n%\n%\nBefore we started, it's necessary for us to distinguish an important\nconcept: that the difference between symmetry operation and symmetry\nelement. Symmetry operation is the transformation of a body such that\nthe final position is physically indistinguishable from the initial\nposition. Symmetry elements is the geometrical entity (point, line or\nplane) with respect to which a symmetry operation is carried out. So\nwe can see that they are conceptually different.  Furthermore, the\npoint group we will discuss here, is related to the group of symmetry\noperations; and the symmetry element is a way to help us to\nintuitively understand the symmetry operation.\n\nThe introduction of the concept of symmetry operation is vital to the\nuse of group theory in the chemistry. This concept generalizes the\nintrinsic symmetric property of the molecules, through this concept\nthe application of the group theory is made possible.  Therefore, the\nsymmetry operation is the most fundamental concept in this subject.\n\nHow can we understand the symmetry operations? To some extent, the\nsymmetry operation is similar to the operator in the quantum\nmechanics. Symmetry operation is only some general and abstract form\nof operation, as we use different ``bases'' on which the symmetry\noperation is applied, there will be accordingly different ways to\nrepresent the same symmetry operation. For example, if we use the\ncoordinates of an atom (the base is the coordinates), then the\nsymmetry operation will naturally correspond to some $3\\times 3$\nmatrix which converts one position of atom to another. If we use the\ncoordinates from s specific molecule (for example, a molecule contains\n$9$ atoms), then the same symmetry operation will be some $27\\times\n27$ matrix working on the coordinates of the bunch of atoms. On the\nother hand, if the atom orbitals(or more specifically to say, the\nbasis functions) are used, the symmetry operation will be the matrix\nthat describing the mixture of the corresponding orbitals. However, no\nmatter what kind of representations the symmetry operation is chosen\nto be, they all reflect the same essence behind it; that's why we can\nuse the abstract group theory to describe such generalized concept.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\subsection{Fundamental symmetry operations}\n%\n% 1 five fundamental symmetry operations 2 why the Sn is fundamental?\n% 3 further discussion to the Sn\n%\n\nThere are five fundamental symmetry operations; in a sense that all\nthe other symmetry operations can be composed from them.\n\\begin{itemize}\n\\item rotation over an axis ($C_{n}$)\n\\item inversion related to a point ( i )\n\\item reflection through a mirror of plane ($\\sigma$)\n\\item rotation over an axis then plus reflection through a mirror of\n  plane (here the index of h means that the plane is vertical to the\n  axis) ($S_{n} = \\sigma_{h} C_{n}$)\n\\item identical operation ($E$)\n\\end{itemize}\n\nIt's very natural to understand the symmetry operation of reflection,\ninversion and rotation. Such operations are represented by the\nfundamental symmetry elements of point, axis and plane.  Identical\noperation of $E$ makes the molecule unchanged, actually it's the\nidentity element in the point group. Any group can not be short of the\nidentity element, so it's a fundamental operation.\n\nHere is an interesting question that why the rotation-reflection\n$S_{n}$ is a fundamental operation? Actually we can find that there\nhas some molecule that only has the $S_{n}$ operation, where the\nrotation operation and reflection operation are absent. Therefore,\n$S_{n}$ is symmetry operation independent of $C_{n}$ and\n$\\sigma_{h}$. Here below the (\\ref{GROUP11}) shows that how to make a\n$S_{n}$ symmetry operation.\n\n\\begin{figure}[htp]\n  \\begin{center}\n    \\includegraphics[scale=0.7]{s4.eps}\n    \\caption{an example that how to make S4 symmetry operation}\n    \\label{GROUP11}\n  \\end{center}\n\\end{figure}\n\nTo further understand this situation, there are several general rules\nrespect to the connection between $S_{n}$ and $C_{n}, \\sigma$.\n\\begin{itemize}\n\\item if $n$ is odd number, the $S_{n}$ is the direct product of\n  $C_{n}$ and $\\sigma_{h}$; here the $S_{n}$ is the combination\n  between the $C_{n}$ and $\\sigma$. the case of $S_{3}$ clearly\n  demonstrates such rules.\n\\item if $n$ is an even number, the case should be divided into two\n  subgroups:\n  \\begin{itemize}\n  \\item if the $n=4k$, $S_{n}$ is an unique and independent symmetry\n    operation, together with the $C_{\\frac{n}{2}}$ symmetry operation.\n  \\item for the other cases, the $S_{n}$ is composed by the\n    $C_{\\frac{n}{2}}$ and $\\sigma_{h}$. The case of $S_{6}$ will show\n    this.\n  \\end{itemize}\n\\end{itemize}\n\nthe $S_{4}$ is:\n\\begin{eqnarray}\\label{GROUPeq:2}\n  S^{1}_{4} &=& \\sigma_{h}C^{1}_{4}  \\nonumber \\\\\n  S^{2}_{4} &=& \\sigma^{2}_{h}C^{2}_{4} = C^{1}_{2} \\nonumber \\\\\n  S^{3}_{4} &=& \\sigma_{h}C^{3}_{4}   \\nonumber \\\\\n  S^{4}_{4} &=& E  \\nonumber \\\\\n  S^{i}_{4} &=& S^{i-4}_{4} (i > 4)\n\\end{eqnarray}\n\nthe $S_{3}$ is:\n\\begin{eqnarray}\\label{GROUPeq:3}\n  S^{1}_{3} &=& \\sigma_{h}C^{1}_{3}                 \\nonumber \\\\\n  S^{2}_{3} &=& \\sigma^{2}_{h}C^{2}_{3} = C^{2}_{3} \\nonumber \\\\\n  S^{3}_{3} &=& \\sigma_{h}C^{3}_{3} = \\sigma_{h}    \\nonumber \\\\\n  S^{4}_{3} &=& C^{1}_{3}                           \\nonumber \\\\\n  S^{5}_{3} &=& \\sigma_{h}C^{2}_{3}                 \\nonumber \\\\\n  S^{6}_{3} &=& E\n\\end{eqnarray}\nHere we can see that the $S_{3}$ reproduce the group of $C_{3}\\otimes\n\\sigma_{h}$.\n\n\nNow let's see the case of $S_{6}$.\n\n\\begin{eqnarray}\\label{GROUPeq:4}\n  S^{1}_{6} &=& \\sigma_{h}C^{1}_{6}                 \\nonumber \\\\\n  S^{2}_{6} &=& \\sigma^{2}_{h}C^{1}_{3} = C^{1}_{3} \\nonumber \\\\\n  S^{3}_{6} &=& \\sigma_{h}C^{1}_{2} = i             \\nonumber \\\\\n  S^{4}_{6} &=& C^{2}_{3}                           \\nonumber \\\\\n  S^{5}_{6} &=& \\sigma_{h}C^{5}_{6}                 \\nonumber \\\\\n  S^{6}_{6} &=& E\n\\end{eqnarray}\n\nHence, we can see that $S_{4k}$ is indecent of the $C_{n}$ and\n$\\sigma$, as in $S_{4}$ there's no $\\sigma$ operation.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Algorithm between symmetry operation}\n%\n% 1 multiplication 2 commutative character 3 division 4 do not have\n% addition ??\n%\n%\nAfter setting up the fundamental symmetry operation, now in this\nsection we are going to demonstrate the algorithm between them.\n\nThe symmetry operations can be multiplied like operators. If $P$ and\n$Q$ are two symmetry operations, their product of $PQ$ is naturally\nthe symmetry operation, too. Such multiplication is defined by the way\nthat first to apply the symmetry operation $Q$, then apply the\nsymmetry operation $P$:\n\\begin{equation}\\label{}\n  R = PQ\n\\end{equation}\nSimilar to the operator that the multiplication order is important.\nGenerally we have that $PQ \\neq QP$. For example, for the $NH_{3}$\nmolecule it has $C_{3}$ and $\\sigma$ operations, but we can see that\n(this molecule has three reflection mirrors, they are labeled by $1$,\n$2$ and $3$; separately):\n\\begin{equation}\\label{}\n  C_{3}^{1}\\sigma_{1} = \\sigma_{2} \\quad  \\sigma_{1}C_{3}^{1} =\n  \\sigma_{3}\n\\end{equation}\nTherefore different order produce different results. However, there\nexists some symmetry operations which do not care about the order:\n$PQ=QP$, it's said that they are commutative. For example, $C_{3}$ and\n$i$ are two commutative operations.\n\nThe multiplication between symmetry operations satisfy the commutation\nrules below:\n\\begin{equation}\\label{}\n  (PQ)R = P(QR) = PQR\n\\end{equation}\n\nThe division algorithm, which is considered to be the counter\nalgorithm of the multiplication; can be defined that:\n\\begin{equation}\\label{}\n  PQ = E \\Rightarrow P = Q^{-1}\n\\end{equation}\nSince that any symmetry operation all has its counter operation (this\nis the requirement by the group theory), thus for any point group, the\nidentity operation of $E$ always exists.\n\nThe algorithms concerned with the symmetry operation are mainly\nrelated to the multiplication and division. It's interesting that\nthere's no addition, substraction etc. for the symmetry operations,\nalthough in the quantum mechanics the operator has such operations.\nThat's because the addition etc. have no physical correspondence to\nthe symmetry operation, we do not know how to define the physical\nprocess for the addition of two symmetry operations.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Product rules between symmetry operations}\n%\n% 1 we can form any groups based on the fundamental five symmetry\n% operations 2 rules related to the product between symmetry\n% operations 3 commutative rules between symmetry operations\n%\nSo far, we have five fundamental symmetry operations, each of them can\nform an independent group, and is labeled with an unique symmetry\nelement. They are:\n\\begin{itemize}\n\\item rotation group $C_{n}$: $\\{E, C^{1}_{n}, C^{2}_{n}, \\cdots,\n  C^{n-1}_{n}\\}$\n\\item reflection group $\\sigma$: $\\{E, \\sigma \\}$\n\\item inversion group $i$: $\\{E, i \\}$\n\\item rotation-reflection group $S_{n}$: $\\{E, S^{1}_{n}, S^{2}_{n},\n  \\cdots, S^{n-1}_{n} \\}$\n\\item identical group $E$: $\\{E \\}$\n\\end{itemize}\n\nTo some extent, the point group can be seen as the combination of such\nfive fundamental groups. Here between them, the presence of some\nspecial symmetry elements will lead to the existence of some other\nsymmetry elements. In the content below, we are going to state such\nsummarized rules.\n\\begin{itemize}\n\\item combination of two rotation axes\n  \\begin{itemize}\n  \\item If two $C_{2}$ axes crosses with each other with an angle of\n    $\\frac{2\\pi}{2n}$, there has a $C_{n}$ axis drilling through the\n    cross point and perpendicular with the plane forming by the two\n    $C_{2}$ axes. \\\\\n    On the other hand, if there exists a $C_{n}$ axis and a $C_{2}$\n    axis which is vertical to the $C_{n}$ axis; another $C_{2}$ axis\n    which satisfies the above condition also holds its presence.\n  \\end{itemize}\n\\item combination of two mirrors\n  \\begin{itemize}\n  \\item If two mirrors crosses with each other with an angle of\n    $\\frac{2\\pi}{2n}$, the cross line is a $C_{n}$ axis. On the other\n    hand, if we have a $C_{n}$ axis and a reflection mirror through\n    it, the rotation of the mirror leads to $n$ mirrors; with an angle\n    of $\\frac{2\\pi}{2n}$ between any adjacent mirror pairs .\n  \\end{itemize}\n\\item combination between axis and mirror\n  \\begin{itemize}\n  \\item If we have an even $C_{n}$ axis with a mirror vertical to it,\n    the cross point must be inversion point. Similarly if we have an\n    inversion point and a mirror through it, we have a $C_{2}$ axis\n    perpendicular to the mirror and through the inversion point.\n  \\end{itemize}\n\\end{itemize}\n\nFor the commutative character of the symmetry operation, it can be\nproved that the pairs of symmetry operations below are always\ncommutative.\n\\begin{itemize}\n\\item two rotations around same axis\n\\item reflection through two perpendicular mirror\n\\item inversion and any rotation or reflection\n\\item rotations in succession on two vertical $C_{2}$ axis\n\\item rotation and reflection where the mirror vertical to the\n  rotation axis\n\\end{itemize}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Point group}\n% 1 the definition of the point group, it's the unit for study 2 why\n% called point group\n%\nWhat is the point group? The point group is the collection of all the\nsymmetry operations corresponding to some specifical molecules.\nMathematically, such collection forms an entire and complete group,\neach possesses some individual characters. Here it's noted that the\npoint group is the unit for studying the application of group theory\non the chemistry.\n\nThe point group can always judged from the outside appearance of the\nmolecules. For example, the carbon dioxide molecule and the hydrogen\ngas molecule are belonging to the same kind, because they own the same\nkind of symmetry operations. On the other hand, the water molecule has\nthe different point group with the molecules mentioned above.\n\nFor a given molecule, since that the translation can not alter its\nsymmetry properties, all the symmetry operations should be all through\none point (this point is not varied for any symmetry operations. For a\nsingle molecule, this point is its center of mass). Therefore the\npoint group is also called molecule group.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Conjugation in symmetry operations}\n%\n% 1 mathematically define the conjugation 2 three characters related\n% to the conjugation 3 class definition, and it's not subgroup 4\n% connection between commutation and conjugation\n%\n%\nIn a given point group of $G$, and if we have element of $C$ to make\noperation $A$ and $B$ satisfy that $AC=CB$ (this is equivalent to\n$C^{-1}AC = B$ since $C^{-1}$ always exists); then $A$ and $B$ are\ncalled conjugated with each other.\n\nWe can prove the following characters related to the conjugation.\nFirst, $A$ always conjugated to itself, that is we can always find\nsome $X$, to make $A = X^{-1}AX$.\n\\begin{equation}\\label{}\n  A^{-1}A = A^{-1}X^{-1}AX = (AX)^{-1}AX = E\n\\end{equation}\nHere, we can always has $X = E$, but we may also find some others to\nget the equation. For example, we have $i^{-1}C^{1}_{3}i = C^{1}_{3}$;\nthis is because $i$ and $C^{1}_{3}$ are commutative.\n\nSecond, $A$ conjugates with $B$ is equivalent to that $B$ conjugates\nwith $A$.\n\\begin{equation}\\label{}\n  X^{-1}AX = B \\Leftrightarrow A = XBX^{-1}\n\\end{equation}\n\nThird, if $A$ and $B$ are conjugated, and $B$ and $C$ are conjugated;\nthen $A$ and $C$ are conjugated, too.\n\\begin{align}\\label{}\n  P^{-1}AP = B  & \\quad  Q^{-1}BQ = C \\Rightarrow \\nonumber \\\\\n  Q^{-1}P^{-1}APQ &= R^{-1}AR = C\n\\end{align}\nHere, $R = PQ$. Thus, the conjugated character can be passed from one\nto another.\n\nIt's interesting to see that from the above three characters, it\nimplies that the operation of conjugation seems to be\n``self-contained''. In fact, the elements which conjugated with each\nother in a given group forms a ``class''; such class is some kind of\nself-contained.\n\nHowever, here the meaning of self-contained does not denote that the\nclass is forming a subgroup. For example, the symmetry operations for\nthe $NH_{3}$ molecule has been classified into three classes: $E$,\n$\\sigma_{1}, \\sigma_{2},\\sigma_{3}$ and $C^{1}_{3}, C^{2}_{3}$.  We\ncan see that in the second and third class there has not $E$ so that\nthey can not be subgroups.\n\nOn the other hand, there's no direct relations between commutation and\nthe conjugation. For example, the symmetry operations of $C^{i}_{n}\n(i=1,2,\\cdots,n)$ are commutative, but they are not in one class(from\nthe definition we can see this point. For any $C^{i}_{n} = P$ and\n$C^{j}_{n} = Q$, and $i \\neq j$; we always have $Q^{-1}PQ \\equiv P$\nfor any $Q$). Generally, if the point group is an Abel kind, the\ndifferent elements in this group are in separate class, the number is\nsame to the order of the group.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Equivalent symmetry operations}\n%\n% this section talk about the conjugation in intuitional way\n%\n%\n%\nIn the $C^{-}AC=B$, the $A$ and $B$ are called equivalent symmetry\noperations. In this section, we are going to provide some way to\nunderstand them in some intuitional way.\n\nFirstly, we note that symmetry operation to the molecular coordinates\nwhile retaining the coordinate system unchanged is identical to the\nway that operation to the coordinate system while keeping the molecule\ncoordinates unchanged. This fact is easily understood in three\ndimensional space. Therefore it turns out that we can interpret the\n$C^{-}AC=B$ in this way:\n\\begin{quote}\n  \\begin{center}\n    first the $C$ operation is made to the coordinate system to\n    transform it to the new one, then in the new coordinate system the\n    $A$ operation is made to the molecule coordinates; then finally\n    the $C^{-}$ operation makes the new coordinates system restores to\n    original one. From the equality, this process will generate the\n    $B$ operation.\n  \\end{center}\n\\end{quote}\n\nThis is some very interesting interpretation. Here, it also implies\nthat why we call them as ``equivalent'' symmetry operations. Through\nthis process, we can clearly see that $A$ and $B$ are equivalent as\nlong as that they are the same symmetry operation by executing in\ndifferent coordinate system (here in the above interpretation, the $A$\nhappens in the new one changed by the $C$, and the $B$ happens in the\nold one; but they lead to the same result).\n\nOn the other hand, by the similar way we can understand the equivalent\nsymmetry operation in another way; that if there exists a symmetry\noperation working on the coordinate system, which is able to replace\n$A$ by $B$ ($A$ and $B$ are also the symmetry operation in this\ngroup); then $A$ and $B$ are conjugated with each other (they are also\nthe equivalent symmetry operations).\n\nThe understanding of this issue is same with the way above. Since that\nwe have $AC=CB$ for conjugated $A$ and $B$, if we can find the $C$\nworking on the coordinate system (that is equivalent to working on the\nmolecule itself); then the $AC$ means to change the coordinate system\nby $C$, then apply the $A$ to the molecule. That is same to apply the\n$B$ to the molecule, then change the coordinate system by $C$. Thus,\nif $A$ and $B$ are conjugated; the effects of $B$ can be replaced by\nthe $A$, $A$ is doing in a new coordinate system. Such new system can\nbe transformed by one of the symmetry operation in this group.\n\nNow let's take $C_{4v}$ as an example, it turns out that $C^{1}_{4}$\nand $C^{3}_{4}$ are conjugated with each other. the $C^{1}_{4}$ makes\nthe molecule contrarotate for $\\frac{2\\pi}{4}$ angle, while the\n$C^{3}_{4}$ makes the molecule rotate $\\frac{2\\pi}{4}$ in the\nclockwise direction (the cartesian system used here are defined in the\nfigure of (\\ref{GROUP12})).\n\\begin{figure}[htp]\n  \\begin{center}\n    \\includegraphics[scale=0.7]{coordinate_change.eps}\n    \\caption{coordinate changes by the $\\sigma_{d}$} \\label{GROUP12}\n  \\end{center}\n\\end{figure}\n\nIn the original coordinate system, the effects for both of $C^{1}_{4}$\nand $C^{3}_{4}$ are:\n\\begin{eqnarray}\n  % \\nonumber to remove numbering (before each equation)\n  C^{1}_{4}(z)[x,y] &\\Rightarrow& [y,-x] \\nonumber \\\\\n  C^{3}_{4}(z)[x,y] &\\Rightarrow& [-y,x]\n\\end{eqnarray}\nHere it has a third symmetry operation of $\\sigma_{d}$, which exchange\n$x$ and $y$ ($\\sigma_{d}[x,y] \\Rightarrow [y,x]$).  Therefore, in the\nnew coordinate system indicating by the figure of (\\ref{GROUP12}), we\nhave:\n\\begin{eqnarray}\n  % \\nonumber to remove numbering (before each equation)\n  C^{1}_{4}(z)[x,y] \\Leftrightarrow C^{1}_{4}(z)[y,x] (\\text{old system})\n  &\\underrightarrow{\\sigma_{d}}& [-y,x] \\nonumber \\\\\n  C^{3}_{4}(z)[x,y] \\Leftrightarrow C^{3}_{4}(z)[y,x] (\\text{old system})\n  &\\underrightarrow{\\sigma_{d}}& [y,-x]\n\\end{eqnarray}\nThus, the $C^{1}_{4}$ and $C^{3}_{4}$ are equivalent symmetry\noperations.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Class in point group}\n%\n% this section provide the details related to variety of the\n% equivalent symmetry operation\n%\nSo far we have fully understand the meaning of conjugation in the\npoint group. Now we can make some summarization that what kind of\nsymmetry operations are equivalent:\n\n\\begin{enumerate}\n\\item the identical operation and inversion operation.\n  \\begin{itemize}\n  \\item Since the both of $E$ and $i$ has only one element, $E$ and\n    $i$ are individual class respectively.\n  \\end{itemize}\n\\item reflection\n  \\begin{itemize}\n  \\item If there's some operation to exchange their reflection mirror,\n    such reflections related to these mirrors are in same class.\n  \\end{itemize}\n\\item $C_{n}$ and $S_{n}$ axis\n  \\begin{itemize}\n  \\item If there has mirrors containing the axis, or it has the\n    $C_{2}$ vertical to the axis; the $C^{i}_{n}$ and $C^{n-i}_{n}$\n    fall into same class, so as the $S^{i}_{n}$.\n  \\end{itemize}\n\\end{enumerate}\n\nFinally we can make some extra example of $C_{4v}$ to classify the\nprinciple with the $C_{n}$ and $S_{n}$ axis. The $C^{1}_{4}$ and\n$C^{3}_{4}$ are conjugated for there is a mirror vertical to the\n$C_{4}$ axis.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Classification of point group}\n%\n% this section provides the example of the point group\n%\n%\nIn the following content, we are going to give the systematical method\nclassification of the point group. From now on, for any molecules; we\ncan specify which point group it belongs to. All the symmetry\ncharacters related to the molecule, is wholly demonstrated by the\ndetails defined in its point group. We will begin from the simplest\ncase until reach to the complex ones.\n\n$C_{1}$ group: \\\\\nActually this is only identical operation (E) related to this kind of\nmolecule, see figure of (\\ref{GROUP1}).\n\\begin{figure}[htp]\n  \\begin{center}\n    \\includegraphics[scale=0.7]{molecule1.eps}\n    \\caption{C1 group} \\label{GROUP1}\n  \\end{center}\n\\end{figure}\n\n$C_{s}$ group: \\\\\n$C_{s}$ is actually the group of $\\sigma$; has two elements: $E$ and\n$\\sigma$, see figure of (\\ref{GROUP2}).\n\\begin{figure}[htp]\n  \\begin{center}\n    \\includegraphics[scale=0.7]{molecule2.eps}\n    \\caption{CS group} \\label{GROUP2}\n  \\end{center}\n\\end{figure}\n\n$C_{n}$ group: \\\\\nThis group is identical to the group of $C_{n}$, only has a rotation\naxis and identical operation, see figure of (\\ref{GROUP3}).\n\\begin{figure}[htp]\n  \\begin{center}\n    \\includegraphics[scale=0.7]{molecule3.eps}\n    \\caption{C3 group} \\label{GROUP3}\n  \\end{center}\n\\end{figure}\n\n$C_{i}$ group: \\\\\nThis group is identical to the group of $i$, only has a inversion\noperation and identical operation, see figure of (\\ref{GROUP4}).\n\\begin{figure}[htp]\n  \\begin{center}\n    \\includegraphics[scale=0.7]{molecule4.eps}\n    \\caption{Ci group} \\label{GROUP4}\n  \\end{center}\n\\end{figure}\n\n$S_{n}$ group: \\\\\nFrom the content above, we know that $S_{4}$ is some individual\ngroup. Here below we present one example in the figure of\n(\\ref{GROUP7}).\n\\begin{figure}[htp]\n  \\begin{center}\n    \\includegraphics[scale=0.7]{S4_example.eps}\n    \\caption{S4 group} \\label{GROUP7}\n  \\end{center}\n\\end{figure}\n\n$C_{nv}$ group: \\\\\nIf we add a symmetry element of mirror to the $C_{n}$ axis, and this\nmirror just contains the axis; from the analysis above we can know\nthat there must have n planes exist, as the rotation axis varies.\nThis group is called $C_{nv}$ group. The most famous example is\n$H_{2}O$ molecule, see figure of (\\ref{GROUP5}).\n\\begin{figure}[htp]\n  \\begin{center}\n    \\includegraphics[scale=0.7]{molecule5.eps}\n    \\caption{C2v group} \\label{GROUP5}\n  \\end{center}\n\\end{figure}\n\n$C_{nh}$ group: \\\\\nAs what we have shown, This group is the direct product of the $C_{n}$\nand $\\sigma_{h}$, see figure of (\\ref{GROUP6}).\n\\begin{figure}[htp]\n  \\begin{center}\n    \\includegraphics[scale=0.7]{molecule6.eps}\n    \\caption{Cnh group} \\label{GROUP6}\n  \\end{center}\n\\end{figure}\n\n$D_{n}$ group: \\\\\nIf we add $C_{2}$ axis to the $C_{n}$ axis, and the $C_{2}$ axis is\nvertical to the $C_{n}$ axis; from the product principle above we can\nknow that there must have n $C_{2}$ axes as the $C_{n}$ axis\nrotates. This situation is similar to the $C_{nv}$, actually they are\nisomorphic groups, see figure of (\\ref{GROUP8}).\n\\begin{figure}[htp]\n  \\begin{center}\n    \\includegraphics[scale=0.7]{molecule8.eps}\n    \\caption{D3 group} \\label{GROUP8}\n  \\end{center}\n\\end{figure}\n\n$D_{nh}$ group: \\\\\n$D_{nh}$ group is produced by adding a $\\sigma_{h}$ to the $D_{n}$\ngroup, where the $\\sigma$ is vertical to the main $C_{n}$ axis.  Since\nwe have n $C_{2}$ axes vertical to the $C_{n}$ axis, so the mirror\nformed by the $\\sigma_{h}$ embraces the n $C_{2}$ axes, thus we have\nanother n $\\sigma_{v}$ containing the $C_{n}$ axis.  Besides, we have\nthe inversion point due to the cross of $C_{n}$ and $\\sigma_{h}$. This\ngroup is $D_{nh}$. The benzene molecule is one of this type, see\nfigure of (\\ref{GROUP10}).\n\\begin{figure}[htp]\n  \\begin{center}\n    \\includegraphics[scale=0.7]{molecule10.eps}\n    \\caption{benzene molecule of D6h group} \\label{GROUP10}\n  \\end{center}\n\\end{figure}\n\n$D_{nd}$ group: \\\\\nIn the $D_{nh}$ group, if the added in $\\sigma_{h}$ is replaced by the\n$\\sigma_{d}$, which covers the main $C_{n}$ axis and split the\nrotation angle into half in equal; this group we called $D_{nd}$\ngroup, see figure of (\\ref{GROUP9}).\n\\begin{figure}[htp]\n  \\begin{center}\n    \\includegraphics[scale=0.7]{molecule9.eps}\n    \\caption{D5d group} \\label{GROUP9}\n  \\end{center}\n\\end{figure}\n\nIn this list, we omit all the more complicated cases, they are\ncontaining more than one $C_{n}$ axes; such as the $CH_{4}$ molecule,\nit has four $C_{3}$ axes. The more details can be found in the book\nlisted in reference\\cite{Bishop, Cotton}.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Matrix representation of point group}\n\n\\subsection{What's the representations?}\n%\n% 1 explain what's the representations, however; in a example way to\n% show this 2 detailed example to show what's the representation.  3\n% general definition. the symmetry operation always has a matrix to\n% express it on a given representation\n%\nIn the above content, we have generally introduce the concept of\nsymmetry operation. However, what does the symmetry operation derive\nfrom? That's what we call the ``representations'' (that's same to the\n``base'' concept as in the discussion of section (\\ref{GROUP13})).\n\nNow let's give some example. For simplicity, we choose the $C_{4}$\n(which contains the $C^{1}_{4}, C^{2}_{4}, C^{3}_{4}, E$ symmetry\noperations) point group and try to give their corresponding\nrepresentations.\n\nThe first example is the most plain one. We can choose an arbitrary\npoint of $(x,y,z)$ to be the representation. Here, each of the\nsymmetry operation in the $C_{4}$ is embodied as a three dimensional\nmatrix, which is to describe the transformation of the point from one\nposition to another:\n\\begin{equation}\\label{}\n  \\begin{bmatrix}\n    \\cos \\frac{2i\\pi}{4} & \\sin \\frac{2i\\pi}{4} & 0 \\\\\n    -\\sin \\frac{2i\\pi}{4} & \\cos \\frac{2i\\pi}{4} & 0 \\\\\n    0                   & 0                   & 1 \\\\\n  \\end{bmatrix}\n  \\begin{bmatrix}\n    x \\\\\n    y \\\\\n    z \\\\\n  \\end{bmatrix}\n  =\n  \\begin{bmatrix}\n    x^{'} \\\\\n    y^{'} \\\\\n    z^{'} \\\\\n  \\end{bmatrix}\n\\end{equation}\nHere the matrix shown above represents the $C^{i}_{4}$ symmetry\noperation in the given representation. Here we note that The rotation\naxis is set to the Z direction.\n\nThis simple example can be extended to some more complicated form.  If\nwe consider some molecules, for instance, the $Ni(CO)_{4}$; it holds a\n$C_{4}$ axis. Suggest that this molecule is putting on to the $XY$\nplane then the rotation of $C^{i}_{4}$ can be clearly defined as the\ncounter-clock rotation around the $Z$ axis. Therefore if we consider\nthe coordinates of the atoms, then such rotation will be accordingly\nsome $27\\times 27$ matrix describing the mixing states between the\natoms coordinates. A similar example can be found in Bishop's\nbook\\cite{Bishop}, PP $94$.\n\nOn the other hand, we can strike up some other choices. For the\nmolecule of $Ni(CO)_{4}$, if we put the coordinate system on each atom\nand keep the molecule unchanged(that's a bit different with the above\ncase, where we consider the coordinates of the atoms in a fixed\ncoordinate system); then for the $3\\times 9=27$ vectors, we can also\nfind some matrix corresponding to the rotation operation of\n$C_{4}^{i}$. Here, it's interesting to note that if we consider the\nother molecules, which also holds the $C_{4}$ symmetry (for example,\n$PtCl_{4}$ molecule; it's in a square shape); the representations will\nalso changed into other forms.\n\nMoreover, the basis sets for the molecule of $Ni(CO)_{4}$ can also\nform some representation. For example, the $6-31g(d,p)/Lanl2dz$ (here\nthe $Lanl2dz$ is used to describe the $Ni$ atom). For each of the\nbasis set, it actually forms some function space for the symmetry\noperations of $C_{4}$; based on these function space, the $C_{4}$ can\nbe generalized to be some operators on the basis sets; yet in practice\nit can be expressed into the transformation matrices to portray the\nmixing states of the basis functions.\n\nAll in all, the representations is actually what we express the\nsymmetry operations on. It can be coordinates, basis sets, orbitals,\nwave functions etc. There are unlimited ways to find the new form of\nrepresentations for a given symmetry operation (or a group of symmetry\noperations). Among each of the concrete representation, we can always\nfind a way to express the abstract symmetry operation into some matrix\nform, to fully express the symmetric property. Such matrices are\nisomorphic to the given symmetry operations, in fact; these matrices\nmirrors the symmetry operations are the most crucial link between the\nsymmetry of a molecule and its practical properties such as the\nspectral character.\n\nIn Bishop's book\\cite{Bishop}, the author offers sufficient discussion\nabout how to express a certain symmetry operation by variety of\nrepresentations. It's the best material for the further reading.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Equivalent representations}\n%\n% 1 take the mathematical form 2 express the relation between two\n% selected representations 3 to express the symmetry operation, to get\n% the similarity transformation similarity transformation does not\n% hurt the multiplication rules, that's why the selected\n% representations are equivalent 4 so that we can always choose the\n% unitary representation\n%\nFrom this section, we are going to study the characters related to the\nmatrix representation. The first we consider, is the equivalent\nproperty.\n\nHere it's more clear to introduce the idea of the equivalent\nrepresentation on mathematical form, rather than to introduce its\nphysical meanings. From the derivation below, the physical meaning is\nquite clear.\n\nFirst, let's consider some representations, it can be formed by the\nbasis sets, or the coordinates of atoms; now we choose the function\nspace as the example. Suggesting we have two sets of functions below:\n\\begin{align}\\label{}\n  f_{1}, f_{2}, f_{3}, &\\cdots, f_{n} \\nonumber \\\\\n  g_{1}, g_{2}, g_{3}, &\\cdots, g_{n}\n\\end{align}\nThese $n$-dimensional function space can be got from the result HF\norbitals, or the original basis sets. It's assumed that they express\nthe same function space, thus we can use an matrix transformation to\nlinking them together:\n\\begin{align}\\label{}\n  f_{i} &= \\sum_{j}A_{ij}g_{j} \\quad (j=1,2,\\cdots, n) \\nonumber \\\\\n  g_{k} &= \\sum_{j}B_{kj}f_{j} \\quad (j=1,2,\\cdots, n)\n\\end{align}\nFor the $A$ and $B$ we have:\n\\begin{align}\\label{}\n  f_{i} &= \\sum_{j}A_{ij}(\\sum_{l}B_{jl}f_{l}) \\nonumber \\\\\n  &= \\sum_{j}\\sum_{l}A_{ij}B_{jl}f_{l} \\Rightarrow \\nonumber \\\\\n  &\\sum_{j}A_{ij}B_{jl} = \\delta_{il}\n\\end{align}\nSo we have $AB=E$. On the other hand, we can prove that $BA=E$. So\n$A=B^{-1}$.\n\nThen we consider the operator of $\\hat{O}_{R}$ (it corresponds to the\nsymmetry operation of R), for both of the $f$ and $g$ bases, we can\nhave:\n\\begin{align}\\label{}\n  \\hat{O}_{R} f_{i} &= \\sum_{k=1}^{n}D^{f}_{ik}(R)f_{k} \\nonumber \\\\\n  \\hat{O}_{R} g_{i} &= \\sum_{j=1}^{n}D^{g}_{ij}(R)g_{j}\n\\end{align}\nThe $D$ denotes the transformation matrix for the $\\hat{O}_{R}$.\n\nNow we have:\n\\begin{align}\\label{}\n  \\hat{O}_{R} g_{i} &= \\hat{O}_{R}(\\sum_{j}B_{ij}f_{j}) \\nonumber \\\\\n  &= \\sum_{j}B_{ij}(\\hat{O}_{R}f_{j}) \\nonumber \\\\\n  &= \\sum_{j}B_{ij}(\\sum_{k=1}^{n}D^{f}_{jk}(R)f_{k})\\nonumber \\\\\n  &= \\sum_{j}B_{ij}\\sum_{k=1}^{n}D^{f}_{jk}(R)(\\sum_{l}A_{kl}g_{l})\n  \\nonumber \\\\\n  &=(\\sum_{j}B_{ij}\\sum_{k=1}^{n}D^{f}_{jk}(R)\\sum_{l}A_{kl})g_{l}\n  \\nonumber \\\\\n\\end{align}\nTherefore, we have:\n\\begin{equation}\\label{}\n  D^{g}_{il}(R) =\n  \\sum_{j=1}^{n}\\sum_{k=1}^{n}B_{ij}D^{f}_{jk}(R)A_{kl}\n\\end{equation}\nor express in a matrix form:\n\\begin{equation}\\label{}\n  D^{g}(R) = BD^{f}(R)A = BD^{f}(R)B^{-1}\n\\end{equation}\n\nHere we note that in the above deduction, the base of $f$ and $g$ are\nmanipulated all by the column; that is:\n\\begin{equation}\\label{}\n  \\sum_{j}A_{ij}g_{j} \\Leftrightarrow\n  \\begin{bmatrix}\n    A_{11} & \\cdots & A_{1n} \\\\\n    \\cdots & \\cdots & \\cdots \\\\\n    A_{n1} & \\cdots & A_{nn} \\\\\n  \\end{bmatrix}\n  \\begin{bmatrix}\n    g_{1}  \\\\\n    \\cdots \\\\\n    g_{n}  \\\\\n  \\end{bmatrix}\n\\end{equation}\n\nAll in all, the above derivation shows that the $f$ and $g$ are\nassociated with each other by some similarity transformation. On this\ncondition, $f$ and $g$ are called ``equivalent'' representations.\n\nIt's easy to know that the similarity transformation does not alter\nthe multiplication rules, that is if we have $D^{f}(SR) =\nD^{f}(S)D^{f}(R)$, for the $g$ basis it also has $D^{g}(SR) =\nD^{g}(S)D^{g}(R)$. That's why we say such basis are equivalent. This\nis the final conclusion we get.\n\nFor this reason, it's safe to choose some special form of\nrepresentations, which is the most suitable one to deal with\nquestion. It can prove that among the equivalent expressions, it can\nalways choose the unitary matrices without hurting the universality.\nHence in the following content, the unitary matrices is chosen to\nexpress the specific symmetry operations or the point group.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Reducible and irreducible representations}\n%\n% 1 introduce the Gamma to represent the representation wholly 2\n% introduce the concept of reducible representation 3 discussion\n% related to the counter operation 4 reducible and irreducible\n% concepts 5 the relations between reducible and irreducible\n% representations\n%\nNow it's the time to introduce the symbol of ``$\\Gamma$'' to express\nall the matrices in a given group (as we note above, in a specific\nrepresentation each matrix corresponds to some symmetry operation) for\na given representation. Here, $\\Gamma$ is not representing one single\nmatrix but all the matrices in a given group constituting the given\nrepresentation. The introduction of such concept is used to depict the\nirreducible and reducible character, which are related to all the\nmatrices within a given group.\n\nSuggesting we have a set of base of $f_{i}$ ($i=1,2,\\cdots, n$). If\nfor each of the symmetry operation of $\\hat{O}_{R}$ in the given\ngroup, we have the relations below:\n\\begin{align}\\label{}\n  \\hat{O}_{R}f_{1} &= D_{11}(R)f_{1} + \\cdots + D_{m1}(R)f_{m} +\n  0f_{m+1} + \\cdots + 0f_{n} \\nonumber \\\\\n  \\hat{O}_{R}f_{2} &= D_{12}(R)f_{1} + \\cdots + D_{m2}(R)f_{m} +\n  0f_{m+1} + \\cdots + 0f_{n} \\nonumber \\\\\n  \\cdots & \\cdots \\cdots \\cdots \\nonumber \\\\\n  \\hat{O}_{R}f_{m} &= D_{1m}(R)f_{1} + \\cdots + D_{mm}(R)f_{m} +\n  0f_{m+1} + \\cdots + 0f_{n} \\nonumber \\\\\n  \\hat{O}_{R}f_{m+1} &= 0f_{1} + \\cdots + 0f_{m} +\n  D_{m+1, m+1}(R)f_{m+1} + \\cdots + D_{n,m+1}(R)f_{n} \\nonumber \\\\\n  \\hat{O}_{R}f_{m+2} &= 0f_{1} + \\cdots + 0f_{m} +\n  D_{m+1, m+2}(R)f_{m+1} + \\cdots + D_{n,m+2}(R)f_{n} \\nonumber \\\\\n  \\cdots & \\cdots \\cdots \\cdots \\nonumber \\\\\n  \\hat{O}_{R}f_{n} &= 0f_{1} + \\cdots + 0f_{m} +\n  D_{m+1, n}(R)f_{m+1} + \\cdots + D_{n,n}(R)f_{n} \\nonumber \\\\\n\\end{align}\n\nHere we can see that the above equation shows that for each of the\nmatrix in the representation, it has the form below:\n\\begin{equation}\n  D(R) \\Leftrightarrow \\left(\n    \\begin{array}{cc}\n      D^{1}(R) & 0        \\\\\n      0        & D^{2}(R) \\\\\n    \\end{array}\n  \\right)\n\\end{equation}\nIn the above example, the $D^{1}(R)$ is $m$-dimensional, the the\n$D^{2}(R)$ is $n-m$-dimensional.\n\nAccording to the discussion above, we can choose the unitary form of\nthe matrices to express the symmetry operation of R. Thus, for its\ncounter operation of $R^{-1}$, we have:\n\\begin{equation}\\label{}\n  D(R^{-1}) = D(R)^{+} =\\left(\n    \\begin{array}{cc}\n      D^{1}(R)^{+} & 0        \\\\\n      0        & D^{2}(R)^{+} \\\\\n    \\end{array}\n  \\right)\n\\end{equation}\nTherefore, the counter operation also holds the block form.\n\nFor the $\\Gamma$, if there's some way to change all the matrices in\nthis representation into such block form, then this $\\Gamma$ is\nreducible; else it's irreducible.\n\nFor the $D(R)$ in reducible suggest that $\\Gamma_{1}$ has the form\nbelow:\n\\begin{equation}\\label{}\n  D(R)       = \\begin{vmatrix}\n    D^{1}(R) & 0        & 0        \\\\\n    0        & D^{2}(R) & 0        \\\\\n    0        & 0        & D^{3}(R) \\\\\n  \\end{vmatrix}\n\\end{equation}\nIT's easy to prove that if we have $D(Q) = D(R)D(S)$, then for each of\nthe $D^{i}(R)$, it also has $D^{i}(Q) = D^{i}(R)D^{i}(S)$.  Different\n$D^{i}(R)$ never mix with each other. Therefore, the blocks in the\nreducible representation of $D^{i}(R)$ also fully corresponds to the\ngiven symmetry operations or point group (additionally, the\nrepresentations behind the block matrix of $D^{i}(R)$ is sufficient to\nbe some independent representations). In this sense, it's said that\nthe reducible representation is the ``direct sum'' of the irreducible\nrepresentations, all of the characters inside the reducible\nrepresentation is wholly determined by its irreducible components.\n\nFor this reason, the reducible representation can be expressed as:\n\\begin{equation}\\label{}\n  \\Gamma = \\Gamma^{1} \\bigoplus \\Gamma^{2} \\bigoplus \\Gamma^{3}\n\\end{equation}\nIf some $\\Gamma^{i}$ appears many times, we can also write:\n\\begin{equation}\\label{}\n  \\Gamma = a_{1}\\Gamma^{1} \\bigoplus a_{2}\\Gamma^{2} \\bigoplus\n  a_{3}\\Gamma^{3}\n\\end{equation}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Great orthogonality theorem}\n%\n%\n%\nIn the application of the group theory in chemistry, there has a\ntheorem which possesses the key position in the whole theory; that's\nthe the great orthogonality theorem; or the key theorem. This theorem\ndescribe the relationship between the matrix elements among the\nirreducible representations, however; the deep study will show that\nit's a connection between the properties of abstract symmetry\noperation and its corresponding representation matrices. In this\nsection, we are going to give a detailed study around this subject.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{The key theorem}\n%\n% 1 to show this theorem 2 transform it to the unitary matrices form 3\n% make a bit of analysis 4 show the reason that why we consider the\n% characters\n%\nFirst let's state the key theorem. Here for simplicity the proof is\nomitted, but it can found in the Bishop's book\\cite{Bishop}.\n\nSuggest we have a point group. For every symmetry operations of R in\nthis point group, we introduce two irreducible representations of\n$\\Gamma^{\\mu}$ and $\\Gamma^{\\nu}$ (the matrices are labeled as\n$D^{\\mu}(R)$ and $D^{\\nu}(R)$, separately). Here, the key theorem\nstates that for the elements of $D^{\\mu}(R)$ and $D^{\\nu}(R)$, they\nsatisfy the relations below:\n\\begin{equation}\\label{GROUPeq:15}\n  \\sum_{R}D^{\\mu}_{ik}(R) D^{\\nu}_{mj}(R^{-1}) =\n  (g/n_{\\mu})\\delta_{\\mu\\nu} \\delta_{ij} \\delta_{km}\n\\end{equation}\n\nSince that we can always take the unitary matrix form, we can rewrite\nthe theorem as:\n\\begin{align}\\label{}\n  \\sum_{R}D^{\\mu}_{ik}(R) D^{\\nu}_{mj}(R^{-1}) &=\n  \\sum_{R}D^{\\mu}_{ik}(R) D^{\\nu}_{mj}(R)^{+} \\nonumber \\\\\n  &= \\sum_{R}D^{\\mu}_{ik}(R) D^{\\nu}_{jm}(R)^{*} \\nonumber \\\\\n  &= (g/n_{\\mu})\\delta_{\\mu\\nu} \\delta_{ij} \\delta_{km}\n\\end{align}\n\nThus, the final form below is what we always refer to.\n\\begin{equation}\\label{GROUPeq:16}\n  \\sum_{R}D^{\\mu}_{ik}(R) D^{\\nu}_{jm}(R)^{*} =\n  (g/n_{\\mu})\\delta_{\\mu\\nu} \\delta_{ij} \\delta_{km}\n\\end{equation}\n\nNow we are going to make a bit of analysis. For the $\\Gamma^{\\mu}$,\neach symmetry operation of R will give a matrix, which contains\n$n_{\\mu}^{2}$ elements. If we loop over all the symmetry operations R\n(suggest we have $g$ symmetry operations in this point group), the\nmatrix element of $D_{ij}(R)$ will form a $g$-dimensional vector; such\nvectors is in total number of $n_{\\mu}^{2}$. From the equation of\n(\\ref{GROUPeq:16}), we can see that these vectors are orthogonal with\neach other. Furthermore, since that different representations are also\northogonal with each other, we can imagine that we can construct a\nmatrix similar like this:\n\\begin{equation}\\label{}\n  \\begin{vmatrix}\n    D_{11}^{\\mu}(R_{1})             & D_{11}^{\\mu}(R_{2})             & \\cdots &  D_{11}^{\\mu}(R_{g})              \\\\\n    D_{12}^{\\mu}(R_{1})             & D_{12}^{\\mu}(R_{2})             & \\cdots &  D_{12}^{\\mu}(R_{g})              \\\\\n    \\cdots                          & \\cdots                          & \\cdots &  \\cdots                           \\\\\n    D_{n_{\\mu}n_{\\mu}}^{\\mu}(R_{1}) & D_{n_{\\mu}n_{\\mu}}^{\\mu}(R_{2}) & \\cdots &  D_{n_{\\mu}n_{\\mu}}^{\\mu}(R_{g})  \\\\\n    D_{11}^{\\nu}(R_{1})             & D_{11}^{\\nu}(R_{2})             & \\cdots &  D_{11}^{\\nu}(R_{g})              \\\\\n    D_{12}^{\\nu}(R_{1})             & D_{12}^{\\nu}(R_{2})             & \\cdots &  D_{12}^{\\nu}(R_{g})              \\\\\n    \\cdots                          & \\cdots                          & \\cdots &  \\cdots                           \\\\\n    D_{n_{\\nu}n_{\\nu}}^{\\nu}(R_{1}) & D_{n_{\\nu}n_{\\nu}}^{\\nu}(R_{2}) & \\cdots &  D_{n_{\\nu}n_{\\nu}}^{\\nu}(R_{g})  \\\\\n    \\cdots                          & \\cdots                          & \\cdots &  \\cdots                           \\\\\n  \\end{vmatrix}\n\\end{equation}\nThis matrix totally has $\\sum n_{\\mu}^{2}$ rows, but has only $g$\ncolumns. Thus it leads to conclusion:\n\\begin{equation}\\label{}\n  \\sum n_{\\mu}^{2} \\leq g\n\\end{equation}\nFurther proof shows that\n\\begin{equation}\\label{}\n  \\sum n_{\\mu}^{2} = g\n\\end{equation}\n\nTherefore, it limits the number and dimension of irreducible\nrepresentations for a given point group.\n\nHowever, the great orthogonality theorem is complicated so that\ndifficult to get more valuable information. For this reason, we\nintroduce the concept of ``character'' to re-express this theorem.  At\nthat moment we can see the clear expression will lead to more fruitful\nresults.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Character}\n%\n% 1 introduce the trace concept 2 for the symmetry operations in the\n% same class, their corresponding matrices have the same characters.\n% 3 rewrite the key theorem by the characters\n%\n%\nFrom the algebra, the trace of a matrix is its sum of diagonal\nelements:\n\\begin{equation}\\label{}\n  Trace(A) = \\sum_{i} A_{ii}\n\\end{equation}\nIt's well known that the trace does not change between the similarity\ntransformations. Thus, we introduce the concept of character, which is\nis the trace of representation matrix (it's labeled as $\\chi$):\n\\begin{equation}\\label{}\n  \\chi^{\\mu}(R) = Trace(D^{\\mu}(R))\n\\end{equation}\n\nNow let's say more about related to the characters. First we can prove\nthat for the symmetry operations in the same class, their\ncorresponding matrices have the same characters.\n\nThis is easy to understand. Suggest we have symmetry operations of $P$\nand $Q$, which has the relations:\n\\begin{equation}\\label{}\n  X^{-1}PX = Q\n\\end{equation}\nThen the corresponding matrix satisfy (for the $\\mu$ representation):\n\\begin{equation}\\label{}\n  D^{\\mu}(X)^{-1}D^{\\mu}(P)D^{\\mu}(X) = D^{\\mu}(Q)\n\\end{equation}\nThus P and Q are connected by some similarity transformation, so\ndirectly we can get:\n\\begin{equation}\\label{}\n  \\chi(P) = \\chi(Q)\n\\end{equation}\n\nThus for a given representation, the character for the symmetry\noperation within a class is same. Similarly, by the same way we can\nget that the equivalent representations share the same characters for\neach of the symmetry operation (because they are associated with each\nother by the similarity transformation, too). Hence, it's worthy to\nnote that through the concept of ``character'', now the ``class'' and\nthe ``equivalent representations'' are connected together.\n\nFurthermore, we can use the character to rewrite the great\northogonality theorem. From the (\\ref{GROUPeq:16}), we can have:\n\\begin{eqnarray}\\label{GROUPeq:9}\n  % \\nonumber to remove numbering (before each equation)\n  \\sum_{R} D^{\\mu}_{ii}(R) D^{\\nu}_{jj}(R)^{*} &=&  (g/n_{\\mu})\\delta_{\\mu\\nu}\n  \\delta_{ij}  \\nonumber \\\\\n  \\sum_{i}\\sum_{j}\\sum_{R} D^{\\mu}_{ii}(R) D^{\\nu}_{jj}(R)^{*} &=&\n  (g/n_{\\mu})\\delta_{\\mu\\nu}\\sum_{i}\\sum_{j}\\delta_{ij}  \\nonumber \\\\\n  \\sum_{R}\\chi^{\\mu}(R)\\chi^{\\nu}(R)^{*} &=&  g\\delta_{\\mu\\nu}\n\\end{eqnarray}\nThen for the irreducible representation of $\\Gamma^{\\mu}$, the\n$\\chi^{\\mu}(R)$ ($R = R_{1}, R_{2}, \\cdots, R_{g}$) is composed into\nsome $g$-dimensional vector; and here the vectors from different\nrepresentations are orthogonal with each other.\n\nNext we are going to show how to express the concept of class in the\nkey theorem. Now for a given point group, each class inside we label\nit as $C_{i}$ (here it should not mix with the n axis of $c_{n}$), the\nnumber of the classes is $k$, the number of all the symmetry\noperations is $g$, and the number of symmetry operations within each\nclass is $g_{i}$. So we have: $\\sum_{i=1}^{k} g_{i} = g$.\n\nFor example, to the point group of $C_{3v}$; we have:\n\\begin{align}\\label{}\n  C_{1} &: E \\nonumber \\\\\n  C_{2} &: \\sigma_{1}, \\sigma_{2}, \\sigma_{3} \\nonumber \\\\\n  C_{3} &: c^{1}_{3},c^{2}_{3}\n\\end{align}\nThus in the given example, $g=6$, $k=3$. Since that in each class of\n$C_{i}$, the character keep to be same; so we can write the\n(\\ref{GROUPeq:9}) as:\n\\begin{equation}\\label{}\n  \\sum_{i=1}^{k}g_{i}\\chi^{\\mu}(C_{i})\\chi^{\\nu}(C_{i})^{*} =\n  g\\delta_{\\mu\\nu}\n\\end{equation}\n\nFurthermore, the above equation can be rearranged as:\n\\begin{equation}\\label{}\n  \\sum_{i=1}^{k}\\{g_{i}^{\\frac{1}{2}}\\chi^{\\mu}(C_{i})\\}\n  \\{g_{i}^{\\frac{1}{2}}\\chi^{\\nu}(C_{i})^{*}\\}\n  = g\\delta_{\\mu\\nu}\n\\end{equation}\nNow it can see that the $g_{i}^{\\frac{1}{2}}\\chi^{\\mu}(C_{i})$ has\nformed as some $k$-dimensional vectors, and they are orthogonal with\neach other if they come from different representations. Each one\nrepresents the specific character for the class.\n\nTherefore, we can see that the number of irreducible representations\nshould be less than the number of class:\n\\begin{equation}\\label{}\n  r \\leq k\n\\end{equation}\nThe more strict proof demonstrates that actually the equality is\narchived:\n\\begin{equation}\\label{}\n  r = k\n\\end{equation}\nFinally, we can see that the number of irreducible representations\nshould equal to the number of classes in the point group.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Clarification about the representations}\n%\n% clarify the concept between the equivalent representations and the\n% class give some example to show how to understand the conclusion got\n% from the above content.\n%\n\nAlthough it's very easy to distinguish literally the concept of\nequivalent representations and the concept of ``class'' in the\nsymmetry operations, however I find that their mathematical\nexpressions always puzzle me. Thus in this passage I hope to give a\nthorough discussion to it.\n\nAs we have known, the equivalent representations share the same\ncharacters, that means for each of symmetry operation in the given\npoint group, the matrix of $D^{k}(R_{i})$ formed from the specific\nrepresentation $k$ ($i = 1, 2, \\cdots, n$) shares the same character\nof $D^{k^{'}}(R_{i})$ in the representation of $k^{'}$.\n\nOn the other hand, the concept of class is expressed based on the\ndifferent things. For a specific representation of $k$, they symmetry\noperations are grouped in classes; for each class the matrices share\nthe same characters.\n\nHence, it turns out that they are two different things. However, the\ngreat orthogonality theorem bridges them together, by requiring that\nthe number of non-equivalent irreducible representations should be the\nsame to the number of classes in a given point group. That means, for\nany representations; if it's irreducible, it only belongs to several\nkinds restricted by the number of class (else it must be equivalent to\nsome other irreducible representations); if it's reducible, that\nthere's only several kinds of non-equivalent irreducible\nrepresentations can be found, the other irreducible representations\nmust be equivalent to them.\n\nNow let's give some example. For the molecule with the $C1$ symmetry,\nit only has one class that contains only symmetry operation of $E$,\nthus there's only one non-equivalent irreducible representation, in\nthe later concept we can see such representation is labeled as\n$A$. Hence no matter how many molecule orbitals we have, for the $C1$\nmolecule we can only get the $A$ type of orbitals.\n\nSimilarly, for the point group of $C2v$, we have $4$ classes then we\nmust has only $4$ kinds of non-equivalent irreducible\nrepresentations. Actually these four non-equivalent irreducible\nrepresentations are characterized by $A_{1}$, $A_{2}$, $B_{1}$ and\n$B_{2}$. Hence for the molecule possesses the $C2v$ symmetry, their\norbitals must fall into these four kinds.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Evaluate the number of irreducible representations in the\n  reducible one}\n%\n% 1 the equation of evaluating the number of irreducible\n% representations from the reducible one 2 to prove the theorem that\n% any two representations, if they share the same character arrays;\n% then they must be equivalent.\n%\nNow let's consider an reducible representation of $\\Gamma^{red}$, it\ncan be expressed by:\n\\begin{equation}\\label{}\n  \\Gamma^{red} = \\sum_{i=1}^{k}a_{i}\\Gamma^{i}\n\\end{equation}\nHere $\\Gamma^{i}$ denotes to the non-equivalent irreducible\nrepresentation, from the discussion above we can know that only these\nrepresentations are meaningful in the reducible ones. The $k$ denotes\nto the number of classes.\n\nOn the other hand, it's much more natural to rewrite the above\nequation by the character:\n\\begin{equation}\\label{}\n  \\chi^{red}(R) = \\sum_{i=1}^{k}a_{i}\\chi_{i}(R)\n\\end{equation}\nFrom this expression, the meaning of using non-equivalent irreducible\nrepresentation is more clear since that different non-equivalent\nirreducible representation will get different character array (if we\ntake all the symmetry operations of R into consideration, the\ncharacters are forming an array; and arrays from different\nnon-equivalent irreducible representation are orthogonal with each\nother).\n\nNow by multiplying the $\\chi_{j}^{*}(R)$ to the above equation, we can\nhave:\n\\begin{align}\\label{}\n  \\sum_{R}\\chi^{red}(R)\\chi_{j}^{*}(R) &=\n  \\sum_{R}\\sum_{i=1}^{k}a_{i}\\chi_{i}(R)\\chi_{j}^{*}(R) \\nonumber \\\\\n  &=\\sum_{i=1}^{k}a_{i}g\\delta_{ij} \\nonumber \\\\\n  &= ga_{i}\n\\end{align}\n\nThat yields some useful equation:\n\\begin{equation}\\label{GROUPeq:1}\n  a_{i} = \\frac{1}{g}\\sum_{R}\\chi^{red}(R)\\chi_{i}^{*}(R)\n\\end{equation}\n\nFrom the previous discussion, we have known that if two\nrepresentations are equivalent, they will give the same character\narrays formed by the symmetry operations of $R_{i}$ ($i=1,2,\\cdots,\nn$).\n\nNow based on the equation of (\\ref{GROUPeq:1}), we can prove its\ninverse proposition that if the character arrays are same between two\nrepresentations, then they must be equivalent.\n\nFirst, suggest two irreducible representations; there will be two\nsituations: one is that they are non-equivalent, then the character\narrays formed must be orthogonal; the other case is that they are\nequivalent, then the character arrays formed must be same (since for\neach symmetry operation both of the representation matrices has the\nsame characters).\n\nSecond, for two representations which are reducible; let's consider\ntheir character arrays formed by the non-equivalent irreducible\nrepresentations (equivalent ones get the same character arrays so that\nthey are needed to take into account). If the two reducible\nrepresentations have the same character arrays, it can see that they\nmust have the same type of non-equivalent irreducible\nrepresentations. Then according to the equation of (\\ref{GROUPeq:1}),\ntheir number must be same. Thus, we can rearrange the non-equivalent\nirreducible representations of $\\Gamma^{i}$ so that to make the two\nreducible representations same. Therefore, for any two\nrepresentations, if they share the same character arrays; then they\nmust be equivalent.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Criteria for irreducibility}\n%\n%\n% how to judge a given representation is reducible or not\n%\n%\nNow we can judge a given representation is reducible or not based on\nthe (\\ref{GROUPeq:9}). Suggest for some representation we have:\n\\begin{equation}\\label{}\n  \\chi^{a}(R) = \\sum_{i=1}^{k_{1}}a_{i}\\chi_{i}(R)\n\\end{equation}\nThen we have:\n\\begin{align}\\label{}\n  \\sum_{R}\\chi^{a}(R)\\chi^{a}(R)^{*} &=\n  \\sum_{R}\\sum_{i=1}^{k_{1}}a_{i}\\chi_{i}(R)\\sum_{j=1}^{k_{1}}a_{j}\\chi_{j}(R)^{*} \\nonumber \\\\\n  &=\\sum_{i=1}^{k_{1}}a_{i}\\sum_{j=1}^{k_{1}}a_{j}\\sum_{R}\\chi_{i}(R)\\chi_{j}(R)^{*} \\nonumber \\\\\n  &= g\\sum_{i=1}^{k_{1}}\\sum_{j=1}^{k_{1}}a_{i}a_{j}\\delta_{ij} \\nonumber \\\\\n  &= g\\sum_{i=1}^{k_{1}}a_{i}^{2}\n\\end{align}\n\nIf $\\chi^{a}$ represents some irreducible representation, then it can\nonly has one component of $a_{i}$, other items will go to be\nzero. Then we have:\n\\begin{equation}\\label{GROUPeq:5}\n  \\sum_{R}\\chi^{a}(R)\\chi^{a}(R)^{*}  = g\n\\end{equation}\nTherefore the (\\ref{GROUPeq:5}) indicates that if the representation\nis irreducible, then the inner product of the corresponding character\narray will be a number of $g$.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Character Table}\n%\n% 1 why do we have the character table 2 mulliken symbol 3 how to\n% understand the non-equivalent irreducible representations\n%\n\nFrom the discussion above, we can see that the character for each\npoint group are unique, it's one-to-one mapping with the\nnon-equivalent irreducible representations; in other words, it\ncharacterizes the non-equivalent irreducible representations for a\ngiven point group. Since that the characters for the non-equivalent\nirreducible representations only depend on the class of symmetry\noperations, and irrelevant to what concrete representations we choose;\nthen it's possible to construct the character table. Below there's a\ntypical character table for $C_{3v}$:\n\n\\begin{center}\n  \\begin{tabular}{c|c c c|c|c}\n    % after \\\\: \\hline or \\cline{col1-col2} \\cline{col3-col4} ...\n    $C_{3v}$ & $E$ & $2C_{3}$ & $3\\sigma_{v}$ &                          &    \\\\\n    \\hline\n    $A_{1} $ & 1   &     1    &      1        & $z$                      &\n    $x^{2}+y^{2}$, $z^{2}$ \\\\\n    $A_{2} $ & 1   &     1    &     -1        & $R_{z}$                  &    \\\\\n    $E$      & 2   &    -1    &      0        & $(x,y)$, $(R_{x},R_{y})$ &\n    $(x^{2}-y^{2}, xy)$, $(xz, yz)$ \\\\\n  \\end{tabular}\n\\end{center}\n\nNow by the example of $C_{3v}$, we are going to give some illustration\nabout how to understand the character table.\n\nAs we can see, the character table can be divided into four blocks and\neach one is separated from the others by the vertical line.\n\nIn the first block, there's the label for the non-equivalent\nirreducible representations. The designation for these representations\nare brought up by Mulliken, so it's also called Mulliken symbols. the\nrule to draw the Mulliken symbols is:\n\\begin{itemize}\n\\item all the one dimensional representations are labeled as $A$ or\n  $B$, two dimensional representations are labeled as $E$; and three\n  dimensional representations are labeled as $T$ or $F$.\n\\item for the one dimensional representation, if it has the $C_{n}$\n  axis ($n \\geq 2$), the symbol of $A$ or $B$ is decided by the state\n  of character for the highest order of $C^{1}_{n}$; if it's $+1$,\n  then the label of $A$ is used; if $-1$ the label of $B$ is used.\n\\item for the $C_{1}$, $C_{i}$ and $C_{s}$ type of molecule, they all\n  labeled as $A$.\n\\item If the molecule has $C_{2}$ axis or the mirrors containing the\n  $C_{n}$ axis; the subscript of $1$ or $2$ can be used to classify\n  the case that whether the $C_{2}$ axis (or the mirrors) give the\n  $+1$ character or the $-1$ character. If $+1$ then the subscript of\n  $1$ is selected, else $2$ is chosen.\n\\item If the molecule has $\\sigma_{h}$, then the symbol of $'$ or $''$\n  indicate that the character for the $\\sigma_{h}$ is $+1$ or $-1$.\n\\item If the molecule has symmetry operation of $i$, then the\n  subscript of $g$ means the character for the $i$ operation is $+1$,\n  and the subscript of $u$ means the character for the $i$ operation\n  is $-1$.\n\\end{itemize}\n\nThe second block is the characters for each class. Formally they can\nbe constructed from the mathematical rules we mentioned in the above\ncontent.\n\nThe third and fourth blocks are related to the ``base'' of the\nrepresentations. For example, if we choose one point coordinates of\n$(x,y,z)$ to represent the point group of $C_{3v}$, then for each\nsymmetry operation we can get the corresponding matrix, that is the\nrepresentation; from such matrices we can see that the $z$ component\nis never mixing with the $(x,y)$ by having the formation below:\n\\begin{equation}\\label{}\n  \\begin{bmatrix}\n    D(x,y) & 0    \\\\\n    0      & D(z) \\\\\n  \\end{bmatrix}\n\\end{equation}\nhere the $D$ means small matrix inside the representation. Thus we can\nsee that the $z$ forms the one dimensional irreducible representation\nfor the $C_{3v}$, and the $(x,y)$ forms the two dimensional\nirreducible representation for the $C_{3v}$ point group.  They are\nnon-equivalent, each one has its own character array.  That's what\nthese two blocks tell us.\n\nHere we are going to omit the other detailed discussion of the\ncharacter table. The reader can consult the book by\nBishop\\cite{Bishop} and Cotton\\cite{Cotton} for more interesting\ndetails.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Symmetry project operator}\n%\n% 1 why we want to construct the project operator?  2 derive the\n% concrete expression for the project operator 3 how can we understand\n% the operator 4 examples to show how to do the projection on the\n% basis functions\n%\nIn quantum chemistry, usually we will encounter a kind of problem that\nto transform on function space of $F$ into another of $G$:\n\\begin{equation}\\label{}\n  f_{1}, f_{2}, \\cdots, f_{n} \\Rightarrow g_{1}, g_{2}, \\cdots, g_{n}\n\\end{equation}\nThe new form of $G$ may possess some kind of benefit in calculation.\nThe symmetry project operator is able to perform this transformation\njob.\n\nFor example, the $F$ may be originally selected as the basis functions\nfor some molecules we wish to study, usually they are the reducible\nrepresentations. However; if the molecule has symmetry then we can\nmake use of it. Before the concrete calculation, e.g. HF calculation;\nwe should organize the basis functions into its linear combination of\n$G$ so that it can be the irreducible representations. In the latter\ncontent, we can see that due to the vanishing integral rules that a\nlot of calculations can be avoided by using the irreducible\nrepresentations.\n\nNow we begin to derive the expression for the symmetry project\noperator. Suggest we have some function space of $F$:\n\\begin{equation}\\label{}\n  f^{\\nu}_{1}, f^{\\nu}_{2}, f^{\\nu}_{3}, \\cdots, f^{\\nu}_{n_{\\nu}}\n\\end{equation}\nthis function space can be reducible or irreducible. After imposing on\nthe symmetry operator of $\\hat{O}_{R}$, it gives:\n\\begin{equation}\\label{GROUPeq:10}\n  \\hat{O}_{R}f^{\\nu}_{p} =\n  \\sum_{q=1}^{n_{\\nu}}D^{\\nu}_{pq}(R)f^{\\nu}_{q}\n\\end{equation}\n\nFor each of the symmetry operation of $R$, we can have the above\nexpression. Now we multiply the (\\ref{GROUPeq:10}) with\n$D^{\\mu}_{ij}(R)^{*}$, and sum up all the symmetry operations of $R$;\naccording to the key theorem it gives:\n\\begin{align}\\label{GROUPeq:11}\n  \\sum_{R}D^{\\mu}_{ij}(R)^{*}\\hat{O}_{R}f^{\\nu}_{p} &=\n  \\sum_{q=1}^{n_{\\nu}}\\sum_{R}D^{\\mu}_{ij}(R)^{*}\n  D^{\\nu}_{pq}(R)f^{\\nu}_{q} \\nonumber \\\\\n  &=\\sum_{q=1}^{n_{\\nu}}(g/n_{\\nu})\\delta_{ip}\n  \\delta_{jq}\\delta_{\\mu\\nu}f^{\\nu}_{q} \\nonumber \\\\\n  &=(g/n_{\\nu})\\delta_{ip}\\delta_{\\mu\\nu}f^{\\nu}_{j}\n\\end{align}\n\nNow we can define some new operator, which is taken the form below:\n\\begin{equation}\\label{GROUPeq:12}\n  P^{\\mu}_{ij} = \\sum_{R}D^{\\mu}_{ij}(R)^{*}\\hat{O}_{R}\n\\end{equation}\nThis is the symmetry project operator.\n\nNow we wish to make some analysis based on the derivation on the\n(\\ref{GROUPeq:11}). Firstly, we can see that the project operator is\nassociated with the matrix element of $D^{\\mu}(R)^{*}$ but not the\nwhole matrix; it's a very interesting feature that it implies some\npossibility that the construction of the new function space does not\nneed the information of whole matrix, it's element is enough.\n\nSecondly, it's only that $\\mu$ and $\\nu$ are some equivalent\nirreducible representations then the element in the original function\nspace $F$ can be left behind, other elements which belongs to\ndifferent irreducible representations will be sweeped out. This is\nalso the reason that why we call the operator defined in the\n(\\ref{GROUPeq:12}) as ``project operator''.\n\nBased on the above analysis, we can see the possibility to use the\ntrace to express the symmetry project operator. In (\\ref{GROUPeq:12})\nlet's take the diagonal element ($i=j$) and sum over all the $i$, it\ngives:\n\\begin{align}\\label{}\n  P^{\\mu}=\\sum_{i}P^{\\mu}_{ii} &=\n  \\sum_{i}\\sum_{R}D^{\\mu}_{ii}(R)^{*}\\hat{O}_{R} \\nonumber \\\\\n  &=\\sum_{R}\\sum_{i}D^{\\mu}_{ii}(R)^{*}\\hat{O}_{R} \\nonumber \\\\\n  &=\\sum_{R}\\chi^{*}(R)\\hat{O}_{R}\n\\end{align}\nIn many cases it's much more useful than the (\\ref{GROUPeq:12})\nbecause that the character for the symmetry operation is easier to\nget.\n\nFinally let's give some example to show that how to use the symmetry\nproject operator to ``project'' new function space from the old one.\nTake the $NH^{3}$ molecule as an example, it has three hydrogen atoms;\nwe take the $1s$ orbital(Gaussian orbitals, or Slater type; any is OK)\nfrom each of the atoms, they are labeled as: $a$, $b$, $c$. It's known\nto be the reducible representations. Now we wish to organize them into\nthe irreducible representations.\n\nFirst let's select one of $1S$ hydrogen orbital, e.g. the orbital $a$;\nthen the symmetry operation of $R$ on the orbital $a$ gives:\n\n\\begin{center}\n  \\begin{tabular}{ c|c c c c c c }\n    \\hline\n    % after \\\\: \\hline or \\cline{col1-col2} \\cline{col3-col4} ...\n    R   & E & $c^{1}_{3}$ & $c^{2}_{3}$ & $\\sigma^{'}$\n    & $\\sigma^{''}$ & $\\sigma^{'''}$ \\\\\n    \\hline\n    R(a) & a & b & c & a & c & b \\\\\n  \\end{tabular}\n\\end{center}\nThe table above is derived from the intuitional observations.\n\nNow we can see that in the (\\ref{GROUPeq:11}) we have gotten the\n$\\hat{O}_{R}f^{\\nu}_{p}$. now we consider the character table for the\n$C_{3v}$:\n\n\\begin{center}\n  \\begin{tabular}{ c|c c c c c c }\n    \\hline\n    % after \\\\: \\hline or \\cline{col1-col2} \\cline{col3-col4} ...\n    R   & E & $c^{1}_{3}$ & $c^{2}_{3}$ & $\\sigma^{'}$\n    & $\\sigma^{''}$ & $\\sigma^{'''}$ \\\\\n    \\hline\n    $A_{1}$ & 1 & 1 & 1 & 1  & 1  & 1  \\\\\n    $A_{2}$ & 1 & 1 & 1 & -1 & -1 & -1 \\\\\n    $E$     & 2 &-1 &-1 & 0  & 0  & 0  \\\\\n  \\end{tabular}\n\\end{center}\nNow by using this character table, we are going to sort out the\nirreducible representations from the $a$, $b$ and $c$. For $A_{1}$, we\nhave:\n\\begin{align}\\label{}\n  P^{A_{1}} &= \\sum_{R}\\chi^{*}(R)R(a) \\nonumber \\\\\n  &=a + b + c + a + c + b \\nonumber \\\\\n  &=2(a+b+c)\n\\end{align}\nAfter normalization we can get the irreducible function which belongs\nto the $A_{1}$ type:\n\\begin{equation}\\label{}\n  \\psi_{A_{1}} = \\frac{1}{\\sqrt{3}}(a+b+c)\n\\end{equation}\n\nSimilar process can be done to the $A_{2}$:\n\\begin{align}\\label{}\n  P^{A_{2}} &= \\sum_{R}\\chi^{*}(R)R(a) \\nonumber \\\\\n  &=a + b + c - a - c - b \\nonumber \\\\\n  &=0\n\\end{align}\nIt's interesting to see that the representation of $a$, $b$ and $c$\ndoes not contain the $A_{2}$ type of irreducible representation.\n\nFor the $E$, we have to note that it's actually two dimensional matrix\nso that we should get two independent functions containing $a$, $b$\nand $c$. However, in the character table we use the trace so only one\nfunction we can get:\n\\begin{align}\\label{}\n  P^{E} &= \\sum_{R}\\chi^{*}(R)R(a) \\nonumber \\\\\n  &=2a - b - c\\nonumber \\\\\n\\end{align}\nthe normalization gives the result:\n\\begin{equation}\\label{}\n  \\psi_{E} = \\sqrt{\\frac{1}{6}}(2a-b-c)\n\\end{equation}\n\nObviously that three independent function of $a$, $b$ $c$ will yield\nanother three equivalent functions, now only one is absent. However,\nif we can find the full matrix of $E$ based on the representation of\n$a$, $b$ and $c$; then by using the matrix elements we can get the\nfinal missing function.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Comparison between the framework for symmetry and quantum\n  mechanics}\\label{GROUP14}\n%\n% in this part, we wish to strike up some interesting comparison\n% between the discussion of symmetry and the quantum mechanics\n%\n%\nNow it's time for us to take another view to understand the framework\nfor application of symmetry in quantum mechanics. In this course, we\nhave introduced the concept of representations, reducible and\nirreducible representations, character, the representing matrix for\nthe symmetry operator etc. So far we can see that such framework is a\nbit of similar to what we have constructed in discussing the quantum\nmechanics: eigen states and eigen values, operators, degenerate and\nnon-degenerate states, representations etc.\n\nTherefore, we wish to present a table to build some kind of\n``non-rigorous'' comparison between the two frameworks. In such table,\nthe left side is the concept in the discussion of symmetry, and the\nright side is the equivalent concept used in the quantum mechanics.\n\\begin{center}\n  \\begin{tabular}{c|c}\n    \\hline\n    % after \\\\: \\hline or \\cline{col1-col2} \\cline{col3-col4} ...\n    symmetry  & quantum mechanics \\\\\n    \\hline\n    representations & wave functions \\\\\n    symmetry operations & operators for physical quantity \\\\\n    point group & CSCCO \\\\\n    equivalent representation & equivalent eigen states or wave functions \\\\\n    irreducible representation &  eigen states that give\n    different eigen values \\\\\n    reducible representation &  arbitrary wave functions\\\\\n    \\hline\n  \\end{tabular}\n\\end{center}\n\nBased on the table, let's make some explanations. The representations\nin the symmetry is similar to the wave functions in the quantum\nmechanics. They all provide the ``base'' to describe the target\nsystem. Besides, there's also another similarity between them. If the\nsymmetry operator is selected to be certain, then there are unlimit\nways to find a proper representation to express it, the coordinates,\nbasis functions, etc. In quantum mechanics, things is also\nanalogical. For the given operators, we can have unlimit ways to form\nthe wave functions; for example, for an given molecule we can use the\nplane wave functions, Gaussian type functions, Slater type of\nfunctions etc. to form the eigen states by the variational process.\n\nIn quantum mechanics, the physical quantity is abstracted as\n``operator'', while in symmetry we accordingly have the symmetry\noperator to express the abstract symmetry operations. If we gather the\noperators into a group in quantum mechanics (they all commuting with\nHamiltonian and actually form some freedom to portray the quantum\nsystem), it forms the CSCCO; and we can also get the related symmetry\noperations together to form the point group.\n\nHere, for the given operators, the wave functions is an arbitrary\nstate. It can be pure, so it's the eigen states for that given\noperator; or it can be mixture, thus can be expressed as linear\ncombination of the eigen states. things is also similar in symmetry.\nFor a given symmetry operator, an arbitrary representation can be\npure, that is the irreducible type of representation; or it can be\nmixture; thus it's the reducible representation which can be expressed\nas the sum of the irreducible representations.\n\nHere we note that the most important character for the irreducible\nrepresentations, is that they never mix with each other in the\nreducible ones. Similarly, in quantum mechanics we can see that the\neigen states that give different eigen values are also not mixing with\neach other in the expectation value for an arbitrary physical\nquantity.\n\nFor the given CSCCO, we can see that different representations are\nactually equivalent with each other. Similarly, for a given point\ngroup, we can also find the equivalent representations. That's another\nresemblance in the comparison.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Application of group theory in quantum chemistry}\n\n\\subsection{Operator for symmetry operation}\n%\n%\nAs we have known, the symmetry operations are some abstracted form\nwhich can be shaped into the matrices by introducing the\n``representations'' to express them. Such representations can be\ncoordinates, functions, or even the wave functions, molecule orbitals,\nconfigurations or the basis sets. If the representation is the wave\nfunctions, it's natural to see the symmetry operation can be expressed\nas the operator which is working on the wave functions (however,\nspecifically to say these operators are still the matrix form). In the\ncontent below, these operators will be labeled as $\\hat{O}_{R}$, and\nwe will going to discussion some detailed properties related to them.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Invariance of Hamiltonian operator under $\\hat{O}_{R}$}\n%\n%  \n%\nIn quantum chemistry, it's usually employing the Hamiltonian operator\nunder the Born-Oppenheimer approximation. Under this condition, the\natom nucleus are treated as some kind of ``classical'' objects which\ncan retain the position and trajectory ( that's the base for\nconstructing the potential energy hyper-surface, which is important in\nunderstanding the chemical phenomenon), and electrons are depicted by\nthe wave functions which is able to respond simultaneously to the\nposition change of atom nucleus.\n\nOn the other hand, under the Born-Oppenheimer approximation the atom\nnucleus still possess the identity character, that means the same kind\nof atom nucleus can not distinguish with each other. Hence, if there's\nsome movement(rotation, reflection, inversion etc.) which transform\nthe old atom skeleton to another, however the newer one can not\ndistinguish with the older one because of the identity character; then\nit's natural to see the Hamiltonian operator should keep to be\nsame. In a sense, it can say that the operators formed by the symmetry\noperation is commuting with the Hamiltonian operator, or the\nHamiltonian operator is irreducible and having the type of $A_{1}$ (since\nit's invariant to all the symmetry operations, then it must give the\ncharacter of $+1$). The mathematical demonstration can be found in\nBishop's book\\cite{Bishop} ( for the common Hamiltonian operator, the\nconclusion holds true, too).\n\nThis conclusion can be extended to any other physical operators because of the\nsimilar reason. Hence the symmetry operator are able to commute with any\nphysical operator, in other words it means that all the physical operators is\nirreducible and belong to $A_{1}$ representation.\n\nAll in all, we can express the above idea as:\n\\begin{equation}\\label{GROUPeq:6}\n  \\hat{O}_{R}\\hat{H}\\Psi = \\hat{H}\\hat{O}_{R}\\Psi = E(\\hat{O}_{R}\\Psi)\n\\end{equation}\nSuggest that the $\\Psi$ is some normalized wave function, and has no\ndegeneracy; then it can known that $\\hat{O}_{R}\\Psi$ and $\\Psi$ should\nonly differentiate by no more than a constant. Therefore, the\nrepresentation for the $\\Psi$ is only one dimensional matrix, it's\nirreducible.\n\nIt's easy to see that such constant is only $\\pm 1$. Suggest that\n$\\hat{O}_{R}\\Psi = a\\Psi$, then the orthogonality of the wave function\nof $\\hat{O}_{R}\\Psi$ will give that $a^{2}\\langle\\Psi|\\Psi\\rangle =\n1$, then $a$ could only be $\\pm 1$.  That's why in the last section,\nwhen we introduce the Mulliken rules, the characters for the one\ndimensional matrix (in the discussion of symbol $A$, $B$, $'$, $''$,\n$1$, $2$ etc.) is only considered to be $+1$ or $-1$ (in implies that the wave\nfunction retain its sign or change it sign).\n\nOn the other hand, if there's a series of $\\Psi_{i}$\n($i=1,2,\\cdots,n$) occupying the same energy level; then for the\nenergy of $E$ it constitutes some subspace. In this case, we can only\nassociate $\\hat{O}_{R}\\Psi_{i}$ with an $n$ dimensional matrix:\n\\begin{equation}\\label{}\n  \\hat{O}_{R}\\Psi_{i} = \\sum_{j}^{n}a_{ij}\\Psi_{j} \\quad\n  j=1,2,\\cdots,n\n\\end{equation}\nThus the symmetry operator of $\\hat{O}_{R}$ correspond to some $n$\ndimensional matrix. Similarly to the non-degenerate case, such $n$\ndimensional matrices are irreducible; there is not strict proof to\ndemonstrate this point, but after many concrete study, it's proved to\nbe correct\\cite{XingLinKe}.\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{An Example}\n%\n%  \n%\nNow we are going to give some example to show how to understand what\nwe have discussed. Take $H2O$ molecule as an example, it has a point\ngroup of $C_{2v}$, then we use the $sto-3g$ basis sets to make a\nsingle point calculation for this molecule. Here below is the results\nrelated to the symmetry (from the Gaussian calculation log file):\n\\begin{center}\n\\begin{verbatim}\n Orbital symmetries:\n       Occupied  (A1) (A1) (B2) (A1) (B1)\n       Virtual   (A1) (B2)\n The electronic state is 1-A1.\n Alpha  occ. eigenvalues --  -20.23873  -1.24138\n -0.60350 -0.43450  -0.38430\n Alpha virt. eigenvalues --    0.55266   0.70934\n\\end{verbatim}\n\\end{center}\n\nIt can see that there are seven HF orbitals, each occupies an\nindividual energy level, thus they are seven irreducible\nrepresentations. From the character table for $C_{2v}$, there's $4$\nnon-equivalent irreducible representations, however; for the molecule\nof $H2O$ there only exist three of them.\n\nFrom the population results we can understand the Mulliken rules to\ndesignate the orbitals.\n\n\\begin{verbatim}\n     Molecular Orbital Coefficients\n                           1         2         3\n                        (A1)--O   (A1)--O   (B2)--O\n     EIGENVALUES --   -20.23873  -1.24138  -0.60350\n   1 1   O  1S          0.99422  -0.23485   0.00000\n   2        2S          0.02577   0.85001   0.00000\n   3        2PX         0.00000   0.00000   0.00000\n   4        2PY         0.00000   0.00000   0.59747\n   5        2PZ        -0.00379  -0.11014   0.00000\n   6 2   H  1S         -0.00555   0.15638   0.44528\n   7 3   H  1S         -0.00555   0.15638  -0.44528\n\n                           4         5\n                         (A1)--O   (B1)--O\n     EIGENVALUES --     -0.43450  -0.38430\n   1 1   O  1S          -0.09750   0.00000\n   2        2S           0.50656   0.00000\n   3        2PX          0.00000   1.00000\n   4        2PY          0.00000   0.00000\n   5        2PZ          0.78462   0.00000\n   6 2   H  1S          -0.28828   0.00000\n   7 3   H  1S          -0.28828   0.00000\n\n                           6         7\n                        (A1)--V   (B2)--V\n     EIGENVALUES --     0.55266   0.70934\n   1 1   O  1S         -0.12863   0.00000\n   2        2S          0.82482   0.00000\n   3        2PX         0.00000   0.00000\n   4        2PY         0.00000   0.98180\n   5        2PZ        -0.71063   0.00000\n   6 2   H  1S         -0.77310  -0.79848\n   7 3   H  1S         -0.77310   0.79848\n\\end{verbatim}\n\nFor instance, we can see how to judge the type for the HOMO. From the\ntable above it can see the HOMO is purely the O atom's $2PX$\norbital. Since that the $C_{2}$ axis will be oriented to the $Z$ axis,\nthen to rotate the $Z$ for $180$ degree leads to reverse the sign of\nthe $2PX$, thus it belongs to $B$ type orbital. Moreover, the mirror\nof $\\sigma_{v}$ vertical to the plane of $YZ$ does not alter the\n$2PX$, then it belongs to the $B_{1}$ type of orbital. The symbols for\nthe other orbitals can be derived in the similar way.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{$\\hat{O}_{R}$ Is Unitary Operator}\n%\n%  \n%\nIt's very interesting to compare the symmetry operators of  $\\hat{O}_{R}$ with\nthe unitary operators. Physically to say, unitary operators is some\noperators that transform one representation to another ( see\n\\ref{transformation_in_representation} and \\ref{OPERATOR:2}), the essence\nbehind the unitary operator is that the corresponding unitary transformation\ndoes not alter the character of wave function space (Hilbert space).\n\nFrom this point of view, the symmetry operator is also the unitary operators.\nThe symmetry operator is organized basically by reflection, rotation, inversion\netc. which does not change the inherent physical property of the system, thus\nthe any symmetry operators should commute with any physical operator in\nprinciple, especially for the Hamiltonian operator. Hence the symmetry\noperators only transform the wave functions into its linear combination, which\nworks as transform wave functions from one representation to another.\n\nNow let's discuss the algorithms for the $\\hat{O}_{R}$. As a unitary operator,\nit's also the linear operator; hence it satisfy:\n\\begin{equation}\n \\hat{O}_{R} (A \\pm B) =  \\hat{O}_{R} A \\pm \\hat{O}_{R} B\n\\label{algorithm_O_R_eq:1}\n\\end{equation}\nHere $A$ and $B$ can be any physical operators or the wave functions (MO,\nSlater determinant, or wave functions etc.) What's more, it's very important to\nconsider that how to express the $\\hat{O}_{R}(AB)$.\n\nLet's firstly put forward some examples to show its importance. The first\nexample is that how to determine the Slater determinant's character from the\nMO. It's known that Slater determinants are formed by organizing a number of\nselected MO into determinant, which can be expressed as:\n\\begin{equation}\n \\Phi = \\sum_{1\\leq i_{1} \\leq i_{2} \\leq \\cdots \\leq i_{n}}\n(-1)^{P(i_{1}i_{2}\\cdots\ni_{n})}\\psi_{i_{1}}(1)\\psi_{i_{2}}(2)\\cdots\\psi_{i_{n}}(n)\n\\end{equation}\nAccording to (\\ref{algorithm_O_R_eq:1}) the symmetry operators are linear, so\nthe algorithm for $\\hat{O}_{R}(\\psi_{i_{1}}\\psi_{i_{2}}\\cdots\\psi_{i_{n}})$\ndetermines the character of corresponding Slater determinant.  \n\nThe second example, is the integral of\n$\\bra{\\Psi}\\hat{O}\\ket{\\Phi}$, which can be considered as a summation between\n$\\Psi$ and $\\hat{O}\\ket{\\Phi}$ for all the $r$ in the space. Hence similar to\nthe above example the integral is also determined\nby $\\hat{O}_{R}(\\Psi\\hat{O}\\Phi)$.\n\nNow let's go to prove the fact below: \n\\begin{equation}\n \\hat{O}_{R} (AB) =  (\\hat{O}_{R} A) (\\hat{O}_{R} B)\n\\label{algorithm_O_R_eq:2}\n\\end{equation}\n$A$ and $B$ can be arbitrary operators or wave functions.\n\nFirstly, if $A$ and $B$ are two physical operators, then since they are the\n$A_{1}$ representation for given $\\hat{O}_{R}$, the above fact holds true.\nSecondly, if $A$ is the operator and $B$ is the wave function, then we have:\n\\begin{equation}\n\\hat{O}_{R} (AB) =  A (\\hat{O}_{R} B) = (\\hat{O}_{R} A) (\\hat{O}_{R} B)\n\\end{equation}\nSince $A$ is $A_{1}$ representation. Finally, for two wave functions, the\nsymmetry transformation on them naturally equal to the process that the symmetry\ntransformation is done on each wave function, so the fact declared in\n(\\ref{algorithm_O_R_eq:2}) is true.\n\nThrough the similar manner, the result in (\\ref{algorithm_O_R_eq:2}) can be\nextended to $n$th order multiplication:\n\\begin{equation}\n \\hat{O}_{R} (ABC\\cdots) =  (\\hat{O}_{R} A) (\\hat{O}_{R} B) (\\hat{O}_{R} C)\n\\cdots\n\\label{algorithm_O_R_eq:3}\n\\end{equation}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Direct Product}\n%\n% 1 definition for the direct product 2 how to express the\n% representations for the direct product?\n%\n%\nDirect product is some mathematical algorithm between two matrices, or\nmore generally, the algorithm between two functional space. If we have\ntwo functional space:\n\\begin{align}\\label{}\n  & f_{1}, f_{2}, \\cdots, f_{n} \\nonumber \\\\\n  & g_{1}, g_{2}, \\cdots, g_{m}\n\\end{align}\nHere we note that it's unnecessary to require that $n=m$. Then the\ndirect product rule will give some new functional space of $K$:\n\\begin{equation}\\label{}\n  K = F\\otimes G\n\\end{equation}\nWhile the $K$ can be expressed as:\n\\begin{align}\\label{}\n  & f_{1}g_{1}, f_{1}g_{2}, \\cdots, f_{1}g_{m} \\Rightarrow f_{1}G \\nonumber \\\\\n  & f_{2}g_{1}, f_{2}g_{2}, \\cdots, f_{2}g_{m} \\Rightarrow f_{2}G \\nonumber \\\\\n  & \\cdots      \\cdots     \\cdots \\nonumber \\\\\n  & f_{n}g_{1}, f_{n}g_{2}, \\cdots, f_{n}g_{m} \\Rightarrow f_{n}G\n\\end{align}\nTherefore, $K$ is $n\\times m$ dimensional. Equally it can see that $K$\nis can be also expressed as $G\\otimes F$, where we have $g_{i}F$ form.\n\nFor the matrices, we can also derive the direct product:\n\\begin{align}\\label{}\n  \\begin{bmatrix}\n    A_{11} & A_{12} & \\cdots & A_{1n} \\\\\n    A_{21} & A_{22} & \\cdots & A_{2n} \\\\\n    \\cdots & \\cdots & \\cdots & \\cdots \\\\\n    A_{n1} & A_{n2} & \\cdots & A_{nn} \\\\\n  \\end{bmatrix}\n  \\otimes\n  \\begin{bmatrix}\n    B_{11} & B_{12} & \\cdots & B_{1m} \\\\\n    B_{21} & B_{22} & \\cdots & B_{2m} \\\\\n    \\cdots & \\cdots & \\cdots & \\cdots \\\\\n    B_{m1} & B_{m2} & \\cdots & B_{mm} \\\\\n  \\end{bmatrix} = \\nonumber \\\\\n  \\begin{bmatrix}\n    A_{11}B & A_{12}B & \\cdots & A_{1n}B \\\\\n    A_{21}B & A_{22}B & \\cdots & A_{2n}B \\\\\n    \\cdots & \\cdots   & \\cdots & \\cdots  \\\\\n    A_{n1}B & A_{n2}B & \\cdots & A_{nn}B \\\\\n  \\end{bmatrix}\n\\end{align}\nHere the element of $A_{ij}B$ has such form:\n\\begin{equation}\\label{}\n  A_{ij}B =\n  \\begin{bmatrix}\n    A_{ij}B_{11} & A_{ij}B_{12} & \\cdots & A_{ij}B_{1m} \\\\\n    A_{ij}B_{21} & A_{ij}B_{22} & \\cdots & A_{ij}B_{2m} \\\\\n    \\cdots &       \\cdots & \\cdots &       \\cdots \\\\\n    A_{ij}B_{m1} & A_{ij}B_{m2} & \\cdots & A_{ij}B_{mm} \\\\\n  \\end{bmatrix}\n\\end{equation}\nThus it can see that the direct product between the matrices is\nvirtually the same to the definition in the functional space.\n\nLet's go back to quantum chemistry. here we have a question that why we\ndiscuss the direct product? Actually, it can be observed that the Fock matrix or\nthe Hamiltonian matrix is the direct product between the basis functions in\nthe bra and ket (if it's Fock matrix, then the basis function is basis sets for\nMO, if it's Hamiltonian matrix then the basis function is Slater determinants).\n\nNow let's go to see how to express the representation for the direct\nproduct. We can prove that if $K = F\\otimes G$, then $\\hat{O}_{R} (K)\n= \\hat{O}_{R}(F)\\otimes \\hat{O}_{R}(G)$. From the above discussion, we have\nknown that the element in the representation related to the function space\nof $F\\otimes G$ can be expressed as $f_{i}g_{j}$, where the label of\n$i$ and $j$ are arbitrary. Thus if the symmetry operation is on it,\naccording to the (\\ref{algorithm_O_R_eq:3}) we can have:\n\\begin{align}\\label{}\n  \\hat{O}_{R}(f_{i}g_{j}) &= (\\hat{O}_{R}f_{i})(\\hat{O}_{R}g_{j})\n  \\nonumber \\\\\n  &=(\\sum_{p}^{n}D^{f}_{ip}(R)f_{p})(\\sum_{q}^{m}D^{g}_{jq}(R)g_{q})\n  \\nonumber \\\\\n  &=\\sum_{p}^{n}\\sum_{q}^{m}D^{f}_{ip}(R)D^{g}_{jq}(R)f_{p}g_{q}\n\\label{symmetry_QC_direct_product_eq:1}\n\\end{align}\nHence $\\sum_{p}^{n}\\sum_{q}^{m}D^{f}_{ip}(R)D^{g}_{jq}(R)$ indicates that it's\ntwo vector space direct product. Furthermore, for the giving $F\\otimes G$ matrix\n(the above example is only its one matrix element), the direct product between\ntwo vector space will be evolved to be direct product between two matrix. That\nis:\n\\begin{equation}\n   D^{F \\otimes G}(R) = D^{F}(R)\\otimes D^{G}(R)\n\\label{symmetry_QC_direct_product_eq:2}\n\\end{equation}\nThis is the final result. \n\nHowever, usually in the application what we use is only character, so the\nresult for the (\\ref{symmetry_QC_direct_product_eq:2}) is:\n\\begin{align}\\label{symmetry_QC_direct_product_eq:3}\n  \\chi^{F\\otimes G}(R) &=\n  \\sum_{p}^{n}\\sum_{q}^{m}D^{F}_{pp}(R)D^{G}_{qq}(R) \\nonumber \\\\\n  &=\\chi^{F}(R)\\chi^{G}(R)\n\\end{align}\nThis can be extended to $n$th order multiplication.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Vanishing Integrals}\n%\n% 1 integral is the direct product for the $\\Phi$, $\\Psi$ and\n% $\\hat{A}$ 2 prove the lemma 3 prove the theorem\n%\nNow let's begin to analyze the integrals, from the sections above, we know\nthat: \n\\begin{align}\\label{vanishing_int}\n  \\hat{O}_{R}(\\bra{\\Phi_{i}}\\hat{A}\\ket{\\Psi_{j}}) &=\n\\bra{\\hat{O}_{R}(\\Phi_{i})}\\hat{O}_{R}(\\hat{A})\\ket{\\hat{O}_{R}(\\Psi_{j})}\n\\nonumber \\\\\n&= \\int(\\hat{O}_{R}\\Phi^{*}_{i})\\hat{A}(\\hat{O}_{R}\\Psi_{j})d\\tau\n\\end{align}\nNow let's evaluate the condition that when the integrals vanishes.\n\nFirstly let's give some lemma before the proof. For two irreducible\nrepresentations of $a$ and $b$, we can prove that it's only they\nbelong to the same kind of irreducible representations, then their\ndirect product can have the $A_{1}$ type of representation.\n\nAccording to the (\\ref{GROUPeq:1}), we can see that:\n\\begin{align}\\label{GROUPeq:17}\n  a_{A_{1}} &= \\frac{1}{g}\\sum_{R}\\chi_{ab}(R)\\chi_{A_{1}} \\nonumber\n  \\\\\n  &=\\frac{1}{g}\\sum_{R}\\chi_{ab}(R)\n\\end{align}\nHere we note that for any $R$ the $\\chi_{A_{1}}(R) = 1$.\n\nOn the other hand, according to the (\\ref{symmetry_QC_direct_product_eq:3}) we\nhave the expression of $\\chi_{ab}(R) = \\chi_{a}(R)\\chi_{b}(R)$ ; then we can\nrewrite the (\\ref{GROUPeq:17}) as:\n\\begin{align}\\label{}\n  a_{A_{1}} &= \\frac{1}{g}\\sum_{R}\\chi_{a}(R)\\chi_{b}(R) \\nonumber\n  \\\\\n  &=\\frac{1}{g}\\delta_{ab}\n\\end{align}\nTherefore in the direct product, whether the $A_{1}$ representation\npresents is decided by whether the two irreducible representations are\nequivalent. So we have proved this lemma.\n\nNext, we are going to push this lemma further. In the expectation\nvalue defined in the (\\ref{vanishing_int}), if the $A_{1}$ representation\ndoes not occur, then the integral is zero.\n\nNow suggest the integral is not zero:\n$\\bra{\\Phi_{i}}\\hat{A}\\ket{\\Psi_{j}} = c$. Then we also suggest that\n$\\Phi_{i}$ and $\\Psi_{j}$ are two different irreducible\nrepresentations. This implies that we can find two symmetry operations\nof $\\hat{O}_{R}$ and $\\hat{O}_{R^{'}}$, which satisfy:\n\\begin{align}\\label{}\n  \\hat{O}_{R}\\Phi_{i} = k\\Phi_{i} &\\quad \\hat{O}_{R}\\Psi_{j}=l\\Psi_{j}\n  \\nonumber \\\\\n  \\hat{O}_{R^{'}}\\Phi_{i} = m\\Phi_{i} &\\quad \\hat{O}_{R^{'}}\\Psi_{j}\n  =n\\Psi_{j}\n\\end{align}\nAnd most importantly it has $kl \\neq mn$. Therefore, we can see that\nif $\\hat{O}_{R}$ and $\\hat{O}_{R^{'}}$ are separately applied on the\nintegrals, it gives:\n\\begin{equation}\\label{}\n  klc \\neq mnc\n\\end{equation}\nHowever, it contradicts the conclusion that the symmetry operation\ndoes not alter the expectation value of an physical quantity. Thus the\nintegral can only be zero.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n%%% Local Variables: \n%%% mode: latex\n%%% TeX-master: \"../../main\"\n%%% End: \n", "meta": {"hexsha": "3ca527287c1a300c21d0c25930112f26f485f599", "size": 88492, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "theory/chemistry/groups.tex", "max_stars_repo_name": "murfreesboro/fenglai-note", "max_stars_repo_head_hexsha": "7bdf943f681e54948cd68775a31e4c93a53a13f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-16T07:23:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T07:23:48.000Z", "max_issues_repo_path": "theory/chemistry/groups.tex", "max_issues_repo_name": "murfreesboro/fenglai-note", "max_issues_repo_head_hexsha": "7bdf943f681e54948cd68775a31e4c93a53a13f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "theory/chemistry/groups.tex", "max_forks_repo_name": "murfreesboro/fenglai-note", "max_forks_repo_head_hexsha": "7bdf943f681e54948cd68775a31e4c93a53a13f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.2300928188, "max_line_length": 117, "alphanum_fraction": 0.692152963, "num_tokens": 25691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3156939806757173}}
{"text": "\\subsection{Point of view of this thesis}\n\nThis work is based on the idea that the accurate numerical solution of hyperbolic problems relies on robust and efficient discretization techniques and the ability to embed information about some particular solution of the model into the numerical scheme.\nThe underlying concepts arise from the Godunov method \\cite{Godunov_method} that first proposed to account for the characteristic structure of the solution of hyperbolic problems within numerical schemes.\nThis approach, as we shall see later, enables significant improvements over some other methods.\nAlthough the amount of information provided is limited by the computational cost, new model reduction tools can now allow to \"compress\" the amount of information and, in turn, to reconsider the use of more complex Riemann solvers in order to improve the accuracy of numerical solutions.\n\nTwo scientific objectives have therefore been pursued in the present work:\n\\begin{itemize}\n\\item \\textbf{the development of a promising discretization for solid mechanics problems involving finite deformations}\n\\item \\textbf{the identification of the response of two-dimensional elastic-plastic solids to dynamic step loading}\n\\end{itemize}\n\n\\subsection{The strategy adopted}\n%In the present manuscript, a numerical method for applications in solid mechanics aiming at benefiting from the schemes mentioned in the previous section is developed.\n%% Lagrangian\nFirst, the numerical scheme developed here provides a material description of the motion so as to handle history-dependent constitutive models while avoiding the shortcomings of ALE and Eulerian methods.\n%% Meshfree\nIn addition, in order not to suffer from mesh entanglement, it seems better to turn to a mesh-free method.\n%% DG approximation\nThis method is wanted to mimic the physics of hyperbolic problems by accounting for their intrinsic structure.\n\n%% MPM + DG\nIt is therefore proposed here to mix the above features by extending the material point method to the Discontinuous Galerkin approximation.\n%% Pourquoi pas SDG ou TDG\nThe Discontinuous Galerkin approximation provides an appealing framework for describing moving discontinuities such as waves propagating in solids, and the potential ability of increasing approximation order.\nMoreover, the numerical fluxes naturally arising from the use of DG approximation introduces the characteristic structure on the one hand, and takes advantage of the work done in the context of finite volumes on the other hand.\n%% Pourquoi MPM\n%Furthermore, the use of an arbitrary grid motivates the choice of the MPM due to the convenience it allows in computing the numerical fluxes at finite elements interfaces by means of an approximate Riemann solver \\cite{Toro}.\nFurthermore, the use of an arbitrary grid motivates the choice of the MPM due to the convenience it allows in computing the numerical fluxes at the interfaces between finite elements by means of an approximate Riemann solver \\cite{Toro}.\n%% Réduire la diffusion de la pic grace à DG\nA balance between diffusion and oscillations exists in PIC methods in such a way that there is some freedom in regard to the MPM setting used.\nIt is however thought here that the use of DG approximation leads to a reduction of the influence domain of the particles and hence, to a reduction of the numerical diffusion. \nTherefore, it is preferred here to avoid oscillations at the risk of introducing diffusion, which should be limited by the DG approximation.\nAs a first development step of \\textbf{the Discontinuous Galerkin Material Point Method}, we restrict our attention to space-DG.\nAt last, particular attention is paid here to discontinuous solutions, the extension of the method to higher-order approximation for regular ones will be the purpose of future works.\n\n%% Travail sur la modélisation des écoulements plastiques en 2D\nThe approach described previously should be able to account for the characteristic structure of hyperbolic problems.\nIndeed, the point of view adopted here is that a numerical scheme can properly mimic the solution providing that a sufficient amount of information about the model is available.\nNonetheless, it is not the case for all the constitutive models considered in this work.\nMore specifically, while the response of one-dimensional elastoplastic solids is well-known, there are some lacks in describing the behavior of such materials in more dimensions. \nAs a consequence, the characteristic structure of the solution of hyperbolic problems in elastic-plastic solids under small strains is also investigated in the present work.\nThis preliminary work is expected to pave the way for the solution of similar problems within the large deformations framework.\n% Under small strains\n\n\n\n\n\n\n%%% Local Variables:\n%%% mode: latex\n%%% ispell-local-dictionary: \"american\"\n%%% TeX-master: \"../mainManuscript\"\n%%% End:\n\n", "meta": {"hexsha": "69f8e651ab922cf6e5e822919d23e061dd3b4fd7", "size": 4899, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "manuscript/chapter1/contributions.tex", "max_stars_repo_name": "adRenaud/research", "max_stars_repo_head_hexsha": "2f0062a1800d7a17577bbfc2393b084253d567f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-18T14:52:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-18T14:52:03.000Z", "max_issues_repo_path": "manuscript/chapter1/contributions.tex", "max_issues_repo_name": "adRenaud/research", "max_issues_repo_head_hexsha": "2f0062a1800d7a17577bbfc2393b084253d567f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-01-07T13:11:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-07T13:11:11.000Z", "max_forks_repo_path": "manuscript/chapter1/contributions.tex", "max_forks_repo_name": "adRenaud/research", "max_forks_repo_head_hexsha": "2f0062a1800d7a17577bbfc2393b084253d567f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 84.4655172414, "max_line_length": 286, "alphanum_fraction": 0.8175137783, "num_tokens": 954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3156939732931831}}
{"text": "\\documentclass[a4paper,10pt]{article}\n\\usepackage[utf8x]{inputenc}\n\\usepackage{amssymb,amsmath,amsthm}\n\\usepackage{hyperref}\n\\usepackage{cleveref}\n\n% For Python syntax highlighting.\n\\usepackage{minted}\n\n\\usepackage[margin=1.0in]{geometry}\n\n\n% For testing wether an argument of a macro is empty.\n\\usepackage{xifthen}\n\\usepackage{bm}\n\n% Figures and subfigures.\n\\usepackage{subfig}\n\\usepackage{graphicx}\n\n\\newcommand{\\dl}{\\mathrm{d}\\lambda}\n\\setlength{\\parindent}{0cm}\n\n%opening\n\\title{Development Journal and Specs of the MESLAS package\n}\n\n% \\input{macros}\n\\input{macros}\n\n\\begin{document}\n\\maketitle\n\n\\section{General Considerations}\nThe MESLAS package (\\textbf{M}ulti-variate \\textbf{E}xcursion \\textbf{S}et \\textbf{L}earning by \\textbf{A}daptive \\textbf{S}ampling) is a toolbox for simulation and prediction of mulitivariate Gaussian random fields.\\\\\n\nThe setup of the package is the following: $\\gp$ is a $\\no$-dimensional random\nfield on a domain $\\nd$-dimensional\ndomain $D$.\n\nOur philosophy is to always specify spatial location and response indices\ntogether. That is, one should always specify \\textbf{where} and \\textbf{what}.\n\nSpatial locations are denoted by $s$ and response indices by $\\ell$. We will\nuse boldface (or, in the code, alternatively uppercase or plurals) to denote\nvectors of such objects.\n\n\\medskip\nA generalized sampling location is thus entirely defined by specifying two vectors\n\\begin{align*}\n    \\bm{s} &= \\left(s_1, ..., s_n\\right)\\in D^n\\\\\n    \\bm{\\ell} &= \\left(\\ell_1, ..., \\ell_n\\right) \\in \\lbrace 1, ..., \\no\n    \\rbrace^n\n\\end{align*}\nWe will refer to $n$ as the \\textit{dimension} of the generalized sampling\nlocation and usually just talk of location, using the word \\textit{spatial\nlocation} when we want to specifically refer to points in $D$. Also, we will\nuse boldface $x$ as a shortcut to refer to the couple $\\left(\\bm{s},\n\\bm{\\ell}\\right)$ of spatial location vector and response index vector.\nThe shortcut notation $\\gp[\\bm{x}]$ thus refers to the\nvector\n\\[\n    \\gp[\\bm{x}]:=\\left(\\gp[s_1]^{\\ell_1}, ..., \\gp[s_n]^{\\ell_n}\\right) \\in\n    \\mathbb{R}^n.\n\\]\n\n\\subsection{Covariance Model}\nWe assume a factor model which is the product of a stationary spatial component\nwith a response-index component\n\\begin{equation}\n    \\textrm{Cov}\\left(\\gp[s]^i, \\gp[t]^j\\right) = k\\left(s - t\\right)\n    \\gamma\\left(i, j\\right).\n\\end{equation}\n\nThis makes implementation easier, since then, to compute the covariance matrix\nof a generalized observations $\\left(S, L\\right)$, we first compute the\npairwise distance matrix\n\\[\n    H = \\textrm{cdist}\\left(S,S, p=2\\right) = \\begin{pmatrix}\n        ||s_1 - s_1|| & \\dots & ||s_1 - s_n||\\\\\n        \\vdots &  & \\vdots \\\\\n        ||s_n - s_1|| & \\dots & ||s_n - s_n||\\\\\n    \\end{pmatrix}\n\\]\nwhich can then be feeded to a vectorized stationary covariance function to get\n$K(H)$.\n\nFor the response index part, we compute $L_1, L_2=\\textrm{meshgrid}\\left(L,\nL\\right)$ which yields\n\\begin{align*}\n    L_1 =  \\begin{pmatrix}\n        l_1 & \\dots & l_1\\\\\n        \\vdots &  & \\vdots \\\\\n        l_n & \\dots & l_n\\\\\n    \\end{pmatrix}\n    &,~ \n    L_2 =  \\begin{pmatrix}\n        l_1 & \\dots & l_n\\\\\n        \\vdots &  & \\vdots \\\\\n        l_1 & \\dots & l_n\\\\\n    \\end{pmatrix}\n\\end{align*}\nand then feed it to a vectorized cross-covariance function $\\gamma(L_1, L_2)$.\nFinally, we get the covariance matrix by elementwise multiplication\n\\[\n    K = K\\left(H\\right) \\odot \\gamma\\left(L_1, L_2\\right)\n\\]\n\n\\subsection{Cross-Covariance Models}\nWe here review different usual models for the cross-covariance part $\\gamma(.,\n.)$ of the covariance function. Recall that this is the part that specifies how\ndifferent components of the response vector at one fixed location interact.\n\n\\medskip\nThe simplest model we will consider is \\textbf{uniform mixing}. In this model,\nall components interact with the same coupling $\\gamma_0$:\n\\begin{equation}\n    \\gamma(l, m) = \\begin{cases} \\sigma_l^2,~ l=m\\\\ \n        \\gamma_0\\sigma_l\\sigma_m,~l\\neq m\n    \\end{cases}\n\\end{equation}\nand $\\sigma_1^2, ..., \\sigma_{\\no}^2$ are the variances of the individual\ncomponents.\n\n\\subsection{Implementation Details}\nATTENTION: torch.meshgrid behaves differently than numpy's one.\nFirst of all, it takes single dimensional vectors.\n\\[\n    L=(1,2,3,4),~ \\textrm{torch.meshgrid}(L,L)=\n    \\begin{pmatrix}\n        1 & \\dots & 1\\\\\n        \\vdots &  & \\vdots \\\\\n        n & \\dots & n\\\\\n    \\end{pmatrix}\n    ,~ \n    \\begin{pmatrix}\n        1 & \\dots & n\\\\\n        \\vdots &  & \\vdots \\\\\n        1 & \\dots & n\\\\\n    \\end{pmatrix}\n\\]\n\n\\subsection{Mean Module}\n\\subsection{Covariance Module}\n\\subsection{Gaussian Random Field Class and Sampling}\n\\subsection{Gridding}\n\n\\newpage\n\n\\section{Example Run}\nWe consider a $2$-dimensional GRF on a a $2$-dimensional $100\\times 100$ regular grid on\n$[0,1]^2$. The GRF has a factor covariance model, where the spatial part is a\nMat\\'{e}rn $3/2$ with unit variance and lengthscale $\\lambda_0 = 0.1$. The\ncross-covariance is a uniform mixing with parameters\n\\[\n    \\sigma_1^2 = 0.25,~\\sigma_2^2 = 0.6, \\gamma_0 = 0.3\n\\]\nand the mean function is a constant one with $\\mu_0=(1, -2)$.\n\\medskip\n\nThe plot below shows one realization of the field on the full grid.\n\\begin{figure}[tbh!p]\n\\centering\n\\includegraphics[scale=0.65]{images/sample_low_correlation.png}\n\\caption{Simulated first (left) and second (right) component of the field.}\n\\end{figure}\n\nWe can also increase the cross-correlation factor $\\gamma_0$ to $0.9$ to see\nits effect.\n\\begin{figure}[tbh!p]\n\\centering\n\\includegraphics[scale=0.65]{images/sample_high_correlation.png}\n\\caption{Simulation of highly cross-correlated field.}\n\\end{figure}\n\n\\newpage\nThe code below shows how simple it is to sample a multivariate GRF using MESLAS.\n\\usemintedstyle{tango}\n\\inputminted{python}{example_sample.py}\n\n\\section{Co-Kriging}\nCokriging is also implemented in full generality (heterotopic) in MESLAS. The package also provides conditional simulations. Plots below show an example of cokriging and conditional simulation. The GRF is the same as in the previous section, with a high cross-correlation $\\gamma_0=0.9$.\n\n\\begin{figure}[tbh!p]\n\\centering\n\\subfloat[Conditional mean]{\\includegraphics[scale=0.6]{images/cond_mean_high_corr.png}}\\\\\n\\subfloat[Conditional realisation]{\\includegraphics[scale=0.6]{images/cond_realisation_high_corr.png}}\n\\caption{Example of co-kriging a 2-dimensional GRF with MESLAS, observation locations in red.}\n\\label{fig:example_inv_prob}\n\\end{figure}\n\n\\newpage\n\n\\section{Coverage Function}\nWe compute the $p$-dimensional CDF using the MVNORM package of Sebastion Marmin. We re-packaged it for streamlined distribution via PiPy. The implementation is $3$ times faster than barebone PyTorch (in dimension 2). It is also vectorized over the batch dimension.\n\n\\subsection{Illustrations}\nThe agreed-upon goal was to produce plots to illustrate multivariate excursion\nsets vs univariate.\n\nI suggest we do that by trying to replace figure 4 in the paper.\nSo: sample unconditionally, illustrate various excursions, krig using this\nrealisation, plot coverages.\n\n\\begin{figure}[tbh!p]\n\\centering\n\\subfloat[Simulated Realisation]{\\includegraphics[scale=0.6]{images/Figure4/cond_realisation.png}}\\\\\n\\subfloat[Cokriging Mean (observation locations in red)]{\\includegraphics[scale=0.6]{images/Figure4/cond_mean.png}}\\\\\n\\subfloat[Coverage Function]{\n\t\\includegraphics[scale=0.45]{images/Figure4/salinity_excu.png}\n\t\\includegraphics[scale=0.45]{images/Figure4/temperature_excu.png}\n\t\\includegraphics[scale=0.45]{images/Figure4/joint_excu.png}}\n\\caption{Diagnostics of problems in computation of the coverage function.}\n\\label{fig:example_inv_prob}\n\\end{figure}\n\n\\newpage\n\\section{Discrete Setup}\n\n\\subsection{Variance Reduction}\nThe plot clearly demonstrates that the implementation is correct (see the variance reduction of unobserved components due to correlations).\n\n\\begin{figure}[tbh!p]\n\\centering\n\t\\includegraphics[scale=0.8]{images/variance_reduction.png}\n\\caption{Variance reduction caused by hypothetical measurements at the (generalized) locations in red.}\n\\end{figure}\n\n\\subsection{EIBV Criterion}\nThe plot below demonstrates computation of the EIBV criterion on the whole design grid. The steps are the following.\n\\begin{itemize}\n  \\item First a ground truth is generated by sampling from the GRF model.\n  \\item Then some data is collected (here 9 data points, following a straight northwards route).\n  \\item The data is used to compute kriging mean and covariances.\n  \\item Given those quantities, the EIBV criterion is computed for each point of the design grid, to determine which locations might be interesting for the next data collection steps.\n\\end{itemize}\n\nThe discretization used here is an equilateral tringular grid, with 25 nodes along one dimension (740 nodes in total). The small number of nodes gives rise to artifacts when projecting the observations locations to the grid and when plotting.\n\n\\begin{figure}[tbh!p]\n\\centering\n\\subfloat[Ground truth (observation locations in red)]{\n\\includegraphics[scale=0.75]{images/eibv_whole_design/ground_truth.png}}\\\\\n\\subfloat[Kriging mean]{\n\t\\includegraphics[scale=0.75]{images/eibv_whole_design/kriging_mean.png}}\\\\\n\\subfloat[True excursion, current estimated excursion and EIBV criterion. (red where both excursion conditions are satisfied, white if only one).]{\n\t\\includegraphics[scale=0.5]{images/eibv_whole_design/true_excursion.png}\n\t\\includegraphics[scale=0.5]{images/eibv_whole_design/estimated_excursion.png}\n\t\\includegraphics[scale=0.51]{images/eibv_whole_design/eibv.png}\n\t}\n\\caption{Example of computation of EIBV criterion on whole grid.}\n\\label{fig:example_inv_prob}\n\\end{figure}\n\n\\newpage\n\\section{Hardware/Software Specifications}\nThe AUV feature a Nvidia TX1 with ubuntu 16.04. Current programs use Python\n2.7, but 3.7 can be used.\nIn order to run 3.7, we have to run\nanother backseat-driver (responsible for sending waypoints to the low-leve\ncontrollers).\n\n\n\\end{document}\n", "meta": {"hexsha": "29f53a1da7a451b7595c937325d61a1a55321835", "size": 9987, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc_source/Tex/DEV_Journal.tex", "max_stars_repo_name": "CedricTravelletti/MESLAS", "max_stars_repo_head_hexsha": "362c7f13c5f3d7261e7603920c22429275a4958b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc_source/Tex/DEV_Journal.tex", "max_issues_repo_name": "CedricTravelletti/MESLAS", "max_issues_repo_head_hexsha": "362c7f13c5f3d7261e7603920c22429275a4958b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc_source/Tex/DEV_Journal.tex", "max_forks_repo_name": "CedricTravelletti/MESLAS", "max_forks_repo_head_hexsha": "362c7f13c5f3d7261e7603920c22429275a4958b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6867924528, "max_line_length": 287, "alphanum_fraction": 0.7419645539, "num_tokens": 2906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.31569397329318305}}
{"text": "\n\\title{Deep Learning Project 1}\n\\author{\n        Pranav A (20478966) \\\\\n        Big Data Institute\\\\\n        Hong Kong University of Science and Technology\n}\n\\date{\\today}\n\n\\documentclass[12pt]{article}\n\\usepackage{graphicx}\n\\usepackage{booktabs}\n\\usepackage{cite}\n\\begin{document}\n\\maketitle\n\n\\begin{abstract}\nIn this project, I have used logistic regression and multilayer perceptron as the classification of the data points.\nAt the end, two-layered multilayer perceptron outperformed than linear regression, achieving an accuracy of 97.3\\% on the validation set.\nHowever, the multilayer perceptron was overfitting before converging completely due to its complex architecture.\n\\end{abstract}\n\n\\section{Introduction}\nLogistic regression is the most straightforward way to do classification.\nThis is visualized as the weighted-sum of the features to produce the best output.\nThis can also be thought of as a multilayer perceptron with no hidden layers.\n\nMLP (Multilayer perceptron)  is the most fundamental forms of the artificial neural networks.\nMLP introduces non-linearity through activation functions and extra layers to produce complex decision boundaries.\n\nIn this project, I have used these two techniques on the provided dataset.\n\n\\section{Experimental Setup}\nThe dataset comprises of 57 features with around 3220 items.\nSince MLP are prone to overfitting, I have divided the dataset into traning and validation sets.\nThe training set comprises of 3000 items and the validation sets uses 220 items.\n\nI have used Pytorch \\cite{paszkepytorch} for developing this MLP architecture.\n\nFor logistic regression, I have used no hidden layers.\nThus the problem of MLP reduces down to just logistic regression.\nThen I used Stochastic Gradient Descent, with a batch size of 128 and learning rate of 0.001.\nFinally I used Cross-Entropy loss function with softmax as the output.\n\nTo generate a learning curve, at every iteration I plotted the loss and accuracy for training and validation set.\n\nFor multilayer perceptron, I have used two hidden layers.\nBoth hidden layers contain 64 neurons.\nI have used Adam \\cite{kingma2014adam} as the optimizer, with a batch size of 128 and learning rate of 0.001.\nThe activation functions used were Rectified Linear Units (ReLUs) \\cite{dahl2013improving} at every layer (expect the output one).\nFinally I used Cross-Entropy loss function after taking softmax of the output.\n\n\\section{Final Remarks}\n\n\\begin{figure}[]\n\t\\centering\n\t\\begin{minipage}{0.5\\textwidth}\n\t\t\\centering\n\t\t\\includegraphics[width=1.1\\textwidth]{Accuracy-Learning-Curve.pdf} % first figure itself\n\t\\end{minipage}\\hfill\n\t\\begin{minipage}{0.5\\textwidth}\n\t\t\\centering\n\t\t\\includegraphics[width=1.1\\textwidth]{Loss-Learning-Curve.pdf} % second figure itself\n\t\\end{minipage}\n\t\\caption{Plots of the learning curve for the 2-layers MLP. On the left, accuracy is plotted while on the right, loss is plotted}\n\\end{figure}\n\n\\begin{table}[h]\n\t\\centering\n\t\\label{my-label}\n\t\\begin{tabular}{@{}lcc@{}}\n\t\t\\toprule\n\t\t& Training Accuracy & Validation Accuracy \\\\ \\midrule\n\t\tLogistic Regression & 89.6\\%           & 87.2\\%             \\\\\n\t\tMLP with 2 layers   & \\textbf{98.4\\%}  & \\textbf{97.3\\%}    \\\\ \\bottomrule\n\t\\end{tabular}\n\t\\caption{Accuracy results of the algorithms}\n\\end{table}\n\nThe results are shown in Table 1.\nClearly, MLP with 2 layers performs better than Logistic Regression.\nI have also plotted the learning curves of the MLP experiment in the figure 1.\n\n\nFrom the figures it is easy to see that model has not fully converged but starts to overfit after 150 iterations.\nThis is due to no regularization has been applied to the MLP architecture.\nMaybe, a less complex MLP with less layers and dropout would have resulted in a better performance without being prone to overfitting.\n\n\\bibliographystyle{apalike}\n\\bibliography{ref}\n\\end{document}\n", "meta": {"hexsha": "1c052e22a3d6fc0404aa743c069c842577eed60e", "size": 3846, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "6000B-prediction/Extras/report.tex", "max_stars_repo_name": "pranav-ust/hkust-materials", "max_stars_repo_head_hexsha": "46734e5edeb420c91d039ade7d046bef1e3a83c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2019-01-09T08:34:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T10:48:16.000Z", "max_issues_repo_path": "6000B-prediction/Extras/project1_20478966.tex", "max_issues_repo_name": "pranav-ust/hkust-materials", "max_issues_repo_head_hexsha": "46734e5edeb420c91d039ade7d046bef1e3a83c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "6000B-prediction/Extras/project1_20478966.tex", "max_forks_repo_name": "pranav-ust/hkust-materials", "max_forks_repo_head_hexsha": "46734e5edeb420c91d039ade7d046bef1e3a83c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-03-11T13:44:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-04T06:20:12.000Z", "avg_line_length": 41.8043478261, "max_line_length": 137, "alphanum_fraction": 0.7761310452, "num_tokens": 973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213070736461, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.31569396425209884}}
{"text": "\\documentclass{warpdoc}\n\\newlength\\lengthfigure                  % declare a figure width unit\n\\setlength\\lengthfigure{0.158\\textwidth} % make the figure width unit scale with the textwidth\n\\usepackage{psfrag}         % use it to substitute a string in a eps figure\n\\usepackage{subfigure}\n\\usepackage{rotating}\n\\usepackage{pstricks}\n\\usepackage[innercaption]{sidecap} % the cute space-saving side captions\n\\usepackage{scalefnt}\n\\usepackage{amsmath}\n\\usepackage{bm}\n\n\n\n%%%%%%%%%%%%%=--NEW COMMANDS BEGINS--=%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\newcommand{\\alb}{\\vspace{0.2cm}\\\\} % array line break\n\\newcommand{\\mfd}{\\displaystyle}\n\\newcommand{\\nd}{{n_{\\rm d}}}\n\\newcommand{\\M}{{\\bf M}}\n\\newcommand{\\N}{{\\bf N}}\n\\newcommand{\\B}{{\\bf B}}\n\\newcommand{\\BI}{\\wbar{{\\bf B}}}\n\\newcommand{\\A}{{\\bf A}}\n\\newcommand{\\C}{{\\bf C}}\n\\newcommand{\\T}{{\\bf T}}\n\\newcommand{\\Dstar}{D^{\\!\\star}}\n\\newcommand{\\Fstar}{F^{\\!\\star}}\n\\newcommand{\\Ustar}{U^{\\!\\star}}\n\\newcommand{\\Sstar}{S^{\\!\\star}}\n\\newcommand{\\Kstar}{K^{\\!\\star}}\n\\newcommand{\\Ystar}{Y^{\\!\\star}}\n\\newcommand{\\co}{,~~}\n\\newcommand{\\band}{{\\rm Band}}\n\\renewcommand{\\fontsizetable}{\\footnotesize\\scalefont{1.0}}\n\\renewcommand{\\fontsizefigure}{\\footnotesize}\n\\renewcommand{\\vec}[1]{\\bm{#1}}\n\\setcounter{tocdepth}{3}\n\\let\\citen\\cite\n\n%%%%%%%%%%%%%=--NEW COMMANDS BEGINS--=%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\setcounter{tocdepth}{3}\n\n%%%%%%%%%%%%%=--NEW COMMANDS ENDS--=%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n\\author{\n  Bernard Parent\n}\n\n\\email{\n  bernparent@gmail.com\n}\n\n\\department{\n  Institute for Aerospace Studies\t\n}\n\n\\institution{\n  University of Toronto\n}\n\n\\title{\n  Fluid Relaxation Schemes\n}\n\n\\date{\n  June 2001, July-August 2015\n}\n\n%\\setlength\\nomenclaturelabelwidth{0.13\\hsize}  % optional, default is 0.03\\hsize\n%\\setlength\\nomenclaturecolumnsep{0.09\\hsize}  % optional, default is 0.06\\hsize\n\n\\nomenclature{\n\n  \\begin{nomenclaturelist}{Roman symbols}\n   \\item[$a$] speed of sound\n  \\end{nomenclaturelist}\n}\n\n\n\\abstract{\nabstract\n}\n\n\\begin{document}\n  \\pagestyle{headings}\n  \\pagenumbering{arabic}\n  \\setcounter{page}{1}\n%%  \\maketitle\n  \\makewarpdoctitle\n%  \\makeabstract\n  \\tableofcontents\n%  \\makenomenclature\n%%  \\listoftables\n%%  \\listoffigures\n\\sloppy\n\n\n\n\\section{Explicit Pseudo-Time Stepping}\n\nAfter adding a pseudo-time derivative, the discretized form of the governing equations, using explicit Euler\ntime-marching corresponds to:\n%\n\\begin{align}\n   \\Gamma^n {\\Delta^n {\\Ustar}}\n  &+  Z^n \\left(\\delta_t \\Ustar\\right)^n \\nonumber\\alb\n  &+ \\sum_{i=1}^{\\nd}\n      \\left(  \\delta_{X_i} {\\Fstar_i}^{n} \n            + \\delta_{X_i} \\left({\\Dstar_i} \\Ustar\\right)^n\n            + {\\Ystar_i}^n \\delta_{X_i} H^n\n            - \\sum_{j=1}^{\\nd} \\delta_{X_i} \\left(  {\\Kstar_{ij}}^{\\!\\! n} \\delta_{X_j} G^{n}\\right) \\right)\n ={\\Sstar}^{n}\n\\end{align}\n%\nwhere the superscript $n$ refers to the pseudo-time step,\nand $\\Delta^n {\\Ustar}\\equiv {\\Ustar}^{n+1}-{\\Ustar}^n$. Recall the definition of the discretized\nresidual:\n%\n\\begin{align}\nR_\\Delta^n &\\equiv  Z^n \\left(\\delta_t \\Ustar\\right)^n \\nonumber\\alb\n  &+ \\sum_{i=1}^{\\nd}\n      \\left(  \\delta_{X_i} {\\Fstar_i}^{n} \n            + \\delta_{X_i} \\left({\\Dstar_i} \\Ustar\\right)^n\n            + {\\Ystar_i}^n \\delta_{X_i} H^n\n            - \\sum_{j=1}^{\\nd} \\delta_{X_i} \\left(  {\\Kstar_{ij}}^{\\!\\! n} \\delta_{X_j} G^{n}\\right) \\right)\n -{\\Sstar}^{n}\n\\label{eqn:Rdelta}\n\\end{align}\n%\nThen, the former can be rewritten as\n%\n\\begin{equation}\n     \\Delta^n{\\Ustar}=   - \\left(\\Gamma^n\\right)^{-1} R_\\Delta^n\n\\end{equation}\n%\n\n\n\n\n\\section{Implicit Pseudo-Time Stepping}\n\nDespite its simplicity and the small amount of computing per iteration, explicit time stepping generally has a poor computational efficiency. This is due to the chemical reactions and diffusion terms being particularly stiff and restricting the pseudo-time step to very small values, hence leading to very slow convergence rates. This can be remedied through the use of \\emph{implicit} pseudo-time stepping.\n\n\\subsection{Delta Form}\n\nAfter adding a pseudo-time derivative, the discretized form of the governing equations using implicit Euler\ntime-marching corresponds to:\n%\n\\begin{align}\n   \\Gamma^n {\\Delta^n {\\Ustar}}&+  Z^n \\left(\\delta_t \\Ustar\\right)^{n+1}+   \\sum_{i=1}^{\\nd}\n      \\Bigg(  \\delta_{X_i} {{\\Fstar_i}^{n+1}}\n            + \\delta_{X_i} {\\Dstar_i}^{n} {\\Ustar}^{n+1}\n\\nonumber\\alb\n            &+ {\\Ystar_i}^n \\delta_{X_i} H^{n+1}\n            - \\sum_{j=1}^{\\nd} \\delta_{X_i} \\left( {\\Kstar_{ij}}^{\\!\\! n} \\delta_{X_j} G^{n+1}\\right) \\Bigg) \n - {\\Sstar}^{n+1}=0\n\\label{eqn:govdisc2}\n\\end{align}\n%\nwhere we took some liberty in assuming that $\\Gamma$, $\\Kstar$, $Z$, $\\Dstar$, and $\\Ystar$ do not change in\npseudo-time.\nLet's substract the residual evaluated at pseudo-time level $n$ as shown in Eq.\\ (\\ref{eqn:Rdelta}) on both sides of the latter:\n%\n\\begin{align}\n   \\mfd \\Gamma^n {\\Delta^n {\\Ustar}}\n +   \\sum_{i=1}^{\\nd}\n      &\\Bigg( \\delta_{X_i} \\left({{\\Fstar_i}^{n+1}}-{{\\Fstar_i}^{n}}\\right)\n          + \\delta_{X_i} {\\Dstar_i}^{n} \\left( {\\Ustar}^{n+1}-{\\Ustar}^{n}\\right)\n          + {\\Ystar_i}^n \\delta_{X_i} \\left(H^{n+1}-H^n \\right)\n              \\nonumber\\alb\n          &- \\sum_{j=1}^{\\nd} \\delta_{X_i}\n        \\left({\\Kstar_{ij}}^{\\!\\! n} \\delta_{X_j} G^{n+1}\n        -{\\Kstar_{ij}}^{\\!\\! n} \\delta_{X_j} G^{n}\\right)\n          \\Bigg)-\\left({\\Sstar}^{n+1} -{\\Sstar}^n \\right)\\nonumber\\alb\n        &+ Z^n \\left(\\left(\\delta_t \\Ustar\\right)^{n+1}-\\left(\\delta_t \\Ustar\\right)^n \\right)\n= -R_\\Delta^n\n\\label{eqn:govdisc3}\n\\end{align}\n%\nRewriting Eq.~(\\ref{eqn:govdisc3}) in a more compact form, one gets the\ndelta form:\n%\n\\begin{align}\n   \\mfd\\Gamma^n{\\Delta^n {\\Ustar}}\n   &+\\sum_{i=1}^{\\nd}\\left( \\delta_{X_i}  {\\Delta^n {\\Fstar_i}}\n          + \\delta_{X_i} \\left({\\Dstar_i}^{n} \\Delta^n {\\Ustar}\\right)\n          + {\\Ystar_i}^n \\delta_{X_i}  \\Delta^n H\n            - \\sum_{j=1}^{\\nd} \\delta_{X_i}\n           \\left( {\\Kstar_{ij}}^{\\!\\! n} \\delta_{X_j}\n                 {\\Delta^{n} G}\\right) \\right)\\nonumber\\alb\n  &-\\Delta^n {\\Sstar}+ Z^n \\Delta^n(\\delta_t \\Ustar) = -R_{\\Delta}^n\n\\label{eqn:deltaform}\n\\end{align}\n%\nwhere the operator $\\Delta^n(\\cdot)$ corresponds to:\n%\n\\begin{equation}\n\\Delta^n(\\cdot) = (\\cdot)^{n+1}-(\\cdot)^n\n\\end{equation}\n%\n\n\n\n\\subsection{Block Alternate Direction Implicit (ADI)}\n\nEquation (\\ref{eqn:deltaform}) involves solving a huge banded matrix\nwhich would require too much computer memory storage and CPU\ntime for multidimensional problems. One alternative is to approximate\nthe delta form with a multiplication of one-dimensional operators,\na technique usually referred to as approximate factorization \\cite{misc:1955:peaceman,\nmisc:1955:douglas}. However, contrarily to the scalar approximate factorization in \\cite{misc:1955:peaceman}, we here apply the approximate factorization to the matrix form of the delta form, hence resulting in a \\emph{block implicit} method (see Refs.\\ \\cite{jcp:1980:briley} and \\cite[pp.\\ 318--319]{book:2001:oran} for a discussion of block implicit algorithms):\n%\n\\begin{align}\n\\Bigg\\{   \\prod_{i=1}^{\\nd}\n  \\Bigg[ I\n        &+{(\\Gamma^n)}^{-1} \\delta_{X_i} \\left(\\frac{\\partial \\Fstar_i}{ \\partial \\Ustar}\\right)^n\n        +{(\\Gamma^n)}^{-1} \\delta_{X_i} {\\Dstar_i}^n\n        +{(\\Gamma^n)}^{-1} {\\Ystar_i}^n\\delta_{X_i} \\left(\\frac{\\partial H}{ \\partial \\Ustar}\\right)^n\n\\nonumber\\alb\n&\n        - {(\\Gamma^n)}^{-1} \\sum_{j=1}^{\\nd} \\delta_{X_i} \\left( {\\Kstar_{ij}}^{\\!\\! n}\\delta_{X_j} \\left(\\frac{\\partial G}{ \\partial \\Ustar}\\right)^n \\right) \n        -\\delta_{1i} {(\\Gamma^n)}^{-1} \\left(\\frac{\\partial \\Sstar}{ \\partial \\Ustar}\\right)^n \\nonumber\\alb\n&\n        +\\delta_{1i} {(\\Gamma^n)}^{-1} Z^n \\left(\\frac{\\partial (\\delta_t \\Ustar)}{  \\partial \\Ustar}\\right)^n\n\\Bigg] \\Bigg\\} \\Delta^n {\\Ustar}\n        = - {(\\Gamma^n)}^{-1} R_{\\Delta}^n\n\\label{eqn:approxfact}\n\\end{align}\n%\nwhere $\\delta_{1i}$ here refers to the Kronecker delta and not to\na discretization. \nEquation (\\ref{eqn:approxfact}) corresponds to Eq.~(\\ref{eqn:deltaform})\nif, when the multiplication is expanded, all terms involving ${(\\Gamma^n)}^{-2}$\nor ${(\\Gamma^n)}^{-3}$ are neglected.\nIt is noted that the linearization matrix $\\partial \\Fstar_i / \\partial \\Ustar$ is symbolic\nand stands for the Jacobian of the FDS or FVS scheme (more on this below).\nThe equation to solve for each node at $X_i$ for the $i$th sweep can be written as\n(using the linearization matrices $\\A_i$, $\\B_i$, $\\C_i$ listed in the appendix:\n%\n\\begin{equation}\n\\begin{array}{r}\n\\A_i^{X_i} \\Delta \\widetilde{\\Ustar}_i^{X_i-1} +\n\\B_i^{X_i} \\Delta \\widetilde{\\Ustar}_i^{X_i} +\n\\C_i^{X_i} \\Delta \\widetilde{\\Ustar}_i^{X_i+1} =\n{\\Delta \\widetilde{\\Ustar}^{X_i}_{i-1}}\n\\end{array}\n\\end{equation}\n%\nwhere ${\\Delta \\widetilde{\\Ustar}^{X_i}_1}=- (\\Gamma^{-1})^{X_i} R_{\\Delta}^{X_i}$\nand the total flux increment $\\Delta {\\Ustar}^{X_i}$ is set to ${\\Delta \\widetilde{\\Ustar}^{X_i}_{\\nd}}$.\n\nThe latter is also referred to in the litterature as Alternate-Direction-Implicit (ADI). It is noted that we are here applying the ADI scheme for the system of equations as a whole by solving block tdmas along each direction as outlined in Ref.\\ \\cite{jcp:1980:briley} rather than applying the ADI scheme in scalar form for each equation independently of the other.\n\n\n\\subsection{Block Diagonally-Dominant Alternate Direction Implicit (DD-ADI)}\n\nThe Diagonally-Dominant Alternate Direction Implicit (DD-ADI) is similar to the ADI\nbut the factorization is such that all terms of the original inversion matrix\nare returned. It was first proposed by MacCormack \\cite{aiaaconf:1997:maccormack}\nas the  modified approximate factorization (MAF) and by Bardina \\cite{aiaaconf:1987:bardina} as the DD-ADI.\nLinearizing the delta-form of Eq.~(\\ref{eqn:deltaform}),\nan implicit Euler time-stepping can be expressed in any number of dimensions as:\n%\n\\begin{equation}\n  \\M [ \\Delta^n \\Ustar ] = [- {(\\Gamma^n)}^{-1} R_{\\Delta}]\n\\end{equation}\n%\nwith $\\M$ the linearization matrix corresponding to, in three dimensions for\nexample:\n%\n\\begin{equation}\n\\M=\n \\left[\n   \\begin{array}{@{}c@{\\;\\;}c@{\\;\\;}c@{\\;\\;}c@{\\;\\;}c@{\\;\\;}c@{\\;\\;}c@{\\;\\;}c@{\\;\\;}c@{\\;\\;}c@{\\;\\;}c@{\\;\\;}c@{\\;\\;}c@{\\;\\;}c@{\\;\\;}c@{\\;\\;}c@{\\;\\;}c@{\\;\\;}c@{\\;\\;}c@{\\;\\;}c@{\\;\\;}c@{\\;\\;}c@{}}\n   \\ddots &  0     &  0   & \\ddots   &\\ddots   & \\ddots   & 0     &  0   &\\ddots   &      &    &\\ddots    &    &     &      \\alb\n       &\\A_2^1    &  0   &     0  &\\A_3^1   &\\B^1      & \\C_3^1  & 0    &   0   &\\C_2^1  &    &    &\\C_1^1 &     &      \\alb\n    &       &\\A_2^2  &   0    &    0  &\\A_3^2    & \\B^2    &\\C_3^2  &   0   &  0   &\\C_2^2 &    &    & \\C_1^2 &      \\\\\n   \\ddots &    &  &\\ddots    &  0    &    0   &\\ddots   &\\ddots  &\\ddots   &   0  &  0  &\\ddots  & &  & \\ddots  \\alb\n       &\\A_1^{13} &     &    &\\A_2^{13}&0 & 0 &\\A_3^{13}&\\B^{13} &\\C_3^{13}& 0    & 0   &\\C_2^{13}&     &      \\alb\n       &       &\\A_1^{14}&   &      &\\A_2^{14} &   0   &  0   &\\A_3^{14}&\\B^{14}   & \\C_3^{14} &0&0& \\C_2^{14}&     \\\\\n       &       &     &\\ddots    &      &       &\\ddots   &  0   &   0   &\\ddots&\\ddots   & \\ddots &0&0&\\ddots\\\\\n   \\end{array}\n \\right]\n\\end{equation}\n%\nDefining the tridiagonal matrices:\n%\n%\n\\begin{align*}\n\\T_3&=\n \\left[\n   \\begin{array}{cccccc}\n     \\ddots&\\ddots& 0   & 0   & 0           \\\\\n     \\ddots& \\B^1   & \\C_3^1  & 0   & 0           \\alb\n     0   & \\A_3^2 & \\B^2    & \\C_3^2  & 0           \\\\\n     0   & 0  & \\A_3^3  & \\B^3    & \\ddots          \\\\\n     0   & 0  & 0   & \\ddots& \\ddots      \\alb\n   \\end{array}\n \\right]\\alb\n &=\\left[ \\A_3 \\co \\B \\co \\C_3 \\right]^\\band\n\\end{align*}\n%\nand\n%\n\\begin{align*}\n\\T_2&=\n \\left[\n   \\begin{array}{ccccccccccccc}\n     \\ddots    & 0  & 0   & 0   & \\ddots  & 0   & 0        \\alb\n     0   & \\B^1   & 0  & 0   & 0   & \\C_2^1  & 0       \\\\\n     0   & 0  & \\B^2    & 0  & 0   & 0   & \\ddots      \\alb\n     0   & 0  & 0  & \\B^3    & 0  & 0   & 0       \\\\\n     \\ddots  & 0  & 0   & 0  & \\B^4    & 0  & 0       \\alb\n     0   & \\A_2^5 & 0   & 0   & 0  & \\B^5    & 0      \\\\\n     0   & 0  & \\ddots& 0   & 0   & 0  & \\ddots        \\alb\n   \\end{array}\n \\right]\\alb\n &= \\left[ \\A_2\\co 0\\co  0\\co  0\\co  \\B\\co 0\\co  0\\co  0\\co\\C_2 \\right]^\\band\n\\end{align*}\n%\nThe product $\\T_2 \\T_3$ gives\n%\n\\begin{equation}\n\\T_2 \\T_3=\n \\left[\n   \\begin{array}{cccccccccccccc}\n     \\ddots   & \\ddots  & 0     & \\ddots     & \\ddots   & \\ddots   & 0        & 0 \\\\\n     \\ddots & \\B^1 \\B^1    & \\B^1 \\C_3^1 & 0         & \\C_2^1 \\A_3^5& \\C_2^1 \\B^5     & \\C_2^1 \\C_3^5 & 0 \\\\\n     0     & \\B^2 \\A_3^2  & \\B^2 \\B^2   & \\B^2 \\C_3^2     & 0      & \\C_2^2 \\A_3^6   & \\C_2^2 \\B^6  & \\ddots  \\\\\n     \\ddots  &  0     & \\B^3 \\A_3^3 & \\B^3 \\B^3       & \\B^3 \\C_3^3  & 0         & \\C_2^3 \\A_3^7 & \\ddots \\\\\n     \\ddots  & \\A_2^4 \\C_3^0& 0     & \\B^4 \\A_3^4     & \\B^4 \\B^4    & \\B^4 \\C_3^4     & 0      & \\ddots  \\\\\n     \\ddots  & \\A_2^5 \\B^1 & \\A_2^5 \\C_3^1& 0     & \\B^5 \\A_3^5     & \\B^5 \\B^5    & \\B^5 \\C_3^5     & 0  \\\\\n     0     & \\A_2^6 \\A_3^2& \\A_2^6 \\B^2 & \\A_2^6 \\C_3^2& 0     & \\B^6 \\A_3^6     & \\B^6 \\B^6      & \\ddots \\\\\n     0     &  0    & \\ddots   & \\ddots  & \\ddots   & 0     & \\ddots    & \\ddots \\\\\n   \\end{array}\n \\right]\n\\end{equation}\n%\nor,\n%\n\\begin{equation}\n\\T_2 \\T_3=\\left[\n \\A_2 \\A_3^{-4} \\co\n \\A_2 \\B^{-4} \\co\n \\A_2 \\C_3^{-4} \\co\n 0 \\co\n \\B \\A_3     \\co\n \\B \\B   \\co\n \\B \\C_3 \\co\n 0 \\co\n \\C_2 \\A_3^{+4} \\co\n \\C_2 \\B^{+4} \\co\n \\C_2 \\C_3^{+4}\n\\right]^\\band\n\\end{equation}\n%\nwhile the product $\\T_2 \\BI \\T_3$ gives (with $\\BI \\equiv \\B^{-1}$):\n%\n\\begin{equation}\n\\T_2 \\BI \\T_3=\n \\left[\n   \\begin{array}{c@{\\;}c@{\\;}c@{\\;}c@{\\;}c@{\\;}c@{\\;}c@{\\;}c@{\\;}c@{\\;}c@{\\;}c@{\\;}c@{\\;}c@{\\;}c}\n     \\ddots  & \\ddots  & 0     & \\ddots     & \\ddots   & \\ddots   & 0        & 0 \\\\\n     \\ddots  & \\B^1     & \\C_3^1 & 0         & \\C_2^1 \\BI^5 \\A_3^5& \\C_2^1     & \\C_2^1 \\BI^5 \\C_3^5 & 0 \\\\\n     0     & \\A_3^2  & \\B^2   & \\C_3^2     & 0      & \\C_2^2 \\BI^6 \\A_3^6   & \\C_2^2  & \\ddots  \\\\\n     \\ddots  &  0     & \\A_3^3 & \\B^3       & \\C_3^3  & 0         & \\C_2^3 \\BI^7 \\A_3^7 & \\ddots \\\\\n     \\ddots  & \\A_2^4 \\BI^0 \\C_3^0& 0     &  \\A_3^4     &  \\B^4    &  \\C_3^4     & 0      & \\ddots  \\\\\n     \\ddots  & \\A_2^5  & \\A_2^5 \\BI^1 \\C_3^1& 0     & \\A_3^5     & \\B^5    & \\C_3^5     & 0  \\\\\n     0     & \\A_2^6 \\BI^2 \\A_3^2& \\A_2^6  & \\A_2^6 \\BI^2 \\C_3^2& 0     &  \\A_3^6     & \\B^6       & \\ddots \\\\\n     0     &  0    & \\ddots   & \\ddots  & \\ddots   & 0     & \\ddots    & \\ddots \\\\\n   \\end{array}\n \\right]\n\\end{equation}\n%\nor,\n%\n\\begin{align}\n\\T_2 \\BI \\T_3=\\left[\n \\A_2 \\BI^{-4} \\A_3^{-4} \\co\n \\A_2 \\co\n \\A_2 \\BI^{-4} \\C_3^{-4} \\co\n 0 \\co\n \\A_3     \\co\n \\B    \\co\n \\C_3 \\co\n 0 \\co\n \\C_2 \\BI^{+4} \\A_3^{+4} \\co\n \\C_2 \\co \\right.\\nonumber\\alb\n\\left.\n \\C_2 \\BI^{+4} \\C_3^{+4}\n\\right]^\\band\n\\end{align}\n%\nDefining the matrix\n%\n\\begin{equation}\n\\T_1=\n \\left[\n   \\begin{array}{ccccccccccccccc}\n   \\ddots &0       & 0    &\\ddots    &0    & 0    & 0     \\alb\n   0    &\\B^1      & 0    &\\cdots    &\\C_1^1 & 0    & 0     \\alb\n   0    &0       & \\B^2   &\\cdots    &0    & \\C_1^2 & 0     \\\\\n   \\ddots &\\vdots    & \\vdots &\\ddots    &\\vdots & \\vdots & \\ddots  \\alb\n   0    &\\A_1^{13} & 0    &\\cdots    &\\B^{13}& 0    & 0     \\alb\n   0    &0       &\\A_1^{14}& \\cdots  &0    &\\B^{14} & 0     \\\\\n   0    &0       &0     &\\ddots    &0    &0     &\\ddots   \\alb\n   \\end{array}\n \\right]\n\\end{equation}\n%\nthen,\n%\n\\begin{displaymath}\n\\begin{array}{l}\n\\T_1 \\BI \\T_2 \\BI \\T_3=  \\alb\n  \\begin{array}{l}\n   \\left[\n   \\A_1 \\BI^{-12}\\A_2^{-12} \\BI^{-16} \\A_3^{-16}\\co\n   \\A_1 \\BI^{-12}\\A_2^{-12}\\co\n   \\A_1 \\BI^{-12}\\A_2^{-12} \\BI^{-16} \\C_3^{-16}\\co\n   0\\co\n   \\A_1 \\BI^{-12} \\A_3^{-12}\\co \\right. \\alb\n   \\A_1\\co\n   \\A_1 \\BI^{-12} \\C_3^{-12}\\co\n   0\\co\n   \\A_1 \\BI^{-12}\\C_2^{-12} \\BI^{-8} \\A_3^{-8}\\co\n   \\A_1 \\BI^{-12}\\C_2^{-12}\\co\n   \\A_1 \\BI^{-12}\\C_2^{-12} \\BI^{-8} \\C_3^{-8}\\co\n   0\\co \\alb\n   \\A_2 \\BI^{-4} \\A_3^{-4}\\co\n   \\A_2\\co\n   \\A_2 \\BI^{-4} \\C_3^{-4}\\co\n   0\\co\n   \\A_3\\co\n   \\B\\co\n   \\C_3\\co\n   0\\co\n   \\C_2 \\BI^{+4} \\A_3^{+4}\\co\n   \\C_2\\co\n   \\C_2 \\BI^{+4} \\C_3^{+4}\\co\n   0\\co\\alb\n\n\n   \\C_1 \\BI^{+12}\\A_2^{+12} \\BI^{+8} \\A_3^{+8}\\co\n   \\C_1 \\BI^{+12}\\A_2^{+12}\\co\n   \\C_1 \\BI^{+12}\\A_2^{+12} \\BI^{+8} \\C_3^{+8}\\co\n   0\\co\n   \\C_1 \\BI^{+12} \\A_3^{+12}\\co\n   \\C_1\\co\\alb\n   \\left.\n   \\C_1 \\BI^{+12} \\C_3^{+12}\\co\n   0\\co\n   \\C_1 \\BI^{+12}\\C_2^{+12} \\BI^{+16} \\A_3^{+16}\\co\n   \\C_1 \\BI^{+12}\\C_2^{+12}\\co\n   \\C_1 \\BI^{+12}\\C_2^{+12} \\BI^{+16} \\C_3^{+16}\n   \\right]^\\band\\alb\n  \\end{array}\n\\end{array}\n\\end{displaymath}\n%\nwhere the decomposition error terms can be identified by comparing the latter\nto matrix $\\M$:\n%\n\\begin{displaymath}\n  \\begin{array}{r}\n  \\M=\n   \\left[ 0\\co\n   0\\co\n   0\\co\n   0\\co\n   0\\co\n   \\A_1\\co\n   0\\co\n   0\\co\n   0\\co\n   0\\co\n   0\\co\n   0\\co\n   0\\co\n   \\A_2\\co\n   0\\co\n   0\\co\n   \\A_3\\co\n   \\B\\co\n   \\C_3\\co \\right. \\alb\n   \\left.\n   0\\co\n   0\\co\n   \\C_2\\co\n   0\\co\n   0\\co\n   0\\co\n   0\\co\n   0\\co\n   0\\co\n   0\\co\n   \\C_1\\co\n   0\\co\n   0\\co\n   0\\co\n   0\\co\n   0 \\right]^\\band\n  \\end{array}\n\\end{displaymath}\n%\nThe decomposition error matrix, $\\N$ can then be written as:\n%\n\\begin{equation}\n  \\N\\equiv \\T_1 \\BI \\T_2 \\BI \\T_3- \\M\n\\end{equation}\n%\n\\begin{displaymath}\n\\begin{array}{l}\n\\N=  \\alb\n  \\begin{array}{l}\n   \\left[\n   \\A_1 \\BI^{-12}\\A_2^{-12} \\BI^{-16} \\A_3^{-16}\\co\n   \\A_1 \\BI^{-12}\\A_2^{-12}\\co\n   \\A_1 \\BI^{-12}\\A_2^{-12} \\BI^{-16} \\C_3^{-16}\\co\n   0\\co\n   \\A_1 \\BI^{-12} \\A_3^{-12}\\co \\right. \\alb\n   0 \\co\n   \\A_1 \\BI^{-12} \\C_3^{-12}\\co\n   0\\co\n   \\A_1 \\BI^{-12}\\C_2^{-12} \\BI^{-8} \\A_3^{-8}\\co\n   \\A_1 \\BI^{-12}\\C_2^{-12}\\co\n   \\A_1 \\BI^{-12}\\C_2^{-12} \\BI^{-8} \\C_3^{-8}\\co\n   0\\co \\alb\n   \\A_2 \\BI^{-4} \\A_3^{-4}\\co\n   0\\co\n   \\A_2 \\BI^{-4} \\C_3^{-4}\\co\n   0\\co\n   0\\co\n   0\\co\n   0\\co\n   0\\co\n   \\C_2 \\BI^{+4} \\A_3^{+4}\\co\n   0\\co\n   \\C_2 \\BI^{+4} \\C_3^{+4}\\co\n   0\\co\\alb\n\n\n   \\C_1 \\BI^{+12}\\A_2^{+12} \\BI^{+8} \\A_3^{+8}\\co\n   \\C_1 \\BI^{+12}\\A_2^{+12}\\co\n   \\C_1 \\BI^{+12}\\A_2^{+12} \\BI^{+8} \\C_3^{+8}\\co\n   0\\co\n   \\C_1 \\BI^{+12} \\A_3^{+12}\\co\n   0\\co\\alb\n   \\left.\n   \\C_1 \\BI^{+12} \\C_3^{+12}\\co\n   0\\co\n   \\C_1 \\BI^{+12}\\C_2^{+12} \\BI^{+16} \\A_3^{+16}\\co\n   \\C_1 \\BI^{+12}\\C_2^{+12}\\co\n   \\C_1 \\BI^{+12}\\C_2^{+12} \\BI^{+16} \\C_3^{+16}\n   \\right]^\\band\\alb\n  \\end{array}\n\\end{array}\n\\end{displaymath}\n%\nThe advantage of DD-ADI versus standard ADI is that all the original terms in\n$\\M$ are present in $\\T_1 \\BI \\T_2 \\BI \\T_3$.\nRecalling that $\\M [ \\Delta^n \\Ustar ] = [- \\Gamma^{-1} R_{\\Delta}]$ (for a direct inversion),\nand that $\\M \\approx \\T_1 \\BI \\T_2 \\BI \\T_3$\nthe DD-ADI algorithm can be implemented in three dimensions as:\n%\n\\begin{displaymath}\n\\begin{array}{rcl}\n  {\\rm step~1} & ~~ & \\T_1 [\\Delta^n \\Ustar_1] = [- \\Gamma^{-1} R_{\\Delta}]\\alb\n  {\\rm step~2} & ~~ & \\T_2 [\\Delta^n \\Ustar_2] = [\\B]^\\band [\\Delta^n \\Ustar_1] \\alb\n  {\\rm step~3} & ~~ & \\T_3 [\\Delta^n \\Ustar] = [\\B]^\\band [\\Delta^n \\Ustar_2]\n\\end{array}\n\\end{displaymath}\n%\nand in two dimensions as:\n%\n\\begin{displaymath}\n\\begin{array}{rcl}\n  {\\rm step~1} & ~~ & \\T_1 [\\Delta^n \\Ustar_1] = [- \\Gamma^{-1} R_{\\Delta}]\\alb\n  {\\rm step~2} & ~~ & \\T_2 [\\Delta^n \\Ustar] = [\\B]^\\band [\\Delta^n \\Ustar_1] \\alb\n\\end{array}\n\\end{displaymath}\n%\n\n\n\\subsection{Block Iterative DD-ADI Algorithm: Removal of Decomposition Error}\n\nThe DD-ADI can be further improved through an iterative method to reduce the decomposition error as suggested by MacCormack in Ref.\\ \\cite{caf:2001:maccormack}.\n\nThe direct inversion can be written as:\n%\n\\begin{displaymath}\n  \\begin{array}{c}\n  \\M [ \\Delta^n \\Ustar ] = [- \\Gamma^{-1} R_{\\Delta}] \\alb\n{\\rm or~~}  \\M [ \\Delta^n \\Ustar ] + \\N [ \\Delta^n \\Ustar ]= [- \\Gamma^{-1} R_{\\Delta}] + \\N [ \\Delta^n \\Ustar ]\\alb\n{\\rm or~~}  \\T_1 \\BI \\T_2 \\BI \\T_3 [ \\Delta^n \\Ustar ] = [- \\Gamma^{-1} R_{\\Delta}] + \\N [ \\Delta^n \\Ustar ]\n  \\end{array}\n\\end{displaymath}\n%\nsince $\\N+\\M=\\T_1 \\BI \\T_2 \\BI \\T_3$.\nThe idea behind removing the decomposition error is in performing\n$k$ times the approximate factorization on the same residual, each\ntime using a more updated decomposition error term on the RHS:\n%\n\\begin{equation}\n  \\T_1 \\BI \\T_2 \\BI \\T_3 [ \\Delta^n {\\Ustar}^{(k)} ] = [- \\Gamma^{-1} R_{\\Delta}] + \\N [ \\Delta^n {\\Ustar}^{(k-1)} ]\n\\end{equation}\n%\nwhere $k=1,2,3,4,5,..,\\infty$ and where it is assumed that\n$\\N [ \\Delta^n {\\Ustar}^{(k-1)} ] \\rightarrow 0$ as $k \\rightarrow \\infty$.\nThe latter can also be written as:\n%\n\\begin{equation}\n    \\T_1 \\BI \\T_2 \\BI \\T_3 [ \\Delta^n {\\Ustar}^{(k)} ]\n  = [- \\Gamma^{-1} R_{\\Delta}] + \\T_1 \\BI \\T_2 \\BI \\T_3 [ \\Delta^n {\\Ustar}^{(k-1)} ]\n    - \\M [ \\Delta^n {\\Ustar}^{(k-1)} ]\n\\end{equation}\n%\nwith $\\Delta^n {\\Ustar}^{(0)}=0$. Step by step, this becomes:\n%\n%\n\\begin{displaymath}\n \\begin{array}{rcl}\n   k=1 & ~~&\n    \\T_1 \\BI \\T_2 \\BI \\T_3 [ \\Delta^n {\\Ustar}^{(1)} ]\n    = [- \\Gamma^{-1} R_{\\Delta}]  \\alb\n   k=2 & ~~&\n    \\T_1 \\BI \\T_2 \\BI \\T_3 [ \\Delta^n {\\Ustar}^{(2)} ]\n    = [- 2 \\Gamma^{-1} R_{\\Delta}] - \\M [ \\Delta^n {\\Ustar}^{(1)} ] \\alb\n   k=3 & ~~&\n    \\T_1 \\BI \\T_2 \\BI \\T_3 [ \\Delta^n {\\Ustar}^{(3)} ]\n    = [- 3 \\Gamma^{-1} R_{\\Delta}] - \\M [ \\Delta^n {\\Ustar}^{(1)} + \\Delta^n {\\Ustar}^{(2)} ]  \\alb\n   k=4 & ~~&\n    \\T_1 \\BI \\T_2 \\BI \\T_3 [ \\Delta^n {\\Ustar}^{(4)} ]\n    = [- 4 \\Gamma^{-1} R_{\\Delta}] - \\M [ \\Delta^n {\\Ustar}^{(1)} + \\Delta^n {\\Ustar}^{(2)} + \\Delta^n {\\Ustar}^{(3)}]\n \\end{array}\n\\end{displaymath}\n%\n\n\n\n\n\n\\appendix\n\n\\section{Linearization Matrices for FDS First Order Scheme}\n\n\nWe here list the linearization matrices for the first-order Roe flux difference splitting (FDS) scheme. \nThe matrices $\\A_i$, $\\B$ and $\\C_i$ are defined as, assuming a linearization\nof the Roe scheme with the Roe Jacobian frozen:\n%\n\\begin{align}\n\\A_i =\n  \\Gamma^{-1}\n  \\Bigg\\{\n    &-K^{X_i-\\frac{1}{2}}_{ii} \\left(\\frac{\\partial G}{\\partial \\Ustar}\\right)^{X_i-1}\n    -\\mfd\\frac{\\left( {\\Omega} |A| \\right)_i^{X_i-\\frac{1}{2}}}{2 {\\Omega}^{X_i-1}}\n                         -\\frac{A^{X_i-1}}{2}\\nonumber\\alb\n    &-\\big({\\Dstar_i}^+\\big)^{X_i-1}\n     -\\big({\\Ystar_i}^+\\big)^{X_i-1/2} \\left(\\frac{\\partial H}{\\partial \\Ustar}\\right)^{X_i-1}\n  \\Bigg\\}\n\\end{align}\n%\n\\begin{align}\n\\B_i &=\nI+\\Gamma^{-1}\n \\Bigg\\{\n     -\\delta_{1i} \\left(\\frac{\\partial \\Sstar}{\\partial \\Ustar}\\right)^{X_i}\n    +\\delta_{1i} Z^{X_i} \\left(\\frac{\\partial (\\delta_t \\Ustar)}{\\partial \\Ustar}\\right)^{X_i} \\nonumber\\alb\n    &+\\left( K^{X_i-\\frac{1}{2}}_{ii}+K^{X_i+\\frac{1}{2}}_{ii} \\right)\\left(\\frac{\\partial G}{\\partial \\Ustar}\\right)^{X_i} \n    + \\mfd\\frac{\\left( {\\Omega} |A| \\right)_i^{X_i-\\frac{1}{2}}+\n           \\left( {\\Omega} |A| \\right)_i^{X_i+\\frac{1}{2}}}{2 {\\Omega}^{X_i}} \\nonumber\\alb\n    &+\\big({\\Dstar_i}^+\\big)^{X_i}-\\big({\\Dstar_i}^-\\big)^{X_i}\n     +\\big({\\Ystar_i}^+\\big)^{X_i-1/2} \\left(\\frac{\\partial H}{\\partial \\Ustar}\\right)^{X_i}\n     -\\big({\\Ystar_i}^-\\big)^{X_i+1/2} \\left(\\frac{\\partial H}{\\partial \\Ustar}\\right)^{X_i}\n  \\Bigg\\}\n\\end{align}\n%\n\\begin{align}\n\\B &=\nI+\\Gamma^{-1}\n \\Bigg\\{\n    -\\left(\\frac{\\partial \\Sstar}{\\partial \\Ustar}\\right)^{X_i}\n    + Z^{X_i} \\left(\\frac{\\partial (\\delta_t \\Ustar)}{\\partial \\Ustar}\\right)^{X_i}\n   \\nonumber\\alb\n    &+ \\sum_{j=1}^\\nd \\Bigg[\n     \\left( K^{X_j-\\frac{1}{2}}_{jj}+K^{X_j+\\frac{1}{2}}_{jj} \\right)\\left(\\frac{\\partial G}{\\partial \\Ustar}\\right)^{X_j}\n    +\\frac{\\left( {\\Omega} |A| \\right)_j^{X_j-\\frac{1}{2}}+\n           \\left( {\\Omega} |A| \\right)_j^{X_j+\\frac{1}{2}}}{2 {\\Omega}^{X_j}}\n   \\nonumber\\alb\n    &+\\big({\\Dstar_j}^+\\big)^{X_j}-\\big({\\Dstar_j}^-\\big)^{X_j}    \n     +\\big({\\Ystar_j}^+\\big)^{X_j-1/2} \\left(\\frac{\\partial H}{\\partial \\Ustar}\\right)^{X_j}\n     -\\big({\\Ystar_j}^-\\big)^{X_j+1/2} \\left(\\frac{\\partial H}{\\partial \\Ustar}\\right)^{X_j}\n    \\Bigg]\n  \\Bigg\\}\n\\end{align}\n%\n\\begin{align}\n\\C_i =\n  \\Gamma^{-1}\n  \\Bigg\\{\n    &-K^{X_i+\\frac{1}{2}}_{ii} \\left(\\frac{\\partial G}{\\partial \\Ustar}\\right)^{X_i+1}\n    -\\mfd\\frac{\\left( {\\Omega} |A| \\right)_i^{X_i+\\frac{1}{2}}}{2 {\\Omega}^{X_i+1}}\n                           +\\frac{A^{X_i+1}}{2}\\nonumber\\alb\n    &+\\big({\\Dstar_i}^-\\big)^{X_i+1}\n    +\\big({\\Ystar_i}^-\\big)^{X_i+1/2} \\left(\\frac{\\partial H}{\\partial \\Ustar}\\right)^{X_i+1}\n  \\Bigg\\}\n\\end{align}\n%\nwhere $|A|=L^{-1}  |\\Lambda|  L$, where $A=\\partial \\Fstar_i/\\partial \\Ustar$, where ${\\Ystar}^\\pm=\\frac{1}{2}(\\Ystar\\pm|\\Ystar|)$, and where $\\Omega$ is the inverse of the metrics Jacobian.\n\n  \\bibliographystyle{warpdoc}\n  \\bibliography{all}\n\n\n\\end{document}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "ed8f6b9dce0b884ad661412b7e1cd674ce078ca1", "size": 24212, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "cycle/ts/doc/report.tex", "max_stars_repo_name": "zhanghuanqian/CFDWARP", "max_stars_repo_head_hexsha": "9340a8526bb263d910f79d79e84dcac7aec211b6", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 29, "max_stars_repo_stars_event_min_datetime": "2018-09-13T13:58:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T21:44:13.000Z", "max_issues_repo_path": "cycle/ts/doc/report.tex", "max_issues_repo_name": "zhanghuanqian/CFDWARP", "max_issues_repo_head_hexsha": "9340a8526bb263d910f79d79e84dcac7aec211b6", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-11-10T11:28:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-23T09:21:28.000Z", "max_forks_repo_path": "cycle/ts/doc/report.tex", "max_forks_repo_name": "zhanghuanqian/CFDWARP", "max_forks_repo_head_hexsha": "9340a8526bb263d910f79d79e84dcac7aec211b6", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2018-07-26T08:17:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T08:41:55.000Z", "avg_line_length": 32.8967391304, "max_line_length": 407, "alphanum_fraction": 0.5504708409, "num_tokens": 10523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.31556810430549637}}
{"text": "\\documentclass[a4paper,twocolumn]{article}\n\n\\usepackage[english]{babel}\n\\usepackage[utf8]{inputenc}\n\\usepackage{graphicx}\n\\usepackage{fullpage}\n\n\\usepackage[small]{titlesec}\n% patch titlesec bug of not showing (sub)title numbering http://tex.stackexchange.com/a/300259\n\\usepackage{etoolbox}\n\\makeatletter\n\\patchcmd{\\ttlh@hang}{\\parindent\\z@}{\\parindent\\z@\\leavevmode}{}{}\n\\patchcmd{\\ttlh@hang}{\\noindent}{}{}{}\n\\makeatother\n\n\\makeatletter\n\\newcommand{\\thickhline}{%\n    \\noalign {\\ifnum 0=`}\\fi \\hrule height 1pt\n    \\futurelet \\reserved@a \\@xhline\n}\n\\makeatother\n\n\\newcommand*\\mean[1]{\\overline{#1}}\n\n\\title{Convolutional Neural Fabrics $-$ summary}\n\\author{Matěj Nikl}\n\n\\begin{document}\n\\maketitle\n\\noindent\nConvolutional Neural Fabrics (CNFs) is a architecture for embedding an exponentially large number of CNN architectures (via massive parameter sharing). It is intended as a step aside from the conventional CNN model architecture selection problem $-$  it is not trying to solve it, instead it offers the opportunity for the fabrics to learn/select the most appropriate model (or even ensemble of models) within itself by standard back-propagation algorithm, leaving only the hyper-parameters of number of layers and channels up to us.\nOther hyper-parameters, which are being ``set'' automatically by embedding in the fabrics are:\n\\begin{itemize}\n    \\item filter size per layer\n    \\item stride per layer\n    \\item number of pooling vs. convolutional layers\n    \\item type of pooling operator per layer\n    \\item size of the pooling regions\n    \\item ordering of pooling and convolutional layers\n    \\item channel connectivity pattern between layers\n    \\item type of activation (ReLU vs MaxOut)\n\\end{itemize}\n\n% \\section{Defining the Fabric}\n\n\\begin{figure}[!h]\n    \\includegraphics[width=\\columnwidth]{fabrics1.png}\n    \\caption{Trellis embedding of two seven-layer CNNs. Trellis nodes receiving the input and producing output are encircled. All edges are oriented to the right, down in the first layer, and towards the output in the last layer. The channel dimension of the 3D trellis is omitted for clarity.}\n\\end{figure}\n\n\\section{Making sense of the Fabrics}\nThe Fabrics consist of a 3D trellis that connects response maps at different layers, scales, and channels with a sparse homogeneous local connectivity pattern.\nEach node in the trellis represents a response map with the same number of dimensions as the input signal.\n\n\\subsection{The trellis structure}\nIt is spanned by three axes:\n\\begin{enumerate}\n    \\item a \\textbf{layer} axis $-$ along which all edges advance, is analogous to the depth axis of a CNN\n    \\item a \\textbf{scale} axis $-$ along which response maps of different resolutions are organized from fine to coarse\n    \\item a \\textbf{channel} axis $-$ along which different response maps of the same scale and layer are organized\n\\end{enumerate}\n\nEach node is connected to a 3 x 3 scale-channel neighborhood in the previous layer, i.e. channel $c$ at scale $s$ receives input from channels $\\{c-1, c, c+1\\}$ at scales $\\{s-1, s, s+1\\}$. Input from a finer scale is obtained via strided convolution, and input from a coarser scale by convolution, after upsampling by padding zeros around the activations at the coarser level.\n\n\\subsection{Embedded architectures}\n\\paragraph{Re-sampling operators}\nFine-to-coarse change of the resolution of response maps is done using stride-two convolutions. Larger strides can be obtained by following multiple such edges.\n\n\\textit{Average pooling} across small regions is also a strided convolution with uniform filter weights, thus available in the trellis. Average pooling over larger areas is also available.\n\n\\textit{Bi-linear interpolation} is commonly used in deconvolutional networks. Factor-two interpolation can be represented on coarse-to-fine edges by using a filter with $1$ in the center, $1/4$ on corners, and $1/2$ elsewhere. Larger powers of two can be obtained by repetition.\n\n\\begin{figure*}[t]\n    \\centering\n    \\includegraphics[width=0.375\\textwidth]{fabrics2.png}\n    \\hskip 1cm \n    \\includegraphics[width=0.5\\textwidth]{fabrics3.png}\n    \\caption{Visualization of mean-squared filter weights (mean along weights and channels) in models learned for Part Labels (left) and MNIST (right). Layers are laid out horizontally, and scales vertically.}\n\\end{figure*}\n\n{\n\\renewcommand{\\arraystretch}{1.25}\n\\begin{table*}[ht]\n\\centering\n    \\begin{tabular}{l c c r c}\n        \\thickhline\n                                          & Year & Augmentation & \\# Params. & Error (\\%) \\\\\n        \\hline\n\n        Chang et al.                      & 2015 & N            & 447 K      & 0.24 \\\\\n        Lee et al.                        & 2015 & N            &            & 0.31 \\\\\n        Grid LSTM                         & 2016 & T            &            & 0.32 \\\\\n        Dropconnect                       & 2013 & T+F          & 379 K      & 0.32 \\\\\n        CKN                               & 2014 & N            &  43 K      & 0.39 \\\\\n        Maxout                            & 2013 & N            & 420 K      & 0.45 \\\\\n        Network in Network                & 2013 & N            &            & 0.47 \\\\\n        \\hline\n        Ours: CNF-sparse (L = 16, C = 32) &      & T            & 249 K      & 0.48 \\\\\n        Ours: CNF-dense (L = 8, C = 64)   &      & T            & 5.3 M      & 0.33 \\\\\n        \\thickhline\n    \\end{tabular}\n    \\caption{Comparison of results with the state of the art on MNIST. Data augmentation with translation and flipping is denoted by T and F respectively, N denotes no data augmentation.}\n\\end{table*}\n}\n\n\\paragraph{Filter sizes}\nA 5 x 5 filter can be implemented by computing nine intermediate channels to obtain a vectorized version of the 3 x 3 neighborhood at each pixel. A second 3 x 3 convolution can then aggregate values across the original 5 x 5 patch, and output the desired convolution. Repetition allows to implement every filter of any desired size.\n\n\\paragraph{Ordering convolution and re-sampling}\nIt is up to the back-propagation algorithm to choose the desired path(s) to use $-$ by setting all, except one paths weights to zero, a particular sequence of convolutions and re-sampling operators is obtained.\n\n\\paragraph{Channel connectivity pattern}\nThis sparsely connected among the channel axis trellis suffices to emulate densely connected convolutional layers by copying channels, convolving them, and locally aggregating them.\n\n\n\\section{Principles of modularization}\nThe CNF architecture does not contain any standalone modules. The network itself can utilize some of its parts more, and by weight visualization it can be seen as modules being instationed, maybe even for certain purposes, however they still make up a integral, inseparable part of the network.\n\n\\section{Principles of growing}\nThe CNF architecture does not allow for any more growing as a conventional (C)NN does. Its purpose is not in growing, but in dynamically utilizing its trellis structure, whilst hiding away multiple hyper-parameters.\n\n\\end{document}\n", "meta": {"hexsha": "5574d3d9700f8e80cc7bfa690a534dbc1867a4ed", "size": 7067, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "summary/2/fabrics/fabrics.tex", "max_stars_repo_name": "MatejNikl/incremental_learning", "max_stars_repo_head_hexsha": "57eb7d02c614d5baa5f1814b2347151cc0378b58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "summary/2/fabrics/fabrics.tex", "max_issues_repo_name": "MatejNikl/incremental_learning", "max_issues_repo_head_hexsha": "57eb7d02c614d5baa5f1814b2347151cc0378b58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "summary/2/fabrics/fabrics.tex", "max_forks_repo_name": "MatejNikl/incremental_learning", "max_forks_repo_head_hexsha": "57eb7d02c614d5baa5f1814b2347151cc0378b58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 57.4552845528, "max_line_length": 533, "alphanum_fraction": 0.7087873214, "num_tokens": 1755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3155681043054963}}
{"text": " \n\\chapter{IDL Routines}\n\\label{ch_idlproc}\n\n\\markright{IDL Routines}\n \n\\section{Denoising using MS-VSTS + Isotropic Undecimated Wavelet Transform}\n%\\section{IDL routines for simulated data}\n\n\\subsection{Main routine}\n\n\\vspace{0.3cm}\n\n$\\blacktriangleright$   \\textbf {Starting from a photon counts map}\n\n\\vspace{0.3cm}\n\n$\\looparrowright$ \\textbf{mrs\\_msvsts\\_IUWT\\_denoising.pro} :  Compute Poisson denoising on spherical HEALPix data with MS-VSTS + Isotropic Undecimated Wavelet Transform method.\n\n\n\\begin{center}\n \\bf{USAGE : mrs\\_msvsts\\_IUWT\\_denoising, image, image\\_reconstruite, NbrScale=NbrScale, niter=niter, HSD=HSD, coef\\_seuil=coef\\_seuil, coef\\_pos=coef\\_pos, First\\_Scale=First\\_Scale, mask=mask, filter=filter, pyr=pyr, background=background, expo=expo, alm=alm, curv=curv, separation=separation, back\\_reconstruit=back\\_reconstruit, update\\_support=update\\_support, split\\_support=split\\_support}\n\\end{center}\n\n\\textbf{INPUTS} : \n\\begin{itemize}\n\\item{Image = (IDL array) HEALPix data to be denoised}\n\\item{(Optional) background = (IDL array) if set, substracts a background to the data}\n\\item{(Optional) support = (IDL array) if set, use a given multi-resolution support instead of computing it with the procedure mrs\\_msvsts\\_hypothesis\\_testing}\n\\end{itemize}\n\n\\textbf{OUTPUTS} : \n\\begin{itemize}\n\\item{Image\\_reconstruite = (IDL array) HEALPix denoised image}\n\\item{(optional) Support = (IDL array) multi-resolution support of the image}\n\\item{(optional) Back\\_reconstruit = (IDL array) if set, returns the reconstructed background (need the keyword separation)}\n\\end{itemize}\n\n\\textbf{KEYWORD}\n\n\\begin{itemize}\n  \\item NbrScale  : Number of scales (default is 4)\n  \\item niter  : Number of iterations\n  \\item HSD  : if set, the denoised image will be recontructed using the Hybrid Steepest Descent Method (soft thresholding at each iteration of the reconstruction)\n  \\item  coef\\_seuil  : determines the threshold for the detection of significant coefficients. For each scale i, the threshold is set to $\\text{coef\\_seuil}*\\sigma_i$ (default is 5)\n  \\item coef\\_pos  : if set, negative wavelets coefficients are set to 0.\n  \\item  First\\_Scale  : if $> 2$, finer wavelet scales are set to 0. (default is 1)\n  \\item  mask  : if set, enables impainting with the given mask\n  \\item filter  : if set, the inverse wavelet transform will be computed using filters. Else, it will be obtained by a simple addition of all wavelet scales.\n  \\item pyr  : if set, use pyramidal wavelet transform for the soft thresholding\n  \\item expo  : if set, decreases the thresold exponentially at each step of the HSD. Else, decreases the threshold linearly\n  \\item alm : if set, thresholding is made on alm coefficients instead of wavelet coefficients\n  \\item  curvelets : if set, thresholding is made on curvelets coefficients instead of wavelet coefficients\n  \\item  separation : if set, compute separately the sources and the background\n  \\item  update\\_support : if set, update the multi-resoluation support at each iteration\n  \\item  split\\_support : if set, splits the multi-resolution support\n\\end{itemize}\n\n\n\n\n\\subsection{Subroutines}\n\n\\vspace{0.3cm}\n%$\\twoheadrightarrow$\n$\\looparrowright$ \\textbf{mrs\\_msvsts\\_IUWT\\_param\\_computing.pro} :  For a given number of scales, determines the VST operator at each scale for the MS-VST transform with spherical isotropic Undecimated Wavelet Transform. At scale j, the VST operator is: $T_j(a_j) = b_{(j)} * sgn(a_j+c_{(j)}) * \\sqrt{(|a_j+c_{(j)}|)}$ where $a_j$ is the jth scale coefficient of the wavelet transform.\n\n\\begin{center}\n \\bf{USAGE : mrs\\_msvsts\\_IUWT\\_param\\_computing,nbr,c,b,h,tau1,tau2,tau3,sigma}\n\\end{center}\n\n\\textbf{INPUTS} : \n\\begin{itemize}\n\\item{nbr = (int) number of scales for the MS-VST transform}\n\\end{itemize}\n\n\\textbf{OUTPUTS} : \n\\begin{itemize}\n\\item{c = (1D IDL array) vector of the c(j) coefficients for each scale j}\n\\item{b = (1D IDL array) vector of the b(j) coefficients for each scale j}\n\\item{h = (IDL array) h[*,j] is the low pass filter which gives the jth scale from the original image}\n\\item{tau1 = (1D IDL array) vector of the 1st order moments of h[*,j] for each scale j}\n\\item{tau2 = (1D IDL array) vector of the 2st order moments of h[*,j] for each scale j}\n\\item{tau3 = (1D IDL array) vector of the 3rd order moments of h[*,j] for each scale j}\n\\item{sigma = (1D IDL array) vector of the asymptotic standard deviations of detail coefficients issued from locally homogeneous parts of a signal for each wavelet scale}\n\\end{itemize}\n\n\\vspace{0.3cm}\n%$\\twoheadrightarrow$\n$\\looparrowright$ \\textbf{mrs\\_msvsts\\_IUWT\\_transform.pro} :  Computes the multi-scale variance stabilising transform on the sphere with undecimated isotropic wavelet transform, using the HEALPix representation (nested data representation). The wavelet function is zonal and its spherical harmonics coefficients $a_{l0}$ follow a cubic box-spline profile. If DifInSH is set, wavelet coefficients are derived in the Spherical Harmonic Space, otherwise (default) they are derived in the direct space.\n\n\\begin{center}\n \\bf{USAGE : mrs\\_msvsts\\_IUWT\\_transform, Imag, Trans, NbrScale=NbrScale, lmax=lmax, DifInSH=DifInSH}\n\\end{center}\n\n\\textbf{INPUTS} :\n\\begin{itemize}\n\\item{Imag = (IDL array) HEALPix data}\n\\end{itemize}\n\n\\textbf{OUTPUTS} : \n\\begin{itemize}\n\\item{Trans = IDL structure with the following fields:\n\\begin{itemize}\n  \\item NbrScale = (int) number of scales \n  \\item nside = (int) Healpix nside parameter\n  \\item lmax = (int) Maximum l value in the Spherical Harmonic Space (Healpix)\n  \\item npix = (int) Number of pixels of the input image (12*nside*nside)\n  \\item Coef = (IDL array) stabilised wavelet transform of the data\n  \\item Coef[*,0] = stabilised wavelet coefficients of the finest scale (highest frequencies).\n  \\item Coef[*,NbrScale-1] = coarsest scale (lowest frequencies). \n  \\item lmax = (int) lmax parameter at the first scale\n\\end{itemize} }\n\\end{itemize}\n\n\\textbf{KEYWORDS} :\n\\begin{itemize}\n  \\item NbrScale = (int) Number of scales (default is 4)\n  \\item Lmax = (int) Number of spherical harmonics computed in the decomposition (default is 3*nside, should be between 2*nside and 4*nside)\n  \\item DifInSH   : If set, compute the wavelet coefficients as the difference between two resolution in the spherical harmonics representation. Otherwise, the wavelet coefficients are computed as the difference between two resolutions in the initial representation.\n\\end{itemize}\n\n\\vspace{0.3cm}\n%$\\twoheadrightarrow$\n$\\looparrowright$ \\textbf{mrs\\_msvsts\\_IUWT\\_hypothesis\\_testing.pro} :  Computes the MS-VSTS + Isotropic Undecimate Wavelet Transform of a Poisson Image, perform hypothesis testing on coefficients, returns the multi-resolution support and the denoised image using direct reconstruction\n\n\\begin{center}\n \\bf{USAGE : mrs\\_msvsts\\_IUWT\\_hypothesis\\_testing, image, image\\_vst, support, image\\_rec, NbrScale=NbrScale, coef\\_seuil=coef\\_seuil, First\\_Scale=First\\_Scale, background=background}\n\\end{center}\n\n\\textbf{INPUTS} :\n\\begin{itemize}\n  \\item Imag = (IDL array) HEALPix data\n  \\item (optional) background = (IDL array) if set, substracts a background to the image.\n\\end{itemize}\n\n\\textbf{OUTPUTS} : \n\\begin{itemize}\n  \\item image\\_vst = (IDL structure) MS-VSTS transform of the image computed with mrs\\_msvsts\\_IUWT\\_transform\n  \\item support = (IDL array) multi-resolution support\n  \\item image\\_rec = (IDL array) directly reconstructed denoised image\n\\end{itemize}\n\n\\textbf{KEYWORDS} :\n\\begin{itemize}\n  \\item NbrScale = (int) Number of scales (default is 4)\n  \\item coef\\_seuil = (int) determines the threshold for the detection of significant coefficients. For each scale i, the threshold is set to $\\text{coef\\_seuil}*\\sigma_i$ (default is 5)\n  \\item First\\_Scale = (int) if $> 2$, finer wavelet scales are set to 0. (default is 1)\n\\end{itemize}\n\n\n\\section{Denoising using MS-VSTS + Curvelet Transform}\n\n\\subsection{Main routine}\n\n$\\looparrowright$ \\textbf{mrs\\_msvsts\\_curv\\_denoising.pro} :  Compute Poisson denoising on spherical HEALPix data with MS-VSTS + Curvelet Transform method.\n\n\n\\begin{center}\n \\bf{USAGE : mrs\\_msvsts\\_curv\\_denoising, image, image\\_reconstruite, support, nbrscale=nbrscale, coef\\_seuil=coef\\_seuil, suppr\\_scale1=suppr\\_scale1, hsd=hsd, niter=niter}\n\\end{center}\n\n\\textbf{INPUTS} : \n\\begin{itemize}\n\\item{Image = (IDL array) HEALPix data to be denoised}\n\\end{itemize}\n\n\\textbf{OUTPUTS} : \n\\begin{itemize}\n\\item{Image\\_reconstruite = (IDL array) HEALPix denoised image}\n\\item{(optional) Support = (IDL array) multi-resolution support of the image}\n\\end{itemize}\n\n\\textbf{KEYWORD} :\n\n\\begin{itemize}\n  \\item NbrScale = Number of scales (default is 4)\n  \\item HSD = if set, the denoised estimate will be recontructed using the Hybrid Steepest Descent Method (soft thresholding at each iteration of the reconstruction). If not set, the estimate is direclty reconstructed.\n  \\item niter = Number of iterations\n   \\item coef\\_seuil = determines the threshold for the detection of significant coefficients. For each scale i, the threshold is set to $\\text{coef\\_seuil}*\\sigma_i$ (default is 5)\n  \\item coef\\_pos = if set, negative wavelets coefficients are set to 0.\n  \\item suppr\\_scale1 = if set, remove the finest scale from the reconstructed estimate.\n\\end{itemize}\n\n\\subsection{Subroutines}\n$\\looparrowright$ \\textbf{mrs\\_msvsts\\_curv\\_transform.pro} : Compute the multi-scale variance stabilizing transform on the sphere with standard undecimated curvelet transform on the sphere, using the healPix pixel representation (nested data representation). A band of the curvelet transform is defined by two number, the 2D WT scale number and the ridgelet scale number. The output is a IDL structure.\n\n\n\\begin{center}\n \\bf{USAGE : mrs\\_msvsts\\_curv\\_transform, Imag, Trans, lmax=lmax, NbrScale=NbrScale, FirstBlockSize=FirstBlockSize}\n\\end{center}\n\n\\textbf{INPUTS} : \n\\begin{itemize}\n\\item{Image = (IDL array) HEALPix data to be transformed}\n\\end{itemize}\n\n\\textbf{OUTPUTS} : \n\\begin{itemize}\n\\item Trans = IDL structures with the following fields:\n \\begin{itemize}\n  \\item NBRSCALE = (INT) Nbr of the scale in the 2D WT\n  \\item TABBLOCKSIZE = (INT) TABBLOCKSIZE[j], Block size in the ridgelet transform at scale j.\n  $j = [0..NBRSCALE-2]$\n  \\item TABNBRSCALERID = (INT) TABNBRSCALERID[j], number of ridgelet band at scale j \n  \\item TABNORM = (2D IDL ARRAY) Normalization array\n  \\item RIDSCALE1 = (IDL STRUCT) ridgelet transform of the first wavelet scale (see mrs\\_ridtrans.pro for details)\n  \\item RIDSCALEj = (IDL STRUCT) ridgelet transform of the jth wavelet scale.\n  $j = [0..NBRSCALE-2]$\n  \\item LASTSCALE = (IDL 1D array) Healpix image of the coarsest scale\n  \\item WT = (IDL STRUCT) Wavelet structure (for internal use only)\n  \\item PYRTRANS = (INT) equal to 1 for a pyramidal curvelet transform and 0 otherwise\n \\end{itemize}\n\\end{itemize}\n\n\\textbf{KEYWORD} :\n\n\\begin{itemize}\n  \\item NbrScale = (INT) Number of scale in the 2D wavelet transform (defaut 4)\n  \\item Undec = (INT) if set, an undecimated curvelet transform is used instead of the pyramidal curvelet transform\n  \\item FirstBlockSize = (INT) Block size in the ridgelet transform at the finest scale (default is 16)\n  \\item Lmax = (INT) Number of used spherical harmoniques used in the wavelet transform (defaut = 3*nside, should be between 2*nside and 4*nside)\n  \\item Overlap = (LONG) is equal to 1 if blocks are overlapping\n\\end{itemize}\n\n\\section{Multichannel Denoising using MS-VSTS + Multichannel Wavelet Transform}\n\n%\\subsection{Main routine}\n\n\\vspace{0.3cm}\n\n$\\blacktriangleright$   \\textbf {Starting from a set of photon counts maps}\n\n\\vspace{0.3cm}\n\n$\\looparrowright$ \\textbf{mrs\\_msvsts\\_multichannel\\_denoising.pro} :  Compute multichannel Poisson denoising on spherical 2D-1D HEALPix data with MS-VSTS + multichannel Wavelet Transform method.\n\n\\begin{center}\n \\bf{USAGE : mrs\\_msvsts\\_multichannel\\_denoising,input,solution,NbrScale1=NbrScale1,NbrScale2=NbrScale2,niter=niter\n}\n\\end{center}\n\n\\textbf{INPUT} : \n\\begin{itemize}\n\\item{Input = (IDL array) multichannel HEALPix data to be denoised}\n\\end{itemize}\n\n\\textbf{OUTPUT} : \n\\begin{itemize}\n\\item{Solution = (IDL array) multichannel HEALPix denoised image}\n\\end{itemize}\n\n\\textbf{KEYWORD}\n\n\\begin{itemize}\n  \\item NbrScale1 : Number of scales for the two spatial dimensions (default is 6)\n  \\item NbrScale2 : Number of scales for the non-spatial dimension (time or energy) (default is 6)\n  \\item niter  : Number of iterations\n\\end{itemize}\n\n\\vspace{0.3cm}\n\n%\\subsection{subroutines}\n\n%\\vspace{0.3cm}\n\n%$\\looparrowright$ \\textbf{mrs\\_msvsts\\_multichannel_denoising.pro}\n\n\n\\section{Multichannel Deconvolution using MS-VSTS + Multichannel Wavelet Transform}\n\n\\vspace{0.3cm}\n\n$\\blacktriangleright$   \\textbf {Starting from a set of photon counts maps}\n\n\\vspace{0.3cm}\n\n$\\looparrowright$ \\textbf{mrs\\_msvsts\\_multichannel\\_deconvolution.pro} :  Compute multichannel Poisson deconvolution on spherical 2D-1D HEALPix data with MS-VSTS + multichannel Wavelet Transform method.\n\n\\begin{center}\n \\bf{USAGE : mrs\\_msvsts\\_multichannel\\_deconvolution,input,solution,NbrScale1=NbrScale1,NbrScale2=NbrScale2,niter=niter,beam=beam,regularization}\n\\end{center}\n\n\\textbf{INPUT} : \n\\begin{itemize}\n\\item{Input = (IDL array) multichannel HEALPix data to be denoised}\n\\item{beam = (IDL array) set of convolution beams}\n\\end{itemize}\n\n\\textbf{OUTPUT} : \n\\begin{itemize}\n\\item{Solution = (IDL array) multichannel HEALPix denoised image}\n\\end{itemize}\n\n\\textbf{KEYWORD}\n\n\\begin{itemize}\n  \\item NbrScale1 : Number of scales for the two spatial dimensions (default is 6)\n  \\item NbrScale2 : Number of scales for the non-spatial dimension (time or energy) (default is 6)\n  \\item niter  : Number of iterations\n  \\item regularization : if set, uses a regularization parameter (set to 0.01) to improve the convergence speed of the algorithm\n\\end{itemize}\n\n\n\n\n\n\n%$\\looparrowright$  \\textbf{add\\_gnoise\\_kappa.pro} : Add a Gaussian noise to a mass map structure :\n%\\index{add\\_gnoise\\_kappa.pro}\n%\\noindent Add a Gaussian noise to the mass map by adding a gaussian noise to the shear maps depending on the number of galaxies per pixel.\n\n\n\n%\\begin{center}\n% \\textbf{USAGE : add\\_gnoise\\_kappa, smap, ng, s, smapn}\n%\\end{center}\n\n%\\textbf{INPUTS} : \n%\\begin{itemize}\n%\\item{smap = IDL structure of mass map with the following fields : \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- kappa = (IDL array) mass map}\n%\\item{ng = (int) galaxies number per arcmin square}\n%\\end{itemize}\n\n%\n%\\textbf{OUTPUTS} : \n%\\begin{itemize}\n%\\item{s = (int) the root mean square of the noise}\n%\\item{smapn = IDL structure of mass map embedded in a gaussian noise with the following fields : \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- kappa = (IDL array) noisy mass map}\n%\\end{itemize}\n\n%\n%$\\blacktriangleright$   \\textbf {Starting from a shear maps without noise}\n\n%\\vspace{0.3cm}\n\n%$\\looparrowright$ \\textbf{mk\\_gamma.pro} : Build a shear maps structure from shear maps :\n%\\index{mk\\_gamma.pro}\n%\\noindent Build a shear maps structure from shear maps and the field size in pixels and in degrees (or arcmin)\n\n%\\begin{center}\n% \\bf{USAGE : mk\\_gamma, gamma1, gamma2, npix1, npix2, theta1, theta2, amin = amin, sgamma}\n%\\end{center}\n\n%\\textbf{INPUTS} : \n%\\begin{itemize}\n%\\item{gamma1, gamma2 = IDL array of shear maps $\\gamma_1$ and $\\gamma_2$}\n%\\item{npix1, npix2 = (int) map size in pixels}\n%\\item{theta1, theta2 = (int) map size in degrees (or arcmin if the keyword amin is set)}\n%\\end{itemize}\n\n%\\textbf{KEYWORD} :\n% \\begin{itemize}\n%\\item{amin = (string) if set, the map size theta1 and theta2 are assumed to be in arcmin}\n%\\end{itemize}\n\n%\\textbf{OUTPUTS} : \n%\\begin{itemize}\n%\\item{sgamma = shear maps IDL structure with the following fields : \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- gamma1, gamma2 = (IDL array) shear maps $\\gamma_1$ and $\\gamma_2$}\n%\\end{itemize}\n\n%\n%$\\looparrowright$  \\textbf{add\\_gnoise\\_gamma.pro} : Add a Gaussian noise to a shear maps structure :\n%\\index{add\\_gnoise\\_gamma.pro}\n%\\noindent Add a Gaussian noise to the shear maps depending on the number of galaxies per pixel.\n\n%\\begin{center}\n% \\textbf{USAGE : add\\_gnoise\\_gamma, sgamma, ng, s, sgamman}\n%\\end{center}\n\n%\\textbf{INPUTS} : \n%\\begin{itemize}\n%\\item{sgamma = IDL structure of mass map with the following fields : \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- gamma1, gamma2 = (IDL array) shear maps $\\gamma_1$ and $\\gamma_2$}\n%\\item{ng = (int) galaxies number per arcmin square}\n%\\end{itemize}\n\n%\n%\\textbf{OUTPUTS} : \n%\\begin{itemize}\n%\\item{s = (int) the root mean square of the noise}\n%\\item{sgamman = IDL structure of shear maps embedded in a gaussian noise with the following fields : \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- gamma1, gamma2 = (IDL array) noisy shear maps $\\gamma_{1b}$ and $\\gamma_{2b}$}\n%\\end{itemize}\n\n%\n%$\\looparrowright$  \\textbf{gamma\\_to\\_kappa.pro} : Derive a mass map structure from a shear maps structure:\n%\\index{gamma\\_to\\_kappa.pro}\n%\\noindent Derive a mass map structure from shear maps structure using the relation \\ref{eqn_reckE} in\n%chapter \\ref{ch_weak}.\n\n%\\begin{center}\n% \\textbf{USAGE : gamma\\_to\\_kappa, sgamma, smap}\n%\\end{center}\n\n%\\textbf{INPUTS} : \n%\\begin{itemize}\n%\\item{sgamma = IDL structure of shear maps with the following fields : \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- gamma1, gamma2 = (IDL array) shear maps $\\gamma_1$ and $\\gamma_2$}\n%\\end{itemize}\n\n%\\textbf{KEYWORD} :\n% \\begin{itemize}\n%\\item{cat = (string) if set, some fields (specific to real data) are added to the output mass map structure (ng, wtot, mask, gamma\\_err, kappa\\_err, ng\\_eff, sigma\\_gamma,x1\\_ran, x2\\_ran, x1\\_m, x2\\_m)}\n%\\item{bmode = (string) if set, the magnetic component of the mass map is computed, otherwise is the electric component that is computed}\n%\\end{itemize}\n\n%\n%\\textbf{OUTPUTS} : \n%\\begin{itemize}\n\n%\\item{smap = IDL structure of mass map with the following fields : \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- kappa = (IDL array) mass map\\\\\n%- gamma1, gamma2 = (IDL array) shear maps $\\gamma_1$ and $\\gamma_2$}\n\n%\\textbf{if keyword\\_set(cat) : }\n%\\item{smap = IDL structure of mass map with the following fields : \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- kappa = (IDL array) mass map\\\\\n%- gamma1, gamma2 = (IDL array) shear maps\\\\\n%- ng = (IDL array) number of galaxies per pixel\\\\\n%- wtot = (IDL array) weight per pixel\\\\\n%- mask = (IDL array) mask of the missing data\\\\\n%- gamma\\_err = (IDL array) measurement error in shear maps per pixel taking into account the weight of  each galaxy\\\\\n%- kappa\\_err = (IDL array) measurement error in mass map per pixel\\\\\n%(kappa\\_err=gamma\\_err/sqrt(2.))\\\\\n%- ng\\_eff = (IDL array) effective number of galaxies per pixel taking into account the weight of each galaxy\\\\\n%- sigma\\_gamma = (int) measurement error in shear maps per pixel\\\\\n%- x1\\_ran, x2\\_ran = (int) exact range in degree\\\\\n%- x1\\_m, x2\\_m = IDL array with the exact middle position (in deg) of each pixel }\n%\\end{itemize}\n\n%\\subsection{IDL routines for real data}\n\n%\\vspace{0.3cm}\n\n%$\\blacktriangleright$   \\textbf {Build a catalogue structure}\n\n%\\vspace{0.3cm}\n%%$\\twoheadrightarrow$\n%$\\looparrowright$ \\textbf{mk\\_gcat.pro} : Build a shear catalogue structure :\n%\\index{mk\\_gcat.pro}\n%\\begin{center}\n% \\textbf{USAGE : mk\\_gcat, x, y, pixscale, weight, g1, g2, gcat}\n%\\end{center}\n\n%\\textbf{INPUTS} : \n%\\begin{itemize}\n%\\item{x, y = (1D IDL array) coordinates in pixels of each galaxy}\n%\\item{pixscale = (int) pixel size [in rad]}\n%\\item{weight = (1D IDL array) weight of each galaxy}\n%\\item{g1, g2 = (1D IDL array) shear $\\gamma_1$ and $\\gamma_2$ of each galaxy}\n%\\end{itemize}\n\n%\n%\\textbf{OUTPUTS} : \n%\\begin{itemize}\n%\\item{gcat = IDL structure of catalogue with the following fields : \\\\\n%- x, y = (1D IDL array) coordinates in pixels of each galaxy\\\\\n%- pixscale = (int) pixel size [in deg] \\\\\n%- weight = (1D IDL array) weight of each galaxy \\\\\n%- gamma1, gamma2 = (1D IDL array) shear $\\gamma_1$ and $\\gamma_2$ of each galaxy}\n%\\end{itemize}\n\n%$\\blacktriangleright$   \\textbf {Build a shear maps structure}\n\n%\\vspace{0.3cm}\n%%$\\twoheadrightarrow$\n%$\\looparrowright$ \\textbf{gcat\\_to\\_gamma.pro} : Build a (pixelised) shear maps structure from a shear catalogue structure :\n%\\index{gcat\\_to\\_gamma.pro}\n%\\begin{center}\n% \\textbf{USAGE : gcat\\_to\\_gamma, gcat, gamma, delta=delta}\n%\\end{center}\n\n%\\textbf{INPUTS} : \n%\\begin{itemize}\n%\\item{gcat = IDL structure of catalogue with the following fields : \\\\\n%- x, y = (1D IDL array) galaxies position in pixels of each galaxy\\\\\n%- pixscale = (int) pixel size [in rad] \\\\\n%- weight = (1D IDL array) weight of each galaxy \\\\\n%- gamma1, gamma2 = (1D IDL array) shear $\\gamma_1$ and $\\gamma_2$ of each galaxy}\n%\\end{itemize}\n\n%\\textbf{KEYWORD} :\n% \\begin{itemize}\n%\\item{delta = (string) pixel size in $arcmin$, default is 1}\n%\\end{itemize}\n\n%\n\n%\\textbf{OUTPUTS} : \n%\\begin{itemize}\n%\\item{gamma = IDL structure of shear maps with the following fields : \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- kappa = (IDL array) mass map\\\\\n%- gamma1, gamma2 = (IDL array) shear maps $\\gamma_1$ and $\\gamma_2$\\\\\n%- ng = (IDL array) number of galaxies per pixel\\\\\n%- wtot = (IDL array) weight per pixel\\\\\n%- mask = (IDL array) mask of the missing data\\\\\n%- gamma\\_err = (IDL array) measurement error in shear maps per pixel taking into account the weight of each galaxy\\\\\n%- kappa\\_err = (IDL array) measurement error in mass map per pixel \\\\\n%(kappa\\_err=gamma\\_err/sqrt(2.))\\\\\n%- ng\\_eff = (IDL array) effective number of galaxies per pixel taking into account the weight of each galaxy\\\\\n%- sigma\\_gamma = (int) measurement error in shear maps per pixel\\\\\n%- x1\\_ran, x2\\_ran = (int) exact range in degree\\\\\n%- x1\\_m, x2\\_m = IDL array with the exact middle position (in deg) of each pixel }\\\\\n%\\end{itemize}\n\n%\n%\\section{Relations between the distortion field and the projected (Electric) mass concentration}\n\n%\\vspace{0.3cm}\n\n%\\subsection{From shear maps $\\gamma_1$, $\\gamma_2$ to mass map $\\kappa$}\n%$\\looparrowright$ \\textbf{gamma\\_to\\_kappa.pro} : See description in previous subsection.\\\\\n%\\index{gamma\\_to\\_kappa.pro}\n\n%\\subsection{From mass map $\\kappa$ to shear maps $\\gamma_1$, $\\gamma_2$}\n%$\\looparrowright$ \\textbf{kappa\\_to\\_gamma.pro} : Derive a shear maps structure from a mass map structure using the relation \\ref{eq_gamma} in chapter \\ref{ch_weak}.\n\n%\\begin{center}\n% \\textbf{USAGE : kappa\\_to\\_gamma, smap, sgamma}\n%\\end{center}\n\n%\\textbf{INPUTS} : \n%\\begin{itemize}\n%\\item{smap = IDL structure of mass map with the following fields : \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- kappa = (IDL array) mass map $\\kappa$}\n%\\end{itemize}\n\n%\\textbf{KEYWORD} :\n% \\begin{itemize}\n%\\item{cat = (string) if set, some fields (specific to real data) are added to the output mass map structure (ng, wtot, mask, gamma\\_err, kappa\\_err, ng\\_eff, sigma\\_gamma,x1\\_ran, x2\\_ran, x1\\_m, x2\\_m)}\n%\\end{itemize}\n\n%\n%\\textbf{OUTPUTS} : \n%\\begin{itemize}\n\n%\\item{sgamma = IDL structure of shear maps with the following fields : \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- kappa = (IDL array) mass map\\\\\n%- gamma1, gamma2 = (IDL array) shear maps $\\gamma_1$ and $\\gamma_2$}\n\n%\\textbf{if keyword\\_set(cat) : }\n%\\item{sgamma = IDL structure of mass map with the following fields : \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- kappa = (IDL array) mass map\\\\\n%- gamma1, gamma2 = (IDL array) shear maps\\\\\n%- ng = (IDL array) number of galaxies per pixel\\\\\n%- wtot = (IDL array) weight per pixel\\\\\n%- mask = (IDL array) mask of the missing data\\\\\n%- gamma\\_err = (IDL array) measurement error in shear maps per pixel taking into account the weight of each galaxy\\\\\n%- kappa\\_err = (IDL array) measurement error in mass map per pixel\\\\ \n%(kappa\\_err=gamma\\_err/sqrt(2.))\\\\\n%- ng\\_eff = (IDL array) effective number of galaxies per pixel taking into account the weight of each galaxy\\\\\n%- sigma\\_gamma = (int) measurement error in shear maps per pixel\\\\\n%- x1\\_ran, x2\\_ran = (int) exact range in degree\\\\\n%- x1\\_m, x2\\_m = IDL array with the exact middle position (in deg) of each pixel }\n%\\end{itemize}\n\n\n%A set of routines has been developed in IDL (summarized in flowchart Fig. \\ref{organigramme}). Starting IDL using the script program {\\em mrl.pro} allows the user to add the MRLENS software to the IDL environment. Thus, all routines described in the following can be called. An online help, facility is also available by calling the {\\em  mrh} IDL program.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\\section{Installation}\n\n%\\subsection{System requirements}\n%\\begin{itemize}\n%\\item Disk space : Make sure you have approximately 400 MB of disk space available. After installation MRLENS package occupies approximately 100 MB or 200MB (version with data) of disk space.\\\\\n%\\item Platform : The binaries C++ called by IDL routines are not available under all the systems therefore you cannot use the package on all platforms. The supported platforms are : Unix, Linux, Mac OS X. They will be soon available in Windows platform.\\\\\n%\\end{itemize}\n\n%\\subsection{Download}\n%Use the link to download the package MRL and copy the file in your home directory (/home/user/).\\\\\n%Then, uncompress the filename.tar.gz file by typing:\\\\\n%gunzip filename.tar.gz \\\\\n%tar -xvf filename.tar\\\\\n\n%\n%\\subsection{Installation instructions}\n%The MRLENS package requires that IDL (version 6.0 or later) to be installed. \n%The alias \\textbf{idl} should also be defined to launch the \n%IDL environment. Then, installing the MRLENS package simply requires adding \n%some lines in your shell environment profile depending on your shell :\n%(The command \"echo \\$SHELL\" will give your SHELL environment : bash, csh or tcsh)\n%\\begin{itemize}\n%\\item{define the environment variable \\textbf{MRL} :\\\\\n%In csh or tcsh :\\\\\n%setenv MRL /home/user/MRL\\\\ \n%In bash :\\\\ \n%MRL=/home/user/MRL;export MRL} \\\\\n% \\item{define the alias \\textbf{mrl} \\\\  \n% In csh or tcsh :\\\\\n% alias mrl  'idl \\$MRL/idl/mrl' \\\\ \n% In bash :\\\\\n% alias mrl ='idl \\$MRL/idl/mrl'} \\\\\n%\\end{itemize}\n\n%\\subsection{Startup instructions}\n%The command \"mrl\" will start the IDL session using the MRL environment.\n%The programs can be found in \\$MRL/idl.\n%These routines use data in directory \\$MRL/Data.\n%The command \"mrh\" will open the online help.\\\\\n\n%Two scripts are included in the package giving examples of how to run some main routines :\\\\\n%- mk\\_test\\_1.pro\\\\\n%- mk\\_test\\_2.pro\\\\\n%These scripts use the data files provided with the package in \\$MRL/Data. The first use a simulated noiseless mass map and the second a simulated noisy catalogue.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\\section{Build an Electric noisy mass map}\n%%\\section{IDL routines for simulated data}\n\n%\\subsection{IDL routines for simulated data}\n\n%\\vspace{0.3cm}\n\n%$\\blacktriangleright$   \\textbf {Starting from a mass map without noise}\n\n%\\vspace{0.3cm}\n%%$\\twoheadrightarrow$\n%$\\looparrowright$ \\textbf{mk\\_kappa.pro} : Build a mass map structure from a mass map :\n%\\index{mk\\_kappa.pro}\n\n%\\noindent Build a mass map structure from the mass map and the field size in pixels and in degrees (or arcmin)\n%\\begin{center}\n% \\bf{USAGE : mk\\_kappa, map, npix1, npix2, theta1, theta2, amin = amin, smap}\n%\\end{center}\n\n%\\textbf{INPUTS} : \n%\\begin{itemize}\n%\\item{map = IDL array of mass map}\n%\\item{npix1, npix2 = (int) map size in pixels}\n%\\item{theta1, theta2 = (int) map size in degrees (or arcmin if the keyword amin is set)}\n%\\end{itemize}\n\n%\\textbf{KEYWORD} :\n% \\begin{itemize}\n%\\item{amin = (string) if set, the map size theta1 and theta2 are assumed to be in arcmin}\n%\\end{itemize}\n\n%\\textbf{OUTPUTS} : \n%\\begin{itemize}\n%\\item{smap = mass map IDL structure with the following fields : \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- kappa = (IDL array) mass map}\\\\\n%\\end{itemize}\n\n%$\\looparrowright$  \\textbf{add\\_gnoise\\_kappa.pro} : Add a Gaussian noise to a mass map structure :\n%\\index{add\\_gnoise\\_kappa.pro}\n%\\noindent Add a Gaussian noise to the mass map by adding a gaussian noise to the shear maps depending on the number of galaxies per pixel.\n\n%\\begin{center}\n% \\textbf{USAGE : add\\_gnoise\\_kappa, smap, ng, s, smapn}\n%\\end{center}\n\n%\\textbf{INPUTS} : \n%\\begin{itemize}\n%\\item{smap = IDL structure of mass map with the following fields : \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- kappa = (IDL array) mass map}\n%\\item{ng = (int) galaxies number per arcmin square}\n%\\end{itemize}\n\n%\n%\\textbf{OUTPUTS} : \n%\\begin{itemize}\n%\\item{s = (int) the root mean square of the noise}\n%\\item{smapn = IDL structure of mass map embedded in a gaussian noise with the following fields : \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- kappa = (IDL array) noisy mass map}\n%\\end{itemize}\n\n%\n%$\\blacktriangleright$   \\textbf {Starting from a shear maps without noise}\n\n%\\vspace{0.3cm}\n\n%$\\looparrowright$ \\textbf{mk\\_gamma.pro} : Build a shear maps structure from shear maps :\n%\\index{mk\\_gamma.pro}\n%\\noindent Build a shear maps structure from shear maps and the field size in pixels and in degrees (or arcmin)\n\n%\\begin{center}\n% \\bf{USAGE : mk\\_gamma, gamma1, gamma2, npix1, npix2, theta1, theta2, amin = amin, sgamma}\n%\\end{center}\n\n%\\textbf{INPUTS} : \n%\\begin{itemize}\n%\\item{gamma1, gamma2 = IDL array of shear maps $\\gamma_1$ and $\\gamma_2$}\n%\\item{npix1, npix2 = (int) map size in pixels}\n%\\item{theta1, theta2 = (int) map size in degrees (or arcmin if the keyword amin is set)}\n%\\end{itemize}\n\n%\\textbf{KEYWORD} :\n% \\begin{itemize}\n%\\item{amin = (string) if set, the map size theta1 and theta2 are assumed to be in arcmin}\n%\\end{itemize}\n\n%\\textbf{OUTPUTS} : \n%\\begin{itemize}\n%\\item{sgamma = shear maps IDL structure with the following fields : \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- gamma1, gamma2 = (IDL array) shear maps $\\gamma_1$ and $\\gamma_2$}\n%\\end{itemize}\n\n%\n%$\\looparrowright$  \\textbf{add\\_gnoise\\_gamma.pro} : Add a Gaussian noise to a shear maps structure :\n%\\index{add\\_gnoise\\_gamma.pro}\n%\\noindent Add a Gaussian noise to the shear maps depending on the number of galaxies per pixel.\n\n%\\begin{center}\n% \\textbf{USAGE : add\\_gnoise\\_gamma, sgamma, ng, s, sgamman}\n%\\end{center}\n\n%\\textbf{INPUTS} : \n%\\begin{itemize}\n%\\item{sgamma = IDL structure of mass map with the following fields : \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- gamma1, gamma2 = (IDL array) shear maps $\\gamma_1$ and $\\gamma_2$}\n%\\item{ng = (int) galaxies number per arcmin square}\n%\\end{itemize}\n\n%\n%\\textbf{OUTPUTS} : \n%\\begin{itemize}\n%\\item{s = (int) the root mean square of the noise}\n%\\item{sgamman = IDL structure of shear maps embedded in a gaussian noise with the following fields : \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- gamma1, gamma2 = (IDL array) noisy shear maps $\\gamma_{1b}$ and $\\gamma_{2b}$}\n%\\end{itemize}\n\n%\n%$\\looparrowright$  \\textbf{gamma\\_to\\_kappa.pro} : Derive a mass map structure from a shear maps structure:\n%\\index{gamma\\_to\\_kappa.pro}\n%\\noindent Derive a mass map structure from shear maps structure using the relation \\ref{eqn_reckE} in\n%chapter \\ref{ch_weak}.\n\n%\\begin{center}\n% \\textbf{USAGE : gamma\\_to\\_kappa, sgamma, smap}\n%\\end{center}\n\n%\\textbf{INPUTS} : \n%\\begin{itemize}\n%\\item{sgamma = IDL structure of shear maps with the following fields : \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- gamma1, gamma2 = (IDL array) shear maps $\\gamma_1$ and $\\gamma_2$}\n%\\end{itemize}\n\n%\\textbf{KEYWORD} :\n% \\begin{itemize}\n%\\item{cat = (string) if set, some fields (specific to real data) are added to the output mass map structure (ng, wtot, mask, gamma\\_err, kappa\\_err, ng\\_eff, sigma\\_gamma,x1\\_ran, x2\\_ran, x1\\_m, x2\\_m)}\n%\\item{bmode = (string) if set, the magnetic component of the mass map is computed, otherwise is the electric component that is computed}\n%\\end{itemize}\n\n%\n%\\textbf{OUTPUTS} : \n%\\begin{itemize}\n\n%\\item{smap = IDL structure of mass map with the following fields : \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- kappa = (IDL array) mass map\\\\\n%- gamma1, gamma2 = (IDL array) shear maps $\\gamma_1$ and $\\gamma_2$}\n\n%\\textbf{if keyword\\_set(cat) : }\n%\\item{smap = IDL structure of mass map with the following fields : \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- kappa = (IDL array) mass map\\\\\n%- gamma1, gamma2 = (IDL array) shear maps\\\\\n%- ng = (IDL array) number of galaxies per pixel\\\\\n%- wtot = (IDL array) weight per pixel\\\\\n%- mask = (IDL array) mask of the missing data\\\\\n%- gamma\\_err = (IDL array) measurement error in shear maps per pixel taking into account the weight of  each galaxy\\\\\n%- kappa\\_err = (IDL array) measurement error in mass map per pixel\\\\\n%(kappa\\_err=gamma\\_err/sqrt(2.))\\\\\n%- ng\\_eff = (IDL array) effective number of galaxies per pixel taking into account the weight of each galaxy\\\\\n%- sigma\\_gamma = (int) measurement error in shear maps per pixel\\\\\n%- x1\\_ran, x2\\_ran = (int) exact range in degree\\\\\n%- x1\\_m, x2\\_m = IDL array with the exact middle position (in deg) of each pixel }\n%\\end{itemize}\n\n%\\subsection{IDL routines for real data}\n\n%\\vspace{0.3cm}\n\n%$\\blacktriangleright$   \\textbf {Build a catalogue structure}\n\n%\\vspace{0.3cm}\n%%$\\twoheadrightarrow$\n%$\\looparrowright$ \\textbf{mk\\_gcat.pro} : Build a shear catalogue structure :\n%\\index{mk\\_gcat.pro}\n%\\begin{center}\n% \\textbf{USAGE : mk\\_gcat, x, y, pixscale, weight, g1, g2, gcat}\n%\\end{center}\n\n%\\textbf{INPUTS} : \n%\\begin{itemize}\n%\\item{x, y = (1D IDL array) coordinates in pixels of each galaxy}\n%\\item{pixscale = (int) pixel size [in rad]}\n%\\item{weight = (1D IDL array) weight of each galaxy}\n%\\item{g1, g2 = (1D IDL array) shear $\\gamma_1$ and $\\gamma_2$ of each galaxy}\n%\\end{itemize}\n\n%\n%\\textbf{OUTPUTS} : \n%\\begin{itemize}\n%\\item{gcat = IDL structure of catalogue with the following fields : \\\\\n%- x, y = (1D IDL array) coordinates in pixels of each galaxy\\\\\n%- pixscale = (int) pixel size [in deg] \\\\\n%- weight = (1D IDL array) weight of each galaxy \\\\\n%- gamma1, gamma2 = (1D IDL array) shear $\\gamma_1$ and $\\gamma_2$ of each galaxy}\n%\\end{itemize}\n\n%$\\blacktriangleright$   \\textbf {Build a shear maps structure}\n\n%\\vspace{0.3cm}\n%%$\\twoheadrightarrow$\n%$\\looparrowright$ \\textbf{gcat\\_to\\_gamma.pro} : Build a (pixelised) shear maps structure from a shear catalogue structure :\n%\\index{gcat\\_to\\_gamma.pro}\n%\\begin{center}\n% \\textbf{USAGE : gcat\\_to\\_gamma, gcat, gamma, delta=delta}\n%\\end{center}\n\n%\\textbf{INPUTS} : \n%\\begin{itemize}\n%\\item{gcat = IDL structure of catalogue with the following fields : \\\\\n%- x, y = (1D IDL array) galaxies position in pixels of each galaxy\\\\\n%- pixscale = (int) pixel size [in rad] \\\\\n%- weight = (1D IDL array) weight of each galaxy \\\\\n%- gamma1, gamma2 = (1D IDL array) shear $\\gamma_1$ and $\\gamma_2$ of each galaxy}\n%\\end{itemize}\n\n%\\textbf{KEYWORD} :\n% \\begin{itemize}\n%\\item{delta = (string) pixel size in $arcmin$, default is 1}\n%\\end{itemize}\n\n%\n\n%\\textbf{OUTPUTS} : \n%\\begin{itemize}\n%\\item{gamma = IDL structure of shear maps with the following fields : \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- kappa = (IDL array) mass map\\\\\n%- gamma1, gamma2 = (IDL array) shear maps $\\gamma_1$ and $\\gamma_2$\\\\\n%- ng = (IDL array) number of galaxies per pixel\\\\\n%- wtot = (IDL array) weight per pixel\\\\\n%- mask = (IDL array) mask of the missing data\\\\\n%- gamma\\_err = (IDL array) measurement error in shear maps per pixel taking into account the weight of each galaxy\\\\\n%- kappa\\_err = (IDL array) measurement error in mass map per pixel \\\\\n%(kappa\\_err=gamma\\_err/sqrt(2.))\\\\\n%- ng\\_eff = (IDL array) effective number of galaxies per pixel taking into account the weight of each galaxy\\\\\n%- sigma\\_gamma = (int) measurement error in shear maps per pixel\\\\\n%- x1\\_ran, x2\\_ran = (int) exact range in degree\\\\\n%- x1\\_m, x2\\_m = IDL array with the exact middle position (in deg) of each pixel }\\\\\n%\\end{itemize}\n\n%\n%\\section{Relations between the distortion field and the projected (Electric) mass concentration}\n\n%\\vspace{0.3cm}\n\n%\\subsection{From shear maps $\\gamma_1$, $\\gamma_2$ to mass map $\\kappa$}\n%$\\looparrowright$ \\textbf{gamma\\_to\\_kappa.pro} : See description in previous subsection.\\\\\n%\\index{gamma\\_to\\_kappa.pro}\n\n%\\subsection{From mass map $\\kappa$ to shear maps $\\gamma_1$, $\\gamma_2$}\n%$\\looparrowright$ \\textbf{kappa\\_to\\_gamma.pro} : Derive a shear maps structure from a mass map structure using the relation \\ref{eq_gamma} in chapter \\ref{ch_weak}.\n\n%\\begin{center}\n% \\textbf{USAGE : kappa\\_to\\_gamma, smap, sgamma}\n%\\end{center}\n\n%\\textbf{INPUTS} : \n%\\begin{itemize}\n%\\item{smap = IDL structure of mass map with the following fields : \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- kappa = (IDL array) mass map $\\kappa$}\n%\\end{itemize}\n\n%\\textbf{KEYWORD} :\n% \\begin{itemize}\n%\\item{cat = (string) if set, some fields (specific to real data) are added to the output mass map structure (ng, wtot, mask, gamma\\_err, kappa\\_err, ng\\_eff, sigma\\_gamma,x1\\_ran, x2\\_ran, x1\\_m, x2\\_m)}\n%\\end{itemize}\n\n%\n%\\textbf{OUTPUTS} : \n%\\begin{itemize}\n\n%\\item{sgamma = IDL structure of shear maps with the following fields : \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- kappa = (IDL array) mass map\\\\\n%- gamma1, gamma2 = (IDL array) shear maps $\\gamma_1$ and $\\gamma_2$}\n\n%\\textbf{if keyword\\_set(cat) : }\n%\\item{sgamma = IDL structure of mass map with the following fields : \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- kappa = (IDL array) mass map\\\\\n%- gamma1, gamma2 = (IDL array) shear maps\\\\\n%- ng = (IDL array) number of galaxies per pixel\\\\\n%- wtot = (IDL array) weight per pixel\\\\\n%- mask = (IDL array) mask of the missing data\\\\\n%- gamma\\_err = (IDL array) measurement error in shear maps per pixel taking into account the weight of each galaxy\\\\\n%- kappa\\_err = (IDL array) measurement error in mass map per pixel\\\\ \n%(kappa\\_err=gamma\\_err/sqrt(2.))\\\\\n%- ng\\_eff = (IDL array) effective number of galaxies per pixel taking into account the weight of each galaxy\\\\\n%- sigma\\_gamma = (int) measurement error in shear maps per pixel\\\\\n%- x1\\_ran, x2\\_ran = (int) exact range in degree\\\\\n%- x1\\_m, x2\\_m = IDL array with the exact middle position (in deg) of each pixel }\n%\\end{itemize}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%\\section{Electric and Magnetic mass maps}\n\n%$\\looparrowright$ \\textbf{geb\\_to\\_ke\\_kb.pro} : Compute the Electric and the Magnetic mass map from the shear maps :\n%\\index{geb\\_to\\_ke\\_kb.pro}\n%\\noindent Perform a decomposition of the shear field into its 2 components : the Electric (E) component  and the Magnetic (B) one. The decomposition is based on a rotation of the shear by 45$^\\circ$ to obtain the Magnetic component. The presence of B-modes is used to test the presence of systematic errors in Weak Lensing shear maps. Indeed, Weak Lensing only produces E-modes.\n\n%\\begin{center}\n% \\textbf{USAGE : geb\\_to\\_ke\\_kb, gEB, mE, mB, cat= cat}\n%\\end{center}\n\n%\\textbf{INPUTS} : \n%\\begin{itemize}\n%\\item{gEB = IDL structure of shear maps with the following fields : \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- kappa = IDL array of the mass map\\\\\n%- gamma1, gamma2 = (IDL array) shear maps $\\gamma_1$ and $\\gamma_2$}\n%\\end{itemize}\n\n%\\textbf{KEYWORD} :\n% \\begin{itemize}\n%\\item{cat = (string) if set, some fields (specific to real data) are added to the output mass map structure (ng, wtot, mask, gamma\\_err, kappa\\_err, ng\\_eff, sigma\\_gamma,x1\\_ran, x2\\_ran, x1\\_m, x2\\_m)}\n%\\end{itemize}\n\n%\\textbf{OUTPUTS} : \n%\\begin{itemize}\n%\\item{mE= IDL structure of the magnetic component mass map with the following fields : \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- kappa = (IDL array) mass map with simulated missing data\\\\\n%- gamma1, gamma2 = (IDL array) shear maps $\\gamma_1$ and $\\gamma_2$}\n\n%\\textbf{if keyword\\_set(cat) : }\n%\\item{mE = IDL structure of the magnetic component mass map with the following fields: \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- kappa = (IDL array) mass map\\\\\n%- gamma1, gamma2 = (IDL array) shear maps\\\\\n%- ng = (IDL array) number of galaxies per pixel\\\\\n%- wtot = (IDL array) weight per pixel\\\\\n%- mask = (IDL array) mask of the missing data\\\\\n%- gamma\\_err = (IDL array) measurement error in shear maps per pixel taking into account the weight of each galaxy\\\\\n%- kappa\\_err = (IDL array) measurement error in mass map per pixel\\\\\n% (kappa\\_err=gamma\\_err/sqrt(2.))\\\\\n%- ng\\_eff = (IDL array) effective number of galaxies per pixel taking into account the weight of each galaxy\\\\\n%- sigma\\_gamma = (int) measurement error in shear maps per pixel\\\\\n%- x1\\_ran, x2\\_ran = (int) exact range in degree\\\\\n%- x1\\_m, x2\\_m = IDL array with the exact middle position (in deg) of each pixel }\n\n%\n\n%\\item{mB = IDL structure of the magnetic component mass map with the following fields: \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- kappa = (IDL array) mass map with simulated missing data\\\\\n%- gamma1, gamma2 = (IDL array) shear maps $\\gamma_1$ and $\\gamma_2$}\n\n%\n\n%\\textbf{if keyword\\_set(cat) : }\n%\\item{mB = IDL structure of the magnetic component mass map with the following fields: \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- kappa = (IDL array) mass map\\\\\n%- gamma1, gamma2 = (IDL array) shear maps\\\\\n%- ng = (IDL array) number of galaxies per pixel\\\\\n%- wtot = (IDL array) weight per pixel\\\\\n%- mask = (IDL array) mask of the missing data\\\\\n%- gamma\\_err = (IDL array) measurement error in shear maps per pixel taking into account the weight of each galaxy\\\\\n%- kappa\\_err = (IDL array) measurement error in mass map per pixel\\\\\n% (kappa\\_err=gamma\\_err/sqrt(2.))\\\\\n%- ng\\_eff = (IDL array) effective number of galaxies per pixel taking into account the weight of each galaxy\\\\\n%- sigma\\_gamma = (int) measurement error in shear maps per pixel\\\\\n%- x1\\_ran, x2\\_ran = (int) exact range in degree\\\\\n%- x1\\_m, x2\\_m = IDL array with the exact middle position (in deg) of each pixel }\n%\\end{itemize}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\\section{Missing data}\n\n%\\subsection{Add a hole in order to simulate missing data}\n\n%$\\looparrowright$ \\textbf{add\\_hole.pro} : Add a hole to the mass map :\n%\\index{add\\_hole.pro}\n%\\noindent Add a square hole in the data (pixels are set to zero) to simulate missing data. To add more than one hole,  we can use the procedure in an iterative way, adding holes one by one. \n\n%\\begin{center}\n% \\textbf{USAGE : add\\_hole, smap, xh, yh, sh, mask,smaph}\n%\\end{center}\n\n%\\textbf{INPUTS} : \n%\\begin{itemize}\n%\\item{smap = IDL structure of mass map with the following fields : \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- kappa = IDL array of the mass map}\n%\\item{xh, yh = (int) hole position (center)}\n%\\item{sh = (int) square size (half side)}\n%\\end{itemize}\n\n%\n%\\textbf{OUTPUTS} : \n%\\begin{itemize}\n%\\item{mask = (IDL array) mask to hide missing data in the mass map}\n%\\item{smaph = IDL structure of mass map with simulated missing data with the following fields : \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- kappa = (IDL array) mass map with simulated missing data}\n%\\end{itemize}\n\n%\\subsection{How to overcome this problem?}\n%$\\looparrowright$ \\textbf{whole.pro} : Compute the multi-resolution mask :\n%\\index{whole.pro}\n%\\noindent In some cases in multi-resolution filterings, a multiscale mask data mask can be required to remove all the impact of the missing data. All the pixels in the multi-resolution mask can be distorted by the presence of the hole or by the edge of the image.\n\n%\\begin{center}\n% \\textbf{USAGE : whole, mask, ny, wmask}\n%\\end{center}\n\n%\\textbf{INPUTS} : \n%\\begin{itemize}\n%\\item{mask = (IDL array) mask of the missing data in the mass map}\n%\\item{ny = (int) number of scales used in the wavelet transform}\n%\\end{itemize}\n\n%\n%\\textbf{OUTPUTS} : \n%\\begin{itemize}\n%\\item{wmask = (3D IDL array) multi-resolution mask of the missing data in the mass map}\n%\\end{itemize}\n\n%\n\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%\\section{Filtering}\n%\\subsection{Gaussian Filtering}\n\n%\\vspace{0.3cm}\n\n%\n%$\\looparrowright$ \\textbf{rec\\_kap\\_gaus.pro} : Perform a Gaussian Filtering to filter a noisy mass map :\n%\\index{rec\\_kap\\_gaus.pro}\n%\\noindent Perform a Gaussian filtering by calculating the convolution between the noisy mass map and a gaussian window.\n\n%\\begin{center}\n% \\textbf{USAGE : rec\\_kap\\_gaus, map, sigma, mapg}\n%\\end{center}\n\n%\\textbf{INPUTS} : \n%\\begin{itemize}\n%\\item{map = IDL array of a noisy mass map }\n%\\item{sigma = (int) the width ($\\sigma$) of the Gaussian window}\n%\\end{itemize}\n\n%\n%\\textbf{OUTPUTS} : \n%\\begin{itemize}\n%\\item{mapg = IDL array  of a filtered mass map by Gaussian filtering}\n%\\end{itemize}\n\n%\\subsection{Wiener Filtering}\n\n%\\vspace{0.3cm}\n\n%\n%$\\looparrowright$ \\textbf{rec\\_kap\\_wiener.pro} : Perform a Wiener Filtering to filter a noisy mass map :\n%\\index{rec\\_kap\\_wiener.pro}\n%\\noindent Perform a Wiener filtering (classical 1D method). Build the Wiener weight function by computing a weight for each ring (7) of the image.\n\n%\\begin{center}\n% \\textbf{USAGE : rec\\_kap\\_wiener, smap, sigmae, ng, mapw}\n%\\end{center}\n\n%\\textbf{INPUTS} : \n%\\begin{itemize}\n%\\item{smap = IDL structure of a noisy mass map with the following fields : \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- kappa = IDL array of a noisy mass map}\\\\\n%\\item{sigmae = (int) shear error measurement (a common value is 0.3)}\\\\\n%\\item{ng = (int) number of galaxies per pixel (ng is equal to 20 $gal/amin^2$ for ground observations and 100 $gal/amin^2$ for space observations)}\n%\\end{itemize}\n\n%\n%\\textbf{OUTPUTS} : \n%\\begin{itemize}\n%\\item{mapw = IDL array  of a filtered mass map by Wiener filtering}\n%\\end{itemize}\n\n%\\subsection{Multiscale Entropy Filtering}\n\n%\\vspace{0.3cm}\n\n%\n\n%$\\looparrowright$ \\textbf{rec\\_kap\\_wl.pro} : Perform a Multiscale Entropy Filtering described in chapter \\ref{ch:filter2} to filter a noisy mass map :\n%\\index{rec\\_kap\\_wl.pro}\n%\\noindent Apply the Multi-Resolution Filtering using the Multiscale Entropy concept and the False Discovery Rate (FDR) to derive robust detection levels in wavelet space.\n\n%\\begin{center}\n% \\textbf{USAGE : rec\\_kap\\_wl, map, mapwl, Opt='-n7 -k -I5 -C2 -c2. -s0.05 -F3 -K}\n%\\end{center}\n\n%\\textbf{INPUTS} : \n%\\begin{itemize}\n%\\item{map = (IDL array) noisy mass map}\n%\\end{itemize}\n\n%\n%\\textbf{KEYWORDS} :\\\\\n%      Opt: string which contains the different options. Options are:\\\\\n\n%\t\t[-n number\\_of\\_scales]\\\\\n%               \t\\indent \\indent Number of scales used in the multiresolution transform\\\\\n%               \t\\indent \\indent default is 4.\\\\\n\n%\t\t[-F first\\_detection\\_scale]\\\\\n%\t\t\\indent \\indent First scale used for the detection\\\\\n%\t\t\\indent \\indent default is 1.\\\\\n%          \n%\t\t[-g sigma]\\\\\n%\t\t\\indent \\indent sigma = noise standard deviation assuming a Gaussian noise \\\\\n%\t\t\\indent \\indent by default, the standard deviation is automatically estimated. \\\\\n% \t\t\t\t\t\n%\t\t[-k]\\\\\n%             \t\\indent \\indent Suppress isolated pixels in the support. Default is no.\\\\\n\n%\t\t[-K]\\\\\n%             \t\\indent \\indent Remove the smoothed plane. Default is no.\\\\\n\n%\t\t[-I NbIter]\\\\\n%\t\t\\indent \\indent Number of iterations in an iterative process of reconstruction\\\\\n%\t\t\\indent \\indent default is 10.\\\\\n\n%\t\t[-s NSigma]\\\\\n%              \t\\indent \\indent Thresolding at NSigma * SigmaNoise at each scale\\\\\n%\t\t\\indent \\indent default is 3.\\\\\n%\t\t\\indent \\indent FDR-Thresolding NSigma = $alpha_0$\\\\\n%\t\t\\indent \\indent default value is 0.05.\\\\\n\n%\n%\t\t[-C Thresh\\_Type]\\\\\n%\t\t\\indent \\indent Thresh\\_Type = 1 : Use a NSigma * SigmaNoise thresholding\\\\\n%\t\t\\indent \\indent Thresh\\_Type = 2 : Use a FDR Thresholding\\\\\n%\t\t\\indent \\indent default is 1.\\\\\n%\t\t\n%          \n%\t\t[-c Alpha\\_Variation]\\\\\n%\t\t\\indent \\indent If Thresh\\_Type = 2, use a different alpha per band. \\\\\n%\t\t\\indent \\indent Choose a Alpha\\_Variation value range between 1.7 and 2.\n\n%\t\t[-P]\\\\\n%\t\t\\indent \\indent Apply the positivity constraint\\\\\n%\t\t\\indent \\indent default is no.\\\\\n%  \n%\t\t[-R RMS\\_Map\\_File\\_Name]\\\\\n%               \t\\indent \\indent RMS Map \\\\\n\n%\t\t[-r]\\\\\n%\t\t\\indent \\indent rms map is automatically calculated\\\\\n\n%\t\t[-v]\\\\\n%\t\t\\indent \\indent Verbose. \\\\\n%\t\t\\indent \\indent default is no.\\\\\n\n%\n%\\textbf{OUTPUTS} : \n%\\begin{itemize}\n%\\item{mapwl = IDL array  of the filtered mass map by Multiscale Entropy filtering}\n%\\end{itemize}\n\n%\\textbf{EXTERNAL CALL} : \n%\\begin{itemize}\n%\\item{wl\\_t2\\_filter (C++ program)}\n%\\end{itemize}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%\n%\\section{Tools}\n\n%\\subsection{Characterization}\n\n%\n%\\vspace{0.3cm}\n\n%$\\blacktriangleright$   \\textbf {Error per scale}\n\n%$\\looparrowright$ \\textbf{run\\_sigma.pro} : Compute an error per scale :\n%Compute the error between the original mass map and the filtered one for each scale taking into account the edges.\n%\\index{run\\_sigma.pro}\n%\\begin{center}\n%\\textbf{USAGE : run\\_sigma, w, ny, wn, sigma\\_n}\n%\\end{center}\n\n%\n\n%\\textbf{INPUTS} : \n%\\begin{itemize}\n%\\item{w = (3D IDL array) wavelet transform of the original image}\n%\\item{ny = (int) number of scales used in the wavelet transform}\n%\\item{wn = (3D IDL array) wavelet transform of the filtered image}\n%\\end{itemize}\n\n%\n%\\textbf{OUTPUTS} : \n%\\begin{itemize}\n%\\item{sigma\\_n= error per scale}\n%\\end{itemize}\n\n%$\\looparrowright$ \\textbf{run\\_sigma\\_hole.pro} : Compute an error per scale for a map with missing data :\n%Compute the error between the original mass map and the filtered one for each scale taking into account the edges and the missing data.\n%\\index{run\\_sigma\\_hole.pro}\n\n%\\begin{center}\n% \\textbf{USAGE : run\\_sigma\\_hole, wmask, w, ny, wn, sigma\\_n}\n%\\end{center}\n\n%\\textbf{INPUTS} : \n%\\begin{itemize}\n%\\item{wmask = (3D IDL array) multi-resolution hole mask}\n%\\item{w = (3D IDL array) wavelet transform of the original image}\n%\\item{ny = (int) number of scales used in the wavelet transform}\n%\\item{wn = (3D IDL array) wavelet transform of the filtered image}\n%\\end{itemize}\n\n%\n%\\textbf{OUTPUTS} : \n%\\begin{itemize}\n%\\item{sigma\\_n= error per scale}\n%\\end{itemize}\n\n%$\\blacktriangleright$   \\textbf {Cluster detection}\n\n%Another important aspect of the weak shear mass reconstruction is the possibility \n%to detect clusters and to build a catalog. Thanks to isophote map overplotted on the true mass map as contours, we can check visually the false detections.\n%\\vspace{0.3cm}\n\n%\n%$\\looparrowright$ \\textbf{isophot\\_gaus\\_rms.pro} : Compute an isophote map for Gaussian filtering : In the Gaussian isophote maps, the isophotes corresponds to a $k\\sigma$ detection level where k = 3, 4, 5.\n%\\index{isophot\\_gaus\\_rms.pro}\n%\\begin{center}\n%\\textbf{USAGE : isophot\\_gaus\\_rms, map, sigma, rms\\_map, mapg, isog}\n%\\end{center}\n\n%\n\n%\\textbf{INPUTS} : \n%\\begin{itemize}\n%\\item{map = IDL array of a noisy mass map}\n%\\item{sigma = (int) the width ($\\sigma$) of the Gaussian window}\n%\\item{rms\\_map = (IDL array) rms map, if $rms = cte$ map of constant value}\n%\\end{itemize}\n\n%\n%\\textbf{OUTPUTS} : \n%\\begin{itemize}\n%\\item{mapg = IDL array  of a filtered mass map by Gaussian filtering}\n%\\item{isog = (IDL array)  isophote map for Gaussian filtering}\n%\\end{itemize}\n\n%\n%$\\looparrowright$ \\textbf{isophot\\_wiener\\_rms.pro} : Compute an isophote map for Wiener filtering :\n% In the Wiener isophote maps, the isophotes corresponds to a $k\\sigma$ detection level where k = 3, 4, 5.\n%\\index{isophot\\_wiener\\_rms.pro}\n\n%\\begin{center}\n%\\textbf{USAGE : isophot\\_wiener\\_rms, smap, rms\\_map, sigmae, ng, mapw, isow}\n%\\end{center}\n\n%\n\n%\\textbf{INPUTS} : \n%\\begin{itemize}\n%\\item{smap = IDL structure of a noisy mass map}\n%\\item{rms\\_map = (IDL array) rms map, if $rms = cte$ map of constant value}\n%\\item{sigmae = (int) measurement error in $\\gamma_{i,j}$ per pixel}\n%\\item{ng= (int) number of galaxies per pixel}\n%\\end{itemize}\n\n%\n%\\textbf{OUTPUTS} : \n%\\begin{itemize}\n%\\item{mapw = IDL array  of a filtered mass map by Wiener filtering}\n%\\item{isow = (IDL array)  isophote map for Wiener filtering}\n%\\end{itemize}\n\n%$\\looparrowright$ \\textbf{isophot\\_fdrl.pro} : Compute an isophote map for Multiscale Entropy filtering :\n% Using the FDR-thresholding in wavelet space, we detect as significant a set of wavelet coefficients. Then, we built an isophote map, where each isophote level corresponds to the detection level in a given scale. A cluster surrounded by two isophotes means that it has been \n%detected at two scales.\n%\\index{isophot\\_fdrl.pro}\n%\\begin{center}\n%\\textbf{USAGE : isophot\\_fdrl,  smap, ny, ground=ground, space = space, min\\_scale, iso\\_fdr}\n%\\end{center}\n\n%\n\n%\\textbf{INPUTS} : \n%\\begin{itemize}\n%\\item{smap = IDL structure of a noisy mass map}\n%\\item{ny = (int) number of scales used in the wavelet transform}\n%\\end{itemize}\n\n%\\textbf{KEYWORD} :\n% \\begin{itemize}\n%\\item{ground = (string) if set, we compute the fdr-threshold for ground observations}\n%\\item{space = (string) if set, we compute the fdr-threshold for space observations}\n%\\end{itemize}\n\n%\\textbf{OUTPUTS} : \n%\\begin{itemize}\n%\\item{min\\_scale = (IDL array)  map with the minimum scale of detection for each pixel }\n%\\item{iso\\_fdr = (IDL array)  isophote map with the maximum detection for each pixel for Multiscale Entropy filtering}\n%\\end{itemize}\n\n%\\subsection{Plots}\n\n%\\vspace{0.3cm}\n\n%$\\blacktriangleright$   \\textbf {Plot the shear map}\n\n%\\vspace{0.3cm}\n\n%$\\looparrowright$ \\textbf{plt\\_shear.pro} : Plot a shear map from a mass map or shear maps.\n%Overplot the shear on the corresponding mass map.\n%\\index{plt\\_shear.pro}\n%\\begin{center}\n%\\textbf{USAGE : plt\\_shear, smap, kappa = kappa, gamma = gamma}\n%\\end{center}\n\n%\n\n%\\textbf{INPUTS} : \n%\\begin{itemize}\n%\\item{smap = IDL structure of a mass map or shear maps}\n%\\end{itemize}\n\n%\\textbf{KEYWORD} :\n% \\begin{itemize}\n%\\item{kappa = (string) is set if mass map input}\n%\\item{gamma = (string) is set if shear maps input}\n%\\end{itemize}\n\n%\\textbf{OUTPUTS} : \n%\\begin{itemize}\n%\\item{overplot the shear field over the mass map}\n%\\end{itemize}\n\n%$\\blacktriangleright$   \\textbf {Plot galaxies position from a shear catalogue}\n\n%\\vspace{0.3cm}\n\n%$\\looparrowright$ \\textbf{plt\\_xy\\_gcat.pro} : Plot for each galaxy of the catalogue a cross to give the position.\n%\\index{plt\\_xy\\_gcat.pro}\n%\\begin{center}\n%\\textbf{USAGE : plt\\_xy\\_gcat, gcat}\n%\\end{center}\n\n%\n\n%\\textbf{INPUTS} : \n%\\begin{itemize}\n%\\item{gcat = IDL structure of a shear catalogue with the following fields : \\\\\n%- x, y = (IDL array) coordinates in pixel of each galaxy\\\\\n%- gamma1, gamma2 = (IDL array) shear maps $\\gamma_1$ and $\\gamma_2$\\\\\n%- pixscale = (int) pixel size [rad]}\\\\\n%\\end{itemize}\n\n%\\textbf{OUTPUTS} : \n%\\begin{itemize}\n%\\item{plot the galaxies position of the catalogue}\n%\\end{itemize}\n\n%$\\blacktriangleright$   \\textbf {Plot a mass map field (specific to real data)}\n\n%\\vspace{0.3cm}\n\n%$\\looparrowright$ \\textbf{plt\\_kappa.pro} : Plot the mass map field using the real dimensions [in rad] and overplot the snr contours.\n%\\index{plt\\_kappa.pro}\n%\\begin{center}\n%\\textbf{USAGE : plt\\_kappa, smap, contours = contours}\n%\\end{center}\n\n%\n%\\textbf{INPUTS} : \n%\\begin{itemize}\n%\\item{smap = IDL structure of a mass map  with the following fields : \\\\\n%- n1, n2 = (int) map size in pixels\\\\\n%- theta1, theta2 = (int) map size in radians\\\\\n%- delta1, delta2 = (int) pixel size in radians\\\\\n%- kappa = (IDL array) mass map\\\\\n%- gamma1, gamma2 = (IDL array) shear maps\\\\\n%- ng = (IDL array) number of galaxies per pixel\\\\\n%- wtot = (IDL array) weight per pixel\\\\\n%- mask = (IDL array) mask of the missing data\\\\\n%- gamma\\_err = (IDL array) measurement error in shear maps per pixel taking into account the weight per galaxy\\\\\n%- kappa\\_err = (IDL array) measurement error in mass map per pixel\\\\\n% (kappa\\_err=gamma\\_err/sqrt(2.))\\\\\n%- ng\\_eff = (IDL array) effective number of galaxies per pixel taking into account the weight of each galaxy\\\\\n%- sigma\\_gamma = (int) measurement error in shear maps of each pixel\\\\\n%- x1\\_ran, x2\\_ran = (int) exact range in degree\\\\\n%- x1\\_m, x2\\_m = IDL array with the exact middle position (in deg) of each pixel }\\\\\n%\\end{itemize}\n\n%\\textbf{KEYWORD} :\n% \\begin{itemize}\n%\\item{contours = (string) if set we overplot the snr contours}\n%\\end{itemize}\n\n%\n%\\textbf{OUTPUTS} : \n%\\begin{itemize}\n%\\item{plot the $\\kappa$ field using the real dimensions and overplot the snr contours (if contours is set)}\\\\\n%\\end{itemize}\n\n%\n%$\\blacktriangleright$   \\textbf {Plot an image scaled to the current window}\n\n%\\vspace{0.3cm}\n\n%$\\looparrowright$ \\textbf{plt\\_image.pro} : Plot an image scaled to the current window. Further plotting (such as contours) can be performed over the resulting plot. Optionally, an annotated color bar can be drawn at the top. The 'scalable' keyword must be invoked when outputing to a postscript file.\n%\\index{plt\\_image.pro}\n\n%\n%\\begin{center}\n%\\textbf{USAGE : plt\\_image, map, frame = frame, colbar=colbar, cran=cran, title=title, xtitle=xtitle, ytitle=ytitle, ctitle=ctitle, inverse=inverse, scalable=scalable, csize=csize}\n%\\end{center}\n\n%\n%\\textbf{INPUTS} : \n%\\begin{itemize}\n%\\item{map = (IDL array) an image}\n%\\end{itemize}\n\n%\\textbf{KEYWORD} :\n% \\begin{itemize}\n%\\item{frame = (string) if set, draw a frame with pixel index limits}\n%\\item{colbar = (string) if set, draw color bar}\n%\\item{cran = (string) change the range  (default: [min(map),max(map)])}\n%\\item{title = (string) set a title for the plot}\n%\\item{x,ytitle = (string) set titles for the frame}\n%\\item{ctitle = (string) set a title for the colorbar}\n%\\item{inverse = (string) if set, invert the color coding}\n%\\item{scalable = (string) if set, use scalable pixels which is to be ps devices \n%(default: nonscalable to be used with x-term device)}\n%\\item{csize = (string) vertical size of the color bar (0-1, default:.12)}\n%\\end{itemize}\n\n%\n%\\textbf{OUTPUTS} : \n%\\begin{itemize}\n%\\item{plot of the scaled image with, optionally, a coordinate frame and a color bar.}\n%\\end{itemize}\n\n%\\section{Conclusion}\n\n%We have now at your disposal all the tools to process Weak Lensing data. In the flowchart in Fig.\\ref{organigramme}, the different areas stand for the different main processings. All the routines write down in this flowchart are described in the IDL routines section.\\\\\n\n%\\begin{figure}[htp!]\n%\\begin{center}\n%\\includegraphics[scale=0.7]{organigramme.ps}\n%\\caption{software MRL flowchart}\n%\\label{organigramme}\n%\\end{center}\n%\\end{figure}\n\n% In the yellow area, we have the specific routines to simulated data and in the green area, we have the ones that are specific to real data. The red area is dedicated to the building of the Electric and Magnetic mass map. The white area stands for the relation and the inverse relation between the mass map and the shear maps. Finally the blue area represents the filtering step (Gaussian filtering, Wiener Filtering, Multiscale Entropy Filtering).  Optionally, we can add a characterization step.\\\\\n\n%Depending on the kind of data at your disposal, one can take a different path in the flowchart. And then you run one by one the different routines.\n\n%\\end{document}", "meta": {"hexsha": "7cd093c2c16c1636775c53e4f3129935504bf860", "size": 61945, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/doc/doc_isap/msvst_idl.tex", "max_stars_repo_name": "sfarrens/cosmostat", "max_stars_repo_head_hexsha": "a475315cda06dca346095a1e83cb6ad23979acae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/doc/doc_isap/msvst_idl.tex", "max_issues_repo_name": "sfarrens/cosmostat", "max_issues_repo_head_hexsha": "a475315cda06dca346095a1e83cb6ad23979acae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/doc/doc_isap/msvst_idl.tex", "max_forks_repo_name": "sfarrens/cosmostat", "max_forks_repo_head_hexsha": "a475315cda06dca346095a1e83cb6ad23979acae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8616473616, "max_line_length": 500, "alphanum_fraction": 0.7085156187, "num_tokens": 18793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.31555231278729606}}
{"text": "\\documentclass[11pt,a4paper]{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage{amsmath}\n\\usepackage{amsfonts}\n\\usepackage{amssymb}\n\\usepackage{graphicx}\n%\\usepackage[ddmmyyyy]{datetime} \n\\usepackage[short,nodayofweek,level,12hr]{datetime} \n%\\usepackage{cite}\n%\\usepackage{wrapfig}\n%\\usepackage[left=2cm,right=2cm,top=2cm,bottom=2cm]{geometry}\n\n\\newcommand{\\e}{\\epsilon}\n\\newcommand{\\dl}{\\delta}\n\\newcommand{\\pd}[2]{\\frac{\\partial #1}{\\partial #2}}\n\\newcommand{\\vect}[1]{\\underline{#1}}\n\\newcommand{\\uvect}[1]{\\hat{#1}}\n\\newcommand{\\1}{\\vect{1}}\n\\newcommand{\\grad}{\\nabla}\n\\newcommand{\\lc}{l_c}\n\n\\title{Surface Tension}\n\\date{\\displaydate{date}}\n\\newdate{date}{22}{09}{2018}\n\\author{}\n\n\\begin{document}\n\\maketitle\n\nIf a \\textit{thin} tube is half-dipped in water, we know that water rises in the tube to a height greater than that of the surrounding fluid. But what do we mean by a thin tube? There must be a critical thickness of the tube beyond which we will expect gravity to dominate and below which surface tension will be important.\n\nSince there is a competition between gravity ($g$) and surface tension ($\\Gamma$), we can obtain the critical length ($\\lc$) by comparing the pressures exerted by each of these forces-\n\\begin{align*}\n&\\rho g \\lc \\sim \\frac{\\Gamma}{\\lc}\\\\\n\\Rightarrow &\\lc \\sim \\bigg(\\frac{\\Gamma}{\\rho g}\\bigg)^{1/2}\n\\end{align*}\nThis is the length scale over which the effects of surface tension are comparable with those of gravity. At lengths much smaller than this, surface tension will dominate gravity. For water, $\\Gamma = 0.07 N/m$ and hence $l_c \\approx 2.7$mm. Therefore a \\textit{thin} tube, for water, referes to a tube whose diameter is nearly 2.7mm or less.\n\nBut why is the surface of a fluid under tension? A fluid consists of a bulk and a surface. The surface, though usually idealized as a sheet with zero thickness, is actually a few molecules thick. For a depth of the order of a few molecules near the water surface, the potential energy of the molecules is substantially higher than that in the bulk. The surface molecules are more energetic, jiggling about more rapidly, often escaping from the liquid to the air. If we wanted to calculate the total potential energy of the liquid by evaluating the potential energy per molecule in the bulk and then multiplying it by the total number of molecules, we will incur an error because potential energy for the surface molecules is much larger. This surface energy is usually incorporated by considering the surface to be an area (even though it is a volume few molecules thick). The excess energy associated with the area is proportional to the area and the coefficient of proportionality is the surface tension. \n\nIncreasing the surface area causes more molecules to move from the bulk to the surface which increases their potential energy. We know that force is a derivative of the potential energy ($F=-dU/dx$) and therefore pushing the molecules up the potential energy curve leads to a force. In order to minimize it's potential energy then, a fluid must minimize its surface area which is what we observe in nature.\n\n\\section{The Young - Laplace Equation}\nThe fact that surface of a fluid is under tension leads to a pressure jump between the two fluids. This can be seen by a force balance across the surface. Since the mass of a surface element is zero, the net force must be zero. Therefore, the sum of pressures acting on the two sides plus the surface tension force must add up to zero.\n\\begin{align*}\n&\\int(-p\\vect n + p \\vect n) dA + \\oint \\Gamma \\vect t' ds = 0 \n\\end{align*}\nwhere $\\vect n$ is the normal to the surface, $\\vect t$ is the tangent to the curve bounding the surface and $\\vect t' = \\vect n \\wedge \\vect t$ is a vector perpendicular to the curve. Using Stokes Theorem, this can be written as\n\\begin{align*}\n&\\underbrace{\\bigg[(\\hat p - p)- \\Gamma \\pd{n_k}{x_k} \\bigg]n_i}_{\\text{Normal force balance}} + \\underbrace{(\\dl_{ik} - n_in_k)\\pd{\\Gamma}{x_k}}_{\\text{tangential force balance}} = 0\n\\end{align*}\n\nIf the gradient of surface tension is zero, then second term is vanishes and we get\n\\begin{align*}\n&\\hat p - p = \\Gamma \\pd{n_k}{x_k}\\\\\n&\\hat p - p = \\Gamma (\\grad\\cdot \\vect{n})\n\\end{align*}\nwhich is the Young-Laplace Equation. This equation gives us the pressure jump across an interface due to surface tension provided $\\Gamma$ is constant everywhere. If $\\Gamma$ varies with position, then the gradient of $\\Gamma$ will not be zero and there will be flow due the surface tension gradient. Such flows are called Marangoni flows. \n\nWe can see a quick implementation of the Young-Laplace Equation by evaluating the pressure jump across a spherical bubble (say air bubble in water). For a sphere, the normal is given by $\\vect n = x_i/r$. Hence-\n\\begin{align*}\n\\grad\\cdot n &= \\pd{}{x_i}\\frac{x_i}{r}\\\\\n&= \\frac{1}{r}\\pd{x_i}{x_i} - \\frac{x_i x_i}{r^3} \\tag{writing $r= (x_ix_i)^{1/2}$ }\\\\\n&= \\frac{\\dl_{ii}}{r} - \\frac{x_i x_i}{r^3}\n= \\frac{3}{r} - \\frac{1}{r}\n= \\frac{2}{r}\n\\end{align*}\n\nTherefore, for a spherical bubble, the pressure balance gives us\n\\begin{align*}\n&\\hat p - p  = \\frac{2 \\Gamma}{r}\n\\end{align*}\n\n\\section{Shape of a 2D static meniscus}\nThe Young-Laplce Equation can be used to obtain the shape of a static meniscus. In this section we look at a meniscus close to a plane wall. Just next to the wall, the rise in water level is highest and it tapers off as we move away from the wall. We want to find out the functional form for the interface $z \\equiv z(x)$ where $x$ is the distance from the wall and $z$ is the height of the meniscus at a given $x$. \n\nEvaluation of the Young-Laplace Equation requires us to find the divergence of the unit normal. The normal to any surface $F(x,y) = 0$ is given by:\n\\begin{align*}\n&  \\vect n = \\frac{\\grad F}{|\\grad F|}\\\\\n&\\Rightarrow \\pd{}{x_i}n_i = \\pd{}{x_i}\\frac{\\pd{F}{x_i}}{|\\grad F|}\\\\\n&\\Rightarrow \\pd{n_i}{x_i} = \\frac{1}{|\\grad F|}\\pd{^2F}{x_i^2} - \\frac{1}{|\\grad F|^3}\\pd{F}{x_i}\\pd{F}{x_k}\\pd{^2F}{x_ix_k}\n\\end{align*}\nFor the 2D static meniscus $z=f(x)$ and hence $F(x,z) = z-f(x) = 0$. Evaluating the necessary derivatives:\n\\begin{align*}\n&\\pd{F}{x} = -\\pd{f}{x}\\\\\n&\\pd{F}{z} = 1\\\\\n&\\pd{^2F}{x\\partial z} = \\pd{^2f}{x^2}\\\\\n\\end{align*}\nand substituting them in the Young-Laplace equation, we get the following:\n\\begin{align*}\n&\\hat p - p = -\\Gamma \\bigg(\\frac{\\pd{^2f}{x^2}}{\\big(1+(\\pd{f}{x})^2\\big)^{3/2}} \\bigg)\\\\\n\\Rightarrow &\\hat p - p = -\\rho g z  = -\\Gamma \\bigg(\\frac{\\pd{^2f}{x^2}}{\\big(1+(\\pd{f}{x})^2\\big)^{3/2}} \\bigg)\n\\end{align*}\nHere, $\\hat p$ is the atmospheric pressure and $p$ is the pressure in the fluid at $z=0$. We can non-dimensionalize the equation by considering the length scale $l_c = \\sqrt{\\Gamma/\\rho g}$. This leaves us with\n\\begin{align*}\n& z  = \\frac{\\pd{^2f}{x^2}}{\\big(1+(\\pd{f}{x})^2\\big)^{3/2}} \n\\end{align*}\nWe can greatly simplify the matters if we linearize this equation. Consider the case where the slope of the meniscus is very small everywhere, i.e. $dz/dx \\ll 1$. Then the equation becomes\n\\begin{align*}\n& z = \\pd{^2f}{x^2}\n\\end{align*}\nwhose solution is an exponential \n\\begin{align*}\n&z = z_0 e^{-x}\n\\end{align*}\nor in dimensional terms\n\\begin{align*}\n&z = z_0 e^{-x/l_c}\n\\end{align*}\nwhich tells us that the height of the meniscus decays exponentially away from the wall with a characterstic length scale of $l_c$. Another quantity of interest here is the maximum height to which water rises along the wall. In order to find it, we must impose the contact angle boundary condition:\n\\begin{align*}\n&\\frac{dz}{dx} = \\tan(\\frac{\\pi}{2} + \\theta_c) \\quad @ \\quad z=0\\\\\n\\Rightarrow &\\frac{-z_0}{l_c} = \\tan(\\frac{\\pi}{2} + \\theta_c) \\\\\n\\Rightarrow & z_0 =-l_c \\tan(\\frac{\\pi}{2} + \\theta_c) \\\\\n\\Rightarrow & z_0 =l_c \\cot(\\theta_c) \n\\end{align*}\nThis gives us the height of the meniscus at the wall. But what if $\\theta_c = 0$? The height comes out to be infinity. This is obviously wrong but we must remember that linearization was only valid when slope of the meniscus was small. Since we have violated this assumption, the method is expected to give the wrong answer. In order to obtain the height of meniscus at the wall when $\\theta_c = 0$, we must solve the full non-linear equation, which leads us to\n\\begin{align*}\n&1-\\frac{z^2}{2} = \\frac{1}{(1+\\frac{dz}{dx}^2)^{1/2}}\n\\end{align*}\nFrom this, we can obtain the height at the wall to be $\\sqrt 2 l_c$ when $\\theta_c = 0$.\nThe equation can be further solved to obtain the complete shape of the meniscus as a transcendental function $x\\equiv x(z)$.\n\n\\section{Appendix}\n\\subsection{Force balance interpretation}\nDescribe \n\\begin{align*}\n&1-\\frac{z^2}{2} = \\frac{1}{(1+\\frac{dz}{dx}^2)^{1/2}}\n\\end{align*}\nas a force balance\n\n\\subsection{Solution of the non-linear equation for the 2D meniscus}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\\end{document}\n", "meta": {"hexsha": "42ce13d9f60a2527726a85e02f5d67ba204fb454", "size": 8818, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex_files/lecture13.tex", "max_stars_repo_name": "pulkitkd/Fluid_Dynamics_notes", "max_stars_repo_head_hexsha": "f4ffd25fa16fa08c2c2a5d465bb8a19a1d02d850", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-16T04:19:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-16T04:19:07.000Z", "max_issues_repo_path": "tex_files/lecture13.tex", "max_issues_repo_name": "pulkitkd/Fluid_Dynamics_notes", "max_issues_repo_head_hexsha": "f4ffd25fa16fa08c2c2a5d465bb8a19a1d02d850", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex_files/lecture13.tex", "max_forks_repo_name": "pulkitkd/Fluid_Dynamics_notes", "max_forks_repo_head_hexsha": "f4ffd25fa16fa08c2c2a5d465bb8a19a1d02d850", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 58.3973509934, "max_line_length": 1007, "alphanum_fraction": 0.7186436834, "num_tokens": 2671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.31550783642278574}}
{"text": "\\documentclass[a4paper]{article}\n\\usepackage[width=15cm,height=25.7cm]{geometry}\n\\usepackage{xspace}\n\\usepackage{color}\n\\usepackage[leqno]{amsmath}\n\\usepackage{amssymb}\n\\usepackage{array}\n\\usepackage{tabularx}\n\\usepackage{booktabs}\n\\usepackage{url}\n\\usepackage{hyperref}\n\\usepackage{breakurl}\n\\usepackage{graphicx}\n\\usepackage{subfigure}\n\\def\\url@leostyle{%\n  \\@ifundefined{selectfont}{\\def\\UrlFont{\\small\\sf}}{\\def\\UrlFont{\\small\\sf}}}\n\\makeatother\n\\urlstyle{leo}\n\\usepackage[normalem]{ulem}\n\\input{macros}\n\n\\title{A Cat tutorial: HSA Models}\n\\date{}\n\\author{Jade Alglave and Luc Maranget}\n\\begin{document}\n\\maketitle\n\\part{A reading of the HSA document}\n\n\\section{\\label{coherence}Coherence}\n\nFor a given location~$L$,\nthe coherence order $\\cohl{L}$ is defined as a total order on all loads and\nstores to location~$L$. The ``single Coherent Order'' $\\coh$ is\nthe union of all these orders for all locations.\nIn appendix~\\ref{coh} we describe how to generate the set of all possible\n$\\coh$ ``orders'' in the \\cat{} language.\nFor now, let us assume a variable \\texttt{allCoh}\nwhose value is the set of all possible \\coh{} orders.\n\nThe instruction \\texttt{with $v$ from $S$} will, for each element~$e$ in $S$,\nexecute the rest of the model in an extended environment that binds\n$v$ to~$e$. In our case of \\coh{}, we write:\n\\begin{verbatim}\nwith coh from allCoh\n\\end{verbatim}\nIn effect, the construct performs a further enumeration of candidate\nexecutions: the initial candidate is extended with one \\coh{} order\nbound to the variable~\\texttt{coh}.\n\nWe can then  check the consistency of $\\coh$ and~$\\po$:\n\\begin{verbatim}\ncall consistent(coh,po) as CohPoCons\n\\end{verbatim}\nSee appendix~\\ref{procedure} for the definition of the consistency check as\na procedure.\n\nThe other coherence check is the ``value of a load'' check, phrased\nas: ``\\emph{a load [\\ldots] will always observe the most recent store in the coherent order of location~$L$}''.\nGiven the existence of initial writes, which are minimal amongst writes to\nthe same location in \\coh{}, the above condition defines a relation from\nwrites to reads to the same location. This relation, \\texttt{mincohWR},\nis implemented in the \\cat{} language as follows:\n\\begin{verbatim}\nlet cohWR = coh & (W * R)\nlet cohWW = coh & (W * W)\nlet mincohWR = cohWR \\ (cohWW; cohWR)\n\\end{verbatim}\nWhere ``\\verb+&+'' is intersection, ``\\verb+*+'' is cartesian product\nand ``\\verb+\\+'' is (set or relation) difference.\nThen it remains to check that $\\rf$ equals \\texttt{mincohWR}.\nWe proceed by checking double inclusion:\n\\begin{verbatim}\n(* Relation a includes relation b, ie b(x,y) => a(x,y) *)\nprocedure includes(a,b) = empty b \\ a end\nprocedure equals(a,b) =\n  call includes(a,b)\n  call includes(b,a)\nend\n\ncall equals(rf,mincohWR) as LoadCons\n\\end{verbatim}\nNotice another usage of the difference operator on relations.\n\nFinally, we may view the atomicity of RMW constructs as a coherence property\n\\marginpar{This property does not appear formally in the document?}\nThis property states that there cannot be any write in-between the read\nand the write performed by a RWM operation.\n\nThere are two possible semantics of RMW ``operations'' as ``events''.\n\\begin{enumerate}\n\\item\nA C-like semantics would consider RMW events that are both read and write\nevents. We would then state the atomicity of RMW's as follows:\n\\begin{verbatim}\nlet RMW = R & W\nlet rmw = id & (RMW * RMW)\nlet cohRW = coh & (R * W)\nempty rmw & (cohRW;cohWW) as RmwCons\n\\end{verbatim}\nWhere \\texttt{id} is the pre-defined identity relation on events.\nAs a consequence the relation \\texttt{rmwid} is the identity restricted\nto RMW events.\nHowever, this condition is useless. Indeed, by construction,\n\\texttt{coh} is a total order and is thus irreflexive.\nAs a consequence, \\texttt{cohRW;cohWW} which is included in \\coh{}\ncannot intersect the identity.\n\\item Or, and we prefer this solution, a RMW operation is represented\nby two events a read and a write, which are related by a pre-defined\n\\texttt{rmw} relation.\nWe would then state the atomicity of RMW's as follows:\n\\begin{verbatim}\nempty rmw & (cohRW;cohWW) as RmwCons\n\\end{verbatim}\nIn that case, we cannot get rid of the \\texttt{RmwCons} check,\nas \\texttt{rmw} now relate different events.\n\\end{enumerate}\n\n\\section{No values out-of-thin-air, dependencies}\nThe document defines the ``local dependence order'' $\\ldo$ informally\nas the union of data, address and control dependencies (Sec 3.8).\nOur simulator \\herd{} provides pre-defined relations for those three\n``local dependencies'' relations.\nHence we write\n\\begin{verbatim}\nlet ldo = data | addr | ctrl\n\\end{verbatim}\nWe notice that control dependencies to reads are part of \\ldo.\n\nThe document  then define the ``global dependence order'' as\nthe irreflexive transitive closure of \\ldo{} union \\coh{},\nwhich we would write \\verb!let gdo = (ldo|coh)+!.\nThe document then states\n``\\emph{By rule, there cannot be a cycle in in \\gdo{}}'',\nwhich we interpret as a requirement: \\gdo{} must be acyclic.\nThe intent of the global dependence order clearly is to rule out\nvalues out of thin air, as illustrated by\nthe typical example ``\\ltst{lb+ldos}'':\n\\begin{center}\\fmt{lb+ldos}\\end{center}\n\nHowever, including the complete~\\coh{} in the definition of~\\gdo{} looks too\nstrong: the requirement will then for instance forbid \\ltst{wrc+ldos}.\n\\begin{center}\\hspace*{-2cm}\\fmt{wrc+ldos}\\end{center}\n\nWe  think, given the intent to forbid values out of thin air,\nthat \\gdo{} should include a fragment of \\coh{}: the \\rf{} relation\nwhen source and target belong to different units:\n\\begin{verbatim}\nlet rfe = rf & ext\nlet gdo = ldo | rfe\nacyclic gdo as GdoCons\n\\end{verbatim}\nIn the code above, we first define the \\rfe{} relation (\\rf{} from different\nunits) by intersecting \\rf{} and the pre-defined \\ext{} relation that relates\nall events from different units.\nAlso notice that we do not apply transitive closure to \\gdo{}, as this\ndoes not impact the acyclicity of a relation. Furthermore,\nthe \\gdo{} relation will no longer appear in the remainder of the model.\n\n\n\\section{\\label{sso}Scoped synchronization order}\nThe documents defines a hierarchy of five scope levels:\nsystem, agent, work-group, wave and work-item,\\footnote{We use some abbreviations:``wg'' for work-group and ``wi'' for and work-item.}\nhere listed from top to bottom.\nThe \\herd{} simulator handles scopes by the means\nof various objects: tags, scope relations,\nand set of annotated events.\nThose are defined by reading a prelude ``bell'' file,\nsupplied to \\herd{} with the \\texttt{-bell} option.\nAppendix~\\ref{bell} details the bell file for HSA.\n\nEach test features a ``scope tree'' definition that specifies how\nthe test  units are organized according to the scope hierarchy.\nConsider for instance the test \\ltst{isa2}:\n{\\small\n\\begin{verbatim}\nBell isa2\n{ 2:r1=-1; }\n P0                     | P1                         | P2                          ;\n w[] x 53               | r[atomic,scacq,agent] r0 y | r[atomic,scacq,system] r0 z ;\n w[atomic,screl,wg] y 1 | bne r0, 1, Exit1           | bne r0, 1, Exit2            ;\n                        | w[atomic,screl,system] z 1 | r[] r1 x                    ;\n                        | Exit1:                     | Exit2:                      ;\nscopes: (agent (wg 0 1) (wg 2))\nexists (1:r0=1 /\\ 2:r0=1 /\\ 2:r1=0)\n\\end{verbatim}\n}\nThis test has three units, \\myth{0}, \\myth{1} and~\\myth{2}.\nAccording to the scope tree \\verb+(agent (wg 0 1) (wg 2))+,\nthe first two units \\myth{0} and \\myth{1} are in the same work-group,\nwhile the last unit~\\myth{2} is in a different work-group.\nThen, all units are in the same agent.\nSome scopes remain unspecified: they implicitly contain only one\nitem --- \\emph{e.g.} the system scope contains one agent, while\nthere are three work-item scopes that contain one unit each.\n\nHence, at runtime, there will be two ``scope instances'' of the work-group\nlevel. Those scope instances are available to \\cat{} model as a ``scope\nrelations'' whose names are the names of the corresponding scope levels.\nA scope relation is an equivalence relation that relates events whose units\nare in the same scope instance of the given level.\nFor instance, figure~\\ref{isa2scopes} pictures the \\wg{} relation\nfor the \\ltst{isa2} test.\\footnote{Reflexivity edges are omitted for clarity.}\n\\begin{figure}\n\\caption{\\label{isa2scopes} The \\wg{} scope relation of the \\ltst{isa2} test}\n\\begin{center}\\hspace*{-2cm}\\fmt{isa2+scopes}\\end{center}\n\\end{figure}\nWe could also have pictured the \\agent{} relation. We refrain from doing so,\nas there is a single agent scope instance that contains all units.\nThus, the \\agent{} relation is the total relation over events,\nand picturing it would clobber the diagram.\n\nIt is to be noticed that the bell file must define\nan enumeration of name \\texttt{scopes},\nwhose tags are the name of scope levels:\n\\begin{verbatim}\nenum scopes = 'system || 'agent || 'wg || 'wave || 'wi\n\\end{verbatim}\nThen, given an expression~$e$ whose value is the\ntag \\texttt{'\\textit{lvl}}, the primitive \\texttt{tag2scope($e$)} returns\nthe scope relation \\textit{lvl}.\n\nScopes also appear as event annotations. Such annotations are the ones\nof the instructions that generate them.\nSets of annotated events are also defined from bell file contents,\nand are available to \\cat{} models as pre-defined variables.\nThe name of one of those variables is the name\nof the annotation with uppercase initial letter.\nFor instance, on figure~\\ref{isa2scopes}, we have\n$\\texttt{Wg} = \\{ b \\}$,\n$\\texttt{Agent} = \\{ c \\}$,\n$\\texttt{System} = \\{ d,e \\}$.\nLike scope relations, sets of annotated events can be accessed\nfrom the scope tag by a primitive, \\verb+tag2set+.\nFor instance, in our \\ltst{isa2} example,\nthe expression \\verb+tag2set('system)+ will evaluate to the set\nof events $\\{d,e\\}$.\n\nSection 3.9 ```Scoped synchronization order'' of the HSA document\nstates that two operations may ''\\emph{both specify (directly or indirectly\nthrough scope inclusion) scope instance~$S$}''.\nWe first notice that ``indirectly'' applies to the event annotations,\nnot to the scope instance that is fixed.\nFor instance, a memory operation whose scope annotation is agent also\nspecifies work-group.\nMore generally, the scope annotation~\\textit{lvl} takes effect on\nall scopes at levels \\emph{lower} than~\\textit{lvl}.\n\nIn practice, we shall define equivalence relations\n\\texttt{same-\\textit{lvl}}, where \\textit{lvl} is a scope level.\nTwo operations are related by \\texttt{same-\\textit{lvl}}\nwhen they specify a common instance at level~\\textit{lvl} in the HSA document\nsense.\nThis not only means that the two operations\nare related by the scope relation \\textit{lvl} (\\emph{i.e.}\nthey do belong to one common scope instance at level~\\textit{lvl}),\nbut also that they are annotated by scope~\\textit{lvl} or higher,\nso that they take effect at level~\\textit{lvl}.\n\nHence, we first define a function \\texttt{all-events} that takes\na (scope) tag as argument and returns all the events annotated by\nthis scope or higher:\n\\begin{verbatim}\nlet rec all-events(tag) = match tag with\n|| 'system -> tag2events(tag)\n|| _ -> tag2events(tag) | all-events(wider(tag))\nend\n\\end{verbatim}\nThe (omitted) \\texttt{wider} function is defined in the bell file:\nit simply returns\nthe tag that is immediately above its tag~argument.\nThat is, it associates \\texttt{'system} to~\\texttt{'agent}, \\texttt{'agent}\nto~\\texttt{'wg}, etc.\n\nFollowing our discussion, we then\ndefine the function~\\texttt{same-instance} that takes a scope\ntag~\\texttt{'\\textit{lvl}} as argument and returns the\nrelation~\\texttt{same-\\textit{lvl}}:\n\\begin{verbatim}\nlet same-instance(lvl) =\n let evts = all-events(lvl) in\n tag2scope(lvl) & (evts * evts)\n\\end{verbatim}\nThe function simply performs the intersection of the scope relation\nand of the cartesian product on events annotated with\nscope level~\\textit{lvl} or higher. Figure~\\ref{isa2same} pictures two of\nthose ``same'' relations.\\footnote{Reflexivity edges are omitted for clarity.\nIn particular $e \\same{wg} e$ is omitted.}\n\\begin{figure}\n\\caption{\\label{isa2same}The \\same{wg} and~\\same{agent} relations of the \\ltst{isa2} test.}\n\\begin{center}\\hspace*{-2cm}\\fmt{isa2+instances}\\end{center}\n\\end{figure}\n\nWe are now ready to define scope synchronization orders, which basically\nformalize release-acquire synchronization, with scope restrictions.\nFrom \\herd{} pre-defined sets of annotated events we build a few\nrelevant sets:\n\\begin{verbatim}\nlet Release = Screl | Scar\nlet Acquire = Scacq | Scar\nlet Synchronizing = Acquire | Release (* Could be Screl|Scacq|Scar *)\n\\end{verbatim}\nNotice that the \\texttt{screl}, \\texttt{scacq} and~\\texttt{scar}\nannotations apply to atomic operations and to fences only. As a consequence,\nthe above sets regroup atomic operations and fences only. \nWe then directly follow the description of Sec. 3.9, up to a few innocent\nchanges:\n\\begin{verbatim}\nlet acq-rel =\n  ((W & Release) * (R & Acquire)) & coh\n| ((F & Release) * Acquire) &\n  ((po & (_ * W)); coh; (po? & (R * _)))\n| (Release * (F & Acquire)) &\n  ((po? & (_ * W)); coh; (po & (R * _)))\n\nlet sso s = same-instance(s) & acq-rel  \n\\end{verbatim}\n\\marginpar{The proposed model enforces atomic accesses for the intermediate\n$A$ and~$B$ operations such that $A \\coh B$ in the fence-to-fence case.\nAlthough this is a race, the HSA document does not specify this atomicity\ncondition.}\nThe definition of \\texttt{acq-rel} regroups the three top-level items\nof the description of the HSA document.\nIt uses set and relation constructs intensively, most of which have\nalready been introduced, except the option postfix\noperator~\\texttt{$e$?} that yields,\n\\texttt{$e$|id} (\\emph{i.e.} $e$ union the identity relation),\nand the universe set ``\\verb+_+'' that contains all events.\nOur (minor) changes are:\n\\begin{itemize}\n\\item Some simplifications apply,\nas our \\texttt{Acquire} and \\texttt{Release} sets\ncontain synchronizing operations~only.\n\\item Similarly, we make no specific provision for\nRMW events as they either belong to the pre-defined sets of reads and writes,\n\\verb+R+ and \\verb+W+, or are represented by a read event (in~\\verb+R+)\nand a write event (in \\verb+W+) --- See our Sec.~\\ref{coherence}.\n\\item We have made the definition a bit more symmetric (and redundant)\nby having the third item to produce fence-to-fence order,\nas the second item does.\n\\item We have factored out the condition ``\\emph{$X$ and~$Y$ both specify the same instance~$S$}'' (implemented by the call ``\\verb+same-instance(s)+'').\n\\end{itemize}\n\nFinally the HSA-happens-before order~\\hhb{}\nis defined by following the HSA~document,\nas the transitive closure of the union of the program order and of\nthe union of scope synchronization order for all scopes.\n\\begin{verbatim}\nlet union-scopes f = fold (fun (s,y) -> f s | y) (scopes,0)\n\nlet hhb = (po | union-scopes sso)+\n\\end{verbatim}\nThe function \\texttt{union-scopes} takes a function~$f$ from scope\ntags to relations as argument (as \\texttt{sso} is)\nand returns the union of the \\texttt{$f(\\textit{lvl})$} for all scope tags.\nIt refers to the \\texttt{scopes} tag set, which is implicitly defined\nby the \\verb+enum scopes = +\\ldots{} definition, and to the\n\\verb+fold+ (over sets) function, defined in appendix~\\ref{coh}.\nFigure~\\ref{isa2sso} pictures the scope synchronization orders\nfor scopes agent and work-group, all transitive edges being omitted.\n\\begin{figure}\n\\caption{\\label{isa2sso}Scope synchronization orders for scopes agent (\\textsf{sso-agent}) and work-group (\\textsf{sso-wg}).}\n\\begin{center}\\hspace*{-2cm}\\fmt{isa2+sso}\\end{center}\n\\end{figure}\nThe figure also pictures the \\hhb{} and \\coh{} relations.\n\nThe HSA document defines three validity conditions on~\\hhb.\nThe \\hhb{} relation must be acyclic (equivalently irreflexive, as \\hhb{} is\ntransitive), consistent with \\coh{}, and consistent with sequentially consistent\norders (see next section).\nWe express the first two conditions as follows:\n\\begin{verbatim}\nirreflexive hhb as HhbCons\ncall consistent (hhb,coh) as HhbCohCons\n\\end{verbatim}\nNotice that Figure~\\ref{isa2sso} demonstrates a case of inconsistency\nof \\hhb{} and~\\coh{},\nas the union of their pictured representations without transitivity edges is\ncyclic. And, indeed, our \\ltst{isa2} test\nis similar\\footnote{We have replaced \\texttt{while} loops by \\texttt{if} constructs.} to the test\n``Race-free transitive synchronization through multiple scopes''\nof the HSA document. It should thus be forbidden.\n\n\\section{Sequentially consistent synchronization order}\nSec. 3.10 of the HSA document states: ``\\emph{there is a\ntotal (apparent) order of all synchronizing operations with,\nrelease, acquire, or acquire-release semantics in a single scope instance}''.\nGiven a scope instance~$S$, we write $\\SCS{S}$ for this total order,\nand $\\SCLVL{lvl}$ for the union of  $\\SCS{S}$ orders for all scope instances\nat level~\\textit{lvl}. We also abbreviate\nsequentially consistent synchronization order as ``SC order''.\n\nWe have already defined the set \\texttt{Synchronizing} in the previous section.\nAs to scope instances at level \\textit{lvl} we represent then as the\nequivalence relation~\\symr{\\it{lvl}}, which is available\nin \\cat{} from a scope tag as \\texttt{tag2scope('\\textit{lvl})}.\nWe here need a more direct representation of scope instances, as sets.\nAs a matter of fact,\nfor a given scope level~\\textit{lvl}, scope instances at level~\\textit{lvl}\nare the equivalence classes of the relation~\\symr{\\itshape{}lvl}.\nThe \\cat{} primitive \\texttt{classes} takes an equivalence relation as argument\nand returns its equivalence classes as a set of sets of events.\nHence we can compute the sets~$S$ for a given level as follows:\n\\marginpar{Luc for Jade, all our models use \\texttt{same-instance} in place\nof \\texttt{tag2scope}\\ldots}\n\\begin{verbatim}\nlet sync-instances(lvl) =\n  classes ((Synchronizing * Synchronizing) & tag2scope(lvl))\n\\end{verbatim}\n\nThen, the HSA  document clearly states that the total order $\\SC{$S$}$\nextends \\po{}: ``\\emph{Given synchronisation operations $X$ and~$Y$, if $X \\po Y$ and $X$ and~$Y$ specify the same scope instance~$S$ (directly or indirectly\nthrough inclusivity), then $X \\SC{$S$} Y$}''.\nHowever it is unclear if this applies to any pair of synchronizing operations\nthat belong to~$S$, or only to those whose scope annotations take effect\nat the level of~$S$.\nNevertheless, as $\\SC{$S$}$ is total and later required to be consistent\nwith $\\po$ it does not matter much. We thus choose the first, more simple,\ninterpretation. Hence given a scope instance~$S$, we compute the set\nof $\\po$ linearisation on~$S$ as follows:\n\\begin{verbatim}\nlet preSC = po\nlet makeSCinstance(S) = linearisations(S,preSC)\n\\end{verbatim}\nThe \\texttt{linearisation($S$,$r$)} primitive that computes all topological sorts of the graph $(S \\times r)$ is introduced in appendix~\\ref{coh}.\nFinally, we compute the set of all possible $\\SCLVL{lvl}$ relations as:\n\\begin{verbatim}\nlet makeSCscope(lvl) = cross (map makeSCinstance (sync-instances(lvl)))\n\\end{verbatim}\nThe function~\\texttt{map} is map over sets. In the code above it serves\nto compute the set of the sets of all possible $\\SCS{S}$ orders\nfor all scope instances~$S$ at level~\\textit{lvl}.\nThe function~\\texttt{cross} takes a set of sets $\\{S_1,S_2,\\ldots,S_n\\}$ as argument and returns the set of all sets built by picking one element\nin each~$S_i$. Those two functions are introduced in appendix~\\ref{coh}.\n\nFinally, we iterate over all possible choices of $\\SCLVL{lvl}$ for the five\nHSA scope levels as follows:\n\\begin{verbatim}\nwith SWI from makeSCscope('wi)\ncall consistent(SWI,coh) as ScCohCons\ncall consistent(SWI,hhb) as ScHhbCons\nwith SWAVE from makeSCscope('wave)\ncall consistent(SWAVE,coh) as ScCohCons\ncall consistent(SWAVE,hhb) as ScHhbCons\nwith SWG from makeSCscope('wg)\ncall consistent(SWG,coh) as ScCohCons\ncall consistent(SWG,hhb) as ScHhbCons\nwith SAGENT from makeSCscope('agent)\ncall consistent(SAGENT,coh) as ScCohCons\ncall consistent(SAGENT,hhb) as ScHhbCons\nwith SSYSTEM from makeSCscope('system)\ncall consistent(SSYSTEM,coh) as ScCohCons\ncall consistent(SSYSTEM,hhb) as ScHhbCons\n\\end{verbatim}\nNotice that we also check the consistency of SC orders with \\coh{} and \\hhb{},\nas required, but not with~\\po{}.\nIndeed, by construction the ``order'' \\SCLVL{lvl} includes~\\po and\nthe two relation are thus consistent.\n\nIt remains to check that the SC orders are pairwise consistent:\n\\marginpar{Luc to Jade, unclear whether omitting the \\texttt{ScSc}\nchecks will impact valid candidates or not.}\n\\begin{verbatim}\ncall consistent(SWI,SWAVE) as ScSc\ncall consistent(SWI,SWG) as ScSc\ncall consistent(SWI,SAGENT) as ScSc\ncall consistent(SWI,SSYSTEM) as ScSc\ncall consistent(SWAVE,SWG) as ScSc\ncall consistent(SWAVE,SAGENT) as ScSc\ncall consistent(SWAVE,SSYSTEM) as ScSc\ncall consistent(SWG,SAGENT) as ScSc\ncall consistent(SWG,SSYSTEM) as ScSc\ncall consistent(SAGENT,SSYSTEM) as ScSc\n\\end{verbatim}\nAs an example\n\n\\section{Races}\nThe HSA document provides two definition of conflicts, ordinary\nand special.\nOrdinary conflicts are defined as follows:\n``\\emph{Two operations $X$ and~$Y$ conflict, iff they access one or\nmore common byte locations, at least one is a write, and at least one is\nan ordinary data operation}''.\nHaving noticed that ``conflicts'' form a symmetric relation, we paraphrase\nthe definition:\n\\begin{verbatim}\nlet at-least-one a = (a * _) | (_ * a)\n\nlet ordinary-conflicts = loc & at-least-one(W) & at-least-one(Ordinary)\n\\end{verbatim}\nWe use one pre-defined relation:\n\\verb+loc+ that relates accesses to the same location\n(\\herd{} does not handle mixed-size accesses yet),\nand two pre-defined sets of events:\n\\verb+W+ the set of write operations, and \\verb+Ordinary+ the set of\nordinary data operations.\n\nThe HSA document defines special conflicts as follows:\n\\begin{quote}\\em\n Two special operations $X$ and~$Y$ conflict iff $X$ and $Y$ access\nthe same byte location and:\n\\begin{itemize}\n\\item[35.] $X$ and~$Y$ are different sizes (e.g., 32-bit vs. 64-bit), or\n\\item[36.] At least one is a write (or a read-modify-write),\nand $\\neg(\\textit{Match}(\\textit{SI}(X), \\textit{SI}(Y))$.\n\\end{itemize}\n\\end{quote}\nWe ignore condition~35, by lack of mixed-size accesses,\nand remind that \\verb+W+, our pre-defined set of write operations,\nincludes the write performed by RMW operations.\nCondition~36. refers to a (negated) \\textit{Match} predicate\nand to a~\\textit{SI} function.\nBoth are defined in Sec. ``Scope instances'' of the HSA document.\n\nThe function~\\textit{SI} returns the set of scope instances specified by\nan operation, and the \\textit{Match} predicate\ntests the non-emptiness of intersection.\nIn our Sec.~\\ref{sso} we have defined the relation~\\texttt{same-instance('\\textit{lvl})} that relates events that specify a common scope instance at level~\\textit{lvl}. Hence, we represent~\\textit{Match} by the relation~\\verb+matches+\nthat relates events specifying a common scope instance at some level.\nIn effect, we quantify over scope levels rather than on pairs of operations\nand  define \\verb+matches+ as the union of \\texttt{same-instance('\\textit{lvl})}\nfor all scope levels. In \\cat{} we write:\n\\begin{verbatim}\nlet matches = union-scopes same-instance\n\nlet special-conflicts =\n  (loc & (Atomic * Atomic) & at-least-one(W)) \\ matches\n\\end{verbatim}\nThe function~\\verb+union-scopes+ that returns the union of\nthe application of a function on all scope tags is defined\nin our Sec.~\\ref{sso}.\n\nThe definition of HSA conflicts lacks a common additional condition:\naccesses have to be by different units, which we consider in\nthe definition of conflicts below, by the means of the pre-defined~\\verb+ext+\nrelation that relates operations by different units:\n\\begin{verbatim}\nlet conflicts = ((ordinary-conflicts|special-conflicts) & ext) \\ at-least-one(I)\n\\end{verbatim}\nWe have also considered that initial writes (pre-defined set~\\verb+I+)\ndo not enter in conflicts.\nAs a matter of fact \\herd{} consider the initial value of a location\nto come from an explicit initial write operation, for the $\\rf$ relation to be\ndefined on all read operations.\n\nWe then define races as conflicts that are not ordered by HSA happens-before,\nin either way:\n\\begin{verbatim}\nlet hsa-race = conflicts \\ (hhb | hhb^-1)\n\\end{verbatim}\nWe used the postfix~$r\\texttt{\\^{}-1}$ operator that evaluates to\nthe inverse of relation~$r$.\n\nIt remains to inform the \\herd{} simulator about race occurrence.\nWe do so with the \\texttt{flag} construct, which apply to all checks.\nThe normal behaviour for a check is to stop model execution when invalid.\nBy contrast, a failing flagged check\ndoes not stop execution but instead ``flags'' it with an arbitrary flag\n(here \\verb+undefined+).\nThose flags are recorded and handed over to the \\herd7{} machinery\nat the end of model execution --- hence for valid executions that passed\nall (unflagged) checks.\nThe simulator \\herd{} can then decide that the simulated program is undefined,\nas soon as one of the valid executions has been flagged as \\verb+undefined+.\n\\begin{verbatim}\nflag ~empty hsa-race as undefined\n\\end{verbatim}\nObserve that the execution is flagged when the \\verb+hsa-race+ relation is\n\\emph{not} empty.\n\n\n\\appendix\n\\section{\\label{procedure}Checks and procedures}\nA model text is a list of instructions.\nChecks are significant instructions that, depending on check outcome,\nwill let execution continue or stop it.\nFor instance we can test that the two relations\n\\coh{} and \\po{} are consistent by the instruction:\n\\begin{verbatim}\nirreflexive coh;po as CohPoCons\n\\end{verbatim}\nHere, execution will continue when \\coh{} and~\\po{} are consistent,\n\\emph{i.e.} when the sequence relation $\\coh; \\po$ is irreflexive.\nFurther notice that checks have an optional name, introduced by the \\texttt{as}\nkeyword, for documentation and control purposes (see \\herd{} option \\texttt{-skipchecks}).\n\nIn the case of the consistency check it may be interesting to abstract the\ndetails of the check by defining a procedure:\n\\begin{verbatim}\nprocedure consistent(a,b) =\n  irreflexive a;b\nend\n\\end{verbatim}\n\nA procedure is called by using the explicit ``\\texttt{call}'' keyword.\nAs an example the consistency of \\coh{} and~\\po{} can be checked as follows:\n\\begin{verbatim}\ncall consistent(coh,po) as CohPoCons\n\\end{verbatim}\n\n\n\\section{\\label{coh}Generating \\coh}\n\nThe ``coherence'' relation is a fairly classical one.\nIt can be generated by \\herd{} from the $\\coinit$ pre-defined relation.\nThis relation expresses a few constraints on the writes:\nit relates initial writes to all other writes and\nall non-final writes to final writes, for each  location~$L$.\nThose constraints on writes are introduced by \\herd{} initial machinery\nthat enumerates all candidate executions, considering all possible\nfinal writes\\footnote{As a matter of fact, we assume that each location\nholds a well defined value at the end of program execution, and we\nenumerate all such final values.} in turn.\n\nIn \\herd{}, we can generate all orders on a certain set of events with the\n\\texttt{linearisations($S$,$R$)} primitive that takes two arguments:\na set of events~$S$ and a relation~$R$.\nThe primitive considers $R_S$, the restriction of~$R$ to $S$ (written\n\\texttt{$R$ \\& ($S$ * $S$)} in the \\cat{} language)\nIf $R_S$ is acyclic, the call will return the set of all total orders\nthat extend $R_S$. Otherwise, \\emph{i.e.} if $R_S$ has a cycle,\nthe primitive returns the empty set.\nHence, assuming $S_L$ to be the set of all memory events to location~$L$,\none can generate the set of all possible $\\cohl{L}$ by the call\n\\texttt{linearisations($S_L$,co0)}.\n\\begin{verbatim}\nlet makeCohL(s) = linearisations(s,co0)\n\\end{verbatim}\n\nIn fact, we want to generate the set of all possible $\\coh$ relations,\n\\emph{i.e.} all the unions of all the possible $\\cohl{L}$ orders for all\nlocations~$L$. To that end we use another \\cat{} primitive:\n\\texttt{partition($S$)} that takes a set of events as argument and\nreturns a set of set of events $T = \\{S_1,\\ldots,S_n\\}$, where each\n$S_i$ is the set of all events in $S$ that act on location $L_i$,\nand, of course $S$ is the union $\\bigcup_{i=1}^{i=n} S_i$.\n\nCombining the effect of the \\texttt{partition} and \\texttt{linearisations}\nprimitives is possible in the \\cat{} language.\nWe first define a, quite classical,\n\\texttt{map} functions that, given a set~$S= \\{e_1,\\ldots,e_n\\}$\nand a function $f$, returns the set $\\{f(e_1),\\ldots,f(e_n)\\}$:\n\\begin{verbatim}\nlet map f  =\n  let rec do_map es = match es with\n  || {} -> {}\n  || e ++ es -> f e ++ do_map es\n  end in\n  do_map\n\\end{verbatim}\nNotice that \\texttt{map} is written in curried style.\nThe code above uses a few of \\cat{} set and relation construct\n``\\texttt{++}'' is set addition (in infix notation),\n``\\verb+{}+ is the empty set.\nIt also uses set pattern matching that permits recursion over sets,\nby considering the empty and non-empty cases, in a manner similar\nto list pattern matching.\n\nThen, we generate the set of all possible \\cohl{L} for all locations~$L$ as\nfollows:\n\\begin{verbatim}\nlet allCohL = map makeCohL (partitions(M))\n\\end{verbatim}\n\nNow, \\texttt{allCohL} is a set of set of relations, one element of which\nis the set of all possible $\\cohl{L}$ orders for a specific~$L$.\nIt remains to generate all possible unions of the $\\cohl{L}$ for\nall possible choices of those and all possible locations~$L$.\nIt can be done by another \\cat{} function~\\texttt{cross}, that takes\na set of sets $S = \\{S_1, S_2, \\ldots, S_n\\}$\nas argument and returns all possible unions\nbuilt by picking elements from each of the $S_i$:\n$$\n\\left\\{\\, e_1 \\cup e_2 \\cup \\cdots \\cup e_n \\mid\ne_1 \\in S_1, e_2 \\in S_2, \\ldots, e_n \\in S_n \\,\\right\\}\n$$\n\\begin{verbatim}\nlet fold f =\n  let rec fold_rec (es,y) = match es with\n  || {} -> y\n  || e ++ es -> fold_rec (es,f (e,y))\n  end in\n  fold_rec\n\nlet rec cross ess = match ess with\n  || {} -> { 0 }\n  || es ++ ess ->\n      let yss = cross ess in\n      fold\n        (fun (e,r) -> map (fun ys -> e | ys) yss | r)\n        (es,{})           \n  end      \n\\end{verbatim}\nIn the code above,\none may notice the use of the union operator ``\\verb+|+''\nand of the empty relation ``\\verb+0+''.\n\nFinally we generate all possible $\\coh$ ``orders'' by:\n\\begin{verbatim}\nlet allCoh = cross allCohL\n\\end{verbatim}\n\n\\section{\\label{bell}The bell file for HSA}\n\n\\end{document}\n", "meta": {"hexsha": "9527590326a57f26f5a55fb6b3de86e2276871d8", "size": 30371, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "catalogue/hsa/doc2/hsa.tex", "max_stars_repo_name": "jmadiot/herdtools7", "max_stars_repo_head_hexsha": "b58a26946e2012a40ad280c3a11f2d251824a3ae", "max_stars_repo_licenses": ["CECILL-B"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "catalogue/hsa/doc2/hsa.tex", "max_issues_repo_name": "jmadiot/herdtools7", "max_issues_repo_head_hexsha": "b58a26946e2012a40ad280c3a11f2d251824a3ae", "max_issues_repo_licenses": ["CECILL-B"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-06-29T09:31:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-02T15:26:56.000Z", "max_forks_repo_path": "catalogue/hsa/doc2/hsa.tex", "max_forks_repo_name": "lukeg101/herdtools7", "max_forks_repo_head_hexsha": "85df8df2a428de8f215a4f1dd016cfa9eedb7164", "max_forks_repo_licenses": ["CECILL-B"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.0794326241, "max_line_length": 234, "alphanum_fraction": 0.7412004873, "num_tokens": 8479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3155078364227857}}
{"text": "\\section{Exploiting Subprograms}\\label{sect:foreground}\n\\subsection{BGP Strategy}\nWhat emerges from the details of BGP's successful examples is a stepwise strategy:  \n\\begin{inparaenum}\n\n\\item Capture the behavior of \\st{s} within a program in a trace matrix $T$.\n\n\\item  Regress $T$ as feature data on the desired program outputs and derive a model $M$. \n\n\\item Assign a value of merit $w$ to each \\st within $M$. Use this merit to determine whether it should be inserted into an archive. Use a modified crossover that draws subprograms from the archive. \n\n\\item Integrate model error and complexity into program fitness so that subprogram behavior influences selection.\n\\end{inparaenum} \\\\\n\n% WEKA Citation M. Hall, E. Frank, G. Holmes, B. Pfahringer,\r%P. Reutemann, and I. H. Witten. The weka data mining software: An update. SIGKDD Explor. Newsl., 11(1):10–18, Nov. 2009.\n\nOne example of the strategy is realized in \\cite{krawiecGecco2014} where, in Step~(2), the fast RepTree (\\REPTREE - Reduced  Error  Pruning  Tree) algorithm  of decision tree classification from the WEKA Data Mining software library\\cite{Hall:2009:WDM:1656274.1656278} is used for regression modeling.  \\REPTREE builds a decision/regression tree using information gain/variance. In Step~(3) merit is measured per Equation~\\ref{eq:subtree_weight} where $|U(p)|$ is the number of subprograms (equivalently distinct columns of the trace) used in the model and $e$ is model error.\n\n\n\\begin{equation}\n\\label{eq:subtree_weight}\nw = \\frac{1}{(1 + e)|U(p)|}\n\\end{equation}\n\n\\subsection{Exploring Model Bias}\nFollowing our motivation to understand the impact of model bias on useful subprogram identification and program fitness, we first explore an alternative realization of BGP's strategy by using the \\SCIKIT optimized version of the CART decision tree algorithm\\footnote{\\url{http://scikit-learn.org/stable/modules/tree.html\\#tree-algorithms-id3-c4-5-c5-0-and-cart}}.  CART (Classification and Regression Trees) is very similar to C4.5, but it differs in that it supports numerical target variables (regression) and does not compute rule sets. CART constructs binary trees using the feature and threshold that yield the largest information gain at each node.  With the \\SCIKIT implementation we derive a model we denote by $M_S$ and contrast it to deriving $M$ which for clarity we now denote as $M_R$ with $M$ subscripted S for \\SCIKIT and R for REPTree. \n\n\\subsection{Identifying Useful Subprograms}\n\\newcommand{\\FULL}{\\textbf{FULL}\\xspace}\n\\newcommand{\\DRAW}{\\textbf{DRAW}\\xspace}\nNext, following our goal to investigate alternate ways to identify useful subprograms based upon the observation that prior work derives useful subtree fitness from a model that references just the feature set of \\textit{one} program, we realize Steps~(1) and (4) alternately.  In Step~(1) we first select a set of programs  $C$ from the population. We then form a new kind of trace matrix, $T_c$, by column-wise concatenating all $T${'s} of the programs in $C$. In a version we call \\FULL,  $T_c$ is then passed through Step~(2). Steps~(3) and (4) are omitted because in each generation only a single machine learning model is built so all of the selected trees put into the archive in a single generation have the same weight.  This realization of the strategy allows us to experiment with different programs in $C$, trying $C$ containing all the programs in the population, for diversity and, conversely trying elitism, holding only a top fraction of the  population by fitness. \n\n% $x\\%$ by fitness (as computed by NSGA2 pareto crowding ordering) where $x$ ranges from 25\\% of the population to a less elite shares of $50\\%$ and $75\\%$.\n\nAn alternate implementation, that we name \\DRAW,  is to draw random subsets from the combined trace of the programs in $C$, and build a model on each.  This would create many candidate subtrees with different error and complexity, and possibly contribute a more robust archive, if it can be populated with subtrees that are frequently selected by the machine learning model.  We modify Step~(4) because subprograms in $M$ come from the set $T_C$, not solely one program. The information we can integrate into program fitness is whether a program contributed a feature to $M$. For this we use $w_c$, see Equation~\\ref{eq:subtree_contrib} which weighs how many times a program's subprogram appeared in the model normalized by the number of features in the model. Let $p'$ be the number of subtrees in the model from program $p$.  We define the weight as $w_c$ per Equation~\\ref{eq:subtree_contrib}\n\n\n\\begin{equation}\n\\label{eq:subtree_contrib}\nw_c = 1 - \\frac{p'}{U(M)}\n\\end{equation}\n\nImplementation details of \\FULL and of \\DRAW are provided the next section.  \n\n\n%Initially $U$ will be the entire population.\n", "meta": {"hexsha": "f6cdb12b49fb0dcbfc77869a8b2426b907c02ff7", "size": 4809, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/gecco_2017_BGP_paper/sections/extensions.tex", "max_stars_repo_name": "flexgp/BehavioralGP", "max_stars_repo_head_hexsha": "14cdb7dc2c1343a6405289ca2b046f01b4746d9b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/gecco_2017_BGP_paper/sections/extensions.tex", "max_issues_repo_name": "flexgp/BehavioralGP", "max_issues_repo_head_hexsha": "14cdb7dc2c1343a6405289ca2b046f01b4746d9b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/gecco_2017_BGP_paper/sections/extensions.tex", "max_forks_repo_name": "flexgp/BehavioralGP", "max_forks_repo_head_hexsha": "14cdb7dc2c1343a6405289ca2b046f01b4746d9b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 102.3191489362, "max_line_length": 982, "alphanum_fraction": 0.7720939904, "num_tokens": 1222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3155078364227857}}
{"text": "\\chapter{Scientific computing: a story}\n\\label{chapter:context}\n    %% TODO Historique : https://fr.wikipedia.org/wiki/Superordinateur#Historique_des_records\n\n    \\section{First computers, from carbon to silicon}%\n    \\label{sec:first_computers}\n\n        % TODO talk about the human computers, followed by the first (machine) computer created by Cray and IBM, also\n        % Von Neuman, analog computers, etc.\n        Science has always been tightly associated to computations, hence it is no surprise that the first computers\n        were not machines, but humans. Already in the second century AD, Ptolemy, a scientist living in Alexandria,\n        wrote the Almagest. This book aggregated the state of the art in mathematics and astronomy and remained a\n        reference for centuries. It contained several tables that were computed by the scientist, including a\n        trigonometric table (called \\emph{table of chords}).\n\n        In 1757, three French astronomers, Clairaut, Lalande and Lepaute, started working on the prediction of the next\n        appearances of Halley's comet~\\cite[Chapter~1]{human_computers}. Using the recent theories of Newton, they had\n        to numerically solve the three-body problem: they computed the orbits of Saturn and Jupiter around the Sun,\n        taking into account the attraction force between the two planets. They carried this computation by splitting the\n        orbits into tiny steps, computing the new planet locations for each step. They used these sequences of coordinates\n        to compute the orbit of Halley's comet around the Sun, by taking into account the effect of the two giant\n        planets on the comet and neglecting the effect of the comet itself on the three bodies. In the end, they were successful in\n        predicting the next appearance of the comet in the beginning of 1759, making an error of only one month. Their\n        work constitutes one of the first recorded division of labor applied to computations, Lalande and Lepaute\n        computed the orbits of the two giant planets while Clairaut computed the orbit of the comet.\n\n        Gaspard de Prony, a French civil engineer, went a step further in this endeavor of organized\n        computation~\\cite[Chapter~2]{human_computers}. In 1791, he was named director of the \\emph{Bureau du Cadastre}.\n        At the time, the French revolutionary government was preparing reforms for their outdated system of weights and\n        measures, which will eventually result in the creation of the metric system. The reforms proposed to measure\n        angles in grades instead of degrees, dividing a right angle into 100 grades instead of 90 degrees. Prony was\n        tasked to prepare trigonometric tables for this decimal grade system. He organized his staff in a hierarchy with\n        three levels:\n        \\begin{itemize}\n            \\item The first class of workers, a handful of renowned scientists like Carnot or Legendre, oversaw the\n                operations. They had to research the appropriate formulas for computing approximations of trigonometric\n                functions with basic arithmetical operations.\n            \\item The second class, subsequently named \\emph{planning committee}, was a team of eight experienced\n                computers. Their task consisted in translating the trigonometric equations produced by the first class\n                into a sequence of additions and subtractions. They prepared worksheets where all the basic operations\n                were written with a blank space for the result.\n            \\item The third class consisted in nearly ninety computers. Many of them were former servants or wigmakers\n                that lost their jobs with the Revolution and did not know any mathematics besides the addition and\n                subtraction. Their job was to compute the results to fill the blank spaces left by the second class of\n                workers.\n        \\end{itemize}\n\n        The idea of constructing a machine capable of doing computations is not recent. Already in 1642, Blaise Pascal,\n        a French mathematician, invented and built a mechanical calculator that could perform the four arithmetical\n        operations. The calculator was not commercially viable at the time, so only twenty machines were built. Much\n        later, in the first half of the nineteenth century, Charles Babbage~\\cite[Chapters~2-3]{human_computers}, an\n        English mathematician, invented two very innovative machines. The difference engine, for computing tables of\n        polynomial functions, and the analytical engine, a general purpose computer that would subsequently be qualified\n        as \\emph{Turing-complete}. Unfortunately, due to a lack of funding, he was never able to build his inventions.\n        In the same period, a French inventor named Thomas de Colmar designed and manufactured a digital\n        mechanical calculator, called arithmometer. Capable of doing the four arithmetical operations, it was the first\n        machine of its kind to be reliable enough for a practical use.  Similarly, Herman Hollerith, an American\n        inventor, created the tabulating machine. Initially built to process the 1890 US Census data, it worked by\n        reading and summarizing information stored in punched cards. It decreased considerably the duration and cost of\n        the whole census organization. These two last inventions~\\cite[Chapter~6]{human_computers} were commercial\n        successes and started an era of mechanical computations that lasted until the second half of the twentieth\n        century.\n\n        Gradually, computing became more and more important and recognized as a discipline. The apparition of modern\n        statistics, mainly due to the work of Francis Galton and Karl Pearson in the early twentieth century, led to a\n        growing need for computation power. The First World War itself was an important catalyst, as the American,\n        French and English governments hired entire computing laboratories to create ballistic\n        tables~\\cite[Chapter~10]{human_computers}. By the time, electromechanical computers were used everywhere, for\n        their efficiency and reliability largely superior to human computers. There was still an important need for\n        human labor, not only for operating these machines, but because some complex operations were still carried by hand.\n\n        The first working general purpose programmable computer, named \\emph{Z3}, was designed and built more than two\n        decades later in Germany by Konrad Zuse~\\cite{sep-computing-history}. Completed in 1941, it was an\n        electromechanical machine, using both (mechanical) relays and (electronic) vacuum tubes. Its programs, written\n        on external tapes, could use loops but not conditional branches. In 1944, the British government built the first\n        fully electronic computer, named \\emph{Colossus}. Made of vacuum tubes, its primary function was to break the\n        German ciphers during the war. Later, in 1945, the first US electronic computer was unveiled, called\n        \\emph{ENIAC}. Both the Colossus and ENIAC computers were programmed by plugboards and switches, instead of\n        reading from a tape like the Z3. Interestingly, the Z3 and Colossus machines used binary arithmetic while the\n        ENIAC used decimal representation.\n\n        An important breakthrough came with the notion of stored-program computer, \\ie the idea of storing the program\n        instructions in memory. Although the original ideas can be traced to Turing himself and his 1936 article, the\n        real implementation in electronic computers came several years later. The first stored-program computer was\n        the \\emph{Manchester Baby}, built at the University of Manchester in 1948~\\cite{sep-computing-history}.\n        Similarly, the successor of the ENIAC, called \\emph{EDVAC} was also a stored-program computer. Yet, at the time,\n        computers were still using vacuum tubes. Although this was a great reliability improvement to the mechanical\n        parts used before, the vacuum tubes had a very large electricity consumption which started to become problematic\n        (the ENIAC consumed \\NSI{150}{\\kilo\\watt}, the EDVAC \\NSI{56}{\\kilo\\watt}). They also required many\n        human operators for their daily usage.\n\n        The invention of the transistor in 1947 by three Bell Labs physicists had a huge impact on the whole electronic\n        world. It achieves the same functionality as a vacuum tube (amplifying and switching an electrical signal),\n        but with a much lower power consumption, much smaller size and easier to mass produce. Hence, it is no\n        surprise if the industry quickly started to use this new technology. The first transistor computer was made in\n        1953 in the University of Manchester. Later, in 1955, IBM announced the first commercial transistor computer,\n        the IBM 608~\\cite{ibm608}, made of \\Num{3000} transistors. Compared to its predecessor, switching to transistors\n        allowed IBM to reduce the computer physical size by \\NSI{50}{\\percent} and its power consumption by\n        \\NSI{90}{\\percent} while multiplying its computing speed by \\Num{2.5}, reaching a performance of \\Num{4500}\n        additions per second.\n\n    \\section{Exponential growth}%\n    \\label{sec:exponential_growth}\n\n        % TODO Moore's law, huge performance gains, helped to get great scientifical breakthrough\n        % Not terminated yet, we \"need\" to go further. Side note: when will it be enough? Question of the environmental\n        % impact (we make great progress in terms of efficiency, like flops/W, but the growth is even faster (so for\n        % instance the total consumptions are still increasing)).\n        In 1965, Gordon Moore, who will later become the CEO and co-founder of Intel, predicted an exponential growth of\n        the number of transistors in a chip~\\cite{moore:1965}, based on an extrapolation of the current pace of\n        technological progress. He estimated that the number of transistors was doubling every year:\n        \\begin{quote}\n            The complexity for minimum component costs has increased at a rate of roughly a factor of two per year.\n            Certainly over the short term this rate can be expected to continue, if not to increase. Over the longer\n            term, the rate of increase is a bit more uncertain, although there is no reason to believe it will not\n            remain nearly constant for at least 10 years.\n        \\end{quote}\n\n        Ten years later, Moore revised his forecast to a doubling every two year~\\cite{moore:1975}. This prediction,\n        which revealed to be true, is now known as \\emph{Moore's law}.\n\n        \\begin{figure}[htbp]\n            \\centering\n            \\includegraphics[width=\\textwidth]{img/context/49_years.pdf}\n            \\caption{\\label{fig:context:49_years}\n            Evolution of the processor characteristics between 1971 and 2020. Plot inspired from the work of Pedro Bruel,\n            generated with data from Wikipedia~\\cite{wiki2021chronology,wiki2021transistor}.}\n        \\end{figure}\n\n        One of the main contributors to this exponential growth of the number of transistors is the exponential\n        decrease of their size, as plotted in Figure~\\ref{fig:context:49_years}. While the IBM 608 calculator\n        commercialized in the 50s had transistors ``no bigger than a paper clip''~\\cite{ibm608}, the latest processors\n        commercialized in 2020 have \\NSI{5}{\\nano\\meter} transistors.\n\n        In 1974, Dennard~\\etal listed a set of rules for scaling simultaneously the transistor density, clock frequency\n        and power dissipation of processors~\\cite{dennard}, which would eventually be named \\emph{Dennard scaling}. The\n        effect of this scaling on the device is summarized in Table~\\ref{tab:dennard}. A scaling of \\(\\kappa\\) will\n        result in a clock frequency multiplied by a factor \\(\\kappa\\) and a number of transistors multiplied by\n        \\(\\kappa^2\\) while the power density of the chip remains constant, \\ie if the size of the processor does not\n        change, it will have the same power consumption and generate the same amount of heat.\n\n        \\begin{table}[htpb]\n            \\centering\n            \\caption{Dennard scaling with a factor \\(\\kappa\\) (table reproduced from~\\cite[Table 1]{dennard}).}\n            \\label{tab:dennard}\n            \\begin{tabular}{l|c}\n                Device or Circuit Parameter & Scaling Factor\\\\\n                \\hline\n                Device dimension \\(t_{ox}, L, W\\) & \\(1/\\kappa\\)\\\\\n                Doping concentration \\(N_a\\) & \\(\\kappa\\)\\\\\n                Voltage \\(V\\) & \\(1/\\kappa\\)\\\\\n                Current \\(I\\) & \\(1/\\kappa\\)\\\\\n                Capacitance \\(C=\\epsilon A/t\\) & \\(1/\\kappa\\)\\\\\n                Delay time/circuit \\(VC/I\\) & \\(1/\\kappa\\)\\\\\n                Power dissipation/circuit \\(VI\\) & \\(1/\\kappa^2\\)\\\\\n                Power density \\(VI/A\\) & 1\\\\\n            \\end{tabular}\n        \\end{table}\n\n        Unfortunately, Dennard scaling came to an end 15 years ago. Indeed, it is no longer possible to scale the\n        operating voltage and the gate oxide thickness~\\cite{Bohr_2007}, as transistors have reached scales where power\n        leakage is no longer negligible. With a voltage that cannot be scaled anymore, the power density cannot remain\n        constant and reaches alarming levels of more than\n        \\NSI{4}{\\watt/\\milli\\metre\\squared}~\\cite{Hennessy_2019,Hennessy_youtube}, as illustrated in\n        Figure~\\ref{fig:context:power_density}.\n\n        \\begin{figure}[htpb]\n            \\centering\n            \\includegraphics[width=\\linewidth]{img/context/power_density.pdf}\n            \\caption{Evolution of the power density in the last 20 years (plot reproduced from ~\\cite[Figure\n            3]{Hennessy_2019}).}%\n            \\label{fig:context:power_density}\n        \\end{figure}\n\n        Consequently, it has become impossible to increase further the CPU frequency, which has reached a limit of about\n        \\NSI{5}{\\giga\\hertz} since 2006 after an exponential growth of several decades, as shown by\n        Figure~\\ref{fig:context:49_years}. One of the responses to keep the race for performance was to design multicore\n        processors. Nowadays, nearly all laptops and smartphones have several cores, while high-end servers can have two\n        or four sockets with up to 64 cores per socket.\n\n        Yet, it appears that using several cores was only a short-term help for increasing the CPU\n        performance. With the end of Dennard scaling, the power density increases with each generation of processor.\n        Hence, to stay within a safe thermal design power (TDP), it is no longer possible to power at the nominal\n        voltage all the components of the processors (notion named \\emph{dark silicon}). Esmaeilzadeh~\\etal predict\n        that with the \\NSI{8}{\\nano\\metre} processor generation, more than \\NSI{50}{\\percent} of their transistors might\n        be unpowered at any given time~\\cite{Esmaeilzadeh_2011}. With these constraints, Hennessy and\n        Patterson~\\cite{Hennessy_2019,Hennessy_youtube} estimate that the single-processor performance is now only\n        growing by a mere \\NSI{3}{\\percent} per year, which is a much slower pace than the \\NSI{50}{\\percent} yearly\n        growth rate that the industry got used to for decades.\n\n        % First, performance gains are limited by Amdahl's law, stating that the maximal speedup obtained by running an\n        % application on \\(P\\) cores is \\(\\frac{1}{(1-f) + f/P}\\) where \\(f\\) is the fraction of the application that can\n        % be run in parallel. For instance, an application whose \\NSI{95}{\\percent} of the execution can be made in\n        % parallel will have a speedup of at most \\(20\\), even with an infinite number of cores.\n\n    \\section{Scientific computing today}%\n    \\label{sec:scientific_computing_today}\n\n        \\subsection{High performance computing}%\n        \\label{sub:hpc}\n\n            Computations are now used in every scientific fields, from small statistical calculations to large numerical\n            simulations. Science as a whole has immensely benefited from this exponential performance improvement. For\n            instance, the price for sequencing an entire human genome has dropped from \\SI{100000000}[\\$]{} in 2001 to\n            \\SI{1000}[\\$]{} in 2020~\\cite{genome_sequencing}.\n\n            To reach the highest performance, a single processor is not enough, and the benefit of doing computations in\n            parallel was already well known at the time of human computers, as discussed in Section~\\ref{sec:first_computers}.\n            For this reason, the largest computations are now performed on supercomputers, large machines made of many\n            processors connected through a fast network. The 500 fastest non-classified supercomputers of the world are\n            ranked biannually in the Top500 list~\\cite{top500}. As shown by Figure~\\ref{fig:context:top500}, they suffered from\n            the same frequency staling as the rest of the industry in 2006, yet their performance kept an exponential\n            increase, in part explained by the exponential increase of their total number of cores.\n\n            \\begin{figure}[htbp]\n                \\centering\n                \\includegraphics[width=\\textwidth]{img/context/top500.pdf}\n                \\caption{\\label{fig:context:top500}\n                Evolution of the Top500~\\cite{top500} supercomputers between 1993 and 2020.  The line denotes the median, the inner ribbon\n                contains the \\([\\NSI{10}{\\percent}, \\NSI{90}{\\percent}]\\) interval, the outer ribbon contains all the\n                values.\\\\ Data compiled by Dan Lenski~\\cite{top500_compiled} and plotted by ourselves.}\n            \\end{figure}\n\n            The largest supercomputers now have thousands of processors, millions of cores and power consumptions of several\n            megawatts. At these scales, and with the hardware and software complexity required to reach the highest\n            performance, it is extremely difficult to have an accurate picture of the whole platform. Even if all the\n            individual components are deterministic at a microscopic level, a supercomputer observed at a macroscopic level\n            can arguably be seen as a stochastic object. Hence, it is very common for the operators or the users of these\n            machines to stumble on performance anomalies, \\ie the \\emph{observed} performance is different from the\n            \\emph{expected} performance. For instance, Petrini~\\etal~\\cite{Petrini_2003} found a severe but previously\n            undetected performance problem on the supercomputer they were using, responsible for a \\NSI{100}{\\percent}\n            performance variation and caused by operating system perturbations. Likewise,\n            Tuncer~\\etal~\\cite[Section~1]{Tuncer_2017} list several examples of performance problems observed in operation:\n            \\begin{itemize}\n                \\item The amount of variation in application running time can reach \\NSI{100}{\\percent} on real-life\n                    systems~\\cite{Bhatele_2013,Skinner}.\n                \\item Orphan processes left over from previous jobs consuming system resources~\\cite{Brandt_2010}.\n                \\item Firmware bugs, affecting the CPU usage on the server and making the user programs\n                    fail~\\cite{cisco_bug}.\n                \\item Memory leaks in applications, eventually leading to job failure~\\cite{Agelastos_2015}.\n                \\item CPU throttling of the nodes for thermal control~\\cite{Brandt2015EnablingAO}.\n                \\item Resource contention~\\cite{Bhatele_2013,dorier:hal-00916091}.\n            \\end{itemize}\n            If unnoticed, these kinds of performance anomalies can severely impact the conclusions than an experimenter\n            would draw based on performance measures obtained on the machine.\n\n        \\subsection{A reproducibility crisis}%\n        \\label{sub:reproducibility_crisis}\n\n            For several years there has been an ongoing concern of a reproducibility crisis in science. An online survey\n            done in 2016 found that among the \\Num{1576} scientists who responded, \\NSI{70}{\\percent} have failed at\n            least once to reproduce the work of another scientist, \\NSI{50}{\\percent} have even failed to reproduce\n            their own work~\\cite{nature_survey}. This crisis is particularly concerning in medical science, where some\n            researchers estimate that a large part of claimed research findings are\n            false~\\cite{Ioannidis_2005,freedman}. In this field, the main sources of non-reproducibility are a wrong\n            usage of statistics, poor experimental methods or even frauds~\\cite{science_misconduct}. In other\n            disciplines such as computational biology or computational physics, reproducibility issues mainly come\n            from numerical instability and the growing complexity of software environments~\\cite{dong2021}.\n\n            Computer science is not immune to these concerns of statistical misusage, numerical errors or frauds.  A\n            recurrent problem is also the unavailability of the software programs, methods and data on which are based the\n            research articles. For instance, Collberg~\\etal examined 601 papers from ACM conferences and journals, they\n            were able to personally build the software of only 194 of them while they simply could not access the code\n            of 176 of these papers~\\cite{collberg2015repeatability}. Likewise, Papadopoulos~\\etal propose eight\n            methodological principles for better reproducibility and show that most of the published articles\n            they surveyed did not follow all these principles~\\cite{Papadopoulos_2019}.\n\n            What may be more surprising is that computer science suffers from the same experiment reproducibility\n            problems than the other sciences: experimental biases exist and may even be larger. For instance,\n            Mytkowicz~\\etal show that simply changing the environment variable size can account for a performance\n            variability of more than \\NSI{30}{\\percent}~\\cite{Mytkowicz_2009}. They propose two methods for detecting\n            and avoiding such measurement bias, based on experiment randomization. Similarly, Curtsinger and Berger have\n            implemented a software for repeatedly re-randomizing the layouts of code, stack and heap at runtime, to\n            avoid the bias introduced by a particular binary layout~\\cite{stabilizer}. Again, the growing problem of\n            experimental reproducibility we are describing here is tightly coupled to the growing software and hardware\n            complexity.\n\n    \\section{This thesis}%\n    \\label{sec:this_thesis}\n\n        In this thesis, we argue that a large part of computer science, and in particular high performance computing, is\n        an experimental science. It is commonplace for computer scientists to run experiments, \\eg for comparing the\n        performance of several algorithms. With the kind of variability described in\n        Section~\\ref{sec:scientific_computing_today}, such experiments could easily lead to false conclusions. We\n        therefore advocate for using similar methods to the natural sciences, which have been faced with the same issues\n        for decades.\n\n        Our contribution towards this goal of improving the confidence in the experimental results is multiple:\n        \\begin{itemize}\n            \\item In Part~\\ref{part:prediction}, we propose a methodology for predicting the performance of an\n                application through simulation. Similarly to biology or physics, making an experiment in simulation\n                can be of great help to rule out part of the experimental bias. It can also enable the researchers to\n                test scenarios that would be too costly in reality.\n                \\begin{itemize}\n                    \\item We contextualize this work in Chapters~\\ref{chapter:prediction:related_work}\n                        and~\\ref{chapter:prediction:hpl}.\n                    \\item We explain how to improve the efficiency of the simulation in\n                        Chapter~\\ref{chapter:prediction:emulation}.\n                    \\item The models we used for the predictions are presented in\n                        Chapter~\\ref{chapter:prediction:modeling}.\n                    \\item Chapter~\\ref{chapter:prediction:validation} is a thorough validation of the simulations, where\n                        we compare the predicted performance with the observations made on real experiments.\n                    \\item We illustrate an important use case of such simulations in\n                        Chapter~\\ref{chapter:prediction:sensibility} by performing several sensibility studies.\n                \\end{itemize}\n            \\item In Part~\\ref{part:experiment}, we present additional tools and methods to help experimenters increase\n                the quality of their work.\n                \\begin{itemize}\n                    \\item Automation is a great way to improve both reliability and productivity. It helped tremendously\n                        throughout the last century for scientific computations, as shown in\n                        Section~\\ref{sec:first_computers}. Machines make much fewer mistakes than humans (if any) and\n                        are much faster. For these reasons, we implemented several programs during this thesis. We\n                        automatized the execution of experiments with an experiment engine, presented in\n                        Chapter~\\ref{chapter:experiment:testbed}. We also implemented several tools, listed in\n                        Appendix~\\ref{chapter:zenodo}, for automating some parts of the analyses as well as cumbersome\n                        daily tasks.\n                    \\item Several times while conducting the research in this thesis, our performance models were not in\n                        agreement with the\n                        reality we observed. In some instances, our models were too simple, and we needed to add\n                        complexity to capture additional real-world phenomena, as described in\n                        Chapters~\\ref{chapter:prediction:modeling} and~\\ref{chapter:prediction:validation}. But, most of\n                        the time, we suffered from an experimental bias (or the lack thereof). These difficulties are\n                        described in depth in Chapter~\\ref{chapter:experiment:difficulties}.\n                    \\item With an experimental work that spans several years, like this thesis, it is very likely that the\n                        object of the experimental study will evolve. In the case of high performance computing, the\n                        machine can\n                        have hardware or software upgrades, or even defects, that can all affect significantly the\n                        measured performance. In Chapter~\\ref{chapter:experiment:tests}, we present the performance\n                        non-regression tests we implemented and used in the second half of this thesis. They helped us\n                        to detect numerous platform changes that could have led to wrong conclusions if unnoticed.\n                \\end{itemize}\n        \\end{itemize}\n\n        % \\todo{\n        % Performance anomalies $\\rightarrow$ reproductibility problem (eg. if we compare two implementations, how can we be sure\n        % that the difference we observe really come from the two implementations).\n        % $\\rightarrow$ Need a way for the users to have more confidence in their experiments.\n        % $\\rightarrow$ Several contributions towards this goal:\n        % (1) Simulation of application, to remove the need of doing experiments.\n        % (2) Automation of experiments (peanut), to reduce a lot the possibility of human mistakes.\n        % (3) List several experimental difficulties, some of them very unsettling, to be aware of what can happen.\n        % (4) Performance non regression tests of the platform, to detect significant changes.}\n\n    % \\section{Increased complexity}%\n    % \\label{sec:increased_complexity}\n\n        % TODO increased complexity everywhere (HW and SW), deterministic at micro-level but the macro-level is random\n        % no complete understanding of the whole thing, we need experimental CS, we need models (very similarly to what\n        % is done in physics or biology)\n    %     Some horror stories~\\cite{Petrini_2003}\\dots\n", "meta": {"hexsha": "21d680108e89ffc4ca426c1f5f8307c9fc6e9cd7", "size": 28779, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapter_introduction.tex", "max_stars_repo_name": "Ezibenroc/thesis", "max_stars_repo_head_hexsha": "62c239406d5979f1c9aabf180c8232ce2f2b1ee7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapter_introduction.tex", "max_issues_repo_name": "Ezibenroc/thesis", "max_issues_repo_head_hexsha": "62c239406d5979f1c9aabf180c8232ce2f2b1ee7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter_introduction.tex", "max_forks_repo_name": "Ezibenroc/thesis", "max_forks_repo_head_hexsha": "62c239406d5979f1c9aabf180c8232ce2f2b1ee7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 81.9914529915, "max_line_length": 138, "alphanum_fraction": 0.7045762535, "num_tokens": 6142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3153597123193522}}
{"text": "\\documentclass[12pt]{article}\n\n\\usepackage{headerfooter}\n\\usepackage{epsfig}\n\\usepackage{verbatimfiles}\n\\usepackage{fullpage}\n\\usepackage{amsmath}\n\n\\newcommand{\\HRule}{\\rule{\\linewidth}{.3mm}}\n\n\\bibliographystyle{plain}\n\\begin{document}\n\n\\newcommand{\\pd}[2]{\\frac{\\partial{#1}}{\\partial{#2}}}\n\n\\begin{center}\n{\\bf \\Large Beam-Column Elements in OpenSees}\n\n{\\bf August 22, 2001} \n\n{\\bf Michael H. Scott} \n\n{\\bf PEER, University of California, Berkeley}\n\\end{center}\n\nThis document provides a brief description of the interaction between a beam-column\nelement and the SectionForceDeformation and CoordTransformation classes in OpenSees.\nMaterial and geometric nonlinearities are abstracted, or separated, from the\nelement formulation by using the SectionForceDeformation and CoordTransformation\nclasses. As a result, an element can be programmed in the ``basic system'' to account\nfor material nonlinearities, then use one of many transformation types to pick\nup geometric nonlinearities.\nA displacement based, distributed plasticity formulation is presented as an\nexample of how a beam-column element is formulated in the basic system.\n\n\\section{Geometric Nonlinearity}\nIn general, the transformation of nodal displacements, {\\bf u}, in the global system\nto deformations, {\\bf v}, in the basic system is described by a nonlinear\nfunction,\n\n\\begin{equation}\n\\label{eq:v=v(u)}\n{\\bf v} = {\\bf v}({\\bf u}).\n\\end{equation}\n\nIn a similar manner, the transformation of basic forces, {\\bf q}, to forces\n{\\bf p} in the global frame of reference is given by\n\n\\begin{equation}\n\\label{eq:p=p(q,u)}\n{\\bf p} = {\\bf p}({\\bf q}({\\bf u}), {\\bf u}),\n\\end{equation}\n\n\\noindent where {\\bf p} is implicitly a function of {\\bf u} via the basic forces,\n{\\bf q}, as well as an explicit function of {\\bf u}. The explicit dependence on\n{\\bf u} takes into account {\\em approximate} geometric nonlinearities such as\nP-$\\Delta$. These transformations are shown schematically in\nfigure~\\ref{fig:Transformation}.\n\n\\begin{figure}[htpb]\n\\begin{center}\n\\leavevmode\n\\hbox{%\n\\epsfxsize=6.0in\n\\epsffile{./fig_files/BeamTransf.eps}}\n\\end{center}\n\\caption{Transformations between global and basic systems}\n\\label{fig:Transformation}\n\\end{figure}\n\nAs seen in figure~\\ref{fig:BeamClass}, a beam-column element acquires geometric\nnonlinearity from the CoordTransformation class, and material nonlinearity from the\nSectionForceDeformation class.\n\n\\section{Material Nonlinearity}\nAt every cross-section along the element length, a force-deformation\nrelationship holds, providing section stress resultants, {\\bf s}, as a\nfunction of section deformations, {\\bf e},\n\n\\begin{equation}\n\\label{eq:s=s(e)}\n{\\bf s}(x) = {\\bf s}({\\bf e}(x)).\n\\end{equation}\n\n\\noindent Linearizing the force-deformation relationship with respect to\ndeformations reveals the section tangent stiffness, ${\\bf k}_s$,\n\n\\begin{align}\n\\Delta{\\bf s} &= \\pd{\\bf s}{\\bf e} \\Delta{\\bf e} \\\\\n\\Delta{\\bf s} &= {\\bf k}_s \\Delta{\\bf e},\n\\end{align}\n\n\\noindent where ${\\bf k}_s = \\pd{\\bf s}{\\bf e}$, the partial derivative of the\nsection stress resultants with respect to the section deformations.\n\nA beam-column element obtains material nonlinearity through use of the\nSectionForceDeformation class, as seen in figure~\\ref{fig:BeamClass}.\n\n\\section{Class Hierarchy}\nFigure~\\ref{fig:BeamClass} shows the class interaction between a beam-column\nelement and the CoordTransformation and SectionForceDeformation classes.\nAn element can use any one of Linear, PDelta, or Corotational transformations;\nand any one of ElasticSection or FiberSection constitutive models. When a new\ntransformation or section class is added to the framework, the element can use\nthe new class without modification.\n\n\\begin{figure}[htpb]\n\\begin{center}\n\\leavevmode\n\\hbox{%\n\\epsfxsize=6.5in\n\\epsffile{./fig_files/BeamClass.eps}}\n\\end{center}\n\\caption{DispBeamColumn class diagram}\n\\label{fig:BeamClass}\n\\end{figure}\n\n\\section{Displacement Based Element Formulation}\nThis section describes the formulation of a displacement based, distributed plasticity\nbeam-column element. The governing compatibility and equilibrium equations are covered\nalong with the consistent element stiffness. Bending deformations are assumed to be\nsmall, and shear deformations are neglected.\n\n\\subsection{Compatibility}\nFor displacement based elements, there is a strong form of compatibility between\nbasic displacements, {\\bf v}, and section deformations {\\bf e}, satisfied\npointwise along the element length,\n\n\\begin{equation}\n\\label{eq:e=av}\n{\\bf e}(x) =\n\\left[ \\begin{array}{c} \\varepsilon(x) \\\\ \\kappa(x) \\end{array} \\right] =\n{\\bf a}(x) {\\bf v},\n\\end{equation}\n\n\\noindent where {\\bf a} is the strain-displacement matrix. The section deformations\nare the axial strain, $\\varepsilon$, and curvature, $\\kappa$. Assuming linear axial\ndisplacement and transverse displacement based on cubic Hermitian polynomials,\nthe shape functions in the basic system are\n\n\\begin{equation}\n\\label{eq:N}\n{\\bf N}(x) =\n\\left[ \\begin{array}{c} N_1(x) \\\\ \\\\ N_2(x) \\\\ \\\\ N_3(x) \\end{array} \\right] =\n\\left[ \\begin{array}{c} \\frac{x}{L} \\\\ \\\\\nL\\left( \\frac{x}{L} - 2\\frac{x^2}{L^2} + \\frac{x^3}{L^3} \\right) \\\\ \\\\\nL\\left( -\\frac{x^2}{L^2} + \\frac{x^3}{L^3} \\right)\n\\end{array}\n\\right].\n\\end{equation}\n\n\\noindent The strain-displacement matrix contains the shape function derivatives.\nAxial strain is the first derivative of the axial displacement, and\ncurvature is the second derivative of the transverse displacement,\n\n\\begin{equation}\n{\\bf a}(x) = \\left[ \\begin{array}{ccc}\nN_{1,x} & 0 & 0 \\\\ \\\\\n0 & N_{2,xx} & N_{3,xx}\n\\end{array}\n\\right].\n\\end{equation}\n\n\\noindent Using the shape functions defined in equation~\\ref{eq:N}, the\nstrain-displacement matrix is then,\n\n\\begin{equation}\n{\\bf a}(x) = \\frac{1}{L} \\left[ \\begin{array}{ccc}\n1 & 0 & 0 \\\\ \\\\\n0 & -4+6\\frac{x}{L} & -2+6\\frac{x}{L}\n\\end{array}\n\\right].\n\\end{equation}\n\n\\noindent The basic displacements, {\\bf v}, can be obtained by invoking\nthe method {\\em getBasicTrialDisp()}.\nAfter computing section deformations from basic displacements via\nequation~\\ref{eq:e=av}, the\nmethod {\\em setTrialSectionDeformation()} may be invoked with the updated\ndeformations, {\\bf e}.\n\n\\subsection{Equilibrium}\nUsing the principle of virtual displacements (virtual work),\nequilibrium between element end forces, {\\bf q}, and section stress\nresultants, {\\bf s},\nis satisfied weakly, or in an average sense, along the element length,\n\n\\begin{equation}\n\\label{eq:q}\n{\\bf q} = \\int_0^L {\\bf a}(x)^T {\\bf s}(x) \\: dx,\n\\end{equation}\n\n\\noindent where the section stress resultants are the axial force, $P$, and bending\nmoment, $M$,\n\n\\begin{equation}\n{\\bf s}(x) =\n\\left[ \\begin{array}{c} P(x) \\\\ M(x) \\end{array} \\right].\n\\end{equation}\n\nTo obtain the current value of section stress resultants, {\\bf s}, the method\n{\\em getStressResultant()} must be invoked. To perform the transformation from\nbasic to global resisting force (equation~\\ref{eq:p=p(q,u)}), the method\n{\\em getGlobalResistingForce()} should be invoked.\n\n\\subsection{Element Stiffness}\nTo solve the structural system of equations, the element stiffness must be assembled\nalong with the resisting force. The element stiffness is obtained by taking the\npartial derivative of equation~\\ref{eq:p=p(q,u)} with respect to displacements,\n{\\bf u}.\n\n\\begin{align}\n{\\bf k} &= \\pd{\\bf p}{\\bf q}\\pd{\\bf q}{\\bf u} + \\left.\\pd{\\bf p}{\\bf u}\\right|_{\\bf q} \\\\\n&= \\pd{\\bf p}{\\bf q} \\pd{\\bf q}{\\bf v} \\pd{\\bf v}{\\bf u} +\n\\left.\\pd{\\bf p}{\\bf u}\\right|_{\\bf q} \\\\\n{\\bf k} &= \\label{eq:stiff} \\pd{\\bf p}{\\bf q} {\\bf k}_b \\pd{\\bf v}{\\bf u} +\n\\left.\\pd{\\bf p}{\\bf u}\\right|_{\\bf q}\n\\end{align}\n\n\\noindent The basic element stiffness, ${\\bf k}_b$, is the partial derivative\nof the basic forces, {\\bf q}, with respect to the basic displacements, ${\\bf v}$.\nDifferentiating equation~\\ref{eq:q} gives,\n\n\\begin{align}\n{\\bf k}_b &= \\pd{\\bf q}{\\bf v} \\\\\n&= \\int_0^L {\\bf a}(x)^T \\pd{\\bf s}{\\bf v} \\: dx \\\\\n&= \\int_0^L {\\bf a}(x)^T \\pd{\\bf s}{\\bf e} \\pd{\\bf e}{\\bf v} \\: dx \\\\\n{\\bf k}_b &= \\label{eq:kb} \\int_0^L {\\bf a}(x)^T {\\bf k}_s(x) {\\bf a}(x) \\: dx\n\\end{align}\n\nThe section tangent stiffness matrix, ${\\bf k}_s$, is returned upon invoking the\nmethod {\\em getSectionTangent()}. After computing the basic stiffness, ${\\bf k}_b$,\nthe method {\\em getGlobalStiffMatrix()} should be invoked to perform the\ntransformation in equation~\\ref{eq:stiff}. The remaining partial derivatives in\nequation~\\ref{eq:stiff} are computed by the {\\em getGlobalStiffMatrix()} method.\n\n\\subsection{Numerical Quadrature}\nIn general, the element integrals, equations~\\ref{eq:q} and~\\ref{eq:kb}, cannot\nbe evaluated in closed form due to nonlinearities in the section constitutive model.\nThese integrals must be approximately evaluated by numerical quadrature,\n\n\\begin{align}\n\\label{eq:qapprox} {\\bf q} &\\approx\n\\sum_{i=1}^{N_s} {\\bf a}(x_i)^T {\\bf s}(x_i) \\: W_i \\\\\n\\label{eq:kbapprox}{\\bf k}_b &\\approx\n\\sum_{i=1}^{N_s} {\\bf a}(x_i)^T {\\bf k}_s(x_i) {\\bf a}(x_i) \\: W_i ,\n\\end{align}\n\n\\noindent where $N_s$ is the number of integration points, i.e., the number of section\nsample points along the element length.\n\nIntegration points, $\\xi_i$, and weights, $\\omega_i$, are typically\ndefined over a fixed domain such as $\\left[-1,1\\right]$ or $\\left[0,1\\right]$, then\nmapped to the element domain $\\left[0,L\\right]$, where $L$ is the element length.\nAssuming points and weights defined on $\\left[-1,1\\right]$, the following\nrelationships hold,\n\n\\begin{align}\nx_i &= \\frac{L}{2} \\left( \\xi_i+1 \\right) \\\\\nW_i &= \\frac{L}{2} \\: \\omega_i .\n\\end{align}\n\n\\noindent After mapping the points and weights to the element domain,\nequations~\\ref{eq:qapprox} and~\\ref{eq:kbapprox} can be evaluated.\n\n\\end{document}\n", "meta": {"hexsha": "22e36de9153861db8965ef47b6fc4e336101e26b", "size": 9697, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "OpenSees/SRC/doc/BeamTheory.tex", "max_stars_repo_name": "kuanshi/ductile-fracture", "max_stars_repo_head_hexsha": "ccb350564df54f5c5ec3a079100effe261b46650", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-03-05T16:25:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-17T14:12:03.000Z", "max_issues_repo_path": "SRC/doc/BeamTheory.tex", "max_issues_repo_name": "steva44/OpenSees", "max_issues_repo_head_hexsha": "417c3be117992a108c6bbbcf5c9b63806b9362ab", "max_issues_repo_licenses": ["TCL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SRC/doc/BeamTheory.tex", "max_forks_repo_name": "steva44/OpenSees", "max_forks_repo_head_hexsha": "417c3be117992a108c6bbbcf5c9b63806b9362ab", "max_forks_repo_licenses": ["TCL"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-09-21T03:11:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-19T07:29:37.000Z", "avg_line_length": 36.3183520599, "max_line_length": 89, "alphanum_fraction": 0.7251727338, "num_tokens": 2886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.31535970452053885}}
{"text": "\\chapter{Conclusions}\n\\label{ch:conlusions}\n\nIn this chapter, we take the time to revisit what has been achieved in this thesis and to sum up our original contributions to the reinforcement learning literature. Moreover, we draw some conclusions about the impact that these modern optimization techniques can have on the financial industry and the challenges that must be overcome to make it possible. Finally, we suggest some possible axis for future research. \n\n\\section{What Has Been Achieved}\nIn this thesis, we presented an innovative application of some state-of-the-art policy gradient algorithms to the classical asset allocation problem with transaction costs.\\\\ In Chapter \\ref{ch:discrete_time_stochastic_optimal_control} we introduced the basic concepts of stochastic optimal control in discrete time, which is the standard theoretical framework used to model sequential decision problems. In particular, we presented both the traditional risk-neutral formulation, in which the goal of the agent is to maximize its total returns, and the less common risk-sensitive formulation, in which the agent wishes instead to optimize the trade-off between the rewards and the risk required to achieve them. This chapter laid the theoretical foundations and introduced the notation used in the rest of the thesis.\\\\  \nIn Chapter \\ref{ch:reinforcement_learning} we presented the main ideas of \\glsfirst{RL}, a general class of algorithms in the field of \\glsfirst{ML} that allows an agent to learn how to behave in a stochastic and possibly unknown environment only by trial-and-error. This algorithms are typically based on the feedback mechanism between the stochastic environment and the agent, which receives a numerical reward for his actions. After having discussed the characteristic features of the \\gls{RL} problem, we provided a high-level overview of the different typologies of algorithms.\\\\\nIn Chapter \\ref{ch:policy_gradient} we gave an in-depth presentation of Policy Gradient algorithms for the risk-neutral control problem. After having introduced the key ideas of these methods, we provided a thorough review of the state-of-the-art algorithms that can be found in the literature. For episodic environments, most of these methods are based on the well-known likelihood-ratio technique from stochastic optimization  that allows to rewrite the policy gradient as an expected value. For non-episodic environments, the main result from which most of the learning algorithms are derived is the policy gradient theorem.\\\\ \nIn Chapter \\ref{ch:risk_sensitive_policy_gradient} we discussed policy gradient methods for the risk-sensitive control problem, which is still an active field of research. In particular, we presented an extension of the policy gradient theorem to the risk-sensitive framework, both in the average reward and in the discounted reward formulations. To the best of our knowledge, this is the first time that a risk-sensitive policy gradient theorem is proved for a general discounted Markov decision process, in which rewards might as well depend on the next state of the system.\\\\\nIn Chapter \\ref{ch:parameter_based_policy_gradient} we proposed an original parameter-based version of the policy gradient theorem, both for the risk-neutral and the risk-sensitive framework. This extension allowed us to derive efficient online learning algorithms similar in spirit to the well-known \\gls{PGPE} algorithm, which was originally conceived only for episodic environments. Moreover, these new algorithms can be easily enhanced using a critic or the natural policy gradient idea. This chapter undoubtedly represents the most innovative contribution of this thesis to the \\gls{RL} literature.\\\\ \nIn Chapter \\ref{ch:financial_applications_of_reinforcement_learning}, after a brief discussion about why finance represents an extremely challenging field of research, we provided a bibliographical survey of successful financial applications of \\gls{RL} techniques. In particular, we focused on the classical asset allocation problem with transaction cost, which has been used to numerically test the algorithms proposed in the previous chapters.\\\\\nIn Chapter \\ref{ch:numerical_results} we presented the numerical results for the asset allocation problem. We showed that the learning algorithms proposed in the previous chapters perform extremely well on synthetic data, consistently outperforming a simple buy-and-hold strategy and automatically adapting to transaction costs. On the other hand, the algorithms encountered more difficulties on historical data and we tried to provide an explanation for this behavior.\\\\\n\n\\section{Final Remarks}\nThe main contribution of this thesis to the \\gls{RL} literature is the development of some original, online and parameter-based policy gradient algorithms both for the traditional risk-neutral framework and the less common risk-sensitive framework. These algorithms are highly versatile and can be easily combined with some powerful techniques such as the use of a critic or the use of a natural policy gradient.\\\\\nThe numerical application of this innovative algorithms to the classical financial problem of determining a profitable long-short trading strategy confirmed their potential. For a synthetic asset, the strategies learned by the algorithms outperformed the simple Buy \\& Hold strategy, even when investment decisions were only based on extremely basic autoregressive features. Contrarily to standard prediction-based trading systems, the learning algorithms were able to adapt as expected to the introduction of transaction costs by reducing the frequency of reallocation and of short positions.\\\\\nThe algorithms encountered more difficulties in learning a profitable strategy from historical data. In this case, the algorithms failed to converge to a profitable trading strategy probably because of the low signal-to-noise ratio of the historical price series considered and the low capabilities of representation of the controller used. However, even if we considered a more complex controller success would not be a-priori guaranteed. This is due to the inherent complexity of financial markets. Indeed, while identifying patterns in historical data is not particularly hard, finding signals that work reliably in the real world is. Man AHL, a quant unit of Man Group Plc, needed three years of work to gain enough confidence in a machine learning strategy to devote client money to it. Therefore, it is clear that there is still much work to be done to be able to beat the markets with a strategy produced by a \\gls{RL}  algorithm.\\\\\nDespite the difficulties encountered in applying the algorithms developed in this thesis to historical data, we feel confident that in the future these techniques will have a large impact on financial markets. The first reason is that these algorithms have already proven successful in solving very difficult decision problems, such as mastering the game of Go or controlling robots in complex environments. The second reason is the versatility of these techniques, which can be applied with only minor modifications to very different domains. Finally, their modularity allows them to be combined with other modern techniques, such as \\glsfirst{DL}. These features have attracted the interest of the financial community, with investment banks and hedge funds investing large amount of resources to develop innovative solutions  based on \\gls{ML} methods to classical problems. \n \n\\section{Further Developments}\nTo conclude, let us suggest some research directions that could be explored to improve the work presented in this thesis.\\\\ \nThe first idea is to develop more complex features so as to allow the agent to take more informed decisions. A first approach would be to construct the indicators typically used in the technical analysis of stock prices. These measures embed the expert knowledge acquired by financial analysts over decades of activity and could help in guiding the agent towards better decisions. Another approach would be to employ some \\gls{DL} techniques to learn more powerful features directly from data. A first possibility would be to extract new features using a deep auto-encoder in a completely unsupervised way that would then be fed into a simple parametric controller. A second possibility would be to directly replace the simple autoregressive controller considered in this thesis with a deep neural network. Using a deep neural network was one of the key ingredient of many of the recent successes of \\gls{RL}. For a modern presentation of these techniques, the interested reader may refer to \\cite{bengio2015deep}.\\\\\nThe second idea would be to consider high-frequency data, such as intra-day prices and traded volumes. It is well documented that high-frequency data show some characteristic patterns that could be captured by a deep reinforcement learning trading system. An example of application of \\gls{RL} to high-frequency data can be found in \\cite{nevmyvaka2006reinforcement}, where the authors applied some basic algorithms such as Q-learning to the optimal trade execution problem in a limit-order book. It would thus be interesting to apply more advanced techniques to this problem.\\\\\nAs the \\gls{RL} and \\gls{DL} literatures grows at a frenetic rhythm, new research directions keep opening up and new applications in different fields provide plenty of food for thought. Given the versatility of these techniques, we are convinced that a breakthrough application to finance is not far away. \n\n\n", "meta": {"hexsha": "e487f7cc5b3c9dcfc69d944575e09ade30642e0d", "size": 9559, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Report/Chapters/9_Conclusions.tex", "max_stars_repo_name": "AmineAboussalah/Thesis", "max_stars_repo_head_hexsha": "1a3ae97023acff1ee5e2d197a446734117a6fb99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 80, "max_stars_repo_stars_event_min_datetime": "2016-06-13T15:20:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T23:47:13.000Z", "max_issues_repo_path": "Report/Chapters/9_Conclusions.tex", "max_issues_repo_name": "pnecchi/Thesis", "max_issues_repo_head_hexsha": "1a3ae97023acff1ee5e2d197a446734117a6fb99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Report/Chapters/9_Conclusions.tex", "max_forks_repo_name": "pnecchi/Thesis", "max_forks_repo_head_hexsha": "1a3ae97023acff1ee5e2d197a446734117a6fb99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34, "max_forks_repo_forks_event_min_datetime": "2017-05-15T07:51:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-21T21:48:53.000Z", "avg_line_length": 341.3928571429, "max_line_length": 1016, "alphanum_fraction": 0.8234124908, "num_tokens": 1800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.31535970452053885}}
{"text": "\\chapter{Results and Conclusions}\n\\label{chap:results}\n\nThis chapter outlines the results of the experiments performed using the methods outlined in the preceding chapter. For each section in this chapter an brief comparison of the similarity exhibited by each feature is given followed by lower dimensional representations of the feature space. Finally, plots examining the quality of the visualisation are given.\n\nEach of the experiments in this section used a single image from each patient in the full set of 360 images of both left, right and mediolateral oblique and craniocaudal views chosen at random. This meant was so as not to overrepresent a single patient for the real dataset. Therefore, 90 real mammograms in total were used for each experiment. The set of phantom mammograms used in this project consisted of 60 images but were divided into 6 groups corresponding to only a single ``case\". Because of this limitation a single breast phantom from each case was selected at random to be included in the data used for the experiments, bringing the total number of images used in all experiments to 96.\n\nFeatures extracted from both sets of images are compared using a two sample Kolmogorov-Smirnov (KS) test and are reported in the relevant section. The three dimensionality reduction algorithms were tested with each of the different feature sets and visualisations of the feature space in both 2 and 3 dimensions are shown for each.\n\nTwo different kinds of quality measure derived from the co-ranking matrix were computed for each of the visualisations shown in this section. The quality metrics used were trustworthiness \\& continuity and the local continuity meta-criteria up to a neighbourhood of size $k=50$.\n\n\\section{Blob features} \nThe results for the two sample KS test between the real and synthetic datasets for blob features detected over 10 scales are shown in table \\ref{table:blob_features_ks}. An explanation of what each type of feature means can be found in section \\ref{subsubsec:implementation-blob-features}. 2D projections of the blob feature space as produced by t-SNE, Isomap and locally linear embedding are shown in figures \\ref{fig:blob_SNE_mapping}, \\ref{fig:blob_iso_mapping}, and \\ref{fig:blob_LLE_mapping} respectively. \n\nIn each of the figures the real mammograms are shown as coloured dots and the breast phantoms are shown as coloured triangles. The labels corresponding to the colours used in each of the visualisations are the image's BIRADS class (in the case of real mammograms) or the volumetric breast density (VBD) (in the case of breast phantoms).\n\nGenerally speaking the phantom mammograms are shown to be very different from the real mammograms features used. The size of blobs detected in the phantom mammograms are generally larger and contain far fewer small scale blobs when compared to real mammograms. This is reflected in the projections for this feature space. \n\nIn the t-SNE projections it can be seen that all of the phantom blobs, regardless of VBD, are grouped towards the bottom of the distribution which contains a relatively high proportion of BIRADS risk class 3 \\& 4 images. The projections produced by Isomap and LLE generally separate the breast phantoms for the original data more than with t-SNE. Several of the real mammograms with features that match those of the breast phantoms are also interspersed with the phantom mammograms. This can be seen best in the 2D projection produced by Isomap in figure \\ref{fig:blob_iso_mapping}. These real mammograms are ones which tend to have a higher number of larger blobs detected than real mammograms in general.\n\n\\begin{table}[H]\n\\label{table:blob_features_ks}\n\\centering\n\\primitiveinput{tables/blob_features_ks}\n\\caption{Comparison of the Kolmogorov-Smirnov test results for each feature generated from the radii of blobs detected in an image between real and phantom mammograms.}\n\\end{table}\n\nThe quality evaluation for each of the visualisations are shown in figures \\ref{fig:TC_2d_blobs}, \\ref{fig:TC_3d_blobs}, and \\ref{fig:LCMC_blobs}. The quality metrics shown in these figures suggest that the 2D visualisation produced by Isomap is the most trustworthy, but t-SNE has better continuity. In the case of the 3D projections Isomap provides a better visualisation with it topping both criteria. For both projections Isomap show better performance in terms of the LCMC, but is overtaken for larger values of $k$ in 2D projections by t-SNE and in 3D projections by LLE. \n\n\\clearpage\n\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.4\\textwidth]{figures/mappings/blob_SNE_mapping_2d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/mappings/blob_SNE_mapping_3d.png}}\n\t\\caption{2D \\& 3D projections of the blob feature space produced by the t-SNE algorithm with a learning rate of 200 and perplexity of 20.}\\label{fig:blob_SNE_mapping}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.4\\textwidth]{figures/mappings/blob_iso_mapping_2d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/mappings/blob_iso_mapping_3d.png}}\n\t\\caption{2D \\& 3D projections of the blob feature space  produced by the Isomap algorithm with 4 neighbours.}\\label{fig:blob_iso_mapping}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.4\\textwidth]{figures/mappings/blob_lle_mapping_2d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/mappings/blob_lle_mapping_3d.png}}\n\t\\caption{2D \\& 3D projections of the blob feature space produced by the LLE algorithm with 4 neighbours.}\\label{fig:blob_LLE_mapping}\n\\end{figure}\n\\clearpage\n\n\\clearpage\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/blob_trustworthiness_2d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/blob_continuity_2d.png}}\n\t\\caption{Trustworthiness (left) and continuity (right) of the 2D projections produced from blob features.}\\label{fig:TC_2d_blobs}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/blob_trustworthiness_3d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/blob_continuity_3d.png}}\n\t\\caption{Trustworthiness (left) and continuity (right) of the 3D projections produced from blob features.}\\label{fig:TC_3d_blobs}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/blob_lcmc_2d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/blob_lcmc_3d.png}}\n\t\\caption{LCMC of both the 2D projection (left) and 3D projection (right) of the feature space for blobs.}\\label{fig:LCMC_blobs}\n\\end{figure}\n\\clearpage\n\n\\subsection{Line features}\nResults for the KS two sample test between the two feature spaces can be seen in table \\ref{table:line_features_ks}. Again, as with blobs, the distributions for real and synthetic mammograms are not in particularly good agreement according to the test. 2D and 3D projections for the line feature space for each of the three different dimensionality reduction algorithms are shown in figures \\ref{fig:line_SNE_mapping}, \\ref{fig:line_iso_mapping}, and \\ref{fig:line_LLE_mapping} respectively.\n \nNote that in these results the value of the min area feature was removed. When using the min area feature all projections would produce two clusters. One smaller cluster would be created containing which contained blobs where the min area was much larger than the rest of the dataset. This is most likely caused by a thresholding issue causing some unwanted smaller lines to be retained for some of the images.\n\n\\begin{table}[H]\n\\label{table:line_features_ks}\n\\centering\n\\primitiveinput{tables/line_features_ks}\n\\caption{Comparison of the Kolmogorov-Smirnov test results for each feature generated from the area of lines detected in an image between real and phantom mammograms.}\n\\end{table}\n\nThe t-SNE projection shows that there is a general transition from images which contain a high mean area of linear structure on the bottom right towards images which have a lower mean area in the top left. In terms of BIRADS risk it can be seen that very low and very high risk classes are grouped towards the bottom right, reflecting that less liner structure is detected using the orientated bins method in low risk classes (because there's very little dense structure present) and high risk classes (because dense areas are mostly large, homogenous blobs not linear structure). As can be clearly seen from the visualisation the synthetic images are grouped towards the lower end reflecting the smaller size of the linear structures detected. The 3D version produced by t-SNE produced a far worse projection with less visible structure.\n\nThe projections produced by Isomap produce more clearly show the synthetics begin grouped in with the very low/high risk blobs towards the left of the mapping. For LLE the majority of the blobs are pushed away from the main body of the mapping and closer to some of the outliers of the real mammograms.\n\nExamination of the three quality criteria show that Isomap produces better projections across both the 2D and 2D visualisations. t-SNE produced a 2D mapping which was comparable to Isomap in terms of trustworthiness and continuity, and LCMC. However in the case of the 3D case this was radically worse over all measures.\n\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.4\\textwidth]{figures/mappings/line_SNE_mapping_2d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/mappings/line_SNE_mapping_3d.png}}\n\t\\caption{2D \\& 3D projections of the line feature space produced by the t-SNE algorithm with a learning rate of 200 and perplexity of 20.}\\label{fig:line_SNE_mapping}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.4\\textwidth]{figures/mappings/line_iso_mapping_2d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/mappings/line_iso_mapping_3d.png}}\n\t\\caption{2D \\& 3D projections of the line feature space  produced by the Isomap algorithm with 4 neighbours.}\\label{fig:line_iso_mapping}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.4\\textwidth]{figures/mappings/line_lle_mapping_2d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/mappings/line_lle_mapping_3d.png}}\n\t\\caption{2D \\& 3D projections of the line feature space produced by the LLE algorithm with 4 neighbours.}\\label{fig:line_LLE_mapping}\n\\end{figure}\n\\clearpage\n\n\\clearpage\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/line_trustworthiness_2d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/line_continuity_2d.png}}\n\t\\caption{Trustworthiness (left) and continuity (right) of the 2D projections produced from line features.}\\label{fig:TC_2d_lines}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/line_trustworthiness_3d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/line_continuity_3d.png}}\n\t\\caption{Trustworthiness (left) and continuity (right) of the 3D projections produced from line features.}\\label{fig:TC_3d_lines}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/line_lcmc_2d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/line_lcmc_3d.png}}\n\t\\caption{LCMC of both the 2D projection (left) and 3D projection (right) of the feature space for lines.}\\label{fig:LCMC_lines}\n\\end{figure}\n\\clearpage\n\n\n\\begin{figure}[H]\n\t\\label{fig:mammogram-histogram}\n\t\\centering\n\t\\includegraphics[width=0.8\\textwidth]{Images/inverted_hist.png}\t\n\t\\caption{Comparison of the histogram of a real mammogram (blue) against a synthetic mammogram (green). The distribution of intensities are radically different from one another.}\n\\end{figure}\n\n\\subsection{Intensity \\& Texture Features}\n\\label{subsec:results-texture}\nIntensity and texture features showed the lowest similarity between the real and phantom datasets. As can be seen in figure \\ref{fig:mammogram-histogram} the intensity distribution of the phantom mammograms are nothing like a real mammogram. Because of this difference the results show that the they are clearly in different spaces. The results of the KS two sample test showed that the two distributions generated for both intensity and texture features are completely different. The results of the two sample Kolmogorov-Smirnov test are included in appendix \\ref{appendix:ks-test} because the number of features for blobs is based on the number of scales used leading to the a large number (up to 100) of entries. \n\nThe feature spaces presented in this section were generated by taking ROIs defined by the blob and line features detected from each of the mammograms by computing intensity and texture features from each image patch. Because blobs are detected across a range of scales the average value for each scale is used leading to a feature space of size $nk$ where $n$ is the number of features and $k$ is the number of scales (e.g. for texture: $n = 4$ and $k = 10$ so it has $40$ features). \n\nThe results of performing dimensionality reduction on both of these feature spaces is that in all almost all cases the synthetic mammograms are separated from the real mammograms into an isolated cluster on their own. This is because the values for both types of feature are on average much higher for the breast phantoms than the real mammograms.\n\nFor features derived from patches defined by blobs it can be seen that between the real mammograms there is a trend visible in both intensity and textural features which causes some transition between high to low risk. This is particularly visible for intensity features in the 2D plot produced by t-SNE shown in figure \\ref{fig:intensity_SNE_mapping} and in the 2D plot for Isomap shown in figure \\ref{fig:texture_iso_mapping} for texture features. For both intensity and texture feature LLE was shown to produce two clear clusters. One which contains the synthetics and one which contains the real mammograms. LLE still shows some variation between real in a similar way to what is seen in the projections produced by Isomap and LLE, but the resulting visualisation shows a much clear division.\n\nIn the case of intensity features this transition is caused by a higher detection of blobs which are of generally higher intensity. For texture features the trend is explained by a transition for blobs with low contrast and dissimilarity and high homogeneity and energy corresponding to high risk blobs transitioning through to low risk blobs where the reverse is true.\n\nIntensity features derived from lines do show a degree of separation between high and low risk mammograms. High risk mammograms typically have a higher average intensity. This is most clearly seen in the 2D visualisation produced by t-SNE in \\ref{fig:intensity_SNE_mapping_lines}. On the other hand the texture features do not appear to show any meaningful relationship between risk classes. LLE shows results that are also very similar to what is seen in blob features and the reasons behind this splitting are much the same.\n\nThe quality measures for intensity features derived from blobs show that these visualisations are generally less faithful in comparison to shape based features. Isomap is again a winner here with it producing better visualisations across all measures. Both t-SNE and LLE generally performed much worse than Isomap. The embedding by texture features are much more faithful. The 2D projections show a close call between Isomap and t-SNE. For 3D projections t-SNE is the clear loser, being dramatically worse compared with t-SNE and Isomap.\n\nQuality measures taken from the visualisations for intensity from lines show that the mapping produced by Isomap is better for projections in both two and three dimensions, but that t-SNE is at least comparable to Isomap in 2D. The results for texture features derived from lines show that the t-SNE performance of t-SNE is better for 2D. In the three dimensions Isomap is again a clear winner.\n\n%------------------------------------------------------------------------------------\n% Blob intensity and texture features\n%------------------------------------------------------------------------------------\n\n\n\\clearpage\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.4\\textwidth]{figures/mappings/intensity_SNE_mapping_2d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/mappings/intensity_SNE_mapping_3d.png}}\n\t\\caption{2D \\& 3D projections of the intensity feature space produced by the t-SNE algorithm with a learning rate of 200 and perplexity of 20.}\\label{fig:intensity_SNE_mapping}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.4\\textwidth]{figures/mappings/intensity_iso_mapping_2d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/mappings/intensity_iso_mapping_3d.png}}\n\t\\caption{2D \\& 3D projections of the intensity feature space generated from blobs produced by the Isomap algorithm with 4 neighbours.}\\label{fig:intensity_iso_mapping}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.4\\textwidth]{figures/mappings/intensity_lle_mapping_2d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/mappings/intensity_lle_mapping_3d.png}}\n\t\\caption{2D \\& 3D projections of the intensity feature space generated from blobs produced by the LLE algorithm with 4 neighbours.}\\label{fig:intensity_LLE_mapping}\n\\end{figure}\n\\clearpage\n\n% Quality for blob intensity features\n%------------------------------------------------------------------------------------\n\\clearpage\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/intensity_trustworthiness_2d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/intensity_continuity_2d.png}}\n\t\\caption{Trustworthiness (left) and continuity (right) of the 2D projections produced from intensity features from blobs.}\\label{fig:TC_2d_intensity}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/intensity_trustworthiness_3d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/intensity_continuity_3d.png}}\n\t\\caption{Trustworthiness (left) and continuity (right) of the 3D projections produced from intensity features from blobs.}\\label{fig:TC_3d_intensity}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/intensity_lcmc_2d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/intensity_lcmc_3d.png}}\n\t\\caption{LCMC of both the 2D projection (left) and 3D projection (right) of the feature space for intensity from blobs.}\\label{fig:LCMC_intensity}\n\\end{figure}\n\\clearpage\n\n\\clearpage\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.4\\textwidth]{figures/mappings/texture_SNE_mapping_2d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/mappings/texture_SNE_mapping_3d.png}}\n\t\\caption{2D \\& 3D projections of the texture feature space generated from blobs generated from blobs produced by the t-SNE algorithm with a learning rate of 200 and perplexity of 20.}\\label{fig:texture_SNE_mapping}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.4\\textwidth]{figures/mappings/texture_iso_mapping_2d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/mappings/texture_iso_mapping_3d.png}}\n\t\\caption{2D \\& 3D projections of the texture feature space generated from blobs produced by the Isomap algorithm with 4 neighbours.}\\label{fig:texture_iso_mapping}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.4\\textwidth]{figures/mappings/texture_lle_mapping_2d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/mappings/texture_lle_mapping_3d.png}}\n\t\\caption{2D \\& 3D projections of the texture feature space generated from blobs produced by the LLE algorithm with 4 neighbours.}\\label{fig:texture_LLE_mapping}\n\\end{figure}\n\\clearpage\n\n% Quality for blob texture features\n%------------------------------------------------------------------------------------\n\n\\clearpage\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/texture_trustworthiness_2d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/texture_continuity_2d.png}}\n\t\\caption{Trustworthiness (left) and continuity (right) of the 2D projections produced from texture features from blobs.}\\label{fig:TC_2d_texture}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/texture_trustworthiness_3d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/texture_continuity_3d.png}}\n\t\\caption{Trustworthiness (left) and continuity (right) of the 3D projections produced from texture features from blobs.}\\label{fig:TC_3d_texture}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/texture_lcmc_2d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/texture_lcmc_3d.png}}\n\t\\caption{LCMC of both the 2D projection (left) and 3D projection (right) of the feature space for texture.}\\label{fig:LCMC_texture}\n\\end{figure}\n\\clearpage\n\n%------------------------------------------------------------------------------------\n% Line intensity and texture features\n%------------------------------------------------------------------------------------\n\n\\clearpage\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.4\\textwidth]{figures/mappings/line_intensity_SNE_mapping_2d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/mappings/line_intensity_SNE_mapping_3d.png}}\n\t\\caption{2D \\& 3D projections of the intensity feature space for lines produced by the t-SNE algorithm with a learning rate of 200 and perplexity of 20.}\\label{fig:intensity_SNE_mapping_lines}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.4\\textwidth]{figures/mappings/line_intensity_iso_mapping_2d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/mappings/line_intensity_iso_mapping_3d.png}}\n\t\\caption{2D \\& 3D projections of the intensity feature space generated from lines produced by the Isomap algorithm with 4 neighbours.}\\label{fig:intensity_iso_mapping_lines}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.4\\textwidth]{figures/mappings/line_intensity_lle_mapping_2d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/mappings/line_intensity_lle_mapping_3d.png}}\n\t\\caption{2D \\& 3D projections of the intensity feature space for lines generated from blobs produced by the LLE algorithm with 4 neighbours.}\\label{fig:intensity_LLE_mapping_lines}\n\\end{figure}\n\\clearpage\n\n\n% Quality for line intensity features\n%------------------------------------------------------------------------------------\n\\clearpage\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/line_intensity_trustworthiness_2d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/line_intensity_continuity_2d.png}}\n\t\\caption{Trustworthiness (left) and continuity (right) of the 2D projections produced from intensity features from lines.}\\label{fig:TC_2d_intensity}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/line_intensity_trustworthiness_3d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/line_intensity_continuity_3d.png}}\n\t\\caption{Trustworthiness (left) and continuity (right) of the 3D projections produced from intensity features from lines.}\\label{fig:TC_3d_intensity}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/line_intensity_lcmc_2d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/line_intensity_lcmc_3d.png}}\n\t\\caption{LCMC of both the 2D projection (left) and 3D projection (right) of the feature space for intensity from lines.}\\label{fig:LCMC_intensity}\n\\end{figure}\n\\clearpage\n\n\n\\clearpage\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.4\\textwidth]{figures/mappings/lines_texture_SNE_mapping_2d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/mappings/lines_texture_SNE_mapping_3d.png}}\n\t\\caption{2D \\& 3D projections of the texture feature space generated generated from lines produced by the t-SNE algorithm with a learning rate of 200 and perplexity of 20.}\\label{fig:texture_SNE_mapping_lines}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.4\\textwidth]{figures/mappings/lines_texture_iso_mapping_2d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/mappings/lines_texture_iso_mapping_3d.png}}\n\t\\caption{2D \\& 3D projections of the texture feature space generated from lines produced by the Isomap algorithm with 4 neighbours.}\\label{fig:texture_iso_mapping_lines}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.4\\textwidth]{figures/mappings/lines_texture_lle_mapping_2d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/mappings/lines_texture_lle_mapping_3d.png}}\n\t\\caption{2D \\& 3D projections of the texture feature space generated from lines produced by the LLE algorithm with 4 neighbours.}\\label{fig:texture_LLE_mapping_lines}\n\\end{figure}\n\\clearpage\n\n% Quality for line texture features\n%------------------------------------------------------------------------------------\n\n\\clearpage\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/lines_texture_trustworthiness_2d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/lines_texture_continuity_2d.png}}\n\t\\caption{Trustworthiness (left) and continuity (right) of the 2D projections produced from texture features from lines.}\\label{fig:TC_2d_texture}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/lines_texture_trustworthiness_3d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/lines_texture_continuity_3d.png}}\n\t\\caption{Trustworthiness (left) and continuity (right) of the 3D projections produced from texture features from lines.}\\label{fig:TC_3d_texture}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/lines_texture_lcmc_2d.png}}\n\t\\subfigure{\\includegraphics[width=0.49\\textwidth]{figures/quality_measures/lines_texture_lcmc_3d.png}}\n\t\\caption{LCMC of both the 2D projection (left) and 3D projection (right) of the feature space from lines for texture.}\\label{fig:LCMC_texture}\n\\end{figure}\n\\clearpage\n\n\n\\section{Conclusions}\nIn summary, it can be concluded that the synthetic mammograms used as part of this experiment are not significantly related to real mammograms in terms of the features derived during this study. The synthetic mammograms appear to be closest to real mammograms in terms of the shape of the structures present in the image. The best results from this experiment were derived from the feature space of multi-scale blobs. Line features also seemed to positively show the the real and synthetic mammograms are at least in the same space in terms of shape. However, texture and intensity features derived from either of the features clearly show that the two datasets are not in the same intensity space. The two sample KS test confirms that the features created from both datasets are statistically not drawn from the same distribution and therefore we must conclude that they are, for all features presented here, effectively different.\n\nThis conclusion roughly correlates with the limitations discussed by the authors of the synthetic data \\cite{bakic2002mammogram1, bakic2002mammogram2, bakic2003mammogram3}. They state that the synthetic mammograms are closest to real mammograms in terms of shape but are not so close in terms of intensity and texture. In the experiments with shape features presented here the major difference between the real and synthetic mammograms was caused by a lack of small scale structure being detected in the synthetic mammograms. This causes them to be grouped in with mammograms which are deemed to be of higher risk, regardless of their effective risk, because of the lack of small blob counts detected. The same can be said for line features where the number and size of lines is generally smaller, regardless of the risk.\n\nThe quality evaluation of the visualisations produced suggests that Isomap produces visualisations which best capture the local neighbourhood structure of mappings. t-SNE appears to often show similar levels of faithfulness in compared to Isomap in two dimensions, but was shown to be much worse for three dimensions.\n\n\n", "meta": {"hexsha": "a11892cadf241e05fa8934e9a2b48fb024c7d73a", "size": 29520, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "documents/final-report/Chapter3/chapter3.tex", "max_stars_repo_name": "samueljackson92/major-project", "max_stars_repo_head_hexsha": "5d82b875944fcf1f001f9beb5e5419ba60be3bf1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2015-01-26T16:23:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-17T00:57:42.000Z", "max_issues_repo_path": "documents/final-report/Chapter3/chapter3.tex", "max_issues_repo_name": "samueljackson92/major-project", "max_issues_repo_head_hexsha": "5d82b875944fcf1f001f9beb5e5419ba60be3bf1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 64, "max_issues_repo_issues_event_min_datetime": "2015-02-05T06:34:56.000Z", "max_issues_repo_issues_event_max_datetime": "2015-05-03T15:46:49.000Z", "max_forks_repo_path": "documents/final-report/Chapter3/chapter3.tex", "max_forks_repo_name": "samueljackson92/major-project", "max_forks_repo_head_hexsha": "5d82b875944fcf1f001f9beb5e5419ba60be3bf1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 77.6842105263, "max_line_length": 932, "alphanum_fraction": 0.7932588076, "num_tokens": 7391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.31535970452053885}}
{"text": "\\vsssub\n\\subsubsection{Track output post-processor} \\label{sec:ww3trck}\n\\vsssub\n\n\\proddefH{ww3\\_trck}{w3trck}{ww3\\_trck.ftn}\n\\proddeff{Input}{ww3\\_trck.inp}{Traditional configuration file.}{10} (App.~\\ref{sec:config191})\n\\proddefa{track\\_o.ww3}{Raw track output data.}{11}\n\\proddeff{Output}{standard out}{Formatted output of program.}{6}\n\\proddefa{track.ww3}{Formatted data file.}{51}\n\n\\vspace{\\baselineskip} \n\\noindent\nThis post-processor will convert the raw track output data to an integer\ncompressed formatted file. The file contains the following header records :\n\n\\begin{list}{$\\bullet$}{\\itemsep 0mm \\parsep 0mm}\n\\item File identifier (character string of length 34).\n\\item Number of frequencies and directions, first direction and directional\n      increment (radians, oceanographic convention).\n\\item Radian frequencies of each frequency bin.\n\\item Corresponding directional bin size times frequency bin size to obtain\n      discrete energy per bin.\n\\end{list}\n\n\\noindent\nFor each output point varying in time and position, the following records are printed :\n\\begin{list}{$\\bullet$}{\\itemsep 0mm \\parsep 0mm}\n\\item Date and time in {\\tt yyyymmdd hhmmss} format, longitude and latitude in\n      degrees, and a status identifier `{\\F ice}', `{\\F lnd}' or `{\\F\n      sea}'. The following two records are written only for sea points.\n\\item Water depth in meters, current and wind u and v components in meters per\n      second, friction velocity in meters per second, air-sea temperature\n      difference in degrees centigrade and scale factor for spectrum.\n\\item The entire spectrum in integer packed format (can be read using free\n      format).\n\\end{list}\n\n\\pb\n", "meta": {"hexsha": "2c811505b558021b1cdaa56e5b5bead46d463884", "size": 1669, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "WW3/manual/run/ww3_trck.tex", "max_stars_repo_name": "minsukji/ci-debug", "max_stars_repo_head_hexsha": "3e8bbbe6652b702b61d2896612f6aa8e4aa6c803", "max_stars_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WW3/manual/run/ww3_trck.tex", "max_issues_repo_name": "minsukji/ci-debug", "max_issues_repo_head_hexsha": "3e8bbbe6652b702b61d2896612f6aa8e4aa6c803", "max_issues_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-05-31T15:49:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-04T14:17:45.000Z", "max_forks_repo_path": "WW3/manual/run/ww3_trck.tex", "max_forks_repo_name": "minsukji/ci-debug", "max_forks_repo_head_hexsha": "3e8bbbe6652b702b61d2896612f6aa8e4aa6c803", "max_forks_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-01T09:29:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T09:29:46.000Z", "avg_line_length": 42.7948717949, "max_line_length": 95, "alphanum_fraction": 0.7555422409, "num_tokens": 447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.3153133738234881}}
{"text": "\\begin{savequote}[8cm]\nTwo MCs can't occupy the same space at the same time,\nit's against the laws of physics.\n\\qauthor{--- Lauryn Hill, \\textit{Zealots}}\n\\end{savequote}\n\n\\chapter{\\label{ch:3-methods}Theory and methodology}\n\n\\minitoc\n\n%% Books:\n\n% For a really nice explanation of solid state QM basics - bloch waves, an electron in a crystal potential etc, see Lundstrom \"fundamentals of carrier transport\"\n\n\\section{Introduction} \n\nIn this chapter I present the theory and methodology that underlies the work in this thesis. The chapter starts with an introduction to quantum chemistry and Density Functional Theory (DFT); first I introduce the theoretical concepts, then I provide some details about how DFT is implemented in practice. Later in the chapter I outline how we can use DFT energies combined with a series of post-processing steps to predict defect formation energies and charge transition levels. The chapter ends with an introduction to the theory of lattice dynamics and how this theory is used to calculate the vibrational properties of a material. \n\n\\section{Quantum chemistry}\n\n\\subsection{The Schr\\\"{o}dinger equation}\n\nA fundamental postulate of quantum mechanics is that for any physical system there is an associated wavefunction that contains all of the system information.\nThe Schr\\\"{o}dinger equation describes the wavefunction of a quantum mechanical system.  Once the Schr\\\"{o}dinger equation is solved, and a wavefunction is found, all the physical properties of that system follow. \nThe general form of the many-body Schr\\\"{o}dinger equation is:\\autocite{Kaxiras2007}\n\\begin{equation}\n\\hat{H}\\Psi(\\{\\textbf{R}_I;\\textbf{r}_i\\}) = E\\Psi(\\{\\textbf{R}_I;\\textbf{r}_i\\}),\n\\end{equation}\nwhere $\\Psi(\\{\\textbf{R}_I;\\textbf{r}_i\\})$ is the many-body wavefunction that describes the state of the system with ions in positions $\\{\\textbf{R}_I\\}$ and electrons described by the variables $\\{\\textbf{r}_i\\}$.\nThe Hamiltonian $\\hat{H}$ is an operator corresponding to the sum of the kinetic and potential energies for all particles in a system. \n\nTo take a simple example system, the time-independent non-relativistic Hamiltonian for a single hydrogen atom is:\n\\begin{equation} \\label{singleparticle}\n\\hat{H} = -\\frac{\\hbar^2}{2M_1}\\nabla_{\\textbf{R}_1}^2-\\frac{\\hbar^2}{2m_e}\\nabla_{\\textbf{r}_1}^2-\\frac{e^2}{\\lvert\\textbf{R}_1-\\textbf{r}_1\\rvert},\n\\end{equation}\nwhere the first term is the kinetic energy of the hydrogen ion with mass $M_1$ and the second term is the kinetic energy of the electron with mass $m_e$. The third term is the Coulomb potential energy due to the interaction between the ion at position $R_1$ and electron at position $r_1$. \n\nFor systems with multiple ions and electrons, the Hamiltonian is given by:\\autocite{Kaxiras2007}\n\\begin{equation} \\label{manybodyH}\n\\hat{H} = -\\sum_{I}\\frac{\\hbar^2}{2M_I}\\nabla_{\\textbf{R}_I}^2-\\sum_{i}\\frac{\\hbar^2}{2m_e}\\nabla_{\\textbf{r}_i}^2 +\\sum_{i<j}\\frac{e^2}{\\lvert\\textbf{r}_i-\\textbf{r}_j\\rvert}-\\sum_{i}\\sum_{I}\\frac{Z_Ie^2}{\\lvert\\textbf{R}_I-\\textbf{r}_i\\rvert}+\\sum_{I<J}\\frac{Z_IZ_Je^2}{\\lvert\\textbf{R}_I-\\textbf{R}_J\\rvert}.\n\\end{equation}\nThe first two terms correspond to the kinetic energy of the ions and electrons, respectively. The third term describes the repulsive electrostatic interactions between two electrons with charge $e$ and the fifth term describes the repulsive interactions between ions of charge $Z_Ie$ and $Z_Je$. The fourth term describes the attractive electrostatic interactions between an electron and positively charged ion. The following expression will be used to simplify the latter term:\n\\begin{equation}\nv_\\textrm{ext}(\\textbf{r}) = -\\sum_I\\frac{Z_Ie^2}{\\lvert\\textbf{R}_I-\\textbf{r}\\rvert},\n\\end{equation}\nwhere $v_\\textrm{ext}$ is the external potential felt by a single electron. \n\nThe Born-Oppenheimer approximation can be used to simplify Equation \\ref{manybodyH}.\\autocite{Born1927} This approximation assumes that, because the ions are significantly heavier than the electrons, the ions are moving slowly in space and the electrons can respond instantaneously to any ionic motion. The ions are treated as fixed points and the ion kinetic energy term in Equation \\ref{manybodyH} is zero. Only the electronic sub-system is treated quantum mechanically and so we can neglect the ion-ion term in Equation \\ref{manybodyH} as it is independent of the electronic degrees of freedom.\nUnder the Born-Oppenheimer approximation the many-body Hamiltonian becomes:\\autocite{Kaxiras2007}\n\\begin{equation}\n\\hat{H} = -\\sum_{i}\\frac{\\hbar^2}{2m_e}\\nabla_{\\textbf{r}_i}^2 +\\sum_{i<j}\\frac{e^2}{\\lvert\\textbf{r}_i-\\textbf{r}_j\\rvert}+\\sum_{i}v_\\textrm{ext}(\\textbf{r}_i).\n\\end{equation}\n\n\n\n\\subsection{The Hartree and Hartree-Fock approximations}\n\nFor a simple system, such as the particle in a box system or hydrogen atom, the Schr\\\"{o}dinger equation can be solved exactly. Unfortunately it is not possible to solve the Schr\\\"{o}dinger equation exactly for more complex systems, where there are multiple electrons interacting with each other (N-body or many-body systems). \nHartree-Fock methods and Kohn-Sham DFT provide ways to obtain an approximate solution to the Schr\\\"{o}dinger equation for systems of interest. They do this by mapping the interacting problem onto a non-interacting problem with an effective potential. In doing so, the dimensionality of the problem is greatly reduced. Instead of solving one N-dimensional computationally intractable problem, N one-dimensional problems are solved (Figure \\ref{decouple}). These methods provide a compromise between accuracy and computational efficiency.\n\n\\begin{figure}[h]\n\\centering\n  \\includegraphics[width=1.0\\columnwidth]{figures/ch3/decouple.png}\n  \\caption[Interacting and non-interacting particle systems]{Schematic outlining the equivalence between a system of interacting particles and a system of non-interacting particles in an effective potential $v_{ee}$. The underlying idea is that an interaction can be replaced by the equivalent potential. This maps the interacting 3N-dimensional problem onto N 3-dimensional problems. For the non-interacting case $\\phi_i$ is used to denote a single particle wavefunction. $v_{\\textrm{ext}}$ describes the interaction between an electron and the surrounding ions.} %update so q1q2 in couple term in picture\n  \\label{decouple}\n\\end{figure}  %%% NEED TO ADJUST FIGURE\n\nThe Hartree approximation assumes that the many-body wavefunction $\\Psi^{\\textrm{H}}(\\{\\textbf{r}_i\\})$ is simply a product of independent single electron states $\\phi_i(\\textbf{r}_i)$:\\autocite{Hartree1928}\n\\begin{equation}\n\\Psi^{\\textrm{H}}(\\{\\textbf{r}_i\\}) = \\phi_1(\\textbf{r}_1)\\phi_2(\\textbf{r}_2)\\ldots\\phi_n(\\textbf{r}_n).\n\\end{equation}\n\nAs each state is independent, the system Hamiltonian $\\hat{H}$ becomes the sum over the Hamiltonian for each single electron state $\\hat{h}_i$:\n\\begin{equation}\n\\hat{H} = \\sum_i\\hat{h}_i,\n\\end{equation}\n\nUnder the Hartree approximation, $\\hat{h}_i$ is given by:\n\\begin{align}\n\\hat{h}_i &= -\\frac{\\hbar^2}{2m_e}\\nabla_{\\textbf{r}}^2 + v_\\mathrm{ext}(\\textbf{r}) + v_i^\\textrm{H}(\\textbf{r}) \\\\\nv_i^\\textrm{H}(\\textbf{r}) &= e^2\\sum_{j\\neq i} \\int\\frac{\\rho_j(\\textbf{r}')}{\\lvert\\textbf{r}-\\textbf{r}'\\rvert}\\textrm{d}\\textbf{r}' \\\\ \\label{singleparticledensity}\n\\rho_j &= \\lvert\\phi_j\\rvert^2.\n\\end{align}\n\nThe $v_i^\\textrm{H}$ term corresponds to the average electrostatic repulsion between electrons and is called the Hartree potential. A self-consistent field method (discussed further in Section \\ref{SCFsubsection}) is needed to solve the time-independent Schr\\\"{o}dinger equation $\\hat{h}_i\\phi_i=\\epsilon_i\\phi_i$ for $\\phi_i$, as the Hartree potential depends on the charge density $\\rho_j$, which itself depends on the single-particle wavefunction $\\phi_j$. \n\n% INCLUDE HERE THE SELF INTERACTION ERROR?\n%Hartree-Fock (HF) methods introduce the concept of fictitious non-interacting one-electron orbitals $\\phi$ as a way of solving the Schr\\\"{o}dinger equation. The one-electron orbitals are combined using a Slater determinant to produce the HF many-body wavefunction.\\autocite{Burke2007} \n\nThe Pauli Exclusion Principle states that the many-body wavefunction of an electron (or any particle with a half-integer spin quantum number) must be antisymmetric with respect to exchange - i.e. the wavefunction must change sign if any two electrons are exchanged.\\autocite{Kaxiras2007} The Hartree many-body wavefunction $\\Psi^{\\textrm{H}}$ does not obey this rule. However the single electron states $\\phi_i$ can be combined to form a Slater determinant,\\autocite{Slater1929} which is antisymmetrical with respect to exchange:\n\\begin{equation} \\label{slaterdet}\n\\Psi^{\\textrm{HF}}(\\{\\textbf{r}_i\\}) = \\frac{1}{\\sqrt{N!}}\n\\begin{vmatrix}\n\\phi_1(\\textbf{r}_1)&\\phi_1(\\textbf{r}_2)&\\ldots&\\phi_1(\\textbf{r}_n) \\\\\n\\phi_2(\\textbf{r}_1)&\\phi_2(\\textbf{r}_2)&\\ldots&\\phi_2(\\textbf{r}_n) \\\\\n\\cdot & \\cdot & & \\cdot \\\\\n\\cdot & \\cdot & & \\cdot \\\\\n\\cdot & \\cdot & & \\cdot \\\\\n\\phi_n(\\textbf{r}_1)&\\phi_n(\\textbf{r}_2)&\\ldots&\\phi_n(\\textbf{r}_n) \\\\\n\\end{vmatrix}.\n\\end{equation}\n\nForming a many-body wavefunction $\\Psi^{\\textrm{HF}}(\\{\\textbf{r}_i\\})$ from the Slater determinant of single particle states is the Hartree-Fock approximation. To solve the Schr\\\"{o}dinger equation and find the ground state (lowest energy) solution for $\\Psi^{\\textrm{HF}}$ a variational method can be used.\\autocite{Fock1930} In addition, the energy of each single particle state $\\epsilon_i$ is minimised with respect to $\\phi_i$, and $\\{\\phi_i\\}$ form an orthonormal basis. Applying these principles results in the Hartree-Fock equations:\\autocite{Fock1930}\n\\begin{align}\n\\bigg[-\\frac{\\hbar^2}{2m_i}\\nabla_{\\textbf{r}}^2  + v_\\mathrm{ext}(\\textbf{r}) &+ v_i^\\textrm{H}\\bigg]\\phi_i(\\mathbf{r})-v_i^\\textrm{X}(\\mathbf{r})\\phi_j(\\mathbf{r}) = \\epsilon_i\\phi_i(\\mathbf{r}), \\\\\nv_i^\\textrm{X}(\\mathbf{r}) &= e^2\\sum_{j\\neq i}\\int \\frac{\\phi_j^*(\\mathbf{r}')\\phi_i(\\mathbf{r}')}{\\lvert\\mathbf{r}-\\mathbf{r}'\\rvert}\\textrm{d}\\mathbf{r}'.\n\\end{align}\n% http://nucleartalent.github.io/Course2ManyBodyMethods/doc/pub/hfock/html/hfock-bs.html\n\n$v_i^\\textrm{X}$ accounts for the spin exchange interaction between electrons, whereby two identical electrons (i.e. electrons with the same spin and momentum) cannot occupy the same space at the same time. This results in a repulsion between electrons with parallel spins.\n%IT CANCELS ERROR FROM THE SELF INTERACTION OF THE HARTREE TERM\n\nHartree-Fock methods build upon the classical mean-field approach of the Hartree approximation to include the quantum spin nature of electrons.\nHowever the Hartree-Fock approximation does not give an exact solution to the Schr\\\"{o}dinger equation as the true many body wavefunction is not formed from a simple Slater determinant. As a result, electron correlation -- the correlated motion of electrons with anti-parallel spins as a result of their mutual coulombic repulsion -- is ignored.\n% from http://newton.ex.ac.uk/research/qsystems/people/coomer/dft_intro.html\n\n\n\n\\section{Density Functional Theory: basic concepts} \\label{DFTtheory}\n\nDensity Functional Theory (DFT) is the most commonly used electronic structure method in condensed matter physics and quantum chemistry. The principle underlying DFT is that any ground state property of an interacting system can be determined by the electron density of a non-interacting system. We avoid specifying the form of the many-body wavefunction all together and no longer need to start with an approximation to the many-body wavefunction, as in the Hartree-Fock approach. Instead, the many-body effects of electron exchange and correlation are included as a functional of electron density.\n\nDFT can be used to predict material properties including electron density, total energy, equilibrium structure, vibrational frequencies, and properties relating to differences in total energy, such as defect formation energy or surface energy. \nAs DFT is a ground state theory we are not able to calculate properties relating to excited states and, without further calculations such as those outlined in Section \\ref{sec:latticedynamics}, results do not incorporate the effects of temperature. \n\nThe theoretical basis for DFT was established in 1964 through the work of Walter Kohn and Pierre Hohenberg.\\autocite{Hohenberg1964} This was further developed by Walter Kohn and Lu Jeu Sham to produce Kohn-Sham DFT.\\autocite{Kohn1965} However it was not until the late 1980's that approximations to the exchange-correlation functional were built so that DFT could be used in practice. \n\nThere are a growing number of codes that implement DFT. \nAlthough some codes aspire to a blackbox approach, with the user protected from the underlying mechanics of DFT, for most systems of interest an understanding of the underlying approximations and parameters used are required for reliable results.\n\nFinally, a note on the name. A function accepts one or more numbers as input and produces a number as output. Likewise, a functional accepts one or more \\textit{functions} as inputs, and produces a number as output. In DFT the functional is the electron density which is itself a function of space and time.\n\n\\subsection{The Hohenberg-Kohn theorems}\n\nThe 1964 Hohenberg-Kohn paper\\autocite{Hohenberg1964} contains two key results: (i) the ground state electron density uniquely determines the ground state electronic wave function and, following this, all properties of the system; (ii) the true density functional for the electronic energy assumes its minimum for the correct ground-state density.\\autocite{Scuseria05}\n\nThe potentials -- external ($v_\\mathrm{ext}$), coulomb ($v_i^H$) and exchange ($v_i^X$) -- in Hartree-Fock methods determine the properties of a system. Hohenberg and Kohn demonstrated that the electron density can be used to uniquely characterise the system and rather than solving the Schr\\\"{o}dinger equation for the wavefunction, we can solve it for the electron density.\n\nFirst, Hohenberg and Kohn proved that the electron density is uniquely defined for a given external potential (electron-ion interaction). Their proof uses \\textit{reductio ad adsurdum}; they first assume that two different external potentials can lead to the same density, and then show that this assumption leads to an impossible contradiction.\\autocite{Burke2007} \nSecond, we know that as the external potential is the only thing that differs from system to system, it is this which uniquely determines the system wavefunction. It follows that the electron density $\\rho(\\textbf{r})$ uniquely determines the system wavefunction and all derived properties, including the total energy $E$ of the system:\\autocite{Kaxiras2007}\n\\begin{align}\nE\\left[\\rho(\\textbf{r})\\right]&=\\int v_{\\textrm{ext}}(\\textbf{r})\\rho(\\textbf{r})d\\textbf{r}+T\\left[\\rho(\\textbf{r})\\right]+J\\left[\\rho(\\textbf{r})\\right]+E_{\\textrm{xc}}\\left[\\rho(\\textbf{r})\\right] \\\\\n&=\\int v_{\\textrm{ext}}(\\textbf{r})\\rho(\\textbf{r})d\\textbf{r}+F\\left[\\rho(\\textbf{r})\\right],   \n\\end{align}\nwhere $T\\left[\\rho\\right]$, $J\\left[\\rho\\right]$ and $E_\\textrm{xc}\\left[\\rho\\right]$ describe the kinetic, classical electrostatic and exchange-correlation energies respectively. \nFor a fixed number of electrons the functional $F\\left[\\rho(\\textbf{r})\\right]$ is universal, and the only thing that varies between systems is the external potential. The problem is that the exact form of this functional is unknown.\n\nIn addition to the above, Hohenberg and Kohn demonstrated that the energy functional $E\\left[\\rho(\\textbf{r})\\right]$ is minimised for the correct ground state density corresponding to $v_\\mathrm{ext}(\\textbf{r})$.\\autocite{Hohenberg1964}\n\n\\subsection{The Kohn-Sham formalism} \\label{KSformalismsubsection}\n\nThe Kohn-Sham (KS) formalism provides a practical way to apply the Hohenberg-Kohn theorem. The KS theorem shows that for any \\textit{interacting} system with ground state density $\\rho(\\textbf{\\textrm{r}})$ there exists a \\textit{non-interacting} system with the same ground-state $\\rho(\\textbf{\\textrm{r}})$. To find the ground state energy of the real interacting system, the occupation numbers of fictitious, non-interacting single electron orbitals can be optimised. This allows for a `divide and conquer' approach to the problem of specifying $F\\left[\\rho(\\textbf{r})\\right]$, as for the non-interacting system we can calculate some of the terms exactly.\n\nWe exploit the fact that the orbitals are non-interacting to build the many-body wavefunction $\\Psi(\\{\\textbf{r}_i\\})$ as a Slater determinant of single particle orbitals (as in Equation \\ref{slaterdet}). The functional $F\\left[\\rho(\\textbf{r})\\right]$ can then be expressed as:\\autocite{Kaxiras2007}\n\\begin{equation}\nF\\left[\\rho(\\textbf{r})\\right] = T\\left[\\rho(\\textbf{r})\\right] + \\frac{e^2}{2}\\int\\int\\frac{\\rho(\\textbf{r})\\rho(\\textbf{r}')}{\\lvert\\mathbf{r}-\\mathbf{r}'\\rvert}\\textrm{d}\\mathbf{r}\\textrm{d}\\mathbf{r}' + E_\\mathrm{xc}\\left[\\rho(\\textbf{r})\\right].\n\\end{equation}\nFor a non-interacting system we know how to calculate the kinetic energy $T\\left[\\rho(\\textbf{r})\\right]$. The second term is the Coulomb interaction and so by definition the remaining term, $E_{\\textrm{xc}}\\left[\\rho(\\textbf{r})\\right]$, accounts for exchange and correlation interactions.\nThrough a variational argument the single particle Kohn-Sham equations can also be derived:\\autocite{Kaxiras2007}\n\\begin{equation} \\label{KSequations}\n\\bigg[-\\frac{\\hbar^2}{2m_e}\\nabla_{\\textbf{r}}^2+v_{\\textrm{ext}}(\\textbf{r})+ {e^2}\\int\\frac{\\rho(\\textbf{r}')}{\\lvert\\mathbf{r}-\\mathbf{r}'\\rvert}\\textrm{d}\\mathbf{r}'+\\frac{\\delta E_{\\textrm{xc}}\\left[\\rho(\\textbf{r})\\right]}{\\delta \\left[\\rho(\\textbf{r})\\right] } \\bigg]\\phi_i(\\textbf{r})=\\epsilon_i\\phi_i(\\textbf{r}).\n\\end{equation} \nThe Coloumb and exchange-correlation terms are a function of electron density which is in turn a function of the single particle orbitals $\\phi_i(\\textbf{r})$ (see Equation \\ref{singleparticledensity}), and so a self-consistent iterative method can be used to find $\\phi_i(\\textbf{r})$. The non-interacting single particle orbitals that form the solution of Equation \\ref{KSequations} are the Kohn-Sham orbitals. These are not the `real' single electron orbitals, but the set of orbitals that reproduce the ground state density of the system. \n\nThe first key strength of Kohn-Sham DFT is that \\textit{in principle} the effects of electron exchange and correlation are fully accounted for. However in practice only approximations to the exchange-correlation functional can be made, leading to approximations for the electronic density, total energy and other system properties. This is discussed further in the following subsection.\nThe second key strength is that we are dealing with the electron density. This has a lower dimensionality than the many-body electron wavefunction (Figure \\ref{dimensions}) and allows for more efficient computation.\\autocite{Perdew2010,Kohn1999} \n\n\n\\begin{figure}[h]\n\\centering\n  \\includegraphics[width=0.8\\columnwidth]{figures/ch3/dimensions.png}\n  \\caption[Dimensionality of variational objects]{To solve the Schr\\\"{o}dinger equation we can use a variational object with lower dimensionality and higher computational efficiency, although this will come at the cost of accuracy. This schematic is based on a discussion in Walter Kohn's Nobel Prize lecture.\\autocite{Kohn1999}}\n  \\label{dimensions}\n\\end{figure}\n% Is this right? I don't understand how the two electron wavefunction scales (4^2) - it's discussed in the 14 easy lessons.\n\n\n\\section{DFT in practice}\n\n\\subsection{Exchange-correlation functionals}\n% explain here that Exc is defined by a difference in known energies, as is electron correlation\nTo use Kohn-Sham DFT we must approximate the exchange-correlation functional $E_{\\textrm{xc}}\\left[\\rho\\right]$, and there is a growing list of functionals at varying levels of complexity. John Perdew proposed `Jacob's Ladder' as a way to categorise these functionals (Figure \\ref{jladder}). As a general rule, more accurate functionals are constructed by including more parameters and variables.\n\n\\begin{figure}[h]\n\\centering\n  \\includegraphics[width=0.8\\columnwidth]{figures/ch3/jladder.png}\n  \\caption[Jacob's ladder of exchange-correlation functionals]{Jacob's ladder of exchange correlation functionals. On the right hand side are the various categories of exchange-correlation functionals and on the left hand side are the additional input variables included at each level of theory. As we move up the ladder the chemical accuracy increases, alongside computational expense.}\n  \\label{jladder}\n\\end{figure}\n\n\n\\textbf{Local Density Approximation} \n\nAt the lowest rung of the ladder is the local density approximation (LDA) where only one variable, the electron density for an infinitesimal 3-dimensional volume element, is used to calculate the exchange correlation energy:\\autocite{Henderson2008}\n\\begin{equation}\nE_{\\textrm{LDA,xc}} = \\int E_{\\textrm{HEG,xc}}\\left[\\rho\\left(\\textbf{r}\\right)\\right]\\textrm{d}\\mathbf{r} .\n\\end{equation}\nIt is assumed that the exchange-correlation energy density $E_{\\textrm{HEG,xc}}$ is equal to that of a homogeneous electron gas (HEG) with identical electron density $\\rho$. The exchange energy is calculated exactly:\\autocite{Henderson2008}\n\\begin{equation}\nE_{\\textrm{HEG,x}}\\left[\\rho\\left(\\textbf{r}\\right)\\right] = -\\frac{3}{4}\\left(\\frac{6}{\\pi}\\right)^{\\frac{1}{3}} \\rho^{\\frac{4}{3}}\\left(\\textbf{r}\\right),\n\\end{equation}\nand the correlation energy is calculated numerically by fitting to many-body quantum Monte Carlo calculations for a homogeneous electron gas.\\autocite{Ceperley1980} %Ceperley and Alder\nExchange and correlation effects are inherently non-local, and so we should not expect the LDA to give accurate results.  \nHowever it has performed surprisingly well for predicting the properties of a variety of atoms, solids and molecules. This is due to a cancellation of errors: LDA underestimates the exchange energy and overestimates the correlation energy.\\autocite{Burke2007} However there is a tendency for LDA to overestimate the binding energy and underestimate lattice parameters. This is a particularly pronounced problem in weakly bonded systems.\n\n\\textbf{Generalised Gradient Approximation}\n\nAt the next level of theory (generalised gradient approximation, GGA), two variables are used to determine the exchange-correlation energy: electron density and the density gradient. The LDA energy density is multiplied by a factor $F_\\textrm{xc}$ which corrects for system inhomogeneities:\\autocite{Henderson2008}\n\\begin{equation}\nE_{\\textrm{GGA,xc}} = \\int  E_{\\textrm{HEG,xc}}\\left[\\rho\\left(\\textbf{r}\\right)\\right]F_\\textrm{xc}\\left[\\rho\\left(\\textbf{r}\\right),\\Delta\\rho\\left(\\textbf{r}\\right)\\right]\\textrm{d}\\mathbf{r}.\n\\end{equation}\nDue to their dependence on the electron density gradient, GGA functionals are classed as semi-local. The parameters of GGA functionals can be derived from physical constraints (a non-empirical approach, as in the widely used PBE functional), or obtained from fitting procedures (an empirical approach, as in the case of the B88 functional). GGAs improve the over-binding of LDA, but tend to underestimate the bandgap of the material.\n\n\\textbf{Hybrid functionals} \n\nIn DFT each electron interacts with itself as the potential derives from the total charge density of the system. This error is particularly pronounced for localised states, for example after trapping an electron or hole at a defect site. Hybrid functionals combine the GGA functional exchange-correlation energy $E_{\\textrm{GGA,xc}}$ with a proportion of the exact HF exchange energy $E_{\\textrm{HF,x}}$ to partially correct the self-interaction error. The simplest hybrid functional takes the form:\\autocite{Henderson2008}\n\\begin{equation} \\label{simplehybrid}\nE_{\\textrm{hybrid,xc}} = \\alpha E_{\\textrm{HF,x}} + \\left(1-\\alpha\\right)E_{\\textrm{GGA,xc}}.\n\\end{equation}\nIn some studies the proportion of exact exchange is tuned to reproduce the property of interest correctly. For example, $\\alpha=0.43$ is commonly used to correctly reproduce the bandgap of the hybrid halide perovskite MAPI.\\autocite{Whalley2017} %\n\nRange separated hybrid functionals are a generalisation of the above, without the requirement that $\\alpha$ is constant.\nTo introduce range separated hybrids more formally we define the exchange-correlation hole $h_\\mathrm{xc}$ as:\n\\begin{equation}\nh_\\mathrm{xc}(\\mathbf{r}_1|\\mathbf{r}_{12}) = \\rho(\\mathbf{r}_1|\\mathbf{r}_{12})-\\rho(\\mathbf{r}_1),\n\\end{equation}\nwhere $\\rho(\\mathbf{r}_1|\\mathbf{r}_{12})$ is the probability density for simultaneously finding one electron at position $\\mathbf{r}_1$ and another electron at a distance of $|\\mathbf{r}_{12}|$.\nThe term \\textit{hole} is used as $h_\\mathrm{xc}$ describes the region in space around an electron in which the probability of finding another electron is close to zero.\n\nThe exchange-correlation hole for the simple hybrid functional (Equation \\ref{simplehybrid}) is:\\autocite{Henderson2008}\n\\begin{equation}\nh_\\mathrm{xc}(\\mathbf{r}_1|\\mathbf{r}_{12}) = \\alpha h_{\\textrm{HF,x}}(\\mathbf{r}_1|\\mathbf{r}_{12})+ \\left(1-\\alpha\\right)h_{\\textrm{GGA,x}}(\\mathbf{r}_1|\\mathbf{r}_{12}),\n\\end{equation}\nwhereas for range separated hybrid functionals the proportion of exact exchange used to determine the exchange-correlation hole depends upon the distance between the two electrons:\\autocite{Henderson2008}\n\\begin{equation}\nh_\\mathrm{xc}(\\mathbf{r}_1|\\mathbf{r}_{12}) = \\alpha(\\mathbf{r}_{12}) h_{\\textrm{HF,x}}(\\mathbf{r}_1|\\mathbf{r}_{12})+ \\left(1-\\alpha(\\mathbf{r}_{12})\\right)h_{\\textrm{GGA,x}}(\\mathbf{r}_1|\\mathbf{r}_{12}).\n\\end{equation}\nThe hybrid functional HSE06\\autocite{Heyd2003} is used to generate many of the results in this thesis. This is a screened range-separated functional where the exact exchange is used for small $\\lvert\\mathbf{r}_{12}\\rvert$ only. \n\n%\\textbf{Random Phase Approximation} \n%\n%Closest to heaven is the Random Phase Approximation (RPA), which uses all of the Kohn-Sham orbitals (occupied and unoccupied) as input variables. The functionals listed so far are inaccurate when there are significant long range effects, as they have no information about the electron density far from an electron. The RPA is able to correctly predict long-range interactions, such as the van der Waals interaction, between non-overlapping electron orbitals.\n% can I find plot of total energy as function of seperation using different approaches??\n%As DFT is exact except for the approximation to the exchange-correlation functional, any shortcoming to a DFT prediction can be attributed to the XC-functional. It should be noted though that DFT \n% DFT was not designed to calculate bandgaps.\n% - However, since 2000 functionals have been better at giving total energy but they don’t give accurate density: straying away from ab-initio into a fitting exercise: DFT is straying from the path towards an exact functional\n\n\\subsection{Periodicity and Bl\\\"{o}ch states} \\label{periodicitysubsection}\n\nThe material studied in this thesis, MAPI, is a crystalline solid. Although we want to understand the properties of a finite piece of material, we use the standard approach and model the finite crystal as an infinite crystal. This is acceptable if the crystal piece is large enough so that its properties do not depend on size. Born-von Karman (periodic) boundary conditions are used so that the infinite crystal is built from a repeating array of unit cells. There are an infinite number of unit cells of different shapes and sizes that can be used to build an infinite crystal. Any physically significant function of the crystal must have the same periodicity.\n\nWhen the Schr\\\"{o}dinger equation is solved for a single atom the solution gives wavefunctions corresponding to the 1$s$, 2$s$, 2$p$, etc orbitals found in chemistry. When the Schr\\\"{o}dinger equation is solved for a periodic system, wavefunctions are formed by Bl\\\"{o}ch functions $\\psi_{\\textbf{k}}$:\\autocite{Hoffmann1987}\n\\begin{equation} \\label{bloch}\n\\psi_{\\textbf{k}} = u_\\textbf{k}e^{i\\textbf{k}\\cdot\\textbf{r}}.\n\\end{equation}   %could do a sketch of the two parts and the resulting part, and the periodic potential\nThe Bl\\\"{o}ch function is formed from the product of a basis function $u_\\textbf{k}$ with the same periodicity as the crystal lattice, and a plane wave $e^{i\\textbf{k}\\cdot\\textbf{r}}$. $\\textbf{k}$ is the crystal wave vector which forms a space known as reciprocal space. To understand the physical significance of $\\textbf{k}$ we consider an infinite 1D chain of hydrogen atoms separated at distance $L$. The electron states can be described as a linear combination of hydrogen 1$s$ orbitals $u_n$ centred at each lattice point:\n\n\\begin{equation} \\label{1dbloch}\n\\psi_k = \\sum_nu_ne^{iknL},\n\\end{equation}\n\nwhere $k=0$ corresponds to the lowest energy in-phase state, and $k=\\frac{\\pi}{L}$ corresponds to the highest energy out-of-phase state.\nBetween these two extremes there is a continuum of states forming an electronic band (Figure \\ref{bands}). \n\nFor any periodic system we can apply the Schr\\\"{o}dinger equation for a specific $\\textbf{k}$ and calculate the electronic bandstructure $E(\\textbf{k})$. There are an infinite number of eigenvalues $E_n(\\textbf{\\textbf{k}})$, where $n$ is used to label a particular eigenvalue (band). As a result of crystal symmetry, $E_n(\\textbf{k})$ is periodic and only $k$-vectors within a region of space known as the Brillouin zone ($|\\textbf{k}|<\\frac{\\pi}{a}$) need to be considered.\\autocite{Lundstrom2000} \n%talk about high symmetry points and the naming conventions (greek in zone and latin a boundaries) - choose route through use aflowlib\n\n\\begin{figure}[h]\n\\centering\n  \\includegraphics[width=1.0\\columnwidth]{figures/ch3/bands.png}\n  \\caption[In-phase and out-of-phase states in an infinite 1D crystal]{(LHS) A one dimensional infinite chain of hydrogen atoms with index $n=0,1,2\\ldots$. The atom spacing (unit cell length) is $L$, and there is a hydrogen 1$s$ orbital $u_n$ centred at each lattice point. The electron states for this system are formed from Bl\\\"{o}ch functions as given in Equation \\ref{1dbloch}. (RHS) $k=0$ corresponds to a low energy in-phase state and $k=\\frac{\\pi}{L}$ corresponds to a high energy out-of-phase state. Between these two extremes there exists a continuum of states.} \n  \\label{bands}\n\\end{figure}\n\nIn real materials translational symmetry can be broken, for example when there are point defects (as in Chapter \\ref{ch:6-defects}). Furthermore, lattice vibrations have a periodicity larger than the unit cell. To model defects or lattice vibrations a supercell is built from multiple unit cells and this is used as the basic repeating unit cell (Figure \\ref{translational}).\n\n\\begin{figure}[h]\n\\centering\n  \\includegraphics[width=0.8\\columnwidth]{figures/ch3/supercell.png}\n  \\caption[Translational symmetry and supercell construction]{(LHS) An infinite crystal is built from a repeating unit cell of length $L$. Point defects (marked with an `x') break translational symmetey in real crystals and care must be taken when modelling these as neighbouring defects can interact with each other in an unphysical way. In addition, vibrational modes can have $\\lambda>L$ (sine wave). (RHS) A supercell of length $M=2L$ can be built to reduce defect-defect interactions and model longer wavelength phonons. } \n  \\label{translational}\n\\end{figure}\n\n\\subsection{Basis sets} \\label{basissetsection}\n\nIn the previous section the Bl\\\"{o}ch wavefunction $\\psi_\\mathbf{k}$ was given for a 1D linear chain of hydrogen atoms, and the lattice periodic part of the Bl\\\"{o}ch function, $u_\\mathbf{k}$, took the form of a hydrogen 1$s$ orbital. For more complex systems $u_\\mathbf{k}$ can itself be expanded into a plane wave basis set:\n\\begin{equation}\nu_\\textbf{k} = \\sum_\\textbf{G}c_{\\textbf{k},\\textbf{G}}e^{i\\textbf{G}\\cdot\\textbf{r}},\n\\end{equation}\nwhere the wave vectors $\\textbf{G}$ correspond to reciprocal lattice vectors and $u_\\textbf{k}$ is the Fourier transformation of the wavefunction $\\psi_\\mathbf{k}$ in reciprocal space. \nAs more terms are added to the Fourier series the electron density is described with increased accuracy.\nNumerical convergence is used to justify the term at which the expansion is truncated (this is discussed further in Section \\ref{numericalsubsection}).\nThe complete expanded wavefunction is:\n\\begin{equation} \\label{KSeigenstates}\n\\psi_\\textbf{k} = \\sum_\\textbf{G}c_{\\textbf{k},\\textbf{G}}e^{i(\\textbf{k+G})\\cdot\\textbf{r}},\n\\end{equation}\nwhere we see that the real space wavefunction has been mapped onto a series of plane waves in reciprocal space.\n\nAs a plane wave is inherently periodic this basis set is often used for extended systems. The software used for the DFT calculations in this thesis, \\textsc{VASP},\\autocite{Kresse1996} uses a plane wave basis set. For DFT calculations applied to localised systems, such as molecules or nanoparticles, localised basis sets such as gaussian orbitals are more likely to be used.\n\n\\subsection{Pseudopotentials}\n\nSudden changes in electron density are hard to capture using a plane wave basis set; to take an extreme example, the fourier decomposition of a simple top hat in real space requires an infinite summation in reciprocal space. This can be problematic when describing the region around the nucleus where there are strong oscillations in the DFT wavefunctions. Instead, pseudopotentials - effective potentials which do not lead to oscillations in the wavefunction - can be used. It has been established that for certain systems pseudopotentials are as precise as all-electron calculations.\\autocite{Lejaeghere2016}\n\nTo develop a pseudopotential for a particular element we consider it as an isolated atom and split the single-particle electron states into a set of valence states $\\{\\psi^\\mathrm{v}\\}$ and core states $\\{\\psi^\\mathrm{c}\\}$.\\autocite{Kaxiras2007} The core states are those which contribute a negligible amount to the total electron density beyond a cutoff radius $r_c$. Both sets of states satisfy the single-particle Schr\\\"{o}dinger equation for the atom:\n\\begin{align} \\label{speqn}\n\\hat{H}\\psi^\\mathrm{v} = \\epsilon^\\mathrm{v}\\psi^\\mathrm{v} \\\\\n\\hat{H}\\psi^\\mathrm{c} = \\epsilon^\\mathrm{c}\\psi^\\mathrm{c},\n\\end{align}\nwhere $\\hat{H}$ contains a potential $V$ which accounts the electron-ion and electron-electron interactions.\n\nA new set of single particle valence states, $\\{\\tilde{\\psi}^\\mathrm{v}\\}$ can be defined so that they obey the single-particle Schr\\\"{o}dinger equation above, but now with an additional potential term $\\tilde{V}$. \nThe pseudopotential $V_\\mathrm{ps}$ is the modified potential which includes this term.\nIn addition, the valence states $\\{\\tilde{\\psi}^\\mathrm{v}\\}$ are constructed so that: 1) they have zero overlap with the core states $\\{\\psi^\\mathrm{c}\\}$; 2) their eigenvalues (for the modified Hamiltonian) are equal to $\\epsilon^\\mathrm{v}$; and 3) the additional $\\tilde{V}$ term is repulsive.\n\nThe repulsive $\\tilde{V}$ term can can be interpreted as the core electrons shielding the valence electrons from the attractive Coulomb potential of the atom. For a mathematical description of the pseudpotential construction process the reader is referred to Chapter 2 of Reference \\cite{Kaxiras2007}.\n\nThe pseudopotential $V_\\mathrm{ps}$ is not unique, and is constructed so that $\\{\\tilde{\\psi}^\\mathrm{v}\\}$ reproduce the behaviour of $\\{\\psi^\\mathrm{v}\\}$ beyond the cutoff radius $r_c$. Within this radius, where the behaviour of the wavefunction does not determine the properties of a solid, the $\\{\\tilde{\\psi}^\\mathrm{v}\\}$ are designed to be smooth and nodeless (Figure \\ref{ppfigure}).\n\n\\begin{figure}[h]\n\\centering\n  \\includegraphics[width=0.6\\columnwidth]{figures/ch3/ppfigure.png}\n  \\caption[Construction of the pseudo-wavefunction and pseudopotential]{Construction of the pseudo-wavefunction $\\tilde{\\psi}$ and pseudopotential $\\tilde{V}$. Within the cutoff radius $r_c$ the pseudo-wavefunction is smooth and nodeless. As a result the pseudopotential is finite and smooth near the origin, instead of having a singularity like the Coulomb potential. Beyond $r_c$ the pseudo-wavefunction and pseudopotential reproduce the atomic wavefunction $\\psi$ and Coulomb potential of the ion, respectively.}\n  \\label{ppfigure}\n\\end{figure}\n\nThe key benefits of the pseudopotential method are that: 1) the size of the basis set needed to expand the wavefunctions is reduced (as the strong oscillations within the core region are removed); and 2) it can be combined with the `frozen core' approximation so that the Kohn-Sham equations are solved for the valence electrons only. Both of these features reduce the computational cost of an electronic structure calculation.\n\nThere are several flavours of pseudopotential. Norm-conserving pseudopotentials are constructed so that within $r_c$ the norm of $\\tilde{\\psi}^\\mathrm{v}$ is identical to that of the corresponding state $\\psi^\\mathrm{v}$. This constraint increases the computational cost for first row elements and transition metals. Ultrasoft pseudopotentials (USPP)\\autocite{Vanderbilt1990} do not enforce conservation of the norm, which allows for a reduction in basis set size. \n\nA separate approach to the problem of rapidly oscillating wavefunctions near the nuclei is the Augmented Plane Wave (APW) method.\\autocite{Andersen1975} For this method space is split into two regions; one region inside an atom-centred sphere, and one region outside the sphere. Wavefunctions are defined as atom-like partial waves inside the sphere, and plane waves beyond the sphere. The functions are chosen so that they are continuous at the boundary.\n\nThe DFT software \\textsc{VASP} was used for the calculations reported in this thesis. \n\\textsc{VASP} implements the projector augmented wave (PAW) approach, which is a generalisation of both USPP and the APW method.\\autocite{Blochl1994} A linear transformation $\\hat{T}$ is defined to transform the pseudo wavefunction $\\tilde{\\phi}$ to the all-electron KS wavefunction $\\phi$:\\autocite{Rostgaard2009}\n\\begin{equation}\n\\phi = \\hat{T}\\tilde{\\phi}.\n\\end{equation}\n$\\phi$ is smooth beyond the region $\\Omega_R$ enclosing an atom with index $R$, so $\\hat{T}$ is chosen to modify the wavefunction close to the nuclei only:\\autocite{Rostgaard2009}\n\\begin{equation}\n\\hat{T} = 1+\\sum_R \\hat{T}^R,\n\\end{equation}\nwhere $\\hat{T}^R$ is non-zero only within the spherical region $\\Omega_R$.\n\nUnlike the pseudopotential method, where information about the all-electron wavefunction close to the nuclei is lost, the PAW method provides a way to calculate all-electron properties from $\\tilde{\\phi}$. For an all-electron operator $\\hat{A}$, the equivalent pseudo operator $\\tilde{A}$ is:\\autocite{Rostgaard2009}\n\\begin{equation}\n\\tilde{A} = \\hat{T}^\\dagger\\hat{A}\\hat{T},\n\\end{equation}\nwhere $\\hat{T}^\\dagger$ is the conjugate transport of $\\hat{T}$.\n\n%http://helper.ipam.ucla.edu/publications/maws3/maws3_6085.pdf\n%http://davidbowler.github.io/AtomisticSimulations//blog/dft-reliability#R3\n\n\\subsection{Optimising the atomic and electronic structure} \\label{SCFsubsection}\n\nIn this section the process of optimising the atomic and electronic structure of a system towards the ground-state (minimum energy) configuration is outlined. \n\nAs outlined in Section \\ref{KSformalismsubsection}, the Coulomb and exchange-correlation potentials are dependent on the electron density $\\rho(\\mathbf{r})$, which is itself dependent on the potentials. Therefore an iterative approach called the self consistent field method is used to calculate the ground-state electronic structure (Figure \\ref{SCF}, dashed section). An initial guess for the density $\\rho(\\textbf{r})$ is given by a superposition of the atomic charge densities. This is used to calculate the potential and solve the KS equations, which gives a new $\\rho(\\textbf{r})$. This process continues until there is convergence within a given energy tolerance. Various optimisation routines are provided in DFT codes for finding the ground state configuration, including the conjugate gradient scheme, Davidson Scheme and RMM-DIIS.\n\nDFT is also used to find the ground state atomic structure. Structures inferred from X-ray diffraction data are used as a starting guess, so that finding the energetic minimum becomes a local optimisation problem. Atoms in the systems are displaced (either the internal coordinates of the unit cell or the unit cell parameters themselves are adjusted) and the electronic structure for that geometry is solved self-consistently. This process repeats until the forces on each atom are zero to within a given tolerance (Figure \\ref{SCF}). \n\n\\begin{figure}[h]\n\\centering\n  \\includegraphics[width=0.7\\columnwidth]{figures/ch3/scf.png}\n  \\caption[Nested iterative method for geometry optimisation]{Nested iterative method for geometry optimisation. The electronic structure relaxation (dashed lines) is nested within the atomic structure relaxation (solid lines). $v_\\textrm{ext}(\\textbf{r})$, $v_\\textrm{c}(\\textbf{r})$ and $v_\\textrm{xc}(\\textbf{r})$ correspond to the external, classical (electrostatic) and exchange-correlation potentials respectively.} \n  \\label{SCF}\n\\end{figure}\n\n\\subsection{The limits of DFT} \\label{numericalsubsection}\n\n\n\\textbf{Theoretical limitations} \n\nIn Section \\ref{DFTtheory} the approximations inherent to DFT calculations were outlined: the Born-Oppenheimer approximation and the unknown exchange-correlation functional. Higher levels of theory, which incorporate the effects of spin and relativity (e.g. spin-orbit coupling) are included in many DFT implementations. However DFT is still restricted to ground-state properties and higher levels of theory (GW or time-dependent DFT) are required to describe excited states. Another inherent limitation is that the KS eigenvalues are artificial; only the ground state electron density and derived properties are correct. In practice the KS eigenvalues are used to calculate the bandgap, but quantitatively correct bandgaps often require the use of hybrid functionals with empirically-set parameters.\n\n\\textbf{Numerical limitations} \n\nThere are also approximations that relate to numerical convergence rather than the underlying theory.\nIn Section \\ref{basissetsection} we expanded the lattice periodic part of a wavefunction into a plane wave basis set. In principle an infinite set may be needed to describe the orbitals, but in practice the basis set must be truncated. The kinetic energy operator is given by $-\\frac{\\hbar^2 }{2m}\\nabla^2$ and when this is applied to the wavefunction $\\psi_\\mathbf{k}$ as given in Equation \\ref{KSeigenstates}, we find that the kinetic energy is proportional to $|\\mathbf{k}+\\mathbf{G}|^2$; faster plane-wave oscillations correspond to higher energies. A cutoff energy $\\textrm{E}_\\textrm{cut}$ is defined so that\n\\begin{equation}\n\\frac{1}{2}|\\mathbf{k}+\\mathbf{G}|^2 < \\textrm{E}_\\textrm{cut}.\n\\end{equation}\nThis cutoff energy must be tested to ensure that the property of interest (which is often energy) is converged to within a certain tolerance.\n\nTo calculate many material properties we need to integrate over the Brillouin zone in reciprocal space. To calculate the total energy of an insulator for example, we use\n\\begin{equation} \\label{energyintegral}\n    E = \\frac{\\Omega}{(2\\pi)^3}\\sum_\\textrm{occ.}\\int_\\textrm{BZ}E(\\textbf{k})d^3k\n\\end{equation}\nwhere $\\Omega$ is the volume of the Brillouin zone and the sum is over all occupied bands. \nIn practice we do not know the continuous form for $E(\\textbf{k})$ and so we numerically evaluate Equation \\ref{energyintegral} as a weighted sum over special points in reciprocal space. These points often form an equally spaced mesh centred on the $\\Gamma$-point ($\\textbf{k}=(0,0,0)$) in reciprocal space. For any given system, the $k$-point density scales inversely with cell size; for example, if the unit cell in Figure \\ref{translational} requires a $6\\times6$ $k$-point grid, then the larger $2\\times2$ supercell requires a $3\\times3$ $k$-point grid. As with plane waves, there is a balance between accuracy (the higher the number of $k$-points, the higher the accuracy) and computational expense. An example convergence study is given in Figure \\ref{kpointconvergence} where a $5\\times5\\times5$ $k$-point grid is required to converge pressure to within \\SI{1}{\\kilo\\bar} and energy to within \\SI{0.1}{\\electronvolt}.\n\n\\begin{figure}[h]\n\\centering\n  \\includegraphics[width=0.7\\columnwidth]{figures/ch3/kpointconvergence.png}\n  \\caption[\\ce{CsSnI3} $k$-point convergence]{$k$-point convergence of \\ce{CsSnI3}. The $k$-point grid size is on the $x$-axis. Red dots denote pressure; the region which is within the convergence criteria of \\SI{1}{\\kilo\\bar} is shaded red. Blue crosses denote total energy; the region which is within the \\SI{0.1}{\\electronvolt} convergence criteria is shaded in blue. Only odd grids sample the $\\Gamma$-point and so there is an oscillation in energy and pressure as points move between odd and even grids.}\n  \\label{kpointconvergence}\n\\end{figure}\n\n\n% - K-point grids and the commensurate grids for supercells.\n% - Doubles k-points reuired as k and –k now no longer equivalent (SoC?)\n%All convergence tests must be done for the property of interest. Cancellation of errors can mean that energy differences converge faster than ground state energies, as is reported in Chapter \\ref{}.   % EP coupling calcas \n% - See: Designing meaningful density functional theory calculation in materials science - a primer Anne E Mattson et al. Model. Sim. Mater. Sci Eng. 13 R1-R31 (2005). : for information about convergence and getting meaningful results.\n\n%\\textit{Computational limitations}\n% - history of computers section at science museum for HPC section\n% - put the amount of computer time and carbon burnt here?\n% - computational expense: limitations on size: See review of materials models which Alison Walker mentions. Mesoscopic bridges the atomistic with the drift diffusion models. Meso is often monte carlo, tranjectory tpe calculations. Cells are too big for atomistic (1 cm squared). Efficiecny depends upon J-V curves which can only be modelled at scale of fill device. The electrostatics is incredible important which linked ot build up of charges at SC nd OC. Grain boundaries and recombination at intercaes.\n\n\\section{Defects in semiconductors}\n\nThe second law of thermodynamics states that an isolated system tends towards an equilibrium state with maximum entropy. A consequence of this is that all solids in equilibrium and at finite temperature contain point defects, as the cost in lattice energy is balanced by the increase in configurational entropy. \nPoint defects are associated with a number of microscopic processes that can be either beneficial or detrimental to material performance, including:\n\\setlist{nolistsep}\n\\begin{itemize}[noitemsep]\n    \\item optical: colour centres, up/down conversion\n    \\item electrical: conductivity, carrier trapping, ionic hopping\n    \\item mechanical: material hardening\n    \\item thermal: conductivity, decomposition\n\\end{itemize}\n%Yakov Frenkel introduced the concept of defects in a crystalline structure in 1926. Research interest in this field continued throughout the 20th and 21st centuries as the physical processes listed above determine the success or failure of technologically important materials. \nTheoretical methods are particularly useful in this area as although it is often possible to estimate the quantity of defects in a material using experimental methods, it is much more challenging to identify the defect species.\\autocite{Alkauskas2016}  \n \nIn this section I outline the different types of crystal defects and discuss the thermodynamics of (charged) defect formation. The supercell method for calculating defect properties is also outlined. This method is used in Chapter \\ref{ch:6-defects}.\n% We are interested in calculating the electronic structure properties which lead to a description of the defects (trap density, binding energy, trap level, capture cross section).\n\n% cite defects and defect processes in nonmetallic solids\n\n% - History:\n% - 1912 Born and Karman . PBC (first lattice dynamics paper)\n% - 1925 Frenkel – formation of frenkel pair (first defects paper)\n% - 1922 Jost – probability of forming defects. Tied into experimental work popular at the time, looking at how a material can be an ionic conductor when it is electrically insulating\n% - 1938 Mott – the Mott-Littleton approach for calculating defects\n\n\\subsection{Classification of crystal defects}\n\nThe first way to classify defects is via their dimensionality. 0-dimensional point defects are localised around isolated sites in the crystal. 1-dimensional dislocations are lines along which the crystal pattern is broken. 2-dimensional grain boundaries or interfaces are surfaces along which distinct crystallites are joined. 3-dimensional defects are changes to the crystal pattern in a finite volume. \n\n0-dimensional point defects are the subject of Chapter \\ref{ch:6-defects}. Point defects can be further split into extrinsic or intrinsic defects. Extrinsic point defects (also known as impurities) are a different species from that of the host. These defects may be added intentionally (for example, to increase electrical conductivity) or unintentionally (as a result of the fabrication method). Intrinsic point defects are associated with the host species.\n\nPoint defects can also be classified as non-stochiometric or stochiometric. Non-stochiometric defects include interstitials (where an additional atom occupies a site that is unoccupied in the perfect lattice), vacancies (missing atoms) and antisites (where an atom occupies a site that would have been occupied by another species in the perfect lattice). Interstitials can have a split structure, in which two atoms are split symmetrically around a single lattice site. Stochiometric defects include Frenkel pairs and Shottky pairs. Stochiometric and non-stochiometric point defects are illustrated in Figure \\ref{classification}.\n\n\\begin{figure}[h]\n\\centering\n  \\includegraphics[width=0.8\\columnwidth]{figures/ch3/classification.png}\n  \\caption[Classification of crystal point-defects]{Non-stochiometric defects include interstitials (an additional atom), vacancies (a missing atom) and anti-sites. Stochiometric defects include a Frenkel pair (a vacancy close to an interstitial of the same species), and a Shottky pair (a vacancy on both the anion and cation sub-lattices).}\n  \\label{classification} . %hatch the shapes in this drawing so can tell the differene in b+w\n\\end{figure}\n\nThe final classification is into electrically active and electrically benign defects. Whilst electrically benign defects exist only in one charge state, electrically active defects can take more than one charge state; for example, single acceptors exist in a neutral or negatively charged state and single donors exist in a neutral or positively charged states. Amphoteric defects can exist in a negatively charged or positively charged state.\n% reference alkasukas https://www.osti.gov/pages/servlets/purl/1471061\n% - may be able to say defect is there experimentally but another step to identify which it is. Admittance spectroscopy, DLTS. ESR (later chapter)\n% emphasise that the concentration could be as low as one part in a milllion and wtill have an effect.\n% - defect levels deend on temperature. DLTS assumes T-independent scattering cross sction, not accurate,\n\n\\subsection{Energetics of defect formation} \\label{defectformation}\n\nIn the dilute limit, the equilibrium concentration of defects $n$ at a fixed temperature and pressure is given by the density that minimizes free energy.\n\\begin{equation} \\label{defectconcentration}\n    n = N_\\mathrm{sites} \\exp \\left(-\\frac{\\Delta G}{k_\\mathrm{B} \\mathrm{T}} \\right),\n\\end{equation}\nwhere $\\Delta G$ is the Gibbs free energy of defect formation. The Gibbs free energy is approximated as the formation energy $E_\\mathrm{f}$ of the defect as this dominates over entropic contributions. The formation energy is given by:\n\\begin{equation} \\label{eqn_formation_energy}\nE_\\mathrm{f}(q) = E_\\mathrm{d}(q) - E_\\mathrm{b} - \\sum_i \\mu_i n_i + q(\\epsilon_\\mathrm{VBM}+E_\\mathrm{F}) + E_\\mathrm{corr},\n\\end{equation}\nwhere $E_\\mathrm{d}(q)$ is the total energy of the supercell with a defect of charge $q$ and $E_\\mathrm{b}$ is the total energy of the perfect bulk. \n$E_\\mathrm{corr}$ is a correction energy that is needed when using a finite-sized supercell and is discussed Section \\ref{corrections}.\nThe remaining terms describe the energy needed to add or remove atoms or electrons.\n$\\mu_i$ is the chemical potential of atom $i$ and can be adjusted to describe different growth conditions. \n$n_i$ is the number of atoms that are added or removed and $E_F$ is the Fermi level of the electrons, referenced to the valence band maximum $\\epsilon_\\mathrm{VBM}$.\n\nThe total energies can be calculated using DFT. Convergence criteria for calculations must be tight as, due to the exponential dependence of defect concentration on formation energy, small errors in the energy difference can lead to large errors in the defect concentration.\n\nThe Fermi level is treated as a parameter, of which the defect formation energy is a linear function with a gradient equal to the defect charge. This allows us to plot a graph of formation energy against Fermi level, as shown in Figure \\ref{CdTeformation}. Charge transition levels mark the Fermi level at which two charge states have the same defect formation energy. Electrically active defects have at least one charge transition level in the bandgap. \nThe charge transition level is equivalent to thermal ionization energy, the energy needed to add or remove electron(s). % check this\n% does not always need a charge transition level deep in the bandgap. https://pubs.acs.org/doi/pdf/10.1021/acsenergylett.7b01313\n\n\\begin{figure}[h]\n\\centering\n  \\includegraphics[width=0.8\\columnwidth]{figures/ch3/defectenergetics.png}\n  \\caption[Formation energies of the Te vacancy in CdTe]{Formation energies $\\Delta H_f$ as a function of the Fermi energy for the Te vacancy in \\ce{CdTe}. In a Te-rich environment it is more energetically unfavourable to form a Te-vacancy, as intuition would suggest. The slope of each line corresponds to the defect charge. Charge transition levels correspond to the energies at which the lines intersect. Figure reproduced with permission from the work of Menendez et al.\\autocite{Menendez2016}}\n  \\label{CdTeformation}\n\\end{figure}%cite https://iopscience.iop.org/article/10.1088/1742-6596/720/1/012031/pdf\n\nDeep carrier traps have a defect level towards the middle of the bandgap and produce localised wavefunctions. Carrier capture processes to these defect states are often associated with a large lattice distortion. Shallow defect levels (within thermal energy $k_\\mathrm{B}T$ of the valence or conduction band) produce delocalised, hydrogenic-like defect wavefunctions. \n% - defect energies theoretical founsations - mott littleton (1938)  - a way to calculate E the defecct energy as knew the hopping rate expression, but didnt know E. only experimental input is dielectric constant.see special 1988 issue.\n%  The other problem is that is dependent upon the chemical potential which is difficult to monitor.\n\n% Point defects result in additional energy levels in the bandgap with an associated defect wavefunction to which an electron is added or removed.\n% defect level delocalised, electrical conductivity.EMT.\n%or deep and localised wavefucntion. detrimental in the context of solar cells.\n\n%The concentration of a point defect in a particular charge state can be controlled by tuning the Fermi level through doping. However there is a compensation mechanism, whereby defects form to compensate\n\n% The concentration of point defects can be controlled by thermal treatment, irradiation or doping. \n% - Fermi level pinning (?) / defect concentration: Happens in TCO’s such as FTO. Above a certain concentration there are no more holes. This could happen when there are defect complexes which compensate each other.\n% - This is a compensation mechanism. We try to adjust the fermi level of the system by introducing impurities. However above/below a certain energy level there is spontaneous formation of defects (defects which have a negative energy of formation). These defects compensate for the impurity and in this way the fermi level is pinned.\n\n% - Calculable and observable table:\n% Delta E : heat of formation / concentrations\n% Defect ionisation – optical – instanataneour: PL, optical absorption / photoconductivity\n% Defect ionisation , thermal, after relaxation: DLTS / thermally stimuated conductuvtiy\n% Defect vibrational modes: IR/raman spectra and recombination rates\n\n\\subsection{Supercell method}\n\nDefect concentrations as low as one part in one million can have an influence on device performance. \nOne way to model point defects in the dilute limit, when defect-defect interactions are negligible, is to build a supercell from multiple unit cells (Figure \\ref{translational}).\nThis supercell must be large enough so that there is no interaction between a defect and its periodic images.\nAlthough the supercell method captures localised defects well, it cannot capture the behaviour of delocalised (or band resonant) defects due to the enforced periodicty. \n%http://cmt.dur.ac.uk/sjc/thesis/thesis/node71.html\nTo remove the constraint of translational symmetry it is possible to use an embedded QM/MM approach whereby a region around the defect is modelled using DFT and embedded in a region that is modelled classically.\n\n% - The supercell method leads to some unphysical results for both electronic and vibrational properties. The defect will perturb the lattice. The SC method captures localised defect effects well – but the delocalised defects (possibly in the band) are not captured as there is an enforced periodicity. The only way around this is to use greens functions method (phonons) or QM/MM approach (electrons).\n% vibrations of defects - link to final chapter\n\n\\subsubsection{Supercell corrections} \\label{corrections}\n% this is from the joint JPhysChem defects review paper - if its published I will need to cite it!\n% previous section - defect-defect interaction but there are also longer ranged coloumb interations\nPoint defects can be electrically charged, and are able to change charge state through the trapping and de-trapping of electrons and holes. \nThe charge state of a defect can affect a number of defect properties including the preferred lattice position, surrounding lattice distortion, and the rates of diffusion, carrier capture, and carrier recombination.\nHowever, due to the long range nature of the Coulomb interaction, understanding the properties of charged defects is a challenge for DFT with periodic boundary conditions.\nThere are two issues to resolve: \nFirstly, charged defects can interact with their periodic images; \nSecondly, a homogeneous jellium background charge is introduced to ensure overall charge neutrality and results in an unknown shift to the average electrostatic potential. \nThese are finite-size effects that only a very large, almost infinite, supercell would overcome.\nHowever a system this size is computationally intractable, especially considering that higher levels of theory (for example, hybrid functionals) are often required to calculate accurate total energies.\n\nA number of correction schemes have been developed to deal with these issues; a brief historical overview is given below. These schemes are designed to be used as a post-processing step and provide a value for the $E_{corr}$ term in Equation \\ref{eqn_formation_energy}. A more complete description of these issues can be found in References \\cite{durrant2018} and \\cite{Vinichenko2017}.\n\nThe Leslie Gillan correction $E^\\mathrm{LG}$ models the defect charge $q$ as a point charge interacting with its periodic images through an isotropic dielectric medium.\\autocite{Leslie1985}\nThis correction takes a simple analytic form that depends on the charge state  $q$, static dielectric constant $\\epsilon_0$, separation between defect images $L$ and the Madelung constant $\\alpha_m$, which is determined by the lattice geometry:\n\\begin{equation}\n    E^\\mathrm{LG} = \\frac{q^2\\alpha_{m}}{2\\epsilon L}.\n\\end{equation}\nThe Markov-Payne correction $E^\\mathrm{MP}$ extends the Leslie Gillan correction by including an additional term that accounts for the delocalised part of the defect charge. \n\\begin{equation}\n    E^\\mathrm{MP} = \\frac{q^2\\alpha_{m}}{2\\epsilon L} + qQL^{-3}. \n\\end{equation}\nThe challenge of the Markov-Payne approach is in calculating the quadrupole moment $Q$. \nThe Lany-Zunger correction\\autocite{Lany2009} combines the Markov-Payne correction, including an approach for calculating $Q$, with a potential alignment procedure to correct for the shift in electrostatic potential. \nThe Freysholdt, Neugebauer and van de Walle (FNV) method\\autocite{Freysoldt2009} models the defect charge as a localised gaussian distribution. \nThe difference between the electrostatic potential of the charged defect supercell and the electrostatic potential of the perfect bulk supercell, calculated far from the defect, is aligned with the defect model potential. \nKumagai and Oba have extended to FNV method by using atomic site potentials combined with a point charge model for an anisotropic medium.\\autocite{Kumagai2014} \n\nThere is still no standardised approach to defect charge corrections, \nwhich can lead to a spread in calculated defect formation energies in the literature, and predicted defect densities which differ by orders of magnitude.\nTwo widely used approaches in the recent literature are the FNV method, and the extension to this provided by Kumagai and Oba.\nThis extension is applied to the iodine interstitial defect in Chapter \\ref{ch:6-defects}, using an implementation in the package \\textsc{sxdefectalign}.\n% - for a really good explanation see Suzys group talk (Monday the 10th september 2018) and https://aip.scitation.org/doi/10.1063/1.5029818 which it was based upon.\n%what are the corections used in this work?\n\n\n\\section{Lattice dynamics} \\label{sec:latticedynamics}\n%cite defect and defect processes in nonmetallic solids\n%cite Dove Lattice dynamics\nThis section includes a brief overview of the theory of lattice dynamics, with a particular focus on anharmonic atomic motion. The finite difference method, an intuitive way to calculate the vibrational properties of a crystal, is outlined. This method has been applied to the perfect bulk in Chapter \\ref{ch:5-epcoupling} and a defect supercell in Chapter \\ref{ch:6-defects}.\n\nHeisenberg's uncertainty principle states that it is not possible to know both the position and momentum of a particle exactly. Thus the static lattice model used so far is only an approximation; even at $T=0\\,\\textrm{K}$ there is zero point atomic motion. As temperature increases, this vibrational motion increases in amplitude.\n\nThe lattice vibrations of a crystal must be considered to calculate a number of physical properties. Atomic motion has an associated vibrational energy, and this determines crystal stability as a function of temperature via the Gibbs free energy:\\autocite{Dove1993}\n\\begin{equation}\nG = E_0+E_\\textrm{vib}+PV-TS\n\\end{equation}\nwhere $E_0$ is the ground state energy, which can be calculated using DFT, and $E_\\textrm{vib}$ is the vibrational contribution to internal enery.\nAtomic motion also influences the electrical and optical properties of a crystal; this can be seen experimentally in the homogeneous broadening of photoluminescence linewidths with temperature, for example.\\autocite{silsbee1962} %cite https://journals.aps.org/pr/abstract/10.1103/PhysRev.128.1726\nOther material properties which are only accessible via lattice dynamics include: heat capacity, thermal conductivity, elasticity, thermal expansion coefficients, electron-phonon coupling strengths and static polarization.\n\nFor atomic motion at small amplitudes around the potential energy minimum it is common to use the harmonic approximation, where the atom moves as if it is connected by a spring to its neighbouring atoms (Figure \\ref{harmonicregime}). This is discussed in Section \\ref{harmonicapprox}. At larger vibration amplitudes, and to understand processes relating to the creation and annihilation of phonons, we must consider anharmonic motion, and this is considered in Section \\ref{anharmonicapprox}.\n\nThese motions are determined by the force on each atom. For simple systems, for example a one-dimensional diatomic chain, we can calculate atomic position as a function of time analytically. Otherwise methods such as DFT can be used to build a force constant matrix which, after some post-processing steps, gives the eigenvectors (direction and amplitude) and eigenvalues (frequencies of motion). This is discussed in Section \\ref{finitedisplacement}. As in the previous sections of this chapter, we use the Born-Oppenheimer approximation and assume that the equilibrium positions in a crystal are the minima of the potential energy surface when the electron and nuclear motion are decoupled.\n\n\\begin{figure}[h]\n\\centering\n  \\includegraphics[width=0.8\\columnwidth]{figures/ch3/harmonicregime.png}\n  \\caption[Crystal potential energy expanded with respect to atomic displacement]{The crystal potential energy can be expanded in powers of atomic displacement $x-x_0$, where $x_0$ is the equilibrium position. At small displacements, the anharmonic terms (third order and above) can be ignored, giving the harmonic approximation. For larger displacements, higher order anharmonic terms must be considered. The crystal lattice is relaxed so that all forces on the atoms are zero and there is no first order force term.}\n  \\label{harmonicregime}\n\\end{figure}\n\n%important to understand crstal stabilit as the vibrational energy and entropy enter the Gibbs free energy\n% - Partition function ---> bridge function kTlnZ (bridges micro and macro thermodyamics) to get helmholtz free energy. need vibrations to get temperature dependent energy and stability as a function of temperature.\n\n% We know this affects electrical and optical properties – look at the peak shift in energy and peak broadening ith temperature.\n% % - model for vibrations (harmonic approximation) ---> vib freq and displacement patterns (vibrational spectra) and from that IR/raman, free energies (T) - phase change. all stuff you couldnt get with standard electronic structure\n% thermodynamics requires phonons, (helmholtz free energy)\n\n\n% - What information can we get from phonons? \n% Thermodynamic quantities at low temperature: heat capacity, entropy, free energy, zero-point,\n% Phase transitions from the Gibbs free energy,\n% Conductivity,\n% Infromation about lattice instabilities in the form of imaginary frequencies,\n% Elastic tensor from the q to zero limit of phonon dispersion,\n% Thermal expansion coefficient,\n% Temperature dependence of the bandgap,\n% Electron phonon coupling strengths,\n% Static polarization\n\n% - Experimental evidence:\n% Measured directly with inelastic scattering,\n% IR and Raman spectroscopy\n\n\n% - For small amplitudes we consider a simple harmonic motion. phonon modes are uncoupled and have infinite lifetime.\n% - At larger amplitudes we must consider anharmonic motion. phonons can be created and destroyed, have a lifetime and give access to new properties.\n% - Extent of Anharmonicity depends upon how much of the potential energy space you are exploring ((tie in with perturbative and non-perturbative regime skethc). At low T you may be exploring harmonic potentil like minima, at High T you may be beyond this minima\n% - Adiabatic approximation: Can thin of electronic wavefunction for eignstate of nuclei fixed in position.\n\n\n% - The motions are determined by atomic forces. For a 1D system with a single mass or with two masses (lattice with basis) we can solve analytically. Otherwise these can be determined through DFT calculations (Hellman Feynmann theorem), producing a force constant matrix. \n\n% - Table with the approximation and the properties you can get and codes which implement....\n% - quasi-harmonic:properties as a function of volume.helmholtz as function of temeparture  - at some point it is favourable to have a different volume . Free energy as function volume for several tempatures and the fit an equation of state. \n% - Then you can get the bulk modulus, heat capacity constant pressure, gibbs free, gruneisan, volumetric thermal expansion.use to get properties at finite T - use the structure which minimises for a particular temp.\n% - Thermal expansion coefficients, system anharmonicity (e.g. modal grun parameters) and the temperature-dependence of other properties can be calculated in the quasi-harmonic approximation (QHA). \n% Here the lattice dynamics is harmonic at a given temperature; however, the cell volume is scaled by thermal expansion to give the first-order contribution of finite temperature effects. \n% 2: frequency and eigenvectors\n% 3: phonon linewidths / spectral lifetimes\n% 4: anharmonic frequency shifts\n% https://thelostelectron.wordpress.com/\n\n\\subsection{Harmonic approximation} \\label{harmonicapprox}\n\nIn this section I connect, using a minimum amount of mathematics, an expression for total lattice energy with the force constant matrix (which can be calculated using DFT calculations). For a more complete derivation I refer the reader to Section 2.2 of Reference \\cite{Hayes1985}.\n\nIf the atomic displacement from equilibrium is small, the total energy can be Taylor expanded in the form\\autocite{Hayes1985} \n\\begin{align} \\label{taylorexpansion}\nE&=\\textrm{kinetic energy}+\\textrm{potential energy} \\\\\n&=\\sum_i\\frac{1}{2}M\\dot{x}_i^2+\\sum_{ij}\\frac{1}{2}\\textbf{x}_i\\cdot\\textbf{A}_{ij}\\cdot\\textbf{x}_j+\\textrm{higher-order terms},\n\\end{align}\n\nwhere it is assumed that the structure is relaxed and forces are equal to zero so that there is no term linear in $\\textbf{x}$. The harmonic approximation ignores the higher order terms in Equation \\ref{taylorexpansion}. For these harmonic systems there exists a basis set so that $\\textbf{A}_{ij}$ is diagonal and the oscillators are independent of one another:\n\\begin{align} \\label{independentoscillators}\n&=\\sum_j\\frac{1}{2}\\tilde{M}\\dot{Q}_j^2+\\sum_{j}\\frac{1}{2}\\tilde{\\textbf{A}}_{j}Q_j^2,\n\\end{align}\nwhere the linear transformation has cast coordinates $x$ into $Q$.\nThe general solution to this system of equations for $N$-atoms in three dimensions is a superposition of $3N$ normal modes of vibration, each with its own frequency and eigenvector.\nTo calculate the normal modes Newton's second law, $F=ma$, is applied. For crystalline solids we take advantage of symmetry and seek normal modes $\\textbf{e}(\\textbf{k},t)$ that for a chosen wavevector $\\textbf{k}$ are a linear combination of a relative displacement within the unit cell ($\\textbf{u}_0(i,\\textbf{k})$), a phase that depends on the origin $\\textbf{R}_I$ of cell $I$ ($\\textrm{exp}(i\\textbf{k}\\cdot \\textbf{R}_I)$), and an oscillation in time of well defined frequency $\\omega(\\textbf{k})$ ($\\textrm{exp}(i\\omega(\\textbf{k})t)$):\n\\begin{equation} \\label{normalmodes}\n\\textbf{e}(\\textbf{k},t) = \\textbf{u}_0(i,\\textbf{k})\\textrm{exp}(i\\textbf{k}\\cdot\\textbf{R}_I)\\textrm{exp}(i\\omega(\\textbf{k})t).\n\\end{equation}\nFor displacements of this form, Newton's second law has consistent solutions only if the following secular equation is satisfied:\n\\begin{equation}\n\\textrm{Det}||\\sum_J A_{\\alpha\\beta}(iI,jJ)\\textrm{exp}(i\\textbf{k}\\cdot\\textbf{R}_J)-M_i\\delta_{ij}\\omega^2(\\textbf{k})||=0,\n\\end{equation}\nwhere the first term in the determinent is the dynamical matrix. The dynamical matrix is built from the force constant matrix $A_{\\alpha\\beta}$:\n\\begin{equation} \\label{forceconstant}\n\\textbf{A} = \n\\begin{pmatrix} \n\\frac{\\partial^2E}{\\partial x_1^2} &\\frac{\\partial^2E}{\\partial x_1 \\partial x_2} & \\cdots & \\frac{\\partial^2E}{\\partial x_1 \\partial x_n}\\\\\n\\frac{\\partial^2E}{\\partial x_2 \\partial x_1}&\\frac{\\partial^2E}{\\partial x_2^2} & \\cdots & \\frac{\\partial^2E}{\\partial x_2 \\partial x_n}\\\\\n\\vdots & \\vdots & \\ddots & \\vdots \\\\\n\\frac{\\partial^2E}{\\partial x_n \\partial x_1}&\\frac{\\partial^2E}{\\partial x_n \\partial x_2} & \\cdots & \\frac{\\partial^2E}{\\partial x_n^2}\\\\\n\\end{pmatrix}\n\\end{equation}\n\nThe normal mode frequencies $\\omega(\\textbf{k})$ are roots of the secular equation \\ref{normalmodes} and can be found through matrix diagonalisation. Plotting the frequency $\\omega$ against wavevector $\\textbf{k}$ for a lattice with a periodicity of length $L$ gives a bandstructure plot with a periodicity of $\\frac{2\\pi}{L}$.   %check that a is correct for lattice length \n\nThe discussion so far has only used classical mechanics. To introduce quantum effects we recognise that the harmonic lattice vibrations are analogous to a quantum simple harmonic oscillator and so will be restricted to certain energy values $E_n = \\hbar\\omega(\\textbf{k})(n+\\frac{1}{2})$.\nThe discrete (quantised) unit of energy $\\hbar\\omega(\\textbf{k})$ is a phonon quasiparticle that corresponds to a collective excitation of the crystal lattice.\n% The phonons of energy hbar omega have exact energy so cannot be localised in space: formed of delocalised plane waves\n% But can construct localized packet using modes of different fequency. Can then treat phonons as localised particles. E = hbar omega. K is the crystal momentum .\n% Phonons are bosons, not conserved. They can be created and destroyed. \n% once got eigencevtors nad freuencies have access to toher props via partition function\n\n\\subsection{Anharmonicity} \\label{anharmonicapprox}\n\nAnharmonic atomic motion is described by the higher order terms in Equation \\ref{taylorexpansion}.\nThe third order term accounts for phonon-phonon scattering which, due to the conservation of energy and momentum, is a three particle process (Figure \\ref{anharmonicity}).\\autocite{Lundstrom2000}\n\nThe linear boltzmann transport equation (LBTE) describes a thermodynamic system out of equilibrium. Solving the LBTE under the single mode relaxation time approximation gives an expression for the lattice thermal conductivity $\\kappa$.\nThe phonon-phonon scattering rate determines the phonon lifetime $\\tau_\\lambda$ which is a key quantity in the expression for $\\kappa$:\\autocite{Togo2015a}\n\\begin{equation}\n    \\label{thermalconductivity}\n    \\kappa=\\frac{1}{NV_0}\\sum_\\lambda C_\\lambda v_\\lambda \\times v_\\lambda \\tau_\\lambda,\n\\end{equation}\nwhere $N$ is the number of unit cells in the crystal, $V_0$ is the unit cell volume, and $C_\\lambda$, $v_\\lambda$ and $\\tau_\\lambda$ are the mode-dependent heat capacity, group velocity and lifetime respectively. $C_\\lambda$ and $v_\\lambda$ can be calculated using the harmonic approximation. To quantify the strength of the anharmonic phonon interactions that determine $\\tau_\\lambda$ it is necessary to calculate a third-order force constant matrix. This is often at high computational cost; in Reference \\cite{Whalley2016} 41,544 DFT calculations were required to calculate the thermal conductivity of a 96-atom unit cell.\n% -  can reduce the cst by just considering the phase space (broido talk, laptop notes)\n\nLattice anharmonicity can also be used to describe materials with dynamic disorder. In the halide and oxide perovskites the onset temperature for dynamic disorder is determined by the depth of the double well potential energy surface (Figure \\ref{thermalconductivity}).\\autocite{Yang2017}\nChapter \\ref{ch:5-epcoupling} calculates the coupling between the anharmonic double well phonon modes and electronic states in MAPI.\n % - anharmonicity schematic under visuals: Si, PbTe, SrTiO3% - Anharmonicity also needs to be considered according to material (schematic here)\n% for some vobrations compression and extension will not be equal curvature. talk about % - harmonic approximation expects the energy to increase as you push along the mode.imaginary frequency because $w^2$ is negative.\n% - dynamic stability if all positive\n%- mechanism for some phase transitions is where phonon mode becomes imaginary at a transition temperature\n% frozen phonon approximation\n\n\n% - Anharmonicity most important when under high pressure or high temperature (bouchert) which is often the case for geophysical applications.\n% - Navaneeth : assessing how higher order anharmonicity can aggect htermal conductivity. In Diamond the 4 phonon phase space is 10x that of 3-phonon. In Bas it is 100X that of 3-phonon phase space. We must then also consider the scattering strength (can only consider the scattering rate of those with a large phase space). The size of these phase spaces are huge. For example, Bas which is in the zincbelnde structure has 6 polarisations. If each done explicitly there would be $9x10^ 3$-phonon calculations, for 4-phonon processes there would be $2x10^12$!!!  So instead temperature-dependent ensembles are used (where all atoms are moved at the same time, calculated from explicit 2nd order force constant calculation) and then used to fit 3rd and 4th order force constants to.\n\n\n\n\\begin{figure}[h]\n\\centering\n  \\includegraphics[width=1.0\\columnwidth]{figures/ch3/anharmonicity.png}\n  \\caption[3-phonon processes and anharmonic potential energy surfaces]{A) Energy and momentum are conserved during the creation or annihilation of phonons, so these are three-phonon processes (or higher); B) Some materials, such as silicon (Si) are well-described by a harmonic potential energy surface at typical solar cell operating temperatures. However other materials with dynamic disorder, such as the organic and inorganic perovskite halides, have highly anharmonic double well potentials.}\n  \\label{anharmonicity}\n\\end{figure}  %include phonon-phonon scattering schematic? the third regime where important is given in the other figure, at high temperature %cite ruoxi work\n\n\n\n\\subsection{Finite displacement method} \\label{finitedisplacement}\n\nThere are a number of ways to calculate the second order force constant matrix in Equation \\ref{forceconstant} including: the finite displacement method; density functional perturbation theory; ab-initio molecular dynamics and compressed sensing lattice dynamics.\nIn this work the finite displacement method (also known as the direct or supercell method) is used: a single atom is displaced a small distance from its energetic minimum and there is a self-consistent electronic structure optimisation to calculate the resultant forces. The maximum number of displacements for a system with $N$ atoms in the unit cell is $6N$, although this is reduced through symmetry. \nTo consider phonon wavelengths greater than the unit cell length a supercell is required, and all forces must be well converged (typically to less than \\SI{0.01}{\\electronvolt\\per\\angstrom}).\n\n%negatives of this approach: no long range forces beyond hte supercell (polar materials), no anharmonicity .  %positive - highly parallelisable\n\n% - Note that the  eigenvalue equation for the dynamical matrix is gotten from fourier transform\n% Of the taylor expansion of the crystal potential.\n% - force constant matrix . then construct dynamical matrix - -> wavevector. then diagonalise - the eigenvectors and eigenvalues. do a schematic for this process. then two ways to get to the dynamical matrix.\n\n% - There are a multitude of ways to calculate these force constants: explicitly (finite difference, DFPT for 3rd or 4th orders), empirical potentials (TDEP), compressive sensing lattice dynamics or beyond perturbation (AIMD,PIMD,SCAILD, variational methodslike SSCHA developed by Ion Errea).\n% - perturbation theory- dynamical matrix directly. no supercell and more accurate but constrained which functionals and pseudopotentials you need.\n\n% schematic of workflow: input structure, create displacements, calculate forces, calculate dynamical matrix, diagonalise\n\n% phonon workflow\n\n% in this work the finite displacement approach is used as implemented in...\n% For derivatives we exploit the hellman-feynam theorem and use finite differences % - Force constant via finite displacement - displace small and calculate force. Simple, general and can split into small jobs (parallelise). \n% AKA \"supercell\",\"direct\" or \"frozen phonon\" \n% - phonons can have a wavelength longer than the size of the supercell - need to capture the longer wavelength. but need supercells. use phonopy. Maximum is 6N displacements but this is seriously reduced by symmetry. (spglib)\n% - Need good relaxation: don't skimp on the forces, cutoff or k-points.\n% - PBEsol for reproducing lattice constants and phonons (Jonathan 2015 J.Chem. Phys)\n\n% - See Jonathans talks\n\n\\section{Summary}\n\nIn this chapter I have introduced the key concepts that underly DFT, and the post-processing steps required to calculate the defect and vibrational properties of a crystal. \nMuch of solid state physics is built upon the idea of a translationally invariant crystal, so it should come as little surprise that additional steps are needed to describe defects that break translational symetry and work against the fundamental assumptions of the theoretical framework.\nIn contrast, phonons at the gamma point preserve the underlying translational symmetry, but additional steps are needed to build the force constant matrix from multiple DFT calculations.\nIn this chapter I have presented the defect and vibrational calculations separately. In Chapter \\ref{ch:6-defects} I combine the two approaches, and calculate the vibrational properties of the iodine interstitial defect in MAPI. \n%A discussion about how a point defect perturbs the vibrational sub-system of a bulk material is included in that final chapter.\n%: LW - could we add here that solid state physics of crystalline materials is not really built for defects as they assume perfect translational symmetry, which the defects break ---> which makes modelling defects a continuing challenge for theory and simulation (as we are working \"against\" the fundamental assumptions of the framework).\n% - defects are demainding and computational expensive .n To avoid computationally expensive defect calculations descriptors have been built on the idea of ‘defect tolerant’ materials: http://pubs.acs.org/doi/pdf/10.1021/acs.nanolett.5b04513\n% in fact I combine defect and phonon calculations in final chapter\n\n\n", "meta": {"hexsha": "df9ba36db374fe17516ad145958e0251622f31ab", "size": 82663, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "text/ch3-methods.tex", "max_stars_repo_name": "lucydot/PhD_thesis", "max_stars_repo_head_hexsha": "2af388cb5051b3f675601a3ccf1b328eaed12b59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "text/ch3-methods.tex", "max_issues_repo_name": "lucydot/PhD_thesis", "max_issues_repo_head_hexsha": "2af388cb5051b3f675601a3ccf1b328eaed12b59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "text/ch3-methods.tex", "max_forks_repo_name": "lucydot/PhD_thesis", "max_forks_repo_head_hexsha": "2af388cb5051b3f675601a3ccf1b328eaed12b59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 111.4056603774, "max_line_length": 924, "alphanum_fraction": 0.7870268439, "num_tokens": 20647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3153133670695476}}
{"text": "\\documentclass[12]{scrartcl}\n\\usepackage{amssymb,amsmath,gensymb,dsfont,calc,multicol,fullpage}\n\\makeatletter\n\\newcommand\\Aboxed[1]{\n   \\@Aboxed#1\\ENDDNE}\n\\def\\@Aboxed#1&#2\\ENDDNE{%\n   &\n   \\settowidth\\@tempdima{$\\displaystyle#1{}$}\n   \\setlength\\@tempdima{\\@tempdima+\\fboxsep+\\fboxrule}\n   \\kern-\\@tempdima\n   \\boxed{#1#2}\n}\n\\makeatother\n\n\\begin{document}\n\n\\title{Homework 24, Section 4.6: 2, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 21, 24}\n\\author{Alex Gordon}\n\\date{\\today}\n\\maketitle\n\\section*{Homework}\n\\subsection*{2.}\nRank $A = 2$ \\\\\n$dim Nul = 2$ \\\\\n\nbasis for Col A is $\\begin{bmatrix}  1 \\\\ 2 \\\\ 3 \\\\ 3  \\end{bmatrix}, \\begin{bmatrix}  4 \\\\ 6 \\\\ 3 \\\\ 0  \\end{bmatrix}, \\begin{bmatrix}  2 \\\\ -3 \\\\ -3 \\\\ 0  \\end{bmatrix}$ and the Basis for Row A is (1,3,4,-1,2), (0,0,1,-1,1), (0,0,0,0,-5)\n\n\n\\subsection*{6.}\n3, 2, 2. \n\\subsection*{7.}\nYes; no. Since Col A is a four-dimensional subspace of $R^4$, it coincides with $R^4$. It can then be concluded that the null space cannot be $R^3$ because it is a different dimension, and because the vectors in Nul A have 7 entries. Nul A is a 3 dimensional subspace of $R^7$ by the rank theorem. \n\\subsection*{8.}\n4. It is impossible for Column A to be in $R^4$ because the vectors in Col A have 6 entries and Col A is a $R^4$ subspace of $R^6$. \n\\subsection*{9.}\n3, no. Since the columns of a 4 x 6 matrix are in $R^4$, rather than $R^3$,  Cal A is a 3 dimensional subspace of $R^4$. \n\\subsection*{10.}\n2\n\\subsection*{11.}\n2\n\\subsection*{12.}\n2\n\\subsection*{13.}\n5, 5 in both cases. Since the number of pivots cannot exceed the number of columns or the number of rows, it is the same. \n\\subsection*{14.}\n4, 4. If A is a 5 x 4 matrix, its rows are in $R^4$ and there can be at most four linearly independent vectors in such a set. If A was a 4 x 5 matrix, then it cannot have more than four linearly independent rows because it obviously only has 4 rows. \n\\subsection*{15.}\n4. \n\\subsection*{16.}\n0\n\\subsection*{21.}\nNo. \n\\subsection*{24.}\nThe coefficient matrix A in this case is a 7 by 6 matrix. Consider the case B in $R^7$, and the equation $Ax = b$. The equation must have a unique solution. However, since there are no free variables, the rank of A must equal the number of columns. Since the rank of A cannot exceed 6, and Col A must be a subspace of $R^7$, there must exist vectors in $R^7$ that are not in Col A. This means that the equation $Ax = b$\n\n\n\\end{document}", "meta": {"hexsha": "024c029972e5b40d415b24d2f164ebbbcb8358cc", "size": 2422, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "LinearAlgebra/Homework24.tex", "max_stars_repo_name": "alexggordon/latex", "max_stars_repo_head_hexsha": "7dd945f33490e6585e26cff39d9cf6ad8f582a0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LinearAlgebra/Homework24.tex", "max_issues_repo_name": "alexggordon/latex", "max_issues_repo_head_hexsha": "7dd945f33490e6585e26cff39d9cf6ad8f582a0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LinearAlgebra/Homework24.tex", "max_forks_repo_name": "alexggordon/latex", "max_forks_repo_head_hexsha": "7dd945f33490e6585e26cff39d9cf6ad8f582a0e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.4912280702, "max_line_length": 419, "alphanum_fraction": 0.6837324525, "num_tokens": 891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.3152407215445011}}
{"text": "\\chapter{Gravitational Instability and Collapse}\n\\label{ch:collapse}\n\n\\marginnote{\n\\textbf{Suggested background reading:}\n\\begin{itemize}\n\\item \\href{http://adsabs.harvard.edu/abs/2014arXiv1402.0867K}{Krumholz, M.~R. 2014, Phys.~Rep., 539, 49}, section 3.4 \\nocite{krumholz14c}\n\\end{itemize}\n}\n\nThe previous two chapters provided a whirlwind tour of fluid dynamics and turbulence. However, in that discussion we completely omitted gravity, which is obviously critical to the process of star formation. We will now remedy that omission by bringing gravity back into the discussion.\n\n\\section{The Virial Theorem}\n\nTo open this topic, we will start by proving a powerful and general theorem about the behavior of fluids, known as the virial theorem.\\footnote{Like the equations of motion, there is both an Eulerian form and a Lagrangian form of the virial theorem, depending on which version of the equations of motion we start with. We will derive the Eulerian form here, following the original proof by \\citet{mckee92a}, but the derivation of the Lagrangian form proceeds in a similar manner, and can be found in many standard textbooks, for example \\citet{shu92a}.} To derive the virial theorem, we begin with the MHD equations of motion, without either viscosity or resistivity (since neither of these are important for GMCs on large scales) but with gravity. We leave in the pressure forces, even though they are small, because they are also trivial to include. Thus we have\n\\begin{eqnarray}\n\\frac{\\partial\\rho}{\\partial t} & = & -\\nabla \\cdot (\\rho \\vecv) \\\\\n\\frac{\\partial}{\\partial t}(\\rho \\vecv) & = & -\\nabla\\cdot(\\rho\\vecv\\vecv) -\\nabla P + \\frac{1}{4\\pi} (\\nabla\\times\\vecB)\\times\\vecB - \\rho \\nabla \\phi.\n\\end{eqnarray}\nHere $\\phi$ is the gravitational potential, so $-\\rho \\nabla \\phi$ is the gravitational force per unit volume. These equations are the Eulerian equations written in conservative form.\n\nBefore we begin, life will be a bit easier if we re-write the entire second equation in a manifestly tensorial form -- this simplifies the analysis tremendously. To do so, we define two tensors: the fluid pressure tensor $\\vecPi$ and the Maxwell stress tensor $\\vecT_M$, as follows:\n\\begin{eqnarray}\n\\vecPi & \\equiv & \\rho \\vecv\\vecv + P\\vecI \\\\\n\\vecT_M & \\equiv & \\frac{1}{4\\pi} \\left(\\vecB\\vecB - \\frac{B^2}{2}\\vecI\\right)\n\\end{eqnarray}\nHere $\\vecI$ is the identity tensor. In tensor notation, these are\n\\begin{eqnarray}\n(\\vecPi)_{ij} & \\equiv & \\rho v_i v_j + P \\delta_{ij} \\\\\n(\\vecT_M)_{ij} & \\equiv & \\frac{1}{4\\pi} \\left(B_i B_j - \\frac{1}{2}B_k B_k \\delta_{ij}\\right).\n\\end{eqnarray}\nWith these definitions, the momentum equation just becomes\n\\begin{equation}\n\\frac{\\partial}{\\partial t}(\\rho \\vecv) = -\\nabla\\cdot(\\vecPi-\\vecT_M) - \\rho \\nabla\\phi.\n\\end{equation}\n\nThe substitution for $\\vecPi$ is obvious. The equivalence of $\\nabla\\cdot\\vecT_M$ to $1/(4\\pi) (\\nabla\\times\\vecB)\\times\\vecB$ is easy to establish with a little vector manipulation, which is most easily done in tensor notation:\n\\begin{eqnarray}\n(\\nabla\\times\\vecB)\\times\\vecB & = & \\epsilon_{ijk} \\epsilon_{jmn} \\left(\\frac{\\partial}{\\partial x_m}B_n\\right) B_k \\\\\n& = & -\\epsilon_{jik} \\epsilon_{jmn} \\left(\\frac{\\partial}{\\partial x_m}B_n\\right) B_k \\\\\n& = & (\\delta_{in}\\delta_{km}-\\delta_{im}\\delta_{kn})\\left(\\frac{\\partial}{\\partial x_m}B_n\\right) B_k \\\\\n& = & B_k\\frac{\\partial}{\\partial x_k} B_i - B_k\\frac{\\partial}{\\partial x_i} B_k \\\\\n& = & \\left(B_k\\frac{\\partial}{\\partial x_k} B_i + B_i \\frac{\\partial}{\\partial x_k} B_k\\right) - B_k\\frac{\\partial}{\\partial x_i} B_k \\\\\n& = & \\frac{\\partial}{\\partial x_k}\\left(B_i B_k\\right) -\\frac{1}{2} \\frac{\\partial}{\\partial x_i} \\left(B_k^2\\right)\\\\\n& = & \\nabla\\cdot \\left(\\vecB\\vecB - \\frac{B^2}{2}\\vecI\\right).\n\\end{eqnarray}\n\nTo derive the virial theorem, we begin by imagining a cloud of gas enclosed by some fixed volume $V$. The surface of this volume is $S$. We want to know how the overall distribution of mass changes within this volume, so we begin by writing down a quantity the represents the mass distribution. This is the moment of inertia,\n\\begin{equation}\nI = \\int_V \\rho r^2\\, dV.\n\\end{equation}\n\nWe want to know how this changes in time, so we take its time derivative:\n\\begin{eqnarray}\n\\dot{I} & = & \\int_V \\frac{\\partial\\rho}{\\partial t} r^2 \\,dV \\\\\n& = & -\\int_V \\nabla \\cdot (\\rho \\vecv) r^2\\, dV \\\\\n& = & -\\int_V \\nabla \\cdot (\\rho \\vecv r^2)\\, dV + 2\\int_V \\rho \\vecv\\cdot \\vecr\\, dV \\\\\n& = & -\\int_S (\\rho \\vecv r^2)\\cdot d\\vecS + 2\\int_V \\rho \\vecv\\cdot \\vecr\\, dV.\n\\end{eqnarray}\nIn the first step we used the fact that the volume $V$ does not vary in time to move the time derivative inside the integral. Then in the second step we used the equation of mass conservation to substitute. In the third step we brought the $r^2$ term inside the divergence. Finally in the fourth step we used the divergence theorem to replace the volume integral with a surface integral.\n\nNow we take the time derivative again, and multiply by $1/2$ for future convenience:\n\\begin{eqnarray}\n\\frac{1}{2}\\ddot{I} & = & -\\frac{1}{2} \\int_S r^2 \\frac{\\partial}{\\partial t}(\\rho\\vecv)\\cdot d\\vecS +\n\\int_V \\frac{\\partial}{\\partial t}(\\rho\\vecv)\\cdot\\vecr \\, dV \\\\\n& = & -\\frac{1}{2} \\frac{d}{dt} \\int_S r^2 (\\rho\\vecv)\\cdot d\\vecS \n\\nonumber \\\\\n& & \\quad {} -\n\\int_V \\vecr \\cdot \\left[\\nabla\\cdot(\\vecPi-\\vecT_M)+ \\rho\\nabla \\phi \\right] \\, dV.\n\\end{eqnarray}\nThe term involving the tensors is easy to simplify using a handy identity, which applies to an arbitrary tensor. This is a bit easier to follow in tensor notation:\n\\begin{eqnarray}\n\\int_V \\vecr\\cdot \\nabla\\cdot \\vecT \\, dV & = & \\int_V x_i \\frac{\\partial}{\\partial x_j} T_{ij}\\,dV \\\\\n& = & \\int_V \\frac{\\partial}{\\partial x_j}(x_i T_{ij})\\,dV - \\int_V T_{ij} \\frac{\\partial}{\\partial x_j}x_i \\, dV \\\\\n& = & \\int_S x_i T_{ij} \\,dS_j - \\int_V \\delta_{ij} T_{ij} \\, dV \\\\\n& = & \\int_S \\vecr\\cdot\\vecT\\cdot d\\vecS - \\int_V \\mbox{Tr}\\; \\vecT \\, dV,\n\\end{eqnarray}\nwhere $\\mbox{Tr}\\;\\vecT = T_{ii}$ is the trace of the tensor $\\vecT$.\n\nApplying this to our result our tensors, we note that\n\\begin{eqnarray}\n\\mbox{Tr}\\; \\vecPi & = & 3P + \\rho v^2 \\\\\n\\mbox{Tr}\\; \\vecT_M & = & -\\frac{B^2}{8\\pi}\n\\end{eqnarray}\nInserting this result into our expression for $\\ddot{I}$ gives the virial theorem, which we will write in a more suggestive form to make its physical interpretation clearer:\n\\begin{equation}\n\\frac{1}{2}\\ddot{I} = 2(\\mathcal{T} - \\mathcal{T}_S) + \\mathcal{B} + \\mathcal{W} - \\frac{1}{2}\\frac{d}{dt} \\int_S (\\rho\\vecv r^2)\\cdot d\\vecS,\n\\end{equation}\nwhere\n\\begin{eqnarray}\n\\mathcal{T} & = & \\int_V\\left(\\frac{1}{2}\\rho v^2 + \\frac{3}{2} P\\right)\\, dV \\\\\n\\mathcal{T}_S & = & \\int_S \\vecr \\cdot \\vecPi \\cdot d\\vecS\\\\\n\\mathcal{B} & = & \\frac{1}{8\\pi} \\int_V B^2 \\,dV + \\int_S \\vecr\\cdot \\vecT_M\\cdot d\\vecS\\\\\n\\mathcal{W} & = & -\\int_V \\rho \\vecr\\cdot\\nabla\\phi\\,dV.\n\\end{eqnarray}\n\nWritten this way, we can give a clear interpretation to what these terms mean. $\\mathcal{T}$ is just the total kinetic plus thermal energy of the cloud. $\\mathcal{T}_S$ is the confining pressure on the cloud surface, including both the thermal pressure and the ram pressure of any gas flowing across the surface. $\\mathcal{B}$ is the the difference between the magnetic pressure in the cloud interior, which tries to hold it up, and the magnetic pressure plus magnetic tension at the cloud surface, which try to crush it. $\\mathcal{W}$ is the gravitational energy of the cloud. If there is no external gravitational field, and $\\phi$ comes solely from self-gravity, then $\\mathcal{W}$ is just the gravitational binding energy. The final integral represents the rate of change of the momentum flux across the cloud surface.\n\n$\\ddot{I}$ is the integrated form of the acceleration. For a cloud of fixed shape, it tells us the rate of change of the cloud's expansion or contraction. If it is negative, the terms that are trying to collapse the cloud (the surface pressure, magnetic pressure and tension at the surface, and gravity) are larger, and the cloud accelerates inward. If it is positive, the terms that favor expansion (thermal pressure, ram pressure, and magnetic pressure) are larger, and the cloud accelerates outward. If it is zero, the cloud neither accelerates nor decelerates.\n\nWe get a particularly simple form of the virial theorem if there is no gas crossing the cloud surface (so $\\vecv=0$ at $S$) and if the magnetic field at the surface to be a uniform value $B_0$. In this case the virial theorem reduces to\n\\begin{equation}\n\\frac{1}{2}\\ddot{I} = 2(\\mathcal{T} - \\mathcal{T}_S) + \\mathcal{B} + \\mathcal{W}\n\\end{equation}\nwith\n\\begin{eqnarray}\n\\mathcal{T}_S & = & \\int_S rP \\,dS\\\\\n\\mathcal{B} & = & \\frac{1}{8\\pi} \\int_V (B^2-B_0^2) \\,dV.\n\\end{eqnarray}\nFor this simplified physical setup, $\\mathcal{T}_S$ just represents the mean radius times pressure at the virial surface, and $\\mathcal{B}$ just represents the total magnetic energy of the cloud minus the magnetic energy of the background field over the same volume. Notice that, if a cloud is in equilibrium ($\\ddot{I}=0$) and magnetic and surface forces are negligible, then we have $2\\mathcal{T} = -\\mathcal{W}$. Based on this result, we define the virial ratio\n\\begin{equation}\n\\label{eq:alpha_vir_th}\n\\alpha_{\\rm vir} = \\frac{2\\mathcal{T}}{|\\mathcal{W}|}.\n\\end{equation}\nFor an object for which magnetic and surface forces are negligible, and with no flow across the virial surface, a value of $\\alpha_{\\rm vir} > 1$ implies $\\ddot{I} > 0$, and a value $\\alpha_{\\rm vir} < 1$ implies $\\ddot{I}<0$. Thus $\\alpha_{\\rm vir} = 1$ roughly divides clouds that have enough internal pressure or turbulence to avoid collapse from those that do not.\n\n\\section{Stability Conditions}\n\nArmed with the virial theorem, we are now in a position to understand, at least qualitatively, under what conditions a cloud of gas will be stable against gravitational contraction, and under what conditions it will not be. If we examine the terms on the right hand side of the virial theorem, we can group them into those that are generally or always positive, and thus oppose collapse, and those that are generally or always negative, and thus encourage it. The main terms opposing collapse are $\\mathcal{T}$, which contains parts describing both thermal pressure and turbulent motion, and $\\mathcal{B}$, which describes magnetic pressure and tension. The main terms favoring collapse are $\\mathcal{W}$, representing self-gravity, and $\\mathcal{T}_S$, representing surface pressure. The final term, the surface one, could be positive or negative depending on whether mass is flowing into our out of the virial volume. We will begin by examining the balance among these terms, and the forces they represent.\n\n\\subsection{Thermal Support and the Jeans Instability}\n\nGas pressure is perhaps the most basic force in opposing collapse. Unlike turbulent motions, which can compress in some places even as they provide overall support, gas pressure always tries to smooth out the gas. Similarly, self-gravity is the most reliable promoter of collapse. A full, formal analysis of the interaction between pressure and self-gravity was provided by James Jeans in 1902 \\citep{jeans02a}, and we will go through it below. However, we can already see what the basic result will have to look like just from the virial theorem. We expect the dividing line between stability and instability to lie at $\\alpha_{\\rm vir} \\approx 1$. For an isolated, isothermal cloud of mass $M$ and radius $R$ with only thermal pressure, we have\n\\begin{eqnarray}\n\\mathcal{T} & = & \\frac{3}{2} M c_s^2 \\\\\n\\mathcal{W} & = & -a \\frac{GM^2}{R},\n\\end{eqnarray}\nwhere $a$ is a factor of order unity that depends on the internal density structure. Thus the condition $\\alpha_{\\rm vir} \\gtrsim 1$ corresponds to\n\\begin{equation}\nM c_s^2 \\gtrsim \\frac{GM^2}{R} \\qquad\\Longrightarrow\\qquad R \\gtrsim \\frac{GM}{c_s^2},\n\\end{equation}\nor, rewriting in terms of the mean density $\\rho \\sim M/R^3$,\n\\begin{equation}\nR \\lesssim \\frac{c_s}{\\sqrt{G\\rho}}.\n\\end{equation}\n\nThe formal analysis proceeds as follows. Consider a uniform, infinite, isothermal medium at rest. The density is $\\rho_0$, the pressure is $P_0 = \\rho_0 c_s^2$, and the velocity is $\\vecv_0 = 0$. We will write down the equations of hydrodynamics and self-gravity for this gas:\n\\begin{eqnarray}\n\\frac{\\partial}{\\partial t}\\rho + \\nabla\\cdot (\\rho \\vecv) & = & 0 \\\\\n\\frac{\\partial}{\\partial t}(\\rho\\vecv) + \\nabla\\cdot(\\rho \\vecv\\vecv) & = & -\\nabla P - \\rho \\nabla \\phi \\\\\n\\nabla^2 \\phi & = & 4\\pi G\\rho.\n\\end{eqnarray}\n\nHere the first equation represents conservation of mass, the second represents conservation of momentum, and the third is the Poisson equation for the gravitational potential $\\phi$. We take the background density $\\rho_0$, velocity $\\vecv_0 = 0$, pressure $P_0$, and potential $\\phi_0$ to be an exact solution of these equations, so that all time derivatives are zero as long as the gas is not disturbed.\n\nNote that this involves the \"Jeans swindle\": this assumption is actually not really consistent, because the Poisson equation cannot be solved for an infinite uniform medium unless $\\rho_0 = 0$. In other words, there is no function $\\phi_0$ such that $\\nabla^2\\phi_0$ is equal to a non-zero constant value on all space. That said, we will ignore this complication, since the approximation of a uniform infinite medium is a reasonable one for a very large but finite uniform medium. It is possible to construct the argument without the Jeans swindle, but doing so adds mathematical encumbrance without physical insight, so we will not do so.\n\nThat digression aside, now let us consider what happens if we perturb this system. We will write the density as $\\rho = \\rho_0 + \\epsilon \\rho_1$, where $\\epsilon\\ll 1$. Similarly, we write $\\vecv=\\epsilon \\vecv_1$ and $\\phi=\\phi_0 + \\epsilon \\phi_1$. Since we can always use Fourier analysis to write an arbitrary perturbation as a sum of Fourier components, without loss of generality we will take the perturbation to be a single, simple Fourier mode. The reason to do this is that, as we will see, differential equations are trivial to solve when the functions in question are simple plane waves.\n\nThus we write $\\rho_1 = \\rho_a \\exp[i(kx - \\omega t)]$. Note that we implicitly understand that we use only the real part of this exponential. It is just easier to write things in terms of an $e^{i(kx-\\omega t)}$ than it is to keep track of a bunch of sines and cosines. In writing this equation, we have chosen to orient our coordinate system so that the wave vector $\\veck$ of the perturbation is in the $\\vecx$ direction. Again, there is no loss of generality in doing so.\n\nGiven this density perturbation, what is the corresponding perturbation to the potential? From the Poisson equation, we have\n\\begin{equation}\n\\nabla^2 (\\phi_0 + \\epsilon \\phi_1) = 4\\pi G (\\rho_0 + \\epsilon \\rho_1).\n\\end{equation}\nSince by assumption $\\rho_0$ and $\\phi_0$ are exact solutions to the Poisson equation, we can cancel the $\\phi_0$ and $\\rho_0$ terms out of the equation, leaving\n\\begin{equation}\n\\nabla^2 \\phi_1 = 4 \\pi G \\rho_1 = 4\\pi G \\rho_a e^{i(kx-\\omega t)}.\n\\end{equation}\nThis equation is trivial to solve, since it is just of the form $y'' = a e^{bx}$. The solution is\n\\begin{equation}\n\\phi_1 = -\\frac{4\\pi G \\rho_a}{k^2} e^{i(kx - \\omega t)}.\n\\end{equation}\nBy analogy to what we did for $\\rho_1$, we write this solution as $\\phi_1 = \\phi_a e^{i(kx-\\omega t)}$, with\n\\begin{equation}\n\\phi_a = -\\frac{4\\pi G \\rho_a}{k^2}.\n\\end{equation}\n\nNow that we have found the perturbed potential, let us determine what motion this will induce in the fluid. To do so, we first take the equations of mass and momentum conservation and we linearize them. This means that we substitute in $\\rho = \\rho_0 + \\epsilon \\rho_1$, $\\vecv=\\epsilon \\vecv_1$, $P=P_0+\\epsilon P_1=c_s^2 (\\rho_0 + \\epsilon \\rho_1)$, and $\\phi=\\phi_0+\\epsilon \\phi_1$. Note that $\\vecv_0 = 0$. We then expand the equations in powers of $\\epsilon$, and we drop all the terms that are of order $\\epsilon^2$ or higher on the grounds that they become negligible in the limit of small $\\epsilon$.\n\nLinearizing the equation of mass conservation we get\n\\begin{eqnarray}\n\\frac{\\partial}{\\partial t} (\\rho_0 + \\epsilon \\rho_1) + \\nabla\\cdot [(\\rho_0 + \\epsilon \\rho_1)(\\epsilon\\vecv_1)] & = & 0 \\\\\n\\frac{\\partial}{\\partial t} \\rho_0 + \\epsilon \\frac{\\partial}{\\partial t} \\rho_1 + \\epsilon \\nabla \\cdot (\\rho_0\\vecv_1) & = & 0 \\\\\n\\frac{\\partial}{\\partial t} \\rho_1+ \\nabla \\cdot (\\rho_0\\vecv_1) & = & 0.\n\\label{eq:masscons_linear}\n\\end{eqnarray}\nIn the second step, we dropped a term of order $\\epsilon^2$. In the third step we used the fact that $\\rho_0$ is constant, i.e., that the background density has zero time derivative, to drop that term. Applying the same procedure to the momentum equation, we get\n\\begin{eqnarray}\n\\nonumber\n\\lefteqn{\n\\frac{\\partial}{\\partial t} [(\\rho_0 + \\epsilon \\rho_1)(\\epsilon\\vecv_1)] + \\nabla\\cdot [(\\rho_0 + \\epsilon \\rho_1)(\\epsilon\\vecv_1)(\\epsilon\\vecv_1)] \n}\n\\qquad\\qquad\\qquad\n\\\\\n& = & -c_s^2 \\nabla (\\rho_0 + \\epsilon \\rho_1) \\nonumber \\\\\n& & \\qquad {} - (\\rho_0 + \\epsilon\\rho_1)\\nabla (\\phi_0 + \\epsilon \\phi_1)\n\\\\\n\\epsilon \\frac{\\partial}{\\partial t} (\\rho_0\\vecv_1) & = & -c_s^2 \\nabla \\rho_0 - \\rho_0 \\nabla\\phi_0\n\\nonumber \\\\\n& & \\qquad {}\n- \\epsilon \\left(c_s^2 \\nabla \\rho_1 + \\rho_1\\nabla \\phi_0 + \\rho_0\\nabla \\phi_1\\right) \\\\\n\\frac{\\partial}{\\partial t} (\\rho_0\\vecv_1) & = & -c_s^2 \\nabla \\rho_1 - \\rho_0\\nabla\\phi_1.\n\\label{eq:momcons_linear}\n\\end{eqnarray}\nIn the second step we dropped terms of order $\\epsilon^2$, and in the third step we used the fact that the background state is uniform to drop terms involving gradients of $\\rho_0$ and $\\phi_0$.\n\nNow that we have our linearized equations, we're ready to find out what $\\vecv_1$ must be. By analogy to what we did for $\\rho_1$ and $\\phi_1$, we take $\\vecv_1$ to be a single Fourier mode, of the form\n\\begin{equation}\n\\vecv_1 = \\vecv_a e^{i(kx-\\omega t)}\n\\end{equation}\nSubstituting for $\\rho_1$, $\\phi_1$, and $\\vecv_1$ into the linearized mass conservation equation (\\ref{eq:masscons_linear}), we get\n\\begin{eqnarray}\n\\frac{\\partial}{\\partial t} \\left(\\rho_a e^{i(kx-\\omega t)}\\right) + \\nabla\\cdot (\\rho_0 \\vecv_a e^{i(kx-\\omega t)}) & = & 0 \\\\\n-i\\omega \\rho_a e^{i(kx-\\omega t)} + i k \\rho_0 v_{a,x} e^{i(kx-\\omega t)} & = & 0 \\\\\n-\\omega\\rho_a + k\\rho_0 v_{a,x} & = & 0 \\\\\n\\frac{\\omega\\rho_a}{k\\rho_0} & = & v_{a,x}\n\\end{eqnarray}\nwhere $v_{a,x}$ is the $x$ component of $\\vecv_a$.\n\nWe have now found the velocity perturbation in terms of $\\rho_a$, $\\omega$, and $k$. Similarly substituting into the linearized momentum equation (\\ref{eq:momcons_linear}) gives\n\\begin{eqnarray}\n\\frac{\\partial}{\\partial t} \\left(\\rho_0 \\vecv_a e^{i(kx-\\omega t)}\\right) & = & -c_s^2 \\nabla(\\rho_a e^{i(kx-\\omega t)})\n\\nonumber \\\\\n& & \\qquad {}\n - \\rho_0 \\nabla (\\phi_a e^{i(kx-\\omega t)}) \\\\\n-i\\omega \\rho_0 \\vecv_a e^{i(kx-\\omega t)} & = & -i k c_s^2 \\rho_a \\hat{\\mathbf{x}} e^{i(kx-\\omega t)} \n\\nonumber \\\\\n& & \\qquad {}\n- i k \\rho_0 \\phi_a e^{i(kx-\\omega t)} \\hat{\\mathbf{x}}\\\\\n\\omega \\rho_0 v_{a,x} & = & k \\left(c_s^2 \\rho_a + \\rho_0 \\phi_a\\right).\n\\end{eqnarray}\nNow let us take this equation and substitute in the values for $\\phi_a$ and $v_{a,x}$ that we previously determined:\n\\begin{eqnarray}\n\\omega \\rho_0 \\left(\\frac{\\omega\\rho_a}{k\\rho_0}\\right) & = & k c_s^2 \\rho_a - k\\rho_0 \\left(\\frac{4\\pi G \\rho_a}{k^2}\\right) \\\\\n\\omega^2 & = & c_s^2 k^2 - 4\\pi G \\rho_0\n\\end{eqnarray}\nThis expression is known as a dispersion relation, because it describes the dispersion of the plane wave solution we have found, i.e., how that wave's spatial frequency $k$ relates to its temporal frequency $\\omega$. \n\nTo see what this implies, let us consider what happens when we put in a perturbation with a short wavelength or a large spatial frequency. In this case $k$ is large, and $c_s^2 k^2 - 4\\pi G \\rho_0>0$, so $\\omega$ is a positive or negative real number. The density is $\\rho=\\rho_0 + \\rho_a e^{i(kx-\\omega t)}$, which represents a uniform background density with a small oscillation in space and time on top of it. Since $|e^{i(kx-\\omega t)}| < 1$ at all times and places, the oscillation does not grow.\n\nOn the other hand, suppose that we impose a perturbation with a large spatial range, or a small spatial frequency. In this case $c_s^2 k^2 - 4\\pi G \\rho_0<0$, so $\\omega$ is a positive or negative imaginary number. For an imaginary $\\omega$, $|e^{-i\\omega t}|$ either decays to zero or grows infinitely large in time, depending on whether we take the positive or negative imaginary root. Thus at least one solution for the perturbation will not remain small. It will grown in amplitude without limit.\n\nThis represents an instability: if we impose an arbitrarily small amplitude perturbation on the density at a sufficiently large wavelength, that perturbation will eventually grow to be large. Of course once $\\rho_1$ becomes large enough, our linearization procedure of dropping terms proportional to $\\epsilon^2$ becomes invalid, since these terms are no longer small. In this case we must follow the full non-linear behavior of the equations, usually with simulations.\n\nWe have, however, shown that there is a critical size scale beyond which perturbations that are stabilized only by pressure must grow to non-linear amplitude. The critical length scale is set by the value of $k$ for which $\\omega=0$,\n\\begin{equation}\nk_J = \\sqrt{\\frac{4\\pi G\\rho_0}{c_s^2}}.\n\\end{equation}\nThe corresponding wavelength is\n\\begin{equation}\n\\lambda_J = \\frac{2\\pi}{k_J} = \\sqrt{\\frac{\\pi c_s^2}{G\\rho_0}}.\n\\end{equation}\nThis is known as the Jeans length. One can also define a mass scale associated with this: the Jeans mass, $M_J=\\rho\\lambda_J^3/8$.\\footnote{The definition of the Jeans mass is somewhat ambiguous, and multiple definitions can be found in the literature. The one we have chosen corresponds to considering the mass within a cube of half a Jeans length in size. Possible alternatives include choosing a cube one Jeans length in size or choosing a sphere one Jeans length in radius or diameter, to name just two possibilities. These definitions all scale with density and Jeans length in the same way, and differ only in their coefficients.}\n\nIf we plug in some typical numbers for a GMC, $c_s=0.2$ km s$^{-1}$ and $\\rho_0 = 100 m_p\\mbox{ cm}^{-3}$, we get $\\lambda_J = 3.4$ pc. Since every GMC we have seen is larger than this size, and there are clearly always perturbations present, this means that molecular clouds cannot be stabilized by gas pressure against collapse. Of course one could have guessed this result just by evaluating terms in the virial theorem: the gas pressure term is very small compared to the gravitational one. Ultimately, the virial theorem and the Jeans instability analysis are just two different ways of extracting the same information from the equations of motion.\n\nOne nice thing about the Jeans analysis, however, is that it makes it obvious how fast we should expect gravitational instabilities to grow. Suppose we have a very unstable system, where $c_s^2 k^2 \\ll 4 \\pi G \\rho_0$. This is the case for GMC, for example. There are perturbations on the size of the entire cloud, which might be 50 pc in size. This is a spatial frequency $k=2\\pi/(50\\mbox{ pc}) = 0.12$ pc$^{-1}$. Plugging this in with $c_s = 0.2$ km s$^{-1}$ and $\\rho_0=100 m_p\\mbox{ cm}^{-3}$ gives $c_s^2 k^2 / (4\\pi G \\rho) = 0.005$.\nIn this case we have\n\\begin{equation}\n\\omega \\approx \\pm i \\sqrt{4\\pi G\\rho_0}.\n\\end{equation}\n\nTaking the negative $i$ root, which corresponds to the growing mode, we find that\n\\begin{equation}\n\\rho_1 \\propto \\exp([4\\pi G \\rho_0]^{1/2} t).\n\\end{equation}\nThus the $e$-folding time for the disturbance to grow is $\\sim 1/\\sqrt{G\\rho_0}$. We define the free-fall time as\n\\begin{equation}\nt_{\\rm ff} = \\sqrt{\\frac{3\\pi}{32 G \\rho_0}},\n\\end{equation}\nwhere the numerical coefficient of $\\sqrt{3\\pi/32}$ comes from doing the closely related problem of the collapse of a pressureless sphere, which we will cover in Section \\ref{sec:pressureless_collapse}. The free-fall time is the characteristic time scale required for a medium with negligible pressure support to collapse.\n\nThe Jeans analysis is of course only appropriate for a uniform medium, and it requires the Jeans swindle. Problem Set 2 contains a calculation of the maximum mass of a spherical cloud that can support itself against collapse by thermal pressure, called the Bonnor-Ebert mass \\citep{ebert55a, bonnor56a}. Not surprisingly, the Bonnor-Ebert mass is simply $M_J$ times factors of order unity.\n\n\\subsection{Magnetic Support and the Magnetic Critical Mass}\n\nWe now examine another term that generally opposes collapse: the magnetic one. Let us consider a uniform spherical cloud of radius $R$ threaded by a magnetic field $\\vecB$. We imagine that $\\vecB$ is uniform inside the cloud, but that outside the cloud the field lines quickly spread out, so that the magnetic field drops down to some background strength $\\vecB_0$, which is also uniform but has a magnitude much smaller than $\\vecB$.\n\nHere it is easiest to work directly with the virial theorem. The magnetic term in the virial theorem is\n\\begin{equation}\n\\mathcal{B} = \\frac{1}{8\\pi} \\int_V B^2 \\,dV + \\int_S \\vecr \\cdot \\vecT_M \\cdot d\\vecS\n\\end{equation}\nwhere\n\\begin{equation}\n\\vecT_M = \\frac{1}{4\\pi} \\left(\\vecB\\vecB - \\frac{B^2}{2}\\vecI\\right).\n\\end{equation}\n\nIf the field inside the cloud is much larger than the field outside it, then the first term, representing the integral of the magnetic pressure within the cloud, is\n\\begin{equation}\n\\frac{1}{8\\pi} \\int_V B^2\\, dV \\approx \\frac{B^2 R^3}{6}.\n\\end{equation}\nHere we have dropped any contribution from the field outside the cloud. The second term, representing the surface magnetic pressure and tension, is\n\\begin{equation}\n\\int_S \\vecx \\cdot \\vecT_M \\cdot d\\vecS = \\int_S \\frac{B_0^2}{8\\pi} \\vecx \\cdot d\\vecS\n\\approx \\frac{B_0^2 R_0^3}{6}\n\\end{equation}\n\nSince the field lines that pass through the cloud must also pass through the virial surface, it is convenient to rewrite everything in terms of the magnetic flux. The flux passing through the cloud is $\\Phi_B = \\pi B R^2$, and since these field lines must also pass through the virial surface, we must have $\\Phi_B = \\pi B_0 R_0^2$ as well. Thus, we can rewrite the magnetic term in the virial theorem as\n\\begin{equation}\n\\mathcal{B} \\approx \\frac{B^2 R^3}{6} - \\frac{B_0^2 R_0^3}{6} = \\frac{1}{6\\pi^2} \\left(\\frac{\\Phi_B^2}{R} - \\frac{\\Phi_B^2}{R_0}\\right) \\approx \\frac{\\Phi_B^2}{6\\pi^2 R}.\n\\end{equation}\n\nIn the last step we used the fact that $R \\ll R_0$ to drop the $1/R_0$ term. Now let us compare this to the gravitational term, which is\n\\begin{equation}\n\\mathcal{W} = -\\frac{3}{5} \\frac{GM^2}{R}\n\\end{equation}\nfor a uniform cloud of mass $M$. Comparing these two terms, we find that\n\\begin{equation}\n\\mathcal{B}+\\mathcal{W} = \\frac{\\Phi_B^2}{6\\pi^2 R} - \\frac{3}{5} \\frac{GM^2}{R} \\equiv \\frac{3}{5}\\frac{G}{R} \\left(M_{\\Phi}^2-M^2\\right)\n\\end{equation}\nwhere\n\\begin{equation}\n\\label{eq:mphi}\nM_{\\Phi} \\equiv \\sqrt{\\frac{5}{2}} \\left(\\frac{\\Phi_B}{3 \\pi G^{1/2}}\\right)\n\\end{equation}\nWe call $M_{\\Phi}$ the magnetic critical mass. Since $\\Phi_B$ does not change as a cloud expands or contracts (due to flux-freezing), this magnetic critical mass does not change either.\n\nThe implication of this is that clouds that have $M>M_{\\Phi}$ always have $\\mathcal{B}+\\mathcal{W} < 0$. The magnetic force is unable to halt collapse no matter what. Clouds that satisfy this condition are called magnetically supercritical, because they are above the magnetic critical mass $M_{\\Phi}$. Conversely, if $M<M_{\\Phi}$, then $\\mathcal{B}+\\mathcal{W} > 0$, and gravity is weaker than magnetism. Clouds satisfying this condition are called subcritical.\n\nFor a subcritical cloud, since $\\mathcal{B}+\\mathcal{W} \\propto 1/R$, this term will get larger and larger as the cloud shrinks. In other words, not only is the magnetic force resisting collapse is stronger than gravity, it becomes larger and larger without limit as the cloud is compressed to a smaller radius. Unless the external pressure is also able to increase without limit, which is unphysical, then there is no way to make a magnetically subcritical cloud collapse. It will always stabilize at some finite radius. The only way to get around this is to change the magnetic critical mass, which requires changing the magnetic flux through the cloud. This is possible only via ion-neutral drift or some other non-ideal MHD effect that violates flux-freezing.\n\nOf course our calculation is for a somewhat artificial configuration of a spherical cloud with a uniform magnetic field. In reality a magnetically-supported cloud will not be spherical, since the field only supports it in some directions, and the field will not be uniform, since gravity will always bend it some amount. Figuring out the magnetic critical mass in that case requires solving for the cloud structure numerically. A calculation of this effect by \\citet{tomisaka98a} gives\n\\begin{equation}\nM_{\\Phi} = 0.12\\frac{\\Phi_B}{G^{1/2}}\n\\end{equation}\nfor clouds for which pressure support is negligible. The numerical coefficient we obtained for the uniform cloud case (equation \\ref{eq:mphi}) is $0.17$, so this is obviously a small correction. It is also possible to derive a combined critical mass that incorporates both the flux and the sound speed, and which limits to the Bonnor-Ebert mass for negligible field and the magnetic critical mass for negligible pressure.\n\nIt is not so easy to determine observationally whether the magnetic fields are strong enough to hold up molecular clouds.  The observations are somewhat complicated by the fact that, using the most common technique of Zeeman splitting, one can only measure the line of sight component of the field. This therefore gives only a lower limit on the magnetic critical mass. Nonetheless, for a large enough sample, one can estimate true magnetic field strengths statistically under the assumption of random orientations. When this analysis is performed, the current observational consensus is that magnetic fields in molecular clouds are not, by themselves, strong enough to prevent gravitation collapse. Figure \\ref{fig:bfields} shows a summary of the current observations. Clearly atomic gas is magnetically subcritical, but molecular gas is supercritical.\n\n\\begin{figure}\n\\includegraphics[width=\\linewidth]{bfields_crutcher12}\n\\caption[Magnetic field strength measurements]{\n\\label{fig:bfields}\nMeasurements of the line of sight magnetic field strength from the Zeeman effect, versus total gas column density in H atoms cm$^{-2}$ (data from the compilation of \\citealt{crutcher12a}). The three clumps of points represent, from left to right, measurements from the Zeeman splitting of H~\\textsc{i}, OH, and CN. The dashed black line indicates the separation between field strengths that are large enough to render the gas subcritical, and those weak enough for it to be supercritical.\n}\n\\end{figure}\n\n\\subsection{Turbulent Support}\n\nThere is one more positive term in the virial theorem, which is the turbulent component of $\\mathcal{T}$. This one is not at all well understood, largely because we don't understand turbulence itself. This term almost certainly provides some support against collapse, but the amount is not well understood, and we will defer any further discussion of this effect until we get to our discussions of the star formation rate in Chapter \\ref{ch:sflaw_th}.\n\n\\section{Pressureless Collapse}\n\\label{sec:pressureless_collapse}\n\nAs a final topic for this chapter, let us consider what we should expect to happen if gas does begin to collapse, in the simplest case of an initially-spherical cloud with an initial density distribution $\\rho(r)$. We would like to know how the gas moves under the influence of gravity and thermal pressure, under the assumption of spherical symmetry. For convenience we define the enclosed mass\n\\begin{equation}\nM_r =  \\int_0^r 4\\pi r'^2 \\rho(r') \\, dr'\n\\end{equation}\nor equivalently\n\\begin{equation}\n\\frac{\\partial M_r}{\\partial r} = 4\\pi r^2 \\rho.\n\\end{equation}\nThe equation of mass conservation for the gas in spherical coordinates is\n\\begin{eqnarray}\n\\frac{\\partial}{\\partial t} \\rho + \\nabla\\cdot (\\rho \\vecv) & = & 0 \\\\\n\\frac{\\partial}{\\partial t} \\rho + \\frac{1}{r^2}\\frac{\\partial}{\\partial r}(r^2 \\rho v) & = & 0,\n\\end{eqnarray}\nwhere $v$ is the radial velocity of the gas. It is useful to write the equations in terms of $M_r$ rather than $\\rho$, so we take the time derivative of $M_r$ to get\n\\begin{eqnarray}\n\\frac{\\partial}{\\partial t}M_r & = & 4\\pi \\int_{0}^{r} r'^2 \\frac{\\partial}{\\partial t} \\rho \\,dr' \\\\\n& = & -4\\pi \\int_{0}^{r} \\frac{\\partial}{\\partial r'}(r'^2 \\rho v)\\, dr' \\\\\n& = & -4\\pi r^2 \\rho v \\\\\n& = & -v \\frac{\\partial}{\\partial r}M_r.\n\\end{eqnarray}\nIn the second step we used the mass conservation equation to substitute for $\\partial \\rho/\\partial t$, and in the final step we used the definition of $M_r$ to substitute for $\\rho$.\n\nTo figure out how the gas moves, we write down the Lagrangean version of the momentum equation:\n\\begin{equation}\n\\rho \\frac{Dv}{Dt} = -\\frac{\\partial}{\\partial r}P - \\mathbf{f}_g,\n\\end{equation}\nwhere $\\mathbf{f}_g$ is the gravitational force per unit mass. For the momentum equation, we take advantage of the fact that the gas is isothermal to write $P=\\rho c_s^2$. The gravitational force is $\\mathbf{f}_g = -G M_r / r^2$. Thus we have\n\\begin{equation}\n\\frac{Dv}{Dt}= \\frac{\\partial}{\\partial t}v + v\\frac{\\partial}{\\partial r} v= -\\frac{c_s^2}{\\rho} \\frac{\\partial}{\\partial r}{\\rho} - \\frac{G M_r}{r^2}.\n\\end{equation}\n\nTo go further, let us make one more simplifying assumption: that the sound speed $c_s$ is zero. This is not as bad an approximation as one might think. Consider the virial theorem: the thermal pressure term is just proportional to the mass, since the gas sound speed stays about constant. On the other hand, the gravitational term varies as $1/R$. Thus, even if pressure starts out competitive with gravity, as the core collapses the dominance of gravity will increase, and before too long the collapse will resemble a pressureless one.\n\nIn this case the momentum equation is trivial:\n\\begin{equation}\n\\frac{Dv}{Dt} = -\\frac{GM_r}{r^2}.\n\\end{equation}\nThis just says that a shell's inward acceleration is equal to the gravitational force per unit mass exerted by all the mass interior to it, which is constant. We can then solve for the velocity as a function of position:\n\\begin{equation}\nv = \\dot{r} = -\\sqrt{2GM_r}\\left(\\frac{1}{r}-\\frac{1}{r_0}\\right)^{1/2},\n\\end{equation}\nwhere $r_0$ is the position at which a particular fluid element starts. \n\nThe integral can be evaluated by the trigonometric substitution $r=r_0 \\cos^2\\xi$. The solution, first obtained by Hunter (1962), is\n\\begin{eqnarray}\n-2 r_0 (\\cos\\xi \\sin\\xi) \\dot{\\xi} & = & -\\sqrt{\\frac{2GM_r}{r_0}} \\left(\\frac{1}{\\cos^2\\xi}-1\\right)^{1/2} \\\\\n2 (\\cos\\xi\\sin\\xi) \\dot{\\xi} & = & \\sqrt{\\frac{2GM_r}{r_0^3}}\\tan\\xi \\\\\n2 \\cos^2\\xi\\, d\\xi & = & \\sqrt{\\frac{2GM_r}{r_0^3}} dt \\\\\n\\xi+\\frac{1}{2}\\sin 2\\xi & = & t \\sqrt{\\frac{2GM_r}{r_0^3}}.\n\\end{eqnarray}\nWe are interested in the time at which a given fluid element reaches the origin, $r=0$. This corresponds to $\\xi = \\pi/2$, so this time is\n\\begin{equation}\nt = \\frac{\\pi}{2}\\sqrt{\\frac{r_0^3}{2 G M_r}}.\n\\end{equation}\n\nSuppose that the gas we started with was of uniform density $\\rho$, so that $M_r = (4/3)\\pi r_0^3 \\rho$.\nIn this case we have\n\\begin{equation}\nt = t_{\\rm ff} = \\sqrt{\\frac{3\\pi}{32 G \\rho}},\n\\end{equation}\nwhere we have defined the free-fall time $t_{\\rm ff}$: it is the time required for a uniform sphere of pressureless gas to collapse to infinite density. This is of course just the characteristic growth time for the Jeans instability in the regime of negligible pressure, up to a factor of order unity.\n\nFor a uniform fluid this means that the collapse is synchronized -- all the mass reaches the origin at the exact same time. A more realistic case is for the initial state to have some level of central concentration, so that the initial density rises inward. Let us take the initial density profile to be $\\rho = \\rho_c (r/r_c)^{-\\alpha}$, where $\\alpha > 0$ so the density rises inward. The corresponding enclosed mass is\n\\begin{equation}\nM_r = \\frac{4}{3-\\alpha}\\pi \\rho_c r_c^3 \\left(\\frac{r}{r_c}\\right)^{3-\\alpha} \n\\end{equation}\n\nPlugging this in, the collapse time is\n\\begin{equation}\nt = \\sqrt{\\frac{(3-\\alpha)\\pi}{32 G \\rho_c}} \\left(\\frac{r_0}{r_c}\\right)^{\\alpha/2}.\n\\end{equation}\nSince $\\alpha>0$, this means that the collapse time increases with initial radius $r_0$. This illustrates one of the most basic features of a collapse, which will continue to hold even in the case where the pressure is non-zero. Collapse of centrally concentrated objects occurs inside-out, meaning that the inner parts collapse before the outer parts.\n\nWithin the collapsing region near the star, the density profile also approaches a characteristic shape. If the radius of a given fluid element $r$ is much smaller than its initial radius $r_0$, then its velocity is roughly\n\\begin{equation}\nv \\approx v_{\\rm ff}\\equiv -\\sqrt{\\frac{2GM_r}{r}},\n\\end{equation}\nwhere we have defined the free-fall velocity $v_{\\rm ff}$ as the characteristic speed achieved by an object collapsing freely onto a mass $M_r$. The mass conservation equation is\n\\begin{equation}\n\\frac{\\partial M_r}{\\partial t} = -v\\frac{\\partial M_r}{\\partial r}  = -4\\pi r^2 v \\rho\n\\end{equation}\n\nIf we are near the star so that $v\\approx v_{\\rm ff}$, then this implies that\n\\begin{equation}\n\\rho = \\frac{(\\partial M_r/\\partial t) r^{-3/2}}{4\\pi\\sqrt{2 G M_r}}.\n\\end{equation}\nTo the extent that we look at a short interval of time, over which the accretion rate does not change much (so that $\\partial M_r /\\partial t$ is roughly constant), this implies that the density near the star varies as $\\rho\\propto r^{-3/2}$.\n\nWhat sort of accretion rate do we expect from a collapse like this? For a core of mass $M_c = [4/(3-\\alpha)]\\pi \\rho_c r_c^3$, the last mass element arrives at the center at a time\n\\begin{equation}\nt_c = \\sqrt{\\frac{(3-\\alpha)\\pi}{32 G \\rho_c}} = \\sqrt{\\frac{3-\\alpha}{3}}t_{\\rm ff}(\\rho_c),\n\\end{equation}\nso the time-averaged accretion rate is\n\\begin{equation}\n\\langle\\dot{M}\\rangle = \\sqrt{\\frac{3}{3-\\alpha}} \\frac{M_c}{t_{\\rm ff}(\\rho_c)}.\n\\end{equation}\n\nIn order to get a sense of the numerical value of this, let us suppose that our collapsing object is a marginally unstable Bonnor-Ebert sphere (see Problem Set 2). Such an object does not have negligible pressure, but the pressure will only change the collapse rate at order unity. Problem Set 2 includes a calculation of the structure of a maximum-mass Bonnor-Ebert sphere, so we will just quote the value. The maximum mass is\n\\begin{equation}\nM_{\\rm BE} = 1.18 \\frac{c_s^4}{\\sqrt{G^3 P_s}},\n\\end{equation}\nwhere $P_s$ is the pressure at the surface of the sphere and $c_s$ is the thermal sound speed in the core.\n\nLet us suppose that the surface of the core, at radius $r_c$, is in thermal pressure balance with its surroundings. Thus $P_s = \\rho_c c_s^2$, so we may rewrite the Bonnor-Ebert mass as\n\\begin{equation}\nM_{\\rm BE} = 1.18 \\frac{c_s^3}{\\sqrt{G^3 \\rho_c}}.\n\\end{equation}\nA Bonnor-Ebert sphere does not have a powerlaw structure, but if we substitute into our equation for the accretion rate and say that the factor of $\\sqrt{3/(3-\\alpha)}$ is a number of order unity, we find that the accretion rate is\n\\begin{equation}\n\\langle\\dot{M}\\rangle \\approx \\frac{c_s^3/\\sqrt{G^3\\rho_c}}{1/\\sqrt{G\\rho_c}} = \\frac{c_s^3}{G}.\n\\end{equation}\n\nThis is an extremely useful expression, because we know the sound speed $c_s$ from microphysics. Thus, we have calculated the rough accretion rate we expect to be associated with the collapse of any object that is marginally stable based on thermal pressure support. Plugging in $c_s=0.19$ km s$^{-1}$, we get $\\dot{M} \\approx 2\\times 10^{-6}$ $\\msun$ yr$^{-1}$ as the characteristic accretion rate for these objects. Since the typical stellar mass is a few tenths of $\\msun$, based on the peak of the IMF, this means that the characteristic star formation time is of order $10^5-10^6$ yr. Of course this conclusion about the accretion rate only applies to collapsing objects that are supported mostly by thermal pressure. Other sources of support produce higher accretion rates, as we will see when we get to massive stars.\n\n\n", "meta": {"hexsha": "5e0f1f2ec34e9abf7bd9b789102f286e6dbc1306", "size": 40664, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/chapter6.tex", "max_stars_repo_name": "Open-Astrophysics-Bookshelf/star_formation_notes", "max_stars_repo_head_hexsha": "d1c8a10f84fc1676b492ddb4f3bd8b73455b5d07", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 67, "max_stars_repo_stars_event_min_datetime": "2015-05-05T22:43:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-02T02:02:57.000Z", "max_issues_repo_path": "chapters/chapter6.tex", "max_issues_repo_name": "keflavich/star_formation_notes", "max_issues_repo_head_hexsha": "d1c8a10f84fc1676b492ddb4f3bd8b73455b5d07", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2015-05-31T17:15:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T02:07:47.000Z", "max_forks_repo_path": "chapters/chapter6.tex", "max_forks_repo_name": "keflavich/star_formation_notes", "max_forks_repo_head_hexsha": "d1c8a10f84fc1676b492ddb4f3bd8b73455b5d07", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2015-05-22T17:47:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-08T15:58:05.000Z", "avg_line_length": 90.1640798226, "max_line_length": 1008, "alphanum_fraction": 0.7357613614, "num_tokens": 12002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6723317123102955, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.3151828047146389}}
{"text": "\\section{Method}\nAn overview of the method is presented in figure 2. There are three main routines: feature extraction, classification of vegetation, and segmentation of linear objects. In the feature extraction we use the data of the point and its neighbors to get additional information that can help determine to what class a point belongs to. We then use this information to classify which points belong to higher than herb vegetation. These points we subsequently segment into rectangular region, which can be checked for linearity. Details of the various steps which will be described in the following sections.\n\n\\begin{figure}[t]\n\t\\centering\n\t\\begin{tikzpicture}[node distance=0.70cm, scale=0.7, every node/.style={transform shape}]\n\n\t\\node (pro0) [process, fill=darkorange!20] {Point-based feature extraction};\n\t\\node (pro1) [process, right=of pro0, fill=darkorange!20] {Neighborhood-based geometry feature extraction};\n\t\\node (pro2) [process, right=of pro1, fill=darkorange!20] {Neighborhood-based eigenvalue feature extraction};\n\n\t\\node (param) [title, above=0.4cm of pro1] {Feature extraction};\n\n\t\\begin{scope}[on background layer]\n\t\\node (fit1) [fit=(pro0)(pro1)(pro2)(param), inner sep=4pt, transform shape=false, draw=black!80, fill=darkorange, fill opacity=0.5] {};\n\t\\end{scope}\n\n\t\\node (in1) [io, left=of fit1] {Unclassified point cloud};\n\t\\node (out1) [io, below right=0.9cm and 11.7cm=of fit1] {Point cloud with features};\n\n\t\\node (class) [title, below=1.2cm of pro1] {Vegetation classification};\n\n\t\\node (pro5) [process, below=0.2cm of class, fill=lightblue!20] {Supervised classification (random forest)};\n\t\\node (pro4) [process, right=of pro5, fill=lightblue!20] {Data trimming};\n\t\\node (in2) [io, below=of pro5] {Manually classified point cloud};\n\t\\node (pro6) [process, left=of pro5, fill=lightblue!20] {Accuracy assessment (cross validation)};\n\n\t\\begin{scope}[on background layer]\n\t\\node (fit2) [fit=(class)(pro4)(pro5)(pro6), inner sep=4pt, transform shape=false, draw=black!80, fill=lightblue, fill opacity=0.5] {};\n\t\\end{scope}\n\n\t\\node (out2) [io, below left=4.9cm and 3.7=of fit2] {Classified point cloud};\n\n\t\\node (lin) [title, below=of in2] {Linear object segmentation};\n\t\\node (pro11) [process, below=0.2cm of lin, fill=turquoise!20] {Clustering (using DBSCAN)};\n\t\\node (pro10) [process, left=of pro11, fill=turquoise!20] {Preprocessing (2D conversion and downsampling)};\n\t\\node (pro12) [process, right=of pro11, fill=turquoise!20] {Region growing (based on rectangularity)};\n\t\\node (pro13) [process, below=of pro10, fill=turquoise!20] {Object merging};\n\t\\node (pro14) [process, right=of pro13, fill=turquoise!20] {Elongatedness assessment};\n\t\\node (pro15) [process, right=of pro14, fill=turquoise!20] {Accuracy assessment};\n\n\n\t\\begin{scope}[on background layer]\n\t\\node (fit3) [fit=(lin)(pro10)(pro11)(pro12)(pro13)(pro14)(pro15), inner sep=4pt, transform shape=false, draw=black!80, fill=turquoise, fill opacity=0.5] {};\n\t\\end{scope}\n\n\t\\node (in3) [io, below=of pro15] {Manually segmented vegetation objects};\n\n\t\\node (out3) [io, right=of fit3] {Linear vegetation objects};\n%\t\\node (out3) [io, right=3.2cm of pro14] {Linear vegetation objects};\n\n\t\\draw [arrow] (in1) -- (fit1);\n\t\\draw [arrow] (fit1) -| (out1);\n\t\\draw [arrow] (out1) |- (fit2);\n\t\\draw [arrow] (in2) -- (fit2);\n\n\t\\draw [arrow] (pro0) -- (pro1);\n\t\\draw [arrow] (pro1) -- (pro2);\n\n\t\\draw [arrow] (pro4) -- (pro5);\n\t\\draw [arrow] (pro5) -- (pro6);\n\t\\draw [arrow] (pro6) -- (pro5);\n\n\t\\draw [arrow] (fit2) -| (out2);\n\t\\draw [arrow] (out2) |- (fit3);\n\n\t\\draw [arrow] (pro10) -- (pro11);\n\t\\draw [arrow] (pro11) -- (pro12);\n\t\\draw [arrow] (pro12.south) -| +(0,-0.3) -| (pro13.north);\n\t\\draw [arrow] (pro13) -- (pro14);\n\t\\draw [arrow] (pro14) -- (pro15);\n\n\t\\draw [arrow] (in3) -- (in3 |- fit3.south);\n\n\t\\draw [arrow] (fit3) -- (out3);\n%\t\\draw [arrow] (out3 -| fit3.east) -- (out3);\n\n\t\\end{tikzpicture}\n\t\\caption{Workflow for feature extraction (orange), classification (blue), and segmentation of linear objects (green), with datasets represented as parallelograms and processes as rectangles.}\n\t\\label{fig:workflow}\n\\end{figure}\n\n\\subsection{Feature extraction}\n\nThe relevance of the various input features has extensively been studied to separate urban from vegetation objects \\citep{chehata2009airborne, guo2011relevance, mallet2011relevance}, but concise information for vegetation classification is scarce. After reviewing relevant literature, we selected fourteen features (table \\ref{tbl:features}). These features are based on information from echo and local neighborhood information (geometric and eigenvalue based) and their qualities are considered to be efficient for discriminating vegetation objects from point clouds \\citep{chehata2009airborne}.\n\n\\subsubsection{Point-based features}\nThe point cloud \\(\\mathcal{P}\\) is a set of points \\(\\{p_{1}, p_{2}, \\dots, p_{n}\\}\\) \\(\\in \\mathbb{R}^3\\), where each point \\(p_{i}\\) has x, y and z coordinates. In addition, an intensity value (\\(I\\)), a return number (\\(R\\)), and a number of returns (\\(R_{t}\\)) of the returned signal are stored. Since we do not have all the data required to do a radiometric correction of the intensity data we omitted this feature for the classification \\citep{kashani2015review}. As an additional echo-based feature we calculated a normalized return number (\\(R_{n}\\)) (table \\ref{tbl:features}).\n\n\\subsubsection{Neighborhood-based features}\nIn addition to point-based features, we calculated four geometric features related to local neighborhoods. We defined a neighborhood set \\(\\mathcal{N}_{i}\\) of points \\(\\{q_{1}, q_{2}, \\dots, q_{k}\\}\\) for each point \\(p_{i}\\), where \\(q_{1} = p_{i}\\), by using the k-nearest neighbors method with \\(k = 10\\) points. This method performs well for datasets that vary in point densities (Weinmann et al., 2014). The four geometric features were: the height difference, the height standard deviation, the local radius and local point density (table \\ref{tbl:features}).\n\nWe further calculated eigenvalue-based features which are used to describe the distribution of points in a neighborhood \\citep{hoppe1992surface, chehata2009airborne}. We used the local structure tensor to estimate the surface normal and to define surface variation \\citep{pauly2002efficient}. The structure tensor describes the dominant directions of the neighborhood of a point by determining the covariance matrix of the x, y and z coordinates of the set of neighborhood points and computing the eigenvalues (\\(\\lambda_{1}, \\lambda_{2}, \\lambda_{3}\\), where \\(\\lambda_{1} > \\lambda_{2} > \\lambda_{3}\\)) of this matrix and ranking them based on the eigenvalue values. Hence, the magnitude of the eigenvalues of this covariance matrix describe the spread of points in the direction of the eigenvector. The points are linearly distributed if the eigenvalue of the first principle direction is significantly bigger than the other two (\\(\\lambda_{1} \\gg \\lambda_{2} \\approx \\lambda_{3}\\)), planarly distributed if the eigenvalues of the first two principle directions are about equal and significantly larger than the third (\\(\\lambda_{1} \\approx \\lambda_{2} \\gg \\lambda_{3}\\)), and the points are scattered in all directions if all eigenvalues are about equal (\\(\\lambda_{1} \\approx \\lambda_{2} \\approx \\lambda_{3}\\)). These and additional properties are quantified using formulas (table \\ref{tbl:features}). The eigenvector belonging to the third eigenvalue is equal to the normal vector (\\(\\vec{N} = (N_{x}, N_{y}, N_{z})\\)) \\citep{pauly2002efficient}.\n\n\\begin{table}[t]\n\t\\caption{The features used for classification, split into two main groups: point-based and neighborhood-based. The point-based features are based on echo information and the neighborhood-based features are based on the local geometry and eigenvalue characteristics.}\n\t\\label{tbl:features}\n\t\\footnotesize\n\t\\begin{tabular}{l l l l l}\n\t\t\\toprule\n\t\t\\textbf{Feature group} & \\textbf{Feature} & \\textbf{Symbol} & \\textbf{Formula} & \\textbf{Reference} \\\\\n\t\t\\midrule\n\t\t\\textbf{Point} \\\\ \\\\\n\t\t- Echo & Number of returns & \\(R_{t}\\) & \\\\ \\\\\n\t\t& Normalized return number & \\(R_{n}\\) & \\(R/R_{t}\\) & \\citet{guo2011relevance} \\\\ \\\\\n\t\t\\textbf{Neighborhood} \\\\ \\\\\n\t\t- Geometric & Height difference & \\(\\Delta_{z}\\) & \\(\\max_{j:\\mathcal{N}_{i}}(q_{z_{j}}) - \\min_{j:\\mathcal{N}_{i}}(q_{z_{j}})\\) & \\cite{weinmann2015semantic} \\\\ \\\\\n\t\t& Height standard deviation & \\(\\sigma_{z}\\) & \\(\\sqrt{\\frac{1}{k} \\sum_{j=1}^k (q_{z_{j}} - \\overline{q_{z}})^2}\\) & \\cite{weinmann2015semantic} \\\\ \\\\\n\t\t& Local radius & \\(r_{l}\\) & \\(\\max_{j: \\mathcal{N}_{i}}(|p_{i} - q_{j}|)\\) & \\cite{weinmann2015semantic} \\\\ \\\\\n\t\t& Local point density & \\(D\\) & \\(k/(\\frac{4}{3} \\pi r_{l}^3)\\) & \\cite{weinmann2015semantic} \\\\ \\\\\n\t\t- Eigenvalue & Normal vector Z & \\(N_{z}\\) & & \\citet{pauly2002efficient} \\\\ \\\\\n\t\t& Linearity & \\(L_{\\lambda}\\) & \\(\\frac{\\lambda_{1} - \\lambda_{2}}{\\lambda_{1}}\\) & \\citet{west2004context} \\\\ \\\\\n\t\t& Planarity & \\(P_{\\lambda}\\) & \\(\\frac{\\lambda_{2} - \\lambda_{3}}{\\lambda_{1}}\\) & \\citet{west2004context} \\\\ \\\\\n\t\t& Scatter & \\(S_{\\lambda}\\) & \\(\\frac{\\lambda_{3}}{\\lambda_{1}}\\) & \\citet{west2004context} \\\\ \\\\\n\t\t& Omnivariance & \\(O_{\\lambda}\\) & \\(\\sqrt[3]{\\lambda_{1} \\lambda_{2} \\lambda_{3}}\\) & \\citet{west2004context} \\\\ \\\\\n\t\t& Eigenentropy & \\(E_{\\lambda}\\) & \\(-\\lambda_{1}\\ln(\\lambda_{1}) -\\lambda_{2}\\ln(\\lambda_{2}) -\\lambda_{3}\\ln(\\lambda_{3})\\) & \\citet{west2004context} \\\\ \\\\\n\t\t& Sum of eigenvalues & \\(\\sum_{\\lambda}\\) & \\(\\lambda_{1} + \\lambda_{2} + \\lambda_{3}\\) & \\cite{mallet2011relevance} \\\\ \\\\\n\t\t& Curvature & \\(C_{\\lambda}\\) & \\(\\frac{\\lambda_{3}}{\\lambda_{1} + \\lambda_{2} + \\lambda_{3}}\\) & \\citet{pauly2002efficient} \\\\ \\\\\n\t\t\\bottomrule\n\t\\end{tabular}\n\\end{table}\n\n\\subsection{Vegetation classification}\nThe fourteen features served as input for the classification of vegetation, which required data trimming, a supervised vegetation classifier and accuracy assessment.\n\n\\subsubsection{Data trimming}\nTo facilitate efficient processing, points that certainly do not belong to higher than herb vegetation were removed from the dataset. These points are characterized by a locally planar neighborhood and are selected on the basis of sphericity feature (table \\ref{tbl:features}). In this way, points with a scatter value \\(S_{\\lambda} < 0.05\\) were removed. This threshold was conservative to ensure a large reduction of the data size, while still preserving the higher than herb vegetation points.\n\n\\subsubsection{Supervised classification}\nA random forest classifier provides a good trade-off between classification accuracy and computational efficiency \\citep{breiman2001random, weinmann2015semantic}. The random forest algorithm creates a collection of decision trees, where each tree is based on a random subset of the training data \\citep{ho1998random}. Random forest parameters such as the maximum number of features, minimal samples per leaf, minimal samples per split and the ratio between minority and majority samples were optimized using a cross validated grid search. During the grid search a range of applicable values were chosen for each parameter and all combinations were tested and evaluated for performance using cross validation. To save time first a course grid was created to identify the region of best performance and subsequently a finer grid was made to find the best performing parameter set in that region \\citep{hsu2003practical}.\n\nThe trimmed point cloud is imbalanced, and includes a lot more vegetation than `other' points. Imbalanced training data can lead to undesirable classification results \\citep{he2009learning}. Therefore, we used a balanced random forest algorithm. In this algorithm the subsets are created by taking a bootstrap sample from the minority class and a random sample from the majority class with the same sample size as the minority class sample \\citep{chen2004using}. By employing enough trees eventually all majority class data are used, while still maintaining a balance between the two classes. The decision trees were created using a Classification and Regression Tree (CART) algorithm \\citep{breiman1984classification}. A manual annotation of the trimmed point cloud into `vegetation' and `other' classes was done using an interpretation of the point cloud and high resolution aerial photos.\n\n%The point cloud and high resolution aerial photos  were interpreted and used to manually annotate part of the trimmed 3D point cloud as `vegetation' and `other' classes.\n\n\\subsubsection{Accuracy assessment}\nThe receiver operating characteristic (ROC) curve \\citep{bradley1997use}, the Matthew’s correlation coefficient (MCC) \\citep{matthews1975comparison} and the geometric mean \\citep{kubat1998machine} were used in the accuracy assessment. This allowed to have good performance metrics even when dealing with an imbalanced dataset \\citep{kohavi1995study, sun2009classification, lopez2013insight}. To create a ROC curve, the true positive (TP) rate is plotted against the false positive (FP) rate at various decision thresholds. The area under a ROC curve (AUROCC) is a measure for the performance of the classifier \\citep{bradley1997use}. The MCC analyzes the correlation between the observed and the predicted data and is defined as:\n\\begin{equation}\n\t\\label{eq:MCC}\n\t{\\text{MCC}}={\\frac{TP\\times TN-FP\\times FN}{{\\sqrt{(TP+FP)(TP+FN)(TN+FP)(TN+FN)}}}}\n\\end{equation}\nwhere TN are the true negatives and FN the false negatives. The geometric mean is defined as:\n\n\\begin{equation}\n\t\\label{eq:geom}\n\t{\\text{Geometric mean}}={\\sqrt{\\text{producer's accuracy class 1} \\times \\text{producer's accuracy class 2}}}\n\\end{equation}\n\nThe MCC, AUROCC and the geometric mean were obtained using a 10-fold cross validation. This is done by splitting the data into 10 randomly mutually exclusive subsets and using a subset as testing data and a classifier trained on the remaining data \\citep{kohavi1995study}.\n\n\\subsection{Linear object segmentation}\nTo segment the vegetation points into linear regions we did a preprocessing step, clustered the points using a DBSCAN, applied a region growing algorithm, merged nearby and aligned objects, evaluated their elongatedness and assessed the accuracy.\n\n\\subsubsection{Preprocessing}\nThe point cloud was converted to 2D by removing the z-coordinate of the vegetation points. In addition, the data were spatially downsampled to 1 meter distance between vegetation points. This substantially decreased computation time without losing too much precision (figure \\ref{fig:downsampling}).\n\n\\begin{figure}\n\t\\centering\n\t\\includegraphics[scale=0.80]{./img/downsampling.pdf}\n\t\\caption{The vegetation points of a piece of tree line within the research area before (blue) and after (red) downsampling the point cloud, plotted on top of the high resolution orthophoto, in RD coordinates.}\n\t\\label{fig:downsampling}\n\\end{figure}\n\n\\subsubsection{Clustering}\nAfter reducing the amount of points we clustered the remaining points together using a DBSCAN clustering algorithm \\citep{ester1996density}. This algorithm is able to quickly cluster points together based on density and removes outlying points in the process. This decreases the processing time needed in the subsequent region growing step, since the amount of possible neighboring points is reduced.\n\n\\subsubsection{Region growing}\nRegion growing is an accepted way of decomposing point clouds \\citep{rabbani2006segmentation, vosselman2013point} or raster imagery \\citep{blaschke2014geographic} into homogeneous objects. Normally, seed locations are selected and regions are grown based on proximity and similarity of the attributes of the points. In our method, seed selection was based on the coordinates and regions were grown based on proximity and a rectangularity constraint. The proximity is constrained by taking the eight nearest neighbors of each point during the growing process. The rectangularity of an object is described as the ratio between the area of an object and the area of its minimum bounding rectangle (Rosin, 1999). The minimum bounding rectangle (figure \\ref{fig:hulls}b) is computed with rotating calipers \\citep{toussaint1983solving}. First a convex hull is constructed (figure \\ref{fig:hulls}a) by using the QuickHull algorithm \\citep{preparata1985computational}. The minimum bounding rectangle has a side collinear with one of the edges of the convex hull \\citep{freeman1975determining}. Hence the minimum bounding rectangle can be found by rotating the system by the angle the edges of the convex hull make with the x-axis and checking the bounding rectangles of each rotation. The area of the object can be calculated by computing the concave hull of the set of points belonging to the object (figure \\ref{fig:hulls}c). For this we use a concave hull algorithm using a \\(k\\)-nearest neighbors approach \\citep{moreira2007concave}. This algorithm starts with finding a point with a minimum or maximum of one of the coordinates. Subsequently it goes around the points by repeatably finding the neighbor which makes an edge that makes the largest counterclockwise angle with the previous edge. This process is continued until the current point is the starting point. % Finally a check is done to ensure all the points fall within the hull. If this is not the case the \\(k\\) is increased by 1 and the algorithm repeated until an acceptable concave hull has been found.\n\nIn this way, for each cluster, points with the minimum x-coordinate and its 20 closest neighbors were used as the starting region. Subsequent points were added as long as the region’s rectangularity did not drop below a set threshold of 0.55 (figure \\ref{fig:regiongrowing}). Then, the growing procedure was repeated for the next region until the entire cluster is segmented into rectangular regions.\n\n%\\begin{figure}\n%\t\\centering\n%\t\\includegraphics[scale=0.50]{./img/hulls.pdf}\n%\t\\caption{The vegetation points of a piece of tree line within the research area are plotted on top of the high resolution orthophoto, showing the effect of downsampling the point cloud (a) and the different hulls used during the region growing algorithm: the convex hull (b), the minimal oriented bounding box (c), and the concave hull (d). During the region growing the rectangularity is calculated by dividing the area of the concave hull (d) by the area of the bounding box (c).}\n%\\end{figure}\n\n\\begin{figure}\n\t\\centering\n\t\\includegraphics[width=\\columnwidth]{./img/hulls.pdf}\n\t\\caption{The downsampled vegetation points of a piece of tree line within the research area  plotted on top of the high resolution orthophoto in RD coordinates, showing the different hulls used during the region growing algorithm: the convex hull (a), the minimal oriented bounding box (b), and the concave hull (c). During the region growing the rectangularity is calculated by dividing the area of the concave hull (c) by the area of the bounding box (b).}\n\t\\label{fig:hulls}\n\\end{figure}\n\n\\begin{figure}\n\t\\centering\n\t\\includegraphics[width=\\columnwidth]{./img/region_growing.pdf}\n\t\\caption{An example of the region growing process for one point. First the eight nearest neighbors are computed and the neighbors which are not already part of the region are considered to be added to the region (a). A bounding box and concave hull is computed for the region with the considered point added and the rectangularity is calculated (b). If this rectangularity is above a certain threshold the point is added to the region. Subsequently the process is repeated for the other points to consider (c, d). When all points to consider are checked, a next point of the region is check for nearest neighbors and the whole process is repeated until all points of the region, including the ones which are added during the growing process, have been checked once.}\n\t\\label{fig:regiongrowing}\n\\end{figure}\n\n\\subsubsection{Object merging}\nThe resulting objects can be fragmented as the result of minor curves in the linear vegetation or small interruptions in vegetation. These objects were merged when they were in close proximity, faced a similar compass direction, and were aligned. The compass direction was determined by computing the angle between one of the long sides of the minimum bounding box and the x-axis. The alignment was checked by comparing the angle of the line between the two center points with the directions of the objects. Once merged the lengths of the objects were added and the maximum of the widths taken as the new width.\n\n\\subsubsection{Elongatedness}\nThe merged objects were assessed for linearity by resolving the elongatedness of an object, which is defined as the ratio between its length and its width \\citep{nagao2013structural}. The definition of a linear object is not clearly defined and consequently somewhat arbitrary. After trial and error, we set the minimum elongatedness at 2.5 and, to exclude long and wide patches from the resulting linear objects, a maximum width of 60 meters.\n\n\\subsubsection{Accuracy assessment}\nThe accuracy of the delineated linear objects was assessed by calculating the user’s, producer’s and overall accuracy, as well as the harmonic mean of the precision and recall (F1), kappa and MCC scores \\citep{congalton2008assessing}. We manually annotated the vegetation data into linear and nonlinear objects, after converting the classified vegetation points into polygons. Consequently this assessment evaluates the accuracy of the segmentation given the accuracy of the vegetation points. Differencing of the automated and manually constructed data resulted in confusion matrices to compare true positives, true negatives, false positives and false negatives in the area.", "meta": {"hexsha": "98c4b4ee274eddb8b4349dfc5158b2008347b3f3", "size": 21690, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Article/tex/__latexindent_temp.tex", "max_stars_repo_name": "chrislcs/linear-vegetation-elements", "max_stars_repo_head_hexsha": "8e45a40dca472ca9d5cbb58593d9f5b5bc855bf4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-06-16T09:05:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-02T06:48:26.000Z", "max_issues_repo_path": "Article/tex/__latexindent_temp.tex", "max_issues_repo_name": "chrislcs/linear-vegetation-elements", "max_issues_repo_head_hexsha": "8e45a40dca472ca9d5cbb58593d9f5b5bc855bf4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Article/tex/__latexindent_temp.tex", "max_forks_repo_name": "chrislcs/linear-vegetation-elements", "max_forks_repo_head_hexsha": "8e45a40dca472ca9d5cbb58593d9f5b5bc855bf4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-01-07T18:03:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-07T12:56:39.000Z", "avg_line_length": 108.9949748744, "max_line_length": 2063, "alphanum_fraction": 0.7637159982, "num_tokens": 5573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5888891307678321, "lm_q1q2_score": 0.3151136485091581}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\section*{Mon Oct 14 2019}\n\n% Summary of past lectures: we discussed:\n\n% \\begin{enumerate}\n%     \\item the different time scales of stellar evolution, and their impact on the adiabatic approximation;\n%     \\item easy approximations for stellar pulsation;\n%     \\item acoustic approximations;\n%     \\item Ritter's relation;\n%     \\item linearized structure equations: the adiabatic approximation (arguments for it!), deriving the LAWE;\n%     \\item examples of solutions to the LAWE and stability conditions;\n%     \\item the LNAWE: today.\n% \\end{enumerate}\n\n\\subsection{The LNAWE}\n\nFirst of all, let us recall the linearized equations of stellar structure: \n%\n\\boxalign{\n\\begin{subequations}\n\\begin{align}\n\\frac{ \\delta \\rho }{\\rho } &= - 3 \\zeta - 4 \\pi r^3 \\rho \\pdv{\\zeta }{m}  \\label{eq:linearized-cont}\\\\\nr \\ddot{\\zeta} &= - 4 \\pi r^2 \\qty[\\qty(4 \\zeta + \\frac{ \\delta P}{P})\\pdv{P}{m} + P \\pdv{}{m} \\qty(\\frac{ \\delta P}{P})]  \\label{eq:linearized-mom}\\\\\n\\pdv{}{t} \\qty(\\frac{ \\delta P}{P}) &= \\Gamma_1 \\pdv{}{t} \\qty(\\frac{ \\delta \\rho }{\\rho }) + \\frac{\\rho }{P} \\qty(\\Gamma_3 - 1) \\delta \\qty(\\epsilon_{\\text{eff}} - \\pdv{L}{m})  \\label{eq:linearized-E1}\\\\\n\\pdv{}{t} \\qty(\\frac{ \\delta T}{T}) &= \\qty(\\Gamma_3-1) \\pdv{}{t} \\qty(\\frac{ \\delta \\rho }{\\rho }) + \\frac{1}{c_V T} \\delta \\qty(\\epsilon_{\\text{eff}} - \\pdv{L}{m})  \\label{eq:linearized-E2}\\\\\n\\frac{ \\delta L}{L} &= 4 \\zeta - n \\frac{ \\delta \\rho }{\\rho } + (s+4) \\frac{ \\delta T}{T} + \\qty(\\pdv{\\log T}{m})^{-1} \\pdv{}{m} \\qty(\\frac{ \\delta T}{T}) \\label{eq:linearized-RT}\n\\,,\n\\end{align}\n\\end{subequations}}\n\n%\nusing which we can derive after long manipulations the Linear Non-Adiabatic Wave Equation, which in its Lagrangian formulation reads: \n%\n\\begin{align}\n\\dot{\\ddot{\\zeta}}\n=\n4 \\pi r \\qty(\\dot{z} \\pdv{}{m} \\qty((3 \\Gamma_1 - 4)P) \n-  \\pdv{}{m} \\qty(\\rho (\\Gamma_3 - 1) \\delta \\qty(\\dv{Q}{t})))\n+ \\frac{1}{r^2} \\pdv{}{m} \\qty(16 \\pi^2 \\Gamma_1 P \\rho r^{6} \\pdv{\\dot{\\zeta}}{m})\n\\,,\n\\end{align}\n%\nwhere we used the fact that \\(\\dv*{Q}{t} = \\epsilon _{\\text{eff}} - \\pdv*{L}{m}\\). On the other hand, the Eulerian formulation is \n%\n\\begin{align}\n\\dot{\\ddot{\\zeta}} = \\frac{1}{r \\rho } \\qty(\\dot{\\zeta}\\pdv{}{r} \\qty((3\\Gamma_1 -4) P ) - \\pdv{}{r} \\qty(\\rho (\\Gamma_3 -1) \\delta \\qty(\\dv{Q}{t})))\n+ \\frac{1}{r^4 \\rho}\\pdv{}{r}\\qty(r^{4} \\Gamma_1 P \\pdv{\\dot{\\zeta}}{r}) \n\\,.\n\\end{align}\n\n\\begin{bluebox}\nThe procedure to derive the LNAWE is as follows: \n\\begin{enumerate}\n  \\item substitute the continuity equation \\eqref{eq:linearized-cont} into the \\(P, \\rho \\) form of the energy conservation equation \\eqref{eq:linearized-E1}; \n  \\item substitute the \\(P, \\rho \\) form of the energy conservation equation \\eqref{eq:linearized-E1} into the time derivative of the Eulerian form of the momentum conservation equation \\eqref{eq:linearized-mom};\n  \\item simplify.\n\\end{enumerate}\n\\end{bluebox}\n\n\\subsection{Solving the LNAWE}\n\nOur ansatz for the LNAWE will still be of the form \\(\\zeta (r, t) = \\eta (r) e^{i \\sigma t}\\), but now we insert \\(\\sigma = \\omega + i \\kappa \\): this means we also consider \\emph{damped} exponential solutions and \\emph{diverging} exponential solutions. \nWe want to simplify the exponentials, so we must assume that \n%\n\\begin{align}\n\\delta \\qty(\\dv{Q}{t}) = \\delta \\qty(\\dv{Q}{t}) _{\\text{sp}} e^{i \\sigma t}\n\\,.\n\\end{align}\n\n\\todo[inline]{Why do we assume that the heat derivative perturbation is \\emph{in phase} with the displacement? Maybe we do not, and the \\(_{\\text{sp}}\\) heat variation is complex?}\n\nWith this substitution we get: \n%\n\\begin{align}\n- i \\sigma^3 \\eta = \\frac{i \\sigma \\eta }{r \\rho }\n\\pdv{}{r} \\qty((3 \\Gamma_1 -4)P) - \\frac{1}{r \\rho }\n\\pdv{}{r} \\qty(\\rho (\\Gamma_3 -1) \\delta \\qty(\\pdv{Q}{t})_{\\text{sp}}) \n+ \\frac{i \\sigma}{r^{4} \\rho } \\pdv{}{r} \\qty(r^{4} \\Gamma_1 P \\pdv{\\eta }{r})\n\\,.\n\\end{align}\n\n\n\nThe time scales for these parameters are \\(\\omega \\sim \\omega _{\\text{ad}} \\sim \\tau _{\\text{dyn}}\\), while \\(\\kappa \\sim 1/ \\tau _{\\text{th}}\\): therefore \\(\\omega \\gg \\abs{\\kappa } \\).\n\nUsing this result, we can make some useful \\emph{quasi-adiabatic} approximations: in the LNAWE we will identify the LAWE operator \\(\\mathcal{L}\\), and replace its application to the wavefunction with the corrisponding eigenvalue. Basically, we will consider the thermal contribution to be small and work ``to first order'' with  it.\n%\n\\begin{subequations}\n\\begin{align}\n\\begin{split}\n- i \\sigma^3 \\eta  &= \n-i \\sigma \\qty(- \\frac{1}{r \\rho } \\pdv{}{r} \\qty((3\\Gamma_1 -4) P) - \\frac{1}{r^{4} \\rho } \\pdv{}{r} r^{4} \\Gamma_1 P \\pdv{\\eta }{r}) + \\\\\n&\\phantom{=}\\ \n - \\frac{1}{r \\rho } \\pdv{}{r} \n\\qty(\\rho (\\Gamma_3 -1) \\delta \\qty(\\pdv{Q}{t})_{\\text{sp}})\n\\end{split} \n\\\\\n- i \\sigma^3 \\eta &= \n- i \\sigma \\mathcal{L}(\\eta ) \n- \\frac{1}{r \\rho } \\pdv{}{r} \n\\qty(\\rho (\\Gamma_3 -1) \\delta \\qty(\\pdv{Q}{t})_{\\text{sp}}) \\\\\n\\mathcal{L}(\\eta ) - \\sigma^2 \\eta &= \n\\frac{i}{r \\sigma  \\rho } \\pdv{}{r} \n\\qty(\\rho (\\Gamma_3 -1) \\delta \\qty(\\pdv{Q}{t})_{\\text{sp}})\n\\,,\n\\end{align}\n\\end{subequations}\n%\nso we can see that the eigenvalue of the LAWE operator cannot be \\(\\sigma^2\\) now. We take this equation, multiply it by \\(\\eta r^2\\) and integrate it over the whole star in \\(\\dd{m}\\): we get \n%\n\\begin{align}\ni \\sigma^3 \\int \\eta^2r^2 \\dd{m} \n- i \\sigma \\int \\eta \\mathcal{L}(\\eta) r^2 \\dd{m}\n= \\int \\frac{r}{\\rho } \\pdv{}{r} \\qty(\\rho (\\Gamma_3 -1) \\delta \\qty(\\pdv{Q}{r}) _{\\text{sp}}) \\eta \\dd{m}\n\\overset{\\text{def}}{=} C\n\\,,\n\\end{align}\n%\nwhere we defined the \\emph{work integral} \\(C\\). \nWe only look at the first order terms in \\(\\kappa \\): so we make the approximation \\(i \\sigma^3 \\approx \\omega^2 \\qty(i \\omega - 3 \\kappa )\\), while (to first order, but also exactly) \\(i \\sigma = i \\omega - \\kappa \\). We substitute these two, and then make the key manipulation: we substitute \\(\\mathcal{L}(\\eta )\\) with \\(\\omega^2 \\eta \\). \nThe only thing missing is the definition: \\(J \\overset{\\text{def}}{=} \\int \\eta^2 r^2 \\dd{m}\\).\nSo we get \n%\n\\begin{subequations}\n\\begin{align}\n\\omega^2 \\qty(i \\omega - 3 \\kappa ) J \n- (i \\omega - \\kappa ) \\omega^2 J &= C \\\\\n- 3 \\kappa + \\kappa &= \\frac{C}{J \\omega^2} \\\\\n\\kappa &= - \\frac{C}{2 \\omega^2 J }\n\\,.\n\\end{align}\n\\end{subequations}\n\nNow we make some considerations on the expression of \\(C\\) and integrate by parts, getting:\n%\n\\begin{subequations}\n\\begin{align}\nC &= \\int_{M} \\frac{1}{r \\rho } \\pdv{}{r} \\qty(\\rho(\\Gamma_3 -1) \\delta \\qty(\\dv{Q}{t})_{\\text{sp}}) \\eta r^2 \\dd{m}  \\\\\n&= \\int_{R} \\pdv{}{r}  \\qty(\\rho(\\Gamma_3 -1) \\delta \\qty(\\dv{Q}{t})_{\\text{sp}})\n4 \\pi r^3 \\eta  \\dd{r}\n\\marginnote{\\(\\dd{m} = 4 \\pi r^2\\rho \\dd{r}\\)} \\\\ \n&=  \\eval{\\rho (\\Gamma_3 -1) \\delta \\qty(\\dv{Q}{t})_{\\text{sp}}\n4 \\pi r^3\\eta }_{r=0}^{r=R} \n- \\int_{R} \\rho (\\Gamma_3 -1) \\delta \\qty(\\dv{Q}{t})_{\\text{sp}} \\pdv{}{r} \\qty(4 \\pi r^3 \\eta ) \\dd{r}\n\\\\\n&= - \\int_{R} \\rho (\\Gamma_3 -1) \\delta \\qty(\\dv{Q}{t})_{\\text{sp}} 4 \\pi r^2 \\qty(3 \\eta + r \\pdv{\\eta }{r}) \\dd{r} \\marginnote{\\(\\rho =0\\) if \\(r=R\\)}\n\\\\\n&= \\int_{R} \\rho (\\Gamma_3 -1) \\delta \\qty(\\dv{Q}{t})_{\\text{sp}} 4 \\pi r^2 \\qty(\\frac{ \\delta \\rho }{\\rho})_{\\text{sp}}\n\\dd{r}\n\\marginnote{From equation \\eqref{eq:linearized-cont}: \\(\\frac{ \\delta \\rho }{\\rho } = -3\\zeta - r \\pdv{\\zeta }{r}\\)}\n\\\\\n&= \\int_{R} (\\Gamma_3 -1) \\qty(\\frac{ \\delta \\rho }{\\rho })_{\\text{sp}} \\delta \\qty(\\dv{Q}{t})_{\\text{sp}}\n \\dd{m}\n\\\\\n&= \\int_M \\qty(\\frac{\\delta T}{T})_{\\text{sp}} \\delta \\qty(\\epsilon _{\\text{eff}}- \\pdv{L}{m} ) \\dd{m}\n\\marginnote{From the time-integrated equation \\eqref{eq:linearized-E2}, neglecting the heat transfer term}\n\\,,\n\\end{align}\n\\end{subequations}\n%\nand now this expression allows us to study the mechanisms which create perturbations: the coefficient to calculate is \\(\\kappa \\), which we now know to be given by \n%\n\\begin{align} \\label{eq:kappa-driven-oscillations}\n\\kappa = - \\frac{1}{2 \\omega^2 J}\n\\int_M \\qty(\\frac{\\delta T}{T})_{\\text{sp}} \\delta \\qty(\\epsilon _{\\text{eff}}- \\pdv{L}{m} ) \\dd{m}\n\\,,\n\\end{align}\n%\nwhich we will study in the next section.\n\n\\subsection{Driving mechanisms}\n\nThe energy of the vibrations comes from the internal thermal energy of the star, which ultimately comes from thermonuclear reactions. We can rewrite equation \\eqref{eq:kappa-driven-oscillations} as \n%\n\\begin{align} \\label{eq:kappa-driving-mechanisms}\n\\kappa = - \\frac{1}{2 \\omega^2 J} \\underbrace{\\int_{M} \\qty(\\frac{ \\delta T}{T})_{\\text{sp}} \\delta \\epsilon _{\\text{eff}} \\dd{m}}_{\\text{energy generation}}\n+ \\frac{1}{2 \\omega^2J} \\underbrace{\\int_{M} \\qty(\\frac{ \\delta T}{T})_{\\text{sp}}\n\\pdv{ \\delta L}{m} \\dd{m}}_{\\text{energy transfer}}\n\\,.\n\\end{align}\n\nThe \\(\\epsilon \\)-mechanism is about energy generation, which is assumed to be due to nuclear reactions, without considering neutrino processes:\nthis can happen if the magnitude of the temperature and density perturbations are large enough.\n\nThe \\(\\kappa \\)-\\(\\gamma \\)-mechanism is about considering the regions where the luminosity gradient and temperature gradient are discordant.\nThis means that the considered stellar layer is absorbing or emitting; this is usually assumed to be happening through free-free interactions (bremsstrahlung and inverse bremsstrahlung).\n\n\\end{document}\n", "meta": {"hexsha": "a8a9e0ad301cdc56db18035a6ef5a51583715153", "size": 9211, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ap_first_semester/advanced_astrophysics/14oct.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "ap_first_semester/advanced_astrophysics/14oct.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ap_first_semester/advanced_astrophysics/14oct.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 47.9739583333, "max_line_length": 342, "alphanum_fraction": 0.6410813158, "num_tokens": 3449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5888891307678319, "lm_q1q2_score": 0.31511364850915796}}
{"text": "\\chapter{Introduction}\n\\label{chpr:intro}\nAssociate dates with events is the essential medium to write history. \nIn the distant past it was appanage of a restricted elite of powerful individuals, with the evolution and progress of society, the amount of people able to write their own history has increased.\nThis lead to the emergence of different versions: not a crucial concern because, as for several human constructions, history can be a distortion of reality.\nConverge to a single version is a tough matter, yet it is grounded into the ability of everyone to write their own history.\nPrecluding some individuals from the ability to state and record their viewpoint does compromise the natural interaction between history and reality.\nIn this work we focus on the primary obstacle: the ability of recording arbitrary events.\n\nUsing proper semantics, an event is mapped into data, which are then embedded in an item suitable for storing and sharing, finally on the resulting object a date is attached. \nEach step can be performed in a variety of manners and has its own optimal choices to fulfil the given requirements. \nIn this work we assume the meaning of the data is given and we refer to the procedure of binding a date to data as timestamping. \nWe focus on weaknesses and strengths of every choice, starting from physical to digital timestamping, with particular emphasis on the trust issue.\nIf a third party is placing the date on the item containing the data, it may behave maliciously, e.g. compromising the data or setting a wrong date. This issue can be addressed using distributed consensus technologies, like Bitcoin, allowing anyone to write his own version of the events: oppressed people have the possibility to record what they witness even in hostile environments, reducing powers and responsibilities of central authorities.\n\nHow to make this approach viable and accessible on large scale presents tough technical steps, resulting in best practices \\cite{OTSWeb} that have been used to define an open protocol standard. This protocol has emerged as the first (along with very few others) non-financial blockchain-related working application \\cite{ESMAresponse}.\n\nOur contribution starts with a deep investigation of an improvement proposal \\cite{PoePR, PoeIs} to the standard that allows the inclusion of a timestamp inside a regular bitcoin transaction without increasing its size and hence its cost. \nWe aim to provide guidelines to properly understand what is behind this technique and the implications it carries.\nFinally we present a practical implementation of this new feature we have developed as integration inside a popular bitcoin open source wallet: users can create timestamps within transactions with no additional charge. \n\n\\section{Structure}\nIn this work we aim to describe exhaustively foundations, benefits and issues of arising from the new proposed technique. \nIt requires to traverse different subjects, mainly cryptography, computer science and distributed systems.\nIn this section we outline the path we are going to undertake.\n\nIn Chapter \\ref{chpr:timestamping} we define what a timestamp is and we exploit the essential characteristics of its components: operations and attestations.\n\nIn Chapter \\ref{chpr:trustless}, after a brief introduction on Bitcoin, we show how it can be used to achieve digital timestamping without relying on trusted third parties.\n\nIn Chapter \\ref{chpr:state-of-art}, we show the state of the art of trustless digital timestamping, with the open source project OpenTimestamps. \nWe provide a description of the standard it defines and the solution to address scalability issues.\n\nIn Chapter \\ref{chpr:ec-commitments} we plunge into the core of the work, analysing the technique of elliptic curve commitment, with main focus on timestamping applications, particularly \\textit{sign-to-contract}.\n\nIn Chapter \\ref{chpr:s2c} we highlight the practical implications of \\textit{sign-to-contract}, both benefits and issues. Finally we show a plugin for a popular open source wallet that implements the technique described.\n\nTo conclude, in Chapter \\ref{chpr:conclusions}, we summarize what has been discussed and draw attention to which future works can start from the point reached.\n", "meta": {"hexsha": "5d40baf4bc1888c65f771102c93618a51ebc3aae", "size": 4252, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapters/Introduction.tex", "max_stars_repo_name": "LeoComandini/Thesis", "max_stars_repo_head_hexsha": "d5754ae5c05f110e1fba115dc011f240878933f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2018-04-09T03:42:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-20T10:25:26.000Z", "max_issues_repo_path": "Chapters/Introduction.tex", "max_issues_repo_name": "LeoComandini/Thesis", "max_issues_repo_head_hexsha": "d5754ae5c05f110e1fba115dc011f240878933f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapters/Introduction.tex", "max_forks_repo_name": "LeoComandini/Thesis", "max_forks_repo_head_hexsha": "d5754ae5c05f110e1fba115dc011f240878933f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-04-06T17:48:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-19T09:36:36.000Z", "avg_line_length": 109.0256410256, "max_line_length": 445, "alphanum_fraction": 0.8160865475, "num_tokens": 830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.31511364078757614}}
{"text": "% !TeX encoding = UTF-8\n% !TeX program = lualatex\n% !TeX spellcheck = en_US\n% !TeX root = thesis.tex\n\n\\chapter{Computational Fluid Dynamics}\n\\label{chap:CFD}\n\\index{CFD}\n%\\todo{This should be $\\leq$ 10 pages;work in progress}\n\n\n\nThis chapter aims to provide a concise introduction to \\gls{CFD}. \nThe main focus are the governing equations of \\CFD\\ and the assumptions and approximations needed to model natural ventilation.\nThis chapter does not attempt to cover numerical methods in great detail\\textemdash for further information, refer to the relevant literature \\citep{Wilcox2006, Etheridge2012, Nielsen2007, Ferziger}. \n\n\\Fref{fig:schema_cfd} illustrates the usual work-flow necessary to solve \\gls{CFD} problems.\nThe work-flow can be summarized in 3 parts, namely (1) pre-processing, (2) numerical simulation and (3) post-processing:\n\n\n\\begin{enumerate}\n\t\n\\item Pre-processing entails the real-world problem definition, which has to be simplified as far as possible to be sufficiently captured by the physical and mathematical model. Once this is done, the \\gls{CAD} geometry has to be meshed appropriately (discretization) into a finite number of discrete regions, called cells. Where high pressure gradients are expected, the mesh should be appropriately refined to capture important flow features. This work-flow is illustrated in  \\fref{fig:cadboundary}.\n\n\\begin{sidefigure}[2][htb]\n\t\\centering\n\t\\includegraphics[width=0.6\\linewidth, trim= 0cm 1cm 1cm 0, clip]{images/CAD_boundary}\n\t\\captionsetup{format=plain,labelsep=newline}\n\t\\caption[Relation between \\gls{CAD} geometry, computational grid and boundary conditions]{Illustration of the relation between a \\gls{CAD} geometry, the computational grid and its boundaries, and the boundary conditions applied. Adapted from \\citep{Maric2014}.}\n\t\\label{fig:cadboundary}\n\\end{sidefigure}\n\n\\item Before the simulation starts, physically appropriate boundary conditions as well as numerical settings have to be specified. The simulation eventually solves the algebraic set of equations by a solver that is tailored to capture the physical problem. The simulation ends after the simulation has reached either the final number of iterations or the specified convergence criteria.\n\n\n\\item Finally, the variables of interest need to be post-processed by visualizing the fluid flow with appropriate plots or further calculations. This should be supplemented by a verification/validation study in which the simulation is compared against measured values. An error estimation and sensibility analysis is needed to finally discuss the results. \\CFD\\ studies are usually of an iterative nature, which means the conclusions drawn will influence the pre-processing of the following simulation. This will procedure will be repeated until results are compliant with verification \\& validation guidelines.\n\n\\end{enumerate}\n\n\n\n\n\\begin{figure}[htb]\n\t\\includegraphics[width=1\\linewidth, trim=1.1cm 0cm 1.1cm 0, clip]{images/cfd_schematic}\n\t\\caption[Work-flow schematic for \\CFD]{Work-flow schematic for \\CFD. Adapted from \\citep{Giglmaier2016}.}\n\t\\label{fig:schema_cfd}\n\\end{figure}\n\n\n\n%\n% %\n% % %\n% % % %\n% % %\n% %\n%\n\n\\clearpage\n\\section{Governing equations}\n\\label{sec:CFD:governing_equations}\n\\index{CFD!governing equations}\n\nThe \\glsplural{NSE} describe the conservation of (1) mass , (2) momentum  and (3) energy.\nThe \\glsplural{NSE} are derived from (1) the continuity equation, (2) Newton's second law and (3) the first law of thermodynamics. \nThese equations treat the flow as a continuum and can be solved analytically only for several specific cases.\nIt is, however, possible to discretize the equations and solve them with regard to time and space.\nThe following notations $u$, $\\bar{u}$, $u^{\\prime}$ denote the instantaneous, mean, and fluctuating terms, respectively.\n\nThe continuity equation, also referred to as mass balance, is defined as:\n\n\\begin{equation}\n\\frac{\\delta }{\\delta t}\\rho +\\nabla (\\rho \\vec{u})= 0\n\\label{eq:theory:continuity}\n\\end{equation}\n\nFor a steady flow through a control volume, this equation shows that the net mass flux in the control volume must be zero.\nThe equation for linear momentum conservation, also know as the \\gls{NSE} in its non-conservative form, is defined as:\n\n\\begin{equation}\n\\rho\\left[\\frac{\\delta \\vec{u}}{\\delta t}+(\\vec{u}\\cdot\\nabla)\\vec{u} \\right ]=-\\nabla p + \\nabla \\bar{\\bar{\\tau}}+\\rho \\vec{f}\n\\label{eq:theory:momentum_conservation}\n\\end{equation}\n\nwhere $\\vec{f}$ is the body force per unit mass. If the weight of the fluid happens to be the only force present, $\\vec{f}$ may be replaced with the gravitational vector $\\vec{g}$.\n$\\bar{\\bar{\\tau}}$ is the symmetrical viscous stress tensor. For Newtonian fluids it is defined as:\n\n\n\n\n\\begin{equation}\n\\tau_{ij} = \\mu \\left(\\frac{\\delta u_i}{\\delta x_j} +\\frac{\\delta u_j}{\\delta x_i}\\right )-\\frac{2}{3} (\\nabla \\vec{u})\\delta_{ij} ,\\quad i,j = 1,2,3\n\\label{eq:CFD:stress_tensor}\n\\end{equation}\n\n\nwhere $\\delta_{ij}$ is the Kronecker-Delta operator, and \\gls{symb:mu} is the \\glsdesc{symb:mu} \\citep{Sert2012}.\n\n\\paragraph*{Incompressible flows}\n\\index{CFD!incompressible flows}\n\n\nFor incompressible flows, density is defined as a constant, which leads to a simplified set of equations. Consequently,  \\fref{eq:theory:continuity} reduces to:\n\n\n\\begin{equation}\n\\nabla \\vec{u} = 0\n\\label{eq:CFD:continuity_imcompressible}\n\\end{equation}\n\n\\Fref{eq:CFD:continuity_imcompressible} states that the velocity field for incompressible flows is divergence-free. For the conservation of momentum, using \\fref{eq:CFD:continuity_imcompressible} in  \\fref{eq:CFD:stress_tensor}  cancels the second term in the stress tensor. Moreover, if viscous effects are negligible, \\fref{eq:theory:momentum_conservation} simplifies to:\n\n\n\n\\begin{equation}\n\\rho\\left[\\frac{\\delta \\vec{u}}{\\delta t}+(\\vec{u}\\cdot\\nabla)\\vec{u} \\right ]=-\\nabla p + \\mu \\nabla^2 \\vec{u} +\\rho \\vec{f}\n\\label{eq:Navier_incompressible}\n\\end{equation}\n\n\\glsdesc{symb:mu} and \\glsdesc{symb:nu} are related by the density.\n\n\\begin{equation}\n\\nu= \\frac{\\mu}{\\rho}\n\\end{equation}\n\nThus, if we normalize \\fref{eq:Navier_incompressible} by the density, we obtain the form of the \\gls{NSE} that is commonly referred to when using this method.\n\n\\begin{equation}\n\\frac{\\delta \\vec{u}}{\\delta t}+\\underbrace{(\\vec{u}\\cdot\\nabla)\\vec{u}}_{\\text{convective term}} =-\\frac{1}{\\rho}\\nabla p + \\underbrace{\\nu \\nabla^2 \\vec{u}}_{\\text{diffusion term}}+\\vec{f}\n\\end{equation}\n\n\n\\gls{symb:nu} is the \\glsdesc{symb:nu}, which is considered to be constant. \n\nIn a 3-dimensional space, this yields \\num{4} equations with \\num{4} unknowns, namely the pressure and \\num{3} velocity components.\n\n%\\section{Finite volume method}\n\nThe process of representing differential equations as a set of algebraic equations with equivalent properties is called discretization. In OpenFOAM, this is done with an approach called \\gls{FVM}. This is necessary to solve the equations numerically.\nAfter setting the appropriate \\BC, it can be expressed in a linear equation system of the form:\n\n\n\\begin{equation}\n\\underline{A}\\, \\vec{x} = \\vec{b}\n\\end{equation}\n\nwhere $\\vec{x}$ is the vector of the variable of interest, $\\underline{A}$ is the square matrix and $\\vec{b}$ is the source vector \\citep{Sert2012}.\n\n%\n% %\n% % %\n% % % %\n% % %\n% %\n%\n", "meta": {"hexsha": "329ec24190acd4a88fb521d8f515f9e555308790", "size": 7313, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "3_chapter.tex", "max_stars_repo_name": "kostnermo/CleanThesisLaTeX", "max_stars_repo_head_hexsha": "021e8ef8c6e019ab4b12ab68d8dab021765dd17d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2018-03-09T03:57:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-03T18:00:07.000Z", "max_issues_repo_path": "3_chapter.tex", "max_issues_repo_name": "kostnermo/CleanThesisLaTeX", "max_issues_repo_head_hexsha": "021e8ef8c6e019ab4b12ab68d8dab021765dd17d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-24T15:24:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-24T15:25:07.000Z", "max_forks_repo_path": "3_chapter.tex", "max_forks_repo_name": "kostnermo/CleanThesisLaTeX", "max_forks_repo_head_hexsha": "021e8ef8c6e019ab4b12ab68d8dab021765dd17d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-03-08T22:55:05.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-05T09:43:28.000Z", "avg_line_length": 46.8782051282, "max_line_length": 611, "alphanum_fraction": 0.7590592096, "num_tokens": 2034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3148873037022067}}
{"text": "\\documentclass[10pt,leqno]{amsart}\n\n% Les packages\n\\usepackage{amssymb,amsbsy}\n\\usepackage{mathrsfs}\n\\usepackage{color}\n\\usepackage{soul}\n\\usepackage{graphicx}\n\\usepackage{booktabs}\n%\\setlength{\\heavyrulewidth}{1.5pt}\n%\\setlength{\\abovetopsep}{4pt}\n\\usepackage[pdfborder={0 0 0}]{hyperref}\n\\usepackage[left=2cm,right=2cm,top=2cm,bottom=2cm]{geometry}\n\\setlength{\\parskip}{3pt} % 1ex plus 0.5ex minus 0.2ex}\n%\\setlength{\\parindent}{15pt}\n\n% La profondeur de la table des matieres\n\\setcounter{tocdepth}{1}\n\n% Les principaux ensembles\n\\newcommand{\\Abs}[1]{\\left\\lvert#1\\right\\rvert}\n\\newcommand\\N{{\\mathbb N}}\n\\newcommand\\R{{\\mathbb R}}\n\\newcommand\\T{{\\mathbb T}}\n\\newcommand\\C{{\\mathbb C}}\n\\newcommand\\Q{{\\mathbb Q}}\n\\newcommand\\Z{{\\mathbb Z}}\n\\newcommand\\Pp{{\\mathbb P}}\n\\newcommand\\Ee{{\\mathbb E}}\n\\def\\x{{\\mathbf x}}\n\\def\\w{{\\mathbf w}}\n\\def\\xxi{{\\pmb \\xi}}\n\n% Quelques definitions raccourcis pour les calculs\n\\DeclareMathOperator{\\diver}{div}\n\\DeclareMathOperator{\\Supp}{Supp}\n\\newcommand{\\dbm}{\\mathbf{d}}\n\\def\\esssup{\\mathop{\\rm ess\\,sup\\,}}\n\\def\\essinf{\\mathop{\\rm ess\\,inf\\,}}\n\\newcommand{\\indiq}{{\\bf 1}}\n\n% Les defs, theo, et equations\n\\newtheorem{theo}{Theorem}\n\\newtheorem{prop}[theo]{Proposition}\n\\newtheorem{lem}[theo]{Lemma}\n\\newtheorem{cor}[theo]{Corollary}\n\\newtheorem{rem}[theo]{Remark}\n\\newtheorem{rems}[theo]{Remarks}\n\\newtheorem{defin}[theo]{Definition}\n\\newtheorem{ex}[theo]{Example}\n\\newtheorem{notation}[theo]{Notations}\n\\renewcommand{\\theequation}{\\thesection.\\arabic{equation}}\n\\renewcommand{\\thetheo}{\\thesection.\\arabic{theo}}\n\n\\newcommand{\\PM}[1]{\\textcolor{red}{#1}}\n\\newcommand{\\CQ}[1]{\\textcolor{blue}{#1}}\n\n%%%%%%%%%%      Document     %%%%%%%%%%%%%%%\n\n\\begin{document}\n\n\\title[]{Machine learning for Social Ideology Recognition: An Experimental Case Study.}\n\n\\author{H. Bahamondes \\and C. Quininao} \n\n\\begin{abstract}\n\n\\end{abstract}\n\n\\maketitle\n\n \n\\begin{center} {\\bf Preliminary version of \\today}\n\\end{center}\n\n\\bigskip\n\\textbf{Keywords}: Vote Selling - Machine Learning\n\n\\vspace{0.3cm}\n\\bigskip\n\n\\tableofcontents\n\n\\section{Materials and methods}\n\nThe overall model training and validation process consists in a three phases. First we clean the database by eliminating repeated observations, and we normalize using a MinMax scaler. We perform two different experiments, first we use machine learning algorithms to classify participants as vary liberals or not, and later we do the same for very conservative. Since our resulting training pairs datasets are strongly imbalanced, prior to the construction of learning models, we use the SMOTE~\\cite{chawla2002smote} oversampling procedure with five nearest neighbors for each vote-selling sample~\\cite{artetxe2020balanced}. The resulting training data pairs is then used for validation in a repeated cross-validation (RCV) process. This process consists in construct several machine learning models by using the same dataset but under the idea of generate folds and repetition. In particular, each cross-validation repetition consists in: partitioning the dataset in a particular number of folds, using each fold as a test dataset while using all remaining data for model training. Finally, we report average performance measures across all repetitions. In this manuscript, the reported results are the average of the 30 repetitions of the CV models.\n\n\\subsection{Classification Methods}\n\nSeveral machine learning approaches can be used for analyze the present data, in a predictive model framework~\\cite{vapnik2013nature,witten2002data,maimon2005data}. Due to the nature of the experiment and the data, and since we do not have a large dataset, we discard the application of deep learning algorithms~\\cite{balas2019handbook}. Therefore, we focus in the following classical well-known methods: \\textit{Support Vector Machines, Multilayer Perceptron and Na\\\"ive Bayes method.}\n\n\\subsubsection{Support Vector Machines (SVM)} As stated in~\\cite[Chapter 12]{maimon2005data}, support vector machines (SVMs) are a set of related methods for supervised learning, which has applications to classification (the output data is a sequence of tags) and regression (the output data is a continuous variable) problems. When using SVM for the classifying problem, we look for linear functions that can separate the data based on the support vectors or boundaries of the classes. The idea of the algorithm is to find the optimal hyperplane, i.e., the hyperplane that maximizes the distance to the boundaries of each class. This can be done by stating a quadratic programming problem~\\cite{vapnik2013nature}. When the classes are not linearly separable, then it is possible place the data into a space of superior dimensionality using a kernel trick~\\cite{vapnik2013nature,maimon2005data}, so that the transformed dataset might become linearly separable. We used the SVM module from Python Sklearn library for training and estimation. We try linear and Radial Bases Function (RBF).\n\n\\subsubsection{Multilayer Perceptron} Multilayer perceptron (MLP) is the classical feed-forward artificial neural networks (ANN) composed of multiple densely interconnected layers of computational units, aka artificial neurons~\\cite{wolff2019machine}. It corresponds to a supervised learning algorithm that finds a function that maps our multidimensional samples (socio demographic data) into the vote-selling response of the experimental participants. Any MLP is constructed as follows: (i) we fix a number of hidden layers, (ii) the architecture starts with $m$ artificial neurons corresponding to the features of the input data corresponding to the input layer, (iii) any artificial neuron in the first hidden layer integrates the inputs from the input layer and combines the input values with a weighted linear summation (the weights become part of the parameters to be tuned in the learning phase), (iv) the result of this summation is nonlinearly transformed through an activation function (for instance an hyperbolic $\\tanh$ function). The procedure is repeated for each hidden layer, until the output layer is reached. The connection weights can be learned from data applying the back-propagation algorithm~\\cite{haykin2004comprehensive}. Concerning the implementation of the MLP, we used the MLPClassifier module from Python Sklearn library for training and estimation. The MLPClassifier implements a MLP algorithm that trains using back-propagation through a stochastic gradient descent. We used the rectified linear unit function for the activation of the hidden layers. The MLP model constructed has two hidden layer, each of 50 neurons.\n\n\\subsubsection{Na\\\"ive Bayes Method} Na\\\"ive Bayes methods are a set of supervised learning algorithms based on applying Bayes’ theorem with the ``naive'' assumption that all features of an individual are independent. Bayes’ theorem provides a rule to calculate the conditional probability of an event given some knowledge, in terms of the conditional probability of the knowledge given the event. This idea along with the naive independent assumption allows the model to estimate the joint probability distribution of a  feature vector as the product of the unidimensional distribution probabilities of each feature~\\cite{wolff2019machine}. In our study we use the GaussianNB module from Sklearn library, which implements the Gaussian Naive Bayes algorithm for classification. The likelihood of the features is assumed to be Gaussian.\n\n\\subsection{Classification Performance Metrics} We illustrate the chosen metrics with only liberal classification machines, the conservative situation is straightforward. At the end of each cross-validation fold we have two different vectors: $y_{test}$ corresponding to the responses of the participants to the very liberal question restricted to the fold used for testing, and $y_{pred}$ corresponding to the predicted answers given by the model for the input features. With these two vectors at hand we compute the \n\\begin{itemize}\n\\item True positive counts (tp): number of participants such that the model predicts as very liberal and they actually belong to the very liberal class\n\\item True negative counts (tn): number of participants such that the model predicts as not very liberal and they do not belong to the very liberal class\n\\item False positive counts (fp): number of participants such that the model predicts as very liberal but they do not belong to the very liberal class\n\\item False negative counts (fn): number of participants such that the model predicts as not very liberal but they actually belong to the very liberal class\n\\end{itemize}\nwith this numbers, we compute the Recall or sensitivity $R$\\footnote{The fraction of examples classified as very liberal, among the total number of very liberal examples.}, the positive predictive value $PPV$ or precision\\footnote{The fraction of true very liberal examples among the examples that the model classified as very liberal.} and the $f$-score\\footnote{A perfect model has an $f$-score of 1.} with the relationships\n$$\nR=\\frac{tp}{tp+fn},\\quad PPV=\\frac{tp}{tp+fp},\\quad F=\\frac{2}{1/R+1/PPV},\n$$\nand finally report the average and the standard deviation across all cross-validation folds. Notice one could use the accuracy metric defined as\n$$\nA = \\frac{tp+tn}{tp+tn+fp+fn}=\\frac{tp+tn}{\\text{size of the fold}},\n$$\nbut considering that the dataset is strongly imbalanced, previous measures are more informative. Another metric widely used to compare binary classifiers~\\cite{wolff2019machine,artetxe2020balanced} is the Receiver Operating Curve or ROC, which corresponds to a plot of sensitivity $R$ versus the false positive rate\n$\nFPR = \\frac{fp}{fp+tn}.\n$\nROC is computed as a probability curve and, and the area under ROC curve of AUC represents the degree of separability. In other words, it quantifies in a number how much the model is capable of distinguishing between classes. In our setting, the higher the AUC, the better the model is at predicting liberals as liberals and non liberals as non liberals. Remark that (i) a perfect model has AUC equals to 1, (ii) a model with AUC approximately 0, means that the model is actually reciprocating the classes, therefore a simple relabelling is enough to get good results; and (iii) the worst case scenario is when the AUC equals 0.5, meaning that the model has no class separation capacity.\n\nThe methodology we use to compute previously explained metrics is as follows: at each fold test, we use the remaining folds as training dataset. Since the resulting training data set is imbalanced, we use the oversampling technique SMOTE with five neighbors on the minority class. Remark that the test set remains imbalanced which has some consequences. In particular, even one misclassified sample translates into large reductions of the performance measures. Moreover, the number of remaining liberal samples in each fold depends on the number of folds, thus having consequences in the imbalance ratio. We report results with decreasing number of RVC folds in order to test the stability of the results.\n\n\\section{Results}\n\nTables~\\ref{tab:r_ppv} and~\\ref{tab:f_auc} show the results for  metrics mentioned above of the machine learning techniques after 40 repetitions (3 fold), 10 repetitions (4 fold), 8 repetitions (5 fold) and 4 repetitions (10 fold) of the RCV experiments with SMOTE class imbalance correction. There is no statistical evidence to argument that the number of folds has an effect on the performance of each method. An F- test over the number of folds shows that there is no statistically significant difference $p\\gg0.1$.\n\nIf we test the performance of each methods we find some differences, specially on the PPV, f-Score and AUC metrics. SVM with RBF kernel is above SVM Linear, MLP, and NB independently of the number of folds. On the other hand, the recall metric (R), shown in Table~\\ref{tab:r_ppv} (left), shows no sufficient evidence to affirm that methods perform differently. Indeed, applying an F-test over the different type of machines for the each folds number we find no strong statistical evidence, and it would depend on the confidence level whether or not we reject the null hypothesis  (for instance, the p-value es approx $0.026$ for 10 folds). However, the result changes dramatically, if we discard the MLP model which performs below any other model ($p\\approx0.77$ for 10 folds). We conclude that according to the recall metric, all methods except for MLP have similar performance. Figure 2 shows the ROC curves for all approaches in the case of RCV with 5 folders.\n\nThe f-scores shown in Table~\\ref{tab:f_auc} confirm that SVM with RBF kernel improves over SVM Linear, MLP and NB regardless of RCV number of folders. An F-test carried out over these results confirms that the performance differences between predictive models are statistically significant  ($p\\approx0.002$) . Specific one-sided t-tests comparing each pair of modeling approaches confirms that SVM with RBF kernel perform better than SVM Linear, MLP and NB. However, the superiority of SVM with RBF kernel relative to MLP is less pronounced ($p\\approx0.05$). On the contrary, the effect is more pronounced for the AUC metric. The F-test carried out over these results confirms ($p\\ll0.001$), t-test pairwise tests ($p<0.001$). \n\\begin{table}[!htbp]\n\\centering\n\\footnotesize\n\\caption{Average $\\pm$ standard deviation Recall R (left) and positive predictive value PPV (right) performance of SVM (linear), SVM (RBF), MLP and NB for decreasing number of folders in the repeated cross validation process. All results are calculated with SMOTE oversampling correction of class imbalance.}\n\\label{tab:r_ppv}\n\\begin{tabular}{*5c}\n\\toprule\n  \\multicolumn{5}{c}{SMOTE} \\\\\nnfolds & SVM (linear) & SVM (RBF) & MLP & NB\n\\\\\n\\midrule\n10 & 0.68$\\pm$0.07 & 0.67$\\pm$0.08 & 0.65$\\pm$0.07 & 0.68$\\pm$0.08\n\\\\\n5 & 0.68$\\pm$0.05 & 0.67$\\pm$0.04 & 0.65$\\pm$0.06 & 0.66$\\pm$0.06\n\\\\\n4 & 0.67$\\pm$0.03 & 0.66$\\pm$0.04 & 0.64$\\pm$0.04 & 0.67$\\pm$0.04\n\\\\\n3 & 0.68$\\pm$0.03 & 0.67$\\pm$0.05 & 0.67$\\pm$0.05 & 0.67$\\pm$0.05\n\\\\\n\\bottomrule\n\\end{tabular}\n\\quad\n\\begin{tabular}{*5c}\n\\toprule\n  \\multicolumn{5}{c}{SMOTE} \\\\\nnfolds & SVM (linear) & SVM (RBF) & MLP & NB\n\\\\\n\\midrule\n10 & 0.45$\\pm$0.06 & 0.52$\\pm$0.08 & 0.47$\\pm$0.07 & 0.44$\\pm$0.07\n\\\\\n5 & 0.46$\\pm$0.05 & 0.52$\\pm$0.07 & 0.48$\\pm$0.05 & 0.44$\\pm$0.05\n\\\\\n4 & 0.45$\\pm$0.04 & 0.52$\\pm$0.06 & 0.47$\\pm$0.04 & 0.43$\\pm$0.05\n\\\\\n3 & 0.45$\\pm$0.03 & 0.52$\\pm$0.04 & 0.45$\\pm$0.03 & 0.44$\\pm$0.04\n\\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n\n\\begin{table}[!htbp]\n\\centering\n\\footnotesize\n\\caption{Average $\\pm$ standard deviation f-score (left) and AUC (right) performance of SVM (linear), SVM (RBF), MLP and NB for decreasing number of folders in the repeated cross validation process. All results are calculated with SMOTE oversampling correction of class imbalance.}\n\\label{tab:f_auc}\n\\begin{tabular}{*5c}\n\\toprule\n  \\multicolumn{5}{c}{SMOTE} \\\\\nnfolds & SVM (linear) & SVM (RBF) & MLP & NB\n\\\\\n\\midrule\n10 & 0.54$\\pm$0.06 & 0.58$\\pm$0.07 & 0.54$\\pm$0.06 & 0.53$\\pm$0.06\n\\\\\n5 & 0.55$\\pm$0.05 & 0.59$\\pm$0.05 & 0.55$\\pm$0.05 & 0.53$\\pm$0.05\n\\\\\n4 & 0.54$\\pm$0.03 & 0.58$\\pm$0.04 & 0.54$\\pm$0.03 & 0.52$\\pm$0.04\n\\\\\n3 & 0.54$\\pm$0.02 & 0.58$\\pm$0.03 & 0.54$\\pm$0.03 & 0.53$\\pm$0.04\n\\\\\n\\bottomrule\n\\end{tabular}\n\\quad\n\\begin{tabular}{*5c}\n\\toprule\n  \\multicolumn{5}{c}{SMOTE} \\\\\nnfolds & SVM (linear) & SVM (RBF) & MLP & NB\n\\\\\n\\midrule\n10 & 0.68$\\pm$0.04 & 0.72$\\pm$0.05 & 0.68$\\pm$0.04 & 0.67$\\pm$0.04\n\\\\\n5 & 0.67$\\pm$0.03 & 0.72$\\pm$0.03 & 0.68$\\pm$0.03 & 0.67$\\pm$0.03\n\\\\\n4 & 0.67$\\pm$0.02 & 0.72$\\pm$0.04 & 0.67$\\pm$0.03 & 0.67$\\pm$0.03\n\\\\\n3 & 0.68$\\pm$0.02 & 0.71$\\pm$0.02 & 0.68$\\pm$0.02 & 0.67$\\pm$0.02\n\\\\\n\\bottomrule\n\\end{tabular}\n\n\\end{table}\n%$$\n%0.000001\n%Ttest_indResult(statistic=4.705128336546723, pvalue=1.0954486268281921e-05)\n%Ttest_indResult(statistic=4.044118570892123, pvalue=0.00012315327310524272)\n%Ttest_indResult(statistic=4.82778883801976, pvalue=6.762417354421785e-06)\n%$$\n\\bibliographystyle{abbrv}\n\\bibliography{biblio_conjoint.bib} \n\n\\end{document}\n ", "meta": {"hexsha": "9a5242faa644eabc5de66e5080309800e2470c8c", "size": 16068, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Datos/Notas/learning_model.tex", "max_stars_repo_name": "hbahamonde/Smote_US", "max_stars_repo_head_hexsha": "7bbb2bd5182e96c034f7b3c8b6e13d7584f8d6d3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Datos/Notas/learning_model.tex", "max_issues_repo_name": "hbahamonde/Smote_US", "max_issues_repo_head_hexsha": "7bbb2bd5182e96c034f7b3c8b6e13d7584f8d6d3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Datos/Notas/learning_model.tex", "max_forks_repo_name": "hbahamonde/Smote_US", "max_forks_repo_head_hexsha": "7bbb2bd5182e96c034f7b3c8b6e13d7584f8d6d3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-07T02:02:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T02:02:07.000Z", "avg_line_length": 73.7064220183, "max_line_length": 1649, "alphanum_fraction": 0.7667413493, "num_tokens": 4458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3148873037022067}}
{"text": "\n%%\n%% Template chap2.tex\n%%\n\n\\chapter{Photometric Classification}\n\\label{cha:ml}\n\nLet us now bring machine learning to the realm of astronomy. We start with a motivation for why\nastronomers might find machine learning helpful (Section \\ref{sec:machine}) and an overview of\nthree families of classifiers (Section \\ref{sec:classifiers}). We then discuss active learning and\nsix heuristics that can be used to rank unlabelled examples (Section \\ref{sec:active} and\n\\ref{sec:heuristics}). Our novel contributions include the application of Thompson sampling to the\nheuristic selection setting  (Section \\ref{sec:bandit} and \\ref{sec:thompson}) and a derivation of\nthe multi-class posterior balanced accuracy (Section \\ref{sec:measures}) which can be used to\nmeasure the performance of our algorithms.\n\n\n\\section{Maching Learning in Astronomy} \\index{machine learning}\n\\label{sec:machine}\n\nThe two most common types of celestial objects are stars and galaxies. There are also some other\ninteresting objects such as quasars and white dwarfs. Quasars \\index{quasar} are thought to be\nsupermassive black holes surrounded by an accretion disc. They are very luminous and, unlike\ngalaxies, appear as single-source objects. White dwarfs \\index{white dwarf} are low to intermediate\nmass stars that are in their final evolutionary stage. They are very dense and have a faint\nluminosity.\n\nOne way to classify objects into these various groups is to manually inspect their spectra.\n\\index{spectrum} There have even been attempts to make the process more automatic. For example,\n\\citeN{hala14} achieved a 95\\% accuracy rate by training a convolutional neural network\n\\index{neural network} on one-dimensional spectra to classify objects into stars, quasars, and\ngalaxies. Even so, it is currently not possible to obtain a spectrum of every object, especially\nfaint ones. This means that only a small number of objects (e.g. 0.35\\% in the SDSS dataset) can be\nclassified this way. For the rest, we only have photometric measurements.\n\nFortunately, the field of machine learning came about to solve this kind of problem. In the most\nbasic set-up, we have a collection of objects, each with a vector of photometric measurements\n$\\bm{x} \\in \\X$. A subset of them has been spectroscopically classified into some class $y \\in \\Y$\nand they form the labelled set $\\Labelled \\subset \\X \\times \\Y$. We call $\\X$ the feature space and\n$\\Y$ the label space. Let us now partition $\\Labelled$ into two disjoint subsets, a training set\n$\\Labelled_T$ and a test set $\\Labelled_S$. During the training phase, we feed  $\\Labelled_T$ to a\nclassifier, and the classifier will then learn a hypothesis $h: \\X \\rightarrow \\Y$. The labelling\nprocess might not be perfect, so the goal in machine learning is to capture as much of the\nunderlying trend in the data as possible, while avoiding fitting the random noise. To see how well\nthe hypothesis generalises to unknown data, in the testing phase, we ask the classifier to predict\nlabels of objects in  $\\Labelled_S$. These predictions are then be compared to the true labels,\nand an accuracy rate can be calculated.\n\n\n% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %\n\\section{Classifiers}\n\\label{sec:classifiers}\n\nThree families of classifiers are used in our experiments. They are random forests, logistic\nregression, and support vector machines. Below we give a quick overview of how each of them works.\nWe do not implement these classifiers ourselves. Rather we shall use scikit-learn\n\\cite{pedregosa11}, the most well-known machine learning package in Python.\n\n\\subsection{Random Forest} \\index{random forest}\n\\label{sub:forest}\n\nTo understand the motivation behind random forests, we first need to know how to construct\nindividual decision trees\\index{decision tree}. Building each of these trees is like playing a game\nof Twenty Questions. We start with the whole training set and at each step, we slice the feature\nspace along the axis of one feature. After many steps, we end up with a set of hyper-dimensional\ncuboids which form a partition of the feature space. The algorithm stops when each of these cuboids\ncontains data from only one class. There are many criteria that we can use to decide on which\nfeature and where we slice along the axis. In this thesis, we use the Gini impurity \\index{Gini\n    impurity} which intuitively measures the potential misclassification rate. In particular, let $k$\nbe the number of classes and $q_D(i)$ be the frequency of objects belonging to class $i$ in set\n$D$. Then the Gini impurity of $D$ is the probability that a randomly selected object from $D$ is\nmisclassified if it were labelled according to its frequency in $D$:\n\t\\begin{IEEEeqnarray*}{lCl}\n\t\t\\iota_G(D) &=& \\sum_{i=1}^{k} q_D(i) (1 - q_D(i)) \\\\\n\t\t           &=& \\sum_{i=1}^{k} q_D(i)  - \\sum_{i=1}^{k} q_D(i)^2 \\\\\n\t\t           &=& 1 - \\sum_{i=1}^{k} q_D(i)^2\n\t\\end{IEEEeqnarray*}\nWhen we partition $D$ into subsets $\\{D_1, D_2, ..., D_d\\}$, the Gini impurity of $D$ is now the sum\nof the individual Gini impurities, weighted by the size of the subsets:\n\t\\begin{IEEEeqnarray*}{lCl}\n\t\t\\iota_G(D) &=& \\sum_{i=1}^{d} \\frac{|D_i|}{|D|} \\iota_G(D_i)\n\t\\end{IEEEeqnarray*}\nObserve that if a subset contains objects from only one class, then its Gini impurity will be zero.\nThis gives us the following splitting criterion: at each step, slice the feature space along the\naxis that will result in the greatest drop in the Gini impurity.\n\nOne problem with decision trees is that they tend to overfit \\index{overfitting} the data and thus\ndo not generalise well. To solve this, \\citeN{breiman01} proposes that we build many decision\ntrees, thus creating a random forest. The random forest makes its prediction by simply counting up\nthe predictions of all the individual trees and then choosing the most popular choice. By taking an\naverage of the predictions, we avoid the problem of overfitting. Furthermore, for each tree, we\nonly give it a small bootstrap sample and at each split, we only consider a small number of\nfeatures. This bootstrapping and random subspace selection have been shown empirically to improve\nthe accuracy \\cite{breiman96, ho98, louppe12}. Another nice feature of random forests is that\nthey are extremely fast and hence scale well with large datasets. Although they do not provide\nclass probability estimates, we can use proportions of the votes as a proxy for the\nprobabilities. However, in practice, we find these probability estimates to be a bit unstable.\n\n\n\\subsection{Logistic Regression} \\index{logistic regression}\n\\label{sub:logistic}\n\nIf we want the hypothesis to model actual class probabilities, then an alternative approach is to use\nlogistic regression. Developed by \\citeN{cox58}, the algorithm tries to directly model the\nprobability of being in a class. Let $\\bm{x}$ be the feature vector and $\\bm{\\theta}$ be the vector\nof coefficients. The linear predictor $\\eta$ is defined as\n\t\\begin{IEEEeqnarray*}{lCl}\n\t\t\\eta(\\bm{x}) &=& \\bm{\\theta}^T \\bm{x}\n\t\\end{IEEEeqnarray*}\t\nSince probabilities must lie between 0 and 1, we want our predictor to have the same range. This can\nbe achieved by wrapping $\\eta$ around the logistic function:\n\t\\begin{IEEEeqnarray*}{lCl}\n\t\tp(y=1 | \\bm{x}; \\bm{\\theta}) &=& \\sigma(\\eta(\\bm{x}))  \\\\\n                                    &=& \\frac{1}{1 + e^{-\\eta(\\bm{x})}}\n\t\\end{IEEEeqnarray*}\nWe can now interpret $p(y=1 | \\bm{x}; \\bm{\\theta})$ as the probability that an object with feature vector\n$\\bm{x}$ belongs to the positive class. The goal of the algorithm is then to use the training data\nto estimate the coefficient vector $\\bm{\\theta}$. This can be done by finding $\\hat{\\bm{\\theta}}$ that\nmaximises the log-likelihood function:\n    \\begin{IEEEeqnarray*}{lCl}\n        \\hat{\\bm{\\theta}} &=& \\argmax_{\\bm{\\theta}} \\sum_{i = 1}^{n} \\log p(y_i| \\bm{x}_i; \\bm{\\theta})\n                         - \\frac{1}{C} R(\\bm{\\theta})\n    \\end{IEEEeqnarray*}\nwhere $n$ is the size of the training set, $R(\\bm{\\theta})$ is the regularisation term, and $C$ is\nthe inverse of the regularisation strength. \\index{regularisation} A low value of $C$ forces the\nvalues of the parameters to be small, thus avoiding overfitting. However if $C$ is too low, we\nmight have a hypothesis that is too simple. For the regularisation term, we can either sum up the\nabsolute values of the coefficients (L1) or the squares of the coefficients (L2):\n    \\begin{IEEEeqnarray*}{lClllCl}\n        R_{L1}(\\bm{\\theta}) &=& \\sum_{i = 1}^{m} \\abs{\\bm{\\theta}_i } &\\qquad\\qquad\n        R_{L2}(\\bm{\\theta}) &=& \\sum_{i = 1}^{m} \\bm{\\theta}_i^2\n    \\end{IEEEeqnarray*}\nwhere $m$ is the number of features. One advantage of the L1 regularisation is that it leads to\nsparse solutions, where a lot of coefficients become zero \\cite{tibshirani96}. This is useful if we\nhave many features, which for example is the case after we do a polynomial transformation (see\nSection \\ref{sub:complex}).\n\nThere are a few ways to extend the above model to the multi-class setting. One option is\nmultinomial logistic regression, where we would need to jointly solve a set of $(k-1)$ binary\nregressions if we have $k$ classes. In practice, when running the multinomial option in\nscikit-learn, \\index{scikit-learn} the probability estimates are not very reliable, especially when\nwe have many classes. The cause of this is unknown, but it is more likely due to flaws in the\nscikit-learn implementation than in the actual theory. A more empirically stable alternative is to\nuse the one-vs-rest \\index{one-vs-rest} strategy, where we run $k$ independent binary regressions.\nIn particular, for class $i$, we pretend that the dataset contains only objects from class $i$ and\nclass `not $i$'. We then train the binary logistic model on this simplified dataset and we do this\n$k$ times, one for each class. At the end, we end up with $k$ probabilities. These can be\ninterpreted like normal class probabilities after normalisation.\n\n\n\\subsection{Support Vector Machines} \\index{support vector machine}\n\\label{sub:svm}\n\nSupport vector machines (SVMs), first introduced by \\citeN{boser92}, are another popular family of\nalgorithms. They have been used in astronomy, for example by \\citeN{elting08}, to find non-linear\ndecision boundaries in the colour space of the SDSS dataset. The idea here is to find a decision\nboundary that can maximise the distance between the boundary and the closest data points, which we\ncall support vectors. This involves finding the weights $\\hat{\\bm{w}}$ and the bias $\\hat{b}$ that\nminimise the objective function\n    \\begin{IEEEeqnarray*}{lCl}\n        \\argmin_{\\bm{w}, b} R(\\bm{w}) + C \\sum_{i = 1}^{n} \\ell(\\bm{x}_i)\n    \\end{IEEEeqnarray*}\nwhere $R(\\bm{w})$ can either be L1 or L2 regularisation \\index{regularisation} like in logistic\nregression, and $\\ell(\\bm{x}_i)$ is the loss function. \\index{loss function} Two common loss functions\nare the hinge loss\n    \\begin{IEEEeqnarray*}{lCl}\n        \\ell(\\bm{x}_i) &=& \\max (0, 1 - y_i (\\bm{w}^T \\bm{x}_i + b))\n    \\end{IEEEeqnarray*}\nand the square of the hinge loss\n    \\begin{IEEEeqnarray*}{lCl}\n        \\ell(\\bm{x}_i) &=& \\max (0, 1 - y_i (\\bm{w}^T \\bm{x}_i + b))^2\n    \\end{IEEEeqnarray*}\nAs usual, the penalty parameter $C$ controls the trade-off between the misclassification of\ntraining examples and the simplicity of the decision surface, with a low value of $C$ resulting in\na simple hypothesis. SVMs, in their original formulation, are inherently binary classifiers.\nHowever we can still use the one-vs-rest \\index{one-vs-rest} strategy to extend it to the\nmulti-class setting. There has even been an attempt to derive an inherently multi-class SVM\n\\cite{crammer02}.\n\n\n\\subsection{Learning Complex Hypotheses}\n\\label{sub:complex}\n\nBoth SVMs and logistic regression are linear classifiers. When dealing with real-world data like\nthose in astronomy, we should not expect to be able to separate classes with a hyper-dimensional\nplane. If we want them to learn more complex hypotheses, one option is do an explicit polynomial\ntransformation \\index{polynomial transformation} of the original photometric measurements. When we\ngive the classifier the transformed features, it would still find a linear boundary in the\ntransformed space. However, the boundary would most of the time be non-linear in the original space.\n\nA second option is to use the kernel trick which does an implicit map into a high-dimensional\nfeature space. For example, a popular kernel that is often used with SVMs is the radial basis\nfunction \\index{RBF kernel} (RBF), which actually maps the inputs into an infinite-dimensional\nspace. The RBF kernel has the parameter $\\gamma$ which is inversely proportional to the radius of\ninfluence of the support vectors. This means that a low value of $\\gamma$ corresponds to a smoother\nmodel.\n\nIn random forests, we do not have to worry about any transformation. Although in each round, we\nslice the data along only one axis, there is no limit on how many slices we can take and how small\nthe resulting cuboids can be. This allows us to learn arbitrarily complex hypotheses.\n\n\n% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %\n\\section{Overview of Active Learning} \\index{active learning}\n\\label{sec:active}\n\nWe now turn our attention to the construction of the training set. Getting spectroscopic labels is\nexpensive. Until now, astronomers do not have a quantitative method to help them choose objects\nwhose spectroscopic labels would provide them with the most amount of new information. Often, they\nsimply take a random sample of the sky. This, however, might not always be optimal. To see why,\nimagine that there is a group of objects with very similar photometric measurements. We can obtain\nspectra from all of them and conclude, for example, that they are all stars. However, a smarter way\nis to get only one spectrum from this group for labelling and let the classifier generalise to\nother similar objects. Keeping the size of the training set as small as possible while not\nsacrificing the classifier accuracy is the goal of active learning.\n\nThere are three main types of active learning: membership query synthesis, stream-based selective\nsampling, and pool-based active learning. In membership query synthesis\\index{membership query\n    synthesis}, we are allowed to request labels for any unlabelled instance in the feature space\n\\cite{angluin88}. Equivalently, we may request the astronomer to find an object with a certain\ncombination of colours and magnitudes. This is not very realistic since such objects might not even\nexist. In stream-based selective sampling\\index{stream-based selective sampling}, we sample objects\nfrom the source one at a time, and as objects are streaming in, we must decide to either label or\ndiscard each of them \\cite{cohn94}. The assumption here is that it is free to obtain unlabelled\nexamples, which again is not applicable to astronomy. Thus we shall not discuss membership query\nsynthesis and stream-based selective sampling further in this thesis.\n\nInstead, we shall focus on pool-based active learning \\index{active learning!pool-based}\n\\cite{lewis94}, the most relevant type of active learning for astronomy. In this setting, we keep\ntrack of two sets. As usual, we have a labelled set $\\Labelled$, which can be further partitioned\ninto a training set $\\Labelled_T$ and a test set $\\Labelled_S$. There is also an unlabelled set\n$\\Unlabelled \\subset \\X$, which contains all the remaining unlabelled examples. The question now is\nhow to select the next example from $\\Unlabelled$ for labelling. In practical terms, where should\nwe next point the telescope to, in order to obtain a spectrum? To answer this question, we need a\nrule $r(\\bm{x}; h)$ that can assign a score to each object in $\\Unlabelled$, based solely on their\nphotometric features $\\bm{x}$ and the current hypothesis $h$. This score should reflect the amount\nof new information we would gain if we were to label the object. Once we have computed $r(\\bm{x};\nh)$ for all candidates, we can then pick the example with the highest score and obtain its\nspectrum. The object's feature vector and its label are then added to the training set and the\nclassifier is retrained to obtain a new $h$.\n\nFinding an algorithm to compute $r(\\bm{x}; h)$ exactly is still an open problem. For now, the best\nthat we can do is to come up with heuristics that can approximate $r(\\bm{x}; h)$. Another problem\nis that in practice, the unlabelled pool can be arbitrarily large. For example, there are 800\nmillion unlabelled objects in the SDSS. Thus if we only have a limited computing power, in each\nround, we might only be able to assign scores to a subset $\\Ecal \\subseteq \\Unlabelled$ of size\n$E$. A formal description of the active learning routine is given in Algorithm \\ref{alg:active}. As\nwe shall see in Section \\ref{sec:heuristics}, for some active learning heuristics, we need to\nsubstitute $\\argmax$ with $\\argmin$ in line 4 of Algorithm \\ref{alg:active}.\n\n\\algblock[Name]{Start}{End}\n\n\\algblockdefx[Forall]{Foreach}{Endforeach}%\n\t\t\t[1]{\\textbf{for each} #1 \\textbf{do}}%\n\t\t\t{\\textbf{end for}}\n\n\\begin{algorithm}[h]\n\t\\caption{The general pool-based active learning algorithm}\n\t\\label{alg:active}\n\t\\begin{algorithmic}[1]\n\t\t\\Procedure {ActiveLearner}{$\\Unlabelled$, $\\Labelled_T$, $h$, $r$, $n$, $E$}\n\t\t\t\\While {$|\\Labelled_T| < n$}\n\t\t\t\t\\State $\\Ecal$ $\\leftarrow$ random sample of size $E$ from $\\Unlabelled$\n\t\t\t\t\\State $\\bm{x}_* \\leftarrow \\argmax_{\\bm{x} \\in \\Ecal} r(\\bm{x}; h)$\n\t\t\t\t\\State $y_* \\leftarrow$ ask the expert to label $\\bm{x}_*$\n\t\t\t\t\\State $\\Labelled_T \\leftarrow \\Labelled_T  \\cup (\\bm{x}_*, y_*)$\n\t\t\t\t\\State $\\Unlabelled \\leftarrow \\Unlabelled \\setminus \\bm{x}_*$\n\t\t\t\t\\State $h(\\bm{x}) \\leftarrow$ retrain the classifier\n\t\t\t\\EndWhile\n\t\t\t\\EndProcedure\n\t\\end{algorithmic}\n\\end{algorithm}\n\n\n% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %\n\\section{Active Learning Heuristics} \\index{heuristic}\n\\label{sec:heuristics}\n\nMany methods have been proposed to rank the informativeness of unlabelled objects. The four\nprominent families of heuristics are uncertainty sampling, version space reduction, loss function\nminimisation, and classifier certainty. All of these heuristics require the class probabilities\nestimated by the current hypothesis. We now discuss each of them in turn, starting with the least\ncomputationally expensive one.\n\n\\subsection{Uncertainty Sampling} \\index{uncertainty sampling}\n\\label{sub:uncertainty}\n\n\\citeN{lewis94} introduce the idea of uncertainty sampling, where we select the example whose class\nmembership the classifier is least certain about. These tend to be points that are near the\ndecision boundary of the classifier. One way to quantify the uncertainty is to calculate the\nentropy \\cite{shannon48}, which measures the amount of information needed to encode a distribution.\nIntuitively, the closer class probabilities of an object are to random guessing, the higher its\nentropy will be. This gives us the heuristic of picking the candidate with the highest entropy:\n\\index{entropy}\n\t\\begin{IEEEeqnarray*}{lCl}\n        \\bm{x}_*\n        &=&  \\argmax_{x \\in \\Ecal} r_S(\\bm{x}; h) \\\\\n        &=&  \\argmax_{x \\in \\Ecal} \\left\\{-\\sum_{y \\in \\Y} p(y | \\bm{x}; h)\n        \\log \\big[ p(y | \\bm{x}; h) \\big] \\right\\}\n    \\end{IEEEeqnarray*}\nIn fact, if we care about how close the class probabilities are to random guessing, there is an\neven simpler measure. \\shortciteN{scheffer01} define the margin as the difference between the two\nhighest class probabilities. Since the sum of all probabilities must be 1, the smaller the margin\nis, the more uncertain we are about the object's class membership. Thus another heuristic is to pick\nthe candidate with the smallest margin: \\index{margin}\n\t\\begin{IEEEeqnarray*}{lCl}\n        \\bm{x}_*\n        &=& \\argmin_{x \\in \\Ecal} r_M(\\bm{x}; h)  \\\\\n\t\t&=& \\argmin_{x \\in \\Ecal} \\left\\{ \\max_{y \\in \\Y} p(y | \\bm{x}; h) -\n            \\max_{z \\in \\Y \\setminus \\{y\\}} p(z | \\bm{x}; h)  \\right\\}\n\t\\end{IEEEeqnarray*}\n\n\n%--------------------------------------------------------------------------------------------------\n\\subsection{Version Space Reduction} \\index{version space reduction}\n\\label{sub:qbb}\n\nLet us define the version space as the set of all possible hypotheses that are consistent with the\ncurrent training set. Instead of focussing on the uncertainty of individual predictions, we could\ninstead try to constrain the size of the version space, thus allowing the search for the optimal\nhypothesis to be more precise. To quantify the size the version space, we can train a committee of\nclassifiers, $\\B = \\{h_1, h_2, ..., h_B\\}$, and measure the disagreement among the members about an\nobject's class membership. Each committee member needs to have a hypothesis that is as different\nfrom the others as possible but that is still in the version space \\cite{melville04}. In order to\nhave this diversity, we give each member only a subset of the training examples. Since there might\nnot be enough training data (for example, in our experiments, we have 11 members but only a maximum\nof 300 labelled points), we need to use bootstrapping and select samples with replacement. Hence\nthis method is often called Query by Bagging (QBB). \\index{query by bagging}\n\nOne way to measure the level of disagreement is to calculate the margin using the class\nprobabilities estimated by the committee \\cite{melville04}. This looks similar to one of the\nuncertainty sampling heuristics, except now we first average out the probabilities of the members\nbefore minimising the margin: \\index{margin}\n    \\begin{IEEEeqnarray*}{lCl}\n        \\bm{x}_*\n        &=& \\argmin_{x \\in \\Ecal} r_{QM}(\\bm{x}; \\B)  \\\\\n        &=& \\argmin_{x \\in \\Ecal} \\left\\{ \\max_{y \\in \\Y} p(y | \\bm{x}; \\B) -\n        \\max_{z \\in \\Y \\setminus \\{y\\}} p(z | \\bm{x}; \\B)  \\right\\}\n    \\end{IEEEeqnarray*}\nwhere\n\t\\begin{IEEEeqnarray*}{lCl}\n\t\tp(y | \\bm{x}; \\B) &=& \\dfrac{1}{B} \\sum_{b=1}^{B} p(y | \\bm{x}, h_b)\n\t\\end{IEEEeqnarray*}\nIn addition to the margin, \\citeN{mccallum98} offer an alternative disagreement measure which\ninvolves picking the candidate with the largest expected Kullback--Leibler (KL) divergence\n\\index{KL divergence} from the average:\n\t\\begin{IEEEeqnarray*}{lCl}\n        \\bm{x}_*\n        &=& \\argmax_{x \\in \\Ecal} r_{QK}(\\bm{x}; \\B)  \\\\\n\t\t&=& \\argmax_{x \\in \\Ecal} \\left\\{ \\dfrac{1}{B} \\sum_{b=1}^B D_{\\mathrm{KL}}(p_b\\|p_\\B) \\right\\}\n\t\\end{IEEEeqnarray*}\nwhere \n\t\\begin{IEEEeqnarray*}{lCl}\n\t\tD_{\\mathrm{KL}}(p_b\\|p_\\B) = \\sum_{y \\in \\Y} p(y | \\bm{x}; h_b) \\,\n\t\t                             \\ln\\frac{p(y | \\bm{x}; h_b)}{p(y | \\bm{x}; \\B)}\n\t\\end{IEEEeqnarray*}\nThe KL divergence measures the amount of information lost when $p_\\B$ is used to approximate $p_b$.\nIntuitively, the larger the KL divergence is, the more disagreement there is between $p_\\B$ and\n$p_b$. In the active learning context, $p_\\B$ is the average prediction probability distribution of\nthe committee, while $p_b$ is the prediction of a particular committee member $h_b$.\n\n\n%--------------------------------------------------------------------------------------------------\n\\subsection{Loss Function Minimisation} \\index{loss function}\n\\label{sub:variance}\n\nThe third approach involves minimising a loss function directly, which in turn will minimise the\nfuture generalisation error. A commonly used loss function is the squared loss that has the\nfollowing decomposition:\n\t\\begin{IEEEeqnarray*}{lCl}\n\t\t\\E{\\text{Squared Loss}} &=& \\text{Bias}^2 + \\text{Variance} + \\text{Noise}\n\t\\end{IEEEeqnarray*}\nSince the noise is intrinsic to the data and represents the expected loss under the optimal\nhypothesis, there is nothing we can do about it. The squared bias reflects the error due to the model\nclass itself. For example, there will be bias if we use a linear hypothesis to learn a non-linear\nfunction. Thus the bias is fixed under the same classifier. However, under certain assumptions\nlike the consistency of parameter estimates, the variance will vanish as the training set size\napproaches infinity. This gives us the heuristic of picking the candidate that would cause the\ngreatest drop in the variance if we knew its label. Unfortunately, this is a chicken-and-egg problem\nsince we need to know the labelling information before we can calculate the drop in the variance,\nwhich defeats the purpose of the approach. The next best thing we can do is to pick the candidate\nthat will result in the lowest expected variance: \\index{variance minimisation}\n    \\begin{IEEEeqnarray*}{lCl}\n        \\bm{x}_*\n        &=& \\argmin_{x \\in \\Ecal} r_V(\\bm{x}; h)  \\\\\n        &=& \\argmin_{x \\in \\Ecal}  \\E{V(\\Labelled_T \\cup (\\bm{x}, y); h)} \\\\\n        &=& \\argmin_{x \\in \\Ecal} \\left\\{ \\sum_{y \\in \\Y} p(y | \\bm{x}; h)\n            V(\\Labelled_T \\cup (\\bm{x}, y); h)  \\right\\}\n    \\end{IEEEeqnarray*}\nwhere the expectation is over the class probability distribution under the current hypothesis and\n$V(\\Labelled_T \\cup (\\bm{x}, y); h)$ is the variance of the model after $(\\bm{x}, y)$ has been\nadded to the label set $\\Labelled_T$. Note that this is quite an expensive computation, since for\nus to assign a score to each candidate, we first need to give it each of the possible labels, add\nit to the training set to get an updated hypothesis, and calculate the new variance.\n\nIn addition, estimating $V(\\Labelled_T; h)$ requires a bit of work. In multinomial logistic\nregression, we can take the first two terms of the Taylor series expansion of the probability\n\t\\begin{IEEEeqnarray*}{lCl}\n\t\tp(y | \\bm{x}, \\bm{\\hat{\\theta}}, h)\n\t\t&\\approx& p(y | \\bm{x}; \\bm{\\theta}, h) + \\nabla p(y | \\bm{x}; \\bm{\\theta}, h)^T(\\bm{\\hat{\\theta}} - \\bm{\\theta})\n\t\\end{IEEEeqnarray*}\nwhere $\\bm{\\theta}$ and $\\bm{\\hat{\\theta}}$ are the expected and the current estimates of the model\nparameters, respectively, and $\\nabla p(y | \\bm{x}, \\bm{\\theta}, h)$ is called the gradient vector. Let\n$\\mathcal{I}$ be the Fisher information matrix \\index{Fisher information matrix} and\n\t\\begin{IEEEeqnarray*}{lCl}\n\t\tO &=& \\sum_{\\bm{x} \\in \\Unlabelled}\n\t\t      \\sum_{y \\in \\Y} \\nabla p(y | \\bm{x}; \\bm{\\theta}, h) ~ \\nabla p(y | \\bm{x}; \\bm{\\theta}, h)^T\n\t\\end{IEEEeqnarray*}\n\\citeN{schein07} show that\n\t\\begin{IEEEeqnarray*}{lCl}\n\t\tV(\\Labelled_T; h) &=& \\tr(O\\mathcal{I}^{-1})\n\t\\end{IEEEeqnarray*}\nwhere the trace \\index{trace} function $\\tr(X)$ is the sum of the elements along the main diagonal\nof the square matrix $X$. Note that the above expression is specific to multinomial logistic\nregression. If we use the one-vs-rest strategy with binary logistic regression or another entirely\ndifferent classifier like SVMs in our experiments, the same approximation might not hold and we\nshould not expect to get good results. We leave the variance estimation for other learning\nalgorithms to future work.\n\n\n%--------------------------------------------------------------------------------------------------\n\\subsection{Classifier Certainty} \\index{classifier certainty}\n\\label{sub:cc}\n\nFinally, instead of minimising the variance of $\\Unlabelled$, \\citeN{mackay91} proposes\nminimising the entropy \\index{entropy} of the classifier's predictions on $\\Unlabelled$:\n    \\begin{IEEEeqnarray*}{lCl}\n\t\tH(\\Labelled_T; h) &=& - \\sum_{\\bm{x} \\in \\Unlabelled} \\sum_{y \\in \\Y}\n\t\t\t\t\t\t\t p(y | \\bm{x}; h) \\log \\big[ p(y | \\bm{x}; h)  \\big]\n\t\\end{IEEEeqnarray*}\nAlthough this sounds similar to one of the uncertainty sampling heuristics, here instead of picking\nthe most uncertain candidate, we pick the candidate that is expected to increase the classifier's\nprediction certainty by the the greatest amount:\n\t\\begin{IEEEeqnarray*}{lCl}\n        \\bm{x}_*\n        &=& \\argmin_{x \\in \\Ecal} r_{H}(\\bm{x}; h) \\\\\n        &=& \\argmin_{x \\in \\Ecal}  \\E{H(\\Labelled_T \\cup (\\bm{x}, y); h)} \\\\\n\t\t&=& \\argmin_{x \\in \\Ecal} \\left\\{ \\sum_{y\\in \\Y} p(y|\\bm{x}; h) \n             H(\\Labelled_T \\cup (\\bm{x}, y); h) \\right\\}  \n\t\\end{IEEEeqnarray*}\nLike the variance minimisation technique, we need to calculate the expectation over the possible classes.\nThus to get the score of just one candidate, we need to retrain the classifier $k$ times, where\n$k$ is the number of labels. In practice, both the variance and the classifier certainty\nheuristics are too computationally expensive to run.\n\n\\subsection{Summary of Heuristics}\n\n\\begin{table}[h]\n\t\\caption {Summary of active learning heuristics used in our experiments} \\label{tab:heuristics}\n\t\\centering\n\t\\begin{tabular}{lll}\n\t\t\\toprule\n\t\t{Name}  & Notation &  Objective  \\\\\n\t\t\\midrule\n\t\tEntropy & $r_S(\\bm{x}; h)$\n\t\t\t& $\\argmax_{x \\in \\Ecal} \\left\\{-\\sum_{y \\in \\Y} p(y | \\bm{x}; h)\n            \\log \\big[ p(y | \\bm{x}; h) \\big] \\right\\}$\n\t\t\t\\\\[2ex]\n\t\tMargin & $r_M(\\bm{x}; h)$\n\t\t\t& $\\argmin_{x \\in \\Ecal} \\left\\{ \\max_{y \\in \\Y} p(y | \\bm{x}; h) -\n            \\max_{z \\in \\Y \\setminus \\{y\\}} p(z | \\bm{x}; h)  \\right\\}$\n\t\t\t\\\\[2ex]\n\t\tQBB Margin & $r_{QM}(\\bm{x}; h)$\n\t\t\t& $\\argmin_{x \\in \\Ecal} \\left\\{ \\max_{y \\in \\Y} p(y | \\bm{x}; \\B) -\n            \\max_{z \\in \\Y \\setminus \\{y\\}} p(z | \\bm{x}; \\B)  \\right\\}$\n\t\t\t\\\\[2ex]\n\t\tQBB KL & $r_{QK}(\\bm{x}; h)$\n\t\t\t& $\\argmax_{x \\in \\Ecal} \\left\\{ \\dfrac{1}{B}\n               \\sum_{b=1}^B D_{\\mathrm{KL}}(p_b\\|p_\\B) \\right\\}$\n\t\t\t\\\\[2ex]\n\t\tPool Variance & $r_V(\\bm{x}; h)$\n\t\t\t& $\\argmin_{x \\in \\Ecal} \\left\\{ \\sum_{y \\in \\Y} p(y | \\bm{x}; h)\n            V(\\Labelled_T \\cup (\\bm{x}, y); h)  \\right\\}$\n\t\t\t\\\\[2ex]\n\t\tPool Entropy & $r_{H}(\\bm{x}; h)$\n\t\t\t& $\\argmin_{x \\in \\Ecal} \\left\\{ \\sum_{y\\in \\Y} p(y|\\bm{x}; h) \n               H(\\Labelled_T \\cup (\\bm{x}, y); h) \\right\\}  $\n\t\t\t\\\\\n\t\t\\bottomrule\n\t\\end{tabular}\n\\end{table}\n\n\n% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %\n\\section{Multi-arm Bandit} \\index{bandit}\n\\label{sec:bandit}\n\nOut of the six heuristics discussed, how do we know which one is the optimal, anyway? There have\nbeen some attempts in the literature to do a theoretical analysis of them. However proofs are\nscarce, and when there is one available, they normally only work under simplifying assumptions. For\nexample, \\shortciteN{freund97} show that the query by committee algorithm (a slight variant of our\nQBB heuristics) guarantees an exponential decrease in the prediction error with the training size,\nbut only under certain restrictions such as there is no noise. Thus whether any of these heuristics\nis guaranteed to beat random sampling is still an open question. We shall not worry too much about\nthe theoretical analysis in this thesis. Instead we shall focus on an empirical analysis in the\nastronomical domain.\n\nTo help us automatically choose the optimal heuristic, we now turn our attention to the multi-armed\nbandit problem in probability theory. The colourful name originates from the situation where a\ngambler stands in front of a slot machine with $s$ levers. When pulled, each lever gives out a random\nreward according to some unknown distribution. The goal of the game is to come up with a strategy\nthat can maximise the gambler's lifetime rewards while minimising the number of pulls.\n\nOur key novel contribution is the application of this theory to the problem of heuristic selection.\nSuppose we have a set of $s$ heuristics $ \\R = \\{r_1, ..., r_s \\}$. Each heuristic has a different\nability to identify the candidate whose labelling information is most valuable. An appropriate\nreward is then the incremental increase in the accuracy rate after the candidate is added to the\ntraining set. We assume that the heuristic rewards are independent of each other. This is\nreasonable since the theories with which we use to derive the heuristics are mostly unrelated.\n\nLet $\\rho_i$ be the reward \\index{reward} of heuristic $r_i \\in \\R$. Observe that even with the\noptimal heuristic, there are still two sources of error. First, there could be error during the\nlabelling process that causes the accuracy rate to decrease. In addition, even without label noise,\nthe classifier trained on finite data might not be the right one, so we still cannot score\nperfectly due to having a poor $h$. Conversely, a bad heuristic might be able to pick an\ninformative candidate due to pure luck. Thus there is always a certain level of randomness in the\nreward received. These errors are probably normally distributed, so\n\t\\begin{IEEEeqnarray*}{lCl}\n\t\t(\\rho_i \\mid \\nu_i) \\sim \\Normal(\\nu_i, \\tau_i^2)\n\t\\end{IEEEeqnarray*}\nand the probably density function (PDF) of the reward is\n    \\begin{IEEEeqnarray}{lCl}\n        f(\\rho_i \\mid \\nu_i)\n        &=& \\frac{1}{\\tau_i \\sqrt{2\\pi}} \\exp\\left[ -\\frac{(\\rho_i - \\nu_i)^2}{2 \\tau_i^2} \\right]\n         \\label{eqn:rlike}\n    \\end{IEEEeqnarray}\nIf we knew both the mean $\\nu_i$ and the variance $\\tau_i^2$ for all heuristics, the problem would\nbecome trivially easy since we just need to always use the heuristic that has the highest mean\nreward. In practice, we do not know $\\nu_i$, so let us assume that it follows a normal\ndistribution\n\t\\begin{IEEEeqnarray*}{lCl}\n        \\nu_i \\sim \\Normal(\\mu_i, \\sigma_i^2)\n    \\end{IEEEeqnarray*}\nThus the PDF of $\\nu_i$ is\n    \\begin{IEEEeqnarray}{lCl}\n        f(\\nu_i)\n        &=& \\frac{1}{\\sigma_i \\sqrt{2\\pi}} \\exp\\left[ -\\frac{(\\nu_i - \\mu_i)^2}{2 \\sigma_i^2} \\right]\n         \\label{eqn:rprior}\n    \\end{IEEEeqnarray}\nTo make the problem tractable, assume that $\\tau_i^2$ is a known constant. The goal now is to find a\ngood algorithm that can estimate $\\mu_i$ and $\\sigma_i^2$.\n\nOne problem in multi-arm bandits is the trade-off between exploration and exploitation.\n\\index{exploration vs exploitation} Suppose we have managed to estimate $\\mu_i$ and $\\sigma_i^2$\nfor all $i$, then by always selecting the heuristic with the highest possible mean, or the greedy\nheuristic, we would be exploiting our current knowledge. If however we select one of the other\nnon-greedy heuristics, we would then be exploring with the intention of improving our estimates of\n$\\mu_i$ and $\\sigma_i^2$. There are many instances in which we find our previously held beliefs to\nbe completely wrong. Thus by always exploiting, we could miss out on the optimal heuristic. On the\nother hand, if we explore too much, it might take a long time to reach the desired accuracy and the\nstrategy ends up being no different from random sampling.\n\n\\section{Thompson Sampling} \\index{Thompson sampling}\n\\label{sec:thompson}\n\nThere are two main methods in the literature that address this exploration vs exploitation problem.\nThe algorithm with a strong theoretical guarantee is Upper Confidence Bound \\cite{auer02}. We\nshall, however, focus on a simpler and much older algorithm called Thompson sampling. First\nintroduced by \\citeN{thompson33}, this algorithm solves the trade-off from a Bayesian perspective.\nIt has been shown to achieve results that are comparable and sometimes even better than Upper\nConfidence Bound \\cite{chapelle11}.\n\nUnder the heuristic selection setting, Thompson sampling works as follows. We start with a prior\nknowledge of $\\mu_i$ and $\\sigma_i^2$ for all $i$. So long as we do not choose anything stupid,\ne.g. a zero variance, our choice of prior should not matter too much in the long run. Since\ninitially we do not have any information about the performance of each heuristic, the appropriate\nprior value for $\\mu_i$ is $0$, i.e. there is no evidence (yet) that any of the heuristics offers an\nimprovement to the accuracy.\n\nIn each round, we draw a random sample $\\nu_i'$ from the distribution $\\Normal(\\mu_i, \\sigma_i^2)$ for\neach $i$ and select heuristic $r_*$ that has the highest sampled value of the mean reward:\n    \\begin{IEEEeqnarray*}{lCl}\n        r_* = \\argmax_{i} \\nu_i'\n    \\end{IEEEeqnarray*}\nWe then use this heuristic to assign scores to the candidates. The object that is deemed to be the\nmost informative is then added to the training set $\\Labelled_T$ and the classifier is retrained.\nNext we use the updated hypothesis to predict the labels of objects in the test set $\\Labelled_S$.\nLet $\\delta$ be the reward observed, which is the incremental increase in the accuracy rate on\n$\\Labelled_S$. We now have a new piece of information that we can use to update our prior belief\nabout the mean $\\mu_*$ and the variance $\\sigma_*^2$ of $r_*$. In the Bayesian setting, \\index{Bayesian} \n(\\ref{eqn:rprior}) is called the prior and (\\ref{eqn:rlike}) is the likelihood. From Bayes'\ntheorem, the posterior distribution is proportional to the product of the prior and the likelihood:\n    \\begin{IEEEeqnarray*}{lCl}\n        f(\\nu_* \\mid \\rho_* = \\delta)\n        &\\propto& f(\\nu_*) f(\\delta \\mid \\nu_*) \\\\\n        &\\propto& \\exp \\left[ -\\frac{1}{2 \\sigma_*^2} (\\nu_* - \\mu_*)^2 \\right]\n                  \\exp \\left[ -\\frac{1}{2 \\tau_*^2} (\\delta - \\nu_*)^2 \\right] \\\\\n        &=& \\exp \\left[ -\\frac{1}{2 \\sigma_*^2} (\\nu_* - \\mu_*)^2 \n                        -\\frac{1}{2 \\tau_*^2} (\\delta - \\nu_*)^2  \\right] \\\\\n        &=& \\exp \\left[ -\\frac{\\nu_*^2}{2} \\left( \\frac{1}{\\sigma_*^2} + \\frac{1}{\\tau_*^2} \\right) \n                        +\\nu_* \\left( \\frac{\\mu_*}{\\sigma_*^2} + \\frac{\\delta}{\\tau_*^2} \\right) \n                        - \\left( \\frac{\\mu_*^2}{2\\sigma_*^2} + \\frac{\\delta^2}{2 \\tau_*^2} \\right) \n                        \\right] \\\\\n        &\\propto& \\exp \\left[ -\\frac{\\nu_*^2}{2} \\left( \\frac{1}{\\sigma_*^2} + \\frac{1}{\\tau_*^2} \\right) \n                        +\\nu_* \\left( \\frac{\\mu_*}{\\sigma_*^2} + \\frac{\\delta}{\\tau_*^2} \\right)\n                        \\right] \\\\\n        &=& \\exp \\left[ -\\frac{\\nu_*^2}{2} \\left( \\frac{\\sigma_*^2 + \\tau_*^2}{\\sigma_*^2 \\tau_*^2}\n                        \\right) \n                        +\\nu_* \\left( \\frac{\\mu_*\\tau_*^2 + \\delta\\sigma_*^2}{\\sigma_*^2 \\tau_*^2}\n                         \\right) \\right] \\\\\n        &=& \\exp \\left[ -\\frac{1}{2 {\\sigma'_*}^2} (\\nu^2_* - 2\\nu_*\\mu_*' ) \\right] \\\\ \n        &\\propto& \\exp \\left[ -\\frac{1}{2 {\\sigma'_*}^2} (\\nu^2_* - 2\\nu_*\\mu_*'  + {\\mu'_*}^2)\n                   \\right] \\\\      \n        &=& \\exp \\left[ -\\frac{1}{2 {\\sigma'_*}^2} (\\nu_* - \\mu'_*)^2 \\right]\n    \\end{IEEEeqnarray*}\nwhere we have defined\n    \\begin{IEEEeqnarray*}{lClllCl}\n        \\mu_*' &=& \\frac{\\mu_* \\tau^2_* + \\delta \\sigma^2_*}{\\sigma^2_* + \\tau^2_*} &\\qquad\\qquad\n        {\\sigma'_*}^2 &=& \\frac{\\sigma^2_* \\tau^2_*}{\\sigma^2_* + \\tau^2_*}\n    \\end{IEEEeqnarray*}\nThus the posterior distribution of the mean reward of $r_*$ remains normal:\n    \\begin{IEEEeqnarray*}{lCl}\n        (\\nu_* \\mid \\rho_* = \\delta) \\sim \\Normal (\\mu_*', {\\sigma'_*}^2)\n    \\end{IEEEeqnarray*}\nFor compactness, let:\n    \\begin{IEEEeqnarray*}{lClllCl}\n        \\bm{\\nu} &=& (\\nu_1, \\nu_2, ..., \\nu_s) &\\qquad\\qquad\n        \\bm{\\mu} &=& (\\mu_1, \\mu_2, ..., \\mu_s) \\\\\n        \\bm{\\sigma}^2 &=& (\\sigma^2_1, \\sigma^2_2, ..., \\sigma^2_s) &\\qquad\\qquad\n        \\bm{\\tau^2} &=& (\\tau^2_1, \\tau^2_2, ..., \\tau^2_s)\n    \\end{IEEEeqnarray*}\nAlgorithm \\ref{alg:thompson} on page \\pageref{alg:thompson} shows the formal specification of the\nThompson sampling procedure with normally distributed rewards. If we then combine this with the\ngeneral pool-based active learning algorithm, we end up with a multi-arm bandit version of active\nlearning where each arm is a heuristic (Algorithm \\ref{alg:bandit}). Note again that in line 8 of\nAlgorithm \\ref{alg:bandit}, some heuristics have $\\argmin$ in place of $\\argmax$.\n\n\\begin{algorithm}[p]\n\t\\caption{Thompson sapmling with normally distributed rewards} \\index{Thompson sampling}\n\t\\label{alg:thompson}\n\t\\begin{algorithmic}[1]\n\t\t\\Procedure {ThompsonSampling}{$\\R$, $\\bm{\\mu}$, $\\bm{\\sigma}^2$, $\\bm{\\tau}^2$, n}\n    \t\t\\Foreach {$t \\in \\{1, 2, ..., n\\}$}\n        \t\t\\Foreach {$i \\in \\{1, 2, ..., |\\R|\\}$}\n            \t\t\\State $\\nu_i' \\leftarrow$ draw a sample from $\\Normal(\\mu_i, \\sigma^2_i)$\n        \t\t\\Endforeach\n        \t\t\\State $r_* \\leftarrow \\argmax_{i} \\nu_i'$\n        \t\t\\State Observe reward $\\delta$\n        \t\t\\State $\\mu_* \\leftarrow \\dfrac{\\mu_* \\tau^2_* + \\delta \\sigma^2_*}{\\sigma^2_* + \\tau^2_*}$\n        \t\t\\State $\\sigma_*^2 \\leftarrow \\dfrac{\\sigma^2_* \\tau^2_*}{\\sigma^2_* + \\tau^2_*}$\n    \t\t\\Endforeach\n\t\t\\EndProcedure\n\t\\end{algorithmic}\n\\end{algorithm}\n\n\n\\begin{algorithm}[p]\n\t\\caption{The multi-arm bandit active learning algorithm} \\index{bandit}\n\t\\label{alg:bandit}\n\t\\begin{algorithmic}[1]\n\t\t\\Procedure {ActiveBandit}{$\\Unlabelled$, $\\Labelled_T$, $h$, $n$, $E$,\n\t\t\t                      $\\R$, $\\bm{\\mu}$, $\\bm{\\sigma}^2$, $\\bm{\\tau}^2$}\n    \t\t\\While {$|\\Labelled_T| < n$}\n        \t\t\\Foreach  {$i \\in \\{1, 2, ..., |\\R|\\}$}\n        \t\t\t\\State $\\nu_i' \\leftarrow$ draw a sample from $\\Normal(\\mu_i, \\sigma^2_i)$\n        \t\t\\Endforeach\n        \t\t\\State $r_* \\leftarrow \\argmax_{i} \\nu_i'$\n        \t\t\\State $\\Ecal$ $\\leftarrow$ random sample of size $E$ from $\\Unlabelled$\n        \t\t\\State $\\bm{x}_* \\leftarrow \\argmax_{\\bm{x} \\in \\Ecal} r_*(\\bm{x})$\n        \t\t\\State $y_* \\leftarrow$ ask the expert to label $\\bm{x}_*$\n        \t\t\\State $\\Labelled_T \\leftarrow \\Labelled_T  \\cup (\\bm{x}_*, y_*)$\n        \t\t\\State $\\Unlabelled \\leftarrow \\Unlabelled \\setminus \\bm{x}_*$\n        \t\t\\State $h(\\bm{x}) \\leftarrow$ retrain the classifier\n        \t\t\\State $\\delta$ $\\leftarrow$ incremental increase in the accuracy\n        \t\t\\State $\\mu_* \\leftarrow \\dfrac{\\mu_* \\tau^2_* + \\delta \\sigma^2_*}{\\sigma^2_* + \\tau^2_*}$\n                \\State $\\sigma_*^2 \\leftarrow \\dfrac{\\sigma^2_* \\tau^2_*}{\\sigma^2_* + \\tau^2_*}$\n    \t\t\\EndWhile\n\t\t\\EndProcedure\n\t\\end{algorithmic}\n\\end{algorithm}\n\n\\pagebreak\nHow does Thompson sampling balance between exploration and exploitation? If we only wanted to\nexploit our current knowledge, then we would naturally select the heuristic that maximises the\nimmediate reward:\n    \\begin{IEEEeqnarray*}{lCl}\n        r_*\n        &=& \\argmax_{i} \\E{\\rho_i} \\\\\n        &=& \\argmax_{i} \\mathbb{E} \\{ \\E{\\rho_i \\given \\bm{\\nu}} \\} \\\\\n        &=& \\argmax_{i} \\mathbb{E} \\{ \\E{\\rho_i \\given \\nu_i} \\} \\\\\n        &=& \\argmax_{i} \\int_{-\\infty}^{+\\infty} \\E{\\rho_i \\given \\nu_i} f(\\nu_i) \\, d\\nu_i \\\\\n        &=& \\argmax_{i} \\int_{-\\infty}^{+\\infty} \\nu_i f(\\nu_i) \\, d\\nu_i \\\\\n        &=& \\argmax_{i} \\E{\\nu_i} \\\\\n        &=& \\argmax_{i} \\mu_i\n    \\end{IEEEeqnarray*}\nwhere we have used the law of total expectation and the fact that both $(\\rho_i \\mid \\nu_i)$ and\n$\\nu_i$ are normally distributed. Unsurprisingly, the heuristic that maximises the immediate reward\nis simply the one with the highest $\\mu_i$. However, there is a chance that we could be wrong about\nour estimate of $\\bm{\\mu}$. Thus a better option is to only select a heuristic at the same\nfrequency as the probability that it is optimal. For a given heuristic $r_i$, this probability is\n    \\begin{IEEEeqnarray*}{lCl}\n        \\Prob{ \\E{\\rho_i} = \\max_j \\E{\\rho_j} }\n        &=& \\E{ \\Prob{ \\E{\\rho_i} = \\max_j \\E{\\rho_j} | \\bm{\\nu}} } \\\\\n        &=& \\int_{\\bm{\\nu}} \\Prob{ \\E{\\rho_i} = \\max_j \\E{\\rho_j}  \\given \\bm{\\nu} }\n             f(\\bm{\\nu}) \\, d\\bm{\\nu} \\\\\n        &=& \\int_{\\bm{\\nu}} \\Prob{ \\E{\\rho_i \\given \\bm{\\nu}} = \\max_j \\E{\\rho_j \\given \\bm{\\nu}} }\n            f(\\bm{\\nu}) \\, d\\bm{\\nu} \\\\\n        &=& \\int_{\\bm{\\nu}} \\Prob{ \\nu_i = \\max_j \\nu_j }\n            f(\\bm{\\nu}) \\, d\\bm{\\nu} \\\\\n        &=& \\int_{\\bm{\\nu}} \\mathbb{I}( \\nu_i = \\max_j \\nu_j )\n              f(\\bm{\\nu}) \\, d\\bm{\\nu}\n    \\end{IEEEeqnarray*}\nwhere $\\mathbb{I}$ is the indicator function. In fact we do not have to evaluate this integral\ndirectly. If in each round, we draw a random sample of $\\bm{\\nu}$ and act optimally according to\nthe sample values, then over the long run, the frequency that we select each heuristic will\napproach its probability of being optimal. This is exactly what Thompson sampling does.\n\nFinally, as we shall see in Chapter \\ref{cha:expt2}, the reward function \\index{reward!drifting}\ndynamically evolves as the training size increases. Intuitively, the accuracy rate can never go\nbeyond 100\\%, so we would expect the incremental change in the accuracy to become smaller over\ntime. Attempts to address this problem have been made in the literature. For example\n\\citeN{gupta11} introduce the Dynamic Thompson Sampling method that can adapt to the evolving\nparameters faster than Algorithm \\ref{alg:thompson} and \\ref{alg:bandit}. However, we shall leave\nthe investigation of this method to future work.\n\n\n% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % \n\\section{Posterior Balanced Accuracy} \\index{performance measure} \\index{MPBA} \\index{accuracy}\n\\label{sec:measures}\n\nCertain astronomical objects are either rarer or more difficult to detect than others. In the SDSS\nlabelled set, there are 4.5 times as many galaxies as quasars. The problem of class imbalance is\neven more severe in the VST ATLAS set, with 43 times more stars than white dwarfs. An easy fix is\nto undersample the dominant class when creating training and test sets. This, of course, means that\nthe size of these sets are limited by the size of the minority class.\n\nWhen we do not want to alter the underlying class distributions or when larger training and test\nsets are desired, we need a performance measure that can correct for the class imbalance.\n\\shortciteN{brodersen10} show that the posterior balanced accuracy distribution can overcome the\nbias in the binary case. We now extend this idea to the multi-class setting.\n\nSuppose we have $k$ classes. For each class $i$ between $1$ and $k$, there are $N_i$ objects in the\nuniverse. Given a hypothesis, we can predict the label of every object and compare our prediction\nto the true label. Let $G_i$ be the number of objects in class $i$ that are correctly predicted.\nThen we define the recall $A_i$ of class $i$ as \\index{recall}\n\t\\begin{IEEEeqnarray*}{lCl}\n\t\tA_i &=& \\frac{G_i}{N_i}\n\t\\end{IEEEeqnarray*}\nThe problem is that it is not feasible to get the actual values of $G_i$ and $N_i$ since that would\nrequire us to obtain the true label of every object. Thus we need a method to estimate these\nquantities when we only have a sample. Initially we have no information about $G_i$ and\n$N_i$, so we can assume that each $A_i$ follows a uniform prior from 0 to 1. This is the same as a\nBeta distribution with shape parameters $\\alpha = \\beta = 1$:\n\t\\begin{IEEEeqnarray*}{lCl}\n\t\tA_i &\\sim& \\Beta(1,1) \n\t\\end{IEEEeqnarray*}\nThe PDF of $A_i$ is then\n    \\begin{IEEEeqnarray}{lCl}\n        f_{A_i}(a) &=& \\frac{\\Gamma(\\alpha+\\beta)}{\\Gamma(\\alpha)\\Gamma(\\beta)}\\, \n        a^{\\alpha-1}(1-a)^{\\beta-1} \\label{eqn:prior} \\\\\n        &\\propto&   a^{1-1}(1-a)^{1-1}  \\notag\n    \\end{IEEEeqnarray}\nwhere $\\Gamma(\\alpha)$ is the gamma function.\n\nAfter we have trained the classifier, suppose we have a test set containing $n_i$ objects in class\n$i$. Running the classifier on this test set is the same as conducting $k$ binomial experiments,\nwhere, in the $i$th experiment, the sample size is $n_i$ and the probability of success is simply\n$A_i$. Let $g_i$ be the number of correctly labelled objects belonging to class $i$ in the test\nset. Then, conditional on the accuracy rate, $g_i$ follows a binomial distribution:\n\t\\begin{IEEEeqnarray*}{lCl}\n\t\t(g_i \\mid A_i) &\\sim& \\Bin(n_i, A_i)\n\t\\end{IEEEeqnarray*}\nThe probability mass function of $(g_i \\mid A_i = a)$ is thus\n    \\begin{IEEEeqnarray}{lCl}\n        p_{g_i \\mid A_i}(g_i) &=& \\binom{n_i}{g_i} a^{g_i} (1 - a)^{n_i - g_i} \\label{eqn:likelihood} \\\\\n                              &\\propto& a^{g_i} (1 - a)^{n_i - g_i} \\notag\n    \\end{IEEEeqnarray}\nIn the Bayesian \\index{Bayesian} setting, \\eqref{eqn:prior} is the prior and \\eqref{eqn:likelihood}\nis the likelihood. To get the posterior PDF, we simply multiply the prior with the likelihood:\n\t\\begin{IEEEeqnarray*}{lCl}\n\t\tf_{A_i \\mid \\bm{g}}(a)\n\t\t&\\propto& f_{A_i}(a) \\times f_{g_i \\mid A_i}(g_i) \\\\\n\t\t&\\propto& a^{1-1}(1-a)^{1-1} \\times a^{g_i} (1 - a)^{n_i - g_i} \\\\\n\t\t&=& a^{1 + g_i - 1}(1-a)^{1 + n_i - g_i - 1}\n\t\\end{IEEEeqnarray*}\nThus, with respect to the binomial likelihood function,\nthe Beta distribution is conjugate to itself. The posterior recall rate $A_i$\nalso follows a Beta distribution, now with parameters\n\t\\begin{IEEEeqnarray*}{lCl}\n\t\t(A_i \\mid g_i) &\\sim& \\Beta(1 + g_i, 1 + n_i - g_i)\n\t\\end{IEEEeqnarray*}\nOur goal is to have a balanced accuracy rate, $A$, that puts an equal weight in each class. One way\nto achieve this is to take the average of the individual recalls:\n\t\\begin{IEEEeqnarray*}{lCl}\n\t\tA &=& \\frac{1}{k} \\sum_{i=1}^k A_i \\\\\n\t\t&=& \\frac{1}{k} A_T\n\t\\end{IEEEeqnarray*}\nHere we have defined $A_T$ to be the sum of the individual recalls. We call  $(A \\mid \\bm{g})$ the\nposterior balanced accuracy (PBA), where $\\bm{g} =(g_1,...,g_k)$. Most of the time, we simply want\nto calculate its expected value:\n\t\\begin{IEEEeqnarray*}{lCl}\n\t\t\\E{A \\given \\bm{g}} &=& \\frac{1}{k} \\, \\E{A_T \\given \\bm{g}} \\\\\n\t\t&=& \\frac{1}{k} \\int a \\cdot f_{A_T \\mid \\bm{g}}(a) \\, da\n\t\\end{IEEEeqnarray*}\nLet us call this the mean posterior balanced accuracy (MPBA). Note that there is no closed\nform solution for the PDF $f_{A_T \\mid \\bm{g}}(a)$. However assuming that $A_T$ is a sum of $k$\nindependent Beta random variables, $f_{A_T \\mid \\bm{g}}(a)$ can be approximated by numerically\nconvolving $k$ Beta distributions. The independence assumption is reasonable here, since there\nshould be little to no correlation between the individual class accuracy rates. Knowing that a\nclassifier is really good at recognising stars does not tell us much about how well that classifier\ncan recognise galaxies.\n\nHaving the knowledge of $f_{A \\mid \\bm{g}}(a)$ will allow us to make violin plots,\nconstruct confidence intervals and do hypothesis tests. To get an expression for this,\nlet us first rewrite the cumulative distribution function (CDF) as\n\t\\begin{IEEEeqnarray*}{lCl}\n\t\tF_{A\\mid \\bm{g}}(a) &=& \\Prob{A \\leq a \\mid \\bm{g}} \\\\\n\t\t&=& \\Prob[\\Big]{\\frac{1}{k} A_T \\leq a \\given \\bm{g}} \\\\\n\t\t&=& \\Prob{A_T \\leq ka \\given \\bm{g}} \\\\\n\t\t&=& F_{A_T \\mid \\bm{g}}(ka) \\IEEEyesnumber \\label{eqn:CDF}\n\t\\end{IEEEeqnarray*}\nDifferentiating \\eqref{eqn:CDF} with respect to $a$, we obtain the PDF of $(A \\mid \\bm{g})$:\n\t\\begin{IEEEeqnarray*}{lCl}\n\t\tf_{A \\mid \\bm{g}}(a) &=& \\frac{\\partial}{\\partial a} F_{A \\mid \\bm{g}}(ka) \\\\\n\t\t&=& \\frac{\\partial}{\\partial a} (ka) \\cdot \\frac{\\partial}{\\partial ka} F_{A_T \\mid \\bm{g}}(ka) \\\\\n\t\t&=& k \\cdot f_{A_T \\mid \\bm{g}}(ka)\n\t\\end{IEEEeqnarray*}\nWe shall use the posterior balanced accuracy rate throughout the experiments to report the overall\nperformance of a classifier on a test set.\n\n%%% Local Variables: \n%%% mode: latex\n%%% TeX-master: \"thesis\"\n%%% End: \n", "meta": {"hexsha": "1bad5d1954c115d1ac3a2070b7b14954f2838b0c", "size": 50606, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "projects/alasdair/thesis/3_ml.tex", "max_stars_repo_name": "chengsoonong/mclass-sky", "max_stars_repo_head_hexsha": "98219221c233fa490e78246eda1ead05c6cf7c17", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2016-06-01T12:09:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-16T05:28:01.000Z", "max_issues_repo_path": "projects/alasdair/thesis/3_ml.tex", "max_issues_repo_name": "alasdairtran/mclearn", "max_issues_repo_head_hexsha": "98219221c233fa490e78246eda1ead05c6cf7c17", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 165, "max_issues_repo_issues_event_min_datetime": "2015-01-28T10:37:34.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-23T06:55:13.000Z", "max_forks_repo_path": "projects/alasdair/thesis/3_ml.tex", "max_forks_repo_name": "alasdairtran/mclearn", "max_forks_repo_head_hexsha": "98219221c233fa490e78246eda1ead05c6cf7c17", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2015-01-24T16:27:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-01T08:54:31.000Z", "avg_line_length": 61.2663438257, "max_line_length": 115, "alphanum_fraction": 0.6969529305, "num_tokens": 14712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.31483006197816854}}
{"text": "\n\\section{\\namee by Examples}\n\\label{nested:sec:overview}\n\n\n\nThis section illustrates \\namee with an encoding of a family polymorphism\nsolution to the expression problem, and informally presents its salient\nfeatures.\n\n\n%-------------------------------------------------------------------------------\n\\subsection{The Expression Problem, \\namee Style}\n\nThe \\namee calculus allows us to solve the expression problem in a way that is\nvery similar to \\citeauthor{Ernst_2001}'s \\textsf{gbeta} solution in \\cref{sec:ernst}.\nHowever, the underlying mechanisms of \\namee are quite different from those of\n\\textsf{gbeta}. In particular, \\namee features a structural type system in which we can\nmodel objects with records, and object types with record types. For instance, we\nmodel the interface of \\lstinline{Lang.Exp} with the singleton record type\n\\lstinline${ print : String }$. For the sake of conciseness, we use \\lstinline{type} aliases\nto abbreviate types.\n\\lstinputlisting[linerange=4-4]{./examples/overview.sl}% APPLY:linerange=PRINT_INTERFACE\nSimilarly, we capture the interface of the \\lstinline{Lang} family in a record,\nwith one field for each case's constructor.\n\\lstinputlisting[linerange=8-11]{./examples/overview.sl}% APPLY:linerange=LANG_FAMILY\nHere is the implementation of \\lstinline{Lang}.\n\\lstinputlisting[linerange=20-27]{./examples/overview.sl}% APPLY:linerange=LANG_IMPL\nWe assume several primitive types: fixed width integers \\lstinline{Int},\n\\lstinline{Double} for numeric operations and \\lstinline{String} for text\nmanipulation. A \\namee program consists of a collection of definitions and\ndeclarations, separated by semicolon \\lstinline{;}.\n\n% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\\paragraph{Adding evaluation.}\nWe obtain \\lstinline{IPrint & IEval}, which is the corresponding type for \\lstinline{LangEval.Exp}, by\nintersecting \\lstinline{IPrint} with \\lstinline{IEval} where\n\\lstinputlisting[linerange=32-32]{./examples/overview.sl}% APPLY:linerange=EVAL_INTERFACE\nThe type for \\lstinline{LangEval} is then\n\\lstinputlisting[linerange=37-40]{./examples/overview.sl}% APPLY:linerange=EVAL_PRINT_INTERFACE\nWe obtain an implementation for \\lstinline{LangEval} by merging the existing\n\\lstinline{Lang} implementation \\lstinline{implLang} with the new evaluation\nfunctionality \\lstinline{implEval} using the merge operator \\lstinline{,,}.\n\\lstinputlisting[linerange=48-56]{./examples/overview.sl}% APPLY:linerange=EVAL_PRINT_IMPL\n\n% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\\paragraph{Adding negation.}\nAdding negation to \\lstinline{Lang} works similarly.\n\\lstinputlisting[linerange=60-68]{./examples/overview.sl}% APPLY:linerange=LANG_NEG\n% \\begin{Verbatim}[xleftmargin=10mm,fontsize=\\relscale{.80}]\n% type LangNeg = Lang & { neg : IPrint -> IPrint }\n\n% implLangNeg : LangNeg\n% implLangNeg = implLang ,, implNeg\n\n% implNeg = { neg = \\a.{print = \"-\" ++ a.print } }\n% \\end{Verbatim}\n\n% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\\paragraph{Putting everything together.}\nFinally, we can combine the two extensions and provide the missing\nimplementation of evaluation for the negation case.\n\\lstinputlisting[linerange=73-83]{./examples/overview.sl}% APPLY:linerange=LANG_FINAL\nWe can test \\lstinline{implLangNegEval} by creating an object that represents $-2 + 3$, which is able to print and evaluate at the same time.\n\\lstinputlisting[linerange=101-103]{./examples/overview.sl}% APPLY:linerange=TEST\n\n\n\n%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\\paragraph{Multi-field records.}\nRecall that in \\cref{bg:sec:intersection}, we show how to model multi-field records by\nsingle-field records. Thus \\namee does not have multi-field record types built in.\nThey are merely syntactic sugar for intersections of single-field record types.\nHence, the following is an equivalent definition of \\lstinline{Lang}:\n\\lstinputlisting[linerange=16-16]{./examples/overview.sl}% APPLY:linerange=LANG_FAMILY2\nSimilarly, the multi-field record expression in the definition of\n\\lstinline{implLang} is syntactic sugar for the explicit merge of two\nsingle-field records.\n\\begin{lstlisting}\nimplLang : Lang = { lit = ... } ,, { add = ... };\n\\end{lstlisting}\n\n%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\\paragraph{Subtyping.}\nA distinctive difference compared to \\textsf{gbeta} is that many more \\namee types are related through\nsubtyping. Indeed, \\textsf{gbeta} is unnecessarily conservative~\\citep{ernst_hoh}: none of the families is related\nthrough subtyping, nor is any of the class members of one family related to any\nof the class members in another family. For instance, \\lstinline{LangEval} is\nnot a subtype of \\lstinline{Lang}, nor is \\lstinline{LangNeg.Lit} a subtype\nof \\lstinline{Lang.Lit}.\n\nIn contrast, subtyping in \\namee is much more nuanced and depends entirely on the\nstructure of types. The primary source of subtyping are intersection types:\nany intersection type is a subtype of its components. For instance, \n\\lstinline{IPrint & IEval} is a subtype of both \\lstinline{IPrint} and\n\\lstinline{IEval}. Similarly \\lstinline{LangNeg = Lang & NegPrint} is a subtype\nof \\lstinline{Lang}. Compare this to \\textsf{gbeta} where \\lstinline{LangEval.Expr} is\nnot a subtype of \\lstinline{Lang.Expr}, nor is the family \\lstinline{LangNeg} a\nsubtype of the family \\lstinline{Lang}.\n\nHowever, \\textsf{gbeta} and \\namee agree that \\lstinline{LangEval} is not a subtype of\n\\lstinline{Lang}. The \\namee-side of this may seem contradictory at first, as we\nhave seen that intersection types arise from the use of the merge operator.\nWe have created an implementation for \\lstinline{LangEval} with\n\\lstinline{implLang ,, implEval} where \\lstinline{implLang} has type \\lstinline{Lang}, which\nsuggests that \\lstinline{LangEval} is a subtype of \\lstinline{Lang}.\nYet, there is a flaw in our reasoning:\nstrictly speaking, \\lstinline{implLang ,, implEval} is not of\ntype \\lstinline{LangEval} but instead of type \\lstinline{Lang & EvalExt}, where\n\\lstinline{EvalExt} is the type of \\lstinline{implEval}:\n\\lstinputlisting[linerange=44-44]{./examples/overview.sl}% APPLY:linerange=EVAL_INTERFACE2\n\nNevertheless, the definition of \\lstinline{implLangEval} is valid because\n\\lstinline{Lang & EvalExt} is a subtype of \\lstinline{LangEval}.\nIndeed, if we consider for the sake of simplicity only the \\lstinline{lit}\nfield, we have that \\lstinline{(Int -> IPrint) & (Int -> IEval)} is a\nsubtype of \\lstinline{Int -> IPrint & IEval}. This follows from a standard\nsubtyping axiom for distributivity of functions and intersections in the BCD system inherited by \\namee.\nIn conclusion, \\lstinline{Lang & EvalExt} is a subtype of both \\lstinline{Lang}\nand of \\lstinline{LangEval}. However, neither of the latter two types is a subtype of the other.\nIndeed, \\lstinline{LangEval} is not a subtype of \\lstinline{Lang} as the type\nof \\lstinline{add} is not covariantly refined and thus admitting the subtyping\nis unsound. For the same reason \\lstinline{Lang} is not a subtype of \\lstinline{LangEval}.\n\n\nA summary of the various relationships between the language components is shown\nin \\cref{fig:diagram}. Admittedly, the figure looks quite complex because our\ncalculus has a structural type system (as often more foundational calculi\ndo) where more types are related through subtyping, whereas mainstream object-oriented\nlanguages have nominal type systems.\n\n\n\n\\begin{figure}[t]\n  \\centering\n\\includegraphics[scale=0.75]{figures/diagram.eps}\n\\caption{Summary of the relationships between language components}\n\\label{fig:diagram}\n\\end{figure}\n\n\n\\paragraph{Stand-alone extensions.}\nUnlike in \\textsf{gbeta} and other class-based inheritance systems, in \\namee\nthe extension \\lstinline{implEval} is not tied to \\lstinline{LangEval}. In that\nsense, it resembles trait and mixin systems that can apply the same extension\nto different classes. However, unlike those systems, \\lstinline{implEval} can also\nexist as a value on its own, i.e., it is not an extension per se.\n\n%-------------------------------------------------------------------------------\n% \\subsection{Disjoint Intersection Types and Ambiguity}\n\n% The above example shows that intersection types and the merge operator\n% are closely related to multiple\n% inheritance. Indeed, they share a major concern with multiple inheritance,\n% namely ambiguity. When a subclass inherits an implementation of the same\n% method from two different parent classes, it is unclear which of the two\n% methods is to be adopted by the subclass. In the case where the two parent classes\n% have a common superclass, this is known as the \\emph{diamond problem}.\n% The ambiguity problem also appears in \\namee,\n% e.g., if we merge two numbers to obtain $\\mer{1}{2}$ of type\n% $\\inter{\\mathsf{Int}}{\\mathsf{Int}}$. Is the result of $\\mer{1}{2} + 3$\n% either $4$ or $5$?\n\n% Disjoint intersection types offer to statically detect potential ambiguity and\n% to ask the programmer to explicitly resolve the ambiguity by rejecting the\n% program in its ambiguous form. In the previous work on \\oname, ambiguity is\n% avoided by dictating that all intersection types have to be disjoint, i.e.,\n% $\\inter{\\mathsf{Int}}{\\mathsf{Int}}$ is ill-formed because the first component\n% has the same type as the second.\n\n\n% Disjoint intersection types ensure unambiguity and conflicts are\n% statically detected and manually resolved by programmers. This\n% is similar to the trait model.\n\n\n% Local Variables:\n% TeX-master: \"../../Thesis\"\n% org-ref-default-bibliography: ../../Thesis.bib\n% End:\n", "meta": {"hexsha": "49b3429f0ba6b7318ca43b71069d8ce78433d052", "size": 9665, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Sources/Nested/overview.tex", "max_stars_repo_name": "bixuanzju/thesis", "max_stars_repo_head_hexsha": "dd2b64513af51f30e1b87baae0ecc1ba32745bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-10-25T15:09:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-26T22:17:51.000Z", "max_issues_repo_path": "Sources/Nested/overview.tex", "max_issues_repo_name": "bixuanzju/thesis", "max_issues_repo_head_hexsha": "dd2b64513af51f30e1b87baae0ecc1ba32745bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sources/Nested/overview.tex", "max_forks_repo_name": "bixuanzju/thesis", "max_forks_repo_head_hexsha": "dd2b64513af51f30e1b87baae0ecc1ba32745bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-08T09:02:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-08T09:02:19.000Z", "avg_line_length": 53.3977900552, "max_line_length": 141, "alphanum_fraction": 0.7350232799, "num_tokens": 2557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3148300531811561}}
{"text": "%!TEX root = ../thesis.tex\n\\chapter{Blockchain}\n\\label{blockchain}\n\nA \\textit{blockchain} is a \\textit{distributed transaction ledger}~\\cite{nakamoto2012bitcoin}. It consists of a continuously growing list of \\textit{blocks} which are linked, ordered, and immutable. Each block typically contains a \\textit{hash pointer} being a link to a previous block, a timestamp and a list of \\textit{transactions}. Transactions describe the transfer of assets from one entity to another. A distributed network is formed by the users of the system without central control. Each node of the network contains a local copy of the blockchain; the transaction ledger. To come to an agreement on the correct ledger, the network uses a decentralized \\textit{consensus} mechanism with which integrity is achieved and malicious activity is prevented.\n\nBlockchains are potentially suitable for financial activities, the recording of events, medical records~\\cite{blockchain_ehr,Azaria2016}, and other record management activities, such as identity management, transaction processing or documenting provenance. Blockchain can be seen as a distributed immutable, tamper-proof, and audit log that records all data transactions. As a result any attempt to tamper blockchain is immediately evident and easily detectable.\n\n\\textit{Bitcoin}~\\cite{nakamoto2012bitcoin} is the first decentralized \\textit{cryptocurrency}, a monetary system without central authority invented by an unknown person or a group of people under the name of \\textit{Satoshi Nakamoto}~\\cite{nakamoto2012bitcoin}. Its ability to provide a solution to the \\textit{double spending problem}~\\cite{double_spent, nakamoto2012bitcoin} made it a powerful digital currency among physical currencies in less that 10 years, triggering an explosion of more than 800 other digital coins.\n\nThe goal of this chapter is to present of the basic operating principles of the blockchain, which are based on the foundation of cryptography -- without getting to unnecessary details or rigorous mathematical proofs. As Bitcoin was the first decentralized blockchain system that put the bases for others to be made and involve~\\cite{7163021,10.1007/978-3-662-46803-6_10, ethereum_whitepaper}, we mainly focus on blockchain internals. Notable variations of blockchains that support features of our interest are mentioned selectively further in this chapter.\n\n\\section{History}\\label{blockchain:history}\n\nCredit card transactions are the dominant payment method that is used on the web today~\\cite{Narayanan:2016:BCT:2994437}. This system is handled by a financial\nsystem involving processors, banks, credit card companies and other intermediaries. Normally a credit card transaction is realized as follows: first, the buyer sends over his credit card details to the merchant; then the merchant sends and validates the data in the financial system.\n\nBuyers may not want to handle their credit card details to an unknown vendor over an insecure channel. Intermediate services -- such as Paypal -- sits between the buyer and the seller and the intermediate service approves\nthe transaction and notify the seller. This allows the buyer to keep his anonymity and avoid security risks.\n\nThe idea of \\textit{digital cash} was first introduced by David Chaum in his paper~\\cite{Chaum1983}, entitled ``Blind Signatures for Untraceable Payments'', in 1983. In 1990 Chaum proposed the first off-line e-cash system~\\cite{Chaum:1988:UEC:646753.704915} and founded DigiCash~\\cite{chaum1983blind}, an electronic money corporation that sent the first electronic payment in 1994.\n\nDigital cash schemes are vulnerable to that is called double-spending~\\cite{10.1007/978-3-662-46803-6_10, 7163021}. It comes up when the same digital token is spent more than once.  Chaum found a way to both keep the system anonymous and prevent double-spendings with the use of \\textit{blind signatures}~\\cite{Chaum1983,Chaum:1988:UEC:646753.704915}.\nYet still, Chaum's solution needed a centralized trusted oracle which validated the transactions. Many cryptographers attempted to improve Chaum's scheme over the years. Okamoto and Ohta~\\cite{Watanabe1996}, for example, in 1996 implemented coin subdivisions with the use of \\textit{Merkle trees}~\\cite{merkle_tree}.\n\nAbout the same time, a group of cryptographers called \\textit{Cypherpunks}~\\cite{cypherpunk,cypherpunks_manifesto} was formed and advocate the widespread\nuse of strong cryptography and privacy-enhancing technologies~\\cite{cypherpunks_manifesto} as a way to social and political change. Cypherpunks electronic mailing list, through which they communicating originally, was the predecessor to the mailing list where Satoshi Nakamoto would announce later Bitcoin~\\cite{nakamoto2012bitcoin}. Chaum's ideas are supposed to have set the technical roots of the vision of the Cypherpunk movement~\\cite{cypherpunk}. Chaum patented the blind-signature scheme preventing others from developing ecash system that use the same protocol. Violating Chaum's patents, Cypherpunks implemented an e-cash system called Magic Money~\\cite{magic_money} which further developed his technology.\n\nHowever, DigiCash failed to gain public attraction. Its main problem was that  banks and merchants would not adopt it for commercial and financial purposes.\n\nIn 1991, Haber et al.~\\cite{Haber1991} proposed a scheme for \\textit{secure timestamping} of digital documents using digital signatures and hash pointers in previous documents, thus creating a chain of document certificates. In an improvement which was proposed later documents were collected into a block, all the blocks linked together in a chain. This data structure form of the skeleton for Bitcoin's blockchain.\n\nA year later, cryptographers Dwork and Naor came up with a solution to email spamming~\\cite{Dwork1993} by using \\textit{computational puzzles}.They created the idea of \\textit{Proof-of-Work}. In 1997, Adam Back proposed a similar idea that he called Hashcash~\\cite{hash_cash}. Back's Proof-of-Work system set the basis for Bitcoin's consensus mechanism.\n\nWei Dai at 1998 proposed b-money~\\cite{b_money}, an anonymous distributed electronic cash system, in which everyone could create money using a Proof-of-Work mechanism like Ηashcash. B-money used the notion of a secured timestamp ledger as used by Haber et al. for digital documents~\\cite{Haber1991}.\n\nIn 2008, Satoshi Nakamoto published a paper under the title \\textit{``Bitcoin: A Peer-to-Peer Electronic Cash System''} on The Cryptography Mailing list at metzdowd.com~\\cite{satoshi_mailing_list} describing the Bitcoin protocol. The Bitcoin network came into existence on 3 January 2009 with the release of the first Bitcoin client, \\verb|wxBitcoin|, and the issuance of the first Bitcoins~\\cite{btc_client, btc_first_block}. Bitcoin represents a decade long work of research in cryptography combining several prior inventions~\\cite{antonopoulos2014mastering}.\n\nBitcoin is the first decentralized digital currency. The Bitcoin network is a fully distributed peer-to-peer network that anyone can freely join by running an open source implementation of the bitcoin protocol. Bitcoin does not rely on a trusted central authority and was he first applied solution to overcome the \\textit{Byzantine Generals' Problem}~\\cite{byzantine_fault_tolerance}. Bitcoin makes use a Proof-of-Work consensus mechanism that keeps  the public ledger consistent, prevents double-spends and confirms transactions. It can also be used to achieve consensus on decentralized networks for elections, lotteries, asset registries, and more~\\cite{antonopoulos2014mastering}.\n\nRunning from 2009, Bitcoin is the most well studied Blockchain network~\\cite{10.1007/978-3-662-46803-6_10} with various published papers on different topics such as privacy~\\cite{10.1007/978-3-319-70278-0_8, 10.1007/978-3-642-39884-1_2, Bonneau14e.w.:mixcoin, 10.1007/978-3-662-44774-1_9}, economics~\\cite{Babaioff:2012:BRB:2229012.2229022, 10.1007/978-3-319-70278-0_17, Bentov2017DecentralizedPM, Carlsten:2016:IBW:2976749.2978408}, attacks~\\cite{DBLP:journals_corr_Bahack13, DBLP:journals_corr_EyalS13}, network~\\cite{10.1007/978-3-662-44774-1_7, 190890} and scalability~\\cite{kiayias2017non, 10.1007/978-3-662-53357-4_5, 10.1007/978-3-662-53357-4_8}. Over the years, Bitcoin's blockchain has grown significantly is size making it difficult for certain devices to store all of it and run as a full node. Specifically, In April 2018 the Bitcoin's blockchain size is over 160GB~\\cite{btc_bl_size}.\n\nBitcoin does not scale efficiently. There is a limit on the amount of transactions the bitcoin network can process. The maximum transaction processing capacity is estimated between 3.3 and 7 transactions per second~\\cite{10.1007/978-3-662-53357-4_8}. The limit is related to the block size limit -- the total number of transactions a block can contain -- that was introduced as an anti-spam measure. Various solutions proposed to address this issue. One implemented solution is \\textit{Segregated Witness} (SegWit, BIP 141)~\\cite{segwit}. The SegWit implementation increased the block size by a factor of approximately of two.\n\n\\section{Identity}\\label{blockchain:identity}\n\nThe identity of a blockchain user is defined as a cryptographic key pair $(s_k, p_k)$, where $s_k$ is the private key and $p_k$ the public key. The private key is used for spending a ``coin'' and the public key is used as the receiving \\textit{address} of the user. No real-world name or identifying information are required~\\cite{7163021,nakamoto2012bitcoin}.\n\nIn Bitcoin, due to the public nature of the blockchain, it is possible to trace the flow of money between addresses and conclude that they are likely controlled by the same individual~\\cite{7163021,10.1007/978-3-319-17016-9_1}. For that reason, Bitcoin's identity system is considered \\textit{pseudonymous}. The underlaying non-anonymous Internet infrastructure -- nodes leak their IP address when broadcasting transactions -- together with the availability of all bitcoin transactions in the blockchain can be a threat to anonymity~\\cite{10.1007/978-3-319-17016-9_1, 7163021,Meiklejohn:2013:FBC:2504730.2504747,6113303,10.1007/978-3-642-39884-1_2,fi5020237}.\nAlthough Bitcoin let users to create new addresses at any time for any transaction, various techniques, such as transaction graph analysis, can be utilized to link together different addresses controlled by the same user~\\cite{7163021,Meiklejohn:2013:FBC:2504730.2504747,6113303,10.1007/978-3-642-39884-1_2,fi5020237}.\n\nDifferent cryptocurrencies, such as Zerocash~\\cite{zcash} and CryptoNote~\\cite{cryptonote}, were built differently in ways that improve bitcoin's anonymity. In particular, Zerocash utilize zero-knowledge proofs (zkSNARKs~\\cite{10.1007/978-3-642-40084-1_6}) which reveal no information at all about the amount or recipients enabling a completely untraceable ledger. On the other hand, CryptoNote uses \\textit{ring signatures} creating a \\textit{mixing protocol} satisfying both \\textit{untraceability} -- for each incoming transaction all possible senders are probable -- and \\textit{unlinkability}. CryptoNote compared to Zerocash has better performance but weaker anonymity~\\cite{7163021}.\n\n\\section{Network}\\label{blockchain:network}\n\nBlockchain networks are \\textit{peer-to-peer} networks. Anyone who wants to and spend and receive coins can freely join and participate in the network by running a software on their computer. All the nodes of the network are equal. There is no central server or trusted authority, neither hierarchy within the network. Both the protocol as well as the software are open. Every node connects to other peers of the network using peer-to-peer discovery schemes. In Bitcoin, there are some nodes called seed nodes, that their IP address is hardcoded in the code. This nodes can be used to quickly discover other nodes. Alternatively, a known IP address of a bitcoin node can be given manually.\n\n\\section{Transactions}\\label{blockchain:structure:tx}\n\nThe basic data structure of the blockchain is \\textit{transaction (tx)}. A transaction transfers assets from one party to another. When a user wants to transfer coins to another user she must sign a transaction. The signature certify that the sender owns the coins.\n\nA blockchain transaction can be described as a \\textit{node} with two \\textit{edges}, one \\textit{incoming} edge and one \\textit{outcoming} edge~\\cite{zindros_thesis}. The incoming edge describes the sender (from) and the outcoming edge the recipient (to). Each edge have each entity's address; its public key. Every bitcoin transaction has a unique \\textit{transaction id (txid)} which is derived by double hashing the transaction with the use of the SHA-256 cryptographic hash function. Payments are done by \\textit{linking} transaction nodes and money can be view as a chain of transactions where monetary value pass~\\cite{zindros_thesis}. All transactions together form a transaction graph which is public. Every participant of the network can access and add a new transaction to the transaction graph.\n\n\\begin{figure}[!ht]\n  \\centering\n  \\begin{subfigure}[!ht]{\\textwidth}\n    \\centering\n    \\begin{tikzpicture}\n      \\node[tx] (A) at (0,0) {$tx$};\n      \\draw [->] ++(-3,0) -- (A) node[midway, below]{Alice} node[midway, above]{5mBTC};\n      \\draw [->] (A) -- ++(3, 0) node[midway, below]{Bob} node[midway, above]{5mBTC};\n    \\end{tikzpicture}\n    \\caption{Simplified}\n    \\label{fig:bl_tx:simple}\n    \\vspace*{2mm}\n  \\end{subfigure}\n  \\begin{subfigure}[!ht]{\\textwidth}\n    \\centering\n    \\begin{tikzpicture}\n      \\node[tx] (A) at (0,0) {$tx$};\n      \\draw [->] (-3,0) -- (A) node[below, xshift=-4.7cm]{\\footnotesize{1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2}} node[midway, above]{5mBTC};\n      \\draw [->] (A) -- (3, 0) node[left, below, xshift=1.5cm]{\\footnotesize{1J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy}} node[midway, above]{5mBTC};\n    \\end{tikzpicture}\n    \\caption{Addresses are public keys}\n    \\label{fig:bl_tx:pub}\n    \\vspace*{2mm}\n  \\end{subfigure}\n  \\caption{A bitcoin transaction}\n  \\label{fig:bl_tx:tx}\n\\end{figure}\n\n\\begin{figure}[!ht]\n  \\centering\n  \\begin{tikzpicture}\n    \\node[tx] (A) at (0,0) {$tx$};\n    \\draw [->] (-3,0) -- (A) node[midway, below]{Alice} node[midway, above]{5mBTC};\n    \\draw [->] (A) -- (3, 0) node[midway, below]{Bob} node[midway, above]{5mBTC};\n    \\node (txid) at (-5,0) {$txid = SHA256^{2}($};\n    \\node (txid) at (3.3,0) {$)$};\n  \\end{tikzpicture}\n  \\caption{Bitcoin Transaction ID}\n  \\label{fig:bl_tx:id}\n\\end{figure}\n\nWhen a transaction is occured, each node on the network should be able to confirm that the user making the transaction, has indeed the amount of transfer. Otherwise, anyone could produce money arbitrarily, sign it and create a valid transaction. As there is no central authority the whole network have to maintain exactly who has how much coin.\n\nA transaction can have \\textit{outgoing unlinked edges}, edges that are not connected to another node transaction. These edges are unspent coins, owned by various users and ready to be spent. This type of edges are called \\textit{unspent transaction outputs} (UTXO). The UTXO set, the list of all outgoing unlinked edges, describes how much coins each user owns and is kept by every node of the network. In this way, the network can confirm, by checking the UTXO set, that the sender owns the money at the time of the transaction.\n\nWhen a user wants to transfer money to another user, she have to find a previous transaction with a UTXO that she owns. Then she creates one transaction with one incoming and one outgoing edge and connects the incoming edge of the new transaction with the UTXO of the previous transaction. The previous UTXO is removed from the UTXO set. The outgoing edge of the new transaction is unconnected and becomes a new UTXO. The new UTXO specifies the value and the owner (address) of that edge. Finally she signs the transaction. The signing of the transaction is a way of declaring asset ownership. The user have to prove that for a public key -- the address where the UTXO points to -- she holds the corresponding private key. Only the owner of the private key can produce valid signatures that are verifiable under the corresponding public key.\n\nThe UTXO set is maintained collectively by the network. When a full node is connected for the first time to the network, the nodes with which it connects inform it about the UTXO set and the history of all transactions that occurred from the begging of time. If a full node reconnects after a period on inactivity the node is informed about the new transactions that took place since the last time the node was connected to the network.\n\nEach transaction is published on the network. This is achieved through a mechanism called broadcasting. When a transaction is created, the participants broadcast the details of the transaction to their neighbors. The neighbors publish the transaction to their neighbors and recursively the transaction is being published until the whole network becomes aware of it.\n\nIn Bitcoin a user cannot give changes. This is due to the lack of accounts and balances. The only way of keeping track money ownership is with the use of the UTXO set. For that reason, the total value of the income edge must be consumed at once. To overcome this problem bitcoin uses multiple incoming and outcoming edges for each transaction to create a changing system. In particular, when a user wants to transfer money to another user and the value of the UTXO edge is bigger than the desired amount, she can create a transaction with two outcoming edges, one for the recipient and one to give changes to herself.\n\n\\begin{figure}[!ht]\n  \\centering\n  \\begin{tikzpicture}\n    \\node[tx] (A) at (0,0) {$tx$};\n    \\draw [->] (-3,0) -- (A) node[midway, below]{Alice} node[midway, above]{1mBTC};\n    \\draw [->] (A) -- ++(2, 0) -- ++(1, 1) -- ++(2, 0) node[midway, below]{Bob} node[midway, above]{0.1mBTC};\n    \\draw [->] (A) -- ++(2, 0) -- ++(1, -1) -- ++(2, 0) node[midway, below]{Alice} node[midway, above]{0.9mBTC};\n  \\end{tikzpicture}\n  \\caption{Change exchange}\n  \\label{fig:bl_tx:change}\n\\end{figure}\n\n\\begin{figure}[!ht]\n  \\centering\n  \\begin{tikzpicture}[node distance=3cm]\n    \\node[tx] (A) at (0,0) {$tx$};\n    \\node[tx, below of=A] (B) {$tx$};\n    \\node[tx, below of=B] (C) {$tx$};\n    \\node[tx, right of=B, node distance=7cm] (D) {$tx$};\n\n    \\draw [->] (A) -- ++(4, 0) node[midway, below]{Alice} node[midway, above]{1mBTC} -- (D);\n    \\draw [->] (B) -- ++(4, 0) node[midway, below]{Alice} node[midway, above]{2mBTC} -- (D);\n    \\draw [->] (C) -- ++(4, 0) node[midway, below]{Alice} node[midway, above]{1.5mBTC} -- (D);\n\n    \\draw [->] (D) -- ++(4, 0) node[midway, below]{Bob} node[midway, above]{4.5mBTC};\n\n  \\end{tikzpicture}\n  \\caption{Transaction multiple inputs}\n  \\label{fig:bl_tx:change}\n\\end{figure}\n\n\\begin{figure}[!ht]\n  \\centering\n  \\begin{tikzpicture}\n    \\node[tx] (A) at (-5,0) {$tx$};\n    \\node[tx] (B) at (0,0) {$tx$};\n    \\draw [->] (A) -- (B) node[midway, below]{Wage} node[midway, above]{1mBTC};\n    \\draw [->] (B) -- ++(2, 0) -- ++(1, 2) -- ++(2, 0) node[midway, below]{Rent} node[midway, above]{0.6mBTC};\n    \\draw [->] (B) -- ++(2, 0) -- ++(3, 0) node[midway, below, xshift=1em]{Electricity} node[midway, above, xshift=1em]{0.2mBTC};\n    \\draw [->] (B) -- ++(2, 0) -- ++(1, -2) -- ++(2, 0) node[midway, below]{Gas} node[midway, above]{0.2mBTC};\n  \\end{tikzpicture}\n  \\caption{Transaction multiple outputs}\n  \\label{fig:bl_tx:multi_out}\n\\end{figure}\n\nIn Bitcoin each transaction must satisfy the Kirchhoff's property. Kirchhoff's property mandates that the total outputs of a transaction are at most equal to the total inputs. In particular, let $txs$ be all transactions of the network, $out(tx)$ all the output edges of the transaction $tx$, $in(tx)$ all the input edges of the transaction $tx$ and $w(e)$ the value of that edge, it holds that:\n\n\\begin{equation*}\n  \\forall tx \\in txs: \\sum_{o \\in out(tx)}w(o) \\leq \\sum_{i \\in in(tx)}w(i)\n\\end{equation*}\n\n\\begin{figure}[ht!]\n    \\centering\n    \\begin{tikzpicture}[scale=0.9]\n      \\node[tx] (A) at (0,0) {$tx$};\n      \\node[tx] (B) at (4,0) {$tx$};\n      \\node[tx] (C) at (8,0) {$tx$};\n      \\draw [->] (-3,0) -- (A) node[midway, below]{Alice} node[midway, above]{1mBTC};\n      \\draw [->] (A) -- (B) node[midway, below]{Bob} node[midway, above]{1mBTC};\n      \\draw [->] (B) -- (C) node[midway, below]{Charlie} node[midway, above]{1mBTC};\n      \\draw [->] (C) -- (11,0) node[midway, below]{Eve} node[midway, above]{1mBTC};\n\n      \\node[red] (D) at (10, 3) {$utxo$};\n      \\draw [->, red] (D) -- (10,0.8);\n      \\node[ellipse, draw, red, inner xsep=4.5ex,inner ysep=1.9ex] at (10,0) {};\n    \\end{tikzpicture}\n  \\caption{Transaction graph and UTXO}\n  \\label{fig:bl_utxo}\n\\end{figure}\n\n\\begin{figure}[ht!]\n  \\begin{subfigure}[t]{0.50\\textwidth}\n    \\centering\n    \\begin{tikzpicture}\n      \\node[tx] (A) at (0,0) {$tx$};\n      \\draw [->] (A) -- (3,0) node[midway, below]{Alice} node[midway, above]{1mBTC};\n\n      \\node[red] (utxo) at (2, 3) {$utxo$};\n      \\draw [->, red] (utxo) -- (2,0.8);\n      \\node[ellipse, draw, red, inner xsep=4.5ex,inner ysep=1.9ex] at (2,0) {};\n    \\end{tikzpicture}\n    \\caption{Alice finds one UTXO that belongs to her}\n    \\label{fig:bl_spent:a}\n  \\end{subfigure}\n  \\begin{subfigure}[t]{0.50\\textwidth}\n    \\centering\n    \\begin{tikzpicture}[scale=0.9]\n      \\node[tx] (A) at (0,0) {$tx$};\n      \\draw [->] (A) -- (3,0) node[midway, below]{Alice} node[midway, above]{1mBTC};\n      \\node[tx] (B) at (5,0) {$tx$};\n      \\draw [->] (B) -- (8,0) node[midway, below]{Bob} node[midway, above]{1mBTC};\n\n      \\node[red] (utxo) at (2, 3) {$utxo$};\n      \\draw [->, red] (utxo) -- (2,0.8);\n      \\node[ellipse, draw, red, inner xsep=4.5ex,inner ysep=1.9ex] at (2,0) {};\n    \\end{tikzpicture}\n    \\caption{Alice create a transaction with recipient Bob}\n    \\label{fig:bl_spent:b}\n  \\end{subfigure}\n  \\begin{subfigure}[t]{0.50\\textwidth}\n    \\centering\n    \\begin{tikzpicture}[scale=0.9]\n      \\node[tx] (A) at (0,0) {$tx$};\n      \\node[tx] (B) at (4,0) {$tx$};\n      \\draw [->] (A) -- (B) node[midway, below]{Alice} node[midway, above]{1mBTC};\n      \\draw [->] (B) -- (7,0) node[midway, below]{Bob} node[midway, above]{1mBTC};\n\n      \\node[red] (utxo) at (2, 3) {$not\\text{ }utxo\\text{ }anymore$};\n      \\draw [->, red] (utxo) -- (2,0.8);\n      \\node[ellipse, draw, red, inner xsep=4.5ex,inner ysep=1.9ex] at (2,0) {};\n\n      \\node[blue] (utxo) at (6, 3) {$new\\text{ }utxo$};\n      \\draw [->, blue] (utxo) -- (6,0.8);\n      \\node[ellipse, draw, blue, inner xsep=4.5ex,inner ysep=1.9ex] at (6,0) {};\n    \\end{tikzpicture}\n    \\caption{Alice connects the incoming edge of the new transaction with the old UTXO}\n    \\label{fig:bl_spent:c}\n  \\end{subfigure}\n  \\begin{subfigure}[t]{0.50\\textwidth}\n    \\centering\n    \\begin{tikzpicture}[scale=0.9]\n      \\node[tx] (A) at (0,0) {$tx$};\n      \\node[tx] (B) at (4,0) {$tx$};\n      \\draw [->] (A) -- (B) node[midway, below]{Alice} node[midway, above]{1mBTC};\n      \\draw [->] (B) -- (7,0) node[midway, below]{Bob} node[midway, above]{1mBTC};\n\n      \\node[red] (utxo) at (4.8, 3) {$Alice\\text{ }signs\\text{ }$};\n      \\node[ellipse, draw, red, inner xsep=8ex,inner ysep=4ex] (ell) at (4.8,0) {};\n      \\draw [->, red] (utxo) -- (ell);\n    \\end{tikzpicture}\n    \\caption{Alice signs the transaction. No one else can forge this signature}\n    \\label{fig:bl_spent:d}\n  \\end{subfigure}\n  \\caption{Speding money}\n  \\label{fig:bl_spent}\n\\end{figure}\n\n\\section{Blocks \\& Blockchain}\\label{blockchain:structure:blockchain}\n\nA double spent or a double spent attack is the action where a user sends the same transaction twice; transactions that spend the same UTXO. For example, Eve buys a coffee from Alice and creates a transaction that pays Alice. At the same time, Eve creates a transaction that sent the same amount to herself. Eve get her coffee and leave. Alice learn about the double spent later. Both transactions are valid: the signatures are valid and the Kirchhoff's property holds for both transactions.\n\nAs the network is decentralized and there is \\textit{latency}, a double spending may not be immediately noticed. In this case, it is impossible to tell which transaction occurred first and which second. To prevent double-spending the transaction must be put in \\textit{chronological order}. This way nodes of the network are sure if transaction A precedes transaction B. Furthermore, the order must be common for everyone.\n\n\\begin{figure}[!ht]\n  \\centering\n  \\begin{tikzpicture}\n    \\node[tx] (A) at (0,0) {$tx$};\n    \\draw [->] (-3,0) -- (A) node[midway, below]{Eve} node[midway, above]{1mBTC};\n    \\draw [->] (A) -- ++(2, 0) -- ++(1, 1) -- ++(2, 0) node[midway, below]{Alice} node[midway, above]{1mBTC};\n    \\draw [->] (A) -- ++(2, 0) -- ++(1, -1) -- ++(2, 0) node[midway, below]{Eve} node[midway, above]{1mBTC};\n  \\end{tikzpicture}\n  \\caption{A double spent}\n  \\label{fig:bl_tx:change}\n\\end{figure}\n\nTo achieve chronological order Bitcoin utilize a data structure called \\textit{blockchain}. The blockchain is an ordered back-linked list of \\textit{blocks}. Each block contains a set of transactions. A block cannot contain double spends and each transaction can appear only once in a block. A transaction is called \\textit{confirmed} if it is in a valid block. A valid block cannot contain a transaction that spends an already spent UTXO  by another transaction in a preceding block. Transaction A precedes transaction B if A is contained in a previous block from B. To ensure that a transaction is not a double spent, a user have to wait until the transaction contained in a valid block and thus confirmed. In the bitcoin network a block is set to be created approximately once every \\textit{ten minutes} and every newly created block contains the most recent transactions that did not exist in previous blocks.\n\nEvery bitcoin's block has a unique \\textit{block id} which is derived from the double hash of the header of the block with the use of the SHA-256 cryptographic hash function. Each block references to the previous block id known as the \\textit{parent block} through a pointer. Thus, every next block contains the hash of the previous block. This results in every next block in the chain requiring the previous block to have been already computed~\\cite{zindros_thesis}.\n\n\\begin{figure}[ht!]\n  \\begin{subfigure}[t]{0.40\\textwidth}\n    \\centering\n    \\begin{tikzpicture}\n      \\draw (0,0) rectangle (5,3);\n      \\foreach \\x in {1,2,...,4}\n        \\foreach \\y in {1,...,2}\n          \\node[circle,draw, minimum size=0.4cm] at (\\x,\\y) {$tx$};\n\n      \\node[red] (confirm) at (4.8, 4) {$confirmed \\text{ }transaction$};\n      \\draw [->, red] (confirm) -- (4,2.2);\n    \\end{tikzpicture}\n    \\caption{A block}\n    \\label{fig:block:a}\n  \\end{subfigure}\n  \\begin{subfigure}[t]{0.40\\textwidth}\n    \\centering\n    \\begin{tikzpicture}[scale=0.9]\n      \\draw (0,0) rectangle (5,3);\n      \\foreach \\x in {1,2,...,4}\n        \\foreach \\y in {1,...,2}\n          \\node[circle,draw, minimum size=0.4cm] at (\\x,\\y) {$tx$};\n      \\node (txid) at (-2.5,1.5) {$blockid = SHA256^{2}($};\n      \\node (txid) at (5.5,1.5) {$)$};\n    \\end{tikzpicture}\n    \\caption{Bitcoin Block ID}\n    \\label{fig:block:b}\n  \\end{subfigure}\n  \\caption{Blocks}\n  \\label{fig:blocks}\n\\end{figure}\n\n\\begin{figure}[ht!]\n  \\centering\n  \\begin{tikzpicture}\n    \\foreach \\x in {0,1,...,4}\n        \\pgfmathparse{(\\x*3)}\n        \\edef\\position{\\pgfmathresult}\n        \\node[bl_block] (\\x) at (\\position,0) {$block$};\n\n    \\foreach \\x in {1,2,...,4}\n        \\pgfmathparse{(\\x-1)}\n        \\edef\\previous{\\pgfmathresult}\n        \\draw [->] (\\x) -- (\\previous);\n\n  \\end{tikzpicture}\n  \\caption{The blockchain}\n  \\label{fig:blockchain}\n\\end{figure}\n\n\\begin{figure}[ht!]\n  \\begin{tikzpicture}\n    \\foreach \\x in {0,1,...,4}{\n        \\pgfmathparse{(\\x*3)}\n        \\edef\\position{\\pgfmathresult}\n        \\node[bl_block] (\\x) at (\\position,0) {$block$};\n        \\pgfmathparse{int(\\x*10 + 10)}\n        \\edef\\time{\\pgfmathresult}\n        \\node[] at (\\position,-2) {$17:\\time$};\n    }\n\n\n    \\foreach \\x in {1,2,...,4}\n        \\pgfmathparse{(\\x-1)}\n        \\edef\\previous{\\pgfmathresult}\n        \\draw [->] (\\x) -- (\\previous);\n\n    \\node[ellipse, draw, red, inner xsep=6ex,inner ysep=3ex] (old_ell) at (0) {};\n    \\node[ellipse, draw, red, inner xsep=6ex,inner ysep=3ex] (recent_ell) at (4) {};\n    \\node[red,below=0cm of old_ell] (old) {$oldest\\text{ }block\\text{ }$};\n    \\node[red,below=0cm of recent_ell] (recent) {$recent\\text{ }block\\text{ }$};\n  \\end{tikzpicture}\n  \\caption{The blockchain timeline}\n  \\label{fig:blockchain_timeline}\n\\end{figure}\n\n\\section{Consensus mechanisms}\\label{blockchain:consensus_mechanisms}\n\nThe use of the blockchain data structure achieves transaction chronological order. What remains is a \\textit{global agreement} on the order of the blocks among the participants of the network. Someone can easily change the order of two blocks within the chain by changing the respective hashes or producing new ones wherever required~\\cite{zindros_thesis}. This would allow an adversary to fake the order of transactions in time, which is an undesired outcome.\n\nThe global agreement on a common truth, the global blockchain (\\textit{ledger}), is called \\textit{consensus} -- a single universal “truth”. The consensus mechanism is the core mechanism of the blockchain. Through consensus, the \\textit{shared state} of the ledger comes to an agreement allowing all the nodes of the network to reach the same ledger state. Through consensus the users of the network agree on a common order of the blocks in the blockchain and therefore on the order of the transactions. Achieving consensus in a distributed system is challenging. A consensus mechanism has to be resilient to node failures, network delays and the existence of malicious nodes.\n\nAt high level, every public consensus mechanism works as follows: A ``game'', involving randomness, is taken place where each node of the network participates. The winner of the game is eligible to propose the new block that will be adopted in the blockchain. The probabilistic nature of the process is paramount to its security~\\cite{10.1007/978-3-662-46803-6_10}.\n\nThere are three basic consensus mechanism categories:\n\n\\begin{enumerate}\n  \\item Proof-of-Work (PoW).\n  \\item Proof-of-Stake (PoS).\n  \\item Practical Byzantine Fault Tolerance (PBFT)\n\\end{enumerate}\n\n\n\\subsection{Proof of Work (PoW)}\\label{blockchain:consensus:pow}\n\nA Proof-of-Work (PoW) consensus mechanism, is a consensus mechanism where each node of the network tries to solve a computational puzzle that is computational \\textit{hard}, but feasible to find, and easy to verify \\textit{correctness}. Assuming that cryptographic hash functions are hard to invert, proof of work usually is established by seeking a range-collision of the hash function on the block~\\cite{zindros_thesis}.\n\n\\begin{figure}[!ht]\n  \\centering\n  \\begin{tikzpicture}[node distance=10cm, minimum height=1cm, minimum width=2cm]\n    \\node[draw] (a) {Alice};\n    \\node[draw, right of =a] (b) {Bob};\n    \\node[below of=a, node distance=1cm] (c) {$H(K || x) \\stackrel{?}{\\leq} \\epsilon$};\n    \\node[below of=b, node distance=1cm] (d) {$pow(K, e)$};\n    \\draw[->] ([yshift=0.5em]a.east) -- ([yshift=0.5em]b.west) node[midway, above] {$K, \\epsilon$};\n    \\draw[<-] ([yshift=-0.5em]a.east) -- ([yshift=-0.5em]b.west) node[midway, below] {$x$};\n  \\end{tikzpicture}\n  \\caption{The Proof-of-Work protocol}\n  \\label{fig:consensus:pow}\n\\end{figure}\n\nBitcoin~\\cite{Zohar:2015:BUH:2817191.2701411} is the first blockchain system that uses Proof-of-Work for achieving consensus among the nodes of the network. A \\textit{target} $\\epsilon$ is given and is asked that the hash of the block is \\textit{smaller} than the target. The node can only modify a \\textit{nonce}. By changing the nonce the node can change the block's hash (id). As cryptographic hash functions is assumed to be one-way, the only way to find a hash value smaller than the target is with a series of \\textit{brute-force} trials of different nonce values. Bitcoin's proof-of-work can be summarized as:\n\n\\begin{equation*}\n  H(txs || nonce || parent\\_blockid) \\leq \\epsilon\n\\end{equation*}\n\nThe network evaluates collectively the target value using a predefined algorithm. Thus, the difficulty of proof-of-work and the frequency with which the blocks are generated are controlled by the network. In Bitcoin the expected \\textit{block generation rate} is one block per 10 minutes.\n\nAll the nodes of the network simultaneously try to produce a new block, meaning they try to find a correct nonce satisfying the proof-of-work requirements. The block the node produces includes all the valid transactions -- transactions that are not in a previous block -- and a reference to a parent block. Each block has to meet the target proof-of-work requirements. If not the block is considered invalid.\n\nWhen a node finds a hash value less than the target, it gets to add the proposed block to the blockchain. It broadcasts the new block to all its neighbors which, in turn, transmit it to the whole network. When a block is found by another node, all the nodes stop the block production and start over upon the new block. A block is valid if it contains valid transactions, a valid proof-of-work and a reference to a known valid parent block.\n\nThe existence of a transaction in a block makes the transaction valid. The deeper the block is in the blockchain the more difficult is for an adversary to alter the block. The reason is that the time an adversary needs to alter a block grows \\textit{exponentially} in the number of blocks that have followed~\\cite{10.1007/978-3-662-46803-6_10} -- she will need to reproduced those blocks and the blockchain is constantly extended. Waiting 6 confirmation blocks to appear after the block in which the transaction is confirmed is enough for a transaction to be considered secure.\n\nA PoW system is based on \\textit{randomness}. Each node has a small change to win the block which is approximated proportionally to the computational power of each node. PoW depends on having a majority of the miners acting honestly out of self-interest~\\cite{antonopoulos2014mastering}.\n\nPoW consensus mechanism works very well in \\textit{public} blockchain systems where trust of the nodes is low. It eliminates the double-spend problem and guards against \\textit{Sybil attacks}~\\cite{sybil_attack}. However, the transaction confirmation time is longer compared to conventional financial services (such as VISA)~\\cite{Sompolinsky2015,Zohar:2015:BUH:2817191.2701411,DBLP:journals/corr/abs-1708-05665} resulting in slower transaction confirmation rates. Lastly, the energy waste attributed to the mining process can be very high -- the energy requirements of the Bitcoin protocol are estimated to be comparable to those of a small country~\\cite{6912770}.\n\n\\begin{lstlisting}[language=C, caption={A simple Proof-of-Work Algorithm}, mathescape=true]\n  x = rand();\n\n  do {\n    ++x;\n  } while (H(K||x) >= $\\epsilon$);\n\n  return x;\n\\end{lstlisting}\n\n\\subsection{Proof of Stake (PoS)}\\label{blockchain:consensus:pos}\n\nProof-of-Stake algorithms are designed to overcome the disadvantages of PoW in terms of the high electricity consumption involved in block generation~\\cite{bl_consensus}\nand provide equal security guarantees~\\cite{Kiayias2017}. Unlike PoW where the nodes of the network solve computational puzzles in order to create a new block, in PoS the choice\nof the block creator among the miners is random, yet relative to the \\textit{stake} the node possesses according to the current ledger. Maintaining the blockchain relies on the \\textit{stakeholders} themselves and assigns work to them based on the amount of stake that each possesses as reported in the ledger~\\cite{Kiayias2017}. The higher the stake participant, the higher the possibility to be chosen.\n\nProof-of-Stake algorithms suffer from the so-called ``\\textit{nothing at stake}'' problem. The ``nothing at stake'' problem refers to attacks against PoS blockchain systems where shareholders do not have \\textit{incentives} to follow the protocol and vote simultaneously on multiple blockchains exploiting the fact that little computational effort is needed to build a PoS blockchain~\\cite{Kiayias2017}. Blockchains with PoS as a consensus mechanism can be either \\textit{permissioned} or \\textit{permissionless} in the sense of stake availability rather than node authorization. A node to participate in block election has to possess a stake. If the market where the stake is available for sale is public and accessible for anyone then the blockchain is considered as truly permissionless. Otherwise, the initial stakeholders can sell stake selectively to participants of their choice making it permissioned. Ouroboros is the first \\textit{provable} secure PoS algorithm~\\cite{Kiayias2017} and is the main consensus algorithm of the Cardano blockchain~\\cite{cardano_site}.\n\n\\subsection{Practical Byzantine Fault Tolerance (PBFT)}\\label{blockchain:consensus:PBFT}\n\nThe \\textit{Practical Byzantine Fault Tolerance} algorithm (PBFT)~\\cite{Castro:1999:PBF:296806.296824} is a high-performance Byzantine Fault Tolerance~\\cite{byzantine_fault_tolerance} consensus mechanism. It is based on the concept of \\textit{state machine replication} and \\textit{replication state voting}, and is able to process tens of thousands of requests per second with minimal latency. PBFT has only a 3\\% overhead over a typical filesystem~\\cite{Castro:1999:PBF:296806.296824}.\n\nPBFT and state-machine replication protocols’ downside is poor \\textit{scalability}. The number of nodes (replicas)~\\cite{Vukolić2016} that can be supported is very limited. PBFT has only been scaled and studied up to 20 replicas~\\cite{bl_consensus,Vukolić2016}. To overcome this limitation, without compromising security, various PBFT variants, such as Ripple and Stellar, partition the network into smaller groups called federates and each one runs a local consensus protocol among its members. A global consensus is achieved when certain conditions are being met~\\cite{DBLP:journals/corr/abs-1708-05665}.\n\n\\begin{table}[!ht]\n  \\centering\n  \\caption{Blockchain consensus mechanisms. Adapted and modified from~\\cite{bl_consensus,Vukolić2016}}\n  \\begin{tabular}{|l|l|l|l|}\n    \\hline\n    & PoW &\tPoS &\tPBFT \\\\ \\hline\n    Blockchain Type &\tPermissionless &\tBoth &\tPermissioned \\\\ \\hline\n    Scalability of nodes &\tHigh &\tHigh &\tLow \\\\ \\hline\n    Scalability of clients &\tHigh &\tHigh &\tHigh \\\\ \\hline\n    Transaction rate &\tLow &\tHigh &\tHigh \\\\ \\hline\n    Latency &\tHigh &\tLow &\tMinimal \\\\ \\hline\n    Power consumption &\tHigh &\tLow &\tLow \\\\ \\hline\n    Token needed &\tYes &\tYes &\tNo \\\\ \\hline\n    Cost of participation &\tYes &\tYes &\tNo \\\\ \\hline\n  \\end{tabular}\n  \\label{table:blockchain_consensus}\n\\end{table}\n\n\\section{Mining \\& incentives}\\label{blockchain:mining}\n\nThe process of creating a block in a PoW consensus system is known as \\textit{mining} and the participants as \\textit{miners}. Miners contribute their computation resources to validate and generate blocks. This process can be costly. For that reason incentives motivates the miners of the network to mine blocks. In permissionless blockchains such as Bitcoin or Ethereum a monetary incentive in the form of cryptocurrency incentivize the miners while in permissioned blockchains incentives can be financial or acquiring access to valuable information~\\cite{deloitte}.\n\nIn Bitcoin a reward is given to the miner who its proposed block got into the blockchain. This happens through a specific type of transaction called \\textit{coinbase}. This type of transaction has an unconnected income edge without a sender and an outcoming edge with recipient the miner that produced the particular block. This is how new bitcoins are generated. The amount of coin mined in each block is pre agreed by the network and every four years is reduced by half. At the moment of writing, the reward is 12,5 BTC.\n\n\\begin{figure}[!ht]\n  \\centering\n  \\begin{tikzpicture}\n    \\node[tx] (A) at (0,0) {$tx$};\n    \\draw [->] (-3,0) -- (A) node[midway, below]{} node[midway, above]{12.5 BTC};\n    \\draw [->] (A) -- (3, 0) node[midway, below]{miner} node[midway, above]{12.5 BTC};\n  \\end{tikzpicture}\n  \\caption{Coinbase transaction}\n  \\label{fig:mining:coinbase}\n\\end{figure}\n\nAnother way a miner is rewarded is by collecting \\textit{transactions fees}. A transaction fee is the difference between the total value of all incoming edges and the total value of all outcoming edges. In particular, the total fees a miner collects by a block are defined as:\n\n\\begin{equation*}\n  fees = \\sum_{tx \\in block} [ \\sum_{i \\in in(tx) }w(i) -  \\sum_{o \\in out(tx) }w(o)]\n\\end{equation*}\n\n\\section{Blockchain fork}\\label{blockchain:fork}\n\nDue to network latency and the distributed nature of the system, it is possible that two miners will find a block around the same time and some nodes will accept the first block and some others the second one. Both blocks are valid, containing a valid proof of work, valid transactions and both extent the same parent block. In such cases there is a temporary \\textit{fork} in the blockchain, where some nodes are adding blocks to one branch while other nodes are adding blocks to another branch. As a result, two competitive versions of the blockchain will emerge~\\cite{antonopoulos2014mastering}. Similarly to transactions the order of the blocks cannot be decided.\n\nTo resolve this, each node always selects the longest brach to extent. At some point, one of the two branches will be extended by a new block. The nodes that were working on the first branch will see that the new branch is the longest and start working immediately on that. Eventually the system will come to an agreement, the longest branch will be accepted and other blocks will be discarded. The process of chain selection can be likened to voting where mining nodes ``\\textit{vote}'' with their mining power by choosing which chain to extend by mining the next block; the new block itself represents the voting result~\\cite{antonopoulos2014mastering}.\n\n\\begin{figure}[!ht]\n  \\centering\n  \\begin{tikzpicture}\n    \\foreach \\x in {0,1,...,5}\n        \\pgfmathparse{(\\x*2)}\n        \\edef\\position{\\pgfmathresult}\n        \\node[bl_block, minimum width=1cm, fill=blue!30] (\\x) at (\\position,0) {$block$};\n\n    \\foreach \\x in {1,2,...,5}\n        \\pgfmathparse{(\\x-1)}\n        \\edef\\previous{\\pgfmathresult}\n        \\draw [->] (\\x) -- (\\previous);\n\n    \\foreach \\x in {3,4}\n        \\pgfmathparse{(\\x*2)}\n        \\edef\\position{\\pgfmathresult}\n        \\node[bl_block, minimum width=1cm, fill=orange!30] (\\x_fork) at (\\position,2) {$block$};\n\n    \\draw [->] (4_fork) -- (3_fork);\n    \\draw [<-] (2.north) -- (3_fork.west);\n\n  \\end{tikzpicture}\n  \\caption{A blockchain fork}\n  \\label{fig:bl:fork}\n\\end{figure}\n\nIf a malicious adversary wants to double spent or execute a denial-of-service, she has to produce a malicious blockchain \\textit{longer} than the honest. To achieve that, an adversary would need to control the majority of the CPU power of the network and specifically more than 51\\% of the total network’s hashing power. This is called the \\textit{51\\% attack}. It is important to note that this kind of consensus attack affects at best the most recent blocks. Beyond a certain depth blockchain is absolute immutable. In addition, this type of attacks cannot steal or spend coins. The adversary cannot forge a signature to produce a valid transaction impersonating another user. Bitcoin's security has been formalized and rigorously explored~\\cite{10.1007/978-3-662-46803-6_10} over the last years.\n\n Ethereum is designed to produce blocks very fast (around 12-15 second) in comparison to Bitcoin (around 10 minutes). Blockchains with fast block confirmation times, suffer from reduced security due to high \\textit{stale rate}~\\cite{ethereum_whitepaper}. To counterpart that, Ethereum use a variant of the \\textit{GHOST} protocol~\\cite{Sompolinsky2015}. The GHOST protocol rule picks the chain that has had the \\textit{most computation} done upon it and not the chain with the longest depth.\n\n\\begin{figure}[ht!]\n  \\centering\n  \\begin{tikzpicture}\n    \\foreach \\x in {0,1,...,5}\n        \\pgfmathparse{(\\x*2)}\n        \\edef\\position{\\pgfmathresult}\n        \\node[bl_block, minimum width=1cm, fill=blue!30] (\\x) at (\\position,0) {};\n\n    \\foreach \\x in {1,2,...,5}\n        \\pgfmathparse{(\\x-1)}\n        \\edef\\previous{\\pgfmathresult}\n        \\draw [->] (\\x) -- (\\previous);\n\n    \\foreach \\x in {3,...,6}\n        \\pgfmathparse{(\\x*2)}\n        \\edef\\position{\\pgfmathresult}\n        \\node[bl_block, minimum width=1cm, fill=red!30] (\\x_mal) at (\\position,2) {};\n\n    \\draw [->] (4_mal) -- (3_mal);\n    \\draw [->] (5_mal) -- (4_mal);\n    \\draw [->] (6_mal) -- (5_mal);\n\n    \\draw [<-] (2.north) -- (3_mal.west);\n\n    \\node[circle, draw, minimum size=0.1cm, fill=red] at (4_mal.center) {};\n    \\node[circle, draw, minimum size=0.1cm, fill=green] at (3.center) {};\n\n    \\draw[decorate,decoration={brace,amplitude=10pt, mirror}, xshift=-1.2em, yshift=-1.5em](0, 0) -- (5, 0) node [black,midway,yshift=-1cm, above] {\\footnotesize{Honest common prefix}};\n\n    \\draw[decorate,decoration={brace,amplitude=10pt, mirror}, xshift=-1.2em, yshift=-1.5em](6, 0) -- (11, 0) node [black,midway,yshift=-1cm, above] {\\footnotesize{Honest blockchain}};\n\n    \\draw[decorate,decoration={brace,amplitude=10pt}, xshift=-1.2em, yshift=1.5em](6, 2) -- (13, 2) node [black,midway, above, yshift=1em] {\\footnotesize{Malicious blockchain}};\n\n  \\end{tikzpicture}\n  \\caption{Double spent attack}\n  \\label{fig:blockchain:dl_spent}\n\\end{figure}\n\n\\section{Blockchain Types}\\label{blockchain:blockchain_types}\n\nThere are various types of blockchains varying in restrictions on data access and participation in the consensus process. Each one has its own advantages and disadvantages.\n\n\\begin{itemize}\n  \\item \\textbf{Public Blockchain}: A public blockchain is a blockchain, in which there are no restrictions on reading blockchain data -- encrypted or not -- and validating transactions~\\cite{prbc_vs_pubbc}.\n  The most common implementation of public blockchain is Bitcoin~\\cite{nakamoto2012bitcoin} and Ethereum~\\cite{ethash}.\n  \\item \\textbf{Federated or Consortium blockchain}: In a federated blockchain transaction validation is limited to a predefined list of entities with known identities to the network. Data access can either be public or restricted~\\cite{prbc_vs_pubbc}.\n  \\item \\textbf{Private blockchain}: A private blockchain is a blockchain where consensus mechanism is centralized to one single entity regardless of data access~\\cite{prbc_vs_pubbc}.\n\\end{itemize}\n\n\\section{Consensus defined types of Blockchain}\\label{blockchain:consensus_blockchain_types}\n\n\\begin{itemize}\n  \\item \\textbf{Permissionless blockchain}: A permissionless blockchain is a blockchain, in which there are no restrictions on participation to the network~\\cite{prbc_vs_pubbc}.\n  \\item \\textbf{Permissioned blockchain}: A permissioned blockchain is a blockchain, in which transaction processing is performed by a predefined list of subjects with known identities~\\cite{prbc_vs_pubbc}.\n\\end{itemize}\n\n\\begin{table}[!ht]\n  \\centering\n  \\caption{Blockchain Types. Source~\\cite{hub-bl-types}}\n  \\begin{tabular}{|l|l|l|l|}\n    \\hline\n     & Public & \\makecell[cl]{Permissioned \\\\ (Multiple Entities)} & \\makecell[cl]{Private \\\\ (Single Entity)} \\\\ \\hline\n     Participants & \\makecell[cl]{Permissionless \\\\ Anonymous} & \\makecell[cl]{Permissioned \\\\ Identified \\\\ Trusted} & \\makecell[cl]{Permissioned \\\\ Identified \\\\ Trusted} \\\\ \\hline\n     Data Access & Public & Public or Restricted & Restricted \\\\ \\hline\n     Consensus & PoW, PoS & FBTA, PoS & FBTA \\\\ \\hline\n  \\end{tabular}\n  \\label{table:blockchain_types}\n\\end{table}\n\n\\section{Smart Contracts}\n\\label{smart_contracts}\n\nThe idea of \\textit{smart contracts} proposed in the early 1990s~\\cite{FM548}, by Nick Szabo. He defined them as a computer protocol intended to facilitate, verify, or enforce the negotiation or performance of a contract~\\cite{FM548,szabo1996smart}. They have been used primarily in association with cryptocurrencies enabling\nparties to formally specify a cryptographically enforceable agreements~\\cite{7163021}. A smart contract consists of a set of promises including protocols within which the parties perform on these promises. It can define rules and penalties around an agreement and automatically enforce those obligations. The contractual rules may be partially or fully self-executed, self-enforcing or both. Regarding blockchain a smart contract is any computer program that is executed on the blockchain -- a general purpose computation.\n\n\\subsection{Bitcoin scripts}\n\\label{smart_contracts:bitcoin}\n\nBitcoin is the first blockchain that implements smart contract functionality. It provides a \\textit{scripting} language for expressing simple smart contracts such as ownership of an amount of coins by one or multiple entities. Bitcoin's language is a \\textit{stack-based} scripting language inspired by Forth~\\cite{forth_lang}. It offers a set of simple \\textit{serial commands} supporting cryptographic primitives such as hash functions and signature verification. The main disadvantage of Bitcoin's language is that is not \\textit{Turing-complete} limiting the type of smart contracts one can create. Furthermore, adding new commands to extent functionality requires either a soft-fork which implements the new functionality or the creation of a blockchain anew. A soft fork has to be decided by the majority of Bitcoin's network. There is no guarantee that the nework will adopt the new change. On the other hand, the implementation of a new blockchain has the disadvantage that Bitcoin's mining power is lost. Numerous previous smart contract application atop Bitcoin (e.g., lottery\\cite{Andrychowicz:2014:SMC:2650286.2650764,10.1007/978-3-662-44381-1_24}, verifiable computation~\\cite{Kumaresan:2014:UBI:2660267.2660380}) have demonstrated the difficulty of Bitcoin's scripting language~\\cite{cryptoeprint:2015:675}.\n\nIn~\\ref{blockchain:structure:tx}, a transaction is defined as a graph node with two edges, one incoming and one outcoming and each edge contains an address. In reality, each edge contains a program which decides whether the edge can be spent or not. The program is written in Bitcoin's scripting language and is called \\verb|scriptPubKey|. This allows the expression of more complicated ownership of assets such as \\textit{multi-signatures} or \\textit{micropayments}. The script is executed on a stack machine and containes a series of simple serial commands. When a UTXO is spent, every node of the network executes the \\textit{script}. If the output of the program is $1$, then the transaction is valid and can be spent. Otherwise, the transaction is considered invalid.\n\n\\begin{figure}[!ht]\n  \\centering\n  \\begin{tikzpicture}\n    \\node[tx] (A) at (0,0) {$tx$};\n    \\draw [->] ++(-8,0) -- (A) node[above, midway]{5mBTC} node[left, below,  align=left, font=\\footnotesize, xshift=-4.5cm]{\n      OP\\_DUP \\\\\n      OP\\_HASH160 \\\\\n      1FdtUtvK5vZxwo8jzjzid5EwGAB7paqX4n \\\\\n      OP\\_EQUALVERIFY \\\\\n      OP\\_CHECKSIG\n    };\n    \\draw [->] (A) -- (8, 0) node[midway, above]{5mBTC} node[midway, below, align=left, font=\\footnotesize, xshift=0.2cm]{\n      OP\\_DUP \\\\\n      OP\\_HASH160 \\\\\n      128MZKqUsvg2kYJQ5LCVDx8Mdn8xrijzQY \\\\\n      OP\\_EQUALVERIFY \\\\\n      OP\\_CHECKSIG};\n  \\end{tikzpicture}\n  \\caption{A Bitcoin script}\n  \\label{fig:bl_tx:script}\n\\end{figure}\n\n\\subsection{Ethereum smart contracts}\n\\label{smart_contracts:ethereum}\n\nThe need of user defined open source blockchain applications have been emerged. As a result, \\textit{Ethereum}~\\cite{ethereum_yellowpaper, ethereum_whitepaper} was born. Ethereum is an open-source, public, blockchain-based distributed computing platform and a smart contract framework that enables anyone to build \\textit{distributed applications}. It provides a decentralized Turing-complete virtual machine, the \\textit{Ethereum Virtual Machine} (EVM) in which smart contracts are executed by all nodes of the network. In Ethereum, one can create smart contracts in a high level language, such as \\textit{Solidity}~\\cite{solidity}, which in turn is compiled to \\textit{bytecode} that is executable on the EVM. Ethereum provides a cryptocurrency called \\textit{Ether} which can be transferred between accounts, and \\textit{gas}, an internal pricing mechanism used to execute contracts and allocate resources on the network. Like Bitcoin, Ethereum use a Proof-of-Work consensus mechanism called \\textit{Ethash} and has been designed to be \\textit{ASIC-resistant}~\\cite{ethash}. Soon Ethereum will be moved to a Proof-of-Stake consensus mechanism called \\textit{Casper}.\n\nWith Ethereum launch, the notion of \\textit{DApps} (decentralized applications) arisen\nand a lot of developers and companies are building numerous applications atop Ethereum such as prediction markets~\\cite{augur,gnosis}, social media platforms~\\cite{akasha,backfeed},\nonline gambling~\\cite{etheroll,coinpoker} and video games~\\cite{cryptokitties}. As of January 2018, there are more than 250 live DApps.\n\nBefore describing how smart contracts are deployed in Ethereum, a thorough analysis of Ethereum's core mechanisms must be made. Ethereum constitute of a set of one global object, that of \\textit{account}. Each account has a \\textit{state}, in which the nodes of the network must agree upon with the use of a consensus mechanism. A 20-byte address is associated for each account. The state of an account can only be changed by a transaction. The global state of Ethereum is made up of accounts. For that reason, Ethereum is often described as a \\textit{state machine}~\\cite{ethereum_whitepaper} where the \\textit{state transition function} takes as input a transaction and outputs a different state.\n\nEach account is composed by the following fields: \\textit{address}, \\textit{balance}, and \\textit{nonce}. The address is a 160-bit account identifier derived from a public key. The balance contains the total amount the account holds in \\textit{Wei}; the smallest denomination of ether. Ethereum instead of using UTXOs to keep track of coin ownership, adopted the traditional notion of balances as in financial systems. The choice of balances over UTXOs was a design decision by the Ethereum foundation. Each option has its advantages and disadvantage. According to Ethereum founders, the advantages of accounts massively outweigh the alternatives~\\cite{eth_design}. The nonce is the total number of transactions sent from the account. The nonce is used as a \\textit{replay-attack} prevention mechanism. In the absence of nonce, a malicious adversary may send the same transaction twice and amount of the transaction will be deducted twice from the user's balance.\n\nSimilar to Bitcoin, anyone can send ethers from one account to another. The principles of the transaction described in~\\ref{blockchain:structure:tx} are also applicable to Ethereum. Each transaction consist of the following fields: \\textit{from}, \\textit{signature}, to, and \\textit{amount}. The from and to fields describe the sender and the receiver respectively. The signature field contains the valid signature of the transaction where the nodes of the network verify. Lastly, the amount contains the amount to be sent in Wei.\n\nThere are two type of accounts: \\textit{personal} (or external own accounts) and \\textit{contract} accounts. A contact account is an account dedicated for smart contracts. They contain two extra fields: \\textit{code} and \\textit{storage}. The code field contains the code of the smart contract and the storage field the internal persistent storage of the smart contract. Those fields are empty, and optional, when it comes to personal accounts.\n\n\\begin{figure}[!ht]\n  \\centering\n  \\begin{tikzpicture}[x=2cm, y=-1cm, node distance=0 cm,outer sep = 0pt]\n    \\node[account_block, fill=orange!30] (address) {$address$};\n    \\node[account_block, right=of address, fill=magenta!30] (code) {$code$};\n    \\node[account_block, right=of code, fill=purple!30] (storage) {$storage$};\n    \\node[account_block, right=of storage, fill=blue!30] (balance) {$balance$};\n    \\node[account_block, right=of balance, fill=green!30] (nonce) {$nonce$};\n  \\end{tikzpicture}\n  \\caption{An Ethereum account}\n  \\label{fig:eth_account}\n\\end{figure}\n\nTransactions contain an extra field, called \\textit{data} field. To create a contact, a user has to sent a transaction with empty recipient and data field the code of the smart contract. When the nodes of the network hear a transaction, where the field of the recipient is empty, they treat the transaction as a smart contract creation transaction. They create a contract account with code, the string that is contained in the data field of the transaction, and empty storage. After the creation of the contract account an address is returned to the creator of the contract. The address is created from the concatenation of the creator's public key and her account current nonce. Anyone knowing the address of the contract can interact with it. In particular, to call a smart contract function, the interested party has to send a transaction with recipient the smart contract's address and data the function's name along with its arguments.\n\n\\begin{table}[!ht]\n  \\centering\n  \\caption{Ethereum accounts}\n  \\begin{tabular}{|c|c|c|}\n  \\hline\n   & Personal account  & Contract account \\\\ \\hline\n   address & $H(p_k)$ & $H(creator, nonce)$ \\\\ \\hline\n   code & $\\emptyset$ & Code to be executed \\\\ \\hline\n   storage & $\\emptyset$ & Data of the contract \\\\ \\hline\n   balance & \\multicolumn{2}{c|}{ETH} \\\\ \\hline\n   nonce &  \\multicolumn{2}{c|}{\\# transaction sent}  \\\\ \\hline\n  \\end{tabular}\n  \\label{fig:eth_accounts}\n\\end{table}\n\nWhen a contract account is activated the contract's code runs. The contract can read or write to internal storage, do various computations, send messages or create new contracts. A contract account can not initiate new transactions on its own but only in response to a transaction initiated by a personal account -- only personal accounts can change the state of the accounts.\n\nContract accounts can send \\textit{messages} to other contracts accounts. Messages are like transactions except it is produced by a contract and exist only in the Ethereum's execution environment. The network never sees the messages neither are stored in the blockchain. This way, contracts can have relationships with other contracts.\n\n\\begin{table}[!ht]\n  \\centering\n  \\caption{Ethereum transactions}\n  \\begin{tabular}{|c|c|c|c|}\n  \\hline\n   & create & send & call \\\\ \\hline\n   from & creator & sender & caller \\\\ \\hline\n   signature & $\\sigma$ & $\\sigma$ & $\\sigma$ \\\\ \\hline\n   to & $\\emptyset$ & receiver & contract \\\\ \\hline\n   amount & \\multicolumn{3}{c|}{ETH} \\\\ \\hline\n   data & code & $\\emptyset$ & $f, args$ \\\\ \\hline\n  \\end{tabular}\n  \\label{fig:eth_transactions}\n\\end{table}\n\n\\begin{figure}[!ht]\n  \\centering\n  \\begin{tikzpicture}[scale=0.5, node distance=2.5 cm,outer sep = 0pt]\n    \\node[node, fill=blue!30] (pr_1) {Personal Account};\n    \\node[node, fill=blue!30, below=of pr_1] (pr_2) {Personal Account};\n    \\node[node, fill=orange!30, right=of pr_1] (c_1) {Contract Account};\n    \\node[node, fill=orange!30, below=of c_1] (c_2) {Contract Account};\n    \\node[node, fill=orange!30, right=of c_2] (c_3) {Contract Account};\n\n      \\draw [->] (pr_1) -- (c_1);\n      \\draw [->] (pr_2) -- (c_2);\n      \\draw [->] (c_1) -- (c_2);\n      \\draw [->] (c_2) -- (c_3);\n  \\end{tikzpicture}\n  \\caption{Transactions \\& messages}\n  \\label{fig:eth_transaction}\n\\end{figure}\n\nThe code of a smart contract is run by all nodes of the network. The code can change the state of the contract or the state of another contract or personal account. The nodes must agree on a global common state, the state of each account. Similar to Bitcoin, the transactions, that change the state of each account, are contained in a block. A proof-of-work consensus mechanism is used by the network to agree upon the block that will extent the blockchain. The new block contains the new state of all accounts.\n\nAll nodes evaluate all transactions, execute code and store all state. Because Ethereum is turing-complete, infinite loops or computational heavy code could make all the nodes of the system to be occupied for a very long period of time, or even infinitely. Furthermore, storage requirements can be grown very fast making unable to fulfil and maintain that demand. To address this issues, Ethreuem use a unit called \\textit{gas} as a measurement of computation usage. It acts as an anti-denial of service mechanism. The intent of gas, is to enforce a malicious adversary to pay proportionately for every resource that consumes, including computation, bandwidth and storage~\\cite{ethereum_whitepaper}.\n\nEach gas unit has a gas price that is expressed in \\textit{gwei} ($1 \\times 10^9$ Wei). Every node in the Ethereum network executes instructions (\\textit{opcodes}), that represent the code of the contract, within the Ethereum Virtual Machine (EVM). Each of these instructions has an associated cost in gas. The cumulative sum of all the operations is the total gas cost for a transaction and is the fee that is being paid to the miners.\n\nThe cost of each opcode (operation code) of EVM is defined in Ethereum's yellow paper~\\cite{ethereum_yellowpaper} and a gas cost summarization of basic opcodes are be shown in Table~\\ref{table:opcode_gas_cost}. For storing data, Ethereum offers two opcodes: the \\textit{SLOAD} opcode which loads a word from the storage and the \\textit{SSTORE} opcode which saves a word to storage. The size of an EVM word is 32 bytes (256 bit) and to store one EVM word using the SSTORE opcode costs 20.000 gas. Due to that reasons, storing data is expensive and for the moment blockchain technologies cannot be used for data storage or data processing.\n\n\\begin{table}[!ht]\n  \\centering\n  \\caption{Ethereum opcodes gas costs}\n  \\begin{tabular}{|l|l|l|}\n  \\hline\n   Operation & Gas  & Description \\\\ \\hline\n   ADD/SUB & 3 & Arithmetic operation \\\\ \\hline\n   MUL/DIV & 5 & Arithmetic operation \\\\ \\hline\n   ADDMOD/MULMOD & 8 & Arithmetic operation \\\\ \\hline\n   AND/OR/XOR & 3 & Bitwise logic operation \\\\ \\hline\n   LT/GT/SLT/SGT/EQ & 3 & Comparison operation \\\\ \\hline\n   POP & 2 & Stack operation \\\\ \\hline\n   PUSH/DUP/SWAP & 3 & Stack operation \\\\ \\hline\n   MLOAD/MSTORE & 3 & Memory operation \\\\ \\hline\n   JUMP & 8 & Unconditional jump \\\\ \\hline\n   JUMPI & 10 & Conditional jump \\\\ \\hline\n   SLOAD & 200 & Storage operation \\\\ \\hline\n   SSTORE & 5.000 / 20.000 & Storage operation \\\\ \\hline\n   BALANCE & 400 & Get balance of an account \\\\ \\hline\n   CREATE & 32.000 & Create a new account using CREATE \\\\ \\hline\n   CALL & 25.000 & Create a new account using CALL \\\\ \\hline\n   LOG & 375 & Logging operation \\\\ \\hline\n  \\end{tabular}\n  \\label{table:opcode_gas_cost}\n\\end{table}\n\nAn Ethereum transaction has two extra fields: the \\textit{start gas} and \\textit{gas price}. The start gas is the maximum amount of gas willing to pay and the gas price is the price willing to pay per gas unit. The start gas (or gas limit) acts as a protection to computational wastage or malicious code. Even if the code needs more gas to terminate, when the gas limit is reached the execution is stoped and all state changes are revert. An extra benefit of gas limit is, that a miner seeing the gas limit field can estimate the needed computational time beforehand and act accordingly. The gas price is not defined by any central trusted authority but is regulated by the network itself. By setting the gas price, the user in a sense ``votes'' for the value of the gas. Gas price determines how quickly a transaction will be mined; the higher the price is, the more likely is the transaction to be in the next block.\n\n\\begin{figure}[!ht]\n  \\centering\n  \\begin{tikzpicture}[x=2cm, y=-1cm, node distance=0 cm,outer sep = 0pt]\n    \\node[account_block, fill=orange!30] (from) {$from$};\n    \\node[account_block, right=of from, fill=magenta!30] (signature) {$signature$};\n    \\node[account_block, right=of signature, fill=purple!30] (to) {$to$};\n    \\node[account_block, right=of to, fill=blue!30] (amount) {$amount$};\n    \\node[account_block, right=of amount, fill=green!30] (data) {$data$};\n    \\node[account_block, right=of data, fill=yellow!30] (startgas) {$startgas$};\n    \\node[account_block, right=of startgas, fill=blue!30] (gasprice) {$gasprice$};\n  \\end{tikzpicture}\n  \\caption{An Ethereum transaction}\n  \\label{fig:eth_transaction}\n\\end{figure}\n\nThe start gas can be larger than the cost of the computation. In this case, all unused gas is refunded at the end of the transaction to the sender. If the computation exceed the gas limit then a \\textit{out of gas exception} is triggered and the state is reverted to the previous one. Out of gas exceptions are not refundable. The miner still claims the fee for each computational step performed.\n\n\\begin{figure}[!ht]\n  \\begin{tikzpicture}[node distance=2.5cm]\n    \\node[execution_entity, label=below:{\\footnotesize{250}}] (sender) at (0, 0) {Sender};\n    \\node[execution_process, right =of sender] (start) {Start \\\\ Transaction};\n    \\node[execution_operation, right =of start, label=below:{\\footnotesize{200}}] (op_1) {Operation};\n    \\node[execution_operation, right =of op_1, label=below:{\\footnotesize{170}}] (op_2) {Operation};\n    \\node[execution_process, below =of start, label=below:{\\footnotesize{170}}] (end) {End \\\\ Transaction};\n    \\node[execution_entity, right =of end] (receiver) {Receiver};\n\n    \\node[execution_label, below=of end] (rem_gas) {Remaing \\\\ gas};\n    \\node[execution_label, below=of sender] (str_gas) {Start \\\\ gas};\n\n    \\draw[->] (sender) -- (start);\n    \\draw[->] (start) -- (op_1) node[midway, above, red]{\\footnotesize{Use -50 gas}};\n    \\draw[->] (op_1) -- (op_2) node[midway, above, red]{\\footnotesize{Use -30 gas}};\n    \\draw[->] (op_2.east) -- ++(0.5, 0) -- ++(0, -1.5) -- ++(-11.4, 0) -- (end.north);\n    \\draw[->] (end) -- (receiver);\n\n    \\draw[->] ([yshift=-0.55cm]end.south) -- (rem_gas);\n    \\draw[->] (rem_gas.west) -- ++(-4.2, 0) -- (str_gas);\n\n    \\draw[<-] ([yshift=-0.55cm]sender.south) -- (str_gas);\n  \\end{tikzpicture}\n  \\caption{Smart contract execution}\n  \\label{fig:smart_contract_execution}\n\\end{figure}\n\n\\begin{figure}[!ht]\n  \\begin{tikzpicture}[node distance=2.5cm]\n    \\node[execution_entity, label=below:{\\footnotesize{250}}] (sender) at (0, 0) {Sender};\n    \\node[execution_process, right =of sender] (start) {Start \\\\ Transaction};\n    \\node[execution_operation, right =of start, label=below:{\\footnotesize{200}}] (op_1) {Operation};\n    \\node[execution_operation, right =of op_1, label=below:{\\footnotesize{170}}] (op_2) {Operation};\n\n    \\node[execution_operation, below =of op_2, label=below:{\\footnotesize{0}}] (op_3) {Operation};\n    \\node[execution_operation, left =of op_3, label=below:{\\footnotesize{0}}] (op_4) {Operation};\n\n    \\node[execution_entity, below =of op_3] (receiver) {Receiver};\n\n    \\node[execution_label, below=of sender] (str_gas) {Start \\\\ gas};\n\n    \\draw[->] (sender) -- (start);\n    \\draw[->] (start) -- (op_1) node[midway, above, red]{\\footnotesize{Use -50 gas}};\n    \\draw[->] (op_1) -- (op_2) node[midway, above, red]{\\footnotesize{Use -30 gas}};\n    \\draw[->] ([yshift=-0.55cm]op_2.south) -- (op_3) node[midway, left, red]{\\footnotesize{Use -170 gas}};\n    \\draw[->] (op_3) -- (op_4) node[midway, above, red]{\\footnotesize{Out of gas}};\n\n    \\draw[red!100, thick] ([yshift=1cm]sender |- receiver.north) -- ([yshift=1cm]receiver.north) node[midway, below, red]{\\footnotesize{Revert state}};\n\n    \\draw[<-] ([yshift=-0.55cm]sender.south) -- (str_gas);\n  \\end{tikzpicture}\n  \\caption{Out of gas exception}\n  \\label{fig:smart_contract_out_of_gas}\n\\end{figure}\n\nEach miner at code execution perform the following steps:\n\n\\begin{enumerate}\n  \\item If $start\\_gas * gas\\_price > balance$ then halt\n  \\item Deduct $start\\_gas * gas\\_price$ from $balance$\n  \\item Set $gas = start\\_gas$\n  \\item Run code deducting from gas\n  \\item After termination return remaining $gas$ to $balance$\n\\end{enumerate}\n\nThe total gas cost of the transaction is paid to miner that mined the block. The \\textit{maximum fee} a miner could take by a transaction is calculated as:\n\n\\begin{equation*}\n  fee_{max} = startgas \\times gasprice\n\\end{equation*}\n\nFor example if the start gas is set to $50.000$ and the gas price to $20$ Gwei the maximum fee is $0.001$ ETH.\n\nAs discussed earlier, the code of the contract is executed within the Ethereum Virtual Machine (EVM). EVM is a stack-based machine and uses 32-bytes (256-bit) words. It reads a series of bytecode instructions (EVM code) where each bytecode represents an operation (opcode). Lastly, it provides various built-in cryptographic primitives.\n\n\\begin{lstlisting}[language=Solidity, caption={EVM bytecode}]\nPUSH1 0\nCALLDATALOAD\nSLOAD\nNOT\nPUSH1 9\nJUMPI\nSTOP\nJUMPDEST\nPUSH1 32\nCALLDATALOAD\nPUSH1 0\nCALLDATALOAD\nSSTORE\n\\end{lstlisting}\n\nWriting smart contract on bytecode can be challenging. For that reason, various high level programming language that compile to EVM code have been implemented. The most wide used is Solidity~\\cite{solidity}. From the perspective of a developer, Solidity is much alike to JavaScript as it supports most of its structures. Every contact have to be declared with the keyword \\verb|contract| at the begging of the file. It is the same as declaring a class or an object in object-oriented programming languages.\n\nSolidity supports two types of variables: \\textit{state} variables and \\textit{local} variables. State variables are contract variables that are permanently stored in contract storage and have to be declared at compilation time. Local variables are function variables that cannot be accessed outside the scope of the function and they can be stored either in storage or in memory.\n\nSolidity supports the following variable value types:\n\n\\begin{itemize}\n  \\item Boolean: true of false.\n  \\item Integers: Signed and unsigned integers of various sizes. Keywords \\verb|uint8| to \\verb|uint256| in steps of  8 (unsigned of 8 up to 256 bits) and \\verb|int8| to  \\verb|int256|.\n  \\item Fixed-size byte arrays: \\verb|bytes1| to  \\verb|bytes32| in steps of one.\n  \\item Dynamically-sized byte array: \\verb|bytes| or \\verb|string|.\n  \\item Address: 20-byte value holding an Ethereum address.\n  \\item Enum: Enumerated type.\n  \\item Mapping: A key-map type similar to hash tables. \\verb|mapping(keyType => valueType)|.\n  \\item Structs: A structure. It can be used to define new types.\n  \\item Function: Variables that hold a function reference.\n\\end{itemize}\n\nEVM supports a built-in logging mechanism which can be used by smart contracts to notify for various events. Services outside the blockchain can register listeners to this events and act accordingly. In solidity, an event is declared by the \\verb|event| keyword along with its arguments.\n\nLastly, Solidity supports multiple inheritance including abstract class and interfaces. Contracts can extend another contract with the keyword \\verb|is| and access internal functions and non-private members.\n\nSince smart contracts deal directly with currency exchange, security of smart contract is of the utmost importance~\\cite{safe_smart_contracts, smart_contracts_smarter}. The DAO bug~\\cite{dao, dao_2} is a perfect example. At least 60 millions US dollars was lost leading to a hard fork in Ethereum and the creation of Ethereum Classic.\n\nIn contrast to traditional application that can be patched when bugs are detect, smart contracts, due to the nature of blockchain, are irreversible and immutable. Various analysis~\\cite{safe_smart_contracts, smart_contracts_smarter} have shown that most of the deployed smart contracts on Ethereum are vulnerable. In particular, an analysis tool called \\verb|Oyente|~\\cite{smart_contracts_smarter}, created by Loi Luu et. al, marked 8,833 out of 19,336 smart contracts as vulnerable. Is believed that these bugs arise from the gap in understanding the actual mechanisms of the underlying platform of Ethereum~\\cite{smart_contracts_smarter}; developers make false assumptions of the semantics of the system.\n\n\\subsection{Cardano}\\label{blockchain:impl:cardano}\n\nAnother platform for smart contract implementation is Cardano. Cardano is a security focused blockchain that utilize the latest research and engineering insights to build a platform suitable for the highest value applications~\\cite{cardano_site}. It supports distributed applications creation and smart contracts verifiable by a method called formal verification allowing logical proof of correctness of code providing high security. Cardano addresses the need for regulatory oversight while maintaining consumer privacy and security. Cardano is the first blockchain project to be peer reviewed by academic researchers~\\cite{cardano_site} and its consensus mechanism, \\textit{Ouroboros}, is the first Proof of Stake algorithm to be provably secure~\\cite{Kiayias2017}. Cardano consists of two main layers, one for accounting and one for computation. The accounting layer is called \\textit{Cardano Settlement Layer} (CSL)\nand the computation layer \\textit{Cardano Computation Layer} (CCP) where distributed application can be built and run upon. The CCP layer has not been implemented yet and there is a plan to be released as a beta by the first quarter of 2018~\\cite{cardano_parsons}.\n\n\\clearpage\n\n\\begin{lstlisting}[language=Solidity, caption={An Ethereum Smart Contract}]\npragma solidity ^0.4.16;\n\ncontract Namespace{\n\n  struct NameEntry {\n      address owner;\n  }\n\n  uint32 constant REGISTRATION_COST = 100;\n  uint32 constant UPDATE_COST = 10;\n  mapping(bytes32 => NameEntry) data;\n\n  function nameNew(bytes32 hash){\n      if (msg.value >= REGISTRATION_COST){\n          data[hash].owner = msg.sender;\n      }\n  }\n\n  function nameUpdate(bytes32 name, bytes32 newValue, address newOwner){\n      bytes32 hash = sha3(name);\n      if (data[hash].owner == msg.sender && msg.value >= UPDATE_COST) {\n          data[hash].value = newValue;\n          if(newOwner != 0) {\n              data[hash].owner = newOwner;\n          }\n      }\n  }\n\n  function nameLookup (bytes32 name) {\n      return data[sha3(name)]\n  }\n}\n\\end{lstlisting}\n\n\\clearpage\n", "meta": {"hexsha": "b2c02caeb7cf2162b1180e3567fcc8a7a0558bf1", "size": 74564, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/blockchain.tex", "max_stars_repo_name": "cnasikas/thesis", "max_stars_repo_head_hexsha": "e5bfd9d293fb7b8024863e389c9a2bc1f5d53509", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-06-21T17:44:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-21T17:44:21.000Z", "max_issues_repo_path": "chapters/blockchain.tex", "max_issues_repo_name": "cnasikas/thesis", "max_issues_repo_head_hexsha": "e5bfd9d293fb7b8024863e389c9a2bc1f5d53509", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/blockchain.tex", "max_forks_repo_name": "cnasikas/thesis", "max_forks_repo_head_hexsha": "e5bfd9d293fb7b8024863e389c9a2bc1f5d53509", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 82.2094818082, "max_line_length": 1321, "alphanum_fraction": 0.7436698675, "num_tokens": 20206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.615087862571909, "lm_q1q2_score": 0.31475067263003953}}
{"text": "\\documentclass[11pt,oneside]{article}\n\\usepackage{amsmath}\n\\usepackage{pdfpages}\n\\usepackage{appendix}\n\\usepackage{natbib}\n% \\usepackage{amssymb}\n\\usepackage{makeidx}\n\\usepackage{graphicx}\n\\usepackage{epstopdf}\n\\usepackage{float}\n\\usepackage{mdwlist}\n\\usepackage{bm}\n\\usepackage{fullpage}\n\n\\begin{document}\n\\title{Exploring non-linear inversions: a 1D magnetotelluric example}\n\\author{Seogi Kang, Lindsey Heagy, Rowan Cockett, and Douglas Oldenburg}\n\n\\maketitle\n\nAt some point in many geophysical workflows, an inversion is a necessary step for answering the geoscientific question at hand: whether it is recovering a reflectivity series from a seismic trace in a deconvolution problem, finding a susceptibility model from magnetic data or recovering conductivity from an electromagnetic survey. This is particularly true when working with data sets where it may not even be clear how to plot the data: 3D direct current resistivity and induced polarization surveys (it is not necessarily clear how to organize data into a pseudosection) or multi-component data, such as electromagnetic data (we can measure three spatial components of electric and/or magnetic fields through time over a range of frequencies). Inversion is a tool for translating these data into a model we can interpret. The goal of the inversion is to find a ``model'', some description of the earth’s physical properties, that is consistent with those data and geologic knowledge.\n\nIn spite the wide applicability of inverse problems, inversions are often used (and provided) as black-boxes: data goes in, some number crunching happens, your computer fan starts working pretty hard, and at some point a list of numbers (the model) comes out the other side. In such a paradigm, it is often unclear how to set expectations of what information we should be able to extract from our data through inversion, and difficult to gauge how to use all of the knobs appropriately (trade-off parameters, stopping criteria, noise model, choice of regularization functional, mesh generation, etc.).\n\nA number of authors have published tutorials and papers that open up the black box and discuss the numerical gears that make an inversion machine run as well as the knobs that tune it. \\cite{OldenburgTutorial} provides a comprehensive tutorial on inversion; many of the topics we will discuss are presented in much more detail in their tutorial. The implementation of the physics simulations, optimization, and structure necessary to perform an inversion can be overwhelming to implement and organize from scratch; in \\citep{SimPEGPaper}, we introduce a general simulation and inversion framework and a set of tools (in Python!) to hopefully make this easier.\n\nThe style of the Leading Edge tutorials ups the ante, as we can provide code that brings examples to life so that not only can you see images produced by someone else, you can play with the knobs yourself. Matt Hall kicked off the discussion of inversions in the Leading Edge in his \\emph{Linear Inversion} tutorial \\citep{HallTutorial}. He walked through how to solve the classic linear inverse problem $\\mathbf{G}\\mathbf{m} = \\mathbf{d}$, where $\\mathbf{G}$ is our forward operator (the mathematical description of the physics/problem), $\\mathbf{d}$ is our data, and $\\mathbf{m}$ is what we are after: our ``model'' of the earth. The example he demonstrated is a deconvolution problem, in that case, $\\mathbf{G}$ is a convolution matrix, $\\mathbf{m}$ is the reflectivity series and $\\mathbf{d}$ is a seismic trace. He introduced the concepts of an underdetermined problem, motivated the need for regularization, formulated the inversion in terms of an optimization problem and solved the linear inverse problem (in true polyglot fashion, using Python, Lua, Julia, and R!).\n\n\\section{Magnetotellurics}\nIn this tutorial, we will pick up from there and explore a nonlinear forward problem, of the form $\\mathcal{F}[\\mathbf{m}] = \\mathbf{d}$. Here, we choose $\\mathcal{F}[\\mathbf{m}]$ to be the 1D magnetotelluric (MT) forward simulation. The MT problem is a natural source electromagnetic method; plane-wave source-fields are generated by solar wind (giving us low frequency signals $<$ 1 Hz) and lightning strikes worldwide (giving us higher frequency signals $>$ 1 Hz). In magnetotellurics, the model, $\\mathbf{m}$, is a description of the earth’s electrical conductivity and $\\mathcal{F}[\\mathbf{m}]$ solves Maxwell’s equations for a plane wave source:\n\\begin{equation}\n\\begin{split}\n\\nabla \\times \\vec{E} + i\\omega\\mu\\vec{H} &= 0 \\\\\n\\nabla \\times \\vec{H} + \\sigma\\vec{E} &= 0\n\\end{split}\n\\label{eq:maxwell}\n\\end{equation}\nThe plane wave source is incorporated in the modelling through a boundary condition. The data, $\\mathbf{d}$, are impedances; for the 1D problem, the impedance at a single frequency is given by\n\\begin{equation}\nZ_{xy} = -\\frac{E_x}{H_y}.\n\\label{eq:impedance}\n\\end{equation}\nNote that the impedance is a complex number. When we work with the data in the inversion, it is convenient to work only with real numbers, so at each frequency we define 2 data points: $\\text{Re}(Z_{xy})$ and $\\text{Im}(Z_{xy})$, thus the total number of data for the 1D simulations we will consider are $2 \\times N_{\\text{frequencies}}$. Impedance is a non-intuitive quantity; often, we instead consider apparent resistivity\\footnote{Note that resistivity is the inverse of conductivity $\\rho = 1/\\sigma$} and phase, given by\n\\begin{equation}\n\\rho_a = \\frac{1}{\\mu_0\\omega} \\big|Z_{xy}\\big|^2,\n\\quad\n\\phi = \\tan^{-1}\\left(\\frac{\\text{Im}(Z_{xy})}{\\text{Re}(Z_{xy})}\\right).\n\\label{eq:rhoa_phase}\n\\end{equation}\nFor an earth that is a half-space, the apparent resistivity equals the true resistivity, and the phase is $45^{\\circ}$. The ability to compute the complex impedance or apparent resistivity and phase solves the forward problem.\n\nThe inversion aims to solve $\\mathcal{F}^{-1}[\\mathbf{d}]$ for a model. Just as in the linear problem, we are dealing with an ill-posed inverse problem\\footnote{Ill posed problems are problems that are not well-posed. For a well-posed problem, a solution exists, the solution is unique and the solution depends continuously on the input.}, thus, regularization is required in order to select a model from the infinitely many that can fit the data. Before we tackle the inverse problem, let's explore an example of nonuniqueness: how can different models give us the same data?\n\n\\section{Go forwards}\nPrior to any inversion, we require the ability to accurately simulate predicted data. In a few specific cases, this can be accomplished by analytically solving a set of equations with the specified boundary conditions, but in general, we must discretize the equations of interest (here, Maxwell’s equations) and solve the partial differential equations. In the first notebook, we walk through a finite difference approach for solving the 1D MT problem. Rather than going into those details in this write up, we will let you explore the notebook, and if you are looking for more, we wrote a tutorial on finite volume methods \\citep{Cockett2016}! Here, we take for granted that we have designed an appropriate mesh\\footnote{The mesh must extend far enough so that the lowest frequency electromagnetic fields have decayed sufficiently by the time they reach it, and the finest cells must be small enough as to capture the behaviour of the highest frequencies. See the second notebook for more discussion.}, can solve Maxwell’s equations, and will use forward modelling as a tool for setting expectations on what we can hope to recover from our data. In particular, let’s examine an example of nonuniqueness.\n\nA classic example that demonstrates non-uniqueness of MT data is the equivalence of the   conductivity-thickness product (conductance) of a thin layer. If we start with a layer that has a conductivity of $\\sigma$, halve its thickness and double its conductivity, the resulting data will be similar. In Figure \\ref{fig:sigmat}, we show apparent resistivity and phase data for five models, each of which has the same conductance. In all of the simulations, the data shows a decrease in apparent resistivity and an increase in phase starting at $\\sim$10Hz. Thus in all of the data we have evidence of a conductive layer, and the frequency range at which it appears is an indicator of the depth of the layer (you can explore by changing the \\texttt{depth} variable in the model setup of the second notebook). However, all scenarios produce similar data, and in the second interactive notebook, you can explore what happens if you add noise. Even with a small amount of noise, we cannot expect an inversion code to separate the conductivity and thickness of a conductive unit without incorporating additional information. When setting up the inverse problem and defining regularization (next up!), it is important to realize that the choices we make there will influence the character of the model we recover, as the data alone do not provide us with a unique model.\n\n\\begin{figure}[htb!]\n    \\centering\n    \\includegraphics[width=\\textwidth]{../images/sigmat_old.png}\n\\caption{Magnetotelluric responses from five models, each having an equivalent conductivity-thickness product for the conductive layer. (a) Conductivity models, (b) apparent resistivity ($\\rho_a$), and (c) phase ($\\phi$).}\n\\label{fig:sigmat}\n\\end{figure}\n\n\\section{Go backwards}\n\nTo solve the inverse problem, we will use a deterministic approach and pose the inverse problem as an optimization problem of the form\n\\begin{equation}\n\\min_{\\mathbf{m}} \\phi(\\mathbf{m}) = \\phi_d(\\mathbf{m}) + \\beta\\phi_m(\\mathbf{m})\n\\end{equation}\nwhere $\\mathbf{m}$ is our model - the array of numbers that describes our earth model; $\\phi_d(\\mathbf{m})$ is the data misfit, a measure of ``how far'' our data are from the observed data; $\\phi_m(\\mathbf{m})$ is the regularization; and $\\beta$ is a trade-off parameter.\n\nThe data misfit, is often taken to be a weighted $\\ell_2$-norm:\n\\begin{equation}\n\\phi_d(\\mathbf{m}) = \\frac{1}{2}\\|\\mathbf{W_d} (\\mathcal{F}(\\mathbf{m}) - \\mathbf{d}^{\\text{obs}})\\|^2\n\\end{equation}\nwhere $\\mathbf{W_d}$ captures the noise model (typically it is a diagonal matrix containing the standard deviation of each datum). Tikhonov regularization, which again employs $\\ell_2$-norms, is a standard choice:\n\\begin{equation}\n\\phi_m(\\mathbf{m}) = \\frac{1}{2}\\big(\\alpha_s\\|\\mathbf{W_s} (\\mathbf{m} - \\mathbf{m}_{\\text{ref}})\\|^2 + \\alpha_z\\|\\mathbf{W_z} (\\mathbf{m})\\|^2 \\big)\n\\end{equation}\nThe first term is often referred to as the \"smallness\" as it measures the \"size\" of the model (in the $\\ell_2$ sense). The matrix $\\mathbf{W_s}$ is generally taken to be a diagonal matrix that may contain information about the length scales of the model or be used to weight the relative importance of various parameters in the model. The scalar $\\alpha_s$ weights the relative importance of this term in the regularization. Notice that we include a reference model, $\\mathbf{m}_{\\text{ref}}$. Often this is defined as a constant value, but if more information is known about the background, that can be used to construct a more intricate reference model. Here, we will not delve too far into how the reference model impacts the recovered results, but you are encouraged to change \\texttt{mref} in the notebooks and investigate its impact. The second term is often referred to as the \"smoothness\". The matrix $\\mathbf{W_z}$ approximates the derivative of the model with respect to depth, and is hence a measure of how \"smooth\" the model is. The term $\\alpha_z$ weights the relative importance of smoothness in the regularization.\n\nFrom this setup, we see that there are quite a number of choices to make: defining uncertainties on the data ($\\mathbf{W_d}$), selecting a reference model ($\\mathbf{m}_{\\text{ref}}$), choosing the importance of smallness and smoothness ($\\alpha_s$ and $\\alpha_z$), and selecting a trade-off parameter ($\\beta$). Let’s start by assuming a known noise model, fix $\\alpha_s$ and $\\alpha_z$, and explore the impact of the trade off parameter $\\beta$. Our forward problem depends upon the electrical conductivity. For the inverse problem, however, we are free to use any function of the conductivity as a parameter. The electrical conductivity of earth materials varies by many orders of magnitude and is strictly positive. Thus it is advantageous to use $\\mathbf{\\log(\\sigma)}$ as the model in the inverse problem. For a nonlinear problem, we also have the additional choice of the initial model $\\mathbf{m}_0$ at which to start the inversion. Although we will not discuss the choice of $\\mathbf{m}_0$, you are encouraged to change the initial model in the notebooks and examine the impact it makes - it can be significant!\n\n\\subsection{The $\\beta$ knob}\n\nIf the noise is Gaussian, then the sum of squares (our data misfit) is a Chi-squared distribution, which has an expected value of $N_\\text{data}$ (in our case, we divide this by two to match our definition of $\\phi_d$). Thus, the ideal choice of $\\beta$ is one that gives us $\\phi_d^* \\approx \\frac{1}{2} N_\\text{data}$. To demonstrate the effect of $\\beta$, we consider a five layer model, originally shown in \\cite{Monographs}, and will demonstrate inversions when we achieve the target misfit, underfit the data and overfit fit the data. The conductivity model used is the solid line in Figure \\ref{fig:justright}a. For these inversions we fix the regularization parameters to $\\alpha_s = 10^{-2}$, $\\alpha_z = 1$ and set $\\mathbf{m}_{\\text{ref}} = 10^{-2} S/m$, and the initial model, $\\mathbf{m}_0 = \\mathbf{m}_{\\text{ref}}$ (feel free to change them in the notebook!). We start the inversion with a large $\\beta$ and decrease its value to plot the trade-off or Tikhonov curve (Figure \\ref{fig:justright}b). In this figure, the inversion is stopped when the data misfit approximately equals the  target misfit (the star in Figure \\ref{fig:justright}b). Figures \\ref{fig:justright}c and \\ref{fig:justright}d show the data as apparent resistivity and phase, which is a visualization of our complex-valued impedance data. The dashed line in Figure \\ref{fig:justright}a shows the recovered model, which identifies the general structure and amplitudes of the five layer model. In this case, we are employing a smooth regularization, thus we expect to recover smoothly varying structures.\n\n\n\n\\begin{figure}[htb!]\n    \\centering\n    \\includegraphics[width=\\textwidth]{../images/justright_old.png}\n\\caption{Inversion which achieves target misfit. (a) True (solid) and recovered (dashed) electrical conductivity models. (b) Tikhonov curve showing the target misfit (red star) and achieved misfit (red circle, in this example they overlap) in the inversion (c) observed (solid) and predicted (x’s) apparent resistivity data, (d) observed (solid) and predicted (x’s) phase data}\n\\label{fig:justright}\n\\end{figure}\n\nIf we instead choose a larger $\\beta$, reducing the contribution of the data misfit to the objective function, we ``underfit'' the data, as is shown in Figure \\ref{fig:underfit}. Although we still see evidence of two conductive structures, we do not recover their amplitudes, and do a poor job resolving the location and widths of the conductive layers (if you had to pick the top of the first layer - where should it be?). Examining the data plots in \\ref{fig:underfit}c and d, there is more insight about the subsurface conductivity that can be learned by extracting more information from the data.\n\n\n\\begin{figure}[htb!]\n    \\centering\n    \\includegraphics[width=\\textwidth]{../images/underfit_old.png}\n\\caption{Inversion which underfits the data. (a) True (solid) and recovered (dashed) electrical conductivity models. (b) Tikhonov curve showing the target misfit (red star) and achieved misfit (red circle) in the inversion (c) observed (solid) and predicted (x’s) apparent resistivity data, (d) observed (solid) and predicted (x’s) phase data}\n\\label{fig:underfit}\n\\end{figure}\n\nOn the other extreme, we can choose a very small $\\beta$, and try to fit all of the details in the data. Doing this, we obtain the results shown in Figure \\ref{fig:overfit}. When we push the inversion to fit the (noisy!) data very closely, we end up fitting the noise. In order to do this, conductivity contrasts are exaggerated and oscillatory and erroneous conductivity structures are introduced in the inversion.\n\n\n\n\\begin{figure}[htb!]\n    \\centering\n    \\includegraphics[width=\\textwidth]{../images/overfit_old.png}\n\\caption{Inversion which overfits the data. (a) True (solid) and recovered (dashed) electrical conductivity models. (b) Tikhonov curve showing the target misfit (red star) and achieved misfit (red circle) in the inversion (c) observed (solid) and predicted (x’s) apparent resistivity data, (d) observed (solid) and predicted (x’s) phase data}\n\\label{fig:overfit}\n\\end{figure}\n\\subsection{The $\\alpha$ knobs}\n\nFor Figures \\ref{fig:justright}-\\ref{fig:overfit}, we prescribed the values the $\\alpha_s$, $\\alpha_z$. What impact do they have on the character of the model we recover?\n\nIn Figure \\ref{fig:alphas}, we compare two inversions with different regularization parameters: (1) a ``smooth'' inversion (blue line), with $\\alpha_s = 10^{-5}$ and $\\alpha_z = 1$, and (2) a ``small'' inversion (red line): with $\\alpha_s = 1$ and $\\alpha_z = 10^{-5}$. In both, $\\beta$ was chosen so that a desired target misfit was achieved. The smooth inversion penalizes large gradients; the resulting model has two smooth peaks. Note that we smooth over the resistive third layer, over-estimating its conductivity. The ``small'' inversion instead favors models that are close to the reference model; this model has more structure. The resistivity of the first layer matches well (the conductivity of the first layer is equivalent to our reference model) and the conductivity of the third layer is closer to its true value, but additional oscillatory structures are introduced at depth. In the fourth notebook, you can explore the impact of these parameters yourself!\n\n\\begin{figure}[htb!]\n    \\centering\n    \\includegraphics[width=0.5\\textwidth]{../images/alphas_old.png}\n\\caption{Comparing the use of Smooth regularization versus Small regularization in the inversion.}\n\\label{fig:alphas}\n\\end{figure}\n\n\nIn practice, these parameters are often determined by experimentation; strategies such as examining length scales are often successfully adopted (see page 38 \\cite{OldenburgTutorial}). Changing the relative values of $\\alpha_s$ and $\\alpha_z$ is one way to bring in a-priori information, if we know very little, often starting with a smooth inversion is a good option; this penalizes structure (high gradients) while showing general trends. If more structure is expected, or a reliable reference model can be built from additional data such as physical property measurements, well logs, or additional geophysical/geologic data, then the influence of the smallness term may be increased. There are a few other ways to bring in additional a-priori information. If we are expecting a more ``blocky'' model, we can choose a different norm (such as an $\\ell_1$ norm), or if we have structural constraints, we can introduce other weighting structures (e.g. on the smoothness); these are knobs for another tutorial and there is discussion in \\cite{OldenburgTutorial}.\n\n\\section{Summary}\nIn this tutorial, we have introduced the forward simulation of Maxwell’s equations for magnetotellurics and explored a few aspects of the inverse problem. Prior to jumping into an inversion, it is important to know the limitations of the survey and data and what you can and cannot resolve, even if there is no noise! Forward modelling is a powerful tool for setting realistic expectations of an inversion. In the magnetotelluric problem, thin layers which have the same conductance produce very similar data signatures and we cannot expect to independently resolve both the conductivity and thickness of a layer without bringing in additional information.\n\nTo set up and solve the inverse problem, we introduced a simple deterministic inversion for the electrical conductivity where we posed the inversion as an optimization problem that minimizes an objective function consisting of a data misfit and a regularization term. There are many choices to be made in defining the various elements of the inverse problem, including how to assign uncertainties, selecting a trade-off parameter, defining the regularization function, and choosing an initial and reference model. In this tutorial we explored two of the knobs: (1) the trade-off parameter and (2) the relative importance of smallness and smoothness contributions in a Tikhonov regularization. There are many other parameters that can be introduced, tuned and manipulated -- this should first be done with a synthetic, when you know the true model! The interactive notebooks that are provided allow you to change parameters and experiment with their impact.\n\n\\clearpage\n\\bibliographystyle{seg}  % style file is seg.bst\n\\bibliography{references.bib}\n\n\\end{document}\n", "meta": {"hexsha": "b2baba73f861e590833afe8645a959f0fd82fdbf", "size": 21113, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "MTtutorialV0/MTtutorial.tex", "max_stars_repo_name": "simpeg/tle-magnetotelluric_inversion", "max_stars_repo_head_hexsha": "49b038b013a40283a32ea18ea9144bf707656873", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2017-11-29T01:03:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-11T04:28:49.000Z", "max_issues_repo_path": "MTtutorialV0/MTtutorial.tex", "max_issues_repo_name": "thast/tle-magnetotelluric_inversion", "max_issues_repo_head_hexsha": "74c15e73ec9c4d656c35ecef6661e2fea7774fc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-02-13T04:28:31.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-13T04:54:36.000Z", "max_forks_repo_path": "MTtutorialV0/MTtutorial.tex", "max_forks_repo_name": "simpeg/tle-magnetotelluric_inversion", "max_forks_repo_head_hexsha": "49b038b013a40283a32ea18ea9144bf707656873", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-03-27T19:26:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-20T11:41:26.000Z", "avg_line_length": 145.6068965517, "max_line_length": 1587, "alphanum_fraction": 0.778951357, "num_tokens": 5031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.615087848460224, "lm_q1q2_score": 0.31475066540885605}}
{"text": "\\chapter{Calculation of Electron Density}\\index{DENSITY!program|ff}\r\n\\index{Electron!density}\r\n\\section{Theory}\r\nFirst of all, let us understand what is meant in this Chapter by electron\r\ndensity.\r\n\\index{Density matrix}\r\nA density matrix is generated during a SCF calculation.  This density matrix\r\nrepresents the distribution of electrons in atomic orbitals; thus, for H$_2$,\r\nthe density matrix would be:\r\n\\[\r\n\\left | \\begin{array}{cc} 1.0 & 1.0 \\\\ 1.0 & 1.0 \\end{array} \\right |\r\n\\]\r\nThis particular matrix indicates that there is one electron on each of atomic\r\norbitals $\\varphi_1$ and $\\varphi_2$, and that this density is modified by 1.0\r\ntimes the product of $\\varphi_1\\varphi_2$.\r\n\r\nIn this Chapter we will be concerned, not with the density matrix {\\em per se},\r\nbut with the electron density.  Electron density is the density of electrons in\r\nelectrons per cubic \\AA ngstrom at a defined point in space.  In order to be\r\nuseful,  a surface of constant electron density, or a cross-section through a\r\nsystem, will usually be generated.\r\n\r\n\\index{Eigenvectors}\r\nThe density matrix arises from the normalized eigenvectors.  These, in turn,\r\nare generated by diagonalizing the Fock matrix in the eigenvalue equation.  In\r\nNDDO \\index{NDDO} methods, the assumption of Neglect of Diatomic Differential\r\nOverlap is made. This assumption is not valid when electron density plots are\r\nbeing generated.\r\n\r\n\\paragraph*{Failure of NDDO Approximation}\r\nBefore going on to calculate  electron density, let us examine the reason for\r\nthe breakdown of the NDDO approximation when electron density is being\r\ncalculated.\r\n\r\nConsider again the H$_2$ system.  The bonding M.O.\\  is $\\psi =\r\n1/\\sqrt{2}(\\varphi_1 + \\varphi_2)$, which is   the M.O.\\ which gives rise to the\r\ndensity matrix shown above.\r\n\r\nConsider what would happen if the electron density were to be calculated using\r\nthis density matrix.  For each point in space there would be a density, $\\rho(x,y,z)$,\r\nwhich would arise from:\r\n$$\r\n\\rho(x,y,z) = 1.0\\varphi_1(x,y,z)^2 + 1.0\\varphi_2(x,y,z)^2 + 2.0\\varphi_1(x,y,z)\\varphi_2(x,y,z)\r\n$$\r\nNow, the integral of this function over all space would equal the number of electrons\r\nin H$_2$:\r\n$$\r\n N_e = \\int_{-\\infty}^{+\\infty}\\int_{-\\infty}^{+\\infty}\\int_{-\\infty}^{+\\infty}\\rho(x,y,z)dx\\,dy\\,dz\r\n$$\r\n The integral over all space of a normalized atomic orbital is 1.00; therefore,\r\n$$\r\nN_e = 1.0 + 1.0 + 2<\\varphi_1\\varphi_2> \\neq 2,\r\n$$\r\n\r\nIn other words, the total number of electrons in H$_2$, assuming the NDDO\r\napproximation,  is greater than 2.0.  The extra density comes from the product\r\n$ 2.0\\varphi_1(x,y,z)\\varphi_2(x,y,z)$, which must not be neglected.  If it\r\nwere to be neglected, then all phenomena such as bonds and lone pairs could not\r\nbe modeled.\r\n\r\nAnother way of looking at this is to recognize that, in H$_2$, electron density\r\nbetween the atoms is greater when a bond exists than when it does not exist.\r\nGiven this, it follows that, in order to ensure that the total number of\r\nelectrons in the system remains constant when a bond forms, at some other point\r\nin space the electron density must be less when a bond exists than when it does\r\nnot exist.  In other words, if density builds up in some region of space, then\r\nit must become less somewhere else in order that the total number of electrons\r\nwould remain constant.\r\n\r\n\\paragraph*{Starting M.O.s}\r\n\r\nBecause of the failure of the NDDO approximation, the M.O.s must be re-normalized\r\nbefore the density is calculated.  This is most easily done by performing the\r\noperation\r\n$$\r\n  \\psi = S^{-1/2}\\psi'S^{-1/2},\r\n$$\r\nwhere $\\psi'$ is the original NDDO molecular orbital, and $S$ is the overlap matrix over atomic orbitals.\r\nIn practice, it is easier to matrix-multiply $\\Psi =  S^{-1/2}\\Psi'S^{-1/2}\r\n$, as this generates all the M.O.s in one operation.\r\nFrom these re-normalized M.O.s, a re-normalized density matrix can\r\nbe calculated in the normal way:\r\n$$\r\n P'_{\\lambda\\sigma}=2\\sum_i^{occ}c_{\\lambda i} c_{\\sigma i}.\r\n$$\r\n\\paragraph*{Calculation of Electron Density}\r\nIn order to calculate electron density for any given point, the value of\r\neach atomic orbital must be calculated.  Atomic orbitals, as Slaters, are\r\nof form\r\n$$\r\n\\varphi = Nf_rf_{\\theta\\phi},\r\n$$\r\nin which $N=c\\frac{(2\\xi)^{n+1/2}}{(2n)!2\\sqrt{\\pi}}$, where $\\xi$ is the orbital\r\nexponent, $n$ is the principal quantum number, and $c=1$ for $s$ orbitals,\r\n$\\sqrt{3}$ for $p$ orbitals, and $\\sqrt{15}$ for $d$ orbitals.\r\nAt any given point, the value of $\\varphi$ is given as the product of the\r\nnormalization constant, the radial term, and the angular component.  The\r\nradial term is simply $f_r=r^{n-1}e^{-\\xi r}$, where $r$ is the distance\r\nfrom the point under study to the atomic center.\r\nThe angular terms are more complicated.  For a $s$-$p$-$d$ basis set, the\r\nvalue of $\\varphi$ is\r\n\\begin{eqnarray}\r\n\\varphi       _s          &=& Nf_r \\nonumber  \\\\\r\n\\varphi       _{p_x}       &=& Nf_rx \\nonumber  \\\\\r\n\\varphi       _{p_y}       &=& Nf_ry \\nonumber  \\\\\r\n\\varphi       _{p_z}       &=& Nf_rz\\nonumber  \\\\\r\n\\varphi       _{d_{x^2-y^2}}&=& Nf_r\\frac{1}{2}(x^2-y^2)\\nonumber  \\\\\r\n\\varphi       _{d_{xz}}     &=& Nf_rxz \\nonumber \\\\\r\n\\varphi       _{d_{z^2}   } &=& Nf_r\\frac{1}{\\sqrt{12}}(2z^2-x^2-y^2)\\nonumber  \\\\\r\n\\varphi       _{d_{yz }   } &=& Nf_ryz         \\nonumber   \\\\\r\n\\varphi       _{d_{xy }   } &=& Nf_rxy         \\nonumber\r\n\\end{eqnarray}\r\nwhere $x$, $y$, and $z$ are the normalized direction components.\r\n\\paragraph*{Electron density}\r\n\r\nThe density at a point is then simply\r\n$$\r\n\\rho(x,y,z) = \\sum_{\\lambda}\\sum_{\\sigma}\r\n\\varphi_{\\lambda}(x,y,z)P_{\\lambda\\sigma}'\\varphi_{\\sigma}(x,y,z).\r\n$$\r\nThis function is everywhere positive, although it may become vanishingly small.\r\n\\paragraph*{Molecular Orbitals}\r\n\r\nMolecular orbitals can be generated by calculating the function\r\n$$\r\n\\psi_i(x,y,z) = \\sum_{\\lambda}c_{\\lambda i}\\varphi_{\\lambda}(x,y,z).\r\n$$\r\nNote that molecular orbitals are expressed in intensity, not density.\r\nThe intensity of a M.O.\\ is its instantaneous value.  This should not\r\nbe confused with, e.g., electrons per cubic \\AA ngstrom.\r\n\r\nExcept for very simple cases, such as the bonding M.O.\\ in H$_2$, this function\r\nwill have both positive and negative regions.\r\n\r\n\\paragraph*{Bonds}\r\nBonds can be modeled by generating a difference map.  The density due to\r\nthe atoms can be subtracted from the density arising from the density matrix.\r\nThe density due to the atoms is that given by MOPAC: i.e., using the\r\nun-re-normalized M.O.s, but spherically averaged before use, thus:\r\n\\begin{eqnarray}\r\nP^{\\dagger}_{ss}& =& P_{ss} \\nonumber \\\\\r\nP^{\\dagger}_{p_xp_x}= P^{\\dagger}_{p_yp_y}=P^{\\dagger}_{p_zp_z}& =&\\frac{1}{3}(P_{p_xp_x}+P_{p_yp_y}+P_{p_zp_z})\\nonumber \\\\\r\nP^{\\dagger}_{d_{x^2-y^2}d_{x^2-y^2}}=P^{\\dagger}_{d_{xz}d_{xz}} &=&\\nonumber \\\\\r\nP^{\\dagger}_{d_{z^2}d_{z^2}}= P^{\\dagger}_{d_{yz }d_{yz }}=P^{\\dagger}_{d_{xy }d_{xy }}&=&\\frac{1}{5}(P_{d_{x^2-y^2}d_{x^2-y^2}} +P_{d_{xz}d_{xz}} +P_{d_{z^2}d_{z^2}} +\r\nP_{d_{yz }d_{yz }}+P_{d_{xy }d_{xy }}) \\nonumber\r\n\\end{eqnarray}\r\nUsing this re-normalized, isotropic, density matrix the difference map can now be\r\ncalculated:\r\n$$\r\n\\rho(x,y,z) = \\sum_{\\lambda}\\sum_{\\sigma}\r\n\\varphi_{\\lambda}(x,y,z)P_{\\lambda\\sigma}^{\\dagger}\\varphi_{\\sigma}(x,y,z) -\\sum_{\\lambda}\r\nP^{\\dagger}_{\\lambda\\lambda}(\\varphi_{\\lambda}(x,y,z))^2\r\n$$\r\nThis map is the most informative, but is somewhat difficult to see when first used.\r\n\r\nThe difference map will {\\em always} have both positive and negative regions in\r\nspace.  For most, but not all systems, bonding is indicated by a build-up of\r\ndensity between two atoms.  Exceptions are, for example, F$_2$ and Cl$_2$.\r\n\r\n\r\n\\section{Program DENSITY}\r\n% 139 lines, including this one\r\n%\\setlength{\\unitlength}{0.07cm}\r\n\r\n\\begin{figure}\r\n\\begin{makeimage}\r\n\\end{makeimage}\r\n\\index{Benzene!DENSITY plot}\r\n\\index{Bonds!Density plot}\r\n\\index{GRID!DENSITY plot}\r\n\\begin{center}\r\n\\includegraphics{benzene2} \\\\~\\\\\r\n\\begin{latexonly}\r\n\\parbox{30em}{Keywords used are:\r\n\r\n\\comp{CENTER=(0.7,1.2,0) LINE=(0.0,0.0,1.0) EDGE=6.0}\r\n\r\nAtom C$_1$ is at the origin, C$_2$ is at coordinates (0.0,1.39,0),\r\nand C$_3$ is at (2.09,1.20,0).\r\nNote that, because the atomic orbitals of carbon have a node at the\r\nnucleus, the electron density at every carbon nucleus is almost\r\nzero.}\r\n\\end{latexonly}\r\n\\begin{htmlonly}\r\nKeywords used are:\r\n\r\n\\comp{CENTER=(0.7,1.2,0) LINE=(0.0,0.0,1.0) EDGE=6.0}\r\n\r\nAtom C$_1$ is at the origin, C$_2$ is at coordinates (0.0,1.39,0),\r\nand C$_3$ is at (2.09,1.20,0).\r\nNote that, because the atomic orbitals of carbon have a node at the\r\nnucleus, the electron density at every carbon nucleus is almost\r\nzero.\r\n\\end{htmlonly}\r\n\\end{center}\r\n\\caption{\\label{d_mol}Total electron density map for benzene}\r\n\\end{figure}\r\n\r\n\\begin{figure}\r\n\\begin{makeimage}\r\n\\end{makeimage}\r\n\\begin{center}\r\n\\includegraphics{benzene3} \\\\~\\\\\r\n\\begin{latexonly}\r\n\\parbox{30em}{Keywords used:\r\n\r\n\\comp{CENTER=(0.7,1.2,0) LINE=(0.0,0.0,1.0) EDGE=6.0 BONDS}\r\n\r\nNote the build-up of density {\\em between} all bonded pairs of atoms.\r\n\r\nThe six roughly triangular regions represent the loss of electron density,\r\nas do the six egg-shaped lobes on the hydrogens.  In the center of the\r\nbenzene ring, there is no significant gain or loss of electron density.}\r\n\\end{latexonly}\r\n\\begin{htmlonly}\r\nKeywords used:\r\n\r\n\\comp{CENTER=(0.7,1.2,0) LINE=(0.0,0.0,1.0) EDGE=6.0 BONDS}\r\n\r\nNote the build-up of density {\\em between} all bonded pairs of atoms.\r\n\r\nThe six roughly triangular regions represent the loss of electron density,\r\nas do the six egg-shaped lobes on the hydrogens.  In the center of the\r\nbenzene ring, there is no significant gain or loss of electron density.\r\n\\end{htmlonly}\r\n\\end{center}\r\n\\caption{\\label{d_mol1}Bonds map for benzene}\r\n\\end{figure}\r\n\r\n\\begin{figure}\r\n\\begin{makeimage}\r\n\\end{makeimage}\r\n\\begin{center}\r\n\\includegraphics{benzene} \\\\~\\\\\r\n\\begin{latexonly}\r\n\\parbox{30em}{Keywords used:\r\n\r\n\\comp{MULT=1 CENTER=(-0.27,-0.5,0) LINE=(0,0,1) EDGE=3 AXIS=.4 GRID NO-CONTOURS}\r\n\r\nThis type of plot is best viewed with the contours added in, but for the\r\nsake of clarity they have been omitted from this picture.}\r\n\\end{latexonly}\r\n\\begin{htmlonly}\r\nKeywords used:\r\n\r\n\\comp{MULT=1 CENTER=(-0.27,-0.5,0) LINE=(0,0,1) EDGE=3 AXIS=.4 GRID NO-CONTOURS}\r\n\r\nThis type of plot is best viewed with the contours added in, but for the\r\nsake of clarity they have been omitted from this picture.\r\n\\end{htmlonly}\r\n\\end{center}\r\n\\caption{Detail of C-H bond in benzene}\r\n\\end{figure}\r\n\r\n% 21 lines, including this one\r\n% \\setlength{\\unitlength}{0.06cm}\r\n\\begin{figure}\r\n\\begin{makeimage}\r\n\\end{makeimage}\r\n\\index{Polyacetylene!DENSITY plot}\r\n\\index{Graphite!DENSITY plot}\r\n\\begin{center}\r\n\\includegraphics{polyacetylene_total} \\\\~\\\\\r\n\\begin{latexonly}\r\n\\parbox{30em}{Keywords used are:\r\n\r\n\\comp{CENTER=(0.0,0.0,0.0) LINE=(0,0,1) EDGE=7.0}\r\n\r\nThe picture is centered on atom C$_1$, and shows the `join' of the central\r\nunit cell with the adjacent unit cell.  Note that the `join' is quite\r\ninvisible.}\r\n\\end{latexonly}\r\n\\begin{htmlonly}\r\nKeywords used are:\r\n\r\n\\comp{CENTER=(0.0,0.0,0.0) LINE=(0,0,1) EDGE=7.0}\r\n\r\nThe picture is centered on atom C$_1$, and shows the `join' of the central\r\nunit cell with the adjacent unit cell.  Note that the `join' is quite\r\ninvisible.\r\n\\end{htmlonly}\r\n\\end{center}\r\n\\caption{\\label{d_solids}Total electron density map for polyacetylene}\r\n\\end{figure}\r\n\r\n\\begin{figure}\r\n\\begin{makeimage}\r\n\\end{makeimage}\r\n\\begin{center}\r\n\\includegraphics{polyacetylene_pi} \\\\~\\\\\r\n\\begin{latexonly}\r\n\\parbox{30em}{Keywords used:\r\n\r\n\\comp{CENTER=(0.0,0.0,0.6) LINE=(0,0,1) EDGE=7.0 BONDS}\r\n\r\nAs with benzene, note the build-up of density {\\em between} all\r\nbonded pairs of atoms.  In order to show the strong $\\pi$-bond, the\r\ncenter of the plot has been raised 0.6\\AA\\ above the backbone chain.}\r\n\\end{latexonly}\r\n\\begin{htmlonly}\r\nKeywords used:\r\n\r\n\\comp{CENTER=(0.0,0.0,0.6) LINE=(0,0,1) EDGE=7.0 BONDS}\r\n\r\nAs with benzene, note the build-up of density {\\em between} all\r\nbonded pairs of atoms.  In order to show the strong $\\pi$-bond, the\r\ncenter of the plot has been raised 0.6\\AA\\ above the backbone chain.\r\n\\end{htmlonly}\r\n\\end{center}\r\n\\caption{\\label{d_solids1}Bonds map for polyacetylene}\r\n\\end{figure}\r\n\r\n\\begin{figure}\r\n\\begin{makeimage}\r\n\\end{makeimage}\r\n\\begin{center}\r\n\\includegraphics{graphite001} \\\\~\\\\\r\n\\begin{latexonly}\r\n\\parbox{30em}{Keywords used:\r\n\r\n\\comp{CENTER=(0.0,0.0,0.0) LINE=(0,0,1) EDGE=4.0}\r\n\r\nThe center of the plot is at C$_{1,1}$ in a 5 $\\times$ 5 array of atoms.\r\nThe picture therefore shows the `join' of four unit cells, cells (0,0),\r\n(0,-1), (-1,0), and (-1,-1).  As with polyacetylene, the `join' is\r\ninvisible.}\r\n\\end{latexonly}\r\n\\begin{htmlonly}\r\nKeywords used:\r\n\r\n\\comp{CENTER=(0.0,0.0,0.0) LINE=(0,0,1) EDGE=4.0}\r\n\r\nThe center of the plot is at C$_{1,1}$ in a 5 $\\times$ 5 array of atoms.\r\nThe picture therefore shows the `join' of four unit cells, cells (0,0),\r\n(0,-1), (-1,0), and (-1,-1).  As with polyacetylene, the `join' is\r\ninvisible.\r\n\\end{htmlonly}\r\n\\end{center}\r\n\\caption{\\label{d_solids2}Graphite, Total Electron Density}\r\n\\end{figure}\r\n\r\nThe program DENSITY is designed to generate  maps of electron density\r\ndistribution and molecular orbital intensity within molecules\r\n(Figure~\\ref{d_mol}) and solids (Figure~\\ref{d_solids}). Two main modes of\r\noperation are provided: manual data input, which is a ``stand-alone'' mode, and\r\nnormal input, which assumes the existence of large unformatted data-files\r\nproduced  by, e.g.\\ MOPAC.\r\n\r\n\\index{GRAPH!use in DENSITY} To generate the large unformatted data-file, MOPAC\r\nshould be run using the key-word \\comp{GRAPH}. At present, MOPAC can only\r\nproduce graphics files in the RHF mode, the UHF capability having not yet being\r\nwritten.\r\n\r\nAlthough DENSITY has a very simple data-input, users are warned that care is\r\nneeded in precisely wording a request. As an example, in learning how to use\r\nDENSITY a user might want to plot the highest-filled $\\pi$ orbital in benzene,\r\nand choose the plane to be that of the carbon atoms. At first sight this\r\nappears reasonable, but when one recalls that the $\\pi$ system has a node in\r\nthis plane, another choice of plane is seen to be essential. A better choice of\r\nplane would be one parallel to the plane of the carbon  atoms, but 0.5 to 1.0\r\n\\AA ngstroms above it.\r\n\r\nSimilarly, if only a detail of the molecule is to be studied, it is wasteful to\r\nplot the whole molecule. The picture is essentially made up of 2,500 pixels, so\r\nfine detail can very easily be lost if the whole molecule is used.\r\n\r\nWith one important exception the whole program is written using the FORTRAN-77\r\nstandard, so translation to allow DENSITY to run on different machines should\r\nnot be difficult. FORTRAN-77 does not support graphical functions, and an\r\ninterface, designed to allow users to easily write their own interfaces, has\r\nbeen written.  This interface is, of course, machine-dependent.\r\n\r\n\\section{Data}\r\nRather than fully define the input, a worked example will be given\r\n(Figure~\\ref{d_c2h4}) and other data-files can then be generated by analogy.\r\n\r\n\\subsection{Example of Data: Ethylene}\r\n\\index{Ethylene! $\\pi$-density in}\r\nFor this example we will use the $\\pi$ system in ethylene. Two pictures are to\r\nbe drawn based on the results from an earlier MOPAC calculation.  The first\r\nplot is in the plane parallel  to the plane of the molecule, the second one is\r\nin the plane perpendicular to the C-C axis.  DENSITY data-files should have the\r\nsuffix \\comp{.gra}.\r\n\\begin{figure}\r\n\\begin{makeimage}\r\n\\end{makeimage}\r\n\\begin{verbatim}\r\nLine 1 :  DEBUG\r\nLine 2 :  Ethylene pi system\r\nLine 3a:  CENTER=(0.7,0.0,0.5) LINE=(0.0,0.0,1.0) EDGE=2.0 HOMO\r\nLine 3b:  CENTER=(0.7,0.0,0.5) LINE=2 EDGE=2.0 HOMO\r\nLine 4 :\r\n\\end{verbatim}\r\n\\caption{\\label{d_c2h4} DENSITY data-set for Ethylene}\r\n\\end{figure}\r\n\r\n\\begin{description}\r\n\\item[Line 1:] First set of key-words.  These  control the mode of operation.\r\n\\item[Line 2:] Title of plot. Up to 79 characters can be used.\r\n\\item[Line 3a:] Second set of key-words. A full list of key-words, and\r\ntheir definitions, is given in the next Section.\r\n\\item[Line 3b:] Key-words for the second picture.\r\n\\item[Line 4:] End the input with a blank line.\r\n\\end{description}\r\n\r\n\\subsection{Keywords}\r\nTwo sets of key-words are provided. At the start of a run the user must provide\r\ninformation about the source of the molecular data. At present, this data can\r\ncome from one of two sources. These are (a) off the data-file itself, which is\r\nthe \\comp{MANUAL} mode, and (b) from a disk or restart-type file, which was\r\ncreated by an earlier run using MOPAC.\r\n\r\n\\subsection{Definitions of First set of Key-Words}\r\n\\begin{description}\r\n\\item[\\comp{DEBUG}] Print part of working of DENSITY.\r\n\\item[\\comp{DMAT}] Lower half triangle of density matrix to be read in (Used\r\nwith \\comp{MANUAL} only)\r\n\\item[\\comp{MANUAL}] Stand-alone  mode. All data supplied from datafile.\r\n\\item[\\comp{M.O.}] A molecular orbital to be used as source of density matrix.\r\n(Used with \\comp{MANUAL} only)\r\n\\end{description}\r\n\r\n\\subsubsection*{\\comp{DEBUG}}\\index{DEBUG!use in DENSITY}\r\nThe density matrix or molecular orbital used by the density calculation will be\r\nprinted if \\comp{DEBUG} is specified.\r\n\r\n\\subsubsection*{\\comp{DMAT}}\r\nTo be used only if \\comp{MANUAL} is also specified. \\comp{DMAT} specifies that\r\nthe lower-half of the density matrix, in free-format, is read in. There would\r\nbe (NORBS$\\times$(NORBS+1))/2 of these numbers.\r\n\r\n\\subsubsection*{\\comp{MANUAL}}\\index{MANUAL}\r\nThis word was used in the writing and de-bugging of DENSITY,  but now is only\r\nintended for testing and demonstration purposes.\r\n\r\nWhen \\comp{MANUAL} is specified, either \\comp{DMAT} or \\comp{M.O.} must be\r\nspecified on the same line as \\comp{MANUAL}.\r\n\r\nIf \\comp{MANUAL} is specified, the following data must be supplied on the next\r\nfew lines:\r\n\\begin{enumerate}\r\n\\item Number of atoms, orbitals, and electrons (NATOMS, NORBS, NELECS).\r\nOne line, free format, integer.\r\n\\item Cartesian coordinates for each atom, one atom per line, free format,\r\nreal, in order x, y, z. There will be NATOMS of these.\r\n\\item Labels for all atoms. For example, all carbon atoms might be called\r\n``1'', all hydrogen atoms ``2'', etc. Free format, integer. There will be NATOMS\r\nof these numbers. The numbers must be 1 to NUNI, NUNI being the number\r\nof unique atom-types in the molecule.\r\n\r\n\\begin{tabular}{llc|llllll|l} \\hline\r\n   Compound   &   Atom Labels       &NUNI &  \\multicolumn{6}{c}{Line would read} & \\\\ \\hline\r\n  Methane     & C: 1,   H: 2        & 2 & 1 & 2 & 2 & 2 & 2 &       &   CH4  \\\\\r\n  Formic Acid & H: 1,   C: 2,  O: 3 & 3 & 1 & 2 & 3 & 3 & 1 &        &  HCOOH  \\\\\r\n  Thiomethanol& C: 1,   H: 2,  S: 3 & 3 & 1 & 2 & 2 & 2 & 3 & 2     &   CH3SH  \\\\ \\hline\r\n\\end{tabular}\r\n\r\n\\item Atomic Numbers for all unique atoms. Free format, integer. There are\r\nNUNI of these numbers. If atom of type 1 is a carbon atom, then the\r\ncorresponding atomic number would be 6. Using the examples above, we have:\r\n\r\n\\begin{tabular}{ll|lll} \\hline\r\n&                 Atomic Numbers & \\multicolumn{3}{c}{Line would read}  \\\\\r\n     Compound     &  Unique atom: &  1 &  2 &  \\ 3 \\\\\\hline\r\n     Methane      &          &       6  & 1 & \\\\\r\n     Formic Acid  &           &      1  & 6 & \\  8 \\\\\r\n     Thiomethanol &           &      6  & 1 & 16 \\\\ \\hline\r\n\\end{tabular}\r\n\r\n\\item Principal Quantum numbers. Free format, integer. There are\r\nNUNI of these numbers.\r\n\r\n\\begin{tabular}{ll|lll}\r\n\\hline\r\n  & Principal Quantum Numbers  & \\multicolumn{3}{c}{Line would read}  \\\\\r\n     Compound &  Unique atom: & 1 & 2 & 3\r\n\\\\ \\hline\r\n     Methane  &               & 2 & 1 &    \\\\\r\n     Formic Acid  &           & 1 & 2 & 2    \\\\\r\n     Thiomethanol &           & 1 & 2 & 3    \\\\\r\n\\end{tabular}\r\n\r\n\\item Number of orbitals for all unique atoms. Free format, integer, there are\r\nNUNI of these numbers.\r\n\r\n\\begin{tabular}{ll|lll}\r\n\\hline\r\n&            Number of Orbitals  & \\multicolumn{3}{c}{Line would read} \\\\\r\n     Compound &  Unique atom: & 1 & 2 & 3  \\\\\r\n               \\hline\r\n     Methane  &                4 & 1  \\\\\r\n     Formic Acid  &            1 & 4 & 4  \\\\\r\n     Thiomethanol &            1 & 4 & 9  \\\\\r\n\\hline\r\n\\end{tabular}\r\n\r\n\\item Orbital exponents for all unique atoms, format is 3F10, three numbers\r\nper atom (one each for $s$, $p$, and $d$ orbital exponents); if $p$ or $d$ is\r\nabsent, these can be left blank.\r\n\r\n\\begin{tabular}{lc|lll} \\hline\r\n Compound & Unique atom &  \\multicolumn{3}{c}{Line would read} \\\\ \\hline\r\n     Methane       &      1      & 1.78  &    1.78  \\\\\r\n                   &      2      & 1.3&  \\\\\r\n     Thiomethanol  &      1      & 1.78  &    1.78  \\\\\r\n                   &      2      & 1.&  \\\\\r\n                   &      3      & 2.4   &    2.1   &    1.0  \\\\ \\hline\r\n\\end{tabular}\r\n\r\n\\item If M.O.\\  is specified, the eigenvector coefficients are read in\r\nat this point. Free format, there\r\nare NORBS of these. Otherwise, if DMAT specified, the lower-half\r\nof the density matrix, in free-format, is read in. There would be\r\n(NORBS$\\times$(NORBS+1))/2 of these numbers.\r\n\\end{enumerate}\r\n\r\n\\begin{figure}\r\n\\begin{makeimage}\r\n\\end{makeimage}\r\n\\compresstable\r\n\\begin{verbatim}\r\nLine  1:      MANUAL       M.O.                   (Key-words\r\nLine  2:      FORMIC ACID                         (Title\r\nLine  3:      5  14 18                            (NATOMS, NORBS, NELECS\r\nLine  4:   0.0000    0.0000    0.0000             (Cartesian coordinates\r\nLine  5:   1.2270    0.0000    0.0000\r\nLine  6:   1.9164    1.1676    0.0000\r\nLine  7:   1.3973    1.9625    0.0000\r\nLine  8:   1.8882   -0.8836    0.0000\r\nLine  9:    1 2 1 3 3                             (Labels\r\nLine 10:    8 6 1                                 (Atomic Numbers\r\nLine 11:    2 2 1                                 (Princ. Quant. Nos.\r\nLine 12:    4 4 1                                 (Orbitals per atom\r\nLine 13:   2.699905  2.699905                     (Exponents\r\nLine 14:   1.787537  1.787537\r\nLine 15:   1.331967                    (below: eigenvector coefficients\r\nLine 16:   -0.1616  0.4769  -0.0514   0.0000  -0.0628  -0.3488  -0.0032\r\nLine 17:    0.0000  0.2634   0.6282  -0.0893   0.0000  -0.2925  -0.2457\r\nLine 18:    CENTER=2 LINE=(0,0,1) EDGE=4          (Rest of data\r\n\\end{verbatim}\r\n\\caption{\\label{d_hcooh} Full Example of Manual Data for Formic Acid}\r\n\\end{figure}\r\n\r\n\\subsubsection*{\\comp{M.O.}}\r\nThis keyword is to be used only when \\comp{MANUAL} is also specified. A\r\nmolecular orbital to be used as source of density matrix.  The M.O.\\ comes\r\nafter the other data required by \\comp{MANUAL} as a set of free-format\r\ncoefficients. After all these data are read in, the program continues as usual,\r\nbut many limitations apply. For example, if \\comp{M.O.} was used, then the\r\nkey-words  \\comp{PSI=$n$}, \\comp{HOMO} and \\comp{LUMO} would all give the same\r\nresult. These limitations are due to the absence of other data. The second set\r\nof key-words defines the type of plot to be drawn; much of this data is\r\nobligatory in that there are no defaults for certain data. The user must\r\nsupply:\r\n\\begin{itemize}\r\n\\item A definition of the center of the plot.\r\n\\item A definition for the axis of the vector perpendicular to the plot.\r\n\\item A length, in \\AA ngstroms, of the edge of the plot.\r\n\\end{itemize}\r\nOther data, which are mutually exclusive, are:\r\n\\begin{itemize}\r\n\\item A molecular orbital number, given by \\comp{PSI=$n$}, or\r\n\\item A highest-occupied molecular orbital, defined by the key-word\r\n \\comp{HOMO}, or\r\n\\item A lowest-unoccupied molecular orbital, defined by the\r\nkey-word \\comp{LUMO}, or\r\n\\item The explicit molecular-orbital occupancy, see key-word \\comp{OCCUPANCY}, or\r\n\\item The normal electron density of the molecule. This is specified by\r\nthe absence of the other key-words; i.e., this is the default.\r\n\\end{itemize}\r\nIf a full electron density map is specified. (That is, if the last option\r\nabove is taken), then another key-word, \\comp{BONDS}, can be used. \\comp{BONDS}\r\nwill remove the electron density due to the atom from the plot. The effect of\r\nthis is to  generate a plot showing where the charge build-up in the bonds\r\noccurs. Note: Ionic separations are not shown by \\comp{BONDS}.\r\n\r\n\\subsection{Definitions of Second set of Key-Words}\r\n\\begin{description}\r\n\\item[\\comp{ADD}] The current plot is to be added to the next plot.\r\n\\item[\\comp{AXIS=$n.nn$}] Angle of plane of plotted square to viewer's eye.\r\n\\item[\\comp{BONDS}] Subtract the electron density due to the atoms.\r\n\\item[\\comp{CENTER}] Used to define the center of the plot.\r\n\\item[\\comp{EDGE=$n.nn$}] Definition of the length of one side of the plot.\r\n\\item[\\comp{FINE}] Produce four times the default number of contours.\r\n\\item[\\comp{GRID}] Overlay x-y grid onto plot. Used with AXIS.\r\n\\item[\\comp{HOMO}] Plot the highest occupied M.O.\r\n\\item[\\comp{LINE}] Used to define the axis perpendicular to the plot.\r\n\\item[\\comp{LUMO}] Plot the lowest unoccupied M.O.\r\n\\item[\\comp{MULT=$n.nn$}] Multiply vertical relief by specified amount.\r\n\\item[\\comp{OCCUPANCY}] Used to allow the individual M.O.\\ populations to be specified.\r\n\\item[\\comp{PSI=$n$}] Plot a specific M.O.\r\n\\item[\\comp{PHASE}] Multiply the current plot by a constant.\r\n\\end{description}\r\n\r\n\\subsubsection*{\\comp{ADD}\\index{ADD}}\r\nWhen two or more pictures are to be added together to form a single picture,\r\n\\comp{ADD} must be used. For example, a user might want to add or subtract\r\ntwo M.O.s to see the effect. Thus if M.O.\\ 2 and M.O.\\ 3 were to be\r\nadded together, the data for such a calculation could be:\r\n\\begin{verbatim}\r\nLine 1:\r\nLine 2:   FORMALDEHYDE\r\nLine 3: CENTER=2 LINE=(0,0,1) EDGE=2 PSI=2 ADD\r\nLine 4: CENTER=2 LINE=(0,0,1) EDGE=2 PSI=3\r\nLine 5:\r\n\\end{verbatim}\r\nSee also \\comp{PHASE}.\r\n\r\n\\subsubsection*{\\comp{AXIS=$n.nn$}\\index{AXIS}}\r\nA square plot is drawn by default. If the user wants to show the\r\nthree-dimensional nature of the contour map a facility exists to tilt the plot\r\nso that a foreshortened and rotated plot is drawn. Of course, the degree of\r\ntilt depends very much on the system; there is no facility in DENSITY to\r\neliminate ``hidden lines'', so the tilt should not be so great that hidden\r\nlines would show. The range of $n.nn$ in  \\comp{AXIS=$n.nn$} is 1.0 to 0.0. 1.0\r\n(the default) would give a square plot, as if the user was viewing the plot\r\nfrom directly overhead looking straight down; 0.0 gives a view of the plot as\r\nif the user was looking at it from the horizon, looking horizontally. Clearly,\r\n\\comp{AXIS=1.0} would not show the relief. If \\comp{GRID} were used only a\r\nperfectly featureless square grid would be seen. Conversely, \\comp{AXIS=0.0}\r\nwould show the contours as perfectly flat, straight lines. Therefore, a better\r\nchoice would be \\comp{AXIS=0.6}.\r\n\r\n\\subsubsection*{\\comp{BONDS}\\index{BONDS!use in DENSITY}}\r\nNot to be used in conjunction with \\comp{HOMO}, \\comp{LUMO},\r\n\\comp{PSI=$n$}, or \\comp{OCCUPANCY}.\r\n\\comp{BONDS} calculates the average atomic orbital occupancy of each atom,  and\r\nsubtracts that number from the density matrix. The result is a plot whose\r\naverage value is zero, and which shows where the electrons have come from and\r\ngone to when the bonds are formed.\r\n\r\n\\subsubsection*{\\comp{CENTER}\\index{CENTER}}\r\nThis key-word is essential. It defines the center of the plot (see\r\nSection~\\ref{area}). Two formats are provided to define the center: (a) an atom\r\nnumber can be used, and (b) an absolute Cartesian coordinate  can be specified.\r\n\r\n\\begin{description}\r\n\\item[Definition by atom number]~\\\\\r\nFormat: \\comp{CENTER=$n$}  The location of atom $n$ is defined as the center\r\nof  the plot. Thus if atom $n$ has Cartesian coordinates (x=0.5, y=1.4, z=-0.8)\r\nthen the center of the plot is (x=0.5, y=1.4, z=-0.8). Dummy atoms are not\r\ncounted, so if any dummy atoms were used in the definition of the geometry,\r\nthey must be ignored when considering the atom number. In other words, only a\r\nreal atom can be used to define a point in the molecule.\r\n\r\n\\item[Definition by absolute Cartesian coordinate]~\\\\\r\nFormat: \\comp{CENTER=($n.nn$,$n.nn$,$n.nn$)} The location of the  center of the\r\nplot is defined as ($n.nn$,$n.nn$,$n.nn$). Of course, before such a center can\r\nbe defined, the user must know the Cartesian coordinates of the atoms in the\r\nmolecule.\r\n\\end{description}\r\n\r\nRegardless of which option is used, the center of the plot will be converted\r\ninternally into absolute Cartesian coordinates.\r\n\r\n\\subsubsection*{\\comp{FINE}}\r\nNormally, between 10 and 25 contours are plotted. In order to increase this\r\nnumber, \\comp{FINE} can be used, in which case 40 to 100 contours will be\r\ngenerated.\r\n\r\n\\subsubsection*{\\comp{EDGE=$n.nn$}\\index{EDGE}}\r\nThe length of one side of the graph-plot is defined as being $n.nn$  \\AA ngstroms.\r\n\r\n\\subsubsection*{\\comp{GRID}\\index{GRID!use in DENSITY}}\r\n\\comp{GRID} can be used to enhance the legibility of a plot. It draws a regular\r\nmesh of lines across the plot, with the same relief as the contours.\r\n\\comp{GRID} should only be used with an \\comp{AXIS} which is not 1.0.\r\n\r\n\\subsubsection*{\\comp{HOMO}\\index{HOMO!use in DENSITY}}\r\nFor closed-shell systems with non-degenerate highest occupied molecular\r\norbitals, the key-word \\comp{HOMO} can be used to produce an intensity map of\r\nthe highest occupied molecular orbital. For other systems, the key-word\r\n\\comp{PSI=$n$} should be used.\r\n\r\n\\subsubsection*{\\comp{LINE}\\index{LINE}}\r\nThis key-word is essential. It defines the vector perpendicular to the plane\r\nof the plot, see Section~\\ref{area}. Two formats are provided to define the axis\r\nperpendicular to the plane of the plot; these formats use radically different\r\nconcepts, so users are cautioned to verify that they understand both\r\ndefinitions and the distinction between them.\r\n(a) an atom number can be used, and (b) an absolute Cartesian coordinate\r\ncan be specified.\r\n\r\n\\begin{description}\r\n\\item[Definition by atom number]~\\\\\r\nFormat: \\comp{LINE=$n$}  The axis of the plot is defined  by the vector drawn\r\nfrom  atom $n$ to the defined center of the plot. Thus if atom $n$ has\r\nCartesian coordinates (x=0.5, y=1.4, z=0.2) and the center of the plot is at\r\npoint (x=0.5, y=1.4, z=-0.8) then the axis of the plot is (0.0, 0.0, 1.0).\r\nDummy atoms are not counted, so if any dummy atoms were used in the definition\r\nof the geometry, they must be ignored when considering the atom number. In\r\nother words, only a real atom can be used to define the axis of the graph.\r\n\r\n\\item[Definition by absolute Cartesian coordinate]~\\\\\r\nThe vector need not be  normalized, but must not be of zero length.\r\n\r\nFormat: \\comp{LINE=($n.nn$,$n.nn$,$n.nn$)} The axis of a  line perpendicular to\r\nthe plane of the plot is ($n.nn$,$n.nn$,$n.nn$). This axis need not be\r\nnormalized, but must be finite; that is, the only axis not allowed is (0,0,0).\r\n\\end{description}\r\n\r\nIrrespective of which option is used, the axis of the plot will be converted\r\ninternally into a unit vector in Cartesian coordinates.\r\n\r\n\\subsubsection*{\\comp{LUMO}\\index{LUMO!use in DENSITY}}\r\nFor closed-shell systems with non-degenerate lowest unoccupied molecular\r\norbitals, the key-word \\comp{LUMO} can be used to produce an intensity map of\r\nthe lowest unoccupied molecular orbital. For other systems, the key-word\r\n\\comp{PSI=$n$} should be used.\r\n\r\n\\subsubsection*{\\comp{MULT=$n.nn$}\\index{MULT}}\r\nThere is a default scale for the relief of a plot, when viewed as a 3-D\r\nstructure. If this default is not suitable, say the plot is too flat, then\r\n\\comp{MULT=$n.nn$} can be used to change the vertical scale.  \\comp{MULT=1.0}\r\nwill do nothing, \\comp{MULT=2.0} will increase the vertical relief.\r\n\r\n\\subsubsection*{\\comp{OCCUPANCY}\\index{OCCUPANCY}}\r\nWhen the user wants to explicitly define an electronic configuration for a\r\nsystem, \\comp{OCCUPANCY} is used. This key-word requires the explicit occupancy\r\nof the M.O.s to be defined on the next line, in I1 format. For example, to\r\ndefine methane with one electron in each of the three triply-degenerate levels,\r\nthe lines\r\n\\begin{verbatim}\r\nLine 1:CENTER=1 LINE=(0.0,0.0,1.0) OCCUPANCY EDGE=2.0\r\nLine 2:2111\r\n\\end{verbatim}\r\ncould be used. Similarly, if an excited ethoxy radical were to be specified,\r\nthe following definition could be used:\r\n\\begin{verbatim}\r\nLine 1:CENTER=(0.7,0.0,0.0) LINE=(0.0,0.0,1.0) OCCUPANCY EDGE=2.0\r\nLine 2:22222201\r\n\\end{verbatim}\r\n\r\n\\subsubsection*{\\comp{PHASE}\\index{PHASE}}\r\nTwo formats for this are possible. If \\comp{PHASE} is specified, the data being\r\nadded to the plot is multiplied by -1, i.e.\\ negated.  If \\comp{PHASE=$n.nnnn$}\r\nis used, the data are multiplied by $n.nnnn$. For example, to form the\r\nnormalized M.O.\\ of formaldehyde resulting from equal and opposite amounts of\r\nthe second and third M.O.s, i.e.\\ 0.7071(M.O.2 $-$ M.O.3), the following  data\r\ncould be used.\r\n\\begin{verbatim}\r\nLine 1:\r\nLine 2:   FORMALDEHYDE\r\nLine 3: CENTER=2 LINE=(0,0,1) EDGE=1 PSI=2 PHASE=0.7071 ADD\r\nLine 4: CENTER=2 LINE=(0,0,1) EDGE=1 PSI=3 PHASE=-0.7071\r\nLine 5:\r\n\\end{verbatim}\r\nNote that the first phase is positive. It is not the plot that is reversed,\r\nonly the data going in to the plot, so that the data arising from line 4 are to\r\nbe multiplied by -0.7071 before being added to the plot.\r\n\r\n\\subsubsection*{\\comp{PSI=$n$}}\r\nA specified molecular orbital is to be plotted. Note that degenerate M.O.s\r\ncannot be unambiguously represented, as they are ill-defined by a random\r\nunitary transform. To plot degenerate M.O.s the user should be prepared to use\r\n\\comp{PHASE} and \\comp{ADD}.\r\n\r\n\\subsection{Calculation of Excited State Density}\r\nExcited states can be represented by a linear combination of Slater\r\ndeterminants.  As far as electron density is concerned, each determinant, or\r\n{\\em microstate}, can be represented by a set of molecular orbital occupancies,\r\nwithout regard for spin.  By use of \\comp{OCCUPANCY}, any spin-free microstate\r\ncan be defined.  These facts can be used in the calculation of state densities.\r\n\r\nState densities can be calculated by adding together the densities arising from\r\nvarious microstates, weighted by their contribution to the overall state.\r\nThe weight is given simply by the square of the coefficient of the microstate\r\nin the state.\r\n\r\nAs an example, consider the state density arising from the fourth state in\r\nformaldehyde.  Keywords used in MOPAC would be:\\\\ \\comp{LARGE MECI PRECISE\r\nGRADIENTS C.I.=2  ROOT=4 GRAPH} \\\\ and the microstates used in the MECI\r\ncalculation are shown in Figure~\\ref{fourth}. In this system, the HOMO is\r\nmolecular orbital 6, and the LUMO is molecular orbital 7.\r\n\r\n\\begin{figure}\r\n\\begin{makeimage}\r\n\\end{makeimage}\r\n\\begin{center}\r\n\\input{pic_ci2}\r\n\\end{center}\r\n\\caption{\\label{fourth}Configurations used with C.I.=2}\r\n\\end{figure}\r\n\r\nThe linear combinations of microstates in the state functions are given in the\r\noutput, as shown in Figure~\\ref{ci_output}.\r\n\r\n\\begin{figure}\r\n\\begin{makeimage}\r\n\\end{makeimage}\r\n\\begin{verbatim}\r\n   Root No.    1       2       3       4\r\n\r\n              1 A1    1 A2    2 A2    2 A1\r\n\r\n               0.0     2.5     2.9     7.5\r\n\r\n         1  0.9997  0.0000  0.0000  0.0256\r\n         2  0.0000  0.7071 -0.7071  0.0000\r\n         3  0.0000  0.7071  0.7071  0.0000\r\n         4 -0.0256  0.0000  0.0000  0.9997\r\n\\end{verbatim}\r\n\\caption{\\label{ci_output}State functions in Formaldehyde arising from C.I.=2}\r\n\\end{figure}\r\n\r\nThe electron density contour map for the fourth state can be generated by use\r\nof \\comp{OCCUPANCY}, \\comp{ADD}, and \\comp{MULT}, thus:\r\n\\compresstable\r\n\\begin{verbatim}\r\n   Formaldehyde, Electron Density for the fourth state\r\nCENTER=(0.7,0.0,0.1) LINE=(0.0,0.0,1.0) EDGE=3.0 OCCUPANCY PHASE=0.000655 add\r\n2222220\r\nCENTER=(0.7,0.0,0.1) LINE=(0.0,0.0,1.0) EDGE=3.0 OCCUPANCY PHASE=0.999400\r\n2222202\r\n\\end{verbatim}\r\n\\normalsize\r\nThe corresponding data set for DENSITY for the third state would be:\r\n\\compresstable\r\n\\begin{verbatim}\r\n   Formaldehyde, Electron Density for the third state\r\nCENTER=(0.7,0.0,0.1) LINE=(0.0,0.0,1.0) EDGE=3.0 OCCUPANCY PHASE=0.500000 add\r\n2222211\r\nCENTER=(0.7,0.0,0.1) LINE=(0.0,0.0,1.0) EDGE=3.0 OCCUPANCY PHASE=0.500000\r\n2222211\r\n\\end{verbatim}\r\n\\normalsize\r\nHowever, because the electron density arising from microstates 2 and 3 is the\r\nsame, this data set could be written in a more compact form, thus:\r\n\\compresstable\r\n\\begin{verbatim}\r\n   Formaldehyde, Electron Density for the third State\r\nCENTER=(0.7,0.0,0.1) LINE=(0.0,0.0,1.0) EDGE=3.0 OCCUPANCY\r\n2222211\r\n\\end{verbatim}\r\n\\normalsize\r\nFinally, note that the electron density distribution for the second and third\r\nstates are the same.  With \\comp{C.I.=2}, the first excited state, a triplet,\r\nand the second excited state, the first excited singlet, have the same electron\r\ndensity everywhere.\r\n\r\n\\subsection{Definition of the area of the graph plot}\\label{area}\r\nThe graph plot is a square, which represents a slice or cut through the volume\r\nof a molecule. To define a square, seven numbers are needed. In order, these\r\nare:\r\n\\begin{itemize}\r\n\\item Three numbers to define the position of the center of the square.\r\n\\item Three numbers to define an axis perpendicular to the surface of the square.\r\n\\item One number to define the length of the edge of the square.\r\n\\end{itemize}\r\nTo specify the center of the square, the key-word \\comp{CENTER} is  provided.\r\n\\comp{CENTER} can be either an atom number, e.g.\\ \\comp{CENTER=4}, or an\r\nabsolute Cartesian  coordinate, e.g.\\ \\comp{CENTER=(0.6,0.5,2.4)}. If an atom\r\nis used, the absolute Cartesian coordinates of that atom are used to define the\r\ncenter of the square. In either case, the center of the square, i.e.\\ the\r\nintersection of the two diagonals of the square, is defined by the resulting\r\nabsolute Cartesian coordinate.\r\n\r\nExamples:\r\n\\begin{itemize}\r\n\\item Methane, center of plot to be on one of the hydrogen atoms, these\r\nbeing atoms 1, 3, 4, and 5. Use \\comp{CENTER=1} or \\comp{CENTER=3} etc.; as an\r\nalternative, assuming the first atom is at the origin,\r\n\\comp{CENTER=(0.0,0.0,0.0)} could be used.\r\n\\item Benzene, given Cartesian coordinates as follows:\r\n\\begin{verbatim}\r\n             X         Y         Z\r\n  C1       0.0000    0.0000    0.0000\r\n  C2       1.4066    0.0000    0.0000\r\n  C3       2.1099    1.2182    0.0000\r\n  C4       1.4066    2.4363    0.0000\r\n  C5       0.0000    2.4363    0.0000\r\n  C6      -0.7033    1.2182    0.0000\r\n  H1      -0.5451   -0.9442    0.0000\r\n  H2      -0.5451    3.3805    0.0000\r\n  H3       1.9517   -0.9442    0.0000\r\n  H4      -1.7935    1.2182    0.0000\r\n  H5       3.2002    1.2182    0.0000\r\n  H6       1.9517    3.3805    0.0000\r\n\\end{verbatim}\r\nThen, if a plot of benzene with the center of the molecule at the middle\r\nof the picture, \\comp{CENTER=(0.7,1.2,0.0)} could be used.\r\n\\item Benzene, $\\pi$-system. Using the above Cartesian coordinates for the\r\nbenzene ring, the center of the plot must be above the plane of the\r\nring in order to avoid the nodes in the $\\pi$-system. In this case\r\n\\comp{CENTER=(0.7,1.2,0.5)} would be appropriate.\r\n\\end{itemize}\r\n Once the center of the plot is defined, the orientation of the plane\r\nof the plot needs to be specified. Thus if a plot of methane was wanted,\r\nand the center of the plot was on the carbon atom, the following\r\ncross-sections could be drawn:\r\n\\begin{itemize}\r\n\\item Four-fold symmetry: Plot is oriented in the reflection plane of the\r\nS$_4$ symmetry operation. To specify this, absolute Cartesian\r\ncoordinates would need to be used.\r\n\\item Three-fold symmetry: Axis of plot is from carbon to any hydrogen.\r\nTo specify this, \\comp{LINE=4} could be used.\r\n\\item Showing two C-H bonds: Given that the first three atoms are H, C, and\r\nH, then the axis (0.0,0.0,1.0) would be perpendicular to the plane\r\nof  these three atoms (assuming that all three atoms had the same z component).\r\n\\end{itemize}\r\n It might be helpful in visualizing the axis of the plot by imagining the plot\r\nwithout the line specified. The center of the plot is already defined, but\r\nthe square is still free to rotate in all three dimensions, so only one\r\npoint in the square is defined. The plane of the plot is then\r\ndefined by \\comp{LINE}.\r\n\r\nThe final unknown is the size of the plot. This is\r\nspecified by \\comp{EDGE=$n.nn$}.\r\nThe length $n.nn$ defines the length, in \\AA ngstroms, of the side of the plot.\r\nNote that most molecules are bigger than their simple atomic coordinates\r\nwould suggest. As an example, to get a benzene ring to fit inside a plot,\r\n\\comp{EDGE=6.0} would be needed, even though the H-H distance across the ring is\r\nonly 4.8-5.0 \\AA ngstroms.\r\n\\section{Details of Graph Plots}\r\n\\subsection{Contours}\\index{Contours}\r\n There are normally between 10 and 25 contours. The contours are separated\r\nby steps of size 1, 2.5, and 5 times 10 to some integer power. The most\r\ncommon step sizes are:\r\n\\begin{verbatim}\r\n 0.0010, 0.0025, 0.0050, 0.0100, 0.0250, 0.0500,\r\n 0.1000, 0.2500, 0.5000, 1.0000, 2.5000, 5.0000\r\n\\end{verbatim}\r\nin units of electrons per cubic \\AA ngstrom, for electron density, and\r\nthe square root of these units for wave-functions.\r\n\r\n The flexible nature of the step size means that the user can expect to see\r\nsomething in the picture, but close attention should be paid to the contour\r\ninterval. If the step size is excessively small, less than 0.00001,\r\nthe user will be warned, but the calculation will be continued.\r\n\r\n\\subsection{Density Around Atoms}\r\n All Slater atomic orbitals have a node at the nucleus, with the\r\nimportant exception\r\nof hydrogen. One result of this is that hydrogen is the only element whose\r\nelectron density has a maximum at the nucleus. All other atoms have an almost\r\nzero electron density at their nucleus. This is usually disconcerting\r\nat first sight,\r\nbut is a consequence of the behavior of Slater-type orbitals.\r\n For planar systems, it is a good idea to plot the density in the plane\r\na fraction of an \\AA ngstrom above the plane of the molecule.\r\n\\subsection{Difference Maps}\\index{Difference maps}\r\n A difference map shows where electron density builds up when bonds are\r\nformed. It will NOT show ionic character. To form a \\comp{BONDS} map\r\nthe electron density arising from the atoms is spherically averaged and\r\nthen subtracted from the density matrix. For example, suppose the atomic\r\norbital populations on an atom arising from the un-renormalized eigenvectors\r\nare  1.0, 1.1, 1.2, and 1.3 for $s$, $p_x$, $p_y$, and $p_z$,\r\nrespectively. Then the\r\nspherically averaged populations are 1.0, 1.2, 1.2, and 1.2 for these atomic\r\norbitals.\r\n\\subsection{Renormalization of Molecular Orbitals}\r\n  All maps are calculated from data originally derived from the supplied\r\nmolecular orbitals. These M.O.s are presumed to be un-renormalized: that\r\nis, the sum of the squares of the coefficients of the M.O.s add to unity.\r\nThe first step, therefore, is to re-normalize the M.O.s. This is done\r\nby matrix multiplying the starting eigenvector matrix by the\r\ninverse-square-root of the overlap matrix. This requires the presence of\r\nthe inverse-square-root of the overlap matrix, which must be supplied by\r\nthe MOPAC file. If re-normalization is not done, the total\r\nelectron density would be too large, and the difference maps would be\r\nquite incorrect.\r\n\r\n\r\n\\section{Programming Considerations}\r\n DENSITY is not intended to be a ``stand-alone'' program. Its main purpose\r\nis to be run using data generated by an earlier MOPAC calculation.\r\nResults from DENSITY need some further processing before a hard-copy\r\ngraph-plot is obtained.\r\n In order, then, the unformatted data required from\r\na MOPAC type calculation to be used as auxiliary\r\ndata for DENSITY are as follows:\r\n\r\nRecord:\r\n\r\n\\begin{enumerate}\r\n\\item Number of Atoms, Number of Orbitals, Number of Electrons,\r\nX-Cartesian coordinates for all atoms, Y-Cartesian coordinates for all atoms,\r\nZ-Cartesian coordinates for all atoms.\r\n\\item Stopping and starting orbital counters for all atoms.\r\n\\item $s$-orbital exponents for all atoms, $p$-orbital exponents for all atoms,\r\n$d$-orbital exponents for all atoms. Atomic numbers for all atoms.\r\n\\item All the un-renormalized eigenvectors, atomic orbital indices running\r\nfastest.\r\n\\item Lower half triangle of the inverse-square-root of the overlap matrix.\r\n\\end{enumerate}\r\n DENSITY produces a default file suitable for a plotting program to use.\r\nThis file has the following format:\r\n\r\n Line 1: This line consists of the single, unchanging, message\r\n\\begin{verbatim}\r\n                    NUMBER OF CONTOURS =  nn,\r\n\\end{verbatim}\r\nwith  $nn$  the actual number of different contours supplied. The programmer\r\ncan use this message to detect the start of a contouring file, and, if\r\ndesired, make use of the number nn to decide what action to take.\r\n\r\n Lines 2-4: Text. The programmer should print these lines without assuming\r\nthat the text makes any sense.\r\n\r\n Lines 5 on: The layout of these lines is as follows:\r\n\\begin{verbatim}\r\n     <x-coordinate> <y-coordinate> <Pen code>  <Contour Height>\r\n\\end{verbatim}\r\nAs the whole plot is within the range 0.0 to 1.0, the x- and y-coordinates\r\nare fractions of unity. The pen code is integer, 1 for pen up, 2 for pen down.\r\nThe contour height is real, and self-explanatory.\r\n\r\n Near to the end of the file is a single contour of height 99.999. This\r\n ``contour''\r\ndraws a box around the plot.\r\n\r\n Finally, the last few lines are the chemical symbols. These use the\r\nsame layout as Lines 5 on, but in place of the pen code, the chemical symbols\r\nare present.\r\nIf this output is not\r\nsuitable, the programmer should modify subroutine PLOTGR.\r\n\r\n\\section{Description of Program}\r\n\\subsection{Fortran Files}\r\n DENSITY consists of several FORTRAN-77 files. These are:\r\n\\begin{description}\r\n\\item[CNTOUR] A general 2 or 3-dimensional contour-drawing subroutine.\r\n\\item[DRAW] A subroutine to draw one contour.\r\n\\item[EULER] Rotates a point in 3-D space.\r\n\\item[DATIN] Reads in data defining one particular picture.\r\n\\item[MAIN] Main segment; generates array for contouring.\r\n\\item[MAXMIN] Calculates highest and lowest points in the picture.\r\n\\item[PLOTGR] Interface between FORTRAN-77 and graphics routine.\r\n\\item[READIN] Gets in data defining molecule\r\n\\item[PLOTGR] Generates data for graph plotter.\r\n\\end{description}\r\n\r\n\\subsection{Description of FORTRAN Files}\r\n\\paragraph*{CNTOUR}\\index{CNTOUR}\r\nCNTOUR is a general contour-drawing routine. It calls subroutines\r\nDRAW, EULER, and MAXMIN. The contour map can be tilted to show the\r\nthree-dimensional structure of the density map.\r\n\r\n\\paragraph*{DRAW}\r\n Draws a single contour, given a starting address. Called by CNTOUR\r\nto allow users to rapidly write their own interfaces.\r\n\r\n\\paragraph*{EULER}\\index{EULER}\r\n Performs a three-dimensional rotation on a three-dimensional\r\npoint provided; the resulting point is then used as a data\r\npoint for plotting.\r\n\r\n\\paragraph*{DATIN}\r\n All the user-supplied data defining a picture are read in in DATIN.\r\nSome checking is done to ensure that the key-words provided are\r\ncompatible.\r\n\r\n\\paragraph*{MAIN}\r\n The main program, generates the wave-function in terms of atomic\r\norbitals, this is then used to calculate the pixel array, which in\r\nturn is used by the contouring subroutine.\r\n\r\n\\paragraph*{MAXMIN}\r\n Prints the values and positions of the maxima and minima on the plot.\r\nNo data are altered by a call to MAXMIN.\r\n\r\n\\paragraph*{PLOTGR}\\index{PLOTGR}\r\n The interface between FORTRAN-77 and the graphics routines is provided\r\nby PLOTGR. Only very simple graphics commands are used, in order to\r\npermit easy conversion of the program to run on other machines.\r\nProgrammers will need to change PLOTGR to suit local equipment.\r\n\r\n\\section{Installing Density}\r\nDENSITY is distributed with MOPAC, and is normally written\r\nto the sub-directories \\comp{\\ldots/density\\_source/} and\r\n\\comp{\\ldots/density\\_examples}.\r\n\r\nThe parameter file SIZES should be read and, if necessary, modified before\r\n\\comp{Makefile} is run. The two parameters within SIZES that the user can\r\nmodify are MAXLIT and MAXHEV. MAXLIT is assigned a value equal to the largest\r\nnumber of hydrogen atoms that a DENSITY job is expected to run, MAXHEV is\r\nassigned the corresponding number of heavy (non-hydrogen) atoms.\r\n\r\nOnce you are satisfied with the contents of SIZES, compile DENSITY by issuing\r\nthe command `make'. Once this is complete, there is no  reason to keep the\r\nobject  files, and if space is at a premium these can be deleted at this time.\r\nThey should be kept if modifications are to be made to the program, in order to\r\nallow rapid re-linking with the modified subroutines.\r\n\r\n\\section{Running DENSITY}\r\nThe command \\comp{density} followed by a filename will start an on-line DENSITY\r\njob.   E.g.\\ \\comp{density ethylene}, where \\comp{ethylene.gra} is the data-set\r\nfor DENSITY, and a calculation of ethylene had been run earlier using MOPAC.\r\n\r\nThe main files that are required by DENSITY are:\r\n\\begin{center}\r\n\\begin{tabular}{ccl}\r\n           File    &      Channel  &   Description \\\\ \\hline\r\n         \\comp{$<$filename$>$.gpt}  &  13 &   MOPAC generated file. \\\\\r\n         \\comp{$<$filename$>$.gra}  &   5 &   User-generated data file \\\\\r\n\\end{tabular}\r\n\\end{center}\r\nThe main files that are produced are:\r\n\\begin{center}\r\n\\begin{tabular}{ccl}\r\n           File     &    Channel &   Description  \\\\ \\hline\r\n        \\comp{$<$filename$>$.out} &    6 &  Results  \\\\\r\n        \\comp{$<$filename$>$.tec} &   15 &  Formatted file of graph-plot \\\\\r\n                                            for use by a graphics program. \\\\\r\n\\end{tabular}\r\n\\end{center}\r\n", "meta": {"hexsha": "9bc8310488aa2aca06918b3792758d593547c140", "size": 49643, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "manuals/MOPAC2000_manual/density.tex", "max_stars_repo_name": "openmopac/MOPAC-archive", "max_stars_repo_head_hexsha": "01510e44246de34a991529297a10bcf831336038", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-16T20:53:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T20:54:11.000Z", "max_issues_repo_path": "manuals/MOPAC2000_manual/density.tex", "max_issues_repo_name": "openmopac/MOPAC-archive", "max_issues_repo_head_hexsha": "01510e44246de34a991529297a10bcf831336038", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "manuals/MOPAC2000_manual/density.tex", "max_forks_repo_name": "openmopac/MOPAC-archive", "max_forks_repo_head_hexsha": "01510e44246de34a991529297a10bcf831336038", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.8446251129, "max_line_length": 169, "alphanum_fraction": 0.707632496, "num_tokens": 14677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.314662960143282}}
{"text": "The Wave Action Equation in Cartesian  (\\ref{eq:bal_plane}) or spherical  (\\ref{eq:bal_sphere}) coordinates is the basic\nequations of the wave model. However, modified versions of these equations are\nused in the model, where (a) they are solved on a variable wavenumber grid\n(see below), where (b) modified versions of these equations are used to\nproperly describe dispersion for discretized equations in selected numerical\nschemes (see \\para\\ref{sub:xy_prop}), and where (c) sub-grid obstacles such as\nislands are considered (see \\para\\ref{sub:xy_prop}).\n\n\n\\vssub\n\\subsection{~Spectral discretization} \\label{sec:basic_num}\n\\vsssub\n\n\nIf Eq. (\\ref{eq:bal_plane}) or Eq. (\\ref{eq:bal_sphere}) is solved directly, an\neffective reduction of spectral resolution occurs in shallow water\n\\citep[see][]{tol:GAOS98b}. This loss of resolution can be avoided if the\nequation is solved on a variable wavenumber grid, which implicitly\nincorporates the kinematic wavenumber changes due to shoaling. Such a\nwavenumber grid corresponds to a spatially and temporally invariant\ngrid in relative frequency \\citep{tol:GAOS98b}. The corresponding local wavenumber grid can be\ncalculated directly from the invariant frequency grid and the dispersion\nrelation (\\ref{eq:disp}), and hence becomes a function of the local depth\n$d$. To accommodate economical calculations of $S_{nl}$ and allow a good separation of swell frequencies, a frequency discretization with \nexponentially increasing increments is adopted, so that the varying frequency resolution is proportional to the local frequency, \n\n%----------------------------%\n% Exponential frequency grid %\n%----------------------------%\n% eq:sigma_grid\n\n\\begin{equation}\n\\sigma_{m+1} = X_\\sigma \\, \\sigma_m \\: , \\label{eq:sigma_grid}\n\\end{equation}\n\n\\noindent\nwhere $m$ is a discrete grid counter in $k$-space. $X_\\sigma$ is defined by\nthe user in the input files of the program. Traditionally, in most\napplications of third-generation models $X_\\sigma \\simeq 1.1$ is used.\n\nThe effects of a spatially varying grid will be discussed for the Cartesian\nEq. (\\ref{eq:bal_plane}) only. Adaptation to the spherical grid is\ntrivial. Denoting the variable wavenumber grid with $\\kappa$, the balance\nequation becomes\n\n%------------------------------%\n% general equations kappa-grid %\n%------------------------------%\n% eq:bal_f_grid\n% eq:sigma_dot\n\n\\begin{equation}\n\\frac{\\p}{\\p t} \\frac{N}{c_g} +  \n\\frac{\\p}{\\p x} \\frac{\\dot{x} N}{c_g} + \n\\frac{\\p}{\\p y} \\frac{\\dot{y} N}{c_g} + \n\\frac{\\p}{\\p \\kappa} \\frac{\\dot{\\kappa} N}{c_g} + \n\\frac{\\p}{\\p \\theta} \\frac{\\dot{\\theta} N}{c_g}  =\n\\frac{S}{\\sigma c_g} \\: , \\label{eq:bal_f_grid} \\end{equation} \\begin{equation}\n\\dot{\\kappa} \\:\\frac{\\p k}{\\p \\kappa} =\n     c_g^{-1} \\frac{\\p \\sigma}{\\p d} \\left (\n    \\frac{\\p d}{\\p t} + {\\bf U} \\cdot \\nabla_x d \\: \\right ) -\n    {\\bf k} \\cdot \\frac{\\p {\\bf U}}{\\p s}\n\\: . \\label{eq:sigma_dot}\n\\end{equation}\n\n\\noindent\n\n\\vssub\n\\subsection{~Splitting of the wave action equation} \\label{sec:basic_num}\n\\vsssub\n\nIn \\ws\\, Eq. (\\ref{eq:bal_f_grid}) is solved using a fractional step method. \nThe first step treats the temporal variations of\nthe depth, and corresponding changes in the wavenumber grid. As is discussed\nby \\cite{tol:GAOS98b}, this step can be invoked sparsely. By splitting off\neffects of (temporal) water level variations, the grid becomes invariant, and\nthe depth becomes quasi-steady for the remaining fractional steps. Other\nfractional steps consider spatial propagation, intra-spectral propagation and\nsource terms. Starting with version 5.10, the source term $S$ is further split into \nnon-ice $S_{no~ice}$ and ice $S_{ice}$ source term. For a single model grid, the following sequence of integration  is performed \nby the {\\code W3WAVE} routine:\n\\begin{itemize}\n \\item[1.] Update of water level \n \\item[2.] Intra-spectral part 1: integration over $\\Delta t_g/2$ of  $\\frac{\\p}{\\p t} \\frac{N}{c_g} + \\frac{\\p}{\\p \\kappa} \\frac{\\dot{\\kappa} N}{c_g} + \\frac{\\p}{\\p \\theta} \\frac{\\dot{\\theta} N}{c_g}  =0 $ \n \\item[3.] Spatial propagation: integration over $\\Delta t_g$ of $\\frac{\\p}{\\p t} \\frac{N}{c_g} +  \n\\frac{\\p}{\\p x} \\frac{\\dot{x} N}{c_g} + \n\\frac{\\p}{\\p y} \\frac{\\dot{y} N}{c_g}  = 0$\n \\item[4.] Intra-spectral part 2: integration over $\\Delta t_g/2$ of  $\\frac{\\p}{\\p t} \\frac{N}{c_g} + \\frac{\\p}{\\p \\kappa} \\frac{\\dot{\\kappa} N}{c_g} + \\frac{\\p}{\\p \\theta} \\frac{\\dot{\\theta} N}{c_g}  =0 $ \n \\item[5.] Source term integration: integration over $\\Delta t_g$ of $\\frac{\\p}{\\p t} \\frac{N}{c_g}   = \\frac{S_{no~ice}}{\\sigma c_g}$\n \\item[6.] Ice source term integration: integration over $\\Delta t_g$ of $\\frac{\\p}{\\p t} \\frac{N}{c_g}   = \\frac{S_{ice}}{\\sigma c_g}$ \n\\end{itemize}\nThe succession of these 6 steps is, in the limit $\\Delta t_g \\rightarrow 0$, equivalent to the integration of Eq. (\\ref{eq:bal_f_grid}) over a global \ntime step $\\Delta t_g$. \n\nThis splitting in multiple steps allows an  efficient \nvectorization and parallelization at the same time. The time splitting furthermore\nallows for the use of separate partial or dynamically adjusted time steps in\nthe different fractional steps of the model. \\ws\\ makes a distinction between\n4 different time steps. \\label{dt_list}\n\n\\begin{list}{xx}{\\itemsep 0mm \\parsep 0mm \\rightmargin 5mm}\n\n\\item[1)] The `global' time step $\\Delta t_g$, is the common step of all the splitted sub-integrations. In that sense, \nit is the smallest time step for which a physically meaningful solution can be obtained, because all terms in the equation have been \nintegrated. As a result, this is a possible time step for evaluating model output or coupling with other models, \nand, in the case of a multi-grid system,  it is the time step at which communication \nbetween grids is performed. In the case of a forced -- not coupled -- model, input winds and currents are\ninterpolated at this global step. This time step is provided by the user in the input file of {\\code ww3\\_grid}, but can be reduced\nwithin the model to reach a requested input or output time.\n\n\\item[2)] The second time step is the time step for spatial propagation. This is not used for triangular-based \ngrids, for which the advection step is -- in the case of explicit schemes -- adjusted internally for each spectral component. For other grid types, the\nuser supplies a reference maximum propagation time step for the lowest model\nfrequency $\\Delta t_{p,r}$, assuming no currents, and no grid motion. For the\nfrequency with counter $m$, the maximum time step $\\Delta t_{p,m}$ is\ncalculated within the model as\n\n%-------------------------%\n% Time stepping equations %\n%-------------------------%\n% eq:dtpl\n\n\\begin{equation}\n\\Delta t_{p,m} = \\frac{{\\dot{x}}_{p,r}}{{\\dot{x}}_{p,m}} \\Delta t_{p,r}\n\\: , \\label{eq:dtpl} \\end{equation}\n\n\\noindent\nwhere $\\dot{x}_{p,r}$ is the maximum advection speed for the longest waves\nwithout currents or grid motion, and $\\dot{x}_{p,m}$ is the actual maximum\nadvection speed (including current) for frequency $m$. If the propagation time\nstep is smaller than the global time step, the propagation effects are\ncalculated with a number of successive smaller time steps. This generally\nimplies that several partial time steps are used for the lowest frequency, but\nthat the highest frequencies are propagated over the interval $\\Delta t_g$\nwith a single calculation. The latter results in a significantly more\nefficient model, particularly if higher-order accurate propagation schemes are\nused. Note that $\\Delta t_{p,m}$ may be defined bigger than $\\Delta t_g$, and\nthat this has potential impact in model economy for cases with (strong)\ncurrents.\n\n\\item[3)] The third time step is the time step for intra-spectral\npropagation. For large-scale and deep-water grids this time step can generally\nbe taken equal to the global time step $\\Delta t_g$. For shallow water grids,\nsmaller intra-spectral propagation time steps allow for larger effects of\nrefraction within the stability constraints of the scheme. Note that the order\nof invoking spatial and intra-spectral propagation is alternated to enhance\nnumerical accuracy. If strong refraction of long period swells occur, this may\nresult in a notable undulation of mean wave parameters. This can be avoided by\nsetting this time step to an even integer fraction of $\\Delta t_g$.\n\n\\item[4)] The final time step is the time step for the integration of the\nsource terms, which is dynamically adjusted for each separate grid point and\nglobal time step $\\Delta t_g$ (see \\para~\\ref{sub:source}). This results in\nmore accurate calculations for rapidly changing wind and wave conditions, and\na more economical integration for slowly varying conditions. In order to limit the \ncalculation time, a minimum time step is defined by the user. \n\n\\end{list}\n\n\\vspace{\\baselineskip} \\noindent \n\nThe following sections deal with the separate steps in the fractional step\nmethod, and various subjects associated with this.  The main issue are covered\nin \\para\\ref{sub:num_depth}, which addresses treatment of temporal variations\nof the water depth, \\para\\ref{sub:xy_prop} which addresses spatial\npropagation, \\para\\ref{sub:spec} which addresses intra-spectral propagation,\nand Sections \\ref{sub:source} and \\ref{sub:icesource} which address the numerical \nintegration of non-icea and ice source\nterms.  The other sections deal with additional\nnumerical approaches and techniques, covering the treatment of winds and\ncurrents (\\para\\ref{sub:num_w_c}), including tides (\\para\\ref{sub:num_tide}), calculating space-time extremes (\\para\\ref{sub:space_time_ext}), treatment\nof ice (\\para\\ref{sub:num_ice}), spectral partitioning and the corresponding\ntracking of wave systems in space and time (Sections \\ref{sub:num_part},\n\\ref{sub:num_track}), and nesting (\\para\\ref{sub:num_nest}).\n", "meta": {"hexsha": "6e59bf178da94f8dc01ddbcb338b2f0cda0939dd", "size": 9786, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "WW3/manual/num/basics.tex", "max_stars_repo_name": "minsukji/ci-debug", "max_stars_repo_head_hexsha": "3e8bbbe6652b702b61d2896612f6aa8e4aa6c803", "max_stars_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WW3/manual/num/basics.tex", "max_issues_repo_name": "minsukji/ci-debug", "max_issues_repo_head_hexsha": "3e8bbbe6652b702b61d2896612f6aa8e4aa6c803", "max_issues_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-05-31T15:49:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-04T14:17:45.000Z", "max_forks_repo_path": "WW3/manual/num/basics.tex", "max_forks_repo_name": "minsukji/ci-debug", "max_forks_repo_head_hexsha": "3e8bbbe6652b702b61d2896612f6aa8e4aa6c803", "max_forks_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-01T09:29:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T09:29:46.000Z", "avg_line_length": 55.92, "max_line_length": 207, "alphanum_fraction": 0.7360515021, "num_tokens": 2644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.3145802642480249}}
{"text": "\\subsubsection{\\stid{3.12} Sub-project: hypre}\n\n\\paragraph{Overview}\nThe {\\sl hypre} software library \\cite{hypre:homepage,hypre_design_impl_2006} provides high performance preconditioners and solvers for the solution of large sparse linear systems on massively parallel computers, with particular focus on algebraic multigrid solvers. One of {\\sl hypre}’s unique features is the provision of a (semi)-structured interface, in addition to a traditional linear-algebra based interface. The semi-structured interface is appropriate for applications whose grids are mostly structured, but with some unstructured features. Examples include block-structured grids, composite grids in structured adaptive mesh refinement (AMR) applications, and overset grids. These interfaces give application users a more natural means for describing their linear systems, and provide access to methods such as structured multigrid solvers, which can take advantage of the additional information beyond just the matrix. Since current architecture trends are favoring regular compute patterns to achieve high performance, the ability to express structure has become much more important. The {\\sl hypre} library provides both unstructured and structured multigrid solvers, which have shown excellent scalability on a variety of high performance computers, e.g Blue Gene systems (unstructured solver BoomerAMG has scaled up to 1.25 million MPI cores with a total of 4.5 million hardware threads). It is used by many ECP application teams, including ExaAM, Subsurface, ExaWind, CEED, and more. It requires a C compiler and an MPI implementation, but it also runs in an OpenMP environment. It also has GPU capabilities.\n\n\\paragraph{Key  Challenges}\n\nWhile {\\sl hypre}'s solvers contain much parallelism, their main focus is the solution of sparse linear systems, leading to  very large demands on memory bandwidth. In addition, the use of multiple levels, while greatly aiding convergence of the solvers, leads to decreasing systems sizes, number of operations and parallel efficiencies on coarser levels. Particularly the unstructured algebraic multigrid solver BoomerAMG\\cite{HeYa2002}, which is {\\sl hypre}'s most often used preconditioner, suffers from increasing communication complexities on coarser levels. Coarse grid operators are generated by multiplying three matrices leading to increasing numbers of nonzeroes per row in the resulting matrices and with it increasing numbers of neighbor processes. While BoomerAMG's solve phase mainly consists of matrix vector products and smoothing operations, which are fairly straight forward to parallelize, even on a GPU, its setup phase is highly complex, including many branches, a lot of integer operations as well as some sequential passages. Previous interpolation strategies that lead to best convergence and performance on distributed memory machines were not suitable for implementation on GPUs or similar architectures requiring extreme parallelism and required new algorithmic approaches. Since {\\sl hypre} is a mature product with many solvers and interdependent features, any significant changes that affect the whole library, are tedious and require much testing to ensure that the library stays backward compatible and no features are broken.\n\n\\paragraph{Solution Strategy}\n\nSince computer architectures continue to change rapidly, it was important to come up with strategies that will facilitate future porting of the software. Therefore we developed and implemented a new memory model that addresses the use of different memory locations.\nSince the upcoming computer architectures are heterogeneous with accelerators, we focus on enabling {\\sl hypre} for GPUs. We have looked into various options, such as the use of CUDA, OpenMP 4.5, as well as RAJA and Kokkos. We limited the latter three options to the structured interface and solvers which are more natural candidates for such an approach due to their use of macros, called BoxLoops, for loops. We adopted a modular approach for the unstructured interface, which relies on the restructuring the solver components to use smaller kernels that are and/or will be implemented in CUDA for Nvidia GPUs. Since hip is similar to CUDA, porting to AMD GPUs has been fairly straight forward. We are now investigating the use of a vendor conversion tool from CUDA to SYCL to port structured and unstructured solvers to upcoming exascale computers with Intel GPUs.\n\n\\paragraph{Recent Progress}\n\nPreviously we had enabled the structured interface and solvers, SMG and PFMG\\cite{AsFa1996}, to completely run on GPUs, using CUDA, OpenMP4.5, RAJA and Kokkos, and have now also added hip to enable use on AMD GPUs.\nFor our unstructured AMG solver BoomerAMG, we had implemented suitable CUDA kernels for setup and solve phase, designed a new class of interpolation operators based on sparse matrix operations\\cite{LiSY2020}, implemented it on GPUs and ported aggressive coarsening to the GPU. Recently, we added Umpire support for memory pooling on GPUs, which can significantly improve performance. We have enabled hypre's specialized solvers, including linear and eigensolvers for Maxwell problems and solvers for H-div problems, to run on Nvidia GPUs. Figure \\ref{fig:AMS-PCG} shows some results for a Maxwell problem using finite elements of increasing order on 1 node of Lassen. We have ported many of the CUDA kernels and routines in the unstructured interface to hip to enable their use on AMD GPUs. We have also developed a new version of multipass interpolation based on matrix-matrix multiplications and implemented it in CUDA and hip. Multipass interpolation is a popular low-memory prolongation used with aggressive coarsening. Figure \\ref{fig:Spock-AMG} shows a comparison of CPU and GPU runtimes on 2 nodes of Spock for a 3D diffusion problem with a 27-point stencil on a $n \\times n \\times n$ grid using AMG-PCG with aggressive coarsening on the first level for increasing $n$.\n\n\\begin{figure}[bth]\n\\centering\n\t\\includegraphics[width=3.9in]{projects/2.3.3-MathLibs/2.3.3.12-SUNDIALS-hypre/AMS-PCG.png}\n\t%\\includegraphics[width=3in]{AMS-PCG.png}\n\t\\caption{\\label{fig:AMS-PCG} Solution of a simple 3D electromagnetic diffusion problem corresponding to the 2nd order definite Maxwell equation  $\\nabla \\times \\nabla \\times E + E = f$ using AMS-PCG on 1 node of Lassen (4 GPUs vs. 40 CPU cores) using finite elements of increasing order on a Fichera mesh.}\n\n\\end{figure}\n\n\\begin{figure}[bth]\n\\centering\n\t\\includegraphics[width=3in]{projects/2.3.3-MathLibs/2.3.3.12-SUNDIALS-hypre/spock-AMG-PCG.png}\n\t%\\includegraphics[width=3in]{spock-AMG-PCG.png}\n\t\\caption{\\label{fig:Spock-AMG} Total times (setup plus solve times) on 2 nodes of Spock using AMG-PCG with aggressive coarsening and multi-pass interpolation for a 3D diffusion problem with a 27-point stencil on a $n \\times n \\times n$ grid. The CPU runs were performed with 8 MPI tasks with 16 OpenMP threads per MPI task, the GPU runs were performed on 8 AMD MI100 GPUs.}\n\n\\end{figure}\n\n\\begin{figure}[bth]\n\\centering\n\t\\includegraphics[width=5in]{projects/2.3.3-MathLibs/2.3.3.12-SUNDIALS-hypre/crusher-AMG-PCG.png}\n\t%\\includegraphics[width=5in]{crusher-AMG-PCG.png}\n\t\\caption{\\label{fig:crusher-AMG} Setup, solve times and Speedups of GPU over CPU performance on 1 node of Crusher using AMG-PCG with three different settings for a 3D diffusion problem with a 27-point stencil on a $n \\times n \\times n$ grid. The CPU runs were performed with 64 MPI tasks, the GPU runs were performed on 8 AMD MI250 GPUs. Solid lines use the GPU default settings, whereas dashed and dotted lines use in addition one level of aggressive coarsening with two-stage and multipass interpolation, respectively.}\n\n\\end{figure}\n\n\\paragraph{Early Access System Experiences}\n\nWe have tested {\\sl hypre} performance on both Spock, see Figure \\ref{fig:Spock-AMG}, and Crusher.  Figure \\ref{fig:crusher-AMG} \nshows the Setup and Solve times for three different settings of AMG for increasing $n$ of a 3D diffusion problem on a $n \\times n \\times n$ grid. Both CPU and GPU runs use the same settings. Solid lines use the default AMG settings, whereas dashed and dotted lines use one level of aggressive coarsening with two-stage and multipass interpolation, respectively. While generally systems in application problems would be in the range of up to $n=300$, we here continue to increase the problem size until the GPU runs reach the memory limit to demonstrate memory usage for these different AMG settings. This is reached first for the default version, which requires a lot of memory, but also achieves the lowest number of iterations, followed by the use of aggressive coarsening with two-stage interpolation. The use of one level of aggressive coarsening combined with multipass interpolation allows solving the largest system illustrated using GPUs, since it has lower memory requirements at the cost of having the worst convergence.  \n\n{\\sl Hypre} release v2.24.0 contains support for Intel GPUs for the structured interface and solvers via SYCL and Kokkos and for the solve phase of unstructured solvers via SYCL. All these features have been tested on Arcticus.\n\n\\paragraph{Next Steps}\n\nWe will pursue the following tasks:\n\n\\begin{itemize}\n\\item We will continue to add new GPU capabilities to {\\sl hypre} and improve the performance of current capabilities. We will thoroughly investigate the performance on AMD GPUs and begin porting to Intel GPUs.\n\\item We will test and evaluate performance of important hypre solvers on AMD and Intel GPUs, improve their performance and port additional components if necessary.\n\\end{itemize}\nIn addition, we will work with ECP application teams who are using {\\sl hypre}, such as ExaWind, ExaAM, AMReX,  to achieve best performance by tuning the solvers for them and potentially implementing suitable algorithmic changes.\n", "meta": {"hexsha": "a0d40c6f86405d08ab65d6ac27ef5338272bad47", "size": 9880, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "projects/2.3.3-MathLibs/2.3.3.12-SUNDIALS-hypre/2.3.3.12-hypre.tex", "max_stars_repo_name": "ulrikeyang/ECP-ST-CAR-PUBLIC", "max_stars_repo_head_hexsha": "4b15fa1ce1e07b1f1e464ad77d47a327cfae1381", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "projects/2.3.3-MathLibs/2.3.3.12-SUNDIALS-hypre/2.3.3.12-hypre.tex", "max_issues_repo_name": "ulrikeyang/ECP-ST-CAR-PUBLIC", "max_issues_repo_head_hexsha": "4b15fa1ce1e07b1f1e464ad77d47a327cfae1381", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-10-07T00:22:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-05T22:02:00.000Z", "max_forks_repo_path": "projects/2.3.3-MathLibs/2.3.3.12-SUNDIALS-hypre/2.3.3.12-hypre.tex", "max_forks_repo_name": "ulrikeyang/ECP-ST-CAR-PUBLIC", "max_forks_repo_head_hexsha": "4b15fa1ce1e07b1f1e464ad77d47a327cfae1381", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2019-11-01T16:12:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T20:45:02.000Z", "avg_line_length": 164.6666666667, "max_line_length": 1624, "alphanum_fraction": 0.8087044534, "num_tokens": 2246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.31457372954389706}}
{"text": "\\section{Reptation Monte Carlo}\n\\label{sec:rmc}\nLike diffusion monte carlo, reptation monte carlo (RMC) is a projector based method, allowing us the ability to sample the fixed-node wavefunciton.  However, by exploiting the path-integral formulation of Schr\\\"{o}dinger's equation, the RMC algorithm can offer some advantages over traditional DMC, such as sampling both the mixed and pure fixed-node distributions in polynomial time, as well as not having population fluctuations and biases.  The current implementation does not work with T-moves.\n\nThere are two adjustable parameters that affect the quality of the RMC projection:  imaginary projection time $\\beta$ of the sampling path (commonly called a ``reptile\"), and the Trotter time step $\\tau$.  $\\beta$ must be chosen to be large enough such that $e^{-\\beta \\hat{H}}|\\Psi_T\\rangle \\approx |\\Phi_0\\rangle$ for mixed observables, and $e^{-\\frac{\\beta}{2} \\hat{H}}|\\Psi_T\\rangle \\approx |\\Phi_0\\rangle$ for pure observables.  The reptile is discretized into $M=\\beta/\\tau$ beads at the cost of an $\\mathcal{O}(\\tau)$ time-step error for observables arising from the Trotter-Suzuki breakup of the short-time propagator.  \n\nThe following table lists some of the more practical \n\\begin{table}[h]\n\\begin{center}\n\\begin{tabularx}{\\textwidth}{l l l l l l }\n\\hline\n\\multicolumn{6}{l}{\\texttt{vmc} method} \\\\\n\\hline\n\\multicolumn{2}{l}{parameters}  & \\multicolumn{4}{l}{}\\\\\n   &   \\bfseries name     & \\bfseries datatype & \\bfseries values & \\bfseries default   & \\bfseries description \\\\\n   &   \\texttt{beta            } &  real  & $> 0$ & dep.   & reptile projection time $\\beta$  \\\\\n   &   \\texttt{timestep            } &  real     & $> 0$ & 0.1 & Trotter time step $\\tau$ for each electron move \\\\\n   &   \\texttt{beads           } &  int     & $> 0$ & 1 & Number of reptile beads $M=\\beta/\\tau$ \\\\\n   &   \\texttt{blocks              } &  integer  & $\\ge 0$ & 1   & number of blocks            \\\\\n   &   \\texttt{steps               } &  integer  & $\\ge 0$ & 1   & number of steps per block   \\\\\n   &   \\texttt{vmcpresteps        } &  integer  & $\\ge 0$ & 0   & propagates reptile using VMC for given number of steps\\\\\n   &   \\texttt{warmupsteps         } &  integer  & $\\ge 0$ & 0   & number of steps for warming up\\\\\n   &   \\texttt{MaxAge              }   & integer & $\\ge 0 $   & 0   & force accept for stuck reptile if age exceeds MaxAge. \\\\\n  \\hline\n\\end{tabularx}\n\\end{center}\n\\end{table}\n\nAdditional information:\n\nBecause of the sampling differences between DMC ensembles of walkers and RMC reptiles, the RMC block should contain the following estimator declaration to ensure correct sampling:  \\texttt{ <estimator name=\"RMC\" hdf5=\"no\">}. \n  \n\\begin{itemize}\n\\item \\texttt{beta} or \\texttt{beads}?  One can specify one or the other, and from the Trotter time-step, the code will construct an appropriately sized reptile.  If both are given, \\texttt{beta} overrides \\texttt{beads}.  \n\n\\item \\textbf{Mixed vs. Pure observables?}  Configurations sampled by the endpoints of the reptile are distributed according to the mixed distribution $f(\\mathbf{R})=\\Psi_T(\\mathbf{R})\\Phi_0(\\mathbf{R})$.  Any observable that is computable within DMC and is dumped to the scalar.dat file will likewise be found in the scalar.dat file generated by RMC, except there will be an appended \\texttt{\\_m} to alert the user that the observable was computed on the mixed distribution.  For pure observables, care must be taken in the interpretation.  If the observable is diagonal in the position basis (in layman's terms, if it is entirely computable from a single electron configuration $\\mathbf{R}$, like the potential energy), and if the observable does not have an explicit dependence on the trial wavefunction (for example, the local energy has an explicit dependence on the trial wavefunction from the kinetic energy term), then pure estimates will be correctly computed.  These observables will be found in either the scalar.dat file, where they will be appended with a \\texttt{\\_p} suffix, or in the stat.h5 file.  No mixed estimators will be dumped to the h5 file. \n\n\\item \\textbf{Sampling}.  For pure estimators, one should check the traces of both pure and mixed estimates.  Ergodicity is a known problem in RMC.  Because we use the bounce algorithm, it is possible for the reptile to bounce back and forth without changing the electron coordinates of the central beads.  This might not easily show up with mixed estimators, since these are accumulated at constantly regrown ends, but pure estimates are accumulated on these central beads, and so can exhibit strong autocorrelations in pure estimate traces.  \n\n\\item \\textbf{Propagator}:  Our implementation of RMC uses Moroni's DMC link action (symmetrized), with Umrigar's scaled drift near nodes.  In this regard, the propagator is identical to the one QMCPACK uses in DMC.  \n\n\\item \\textbf{Sampling}:  We use Ceperley's bounce algorithm.  MaxAge is used in case the reptile gets stuck, at which point the code forces move acceptance, stops accumulating statistics, and requilibrates the reptile.  Very rarely will this be required.  For move proposals, we use particle-by-particle VMC a total of $N_e$ times to generate a new all-electron configuration, at which point the action is computed and the move is either accepted or rejected.  \n\\end{itemize}\n\n\n\n\n", "meta": {"hexsha": "eaf2873df01512da03393618995a7b1e4e22d762", "size": 5354, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "manual/reptation.tex", "max_stars_repo_name": "bwvdg/qmcpack", "max_stars_repo_head_hexsha": "cd09fc54b36de2579c9802f5e64b7ec15506f3c3", "max_stars_repo_licenses": ["NCSA"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "manual/reptation.tex", "max_issues_repo_name": "bwvdg/qmcpack", "max_issues_repo_head_hexsha": "cd09fc54b36de2579c9802f5e64b7ec15506f3c3", "max_issues_repo_licenses": ["NCSA"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-10T15:33:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-10T15:35:59.000Z", "max_forks_repo_path": "manual/reptation.tex", "max_forks_repo_name": "bwvdg/qmcpack", "max_forks_repo_head_hexsha": "cd09fc54b36de2579c9802f5e64b7ec15506f3c3", "max_forks_repo_licenses": ["NCSA"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-23T17:44:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-23T17:44:39.000Z", "avg_line_length": 111.5416666667, "max_line_length": 1166, "alphanum_fraction": 0.7273066866, "num_tokens": 1421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.3145285762883888}}
{"text": "%% -*- coding:utf-8 -*-\n\\chapter{Natural transformation}\n\nNatural transformation is the most important part of the category\ntheory. It provides a possibility to compare \\mynameref{def:functor}s\nvia a standard tool. \n\n\\section{Definitions}\n\nThe natural transformation is not an easy concept compare other ones\nand requires some additional preparations before we can give the\nformal definition.\n\n\\begin{figure}\n  \\centering\n  \\begin{tikzpicture}[ele/.style={fill=black,circle,minimum\n        width=.8pt,inner sep=1pt},every fit/.style={ellipse,draw,inner\n        sep=-2pt}]\n\n    % the texts\n\n    \\node at (0,3) {$C$};        \n    \\node at (4,3) {$D$};        \n\n    \\node[ele,label=above:$a$] (a) at (0,2) {};    \n    \\node[ele,label=above:$a_F$] (af) at (4,2) {};\n    \\node[ele,label=below:$a_G$] (ag) at (4,0) {};\n\n    \\node[draw,fit= (a),minimum width=2cm, minimum\n      height=3.5cm] {} ;\n    \\node[draw,fit= (af) (ag),minimum width=2cm, minimum\n      height=3.5cm] {} ;\n\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (a) to\n    node[above]{$F$} (af);\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (a) to\n    node[above]{$G$} (ag);\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (af) to\n    node[right]{$\\alpha_a$} (ag);\n  \\end{tikzpicture}\n  \\caption{Natural transformation: object mapping}\n  \\label{fig:nt_objects_mapping}\n\\end{figure}\n\nConsider 2 categories $\\cat{C}, \\cat{D}$ and 2\n\\mynameref{def:functor}s $F: \\cat{C} \\tof \\cat{D}$ and $G:\n\\cat{C} \\tof \\cat{D}$. If we have an \\mynameref{def:object} $a \\in \\catob{C}$ then\nit will be translated by different functors into different objects of\ncategory $\\cat{D}$: $a_F = F(a), a_G = G(a) \\in \\catob{D}$ (see\n\\cref{fig:nt_objects_mapping}). There are 2 options possible\n\\begin{enumerate}\n\\item There is not  any \\mynameref{def:morphism} that connects $a_F$\n  and $a_G$.\n\\item $\\exists \\alpha_a \\in \\hom\\left(a_F, a_G\\right) \\subset\n  \\cathom{D}$. \n\\end{enumerate}\nWe can of course to create an artificial morphism that connects the\nobjects but if we use \\textit{natural} morphisms \n\\footnote{the word natural means that already existent morphisms from\n  category $\\cat{D}$ are used}\nthen we can get a\nspecial characteristic of the considered functors and categories. For\ninstance if we have such morphisms then we can say that the\nconsidered functors are related each other. Opposite example if there\nare no such morphisms then the functors can be considered as unrelated\neach other. \n%% Another example if the\n%% morphisms are \\mynameref{def:isomorphism}s then the functors can be\n%% considered as very close each other.\n\n\\begin{figure}\n  \\centering\n  \\begin{tikzpicture}[ele/.style={fill=black,circle,minimum\n        width=.8pt,inner sep=1pt},every fit/.style={ellipse,draw,inner\n        sep=-2pt}]\n\n    % the texts\n\n    \\node at (0,3) {$C$};        \n    \\node at (4,3) {$D$};        \n\n    \\node[ele,label=above:$a$] (a) at (0,2) {};    \n    \\node[ele,label=below:$b$] (b) at (0,0) {};    \n    \\node[ele,label=above:$a_F$] (af) at (4,2) {};\n    \\node[ele,label=below:$a_G$] (ag) at (4,0) {};\n    \\node[ele,label=above:$b_F$] (bf) at (5.5,2) {};\n    \\node[ele,label=below:$b_G$] (bg) at (5.5,0) {};\n\n    \\node[draw,fit= (a) (b),minimum width=2cm, minimum\n      height=3.5cm] {} ;\n    \\node[draw,fit= (af) (ag) (bf) (bg),minimum width=3cm, minimum\n      height=4cm] {} ;\n\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (a) to\n    node[left]{$f$} (b);\n\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (af) to\n    node[below]{$f_F$} (bf);\n\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (ag) to\n    node[above]{$f_G$} (bg);\n\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (a) to\n    node[above]{$F$} (af);\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (b) to\n    [out=45,in=135,looseness=1] node[above]{$F$} (bf);\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (a) to\n    node[above]{$G$} (ag);\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (b) to\n    [out=-45,in=-135,looseness=1] node[above]{$G$} (bg);\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (af) to\n    node[left]{$\\alpha_a$} (ag);\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (bf) to\n    node[right]{$\\alpha_b$} (bg);\n  \\end{tikzpicture}\n  \\caption{Natural transformation: morphisms mapping}\n  \\label{fig:nt_morphisms_mapping}\n\\end{figure}\n\n\nThe functor is not just the object mapping but also the morphisms\nmapping. If we have 2 objects $a$ and $b$ in the category $\\cat{C}$\nthen we potentially can have a morphism $f \\in \\hom_{\\cat{C}}(a, b)$. In this\ncase the morphism is mapped by the functors $F$ and $G$ into 2\nmorphisms $f_f$ and $f_G$ in the category $\\cat{D}$. \nAs result we have 4 morphisms: $\\alpha_a, \\alpha_b, f_F, f_G \\in\n\\cathom{D}$. It is natural to impose additional conditions on the\nmorphisms especially that they form a\n\\mynameref{def:commutative_diagram} (see \\cref{fig:nt_def}): \n\\[\nf_f \\circ \\alpha_b = \\alpha_a \\circ f_G.\n\\]\n\n\\begin{definition}[Natural transformation]\n\\label{def:nt}\n\n\\begin{figure}\n  \\centering\n  \\begin{tikzpicture}[ele/.style={fill=black,circle,minimum\n        width=.8pt,inner sep=1pt},every fit/.style={ellipse,draw,inner\n        sep=-2pt}]\n\n    % the texts\n    \\node[ele,label=above:$a_F$] (af) at (0,2) {};\n    \\node[ele,label=below:$a_G$] (ag) at (0,0) {};\n    \\node[ele,label=above:$b_F$] (bf) at (1.5,2) {};\n    \\node[ele,label=below:$b_G$] (bg) at (1.5,0) {};\n\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (af) to\n    node[below]{$f_F$} (bf);\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (ag) to\n    node[above]{$f_G$} (bg);\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (af) to\n    node[left]{$\\alpha_a$} (ag);\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (bf) to\n    node[right]{$\\alpha_b$} (bg);\n  \\end{tikzpicture}\n  \\caption{Natural transformation: commutative diagram}\n  \\label{fig:nt_def}\n\\end{figure}\n\nLet $F$ and $G$ are 2 \\mynameref{def:functor}s from category $\\cat{C}$\nto the category $\\cat{D}$. The \\textit{natural transformation} is a\nset of \\mynameref{def:morphism}s $\\alpha \\subset \\cathom{D}$ which\nsatisfy the following conditions:\n\\begin{itemize}\n\\item For every \\mynameref{def:object} $a \\in \\catob{C}$ $\\exists\n\\alpha_a \\in \\hom\\left(a_F, a_G\\right)$\n\\footnote{\n$a_F = F(a), a_G = G(a)$\n}\n- \\mynameref{def:morphism}\nin category $\\cat{D}$. The morphism $\\alpha_a$ is called the component of\nthe natural transformation.\n\\item For every morphism $f \\in \\cathom{C}$ that connects 2 objects\n  $a$ and $b$, i.e. $f \\in \\hom_{\\cat{C}}(a,b)$ the corresponding components of\n  the natural transformation $\\alpha_a, \\alpha_b \\in \\alpha$ should\n  satisfy the following conditions\n  \\begin{equation}\n    f_G \\circ \\alpha_a = \\alpha_b \\circ f_F,\n    \\label{eq:nt_definition}\n  \\end{equation}\n  where $f_F = F(f), f_G = G(f)$.\n  In other words the morphisms form a\n  \\mynameref{def:commutative_diagram} shown on the \\cref{fig:nt_def}. \n\\end{itemize}\n\nWe use the following notation (arrow with a dot) for the natural transformation between\nfunctors $F$ and $G$: $\\alpha: F \\tont G$. \n\\end{definition}\n\n\\section{Operations with natural transformations}\n\n\\begin{example}[\\textbf{Fun} category]\n\\label{ex:fun_category}\n\\index{Object!\\textbf{Fun} example}\n\\index{Morphism!\\textbf{Fun} example}\n\\index{Category!\\textbf{Fun} example}\n\nThe functors can be considered as objects in a special category\n\\textbf{Fun}. The morphisms in the category are \\mynameref{def:nt}s.\n\nTo define a category we need to define composition operation that\nsatisfied \\mynameref{axm:composition}, identity\nmorphism and verify \\mynameref{axm:associativity}. \n\n\\begin{figure}\n  \\centering\n  \\begin{tikzpicture}[ele/.style={fill=black,circle,minimum\n        width=.8pt,inner sep=1pt},every fit/.style={ellipse,draw,inner\n        sep=-2pt}]\n\n    % the texts\n\n    \\node at (0,3) {$C$};        \n    \\node at (4,5) {$D$};        \n\n    \\node[ele,label=above:$a$] (a) at (0,2) {};    \n    \\node[ele,label=above:$a_F$] (af) at (4,4) {};\n    \\node[ele,label=right:$a_G$] (ag) at (4,2) {};\n    \\node[ele,label=below:$a_H$] (ah) at (4,0) {};\n\n    \\node[draw,fit= (a),minimum width=2cm, minimum\n      height=3.5cm] {} ;\n    \\node[draw,fit= (af) (ag) (ah),minimum width=5cm, minimum\n      height=5cm] {} ;\n\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (a) to\n    node[above]{$F$} (af);\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (a) to\n    node[above]{$G$} (ag);\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (a) to\n    node[above]{$H$} (ah);\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (af) to\n    node[right]{$\\alpha_a$} (ag);\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (ag) to\n    node[right]{$\\beta_a$} (ah);\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (af) to\n     [out=-45,in=45,looseness=1] node[right]{$\\beta_a \\circ \\alpha_a$} (ah);\n  \\end{tikzpicture}\n  \\caption{Natural transformation vertical composition: object mapping}\n  \\label{fig:nt_objects_mapping_composition}\n\\end{figure}\n\n\nFor the composition consider 2 \\mynameref{def:nt}s $\\alpha, \\beta$ and\nconsider how they act on an object $a \\in \\catob{C}$ (see\n\\cref{fig:nt_objects_mapping_composition}). We always can construct\nthe composition $\\beta_a \\circ \\alpha_a$ i.e. we can define the\ncomposition of natural transformations $\\alpha, \\beta$ as \n\\(\n\\beta \\circ \\alpha = \\left\\{\n\\beta_a \\circ \\alpha_a | a \\in \\catob{C}\n\\right\\}\n\\). \n\n\\begin{figure}\n  \\centering\n  \\begin{tikzpicture}[ele/.style={fill=black,circle,minimum\n        width=.8pt,inner sep=1pt},every fit/.style={ellipse,draw,inner\n        sep=-2pt}]\n\n    % the texts\n\n    \\node[ele,label=above:$a_F$] (af) at (0,4) {};\n    \\node[ele,label=left:$a_G$] (ag) at (0,2) {};\n    \\node[ele,label=below:$a_H$] (ah) at (0,0) {};\n    \\node[ele,label=above:$b_F$] (bf) at (3,4) {};\n    \\node[ele,label=right:$b_G$] (bg) at (3,2) {};\n    \\node[ele,label=below:$b_H$] (bh) at (3,0) {};\n\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (af) to\n    node[above]{$f_F$} (bf);\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (ag) to\n    node[above]{$f_G$} (bg);\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (ah) to\n    node[above]{$f_H$} (bh);\n\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (af) to\n    node[right]{$\\alpha_a$} (ag);\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (ag) to\n    node[right]{$\\beta_a$} (ah);\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (af) to\n     [out=-135,in=135,looseness=1] node[left]{$\\beta_a \\circ\n       \\alpha_a$} (ah);\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (bf) to\n    node[right]{$\\alpha_b$} (bg);\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (bg) to\n    node[right]{$\\beta_b$} (bh);\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (bf) to\n     [out=-45,in=45,looseness=1] node[right]{$\\beta_b \\circ \\alpha_b$}\n     (bh); \n  \\end{tikzpicture}\n  \\caption{Natural transformation vertical composition: morphism mapping -\n    commutative diagram}\n  \\label{fig:nt_morphism_mapping_composition}\n\\end{figure}\n\n\nThe natural transformation is not just object mapping but also\nmorphism mapping. We will require that all morphisms shown on \\cref{fig:nt_morphism_mapping_composition} commute. The composition\ndefined in such way is called\n\\mynameref{def:vertical_composition}. \n\nThe functor category between categories $\\cat{C}$ and $\\cat{D}$ is\ndenoted as $[\\cat{C}, \\cat{D}]$.\n\n\\end{example}\n\n\\begin{definition}[Vertical composition]\n\\label{def:vertical_composition}\n\\index{Natural transformation!Vertical composition}\nLet $F,G,H$ are functors between categories $\\cat{C}$ and $\\cat{D}$.\nAlso we have $\\alpha : F \\tont G, \\beta: G \\tont\nH$ - natural transformations. We can compose the $\\alpha$ and $\\beta$\nas follows \n\\[\n\\alpha \\circ \\beta: F \\tont H.\n\\]\nThis composition\nis called \\textit{vertical composition}.\n\\end{definition}\n\n\\begin{definition}[Horizontal composition]\n\\label{def:horizontal_composition}\n\\index{Natural transformation!Horizontal composition}\nIf we have 2 pairs of functors. The first one $F,G: \\cat{C} \\to\n\\cat{D}$ and another one $J,K: \\cat{D} \\tof \\cat{E}$. We also have a\nnatural transformation between each pair: $\\alpha : F \\tont\nG$ for the first one and $\\beta : J \\tont\nK$ for the second one. We can create a new transformation\n\\[\n\\alpha \\star \\beta: F \\circ J \\tont G \\circ K\n\\] \nthat is called \\textit{horizontal composition}. Note that we use a\nspecial symbol $\\star$ for the composition.\n\\end{definition}\n\n\\begin{remark}[Bifunctor in category of functors]\n \\label{rem:bifunctor_fun_cat}\nIf we have the same pair of functors as in\n\\cref{def:horizontal_composition} then we can consider the functors as\nobjects of 3 categories: $\\cat{\\mathcal{A}} = \\left[\\cat{C},\n  \\cat{D}\\right], \\cat{\\mathcal{B}} = \\left[\\cat{D},\n  \\cat{E}\\right]$ and $\\cat{\\mathcal{C}} = \\left[\\cat{C},\n  \\cat{E}\\right]$ \n\n  Next we want to construct a \\mynameref{def:bifunctor} \n  $\\otimes: \\cat{\\mathcal{A}} \\times \\cat{\\mathcal{B}} \\tof \\cat{\\mathcal{C}}$\n  where for each pair of objects $F \\in \\catob{\\mathcal{A}}, J \\in\n  \\catob{\\mathcal{B}}$ we got another object from $\\cat{\\mathcal{C}}$.\n  The used operation is an ordinary functor's composition.\n  I.e.\n  \\[\n  \\otimes: F \\times G \\to F \\circ G \\in \\catob{\\mathcal{C}}.\n  \\]\n  \n  The bifunctor is not just a map for objects. There is also a map\n  between morphisms. Thus if we have 2 \\mynameref{def:morphism}s:\n  $\\alpha : F \\to G$ and $\\beta : J \\to K$ then we can construct the\n  following mapping \n  \\[\n  \\otimes: \\alpha \\times \\beta \\to \\alpha \\star \\beta \\in \\cathom{\\mathcal{C}}.\n  \\]\n  \n  As result we have the introduced mapping $\\otimes$ as a bifunctor.\n\\end{remark}\n\n\\begin{definition}[Left whiskering]\n\\label{def:lw}\nIf we have 3 categories $\\cat{B}, \\cat{C}, \\cat{D}$, \n\\mynameref{def:functor}s $F,G: \\cat{C} \\tof \\cat{D}$, $H: \\cat{B} \\to\n\\cat{C}$ and \\mynameref{def:nt} \n$\\alpha: F \\tont G$ then we can construct a new natural\ntransformations:\n\\[\n\\alpha H : F \\circ H \\tont G \\circ H\n\\]\nthat is called \\textit{left whiskering} of functor and natural\ntransformation \\cite{nlab:whiskering}. \n\\end{definition}\n\n\\begin{definition}[Right whiskering]\n\\label{def:rw}\nIf we have 3 categories $\\cat{C}, \\cat{D}, \\cat{E}$, \n\\mynameref{def:functor}s $F,G: \\cat{C} \\tof \\cat{D}$, $H: \\cat{D} \\to\n\\cat{E}$ and \\mynameref{def:nt} \n$\\alpha: F \\tont G$ then we can construct a new natural \ntransformations: \n\\[\nH \\alpha : H \\circ F \\tont H \\circ G\n\\]\nthat is called \\textit{right whiskering} of functor and natural\ntransformation \\cite{nlab:whiskering}. \n\\end{definition}\n\n\\begin{definition}[Identity natural transformation]\n\\label{def:idnt}\nIf $F: \\cat{C} \\tof \\cat{D}$ is a \\mynameref{def:functor} then we can\ndefine \\textit{identity natural transformation}\n$\\idnt{F}$ that maps any \\mynameref{def:object} \n$a \\in \\catob{C}$ into \\mynameref{def:id} $\\idm{F(a)} \\in \\cathom{D}$.\n\\end{definition}\n\n\\begin{remark}[Whiskering]\n\\label{rem:whiskering}\nWith \\mynameref{def:idnt} we can redefine \\mynameref{def:lw} and\n\\mynameref{def:rw} via \\mynameref{def:horizontal_composition} as follows.\n\nFor left whiskering:\n\\begin{equation}\n\\label{eq:lw}\n\\alpha H = \\alpha \\star \\idnt{H}\n\\end{equation}\n\nFor right whiskering:\n\\begin{equation}\n\\label{eq:rw}\nH \\alpha = \\idnt{H} \\star \\alpha\n\\end{equation}\n\\end{remark}\n\n\n\\section{Polymorphism and natural transformation}\n\nPolymorphism plays a certain role in programming languages. Category\ntheory provides several facts about polymorphic functions which are\nvery important.\n\n\\begin{definition}[Parametrically polymorphic function]\n\\index{Parametric polymorphism}\n\\label{def:pp_function}\nPolymorphism is parametric if all function instances behave uniformly\ni.e. have the same realization. The functions which satisfy the\nparametric polymorphism requirements are parametrically polymorphic.\n\\end{definition}\n\n\\begin{definition}[Ad-hoc polymorphism]\n\\label{def:ad_hoc_polymorphism}\nPolymorphism is parametric if the function instances can behave\ndifferently dependently on the type they are being instantiated with. \n\\end{definition}\n\n\\begin{theorem}[Reynolds]\n\\label{thm:reynolds}\n\\mynameref{def:pp_function}s are \\mynameref{def:nt}s \n\\begin{proof}\nTBD\n\\end{proof}\n\\end{theorem}\n\n\\subsection{\\textbf{Hask} category}\n\nIn Haskell most of functions are \\mynameref{def:pp_function}s \n\\footnote{really in the run-time the functions are not\n  \\mynameref{def:pp_function}s}.  \n\n\\begin{example}[Parametrically polymorphic function][\\textbf{Hask}]\n\\label{ex:nt_hask}\nConsider the following function\n\\begin{minted}{haskell}\nsafeHead :: [a] -> Maybe a\nsafeHead [] = Nothing\nsafeHead (x:xs) = Just x\n\\end{minted}\nThe function is parametricaly polymorphic and by\n\\mynameref{thm:reynolds} is \\mynameref{def:nt} (see \\cref{fig:nt_pp_hask}).\n\n\\begin{figure}\n  \\centering\n  \\begin{tikzpicture}[ele/.style={fill=black,circle,minimum\n        width=.8pt,inner sep=1pt},every fit/.style={ellipse,draw,inner\n        sep=-2pt}]\n\n    % the texts\n\n    \\node[ele,label=above:$a$] (a) at (0,2) {};    \n    \\node[ele,label=below:$b$] (b) at (0,0) {};    \n    \\node[ele,label=above:$\\mbox{[a]}$] (af) at (5,2) {};\n    \\node[ele,label=below:$\\mbox{Maybe a}$] (ag) at (5,0) {};\n    \\node[ele,label=above:$\\mbox{[b]}$] (bf) at (7.5,2) {};\n    \\node[ele,label=below:$\\mbox{Maybe b}$] (bg) at (7.5,0) {};\n\n    \\node[draw,fit= (a) (b),minimum width=2cm, minimum\n      height=3.5cm] {} ;\n    \\node[draw,fit= (af) (ag) (bf) (bg),minimum width=6.5cm, minimum\n      height=5.5cm] {} ;\n\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (a) to\n    node[left]{$f$} (b);\n\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (af) to\n    node[below]{$\\mbox{fmap}_{[]}$} (bf);\n\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (ag) to\n    node[above]{$\\mbox{fmap}_{Maybe}$} (bg);\n\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (a) to\n    node[above]{$$} (af);\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (b) to\n    [out=45,in=135,looseness=1] node[above]{$$} (bf);\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (a) to\n    node[above]{$$} (ag);\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (b) to\n    [out=-45,in=-135,looseness=1] node[above]{$$} (bg);\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (af) to\n    node[left]{$\\mbox{safeHead}_a$} (ag);\n    \\draw[->,thick,shorten <=2pt,shorten >=2pt] (bf) to\n    node[right]{$\\mbox{safeHead}_b$} (bg);\n  \\end{tikzpicture}\n  \\caption{Haskell parametric polymorphism as a natural transformation}\n  \\label{fig:nt_pp_hask}\n\\end{figure}\n\nTherefore from the definition of the natural transformation\n\\eqref{eq:nt_definition} we have \n\\mintinline{haskell}{fmap f . safeHead = safeHead . fmap f}. I.e. it\ndoes not matter if we initially apply \\mintinline{haskell}{fmap f} and\nthen \\mintinline{haskell}{safeHead} to the result or initially\n\\mintinline{haskell}{safeHead} and then \\mintinline{haskell}{fmap f}.\n\nThe statement can be verified directly. For empty list we have\n\\begin{minted}{haskell}\nfmap f . safeHead []\n-- equivalent to\nfmap f Nothing \n-- equivalent to\nNothing\n\\end{minted}\nfrom other side\n\\begin{minted}{haskell}\nsafeHead . fmap f []\n-- equivalent to\nsafeHead [] \n-- equivalent to\nNothing\n\\end{minted}\n\nFor a non empty list we have\n\\begin{minted}{haskell}\nfmap f . safeHead (x:xs)\n-- equivalent to\nfmap f (Just x) \n-- equivalent to\nJust (f x)\n\\end{minted}\nfrom other side\n\\begin{minted}{haskell}\nsafeHead . fmap f (x:xs)\n-- equivalent to\nsafeHead (f x: fmap f xs ) \n-- equivalent to\nJust ( f x )\n\\end{minted}\n\nUsing the fact that \\mintinline{haskell}{fmap f} is an expensive\noperation if it is applied to the list we can conclude that the second\napproach is more productive. Such transformation allows compiler to\noptimize the code.\n\\footnote{It is not directly applied to Haskell because it has lazy\n  evaluation that can perform optimization before that one}\n\\end{example}\n", "meta": {"hexsha": "75e271f8db795e8a8807a90c2649a452f0d4f7bf", "size": 19626, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "cattheory/nt.tex", "max_stars_repo_name": "ivanmurashko/articles", "max_stars_repo_head_hexsha": "522db3ad21e96084490acd39a146a335763e5beb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-09-27T08:59:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-27T08:59:55.000Z", "max_issues_repo_path": "cattheory/nt.tex", "max_issues_repo_name": "ivanmurashko/articles", "max_issues_repo_head_hexsha": "522db3ad21e96084490acd39a146a335763e5beb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cattheory/nt.tex", "max_forks_repo_name": "ivanmurashko/articles", "max_forks_repo_head_hexsha": "522db3ad21e96084490acd39a146a335763e5beb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8596802842, "max_line_length": 129, "alphanum_fraction": 0.6682971568, "num_tokens": 6903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.3145090619776183}}
{"text": "%% Stefan Negru -- blankdots.com -- An adaption of MIT Thesis format for\n%% Faculty of Computer Science, Alexandru Ioan Cuza University\n\n\\chapter{Appendix Example}\n\\label{chap:AppendixA}\n\n\\begin{table}[h]\n\\centering\n\\renewcommand{\\arraystretch}{1}\n\\caption{OWL DL descriptions, data ranges, properties, individuals, and data values; content adapted from \\cite{Baader2003}.}\n\\begin{tabular}{|p{10cm}|p{5cm}|}\n\t\\multicolumn{1}{l}{\\textbf{Abstract Syntax}}\n\t& \\multicolumn{1}{l}{\\textbf{DL Syntax}}\\\\\n\t\t\t\\hline\n\t\t\tDescriptions ($C$) & {}\\\\\n\t\t\t\\hline\n\t\t\tA & A\\\\\n\t\t\towl:Thing & $\\top$\\\\\n\t\t\towl:Nothing & $\\bot$\\\\\n\t\t \\hline\n\t\t\tintersectionOf $(C_{1}\\ldots C_{n})$ & $C_{1}\\sqcap \\cdots \\sqcap C_{n}$ \\\\\n\t\t\tunionOf $(C_{1}\\ldots C_{n})$ & $C_{1}\\sqcup \\cdots \\sqcup C_{n}$ \\\\\n\t\t\tcomplementOf $(C)$ & $\\neg C$\\\\\n\t\t\toneOf $(o_{1} \\ldots o_{n})$ & $\\{o_{1}\\} \\sqcup \\cdots \\sqcup \\{o_{n}\\}$\\\\\n\t\t\t\\hline\n\t\t\trestriction ($R$ someValuesFrom $(C)$) & $\\exists R.C$ \\\\\n\t\t\trestriction ($R$ allValuesFrom $(C)$) & $\\forall R.C$ \\\\\n\t\t\trestriction ($R$ hasValue $(o)$) & $R:o$ \\\\\n\t\t\trestriction ($R$ minCardinality $(n)$) & $\\ge n$ $R$ \\\\\n\t\t\trestriction ($R$ maxCardinality $(n)$) & $\\le n$ $R$ \\\\\n\t\t\t\\hline\n\t\t\trestriction ($U$ someValuesFrom $(C)$) & $\\exists U.C$ \\\\\n\t\t\trestriction ($U$ allValuesFrom $(C)$) & $\\forall U.C$ \\\\\n\t\t\trestriction ($U$ hasValue $(v)$) & $U:v$ \\\\\n\t\t\trestriction ($U$ minCardinality $(n)$) & $\\ge n$ $U$ \\\\\n\t\t\trestriction ($U$ maxCardinality $(n)$) & $\\le n$ $U$ \\\\\n\t\t\t\\hline\n\t\t\t\\hline\n\t\t\tData Ranges ($D$) & {}\\\\\n\t\t\t\\hline\n\t\t\tD & D\\\\\n\t\t\toneOf $(v_{1} \\cdots v_{n})$ & $\\{o_{1}\\} \\sqcup \\cdots \\sqcup \\{v_{n}\\}$\\\\\n\t\t\t\\hline\n\t\t\tObject Properties($R$) & {}\\\\\n\t\t\t\\hline\n\t\t\tR & R\\\\\n\t\t\tinv$(R)$ & $R^{-}$\\\\\n\t\t\t\\hline\n\t\t\t\\hline\n\t\t\tDatatype Properties($U$) & {}\\\\\n\t\t\t\\hline\n\t\t\tU & U\\\\\n\t\t\t\\hline\n\t\t\t\\hline\n\t\t\tIndividuals($o$) & {}\\\\\n\t\t\t\\hline\n\t\t\to & o\\\\\n\t\t\t\\hline\n\t\t\t\\hline\n\t\t\tData Values($v$) & {}\\\\\n\t\t\t\\hline\n\t\t\tv & v\\\\\n\t\t\t\\hline\n\t\t\\end{tabular}\n\\label{tab:OWLvsDL}\n\\end{table}\n", "meta": {"hexsha": "21c3a0ba3171bbc406a21824ad5c394cd99aa94b", "size": 1981, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "appa.tex", "max_stars_repo_name": "blankdots/LatexThesisTemplate", "max_stars_repo_head_hexsha": "39f5043388c6bade9dfed44550301ce860551dca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-30T21:37:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-30T21:37:18.000Z", "max_issues_repo_path": "appa.tex", "max_issues_repo_name": "blankdots/LatexThesisTemplate", "max_issues_repo_head_hexsha": "39f5043388c6bade9dfed44550301ce860551dca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "appa.tex", "max_forks_repo_name": "blankdots/LatexThesisTemplate", "max_forks_repo_head_hexsha": "39f5043388c6bade9dfed44550301ce860551dca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5671641791, "max_line_length": 125, "alphanum_fraction": 0.5608278647, "num_tokens": 808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.3145090531165992}}
{"text": "%\n% Copyright (c) Meta Platforms, Inc. and affiliates.\n%\n% This source code is licensed under the MIT license found in the LICENSE file\n% in the root directory of this source tree. \n%\n\n\\documentclass{article}\n\\usepackage[margin=1in]{geometry}\n\\usepackage{amsthm,amsmath,amssymb}\n\\usepackage{graphicx}\n\\usepackage[hidelinks,breaklinks]{hyperref}\n\\pdfsuppresswarningpagegroup=1\n\n\n\n\n\\newtheorem{theorem}{Theorem}[]\n\\newtheorem{lemma}[theorem]{Lemma}\n\\newtheorem{corollary}[theorem]{Corollary}\n\\newtheorem{definition}[theorem]{Definition}\n\\newtheorem{observe}[theorem]{Observation}\n\\newtheorem{remark1}[theorem]{Remark}\n\\newenvironment{remark}{\\begin{remark1} \\rm}{\\end{remark1}}\n\n\n\n\n\\DeclareMathOperator{\\Bernoulli}{Bernoulli}\n\\DeclareMathOperator{\\E}{\\mathop{}\\mathbb{E}}\n\n\n\n\n\\newlength{\\vertsep}\n\\setlength{\\vertsep}{.085in}\n\\newlength{\\imsize}\n\\setlength{\\imsize}{.415\\textwidth}\n\\newlength{\\imsized}\n\\setlength{\\imsized}{.48\\textwidth}\n\n\n\n\n\\title{Controlling for multiple covariates}\n\\author{Mark Tygert\\\\{\\normalsize Facebook Artificial Intelligence Research}\\\\\n{\\normalsize 1 Facebook Way, Menlo Park, CA 94025}\\\\\n{\\normalsize Main e-mail address:\\ \\ {\\tt mark@tygert.com}}}\n\n\n\n\n\\begin{document}\n\n\n\n\\maketitle\n\n\n\n\\begin{abstract}\nA fundamental problem in statistics is to compare\nthe outcomes attained by members of subpopulations,\nwhether comparing a subpopulation to the full population\nor comparing two distinct subpopulations.\nThis problem arises in the analysis of randomized controlled trials,\nin the analysis of A/B tests, and in the assessment of fairness and bias\nin the treatment of sensitive subpopulations,\nand is becoming especially important in measuring the effects\nof algorithms and machine-learned systems.\nVery often the comparison makes the most sense when performed\nseparately for individuals who are similar according to certain characteristics\ngiven by the values of covariates of interest;\nthe separate comparisons can also be aggregated in various ways\nto compare across all values of the covariates.\nSeparating, segmenting, or stratifying into those with similar values\nof the covariates is also known as ``conditioning on'' or ``controlling for''\nthose covariates.\nFor instance, controlling for age or annual income is common.\n\nTwo standard methods of controlling for covariates are (1) binning\nand (2) regression modeling.\nBinning requires making fairly arbitrary, yet frequently highly influential\nchoices, and is unsatisfactorily temperamental in multiple dimensions,\nwith multiple covariates.\nRegression analysis works wonderfully when there is good reason to believe\nin a particular regression model or classifier (such as logistic regression).\nRegression typically assumes a parametric or semi-parametric model,\npossibly validated with non-parametric goodness-of-fit tests.\nGoodness-of-fit only very indirectly characterizes differences\nof a subpopulation from the full population\nor between two distinct subpopulations.\nThus, there appears to be no extant canonical fully non-parametric regression\nfor the comparison of a subpopulation to the full population\nor for the comparison of two distinct subpopulations,\nnot while conditioning on multiple specified covariates.\nExisting methods rely on analysts to make choices,\nand those choices can be debatable;\nanalysts can deceive others or even themselves,\nwhether purposefully or unintentionally.\nThe present paper aims to provide\nan essentially unique fully non-parametric method\nfor such comparisons, combining two ingredients:\n(1) recently developed methodologies for such comparisons\nthat already exist when conditioning on a single scalar covariate and\n(2) the Hilbert space-filling curve that maps continuously\nfrom one dimension to multiple dimensions.\n\\end{abstract}\n\n\n\n\\section{Introduction}\n\\label{intro}\n\nControlling for specified covariates during analysis of differences\nbetween two subpopulations is essential in comparisons\nthroughout biomedicine, the fairness of algorithms,\nand the social sciences.\nFormally, controlling for specified covariates refers to conditioning\non those covariates (that is, on the ``independent variables'') when analyzing\nthe differences in responses (that is, in ``dependent variables'');\nthe point is to compare responses between individuals\nwho have similar values for the covariates.\nMany studies in biomedicine, the fairness of algorithms,\nand the social sciences aim to compare individuals\nwhose socioeconomic status is similar, for instance.\nAfter comparing the responses from individuals whose covariates are similar,\nthe obtained differences are easy to summarize across all values of covariates\nvia standard methods for aggregation (for example, simply sum across all values\nof the covariates the differences for every set of values for the covariates).\n\nCanonical examples of controlling for specified covariates\noccur with randomized controlled trials, A/B tests, and assessing fairness\nin the treatment of a sensitive subpopulation (where ``sensitive''\ncan refer to protected classes, such as those defined by race, color, religion,\ngender, national origin, age, disability, veteran status, genetic information,\nor political affiliation). In biomedicine, the subpopulation of interest\noften is diseased, infected, treated, or recovered (while the control\nor full population typically has no such special characteristic).\nAlternatively, the covariates on which the analysis gets conditioned\ncan involve attributes including those just mentioned (such as age),\nin addition to other defining characteristics (such as annual income).\n\nBinning together similar values of the covariates and analyzing in each bin\nthe differences between the subpopulations' responses is perhaps\nthe most direct way to condition on the covariates.\nUnfortunately, binning requires making rather arbitrary,\nyet often highly influential decisions about the number of bins\nand where to set the bins' boundaries,\neven with only a single scalar covariate;\nworse, the potential pitfalls multiply as the number of covariates grows.\nClosely related to binning are smoothing methods based\non kernel density estimation, as detailed and compared to binning\nby~\\cite{srihera-stute}, Chapter~8 of~\\cite{wilks}, and others;\nall such methods require making choices similar to those required when binning.\nFortunately, the methods of~\\cite{tygert_full} and~\\cite{tygert_two}\nspecifically avoid binning and smoothing kernels,\nand \\cite{tygert_full} and~\\cite{tygert_two} provide\ncopious examples of problems when binning or smoothing; unfortunately,\nthe methods of~\\cite{tygert_full} and~\\cite{tygert_two} on their own\nare limited to a single scalar covariate.\n\nAnother way to control for specified covariates\nis to perform regression analysis with an assumed regression model,\nand such regression can work very well even with multiple covariates.\nWhen the responses are discrete,\nstandard models such as logistic regression or Poisson regression\nare often appropriate, and classifiers based on neural networks\nare very popular, as reviewed, for example,\nby~\\cite{hastie-tibshirani-friedman}.\nSuch methods are great and often highly informative.\nHowever, regression modeling relies on the validity\nof a parametric (or semi-parametric) statistical model.\nGoodness-of-fit tests can partially assess\nthe validity of the parametric model, but do not directly quantify\nthe differences between subpopulations being analyzed.\n\nThe present paper proposes a fully non-parametric method\nfor analyzing the differences between two subpopulations' discrete responses\n(or between the responses from a subpopulation and from the full population)\nwhile conditioning on specified covariates.\nThe method is canonical --- essentially unique --- there are no parameters\nto manipulate, aside from the ordering of the covariates\n(and numerical experiments indicate that the results of such analyses\nare relatively insensitive to the choice of the ordering of the covariates).\nThus, the non-parametric methodology of the present paper\nenables adjustment for selected covariates in comparisons\nbetween subpopulations or between a subpopulation and the full population,\nand the adjustment is almost completely canonical,\nwith essentially no knobs to turn or parameters to set;\nanalysts cannot deceive anyone (including themselves)\nwhen using the methods proposed in the present paper.\nThis may make the methods especially appealing for regulatory compliance.\nUnlike in regression analysis, there is no need to choose and believe a model.\n(In cases for which there is good reason to believe in a particular model,\nthough, the analyst may wish to take advantage of the additional power afforded\nby parametric modeling.)\n\nFor detailed investigations, the present paper provides a graphical method.\nFor investigators' convenience, the present paper also provides\nstatistics that summarize the graph into a single scalar (namely, an analogue\nof the Kolmogorov-Smirnov or Kuiper metrics familiar from comparisons\nof probability distributions) and that gauge the statistical significance\nof deviations displayed across the full range of the graph.\nThe graph and scalar summary statistics\ncome from~\\cite{tygert_full} and~\\cite{tygert_two}.\n\nThe methods of~\\cite{tygert_full} and~\\cite{tygert_two}\nare already fully non-parametric and canonical when conditioning\non a single real-valued covariate.\nThe present paper simply extends those methods to controlling\nfor multiple covariates, by imposing a total order\non the values of the covariates via a Hilbert space-filling curve.\nThe Hilbert curve is unique aside from the ordering of the covariates\n(that is, aside from the ordering of the dimensions in which the curve\nis embedded), and is optimal according to many criteria, such as those\ndiscussed by~\\cite{moon-jagadish-faloutsos-saltz}.\nThe extent to which the Hilbert curve is unique is what makes the scheme\nof the present paper essentially unique and canonical, with no parameters\nto set except for the ordering of the dimensions in which the Hilbert curve\nis embedded.\nFurthermore, the numerical examples of Section~\\ref{results} below indicate\nthat the scheme yields similar results irrespective of the ordering\nof the dimensions.\n\nThe Hilbert curve is ideal for clustering multi-dimensional data,\nas long observed empirically and proven rigorously\nby~\\cite{moon-jagadish-faloutsos-saltz}.\nIndexing and sharding in databases have often imposed a total ordering\non the data via a space-filling curve and then fed the results\ninto one-dimensional schemes; this reduction of the problem\nfrom multi-dimensional to one-dimensional is the primary application\ndiscussed by~\\cite{moon-jagadish-faloutsos-saltz}.\nA prominent recent deployment of this using the Hilbert curve\nis Google's S2 Geometry Library, which drives Google Maps, Foursquare, MongoDB,\net al.\\footnote{Google's S2 Geometry Library is described\nat \\url{https://s2geometry.io/devguide/s2cell_hierarchy.html}}\nVisualization of multi-dimensional data is another popular application,\nas illustrated and reviewed by~\\cite{castro-burns}.\nOther applications related to the use in the present paper\ninclude numerical integration in high-dimensional spaces,\nas coupled with Markov-chain Monte-Carlo methods by~\\cite{skilling2}.\nThe simplest, most efficient algorithms for the Hilbert curve\nare due to~\\cite{skilling}. The numerical experiments reported\nin Section~\\ref{results} below leverage the Python package\n{\\tt hilbertcurve},\\footnote{The Python module {\\tt hilbertcurve}\nis available at \\url{https://github.com/galtay/hilbertcurve}\nunder the permissive MIT copyright license.}\nwhich implements the algorithms of~\\cite{skilling}.\n\nThe remainder of the paper has the following structure:\nSection~\\ref{methods} first reviews the methods\nof~\\cite{hilbert} (the Hilbert space-filling curve),\nof~\\cite{tygert_full} (comparing a subpopulation to the full population\nwhile controlling for a single scalar covariate),\nand of~\\cite{tygert_two} (comparing two subpopulations\nwhile conditioning on a single scalar covariate);\nSection~\\ref{methods} also combines these methods\nin order to obtain the main methodology proposed here\nfor conditioning on several covariates.\nSection~\\ref{results} then presents the results\nof several numerical experiments, some using synthetic data\nand others using public surveys.\\footnote{Permissively licensed\nopen-source software implementing these methods in Python\n--- software that also reproduces all figures and statistics reported below\n--- is available at \\url{https://github.com/facebookresearch/metamulti}}\nFinally, Section~\\ref{conclusion} recapitulates the main findings to conclude.\n\n\n\n\\section{Methods}\n\\label{methods}\n\nThis section presents the methodology of the present paper,\nbeginning with three subsections reviewing the required ingredients.\nThe first, Subsection~\\ref{Hilbert}, collects together well-known facts\nabout Hilbert space-filling curves.\nThen, Subsection~\\ref{subpop} summarizes methods of~\\cite{tygert_full}\nfor analyzing deviation of a subpopulation from the full population.\nSimilarly, Subsection~\\ref{subpops} summarizes methods of~\\cite{tygert_two}\nfor analyzing deviations between different subpopulations.\nFinally, Subsection~\\ref{combo} chains together\nfirst Subsections~\\ref{Hilbert} and~\\ref{subpop}\nand then Subsections~\\ref{Hilbert} and~\\ref{subpops},\nyielding the main solution to the problem posed in the introduction.\n\n\n\\subsection{Preliminaries on Hilbert curves}\n\\label{Hilbert}\n\nThis subsection reviews the construction and properties of Hilbert curves.\n\nHilbert curves are so-called ``space-filling'' curves similar\nto the original Peano curves introduced by~\\cite{peano}.\n\\cite{hilbert} originally introduced these curves\nfor the two-dimensional plane, but they generalize straightforwardly\nto any finite-dimensional Euclidean space.\nA detailed presentation of what the present subsection summarizes\nis available from~\\cite{moon-jagadish-faloutsos-saltz}.\n\nA canonical space-filling curve in $p$ dimensions is a continuous mapping $h$\nfrom the unit interval $(0, 1)$ onto the unit hypercube $(0, 1)^p$,\nwhere ``onto'' means that the curve covers every point in the hypercube\n--- the mapping is surjective.\nA mapping $g$ from the unit hypercube $(0, 1)^p$\nto the unit interval $(0, 1)$ that is a right inverse for $h$\naccompanies the space-filling curve: $h(g(x)) = x$\nfor any point $x$ in the unit hypercube $(0, 1)^p$.\nHowever, the ``inverse'' mapping $g$ cannot be continuous when $p > 1$:\nthe existence of a left inverse function ($h$) for $g$\nimplies that $g$ is injective (that is, $g$ is one-to-one),\nso $g$ cannot be continuous without violating the topological invariance\nof dimension (or the Brouwer invariance of domain).\\footnote{See, for example,\nCorollary~3 and its proof on Terence Tao's blog at\n\\url{https://terrytao.wordpress.com/2011/06/13/brouwers-fixed-point-and-invariance-of-domain-theorems-and-hilberts-fifth-problem}}\n\nThe continuity of the mapping $h$ from the unit interval $(0, 1)$\nonto the unit hypercube $(0, 1)^p$ ensures that,\nfor any points $t$ and $u$ from the unit interval $(0, 1)$,\nif $t$ and $u$ are close, then so are $h(t)$ and $h(u)$.\nTherefore, for any real-valued function $f$ on the unit hypercube $(0, 1)^p$,\nlocal averages of $f \\circ h$ will also be local averages of $f$\n(with ``local'' defined by the usual Euclidean metric),\nwhere $f \\circ h$ is the composition of $f$ and $h$, that is,\n$(f \\circ h)(t) = f(h(t))$ for any point $t$ in the unit interval $(0, 1)$.\nThe constructions below impose a total order on the unit hypercube $(0, 1)^p$\nvia the inverse mapping $g$: if $x$ and $y$ are two points\nin the unit hypercube $(0, 1)^p$, then $x < y$ means that $g(x) < g(y)$.\nA local average of $f$ under this ordering (with ``local'' defined\nby the perhaps counterintuitive total order ``$<$'' imposed via $g$\nas just mentioned, rather than via the usual Euclidean metric)\nis a local average of $f \\circ h$ and thus is also a local average of $f$\nunder the usual Euclidean metric (where this latter consequence\nis simply restating the second sentence of this paragraph).\nIf $g$ could be continuous, then any local average of $f$\nunder the usual Euclidean metric would also be a local average of $f$\nunder the total ordering \\dots\\,but $g$ cannot be continuous,\nas discussed in the previous paragraph.\nThe constructions below consider all the local averages of $f$\nunder the total ordering, without needing to consider\nevery single other possible local average of $f$\nunder the usual Euclidean metric.\n\nA Hilbert curve $h$ is an instance from a specific class\nof space-filling curves in which the points are ordered according\nto a depth-first traversal of the canonical $2^p$-ary (dyadic) tree\non the unit hypercube $(0, 1)^p$\n--- this is the canonical binary tree for $p = 1$,\nthe canonical quad-tree for $p = 2$, the canonical oct-tree for $p = 3$,\nand so on. A Hilbert curve minimizes the Lipschitz constant of order $1/p$\nbeyond that for the original Peano curve of~\\cite{peano}\n(the Lipschitz constant is also known as the constant of H\\\"older continuity\nto order $1/p$); indeed, the Hilbert curve possesses many favorable properties,\nas discussed by~\\cite{moon-jagadish-faloutsos-saltz}.\n\nFigure~\\ref{hilbert} displays an approximation to the image of a Hilbert curve.\nThe traditional construction of a Hilbert curve leverages approximations\nwith more and more line segments, where every line segment\nin the same approximation has the same length as every other line segment\nin that same approximation. The mapping from one dimension to $p$ dimensions \nfor each approximation is continuous, and the approximations converge uniformly\nas the numbers of line segments increase, so the limit exists\nand is continuous. The limit is the Hilbert curve.\nFor calculations with 64-bit variables (unsigned 8-byte integers),\nwe use an approximation with $2^{64} - 1$ line segments.\n\n\\begin{figure}\n\\begin{centering}\n\\hfil\\parbox{0.71\\textwidth}\n{\\includegraphics[width=0.71\\textwidth]{../codes/hilbert.pdf}}\n\\end{centering}\n\\caption{An approximation to the Hilbert curve in $p = 2$ dimensions\nwith $255$ line segments --- the numbers of the points on the curve\nspecify the total ordering.}\n\\label{hilbert}\n\\end{figure}\n\n\n\\subsection{Preliminaries on cumulative differences of a subpopulation\nfrom the full population}\n\\label{subpop}\n\nThis subsection reviews cumulative methods developed by~\\cite{tygert_full}\nfor assessing deviation of a subpopulation from the full population.\n\nSuppose that $S_1$,~$S_2$, \\dots, $S_m$ are real numbers (known as ``scores''),\n$R_1$,~$R_2$, \\dots, $R_m$ are real numbers (known as ``responses,''\n``results,'' ``regressands,'' or ``outcomes''),\nand $W_1$,~$W_2$, \\dots, $W_m$ are positive real numbers (known as ``weights'')\nsuch that $S_1 < S_2 < \\dots < S_m$ and $R_1$,~$R_2$, \\dots, $R_m$\nare random variables.\nSuppose also that $i_1$,~$i_2$, \\dots, $i_n$ are integers (with $n < m$)\nsuch that $1 \\le i_1 < i_2 < \\dots < i_n \\le m$; these indices specify\na subpopulation of the full population.\nThe probability distributions of $R_1$,~$R_2$, \\dots, $R_m$ will be discrete\nin the examples considered below, and the scores $S_1$,~$S_2$, \\dots, $S_m$,\nweights $W_1$,~$W_2$, \\dots, $W_n$, and indices $i_1$,~$i_2$, \\dots, $i_n$\nwill be deterministic, not viewed as random.\nThe following sets up notation in order to define a graph.\n\nThe cumulative weighted response for the subpopulation is\n%\n\\begin{equation}\nF_k = \\frac{\\sum_{j=1}^k W_{i_j} R_{i_j}}{\\sum_{j=1}^n W_{i_j}}\n\\end{equation}\n%\nfor $k = 1$, $2$, \\dots, $n$.\nThe weighted average response for the full population in a narrow bin\naround a score $S_{i_k}$ from the subpopulation is\n%\n\\begin{equation}\n\\tilde{R}_{i_k} = \\frac{\\sum_{i : B_{k-1} < S_i \\le B_k} W_i R_i}\n                       {\\sum_{i : B_{k-1} < S_i \\le B_k} W_i}\n\\end{equation}\n%\nfor $k = 1$,~$2$, \\dots, $n$, where the thresholds for the bins are\n%\n\\begin{equation}\nB_k = \\frac{S_{i_k} + S_{i_{k+1}}}{2}\n\\end{equation}\n%\nfor $k = 0$,~$1$,~$2$, \\dots, $n$, using the notation that\n$S_{i_0} = -\\infty$ and $S_{i_{n+1}} = \\infty$\n(and so $B_0 = -\\infty$ and $B_n = \\infty$).\nThen, the cumulative weighted response for the full population\naveraged to the scores from the subpopulation is\n%\n\\begin{equation}\n\\tilde{F}_k = \\frac{\\sum_{j=1}^k W_{i_j} \\tilde{R}_{i_j}}{\\sum_{j=1}^n W_{i_j}}\n\\end{equation}\n%\nfor $k = 1$, $2$, \\dots, $n$.\nThe cumulative weight is the aggregate\n%\n\\begin{equation}\nA_k = \\frac{\\sum_{j=1}^k W_{i_j}}{\\sum_{j=1}^n W_{i_j}}\n\\end{equation}\n%\nfor $k = 1$, $2$, \\dots, $n$.\n\nIn a plot where $A_k$ is the abscissa (that is, the horizontal coordinate)\nand $F_k - \\tilde{F}_k$ is the ordinate (that is, the vertical coordinate),\nthe expected slope of a secant line connecting two points on the graph is equal\nto the weighted average difference in responses between the subpopulation\nand the full population over the range of scores between the two points.\nThus, deviation between the subpopulation and the full population\nis simply the slope. A long range of steep slopes in the graph\nindicates significant weighted average deviation over that range.\nIf the weights are all identical ---\n$W_1 = W_2 = \\dots = W_m$ --- then $A_k = k/n$, so the graph\nof $F_k - \\tilde{F}_k$ versus $A_k$ is then the same as the usual graph\nof $F_k - \\tilde{F}_k$ (with equispaced abscissae).\n\nIf the differences are all small, then the graph should be fairly flat\nand hence not deviate much overall.\nTwo standard metrics which summarize the overall deviation across all scores\nare the statistic of Kolmogorov and Smirnov, the maximal absolute deviation\n%\n\\begin{equation}\n\\label{Kolmogorov-Smirnov}\nG = \\max_{1 \\le k \\le n} |F_k - \\tilde{F}_k|,\n\\end{equation}\n%\nand the statistic of Kuiper, the size of the range of deviations\n%\n\\begin{equation}\n\\label{Kuiper}\nH = \\max_{0 \\le k \\le n} (F_k - \\tilde{F}_k)\n  - \\min_{0 \\le k \\le n} (F_k - \\tilde{F}_k),\n\\end{equation}\n%\nwith $F_0 = \\tilde{F}_0 = 0$.\nAs detailed by~\\cite{tygert_full},\nthe expected value of $G$ is roughly $1.25\\sigma$\nunder the null hypothesis of no deviation between the subpopulation\nand the full population in their responses'\nunderlying probability distributions (and similarly for $H$),\nwhere estimation of $\\sigma$ is discussed at length by~\\cite{tygert_full};\nnormalizing $G$ and $H$ by $\\sigma$ therefore characterizes\nstatistical significance (as both $G$ and $H$ are sub-Gaussian\nunder the null hypothesis).\nValues of $G/\\sigma$ much greater than 1.25 indicate\nhighly statistically significant deviation,\nwhile values of $G/\\sigma$ near 0 give little indication\nof statistically significant deviation.\n\n\n\\subsection{Preliminaries on cumulative differences\nbetween distinct subpopulations}\n\\label{subpops}\n\nThis subsection reviews cumulative methods developed by~\\cite{tygert_two}\nfor assessing deviations between different subpopulations.\n\nSimilar to the set-up from the previous subsection,\nthe present subsection considers a strictly increasing sequence\nof distinct real numbers known as ``scores,'' where each score\nis associated with another real number known as a ``response,'' ``result,''\n``regressand,'' or ``outcome,'' as well as with a third, positive real number\nknown as a ``weight.''\nEach score will be designated as belonging either to subpopulation 0\nor to subpopulation 1 (always one or the other, but never both).\nAs in the previous subsection, the probability distributions\nof the responses will be discrete in the examples considered below,\nand the scores, weights, and subpopulation designations will be deterministic,\nnot viewed as random.\nThe following sets up notation in order to define a graph.\n\nFigure~\\ref{partition} illustrates the first stage of processing for this data:\nin each contiguous block of scores from one of the subpopulations,\nthe weighted average of responses gets labeled $R^0_k$ or $R^1_k$,\nthe weighted average of scores gets labeled $S^0_k$ or $S^1_k$,\nand the sum total of the weights gets labeled $T^0_k$ or $T^1_k$\n(with the superscript chosen to match the designation as either subpopulation 0\nor subpopulation 1 associated with the block, and with the subscript $k$\nchosen such that\n$S^0_0 < S^1_0 < S^0_1 < S^1_1 < S^0_2 < S^1_2 < S^0_3 < S^1_3 < \\dots$).\n\nFigures~\\ref{diffs} and~\\ref{sums} illustrate the second stage\nof processing for this data: construct the differences\nwith even-indexed entries\n%\n\\begin{equation}\n\\label{diff_even}\nD_{2k} = \\frac{(R^0_k - R^1_k) + (R^0_{k+1} - R^1_k)}{2}\n       = \\frac{R^0_k + R^0_{k+1} - 2R^1_k}{2}\n\\end{equation}\n%\nand odd-indexed entries\n%\n\\begin{equation}\n\\label{diff_odd}\nD_{2k+1} = \\frac{(R^0_{k+1} - R^1_k) + (R^0_{k+1} - R^1_{k+1})}{2}\n         = \\frac{2R^0_{k+1} - R^1_k - R^1_{k+1}}{2},\n\\end{equation}\n%\nas well as the sums with even-indexed entries\n%\n\\begin{equation}\n\\label{sum_even}\nW_{2k} = \\frac{T^0_k + T^0_{k+1} + 2T^1_k}{2}\n\\end{equation}\n%\nand odd-indexed entries\n%\n\\begin{equation}\n\\label{sum_odd}\nW_{2k+1} = \\frac{2T^0_{k+1} + T^1_k + T^1_{k+1}}{2}.\n\\end{equation}\n%\n\nThe abscissae (that is, the horizontal coordinates)\nfor a graph consist of the normalized aggregated weights\n%\n\\begin{equation}\n\\label{abscissae}\nA_j = \\frac{\\sum_{k=0}^{j-1} W_k}{\\sum_{k=0}^{n-1} W_k}\n\\end{equation}\n%\nfor $j = 1$, $2$, \\dots, $n$.\nThe ordinates (that is, the vertical coordinates)\nfor the graph are the cumulative differences\n%\n\\begin{equation}\n\\label{cumulativew}\nC_j = \\frac{\\sum_{k=0}^{j-1} W_k D_k}{\\sum_{k=0}^{n-1} W_k}\n\\end{equation}\n%\nfor $j = 1$, $2$, \\dots, $n$.\n\nIn a plot where $A_k$ is the abscissa (that is, the horizontal coordinate)\nand $C_k$ is the ordinate (that is, the vertical coordinate),\nthe expected slope of a secant line connecting two points on the graph is equal\nto the weighted average difference in responses\nbetween the two subpopulations over the range of scores between the two points.\nThus, deviation between the subpopulations is simply the slope.\nA long range of steep slopes in the graph indicates significant\nweighted average deviation between the subpopulations over that range.\nIf the weights are all identical ---\n$W_0 = W_1 = \\dots = W_{n-1}$ --- then $A_k = k/n$, so the graph\nof $C_k$ versus $A_k$ is then the same as the usual graph\nof $C_k$ (with equispaced abscissae).\n\nIf the differences are all small, then the graph should be fairly flat\nand hence not deviate much overall.\nTwo standard metrics which summarize the overall deviation across all scores\nare the statistic of Kolmogorov and Smirnov, the maximal absolute deviation\n%\n\\begin{equation}\n\\label{Kolmogorov-Smirnov2}\nG = \\max_{1 \\le k \\le n} |C_k|,\n\\end{equation}\n%\nand the statistic of Kuiper, the size of the range of deviations\n%\n\\begin{equation}\n\\label{Kuiper2}\nH = \\max_{0 \\le k \\le n} C_k - \\min_{0 \\le k \\le n} C_k,\n\\end{equation}\n%\nwith $C_0 = 0$.\nAs in the last paragraph of Subsection~\\ref{subpop},\nnormalizing $G$ and $H$ by an estimate $\\sigma$ characterizes\nstatistical significance under the null hypothesis\nof no difference between the probability distributions\nunderlying the responses of the two subpopulations,\nwhere the estimation of $\\sigma$ is detailed by~\\cite{tygert_two}.\n\n\\begin{figure}\n\\begin{centering}\n\\hfil\\parbox{0.65\\textwidth}\n{\\includegraphics[width=0.65\\textwidth]{./partition.pdf}}\n\\end{centering}\n\\caption{The crosses (``x'') indicate the scores for subpopulation 0\nwhile the circles (``o'') indicate the scores for subpopulation 1.\nThe weighted averages of the scores for subpopulation 0\nfor the indicated blocks of observed scores are\n$S^0_0$, $S^0_1$, \\dots, $S^0_9$,\nwhile the weighted averages of the scores for subpopulation 1 are\n$S^1_0$, $S^1_1$, \\dots, $S^1_9$.\nThe weighted averages of the responses for subpopulation 0 corresponding\nto the indicated blocks of observed scores are\n$R^0_0$, $R^0_1$, \\dots, $R^0_9$, while the weighted averages of the responses\nfor subpopulation 1 are $R^1_0$, $R^1_1$, \\dots, $R^1_9$.\n}\n\\label{partition}\n\\end{figure}\n\n\\begin{figure}\n\\vspace{.2in}\n\\begin{centering}\n\\hfil\n(a) \\parbox{0.111\\textwidth}\n{\\includegraphics[width=0.111\\textwidth]{./diffs0.pdf}}\n\\hfil\n(b) \\parbox{0.111\\textwidth}\n{\\includegraphics[width=0.111\\textwidth]{./diffs1.pdf}}\n\\end{centering}\n\\caption{In each of these subfigures, the operation indicated by ``$+$'' sums\nits two inputs and the operations indicated by ``$-$'' subtract their inputs,\nwith one of these ``$-$'' operations subtracting its rightmost input\nfrom its leftmost input, while the other subtracts its leftmost input\nfrom its rightmost input.\nIn all cases, the operations indicated by ``$-$'' subtract\nsubpopulation 1 from subpopulation 0, in that order.\nThe operation indicated by ``$\\div 2$'' divides its input by 2.\n}\n\\label{diffs}\n\\end{figure}\n\n\\begin{figure}\n\\vspace{.2in}\n\\begin{centering}\n\\hfil\n(a) \\parbox{0.111\\textwidth}\n{\\includegraphics[width=0.111\\textwidth]{./sums0.pdf}}\n\\hfil\n(b) \\parbox{0.111\\textwidth}\n{\\includegraphics[width=0.111\\textwidth]{./sums1.pdf}}\n\\end{centering}\n\\caption{In each of these subfigures, the operation indicated by ``$+$'' sums\nits two inputs. The operation indicated by ``$\\div 2$'' divides its input by 2.\n}\n\\label{sums}\n\\end{figure}\n\n\n\\subsection{Combination}\n\\label{combo}\n\nThis subsection combines the methods summarized\nin Subsections~\\ref{Hilbert}, \\ref{subpop}, and~\\ref{subpops},\nyielding the main methodology of the present paper.\n\nThe cumulative graphs and scalar summary statistics\nof Subsections~\\ref{subpop} and~\\ref{subpops}\nrequire as inputs both scores and responses\n(together with weights when the sampling is weighted).\nEach example considered in the present paper\nwill detail a specific choice of scalar, real-valued responses (and weights,\nwhen using non-uniform weights), chosen similarly to what~\\cite{tygert_full}\nand~\\cite{tygert_two} set as precedents.\nThe novelty of the combined approach that the present subsection proposes\nlies solely in the choice of scores:\n\nFor the scores, we use the mapping $g$ from Subsection~\\ref{Hilbert},\nfirst applying $g$ to the vectors of covariates\nfor the members of the populations and then normalizing the results\nto range from 0 to 1 (the normalization is affine --- linear plus a constant\n--- simply subtracting the minimum of all values\nand then dividing by the original maximum minus the original minimum).\nThese scores directly account for the geometry of the data\nas embedded in the ambient space of covariates, since the Hilbert curve snakes\nthrough the ambient space in accord with the geometry of the ambient space.\nThese scores also account for the intrinsic geometry of the data, or\nat least for the density of data points in various parts of the ambient space\nof covariates. Indeed, while the Hilbert curve is the same for every data set\nwith the same number of covariates, the positioning of the points\nalong the curve is specific to each data set.\n\n\n\n\\section{Results and discussion}\n\\label{results}\n\nThis section illustrates the methods of the previous section\nvia several numerical examples.\\footnote{Permissively licensed\nopen-source Python scripts that reproduce all figures and statistics\nreported here are available at\n\\url{https://github.com/facebookresearch/metamulti}}\nSubsection~\\ref{synthetic} considers synthetic, toy examples\nwhose construction is especially easy to understand.\nSubsection~\\ref{kddcup98} analyzes A/B tests from a classic marketing campaign.\nSubsection~\\ref{acs} analyzes the latest (2019) American Community Survey\nfrom the U.S.\\ Census Bureau, whose data arises from weighted sampling.\nSubsection~\\ref{outlook} discusses the results and proposes avenues\nfor further development of the methods.\n\nThe implementation combines version 2 of the Python package\n{\\tt hilbertcurve}\\footnote{The Python package {\\tt hilbertcurve}\nis available at \\url{https://github.com/galtay/hilbertcurve}\nunder the permissive MIT license.} with the Python modules\n{\\tt fbcdgraph}\\footnote{The Python module {\\tt fbcdgraph}\nis available at \\url{https://github.com/facebookresearch/fbcdgraph}\nunder the MIT copyright license.} and\n{\\tt fbcddisgraph}.\\footnote{The Python module {\\tt fbcddisgraph}\nis available at \\url{https://github.com/facebookresearch/fbcddisgraph}\ncopyrighted under the MIT license.}\n\nIn every plot for a subpopulation\nversus the full population and whose title begins,\n``subpop.\\ deviation is the slope as a function of\\dots,''\nthe slope of the secant line connecting two points on the displayed graph\nconverges to the average deviation of the subpopulation's responses\nfrom the full population's responses,\nwith the average taken over the range of index $k$ between the two points\non the graph, as the range becomes large.\nSimilarly, in every plot for one subpopulation\nversus another distinct subpopulation and whose title begins,\n``subpop.\\ deviation is the slope as a function of\\dots,''\nthe slope of the secant line connecting two points on the displayed graph\nconverges to the average deviation of the first subpopulation's responses\nfrom the other subpopulation's responses,\nwith the average taken over the range of index $k$ between the two points\non the graph, as the range becomes large.\nIf a slope is positive, then the deviation is positive;\nif a slope is negative, then the deviation is negative.\nFlat horizontal lines correspond to lack of deviation.\nThe height of the triangle displayed at the origin of each plot indicates\nthe size of deviations over the full range of scores\nwhich would be statistically significant at about the 95\\% confidence level,\naccounting for random fluctuations expected in the responses\n(recall that the responses are random variables).\n\nThe values of $G$ and $H$ reported beneath the corresponding plots\nrefer to the Kolmogorov-Smirnov and Kuiper statistics\ndefined in~(\\ref{Kolmogorov-Smirnov}) and~(\\ref{Kuiper}), respectively,\nwhen comparing a subpopulation to the full population.\nThe values of $G$ and $H$ refer to the Kolmogorov-Smirnov and Kuiper metrics\ndefined in~(\\ref{Kolmogorov-Smirnov2}) and~(\\ref{Kuiper2}), respectively,\nwhen comparing two different subpopulations directly.\nAs discussed at the ends of Subsections~\\ref{subpop} and~\\ref{subpops},\nthe normalized statistics $G/\\sigma$ and $H/\\sigma$ characterize\nthe statistical significance of the deviations;\nfor example, values of $G/\\sigma$ much greater than 1.25 indicate\nhighly statistically significant deviation,\nwhile values of $G/\\sigma$ near 0 give little indication\nof statistically significant deviation.\n\n\n\\subsection{Synthetic}\n\\label{synthetic}\n\nThis subsection presents Figures~\\ref{synth}--\\ref{randwalks}.\nThese figures consider simple, easily understandable constructions,\ndetailed as follows:\n\nFigures~\\ref{synth}--\\ref{randwalks} pertain to synthetic examples,\nillustrating the methods of Section~\\ref{methods}\nin a controlled setting for which the geometry of the data is easy to grasp.\nWe consider a full population with $m =$ 1,000 members,\n$n =$ 100 observations from a subpopulation,\nand several different numbers of covariates,\nnamely $p =$ 2, 4, 8, 16, \\dots, 4096.\nWe select the subpopulation uniformly at random\nfrom the full population defined as follows.\nWe construct an $m \\times p$ matrix $A$ whose entries\nare independent and identically distributed (i.i.d.)\\ draws\nfrom the uniform distribution over the interval $(-1, 1)$.\nWe generate a $p \\times 1$ vector $v$ whose entries are i.i.d.\\ draws\nfrom the standard normal distribution, so that $v$ points\nin a uniformly random direction.\nFor the responses, we start with the Heaviside function applied\nto every entry of the product of $A$ and $v$\n(the Heaviside function is also known as the unit step function,\nand takes the value 0 for negative arguments and the value 1\nfor positive arguments); for Figures~\\ref{synth}--\\ref{reverses}\n(but not for Figures~\\ref{randwalk} and~\\ref{randwalks}),\nwe then modify the responses for the subpopulation to be 1 always, never 0.\nThus, the responses for the subpopulation are always 1\nfor Figures~\\ref{synth}--\\ref{reverses},\nwhereas the responses for the remaining 90\\% of the full population\nare 1 only about half the time.\nFor the covariates, we normalize the entries of $A$ to range from 0 to 1,\nthat is, the covariates take on the values given by the entries\nof $(A+1)/2$, where $1$ denotes the $m \\times p$ matrix\nwhose entries are all equal to 1.\nWe condition on (that is, control for) all the covariates.\n\nFigures~\\ref{synth} and~\\ref{synths} plot the cumulative graphs\nfor the cases $p =$ 2, 4, 8, 16, \\dots, 4096 indicated to the left\nof each subfigure ($p$ is the number of covariates);\nFigures~\\ref{reverse} and~\\ref{reverses} also plot the cumulative graphs\nfor the cases $p =$ 2, 4, 8, 16, \\dots, 4096 indicated to the left\nof each subfigure, but with the covariates controlled for in reverse order\n(so that the Hilbert curve cycles through the covariates in the reverse order).\nThe normalized scalar summary statistics ($G/\\sigma$ and $H/\\sigma$)\ndisplay a significant decrease as $p$ increases through its smallest values.\nComparing Figure~\\ref{synth} with Figure~\\ref{reverse}\n(as well as Figure~\\ref{synths} with Figure~\\ref{reverses})\nshows that the normalized scalar summary statistics\nare very similar when conditioning on the same sets of covariates, that is,\nthey change little when the order of the covariates is reversed.\n\nFigures~\\ref{randwalk} and~\\ref{randwalks} plot the cumulative graphs\nfor the cases $p =$ 2, 4, 8, 16, \\dots, 4096 indicated to the left\nof each subfigure ($p$ is the number of covariates),\nusing data in which the responses for both the subpopulation\nand the full population are 1 about half the time and 0 about half the time.\nSince there is no statistically significant deviation\nbetween the responses for the subpopulation\nand the responses for the full population,\nthe cumulative graphs should and do look like driftless,\nperfectly random walks.\nThe normalized scalar summary statistics ($G/\\sigma$ and $H/\\sigma$)\naccordingly never indicate any statistically significant deviation,\nwith $G/\\sigma$ never exceeding even twice its expected value of about 1.25\n(the expected value is about $\\sqrt{\\pi/2} \\approx 1.25$\nunder the null hypothesis of no deviation\nbetween the probability distributions underlying the responses\nfor the subpopulation and the responses for the full population,\nas detailed in Remark~7 of~\\cite{tygert_full}).\n\n\n\\subsection{KDD Cup 1998}\n\\label{kddcup98}\n\nThis subsection presents Figures~\\ref{folding}--\\ref{allcovariates};\nTable~\\ref{labels} gives details about each subfigure\nof Figures~\\ref{folding}--\\ref{folding_normal}.\nThese figures consider data from an experiment in direct-mail promotions\nfrom back when snail-mail was a leading means of fundraising,\ndetailed as follows:\n\nIn 1994, a national veterans organization in the U.S. mailed many solicitations\nfor donations, trying different types of mailings to test\nwhich would be best, and later contributed this data\nto the 1998 Knowledge Discovery and Data-mining (KDD) Cup\ncompetition.\\footnote{The data from the 1998 KDD Cup is available\nat \\url{https://kdd.ics.uci.edu/databases/kddcup98/kddcup98.html}}\n1,236 prospective donors received a mailing of folding cards,\n15,866 received a mailing of normal cards,\nand 30,015 got both mailings --- both folding cards and normal cards.\nThese three subsets form natural subpopulations of the full population\nof 47,117.\nAll these numbers exclude those with missing ages (``AGE'' in the data set),\nthose with missing average household incomes in the associated Census block\n(``IC3'' in the data), and those missing what fractions of householders\nin the associated Census block are married (``MARR1'').\nThe figures report results of conditioning on various tuples formed\nfrom combinations of these covariates\n(ages, fractions married, and average household incomes\nrandomly perturbed by about 1 part in $10^8$ to guarantee uniqueness),\nwith each covariate normalized to range from 0 to 1 prior\nto ordering via the Hilbert curve.\nPrior to normalization, age is an integer\nand the fraction married is an integer percentage.\nEach response $R_i$ is simply whether the corresponding prospective donor\nresponded to the mailed solicitation (the mailing is considered effective\nif it resulted in a response and ineffective otherwise,\nwith $R_i = 1$ in the former case and $R_i = 0$ in the latter case).\nFigures~\\ref{folding}--\\ref{folding_normal} present four examples\nconditioning on ordered pairs of covariates.\nThe first three, corresponding to Figures~\\ref{folding}--\\ref{both},\ncompare to the full population the single subpopulation indicated\nin the caption to the corresponding figure;\nthese examples follow Subsection~\\ref{subpop}.\nThe fourth example, corresponding to Figure~\\ref{folding_normal},\ncompares directly the subpopulation sent folding cards only\nto the subpopulation sent normal cards only;\nthis example follows Subsection~\\ref{subpops}.\nTable~\\ref{labels} describes each subfigure\nof Figures~\\ref{folding}--\\ref{folding_normal}.\nFigure~\\ref{allcovariates} presents analogues\nof Figures~\\ref{folding}--\\ref{folding_normal},\nconditioning on all three covariates rather than just the pairs\nconsidered in Figures~\\ref{folding}--\\ref{folding_normal}.\n\nFigures~\\ref{folding}, \\ref{normal}, \\ref{both}, \\ref{allcovariates}(a),\n\\ref{allcovariates}(b), and \\ref{allcovariates}(c)\nfollow Subsection~\\ref{subpop},\nwith $m$ being the number of members of the full population\nand $n$ being the number in the subpopulation.\nFigures~\\ref{folding_normal} and \\ref{allcovariates}(d)\nfollow Subsection~\\ref{subpops},\nwith $n$ being the number of blocks for either one of the subpopulations,\n$n_0$ being the number of members of subpopulation~0,\nand $n_1$ being the number of members of subpopulation~1\n(note that each block can contain multiple members).\n\nIn each of Figures~\\ref{folding}--\\ref{folding_normal},\nthe normalized scalar summary statistic $H/\\sigma$\nis always close across subfigures~(e) and~(f)\nwhile also being either greater than in both subfigures~(e) and~(f)\nor less than in both subfigures~(e) and~(f) when comparing\nwith subfigures~(a) and~(b) (greater in Figures~\\ref{folding} and~\\ref{normal},\nless in Figures~\\ref{both} and~\\ref{folding_normal}).\nMoreover, essentially the same remark holds separately\nfor the normalized scalar summary statistic $G/\\sigma$.\nThis shows empirically that which covariates are conditioned on\ntends to matter more than the ordering within that set of covariates.\n\n\n\\subsection{American Community Survey of the U.S.\\ Census Bureau}\n\\label{acs}\n\nThis subsection presents Figures~\\ref{los_angeles}--\\ref{napa};\nTable~\\ref{labelsw} gives details about each subfigure\nof Figures~\\ref{los_angeles}--\\ref{napa}.\nThese figures consider weighted sampling of the U.S.\\ population,\ndetailed as follows:\n\nAs with most years, in 2019 the U.S.\\ Census Bureau collected\ndetailed information on an extensive sample of households,\nin its American Community Survey.\\footnote{The data\nfrom the American Community Survey is available\nat \\url{https://www.census.gov/programs-surveys/acs/microdata.html}}\nThe sampling in this survey is weighted; to analyze this data,\nwe retain only those households whose weights (``WGTP'' in the microdata)\nare strictly positive (thus also eliminating consideration of group quarters),\nand discard any household whose personal income (``HINCP'') is zero\nor for which the adjustment factor to income (``ADJINC'') is flagged\nas missing (thus eliminating consideration of vacant addresses, too).\nFor the full population, we use the households from all counties\nin the state of California put together; for the subpopulation,\nwe use the households from the individual county specified in the caption\nto the corresponding figure.\nWe consider conditioning on various tuples of covariates, with each covariate\nnormalized to range from 0 to 1 prior to ordering via the Hilbert curve\n(the normalization simply divides by the maximum of all values).\nAll tuples considered include the logarithm\nof the adjusted household personal income\n(the adjusted income is ``HINCP'' times ``ADJINC,'' divided by one million\nwhen ``ADJINC'' omits its decimal point in the integer-valued microdata),\nrandomly perturbed by about one part in $10^8$ to ensure uniqueness.\nThe two other covariates considered as controls are\n(1) the data set's ordinal, integer encoding of the duration\nsince the last move (``MV'' in the microdata) and\n(2) the number of the householder's own children (``NOC'' in the microdata).\nFor the responses $R_1$,~$R_2$, \\dots, $R_m$ (where $m =$ 134,094),\nwe use the variates specified at the beginnings of the captions of the figures.\nAs in Subsection~\\ref{subpop}, $m$ is the number of members\nof the full population, while $n$ is the number in the subpopulation\n(specified in the caption to each figure).\nFigures~\\ref{los_angeles}--\\ref{napa} present six examples.\nTable~\\ref{labelsw} describes each subfigure.\n\nAs in Subsections~\\ref{synthetic} and~\\ref{kddcup98},\nFigures~\\ref{los_angeles}--\\ref{napa} indicate that \nthe normalized scalar summary statistics ($G/\\sigma$ and $H/\\sigma$)\ndepend more on which covariates are conditioned on\nthan on the ordering of the conditioning within a particular set of covariates.\nThe captions of the figures discuss these results in greater detail.\n\n\n\\begin{figure}\n\\begin{centering}\n\n(2) \\parbox{\\imsize}{\\includegraphics[width=\\imsize,\n                                      trim={0pt 0pt 0pt 3pt}, clip]\n{../codes/unweighted/synth0002.pdf}}\n\\quad\\quad\n(32) \\parbox{\\imsize}{\\includegraphics[width=\\imsize,\n                                       trim={0pt 0pt 0pt 3pt}, clip]\n{../codes/unweighted/synth0032.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.3965; $H$ = 0.3965;\n$G/\\sigma$ = 15.66; $H/\\sigma$ = 15.66}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.4063; $H$ = 0.4063;\n$G/\\sigma$ = 9.450; $H/\\sigma$ = 9.450}\n\n\\vspace{\\vertsep}\n\n(4) \\parbox{\\imsize}{\\includegraphics[width=\\imsize,\n                                      trim={0pt 0pt 0pt 2pt}, clip]\n{../codes/unweighted/synth0004.pdf}}\n\\quad\\quad\n(64) \\parbox{\\imsize}{\\includegraphics[width=\\imsize,\n                                       trim={0pt 0pt 0pt 2pt}, clip]\n{../codes/unweighted/synth0064.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.4256; $H$ = 0.4256;\n$G/\\sigma$ = 13.03; $H/\\sigma$ = 13.03}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.4368; $H$ = 0.4368;\n$G/\\sigma$ = 9.967; $H/\\sigma$ = 9.967}\n\n\\vspace{\\vertsep}\n\n(8) \\parbox{\\imsize}{\\includegraphics[width=\\imsize,\n                                      trim={0pt 0pt 0pt 2pt}, clip]\n{../codes/unweighted/synth0008.pdf}}\n\\quad\\quad\n(128) \\parbox{\\imsize}{\\includegraphics[width=\\imsize,\n                                        trim={0pt 0pt 0pt 2pt}, clip]\n{../codes/unweighted/synth0128.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.3924; $H$ = 0.3924;\n$G/\\sigma$ = 10.58; $H/\\sigma$ = 10.58}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.4090; $H$ = 0.4090;\n$G/\\sigma$ = 9.099; $H/\\sigma$ = 9.099}\n\n\\vspace{\\vertsep}\n\n(16) \\parbox{\\imsize}{\\includegraphics[width=\\imsize,\n                                       trim={0pt 0pt 0pt 2pt}, clip]\n{../codes/unweighted/synth0016.pdf}}\n\\quad\\quad\n(256) \\parbox{\\imsize}{\\includegraphics[width=\\imsize,\n                                        trim={0pt 0pt 0pt 2pt}, clip]\n{../codes/unweighted/synth0256.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.3960; $H$ = 0.3960;\n$G/\\sigma$ = 9.833; $H/\\sigma$ = 9.833}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.3978; $H$ = 0.3978;\n$G/\\sigma$ = 8.962; $H/\\sigma$ = 8.962}\n\n\\end{centering}\n\\caption{Synthetic examples with a varying number of covariates\n($m =$ 1,000; $n =$ 100)}\n\\label{synth}\n\\end{figure}\n\n\n\\begin{figure}\n\\begin{centering}\n(512) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/synth0512.pdf}}\n\\quad\n(2048) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/synth2048.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.3975; $H$ = 0.3975;\n$G/\\sigma$ = 8.916; $H/\\sigma$ = 8.916}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.3983; $H$ = 0.3983;\n$G/\\sigma$ = 8.716; $H/\\sigma$ = 8.716}\n\n\\vspace{\\vertsep}\n\n(1024) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/synth1024.pdf}}\n\\quad\n(4096) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/synth4096.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.4411; $H$ = 0.4411;\n$G/\\sigma$ = 9.428; $H/\\sigma$ = 9.428}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.4082; $H$ = 0.4082;\n$G/\\sigma$ = 8.962; $H/\\sigma$ = 8.962}\n\\end{centering}\n\\caption{Synthetic examples with even more covariates ($m =$ 1,000; $n =$ 100)}\n\\label{synths}\n\\end{figure}\n\n\n\\begin{figure}\n\\begin{centering}\n\n(2) \\parbox{\\imsize}{\\includegraphics[width=\\imsize,\n                                      trim={0pt 0pt 0pt 3pt}, clip]\n{../codes/unweighted/reverse0002.pdf}}\n\\quad\\quad\n(32) \\parbox{\\imsize}{\\includegraphics[width=\\imsize,\n                                       trim={0pt 0pt 0pt 3pt}, clip]\n{../codes/unweighted/reverse0032.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.4110; $H$ = 0.4110;\n$G/\\sigma$ = 15.90; $H/\\sigma$ = 15.90}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.4185; $H$ = 0.4185;\n$G/\\sigma$ = 9.104; $H/\\sigma$ = 9.104}\n\n\\vspace{\\vertsep}\n\n(4) \\parbox{\\imsize}{\\includegraphics[width=\\imsize,\n                                      trim={0pt 0pt 0pt 2pt}, clip]\n{../codes/unweighted/reverse0004.pdf}}\n\\quad\\quad\n(64) \\parbox{\\imsize}{\\includegraphics[width=\\imsize,\n                                       trim={0pt 0pt 0pt 2pt}, clip]\n{../codes/unweighted/reverse0064.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.4225; $H$ = 0.4225;\n$G/\\sigma$ = 13.03; $H/\\sigma$ = 13.03}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.4267; $H$ = 0.4267;\n$G/\\sigma$ = 9.530; $H/\\sigma$ = 9.530}\n\n\\vspace{\\vertsep}\n\n(8) \\parbox{\\imsize}{\\includegraphics[width=\\imsize,\n                                      trim={0pt 0pt 0pt 2pt}, clip]\n{../codes/unweighted/reverse0008.pdf}}\n\\quad\\quad\n(128) \\parbox{\\imsize}{\\includegraphics[width=\\imsize,\n                                        trim={0pt 0pt 0pt 2pt}, clip]\n{../codes/unweighted/reverse0128.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.3912; $H$ = 0.3912;\n$G/\\sigma$ = 10.41; $H/\\sigma$ = 10.41}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.3880; $H$ = 0.3880;\n$G/\\sigma$ = 8.894; $H/\\sigma$ = 8.894}\n\n\\vspace{\\vertsep}\n\n(16) \\parbox{\\imsize}{\\includegraphics[width=\\imsize,\n                                       trim={0pt 0pt 0pt 2pt}, clip]\n{../codes/unweighted/reverse0016.pdf}}\n\\quad\\quad\n(256) \\parbox{\\imsize}{\\includegraphics[width=\\imsize,\n                                        trim={0pt 0pt 0pt 2pt}, clip]\n{../codes/unweighted/reverse0256.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.4087; $H$ = 0.4087;\n$G/\\sigma$ = 9.768; $H/\\sigma$ = 9.768}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.4055; $H$ = 0.4055;\n$G/\\sigma$ = 9.153; $H/\\sigma$ = 9.153}\n\n\\end{centering}\n\\caption{Synthetic examples with a varying number of covariates,\nreversing the order of the covariates}\n\\label{reverse}\n\\end{figure}\n\n\n\\begin{figure}\n\\begin{centering}\n(512) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/reverse0512.pdf}}\n\\quad\n(2048) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/reverse2048.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.3927; $H$ = 0.3927;\n$G/\\sigma$ = 8.798; $H/\\sigma$ = 8.798}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.4044; $H$ = 0.4044;\n$G/\\sigma$ = 8.872; $H/\\sigma$ = 8.872}\n\n\\vspace{\\vertsep}\n\n(1024) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/reverse1024.pdf}}\n\\quad\n(4096) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/reverse4096.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.4305; $H$ = 0.4305;\n$G/\\sigma$ = 9.496; $H/\\sigma$ = 9.496}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.3966; $H$ = 0.3966;\n$G/\\sigma$ = 8.806; $H/\\sigma$ = 8.806}\n\\end{centering}\n\\caption{Synthetic examples with even more covariates,\nreversing the order of the covariates}\n\\label{reverses}\n\\end{figure}\n\n\n\\begin{figure}\n\\begin{centering}\n\n(2) \\parbox{\\imsize}{\\includegraphics[width=\\imsize,\n                                      trim={0pt 0pt 0pt 3pt}, clip]\n{../codes/unweighted/randwalk0002.pdf}}\n\\quad\\quad\n(32) \\parbox{\\imsize}{\\includegraphics[width=\\imsize,\n                                       trim={0pt 0pt 0pt 3pt}, clip]\n{../codes/unweighted/randwalk0032.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.006815; $H$ = 0.006815;\n$G/\\sigma$ = 0.6642; $H/\\sigma$ = 0.6642}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.06699; $H$ = 0.08992;\n$G/\\sigma$ = 1.616; $H/\\sigma$ = 2.169}\n\n\\vspace{\\vertsep}\n\n(4) \\parbox{\\imsize}{\\includegraphics[width=\\imsize,\n                                      trim={0pt 0pt 0pt 2pt}, clip]\n{../codes/unweighted/randwalk0004.pdf}}\n\\quad\\quad\n(64) \\parbox{\\imsize}{\\includegraphics[width=\\imsize,\n                                       trim={0pt 0pt 0pt 2pt}, clip]\n{../codes/unweighted/randwalk0064.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.0570; $H$ = 0.0570;\n$G/\\sigma$ = 2.281; $H/\\sigma$ = 2.281}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.06966; $H$ = 0.09274;\n$G/\\sigma$ = 1.636; $H/\\sigma$ = 2.178}\n\n\\vspace{\\vertsep}\n\n(8) \\parbox{\\imsize}{\\includegraphics[width=\\imsize,\n                                      trim={0pt 0pt 0pt 2pt}, clip]\n{../codes/unweighted/randwalk0008.pdf}}\n\\quad\\quad\n(128) \\parbox{\\imsize}{\\includegraphics[width=\\imsize,\n                                        trim={0pt 0pt 0pt 2pt}, clip]\n{../codes/unweighted/randwalk0128.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.02393; $H$ = 0.04177;\n$G/\\sigma$ = 0.6957; $H/\\sigma$ = 1.214}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.05644; $H$ = 0.06315;\n$G/\\sigma$ = 1.249; $H/\\sigma$ = 1.397}\n\n\\vspace{\\vertsep}\n\n(16) \\parbox{\\imsize}{\\includegraphics[width=\\imsize,\n                                       trim={0pt 0pt 0pt 2pt}, clip]\n{../codes/unweighted/randwalk0016.pdf}}\n\\quad\\quad\n(256) \\parbox{\\imsize}{\\includegraphics[width=\\imsize,\n                                        trim={0pt 0pt 0pt 2pt}, clip]\n{../codes/unweighted/randwalk0256.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.05145; $H$ = 0.05289;\n$G/\\sigma$ = 1.329; $H/\\sigma$ = 1.366}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.03697; $H$ = 0.05481;\n$G/\\sigma$ = 0.8171; $H/\\sigma$ = 1.211}\n\n\\end{centering}\n\\caption{Synthetic examples with a varying number of covariates\nbut no significant deviation}\n\\label{randwalk}\n\\end{figure}\n\n\n\\clearpage\n\n\n\\begin{figure}\n\\begin{centering}\n(512) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/randwalk0512.pdf}}\n\\quad\n(2048) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/randwalk2048.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.03135; $H$ = 0.05414;\n$G/\\sigma$ = 0.6899; $H/\\sigma$ = 1.192}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.03382; $H$ = 0.04174;\n$G/\\sigma$ = 0.7518; $H/\\sigma$ = 0.9279}\n\n\\vspace{\\vertsep}\n\n(1024) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/randwalk1024.pdf}}\n\\quad\n(4096) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/randwalk4096.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.04182; $H$ = 0.05950;\n$G/\\sigma$ = 0.9003; $H/\\sigma$ = 1.281}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.03812; $H$ = 0.05705;\n$G/\\sigma$ = 0.8321; $H/\\sigma$ = 1.245}\n\\end{centering}\n\\caption{Synthetic examples with even more covariates\nbut no significant deviation}\n\\label{randwalks}\n\\end{figure}\n\n\n\n\\begin{table}\n\\caption{Description of subfigures\nfor Figures~\\ref{folding}--\\ref{folding_normal};\nthe averages and percentages mentioned in the table refer to the individual's\nCensus block, and every covariate is normalized to range from 0 to 1.\nThe conditioning (via the Hilbert curve) happens in the order specified\nin the table.}\n\\label{labels}\n\\begin{center}\n\\begin{tabular}{rl}\nsubfigure & description \\\\\\hline\n(a) & conditioning on the individual's age and the average household income\ntoo \\\\\n(b) & conditioning on the average household income and the individual's age\ntoo \\\\\n(c) & the average household income versus the individual's age \\\\\n(d) & the individual's age versus the average household income \\\\\n(e) & conditioning on the percent married and the average household income\ntoo \\\\\n(f) & conditioning on the average household income and the percent married\ntoo \\\\\n(g) & the average household income versus the percent married \\\\\n(h) & the percent married versus the average household income \\\\\\hline\n& The points' intensities indicate the total ordering given\nby the Hilbert curve. \\\\\n& The grayscale plots, which compare a subpopulation to the full population, \\\\\n(c), (d), (g), (h) &\nuse large points for the subpopulation and small for the full population. \\\\\n& The color plots, which compare two subpopulations (numbered 0 and 1), \\\\\n& use blue points for subpopulation 0 on top of red points for subpopulation 1.\n\\end{tabular}\n\\end{center}\n\\end{table}\n\n\n\\begin{figure}\n\\begin{centering}\n\n(a) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/folding/02/cumulative.pdf}}\n\\quad\\quad\n(b) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/folding/20/cumulative.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.1526; $H$ = 0.1526;\n$G/\\sigma$ = 11.54; $H/\\sigma$ = 11.54}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.1547; $H$ = 0.1554;\n$G/\\sigma$ = 11.71; $H/\\sigma$ = 11.76}\n\n\\vspace{\\vertsep}\n\n(c) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/folding/02/inputs.jpg}}\n\\quad\\quad\n(d) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/folding/20/inputs.jpg}}\n\n\\vspace{\\vertsep}\n\n(e) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/folding/12/cumulative.pdf}}\n\\quad\\quad\n(f) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/folding/21/cumulative.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.1559; $H$ = 0.1559;\n$G/\\sigma$ = 11.80; $H/\\sigma$ = 11.80}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.1565; $H$ = 0.1565;\n$G/\\sigma$ = 11.85; $H/\\sigma$ = 11.85}\n\n\\vspace{\\vertsep}\n\n(g) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/folding/12/inputs.jpg}}\n\\quad\\quad\n(h) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/folding/21/inputs.jpg}}\n\n\\end{centering}\n\\caption{Responses from folding cards versus the full population\n($m =$ 47,117; $n =$ 1,236)}\n\\label{folding}\n\\end{figure}\n\n\n\\begin{figure}\n\\begin{centering}\n\n(a) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/normal/02/cumulative.pdf}}\n\\quad\\quad\n(b) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/normal/20/cumulative.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.04787; $H$ = 0.04787;\n$G/\\sigma$ = 18.27; $H/\\sigma$ = 18.27}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.04850; $H$ = 0.04852;\n$G/\\sigma$ = 18.59; $H/\\sigma$ = 18.60}\n\n\\vspace{\\vertsep}\n\n(c) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/normal/02/inputs.jpg}}\n\\quad\\quad\n(d) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/normal/20/inputs.jpg}}\n\n\\vspace{\\vertsep}\n\n(e) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/normal/12/cumulative.pdf}}\n\\quad\\quad\n(f) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/normal/21/cumulative.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.05023; $H$ = 0.05023;\n$G/\\sigma$ = 18.92; $H/\\sigma$ = 18.92}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.05046; $H$ = 0.05052;\n$G/\\sigma$ = 18.93; $H/\\sigma$ = 18.95}\n\n\\vspace{\\vertsep}\n\n(g) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/normal/12/inputs.jpg}}\n\\quad\\quad\n(h) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/normal/21/inputs.jpg}}\n\n\\end{centering}\n\\caption{Responses from normal cards versus the full population\n($m =$ 47,117; $n =$ 15,866)}\n\\label{normal}\n\\end{figure}\n\n\n\\begin{figure}\n\\begin{centering}\n\n(a) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/both/02/cumulative.pdf}}\n\\quad\\quad\n(b) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/both/20/cumulative.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.02668; $H$ = 0.02668;\n$G/\\sigma$ = 21.01; $H/\\sigma$ = 21.01}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.02702; $H$ = 0.02703;\n$G/\\sigma$ = 21.32; $H/\\sigma$ = 21.33}\n\n\\vspace{\\vertsep}\n\n(c) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/both/02/inputs.jpg}}\n\\quad\\quad\n(d) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/both/20/inputs.jpg}}\n\n\\vspace{\\vertsep}\n\n(e) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/both/12/cumulative.pdf}}\n\\quad\\quad\n(f) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/both/21/cumulative.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.02710; $H$ = 0.02714;\n$G/\\sigma$ = 21.02; $H/\\sigma$ = 21.05}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.02706; $H$ = 0.02706;\n$G/\\sigma$ = 21.07; $H/\\sigma$ = 21.07}\n\n\\vspace{\\vertsep}\n\n(g) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/both/12/inputs.jpg}}\n\\quad\\quad\n(h) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/both/21/inputs.jpg}}\n\n\\end{centering}\n\\caption{Responses from those sent both types versus the full population\n($m =$ 47,117; $n =$ 30,015)}\n\\label{both}\n\\end{figure}\n\n\n\\begin{figure}\n\\begin{centering}\n\n(a) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/folding_normal/02/cumulative.pdf}}\n\\quad\\quad\n(b) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/folding_normal/20/cumulative.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.09407; $H$ = 0.09442;\n$G/\\sigma$ = 4.509; $H/\\sigma$ = 4.525}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.09591; $H$ = 0.09694;\n$G/\\sigma$ = 4.595; $H/\\sigma$ = 4.644}\n\n\\vspace{\\vertsep}\n\n(c) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/folding_normal/02/blue_on_red.jpg}}\n\\quad\\quad\n(d) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/folding_normal/20/blue_on_red.jpg}}\n\n\\vspace{\\vertsep}\n\n(e) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/folding_normal/12/cumulative.pdf}}\n\\quad\\quad\n(f) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/folding_normal/21/cumulative.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.09469; $H$ = 0.09469;\n$G/\\sigma$ = 4.527; $H/\\sigma$ = 4.527}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.08869; $H$ = 0.08869;\n$G/\\sigma$ = 4.232; $H/\\sigma$ = 4.232}\n\n\\vspace{\\vertsep}\n\n(g) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/folding_normal/12/blue_on_red.jpg}}\n\\quad\\quad\n(h) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/folding_normal/21/blue_on_red.jpg}}\n\n\\end{centering}\n\\caption{Responses from folding cards versus normal cards\n($n =$ 2,279 --- $n_0 =$ 1,236; $n_1 =$ 15,866)}\n\\label{folding_normal}\n\\end{figure}\n\n\n\\begin{figure}\n\\begin{centering}\n\n(a) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/folding/012/cumulative.pdf}}\n\\quad\\quad\n(b) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/normal/012/cumulative.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.1515; $H$ = 0.1515;\n$G/\\sigma$ = 11.47; $H/\\sigma$ = 11.47}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.04964; $H$ = 0.04964;\n$G/\\sigma$ = 18.70; $H/\\sigma$ = 18.70}\n\n\\vspace{\\vertsep}\n\n(c) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/both/012/cumulative.pdf}}\n\\quad\\quad\n(d) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/unweighted/folding_normal/012/cumulative.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.02537; $H$ = 0.02537;\n$G/\\sigma$ = 19.95; $H/\\sigma$ = 19.95}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.09074; $H$ = 0.09136;\n$G/\\sigma$ = 4.332; $H/\\sigma$ = 4.362}\n\n\\end{centering}\n\\caption{Responses while controlling for the individual's age as well as\nfor the percent married and the average household income\nin the individual's Census block ($m =$ 47,117);\nthe indicated subfigures compare\n(a) folding cards only versus the full population ($n =$ 1,236),\n(b) normal cards only versus the full population ($n =$ 15,866),\n(c) those sent both folding and normal cards versus the full population\n($n =$ 30,015), and (d)~folding cards only versus normal cards only\n($n =$ 2,279 --- $n_0 =$ 1,236; $n_1 =$ 15,866)}\n\\label{allcovariates}\n\\end{figure}\n\n\n\n\\begin{table}\n\\caption{Description of subfigures for Figures~\\ref{los_angeles}--\\ref{napa};\nall variates pertain to the Census-defined individual household\nunder consideration.}\n\\label{labelsw}\n\\begin{center}\n\\begin{tabular}{rl}\nsubfigure & description \\\\\\hline\n(a) & conditioning on the log of the income\nand on the duration since last moving \\\\\n(b) & conditioning on the log of the income\nand on the number of children \\\\\n(c) & the duration since last moving versus the logarithm of the income \\\\\n(d) & the number of children versus the logarithm of the income \\\\\n(e) & conditioning on the duration since last moving,\non the number of children, \\\\\n& and on the logarithm of the income, in that order \\\\\n(f) & conditioning on the number of children,\non the duration since last moving, \\\\\n& and on the logarithm of the income, in that order \\\\\\hline\n& The points' intensities indicate the total ordering given\nby the Hilbert curve. \\\\\n(c), (d) & The grayscale plots, which compare a subpopulation\nto the full population, \\\\\n& use large points for the subpopulation and small for the full population.\n\\end{tabular}\n\\end{center}\n\\end{table}\n\n\n\\clearpage\n\n\n\\begin{figure}\n\\begin{centering}\n\n(a) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/MV/County_of_Los_Angeles-NP/cumulative.pdf}}\n\\quad\\quad\n(b) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/NOC/County_of_Los_Angeles-NP/cumulative.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.09221; $H$ = 0.09267;\n$G/\\sigma$ = 13.38; $H/\\sigma$ = 13.45}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.09514; $H$ = 0.09595;\n$G/\\sigma$ = 17.73; $H/\\sigma$ = 17.88}\n\n\\vspace{\\vertsep}\n\n(c) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/MV/County_of_Los_Angeles-NP/inputs.jpg}}\n\\quad\\quad\n(d) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/NOC/County_of_Los_Angeles-NP/inputs.jpg}}\n\n\\vspace{\\vertsep}\n\n(e) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/MV+NOC/County_of_Los_Angeles-NP/cumulative.pdf}}\n\\quad\\quad\n(f) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/NOC+MV/County_of_Los_Angeles-NP/cumulative.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.08162; $H$ = 0.08209;\n$G/\\sigma$ = 15.40; $H/\\sigma$ = 15.48}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.07591; $H$ = 0.07674;\n$G/\\sigma$ = 14.06; $H/\\sigma$ = 14.22}\n\n\\end{centering}\n\\caption{Los Angeles County ($m =$ 134,094; $n =$ 35,364),\nnumber of persons in the household;\nnotice that conditioning on ``MV'' and ``NOC'' in that order (e)\nyields results more similar to conditioning on ``NOC'' and ``MV'' (f)\nthan to conditioning only on ``MV'' (a) or only on ``NOC'' (b) ---\nthe results of controlling for covariates appear to depend more on the choice\nof the set of covariates than on the ordering of the conditioning\nwithin a particular set. All cases condition also on the logarithm\nof the adjusted household personal income, in addition to the combinations\nof covariates ``MV'' and ``NOC'' mentioned here --- see Table~\\ref{labelsw},\nwhich details subfigures~(c) and~(d), too.}\n\\label{los_angeles}\n\\end{figure}\n\n\n\\begin{figure}\n\\begin{centering}\n\n(a) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/MV/County_of_San_Joaquin-NRC/cumulative.pdf}}\n\\quad\\quad\n(b) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/NOC/County_of_San_Joaquin-NRC/cumulative.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.1624; $H$ = 0.1665;\n$G/\\sigma$ = 6.706; $H/\\sigma$ = 6.875}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.01118; $H$ = 0.01495;\n$G/\\sigma$ = 1.165; $H/\\sigma$ = 1.557}\n\n\\vspace{\\vertsep}\n\n(c) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/MV/County_of_San_Joaquin-NRC/inputs.jpg}}\n\\quad\\quad\n(d) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/NOC/County_of_San_Joaquin-NRC/inputs.jpg}}\n\n\\vspace{\\vertsep}\n\n(e) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/MV+NOC/County_of_San_Joaquin-NRC/cumulative.pdf}}\n\\quad\\quad\n(f) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/NOC+MV/County_of_San_Joaquin-NRC/cumulative.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.01291; $H$ = 0.01714;\n$G/\\sigma$ = 1.371; $H/\\sigma$ = 1.821}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.01198; $H$ = 0.02339;\n$G/\\sigma$ = 1.243; $H/\\sigma$ = 2.426}\n\n\\end{centering}\n\\caption{San Joaquin County ($m =$ 134,094; $n =$ 2,282),\nnumber of related children in the household;\nnotice that conditioning on ``MV'' and ``NOC'' in that order (e)\nyields a graph more similar to conditioning on ``NOC'' and ``MV'' (f)\nthan to conditioning only on ``MV'' (a) or only on ``NOC'' (b) ---\nagain the graphs seem to depend more on the choice\nof which set of covariates constitutes the controls\nthan on the ordering of the conditioning within a particular set.\nAll cases condition also on the logarithm\nof the adjusted household personal income, in addition to the combinations\nof covariates ``MV'' and ``NOC'' mentioned here --- see Table~\\ref{labelsw},\nwhich details subfigures~(c) and~(d), too.}\n\\label{san_joaquin}\n\\end{figure}\n\n\n\\begin{figure}\n\\begin{centering}\n\n(a) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/MV/County_of_Stanislaus-NRC/cumulative.pdf}}\n\\quad\\quad\n(b) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/NOC/County_of_Stanislaus-NRC/cumulative.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.1523; $H$ = 0.1546;\n$G/\\sigma$ = 5.470; $H/\\sigma$ = 5.551}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.008848; $H$ = 0.01096;\n$G/\\sigma$ = 0.7724; $H/\\sigma$ = 0.9568}\n\n\\vspace{\\vertsep}\n\n(c) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/MV/County_of_Stanislaus-NRC/inputs.jpg}}\n\\quad\\quad\n(d) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/NOC/County_of_Stanislaus-NRC/inputs.jpg}}\n\n\\vspace{\\vertsep}\n\n(e) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/MV+NOC/County_of_Stanislaus-NRC/cumulative.pdf}}\n\\quad\\quad\n(f) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/NOC+MV/County_of_Stanislaus-NRC/cumulative.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.01005; $H$ = 0.01505;\n$G/\\sigma$ = 0.8283; $H/\\sigma$ = 1.241}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.01545; $H$ = 0.01602;\n$G/\\sigma$ = 1.341; $H/\\sigma$ = 1.391}\n\n\\end{centering}\n\\caption{Stanislaus County ($m =$ 134,094; $n =$ 1,624),\nnumber of related children in the household;\nnotice that conditioning on ``MV'' and ``NOC'' in that order (e) yields\nmetrics more similar to those when conditioning on ``NOC'' and ``MV'' (f)\nthan to those when conditioning only on ``MV'' (a) or only on ``NOC'' (b) ---\nthe Kolmogorov-Smirnov and Kuiper metrics when controlling\nfor covariates apparently depend more on the choice\nof the set of covariates than on the ordering of the conditioning\nwithin a particular set. All cases condition also on the logarithm\nof the adjusted household personal income, in addition to the combinations\nof covariates ``MV'' and ``NOC'' mentioned here --- see Table~\\ref{labelsw},\nwhich details subfigures~(c) and~(d), too.}\n\\label{stanislaus}\n\\end{figure}\n\n\n\\begin{figure}\n\\begin{centering}\n\n(a) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/MV/County_of_Orange-HISPEED/cumulative.pdf}}\n\\quad\\quad\n(b) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/NOC/County_of_Orange-HISPEED/cumulative.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.02821; $H$ = 0.02825;\n$G/\\sigma$ = 6.840; $H/\\sigma$ = 6.849}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.02394; $H$ = 0.02407;\n$G/\\sigma$ = 5.738; $H/\\sigma$ = 5.769}\n\n\\vspace{\\vertsep}\n\n(c) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/MV/County_of_Orange-HISPEED/inputs.jpg}}\n\\quad\\quad\n(d) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/NOC/County_of_Orange-HISPEED/inputs.jpg}}\n\n\\vspace{\\vertsep}\n\n(e) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/MV+NOC/County_of_Orange-HISPEED/cumulative.pdf}}\n\\quad\\quad\n(f) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/NOC+MV/County_of_Orange-HISPEED/cumulative.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.02709; $H$ = 0.02713;\n$G/\\sigma$ = 6.521; $H/\\sigma$ = 6.529}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.02570; $H$ = 0.02573;\n$G/\\sigma$ = 6.287; $H/\\sigma$ = 6.295}\n\n\\end{centering}\n\\caption{Orange County ($m =$ 134,094; $n =$ 10,680),\nhousehold has high-speed (broadband) access to the Internet;\nall four cumulative graphs are fairly similar.\nSee Table~\\ref{labelsw} for detailed descriptions of the subfigures.}\n\\label{orange}\n\\end{figure}\n\n\n\\begin{figure}\n\\begin{centering}\n\n(a) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/MV/County_of_Humboldt-LNGI/cumulative.pdf}}\n\\quad\\quad\n(b) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/NOC/County_of_Humboldt-LNGI/cumulative.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.08140; $H$ = 0.08140;\n$G/\\sigma$ = 5.721; $H/\\sigma$ = 5.721}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.08751; $H$ = 0.08751;\n$G/\\sigma$ = 6.321; $H/\\sigma$ = 6.321}\n\n\\vspace{\\vertsep}\n\n(c) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/MV/County_of_Humboldt-LNGI/inputs.jpg}}\n\\quad\\quad\n(d) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/NOC/County_of_Humboldt-LNGI/inputs.jpg}}\n\n\\vspace{\\vertsep}\n\n(e) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/MV+NOC/County_of_Humboldt-LNGI/cumulative.pdf}}\n\\quad\\quad\n(f) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/NOC+MV/County_of_Humboldt-LNGI/cumulative.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.08636; $H$ = 0.08636;\n$G/\\sigma$ = 6.083; $H/\\sigma$ = 6.083}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.08488; $H$ = 0.08488;\n$G/\\sigma$ = 6.008; $H/\\sigma$ = 6.008}\n\n\\end{centering}\n\\caption{Humboldt County ($m =$ 134,094; $n =$ 583),\nhousehold includes someone older than 13 who speaks English very well.\nOnce again, conditioning on ``MV'' and ``NOC'' in that order (e) yields\nmetrics more similar to those when conditioning on ``NOC'' and ``MV'' (f)\nthan to those when conditioning only on ``MV'' (a) or only on ``NOC'' (b) ---\nthe Kolmogorov-Smirnov and Kuiper metrics when controlling\nfor covariates seem to depend more on the choice\nof the set of covariates than on the ordering of the conditioning\nwithin a particular set. All cases condition also on the logarithm\nof the adjusted household personal income, in addition to the combinations\nof covariates ``MV'' and ``NOC'' mentioned here --- see Table~\\ref{labelsw},\nwhich details subfigures~(c) and~(d), too.}\n\\label{humboldt}\n\\end{figure}\n\n\n\\begin{figure}\n\\begin{centering}\n\n(a) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/MV/County_of_Napa-SATELLITE/cumulative.pdf}}\n\\quad\\quad\n(b) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/NOC/County_of_Napa-SATELLITE/cumulative.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.05191; $H$ = 0.05346;\n$G/\\sigma$ = 3.995; $H/\\sigma$ = 4.114}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.04128; $H$ = 0.04314;\n$G/\\sigma$ = 3.114; $H/\\sigma$ = 3.254}\n\n\\vspace{\\vertsep}\n\n(c) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/MV/County_of_Napa-SATELLITE/inputs.jpg}}\n\\quad\\quad\n(d) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/NOC/County_of_Napa-SATELLITE/inputs.jpg}}\n\n\\vspace{\\vertsep}\n\n(e) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/MV+NOC/County_of_Napa-SATELLITE/cumulative.pdf}}\n\\quad\\quad\n(f) \\parbox{\\imsize}{\\includegraphics[width=\\imsize]\n{../codes/weighted/NOC+MV/County_of_Napa-SATELLITE/cumulative.pdf}}\n\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.06203; $H$ = 0.06320;\n$G/\\sigma$ = 4.685; $H/\\sigma$ = 4.773}\n\\parbox{\\imsized}{\\hfil \\footnotesize $G$ = 0.06783; $H$ = 0.06957;\n$G/\\sigma$ = 4.935; $H/\\sigma$ = 5.061}\n\n\\end{centering}\n\\caption{Napa County ($m =$ 134,094; $n =$ 679),\nhousehold obtains access to the Internet via satellite.\nYet again, conditioning on ``MV'' and ``NOC'' in that order (e) yields\nmetrics closer to those when conditioning on ``NOC'' and ``MV'' (f)\nthan to those when conditioning only on ``MV'' (a) or only on ``NOC'' (b) ---\nthe Kolmogorov-Smirnov and Kuiper metrics when controlling\nfor covariates appear to depend more on the choice\nof the set of covariates than on the ordering of the conditioning\nwithin a particular set. All cases condition also on the logarithm\nof the adjusted household personal income, in addition to the combinations\nof covariates ``MV'' and ``NOC'' mentioned here --- see Table~\\ref{labelsw},\nwhich details subfigures~(c) and~(d), too.}\n\\label{napa}\n\\end{figure}\n\n\n\\clearpage\n\n\n\\subsection{Future outlook}\n\\label{outlook}\n\nThis subsection discusses potential alternatives to and generalizations of\nthe space-filling curves used in the present paper.\n\nThe Hilbert curve is ideal for adhering to the geometry of the data given\nby the $L^1$ metric of the ambient space of covariates\n(the $L^1$ distance is also known as the ``Manhattan,'' ``city block,''\nor ``taxicab'' metric, as reviewed, for example,\nby~\\cite{cormen-leiserson-rivest-stein}).\nThe Hilbert curve avoids mixing together different coordinates\nas the Euclidean metric does.\nHowever, the Hilbert curve is agnostic to the intrinsic geometry\nof the data set, except insofar as applying the inverse mapping $g$\nfrom Subsection~\\ref{Hilbert} encodes the density of data points\nin various parts of the ambient space.\nOne way to account more extensively for the intrinsic geometry of the data\nwould be to find an approximate solution to the traveling salesman problem,\nyielding a total order for the data points, as reviewed, for example,\nby~\\cite{cormen-leiserson-rivest-stein}.\nIn the examples above which condition on one discrete variable\ntogether with one variable that takes on a fairly dense set of values\ncontinuously throughout its range, the solution\nto the traveling salesman problem yields the snake raster ordering.\nThe snake raster scan simply stratifies the data into separate slices,\none for each value of the discrete variable, then concatenates these slices\ntogether in the order given by the values of the discrete variable.\nThe methods of Subsections~\\ref{subpop} and~\\ref{subpops} thus degenerate\nwhen using the ordering from the solution to the traveling salesman problem,\nessentially analyzing each stratum\n(one for each value of the discrete covariate) separately.\nNevertheless, using an approximate solution to the traveling salesman problem\ndoes account for the intrinsic geometry of the data set and may be helpful\nwhen conditioning on many covariates or with other data sets that are\nvery sparse. Still, the degeneration of the solution\nto the traveling salesman problem in even the simplest real examples\ngiven above indicates that more meaningfully accounting\nfor the intrinsic geometry of the data set might require better ideas.\nPerhaps future work will address this issue.\n\n\n\n\\section{Conclusion}\n\\label{conclusion}\n\nTraditional methods of controlling for or conditioning on specified covariates\ndepend on fairly arbitrary and often debatable choices,\nwhether using binning, separation, segmentation, stratification, or smoothing,\nor using regression analysis via parametric or semi-parametric modeling.\nIn contrast, the graphical method and scalar summary statistics\nproposed in the present paper are fully automatic,\nunique to the extent that the Hilbert curve is unique,\nthat is, unique modulo the ordering of the dimensions\ncorresponding to the covariates.\nThe Hilbert curve induces a total ordering on the values\ntaken by the vector of covariates, naturally yielding one-dimensional scores\nfor use in the methodology of~\\cite{tygert_full} and~\\cite{tygert_two}\n(the methodology of~\\cite{tygert_full} and~\\cite{tygert_two}\nis tailor-made for one-dimensional scores);\nthe continuity of the curve as a mapping from one dimension\nto multiple dimensions ensures that the cumulative approach\nof~\\cite{tygert_full} and~\\cite{tygert_two} works nicely\nfor conditioning on the multiple covariates, too.\nThe Hilbert curve does depend on the ordering of the dimensions\nassociated with the covariates, yet the empirical results\nof Section~\\ref{results} above indicate that this ordering\nhas relatively little impact.\nThus, the graphical method and summary statistics of the present paper\nleave no parameters to tune or knobs to twist,\naside from setting the ordering of the covariates,\nand the ordering of the covariates appears to have fairly little impact\nin experiments, in any case.\nThe methodology of the present paper is fully non-parametric\nand fully automated.\n\n\n\n\\section*{Acknowledgements}\n\nWe would like to thank Mike Rabbat and Arthur Szlam for helpful discussions.\n\n\n\n\\newpage\n\n\n\n\\bibliography{multidim}\n\\bibliographystyle{vancouver}\n\n\n\n\\end{document}\n", "meta": {"hexsha": "836684f076f4ccceb293f7c9dca9b9e6eb38ca9f", "size": 81793, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/multidim.tex", "max_stars_repo_name": "facebookresearch/metamulti", "max_stars_repo_head_hexsha": "109b68628de58dbb7f110575b3aa6c7c9785b90b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-02T04:59:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T04:59:32.000Z", "max_issues_repo_path": "tex/multidim.tex", "max_issues_repo_name": "facebookresearch/metamulti", "max_issues_repo_head_hexsha": "109b68628de58dbb7f110575b3aa6c7c9785b90b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/multidim.tex", "max_forks_repo_name": "facebookresearch/metamulti", "max_forks_repo_head_hexsha": "109b68628de58dbb7f110575b3aa6c7c9785b90b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.1226747109, "max_line_length": 130, "alphanum_fraction": 0.7403200763, "num_tokens": 24249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.3145090531165991}}
{"text": "% $Id$\n\n\\subsection{Design and Implementation Notes}\n\\begin{enumerate}\n\n\\item {\\bf Base TimeIntervals and Times on the same integer representation.} \nIt is useful to allow both TimeIntervals and Times to \ninherit from a single class, BaseTime.  In C++, this can be\nimplemented by using inheritance.  In Fortran, it can be implemented\nby having the derived types TimeIntervals and Times\ncontain a derived type BaseTime.  In both cases, the \nBaseTime class can be made private and invisible to the user.\n\nThe result of this strategy is that Time Intervals and \nTimes gain a consistent core representation of time as well a set\nof basic methods.\n\nThe BaseTime class can be designed with a minimum number of elements\nto represent any required time.  The design is based on the idea used\nin the real-time POSIX 1003.1b-1993 standard.  That is, to represent\ntime simply as a pair of integers: one for seconds (whole) and one for\nnanoseconds (fractional).  These can then be converted at the interface\nlevel to any desired format.\n\nFor ESMF, this idea can be modified and extended, in order to handle the\nrequirements for a large time range (> 200,000 years) and to exactly\nrepresent any rational fraction, not just nanoseconds.  To handle the\nlarge time range, a 64-bit or greater integer is used for whole seconds.\nAny rational fractional second is expressed using two additional integers:\na numerator and a denominator.  Both the whole seconds and fractional\nnumerator are signed to handle negative time intervals and instants.\nFor arithmetic consistency both must carry the same sign (both positive\nor both negative), except, of course, for zero values.  The fractional\nseconds element (numerator) is bounded with respect to whole seconds. \nIf the absolute value of the\nnumerator becomes greater than or equal to the denominator, whole\nseconds are incremented or decremented accordingly and the numerator is\nreset to the remainder.  Conversions are performed upon demand by\ninterface methods within the TimeInterval and\nTime classes.  This is done because different applications require different\nrepresentations of time intervals and time instances.  Floating point values as well as integers can be specified for the various time units in the interfaces, see Table~\\ref{table:timeOpts}.  Floating point values are represented internally as integer-based rational fractions.\n\nThe BaseTime class defines increment and decrement methods for basic\nTimeInterval calculations between Time instants.  It is done here rather\nthan in the Calendar class because it can be done with simple \nsecond-based arithmetic that is calendar independent.  \n\nComparison methods can also be defined in the BaseTime class.  These\nperform equality/inequality, less than, and greater than comparisons\nbetween any two TimeIntervals or Times.  These methods capture\nthe common comparison logic between TimeIntervals and Times and\nhence are defined here for sharing.\n\n\\item {\\bf The Time class depends on a calendar.} The Time class contains \nan internal Calendar class.  \nUpon demand by a user, the results of an increment or decrement operation are \nconverted to user units, which may be calendar-dependent, via methods \nobtained from their internal Calendar.\n\n\\end{enumerate}\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "12a675c18fbd5d0174bc46087464e64a387c65e3", "size": 3261, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ESMF/src/Infrastructure/TimeMgr/doc/TimeMgr_implnotes.tex", "max_stars_repo_name": "joeylamcy/gchp", "max_stars_repo_head_hexsha": "0e1676300fc91000ecb43539cabf1f342d718fb3", "max_stars_repo_licenses": ["NCSA", "Apache-2.0", "MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-07-05T16:48:58.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-05T16:48:58.000Z", "max_issues_repo_path": "ESMF/src/Infrastructure/TimeMgr/doc/TimeMgr_implnotes.tex", "max_issues_repo_name": "joeylamcy/gchp", "max_issues_repo_head_hexsha": "0e1676300fc91000ecb43539cabf1f342d718fb3", "max_issues_repo_licenses": ["NCSA", "Apache-2.0", "MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-04T16:12:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T16:12:02.000Z", "max_forks_repo_path": "ESMF/src/Infrastructure/TimeMgr/doc/TimeMgr_implnotes.tex", "max_forks_repo_name": "joeylamcy/gchp", "max_forks_repo_head_hexsha": "0e1676300fc91000ecb43539cabf1f342d718fb3", "max_forks_repo_licenses": ["NCSA", "Apache-2.0", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.6712328767, "max_line_length": 278, "alphanum_fraction": 0.8031278749, "num_tokens": 689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3142309233341246}}
{"text": "% !TeX spellcheck = en_GB\n\\section{Operational Weather Forecast Model}\\label{sec:DIM:MEPS}\nMetCoOp Ensemble Prediction System (MEPS) became operational at Met-Norway in November 2016 when the extreme Christmas storm occurred over Norway. Comparing model data with actual observations helps to validate %verify the agreement between \nmodel predictions. % and ground-based measurements. \n\\\\\nMEPS is used as weather forecast at the Norwegian Meteorological Institute, the Swedish Meteorological and Hydrological Institute (SMHI) and the Finnish Meteorological Institute (FMI), \\citep{muller_arome-metcoop:_2017, koltzow_metcoop_2017}.\nIt replaced Mèteo-France Applications of Research to Operations at MEsoscale (AROME)-MetCoOp, which was operational from March 2014 until November 2016. %, when it was replaced with an ensemble prediction system (EPS) based on AROME-MetCoOp.\n%\\textcolor{red}{Say more about the model itself! == AROME, Both models are based on...}\nBoth models are a branch of the Hirlam Aladin Regional Meso-scale Operational NWP In Europe (HARMONIE) AROME model, version 40h1.1. MEPS and AROME-MetCoOp therefore built on the bases of AROME-France a convective-scale model. The physical parametrisations are from the French mesoscale non-hydrostatic atmosphere model (Meso-NH). The model got operational in 2008 and has a horizontal resolution of \\SI{2.5}{\\km} \\citep{seity_arome-france_2010}. \n\n%Ensemble prediction has the goal to improve the forecast by ensemble averaging, to provide an indication of the reliability of the forecast, and a quantitative basis for probabilistic forecasting \\citep{kalnay_atmospheric_2003}. \n\\subsection{Ensemble Prediction System}\nThe main difference between AROME-MetCoOP and MEPS is that AROME-MetCoOp only contains a deterministic prediction whereby MEPS has additionally nine individual perturbed ensemble member \\citep{metcoop_wiki_description_2017}. \n\\\\\n\\Cref{fig:MEPS:kalnay_ens} shows the schematic of an ensemble prediction system (EPS). An ensemble forecasting system requires the definition of the initial amplitude and the horizontal and vertical structure of the perturbation. In general, the initial perturbation is chosen to be close to the observations. The initial condition for the disturbance is within a circle (\\Cref{fig:MEPS:kalnay_ens}) of the observation uncertainty. In an ensemble prediction system one of the members is the deterministic forecast (single control forecast) where the other forecast members start from a slight perturbed state of the deterministic forecast. For a short time, should the forecast members be close together, this is a few hours in mesoscale prediction (deterministic in \\Cref{fig:MEPS:kalnay_ens}). After a certain period of time, the forecast of the different perturbed members are so large that they have to be considered as stochastic (\\Cref{fig:MEPS:kalnay_ens}). \n\\\\\nImportant is, that the observations, which are going to be used for the initialisation are within the spread of the individual ensemble member forecasts \\citep{kalnay_atmospheric_2003}.\n%%% image Kalnay Fig 6.4.1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{figure}[t!]\n\t\\centering\n\t\\includegraphics[width=0.49\\textwidth]{./fig_MEPS/ensemble}\n\t\\caption{Schematic of ensemble prediction. Circle, representing the uncertainty of the initial conditions. Individual lines, perturbed ensemble member from the initial conditions ending in solution space, grey area \\citep{kalnay_atmospheric_2003}.}\\label{fig:MEPS:kalnay_ens}\n\\end{figure}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\\noindent\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%% MEPS %%%%%%%%%%%%%%\n\\subsection{MetCoOP Ensemble Prediction System}\\label{sec:AROME}\nIn principle, MEPS is a short-term weather forecast consisting of ten ensemble members %forecast system \nwith \\SI{66}{\\hour} prediction time and a horizontal resolution of \\SI{2.5}{\\km} and 65 vertical levels. Hourly \\SI{66}{\\hour} forecast data is available at Met-Norway for the deterministic and the first perturbed ensemble member. \\SI{54}{\\hour} forecasts are stored for the three hourly values.\n\\\\\nThe lower layer, near the ground is approximately \\SI{12}{\\km} height. With increasing height decreases the vertical resolution of \\SIrange{25}{200}{\\metre} in the lower \\SI{3}{\\km}. The model top is at located at approximately \\SI{23}{\\km}.\nThe initialisation of each member is performed at \\SIlist{00;06;12;18}{\\UTC} \\citep{metcoop_wiki_description_2017}.\nForecast data saved for the deterministic and first ensemble member have a time resolution of one hour for the \\SI{66}{\\hour} forecast period. The other eight members have data stored every three hours for up to \\SI{48}{\\hour} forecast time.\n% %\\\\\n%%% image MEPS resolution %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\input{./images_tex/meps_Haukeli_map}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\noindent\n\\Cref{fig:meps:Norway} shows \nthe MEPS model domain and its elevation as it was operational for December 2016. It covers Scandinavian countries including open water such as the Atlantic Ocean, the North and the Baltic Seas. \nA representation of the horizontal resolution zoomed for the Haukeliseter site is shown in \\Cref{fig:meps:site}. \n%Haukeliseter is surrounded by a complex terrain with mountains up to \\SI{1500}{\\metre} no the west and the north and the more open terrain to the south-east.\nThe topographical resolution of MEPS and its influence on local wind and precipitation will be discussed in \\Cref{sec:res:oro_infl}.\nTo compare the measurements from the surface with the MEPS data, the closest model grid point to Haukeliseter, is used (\\Cref{fig:meps_site}). The closest grid point to Haukeliseter is \\ang{59.80}\\,N, \\ang{7.22}\\,E at \\SI{1041}{\\metre} above sea level.\n\\\\\nThe centre of the model is approximately at \\ang{63.5}\\,N, \\ang{15}\\,E. \nThe horizontal grid points are %projected on a \nLambert projected to receive the same area size of each grid cell. \n%The outer, parent grid is the ECMWF-IFS model (European Centre for Medium-Range Weather Forecasts Integrated Forecasting System) with a horizontal resolution of \\SI{9}{\\km} \\citep{homleid_verification_2016}. The ECMWF-IFS forecasts are used \\SI{6}{\\hour} prior to the actual cycle in MEPS.\nThe regional model MEPS receives initial and boundary conditions from the global ECMWF-IFS (European Centre for Medium-Range Weather Forecasts Integrated Forecasting System) before it can produce its own regional forecasts. In addition, to produce the forecast analysis the background model is initiated for upper-air and surface data assimilation \\citep{muller_arome-metcoop:_2017}. \nThe horizontal resolution of the parent ECMWF grid is \\SI{9}{\\km}, has \\num{137} model levels, and the model level top is at \\SI{80}{\\km}. The ECMWF-IFS forecasts are available \\SI{5}{\\hour} later than the model runs at Met-Norway. MEPS is updated each third hour using obsrvations received in real-time from the global observing system \\citep{homleid_verification_2016}.\n%used \\SI{3}{\\hour} prior to the actual cycle in MEPS with.\nSince initial conditions such as observations have uncertainties as well as the model has internal variability, it has to reach a background climatology state (spin-up) before the output can be analysed. %has mistrust, and  the own climatology needs to be approached, a model has to stabilize before the simulations can be trusted. \n%The initial conditions such as observations and the model itself have uncertainties. \n\\citet{warner_tutorial_1997} states, spin-up time varies depending on the amount and quality of the initial and boundary conditions. If only a few mesoscale initial condition are available then the model should be initialised well before the forecast time. This will allow the model to spin-up mesoscale structures that are responsive to large-scale and local forcing. \nIn MEPS, the spin-up time %varies depending on the quality of the initial and boundary conditions, \ncan be assumed to be \\SI{6}{\\hour} for precipitation \\citep[personal communication,][]{Priv_Comm_Koltzow}. \n\\\\\nTo model the snow in AROME-MetCoOp an one-layer atmosphere model scheme is implemented. The representation is covered by an adjustment of the three-class ice parametrization (ICE3) scheme (\\Cref{sec:AROME:adjustment}). \nThis includes three variables such as: snow water equivalent (SWE), snow density, and snow albedo \\citep{muller_arome-metcoop:_2017}.\nHow liquid-phase processes are separated from slow ice-phase processes are described in \\Cref{sec:MesoNH}. \n% \\\\\n% As synoptic observations are included in the model the snow-depth predictions underlay a special performance. Observations of snow-depth are only available at \\SIlist{06;18}{\\UTC}, therefore the snow analysis is only performed twice daily \\citep{muller_arome-metcoop:_2017, homleid_verification_2016}. \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%% MESONH %%%%%%%%%%%%%%\n\\subsection{Meso-NH and the ICE3 Scheme} \\label{sec:MesoNH}\nThe physical parametrisation within AROME is based on the French research communities' Meso-NH. The microphysical scheme in the Meso-NH atmospheric simulation system is based on the Kessler scheme for liquid processes whereas the ICE3 parametrisation scheme is for cold processes \\citep{meteo_france_meso-nh_2009}. The purpose of the scheme is to model as correctly as possible the ice phase in the atmosphere. The three-class parametrisation scheme is coupled to a Kessler scheme for the warm processes \\citep{pinty_mixed-phased_1998}. \\cite{mccumber_comparison_1991} concluded from their case study of simulating two different types of tropical convection, that at least three different ice categories are necessary to cover most precipitation but that applications might be case specific. \n%\\\\%\n\\par\\medskip\\noindent\nAccording to the \\cite{meteo_france_meso-nh_2009} documentation, the ice phase microphysical scheme includes: \n\\begin{itemize}\n\t\\item [$\\mathbf{i}$:] pristine ice phase  \n\t\\item [$\\mathbf{s}$:] snowflake type from lightly rimed large ice crystals or dry clusters, and\n\t\\item [$\\mathbf{g}$:] heavily rimed crystals, such as graupel, frozen drops or hail.\n\\end{itemize}\nWithin the ICE3 scheme no distinction between hail and graupel exists and therefore the physical discrimination is in the growth mode of graupel and hail is neglected. \\\\\nTo achieve snow water content within MEPS the number intercept parameter ($N_0$, [\\SI{}{\\metre^{-3}\\per\\mm}]), slope parameter of exponential size distribution ($\\lambda$, [\\SI{}{\\per\\metre}]), mass diameter ($D$, [\\SI{}{\\mm}]) and  the particle size distribution [\\SI{}{\\metre^{-3}\\per\\mm}] of pristine ice ($n_\\mathbf{i}$), snowflakes ($n_\\mathbf{s}$), and rimed crystals ($n_\\mathbf{g}$)  has to be determined. \nAccording to \\cite{caniaux_numerical_1994}, the particle size distribution in the ICE3 scheme follows the Marshall-Palmer distribution (\\Cref{eq:num_dens}). The goal in ICE3 is to use a varying intercept parameter dependent on the ice category. The study of \\citet{caniaux_numerical_1994} has shown that $N_0$ can be parametrised with:\n\\begin{align}\n\tN_0 & = C \\lambda^x  \\label{eq:model_N0}\n\t\\\\\n\t\\log_{10}C & = -3.55x + 3.89  \\nonumber\n\\end{align}\nwhere $C$ and $x$ are constants depending on the ice category %and represent the relation between each other in \n(\\Cref{eq:model_N0}). \n\\\\\nThe ice water content for primary ice, snowflakes, and rimed crystals is then assumed to be similar to \\Cref{eq:SWC}, but the integration limits range from zero to infinity and mass (($m$, [\\SI{}{\\kg}])), and particle size distribution ($n(D)$) are dependent on the diameter of the hydrometeor particle. The mass of a single particle and PSD (\\Cref{eq:mass_diameter,eq:PSD_MEPS}) are represented depending on the ice category (\\Cref{tab:ice_parameter})\n\\begin{align}\n\tm(D) & = aD^b \t\\label{eq:mass_diameter} \\\\\n\tn(D) & = N_0 g(D)\t\\label{eq:PSD_MEPS}\n\\end{align}\n$a$, $b$ are the characterisations of the parameters according to their type (\\Cref{tab:ice_parameter}) and $g(D)$ the generalised Gamma function: \n\\begin{align}\n\tg(D) = \\frac{\\alpha}{\\Gamma(\\nu)} \\lambda^{\\alpha \\nu} D^{\\alpha \\nu -1} \\exp\\left( -(\\lambda D)^\\alpha \\right)\n\\end{align}\nwith $\\alpha$, $\\nu$ the shape and tail dispersion parameters and $\\Gamma(\\nu)$ the gamma function. \n%%% table ice parameters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\input{./tables_tex/ice_category_scheme}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\\\\nAfter following the above equations including \\Cref{eq:SWC} the exponential slope parameter of pristine ice, snow, and rimed crystals, $\\lambda$ can be generated with $G(b)$, the gamma function:\n\\begin{align}\n\t\\lambda & = \\left( \\frac{\\text{SWC}}{aCG(b)}\\right)^{\\frac{1}{x-b}}\n\\end{align}\n\\\\\nFor all hydrometeors the terminal fall velocity based on the diameter, $D$ is assumed.\n\\begin{align}\n\tV(D) = c D^d \\left(\\frac{\\rho_{00}}{\\rho_{dref}}\\right)^0.4 . \\label{eq:fall_velo_MEPS}\n\\end{align}\nIn \\Cref{eq:fall_velo_MEPS} the last factor is the \\citet{foote_terminal_1969} correction of the air density and $\\rho_{00}$ being the air density at the reference pressure level $P_{00}$.\n%\n%\n\\\\\n\\Cref{fig:ICE3_scheme} shows the summary of the microphysical processes for mixed phase clouds. The study focuses mostly on solid precipitation particles and therefore only the initiation and growth of pristine ice crystals $\\mathbf{i}$, snowflakes $\\mathbf{s}$, and rimed crystals $\\mathbf{g}$ is presented. \n%%% image ICE3 scheme  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\input{./images_tex/meps_ice3_scheme}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\noindent\n\\\\\nFollowing \\cite{pinty_mixed-phased_1998} and \\Cref{fig:ICE3_scheme} it can be seen how AROME calculates ice growth. %\n\\begin{itemize}\n\t\\item The ICE3 scheme starts with \\textit{cold} - 'slow' processes for ice processes (right side in \\Cref{fig:ICE3_scheme}) \n\t\\begin{itemize}\n\t\t\\item homogeneous (HON) and heteorogeneous (HEN) nucleation\n\t\t\\item vapour deposition of snow and graupel particles (DEP)\n\t\t\\item aggregation (AGG) and auto conversion (AUT)\n\t\\end{itemize}\n\t\\item The second step is to initiate the \\textit{warm} processes (left side in \\Cref{fig:ICE3_scheme})\n\t\\item Then including the \n\t\\begin{itemize}\n\t\t\\item aggregation and conversion-melting (CVM) for snowflakes and \n\t\t\\item contact freezing of raindrops (CFR)\n\t\\end{itemize}\n\t\\item Followed by AGG and melting for graupel (MLT)\n\t\\item And the melting from pristine ice and the Wegener-Bergeron-Findeisen (BER) effect\n\t\\item finally integrate the sedimentation terms\n\\end{itemize}\n\n%\\cite{meteo_france_meso-nh_2009} documentation suggests starting the microphysics in the ICE3 scheme with 'slow' processes such as homogeneous and heterogeneous nucleation (HON, HEN), vapour deposition of snow and graupel particles (DEP), aggregation (AGG) and auto conversion (AUT), for ice processes right side in \\Cref{fig:ICE3_scheme}. The second step is to initiate the warm processes left side in \\Cref{fig:ICE3_scheme}. Then include the aggregation and conversion-melting (CVM) for snowflakes and contact freezing of raindrops (CFR). Add AGG and melting for graupel (MLT), and then the melting from pristine ice  and the Wegener-Bergeron-Findeisen (BER) effect and lastly the sedimentation terms.  \\\\\n\n% are the primary ice crystals activated by either heterogeneous nucleation (HEN), when some ice nuclei are present or by homogeneous nucleation (HON), when the atmospheric temperature is below \\SI{-35}{\\celsius}. The growing process for these particles can be the Bergeron-Findeisen process (BER) or deposition of water vapour (DEP). \\\\\n% Snow particles are initiated by auto conversion (AUT) of r$_i$ and grow by the riming of cloud droplets (RIM) or rain droplets (ACC), and by collection of small pristine crystals (AGG), indicated by the green lines in \\Cref{fig:ICE3_scheme}. \\\\\n% As indicated by the blue lines in \\Cref{fig:ICE3_scheme} are graupel an effect of heavy riming and grow in the scheme if the riming aggregates are of larger diameter size than \\SI{7}{\\mm} \\citep{meteo_france_meso-nh_2009}. As indicated can graupel also grow when larger colliding raindrops reshape snowflakes to graupel (ACC). Furthermore, is graupel growth affected by wet or dry (WET, DRY) accretion, when the surface temperature of graupel is larger than the environmental temperature. DRY graupel expansion happens as long as the surface temperature is less that the surrounding temperature, then collected drops will freeze. WET graupel growth appears, when a liquid film is on the surface of the graupel particle (surface temperature larger than surrounding) then the liquid condensate is shed away, and hail will be formed. In ICE3 is hail not specifically included it is mixed in to the graupel category and therefore a distinction between the two categories cannot be made. \n\n%\n%\\newpage\n\\subsection{AROME-MetCoOp Adjustment}\\label{sec:AROME:adjustment}\n% refinement for AROME \nSince the ICE3 scheme showed some weaknesses in AROME-MetCoOp for the boreal winter month, \\cite{muller_arome-metcoop:_2017} introduced some modifications. \nDuring cold conditions (\\SI{2}{\\metre} temperature between \\SIlist{-5;-10}{\\celsius}) the ICE3-scheme followed too low \\SI{2}{\\metre} temperature in AROME-MetCoOp. Furthermore, too much ice fog or low clouds were simulated for \\SI{2}{\\metre} temperature $\\le$ \\SI{-15}{\\celsius}, all year long. After implementing the modifications such as separating fast liquid-phase processes from the slower ice-processes, as well as reducing sublimation speed of ice particles. Also, taking into account the difference of optical thickness between ice-phase clouds and water, mixed-clouds reduced the negative \\SI{2}{\\metre} temperature bias \\citep{muller_arome-metcoop:_2017}. %the two meter temperature bias was reduced as well as an improvement of low-level clouds was shown. \nA negative aspect of these adjustments was that the occurrence of fog increased.%, by an error in the surface scheme.\n\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %%%%%%%%% SURFEX %%%%%%%%%%%%%%\n% \\section{SURFEX}\n% \\cite{masson_surfexv7.2_2013} \\\\\n% SURFEX stands for 'surface externalisée' and is introduced into NWP models to ensure the consistent treatment of surface processes. It simulates the exchange of energy between four surface types and the atmosphere \\citep{homleid_verification_2016}.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "f1052deb753a70e3946b6992a10fede09e7136ac", "size": 18958, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis_full/Data_Instrument_Methods/MEPS.tex", "max_stars_repo_name": "franzihe/Latex_thesis", "max_stars_repo_head_hexsha": "128284a01155bdc28b3e9374e538a07a1e5722c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thesis_full/Data_Instrument_Methods/MEPS.tex", "max_issues_repo_name": "franzihe/Latex_thesis", "max_issues_repo_head_hexsha": "128284a01155bdc28b3e9374e538a07a1e5722c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis_full/Data_Instrument_Methods/MEPS.tex", "max_forks_repo_name": "franzihe/Latex_thesis", "max_forks_repo_head_hexsha": "128284a01155bdc28b3e9374e538a07a1e5722c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 105.9106145251, "max_line_length": 985, "alphanum_fraction": 0.7372085663, "num_tokens": 4698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.31423091646803714}}
{"text": "%!TEX root = ../thesis.tex\n%*******************************************************************************\n%*********************************** First Chapter *****************************\n%*******************************************************************************\n\n\\chapter{Viscous acoustic flow}  %Title of the First Chapter\n\n\\ifpdf\n    \\graphicspath{{Chapter1/Figs/Raster/}{Chapter1/Figs/PDF/}{Chapter1/Figs/}}\n\\else\n    \\graphicspath{{Chapter1/Figs/Vector/}{Chapter1/Figs/}}\n\\fi\n\nIn this chapter we start with the review of the fully compressible Navier--Stokes equations and aim to derive two limit cases: incompressible flow and acoustic flow equations from the power expansion of the initial problem by assuming that the flow is governed by some low characteristic numbers. We will see that in the case of low Mach number of the base and fluctuating flows the initial problem can be split into two sub-problems. Then, we discuss both the strong and the weak forms for each of two cases; finally, we consider possible boundary conditions and their implementation.\n\n\\section{Equations of motion}\n\nThe full compressible Navier--Stokes equations govern the motion of a fluid with the presence of viscous effects, heat conductivity, compressibility, external body forces and many others. In general, the equations in conservative form are given by \\cite{LandauHydro}:\n\n\\begin{equation}\n\\label{eq:cNSPrimForm}\n    \\frac{\\partial}{\\partial t} \\textbf{q} + \\frac{\\partial}{\\partial x_k} \\left( \\textbf{f}^c_k(\\textbf{q}) -  \\textbf{f}^v_k(\\textbf{q}, \\nabla \\cdot \\textbf{q}) \\right) = 0 \\ \\  \\ in  \\ \\Omega\n\\end{equation}\n\nHere we use $^c$ and $^v$ referring to convective and viscous parts of the equations. The vector of conservative variables $\\textbf{q}$ and the fluxex $f^c(\\textbf{q}), f^v(\\textbf{q})$ are defined by\n\n\\begin{align}\n\\label{eq:cNSFluxes}\n    \\textbf{q} &= \\begin{bmatrix}\n           \\rho \\\\\n           \\rho u_1 \\\\\n           \\rho u_2 \\\\\n           \\rho E\n         \\end{bmatrix},&\n    f_k^c(\\textbf{q}) &= \\begin{bmatrix}\n           \\rho u_1 \\\\\n           \\rho u_1 u_k + P \\delta_{1k} \\\\\n           \\rho u_2 u_k + P \\delta_{2k}\\\\\n           \\rho u_k H\n         \\end{bmatrix},&\n    f_k^v(\\textbf{q}) &= \\begin{bmatrix}\n           0 \\\\\n           \\tau_{k1} \\\\\n           \\tau_{k2} \\\\\n           \\tau_{kj}u_j + \\partial_{k} \\kappa T\n         \\end{bmatrix}\n  \\end{align}\n\nThe viscous stress tensor $\\tau_{ij}$ is proportional to the dynamic viscosity coefficient $\\mu$ and equals to\n\n\\begin{equation}\n    \\tau_{ij} = \\mu \\left( \\nabla_i u_j + \\nabla_j u_i - \\frac{2}{3} div(\\textbf{u}) \\  \\delta_{ij} \\right)\n\\end{equation}\n\nIntroduced variables $\\rho, \\textbf{u}, P, E$ and $H$ denote the density, velocity vector, pressure, total energy and enthalpy of the flow:\n\n\\begin{subequations}\n    \\begin{align}\n        & P(\\textbf{q}) = (\\gamma - 1) \\rho e, \\\\\n        &\\rho E = \\rho e + \\frac{\\rho \\textbf{u}^2}{2}, \\\\\n        &H(\\textbf{q}) = \\frac{\\rho E + P}{\\rho}\n    \\end{align}\n\\end{subequations}\n\nStatic internal energy $e$ is related to the temperature $T$ of the flow by $e = c_v T$, where $c_v$ denotes the constant volume heat capacity. We can define the Prandtl number $Pr = \\frac{\\mu \\gamma c_v}{\\kappa}$, $\\kappa$ is the thermal conductivity coefficient. For example, in the case of an ideal gas, a Prandtl number $Pr = 0.72$. We also need to introduce an equation of state, which relates the pressure, density and temperature, i.e. $\\rho = \\rho(P,T)$.\n\nUsually, solving these equations is a challenge itself, including choosing an appropriate discretization and numerical methods, which is another noticeable research area. For example, discontinuous Galerkin finite element method \\cite{hartmann2008} is a promising candidate to solve the full problem.\n\n\\section{Equations of motion in the low Mach number limit}\n\nNow, let us introduce two parameters to describe the flow. Here we follow the results presented in \\cite{Muller99lowmach} for the low Mach number asymptotics of the Navier--Stokes equations, and \\cite{culick2006unsteady} for two-parameter expansion derivation. \n\nFirst, consider that we have a steady fluid flow in a channel with rigid boundaries, and the mean inlet velocity is in order of $1-10$ m/s. Then the Mach number of the base mean flow can be characterized by a small parameter, $\\mu = M^b$, since the velocity of the flow is much smaller than the speed of sound $c_s^b = \\sqrt{\\gamma P^{b}/\\rho^{b}}$, such that the local Mach number is:\n\n\\begin{equation}\nM = \\frac{u}{\\sqrt{\\gamma P^{b}/\\rho^{b}}} = \\frac{u}{u^{b}} M^{b} \\rightarrow 0 \\ \\ if \\ \\ M^{b} \\rightarrow 0\n\\end{equation}\n\n\\noindent where $^b$ corresponds to the reference base dimensional values describing the flow. We choose the reference quantities such that the $u/u^{b}$ is in order of $\\mathcal{O}(1)$.\n\nSecond, the flow is perturbed by a small boundary oscillations created by a piezo-element. These fluctuations are created at the boundary and propagate inside the channel. The inkjet printing device is designed to create a sequence of small droplets jetting through a tiny orifice, and these oscillations are the primal mechanism of droplets formation at the nozzle outlet boundary [REF]. Although the boundary displacement is negligibly small [REF], acoustic waves form inside the channel and represent an additional physical phenomenon to be studied. This type of fluctuating motion should be small in comparison to the mean quantities, and moreover be described by another parameter. Introducing a new small characteristic number, $\\varepsilon$, we will use it to define the Mach number of the fluctuating flow.\n\nThese two small parameters, $\\mu$ and $\\varepsilon$, represent different physical phenomena. Consequently, the formal expansion of the governing equations will give us terms with different orders in $\\mu, \\varepsilon$: $\\mathcal{O}(\\mu^{k_1}\\varepsilon^{k_2})$, where $k_1, k_2$ are some integer numbers (e.g., $k_2 = 0$ for a flow with no oscillations). This generally characterize the flow processes. For example, as will be shown later, setting $\\varepsilon$ to zero and collecting terms of $\\mathcal{O}(\\mu)$ leads to the well-known momentum equation of an incompressible flow.\n\n\\subsection{Nondimensionalization}\n\nTo perform the following analysis of the low Mach number limit of the equations of motion, it is necessary to define the nondimensional variables. New equations will include dimensionless quantities such as the Reynolds number (if the flow is viscous), the Froude number (if gravity is included into the model), or, for instance, those related to the considered forces acting on the flow.\n\nDimensional reference quantities can be based on the far-field conditions, but in the case of the internal flow it seems more natural to refer to the steady flow state without mean flow: $\\rho^b, T^b, c_s^b, \\mu^b$ (reference density, temperature, speed of sound and viscosity) and a domain size $L$ as a reference length scale. The reference pressure $P^b$ used here is chosen as a function of density and speed of sound: $P^b = \\rho^b (c_s^b)^2$. Hence a new set of variables becomes:\n\n\\begin{subequations}\n\\label{eq:NSderDimens}\n\\begin{align}\n    \\frac{\\rho}{\\rho^b} \\rightarrow \\rho, \\ \\ \\frac{P}{P^b} \\rightarrow P, \\ \\ \\frac{T}{T^b} \\rightarrow T, \\ \\ \\frac{u}{c_s^b} \\rightarrow u\\\\\n    \\frac{E}{P^b/\\rho^b} \\rightarrow E, \\ \\ \\frac{H}{P^b/\\rho^b} \\rightarrow H, \\\\\n    \\frac{x}{L} \\rightarrow x, \\ \\ \\frac{t}{L/ c_s^b} \\rightarrow t\n\\end{align}\n\\end{subequations}\n\nThe dimensionless parameters such as the Reynolds number appear in the equations at this stage, with $Re = \\rho^b c_s^b L / \\mu^b$. These values depend on the choice of the reference values.\n\nWhile some approaches \\cite{culick2006unsteady} are based on the speed of sound dimensionalization, also in some cases choosing a known velocity of the flow (for example, at the inlet) as a reference quantity helps obtaining slightly different and more demonstrative results, such as temporal multiple scales analysis \\cite{Muller99lowmach}. However, this approach is not suitable if the inlet velocity is zero, whilst the speed of sound is never a small quantity. We will use speed of sound as a reference velocity for the compressible flow, and the non-zero inlet velocity in the incompressible case. \n\n\\subsection{Flow values expansion}\n\nAs discussed before, physical processes in the flow arise from two different sources: the mean flow characterized by the parameter $\\mu$ and the fluctuating flow related to the second parameter $\\varepsilon$. We can then write the flow state \\textbf{q} as a sum of mean values $\\bar{\\mathbf{q}}$ and fluctuating values $\\tilde{\\mathbf{q}}$:\n\n\\begin{equation}\n\\label{eq:NSderMeanFluctExpansion}\n\\rho = \\bar{\\rho} + \\tilde{\\rho}, \\ \\ u = \\bar{u} + \\tilde{u}, \\dots\n\\end{equation}\n\nRefering back to the original idea of two parameters analysis, fluctuating values should be of the order in amplitude $\\varepsilon$, while some mean values are in order of 1, not $\\mu$. For instance, consider the no-mean flow configuration when $\\mu = 0$, so the dimensional flow density becomes $\\rho = \\rho^b = \\mathcal{O}(1)$.\n\nWe substitute (\\ref{eq:NSderMeanFluctExpansion}) into the full system of compressible Navier--Stokes equations (\\ref{eq:cNSPrimForm}) and gather terms which have the same order of magnitude (see Appendix A). In particular, holding only the leading terms in $\\mu, \\epsilon$, the split mass and momentum conservation equations become:\n\n\\begin{equation}\n\\label{eq:NSderMassSplit}\n\\left[ \\partial_t  \\bar{\\rho} + \\nabla_i (\\bar{\\rho} \\bar{u}_i) \\right] + \\left[ \\partial_t  \\tilde{\\rho} + \\nabla_i (\\bar{\\rho} \\tilde{u}_i) \\right] + \\mathcal{O}(\\varepsilon^2, \\varepsilon \\mu, \\dots) = 0\n\\end{equation}\n%+ \\left[ \\nabla_i \\left(\\tilde{\\rho} (\\bar{u}_i + \\tilde{u}_i) \\right) \\right]\n\\begin{equation}\n\\label{eq:NSderMomenSplit}\n\\left[ \\partial_t  (\\bar{\\rho} \\bar{u}_i) + \\nabla_j (\\bar{\\rho} \\bar{u}_i\\bar{u}_j) + \\nabla_i \\bar{P} - \\frac{1}{Re} \\nabla_j \\bar{\\tau}_{ij} \\right] + \\left[ \\partial_t (\\bar{\\rho} \\tilde{u}_i) + \\nabla_i \\tilde{P} - \\frac{1}{Re} \\nabla_j \\tilde{\\tau}_{ij} \\right] +  \\mathcal{O}(\\varepsilon^2, \\varepsilon \\mu, \\dots) = 0\n\\end{equation}\n\nThe first bracket in both (\\ref{eq:NSderMassSplit}) and (\\ref{eq:NSderMomenSplit}) contains only terms related to the mean state $\\bar{\\mathbf{q}}$, and the second bracket gathers the fluctuating quantities $\\tilde{\\mathbf{q}}$. The rest of the equations represents the combination of the mean and fluctuating flow with terms containing both Mach numbers, thus describes the interactions between these two physical processes.\n\nDirect consideration of the first bracket in (\\ref{eq:NSderMomenSplit}) shows that all terms are proportional to some power of $\\mu$: mean density $\\bar{\\rho}$ has the leading term of $\\mathcal{O}(1)$ as shown before, the temporal derivative and the Reynolds number are proportional to $\\mu$ since the speed of sound was chosen to nondimensionalize them (it can be clearly seen from (\\ref{eq:NSderDimens}) that by choosing $u^b$ instead of $c_s^b$ as a reference velocity quantity results in the $u^b/c_s^b = \\mathcal{O}(\\mu)$ term appearing). Consequently, all terms in the first bracket of (\\ref{eq:NSderMomenSplit}) are $\\mathcal{O}(\\mu^2)$ except the pressure gradient, which should be in order of $\\mathcal{O}(1)$. To understand this seeming discrepancy, let us follow \\cite{Muller99lowmach} and expand pressure in power series of $\\mu$:\n\n\\begin{equation}\n\\bar{P} = \\bar{P}_0 + \\mu \\bar{P}_1 + \\mu^2 \\bar{P}_2 + \\mathcal{O}(\\mu^3)\n\\end{equation}\n\nNow, applying this expansion to the first bracket of (\\ref{eq:NSderMomenSplit}) and gathering terms with the same power of the small parameter gives:\n\n\\begin{subequations}\n\\begin{flalign}\n    &\\mu^0: \\ \\ \\nabla_i \\bar{P}_0 = 0, \\\\&\n    \\mu^1: \\ \\ \\nabla_i \\bar{P}_1 = 0, \\\\&\n    \\mu^2: \\ \\ \\partial_t  (\\bar{\\rho} \\bar{u}_i) + \\nabla_j (\\bar{\\rho} \\bar{u}_i\\bar{u}_j) + \\nabla_i \\bar{P_2} - \\frac{1}{Re} \\nabla_j \\bar{\\tau}_{ij} = 0\n\\end{flalign}\n\\end{subequations}\n\nPerforming similar analysis for the energy equation and considering the mean flow quantities behavior, it becomes clear that the zeroth and first order pressure terms are related to the total energy density and act like a thermodynamic pressure. The second order term $\\bar{P}^2$ however plays a similar role as the pressure in the incompressible Navier--Stokes equation.\n\nTo finally derive the incompressible Navier--Stokes equation, assume that the variation of density and temperature of the flow is small in comparison to the no-flow state, $||\\delta \\bar{\\rho}|| = ||\\bar{\\rho} - \\rho^b|| \\ll || \\rho^b ||$, or, in other words, $\\delta \\bar{\\rho} = \\mathcal{O}(\\mu)$. This leads us to the Boussinesq buoyancy equations \\cite{Rehm}, which to the lowest order in $\\mu$ results in:\n\n\\begin{subequations}\n\\begin{align}\n        div(\\bar{u}) = 0, \\\\\n        \\bar{\\rho} \\partial_t  (\\bar{u}_i) + \\bar{\\rho} (\\bar{u}_j \\nabla_j)\\bar{u}_i + \\nabla_i \\bar{P}_2 - \\frac{1}{Re} \\nabla_j \\bar{\\tau}_{ij} = 0\n\\end{align}\n\\end{subequations}\n\nThe second brackets in (\\ref{eq:NSderMassSplit}) and (\\ref{eq:NSderMomenSplit}) are the acoustic motion of the flow; terms are proportional to $\\varepsilon$ and do not contain information about the mean flow. Since the first bracket terms were shown to be zero, we can conclude that the second bracket terms should also be zero, leading us to the equations of linear acoustics:\n\n\\begin{subequations}\n\\label{eq:acousticT}\n\\begin{align}\n        \\partial_t  \\tilde{\\rho} + \\bar{\\rho}  \\nabla_i (\\tilde{u}_i) = 0, \\\\\n        \\bar{\\rho} \\partial_t (\\tilde{u}_i) + \\nabla_i \\tilde{P} - \\frac{1}{Re} \\nabla_j \\tilde{\\tau}_{ij} = 0\n\\end{align}\n\\end{subequations}\n\nNecessary to note, that the problem can be separated in two smaller problems: incompressible mean flow and linear acoustics, only due to the fact that we assumed terms of $\\mathcal{O}(\\varepsilon^2, \\varepsilon \\mu, \\dots)$ to be small and therefore we neglect the interaction between the mean flow and the fluctuating flow. Otherwise, mean state $\\bar{\\mathbf{q}}$ and fluctuating state $\\tilde{\\mathbf{q}}$ are coupled through the higher order terms which represent mass, momentum and energy transfer between them.\n\n\n\\clearpage\n\\section{Mean flow in the low Mach number limit}\n\nLow Mach number expansion of the Navier--Stokes equations results in the mass and momentum conservation laws of incompressible base flow and classical linear acoustic problem. In this section we consider both steady and unsteady incompressible flow and briefly discuss the governing equations and weak formulation.\n\n\\subsection{Problem statement}\n\nIncompressible Navier--Stokes equation can be considered as an equation of motion plus a constraint, that makes the flow divergenceless. The pressure variable is not directly related to the thermodynamic state, and adjusts in a way that the velocity constraint is satisfied. The governing equations are:\n\n\\begin{subequations}\n\\label{eq:IncNSeqFull}\n    \\begin{align}\n    \\label{eq:IncNSeq}\n    \\frac{\\partial u_i}{\\partial t} + (u_j \\nabla_j) u_i + \\nabla_i P - \\frac{1}{Re} \\Delta u_i = 0, \\\\\n    \\label{eq:div0cons}\n    div(u) = 0\n    \\end{align}\n\\end{subequations}\n\nThis dimensionless form contains a characteristic Reynolds number $Re$, which defines the flow behaviour. Previously, speed of sound was used as a reference speed; however, in this case it is necessary to dimensionalize velocity by some known value related to the base flow itself, for example, inlet velocity, since there is no meaningful sound speed. Then, Reynolds number is defined as $Re = \\frac{\\rho U_{in} L}{\\mu}$.\n\nWe consider four types of boundary conditions:\n\n\\begin{itemize}\n    \\item Inlet boundary\n    \n    Velocity is prescribed at the inlet boundary, but not pressure. This is Dirichlet boundary condition, namely:\n    \\begin{equation}\n    u = U_{in} \\ \\ on \\ \\ \\Gamma_{in}\n    \\end{equation}\n    \n    \\item No slip boundary\n    \n    No slip boundary imposes no flow through the wall, and adhesion condition for viscous flows. Then, both normal and tangential velocity components are zero and the no slip Dirichlet boundary condition becomes:\n   \n    \\begin{equation}\n    u = 0 \\ \\ on \\ \\ \\Gamma_{nsl}\n    \\end{equation} \n    \n    \\item Slip boundary\n    \n    In some cases, for example if fluid is inviscid or a symmetry plane is modelled, slip wall boundary condition is required:\n    \n    \\begin{equation}\n    u_n = 0 \\ \\ on \\ \\ \\Gamma_{nsl}\n    \\end{equation} \n    \n    Here $u_n$ is a normal component of the flow velocity. Slip boundary condition allows non-zero flow along the surface.\n    \n    \\item Outlet boundary\n    \n    Outlet, or no-stress boundary is used to model outflow. Since pressure appears only in the gradient term, it is defined up to some constant. Let us set the outer pressure to zero, then the stress-free condition turns into\n    \n    \\begin{equation}\n    n_j (P\\delta_{ij} - \\frac{1}{Re} \\nabla_j u_i) = P n_i - \\frac{1}{Re} \\frac{\\partial u_i}{\\partial n} = 0\n    \\end{equation}\n    \n\\end{itemize}\n\nAdditionally, in the case of unsteady flow, initial condition $u(x,t=0)$ should be provided.\n\n\\subsection{Weak formulation}\n\nConsider for now that the flow is steady, $\\frac{\\partial u_i}{\\partial t} = 0$, and here we aim to construct a weak form of the reduced problem. Non-zero time derivative will be taken into account in the following section. \n\nFirst, we multiply the incompressible Navier--Stokes equation (\\ref{eq:IncNSeq}) by vector test function, $v_i$, and the divergence constraint (\\ref{eq:div0cons}) by scalar function, $q$, and integrate both over the computational domain. Second, we integrate the highest order derivatives, $-\\frac{1}{Re}\\Delta u_i$ and $\\nabla_i P$ by parts and collect all the integrals together. This leads to:\n\n\\begin{equation}\n\\label{eq:IncNSWeakForm}\n\\left<v_i (u_j \\nabla_j) u_i - P div(v) + \\frac{1}{Re}\\nabla_j v_i \\nabla_j u_i - q div(u)\\right> + \\left\\{ vi \\left( P n_i - \\frac{1}{Re} \\frac{\\partial u_i}{\\partial n} \\right) \\right\\} = 0\n\\end{equation}\n\nThe boundary integral disappears completely due to the boundary conditions. Inlet and no slip Dirichlet boundaries result in $v = 0$ since the choice of test function is arbitrary. Slip boundary sets both $u_{\\tau}, v_{\\tau}$ to zero and the remaining term vanishes due to the symmetry (or, equivalently, no shear stress at the boundary). Outlet boundary condition is exactly the last boundary integral multiplyed by some function, such that the last remaining term is zero everywhere.\n\nSumming up, the weak form of the incompressible Navier--Stokes equation with the given boundary types contains only a volumetric integral, with Dirichlet boundary conditions for inlet, slip and no slip boundaries.\n\n\\subsection{Newton method}\n\nThe problem (\\ref{eq:IncNSeqFull}) is nonlinear, the convective term is proportional to $u^2$. Let us recall the weak form (\\ref{eq:IncNSWeakForm}) and a steady residual form $\\mathbb{R}(q)$ is:\n\n\\begin{equation}\n\\mathbb{R}(q) = \\left<v_i (u_j \\nabla_j) u_i - P div(v) + \\frac{1}{Re}\\nabla_j v_i \\nabla_j u_i - q div(u)\\right>\n\\end{equation}\n\nIt should be zero if $q = (u,P)$ satisfies the incompressible Navier--Stokes equation. Consider we have an initial guess of the flow state $q_0 = (u_0, P_0)$, which can, for instance, be chosen zero everywhere or satisfy the linear Stokes equation. We employ a Newton method to solve the nonlinear system with a known initial guess. To find the next iterate we linearize the residual form by taking the Frechet derivative with respect to state $q$. Linearization of the Dirichlet boundary conditions is straightforward, which finally gives:\n\n\\begin{equation}\n\\label{eq:IncNSFrechet}\n\\mathbb{R}(q^{n+1}) = \\mathbb{R}(q^n) + \\frac{\\partial \\mathbb{R}}{\\partial q} \\delta q + \\mathcal{O}(\\delta q^2)\n\\end{equation}\n\nAnd the linearized weak problem becomes:\n\n\\begin{equation}\n\\left<v_i \\left( (u_j \\nabla_j) \\delta u_i + (\\delta  u_j \\nabla_j) u_i \\right) - \\delta  P div(v) + \\frac{1}{Re}\\nabla_j v_i \\nabla_j \\delta  u_i - q div(\\delta u)\\right> = - \\mathbb{R}(q^n) \n\\end{equation}\n\nThen the initial nonlinear problem turns into a linear system on $\\delta q$. Setting (\\ref{eq:IncNSFrechet}) to zero and finding $\\delta q$, we update the previous solution as $q^{n+1} = q^n + \\delta q$ and calculate the $l_2$-norm of the updated residual, $\\Vert \\mathbb{R}(q^{n+1}) \\Vert _2$. If the norm is less than the chosen tolerance, the process is stopped. Otherwise, we continue the convergence procedure.\n\nA damped Newton method can be useful for some problems. It means, that the solution is updated by weighed step, $\\alpha_w \\delta q$, which is dynamically chosen to maintain better convergence rate. In present research, we used the undamped Newton algorithm.\n\n\\subsection{Unsteady mean flow}\n\nNow, consider time-dependent Navier--Stokes equation, with a new residual form to be introduced:\n\n\\begin{equation}\n    \\mathbb{N}(q(t)) = \\left< v_i \\frac{\\partial u_i}{\\partial t} \\right> + \\mathbb{R}(q(t))\n\\end{equation}\n\nThere are several methods of solving the unsteady problem, for example, fractional step method \\cite{DoneaFrac}. However, we want to employ the existing solution of the steady problem, and we aim to derive an implicit scheme for time integration. The idea is to perform the temporal discretization first, and then reduce new system to previous case. The Euler approach presents time derivative as\n\n\\begin{equation*}\n    \\frac{\\partial u}{\\partial t} \\rightarrow \\frac{u^{n+1} - u^n}{\\Delta t}\n\\end{equation*}\n\nHere we perform time discretization as $t^k = k\\Delta t$, where $\\Delta t$ is time step. The unsteady weak formulation then becomes:\n\n\\begin{equation}\n\\label{eq:IncNSweakUnst}\n    \\left< v_i \\frac{u^{n+1}_i}{\\Delta t} \\right> + \\mathbb{R}(q^{n+1}) = \\left< v_i \\frac{u^{n}_i}{\\Delta t} \\right>\n\\end{equation}\n\nThis is still a nonlinear problem, and we follow the same strategy as for the steady problem. Taking the Frechet derivative of (\\ref{eq:IncNSweakUnst}), the iterative scheme is given by:\n\n\\begin{subequations}\n\\begin{align}\n    \\left< v_i \\frac{\\delta u_i}{\\Delta t}  + v_i \\left( (u_j \\nabla_j) \\delta u_i + (\\delta  u_j \\nabla_j) u_i \\right) - \\delta  P div(v) + \\frac{1}{Re}\\nabla_j v_i \\nabla_j \\delta  u_i - q div(\\delta u)\\right> = \\\\\n    \\label{eq:IncNSweakUnsRHS}\n    - \\mathbb{R}(q) + \\left< v_i \\frac{u^{n}_i - u_i}{\\Delta t} \\right>\n\\end{align}\n\\end{subequations}\n\nHere linear system is solved for $\\delta q$, $u^n$ corresponds to the known velocity at the previous time step, and $u_i$ is the velocity iterate updated as $u_i \\rightarrow u_i + \\delta u_i$ until the convergence criteria is met. As the right hand side (\\ref{eq:IncNSweakUnsRHS}) goes to zero, a new solution is found for time $t^{n+1}$.\n\nThe advantage of this approach is only a little difference from the steady formulation. First, the time derivative term $v_i \\frac{\\delta u_i}{\\Delta t}$ is added to the bilinear form, and second, the semi-time derivative $\\frac{u^{n}_i - u_i}{\\Delta t}$ appears on the linear form. Essentially, the solution process doesn't differ from that previously discussed. \n\\clearpage\n\n\n\n\n\n\\section{Acoustic flow in low Mach number limit}\n\nIn the previous sections we discussed the technique of splitting the initial set of compressible Navier--Stokes equations into two smaller problems, the incompressible mean flow and the acoustic flow, governed by two small parameters, $\\mu$ and $\\varepsilon$, respectively. Here we consider the acoustic, or the fluctuating flow created by an oscillating piezo-element boundary. We develop the general strong and weak formulation of the acoustic problem, types of boundary conditions relevant to the problem, to finally obtain the adjoint system and the stability sensitivity to the changes in shape.\n\n\\subsection{Problem statement}\n\nWe recall the result of the low Mach number expansion, and the linear acoustic equations (\\ref{eq:acousticT}) will be the primal object of interest. Since the viscous source term in the energy equation (\\ref{eq:cNSFluxes}) is proportional only to the squared amplitude of the velocity $\\mathcal{O}(u^2)$, this allows us to assume that the energy production due to the viscosity is small thus making our flow isentropic for the purpose of relating $\\tilde{P}$ to $\\tilde{\\rho}$. Note that we retain viscosity in the momentum equation, where it appears at first order in $u$. The isentropic flow property allows us to eliminate the pressure term in the momentum equation which in dimensional case is related to density through the speed of sound, $c_s$: $\\nabla \\tilde{P} = c_s^2 \\nabla \\tilde{\\rho}$. Summing up, the remaining dimensional continuity and momentum equations are:\n\n\\begin{subequations}\n\\label{eq:linNS}\n\\begin{align}\n        \\partial_t \\tilde{\\rho} + \\rho_0 div(\\tilde{u}) = 0, \\\\\n        \\rho_0 \\partial_t \\tilde{u}_i + c_s^2 \\nabla_i \\tilde{\\rho} - \\mu \\left(\\Delta \\tilde{u}_i + \\frac{1}{3} \\nabla_i div(\\tilde{u}) \\right) = 0.\n\\end{align}\n\\end{subequations}\n\nFor the purpose of the stability analysis of the acoustic problem, instead of solving the unsteady problem we move to the frequency domain assuming solutions in form of $\\tilde{\\mathbf{q}}(x,t) = \\hat{\\mathbf{q}}(x) e^{st}$, such that $\\partial_t (\\rho', u') \\rightarrow s (\\hat{\\rho}, \\hat{u})$, where $\\hat{\\rho}, \\hat{u}$ are  complex  amplitudes  and $s$ is a complex  frequency  of  a  mode. New dimensionless variables become: $\\tilde{\\rho}/\\rho_0 \\rightarrow \\hat{\\rho}, \\tilde{u}_i / c_s \\rightarrow \\hat{u}_i , \\mu/ (\\rho_0 c_s L) \\rightarrow \\nu \\equiv Re^{-1}, s L/c_s \\rightarrow s $. We  look  for  a  normal mode solution, so the  eigenvalue problem can finally be written as:\n\n\\begin{subequations}\n\\label{eq:strViscAc}\n\\begin{align}\n        -div(\\hat{u}) = s \\hat{\\rho}, \\\\\n        \\nabla_i \\hat{\\rho} - \\nu \\left(\\Delta \\hat{u}_i + \\frac{1}{3} \\nabla_i div(\\hat{u}) \\right) = - s \\hat{u}_i .\n\\end{align}\n\\end{subequations}\n\nThe sign of the first equation becomes important for the symmetry of the weak form. The momentum equation can be rewritten in the form of the Newton's law, by introducing a new variable for the stress tensor $\\hat{\\sigma}_{ij} = - \\hat{\\rho} \\delta_{ij} + \\nu \\left( \\nabla_j \\hat{u}_i + \\nabla_i \\hat{u}_j - 2/3 \\delta_{ij} div(\\hat{u}) \\right)$. The divergence of the stress tensor is an acting force, thus \n\n\\begin{equation}\ns \\hat{u}_i = \\nabla_j \\hat{\\sigma}_{ij}\n\\end{equation}\n\nNow the acceleration term on the left hand side equals to the force term on the right hand side. We will use the stress tensor notation while formulating the weak problem and the boundary conditions.\n\n\n\\subsection{Weak formulation}\n\nNow, the weak form of the given dimensionless eigenvalue problem is introduced. Multiplying the first scalar equation by a scalar test function, $w$, and the momentum equation by a vector test function, $v_i$, and integrating over the domain we have:\n\n\\begin{subequations}\n\\begin{align}\n        \\left< -div(\\hat{u}) w \\right> =\\left< s \\hat{\\rho} w \\right>, \\\\\n        \\left< - v_i \\nabla_j \\hat{\\sigma}_{ij} \\right>= \\left<- s \\hat{u}_i v_i\\right>\n\\end{align}\n\\end{subequations}\n\nAfter summation and integration by part the highest order derivatives once we will have several boundary integrals, namely:\n\n\\begin{equation}\n\\label{eq:AcousGenerWeak}\n    \\left< - div(\\hat{u}) w  + \\hat{\\sigma}_{ij} \\nabla_j v_i \\right>  - \\left\\{ v_i n_j \\hat{\\sigma}_{ij} \\right\\} = s \\left< \\hat{\\rho} w - \\hat{u}_i v_i \\right>.\n\\end{equation}\n\nThe volumetric terms $\\left<\\dots\\right>$  and the boundary terms $\\left\\{\\dots\\right\\}$ of the weak form are not yet symmetric to the swap of the test functions to trial functions. We won't symmetrize the boundary integrals at this point, but after the boundary conditions are considered. Regarding the volume integrals, from the symmetry of the stress tensor it is clear that:\n\n\\begin{subequations}\n\\begin{align}\n        &\\left<\\hat{\\sigma}_{ij} \\nabla_j v_i \\right> = \\left<\\frac{1}{2}\\hat{\\sigma}_{ij} (\\nabla_j v_i + \\nabla_j v_i) \\right>  = \\\\\n        &\\left<- \\hat{\\rho} div(v) +  \\frac{\\nu}{2} \\left( \\nabla_j \\hat{u}_i + \\nabla_i \\hat{u}_j - \\frac{2}{3} \\delta_{ij} div(\\hat{u}) \\right) (\\nabla_j v_i + \\nabla_i v_j) \\right> = \\\\\n        \\label{eq:DirWeakSymm}\n        &\\left<- \\hat{\\rho} div(v) +  \\frac{\\nu}{2} \\left( \\nabla_j \\hat{u}_i + \\nabla_i \\hat{u}_j - \\frac{2}{3} \\delta_{ij} div(\\hat{u}) \\right) (\\nabla_j v_i + \\nabla_i v_j - \\frac{2}{3} \\delta_{ij} div(v) ) \\right>\n\\end{align}\n\\end{subequations}\n\nSubstituting (\\ref{eq:DirWeakSymm}) back to the (\\ref{eq:AcousGenerWeak}), one can see, that by rearranging terms in the volume integral it is possible to maintain symmetry between the test and trial functions.\n\nThe weak formulation can be alternatively written in matrix form:\n\n\\begin{equation}\n    \\mathbf{A}\\mathbf{q}_k = s_k \\mathbf{B}\\mathbf{q}_k\n\\end{equation}\n\nHere \\textbf{A},\\textbf{B} are the matrix representation of the left and right  hand  side  differential  operators in (\\ref{eq:strViscAc}),  $\\mathbf{q}_k$ is the state vector $(\\hat{\\rho}, \\hat{u})$, i.e. a natural mode of the system, and $s_k$ is  the $k$-th eigenvalue. \n\n\n\n\\subsection{Boundary conditions}\n\nSince the acoustics is decoupled from the mean flow, we will call inlet and outlet boundaries $free$ boundaries, while the $slip$ and $no slip$ boundaries still have the same meaning as for the mean flow problem. Then, boundary conditions for two state variables - density and velocity perturbations $\\rho$ and $u$, can be written as:\n\n\\begin{subequations}\n\\begin{align}\n    \\hat{\\sigma}_{ij} n_j  = 0 \\ \\ on  \\ \\ \\Gamma_{free}, \\\\\n    \\hat{u}_i = 0 \\ \\ on \\ \\ \\Gamma_{nsl},\\\\\n    \\hat{u}_i n_i = 0 \\ \\ on \\ \\ \\Gamma_{sl}\n\\end{align}\n\\end{subequations}\n\nThe free boundary condition reads as zero stress on the inlet and outlet boundaries, and in the limit of zero viscosity $\\nu \\rightarrow 0$ it acts like a pressure (density) node.\n\nAdditionally, the presence of a slip boundary imposes the symmetry of the system. Then, every variable implies to be either an even or an odd function. In case of the normal velocity, $u_n$, it is odd as a result of the $u_i n_i = 0$ boundary condition. Then it is clearly seen (e.g. from the continuity equation), that two other variables, $\\rho$ and $u_{\\tau}$ must be even with respect to the normal symmetry. This gives us an additional boundary condition $\\frac{\\partial}{\\partial n}u_{\\tau}= 0$ on the symmetry plane.\n\n%Let us make a small remark regarding a vector's components normal and tangential to a boundary. Consider we have a general expression for a scalar product of a vector $a_i$ and a normal directional derivative of a vector $\\frac{\\partial b_i}{\\partial n}$. It can be shown, that:\n\n%\\begin{subequations}\n%\\begin{align}\n%    a_i \\frac{\\partial b_i}{\\partial n} = \\left(a_n n_i + a_{\\tau} \\tau_i \\right) n_j \\nabla_j \\left( b_n n_i + b_{\\tau} \\tau_i \\right) = \\\\\n%    \\label{eq:scalProdDirDer}\n%    \\left(a_n \\frac{\\partial b_n}{\\partial n} + a_{\\tau} \\frac{\\partial b_{\\tau}}{\\partial n} \\right) + \\left(a_n b_{\\tau} - a_{\\tau} b_n \\right) n_j n_i \\nabla_j \\tau_i\n%\\end{align}\n%\\end{subequations}\n\n%Here we denote $n_i$ as $i-$th component of the surface normal vector and ${\\tau}_i$ stands for a vector tangent to surface; $a_n, b_n$ are (scalar) projections of two vectors on $n$, and $a_{\\tau}, b_{\\tau}$ are (scalar) tangent projections. Note, that in (\\ref{eq:scalProdDirDer}) there is a term which represents surface curvature; it appears because of the changing direction of surface normal along the boundary. While applying boundary conditions to the weak form, one should be careful not to forget the presence of the surface curvature. However, in many cases both $a_{\\tau}$ and $b_{\\tau}$ are zero, so the curvature term vanishes. \n\nNow, we can apply these boundary conditions to the weak formulation by introducing different boundary terms. Moreover, it becomes clear how to make the full weak form symmetric and still consistent with the strong form.\n\n\\begin{itemize}\n  \\item Free boundary, $\\Gamma_{free}$\n  \n  First, free boundary models an open end; thus, a zero force boundary condition is considered. This yields:\n  \n  %\\begin{equation}\n  %\\left\\{ v_i n_j \\hat{\\sigma}_{ij} \\right\\}_{\\Gamma_{free}} = \\left\\{ v_n n_i n_j \\hat{\\sigma}_{ij} + v_{\\tau} \\tau_i n_j \\hat{\\sigma}_{ij} \\right\\}_{\\Gamma_{free}}\n  %\\end{equation}\n  \\begin{equation}\n  \\left\\{ v_i n_j \\hat{\\sigma}_{ij} \\right\\}_{\\Gamma_{free}} = 0\n  \\end{equation}\n  %The first term on the right hand side vanished due to the force boundary condition, and the second term after substitution of $\\hat{\\sigma}_{ij}$ becomes:\n  \n  %\\begin{equation}\n  %\\left\\{ - \\nu v_{\\tau} \\tau_i \\frac{\\partial u_i}{\\partial n} \\right\\}_{\\Gamma_{free}}\n  %\\end{equation}\n  \n  %The $u_{\\tau} = 0$ is a Dirichlet boundary condition, and if one apply the usual finite element Dirichlet boundary condition on the tangential velocity, the corresponding test function $v_{\\tau}$ can be (or is automatically) chosen to be zero, thus the boundary term vanished completely. However, in some cases tangential direction is not constant (e.g. if the inlet boundary is curved), therefore it becomes less straightforward how to impose the $u_{\\tau}$ value.\n  \n  A possible way to enforce the zero force boundary condition  is to impose it weakly by introducing a penalty boundary term \\cite{Nitsche1971}, \\cite{freund1995weakly}. We add a symmetric term consistent with the primal formulation, such that the boundary integral over the free surface becomes\n  \n  %\\begin{equation}\n  %\\left\\{ - \\nu  v_{\\tau} \\tau_i \\frac{\\partial u_i}{\\partial n} \\right\\}_{\\Gamma_{free}} = \\left\\{ - \\nu \\left( v_{\\tau} \\tau_i \\frac{\\partial u_i}{\\partial n}  + u_{\\tau} \\tau_i \\frac{\\partial v_i}{\\partial n} \\right) \\right\\}_{\\Gamma_{free}} + \\beta \\left\\{  u_{\\tau}  v_{\\tau} \\right\\}_{\\Gamma_{free}}\n  %\\end{equation}\n  \n  \\begin{equation}\n  \\frac{\\beta}{h} \\left\\{ \\sigma_{ij} n_j , \\sigma_{ik}^\\dagger n_k \\right\\}_{\\Gamma_{free}}\n  \\end{equation}\n  \n  Here $\\beta$ is a constant coefficient, and $h$ is the triangulation cells size; the ''daggered'' stress tensor takes test functions as variables: $\\sigma_{ik}^\\dagger = \\sigma_{ik} (w, v)$. The updated form of the boundary term is consistent with the initial problem, since $\\sigma_{ij} n_j$ vanishes on ${\\Gamma_{free}}$.\n  \n  \\item No slip boundary, $\\Gamma_{nsl}$\n  \n  Second, the no slip boundary represents a rigid wall with no flow through it, so the velocity is zero at $\\Gamma_{nsl}$ and no restriction on density is applied. Even if the no slip boundary is curved, i.e. if the normal and tangential directions depend on the position on the boundary, the Dirichlet boundary condition can be easily applied and thus the test function can be set to zero on $\\Gamma_{nsl}$. Note, that the boundary term in (\\ref{eq:AcousGenerWeak}) is linear on $v_i$ thus it vanishes. \n  \n  \\item Slip boundary, $\\Gamma_{sl}$\n  \n  Third, the slip or symmetry boundary implies that there is no normal flow, but the tangential velocity is not specified. The slip boundary in viscous flows usually appears as a plane of symmetry, which is a line in 2D or a plane surface in 3D, thus the Dirichlet boundary condition should be generally easy to implement. In other words, the normal velocity should vanish $u_n = 0$ as well as the normal test function can be set to zero $v_n = 0$. Assuming the surface normal being constant along the slip boundary, the surface integral becomes:\n  \n  \\begin{equation}\n  \\begin{aligned}\n  \\left\\{ v_i\\sigma_{ij} n_j \\right\\}_{\\Gamma_{sl}} =   \\left\\{ v_n n_i \\sigma_{ij} n_j + v_{\\tau} \\tau_i \\sigma_{ij} n_j \\right\\}_{\\Gamma_{sl}} = \\\\ \n  \\left\\{ v_{\\tau} \\nu \\left( \\frac{\\partial u_{\\tau}}{\\partial n} + \\frac{\\partial u_n}{\\partial \\tau} \\right)  \\right\\}_{\\Gamma_{sl}} = 0\n  \\end{aligned}\n  \\end{equation}\n  \n  The first term vanishes due to the symmetry of the symmetry of the slip plane, and the second term is zero since the normal velocity component is constant in the tangent direction.\n  \n  \\item Robin (compliant) boundary\n  \n  Finally, the last boundary type to be presented is a mixed Robin boundary, or a compliant boundary. Previous boundaries were defined by either Dirichlet or Neumann type of boundary conditions. Furthermore, we can assume a mixed case or equivalently a boundary condition which relates the components of the state vector $\\hat{\\mathbf{q}}$ to each other; or, a value to its gradient. The velocity Robin boundary condition generally appears in the following form:\n  \n  \\begin{equation*}\n     \\frac{\\partial u}{\\partial n} = \\frac{1}{\\varepsilon} (u - u_0) + f \\ \\ on \\ \\ \\Gamma_{Rob}\n  \\end{equation*}\n  \n  As the parameter $\\varepsilon$ approaches two limit cases, $\\varepsilon \\to 0$ or $\\varepsilon \\to \\infty$, the Robin boundary condition turns into a inhomogeneous Dirichlet or Neumann boundary condition, respectively. The quantities of $u_0$ and $f$ then play role of prescribed velocity or velocity gradient at the boundary. Boundary condition becomes homogeneous when $u_0$ or $f$ are zero.\n  \n  Following \\cite{JuntunenS09}, it is possible to extend the Nitsche approach for imposing Dirichlet boundary condition \\cite{Nitsche1971} to broader range of boundary types with $\\epsilon \\ge 0$. The final weak formulation is consistent, symmetric and successfully compared to the traditional techniques. We refer to \\cite{JuntunenS09} for the detailed derivation of the general method, and the following section will consider the particular case of the Robin condition.\n\\end{itemize}  \n  \n\\subsection{Compliant boundary}\n\nWe consider the following problem: the domain now acts as a solid structure which boundaries are not fixed and can displace, reacting to the flow. This is a fluid-structure interaction (FSI) problem, and the modeled geometry and thus the computational domain may change as a result of boundary displacement. When the displacement is big enough to actually affect the mean flow, computational meshes and structure position should be moved. A number of methods describing the motion of fluid particles and mesh nodes exists, for instance the Arbitrary-Lagrange-Eulerian (ALE) approach \\cite{Donea1982}. Moving boundary condition prescribes equality of the flow and solid surface quantities, namely kinematic and dynamic conditions. First, as soon as the surface is compliant (in contrast to permeable), the continuity of displacements and velocities is required; second, the stresses in the fluid and the body should be the same \\cite{Donea2004}. These conditions couple the fluid-structure system.\n\nMoreover, one can consider a FSI problem when boundaries are compliant, but surface deformation is tiny in comparison to the domain's size. This is the case of the inkjet printer chamber, whose height is in order of 100 $\\mu$m and the boundary displacement is less than 100 nm. Then the relative displacement is lower than $10^{-3}$ and modelling this phenomena as a full FSI problem with the mesh movement is excessive. However, the flow can differ from those obtained with rigid slip or no slip boundary, especially for the oscillating acoustic quantities. This leads us to the idea of treating the compliant boundary in a more suitable way: with no actual domain and mesh deformation but taking into account the nature of the solid-fluid interaction on this boundary type.\n\nThe Robin boundary can describe a boundary which act like a moving membrane, reacting to the perturbations in the flow. The acoustic compliant boundary condition links the flow density (or pressure) and velocity at a certain surface point and a complex boundary impedance $Z$ is a function which relates the normal velocity component to pressure \\cite{Myers1980}:\n\n\\begin{equation}\n\\label{eq:InitImpedAcoustic}\nu_i n_i = - \\frac{P}{Z}\n\\end{equation}\n\nFurthermore, we should extend this definition for the viscous acoustic problem. Recalling the idea of the impedance concept, \\enquote{impedance denotes originally the ratio between a force amplitude and a velocity amplitude} \\cite{rienstra}. Now, a force is represented not only by pressure, but also by viscous stress tensor. Then, the impedance-based relation becomes:\n\n\\begin{equation}\n\\label{eq:InitImped}\nZ u_i = \\sigma_{ij} n_j  =   (-P \\delta_{ij} + \\tau_{ij}) n_j\n\\end{equation}\n\nWe would neither restrict the velocity to be zero in the tangential direction, nor allow only normal displacements of the compliant boundary. Boundary impedance describes the physical properties of the boundary, such as stiffness, elasticity, thickness and others. Usually, the impedance value is known for harmonic motion with a given frequency, making the boundary condition frequency dependent: $Z = Z(s)$. As discussed before, both acoustic pressure and velocity are considered to be proportional to $(\\tilde{P}, \\tilde{u}) \\sim e^{st}$ thus they can become out of phase due to the complex impedance boundary condition.\n\nTo apply the compliant boundary condition to viscous acoustic flow, we need to rearrange some terms in (\\ref{eq:InitImped}). First, performing low Mach number expansion of the impedance expression and nondimensionalizing it, we obtain an equation of the velocity and density fluctuations coupled through the dimensionless acoustic impedance, $\\hat{Z} = \\frac{Z}{\\rho^b c_s^b}$. Second, the pressure fluctuation is substituted with density. Summing up:\n\n\\begin{equation}\n\\label{eq:BCCompl}\n\\hat{Z} \\hat{u}_i= \\hat{\\sigma}_{ij} n_j  \\ \\ on \\ \\ \\Gamma_{com}\n\\end{equation}\n\nNow, we can derive boundary integrals of the weak problem on the compliant boundary. The boundary relation (\\ref{eq:BCCompl}) can now be inserted into the weak form.\n\n\\begin{equation}\n\\left\\{ v_i n_j \\hat{\\sigma}_{ij} \\right\\}_{\\Gamma_{com}} = \\left\\{ Z v_i u_i \\right\\}_{\\Gamma_{com}}\n\\end{equation}\n\nThe boundary integral is symmetric; for the same reason as we did in the free boundary case, additional penalty term should be added to impose compliant boundary condition. Consequently, the compliant boundary integral becomes:\n\n\\begin{equation}\n\\label{eq:ComplBoundInt}\n\\left\\{\\hat{Z} v_i u_i \\right\\}_{\\Gamma_{com}} + \\frac{\\beta}{h} \\left\\{ Z u_i - \\hat{\\sigma}_{ij} n_j , Z v_i - \\hat{\\sigma}_{ij}^{\\dagger} n_j \\right\\}_{\\Gamma_{com}}\n\\end{equation}\n\nThe initial acoustic problem is an eigenvalue problem, and previously the boundary terms were independent of $s$. Both terms in (\\ref{eq:ComplBoundInt}) is proportional to $\\hat{Z}(s)$, so the impedance needs to be moved to the right hand side of the weak form. But then the problem becomes nonlinear on $s$, which requires to introduce some complication to the calculation routine. While this is not preferable, we assume $\\hat{Z}$ to be fixed and only rearrange the term directly dependent on $s$. We solve the simplified eigenvalue problem iteratively, substituting the complex frequency into the known impedance function until the convergence criteria is reached. The algorithm for the direct and adjoint problems will be discussed separately.\n\nFinally, two limit cases should be discussed. Compliant boundary condition is in close relation to both free and no slip conditions, which is clearly seen from (\\ref{eq:BCCompl}). As $\\hat{Z} \\to 0$, the compliant boundary turns into the free surface, i.e. $n_j \\hat{\\sigma}_{ij} \\to 0$. The boundary integral (\\ref{eq:ComplBoundInt}) approaches the free boundary term as well. If the impedance amplitude is high, $\\hat{Z} \\to \\infty$, we can expect no slip behavior, and the terms proportional to $\\hat{Z}$ in (\\ref{eq:ComplBoundInt}) dominate, weakly imposing Dirichlet boundary condition on $\\Gamma_{com}$ by penalty formulation. The concept of one universal parameter, $\\hat{Z}$ in this case, which describes each of the existing boundary types with only one quantity, is quite convenient, since the development of a numerical solver becomes more generalized in comparison to boundaries with different physics behind.\n", "meta": {"hexsha": "00a587b5832ff24dfa4d9d00a2a8c1047c9cd3c7", "size": 44030, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapter1/chapter1.tex", "max_stars_repo_name": "Corwinpro/FirstYearReport", "max_stars_repo_head_hexsha": "4a8b6f5af3787dd3c182fa074d4242d8a29f8348", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter1/chapter1.tex", "max_issues_repo_name": "Corwinpro/FirstYearReport", "max_issues_repo_head_hexsha": "4a8b6f5af3787dd3c182fa074d4242d8a29f8348", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1/chapter1.tex", "max_forks_repo_name": "Corwinpro/FirstYearReport", "max_forks_repo_head_hexsha": "4a8b6f5af3787dd3c182fa074d4242d8a29f8348", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 84.3486590038, "max_line_length": 996, "alphanum_fraction": 0.7303202362, "num_tokens": 12164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.3142240456389592}}
{"text": "\\section{Deep Learning: Advanced}\n\\subsection{Autoencoders}\n\\subsubsection{Variational Autoencoders}\n\\subsection{General Adversarial Networks}\n\\subsection{Encoder-Decoder Models}\nEncoder-decoder models allow for many to many RNN sequence learning. The idea\nfor them is two take a source sequence, encode it to a vectorized output, and\npass the hidden state over to the decoder (and possible the encodings themselves)\nto generate output. These models come up in machine tranlsations, allowing\nmodels to translate a source language into a target language.\n\\subsubsection{Encoders}\n% The encoder, or \\emph{inference network}, recieves an input sequence\n% $\\arrow{x} = \\left[x_1, \\cdots, x_n \\right]$ and encodes the sequence through\n% recurrent layers.\n\\subsubsection{Decoders}\n\\subsection{Attention Models}\nAttention models were discussed by Bahdanau, and later Luong. They are a means\nto alter the representation of a set of encodings to pay attention to certain\nsequence elements more so than others. In an encoder-decoder model with out\nattention, the decoder relies exclusivly on the hidden state to hold all\ninformation. Attention, by contrast, uses the hidden state to create a context\nvector of the encodings.\n\\subsubsection{Context Vector}\nAttention mechanisms rely on one simple concept: producing context vectors.\nHence, given a set of encodeings $h = \\left[h_i, \\cdots, h_j, \\cdots h_n \\right]$\nfrom the encoder, and the current hidden state $s_{i-1}$, we compute a score\nfor each encoding $h_j$, denoted $score(s_{i-1}, h_j)$. These scores are discussed\nin later sections. With a score computed for each encoding, we apply a softmax\nacross all scores:\n\\begin{equation}\n  a(s_{i-1}, h_j) = \\frac{\\exp(score(s_{i-1}, h_j))}{\\sum_{j'} \\exp(score(s_{i-1}, h_{j'}))}\n\\end{equation}\nThese softmax proabilities are attention weights, and our context vector $c_i$\nis the weighted sum of the encodings given these weights:\n\\begin{equation}\n  c_i = \\sum_{j'} a(s_{i-1}, h_{j'}) \\cdot h_{j'}\n\\end{equation}\nThese context vectors are appended to the embedding of the token set into the decoder.\n\\subsubsection{Concat (Bahdanau) Attention}\nThe concat attention scoring mechanism has two learnable weights, $v_a$ and $W_a$\nand is defined as:\n\\begin{equation}\n  score(s_{i-1}, h_j) = v_a^T \\cdot \\tanh \\left( W_a \\cdot \\left[ s_{i-1} ; h_j \\right] \\right)\n\\end{equation}\n\\subsubsection{Luong Attention Mechanisms}\nLuong defined several global attention mechanisms, defined here:\n\\begin{equation}\n  score(s_{i-1}, h_j) =\n    \\begin{cases}\n      s_{i-1}^T \\cdot W_a \\cdot h_j & general \\\\\n      s_{i-1}^T \\cdot h_j & dot\n    \\end{cases}\n\\end{equation}\nLuong also explored local attention weights, with monotonic alignment and\npredictive alignment. The difference in local attention is that the\ncontext vector is derived on source hidden states within the window\n$\\left[p_t - D , \\, p_t + D\\right]$ for some $D$ and decoder time step $t$ (i.e. $i-1$).\nIn monotonic alignment, aligned position $p_t=t$.\nIn predicitve alignment, the aligned position is:\n\\begin{equation}\n  p_t = S \\cdot \\sigma \\left( v_p^T \\tanh \\left( W_p s_{i-1} \\right) \\right)\n\\end{equation}\nwhere $v_p$ and $W_p$ are learnable parameters,\n$S$ is the source sentence length. In addition, the weights are gaussian centered\naround $p_t$:\n\\begin{equation}\n  a(s_{i-1}, h_j) = \\frac{\\exp(score(s_{i-1}, h_j))}{\\sum_{j'} \\exp(score(s_{i-1}, h_{j'}))} \\cdot \\exp\\left(-\\frac{(s-p_t)^2}{2\\left(\\frac{D}{2}\\right)^2}\\right)\n\\end{equation}\nHere, $s$ is an integer within the window centered at $p_t$.\n\n\n\\subsection{Word Embeddings}\nWord Embeddings seek to create a dense vector representation of real values\nto represent a single word in a euclidean space. Word vectors are weight matrices\nwhere each row corresponds to a word, acessed through a numerical token representing\nthe word itself. However, several models have been developed to train these\nword embedding weights to encode lexical meaning.\n\\subsubsection{N-Gram Models}\nA simple apporach is to take a context of size $n$ words that appear before our\ntarget word, and attempt to train a model to predict a word $w_i$ that appears\nin a training corpus. We effectively average the input word embeddings, apply\na linear layer to project the data to the vocab size, and maximize the probability\nof predicitng the target word (i.e. apply a softmax of the output vector).\n\\begin{equation}\n  \\max \\, p(w_{i} \\,|\\, w_{i-n}, \\dots, w_{i-1}) = \\max \\frac{\\exp f(w_{i-n}, \\dots, w_{i-1})_i}{\\sum_{j=1}^{|V|}\\exp f(w_{i-n}, \\dots, w_{i-1})_j }\n\\end{equation}\nWhere our model is:\n\\begin{equation}\n  f(w_{i-n}, \\dots, w_{i-1}) = W_d \\cdot \\left( \\frac{1}{n}\\sum_{j=1}^n W_e[w_{i-j}] \\right) + b_d \\in \\mathbb{R}^{|V|}\n\\end{equation}\nHere, $|V|$ is the size of the vocabulary, $W_d\\in\\mathbb{R}^{d\\times|V|}$ is\na projection matrix used for training along with bias $b_d$,\nand $W_e\\in\\mathbb{R}^{|V|\\times d}$ are the word embeddings we seek to train.\n$d$ is the embedding dimension. \\\\\nNow we can write the negative log likelihood as:\n\\begin{equation}\n    \\min -\\log p(w_{i} \\,|\\, w_{i-n}, \\dots, w_{i-1}) = - f(w_{i-n}, \\dots, w_{i-1})_i + \\log \\sum_{j=1}^{|V|} \\exp f(w_{i-n}, \\dots, w_{i-1})_j\n\\end{equation}\n\\subsubsection{Continuous Bag-of-Words Models (CBOW)}\nThe continuous bag of words model, or CBOW, seeks to predict a center word\ngiven the surrounding context words. For instance, given a context size of $n$,\nfor a target center word $w_i$, we are given context words\n$w_{i-n}, \\dots w_{i-1}, w_{i+1}, \\dots w_{i+n}$ and attempt to predict $w_i$.\nHence:\n\\begin{equation}\n  \\max \\, p(w_{i} \\,|\\, w_{i-n}, \\dots, w_{i-1}, w_{i+1}, \\dots, w_{i+n}) = \\max \\frac{\\exp f(w_{i-n}, \\dots, w_{i-1}, w_{i+1}, \\dots, w_{i+n})_i}{\\sum_{j=1}^{|V|}\\exp f(w_{i-n}, \\dots, w_{i-1}, w_{i+1}, \\dots, w_{i+n})_j }\n\\end{equation}\nWhere our model is:\n\\begin{equation}\n  f(w_{i-n}, \\dots, w_{i-1}, w_{i+1}, \\dots, w_{i+n}) = W_d \\cdot \\left( \\frac{1}{2*n}\\sum_{j=-n,j\\not=0}^n W_e[w_{i+j}] \\right) + b_d \\in \\mathbb{R}^{|V|}\n\\end{equation}\nHere, $|V|$ is the size of the vocabulary, $W_d\\in\\mathbb{R}^{d\\times|V|}$ is\na projection matrix used for training along with bias $b_d$,\nand $W_e\\in\\mathbb{R}^{|V|\\times d}$ are the word embeddings we seek to train.\n$d$ is the embedding dimension. \\\\\nNow we can write the negative log likelihood as:\n\\begin{equation}\n  \\begin{split}\n    \\min -\\log p(w_{i} \\,|\\, w_{i-n}, \\dots, w_{i-1}, w_{i+1}, \\dots, w_{i+n}) =& - f(w_{i-n}, \\dots, w_{i-1}, w_{i+1}, \\dots, w_{i+n})_i \\\\\n    &+ \\log \\sum_{j=1}^{|V|} \\exp f(w_{i-n}, \\dots, w_{i-1}, w_{i+1}, \\dots, w_{i+n})_j\n  \\end{split}\n\\end{equation}\n\\subsubsection{Skip-Gram Model}\n\\subsubsection{Negative Sampling}\n", "meta": {"hexsha": "af50c3b13f7b33605ad558f2499068e001d0c0c1", "size": 6687, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "study_guide/sections/dl_advanced.tex", "max_stars_repo_name": "nextBillyonair/StudyGuide", "max_stars_repo_head_hexsha": "3fbb85c1f738878935c18280d728ca7e92aa1414", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-02-18T19:47:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-17T21:49:14.000Z", "max_issues_repo_path": "study_guide/sections/dl_advanced.tex", "max_issues_repo_name": "nextBillyonair/StudyGuide", "max_issues_repo_head_hexsha": "3fbb85c1f738878935c18280d728ca7e92aa1414", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "study_guide/sections/dl_advanced.tex", "max_forks_repo_name": "nextBillyonair/StudyGuide", "max_forks_repo_head_hexsha": "3fbb85c1f738878935c18280d728ca7e92aa1414", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.496, "max_line_length": 223, "alphanum_fraction": 0.7076416928, "num_tokens": 2177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3142240456389592}}
{"text": "\\documentclass[american]{beamer}\n\\usepackage[T1]{fontenc}\n\\usepackage[utf8]{inputenc}\n\\setcounter{secnumdepth}{3}\n\\setcounter{tocdepth}{3}\n\\usepackage{amssymb}\n\\usepackage{graphicx}\n\\usepackage{babel}\n\\usepackage{amsmath}\n\n\\usetheme{Berlin}\n\\usecolortheme{whale}\n\n\n\\title{Random Walk with Varying Transition Probabilities Applied on Tennis Modelling}\n\\subtitle{Mathsport International 8 - 2021}\n\\institute[Tomáš Kouřim (tom@skourim.com)]{\\inst{} Faculty of Nuclear Sciences and Physical Engineering, CTU Prague \\and\n    \\inst{} Institute of Information Theory and Automation, CAS CR Prague}\n\\date{25.6.2021}\n\\author[\\selectlanguage{czech}%\nTomáš Kouřim\\selectlanguage{czech}%\n]{Tomáš~Kouřim \\and }\n\\newcommand{\\nologo}{\\setbeamertemplate{logo}{}} % command to set the logo to nothing\n\\setbeamertemplate{itemize item}[circle]\n\\setbeamertemplate{itemize subitem}[square]\n\\setbeamercovered{transparent}\n%\\logo{\\includegraphics[height=1.3cm]{../CMSIM_Logo.pdf}}\n\n\\begin{document}\n    \\maketitle\n\n    \\section{Motivation}\\label{sec:motivation}\n\n    \\begin{frame}{Random walk}\n        \\begin{definition}\n            A man starts from a point $O$ and walks $l$ yards in a straight line;\n            he then turns through any angle whatever and walks another $l$\n            yards in a second straight line.\n            He repeats this process $n$ times.\n            I require the probability that after these $n$ stretches he is at\n            a distance between $r$ and $r+\\delta r$ from his starting point, $O$.\n\n            {\\footnotesize{}\\medskip{}\\emph{[Karl Pearson: The problem of the random walk.(1905)]}}\n\n            \\vspace{10mm}\n            \\begin{itemize}\n                \\item[]<2-> \\large{Where is the \\emph{drunken sailor}?}\n            \\end{itemize}\n        \\end{definition}\n    \\end{frame}\n\n    \\begin{frame}{Motivation - Random process with varying probability}\n        \\includegraphics[width=1\\textwidth]{../../simulations/probability_25_steps_type_success_punished_two_lambdas}\n    \\end{frame}\n\n    \\begin{frame}{Motivation}\n        \\begin{itemize}\n            \\item Failure of a machine\n            \\begin{itemize}\n                \\item repair after failure\n                \\item preventive maintenance\n            \\end{itemize}\n            \\item<2-> Occurrence of a disease\n            \\begin{itemize}\n                \\item cure of the disease\n                \\item prevention (i.e. lifestyle change)\n            \\end{itemize}\n            \\item<3-> Development of sports match\n            \\begin{itemize}\n                \\item goal scored, point achieved\n                \\item period won\n            \\end{itemize}\n        \\end{itemize}\n    \\end{frame}\n\n    \\begin{frame}{Motivation - Random process with varying probability}\n        \\includegraphics[width=1\\textwidth]{../../simulations/probability_dots_25_steps_type_success_punished_two_lambdas}\n    \\end{frame}\n\n    \\section{Model description}\\label{sec:model-description}\n    \\begin{frame}{Random walk with varying probabilities}\n        \\begin{itemize}\n            \\item<1-> Random walk with memory based the on standard Bernoulli random walk\n            \\item<2-> Given starting probability $p_0$\n            \\item<3-> $X_t\\in\\{-1,1\\}$ with $X_t \\sim {\\textrm{Bernoulli} }(p_{t-1})$\n            \\item<4-> Memory coefficient $\\lambda\\in(0,\\,1)$ affecting the development of probabilities $p_{t}$ as\n            \\onslide<4->\\begin{flalign*}\n                            X_{t} & =1\\rightarrow p_{t}=\\lambda p_{t-1} &\n                            X_{t} & =-1\\rightarrow p_{t}=1-\\lambda(1-p_{t-1}) &\n            \\end{flalign*}\n            \\vspace{-5mm}\n            \\begin{itemize}\n                \\item[-->]<5-> ``Success punishing''\n            \\end{itemize}\n            \\onslide<6->\\begin{flalign*}\n                            X_{t}&=1\\rightarrow p_{t}=1-\\lambda(1-p_{t-1})&\n                            X_{t}&=-1\\rightarrow p_{t}=\\lambda p_{t-1}&\n            \\end{flalign*}\n            \\vspace{-5mm}\n            \\begin{itemize}\n                \\item[-->]<6-> ``Success rewarding''\n            \\end{itemize}\n        \\end{itemize}\n    \\end{frame}\n\n    \\begin{frame}{Example - RW development}\n        \\includegraphics[width=1\\textwidth]{../../simulations/single_walk_1000_steps_type_success_punished}\n    \\end{frame}\n\n    \\begin{frame}{Example - RW development}\n        \\includegraphics[width=1\\textwidth]{../../simulations/single_walk_1000_steps_type_success_punished_p0_0.55}\n    \\end{frame}\n\n    \\begin{frame}{Walk steps properties}\n\n        \\begin{flalign*}\n            EX_{t} & =(2\\lambda-1)^{t-1}(2p_{0}-1)&\n        \\end{flalign*}\n        \\vspace{-5mm}\n        \\begin{flalign*}\n            \\lim_{t\\to+\\infty}EX_{t}&=0&\n        \\end{flalign*}\n        \\onslide<2->\n        \\begin{flalign*}\n            Var\\,X_{t}&=1-(2\\lambda-1)^{2(t-1)}(2p_{0}-1)^{2}&\n        \\end{flalign*}\n        \\vspace{-5mm}\n        \\begin{flalign*}\n            \\lim_{t\\to+\\infty}Var\\,X_{t}&=1&\n        \\end{flalign*}\n\n    \\end{frame}\n\n    \\begin{frame}{Example - RW steps}\n        \\includegraphics[width=1\\textwidth]{../../simulations/e_step_1000_walks_50_steps_type_success_punished}\n    \\end{frame}\n\n    \\begin{frame}{Walk probabilities properties}\n        \\begin{flalign*}\n            EP_{t} & =(2\\lambda-1)^{t}p_{0}+\\frac{1-(2\\lambda-1)^{t}}{2} &\n        \\end{flalign*}\n        \\vspace{-5mm}\n        \\begin{flalign*}\n            \\lim_{t\\to+\\infty}EP_{t} & =\\frac{1}{2} &\n        \\end{flalign*}\n        \\onslide<2->\n        \\begin{flalign*}\n            Var\\,P_{t} & =(3\\lambda^{2}-2\\lambda)^{t}p_{0}^{2}+\\sum_{i=0}^{t-1}K(i;p_{0},\\lambda)(3\\lambda^{2}-2\\lambda)^{t-1-i}-k(t;p_{o},\\lambda)^{2} &\n        \\end{flalign*}\n        \\vspace{-5mm}\n        \\begin{flalign*}\n            \\lim_{t\\to+\\infty}Var\\,P_{t} & =\\frac{\\frac{1}{2}(1-\\lambda^{2})}{-3\\lambda^{2}+2\\lambda+1}-\\frac{1}{4} &\n        \\end{flalign*}\n    \\end{frame}\n\n    \\begin{frame}{Example - RW probabilities}\n        \\includegraphics[width=1\\textwidth]{../../simulations/e_probability_1000_walks_50_steps_type_success_punished}\n    \\end{frame}\n\n    \\begin{frame}{Walk position properties}\n        \\begin{flalign*}\n            ES_{t} & =S_{0}+(2p_{0}-1)\\frac{1-(2\\lambda-1)^{t}}{2(1-\\lambda)} &\n        \\end{flalign*}\n        \\vspace{-5mm}\n        \\begin{flalign*}\n            \\lim_{t\\to+\\infty}ES_{t} & =S_{0}+\\frac{(2p_{0}-1)}{2(1-\\lambda)} &\n        \\end{flalign*}\n        \\onslide<2->\n        \\begin{flalign*}\n            Var\\,S_{t} & =t+4\\sum_{i=0}^{t-1}\\sigma(i;p_{0},0,\\lambda)-a(t;p_{0},\\lambda) &\n        \\end{flalign*}\n        \\vspace{-5mm}\n        \\begin{flalign*}\n            \\lim_{t\\to+\\infty}Var\\,S_{t} & =c_{1}(p_{0},\\lambda)t+c_{2}(p_{0},\\lambda) &\n        \\end{flalign*}\n    \\end{frame}\n\n    \\begin{frame}{Example - RW position}\n        \\includegraphics[width=1\\textwidth]{../../simulations/e_position_1000_walks_50_steps_type_success_punished}\n    \\end{frame}\n\n    \\begin{frame}{Success rewarding model}\n        \\onslide<2->\n        \\begin{flalign*}\n            EX_{t} & =2p_{0}-1 &\n        \\end{flalign*}\n        \\vspace{-8mm}\n        \\begin{flalign*}\n            Var\\,X_{t} & =4p_{0}(1-p_{0}) &\n        \\end{flalign*}\n        \\onslide<1->\n        \\begin{flalign*}\n            EP_{t} & =p_{0} &\n        \\end{flalign*}\n        \\vspace{-8mm}\n        \\onslide<2->\n        \\begin{flalign*}\n            Var\\,P_{t} & =(2\\lambda-\\lambda^{2})^{t}p_{0}^{2}+p_{0}(1-\\lambda)^{2}\\sum_{i=0}^{t-1}(2\\lambda-\\lambda^{2})^{i}-p_{0}^{2} &\n        \\end{flalign*}\n        \\begin{flalign*}\n            ES_{t} & =S_{0}+t(2p_{0}-1) &\n        \\end{flalign*}\n        \\vspace{-8mm}\n        \\begin{flalign*}\n            Var\\,S_{t} & =4p_{0}(1-p_{0})t^{2}+a(p_{0},\\lambda)t-a(p_{0},\\lambda)\\frac{1-(2\\lambda-\\lambda^{2})^{t}}{(1-\\lambda)^{2}} &\n        \\end{flalign*}\n    \\end{frame}\n\n    \\begin{frame}{More complex models}\n        \\begin{itemize}\n            \\item Two memory coefficients $\\lambda$ each affecting one direction of the walk\n            \\item Again two variants -- success punishing and success rewarding\n            \\onslide<2->\\begin{flalign*}\n                            X_{t-1} & =1\\rightarrow p_{t}=\\lambda_{0} p_{t-1} &\n                            X_{t-1} & =-1\\rightarrow p_{t}=1-\\lambda_{1}(1-p_{t-1}) &\n            \\end{flalign*}\n            \\vspace{-5mm}\n            \\begin{itemize}\n                \\item[-->]<2-> ``Two-parameter success punishing model''\n            \\end{itemize}\n            \\onslide<3->\\begin{flalign*}\n                            X_{t-1}&=1\\rightarrow p_{t}=1-\\lambda_{0}(1-p_{t-1})&\n                            X_{t-1}&=-1\\rightarrow p_{t}=\\lambda_{1} p_{t-1}&\n            \\end{flalign*}\n            \\vspace{-5mm}\n            \\begin{itemize}\n                \\item[-->]<3-> ``Two-parameter success rewarding model''\n            \\end{itemize}\n            \\item<4-> $M$ steps, $\\lambda(t)$, $n$-dimensional walk\n        \\end{itemize}\n    \\end{frame}\n\n\n    \\section{Model application}\\label{sec:model-application}\n\n    \\begin{frame}{Model fitting}\n        \\begin{enumerate}\n            \\item Find $p_{0}$\n            \\item<2-> Find $\\lambda$ parameter(s)\n            \\item<3-> Choose optimal model type\n            \\begin{itemize}\n                \\item <4-> Akaike Information Criterion (AIC) \\& numerical optimization\n            \\end{itemize}\n        \\end{enumerate}\n    \\end{frame}\n\n    \\begin{frame}{Real life application}\n        \\begin{itemize}\n            \\item Results of tennis matches from February till May 2021 together with real life odds (both \\emph{pre-match} and \\emph{in-play}) provided by a bookmaker\n\t        \\item Data divided into training (February - April) and testing (May) datasets\n            \\item $p_{0}$ estimated using the first set winning odds provided by the bookmaker\n            \\item ``Single lambda success rewarding'' model selected as best fit using AIC and training data\n        \\end{itemize}\n    \\end{frame}\n\n    \\begin{frame}{Real life application}\n        \\begin{itemize}\n            \\item Simulated in-play betting on set winner\n            \\begin{itemize}\n                \\item<2-> Bet if $p\\geq {1.2}\\frac{1}{odds}$\n                \\item<3-> Three betting strategies tested\n                \\item<4-> ROI 98-148\\% within just one month of betting\n                \\item<5-> Only 65 bets placed\n            \\end{itemize}\n        \\end{itemize}\n    \\end{frame}\n\n    \\begin{frame}{Example - RW position}\n        \\includegraphics[width=1\\textwidth]{../../simulations/account_balance_development}\n    \\end{frame}\n\n    \\begin{frame}{Summary}\n        \\begin{itemize}\n            \\item A specific model of a random walk with memory\n            \\item Model properties derived\n            \\item Possible applications in a set of real life scenarios\n            \\item Initial results show big potential of the model\n        \\end{itemize}\n    \\end{frame}\n\n    \\begin{frame}[plain]\n        \\begin{quote}\n            \\begin{center}\n                \\huge{Thank you.}\n            \\end{center}\n            \\vspace{10mm}\n            \\begin{center}\n                \\large{tom@skourim.com}\n            \\end{center}\n        \\end{quote}\n    \\end{frame}\n\n\\end{document}\n", "meta": {"hexsha": "990f1e062eb13e4d8e9496c177ec2beff4ba6753", "size": 11132, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/presentation/Predicting Tennis Outcomes Using Random Walks.tex", "max_stars_repo_name": "tomaskourim/mathsport2021", "max_stars_repo_head_hexsha": "7760c7a676cb5300c15c15e1df178147c7470df1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paper/presentation/Predicting Tennis Outcomes Using Random Walks.tex", "max_issues_repo_name": "tomaskourim/mathsport2021", "max_issues_repo_head_hexsha": "7760c7a676cb5300c15c15e1df178147c7470df1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/presentation/Predicting Tennis Outcomes Using Random Walks.tex", "max_forks_repo_name": "tomaskourim/mathsport2021", "max_forks_repo_head_hexsha": "7760c7a676cb5300c15c15e1df178147c7470df1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8639455782, "max_line_length": 167, "alphanum_fraction": 0.5624326267, "num_tokens": 3378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.3142240456389592}}
{"text": "%!TEX root = main.tex\n\n\\section{Syntax}\n\n\\subsection*{Identifiers}\n\n$$\n\\begin{array}{@{}lrcl@{\\qquad}l}\n\\text{(identifier)} & \\x{id} &::=&\n  \\dots \\\\\n\\end{array}\n$$\n\n\n\\subsection*{Types}\n\n$$\n\\begin{array}{@{}lrcl@{\\qquad}l}\n\\text{(type)} & \\x{typ} &::=&\n  \\x{id}~\\x{typ-args}\n    & \\text{constructor} \\\\&&|&\n  \\KK{actor}^? \\K\\{~\\x{typ-fields}~\\K\\}\n    & \\text{object} \\\\&&|&\n  \\KK{var}^? \\x{typ}~\\K[~\\K]\n    & \\text{array} \\\\&&|&\n  \\x{typ}~\\K?\n    & \\text{option} \\\\&&|&\n \\KK{class}^?  \\x{typ-params} \\x{typ} \\Kto \\x{typ}\n    & \\text{function} \\\\&&|&\n  \\KK{async}~\\x{typ}\n    & \\text{future} \\\\&&|&\n  \\K(~( (\\x{id}~\\K:)^? \\x{typ})\\K,^\\ast~\\K)\n    & \\text{tuple} \\\\\n[1ex]\n\\text{(type fields)} & \\x{typ-fields} &::=&\n  \\KK{var}^? \\x{id}~\\K:~\\x{typ}\n    & \\text{field} \\\\&&|&\n  \\x{id}~\\x{typ-params}~\\x{exp-params}~\\K:~\\x{typ}\n    & \\text{function field} \\\\&&|&\n  \\x{typ-fields}~\\K;~\\x{typ-fields}\n    & \\text{composition} \\\\\n[1ex]\n\\text{(type parameters)} & \\x{typ-params} &::=&\n  (\\Klt~(\\x{id}~(\\Ksub \\x{typ})^?)\\K,^\\ast~\\Kgt)^? \\\\\n[1ex]\n\\text{(type arguments)} & \\x{typ-args} &::=&\n  (\\Klt~\\x{typ}\\K,^\\ast~\\Kgt)^? \\\\\n\\end{array}\n$$\n\n\\subsubsection*{Desugaring}\n\n$$\n\\begin{array}{@{}lrcl@{}}\n\\text{(type)} &\n\\K( \\dots \\K, \\x{id} \\K: \\x{typ} \\K, \\dots \\K) &:=&\n  \\K( \\dots \\K, \\x{typ} \\K, \\dots \\K) \\\\\n[1ex]\n\\text{(type field)} &\n\\x{id} \\x{typ-params} \\x{exp-params} \\K: \\x{typ} &:=&\n  \\x{id} \\K: \\x{typ-params} \\x{exp-params} \\Kto \\x{typ} \\\\\n[1ex]\n\\text{(type parameters)} &\n\\Klt \\dots \\K, \\x{id} \\K, \\dots \\Kgt &:=&\n  \\Klt \\dots \\K, \\x{id} \\Ksub \\K{Any} \\K, \\dots \\Kgt \\\\&\n\\epsilon &:=&\n  \\Klt \\Kgt \\\\\n\\text{(type arguments)} &\n\\epsilon &:=&\n  \\Klt \\Kgt \\\\\n\\end{array}\n$$\n\n\n\\subsection*{Expressions}\n\n$$\n\\begin{array}{@{}lrcl@{\\qquad}l}\n\\text{(literal)} & \\x{lit} &::=&\n  \\x{nat}\n    & \\text{natural number} \\\\&&|&\n  \\x{float}\n    & \\text{floating-point number} \\\\&&|&\n  \\x{char}\n    & \\text{unicode character} \\\\&&|&\n  \\x{text}\n    & \\text{unicode text string} \\\\\n[2ex]\n\\text{(unary operators)} & \\x{unop} &:=&\n  \\K{+} ~|~ \\K\\textendash ~|~ \\K{\\^{}} \\\\\n[1ex]\n%\\text{(count operators)} & \\x{cntop} &:=&\n%  \\K{++} ~|~ \\K{\\textendash\\,\\textendash} \\\\\n%[1ex]\n\\text{(binary operators)} & \\x{binop} &:=&\n  \\K{+} ~|~ \\K\\textendash ~|~ \\K{*} ~|~ \\K{/} ~|~ \\K{\\%} \\\\&&|&\n  \\K{\\&} ~|~ \\;\\K\\textbar\\; ~|~ \\K{\\^{}} ~|~ \\Klt\\Klt ~|~ \\Kgt\\Kgt ~|~ \\K{+}\\Kgt\\Kgt ~|~ \\Klt\\Klt\\Kgt ~|~ \\Klt\\Kgt\\Kgt \\\\\n[1ex]\n\\text{(relational operators)} & \\x{relop} &:=&\n  \\K= ~|~ \\K{!=} ~|~ \\Klt ~|~ \\Kgt ~|~ {\\Klt}{\\K=} ~|~ {\\Kgt}{\\K=} \\\\\n\\end{array}\n$$\n\n$$\n\\begin{array}{@{}lrcl@{\\qquad}l}\n\\text{(expression)} & \\x{exp} &::=&\n  \\x{lit}\n    & \\text{literal} \\\\&&|&\n  \\x{id}\n    & \\text{variable} \\\\&&|&\n  \\x{unop}~\\x{exp}\n    & \\text{unary operation} \\\\&&|&\n  \\x{exp}~\\x{binop}~\\x{exp}\n    & \\text{binary operation} \\\\&&|&\n  \\x{exp}~\\x{relop}~\\x{exp}\n    & \\text{relational operation} \\\\&&|&\n  \\x{exp}~\\K?\n    & \\text{option} \\\\&&|&\n  \\K(~\\x{exp}\\K,^\\ast~\\K)\n    & \\text{tuple} \\\\&&|&\n  \\x{exp}~\\K.~\\x{nat}\n    & \\text{tuple projection} \\\\&&|&\n  \\KK{actor}^? \\K\\{~\\x{exp-fields}~\\K\\}\n    & \\text{object} \\\\&&|&\n  \\x{exp}~\\K.~\\x{id}\n    & \\text{object projection} \\\\&&|&\n  \\x{exp}~\\K{:=}~\\K{exp}\n    & \\text{assignment} \\\\&&|&\n%  \\x{cntop}~\\x{exp}\n%    & \\text{count update} \\\\&&|&\n  \\x{unop}{\\!\\K=}~\\x{exp}\n    & \\text{unary update} \\\\&&|&\n  \\x{exp}~\\x{binop}{\\!\\K=}~\\x{exp}\n    & \\text{binary update} \\\\&&|&\n  \\K[~\\void{\\KK{var}^?} \\x{exp}\\K,^\\ast~\\K]\n    & \\text{array} \\\\&&|&\n  \\x{exp}~\\K[~\\x{exp}~\\K]\n    & \\text{array indexing} \\\\&&|&\n  \\x{exp}~\\x{typ-args}~\\x{exp}\n    & \\text{function call} \\\\&&|&\n  \\KK{not}~\\x{exp}\n    & \\text{negation} \\\\&&|&\n  \\x{exp}~\\KK{and}~\\x{exp}\n    & \\text{conjunction} \\\\&&|&\n  \\x{exp}~\\KK{or}~\\x{exp}\n    & \\text{disjunction} \\\\&&|&\n  \\KK{if}~\\x{exp}~\\x{exp}~(\\KK{else}~\\x{exp})^?\n    & \\text{conditional} \\\\&&|&\n  \\KK{switch}~\\x{exp}~\\K\\{~(\\KK{case}~\\x{pat}~\\x{exp})\\K;^\\ast~\\K\\}\n    & \\text{pattern match} \\\\&&|&\n  \\KK{while}~\\x{exp}~\\x{exp}\n    & \\text{guarded loop} \\\\&&|&\n  \\KK{loop}~\\x{exp}~(\\KK{while}~\\x{exp})^?\n    & \\text{unconditional loop} \\\\&&|&\n  \\KK{for}~\\K(~\\x{pat}~\\KK{in}~\\x{exp}~\\K)~\\x{exp}\n    & \\text{iteration} \\\\&&|&\n  \\KK{label}~\\x{id}~(\\K:~\\x{typ})^?~\\x{exp}\n    & \\text{label} \\\\&&|&\n  \\KK{break}~\\x{id}~\\x{exp}^?\n    & \\text{break} \\\\&&|&\n  \\KK{continue}~\\x{id}\n    & \\text{continue} \\\\&&|&\n  \\KK{return}~\\x{exp}^?\n    & \\text{return} \\\\&&|&\n  \\KK{async}~\\x{exp}\n    & \\text{future} \\\\&&|&\n  \\KK{await}~\\x{exp}\n    & \\text{future synchronisation} \\\\&&|&\n  \\KK{assert}~\\x{exp}\n    & \\text{assertion} \\\\&&|&\n  \\x{exp}~\\KK{is}~\\x{exp}\n    & \\text{instance check} \\\\&&|&\n  \\x{exp}~\\K:~\\x{typ}\n    & \\text{type annotatione} \\\\&&|&\n  \\x{exp}~\\K;~\\x{exp}\n    & \\text{sequence} \\\\&&|&\n  \\K\\{~\\x{dec}\\K;^\\ast~\\K\\}\n    & \\text{block} \\\\&&|&\n  \\x{dec}\n    & \\text{declaration} \\\\\n[1ex]\n\\text{(expression fields)} & \\x{exp-fields} &::=&\n  \\KK{private}^? \\KK{var}^? \\x{id}~(\\K:~\\x{typ})^?~\\K=~\\x{exp}\n    & \\text{field} \\\\&&|&\n  \\KK{private}^? \\x{id}~\\x{typ-params}~\\x{exp-params}~(\\K:~\\x{typ})^?~\\K=^?~\\x{exp}\n    & \\text{function field} \\\\&&|&\n  \\x{exp-fields}~\\K;~\\x{exp-fields}\n    & \\text{composition} \\\\\n[1ex]\n\\text{(expression parameters)} & \\x{exp-params} &::=&\n  \\K(~(\\x{id}~\\K:~\\x{typ})\\K,^\\ast~\\K) \\\\\n\\end{array}\n$$\n\n\\subsubsection*{Desugaring}\n\n$$\n\\begin{array}{@{}lrcl@{}}\n\\text{(expression)} &\n\\K\\{ \\K\\} &:=&\n  \\K\\{ \\K{()} \\K\\} \\\\&\n\\KK{if} \\x{exp}_1 \\x{exp}_2 &:=&\n  \\KK{if} \\x{exp}_1 \\x{exp}_2 \\K{()} \\\\&\n\\KK{loop} \\x{exp} &:=&\n  \\KK{loop} \\x{exp}_1 \\KK{while} \\; \\K{true} \\\\&\n\\KK{label} \\x{id} \\x{exp} &:=&\n  \\KK{label} \\x{id} \\K: \\x{typ} \\x{exp} \\\\&\n\\KK{label} \\x{id} \\KK{while} \\x{exp}_1 \\x{exp}_2 &:=&\n  \\KK{label} \\x{id} \\KK{while} \\x{exp}_1 (\\KK{label} \\x{id}_{\\K{continue}} \\x{exp}_2) \\\\&\n\\KK{label} \\x{id} \\KK{loop} \\x{exp}_1 \\KK{while} \\x{exp}_2 &:=&\n  \\KK{label} \\x{id} \\KK{loop} \\, (\\KK{label} \\x{id}_{\\K{continue}} \\x{exp}_1) \\, \\KK{while} \\x{exp}_2 \\\\&\n\\KK{label} \\x{id} \\KK{for} \\x{id} \\KK{in} \\x{exp}_1 \\x{exp}_2 &:=&\n  \\KK{label} \\x{id} \\KK{for} \\x{id} \\KK{in} \\x{exp}_1 (\\KK{label} \\x{id}_{\\K{continue}} \\x{exp}_2) \\\\&\n\\KK{break} \\x{id} &:=&\n  \\KK{break} \\x{id} \\K{()} \\\\&\n\\KK{continue} \\x{id} &:=&\n  \\KK{break} \\x{id}_{\\K{continue}} \\K{()} \\\\&\n\\KK{return} &:=&\n  \\KK{return} \\, \\K{()} \\\\\n\\end{array}\n$$\n$$\n\\begin{array}{@{}rcl@{}}\n\\text{(expression field)} \\hfill \\\\\n\\KK{private}^? \\KK{var}^? \\x{id} \\K: \\x{typ} \\K= \\x{exp} &:=&\n  \\KK{private}^? \\KK{var}^? \\x{id} \\K= \\x{exp} \\K: \\x{typ} \\\\\n\\KK{private}^? \\x{id} \\x{typ-params} \\x{exp-params} \\, (\\K: \\x{typ})^? \\K= \\x{exp} &:=&\n  \\KK{private}^? \\x{id} \\K= \\, \\KK{func} \\x{id} \\x{typ-params} \\x{exp-params} \\, (\\K: \\x{typ})^? \\K= \\x{exp} \\\\\n\\end{array}\n$$\n\n\n\\subsection*{Patterns}\n\n$$\n\\begin{array}{@{}lrcl@{\\qquad}l}\n\\text{(pattern)} & \\x{pat} &::=&\n  \\K\\textunderscore\n    & \\text{wildcard} \\\\&&|&\n  \\x{id}\n    & \\text{variable} \\\\&&|&\n  \\x{lit}\n    & \\text{literal} \\\\&&|&\n  \\x{unop}~\\x{lit}\n    & \\text{modified literal} \\\\&&|&\n  \\x{pat}~\\K?\n    & \\text{option} \\\\&&|&\n  \\K(~\\x{pat}\\K,^\\ast~\\K)\n    & \\text{tuple} \\\\&&|&\n  \\x{pat}~\\K:~\\x{typ}\n    & \\text{type annotation} \\\\\n\\end{array}\n$$\n\n\n\\subsection*{Declarations}\n\n$$\n\\begin{array}{@{}lrcl@{\\qquad}l}\n\\text{(declarations)} & \\x{dec} &::=&\n  \\x{exp}\n    & \\text{expression} \\\\&&|&\n  \\KK{let}~\\x{pat}~\\K=~\\x{exp}\n    & \\text{immutable} \\\\&&|&\n  \\KK{var}~\\x{id}~(\\K:~\\x{typ})^?~\\K=~\\x{exp}\n    & \\text{mutable} \\\\&&|&\n  \\KK{async}^?\\, \\KK{func}~\\x{id}^? \\x{typ-params}~\\x{exp-params}~(\\K:~\\x{typ})^?~\\K=^?~\\x{exp}\n    & \\text{function} \\\\&&|&\n  \\KK{actor}^?\\, \\KK{class}~\\x{id}^? \\x{typ-params}~\\x{exp-params}~\\K=^?~\\K\\{~\\x{exp-fields}~\\K\\}\n    & \\text{class} \\\\&&|&\n  \\KK{type}~\\x{id}~\\x{typ-params}~\\K=~\\x{typ}\n    & \\text{type} \\\\%&&|&\n%  \\x{dec}~\\K;~\\x{dec} \n%    & \\text{sequencing} \\\\\n\\end{array}\n$$\n\n\\subsubsection*{Desugaring}\n\n$$\n\\begin{array}{@{}rcl@{}}\n\\text{(declaration)} \\hfill \\\\\n\\KK{let} \\x{pat} \\K: \\x{typ} \\K= \\x{exp} &:=&\n  \\KK{let} \\x{pat} \\K= \\x{exp} \\K: \\x{typ} \\\\\n\\KK{var} \\x{id} \\K: \\x{typ} \\K= \\x{exp} &:=&\n  \\KK{var} \\x{id} \\K= \\x{exp} \\K: \\x{typ} \\\\\n\\KK{func} \\x{id}^? \\x{typ-params} \\x{exp-params} \\K= \\x{exp} &:=&\n  \\KK{func} \\x{id}^? \\x{typ-params} \\x{exp-params} \\K: \\, \\K{()} \\, \\K= \\x{exp} \\\\\n\\KK{async} \\, \\KK{func} \\x{id}^? \\x{typ-params} \\x{exp-params} (\\K: \\x{typ})^? \\K= \\x{exp} &:=&\n\\KK{func} \\x{id}^? \\x{typ-params} \\x{exp-params} \\, (\\K: \\, \\KK{async} \\x{typ})^? \\K= \\, \\KK{async} \\x{exp} \\\\\n\\end{array}\n$$\n\n\n\\subsection*{Programs}\n\n$$\n\\begin{array}{@{}lrcl@{\\qquad}l}\n\\text{(program)} & \\x{prog} &::=&\n  \\x{dec}\\K;^\\ast\n\\end{array}\n$$\n", "meta": {"hexsha": "c24fb66be6dc6ee49ea731851f9ff75bbbfc4d70", "size": 8536, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "spec/fig-syntax.tex", "max_stars_repo_name": "olaszakos/motoko", "max_stars_repo_head_hexsha": "01867bdb76d6ceb7e986297464a41146f3d34839", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 248, "max_stars_repo_stars_event_min_datetime": "2021-06-10T07:25:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T10:34:45.000Z", "max_issues_repo_path": "spec/fig-syntax.tex", "max_issues_repo_name": "pipepi/motoko", "max_issues_repo_head_hexsha": "4ff4e76645127b5dd5e0a11913d899e96e60adba", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 612, "max_issues_repo_issues_event_min_datetime": "2021-06-10T07:04:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:28:29.000Z", "max_forks_repo_path": "spec/fig-syntax.tex", "max_forks_repo_name": "pipepi/motoko", "max_forks_repo_head_hexsha": "4ff4e76645127b5dd5e0a11913d899e96e60adba", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 36, "max_forks_repo_forks_event_min_datetime": "2021-06-10T06:46:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T20:22:04.000Z", "avg_line_length": 28.1716171617, "max_line_length": 121, "alphanum_fraction": 0.4759840675, "num_tokens": 4247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.3141640248922661}}
{"text": "\\section{Introduction}\n%\\cite{SurynekFSB16}\n% Problem definition\n% The \\textit{Multi-Agent Path Finding} (MAPF) problem is defined by a graph $G = (V,E)$ and a set of $k$ agents $\\{r_1 ... r_k \\}$. Each agent $r_i$ has a start location $s_i \\in V$ and a goal location $g_i \\in V$. At each timestep the agents take an action that can \\textit{move} them to an adjacent location or \\textit{wait} in its current location. A \\textit{path} for an agent $r_i$ is a sequence of actions that take $r_i$ from $s_i$ to $g_i$. The objective is to find a \\textit{path} for each agent such that agents...\n\n\\emph{Multi-agent pathfinding (MAPF)} is the problem of finding $k$ conflict-free paths for a group of $k$ agents, each of which has the goal of reaching a goal state from a certain start location. Formally, given:\n\n\n Solving MAPF optimally for each one of the cost functions is intractable. Indeed, it is NP-complete when considering MAPF over 4-connected grids \\cite{YuL13}.\n", "meta": {"hexsha": "642c3a3e557c9d8f63fcc5b3246067a08ccb8405", "size": 969, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "aaai20/old_files/intro.tex", "max_stars_repo_name": "rkoco/lp-mapf", "max_stars_repo_head_hexsha": "8ffa93bd33feb244ac2db7230ea3b9ff2deb7038", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aaai20/old_files/intro.tex", "max_issues_repo_name": "rkoco/lp-mapf", "max_issues_repo_head_hexsha": "8ffa93bd33feb244ac2db7230ea3b9ff2deb7038", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aaai20/old_files/intro.tex", "max_forks_repo_name": "rkoco/lp-mapf", "max_forks_repo_head_hexsha": "8ffa93bd33feb244ac2db7230ea3b9ff2deb7038", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 96.9, "max_line_length": 525, "alphanum_fraction": 0.7399380805, "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6757645879592641, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.31416401882075223}}
{"text": "\\documentclass[preprint,12pt]{elsarticle}\n\\pdfoutput=1\n\\usepackage{a4wide}\n\\usepackage{amsfonts}\n\\usepackage{amssymb}\n\\usepackage{amsmath}\n\\usepackage{graphicx}\n\\usepackage{booktabs}\n\\usepackage{array}\n\\usepackage{color}\n\\usepackage{ulem}\n\\usepackage[small,bf]{caption}\n\\setlength{\\captionmargin}{\\parindent}\n\\usepackage[usenames,dvipsnames]{xcolor}\n\\usepackage{subfigure}\n\\usepackage{verbatim}\n\\usepackage{dsfont}\n\\usepackage{bbm}\n%\\usepackage[backend=bibtex8,sorting=none,natbib=false,maxbibnames=10,style=numeric-comp,block=ragged]{biblatex}\n\\usepackage{hyperref}\n\\usepackage{listings}\n\n\n\\lstdefinestyle{cpp}{\n  belowcaptionskip=1\\baselineskip,\n  breaklines=true,\n  xleftmargin=\\parindent,\n  language=C,\n  showstringspaces=false,\n  basicstyle=\\footnotesize\\ttfamily,\n  morekeywords={gauge,yukawa,self,Eigen,std,complex,class,cout,endl,using,namespace,boost,public,private,bool,template,typename},\n  keywordstyle=\\bfseries\\color{green!40!black},\n  classoffset=0,\n  commentstyle=\\itshape\\color{red!40!black},\n  identifierstyle=\\color{blue},\n  stringstyle=\\color{orange},\n}\n\n\\hypersetup{%\n  colorlinks=true, linktocpage=true, pdfstartpage=1, pdfstartview=FitV,\n  breaklinks=true, pageanchor=true,\n  pdfpagemode=UseNone,\n  plainpages=false, bookmarksnumbered, bookmarksopen=true, bookmarksopenlevel=1,\n  hypertexnames=true, pdfhighlight=/O,\n  urlcolor=RoyalBlue, linkcolor=Maroon, citecolor=RoyalBlue,\n  pdftitle={\\texttt{RGE++}},\n  pdfauthor={Thomas Deppisch and Florian Herren},\n  pdfsubject={},\n  pdfkeywords={},\n  pdfcreator={pdfLaTeX},\n  pdfproducer={LaTeX with hyperref}\n}\n\n\\newcounter{bla}\n\\newenvironment{refnummer}{%\n\\list{[\\arabic{bla}]}%\n{\\usecounter{bla}%\n \\setlength{\\itemindent}{0pt}%\n \\setlength{\\topsep}{0pt}%\n \\setlength{\\itemsep}{0pt}%\n \\setlength{\\labelsep}{2pt}%\n \\setlength{\\listparindent}{0pt}%\n \\settowidth{\\labelwidth}{[9]}%\n \\setlength{\\leftmargin}{\\labelwidth}%\n \\addtolength{\\leftmargin}{\\labelsep}%\n \\setlength{\\rightmargin}{0pt}}}\n {\\endlist}\n\n\\journal{Computer Physics Communications}\n\n\\begin{document}\n\\lstset{style=cpp}\n\n\\begin{frontmatter}\n\\title{\\vskip-3cm{\\baselineskip14pt\n    \\begin{flushleft}\n      \\normalsize TTP19-025\\\\ P3H-20-085\n  \\end{flushleft}}\n  \\vskip1.5cm\n  \\texttt{RGE++}\\\\ A \\texttt{C++} library to solve renormalisation group equations in quantum field theory}\n\n\\author[a]{Thomas Deppisch}\n\\author[b]{Florian Herren\\corref{author}}\n\n\\cortext[author] {Corresponding author.\\\\\\textit{E-mail address:} fherren@fnal.gov}\n\\address[a]{German Weather Service (DWD)\\\\ Research and Development --- Data Assimilation\\\\ Frankfurter Stra\\ss{}e 135, D-73067 Offenbach am Main, Germany}\n\\address[b]{Institut f\\\"ur Theoretische Teilchenphysik\\\\ Karlsruhe Institute of Technology (KIT)\\\\ Wolfgang-Gaede-Stra\\ss{}e 1, D-76128 Karlsruhe, Germany}\n\n\\begin{abstract}\nIn recent years three-, four- and five-loop beta functions have been computed for various phenomenologically interesting models.\nHowever, most of these results have not been implemented in easy to use software packages. \\texttt{RGE++} bridges\nthis gap by providing a flexible, template-based, \\texttt{C++} library to solve renormalisation group equations.\nFurthermore, we implement the available beta functions for the Standard Model, the minimal supersymmetric\nextension of the Standard Model and two-Higgs-doublet models, as well as right-handed neutrino extensions of the former two.\n\\end{abstract}\n\\begin{keyword}\nRenormalization group equations, quantum field theory, running coupling constants\n\\end{keyword}\n\\end{frontmatter}\n\\newpage\n{\\bf PROGRAM SUMMARY}\n  %Delete as appropriate.\n\n\\begin{small}\n\\noindent\n{\\em Program Title:} \\texttt{RGE++}                                       \\\\\n{\\em CPC Library link to program files:} (to be added by Technical Editor) \\\\\n{\\em Developer's repository link:} \\href{www.github.com/Herren/RGEpp}{www.github.com/Herren/RGEpp} \\\\\n{\\em Code Ocean capsule:} (to be added by Technical Editor)\\\\\n{\\em Licensing provisions:} MIT  \\\\\n{\\em Programming language:} \\texttt{C++}                           \\\\\n{\\em Nature of problem:}\\\\\nValues of coupling constants in dimensionally regularized quantum field theories depend on the chosen renormalization scale $\\mu$.\nThe change of coupling constants w.r.t a change of $\\mu$ is encoded in coupled first-order differential equations. \\texttt{RGE++} provides\nroutines for solving these differential equations in the Standard Model and selected models beyond it. Furthermore,\nit provides templates for the implementation of additional models.\\\\\n{\\em Solution method:}\\\\\n\\texttt{RGE++} is implemented as a set of \\texttt{C++} template classes. To numerically solve the differential equations, we employ \\texttt{Eigen3} [1] and \\texttt{odeint} [2].\nFurthermore, various additional \\texttt{C++} routines are implemented to extract physical quantities from Yukawa matrices.\\\\\n{\\em Additional comments including restrictions and unusual features:}\\\\\nFor non-physical choices of the coupling constants Landau poles might occur.\n\n\n\\begin{thebibliography}{0}\n\\bibitem{1}\nG.~Guennebaud, B.~Jacob, et~al., \\href{http://eigen.tuxfamily.org}{Eigen v3} (2010).\n\\bibitem{2}\nK.~Ahnert, M.~Mulansky, Odeint - solving ordinary differential equations in\n  c++, AIP Conference Proceedings 1389 (2011) 001.\n\\end{thebibliography}\n\\end{small}\n\n\\newpage\n\n\\setcounter{footnote}{0}\n\n\\section{Introduction}\nWhen renormalised in the modified minimal subtraction ($\\overline{\\mathrm{MS}}$) or modified dimensional reduction ($\\overline{\\mathrm{DR}}$) schemes,\nparameters and fields in quantum field theories depend on the renormalisation scale $\\mu$. The change of a parameter with respect to a change of $\\mu$\nis encoded in anomalous dimensions, or, in the case of coupling constants, the beta functions\n\\begin{align}\n\\frac{\\mathrm{d}}{\\mathrm{d}\\ln\\mu}g_i = \\beta_g\\left(\\left\\{g_j\\right\\}\\right)~,\n\\label{eq::beta}\n\\end{align}\nwhere the $g_i$ denote any dimensionless coupling of the theory under consideration and $\\left\\{g_j\\right\\}$ denotes the set of\nall couplings of the theory.\nBeta functions play a crucial role in connecting parameters at different scales, for example when comparing measurements of the\nstrong coupling constant at different energy scales at the Z-Boson mass $\\mu = M_Z$. Other applications include the study of\nGrand Unified Theories (GUTs) by extrapolating the measured couplings at low scales to the unification scale or the generation\nof supersymmetric (SUSY) spectra from high-scale input.\n\nUsually, Eq.~(\\ref{eq::beta}) is solved numerically and over the years many public programs appeared which implement\nanomalous dimensions and beta functions of various models. Most of them implement more features than the scope of \\texttt{RGE++}, but are rather specific to a certain model. \nHere we provide a short overview of programs or libraries which are relevant in the context of renormalisation group equations (RGEs):\nFor pure QCD at the highest perturbative orders available there is \\texttt{(C)RunDec} \\cite{Chetyrkin:2000yt,Schmidt:2012az,Herren:2017osy}. \\texttt{SMDR} \\cite{Martin:2019lqd} and \\texttt{mr} \\cite{Kniehl:2016enc}\nimplement running and matching relations in the full Standard Model,\nwhile REAP \\cite{Antusch:2005gp} implements beta functions in the SM, MSSM and 2HDMs including right-handed neutrinos. For supersymmetric theories there is a plethora of spectrum generators,\nwhich all implement various models, such as \\texttt{SOFTSUSY} \\cite{Allanach:2001kg}, \\texttt{SuSpect} \\cite{Djouadi:2002ze}, \\texttt{SPheno} \\cite{Porod:2003um,Porod:2011nf},\n\\texttt{Flexible SUSY} \\cite{Athron:2014yba,Athron:2017fvs}. Furthermore, there are programs implementing the general two-loop beta functions\n\\cite{Machacek:1983tz,Machacek:1983fi,Machacek:1984zw,Jack:1982hf,Jack:1982sr,Jack:1984vj} and anomalous dimensions of the dimensionful couplings \\cite{Luo:2002ti,Sartore:2020pkk}, such\nas \\texttt{SARAH} \\cite{Staub:2013tta}, \\texttt{PyR@TE} \\cite{Lyonnet:2016xiz,Sartore:2020gou} and \\texttt{ARGES} \\cite{Litim:2020jvl}\\footnote{\\texttt{PyR@TE} and \\texttt{ARGES} also implement the results for three-loop gauge coupling beta functions \\cite{Poole:2019kcm}}.\n\nThe goal of \\texttt{RGE++} is much simpler: to provide an easy to use, template-based \\texttt{C++} class library, capable of numerically solving rather generic\nRGEs, which can be used from within other programs. Furthermore, we want to provide various higher-order results, since many of\nthe aforementioned programs only implement the relevant beta functions and anomalous dimensions up to two loops. \n\nGiven recent developments\nsuch as the extraction of the gauge coupling beta function in a general quantum field theory at three loops \\cite{Poole:2019txl,Poole:2019kcm}, the computation\nof the gauge coupling beta functions in the SM at four loops \\cite{Davies:2019onf}, as well as the identification of all colour structures appearing in the four-loop\ngauge and three-loop Yukawa coupling beta functions, we can expect a plethora of new results for various models. A flexible code such as \\texttt{RGE++}\nwill be able to incorporate such new results quickly.\n\nThe remainder of this paper is structured as follows: In Section \\ref{sec::manual} we present the base classes and discuss the models implemented.\nSection \\ref{sec::examples} showcases the usage of \\texttt{RGE++} with four examples.\nA brief summary, as well as an outlook on further developments can be found in \\ref{sec::sum}.\n\n\n\\section{\\label{sec::manual}The RGE++ classes and functions}\nIn this section we discuss the functionality of \\texttt{RGE++} and its implementation. Readers who are more interested in actual examples are encouraged to skip ahead to\nSection \\ref{sec::examples} and come back to this section afterwards.\n\nFirst, in Sec.~\\ref{sec::installation}, we describe the installation and the dependencies of \\texttt{RGE++},\nfollowed by a brief overview about the implemented models in Sec.~\\ref{sec::overview}.\nThe description of the base classes all models are derived from can be found in Sec.~\\ref{sec::base}. In Sec.~\\ref{sec::models} we discuss the implementation of the various models\nand fix the conventions. We conclude with documenting auxiliary functions in Sec.~\\ref{sec::auxiliary}.\n\n\\subsection{\\label{sec::installation}Installation and usage}\nThe code can be obtained from \\url{https://github.com/Herren/RGEpp} and is structured as follows: the folders \\texttt{include} and \\texttt{src} contain the header and source files of the basic classes, respectively.\n\\texttt{models} contains the code for all implemented models, while \\texttt{examples} contains the code for various examples, including those documented in the following.\n\nTo use \\texttt{RGE++} an installation of the libraries \\texttt{Eigen3} \\cite{eigenweb} and \\texttt{odeint} \\cite{Ahnert:2011} is necessary.\n\\texttt{Eigen3} provides template-based implementations of vector and matrix classes. \\texttt{odeint} implements standard algorithms for numerically solving differential equations\nand can operate on the matrix classes provided by \\texttt{Eigen3}.\nThey can be obtained by following the instructions in the \\texttt{README} file. For building the examples, the variables \\texttt{EIGENPATH} and \\texttt{ODEINTPATH} in the \\texttt{Makefile} might need to be changed accordingly.\n\n\\subsection{\\label{sec::operation} General structure}\nThe source code of \\texttt{RGE++} is distributed over four folders:\n\\begin{itemize}\n\\item \\texttt{include}: contains header files of template and auxiliary classes\n\\item \\texttt{src}: contains source files of auxiliary classes\n\\item \\texttt{models}: contains model implementations\n\\item \\texttt{examples}: contains examples showcasing the use of \\texttt{RGE++}\n\\end{itemize}\nAll models are derived from two template classes with a flexible number of gauge and quartic couplings: \\texttt{base} and \\texttt{nubase}. The latter extends the former by additional matrices to account for neutrino Yukawa couplings\nand Majorana masses. Both template classes provide all routines and operators for solving the RGEs numerically using \\texttt{odeint}.\n\nSpecific models are derived from either of the two base classes and implement the operator\n\\begin{lstlisting}\n      void operator()(const class & X, class & dX, const double)\n\\end{lstlisting}\nThis operator is called by \\texttt{odeint} at each step of the numerical integration, writing the derivative of \\texttt{X} into \\texttt{dX}.\nThus for each model, this operator needs to implement the beta functions of the model. A more detailed discussion is given in Sec.~\\ref{sec::examples}.\n\n\\subsection{\\label{sec::overview}Overview of implemented models}\n\\texttt{RGE++} implements the SM beta functions for gauge couplings, Yukawa matrices and the scalar quartic coupling up to three loops \\cite{Machacek:1983tz,Machacek:1983fi,Machacek:1984zw,\n                               Mihaila:2012fm,Mihaila:2012pz,Bednyakov:2012rb,Chetyrkin:2012rz,Bednyakov:2012en,Bednyakov:2014pia,Herren:2017uxn,Chetyrkin:2013wya,Bednyakov:2013eba,Bednyakov:2013cpa}.\nFurthermore, the four-loop corrections to the gauge coupling beta functions \\cite{Davies:2019onf} are available\\footnote{Note that in \\cite{Davies:2019onf} only third generation Yukawa couplings are taken into account.}.\nThe non-supersymmetric extensions implemented are the SM including right-handed neutrinos at two-loop order \\cite{Machacek:1983tz,Machacek:1983fi,Machacek:1984zw, Antusch:2005gp, Grzadkowski:1987tf}, as well as\nthe $\\mathbb{Z}_2$-symmetric two-Higgs-doublet models at three-loop order for gauge coupling and Yukawa matrices and two-loop order for the quartic couplings\n\\cite{Machacek:1983tz,Machacek:1983fi,Machacek:1984zw, Herren:2017uxn, Chowdhury:2015yja}.\nThe beta functions for the minimal supersymmetric extension of the SM are implemented up to three-loop order \\cite{Martin:1993zk,Ferreira:1996ug} and its extension with right-handed (s)neutrinos at two-loop order\n\\cite{Martin:1993zk,Antusch:2005gp,Grzadkowski:1987wr}. All implemented models employ $\\mathrm{SU}(5)$ normalization for the $\\mathrm{U}(1)_\\mathrm{Y}$ gauge coupling $g_1$.\n\nA full list, including all references, can be found in Table \\ref{tbl:models}.\n\n\\begin{table}\n  \\centering\n  \\begin{tabular}{lll} \\toprule\n    file name & loop order & publications \\\\\\midrule\n    \\texttt{sm.h}  & 2 & \\cite{Ahnert:2011,eigenweb,Machacek:1983tz,Machacek:1983fi,Machacek:1984zw} \\\\\n    \\texttt{sm.h}  & 3 & \\cite{Ahnert:2011,eigenweb,Machacek:1983tz,Machacek:1983fi,Machacek:1984zw,\n                               Mihaila:2012fm,Mihaila:2012pz,Bednyakov:2012rb,Chetyrkin:2012rz,Bednyakov:2012en,Bednyakov:2014pia,Herren:2017uxn,Chetyrkin:2013wya,Bednyakov:2013eba,Bednyakov:2013cpa} \\\\\n    \\texttt{sm.h}  & 4 & \\cite{Ahnert:2011,eigenweb,Machacek:1983tz,Machacek:1983fi,Machacek:1984zw, \n                               Mihaila:2012fm,Mihaila:2012pz,Bednyakov:2012rb,Chetyrkin:2012rz,Bednyakov:2012en,Bednyakov:2014pia,Herren:2017uxn,Chetyrkin:2013wya,Bednyakov:2013eba,Bednyakov:2013cpa, Davies:2019onf} \\\\\n    \\midrule\n    \\texttt{mssm.h} & 2 & \\cite{Ahnert:2011,eigenweb,Martin:1993zk} \\\\\n    \\texttt{mssm.h} & 3 & \\cite{Ahnert:2011,eigenweb,Martin:1993zk,Ferreira:1996ug,Harlander:2009mn} \\\\\n    \\texttt{nusm.h}  & 2 & \\cite{Ahnert:2011,eigenweb,Machacek:1983tz,Machacek:1983fi,Machacek:1984zw, Antusch:2005gp, Grzadkowski:1987tf} \\\\\n    \\texttt{numssm.h} & 2 & \\cite{Ahnert:2011,eigenweb, Martin:1993zk,Antusch:2005gp,Grzadkowski:1987wr} \\\\\n    \\texttt{thdmi.h} & 3 & \\cite{Ahnert:2011,eigenweb, Machacek:1983tz,Machacek:1983fi,Machacek:1984zw, Herren:2017uxn, Chowdhury:2015yja}  \\\\\n    \\texttt{thdmii.h} & 3 & \\cite{Ahnert:2011,eigenweb, Machacek:1983tz,Machacek:1983fi,Machacek:1984zw,Herren:2017uxn, Chowdhury:2015yja}  \\\\\n    \\texttt{thdmx.h} & 3 & \\cite{Ahnert:2011,eigenweb, Machacek:1983tz,Machacek:1983fi,Machacek:1984zw,Herren:2017uxn, Chowdhury:2015yja}  \\\\\n    \\texttt{thdmy.h} & 3 & \\cite{Ahnert:2011,eigenweb, Machacek:1983tz,Machacek:1983fi,Machacek:1984zw,Herren:2017uxn, Chowdhury:2015yja}  \\\\\n    \\midrule\n    \\texttt{ckm.h} & any & \\cite{Ahnert:2011,eigenweb,Antusch:2005gp}  \\\\\n    \\texttt{pmns.h} & any & \\cite{Ahnert:2011,eigenweb,Antusch:2005gp}  \\\\\n    \\texttt{sm\\_example.cpp} & 2 & \\cite{Ahnert:2011,eigenweb,Deppisch:2018flu,Antusch:2005gp,Machacek:1983tz,Machacek:1983fi,Machacek:1984zw} \\\\\n    \\bottomrule\n  \\end{tabular}\n  \\caption{\\label{tbl:models}Relevant literature for each implemented model that should be cited together with this work when using \\texttt{RGE++} in scientific publications.}\n\\end{table}\n\n\n\\subsection{\\label{sec::base} Base classes}\n\\paragraph{eigentypes.h}\nsets the type definitions\n\\begin{lstlisting}\n  template<int n>\n  using gauge = Eigen::Matrix<double, n,1>;\n   \n  using yukawa = Eigen::Matrix<std::complex<double>, 3,3>;\n\n  template<int n>\n  using self = Eigen::Matrix<std::complex<double>, n,1>;\n\\end{lstlisting}\nwhere \\texttt{gauge} and \\texttt{self} represent $n$-dimensional vectors of gauge and quartic couplings, while \\texttt{yukawa} represents fixed-size quadratic Yukawa matrices.\nFurthermore, for each of the aforementioned types, the functions\n\\begin{lstlisting}\n  typename abs(typename);  // returns the coefficient-wise absolute values\n  bool isnotnan(typename); // checks whether a coupling is 'NaN'\n\\end{lstlisting}\nare defined, which are used internally in the routines solving the RGE numerically.\nThe types defined in this header file constitute the basic data types on which the various classes are built.\n\n\\paragraph{base.h}\ndefines the class \\texttt{base}, which serves as a base class from which all model classes with three Yukawa matrices are derived. The following model parameters are defined as \\texttt{public} members:\n\\begin{lstlisting}\n  gauge<n> g;      // vector of gauge couplings\n  self<m> La;      // Higgs self-coupling(s)\n  yukawa Yu,Yd,Ye; // Yukawa matrices\n\\end{lstlisting}\nHere \\texttt{n} and \\texttt{m} are the template parameters of \\texttt{base}, specifying the number of gauge and quartic couplings of the model, respectively.\nThe loop order for the beta functions is via the \\texttt{protected} member\n\\begin{lstlisting}\n  unsigned int nloops; // loop order of the beta functions\n\\end{lstlisting}\nIn all models derived from \\texttt{base} \\texttt{nloops} defaults to \\texttt{2}.\n\n\\texttt{base.h} defines the following member functions of \\texttt{base} as public:\n\\begin{lstlisting}\n  void setZero() // sets g, La, Yu, Yd, Ye to zero\n  bool check() // 'true' if no Landau poles appear and no member is 'NaN'\n  void setNloops(const unsigned int) // sets the value of nloops\n  unsigned int getNloops() // returns the current value nloops\n\\end{lstlisting}\nBesides, \\texttt{base} provides all vector space operations needed for the numerical integration with \\texttt{odeint}. The classes \\texttt{sm}, \\texttt{thdmi/ii/x/y}, \\texttt{mssm} are derived from \\texttt{base}.\n\n\\paragraph{nubase.h}\ndefines the class \\texttt{nubase} from which all model classes with four Yukawa matrices, the Wilson coefficient of the Weinberg operator, as well as a Majorana mass for right-handed neutrinos are derived.\nIn analogy to \\texttt{base}, it has the following model parameters as \\texttt{public} members:\n\\begin{lstlisting}\n  gauge<n> g;         // vector of gauge couplings\n  self<m> La;         // Higgs self-coupling(s)\n  yukawa Yu,Yd,Ye,Yn; // Yukawa matrices\n  yukawa Ka,Mn;       // Wilson coefficient of the Weinberg operator,\n                      // neutrino mass matrix   \n\\end{lstlisting}\nThe loop order for the beta functions is set via the \\texttt{protected} member\n\\begin{lstlisting}\n  unsigned int nloops; // loop order of the beta functions\n\\end{lstlisting}\nIn all models derived from \\texttt{nubase} \\texttt{nloops} defaults to \\texttt{2}.\nIn analogy to \\texttt{base.h}, \\texttt{nubase.h} defines the following public member functions of \\texttt{nubase}\n\\begin{lstlisting}\n  void setZero(); // sets g, La, Yu, Yd, Ye, Yn, Ka, Mn to zero\n  bool check(); // 'true' if no Landau poles appear and no member is 'NaN'\n  void setNloops(const unsigned int); // sets the value of nloops\n  unsigned int getNloops(); // returns the current value nloops\n\\end{lstlisting}\nand provides all vector space operations needed for the numerical integration with \\texttt{odeint}.\n\nFurthermore, the class \\texttt{nubase} supports the decoupling of heavy right-handed neutrino. The tree-level matching is performed as described in \\cite{Antusch:2005gp} according to\n\\begin{equation}\n    \\kappa_{ij}^{\\rm low} = \\kappa_{ij}^{\\rm high} + 2\\, \\bigl(Y_\\nu^T\\bigr)_{in} M_n^{-1} \\bigl(Y_\\nu\\bigr)_{nj} \\;,\n\\end{equation}\nin the basis where \\texttt{Mn} is diagonal. Here, $\\kappa$ corresponds to \\texttt{Ka}, the Wilson coefficient of the Weinberg operator.\nTo this end, the class \\texttt{nubase} implements the function\n\\begin{lstlisting}\n  void integrate_out(int n);\n\\end{lstlisting}\nwhich integrates out the $n^\\mathrm{th}$ generation (counting from zero) of right-handed neutrinos. \nAfterwards, the $n^\\mathrm{th}$ row of $Y_\\nu$ (counting from zero) is set to zero.\nIn addition, \n\\begin{lstlisting}\n  Eigen::Vector3d logthresholds();\n\\end{lstlisting}\nreturns the logarithm of the eigenvalues of the right-handed neutrino mass matrix, while\n\\begin{lstlisting}\n  yukawa getML(double vev);\n  yukawa getML(double vev, double tanb);\n\\end{lstlisting}\ncomputes the masses of the light neutrinos.\nThe classes \\texttt{nusm} and \\texttt{numssm} are derived from \\texttt{nubase}.\n\n\\subsection{\\label{sec::models} Implemented models}\n\\paragraph{sm.h}\nimplements the class \\texttt{sm}, which is derived as \\texttt{public} from \\texttt{base} and therefore has all members and member functions of \\texttt{base}. A \\texttt{sm} object can be constructed by\n\\begin{lstlisting}\n  sm() : base<3,1>() {};\n  \n  sm(const gauge<3> g_in, const std::complex<double> La_in,\n     const yukawa Yu_in, const yukawa Yd_in, const yukawa Ye_in,\n     const int nloops_in)\n   : base<3,1>(g_in, Yu_in, Yd_in, Ye_in, nloops_in) { La[0] = La_in; };\n   \n  sm(const gauge<3> g_in, const std::complex<double> La_in,\n     const yukawa Yu_in, const yukawa Yd_in, const yukawa Ye_in)\n   : base<3,1>(g_in, Yu_in, Yd_in, Ye_in) { La[0] = La_in; };\n   \n  sm(const base<3,1> &X) : base<3,1>(X) {};\n\\end{lstlisting}\nThe first constructor initializes the values of all couplings to $0$, whereas in the second and third version the couplings are passed as arguments. The third version sets the number of loops to $2$.\nFinally, the fourth version serves as copy-constructor.\nFurthermore, \\texttt{sm} provides the operator\n\\begin{lstlisting}\n  void operator()(const sm &X, sm &dX, const double);\n\\end{lstlisting}\nwhich is implemented in \\texttt{sm.cpp}. This operator contains the actual implementation of the beta functions and is called by the \\texttt{odeint} routines when running from one scale to another.\n\nIn the implementation of the beta functions, the `right-left-convention' for the Yukawa interactions is used\n\\begin{equation} \\label{eq:sm_yuk}\n    \\mathcal{L}_{\\mathrm{Yukawa}}^{\\mathrm{SM}} = - Y_e^{ij}\\; \\overline{e_{R}}_{i} \\, \\phi^\\dagger \\cdot L_j\n  - Y_d^{ij}\\; \\overline{d_{R}}_{i} \\, \\phi^\\dagger \\cdot Q_j\n  - Y_u^{ij}\\; \\overline{u_{R}}_{i} \\, Q_j^T \\cdot \\varepsilon \\cdot \\phi + \\mathrm{H.c.}~,\n\\end{equation}\nwhere $\\varepsilon = \\left(\\begin{smallmatrix} 0 & 1 \\\\ -1 & 0 \\end{smallmatrix}\\right)$, $\\cdot$ denotes matrix multiplication and the charge conjugated Dirac spinor is $\\psi^C = -\\mathrm{i}\\gamma^2\\gamma^0\\psi^T$. For the Higgs self-coupling $\\lambda$ we have\\footnote{Thus, $\\lambda = m_h^2/v^2$ with $v=174.14\\,\\mathrm{GeV}$.}\n\\begin{equation} \\label{eq:sm_la}\n  \\mathcal{L}_{\\mathrm{self}} = -\\frac{\\lambda}{4} (\\phi^\\dagger\\phi)^2\n\\end{equation}\n\\texttt{La} is implemented in \\texttt{base} as a vector of \\texttt{std::complex<double>}. In \\texttt{sm}, therefore, all entries but \\texttt{La[0]} are set to zero at construction.\n\n\\paragraph{thdm.h}\nimplements the classes \\texttt{thdmi}, \\texttt{thdmii}, \\texttt{thdmx} and \\texttt{thdmy}, which denote the four $\\mathbb{Z}_2$-symmetric 2HDMs.\nThey are derived as \\texttt{public} from \\texttt{base} and therefore have all members and member functions of \\texttt{base}.\nA Type-I 2HDM, for example, can be initialized by\n\\begin{lstlisting}\n  thdmi() : base() {};\n \n  thdmi(const gauge g_in, const self La_in, const yukawa Yu_in,\n        const yukawa Yd_in, const yukawa Ye_in, const int nloops_in)\n      : base(g_in, La_in, Yu_in, Yd_in, Ye_in, nloops_in) {};\n      \n  thdmi(const gauge g_in, const self La_in, const yukawa Yu_in,\n        const yukawa Yd_in, const yukawa Ye_in)\n      : base(g_in, La_in, Yu_in, Yd_in, Ye_in) {};\n      \n  thdmi(const base &X) : base(X) {};\n\\end{lstlisting}\nThe only difference w.r.t. the SM case is that the self-couplings now form a vector.\n\nLike in the SM case, we use the `right-left-convention' and take $\\phi_2$ to be the SM-like doublet. So in the Type-I 2HDM\n\\begin{equation} \\label{eq:thdm_yuk}\n    \\mathcal{L}_{\\mathrm{Yukawa}}^{\\mathrm{2HDM,I}} = - Y_e^{ij}\\; \\overline{e_{R}}_{i} \\, \\phi_2^\\dagger \\cdot L_j\n  - Y_d^{ij}\\; \\overline{d_{R}}_{i} \\, \\phi_2^\\dagger \\cdot Q_j\n  - Y_u^{ij}\\; \\overline{u_{R}}_{i} \\, Q_j^T \\cdot \\varepsilon \\cdot \\phi_2 + \\mathrm{H.c.}~.\n\\end{equation}\nTo obtain the other three types, one or two of the occurences of $\\phi_2$ in the above Lagrangian have to be exchanged for $\\phi_1$, according to Table \\ref{tbl::2hdm}.\n\n\\begin{table}\n  \\centering\n  \\begin{tabular}{cccc} \\toprule\n    Type & $u_R$ & $d_R$ & $e_R$ \\\\\\midrule\n    I & $\\phi_2$ & $\\phi_2$ & $\\phi_2$ \\\\\n    II & $\\phi_2$ & $\\phi_1$ & $\\phi_1$ \\\\\n    X & $\\phi_2$ & $\\phi_2$ & $\\phi_1$ \\\\\n    Y & $\\phi_2$ & $\\phi_1$ & $\\phi_2$ \\\\\n    \\bottomrule\n  \\end{tabular}\n  \\caption{\\label{tbl::2hdm} Couplings of the scalar doublets to right-handed fermions in the four $\\mathbb{Z}_2$-symmetric 2HDMs.}\n\\end{table}\n\nFor the quartic scalar couplings $\\lambda_i$ we have\n\\begin{equation} \\label{eq:thdm_la}\n  \\mathcal{L}_{\\mathrm{self}} = -\\frac{\\lambda_1}{2} (\\phi_1^\\dagger\\phi_1)^2 -\\frac{\\lambda_2}{2} (\\phi_2^\\dagger\\phi_2)^2 - \\lambda_3(\\phi_1^\\dagger\\phi_1)(\\phi_2^\\dagger\\phi_2) - \\lambda_4(\\phi_1^\\dagger\\phi_2)(\\phi_2^\\dagger\\phi_1)\n                                -\\left[\\frac{\\lambda_5}{2} (\\phi_1^\\dagger\\phi_2)^2 + \\mathrm{h.c.}\\right]~.\n\\end{equation}\n\\texttt{La} is implemented in \\texttt{base} as a vector of \\texttt{std::complex<double>} with 5 entries.\n\n\\paragraph{mssm.h}\nimplements the class \\texttt{mssm}, which is derived as \\texttt{public} from \\texttt{base}. A \\texttt{mssm} object can be constructed by\n\\begin{lstlisting}\n  mssm() : base<3,0>() {};\n \n  mssm(const gauge<3> g_in, const yukawa Yu_in, const yukawa Yd_in,\n       const yukawa Ye_in) : base<3,0>(g_in, Yu_in, Yd_in, Ye_in) {};\n \n  mssm(const base<3,0> &X) : base<3,0>(X) {};\n\\end{lstlisting}\nNote, that in the case of the MSSM, all quartic self-couplings of the scalars are determined by other couplings, namely gauge and Yukawa couplings.\nThus all entries of \\texttt{La} are set to zero at construction.\n\nThe Yukawa couplings are fixed by the superpotential\n\\begin{equation} \\label{eq:mssm_yuk}\n  \\mathcal{W_\\mathrm{Yukawa}}^{\\mathrm{MSSM}} = Y_e^{ij} \\; {e_R}_i\\, H_1\\cdot \\varepsilon \\cdot L_j \\quad + Y_d^{ij} \\; {d_R}_i \\, H_1\\cdot \\varepsilon \\cdot Q_j + Y_u^{ij} \\; {u_R}_i \\, \\cdot Q_j\\cdot \\varepsilon \\cdot H_2 \\;.\n\\end{equation} \n\n\\paragraph{nusm.h}\nimplements the class \\texttt{nusm} which corresponds to the SM extended by three generations of right-handed neutrinos.\n\\texttt{nusm} is derived as \\texttt{public} from \\texttt{nubase} and therefore has all members and member functions of \\texttt{nubase}. A \\texttt{nusm} object can be constructed by\n\\begin{lstlisting}\n  nusm() : nubase<3,1>() {};\n \n  nusm(const gauge<3> g_in, const std::complex<double> La_in,\n       const yukawa Yu_in, const yukawa Yd_in, const yukawa Ye_in,\n       const yukawa Yn_in, const yukawa Ka_in, const yukawa Mn_in)\n     : nubase<3,1>(g_in, Yu_in, Yd_in, Ye_in, Yn_in, Ka_in, Mn_in)\n     {La[0] = La_in;};\n  \n  nusm(const nubase<3,1> &X) : nubase<3,1>(X) {};\n\\end{lstlisting}\nThe conventions for the Yukawa couplings and self-couplings are those of eqs.~\\eqref{eq:sm_yuk} and \\eqref{eq:sm_la}.\n\nThe conventions for \\texttt{Yn, Ka, Mn} are defined through\n\\begin{equation}\\label{eq:sm_nu}\n  \\mathcal{L}_{\\kappa}^{SM} = - Y_\\nu^{ij}\\; \\overline{N}_i\\, L_j^T \\cdot \\varepsilon \\cdot \\phi -\\frac{1}{2}\\, M^{ij}\\; \\overline{N}_i N^c_j  + \\frac{\\kappa^{ij}}{4} \\bigl(\\overline{L^c}_i\\cdot \\varepsilon \\cdot \\phi \\bigr) \\bigl(L_j^T\\cdot \\varepsilon \\cdot \\phi \\bigr) + \\mathrm{H.c.} \\;.\n\\end{equation}\n\n\\paragraph{numssm.h}\nimplements the class \\texttt{numssm} which is derived as \\texttt{public} from \\texttt{nubase} and therefore has all members and member functions of \\texttt{nubase}. A \\texttt{numssm} object can be constructed by\n\\begin{lstlisting}\n  numssm() : nubase<3,0>() {};\n  \n  numssm(const gauge<3> g_in, const yukawa Yu_in, const yukawa Yd_in,\n         const yukawa Ye_in, const yukawa Yn_in, const yukawa Ka_in,\n         const yukawa Mn_in)\n       : nubase<3,0>(g_in, Yu_in, Yd_in, Ye_in, Yn_in, Ka_in, Mn_in) {};\n  \n  numssm(const nubase<3,0> &X) : nubase<3,0>(X) {};\n\\end{lstlisting}\nThe conventions for the Yukawa couplings are the same as in eq.~\\eqref{eq:mssm_yuk}.\n\nFor \\texttt{Yn, Ka, Mn} we have\n\\begin{equation} \\label{eq:mssm_nu}\n    \\mathcal{W}_{N} = \\frac{1}{2}\\, M^{ij}\\; N_i\\, N_j + Y_\\nu^{ij}\\; N_i\\, L_j \\cdot \\varepsilon^T \\cdot H_2 -\\frac{\\kappa^{ij}}{4} \\bigl(L_i\\cdot \\varepsilon \\cdot H_2\\bigr) \\bigl(L_j\\cdot \\varepsilon \\cdot H_2\\bigr)\\;.\n\\end{equation}\nAs in the MSSM, all entries of \\texttt{La} are set to zero at construction.\n\n\\subsection{\\label{sec::auxiliary} Auxiliary classes}\nIn the header files \\texttt{ckm.h} and \\texttt{pmns.h} classes to obtain fermion masses and mixing angles from Yukawa matrices are implemented. The routines are \\texttt{C++} implementations of the \\texttt{Mathematica} package \\texttt{MPT} that comes alongside \\texttt{REAP}. Both classes therefore adopt the conventions of \\texttt{MPT}. If you use one of these classes, please do not forget to cite \\cite{Antusch:2005gp}.\n\\paragraph{ckm.h}\nimplements the class \\texttt{ckm}.\nA \\texttt{ckm} object can be constructed by\n\\begin{lstlisting}\n  ckm(const yukawa Yuin, const yukawa Ydin); // sets Yu and Yd\n  ckm(const yukawa Yuin, const yukawa Ydin, const double vevin);\n      // sets Yu, Yd and the vev\n\\end{lstlisting}\nThe routines that extract the quark observables from the Yukawa matrices are called by\n\\begin{lstlisting}\n  void calculate();\n\\end{lstlisting}\nAccess to the results is given by the member functions\n\\begin{lstlisting}\n  yukawa get_CKM(); // returns the CKM matrix\n  Vector3d get_upyukawas(); // returns the central values y_u, y_c, y_t\n  Vector3d get_downyukawas(); // returns the central values y_d, y_s, y_b\n  Vector4d get_CKMparameters(); // return theta_12, theta_13, theta_23, delta_CP\n  Vector3d get_upmasses(); // returns m_u, m_c, m_t\n  Vector3d get_downmasses(); // returns m_d, m_s, m_b\n  Vector3d get_upmasses(const double tanb); // return m_u, m_c, m_t using tan(beta)\n  Vector3d get_downmasses(const double tanb); // returns m_d, m_s, m_b using tan(beta)\n\\end{lstlisting}\nThe convention for the CKM matrix is chosen such that\n\\begin{equation}\n  Y_d = \\operatorname{diag}(y_d,y_s,y_b)\\,\\cdot V_{\\mathrm{CKM}}^\\dagger\\;,\n\\end{equation}\nin the flavour basis where $Y_u$ is diagonal. The CKM parameters are defined as in the PDG \\cite{Patrignani:2016xqp}.\nThe functions \\verb|get_upmasses| and \\verb|get_downmasses| are overloaded to also support models where the down-type quarks couple to another Higgs doublet than the up-type quarks,\nsuch as the MSSM or the type-II 2HDM. To this end, the ratio between the two vacuum expectation values (vevs) of the two Higgs doublets\n\\begin{equation}\n\\tan\\beta = \\frac{v_2}{v_1}\n\\end{equation}\ncan be provided as an argument. Here $v_1$ is the vev of the doublet coupling to the down-type quarks and $v_2$ the vev of the doublet coupling to the up-type quarks.\n\n\\paragraph{pmns.h}\nimplements the class \\texttt{pmns} which can be constructed by\n\\begin{lstlisting}\n  pmns(const yukawa Min, const yukawa Yein); // sets M and Ye\n  pmns(const yukawa Min, const yukawa Yein, const double vevin);\n       // sets M, Ye and the vev\n\\end{lstlisting}\nNote that $M$ is the mass matrix of the left-handed neutrinos.\nThe routines the extract the lepton observables are called by\n\\begin{lstlisting}\n  void calculate();\n\\end{lstlisting}\nAccess to the results is given by the member functions\n\\begin{lstlisting}\n  yukawa get_PMNS(); // returns the PMNS matrix\n  Vector3d get_elyukawas(); // returns the central values y_e, y_mu, y_tau\n  Vector3d get_numasses(); // returns the light neutrino masses\n  Vector4d get_PMNSparameters(); // returns theta_12, theta_13, theta_23, delta_CP\n  Vector3d get_elmasses(); // returns m_e, m_mu, m_tau\n  Vector3d get_elmasses(const double tanb); // returns m_e, m_mu, m_tau using tan(beta)\n  double get_betadecaymass(); // returns the effective beta decay mass for neutrinos\n\\end{lstlisting}\nThe convention for the PMNS matrix is chosen such that\n\\begin{equation}\n  V_{\\mathrm{PMNS}}^T \\cdot m_\\nu \\cdot V_{\\mathrm{PMNS}}\n\\end{equation}\ndiagonalises $m_\\nu$ in the flavour basis where $Y_e$ is diagonal. The PMNS parameters are defined as in the 'standard convention' \\cite{Patrignani:2016xqp}.\n\n\\paragraph{rundown.cpp}\nThe template function\\texttt{rundown} provides routines that simplify the numerical integration of the RGEs. As it uses the \\texttt{auto} functionality, \\texttt{rundown} will not work with standards prior to \\texttt{C++11}. The numerical integration is called with\n\\begin{lstlisting}\n  rundown <Stepper, Model, Observer> (Model & state, double start,\n           double end, double error = 1e-10, double firststep = 0.01);\n\\end{lstlisting}\n\\texttt{Stepper} needs to be of \\texttt{odeint} Error Stepper type, e.g. \\texttt{runge\\_kutta\\_fehlberg78}. See the examples in Section~\\ref{sec::examples} or the \\texttt{odeint} documentation for greater detail. \\texttt{Model} refers to an \\texttt{RGE++} model (\\texttt{sm}, \\texttt{mssm}, \\texttt{tdhmi/ii/x/y}, \\texttt{nusm}, \\texttt{numssm}) and \\texttt{state} to an instantation thereof. \\texttt{Observer} is a struct or class that provides an operator of the form \\texttt{void operator()(const \\& Model, double t)} that is called at each step of the numerical integration providing access to intermediate results. A possible example is given in \\texttt{numssm\\_example.cpp}. \\texttt{Observer} can also be \\texttt{void}, if intermediate results are not necessary.\n\nThe arguments \\texttt{start} and \\texttt{end} denote the starting point $\\ln\\mu_{\\mathrm{start}}$ and end point $\\ln\\mu_{\\mathrm{end}}$ of the numerical integration. If \\texttt{start} $>$ \\texttt{end}, i.e. when going from higher to lower renormalisation scales, \\texttt{rundown} will determine the thresholds at which particles need be integrated out using the \\texttt{logthresholds()} functionality of \\texttt{Model}. At these thresholds \\texttt{rundown} will integrate out particles by using the \\texttt{integrate\\_out(int)} member function of \\texttt{Model}. If \\texttt{end} $<$ \\texttt{start}, i.e. when going towards higher renormalisation scales, no particles are integrated out.\\\\\nThe arguments \\texttt{error} and \\texttt{firststep} control the numerical error at each step of the integration and the size of the first integration step. If no value is given they default to $10^{-10}$ and $0.01$, respectively. From the second integration step onwards, the step size is adjusted by the algorithms of \\texttt{odeint} based on the value of \\texttt{error}.\n\n\\section{\\label{sec::examples}Examples and usage}\nIn the following, we discuss the basic usage of models implemented in \\texttt{RGE++} to evolve parameters from one scale to another.\n\n\n\\subsection{\\label{sec::sm_example} A SM example}\nIn \\texttt{sm\\_example.cpp} the parameters of the SM are given at the Z-Boson mass and we employ the beta functions to extrapolate them to higher energy scales. \nTo build the example call \\texttt{make sm\\_example} from the main folder. Then, the program can be called from the command line via\n\\begin{lstlisting}\n  ./examples/sm_example\n\\end{lstlisting}\nSince we have not given any additional options to the program the output should look like\n\\begin{lstlisting}[keywordstyle=\\color{blue}]\n  SM parameters at 3000 GeV and 2 loops:\n  gauge couplings: 0.47077 0.63383  1.0008\n  up-type yukawas: 6.3691e-06   0.002976    0.83158\n  down-type yukawas: 1.3614e-05 0.00025413   0.013092\n  charged lepton yukawas: 2.8666e-06 0.00060516   0.010287\n  ckm parameters:   0.22704 0.0038204  0.043031     1.143\n  Higgs quartic coupling: (0.50749,-8.5389e-59)\n\\end{lstlisting}\nThis example program also accepts other choices of the energy scale or the loop orders which should be used for running the parameters.\nThe SM parameters at, e.g., 5000 GeV using three-loop accuracy can be obtained by calling\n\\begin{lstlisting}\n  ./examples/sm_example 5000 3\n\\end{lstlisting}\n\nHaving established the general idea of the example, we are now in the position to discuss the corresponding source code.\nThe first two lines of the \\texttt{main} function parse the options given to the program via the command line. The first argument denotes the final renormalisation scale. If no argument is given it defaults to 3000 GeV. The\nsecond argument stands for the number of loops included in the beta functions. It defaults to 2 but can be chosen to be as high as 4, as the gauge coupling beta functions are implemented at this order,\n\\begin{lstlisting}\n  double scale = (argc == 2) ? atoi(argv[1]) : 3000.;\n  int nloops = (argc == 3) ? atoi(argv[2]) : 2;\n\\end{lstlisting}\nThen the initial renormalisation scale is defined at which the input parameters are given\n\\begin{lstlisting}\n  double MZ(91.1876);\n\\end{lstlisting}\nThe model parameters are \\texttt{eigen3} matrix types. The down-type Yukawa matrix $Y_d$ e.g. is initialized and defined as \\footnote{Please cite \\cite{Deppisch:2018flu} and references therein if you use these numbers.}\n\\begin{lstlisting}\n  yukawa Yd; \n  Yd << 0.0000166293, 0,0,0, 0.000310436, 0,0,0, 0.0164568;\n\\end{lstlisting}\nThe non-zero numbers are the down-, strange- and bottom-quark Yukawa couplings in the basis where the down-type Yukawa matrix is diagonal.\nFor details on how to define and manipulate  \\texttt{eigen3} matrix types see the \\texttt{eigen3} manual. In a flavour basis where $Y_u$ is diagonal, $Y_d$ takes the form\n\\begin{equation}\n    Y_d = \\operatorname{diag}(y_d,y_s,y_b) \\cdot V_{\\mathrm{CKM}}^\\dagger\\;.\n\\end{equation}\nThis rotation is performed by the line\n\\begin{lstlisting}\n  Yd = Yd*ckm(th12,th13,th23,phi).adjoint();\n\\end{lstlisting}\nNote that the function \\texttt{ckm} returns the CKM matrix in the conventions of the PDG \\cite{Patrignani:2016xqp} taking the mixing angles and the CP phase as input and is defined at the beginning of \\texttt{sm\\_example}.\n\nUsing these input parameters we can now construct the \\texttt{sm} class object \\texttt{values} which contains both the RGEs and the input parameters\n\\begin{lstlisting}\n  sm values(g, lambda, Yu, Yd, Ye, nloops);\n\\end{lstlisting}\nFor the numerical integration an \\texttt{ODEint} stepper needs to be defined \\footnote{See the \\texttt{ODEint} documentation for other steppers. In our tests all adaptive steppers performed equally well.}\n\\begin{lstlisting}\n  using namespace boost::numeric::odeint;\n  typedef runge_kutta_fehlberg78< sm, double, sm, double, vector_space_algebra > stepper;\n\\end{lstlisting}\nThe integration is then performed by\n\\begin{lstlisting}\n  int steps = integrate_adaptive(make_controlled<stepper>(1E-10, 1E-10),\n                                 sm(), values, log(MZ), log(scale), 0.01);\n\\end{lstlisting}\nThe \\texttt{sm} class object \\texttt{values} now contains the SM parameters at the renormalisation scale \\texttt{scale}. The argument \\texttt{make\\_controlled<stepper>( 1E-10 , 1E-10 )} concerns the error control\nand the last argument \\texttt{0.01} defines the size of the first step of the integration. For calculating RGEs, these are sensible values from our experience.\nNote that the beginning (\\texttt{log(MZ)}) and the end (\\texttt{log(scale)}) of the integration need to be given as logarithms since the beta functions are implemented as the logarithmic derivatives of the\nrenormalised theory parameters with respect to the renormalisation scale.\n\nTo extract the physical observables, i.e. fermion masses and their mixing angles,  from the Yukawa matrices we can use the \\texttt{ckm} and \\texttt{pmns} classes. A \\texttt{ckm} object is defined by\n\\begin{lstlisting}\n  class ckm quarks(values.Yu, values.Yd);\n\\end{lstlisting}\nand the quark masses and CKM parameters are calculated by calling\n\\begin{lstlisting}\n  quarks.calculate();\n\\end{lstlisting}\nThey can be accessed as shown in the final lines of the example\n\\begin{lstlisting}\n  std::cout << \"up-type yukawas: \"\n            << quarks.get_upyukawas().transpose() << std::endl;\n\\end{lstlisting}\n\n\n\\subsection{\\label{sec::sm_plot_example} SM example suitable for plotting}\nA further SM example is given in \\texttt{running\\_plot.cpp}. It can be built by invoking \\texttt{make running\\_plot} from the main folder.\nThe setup is similar as in the previous example, however, instead of an adaptive stepsize, it uses a constant one.\nIn this case, the integration is performed by\n\\begin{lstlisting}\n  int steps = integrate_const(stepper(), sm(), values, log(MZ),\n                              log(MGUT), 1., write_out());\n\\end{lstlisting}\nwhere the last argument of \\texttt{integrate\\_const} is a structure with an overloaded operator \\texttt{()} that gets called at each step.\nIt is implemented as\n\\begin{lstlisting}\n  struct write_out {\n    void operator()(const sm &x, double t) {\n\n      // calculate quark yukawas\n      ckm quarks(x.Yu, x.Yd);\n      quarks.calculate();\n\n      // calculate lepton yukawas\n      yukawa zero;\n      pmns leptons(zero, x.Ye);\n      leptons.calculate();\n    \n      // write to standard output\n      std::cout << exp(t) << \"   \"\n\t      << alpha(x.g[0]) << \"   \"\n      \t      << alpha(x.g[1]) << \"   \"\n      \t      << alpha(x.g[2]) << \"   \"\n\t      << alpha(quarks.get_upyukawas()[2]) << \"   \"\n\t      << alpha(quarks.get_downyukawas()[2]) << \"   \"\n\t      << alpha(leptons.get_elyukawas()[2]) << std::endl;\n    }\n  };\n\\end{lstlisting}\nand prints the $\\alpha_i = g_i^2/\\left(4\\pi\\right)$ to standard output.\n\nIn \\cite{Davies:2019onf} it was observed, that the four-loop contributions to the\nbeta function of the strong coupling, $\\beta_3$, is larger than the three-loop contributions by a factor of 1.27 for $\\mu = M_Z$. This seemingly bad perturbative convergence\nis due to an accidental cancellation in the three-loop terms \\cite{Davies:2019onf}, which is not present in the four-loop terms. Using the code of this example, this can be seen from Fig.~\\ref{plt::delta}, where the dependence of\n\\begin{align}\n\\Delta = \\frac{|\\alpha_3^{(4l)} - \\alpha_3^{(3l)}|}{|\\alpha_3^{(3l)} - \\alpha_3^{(2l)}|}\n\\end{align}\non the renormalisation scale is shown.\n\\begin{figure}\n\\centering\n\\includegraphics{delta_running.pdf}\n\\caption{\\label{plt::delta} $\\Delta$ plotted over the renormalisation scale. For energies above $10^4$~TeV, the three-loop terms have a bigger impact than the four-loop ones. Still,\nthe four-loop contributions are at least half the size of the three-loop ones for the renormalisation scales under consideration.}\n\\end{figure}\nIndeed, for renormalisation scales below $10^4$~GeV, the four-loop contributions have a larger impact than the three-loop ones. However, for larger scales,\nthe accidental cancellation in the three-loop terms is lifted and the perturbative convergence improves.\n\n\\subsection{\\label{sec::mssm_example} A SUSY GUT example}\nAnother useful application is to evolve the RGEs in the MSSM including right-handed neutrinos from a high scale down to $M_Z$, where it can be matched onto the SM. Such an example is given in the file \\texttt{numssm\\_example.cpp}.\nTo build the example call \\texttt{make numssm\\_example} from the main folder.\nLet us assume the Yukawa and gauge couplings are set by some (unrealistically oversimplified) GUT scenario, i.e.\n\\begin{equation}\ng_1 = g_2 = g_3 = 0.7, \\qquad Y_u = Y_\\nu = Y_1 + Y_2 \\qquad Y_d = Y_e = Y_1 - Y_2, \n\\label{eq::GUT}\n\\end{equation}\nwith some numerical Yukawa matrices $Y_1$ and $Y_2$ and the right-handed neutrino mass matrix $M = 10^{14}\\cdot Y_1$, which gives rise to neutrino masses but\ndoes not influence the running of the gauge couplings and Yukawa matrices. These conditions hold at $M_{GUT} = 2\\times 10^{16}\\ \\mathrm{GeV}$.\n\n\nThe code \\texttt{numssm\\_example.cpp} starts with defining the initial and final renormalisation scales\n\\begin{lstlisting}\n  double MGUT = 2.e16;\n  double MZ = 91.1876;\n\\end{lstlisting}\nThe Yukawa matrices and the gauge couplings are defined by\n\\begin{lstlisting}\n  yukawa zero, Y1, Y2;\n  gauge g;\n\n  Y1 << 1.e-4, 0., 0.,  0., 2.e-2, 0.,  0., 0., 0.4;\n  Y2 << 0., -2.e-3, 3.e-2,  -2.e-3, 0., 0.5,  3.e-2, 0., 0.5;\n  g << 0.7, 0.7, 0.7;\n\\end{lstlisting}\nUsing those input parameters, and following Eq.~(\\ref{eq::GUT}) we construct a \\texttt{numssm} object via\n\\begin{lstlisting}\n  numssm values(g, Y1 + Y2, Y1 - Y2, Y1 - Y2, Y1 + Y2, zero, Y1*1.e14); \n\\end{lstlisting}\nThe matrix \\texttt{zero} contains zeros in each entry and is used to set the Wilson coefficient of the Weinberg operator $\\kappa$ to zero at the beginning.\n \nAgain, the \\texttt{ODEint} stepper functions have to be set up for the numerical integration\n\\begin{lstlisting}\n  using namespace boost::numeric::odeint;\n  typedef runge_kutta_fehlberg78< numssm, double, numssm, double, vector_space_algebra > stepper;\n\\end{lstlisting}\nThis time, however, we will use the \\texttt{rundown} template which not only performs the integration but also determines the see-saw scale (i.e. the mass scales of the right-handed neutrinos) and integrates out the right-handed neutrinos at tree-level, when coming across these see-saw scales.\n\\begin{lstlisting}\n  rundown<stepper,numssm,void> foo(values, log(MGUT), log(MZ));\n\\end{lstlisting}\nNote, that although the name suggests otherwise, \\texttt{rundown} works `both ways', i.e. both from the high to the low as well as from the low to high renormalisation scale. Only when evolving to a lower renormalisation scale, however, it will check for thresholds and integrate out the relevant particles using the \\texttt{integrate\\_out()} routine of the respective model (\\texttt{numssm} in this case).\n  \nSince the MSSM contains two Higgs doublets, also the ratio of their respective vevs, $\\tan\\beta = v_2 / v_1$, has to be defined in order to calculate the fermion masses.\n\\begin{lstlisting}\n  double tanb(60.);\n\\end{lstlisting}\nAs before the quark masses and their mixing can be extracted from the Yukawa matrices by\n\\begin{lstlisting}\n  class ckm quarks(values.Yu, values.Yd);\n  quarks.calculate();\n\\end{lstlisting}\nIn the lepton sector we additionally need the mass matrix of the left-handed neutrinos which is calculated from the Wilson coefficient of the Weinberg operator $\\kappa$.\n\\begin{lstlisting}\n  yukawa ML = values.getML(tanb);   // left-handed neutrino mass matrix\n  class pmns leptons(ML, values.Ye);\n  leptons.calculate();\n\\end{lstlisting}\nThe results can be written to the standard output similar to\n\\begin{lstlisting}\n  std::cout << \"up-type masses (GeV): \" << quarks.get_upmasses(tanb).transpose() << std::endl;\n\\end{lstlisting}    \nThe complete output should then look like\n\\begin{lstlisting}[keywordstyle=\\color{blue}]\n  nuMSSM parameters at MZ:\n  gauge couplings: 0.45494 0.63045  1.1092\n  ckm parameters:  0.95698 0.058163 0.030761   3.1416\n  up-type masses (GeV): 0.6205 7.3594 170.36\n  down-type masses (GeV): 0.0053232   0.20148    2.2537\n  PMNS parameters:    1.5057  0.037873 0.0012002    3.1416\n  neutrino masses  (eV): 0.00037949    0.01031     3.4087\n  charged lepton massess  (GeV): 0.0025152  0.095236    1.3424\n\\end{lstlisting}    \n\n\\subsection{\\label{sec::adding} Adding additional Models}\nIn this example we outline the necessary steps for implementing additional models. As an example, we implement the RGEs for the SM with an additional singlet scalar field $s$ such that the scalar sector of the theory takes the form\n\\begin{equation} \\label{eq:nsm_la}\n  \\mathcal{L}_{\\mathrm{self}} = -\\frac{\\lambda_1}{4} (\\phi^\\dagger\\phi)^2  -\\frac{\\lambda_2}{2} (\\phi^\\dagger\\phi)\\ (s^\\dagger s)   -\\frac{\\lambda_3}{4} (s^\\dagger s)^2 ,\n\\end{equation}\nwhere additional couplings are forbidden by an ad-hoc $\\mathbb{Z}_2$ symmetry. For reference of such models see e.g. \\cite{Schabinger:2005ei,Patt:2006fw,Bowen:2007ia}.\n\nRegarding the fermion sector, this model is identical to the SM, since the singlet couples neither to quarks nor leptons. Therefore, the RGEs for the Yukawa couplings are the same as in the SM at leading order.\nThe same holds also for the gauge couplings. We only need to adapt the RGEs in the scalar sector, which can be obtained from the general results in \\cite{Machacek:1984zw,Poole:2019kcm}.\n\nLet us start this example with the header file \\texttt{nsm.h} in the \\texttt{models} folder. The class definition of the \\texttt{nsm} class is\n\\begin{lstlisting}\n  class nsm : public base<3,3> {\n  \n   public:\n    nsm() : base<3,3>() {};\n\n    nsm(const gauge<3> g_in, const std::complex<double> La1_in,\n      const std::complex<double> La2_in, const std::complex<double> La3_in,\n      const yukawa Yu_in, const yukawa Yd_in, const yukawa Ye_in)\n      : base<3,3>(g_in, Yu_in, Yd_in, Ye_in, 1)\n      { La << La1_in, La2_in, La3_in; };\n\n    nsm(const base<3,3> &X) : base<3,3>(X) {};\n \n    // contains the RGEs\n    void operator()(const nsm &X, nsm &dX, const double);\n  };\n\\end{lstlisting}\nThe first line lets the \\texttt{nsm} class inherit the properties of the \\texttt{base} class specifying the number of gauge couplings (3) and the number of scalar couplings (also 3: $\\lambda_1$, $\\lambda_2$, $\\lambda_3$).\nAfter the \\texttt{public} statement three constructors are defined. The first one, setting all couplings to 0, is inherited from \\texttt{base}.\nThe second one allows one to construct an \\texttt{nsm} object using three complex variables as input for $\\lambda_1$, $\\lambda_2$, $\\lambda_3$ in addition to the Yukawa couplings,\nwhich are then stored in the vector of self-couplings \\texttt{La}.\nIn this example, we will only consider one-loop RGEs, thus the variable (\\texttt{nloops}) is set to one.\nFor the function \\texttt{void operator()} only the type of the input parameters has been changed in comparison to \\texttt{sm.h}.\n\nAfter the class definition there is an additional piece of code copied from \\texttt{sm.h} that defines a struct that returns the modulus of the largest coupling in the model. This code does not need to be changed as long as there are no additional Yukawa couplings. In that case it should be straightforward to include theses additional couplings in the calculation of the largest coupling.\n\nNow we are ready to set up the actual RGEs in the file \\texttt{nsm.cpp}. Again, for the gauge and Yukawa couplings we can simply copy the SM ones from from \\texttt{sm.cpp}. The code that needs some further adjustments is marked with a comment reading \\texttt{NEW CODE}. The RGEs for the scalar couplings read\n\\begin{lstlisting}\n  self<3> La2 = X.La.cwiseAbs2();\n\n  dX.La[0] = loopfactor*((12.)*X.La[0]*Yd2Tr + (-24.)*Yd4Tr\n             + (4.)*X.La[0]*Ye2Tr + (-8.)*Ye4Tr + (12.)*X.La[0]*Yu2Tr\n             + (-24.)*Yu4Tr + (-9./5.)*X.La[0]*g2[0]\n             + (-9.)*X.La[0]*g2[1] + (9./5.)*g2[0]*g2[1]\n             + (27./50.)*g4[0] + (9./2.)*g4[1]\n             + 6.*La2[0] + 6.*La2[1]);\n  dX.La[1] = loopfactor*( 4.*X.La[0]*X.La[1] + 4.*X.La[1]*X.La[2] );\n  dX.La[2] = loopfactor*( 6.*La2[2] + 6.*La2[1]);\n\\end{lstlisting}\nThe first line defines a convenient abbreviation for the modulus squared of the vector self-couplings \\texttt{La}. The second assignment resembles the RGE for $\\lambda_1$. The part that stems from the interactions with the SM particles is, of course, the same as in \\texttt{sm.cpp}. But there is an additional term from diagrams where singlet scalars appear in the loops. The next two assignments contain the RGEs of $\\lambda_1$ and $\\lambda_2$. We further deleted all higher loop orders that appear in \\texttt{sm.cpp} for the sake of transparency.\n\nThe application of this model is demonstrated in the \\texttt{nsm\\_example.cpp} file which is an adapted version of \\texttt{sm\\_example.cpp}. Upon compilation and running the command line prompt should look like\n\\begin{lstlisting}[keywordstyle=\\color{blue}]\n  nSM parameters at  1000 GeV:\n  Higgs self-couplings: (0.65818637,0)  (1.0515135,0) (0.19774487,0)\n\\end{lstlisting}\nNote that the numbers are chosen arbitrarily for demonstration purposes.\n\n\\section{\\label{sec::sum}Summary and Outlook}\nWe present the \\texttt{C++} library \\texttt{RGE++} for solving RGEs in theories with multiple couplings numerically. This concerns in particular the Standard Model up to four loops, as well as\ntwo-Higgs-doublet models and the MSSM up to three loops. Furthermore, \\texttt{RGE++} supports models with right-handed neutrinos and provides routines for decoupling them from the evolution.\nWe provide three examples showcasing the usage and discuss the implemented classes in detail. The source code and further examples is available from \\url{https://github.com/Herren/RGEpp}.\nThe template-based structure gives the user the flexibility to implement higher-order corrections or new models easily.\n\n\\section*{Acknowledgements}\nWe thank Joshua Davies, Marvin Gerlach and Matthias Linster for testing the code, as well as Josha Davies, Matthias Steinhauser and Anders Eller Thomsen for careful reading of the manuscript.\nTD would like to thank Martin Spinrath and Stefan Schacht for collaboration on the project initiating the development of \\texttt{RGE++}.\nThis research was supported by the Deutsche Forschungsgemeinschaft (DFG, German Research Foundation) under grant 396021762 - TRR 257 \"Particle Physics Phenomenology after the Higgs Discovery\".\nFH acknowledges the support by the Doctoral School \"Karlsruhe School of Elementary and Astroparticle Physics: Science and Technology\".\n\\bibliographystyle{elsarticle-num}\n\\bibliography{literature}\n\\end{document}\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: t\n%%% End:\n", "meta": {"hexsha": "dcc4ecc9d18933d97cf33c467c2b337f83306f68", "size": 54520, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/documentation.tex", "max_stars_repo_name": "Herren/RGEpp", "max_stars_repo_head_hexsha": "65b23c877b94be71fb5ba8eb0b061c4fcbc844ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-01-20T11:39:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-11T04:39:54.000Z", "max_issues_repo_path": "doc/documentation.tex", "max_issues_repo_name": "Herren/RGEpp", "max_issues_repo_head_hexsha": "65b23c877b94be71fb5ba8eb0b061c4fcbc844ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/documentation.tex", "max_forks_repo_name": "Herren/RGEpp", "max_forks_repo_head_hexsha": "65b23c877b94be71fb5ba8eb0b061c4fcbc844ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-01-20T11:40:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-01T00:11:54.000Z", "avg_line_length": 63.691588785, "max_line_length": 768, "alphanum_fraction": 0.744350697, "num_tokens": 16546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.314150807917908}}
{"text": "\\documentclass[aps,prx,superscriptaddress,notitlepage,twocolumn,longbibliography]{revtex4-2}\n\n%%% linking references\n\\usepackage{hyperref}\n\\hypersetup{\n  colorlinks=true,\n  linkcolor=blue,\n  urlcolor=cyan,\n}\n\n%%% physics and math packages\n\\usepackage{physics} % general physics package\n\\usepackage{amssymb} % math fonts and symbols\n\\usepackage{bm} % for making math symbols bold\n\\usepackage{braket} % for nice brackets (e.g. |X>)\n\\usepackage{mathtools} % for \\coloneqq\n\\usepackage{graphicx} % for figures\n\\graphicspath{{./figures/}} % set path for all figures\n\n%%% shorthands to use inside math environments\n\\renewcommand{\\t}{\\text} % text in math mode\n\\newcommand{\\f}[2]{\\dfrac{#1}{#2}} % shorthand for fractions\n\\newcommand{\\p}[1]{\\left(#1\\right)} % parenthesis\n\\renewcommand{\\sp}[1]{\\left[#1\\right]} % square parenthesis\n\\renewcommand{\\set}[1]{\\left\\{#1\\right\\}} % square parenthesis\n\\renewcommand{\\c}{\\cdot} % inner product\n\\renewcommand{\\d}{\\text{d}} % integration measure, e.g. d^3 x\n\\renewcommand{\\v}{\\bm} % bold symbols (e.g. for vectors)\n\\newcommand{\\uv}[1]{\\hat{\\bm #1}} % unit vectors, or vector operators\n\\newcommand{\\bk}{\\Braket}\n\\renewcommand{\\ket}{\\Ket}\n\\renewcommand{\\bra}{\\Bra}\n\n\\newcommand{\\B}{\\mathcal{B}}\n\\newcommand{\\E}{\\mathcal{E}}\n\\newcommand{\\G}{\\mathcal{G}}\n\\newcommand{\\I}{\\mathcal{I}}\n\\newcommand{\\J}{\\mathcal{J}}\n\\renewcommand{\\L}{\\mathcal{L}}\n\\renewcommand{\\O}{\\mathcal{O}}\n\\renewcommand{\\P}{\\mathcal{P}}\n\\newcommand{\\Q}{\\mathcal{Q}}\n\\renewcommand{\\S}{\\mathcal{S}}\n\n\\newcommand{\\z}{\\text{z}}\n\\newcommand{\\x}{\\text{x}}\n\\newcommand{\\y}{\\text{y}}\n\n\\newcommand{\\up}{\\uparrow}\n\\newcommand{\\dn}{\\downarrow}\n\n%%% text for affiliations and contributions\n\\newcommand{\\JILA}{JILA, National Institute of Standards and Technology and Department of Physics, University of Colorado, Boulder, CO, 80309, USA}\n\\newcommand{\\CTQM}{Center for Theory of Quantum Matter, University of Colorado, Boulder, CO, 80309, USA}\n\\newcommand{\\contrib}{\\thanks{Authors P.H.~and M.A.P.~contributed equally to this work.}}\n\n\\begin{document}\n\n\\title{Engineering spin squeezing in a 3D optical lattice with interacting spin-orbit-coupled fermions}\n\n\\author{P.~He} \\contrib\n\\author{M.~A.~Perlin} \\contrib\n\\author{S.~R.~Muleady}\n\\author{R.~J.~Lewis-Swan}\n\\affiliation{\\JILA}\n\\affiliation{\\CTQM}\n\\author{R.~B.~Hutson}\n\\author{J.~Ye}\n\\affiliation{\\JILA}\n\\author{A.~M.~Rey}\n\\affiliation{\\JILA}\n\\affiliation{\\CTQM}\n\n\\begin{abstract}\nOne of the most important tasks in modern quantum science is to coherently control and entangle many-body systems, and to subsequently use these systems to realize powerful quantum technologies such as quantum-enhanced sensors.\nHowever, many-body entangled states are difficult to prepare and preserve since internal dynamics and external noise rapidly degrade any useful entanglement.\nHere, we introduce a protocol that counterintuitively exploits inhomogeneities, a typical source of dephasing in a many-body system, in combination with interactions to generate metrologically useful and robust many-body entangled states.\nMotivated by current limitations in state-of-the-art three-dimensional (3D) optical lattice clocks (OLCs) operating at quantum degeneracy, we use local interactions in a Hubbard model with spin-orbit coupling to achieve a spin-locking effect.\nIn addition to prolonging inter-particle spin coherence, spin-locking transforms the dephasing effect of spin-orbit coupling into a collective spin-squeezing process that can be further enhanced by applying a modulated drive.\nOur protocol is fully compatible with state-of-the-art 3D OLC interrogation schemes and may be used to improve their sensitivity, which is currently limited by the intrinsic quantum noise of independent atoms.\nWe demonstrate that even with realistic experimental imperfections, our protocol may generate $\\sim10$--$14$ dB of spin squeezing in $\\sim1$ second with $\\sim10^2$--$10^4$ atoms.\nThis capability allows OLCs to enter a new era of quantum enhanced sensing using correlated quantum states of driven non-equilibrium systems.\n\\end{abstract}\n\n% keywords: ultracold atoms, optical lattices, atomic clocks, metrology, spin squeezing\n\n\\maketitle\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Introduction}\n\nA major frontier of contemporary physics is the understanding of non-equilibrium behaviors of many-body quantum systems, and the application of these behaviors toward the development of novel quantum technologies with untapped capabilities\\cite{eisert2015quantum}.\nTo this end, ultracold atomic, molecular, and optical systems are ideal platforms for studying unexplored regimes of many-body physics due to their clean preparation and readout, high controllability, and long coherence times\\cite{bloch2008manybody, gross2017quantum}.\nThe exquisite capabilities of these systems have pushed the frontiers of metrology, quantum simulation, and quantum information science.\n\nOptical lattice clocks in particular have seen some of the most impressive developments in recent years, reaching record levels of precision ($\\sim 3\\times 10^{-19}$)\\cite{campbell2017fermidegenerate, marti2018imaging} and accuracy ($\\sim 1\\times 10^{-18}$)\\cite{bloom2014optical, mcgrew2018atomic}.\nThese advancements required important breakthroughs, including the capability to cool and trap fermionic alkaline-earth atoms in spin-insensitive potentials\\cite{takamoto2003spectroscopy, barber2006direct, ye2008quantum}; the development of ultracoherent lasers\\cite{kessler2012sub40mhzlinewidth, cole2013tenfold, matei2017mu} to fully exploit an ultranarrow clock transition\\cite{ludlow2015optical}; the detailed characterization of inter-atomic interactions\\cite{scazza2014observation, cappellini2014direct, zhang2014spectroscopic}; and, more recently, the preparation of a quantum degenerate gas in a three-dimensional (3D) optical lattice\\cite{campbell2017fermidegenerate, marti2018imaging, goban2018emergence}.\nNonetheless, all improvements in sensing capabilities to date have been based on single-particle control of internal atomic degrees of freedom.\nSuch strategies will eventually have diminishing returns due to practical difficulties in (i) suppressing decoherence from external (motional) degrees of freedom, and (ii) interrogating more particles without additional systematic errors from interactions\\cite{martin2013quantum, ludlow2015optical, marti2018imaging}.\n\nPushing beyond the current independent-particle paradigm requires leveraging many-body quantum correlations.\nEntangled states such as spin-squeezed states\\cite{kitagawa1993squeezed, wineland1992spin, ma2011quantum} can enhance measurement sensitivity, i.e.~the uncertainty $\\Delta\\theta$ in the estimation of a parameter $\\theta$, below the standard quantum limit $\\Delta\\theta\\sim1/\\sqrt{N}$ for $N$ uncorrelated particles\\cite{itano1993quantum, degen2017quantum}.\nThe major challenge for progress in this direction is that generating entanglement requires interactions, which are generally undesirable because they degrade atomic coherence, thereby limiting clock performance\\cite{swallows2011suppression, martin2013quantum, rey2014probing, ludlow2011coldcollisionshift, lemke2011wave, ludlow2015optical}.\nIn fact, the most precise and accurate optical lattice clocks were designed to operate with fermionic atoms in identical nuclear and electronic states to suppress collisional decoherence\\cite{campbell2009probing, swallows2011suppression, campbell2017fermidegenerate}, as identical fermions cannot interact via the otherwise dominant ($s$-wave) collisions at ultracold temperatures.\nHowever, an initially spin-polarized Fermi gas still exhibits interactions at later times due to spin-orbit coupling (SOC) that is induced by the laser that drives the clock transition (i.e.~the ``clock laser'')\\cite{wall2016synthetic, kolkowitz2016spinorbitcoupled, livi2016synthetic, bromley2018dynamics}.\nSpecifically, the momentum kick imparted by this laser imprints a position-dependent phase that induces inhomogeneous spin precession and generates spin dephasing, thereby making atoms distinguishable and vulnerable to collisions.\nWhile a deep lattice can suppress SOC, it also intensifies the light scattering which currently limits the coherence time of the clock\\cite{dorscher2018latticeinduced, goban2018emergence, hutson2019engineering}.\n\nIn this work, we describe a scheme that can lead to metrological advances in state-of-the-art optical lattice clocks through direct use of quantum entanglement by harnessing the interplay between nominally undesirable collisions and SOC.\nThis scheme is made possible in the weak SOC regime by the formation of an interaction-energy gap that suppresses the SOC-induced population transfer from the exchange-symmetric Dicke manifold (spanned by spin-polarized, and thus non-interacting states) to the remainder of Hilbert space.\nInteractions thereby prolong inter-particle spin coherence through a spin-locking effect, which additionally transforms the dephasing effect of SOC into a collective spin squeezing process.\nTo generate spin squeezing, our protocol only requires the capability to fix (i) the orientation of the clock laser and (ii) the optical lattice depth.\nThese controls are straightforward to incorporate into current 3D clock interrogation sequences without sacrificing atom numbers or coherence times.\nAdditionally, we show that by applying a modulated drive from the clock laser, one can further prepare states that saturate the Heisenberg limit $\\Delta\\theta\\sim1/N$ for phase sensitivity\\cite{kitagawa1993squeezed, ma2011quantum, degen2017quantum}.\nThis capability mirrors efforts in other settings, such as nitrogen-vacancy centers in diamond\\cite{bauch2018ultralong, aiello2013compositepulse} and trapped ions\\cite{burd2019quantum}, to enhance quantum metrology through the use of driven non-equilibrium phenomena.\n\nDespite an abundance of proof-of-principle experiments with entangled states\\cite{degen2017quantum, pezze2018quantum}, so far only the remarkable example of LIGO\\cite{aasi2013enhanced, abbott2016gw150914} has demonstrated a quantum advantage in a state-of-the-art quantum sensing or measurement system.\nThe new generation of 3D optical lattice systems have fully quantized motional degrees of freedom\\cite{campbell2017fermidegenerate}, allowing for precise control of collisional interactions.\nWe demonstrate how these interactions can naturally give rise to metrologically useful correlated many-body fermionic states, opening a path to not only generate entanglement, but also harness it to achieve a quantum advantage in a world-class sensor.\nSuch an advance will ultimately deliver gains to real-world applications including timekeeping, navigation, telecommunication, and our understanding of the fundamental laws of nature\\cite{safronova2018search}.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Spin squeezing with the Fermi-Hubbard model}\n\\label{sec:theory}\n\nWe consider $N$ fermionic atoms with two spin states (labeled $\\up$ and $\\dn$) trapped in a 3D optical lattice.\nIn this discussion, these spin states are associated with the two electronic states of a nuclear-spin-polarized gas.\nAt sufficiently low temperatures, atoms  occupy the lowest Bloch band of the lattice and interact only through $s$-wave collisions.\nA schematic of this system is provided in Fig.~\\ref{fig:protocol_schematic}(a), where tight confinement prevents motion along the vertical direction ($z$), effectively forming a stack of independent 2D lattices.\nFor simplicity and without loss of generality, however, we first consider the case when tunneling can only occur along one direction, $x$, and thus model the system as living in  one dimension.\n\n\\begin{figure*}\n\\centering\n\\includegraphics[width=0.6\\textwidth]{protocol_schematic.pdf}\n\\caption{{\\bf Schematic of the setup for spin squeezing}.\n({\\bf a}) We consider $N$ fermionic atoms with two (pseudo-)spin components, represented by red and blue spheres, trapped in the ground band of an optical lattice (shown in 2D for the sake of presentation).\nAtoms tunnel to neighboring sites at a rate $J$ and experience on-site interactions with strength $U$.\nAn external laser carrying a position dependent phase $e^{i\\v k_{\\t{L}}\\cdot\\v r}$ couples the spin states of the atoms.\n({\\bf b}) After a gauge transformation, different spin states exhibit different dispersion relations with a relative phase $\\phi=k_{\\text{L}} a$, where $a$ is the lattice spacing.\nThe external laser couples spin states with identical quasi-momenta $q$ in the gauge-transformed frame.\n({\\bf c}) If interactions are sufficiently weak, all motional degrees of freedom become frozen in momentum space, with atoms effectively pinned to fixed quasi-momentum modes $\\v q$.\nThe dynamics on the frozen $\\v q$-space lattice can then be mapped to a spin model in which collisional interactions correspond to a uniform, all-to-all ferromagnetic Heisenberg Hamiltonian with strength $U/L$, where $L$ is the total number of lattice sites.\n({\\bf d}) The spin dependence of the dispersion relation is captured by a mode-dependent axial field $B_q$ that generates inhomogeneous spin precession.\nThis axial field couples exchange-symmetric many-body Dicke states with total spin $S=N/2$ to spin-wave states with $S=N/2-1$.\nThe all-to-all interaction opens an energy gap $fU$ (with $f=N/L$ the filling fraction of spatial modes) between the Dicke states and the spin-wave states, which forbids population transfer between them in the weak-field limit.\n({\\bf e}) To generate spin squeezing via one-axis twisting, we initialize a product state with all spins polarized in $-z$ (i.e.~in $\\ket{\\dn}$), and apply a fast external laser pulse to rotate all spins into $x$.\nWe then let atoms freely evolve for a variable time $t$ (with a spin-echo pulse), after which the amount of spin squeezing can be determined experimentally from global spin measurements.\nThe spin-squeezed state can be used for a follow-up clock interrogation protocol (see Appendix \\ref{sec:clock_interrogation}).\n}\n\\label{fig:protocol_schematic}\n\\end{figure*}\n\nAn external laser with Rabi frequency $\\Omega$ and wavenumber $k_{\\t{L}}$ along the tunneling axis resonantly couples atoms' internal states through the Hamiltonian $\\hat H_{\\t{laser}}/\\hbar = \\sum_j \\Omega e^{ik_{\\t{L}}x_j} \\hat c_{j,\\up}^\\dag \\hat c_{j,\\dn} + \\t{h.c.}$, where $\\hat c_{j\\alpha}$ is a fermionic annihilation operator for an atom on site $j$ with internal state $\\alpha\\in\\set{\\up,\\dn}$ and $x_j$ is the position of site $j$.\nThis laser imprints a position-dependent phase that equates to a momentum kick $k_{\\t{L}}$ when an atom changes internal states by absorbing or emitting a photon, thereby generating spin-orbit coupling\\cite{wall2016synthetic, livi2016synthetic}.\nAfter absorbing the position dependence of the laser Hamiltonian into fermionic operators through the gauge transformation $\\hat c_{j,\\up}\\to e^{ik_{\\t{L}} x_j}\\hat c_{j,\\up}$, which makes $\\hat H_{\\t{laser}}$ spatially homogeneous, the atoms are well-described in the tight-binding limit by the Fermi-Hubbard Hamiltonian\\cite{esslinger2010fermihubbard}\n\\begin{align}\n  \\hat H_{\\t{FH}}^{(\\phi)}/\\hbar\n  &= -J \\sum_j \\p{e^{i\\phi} \\hat c_{j,\\up}^\\dag \\hat c_{j+1,\\up}\n  + \\hat c_{j,\\dn}^\\dag \\hat c_{j+1,\\dn} + \\text{h.c.}} \\notag \\\\\n  &\\qquad + U \\sum_j \\hat n_{j,\\up} \\hat n_{j,\\dn},\n\\end{align}\nwhere $J$ is the nearest-neighbor tunneling rate; the SOC angle $\\phi\\equiv k_{\\t{L}}a$ determines the phase gained by spin-up atoms upon tunneling from site $j$ to site $j+1$ (in the gauge-transformed frame) with lattice spacing $a=x_{j+1}-x_j$; $U$ is the on-site interaction energy of two atoms; and $\\hat n_{j\\alpha}\\equiv\\hat c_{j\\alpha}^\\dag \\hat c_{j\\alpha}$ is a number operator.\n\nThe Fermi-Hubbard Hamiltonian can be re-written in the quasi-momentum basis with annihiliation operators $\\hat c_{q\\alpha}\\equiv L^{-1/2}\\sum_j e^{-iqx_j}\\hat c_{j\\alpha}$, where $q$ is a quasi-momentum and $L$ is the total number of lattice sites.\nIn this basis, the single-particle Hamiltonian exhibits shifted dispersion relations that signify spin-orbit coupling [see Fig.~\\ref{fig:protocol_schematic}(b)]:\n\\begin{align}\n  \\hat H_{\\t{FH,single}}^{(\\phi)}/\\hbar\n  = -2J\\sum_q\\sp{\\cos(qa + \\phi) \\hat n_{q,\\up}\n  + \\cos(qa) \\hat n_{q,\\dn}}.\n\\label{eq:FermiHubbard}\n\\end{align}\nWhen $U\\lesssim J$, interaction energies are too weak for collisions to change the occupancies of single-particle quasi-momentum modes.\nAtoms are then pinned to these modes, which form a lattice in quasi-momentum space [see Fig.~\\ref{fig:protocol_schematic}(c)]\\cite{bromley2018dynamics}.\nIn this strong-tunneling limit, the Fermi-Hubbard Hamiltonian [Eqn.~\\eqref{eq:FermiHubbard}] can be mapped to a spin-$1/2$ system with a collective ferromagnetic Heisenberg interaction and an inhomogeneous axial field, given by\\cite{martin2013quantum,rey2014probing, bromley2018dynamics}\n\\begin{align}\n  \\hat H_{\\t{spin}}/\\hbar\n  = -\\frac{U}{L} \\hat{\\v S} \\c \\hat{\\v S}\n  - \\sum_q B_q \\hat s_q^\\z,\n\\label{eq:SpinModel}\n\\end{align}\nwhere $\\hat{\\v S}=\\sum_q\\hat{\\v s}_q$ is a collective spin operator; $\\hat{\\v s}_q$ is a spin-1/2 operator for mode $q$ with components $\\hat{s}_q^{j=\\x,\\y,\\z}\\equiv\\frac12\\sum_{\\alpha,\\beta}\\hat c_{q\\alpha}^\\dag\\sigma^j_{\\alpha\\beta}\\hat c_{q\\beta}$ defined in terms of the Pauli matrices $\\sigma^{j=\\x,\\y,\\z}$; the sums over $q$ run over all occupied quasi-momentum modes; and $B_q \\equiv -4J\\sin(qa+\\phi/2)\\sin(\\phi/2)$ is the SOC-induced axial field.\n\nOn its own, the collective Heisenberg term ($\\sim\\hat{\\v S}\\c\\hat{\\v S}$) in Eqn.~\\eqref{eq:SpinModel} opens an energy gap $fU$, with $f\\equiv N/L$ the filling fraction of spatial modes, between the collective Dicke states $\\ket{S=N/2, M_S}$ and the remainder of Hilbert space\\cite{rey2008manybody, martin2013quantum, norcia2018cavitymediated, smale2019observation} with $S<N/2$.\nHere $S$ and $M_S$ respectively label the eigenvalues of the collective spin operators $\\hat{\\v S}\\c\\hat{\\v S}$ and $\\hat{S}_\\z$, with eigenvalues $S(S+1)$ for non-negative $S\\in\\set{N/2,N/2-1,\\cdots}$ and $M_S\\in\\set{-S,-S+1,\\cdots,S}$.\nThe axial field $B_q$ generally couples states within the Dicke manifold to states outside it.\nIn the weak SOC limit (i.e.~$B_q\\ll fU$), however, the interaction energy gap suppresses population transfer between states with different total spin $S$ [see Fig.~\\ref{fig:protocol_schematic}(d)].\nIn this regime, the virtual occupation of states outside the Dicke manifold can be accounted for perturbatively.\nThe symmetries of SOC as expressed in Eqn.~\\eqref{eq:SpinModel} dictate that this treatment should yield powers of $\\hat S_\\z$ when projected onto the collective Dicke manifold at higher orders in perturbation theory.\nAt second order in perturbation theory (see Appendix \\ref{sec:derivation_OAT}), we thus find that SOC effectively yields a one-axis twisting (OAT) model widely known to generate squeezing dynamics\\cite{kitagawa1993squeezed, ma2011quantum}:\n\\begin{align}\n  \\hat H_{\\t{eff}}/\\hbar\n  = -\\frac{U}{L} \\hat{\\v S} \\c \\hat{\\v S}\n  - \\overline B \\hat S_\\z + \\chi \\hat S_\\z^2,\n  &&\n  \\chi \\equiv \\f{\\widetilde B^2}{(N-1)fU},\n  \\label{eq:H_eff}\n\\end{align}\nwhere $\\overline B\\equiv\\sum_q B_q/N$ is the mean and $\\widetilde B^2\\equiv\\sum_q\\p{B_q-\\overline B}^2/N$ the variance of the axial field.\nThe effect of the $\\sim\\hat{\\v S}\\c\\hat{\\v S}$ term is to generate a relative phase between states with different total spin $S$ and thus has no effect on dynamics  restricted to a fixed $S$.\nNote also that  the collective spin rotation from $\\overline B \\hat S_\\z$  can be eliminated by going into a rotating frame or by using a spin echo.\n\nThe entire protocol for preparing a squeezed state via OAT, sketched out in Fig.~\\ref{fig:protocol_schematic}(e), reduces to a standard Ramsey protocol with a spin echo: after initially preparing a spin-down (i.e.~$-\\uv z$) polarized sample of ultracold atoms populating the lowest Bloch band of a lattice, a fast $\\pi/2$ pulse is applied with the clock laser to rotate all spin vectors into $+\\uv x$.\nThe atoms then freely evolve for a variable time $t$ (possibly with spin-echo $\\pi$-pulses), after which the amount of metrologically useful spin squeezing, measured by the Ramsey squeezing parameter\n\\begin{align}\n  \\xi^2 \\equiv\n  \\min_\\theta \\braket{\\t{var}(\\hat S^\\perp_\\theta)}\n  \\times N/\\abs*{\\braket{\\hat{\\v S}}}^2,\n  \\label{eq:sqz}\n\\end{align}\ncan be determined experimentally from global spin measurements.\nHere $\\braket{\\hat{\\v S}}$ is the mean collective spin vector and $\\braket{\\t{var}(\\hat S^\\perp_\\theta)}$ is the variance of spin measurements along an axis orthogonal to $\\braket{\\hat{\\v S}}$, parameterized by the angle $\\theta\\in[0,2\\pi)$.\n\nThe above protocol concerns only the preparation of a spin-squeezed state, which would then be used as an input state for a follow-up clock interrogation protocol without SOC.\nWhile increasing the lattice depth to turn off SOC during clock interrogation is the simplest approach, this will limit the interrogation time due to light scattering (see discussion below).\nAlternatively, it is possible to keep the same lattice depth used for the spin squeezing generation by adding a specific pulse sequence to suppress SOC.\nSee details in Appendix \\ref{sec:clock_interrogation}.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Model validity}\n\\label{sec:validity}\n\nThe validity of the OAT model in Eqn.~\\eqref{eq:H_eff} relies on two key conditions concerning experimental parameter regimes.\nFirst, the on-site interaction energy $U$ should not be much larger in magnitude than the tunneling rate $J$ (clarified below); otherwise, one cannot assume frozen motional degrees of freedom (i.e.~with atoms pinned to fixed quasi-momentum modes) and map the Fermi-Hubbard model to a spin model.\nSecond, the SOC-induced fields $B_q\\sim J\\sin(\\phi/2)$ should be considerably smaller in magnitude than the interaction energy gap $fU$, as otherwise one cannot perturbatively transform SOC into OAT.\nThese two conditions can be satisfied by appropriate choices of $U/J$ and the SOC angle $\\phi$, which are respectively controlled by tuning the lattice depth and changing the angle between the clock laser and the lattice axes [see Fig.~\\ref{fig:protocol_schematic}(a)].\n\n\\begin{figure*}\n\\centering\n\\includegraphics[width=0.8\\textwidth]{model_benchmarking.pdf}\n\\caption{{\\bf Benchmarking the spin and one-axis twisting models}.\nComparisons of maximum squeezing (top panels, {\\bf a.i} and {\\bf b.i}) and optimal squeezing time (lower panels, {\\bf a.ii} and {\\bf b.ii}) between the Fermi-Hubbard (FH), spin, and one-axis twisting (OAT) models; obtained numerically via the protocol depicted in Fig.~\\ref{fig:protocol_schematic}(e) in a 1D lattice with $L=12$ sites.\nResults are shown for half filling with $N=12,f\\equiv N/L=1$ (left panels, {\\bf a.i} and {\\bf a.ii}) and filling $f=5/6$ (right panels, {\\bf b.i} and {\\bf b.ii}) as a function of $U/J$ and the SOC angle $\\phi$.\nIn both cases, the system is initialized in the corresponding ground state.\nInsets for both $f=1$ and $f=5/6$ show (in green) regions of the $U$-$\\phi$ plane in which both the optimal squeezing (in dB) and the corresponding squeezing time of all three models agree to within 20\\%.\nAt half filling ({\\bf a.i} and {\\bf a.ii}), mode-changing collisions are suppressed by Pauli blocking, resulting in almost exact agreement between the FH and spin models; both of these models converge onto the OAT model in the gap-protected, weak SOC regime of large $U/J$ and small $\\phi$.\nThe spin and OAT models show similar behavior away from half filling ({\\bf b.i} and {\\bf b.ii}), but the presence of mode-changing collisions results in their disagreement with the FH model as interactions begin to dominate at larger $U/J$.\nEven below half filling, however, the FH exhibits comparable amounts of squeezing to the spin model across a broad range of $U/J$ and $\\phi$, albeit at earlier times when $U/J\\gtrsim2$.\n}\n\\label{fig:model_benchmarking}\n\\end{figure*}\n\nWe demonstrate the importance of these conditions in Fig.~\\ref{fig:model_benchmarking}, where we show numerical results from exact simulations of a 1D system with $L=12$ sites.\nTherein, optimal squeezing achievable under unitary dynamics is provided in dB, i.e.~$-10\\log_{10}(\\xi_{\\t{opt}}^2)$, while the time at which this squeezing occurs is provided in units of the nearest-neighbor tunneling time $2\\pi/J$.\nAt $f=1$ atom per lattice site, i.e.~half filling of all atomic states in the lowest Bloch band, the spin model [Eqn.~\\eqref{eq:SpinModel}] agrees almost exactly with the Fermi-Hubbard (FH) model [Eqn.~\\eqref{eq:FermiHubbard}] up through (and exceeding) $U/J=8$. The agreement at half filling ($f=1$) is assisted by Pauli blocking of mode-changing collisions.\nBelow half filling ($f=5/6$), these two (FH and spin) models show good agreement at $U/J\\lesssim2$, while at $U/J\\gtrsim2$ mode-changing collisions start to become relevant and invalidate the frozen-mode assumption of the spin model.\nNote that we chose filling $f=5/6$ to demonstrate that our protocol should work, albeit sub-optimally, even in this highly hole-doped case; in practice, optimized experiments are capable of achieving fillings closer to the optimal $f=1$\\cite{brown2017spinimbalance}.\nInterestingly, even with mode-changing collisions the Fermi-Hubbard model exhibits comparable amounts of squeezing to the spin model, and achieves this squeezing in less time.\nThe spin and OAT models agree in the regime of weak SOC with $\\widetilde{B}\\sim J\\sin(\\phi/2)\\ll fU$, and exhibit different squeezing behaviors outside this regime as single-particle spin dephasing can no longer be treated as a weak perturbation to the spin-locking  interactions.\n\nIn realistic implementations, the Gaussian profile of the laser beams always introduces an additional effective harmonic potential that modifies the translational invariance assumed so far.\nWe present a detailed discussion of the role of the harmonic trap in Appendix \\ref{sec:harmonic_trap}, where we demonstrate that the addition of harmonic confinement barely modifies the achievable spin squeezing with currently accessible trapping frequencies.\nWe find that the existence of single-particle localized modes in the lattice with harmonic confinement\\cite{rey2005ultracold, pupillo2006extended} helps to protect spin squeezing and shifts the optimal parameter window to $U/J\\gtrsim 2$.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Two-axis twisting}\n\\label{sec:TAT}\n\nThe above scheme for OAT achieves optimal spin squeezing that scales as $\\xi^2_{\\t{opt}}\\sim N^{-2/3}$ with minimal intervention, i.e.~a standard Ramsey protocol.\nFurther improvements upon this scheme can be made by introducing a time-dependent driving field that transforms the OAT Hamiltonian into a two-axis twisting (TAT) one.\nWhile the OAT model initially generates squeezing faster than the TAT model, the squeezing generation rate of OAT (measured in dB per second) falls off with time, while the squeezing generation rate for TAT remains approximately constant until reaching Heisenberg-limited amount of spin squeezing with $\\xi^2_{\\t{opt}}\\sim N^{-1}$\\cite{kitagawa1993squeezed}.\n\nThere are two general strategies for converting OAT into TAT: by use of either a pulsed\\cite{liu2011spin} or continuous\\cite{huang2015twoaxis} drive protocol.\nFor simplicity, we consider the latter in this  work, although the pulsed protocol could provide additional advantages, as explained at the end of Appendix \\ref{sec:clock_interrogation}.\nFollowing the prescription in Ref.~[\\citenum{huang2015twoaxis}], we use the clock laser to apply an amplitude-modulated drive $\\hat H_{\\t{drive}}(t)/\\hbar=\\Omega_0\\cos(\\omega t)\\hat{S}_\\x$.\nIf the modulation frequency $\\omega$ satisfies $\\omega\\gg N\\chi$ and $\\J_0\\p{2\\Omega_0/\\omega}=\\pm1/3$, where $\\chi$ is the OAT squeezing strength in Eqn.~\\eqref{eq:H_eff} and $\\J_0$ is the zero-order Bessel function of the first kind, then up to (i) an $\\sim\\hat{\\v S}\\c\\hat{\\v S}$ term that contributes only overall phase factors, and (ii) an $\\sim\\hat S_\\z$ term that can be eliminated with a simple dynamical decoupling pulse sequence (see Appendix \\ref{sec:dynamical_decoupling}), the effective Hamiltonian becomes $\\hat H_{\\t{TAT}}^{(+)}/\\hbar = (\\chi/3)(\\hat S_\\z^2-\\hat S_\\x^2)$ or $\\hat H_{\\t{TAT}}^{(-)}/\\hbar = (\\chi/3)(\\hat S_\\y^2-\\hat S_\\x^2)$ (see Appendix \\ref{sec:derivation_TAT}), which squeezes an initial state polarized along the $y$ or $z$ axis, respectively.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Experimental implementation and practical considerations}\n\nThus far, we have largely considered the general preparation of spin-squeezed states with the Fermi-Hubbard model.\nHere, we discuss the specific implementation of the above protocols in the state-of-the-art 3D $^{87}$Sr optical lattice clock (OLC).\nIf successful, such an implementation would (to our knowledge) for the first time break through the proof-of-principle stage of spin squeezing efforts, and achieve a genuine metrological enhancement of a world-class quantum sensor.\n\nAs required for our protocol, 3D $^{87}$Sr OLC has demonstrated the capability to load a quantum degenerate gas into a 3D lattice at the ``magic wavelength'' ($\\lambda_{\\t{lattice}}=2a\\approx813$ nm) for which both the ground ($^1S_0,\\dn$) and first excited ($^3P_0,\\up$) electronic states (i.e.~the ``clock states'') of the atoms experience the same optical potential\\cite{campbell2017fermidegenerate}.\nFurthermore, the 3D $^{87}$Sr OLC currently operates at sufficiently low temperatures to ensure vanishing population above the lowest Bloch band, such that its dynamics are governed by the Fermi-Hubbard Hamiltonian [Eqn.~\\eqref{eq:FermiHubbard}]\\cite{esslinger2010fermihubbard}.\n\nAn external clock laser with wavelength $\\lambda_{\\t{L}}\\approx698$ nm resonantly interrogates the $^1S_0$ and $^3P_0$ states of the atoms and generates spin-orbit coupling (SOC)\\cite{wall2016synthetic}.\nWhile the relative wavelengths of the lattice and clock lasers do not allow for weak SOC along all three lattice axes, weak SOC along two axes can be implemented by, for example, (i) fixing a large lattice depth along the $z$ axis, effectively freezing atomic motion along  $z$, and then (ii) making the clock laser nearly collinear with the $z$ axis, with only a small projection of its wavenumber $\\v k_{\\t{L}}$ onto the $x$-$y$ plane [see Figure \\ref{fig:protocol_schematic}(a)].\nThe entire 3D OLC then factorizes into an array of independent 2D systems with $N=f\\ell^2$ atoms each, where $\\ell$ is the number of lattice sites along each axis of the lattice.\nAs in the 1D case, atoms within the 2D system experience all-to-all interactions, as well as spin-orbit coupling along two directions characterized by SOC angles $\\phi_{\\x,\\y}=k_{\\t{L}}^{\\x,\\y}a$.\nGenerally speaking, higher-dimensional systems (e.g.~2D vs.~1D) are more desirable because they allow packing more interacting atoms into a fixed system volume, thereby increasing the maximally attainable amount of spin squeezing.\n\n\\begin{figure*}\n\\centering\n\\includegraphics{optima_coherent.pdf}\n\\caption{{\\bf Optimal squeezing} with one- and two-axis twisting in a 2D section of the 3D $^{87}$Sr optical lattice clock.\n({\\bf a}) The maximum amount of squeezing depends only on the atom number $N=\\ell^2$, where $\\ell$ is the number of lattice sites along each axis of the lattice.\nWhile the time scales for squeezing generally depend on several experimental parameters, the time at which maximal squeezing occurs can be minimized at any given lattice depth $V_0$ by choosing SOC angles $\\phi$ that saturate $\\widetilde{B}/U\\approx0.05$, where $\\widetilde{B}$ is the variance of the SOC-induced axial field and $U$ is the two-atom on-site interaction energy.\nPanels ({\\bf b}, {\\bf c}) show these minimal squeezing times as a function of the depth $V_0$ and linear size $\\ell$ of the lattice.\nLattice depths $V_0$ are normalized to the atomic lattice recoil energy $E_{\\t{R}}$, and the upper axis on panels ({\\bf b}, {\\bf c}) marks values of  $U/J$ at fixed lattice depths.\nIn general, TAT achieves more squeezing than OAT for any system size, and achieves optimal squeezing faster for $N\\gtrsim400$ atoms, as denoted by a dotted line in panels ({\\bf b}, {\\bf c}).\n}\n\\label{fig:optima_coherent}\n\\end{figure*}\n\nFigure \\ref{fig:optima_coherent} shows, for both OAT and TAT protocols, the maximally attainable amount of spin squeezing and the shortest time at which it occurs as a function of the lattice depth $V_0$ and linear lattice size $\\ell$ in a single half-filled 2D layer (i.e.~$f=1,N=\\ell^2$) of the 3D OLC.\nAtoms are confined along the direction transverse to the 2D layer by a lattice of depth 60 $E_{\\t{R}}$, where $E_{\\t{R}}$ is the atomic lattice recoil energy.\nThe maximally attainable amount of spin squeezing by each protocol in Fig.~\\ref{fig:optima_coherent} depends only on the atom number $N$, while the shortest attainable time is determined by choosing the largest SOC angles $\\phi_\\x=\\phi_\\y\\equiv\\phi$ which saturate $\\widetilde{B}/U\\approx0.05$.\nWe impose this constraint on $\\widetilde{B}/U$ to ensure validity of the OAT Hamiltonian perturbatively derived in Appendix \\ref{sec:derivation_OAT} (see also Appendix \\ref{sec:benchmarking}).\n\n\\begin{figure*}\n\\centering\n\\includegraphics{optima_decoherence.pdf}\n\\caption{{\\bf Optimal squeezing with decoherence} via one- and two-axis twisting in a 2D section of the 3D $^{87}$Sr optical lattice clock (OLC).\nIn practice, decoherence due to light scattering limits the amount of squeezing that is attainable in the the 3D $^{87}$Sr OLC.\nDue to growing squeezing times with increasing system size, the maximal squeezing obtainable via OAT saturates past $\\ell\\approx30$ sites along each axis of the lattice, with $N\\approx10^3$ atoms total.\nThe more favorable size-dependence of TAT time scales,  however, allow for continued squeezing gains through $\\ell=100$ ($N=10^4$).\nWhile the OAT results in ({\\bf a}) are exact, the TAT results in ({\\bf b}) reflect only a lower bound on the maximum squeezing obtainable, albeit one that is likely close (within a few dB) to the actual value.\nOptimal squeezing times in the presence of decoherence are generally smaller than the corresponding times shown in Fig.~\\ref{fig:optima_coherent}, as decoherence typically degrades squeezing before it reaches the decoherence-free maximum.\nThe decoherence considered in this work also limits maximally achievable squeezing to $\\sim20$ dB less than the decoherence-free maxima shown in Fig.~\\ref{fig:optima_coherent}.\nSample plots of squeezing over time for particular choices of lattice size ($\\ell$) and depth ($V_0/E_{\\t{R}}$) are provided in Appendix \\ref{sec:time_series}.\n}\n\\label{fig:optima_decoherence}\n\\end{figure*}\n\nCurrently, light scattering from the lattice beams induces decoherence of the clock on a time scale of $\\sim10$ seconds\\cite{goban2018emergence, hutson2019engineering}, which is much shorter than the natural $^3P_0$ lifetime of $\\sim160$ seconds (see Appendix \\ref{sec:decoherence}).\nThis limitation imposes significant constraints on achievable spin squeezing, as shown in Figure \\ref{fig:optima_decoherence} where the maximal squeezing with spin decay in the OAT case was determined using exact expressions for spin correlators derived in Ref.~[\\citenum{foss-feig2013nonequilibrium}], while in the TAT case these correlators were determined by solving Heisenberg equations of motion for collective spin operators\\cite{perlin2019shorttime} (see Appendix \\ref{sec:collective_simulation}).\nDue to the fast growth of Heisenberg operators in systems with all-to-all interactions, the latter method is not always capable of simulating up to the optimal squeezing time, and thus only provides a lower bound on the maximal squeezing theoretically obtainable via TAT.\n\nThe results in Fig.~\\ref{fig:optima_decoherence} show that squeezing via OAT saturates with system size around $N\\approx10^3$ ($\\ell\\approx30$), while TAT allows for continued squeezing gains through $N=10^4$ ($\\ell=100$).\nEven with decoherence, our protocol may realistically generate $\\sim10$--$14$ dB of spin squeezing in $\\sim1$ second with $\\sim10^2$--$10^4$ atoms in a 2D section of the lattice, which is compatible with the atom numbers and interrogation times of state-of-the-art optical lattice clocks\\cite{campbell2017fermidegenerate, marti2018imaging}.\nThis amount of spin squeezing exceeds those reported in the ground-state nuclear spin sublevels of a state-of-the-art ${}^{171}$Yb OLC ($\\sim6.5$ dB)\\cite{braverman2019nearunitary}.\nWhile the latter protocol might be used to transfer spin squeezing to the electronic clock state, to date there has been no demonstration of spin squeezing in an optical clock transition.\n\nIn addition to light scattering, $p$-wave losses from inelastic ${}^3 P_0$ collisions\\cite{martin2013quantum, zhang2014spectroscopic, bishof2011inelastic} can also degrade the maximum achievable spin squeezing, which becomes more pronounced for shallower lattices.\nMore details on $p$-wave losses are discussed in Appendix \\ref{sec:inelastic_collision}, where we show that operating at lattice depths $V_0\\gtrsim 7 E_{\\t{R}}$ may be necessary to suppress the impact of inelastic collisions on spin squeezing, at the cost of slightly increasing light scattering.\n\nThe sources of decoherence considered above are not fundamental, and can be avoided by, for instance, using two nuclear spin levels as spin-1/2 degrees of freedom that are interrogated by far-detuned Raman transitions instead of a direct optical transition\\cite{mancini2015observation}.\nThe strength of SOC for Raman transitions is tunable and, moreover, the lifetimes of ground nuclear spin levels are longer than 100 seconds in the lattice\\cite{goban2018emergence}.\nIn this case, our protocol for preparing a squeezed state would additionally end with a coherent state transfer from nuclear to electronic degrees of freedom to retain metrological utility for the atomic clock.\nIf, for example, the $-9/2$ and $-7/2$ nuclear spin states are used for the preparation of a squeezed state, then the collective-spin entanglement of atoms can be transferred to electronic states at the end of the spin squeezing protocol with a $\\sigma^-$ polarized $\\pi$ pulse.\nSuch a pulse can transfer $\\ket{g,-7/2}$ to $\\ket{e,-9/2}$ without affecting $\\ket{g,-9/2}$, where $g$ and $e$ respectively denote the ground and excited (electronic) clock states.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Conclusions}\n\nWe have proposed a new protocol to generate spin squeezing in a fermionic 3D optical lattice clock by combining nominally undesirable atomic collisions with spin-orbit coupling.\nTo our knowledge, this is the first proposal to use quantum correlations in a many-body fermionic system to push state-of-the-art quantum sensors beyond the independent-particle regime, thereby achieving a genuine quantum advantage.\nSuch capability could allow for major improvements in clock sensitivity and bandwidth, enhancing not only traditional timekeeping applications such as measurement standards, navigation (GPS), and telecommunications, but also geodesy and gravitational wave detection, precision tests of fundamental physics, and the search for new physics beyond the standard model\\cite{safronova2018search}.\n\n\n\\section{Acknowledgments}\n\nWe acknowledge helpful discussions with M.~Norcia, C.~Sanner, and M.~Mamaev.\nThis work is supported by the Air Force Office of Scientific Research (AFOSR) grant FA9550-18-1-0319; the AFOSR Multidisciplinary University Research Initiative (MURI) grant; the Defense Advanced Research Projects Agency (DARPA) and Army Research Office (ARO) grant W911NF-16-1-0576; the National Science Foundation (NSF) grant PHY-1820885; JILA-NSF grant PFC-1734006; and the National Institute of Standards and Technology (NIST).\n\n\n\\appendix\n\n% make figure numbers include the appendix letter\n\\renewcommand\\thefigure{\\thesection\\arabic{figure}}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Derivation of the effective one-axis-twisting model}\n\\label{sec:derivation_OAT}\n\nSuppose we have a Hamiltonian of the form ($\\hbar=1$)\n\\begin{align}\n  H = H_0 + V,\n\\end{align}\nwith\n\\begin{align}\n  H_0 = - \\f{U}{L} \\v S\\c\\v S,\n  &&\n  V = - \\sum_n B_n s_\\z^{(n)} + \\Omega S_\\x,\n\\end{align}\nand we consider $N$-particle states initially in the ground-state manifold $\\G_0$ of $H_0$, which have total spin $S=N/2$.\nIf the largest eigenvalue of $V$ is smaller in magnitude than half of the collective spin gap $NU/L=fU$, i.e.~the energy gap under $H_0$ between $\\G_0$ and its orthogonal complement $\\E_0$, then we can formally develop a perturbative treatment for the action of $V$ on $\\G_0$.\nSuch a treatment yields an effective Hamiltonian on $\\G_0$ of the form $H_{\\t{eff}}=\\sum_pH_{\\t{eff}}^{(p)}$, where $H_{\\t{eff}}^{(p)}$ is order $p$ in $V$.\nLetting $\\P_0$ ($\\Q_0$) be a projector onto $\\G_0$ ($\\E_0$), we define the super-operators $\\O$ and $\\L$ by\n\\begin{align}\n  \\O V &\\equiv \\P_0 V \\Q_0 + \\Q_0 V \\P_0, \\\\\n  \\L V &\\equiv \\sum_{\\alpha,\\beta}\n  \\f{\\op{\\alpha}\\O V \\op{\\beta}}{E_\\alpha-E_\\beta},\n\\end{align}\nwhere $H_0 = \\sum_\\alpha E_\\alpha \\op\\alpha$.\nThe first few terms in the expansion of the effective Hamiltonian $H_{\\t{eff}}$ are then, as derived in Ref.~[\\citenum{bravyi2011schrieffer}],\n\\begin{align}\n  H_{\\t{eff}}^{(0)} = \\P_0 H_0 \\P_0,\n  &&\n  H_{\\t{eff}}^{(1)} = \\P_0 V \\P_0,\n\\end{align}\nand\n\\begin{align}\n  H_{\\t{eff}}^{(2)} = -\\f12 \\P_0 \\sp{\\O V,\\L V}_- \\P_0,\n\\end{align}\nwith $\\sp{X,Y}_-\\equiv XY-YX$.\nThe zero-order effective Hamiltonian $H_{\\t{eff}}^{(0)}=H_0$ within the ground-state manifold.\nTo calculate $H_{\\t{eff}}^{(1)}$, we note that the ground-state manifold $\\G_0$ is spanned by the Dicke states\n\\begin{align}\n  \\ket{m} \\propto S_+^{N/2+m} \\ket{\\downarrow}^{\\otimes n},\n  &&\n  S_+ \\equiv \\sum_n s_+^{(n)},\n\\end{align}\nin terms of which we can expand the collective spin-z operator as $S_\\z=\\sum_m m\\op{m}$.\nWe can likewise expand the collective spin-x operator $S_\\x$ in terms of $x$-oriented Dicke states $\\ket{m_\\x}$ as $S_\\x=\\sum_m m\\op{m_\\x}$.\nThe ground-state projector $\\P_0$ onto $\\G_0$ can be expanded in either basis as $\\P_0=\\sum_m\\op{m}=\\sum_m\\op{m_\\x}$.\nDefining the mean and residual fields\n\\begin{align}\n  \\overline B \\equiv \\f1N \\sum_n B_n,\n  &&\n  b_n \\equiv B_n - \\overline B,\n\\end{align}\nwe can then write\n\\begin{align}\n  V &= -\\sum_n \\p{b_n+\\overline B} s_\\z^{(n)} + \\Omega S_\\x \\notag \\\\\n  &= -\\sum_n b_n s_\\z^{(n)} - \\overline B S_\\z + \\Omega S_\\x,\n\\end{align}\nand in turn\n\\begin{align}\n  H_{\\t{eff}}^{(1)}\n  &= \\P_0\\p{-\\sum_n b_n s_\\z^{(n)} - \\overline B S_\\z + \\Omega S_\\x} \\P_0 \\notag \\\\\n  &= -\\sum_n b_n \\P_0 s_\\z^{(n)} \\P_0 - \\overline B S_\\z + \\Omega S_\\x,\n\\end{align}\nwhere we used the fact that $\\P_0 S_{j=\\z,\\x} \\P_0 = S_j$ within the ground-state manifold.\nBy construction, the residual fields are mean-zero, i.e.~$\\sum_n b_n=0$.\nUsing the particle-exchange symmetry of the Dicke states, we can therefore expand\n\\begin{multline}\n  \\sum_n b_n \\P_0 s_\\z^{(n)} \\P_0\n  = \\sum_{n,m,m'} b_n \\op{m} s_\\z^{(n)} \\op{m'} \\\\\n  = \\sum_n b_n \\sum_{m,m'} \\op{m} s_\\z^{(1)} \\op{m'}\n  = 0,\n\\end{multline}\nwhich implies\n\\begin{align}\n  H_{\\t{eff}}^{(1)} = - \\overline B S_\\z + \\Omega S_\\x.\n\\end{align}\nTo calculate the second-order effective Hamiltonian $H_{\\t{eff}}^{(2)}$, we let $\\B_0\\p{\\E_0}$ denote an eigenbasis of $H_0$ for the excited subspace $\\E_0$, and set the ground-state energy to 0.\nWe then define the operator\n\\begin{align}\n  \\I \\equiv \\sum_{\\ket\\alpha\\in\\B_0\\p{\\E_0}} \\f{\\op\\alpha}{E_\\alpha},\n\\end{align}\nwhich sums over projections onto excited states with corresponding energetic suppression factors, in terms of which we can write\n\\begin{align}\n  H_{\\t{eff}}^{(2)} = -\\P_0 V \\I V \\P_0,\n\\end{align}\nwhich is simply an operator-level version of the textbook expression for second-order perturbation theory.\nThe only part of $V$ which is off-diagonal with respect to the ground- and excited-state manifolds $\\G_0$ and $\\E_0$ is $-\\sum_n b_n s_\\z^{(n)}$, and the individual spin operators in this remainder can only change the total spin $S$ by at most 1.\nIt is therefore sufficient to expand $\\I$ in a basis for states which span the image of $\\G_0$ under all $s_\\z^{(n)}$ within the $S=N/2-1$ manifold.\nSuch a basis is provided by the spin-wave states\n\\begin{align}\n  \\ket{mk}\n  \\propto\n  \\sum_{n=1}^N e^{2\\pi ikn/N} s_+^{(n)} \\ket{m-1},\n\\end{align}\nfor $k=1,2,\\cdots,N-1$\\cite{swallows2011suppression}.\nUsing the fact that all spin-$z$ operators preserve the projection of total spin onto the $z$ axis, we then have that\n\\begin{multline}\n  H_{\\t{eff}}^{(2)}\n  = -\\f1{fU} \\sum_{m,k,n,n'} b_n b_{n'}\n  \\op{m} s_\\z^{(n)} \\ket{mk} \\\\\n  \\times \\bra{mk} s_\\z^{(n')} \\op{m},\n  \\label{eq:general_H_eff_2}\n\\end{multline}\nwhere the relevant matrix elements between the Dicke states and the spin-wave states are\\cite{swallows2011suppression}\n\\begin{align}\n  \\bk{m|s_\\z^{(n)}|mk}\n  = e^{2\\pi i k n/N} \\sqrt{\\f{(N/2)^2-m^2}{N^2 (N-1)}},\n\\end{align}\nwhich implies\n\\begin{multline}\n  H_{\\t{eff}}^{(2)}\n  = -\\f1{fU} \\sum_m \\f{(N/2)^2-m^2}{N^2 (N-1)} \\op{m} \\\\\n  \\times \\sum_{k,n,n'} b_n b_{n'} e^{2\\pi ik\\p{n-n'}/N}.\n\\end{multline}\nUsing the fact that $\\sum_nb_n=0$, we can expand\n\\begin{align}\n  \\sum_{k,n,n'} b_n b_{n'} e^{2\\pi ik\\p{n-n'}/N}\n  &= \\sum_{n,n'} b_n b_{n'} \\sum_{k=1}^{N-1} e^{2\\pi ik\\p{n-n'}/N} \\notag \\\\\n  &= \\sum_{n,n'} b_n b_{n'} \\sum_{k=0}^{N-1} e^{2\\pi ik\\p{n-n'}/N},\n\\end{align}\nwhere the sum over $k$ vanishes for $n\\ne n'$ and equals $N$ when $n=n'$, so\n\\begin{align}\n  \\sum_{k,n,n'} b_n b_{n'} e^{2\\pi ik\\p{n-n'}/N}\n  = N^2 \\widetilde B^2,\n\\end{align}\nwhere\n\\begin{align}\n  \\widetilde B^2\n  \\equiv \\f1N \\sum_n b_n^2 = \\f1N \\sum_n \\p{B_n - \\overline B}^2.\n  \\label{eq:sum_knn}\n\\end{align}\nWe therefore have that\n\\begin{align}\n  H_{\\t{eff}}^{(2)}\n  = -\\sum_m \\f{\\p{N/2}^2-m^2}{\\p{N-1}fU}~ \\widetilde B^2 \\op{m},\n\\end{align}\nwhere the $\\p{N/2}^2$ term contributes a global energy shift which we can neglect, while the $m^2$ term is proportional to $m^2\\op{m}=S_\\z^2$.\nIn total, the effective Hamiltonian through second order in perturbation theory is thus\n\\begin{align}\n  H_{\\t{eff}}\n  = -\\f{U}{L}\\v S\\c\\v S - \\overline B S_\\z + \\Omega S_\\x + \\chi S_\\z^2,\n\\label{eq:H_OAT}\n\\end{align}\nwith\n\\begin{align}\n  \\chi \\equiv \\f{\\widetilde B^2}{\\p{N-1}fU}.\n\\end{align}\nWe benchmark the validity of this effective Hamiltonian via exact simulations of the spin [Eqn.~\\eqref{eq:SpinModel}] and OAT [Eqn.~\\eqref{eq:H_eff}] Hamiltonians in a system of 20 spins, finding that the relative error in maximal squeezing (in dB) of the OAT model is less than 3\\% when $\\widetilde{B}/U<0.06$ (see Appendix \\ref{sec:benchmarking}).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Numerical benchmarking of the OAT model}\n\\label{sec:benchmarking}\n\\setcounter{figure}{0}\n\nHere we provide additional information about our benchmarking of the one-axis twisting model against the spin model.\nThis benchmarking was performed via exact simulations of a 20-spin system.\nFig.~\\ref{fig:relative_error} shows the relative error in maximal squeezing of the OAT model (measured against the spin model) as a function of the reduced field variance $\\widetilde{B}/U$.\nHere squeezing is measured in decibels (dB) by $-10\\log_{10}\\xi^2$ for the squeezing parameter $\\xi^2$ define in Eqn.~\\eqref{eq:sqz}.\nThe relative error in maximal squeezing (in dB) by the OAT model is less than 3\\% when $\\widetilde{B}/U<0.06$.\n\n\\begin{figure}\n\\centering\n\\includegraphics[width=0.35\\textwidth]{relative_error.pdf}\n\\caption{{\\bf Relative error} between maximal squeezing (measured in dB) obtained by the OAT [Eqn.~\\eqref{eq:H_eff}] and spin [Eqn.~\\eqref{eq:SpinModel}] models of the main text in a system of 20 particles.\nThe OAT model correctly captures the maximal squeezing (in dB) of the spin model to within 3\\% (marked by the horizontal reference line) within the gap-protected regime $\\widetilde{B}/U<0.06$.\n}\n\\label{fig:relative_error}\n\\end{figure}\n\nIn principle, spin-changing decoherence compromises the validity of the OAT model, as its perturbative derivation in Appendix \\ref{sec:derivation_OAT} relies on spin population remaining primarily within the Dicke manifold.\nThis assumption breaks down in the presence of, for example, spontaneous emission, which transfers population outside of the Dicke manifold.\nNonetheless, we find decent agreement between the OAT and spin models when decoherence is sufficiently weak (see Fig.~\\ref{fig:benchmarking_decay}).\n\n\\begin{figure*}\n\\centering\n\\includegraphics[width=0.75\\textwidth]{benchmarking_decay.pdf}\n\\caption{{\\bf Comparison between the OAT and the spin model in the presence of decoherence.}\n({\\bf a}) The difference between the maximal squeezing (measured in dB) obtained by the OAT [Eqn.~\\eqref{eq:H_eff}] and spin [Eqn.~\\eqref{eq:SpinModel}] models increases with the particle number $N$ and the single-particle spontaneous emission rate $\\gamma$.\nThis disagreement is attributed in part to the fact that spontaneous emission transfers population of the collective spin state outside of the Dicke manifold, violating an assumption of the OAT model; see panel ({\\bf b}).\nThe rate of population transfer outside of the Dicke manifold increases with both particle number and spontaneous emission rate.\n(Parameters for simulations in this figure: $U=1000$ Hz, $J=200$ Hz, and $\\phi=\\pi/20$).\n}\n\\label{fig:benchmarking_decay}\n\\end{figure*}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Two-axis twisting, decoherence, and the residual axial field}\n\\label{sec:derivation_TAT}\n\nThe protocol we use to transform one-axis twisting (OAT) into two-axis twisting (TAT) is as previously proposed in Ref.~[\\citenum{huang2015twoaxis}]; we provide a summary of this protocol here, in addition to some brief discussion of its implications for decoherence and the residual $\\sim\\v S\\v\\c\\v S$ and $\\sim S_\\z$ terms of our OAT protocol.\nThe TAT protocol begins with the OAT Hamiltonian with a time-dependent transverse field,\n\\begin{align}\n  H = \\chi S_\\z^2 + \\Omega\\p{t} S_\\x,\n  &&\n  \\Omega\\p{t} = \\beta\\omega \\cos\\p{\\omega t},\n  \\label{eq:driven_OAT}\n\\end{align}\nwhere $\\beta$ is the modulation index of the driving field and the drive frequency $\\omega\\gg N\\chi$, with $N$ the total number of spins.\nMoving into the rotating frame of $\\Omega\\p{t}S_\\x$ subtracts this term from the Hamiltonian, and transforms operators $\\O$ as\n\\begin{align}\n  \\O \\to U\\p{t}^\\dag \\O U\\p{t},\n\\end{align}\nwhere\n\\begin{align}\n  U\\p{t} \\equiv \\exp\\sp{-i\\int_0^t\\d\\tau~\\Omega\\p{\\tau}S_\\x}\n  = \\exp\\sp{-i\\beta\\sin\\p{\\omega t}S_\\x}.\n\\end{align}\nIn particular, the operators $\\tilde S_\\pm\\equiv-S_\\z\\pm iS_\\y$ (i.e.~the raising and lowering operators in the $x$ basis) transform simply as\n\\begin{align}\n  \\tilde S_\\pm\n  \\to U^\\dag \\tilde S_\\pm U\n  = e^{\\pm i\\beta\\sin\\p{\\omega t}} \\tilde S_\\pm.\n\\end{align}\nFor any operator $\\O$ and drive frequency $\\omega\\gg\\norm{\\O}$, where $\\norm{\\O}\\equiv\\max_\\psi\\sqrt{\\braket{\\psi|\\O^\\dag\\O|\\psi}}$ is the operator norm of $\\O$ (i.e.~the magnitude of the largest eigenvalue of $\\O$), we can generally make a secular approximation to say\n\\begin{align}\n  e^{\\pm im\\beta\\sin\\p{\\omega t}} \\O\n  &= \\sum_{n=-\\infty}^\\infty \\J_n\\p{\\pm m\\beta} e^{in\\omega t} \\O \\notag \\\\\n  &\\approx \\J_0\\p{\\pm m\\beta} \\O\n  = \\J_0\\p{m\\beta} \\O,\n\\end{align}\nwhere $\\J_n$ is the $n$-th order Bessel function of the first kind.\nExpanding $S_\\z^2=\\f14\\p{\\tilde S_+ + \\tilde S_-}^2$, one can thus work out that the effective Hamiltonian in the rotating frame of the drive is\n\\begin{align}\n  H_{\\t{eff}}\n  \\approx \\f{\\chi}{2} \\p{\\sp{1+\\J_0\\p{2\\beta}} S_\\z^2\n  + \\sp{1-\\J_0\\p{2\\beta}} S_\\y^2}.\n\\end{align}\nDriving with a modulation index $\\beta$ for which $J_0\\p{2\\beta}=\\pm1/3$ then gives us the effective two-axis twisting Hamiltonians\n\\begin{align}\n  H_{\\t{eff}}^{(+)}\n  &= \\f{\\chi}{3} \\p{2 S_\\z^2 + S_\\y^2}\n  \\simeq \\f{\\chi}{3} \\p{S_\\z^2 - S_\\x^2}, \\\\\n  H_{\\t{eff}}^{(-)}\n  &= \\f{\\chi}{3} \\p{S_\\z^2 + 2 S_\\y^2}\n  \\simeq \\f{\\chi}{3} \\p{S_\\y^2 - S_\\x^2},\n\\end{align}\nwhere $\\simeq$ denotes equality up to the addition of a term proportional to $\\v S^2=S_\\z^2+S_\\x^2+S_\\y^2$, which is irrelevant in the absence of coherent coupling between states with different net spin.\nIn a similar spirit, one can work out that single-spin operators transverse to the $x$-axis transform as\n\\begin{multline}\n  \\tilde s_\\pm\n  \\equiv \\f12\\p{-s_\\z\\pm i s_\\y} \\\\\n  \\to U^\\dag \\tilde s_\\pm U\n  = e^{\\pm i\\beta\\sin\\p{\\omega t}} \\tilde s_\\pm\n  \\approx \\J_0\\p{\\beta} \\tilde s_\\pm,\n\\end{multline}\nwhich implies that shifting into the rotating frame of the time-dependent drive takes\n\\begin{align}\n  s_\\x \\to s_\\x,\n  &&\n  s_{\\y,\\z} \\to \\J_0\\p{\\beta} s_{\\y,\\z},\n  \\label{eq:dec_transformation_xyz}\n\\end{align}\nand\n\\begin{align}\n  s_\\pm\n  \\to \\f12\\sp{1 \\pm \\J_0\\p{\\beta}} s_+\n  + \\f12\\sp{1 \\mp \\J_0\\p{\\beta}} s_-.\n  \\label{eq:dec_transformation_pm}\n\\end{align}\nAs the TAT Hamiltonians $H_{\\t{eff}}^{(\\pm)}$ are realized in a rotating frame, to properly account for decoherence throughout the TAT protocol one must transform jump operators according to Eqns.~\\eqref{eq:dec_transformation_xyz}-\\eqref{eq:dec_transformation_pm}.\n\nIn practice, our protocols realize the OAT Hamiltonian in Eqn.~\\eqref{eq:driven_OAT} with additional $\\sim\\v S\\c\\v S$ and $\\sim S_\\z$ terms [see Eqn.~\\eqref{eq:H_OAT}].\nThe effect of the $\\sim\\v S\\c\\v S$ term is to generate a relative phase between states with different total spin $S$ (with e.g.~$S=N/2$ within the Dicke manifold).\nIn the absence of coherent coupling between states with different total spin, therefore, the $\\sim\\v S\\c\\v S$ term has no effect on system dynamics.\nThe $\\sim S_z$ term, meanwhile, is important; the magnitude of this term (as measured by the operator norm) is generally comparable to that of the squeezing term $\\chi S_\\z^2$.\nUnlike in the case of OAT, $S_\\z$ does not commute with the TAT Hamiltonians, so its effects cannot be eliminated by a single spin-echo $\\pi$-pulse $\\exp\\p{-i\\pi S_\\x}$ half way through the squeezing protocol.\nNonetheless, we find that for $N=10^2$ ($10^3$) atoms, $\\sim5$ (10) $\\pi$-pulses in a CPMG (Carr-Purcell-Meiboom-Gill) sequence\\cite{carr1954effects, meiboom1958modified} suffice to mitigate the effects of the $S_\\z$ term in the TAT protocol (see Appendix \\ref{sec:dynamical_decoupling}).\nPhase control over these pulses, specifically choices of whether to apply $\\exp\\p{\\pm i\\pi S_\\x}$ or $\\exp\\p{\\pm i\\pi S_\\y}$ in any given $\\pi$-pulse, can be used to construct XY-$n$ pulse sequences\\cite{maudsley1986modified, gullion1990new} that are robust to pulse errors.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Dynamical decoupling in the TAT protocol}\n\\label{sec:dynamical_decoupling}\n\\setcounter{figure}{0}\n\nThe effective Hamiltonian resulting from a perturbative treatment of SOC is (see Appendix \\ref{sec:derivation_OAT})\n\\begin{align}\n  H_{\\t{eff}}\n  = -\\f{U}{L}\\v S\\c\\v S - \\overline B S_\\z + \\Omega S_\\x + \\chi S_\\z^2,\n  \\label{eq:H_eff_DD}\n\\end{align}\nwhere $U$ is a two-atom on-site interaction strength; $L$ is the number of lattice sites; $\\overline B\\equiv \\sum_n B_n/N$ is a residual axial field determined by the occupied quai-momentum modes $\\set{n}$ (with $\\abs{\\set{n}}=N$ atoms total); $\\Omega$ is the magnitude of a driving field; and $\\chi$ is an effective OAT squeezing strength.\nThe effect of the $\\sim\\v S\\c\\v S$ term is to generate a relative phase between states with different total spin $S$ (where $S=N/2$ within the Dicke manifold).\nIn the absence of coherent coupling between states with different total spin, therefore, the $\\sim\\v S\\c\\v S$ term has no effect on system dynamics, and we are safe to neglect it entirely.\n\nIn the parameter regimes relevant to our discussions in the main text, the operator norms of $\\overline{B}\\hat S_\\z$ and $\\chi \\hat S_\\z^2$ in Eqn.~\\eqref{eq:H_eff_DD} will typically be comparable in magnitude.\nThe OAT protocol sets $\\Omega=0$, and eliminates the effect of $\\overline{B}\\hat S_\\z$ with a spin-echo $\\pi$-pulse $\\exp\\p{-i\\pi\\hat S_\\x}$ applied half way through the squeezing protocol.\nThe TAT protocol, meanwhile, effectively takes $\\chi\\hat S_\\z^2+\\Omega \\hat S_\\x\\to\\hat H_{\\t{TAT}}^{(\\pm)}$ (as defined in Appendix \\ref{sec:derivation_TAT}) and $\\overline{B}\\hat S_\\z\\to\\J_0\\p{\\beta_\\pm}\\overline{B}\\hat S_\\z$, where $\\J_0$ is the zero-order Bessel function of the first kind and $\\beta_\\pm$ is the modulation index of the amplitude-modulated driving field $\\Omega$, satisfying $\\J_0\\p{2\\beta_\\pm}=\\pm1/3$.\nUnlike in the case of OAT, $\\hat S_\\z$ does not commute with the TAT Hamiltonian, so its effect cannot be eliminated with a spin-echo.\nNonetheless, this term can be eliminated with a dynamical decoupling pulse sequence that periodically inverts the sign of $\\hat S_\\z$ while preserving $\\hat H_{\\t{TAT}}^{(\\pm)}$.\n\n\\begin{figure*}\n\\centering\n\\includegraphics{pulsed_squeezing.pdf}\n\\caption{{\\bf Optimal squeezing as a function of $\\pi$-pulses} applied prior to the optimal TAT squeezing time in a CPMG sequence with ({\\bf a)} $N=100$ and ({\\bf b}) $N=1000$ atoms.\nResults are shown for OAT, TAT, and TAT$_{\\pm,\\z}$, where TAT$_{\\pm,\\z}$ denotes squeezing via the Hamiltonian $\\hat H_{\\t{TAT}}^{(\\pm,\\z)}\\equiv \\hat H_{\\t{TAT}}^{(\\pm)}-\\J_0\\p{\\beta_\\pm}\\bk{\\overline B}^{\\t{rms}}_f \\hat S_\\z$.\nDetails about experimental parameters for these simulations are provided in the text.\n}\n\\label{fig:pulsed_squeezing}\n\\end{figure*}\n\nFig.~\\ref{fig:pulsed_squeezing} shows the maximal squeezing generated by $N=10^2$ and $10^3$ atoms via OAT, TAT, and TAT in the presence of the mean field $\\J_0\\p{\\beta_\\pm}\\overline B\\hat S_\\z$ as a function of the number of $\\pi$-pulses performed prior to the optimal TAT squeezing time.\nThese pulses are applied in a CPMG sequence $\\p{\\tau_n/2-\\pi_\\x-\\tau_n/2}^n$, where $\\tau_n/2$ denotes Hamiltonian evolution for a time $\\tau_n/2$, $\\pi_\\x$ denotes the application of an instantaneous $\\pi$-pulse $\\exp\\p{-i\\pi\\hat S_\\x}$, and $n$ is the number of pulses, such that the optimal TAT squeezing time is $t_{\\t{opt}}^{\\t{TAT}}=\\p{\\tau_n}^n$.\nThe label TAT$_{\\pm,\\z}$ in Fig.~\\ref{fig:pulsed_squeezing} denotes squeezing through the Hamiltonian $\\hat H_{\\t{TAT}}^{(\\pm,\\z)}\\equiv \\hat H_{\\t{TAT}}^{(\\pm)}-\\J_0\\p{\\beta_\\pm}\\bk{\\overline B}^{\\t{rms}}_f\\hat S_\\z$, where $\\bk{\\overline B}^{\\t{rms}}_f$ is the root-mean-square average of $\\overline B$ over choices of occupied spacial modes $\\set{n}$ at fixed filling $f$ of all spatial modes in the lowest Bloch band of a periodic 2D lattice.\nWhile the modulation index $\\beta_+$ is uniquely defined by $\\J_0\\p{2\\beta_+}=1/3$, there are two choices of $\\beta_-$ for which $\\J_0\\p{2\\beta_-}=-1/3$; we use that which minimizes $\\abs{\\J_0\\p{\\beta_-}}$.\nFig.~\\ref{fig:pulsed_squeezing} assumes an SOC angle $\\phi=\\pi/50$ (although results are independent of $\\phi$ for $\\phi\\ll1$), a reduced field variance $\\widetilde{B}/U=0.05$, and a filling $f=5/6$.\nNote that as the filling $f\\to1$, the residual axial field vanishes ($\\overline{B}\\to0$), so TAT$_{\\pm,\\z}\\to$ TAT.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Clock interrogation after squeezing}\n\\label{sec:clock_interrogation}\n\nThe protocols in our work concern the preparation of spin-squeezed states in an optical lattice clock.\nHere, we discuss the use of these states in a follow-up clock interrogation protocol.\nFor simplicity, we restrict our discussion to the case of squeezing in 1D, as in Section \\ref{sec:theory} of the main text, with the understanding that a generalization of this discussion to higher dimensions is straightforward.\n\nA spin-squeezed state is generated by interactions and SOC that are generally undesirable during the clock interrogation protocol.\nIn the parameter regimes considered in our work, interactions alone have no effect on clock interrogation: absent of coherence between states with different net spin $S$, collective $\\v S\\c\\v S$ interactions only generate unobservable global phases within each fixed-$S$ sector of Hilbert space.\nTherefore, the remaining task to allow clock interrogation after spin squeezing is to turn off SOC, which inhomogeneously detunes atomic transition frequencies by an amount $B_q$ that depends on the quasi-momentum $q$ of an atom.\nThe SOC-induced axial fields $B_q\\sim J\\sin(\\phi/2)$ depend on two tunable parameters: the tunneling rate $J$ and the SOC angle $\\phi$.\nThe simplest way to turn off SOC is thus to increase the lattice depth prior to clock interrogation, taking $J\\sim B_q\\to0$.\nIncreasing the lattice depth to turn off SOC is compatible with the current clock interrogation sequence, but is incompatible with ongoing efforts to mitigate light scattering from the lattice beams (currently the primary source of decoherence in the clock; see Appendix \\ref{sec:decoherence}) by using shallower lattices\\cite{hutson2019engineering}.\nWe thus devote the rest of this section to discussing strategies for turning off SOC that are compatible with using the same lattice depth for clock interrogation as the spin squeezing generation.\n\nIf we cannot take the tunneling rate $J\\to0$, our remaining control parameter for turning off SOC is the SOC angle $\\phi=k_{\\t{L}}a$, where $k_{\\t{L}}$ is the projection of the clock laser wavenumber onto the lattice axis and $a$ is the lattice spacing.\nThe squeezing protocol needs a clock laser with a small but nonzero SOC angle $\\phi\\ll1$, while the clock interrogation protocol requires a clock laser with $\\phi=0$.\nSimply using one clock laser with $\\phi\\ne0$ for the squeezing protocol and another clock laser with $\\phi=0$ for the clock interrogation protocol, however, does not resolve this discrepancy, because a state that is squeezed with respect to spin operators that are homogeneous (i.e.~of the form $S_\\x,S_\\y,S_\\z$) in a particular gauge is not necessarily squeezed with respect to spin operators that are homogeneous in a different gauge.\nIn this appendix, we will work explicitly in the ``lab gauge'' of the clock interrogation protocol, in which the Fermi-Hubbard Hamiltonian is SOC-free and the $\\phi=0$ clock laser is homogeneous.\nTo resolve the fact that our squeezing protocol prepares a state that is squeezed in the ``wrong gauge'', we will construct a simple pulse sequence that transforms the inhomogeneous spin operators accessible by the $\\phi\\ne0$ laser into a homogeneous form in our lab gauge.\n\nStarting with a spin-down-polarized initial state\n\\begin{align}\n  \\ket{-\\t{Z}}\\equiv\\p{\\prod_j c_{j,\\dn}^\\dag}\\ket{\\t{vacuum}},\n\\end{align}\nour OAT protocol prepares the state\n\\begin{align}\n  \\ket{\\xi_{\\t{OAT}}^{(\\theta)}} = e^{-i H_{\\t{FH}}^{(0)}t}\n  e^{-i\\p{\\pi/2}S_\\x^{(\\theta)}} \\ket{-\\t{Z}},\n\\end{align}\nwhere $H_{\\t{FH}}^{(0)}$ is the Fermi-Hubbard Hamiltonian in Eqn.~\\eqref{eq:FermiHubbard} without SOC; $t$ is some free evolution time; and $S_\\x^{(\\theta)}$ is the ``rotated'' spin-$x$-like generator induced by a clock laser with SOC angle $\\phi=\\theta$, namely\n\\begin{align}\n  S_\\x^{(\\theta)}\n  = \\f12 \\sum_j e^{i\\theta j} c_{j,\\up}^\\dag c_{j,\\dn} + \\t{h.c.}.\n\\end{align}\nDefining on-site spin operators (in the lab gauge)\n\\begin{align}\n  s_\\z^{(j)} &\\equiv \\f12 \\p{ c_{j,\\up}^\\dag c_{j,\\up}\n    - c_{j,\\dn}^\\dag c_{j,\\dn}} \\\\\n  s_\\x^{(j)} &\\equiv \\f12 \\p{c_{j,\\up}^\\dag c_{j,\\dn}\n    + c_{j,\\dn}^\\dag c_{j,\\up}} \\\\\n  s_\\y^{(j)} &\\equiv \\f{i}{2} \\p{c_{j,\\dn}^\\dag c_{j,\\up}\n    - c_{j,\\up}^\\dag c_{j,\\dn}},\n\\end{align}\nwe can identify the rotated collective spin operators\n\\begin{align}\n  S_\\x^{(\\theta)} &\\equiv \\sum_j \\p{\\cos\\p{\\theta j} s_\\x^{(j)}\n  + \\sin\\p{\\theta j} s_\\y^{(j)}},\n  \\label{eq:S_x_theta} \\\\\n  S_\\y^{(\\theta)} &\\equiv \\sum_j \\p{\\cos\\p{\\theta j} s_\\y^{(j)}\n  - \\sin\\p{\\theta j} s_\\x^{(j)}}.\n  \\label{eq:S_y_theta}\n\\end{align}\nThe state $\\ket{\\xi_{\\t{OAT}}^{(\\theta)}}$ is squeezed with respect to components of the rotated collective spin vector $\\v S_\\theta \\equiv \\p{S_\\x^{(\\theta)},S_\\y^{(\\theta)},S_\\z}$.\nTherefore, to take advantage of the squeezing in $\\ket{\\xi_{\\t{OAT}}^{(\\theta)}}$, the clock interrogation protocol effectively needs to rotate this state by some unitary $\\exp\\p{-i\\v\\eta\\c\\v S_\\theta}$, and then extract information about the rotation vector $\\v\\eta$ from collective spin observables of the form\n\\begin{align}\n  \\bk{\\O_\\theta}_{\\t{OAT}}^{\\v\\eta}\n  \\equiv \\bk{\\xi_{\\t{OAT}}^{(\\theta)}| e^{i\\v\\eta\\c\\v S_\\theta}\n    \\O_\\theta e^{-i\\v\\eta\\c\\v S_\\theta} |\\xi_{\\t{OAT}}^{(\\theta)}},\n\\end{align}\nwhere $\\O_\\theta$ is some product of the rotated collective spin operators in $\\v S_\\theta$, e.g.~$S_\\x^{(\\theta)}$ or $S_\\x^{(\\theta)} S_\\y^{(\\theta)}$.\nIn order to turn off SOC during clock interrogation, however, we are restricted to performing rotations of the form $\\exp\\p{-i\\v\\eta\\c\\v S_0}$ and measuring homogeneous operators $\\O_0$.\nWe thus seek a ``gauge-switching'' operation $G_\\theta$ that maps homogeneous operators $\\O_0$ onto rotated operators $\\O_\\theta$ via $G_\\theta^\\dag \\O_0 G_\\theta = \\O_\\theta$.\nEquipped with $G_\\theta$, we could decompose\n\\begin{align}\n  \\bk{\\O_\\theta}_{\\t{OAT}}^{\\v\\eta}\n  &= \\bk{\\xi_{\\t{OAT}}^{(\\theta)}| G_\\theta^\\dag e^{i\\v\\eta\\c\\v S_0}\n    \\O_0 e^{-i\\v\\eta\\c\\v S_0} G_\\theta |\\xi_{\\t{OAT}}^{(\\theta)}}\n  \\notag \\\\\n  &= \\bk{\\tilde \\xi_{\\t{OAT}}^{(\\theta)}| e^{i\\v\\eta\\c\\v S_0}\n    \\O_0 e^{-i\\v\\eta\\c\\v S_0} |\\tilde \\xi_{\\t{OAT}}^{(\\theta)}}\n\\end{align}\nfor a transformed state\n\\begin{align}\n  \\ket{\\tilde \\xi_{\\t{OAT}}^{(\\theta)}}\n  \\equiv G_\\theta \\ket{\\xi_{\\t{OAT}}^{(\\theta)}}\n\\end{align}\nthat is now squeezed with respect to the homogeneous collective spin operators in $\\v S_0$, accessible with the SOC-free ($\\phi=0$) clock laser used during clock interrogation.\n\nGiven the definitions of the rotated spin operators $S_\\x^{(\\theta)},S_\\x^{(\\theta)}$ in Eqns.~\\eqref{eq:S_x_theta}, \\eqref{eq:S_y_theta}, a suitable candidate for the gauge-switching operator $G_\\theta$ is the site-dependent rotation\n\\begin{align}\n  G_\\theta = \\prod_j \\exp\\p{i\\theta j s_\\z^{(j)}}.\n\\end{align}\nTo implement $G_\\theta$ with ``global'' (i.e.~non-site-selective) experimental controls, we decompose each local rotation into a product of two reflections:\n\\begin{align}\n  \\exp\\p{i2\\alpha s_\\z^{(j)}}\n  \\simeq \\exp\\p{i\\pi s_\\x^{(j)}} \\exp\\p{i\\pi s_\\alpha^{(j)}}\n\\end{align}\nwhere $\\simeq$ denotes equality up to an overall phase, and $s_\\alpha^{(j)} \\equiv \\cos\\alpha s_\\x^{(j)} + \\sin\\alpha s_\\y^{(j)}$.\nThis decomposition implies\n\\begin{align}\n  G_\\theta \\simeq \\exp\\p{i\\pi S_\\x^{(0)}} \\exp\\p{i\\pi S_\\x^{(\\theta/2)}},\n  \\label{eq:G_pi_pi}\n\\end{align}\nwhich can be implemented using one SOC-free ($\\phi=0$) clock laser, and one clock laser with SOC angle $\\phi=\\theta/2$.\nAppending the two $\\pi$-pulses given by Eqn.~\\eqref{eq:G_pi_pi} to our squeezing protocol thus prepares a state $\\ket{\\tilde\\xi_{\\t{OAT}}^{(\\theta)}}$ that is squeezed with respect to the homogeneous collective spin operators $S_\\x,S_\\y,S_\\z$ accessible to the SOC-free ($\\phi=0$) clock laser used during clock interrogation.\n\nAs presented, the combined squeezing and clock interrogation protocols require three clock lasers in total: one without SOC ($\\phi=0$), and one each for SOC angles $\\phi\\in\\set{\\theta/2,\\theta}$.\nWe can use $G_\\theta$, however, to decompose any pulse $\\exp\\p{-i\\v\\beta\\c\\v S_\\theta}$ into composite pulses that use only $\\v S_0$ and $\\v S_{\\theta/2}$:\n\\begin{align}\n  \\exp\\p{-i\\v\\beta\\c\\v S_\\theta}\n  = G_\\theta^\\dag \\exp\\p{-i\\v\\beta\\c\\v S_0} G_\\theta.\n  \\label{eq:pulse_decomposition}\n\\end{align}\nThe state prepared by the OAT squeezing protocol, for example, can be equivalently prepared via\n\\begin{align}\n  \\ket{\\xi_{\\t{OAT}}^{(\\theta)}}\n  &= e^{-i H_{\\t{FH}}^{(0)}t} G_\\theta^\\dag\n  e^{-i\\p{\\pi/2}S_\\x^{(0)}} G_\\theta \\ket{-\\t{Z}} \\notag \\\\\n  &\\simeq e^{-i H_{\\t{FH}}^{(0)}t} e^{-i\\pi S_\\x^{(\\theta/2)}}\n  e^{i\\p{\\pi/2} S_\\x^{(0)}} \\ket{-\\t{Z}}.\n\\end{align}\nSpin-echo pulses applied throughout OAT can likewise be decomposed according to \\eqref{eq:pulse_decomposition}, eliminating the need for a clock laser with SOC angle $\\phi=\\theta$.\nApplying a continuous drive during a squeezing protocol, however, still requires all three clock lasers.\nIf carefully tuning the relative orientations of three clock lasers proves to be too difficult in practice, converting OAT into TAT would therefore need to be done with a pulsed drive protocol, as in Ref.~[\\citenum{liu2011spin}].\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Decoherence in the 3D $^{87}$Sr optical lattice clock}\n\\label{sec:decoherence}\n\nCurrently, light scattering from lattice beams in the 3D $^{87}$Sr optical lattice clock induces decoherence on a time scale of $\\sim$10 seconds\\cite{goban2018emergence, hutson2019engineering}.\nThis decoherence acts identically on all atoms in an uncorrelated manner, and can be understood by considering the density operator $\\rho$ for a single atom, with effective spin states $\\dn$ and $\\up$ respectively corresponding to the ${}^1\\t{S}_0$ and ${}^3\\t{P}_0$ electronic states.\nEmpirically, the effect of decoherence after a time $t$ within the $\\set{\\dn,\\up}$ subspace of a single atom is to take $\\rho\\to\\rho\\p{t}$ with $\\rho\\p{0}\\equiv\\rho$ and\n\\begin{align}\n  \\rho\\p{t} \\coloneqq\n  \\begin{pmatrix}\n  \\rho_{\\up\\up} e^{-\\Gamma_{\\up\\up}t} &&\n  \\rho_{\\up\\dn} e^{-\\Gamma_{\\up\\dn}t} \\\\\n  \\rho_{\\up\\dn}^* e^{-\\Gamma_{\\up\\dn}t} &&\n  \\rho_{\\dn\\dn} + \\p{1-e^{-\\Gamma_{\\up\\up}t}} \\rho_{\\up\\up}\n  \\end{pmatrix},\n  \\label{eq:decay_matrix}\n\\end{align}\nwhere $\\Gamma_{\\up\\up}\\approx\\Gamma_{\\up\\dn}\\approx\\Gamma=0.1~\\t{sec}^{-1}$ are respectively decay rates for $\\rho_{\\up\\up}$ and $\\rho_{\\up\\dn}$.\nThis form of decoherence can be effectively modeled by decay and dephasing of individual spins (respectively denoted $\\Gamma_{\\t{ud}}$ and $\\Gamma_{\\t{el}}$ in Ref.~[\\citenum{foss-feig2013nonequilibrium}]) at rates $\\Gamma$.\nIn the language of the section that follows, we would say that this decoherence is captured by the sets of jump operators $\\J_-\\equiv\\set{s_-^{(j)}}$ and $\\J_\\z\\equiv\\set{s_\\z^{(j)}}$ with corresponding decoherence rates $\\gamma_-=\\gamma_\\z=\\Gamma$.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Time-series of squeezing via OAT and TAT}\n\\label{sec:time_series}\n\\setcounter{figure}{0}\n\nFigure \\ref{fig:squeezing_example} shows an example of squeezing over time via OAT and TAT, both with and without decoherence via decay and dephasing of individual spins.\nThe OAT model initially generates squeezing faster than the TAT model, but the squeezing generation rate of OAT (measured in dB per second) falls off with time.\nThe squeezing generation rate for TAT, meanwhile, remains approximately constant (in the absence of decoherence) until squeezing via TAT surpasses that of OAT.\nIn the absence of decoherence, OAT achieves a maximal amount of squeezing that scales as $\\xi^2\\sim N^{-2/3}$, while TAT achieves Heisenberg-limited squeezing with $\\xi^2\\sim N^{-1}$.\nNote that our method for computing squeezing via TAT in the presence of decoherence (described in Appendix \\ref{sec:collective_simulation}) is not capable of computing squeezing for the full range of times shown in Fig.~\\ref{fig:squeezing_example}; the corresponding time-series data in this figure is therefore shown up to the point at which this method breaks down.\n\n\\begin{figure*}\n\\centering\n\\includegraphics{squeezing_example_L40.pdf}\n\\includegraphics{squeezing_example_L100.pdf}\n\\caption{{\\bf Squeezing via OAT and TAT} in a 2D section of the 3D $^{87}$Sr optical lattice clock, shown for ({\\bf a}) $\\ell=40$ and ({\\bf b}) $\\ell=100$ sites per axis (with $N=\\ell^2$ atoms total), and a lattice depth of $V_0=4~E_{\\t{R}}$, where $E_{\\t{R}}$ is the atomic lattice recoil energy.\nAtoms are confined along the direction transverse to the 2D layer by a lattice of depth 60 $E_{\\t{R}}$.\nSqueezing over time is shown for OAT (blue) and TAT (green), both with (solid lines) and without (dashed lines) decoherence via uncorrelated decay and dephasing of individual spins at rates of $0.1~\\t{sec}^{-1}$ (see Appendix \\ref{sec:decoherence}).\n}\n\\label{fig:squeezing_example}\n\\end{figure*}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Solving Heisenberg equations of motion for collective spin systems}\n\\label{sec:collective_simulation}\n\nIn order to compute squeezing of a collective spin system, we need to compute expectation values of (homogeneous) collective spin operators.\nWe compute these expectation values using a method recently developed in Ref.~[\\citenum{perlin2019shorttime}], and provide a short overview of the method here.\nChoosing the basis $\\set{\\S_{\\v m}}$ for all collective spin operators, where $\\S_{\\v m}\\equiv S_+^{m_+} S_\\z^{m_\\z} S_-^{m_-}$ with\n$\\v m\\equiv\\p{m_+,m_\\z,m_-}\\in\\mathbb{N}_0^3$, we can expand all\ncollective spin Hamiltonians in the form\n\\begin{align}\n  H = \\sum_{\\v m} h_{\\v m} \\S_{\\v m}.\n  \\label{eq:H_general}\n\\end{align}\nThe evolution of a general correlator $\\bk{\\S_{\\v n}}$ under a Hamiltonian of the form in Eqn.~\\eqref{eq:H_general} is then given by\n\\begin{align}\n  \\f{d}{dt} \\bk{\\S_{\\v n}}\n  &= i \\sum_{\\v m} h_{\\v m}\n  \\bk{\\sp{\\S_{\\v m}, \\S_{\\v n}}_-}\n  + \\sum_\\J \\gamma_\\J \\bk{\\mathcal D\\p{\\J; \\S_{\\v n}}} \\notag \\\\\n  &\\equiv \\sum_{\\v m} \\bk{\\S_{\\v m}} T_{\\v m\\v n},\n\\end{align}\nwhere $\\sp{X,Y}_\\pm\\equiv XY\\pm YX$; $\\J$ is a set of jump operators with corresponding decoherence rate $\\gamma_\\J$; the decoherence operator $\\mathcal D$ is defined by\n\\begin{align}\n  \\mathcal{D}\\p{\\J;\\O}\n  \\equiv \\sum_{J\\in\\J}\\p{J^\\dag \\O J - \\f12\\sp{J^\\dag J,\\O}_+};\n\\end{align}\nand $T_{\\v m\\v n}$ is a matrix element of the time derivative operator $T\\equiv d/dt$.\nThese matrix elements can be calculated analytically using product and commutation rules for collective spin operators.\nWe can then expand correlators in a Taylor series about $t=0$ to write\n\\begin{align}\n  \\bk{\\S_{\\v n}}\n  &= \\sum_{k\\ge0} \\f{t^k}{k!} \\bk{\\f{d^k}{dt^k} \\S_{\\v n}}_{t=0}\n  \\notag \\\\\n  &= \\sum_{k\\ge0} \\f{t^k}{k!}\n  \\sum_{\\v m} T_{\\v m\\v n;k} \\bk{\\S_{\\v m}}_{t=0},\n  \\label{eq:time_series}\n\\end{align}\nwhere $T_{\\v m\\v n;k}\\equiv\\sp{T^k}_{\\v m\\v n}$ are matrix elements of the $k$-th time derivative.\nExpectation values of collective spin operators can thus be computed via the expansion in Eqn.~\\eqref{eq:time_series}, which at short times can be truncated at some finite order beyond which all terms have negligible contribution to $\\bk{\\S_{\\v n}}$.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Effect of a harmonic confining trap}\n\\label{sec:harmonic_trap}\n\\setcounter{figure}{0}\n\n\\begin{figure*}\n\\centering\n    \\includegraphics[width=0.7\\linewidth]{fig_harmonic.pdf}\n    \\label{fig:harmonic_trap1}\n    \\caption{Dynamics of non-interacting spin-orbit coupled fermions in a 1D lattice with SOC angle $\\phi = \\pi/50$, plus a harmonic trap with $\\Omega/J = 0.01$. Starting with a spin-polarized cloud in $\\downarrow$ ground state, an initial clock laser pulse is applied to rotate spins into $x$, and the atoms are allowed to evolve during the dark time. We track the dynamics of the $\\uparrow$ particle density for the cases of (a) $N = 20$ and (b) $N = 60$ atoms. Panel (c) shows the time-averaged fluctuations of the $\\uparrow$ particle density for each site index $j$ from its initial value following the Ramsey pulse; see Eqn.~\\eqref{eq:time_avg_fluc}. For $N = 60$, we have filled all delocalized modes as well as several localized modes, resulting in a large region of no density fluctuations at the trap center. Panel (d) contains the eigenspectrum for a single internal state in the presence of the trap (with the index $n$ labeling the eigenvalues in order of increasing energy), where the critical mode $n_c$ dividing the spatially delocalized and localized modes is indicated  by a black dash-dotted line. The highest occupied mode in the $\\downarrow$ ground state for $N = 20$ and $N = 60$ is indicated by the green and red solid lines, respectively.}\n    \\label{fig:harmonic_trap}\n\\end{figure*}\n\n\\begin{figure*}\n    \\includegraphics[width=0.95\\linewidth]{fig_harmonic_MB.pdf}\n    \\label{fig:harmonic_trap_MB1}\n    \\caption{Dynamics of interacting spin-orbit  coupled fermions in a 1D lattice plus a harmonic trap for $U/J = 1$ (a), 2 (b), and 4 (c). For a 1D lattice with 10 sites and an SOC angle $\\phi = \\pi/50$, we apply a $\\pi/2$ clock laser pulse to the $\\downarrow$ ground state and let the system evolve during the dark time. In (a.i)-(c.i) we show the squeezing dynamics of the system for both $N = 10$ (solid lines) and $N = 9$ (dashed lines) for a variety of trapping strengths. In (a.ii)-(c.ii), we plot the time-averaged fluctuations in total particle density, $\\overline{\\delta n_j}$ (as in Eqn.~\\eqref{eq:time_avg_fluc} but with $\\hat{n}_{j,\\uparrow}$ replaced by $\\sum_{\\alpha}\\hat{n}_{j,\\alpha}$). In (a.iii)-(c.iii), we plot the growth of the doublon population $N_d(t)$ (see Eqn.~\\eqref{eq:doublon}) as a function of time, noting the absence of squeezing in the presence of a large doublon population. For the chosen trap strengths, the corresponding values of $n_c$ are 28 ($\\Omega/J = 0.01$), 14 ($\\Omega/J = 0.04$), and 6 ($\\Omega/J = 0.2$). In panels where the results for the homogeneous case (orange curves) are not visible, they are nearly identical to the results for $\\Omega/J = 0.01$ (green curves). Here, we utilize periodic boundary conditions to minimize finite size effects.}\n    \\label{fig:harmonic_trap_MB}\n\\end{figure*}\n\nCurrent 3D optical lattice implementations involve a harmonic confining potential, which significantly alters the underlying single-particle eigenstructure and can potentially degrade accessible squeezing within our protocol. In this appendix, we examine the effect of a harmonic trap on our protocol and discuss strategies to mitigate undesired effects. We model the trap by the addition of the term\n\\begin{align}\n    \\hat{H}_{\\Omega} = \\hbar\\Omega\\sum_{j,\\alpha}(j-j_0)^2\\hat{n}_{j,\\alpha}\n\\end{align}\nto our Fermi-Hubbard model (Eqn.~\\eqref{eq:FermiHubbard}), where $j_0$ denotes the trap center and $\\Omega = m(\\omega a)^2/2\\hbar$ characterizes the trap strength for atom mass $m$, trap frequency $\\omega$, and lattice spacing $a$. In current state-of-the-art 3D $^{87}$Sr OLC implementations, values of $\\omega \\approx 56 \\times 2\\pi~\\t{sec}^{-1}$ can be achieved within each 2D layer of weak SOC by utilizing in-plane lattice depths of $5 E_R$ and a lattice depth of $60 E_R$ in the axial direction, resulting in a value of $\\Omega/J \\approx 0.01$. We restrict our discussion to 1D, although for a separable 3D lattice our arguments should extend in a straightforward manner.\n\nWe briefly review the structure of the single-particle eigenstates of the system, before discussing the effects on squeezing. In the quasi-momentum basis, the eigenfunctions $\\psi_{n,\\alpha}(q) = \\braket{q|n,\\alpha}$ are given by the $\\pi$-periodic Mathieu functions, with the corresponding energies described by the Mathieu characteristic values\\cite{rey2005ultracold}. In the presence of SOC, using  the gauge transformation described in the main text, we obtain the relation\n\\begin{gather}\n    \\psi_{n,\\uparrow}(q) = \\psi_{n,\\downarrow}(q-\\phi/a).\n    \\label{eq:trap_states}\n\\end{gather}\nIn contrast to the case of a pure harmonic potential, which generically has spatially delocalized single-particle eigenstates, the addition of a tight-binding lattice causes eigenmodes with quantum number $n$ (index $n$ labels the eigenvalues in order of increasing energy) larger than $n_c \\approx 2\\sqrt{2J/\\Omega}$ to become localized at corresponding lattice sites. Therefore the  sites at a distance $n_c/2$ from the trap center with  potential energy $2\\hbar J$ define  the boundary between the delocalized modes at the trap center and the high-energy localized trap edges. Tunneling in the region of  localized modes is typically suppressed by large potential energy differences even in the presence of SOC. These modes are thus largely decoupled and do not contribute to the trap center dynamics. On the other hand the delocalized modes may be approximated by those of a quantum harmonic oscillator with effective mass $m^{*} = \\hbar/(2Ja^2)$ and frequency $\\omega^* = \\sqrt{4J\\Omega}$.\n\nAs emphasized in the main text, the key requirements for our protocol are 1) the validity of the spin model, which depends on the pinning  of particles in their initial single particle modes, and 2) the gap protection against SOC dephasing, which arises from collective spin interactions. Concerning the latter point, it is desirable to maintain a weak trap so as to enable a large number of delocalized modes in the trap center, which are the only type capable of contributing to the generation of squeezing. Though the interactions between these modes are not strictly all-to-all, they remain long-ranged, and can thus still lead to a spin-locking effect and a protective gap\\cite{rey2014probing, smale2019observation}. For $\\Omega/J = 0.01$ we have $n_c = 28$, enabling $\\sim10^3$ contributing modes in each 2D layer of our system. Concerning the validity of the spin model, from a single-particle perspective the eigenmodes  of our $\\uparrow$ states will be initially displaced in quasi-momentum space from equilibrium by $\\phi/a$ as per Eqn.~\\eqref{eq:trap_states}, and will generally undergo dipole oscillations and not remain strictly pinned to their initial modes. However, as long as we ensure the displacement is small enough to guarantee  a constant density distribution across  the  trap center, the  spin model will remain valid. The localized modes at the trap edges can  actually help to satisfy this condition, since they can serve as a barrier against motion. This is demonstrated in Fig.~\\ref{fig:harmonic_trap} where we show that filling all delocalized modes guarantees that the trap center maintains a constant density; we characterize this by the time-averaged fluctuations of the $\\uparrow$ density at each site $j$ about its initial value following the Ramsey pulse,\n\\begin{align}\n    \\overline{\\delta n_{j,\\uparrow}} \\equiv \\sqrt{\\lim_{t\\to\\infty}\\frac{1}{t}\\int_0^t \\d\\tau \\bigg(\\langle\\hat{n}_{j,\\uparrow}(\\tau)\\rangle - \\langle\\hat{n}_{j,\\uparrow}(0)\\rangle\\bigg)^2},\n    \\label{eq:time_avg_fluc}\n\\end{align}\nchoosing sufficiently large evolution times to ensure convergence.\n\nIn the presence of interactions, an additional point of concern is that the interplay between the trap and interactions may induce resonances that enable the formation of a significant doublon population,\n\\begin{align}\n    N_d(t) = \\sum_j \\langle\\hat{n}_{j,\\uparrow}(t)\\hat{n}_{j,\n    \\downarrow}(t) \\rangle,\n    \\label{eq:doublon}\n\\end{align}\nwhich in turn may alter the density distribution and invalidate the spin model. Since doublon formation in the localized edges will not have consequences for our squeezing protocol, we must only ensure that doublons are not formed in the trap center, which requires $U > \\Omega (n_c/2)^2 = 2J$\\cite{pupillo2006extended}. In Fig.~\\ref{fig:harmonic_trap_MB}, we perform exact simulations to assess the effect of the trap on our system. Though restricted to small system sizes, the results demonstrate that for $U/J \\lesssim 2$, the trap will always lead to a decrease of squeezing due to the formation of doublons in the trap center, while for $U/J \\gtrsim 2$, we are protected from this process even for trap strengths much stronger than the experimentally relevant ones.\n\n\n\\section{Accounting for $p$-wave inelastic collisions}\n\\label{sec:inelastic_collision}\n\\setcounter{figure}{0}\n\n\\begin{figure}[t]\n\\centering\n\\includegraphics[width=0.4\\textwidth]{rates.pdf}\n\\caption{\n{\\bf $p$-wave loss rates}.\nBoth the averaged $p$-wave inelastic collision rate $\\gamma$ (orange) and the ratio of this collision rate to the optimal squeezing rate $\\chi_{\\text{opt}}$ (blue) are suppressed as the lattice depth increases.\n$\\chi_{\\text{opt}}$ is obtained by choosing SOC angles $\\phi$ that saturate $\\widetilde{B}/U\\approx0.05$, where $\\widetilde{B}$ is the variance of the SOC-induced axial field and $U$ is the two-atom on-site interaction energy.\n}\n\\label{fig:inelastic_rates}\n\\end{figure}\n\n\\begin{figure*}[t]\n\\centering\n\\includegraphics[width=0.7\\textwidth]{inelasticPlot.pdf}\n\\caption{\\textbf{Squeezing via OAT in the presence of inelastic collisions}.\n(a) For fixed particle number $N=100$, the optimal squeezing decreases as the inelastic collision rate increases.\nPanel (b) shows squeezing over time for $\\gamma/\\chi_{\\text{opt}}=0.04$ (solid lines), which corresponds to $U/J=6$,\nand compares it with $\\gamma=0$ (dashed lines) for  different particle numbers.\nInelastic collisions prevent the growth of optimal squeezing with particle number.\nFor $N=1000$, the maximum squeezing saturates to $\\sim 10$ dB.\n}\n\\label{fig:inelastic_squeezing}\n\\end{figure*}\n\nInelastic $^{3}\\text{P}_{0}$ (electronic state $e$ or $\\up$) collisions are detrimental for optical lattice clocks. For the  nuclear-spin-polarized gas discussed in this work, $ee$ losses are only possible via the $p$-wave scattering channel since $s$-wave collisions are suppressed by Fermi statistics. The big advantage here compared to  prior experiments done in a 1D lattice at $\\mu$K temperature\\cite{martin2013quantum} is that in a Fermi  degenerate  gas loaded in a 3D optical lattice, $p$-wave losses are further suppressed by the centrifugal barrier and Pauli blocking, and only happen through a wave-function overlap between atoms at different lattice sites.  In this appendix, we quantify the effect of $p$-wave interactions on squeezing. To account for $p$-wave losses, we describe the dynamics  using a master equation for the system's density matrix $\\hat{\\rho}$:\n\\begin{align}\n  \\frac{d\\hat{\\rho}}{dt}\n  = -\\frac{i}{\\hbar} [\\hat{H}_{\\text{eff}},\\,\\hat{\\rho}]\n  + \\mathcal{L}\\hat{\\rho},\n\\end{align}\nwhere $\\hat{H}_{\\text{eff}}=\\chi\\hat{S}_z^2$ is the effective one-axis twisting Hamiltonian obtained from  the original Fermi-Hubbard Hamiltonian with spin-orbit coupling, and $\\mathcal{L}$ is the Lindblad superoperator that accounts for $p$-wave $ee$ inelastic collisions. This latter term can be written using a pseudo-potential approximation as\\cite{rey2014probing}:\n\\begin{multline}\n  \\mathcal{L}\\hat\\rho\n  = \\sum_{{\\bm k}{\\bm k'}} \\Gamma_{{\\bm k}{\\bm k'}}\n  \\bigg[\\hat{A}_{{\\bm k}{\\bm k'}}\n  \\hat\\rho\\hat{A}_{{\\bm k}{\\bm k'}}^\\dag \\\\\n  - \\f12 \\p{\\hat{A}_{{\\bm k}{\\bm k'}}^\\dag \\hat{A}_{{\\bm k}{\\bm k'}} \\hat\\rho\n+\\hat\\rho\\hat{A}_{{\\bm k}{\\bm k'}}^\\dag \\hat{A}_{{\\bm k}{\\bm k'}}}\\bigg],\n\\end{multline}\nwhere the jump operators are $\\hat{A}_{{\\bm k}{\\bm k'}}=\\hat{c}_{{\\bm k},\\up}\\hat{c}_{{\\bm k'},\\up}$, and\n$\\bm k$, $\\bm k'$ sum over all the populated quasi-momentum modes. The decay matrix elements $\\Gamma_{{\\bm k}{\\bm k'}}$ are given by:\n\\begin{align}\n  \\Gamma_{{\\bm k}{\\bm k'}}\n  = \\frac{3\\pi \\hbar b_{\\text{im}}^3 }{m} \\p{\\int d{\\bm r}^{\\,3}\n    W[\\phi_{{\\bm k}}({\\bm r}),\\phi_{{\\bm k'}}({\\bm r})]},\n\\end{align}\nwhere $b_{\\text{im}} = 121 a_0$\\cite{zhang2014spectroscopic, goban2018emergence} is the $p$-wave inelastic scattering length (with $ a_0=5.29\\times 10 ^{-11}$ m the Bohr radius), $\\phi_{{\\bm k}}({\\bm r})$ is the Bloch function with quasi-momentum ${\\bm k}$, and\n\\begin{multline}\n  W\\sp{\\phi_{{\\bm k}}({\\bm r}),\\phi_{{\\bm k'}}({\\bm r})} \\\\\n  \\equiv \\sp{\\p{{\\bm \\nabla}\\phi^{*}_{{\\bm k}}(\\bm r)}\n  \\phi^{*}_{{\\bm k'}}(\\bm r)-\\phi^{*}_{{\\bm k}}(\\bm r)\n  \\p{{\\bm \\nabla}\\phi^{*}_{{\\bm k'}}(\\bm r)}} \\\\\n  \\cdot\\sp{\\p{{\\bm \\nabla}\\phi_{{\\bm k}}(\\bm r)}\n  \\phi_{{\\bm k'}}(\\bm r)-\\phi_{{\\bm k}}(\\bm r)\n  \\p{{\\bm \\nabla}\\phi_{{\\bm k'}}(\\bm r)}}\n\\end{multline}\n\nIn Fig.~\\ref{fig:inelastic_rates}, we show the averaged decay rate $\\gamma\\equiv\\sum_{{\\bm k}{\\bm k'}}\\Gamma_{{\\bm k}{\\bm k'}}/\\ell^2$, where $\\ell$ is the number of lattice sites along the $x$ and $y$ axes, as a function of the lattice depth $V_0$ along these axes.\nHere, we assume the same lattice depth in the $z$ direction used in the main text, $V=60E_{\\text{R}}$.\nThe decay rate $\\gamma$ is suppressed exponentially with increasing lattice depth  $V_0$.\nTo quantify the effect of these losses on the spin squeezing generation process, we follow a similar methodology to the one described in detail in Ref.~\\cite{rey2014probing}.\nThe basic idea is to take advantage of the so-called Truncated-Wigner Approximation (TWA)\\cite{polkovnikov2010phase, schachenmayer2015manybody}, which allows us to capture the development of spin squeezing using semi-classical phase-space methods.\nIn the TWA the quantum dynamics are accounted for by solving mean field equations of motion supplemented by noise.\nThe mean field equations are  derived by assuming that the many-body density matrix of the system can be factorized as\n$\\hat{\\rho}= \\bigotimes_{i} \\hat{\\rho}({i})$, where $\\hat{\\rho}(i)$ is the reduced density matrix of the  particle in quasi-momentum  mode  ${\\bm q}_i$ [see Eqn.~\\eqref{eq:decay_matrix}].\nUnder this assumption, the non-linear mean field equations are given by\n\\begin{align}\n  \\frac{d\\rho_{\\up\\up}(j)}{dt}\n  = -\\sum_{j'}\\Gamma_{{\\bm k}_j{\\bm k}_{j'}}\n  \\rho_{\\up\\up}(j) \\rho_{\\up\\up}(j'),\n  &&\n  \\frac{d\\rho_{\\dn \\dn}(j)}{dt}=0\n\\end{align}\nand\n\\begin{multline}\n  \\frac{d\\rho_{\\up\\dn}(j)}{dt}\n  = \\rho_{\\up\\dn}(j) \\sum_{j'}\n  \\bigg[i\\chi(\\rho_{\\up\\up}(j')-\\rho_{\\dn\\dn}(j')) \\\\\n  - \\f12 \\Gamma_{{\\bm k}_j{\\bm k}_{j'}} \\rho_{\\up\\up}(j')\\bigg],\n\\end{multline}\nwhere $\\rho_{\\sigma\\sigma'}\\equiv\\langle\\hat{\\rho}_{\\sigma\\sigma'}\\rangle$.\nSince we are interested in the collective behavior, one can define $\\rho_{\\sigma\\sigma'}^T=\\sum_j \\rho_{\\sigma\\sigma'}(j)$. For these observables the equations of motion simplify to\n\\begin{align}\n  \\frac{d\\rho_{\\up\\up}^T}{dt} = -f\\gamma  (\\rho_{\\up\\up}^T)^2,\n  &&\n  \\frac{d\\rho_{\\dn \\dn}^T}{dt} = 0\n\\end{align}\nand\n\\begin{align}\n  \\frac{d\\rho_{\\up\\dn}^T}{dt}\n  = \\rho_{\\up\\dn}^T\n  \\sp{i\\chi(\\rho_{\\up\\up}^T-\\rho_{\\dn\\dn}^T)\n    - \\f12 f\\gamma \\rho_{\\up\\up}^T},\n\\end{align}\nwhere $f\\equiv N/\\ell^2$ is the filling fraction.\n\nUnder the TWA, one accounts for quantum fluctuations during the dynamics by  averaging over different mean field trajectories generated by sampling over different initial conditions chosen to reconstruct the Wigner function of the initial coherent spin state at $t=0$\\cite{rey2014probing}.\nThis method has proven to be successful in simulating quantum spin dynamics.\nUsing this approach, Fig.~\\ref{fig:inelastic_squeezing} shows numerical simulation results of squeezing over time in the presence of inelastic collisions.\nFor shallow lattices ($V_0\\lesssim7E_{\\t{R}}$), the effect of inelastic collisions can limit the spin squeezing to $\\sim10$ dB.\nThus, in this regime, losses are as relevant as light scattering.\nThe role of inelastic interactions could be mitigated by either operating at deeper lattices as shown in Fig.~\\ref{fig:inelastic_squeezing}, or by using nuclear spin states to generate the squeezing instead of the clock states directly.\n\n\n\\bibliography{main.bib}\n\n\\end{document}\n", "meta": {"hexsha": "8b0a107b64017e9eff6cc9a1eebd22f573c8097e", "size": 91463, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "soc_squeezing/squeezing_paper/main.tex", "max_stars_repo_name": "perlinm/rey_research", "max_stars_repo_head_hexsha": "491d1d33cc8d20dc1b72de552ac7c1b65fb3ee63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "soc_squeezing/squeezing_paper/main.tex", "max_issues_repo_name": "perlinm/rey_research", "max_issues_repo_head_hexsha": "491d1d33cc8d20dc1b72de552ac7c1b65fb3ee63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "soc_squeezing/squeezing_paper/main.tex", "max_forks_repo_name": "perlinm/rey_research", "max_forks_repo_head_hexsha": "491d1d33cc8d20dc1b72de552ac7c1b65fb3ee63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 89.6696078431, "max_line_length": 1790, "alphanum_fraction": 0.736472672, "num_tokens": 26444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.314150807917908}}
{"text": "% This is a simple template for an iSIM LaTeX lab using the \"article\" class. Read both the text and the comments--everything is useful!\n\n\\documentclass[11pt]{article} % use larger type; default would be 10pt\n\n% There's a lot of boilerplate crap that you don't need to understand\n\\usepackage[utf8]{inputenc}\n\n% These are packages you may need... It doesn't cost anything to include them all, so you might as well.\n\\usepackage{amstext} %allows you to put text in math mode\n\\usepackage{amsmath} %includes lots of math-related capabilities\n\\usepackage{graphicx} %allows you to include pictures\n\\usepackage{float} %improves the use of floating objects (like picutes)\n\\usepackage{caption} %allows you to change caption styles on figures\n\\usepackage{epstopdf} %automatically converts EPS files (like from matlab)\n\\usepackage{hyperref} %allows you to include links\n\\usepackage{varioref} %requirement of fancyref\n\\usepackage{fancyref} %allows really nice looking and convienient references\n\\usepackage[section]{placeins} %makes your figures not float past section barriers\n\\usepackage{perpage} %restarts footnote numbering by page\n\\usepackage[margin=1in, paperwidth=8.5in, paperheight=11in]{geometry} %I'll bet you can figure this one out\n\\MakeSorted{figure} %deals with figures using both [h] and [H]\n\n% Makes sure your document compiles when you screw up the references\n\\vrefwarning\n\n% Uncomment the following line to default all of your figures to [H] (explained later)\n%\\float­place­ment{fig­ure}{H}\n\n%add some metadata to the PDF produced\n % \\pdfinfo{/Author (Eric Miller)\n\n%%% The \"real\" document content comes below...\n\n\\title{Lab Report: Glucose monitor}\n\\author{Eric Miller}\n%\\date{Now} % Leave this commented to automatically display the current date. Otherwise, you can redefine it here.\n\n\\begin{document}\n\\maketitle % Make sure to include this (after begin{document}, or you'll have no title!\n\n%\\begin{abstract}\n%\\LaTeX~is a markup language (like HTML) that allows you to create beautiful lab reports (among other things) with a wide variety of STEM-oriented features. Like almost everything else, you can find out a lot about using \\LaTeX~by using Google. You can also have a look at the wikibook\\footnote{You can add links like so: \\href{http://en.wikibooks.org/wiki/LaTeX}{\\LaTeX~Wikibook} Have a look at that wikibook--it contains almost everything you'll ever need to know about \\LaTeX.} which is usually among the first few Google results for most \\LaTeX-related queries.\n%\\end{abstract}\n\n\\section{Voltage Source}\n\nHaving my younger siblings visiting for Family Weekend, I asked them to find a pair of resistors ending in \"k\" with a ratio of approximately $2:3$. The resulting resistor values were nominally $4 k\\Omega$ and $6.04 k\\Omega$, for a theoretical voltage divider output of \n$$5V*\\frac {4 k\\Omega} {4 k\\Omega + 6.04 k\\Omega} = 1.992 V$$\n\nThe actual measured value was slightly lower, at $1.97V$, but the difference wasn't significant enough to be a problem.\n\n%Note the use of \\Fref here... This automatically creates a reference to your figure, no matter where it is in the document. If it is on a different page, \\Fref will include the page of the figure. For this to work, you have to provide intelligent labels, i.e. fig:whatever for figures. Labels should be lowercase and have no spaces.\t\n\n%the [!ht] here means \"LaTeX, I would very much like you to put this figure here, but if you can't that's ok, just make sure it's at the top of some other page\"\n% However, because you (what a smart cookie you are) decided to include the float package, you can use the option [H], which tells LaTeX \"PUT THE ****ing FIGURE HERE OR I WILL GO BACK TO USING WORD YOU GODDAMN STUPID PIECE OF **** TYPESETTING PROGRAM\" \n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=.7\\textwidth]{CD1.PNG}\n\t\\caption{Voltage Divider circuit}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t%instead of entering the width in terms of textwidth, you can use a set number of inches, or pt, or mm, or whatever\n\t\\includegraphics[width=.7\\textwidth]{VoltageDivider.png}\n\t%Make sure to caption your figures! LaTeX will automatically number them for you.\n\t\\caption{Voltage Divider results}\n \t\\label{fig:awesome}\n\\end{figure}\n\n%You can make subsections (and subsubsections) if you need to go into detail\n\\section{Measure Resistance}\n !!! NEED THEORY !!!\nFive resistor values were tested, as shown below. For each resistor, the current it theoretically allowed was calculated as $\\frac {1.976V} {[Resistance]}$, also in the table.\n\\begin{table}[H]\n\\centering\n\\caption{Resistor testing data}\n\\begin{tabular}{lll}\nResistance & Calculated Current (mA) & Measured voltage \\\\\n604        & 3.272                   & 4.96             \\\\\n4000       & 0.494                   & 3.75             \\\\\n20000      & 0.099                   & 2.74             \\\\\n60000      & 0.033                   & 2.54             \\\\\n249000     & 0.008                   & 2.50            \n\\end{tabular}\n\\end{table}\n\nShown here is a plot of the Currents and measurements for the lower four rows in the table, those with less than $1mA$ theoretical current flow. As expected, the data points fall nicely along a line, giving an accurate way to measure small currents. (\\Fref{fig:some})\n\nUnfortunately, the $604\\Omega$ resistor proved to allow more current to pass than the system could reliably measure, as seen by the fact that its data point falls well off the line. (\\Fref{fig:current})\n\n\n\n\\begin{figure}[]\n\t\\centering\n\t\\includegraphics[width=\\textwidth]{4points-current.png}\n\t\\caption{Partial current measurement results}\n \t\\label{fig:some}\n\\end{figure}\n\n\\begin{figure}[]\n\t\\centering\n\t%instead of entering the width in terms of textwidth, you can use a set number of inches, or pt, or mm, or whatever\n\t\\includegraphics[width=\\textwidth]{5points-current.png}\n\t%Make sure to caption your figures! LaTeX will automatically number them for you.\n\t\\caption{Full current measurement results}\n \t\\label{fig:current}\n\\end{figure}\n\n\n\\section{Integrator }\n\nIn \\fref{fig:integrate}, the orange line charts the input to the circuit, and the blue line charts the output. Clearly, when the orange line is HIGH, the blue line rises and inversely. This is the expected behavior of an integrator.\n\n\\begin{figure}[H]\n\t\\centering\n\t%instead of entering the width in terms of textwidth, you can use a set number of inches, or pt, or mm, or whatever\n\t\\includegraphics[width=\\textwidth]{integrator.png}\n\t%Make sure to caption your figures! LaTeX will automatically number them for you.\n\t\\caption{Integrator testing results}\n \t\\label{fig:integrate}\n\\end{figure}\n\n\n\n\\section{Glucose sensor}\n\n\n The glucose monitor, as expected, produced substantially higher currents when the concentration of the glucose in the solution was higher. The raw data collected can be seen in\n \\fref{fig:gcurrent}, where concentrations are measured in mg/dL. \\Fref{fig:gcal} shows some values extracted from these curves, including the maximum amount of current measured, the current flow measured after 10 seconds, and the value of the integrator after 10 seconds (adjusted for the starting value).\n \n These results indicate that the maximum amount of current is a poor indicator of the concentration, with the points substantially deviating from a line. The integral of current is better, but still does not display quite as much regularity as the absolute current measurement after 10 seconds. This could be a measurement peculiarity from this specific trial. Further investigation is needed to determine whether some combination of these signals could be used to create an even more consistent measurement.\n\n\\begin{figure}[]\n\t\\centering\n\t%instead of entering the width in terms of textwidth, you can use a set number of inches, or pt, or mm, or whatever\n\t\\includegraphics[width=\\textwidth]{glucose_currents.png}\n\t%Make sure to caption your figures! LaTeX will automatically number them for you.\n\t\\caption{Time series data for various glucose concentrations}\n \t\\label{fig:gcurrent}\n\\end{figure}\n\n\\begin{figure}[]\n\t\\centering\n\t%instead of entering the width in terms of textwidth, you can use a set number of inches, or pt, or mm, or whatever\n\t\\includegraphics[width=\\textwidth]{glucose_calibration.png}\n\t%Make sure to caption your figures! LaTeX will automatically number them for you.\n\t\\caption{}\n \t\\label{fig:gcal}\n\\end{figure}\n\n\n\n\n\n\\end{document}\n\n\n\n", "meta": {"hexsha": "f29f05601debb2a435dbddbf457c1e3c1f9dc201", "size": 8368, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Lab report.tex", "max_stars_repo_name": "HALtheWise/iSIM-lab-6", "max_stars_repo_head_hexsha": "f5eea034b54ac366826bceb98ada0cc40e75018a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lab report.tex", "max_issues_repo_name": "HALtheWise/iSIM-lab-6", "max_issues_repo_head_hexsha": "f5eea034b54ac366826bceb98ada0cc40e75018a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lab report.tex", "max_forks_repo_name": "HALtheWise/iSIM-lab-6", "max_forks_repo_head_hexsha": "f5eea034b54ac366826bceb98ada0cc40e75018a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.3, "max_line_length": 565, "alphanum_fraction": 0.7516730402, "num_tokens": 2105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.3141508004314963}}
{"text": "\\section{Related Work} \\label{sec:RelatedWork}\n\nMost of the parallelization of LCS on most multi-core platforms\nfocuses on {\\em wavefront} parallelism.  The wavefront method keeps\nthe computation as a wavefront that sweep through the entire dynamic\nprogramming tables.  The wavefront computation is {\\em not}\ncache-friendly, i.e., the wavefront algorithm cannot effectively keep\nthe required data in cache.  To address this cache issue, Maleki et\nal.~\\cite{Maleki2016EfficientPU} developed a technique to exploit more\nparallelism in the dynamic programming.\n\nThe alternative to wavefront method is the traditional row-by-row\napproach, in which the dynamic programming tables is built in a\nrow-by-row manner.  For example, Peng~\\cite{Peng2011TheLC} gives a\n$O(nm \\alpha(n))$ VGLCS algorithm that is easy to implement and an\nasymptotically better $O(nm)$ algorithm, where $\\alpha$ is the inverse\nof Ackermann's function~\\cite{Banachowski1980ACT}.\n\nIt is difficult to parallelize traditional row-by-row approach for VGLCS\ndue to the difficulty in efficient suffix and range query in a parallel\nenvironment.  Peng's sequential VGLCS algorithm uses disjoint sets by\nGabow~\\cite{Gabow1983ALA} and Tarjan~\\cite{Tarjan1975EfficiencyOA} for\nsuffix maximum query.  We instead use {\\em sparse\ntable}~\\cite{Berkman1993RecursiveSP} to support incremental suffix/range\nmaximum queries in our VGLCS algorithm.  The sparse table is simple to\nimplement and provides sufficient parallelism for good performance in a\nparallel environment.\n\nFischer~\\cite{Fischer2006TheoreticalAP} proposed blocked sparse table\nfor better performance than the unblocked sparse\ntable~\\cite{Berkman1993RecursiveSP}.  We also adopted blocked sparse\ntable and tested its implementation in our experiments.  Fischer's\nalgorithm~\\cite{Fischer2006TheoreticalAP} builds least ancestor tables\nfor answering range maximum query.  We instead use a {\\em\nrightmost-pops} encoding for Cartesian trees.\n\nDemaine~\\cite{Demaine2009OnCT} also proposed {\\em cache-aware}\noperations on Cartesian tree~\\cite{Vuillemin1980AUL}, to address the\ncache miss issues in Fischer's least common ancestor table\nbuilding~\\cite{Fischer2006TheoreticalAP}.  Masud~\\cite{Hasan2010CacheOA}\npresents a new encoding method that reduces the number of instructions.\nOur rightmost-pops encoding for Cartesian trees also reduces cache\nmisses, and with a much simpler implementation than Demaine's encoding.\n\nFinally the authors would like to point out that to the best of our\nknowledge, we are not aware of any {\\em dynamic} encoding for Cartesian\ntrees.  All previous works are {\\em off-line}, i.e., they assume all\ndata are given in advance, as a result, they cannot cope with\nincrementally added data.  In contrast, our dynamic Catalan index\ncomputation technique in Section~\\ref{sec:dynamic} does support\nefficient range query on an incremental data sets.\n", "meta": {"hexsha": "144a46f184a2e82c19c53574ca150ed2bb56d30c", "size": 2880, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/IEEE/partial/related-en.tex", "max_stars_repo_name": "morris821028/parallel-VGLCS", "max_stars_repo_head_hexsha": "87fe1c71e14cf7ed6092f728b085b735cf683a4b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-02-11T08:45:21.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-22T07:30:24.000Z", "max_issues_repo_path": "doc/IEEE/partial/related-en.tex", "max_issues_repo_name": "morris821028/parallel-VGLCS", "max_issues_repo_head_hexsha": "87fe1c71e14cf7ed6092f728b085b735cf683a4b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-02-21T02:01:16.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-24T00:13:34.000Z", "max_forks_repo_path": "doc/IEEE/partial/related-en.tex", "max_forks_repo_name": "morris821028/parallel-VGLCS", "max_forks_repo_head_hexsha": "87fe1c71e14cf7ed6092f728b085b735cf683a4b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.3846153846, "max_line_length": 72, "alphanum_fraction": 0.8114583333, "num_tokens": 705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3138783160255456}}
{"text": "\\section{Background on LDA}\n\\label{sec:background}\n\n%------------------------------------------------\n\nTopic modeling, a form of latent variable modeling, is an unsupervised machine learning method which attempts to recreate the distribution of so-called ``topics'' an author used to generate a corpus of documents.\nThe term topic is used to describe a frequency distribution of terms within a vocabulary.\nIn this use, a topic can be understood to represent an academic concept covered within the context of a course.\nThis is based on the assumption that the words used in a course description when introducing the course's topics are the same words used within descriptions of the topic itself.\nThe topics discovered in a corpus can be used to categorize documents and provide structure to an otherwise unknown dataset.\n\n%------------------------------------------------\n\n\\acf{lda} is a specific type of topic modeling which assumes that a mixture of multiple topics exist within a single document in some proportion (\\ie\\ were used to generate that document)~\\cite{Blei2003}.\n\\ac{lda} assumes a generative process where, for each word in the document, the algorithm selects a distribution over topics, selects a topic, and then selects a vocabulary term~\\cite{Blei2003}.\nReversing this generative process is significantly more difficult because the topic distributions are unknown; these unknown information is what the ``hidden model'' or ``latent model'' refers to.\n\n%------------------------------------------------\n\nThe computation \\ac{lda} performs is the determination of the topic distributions over a set of documents.\nGiven the set of documents as input, generating the corpus topics is a probabilistic process.\nTaking the variables $\\theta_{d,k}$ (topic proportion for topic $k$ in document $d$), $\\beta_{1:k}$ (topic $k$), $z_{d,n}$ (topic assignment for word $n$ in document $d$), and $w_{d,n}$ (the $n^{th}$ word in document $d$), \\ac{lda} estimates the posterior probability in \\eref{eq:posterior}~\\cite{Blei2012}.\n\n%------------------------------------------------\n\n\\begin{equation}\np(\\beta_{1:K}, \\theta_{1:D},z_{1:D} | w_{1:D}) = \\frac{\\beta_{1:K},\n\\theta_{1:D},z_{1:D}, w_{1:D}}{w_{1:D}}\n\\label{eq:posterior}\n\\end{equation}\n\n%------------------------------------------------\n\n\\noindent\nGibbs Sampling is used to estimate the denominator (\\ie\\ the evidence)~\\cite{Blei2003}.\nRunning \\ac{lda} over a document set results in a usable set of vocabulary frequency distributions or topics for each document.\n\n%------------------------------------------------\n\nA graphical ``plate'' diagram of \\ac{lda}'s generative process is given in \\fref{fig:lda-plates}, adapted from~\\cite{Blei2003}.\nCircular nodes represent random variables while rectangular plates represent duplication.\nThe shaded node is the only observed (\\ie\\ evidence) variable, words from the document set.\n\n%------------------------------------------------\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=0.45\\textwidth]{figures/lda-plates}\n  \\caption{LDA graphical diagram adapted from~\\cite{Blei2012}\\label{fig:lda-plates}.}\n\\end{figure}\n\n%------------------------------------------------\n\n\\subsection{Related Work}\n\\label{sec:related-work}\n\n%------------------------------------------------\n\nOur research complements other efforts within Computer Science education that are directed towards categorization of content to improve pedagogy, \\eg\\ Hubwieser et al.~\\cite{hubwieser2013}.\nWe believe that our project contributes both, by identifying content (\\ie\\ topics) being taught across institutions and by identifying gaps and unique contributions.\nThis information can be compared to teacher competencies and used to design assessment and instruments to measure them.\nAnother area in which this work can assist is in identification of concepts and their classification, especially ``threshold concepts''~\\cite{ShinnersKennedyFincher2013}.\nOverall, we believe our data-driven approach complements other qualitative efforts by building on them and by automating some aspects of the research.\nThe work of~\\cite{airasian2001taxonomy} discusses a taxonomy related to learning breaking the process down along the cognitive process and knowledge dimensions.\nUsing a richer source of course information that course descriptions our proposed method could be adopted to learn concepts along these dimensions.\n\n%------------------------------------------------\n\nOther work has also attempted to extract concept information from course data.\nYang et al.\\ employ four distinct techniques to map courses into a conceptual space and then learn prerequisite relationships between similar courses~\\cite{Yang2015}.\nTwo of their conceptual mapping techniques generate latent features, which have the downside of not being human-readable as in \\ac{lda}.\nThe remaining two techniques generate human-readable topics, but rely either on an outside source (Wikipedia) or simply represent concepts as the vocabulary of the document.\nThe benefit of \\ac{lda} as an information retrieval tool is its ability to generate pseudo human-readable topics while acting in a fully unsupervised manner on a single, large data set.\nOur approach naively targets a dataset of fixed universities and customizes web scrapers specifically for their computer science departments.\nEffland et al.\\ introduces a robust web crawler system to automatically search for, identify, and extract course descriptions from disparate locations on the Internet~\\cite{Effland2015}.\nApplication of similar technology in this work was considered, and would greatly improve the scale of the analyzed data.\n\n%------------------------------------------------\n\n", "meta": {"hexsha": "d5fe2730ae7ceca24be318f77b6a702779b5d5e0", "size": 5683, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/paper/sections/background.tex", "max_stars_repo_name": "jrouly/trajectory", "max_stars_repo_head_hexsha": "1be2290e0d1c9158781281824c0e49bc1872f2b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2015-03-19T13:05:38.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-15T21:46:16.000Z", "max_issues_repo_path": "docs/paper/sections/background.tex", "max_issues_repo_name": "jrouly/trajectory", "max_issues_repo_head_hexsha": "1be2290e0d1c9158781281824c0e49bc1872f2b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/paper/sections/background.tex", "max_forks_repo_name": "jrouly/trajectory", "max_forks_repo_head_hexsha": "1be2290e0d1c9158781281824c0e49bc1872f2b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-02-18T15:38:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-10T23:52:51.000Z", "avg_line_length": 71.0375, "max_line_length": 307, "alphanum_fraction": 0.7191624142, "num_tokens": 1163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3138783160255456}}
{"text": "% !TEX root = ../00_thesis.tex\n\n\n%-------------------------------------------------------------------------------\n\\subsection{Simulated Worst-Case Performance}\n\\label{subsec:simulation}\n\nIn \\cref{subsec:perf_model}, we derived the optimal performance achievable according to our \\DRP's model.\nHowever, this model is based on a worst-case analysis of message latency throughout the system.\nBecause such an analysis is inherently pessimistic, it is important to estimate how pessimist the analysis is. In other words, how tight are the latency bounds given by the model?\nIn this section, we investigate this question using a discrete event simulation.\n\n\\fakepar{Procedure}\nWe simulate the run-time behavior of \\DRP using the values and parameters from our implementations~(\\cref{table:simulation_parameters}).\nThe simulation framework tracks the latency of each individual message through the entire system, \\ie all \\APs, \\CPs, \\bolt and the wireless communication network.\nConcretely, the simulation is implemented using Matlab scripts (openly available -- \\cref{append:drp_artifacts}).\n\n\\blink computes the round schedules assuming that the first message of each flow is available for communication at $t = 0\\s$. The actual epoch at which the  \\APs write the first packet of each flow is randomized between $0\\s$ and the flow's minimal message interval $T$; subsequent packets are sent with period $T$.\nThe random seed is fixed for reproduciblility.\n\n\\squarepar{%\n\t\\fakepar{Scenario}\n\tNode 1 acts as the sink and communicates with all other nodes in the network. As described in \\cref{sec:designDetailed}, \\DRP is initialized with a set of control flows $\\mathcal{F}_{control}$, which is necessary in order to register subsequent flows%\n}\n\\[\n\\mathcal{F}_{control} =\n\t\\left\\lbrace\n\t\\begin{tabular}{@{\\,}l@{\\,}}\n\t(1\\,, n\\,, \\periodany = 10\\s\\,, \\jitterany = 0\\s\\,, \\deadlineany = 30\\s )\\\\\n\t(n\\,, 1\\,, \\periodany = 10\\s\\,, \\jitterany = 0\\s\\,, \\deadlineany = 30\\s )\\\\\n\t\\end{tabular}\n\t\\right\\rbrace\n\\]\nfor $n \\in ($2$ .. $20$)$. In practice, such flows can also be used to send low-priority data (\\eg status data) regularly to the sink.\n\nAn event from the environment (\\eg a rock crack~\\cite{meyer2019IPSN}) is co-detected by nodes 2 to 5, which consequently emit a request for a new flow to the sink node. In order to transfer the event data as fast as possible, the message interval is chosen as small as possible\n(\\ie equal to $T_f^s$, the flushing interval of $\\cp$ -- Refer to \\eqref{eq:design_flush_period_source}, \\eqref{eq:design_round_period} and \\eqref{eq:ndeadline_constraint_period}),\n\\[\n\\mathcal{F}_{new} =\n\t\\left\\lbrace\n\t\\begin{tabular}{@{}l@{}}\n\t(n\\,, 1\\,, \\periodany = 1.074\\s\\,, \\jitterany = 0\\s\\,, \\deadlineany = 10\\s )\\\\\n\t\\end{tabular}\n\t\\right\\rbrace\n\\]\nfor $n \\in ($2$ .. $5$)$. We record the end-to-end latency of all packets during two minutes, during which about 900 messages are transmitted through the system.\n\n\\fakepar{Results}\n\\cref{fig:latency} shows the distribution of end-to-end latency of messages, shown as percentage of the analytical worst-case latency (given by \\cref{thm:delta}).\nWe see that a few messages indeed experience a latency up to 97\\,\\% of the analytic worst-case bound.\nThe simulation also indicates that, in many cases, the worst-case buffer sizes of $\\cp$ and \\bolt are reached.\nOverall, these results support our analysis of \\DRP. They show that our worst-case bounds are tight; therefore, we can conclude that the performance derived using \\DRP's model~(\\cref{subsec:perf_model}) is representative of the performance that can be truly guaranteed by the system.\n\n\n\\begin{figure}\n\t\\centering\n\t\\href{\\drpfig{Figure-11}}{%\n\t\\includegraphics[scale=1]{lat_simu}}\n\t\\caption{Distribution of end-to-end latency of messages, shown as percentage of the analytical worst-case latency.\n\t\t\\capt{Some messages experience a latency very close to their worst-case bound (97\\,\\%), which demonstrates the tightness of the analysis.}\n\t }\n\t\\label{fig:latency}\n\\end{figure}\n\n%-------------------------------------------------------------------------------\n\\subsection{Real-World Performance}\n\\label{subsec:flocklab}\n\n\\begin{table}\n\t\\caption{Flow sets used in the end-to-end latency evaluation of \\DRP.\n\t\\capt{The \\blink utilization is computed assuming a strictly periodic release of messages.}}\n\t{\\smaller\\input{\\PathTab/flow_set.csv}}\n\t\\label{tab:flow_set}\n\\end{table}\n\n% Some intro about why we do real tests\nWe now consider the performance of our implementation of \\DRP on embedded hardware: We use the first-generation DPP, which features a TI MSP432P401R as \\AP and a TI CC430F5147 as \\CP~(\\cref{append:dpp}).\nThe software is based on the publicly available implementation of LWB~\\cite{Code_LWB}; it is written in C and uses Contiki 2.7~\\cite{contiki} as operating system.\nThe implementation of \\blink on the \\AP is built upon~\\cite{acevedo2016Realtime}.\n%\nWe discuss our implementation performance in terms of memory usage, computation workload, and message latency.\n\n\\squarepar{%\n\t\\fakepar{Memory usage}\n\t\\DRP requires both \\AP and \\CP to store some state information related to the currently running flows, as well message queues and buffers. The available RAM on both processors is shown in \\cref{table:memory}.%\n}\n\nThe 64\\kB of the \\AP are largely sufficient; it would supports hundreds of flows. The \\CP is more limited: With a payload size of 32\\bytes, \\CP is capped to a maximum for 40 flows~(\\cref{table:memory}). For a regular node, this will likely be sufficient for most applications; however, on the host node, this seriously limits the scalability of the system.\n\nOne possible solution is to use the embedded external memory (128\\kB); this would solve the memory limitation issue, but it may also introduce additional delays, which are currently not accounted for. Or we could use another processor as \\CP with more than 4\\kB of RAM.\n\n\\begin{table}\n\t\\centering\n\t\\caption{Memory available and required for our implementation of \\DRP.\n\t\\capt{%\n\t\tThe difference between ``total'' and ``available''  memory corresponds to the memory taken by the firmware only. $L$ is the message payload.}\n\t}\n\t\\label{table:memory}\n\t{\\smaller\\input{\\PathTab/memory.csv}}\n\\end{table}\n\n\\pagebreak\n\n\\squarepar{%\n\t\\fakepar{Computation}\n\tThe most extensive computations in \\DRP are the computations of the \\blink schedules and admission tests. The evaluation of these computations on embedded hardware is discussed in depth in~\\cite{zimmerling2017Blink}.%\n}\n\nIn addition to \\blink computations, the \\APs must perform \\DRP admission tests. These are simple operations~(\\cref{thm:CP} and \\ref{thm:AP}) which can be implemented efficiently. In our experiments, an admission test takes typically around 30\\ms to complete (maximum observed execution time: 130\\ms).\n\n\\DRP admission tests are performed only once per flow (when a new flow is requested). Thus, we can conclude that the computational workload induced by \\DRP (in addition to \\blink) is negligible.\n\n\\afterpage{\n\\begin{figure}\n\t\\centering\n\t\t\\begin{subfigure}{\\linewidth}\n\t\t\t\t\\captionsetup{labelformat=empty}\n\t\t\t\t\\href{\\drpfig{Figure-12}}{%\n\t      \\includegraphics[scale=1]{lat_real_low}}\n\t\t\t\t\\caption{}\n\t\t\t\\end{subfigure}\\\\[10pt]\n\t\t\t\\begin{subfigure}{\\linewidth}\n\t\t\t\t\t\\captionsetup{labelformat=empty}\n\t\t\t\t\t\\href{\\drpfig{Figure-12}}{%\n\t\t      \\includegraphics[scale=1]{lat_real_medium}}\n\t\t\t\t\t\\caption{}\n\t\t\t\t\\end{subfigure}\\\\[10pt]\n\t\t\t\t\\begin{subfigure}{\\linewidth}\n\t\t\t\t\t\t\\captionsetup{labelformat=empty}\n\t\t\t\t\t\t\\href{\\drpfig{Figure-12}}{%\n\t\t\t      \\includegraphics[scale=1]{lat_real_high}}\n\t\t\t\t\t\t\\caption{}\n\t\t\t\t\t\\end{subfigure}\n  \\caption{%\n\tDistribution of end-to-end latency of messages, shown as percentage of the analytical worst-case latency for a \\DRP run using different flow sets~(\\cref{tab:flow_set}).\n\t\\capt{%\n\tTop -- Low utilization.\n\tMiddle -- Medium utilization.\n\tBottom -- High utilization.}\n  }\n  \\label{fig:lat_real_all}\n\\end{figure}\n}\n\n\n\\fakepar{End-to-end latency}\nWe investigate the experienced end-to-end latency of messages. We use a network of 10 source nodes and one host, and run experiments on the FlockLab testbed~\\cite{lim2013FlockLab}. In addition to the control flows, each source node request a data flow toward the host with a pseudo-random period and end-to-end deadline.\nOnce the flow is admitted, the source \\APs release new packets periodically.\nThe different flow sets used are listed in \\cref{tab:flow_set}. \\DRP is configured with a deadline ratio $r=0.5$, a round length $\\rlength = 1\\s$, and a maximum of $\\nslotsmax = 5$ slots per round.\n\n\n\\begin{table}\n\t\\centering\n\t\\caption{Experienced latency of messages, expressed as percentage of the flow's end-to-end deadline.\n\t\\capt{The tightness correspond to the ratio of the experienced latency with the analytical upper-bound given by~\\cref{thm:delta}.}}\n\t{\\smaller\\input{\\PathTab/latency.csv}}\n\t\\label{tab:latency}\n\\end{table}\n\n\nThe results are summarized in \\cref{tab:latency} and \\cref{fig:lat_real_all}, reporting data from one run for each flow set.\nThe first observation is that all messages that are successfully transmitted over the wireless network do meet their end-to-end deadline.\nHowever, compared to the simulation experiment~(\\cref{subsec:simulation}), we do not encounter so much analytical corner cases: the observed latency is often much smaller than the analytical upper-bound~(\\cref{fig:lat_real_all}).\nOn the other hand, this means that the actual runtime performance is better that what is guaranteed: even with large end-to-end deadlines (around 60\\s), the experience message latency is most of the time between 5\\s to 15\\s.\n\nSuch ``short'' average latency can be explained by the nature of the flow set. The \\emph{network} deadline, enforced by \\blink, must be smaller than the flow period~\\cref{sec:designDetailed}. Since the period are small compared to the \\emph{end-to-end deadlines}, these end-to-end deadlines do not constraint the \\DRP contracts: the experience latency correlates with the flow period.\n\nIt is interesting to observe that the average end-to-end latency is smaller for the high utilization flow set than for the low and middle ones. Again, this is due to the flow set. To meet the network deadline, \\blink schedule at least one round per period. Thus, a flow set with shorter period results in more frequent rounds. Once a round is scheduled, it is filled with any message ready for transmission. Thus, flows are opportunistically served earlier than necessary to meet their end-to-end deadline. Conclusion: having a flow with a small period reduces the average latency experienced by all flows in the system. This is an interesting (and unforeseen) consequence of \\DRP mechanism.\n\n\\squarepar{%\n\t\\fakepar{Conclusions}\n\tThe performance evaluation presented in this section validates the design of \\DRP and our implementation: we showcased that we can run a wireless \\CPS that meet end-to-end deadlines between distributed applications~(\\cref{subsec:simulation} and \\ref{subsec:flocklab}).\n\tIn addition, we derived the theoretical optimal performance achievable based on \\DRP's model~(\\cref{subsec:perf_model}).%\n}\n\nA more thorough investigation of the actual system performance across different scenarios and environments remains to be performed.\nFor such a performance evaluation, using \\triscale~(\\cref{ch:triscale}) would be natural.\n%\nChronologically, \\triscale is the last piece of work of this dissertation. In hindsight, our evaluation of \\DRP appears a bit naive and simple. Still, we argue that it successfully demonstrates the soundness of \\DRP's design.% and supports our claims.\n", "meta": {"hexsha": "3a17c3f97c941bb60c1c753e9803f07127fc6daf", "size": 11598, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "40_DRP/7_eval_2-Performance.tex", "max_stars_repo_name": "romain-jacob/doctoral-theis", "max_stars_repo_head_hexsha": "fd21e9f0cddeda91821eb061c9ab12df9f610da9", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "40_DRP/7_eval_2-Performance.tex", "max_issues_repo_name": "romain-jacob/doctoral-theis", "max_issues_repo_head_hexsha": "fd21e9f0cddeda91821eb061c9ab12df9f610da9", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "40_DRP/7_eval_2-Performance.tex", "max_forks_repo_name": "romain-jacob/doctoral-theis", "max_forks_repo_head_hexsha": "fd21e9f0cddeda91821eb061c9ab12df9f610da9", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 64.4333333333, "max_line_length": 691, "alphanum_fraction": 0.7529746508, "num_tokens": 2921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621764862150636, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.3138783078344785}}
{"text": "\\documentclass{report}\n\\usepackage{graphicx}\n\n\\usepackage{amsmath}\n\\DeclareMathOperator*{\\argmax}{argmax}\n\n\\usepackage{hyperref}\n\\hypersetup{\n    colorlinks=true,\n    linkcolor=blue,\n    filecolor=magenta,      \n    urlcolor=cyan,\n}\n\n\\begin{document}\n\n\\title{Banana World Project Report}\n\\author{Denis Sergeev}\n\n\n\\section*{Problem definition}\n\nThe goal of the project was to create a RL Agent which is able to train from scratch by interacting with the Reacher (robot arm) environment for a series of episodes. During the episode the agent receives the environment state. The agent is able to perform some actions which may change the environment state.\n\n\\subsection*{Environment description}\n\nIn this environment, a double-jointed arm can move to target locations. A reward of \\(+0.1\\) is provided for each step that the agent's hand is in the goal location. Thus, the goal of the agent is to maintain its position at the target location for as many time steps as possible.\n\nThe observation space consists of 33 variables corresponding to position, rotation, velocity, and angular velocities of the arm. Each action is a vector with four numbers, corresponding to torque applicable to two joints. Every entry in the action vector should be a number between \\(-1\\) and \\(1\\).\n\nThe barrier for solving the problem is that all agents must get an average score of +30 (over 100 consecutive episodes). Specifically, after each episode, we add up the rewards that each agent received (without discounting), to get a score for each agent. This yields 20 (potentially different) scores. We then take the average of these 20 scores. This yields an average score for each episode (where the average is over all 20 agents).\n\n\n\\section*{Solution}\n\\subsection*{Deep Deterministic Policy Gradient Algorithm}\n\\subsubsection*{Network}\nThe DDPG algorithm uses two neural networks, an actor and a critic. Each one has two copies, a local and a target one. The Actor is trained to give the best possible action, given the current state of the environment. \\(s => a\\). The Critic is trained to give an estimate of the reward that'd be obtained if an action A is applied at the state \\(s\\). \\((s, a) => V\\) Local networks are trained to get the \"labels\" given by the target.\n\nBoth networks consist of fully connected units with batch normalization and ReLu activation. The input to the actor network is the environment state, which goes through 3 fully connected layers. The final activation function is \\(tanh\\), since the action value should be in-between \\(-1\\) and \\(1\\).\n\nThe input to the critic is the environment state, which goes through the first fully connected layer. After batch normalization and ReLu activation it is concatenated with the action tensor and goes through the remaining 2 layers.\n\n\\subsection*{Training}\n\\subsubsection*{Loss function and optimizing method}\n\nDDGP algorithm uses following loss function for critic network \\ref{critic-loss}:\n\\begin{equation} \\label{critic-loss}\nL \\equiv (R_t + \\gamma Q(S_{t+1}, a_{t+1}; \\theta'_t) - Q(S_t, a_t; \\theta_t))^{2}\n\\end{equation}\n\nWhere \\(Q(S_t, a_t; \\theta_t)\\) is output (value of action) of the critic network with internal parameters \\(\\theta_t\\) given input \\(S_t\\) and \\(a_t\\). \\(a_{t+1}\\) is obtained from \\(\\pi(S_t; \\eta'_t)\\) (target actor) prediction with internal parameters \\(\\eta'_t\\).\n\nActor loss function is following \\ref{actor-loss}:\n\\begin{equation} \\label{actor-loss}\nL \\equiv -(Q(S_t, \\pi(S_t; \\eta_t); \\theta_t))\n\\end{equation}\n\nBoth loss functions used 2 sets of network parameters: target \\(\\theta'_t\\), \\(\\eta'_t\\) and local \\(\\theta_t\\), \\(\\eta_t\\). Target network parameters are updating through soft update \\(\\theta'_t = (1 - \\tau) \\theta'_t + \\tau \\theta_t\\).\nAs optimizing method for both networks I used Adam with learning rate \\(\\alpha\\).\n\n\\subsubsection*{Experience replay}\nThe input for training did not come directly from episodes. Instead I used experience replay technique (see \\href{https://storage.googleapis.com/deepmind-media/dqn/DQNNaturePaper.pdf}{Human-level control through deep reinforcement learning}).\n\n\\subsubsection*{Exploratory noise}\nIn order to make the agent explore the environment DDPG algorithm adds noise in it actions during training. I used \\href{https://en.wikipedia.org/wiki/Ornstein-Uhlenbeck_process}{Ornstein–Uhlenbeck process} for this purpose.\n\n\n\\section*{Results}\n\nI came up using following training hyper parameters:\n\\begin{itemize}\n\t\\item Buffer size: 10e6\n\t\\item Batch size: 128\n\t\\item \\(\\gamma\\): 0.95\n\t\\item \\(\\tau\\): 0.001\n\t\\item \\(\\alpha_{actor}\\): 0.0001\n\t\\item \\(\\alpha_{critic}\\): 0.001\n\\end{itemize}\nThey were used across all training experiments below.\n\n\n\\subsection*{Training DDPG 128x256 128x256}\n\nDDPG actor: 128x256, critic 128x(256+31).\n\nTraining history:\n\nEpisode 10.\tAverage Score: 1.29.\tTime elapsed: 4:41\n\nEpisode 20.\tAverage Score: 2.01.\tTime elapsed: 9:22\n\nEpisode 30.\tAverage Score: 3.98.\tTime elapsed: 14:12\n\nEpisode 40.\tAverage Score: 8.78.\tTime elapsed: 19:10\n\nEpisode 50.\tAverage Score: 13.40.\tTime elapsed: 24:40\n\nEpisode 60.\tAverage Score: 16.83.\tTime elapsed: 29:54\n\nEpisode 70.\tAverage Score: 19.30.\tTime elapsed: 35:04\n\nEpisode 80.\tAverage Score: 21.39.\tTime elapsed: 40:21\n\nEpisode 90.\tAverage Score: 22.95.\tTime elapsed: 46:02\n\nEpisode 100.\tAverage Score: 24.32.\tTime elapsed: 51:54\n\nEpisode 110.\tAverage Score: 27.81.\tTime elapsed: 57:52\n\nEnvironment solved in 17 episodes!\tAverage Score: 30.10.\tTime elapsed: 62:04. See \\ref{fig:DDPG_128x256}.\n\n\\begin{figure}\n\t\\includegraphics[width=0.9\\linewidth]{res/ddpg_128x256/score.png}\n\t\\caption{DDPG 128x256: Rewards per episode}\n\t\\label{fig:DDPG_128x256}\n\\end{figure}\n\n\n\\subsection*{Training DDPG 128x128 128x128}\n\nDDPG actor: 128x128, critic 128x(128+31).\n\nEpisode 10.\tAverage Score: 0.48.\tTime elapsed: 2:00\n\nEpisode 20.\tAverage Score: 0.95.\tTime elapsed: 4:26\n\nEpisode 30.\tAverage Score: 1.47.\tTime elapsed: 7:16\n\nEpisode 40.\tAverage Score: 2.20.\tTime elapsed: 10:27\n\nEpisode 50.\tAverage Score: 3.02.\tTime elapsed: 13:59\n\nEpisode 60.\tAverage Score: 4.29.\tTime elapsed: 17:43\n\nEpisode 70.\tAverage Score: 5.77.\tTime elapsed: 21:24\n\nEpisode 80.\tAverage Score: 7.87.\tTime elapsed: 25:11\n\nEpisode 90.\tAverage Score: 9.93.\tTime elapsed: 29:02\n\nEpisode 100.\tAverage Score: 12.19.\tTime elapsed: 33:03\n\nEpisode 110.\tAverage Score: 15.77.\tTime elapsed: 37:09\n\nEpisode 120.\tAverage Score: 19.19.\tTime elapsed: 41:21\n\nEpisode 130.\tAverage Score: 22.43.\tTime elapsed: 45:05\n\nEpisode 140.\tAverage Score: 25.19.\tTime elapsed: 48:39\n\nEpisode 150.\tAverage Score: 27.81.\tTime elapsed: 52:17\n\nEpisode 160.\tAverage Score: 29.93.\tTime elapsed: 56:03\n\nEnvironment solved in 61 episodes!\tAverage Score: 30.14.\tTime elapsed: 56:25. See \\ref{fig:DDPG_128x128}.\n\n\\begin{figure}\n\t\\includegraphics[width=0.9\\linewidth]{res/ddpg_128x128/score.png}\n\t\\caption{DDPG 128x128: Rewards per episode}\n\t\\label{fig:DDPG_128x128}\n\\end{figure}\n\n\n\\subsection*{Conclusion}\n\nFrom the above results we can summarize, that actor: 128x256, critic 128x(256+31) networks architecture have better performance and learn faster than actor: 128x128, critic 128x(128+31). In overall DDPG algorithm performs very good in this environment.\n\n\n\\section*{Areas of improvement}\n\nI also tried to implement \\href{https://arxiv.org/pdf/1707.06347.pdf}{PPO algorithm}. I used some code form \\href{https://github.com/ShangtongZhang/DeepRL}{Shangtong Zhang DeepRL github repository} to build more intuition about PPO and be more confident in correct implementation. But implemented algorithm almost didn't perform. Seems like something is still wrong. PPO algorithm is said to be more stable and perform better.\n\nAnother improvement could be implementing \\href{https://arxiv.org/abs/1511.05952}{prioritized experience replay} in DDPG algorithm.\n\n\\end{document}\n", "meta": {"hexsha": "e64c4917cc19824f83c8d025f69776356db9b556", "size": 7798, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "robot_arm/report.tex", "max_stars_repo_name": "denmatfoton/reinforcement_learning", "max_stars_repo_head_hexsha": "788f95fca0b3cb67370539aaad7c5b28710d58a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-01T01:30:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-01T01:30:04.000Z", "max_issues_repo_path": "robot_arm/report.tex", "max_issues_repo_name": "denmatfoton/reinforcement_learning", "max_issues_repo_head_hexsha": "788f95fca0b3cb67370539aaad7c5b28710d58a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "robot_arm/report.tex", "max_forks_repo_name": "denmatfoton/reinforcement_learning", "max_forks_repo_head_hexsha": "788f95fca0b3cb67370539aaad7c5b28710d58a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.3068181818, "max_line_length": 436, "alphanum_fraction": 0.7577583996, "num_tokens": 2228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3138405685046137}}
{"text": "%\n% \n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\chapter{Fundamental Components in CPPINTS}\n%\n%\n%\nIn this chapter the fundamental component classes in CPPINTS will be discussed in \ndetail. These classes forms foundation for building the recurrence\nrelation(RR).\n\n\\section{Basis Set}\n%\n% 1  what's the form of basis sets?\n% 2  why in basis set class we only store l,m,n information?\n%\n\\label{bs}\n\nIn quantum chemistry, the basis set functions is the fundamental \nunit for practical calculations\\cite{Davidson_Feller_CR_86_681_1986}. \nPrimarily the basis set functions can be divided into radial part\nand angular part. The radial part for the basis set function we discuss\nin CPPINTS is formed by Gaussian functions, and the angular part could \nbe further divided into two groups in terms of its function form.  \nOne group uses the spherical harmonics:\n\\begin{equation}\n \\chi = Y_{m}^{L}(\\theta,\\phi)e^{-\\alpha r^{2}}\n\\end{equation}\nThe other group uses the Cartesian function:\n\\begin{equation}\\label{basis_set_cart_form}\n \\chi = x^{l}y^{m}z^{n}e^{-\\alpha r^{2}}\n\\end{equation}\nIn this program, we only focus on the Cartesian type\nGaussian basis set functions.\n\nGenerally the basis set function $\\psi$ is a linear combination of \nGaussian functions, and each such Gaussian function is also termed\nas primitive function:\n\\begin{equation}\\label{program_contract_basis_set}\n\t\\psi = \\sum_{\\mu}d_{\\mu}\\chi_{\\mu}\n\\end{equation}\n$d$ is pre-optimized contraction coefficients.\n$\\chi_{\\mu}$ is the primitive \nfunctions as defined in \\ref{basis_set_cart_form}.\nAll of $\\chi$ are on the same center as $\\psi$, and they all share the \nsame angular momentum with the basis set function.\n\nFor each basis set function, $x^{l}y^{m}z^{n}$ is its angular momentum part,\nwhich is characterized by three number of l, m, and n. The $e^{-\\alpha r^{2}}$\nis its radial part, so l,m,n combined with exponential factor $\\alpha$ and \nits coefficient of $d_{\\mu}$; that give all of information to get $\\psi$.\n\nIn the recurrence relation(RR), typically it starts with the bottom integral\n\\footnote{for VRR, bottom integral is in form of $(00|00)^{(m)}$ etc. For \nHRR, bottom integral is in form of $(0e|0f)$. See the chapter discussing RR \nfor more information} and by raising up angular momentums it reaches the target\nintegrals. Therefore in the basis set class, we only use $l,m,n$ to represent \nthe basis set.\n\nIn CPPINTS we also define the ``NULL'' basis set which means that \nthis basis set is physical meaningless (l, m and n are all set to be -1). \nThis type of basis set is used to complete an integral definition (see the \n\\ref{integral} for more definition).\n\nThe basis set is defined in the file basis.cpp and basis.h.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Shell}\n%\n% 1  what's the shell? Why shell only have one data member of L?\n% 2  what is the basis set order? How can we change it?\n%\n\\label{shell}\n\nIn quantum chemistry, shell is an aggregation of same type of basis set\nfunctions; whose total angular momentum is same(sum of l,m,n). For example, \nP shell contains 3 basis set functions, their l, m, n are characterized by:\n\\begin{align}\\label{pshell_example}\n\tP_{x} &\\Leftrightarrow (1,0,0) \\nonumber \\\\\n\tP_{y} &\\Leftrightarrow (0,1,0) \\nonumber \\\\\n\tP_{z} &\\Leftrightarrow (0,0,1)\n\\end{align}\nBy following the same principle, it's able the form D shell ($L = l+m+n = 2$), \nF shell ($L = l+m+n = 3$) etc.\n\nAs what we have demonstrated in the basis set functions section, to fulfill\nrecurrence relation it only requires the angular momentum information. \nTherefore, in the shell class it's only the total angular momentum L\nis defined.\n\nHere it needs to emphasize that how to arrange the basis set\nfunctions in a given shell, this is called ``basis set order''.\nFor example, for the P shell, it's able to have:\n\\begin{equation}\n P_{x} \\Rightarrow P_{y} \\Rightarrow P_{z}\n\\end{equation} \nor the other order of \n\\begin{equation}\n P_{z} \\Rightarrow P_{y} \\Rightarrow P_{x}\n\\end{equation} \n\nSince different basis sets in a shell are in a same level, therefore\nthere's not a basis set order prior to the others. It's able to \npick up any basis set order theoretically. In this program, we \npick up the ``libint'' order (which is used by libint program\n\\footnote{\\url{http://sourceforge.net/projects/libint/}}). \nIn basisutil.h, the arrangement of basis set order is given for \nL up to 20. On the other hand, it's able to use the other \ntype of basis set orders. Therefore we separate the basis set \norder information all into the basisutil.h and basisutil.cpp.\n\nIn terms of a given basis set order, each basis set occupies an\nunique position in the \nbasis set order array, which refers as ``local index'' of the \nbasis set in the given shell. For example, in the above P shell\ncase \\ref{pshell_example} $Px$ is 0, $Py$ is 1, $Pz$ is 2. For \neach basis set it's able to set up some ``ONE-TO-ONE'' mapping \nrelation between basis set and it's position in the basis set \norder list. Such fundamental relation is used for building the \nmapping relation between shell quartet and integral (see \nsection \\ref{mapping_integral_sq} for more details).\n\nIf the user wants to employ other type of basis set order other \nthan the libint order, here is the procedure the user should\nfollow:\n\\begin{itemize}\n \\item generate all of explicit basis set order array and \n\t replace the old content of ``LIBINT\\_BASIS\\_SET\\_ORDER''\n\t with the new array (this is in basisutil.h). This step\n\t will enable you to get correct basis set by given \n\t a basis set index;\n \\item Secondly the function of ``getLocalBasisSetIndex'' in\n\t basisutil.cpp should be updated for the new basis \n\t set order. This step will give the correct local index\n\t by an arbitrary input l, m, n value of basis set.\n\\end{itemize}\nNow the mapping between index and angular momentum should \nset up. You should get correct integral results without \nreferring to the other places.\n\nSimilar with basis set, we also define ``NULL'' shell whose \nL is set to be -1. This type of shell is used to complete \nshell quartet definition.\n\nThe shell is defined in shell.h and shell.cpp.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Composite Shells}\n%\n% 1  what is the composite shell?\n% 2  how we handle the composite shell? \n\\label{composite_shell}\n%\n%\nThe composite shell is that for each shell it may contain several\ntype of sub-shells. For example, SP shell has one S shell and one \nP shell, and SPD shell has S shell, P shell and a D shell. All of \nthese sub-shells share the same exponential factors for it's radial part,\nand each of them has its own contraction coefficients of $d$ in equation\n\\ref{program_contract_basis_set}. The most famous basis set library using \ncomposite shell is Pople basis sets (6-31G etc.)\n\nIn our program, the shell class is defined for ``pure'' shell(shell that\nonly corresponds to one $L$ value) and the composite shell situation is \nhandled elsewhere. You can refer to the section \\ref{composite_shell_quartet} \netc. for more details that how CPPINTS handle the composite shell situation.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Integral Type}\n%\n% how to represent the integral operator?\n%\n\\label{inttype}\n\nIn CPPINTS, we have a series of pre-defined integer to represent \nthe ``OPERATORS'' used in quantum chemistry integrals. For example,\nthe two body overlap integral(TOV), nuclear-electron attraction integral(NAI)\netc. These integers are defined in the inttype.h and inttype.cpp(it's \nname appears as macro defined in general.h). The pre-defined integral \nis a data member for both integral and shell quartet class.\n\nFor the given integral type, there are some integral properties that \nis solely determined by the integral operator itself. For example,\nNAI is two body integral, and it requires $(0|0)^{(m)}$ for RR etc.\nYou can find the details from inttype.cpp that what kind of properties \ncan be determined only from operator itself.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Integral and Shell Quartets}\n%\n% \n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Integral}\n\\label{integral}\n%\n% 1  what is integral?\n% 2  how to represent it?\n%\nFor a given operator representing quantum quantity (for example,\nthe kinetic operator, electron repulsion operator etc.) it's able \nto form the integrals based on the basis set functions:\n\\begin{equation}\n I = \\langle \\psi_{l_{1}m_{1}n_{1}}(r)\\psi_{l_{2}m_{2}n_{2}}(r)| \n \\hat{f}(r,r^{'})| \\psi_{l_{3}m_{3}n_{3}}(r^{'})\n \\psi_{l_{4}m_{4}n_{4}}(r^{'})\\rangle\n\\end{equation}\ntherefore to define an integral, basically the following \ninformation is needed:\n\\begin{itemize}\n \\item operator;\n \\item basis set information for all given integral positions\n\\end{itemize}\nBecause recurrence relation also uses the integrals $(ab|cd)^{(m)}$,\nan additional $m$ value is defined in both integral and shell\nquartet class.\n\nPrimarily the integrals could be divided into different categories according \nto the number of its basis set function components. In quantum chemistry, \nthe possible number of basis set functions in the integral is ranging \nfrom 1 to 4. Therefore, integral is ranging from one body integral to \nfour body integrals. \n\nThe four possible basis set positions are called as: ``BRA1'', ``BRA2'',\n``KET1'' and ``KET2''. For one body integral, it's only the bra1\nposition having basis sets(other positions have null basis set); \nfor the two body integral, it's only bra1 and bra2 positions having \nbasis sets; for the three body integral, \nit's only bra1, bra2, and ket1 positions having basis sets. \nSuch position definition is used across the whole program, and the \nsimilar definition holds for shell quartet, too.\n\nThe integral class always has four position for the basis set (see \nintegral.h). For the one to three body integrals, we use NULL\nbasis set to complete the integral definition.\n\nThe integral is defined in integral.cpp and integral.h.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Shell Quartet}\n%\n% how to define shell quartet?\n% what is the relation between shell quartet and integral?\n%\n\\label{shell_quartet}\nSimilar to the relation between basis set and shell, the aggregation \nof certain type of integrals will lead to the ``shell quartet''.\n\nFor example, for the electron repulsion operator it's able to define \nthe shell quartet over four shells:\n\\begin{equation}\n SQ_{P,P,P,P} = \\langle P_{bra1}P_{bra2}|\n \\frac{1}{r_{12}}|P_{ket1}P_{ket2} \\rangle\n\\end{equation}\nThis shell quartet includes all of integrals in terms of basis sets\nfor the given four P shells. Because each P shell have 3 basis set\nfunctions, the shell quartet contains $3^{4} = 81$ ERI integrals.\n\nSimilar to the integral class which is defined based on the basis set\nclass; the shell quartet is constructed based on the shell class. Therefore\nfor defining a fundamental shell quartet, it needs shell information\non all of four BRA1, BRA2, KET1 and KET2 positions (null shell is used\nto complement the shell quartet definition) as well as the operation\ninformation.\n\nThe definition of shell quartet could be referred to shellquartet.h\nand shellquartet.cpp.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Mapping between Integral and Shell Quartet}\n\\label{mapping_integral_sq}\n\nFor CPPINTS, shell quartet is the basic unit for deriving the \nrecurrence relation. The integrals are considered to be attached to \nits corresponding shell quartet.\n\nBased on the ``ONE-TO-ONE'' mapping relation between basis set \nand shell, it's able to construct the ``ONE-TO-ONE'' mapping relation\nbetween integral and its shell quartet. For each integral, it \nhas a unique position according to the given basis set order.\nFor example, integrals in the shell quartet $(SPSP|SPSP)$ may \ncorrespond to an order like:\n\\begin{align}\n (SS|SS)         &\\rightarrow  0 \\nonumber \\\\\n (P_{x}S|SS)     &\\rightarrow  1 \\nonumber \\\\\n (P_{y}S|SS)     &\\rightarrow  2 \\nonumber \\\\\n (P_{z}S|SS)     &\\rightarrow  3 \\nonumber \\\\\n (SP_{x}|SS)     &\\rightarrow  4 \\nonumber \\\\\n (P_{x}P_{x}|SS) &\\rightarrow  5 \\nonumber \\\\\n (P_{y}P_{x}|SS) &\\rightarrow  6 \\nonumber \\\\\n (P_{z}P_{x}|SS) &\\rightarrow  7 \\nonumber \\\\\n                 &\\cdots\n\\end{align}\nBy giving the shell quartet and this unique position, it's able \nto reconstruct the integral; on the other hand, from the given \nintegral it's able to derive its unique position\\footnote{please\nrefer to integral.cpp for more details that how we do it}.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Representation of Integral in Recurrence Relation}\n%\n% why we use position ID to reprernt integral in shell quartet?\n%\n\\label{representation_integral_sq}\n\nThe ``ONE-TO-ONE'' mapping relation could be used to improve the memory \nusage for CPPINTS. Suggest we have a $(II|II)$ ERI shell \nquartet for deriving its vertical recurrence relation, to record\nall of the information for each integrals requires the following \nitems:\n\\begin{itemize}\n \\item LHS integral;\n \\item RHS integral and its coefficients.\n\\end{itemize}\n\nFor each integral, to characterize it it requires $3\\times 4 = 12$\nintegers to record angular momentum information, plus two integers\nfor operator and m value. Therefore each integral needs 14 integer\n\\footnote{we have not considered the division yet, which is related to\ncomposite shell quartet case}.\n\nFor the OS VRR framework, the recursive relation has 8 items on the \nRHS so there are totally 9 integrals, which needs 126 integers. \nBecause the $(II|II)$ has $28^4$ integrals, it needs 77446656 integers.\nSuggest each integer takes 4 byte memory, the total memory for \nstoring integer of this shell quartet would be 296mb! So far we did not\ncount in the coefficients.\n\nHowever, if we use the ``position ID'' to represent the integrals \ninside the shell quartet, then each integral only need one integer \nthus it's only 5.3mb memory needed. Therefore, to use the position \nID to represent integrals inside shell quartet is a good way for \nmemory saving with only marginal CPU cost added. This is the way\nwe handle integrals in the recurrence relation(RR) process.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Composite Shell Quartet}\n%\n%\n\\label{composite_shell_quartet}\n\nIn a given shell quartet, if one of its shell is in composite type; \nthen this shell quartet is composite shell quartet. It contains\nseveral shell quartets in terms of pure shell. For example,\nshell quartet $(DD|DSP)$ has two pure shell quartets; namely \n$(DD|DS)$ and $(DD|DP)$.\n\nHow to process composite shell quartet in the recurrence relation?\nIt's depending on whether it's HRR or it's in VRR.\n\nFor VRR, Let's take ERI as example. Because the recurrence relation \nis generally expressed as: \n\\begin{align}\nI(L,m) &= a_{0}I_{0}(L-1,m) + a_{1}I_{1}(L-1,m+1) \\nonumber \\\\ \n&+ a_{2}I_{2}(L-2,m) - a_{3}I_{3}(L-2,m+1) \\nonumber \\\\\n&+ a_{4}I_{4}(L-2,m) - a_{5}I_{5}(L-2,m+1) \\nonumber \\\\\n&+ a_{6}I_{6}(L-2,m+1) + a_{7}I_{7}(L-2,m+1)\n\\end{align}\nThe above integral expression is on primitive Gaussian function, and \n$a_{i}$ is RR coefficient which is independent with the integral.\nBecause VRR is linear with the contraction coefficients $d$,\nthe expression above holds for both contracted and un-contracted primitive\nGaussian functions. Therefore, the recurrence relation for VRR is \nindependent of the contraction information. We can simply get the \nintegral with contraction coefficients by multiply it to the final\nresults:\n\\begin{equation}\\label{composte_sq_contraction_coefs}\n I_{contracted}(L,m) = d_{bra1}d_{bra2}d_{ket1}d_{ket2}I(L,m)\n\\end{equation}\nThis is what we do for dealing with the composite shell quartets in VRR.\nBecause in composite shell the sub-shells share the same exponential\nfactor, the raw integral $I(L,m)$ in \\ref{composte_sq_contraction_coefs} \nis same between different pure shell quartets; the final integral results\nwith contraction coefficients could be simply retrieved by performing \n\\ref{composte_sq_contraction_coefs}. This is called ``contraction'' step\nin VRR. The pseudocode is given like this:\n\\begin{verbatim}\nloop over ket side primitive Gaussian pairs:\n  loop over bra side primitive Gaussian pairs:\n    compute bottom integrals;\n    do VRR to derive result integrals;\n    perform contraction step; \n  end loop\nend loop\n\\end{verbatim}\nFor pure shell quartet like $(DD|DD)$, there's no need to perform \ncontraction step because it can simply add contraction information\nto the bottom integrals $(00|00)^{(m)}$ so that VRR is performed \nfor contracted integrals. After VRR is ending, the result integrals\nget updated by the result in the primitive integral loops.\n\nHowever, for HRR the story is different. Because HRR is usually applied on\ncontracted integral results (it sums over all of integrals on \nprimitive Gaussian functions), the equation \\ref{composite_sq_hrr}\nshows that how we can step from\nun-contracted integrals to contracted ones in HRR:\n\\begin{align}\\label{composite_sq_hrr}\n [a(b+\\iota_{i})|cd]_{k} &= [(a+\\iota_{i})b|cd]_{k} + \n(A_{i} - B_{i})[ab|cd]_{k} \\rightarrow \\nonumber \\\\\n\\sum_{k}C_{k}[a(b+\\iota_{i})|cd]_{k} &= \\sum_{k}C_{k}[(a+\\iota_{i})b|cd]_{k} + \n(A_{i} - B_{i})\\sum_{k}C_{k}[ab|cd]_{k} \\rightarrow \\nonumber \\\\\n(a(b+\\iota_{i})|cd) &= ((a+\\iota_{i})b|cd) + \n(A_{i} - B_{i})(ab|cd)\n\\end{align}\nHere $[ab|cd]$ is used to represent the integrals on un-contracted Gaussian \nfunctions, and $(ab|cd)$ for the contracted integrals; $C_{k}$ is the \ncombination for all of contraction coefficients of $d$.\n\nIt's clear from \\ref{composite_sq_hrr} that as long as LHS and RHS share the \nsame contraction coefficients, HRR can be applied from $(0e|0f)$ until\nthe final target integral $(ab|cd)$ is derived. Hence for the composite \nshell quartets, each pure shell quartet has its own HRR process and they\nare independent with each other.\n\nFor this reason, we have a data member named as ``division'' on both\nintegral and shell quartet classes. It's an ID for each pure shell quartet\nin the composite shell quartet. For example; $(DSP|DSP)$ has four shell quartets;\n$(DS|DS)$, $(DS|DP)$, $(DP|DS)$ and $(DP|DP)$ and each pure shell quartet has it's \nown ID number (characterized by division). They will have their own\nHRR process.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Sorting Shell Quartets}\n%\n%\n\\label{sort_shell_quartet}\n\nAfter RR(VRR or HRR) path is constructed in detail, a sorting \nfunction is needed to be applied to the whole LHS shell quartets\nso that to make sure all of RHS shell quartets are well defined\nin the previous content. Therefore, we need sorting function for \nbuilding the correct RR.\n\nThe inconvertibility character for VRR establishes in section \n\\ref{optimal_path} in fact enables us to set up sorting facility\non the shell quartet in the RR direction. In other words, in \naccumulating all of RR terms along the VRR path; we are able \nto sort the shell quartets either from bottom integrals to\nthe results(this is always from RHS to LHS in terms of RR),\nor from the results to the bottom integrals in reverse.\n\nThis is what the operator $<$ function in shell quartet class\ndoes. By following the VRR formula\\footnote{right now the function\njust follows the VRR in OS framework}, it's able to distinguish\nthe shell quartet on either RHS or LHS. More details can be \nfound in the comments of this function.\n\nHRR does not hold the inconvertibility character as shown in \nsection \\ref{optimal_path}. However, it's still applicable \nto set up some algorithm to sort the shell quartets in the \nHRR process. The sorting function for HRR is presented in\nhrrCompare function in shellquartet.cpp. Therefore, it's \nable to sort the HRR shell quartets so that we print out \nthe HRR formula in correct order.\n\n", "meta": {"hexsha": "5ca9c81972b8cc578067ea4e12905896f48114ee", "size": 19908, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/basic.tex", "max_stars_repo_name": "murfreesboro/cppints", "max_stars_repo_head_hexsha": "a7beaac034e2bfae8e71997b322133906d1afcaf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/basic.tex", "max_issues_repo_name": "murfreesboro/cppints", "max_issues_repo_head_hexsha": "a7beaac034e2bfae8e71997b322133906d1afcaf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/basic.tex", "max_forks_repo_name": "murfreesboro/cppints", "max_forks_repo_head_hexsha": "a7beaac034e2bfae8e71997b322133906d1afcaf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.6578947368, "max_line_length": 83, "alphanum_fraction": 0.7302089612, "num_tokens": 5139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604274, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3138405603864024}}
{"text": "\\section{Introduction}\n\nAchieving an optimal runtime complexity is a fundamental challenge when it comes to designing scalable solutions for handling a large amount of data\\cite{sipser13}. Recently, quantum computing has sparked the interest of both scientists and engineers due to its asymptotical performance gain on some problems compared to classical computing. While the field has witnessed rapid progress in developing new software, hardware, and efficient algorithms, the core principles at play have been relatively stable. In almost every physical or abstract quantum computer, information encoding and processing occur via unitary transformations while the result is written onto some classical storage via projective measurements\\cite{Nielsen2009}. In this project, we aim to investigate \\emph{measurement-based quantum computing}, a different formulation for quantum computation that provides several advantages over the circuit based model.\n\nMeasurement-based quantum computing was first proposed by Briegel and Russeldorf in 2000 \\cite{Briegel_2001} as a general framework for universal computation via using the entanglement patterns of two-state particles. They later extended their work to include a formulation based on stabilizers, whose use in quantum mechanics is mainly restricted to error correction \\cite{Nielsen2009, quant-ph/9705052}. The structure of a measurement-based quantum computer was further generalized to encompass the use of graph states, which are used to represent qubits with Ising interaction patterns via simple graphs \\cite{hein2006}. Recently, several algorithms formulated for measurement-based quantum computing have been suggested \\cite{keith2014, debeaudrap2008theory, Fitzsimons2017}.\n\nIn this project, we start by reviewing the necessary mathematical background, where we introduce graphs and their relevant properties. We use these graph states as a general framework for studying the entanglement properties of special qubit systems, which can be represented by simple graphs. We use two different mathematical formulations for our exposition of graph states. One such way of formulating these objects is by using their interaction patterns. As graph states interact via specific Ising interactions, their states can be expressed by applying the well-known Ising interaction hamiltonians\\cite{ichikawa2013}. The second formulation uses stabilizer formalism to achieve a more compact and transparent representation of the graph state and its entanglement patterns.\n\nIn the second phase of the project, we introduce the notion of a \\emph{cluster state} which is a regular lattice-like graph state that will be a general substrate for universal quantum computation. Following this introduction, we define an abstract machine called the one-way quantum computer, which takes some measurement patterns and executes them on its cluster. Furthermore, we provide a method to simulate circuit-based quantum computation using this abstract machine to prove its universal computation capability.", "meta": {"hexsha": "2b74fb0d6691deb7ca3b3f07abbc5ede83da109b", "size": 3037, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "documents/final/sections/introduction.tex", "max_stars_repo_name": "kurabirko/phys400", "max_stars_repo_head_hexsha": "1e7608322457c090e4db8c52ff1c7c8c55a612c3", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "documents/final/sections/introduction.tex", "max_issues_repo_name": "kurabirko/phys400", "max_issues_repo_head_hexsha": "1e7608322457c090e4db8c52ff1c7c8c55a612c3", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "documents/final/sections/introduction.tex", "max_forks_repo_name": "kurabirko/phys400", "max_forks_repo_head_hexsha": "1e7608322457c090e4db8c52ff1c7c8c55a612c3", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 337.4444444444, "max_line_length": 929, "alphanum_fraction": 0.8373394797, "num_tokens": 562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.31384056038640235}}
{"text": "\\begin{savequote}[90mm]\n  {\\QuoteFont Praesent metus ligula, auctor vitae, lacinia sed.}\n\\qauthor{- Chao Chao}\n\\end{savequote}\n\n\\chapter{Example of Math}\n\\label{chap:chapter_04}\n\nMauris mollis condimentum risus. Integer ipsum. Quisque\nmalesuada, erat ac dictum pulvinar, magna nisl fermentum ligula,\nquis euismod mauris felis non diam. Nullam sapien turpis, rutrum\nvel, condimentum ac, bibendum vulputate, nulla. Vestibulum tortor\nipsum, fermentum egestas, placerat ut, vulputate et, wisi. Aliquam\nerat volutpat. Each element is defined as $t_{seek}$,$t_{rot}$, and\n$t_{trans}$, respectively. Donec consequat, ligula sit amet tincidunt aliquam,\nnunc lorem sagittis nunc, a ullamcorper erat ante ac felis. Donec\neleifend. Nullam quam leo, lobortis non, condimentum at, tempus\nconsectetuer, orci. Quisque ut lorem.  Vestibulum ante ipsum primis\nin faucibus orci luctus et ultrices posuere cubilia Curae; Donec\nporta, libero eget feugiat posuere, felis arcu pulvinar odio, vel\ndapibus enim dui nec turpis. \\begin{equation}\n\\label{eq:attf}\nt_{HDD}(f_{n}) = t_{seek}(f_{n}) +t_{rot}(f_{n}) + t_{trans}(f_{n})\n\\end{equation}\nSuspendisse porta, dolor sed fringilla\nultrices, augue mauris gravida dolor, vel sollicitudin magna dui sit\namet nunc. \n\n \nDonec nisl. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. More\ndetailed description of the expressions is found in \\cite{miner,CloSpan}. Let\n$F=\\{ f_{1}, ~ f_{2}, ..., ~ f_{n} \\}$ be a set of all files accessed during\nlaunch of an application.  A sequence \n$\\sigma = < s_{1}, ~ s_{2}, ..., ~ s_{i} >$ \nis an ordered list and is a subset of $F$ such that \n$\\{ s_{n} \\sqsubseteq F \\}$. \nGiven two sequences \n$\\alpha = < a_{1}, ~ a_{2}, ..., ~ a_{n} >$ and \n$\\beta = < b_{1}, ~ b_{2}, ..., ~ b_{m} >$, sub-sequence is defined as follows:\nSequence  $\\alpha$ is a sub-sequence of another sequence $\\beta$, if and only\nif there exist $i_{1}, ~ i_{2}, \\ldots, ~ i_{m}$ such that \n$1 \\le i_{1} < i_{2} < \\ldots < i_{m} \\le n$  and \n$a_{1} \\subseteq b_{i1},  ~ a_{2} \\subseteq b_{i2} , \\ldots and  a_{m} \\subseteq b_{im}$. \nIf $\\alpha \\neq \\beta$ then it is denoted as $ \\alpha \\subset \\beta $. \nIf files in sequence $\\alpha$ are in the\nsame order as sequence $\\beta$, then we call $\\beta$ a super-sequence of\n$\\alpha$.  A sequence database, \n$D = \\{ \\sigma_{1}, ~ \\sigma_{2}, ..., ~ \\sigma_{i} \\}$, \nis a set of sequences, and $|D|$ is the number of sequences in\nthe database $D$. The support of a sequence $\\alpha$ in $D$ is the number of\nsequences of $D$ which contains $\\alpha$ as a subsequence. We define frequent\nsub-sequence as sequences with the support greater than or equal to $min\\_sup$,\nwhere $min\\_sup$ is the minimum support threshold.\n\n{\\bfseries \\noindent Example 1.} Suppose a database $D$ with $|D| = 5$ has the\nfollowing set of sequences $\\{ ab, ~ acde, ~ bcdf, ~ abcd, ~ abcf \\}$. Then, 2\nis the support of $abc$ and 3 is the support of $ac$ in $D$. Suppose \n$min\\_sup = 3$, then $abc$ is not a frequent sub-sequence but $ac$ is a frequent\nsub-sequence. $\\blacksquare$\n\n\n \n\n\\lipsum[1-4]\n", "meta": {"hexsha": "45c50a1dd594a69c556889797d525ebed0ea4078", "size": 3052, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/chapter_04.tex", "max_stars_repo_name": "resourceful/HYU_PhD_Dissertation", "max_stars_repo_head_hexsha": "c22f1f05003f1ca6fa4a3d5523c155d8751c5f37", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-01-22T07:09:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-19T13:17:47.000Z", "max_issues_repo_path": "chapters/chapter_04.tex", "max_issues_repo_name": "resourceful/HYU_PhD_Dissertation", "max_issues_repo_head_hexsha": "c22f1f05003f1ca6fa4a3d5523c155d8751c5f37", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/chapter_04.tex", "max_forks_repo_name": "resourceful/HYU_PhD_Dissertation", "max_forks_repo_head_hexsha": "c22f1f05003f1ca6fa4a3d5523c155d8751c5f37", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.9538461538, "max_line_length": 90, "alphanum_fraction": 0.6979030144, "num_tokens": 1038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.31384056038640235}}
{"text": "% This file contains the content for a main section\n\\regularsectionformat\t% Change formatting to that of \"Introduction\" section\n%% Modify below this line %%\n\\chapter{Specification}\n\n\\section{Naming conventions}\nThe encoding of ACES specified in \\autoref{sec:ACEScg} shall be known as ACEScg.\n\n\\section{Color component value encoding}\nACEScg shall be stored as either 16-bit (IEEE binary16) or 32-bit (IEEE binary32) floating point values.\n\n\\section{Color component value range}\nThe value range for ACEScg color component values is [-65504.0, +65504.0].\n\nThe chromaticity coordinates of the defined ACEScg RGB primaries (AP1) form a triangle on the CIE chromaticity diagram. ACEScg RGB values which express visible colors are represented by points within this triangle that also lie within the visual gamut.\n\nThe set of valid ACEScg RGB values also includes members whose projection onto the CIE chromaticity diagram falls outside the region of the AP1 primaries. These ACEScg RGB values include those with one or more negative ACEScg color component values; Ideally these values would be preserved through any compositing operations done in ACEScg space but it is recognized that keeping negative values is not always practical, in which case it will be acceptable to replace negative values with zero.\n\nValues well above 1.0 are expected and should not be clamped except as part of the color correction needed to produce a desired artistic intent.\n\n\\section{Color component transfer function}\nThe color component transfer function directly encodes relative exposure values and is defined as\n\\begin{center}\n$R = E_r, \\quad G = E_g, \\quad B = E_b$\n\\end{center}\nwhere $E_r$, $E_g$ and $E_b$ represent relative exposure values that would be captured from the scene by the ACES Reference Image Capture Device (RICD) and $R$, $G$ and $B$ are the resulting ACES color component values transformed to ACEScg using the methods specified in section 4.1.6.\n\n\\section{Color space chromaticities}\n\\label{sec:colorspace}\nACEScg uses a different set of primaries than ACES RGB primaries defined in SMPTE ST 2065-1. The CIE 1931 colorimetry of the ACEScg RGB primaries and white are specified below.\n\n\\subsection{Color primaries}\nThe RGB primaries chromaticity values, known as AP1, shall be those found in \\autoref{table:AP1rgb}.\n\n\\begin{center}\n\\begin{tabularx}{4.5in}{XlllXll}\n        & R       & G       & B       & & CIE x & CIE y \\\\ \\hline\nRed     & 1.00000 & 0.00000 & 0.00000 & & 0.713 & 0.293 \\\\\nGreen   & 0.00000 & 1.00000 & 0.00000 & & 0.165 & 0.830 \\\\\nBlue    & 0.00000 & 0.00000 & 1.00000 & & 0.128 & 0.044 \\\\\n\\end{tabularx}\n\\captionof{table}{ACEScg RGB primaries chromaticity values}    \n\\label{table:AP1rgb}\n\\end{center}\n\n\\subsection{White Point}\nThe white point shall be that found in \\autoref{table:AP1w}.\n\n\\begin{center}\n\\begin{tabularx}{4.5in}{XlllXll}\n        & R       & G       & B       & & CIE x & CIE y \\\\ \\hline\nWhite   & 1.00000 & 1.00000 & 1.00000 & & 0.32168 & 0.33767 \\\\\n\\end{tabularx}\n\\captionof{table}{ACES RGB white point chromaticity values}    \n\\label{table:AP1w}\n\\end{center}\n\n\\note{The ACEScg white point is the same as the white point of ACES 2065-1.}\n\n\\section{ACEScg}\n\\label{sec:ACEScg}\nThe following functions shall be used to convert between ACES values, encoded according to SMPTE ST 2065-1, and ACEScg.\n\n\\subsection{Converting ACES2065-1 RGB values to ACEScg RGB values}\n\\label{sec:aces2acescg}\nACES $R$, $G$, and $B$ values shall be converted to ACEScg $R$, $G$, and $B$ values using the transformation matrix ($TRA$) calculated and applied using the methods provided in Section 4 of SMPTE RP 177:1993.\n\n\\note{Equation \\ref{eq:aces2acescg} shows the relationship between ACES $R$, $G$, and $B$ values and ACEScg $R$, $G$, and $B$ values. $TRA_{1}$, rounded to 10 significant digits, is derived from the product of $NPM_{AP1}$ inverse and $NPM_{AP0}$ calculated using methods provided in Section 3.3 of SMPTE RP 177:1993. AP0 are the primaries of ACES specified in SMPTE ST 2065-1:2012. AP1 are the primaries of ACEScg specified in \\autoref{sec:colorspace}.}\n\n\\begin{floatequ} \n\\begin{gather}\n    \\begin{bmatrix}\n        R_{ACEScg}\\\\\n        G_{ACEScg}\\\\\n        B_{ACEScg}\n    \\end{bmatrix}\n    =\n    TRA_{1}\n    \\cdot\n    \\begin{bmatrix}\n        R_{ACES}\\\\\n        G_{ACES}\\\\\n        B_{ACES}\n    \\end{bmatrix} \\\\\n    \\\\\n    TRA_{1} =\n    \\begin{bmatrix*}[r]\n        1.4514393161 & -0.2365107469 & -0.2149285693 \\\\\n       -0.0765537734 &  1.1762296998 & -0.0996759264 \\\\\n        0.0083161484 & -0.0060324498 &  0.9977163014 \\\\\n    \\end{bmatrix*} \\\\\n    \\\\\n    TRA_{1} = NPM^{-1}_{AP1} \\cdot NPM_{AP0}\n\\end{gather}\n\\caption{ACES2065-1 to ACEScg}\n\\label{eq:aces2acescg}\n\\end{floatequ}\n\n\\subsection{Converting ACEScg RGB values to ACES2065-1 RGB values}\nACEScg $R$, $G$, and $B$ values shall be converted to ACES2065-1 $R$, $G$ and $B$ using the transformation matrix ($TRA$) calculated and applied using the methods provided in Section 4 of SMPTE RP 177:1993.\n\n\\note{Equation \\ref{eq:acescg2aces} shows the relationship between ACES $R$, $G$, and $B$ values and ACEScg $R$, $G$, and $B$ values. $TRA_{2}$, rounded to 10 significant digits, is derived from the product of $NPM_{AP0}$ inverse and $NPM_{AP1}$ calculated using methods provided in Section 3.3 of SMPTE RP 177:1993. AP0 are the primaries of ACES specified in SMPTE ST 2065-1:2012. AP1 are the primaries of ACEScg specified in \\autoref{sec:colorspace}.}\n\n\\begin{floatequ} \n\\begin{gather}\n    \\begin{bmatrix}\n        R_{ACES}\\\\\n        G_{ACES}\\\\\n        B_{ACES}\n    \\end{bmatrix}\n    =\n    TRA_{2}\n    \\cdot\n    \\begin{bmatrix}\n        R_{ACEScg}\\\\\n        G_{ACEScg}\\\\\n        B_{ACEScg}\n    \\end{bmatrix} \\\\\n    \\\\\n    TRA_{2} =\n    \\begin{bmatrix*}[r]\n        0.6954522414 & 0.1406786965 & 0.1638690622 \\\\\n        0.0447945634 & 0.8596711185 & 0.0955343182 \\\\\n        -0.0055258826 & 0.0040252103 & 1.0015006723 \\\\\n    \\end{bmatrix*} \\\\\n    \\\\\n    TRA_{2} = NPM^{-1}_{AP0} \\cdot NPM_{AP1}\n\\end{gather}\n\\caption{ACEScg to ACES2065-1}\n\\label{eq:acescg2aces}\n\\end{floatequ}", "meta": {"hexsha": "330c61605c1a48e1df5d4b73a6e76c939b73fb87", "size": 6064, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "documents/LaTeX/S-2014-004/specification.tex", "max_stars_repo_name": "kdt3rd/aces-dev", "max_stars_repo_head_hexsha": "28f08367e192391acacfaf8d8bee66123dfad506", "max_stars_repo_licenses": ["AMPAS"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-03-26T05:44:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-26T05:44:31.000Z", "max_issues_repo_path": "documents/LaTeX/S-2014-004/specification.tex", "max_issues_repo_name": "KevinJW/aces-dev", "max_issues_repo_head_hexsha": "191f7d7d711cb75390deca3aca470050946aa343", "max_issues_repo_licenses": ["AMPAS"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "documents/LaTeX/S-2014-004/specification.tex", "max_forks_repo_name": "KevinJW/aces-dev", "max_forks_repo_head_hexsha": "191f7d7d711cb75390deca3aca470050946aa343", "max_forks_repo_licenses": ["AMPAS"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.2900763359, "max_line_length": 494, "alphanum_fraction": 0.7046503958, "num_tokens": 1908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.3137883826719046}}
{"text": "\\section{Plugin for the RAVEN Code}\n\\label{sec:RavenPlugin}\n\nThe deterministic model can be repeatedly solved by changing the input values (i.e.,\n\\xmlNode{available\\_capitals} [$b_{kt}$] and \\xmlNode{net\\_present\\_values} [$a_{ij}$]).\nThis will allow for what-if sensitivity analysis to identify the\ncrucial drivers behind the optimal project selection decision. Monte Carlo simulation permits a\npowerful variant of this approach in which we model $a_{ij}$ and $b_{kt}$ as random\nvariables, sample from their distributions, and perform a form of uncertainty quantification\nin terms of the resulting distributions governing the binary decisions selected, $x_{ij}$, and\nthe overall NPV of the selected portfolio.\n\nExample RAVEN input \\xmlNode{ExternalModel} XML:\n\\begin{lstlisting}[style=XML]\n<Models>\n  <ExternalModel name=\"singleKnapsack\" subType=\"LOGOS.CapitalInvestmentModel\">\n    <variables>available_capitals,i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,\n      MaxNPV</variables>\n    <ModelData>\n      <Sets>\n        <investments>\n          i1,i2,i3,i4,i5,i6,i7,i8,i9,i10\n        </investments>\n      </Sets>\n      <Parameters>\n        <net_present_values index=\"investments\">\n          18,20,17,19,25,21,27,23,25,24\n        </net_present_values>\n        <costs index=\"investments\">\n          1,3,7,4,8,9,6,10,2,5\n        </costs>\n        <available_capitals>\n          15\n        </available_capitals>\n      </Parameters>\n      <Settings>\n        <solver>glpk</solver>\n        <sense>maximize</sense>\n      </Settings>\n    </ModelData>\n  </ExternalModel>\n</Models>\n\\end{lstlisting}\n\nAs the name suggests, an external model is an entity that is embedded in the RAVEN\ncode at run time. This object allows the user to import the LOGOS module that will\nbe treated as a predefined internal RAVEN object. In other words, the\n\\textbf{External Model} will be treated by RAVEN as a normal external model.\nCheck the RAVEN user manual for a more detailed description.\n\\nb The value for attribute \\xmlAttr{subType} should always be \\xmlString{LOGOS.CapitalInvestmentModel}.\n\n\\xmlNode{variables} specifies a list of variable names that need to match\nvariables used/defined in the LOGOS model. In the above example, the variable\n\\xmlString{available\\_capitals} is sampled by RAVEN, and its value is used\nby LOGOS instead of using the default values specified by \\xmlNode{ModelData}.\nThe decision variables \\xmlString{i1,i2,i3,i4,i5,i6,i7,i8,i9,i10} and the\nobjective variable \\xmlString{MaxNPV} are collected from the output of the LOGOS model,\nand can be stored in the RAVEN data objects.\nThe XML node \\xmlNode{ModelData} is used to specify the LOGOS optimization problem, which\nshould be consistent with the LOGOS input XML file.\n\n\\subsection{Test Automation}\nAutomated regression testing is a development methodology generally used\nto verify the correctness and performance of software after each modification.\nThis methodology is integrated directly into GitHub and GitLab for RAVEN and\nRAVEN-supported plugins. In this case, testing is performed automatically as part of the\ncontinuous integration system (CIS) process whenever a user commits a change to the\nrepository. Tests of changes across multiple platforms are executed with each pull\nrequest. Results from each test execution are maintained in an approved records\nrepository in the CIS database, along with results from the timing executions.\n\n\\subsection{Testing System Prerequisites}\nThe module test system consists of scripts written in Bash shell language\nand Python. It may be used on any platform supported by RAVEN (i.e.\nLinux, Mac, and Windows). The following conditions must be satisfied for the\nmodule test system to function properly:\n\\begin{itemize}\n  \\item RAVEN should be installed and updated. This is because RAVEN is used to\n  run the module tests;\n  \\item The system running the tests must be configured with the software prerequisites\n  necessary to build and run RAVEN. These include a Python interpreter, Python\n  libraries (h5py, matplotlib, numpy, scipy, and scikit-learn), and development\n  tools (C++ compiler, Miniconda package manager for Python, and Git source code control);\n  \\item RAVEN must be built with the appropriate compiler before it can be used to\n  run the tests;\n  \\item The LOGOS submodule must be initialized and fully updated. Additional prerequisites\n  include PYOMO, glpk, and coincbc;\n\\end{itemize}\n\n\\subsection{Test Location and Definition}\nLOGOS is a RAVEN-supported plugins and managed by Git. RAVEN plugins afford\nan option to associate a workflow or a set of RAVEN external models to RAVEN\nwithout having them included in the RAVEN main repository. The benefits include\nmodularity, access restriction, and regression testing for compatibility with RAVEN\nas it continues to grow. In this case, we are able to treat this repository as\nseparate, yet still be able to use one from within the other. The main structure\nof the LOGOS repository is shown in Figure~\\ref{fig:Logos}. The folder \\textit{tests} contains the input of\nthe tests, in addition to the corresponding output (in the gold folder) used for\nassurance that the behavior of the code is not changed for new modifications. These\ntests can also be collected in subfolders based on their characteristics.\n\n\\begin{figure}\n    \\centering\n    \\centerline{\\includegraphics[scale=0.5]{LogosRepo.jpg}}\n    \\caption{Folder tree of the Logos repository.}\n    \\label{fig:Logos}\n\\end{figure}\n\nThe RAVEN repository contains a complete testing system for providing regression\ntesting for itself and its plugins. The LOGOS module tests are defined in the\nsame manner as for RAVEN. A single test consists of a RAVEN input file\nalong with associated data needed to perform that run. This can include input data,\nexternal models, and Python files. These may be placed in the \\textit{tests} directory\nor a related subdirectories. Each directory that contains tests to be run by\nthe framework must contain a test specification file named “tests”. The syntax of\nthese files is defined by the RAVEN test framework, which controls how each test\nis run and sets the criteria used to determine whether it passed or not. An example\nof a test specification file is presented here:\n\\begin{lstlisting}[language=python]\n[Tests]\n  [./skp_optimization]\n    type = 'RavenFramework'\n    input = 'test_skp.xml'\n    UnorderedCsv = 'skp/test_skp.csv'\n  [../]\n[]\n\\end{lstlisting}\nIn the above example, one test, named ``skp\\_optimization'', is defined using the RAVEN\ntest module (defined in the test file as “type = `RavenFramework'”). Comparison\ncriteria are also defined in the “tests” file. In most cases, one or more output\nfiles generated by running the specified input file with RAVEN are compared\nagainst a gold standard provided by the developer and stored in the repository.\nTypically, comparisons are performed on numeric values contained in\nCSV files up to a defined tolerance. When these file comparisons are specified\nby the test developer, reference files must have the same name and be placed\nin the gold subdirectory below that containing the “tests” file.\n\n\\subsection{Running the Tests}\nThe integrated tests can be run separately, as indicated by following this pathway:\n\\begin{lstlisting}[language=bash]\npath/to/raven/raven_framework path/to/LOGOS/tests/TestName\n\\end{lstlisting}\n\n\\subsection{Continuous Integration System (CIVET)}\nCIVET, developed at INL, is used for continuous integration, verification,\nenhancement, and testing of RAVEN and LOGOS. Each time a developer\nproposes modification of the contents of the LOGOS repository, CIVET will cause\nthe automated tests to be run on the modified version. These tests must all pass\nbefore a proposed change can become part of the official repository. In this way,\nthe LOGOS project is protected from the accidental introduction of flaws into\nsoftware that required such a significant investment of resources to develop.\n", "meta": {"hexsha": "f211318e16ae5859671d46548afa7e171e4541e2", "size": 7905, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/user_manual/include/PluginForRavenCode.tex", "max_stars_repo_name": "dgarrett622/LOGOS", "max_stars_repo_head_hexsha": "7234b8b5e80bc79526b4cbced7efd5ae482f7c44", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-05-04T08:42:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T13:14:12.000Z", "max_issues_repo_path": "doc/user_manual/include/PluginForRavenCode.tex", "max_issues_repo_name": "albernsrya/LOGOS", "max_issues_repo_head_hexsha": "535a25ccd3a83259b615acd569257d751fe00439", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 28, "max_issues_repo_issues_event_min_datetime": "2021-01-12T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-03T18:20:16.000Z", "max_forks_repo_path": "doc/user_manual/include/PluginForRavenCode.tex", "max_forks_repo_name": "albernsrya/LOGOS", "max_forks_repo_head_hexsha": "535a25ccd3a83259b615acd569257d751fe00439", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-05T17:18:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:36:42.000Z", "avg_line_length": 52.0065789474, "max_line_length": 107, "alphanum_fraction": 0.7771030993, "num_tokens": 1891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.3137883826719046}}
{"text": "% !TeX root = ../main.tex\n\n\\section{Neighborhood-based Collaborative Filtering}\n\\subsection{Introduction}\n\\begin{frame}\n    \\frametitle{Introduction}\n    \\centering\n    \\underline{\\textbf{Collaborative Filtering}}\n    \\begin{itemize}\n        \\item \\textbf{User-based}\n            \\begin{itemize}\n                \\item Many People like \"The Godfather\" should I watch it too?\n                \\item Choose a number of users who like things I like and\n                      decide based on how much they liked it\n                \\item If we used to like similar items in the past, we will continue to like similar items in the future\n            \\end{itemize}\n        \\item \\textbf{Item-based}\n            \\begin{itemize}\n                \\item Is \"Jurassic Park\" a good choice based on movies I usually see?\n                \\item Choose a number of movies that I have seen and share similar audience with \"Jurassic Park\",\n                then decide based on how much I liked the previous movies\n                \\item If I liked these type of items in the past, I will probably also like those items\n            \\end{itemize}\n    \\end{itemize}\n\\end{frame}\n\\begin{frame}[t]\n    \\frametitle{Introduction}\n    \\centering\n    \\underline{\\textbf{Advantages of Collaborative Filtering}}\n    \\begin{center}\n        \\begin{enumerate}\n            \\item Simplicity\n            \\item Justifiability\n            \\item Efficiency\n            \\item Stability\n        \\end{enumerate}\n    \\end{center}\n\\end{frame}\n\n\\subsection{Similarity Function Variants}\n\\begin{frame}\n    \\frametitle{Cosine Similarity}\n    \\begin{columns}\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{User-based}}\n        \\begin{equation*}\n            cos(u,v) = \\frac{\\sum_{i \\in \\mathcal{I}_{uv}}r_{ui}r_{vi}}\n        \t\t    {\\sqrt{\\sum_{i \\in \\mathcal{I}_{u}}r_{ui}^2}\n        \t\t     \\sqrt{\\sum_{i \\in \\mathcal{I}_{v}}r_{vi}^2}}\n        \\end{equation*}\n        \\tiny\n        \\begin{itemize}\n            \\item $\\mathcal{I}_{u}:$ The set of items that have been rated by user $u$\n            \\item $\\mathcal{I}_{v}:$ The set of items that have been rated by user $v$\n            \\item $\\mathcal{I}_{uv}:$ The set of items that users $u$ and $v$ rated in common\n            \\item $r_{ui}:$ The rating that user $u$ gave to item $i$\n            \\item $r_{vi}:$ The rating that user $v$ gave to item $i$\n        \\end{itemize}\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{Item-based}}\n        \\begin{equation*}\n            cos(i,j) = \\frac{\\sum_{u \\in \\mathcal{U}_{ij}}r_{iu}r_{ju}}\n        \t\t    {\\sqrt{\\sum_{u \\in \\mathcal{U}_{i}}r_{iu}^2}\n        \t\t     \\sqrt{\\sum_{u \\in \\mathcal{U}_{j}}r_{ju}^2}}\n        \\end{equation*}\n        \\tiny\n        \\begin{itemize}\n            \\item $\\mathcal{U}_{i}:$ The set of users that have rated item $i$\n            \\item $\\mathcal{U}_{j}:$ The set of users that have rated item $j$\n            \\item $\\mathcal{U}_{ij}:$ The set of users that have both rated items $i$ and $j$\n            \\item $r_{iu}:$ The rating item $i$ received from user $u$\n            \\item $r_{ju}:$ The rating item $j$ received from user $u$\n        \\end{itemize}\n    \\end{columns}\n\\end{frame}\n\\begin{frame}\n    \\frametitle{Modified Cosine Similarity}\n    \\begin{columns}\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{User-based}}\n        \\begin{equation*}\n            MC(u,v) = \\frac{\\sum_{i \\in \\mathcal{I}_{uv}}r_{ui}r_{vi}}\n\t\t   {\\sqrt{\\sum_{i \\in \\mathcal{I}_{uv}}r_{ui}^2}\n                    \\sqrt{\\sum_{i \\in \\mathcal{I}_{uv}}r_{vi}^2}}\n        \\end{equation*}\n        \\tiny\n        \\begin{itemize}\n            \\item $\\mathcal{I}_{uv}:$ The set of items that users $u$ and $v$ rated in common\n            \\item $r_{ui}:$ The rating that user $u$ gave to item $i$\n            \\item $r_{vi}:$ The rating that user $v$ gave to item $i$\n        \\end{itemize}\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{Item-based}}\n        \\begin{equation*}\n            MC(i,j) = \\frac{\\sum_{u \\in \\mathcal{U}_{ij}}r_{iu}r_{ju}}\n\t\t   {\\sqrt{\\sum_{u \\in \\mathcal{U}_{ij}}r_{iu}^2}\n                    \\sqrt{\\sum_{u \\in \\mathcal{U}_{ij}}r_{ju}^2}}\n        \\end{equation*}\n        \\tiny\n        \\begin{itemize}\n            \\item $\\mathcal{U}_{ij}:$ The set of users that have both rated items $i$ and $j$\n            \\item $r_{iu}:$ The rating item $i$ received from user $u$\n            \\item $r_{ju}:$ The rating item $j$ received from user $u$\n        \\end{itemize}\n    \\end{columns}\n\\end{frame}\n\\begin{frame}\n    \\frametitle{Adjusted Cosine Similarity}\n    \\vspace{-0.8cm}\n    \\begin{columns}\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{User-based}}\n        \\begin{equation*}\n            \\small\n            \\begin{split}\n            &AC(u,v) = \\frac{\\sum_{i \\in \\mathcal{I}_{uv}}(r_{ui}-\\bar{r_{i}})(r_{vi}-\\bar{r_{i}})}\n        \t\t    {\\sqrt{\\sum_{i \\in \\mathcal{I}_{uv}}(r_{ui}-\\bar{r_{i}})^2}\n                             \\sqrt{\\sum_{i \\in \\mathcal{I}_{uv}}(r_{vi}-\\bar{r_{i}})^2}} \\\\\\\\\n            &\\bar{r_{i}} = \\frac{\\sum_{u \\in \\mathcal{U}_i}r_{iu}}\n         \t\t        {\\mathopen|\\mathcal{U}_i\\mathclose|}\n            \\end{split}\n        \\end{equation*}\n        \\tiny\n        \\begin{itemize}\n            \\item $\\mathcal{I}_{uv}:$ The set of items that users $u$ and $v$ rated in common\n            \\item $r_{ui}:$ The rating that user $u$ gave to item $i$\n            \\item $r_{vi}:$ The rating that user $v$ gave to item $i$\n            \\item $\\mathcal{U}_{i}:$ The set of users that have rated item $i$\n            \\item $\\bar{r_{i}}:$ The mean rating of item $i$\n\n        \\end{itemize}\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{Item-based}}\n        \\begin{equation*}\n            \\small\n            \\begin{split}\n            &AC(i,j) = \\frac{\\sum_{u \\in \\mathcal{U}_{ij}}(r_{iu}-\\bar{r_{u}})(r_{ju}-\\bar{r_{u}})}\n        \t\t    {\\sqrt{\\sum_{u \\in \\mathcal{U}_{ij}}(r_{iu}-\\bar{r_{u}})^2}\n                             \\sqrt{\\sum_{u \\in \\mathcal{U}_{ij}}(r_{ju}-\\bar{r_{u}})^2}} \\\\\\\\\n            &\\bar{r_{u}} = \\frac{\\sum_{i \\in \\mathcal{I}_u}r_{ui}}\n         \t\t        {\\mathopen|\\mathcal{I}_u\\mathclose|}\n            \\end{split}\n        \\end{equation*}\n        \\tiny\n        \\begin{itemize}\n            \\item $\\mathcal{U}_{ij}:$ The set of users that have both rated items $i$ and $j$\n            \\item $r_{iu}:$ The rating item $i$ received from user $u$\n            \\item $r_{ju}:$ The rating item $j$ received from user $u$\n            \\item $\\mathcal{I}_{u}:$ The set of items that have been rated by user $u$\n            \\item $\\bar{r_{u}}:$ The mean rating of user $u$\n        \\end{itemize}\n    \\end{columns}\n\\end{frame}\n\\begin{frame}\n    \\frametitle{Modified Adjusted Cosine Similarity}\n    \\vspace{-0.6cm}\n    \\begin{columns}\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{User-based}}\n        \\begin{equation*}\n        \\footnotesize\n        \\begin{split}\n        &MAC(u,v) = \\frac{\\sum_{i \\in \\mathcal{I}_{uv}}(r_{ui}-\\bar{r_{i}})(r_{vi}-\\bar{r_{i}})}\n                         {\\sqrt{\\sum_{i \\in \\mathcal{I}_{u}}(r_{ui}-\\bar{r_{i}})^2}\n                          \\sqrt{\\sum_{i \\in \\mathcal{I}_{v}}(r_{vi}-\\bar{r_{i}})^2}} \\\\\\\\\n        &\\bar{r_{i}} = \\frac{\\sum_{u \\in \\mathcal{U}_i}r_{iu}}\n                            {\\mathopen|\\mathcal{U}_i\\mathclose|}\n        \\end{split}\n        \\end{equation*}\n        \\tiny\n        \\begin{itemize}\n            \\item $\\mathcal{I}_{u}:$ The set of items that have been rated by user $u$\n            \\item $\\mathcal{I}_{v}:$ The set of items that have been rated by user $v$\n            \\item $\\mathcal{I}_{uv}:$ The set of items that users $u$ and $v$ rated in common\n            \\item $r_{ui}:$ The rating that user $u$ gave to item $i$\n            \\item $r_{vi}:$ The rating that user $v$ gave to item $i$\n            \\item $\\mathcal{U}_{i}:$ The set of users that have rated item $i$\n            \\item $\\bar{r_{i}}:$ The mean rating of item $i$\n        \\end{itemize}\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{Item-based}}\n        \\begin{equation*}\n        \\footnotesize\n        \\begin{split}\n        &MAC(i,j) = \\frac{\\sum_{u \\in \\mathcal{U}_{ij}}(r_{iu}-\\bar{r_{u}})(r_{ju}-\\bar{r_{u}})}\n                         {\\sqrt{\\sum_{u \\in \\mathcal{U}_{i}}(r_{iu}-\\bar{r_{u}})^2}\n                          \\sqrt{\\sum_{u \\in \\mathcal{U}_{j}}(r_{ju}-\\bar{r_{u}})^2}} \\\\\\\\\n        &\\bar{r_{u}} = \\frac{\\sum_{i \\in \\mathcal{I}_u}r_{ui}}\n                            {\\mathopen|\\mathcal{I}_u\\mathclose|}\n        \\end{split}\n        \\end{equation*}\n        \\tiny\n        \\begin{itemize}\n            \\item $\\mathcal{U}_{i}:$ The set of users that have rated item $i$\n            \\item $\\mathcal{U}_{j}:$ The set of users that have rated item $j$\n            \\item $\\mathcal{U}_{ij}:$ The set of users that have both rated items $i$ and $j$\n            \\item $r_{iu}:$ The rating item $i$ received from user $u$\n            \\item $r_{ju}:$ The rating item $j$ received from user $u$\n            \\item $\\mathcal{I}_{u}:$ The set of items that have been rated by user $u$\n            \\item $\\bar{r_{u}}:$ The mean rating of user $u$\n        \\end{itemize}\n    \\end{columns}\n\\end{frame}\n\\begin{frame}\n    \\frametitle{Pearson Correlation Coefficient}\n    \\vspace{-0.8cm}\n    \\begin{columns}\n        \\hspace{-7mm}\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{User-based}}\n        \\begin{equation*}\n            \\small\n            \\begin{split}\n            &PCC(u,v) = \\frac{\\sum_{i \\in \\mathcal{I}_{uv}}(r_{ui}-\\bar{r_{u}})(r_{vi}-\\bar{r_{v}})}\n                             {\\sqrt{\\sum_{i \\in \\mathcal{I}_{uv}}(r_{ui}-\\bar{r_{u}})^2}\n                              \\sqrt{\\sum_{i \\in \\mathcal{I}_{uv}}(r_{vi}-\\bar{r_{v}})^2}} \\\\\\\\\n            &\\bar{r_{u}} = \\frac{\\sum_{i \\in \\mathcal{I}_u}r_{ui}}\n                                {\\mathopen|\\mathcal{I}_u\\mathclose|}\n        \\end{split}\n        \\end{equation*}\n        \\tiny\n        \\begin{itemize}\n            \\item $\\mathcal{I}_{uv}:$ The set of items that users $u$ and $v$ rated in common\n            \\item $r_{ui}:$ The rating that user $u$ gave to item $i$\n            \\item $r_{vi}:$ The rating that user $v$ gave to item $i$\n            \\item $\\bar{r_{u}}:$ The mean rating of user $u$\n\n        \\end{itemize}\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{Item-based}}\n        \\begin{equation*}\n            \\small\n            \\begin{split}\n            &PCC(i,j) = \\frac{\\sum_{u \\in \\mathcal{U}_{ij}}(r_{iu}-\\bar{r_{i}})(r_{ju}-\\bar{r_{j}})}\n                             {\\sqrt{\\sum_{u \\in \\mathcal{U}_{ij}}(r_{iu}-\\bar{r_{i}})^2}\n                              \\sqrt{\\sum_{u \\in \\mathcal{U}_{ij}}(r_{ju}-\\bar{r_{j}})^2}} \\\\\\\\\n            &\\bar{r_{i}} = \\frac{\\sum_{u \\in \\mathcal{U}_i}r_{iu}}\n                                {\\mathopen|\\mathcal{U}_i\\mathclose|}\n        \\end{split}\n        \\end{equation*}\n        \\tiny\n        \\begin{itemize}\n            \\item $\\mathcal{U}_{ij}:$ The set of users that have both rated items $i$ and $j$\n            \\item $r_{iu}:$ The rating item $i$ received from user $u$\n            \\item $r_{ju}:$ The rating item $j$ received from user $u$\n            \\item $\\bar{r_{i}}:$ The mean rating of item $i$\n\n        \\end{itemize}\n    \\end{columns}\n\\end{frame}\n\\begin{frame}\n    \\frametitle{Modified Pearson Correlation Coefficient 1}\n    \\vspace{-0.8cm}\n    \\begin{columns}\n        \\hspace{-7mm}\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{User-based}}\n        \\begin{equation*}\n            \\footnotesize\n            \\begin{split}\n    &MPCC1(u,v) = \\frac{\\sum_{i \\in \\mathcal{I}_{uv}}(r_{ui}-\\tilde{r_{u}})(r_{vi}-\\tilde{r_{v}})}\n                       {\\sqrt{\\sum_{i \\in \\mathcal{I}_{uv}}(r_{ui}-\\tilde{r_{u}})^2}\n                        \\sqrt{\\sum_{i \\in \\mathcal{I}_{uv}}(r_{vi}-\\tilde{r_{v}})^2}} \\\\\\\\\n      &\\tilde{r_{u}} = \\frac{\\sum_{i \\in \\mathcal{I}_{uv}}r_{ui}}\n                          {\\mathopen|\\mathcal{I}_{uv}\\mathclose|}\n            \\end{split}\n        \\end{equation*}\n        \\tiny\n        \\begin{itemize}\n            \\item $\\mathcal{I}_{uv}:$ The set of items that users $u$ and $v$ rated in common\n            \\item $r_{ui}:$ The rating that user $u$ gave to item $i$\n            \\item $r_{vi}:$ The rating that user $v$ gave to item $i$\n            \\item $\\tilde{r_{u}}:$ The mean rating of user $u$\n\n        \\end{itemize}\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{Item-based}}\n        \\begin{equation*}\n            \\footnotesize\n            \\begin{split}\n            &MPCC1(i,j) = \\frac{\\sum_{u \\in \\mathcal{U}_{ij}}(r_{iu}-\\tilde{r_{i}})(r_{ju}-\\tilde{r_{j}})}\n                             {\\sqrt{\\sum_{u \\in \\mathcal{U}_{ij}}(r_{iu}-\\tilde{r_{i}})^2}\n                              \\sqrt{\\sum_{u \\in \\mathcal{U}_{ij}}(r_{ju}-\\tilde{r_{j}})^2}} \\\\\\\\\n            &\\tilde{r_{i}} = \\frac{\\sum_{u \\in \\mathcal{U}_i}r_{iu}}\n                                {\\mathopen|\\mathcal{U}_i\\mathclose|}\n        \\end{split}\n        \\end{equation*}\n        \\tiny\n        \\begin{itemize}\n            \\item $\\mathcal{U}_{ij}:$ The set of users that have both rated items $i$ and $j$\n            \\item $r_{iu}:$ The rating item $i$ received from user $u$\n            \\item $r_{ju}:$ The rating item $j$ received from user $u$\n            \\item $\\tilde{r_{i}}:$ The mean rating of item $i$\n\n        \\end{itemize}\n    \\end{columns}\n\\end{frame}\n\\begin{frame}\n    \\frametitle{Modified Pearson Correlation Coefficient 2}\n    \\vspace{-0.8cm}\n    \\begin{columns}\n        \\hspace{-7mm}\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{User-based}}\n        \\begin{equation*}\n            \\footnotesize\n            \\begin{split}\n            &MPCC2(u,v) = \\frac{\\sum_{i \\in \\mathcal{I}_{uv}}(r_{ui}-\\bar{r_{u}})(r_{vi}-\\bar{r_{v}})}\n                             {\\sqrt{\\sum_{i \\in \\mathcal{I}_{u}}(r_{ui}-\\bar{r_{u}})^2}\n                              \\sqrt{\\sum_{i \\in \\mathcal{I}_{v}}(r_{vi}-\\bar{r_{v}})^2}} \\\\\\\\\n            &\\bar{r_{u}} = \\frac{\\sum_{i \\in \\mathcal{I}_u}r_{ui}}\n                                {\\mathopen|\\mathcal{I}_u\\mathclose|}\n        \\end{split}\n        \\end{equation*}\n        \\tiny\n        \\begin{itemize}\n            \\item $\\mathcal{I}_{u}:$ The set of items that have been rated by user $u$\n            \\item $\\mathcal{I}_{v}:$ The set of items that have been rated by user $v$\n            \\item $\\mathcal{I}_{uv}:$ The set of items that users $u$ and $v$ rated in common\n            \\item $r_{ui}:$ The rating that user $u$ gave to item $i$\n            \\item $r_{vi}:$ The rating that user $v$ gave to item $i$\n            \\item $\\bar{r_{u}}:$ The mean rating of user $u$\n        \\end{itemize}\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{Item-based}}\n        \\begin{equation*}\n            \\footnotesize\n            \\begin{split}\n            &MPCC2(i,j) = \\frac{\\sum_{u \\in \\mathcal{U}_{ij}}(r_{iu}-\\bar{r_{i}})(r_{ju}-\\bar{r_{j}})}\n                             {\\sqrt{\\sum_{u \\in \\mathcal{U}_{i}}(r_{iu}-\\bar{r_{i}})^2}\n                              \\sqrt{\\sum_{u \\in \\mathcal{U}_{j}}(r_{ju}-\\bar{r_{j}})^2}} \\\\\\\\\n            &\\bar{r_{i}} = \\frac{\\sum_{u \\in \\mathcal{U}_i}r_{iu}}\n                                {\\mathopen|\\mathcal{U}_i\\mathclose|}\n        \\end{split}\n        \\end{equation*}\n        \\tiny\n        \\begin{itemize}\n            \\item $\\mathcal{U}_{i}:$ The set of users that have rated item $i$\n            \\item $\\mathcal{U}_{j}:$ The set of users that have rated item $j$\n            \\item $\\mathcal{U}_{ij}:$ The set of users that have both rated items $i$ and $j$\n            \\item $r_{iu}:$ The rating item $i$ received from user $u$\n            \\item $r_{ju}:$ The rating item $j$ received from user $u$\n            \\item $\\bar{r_{i}}:$ The mean rating of item $i$\n        \\end{itemize}\n    \\end{columns}\n\\end{frame}\n\\begin{frame}\n    \\frametitle{Mean Squared Difference}\n    \\begin{columns}\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{User-based}}\n        \\begin{equation*}\n        MSD(u,v) = \\frac{\\mathopen|\\mathcal{I}_{uv}\\mathclose|}\n                        {\\sum_{i \\in \\mathcal{I}_{uv}}(r_{ui}-r_{vi})^2}\n    \\end{equation*}\n        \\tiny\n        \\begin{itemize}\n            \\item $\\mathcal{I}_{uv}:$ The set of items that users $u$ and $v$ rated in common\n            \\item $r_{ui}:$ The rating that user $u$ gave to item $i$\n            \\item $r_{vi}:$ The rating that user $v$ gave to item $i$\n        \\end{itemize}\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{Item-based}}\n        \\begin{equation*}\n        MSD(i,j) = \\frac{\\mathopen|\\mathcal{U}_{ij}\\mathclose|}\n                        {\\sum_{u \\in \\mathcal{U}_{ij}}(r_{iu}-r_{ju})^2}\n    \\end{equation*}\n        \\tiny\n        \\begin{itemize}\n            \\item $\\mathcal{U}_{ij}:$ The set of users that have both rated items $i$ and $j$\n            \\item $r_{iu}:$ The rating item $i$ received from user $u$\n            \\item $r_{ju}:$ The rating item $j$ received from user $u$\n        \\end{itemize}\n    \\end{columns}\n\\end{frame}\n\\begin{frame}\n    \\frametitle{Mean Absolute Difference}\n    \\begin{columns}\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{User-based}}\n        \\begin{equation*}\n        MAD(u,v) = \\frac{\\mathopen|\\mathcal{I}_{uv}\\mathclose|}\n                        {\\sum_{i \\in \\mathcal{I}_{uv}}\\mathopen|r_{ui}-r_{vi}\\mathclose|}\n    \\end{equation*}\n        \\tiny\n        \\begin{itemize}\n            \\item $\\mathcal{I}_{uv}:$ The set of items that users $u$ and $v$ rated in common\n            \\item $r_{ui}:$ The rating that user $u$ gave to item $i$\n            \\item $r_{vi}:$ The rating that user $v$ gave to item $i$\n        \\end{itemize}\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{Item-based}}\n        \\begin{equation*}\n        MAD(i,j) = \\frac{\\mathopen|\\mathcal{U}_{ij}\\mathclose|}\n                        {\\sum_{u \\in \\mathcal{U}_{ij}}\\mathopen|r_{iu}-r_{ju}\\mathclose|}\n    \\end{equation*}\n        \\tiny\n        \\begin{itemize}\n            \\item $\\mathcal{U}_{ij}:$ The set of users that have both rated items $i$ and $j$\n            \\item $r_{iu}:$ The rating item $i$ received from user $u$\n            \\item $r_{ju}:$ The rating item $j$ received from user $u$\n        \\end{itemize}\n    \\end{columns}\n\\end{frame}\n\\begin{frame}\n    \\frametitle{Jaccard Coefficient}\n    \\begin{columns}\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{User-based}}\n        \\begin{equation*}\n    J(u,v) = \\frac{\\mathopen|\\mathcal{I}_{uv}\\mathclose|}\n                  {\\mathopen|\\mathcal{I}_{u}\\mathclose| +\n\t\t   \\mathopen|\\mathcal{I}_{v}\\mathclose| -\n\t\t   \\mathopen|\\mathcal{I}_{uv}\\mathclose|}\n       \\end{equation*}\n        \\tiny\n        \\begin{itemize}\n            \\item $\\mathcal{I}_{u}:$ The set of items that have been rated by user $u$\n            \\item $\\mathcal{I}_{v}:$ The set of items that have been rated by user $v$\n            \\item $\\mathcal{I}_{uv}:$ The set of items that users $u$ and $v$ rated in common\n            \\item $\\mathopen|\\mathcal{I}_{u}\\mathclose|:$ The number of items in set $\\mathcal{I}_{u}$\n            \\item $\\mathopen|\\mathcal{I}_{v}\\mathclose|:$ The number of items in set $\\mathcal{I}_{v}$\n            \\item $\\mathopen|\\mathcal{I}_{uv}\\mathclose|:$ The number of items in set $\\mathcal{I}_{uv}$\n        \\end{itemize}\n        \\column{0.5\\textwidth}\n        \\centering\n        \\underline{\\textbf{Item-based}}\n        \\begin{equation*}\n    J(i,j) = \\frac{\\mathopen|\\mathcal{U}_{ij}\\mathclose|}\n                  {\\mathopen|\\mathcal{U}_{i}\\mathclose| +\n\t\t   \\mathopen|\\mathcal{U}_{j}\\mathclose| -\n\t\t   \\mathopen|\\mathcal{U}_{ij}\\mathclose|}\n       \\end{equation*}\n        \\tiny\n        \\begin{itemize}\n            \\item $\\mathcal{U}_{i}:$ The set of users that have rated item $i$\n            \\item $\\mathcal{U}_{j}:$ The set of users that have rated item $j$\n            \\item $\\mathcal{U}_{ij}:$ The set of users that rated items $i$ and $j$ in common\n            \\item $\\mathopen|\\mathcal{U}_{i}\\mathclose|:$ The number of users in set $\\mathcal{U}_{i}$\n            \\item $\\mathopen|\\mathcal{U}_{j}\\mathclose|:$ The number of users in set $\\mathcal{U}_{j}$\n            \\item $\\mathopen|\\mathcal{U}_{ij}\\mathclose|:$ The number of users in set $\\mathcal{U}_{ij}$\n        \\end{itemize}\n    \\end{columns}\n\\end{frame}\n\\subsection{K-Nearest Neighbors Algorithm}\n\\begin{frame}\n    \\frametitle{K-Nearest Neighbors Algorithm}\n    \\only<1>{\n        \\vspace{2cm}\n        \\centering\n        \\textbf{The K-Nearest Neighbors algorithm}\n    }\n    \\vspace{-1cm}\n    \\begin{itemize}\n\t\\item[]<2-> \\textbf{Step 1:} Select users that have rated $Item_B$.\n\t\\item[]<3-> \\textbf{Step 2:} Compute the similarities between $User_A$ and the users that have\n\trated $Item_B$.\n\t\\item[]<4-> \\textbf{Step 3:}  Sort the similarities in descending order.\n\t\\item[]<5-> \\textbf{Step 4:}  Choose how many neighbors will contribute in the rating\n\tprediction by selecting the top $\\mathcal{K}$ out of all the available\n\tneighbors($\\mathcal{K}$ can be in range [1 - $\\mathcal{N}$] where $\\mathcal{N}$ is all\n\tthe available neighbors).\n\t\\item[]<6-> \\textbf{Step 5:} Use an aggregation formula to calculate the rating prediction of\n\t$User_A$ to $Item_B$. In this case the weighted sum is used.\n\\begin{equation*}\n\t\\hat{r}(User_A,Item_B) = \\frac{\\sum_{u \\in \\mathcal{K}}{similarity(User_A,User_u) * r(User_u,Item_B)}}\n\t\t\t\t\t\t    {\\sum_{u \\in \\mathcal{K}}{\\mathopen|similarity(User_A,User_u)\\mathclose|}}\n\\end{equation*}\n\\end{itemize}\n\\end{frame}\n", "meta": {"hexsha": "45482c1285ddebb161324c349062344ea4e156b6", "size": 21838, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "dipoma_presentation/sections/section_2.tex", "max_stars_repo_name": "tseste/Recursive-K-Nearest-Neighbors", "max_stars_repo_head_hexsha": "5e35c643dc8c530102554492c56bfcf05b242298", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-06T16:08:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T16:08:44.000Z", "max_issues_repo_path": "dipoma_presentation/sections/section_2.tex", "max_issues_repo_name": "tseste/Recursive-K-Nearest-Neighbors", "max_issues_repo_head_hexsha": "5e35c643dc8c530102554492c56bfcf05b242298", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dipoma_presentation/sections/section_2.tex", "max_forks_repo_name": "tseste/Recursive-K-Nearest-Neighbors", "max_forks_repo_head_hexsha": "5e35c643dc8c530102554492c56bfcf05b242298", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.5673469388, "max_line_length": 120, "alphanum_fraction": 0.5311383826, "num_tokens": 7039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3137650671384207}}
{"text": "\n\\section{Introduction}\n\\label{s:intro}\n\nIn this work, we successfully replicated the results of the article \\textit{A Neurodynamical Model for Working Memory}\\supercite{bib:NeurodynamicalModel} written by Razvan Pascanu and Herbert Jaeger.\nThis replication has been done using Python, and the code is available on \\href{https://github.com/theoboraud/ESN}{GitHub}\\supercite{bib:githubRepo}.\nIn their article, they propose (1) a way to implement working memory and (2) a way to characterise working memory states. \\\\\n\\\\\n(1) First, they implemented a working memory model in the form of a Recurrent Neural Network (RNN), more precisely an Echo State Network (ESN).\nIn their model, working memory corresponds to special output units trained to maintain information through feedback connections.\nTheir model had been trained to predict the next character in a sequence randomly generated depending on a context, and to maintain this context in working memory in order to help the prediction. We replicated the same model, trained it to solve mostly the same task and obtained comparable results. \\\\\n\\\\\n(2) They characterised the working memory states of their model by defining a notion of attractors for input driven dynamical systems.\nIn autonomous dynamical systems the memory states could have been characterised for instance by the stable fixed points of the dynamic.\nHowever with inputs, these points are transformed into blobs stable against input that does not aim to change the memory state.\nIn our replication we also obtained qualitatively the same result.\nHowever in the paper they go further and propose a method to automatically find the attractors of an input driven dynamical system.\nThey applied this method only to a toy model and not to the working memory model so we did not implement that part. \\\\\n\\\\\nIn \\textbf{Section~\\ref{s:method}} we give all the implementation details of the model and the tasks it aims to solve.\nWe also highlight the few details that were missing in the paper and that we had to make a choice on in order to reproduce the results.\nThen, in \\textbf{Section~\\ref{s:result}}, we compare the results we obtain to their results in the former article, to see whether or not we had been able to successfully replicate the experiments.\n\n\\section{Methods}\n\\label{s:method}\n\n\\subsection{Model}\n\\label{s:model}\n\nTheir model is a slightly modified Echo State Network, a special kind of Recurrent Neural Network where only the readout weights are trained.\n\\textbf{Figure \\ref{fig:architecture}} illustrates and sums up the overall architecture of the model.\nIt is composed of a recurrent internal layer of size $\\mathbf{N}$, a.k.a. reservoir, $\\mathbf{K}$ input, $\\mathbf{L}$ normal output units that are not fed back to the reservoir, and $\\mathbf{WM}$ additional special output units.\nThey call the latter the Working Memory units (or WM-units).\nThese WM-units have a recurrent trainable connection to other WM-units (including themselves), and a feedback connection to the reservoir units.\n\nIn the following we use the following notations to describe the dynamic of their model:\n\\begin{itemize}\n    \\item Input units activations $\\mathbf{u}$, with weights matrix $\\mathbf{W^{in}}$ for input connections;\n    \\item Internal units activations $\\mathbf{x}$, with weights matrix $\\mathbf{W}$ for internal connections;\n    \\item Output units activations $\\mathbf{y}$, with weights matrix $\\mathbf{W^{out}}$ for output connections;\n    \\item WM-units activations $\\mathbf{m}$, with weights matrix $\\mathbf{W^{mem}}$ for connections from the input units, the reservoir and the WM-units to the WM-units;\n    \\item Weights matrix $\\mathbf{W^{b}}$ for the feedback connections from the WM-units to the reservoir.\n\\end{itemize}\n\nGiven these notations, the dynamic of their model is as follow:\n\\begin{itemize}\n    \\item Eq. (\\ref{eq:xn+1}) represents the dynamic of the internal units. This dynamic involves at the same time the state of the internal units given their previous state, the previous state of the WM-units and the actual state of input units. We use $\\mathbf{}{f}$ to subsume its activation functions, which are the hyperbolic tangent in this model.\n    \\begin{equation} \\label{eq:xn+1}\n        x(n+1) = f(W^{in}u(n+1) + Wx(n) + W^{b}m(n))\n    \\end{equation}\n\n    \\item Eq. (\\ref{eq:mn+1}) represents the dynamic of the WM-units. This dynamic involves the state of the WM-units given the actual state of input and internal units, and the actual state of the WM-units. The sharp threshold function $\\mathbf{f^{m}}$ is the activation function for the WM-units, and is given by Eq. (\\ref{eq:fm}), while $\\mathbf{W^{mem}}$ is computed by linear regression during the step 1 of the model \\textit{Training} phase as shown in Eq. (\\ref{eq:Wmem}).\n    \\begin{equation} \\label{eq:mn+1}\n        m(n+1) = f^{m}(W^{mem}(u(n+1), x(n+1)))\n    \\end{equation}\n\n    \\item Eq. (\\ref{eq:fm}) is the sharp threshold function used as the activation function of the WM-units.\n    \\begin{equation} \\label{eq:fm}\n        f^{m} = \\begin{cases}\n            -0.5 \\; \\; x\\leq 0. \\\\\n            +0.5 \\; \\; x>0. \\end{cases}\n    \\end{equation}\n\n    \\item Eq. (\\ref{eq:yn+1}) represents the dynamic of the output units. This dynamic involves the state of the output units given the actual state of input and internal units. $\\mathbf{f^{out}}$ is the activation function of the output units, and is the Identity function, while $\\mathbf{W^{out}}$ will be computed by linear regression during the step 2 of the model \\textit{Training} phase as shown in Eq. (\\ref{eq:Wout}).\n    \\begin{equation} \\label{eq:yn+1}\n        y(n+1) = f^{out}(W^{out}(u(n+1), x(n+1)))\n    \\end{equation}\n\n    \\item Eq. (\\ref{eq:Wmem}) is the equation to compute the weights matrix for WM-units using linear regression. The activations of the reservoir, the input and the target of the WM-units are all stored in matrix $\\mathbf{H}$, $\\mathbf{M_{target}}$ is the target of the WM-units, and $\\dagger$ stands for the pseudo-inverse.\n    \\begin{equation} \\label{eq:Wmem}\n        W^{mem} = (H^{\\dagger} \\cdot M_{target})^T\\\\\n    \\end{equation}\n\n    \\item Eq. (\\ref{eq:Wout}) is the equation to compute the weights matrix for output units using linear regression. The activations of the reservoir and the input units are all stored in matrix $\\mathbf{G}$, $\\mathbf{Y_{target}}$ is the target of the output units, and $\\dagger$ stands as before for the pseudo-inverse.\n    \\begin{equation} \\label{eq:Wout}\n        W^{out} = (G^{\\dagger} \\cdot f^{out^{-1}}(Y_{target}))^T\\\\\n    \\end{equation}\n\n\\end{itemize}\n\nWhen the model starts, the weights are initialized as stated:\n\\begin{itemize}\n    \\item We have $\\mathbf{K}=13$, $\\mathbf{N}=1200$, $\\mathbf{L}=65$ and $\\mathbf{WM}=6$.\n    \\item $\\mathbf{W^{in}}$ is of size $\\mathbf{N \\times K}$, with 10\\% of which are +0.5, 10\\% are -0.5, and the rest is 0.\n    \\item $\\mathbf{W}$ is of size $\\mathbf{N \\times N}$, with only 12000 random non-zero connections, which will randomly either take the value +0.1540 or -0.1540.\n    \\item $\\mathbf{W^{b}}$ is of size $\\mathbf{N \\times WM}$, where every weight is either +0.4 or -0.4.\n\n\\end{itemize}\n\n\\begin{figure}[h]\n    \\centering\n    \\includegraphics[width = \\linewidth]{data/Architecture.png}\n    \\caption{Model architecture. See \\textbf{Section~\\ref{s:model}} for further details.}\n    \\label{fig:architecture}\n\\end{figure}\n\n\\subsection{Input generation}\n\nPascanu and Jaeger also describe the method they used to generate the input of the model.\nThe input consists of a constant bias (-0.5) and a column of 12 pixels of an image.\nEach column of 12 pixels of the image is given as input to the network one after the other. \\\\\n\\\\\nThis image represents a sequence of characters, i.e. curly brackets (opened or closed) or 65 other ASCII symbols (e.g. letters in lower cases, numbers...).\nTo each of these characters we associate a number that is its position in an alphabet sequence (see \\textbf{Table~\\ref{tab:alphabet}}).\nFor the sake of simplicity, in the following we say character $i$ for the $i$-th character in that sequence.\nThe sequence of characters is generated randomly using different 7 Markov Chains, and the Markov Chain used depends on the current curly bracket level.\nMore precisely, the next character is either:\n\\begin{itemize}\n    \\item an open (resp. closed) curly bracket thus increasing (resp. decreasing) the current bracket level by 1 to a maximum (resp. minimum) of 6 (resp. 0)\n    \\item or generated with a Markov chain given the last character that was not a curly bracket\n\\end{itemize}\nGiven that the next character is not a curly bracket, if the current bracket level is $\\mathit{j}$, the next character after $\\mathit{i}$ will either be:\n\\begin{itemize}\n    \\item $\\mathit{i} + \\mathit{j} + 1$ modulo 65 with probability $0.8$;\n    \\item any of the 64 other characters from the alphabet with probability $\\frac{0.2}{64} = 0.003125\n$.\n\\end{itemize}\nDuring the training phase, the probability for the next character to be an open (resp. closed) curly bracket is 0.15.\nWhereas in the testing phase it is 0.03, which forces the WM-unit to maintain the current bracket level for a longer time. \\\\\n\\\\\nThe sequence is transformed into an image by displaying and concatenating each of its characters.\nThe characters are displayed using a randomly selected font and then uniformly randomly stretched between 6, 7 or 8 pixels in width.\nFinally a salt-and-pepper noise of amplitude 0.1 and probability 1 is added to the whole image.\\\\\n\\\\\nSee \\textbf{Table \\ref{tab:sequence_example}} to observe an example of input sequence generated from the alphabet in \\textbf{Table \\ref{tab:alphabet}} in \\textbf{Section \\ref{s:input_gen2}}.\n\n\\subsection{Task}\n\nThe aim of the WM-units is to keep track of the current bracket level. When the current bracket level is $\\mathit{k}$, the $\\mathit{k}$ first WM-units should be at +0.5, whereas the remaining ones should be at -0.5. \\\\\n\\\\\nThe aim of the output units is to predict the next character in the sequence when the current character is not a curly bracket.\nThe prediction for the next character should be made in the middle of receiving the current character. If character $i$ should be predicted, then all the output units but the $i$-th one should be set to 0 whereas the $i$-th one should be 1. \\\\\n\n\\begin{figure}[h]\n    \\centering\n    \\includegraphics[width = \\linewidth]{data/Sequence_img.png}\n    \\caption{Input and target outputs of the network. The first row represents the image input sent to the network columns by columns; the second is the target values for WM-units, with each white rows representing the time steps on which the corresponding WM-units has a value of 0.5, and in black when its value is -0.5 (a.k.a. white when the corresponding bracket level has been reached, and black when not); the third one is the target output, with 65 black pixels (value 0) at the middle of the character representation, and the next predicted character represented by a white pixel (value 1) depending of its location in the alphabet (see \\textbf{Table \\ref{tab:alphabet}}).}\n    \\label{fig:archi tecture}\n\\end{figure}\n\n\\subsection{Training and testing}\n\nAs they did, we train $W^{mem}$ and $W^{out}$ separately with different input sequences.\nFirst we train $W^{mem}$ using teacher forcing and then we train $W^{out}$.\nWe use a sequence of 10000 characters to train $W^{mem}$, and of 49000 characters to train $W^{out}$.\nThe teacher signal for training $W^{mem}$ is defined at all times whereas for training $W^{out}$ it is defined only in the middle of characters that are not curly brackets.\nFinally we test the model with a 35000 characters long sequence.\nAs an error on the bracket level would propagate and create more errors, each time the model makes a mistake on the bracket level in the WM-units we count it and correct it.\nThese errors are classified between \\textit{false positives} (i.e. the network detects a bracket when there is none) and \\textit{false negatives} (i.e. the network fails to detect a bracket).\nThe errors made by the output units are also counted but not corrected. The error rate of prediction is then computed given the number of characters the network failed to predict correctly and the total length of the sequence.\n\n\\subsection{Attractors}\n\nFollowing the instructions in the original article, we run the WM model 7 times, each time with a different sequence with no bracket, and forcing the WM-unit to a fixed bracket level (\\textit{k} = 0 for the first, \\textit{k} = 1 for the second, etc...). Each sequence has a length of 6500 characters, for about 45,000 network updates in total. We collect in each case both the reservoir states and the input units. Then, every sets of reservoir states (resp. input vectors) are concatenated, and their first principal components (or PCs) are computed. Finally, for each of the 7 original sets, the first PC of the inputs is plotted against the first two PCs of the reservoir states.\n\n\\subsection{Implementation choices}\n\nIn the original article very few parts were unclear. Pascanu and Jaeger briefly explain how they choose to generate the input, but did not specify the exact method and tools they used to implement it. This subsection aims at listing out the choices we made and the tools we used to obtain similar results than the original paper.\n\n\\subsubsection{Language and libraries}\n\nSince the language used for the former model was not specified, we decide to use Python (3.7.4) to implement our model.\nThe article did not specify which tools they used to transform their symbolic sequence into an image.\nThus, we choose to use the libraries \\href{https://pillow.readthedocs.io/en/stable/}{\\textit{PIL}}, \\href{https://github.com/rougier/freetype-py}{\\textit{FreeType}} and \\href{https://www.scipy.org/}{\\textit{SciPy}} for this purpose.\n\n\\subsubsection{Input sequence alphabet}\n\\label{s:input_gen2}\n\nIn the original paper Pascanu and Jageger did not specify which exact characters they used for their 65 symbols, and therefore not the exact order of this alphabet. For this, we decide to create our own, as shown on \\textbf{Table \\ref{tab:alphabet}}. We can observe in \\textbf{Table \\ref{tab:sequence_example}} an input sequence example in order to further understand the behaviour of the input generation algorithm with our alphabet.\n\n\\begin{table}[!ht]\n    \\centering\n    \\begin{tabular}{|c|}\n        \\hline\n        \\textbf{Alphabet sequence order} \\\\ \\hline \\hline\n        abcdefghijklmnopqrstuvwxyz0123456789\\ !\"\\#\\$\\%\\&'()*+,.-\\_/:;<=>?@€|$[]$§\\\\ \\hline % abcdefghijklmnopqrstuvwxyz0123456789 !\\\"#$%&'()*+,.-_/:;<=>?@|€[]§\n    \\end{tabular}\n    \\caption{Order of alphabet for data generation.}\n    \\label{tab:alphabet}\n\\end{table}\n\n\\begin{table}[!ht]\n    \\centering\n    \\begin{tabular}{|c|}\n        \\hline\n        \\textbf{Input sequence example} \\\\ \\hline \\hline\n        abc\\{eg\\textcolor{red}{0}24\\{7\\{!\\textcolor{red}{o}sw0\\textcolor{red}{-}\\}:=\\{\\{\\textcolor{red}{f}kp\\\\ \\hline\n    \\end{tabular}\n    \\caption{Example of input sequence. Each character in red corresponds to a randomly chosen character which does not depend on the current character and the memory states (with a probability of 20\\%). Use \\textbf{Table \\ref{tab:alphabet}} to understand how the input is selected 80\\% of the time depending on the bracket level (i.e. when the characters are in black).}\n    \\label{tab:sequence_example}\n\\end{table}\n\n\\subsubsection{Font}\n\nWe have not been able to find the fonts used in the original model (\\textit{FreeMono}, \\textit{FreeMono Bold}, \\textit{FreeMono Oblique} and FreeMono Bold Oblique of \\href{https://gimp.software/2018/11/13/download-gimp-2-3-6/}{Gimp 2.3.6}).\nTherefore, we try in the first place to use these \\href{https://www.fontspace.com/gnu-freefont/freemono}{\\textit{FreeMono}} (classic, oblique, bold and bold oblique) fonts.\nHowever, as we encounter more errors than in the original paper, we use the \\href{https://fonts.google.com/specimen/Inconsolata}{\\textit{Incosolata}} (regular and bold) fonts distributed by Google, which give far better results.\n\n\\begin{figure}[h]\n    \\centering\n    \\includegraphics[width = \\linewidth]{data/input_freemono.png}\n    \\includegraphics[width = \\linewidth]{data/input_inconsolata.png}\n    \\caption{Images example of a sequence using 2 different set of fonts. The first image is computed using \\textit{FreeMono}, the second is using \\textit{Inconsolata}.}\n    \\label{fig:input_imgs}\n\\end{figure}\n\n\\subsubsection{Noise}\n\nPascanu and Jaeger did not specify in the original the probability of the salt-and-pepper noise. Thus, we tried a salt-and-pepper noise of amplitude 0.1, and probability 1. \\\\\n\n\\subsubsection{Warm up in Principal Component Analysis}\n\nWe can observe that for each memory state the first few points do not necessarily gather with their cluster. Thus, the first 100 time steps are removed from display only for clarity purposes.\n\n\\section{Results}\n\\label{s:result}\n\n\\subsection{Network}\nAccording to the former article, the experiment has been run over 30 runs for the network.\nWe assume that each time, it uses different randomly generated training and testing sequences, and reservoir, input and feedback weights. Those 30 runs are then used to compute mean and standard deviation of different performance measures. In the following Tables we use the color light green for the \\textit{FreeMono}\\footnote{Seed used for results using \\textit{FreeMono}: \\textit{1639617780}} fonts (first row on result tables), dark green for \\textit{Inconsolata}\\footnote{Seed used for results using \\textit{Inconsolata}: \\textit{3939310522}} (second row), and black for their former results (third row). \\\\\n\\\\\nFirst, as they did in the original paper we inspect the WM-units performance.\nWe dissociate the errors made by the WM-units into false negative errors (when the network did not recognize a curly bracket as such) and false positive errors (when the network detects the character as a curly bracket while it is not).\nThese errors are counted, and then transformed into three different percentages, depending on the number of curly brackets in the sequence, the number of characters, or the number of time steps (i.e. length of the input image in pixels). The \\textbf{Table \\ref{tab:errors_wm}} shows the results obtained. \\\\\n\\\\\n\n\\begin{table}[!ht]\n    \\centering\n    \\begin{tabular}{|C{23mm}|C{20mm}|C{22mm}|C{24mm}|C{24mm}|}\n        \\hline\n        Type of error & Number of errors & Percentage of curly brackets ($\\%$) & Percentage of characters ($\\%$) & Percentage of time steps ($\\%$) \\\\\n        \\hline\n        \\multirow{3}{*}{false negatives} & \\textcolor{mygreen}{$54.7 \\pm 6.6$} & \\textcolor{mygreen}{$3.01 \\pm 0.35$} & \\textcolor{mygreen}{$0.16 \\pm 0.020$} & \\textcolor{mygreen}{$0.022 \\pm 0.003$} \\\\\n        & \\textcolor{mygreen2}{$0.2 \\pm 0.4$} & \\textcolor{mygreen2}{$0.01 \\pm 0.02$} & \\textcolor{mygreen2}{$0 \\pm 0.001$} & \\textcolor{mygreen2}{$0 \\pm 0$} \\\\\n        & $7.2 \\pm 6.5$ & $0.34 \\pm 0.30$ & $0.02 \\pm 0.018$ & $0.003 \\pm 0.002$ \\\\ \\hline\n\n        \\multirow{3}{*}{false positives} & \\textcolor{mygreen}{$1252.6 \\pm 48.5$} & \\textcolor{mygreen}{$68.97 \\pm 2.44$} & \\textcolor{mygreen}{$3.77 \\pm 0.148$} & \\textcolor{mygreen}{$0.511 \\pm 0.020$} \\\\\n        & \\textcolor{mygreen2}{$97.2 \\pm 34.5$} & \\textcolor{mygreen2}{$5.37 \\pm 1.89$} & \\textcolor{mygreen2}{$0.29 \\pm 0.104$} & \\textcolor{mygreen2}{$0.040 \\pm 0.014$} \\\\\n        & $59.8 \\pm 21.6$ & $2.84 \\pm 1.02$ & $0.17 \\pm 0.061$ & $0.024 \\pm 0.008$ \\\\ \\hline\n\n        \\multirow{3}{*}{total} & \\textcolor{mygreen}{$1307.3 \\pm 49.3$} & \\textcolor{mygreen}{$71.98 \\pm 2.44$} & \\textcolor{mygreen}{$3.94 \\pm 0.151$} &  \\textcolor{mygreen}{$0.534 \\pm 0.020$} \\\\\n        & \\textcolor{mygreen2}{$97.4 \\pm 34.6$} & \\textcolor{mygreen2}{$5.37 \\pm 1.89$} & \\textcolor{mygreen2}{$0.29 \\pm 0.104$} & \\textcolor{mygreen2}{$0.040 \\pm 0.014$} \\\\\n        & $67.0 \\pm 22.9$ & $3.18 \\pm 1.09$ & $0.19 \\pm 0.065$ & $0.027 \\pm 0.009$ \\\\ \\hline\n\n    \\end{tabular}\n    \\caption{Number of erroneous WM states obtained by the ESN, averaged over 30 runs. Colour light green is used for results using \\textit{FreeMono} as font, dark green for \\textit{Inconsolata}, and black for the original results.}\n    \\label{tab:errors_wm}\n\\end{table}\n\nThen we look at the characters falsely identified as curly brackets. The \\textbf{Table \\ref{tab:false_positives}} shows how the characters highlighted in the original experiment are falsely identified as curly brackets.\n\n\\begin{table}[!ht]\n    \\centering\n    \\begin{tabular}{|C{15mm}|C{32mm}|C{32mm}|C{32mm}|}\n        \\hline\n        Character & Number of times the character is in testing sequences & Number of times the counter increased & Number of times the counter decreased \\\\ \\hline \\hline\n\n        \\multirow{3}{*}{\"(\"} & \\textcolor{mygreen}{$508.7 \\pm 23.8$} & \\textcolor{mygreen}{$128.07 \\pm 14.08$} & \\textcolor{mygreen}{$3.8 \\pm 2.0$} \\\\\n        & \\textcolor{mygreen2}{$514.2 \\pm 23.7$} & \\textcolor{mygreen2}{$93.40 \\pm 34.50$} & \\textcolor{mygreen2}{$0 \\pm 0$} \\\\\n        & $499.5 \\pm 22.3$ & $21.5 \\pm 10.1$ & $0 \\pm 0$ \\\\ \\hline\n\n        \\multirow{3}{*}{\")\"} & \\textcolor{mygreen}{$516.7 \\pm 19.7$} & \\textcolor{mygreen}{$12.10 \\pm 4.21$} & \\textcolor{mygreen}{$3.9 \\pm 1.7$} \\\\\n        & \\textcolor{mygreen2}{$516.8 \\pm 18.2$} & \\textcolor{mygreen2}{$0 \\pm 0$} & \\textcolor{mygreen2}{$0.3 \\pm 0.7$}\\\\\n        & $502.4 \\pm 18.6$ & $0 \\pm 0$ &  $0.5 \\pm 0.2$ \\\\ \\hline\n\n        \\multirow{3}{*}{\"[\"} & \\textcolor{mygreen}{$513.1 \\pm 18.8$} & \\textcolor{mygreen}{$191.83 \\pm 28.71$} & \\textcolor{mygreen}{$3.8 \\pm 1.6$} \\\\\n        & \\textcolor{mygreen2}{$507.9 \\pm 15.6$} & \\textcolor{mygreen2}{$0 \\pm 0$} & \\textcolor{mygreen2}{$0 \\pm 0$}\\\\\n        & $496.2 \\pm 22.8$ & $5.8 \\pm 5.1$ & $6.0 \\pm 5.4$ \\\\ \\hline\n\n        \\multirow{3}{*}{\"]\"} & \\textcolor{mygreen}{$509.6 \\pm 18.3$} & \\textcolor{mygreen}{$9.53 \\pm 3.58$} & \\textcolor{mygreen}{$3.0 \\pm 1.4$}\\\\\n        & \\textcolor{mygreen2}{$514.4 \\pm 18.3$} & \\textcolor{mygreen2}{$0.13 \\pm 0.34$} & \\textcolor{mygreen2}{$0 \\pm 0$}\\\\\n        & $501.3 \\pm 15.1$ & $0.05 \\pm 0.03$ & $6.0 \\pm 5.4$ \\\\ \\hline\n\n        \\multirow{3}{*}{\"@\"} & \\textcolor{mygreen}{$507.0 \\pm 20.8$} & \\textcolor{mygreen}{$10.13 \\pm 2.84$} & \\textcolor{mygreen}{$3.9 \\pm 2.1$} \\\\\n        & \\textcolor{mygreen2}{$508.8 \\pm 22.5$} & \\textcolor{mygreen2}{$0 \\pm 0$} & \\textcolor{mygreen2}{$0 \\pm 0$} \\\\\n        & $492.7 \\pm 21.3$ & $25.1 \\pm 14.1$ & $0.2 \\pm 0.1$ \\\\ \\hline\n\n        \\multirow{3}{*}{other} & \\multirow{3}{*}{-} & \\textcolor{mygreen}{$656.23 \\pm 30.19$} & \\textcolor{mygreen}{$226.2 \\pm 22.5$} \\\\\n        & & \\textcolor{mygreen2}{$3.13 \\pm 2.03$} & \\textcolor{mygreen2}{$0.2 \\pm 0.6$} \\\\\n        & & $0.05 \\pm 0.04$ & $0.6 \\pm 0.5$ \\\\ \\hline\n    \\end{tabular}\n    \\caption{Trigger characters for false positives, averaged over 30 runs. Colour light green is used for results using \\textit{FreeMono} as font, dark green for \\textit{Inconsolata}, and black for the original results.}\n    \\label{tab:false_positives}\n\\end{table}\n\nAs in the former article, we measure the average absolute value of $\\mathbf{W^{mem}}$ weights over the 30 runs, which can be observed in \\textbf{Table \\ref{tab:wmem}}. \\\\\n\\\\\n\n\\begin{table}[!ht]\n    \\centering\n    \\begin{tabular}{|c|C{35mm}|}\n        \\hline\n        \\begin{tabular}[c]{@{}c@{}}considered weights\\end{tabular} & \\multicolumn{1}{c|}{\\begin{tabular}[c]{@{}c@{}}average absolute value\\end{tabular}}\\\\ \\hline \\hline\n\n        \\multirow{3}{*}{input to WM-units weights} &\n        \\textcolor{mygreen}{$0.3395 \\pm 0.2975$} \\\\\n        & \\textcolor{mygreen2}{$0.2834 \\pm 0.2445$} \\\\\n        & $0.2327 \\pm 0.1813$ \\\\ \\hline\n\n        \\multirow{3}{*}{reservoir to WM-units weights} &\n        \\textcolor{mygreen}{$0.0971 \\pm 0.0920$} \\\\\n        & \\textcolor{mygreen2}{$0.0852 \\pm 0.0782$} \\\\\n        & $0.0667 \\pm 0.0591$ \\\\ \\hline\n\n        \\multirow{3}{*}{WM-units to WM-units weights} &\n        \\textcolor{mygreen}{$0.9217 \\pm 0.6893$} \\\\\n        & \\textcolor{mygreen2}{$0.7003 \\pm 0.5436$} \\\\\n        & $0.5825 \\pm 0.5627$ \\\\ \\hline\n\n    \\end{tabular}\n    \\caption{Average learned output weights of the ESN over 30 runs. Colour light green is used for results using \\textit{FreeMono} as font, dark green for \\textit{Inconsolata}, and black for the original results.}\n    \\label{tab:wmem}\n\\end{table}\n\nAs we can see in \\textbf{Tables \\ref{tab:errors_wm} and \\ref{tab:false_positives}}, by using the \\textit{FreeMono} font we obtain way more errors in the WM-unit than in the original paper. However by using the \\textit{Inconsolata} font we obtain similar results. \\\\\n\\\\\nFinally, we compute the average error rate for the prediction made in the output units. We count only the errors in the middle of the presentation of a character that is not a curly bracket, as the target is defined only during these time steps.\nOver the 30 runs, with the \\textit{Freemono} font we find an error rate of \\textbf{26.02 $\\pm$ 0.32\\%}, for \\textbf{24.83 $\\pm$ 0.27\\%} in the former article. With the \\textit{Inconsolata} font we obtain an error rate of \\textbf{22.22 $\\pm$ 0.25\\%}. These three results are very similar. \\\\\n\\\\\nIt is important to note that, during our various testing, and as in the original model, the network never changes the WM-units to an invalid state or by increasing or decreasing the counter by more than one, attesting their assumption that any error would be the result of misclassification of a character (as expected), and not any other subprocesses of the WM-units.\n\n\\subsection{Attractors}\n\nAs in the original paper, for both \\textit{Freemono} and \\textit{Inconsolata} font we can see clusters of points in the first two principal components(see dark projection in \\textbf{Figure \\ref{fig:PCA}}). Each of this cluster seems to be an attractor (as they defined in the original paper) associated to a memory state. It is stable against the characters that are not curly brackets, and the curly brackets makes it move from one to the other.\n\n\\begin{figure}[h]\n    \\centering\n    \\includegraphics[width = .45\\linewidth]{data/FreeMono_PCA.png}\n    \\includegraphics[width = .45\\linewidth]{data/Inconsolata_PCA.png}\n    \\caption{Principal Component Analysis results. Each coloured column represents the several reservoir states for each memory states in the form of attractors, with \\textit{FreeMono} results on the left, and \\textit{Inconsolata} on the right. For each memory states we do not display the first 100 points. We can observe that the points for the different working memory states are clustered much more clearly than in the original article, spanning a much larger range. However, being only a quantitative difference, the results stay very similar from the original}\n    \\label{fig:PCA}\n\\end{figure}\n\n\\section{Conclusion}\n\nConsidering the original tools were not sourced, we needed to use our own tools, whether it be for the language, the fonts but also for the input generation, which could easily justify the differences between the original results and the ones found in this replication. However, these differences also highlight the fact that this model is really modular and consistent, giving similar results despite the differences in fonts and error rates. \\\\\n\\\\\nIn the end, we consider that we have been able to successfully replicate the result obtained by Pascanu and Jaeger in \\textit{A Neurodynamical Model for Working Memory}.\n%With the same ESN-based model (i.e. mainly composed of random connections)\nVery few information were missing in the original paper, such as the input generation methods from string to image they used, a more precise definition of the noise they added or the ASCII characters alphabet they used.\n", "meta": {"hexsha": "94a93cd25346f07d7c935d1a1d07811149a612ce", "size": 27723, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ReScience Article/content.tex", "max_stars_repo_name": "rougier/ESN", "max_stars_repo_head_hexsha": "4340149c63c096949fb3d28e252e0710d7691fa8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-01-18T13:54:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-01T10:08:35.000Z", "max_issues_repo_path": "ReScience Article/content.tex", "max_issues_repo_name": "rougier/ESN", "max_issues_repo_head_hexsha": "4340149c63c096949fb3d28e252e0710d7691fa8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-12-27T21:30:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:52:21.000Z", "max_forks_repo_path": "ReScience Article/content.tex", "max_forks_repo_name": "rougier/ESN", "max_forks_repo_head_hexsha": "4340149c63c096949fb3d28e252e0710d7691fa8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-11-06T02:23:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-01T09:07:25.000Z", "avg_line_length": 81.2991202346, "max_line_length": 682, "alphanum_fraction": 0.7186090971, "num_tokens": 7994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3137650671384207}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\marginpar{Wednesday\\\\ 2021-11-10, \\\\ compiled \\\\ \\today}\n\nRegarding books, the course is a synthesis of several topics, so many books cover them but they also include lots of other material.\n\nFor plasma physics, ``Plasma physics for astrophysics'' by Russel M.\\ Kulsrud.\n\nFor transport, ``Astrophysics of cosmic rays''.\n\n\\section{Basics of plasma physics}\n\nFrom the microphysical point of view, cosmic rays are just electric charges moving in a plasma, which they in turn  affect. \n\nLoosely, a plasma is ionized gas; however the interstellar medium is also at temperatures of \\SI{e4}{K} to \\SI{e6}{K}, this is also true for the intergalactic medium, which has a much lower density and similar temperatures, \n\nThis also applies to the medium in clusters, which has a higher temperature, of the order of \\SI{e8}{K} but lower densities, \\SI{e-3}{cm^{-3}}.\n\nMagnetic fields are sourced by currents, which cosmic rays affect. \nElectric fields, on the other hand, are ``short-circuited'' since the conductivity is very large. \n\nIf it is difficult to have an electric field, how can particles be accelerated? \nWe will simply assume that cosmic rays, which are non-thermal, exist. \n\nFirst, though, we will try to understand how the plasma works, then we will look at the non-thermal particles, and finally we will put them together.\n\nFor simplicity, let us consider a plasma made of protons (with density \\(n_i\\)) and electrons (with density \\(n_e\\)). \nMaxwell' equations will read \n%\n\\begin{subequations}\\label{eq:maxwell}\n\\begin{align}\n\\vec{\\nabla} \\cdot \\vec{E} &= 4 \\pi \\zeta  \\\\\n\\vec{\\nabla} \\cdot \\vec{B} &= 0  \\\\\n\\vec{\\nabla} \\times \\vec{E} &= - \\frac{1}{c} \\pdv{\\vec{B}}{t}  \\\\\n\\vec{\\nabla} \\times \\vec{B} &= \\frac{4 \\pi }{c} \\vec{J} + \\frac{1}{c} \\pdv{\\vec{E}}{t}\n\\,,\n\\end{align}\n\\end{subequations}\n%\nwhere \\(\\zeta = n_i e - n_e e\\), while the current reads \\(\\vec{J} = n_i e \\vec{v}_i - n_e e \\vec{v}_e\\). \n\nThe interactions between these will be Coulomb ones. \nAt thermal equilibrium, we will have charge neutrality, so \\(n_i = n_e = n_0\\). \n\n\\paragraph{Screening}\n\nSuppose we add a positive charge in a neutral medium, at \\(\\vec{r} = 0\\). \nThen, the divergence of \\(\\vec{E}\\) will be \n%\n\\begin{align} \\label{eq:electric-field-perturbation}\n\\vec{\\nabla} \\cdot \\vec{E} = 4 \\pi n_i e - 4 \\pi n_e e + 4 \\pi e \\delta (\\vec{r})\n\\,,\n\\end{align}\n%\nwhere the tilde means that the densities are perturbed. \n\nWe will assume that the perturbation induced by this is small. The potential energy drop of a particle at a distance \\(d\\) from another is \\(e^2 / d\\), so if we assume \\(e^2 / d \\ll k_B T\\) the thermal background remains fixed, and is not ``broken'' by Coulomb interactions. \nThe typical distance between particles will be \\(d \\sim n_0^{-1/3}\\), so the weak perturbation condition will read \\(e^2 n_0^{1/3} \\ll k_B T\\). \n\nWhat we want to do now is to solve this equation \\eqref{eq:electric-field-perturbation} for the electric field.\n\nIn order to do so, we need to discuss the dependence of the phase space distribution on the energy of each particle, which we call \\(\\epsilon \\). \nAt zeroth order, we will have \n%\n\\begin{align}\n\\widetilde{n}_i = n_0 \\exp(- \\frac{\\epsilon}{k_B T})\n\\,,\n\\end{align}\n%\nwhich we assume, on mesoscopic scales, to average out to \\(\\expval{e^{- \\epsilon / k_B T}} = 1\\).\nIn the following discussion we apply this mesoscopic approximation by setting \\(\\epsilon \\equiv k_B T\\), but we do leave in the external perturbation to the potential. \n\nThe external potential will perturb the energy \\(\\epsilon \\) by \\(e \\varphi \\) where \\(\\varphi \\) is the electric potential, so \n%\n\\begin{subequations}\n\\begin{align}\n\\widetilde{n}_i &= n_0 \\exp(\\frac{- \\epsilon + e \\varphi }{k_B T})  \\\\\n\\widetilde{n}_e &= n_0 \\exp(\\frac{- \\epsilon - e \\varphi }{k_B T})\n\\,,\n\\end{align}\n\\end{subequations}\n%\nand we can use \\(\\vec{E} = - \\vec{\\nabla} \\varphi \\): then, for \\(r \\neq 0\\) we will have\n%\n\\begin{align}\n\\vec{\\nabla}^2 \\varphi = \n- 4 \\pi e n_0 \\exp(- \\frac{\\epsilon }{k_B T}) \n\\exp( - \\frac{e \\varphi }{k_B T})\n+ 4 \\pi e n_0 \\exp(- \\frac{\\epsilon }{k_B T}) \\exp( \\frac{e \\varphi }{k_B T})\n\\,,\n\\end{align}\n%\nwhich we can expand up to linear order: \n%\n\\begin{subequations}\n\\begin{align}\n\\vec{\\nabla}^2 \\varphi &= \n- 4 \\pi e n_0 \\exp(- \\frac{\\epsilon }{k_B T}) \n\\qty( \\exp(- \\frac{e \\varphi }{k_B T}) - \\exp(\\frac{e \\varphi }{k_B T}))  \\\\\n&\\approx \n- 4 \\pi e n_0 \\exp(- \\frac{\\epsilon }{k_B T}) \n\\qty(1 - \\frac{e \\varphi }{k_BT} - 1 - \\frac{e \\varphi }{k_B T})  \\\\\n&=\n8 \\pi e \\underbrace{n_0 \\exp(- \\frac{\\epsilon }{k_B T})}_{ = n_0 } \n\\frac{e }{k_B T} \\varphi\n\\,.\n\\end{align}\n\\end{subequations}\n\nThe prefactor had the dimensions of an inverse square length; further, we include the exponential \\(e^{- \\epsilon / k_BT}\\) into the unperturbed density \\(n_0 \\).\n\n\\begin{extracontent}\nWe are being a bit cavalier in the distinction between the phase space density \\(f(\\vec{x}, \\vec{p})\\) and the spatial number density \\(n(\\vec{x})\\). \n\nRoughly speaking, the first is defined so that its integral over all of \\(\\dd[3]{x} \\dd[3]{p}\\) yields the total number of particles, while for the second the integral need only be done over \\(\\dd[3]{x}\\). \nWe can recover the number density by integrating the phase space density: specifically, the correct normalization in natural units reads \n%\n\\begin{align}\nn(\\vec{x}) = \\frac{g}{(2 \\pi )^3} \\int f(\\vec{x}, \\vec{p}) \\dd[3]{p}\n\\,,\n\\end{align}\n%\nwhere \\(g\\) is the number of helicity states of the particle at hand. \n\nThe isotropic Maxwellian phase space distribution (which approximates both the Bose-Einstein and Fermi ones) reads \\(f(\\vec{x}, \\vec{p}) = \\exp(- \\epsilon (\\vec{p}) / k_B T)\\), where \\(\\epsilon (\\vec{p}) = \\sqrt{m^2 + \\vec{p}^2}\\) is the energy corresponding to the momentum \\(\\vec{p}\\). \n\nThe way the specific integral is computed for this density does not really matter (and is actually rather complicated in general), but we call the result \\(n_0 \\) --- it is independent of \\(\\vec{x}\\), since the phase space density is as well.\n\nNow, we insert an external potential energy term to the \\emph{phase space} density, mapping \\(\\epsilon \\to \\epsilon + U(\\vec{x})\\) (which for us will be \\(U(\\vec{x}) = - e \\varphi (\\vec{x})\\)). The integral then reads \n%\n\\begin{align}\nn(\\vec{x}) = \\frac{g}{(2 \\pi )^3} \\int \\exp(- \\frac{\\epsilon }{k_B T}) \\exp(- \\frac{U(\\vec{x})}{k_B T}) \\dd[3]{p} = n_0 \\exp(- \\frac{U(\\vec{x})}{k_B T})\n\\,.\n\\end{align}\n\\end{extracontent}\n\n\nWe define the \\textbf{Debye length}\n%\n\\begin{align}\n\\lambda _D = \\qty(\\frac{k_B T}{8 \\pi n_0 e^2})^{1/2}\n\\,,\n\\end{align}\n%\nin terms of which (with the assumption of spherical symmetry for our problem) the equation reads \n%\n\\begin{align}\n\\nabla^2\\varphi = \\frac{1}{r^2} \\pdv{r} \\qty(r^2 \\pdv{\\varphi }{r}) \n= \\frac{1}{\\lambda _D^2} \\varphi \n\\,,\n\\end{align}\n%\nwhich is solved by looking at \\(f = r \\varphi \\): then, \n%\n\\begin{align}\n\\dv[2]{f}{r} = \\frac{f}{\\lambda _D^2}\n\\,,\n\\end{align}\n%\nwhich means \\(f = A \\exp(- r / \\lambda _D)\\) (we discard the unphysical, exponentially diverging solution). \nInserting back our particle boundary condition to fix \\(A\\), we get \n%\n\\begin{align}\n\\varphi = \\frac{e}{r} \\exp(- \\frac{r}{\\lambda _D})\n\\,.\n\\end{align}\n\nThis is physically meaningful: there is a \\textbf{screening effect} on charges, on length scales of \\(\\lambda _D\\). \n\nFor this to happen, however, we need to have enough charges to screen the inserted one: the number of particles in the Debye volume, \\(\\sim n_0 \\lambda _D^3\\), must be much larger than 1. \nIn a way, this is also a mesoscopic statistical requirement. \n\nThis can be written as \n%\n\\begin{align}\nn_0 \\frac{(k_BT)^{3/2}}{( 8 \\pi e^2)^{3/2} n_0^{3/2}} \n= \\frac{(k_BT)^{3/2}}{( 8 \\pi e^2)^{3/2} n_0^{1/2}} \n\\gg 1\n\\,,\n\\end{align}\n%\nwhich shows that, counter-intuitively, this condition is easier to fulfill for under-dense plasmas. \n\nThe path length for Coulomb scattering, \\(\\lambda _C\\), should be much larger than both \\(\\Delta r \\approx n^{-1/3}\\) (the separation between particles) and \\(\\lambda _D\\). \n\nIt can be estimated by \n%\n\\begin{align}\n\\lambda _C = \\frac{1}{n_0 \\sigma _C} = \\frac{(k_B T)^2}{n_0 e^{4}} \\gg n^{-1/3} \n\\,,\n\\end{align}\n%\nwhere \\(e^2 / b = k_B T\\) gives us a limit for the Coulomb interaction length, therefore \\(\\sigma _C \\approx b^2 \\approx (e^2 / k_B T)^2\\). \n\n\n\\begin{extracontent}\nIt can be shown that \\(\\lambda _C \\gg \\lambda _D\\) is equivalent to the condition that many particles should be contained in a single Debye length: the condition reads \n%\n\\begin{align}\n\\lambda _C = \\frac{(k_B T)^2}{n_0 e^{4}} &\\gg \\sqrt{\\frac{k_B T}{8 \\pi n_0 e^2}} = \\lambda _D   \\\\\n(8 \\pi)^2 n_0 \\qty(\\frac{k_B T}{8 \\pi n_0 e^2})^2 &\\gg  \\qty( \\frac{k_BT}{ 8 \\pi n_0 e^2})^{1/2}  \\\\\n\\lambda _D^3 &\\gg \\frac{1}{(8 \\pi )^2 n_0 }\n\\,.\n\\end{align}\n\\end{extracontent}\n\nCollective effects dominate the dynamics of a plasma, while the effect of a single charge quickly becomes negligible.\n\n\\paragraph{Propagation modes in a plasma}\n\nWe will now do an exercise in perturbation theory: which perturbations are allowed, beyond electromagnetic waves? \nCertain modes are ``allowed'', in that they do not die out. \n\nA lot of interesting physics come from the fact that each particle interacts with the collection of all the others. \n\nPerturbations which are unstable are interesting, but they break our perturbative approach. \n\nThe fields in Maxwell's equations \\eqref{eq:maxwell} are assumed to start out at zero in the unperturbed configuration. \n\nThe current \\(J\\) is given by the Generalized Ohm's law: \n%\n\\begin{align}\nJ_r = \\sigma_{rs} E_s \n\\,,\n\\end{align}\n%\nwhere the proportionality constant \\(\\sigma _{rs}\\) is the \\emph{conductivity tensor} (whose components are, roughly, 1 over resistance). \n\nIt is also convenient to define the displacement current \\(\\vec{D}\\) by:\n%\n\\begin{align}\n\\frac{4 \\pi \\vec{J}}{c} + \\frac{1}{c} \\pdv{\\vec{E}}{t} = \\frac{1}{c} \\pdv{\\vec{D}}{t}\n\\,,\n\\end{align}\n%\nwhich means that the current can be recovered by \n%\n\\begin{align}\n\\vec{J} = \\frac{1}{4 \\pi } \\qty(\\pdv{\\vec{D}}{t} + \\pdv{\\vec{E}}{t})\n\\,.\n\\end{align}\n\nThe idea is to decompose the perturbation in Fourier modes:\n%\n\\begin{align}\n \\vec{E} \\to \\widetilde{E}_k (\\vec{k}, \\omega ) \\exp(- i \\omega t + i \\vec{k} \\cdot \\vec{r})\n\\,.\n\\end{align}\n\nThe full expression for the electric field is a superposition of these modes, but we can look at them just one at a time. \nThis simplifies things: time derivatives become \\(i \\omega \\), curls become \\(\\vec{k} \\times \\) and so on. \n\nThe current reads, with this as well as Ohm's law,\n%\n\\begin{align}\n\\widetilde{J} _r = \\frac{- i \\omega }{4 \\pi } \\qty(\\widetilde{D}_r - \\widetilde{E}_r) = \\sigma_{rs} E_s\n\\,.\n\\end{align}\n\nThe displacement field is therefore \n%\n\\begin{align}\n\\widetilde{D}_r\n= \\frac{4 \\pi }{ i \\omega } \\qty(\\frac{i \\omega }{ 4 \\pi } \\widetilde{E}_r - \\sigma_{rs} E_s) = \\widetilde{E}_r\n+ i \\frac{4 \\pi }{\\omega } \\sigma_{rs} \\widetilde{E}_s \n= \\mathbb{K}_{rs} \\widetilde{E}_s\n\\,,\n\\end{align}\n%\nwhere \\(\\mathbb{K}_{rs} = \\delta_{rs} + (4 \\pi i / \\omega ) \\sigma_{rs}\\) is called the \\textbf{Dielectric tensor}.\n\nWhat we are trying to do is to write a \\emph{dispersion relation}, \\(F(\\vec{k}, \\omega ) E = 0\\). \n\nNow we move to Lenz's law: we take another curl, to get \n%\n\\begin{subequations}\n\\begin{align}\n\\vec{\\nabla} \\times (\\vec{\\nabla} \\times \\vec{E}) &= - \\frac{1}{c} \\pdv{}{t} \\qty(\\vec{\\nabla} \\times \\vec{B})   \\\\\n&= - \\frac{1}{c} \\pdv{}{t} \\qty( \\frac{1}{c}\\pdv{\\vec{D}}{t})  \\\\\n&= - \\frac{1}{c^2} \\pdv[2]{\\vec{D}}{t}  \\\\\n[- \\vec{k} \\times (\\vec{k} \\times \\widetilde{E})]_r &= + \\frac{\\omega^2}{c^2} \\widetilde{D}_r = \\frac{\\omega^2}{c^2} \\mathbb{K}_{rs} \\widetilde{E}_s\n\\,.\n\\end{align}\n\\end{subequations}\n\nWe are almost done: the only issue here is that \\(\\mathbb{K}_{rs}\\) contains the conductivity tensor \\(\\sigma_{rs}\\). \n\nSupposing for simplicity  that our plasma is non-relativistic, we have the EoM \n%\n\\begin{align}\nm_e \\dv{v_e}{t} = - e E \\implies \n- i \\omega m_e \\widetilde{v}_e = - e \\widetilde{E}\n\\,,\n\\end{align}\n%\nbut the current \\(\\vec{J}\\) is \\(\\vec{J} = - e n_e \\vec{v}_e\\), so \\(\\widetilde{J}_r = - (n e^2 / \\omega m_e) \\widetilde{E}_r\\), therefore the conductivity reads \n%\n\\begin{align}\n\\sigma_{rs} = \\frac{i n e^2}{\\omega m_e} \\delta_{rs} \n\\,,\n\\end{align}\n%\nso we can write out the dielectric tensor explicitly: \n%\n\\begin{align}\n\\mathbb{K}_{rs} = \\delta_{rs} \\qty[ 1 - \\qty(\\frac{\\omega_p}{\\omega })^2]\n\\qquad \\text{where} \\qquad\n\\omega_p = \\sqrt{\\frac{ 4 \\pi n_e e^2}{m_e}}\n\\,\n\\end{align}\n%\nis called the plasma frequency.\n% This is a \\textbf{high-pass filter}!\n\nWe have found our dispersion relation: \n%\n\\begin{align}\n\\vec{k} \\times \\qty(\\vec{k} \\times \\vec{E})\n+ \\qty(\\frac{\\omega^2 - \\omega _p^2}{c^2}) \\widetilde{E} = 0\n\\,.\n\\end{align}\n\nLet us separate out \\emph{longitudinal perturbations}, which have \\(\\vec{k} \\propto \\vec{E}\\), from \\emph{transverse} ones, since we are always able to write \\(\\vec{E} = \\vec{E}_\\parallel + \\vec{E}_\\perp\\). \n\nIn the \\textbf{longitudinal case},\n%\n\\begin{align}\n(\\omega^2 - \\omega _p^2) E_{\\parallel} = 0\n\\,,\n\\end{align}\n%\nwhich means that the propagation must happen exactly at the plasma frequency: these are called \\textbf{Langmir waves}, or plasma waves. \nIn the transverse case, we get \n%\n\\begin{align}\n\\qty[ - k^2 c^2 + (\\omega^2 - \\omega _p^2)] E_\\perp = 0\n\\,.\n\\end{align}\n\nThe pulsation must be \n%\n\\begin{align}\n\\omega^2 = \\omega _p^2 + c^2 k^2\n\\qquad \\text{or} \\qquad\nk^2 = \\frac{\\omega^2 - \\omega^2_p}{c^2}\n\\,.\n\\end{align}\n\nIf \\(\\omega > \\omega _p\\), then \\(k^2 > 0 \\): these are allowed perturbations, which indeed exhibit oscillatory behavior.\n\nActually, we can compute their group velocity \n%\n\\begin{align}\nv_g = \\pdv{\\omega }{k} = c \\qty(1 - \\frac{\\omega_p^2}{\\omega^2})^{1/2}\n\\,,\n\\end{align}\n%\nwhich shows that if \\(\\omega \\gg \\omega _p\\) the speed is close to \\(c\\). \n\nIf \\(\\omega < \\omega _p\\), on the other hand, \\(k\\) is imaginary.\nThe solution corresponding to exponential growth is unphysical (for one, there is no mechanism providing the energy for the magnitude of the oscillation to exponentially grow), so we only look at the exponentially damped solutions. \n\nThey are exponentially damped over a scale \\(\\abs{\\vec{k}}^{-1} = c / \\omega _p\\).\nThis is the \\textbf{skin depth} of the plasma, the largest distance a perturbation can penetrate in the plasma if it oscillates too slowly.\n\nThis characteristic wavelength's ratio to the Debye length reads \n%\n\\begin{align}\n\\frac{\\lambda _{\\text{skin depth}}}{ \\lambda _{\\text{Debye}}} \n= \\sqrt{\\frac{m_e c^2}{4 \\pi n_e e^2} \\frac{8 \\pi n_e e^2}{k_B T}}\n= \\sqrt{\\frac{2 m_e c^2}{k_B T}} \\gg 1\n\\,,\n\\end{align}\n%\nsince the plasmas we are considering are typically non-relativistic. \n\n\\paragraph{An example: fast radio bursts}\n\nFast radio bursts are like \\(\\gamma \\)-ray bursts in the radio band.\nThese are relatively high-frequency, around \\SI{1.4}{GHz}. \nWe do not really know what their sources are; some were false positives due to microwave ovens making lunch, but others were certified to be true detections.\n\nWe know of one which came from a galaxy \\(L \\sim \\SI{1}{Gpc}\\) away, and which had a dispersion of about \\(\\Delta \\omega \\sim \\SI{300}{MHz}\\). \n\nPhotons of different frequencies arrived at different times, with a spread of about \\SI{300}{ms}. \n\nWe are in the second case (\\(\\vec{k} \\perp \\vec{E}\\)) since they are EM waves. \nThe group velocity is, again\n%\n\\begin{align}\nv_g = c \\qty[ 1 - \\qty(\\frac{\\omega _p}{\\omega})^2]^{1/2}\n\\,,\n\\end{align}\n%\nand we can assume (we will check \\emph{a posteriori}) that \\(\\omega \\gg \\omega _p\\). \n\nThe time difference will be \n%\n\\begin{subequations}\n\\begin{align}\n\\Delta t &= \\frac{L}{v_g (\\omega)} - \\frac{L}{v_g (\\omega + \\Delta \\omega )} \n\\approx \\frac{L}{v_g(\\omega )} \\frac{1}{v_g(\\omega )}\\pdv{v_g}{\\omega } \\Delta \\omega  \\\\\n&\\approx \\frac{L}{c^2} \\underbrace{c \\frac{\\omega _p^2}{\\omega^3}}_{\\approx \\pdv*{v_g}{\\omega }} \\Delta \\omega \\\\\n\\omega _p &\\approx \\sqrt{\\frac{ c \\omega^3 \\Delta t}{L \\Delta \\omega }}\n\\,,\n\\end{align}\n\\end{subequations}\n%\nbut we know that \n%\n\\begin{align}\n\\omega _p^2 = \\frac{ 4 \\pi n_e e^2}{m_e}\n\\,.\n\\end{align}\n\nThis allows us to measure \\(\\omega _p \\sim \\SI{5.2}{Hz}\\), and therefore also the density, which comes out to be \\(n_e \\sim \\SI{8.2e-09}{cm^{-3}}\\).\n% This corresponds with the \\(\\Omega _b\\) from CMB observations (?)\n\n\\begin{extracontent}\nHow well does this match the baryon density computed from the CMB? \nThe computation goes  \n%\n\\begin{align}\n\\underbrace{\\underbrace{\\frac{\\omega _p^2 m_e}{4 \\pi e^2}}_{n_e} m_p}_{\\rho _{\\text{plasma}}} \\times \\frac{1}{\\Omega _{0b} \\rho _c} \\approx 0.03\n\\,.\n\\end{align}\n\nTherefore, from this observation we can estimate that about \\SI{3}{\\percent} of baryonic matter is in the ISM. \n\nThis can be generalized a bit: maybe, not all the path \\(L\\) from the source to here had this much plasma in it. \nSuppose, for simplicity's sake, that a fraction \\(\\alpha \\) of the path was constituted by uniform-density plasma. \n\nThen, our estimate for \\(\\omega _p\\) will be multiplied by a factor \\(\\alpha^{-1/2}\\), while our estimate for \\(n_e\\) will be multiplied by \\(\\alpha^{-1}\\). \nOn the other hand, in the estimate for \\(\\rho _{\\text{plasma}}\\), averaged over the whole universe, will need to be shifted by some factor. \n\nIf the path we were looking at is a fair sample for the population (not a given, but let's approximate as such), then about a fraction \\(\\alpha \\) of the universe is filled with this plasma --- this precisely cancels the correction to our estimate, so it all works out. \n\nThis is done in a better way through the measurement of several pulsars for which we have more accurate distance measurements.\n\\end{extracontent}\n\n\\todo[inline]{Check: the frequency given was \\(\\nu \\), not \\(\\omega \\)!}\n\n\\end{document}", "meta": {"hexsha": "f8a2d3fa9cd00a91e91b056474bcbb44fe20b454", "size": 17775, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "phd_courses/theoretical_high_energy_astroparticle/nov10.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "phd_courses/theoretical_high_energy_astroparticle/nov10.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phd_courses/theoretical_high_energy_astroparticle/nov10.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 40.0337837838, "max_line_length": 288, "alphanum_fraction": 0.6754992968, "num_tokens": 5962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.3137554720332442}}
{"text": "\\chapter{Identical particles}\n\\section{Introduction}\n\\textbf{Identical particles}\\\\\nParticle having same intrinsic properties (mass, charge, spin) as known as identical particles. There are two types of identical particles i.e.\n\\begin{enumerate}\n\t\\item Classical identical particle(Distiquishable particles)\\\\\n\tVolume available for a gas molecule at NTP is $\\sim 10^{-25} \\mathrm{~m}^{3}$ and volume of single gas molecule $\\sim 10^{-30} \\mathrm{~m}^{3}$ So, we can identify every molecule of the gas. Hence, gas molecules are distinguishable.\n\t\\item Quantum identical particle(indistiquishable)\n\tVolume available for each electron taking part in conduction within the metals is $\\sim 10^{-28} \\mathrm{~m}^{3}$ but the volume of a single electron is $\\sim 10^{-27} \\mathrm{~m}^{3}$. This shows that the electron wave functions overlap considerably and hence cannot be identified separately, i.e. they are indistinguishable.\n\\end{enumerate}\n\\begin{note}\n\tFor a system of 'n' indistinguishable particles say electrons, we may be able to specify their positions, but it is not possible to say which electron is at a particular position. Therfore, interchanging the coordinates of any two electrons does not change the Hamiltonian. In other words, the Hamiltonian of the system is symmetric in coordinates of the particles i.e.\n\t$$\n\t\\hat{H}\\left(x_{1}, x_{2}, x_{3} \\ldots \\ldots x_{i}, x_{i+1}, \\ldots x_{n}\\right)=\\hat{H}\\left(x_{1}, x_{2}, x_{3} \\ldots \\ldots x_{i+1}, x_{i}, \\ldots x_{n}\\right)\n\t$$\n\t\\end{note}\n\\textbf{Particle exchange operator}\\\\\n$\\text { This operator exchanges the particle in pair (both position and spin co-ordinates). }$\n\\begin{note}\n\t$\\text { (i) Particle exchange operator is a hermitian operator. }$\\\\\n\t(ii) Since particles are indistinguishable, any operator representing a physical property of the sys tem must be symmetric w.r.t the particle exchange. Therefore, any operator representing a physical property commute with the particle exchange operator.\n\\end{note}\n\\subsection{ Symmetric wave function:}\nA wave function is said to be symmetric if interchange of any pair of particles leaves the wave function unchanged.\n$$\n\\psi_{\\mathrm{s}}(1,2, \\ldots . \\mathrm{i}, \\mathrm{j} \\ldots \\mathrm{N})=\\psi_{\\mathrm{s}}(1,2 \\ldots \\ldots . \\mathrm{j}, \\mathrm{i}, \\ldots . . \\mathrm{N})\n$$\nThe particles having symmetric wave function obey BE statistics and known as bosons.\nExample: Photons (spin 1), neutral helium (spin 0), $\\alpha$-particle (spin 0), deutron (spin 1)\\\\\n\\subsection{ Anti-symmetric wave function:}\nA wave function is said to be anti-symmetric if interchange of any pair of particle changes the signof the wave function.\n$$\n\\psi_{\\mathrm{a}}(1,2, \\ldots \\ldots . \\mathrm{i}, \\mathrm{j}, \\ldots \\ldots \\mathrm{N})=-\\psi_{\\mathrm{a}}(1,2, \\ldots \\ldots . \\mathrm{j}, \\mathrm{i} \\ldots . . \\mathrm{N})\n$$\nThe particles having anti-symmetric wave functions are known as fermions and follow FD statistics. Example: Electron, protons, neutrons, muons (spin $1 / 2$ ), $\\Omega$ particle (spin $3 / 2$ )\n\\section{Symmetrization postulate}\nThe state of the system containing $\\mathrm{N}$ identical particles, are either totally symmetric or totally anti symmetric under the exchange of any pair of particles and the states with mixed symmetry do not exist.\n\\begin{note}\n\t(i) Bosons have symmetric wave functions and Fermions have anti-symmetric wave functions\\\\\n\t(ii) Wave function of a system of identical bosons is totally symmetric and of a system of identical fermions is totally anti-symmetric.\n\t\n\tThe total wave function corresponding to a system containing of $\\mathrm{N}$ identical particles consisting of two parts (a) space part and (b) spin part, i.e.\n\tTherefore,\n\t$$\n\t\\psi_{\\text {total }}=\\psi_{\\text {space }} \\times \\chi_{\\text {spin }}\n\t$$\n\tTherefore\\\\\n\t(i) Both space part and spin part of total wave function of a system of identical bosons will be either symmetric or anti-symmetric.\n\t$$\n\t\\psi_{s, f e r m i o n}=\\left\\{\\begin{array}{l}\n\t\\psi_{s}(\\text { space }) \\times \\chi_{a}(\\text { spin }) \\\\\n\t\\psi_{a}(\\text { space }) \\times \\chi_{s}(\\text { spin })\n\t\\end{array}\\right.\n\t$$\n\t(ii) any one of the space part and spin part of total wave function of a system of identical fermions will be symmetric and other one is anti-symmetric.\n\t$$\n\t\\psi_{s, j e r m i o n}=\\left\\{\\begin{array}{l}\n\t\\psi_{s}(\\text { space }) \\times \\chi_{a}(\\text { spin }) \\\\\n\t\\psi_{a}(\\text { space }) \\times \\chi_{s}(\\text { spin })\n\t\\end{array}\\right.\n\t$$\n\t\\end{note}\n\t\\textbf{Composite particle:}\\\\\nConsider a system of identical composite particles where each particle is composed of two or more identical particles. Spin of each composite particles can be obtained by adding the spin of its constituents. If total spin of the composite particles is half-integer, then the particle will behave as a fermion. If total spin of the composite particles is integer, then the particle will behave as a boson.\\\\\n\\textbf{example} \\\\\n(i) A system of $\\mathrm{N}$ identical $\\mathrm{H}$ atoms. Each $\\mathrm{H}$ atom consists of 1 proton and 1 electron (spin $\\mathrm{I} / 2$) Therefore each H atom has spin 1 and it will behave as a boson.So the system of N identical H atoms will have symmetric wavefunction\\\\\n(ii) ${ }^{4} \\mathrm{He}$ (two protons and two meutrons) has integer spin and will behave as boson.\\\\\n(iii)$^3He$(2 proton and 1 neutron) has half integral spin and will behave as fermion\n\\section{Symmetric and anti symmetric wavefunction(space part)}\nFor a system of ' $n$ ' non-interacting distinguishable particles, the wave function can be written as\n$$\n\\psi\\left(\\vec{r}_{1}, \\vec{r}_{2}, \\vec{r}_{3} \\ldots \\ldots \\ldots \\vec{r}_{n}\\right)=\\psi_{1}\\left(\\vec{r}_{1}\\right) \\cdot \\psi_{2}\\left(\\vec{r}_{2}\\right) \\cdot \\psi_{3}\\left(\\vec{r}_{3}\\right) \\ldots \\ldots \\ldots \\psi_{n}\\left(\\vec{r}_{n}\\right)\n$$\nBut, for a system of ' $n$ ' non-interacting indistinguishable particles, the wave function will be different.\nExample:\nConsider a system of 2 non-interacting indistinguishable particles, in which one particle is in state 1 and the other particle is in state 2. Since, the particles are distinguishable, therefore the possible eigenfunctions are $\\psi_{1}\\left(\\vec{r}_{1}\\right) \\psi_{2}\\left(\\vec{r}_{2}\\right)$ and $\\psi_{1}\\left(\\vec{r}_{2}\\right) \\psi_{2}\\left(\\vec{r}_{1}\\right)$ and both are equal probable. The symmetric and anti-symmetric combinations for the wave function of the system of 2 particles will be\n$$\n\\begin{aligned}\n&\\psi_{s}\\left(\\vec{r}_{1}, \\vec{r}_{2}\\right)=\\frac{1}{\\sqrt{2}}\\left[\\psi_{1}\\left(\\vec{r}_{1}\\right) \\psi_{2}\\left(\\vec{r}_{2}\\right)+\\psi_{1}\\left(\\vec{r}_{2}\\right) \\psi_{2}\\left(\\vec{r}_{1}\\right)\\right] \\\\\n&\\psi_{a}\\left(\\vec{r}_{1}, \\vec{r}_{2}\\right)=\\frac{1}{\\sqrt{2}}\\left[\\psi_{1}\\left(\\vec{r}_{1}\\right) \\psi_{2}\\left(\\vec{r}_{2}\\right)-\\psi_{1}\\left(\\vec{r}_{2}\\right) \\psi_{2}\\left(\\vec{r}_{1}\\right)\\right]\n\\end{aligned}\n$$\nIf both the particles are in the same state, then $\\psi_{a}\\left(\\vec{r}_{1}, \\vec{r}_{2}\\right)=0$ i.e. two identical fermions cannot occupy the same state. This is known as 'Pauli's exclusion principle'.\\\\\nIn general, if we take a system of $\\mathrm{N}$ identical non-interacting indistinguishable particles and each particle is in a different state, then there will be $N !$ different type possible eiegenfunctions having same value of energy. The degenaracy arises due to the exchange of indistingushable particles and known as exchange degenaracy. The symmetric and anti-symmetric combinations for the wave function of the system of $\\mathrm{N}$ particles will be\\\\\n$$\\begin{aligned}\n\t&\\psi_{S}\\left(\\vec{r}_{1}, \\vec{r}_{2}, \\ldots \\ldots . \\vec{r}_{N}\\right)=\\frac{1}{\\sqrt{N !}} \\sum_{P} \\hat{P}\\left[\\psi_{1}\\left(\\vec{r}_{1}\\right) \\psi_{2}\\left(\\vec{r}_{2}\\right) \\psi_{3}\\left(\\vec{r}_{3}\\right) \\ldots \\ldots \\ldots \\psi_{n}\\left(\\vec{r}_{N}\\right)\\right] \\\\\n\t&\\psi_{a}\\left(\\vec{r}_{1}, \\vec{r}_{2}, \\ldots \\ldots . \\vec{r}_{N}\\right)=\\frac{1}{\\sqrt{N !}}\\left|\\begin{array}{llll}\n\t\t\\psi_{1}\\left(\\vec{r}_{1}\\right) & \\psi_{1}\\left(\\vec{r}_{2}\\right) & \\ldots \\ldots \\ldots \\ldots & \\psi_{1}\\left(\\vec{r}_{N}\\right) \\\\\n\t\t\\psi_{2}\\left(\\vec{r}_{1}\\right) & \\psi_{2}\\left(\\vec{r}_{2}\\right) & \\ldots \\ldots \\ldots \\ldots & \\psi_{2}\\left(\\vec{r}_{N}\\right) \\\\\n\t\t\\vdots & & & \\\\\n\t\t\\psi_{N}\\left(\\vec{r}_{1}\\right) & \\psi_{N}\\left(\\vec{r}_{2}\\right) & \\ldots \\ldots \\ldots \\ldots & \\psi_{N}\\left(\\vec{r}_{N}\\right)\n\t\\end{array}\\right|\n\\end{aligned}$$\n\\section{Symmetric and anti symmetric wavefunction(spin part)}\nSpin functions for two-electron system:\nTwo electrons each having spin $1 / 2$ i.e. $s_{1}=\\frac{1}{2}, s_{2}=\\frac{1}{2}$, then the total spin of two electrons will be\n$$\ns=\\left|s_{1}+s_{2}\\right| \\ldots \\ldots\\left|s_{1}-s_{2}\\right|=1,0\n$$\nand corresponding magnetic spin quantum number will be $m_{s}=1,0,-1,0$\nTherefore, the possible spin states will be $\\left|s, m_{s}\\right\\rangle \\equiv|0,0\\rangle,|1,1\\rangle,|1,0\\rangle,|1,-1\\rangle$ and given as follows:\\\\\n\\textbf{Symmetric Triplet state:}\\\\\n$$\n\\begin{aligned}\n|1,1\\rangle &=|\\uparrow \\uparrow\\rangle=|\\alpha \\alpha\\rangle=\\left|\\frac{1}{2}, \\frac{1}{2}\\right\\rangle\\left|\\frac{1}{2}, \\frac{1}{2}\\right\\rangle \\\\\n|1,-1\\rangle &=|\\downarrow \\downarrow\\rangle=|\\beta \\beta\\rangle=\\left|\\frac{1}{2},-\\frac{1}{2}\\right\\rangle\\left(\\frac{1}{2},-\\frac{1}{2}\\right\\rangle \\\\\n|1,0\\rangle &=\\frac{1}{\\sqrt{2}}[|\\uparrow \\downarrow\\rangle+|\\downarrow \\uparrow\\rangle]=\\frac{1}{\\sqrt{2}}[|\\alpha \\beta\\rangle+|\\beta \\alpha\\rangle] \\\\\n&=\\frac{1}{\\sqrt{2}}\\left[\\left|\\frac{1}{2}, \\frac{1}{2}\\right\\rangle\\left\\langle\\frac{1}{2},-\\frac{1}{2}\\right\\rangle+\\left|\\frac{1}{2},-\\frac{1}{2}\\right\\rangle\\left\\langle\\frac{1}{2}, \\frac{1}{2}\\right\\rangle\\right]\n\\end{aligned}\n$$\n\\textbf{Anti-symmetric Singlet state:}\n$$\n\\begin{aligned}\n|0,0\\rangle &=\\frac{1}{\\sqrt{2}}[|\\uparrow \\downarrow\\rangle-|\\downarrow \\uparrow\\rangle]=\\frac{1}{\\sqrt{2}}[|\\alpha \\beta\\rangle-|\\beta \\alpha\\rangle] \\\\\n&\\left.=\\frac{1}{\\sqrt{2}}\\left[\\left|\\frac{1}{2}, \\frac{1}{2}\\right\\rangle\\left|\\frac{1}{2},-\\frac{1}{2}\\right\\rangle-\\left|\\frac{1}{2},-\\frac{1}{2}\\right\\rangle\\left|\\frac{1}{2}, \\frac{1}{2}\\right\\rangle\\right]\\right]\n\\end{aligned}\n$$\nFor a system of $N$ identical non-interacting indistinguishable particles each having spin 's', total number of possible spin states is $(2 s+1)^{N}$.\n\\begin{exercise}\nExample 1. $N$ non interacting bosons are in an infinite potential well defined by $V(x)=0$ for $0<x<a$; $V(x)=\\infty$ for $x<0$ and for $x>a$. Find the ground state energy of the system. What would be the ground state energy if the particles are fermions.\n\t\\end{exercise}\n\\begin{answer}\n\tThe energy eigenvalue of a particle in the infinite square well is given by\n\t$$\n\tE_{n}=\\frac{\\pi^{2} \\hbar^{2} n^{2}}{2 m a^{2}}, \\quad n=1,2,3, \\ldots\n\t$$\n\tAs the particles are bosons, all the $\\mathrm{N}$ particles will be in the $n=1$ state in the ground state configuration. Hence, the ground state energy of the configuration will be\n\t$$\n\tE=\\frac{N \\pi^{2} \\hbar^{2}}{2 m a^{2}}\n\t$$\n\tIf the particles are fermions, a state can have only two of them, one spin up and the other spin down.\\\\\n\txilaal Part Therefore, the lowest $\\mathrm{N} / 2$ states will be filled. The total ground state energy will be\n\t$$\n\t\\begin{aligned}\n\tE &=2 \\frac{\\pi^{2} \\hbar^{2}}{2 m a^{2}}\\left[1^{2}+2^{2}+3^{3}+\\ldots+(N / 2)^{2}\\right] \\\\\n\t&=\\frac{\\pi^{2} \\hbar^{2}}{m a^{2}} \\frac{1}{6}\\left[\\frac{N}{2}\\left(\\frac{N}{2}+1\\right)\\left(2 \\frac{N}{2}+1\\right)\\right] \\\\\n\t&=\\frac{\\pi^{2} \\hbar^{2}}{24 m a^{2}} N(N+1)(N+2)\n\t\\end{aligned}\n\t$$\n\\end{answer}\n\\begin{exercise}\n Consider two noninteracting electrons described by the Hamiltonian\n\t$$\n\tH=\\frac{p_{1}^{2}}{2 m}+\\frac{p_{2}^{2}}{2 m}+V\\left(x_{1}\\right)+V\\left(x_{2}\\right)\n\t$$\n\twhere $V(x)=0$ for $0<x<a ; V(x)=\\infty$ for $x<0$ and for $x>a$. If both the electrons are in the same spin state, what is the lowest energy and eigenfunction of the two-electron system?\n\t\\end{exercise}\n\\begin{answer}\n\tAs both the electrons are in the same spin state, the possible combinations of spin part of the wave functions will be $|\\uparrow \\uparrow\\rangle$ or $|\\downarrow \\downarrow\\rangle$, both being symmetric. Since, the system contains two electrons (fermions), then the total wave function of the sytem will be anti-symmetric. Hence the space function must be antisymmetric. Therefore, both electrons cannot be in the same state. So, ground state energy will corresponds to $n_{1}=1, n_{2}=2$\\\\\n\tGround state energy $\\left(n_{1}=1, n_{2}=2\\right)=\\frac{\\pi^{2} \\hbar^{2}}{2 m a^{2}}+\\frac{4 \\pi^{2} \\hbar^{2}}{2 m a^{2}}=\\frac{5 \\pi^{2} \\hbar^{2}}{2 m a^{2}}$\\\\\n\tSince, the electrons are indistinguishable, therefore the antisymmetric combination for the space part is\n\t$$\n\t\\frac{1}{\\sqrt{2}}\\left[\\psi_{1}\\left(\\vec{r}_{1}\\right) \\psi_{2}\\left(\\vec{r}_{2}\\right)-\\psi_{1}\\left(\\vec{r}_{2}\\right) \\psi_{2}\\left(\\vec{r}_{1}\\right)\\right]\n\t$$\n\\end{answer}\n\\begin{exercise}\n\tExample 3. Sixteen noninteracting electrons are confined in a potential $V(x)=\\infty$ for $x<0$ and $x>0 ; V(x)=0$, for $0<x<a$.\\\\\n\t(i) What is the energy of the least energetic electron in the ground state?\\\\\n\t(ii) What is the energy of the most energetic electron in the ground state?\\\\\n\t(iii) What is the Fermi energy $E_{f}$ of the system?\n\t\\end{exercise}\n\\begin{answer}\n\t(i) The least energetic electron in the ground state is given by $E_{1}=\\frac{\\pi^{2} \\hbar^{2}}{2 m a^{2}}$.\\\\\n\t(ii) In the given potential, the energy eigenvalue\n\t$$\n\tE_{n}=\\frac{\\pi^{2} \\hbar^{2} n^{2}}{2 m a^{2}}, \\quad n=1,2,3, \\ldots\n\t$$\n\tAs two electrons can go into each of the states $n=1,2,3, \\ldots$, the highest filled level will have $n=8$ and its energy will be\n\t$$\n\tE_{8}=\\frac{\\pi^{2} \\hbar^{2} 8^{2}}{2 m a^{2}}=\\frac{32 \\pi^{2} \\hbar^{2}}{m a^{2}}\n\t$$\n\t(iii)The energy of the highest filled state is the Fermi energy $E_{F}$ Hence,\n\t$$\n\tE_{F}=\\frac{32 \\pi^{2} \\hbar^{2}}{m a^{2}}\n\t$$\n\\end{answer}\n\n\n\\newpage\n\\begin{abox}\n\tPractice set 1\n\t\\end{abox}\n\\begin{enumerate}\n\t\\begin{minipage}{\\textwidth}\n\t\t\\item Consider a particle in a one dimensional potential that satisfies $V(x)=V(-x) .$ Let $\\left|\\psi_{0}\\right\\rangle$ and $\\left|\\psi_{1}\\right\\rangle$ denote the ground and the first excited states, respectively, and let $|\\psi\\rangle=\\alpha_{0}\\left|\\psi_{0}\\right\\rangle+\\alpha_{1}\\left|\\psi_{1}\\right\\rangle$ be a normalized state with $\\alpha_{0}$ and $\\alpha_{1}$ being real constants. The expectation value $\\langle x\\rangle$ of the position operator $x$ in the state $|\\psi\\rangle$ is given by\n\t\t\\exyear{NET DEC 2011}\n\t\\end{minipage}\n\t\\begin{tasks}(2)\n\t\t\\task[\\textbf{A.}] $\\alpha_{0}^{2}\\left\\langle\\psi_{0}|x| \\psi_{0}\\right\\rangle+\\alpha_{1}^{2}\\left\\langle\\psi_{1}|x| \\psi_{1}\\right\\rangle$\n\t\t\\task[\\textbf{B.}]$\\alpha_{0} \\alpha_{1}\\left[\\left\\langle\\psi_{0}|x| \\psi_{1}\\right\\rangle+\\left\\langle\\psi_{1}|x| \\psi_{0}\\right\\rangle\\right]$\n\t\t\\task[\\textbf{C.}]$\\alpha_{0}^{2}+\\alpha_{1}^{2}$\n\t\t\\task[\\textbf{D.}]$2 \\alpha_{0} \\alpha_{1}$\n\t\\end{tasks}\n\\begin{minipage}{\\textwidth}\n\t\\item Consider a system of two non-interacting identical fermions, each of mass $m$ in an infinite square well potential of width $a$. (Take the potential inside the well to be zero and ignore spin). The composite wavefunction for the system with total energy $E=\\frac{5 \\pi^{2} \\hbar^{2}}{2 m a^{2}}$ is\n\t\\exyear{NET JUNE 2014}\n\\end{minipage}\n\\begin{tasks}(2)\n\t\\task[\\textbf{A.}] $\\frac{2}{a}\\left[\\sin \\left(\\frac{\\pi x_{1}}{a}\\right) \\sin \\left(\\frac{2 \\pi x_{2}}{a}\\right)-\\sin \\left(\\frac{2 \\pi x_{1}}{a}\\right) \\sin \\left(\\frac{\\pi x_{2}}{a}\\right)\\right]$\n\t\\task[\\textbf{B.}]$\\frac{2}{a}\\left[\\sin \\left(\\frac{\\pi x_{1}}{a}\\right) \\sin \\left(\\frac{2 \\pi x_{2}}{a}\\right)+\\sin \\left(\\frac{2 \\pi x_{1}}{a}\\right) \\sin \\left(\\frac{\\pi x_{2}}{a}\\right)\\right]$\n\t\\task[\\textbf{C.}]$\\frac{2}{a}\\left[\\sin \\left(\\frac{\\pi x_{1}}{a}\\right) \\sin \\left(\\frac{3 \\pi x_{2}}{2 a}\\right)-\\sin \\left(\\frac{3 \\pi x_{1}}{2 a}\\right) \\sin \\left(\\frac{\\pi x_{2}}{a}\\right)\\right]$\n\t\\task[\\textbf{D.}]$\\frac{2}{a}\\left[\\sin \\left(\\frac{\\pi x_{1}}{a}\\right) \\cos \\left(\\frac{\\pi x_{2}}{a}\\right)-\\sin \\left(\\frac{\\pi x_{2}}{a}\\right) \\cos \\left(\\frac{\\pi x_{2}}{a}\\right)\\right]$\n\\end{tasks}\n\\begin{minipage}{\\textwidth}\n\t\\item The state vector of a one-dimensional simple harmonic oscillator of angular frequency $\\omega$, at time $t=0$, is given by $|\\psi(0)\\rangle=\\frac{1}{\\sqrt{2}}[|0\\rangle+|2\\rangle]$, where $|0\\rangle$ and $|2\\rangle$ are the normalized ground state and the second excited state, respectively. The minimum time $t$ after which the state vector $|\\psi(t)\\rangle$ is orthogonal to $|\\psi(0)\\rangle$, is\n\t\\exyear{NET DEC 2017}\n\\end{minipage}\n\\begin{tasks}(2)\n\t\\task[\\textbf{A.}] $\\frac{\\pi}{2 \\omega}$\n\t\\task[\\textbf{B.}]$\\frac{2 \\pi}{\\omega}$\n\t\\task[\\textbf{C.}]$\\frac{\\pi}{\\omega}$\n\t\\task[\\textbf{D.}]$\\frac{4 \\pi}{\\omega}$\n\\end{tasks}\n\\end{enumerate}\n\\colorlet{ocre1}{ocre!70!}\n\\colorlet{ocrel}{ocre!30!}\n\\setlength\\arrayrulewidth{1pt}\n\\begin{table}[H]\n\t\\centering\n\t\\arrayrulecolor{ocre}\n\t\n\t\\begin{tabular}{|p{1.5cm}|p{1.5cm}||p{1.5cm}|p{1.5cm}|}\n\t\t\\hline\n\t\t\\multicolumn{4}{|c|}{\\textbf{Answer key}}\\\\\\hline\\hline\n\t\t\\rowcolor{ocrel}Q.No.&Answer&Q.No.&Answer\\\\\\hline\n\t\t1&\\textbf{b}&2&\\textbf{a}\\\\\\hline\n\t\t3&\\textbf{a}&&\\\\\\hline\n\t\\end{tabular}\n\\end{table}\n\\newpage\n\\begin{abox}\n\tPractice set 2\n\t\\end{abox}\n\\begin{enumerate}\n\\begin{minipage}{\\textwidth}\n\t\\item Consider the wavefunction $\\psi=\\psi\\left(\\vec{r}_{1}, \\vec{r}_{2}\\right) \\chi_{s}$ for a fermionic system consisting of two spinhalf particles. The spatial part of the wavefunction is given by\n\t$$\n\t\\psi\\left(\\vec{r}_{1}, \\vec{r}_{2}\\right)=\\frac{1}{\\sqrt{2}}\\left[\\phi_{1}\\left(\\vec{r}_{1}\\right) \\phi_{2}\\left(\\vec{r}_{2}\\right)+\\phi_{2}\\left(\\vec{r}_{1}\\right) \\phi_{1}\\left(\\vec{r}_{2}\\right)\\right]\n\t$$\n\twhere $\\phi_{1}$ and $\\phi_{2}$ are single particle states. The spin part $\\chi_{s}$ of the wavefunction with spin states $\\alpha(+1 / 2)$ and $\\beta(-1 / 2)$ should be\n\t\\exyear{GATE 2013}\n\\end{minipage}\n\\begin{tasks}(2)\n\t\\task[\\textbf{A.}]$\\frac{1}{\\sqrt{2}}(\\alpha \\beta+\\beta \\alpha)$\n\t\\task[\\textbf{B.}]$\\frac{1}{\\sqrt{2}}(\\alpha \\beta-\\beta \\alpha)$\n\t\\task[\\textbf{C.}]$\\alpha \\alpha$\n\t\\task[\\textbf{D.}] $\\beta \\beta$\n\\end{tasks}\n\\begin{minipage}{\\textwidth}\n\t\\item The ground state and first excited state wave function of a one dimensional infinite potential well are $\\psi_{1}$ and $\\psi_{2}$ respectively. When two spin-up electrons are placed in this potential which one of the following with $x_{1}$ and $x_{2}$ denoting the position of the two electrons correctly represents the space part of the ground state wave function of the system?\n\t\\exyear{GATE 2014}\n\\end{minipage}\n\\begin{tasks}(2)\n\t\\task[\\textbf{A.}] $\\frac{1}{\\sqrt{2}}\\left[\\psi_{1}\\left(x_{1}\\right) \\psi_{2}\\left(x_{1}\\right)-\\psi_{1}\\left(x_{2}\\right) \\psi_{2}\\left(x_{2}\\right)\\right]$\n\t\\task[\\textbf{B.}]$\\frac{1}{\\sqrt{2}}\\left[\\psi_{1}\\left(x_{1}\\right) \\psi_{2}\\left(x_{2}\\right)+\\psi_{1}\\left(x_{2}\\right) \\psi_{2}\\left(x_{1}\\right)\\right]$\n\t\\task[\\textbf{C.}]$\\frac{1}{\\sqrt{2}}\\left[\\psi_{1}\\left(x_{1}\\right) \\psi_{2}\\left(x_{1}\\right)+\\psi_{1}\\left(x_{2}\\right) \\psi_{2}\\left(x_{2}\\right)\\right]$\n\t\\task[\\textbf{D.}]$ \\frac{1}{\\sqrt{2}}\\left[\\psi_{1}\\left(x_{1}\\right) \\psi_{2}\\left(x_{2}\\right)-\\psi_{1}\\left(x_{2}\\right) \\psi_{2}\\left(x_{1}\\right)\\right]$\n\\end{tasks}\n\\begin{minipage}{\\textwidth}\n\t\\item $\\psi_{1}$ and $\\psi_{2}$ are two orthogonal states of a spin $\\frac{1}{2}$ system. It is given that\n\t$\\psi_{1}=\\frac{1}{\\sqrt{3}}\\left(\\begin{array}{l}1 \\\\ 0\\end{array}\\right)+\\sqrt{\\frac{2}{3}}\\left(\\begin{array}{l}0 \\\\ 1\\end{array}\\right)$, where $\\left(\\begin{array}{l}1 \\\\ 0\\end{array}\\right)$ and $\\left(\\begin{array}{l}0 \\\\ 1\\end{array}\\right)$ represent the spin-up and spin-down states, respectively. When the system is in the state $\\psi_{2}$ its probability to be in the spin-up state is\n\t\\exyear{GATE 2014}\n\\end{minipage}\n\\begin{minipage}{\\textwidth}\n\t\\item For a spin $\\frac{1}{2}$ particle, let $|\\uparrow\\rangle$ and $|\\downarrow\\rangle$ denote its spin up and spin down states respectively. If $|a\\rangle=\\frac{1}{\\sqrt{2}}(|\\uparrow\\rangle|\\downarrow\\rangle+|\\downarrow\\rangle|\\uparrow\\rangle)$ and $|b\\rangle=\\frac{1}{\\sqrt{2}}(|\\uparrow\\rangle|\\downarrow\\rangle-|\\downarrow\\rangle|\\uparrow\\rangle)$ are composite states of two such particles, which of the following statements is true for their total spin $S ?$\n\t\\exyear{GATE 2018}\n\\end{minipage}\n\\begin{tasks}(2)\n\t\\task[\\textbf{A.}] $S=1$ for $|a\\rangle$ and $|b\\rangle$ is not an eigenstate of the operator $\\hat{S}^{2}$\n\t\\task[\\textbf{B.}]$|a\\rangle$ is not an eigenstate of the operator $\\hat{S}^{2}$ and $S=0$ for $|b\\rangle$\n\t\\task[\\textbf{C.}]$S=0$ for $|a\\rangle$, and $S=1$ for $|b\\rangle$\n\t\\task[\\textbf{D.}]$S=1$ for $|a\\rangle$, and $S=0$ for $|b\\rangle$\n\\end{tasks}\n\\begin{minipage}{\\textwidth}\n\t\\item Let $\\left|\\psi_{2}\\right\\rangle=\\left(\\begin{array}{c}1 \\\\ 0\\end{array}\\right),\\left|\\psi_{2}\\right\\rangle=\\left(\\begin{array}{c}0 \\\\ 1\\end{array}\\right)$ represent two possible states of a two-level quantum system. The state obtained by the incoherent superposition of $\\left|\\psi_{1}\\right\\rangle$ and $\\left|\\psi_{2}\\right\\rangle$ is given by a density matrix that is defined as $\\rho \\equiv c_{1}\\left|\\psi_{1}\\right\\rangle\\left\\langle\\psi_{1}\\left|+c_{2}\\right| \\psi_{2}\\right\\rangle\\left\\langle\\psi_{2}\\right| .$ If $c_{1}=0.4$ and $c_{2}=0.6$, the matrix element $\\rho_{22}$ (rounded off to one decimal place) is\n\t\\exyear{GATE 2018}\n\\end{minipage}\n\\end{enumerate}\n\\colorlet{ocre1}{ocre!70!}\n\\colorlet{ocrel}{ocre!30!}\n\\setlength\\arrayrulewidth{1pt}\n\\begin{table}[H]\n\t\\centering\n\t\\arrayrulecolor{ocre}\n\t\n\t\\begin{tabular}{|p{1.5cm}|p{1.5cm}||p{1.5cm}|p{1.5cm}|}\n\t\t\\hline\n\t\t\\multicolumn{4}{|c|}{\\textbf{Answer key}}\\\\\\hline\\hline\n\t\t\\rowcolor{ocrel}Q.No.&Answer&Q.No.&Answer\\\\\\hline\n\t\t1&\\textbf{b}&2&\\textbf{d}\\\\\\hline\n\t\t3&\\textbf{2/3}&4&\\textbf{d}\\\\\\hline\n\t\t5&\\textbf{0.6}&&\\\\\\hline\n\t\\end{tabular}\n\\end{table}\n", "meta": {"hexsha": "5b7b4db999c99908003641422b8f6cc768df79a9", "size": 22049, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "QM -CSIR/chapter/identical particles.tex", "max_stars_repo_name": "archives-futuring/CSIR-Physics-Study-Material", "max_stars_repo_head_hexsha": "689cff91895fec36b4bb0add178f13a0f68648ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "QM -CSIR/chapter/identical particles.tex", "max_issues_repo_name": "archives-futuring/CSIR-Physics-Study-Material", "max_issues_repo_head_hexsha": "689cff91895fec36b4bb0add178f13a0f68648ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QM -CSIR/chapter/identical particles.tex", "max_forks_repo_name": "archives-futuring/CSIR-Physics-Study-Material", "max_forks_repo_head_hexsha": "689cff91895fec36b4bb0add178f13a0f68648ab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 74.7423728814, "max_line_length": 627, "alphanum_fraction": 0.6842940723, "num_tokens": 7743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.3137554646262615}}
{"text": "\\documentclass[revision-guide.tex]{subfiles}\n% !TEX = xelatex\n%% Current Author:\n\\setcounter{chapter}{19}\n\\begin{document}\n\\raggedbottom\n\\chapter{Astronomy and cosmology}\n\\begin{content}\n    \\item standard candles\n    \\item stellar radii\n    \\item Hubble's law\n    \\item the Big Bang theory\n    \\item the age of the Universe\n\\end{content}\n\\spec{understand the term luminosity}\n\\spec{ recall and use the inverse square law for radiant flux intensity $F$ in terms of the luminosity $L$ of the source\n\\begin{equation}\n  F = \\frac{L}{4\\pi d^2}\n\\end{equation}\n}\nStars are described as LUMINOUS because they emit electromagnetic waves.\n\nThe LUMINOSITY of a luminous (``hot'') object is defined as the amount\nof electromagnetic wave energy emitted by the object per second i.e. it\nis the emission Power of the object and is thus measured in Watts (W).\nIt is a measure of the absolute ``brightness'' of the object.\n\nFLUX (F) is Power per unit area (an Intensity). For a spherical emitter\nof radius R (and thus surface area of $ 4\\pi R^{2}$), this\nmeans that $F = \\frac{L}{4\\pi d^2}$.\n\n\\spec{understand the need to use standard candles to help determine distances to galaxies}\n\nStandard Candles are types of stars or galaxies for which the Luminosity\n(the absolute brightness) can be determined directly from observations.\nBy measuring the observed brightness and comparing it to the absolute\nbrightness of the object, it is possible to determine how far away that\nobject is.\n\nThe best-known and most widely used Standard Candles are Cepheid\nVariables and Type 1a Supernovae.\n\nCepheid Variables (named after the star Delta Cephei) pulsate and vary\nin brightness with a frequency that is related to the star's Luminosity.\nThe periods of some Cepheids have been measured as a few days, others a\nfew months. Once the absolute brightness has been found from the\nobserved period of the pulsation, it can be compared with the brightness\nthe star appears to have as observed from the Earth and hence the\ndistance can be determined.\n\nType 1a supernovae occur when one of the stars (a white dwarf) in a\nbinary system gains mass, becomes unstable and catastrophically explodes\nemitting vast quantities of light and other electromagnetic energy in\nthe process. The maximum absolute brightness achieved is related to the\nrate at which the emission fades (the so-called Light Curve). Thus,\nagain, once the absolute brightness is known, a comparison with how\nbright the object appears to be from the Earth will yield its distance.\nBecause they are so bright, these objects can be easily seen in distant\ngalaxies, so that distances well beyond the limits of the Milky Way can\nbe established.\n\\spec{recognise and use Wien's displacement law\n\\begin{equation}\n  \\lambda_{\\text{max}} \\propto  \\frac{1}{T}\n\\end{equation}\nto estimate the peak surface temperature of a star either graphically or algebraically}\n\nBlack bodies of a particular temperature T will emit radiation over a\nrange of wavelengths (a radiation distribution known as a Planck Curve):\n\n\\begin{figure}[h]\n\\includegraphics{figs/chapt-20/media/image1.png}\n\\caption{Planck curves}\n\\label{plank-curves}\n\\end{figure}\n\nThe distribution peaks at a wavelength λ\\textsubscript{max} which is\ndetermined by the reciprocal of the absolute temperature T of the\nobject. This is known as Wien's Displacement Law. The constant of\nproportionality has a value of 2.90 x 10\\textsuperscript{-3} m K:\n\n\\[\\lambda_{max} = \\frac{2.90 \\times 10^{-3}} {T}\\]\n\nThe greater the temperature, the larger the area under the curve,\nsuggesting that more radiation is being emitted altogether, consistent\nwith the Stefan-Boltzmann relation. Refer to Figure \\ref{plank-curves} and consider the T\n= 8000 K and the T = 6000 K graphs. The area beneath the T = 8000 K\ngraph is (8000/6000)\\textsuperscript{4} times that beneath the T = 6000\nK graph, i.e. 3.16 times greater.\n\nThe Sun's photosphere is at a temperature of a little under 6000 K;\nnotice that the Planck Curve for this temperature peaks at a wavelength\nlying in the visible part of the electromagnetic spectrum.\n\nWien's Displacement Law enables astronomers to determine the temperature\nof a star from observations of the light (and other radiation) emitted\nby that star.\n\\spec{recognise and use Stefan's law for a spherical body\n\\begin{equation}\n  L = 4\\pi \\sigma r^2 T^4\n\\end{equation}\n}\n\nThe Stefan-Boltzmann Law (sometimes simply called Stefan's Law) states\nthat the Flux from a hot object is proportional to the fourth power of\nthe absolute temperature, T. Strictly speaking, this applies only to\nidealised radiation emitters (referred to as ``black bodies''); the\nconstant of proportionality is the Stefan-Boltzmann constant, $\\sigma$, which\nhas a value of 5.67 x 10\\textsuperscript{-8} W m\\textsuperscript{-2}\nK\\textsuperscript{-4}:\n\n\\[F = \\sigma T^{4}\\]\n\nTherefore, for an emitted with surface area A, the Luminosity will be\ngiven by\n\n\\[L =\\sigma A T^{4}\\]\n\nand in the case of a spherical emitter (such as a star) of radius R,\nthis becomes\n\n\\[L = 4 \\pi R^{2} \\sigma T^{4}\\]\n\n\\spec{use Wien's displacement law and Stefan’s law to estimate the radius of a star}\n\n\n\nHaving determined the temperature, T, one can then use the\nStefan-Boltzmann relation to determine the Luminosity, L. This is a\nmeasure of the actual amount of radiation being emitted by the star. By\nmeasuring the actual amount of radiation received per second per unit\narea (i.e. the flux, F), one can then calculate how big the star must be\n(the surface area from which the radiation is being emitted) in order to\nproduce that amount of Flux.\n\n\\begin{example}\n\\emph{Worked example: Proxima Centauri, the nearest star to the Sun}\n\nData:\n\nParallax angle = 0.8 seconds of arc\n\nPeak wavelength, λ\\textsubscript{max} = 967 nm\n\nFlux measured at Earth = 3.56 x 10\\textsuperscript{11} W\nm\\textsuperscript{-2}\n\n\\begin{enumerate}\n\\def\\labelenumi{\\arabic{enumi}.}\n\\item\n  Calculate the distance to Proxima Centauri.\n\\item\n  Calculate its surface temperature.\n\\item\n  Calculate the Flux at the star's surface\n\\item\n  Hence calculate the radius of the star.\n\\end{enumerate}\n\n\\answer\n\n\\begin{enumerate}\n\\def\\labelenumi{\\arabic{enumi}.}\n\\item\n  D (in parsecs) = 1 / angle of parallax in seconds of arc = 1.25 pc =\n  \\emph{3.85 x 10\\textsuperscript{16} m}\n\\item\n  From Wien's Displacement Law, T = 2.90 x 10\\textsuperscript{-3} m K /\n  967 x 10\\textsuperscript{-9} m = 3000 K\n\\item\n  From Stefan's Law, F = $\\sigma$ T\\textsuperscript{4} = 5.67 x\n  10\\textsuperscript{-8} x 8.10 x 10\\textsuperscript{13} = \\emph{4.6 x\n  10\\textsuperscript{6} W m\\textsuperscript{-2}}\n\\item\n  Flux measured at a distance of 3.85 x 10\\textsuperscript{16} m is 3.56\n  x 10\\textsuperscript{-11} W m\\textsuperscript{-2}.\n\n  So, F\\textsubscript{at Earth} / F\\textsubscript{star's surface} =.\n  (radius of star)\\textsuperscript{2} / (distance to\n  star)\\textsuperscript{2}\n\\end{enumerate}\n\n\\begin{itemize}\n\\item\n  Radius of star = \\emph{1.07 x 10\\textsuperscript{8} m}\n\\end{itemize}\n\n\\end{example}\n\n\\spec{understand that the successful application of Newtonian mechanics and gravitation to the Solar System and beyond indicated that the laws of physics apply universally and not just on Earth}\n\nNewton's law of Universal Gravitation states that two masses, M and m,\nwhose centres are separated by a distance r, will mutually attract with\na gravitational force given by\n\n\\[F = \\frac{G M m }{ r^{2}}\\]\n\nwhere G, the Universal Gravitational Constant, = 6.67 x\n10\\textsuperscript{-11} N m\\textsuperscript{2} kg\\textsuperscript{-2}.\n\nOne of the great triumphs of the law was to demonstrate consistency with\nKepler's Laws of Planetary Motion, formulated empirically some 70 years\nearlier. Kepler's Laws state that the planets move about the Sun in\nelliptical orbits and whilst Newton's Law can be applied to such orbits,\nfor simplicity we consider a planet moving in a circular orbit. If the\nradius of the orbit is r, then from rotational mechanics, the planet\nwill experience a constant centripetal force of $mv^{2}/r$.\nThis origin of this force is the gravitational attraction given by\nNewton's equation and by equating the two formulae it is possible to\nshow that\n\n\\begin{equation}\nT^{2} = \\frac{4 \\pi^{2} r^{3}}{ G M}\n\\end{equation}\n\ni.e. that T\\textsuperscript{2} α r\\textsuperscript{3} as stated by\nKepler's 3\\textsuperscript{rd} Law. Newton's Law, when combined with his\nLaws of Motion, was applied to other objects observed to be in\ngravitational orbits with great success. The movements of planetary\nsatellites, binary star systems, galactic spiral arms and even clusters\nof galaxies themselves have all been shown to be consistent with the\nrelationships. Famously, the relationships demonstrated orbital\nirregularities in the motion of the planet Uranus, high led to the\ndiscovery of the planet Neptune beyond it. Similar anomalous behaviour\nin the rotations of spiral galaxies observed by Vera Rubin has led to\nthe speculation of the existence of Dark Matter.\n\n\\begin{example}\n\nFrom the orbital data for the Earth, calculate the mass of the Sun\n(assuming a circular orbit).\n\n\\answer\n\nRadius of Earth's orbit = 150 x 10\\textsuperscript{6} km\n\nOrbital period of earth = 1 year = 3.2 x 10\\textsuperscript{7} s\n\n\\begin{itemize}\n\\item\n  From Kepler's 3\\textsuperscript{rd} Law (above), \\emph{M = 1.96 x\n  10\\textsuperscript{30} kg}\n\\end{itemize}\n\n\\end{example}\n\\spec{recognise and use\n\\begin{equation}\n  \\frac{\\Delta \\lambda}{\\lambda} \\approx \\frac{\\Delta f}{f} \\approx \\frac{v}{c}\n\\end{equation}\n for a source of electromagnetic radiation moving relative to an observer}\n\n When a source of waves moves away from an observer (in a stationary\n medium), the observer will receive waves of a longer wavelength (and\n thus lower frequency) than those emitted by the source. If the source\n moves towards the observer then the observed wavelength is shorter\n (frequency is higher). This is called Doppler Shift. For example, with\n sound waves this can be perceived as a change in the pitch of the\n emitted sound.\n\n The greater the speed of the source, v, the greater the change in the\n wavelength $\\Delta \\lambda$ (or frequency, $\\Delta f$, whichever is being measured) of the\n waves received by the observer in which c is the velocity of the emitted waves (a relationship strictly\n only true for if c is much greater than v).\n\n The dark lines observed in the visible light spectra of stars and\n galaxies are caused by the absorption of specific frequencies (colours)\n by elements present in those objects, enabling astronomers to determine\n their composition. In the 1920s, Edwin Hubble discovered that the\n absorption lines for distant galaxies were shifted towards the red end\n of the colour (emission) spectrum. This Red Shift indicated that the\n galaxies were moving away (receding) from the Earth. But there were two\n particular features of his discovery that made a special impact:\n\n \\begin{enumerate}\n \\def\\labelenumi{\\alph{enumi})}\n \\item\n   Galaxies were receding in all directions.\n \\item\n   The more distant the galaxy, the higher its recessional velocity.\n \\end{enumerate}\n\n (The distances to the galaxies were established using Standard Candles,\n especially Cepheid Variables.)\n\n\\spec{state Hubble's law and explain why galactic redshift leads to the idea that the Universe is expanding and to the Big Bang theory}\n\nThese observations have led to the conclusion that the universe began\nwith a Big Bang and what Hubble observed was the expansion of space\nitself. A helpful picture is that of the infinite scaffolding by M C\nEscher (Figure \\ref{mcescher}):\n\n\\begin{figure}[h]\n\\begin{center}\n\\includegraphics{figs/chapt-20/media/image2.jpeg}\n\\end{center}\n\\caption{M C Escher drawing}\n\\label{mcescher}\n\\end{figure}\n\nNo matter which junction you view from, if each scaffold pole is\nexpanding, junctions in all directions will appear to recede. Note that,\nin effect, the junctions themselves do not move: the space in between\nthem does. Also, more distant junctions (with more expanding poles\nbetween them and the observer) will appear to recede with greater\nspeeds.\n\nIn such a model, the speed of ``recession'' (expansion) is proportional\nto the distance of the observed galaxy and observations are by and large\nconsistent with this:\n\n$ V = H_{o} d$\n\nin which the constant of proportionality, H\\textsubscript{o,} is known\nas the Hubble Constant, the value of the gradient of the graph of v\nplotted against d (Figure \\ref{hubble-law}):\n\n\\begin{figure}[h]\n\\includegraphics[width=\\textwidth]{figs/chapt-20/media/image3.jpeg}\n\\caption{Hubble's Law}\n\\label{hubble-law}\n\\end{figure}\n\nRecent measurements (see graph) suggest a value of H\\textsubscript{o} of\na little over 67 km s\\textsuperscript{-1} Mpc\\textsuperscript{-1}\n\nGiven that, in the observable universe, the greatest distance from which\nradiation could be received is given by the speed of light x the age of\nthe universe, it follows that the age of the universe will be given by\n1/H\\textsubscript{o}. For the value of H\\textsubscript{o} quoted, this\nequates to an age of\n\nWhen measuring the red shifts of distant galaxies, the calculated\nvelocities thus more properly indicate the rate at which the intervening\nspace is stretching. The value of Δλ/λ (or Δf/f) is called the\nCosmological Red Shift, z, indicating that the space has expanded by a\nfactor of 1 + z in order to produce the observed Doppler Shift.\n\n\nThe quasar 3C273 was the first object of its kind to be identified. So\ncalled because they were star-like but much more luminous\n(``quasi-stellar objects'') they are now known to consist of\nsupermassive black holes that draw in a huge disc of orbiting gas,\ncausing large emissions of radiation across a wide range of wavelengths.\nTheir spectra exhibit large red shifts.\n\n\n\\begin{example}\n\n\\begin{enumerate}\n\\def\\labelenumi{\\arabic{enumi}.}\n\\item\n  One emission line in the spectrum of 3C273 appears at a wavelength of\n  475.0 nm; in the laboratory the same line is measured at 410.2 nm.\n  Calculate the recessional velocity of the quasar.\n\\item\n  Using the value of H\\textsubscript{0} quoted above, hence calculate\n  the distance of 3C273.\n\\end{enumerate}\n\n\\answer\n\n\\begin{enumerate}\n\\def\\labelenumi{\\arabic{enumi}.}\n\\item\n  Δλ = 475.0 -- 410.2 nm = 64.8 nm.\n\\end{enumerate}\n\nFrom Doppler equation, Δλ/λ = v/c, this gives v = 4.74 x\n10\\textsuperscript{7} ms\\textsuperscript{-1} or \\emph{4.74 x\n10\\textsuperscript{4} km s\\textsuperscript{-1}}.\n\n\\begin{enumerate}\n\\def\\labelenumi{\\arabic{enumi}.}\n\\item\n  Assume a value of H\\textsubscript{0} of 67 km s\\textsuperscript{-1}\n  Mpc\\textsuperscript{-1}.\n\\end{enumerate}\n\n\\begin{itemize}\n\\item\n  d = 4.74 x 10\\textsuperscript{4} km s\\textsuperscript{-1} / 67 km\n  s\\textsuperscript{-1} Mpc\\textsuperscript{-1} = \\emph{707 Mpc.}\n\\end{itemize}\n\n\n\\end{example}\n\\spec{explain how microwave background radiation provides empirical support for the Big Bang theory}\n\\spec{understand that the theory of the expanding Universe involves the expansion of space-time and does not imply a pre-existing empty space into which this expansion takes place or a time prior to the Big Bang}\n\\spec{recall and use the equation\n\\begin{equation}\n  v \\approx H_0 d\n\\end{equation}\nfor objects at cosmological distances}\n\\spec{derive an estimate for the age of the Universe by recalling and using the Hubble time\n\\begin{equation}\n  t = \\frac{1}{H_0}\n\\end{equation}\n}\nIn the 1940s, George Gamow suggested that the observed ratio of hydrogen\nto helium in the universe could be explained by assuming the universe\nwas much hotter and denser a long time ago, consistent with the idea of\na Big Bang origin stemming from Hubble's work. His theory predicted the\nexistence of a ``leftover'' radiation which was eventually discovered by\nchance in 1965. This is today known as the Cosmic Microwave Background\nRadiation and it has the biggest cosmological red shift. It was produced\nwhen the early universe had cooled down to about 3000K, low enough for\nelectrons to combine with protons to produce atoms, a process resulting\nin the emission of photons of wavelengths around 1 mm. Because of\ncosmological expansion, the wavelength is now a thousand times bigger\n(millimetres) and the temperature a thousand times smaller, about 3 K.\n\nRefinements to the Big Bang model have included a period of Inflation\nvery early on which gave rise to the eventual clumping of matter, which\naccounts for the later existence of stars and galaxies (and planets and\nhumans). The Cosmic Background Explorer satellite revealed such clumping\n(measured as tiny temperature fluctuations in the background radiation)\nand further evidence is still being sought to confirm Inflation as a\npart of the model.\n\n\\begin{figure}[h]\n\\includegraphics[width=\\textwidth]{figs/chapt-20/media/image4.jpeg}\n\\caption{COBE satellite image}\n\\end{figure}\n\\end{document}\n", "meta": {"hexsha": "aca2882c520b9369c5638773495a2f0bc611899b", "size": 16790, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "20-astronomy-and-cosmology.tex", "max_stars_repo_name": "sirioq/physics-PreU", "max_stars_repo_head_hexsha": "d0f993750d660df38f05085ccf3b351d2ea3dd7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "20-astronomy-and-cosmology.tex", "max_issues_repo_name": "sirioq/physics-PreU", "max_issues_repo_head_hexsha": "d0f993750d660df38f05085ccf3b351d2ea3dd7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "20-astronomy-and-cosmology.tex", "max_forks_repo_name": "sirioq/physics-PreU", "max_forks_repo_head_hexsha": "d0f993750d660df38f05085ccf3b351d2ea3dd7d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5990566038, "max_line_length": 212, "alphanum_fraction": 0.7727814175, "num_tokens": 4483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.31375546462626147}}
{"text": "\\par\n\\chapter{{\\tt Iter}: Iterative Methods}\n\\par\n{\\tt Iter} is composed of 5 Krylov space iterative methods, PCG (Preconditioned Conjugate\nGradients),  BiCGStab,  TFQMR, and BGMRES (Block GMRES), \nand MLBiCGStab. \n(For references, see top comments in codes.)\nThe intent of these methods is to provide the user of {\\bf SPOOLES} with an\n easy way to evaluate the effectiveness of the approximate factorizations belonging\nto the {\\tt FrontMtx} object.  To further facilitate the evaluation we have included\na single call {\\tt driver} that can run anyone of the methods we have provided with the\ntype of preconditioner desired.  For each iterative method we allow for left and right \npreconditioning.  Also, for each method, except BGMRES, we allow for real or\ncomplex matrices.\n\\par\nBecause our intent was to provide a simple means to test the effectiveness of the\npreconditioners, these implementations are not parallel (neither shared or distributed\nmemory).  However, they were intentionally written to be consistent in style and form\nso that they could be easily adapted to exploit the parallelism that is in {\\bf SPOOLES}.\nAll iterative methods use the basic structure {\\tt DenseMtx} for handling the intermediate\nvectors and performing the matrix multiplications and system solves.  By doing this\nwe have also anticipated the eventual movement to block iterative methods and the\n{\\tt DenseMtx} structure can remain the basic structure.  There are a few basic\nutilities that have been added, which are discribed in this section, upon which the\niterative methods were built.  These are provided to aid the experienced {\\bf SPOOLES} \nuser with an ability to develop additional iterative methods, as seen fit.\n\n\n", "meta": {"hexsha": "6efa9a4618bc85efd74caec51008db4fd5133b56", "size": 1712, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ccx_prool/SPOOLES.2.2/Iter/doc/intro.tex", "max_stars_repo_name": "alleindrach/calculix-desktop", "max_stars_repo_head_hexsha": "2cb2c434b536eb668ff88bdf82538d22f4f0f711", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ccx_prool/SPOOLES.2.2/Iter/doc/intro.tex", "max_issues_repo_name": "alleindrach/calculix-desktop", "max_issues_repo_head_hexsha": "2cb2c434b536eb668ff88bdf82538d22f4f0f711", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-09-21T17:03:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-25T16:08:31.000Z", "max_forks_repo_path": "ccx_prool/SPOOLES.2.2/Iter/doc/intro.tex", "max_forks_repo_name": "alleindrach/calculix-desktop", "max_forks_repo_head_hexsha": "2cb2c434b536eb668ff88bdf82538d22f4f0f711", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-08-29T18:41:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-29T18:41:28.000Z", "avg_line_length": 59.0344827586, "max_line_length": 90, "alphanum_fraction": 0.796728972, "num_tokens": 399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3136611049543904}}
{"text": "\\section{Additional visualizations}\n\n\\begin{figure}[h]\n\\begin{subfigure}[t]{0.3\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{img/loracs/mnist/tsne/mnist2-tsne-normal.png}\n    \\caption{Normal prior}\n\\end{subfigure}\n\\begin{subfigure}[t]{0.3\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{img/loracs/mnist/tsne/mnist2-tsne-noprior.png}\n    \\caption{No prior}\n\\end{subfigure}\n\\begin{subfigure}[t]{0.3\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{img/loracs/mnist/tsne/mnist2-tsne-vamp.png}\n    \\caption{Vam\\p(500) prior}\n\\end{subfigure}\n~\n\\begin{subfigure}[t]{0.3\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{img/loracs/mnist/tsne/mnist2-tsne-maf.png}\n    \\caption{MAF prior}\n\\end{subfigure}\n\\begin{subfigure}[t]{0.3\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{img/loracs/mnist/tsne/mnist2-tsne-tmc.png}\n    \\caption{\\acronym(200) prior}\n\\end{subfigure}\n\\caption{TSNE visualizations of the latent space of the MNIST test set with various prior distributions, color-coded according to class.}\n\\label{fig:tsne}\n\\end{figure}\n\n\\begin{figure}[h]\n    \\centering\n    \\includegraphics[width=0.5\\textwidth]{img/loracs/mnist/tsne/mnist2-tsne-tmc-tree.png}\n    \\caption{A TSNE visualization of the latent space for the TMC(200) model with inducing points and one sample from $\\q(\\tree; \\inducingpoints)$ plotted. Internal nodes are visualized by computing their expected posterior values, and branches are plotted in 2-d space.}\n    \\label{fig:mnist-tsne-tree}\n\\end{figure}\n\n\n\\begin{figure}[h]\n\\centering\n\\includegraphics[width=0.5\\textwidth]{img/loracs/mnist/mnist-vamp-inputs.png}\n\\caption{MNIST VampPrior learned pseudo-inputs.}\n\\label{fig:mnist-vamp-inducing}\n\\end{figure}\n\\begin{figure}[h]\n\\centering\n\\includegraphics[width=0.5\\textwidth]{img/loracs/mnist/mnist-vamp-outputs.png}\n\\caption{MNIST VampPrior reconstructed pseudo-inputs obtained by\ndeterministically encoding and decoding each pseudo-input.}\n\\label{fig:mnist-vamp-inducing-outputs}\n\\end{figure}\n\n\\begin{figure}[h]\n\\centering\n\\includegraphics[width=0.4\\textwidth]{img/loracs/omniglot/inducing-points.png}\n\\caption{Omniglot learned inducing points.}\n\\label{fig:omniglot-inducing-points}\n\\end{figure}\n\n\\begin{figure}[h]\n\\centering\n\\includegraphics[width=0.8\\textwidth]{img/loracs/celeba/inducing-points.png}\n\\caption{CelebA learned inducing points.}\n\\label{fig:celeba-inducing-points}\n\\end{figure}\n\n\\section{Empirical results}\n\n\\begin{sidewaystable}\n\\scriptsize\n\\centering\n\\caption{MNIST few-shot classification results.}\n\\setlength{\\tabcolsep}{2pt}\n\\input{results/loracs/cf-mnist.tex}\n\\label{tab:semisupervised-mnist}\n\\end{sidewaystable}\n\n\\begin{sidewaystable}\n\\scriptsize\n\\setlength{\\tabcolsep}{2pt}\n\\centering\n\\caption{Omniglot few-shot classification results.}\n\\input{results/loracs/cf-omniglot.tex}\n\\label{tab:semisupervised-omniglot}\n\\end{sidewaystable}\n\n\\begin{table}\n\\centering\n\\caption{MNIST few-shot classification with labeled inducing points.}\n\\scriptsize\n\\setlength{\\tabcolsep}{2pt}\n\\begin{tabular}{r|cc}\n\\toprule\n     \\# of inducing points &  200 & 500\\\\\n\\midrule\n        & 0.9428 & 0.9474\\\\\n\\bottomrule\n\\end{tabular}\n\\label{tab:inducing-point-labels}\n\\end{table}\n\n\\begin{figure}\n\\centering\n\\begin{subfigure}[h]{0.4\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{img/loracs/mnist/ir-mnist-joint.png}\n    \\caption{MNIST}\n\\end{subfigure}\n\\begin{subfigure}[h]{0.4\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{img/loracs/omniglot/ir-omniglot-joint.png}\n    \\caption{Omniglot}\n\\end{subfigure}\n\\caption{Averaged precision-recall curves over test datasets.}\n\\label{fig:prec-rec}\n\\end{figure}\n\n\\section{Algorithm details}\n\\label{sec:algorithm-details}\n\n\\subsection{Stick breaking process}\n\\label{sec:stick-breaking}\nConsider inserting a node $\\numdata + 1$ into the tree in between vertices $u$ and $v$\nsuch that $t_v > t_u$,\ncreating branch $e_{\\numdata + 1}$.\nThe inserted node has time $t_{\\numdata + 1}$ with probability according to the stick breaking process, i.e.\n\\begin{equation}\n\\textstyle r(t_{\\numdata+1}\\given e_{\\numdata+1}, V, E) =\n\\mathrm{Beta}\\left(\\frac{t_v - t_{\\numdata + 1}}{1 - t_{\\numdata + 1}}; a, b\\right)\\mathrm{Beta}\\left(\\frac{t_{\\numdata + 1} - t_u}{1 - t_u}; a, b\\right).\n\\end{equation}\n\n\\subsection{Belief propagation in TMCs}\n\nThe TMC is at the core of the \\acronym\\;\nprior.\nRecall that the TMC is\na prior over phylogenies $\\tree$,\nand after attaching a Gaussian random walk (GRW),\nwe obtain a distribution over $N$ vectors in $\\mathbb{R}^d$,\ncorresponding to the leaves, $r(\\latentdataset \\given \\tree)$.\nHowever, the GRW samples\nlatent vectors at internal nodes $z_{V_{\\text{int}}}$.\nRather than explicitly representing these values,\nin this work we marginalize them out, i.e.\n\\begin{equation}\n    r(\\latentdataset \\given \\tree) = \\int r(\\latentdataset \\given z_{V_{\\text{int}}}, \\tree)\\p(z_{V_{\\text{int}}} \\given \\tree) dz_{V_{\\text{int}}}\n\\end{equation}\nThis marginalization process can be done efficiently, because our graphical model\nis tree-shaped and all nodes have Gaussian likelihoods. Belief propagation is a message-passing\nframework for marginalization and we utilize message-passing\nfor several TMC inference queries. The main queries we are interested in are:\n\\begin{enumerate}\n    \\item $r(\\latentdataset, \\tree)$ - for the purposes of MCMC, we are interested in computing the joint likelihood of a set of observed\n    leaf values and a phylogeny.\n    \\item $r(\\z_\\n \\given z_{\\backslash n}, \\tree)$ - this query computes the posterior density over one leaf given all the others;\n    we use this distribution when computing the posterior predictive density of a TMC.\n    \\item $\\nabla_{z_{\\backslash n}} r(\\z_\\n \\given z_{\\backslash n}, \\tree)$ - this query is the gradient of the predictive density \n    of a single leaf with respect to the values at all other leaves. This query is used\n    when computing gradients of the ELBO w.r.t $\\inducingpoints$ in the \\acronym\\;prior.\n\\end{enumerate}\n\n\\textbf{Message passing} Message\npassing treats the tree as an undirected graph. \nWe first pick start node $v_{\\text{start}}$\nand request messages from each of $v_{\\text{start}}$'s neighbors.\n\nMessage passing is thereafter defined recursively. \nWhen a node $v$ has requested messages from a source node $s$,\nit thereafter requests messages from all its neighbors but $s$.\nThe base case for this recursion is a leaf node $v_\\n$,\nwhich returns a message with the following contents:\n\\begin{equation}\n    \\nu_\\n = \\bm{0};\\quad \\mu_\\n = \\z_\\n;\\quad \\log \\z_\\n = 0;\\quad \\nabla_{\\nu_\\n}(\\nu) = \\bm{1};\\quad \\nabla_{\\nu_\\n}(\\mu) = \\bm{0};\\quad \\nabla_{\\mu_\\n}(\\mu) = \\bm{1}\n\\end{equation}\nwhere bold numbers $\\bm{0}\\triangleq (0,\\ldots,0)^\\top$ and $\\bm{1}\\triangleq (1,\\ldots,1)^\\top$ denote vectors obtained by repeating a scalar $d$ times.\n\nIn the recursive case, consider being at a node $i$ and receiving a set of messages from its neighbors $M$.\n\\begin{equation}\n\\begin{split}\n    \\nu_i = \\frac{1}{\\sum_{m \\in M}\\frac{1}{\\nu_m + e_{im}}} ;\\quad \\mu_i = v_i \\sum_{m \\in M} \\frac{\\mu_m}{\\nu_m + e_{im}}\\\\\n\\end{split}\n\\end{equation}\nwhere $e_{im}$ is the length of the edge between nodes $i$ and $m$.\nThese messages are identical to those used in \\citet{Boyles2012}.\n\nAdditionally, our messages include gradients w.r.t. \\emph{every} leaf node\ndownstream of the message.\nWe update each of these gradients when computing the new message\nand pass them along to the source node.\nGradients with respect to one of these nodes $j$ are calculated as\n\\begin{equation}\n\\begin{split}\n    \\nabla_{\\nu_j}(\\nu) &= \\nabla_{\\nu_j} \\nu_i\\\\\n    \\nabla_{\\nu_j}(\\mu) &= \\nabla_{\\nu_j} \\mu_i\\\\\n    \\nabla_{\\mu_j}(\\mu) &= \\nabla_{\\mu_j} \\mu_i\\\\\n\\end{split}\n\\end{equation}\nThe most complicated message is the $\\log Z_i$ message, which depends\non the number of incoming messages. $v_{\\text{start}}$ gets\nthree incoming messages,\nall other nodes get only two. Consider\ntwo messages from nodes $v_k$ and $v_l$:\n\\begin{equation}\n\\begin{split}\n    \\Sigma_i &\\triangleq (\\nu_k + e_{ik} + \\nu_l + e_{il})I \\\\\n    \\log Z_i &= -\\frac{1}{2}\\|\\mu_k - \\mu_l\\|^2_{\\Sigma_i} - \\frac{1}{2}\\left(\\log|\\Sigma_i| _ d\\log2\\pi\\right)\n\\end{split}\n\\end{equation}\nFor three messages from nodes\n$v_k$, $v_l$, and $v_m$:\n\\begin{equation}\n\\begin{split}\n    \\Sigma_i &\\triangleq \\left((\\nu_k + e_{ik})(\\nu_l + e_{il}) + (\\nu_l + e_{il})(\\nu_m + e_{im}) + (\\nu_m + e_{im})(\\nu_k + e_{ik})\\right)I \\\\\n    \\log Z_i &= -\\frac{1}{2}\\left((\\nu_m + e_{im})\\|\\mu_k - \\mu_l\\|^2_{\\Sigma_i} + (\\nu_k + e_{ik})\\|\\mu_l - \\mu_m\\|^2_{\\Sigma_i} + (\\nu_l + e_{il})\\|\\mu_m - \\mu_k\\|^2_{\\Sigma_i}\\right)  \\\\\n             &- \\frac{1}{2}\\log|\\Sigma_i| - \\log2\\pi\n\\end{split}\n\\end{equation}\n\nWith these messages, we can answer all the aforementioned inference queries.\n\\begin{enumerate}\n    \\item We can begin message passing at any internal node and compute: $\\log r(\\latentdataset, \\tree) = \\sum_{v \\in V} \\log Z_v$\n    \\item We start message passing at $v_\\n$. $r(\\z_\\n \\given z_{\\backslash n}, \\tree)$ is a Gaussian with mean $\\mu_\\n$ and variance $\\nu_\\n$.\n    \\item $\\nabla_{z_{\\backslash n}} r(\\z_\\n \\given z_{\\backslash n}, \\tree)$ is $\\nabla_{z_{\\backslash n}} \\N(\\z_\\n \\given \\mu_\\n, \\nu_\\n I)$,\n    which in turn utilizes gradients sent via message passing.\n\\end{enumerate}\n\n\\textbf{Implementation} We chose\nto implement the TMC and message\npassing in Cython because we found raw Python to be\ntoo slow due to function call and type-checking\noverhead. Furthermore, we used diagonal rather than\nscalar variances in the message passing implementation\nto later support diagonal variances handed \nfrom the variational posterior over $\\z_\\n$.\n\n\\subsection{Variational inference for the \\acronym\\;prior}\n\\label{sec:inference-details}\n\nThe \\acronym\\; prior involves first sampling a tree\nfrom the posterior distribution over TMCs\nwith $\\inducingpoints$ as leaves.\nWe then sample a branch and time\nfor each data $\\z_\\n$ according\nto the posterior predictive\ndistribution described in \\autoref{sec:bnhc}.\nWe then sample a $\\z_\\n$ from\nthe distribution induced by the GRW likelihood model.\nFinally, we pass the sampled $\\z_\\n$\nthrough the decoder.\n\\begin{equation}\n    \\begin{split}\n        \\tree &\\sim \\p(\\tree ; \\inducingpoints) \\\\\n        e_\\n, t_\\n &\\sim \\p(e_\\n, t_\\n | \\tree) \\\\\n        \\z_\\n | e_\\n, t_\\n, \\tree &\\sim \\p(\\z_\\n | e_\\n, t_\\n, \\tree; \\inducingpoints) \\triangleq r(s_{M + 1} = \\z_\\n | e_\\n, t_\\n, \\tree) \\\\\n        \\x_\\n | \\z_\\n &\\sim \\p_\\genparam(\\x_\\n | \\z_\\n)\n    \\end{split}\n\\end{equation}\n\nConsider sampling the optimal $q^*(\\tree; \\inducingpoints)$.\n\n\\begin{equation}\n\\begin{split}\n    q^*(\\tree; \\inducingpoints) \n    &\\propto \\exp{\\E_\\q\\left[\\log \\p(\\tree, \\latentdataset, \\dataset)\\right]} \\\\\n    &\\propto \\exp{\\log \\p(\\tree ; \\inducingpoints) + \\sum_\\n \\E_\\q\\left[\\p(\\z_\\n | e_\\n, t_\\n, \\tree)\\right]} \\\\\n    &\\propto \\exp{\\log \\mathrm{TMC}_\\n(\\tree; a, b) + \\sum_{m = 1}^M \\log r(\\inducingpoint_m | \\inducingpoint_{1:m - 1}, \\tree) \\\\&+ \\sum_\\n \\E_\\q\\left[\\log \\p(\\z_\\n | e_\\n, t_\\n, \\tree)\\right]} \\\\\n\\end{split}\n\\end{equation}\nWe  set $\\q(\\tree; \\inducingpoints) = r(\\tree \\given \\inducingpoints)$.\nWe use additional variational factors\n$\\q(e_\\n)$,\n$q_{\\xi}(t_\\n | e_\\n, \\z_\\n; \\inducingpoints)$,\nand\n$q_\\recparam(\\z_\\n | \\x_\\n)$.\n$q_{\\xi}(t_\\n | e_\\n, \\z_\\n; \\inducingpoints)$ is a\nrecognition network that outputs\nthe attach time for a particular branch.\nSince the $\\q(\\tree; \\inducingpoints)$ and $\\p(\\tree; \\inducingpoints)$ terms\ncancel out, we obtain the following ELBO.\n\\begin{equation}\n    \\begin{split}\n    \\L[q] &\\triangleq \\E_\\q \\left[\\log \\frac{\\prod_\\n \\p(e_\\n, t_\\n | \\tree) \\p(\\z_\\n | e_\\n, t_\\n, \\tree; \\inducingpoints)\\p_\\genparam(\\x_\\n | \\z_\\n)}{\\prod_\\n \\q(e_\\n)q_{\\xi}(t_\\n | e_\\n, \\z_\\n; \\inducingpoints)q_\\recparam(\\z_\\n | \\x_\\n)}\\right] \\\\\n    \\end{split}\n\\end{equation}\n\n\\textbf{Inference procedure}\nIn general, $\\q(\\tree; \\inducingpoints)$ can\nbe sampled using vanilla SPR Metropolis-Hastings,\nso samples from this distribution are readily available. \n\nFor each data in the minibatch $\\x_\\n$, we pass it\nthrough the encoder to obtain $\\q(\\z_\\n | \\x_\\n)$.\nWe then compute\n\\begin{equation}\n    q^*(e_\\n) = \\exp{\\E_\\q\\left[\\log \\p(e_\\n | t_\\n, \\z_\\n, \\tree; \\inducingpoints)\\right]}\n\\end{equation}\nThis quantity is computed by looping\nover every branch $b$ of \na sample from $\\q(\\tree)$,\nstoring incoming messages at each node,\npassing the $\\mu$ and $\\nu$\nand a sample from $\\q(\\z_\\n | \\x_\\n)$\ninto $q_\\xi(t_\\n | e_\\n, \\inducingpoints, \\z_\\n)$,\noutputting a logistic-normal distribution\nover times for that branch. We sample that\nlogistic normal to obtain a time $t$\nto go with branch $b$. We can then compute\nthe log-likelihood of $\\z_\\n$ if it were\nto attach to $b$ and $t$, using TMC\ninference query \\#2.\nThis log-likelihood is added to the TMC prior log-probability\nof the branch being selected to obtain\na joint probability $\\E_\\q\\left[\\log \\p(e_\\n)\\p(t_\\n)\\p(\\z_\\n | e_\\n, t_\\n, \\tree; \\inducingpoints)\\right]$ over the branch.\nAfter doing this for every branch, we normalize\nthe joint likelihoods to obtain\nthe optimal categorical distribution over every branch\nfor $\\z_\\n$, $q^*(e_\\n)$. We then sample this\ndistribution to obtain an attach location and time\n$e_\\n, t_\\n$ for each data in the minibatch.\n\nThe next stage is to compute gradients w.r.t. to the\nlearnable parameters of the model ($\\genparam$, $\\inducingpoints$, $\\recparam$, and $\\xi$).\nIn the process of calculating $q^*(e_\\n)$,\nwe have obtained samples from its corresponding \n$q_\\xi(t_\\n | e_\\n, \\z_\\n, \\tree; \\inducingpoints)$ and $\\q(\\z_\\n | \\x_\\n)$.\nWe plug these into the ELBO and can compute\ngradients via automatic differentiation w.r.t. $\\recparam$,\n$\\genparam$, and $\\xi$. Computing gradients w.r.t.\n$\\inducingpoints$ is more tricky. We first examine the ELBO.\n\n\\begin{equation}\n    \\L[\\q] = \\E_\\q \\left[\\log \\frac{\\prod_\\n \\p(e_\\n|\\tree) \\p(t_\\n) \\p(\\z_\\n | e_\\n, t_\\n, \\tree; \\inducingpoints)\\p_\\genparam(\\x_\\n | \\z_\\n)}{\\prod_\\n \\q(e_\\n)\\q_{\\xi}(t_\\n | e_\\n, \\z_\\n; \\inducingpoints)q_\\recparam(\\z_\\n | \\x_\\n)}\\right]\n\\end{equation}\n\nConsider the gradient of the ELBO with respect to $\\inducingpoints$.\n\n\\small\n\\begin{equation}\n    \\begin{split}\n    \\nabla_{\\inducingpoints}\\L[q] &=\n    \\nabla_{\\inducingpoints}\\E_\\q \\left[\\log \\frac{\\prod_\\n \\p(e_\\n|\\tree) \\p(t_\\n) \\p(\\z_\\n | e_\\n, t_\\n, \\tree; \\inducingpoints)\\p_\\genparam(\\x_\\n | \\z_\\n)}{\\prod_\\n \\q(e_\\n)q_{\\xi}(t_\\n | e_\\n, \\z_\\n; \\inducingpoints)q_\\recparam(\\z_\\n | \\x_\\n)}\\right] \\\\\n    &= \\nabla_{\\inducingpoints}\\sum_{\\tree} \\q(\\tree; \\inducingpoints)\\E_\\q \\left[\\log \\frac{\\prod_\\n \\p(e_\\n|\\tree) \\p(t_\\n) \\p(\\z_\\n | e_\\n, t_\\n, \\tree; \\inducingpoints)\\p_\\genparam(\\x_\\n | \\z_\\n)}{\\prod_\\n \\q(e_\\n)q_{\\xi}(t_\\n | e_\\n, \\z_\\n; \\inducingpoints)q_\\recparam(\\z_\\n | \\x_\\n)}\\right]\\\\\n    &= \\sum_\\tree \\q(\\tree; \\inducingpoints)\\nabla_{\\inducingpoints}\\E_\\q\\left[\\log \\frac{\\prod_\\n \\p(e_\\n|\\tree) \\p(t_\\n) \\p(\\z_\\n | e_\\n, t_\\n, \\tree; \\inducingpoints)\\p_\\genparam(\\x_\\n | \\z_\\n)}{\\prod_\\n \\q(e_\\n)q_{\\xi}(t_\\n | e_\\n, \\z_\\n; \\inducingpoints)q_\\recparam(\\z_\\n | \\x_\\n)}\\right]\\\\\n    &+ \\sum_\\tree \\left(\\nabla_{\\inducingpoints} \\q(\\tree; \\inducingpoints)\\right)\\E_\\q \\left[\\log \\frac{\\prod_\\n \\p(e_\\n|\\tree) \\p(t_\\n) \\p(\\z_\\n | e_\\n, t_\\n, \\tree; \\inducingpoints)\\p_\\genparam(\\x_\\n | \\z_\\n)}{\\prod_\\n \\q(e_\\n)q_{\\xi}(t_\\n | e_\\n, \\z_\\n; \\inducingpoints)q_\\recparam(\\z_\\n | \\x_\\n)}\\right]\\\\\n    &= \\sum_\\tree \\q(\\tree; \\inducingpoints)\\nabla_{\\inducingpoints}\\E_\\q\\left[\\log \\frac{\\prod_\\n \\p(e_\\n|\\tree) \\p(t_\\n) \\p(\\z_\\n | e_\\n, t_\\n, \\tree; \\inducingpoints)\\p_\\genparam(\\x_\\n | \\z_\\n)}{\\prod_\\n \\q(e_\\n)q_{\\xi}(t_\\n | e_\\n, \\z_\\n; \\inducingpoints)q_\\recparam(\\z_\\n | \\x_\\n)}\\right]\\\\\n    &+ \\sum_\\tree \\left(\\q(\\tree;\\inducingpoints)\\nabla_{\\inducingpoints} \\log \\q(\\tree; \\inducingpoints)\\right)\\E_\\q \\left[\\log \\frac{\\prod_\\n \\p(e_\\n|\\tree) \\p(t_\\n) \\p(\\z_\\n | e_\\n, t_\\n, \\tree; \\inducingpoints)\\p_\\genparam(\\x_\\n | \\z_\\n)}{\\prod_\\n \\q(e_\\n)q_{\\xi}(t_\\n | e_\\n, \\z_\\n; \\inducingpoints)q_\\recparam(\\z_\\n | \\x_\\n)}\\right]\\\\\n    &= \\E_{\\q(\\tree)}\\left[\\nabla_{\\inducingpoints}\\E_\\q\\left[\\log \\frac{\\prod_\\n \\p(e_\\n|\\tree) \\p(t_\\n) \\p(\\z_\\n | e_\\n, t_\\n, \\tree; \\inducingpoints)\\p_\\genparam(\\x_\\n | \\z_\\n)}{\\prod_\\n \\q(e_\\n)q_{\\xi}(t_\\n | e_\\n, \\z_\\n; \\inducingpoints)q_\\recparam(\\z_\\n | \\x_\\n)}\\right]\\right.\\\\\n    &+ \\left.\\nabla_{\\inducingpoints} \\log \\q(\\tree; \\inducingpoints)\\E_\\q \\left[\\log \\frac{\\prod_\\n \\p(e_\\n|\\tree) \\p(t_\\n) \\p(\\z_\\n | e_\\n, t_\\n, \\tree; \\inducingpoints)\\p_\\genparam(\\x_\\n | \\z_\\n)}{\\prod_\\n \\q(e_\\n)q_{\\xi}(t_\\n | e_\\n, \\z_\\n; \\inducingpoints)q_\\recparam(\\z_\\n | \\x_\\n)}\\right]\\right]\\\\\n    &= \\E_{q}\\left[\n        \\nabla_{\\inducingpoints}\\left(-\\log \\q(e_\\n) - \\log \\q(t_\\n \\given \\z_\\n, e_\\n, \\tree; \\inducingpoints) + \\log \\p(\\z_\\n \\given e_\\n, t_\\n, \\tree; \\inducingpoints)\\right)\n    \\right] \\\\\n    &+ \\E_\\q\\left[\\nabla_{\\inducingpoints}\\left(\\log \\q(\\tree) + \\log \\q(e_\\n)\\right)\\log\\frac{\\p(e_\\n | \\tree)}{\\q(e_\\n)}\\frac{\\p(\\z_\\n \\given \\z_\\n, e_\\n, t_\\n, \\tree; \\inducingpoints)}{\\q(t_\\n \\given \\z_\\n, e_\\n, \\tree; \\inducingpoints)}\\right]\n    \\end{split}\n\\end{equation}\n\\normalsize\n\nIn the last step, we expand out expectation over $e_\\n$ and\nthen pass the derivative through like we did for $\\tree$.\nThe gradients w.r.t. $\\q(e_\\n)$ are zero, since $q^*(e_\\n)$ is\na partial optimum of the ELBO and we are left with:.\n\\begin{equation}\n    \\begin{split}\n        \\nabla_{\\inducingpoints}\\L[q] &= \\E_\\q\\left[\\nabla_{\\inducingpoints}\\log \\p(\\z_\\n | e_\\n, t_\\n, \\tree; \\inducingpoints)\\right] - \\E_\\q\\left[\\log \\q(t_\\n \\given \\z_\\n, e_\\n, \\tree; \\inducingpoints)\\right] \\\\\n        &+ \\E_\\q\\left[\\nabla_{\\inducingpoints} \\log \\q(\\tree; \\inducingpoints)\\log\\frac{\\p(e_\\n | \\tree)}{\\q(e_\\n)}\\frac{\\p(\\z_\\n \\given \\z_\\n, e_\\n, t_\\n, \\tree; \\inducingpoints)}{\\q(t_\\n \\given \\z_\\n, e_\\n, \\tree; \\inducingpoints)}\\right]\n    \\end{split}\n\\end{equation}\nThe first term of the gradient is the expected gradient\nof the posterior predictive density w.r.t $\\inducingpoints$.\nThis can be calculated by using TMC inference query \\#3\nusing samples from $\\q(e_\\n)$ and $\\q(t_\\n \\given \\z_\\n, e_\\n, \\tree; \\inducingpoints)$. The second term also uses the same gradients, by means\nof the chain rule to differentiate through the time-amortization network.\nThe third term of this gradient is a score function gradient,\nwhich we decide to not use due to the high-variance nature of score function gradients. We found that we were able to obtain strong results even with biased gradients.\n\n\\section{Details of experiments}\n\\label{sec:implementation-details}\n\nWe implemented the \\acronym\\;prior in Tensorflow\nand Cython. \nFor MNIST and Omniglot, our architectures are in \\autoref{tab:mnist-arch} and CelebA is in \\autoref{tab:celeba-arch}.\n\n\\begin{table}\n\\centering\n\\caption{Network architectures for MNIST and Omniglot}\n\\begin{subfigure}[h]{0.4\\textwidth}\n\\caption{Encoder}\n\\begin{tabular}{lll}\n\\toprule\nLayer type & Shape \\\\\n\\midrule\nConv + ReLU & [3, 3, 64], stride 2 \\\\\nConv + ReLU & [3, 3, 32], stride 1 \\\\\nConv + ReLU & [3, 3, 16], stride 2 \\\\\nFC + ReLU & 512 \\\\\nGaussian & 40 \\\\\n\\bottomrule\n\\end{tabular}\n\\end{subfigure}\n\\begin{subfigure}[h]{0.4\\textwidth}\n\\caption{Decoder}\n\\begin{tabular}{lll}\n\\toprule\nLayer type & Shape \\\\\n\\midrule\nFC + ReLU & 3136 \\\\\nDeconv + ReLU & [3, 3, 32], stride 2 \\\\\nDeconv + ReLU & [3, 3, 32], stride 1 \\\\\nDeconv + ReLU & [3, 3, 1], stride 2 \\\\\nBernoulli & \\\\\n\\bottomrule\n\\end{tabular}\n\\end{subfigure}\n\\label{tab:mnist-arch}\n\\end{table}\n\n\\begin{table}\n\\centering\n\\caption{Network architectures for CelebA}\n\\begin{subfigure}[h]{0.4\\textwidth}\n\\caption{Encoder}\n\\begin{tabular}{lll}\n\\toprule\nLayer type & Shape \\\\\n\\midrule\nConv + ReLU & [3, 3, 64], stride 2 \\\\\nConv + ReLU & [3, 3, 32], stride 1 \\\\\nConv + ReLU & [3, 3, 16], stride 2 \\\\\nFC + ReLU & 512 \\\\\nGaussian & 40 \\\\\n\\bottomrule\n\\end{tabular}\n\\end{subfigure}\n\\begin{subfigure}[h]{0.4\\textwidth}\n\\caption{Decoder}\n\\begin{tabular}{lll}\n\\toprule\nLayer type & Shape \\\\\n\\midrule\nFC + ReLU & 4096 \\\\\nDeconv + ReLU & [3, 3, 32], stride 2 \\\\\nDeconv + ReLU & [3, 3, 32], stride 1 \\\\\nDeconv + ReLU & [3, 3, 3], stride 2 \\\\\nBernoulli & \\\\\n\\bottomrule\n\\end{tabular}\n\\end{subfigure}\n\\label{tab:celeba-arch}\n\\end{table}\n\nIn general, we trained the model interleaving\none gradient step with 100 sampling steps for $\\q(\\tree; \\inducingpoints)$.\nWe also found that experimenting with values of $a$ and $b$\nin the TMC prior did not impact results significantly.\nWe initialized the networks with weights\nfrom a VAE trained for 100 epochs and inducing points\nwere initialized using k-means. All parameters\nwere trained using Adam \\citep{Kingma2014adam} with a $10^{-3}$ learning rate\nfor an 100 epochs with learning rate decay to $10^{-5}$ for the last 20 epochs. \nFinally, we initialized trees with all node times close to 0,\nto emulate a VAE prior.\n\n\\subsection{Baseline details}\nAll baselines were trained with the default architecture.\nThey were trained for 400 epochs,\nwith KL warmup ($\\beta$ started at $10^{-2}$, and ramped up to $\\beta = 1$\nlinearly over 50 epochs). They were trained using Adam with a\nlearning rate of $10^{-3}$, with a learning rate of $10^{-5}$ for\nthe last 80 epochs.\n\nDVAE\\# was trained using the default implementation from\n\\url{https://github.com/QuadrantAI/dvae}, which is hierarchical\nVAE consisting of two Bernoulli latent variables, 200-dimensional each.\nEach is learned via a feed-forward neural network 4-layers deep.\nThe default DVAE\\# implementation also uses statically binarized MNIST\nwhere we use dynamically binarized.\n", "meta": {"hexsha": "508ce708728e1df4e4f97dfd2bf11c3e9c28eebb", "size": 21600, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "writeup/content/appendix/loracs-appendix.tex", "max_stars_repo_name": "sharadmv/thesis", "max_stars_repo_head_hexsha": "5fbf70c0645e44b2992f3cb4d7c2fbbbf7592d7f", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-30T01:28:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-30T01:28:54.000Z", "max_issues_repo_path": "writeup/content/appendix/loracs-appendix.tex", "max_issues_repo_name": "sharadmv/thesis", "max_issues_repo_head_hexsha": "5fbf70c0645e44b2992f3cb4d7c2fbbbf7592d7f", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "writeup/content/appendix/loracs-appendix.tex", "max_forks_repo_name": "sharadmv/thesis", "max_forks_repo_head_hexsha": "5fbf70c0645e44b2992f3cb4d7c2fbbbf7592d7f", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.0939457203, "max_line_length": 340, "alphanum_fraction": 0.6953703704, "num_tokens": 7505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.31366109789601915}}
{"text": "% !TeX root = ../../main.tex\n% !TEX spellcheck = en_GB\n\n\\section{Design}\n\\label{ch:Design}\nOn \\cref{fig:DetailedDesign_prepro} is a detailed description of the preprocessing block.\n\\begin{figure}\n\t\\centering\n\t\\includegraphics[width=1\\linewidth]{gfx/Design/DesignDetailed_Preprocesing.pdf}\n\t\\caption{Detailed description of preprocessing in \\systemName.}\n\t\\label{fig:DetailedDesign_prepro}\n\\end{figure}\n\nInput is a time signal, and the output is a discrete signal. Firstly the time signal will be sampled with \\SI{48000}{\\hertz}. After the signal is sampled it will enter the decimation part, which consist of a lowpass filter with a cutoff at \\SI{1200}{\\hertz} and stop at \\SI{2400}{\\hertz}. The downsampling will be a factor $M=10$. The last phase of the proprocessing is too gather the data in a buffer. The buffer size will be 4069, hence the frequency resolution will be $f_{resolution} = \\frac{fs_{new}}{size}= \\frac{\\SI{4800}{\\hertz}}{4096}= \\SI{1.17}{\\hertz}$. An problem with this method is, the time delay that will be created. The closer the size of the buffer gets to $4800$ the closer the delay will become \\SI{1}{\\second}. An advantage is that the memory usage will be significantly lower then if there was sampled 48000 samples.\\newline The output from the preprocessing block will continue too the signal processing block, here a detailed block can be seen on \\cref{fig:DetailedDesign_sigpro}.\n\\begin{figure}\n\t\\centering\n\t\\includegraphics[width=1\\linewidth]{gfx/Design/DesignDetailed_Signalprocessing.pdf}\n\t\\caption{Detailed description of signal processing in \\systemName.}\n\t\\label{fig:DetailedDesign_sigpro}\n\\end{figure}\n\nInput to the signal processing block is the discrete signal which was the output from the preprocessing block. The output from signal processing is, the new changed discrete signal where the frequency has been changed. The input signal will go too the FFT block, here $fs=\\SI{4800}{\\hertz}$ and $n=4096$. The FFT block will have as output the transformed signal called xfft. xfft will be passed onto the block FindMax which will find the max frequency and the corresponding bin nr. FindMax will then pass on this information to the PitchShift Algorithm which will use this information on the discrete input signal. As output will the new discrete signal with a new frequency. The challenge is the end of each processed block has to match the next block of data. Therefore a future extension would be to make each block overlap so they match eachother. The output from signal processing will be passed on to the postprocessing block which can be seen on \\cref{fig:DetailedDesign_postpro}. \n\n\\begin{figure}\n\t\\centering\n\t\\includegraphics[width=1\\linewidth]{gfx/Design/DesignDetailed_Postprocessing.pdf}\n\t\\caption{Detailed description of postprocessing in \\systemName.}\n\t\\label{fig:DetailedDesign_postpro}\n\\end{figure}\n\nThe main function of the post processing block is to upsample the signal so it can be played send out by the DAC at a $fs=\\SI{48000}{\\hertz}$. The interpolation is an integer of 10, followed up by a lowpass filter. The DAC will send out the final signal which shoulde have a new frequency now compared to the input signal. \\fxnote{Move this to an appendix}\n\n\n\\FloatBarrier", "meta": {"hexsha": "c9875ee41d3772cfa433a6c6618540c0581ab385", "size": 3227, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Report/Report/Music/design.tex", "max_stars_repo_name": "lsangild/ETISB", "max_stars_repo_head_hexsha": "7ed401e1a9d7b34120f953d1afe5266d57f9e7a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Report/Report/Music/design.tex", "max_issues_repo_name": "lsangild/ETISB", "max_issues_repo_head_hexsha": "7ed401e1a9d7b34120f953d1afe5266d57f9e7a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Report/Report/Music/design.tex", "max_forks_repo_name": "lsangild/ETISB", "max_forks_repo_head_hexsha": "7ed401e1a9d7b34120f953d1afe5266d57f9e7a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 94.9117647059, "max_line_length": 1005, "alphanum_fraction": 0.7874186551, "num_tokens": 800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.3136518723240615}}
{"text": "% !TeX root = ../solution.tex\n\n\\hypertarget{he22.teaser}{%\n\\chapter{Teaser Challenge}\\label{hv22.teaser}}\n\n\\begin{figure}\n\t\\includegraphics[width=100mm]{00teaser/banner.jpg}\n\\end{figure}\n\n\\begin{center}\nCraCC this, you HAXXOR!\n\n\\verb+a4a9fefcfefeb7b8fff8bfa9bee1a8fca2ffedb1+\n\\end{center}\n\n\\section{Solution}\\label{he22.01-solution}\n\nHAXXOR $\\rightarrow$ XOR encoding\n\n\\noindent CraCC hints at 0xCC as the key to XOR with\n\n\\begin{minted}{python}\nmsg = 'a4a9fefcfefeb7b8fff8bfa9bee1a8fca2ffedb1'\nres = ''\nfor i in range(len(msg)//2):\n    s = int(msg[2*i:2*i+2],16)\n    c = s ^ 0xcc\n    res += chr(c)\n    print(f'{s} -> {c} %s'%chr(c)) \nprint(res)\n\\end{minted}\n\n\\noindent \\verb+he2022{t34ser-d0n3!}+.\n\n", "meta": {"hexsha": "eb47349229ddcfca48a484ba3850b9844def8361", "size": 700, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "HackyEaster/he2022/00teaser/teaser.tex", "max_stars_repo_name": "tbrup/ctf-writeups", "max_stars_repo_head_hexsha": "dfac11abb3051af657ed3384c3c389c14a40c10e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HackyEaster/he2022/00teaser/teaser.tex", "max_issues_repo_name": "tbrup/ctf-writeups", "max_issues_repo_head_hexsha": "dfac11abb3051af657ed3384c3c389c14a40c10e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HackyEaster/he2022/00teaser/teaser.tex", "max_forks_repo_name": "tbrup/ctf-writeups", "max_forks_repo_head_hexsha": "dfac11abb3051af657ed3384c3c389c14a40c10e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0, "max_line_length": 52, "alphanum_fraction": 0.6971428571, "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.31365187232406144}}
{"text": "\\subsection{\\acrshort{nrpa}, a story of code}%\n\\label{sub:nrpa_a_story_of_code}\n\nAs seen in the playout (see section~\\ref{sub:nrpa_playout}) and the adapt (see section~\\ref{sub:nrpa_adapt}), the \\gls{nrpa} uses a function named \\textit{code}.\nThis function is essential because it changes what the algorithm learns entirely.\nThis function takes an action (and can also take a state) and returns a number corresponding to it.\nIt can be viewed as an hash function for moves.\nIt helps to store the weight inside the policy that can be seen as a list.\nThe size of this list will be the number of code possible but that is just one way to see it or implement it.\n\nWhen we say that it changes the knowledge acquired by the \\gls{nrpa} it is undertone.\nLet's consider the \\gls{lmp} as defined in section~{sub:mdp} and examine two way of coding the actions.\n\n\\[\n    code(a)= \n    \\begin{cases}\n        1 & \\text{if } a = left\\\\\n        0 & \\text{otherwise }\n    \\end{cases}\n\\]\n\nIn this first case, the code is produces from the action itself.\nGoing to the left is 1 and going to the right is 0.\nThis means that there is only 2 codes possible; therefore, their are two weights to adjust.\nThe policy will be binary and only learn to go left or right.\nThis is very adapted to the problem since the question does not change according to the number of turn already played.\n\n\\[\n    code(a, s=(r, d)) = d*2 + \n    \\begin{cases}\n        1 & \\text{if } a = left\\\\\n        0 & \\text{otherwise }\n    \\end{cases}\n\\]\n\nIn this second case, there are \\(2 \\times N\\) codes and the same number of weight to adjust.\nThis means that, at each level of deepness, the algorithm will wonder if it is better to go left or right.\nIf he knows that, at the root level, it is always better to go left, he does not apply it on other levels.\nThis is a real problem in the modelization of the problem since it does not capture well what the algorithm have to learn.\nThat said, even with this version, it probably find the best solution but in more time.\n\nThe codes are an essential part of the \\gls{nrpa} since they modelize the knowledge the algorithm is acquiring.\nBad codes will result in bad learning and bad learning results in bad results.\n", "meta": {"hexsha": "946ad61a4805992d840489222fdcc3e4a7ae236f", "size": 2206, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "documents/report/src/sections/nrpa/subs/code.tex", "max_stars_repo_name": "XanX3601/stochastic_mcts_optimization", "max_stars_repo_head_hexsha": "743ef3df090427750fee55fd69d7646a88d5946a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "documents/report/src/sections/nrpa/subs/code.tex", "max_issues_repo_name": "XanX3601/stochastic_mcts_optimization", "max_issues_repo_head_hexsha": "743ef3df090427750fee55fd69d7646a88d5946a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "documents/report/src/sections/nrpa/subs/code.tex", "max_forks_repo_name": "XanX3601/stochastic_mcts_optimization", "max_forks_repo_head_hexsha": "743ef3df090427750fee55fd69d7646a88d5946a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.1363636364, "max_line_length": 161, "alphanum_fraction": 0.7343608341, "num_tokens": 566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.31365187232406144}}
{"text": "\\chapter{Roll the dice!}\nWorld of Artograch - in spite of being intended more to serve as the base of CRPG adaptations, rather than a tabletop RPG meant to be played among friends - is, at the end of the day, still a tabletop RPG, as such, it is only expected that it will rely on dice-rolls to determine things. Events will be generally detailed in percentages rather than dice rolls by default, but game masters are expected to adapt this to dice rolls: for example, if we state that character has 50\\% of succeeding at a task, the game master must ask the character's controller to roll the dice. If it's a 20-sided dice, they must roll 10 or greater, if it's a 6-sided dice, they must roll 3 or greater, and so on. House rules. Nevertheless, for the sake of convenience, sometimes, dice measurements will be also given.\n", "meta": {"hexsha": "8f1170f093e65fbdcf2db66c73cba205d4528b26", "size": 824, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters.d.tex/02-RollTheDice.tex", "max_stars_repo_name": "Metalhead33-Foundation/Ways-of-Darkness-Tabletop", "max_stars_repo_head_hexsha": "1c832ec305794e60d998213cdeadb8045228163a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters.d.tex/02-RollTheDice.tex", "max_issues_repo_name": "Metalhead33-Foundation/Ways-of-Darkness-Tabletop", "max_issues_repo_head_hexsha": "1c832ec305794e60d998213cdeadb8045228163a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters.d.tex/02-RollTheDice.tex", "max_forks_repo_name": "Metalhead33-Foundation/Ways-of-Darkness-Tabletop", "max_forks_repo_head_hexsha": "1c832ec305794e60d998213cdeadb8045228163a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 274.6666666667, "max_line_length": 798, "alphanum_fraction": 0.7766990291, "num_tokens": 192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.3135726817720545}}
{"text": "% !TEX root=/home/tavant/these/manuscript/src/manuscript.tex\n\n\\section{Electron-induced secondary electron emission}\n\\label{sec-seemodel}\nWhen an incident electron reaches the wall material, several scenarii are possible, as described in \\citet{villemant2018}\n\\begin{enumerate}\n  \\item Elastic reflection\\string: the electron encounters only elastic collision with the material, hence its energy is constant. However, its reflection is not necessary specular.\n  \\item Inelastic reflection\\string: the electron looses some of its energy to the material before returning to the plasma.\n  \\item Secondary electron emission\\string: the energy of the primary electron is enough to extract one or more electrons from the material.\n  \\item No emission, the electron is absorbed by the wall.\n\\end{enumerate}\n\nThe probability \\proba{}  that one event happens instead of another depends predominantly on the particle energy, and weakly on its  impact angle.\nConcerning the mean flux of electron incident and emitted, we use the mean emission rate, or yield, \\rate\n\\begin{equation*} \\label{eq-ratedifinition}\n  \\rate = \\frac{\\Gamma_{e, \\rm secondary}}{\\Gamma_{e, \\rm primary}}\n\\end{equation*}\nwhich can be developed using the distribution function to \n\\begin{equation} \n  \\label{eq-ratedifinition_evdf}\n  \\rate = \\frac{\\iiint_{\\Omega} v_x \\proba(\\vect{v_e}) f(\\vect{v_e}) d^3v}{\\iiint_{\\Omega} v_x  f(\\vect{v_e}) d^3v}\n\\end{equation}\nwith $\\Omega$ the ensemble of $\\vect{v_e}$ directed towards the wall\\string: $\\vect{v_e} \\cdot \\vect{n} > 0$, with $\\vect{n} $ the unit vector normal to and towards the wall.\n\n\\subsection{Models of emission } \\label{subsec-seemodels}\nSeveral models can be used to describe the electron emission.\n\n\\paragraph{Monte Carlo models} are the most realistic.\n They are based on the computation of the trajectory of the electrons through the material, during which the electron can encounter several interactions with the material.\n Each interaction can modify the electron direction, energy, and generate new electrons.\n Several models have been proposed, as \\citet{furman2002,pierron2017}.\n These models allow a precise characterization of the processes, but depend on a large number of parameters difficult to obtain due to the lack of experimental data.\n \n\\paragraph{Analytical models} provide a simplified description of the rate of emission.\nTheir complexity depends on the accuracy desired.\nThe most largely used are the models of \\citet{vaughan1989,barral2003a,sydorenko2006b}.\n\nIn this work, we are interested only in representing qualitatively the electron emission.\nMoreover, \\citet{croes2017} showed that changing the model used does not affect significantly the results. \nHence, we will use the model of \\citet{barral2003a} for its simplicity.\n\n\\subsection{Barral electron emission model}\n\\label{sec-modelused}\n\nThe emission model used follows a linear-saturated law for the probability of emission with three parameters. \nIt describes the total emission corresponding to the sum of the elastic and inelastic backscattering and the secondary electron emission.\n\\begin{equation} \\label{eq-proba_barral}\n  \\proba(\\ek) = \n  \\begin{cases}\n    \\proba_0 + (1 - \\proba_0) \\frac{\\ek}{\\crover}   &\\text{ if } \\ek <  \\ek_{\\max} \\\\\n    \\probamax &\\text{ if } \\ek \\geq \\ek_{\\max}\n  \\end{cases}\n\\end{equation}\nwhere $\\ek$ is the kinetic energy of the incoming electron, $\\proba_0$ is the asymptotic probability of emission at null energy, $\\crover$ is the crossover energy above which the probability of emission is higher than one, \\probamax{} is the maximum probability and $\\ek_{\\max}= \\frac{\\probamax - \\proba_0}{1 - \\proba_0} \\crover $ is the minimum energy for which $\\rate = \\probamax$.\n\\Cref{eq-proba_barral} is illustrated in \\Cref{fig-modelbarral}.\n\n\\begin{figure}[hbt]\n  \\centering\n  \\includegraphics[width=\\defaultwidth]{barral}\n  \\caption{Linear-saturated emission model from \\citet{barral2003a}.}\n  \\label{fig-modelbarral}\n\\end{figure}\n\n We suppose that all the electrons are isotropically emitted following a Maxwellian flux distribution function of temperature $\\Tsee$.\n The parameters $\\proba_0$,  $\\probamax$ and $\\crover$ can be obtained from experiments. \n \\Cref{tab-seeparames} shows the crossover energy and the  probability of emission at energy null for different materials.\n The value of $\\proba_0$ is always close to $0.5$, but $\\crover$ can vary from 18 to 305 V.\n Hence, in the following parametric studies, $\\proba_0$ will be kept at 0.5 while we vary $\\crover$ from low values, corresponding to highly emissive materials, to high values, representing less emissive materials.\n \n \\begin{table}[hbt]\n   \\ra{1.3}\n   \\centering\n   \\caption{Emission parameters for different materials, from \\citet{barral2003a}.}\n   \\label{tab-seeparames}\n   \\begin{tabular}{@{}lll@{}} \\toprule\n   Material & $\\crover$ (V)& $\\proba_0$ \\\\ \\midrule\n   BN-SiO$_2$ & 53 & 0.45 \\\\ \n   Al$_2$O$_3$ & 18  & 0.57 \\\\ \n   SiC     &  43  &0.69  \\\\\n   Graphite & 305  & 0.40 \\\\ \n   \\bottomrule\n   \\end{tabular}\n \\end{table}\n \n Since the model used describes both the reflected and true secondary electron emission, we will use the general name \\emph{electron emission}  to refer to the flux of electrons emitted by the walls towards the plasma.\n In contrast, the electrons reaching the plasma are referred to as the \\emph{primary electrons}.\n", "meta": {"hexsha": "22779b12d88bd99c5576ce08c14334d159b26a6c", "size": 5353, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/Chapitre1/15_SEE.tex", "max_stars_repo_name": "antoinetavant/PhD_thesis_manuscript", "max_stars_repo_head_hexsha": "1fdaf99356f75abc488edf1f30b5dd65f22bcdca", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Chapitre1/15_SEE.tex", "max_issues_repo_name": "antoinetavant/PhD_thesis_manuscript", "max_issues_repo_head_hexsha": "1fdaf99356f75abc488edf1f30b5dd65f22bcdca", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Chapitre1/15_SEE.tex", "max_forks_repo_name": "antoinetavant/PhD_thesis_manuscript", "max_forks_repo_head_hexsha": "1fdaf99356f75abc488edf1f30b5dd65f22bcdca", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 61.5287356322, "max_line_length": 383, "alphanum_fraction": 0.7580795815, "num_tokens": 1440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.31353900591534367}}
{"text": "\\chapter{De-Entanglement}\n\n\\section{How to accomplish de-entanglement?}\n\nThe most popular approach to obtain isolation of factors of variation in neural models is by employing stochastic random variables. This approach provides flexibility to jointly train the latent representations as well as the downstream  network. It has been observed that the latent representations resemble disentangled representations under certain conditions \\citep{isolating_sources_betavae, understanding_disentanglement_betavae,structured_disentangled_representations,hyperprior_disentanglement}. Note that although obtaining such degenerate representations is considered typical, it is not the only manifestation: it also manifests as continuous representations\\citep{ravanelli2018interpretablesyncnet} and other abstract phenomena(e.g. grounding). I argue that explicitly controlling what and how much gets de-entangled \\citep{understanding_disentanglement_betavae} is better than implicit disentanglement as is followed today\\citep{locatello2018challenging}. I identify four ways to computationally control de-entanglement in encoder decoder models\n\n\\begin{itemize}\n    \\item (1) By employing suitable priors about task or data distribution\n    \\item (2) By incorporating additional adversarial or multi task objectives within the model\n    \\item (3) By utilizing a different divergence objective\n    \\item (4) By employing an alternative formulation of probability density estimation\n\\end{itemize}\n\nI will  expand on each of these in the following chapters, providing one task from language technologies as a case study. \n\n\n\nI posit that designing learning paradigms such that we explicitly control de-entanglement of relevant factors of variation while marginalizing the nuisance factors of variation leads to massive improvements. Such an approach, I claim, leads to further advantages in the context of both generative processes: in terms of generation of novel content and discriminative processes: in terms of robustness of such models to noise and attacks. Let us consider a typical deep learning architecture such as AlexNet\\citep{alexnet}. It is characterized by a series of convolutional layers (feature extraction module) followed by a pooling layer and a SoftMax layer(classification module). Note that while I mention AlexNet as an example, this abstraction can be extended to most sequence to sequence architectures with encoder as feature extraction module and decoder as the classification module\\citep{tutorial_dataaugmentation} across modalities and tasks. It can be shown that the pooling layer acts as information bottleneck\\citep{tishby2000information} module in such architectures. I point out\\citep{variational_attention_rsk} that in case of conventional Seq2Seq architectures deployed today, attention plays the role of information bottleneck module regulating the amount of information being utilized by the decoder. In \\citep{variational_attention_rsk,vyas2019learning} I show that this module controls optimization in encoder decoder models leading to (1) Disentanglement of Causal Factors of variation in the data distribution (2) Marginalization of nuisance factors of variation from the input distribution. In case of models that employ stochasticity, two more effects can be observed : (a) Posterior collapse or Degeneration due to powerful decoders and (b) Loss of output fidelity due to finite capacity decoders. In current architectures, marginalization and disentanglement are realized implicitly and often lead to (a) and (b) when deployed in practise.\n\nThe most popular approach to obtain isolation of factors of variation in neural models is by employing stochastic random variables. This approach provides flexibility to jointly train the latent representations as well as the downstream  network. It has been observed that the latent representations resemble disentangled representations under certain conditions \\citep{isolating_sources_betavae, understanding_disentanglement_betavae,structured_disentangled_representations,hyperprior_disentanglement}. Note that although obtaining such degenerate representations is considered typical, it is not the only manifestation: it also manifests as continuous representations\\citep{ravanelli2018interpretablesyncnet} and other abstract phenomena(e.g. grounding). I argue that explicitly controlling what and how much gets de-entangled \\citep{understanding_disentanglement_betavae} is better than implicit disentanglement as is followed today\\citep{locatello2018challenging}. I identify four ways to computationally control de-entanglement in encoder decoder models\n\n\\begin{itemize}\n    \\item (1) By employing suitable priors about task or data distribution\n    \\item (2) By incorporating additional adversarial or multi task objectives within the model\n    \\item (3) By utilizing a different divergence objective\n    \\item (4) By employing an alternative formulation of probability density estimation\n\\end{itemize}\n\n\n\n\n\n\n\\subsection{Case for Controlled De-Entanglement}\n\nI believe that complete disentanglement of input data into its independent causal factors of variation is not fully useful. A more attractive option is to control what and how much gets de-entangled in a a task dependent manner. It has to be noted that given a particular downstream task, some causal factors of variation might not be relevant, in which case modeling them would be unnecessary. Let us consider a data distribution X which consists of class examples $\\{ x_1, x_2...,x_n \\}$, where each $x_i$ is described by attribute-set $(a,b,c)$. The prior distribution of X can be represented by a parameteric function g such that g maximizes the likelihood of X over the set of its attributes:\n\n\\begin{equation}\nP_{\\omega}(X) = g_{\\omega}(a,b,c)\n\\end{equation}\n\nNote that the attribute-set can either contain individual entities or the relationships between them or both.  To illustrate this, let us consider a toy-example where we build a binary classifier to predict if a given integer triplet is a Pythagorean triplet. Pythagorean triplets are a triplet of numbers that follow Pythagoras Theorem such as $\\{3,4,5\\}$ and $\\{5,12,13 \\}$. In this task, the attribute-set consists of the relationship between the first two-elements of the triplet. If the model is able to discover this attribute, it can generalize for any given numbers. %Another example is to build a generative model for predicting the next number in the Fibonacci series. The attribute-set consists of the relation between the last two elements on the input list. \nHowever, if we have a more complicated task like building a classifier for MNIST digits, then the attribute-set has multiple first and second order relations like brush strokes, shape of the digits etc. The success of modelling $P_{\\omega}(X)$, and ultimately the success on the downstream task, relies on how well can the model isolate these individual attributes from the observed data $X_{t}$. This isolation ability becomes even more important in case we want to regenerate the digits using a generative model. Mathematically, let us consider the posterior probability of a training instance $x_1$ expressed as \n\n\n\\begin{equation}\nP_{\\theta}(x_1) = f_{\\theta}(x_1)\n\\end{equation}\n\nwhere \\textit{f} denotes arbitrary function and $\\theta$ denotes the parametric family used to model the distribution $X$. It can be seen that compositionality over an unseen training instant $x_{new}$ would be possible if \\textit{f} is related to \\textit{g}. In other words, \\textit{f} needs to intuitively have some information about the latent causal factors of variation that generated $X$ in the first place. In such scenarios, the test instance can be appropriately expressed as \n\n\\begin{equation}\nP_{\\theta}(x_{new}) = h(a,k(b,c))\n\\end{equation}\n\nwhere h and k can be a novel combination of functions that embed these attributes in the manifold of original distribution of $X$. Not tracking the relevant factors of variation typically leads to model memorizing only the surface level associations leading to mode collapse and lack of diversity in the generated outputs. On the other hand, explicitly caring about the factors of variation can be seen as a way of incorporating inductive bias into the model and has the potential to avoid such pitfalls. \n \n\\iffalse \n\\subsection{Inductive Bias}\nInductive bias typically refers to the set of constraints applied on the model that help restrict the hypothesis space apriori based on the background knowledge about the distribution of data. Having such priors helps the model reach the solution faster. For instance, consider the prior of linearity imposed on a curve fittign task between two points in cartesian co ordinates. Having such prior extremely simplifies the task since there is only one line through two points while there are infinitely many curves. Not having any sort of priors about the data distribution might also lead to uninterpretible and black box results even if the solution is infact correct. While this might be okay in the beginning, to make the technology closer to acceptance, we need models that are interpretible atleast conditionally. Not having any sort of inductive biases might lead to model memorizing or just learning surface level associations. This leads to the model becoming vulnerable to adversarial attacks. Voice impersonation attacks for example can be very serious. Additionally, having such priors in place also acts as a probe to let us diagnose the performance of the model when it fails. This we believe is a more principled way towards building and debugging reliable systems as opposed to post hoc fixes based on the errors made by such models. Community today is two paced: either based on end to end neural approaches where the aim is to discover everything through data or based on hand crafted features. We believe that a far more interesting approach is to take a leaf out of research from epigenetics that shows biology builds both by nature as well as nurture and not absolute. Specifically, we believe going forward it is important to design techniques that have quirks from the nature - prior knowledge incorporated into the nurture - end to end approaches. In this paper, we perform a case study on a manifestation of speech generation, voice conversion, and present approaches that enable us to incorporate inductive biases into the model.\n\\fi\n\n\n\\begin{center}\n\\begin{table}\n\\caption{Implicit Realization of information bottleneck in popular deep learning mechanisms}\n\\begin{tabular}{  | c | c | c| }\n\\hline\n\\textbf{Architecture} & \\textbf{Manifestation of Information Bottleneck} & \\textbf{Type of Bottleneck} \\\\\n\\hline\nAlexNet & Pooling  & Spatial \\\\\n \\hline \nAttention & Activation & Temporal\\\\\n\\hline\nVAE & Priors & Spatio temporal\\\\\n\\hline\nNeural Module Networks & Softmax over Modules & Spatial \\\\\n\\hline\nLISA & Linguistic Priors & Temporal\\\\\n\\hline\nBERT & Masking  & Spatio temporal\\\\ \n\\hline\nXLNet & Permutation & Spatio temporal \\\\\n \\hline\n\\end{tabular}\n\n\\end{table}\n\\label{Message}\n\\end{center}\n\n\n\\subsection{Implicit De-Entanglement in Seq2Seq Models: Deterministic Attention vs Stochastic Attention}\n\nI will illustrate this sub section with a typical generative model of speech: Text to Speech. Consider that we are interested in building a code mixed version: a model that can accomodate two languages in a single utterance. Let us also consider a speech corpus $X$ consisting of languages $\\{ l_1,...,l_n \\}$, where each $l_i$ might comprise of multiple speakers.  Let \\textit{$y_1$,...,$y_n$} denote acoustic frames in the target sequence \\textit{y}  while \\textit{$x_1$,...,$x_n$} denote the encoded text sequence \\textit{x} from one of the languages. A typical attention based encoder decoder network such as Tacotron\\citep{tacotron_original} factorizes the joint probability of acoustic frames as product of conditional probabilities. Mathematically, this can be shown as below:\n\n\\begin{equation}\nP_\\theta(y|x) = \\Pi_{ t=1}^{t=n} P(y_t | x_1...x_m,s_t) \n\\end{equation} \nwhere $s_t$ is a decoder state summarizing $y_1$,...$y_{t-1}$. Parameters $\\theta$ of the model are set by maximizing either the log likelihood of training examples or the divergence between predicted and true target distributions. At each time step t in these models, an attention variable $a_t$ is used to denote which encoded  state of \\textbf{$x_1...x_m$} aligns with \\textit{$y_t$}. The most common form of attention used is soft attention, a convex combination from encoded representation of input text. It has to be noted that soft attention in such scenarios is essentially a latent deterministic variable that computes an expectation over the alignment between input and output sequences. Empirically, soft attention provides surprisingly good alignment often  correlating with human intuitions. Having said that, to synthesize speech from different languages at test time, the generative process needs to disentangle appropriate individual language attributes from observed data $X_{obs}$ and also compose them to form a coherent utterance in the voice of desired speaker. However, presence of deterministic alignment method limits the ability of models to generalize to such scenario.\n\n%Incorporating latent alignment into Seq2Seq models by injecting stochastic latent variables allows to efficiently marginalize the likelihood of data distribution. \n\nOn the other hand, variational attention\\citep{latentalignment_variationalattention} provides a mechanism to factorize this alignment and mediate the generative process of $y$ through a stochastic variable $z$. In addition, both soft and hard attention mechanisms can be shown as special cases of ELBO\\citep{latentalignment_variationalattention}. Therefore, incorporating latent stochastic variables allows us to directly optimize ELBO. In this context, model parameters are set by maximizing the log marginal likelihood of the training samples. But direct maximization of this marginal in the presence of latent variable  is often difficult due to expectation involved. To address this, a recognition network $q$ is employed to approximate the posterior probability using reparameterization. It is interesting to note that the encoder in a deterministic Seq2Seq network functions as the recognition network in latent stochastic variable models and is incentivized to search over variational distributions to improve ELBO. Intuitively, the lower bound is tight when the inferred variational distribution is closer to the true posterior of the data. This has a sense of grounding in our understanding of the task as well. Perhaps there are a set of universal phonemes, around 120, which should be enable us to speak in any language subject to the phonotactic constraints of the language. Having such prior information greatly reduces the model size as opposed to naively using a combination of all phones from all the languages to build a polyglot model. \n\n\n\\subsection{Analysis of role of priors in Latent Stochastic Models}\n\\label{analysis}\n\n\n\nThe choice of priors plays a significant role in optimization within latent stochastic models. In this subsection, we present an analysis to show that priors control the disentanglement of causal factors of variation in such models. Let us consider the ELBO being optimized in a VAE:\n\n\\begin{equation}\nE_{q_{\\phi}(z|x,c)}[log p_{\\theta} (x|c,z)] -  |D_{KL}(q_{\\phi} (z|x,c) || p_{\\theta} (z|c))| \n\\end{equation}\n\nwhere the first term is the reconstruction error while the second is the divergence between approximate and true posteriors. Here are the four phenomenon that are manifested due to choices of priors:\n\n(1) \\textit{Disentanglement or Factorization of causal factors of variation} \\\\\nThe KL divergence forces the posterior distribution output by encoder to follow an appropriate prior about the data generation process. Typically, prior space is assumed to be continuous distribution and a unit Gaussian. The global optimum value for the divergence in such cases is 0 and is reached only when both the distributions exactly match each other. Since the prior information about the data generation process typically involves some causal factors of variation of the data, this naturally is assumed to translate to a constraint on the encoder to track such factors. Thus, such models have potential to disentangle or factorize the causal factors of variation in the distribution.\n\n(2) \\textit{Marginalization of Nuisance Factors of Variation} \\\\\nIt has to be noted that during training optimization is performed in expectation over minibatches. Therefore, the expectation of KL divergence can be rewritten as related to the amount of mutual information between the latent representation and the data distribution \\citep{pixelgan_autoencoder}. As this divergence decreases, the amount of information the encoder can place in the latent space also decreases. As a result, encoder is forced to discard some nuisance factors that may not have contributed to the generation of data. Thus, KL divergence also forces the model to marginalize the nuisance variables.\n\n%Thus, the KL divergence forces the encoder network to disentangle the causal factors - akin to the basis vectors - of variation in the data and ignore the nuisance factors that may have contributed to the generation of data. \n\n(3) \\textit{Posterior Collapse due to simple priors} \\\\\nConsider the scenario where the prior is too simplistic, such as the aforementioned unit normal distribution. In such cases, the model is incentivized to force the posterior distribution to closely follow the Gaussian distribution \\citep{lossy_vae}. Typically the decoders in variational models are implemented using universal approximators such as RNNs. In the context of a TTS systems, decoder segment of the acoustic model along with the neural vocoder act as the decoders. Since such decoders are very powerful, they are able to learn or ignore the priors about data distribution themselves and hence marginalize out the latent representation input from the encoder. In other words, the prediction of next sample is based solely on the marginal distribution at the current timestep which can be implemented by learning a dictionary per time step. Therefore, the encoder is no longer forced to track the causal factors of variation in the data. This is referred to as posterior collapse or mode collapse. \n\n(4) \\textit{Loss of output fidelity due to complex priors} \\\\\nA reasonable and intuitive solution to posterior collapse is making the prior space more complex thereby pressurizing the posterior distribution to track the prior space more closely. For instance, \\citep{beta_analysis} attempt to accomplish this by adding a hyperparameter $\\beta$ to promote disentanglement and gradually increasing channel capacity, something that increases loss. However, it has to be noted that simply making the prior distribution arbitrarily complex also perhaps leads to unreasonable constraints on the decoder. For instance, in scenarios that have categorical distribution as their output (tasks such as language modeling, machine translation, image captioning among others) it is unintuitive to assume that the true prior that generates latent distribution is a Gaussian when the likelihood is based on discrete sequential data in such tasks. Having such strong priors directly affects the reconstruction ability in these models.\n\nTherefore, priors in latent stochastic models play a significant role in the optimization and facilitate disentanglement of causal factors of variation on the one hand, as well as help the ability of the model to reconstruct the data distribution on the other. Having this knowledge enables us to engineer various components to tune the model behavior as per our requirements. \n\n\n", "meta": {"hexsha": "4919db5da41f2584bc00bfee09ab9071d251a78a", "size": 19831, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "quarterly_stuff/2020Q2/chapters/deentanglement.tex", "max_stars_repo_name": "saikrishnarallabandi/phdthesis", "max_stars_repo_head_hexsha": "ff0d0f3a6af19695520fe3e74c2cec69806f2f96", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-07-17T17:50:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-01T20:13:21.000Z", "max_issues_repo_path": "quarterly_stuff/2020Q2/chapters/deentanglement.tex", "max_issues_repo_name": "saikrishnarallabandi/phdthesis", "max_issues_repo_head_hexsha": "ff0d0f3a6af19695520fe3e74c2cec69806f2f96", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "quarterly_stuff/2020Q2/chapters/deentanglement.tex", "max_forks_repo_name": "saikrishnarallabandi/phdthesis", "max_forks_repo_head_hexsha": "ff0d0f3a6af19695520fe3e74c2cec69806f2f96", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 145.8161764706, "max_line_length": 2054, "alphanum_fraction": 0.8128183148, "num_tokens": 4136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370308082623216, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.31353900591534367}}
{"text": "\\documentclass[a4paper,12pt]{amsart}\n\\usepackage[utf8]{inputenc}\\usepackage[T1]{fontenc}\n\n\\title[Multi-Agent Deep Deterministic Policy Gradients]{The Tennis environment solved using a Deep Deterministic Policy Gradient algorithm}\n\\author{Julian Wergieluk}\\address{}\\email{julian.wergieluk@risklab.com}\n\\input{preamble}\n\\input{commands}\n\n\\usepackage[url=false,backend=biber]{biblatex}\n\\addbibresource{rl.bib}\n\\addbibresource{ddpg.bib}\n\n\\newcommand{\\stateSpace}{\\mathbb S}\n\\newcommand{\\stateSpaceAlg}{\\mathcal S}\n\\newcommand{\\coffinSpace}{\\Delta}\n\\newcommand{\\actionSpace}{\\mathbb A}\n\\newcommand{\\actionSpaceAlg}{\\mathcal A}\n\\newcommand{\\stateValueFunc}{V}\n\\newcommand{\\actionValueFunc}{Q}\n\\newcommand{\\advantageFunc}{A}\n\\newcommand{\\policy}{\\pi}\n\\newcommand{\\policyLik}{f}\n\\newcommand{\\discountFactor}{\\gamma}\n\\newcommand{\\prob}{\\mathbb P}\n\\newcommand{\\rewardFunc}{\\phi}\n\\newcommand{\\trajectory}{\\tau}\n\\newcommand{\\trajectorySpace}{\\mathbb T}\n\\newcommand{\\startStateDist}{\\rho_0}\n\n\\begin{document}\n\n\\maketitle\n\n\\begin{abstract}\nThis short note provides a concise description of the model architecture and\nlearning algorithms of the agent developed in this project. We also report learning\nperformance of the agent and provide a list of possible future model improvements.\n\\end{abstract}\n\n\\section{Description of the learning algorithm}\n\nFor this problem, we use a standard Deep Deterministic Policy Gradient \nalgorithm (DDPG) and parameterize it in a way to make it suitable for multi-agent\nenvironments.\n\nDeep deterministic policy gradient algorithm is an actor-critic type method\nwith a deterministic actor policy $\\pi$ mapping states from $\\stateSpace$ to\nactions in $\\actionSpace$. During the training, the action-value\nfunction $Q$ is optimized using a standard DQN algorithm as described in\n\\cite{mnih2015humanlevel} employing a replay buffer and a separate target\nnetwork.\n\nThe policy network is trained using a policy gradient derived from the action-value\nfunction approximation. Specifically, the parameter vector $\\theta$ is given as\n$\\theta = (\\theta^{Q}, \\theta^{\\pi})$, where $\\theta^{Q}$ determines $Q$ and\n$\\theta^{\\pi}$ determines $\\pi$. Let $J(\\theta)$ be the cumulative expected \nreward. Then the policy gradient can be approximated by\n\\begin{align*}\n    \\nabla_{\\theta^{\\pi}} J & \\approx\n    \\E \\left[ \\nabla_{a} Q(S_t, \\pi(S_t)) \\nabla_{\\theta^\\pi} \\pi(S_t) \\right].\n\\end{align*}\n\nTo improve the algorithm stability we use soft target updates for the\nparameters of both actor and critic networks, described in\n\\cite{mnih2015humanlevel}, and batch normalization.\n\n\\section{Training analysis}\n\nWe train a DDPG agent for 1900 episodes consisting of at most 1000 time steps\neach. The cumulative reward averaged over 100 episodes reaches the level of\n0.5017 after completing the episode 494. \n\n\\begin{figure}[tb]\n    \\centering\n    \\includegraphics[width=\\textwidth]{{scores}.pdf}\n    \\caption{We train a DDPG agent for 1900 episodes. The ``reward'' curve gives\n        the maximum of individual agents rewards at the end of each episode. The\n        ``average reward'' curve is the rolling mean of the ``reward'' curve\n        calculated over 100 episodes. (For episodes $1,\\cdots, 99$ we use an\n        expanding window.)}\n    \\label{fig:scores}\n\\end{figure}\n\n\\section{Algorithm parametrization}\n\n\\paragraph{The Actor network architecture.} The actor is a feed-forward neural\nnetwork mapping the state of the environment to a deterministic action. The\nnetwork consists of three layers sandwiched with batch normalization. The final\nlayer uses the tanh nonlinearity to produce an action vector in the cube $[-1, 1]^{2}$.\n\n\\verbatiminput{actor-net.txt}\n\n\\paragraph{The Critic network architecture.} The critic is a feed-forward neural \nnetwork approximating the state-action value function $Q$ mapping state-action\npairs to the expected cumulative reward. The critic network consists of two subnetworks: \na one-layer network combined with batch normalization that maps the state to a high-dimensional \nstate representation, and a two-layer network that maps the aforementioned representation\nof the state concatenated with the action vector to the approximation of the state-action\nvalue $Q(s,a)$.\n\n\\verbatiminput{critic-net.txt}\n\nThe list of hyperparameters used by the agent is listed in Table \\ref{tab:hyperparameters}.\n\n\\begin{table}\n%\\centering\n\\caption{List of hyperparameters and their values}\n\\begin{tabular}{|l|l|l|l|}\n    \\hline\nHyperparameter & Variable name & Value \\\\ \n    \\hline \\hline\n    Replay buffer size & \\texttt{BUFFER\\_SIZE} &  2e5 \\\\ \\hline\n    Batch size & \\texttt{BATCH\\_SIZE} &  128  \\\\  \\hline\n    Discount factor ($\\gamma$) & \\texttt{GAMMA} &  0.99 \\\\ \\hline\n    Tau & \\texttt{TAU} & 1e-3 \\\\ \\hline\n    Actor learning rate & \\texttt{LR\\_ACTOR} & 0.001 \\\\ \\hline\n    Critic learning rate & \\texttt{LR\\_CRITIC} & 0.001 \\\\ \\hline\n    Initial value of the & \\texttt{EPSILON} & 1.0 \\\\\n    OU process scaling factor $\\varepsilon$ && \\\\ \\hline\n    OU mean reversion level & & 0.0 \\\\ \\hline\n    OU mean reversion speed & & 0.15 \\\\ \\hline\n    OU volatility (sigma) & & 0.2 \\\\ \\hline\n    Learning frequency & \\texttt{} &  every 5 time steps \\\\ \\hline\n\\end{tabular}\n\\label{tab:hyperparameters}\n\\end{table}\n\n\\section{Ideas for future work}\n\n\\begin{itemize}\n    \\item Use of a real multi-agent reinforcement learning algorithm explicitly taking the\n        non-stationarity of the environment into the account.\n    \\item Actor and critic could use a common network for state processing. \n\\end{itemize}\n\n\\nocite{lillicrap2015continuous}\n\\printbibliography\n\n\\end{document}\n\n% vim: spelllang=en_us:spell:\n", "meta": {"hexsha": "b03013d0f2c2026ce0a536c4410c937aae1e0384", "size": 5632, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/report.tex", "max_stars_repo_name": "jwergieluk/deep_tennis", "max_stars_repo_head_hexsha": "2ef51f3c32f9e18b2403c8c21edfe320763343d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tex/report.tex", "max_issues_repo_name": "jwergieluk/deep_tennis", "max_issues_repo_head_hexsha": "2ef51f3c32f9e18b2403c8c21edfe320763343d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/report.tex", "max_forks_repo_name": "jwergieluk/deep_tennis", "max_forks_repo_head_hexsha": "2ef51f3c32f9e18b2403c8c21edfe320763343d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.661971831, "max_line_length": 139, "alphanum_fraction": 0.7510653409, "num_tokens": 1514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.31350102996167467}}
{"text": "\\documentclass[fleqn, final]{../styles/unmphythesis}\n\\usepackage{../styles/qxd}\n\\renewcommand{\\thechapter}{2}\n%\\newcommand{\\thechapter}{1}\n\n\\makeindex\n\\begin{document}\n\n%<*waveguideinterface>\n\n\\chapter{Atom-waveguide interface}\\label{chap:waveguideinterfaces}\n\\section{Introduction}\nIn this chapter, we review the semiclassical theory of the interaction of the electromagnetic field (treated classically) with an atom trapped near the surface of a waveguide.  We consider the case that only one atom is trapped nearby a waveguide. As will be discussed later, in the dispersive regime, the interaction from many atoms can be treated as a sum of the interactions from all individual atoms. To be specific, for this chapter, we consider the following scenario: a laser beam propagates through a waveguide along the $ z $ direction; an alkali atom (cesium, for example) is trapped at $ \\mathbf{r}_{\\rm atom} =\\mathbf{r}'$ in the evanescent field of the waveguide~\\footnote{We will use the prime ($ ' $) notation to indicate the position of a photon emitter.} and responds to the guided optical field dispersively. In the dynamics, we consider the dispersive phase shift of the light and ignore intensity attenuation in photon detections. Effectively, the presence of the atom outside of the waveguide changes the index of refraction\\index{index of refraction} of the waveguide. \nThe dispersive light shift applies when the saturation parameter is small,\n\\begin{align}\ns=\\frac{\\Omega^2/4}{\\Delta^2+\\Gamma^2/4}\\ll 1,\n\\end{align}\nwhere $ \\Omega $ is the Rabi frequency, $ \\Gamma $ is the spontaneous emission rate of the atom, and $ \\Delta=\\omega_0-\\omega_{eg} $ is the probe detuning from the atomic resonance frequency $ \\omega_{eg} $ as a two-level system with the probe's frequency set to be $ \\omega_0 $. \n\n\\begin{figure}\n\\centering\\makebox[\\textwidth]{\n\\includegraphics[width=0.85\\textwidth]{../media/Figs/NanofiberTrappedAtoms}}\n\\caption[Guided and unguided photon emissions from atoms trapped next to a nanophotonic waveguide.]{Guided and unguided photon emissions from atoms trapped next to a nanophotonic waveguide. In the dispersive regime and when the atoms are placed a few hundred nm away from each other, the effect of the unguided radiation from the atoms can be ignored, and the photon scatterings among atoms are also negligible. For a quantum-measurement--targeted research, we mainly care about how the atomic emissions are modified by the waveguide interface and coupled to the guided modes to be detected at the measurement apparatus. Color contour on the left-hand part is an illustration of one guided mode intensity distribution of an optical nanofiber, which leaks into the free space to interact with atoms and propagates through the fiber. }\\label{fig:trappedatomradiation}\n\\end{figure}\n\nIn this chapter, we will first outline the basic concept of the polarization state of light and introduce the experimental setup to characterize the dispersive light shift interaction based on \\emph{polarization spectroscopy}\\index{polarization spectroscopy}.\nThe theme of this dissertation relates to the atom-light interactions including two aspects: how the light responds to the presence of the atoms, and how the atoms' properties are modified by the light. For the light response aspect, we will derive a general theory in the language of Green's function to formulate the atom-light interaction mainly from the semi-classical perspective where the light is treated as a continuous wave while the atom has discrete level structures. \nFigure~\\ref{fig:trappedatomradiation} shows a nanofiber interface.\n\nFor the atoms' response, we will extend the definition of the polarizability of atoms from a classical oscillator picture to the multiple-level quantum representation, and then introduce the Purcell effect~\\cite{Purcell1946} and derive the modified spontaneous decay rates of atoms in the presence of a waveguide using the Green's function language. \nWe will show that the modifications of spontaneous emissions when atoms are placed at certain distance can be ignored.\nAt the end of this chapter, we will conclude with some geometric explanations on the unique features and advantages of using a nanophotonic waveguide interface to implement atom-light coupling over the free-space interface commonly employed in previous experiments.\n\n\\section{Polarization spectroscopy and dispersive light shift measures}\n\n\\subsection{Measuring the polarization state of light in free space}\n\nThe electric field of a monochromatic plane wave, freely propagating in $ z $ direction, can be expressed in the Cartesian coordinate system by\n\\begin{align}\n\\mathbf{E}(\\br,t) = \\mathbf{E}_x(\\br,t) + \\mathbf{E}_y (\\br,t),\n\\end{align}\nwhere the $ x $ and $ y $ components\n\\begin{subequations}\n\\begin{align}\n\\mathbf{E}_x(\\br,t) &= \\mathcal{E}_{x}\\mathbf{e}_x e^{i(k_0z-\\omega_0 t)},\\\\\n\\mathbf{E}_y(\\br,t) &= \\mathcal{E}_{y}\\mathbf{e}_y e^{i(k_0z-\\omega_0 t)},\n\\end{align}\n\\end{subequations}\nwith complex amplitudes $ \\mathcal{E}_{0x} $ and $ \\mathcal{E}_{0y} $ in the linear polarization basis supported by the direction vectors $ \\mathbf{e}_x $ and $ \\mathbf{e}_y $.\nWe define the propagation direction of the light is along the $ z $ axis. \nDepending on the relative amplitude and phase between the $ x $ and $ y $ components, the polarization state of the light can be \\emph{linear}\\index{polarization!linear polarization}, \\emph{circular}\\index{polarization!circular polarization} and elliptical\\index{polarization!elliptical polarization}.\nFor the convenience of describing the polarization state of light, we define the following polarization bases. \n\nFirst, we define the circular polarization basis by the complex orthogonal unit vectors\n\\begin{align}\\label{eq:epm}\n\\mathbf{e}_{\\pm}=\\frac{1}{\\sqrt{2}}(\\mathbf{e}_x \\pm i\\mathbf{e}_y)\n\\end{align}\nwith properties\n\\begin{align}\n\\mathbf{e}_q\\cdot \\mathbf{e}_{q'}^* &=\\delta_{q,q'}\\\\\n\\mathbf{e}_q^* &=\\mathbf{e}_{-q}\n\\end{align}\nwhere the field has been decomposed into the $ q=\\pm $ components by \n\\begin{align} \n\\mathbf{E}&=\\sum_q \\mathcal{E}_q\\mathbf{e}_q=\\mathcal{E}_+ \\mathbf{e}_+ +\\mathcal{E}_-\\mathbf{e}_-\n\\end{align} \nwith $ \\mathcal{E}_q=\\mathbf{e}_q^*\\cdot \\mathbf{E} $.\nThe circular polarization components can be given by \n\\begin{align}\nE_\\pm(\\br_0,t) &= \\re\\left[\\mathbf{e}_\\pm^* \\cdot \\mathbf{E}\\right] = \\re\\left[\\mathcal{E}_\\pm \\right].\n\\end{align}\nThe $ + $ and $- $ subscripts correspond to the positive and negative helicity of circular polarizations.\n\nSecond, we define another linear polarization basis, namely, the diagonal polarization basis $ (\\mathbf{e}_D,\\mathbf{e}_{\\thickbar{D}}) $ by \n\\begin{subequations}\\label{eq:eDeDbar}\n\\begin{align}\n\\mathbf{e}_D &= \\frac{1}{\\sqrt{2}} (\\mathbf{e}_x+ \\mathbf{e}_y),\\\\\n\\mathbf{e}_{\\thickbar{D}} &= \\frac{1}{\\sqrt{2}} (\\mathbf{e}_y - \\mathbf{e}_x).\n\\end{align}\n\\end{subequations}\nThis linear polarization basis is a $ 45^\\circ $ rotation from the $ (\\mathbf{e}_x,\\mathbf{e}_y) $ basis in the $ xy $ plane. \nOne can decompose the $ \\mathbf{E} $ vector in the diagonal linear polarization basis by $\\mathbf{E} = \\mathcal{E}_D\\mathbf{e}_D + \\mathcal{E}_{\\thickbar{D}}\\mathbf{e}_{\\thickbar{D}}=E_De^{i\\delta_D}\\mathbf{e}_D + E_{\\thickbar{D}}e^{i\\delta_{\\thickbar{D}}}\\mathbf{e}_{\\thickbar{D}} $, where $ \\delta_D $ and $ \\delta_{\\bar{D}} $ are the phases of the two components.\n\nThe polarization state of light can be fully described by the Stokes vector $ \\mathbf{S}= (S_0, S_1,S_2,S_3) $~\\cite{Born1999Principles,Jackson1975}, \nwhere the Stokes vector components can be defined using the real amplitudes of the electric field components in those polarization bases:\n\\begin{subequations}\\label{eq:S_intensitydiff}\n\\begin{align}\nS_0 &= E_H^2+E_V^2 = E_+^2+E_-^2 = E_D^2+E_{\\thickbar{D}}^2,\\\\\nS_1 &= E_H^2-E_V^2,\\\\\nS_2 &= E_D^2-E_{\\thickbar{D}}^2,\\\\\nS_3 &= E_+^2-E_-^2. %=E_L^2-E_R^2\n\\end{align}\n\\end{subequations}\nAbove, we have replaced $ x\\rightarrow H $ and $ y\\rightarrow V $.\nGiven that $ E_i^2 (i=H,V,L,R,D,\\thickbar{D})$ are intensity components proportional to the photon fluxes of the linear and circular polarization components, $ S_0 $ is proportional to the total flux of the light, $ S_1 $ is proportional to the photon flux difference between the $ x $- and $ y $-polarization components, $ S_2 $ is proportional to the photon flux difference of the $ D $- and $ \\thickbar{D} $-polarization components, and $ S_3 $ is proportional to the photon flux difference of the two circular-polarization components of the light. \nWe summarize more details of the polarization state of light and properties of Stokes vectors in Appendix~\\ref{chap:polarizationstokesvectors} for your reference.\n\nIn experiments, one can use waveplates and beam splitters to decompose field components in a given polarization basis, and use a pair of photon detectors to measure the photon flux of the corresponding orthogonal polarization components.\nIf we know the total power or intensity of the light, by measuring the photon flux difference in different polarization bases, one can find the normalized Stokes vector components and hence the polarization state of the light. \nThis defines the \\emph{polarization spectroscopy technique}\\index{polarization spectroscopy}~\\cite{Deutsch2010a,Salvail2013}.\nThe Stokes vector components of the light uniquely map the polarization state to a vector on the \\Poincare sphere (see Fig.~\\ref{fig:Poincaresphere}).\n\n\\begin{figure}[!tpb] % Poincare sphere.\n   \\centering\\makebox[\\textwidth]{\n   %\\includegraphics[width=0.55\\textwidth]{../media/Figs/poincaresphere_initialS1_Faradayrot_crystal}}\n   \\begin{minipage}[h]{\\linewidth}\n    %\\begin{tabular}{*{2}{b{0.2\\textwidth-2\\tabcolsep}}}\n     \\subfloat[h][]{\n       %\\input{fig/nanofiber_peakxi_rp_NA2500.tex}\n       \\includegraphics[width=0.4\\linewidth]{../media/Figs/poincaresphere_initialS2_birefringencerot_crystal}\n       \\label{fig:poincaresphere_initialS2_birefringencerot_crystal}\n       }\n       \\hfill\n     \\subfloat[h][]{\n         \\label{fig:poincaresphere_initialS2_Faradayrot_crystal}\n         \\includegraphics[width=0.4\\linewidth]{../media/Figs/poincaresphere_initialS2_Faradayrot_crystal}\n         %\\input{fig/nanofiber_C1_y.tex}\n         }\n   \\end{minipage}}\n   \\caption[Birefringence and Faraday rotations of the polarization state of light represented on the \\Poincare sphere.]{Birefringence (a) and Faraday (b) rotations of the polarization state of light represented on the \\Poincare sphere. A state of polarization of light can be represented as a vector $ \\mathbf{S}=(S_0,S_1,S_2,S_3) $ with the Stokes parameter $ S_0 $ defining the radius of the sphere. \n   $ S_1 $, $ S_2 $ and $ S_3 $ directions correspond to a horizontal-linear ($ H $), diagonal-linear ($ D $) and circular ($ R $, with positive helicity) polarization states of light. \n   We consider a polarization state initially represented by the $ S_2 $ vector. \n   (a) If the Stokes vector rotes around $ S_1 $ or other linear-polarization axis by some angle $ \\varphi $, we call this rotation as a birefringence rotation and the polarization state becomes elliptical afterwards. \n   (b) If the Stokes vector rotates about $ S_3 $ axis on the equator by some angle $ \\varphi $, we call this a Faraday rotation and the helicity of the polarization state remains. \n   }\n   \\label{fig:Poincaresphere}\n\\end{figure}\n\nFor a completely polarized light\\footnote{ The Stokes parameters of a partially polarized light satisfy $ S_0^2>S_1^2+S_2^2+S_3^2 $. For ``natural light\" or completely unpolarized light, the Stokes parameters satisfy $ S_1=S_2=S_3=0 $. Such, the degree of polarization is defined by $ R=\\frac{\\sqrt{S_1^2+S_2^2+S_3^2}}{S_0} \\le 1$. Throughout this dissertation work, the degree of polarization is not our concern, and we assume that the length of Stokes vectors are properly normalized.}, the Stokes parameters satisfy~\\cite{Born1999Principles}\n\\begin{align}\nS_0^2=S_1^2+S_2^2+S_3^2,\n\\end{align}\nfixing one degree of freedom of the Stokes vectors. That leaves three independent variables to be specified to fully describe the polarization state of a light.\nFor example, in the linear polarization basis, the real amplitudes $ E_x $, $ E_y $ and the relative phase $ \\delta_x-\\delta_y $ uniquely define the polarization state of the light.\nThe phase difference between the two linear components of the field, $ \\phi=\\delta_x-\\delta_y $, determines the helicity. \nThe amplitudes of the two field components determine the polarization magnitude and the polarization angle from the $ x $ axis~\\cite{Jackson1975}. \nSimilar rules can be found for using other polarization representation bases at large~\\cite{Mecozzi2011Unified}. \nIn real space, the trace of the light's polarization vector projected onto the plane perpendicular to the propagation direction is an ellipse, in general. \nOn the \\Poincare sphere, $ (S_1,S_2,S_3) $ can be specified by the orientation angle $2 \\Psi \\,(0\\le \\Psi \\le \\pi) $ rotated from the $ S_1 $-$ S_3 $ plane, and another angle $ 2\\Theta \\,(-\\frac{\\pi}{4}\\le \\Theta \\le \\frac{\\pi}{4}) $ rotated from the $ S_1 $-$ S_2 $ plane on the \\Poincare sphere. \nThat is~\\cite{Born1999Principles}\n\\begin{align}\nS_1 &= S_0\\cos(2\\Theta)\\cos(2\\Psi)\\\\\nS_2 &= S_0\\cos(2\\Theta)\\sin(2\\Psi)\\\\\nS_3 &= S_0\\sin(2\\Theta).\n\\end{align}\nThe factor of 2 reflects the symmetry of polarization. For example, a linear polarization with an oscillation vector along the positive $ x $ direction is the same as that along the negative $ x $ direction. \nGiven that the trace of the electric field vector projected onto the transverse plane perpendicular to the light's propagation direction, $ z $ axis, is an ellipse in general, one can prove that $ \\Theta $ and $ \\Psi $ are associated with the ratio and orientation of the major and minor axes of the ellipse of the light vector's trace in real space~\\cite{Born1999Principles}.\n\nWhen the polarization magnitude $S_0$ is fixed, we only need two free variables $ \\Theta $ and $ \\Psi $ to specify a state of a completely polarized light. On the \\Poincare sphere, one can specify a state of polarization from a given initial state by two consecutive rotations around two orthogonal axes. \nThe rotation around the $ S_1 $, $ S_2 $ or an arbitrary linear polarization axis is physically generated by the \\emph{birefringence effect}\\index{birefringence effect}.\nThe rotation around the $ S_3 $ axis is generated by the \\emph{Faraday effect}\\index{Faraday effect} (see Fig.~\\ref{fig:polarizationspectroscopy}). \nWith these two polarization transformation effects, one can generate an arbitrary polarization state of light from an initial state. \n\n\\subsection{Polarization spectroscopy on waveguide interfaces}\nNow, we turn to the atom-light interface with nanophotonic waveguides. \nWe assume that a waveguide is designed so that the polarization of a transverse light beam in free space can be adiabatically coupled to a unique mode of the waveguide when the light travels through the waveguide. \nWhen the light exits the waveguide, the mode of the waveguide can again adiabatically transfers to a unique polarization state of a transverse light in free space~\\cite{Nayak2007}. \nThe adiabatic connection between the light's polarization states in free space and the modes in the waveguide region applies identically to the processes of incidence to and exiting from the waveguide. \nWe also assume that the dispersive and distortion effects solely due to the waveguide have been compensated before the polarization state measurement or can be extracted out from the measurement result so that we can focus on the effects caused by atom-light interaction in the nanophotonic waveguide region. \nWe label the waveguide mode by the polarization state of the free-space light to which the mode is adiabatically connected. \nFor instance, an $ H $ mode of a nanofiber indicates the mode adiabatically connected to a linearly polarized incident light with the polarization direction along the $ x $ or $ H $ axis. To study how the atom-light interaction changes the polarization state of the light, one could simply measure the state of light in the free space, and hence the same method of polarization spectroscopy technique can be applied to the waveguide platform. A typical polarization spectroscopy experimental setup is illustrated in Fig.~\\ref{fig:polarizationspectroscopy}.\n\n\\begin{figure}[ht] % Poincare sphere.\n   \\centering\\makebox[\\textwidth]{\n   \\includegraphics[width=0.85\\textwidth]{../media/Figs/ProbeNanofiber_birefringence_lightpath_inputlight}}\n   \\caption[Polarization spectroscopy on a nanofiber platform.]{This figure shows an example of a polarization spectroscopy scheme to measure the birefringence effect (see text) due to atom-light interaction near an optical nanofiber. A light linearly polarized along the $ D $ direction (in blue) is incident to the tapered fiber and converted to the fiber's $ D $ mode that interacts with the atoms trapped near the waveguide. After the interaction with the atoms, the guided light adiabatically connect to the light in free space again. \n   Two photon detectors measuring the photon flux difference of orthogonal polarization components can be used at the end to measure the polarization state of the output. }\n   \\label{fig:polarizationspectroscopy}\n\\end{figure}\n\nAlthough we will keep our analysis as general as possible, for simplicity, we will only look at single-mode waveguides that only allow degenerate fundamental modes to propagate. The rest of this dissertation will be focusing on the atom-light interaction in the nanophotonic waveguide region and the design of particular quantum measurement protocols. There are two basic light-response effects to be introduced in the following section: the \\emph{birefringence effect}\\index{birefringence effect} and the \\emph{Faraday effect}\\index{Faraday effect}.\n\n\n\\subsection{Birefringence and Faraday effects caused by atom-light interactions}\n\nConsider a laser beam that propagates through a cloud of atoms and generates a birefringence rotation on its polarization state. This process is possible if there is a relative speed difference of the light propagation along two orthogonal linear polarizations which are usually defined as the \\emph{fast axis}\\index{fast axis} and the \\emph{slow axis}\\index{slow axis}. Correspondingly, the effective index of refraction due to the atom-light interaction along the two directions are different and denoted by $ n_f $ and $ n_s $ with $ 1\\le n_f<n_s $, respectively. Therefore, there is a phase difference $ \\phi $ after the light propagates by a distance $ L $, where \n\\begin{align}\n\\phi= k(n_f-n_s)L.\n\\end{align}\nConsequently, a linearly polarized light input may become elliptically polarized after the interaction, and the phase difference above indicates how much the Stokes vector is rotated from a linear polarization axis on the \\Poincare sphere defined by the orientation of the fast axis.\nPhysically, how much the phase shift is generated due to the interaction with atoms determines how strong the birefringence effect is. \nGiven a thickness of the atom cloud, if a linear polarization component of the light along the $ x $ axis gives the maximum phase shift after the interaction among all the other linear polarization components while the $ y $ component yields the minimum phase shift, then the $ x $ axis and the $ y $ axis define the fast axis and the slow axis, respectively. The interaction will yield a birefringence effect, rotating the Stokes vector around the $ S_1$ axis on the \\Poincare sphere. \n\nSimilar to Eq.~\\eqref{eq:S_intensitydiff}, one can generalize the physical explanation of birefringence effect due to a cloud of atoms to both birefringence and Faraday effects due to atoms trapped near a waveguide by looking at the phase shift difference between two orthogonal modes.\nIn our study, all atoms trapped outside of a waveguide can be projected to the same position on the transverse plane of the fiber profile up to a reflection symmetry across the fiber axis. \nWe see this in the tapered nanofiber experiments with atoms trapped on an optical lattice~\\cite{Dawkins2011,Vetsch2010Optical}. \nIf both the $ H $ mode and the $ V $ mode have the same phase shift at the atoms' position while the $ R $ mode and the $ L $ mode have different phase shifts, then the atom-light interaction will yield a Faraday rotation around the $ S_3 $ axis on the \\Poincare sphere.\n\n%In general, as a result of the atom-light interaction, the polarization of the light will experience one of the two optical effects, the birefringence effect and the Faraday effect, or a mixture of the two effects. If we denote the polarization state of the light by $ \\ket{\\phi} $ and quantize the Stokes vector, promoting it to a column vector operator $ \\hat{\\mathbf{S}}=(\\hat{S}_0;\\hat{S}_1;\\hat{S}_2;\\hat{S}_3) $, the rotation of the polarization of the light on the \\Poincare sphere due to the interaction with atoms can be denoted as\n%\\begin{align}\n%e^{i\\boldsymbol{\\chi}\\cdot\\hat{\\mathbf{S}} }\\ket{\\phi},\n%\\end{align}\n%where the coordinates $ \\boldsymbol{\\chi}=(\\chi_0,\\chi_1,\\chi_2,\\chi_3) $ are the rotation angles around $ S_i (i=1,2,3) $ axes and the photon number attenuation \\nd{on?} $ S_0 $. The strength and details of the atom-light interactions hide in the $ \\boldsymbol{\\chi} $ vector. The key to designing particular polarization-based interactions lies on the phase response of particular waveguide modes. With this brief introduction of the polarization rotations and waveguide setups, we will dive into the beauty of atom-light interactions and inspire non-classical applications in the rest of the dissertation.\n\nIn the next section, we will look into the properties of the bare waveguide modes and the dispersive response of the waveguide modes due to the presence of the atoms from the perspective of Green's function. \n\n\\section{Dispersive light response in the perspective of Green's function}\n\\subsection{Eigenmodes of a dielectric waveguide}\\label{sec:eigenmodesofwaveguides}\nWe assume an infinitely long waveguide with a uniform profile of refractive index through the fiber axis. For a nanophotonic waveguide that can trap atoms using its evanescent field, its dimension of the cross-section is smaller than the wavelength $ \\lambda $ of the probe (typically, around $ \\lambda=894 $ nm or $852  $ nm, which are the D1 and D2 lines of cesium atoms). \nWe assume the waveguide is a linear medium with no absorption to the guided modes. The refractive bulk index\\index{refractive index} of the waveguide can be given by\n\\begin{align}\nn_0(\\br_\\perp) = \\begin{cases} \nn_1(\\br_\\perp), &\\quad \\text{core region},\\\\\nn_2(\\br_\\perp), &\\quad \\text{clad},\n\\end{cases} \n\\end{align}\nwhere $ n_1>n_2 $, $ \\br_\\perp=(x,y) $ are the coordinates in the transverse plane of the waveguide, and the index of refraction defined above applies to all transverse slices along the $ z $ axis which is the waveguide axis along the light propagation direction.\n\nA monochromatic electric field propagating in such a waveguide can be given by~\\cite{Jackson1975}\n\\begin{equation}\n\\mathbf{E}_0(\\br,t)=\\boldsymbol{\\mathcal{E}}_0(\\br_\\perp)e^{i(b\\beta z-\\omega_0 t)} %+\\frac{1}{2}\\mathrm{c.c.}\n=\\mathcal{E}_0\\mathbf{u}(\\br_\\perp)e^{i(b\\beta z-\\omega_0 t)}, %+\\frac{1}{2}\\mathrm{c.c.},\n\\label{Ert0}\n\\end{equation}\nwhere $ b=\\pm $ indicates the propagating direction, and $\\boldsymbol{\\mathcal{E}}_0(\\br_\\perp)=\\mathcal{E}_0\\mathbf{u}(\\br_\\perp)$ is the positive-frequency electric field envelope,\nwith $\\mathcal{E}_0$ determining the field amplitude and $\\mathbf{u}(\\br_\\perp)$ as the polarization vector at $ \\br_\\perp=(x,y)=(r_\\perp,\\phi) $ in either Cartesian or cylindrical coordinate system.\nIn general, $\\mathcal{E}$ is a complex scalar constant and $\\mathbf{u}(\\br_\\perp)$ is a complex vector normalized to the energy flux or the power across a transverse plane. The spatial dependent part of the field $ \\mathbf{u}(\\br_\\perp)e^{ib\\beta z} $ can be written as a linear combination of the \\emph{eigenmodes}\\index{eigenmode} supported by the waveguide.\n\nThe eigenmodes of a waveguide include both guided (bound) and unguided (unbound or radiation) modes, based on the corresponding waveguide boundary condition problem governed by the Maxwell equations~\\cite{Jackson1975}. \n\nWe use subscript $ \\mu=(\\omega,j,b,p) $ to indicate generic guided eigenmodes, $ \\mathbf{u}_\\mu (\\br) $, in which $ j=1 $ and $ \\beta=\\beta_0 $ for single-mode waveguides, and  $ b=\\pm $ denotes the propagation direction.\nWe use mode index $ \\nu=(\\omega,\\beta,m,p) $ to indicate unguided eigenmodes, $ \\mathbf{u}_\\nu(r\\!_\\perp ) $, where $ m=0,\\,\\pm 1,\\,\\pm 2,\\cdots $ is the mode index, and $p=\\pm$ denotes the polarization pattern.\nOne can show that (see Appendix~\\ref{chap:guidedunguidedmodes}), for a guided mode, $ n_2k_0< \\beta<n_1 k_0 $; for an unguided mode, $ 0<\\beta <n_2 k_0 $. \n\nThese eigenmodes satisfy the orthogonality condition,\n\\begin{subequations}\\label{eq:eigenmodeorthog}\n\\begin{align}\n\\int d^2 \\mbf{r}_\\perp \\, n^2(r_\\perp)\\mathbf{u}^*_\\mu (\\br_\\perp) \\cdot \\mathbf{u}_{\\mu'} (\\br_\\perp)\\big|_{\\beta = \\beta'} &= \\delta_{j,j'}\\delta_{p,p'},\\\\\n\\int\\mathrm{d}^2\\br_\\perp n^2(\\br_\\perp)\\left[\\mathbf{u}_{\\nu}(\\br\\!_\\perp )\\cdot\\mathbf{u}_{\\nu'}^*(\\br\\!_\\perp )\\right]_{\\beta=\\beta',m=m'} &=\\delta(\\omega-\\omega')\\delta_{pp'},\n\\end{align}\n\\end{subequations}\nand have dimension $1/\\sqrt{A}$, where $ A $ is the area for the corresponding mode with $ \\beta=\\beta' $~\\cite{LeKien2014}.\nThe completeness relations of these eigenmodes can be given by\n\\begin{align}\n\\sum_{\\mu}\\! n^2(\\br_\\perp)\\mathbf{u}_{\\mu}(r\\!_\\perp )\\mathbf{u}_{\\mu}^*(r'\\!_\\perp ) \\!+\\!\n\\sum_{\\nu}\\! n^2(\\br_\\perp)\\mathbf{u}_{\\nu}(r\\!_\\perp )\\mathbf{u}_{\\nu}^*(r'\\!_\\perp ) &=\\unittensor\\delta^T(r\\!_\\perp-r'\\!_\\perp),\n\\end{align}\nwhere $ \\unittensor $ is the unit tensor, and $\\delta^T(r\\!_\\perp-r'\\!_\\perp)$ is the delta function for transverse fields.\n\n%The orthogonality conditions of the guided and radiation modes can be summarized as follows: \n%\\begin{align}\n%\\int\\mathrm{d}^2\\br_\\perp n^2(\\br_\\perp)\\mathbf{u}_{\\mu}(\\br\\!_\\perp )\\cdot\\mathbf{u}_{\\mu'}^*(\\br\\!_\\perp ) &=\\delta_{\\mu\\mu'},\\label{eq:normalu}\n%\\end{align}\n\n\\subsubsection{Solving the eigenmodes for a nanofiber and \\SWG}\nAs an example, consider a typical optical nanofiber with a cylindrical cross-section of radius $ a $. We use $ a=225 $nm, $ n_1=1.4496 $ as a constant in the core region ($ r_\\perp\\le a $) and $ n_2=1.0000 $ in the vacuum clad region ($ r_\\perp>a $), where we have set the $ z $ axis to be the symmetric center of the nanofiber and $ r_\\perp =\\sqrt{x^2+y^2} $.\nWe will also study another nanophotonic waveguide with a square cross section, which we call a square waveguide. The waveguide has a width of $ w=300 $nm, $ n_1=2.0 $ for an ideal Si$_3$N$_4$ core medium $ (|x|\\le w/2,|y|\\le w/2) $, and the clad is also the vacuum\\footnote{Details about our choice of the \\SWG are in Appendix~\\ref{chap:choozingSWGs}.}.\nIn both cases, only the fundamental guided modes are allowed to propagate through the waveguide. That is, the allowed guided modes have a single propagation constant\\index{propagation constant} or projected wavenumber $ \\beta_0 \\,(n_1k_0<\\beta_0<n_2k_0)$ with wavenumber\\index{wavenumber} $k_0=2\\pi/\\lambda=\\omega_0/c $, where $\\omega_0$ is the angular frequency of the electric field, and $ c $ is the speed of light in a vacuum.\n\nThe fundamental modes of the cylindrical nanofiber are the \\HE-modes with degeneracy in propagation directions $ b=\\pm $ and polarizations of two labeled by $ p $~\\cite{Kien2004}. \nFor a single-mode \\SWG, the quasi-\\TE and the quasi-\\TM modes~\\cite{Lee2017Characterizations} together have a similar degeneracy as the \\HE-modes of the nanofiber in propagation directions and polarizations.\n\nTo calculate the eigenmodes of a dielectric waveguide, one may find analytical solutions if the waveguide has a solvable symmetry--like the cylindrical nanofiber. \nIn other cases such as for the square waveguide, one has to rely on numerical tools. \n \n\n\nThe electric field for the fundamental eigenmodes of a cylindrical fiber have been solved in previous works~\\cite{Snyder1983Optical,LeKien2014}. We provide a brief review of the method to solve the fiber problem in Appendix~\\ref{chap:fibereigenmodes} with solutions of the \\HE eigenmodes and its group velocity. The unguided or radiation mode solution is less used in this dissertation and can be found in, for example, Ref.~\\cite{LeKien2014}. \n\nA relatively simple form for the guided eigenmodes of a nanofiber can be expressed in a cylindrical basis $(r_\\perp, \\phi, z)$ with longitudinal unit vector $\\mathbf{e}_z$, oriented along the waveguide axis.  \nThe transverse unit vectors are related to their fixed Cartesian counterparts via the relations\n\\begin{subequations}\n\t\\begin{align}\n\t\t\\mathbf{e}_{r_{\\!\\perp}}     &= \\mathbf{e}_x \\cos \\phi + \\mathbf{e}_y \\sin \\phi, \\\\\n\t\t\\mathbf{e}_\\phi &= - \\mathbf{e}_x \\sin \\phi + \\mathbf{e}_y \\cos \\phi.\n\t\\end{align}\n\\end{subequations}\nThe transverse profile for the quasicircular guided modes, $p = \\pm$, is\n\t\\begin{align} \\label{Eq::QuasicircularModes_nanofiber}\n\t\t\\mbf{u}_{b,\\pm}(\\mathbf{r}_\\perp) = \\big[\\mathbf{e}_{r_{\\!\\perp}} u_{r_{\\!\\perp}}(r_\\perp) \\pm i \\mathbf{e}_\\phi u_\\phi(r_\\perp) +  i b \\mathbf{e}_z  u_z(r_\\perp) \\big]e^{ \\pm i \\phi}, \n\t\\end{align}\nand for the quasilinear guided modes, $p = \\{H,V\\}$, is\n\t\\begin{subequations} \\label{Eq::QuasilinearModes_nanofiber}\n\t\\begin{align}\n\t\t\\mbf{u}_{b,H}(\\mathbf{r}_\\perp) = & \\sqrt{2} \\big[ \\mathbf{e}_{r_{\\!\\perp}} u_{r_{\\!\\perp}}(r_\\perp) \\cos \\phi - \\mathbf{e}_\\phi u_\\phi(r_\\perp) \\sin \\phi +  ib \\mathbf{e}_z  u_z(r_\\perp) \\cos \\phi \\big] \\\\\n\t\t\\mbf{u}_{b,V}(\\mathbf{r}_\\perp) = & \\sqrt{2} \\big[ \\mathbf{e}_{r_{\\!\\perp}} u_{r_{\\!\\perp}}(r_\\perp) \\sin \\phi + \\mathbf{e}_\\phi u_\\phi(r_\\perp) \\cos \\phi +  ib \\mathbf{e}_z  u_z(r_\\perp) \\sin \\phi \\big]. \n\t\\end{align}\n\t\\end{subequations}\nThese modes are expressed in terms of real-valued functions $ \\left[u_{r_{\\!\\perp}}(r_\\perp), u_\\phi(r_\\perp), u_z(r_\\perp)\\right] $ of the HE$_{11}  $ modes of a nanofiber, which depend only on the radial coordinate $r_\\perp$ given by Eq.~\\eqref{Eq::ProfileFunctions}.\n\n%\\qxd{Need mode plots for the nanofiber and the \\SWG. Codes: \\url{rectwg_TETMlow_fullvector.m} and \\url{fibermodestudy.m}.}\n\\begin{figure}[!tbp]\n\\centering\\makebox[\\textwidth]{\n\\includegraphics[width=12cm]{../media/Figs/nanofiber_HVmode_absE_xy}}\n\\caption[Non-zero $ H $- and $ V $-mode components of a nanofiber in the $xy $ plane.]{Non-zero $ H $ and $ V $ mode components of a nanofiber in the $xy $ plane. The first (second) row plots the $ H $($ V $)-mode components $ \\left|\\re\\left[u_x(\\br) \\right]\\right| $, $\\left| \\re\\left[u_y(\\br) \\right]\\right| $, and $\\left| \\im\\left[u_z(\\br) \\right]\\right| $ from left to right. Amplitudes are normalized to the maximum value of all component parts. The white lines outline the profile of the nanofiber on each subplot. }\\label{fig:nanofiber_HVmode_E_xy}\n\\end{figure}\n\nWe plot the non-zero mode component parts of the quasilinear $ H$ and $ V $ modes of a nanofiber in Fig.~\\ref{fig:nanofiber_HVmode_E_xy}.\nThese eigenmodes usually have non-zero longitudinal component. \nMoreover, if we place an atom on the $ x $ axis ($ \\phi'=0 $), the forward-propagating $ H $ and $ V $ modes at the atom position have the following form,\n\\begin{subequations}\\label{eq:uHVrx}\n\\begin{align}\n\\mbf{u}_{H}(\\mathbf{r}'_\\perp) = & \\sqrt{2} \\big[ \\mathbf{e}_{r_{\\!\\perp}} u_{r_{\\!\\perp}}(r_\\perp') +  i \\mathbf{e}_z  u_z(r_\\perp') \\big] \\\\\n\\mbf{u}_{V}(\\mathbf{r}'_\\perp) = & \\sqrt{2}  \\mathbf{e}_\\phi u_\\phi(r_\\perp') ， \n\\end{align}\n\\end{subequations}\nwhere the $ H $ mode is elliptically polarized, and the $ V $ mode is linearly polarized. \nPutting the atom on the $ y $ axis gives a similar result by exchanging the $ H $ and $ V $ labels from Eq.~\\eqref{eq:uHVrx}. \n\n\\begin{figure}[!tbp]\n\\centering\\makebox[\\textwidth]{\n\\includegraphics[width=12cm]{../media/Figs/swg_HVmode_absE_xy}}\n\\caption[Non-zero $ H $- and $ V $-mode components of a square waveguide in the $xy $ plane.]{Non-zero $ H $ and $ V $ mode components of a \\SWG in the $xy $ plane. The first (second) row plots the $ H $($ V $)-mode components $\\left| \\re\\left[u_x(\\br) \\right]\\right| $, $\\left| \\re\\left[u_y(\\br) \\right]\\right| $, and $ \\left|\\im\\left[u_z(\\br) \\right]\\right| $ from left to right. Amplitudes are normalized to the maximum value of all component parts. The white lines outline the profile of the square waveguide on each subplot. }\\label{fig:swg_HVmode_E_xy}\n\\end{figure}\n\nFor the \\SWG and general geometries, we solve the eigenmodes using a numerical method called \\emph{Boundary Element Method}\\index{Boundary Element Method} or BEM~\\cite{Fallahkhair2008}. This method divides the regions close to the waveguide boundaries into finite grids, and we solve the wave equations by matching the boundary conditions on the grids. \nThe wave equations are discretized to a set of linear equations. The eigenmodes are found by solving the eigenvalue problem defined by the boundary condition in the frequency domain. \nIt is fairly efficient when we have a fixed frequency point. \nWe verify the accuracy of the BEM calculation with the nanofiber case since we know the analytical solution. Then we use BEM to solve the eigenmodes for the \\SWG geometry. \nBy find the propagation constant $ \\beta $ of the guided eigenmode as varying $ \\omega $, we can solve for the group velocity $ v_g=\\left.\\dd{\\omega}{\\beta}\\right|_{\\beta=\\beta_0} $ and the group index of refraction\\index{group index of refraction} $n_g = \\frac{c}{v_g}=\\left.\\dd{\\beta}{k}\\right|_{\\beta=\\beta_0}$.\n\n\n\nThe quasi-\\TE and quasi-\\TM modes are eigenmodes of the \\SWG with orthogonal polarizations and can be adiabatically connected to the $ x $- and $ y $-polarized linear free-space light inputs. Therefore, we can define the quasi-\\TE and quasi-\\TM modes as the $ H $ and $ V $ modes for the \\SWG geometry.\nWe plot the non-zero mode component parts of the quasilinearly $ H $ and $ V $ modes of a \\SWG in Fig.~\\ref{fig:swg_HVmode_E_xy}.\nAs shown, the field on the $ y $ axis of the $ H $ mode is also purely linearly polarized along the $ x $ direction. The electric fields on the $ x $ axis of the $ H $ mode are also elliptically polarized with the $ x $ component and the out-of-phase $ z $ component.\n\n\n\n%As an aside, here are the reasons why we only consider a \\SWG with a width of $ 300 $ nm besides the long-studied nanofiber case. In fact, on the course of this study, we have considered ridge and other types of waveguides. Eventually, we decided to study a simple shape of waveguides--a \\SWG--as a proof of principles. There has also been a long discussion on purposefully designing a rectangular waveguide and imperfections on fabricating a \\SWG, in which a \\SWG essentially becomes a rectangular one. \\nd{Do you mean that the discussion leads to the choice of a square waveguide?} Based on some back-of-envelope calculations and simple simulations, we find that, to be useful, a rectangular waveguide might have to be very long to fabricate and, if we choose a width of $ 300$--$320 $ nm, the imperfections in fabricating a \\SWG processes would not generate noticeable influence on the physical effects we care about. As these reasonings involve the knowledge we are going to introduce later, \n\n\\subsubsection{Mode superposition and decomposition}\n\\begin{figure}[!tbp]\n\\centering\\makebox[\\textwidth]{\n\\includegraphics[width=12cm]{../media/Figs/nanofiber_DaDmode_absE_xy}}\n\\caption[Non-zero $ D $- and $ \\bar{D} $-mode components of a nanofiber in the $xy $ plane.]{Non-zero $ D $ and $ \\thickbar{D} $ mode components of a nanofiber in the $xy $ plane. The first (second) row plots the $ D $($ \\thickbar{D} $)-mode components $\\left| \\re\\left[u_x(\\br) \\right]\\right| $, $ \\left|\\re\\left[u_y(\\br) \\right]\\right| $, and $\\left| \\im\\left[u_z(\\br) \\right]\\right| $ from left to right. Amplitudes are normalized to the maximum value of all component parts. }\\label{fig:nanofiber_DaDmode_E_xy}\n\\end{figure}\n\n%\\begin{figure}[!tbp]\n%\\centering\\makebox[\\textwidth]{\n%\\includegraphics[width=12cm]{../media/Figs/nanofiber_HVDaDmode_Ints_xy}}\n%\\caption[Intensity distributions of quasi-linearly polarized modes  in the $xy $ plane of a nanofiber.]{Intensity distributions of quasi-linearly polarized modes  in the $xy $ plane of a nanofiber. }\\label{fig:nanofiber_HVDaDmode_Ints_xy}\n%\\end{figure}\n\nThe degeneracy in polarizations of the \\HE modes allows one to write the eigenmodes of the nanofiber in an arbitrary polarization basis. \nTwo convenient guided-mode bases are the quasilinear and quasicircular polarization modes. \n%In Figs.~\\ref{fig:Modes_Rot45HV_fiber} and~\\ref{fig:Modes_Rot45LR_fiber}, we show the decomposition of a diagonally polarized $ D $ mode of a nanofiber in the $ HV $- and $ LR $-bases, respectively. \nBased on Eq.~\\eqref{eq:eDeDbar}, the $ D $ and $ \\bar{D} $ mode bases can be written as a linear combination of the $ H $ and $ V $ modes [see Fig.~\\ref{fig:Modes_Rot45HV_fiber}]. We plot the non-zero component parts of the $ D $ and $ \\bar{D} $ modes in Fig.~\\ref{fig:nanofiber_DaDmode_E_xy}.\n%We also plot the intensity distribution of $ H $, $ V $, $ D $ and $ \\bar{D} $ modes of a nanofiber in Fig.~\\ref{fig:nanofiber_HVDaDmode_Ints_xy} for comparison. \nThe quasicircular polarization mode bases can be found from the $ H $ and $ V $ modes. \nIn other words, a quasilinear mode can be decomposed into the quasicircular mode bases, Fig.~\\ref{fig:Modes_Rot45LR_fiber}.\nWe find that the $ H $ mode component has a much stronger intensity at the atom position than the $ V $ mode component as shown in Fig.~\\ref{fig:Modes_Rot45HV_fiber}, if we place an atom on the $ x $ axis.\nThis property of \\emph{mode anisotropy}\\index{anisotropy of waveguide modes} in azimuthal direction is intrinsic to the waveguides but does not exist in freely propagating fundamental Gaussian laser beams typically used in atom-light coupling experiments. In contrast, the decomposed $ R $ and $ L $ modes at the atom position have the same intensity. \nAs we will see later, we can choose a good mode basis based on the atomic internal structure and fully utilize the isotropic property of waveguide modes, which is the key to optimally designing some quantum operations and yields great advantages for the nanophotonic waveguides over the free-space atom-light quantum interface. For now, we lay some necessary foundations.\n\n\\begin{figure}\n\\centering\\makebox[\\textwidth]{\n\\includegraphics[width=12cm]{../media/Figs/Modes_Rot45HV}}\n\\caption[Mode decomposition of an input quasilinear polarized laser beam in the $ H$ and $V$ mode basis.]{Mode decomposition of an input quasilinear polarized $ D $ mode in the $ H $ and $ V $ mode basis of a nanofiber. Red double-arrowed lines indicate the linear polarization directions of the free-space mode correspondence. This figure shows that the decomposition relation $ D=(H+V)/\\sqrt{2} $. \nWe put a dark dot on the $ x $ axis of each mode plot to highlight the anisotropy of modes (see text). }\\label{fig:Modes_Rot45HV_fiber}\n\\end{figure}\n\n\\begin{figure}[!tbp]\n\\centering\\makebox[\\textwidth]{\n\\includegraphics[width=12cm]{../media/Figs/Modes_Rot45LR}}\n\\caption[Mode decomposition of an input quasilinear polarized laser beam in the quasicircular mode basis.]{Same as Fig.~\\ref{fig:Modes_Rot45HV_fiber} but decomposed in the $ LR$-mode basis. At the dark dot's position, the $ L $ and $ R $ modes have the same intensity.}\\label{fig:Modes_Rot45LR_fiber}\n\\end{figure}\n\nFor the \\SWG case, similarly, we can define the quasilinear $ D $ and $ \\bar{D} $ modes using the $ H $ and $ V $ mode basis with non-zero components plotted in Fig.~\\ref{fig:swg_DaDmode_E_xy}. \nWe plot the intensity distribution of these quasilinear modes of a \\SWG in the $ xy $ plane in Fig.~\\ref{fig:swg_HVDaDmode_Ints_xy}. These quasilinear modes have similar anisotropic properties as the fiber modes do.\n\n\n\n\\begin{figure}[!tbp]\n\\centering\\makebox[\\textwidth]{\n\\includegraphics[width=12cm]{../media/Figs/swg_DaDmode_absE_xy}}\n\\caption[Non-zero $ D $- and $ \\bar{D} $-mode components of a square waveguide in the $xy $ plane.]{Non-zero $ D $ and $ \\thickbar{D} $ mode components of a \\SWG in the $xy $ plane. The first (second) row plots the $ D $($ \\thickbar{D} $)-mode components $ \\left|\\re\\left[u_x(\\br) \\right]\\right| $, $\\left| \\re\\left[u_y(\\br) \\right]\\right| $, and $\\left| \\im\\left[u_z(\\br) \\right]\\right| $ from left to right. Amplitudes are normalized to the maximum value of all component parts. }\\label{fig:swg_DaDmode_E_xy}\n\\end{figure}\n\n\\begin{figure}[!tbp]\n\\centering\\makebox[\\textwidth]{\n\\includegraphics[width=12cm]{../media/Figs/swg_HVDaDmode_Ints_xy}}\n\\caption[Intensity distributions of quasilinearly polarized modes in the $xy $ plane of a square waveguide.]{Intensity distributions of quasilinearly polarized modes in the $xy $ plane of a \\SWG. }\\label{fig:swg_HVDaDmode_Ints_xy}\n\\end{figure}\n\n\n\\subsection{Dyadic Green's functions of dipole radiations in presence of a dielectric waveguide}\\label{sec:calculatingGreenstensor}\nWe consider light response in the presence of a photon emitter outside of a dielectric waveguide. The dyadic Green's function\\index{dyadic Green's function}, or Green's tensor\\index{Green's tensor}\\footnote{We may also call it Green's function tensor\\index{Green's function tensor} or Green's function dyad\\index{Green's function dyad}.}, $ \\GFT(\\br,\\br')=\\GFT(\\br,\\br';\\omega_0) $ can be understood to be the response function of the field measured at $ \\br $ responding to a unit radiating point source at $ \\br' $ at a frequency $ \\omega_0 $. With the dyadic Green's function, the field response due to an arbitrary source can be calculated. In this section, we consider a scenario that atoms are trapped near a nanophotonic waveguide, and formulate a general theory of field response using the Green's function method. For simplicity, we regard atoms as classical Lorentz dipoles, which interact with light in terms of optical dipole radiation. The dipoles oscillate in space and time to form a current, $ \\mathbf{J} $, responding to the incident field and such the atomic ensemble acts as an effective ``medium\" with a linear susceptibility that modulates the phase and amplitude of the light passing through the waveguide. \n\nGiven the index of refraction distribution function $ n(\\br) $ with the waveguide as the background medium, a chromatic electric field modulated by the presence of atoms can be described by the wave equation below~\\cite{Jackson1975}: \n\\begin{align}\\label{eq:Maxwellwithsource2}\n\\left[\\! -\\! \\nabla\\!\\!\\times\\!\\nabla\\!\\!\\times + n^2\\!(\\br)\\frac{\\omega_0^2}{c^2} \\right]\\!\\! \\boldsymbol{\\mathcal{E}}(\\br) &\\!=\\! -i4\\pi\\! \\frac{\\omega_0}{c^2}\\! \\mathbf{J}(\\br) \\!=\\! -4\\pi\\! \\frac{\\omega_0^2}{c^2}\\! \\mathbf{P}(\\br)\\!=\\! -4\\pi\\! \\frac{\\omega_0^2}{c^2}\\! \\tensor{\\boldsymbol{\\chi}}(\\br)\\! \\cdot\\! \\boldsymbol{\\mathcal{E}}(\\br),\n\\end{align}\nwhere the only difference from the homogeneous wave equation, Eq.~\\eqref{MaxwellHelmholtz0}, is that we have brought in dipole source terms represented by the equivalent expressions on the right-hand side of the equation. For the source terms, we have defined the source of the current\\index{current source} $ \\mathbf{J}(\\br)=\\pp{\\mathbf{P}}{t}=-i\\omega\\mathbf{P}(\\br)=-i\\omega_0 \\tensor{\\boldsymbol{\\chi}}(\\br)\\cdot \\boldsymbol{\\mathcal{E}}(\\br) $ with electric susceptibility\\index{electric susceptibility} $ \\tensor{\\boldsymbol{\\chi}}(\\br) = \\sum_{\\br'}\\delta(\\br-\\mathbf{r}')\\tensor{\\boldsymbol{\\alpha}} \\, (\\br')$ \\footnote{We have used the Gaussian-cgs units here. In the SI units, the corresponding relationship is $ \\tensor{\\boldsymbol{\\chi}}(\\br) = \\sum_{\\br'}\\delta(\\br-\\mathbf{r}')\\tensor{\\boldsymbol{\\alpha}} \\, (\\br')$ and $\\tensor{\\boldsymbol{\\chi}}{}^{SI}=4\\pi\\tensor{\\boldsymbol{\\chi}}{}^{G}  $. Here, $ 4\\pi $ is a typical multiplier factor between the SI and the Gaussian-cgs unit systems. }, where $ \\tensor{\\boldsymbol{\\alpha}} $ is the polarizability tensor\\index{polarizability!polarizability tensor} of the atoms located at $ \\br' $. Specifically, using the dipole approximation, the polarizability due to the presence of atoms, $ \\mathbf{P}(\\br)=\\sum_{\\br'}\\delta(\\br-\\br')\\mathbf{d}(\\br')=\\sum_{\\br'}\\delta(\\br-\\br')\\tensor{\\boldsymbol{\\alpha}} \\, (\\br')\\cdot \\boldsymbol{\\mathcal{E}}(\\br) $, where $ \\mathbf{d}(\\br') $ is the induced dipole moment of an atom at $ \\br' $. \n\nEq.~\\eqref{eq:Maxwellwithsource2} can be solved by finding the corresponding dyadic Green's function\\index{dyadic Green's function} in the frequency domain defined by\\footnote{Although the definition of the source term is arbitrary, to make the relation between $ \\mathbf{E}(\\br) $ and the dyadic Green's function $ \\GFT(\\br,\\br') $ consistent with our later expressions, we have chosen the source term self-consistently. \nIf we define the Green's function by $\\left[ -\\nabla\\times\\nabla\\times + n^2\\frac{\\omega_0^2}{c^2} \\right] \\GFT(\\br,\\br') = \\delta^{(3)}(\\br-\\br')\\unittensor$ and the source term by $\\tensor{\\bf S}(\\br)=-4\\pi \\frac{\\omega_0^2}{c^2} \\tensor{\\boldsymbol{\\chi}}(\\br)$, which has a $4\\pi\\omega_0^2/c^2$ factor compared to our definition in the text, the $4\\pi\\omega_0^2/c^2$ factor will be carried over to the relation between $ \\mathbf{E}(\\br) $ and $ \\GFT(\\br,\\br') $ and other quantities as well. Also see Ref.~\\cite{Wubs2004} as another commonly used definition.}\n\\begin{align}\n\\left[ -\\nabla\\times\\nabla\\times + n^2\\frac{\\omega_0^2}{c^2} \\right] \\GFT(\\br,\\br';\\omega_0) &= -4\\pi \\frac{\\omega_0^2}{c^2}\\delta^{(3)}(\\br-\\br')\\unittensor. \\label{eq:dyadicGF}\n\\end{align}\n\nA special case of the dyadic Green's function\\index{dyadic Green's function} is when a dipole source is placed in a homogeneous medium, say, the vacuum. In this case, the Green's tensor\\index{Green's tensor} is given by\n\\begin{align}\n\\GFT(\\br,\\br') &=  \\left[\\unittensor + \\frac{1}{k_0^2}\\nabla\\nabla \\right]G_0(\\br,\\br')\n\\end{align}\nwith a scalar Green's function \n\\begin{align}\nG_0(\\br,\\br';\\omega_0) =k_0^2\\frac{e^{\\pm ik_0 |\\mathbf{r}-\\br'|}}{|\\br-\\br'|},\\label{eq:G0rrp}\n\\end{align}\nwhere we only need to keep the positive frequency solution for outgoing radiations. This result reflects the fact that the field response at $ \\br $ is a free spherical wave coming out from a point dipole source as we can recognize from basic electromagnetism. This solution is a key to solve radiation problems and normalize modified decay rates of atoms in the presence of a waveguide as we will discuss later. When $ \\br\\rightarrow \\br' $ or when the detection position is the dipole position, the real part of the Green's function diverges yet the imaginary part of $ \\GFT(\\br',\\br') $ takes the form\n\\begin{align}\n\\im\\left[\\GFT(\\br',\\br')\\right] = G_0\\unittensor,\n\\end{align}\nwith the diagonal elements\n\\begin{align}\\label{eq:G0}\nG_0=\\im\\left[\\mathbf{e}_n\\cdot  \\GFT(\\br',\\br')\\cdot \\mathbf{e}_n^*\\right]=\\frac{2}{3}k_0^3,\n\\end{align}\nwhere $ \\mathbf{e}_n $ is an arbitrary unit vector.\nThe details of solving the free-space Green's function and techniques we are going to use, including Born approximation~\\cite{Gubernatis1977Born} and other general methods of solving a radiation problem, can be found in Appendix~\\ref{chap:freespacegreenfunction}. \n\nThe output field follows from the Lippmann-Schwinger equation\\index{Lippmann-Schwinger equation} (the first line in the equation below) after interacting with $ N_A $ atoms placed at $ \\br'=\\br'_n\\, (n=1,2,\\cdots,N_A) $,\n\\begin{subequations}\n\\begin{align}\\label{eq:Lippmann-Schwinger}\n\\mathbf{E}(\\br) &=\\mathbf{E}_0(\\br)+ \\sum_n^{N_A} \\GFT(\\br,\\br'_n)\\cdot \\tensor{\\boldsymbol{\\alpha}}{}^{(n)}\\cdot \\mathbf{E}(\\br'_n)\\\\\n&\\approx \\mathbf{E}_0(\\br)+ \\sum_n^{N_A} \\GFT(\\br,\\br'_n)\\cdot \\tensor{\\boldsymbol{\\alpha}}{}^{(n)}\\cdot \\mathbf{E}_0(\\br'_n)\\label{eq:EGFTnatoms}\n\\end{align}\n\\end{subequations}\nwhere $ \\tensor{\\boldsymbol{\\alpha}}^{(n)} $ is the polarizability of the atom positioned at $ \\br'_n $. \nThe right hand side of Eq.~\\eqref{eq:EGFTnatoms} implies that the total field after the interaction includes two sources of fields: one is the original propagating field through the waveguide (the first term), and the other is the scattered field due to the presence of the atoms (the second term). \nUsing the Born approximation, the photon scattering among atoms and high-order scattering generating self-polarizations have been ignored. \nThis approximation is valid in the dispersive regime, which can be verified based on Ref.~\\cite{Asenjo-Garcia2017Atom} including the atom-atom interactions and other scattering effects~\\footnote{See, for example, Eq.~(10) in Ref.~\\cite{Asenjo-Garcia2017Atom}. It describes the field transformation relations and will recover to our result presented in Eq.~\\eqref{eq:EGFTnatoms} if the detuning $ \\Delta_A $ is much larger than the frequency shift $ J_{\\xi,\\mathrm{1D}} $ and the modified decay rates $ \\Gamma_{\\xi,\\mathrm{1D} }$ of atoms for dispersive interactions.}. Now, the only barrier to fully solving the output electric field is to solve the dyadic Green's function.\n\nIn general, there are two strategies to solve the dyadic Green's function\\index{dyadic Green's function}: one is to solve the dipole radiation problem numerically and/or analytically; the other involves eigenmode decomposition and only needs bare waveguide modes. We call the first approach the \\emph{normalization} approach, and the other the \\emph{eigenmode-decomposition} approach. We will describe the two approaches in the successive subsections. \n\n\\subsubsection{a. The \\emph{normalization} approach}\n\nWe recall the equation governing the dyadic Green's function\\index{dyadic Green's function},\n\\begin{align}\n\\left[ -\\nabla\\times\\nabla\\times + n^2\\frac{\\omega^2_0}{c^2} \\right] \\GFT(\\br,\\br') &= -4\\pi k_0^2\\delta^{(3)}(\\br-\\br')\\unittensor,\n\\end{align}\neach column of which can be expressed as\n\\begin{align}\n\\left[ -\\nabla\\times\\nabla\\times + n^2\\frac{\\omega^2_0}{c^2} \\right] \\mathbf{G}_i(\\br,\\br') &= -4\\pi k_0^2\\mathbf{e}_i\\delta(\\br-\\br'), \\label{eq:Gi}\n\\end{align}\nwhere the subscripts $ i=r\\!_\\perp,\\phi,z $ written in the cylindrical coordinate system or $ i=x,y,z $ in the Cartesian coordinate system denote the coordinate components. The $ \\mathbf{G}_i(\\br,\\br') $ in the equation above is the $ i$th column of the dyadic Green's function of $ \\GFT(\\br,\\br') $. Here, we have used $\\omega_0$ to indicate the angular frequency of the radiation from the source.  \n\nComparing Eq.~\\eqref{eq:Gi} with Eq.~\\eqref{eq:Maxwellwithsource2}, we find that Eq.~\\eqref{eq:Gi} is exactly the chromatic wave equation of $ \\mathbf{E}(\\br) $ when there is a unit dipole source orientated along $ \\mathbf{e}_i $ and placed at $ \\br' $. That is to say, once we solve the electric field components with a unit dipole source orientated along all the $ \\mathbf{e}_i $ directions, the columns of the dyadic function is just the corresponding field components. Concretely, in the cylindrical coordinate system, the dyadic Green's function\\index{dyadic Green's function} elements correspond to the following electric field components emitted by a unit dipole source orientated in the three orthogonal basis directions:\n\\begin{equation}\n\\GFT(\\mathbf{r},\\mathbf{r}')=\\!\\!\\!\\!\\!\\!\\!\\!\\!\\!\\!\\!\\!\\!\\!\\!\\!\\!\\!\\!\\!\\!\\!\\! \\!\\!\\!\\!\\!\\!\\!\\! \\!\\!\\!\\!\\!\\!\\!\\! \\!\\!\\!\\!\\!\\!\\!\\!\n  \\begin{tikzpicture}[baseline=-\\the\\dimexpr\\fontdimen22\\textfont2\\relax ]\n   \\matrix (m)[matrix of math nodes,left delimiter=(,right delimiter=),ampersand replacement=\\&] % Note: the ampersandreplacement line redefines to use \\& instead of the usual & sign to separate columns in the matrix. This can avoid potential conflict with external environment where ampersands are also defined for specific purposes. See https://tex.stackexchange.com/questions/15093/single-ampersand-used-with-wrong-catcode-error-using-tikz-matrix-in-beamer\n  {\n  G_{r\\!_\\perp r\\!_\\perp} \\& G_{r\\!_\\perp\\phi} \\& G_{r\\!_\\perp z}\\\\\n  G_{\\phi r\\!_\\perp} \\& G_{\\phi\\phi} \\& G_{\\phi z} \\\\\n  G_{zr\\!_\\perp} \\& G_{z\\phi} \\& G_{zz} \\\\\n  };\n  % Hightlight columns.\n  \\begin{pgfonlayer}{myback}\n    \\fhighlight[red!30]{m-1-1}{m-3-1}\n    \\fhighlight[blue!30]{m-1-2}{m-3-2}\n    \\fhighlight[green!30]{m-1-3}{m-3-3}\n  \\end{pgfonlayer}\n  % Make links to other equivalent expressions.\n  \\begin{pgfonlayer}{myback}\n    \\draw (m-3-1.south)+(-0.5,-0.76) node [left] {column vector $\\mathbf{G}_i$:};\n    \\draw[implies-implies,double equal sign distance] (m-3-1.south)+(0,-0.08) -- +(0,-0.5) node[below]{$ \\mathbf{G}_{r\\!_\\perp} $};\n    \\draw[implies-implies,double equal sign distance] (m-3-2.south)+(0,-0.08) -- +(0,-0.5) node[below]{$ \\mathbf{G}_{\\phi} $};\n    \\draw[implies-implies,double equal sign distance] (m-3-3.south)+(0,-0.1) -- +(0,-0.55) node[below]{$ \\mathbf{G}_z $};\n    \\draw (m-3-1.south)+(-0.5,-1.7) node [left,align=center] {equivalent $ \\mathbf{E} $ radiated\\\\ from a unit dipole:};\n    \\draw[<-] (m-3-1.south)+(0,-1.08) -- +(0,-1.5) node[below]{$ \\mathbf{d}_{r\\!_\\perp} $};\n    \\draw[<-] (m-3-2.south)+(0,-1.08) -- +(0,-1.5) node[below]{$ \\mathbf{d}_{\\phi} $};\n    \\draw[<-] (m-3-3.south)+(0,-1.1) -- +(0,-1.55) node[below]{$ \\mathbf{d}_z $};\n    %\\draw[<-] (m-3-3.south)+(0.5,-1.32) -- +(1.1,-1.32) node[right]{$\\cdot (-4\\pi k^2)$}; % The old normalization factor.\n  \\end{pgfonlayer}\n  \\end{tikzpicture}\n\\end{equation}\nNote that all calculations are performed with a fixed frequency $ \\omega_0 $. Alternatively, we calculate the $ ij $th element of the dyadic Green's function\\index{dyadic Green's function} by\n\\begin{align}\\label{eq:GFTijEd}\nG_{ij}(\\br,\\br';\\omega_0) =\\frac{E^i_j(\\br)}{d^{(j)}(\\br')},\n\\end{align}\nwhere $ d^{(j)}(\\br') $ is the dipole moment of a dipole at $ \\br' $ with an orientation along the $ \\mathbf{e}_j $ direction, and $ E^i_j(\\br) $ is the $ i $th component of the calculated electric field at $ \\br $ in the presence of the dipole source.\nTherefore, the key to calculate the dyadic Green's function in this approach is to solve the field emitted by a normalized dipole in the presence of the waveguide in the frequency domain. In fact, there are many ways to calculate the fields with a dipole source in a medium. \n\n\\textbf{Analytical solutions:} The field can be analytically solved only if the waveguide has some special geometry. A nanofiber geometry is one example that can be solved analytically.  \nIn Appendix~\\ref{sec:boundrad}, we provide some details of solving the $ \\mathbf{E}(\\br) $ field radiated from three orthogonal unit dipoles by decomposing the dipole radiation function described by Eq.~\\eqref{eq:G0rrp} into the cylindrical coordinate basis. We solve the guided mode and the unguided mode contributions via finding residues of poles and contour integrals of branch cuts. In the end, complex integrations are simplified to be over the real axis to assuming the waveguide is lossless. \nUsing this method, we are able to decompose the responding Green's tensor outside of the waveguide to a part due to free-dipole radiation, $ \\GFT_0(\\br,\\br') $, and a part due to the scattering from the waveguide interface, $ \\GFT_S(\\br,\\br') $; and we interpret the Green's tensor responding inside of the waveguide medium, $ \\GFT_T(\\br,\\br') $, as a result of mode transmission. Each part is calculated by projecting the total dipole radiation into the corresponding orthonormal modes. Therefore, the dyadic Green's function\\index{dyadic Green's function} can be written as\n\\begin{align}\\label{eq:GFTdecomp0RT}\n\\GFT(\\br,\\br') = \\left\\{ \n\\begin{array}{lc}\n\\GFT_0(\\br,\\br')+\\GFT_S(\\br,\\br'), & \\br\\text{ outside of the waveguide}\\\\\n\\GFT_T(\\br,\\br'), & \\br\\text{ inside the waveguide}\n\\end{array}\\right..\n\\end{align}\n\nAs an extension to this mode decomposition method, we decompose a plane wave into cylindrical modes in Appendix~\\ref{Ch:PlanewaveDecomposition}. Although the result has not been used for this dissertation work, it might be useful when we consider the atomic cooling and state preparation protocols with an incident light not through the waveguide (see experiments in Refs.\\cite{Meng2017ground,Ostfeldt2017Dipole}). \n\n\\textbf{Numerical methods:} For most geometries of waveguides, an analytical solution is not always available, and we have to use numerical methods, including finite-difference time-domain (FDTD) method\\index{FDTD method}~\\cite{Taflove2005}, boundary-element method (BEM)\\index{BEM} for radiation problems~\\cite{GarciadeAbajo1998Relativistic,GarciadeAbajo2002Retarded}, finite-element method (FEM)\\index{FEM} and so on. \n\nThe FDTD method solves the Maxwell equations by dividing the real space under consideration completely into regular Yee-cell grids and transforming the differential equations into a linear equation system on those grid points in the time domain. I have used this method to study quantum dynamics and the photon emission spectrum of a many-body system involving nanophotonic cavities for my master's thesis~\\cite{Qi2012}. From my past experience, the FDTD method requires a large computer memory or a long simulation time to perform first-principle time evolution of the field propagation matching the boundary conditions, and then Fourier transform the results into the frequency domain for the dyadic Green's function that we want. Since we only need to calculate the dyadic Green's function at a particular frequency point, this method is an overkilling. Also, it cannot easily separate the guided mode and the unguided mode contributions to help us develop some insights and simplify the simulation with some reasonable approximations. \n\nOn the other hand, BEM evolves the Maxwell equations as a linear system in the $ \\beta $ (projected wave vector) space, which makes it possible to separate the guided and the unguided mode contributions based on the range of $ \\beta $ (see Section~\\ref{sec:eigenmodesofwaveguides}). \nThis method expresses electromagnetic field in terms of charges and currents distributed on the surfaces and interfaces of the structure under consideration. \nThe boundary conditions for the electromagnetic field yields a set of linear integral equations, with unknown charges and currents, which are eventually solved self-consistently in the presence of the external incident field from the dipole source by discretizing the integrals with a finite set of boundary points (elements). \nThe only assumption in this method is that the different media involved in the structures under study are described by frequency-dependent local dielectric functions, which is valid for our problem and we can use constant index of refractions. Therefore, the complexity of BEM only scales quadratically with respect to the points on the boundary elements, not on the full simulation space as the FDTD method does, which makes BEM computational efficient to solve our problem. FEM has a computational complexity between FDTD method and BEM, by using a flexible meshing trick to simplify the calculations yet not as much as BEM does. \n\nTo understand the deduction of computational complexity of this method, one can think about the BEM as a method that works in a ``dressed'' picture and absorbs the influence of boundary conditions fully into induced charges and currents at finite points. \nTherefore, the troubles of evolving Maxwell equations over the full grids as encountered by FDTD, FEM and other numerical methods are avoided in BEM. \n\nFor our study, we decide to use a BEM program to simulate the electromagnetic field due to a unit dipole for the nanofiber geometry first to check the accuracy against our analytical solution, and then apply this method to the \\SWG case. \nSince the field components in the $ z $ direction only yield a phase difference compared to the $ z=0 $ plane, we can fully solve our radiation problem on a 2D plane. \nWith boundary points set for every $ 5 $--$ 6 $ nm away from each other on the boundary, we can achieve a negligible error deviation from our known solution (below $ 1\\% $). \nWe use $ \\Delta \\beta = 0.01k_0 $ to sample the $ \\beta $-space calculations. One issue of this approach is that we have to make the medium of the waveguide ``imperfect\" to avoid a divergent problem when we calculate the field response at the guided mode condition point $ \\beta=\\beta_0 $. \nWe set $ n_1(\\br_\\perp\\in \\text{waveguide region})=n_1+i\\delta n_1 $, where $ n_1 $ is the the real bulk index of refraction of the waveguide and $ \\delta n_1 $ gives a small fake non-radiative loss (we find $ \\delta n_1\\sim 0.001 $ or $ 0.01 $ might be good enough). Without this treatment, since the field at $ \\beta=\\beta_0 $ is a delta function, the result will diverge. To calculate the field response at the dipole position, which will be used for the modified decay rate calculation, we only calculate the induced electric field for a similar reason of the divergence of the real part of the Green's function. \n\nSince BEM is sensitive to sharp edges in finding the induced current or charge distribution, we use smooth curves to replace the sharp corners in simulating the radiation problems for the \\SWG boundary condition. \n\nIn BEM, the Green's function tensor response at the dipole position at $ \\omega_0 $ due to the unguided modes can be decomposed into the free-dipole or homogeneous radiation contribution and the induced-dipole radiation contribution coupled to the unguided modes, that is \n\\begin{align} \\GFT_{ung}(\\br',\\br';\\omega_0)=\\GFT_0(\\br',\\br';\\omega_0)+\\GFT_{ind,ung}(\\br',\\br';\\omega_0).\n\\end{align}\nTo not be confused, when $ \\br' $ is outside of the waveguide, Eq.~\\eqref{eq:GFTdecomp0RT} implies that \n\\begin{align}\n\\GFT_S(\\br',\\br';\\omega_0) &= \\GFT_{ind,gyd}(\\br',\\br';\\omega_0) + \\GFT_{ind,ung}(\\br',\\br';\\omega_0). \n\\end{align}\nThat is, the scattering part of Green's tensor includes both the guided ($ gyd $) and the radiation or unguided ($ ung $) parts that are calculated by integrating over different ranges of $ \\beta $. \nFor a single-mode waveguide, with a unit dipole orientated along $j$ direction placed at $ \\br' $, the induced-dipole radiation Green's tensor elements coupled to unguided modes can be calculated by~\\cite{GarciadeAbajo1998Relativistic,GarciadeAbajo2002Retarded}\n\\begin{align}\nG_{ind,gyd}^{ij}(\\mathbf{r}',\\mathbf{r}')&=\\frac{1}{2\\pi}\\left[\\int_{-n_1k_0}^{-n_2k_0} d\\beta E_j^i(\\mathbf{r}') +\\int_{n_2k_0}^{n_1k_0} d\\beta E_j^i(\\mathbf{r}')\\right]\\nn\\\\\n&=\\frac{1}{\\pi}\\int_{n_2k_0}^{n_1k_0} d\\beta E_j^i(\\mathbf{r}')\\label{eq:BEMGindgydij}\\\\\nG_{ind,ung}^{ij}(\\mathbf{r}',\\mathbf{r}')&=\\frac{1}{2\\pi}\\int_{-n_2k_0}^{n_2k_0} d\\beta E_j^i(\\mathbf{r}')=\\frac{1}{\\pi}\\int_{0}^{n_2k_0} d\\beta E_j^i(\\mathbf{r}') \\label{eq:BEMGindij}\n\\end{align}\nwhere $ E_j^i(\\mathbf{r}') $ is the $i$-th electric field component measured at the dipole position\\footnote{Note that Eqs.~\\eqref{eq:BEMGindgydij} and~\\eqref{eq:BEMGindij} are given formally consistent with Eq.~\\ref{eq:GFTijEd} while absorbing the unit of dipole moment into the measured field $ E_j^i(\\br') $. Not to be confused, the Green's functions should really be in the units of electric field over dipole moment. Numerically, these equations of Green's function tensor elements may have different forms depending on how the ``unit'' dipole is defined in concrete simulations. For those who use the same BEM program this dissertation employed, the prefactor $ 1/2\\pi $ in Eqs.~\\eqref{eq:BEMGindgydij} and~\\eqref{eq:BEMGindij} should be replaced by $ \\frac{2k_0^2}{3\\pi^2} $ following a variant of Gaussian-atomic unit convention that the BEM program obeys.}. \nTo calculate the guided-mode-induced Green's tensor using the first equation above, we need to give an artificial loss to the medium, that is to make the permittivity of the waveguide as\n\\begin{align}\n\\varepsilon(\\br_\\perp) = n^2(\\br_\\perp) + i\\delta n(\\br_\\perp),\n\\end{align}\nwhere $ \\delta n(\\br_\\perp) $ is a small real number in the waveguide region and zero outside. Same for the unguided-mode-induced Green's tensor calculation. \nIn practice, it is tricky to find a proper artificial loss to obtain an accurate value for the guided-mode-induced Green's tensor--especially when $ \\beta_0 $ is close to the integration limit points; and even trickier to use the equation for the guided-mode-induced Green's tensor calculation to find the contribution from a particular guided mode if the waveguide allows multiple guided modes. \nSo, we decide to use the eigenmode decomposition method to calculate the guided-mode-induced Green's tensor, which will be introduced next.\nHowever, the calculation for the unguided-mode-induced Green's tensor equation [Eq.~\\eqref{eq:BEMGindij}] is quite robust to the choice of artificial material loss, since the artificial loss is solely set for avoiding the divergent problem of the guided modes and does not bring in new radiations. \nIf we want to calculate $ \\GFT(\\br,\\br') $, Eqs.~\\eqref{eq:BEMGindgydij} and~\\eqref{eq:BEMGindij} hold if we replace $ E_j^i(\\br') $ with $ E_j^i(\\br) $. \n \n\n\\subsubsection{b. The \\emph{eigenmode-decomposition} approach}\n\nIn the case that the source is extremely small, the total dyadic Green's function should be effectively equal to the transverse dyadic Green's function\\index{dyadic Green's function}. To illustrate this idea, we can expand the current source of the dipole into transverse and longitudinal parts by\n\\begin{align}\n\\mathbf{J}(\\br) &= \\mathbf{J}_T(\\br) + \\mathbf{J}_L(\\br),\n\\end{align}\nwhere the transverse and longitudinal current components, $ \\mathbf{J}_T(\\br) $ and $\\mathbf{J}_L(\\br)$, satisfy\n\\begin{align}\n\\nabla\\cdot\\mathbf{J}_T (\\br) &=0,\\\\\n\\nabla\\times \\mathbf{J}_L (\\br) &=0.\n\\end{align}\nThe continuity condition reads\n\\begin{align}\n\\nabla\\cdot\\mathbf{J}=-\\pp{}{t}\\rho.\n\\end{align}\nUnder the Coulomb gauge ($ \\nabla\\cdot \\mathbf{A}=0 $), the transverse and longitudinal currents can then be written as~\\cite{Jackson1975} \n\\begin{align}\n\\mathbf{J}_T &= -\\frac{c}{4\\pi}(\\nabla^2 -\\frac{1}{c^2}\\spp{}{t})\\mathbf{A}\\label{eq:Jt_cg}\\\\\n\\mathbf{J}_L &= \\frac{1}{4\\pi} \\pp{}{t}\\nabla\\phi .\\label{eq:Jl_cg}\n\\end{align}\nNotice that, the longitudinal current equation (Eq.~\\eqref{eq:Jl_cg}) will become purely local for an ideal dipole source, and can be ignored. Therefore, the longitudinal components may only become important for the case with a charged source. Below, we only consider the transverse eigenmode decompositions for our analysis of neutral atoms that can be treated as neutral point dipole sources.\n\n\nA complete set of eigenmodes in the presence of lossless, spatially inhomogeneous dielectric is defined according to the procedure of Glauber and Lewenstein~\\cite{Glauber1991}.  We seek the eigenmodes $\\eigenf(\\mathbf{r})$, indexed by $\\eta$, that satisfy the homogeneous wave equation in the absence of sources, i.e., \\erf{eq:Maxwellwithsource2} for $\\tensor{\\boldsymbol{\\alpha}} = 0$ or Eq.~\\eqref{MaxwellHelmholtz0} with the eigen-wavenumber $k_0 \\rightarrow k_\\eta$.  To do so, one defines functions $\\eigeng(\\mbf{r}) \\equiv n(\\br) \\eigenf(\\mbf{r})$ that form a complete basis, as they are eigenfunctions of the Hermitian operator, $\\mathcal{H}(k_0) = -\\frac{1}{n(\\br)} \\nabla\\times\\nabla\\times \\frac{1}{n(\\br)} + k_0^2$, according to $\\mathcal{H}(k_0)  \\eigeng(\\mbf{r}) = \\lambda_\\eta \\eigeng(\\mbf{r})$. The eigenvalue, $\\lambda_\\eta= (\\omega_0^2-\\omega_\\eta^2)/c^2$, determines the wavenumber for a given mode at frequency $\\omega_\\eta$.  We are interested specifically in the generalized transverse functions satisfying $\\nabla\\cdot [ n(\\mathbf{r}) \\eigeng(\\br) ] = 0$ with eigenvalues $\\lambda_n \\neq 0$ \\cite{Wubs2004}. These fall into two categories, guided ($\\eta = \\mu$) and unguided ($\\eta = \\nu$) modes, which together form a complete, orthonormal set for transverse vector functions,\n\t\\begin{align}\n\t\\int \\mathrm{d}^3\\br \\, \\eigeng^*(\\mbf{r}) \\cdot \\eigengp(\\mbf{r})  = \\int \\mathrm{d}^3\\br \\, n^2(\\br) \\eigenf^* (\\br)\\cdot  \\eigenfp(\\br) =\\delta_{\\eta, \\eta'},\\label{Eq::Orthogonality}\\\\\n\t \\sum_\\eta \\mathbf{g}_\\eta(\\br) \\mathbf{g}_\\eta^*(\\br') =  \\sum_\\mu \\mathbf{g}_\\mu(\\br) \\mathbf{g}_\\mu^*(\\br')  + \\sum_\\nu \\mathbf{g}_\\nu(\\br) \\mathbf{g}_\\nu^*(\\br')  = \\tilde{\\delta}^{(T)}(\\br-\\br') \\unittens, \\label{Eq::Completeness}\n\t\\end{align}\nwhere $\\tilde{\\delta}^{(T)}(\\br-\\br')$ is the delta function for generalized transverse vector fields \\footnote{The functions $\\eigeng(\\br)$ are not strictly transverse because of the spatial variation of the index of refraction, $n(r_\\perp)$.  These modes do, nonetheless, constitute the far-field radiated by the dipole. For further details see Refs. \\cite{Sakoda1996Optical, Wubs2004} }.  It follows that the generalized transverse dyadic Green's function\\index{dyadic Green's function} can be decomposed in terms of the eigenfunctions~\\cite{Sakoda1996Optical, Sondergaard2001}\n\t\\begin{align}\n\t\t\\tensor{\\mathbf{G}}{}^{(T)}(\\br,\\br'; \\omega_0) &= -4\\pi \\sum_{\\eta} \\frac{  \\omega_0^2 \\eigenf (\\br) \n\\eigenfp^* (\\br')}{\\omega_0^2-\\omega_\\eta^2},\n\t\\end{align}\nwhere the eigenvalues appear as $\\omega_\\eta^2 = c^2 k_\\eta^2$.  The sum includes both guided and unguided contributions. That is,\n\\begin{align}\n\\tensor{\\mathbf{G}}{}^{(T)}(\\br,\\br'; \\omega_0) = \\tensor{\\mathbf{G}}_{gyd}(\\br,\\br'; \\omega_0)+\\tensor{\\mathbf{G}}_{ung}(\\br,\\br'; \\omega_0),\n\\end{align}\nwhere $ \\tensor{\\mathbf{G}}_{gyd} $ is the guided-mode-induced dyadic Green's function, and $ \\tensor{\\mathbf{G}}_{ung} $ the unguided-mode-induced dyadic Green's function\\index{dyadic Green's function}.\n\n\\begin{sloppypar}\nFor the dielectric waveguides we are interested in, the guided modes are $\\mathbf{f}_\\mu (\\br) = \\mathbf{u}_\\mu (\\br_\\perp) e^{i\\beta z}/\\sqrt{2 \\pi}$, with indices $\\mu=\\{\\omega,j,\\beta p\\}$ for the $j$th guided mode with propagation constant $\\beta$ at frequency $\\omega_\\mu=\\omega(\\beta)$ and polarization $p$.  The transverse mode functions are normalized according to $\\int d^2 \\mbf{r}_\\perp \\, n^2(r_\\perp)\\mathbf{u}^*_\\mu (\\br_\\perp) \\cdot \\mathbf{u}_{\\mu'} (\\br_\\perp)\\big|_{\\beta = \\beta'} = \\delta_{j,j'}\\delta_{p,p'}$ and have the dimension of $1/\\sqrt{A}$ \\cite{LeKien2014}. Similarly, one can define the transverse unguided modes in a similar way with indices $ \\nu=\\{\\omega,\\beta,m,p \\} $, where $ m=0,\\pm 1, \\pm 2,\\cdots $ is the mode index, and $ p=\\pm $ indicates the polarization patterns. The unguided modes, $ \\mathbf{u}_\\nu (\\br_\\perp) $, are normalized according to $ \\int\\mathrm{d}^2\\br_\\perp n^2(\\br_\\perp)\\left[\\mathbf{u}_{\\nu}(r\\!_\\perp )\\cdot\\mathbf{u}_{\\nu'}^*(r\\!_\\perp )\\right]_{\\beta=\\beta',m=m'} =\\delta(\\omega-\\omega')\\delta_{pp'} $. \n\\end{sloppypar}\n\nWe consider nanophotonic waveguides that support only the lowest $ j=1 $ fundamental guided modes at the relevant frequency $\\omega_0$, and hence we can drop the $ j $ index.  In this case there are four guided modes: two polarizations $p$, each with propagation constant $\\beta(\\omega_0) = \\pm\\beta_0$ corresponding to forward and backward propagation.  The guided mode contribution to the dyadic Greens function is then \n\t\\begin{equation} \\label{Eq::GreensEigenmodes}\n\t\t\\tensor{\\mathbf{G}}\\!_{gyd}(\\br,\\br'; \\omega_0) \\!=\\!\\! \\int_{\\!-\\infty}^\\infty\\!\\!\\!\\! \\mathrm{d} \\beta \\!\\sum_{p}\\! \n\\frac{-2\\omega_0^2}{\\omega_0^2\\!\\!-\\!\\omega^2(\\beta)} \\mathbf{u}_\\mu (\\br\\!_\\perp)\\mathbf{u}^*_\\mu \n(\\br_{\\!\\perp}^\\prime) e^{i\\beta(\\!z\\!-\\!z'\\!)},\n\t\\end{equation}\nand the unguided mode contribution part of the dyadic Green's function\\index{dyadic Green's function} can be given by \n\\begin{align}\\label{Eq::GreensunguidedEigenmodes}\n\\tensor{\\mathbf{G}}_{ung}(\\br,\\br'; \\omega_0) \\!=\\!\\! \\int_{\\!-\\infty}^\\infty\\!\\!\\!\\! \\mathrm{d} \\beta \\!\\sum_{m,p}\\! \n\\frac{-2\\omega_0^2}{\\omega_0^2\\!\\!-\\!\\omega^2(\\beta)} \\mathbf{u}_\\nu (\\br\\!_\\perp)\\mathbf{u}^*_\\nu \n(\\br_{\\!\\perp}^\\prime) e^{i\\beta(\\!z\\!-\\!z'\\!)},\n\\end{align}\nwhere $ \\omega(\\beta)$ is the frequency of the mode for a given $\\beta$. \nBased on the division of the guided and unguided modes we have discussed in Sec.~\\ref{sec:eigenmodesofwaveguides}, the guided modes only exist when $ n_2k_0<|\\beta|<n_1k_0 $ with the sign of $ \\beta $ indicating the direction of propagation, and the unguided modes exist when $ -n_2k_0<\\beta<n_2k_0 $. Therefore, we can transfer the integration over $ \\beta $ into a contour integral around discrete poles within regions of $ (-n_1k_0,-n_2k_0) $ and $ (n_2k_0,n_1k_0) $ for the guided-mode Green's function, and an integration from $ -n_2k_0 $ to $ n_2k_0 $ for the unguided-mode Green's function using a similar trick discussed in Appendix~\\ref{sec:boundrad} and illustrated in Fig.~\\ref{fig:integralpaths} for a lossless waveguide. \n\nWe first focus here on the guided mode contribution to the Green's function. \nIn general, we define $v_g= \\vert d\\omega/d\\beta \\vert_{\\beta=\\beta_0}$ as the group velocity at $\\omega_0$ so that the dispersion expansion of $ \\omega_\\beta $ around $ \\omega_0 $ yields \n\\begin{align}\n\\omega(\\beta) &=\\omega_0 + \\dd{\\omega_\\beta}{\\beta}(\\beta-b\\beta_0) +\\cdots = \\omega_0 + bv_g(\\beta-b\\beta_0) +\\cdots\\\\\n\\Rightarrow \\omega(\\beta) - \\omega_0 &= bv_g(\\beta-b\\beta_0) +\\cdots\n\\end{align}\nwhere we have explicitly separated the propagation direction $b=\\pm$ from the propagation constant $ \\beta $ and set $ \\beta $ non-negative in the $ \\omega(\\beta) $ equations above. \nFor $z>z'$ ($z<z'$), the contribution of the guided modes to the retarded (causal) Green's function is found by the \nusual displacement of the pole on the positive (negative) $\\beta$ axis into the upper (lower) half of \nthe complex plane. The result for $z \\neq z'$ is \\cite{MangaRao2007Single}\n\t\\begin{align} \n\t\t\\tensor{\\mathbf{G}}^{(+)}_{gyd}(\\br,\\br'; \\omega_0) = &2\\pi i \\sum_{b,p}  {\\rm Res}\\vert_{\\beta =b\\beta_0} \n\\left[\\frac{-2 \\omega_0^2 }{ \\omega_0^2-\\omega^2(\\beta)}\\right]  \\mathbf{u}_{b\\beta_0, p} \n(\\br_\\perp)\\mathbf{u}^*_{b\\beta_0, p} (\\br_{\\perp}^\\prime)e^{ib \\beta_0 (z-z')} \\nonumber \\\\\n= & 2\\pi i \\frac{\\omega_0}{v_g } \\sum_{b,p} \\mathbf{u}_\\mu (\\br_\\perp)\\mathbf{u}^*_\\mu\n(\\br_{\\perp}^\\prime) e^{i b\\beta_0(z-z')} \\Theta \\big( b(z-z') \\big), \\label{Eq::GreensGuided_general}\n\t\\end{align}\nwhere $\\Theta \\big( b(z-z') \\big)$ is a Heaviside function enforcing causality for the forward- and backward-scattered fields. In the second line, we have suppressed the label $\\beta_0$ as it is implicit in the definition of the guided modes at frequency $\\omega_0$. \n\nRadiative properties of a scatterer (the decay rate and energy level shift) are determined by evaluating the dyadic Green's function at the source point $\\mbf{r} = \\mbf{r}'$ \\cite{Fussell2005Decay}.  However, for $z=z'$ we cannot close the contour. Instead, we expand the resonant denominator in \\erf{Eq::GreensEigenmodes} with the poles moved to yield the retarded (causal) response,\n\\begin{equation}\n\\frac{1}{(\\omega_0+i\\epsilon)^2-\\omega^2(\\beta)}=\\frac{1}{2 \\omega(\\beta)}\\left[ \\frac{1}{\\omega_0+ i \n\\epsilon - \\omega(\\beta)} - \\frac{1}{\\omega_0+ i \\epsilon + \\omega(\\beta)} \\right],\n\\end{equation}\n and employ the usual distribution identities \\cite{Sondergaard2001},\n\\begin{equation}\n\\lim_{\\epsilon \\rightarrow 0_+} \\frac{1}{\\omega_0 + i \\epsilon \\mp \n\\omega(\\beta)}=\\mathcal{P}\\left[\\frac{1}{\\omega \\mp \\omega(\\beta)} \\right] + i \\pi \\delta (\\omega_0 \\mp \n\\omega(\\beta)).\n\\end{equation}\nOnly the positive-frequency component contributes to the $\\delta$-function, and it follows that the Green's function tensor at $\\br = \\br'$ is imaginary, which determines the resonant Purcell enhancement of spontaneous emission into the guided modes~\\cite{Dung2000, Fussell2005Decay, Chen2010Finite} and can be given by\n\t\\begin{equation}\\label{Eq::ImGreenLocal_general}\n\t\t\\tensor{\\mathbf{G}}^{(+)}_{gyd}(\\br',\\br'; \\omega_0=\\omega_{eg}) = i\\pi \\frac{\\omega_{eg}}{v_g } \\sum_{b, p} \n\t\t\\mathbf{u}_\\mu (\\br_{\\!\\perp}^\\prime)\\mathbf{u}^*_\\mu (\\br_{\\!\\perp}^\\prime),\n\t\\end{equation}\nwhere $\\omega_{eg}$ is the resonance frequency of the atomic scatterer.  The energy level shift of the scatterer due to its proximity to the dielectric is found from the real part of the Green's function at $\\br = \\br'$. \nTo find the total modified spontaneous emission rate and energy level shift, one must include the unguided modes \\cite{LeKien2005a} or employ other representations of the Green's function \\cite{Klimov2004}.  \n\nApplying a similar process, we provide--without details of proofs--the unguided mode contribution to the positive-frequency Green's function tensor to be~\\cite{LeKien2005a}\n\\begin{align}\n\\GFT_{ung}^{(+)} (\\br,\\br';\\omega_0)&= i2\\pi \\omega_0  \\int_{-n_2k_0}^{n_2k_0}\\!\\!\\!\\mathrm{d}\\beta\\sum_{b,m,p} \\mathbf{u}_\\nu (\\br_{\\!\\perp}^\\prime)\\mathbf{u}^*_\\nu (\\br_{\\!\\perp}^\\prime) e^{i b\\beta(z-z')} \\Theta \\big( b(z-z') \\big)\n\\end{align} \nfor $ z\\neq z' $; and for $ \\br=\\br' $, the imaginary part of the Green's function due to unguided modes can be given by\n\\begin{align}\n\\im\\left[\\GFT_{ung}^{(+)}(\\br',\\br';\\omega_0=\\omega_{eg})\\right] &= \\pi \\omega_{eg}  \\int_{-n_2k_0}^{n_2k_0}\\!\\!\\!\\mathrm{d}\\beta\\sum_{m,p} \\mathbf{u}_\\nu (\\br_{\\!\\perp}^\\prime)\\mathbf{u}^*_\\nu (\\br_{\\!\\perp}^\\prime).\n\\end{align} \nWith these expressions of Green's function components, we can calculate the modified spontaneous emission rates of an optical dipole next to a nanofiber (which will be discussed later in this chapter). Our results recover the spontaneous emission rate calculations presented in Ref.~\\cite{LeKien2005a} based on the Heisenberg-Langevin equations of quantum dynamics, for example. \n\nThe eigenmode decomposition approach of solving dyadic Green's function works really well if the eigenmodes of the waveguide are known, especially for the guided mode contribution part. The guided modes of a waveguide can either be solved analytically or numerically, which provides an efficient and accurate method of decomposing the dyadic Green's function\\index{dyadic Green's function} into the guided mode contribution part, which is most relevant to the QND measurement study we are going to discuss in the next chapter. However, since there is an infinite number of unguided modes, we usually have to cut off the sum of all unguided modes to a finite set as an approximation, which makes the calculation of the unguided-mode-induced dyadic Green's function not exact--especially when the detection position is far from the surface of the waveguide. \n\nWe verified the equivalence of the two methods by numerically comparing the Green's tensors and also the derived spontaneous emission rates using the two methods for the nanofiber case first, and then partially for the \\SWG case. We provide some of the details and data files in Ref.~\\cite{Qi2018i2000s/simnanophotonics}. \n\nCombining these two methods also makes the decomposition of the dyadic Green's function flexible and accurate. For instance, some numerical techniques of calculating radiation problems (like BEM) diverge at the poles due to guided modes for a lossless medium, and one has to artificially add some loss to the medium to transfer the guided-mode-induced Green's function calculation to be an integral around the poles. Given the limited width and finite data points sampled around the poles, the radiation problem solver cannot simultaneously guarantee the precision and efficiency for the guided mode contribution. In this case, using the eigenmode decomposition approach to calculate the guided mode part of the dyadic Green's function while using the radiation problem solver to calculate the unguided mode contribution might be a good solution in practice. \nFor some other numerical solvers for the radiation problems, like the FDTD method, can only calculate the total dyadic Green's function\\index{dyadic Green's function}. To separate out the unguided mode contribution, one can subtract the total dyadic Green's function by the guided mode contribution computed using the eigenmode decomposition approach if the guided modes are known. \n\n\\subsection{Example Green's function of the nanofiber}\n\\includefig{../media/Figs/GFTz0x2a}{0.95\\linewidth}{The absolute value of the total dyadic Green's function's elements $ G_{ij}(\\br,\\br') $ in the $ z=0 $ plane. The calculation follows Appendix~\\ref{sec:boundrad}. A dipole source (marked as $ \\times $) is placed at $\\br'=(r^\\prime_\\perp=2a,\\phi'=0,z'=0) $ position or $ r'_\\perp=2a $ from the fiber axis, where $a=225 $ nm is the radius of the nanofiber. The position of the observer is chosen to be in the $ z=0 $ plane. The wavelength is set to be $ \\lambda=852 $ nm, which is the D2 line of cesium atoms. All values are normalized to the vacuum Green's function, $ G_0$, by Eq.~\\eqref{eq:G0}. The value labeled for each subplot is the maximum value of the corresponding Green's function tensor element among all data points in the transverse plane excluding the dipole position. The unguided modes are calculated up to $ |m|=8 $.}\n{$\\mathrm{abs}{\\left[ G_{ij}(\\mathbf{r},\\mathbf{r}')\\right]}$ contour plots in the transverse plane with $ r^\\prime_\\perp=2a $ and $ z=0\\lambda$.}{!tbp}\n\n\\includefig{../media/Figs/GFTz1x2a}{0.95\\linewidth}{The absolute value of the total dyadic Green's function's elements $ G_{ij}(\\br,\\br') $ in the $ z=\\lambda $ plane. Same as Fig.~\\ref{../media/Figs/GFTz0x2a} but observed in the $ z=\\lambda $ plane.}\n{$\\mathrm{abs}{\\left[ G_{ij}(\\mathbf{r},\\mathbf{r}')\\right]}$ contour plots in the transverse plane with $ r^\\prime_\\perp=2a $ and $ z=\\lambda$.}{!htbp}\n\n\\includefig{../media/Figs/GFTz2x2a}{0.95\\linewidth}{The absolute value of the total dyadic Green's function's elements $ G_{ij}(\\br,\\br') $ in the $ z=2\\lambda $ plane. Same as Fig.~\\ref{../media/Figs/GFTz0x2a} but observed in the $ z=2\\lambda $ plane.}\n{$\\mathrm{abs}{\\left[ G_{ij}(\\mathbf{r},\\mathbf{r}')\\right]}$ contour plots in the transverse plane with $ r^\\prime_\\perp=2a $ and $ z=2\\lambda$.}{!tbp}\n\n\\includefig{../media/Figs/GFTz5x2a}{0.95\\linewidth}{The absolute value of the total dyadic Green's function's elements $ G_{ij}(\\br,\\br') $ in the $ z=5\\lambda $ plane. Same as Fig.~\\ref{../media/Figs/GFTz0x2a} but observed in the $ z=5\\lambda $ plane.}\n{$\\mathrm{abs}{\\left[ G_{ij}(\\mathbf{r},\\mathbf{r}')\\right]}$ contour plots in the transverse plane with $ r^\\prime_\\perp=2a $ and $ z=5\\lambda$.}{!tbp}\n\n\\includefig{../media/Figs/GFTz10x2a}{0.95\\linewidth}{The absolute value of the total dyadic Green's function's elements $ G_{ij}(\\br,\\br') $ in the $ z=10\\lambda $ plane. Same as Fig.~\\ref{../media/Figs/GFTz0x2a} but observed in the $ z=10\\lambda $ plane.}\n{$\\mathrm{abs}{\\left[ G_{ij}(\\mathbf{r},\\mathbf{r}')\\right]}$ contour plots in the transverse plane with $ r^\\prime_\\perp=2a $ and $ z=10\\lambda$.}{!tbp}\n\n\\includefig{../media/Figs/GFTz100x2a}{0.95\\linewidth}{The absolute value of the total dyadic Green's function's elements\\index{dyadic Green's function} $ G_{ij}(\\br,\\br') $ in the $ z=100\\lambda $ plane. Same as Fig.~\\ref{../media/Figs/GFTz0x2a} but observed in the $ z=100\\lambda $ plane. At such a far distance, the patterns are very close to the guided mode contribution components to be plotted in the next figure.}\n{$\\mathrm{abs}{\\left[ G_{ij}(\\mathbf{r},\\mathbf{r}')\\right]}$ contour plots in the transverse plane with $ r^\\prime_\\perp=2a $ and $ z=100\\lambda$.}{!tbp}\n\n\\includefig{../media/Figs/GFTgz0x2a}{0.95\\linewidth}{The absolute value of the \\emph{guided-mode-induced} dyadic Green's function's elements\\index{dyadic Green's function} $ G^g_{ij}(\\br,\\br') $ observed in the transverse plane. Settings are the same as Fig.~\\ref{../media/Figs/GFTz0x2a} but for the guided mode contribution part only. Absolute values of the elements are the same for all $ z $ slices. For the purpose of comparison, the Green's function elements are plotted with only the forwarding propagation part.}\n{$\\mathrm{abs}{\\left[ G_{ij}^g(\\mathbf{r},\\mathbf{r}')\\right]}$ contour plots in the transverse plane with $ r^\\prime_\\perp=2a $.}{!tbp}\n\nNow, we apply the radiation problem solver to calculate the elements of the dyadic Green's function\\index{dyadic Green's function} of an atom trapped near a nanofiber at $ r'\\!_\\perp=2a $ from the fiber axis, and see if the unguided mode contributions vanish after a long propagation distance. The contour plots of the absolute values of the Green's function tensor elements are shown in Figs.~\\ref{../media/Figs/GFTz0x2a} through~\\ref{../media/Figs/GFTz100x2a} for slices at $ z=0,1,2,5,10, $ and $ 100\\lambda $ with a dipole source fixed at $ r'\\!_\\perp=2a $ position on the $ x $-axis. The maximum values of each tensor element are also notated in the plots normalized to the imaginary part of the scalar Green's function in the vacuum ($ G_0 $ defined in Eq.~\\eqref{eq:G0}, which indicates how the unguided mode contributions dissipate along the propagation direction. Note that, since the Green's function diverges at the source position, to find the maximum values shown in the plots we have excluded the source position. \n\nWe see the maximum value oscillates a little bit in the near distance, due to the interference between the free-dipole radiation and the scattered field from the fiber interface, and then decays with the remaining amplitude inversely proportional to the propagation distance as the scattered field dies out in a long distance.\nThis only leaves over the free-dipole radiation and the guided mode contributions in a long distance. To demonstrate that the pattern left in a distant $ z $ slice is mainly the guided mode contribution, we plot the guided mode contribution in Fig.~\\ref{../media/Figs/GFTgz0x2a}, which has a constant amplitude over the $ z $ slices. At $ z=10\\lambda $ (Fig.~\\ref{../media/Figs/GFTz10x2a}), the total Green's function tensor has already been very close to the bare forward-propagating guided-mode Green's function tensor. \nAt $ z=100\\lambda $ (Fig.~\\ref{../media/Figs/GFTz100x2a}), the unguided modes have essentially completely dissipated into free space. \nConsidering the photon detectors to measure the transported signal being at least centimeters away from the nanofiber region, we can safely ignore the influence of the unguided field to the measurement results. \n\nIn sum, given the two approaches, we can compute the dyadic Green's function\\index{dyadic Green's function} for arbitrary nanophotonic waveguides and decompose the total Green's function into its guided and unguided mode components. The strategies of the computation and the decomposition only depend on the availability of software and computer resources, and one can combine the two approaches for fast and accurate calculations. We also show that the unguided modes does not propagate long enough to affect the measurement signal. In the next section, we will assume the dyadic Green's function is known and study the dispersive response theory of the guided light in a semi-classical scenario.\n\n\n\\section{Phase shift and polarizability transformation}\nNow, we can formulate the theory of light response due to the presence of a waveguide next to atoms. We assume that the atoms interact with the light equally for all polarization states of the light, that is, to treat the atomic polarizability as a scalar in this section, and study the influence of a nanophotonic waveguide, as an example, by comparing the light response to the free-space case. A generalized light response theory including a tensor polarizability will be drawn in Chapter~\\ref{chap:birefringence}. \nAs a shorthand, we denote $ \\GFT_g(\\br,\\br')\\equiv \\GFT_{gyd}(\\br,\\br') $ and $ \\GFT_r(\\br,\\br')\\equiv\\GFT_{ung}(\\br,\\br') $.\n\nWe start with the electric field defined in Eq.~\\eqref{eq:EGFTnatoms}, and rewrite the output field by only considering the guided-mode dyadic Green's function\\index{dyadic Green's function} responding from a single atom source placed at $ \\br' $. The output field\n\\begin{align}\n\\mathbf{E}(\\br) & = \\mathbf{E}_0(\\br) +\\alpha \\GFT_g(\\br,\\br')\\cdot\\mathbf{E}_0(\\br'),\n\\end{align}\nwhere $ \\mathbf{E}_0(\\br) $ is the input field propagating in a bare waveguide. We have also set the polarizability of the atom as a scalar, $ \\alpha $. \n\nAs a concrete example, we can consider the case that the atom is placed at $ z'=0 $ and $ \\phi'=0 $ (along the $ H $ axis), and the input field is the right circularly polarized $ p=+,\\,b=+ $ \\HE\\, forward propagating mode of a nanofiber\n\\begin{align}\n\\mathbf{E}_0(\\br) &= E_0n_{e\\!f\\!f} \\mathbf{u}_{p=+,b=+} (\\br) = E_0n_{e\\!f\\!f} \\mathbf{u}_{++} (r\\!_\\perp)e^{i\\phi+i\\beta_0 z}. \n\\end{align}\nWe have defined an effective index of refraction of the waveguide medium based on the normalization condition of the guided modes, Eq.~\\eqref{eq:eigenmodeorthog},\n\\begin{align}\nn_{e\\!f\\!f} = \\sqrt{\\frac{\\int\\! \\mathrm{d}^2\\br\\!_\\perp n^2 (\\br_\\perp) {\\mathbf{u}_{p,b}}^*(\\br_\\perp)\\cdot \\mathbf{u}_{p,b}(\\br_\\perp) }{\\int\\! \\mathrm{d}^2\\br\\!_\\perp {\\mathbf{u}_{p,b}}^*(\\br_\\perp)\\cdot \\mathbf{u}_{p,b}(\\br_\\perp)}}= \\frac{1}{\\sqrt{\\int\\! \\mathrm{d}^2\\br\\!_\\perp {\\mathbf{u}_{p,b}}^*(\\br_\\perp)\\cdot \\mathbf{u}_{p,b}(\\br_\\perp)}}\n\\end{align}\nso that $ n^2_{e\\!f\\!f}\\int\\! \\mathrm{d}^2\\br\\!_\\perp  {\\mathbf{u}_{p,b}}^*(\\br_\\perp)\\cdot \\mathbf{u}_{p,b}(\\br_\\perp)=1 $.\nThe output field in the forward direction at $ z\\ge 0 $ can be written as\n\\begin{align}\n\\mathbf{E}(\\br) &= E_0n_{e\\!f\\!f}\\mathbf{u}_{++} (\\br) + \\sum_{m,f=\\pm } C_{pb} E_0n_{e\\!f\\!f} \\mathbf{u}_{p,b}(\\br),  \n\\end{align}\nwhere the projection coefficients are \n\\begin{align}\nC_{pb} &=  \\alpha \\!\\int\\! \\mathrm{d}^2r\\!_\\perp n^2_{e\\!f\\!f} {\\mathbf{u}_{p,b}}^*(\\mathbf{r},z)\\cdot \\GFT_g(\\br,\\br') \\!\\cdot\\! \\mathbf{u}_{++}(\\mathbf{r}^\\prime,z')\\\\\n&=  \\alpha \\!\\int\\! \\mathrm{d}^2r\\!_\\perp n^2_{e\\!f\\!f} {\\mathbf{u}_{p,b}}^*(\\mathbf{r}\\!_\\perp)\\cdot \\GFT_g(\\br,\\br') \\!\\cdot\\! \\mathbf{u}_{++}(\\mathbf{r}^\\prime\\!_\\perp).\n%&=  \\alpha \\!\\int\\! \\mathrm{d}^2r\\!_\\perp n^2_{e\\!f\\!f} {\\mathbf{u}_{p,b}}^{\\!\\!*}(r\\!_\\perp)\\!\\cdot\\! \\GFT_g(\\br,\\br') \\!\\cdot\\! \\mathbf{u}_{++}(r^\\prime\\!\\!_\\perp)e^{i\\beta_0(z'-bz)+i(\\phi'-p\\phi)}.\n\\end{align}\nUsing the transverse mode decomposition of the dyadic Green's function\\index{dyadic Green's function}, Eq.~\\ref{Eq::GreensGuided_general}, these coefficients become\n\\begin{align}\nC_{pb} &= i2\\pi n_gk_0\\alpha \\!\\int\\! \\mathrm{d}^2r\\!_\\perp n^2_{e\\!f\\!f} {\\mathbf{u}_{p,b}}^*(\\mathbf{r}\\!_\\perp)\\cdot\\!\\!\\!\\!\\!\\! \\sum_{p',b'=\\pm}\\!\\!\\!\\! \\left[\\mathbf{u}_{p',b'}(\\mathbf{r}\\!_\\perp){\\mathbf{u}_{p',b'}}^*(\\mathbf{r}^\\prime\\!_\\perp) \\right]\\!\\!\\cdot\\! \\mathbf{u}_{++}(\\mathbf{r}^\\prime\\!_\\perp)\\nonumber\\\\\n&\\quad\\quad\\quad \\times \\Theta(b'(z-z')) \\\\%e^{ib'\\beta_0(z-z')} e^{i\\beta_0(z'-bz)}\\\\\n&= i2\\pi n_gk_0\\alpha  {\\mathbf{u}_{p,b}}^*(r'_{\\!\\perp})\\cdot \\mathbf{u}_{++}(r'_{\\!\\perp})e^{i\\beta_0 (1-b)z'+i(1-p)\\phi'}.\n\\end{align}\nNotice that, the phase factor in the exponential part depends on the position of the atom as well as the mode index $ (p,b) $. If $ p,b\\neq + $, there will be a fast beating term in the projection coefficient, and may be averaged out in some cases. If the atom is positioned along the $ \\phi'=0 $ and $ z'=0 $ line, the phase factor part will vanish. \n%The projection coefficients can be written as \n%\\begin{align}\n%C_{mf} &\\approx C_m\\equiv  i\\pi k_0 n_g\\alpha  \\mathbf{u}^*_m(\\br'_{\\!\\perp})\\cdot \\mathbf{u}_1(\\br'_{\\!\\perp})\\\\\n%&= i\\pi k_0 n_g\\alpha  \\mathbf{u}^*_m(r'_{\\!\\perp})\\cdot \\mathbf{u}_1(r'_{\\!\\perp})e^{i(1-m)\\phi'}.\n%\\end{align}\n\nTherefore, the emerged forwarding $ p=- $ mode has an amplitude \n\\begin{align}\nC_{-+}=i2\\pi n_gk_0\\alpha  {\\mathbf{u}^1_{-1}}^*(r'_{\\!\\perp})\\cdot \\mathbf{u}_1^1(r'_{\\!\\perp})e^{i2\\phi'}.\n\\end{align}\nSimilarly, the backwarding $ p=+ $ and $ p=- $ modes have amplitudes \n\\begin{align}\nC_{+-} &=i2\\pi n_gk_0\\alpha  {\\mathbf{u}^{-1}_1}^*(r'_{\\!\\perp})\\cdot \\mathbf{u}_1^1(r'_{\\!\\perp})e^{i2\\beta_0 z'},\\\\\nC_{--} &=i2\\pi n_gk_0\\alpha {\\mathbf{u}^{-1}_{-1}}^*(r'_{\\!\\perp})\\cdot \\mathbf{u}_1^1(r'_{\\!\\perp})e^{i2\\beta_0 z'+i2\\phi'}.\n\\end{align}\n\nThe output $ p=+ $ \\HE\\, mode component in presence of the atom in the forward direction is then given by\n\\begin{align}\n\\mathbf{E}_+(\\br) &= (1+C_{++})E_0n_{e\\!f\\!f}\\mathbf{u}_{++} (\\br)\\\\\n&=\\left[1 +i2\\pi n_gk_0\\alpha  | \\mathbf{u}_{++}(r'_{\\!\\perp})|^2 \\right] E_0n_{e\\!f\\!f}\\mathbf{u}_{++} (\\br)\\\\\n&\\approx \\exp\\left[i2\\pi n_gk_0\\alpha  | \\mathbf{u}_{++}(r'_{\\!\\perp})|^2 \\right] E_0n_{e\\!f\\!f}\\mathbf{u}_{++} (\\br)\\\\\n&= te^{i\\delta\\phi}E_0n_{e\\!f\\!f}\\mathbf{u}_{++} (\\br), \n\\end{align}\nwhere the change in amplitude is \n\\begin{align}\nt=\\exp\\left[-\\im[C_{++}]\\right]=\\exp\\left[ -2\\pi n_g k_0 \\Im[\\alpha]  | \\mathbf{u}_{++}(r'_{\\!\\perp})|^2 \\right],\n\\end{align}\nand the phase shift is\n\\begin{align}\n\\delta\\phi &= \\re[C_{++}]\\\\\n&=2\\pi n_gk_0\\re[\\alpha]  | \\mathbf{u}_{++}(r'_{\\!\\perp})|^2\\\\\n&= \\re[\\alpha] 2\\pi k_0 \\{ n_g  | \\mathbf{u}_{++}(r'_{\\!\\perp})|^2\\}\\\\\n&= \\re[\\alpha] \\frac{2\\pi k_0}{A_{e\\!f\\!f}^{\\rm nanofiber}},\\label{eq:deltaphi_alphaA}\n\\end{align}\nwhere the symbols $ \\im[\\cdot] $ and $ \\re[\\cdot] $ indicate the imaginary and real parts of the variable inside; we have also defined an effective mode area at the atom position by $ A_{e\\!f\\!f}^{\\rm nanofiber}=1/\\left[ n_g| \\mathbf{u}_{++}(r'_{\\!\\perp})|^2\\right] $. \n\nSimilar expressions of the output field $ \\mathbf{E}_{-}(\\br) $, phase shift and amplitude attenuation for the field coupling into the forward propagating $ p=- $ \\HE\\, mode can be derived.  \n%\\begin{align}\n%\\mathbf{E}_{-}(\\br) &=  i2\\pi k_0 n_g\\alpha  \\mathbf{u}^*_{-1}(r'_{\\!\\perp})\\cdot \\mathbf{u}_{-+}(r'_{\\!\\perp})e^{i2\\phi'}E_0n_{e\\!f\\!f}\\mathbf{u}_{-+}(\\br).\n%\\end{align}\n$ \\mathbf{E}_{+}(\\br) $ and $\\mathbf{E}_{-}(\\br)$ define the transformation of polarization of the forward-propagating guided light. \n\nAlthough we have taken the example of a circularly polarized light as the input, the results above can be generalized to a linearly polarized input as well; we only need to change the polarization labels to the corresponding linear polarization states. Below, we will first estimate the enhancement of phase shifts of one guided mode, and then take a look at the linear-polarization-input case and calculate the polarization transformation relations.  \n\n\n\n\\subsection{Compare to the free-space case}\n\nTo further compare our results with the free-space atom-light interaction case, we rewrite our equations above following the commonly used quantities and conventions (see summary in Appendix~\\ref{chap:summaryofatomicphysicsformulas})~\\cite{Baragiola2014Open}. \nWe define the polarizability and the atomic decay rates due to the coupling to the guided modes of a nanofiber, $ \\Gamma^{1D}_{\\rm nanofiber} $, in the dispersive regime as below \n\\begin{align}\n\\alpha &=-\\frac{|d_{eg}|^2}{\\hbar \\Delta}, \\,\\, (\\Delta=\\omega-\\omega_{eg}=\\omega-\\omega_0)\\\\\n\\Gamma^{1D}_{\\rm nanofiber} &=2\\pi \\frac{|d_{eg}|^2}{\\hbar A_{e\\!f\\!f}^{\\rm nanofiber}}\\left(\\frac{\\omega_0}{c} \\right),\n\\end{align}\nwhere $ d_{eg} $ is the dipole moment of the atom, and we have ignored the imaginary part of the atomic polarizability in the dispersive regime~\\cite{Deutsch2010a}.\nWe recall the natural linewidth of the atom (see Eq.~\\eqref{eq:naturallinewidth})\n\\begin{align}\n\\Gamma_0 &= \\frac{4}{3} \\left( \\frac{\\omega_0}{c}\\right)^3 \\frac{|d_{eg}|^2}{\\hbar}\n\\end{align}\nand the resonant cross section of the atom \n\\begin{align}\n\\sigma_0 &= \\frac{3\\lambda^2}{2\\pi}=\\frac{6\\pi}{k_0^2}=\\frac{6\\pi c^2}{\\omega_0^2}.\n\\end{align}\nWe can then rewrite the modified decay rate due to the coupling to the guided nanofiber modes by\n\\begin{align}\n\\Gamma^{1D}_{\\rm nanofiber} &= \\frac{1}{4} \\frac{\\sigma_0}{A_{e\\!f\\!f}^{\\rm nanofiber}} \\Gamma_0.\n\\end{align}\n\nPlugging the equations above into Eq.~\\eqref{eq:deltaphi_alphaA}, we find that \n\\begin{align}\\label{phaseshiftGamma1D_nanofiber}\n\\delta\\phi^{\\rm nanofiber} &= -2\\pi \\frac{|d_{eg}|^2}{\\hbar \\Delta} \\frac{\\omega_0}{cA_{e\\!f\\!f}^{\\rm nanofiber}}=-\\frac{\\Gamma^{1\\!D}_{\\rm nanofiber}}{\\Delta}.\n\\end{align}\n\nNow, we consider a trapped atom probed by a Gaussian beam of the TEM$_{00}$ mode (see Appendix~\\ref{chap:paraxialapproximation}). We assume that the beam is focused with a typical waist radius $ w_0=10 \\,\\mu$m so that the atom-light coupling is very strong. Based on the well known results (see Eqs.~\\eqref{Gamma1DGammavac_appendix} and~\\eqref{phaseshiftGamma1D}), we have similar equations for the modified decay rate of the atom and the phase shift for the Gaussian beam case:\n\\begin{align}\n\\Gamma^{1D}_{\\rm GaussianBeam} &= \\frac{1}{4} \\frac{\\sigma_0}{A_{e\\!f\\!f}^{\\rm GaussianBeam}}\\Gamma_0,\\\\\n\\delta\\phi &= -\\frac{\\Gamma^{1\\!D}_{\\rm GaussianBeam}}{\\Delta},\n\\end{align}\nwhere the effective mode area at the atom position for the Gaussian beam, $ A_{e\\!f\\!f}^{\\rm GaussianBeam} $, is given by\n\\begin{align}\nA_{e\\!f\\!f}^{\\rm GaussianBeam} = \\frac{A}{|\\mathbf{u}_{00}(r'_\\perp)|^2},\n\\end{align}\n$ A=\\frac{\\pi w_0^2}{2} $ being the mode area of the Gaussian beam. \n\n\nHence, the relative atom-light coupling strength enhancement indicated by the mode phase shift due to the presence of a nanofiber versus the Gaussian laser beam can be given by\n\\begin{align}\n\\frac{\\delta\\phi^{\\rm nanofiber}}{\\delta\\phi^{\\rm GaussianBeam}} &=\\frac{\\Gamma^{1D}_{\\rm nanofiber}}{\\Gamma^{1D}_{\\rm GaussianBeam}}=\\frac{A_{e\\!f\\!f}^{\\rm GaussianBeam}}{A_{e\\!f\\!f}^{\\rm nanofiber}}\\\\\n&=  \\!n_g\\! \\frac{A|\\mathbf{u}_\\mu(r_\\perp^{\\rm nanofiber})|^2}{|\\mathbf{u}_{00}(r_\\perp^{\\rm GaussianBeam})|^2}=An_g |\\mathbf{u}_\\mu(r_\\perp^{\\rm nanofiber})|^2,\n\\end{align}\nwhere $ \\mathbf{u}_\\mu (r_\\perp^{\\rm nanofiber}) $ is the input mode for the nanofiber case at the atom position $ r_\\perp^{\\rm nanofiber} $, and $ r_\\perp^{\\rm GaussianBeam} $ is the atom position for the Gaussian beam case.\nIn the last step, we have used the fact that the mode of the Gaussian beam reaches the largest value of $ |\\mathbf{u}_{00}(r_\\perp^{\\rm GaussianBeam})|=1 $ when the atom is placed at the center of the beam waist, which has the strongest electric field. \n\n\\begin{figure}[!tbp]\n\\centering\\makebox[\\textwidth]{\n\\includegraphics[width=0.95\\linewidth]{../media/Figs/RelEnhancement}}\n\\caption[Relative atom-light coupling enhancement by using an optical nanofiber compared to a typical Gaussian beam trap.]{Relative enhancement of the atom-light coupling due to the use of a nanofiber compared to a typical Gaussian beam trap system. For the Gaussian beam system, an atom is placed at the center of the beam waist and the beam waist radius is $ 10\\,\\mu $m. Plotted are the relative phase shift or the modified decay rate as a function of the trapping radial position of the atom in the nanofiber system, where the atom is trapped along the $ H $ direction or the $ x $ axis. The $ H $ mode (red, top), $ V $ mode (blue, bottom) and the circular modes (green, middle) are plotted in the main figure. Inset indicates the coordinate of the atom position relative to the fiber (circle). The probe wavelength is $ \\lambda=895 $ nm for comparison.}\\label{fig:relenhancement}\n\\end{figure}\n\nFigure~\\ref{fig:relenhancement} plots the relative enhancement of the atom-light coupling due to the use of an optical nanofiber ($ a=225 $ nm) as a function of the atom's radial distance to the fiber axis. Different polarization states of the input light is studied in the figure while the atom is trapped along the $ x $ or $ H $ axis. The enhancement value is normalized to the case that the atom is probed at the center point of a Gaussian beam's waist with a typical waist radius $ w_0=10\\,\\mu $m. As shown, the nanofiber enhances the atom-light coupling by $ 30 $--$ 100 $ folds if the atom is trapped at $ r'_\\perp=2a $, depending on the polarization state of the input light. If the atom is moved closer to the fiber surface, the enhancement can be further increased up to a few hundred folds. Note that both $ R $ and $ L $ circular modes of the nanofiber generate the same atom-light coupling strength in this rough model.\n\nSimilar results apply to the \\SWG case. \n\n\n\\bigskip\n\\textbf{The rotation angle on the \\Poincare sphere:}\n%\\textcolor{red}{Diagrams for the configuration of setups...}\n\\begin{figure}[!tbp]\n\\centering\\makebox[\\textwidth]{\n\\includegraphics[width=12cm]{../media/Figs/BirefringenceMeasurement}}\n\\caption[Diagram depicting the polarization rotation measurement with an optical nanofiber.]{Diagram of polarization rotation measurement with an optical nanofiber (brown). The input light is initially polarized along the diagonal direction on the $ xy $ plane. \nThe output polarization state is measured by the differential counting of the photon flux between the $ H $ and $ V $ linear polarization states. The rotated angle on the \\Poincare sphere indicates a birefringence rotation of the guided light.}\\label{fig:birefringencenanofibersetup}\n\\end{figure}\n\nSuppose we launch a quasilinear $ D $ mode to the waveguide, which can be decomposed into two equal-power but orthogonal quasilinear modes, $H$ and $V$. \nSuppose we also place atoms along the major axis of the $H$ mode or the $ x $ axis. \nThe atoms will feel both $ H $ and $ V $ modes in different strengths [see Figs.~\\ref{fig:birefringencenanofibersetup} and~\\ref{fig:Modes_Rot45HV_fiber}]. \nSince the local intensities of the $ H $ and $ V $ modes at the atom positions are different, there will be a differential phase shift between the output $ H $- and $ V $-polarized light components ($ \\mathbf{E}_{H}(\\br) $ and $ \\mathbf{E}_{V}(\\br) $), which generates a birefringence rotation on the \\Poincare sphere. The rotation angle of the output light on the \\Poincare sphere due to a scalar interaction with one atom can be given by\n\\begin{align}\n\\varphi &= \\delta\\phi_H-\\delta\\phi_V= 2\\pi \\frac{\\omega_0}{v_g} \\re[\\alpha] \\left[| \\mathbf{u}_H(r'_{\\!\\perp})|^2- | \\mathbf{u}_V(r'_{\\!\\perp})|^2 \\right]\\\\\n&= -\\sigma_0\\frac{c}{v_g}\\frac{\\Gamma_0}{4\\Delta}\\left[| \\mathbf{u}_H(r'_{\\!\\perp})|^2- | \\mathbf{u}_V(r'_{\\!\\perp})|^2 \\right].\\label{eq:birefringencerotang}\n\\end{align}\n\nFrom Fig.~\\ref{fig:relenhancement}, using the nanofiber, we find that the local $ H $ mode is usually $ 3 $--$ 4 $ folds stronger than the $ V $ mode along the $ x $ axis. \nThis generates a strong birefringence effect even with a scalar polarizability of atoms, and is an otherwise unavailable resource for a free-space interface. \n\n\n%</waveguideinterface>\n\n\n\n\\appendix\n% ########################### Apendix ##########################################\n%<*polarizationstokesvectors>\n\\chapter{Polarization states of light and the Stokes vector representation}\\label{chap:polarizationstokesvectors}\n\\section{Polarization states of light}\n\nIn free space, light is a transverse field. The polarization state of light\\index{polarization} can be fully described by the amplitudes and relative phase of two orthogonal electric field components, $ \\mathbf{E}_x $ and $ \\mathbf{E}_y $:~\\cite{Jackson1975}\n\\begin{subequations}\n\\begin{align}\n\\mathbf{E}_x(\\br,t) &= \\mathcal{E}_{x}\\mathbf{e}_x e^{i(k_0z-\\omega_0 t)},\\\\\n\\mathbf{E}_y(\\br,t) &= \\mathcal{E}_{y}\\mathbf{e}_y e^{i(k_0z-\\omega_0 t)},\n\\end{align}\n\\end{subequations}\nwhere $ \\mathcal{E}_{0x} $ and $ \\mathcal{E}_{0y} $ are the complex amplitudes and $ \\mathbf{e}_x $ and $ \\mathbf{e}_y $ are the direction vectors along the $ x $- and $ y $-axes, respectively, in the transverse plane, perpendicular to the propagation direction along the $ z $ axis. \n\nA light is said to be \\emph{linearly polarized}\\index{polarization!linear polarization} if $\\mathcal{E}_{x}$ and $ \\mathcal{E}_{y} $ have the same phase. The polarization direction is set by the polarization angle $ \\theta=\\arctan(\\mathcal{E}_{y}/\\mathcal{E}_{x}) $ from the $ \\mathbf{e}_x $ direction.\nThe polarization magnitude is defined to be $ E=\\sqrt{\\mathcal{E}_{x}^2+\\mathcal{E}_{y}^2} $.\n\nA light is said to be \\emph{circularly polarized}\\index{polarization!circular polarization} if $\\mathcal{E}_{x}$ and $ \\mathcal{E}_{y} $ have the same magnitude, but differ in phase by $ 90^\\circ $. The wave can then be described by \n\\begin{align}\\label{eq:circularlightfield}\n\\mathbf{E}=E_0(\\mathbf{e}_x \\pm i\\mathbf{e}_y)e^{i(k_0z-\\omega_0 t)}\n\\end{align}\nwith $ E_0 $ the common real amplitude. Taking any point $ \\br_0=(x_0,y_0,z_0) $ in space, the combined polarization vector $ \\mathbf{e}_l(z_0)=(\\mathbf{e}_x \\pm i\\mathbf{e}_y)e^{i(k_0z_0-\\omega_0 t)} $ sweeps a complete circle at an angular frequency $ \\omega_0 $.\nUsing the circular polarization basis vectors, $ \\mathbf{e}_\\pm $, defined by Eq.~\\eqref{eq:epm}, the electric field can be rewrite as \n\\begin{align} \n\\mathbf{E}&=\\sum_q \\mathcal{E}_q\\mathbf{e}_q=\\mathcal{E}_+ \\mathbf{e}_+ +\\mathcal{E}_-\\mathbf{e}_-\\\\\n&=\\mathcal{E}_L\\mathbf{e}_++\\mathcal{E}_R\\mathbf{e}_- \n\\end{align} \nwith $ \\mathcal{E}_q=\\mathbf{e}_q^*\\cdot \\mathbf{E} $, and the left- and right-circular polarization amplitudes $ \\mathcal{E}_L=\\mathcal{E}_+ $ and $ \\mathcal{E}_R=\\mathcal{E}_- $, respectively. \nNote that the definition of \\emph{left} and \\emph{right} rotations in modern physics, including quantum mechanics, is different from that in traditional optics. In order to match the classical definitions of basic concepts with the quantum mechanical derivation in Chapter~\\ref{chap:quantumdynamicsrepresentation}, we will primarily stick to the concept of \\emph{helicity} in this chapter.\n\nThe Cartesian basis of the polarization measurement is usually called as the linear polarization basis (see Eq.~\\eqref{eq:circularlightfield} for the circular polarization case). We can also use $ H $ (horizontal) and $ V $ (vertical) to label the $ x $ and $ y $ components of the field.\nAlternatively, if the actual field is detected in the circular polarization basis, only one non-zero amplitude may be detected proportional to the circular polarization component \n\\begin{align}\nE_\\pm(\\br_0,t) &= \\re\\left[\\mathbf{e}_\\pm^* \\cdot \\mathbf{E}\\right] = \\re\\left[\\mathcal{E}_\\pm \\right].\n\\end{align}\nI will label the polarization bases of positive and negative helicities with $ + $ and $- $ subscripts, respectively, in this dissertation. The choice of basis of polarization measurement can be operated by using beam splitters and proper wave planes in real experiments~\\cite{Born1999Principles}.\n\nIf $\\mathcal{E}_{x}$ and $ \\mathcal{E}_{y} $ have different phases, the light is \\emph{elliptically polarized}\\index{polarization!elliptical polarization} in general. Represented in the circular polarization basis, the wave can be given by\n\\begin{align}\n\\mathbf{E}=(\\mathcal{E}_+\\mathbf{e}_+ + \\mathcal{E}_-\\mathbf{e}_-)e^{i(k_0z-\\omega_0 t)},\n\\end{align}\nwhere $ \\mathcal{E}_\\pm $ are complex amplitudes, and $ \\mathrm{angle}\\left(\\mathcal{E}_+\\right)$ may not equal to $\\mathrm{angle}\\left(\\mathcal{E}_-\\right) $. \nWhen $ \\mathcal{E}_+ $ and $ \\mathcal{E}_- $ have different magnitudes yet the same phase, the light is elliptically polarized with the $ \\mathbf{E} $ vector traced as an ellipse defined by the principle axes pointing along $ \\mathbf{e}_x $ and $ \\mathbf{e}_y $ directions~\\cite{Jackson1975}. The semimajor and semiminor axes of the ellipse have a ratio of $ |(1+r)/(1-r)| $, where $ r=\\mathcal{E}_+/\\mathcal{E}_- $. \nWhen the two complex amplitudes in the circular polarization basis have a phase difference, $ \\phi $, or $ \\mathcal{E}_+/\\mathcal{E}_-=re^{i\\phi} $, then the traced ellipse of the $ \\mathcal{E} $ vector has its principal axes rotated by an angle $ \\phi/2 $ from the $ \\mathbf{e}_x $ and $ \\mathbf{e}_y $ axes. \nThe real parameter $ r $ is the ellipticity\\index{polarization!ellipticity} of the ellipse of the $ \\mathbf{E} $ vector trace. For $ r=\\pm 1 $, we recover the linear polarization case. \n\n\\section{Stokes vectors and polarization measurement}\n\nTo help visualize the polarization state of the light, we rewrite the field amplitudes\\footnote{In the terminology of modern physics, they are also the components of Jones vectors defining a polarized light~\\cite{Born1999Principles}.} in the linear and circular polarization bases by\n\\begin{align}\n\\mathcal{E}_x &= E_x e^{i\\delta_x},\\quad & \\mathcal{E}_y &= E_y e^{i\\delta_y},\\\\\n\\mathcal{E}_+ &= E_+ e^{i\\delta_+},\\quad & \\mathcal{E}_- &= E_- e^{i\\delta_-},\n\\end{align} \nwhere $ E_{x/y} $, $ E_\\pm  $, $ \\delta_{x/y} $ and $ \\delta_\\pm $ are all real parameters. Traditionally, the Stokes vector $ \\mathbf{S}=(S_0,S_1,S_2,S_3) $ is usually employed in literature to uniquely project the polarization state of the light onto the famous \\Poincare sphere\\cite{Born1999Principles} (see Fig.\\ref{fig:Poincaresphere}). In terms of the linear polarization basis $ (\\mathbf{e}_x,\\mathbf{e}_y) $, the Stokes vector components are~\\cite{Born1999Principles}\n\\begin{subequations}\\label{eq:S_xybasis}\n\\begin{align}\nS_0 &= |\\mathbf{e}_x\\cdot \\mathbf{E}|^2+|\\mathbf{e}_y\\cdot \\mathbf{E}|^2 =E_x^2+E_y^2\\\\\nS_1 &= |\\mathbf{e}_x\\cdot \\mathbf{E}|^2-|\\mathbf{e}_y\\cdot \\mathbf{E}|^2 =E_x^2-E_y^2\\\\\nS_2 &= 2\\re\\left[ (\\mathbf{e}_x\\cdot \\mathbf{E})^*(\\mathbf{e}_y\\cdot \\mathbf{E})\\right] =2E_xE_y\\cos(\\delta_y-\\delta_x)\\label{eq:S2_xybasis}\\\\\nS_3 &= 2\\im\\left[ (\\mathbf{e}_x\\cdot \\mathbf{E})^*(\\mathbf{e}_y\\cdot \\mathbf{E})\\right] =2E_xE_y\\sin(\\delta_y-\\delta_x)\n\\end{align}\n\\end{subequations}\n\nSimilarly, in the circular polarization basis $ (\\mathbf{e}_+,\\mathbf{e}_-) $, the Stokes vector components can be given by\n\\begin{subequations}\\label{eq:S_circularbasis}\n\\begin{align}\nS_0 &= |\\mathbf{e}_+^*\\cdot \\mathbf{E}|^2+|\\mathbf{e}_-^*\\cdot \\mathbf{E}|^2 =E_+^2+E_-^2\\\\\nS_1 &= 2\\re\\left[ (\\mathbf{e}_+^*\\cdot \\mathbf{E})^*(\\mathbf{e}_-^*\\cdot \\mathbf{E})\\right] = 2E_+E_-\\cos(\\delta_--\\delta_+)\\\\\nS_2 &= 2\\im\\left[ (\\mathbf{e}_+^*\\cdot \\mathbf{E})^*(\\mathbf{e}_-^*\\cdot \\mathbf{E})\\right] =2E_+E_-\\sin(\\delta_--\\delta_+)\\\\\nS_3 &= |\\mathbf{e}_+^*\\cdot \\mathbf{E}|^2-|\\mathbf{e}_-^*\\cdot \\mathbf{E}|^2 =E_+^2-E_-^2 %=E_L^2-E_R^2\n\\end{align}\n\\end{subequations}\n %(\\qxd{Note: should the $S_3$ be $ E_R^2-E_L^2 $ instead?})\nThe Stokes vector components are independent from the choice of basis. \nOne can choose another linear polarization basis, namely, the diagonal polarization basis $ (\\mathbf{e}_D,\\mathbf{e}_{\\thickbar{D}}) $ defined by Eq.~\\eqref{eq:eDeDbar}. \nThe $ \\mathbf{E} $ vector can then be written as  \\begin{align}\n\\mathbf{E} = \\mathcal{E}_D\\mathbf{e}_D + \\mathcal{E}_{\\thickbar{D}}\\mathbf{e}_{\\thickbar{D}}=E_De^{i\\delta_D}\\mathbf{e}_D + E_{\\thickbar{D}}e^{i\\delta_{\\thickbar{D}}}\\mathbf{e}_{\\thickbar{D}} .\\label{eq:E_Dbasis}\n\\end{align}\nPlugging Eqs.~\\eqref{eq:eDeDbar} and~\\eqref{eq:E_Dbasis} into Eq.~\\eqref{eq:S2_xybasis}, one can find that in the diagonal polarization basis\n\\begin{align}\\label{eq:S2_Dbasis}\nS_2 = E_D^2-E_{\\thickbar{D}}^2.\n\\end{align}\n%\\qxd{(Comment: why not $ E_{\\thickbar{D}}^2-E_{D}^2 $?)}\nBased on the expressions of Stokes vectors in different bases or Eqs.~(\\ref{eq:S_xybasis},~\\ref{eq:S_circularbasis} and~\\ref{eq:S2_Dbasis}), we can find the relation between those Stokes vector components and the intensity of field components $ E_i^2 $ in different bases as follows:\n\\begin{subequations}\\label{eq:S_intensitydiff_appendix}\n\\begin{align}\nS_0 &= E_H^2+E_V^2 = E_+^2+E_-^2 = E_D^2+E_{\\thickbar{D}}^2,\\\\\nS_1 &= E_H^2-E_V^2,\\\\\nS_2 &= E_D^2-E_{\\thickbar{D}}^2,\\\\\nS_3 &= E_+^2-E_-^2. %=E_L^2-E_R^2\n\\end{align}\n\\end{subequations}\nAbove, we have replaced $ x\\rightarrow H $ and $ y\\rightarrow V $.\n\n%</polarizationstokesvectors>\n\n%<*guidedunguidedmodes>\n\\chapter{Guided and unguided modes of a waveguide}\\label{chap:guidedunguidedmodes}\nBelow, we sketch out the condition to divide the guided and unguided modes using an analogy to the \\sch equation and based on the total internal reflection condition.\n\n\\section{Wave equations as a scattering problem in analogy}\nIf we want to fully calculate the eigenmodes of a waveguide, we need to consider both the electric and magnetic fields, the spatial parts of which are governed by the wave equations\n\\begin{align}\\label{EBz}\n\\left(\\nabla^2 +k^2 \\varepsilon(\\br_{\\perp})\\right) \\begin{pmatrix}\n\\mathcal{E}_z(\\br)\\\\\n\\mathcal{B}_z(\\br)\n\\end{pmatrix} = 0,\n\\end{align}\nwhere $ \\varepsilon=n^2 $ is the permittivity of the medium and $ k $ is the wavenumber of the modes. The equation above is derived from the \\emph{Maxwell-Helmholtz equation}\\index{Maxwell-Helmholtz equation}, for example,\n\\begin{align}\n\\left[ -\\nabla\\times\\nabla\\times+\\frac{\\omega^2}{c^2}n^2(\\br) \\right] \\boldsymbol{\\mathcal{E}}(\\br) &=0. \\label{MaxwellHelmholtz0},\n\\end{align}\nfor the electric field part.\nNotice that we only concentrate on the $ z $-component of the fields since all the other components can be expressed in terms of the $ z $-components. (See a detailed derivations in Appendix~\\ref{MWE:components} in the cylindrical coordinate system). \n\nWe use the ansatz\n\\begin{align}\n\\mathcal{E}_z (r_\\perp, \\phi, z) &= \\psi(r_\\perp,\\phi) e^{i\\beta z},\\\\\n\\mathcal{B}_z (r_\\perp,\\phi,z) &= \\zeta(r_\\perp,\\phi) e^{i\\beta z}.\n\\end{align}\nSubstituting the above into Eq.~\\ref{EBz}, we obtain\n\\begin{align}\\label{psizeta}\n\\left(\\nabla^2_\\perp +(k^2 \\varepsilon(\\br_{\\perp})-\\beta^2 )\\right) \\begin{pmatrix}\n\\psi(r_\\perp,\\phi)\\\\\n\\zeta(r_\\perp,\\phi)\n\\end{pmatrix} = 0.\n\\end{align}\nNow, the problem of solving a three dimensional wave equation for $ \\boldsymbol{\\mathcal{E}} (r_\\perp, \\phi, z) $ \nand $ \\boldsymbol{\\mathcal{B}} (r_\\perp, \\phi, z)$ turns into a problem of solving a two-dimension differential \n(mode) equation for $ \\psi(r_\\perp,\\phi) $ and $ \\zeta(r_\\perp,\\phi) $. \n\nThere are two special cases for the modes. If $ \\psi=0 $ is constant, which means there is no $ z $-component of the electrical field, then the propagating mode is called a TE mode\\index{mode!TE mode}. Similarly, if $ \\zeta=0 $ is constant, which corresponds to zero magnetic $ z $-component, \nthen this mode is called a TM mode\\index{mode!TM mode}. However, in many waveguide geometries including the nanofiber case with a cylindrical symmetry, the modes cannot be grouped into TE and TM guided waves. In general, the modes with \nboth nonzero electrical and magnetic  $ z $-components are known as EH and HE hybrid \nmodes\\index{mode!HE mode}~\\cite{Snyder1983Optical}--the second letter in the names indicates the field with a dominant longitudinal component.\n\nWe focus on the electrical part for now. The magnetic field can be solved similarly. Eq.~\\ref{psizeta} gives\n\\begin{align}\\label{eigenpsi}\n[\\nabla^2_\\perp + k^2\\varepsilon(r_\\perp)] \\psi(r_\\perp, \\phi) = \\beta^2\\psi(r_\\perp,\\phi).\n\\end{align}\nCompared to the time-independent \\sch equation\n\\begin{align}\n\\left[\\frac{\\hat{P}^2}{2m}+V(\\hat{\\mathbf{r}}_\\perp) \\right] \\psi(\\br_\\perp)&= E\\psi(\\br_\\perp),\\\\\n\\text{or}\\quad \\left[ \\nabla^2_\\perp -V(r_\\perp) \\right] \\psi (r_\\perp, \\phi) &= -E\\psi(r_\\perp,\\phi),\n\\end{align}\nwe can conclude that the mode equation (Eq.~\\ref{eigenpsi}) is basically an eigenvalue equation for the \\sch wavefunctions if we make the replacement\n\\begin{align}\nV_{ef\\!f}=-k^2\\varepsilon(\\br\\!_\\perp) &\\sim V(\\br\\!_\\perp),\\\\\n-\\beta^2 &\\sim E.\n\\end{align}\nWith these analogies, we find that the guided modes dictated by the wave equation should correspond to the bound eigenstates of the trapping potential problem obeying the \\sch equation; likewise, the unguided modes of the wave equation correspond to unbound states in the scattering problem following the \\sch equation. In details, for the time-independent \\sch problem, if $ 0<E\\leq V $, then the eigenstates are bounded and have discrete solutions with respect to $ E $; if $ E>V $, then the resulting states is unbound and have continuous solutions of energy. For the waveguide's eigenmodes, similarly, we can also use the relative position of $ V_{ef\\!f} $ and $ -\\beta^2 $ to classify the guided and unguided modes. \n\nLet us consider the concrete case of a nanofiber with step-function-like permittivity as a function of $ r_\\perp $. The analogy of trapping potentials of the wave equation is illustrated in Fig.~\\ref{Figs/scatteredmode}. In the regime $ n_2k<\\beta<n_1k $, the eigenmodes have discrete solutions with respect to $ \\beta $, which yield $ \\beta=\\beta_0 $ for a single-mode fiber; in the $ 0<\\beta<n_2k $ regime, the eigenmode solutions are continuous with respect to $ \\beta $. Similar result applies to the \\SWG case. \n\n%\\scalefig{Figs/scatteredmode}{0.8}{Bound and unbound states for the nanofiber eigenvalue \n%problem. $ \\varepsilon(r\\!_\\perp)=\\varepsilon_{f} =n_1^2$ if $ r_\\perp < a $; otherwise, $\\varepsilon\n%(r\\!_\\perp) =1 $. The parameter $ a $ is the radium of the nanofiber. } \n\n\\begin{figure}[!tbp]\n\\centering\\makebox[\\textwidth]{\n\\begin{tikzpicture}[scale=1,cap=round]\n% Configurable parameters\n\\def\\k{1.5cm}\n\\def\\eps{1.5*1.7cm}\n\\def\\betasq{1.5*1.4cm}\n\\def\\a{2cm}\n\\def\\maxr{5cm}\n\n% Styles\n\\tikzstyle{axes}=[arrows={-latex}]\n\\tikzstyle{auxline}=[densely dashed]\n\\tikzstyle{important line}=[very thick]\n\n% Coordinates and points.\n\\coordinate (O) at (0,0);\t% Origin.\n\\coordinate (A) at (\\a,0);\t% The surface distance to the axis of the fiber.\n\\coordinate (B) at (0,-\\eps);\t% -k^2\\epsilon at the center of the fiber.\n\\coordinate (C) at (\\a,-\\eps);\t% -k^2\\epsilon on the surface of the fiber.\n\\coordinate (D) at (0,-\\betasq);\t% -\\beta^2 point at the center of the fiber.\n\\coordinate (E) at (\\a*1.3,-\\betasq);\t% -\\beta^2 point at the end of the maximum r.\n\\coordinate (F) at (0,-\\k);\t% -k^2 point at the center of fiber.\n\\coordinate (G) at (\\a,-\\k); \t% -k^2 point on the surface of the fiber.\n\\coordinate (H) at (\\maxr,-\\k); \t% -k^2 point at the end of r.\n\n% The graphic\n % help grid\n% \\draw[style=help lines,step=0.5cm] (-2.0,-2.0) grid (2.0,2.0);\n  \n% Draw axes and marks.\n\\draw [axes] (-1cm, 0) -- (\\maxr,0) node [above] {$r_{\\perp}$};\n\\draw [axes] (0, -1.2*\\eps) -- (0, 1.0cm) node [right] {$V(r_{\\perp})=-k^2n^2(r_{\\perp})=-\\beta^2$};\n\\draw (O) node [above left] {$O$};\n\\draw[thin] (A) -- (\\a,3pt) node[anchor=south] {$a$}; \n\\draw (B) -- (-3pt,-\\eps) node[anchor=east] {$-k^2n_1^2$};\n\\draw (D) -- (-3pt,-\\betasq) node[anchor=east] {$-\\beta_0^2$};\n\\draw (F) -- (-3pt,-\\k) node[anchor=east] {$-k^2n_2^2$};\n\n% Draw potential lines.\n\\draw[important line] (B) -- (C);\n\\draw[important line] (C) -- (G);\n\\draw[important line] (G) -- (H);\n\\draw[auxline] (D) -- (E) node[right] {Guided modes};\n\\draw[auxline,very thin] (F) -- (G);\n\\draw[auxline,very thin] (A) -- (G);\n\n% Other labels and auxlines.\n%\\draw[<->] (\\a*1.25,0) -- (\\a*1.25,-\\k) node[midway,right] {Scattered modes};\n\\draw (\\a*1.2,-\\k/2) node[right] {Radiative modes};\n\\draw[<-] (\\a*1.8,0) -- (\\a*1.8,-0.5cm);\n\\draw[->] (\\a*1.8,-1cm) -- (\\a*1.8,-\\k);\n\\draw[<-] (\\a*1.95,-\\k) -- (\\a*1.95,-\\k-0.4cm);\n\\draw[->] (\\a*1.95,-\\k-0.8cm) -- (\\a*1.95,-\\eps);\n\\draw[auxline] (\\a*1.85,-\\eps) -- (\\a*2.08,-\\eps);\n\\end{tikzpicture}\n}\n\\caption[Trapping potential analogy of the bound and unguided modes of a nanofiber.]{Bound and unbound states for the fiber eigenvalue problem. $ \\varepsilon(r\\!_\\perp)=\\varepsilon_{f} =n_1^2$ if $ r_\\perp < a $; otherwise, $\\varepsilon(r\\!_\\perp) =1 $. The parameter $ a $ is the radius of the nanofiber.}\n\\label{Figs/scatteredmode}\n\\end{figure}\n\n\\section{Categorizing eigenmodes based on the total internal reflection condition}\nThe division of guided and unguided modes based on the value of $ \\beta $ can also be roughly understood in the perspective of geometric optics as elucidated in Fig.~\\ref{fig:Fibermodes}. We regard $ \\beta $ as the $ z $-projected wave number of a wave vector of the light ray on the $ \\vec{k} $ direction. If the ray is incident in an angle that satisfies the total internal reflection condition (in our case, $ k_0<\\beta<n_1k_0 $ with $ n_2=1 $), the corresponding modes are guided; otherwise, the modes are unguided with the light leaking out and decaying along $ z $.\n\n\\begin{figure}[!tbp]\n\\centering\\makebox[\\textwidth]{\n\\begin{tikzpicture}[scale=1,cap=round]\n% Configurable parameters\n\\def\\fiberrad{1cm}\t% Radius of the nanofiber.\n\\def\\comprad{0.45cm}\t% Compressed radius of the nanofiber in the view angle.\n\\def\\fiberleftx{0}\t% The x-coordiante of the center of the left surface of the fiber.\n\\def\\fiberlefty{0}\t% The y-coordiante of the center of the left surface of the fiber.\n\\def\\fiberlength{6.6cm} % The length of the fiber.\n\n% Styles\n\\tikzstyle{axes}=[arrows={-latex}]\n\\tikzstyle{auxline}=[densely dashed]\n\\tikzstyle{important line}=[thick]\n\\tikzstyle{dot}=[circle,inner sep=1pt,fill,label={#1},name=#1]\n\n% Coordinates and points.\n\\coordinate (O) at (0,0);\t% Origin.\n\\coordinate (LO) at (\\fiberleftx,\\fiberlefty); % Center of the left-side surface of the nanofiber.\n\\coordinate (RO) at (\\fiberleftx+\\fiberlength,\\fiberlefty); % Center of the right-side surface\n\\coordinate (A) at ({\\fiberleftx},{\\fiberlefty+\\fiberrad});\t% Top-left point of the nanofiber.\n\\coordinate (B) at ({\\fiberleftx+\\fiberlength},{\\fiberlefty+\\fiberrad});\t% Top-right point of the nanofiber.\n\\coordinate (C) at ({\\fiberleftx+\\fiberlength},{\\fiberlefty-\\fiberrad});\t% Bottom-right point of the fiber.\n\\coordinate (D) at ({\\fiberleftx},{\\fiberlefty-\\fiberrad});\t% Bottom-left point of the nanofiber.\n\n% The graph.\n% help grid\n% \\draw[style=help lines,step=0.5cm] (-2.0,-2.0) grid (2.0,2.0);\n\n% Draw the fiber.\n\\begin{scope} \n    % Outer edge.\n    %\\fill[left color=purple!50!black,right color=purple!50!black,middle \n%color=purple!50,shading=axis,opacity=0.25] (A) -- (B) arc (90:270:{\\comprad} and {\\fiberrad}) -- (D) arc \n%(270:90:{\\comprad} and {\\fiberrad});\n    % Right-side surface.\n    %\\fill[top color=purple!90!,bottom color=purple!2,middle color=purple!30,shading=axis,opacity=0.25] \n%(RO) circle [x radius={\\comprad}, y radius = {\\fiberrad}];\n    % Draw lines of all edges.\n    \\draw (A) -- (B);\n    \\draw  (RO) circle [x radius = {\\comprad}, y radius =  {\\fiberrad}];\n    \\draw (C) -- (D) arc (270:90:{\\comprad} and {\\fiberrad}); \n    \\draw[densely dashed] (A) arc (90:-90:{\\comprad} and {\\fiberrad});\n\\end{scope}\n\n% Draw the guide mode wave vector and propagation lines.\n% First part of the ray: up-solid line.\n\\draw[red] (O)--(2.0*\\fiberrad,\\fiberrad);\n%\\draw[red,decoration={ markings,  % This schema allows for fine-tuning the arrows.\n%      mark=at position 0.5 with {\\arrow{latex'}}, \n%      mark=at position 0.82 with {\\arrow{latex'}}},postaction={decorate}] (O) -- (2.0*\\fiberrad,\\fiberrad)-- (6.0*\\fiberrad,-\\fiberrad);\n% The penetration part of ray: dashed line.\n\\draw[red,densely dotted] (2.0*\\fiberrad,\\fiberrad) -- (2.3*\\fiberrad,1.1732*\\fiberrad) -- (2.6*\\fiberrad,\\fiberrad);\n% The reflected part: solid downarrow.\n\\draw[red,decoration={ markings,  % This schema allows for fine-tuning the arrows.\n      mark=at position 0.2 with {\\arrow{latex'}}, \n      mark=at position 0.6 with {\\arrow{latex'}}},postaction={decorate}] (2.6*\\fiberrad,\\fiberrad)-- (6.6*\\fiberrad,-\\fiberrad);\n% The ruler part.\n\\draw[important line,-latex'] (O) --(27:1) node[below,xshift=8,yshift=5] {$ \\vec{k} $};\n\\draw[auxline] (27:1) -- ({cos(27)},-1.5)  node [below] {$\\beta_0$};\n\n% Draw radiation modes.\n% Radiation ray 1:\n\\draw[blue,decoration={ markings,  % This schema allows for fine-tuning the arrows. \n      mark=at position 0.95 with {\\arrow{latex'}}},postaction={decorate}] (O) -- (0.5,\\fiberrad) -- (1.5,\\fiberrad*1.1);\n\\draw[-latex'] (O)--(63.5:1);\n\\draw[auxline] (63.5:1) -- ({cos(63.5)},-2);\n% Radiation ray 2:\n\\draw[blue,decoration={ markings,  % This schema allows for fine-tuning the arrows. \n      mark=at position 0.95 with {\\arrow{latex'}}},postaction={decorate}] (O) -- (0.4,\\fiberrad) -- (1.4,\\fiberrad*1.4);\n\\draw[-latex'] (O)--(68.5:1);\n\\draw[auxline] (68.5:1) -- ({cos(68.5)},-2);\n% Radiation ray 3:\n\\draw[blue,decoration={ markings,  % This schema allows for fine-tuning the arrows. \n      mark=at position 0.95 with {\\arrow{latex'}}},postaction={decorate}] (O) -- (0.25,\\fiberrad) -- (0.9,\\fiberrad*1.9);\n\\draw[-latex'] (O)--(76:1);\n\\draw[auxline] (76:1) -- ({cos(76)},-2);\n% Radiation ray 3:\n\\draw[blue,decoration={ markings,  % This schema allows for fine-tuning the arrows. \n      mark=at position 0.95 with {\\arrow{latex'}}},postaction={decorate}] (O)-- (0,2*\\fiberrad);\n\\draw[-latex'] (O) -- (0,\\fiberrad);\n% Draw dots inbetween.\n\\draw[dotted] ([shift=(26:1)] 0.2,1.0*\\fiberrad) arc (26:45:1);\n\\draw[dotted] ([shift=(60:1)] 0.1,1.0*\\fiberrad) arc (60:89:1);\n\n% Labels and denotes.\n\\draw (O) node[dot] {};\n\\draw (O) node[left] {O};\n\\draw[auxline,-latex] (O) -- (\\fiberlength*1.0,0) node [above] {$ z $};\t% Z axis line.\n\\draw[auxline] (0,\\fiberrad) -- (0,-2);\n\\draw[important line,-latex] (0,-2) node[left] {$ 0 $}--(2.5,-2) node[right] {$ k_z $};% kz axis.\n\\draw (0,-2) -- (0,-2.08);\n\\draw (0.5,-2) -- (0.5,-2.08) node [anchor=north] {$k_0$};\n\\draw ({cos(27)},-2) -- ({cos(27)},-2.08);\n\\draw (1.1,-2) -- (1.1,-2.08) node [below right,xshift=-5] {$k_0n_1$};\n\\draw (3.35,-0.5) node[red] {Guided modes};\t% Guided modes label.\n\\draw (2.7,1.7*\\fiberrad) node[blue] {Radiative modes};\t% Radiative modes label.\n\\end{tikzpicture}\n}\n\\caption[Fiber modes classified through the $ z $-component of the wave vector, $ \\beta $.]{Fiber modes classified through the $ z $-component of the wave vector, $ \\beta $. We have assumed $ n_2=1 $ for the vacuum clad. From the diagram, we define $ \\beta $ is the $ z $-projection of $ \\vec{k} $, that is $ \\beta=k\\cos\\theta $, where $ k $ is the length of the wave vector following the ray-trace of the light propagating in all directions, and $ \\theta $ is the angle of the ray of light to the $ z $ axis. We see that when $ \\theta $ is small or $ \\beta $ is longer than some value, the light can satisfy the total internal reflection condition and hence the corresponding mode solution can be guided through the fiber; if $ \\theta $ is large or $ \\beta $ is small, then the light cannot satisfy the total internal reflection condition, and hence the corresponding modes are unguided or radiation leaking out of the fiber.}\n\\label{fig:Fibermodes}\n\\end{figure}\n%</guidedunguidedmodes>\n\n%<*eigenmodes>\n\n\\chapter{Fundamental eigenmodes of an optical nanofiber}\\label{chap:fibereigenmodes}\n\nIn this appendix chapter, we will provide some details on solving the eigenmodes of the nanofiber starting from the homogeneous wave equation, Eq.~\\ref{EBz}, and will give the formulas for mode normalization based on power and the eigenmode normalization condition. At the end of this chapter, we will also derive the formulas for calculating the group velocity of the \\HE mode of the nanofiber.\n\nFirst, starting form the operator\n\\begin{align}\n\\nabla^2 \\!_\\perp = \\frac{1}{r_{\\!\\perp}}\\pp{}{r\\!_\\perp}\\! \\left(r\\!_\\perp \\pp{}{r\\!_\\perp} \\right) + \n\\frac{1}{r_\\perp^2} \\spp{}{\\phi},\n\\end{align}\nand the symmetry of the fiber,  we can separate the mode function by\n\\begin{align}\n\\psi(r\\!_\\perp,\\phi)=\\mathcal{E}_{z,\\beta m}(r\\!_\\perp)e^{im\\phi},\n\\end{align} \nand hence\n\\begin{align}\n\\mathcal{E}_z(r\\!_\\perp,\\phi,z) = \\mathcal{E}_{z,\\beta m}(r\\!_\\perp)e^{i(m\\phi+\\beta z)},\n\\end{align}\nwhere $ \\mathcal{E}_{z,\\beta m}(r\\!_\\perp) $ satisfies the Bessel's equation\\index{Bessel function!Bessel equation}\n\\begin{align}\n\\left[ \\spp{}{r\\!_\\perp}+ \\frac{1}{r_{\\!\\perp}}\\pp{}{r\\!_\\perp}- \n\\frac{m^2}{r^2\\!_\\perp} + (k^2\\varepsilon(r\\!_\\perp)-\\beta^2) \\right] \n\\mathcal{E}_{z,\\beta m}(r\\!\\!_\\perp)=0\n\\end{align}\nwith \n\\begin{align}\n\\varepsilon(r\\!\\!_\\perp) = \n\\begin{cases}\n1, & r\\!_\\perp>a\\\\\n\\varepsilon_f, & r\\!_\\perp\\leq a.\n\\end{cases}\n\\end{align}\nThe general solution for $ \\mathcal{E}_{z,\\beta m}(r\\!\\!_\\perp) $ can be given in three cases \ncorresponding to different \nboundary conditions\n\\begin{align}\n\\mathcal{E}_{z,\\beta m}(r\\!\\!_\\perp) = \\begin{cases}\nAJ_m(qr\\!\\!_\\perp) + B Y_m(qr\\!_\\perp)&\\rightarrow J_m(\\theta)\\sim \\cos\\theta,\\, Y_m(\\theta)\\sim \n\\sin\\theta.\\\\\nCI_m(qr\\!_\\perp) + DK_m(qr\\!_\\perp) & \\rightarrow I_m(\\theta) \\sim e^\\theta,\\, K_m(\\theta) \\sim \ne^{-\\theta}.\\\\\nEH_m^{(\\!1\\!)}(qr\\!_\\perp) \\!+\\! FH_m^{(\\!2\\!)}(qr\\!_\\perp ) & \\rightarrow H_m^{(\\!1\\!)} (\\theta) \\! \\sim \\! \ne^{i\\theta},\\, \nH_m^{(\\!2\\!)}(\\theta)\\!\\sim\\! e^{\\!-i\\theta}.\n\\end{cases}\n\\end{align}\n$J_m$ and $Y_m$ are the $m^{th}$ Bessel functions of the first\\index{Bessel function!Bessel function of the first kind} and second kind\\index{Bessel function!Bessel function of the second kind}.\n$I_m$ and $K_m$ are the $m^{th}$ modified Bessel functions of the first\\index{Bessel function!modified Bessel function of the first kind} and second kind\\index{Bessel function!modified Bessel function of the second kind}.\n$H_m^{(1)}$ and $H_m^{(2)}$ are the $m^{th}$ Hankel functions of the first\\index{Hankel function!Hankel function of the first kind} and second kind\\index{Hankel function!Hankel function of the second kind}.\nThe positive parameter $ 1/q $ is the characteristic decay length corresponding to $ 1/h_{11} $ and $ \n1/q_{11} $ \nin the $\\text{HE}_{11}$ mode expression. Using the symmetric and convergent condition at $ \nr\\!_\\perp=0\\,\\text{and}\\, \\infty $, as for guided modes, for example, if $k< \\beta\\leq \nk\\sqrt{\\varepsilon_f}$,\n\\begin{align}\n\\left\\{\n \\begin{array}{lcll}\n\tr\\!_\\perp \\leq a, & \\mathcal{E}_{z,\\beta m}(r\\!_\\perp )\\!=\\! AJ_m(h r\\!_\\perp), & h \\!=\\! \n\t\\sqrt{k^2\\varepsilon_f-\\beta^2}\\! >\\! 0;\\\\\n\tr\\!_\\perp > a, & \\mathcal{E}_{z,\\beta m}(r\\!_\\perp )\\!=\\!DK_m(q r\\!_\\perp), & q\\!=\\! \n\t\\sqrt{\\beta^2-k^2}>0.\n \\end{array}\\right.\n\\end{align}\nBoth $ \\beta $ and $ h $ are discrete for guided modes. \nFor unguided modes, $ 0\\leq \\beta< k $, similarly, \n\\begin{align}\n\\left\\{\n \\begin{array}{lcll}\n\tr\\!_\\perp \\leq a, & \\mathcal{E}_{z,\\beta m}(r\\!_\\perp )\\!=\\! AJ_m(h r\\!_\\perp), & h \\!=\\! \n\t\\sqrt{k^2\\varepsilon_f-\\beta^2}\\! >\\! 0;\\\\\n\tr\\!_\\perp > a, & \\mathcal{E}_{z,\\beta m}(r\\!_\\perp )\\!=\\!EH_m^{(\\!1\\!)}(p r\\!_\\perp\\!), & p\\!\\!=\\!\\! \n\t\\sqrt{k^2-\\beta^2}>0.\n \\end{array}\\right.\n\\end{align}\nBoth $ \\beta $ and $ p $ are continuous. \n%\\textcolor{red}{(Double check the general solutions and the consistence with Eq.~\\ref{ET0Rexpand}.)}\n%Notice that Ref.\\cite{Snyder1983} used $ J_m(hr\\!_\\perp)\\cos m\\phi $ and $ \n%(J_m(pr\\!_\\perp)+CH_m^{(\\!1\\!)})\\cos m\\phi $ as the basis for the general solution of $ e $ and $ o $ \n%light \n%of the radiation modes, and summed them up. They are equivalent to the solution here.  \n\nAt a given frequency, $\\omega = c k$, the magnitudes of the longitudinal and transverse wave vectors for a guided mode are related by $n^2 k^2 = \\beta^2 + k_\\perp^2$.  \nThe positive propagation constant, $\\beta \\equiv \\beta(\\omega)$, is determined from the eigenvalue equation that results from enforcing physical boundary conditions at the fiber surface~\\cite{Snyder1983Optical},\n\t\\begin{align}\\label{eq:eigenfunctionbeta}\n\t\t\\frac{J_0(ha)}{ha J_1(ha)} &= - \\frac{n_1^2+n_2^2}{2n_1^2} \\frac{K'_1(qa)}{qa K_1(qa)} + \\frac{1}{h^2 a^2} \\nn\\\\\n\t\t&\\quad - \\bigg[ \\bigg(\\frac{n_1^2 - n_2^2}{2 n_1^2} \\frac{K'_1(qa)}{qa K_1(qa)} \\bigg)^2  + \\frac{\\beta^2}{n^2_1 k^2} \\bigg(\\frac{1}{q^2a^2} + \\frac{1}{h^2a^2} \\bigg)^2 \\bigg]^{1/2}.\n\t\\end{align}\nAbove, $f'(x)$ indicates a derivative with respect to the argument $x$.\nInside the nanofiber the transverse wavevector is real, $k_\\perp = q$, where $q=\\sqrt{\\beta^2- n_2^2k^2}$, and outside the nanofiber it is purely imaginary, $k_\\perp = i h$, where $h=\\sqrt{n_1^2 k^2 - \\beta^2}$.  \n\nIf $ \\beta $ is a pure imaginary number, the field will have an exponential decay amplitude on the $ z $ direction, and will spread the energy away from the fiber axis. Reference~\\cite{Snyder1983Optical} denotes the modes with pure imaginary $ \\beta $ as evanescent modes. If $ \\beta $ has both real and imaginary parts, the modes are denoted as leaky modes, which are combinations of unguided modes and evanescent modes. Except for the case that the incident light is highly directed at the complementary critical angle $ \\theta_c $ of geometric optics, the unguided modes part alone can propagate for a long distance along the fiber axis. In our nanofiber system, we only consider the bound and unbound modes. The ranges of some waveguide parameters are given in Table~\\ref{tab:fiberparameters}. \nIn the table, we have defined the normalized wave number\\cite{Snyder1983Optical}, or \n$V$-number\\index{V-number@$V$-number} \nof a fiber as $V  = \nk_f a \\mathrm{NA}$.  Here $k_f=\\frac{2\\pi}{\\lambda}$, is the free space wave number, $a$ is the radius \nof the core of the fiber, and $\\mathrm{NA}$ is the numerical aperture\\index{numerical aperture} of \nthe fiber, $\\mathrm{NA} = \n(n_1^2 - n_2^2)^{1/2} = n_1(2\\Delta)^{1/2}$, with profile height \nparameter\\index{profile height parameter} \n$\\Delta =\\frac{1}{2}(1-n_2^2/n_1^2)\\approx (n_1-n_2)/n_1$.  For \ndifferent modes labeled with $ j $, we always have $V_j^2=a^2(h_j^2+q_j^2)$ and $ \\lambda\\beta_j/2\\pi $ is a mode invariance.  The TE and TM modes have non-vanishing cut-off \nfrequencies, as $ a\\rightarrow 0 $.  The cutoff frequency is found from $V = a\\omega (\\Delta)^{1/2}/c =2.405$ for silicon fiber.  \nOnly the lowest HE mode, $\\mathrm{HE}_{11}$, has no cutoff frequency as $ a\\rightarrow 0 $.  For $0 < V < 2.405$, which is the case of the nanofiber we are studying, it is the only mode that propagates in the \nfiber. For fixed $ \\varepsilon_f $, in the range that $ 0\\leq \\beta \\leq \nk\\sqrt{\\varepsilon_f} $, we can distinguish the unguided and guided mode as follows:\n\\begin{align}\n\\begin{cases}\n0\\leq \\beta < k, &\\rightarrow \\text{\\emph{unguided/radiation modes;}}\\\\\nk< \\beta \\leq k \\sqrt{\\varepsilon_f}, &\\rightarrow \\exists \\text{ a},\\, \\text{HE}_{11}\\, \\text{\\emph{is the only \nguided mode.}}\n\\end{cases}\n\\end{align}\n\n\n\\begin{minipage}{0.97\\textwidth}\n\\centering\n\\captionof{table}{Ranges of fiber parameters for different modes. } \\label{tab:fiberparameters} \n\\begin{tabular}{|l|c|c|c|}\n\\hline  & $\\beta$ & $h$ & $p$ \\\\ \n\\hline Bound modes & $k<\\beta_j \\leq k\\sqrt{\\varepsilon_f} $ & $ 0\\leq h_j<V/a $ & $ p^r_j=0,\\, p^i_j>0 $ \\\\ \n\\hline Radiation modes & $0\\leq \\beta<k$ & $V/a < h\\leq k\\sqrt{\\varepsilon_f}$ & $0<p\\leq k $\\\\ \n\\hline Evanescent modes & $ \\beta^r=0,\\, \\beta^i>0 $ & $ k\\sqrt{\\varepsilon_f} < h $ & $ k<p $ \\\\ \n\\hline \n\\end{tabular} \n\\par\n\\bigskip\n%The caption:\nSuperscripts $ r $ and $ i $ denote real and imaginary parts. Subscripts $ j $ denotes the discrete indeces for guided modes. Adapted from Ref.~\\cite{Snyder1983Optical} P.P.516 Table 25-1. This can also be understood in geometric optics as shown in Fig.(\\ref{fig:Fibermodes}).\n\\end{minipage}\n\\bigskip\n\n\n\nDue to the symmetry of equations, we also have\n\\begin{align}\n\\mathcal{B}_z(r\\!_\\perp,\\phi,z) = \\mathcal{B}_{z,\\beta m}(r\\!_\\perp)e^{i(m\\phi+\\beta z)},\n\\end{align}\nwhere $  \\mathcal{B}_{z,\\beta m}(r\\!_\\perp) $ satisfies the same Bessel's equation as above\\index{Bessel function!Bessel equation}.  \n\nIn the case of a nanofiber with a sub-wavelength radius, the high-order modes of the nanofiber can hardly be supported, which only leaves the \\HE mode\\index{mode!HE11 mode@HE$_{11}$ mode} propagating along the nanofiber. Assuming the incident light is quasilinearly polarized, the Cartesian components of the bound optical field are given. For $ r_\\perp>a $ (outside the fiber), by~\\cite{Lacroute2012,LeKien2004}\n\\begin{subequations}\n\\label{Ertrga}\n\\begin{align}\nE_x^g(r_\\perp,\\phi,z,t) &= iA \\frac{\\beta_{11}J_1(h_{11}a)}{2q_{11}K_1(q_{11}a)}[(1-s_{11})K_0(q_{11}r_\\perp)\\cos (\\varphi_0) \\nonumber\\\\\n&\\qquad + (1+s_{11})K_2 (q_{11}r_\\perp) \\cos (2\\phi-\\varphi_0) ] e^{-i(\\omega t-f\\beta_{11}z)},\\\\\nE_y^g(r_\\perp,\\phi,z,t) &= iA \\frac{\\beta_{11}J_1(h_{11}a)}{2q_{11}K_1(q_{11}a)}[(1-s_{11})K_0(q_{11}r_\\perp)\\sin (\\varphi_0) \\nonumber\\\\\n&\\qquad + (1+s_{11})K_2 (q_{11}r_\\perp) \\sin (2\\phi-\\varphi_0) ] e^{-i(\\omega t-f\\beta_{11}z)},\\\\\nE_z^g(r_\\perp,\\phi,z,t) &= fA \\frac{J_1(h_{11}a)}{K_1(q_{11}a)}K_1(q_{11}r_\\perp)\\cos (\\phi-\\varphi_0) e^{-i(\\omega t-f\\beta_{11}z)},\n\\end{align}\n\\end{subequations}\nand, for $ r_\\perp<a $ (inside the nanofiber), by\n\\begin{subequations}\n\\label{Ertrla}\n\\begin{align}\nE_x^g(r_\\perp,\\phi,z,t) &= iA \\frac{\\beta_{11}}{2h_{11}}[(1-s_{11})J_0(h_{11}r_\\perp)\\cos (\\varphi_0) \\nonumber\\\\\n&\\qquad - (1+s_{11})J_2 (h_{11}r_\\perp) \\cos (2\\phi-\\varphi_0) ] e^{-i(\\omega t-f\\beta_{11}z)},\\\\\nE_y^g(r_\\perp,\\phi,z,t) &= iA \\frac{\\beta_{11}}{2h_{11}}[(1-s_{11})J_0(h_{11}r_\\perp)\\sin (\\varphi_0) \\nonumber\\\\\n&\\qquad - (1+s_{11})J_2 (h_{11}r_\\perp) \\sin (2\\phi-\\varphi_0) ] e^{-i(\\omega t-f\\beta_{11}z)},\\\\\nE_z^g(r_\\perp,\\phi,z,t) &= fA J_1(h_{11}r)\\cos (\\phi-\\varphi_0) e^{-i(\\omega t-f\\beta_{11}z)},\n\\end{align}\n\\end{subequations}\nwith\n\\begin{subequations}\n\\begin{align}\ns_{11} &= \\left[\\frac{1}{(h_{11}a)^2}+ \\frac{1}{(q_{11}a)^2} \\right] \\left[ \\frac{J_1'(h_{11}a)}{h_{11}aJ_1(h_{11}a)} + \\frac{K'_1(q_{11}a)}{q_{11}aK_1(q_{11}a)} \\right],\\\\\nh_{11} &= \\sqrt{k_0^2 n_1^2-\\beta_{11}^2},\\\\\nq_{11} &= \\sqrt{\\beta^2_{11}-k_0^2 n_2^2}.\n\\end{align}\n\\end{subequations}\nHere, $ k_0 $ is the vacuum wavenumber\\index{wavenumber} of the incident light,$ f=\\pm$ indicates forward ($+$) or backward ($-$) propagation direction, $ \\phi $ denotes the azimuthal angle in the transverse plane, $ \\varphi_0 $ indicates the polarization axis for the incident polarization relative to the $ x  $ axis, $ n_1 $ and $ n_2 $ are the refractive indices\\index{refractive index}\\index{index of refraction} of inside and outside the nanofiber, respectively, $ \\beta_{11} $ is the mode propagation constant, $ 1/h_{11} $ is the characteristic decay length for the guided mode inside the fiber, $ 1/q_{11} $ is the characteristic decay length outside the fiber; $ A $ is the real-valued amplitude for the linearly polarized input, $ J_l $ and $ K_l  $ are the $ l $-th Bessel function of the first kind\\index{Bessel function!Bessel function of the first kind} and the modified Bessel function of the second kind\\index{Bessel function!modified Bessel function of the second kind}, respectively. As shown in Equs.~\\ref{Ertrga} and~\\ref{Ertrla}, we can factorize $ \\mathbf{E}^g(r_\\perp,\\phi,z,t) $ as $ \\mathbf{E}^g(r_\\perp,\\phi,z,t)= \\boldsymbol{\\mathcal{E}}^g(\\br)e^{i\\omega t} $. \n\nUsing the coordinate system transformation relationships\n\\begin{align}\n\\mathbf{e}_{r\\!_\\perp} &= \\mathbf{e}_x\\cos\\phi + \\mathbf{e}_y\\sin\\phi,\\\\\n\\mathbf{e}_{\\phi} &= -\\mathbf{e}_x\\sin\\phi + \\mathbf{e}_y\\cos\\phi,\n\\end{align}\none can also express the transverse components of the electric field in the polar coordinate. For $ r\\!_\\perp>a $, by\n\\begin{subequations}\n\\label{Erptlrga}\n\\begin{align}\nE_{r\\!_\\perp}^g(r_\\perp,\\phi,z,t) &= iA \\frac{\\beta_{11}J_1(h_{11}a)}{2q_{11}K_1(q_{11}a)}[(1-s_{11})K_0(q_{11}r_\\perp) \\nonumber\\\\\n&\\qquad + (1+s_{11})K_2 (q_{11}r_\\perp) ]\\cos (\\phi-\\varphi_0) e^{-i(\\omega t-f\\beta_{11}z)},\\\\\nE_\\phi^g(r_\\perp,\\phi,z,t) &= -iA \\frac{\\beta_{11}J_1(h_{11}a)}{2q_{11}K_1(q_{11}a)}[(1-s_{11})K_0(q_{11}r_\\perp) \\nonumber\\\\\n&\\qquad - (1+s_{11})K_2 (q_{11}r_\\perp) ]\\sin (\\phi-\\varphi_0) e^{-i(\\omega t-f\\beta_{11}z)},\n\\end{align}\n\\end{subequations}\nand, for $ r_\\perp<a $, by\n\\begin{subequations}\n\\label{Ephirtlrla}\n\\begin{align}\nE_{r\\!_\\perp}^g(r_\\perp,\\phi,z,t) &= iA \\frac{\\beta_{11}}{2h_{11}}[(1-s_{11})J_0(h_{11}r_\\perp) \\nonumber\\\\\n&\\qquad - (1+s_{11})J_2 (h_{11}r_\\perp)  ]\\cos (\\phi-\\varphi_0) e^{-i(\\omega t-f\\beta_{11}z)},\\\\\nE_\\phi^g(r_\\perp,\\phi,z,t) &= -iA \\frac{\\beta_{11}}{2h_{11}}[(1-s_{11})J_0(h_{11}r_\\perp) \\nonumber\\\\\n&\\qquad + (1+s_{11})J_2 (h_{11}r_\\perp)  ]\\sin (\\phi-\\varphi_0) e^{-i(\\omega t-f\\beta_{11}z)}.\n\\end{align}\n\\end{subequations}\n\nAlternatively, we can use the fundamental mode with rotating polarization to decompose an arbitrary polarized-mode propagating in the fiber. The solutions for the cylindrical components of the circularly polarized fundamental mode are given~\\cite{Lacroute2012,Vetsch2010Opticala}, for $ r_\\perp<a $, by\n\\begin{subequations}\n\\label{Ertcrla}\n\\begin{align}\nE^{(\\mu)}_{r_\\perp}(r_\\perp,\\phi,z,t) &=iA\\frac{\\beta_{11}}{2h_{11}}e^{-i(\\omega t-f\\beta_{11} z -p\\phi)}\\nonumber\\\\\n&\\qquad \\left[ (1-s_{11})J_0(h_{11}r_\\perp)-(1+s_{11})J_2(h_{11}r_\\perp) \\right]\\\\\nE^{(\\mu)}_\\phi(r_\\perp,\\phi,z,t) &=  -pA \\frac{\\beta_{11}}{2h_{11}}e^{-i(\\omega t-f\\beta_{11} z -p\\phi)} \\nonumber\\\\\n&\\qquad \\left[ (1-s_{11})J_0(h_{11}r_\\perp) +(1+s_{11})J_2(h_{11}r_\\perp) \\right] \\\\\nE^{(\\mu)}_z(r_\\perp,\\phi,z,t) &= fA J_1(h_{11}r_\\perp) e^{-i(\\omega t-f\\beta_{11} z -p\\phi)},\n\\end{align}\n\\end{subequations}\nand, for $ r_\\perp>a $, by\n\\begin{subequations}\n\\label{Ertcrga}\n\\begin{align}\nE^{(\\mu)}_{r_\\perp}(r_\\perp,\\phi,z,t) &=iA\\frac{\\beta_{11}}{2h_{11}}\\frac{J_1(h_{11}a)}{K_1(q_{11}a)}e^{-i(\\omega t-f\\beta_{11} z -p\\phi)} \\nonumber\\\\ \n&\\qquad \\left[ (1-s_{11})K_0(q_{11}r_\\perp)+(1+s_{11})K_2(q_{11}r_\\perp) \\right]\\\\\nE^{(\\mu)}_\\phi(r_\\perp,\\phi,z,t) &=  -pA \\frac{\\beta_{11}}{2h_{11}} \\frac{J_1(h_{11}a)}{K_1(q_{11}a)}e^{-i(\\omega t-f\\beta_{11} z -p\\phi)} \\nonumber\\\\ \n&\\qquad \\left[ (1-s_{11})K_0(q_{11}r_\\perp) - (1+s_{11})K_2(q_{11}r_\\perp) \\right] \\\\\nE^{(\\mu)}_z(r_\\perp,\\phi,z,t) &= fA \\frac{J_1(h_{11}a)}{K_1(q_{11}a)} K_1(q_{11}r_\\perp) e^{-i(\\omega t-f\\beta_{11} z -p\\phi)}.\n\\end{align}\n\\end{subequations}\nIn Eqs.~\\ref{Ertcrla} and~\\ref{Ertcrga}, we denote the normalized bound fundamental modes as $ \\mathbf{E}^{(\\mu)} (\\br,t)$ by the superscript $ \\mu=(\\omega,f,p) $, where $ f=\\pm $, as before, denote forward $(+)$ or backward $(-)$ propagation direction, and $ p=\\pm$ denote the positive $(+)$ or negative $(-)$ helicities of polarization. Similar to the quasi-linear case, we use $ \\boldsymbol{\\mathcal{E}}^{p=\\pm} $ to indicate the spatial components of the field with a given circulation pattern. For a linearly polarized \\HE mode, the cylindrical components are just the superposition of the two circular fields, \n\\begin{align}\\label{Eilincyc}\nE_i^{lin} = \\frac{1}{\\sqrt{2}}(E_i^+ + E_i^-)\\quad \\mathrm{or}\\quad \\mathcal{E}_i^{lin} = \\frac{1}{\\sqrt{2}}(\\mathcal{E}_i^+ + \\mathcal{E}_i^-),\\quad i\\in(r_\\perp,\\phi,z).\n\\end{align}\n\n\\section{Power flow and normalization factor \\texorpdfstring{$ A $}{A}}\nAs discussed in Vetsch's dissertation~\\cite{Vetsch2010Opticala}, the real-valued amplitude factor $ A $ can be calculated by normalizing the total power of the light propagating in the fiber via the Poynting vector\\index{Poynting vector}\n\\begin{align}\n\\left<\\mathbf{S}\\right>=\\frac{1}{2} \\Re\\left[\\boldsymbol{\\mathcal{E}}^g(\\br)\\times{\\boldsymbol{\\mathcal{H}}^g(\\br)}^* \\right],\n\\end{align}\nwhere $ \\boldsymbol{\\mathcal{H}}^g(\\br) $ is the magnetic field of the guided light. \nSince the $ z $-component of the Poynting vector\\index{Poynting vector} $ \\left< S_z\\right> $ qualifies the energy flux of the electromagnetic field in the propagation direction, integrating $ \\left< S_z \\right> $ over the transverse plane leads to the power propagating inside and outside the fiber as\n\\begin{align}\nP_{in} &= \\int_0^{2\\pi} \\mathrm{d}\\phi \\int_0^a \\left< S_z \\right> r_\\perp \\mathrm{d}r_\\perp ,\\\\\nP_{out} &= \\int_0^{2\\pi} \\mathrm{d}\\phi \\int_a^\\infty \\left< S_z \\right> r_\\perp \\mathrm{d}r_\\perp.\n\\end{align}\nUsing the total transmission power $ P=P_{in}+P_{out} $, the normalization constant $ A $ reads\n\\begin{align}\\label{eq:A}\nA=\\sqrt{\\frac{4\\mu_0\\omega P}{\\pi a^2 \\beta_{11}}}\\left(D_{in} + D_{out} \\right)^{-1/2},\n\\end{align}\nwhere\n\\begin{align}\nD_{in} &= (1-s_{11})\\left[ 1+(1-s_{11})\\frac{\\beta_{11}^2}{h_{11}^2}\\right] \\left(J_0^2(h_{11}a) + J_1^2(h_{11}a) \\right) \\nonumber\\\\\n&\\quad + (1+s_{11})\\left[ 1+(1+s_{11})\\frac{\\beta_{11}^2}{h_{11}^2}\\right] \\left(J_2^2(h_{11}a)- J_1(h_{11}a)J_3(h_{11}a) \\right),\\\\\nD_{out} &= \\frac{J_1^2(h_{11}a)}{K_1^2(q_{11}a)}\\left\\{ (1-s_{11})\\left[ 1-(1-s_{11})\\frac{\\beta_{11}^2}{q_{11}^2}\\right] \\left(K_0^2(q_{11}a) - K_1^2(q_{11}a) \\right)\\right. \\nonumber\\\\\n&\\quad \\left. + (1\\!+\\! s_{11})\\left[ 1\\!-\\! (1\\!+\\! s_{11})\\frac{\\beta_{11}^2}{q_{11}^2}\\right] \\left(K_2^2(q_{11}a)\\! -\\! K_1(q_{11}a)K_3(q_{11}a) \\right) \\right\\}.\n\\end{align}\nThe ratio of $ D_{in} $ and $ D_{out} $ indicates the intensity distribution division inside and outside of the nanofiber, respectively. \n\n\\section{Energy density and normalization factor for traveling field quantization}\nThe energy per unit length stored in the waveguide is defined as\n\\begin{align}\nW &= \\frac{1}{2} \\int \\mathrm{d}\\br\\!_\\perp n^2(\\br\\!_\\perp) |\\boldsymbol{\\mathcal{E}}^g(\\br\\!_\\perp)|^2.\n\\end{align} \nIn our case, we can rewrite the integral over the transverse plane as the sum of inside and outside of the nanofiber parts, \\emph{i.e.},\n\\begin{align}\n\\int \\mathrm{d} \\br\\!_\\perp &= \\int_0^{2\\pi}\\!\\!\\!\\! \\mathrm{d} \\phi \\int_0^a\\!\\!r\\!_\\perp \\mathrm{d}r\\!_\\perp + \\int_0^{2\\pi}\\!\\!\\!\\! \\mathrm{d} \\phi \\int_a^\\infty\\!\\!r\\!_\\perp \\mathrm{d}r\\!_\\perp.\n\\end{align}\nHence, the energy stored per unit distance of propagation can be rewritten as \n\\begin{align}\nW &= n_1^2P_1+n_2^2P_2,\n\\end{align}\nwhere the power flow or the intensity distribution factors $ P_1 $ and $ P_2 $ can be found by\n\\begin{align}\n\\!\\!\\!\\!\\! P_1 &= \\int_0^{2\\pi} \\!\\!\\mathrm{d} \\phi \\int_0^a\\!\\!\\mathrm{d}r\\!_\\perp r\\!_\\perp|\\boldsymbol{\\mathcal{E}}^g(\\br\\!_\\perp)|^2\\\\\n&= \\frac{\\beta^2}{4h^2}\\!\\left\\{(1\\!-\\! s)^2\\!\\left[J_0^2(ha)\\!+\\! J_1^2(ha) \\right] \\!+\\!(1\\!+\\!s)^2\\!\\left[J_2^2(ha)\\!-\\!J_1(ha)J_3(ha) \\right]\\right\\}\\nonumber\\\\\n&\\quad +\\frac{1}{2}\\left[J_1^2(ha)-J_0(ha)J_2(ha) \\right], \\\\\n\\!\\!\\!\\!\\! P_2 &= \\int_0^{2\\pi} \\!\\!\\mathrm{d} \\phi \\int_a^\\infty\\!\\!\\mathrm{d}r\\!_\\perp r\\!_\\perp|\\boldsymbol{\\mathcal{E}}^g(\\br\\!_\\perp)|^2\\\\\n&= \\frac{\\beta^2J_1^2(ha)}{4q^2K_1^2(qa)}\\!\\left\\{\\phantom{\\frac{1}{1}}\\!\\!\\!\\!(1\\!-\\!s)^2\\!\\left[K_1^2(qa)\\!-\\!K_0^2(qa) \\right]\\right.\\nonumber\\\\\n&\\quad\\left. \\!+(1\\!+\\!s)^2\\!\\!\\left[K\\!_1\\!(qa)K\\!_3\\!(qa)\\!-\\! K_2^2\\!(qa) \\right]\\!+\\!\\frac{2q^2}{\\beta^2}\\!\\!\\left[K\\!_0\\!(qa)K\\!_2\\!(qa)\\!-\\!K_1^2\\!(qa) \\right]  \\right\\}.\n\\end{align}\nAbove, we have removed the subscript $ _{11} $ so that $ q=q_{11} $, $ s=s_{11} $ and $ h=h_{11} $.\n\nAlso, to quantize the traveling field of waveguide modes, we can define the normalization factor to be~\\cite{LeKien2005a}\n\\begin{align}\nN_g &= \\int_0^{2\\pi} \\!\\!\\mathrm{d} \\phi \\int_0^\\infty\\!\\!\\mathrm{d}r\\!_\\perp r\\!_\\perp\\,  n^2(\\br\\!_\\perp)|\\boldsymbol{\\mathcal{E}}^g(\\br\\!_\\perp)|^2 = 2\\pi A^2 a^2 (n_1^2P_1 + n_2^2P_2),\n\\end{align}\nwhere the factor $ A $ is defined in Eq.~\\eqref{eq:A} related to the input power. The full expression of unguided modes of the nanofiber system can also be found in Ref.~\\cite{LeKien2005a}.\n\nFor some cases, the total power $ P $ can also be defined as\n\\begin{align}\nP &= \\int \\mathrm{d}\\br\\!_\\perp \\langle S(\\br\\!_\\perp)\\rangle =\\int \\mathrm{d} \\br\\!_\\perp I(\\br\\!_\\perp)=\\frac{\\varepsilon_0 c n_{e\\!f\\!f}}{2}\\int |\\boldsymbol{\\mathcal{E}}^g(\\br\\!_\\perp)|^2,\n\\end{align}\nwhere $ n_{e\\!f\\!f} $ is the effective index of refraction of the waveguide. \nBy plugging in the field expression from Eqs.~\\eqref{Ertcrla} and~\\eqref{Ertcrga}, we find the effective index of refraction for the \\HE modes of the nanofiber to be given by\n\\begin{align}\nn_{e\\!f\\!f} &=\\frac{\\int \\mathrm{d}\\br\\!_\\perp n^2(\\br\\!_\\perp) |\\boldsymbol{\\mathcal{E}}^g(\\br\\!_\\perp)|^2}{\\int |\\boldsymbol{\\mathcal{E}}^g(\\br\\!_\\perp)|^2}\\\\\n&= \\frac{n_1^2\\int_0^{2\\pi} \\!\\!\\mathrm{d} \\phi \\int_0^a\\!\\!r\\!_\\perp\\mathrm{d}r\\!_\\perp|\\boldsymbol{\\mathcal{E}}^g(\\br\\!_\\perp)|^2 + n_2^2\\int_0^{2\\pi}\\!\\! \\mathrm{d} \\phi \\int_a^\\infty\\!\\!r\\!_\\perp \\mathrm{d}r\\!_\\perp|\\boldsymbol{\\mathcal{E}}^g(\\br\\!_\\perp)|^2}\n{\\int_0^{2\\pi} \\!\\!\\mathrm{d} \\phi \\int_0^a\\!\\!r\\!_\\perp\\mathrm{d}r\\!_\\perp|\\boldsymbol{\\mathcal{E}}^g(\\br\\!_\\perp)|^2 + \\int_0^{2\\pi}\\!\\! \\mathrm{d} \\phi \\int_a^\\infty\\!\\!r\\!_\\perp \\mathrm{d}r\\!_\\perp|\\boldsymbol{\\mathcal{E}}^g(\\br\\!_\\perp)|^2}\\\\\n&= \\frac{n_1^2P_1+n_2^2P_2}{P_1+P_2}.\n\\end{align}\nNotice that the group index of refraction\\index{group index of refraction} is not the same as the $ n_{e\\!f\\!f} $ defined above. We will discuss group velocity and group index of refraction of a waveguide in Secs.~\\ref{sec:groupvelocity} and~\\ref{sec:eigenmodesofwaveguides}.\n\n\\section{Solution of guided eigenmodes}\nFollowing the normalization condition in Eq.~\\eqref{eq:eigenmodeorthog} when $ \\mu=\\mu' $, one can solve for the guided eigenmodes. \nFor now, we stick to the notation of the main text, that is to denote the HE$ _{11} $ mode index by frequency $\\omega_0$, propagation constant $ \\beta_0 $, propagation direction $b=f = \\pm$, and polarization $p$.\n\nA relatively simple form for the guided mode functions can be expressed in a cylindrical basis $(r_\\perp, \\phi, z)$ with longitudinal unit vector $\\mathbf{e}_z$, oriented along the fiber axis.  \nThe transverse unit vectors are related to their fixed Cartesian counterparts via the relations\n\\begin{subequations}\n\t\\begin{align}\n\t\t\\mathbf{e}_{r_{\\!\\perp}}     &= \\mathbf{e}_x \\cos \\phi + \\mathbf{e}_y \\sin \\phi, \\\\\n\t\t\\mathbf{e}_\\phi &= - \\mathbf{e}_x \\sin \\phi + \\mathbf{e}_y \\cos \\phi.\n\t\\end{align}\n\\end{subequations}\nThe transverse profile for the quasi-circular guided modes, $p = \\pm$, is\n\t\\begin{align} \\label{Eq::QuasicircularModes}\n\t\t\\mbf{u}_{b,\\pm}(\\mathbf{r}_\\perp) = \\big[\\mathbf{e}_{r_{\\!\\perp}} u_{r_{\\!\\perp}}(r_\\perp) \\pm i \\mathbf{e}_\\phi u_\\phi(r_\\perp) +  i b \\mathbf{e}_z  u_z(r_\\perp) \\big]e^{ \\pm i \\phi}, \n\t\\end{align}\nand for the quasilinear guided modes, $p = \\{H,V\\}$, is\n\t\\begin{subequations} \\label{Eq::QuasilinearModes}\n\t\\begin{align}\n\t\t\\mbf{u}_{b,H}(\\mathbf{r}_\\perp) = & \\sqrt{2} \\big[ \\mathbf{e}_{r_{\\!\\perp}} u_{r_{\\!\\perp}}(r_\\perp) \\cos \\phi - \\mathbf{e}_\\phi u_\\phi(r_\\perp) \\sin \\phi +  ib \\mathbf{e}_z  u_z(r_\\perp) \\cos \\phi \\big] \\\\\n\t\t\\mbf{u}_{b,V}(\\mathbf{r}_\\perp) = & \\sqrt{2} \\big[ \\mathbf{e}_{r_{\\!\\perp}} u_{r_{\\!\\perp}}(r_\\perp) \\sin \\phi + \\mathbf{e}_\\phi u_\\phi(r_\\perp) \\cos \\phi +  ib \\mathbf{e}_z  u_z(r_\\perp) \\sin \\phi \\big]. \n\t\\end{align}\n\t\\end{subequations}\nThe modes are expressed in terms of real-valued functions that depend only on the radial coordinate $r_\\perp$,\n\t\\begin{subequations} \\label{Eq::ProfileFunctions}\n\t\\begin{align} \n\t\tu_{r_{\\!\\perp}}(r_\\perp) =& u_0 \\big[ (1-s) K_0(q{r_{\\!\\perp}}) + (1+s)K_2(q{r_{\\!\\perp}})\\big] \\\\\n\t\tu_\\phi(r_\\perp) =& u_0\\big[ (1-s) K_0(q{r_{\\!\\perp}}) - (1+s)K_2(q{r_{\\!\\perp}})\\big] \\\\\n\t\tu_z(r_\\perp) =& u_0 \\frac{2 q}{\\beta_0} \\frac{K_1(qa)}{J_1(ha)} J_1(h{r_{\\!\\perp}}), \\label{Eq::zprofile}\n\t\\end{align}\n\t\\end{subequations}\nwhere $u_0$ is set by the normalization condition, $\\int d^2 \\mathbf{r}_\\perp n(r_\\perp) | \\mathbf{u}_\\mu(\\br_\\perp)|^2=1$, and \n\t\\begin{align}\n\t\ts = \\frac{1/(q^2 a^2)^{2} + 1/(h^2 a^2)^{2}}{[J'_1(ha)/haJ_1(ha) + K'_1(qa)/qaK_1(qa)]}.\n\t\\end{align}  \nOf particular interest is the $z$-component, \\erf{Eq::zprofile}, which can become appreciable.  Note that the phase convention in Eqs. (\\ref{Eq::QuasicircularModes}-\\ref{Eq::ProfileFunctions}) has been chosen to emphasize properties of the quasilinear modes and differs from that of \\emph{Le Kien et al.} -- for instance in Ref. \\cite{LeKien2014}.  \nFurther details about the guided mode fields inside the nanofiber ($r_\\perp\\leq a$), the radiation (unguided) modes, and the quantized form of both can be found in Refs. \\cite{Sondergaard2001,Tong2004,Kien2004,LeKien2005,Vetsch2010Opticala}.\n\n\n\\section{Calculation of group velocity and group index of refraction (\\texorpdfstring{$ v_g $}{vg} and \\texorpdfstring{$ n_g $}{ng})}\\label{sec:groupvelocity}\nFor a guided mode in a waveguide, the phase index of refraction, $n_p$, is defined as\n\\begin{align}\nn_p &= \\left.\\frac{\\beta}{k}\\right|_{\\beta=\\beta_0}.\n\\end{align}\nCorrespondingly, the group velocity, $v_g$, and group index of refraction\\index{group index of refraction}, $n_g$, for a guided mode in a waveguide can be given by\n\\begin{align}\nv_g &= \\left.\\dd{\\omega}{\\beta}\\right|_{\\beta=\\beta_0},\\\\\nn_g &= \\frac{c}{v_g}=\\left.\\dd{\\beta}{k}\\right|_{\\beta=\\beta_0}.\n\\end{align}\nTherefore, these quantities of $ HE_{11} $ mode can be calculated from the eigen function of $ \\beta $~\\cite{LeKien2005a}. \n\nAnalytically, the eigen function of $ \\beta $ [Eq.~\\eqref{eq:eigenfunctionbeta}] can be expressed as\n\\begin{align}\nf(h,q,k,\\beta) &=0,\n\\end{align}\nwhere$ h $ and $ q $ are both functions of $ k $ and $ \\beta $. \nWe differentiate the equation above with respect to $ \\beta $ on both sides, and obtain\n\\begin{align}\n\\dd{f}{\\beta} &= \\pp{f}{h} \\left(\\pp{h}{k}\\dd{k}{\\beta}+\\pp{h}{\\beta} \\right) + \\pp{f}{q}\\left(\\pp{q}{k}\\dd{k}{\\beta}+\\pp{q}{\\beta} \\right) +\\pp{f}{k}\\dd{k}{\\beta}+\\pp{f}{\\beta}=0\\\\\n\\Rightarrow & \\left( \\pp{f}{h}\\pp{h}{k}+\\pp{f}{q}\\pp{q}{k}+\\pp{f}{k} \\right)\\dd{k}{\\beta} = -\\left(\\pp{f}{h}\\pp{h}{\\beta}+\\pp{f}{q}\\pp{q}{\\beta}+\\pp{f}{\\beta} \\right)\n\\end{align}\n\\begin{align}\n\\Rightarrow &\\quad\\quad n_g = \\dd{\\beta}{k} = -\\frac{\\pp{f}{h}\\pp{h}{k}+\\pp{f}{q}\\pp{q}{k}+\\pp{f}{k}}\n{\\pp{f}{h}\\pp{h}{\\beta}+\\pp{f}{q}\\pp{q}{\\beta}+\\pp{f}{\\beta}}.\n\\end{align}\n\nPhysically, the group index of refraction\\index{group index of refraction} indicates the waveguide dispersion for a given propagating mode. Here, we can ignore the material dispersion due to the small response delay of the silica molecules of the waveguide substrate. Since the waveguide dispersion is merely a property of the waveguide, the presence of the radiating atom does not affect the group index of refraction at all (we have checked numerically through solving the eigen function of $ \\beta $ in presence of an atom). \n\nFrom the perspective of energy flow, the group velocity can also be given by\n\\begin{align}\nv_g&=\\frac{P}{W}.\n\\end{align}\n%The physical interpretation of group and phase velocity of a waveguide mode can be found in the notes on \\emph{Group velocity of the nanofiber}\\satomi{Reference the section}. \nThe effective zig-zag ray model is also described in the notes for understanding the mechanism of group and phase index of refractions. For our nanofiber case, the $ D_2 $ transition line of Cs atoms does not have a strong enhancement of group index of refraction\\index{group index of refraction} for the guided mode, compared to the phase index of refraction. The $ D_1 $ line has a relatively strong enhancement of group index since the wave can penetrate into the clad much deeper compared to the $ D_2 $ line case. \n\n\n%</eigenmodes>\n\n\n%<*paraxialexpansion>\n\\chapter[The paraxial approximation]{Paraxial approximation in solving eigenmode and dipole radiation problems}\\label{chap:paraxialapproximation}\nIn the case where light fields propagate along a certain direction, say $ z $, and spread out only slowly in the transverse direction, \\emph{paraxial approximation}\\index{paraxial approximation} can be used to simplify the light propagation problem, specifically, in the analytic calculationl of the Fourier integrals of the fields. Then, the $ z $ component of the wave vectors can be expanded in a series as\n\\begin{align}\nk_z=k_0\\sqrt{1-(k^2_x+k^2_y)/k_0^2}\\approx k_0-\\frac{(k^2_x+k^2_y)}{2k_0}.\n\\end{align}\nThis reflects the physical fact that the wave vectors\\index{wavevector} $ \\mathrm{k}=(k_x,k_y,k_z) $ in the angular spectrum representation are almost parallel to the $ z $ axis and that the transverse wave numbers $ (k_x,k_y) $ are small compared to $ k_0 $. \n\nMeanwhile, paraxial approximation\\index{paraxial approximation} gives $ \\theta\\rightarrow 0 $, and hence\n\\begin{align}\n\\hat{\\mathrm{r}} &= \\sin\\theta\\cos\\phi \\, \\hat{\\mathrm{e}}_x + \\sin\\theta \\sin\\phi\\, \\hat{\\mathrm{e}}_y + \\cos\\theta \\, \\hat{\\mathrm{e}}_z\\\\\n&\\approx \\hat{\\mathrm{e}}_z.\n\\end{align}\n\n\\section[Paraxial approximation for light propagation]{Paraxial approximation for \\\\ Maxwell equations and Gaussian laser beams}\nIn the paraxial approximation, the field propagating in the $ z $ direction can be treated as dominated by a plane wave, and hence one can assume a free propagating optical field has a form\n\\begin{align}\n\\mathbf{A}(\\br) =A_0 \\mathbf{u}(\\br)e^{ik_0z},\n\\end{align}\nwhere $ A_0 $ is a scaling factor, and $ \\mathbf{u}(\\br) $ is the complex amplitude or mode of the field.  The equation for $ \\mathbf{u}(\\br)$ (the wave (Helmholtz) equation),\n\\begin{align}\n\\left[\\nabla_\\perp^2 +i2k_0\\pp{}{z}\\right] \\mathbf{u}(\\br) =0,\n\\end{align}\nwhere $ \\nabla_\\perp^2\\equiv \\frac{\\partial^2}{\\partial x^2}+\\frac{\\partial^2}{\\partial y^2} $ is the transverse part of the Laplacian, can be solved approximately. The paraxial approximation\\index{paraxial approximation} assumes that $ \\mathbf{u}(\\br) $ is a slowly-varying function of $ z $, \\emph{i.e.},\n\\begin{align}\n\\left|\\frac{\\partial^2 \\mathbf{u}}{\\partial z^2}\\right| \\ll \\left| k_0\\frac{\\partial\\mathbf{u}}{\\partial z}\\right|.\n\\end{align}\nTherefore, one can ignore the second derivatives of $ z $ if $  k_0\\frac{\\partial\\mathbf{u}}{\\partial z} $ terms appear in the wave equation of the field. Using the relations above, the wave equation for such a field can be given by\n\\begin{align}\n\\left[\\nabla_\\perp^2+i\\,2k_0\\pp{}{z}+2k_0^2\\right] \\mathbf{A}(\\br)=0.\n\\end{align}\n\nOne of the solutions of the wave equation above defines the Gaussian beam of lasers. The fundamental mode of a Gaussian beam is the TEM$_{00}$ mode, which defines the electric field in the following form if the light is assumed to be polarized along the $ x $ axis~\\cite{Born1999Principles},\n\\begin{align}\n\\mathbf{E}(\\br) &\\equiv E_0\\mathbf{u}_{00}(\\br)e^{ik_0z}\\\\\n&= E_0 \\mathbf{e}_x \\frac{w_0}{w(z)}\\exp\\left[-\\frac{r_\\perp^2}{w(z)^2} \\right] \\exp\\left[-i\\left( k_0z+k_0\\frac{r_\\perp^2}{2R(z)} -\\psi(z)\n\\right) \\right],\n\\end{align}\nwhere $ z $ is the distance to the beam's focus in the propagation direction, $ w(z) $ is the radius at which the field amplitudes fall to $1/e$ of their axial values at the $z$ plane along the beam, $ w_0 $ is the beam's waist radius, $ R(z) $  is the radius of curvature of the beam's wavefronts at $z$, and $ \\psi(z) $  is the Gouy phase at $z$, and extra phase terms beyond that attribute to the phase velocity of light. We usually have \n\\begin{align}\nw(z) &=w_0\\sqrt{1+\\left(\\frac{z}{z_R} \\right)^2},\\\\\nR(z) &= z\\left[1+\\left(\\frac{z_R}{z}\\right)^2 \\right],\\\\\n\\psi(z) &= \\arctan\\left( \\frac{z}{z_R}\\right),\n\\end{align}\nwhere $ z_R=\\pi w_0^2/\\lambda $ is the Rayleigh range. At the center of the beam waist (focus), the field amplitude reaches the strongest value, which is $ \\sqrt{2}E_0/\\sqrt{\\pi w_0^2} $. We usually define $ A=\\frac{\\pi w_0^2}{2} $ as the mode-area of the mode.\n\n\\section{Paraxial expansion of a propagating dipole radiation mode}\nThe Green's function solution for a point emitter in free space can then be expanded to be\n\\begin{align}\n\\frac{e^{i\\mathrm{k}_0\\cdot \\mathrm{R}}}{R}\\approx \\frac{e^{ik_0(z-z')}}{z-z'}\\exp\\left[ \\frac{ik_0}{2(z-z')} \\left| \\mathrm{r}_\\perp - \\mathrm{r}_\\perp'\\right|^2 \\right],\n\\end{align}\nwhere $ \\mathrm{R}=\\br-\\br' $. \nA far field from a point light-emitter is usually paraxial approximation\\index{paraxial approximation} obedient. \n%</paraxialexpansion>\n\n\n%<*freespacegreenfunction>\n\\chapter[Green's function method for a homogeneous medium and beyond]{Green's function method for a homogeneous medium and calculation methods}\\label{chap:freespacegreenfunction}\nAs one simple example, we consider a free-space case where the photon emitter is placed in the vacuum background. Then the vector potential $ \\mathbf{A}(\\br) $ and scalar potential $ \\phi(\\br) $ are found in the following equations, \n\\begin{align}\n\\boldsymbol{\\mathcal{E}}(\\br) &= ik_0\\mathbf{A}-\\nabla\\phi(\\br), \\label{eq:EAphi}\\\\\n\\boldsymbol{\\mathcal{B}}(\\br) &= \\nabla\\times\\mathcal{A}(\\br,\n\\end{align}\nwhere they satisfy the Lorentz Gauge transformation relation\n\\begin{align}\n\\nabla \\cdot \\mathbf{A}(\\br) &= ik_0\\phi(\\br).\\label{eq:LorentzGauge}\n\\end{align} \nUsing the Maxwell equations, Eqs.~\\ref{eq:maxwelldiv} and~\\ref{eq:maxwellgrad}, one can easily obtain the following wave equations for the potentials:\n\\begin{align}\n\\left[ \\nabla^2+k_0^2 \\right]\\mathbf{A}(\\br) &= -\\frac{4\\pi}{c} \\mathcal{J},\\\\\n\\left[ \\nabla^2+k_0^2 \\right]\\phi(\\br) &= -4\\pi\\rho.\n\\end{align}\nWe have used the relation that $ \\nabla\\times\\nabla\\times =-\\nabla^2+\\nabla(\\nabla\\cdot) $. \nThese wave equations are in the form,\n\\begin{align}\n\\left[\\nabla^2+k_0^2 \\right]f(\\br) &= -g(\\br).\n\\end{align}\nTherefore, one can define a Green's function by\n\\begin{align}\n\\left[\\nabla^2+k_0^2 \\right]G_0(\\br,\\br') &= -4\\pi k^2_0\\delta(\\br-\\br').\n\\end{align}\nThis can be solved easily by transforming the equation above into the $k$-space by Fourier transformation so that \n\\begin{align}\n\\left[ -k^2+k_0^2\\right] G_0(\\mathbf{k},\\mathbf{k}') &= -4\\pi k_0^2 e^{-i\\mathbf{k}\\cdot(\\br-\\br')},\\label{eq:Gkk'equation}\n\\end{align}\nwhich leads to \n\\begin{align}\nG_0(\\mathbf{k},\\mathbf{k}') =\\frac{4\\pi k_0^2 e^{-i\\mathbf{k}\\cdot(\\br-\\br')}}{k^2-k_0^2}.\n\\end{align}\nWhen we transfer the $ k $-space solution to the real 3D $ \\br $ space, we obtain the valid scalar Green's function solutions of a point source:\n\\begin{align}\\label{scalarG}\nG_0(\\br,\\br') =k_0^2\\frac{e^{\\pm i\\mathbf{k}_0\\cdot (\\mathbf{r}-\\br')}}{|\\br-\\br'|}=k_0^2\\frac{e^{\\pm ik_0 |\\mathbf{r}-\\br'|}}{|\\br-\\br'|},\n\\end{align}\nwhere the $ \\pm $ signs correspond to the outgoing ($+$, due to causality) and incoming ($-$) propagating spherical waves from the point source, and the wave is propagating along the $ \\br-\\br' $ direction with wavenumber $ k_0 $. The different signs are obtained by choosing different contour integrals in the inverse transformation. We use the positive frequency or the outgoing solution for our radiation problem due to causality. With this scalar Green's function, we can find the vector potential by\n\\begin{align}\n\\mathbf{A} (\\br) &= \\frac{c}{\\omega_0^2} \\int_V \\mathcal{J}(\\br')G_0(\\br,\\br')\\mathrm{d}^3 r'.\\label{eq:freespaceAG0int}\n\\end{align}\nA similar equation holds for the scalar potential $ \\phi(\\br) $. \n\nIn the meantime, if we plug in the Lorentz Gauge transformation relation, Eq.~\\ref{eq:LorentzGauge}, into Eq.~\\ref{eq:EAphi}, we can find that \n\\begin{align}\n\\boldsymbol{\\mathcal{E}}(\\br) &= ik_0\\left[1+ \\frac{1}{k_0^2}\\nabla\\nabla\\cdot \\right]\\mathbf{A}(\\br).\\label{eq:freespaceEA}\n\\end{align}\n\nComparing with the wave equation based on Eq.~\\ref{eq:Maxwellwithsource2}:\n\\begin{align}\\label{eq:freespacewaveeq_general}\n-\\left[\\nabla\\times\\nabla\\times +\\frac{\\omega_0^2}{c^2}\\right]\\boldsymbol{\\mathcal{E}}(\\br) =  -4\\pi\\! \\frac{\\omega_0^2}{c^2}\\! \\tensor{\\boldsymbol{\\chi}}(\\br)\\! \\cdot\\! \\boldsymbol{\\mathcal{E}}(\\br)=-i4\\pi\\frac{\\omega_0}{c^2}\\mathcal{J},\n\\end{align}\nwhere we have set $ n=1 $ for the vacuum medium from Eq.~\\eqref{eq:Maxwellwithsource2}, we define a dyadic Green's function\\index{dyadic Green's function} $ \\tensor{\\mathbf{G}}(\\br,\\br') $ by \n\\begin{align}\n\\left[ -\\nabla\\times\\nabla\\times + n^2\\frac{\\omega_0^2}{c^2} \\right] \\GFT(\\br,\\br') &=-4\\pi k_0^2\\delta^{(3)}(\\br-\\br')\\unittensor,\\label{eq:freespaceGFTJ}\n\\end{align}\nso that \n\\begin{align}\n\\boldsymbol{\\mathcal{E}}(\\br)&= \\frac{i}{\\omega_0}\\int_V \\GFT(\\br,\\br')\\mathcal{J}(\\br')\\mathrm{d}^3 r'.\\label{eq:freespaceEGint}\n\\end{align}\nThis is the scattered or radiated field from the point source current. \n\nThe first column vector of $ \\GFT(\\br,\\br') $, or $ \\mathbf{G}_x $, defined in Eq.~\\ref{eq:freespaceGFTJ} is formally the electric field due to a point-source current $ \\mathcal{J}=\\frac{\\omega_0}{i}\\delta^{(3)}(\\br-\\br')\\mathbf{e}_x $, where $ \\mathbf{e}_x $ is the unit vector on the $ x $ direction.  \nBased on Eq.~\\ref{eq:freespaceAG0int}, the vector potential from this source current is \n\\begin{align}\n\\mathbf{A}(\\br) &= \\frac{1}{ik_0}G_0(\\br,\\br')\\mathbf{e}_x.\n\\end{align}\nSubstituting this into Eq.~\\ref{eq:freespaceEA} and using Eq.~\\ref{eq:freespaceEGint}, we find \n\\begin{align}\n\\mathbf{G}_x (\\br,\\br') &= \\left[1+ \\frac{1}{k_0^2}\\nabla\\nabla\\cdot \\right]G_0(\\br,\\br')\\mathbf{e}_x.\n\\end{align}\nOne can derive similar equations for $ \\mathbf{G}_y $ and $ \\mathbf{G}_z $. By the definition $ \\nabla\\cdot\\left[G_0\\unittensor \\right]=\\nabla G_0 $, one can rewrite the vector equations of the Green's function above into the full tensor form by\n\\begin{align}\\label{eq:GFThomG0}\n\\GFT(\\br,\\br') &=  \\left[\\unittensor + \\frac{1}{k_0^2}\\nabla\\nabla \\right]G_0(\\br,\\br').\n\\end{align}\nThis is the Green's function of a free dipole in a homogeneous background expressed in terms of the scalar Green's function $ G_0(\\br,\\br') $. Then the field can be expanded as a volume integral by\n\\begin{align}\n\\boldsymbol{\\mathcal{E}}(\\br) &= \\boldsymbol{\\mathcal{E}}_0(\\br) + \\frac{i}{\\omega_0}\\int_V\\GFT(\\br,\\br')\\mathcal{J}(\\br')\\mathrm{d}^3 r'\\\\\n&=\\boldsymbol{\\mathcal{E}}_0(\\br) + \\int_V\\GFT(\\br,\\br')\\tensor{\\boldsymbol{\\chi}}(\\br')\\cdot\\boldsymbol{\\mathcal{E}}(\\br')\\mathrm{d}^3 r',\\label{eq:EGFTinteq}\n\\end{align}\nwhere $ \\boldsymbol{\\mathcal{E}}_0(\\br) $ is an input field (if any) propagating in the free background medium. Eq.~(\\ref{eq:EGFTinteq}) is the quadrature with a dipole point-source that solves for the electric field $ \\boldsymbol{\\mathcal{E}} $. Corresponding to the free-propagating field $ \\boldsymbol{\\mathcal{E}}_0 $, we define the scattering term due to the presence of the source by\n\\begin{align}\n\\boldsymbol{\\mathcal{E}}_s(\\br) &= \\int_V \\GFT(\\br,\\br') \\tensor{\\boldsymbol{\\chi}}(\\br')\\! \\cdot\\! \\boldsymbol{\\mathcal{E}}(\\br') \\mathrm{d}^3 r' \\label{eq:Escattint}\\\\\n&=  \\int_V\\GFT(\\br,\\br')\\cdot \\mathbf{d}(\\br') \\mathrm{d}^3r',\\label{EGd}\n\\end{align}\nwhere we have defined a dipole source $\\mathbf{d}(\\br')= \\tensor{\\boldsymbol{\\chi}}(\\br')\\! \\cdot\\! \\boldsymbol{\\mathcal{E}}(\\br') $.\n\nIn general, scattering problems cannot be solved analytically, due to the presence of the complicated scattered field and medium geometries. By the use of Green's function method, we have converted our differential equation for the scattered field into volume integral equations. One can use Eq.~(\\ref{eq:EGFTinteq}) in order to solve a general scattering problem with arbitrary boundary condition and source distributions. \n%This can be done by placing the sources in a well-characterized volumes of media. \nThe formalism established here is very important since they form the basis for various formalisms such as the \\emph{method of moments}\\index{method of moments}, the \\emph{Lippmann-Schwinger equation}\\index{Lippmann-Schwinger equation}, and the \\emph{coupled dipole method}\\index{coupled dipole method}~\\cite{Novotny2012,Wubs2004}. \nIn Appendix~\\ref{sec:boundrad}, instead of solving the integration equations directly, we will solve the radiation problem by using $ G_0(\\br,\\br') $ as a dipole's Green function in free space and projecting $ G_0(\\br,\\br') $ onto the cylindrical boundary condition to find the vector and scalar potentials, $ \\mathbf{A}(\\br) $ and $ \\phi(\\br) $. \n%This allows us to solve for the electric and magnetic field-components, given a boundary condition of a cylindrical waveguide geometry, in which \nThe key in that case is to find the proper decomposition for the Green's function of a free dipole to match up with the boundary geometry. \n\nIn other cases, we may develop a Liouville-Neumann series\\index{Liouville–Neumann series} solution to the equation, namely the Born series\\index{Born series} to solve problems of multiple scatterings.\n\nThe Born series is typically derived by assuming that the scattering potential is very\nweak, and may be written as $ \\tensor{\\boldsymbol{\\chi}}(\\br)\\rightarrow \\delta \\tensor{\\boldsymbol{\\chi}}(\\br) $, where $ \\delta $ is a dimensionless parameter, which ultimately will be set to be $ 1 $ to obtain the solution of the electrical field. We then seek a series of solutions for the total field of the form\n\\begin{align}\n\\boldsymbol{\\mathcal{E}}(\\br) &= \\sum_{n=0}^{\\infty} \\delta^n \\mathbf{V}_n(\\br).\n\\end{align}\nWhen substituting this expression above into Eq.~\\ref{eq:EGFTinteq}, we find the series\n\\begin{align}\n\\mathbf{V}_0 &= \\boldsymbol{\\mathcal{E}}_0,\\\\\n\\mathbf{V}_1 &= \\int_V \\GFT(\\br,\\br')\\tensor{\\boldsymbol{\\chi}}(\\br')\\cdot\\boldsymbol{\\mathcal{E}}_0(\\br') \\mathrm{d}^3 r',\\\\\n\\ldots & \\ldots\\\\\n\\mathbf{V}_n &= \\int_V \\GFT(\\br,\\br')\\tensor{\\boldsymbol{\\chi}}(\\br')\\cdot\\boldsymbol{\\mathcal{E}}_{n-1}(\\br') \\mathrm{d}^3 r',\n\\end{align}\nwhere $ R=|\\br-\\br'| $ with $ \\mathbf{R}=(\\br-\\br') $, and the \\emph{Born approximation}\\index{Born series!Born approximation} only includes up to the first-order term. Under the Born approximation, the solution for the electric field with one single atom can be given by\n\\begin{align}\n\\boldsymbol{\\mathcal{E}} (\\br) &= \\boldsymbol{\\mathcal{E}}_0 (\\br) + \\int_V \\GFT(\\br,\\br')\\tensor{\\boldsymbol{\\chi}}(\\br')\\cdot\\boldsymbol{\\mathcal{E}}_0(\\br') \\mathrm{d}^3 r'\\\\\n&= \\boldsymbol{\\mathcal{E}}_0(\\br) +\\sum_{\\br'}\\GFT(\\br,\\br') \\tensor{\\boldsymbol{\\alpha}}(\\br') \\! \\cdot\\!\\boldsymbol{\\mathcal{E}}_0 (\\br'),\n\\end{align}\nwhere $ \\boldsymbol{\\alpha}(\\br') $ denotes the polarizability of atoms or dipoles at $ \\br' $. We provide the generic field solution under the Born approximation both in volume integration form for continuous medium, and in the discrete summation form for the case with finite number of sources. Note that Born series does not necessarily converge. \nUsually, verification is required to determine if the perturbation fields are much weaker than the field $ \\boldsymbol{\\mathcal{E}}_0 $ before using Born series. \nDepending on the problem, $ \\GFT(\\br,\\br') $ can be in any explicit form, and can usually be solved by solely using the boundary condition of the problem.\n\nBack to the scattering problem with the vacuum background, when $ \\br\\rightarrow \\br' $ or when we measure the self-induced field at the point source's position $ \\br' $, the real part of the Green's function diverges while the imaginary part is finite.\nThis can be proven as below.\nWe define $ \\mathbf{R}=\\br-\\br' $ with amplitude $ R=|\\br-\\br'| $ and substitute the positive frequency solution of $ G_0(\\br,\\br') $ [Eq.~\\eqref{scalarG}] into Eq.~\\eqref{eq:GFThomG0} to write~\\cite{Novotny2012}\n\\begin{align}\\label{eq:GFThomexpand}\n\\GFT(\\br,\\br') &= \\frac{k_0^2\\exp(ik_0R)}{R}\\left[ \\left( 1 \\!+\\! \\frac{ik_0R \\!-\\! 1}{k_0^2R^2}\\right)\\!\\unittensor \\!+\\! \\left(\\frac{3 \\!-\\! i3k_0R\\!-\\! k_0^2R^2}{k_0^2R^2} \\right)\\!\\frac{\\mathbf{R}\\mathbf{R}}{R^2}\\right].\n\\end{align}\nIn the $ R\\rightarrow 0 $ limit, we can expand\n\\begin{align}\n\\exp(ik_0R) = 1+ ik_0R-\\frac{(k_0R)^2}{2}-\\frac{i(k_0R)^3}{6}+\\cdots \n\\end{align}\nAbove, terms with higher order than $ R^3 $ will not contribute to $ \\lim_{\\br\\rightarrow\\br'} \\GFT(\\br,\\br') $ based on Eq.~\\eqref{eq:GFThomexpand}. \nTherefore, the real part of the vacuum Green's tensor [Eq.~\\eqref{eq:GFThomexpand}] in the $ R\\rightarrow 0 $ limit becomes\n\\begin{align}\n\\lim_{R\\rightarrow 0} \\re\\left[\\GFT(\\br,\\br')\\right] &=\\lim_{R\\rightarrow 0}k_0^2\\left[\\left(\\frac{1}{R}-\\frac{1}{k_0^2R^3} \\right)\\unittensor +\\left(\\frac{3-k_0^2R^2}{k_0^2R^3} \\right)\\frac{\\mathbf{R}\\mathbf{R}}{R^2}\\right.\\nn\\\\\n&\\quad\\left. -\\frac{1}{R}\\unittensor + \\frac{3}{R}\\frac{\\mathbf{R}\\mathbf{R}}{R^2}+\\frac{1}{2R}\\unittensor -\\frac{3}{2R}\\frac{\\mathbf{R}\\mathbf{R}}{R^2} + O(R)  \\right]\\nn\\\\\n&= \\lim_{R\\rightarrow 0} k_0^2\\left[\\left(\\frac{1}{2R}-\\frac{1}{k_0^2R^3} \\right)\\unittensor + \\left(\\frac{3}{k_0^2R^3}+\\frac{1}{2R} \\right)\\frac{\\mathbf{R}\\mathbf{R}}{R^2} +O(R)\\right]\\nn\\\\\n&= \\infty.\n\\end{align}\nCorrespondly, the imaginary part in the $ R\\rightarrow 0 $ limit becomes\n\\begin{align}\n\\lim_{R\\rightarrow 0} \\im\\left[\\GFT(\\br,\\br')\\right] &=\\mathrm{Im}\\left[ \\GFT_0 (\\br^\\prime, \\br^\\prime) \\right]= \\frac{2k_0^3}{3}\\unittensor =G_0\\unittensor,\n\\end{align}\n%At that position, the tensor Green's function is reduced to the scalar Green's function, and the imaginary part can be calculated by first extracting the imaginary part of the Green's function in the Fourier domain or the $ k $-space following Eq.~(\\ref{eq:Gkk'equation}). Then the inverse transform is taken back to the real 3D space by using the corresponding contour integral part (assuming outgoing radiation part). One can show that at the atom position, the imaginary part reads\n%\\begin{align}\n%\\mathrm{Im}\\left[ \\GFT_0 (\\br^\\prime, \\br^\\prime) \\right] &=  G_0\\unittensor,\n%\\end{align}\nwhere we have defined the imaginary part of the Green's tensor projected onto an arbitrary unit vector $ \\mathbf{e}_n $ by\n\\begin{align}\\label{eq:G0_app}\nG_0 &=\\im\\left[\\mathbf{e}_n\\cdot  \\GFT(\\br',\\br')\\cdot \\mathbf{e}_n^*\\right]=\\mathbf{e}_n\\cdot \\im\\left[ \\GFT(\\br',\\br')\\right]\\cdot \\mathbf{e}_n^*=\\frac{2}{3}k_0^3.\n\\end{align}\nSimilar to local density of states used in the scattering problems described by the \\sch equation with a finite potential barrier, one can define the photonic \\emph{total local density of states}\\index{local density of states} by~\\cite{Moroz1995Density}\n\\begin{align}\n\\rho(\\br',\\omega_0) &= \\frac{2\\omega_0}{\\pi c^2} \\im \\left\\{\\tr\\left[\\GFT(\\br',\\br';\\omega_0) \\right]\\right\\}=\\frac{6\\omega_0}{\\pi c^2}G_0,\n\\end{align}\nwhere the prefactor $ \\frac{2\\omega_0}{c^2} $ originates from the fact that the analog of the energy $ E $ used in the \\sch equation is $ E=\\frac{\\omega_0^2}{c^2} $ and hence $ dE=\\frac{2\\omega_0}{c^2}d\\omega_0 $. \n\nNote that, using different conventions of Green's function or units might result in a different expression. For example, without the factor of $ k_0^2 $ when defining the Green's function equation, $ G_0= \\frac{2}{3}k_0 $ (the usual Gauss units); or in the SI units, $ G_0=\\frac{\\varepsilon_0 k_0^3}{6\\pi} $~\\cite{Novotny2012}. One can prove that, if the dipole is radiating in a homogeneous medium with index of refraction $ n $, then in $ G_0 $, $ k_0 $ needs to be replaced with $ nk_0 $. Other equations can be adapted from our framework straightforwardly.\n\nWe use the expression of $ G_0 $ to normalize the waveguide-modified spontaneous decay-rates of atoms with respect to their natural linewidth in related chapters.\n\n%</freespacegreenfunction>\n\n\n%<*nanofiberradiationproblem>\n\n\\chapter[Dipole radiations coupled to an optical nanofiber]{Dipole radiations coupled to the guided and unguided modes of an optical nanofiber}\\label{sec:boundrad}\nIn our study, it is critical to separate the guided mode and the unguided mode. In this section, we present in detail a light propagation theory in the scenario of a nanofiber with a trapped atom. \n\nConsidering that the atom emits photons around the nanofiber, the total electric field in our problem \ncan be written as \n\\begin{align}\\label{Esrt0}\n\\boldsymbol{\\mathcal{E}}(\\br) = \\boldsymbol{\\mathcal{E}}_{source}(\\br) + \n\\boldsymbol{\\mathcal{E}}_{fiber}(\\br)=\\boldsymbol{\\mathcal{E}}_{source}(\\br) + \n\\boldsymbol{\\mathcal{E}}_{scatt}(\\br) +\\boldsymbol{\\mathcal{E}}_{tran}(\\br),\n\\end{align}\nwhere $ \\boldsymbol{\\mathcal{E}}_{source} $ is the electric field generated by the atom source, and $ \\boldsymbol{\\mathcal{E}}_{fiber} $ is the field due to the presence of the nanofiber that includes the \nscattered electrical field $ \\boldsymbol{\\mathcal{E}}_{scatt}(\\br) $ (outside the nanofiber) and transmitted field $ \n\\boldsymbol{\\mathcal{E}}_{tran}(\\br) $ (inside the nanofiber). \n\n\nFirst, we only consider the light propagating in a nanofiber without any scatterers. We estimate \nthe field propagating along the nanofiber as a cylindrical wave due to the geometrical symmetry of the nanofiber. \n\n\n\nNext, we consider the case that an atom -- which can be treated as an electric dipole in the regime we are interested in -- is placed next to the \nnanofiber. Eq.~\\eqref{Esrt0} can be rewritten as \n\\begin{align}\n\\boldsymbol{\\mathcal{E}}(\\br) &= \\boldsymbol{\\mathcal{E}}_{source}(\\br) + \n\\boldsymbol{\\mathcal{E}}_{ref}(\\br)+\\boldsymbol{\\mathcal{E}}_{tran}(\\br)\\\\\n&=\n\t\\begin{cases}\n\t  \\boldsymbol{\\mathcal{E}}_{dipole} (\\br)+ \\boldsymbol{\\mathcal{E}}_{scatt}(\\br) & r\\!_\\perp \\geq a,\\\\\n\t  \\boldsymbol{\\mathcal{E}}_{tran}(\\br) & r\\!_\\perp<a.\n\t\\end{cases} \\\\\n&=\n\t\\begin{cases}\n\t\t  \\boldsymbol{\\mathcal{E}}^{(0)} (\\br)+ \\boldsymbol{\\mathcal{E}}^{(S)}(\\br) & r\\!_\\perp \\geq a,\\\\\n\t\t  \\boldsymbol{\\mathcal{E}}^{(T)}(\\br) & r\\!_\\perp<a.\n\t\t\\end{cases} \\label{Etotalfiber}\n\\end{align}\n\n\nFor longitudinal components of the electric and magnetic fields, we expand them as follows\n\\begin{subequations}\\label{ET0Rexpand}\n\\begin{align}\n\\mathcal{E}^{(T)}_z &= \\sum_{m=-\\infty}^\\infty \\int \\mathrm{d}\\beta e^{im(\\phi-\\phi') + i\\beta (z-z')} \\mathcal{E}^{(T)}_{z,m\\beta}(r\\!_\\perp)\\\\\n&= \\sum_{m=-\\infty}^\\infty \\int \\mathrm{d}\\beta e^{im(\\phi-\\phi') + i\\beta (z-z')} c_{m\\beta} J_m (hr\\!_\\perp),\\\\\n% + B_{m\\beta} Y_m(hr\\!_\\perp)\\right],\\\\\n\\mathcal{E}^{(0)}_{z} &= \\sum_{m=-\\infty}^\\infty \\int \\mathrm{d}\\beta e^{im(\\phi-\\phi') + i\\beta (z-z')} \\mathcal{E}^{(0)}_{z,m\\beta}(r\\!_\\perp)\\\\\n\\mathcal{E}^{(S)}_z &= \\sum_{m=-\\infty}^\\infty \\int \\mathrm{d}\\beta e^{im(\\phi-\\phi') + i\\beta (z-z')} \\mathcal{E}^{(S)}_{z,m\\beta}(r\\!_\\perp)\\\\\n&= \\sum_{m=-\\infty}^\\infty \\int \\mathrm{d}\\beta e^{im(\\phi-\\phi') + i\\beta (z-z')} a_{m\\beta} H_m^{(1)} (pr\\!_\\perp),\n\\end{align}\n\\end{subequations}\n\\begin{subequations}\\label{BT0Rexpand}\n\\begin{align}\n\\mathcal{B}^{(T)}_z &= \\sum_{m=-\\infty}^\\infty \\int \\mathrm{d}\\beta e^{im(\\phi-\\phi') + i\\beta (z-z')} \\mathcal{B}^{(T)}_{z,m\\beta}(r\\!_\\perp)\\\\\n&= \\sum_{m=-\\infty}^\\infty \\int \\mathrm{d}\\beta e^{im(\\phi-\\phi') + i\\beta (z-z')} d_{m\\beta} J_m (hr\\!_\\perp),\\\\\n% + E_{m\\beta} Y_m(hr\\!_\\perp)\\right],\\\\\n\\mathcal{B}^{(0)}_{z} &= \\sum_{m=-\\infty}^\\infty \\int \\mathrm{d}\\beta e^{im(\\phi-\\phi') + i\\beta (z-z')} \\mathcal{B}^{(0)}_{z,m\\beta}(r\\!_\\perp)\\\\\n\\mathcal{B}^{(S)}_z &= \\sum_{m=-\\infty}^\\infty \\int \\mathrm{d}\\beta e^{im(\\phi-\\phi') + i\\beta (z-z')} \\mathcal{B}^{(S)}_{z,m\\beta}(r\\!_\\perp)\\\\\n&= \\sum_{m=-\\infty}^\\infty \\int \\mathrm{d}\\beta e^{im(\\phi-\\phi') + i\\beta (z-z')} b_{m\\beta} H_m^{(1)} (pr\\!_\\perp),\n\\end{align}\n\\end{subequations}\nwhere the superscript indicate the field components of scattering ($S$), dipole oscillation in free space ($0$) and transmission ($ T $). Notice that we have chosen $ m=\\pm 1 $, as the nanofiber can only support HE$_{11}$ modes. \nThe $ r\\!_\\perp $ and $ \\phi $ components of the fields can be obtained using Eq.~\\eqref{EHzgauss}, and $ \\mathcal{B}=\\mathcal{H} $ in Gauss units for given $ m $. \nAlso notice, in the nanofiber case we study, we can define $ z'=0 $ and $ \\phi'=0 $, and hence the factor $ e^{im(\\phi-\\phi') + i\\beta (z-z')} $ in the equations above becomes $ e^{im\\phi + i\\beta z} $.\n\nThe free space dipole emits an electromagnetic field described by\n\\begin{align}\n\\mathcal{A} &= -ik \\mathbf{d}_0 \\frac{e^{ik|\\br-\\br'|}}{|\\br-\\br'|},\n\\end{align}\n\\begin{align}\n\\mathcal{B}^{(0)} &= \\nabla\\times \\mathcal{A}\\nonumber \\\\\n&=-ik\\nabla(\\frac{e^{ik|\\br-\\br'|}}{|\\br-\\br'|})\\times\\mathbf{d}_0=-ik\\nabla G_0(\\br,\\br')\\times\\mathbf{d}_0\\nonumber\\\\\n&=\\quad\\left[\\frac{d_z}{r\\!_\\perp}\\pp{G_0(\\br,\\br')}{\\phi}\\!-\\! d_\\phi\\pp{G_0(\\br,\\br')}{z}\\right]\\mathbf{e}_{r\\!_{\\perp}}\\nonumber\\\\\n&\\quad+\\left[d_{r\\!_\\perp}\\pp{G_0(\\br,\\br')}{z}\\!-\\!d_z\\pp{G_0(\\br,\\br')}{r\\!_\\perp} \\right]\\mathbf{e}_\\phi \\nonumber\\\\\n&\\quad+ \\left[d_\\phi\\pp{G_0(\\br,\\br')}{r\\!_\\perp}\\!-\\! \\frac{d_{r\\!_\\perp}}{r\\!_\\perp}\\pp{G_0(\\br,\\br')}{\\phi} \\right]\\mathbf{e}_z\\\\\n&=\\mathcal{B}^{(0)}_{r\\!_\\perp}\\mathbf{e}_{r\\!_{\\perp}} +\\mathcal{B}^{(0)}_\\phi\\mathbf{e}_\\phi + \\mathcal{B}^{(0)}_z\\mathbf{e}_z,\\\\\n\\mathcal{E}^{(0)} &= \\frac{i}{k} \\nabla\\times \\mathcal{H}^{(0)}=\\frac{i}{k}\\nabla\\times \\mathcal{B}^{(0)}\\nonumber\\\\\n&=\\frac{i}{k}(\\frac{1}{r\\!_\\perp}\\!\\pp{\\mathcal{B}^{(\\!0\\!)}_z}{\\phi}\\!-\\! \\pp{\\mathcal{B}^{(\\!0\\!)}_\\phi}{z})\\mathbf{e}_{r\\!_{\\perp}} \\!\\!+\\! \\frac{i}{k}(\\!\\pp{\\mathcal{B}^{(\\!0\\!)}_{r\\!_\\perp}}{z} \\!-\\! \\pp{\\mathcal{B}^{(\\!0\\!)}_z}{r\\!_\\perp})\\mathbf{e}_\\phi \\!\\!+\\! \\frac{i}{r\\!_\\perp\\! k} (\\!\\pp{(\\! r\\!_\\perp \\mathcal{B}^{(\\!0\\!)}_\\phi)}{r\\!_\\perp} \\!\\!-\\!\\! \\pp{\\mathcal{B}^{(\\!0\\!)}_{r\\!_\\perp}}{\\phi}\\! )\\mathbf{e}_z\\\\\n&=\\mathcal{E}^{(0)}_{r\\!_\\perp}\\mathbf{e}_{r\\!_{\\perp}} +\\mathcal{E}^{(0)}_\\phi\\mathbf{e}_\\phi + \\mathcal{E}^{(0)}_z\\mathbf{e}_z,\n\\end{align}\nor, by Eq.~\\eqref{EGd}. Here, $ \\mathbf{d}_0 $ is the dipole moment in vacuum. We denote $d_{r\\!_\\perp},\\, d_\\phi$ and $d_z$ as the cylindrical components of the dipole moment at an arbitrary observation point ${\\rm {\\bf r}}=\\left( {r\\!_\\perp ,\\phi ,z}\\right) $. We use $d^0_{r\\!_\\perp}$, $d^0_\\phi$ and $d^0_z$ to indicate the dipole moment at the dipole position ${\\rm \n{\\bf {r}^{\\prime }}}=\\left( {{r\\!_\\perp }^{\\prime },{\\phi }^{\\prime },{z}^{\\prime }}\\right) $. As shown in Fig.(\\ref{fig:dipolemomentumtransmission}) on page~\\pageref{fig:dipolemomentumtransmission}, we defined the vector from the center of the nanofiber's core pointing to the atom position as the $x$ axis, and the rotating symmetric axis of the nanofiber as the $z$ axis. The relationships between the dipole moment components at $\\mathbf{r}$ and $\\mathbf{r}'$ can be given by\n\\begin{align}\nd_{r\\!_\\perp}\\! &= \\cos(\\phi\\!-\\!\\phi')d^0_{r\\!_\\perp}\\!\\!+\\!\\sin(\\phi\\!-\\!\\phi')d^0_\\phi=\\frac{1}{\\sqrt{2}}\\left(-e^{-i(\\phi\\!-\\!\\phi')}d_++e^{i(\\phi\\!-\\!\\phi')}d_- \\right),\\\\\nd_\\phi &=\\cos(\\phi\\!-\\!\\phi')d^0_\\phi\\!-\\!\\sin(\\phi\\!-\\!\\phi')d^0_{r\\!_\\perp}=\\frac{i}{\\sqrt{2}}\\left(e^{-i(\\phi\\!-\\!\\phi')}d_++e^{i(\\phi\\!-\\!\\phi')}d_- \\right),\\\\\nd_z &= d^0_z,\n\\end{align}\nwhere we have defined the position-independent reduced dipole vector components\n\\begin{align}\nd_\\pm \\equiv \\mp \\frac{1}{\\sqrt{2}}(d^0_{r\\!_\\perp}\\pm id^0_{\\phi}).\n\\end{align}\nThe terms associated with $d_\\pm$ in the dipole moment formula lowers or raises the mode index by $1$. Notice that we have used $\\phi\\!-\\!\\phi'$ as the projected angle between $\\mathbf{r}$ and $\\mathbf{r}'$ to make the relationship work in general. \nNote that we have dropped the subscript $ 0 $ for $ k_0 $, $ \\beta_0 $ and $ \\omega_0 $ defined in the main text for ease of notation in this appendix. \n\n\\begin{figure}\n\\centering\\makebox[\\textwidth]{\n\\begin{tikzpicture}[scale=2,cap=round]\n% Local definitions\n  \\def\\AngleAtr{60}\t% angle of r w.r.t x axis\n  \\def\\AngleOfd{30}\t% angle of d w.r.t. x axis\n  \\def\\LenOfd{1cm} % length of the dipole momentum vector\n  \\def\\drp{0.8660cm}\t% drp at r'\n  \\def\\dphi{0.5cm}\t% dphi at r'\n  \\def\\drpr{0.8660}\t% drp at r\n  \\def\\dphir{-0.5}\t% dphi at r\n  \\def\\Angledrp{\\AngleAtr}\t% angle of drp w.r.t. x axis\n  \\def\\Angledphi{150}\n  \n  \\coordinate (O) at (0,0);\t\t% origin\n  \\coordinate (R) at (2.0cm,0); % position of the dipole at r'\n  \\coordinate (r) at (\\AngleAtr:1.3cm);\t% position of observation point\n\n  % Colors\n  \\colorlet{anglecolor}{green!50!black}\n  \\colorlet{rvectorcolor}{red}\n  \\colorlet{assisvectorcolor}{orange!80!black}\n  \\colorlet{momentumcolor}{blue}\n\n  % Styles\n  \\tikzstyle{axes}=[]\n  \\tikzstyle{important line}=[very thick]\n  \\tikzstyle{information text}=[rounded corners,fill=red!10,inner sep=1ex]\n\n  % The graphic\n  % help grid\n  %\\draw[style=help lines,step=0.5cm] (-2.0,-2.0) grid (2.0,2.0);\n  \n  % circle for the nanofiber scope\n  \\draw (0,0) circle (1cm); \n  \\draw[<->] (0,0) --node[left=1mm] {$a$} (225:1cm) ;\n  \\draw (-30:1.8cm) node {\\text{nanofiber intersection}};\n  % coordinates\n  \\begin{scope}[style=axes]\n    \\draw[->] (-1.3cm,0) -- (3.0cm,0) node[right] {$\\mathbf{x}$};\n    \\draw[->] (0,-1.3cm) -- (0,2.0cm) node[above] {$\\mathbf{y}$};\n    \\draw (-1mm,1mm) node {$O$};\n  \\end{scope}\n  \n  % angle and position vector for r\n  \\filldraw[fill=green!20,draw=anglecolor] (0,0) -- (3mm,0pt) arc(0:\\AngleAtr:3mm);\n    \\draw (20:6mm) node[anglecolor] {$\\phi\\!-\\! \\phi'$};\n  \\draw[->,style=important line,rvectorcolor] (O) -- (r) node[left=1.5mm] {$\\mathbf{r}$};\n  % arc between two decomposition approaches\n  \\filldraw[fill=green!20,draw=anglecolor] (r.center)--($(r.center)+(2mm,0)$) arc (0:\\AngleAtr:2mm);\n  \\draw ($(r.center)+(10:4.4mm)$) node[anglecolor] {$\\phi\\!-\\! \\phi'$};\n  % dipole momentum vector at r\n  \\draw[->,style=important line,momentumcolor] (r) -- +(\\AngleOfd:\\LenOfd) node[right] {$\\mathbf{d}_0$};\n  \n  % d vector components at r\n  \\draw[->,dashed,thick,assisvectorcolor] (r) -- +(0:\\drp) node[right] {$d^0_{r\\!_\\perp}$};\n  \\draw[style=dotted,assisvectorcolor] ($(r.center)+(0:\\drp)$) -- ($(r.center)+(\\AngleOfd:\\LenOfd)$);\n  \\draw[->,dashed,thick,assisvectorcolor] (r) -- +(90:\\dphi) node[left] {$d^0_\\phi$};\n  \\draw[style=dotted,assisvectorcolor] ($(r.center)+(90:\\dphi)$) -- ($(r.center)+(\\AngleOfd:\\LenOfd)$);\n  \\draw[->,thick,dashed,anglecolor] (r) -- +(\\Angledrp:\\drpr) node[yshift=8mm,xshift=1.8cm,anchor=north] {$d_{r\\!_\\perp}\\!=\\frac{1}{\\sqrt{2}}\\left(-e^{-i(\\phi\\!-\\!\\phi')}d_++e^{i(\\phi\\!-\\!\\phi')}d_- \\right)$};\n  \\draw[style=dotted,anglecolor] ($(r.center)+(\\Angledrp:\\drpr)$) -- ($(r.center)+(\\AngleOfd:\\LenOfd)$);\n  \\draw[->,thick,dashed,anglecolor] (r) -- +(\\Angledphi:\\dphir) node[right] {$d_\\phi=\\frac{i}{\\sqrt{2}}\\left(e^{-i(\\phi\\!-\\!\\phi')}d_++e^{i(\\phi\\!-\\!\\phi')}d_- \\right)$};\n  \\draw[style=dotted,anglecolor] ($(r.center)+(\\Angledphi:\\dphir)$) -- ($(r.center)+(\\AngleOfd:\\LenOfd)$);\n  \\draw [fill=blue] (r) circle (0.2mm) node {}; % starting point at r\n   \n  % dipole momentum vector for r'\n  \\draw[->,style=important line,rvectorcolor] (O) -- (R) node[below=1mm] {$\\mathbf{r}'$};\n  \\draw[->,style=important line,momentumcolor] (R) -- +(\\AngleOfd:\\LenOfd) node[right] {$\\mathbf{d}_0$};\n  \\draw[->,very thick,dashed,assisvectorcolor] (R) -- +(0:\\drp) node[below] {$d^0_{r\\!_\\perp}$};\n  \\draw[style=dotted,assisvectorcolor] ($(R.center)+(0:\\drp)$) -- ($(R.center)+(\\AngleOfd:\\LenOfd)$);\n  \\draw[->,thick,dashed,assisvectorcolor] (R) -- +(90:\\dphi) node[left] {$d^0_\\phi$};\n  \\draw[style=dotted,assisvectorcolor] ($(R.center)+(90:\\dphi)$) -- ($(R.center)+(\\AngleOfd:\\LenOfd)$);\n  \\draw [fill=blue] (R) circle (0.2mm) node {}; % starting point at r'\n\\end{tikzpicture}}\n\\caption{Dipole moment decompositions in the $xy$ plane.}\n\\label{fig:dipolemomentumtransmission}\n\\end{figure}\n\nUsing the expansion of the free-space scalar Green's function [Eq.~\\eqref{scalarG}] for the space $ \\left(r\\!_\\perp <r_\\perp ^{\\prime}\\right) $ that \n\\begin{align}\n\\frac{G_0(\\br,\\br')}{k^2} &={\\frac{{e^{ik{\\left| {{\\rm {\\bf r}}-{\\rm {\\bf {r}^{\\prime }}}}\\right| }}}}{{{%\n\\left| {{\\rm {\\bf r}}-{\\rm {\\bf {r}^{\\prime }}}}\\right| }}}}\\nonumber\\\\\n&={\\frac{{i}}{{2}}%\n}{\\sum\\limits_{m=-\\infty }^{\\infty } {{\\oint\\limits_{C_{1}}{\\mathrm{d}\\beta \\;e^{im\\left( {\\phi -{\\phi }%\n^{\\prime }}\\right) +i\\beta \\left( {z-{z}^{\\prime }}\\right) }J_{m}\\left( {pr\\!_\\perp\n}\\right) H_{m}^{\\left( {1}\\right) }\\left( pr_\\perp ^{\\prime\n}\\right) }}}},\n\\end{align}\nand for $ \\left(r\\!_\\perp >r_\\perp ^{\\prime}\\right) $\n\\begin{align}\n\\frac{G_0(\\br,\\br')}{k^2} &={\\frac{{e^{ik{\\left| {{\\rm {\\bf r}}-{\\rm {\\bf {r}^{\\prime }}}}\\right| }}}}{{{%\n\\left| {{\\rm {\\bf r}}-{\\rm {\\bf {r}^{\\prime }}}}\\right| }}}}\\nonumber\\\\\n&={\\frac{{i}}{{2}}%\n}{\\sum\\limits_{m=-\\infty }^{\\infty } {{\\oint\\limits_{C_{1}}{\\mathrm{d}\\beta \\;e^{im\\left( {\\phi -{\\phi }%\n^{\\prime }}\\right) +i\\beta \\left( {z-{z}^{\\prime }}\\right) }J_{m}\\left( {pr\\!_\\perp^{\\prime} }\\right) H_{m}^{\\left( {1}\\right) }\\left( pr_\\perp \\right) }}}},\n\\end{align}\none can obtain the free space dipole radiation field components in Eq.~\\eqref{ET0Rexpand} and~\\eqref{BT0Rexpand}. The contour $ C_1 $ and field components can be found in Ref.~\\cite{Klimov2004}~\\footnote{Similarly, the decomposition of a plane wave function can be found in Appendix~\\ref{Ch:PlanewaveDecomposition}}.\n\nThe free radiation field components associated with the $ e^{im\\phi+i\\beta z} $ term (the $m$-th mode components) for the $r\\!_\\perp<r'\\!_\\perp$ region can be given by\n\\begin{align}\n\\mathcal{B}_{z,m\\beta}^{(0)} &= \\frac{ikp}{2\\sqrt{2}}J_m(pr\\!_\\perp)\\left[ d_{+} H_{m+1}^{(1)}(pr'\\!\\!_\\perp) \\!-\\! d_- H_{m-1}^{(1)}(pr'\\!_\\perp) \\right],\\\\\n\\mathcal{B}_{\\phi,m\\beta}^{(0)} &= \\frac{ik}{2}\\left[ \\frac{\\beta d_{-}}{\\sqrt{2}} J_{m-1}\\left( pr\\!_\\perp \\right)H_{m-1}^{(1)}\\left( {pr\\!_\\perp^{\\prime} }\\right) -\\frac{\\beta d_+}{\\sqrt{2}} J_{m+1}\\left( pr\\!_\\perp \\right)H_{m+1}^{(1)}\\left( {pr\\!_\\perp^{\\prime} }\\right)\\right. \\nonumber\\\\ \n&\\qquad\\quad \\left. + \\frac{ipd^0_z}{2}\\left(J_{m-1}(pr\\!_\\perp)-J_{m+1}(pr\\!_\\perp) \\right)H_m^{(1)}(pr\\!_\\perp^{\\prime}) \\right],\\\\\n\\mathcal{B}_{r\\!_\\perp, m\\beta}^{(0)} &= \\frac{k}{2}\\left[\\frac{i m d^0_z}{r\\!_\\perp} J_m\\left( pr\\!_\\perp \\right) H_m^{(1)}\\left( {pr\\!_\\perp^{\\prime} }\\right) \\right. \\nonumber\\\\\n&\\qquad \\left. +\\frac{\\beta d_+}{\\sqrt{2}} J_{m\\!+\\!1}(pr\\!_\\perp) H_{m\\!+\\! 1}^{(1)}(pr\\!_\\perp^{\\prime}) \\!+\\! \\frac{\\beta d_-}{\\sqrt{2}} J_{m\\!-\\! 1}(pr\\!_\\perp)H_{m\\!-\\!1}^{(1)}(pr\\!_\\perp^{\\prime})   \\right],\\\\\n\\mathcal{E}_{z,m\\beta}^{(0)} \n&= \\frac{p}{2}J_{m}\\left( pr\\!_\\perp \\right)\\left[  id^0_z p H_m^{(1)}\\left( {pr\\!_\\perp^{\\prime} }\\right) \\phantom{\\frac{d^0_z}{\\sqrt{2}}} \\right. \\nonumber\\\\\n&\\qquad\\qquad\\qquad \\left. + \\frac{\\beta d_{+}}{\\sqrt{2}} H_{m+1}^{(1)}\\left( {pr\\!_\\perp^{\\prime} }\\right) +\\frac{\\beta d_-}{\\sqrt{2}} H_{m-1}^{(1)}\\left( {pr\\!_\\perp^{\\prime} }\\right) \\right], \\\\\n\\mathcal{E}_{\\phi,m\\beta}^{(0)} \n&= -\\frac{im\\beta d^0_z}{2r\\!_\\perp} J_{m}\\left( pr\\!_\\perp \\right) H_m^{(1)}\\left( {pr\\!_\\perp^{\\prime} }\\right) \\nonumber\\\\\n&\\quad+\\frac{d_+}{2\\sqrt{2}} \\left[ \\frac{mp}{r\\!_\\perp}J_{m}\\left( pr\\!_\\perp \\right)-k^2 J_{m+1}\\left( pr\\!_\\perp \\right)\\right] H_{m+1}^{(1)}\\left( {pr\\!_\\perp^{\\prime} }\\right) \\nonumber\\\\\n&\\quad+ \\frac{d_-}{2\\sqrt{2}}\\left[\\frac{mp}{r\\!_\\perp}J_m\\!\\left( pr_\\perp \\right)-k^2J_{m-1}\\!\\left( pr_\\perp \\right) \\right] H_{m-1}^{(1)}\\!\\left( {pr\\!_\\perp^{\\prime} }\\right),\\\\\n\\mathcal{E}_{r\\!_\\perp,m\\beta}^{(0)} \n&= \\frac{\\beta pd^0_z}{4}\\left[ J_{m+1}\\!\\left( pr\\!_\\perp \\right)-J_{m-1}\\!\\left( pr_\\perp \\right)\\right] H_m^{(1)}\\left( {pr\\!_\\perp^{\\prime} }\\right)\\nonumber\\\\ \n&\\quad -\\frac{d_+}{2\\sqrt{2}}\\left[ i\\beta^2J_{m+1}\\!\\left( pr_\\perp \\right) +\\frac{imp}{r\\!_\\perp}J_m\\!\\left( pr_\\perp \\right)\\right] H_{m+1}^{(1)}\\!\\left( {pr\\!_\\perp^{\\prime} }\\right)\\nonumber\\\\\n&\\quad + \\frac{d_-}{2\\sqrt{2}}\\left[ i\\beta^2J_{m-1}\\!\\left( pr_\\perp \\right) +\\frac{imp}{r\\!_\\perp}J_m\\!\\left( pr_\\perp \\right)\\right] H_{m-1}^{(1)}\\!\\left( {pr\\!_\\perp^{\\prime} }\\right).\n\\end{align}\n%More details on deriving the E-field components can be found in \\emph{Derivation of free-space E-field components.pdf}. \nMore details on solving the free dipole radiation problem are in Appendix~\\ref{chap:freespacegreenfunction}.\nSome properties of Bessel functions used in deriving these expressions are in Appendix~\\ref{chap:Besselfunctions}.\n\nBy exchanging $J_m$ and $H_m^{(1)}$ functions, one can also obtain the field components for the case of $ r\\!_\\perp>r'\\!_\\perp $ (which is not shown in reference~\\cite{Klimov2004}). The magnetic and electric fields components for $ \\br\\!_\\perp>\\br'\\!_\\perp $ are \n\\begin{align}\n\\mathcal{B}_{z,m\\beta}^{(0)} &= \\frac{ikp}{2\\sqrt{2}}H^{(1)}_m(pr\\!_\\perp)\\left[ d_{+} J_{m+1}(pr'\\!\\!_\\perp) \\!-\\! d_- J_{m-1}(pr'\\!_\\perp) \\right],\\\\\n\\mathcal{B}_{\\phi,m\\beta}^{(0)} &= \\frac{ik}{2}\\left[ \\frac{\\beta d_{-}}{\\sqrt{2}} H^{(1)}_{m-1}\\left( pr\\!_\\perp \\right)J_{m-1}\\left( {pr\\!_\\perp^{\\prime} }\\right) -\\frac{\\beta d_+}{\\sqrt{2}} H^{(1)}_{m+1}\\left( pr\\!_\\perp \\right)J_{m+1}\\left( {pr\\!_\\perp^{\\prime} }\\right)\\right. \\nonumber\\\\ \n&\\qquad\\quad \\left. + \\frac{ipd^0_z}{2}\\left(H^{(1)}_{m-1}(pr\\!_\\perp)-H^{(1)}_{m+1}(pr\\!_\\perp) \\right)J_m(pr\\!_\\perp^{\\prime}) \\right],\\\\\n\\mathcal{B}_{r\\!_\\perp, m\\beta}^{(0)} &= \\frac{k}{2}\\left[\\frac{i m d^0_z}{r\\!_\\perp} H^{(1)}_m\\left( pr\\!_\\perp \\right) J_m\\left( {pr\\!_\\perp^{\\prime} }\\right) \\right. \\nonumber\\\\\n&\\qquad \\left. +\\frac{\\beta d_+}{\\sqrt{2}} H^{(1)}_{m\\!+\\!1}(pr\\!_\\perp) J_{m\\!+\\! 1}(pr\\!_\\perp^{\\prime}) \\!+\\! \\frac{\\beta d_-}{\\sqrt{2}} H^{(1)}_{m\\!-\\! 1}(pr\\!_\\perp) J_{m\\!-\\!1}(pr\\!_\\perp^{\\prime})   \\right],\\\\\n\\mathcal{E}_{z,m\\beta}^{(0)} \n&= \\frac{p}{2}H^{(1)}_{m}\\left( pr\\!_\\perp \\right)\\left[  id^0_z p J_m\\left( {pr\\!_\\perp^{\\prime} }\\right) \\phantom{\\frac{d^0_z}{\\sqrt{2}}} \\right. \\nonumber\\\\\n&\\qquad\\qquad\\qquad \\left. + \\frac{\\beta d_{+}}{\\sqrt{2}} J_{m+1}\\left( {pr\\!_\\perp^{\\prime} }\\right) +\\frac{\\beta d_-}{\\sqrt{2}} J_{m-1}\\left( {pr\\!_\\perp^{\\prime} }\\right) \\right], \\\\\n\\mathcal{E}_{\\phi,m\\beta}^{(0)} \n&= -\\frac{im\\beta d^0_z}{2r\\!_\\perp} H^{(1)}_{m}\\left( pr\\!_\\perp \\right) J_m\\left( {pr\\!_\\perp^{\\prime} }\\right) \\nonumber\\\\\n&\\quad+\\frac{d_+}{2\\sqrt{2}} \\left[ \\frac{mp}{r\\!_\\perp}H^{(1)}_{m}\\left( pr\\!_\\perp \\right)-k^2 H^{(1)}_{m+1}\\left( pr\\!_\\perp \\right)\\right] J_{m+1}\\left( {pr\\!_\\perp^{\\prime} }\\right) \\nonumber\\\\\n&\\quad+ \\frac{d_-}{2\\sqrt{2}}\\left[\\frac{mp}{r\\!_\\perp}H^{(1)}_m\\!\\left( pr_\\perp \\right)-k^2 H^{(1)}_{m-1}\\!\\left( pr_\\perp \\right) \\right] J_{m-1}\\!\\left( {pr\\!_\\perp^{\\prime} }\\right),\\\\\n\\mathcal{E}_{r\\!_\\perp,m\\beta}^{(0)} \n&= \\frac{\\beta pd^0_z}{4}\\left[ H^{(1)}_{m+1}\\!\\left( pr\\!_\\perp \\right)-H^{(1)}_{m-1}\\!\\left( pr_\\perp \\right)\\right] J_m\\left( {pr\\!_\\perp^{\\prime} }\\right)\\nonumber\\\\ \n&\\quad -\\frac{d_+}{2\\sqrt{2}}\\left[ i\\beta^2H^{(1)}_{m+1}\\!\\left( pr_\\perp \\right) +\\frac{imp}{r\\!_\\perp}H^{(1)}_m\\!\\left( pr_\\perp \\right)\\right] J_{m+1}\\!\\left( {pr\\!_\\perp^{\\prime} }\\right)\\nonumber\\\\\n&\\quad + \\frac{d_-}{2\\sqrt{2}}\\left[ i\\beta^2H^{(1)}_{m-1}\\!\\left( pr_\\perp \\right) +\\frac{imp}{r\\!_\\perp}H^{(1)}_m\\!\\left( pr_\\perp \\right)\\right] J_{m-1}\\!\\left( {pr\\!_\\perp^{\\prime} }\\right).\n\\end{align}\n\n\nThe expressions above are formally different from Ref.~\\cite{Klimov2004}, but are consistent with Ref.~\\cite{Nha1997}. \nBy using some identities of Bessel functions, we are able to reproduce the expression given in Ref.~\\cite{Klimov2004}. \nWe have also verified numerically the equivalence of our result to the two references cited above. \n\nUsing the boundary conditions at $ r\\!_\\perp=a $ and Eq.~(\\ref{Etotalfiber}) yield \n\\begin{align}\n%\\varepsilon_f \\mathcal{E}_{r\\!_\\perp}(r\\!_\\perp =a^> ) = \\mathcal{E}_{r\\!_\\perp}(r\\!_\\perp =a^< ),\\\\\n\\mathcal{E}_{z}(r\\!_\\perp =a^> ) = \\mathcal{E}_{z}(r\\!_\\perp =a^< ),\\\\\n%\\mathcal{B}_{r\\!_\\perp}(r\\!_\\perp =a^> ) = \\mathcal{B}_{r\\!_\\perp}(r\\!_\\perp =a^< ),\\\\\n\\mathcal{B}_{z}(r\\!_\\perp =a^> ) = \\mathcal{B}_{z}(r\\!_\\perp =a^< ),\\\\\n\\mathcal{E}_{\\phi}(r\\!_\\perp =a^> ) = \\mathcal{E}_{\\phi}(r\\!_\\perp =a^< ),\\\\\n\\mathcal{B}_{\\phi}(r\\!_\\perp =a^> ) = \\mathcal{B}_{\\phi}(r\\!_\\perp =a^< ),\n\\end{align}\nwhere $ a^< $ and $ a^> $ denote the boundaries at the sides less and larger than $ a $, respectively. Together with these and the connections between field components (Eq.(\\ref{EHzgauss})), we can obtain all unknown coefficients. Specifically, the boundary conditions yield\n\\begin{align}\na_{m\\beta}H_m^{(1)}(pa)+\\mathcal{E}_{z,m\\beta}^{(0)}(r\\!_\\perp =a ) &= c_{m\\beta}J_m(ha),\\\\\nb_{m\\beta}H_m^{(1)}(pa)+\\mathcal{B}_{z,m\\beta}^{(0)}(r\\!_\\perp =a ) &= d_{m\\beta}J_m(ha),\\\\\n\\frac{m\\! \\beta}{p^2\\! a}a_{m\\!\\beta} H\\!_m^{(1)}\\!(pa)\\! &+\\! \\frac{i\\!k}{p^2}\\! b\\!_{m\\!\\beta}\\! \\left. \\pp{H\\!_m^{( 1 )}(p r\\!_\\perp)}{r\\!_\\perp}\\! \\right|_{r\\!_\\perp\\! =\\! a}\\!\\! -\\! \\mathcal{E}\\! _{\\phi,m\\! \\beta}^{(0)}(r\\!_\\perp\\! =\\! a ) \\nonumber \\\\\n&= \\frac{m\\! \\beta}{h^2\\! a}\\! c_{m\\! \\beta} J\\!_m(ha)\\! +\\! \\frac{i\\!k}{h^2}\\!d\\!_{m\\!\\beta} \\! \\left. \\pp{J\\!_m(h r\\!_\\perp \\!)}{r\\!_\\perp}\\! \\right|_{r\\!_\\perp\\! =\\! a},\\\\\n\\frac{m\\! \\beta}{p^2\\! a}b_{m\\!\\beta} H\\!_m^{(1)}\\!(pa)\\! &+\\! \\frac{i\\!k}{p^2}\\! a\\!_{m\\!\\beta}\\! \\left. \\pp{H\\!_m^{( 1 )}(p r\\!_\\perp)}{r\\!_\\perp}\\! \\right|_{r\\!_\\perp\\! =\\! a}\\!\\! +\\! \\mathcal{B}\\! _{\\phi,m\\! \\beta}^{(0)}(r\\!_\\perp\\! =\\! a ) \\nonumber \\\\\n&= \\frac{m\\! \\beta}{h^2\\! a}\\! d_{m\\! \\beta} J\\!_m(ha)\\! +\\! \\frac{i\\!k\\varepsilon}{h^2}\\!c\\!_{m\\!\\beta} \\! \\left. \\pp{J\\!_m(h r\\!_\\perp \\!)}{r\\!_\\perp}\\! \\right|_{r\\!_\\perp\\! =\\! a}.\n\\end{align}\nOne can substitute the first two equations into the last two equations, and obtain a set equations for $a_{m\\beta}$ and $b_{m\\beta}$ as\n\\begin{align}\n&\\quad \\left[\\frac{m\\! \\beta}{p^2\\! a} H\\!_m^{(1)}\\!(pa) \\!-\\! \\frac{m\\! \\beta}{h^2\\! a}\\!H_m^{(1)}(pa) \\right] a_{m\\!\\beta}\\nonumber\\\\\n&\\quad +\\left[\\! \\frac{i\\!k}{p^2}\\! \\left. \\pp{H\\!_m^{( 1 )}(p r\\!_\\perp)}{r\\!_\\perp}\\! \\right|_{r\\!_\\perp\\! =\\! a}\\!\\!-\\! \\frac{i\\!k}{h^2J_m(ha)}\\! \\left. \\pp{J\\!_m(h r\\!_\\perp \\!)}{r\\!_\\perp}\\! \\right|_{r\\!_\\perp\\! =\\! a} H_m^{(1)}(pa) \\right]b\\!_{m\\!\\beta} \\nonumber\\\\\n&= \\frac{m\\! \\beta}{h^2\\! a}\\! \\mathcal{E}_{z,m\\beta}^{(0)}(r\\!_\\perp =a ) \\!+\\! \\! \\frac{i\\!k}{h^2J_m(ha)}\\! \\left. \\pp{J\\!_m(h r\\!_\\perp \\!)}{r\\!_\\perp}\\! \\right|_{r\\!_\\perp\\! =\\! a}\\mathcal{B}_{z,m\\beta}^{(0)}(r\\!_\\perp =a )  \\!+\\!\\mathcal{E}\\! _{\\phi,m\\! \\beta}^{(0)}(r\\!_\\perp\\! =\\! a )\\\\\n&\\quad \\left[\\frac{m\\! \\beta}{p^2\\! a} H\\!_m^{(1)}\\!(pa) \\!-\\! \\frac{m\\! \\beta}{h^2\\! a}\\!H_m^{(1)}(pa) \\right] b_{m\\!\\beta}\\nonumber\\\\\n&\\quad +\\left[\\! \\frac{i\\!k}{p^2}\\! \\left. \\pp{H\\!_m^{( 1 )}(p r\\!_\\perp)}{r\\!_\\perp}\\! \\right|_{r\\!_\\perp\\! =\\! a}\\!\\!-\\! \\frac{i\\!k\\varepsilon}{h^2J_m(ha)}\\! \\left. \\pp{J\\!_m(h r\\!_\\perp \\!)}{r\\!_\\perp}\\! \\right|_{r\\!_\\perp\\! =\\! a} H_m^{(1)}(pa) \\right]a\\!_{m\\!\\beta} \\nonumber\\\\\n&= \\frac{m\\! \\beta}{h^2\\! a}\\! \\mathcal{B}_{z,m\\beta}^{(0)}(r\\!_\\perp =a ) \\!+\\! \\! \\frac{i\\!k\\varepsilon}{h^2J_m(ha)}\\! \\left. \\pp{J\\!_m(h r\\!_\\perp \\!)}{r\\!_\\perp}\\! \\right|_{r\\!_\\perp\\! =\\! a}\\mathcal{E}_{z,m\\beta}^{(0)}(r\\!_\\perp =a )  \\!-\\!\\mathcal{B}\\! _{\\phi,m\\! \\beta}^{(0)}(r\\!_\\perp\\! =\\! a ).\n\\end{align}\n\nThe solutions of $a_{m\\beta}$ and $b_{m\\beta}$ are given by Equs.(47-50) in Ref.~\\cite{Klimov2004}. To summarize, we also have\n\\begin{align}\na_{m\\beta} &= \\frac{na}{P^2+QR},\\\\\nb_{m\\beta} &= \\frac{nb}{P^2+QR},\\\\\nc_{m\\beta} &= \\frac{\\mathcal{E}_{z,m\\beta}^{(0)}(r\\!_\\perp\\!=\\!a)+ H_m^{(1)}(pa)a_{m\\beta}}{J_m(ha)},\\\\\nd_{m\\beta} &= \\frac{\\mathcal{H}_{z,m\\beta}^{(0)}(r\\!_\\perp\\!=\\!a)+ H_m^{(1)}(pa)b_{m\\beta}}{J_m(ha)},\n\\end{align}\nwhere\n\\begin{align}\nna &= h^2p^2aJ_m(ha)PE_{\\phi,m\\beta}^{(0)}(r\\!_\\perp\\!=\\!a) \\nonumber\\\\\n&\\quad + p^2\\left[J_m(ha)\\beta mP+kan_1^2h \\dd{}{(ha)}J_m(ha)Q \\right] E_{z,m\\beta}^{(0)} \\nonumber\\\\\n&\\quad + ih^2p^2 aJ_m(ha)QB_{\\phi,m\\beta}^{(0)}(r\\!_\\perp\\!\\!=\\!a) \\!-\\! im\\beta hpJ_m(ha)SB_{z,m\\beta}^{(0)}(r\\!_\\perp\\!\\!=\\!a),\\\\\nnb &= h^2p^2aJ_m(ha)PB_{\\phi,m\\beta}^{(0)}(r\\!_\\perp\\!=\\!a) \\nonumber\\\\\n&\\quad + p^2\\left[J_m(ha)\\beta mP-kah \\dd{}{(ha)}J_m(ha)R \\right] B_{z,m\\beta}^{(0)} \\nonumber\\\\\n&\\quad + ih^2p^2 aJ_m(ha)RE_{\\phi,m\\beta}^{(0)}(r\\!_\\perp\\!\\!=\\!a) \\!+\\! im\\beta hpJ_m(ha)TE_{z,m\\beta}^{(0)}(r\\!_\\perp\\!\\!=\\!a),\n\\end{align} \nand\n\\begin{align}\nP &=m\\beta k^2J_m(ha)H_m^{(1)}(pa)(n_1^2-1),\\\\\nQ &=-hpak\\left[ hJ_m(ha)\\dd{}{(pa)}H_m^{(1)}(pa)-pH_m^{(1)}(pa)\\dd{}{(ha)}J_m(ha) \\right],\\\\\nR &=hpak\\left[ hJ_m(ha)\\dd{}{(pa)}H_m^{(1)}(pa)-pn_1^2H_m^{(1)}(pa)\\dd{}{(ha)}J_m(ha) \\right],\\\\\nS &=hpak\\left[ pJ_m(ha)\\dd{}{(pa)}H_m^{(1)}(pa)-hH_m^{(1)}(pa)\\dd{}{(ha)}J_m(ha) \\right],\\\\\nT &=hpak\\left[ pJ_m(ha)\\dd{}{(pa)}H_m^{(1)}(pa)-hn_1^2H_m^{(1)}(pa)\\dd{}{(ha)}J_m(ha) \\right].\n\\end{align}\n\n\\begin{figure}[!tbp]\n\\begin{minipage}{.91\\linewidth}\n\\centering\n\\subfloat[]{\\label{contourplot_upper}\\includegraphics[scale=0.75]{../media/Figs/contourplot_upper}}\n\\end{minipage}\n\\par\\medskip\n\\begin{minipage}{.91\\linewidth}\n\\centering\n\\subfloat[]{\\label{contourplot_lower}\\includegraphics[scale=0.75]{../media/Figs/contourplot_lower}}\n\\end{minipage}\n\\caption[Contour integrations to decompose the guided and unguided modes of a dipole radiation problem in presence of a single mode waveguide.]{Integration paths. For the case that $ z>0 $, we can use the zero-valued contour integral path drawn in subfig.~\\ref{contourplot_upper} to calculate the integration along path $ C_1 $. The simplified integration path by ignoring waveguide losses is given on the right-hand-side. It only contains the forward propagating mode contributions with unguided and guided mode components as divided through the real axis integral and the loop-hole integral. For the $ z<0 $ case, the contour integral analysis is given in subfig.~\\ref{contourplot_lower}, which only includes the backward propagating mode contributions.}\n\\label{fig:integralpath}\n\\end{figure}\n\nNow, we only consider the $ m=\\pm 1 $ modes, and hence Eqs.~(\\ref{ET0Rexpand},~\\ref{BT0Rexpand}) and the corresponding $ \\phi $ and $ r\\!_\\perp $ components can be explicitly expressed as contour integrals\n\\begin{subequations}\\label{ET0RC1}\n\\begin{align}\n\\mathcal{E}^{(T)}_z &= \\sum_{m=\\pm 1} \\int_{C_1} \\mathrm{d}\\beta e^{im(\\phi-\\phi') + i\\beta (z-z')} c_{m\\beta} J_m (hr\\!_\\perp),\\\\\n% + B_{m\\beta} Y_m(hr\\!_\\perp)\\right],\\\\\n\\mathcal{E}^{(0)}_{z} &= \\sum_{m=\\pm 1} \\int_{C_1} \\mathrm{d}\\beta e^{im(\\phi-\\phi') + i\\beta (z-z')} \\mathcal{E}^{(0)}_{z,m\\beta}(r\\!_\\perp)\\\\\n\\mathcal{E}^{(S)}_z &= \\sum_{m=\\pm 1} \\int_{C_1} \\mathrm{d}\\beta e^{im(\\phi-\\phi') + i\\beta (z-z')} a_{m\\beta} H_m^{(1)} (pr\\!_\\perp),\n\\end{align}\n\\end{subequations}\n\\begin{subequations}\\label{BT0RC1}\n\\begin{align}\n\\mathcal{B}^{(T)}_z &= \\sum_{m=\\pm 1} \\int_{C_1} \\mathrm{d}\\beta e^{im(\\phi-\\phi') + i\\beta (z-z')} d_{m\\beta} J_m (hr\\!_\\perp),\\\\\n% + E_{m\\beta} Y_m(hr\\!_\\perp)\\right],\\\\\n\\mathcal{B}^{(0)}_{z} &= \\sum_{m=\\pm 1} \\int_{C_1} \\mathrm{d}\\beta e^{im(\\phi-\\phi') + i\\beta (z-z')} \\mathcal{B}^{(0)}_{z,m\\beta}(r\\!_\\perp)\\\\\n\\mathcal{B}^{(S)}_z &= \\sum_{m=\\pm 1} \\int_{C_1} \\mathrm{d}\\beta e^{im(\\phi-\\phi') + i\\beta (z-z')} b_{m\\beta} H_m^{(1)} (pr\\!_\\perp).\n\\end{align}\n\\end{subequations}\nTo distinguish the guided and unguided modes contributions, we can use the integral path along $ C_1 $ (see Fig.~\\ref{fig:integralpath}) and find the equivalent integral path avoiding the branch cuts and isolated poles, which will be discussed next. \n\nFor the free-dipole radiation components, the $ C_1 $ integral path is almost the real integral path from $ -\\infty $ to the $ +\\infty $ except for the branch point at $ \\pm k $. The sign of $ \\beta $ indicates the propagation direction of the field. The free-dipole components only yield the unguided mode contributions to the total Green's dyadic. This is because the dipole radiation only occurs outside of the fiber and always in the radiation potential zone according to the equivalent scattering potential model. \n\nFor the scattering and transmission components of the field, there are poles in the $ a_{m\\beta} $, $ b_{m\\beta} $, $ c_{m\\beta} $ and $ d_{m\\beta} $ coefficients. There are also branch cuts hidden in the Bessel and Hankel function components of their expressions. Depending on the sign of $ (z-z') $, the integral paths and their simplification are shown in Fig.(\\ref{fig:integralpath}). The guided modes are associated with poles, and hence can be represented as residues if asymptotic approximation can be made. Therefore, the guided mode contribution part of the scattering and transmission components can be given by\n\\begin{subequations}\\label{ET0RRes}\n\\begin{align}\n\\mathcal{E}^{(T)}_z &= \\sum_{m=\\pm 1} \\oint_{\\beta_{1,m}}  e^{im(\\phi\\!-\\!\\phi') + i\\beta (z\\!-\\!z')} c_{m\\beta} J_m (hr\\!_\\perp),\\\\\n%\\mathcal{E}^{(0)}_{z} &= 2\\pi i \\sum_{m=\\pm 1} \\sum_{\\beta_{1,m=\\pm 1}}\\mathrm{Res}\\left[  e^{im(\\phi-\\phi') + i\\beta (z-z')} \\mathcal{E}^{(0)}_{z,m\\beta}(r\\!_\\perp)\\right]_{\\beta=\\beta_{1,m}},\\\\\n\\mathcal{E}^{(S)}_z &= \\sum_{m=\\pm 1} \\oint_{\\beta_{1,m}} e^{im(\\phi\\!-\\!\\phi') + i\\beta (z\\!-\\!z')} a_{m\\beta} H_m^{(1)} (pr\\!_\\perp),\n\\end{align}\n\\end{subequations}\n\\begin{subequations}\\label{BT0RRes}\n\\begin{align}\n\\mathcal{B}^{(T)}_z &= \\sum_{m=\\pm 1} \\oint_{\\beta_{1,m}} e^{im(\\phi\\!-\\!\\phi') + i\\beta (z\\!-\\!z')} d_{m\\beta} J_m (hr\\!_\\perp),\\\\\n%\\mathcal{B}^{(0)}_{z} &= 2\\pi i \\sum_{m=\\pm 1} \\sum_{\\beta_{1,m=\\pm 1}}\\mathrm{Res}\\left[  e^{im(\\phi-\\phi') + i\\beta (z-z')} \\mathcal{B}^{(0)}_{z,m\\beta}(r\\!_\\perp)\\right]_{\\beta=\\beta_{1,m}}, \\\\\n\\mathcal{B}^{(S)}_z &= \\sum_{m=\\pm 1} \\oint_{\\beta_{1,m}} e^{im(\\phi\\!-\\!\\phi') + i\\beta (z\\!-\\!z')} b_{m\\beta} H_m^{(1)} (pr\\!_\\perp).\n\\end{align}\n\\end{subequations}\n%\\begin{subequations}\\label{ET0RRes}\n%\\begin{align}\n%\\mathcal{E}^{(T)}_z &= 2\\pi i \\sum_{m=\\pm 1} \\sum_{\\beta_{1,m=\\pm 1}}\\mathrm{Res}\\left[  e^{im(\\phi\\!-\\!\\phi') + i\\beta (z\\!-\\!z')} c_{m\\beta} J_m (hr\\!_\\perp)\\right]_{\\beta=\\beta_{1,m}},\\\\\n%% + B_{m\\beta} Y_m(hr\\!_\\perp)\\right],\\\\\n%\\mathcal{E}^{(0)}_{z} &= 2\\pi i \\sum_{m=\\pm 1} \\sum_{\\beta_{1,m=\\pm 1}}\\mathrm{Res}\\left[  e^{im(\\phi-\\phi') + i\\beta (z-z')} \\mathcal{E}^{(0)}_{z,m\\beta}(r\\!_\\perp)\\right]_{\\beta=\\beta_{1,m}},\\\\\n%\\mathcal{E}^{(S)}_z &= 2\\pi i \\sum_{m=\\pm 1} \\sum_{\\beta_{1,m=\\pm 1}}\\mathrm{Res}\\left[ e^{im(\\phi\\!-\\!\\phi') + i\\beta (z\\!-\\!z')} a_{m\\beta} H_m^{(1)} (pr\\!_\\perp)\\right]_{\\beta=\\beta_{1,m}},\n%\\end{align}\n%\\end{subequations}\n%\\begin{subequations}\\label{BT0RRes}\n%\\begin{align}\n%\\mathcal{B}^{(T)}_z &= 2\\pi i \\sum_{m=\\pm 1} \\sum_{\\beta_{1,m=\\pm 1}}\\mathrm{Res}\\left[ e^{im(\\phi\\!-\\!\\phi') + i\\beta (z\\!-\\!z')} d_{m\\beta} J_m (hr\\!_\\perp)\\right]_{\\beta=\\beta_{1,m}},\\\\\n%% + E_{m\\beta} Y_m(hr\\!_\\perp)\\right],\\\\\n%\\mathcal{B}^{(0)}_{z} &= 2\\pi i \\sum_{m=\\pm 1} \\sum_{\\beta_{1,m=\\pm 1}}\\mathrm{Res}\\left[  e^{im(\\phi-\\phi') + i\\beta (z-z')} \\mathcal{B}^{(0)}_{z,m\\beta}(r\\!_\\perp)\\right]_{\\beta=\\beta_{1,m}}, \\\\\n%\\mathcal{B}^{(S)}_z &= 2\\pi i \\sum_{m=\\pm 1} \\sum_{\\beta_{1,m=\\pm 1}}\\mathrm{Res}\\left[ e^{im(\\phi\\!-\\!\\phi') + i\\beta (z\\!-\\!z')} b_{m\\beta} H_m^{(1)} (pr\\!_\\perp)\\right]_{\\beta=\\beta_{1,m}}.\n%\\end{align}\n%\\end{subequations}\n\nThe unguided mode contributions of the scattering and transmission components are associated with the branch cuts $ C_2 $~\\cite{Klimov2004} in Fig.(\\ref{fig:integralpath}).\n\\begin{subequations}\\label{ET0RC2}\n\\begin{align}\n\\mathcal{E}^{(T)}_z &= \\sum_{m=\\pm 1} \\int_{C_2} \\mathrm{d}\\beta e^{im(\\phi-\\phi') + i\\beta (z-z')} c_{m\\beta} J_m (hr\\!_\\perp)\\\\\n&\\approx \\sum_{m=\\pm 1} 2\\int_{-n_2k}^{n_2k} \\mathrm{d}\\beta e^{im(\\phi-\\phi') + i\\beta (z-z')} c_{m\\beta} J_m (hr\\!_\\perp),\\\\\n%\\mathcal{E}^{(0)}_{z} &= \\sum_{m=\\pm 1} \\oint_{C_2} \\mathrm{d}\\beta e^{im(\\phi-\\phi') + i\\beta (z-z')} \\mathcal{E}^{(0)}_{z,m\\beta}(r\\!_\\perp),\\\\\n\\mathcal{E}^{(S)}_z &= \\sum_{m=\\pm 1} \\oint_{C_2} \\mathrm{d}\\beta e^{im(\\phi-\\phi') + i\\beta (z-z')} a_{m\\beta} H_m^{(1)} (pr\\!_\\perp)\\\\\n&\\approx \\sum_{m=\\pm 1} 2\\int_{-n_2k}^{n_2k} \\mathrm{d}\\beta e^{im(\\phi-\\phi') + i\\beta (z-z')} a_{m\\beta} H_m^{(1)} (pr\\!_\\perp),\n\\end{align}\n\\end{subequations}\n\\begin{subequations}\\label{BT0RC2}\n\\begin{align}\n\\mathcal{B}^{(T)}_z &= \\sum_{m=\\pm 1} \\oint_{C_2} \\mathrm{d}\\beta e^{im(\\phi-\\phi') + i\\beta (z-z')} d_{m\\beta} J_m (hr\\!_\\perp)\\\\\n&\\approx \\sum_{m=\\pm 1} 2\\int_{-n_2k}^{n_2k} \\mathrm{d}\\beta e^{im(\\phi-\\phi') + i\\beta (z-z')} d_{m\\beta} J_m (hr\\!_\\perp),\\\\\n%\\mathcal{B}^{(0)}_{z} &= \\sum_{m=\\pm 1} \\oint_{C_2} \\mathrm{d}\\beta e^{im(\\phi-\\phi') + i\\beta (z-z')} \\mathcal{B}^{(0)}_{z,m\\beta}(r\\!_\\perp),\\\\\n\\mathcal{B}^{(S)}_z &= \\sum_{m=\\pm 1} \\oint_{C_2} \\mathrm{d}\\beta e^{im(\\phi-\\phi') + i\\beta (z-z')} b_{m\\beta} H_m^{(1)} (pr\\!_\\perp)\\\\\n&\\approx \\sum_{m=\\pm 1} 2\\int_{-n_2k}^{n_2k} \\mathrm{d}\\beta e^{im(\\phi-\\phi') + i\\beta (z-z')} b_{m\\beta} H_m^{(1)} (pr\\!_\\perp).\n\\end{align}\n\\end{subequations}\nAbove, the approximation works when the waveguide is lossless and hence the branch lines along the imaginary axis of the $ \\beta $ plane can be ignored. The factor of $ 2 $ comes from the sign flip of the two branch lines parallel to the real axis in the $ \\beta $ plane ($ 2=1-\\mathrm{e}^{\\pi i} $), and physically corresponds to the degeneracy of $ 2 $ degrees of freedom of the polarization of the unguided modes in the transverse plane. Although we use the integral limits $ -n_2k $ to $ n_2k $, in practice, it should be either $ 0 \\rightarrow n_2k$ or $ -n_2k\\rightarrow 0 $ depending on the propagation directions of interest. \n\nOne can obtain the guided and unguided field components with the dipole oriented in $ z $, $ \\phi $ and $ r\\!_\\perp $ directions by substituting the $ \\bmc{E}^{(0)}_{m\\beta}(r\\!_\\perp) $ expressions for corresponding cases into Eqs.~(\\ref{ET0RRes}-\\ref{BT0RC2}). \n\nTo calculate the guided modes, we need to calculate the residues at isolated poles with $ \\beta_{1,m} $ and $ m=\\pm 1 $. The poles can be found by using the condition that\n\\begin{align}\nD=P^2+QR=0,\n\\end{align}\nor\n\\begin{align}\\label{pole4beta}\n&\\beta^2m^2k^4\\left[J_m(ha) H_m^{(1)}(pa) \\right]^2 (\\varepsilon_f-1)^2\\nonumber\\\\\n-& h^2p^2a^2k^2 \\left[hJ_m(ha) \\dd{}{(pa)}H_m^{(1)}(pa)-pH_m^{(1)}(pa)\\dd{}{(ha)}J_m(ha) \\right]\\nonumber\\\\ &\\times\\left[hJ_m(ha) \\dd{}{(pa)}H_m^{(1)}(pa)-\\varepsilon_f pH_m^{(1)}(pa)\\dd{}{(ha)}J_m(ha) \\right]=0.\n\\end{align}\nUseful relationships to solve the equation above are\n\\begin{align}\nJ_{-m}(z)=(-1)^nJ_n(z),\\, &\\quad H_{-m}^{(1)}(z)=e^{m\\pi i}H_m^{(1)}(z),\\\\\n\\dd{}{z}J_m(z) &= \\frac{1}{2} \\left( J_{m-1}(z)-J_{m+1}(z) \\right),\\\\ \n\\dd{}{z}H^{(1)}_m(z) &= \\frac{1}{2} \\left( H^{(1)}_{m-1}(z)-H^{(1)}_{m+1}(z) \\right).\n\\end{align}\nWe can rewrite Eq.~(\\ref{pole4beta}) as\n\\begin{align}\\label{pole4beta2}\n&\\beta^2m^2k^2\\left(J_m\\!(ha) H_m^{(\\!1\\!)}\\!(pa) \\right)^2 (\\varepsilon_f-1)^2\\nonumber\\\\\n=& \\frac{h^2p^2a^2}{4} \\left[hJ_m\\!(ha)\\! \\left( H^{(\\!1\\!)}_{m-1}\\!(pa)\\!-\\! H^{(\\!1\\!)}_{m+1}\\!(pa) \\right)\\!-\\! pH_m^{(\\!1\\!)}\\!(pa)\\left( J_{m-1}\\!(ha)\\!-\\! J_{m+1}\\!(ha) \\right) \\right]\\nonumber\\\\ \n&\\!\\!\\!\\!\\times\\!\\left[ \\! hJ_m\\!(ha)\\! \\left(\\! H^{(\\!1\\!)}_{m-1}\\!(pa)\\!-\\! H^{(\\!1\\!)}_{m+1}\\!(pa)\\! \\right)\\!-\\! \\varepsilon_f pH_m^{(\\!1\\!)}\\!(pa)\\!\\left( J_{m-1}\\!(ha)\\!-\\! J_{m+1}\\!(ha) \\right) \\right]\\!.\n\\end{align}\nSince both $ h $ and $ p $ are functions of $ \\beta $, the equation above is complicated in solving for $ \\beta $. If $ ka<0.8 $, asymptotic approximation is good enough to solve Eq.~(\\ref{pole4beta2}) and gives an analytic solution for $ \\beta $~\\cite{Klimov2004}. However, in our nanofiber case, this $ ka<0.8 $ condition is not satisfied. We should be able to numerically solve Eq.~(\\ref{pole4beta2}) for $ \\beta $ as the characteristic constant for the guided mode with $ m=\\pm 1 $. %\\textcolor{red}{Q: we may be able to prove that Eq.~\\eqref{pole4beta2} is equivalent to the eigen equation of $ \\beta $ for the bare fiber case. Useful relationship: $ K_n(x)=\\frac{\\pi}{2}i^{n+1}H_n^{(1)}(ix) $.}\n\nNumerically, the $ \\beta_0 $ solved from the radiation problem is indistinguishable with the one solved from the nanofiber's eigenmode equation in the regime we are interested in.\n\nNext, we solve for the guided modes contributions to the longitudinal components of the fields by applying the residual theorem to Eqs.~\\eqref{ET0RRes} and~\\eqref{BT0RRes} and differentiating the denominator that generates poles evaluated at $ \\beta_{1,m=\\pm 1} $. %\\textcolor{red}{(Q: are those poles all of order 1?)} \nAll transverse components of the fields can be obtained from the longitudinal components using the relations of Eq.~\\ref{EHzgauss}. \n%Sample numerical calculations has been performed, and results are documented in the NanofiberProjectPlots.pdf (Dropbox folder, \\url{Nanofiber/Code/Matlab/Plots}). The primary plots show that there are phase shifts for the transmitted and reflected lights so that the mode profile is not symmetric to the $ x $ axis where the atom lies on; the reflected light field has a backaction on the atom tending to move it off the trapping point; the $ m=\\pm 1 $ modes are not balanced... \nOur results were checked by reproducing the decay rates provided in Ref.~\\cite{Klimov2004}. \n\nTo calculate the total decay rate of the atom with the enhancement due to the coupling to the unguided modes, we need to find out the functions describing the branch cuts and the integration path for the unguided modes. The equations defining the branch cut are given by\n\\begin{align}\\label{branchcutequ}\n\\mathrm{Im}\\left[p \\right] &=0\\\\\n\\mathrm{Im}\\left[h\\right] &=0.\n\\end{align}\nBy setting $ \\beta=x+iy $, we can rewrite the first equation as\n\\begin{align}\np&=\\sqrt{k^2-\\beta^2}\\\\\n&=\\left[(k^2-x^2+y^2)^2 + 4x^2y^2 \\right]^{1/4}e^{\\frac{i}{2}\\arctan\\frac{-2xy}{k^2-x^2+y^2}}.\n\\end{align}\nHence Eq.~(\\ref{branchcutequ}) yields\n\\begin{align}\n0&= \\left[(k^2-x^2+y^2)^2 + 4x^2y^2 \\right]^{1/4} \\sin \\left[\\frac{1}{2}\\arctan\\frac{-2xy}{k^2-x^2+y^2} \\right]\\\\\n&= \\frac{1}{\\sqrt{2}} \\left[(k^2\\!-\\! x^2\\!+\\! y^2)^2 \\!+\\! 4x^2y^2 \\right]^{1/4} \\sqrt{1\\!-\\!\\cos \\left(\\arctan\\frac{-2xy}{k^2\\!-\\! x^2\\!+\\! y^2} \\right)}\\\\\n&= \\frac{1}{\\sqrt{2}} \\left[(k^2\\!-\\!x^2\\!+\\! y^2)^2 \\!+\\! 4x^2y^2 \\right]^{1/4} \\sqrt{1\\!-\\! \\frac{k^2\\!-\\! x^2\\!+\\! y^2}{\\left[(k^2\\!-\\! x^2\\!+\\! y^2)^2 \\!+\\! 4x^2y^2 \\right]^{1/2}} }\\\\\n&=\\sqrt{\\left[(k^2-x^2+y^2)^2 + 4x^2y^2 \\right]^{1/2}-(k^2-x^2+y^2)},\n\\end{align}\nwhich gives\n\\begin{align}\n\\left[(k^2-x^2+y^2)^2 + 4x^2y^2 \\right]^{1/2}&=(k^2-x^2+y^2),\\\\\n\\Leftrightarrow \\qquad \\qquad \\qquad \\qquad \\qquad x^2y^2&=0.\\label{branchcut2}\n\\end{align}\nObviously, the $ x $ axis between $ [-k,k] $ and the entire $ y $ axis are the branch cuts. To separate the branches into upper and lower parts, we can define an arbitrarily small positive number $ \\delta\\epsilon\\rightarrow 0 $ so that Eq.~\\eqref{branchcut2} gives\n\\begin{align}\nxy&=\\delta\\epsilon.\n\\end{align}\nSimilarly, the condition for $ \\mathrm{Im}[h]=0 $ gives the same result. To make the field components homomorphic at any point in the complex $ \\beta $ plane, we choose the branch cuts that satisfy \n\\begin{align}\nxy&>\\delta\\epsilon>0.\n\\end{align}\nBy the physics condition of unguided mode, we also have \n\\begin{align}\n-n_2k<x<n_2k.\n\\end{align}\nIn this way, the branch cuts as hyperbola-type lines are symmetrically separated into top-right and lower-left parts, and are very close to the $ x- $ and $ y- $ axes. \nFor the top-right branch, one can choose the integration path as shown in Fig.~\\ref{fig:integralpath} in the contour integral avoiding the branch cut. \n\n%\\scalefig{Figs/contourpath2}{0.8}{Integration path of the contour integral for radiation modes.}\n\nIn the case where the nanofiber can be treated as a lossless medium, the contour integral can be treated as an integral over real axis from $ -kn_2 $ to $ kn_2 $. \nWe illustrate the division of the guided and unguided mode contributions to the integration over $ \\beta $ in Fig.~\\ref{fig:integralpaths} and show the contour integrals in different regions to be calculated. \n\n\\begin{figure}[!tbp]\n\\centering\\makebox[\\textwidth]{\n\\includegraphics[width=0.85\\textwidth]{../media/Figs/integratepath_GF}}\n\\caption[Integral paths for the dyadic Green's function calculations when loss is negligible.]{Integral paths for the dyadic Green's function\\index{dyadic Green's function} calculations. Part (a) is the integral path for the dipole's free-space field contribution calculation [see, for example, Eq.~\\eqref{ET0RC1}]. Part (b) is the integral path for the scattered and transmitted field contributions calculation [see, for example, Eq.~\\eqref{ET0RC1}]. Part (c) is the integral path for the dyadic Green's function calculation using the eigenmode decomposition method [see Eqs.~\\eqref{Eq::GreensEigenmodes} and~\\eqref{Eq::GreensunguidedEigenmodes}]. The integral paths on the left-hand-side (in blue) indicate the backward propagating contributions, while the right-hand-side (in red) parts corresponding to the forward propagating contributions. For the eigenmode decomposition method in part (c), if one choose to use $ f=\\pm 1 $ to indicate the propagation direction, then only the $ \\beta>0 $ portion of integral path will be applied. }\n\\label{fig:integralpaths}\n\\end{figure}\n\nAs shown in section~\\ref{sec:eigenmodesofwaveguides}, the guided and unguided modes contribution to the dyadic Green's function\\index{dyadic Green's function} can be distinguished through the choice of integration paths. Fig.~\\ref{fig:integralpaths}, part (a) shows the integral path to calculate the dipole free-space contribution which does not yield guided mode contribution to the total dyadic Green's function. Part (b) shows the loop and real-valued integral paths of the guided and unguided mode-divisions to the scattered and transmitted field components. The $ \\mathrm{Re}(\\beta)<0 $ and $ \\mathrm{Re}(\\beta)>0 $ parts correspond to the backward and forward propagating contributions, respectively. Part (c) of the figure indicates the path using the eigenmode decomposition method in the case where the sign of $ \\mathrm{Re}(\\beta) $ indicates the propagation directions. Depending on the propagation directions, we should choose the right integral paths for the corresponding methods adopted, and different methods should yield the same result. \n\n\nWith all of the field components solved given a dipole vector, the dyadic Green's function\\index{dyadic Green's function} can be calculated with three parts: the part due to free-dipole radiation, $ \\GFT_0(\\br,\\br') $, the field scattering part due to the presence of the waveguide interface, $ \\GFT_S(\\br,\\br') $, and the part due to mode transmission through the waveguide, $ \\GFT_T(\\br,\\br') $. The former two parts generate the unguided mode contribution to the total dyadic Green's function, and the third part forms the guided mode contribution to the total dyadic Green's function. The $ ij $-th components of the three parts of the dyadic Green's function\\index{dyadic Green's function} can then be calculated by (see Eq.~\\eqref{eq:GFTijEd})\n\\begin{align}\nG_0^{ij}(\\br,\\br') &= \\frac{\\mathcal{E}_i^{(0)}(\\br)}{d_j(\\br')},\\\\\nG_R^{ij}(\\br,\\br') &= \\frac{\\mathcal{E}_i^{(S)}(\\br)}{d_j(\\br')},\\\\\nG_T^{ij}(\\br,\\br') &= \\frac{\\mathcal{E}_i^{(T)}(\\br)}{d_j(\\br')},\n\\end{align}\nwhere $ \\mathcal{E}_i^{(A)}\\,(A=0,S,T) $ are the $ i $-th free-dipole radiation, and interface scattering and mode transmission electric components due to the corresponding dipole $ d_j $ orientated along the $ \\mathbf{e}_j $ direction. The total dyadic Green's function\\index{dyadic Green's function} is\n\\begin{align}\n\\GFT(\\br,\\br')=\\GFT_0(\\br,\\br')+\\GFT_S(\\br,\\br')+\\GFT_T(\\br,\\br') .\n\\end{align} \n\n\n%</nanofiberradiationproblem>\n\n\n%<*choozingSWGs>\n\\chapter{The choice of square waveguides for this study}\\label{chap:choozingSWGs}\n\\section{Phase walkoff problems of rectangular waveguides}\nBased on the enhanced QND-measurement--induced spin squeezing protocol we have studied in Ref.~\\cite{Qi2017Enhanced} or Chapter~\\ref{chap:Faraday}, a key to generate a strong spin squeezing effect for QND measurement is to find orthogonal modes that couple the ``local oscillator\" and the ``signal\". \nWe can denote them as $ H $ and $ V $ modes. \nIn general, the field operator for the QND measurement can be written as \n\\begin{align}\\label{eq:EdifferentHV}\n\\hat{\\mathbf{E}}^{(+)}(r\\!_\\perp,\\phi,z;t) &= \\sqrt{ \\frac{2 \\pi \\hbar \\omega_0}{ v_g^H} } \\mathbf{u}_H(r\\!_\\perp,\\phi) \\hat{a}_H(z,t)  e^{i (\\beta_0^H z- \\omega_0 t)}\\nn\\\\\n&\\quad +\\sqrt{ \\frac{2 \\pi \\hbar \\omega_0}{ v_g^V} } \\mathbf{u}_V(r\\!_\\perp,\\phi) \\hat{a}_V(z,t)  e^{i (\\beta_0^V z- \\omega_0 t)},\n\\end{align}\nwhere $ v_g^{H/V} $ and $ \\beta_0^{H/V} $ are the group velocities and propagation constants of the $ H $ and $ V $ modes, respectively. When a rectangular waveguide is used, $ v_g^H $ and $ v_g^V $, so as the projected mode constants $ \\beta_0^H $ and $ \\beta_0^V $, become non-degenerate.\nThe offset of $ v_g^{H/V} $ and $ \\beta_0^{H/V} $ between the two guided modes could lead to a walkoff effect and causes an intrinsic phase shift.\nWe want to avoid this walkoff effect, unless the phase shift between the two modes at atom positions are multiples of $ 2\\pi $, which is difficult to implement as we will show next. \n%This follows discussions held with the collaborators on Ref.~\\cite{Qi2017Enhanced}.\n\n\\section{Optimal width of a \\SWG to tolerate fabrication imperfections}\n\nFour plots shown in Fig.~\\ref{fig:ng_rect_dwg} are the phase and group indices of refractions of general rectangular waveguides in determining the\npreferred waveguie size for our study. \n%I made four plots when I and Dr. Jongmin Lee were working on determining the preferable dimension of the waveguides. See Fig.~\\ref{fig:ng_rect_dwg}.\n\n\\begin{figure}[!tbp]\n\\centering\n\\begin{minipage}[h]{\\linewidth}\n %\\begin{tabular}{*{2}{b{0.2\\textwidth-2\\tabcolsep}}}\n  \\subfloat[h][]{\n    %\\input{fig/nanofiber_peakxi_rp_NA2500.tex}\n    \\includegraphics[width=0.48\\linewidth]{../media/Figs/ng_D1_dwg}\n    \\label{fig:ng_D1_dwg}\n    }\n    \\hfill\n  \\subfloat[h][]{\n      \\label{fig:ng_D2_dwg}\n      \\includegraphics[width=0.48\\linewidth]{../media/Figs/ng_D2_dwg}\n      %\\input{fig/nanofiber_C1_y.tex}\n      }\n   \\end{minipage}\\vfill\n   \\begin{minipage}[h]{\\linewidth}\n    %\\begin{tabular}{*{2}{b{0.2\\textwidth-2\\tabcolsep}}}\n     \\subfloat[h][]{\n       %\\input{fig/square waveguide_peakxi_rp_NA2500.tex}\n       \\includegraphics[width=0.48\\linewidth]{../media/Figs/ng_D1_rectwg_dwg}\n       \\label{fig:ng_D1_rectwg_dwg}\n       }\n       \\hfill\n     \\subfloat[h][]{\n         \\label{fig:ng_D2_rectwg_dwg}\n         \\includegraphics[width=0.48\\linewidth]{../media/Figs/ng_D2_rectwg_dwg}\n         %\\input{fig/square waveguide_C1_y.tex}\n         }\n   \\end{minipage}\n\\caption[Optimal choice of waveguide width to tolerate fabrication imperfections.]{Group index of refraction with changing width of a square waveguide ($ n_1=2.0,\\,w=300 $ nm) at cesium's D1 line (a) and D2 line (b). Group indices of refraction and the phase indices of refraction\\index{phase index of refraction} for the fundamental quasi-\\TE and quasi-\\TM modes of an imperfect \\SWG with a side changing its length ($ x $ axis) at the D1 line (c) and the D2 line (d).}\\label{fig:ng_rect_dwg}\n\\end{figure}\n\nIn the figure, (a) and (b) show that the group index of refraction\\index{group index of refraction} $n_g$ reaches the\npeak value at $\\sim 300$ nm for both D1 line (a) and D2 line (b). The plateaus\nat the $300$ nm $x$-axis value of the $n_g$ curves as a function\nof the width of a square waveguide, indicating that $n_g$ will be the most\nrobust case in presence of fabrication fluctuations. 1\\% of fabrication\nimperfection may not be a big issue to worry about in our case.\n\nIn Fig.~\\ref{fig:ng_rect_dwg}, (c) and (d), one side of the waveguide is fixed at $300$ nm while\nvarying the other side from $200$ nm to $400$ nm. The the phase index\nof refraction ($\\beta/k$) and the group index of fraction\\index{group index of refraction} ($n_g$) for the\nnon-degenerate fundamental quasi-\\TE and quasi-\\TM modes are plotted. Our formulas of\neffective mode areas for spin squeezing should be modified for the\nnon-degenerate mode case. We merely give the followling brief outline for the modification here: the $n_g$ in the formula of the effective interaction mode area for our Faraday spin squeezing protocol~\\cite{Qi2017Enhanced}, $A_{\\rm Far}$, should be replaced with the geometric average of $n_g^{TE}$ and $n_g^{TM}$, that is $\\sqrt{n_g^{V} \\times n_g^{H}}$ when $V$ and $H$ modes are the quasi-\\TE and quasi-\\TM modes; the equation for the  input mode area, $A_0$, maintains its original form. In the end,\nthe cooperavity formula should be modified by a factor of the square\nroot of the ratio between $n_g^V$ and $n_g^H$, where the input probe is\npolarized along the $H$ direction and atoms are trapped on the $V$ axis.\nFrom the plots of (c) and (d) at D1 and D2 lines, it is seen that the\nphase indices of refraction are only barely distinguishable between the two modes with\n$10\\%/k$ maximum when one side of the waveguide is $200$ nm. The phase\nmatching condition basically tells us that the two groups of atoms\nshould be trapped in a minimum distance of $10\\times k$, which might be too long to implement considering the great photon loss through the waveguide. Notice that the phase\ndifference between the two modes scales almost linearly when one side of\nthe waveguide decreases.\n\nOn the other hand, the ratio between the two group indices increases\ndramatically when one side of the waveguide is shortened. But when we\nplug in the numbers, with a $200$ nm $\\times$ $300$ nm waveguide, the enhancement of\ncooperativity is only about $15\\%$ from the $300$ nm $\\times$ $300$ nm square waveguide case. \nConsidering that the trapping potential well gets sharper when the\ncorresponding side of the waveguide decreases, we think the most\nimportant benefit of using a rectangular waveguide would be the ability\nto make the trapping potential sharp on the direction parallel to the\nnearest side of the waveguide. \n%\\satomi{Qi, you probably don't have to say this following sentence.} We haven't considered the quantized trapping potential-level splitting on the vertical direction, which would be interesting for the experiment.\n\nRegarding the phase mismatch issue, as along as the group velocities\ndo not make the light pulses of the two modes walk off in the\nwaveguide range significantly, the measurement signal with the time integral under a\nresolution of ns or even longer won't distinguish the difference between the\nsignals of polarization states from the two groups of atoms. \nSince the birefringence rotation due to the mode distortion is deterministic given the number of atoms, we might be able to compensate for the phase drafting and extract the pure Faraday rotation from the measurement records.\n\n%</choozingSWGs>\n\n%###################################################################################\n\\bibliographystyle{../styles/abbrv-alpha-letters-links}\n\\bibliography{../refs/Archive}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\printindex\n\\end{document}\n", "meta": {"hexsha": "62a0d50f31906851c9c802aed6f8bfa39727fc3a", "size": 223862, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chap2/WaveguideInterface.tex", "max_stars_repo_name": "i2000s/PhD_Thesis", "max_stars_repo_head_hexsha": "a9bc6bc4213896c70c90cbb3d9b533782d428761", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-03-26T01:58:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T19:11:43.000Z", "max_issues_repo_path": "chap2/WaveguideInterface.tex", "max_issues_repo_name": "i2000s/PhD_Thesis", "max_issues_repo_head_hexsha": "a9bc6bc4213896c70c90cbb3d9b533782d428761", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-18T01:47:21.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-18T01:47:21.000Z", "max_forks_repo_path": "chap2/WaveguideInterface.tex", "max_forks_repo_name": "i2000s/PhD_Thesis", "max_forks_repo_head_hexsha": "a9bc6bc4213896c70c90cbb3d9b533782d428761", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-07-17T21:55:09.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-17T21:55:09.000Z", "avg_line_length": 95.4635394456, "max_line_length": 1498, "alphanum_fraction": 0.7018565009, "num_tokens": 76301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3133126198102942}}
{"text": "% --- [ Subgraph Isomorphism Search Library ] ----------------------------------\n\n\\subsection{Subgraph Isomorphism Search Library}\n\\label{sec:impl_subgraph_isomorphism_search_library}\n\nImplementing the subgraph isomorphism search algorithm was without doubt the most difficult endeavour of the entire project. It took roughly five iterations of implementing, evaluating and rethinking the algorithm to find an approach which felt right and another two iterations to develop a working implementation which passed all the test cases.\n\nAs mentioned in section~\\ref{sec:ver_performance}, an early throwaway prototype provided a partial implementation of the subgraph isomorphism algorithm proposed by Ullman. The prototype was intended to provide insight into the subgraph isomorphism problem domain, and was eventually discarded.\n\nThe second throwaway prototype was specifically designed to exploit known properties of CFG (e.g. connected graphs with a single entry node) to limit the search space. Focusing on connected graphs drastically simplified the general problem of subgraph isomorphism search, and enabled algorithms which traverse the graph from a given start node to identify subgraph isomorphisms. The second prototype had many issues (e.g. non-deterministic, unable to handle graph cycles), but provided valuable insight into how a subgraph isomorphism search algorithm may be designed when focusing on connected graphs.\n\nIn contrast to its predecessor, the third prototype separated subgraph isomorphism candidate discovery from candidate validation logic. A subgraph isomorphism candidate is a potential isomorphism of a subgraph in a graph, which provides a mapping from subgraph node names to graph node names. Should the source and the destination nodes of each directed edge in the subgraph translate through the candidate node mapping to corresponding nodes (with a directed edge from the source to the destination node) in the graph, and should furthermore each node in the subgraph have the same number of directed edges as the nodes of the candidate (with a few caveats regarding entry and exit nodes), then the candidate is considered a valid isomorphism of the subgraph in the graph. The third prototype was still incomplete (mainly with regards to candidate discovery) when discarded, but the separation of candidate discovery and candidate validation logic has had a large influence on its succeeding prototypes.\n\nAs described in section~\\ref{sec:design_control_flow_analysis} and further evaluated in section~\\ref{sec:eval_control_flow_analysis_library_essential_requirements}, the current implementation of the subgraph isomorphism search algorithm enforces a single-entry/single-exit invariant on the subgraphs to simplify control flow analysis. This allows identified subgraphs to be replaced with single nodes, which inherit the predecessors of the subgraph entry node and successors of the subgraph exit node. For this reason, the candidate validation logic disregards the directed edges from predecessors of subgraph entry nodes and the directed edges to successors of subgraph exit nodes, when validating subgraph isomorphism candidates; which should clarify the aforementioned caveats of the preceding paragraph.\n\nSimilar to the third prototype, the fourth throwaway prototype separated candidate discovery from candidate validation. In addition, it introduced the concept of treating candidate node mappings as equations which may be solved, or at least partially solved. The candidate node mappings were extended from one-to-one node mappings (one subgraph node name maps to exactly one graph node name) to node pair mappings, which represent one-to-many node mappings (one subgraph node name maps to zero or more graph node names). The candidate discovery logic was extended to record all potential candidate nodes for a given subgraph node, when traversing the graph in search of candidates. A simple equation solver was implemented which was capable of identifying unique node pair mappings and propagate this information to successively simplify equations until they are either solved or require other methods for solving; an example of which is presented in figure~\\ref{fig:equation_unique}. The equation solver would however fail to find a solution if two node pair mappings had the same candidate nodes, as illustrated in figure~\\ref{fig:equation_fail}.\n\n\\begin{figure}[htbp]\n\t\\centering\n\t\\begin{subfigure}[t]{0.30\\textwidth}\n\t\t\\lstinputlisting[language=go, style=go, breaklines=false, numbers=none]{inc/7_impl/equation_unique_1.json}\n\t\t\\caption{Step 1.}\n\t\\end{subfigure}\n\t\\enskip\n\t\\begin{subfigure}[t]{0.23\\textwidth}\n\t\t\\lstinputlisting[language=go, style=go, breaklines=false, numbers=none]{inc/7_impl/equation_unique_2.json}\n\t\t\\caption{Step 2.}\n\t\\end{subfigure}\n\t\\enskip\n\t\\begin{subfigure}[t]{0.17\\textwidth}\n\t\t\\lstinputlisting[language=go, style=go, breaklines=false, numbers=none]{inc/7_impl/equation_unique_3.json}\n\t\t\\caption{Step 3.}\n\t\\end{subfigure}\n\t\\caption{In step 1, the unique node pair mapping between the subgraph node name \\textit{C} and the graph node name \\textit{Z} is identified, and the remaining node pair mappings are simplified by removing \\textit{Z} from their candidate nodes. Similarly, in step 2, the unique node pair mapping between \\textit{B} and \\textit{Y} is identified; thus simplifying the equation further. Lastly, in step 3, the unique node pair mapping between \\textit{A} and \\textit{X} is identified, and the equation is thereby solved.}\n\t\\label{fig:equation_unique}\n\\end{figure}\n\n\\begin{figure}[htbp]\n\t\\centering\n\t\\begin{subfigure}[ht]{0.23\\textwidth}\n\t\t\\lstinputlisting[language=go, style=go, breaklines=false, numbers=none]{inc/7_impl/equation_fail.json}\n\t\\end{subfigure}\n\t\\caption{An equation which the simple equation solver of the forth prototype would fail to solve, as it cannot be simplified by identifying unique node pair mappings.}\n\t\\label{fig:equation_fail}\n\\end{figure}\n\nThe fifth throwaway prototype extended the capabilities of the simple equation solver by trying different candidate node mappings recursively until a valid subgraph isomorphism was found or known not to exist. These equations were solved concurrently using Go routines (independently executing functions, which are multiplexed onto system threads) which relayed the answers back using channels (typed and synchronised communication channels).\n\nAt this stage, the algorithm design had started to feel mature and the focus shifted from implementing throwaway prototypes to building a solid foundation. Starting with the parts of the system that were best understood, one part or concept at the time were removed from the throwaway prototype and carefully reimplemented in a new library through a series of steps. Firstly, the API of the new library was taken into careful consideration, and a set of stub functions and core data structures were added and thoroughly documented. Secondly, test cases were written for each stub function of the library. Lastly, the stub functions were implemented one at the time and verified against the test cases.\n\nWhile the new implementation passed most test cases, there were a few corner cases for which the library produced incorrect results. The concurrent nature of the library made it difficult to debug, and a decision was made to reimplement the equation solver without concurrency. This resulted in a cleaner implementation which was easy to debug and successfully passed all test cases.\n\nThe final implementation of the subgraph isomorphism search algorithm is a cleaned up and thoroughly tested version of the non-concurrent library, which has a 94.8\\% code coverage; as further described in section~\\ref{sec:ver_code_coverage}. The final implementation was developed in the \\textit{``isobug''} branch on GitHub, and merged\\footnote{Fix subgraph isomorphism search: \\url{https://github.com/decomp/decomp/issues/183}} once stable into the \\textit{``master''} branch.\n", "meta": {"hexsha": "5a05964a83711beb453f02302c939d4185efa877", "size": 7976, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/compositional_decompilation/sections/7_implementation/4_subgraph_isomorphism_search_library.tex", "max_stars_repo_name": "decomp/doc", "max_stars_repo_head_hexsha": "fb82b6a5074aa8721afb24a5537bf1964ed20467", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2016-05-27T10:16:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T08:14:04.000Z", "max_issues_repo_path": "report/compositional_decompilation/sections/7_implementation/4_subgraph_isomorphism_search_library.tex", "max_issues_repo_name": "decomp/doc", "max_issues_repo_head_hexsha": "fb82b6a5074aa8721afb24a5537bf1964ed20467", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 48, "max_issues_repo_issues_event_min_datetime": "2019-01-30T19:08:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-29T19:17:53.000Z", "max_forks_repo_path": "report/compositional_decompilation/sections/7_implementation/4_subgraph_isomorphism_search_library.tex", "max_forks_repo_name": "decomp/doc", "max_forks_repo_head_hexsha": "fb82b6a5074aa8721afb24a5537bf1964ed20467", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-05-25T21:15:26.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-09T07:36:14.000Z", "avg_line_length": 147.7037037037, "max_line_length": 1148, "alphanum_fraction": 0.8135656971, "num_tokens": 1706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3133126119911768}}
{"text": "\\setlength{\\footskip}{8mm}\n\n\\chapter{Extracting the Object from the Shadows: Maximum Likelihood\nObject/Shadow Discrimination}\n\\label{ch:shadow}\n\n\\textit{In this chapter, we propose and experimentally evaluate a new\nmethod for detecting shadows using a simple maximum likelihood\nformulation based on color information. We first estimate, offline, a\njoint probability distribution over the difference in the HSV color\nspace between pixels in the current frame and the corresponding pixels\nin a background model, conditional on whether the pixel is an object\npixel or a shadow pixel.  Given the learned distribution, at run time,\nwe use the maximum likelihood principle to classify each foreground\npixel as either shadow or object.  In an experimental evaluation, we\nfind that the method outperforms standard methods on three different\nreal-world video surveillance data sets.  We conclude that the\nproposed shadow detection method would be an extremely effective\ncomponent in an intelligent video surveillance system.}\n\n\\section{Introduction}\n\nIn many video surveillance applications, detecting and tracking moving\nobjects is an important issue. A very common approach to detect moving\nobjects is to apply background a subtraction algorithm. However,\nbackground subtraction algorithms share one major disadvantage:\nshadows tend to be misclassified as part of the foreground\nobject. This can lead to many undesirable consequences in the\ndetection step while segmenting and extracting features of moving\nobjects. For example, any estimate of the size of the detected object\nwould be an overestimate due to the misclassification of shadow pixels\nas foreground pixels. Additionally, during object segmentation,\nshadows misclassified as moving objects could lead to merging\notherwise separate blobs representing different people walking close\nto each other.  This would make isolating and tracking people in a\ngroup much more difficult than necessary.\n\nSince shadow removal can significantly improve the performance of\ncomputer vision tasks such as tracking, segmentation, and object\ndetection, shadow detection has become an active research area in\nrecent years.\n\nSeveral well-known algorithms for shadow detection already exist. Most\nof the work is based on background modeling and color difference\ninformation. Generally, some model of the background is estimated,\nthen the difference between the background and current image is used\nto identify changed pixels, then the changed pixels are further\nclassified into object and shadow.  Shadow pixels tend to have similar\nchromaticity but lower luminance than the corresponding background\npixel.  In the RGB color space, chromaticity and luminance are not\northogonal, but lighting differences can be controlled for in the\nnormalized RGB color space \\shortcite{finlayson98colour}.  Some\nresearch work thus utilizes the normalized RGB space in the background\nsubtraction and shadow removal\nalgorithm \\shortcite{mckenna00tracking,elgammal02background,hong03background}.\n\n\\shortciteA{mikic00shadow} observe that in the normalized RGB color\nspace, shadow pixels tend to be more blue and less red than\nilluminated pixels.  They apply a probabilistic model based on the\nnormalized red and blue features to classify shadow pixels in traffic\nscenes. The authors assume that the background and shadow values\nfollow Gaussian distributions and foreground values follow a uniform\ndistribution. They iteratively estimate the posterior probabilities of\na given pixel belonging to each of three classes: background, shadow,\nand foreground, until one of the probabilities reaches a fixed\nthreshold. The pixel is then classified accordingly.  If none of the\nthree probabilities reaches the threshold, the pixel is classified as\nbackground.\n\n\\shortciteA{salvador04shadow} propose a new method for detecting\ncast shadows. They first identify the presence of shadows in the RGB\ncolor space based on the fact that shadows darken the surface they\ncast on. The detected regions are further verified based on the color\ninvariance and geometric properties expected of shadows.\n\n\\shortciteA{havasi06geometric} illustrate that color-based methods\nwork well for weak shadows but not strong shadows. Hence, they\nintegrate geometric information into the detection process, resulting\nin an iterative Bayesian framework combining both color and geometric\ninformation that improves detection results.\n\nOne well-known problem with the normalized RGB space is that\nnormalization of pixels with low intensity results in unstable\nchromatic\ncomponents \\shortcite{kender76color}. \\shortciteA{cucchiara01shadow}\nand \\shortciteA{chen08shadow} propose a HSV color-based method to\ndistinguish shadows from moving objects that eliminates this\nconcern. Their approach is based on the assumption that only the\nintensity of the area covered by shadows will significantly\nchange. Therefore, they detect shadows using the so-called\ndeterministic nonmodel-based (DNM) approach as follows:\n\\[\n  SP_t (x,y) = \\left\\{ \n  \\begin{array}{ll}\n    1 & {\\rm if} \\; \\alpha \\le \\frac{{I_t^V (x,y)}}{{B_t^V (x,y)}} \\le \\beta\\\\ \n    & \\;\\;\\; \\wedge \\; (I_t^S (x,y) - B_t^S (x,y)) \\le T_S  \\\\ \n    & \\;\\;\\; \\wedge \\left| {I_t^H (x,y) - B_t^H (x,y)} \\right| \\le T_H\\\\ \\\\\n    0 & {\\rm otherwise}, \\\\ \n  \\end{array} \\right.\n\\]\nwhere $SP_t(x,y)$ is the resulting binary mask for shadows at each\npixel $(x,y)$ at time $t$.  $I_t^H$, $I_t^S$, $I_t^V$, $B_t^H$,\n$B_t^S$, and $B_t^V$ are the H, S, and V components of foreground\npixel $I_t(x,y)$ and background pixel $B_t(x, y)$ at pixel $(x,y)$ at\ntime $t$, respectively.  They prevent foreground pixels from being\nclassified as shadow pixels by setting two thresholds, $0 < \\alpha <\n\\beta < 1$.  The four thresholds $\\alpha$, $\\beta$, $T_S$, and $T_H$\nare empirically determined.\n\nSome researchers have investigated color spaces besides RGB and\nHSV. \\shortciteA{blau06shadow} use an ``improved'' hue, luminance, and\nsaturation (IHLS) color space for shadow detection to deal with the\nissue of unstable hue at low saturation by modeling the relationship\nbetween them. They then perform simple background subtraction method\nbased on the IHLS color space and saturation-weighted hue statistics.\nTheir experimental results show that detecting shadows in this color\nis more reliable than in normalized RGB or HSV color spaces in several\nvideo sequences.\n\nAnother alternative color space is YUV.  Some applications such as\ntelevision and videoconferencing use the YUV color space natively, and\nsince transformation from YUV to HSV is\ntime-consuming, \\shortciteA{schreer02shadow} operate in the YUV color\nspace directly, developing a fast shadow detection algorithm based on\napproximated changes of hue and saturation in the YUV color space.\n\nThere has been some work using texture-based methods such as the\nnormalized cross-correlation (NCC)\ntechnique \\shortcite{tian05shadow,jacques05shadow}. This method\ndetects shadows based on the assumption that the intensity of shadows\nis proportional to the incident light, so shadow pixels should simply\nbe darker than the corresponding background pixels. Under this\nassumption, shadow patches should be scaled versions of the\ncorresponding background patches. This assumption is most valid in\nscenes with visible background texture inside the shadows. The method\ncomputes the NCC between the neighborhood of a pixel in the foreground\nmask and the neighborhood of the corresponding pixel in the background\nmodel.  For each pixel $(i, j)$ of the foreground mask, it considers a\n$(2N + 1)\n\\times (2N + 1)$ template $T_{ij}$ defined by $T_{ij}(n, m) = I(i+n,\nj+m)$ for $-N \\le n \\le N$ and $-N \\le m \\le N$ ($N$ is empirically\ndetermined). If $B(i, j)$ is the background model, the NCC value at\npixel $(i, j)$ is defined as follows:\n\\[\n  NCC(i,j) = \\frac{{ER(i,j)}}{{E_B (i,j)E_{T_{ij} } }},\n\\]\nwhere\n\\[\n  ER(i,j) = \\sum\\limits_{n = -N}^N {\\sum\\limits_{m = -N}^N {B(i + n,j\n  + m)T_{ij} (n,m)}},\n\\]\n\\[\n  E_B (i,j) = \\sqrt {\\sum\\limits_{n = -N}^N {\\sum\\limits_{m = -N}^N\n  {B(i + n,j + m)^2}}},\n\\]\n\\[\n  E_{T_{ij} } = \\sqrt {\\sum\\limits_{n = -N}^N {\\sum\\limits_{m = -N}^N\n  {T_{ij} (n,m)^2}}}.\n\\]\nFor a pixel in a shadow region, the NCC value should be large (close\nto one) and the $E_{T_{ij}}$ for the region around $(i,j)$, i.e., its\nmagnitude, should be smaller than $E_B (i,j)$. Consequently, a pixel\nis classified as shadow if\n\\[\n  NCC(i,j) \\ge L_{NCC} \n\\]\nand\n\\[\n  E_{T_{ij}} < E_B (i,j),\n\\]\nwhere $L_{NCC}$ is an empirical threshold.\n\nHowever, the texture-based method tends to misclassify foreground\npixels as shadow pixels when the foreground region has a similar\ntexture to the corresponding background\nregion. \\shortciteA{xu05shadow} propose a hybrid shadow removal\ntechnique that combines color and texture-based procedures to detect\nshadows.  Since chromaticity in a shadow region should be the same as\nthe corresponding background region, and since the texture in a shadow\nregion should be the same as the corresponding background region, the\nauthors first classify pixels based on a set of thresholds for\nbrightness and color distortion then perform speckle removal filtering\nto reconstruct the final foreground shapes.\n\nHere we propose a new method for detecting shadows using maximum\nlikelihood estimation based on color information.  We extend the\ndeterministic nonmodel-based approach to parametric statistical\nmodel-based approach. Our method estimates the joint distribution over\nthe difference in the HSV color space between pixels in the current\nframe and the corresponding pixels in a background model, conditional\non whether the pixel is an object pixel or a shadow pixel. At run\ntime, we simply use the maximum likelihood principle to classify each\nforeground pixel as either shadow or object given the estimated model.\nExperimental results demonstrate that our proposed method outperforms\nthe standard methods (DNM and NCC) on three different real-world video\nsurveillance data sets. Our method is thus effective and also has the\npotential to improve the object detection and motion analysis module\nin intelligent video surveillance systems.\n\nIn the rest of this chapter, I provide details of the proposed method\nand the overall process in Section \\ref{sec:shadow-algorithm},\ndemonstrate the effectiveness of the shadow detection method with an\nexperimental evaluation in Section \\ref{sec:shadow-results}, and then\nconclude and point to future work in\nSection \\ref{sec:shadow-discussion}.\n\n\\section{Maximum Likelihood Classification of Foreground Pixels}\n\\label{sec:shadow-algorithm}\n\nWe divide our method into two phases.  In the first, offline phase, we\nacquire training video, construct a background model from the first\nfew frames, perform foreground extraction on the remaining frames,\nthen manually label the extracted pixels as either object pixels or\nshadow pixels.  I previously describe these steps in\nSections \\ref{sec:blob-motion-detection}\nand \\ref{sec:blob-blob-extraction}. After that, we construct a joint\nprobability model over the difference in the HSV color space between\npixels in the current frame and the corresponding pixels in the\nbackground model, conditional on whether the pixel is an object pixel\nor a shadow pixel.\n\nDuring the second, online phase, we perform the same background\nmodeling and foreground extraction procedure and further classify\nforeground pixels as either shadow or object using the maximum\nlikelihood approach. I describe each of these steps in more detail in\nthe following sections.\n\n\\subsection{Offline Phase}\n\nAfter foreground extraction, we manually label pixels as either shadow\nor object. We then observe the distribution over the difference in hue\n($H_{\\text{diff}}$), saturation ($S_{\\text{diff}}$), and value\n($V_{\\text{diff}}$) components in the HSV color space between pixels\nin the current frame and the corresponding pixels in the background\nmodel.  Figure \\ref{fig:foreground-distribution} shows examples of\nthese distributions for object pixels, and\nFigure \\ref{fig:shadow-distribution} shows examples of these\ndistributions for shadow pixels.\n\n\\begin{figure}[t]\n  \\centering\n  \\subfloat[]{\\includegraphics[scale=0.25]{figures/foreground_diff_h.png}}\n  \\hspace{0.05cm}\n  \\subfloat[]{\\includegraphics[scale=0.25]{figures/foreground_diff_s.png}}\n  \\hspace{0.05cm}\n  \\subfloat[]{\\includegraphics[scale=0.25]{figures/foreground_diff_v.png}}\n  \\caption[Example distributions over the difference in hue,\n    saturation, and value components for true object pixels, extracted\n    from our hallway dataset.]{\\small Example distributions over the\n    difference in (a) hue, (b) saturation, and (c) value components\n    for true object pixels, extracted from our hallway dataset.}\n  \\label{fig:foreground-distribution}\n\\end{figure}\n\n\\begin{figure}[t]\n  \\centering\n  \\subfloat[]{\\includegraphics[scale=0.25]{figures/shadow_diff_h.png}}\n  \\hspace{0.05in}\n  \\subfloat[]{\\includegraphics[scale=0.25]{figures/shadow_diff_s.png}}\n  \\hspace{0.05in}\n  \\subfloat[]{\\includegraphics[scale=0.25]{figures/shadow_diff_v.png}}\n  \\caption[Example distributions over the difference in hue,\n    saturation, and value components for true shadow pixels, extracted\n    from our hallway dataset.]{\\small Example distributions over the\n    difference in (a) hue, (b) saturation, and (c) value components\n    for true shadow pixels, extracted from our hallway dataset.}\n  \\label{fig:shadow-distribution}\n\\end{figure}\n\nClearly, in all three cases, the distributions for object pixels and\nshadow pixels are very different.  We thus introduce a measurement\nprobability distribution conditional on whether the assignment for a\npixel is object or shadow. In this work, we assume that the individual\ncomponent difference distributions are conditionally independent given\nthe assignment.\n\nWe define the measurement likelihood for pixel $(x, y)$ given its\nassignment as follows.\n\\begin{equation}\n  \\label{eq:shadow-measurement}\n  \\begin{array}{ccl}\n    P(M_{\\text{xy}} \\mid A_{\\text{xy}} = \\text{sh}) \n            & = & P(H_{\\text{diff}} \\mid A_{\\text{xy}} = \\text{sh}) \\times \\\\\n            &   & P(S_{\\text{diff}} \\mid A_{\\text{xy}} = \\text{sh}) \\times \\\\\n            &   & P(V_{\\text{diff}} \\mid A_{\\text{xy}} = \\text{sh}),\n  \\end{array}\n\\end{equation}\nwhere $M_{xy}$ is a tuple containing the HSV value for pixel $(x,y)$\nin the current image as well as the HSV value for pixel $(x,y)$ in the\nbackground model for pixel $(x,y)$, and $A_{xy}$ is the assignment of\npixel $(x,y)$ as object or shadow. ``sh'' stands for shadow.\n\nTo make the problem tractable, we assume that the distributions over\nthe components on the right hand side in \\ref{eq:shadow-measurement}\nfollow Gaussian distributions, defined as follows.\n\\begin{equation*}\n  P(H_{\\text{diff}} \\mid A_{\\text{xy}} = \\text{sh}) =\n  {\\cal N}(H_{\\text{diff}} ;\n  \\mu_{h_{\\text{diff}}^{\\text{sh}}},\n  \\sigma^2_{h_{\\text{diff}}^{\\text{sh}}})\n\\end{equation*}\n\\begin{equation*}\n  P(S_{\\text{diff}} \\mid A_{\\text{xy}} = \\text{sh}) =\n  {\\cal N}(S_{\\text{diff}} ;\n  \\mu_{s_{\\text{diff}}^{\\text{sh}}},\n  \\sigma^2_{s_{\\text{diff}}^{\\text{sh}}})\n\\end{equation*}\n\\begin{equation*}\n  P(V_{\\text{diff}} \\mid A_{\\text{xy}} = \\text{sh}) =\n  {\\cal N}(V_{\\text{diff}} ;\n  \\mu_{v_{\\text{diff}}^{\\text{sh}}},\n  \\sigma^2_{v_{\\text{diff}}^{\\text{sh}}})\n\\end{equation*}\nSimilarly, the measurement likelihood for object pixels can be\ncomputed as follows.\n\\begin{equation}\n  \\label{eq:foreground-measurement}\n  \\begin{array}{ccl}\n    P(M_{\\text{xy}} \\mid A_{\\text{xy}} = \\text{obj}) \n            & = & P(H_{\\text{diff}} \\mid A_{\\text{xy}} = \\text{obj}) \\times \\\\\n            &   & P(S_{\\text{diff}} \\mid A_{\\text{xy}} = \\text{obj}) \\times \\\\\n            &   & P(V_{\\text{diff}} \\mid A_{\\text{xy}} = \\text{obj})\n  \\end{array}\n\\end{equation}\nHere ``obj'' stands for object. As for the shadow pixel distributions,\nwe assume Gaussian distributions over the components on the right hand\nside in \\ref{eq:foreground-measurement}, as follows.\n\\begin{equation*}\n  P(H_{\\text{diff}} \\mid A_{\\text{xy}} = \\text{obj}) =\n  {\\cal N}(H_{\\text{diff}} ;\n  \\mu_{h_{\\text{diff}}^{\\text{obj}}},\n  \\sigma^2_{h_{\\text{diff}}^{\\text{obj}}})\n\\end{equation*}\n\\begin{equation*}\n  P(S_{\\text{diff}} \\mid A_{\\text{xy}} = \\text{obj}) =\n  {\\cal N}(S_{\\text{diff}} ;\n  \\mu_{s_{\\text{diff}}^{\\text{obj}}},\n  \\sigma^2_{s_{\\text{diff}}^{\\text{obj}}})\n\\end{equation*}\n\\begin{equation*}\n  P(V_{\\text{diff}} \\mid A_{\\text{xy}} = \\text{obj}) =\n  {\\cal N}(V_{\\text{diff}} ;\n  \\mu_{v_{\\text{diff}}^{\\text{obj}}},\n  \\sigma^2_{v_{\\text{diff}}^{\\text{obj}}})\n\\end{equation*}\nWe estimate the parameters $\\Theta = \\{\n\\mu_{h_{\\text{diff}}^{\\text{sh}}},\n\\sigma^2_{h_{\\text{diff}}^{\\text{sh}}},\n\\mu_{s_{\\text{diff}}^{\\text{sh}}},\n\\sigma^2_{s_{\\text{diff}}^{\\text{sh}}},\n\\mu_{v_{\\text{diff}}^{\\text{sh}}},\n\\sigma^2_{v_{\\text{diff}}^{\\text{sh}}},\n\\mu_{h_{\\text{diff}}^{\\text{obj}}},\n\\sigma^2_{h_{\\text{diff}}^{\\text{obj}}},\n\\mu_{s_{\\text{diff}}^{\\text{obj}}},\n\\sigma^2_{s_{\\text{diff}}^{\\text{obj}}},\n\\mu_{v_{\\text{diff}}^{\\text{obj}}},\n\\sigma^2_{v_{\\text{diff}}^{\\text{obj}}} \\}$ directly from training\ndata during the offline phase.\n\n\\subsection{Online Phase}\n\nGiven the model estimate $\\Theta$, we use the maximum likelihood\napproach to classify a pixel as a shadow pixel if\n\\begin{equation}\n  \\label{eq:ml}\n  P(M_{\\text{xy}} \\mid A_{xy}=\\text{sh} ; \\Theta ) >\n  P(M_{\\text{xy}} \\mid A_{xy}=\\text{obj} ; \\Theta ).\n\\end{equation}\nOtherwise, we classify the pixel as an object pixel.\n\nWe could add the prior probabilities to the shadow model and the\nobject model in \\ref{eq:ml} to obtain a maximum a posteriori\nclassifier. In our experiments, we assume equal priors.\n\n\\section{Experimental Results}\n\\label{sec:shadow-results}\n\nIn this section, we present experimental results for our proposed\nmaximum likelihood (ML) classification method and compare the results\nwith two other methods from the literature, namely the deterministic\nnonmodel-based (DNM)\nmethod \\shortcite{kender76color,cucchiara01shadow} and the normalized\ncross-correlation (NCC)\nmethod \\shortcite{tian05shadow,jacques05shadow}.\n\n\\begin{figure}[t]\n  \\centering\n  \\subfloat[]{\\includegraphics[scale=0.4]{figures/csim_hallway_benchmark.png}}\n  \\hspace{0.05cm}\n  \\subfloat[]{\\includegraphics[scale=0.4]{figures/aton_lab_benchmark.png}}\n  \\hspace{0.05cm}\n  \\subfloat[]{\\includegraphics[scale=0.4]{figures/aton_highway1_benchmark.png}}\n  \\caption[Sample frames from the Hallway, Laboratory, and Highway\n    video sequences.]{\\small Sample frames from the (a) Hallway, (b)\n    Laboratory, and (c) Highway video sequences}\n  \\label{fig:benchmark}\n\\end{figure}\n\nWe performed the experiments on three video sequences.\nFigure \\ref{fig:benchmark} shows sample frames from the three video\nsequences. The video sequences include both indoor and outdoor\nscenes. The \\textit{Hallway} sequence\\footnote{Freely available for\nothers to experiment with\nat: \\url{http://www.kanouivirach.com/#downloads}.} shows a hallway\nscene. For this video, we mounted a CCTV camera to record in an\nacademic building. The \\textit{Laboratory} sequence shows a laboratory\nroom, and the \\textit{Highway} sequence shows a traffic scene. The\nlast two video sequences were first introduced in Prati et al.'s\nwork\\nocite{prati03shadow}.\n\nTo evaluate the performance of the methods, we compute the two metrics\nproposed by \\shortciteA{prati03shadow}, defining the shadow detection\nrate $\\eta$ and the shadow discrimination rate $\\xi$ as follows:\n\\[\n  \\eta = \\frac{TP_{\\text{sh}}}{TP_{\\text{sh}} + FN_{\\text{sh}}};\\; \n  \\xi = \\frac{TP_{\\text{obj}}}{TP_{\\text{obj}} + FN_{\\text{obj}}},\n\\]\nwhere the subscript ``sh'' and ``obj'' stand for shadow and object,\nrespectively. $TP$ and $FN$ are the number of true positive (i.e., the\nshadow or object pixels correctly identified) and false negative\n(i.e., the shadow or object pixels classified incorrectly) pixels.\n$\\eta$ expresses the proportion of shadow pixels correctly detected,\nand $\\xi$ expresses the proportion of object pixels correctly\ndetected.  $\\eta$ and $\\xi$ can also be thought of as the true\npositive rate (sensitivity) and true negative rate (specificity) for\ndetecting shadows, respectively. In the experiment, we also compare\nthe methods with the additional two metrics: precision and $F_1$\nscore.\n\n\\subsection{Preparation}\n\nGround truth data are provided with the \\textit{Laboratory} and\n\\textit{Highway} video sequences in Sanin et al.'s work\\nocite{sanin12shadow}. \nThey used a standard Gaussian mixture (GMM) background\nmodel\\nocite{stauffer99background} to extract foreground pixels for\nthe two videos. They selected 20 frames including objects from\nthe \\textit{Laboratory} sequence arbitrarily for labeling.  For\nthe \\textit{Highway} sequence, they labeled one out of every twenty\nframes including objects for a total of 20 frames.  For our\n\\textit{Hallway} video sequence, to prepare similar ground truth data,\nwe selected one out of every ten frames including objects for 20\nframes and manually labeled each pixel of each frame as object,\nbackground, or shadow. We used the previously mentioned extended\nversion of the GMM background model for foreground extraction, but the\nresults were not substantially different from those of the standard\nGMM.\n\nTo find the best parameters for each model while avoiding overfitting,\nfor each of the three models and each of the three data sets, we\nperformed five-fold cross validation using 10 of the training frames,\nreserving the remaining 10 frames for the final test. The 10 frames in\neach case were the second of every two frames in sequential order. We\nvaried the parameter settings for each method on each video dataset\nand selected the setting that maximized the $F_1$ score (a measure\ncombining both precision and recall) over the cross validation test\nsets. Finally, we tested on the remaining 10-frame final test set for\neach video sequence.\n\n\\subsection{Shadow Detection Performance}\n\nTable \\ref{tab:comparison-results} compares the shadow detection\nresults between the proposed, DNM, and NCC methods.  Our method\nachieves the top performance for shadow detection rate $\\eta$ and\n$F_1$ score in every case. We also obtain a good shadow discrimination\nrate $\\xi$ and precision in all three video\ndatasets. Figure \\ref{fig:results-for-arbitrary-frame} shows the\nresults for an arbitrary frame in each video sequence. Green pixels\nare those labeled as object pixels and red pixels are those labeled as\nshadow pixels. The results in the figure confirm that our proposed\nmethod clearly outperforms the two standard methods in all three video\ndatasets.\n\n\\begin{table}[t]\n  \\caption[Comparison of shadow detection results between the\n    proposed, DNM, and NCC methods.]{\\small Comparison of shadow\n    detection results between the proposed, DNM, and NCC methods.}\n  \\begin{center}\n    \\includegraphics[width=6.1in]{figures/tab-shadow-results}\n  \\end{center}\n  \\label{tab:comparison-results}\n\\end{table}\n\n\\begin{figure}[t]\n  \\centering\n  \\includegraphics[width=6.2in]{figures/fig-shadow-results}\n  \\caption[Results for an arbitrary frame in each video\n    sequence.]{\\small Results for an arbitrary frame in each video\n    sequence. The first column contains an example original frame for\n    each video sequence. The second column shows the ground truth for\n    that frame, where object pixels are labeled in white and shadow\n    pixels are labeled in gray. The remaining columns show shadow\n    detection results for each method, where pixels labeled as object\n    shown in green and pixels labeled as shadow are shown in red.}\n  \\label{fig:results-for-arbitrary-frame}\n\\end{figure}\n\nThe DNM method has stable performance for all three videos, with good\nperformance for all metrics. Both the DNM method and our proposed\nmethod suffer from the problem that the object colors can be confused\nwith the background color.  In the \\textit{Highway} sequence (third\nrow in Figure \\ref{fig:results-for-arbitrary-frame}), we clearly see\nthis situation. Our method detects shadows well but misclassifies some\nobject pixels as shadow, whereas DNM sometimes better discriminates\nthe shadow from the object.  However, the overall performance of our\nproposed method is superior.\n\nThe NCC method achieves the best shadow discrimination rate $\\xi$ and\nprecision. However, as can be seen in\nFigure \\ref{fig:results-for-arbitrary-frame}, this is because it\nclassifies nearly every pixel as object.  This gives NCC an advantage\nfor shadow precision and $\\xi$ but on the other two metrics, shadow\ndetection rate $\\eta$ and $F_1$ score, NCC performs extremely poorly\nin all cases.  This is due to unclear background texture inside the\nshadows, particularly on the \\textit{Highway} sequence.\n\n\\section{Discussion}\n\\label{sec:shadow-discussion}\n\nWe propose a new method for detecting shadows using a simple maximum\nlikelihood approach based on color information.  We extend the\ndeterministic nonmodel-based approach, designing a parametric\nstatistical model-based approach. Our experimental results show that\nour proposed method is extremely effective and superior to the\nstandard methods on three different real-world video surveillance data\nsets.\n\nIn some cases, our method misdetects shadow pixels due to similar\ncolor between the object and the background and unclear background\ntexture in shadow regions. Incorporating geometric or shadow region\nshape priors would potentially improve the detection and\ndiscrimination rates.\n\nIn future work, we plan to address these issues, further explore the\nfeasibility of combining our method with other useful shadow features,\nand integrate our shadow detection module with a real-world open\nsource video surveillance system \\shortcite{zoneminder}.\n\n\\FloatBarrier\n\n\n%%% Old text %%%\n\n%\\section{Introduction}\n%\n%In video surveillance applications, moving object detection and\n%tracking is an important issue.  A very common approach to detect\n%moving objects is to apply a background subtraction technique. The\n%process is basically to compare a new frame with a background\n%model. The significant differences correspond to foreground. This\n%process should ideally detect the moving objects and limit the false\n%positive as much as possible at the same time.  More importantly, it\n%should be able to avoid detection of shadows or noise. However, one\n%challenging problem arising is to identify and detect shadows. And\n%this has become an active research area in recent years.\n%\n%Shadows can cause lots of problems in the detection step while\n%segmenting and extracting features of moving objects. For example, the\n%size of detected object is larger than the real one due to the\n%misclassification of shadow as foreground.  Shadows can also merge\n%different people walking close to each other of which the output\n%becomes a single object in the background subtraction step. Shadows\n%and objects share two important information which make the problem\n%difficult. Firstly, shadows can be detected as foreground because they\n%are different from the background. Secondly, shadows have the same\n%motion as the objects casting them.\n%\n%Generally, shadows can be categorized into two classes which are self\n%and cast shadows. A self shadow occurs on the part of an object which\n%is not illuminated by light. A cast shadow is an area projected where\n%the light is occluded by an object. Figure \\ref{fig:shadow-example}\n%illustrates an example of self and cast shadow. One feature of shadows\n%is that shadow does not significantly change the color and texture of\n%the background, but only intensity. This feature is very useful since\n%it can lead to many shadow detection algorithms which will be\n%described in the next section.\n%\n%\\begin{figure}[t]\n%  \\begin{center}\n%  \\includegraphics[width=2.5in]{figures/shadow-example.png}\n%   \\caption[Self and cast shadow in a real-world scene image]{Self and\n%   cast shadow in a real-world scene image. Self shadow is on the back\n%   of the person and cast shadow in on the ground.}\n%  \\label{fig:shadow-example}\n%  \\end{center}\n%\\end{figure}\n%\n%Removing shadows can significantly improve the performance of the\n%computer vision tasks such as tracking, segmentation, and object\n%detection. Since the detection and tracking is the core of video\n%surveillance systems, poor detection and tracking can cause the\n%problems to the next processing step such as feature extraction and\n%behavior modeling. Background modeling techniques alone cannot solve\n%the problems. We need an algorithm to detect and remove shadows.\n%Therefore, in this dissertation, we explore and develop the shadow\n%detection and removal algorithms. The experiments analyze the\n%algorithms on the real-world video data.\n%\n%For the existing shadow detection\n%methods, \\shortciteA{cucchiara01shadow} and \\shortciteA{chen08shadow}\n%use the HSV color information to distinguish shadows from moving\n%objects. Their approach is based on the assumption that only the\n%intensity of the area covered by shadows will significantly change.\n%Therefore, they can detect shadows using the following equation.\n%\\[\n%  SP_t (x,y) = \\left\\{ \\begin{array}{l}\n%  1\\;\\;\\;{\\rm if}\\;\\alpha  \\le \\frac{{I_t^V (x,y)}}{{B_t^V (x,y)}} \\le \\beta\\\\ \n%  \\quad \\quad  \\wedge (I_t^S (x,y) - B_t^S (x,y)) \\le T_S  \\\\ \n%  \\quad \\quad  \\wedge \\left| {I_t^H (x,y) - B_t^H (x,y)} \\right| \\le T_H\\\\ \\\\\n%  0\\;\\;\\;{\\rm otherwise}, \\\\ \n%  \\end{array} \\right.\n%\\]\n%where $SP_t(x,y)$ is the binary mask of shadows at pixel $(x,y)$ at\n%time $t$.  $I_t^H$, $I_t^S$, $I_t^V$, $B_t^H$, $B_t^S$, and $B_t^V$\n%are H, S, V components of foreground pixel $I_t(x,y)$ and background\n%pixel $B_t(x, y)$ at pixel $(x,y)$ at time $t$, respectively. They\n%prevent the foreground pixel being classified into shadows by setting\n%two thresholds $\\alpha$ and $\\beta$.  The parameter $\\beta$ is set\n%under 1 and $\\alpha$ is set over 0. $T_S$ and $T_H$ are discovered by\n%experiments.\n%\n%\\shortciteA{tian05shadow}, \\shortciteA{jacques05shadow},\n%and \\shortciteA{tan06shadow} apply the normalized cross-correlation\n%(NCC) to detect shadows based on the assumption that the intensity of\n%shadows is proportional to the incident light ,and shadow pixels are\n%darker than background pixels, or it can be said that the shadows are\n%the scaled versions of background. Therefore, using the NCC, they can\n%identify the scaled versions of the same signal. They perform the NCC\n%on the foreground mask from the background subtraction progress. For\n%each pixel $(i, j)$ of the foreground mask, they considered a $(2N +\n%1) \\times (2N + 1)$ template $T_{ij}$, and defined $T_{ij}(n, m) =\n%I(i+n, j+m)$ for $-N \\le n \\le N$, $-N \\le m \\le N$. $B(i,j)$ is the\n%background image formed by temporal median filtering. The NCC at pixel\n%$(x,y)$ is defined as.\n%\\[\n%  NCC(i,j) = \\frac{{ER(i,j)}}{{E_B (i,j)E_{T_{ij} } }},\n%\\]\n%where\n%\\[\n%  ER(i,j) = \\sum\\limits_{n = -N}^N {\\sum\\limits_{m = -N}^N {B(i + n,j\n%  + m)T_{ij} (n,m)} },\n%\\]\n%\\[\n%  E_B (i,j) = \\sqrt {\\sum\\limits_{n = -qN}^N {\\sum\\limits_{m = -N}^N\n%  {B(i + n,j + m)^2 } } },\n%\\]\n%\\[\n%  E_{T_{ij} } = \\sqrt {\\sum\\limits_{n = -N}^N {\\sum\\limits_{m = -N}^N\n%  {T_{ij} (n,m)^2 } } }.\n%\\]\n%For a pixel in a shadow region, the NCC value should be large (close\n%to one) and the $E_{T_{ij}}$ of this region should be lower than the\n%$E_B (i,j)$.  Consequently, a pixel is classified into shadow if\n%\\[\n%  NCC(i,j) \\ge L_{NCC} \n%\\]\n%and\n%\\[\n%  E_{T_{ij} } < E_B (i,j),\n%\\]\n%where $L_{NCC}$ is a threshold. Figure \\ref{fig:tian-shadow-result}\n%shows some examples of the results from the work\n%of \\shortciteA{tian05shadow}.\n%\n%\\begin{figure}\n%  \\centering\n%  \\begin{tabular}{c}\n%    \\includegraphics[scale=0.7]{figures/tian-mog-results.png}\\\\\n%    \\includegraphics[scale=0.7]{figures/tian-shadow-results.png}\n%  \\end{tabular}\n%  \\caption[Examples of the background subtraction and shadow removal\n%  results.]{Examples of the background subtraction and shadow removal\n%  results. Upper row shows the results of the MoG background modeling\n%  and lower row shows the results from the work of Tian et\n%  al. Reprinted from the work of Tian et al.\\ (2005).}\n%  \\label{fig:tian-shadow-result}\n%\\end{figure}\n%\n%Some authors found that the blue color component increases while the\n%red color component decreases in a shadow\n%region. \\shortciteA{mikic00shadow} combine this information and\n%normalized the blue and red color components as one of their\n%features. After that, they apply a probabilistic model to classify\n%shadow pixels in traffic scenes. They also assume that the background\n%and shadow values follow a Gaussian distribution, and assume the\n%foreground values follow an uniform distribution. They iteratively\n%estimate the posterior probabilities of the pixel belonging to each\n%of the three classes: background, shadow, and foreground until one of\n%the probabilities reaches a fixed threshold. The pixel is then\n%classified into one of those classes. If none of the three\n%probabilities reaches the threshold, the pixel will be classified as\n%background.\n%\n%\\shortciteA{xu05shadow} assume that the chromaticity in a shadow\n%region should be the same as when it is illuminated. Based on the\n%information, they use a normalized chromatic color space to remove\n%shadows. In this paper, they normalize the red and green color\n%components. Then they define a set of thresholds for brightness and\n%color distortion to classify a pixel value into foreground, highlight,\n%or shadow.\n%\n%\\shortciteA{hong03background} mention that there are both\n%chromaticity and brightness in each pixel value in the RGB space. They\n%remove the lightness by using the normalized RGB color space since the\n%normalized RGB color space contains only the chromaticity. Thus, they\n%use this information to propose their background subtraction\n%approach. \\shortciteA{havasi06geometric} illustrate that the color\n%based method works well in case of weak shadow, but strong\n%shadow. Hence, they integrate the geometric information into the\n%detection process and came up with an iterative Bayesian framework\n%which combines both the color and geometric information to improve the\n%detection results.\n%\n%\\section{Methodology}\n%\n%We use NCC and the maximum likelihood based on the HSV color\n%information extracted from a set of training images to remove shadows.\n%\n%We compute the difference of hue $H_{\\text{diff}}$, saturation\n%$S_{\\text{diff}}$, and value $V_{\\text{diff}}$ components under the\n%mask between the current and background frames. We simply calculate\n%the probability as follows.\n%\n%\\begin{equation*}\n%  \\begin{array}{ccl}\n%    P(M_{\\text{xy}} \\mid A_{\\text{xy}} = \\text{sh}) \n%            & = & P(H_{\\text{diff}}^{\\text{sh}} \\mid A_{\\text{xy}} = \\text{sh})\n%                  P(S_{\\text{diff}}^{\\text{sh}} \\mid A_{\\text{xy}} = \\text{sh}) \\\\\n%            &   & P(V_{\\text{diff}}^{\\text{sh}} \\mid A_{\\text{xy}} = \\text{sh}),\n%  \\end{array}\n%\\end{equation*}\n%where $M_{xy}$ is a measurement at pixel $(x,y)$. To make the problem\n%simple, we assume that the distribution of the difference of hue,\n%saturation, and value components follows a normal distribution as\n%follows.\n%\\begin{equation*}\n%  P(H_{\\text{diff}}^{\\text{sh}} \\mid A_{\\text{xy}} = \\text{sh}) \\sim {\\cal\n%    N}(H_{\\text{diff}}^{\\text{sh}} ; 0, \\sigma^2_{h_{\\text{diff}}^{\\text{sh}}}),\n%\\end{equation*}\n%\n%\\begin{equation*}\n%  P(S_{\\text{diff}}^{\\text{sh}} \\mid A_{\\text{xy}} = \\text{sh}) \\sim {\\cal\n%    N}(S_{\\text{diff}}^{\\text{sh}} ; 0, \\sigma^2_{s_{\\text{diff}}^{\\text{sh}}}),\n%\\end{equation*}\n%and\n%\\begin{equation*}\n%  P(V_{\\text{diff}}^{\\text{sh}} \\mid A_{\\text{xy}} = \\text{sh}) \\sim {\\cal\n%    N}(V_{\\text{diff}}^{\\text{sh}} ; 0, \\sigma^2_{v_{\\text{diff}}^{\\text{sh}}}).\n%\\end{equation*}\n%\n%\\noindent Similarly, the measurement given the foreground assignment\n%can be computed as follows.\n%\n%\\begin{equation*}\n%  \\begin{array}{ccl}\n%    P(M_{\\text{xy}} \\mid A_{\\text{xy}} = \\text{fg}) \n%            & = & P(H_{\\text{diff}}^{\\text{fg}} \\mid A_{\\text{xy}} = \\text{fg})\n%                  P(S_{\\text{diff}}^{\\text{fg}} \\mid A_{\\text{xy}} = \\text{fg}) \\\\\n%            &   & P(V_{\\text{diff}}^{\\text{fg}} \\mid A_{\\text{xy}} = \\text{fg})\n%  \\end{array}\n%\\end{equation*}\n%\n%\\noindent Each component is defined as follows.\n%\n%\\begin{equation*}\n%  P(H_{\\text{diff}}^{\\text{fg}} \\mid A_{\\text{xy}} = \\text{fg}) \\sim {\\cal\n%    N}(H_{\\text{diff}}^{\\text{fg}} ; 0, \\sigma^2_{h_{\\text{diff}}^{\\text{fg}}}),\n%\\end{equation*}\n%\n%\\begin{equation*}\n%  P(S_{\\text{diff}}^{\\text{fg}} \\mid A_{\\text{xy}} = \\text{fg}) \\sim {\\cal\n%    N}(S_{\\text{diff}}^{\\text{fg}} ; 0, \\sigma^2_{s_{\\text{diff}}^{\\text{fg}}}),\n%\\end{equation*}\n%and\n%\\begin{equation*}\n%  P(V_{\\text{diff}}^{\\text{fg}} \\mid A_{\\text{xy}} = \\text{fg}) \\sim {\\cal\n%    N}(V_{\\text{diff}}^{\\text{fg}} ; 0, \\sigma^2_{v_{\\text{diff}}^{\\text{fg}}}).\n%\\end{equation*}\n%\n%Finally, we use the maximum likelihood approach to classify a pixel\n%whether it is foreground or shadow.\n%\n%\\section{Experimental Results}\n%\n%To collect data, we used ZoneMinder \\shortcite{zoneminder} to capture\n%video during two weeks. We set up a machine with a Web camera on the\n%second floor in the Computer Science and Information Management (CSIM)\n%building to capture activities in the scene.\n%\n%We have experimented with a shadow detection method using normalized\n%cross correlation (NCC).  We compute the grayscale correlation between\n%the foreground pixels and a background image constructed as the mean\n%over each mixture of Gaussian distribution. Any foreground pixels\n%whose NCC with the background are above some threshold\n%$L_{\\text{NCC}}$ are removed. In the experiments, we set\n%$L_{\\text{NCC}} = 0.995$. The results are shown in\n%Figure \\ref{fig:shadow-outdoor-result}. NCC works well in the outdoor\n%scenes with visible background texture inside shadows. However, when\n%we applied it in the indoor scenes, it does not work very well in many\n%cases due to the lighting effect as shown in\n%Figure \\ref{fig:shadow-poor-result}.\n%\n%\\begin{figure}[t]\n%  \\centering\n%  \\begin{tabular}{ccc}\n%    \\includegraphics[width=0.28\\linewidth]{figures/shadow-result01.png} &\n%    \\includegraphics[width=0.28\\linewidth]{figures/shadow-result02.png} &\n%    \\includegraphics[width=0.28\\linewidth]{figures/shadow-result03.png}\n%    \\\\\n%    (a) & (b) & (c)\n%    \\end{tabular}\n%  \\caption{Sample foreground extraction and shadow removal results in\n%    an outdoor scene.  (a) Original image. (b) Foreground pixels\n%    according to background model.  (c) Foreground pixels after shadow\n%    removal.}\n%  \\label{fig:shadow-outdoor-result}\n%\\end{figure}\n%\n%\\begin{figure}[t]\n%  \\centering\n%  \\begin{tabular}{ccc}\n%    \\includegraphics[width=0.28\\linewidth]{figures/shadow-poor-result01.png} &\n%    \\includegraphics[width=0.28\\linewidth]{figures/shadow-poor-result02.png} &\n%    \\includegraphics[width=0.28\\linewidth]{figures/shadow-poor-result03.png}\n%    \\\\\n%    (a) & (b) & (c)\n%  \\end{tabular}\n%  \\caption{Sample poor shadow removal results in an indoor scene.  (a)\n%    Original image. (b) Foreground pixels according to background\n%    model.  (c) Foreground pixels after shadow removal. Red pixels\n%    show the positives, and green pixels show the negatives.}\n%  \\label{fig:shadow-poor-result}\n%\\end{figure}\n%\n%We have performed another experiment using a maximum likelihood\n%approach on the HSV color space. We first compute the difference of\n%hue, saturation, and value under the mask of the current and\n%background frames from a set of training images. The distributions of\n%those values under the foreground mask are shown in\n%Figure \\ref{fig:foreground-distribution}, and the distributions under\n%the shadow mask are shown in Figure\n%\\ref{fig:shadow-distribution}. For the hue and saturation values, we\n%subtracted the current frame by the background frame, but for the\n%intensity value, to get the positive values, we subtracted the\n%background frame by the current frame.\n%\n%\\begin{figure}[t]\n%  \\centering\n%  \\subfloat[]{\\includegraphics[width=0.32\\linewidth]{figures/foreground_diff_h.png}}\n%  \\hspace{0.05in}\n%  \\subfloat[]{\\includegraphics[width=0.32\\linewidth]{figures/foreground_diff_s.png}}\n%  \\hspace{0.05in}\n%  \\subfloat[]{\\includegraphics[width=0.32\\linewidth]{figures/foreground_diff_v.png}}\n%  \\caption{Distribution of the difference of hue, saturation, and\n%    value under the foreground mask. (a) Difference of hue.(b)\n%    Difference of saturation. (c) Difference of value.}\n%  \\label{fig:foreground-distribution}\n%\\end{figure}\n%\n%\\begin{figure}[t]\n%  \\centering\n%  \\subfloat[]{\\includegraphics[width=0.32\\linewidth]{figures/shadow_diff_h.png}}\n%  \\hspace{0.05in}\n%  \\subfloat[]{\\includegraphics[width=0.32\\linewidth]{figures/shadow_diff_s.png}}\n%  \\hspace{0.05in}\n%  \\subfloat[]{\\includegraphics[width=0.32\\linewidth]{figures/shadow_diff_v.png}}\n%  \\caption{Distribution of the difference of hue, saturation, and\n%    value under the shadow mask. (a) Difference of hue. (b) Difference\n%    of saturation. (c) Difference of value.}\n%  \\label{fig:shadow-distribution}\n%\\end{figure}\n%\n%The results for the maximum likelihood approach compared to the NCC\n%approach are shown in Figure \\ref{fig:comparison-shadow-results}.\n%\n%\\begin{figure}[t]\n%  \\centering\n%  \\begin{tabular}{cccc}\n%    \\includegraphics[width=0.22\\linewidth]{figures/shadow-original.png} &\n%    \\includegraphics[width=0.22\\linewidth]{figures/shadow-bg-results.png} &\n%    \\includegraphics[width=0.22\\linewidth]{figures/shadow-ncc-results.png} &\n%    \\includegraphics[width=0.22\\linewidth]{figures/shadow-ml-results.png}\n%    \\\\\n%    (a) & (b) & (c) & (d)\n%    \\end{tabular}\n%  \\caption{Shadow removal results in an indoor scene.  (a) Original\n%    image. (b) Foreground pixels according to background model. (c)\n%    Shadow detection using NCC.  (d) Shadow detection using the\n%    maximum likelihood approach.}\n%  \\label{fig:comparison-shadow-results}\n%\\end{figure}\n%\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "5333fc15b6af359b1c45613f011f901c7dc396a7", "size": 41853, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "first-revision/shadow.tex", "max_stars_repo_name": "zkan/dissertation", "max_stars_repo_head_hexsha": "458c5fce241973008bdcc3958bdf962b9197e593", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "first-revision/shadow.tex", "max_issues_repo_name": "zkan/dissertation", "max_issues_repo_head_hexsha": "458c5fce241973008bdcc3958bdf962b9197e593", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "first-revision/shadow.tex", "max_forks_repo_name": "zkan/dissertation", "max_forks_repo_head_hexsha": "458c5fce241973008bdcc3958bdf962b9197e593", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.4517203108, "max_line_length": 85, "alphanum_fraction": 0.7445105488, "num_tokens": 11295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.3133126119911768}}
{"text": "%!TEX root = ../thesis.tex\n%*******************************************************************************\n%****************************** Third Chapter **********************************\n%*******************************************************************************\n\\chapter{Bispectrum and Primordial Non-Gaussianity}\n\n% **************************** Define Graphics Path **************************\n\\ifpdf\n    \\graphicspath{{Chapter3/Figs/Raster/}{Chapter3/Figs/PDF/}{Chapter3/Figs/}}\n\\else\n    \\graphicspath{{Chapter3/Figs/Vector/}{Chapter3/Figs/}}\n\\fi\n\nThe primordial perturbations are consistent with being Gaussian distributed according to observations to date \\cite{PlanckCollaboration2018}. The statistical properties of a Gaussian random field are completely characterised by its mean and covariance functions. The latter is directly related to the CMB angular power spectrum since the CMB is a near-linear probe of the early universe. In fact, the power spectrum is a sufficient statistic in the perfect Gaussian limit, which means that it contains all the information about the distribution of the primordial perturbations we may ever extract from the CMB. The inverse is also true however; if the initial perturbations were non-Gaussian, it is essential to go beyond the power spectra and study higher-order statistics. Such non-Gaussian contributions are best captured in the three-point correlation functions, or their Fourier counterpart, the bispectrum.\n\nIn single field slow-roll inflation with standard kinetic term and vacuum, the primordial bispectrum is suppressed by slow-roll parameters \\cite{Maldacena2013}. However, numerous other inflationary scenarios that are physically well-motivated violate these simple assumptions and hence predict non-Gaussian signatures. They are expected to leave imprints on the CMB bispectrum with characteristic shape and amplitude, where the latter is parametrised by $f_{NL}$.\n\nWe discuss the bispectrum in relation to primordial non-Gaussianity in this section, from both theoretical and observational side. Section \\ref{section:bispectrum} covers the basic formalism of bispectrum analysis. Section \\ref{section:primordial_non_Gaussianity} then introduces theoretical tools for calculating the primordial bispectrum from a given inflation model Lagrangian. On the CMB side, we formulate the optimal bispectrum estimator and existing implementations of it in Section \\ref{section:CMB_bispectrum_estimation}.\n\n\n\\section{Bispectrum} \\label{section:bispectrum}\n\nConsider the three-point correlation function $\\left< \\zeta(\\vv{x}_1) \\zeta(\\vv{x}_2) \\zeta(\\vv{x}_3) \\right>$  of the curvature perturbation $\\zeta$ at the end of inflation. Its Fourier transform is given by\n\\begin{align}\n\t\\left< \\zeta(\\vv{k}_1) \\zeta(\\vv{k}_2) \\zeta(\\vv{k}_3) \\right> = \\int d^3\\vv{x}_1 d^3\\vv{x}_2 d^3\\vv{x}_3 \\; e^{-i(\\vv{k}_1 \\cdot \\vv{x}_1 + \\vv{k}_2 \\cdot \\vv{x}_2 + \\vv{k}_3 \\cdot \\vv{x}_3 )} \\left< \\zeta(\\vv{x}_1) \\zeta(\\vv{x}_2) \\zeta(\\vv{x}_3) \\right>. \\label{eqn:bispectrum_from_fourier_derivation_1}\n\\end{align}\nAssuming that the universe is statistically homogeneous, these correlation functions are invariant under arbitrary spatial translation $\\vv{x} \\rightarrow \\vv{x}' = \\vv{x} + \\vv{c}$. In particular, we have \\\\${\\left< \\zeta(\\vv{x}_1) \\zeta(\\vv{x}_2) \\zeta(\\vv{x}_3) \\right> = \\left< \\zeta(\\vv{x}_1 - \\vv{x}_3) \\zeta(\\vv{x}_2 - \\vv{x}_3) \\zeta(\\vv{0}) \\right>}$. Relabelling the integration variables so that $\\vv{x}'_1=\\vv{x}_1-\\vv{x}_3$ and $\\vv{x}'_2=\\vv{x}_2-\\vv{x}_3$, \\eqref{eqn:bispectrum_from_fourier_derivation_1} becomes\n\\begin{align}\n\t&\\int d^3\\vv{x}'_1 d^3\\vv{x}'_2 d^3\\vv{x}_3 \\; e^{-i[ \\vv{k}_1 \\cdot (\\vv{x}'_1 + \\vv{x}_3) + \\vv{k}_2 \\cdot (\\vv{x}'_2 + \\vv{x}_3) + \\vv{k}_3 \\cdot \\vv{x}_3 ]} \\left< \\zeta(\\vv{x}'_1) \\zeta(\\vv{x}'_2) \\zeta(\\vv{0}) \\right> \\nonumber \\\\\n\t&\\hspace{0.05\\textwidth} = (2\\pi)^3 \\delta^{(3)}(\\vv{k}_1 + \\vv{k}_2 + \\vv{k}_3) \\int d^3\\vv{x}'_1 d^3\\vv{x}'_2 \\; e^{-i( \\vv{k}_1 \\cdot \\vv{x}'_1 + \\vv{k}_2 \\cdot \\vv{x}'_2)} \\left< \\zeta(\\vv{x}'_1) \\zeta(\\vv{x}'_2) \\zeta(\\vv{0}) \\right> \\label{eqn:bispectrum_from_fourier_derivation_2}\\\\\n\t&\\hspace{0.05\\textwidth} =: (2\\pi)^3 \\delta^{(3)}(\\vv{k}_1 + \\vv{k}_2 + \\vv{k}_3) \\; B(\\vv{k_1}, \\vv{k_2}), \\label{eqn:bispectrum_from_fourier_derivation_3}\n\\end{align}\nwhere we defined $B(\\vv{k_1}, \\vv{k_2})$ to be the integral expression appearing in \\eqref{eqn:bispectrum_from_fourier_derivation_2}. The delta function enforces $\\vv{k}_1 + \\vv{k}_2 + \\vv{k}_3 = \\vv{0}$ which corresponds to the conservation of momentum.\n\nAssuming further that the universe is statistically isotropic, the correlators remain constant under rotations $\\vv{x} \\rightarrow \\vv{x}' = R \\vv{x}$ for any orthogonal matrix $R$. It is straightforward to see that $B(\\vv{k}_1,\\vv{k}_2)$ remains invariant under rotations as well;\n\\begin{align}\n\tB(R\\vv{k}_1, R\\vv{k}_2) &= \\int d^3\\vv{x}'_1 d^3\\vv{x}'_2 \\; e^{-i[ (R\\vv{k}_1) \\cdot \\vv{x}'_1 + (R\\vv{k}_2) \\cdot \\vv{x}'_2]} \\left< \\zeta(\\vv{x}'_1) \\zeta(\\vv{x}'_2) \\zeta(\\vv{0}) \\right> \\\\\n\t&= \\int d^3\\vv{x}''_1 d^3\\vv{x}''_2 \\; e^{-i( \\vv{k}_1 \\cdot \\vv{x}''_1 + \\vv{k}_2 \\cdot \\vv{x}''_2)} \\left< \\zeta(R \\vv{x}''_1) \\zeta(R \\vv{x}''_2) \\zeta(\\vv{0}) \\right> \\;\\;= B(\\vv{k}_1, \\vv{k}_2),\n\\end{align}\nwhere we have used the fact that $R^T=R^{-1}$. We may therefore fix $\\vv{k}_1$ to be aligned with the $z$-axis, for example, and rotate further to have $\\vv{k}_2$ lie on the $xz$ plane. $B$ then depends only on three variables: two lengths $k_1$, $k_2$ and the angle between the two given by $\\vv{k}_1 \\cdot \\vv{k}_2 / (k_1 k_2)$. Since $\\| \\vv{k_3} \\|^2 = \\| \\vv{k}_1+\\vv{k}_2 \\|^2 = k_1^2 + k_2^2 + 2(\\vv{k_1}\\cdot\\vv{k_2})$, the angle can be replaced by $k_3$. Putting everything together, we obtain\n\\begin{align}\n\t\\left< \\zeta(\\vv{k}_1) \\zeta(\\vv{k}_2) \\zeta(\\vv{k}_3) \\right> =  (2\\pi)^3 \\delta^{(3)}(\\vv{k}_1 + \\vv{k}_2 + \\vv{k}_3) \\; B(k_1, k_2, k_3).\n\\end{align}\nNote that the bispectrum $B(k_1,k_2,k_3)$ is a three-dimensional function, as opposed to the one-dimensional power spectrum $P(k)$. The domain of $B$ is further restricted by the constraint given by the delta function; $k_1,k_2$, and $k_3$ must form three sides of a triangle.\n\nThe functional form of the bispectrum comprises two parts: its dependence on the overall scaling $K=k_1+k_2+k_3$, called \\textit{running}, and the \\textit{shape} of the triangle formed by $k_1$,$k_2$ and $k_3$. Some notable shapes are depicted in Figure \\ref{fig:triangle_configurations}.\n\n\\begin{figure}\n\t\\centering\n\t\\includegraphics[width=0.8\\textwidth]{triangle_configurations.pdf}\n\t\\hspace{10pt}\n\t\\caption{Three notable triangle configurations for the bispectrum $B(k_1,k_2,k_3)$.}\n\t\\label{fig:triangle_configurations}\n\\end{figure}\n\nThe squeezed, equilateral and flattened limits of bispectra all have distinct physical meaning. For example, the squeezed limit corresponds to a configuration with two small-scale (large $k$) modes and one large-scale (small $k$) mode. Heuristically, this relates to how the small scale covariances are affected by an encompassing large scale mode.\n\nOne of the most studied bispectrum shapes comes from the \\textit{local} model. In this model, the perturbative field $\\zeta(\\vv{x})$ is expanded as a local function of some Gaussian field $\\zeta_G(\\vv{x})$ as\n\\begin{align}\n\t\\zeta(\\vv{x}) = \\zeta_G(\\vv{x}) + \\frac{3}{5} f_{NL} \\left(\\zeta_G^2(\\vv{x}) - \\left< \\zeta_G^2 \\right> \\right) + \\cdots. \\label{eqn:local_model_fNL_defitintion}\n\\end{align}\nThe non-linearity parameter $f_{NL}$ measures the amplitude of quadratic contributions to the field. A factor of $(3/5)$ here is conventional; the original definition of $f_{NL}$ was written in terms of the potential $\\Phi$, which is equal to $(3/5)\\zeta$ on super-horizon scales.\n\nSubstituting this form into \\eqref{eqn:bispectrum_from_fourier_derivation_1} gives an expression involving correlation functions of four Gaussian fields, to leading order in $f_{NL}$. Isserlis' theorem allows us to write such four-point correlators in terms of the sum over all possible contractions:\n\\begin{align}\n\t\\left< \\zeta_G(\\vv{x}_1)^2 \\zeta_G(\\vv{x}_2) \\zeta_G(\\vv{x}_3) \\right> = &\\left< \\zeta_G(\\vv{x}_1)^2 \\right> \\left< \\zeta_G(\\vv{x}_2) \\zeta_G(\\vv{x}_3) \\right> + \\left< \\zeta_G(\\vv{x}_1) \\zeta_G(\\vv{x}_2) \\right> \\left< \\zeta_G(\\vv{x}_1) \\zeta_G(\\vv{x}_3) \\right> \\nonumber \\\\ &\\hspace{0.15\\textwidth} + \\left< \\zeta_G(\\vv{x}_1) \\zeta_G(\\vv{x}_3) \\right> \\left< \\zeta_G(\\vv{x}_1) \\zeta_G(\\vv{x}_2) \\right>. \\label{eqn:local_model_derivation_1}\n\\end{align}\nContributions from the first term in \\eqref{eqn:local_model_derivation_1} cancel out with the ones coming from $\\left< \\zeta_G^2 \\right>$ in the definition \\eqref{eqn:local_model_fNL_defitintion}. After expressing the two-point correlations in terms of the power spectrum in Fourier space, we obtain the \\textit{local} bispectrum;\n\\begin{align}\n\tB(k_1, k_2, k_3) = \\frac{3}{5} f_{NL} \\left[ 2P_\\zeta(k_2) P_\\zeta(k_3) + 2P_\\zeta(k_3) P_\\zeta(k_1) + 2P_\\zeta(k_1) P_\\zeta(k_2) \\right]. \\label{eqn:local_bispectrum_using_power_spectrum}\n\\end{align}\n\nDue to this fact, it is common in literature (e.g. \\cite{Burrage2011large}) to define `the reduced bispectrum' $f_{NL}$ to be $f_{NL} := 5B(k_1,k_2,k_3) / 6(P(k_1)P(k_2) + P(k_2)P(k_3) + P(k_3)P(k_1))$. $f_{NL}$ is then a three-dimensional function in general. This can potentially be confusing due to a conflicting convention in the observational community where $f_{NL}$ represents a constant parameter measuring the amplitude of a specific bispectrum shape.\n\nIn this thesis we follow the latter convention and associate one $f_{NL}$ with each of the bispectrum shapes. For example, $f_{NL}$ in \\eqref{eqn:local_bispectrum_using_power_spectrum} is denoted $f_{NL}^{local}$, tied to the local shape. Connection between the theoretical predictions and observations is often made using analytic but approximate templates for the bispectrum.\n\nWe parametrise the power spectrum as $P_\\zeta(k) = A_\\zeta k^{n_s-4}$ using the power spectrum amplitude $A_\\zeta$ and scalar spectral index $n_s$. The local template is then given by\n\\begin{align}\n\tB_\\zeta^{local} (k_1, k_2, k_3) := 2A_\\zeta^2 \\left[ \\frac{1}{k_1^{4-n_s} k_2^{4-n_s}} + \\text{\\;2 cyc.} \\right]. \\label{def:local_template} \n\\end{align}\nNote that we do not include $f_{NL}^{local}$ in our definition of the template either; it is set to $1$.\n\nThe primordial bispectrum from multi-field inflation models typically falls into this category (reviewed in e.g., \\cite{Byrnes2010review}). The local shape peaks in the squeezed limit where ${k_1 \\approx k_2 \\gg k_3}$, diverging as $k_3\\rightarrow0$. General single field models, on the other hand, are better described by the equilateral and orthogonal templates \\cite{Creminelli2006limits,Senatore2010orthogonal}:\n\\begin{align}\n\tB_\\zeta^{equil} (k_1, k_2, k_3) &:= 6A_\\zeta^2 \\left[ -\\left( \\frac{1}{k_1^{4-n_s} k_2^{4-n_s}} + \\text{2 cyc.} \\right) -\\frac{2}{(k_1 k_2 k_3)^{2(4-n_s)/3}} \\right.\\nonumber\\\\\n\t&\\hspace{0.2\\textwidth} + \\left. \\left( \\frac{1}{k_1^{(4-n_s)/3} k_2^{2(4-n_s)/3} k_3^{(4-n_s)}} + \\text{5 cyc.} \\right) \\right], \\label{def:equilateral_template} \\\\\n\tB_\\zeta^{ortho} (k_1, k_2, k_3) &:= 6A_\\zeta^2 \\left[ -3\\left( \\frac{1}{k_1^{4-n_s} k_2^{4-n_s}} + \\text{ 2 cyc.} \\right) -\\frac{8}{(k_1 k_2 k_3)^{2(4-n_s)/3}} \\right.\\nonumber\\\\\n\t&\\hspace{0.2\\textwidth} + \\left. 3\\left( \\frac{1}{k_1^{(4-n_s)/3} k_2^{2(4-n_s)/3} k_3^{(4-n_s)}} + \\text{5 cyc.} \\right) \\right]. \\label{def:orthogonal_template} \n\\end{align}\nThe equilateral and orthogonal shapes are peaked at the equilateral and flattened limits shown in Figure \\ref{fig:triangle_configurations}, respectively. The latter was constructed explicitly to probe bispectrum shapes perpendicular to the equilateral shape.\n\n\\section{Primordial non-Gaussianity} \\label{section:primordial_non_Gaussianity}\n\nPreviously in Section \\ref{section:quantum_fluctuations}, we derived the power spectrum of perturbations in the inflation field assuming a homogeneous background. This section outlines how to compute cosmological correlation functions from single field inflation in general.\n\nWe introduce the necessary tools in Section \\ref{section:in_in_formalism} and \\ref{section:ADM_formalism}. The bispectrum from a general type of single field inflation is derived in Section \\ref{section:bispectrum_from_single_field_inflation}. We focus on illustrating the framework without delving too much into the technical details. A simple example is used to demonstrate how explicit calculations are done, while we refer to, e.g., \\cite{Maldacena2013,Chen2010review,Burrage2011large} for the full (and laborious) calculations.\n\n\\subsection{ADM formalism} \\label{section:ADM_formalism}\n\nIn order to study the perturbed metric in the presence of one or more inflation fields, it is convenient to use the Arnowitt-Deser-Misner (ADM) formalism \\cite{Arnowitt2008ADMrepublication}:\n\\begin{align}\n\tds^2 = -N dt^2 + h_{ij}(dx^i + N^i dt) (dx^j + N^j dt),\n\\end{align}\nwhere the lapse and shift functions $N$ and $N^i$, respectively, are non-dynamical variables of the action. They act as Lagrange multipliers and provide constraint equations. We focus on the scalar perturbations here and ignore vector and tensor modes, since they evolve independently owing to the SVT theorem. The spatial metric $h_{ij}$ contains two scalar degrees of freedom. When inflation is driven by a single scalar field, there is one extra scalar mode from perturbations of the field. Out of the three dynamical scalar degrees of freedom, two can be fixed by a gauge choice as we saw in \\ref{section:metric_perturbations}. Here we choose the gauge so that the inflation field is uniform. The spatial metric takes the form\n\\begin{align}\n\th_{ij} = a(t)^2 \\;e^{2\\zeta} \\; \\delta_{ij},  \\label{eqn:spatial_metric_curvature_perturbation}\n\\end{align}\nwhere $\\zeta(\\vv{x},t)$ is equivalent to the curvature perturbation we defined earlier in \\eqref{def:curvature_perturbation}. Note that, if we define $N(t) = \\int^{t}_{t_0} H dt' = \\ln a(t) - \\ln a(t_0)$ (not to be confused with the lapse function $N$) to represent the number of $e$-folds of expansion between time $t$ and $t_0$, then $\\zeta = \\delta N$. \\footnote{To be precise, $\\delta N$ is defined as in \\eqref{eqn:local_clock_time_fluctuation} with $f=N$. We have $\\zeta(t,\\vv{x})= \\delta N = N(t+\\delta t) - N(t)$, where $\\delta t(t,\\vv{x})$ represents the perturbations in the inflationary `clock time' at the given spatial position $\\vv{x}$.}\n\t\nWe now write down the action. Compared to \\eqref{eqn:real_scalar_field_action}, the Einstein-Hilbert term is added since the metric is no longer fixed. We consider a generalised form of the field Lagrangian with the action given by\n\\begin{align}\n\tS = \\int dt d^3 \\vv{x} \\; \\sqrt{-g} \\left[ \\frac{M_p}{2} R + P(X,\\phi) \\right],  \\label{eqn:general_single_field_action}\n\\end{align}\nwhere $M_p := (8\\pi G)^{-1/2}$ is the reduced Planck mass and $X:=-\\frac{1}{2} g^{\\mu\\nu} \\partial_\\mu \\phi \\partial_\\nu \\phi$ is the canonical kinetic term. We set $M_p=1$ for convenience. $P(X,\\phi)$ is an arbitrary function which generalises $X-V(\\phi)$ of the standard slow-roll inflation \\cite{Chen2007b}.\n\nOne notable consequence of the non-trivial kinetic term $P$ is that fluctuations in the inflation field no longer necessarily propagate with speed of light. The sound speed, defined as the ratio $\\delta P / \\delta \\rho$, in these models is given by\n\\begin{align}\n\tc_s^2 = \\frac{P_{,X}}{P_{,X} + 2 X P_{,XX}}, \\label{eqn:general_single_field_sound_speed}\n\\end{align}\nwhere the subscript `$,X$' represents taking a partial derivative with respect to $X$.\n\nIn the ADM formalism, \\eqref{eqn:general_single_field_action} becomes\n\\begin{align}\n\tS = \\frac{1}{2}\\int dt d^3 \\vv{x} \\; \\sqrt{h} \\; N \\left[ R^{(3)} + 2P(X,\\phi) \\right] + \\frac{1}{2} \\int dt d^3 \\vv{x} \\; \\sqrt{h} \\; N^{-1} \\left[ E_{ij} E^{ij} - E^2 \\right],\n\\end{align}\nwhere the $R^{(3)}$ is the three-dimensional Ricci scalar of $h_{ij}$, and\n\\begin{align}\n\tE_{ij} := \\frac{1}{2} \\left( \\dot{h}_{ij} - \\nabla_i N_j - \\nabla_j N_i \\right), \\hspace{0.05\\textwidth}\n\tE := E_{ij} h^{ij}.\n\\end{align}\nThe spatial indices $i,j$ are lowered and raised by $h_{ij}$.\n\nIn order to obtain an action for $\\zeta$, we substitute \\eqref{eqn:spatial_metric_curvature_perturbation} into the expression and expand perturbatively in $\\zeta$. We keep terms of order up to three as they are all that is relevant for three-point correlation functions. It is sufficient to evaluate $N$ and $N_i$ to first order in $\\zeta$ since they multiply with constraint equations which vanish up to first order.\n\nThe quadratic part of the action is given by\n\\begin{align}\n\tS_2 = \\int dt d^3\\vv{x} \\; \\left[ \\frac{\\epsilon}{c_s^2} a^3 \\dot{\\zeta}^2 - \\epsilon a(\\partial\\zeta)^2  \\right], \\label{eqn:quadratic_action_in_zeta}\n\\end{align}\nwhere the slow roll parameter $\\epsilon=-\\dot{H}/H^2$ has made a reappearance. Here, $(\\partial\\zeta)^2$ is a shorthand for $\\partial_i \\zeta \\partial^i \\zeta$ which involves the spatial derivatives of $\\zeta$. Note that there are no terms proportional to $\\zeta^2$ in the quadratic action, meaning that $\\zeta$ is massless even without the slow-roll assumptions.\n\nThe third order action contains many terms with varying amounts of contributions to the bispectrum. We write only one particular term here for an example calculation which will be shown later. The full result can be found in \\cite{Chen2007b}. \n\\begin{align}\n\tS_3 \\supset \\int d\\tau d^3\\vv{x} \\; a^3 \\left[ -\\frac{\\epsilon}{H c_s^2} \\left( 1 - \\frac{1}{c_s^2} \\right) + \\frac{2\\lambda c_s^2}{H^2 \\epsilon} \\right] \\dot{\\zeta}^3.\t \\label{eqn:cubic_action_example_term}\n\\end{align}\n\n\\subsection{In-in formalism} \\label{section:in_in_formalism}\n\nWe need to calculate the Hamiltonian from the action in order to quantise the field. When only the quadratic part \\eqref{eqn:quadratic_action_in_zeta} is considered, the corresponding Hamiltonian, say $H_0$, is also quadratic in $\\zeta$ and its conjugate momentum $\\pi := \\partial\\Lagr/\\partial(\\dot{\\zeta})$. $H_0$ describes the free theory in which the equations of motion are linear and we can find the mode functions that solve them, as we did in Section \\ref{section:quantum_fluctuations}. Meanwhile, third-order and higher terms in the action such as \\eqref{eqn:cubic_action_example_term} appear in the Hamiltonian as couplings that contribute to the correlation functions. Denoting these `interacting' terms as $H_{int}$, the total Hamiltonian for the perturbations takes the form\n\\begin{align}\n\tH = H_0 + H_{int}. \\label{eqn:interaction_picture_hamiltonian}\n\\end{align}\n\nThere are multiple formalisms in quantum mechanics regarding time evolution of the operators and states. In the Schr\\\"odinger picture, the states evolve in time according to the Hamiltonian, while the operators remain fixed over time. On the other hand, the Heisenberg picture has the operators varying in time and the states constant. Yet another alternative is the interaction picture where the Hamiltonian \\eqref{eqn:interaction_picture_hamiltonian} is split into two parts, responsible for the time evolution of the states and the operators, respectively. All three pictures are physically equivalent; all the correlation function values are identical between them.\n\nWe choose to work in the interaction picture where the operators and states evolve in time through $H_0$ and $H_{int}$, respectively. The main advantage of this formalism is that we can use the results from the free ($H=H_0$) theory to evolve operators in time. In particular, we may canonically quantise the field $\\hat{\\zeta}(\\vv{x},t)$ using its Fourier transform;\n\\begin{align}\n\t\\hat{\\zeta}_\\vv{k} (t) = u_k(t) \\; \\hat{a}_\\vv{k} + u_k^*(t) \\; \\hat{a}_{-\\vv{k}}^\\dagger, \\label{eqn:zeta_canonical_quantisation}\n\t% \\\\ \\hat{\\pi}_\\vv{k} (t) = \\dot{u}_k(t) \\; \\hat{a}_\\vv{k} + \\dot{u}_k^*(t) \\; \\hat{a}_{-\\vv{k}}^\\dagger \n\\end{align} \nwhere the mode functions $u_k(\\tau)$ satisfy the equations of motion from the quadratic action \\eqref{eqn:quadratic_action_in_zeta} related to $H_0$, which we can solve analytically. Note that $u_k(\\tau)$ depends only on $k=\\|\\vv{k}\\|$ because the spatial derivatives enter through $(\\partial\\zeta)^2$ only. The annihilation and creation operators $\\hat{a}_\\vv{k}$ and $\\hat{a}_{-\\vv{k}}^\\dagger$ satisfy the usual commutation relations: $[\\hat{a}_{\\vv{k}_1},\\hat{a}_{\\vv{k}_2}^\\dagger] = (2\\pi)^3 \\delta^{(3)}(\\vv{k}_1-\\vv{k}_2)$.\n\nMeanwhile, all the information about the interactions is captured in the time evolution operator $\\hat{U_I}(t,t_0) = T\\exp \\left(-i\\int_{t_0}^t H_I(t')dt'\\right)$, where $H_I$ denotes $H_{int}$ in the interaction picture. The time-ordering operator $T$ arranges the operators so that the ones evaluated at earlier times appear on the right. The states at time $t$ are given by $|\\psi_I(t)\\rangle = U_I(t,t_0) |\\psi_I(t_0)\\rangle$.\n\nThe in-in formalism (\\cite{Schwinger1961inin,Jordan1986inincosmo1,Calzetta1987inincosmo2}) allows us to calculate correlation functions at a given time $t$ using two `in' states: two copies of the vacuum at infinite past in our case. For some local operator $Q(t)$ written as a product of $\\hat{\\zeta}(\\vv{x},t)$ and $\\hat{\\pi}(\\vv{x},t)$, we define its expected value as follows;\n\\begin{align}\n\t\\left< Q(t) \\right> &:= \\langle in |\\;Q(t)\\;| in \\rangle \\nonumber\\\\ &=  \\langle\\vv{0}| \\left[ \\bar{T} \\exp \\left( i \\int_{t_0}^{t} H_I(t')dt \\right) \\right] Q_I(t) \\left[ T \\exp \\left( -i \\int_{t_0}^{t} H_I(t')dt \\right) \\right]  |\\vv{0}\\rangle. \\label{eqn:in_in_formalism_expectation}\n\\end{align}\nThe interaction picture vacuum, $|\\vv{0}\\rangle$, lies in the infinite past $t=t_0$, where we assume that it can be identified as the vacuum of non-interacting theory and hence $a_\\vv{k}|\\vv{0}\\rangle = 0$.\n\nNote that the operators within the correlator in \\eqref{eqn:in_in_formalism_expectation} are not time ordered thanks to the anti-time-ordering operator $\\bar{T}$. To complicate things further, we do not have an equivalent of the Feynmann propagator in Minkowski space that handles the time ordering for us. We instead treat the time ordering manually. Let us define the \\textit{contraction} between two terms $\\zeta(\\vv{k}_1,t_1)$ on the left and $\\zeta(\\vv{k}_2,t_2)$ on the right as the commutator given by\n\\begin{align}\n\t[ \\zeta^+(\\vv{k}_1,t_1) , \\zeta^-(\\vv{k}_2,t_2) ] &= u_{k_1}(t_1) u^*_{k_2}(t_2) [ \\hat{a}_{\\vv{k_1}}, \\hat{a}_{\\vv{k_2}}^\\dagger] \\\\ &= u_{k_1}(t_1) u^*_{k_2}(t_2) (2\\pi)^3 \\delta^{(3)} (\\vv{k}_1 + \\vv{k}_2), \n\\end{align}\nwhere the positive and negative frequency solutions $\\zeta^+$ and $\\zeta^-$ refer to the terms with $\\hat{a}$ and $\\hat{a}^\\dagger$ in \\eqref{eqn:zeta_canonical_quantisation}, respectively. Note that swapping the order of $\\zeta(\\vv{k}_1,t_1)$ and $\\zeta(\\vv{k}_2,t_2)$ does alter the value of this commutator. We make equivalent definitions for the quantised conjugate momenta $\\hat{\\pi}_\\vv{k}$.\n\nWe now have a result comparable to Wick's theorem;\n\\begin{align}\n\t\\langle\\vv{0}| \\hat{O}(\\vv{k}_1,t_2) \\cdots \\hat{O}(\\vv{k}_n,t_n) |\\vv{0}\\rangle = \\;:\\; \\hat{O}(\\vv{k}_1,t_2)  \\cdots \\hat{O}(\\vv{k}_n,t_n) \\;:\\; + \\;:\\;\\text{all possible contractions}\\;:\\;. \\label{eqn:in_in_Wicks_theorem}\n\\end{align}\nThe normal ordering $::$ keeps $\\hat{a}$s to the right and $\\hat{a}^\\dagger$ to the left, so that its vacuum expectation value vanishes. The fields $\\hat{O}$ are either $\\hat{\\zeta}$ or $\\hat{\\pi}$. \n\n\\subsection{Bispectrum from single field inflation} \\label{section:bispectrum_from_single_field_inflation}\n\nThe mode function defined in \\eqref{eqn:zeta_canonical_quantisation} can be obtained analytically by solving the equations of motion from the quadratic action \\eqref{eqn:quadratic_action_in_zeta}. If the slow-roll and other variation parameters remain small and change slowly in time, then\n\\begin{align}\n\tu_k(\\tau) = \\frac{iH}{\\sqrt{4\\epsilon c_s k^3}} (1 + ikc_s \\tau) e^{-ikc_s \\tau},\n\\end{align}\nwhere $\\tau$ is conformal time. The choice of $u_k(\\tau)$ being the positive frequency solution as shown here is analogous to \\eqref{eqn:bunch_davis_mode_function} from before; we are fixing the vacuum state to be the Bunch-Davis vacuum.\n\nBefore proceeding to computing correlation functions using the in-in formalism, we first need to obtain the Hamiltonian of the system. The conjugate momentum is defined as $\\pi = \\partial \\mathcal{L} / \\partial \\dot{\\zeta}$, where $\\mathcal{L}$ is the Lagrangian density. The Hamiltonian density then takes the form $\\mathcal{H} = \\pi \\dot{\\zeta} - \\mathcal{L} = \\mathcal{H}_0 + \\mathcal{H}_{int}$. At the order of perturbations we are studying, $\\mathcal{H}_{int}$ consists only of cubic terms $\\mathcal{H}_3$, which is simply equal to $-\\mathcal{L}_3$ obtained from the cubic action $S_3$. It is also sufficient to consider the leading contribution to $\\zeta$, so that $\\pi \\propto \\dot{\\zeta}$.\n\\footnote{There are some subtleties here. We first use $\\pi = \\partial \\mathcal{L} / \\partial \\dot{\\zeta}$, which does contain contributions from higher order terms coming from $\\mathcal{L}=\\mathcal{L}_0 + \\mathcal{L}_{int}$. The Hamiltonian density $\\mathcal{H} = \\pi \\dot{\\zeta} - \\mathcal{L}$ is obtained using this $\\pi$. We then rewrite $\\pi$ in terms of $\\zeta$ and its derivatives within $\\mathcal{H}$. Next, the quadratic terms in $\\mathcal{H}$ are combined as $\\mathcal{H}_0$. From this free Hamiltonian we define the conjugate momentum in the interaction picture; $\\pi_I :=  \\partial \\mathcal{H}_0 / \\partial \\dot{\\zeta}$. This $\\pi_I$ is what we refer to as $\\pi$, simply proportional to $\\dot{\\zeta}$ in our case.}\nWe will rewrite $\\pi$ in terms of $\\dot{\\zeta}$ the rest of this section.\n\nWhen working perturbatively, the leading contributions to the three-point correlation function comes from the terms with one factor of the interaction Hamiltonian. Noting that the two terms coming from the two $H_I$s in \\eqref{eqn:in_in_formalism_expectation} are complex conjugates to each other, we have\n\\begin{align}\n\t\\left< \\zeta_{\\vv{k}_1}(t) \\zeta_{\\vv{k}_2}(t) \\zeta_{\\vv{k}_3}(t) \\right> = 2 \\text{Re}\\left[ \\langle\\vv{0}| -i \\zeta_{\\vv{k}_1}(t) \\zeta_{\\vv{k}_2}(t) \\zeta_{\\vv{k}_3}(t) \\int_{t_0}^{t} H_I(t') dt' |\\vv{0}\\rangle \\right], \\label{eqn:in_in_formalism_bispectrum}\n\\end{align}\nin tree-level. This is the key formula for computing the primordial bispectrum from a given single field inflation Lagrangian.\n\nWe will now demonstrate how to compute \\eqref{eqn:in_in_formalism_bispectrum} using a simple example. We take the term proportional to $\\dot\\zeta^3$ within the cubic action \\eqref{eqn:cubic_action_example_term}. To simplify further, we write it as $\\lambda a^3 \\dot{\\zeta}^3$, where $\\lambda=\\lambda(t)$ is given in terms of the variation parameters like $\\epsilon$. The corresponding contribution to the interaction Hamiltonian is given by\n\\begin{align}\n\tH_{I,\\dot{\\zeta}^3}(t) &:= -\\lambda(t) a(t)^3 \\int d^3\\vv{x} \\; \\left[  \\dot{\\zeta}(\\vv{x},t)^3 \\right]  \\\\\n\t&= -\\lambda a^3 \\int d^3\\vv{x} \\; \\frac{d^3\\vv{p}_1}{(2\\pi)^3} \\frac{d^3\\vv{p}_2}{(2\\pi)^3} \\frac{d^3\\vv{p}_3}{(2\\pi)^3} \\; e^{i(\\vv{p}_1 + \\vv{p}_2 + \\vv{p}_3)\\cdot\\vv{x}} \\left[ \\dot{\\zeta}_{\\vv{p}_1} \\dot{\\zeta}_{\\vv{p}_2} \\dot{\\zeta}_{\\vv{p}_3} \\right] \\\\\n\t&= - (2\\pi)^3 \\delta^{(3)}(\\vv{p}_1 + \\vv{p}_2 + \\vv{p}_3) \\cdot \\lambda a^3 \\int \\frac{d^3\\vv{p}_1}{(2\\pi)^3} \\frac{d^3\\vv{p}_2}{(2\\pi)^3} \\frac{d^3\\vv{p}_3}{(2\\pi)^3} \\; \\left[ \\dot{\\zeta}_{\\vv{p}_1} \\dot{\\zeta}_{\\vv{p}_2} \\dot{\\zeta}_{\\vv{p}_3} \\right], \\label{def:interaction_hamiltonian_zeta_dot_cube}\n\\end{align}\nwhere we used the definition of Fourier transformation and omitted the time dependence for brevity. Note also that $\\zeta_{\\vv{p}}(t) = const$ after the mode crosses the horizon because the curvature perturbation freezes out at super-horizon scales\\textemdash a result we have shown in Section \\ref{section:curvature_perturbations}.\n\nWe substitute \\eqref{def:interaction_hamiltonian_zeta_dot_cube} into \\eqref{eqn:in_in_formalism_bispectrum} and swap the order of expectations and integrals. The integrand include a six-point correlation function which can be evaluated using \\eqref{eqn:in_in_Wicks_theorem};\n\\begin{align}\n\t&\\langle\\vv{0}| \\zeta_{\\vv{k}_1}(t) \\zeta_{\\vv{k}_2}(t) \\zeta_{\\vv{k}_3}(t) \\zeta_{\\vv{p}_1}(t') \\zeta_{\\vv{p}_2}(t') \\zeta_{\\vv{p}_3}(t') |\\vv{0}\\rangle \\nonumber\\\\\n\t&\\hspace{0.05\\textwidth}= \\langle\\vv{0}| \\;: \\text{all contractions} :\\;|\\vv{0}\\rangle \\\\\n\t&\\hspace{0.05\\textwidth}= [ \\zeta^+(\\vv{k}_1,t) , \\zeta^-(\\vv{p}_1,t') ] [ \\zeta^+(\\vv{k}_2,t) , \\zeta^-(\\vv{p}_2,t') ] [ \\zeta^+(\\vv{k}_3,t) , \\zeta^-(\\vv{p}_3,t') ] + \\text{5 perms.}  \\\\\n\t&\\hspace{0.05\\textwidth}=  \\prod_{j=1}^{3} \\left[ u_{k_j} \\dot{u}^*_{p_j}(t') (2\\pi)^3 \\delta^{(3)}(\\vv{k}_j+\\vv{p}_j) \\right] + \\text{5 perms.}.\n\\end{align}\nNote that we discarded some terms which involve contracting the fields at equal times. Such contractions necessarily cause one of the $\\vv{p}_j$ to be $\\vv{0}$ due to the delta function present in \\eqref{def:interaction_hamiltonian_zeta_dot_cube}. $\\zeta_\\vv{0}$ corresponds to a constant scaling of the background $a(t)$, and after absorbing that factor into $a(t)$, $\\zeta_{\\vv{0}}$ can be set to zero. \n\nCombining the results so far, we obtain the following expression for the bispectrum induced by the $\\dot{\\zeta}^3$ term\n\\begin{align}\n\tB_{\\dot{\\zeta}^3}(k_1,k_2,k_3,t) = \\text{Re}\\left[ 2i u_{k_1}(t) u_{k_2}(t) u_{k_3}(t) \\int_{t_0}^{t} dt' \\lambda(t') a(t')^3 \\dot{u}^*_{k_1}(t') \\dot{u}^*_{k_2}(t') \\dot{u}^*_{k_3}(t')   + \\text{5 perms} \\right].\n\\end{align}\nIn order to evaluate the bispectrum at the end of inflation, we convert back from comoving to conformal time. The time integral is then taken from $\\tau=-\\infty$ to $\\tau=0$. The lower limit of the integral can be troublesome, since $e^{i k c_s \\tau}$ in the mode function displays oscillatory behaviour as $\\tau\\rightarrow -\\infty$. We shift $-\\infty$ to $-\\infty(1+i\\epsilon)$ so that the integrand is suppressed at the lower limit. We further approximate the variation parameters including $\\lambda(\\tau)$ to be constant and use the de Sitter background $a(\\tau)\\approx -1/(H\\tau)$ within the integral;\n\\begin{align}\n\tB_{\\dot{\\zeta}^3}(k_1,k_2,k_3) &\\approx -12\\lambda \\cdot \\text{Imag}\\left[  u_{k_1}(0) u_{k_2}(0) u_{k_3}(0) \\int_{-\\infty(1+i\\epsilon)}^{0} d\\tau \\;  a(\\tau) {u'}^*_{k_1}(\\tau) {u'}^*_{k_2}(\\tau) {u'}^*_{k_3}(\\tau)  \\right] \\\\\n\t&= -12\\lambda \\cdot \\text{Imag} \\left[ \\frac{H^5 c_s^3}{64\\epsilon^3} \\frac{1}{k_1 k_2 k_3} \\int_{-\\infty(1+i\\epsilon)}^{0} d\\tau \\; \\tau^2 e^{ic_s\\tau(k_1+k_2+k_3)} \\right] \\\\\n\t&= \\frac{3\\lambda H^5}{8\\epsilon^3} \\frac{1}{k_1 k_2 k_3} \\frac{1}{(k_1+k_2+k_3)^3}.\n\\end{align}\nThe corresponding shape function takes the form\n\\begin{align}\n\tS_{\\dot{\\zeta}^3}(k_1,k_2,k_3) \\propto \\frac{k_1 k_2 k_3}{(k_1+k_2+k_3)^3},\n\\end{align}\nwhich is maximised in the equilateral limit and vanishes at the squeezed limit.\n\nThe full bispectrum can be computed using the general methodology shown in this section. We quote one of the most important results; for canonical slow-roll inflation with $P(X,\\phi) = X - V(\\phi)$, the bispectrum is suppressed by the slow-roll parameters $\\epsilon$ and $\\eta$ \\cite{Maldacena2013}. However, relaxing any of the assumptions\\textemdash canonical kinetic term, slow-roll, single-field, and Bunch-Davis vacuum\\textemdash may yield significant and observable signatures in the bispectrum (see \\cite{Chen2010review,Komatsu2010} for reviews).\n\n\\section{CMB bispectrum estimation} \\label{section:CMB_bispectrum_estimation}\n\nThe presence of a non-vanishing bispectrum at the end of inflation due to primordial non-Gaussianity leaves imprints on the CMB. The bispectrum of the observed CMB anisotropy directly relates to the primordial counterpart thanks to the linear nature of the evolution, and hence is a key statistic for constraining primordial non-Gaussianity.\n\nNear-Gaussianity of the CMB means that its bispectrum has relatively small signal-to-noise. In contrast to the power spectrum analysis where we treat each $C_l$ (after binning) as an independent data point, the noise-dominated $b_{l_1 l_2 l_3}$s are not so significant individually. Therefore, we instead fit the whole bispectrum data to the theoretical prediction from a given model in order to estimate a single parameter measuring the amplitude: $f_{NL}$.\n\nIn this section, we formulate the theory of CMB bispectrum estimation. Estimating $f_{NL}$ is an extremely challenging task due to its computational complexity and the oscillatory integrals involved. We review several conventional approaches to handle these challenges and summarise their respective strengths and weaknesses. Lastly, we discuss some significant non-primordial sources of non-Gaussianity that needs to be carefully accounted for in the estimation process.\n\n\n\\subsection{CMB bispectrum}\n\nConsider the three-point correlation function of the spherical harmonic coefficients $a_{lm}^X$ from \\eqref{eqn:alm_from_phi};\n\\begin{align}\n\t\\left< a_{l_1 m_1}^{X_1} a_{l_2 m_2}^{X_2} a_{l_3 m_3}^{X_3}  \\right> = (4\\pi)^3 (-i)^{l_1 + l_2 + l_3} \\left< \\prod_{j=1}^{3} \\left[ \\int \\frac{d^3\\vv{k}_j}{(2\\pi)^3} \\zeta(\\vv{k}_j)   \\Delta_{l_j}^{X_j} (k_j) Y^*_{l_j m_j} (\\hat{\\vv{k}}_j) \\right] \\right>, \\label{eqn:bispectrum_derivation_base_form}\n\\end{align}\nwhere we replaced $\\Phi$ with $\\zeta$ in the integrand. Here, $X_j$s can be either $T$ or $E$ which corresponds to the temperature and E-mode polarisation of the CMB anisotropy, respectively. The transfer functions $\\Delta_l^X (k)$ for $\\zeta$ depend only on $k=\\left\\| \\vv{k} \\right\\|$. They incorporate all information about the evolution of primordial perturbations $\\zeta$ and then projection onto the observed sky today.\n\nWe may take everything but $\\zeta(\\vv{k_j})$s outside the brackets $\\left< \\cdot \\right>$. From the definition of bispectrum, we have\n\\begin{align}\n\t\\left< \\zeta(\\vv{k}_1) \\zeta(\\vv{k}_2)  \\zeta(\\vv{k}_3) \\right> &= (2\\pi)^3 \\delta^{(3)}(\\vv{k}_1 + \\vv{k}_2 + \\vv{k}_3) B(k_1, k_2, k_3) \\label{eqn:primordial_bispectrum}\\\\\n\t&= \\int d^3 \\vv{r} \\; e^{-i\\vv{r} \\cdot (\\vv{k}_1 + \\vv{k}_2 + \\vv{k}_3)}  B(k_1, k_2, k_3). \\label{eqn:bispectrum_derivation_delta_function}\n\\end{align}\nwhere an integral expression is substituted for the Dirac $\\delta$-function in the second line. At the cost of introducing an extra integral, we managed to express the $\\delta$-function in a separable form: $\\exp(\\vv{r} \\cdot (\\vv{k}_1+\\vv{k}_2+\\vv{k}_3)) = \\exp(\\vv{r}\\cdot \\vv{k}_1) \\exp(\\vv{r}\\cdot \\vv{k}_2) \\exp(\\vv{r}\\cdot \\vv{k}_3)$. The remaining exponentials are rewritten using the plane wave expansion;\n\\begin{align}\n\te^{-i \\vv{k} \\cdot \\vv{r}} &= \\sum_{l=0}^{\\infty} (2l+1) (-i)^l j_l(kr) P_l(\\hat{\\vv{k}} \\cdot \\hat{\\vv{r}})  \\\\\t\n\t&= \\sum_{l=0}^{\\infty} \\sum_{m=-l}^{l} 4\\pi (-i)^l j_l(kr) Y_{lm}(\\hat{\\vv{k}}) Y^*_{lm}(\\hat{\\vv{r}}). \\label{eqn:bispectrum_derivation_rayleigh}\n\\end{align}\nThe Legendre polynomial $P_l(\\hat{\\vv{k}} \\cdot \\hat{\\vv{r}})$ has been expanded using the spherical harmonic addition theorem in the last line. Note that $\\vv{k}$ and $\\vv{r}$ mix only through their amplitudes within the spherical bessel functions as $j_l(kr)$. Once substituted into (\\ref{eqn:bispectrum_derivation_base_form}), we can perform the angular integral $d^2 \\hat{\\vv{k}_j}$ separately for each $j=1,2,3$, since $d^3\\vv{k}_j = dk_j k_j^2 d^2 \\hat{\\vv{k}_j}$. Note also that the spherical harmonic orthogonality relation is given by\n\\begin{align}\n\t\\int d^2 \\hat{\\vv{n}} \\; Y_{lm}(\\hat{\\vv{n}}) Y^*_{l'm'}(\\hat{\\vv{n}}) = \\delta_{l l'} \\delta_{m m'}.\n\\end{align}\nIncorporating \\eqref{eqn:bispectrum_derivation_base_form}, \\eqref{eqn:bispectrum_derivation_delta_function}, and \\eqref{eqn:bispectrum_derivation_rayleigh}, we obtain\n\\begin{align}\n\t&\\left< a_{l_1 m_1}^{X_1} a_{l_2 m_2}^{X_2} a_{l_3 m_3}^{X_3}  \\right> \\nonumber \\\\\n\t&\\hspace{0.05\\textwidth}= \\frac{(4\\pi)^3}{(2\\pi)^9} (-1)^{l_1 + l_2 + l_3} \\int d^3 \\vv{r} \\; d^3 \\vv{k}_1 d^3 \\vv{k}_2 d^3 \\vv{k}_3 \\; B(k_1,k_2,k_3) \\nonumber \\\\\n\t&\\hspace{0.25\\textwidth} \\times \\prod_{j=1}^{3} \\left[ \\sum_{l'_j = 0}^{\\infty} \\sum_{m'_j=-l'_j}^{l'_j} j_{l'_j} (k_j r) Y_{l'_j m'_j} (\\hat{\\vv{k}}_j) Y^*_{l'_j m'_j} (\\hat{\\vv{r}}) \\Delta_{l_j}^{X_j} (k_j) Y^*_{l_j m_j} (\\hat{\\vv{k}}_j) \\right]  \\label{eqn:bispectrum_derivation_main_line1}\\\\\n\t&\\hspace{0.05\\textwidth}= \\left( \\frac{2}{\\pi} \\right)^3 \\int d^3 \\vv{r} \\; dk_1 dk_2 dk_3 \\left( k_1 k_2 k_3 \\right)^2 B(k_1, k_2, k_3) \\prod_{j=1}^{3} \\left[ j_{l_j} (k_j r) Y^*_{l_j m_j} (\\hat{\\vv{r}}) \\Delta_{l_j}^{X_j} (k_j) \\right]  \\label{eqn:bispectrum_derivation_main_line2}\\\\\n\t&\\hspace{0.05\\textwidth}= \\left( \\frac{2}{\\pi} \\right)^3 \\mathcal{G}^{l_1 l_2 l_3 *}_{m_1 m_2 m_3} \\int dr \\; dk_1 dk_2 dk_3 r^2 \\left( k_1 k_2 k_3 \\right)^2 B(k_1, k_2, k_3) \\prod_{j=1}^{3} \\left[ j_{l_j} (k_j r) \\Delta_{l_j}^{X_j} (k_j) \\right], \\label{eqn:bispectrum_derivation_main_line3}\n\\end{align}\nwhere the Gaunt integral is defined as\n\\begin{align}\n\t\\mathcal{G}^{l_1 l_2 l_3}_{m_1 m_2 m_3} := \\int d^2 \\hat{\\vv{n}} \\; Y_{l_1 m_1} (\\hat{\\vv{n}}) Y_{l_2 m_2} (\\hat{\\vv{n}}) Y_{l_3 m_3} (\\hat{\\vv{n}}). \\label{def:gaunt_integral}\n\\end{align}\nThis value is always real, so we may omit the complex conjugate in (\\ref{eqn:bispectrum_derivation_main_line3}). Note also that we dropped a factor of $(-1)^{l_1+l_2+l_3}$ in (\\ref{eqn:bispectrum_derivation_main_line2}). This is due to parity reasons. Spherical harmonics have definite parity; $Y_{lm}(-\\hat{\\vv{n}}) = (-1)^l Y_{lm}(\\hat{\\vv{n}})$. Applying parity transformation to the integral in (\\ref{def:gaunt_integral}) gives $\\mathcal{G}^{l_1 l_2 l_3}_{m_1 m_2 m_3} = (-1)^{l_1+l_2+l_3} \\mathcal{G}^{l_1 l_2 l_3}_{m_1 m_2 m_3}$. The Gaunt integral therefore evaluates to zero unless $l_1+l_2+l_3$ is even.\n\nWe define the \\textit{reduced} bispectrum as\n\\begin{align}\n\tb^{X_1 X_2 X_3}_{l_1 l_2 l_3} := \\left( \\frac{2}{\\pi} \\right)^3 \\int dr dk_1 dk_2 dk_3 \\left(r k_1 k_2 k_3 \\right)^2 B(k_1, k_2, k_3) \\prod_{j=1}^{3} \\left[ j_{l_j} (k_j r) \\Delta_{l_j}^{X_j} (k_j) \\right]. \\label{def:reduced_bispectrum}\n\\end{align}\nThe late-time bispectrum can now be written in a concise form;\n\\begin{align}\n\t\\left< a_{l_1 m_1}^{X_1} a_{l_2 m_2}^{X_2} a_{l_3 m_3}^{X_3}  \\right> = \\mathcal{G}^{l_1 l_2 l_3}_{m_1 m_2 m_3} b^{X_1 X_2 X_3}_{l_1 l_2 l_3}. \\label{eqn:late_time_bispectrum_form}\n\\end{align}\n\nRecall that the three point function in (\\ref{eqn:primordial_bispectrum}) is given by a product of delta function enforcing $\\vv{k}_1 + \\vv{k}_2 + \\vv{k}_3 = \\vv{0}$ and the primordial bispectrum $B(k_1,k_2,k_3)$. Its spherical harmonic counterpart (\\ref{eqn:late_time_bispectrum_form}) takes an analogous form. The Gaunt integral $\\mathcal{G}^{l_1 l_2 l_3}_{m_1 m_2 m_3}$ contains all geometrical information, enforcing the triangle condition on $l_1$, $l_2$, $l_3$ and angular momentum conservation $m_1+m_2+m_3=0$. Meanwhile, the reduced bispectrum encodes statistical information about the underlying three point functions, just like $B(k_1,k_2,k_3)$.\n\nThe value of the Gaunt integral is best represented using Wigner 3-j symbols;\n\\begin{align}\n\t\\mathcal{G}^{l_1 l_2 l_3}_{m_1 m_2 m_3} = \\sqrt{\\frac{(2l_1+1)(2l_2+1)(2l_3+1)}{4\\pi}} \\begin{pmatrix}\tl_1 & l_2 & l_3 \\\\ m_1 & m_2 & m_3 \\end{pmatrix} \\begin{pmatrix}\tl_1 & l_2 & l_3 \\\\ 0 & 0 & 0 \\end{pmatrix}.\n\\end{align}\nThe Wigner 3-j symbols, written here as a 2-by-3 matrix, are closely related to the addition of angular momenta. They are real coefficients appearing in the expansion of the zero-total-angular-momentum state $|0 \\; 0\\rangle$;\n\\begin{align}\n\t| 0 \\; 0 \\rangle = \\sum_{l_1,m_1} \\sum_{l_2,m_2} \\sum_{l_3,m_3} \\begin{pmatrix}\tl_1 & l_2 & l_3 \\\\ m_1 & m_2 & m_3 \\end{pmatrix} | l_1 m_1 \\rangle | l_2 m_2 \\rangle | l_3 m_3 \\rangle.\n\\end{align}\nFor further details on Wigner 3-j symbols see, e.g., \\cite{Olver2010nist}. We quote the following two identities for our purposes.\n\\begin{align}\n\t\\sum_{m_1,m_2,m_3} { \\begin{pmatrix}\tl_1 & l_2 & l_3 \\\\ m_1 & m_2 & m_3 \\end{pmatrix} }^2 &= 1, \\label{eqn:wigner_3j_normalisation} \\\\\n\t{ \\begin{pmatrix}\tl_1 & l_2 & l_3 \\\\ 0 & 0 & 0 \\end{pmatrix} }^2 &= \\frac{1}{2} \\int_{-1}^{1} d\\mu \\; P_{l_1}(\\mu) P_{l_2}(\\mu) P_{l_3}(\\mu). \\label{eqn:wigner_3j_legendre_integral} \n\\end{align}\nThe normalisation condition (\\ref{eqn:wigner_3j_normalisation}) can be easily derived by computing norm of the state $|0 \\; 0 \\rangle$ in the definition. The second identity (\\ref{eqn:wigner_3j_legendre_integral}) allows us to rewrite a square of any given 3-j symbol satisfying $m_1=m_2=m_3=0$ in terms of a separable integral.\n\nWe make one last definition which will prove to be useful in the next section;\n\\begin{align}\n\th^2_{l_1 l_2 l_3} :=& \\sum_{m_1, m_2, m_3} \\left( \\mathcal{G}^{l_1 l_2 l_3}_{m_1 m_2 m_3} \\right)^2  \\label{def:h2_using_gaunt_integral}\\\\\n\t=& \\frac{(2l_1+1)(2l_2+1)(2l_3+1)}{4\\pi} { \\begin{pmatrix}\tl_1 & l_2 & l_3 \\\\ 0 & 0 & 0 \\end{pmatrix} }^2 \\\\\n\t=& \\frac{(2l_1+1)(2l_2+1)(2l_3+1)}{8\\pi} \\int_{-1}^{1} d\\mu \\; P_{l_1}(\\mu) P_{l_2}(\\mu) P_{l_3}(\\mu). \\label{def:h2_using_legendre_integral}\n\\end{align}\n\nBy squaring the Gaunt integral and summing over $m$s, we get a simpler quantity $h^2_{l_1 l_2 l_3}$ which preserves all important geometrical information. Here $l_1$, $l_2$ and $l_3$ must still satisfy triangle inequalities and add up to an even number. Otherwise, the integral over Legendre polynomials in (\\ref{def:h2_using_legendre_integral}) vanishes.\n\n\\subsection{Optimal estimator}\nThe bispectrum of the CMB anisotropy is a powerful statistic for studying primordial non-Gaussianity. The Planck collaboration's CMB bispectrum analyses provided the most stringent bounds on the amplitude of primordial bispectrum with respect to various shapes and constrained a wide class of inflationary models. Due to the largely linear evolution of the CMB, there are little contributions to the bispectrum from non-primordial origins compared to other probes such as the large scale structure. Here, we derive the optimal CMB bispectrum estimator using mathematical foundations laid out previously.\n\nConsider a number of inflation models which predict non-zero primordial bispectra. We often use template bispectra which capture some common characteristics of a class of models, like the local, equilateral, and orthogonal shapes (\\ref{def:local_template}-\\ref{def:orthogonal_template}). We would like to find out if the true underlying bispectrum, if any, can be expanded in terms of the functions $B^{(i)}$ chosen;\n\\begin{align}\n\tB(k_1,k_2,k_3) = \\sum_i f_{NL}^{(i)} \\; B^{(i)}(k_1,k_2,k_3), \\label{eqn:primordial_bispectrum_fNLs}\n\\end{align}\nwhere the primordial non-Gaussianity (or non-linearity) parameter $f^{(i)}_{NL}$ measures the magnitude of the $i$th bispectrum shape found in reality. Detection of a non-zero $f_{NL}$ would serve as a strong evidence for the corresponding inflation models. Non-detection of $f_{NL}$, on the other hand, still allows us to place bounds on it and hence constrain models which predict larger bispectra.\n\nExpressing (\\ref{eqn:primordial_bispectrum_fNLs}) in terms of the late-time CMB anisotropies,\n\\begin{align}\n\t\\left< a_{l_1 m_1}^{X_1} a_{l_2 m_2}^{X_2} a_{l_3 m_3}^{X_3}  \\right> = \\sum_i f^{(i)}_{NL} \\; \\mathcal{G}^{l_1 l_2 l_3}_{m_1 m_2 m_3} b^{X_1 X_2 X_3, (i)}_{l_1 l_2 l_3}. \\label{eqn:late_time_bispectrum_fNLs_theoretical}\n\\end{align}\nThe goal of the CMB bispectrum estimation is to compute $f^{(i)}_{NL}$s that best describes the observed data. In reality, we can only observe one realisation of the universe and therefore a single set of $a_{lm}$s. The expectation values $\\left< \\cdot \\right>$ on the left hand side of \\eqref{eqn:late_time_bispectrum_fNLs_theoretical} are replaced by sample estimates, which introduces some errors;\n\\begin{align}\n\ta_{l_1 m_1}^{X_1} a_{l_2 m_2}^{X_2} a_{l_3 m_3}^{X_3} = \\sum_i  f^{(i)}_{NL} \\; \\mathcal{G}^{l_1 l_2 l_3}_{m_1 m_2 m_3} b^{X_1 X_2 X_3, (i)}_{l_1 l_2 l_3} \\;+\\; \\epsilon^{X_1 X_2 X_3}_{l_1 l_2 l_3, m_1 m_2 m_3}. \\label{eqn:late_time_bispectrum_fNLs_sample}\n\\end{align}\nFor simplicity, we drop the $X_j$'s from now on. The derivation of the bispectrum estimator here can easily be generalised to include both temperature and E-mode polarisation. We also define some shorthand notations for the harmonic multipole indices to improve readability;\n\\begin{align}\n\t\\vv{l}_j:=(l_j,m_j), \\;\\; L:=(l_1,l_2,l_3), \\;\\; \\text{and} \\;\\; \\vv{L}:=(\\vv{l}_1, \\vv{l}_2, \\vv{l}_3).\n\\end{align}\nThe estimation problem is summarised as follows.\n\\begin{align}\n\t&B^{obs}_\\vv{L} = \\sum_i B^{(i)}_\\vv{L} f^{(i)}_{NL}  \\;+\\; \\epsilon_\\vv{L}, \\label{eqn:bispectrum_estimation_core}\\\\\n\t\\text{where} \\;\\; &B^{obs}_\\vv{L} := a_{\\vv{l}_1} a_{\\vv{l}_2} a_{\\vv{l}_3} \\;\\; \\text{and} \\;\\; B^{(i)}_\\vv{L} := \\mathcal{G}_\\vv{L} b^{(i)}_L.\n\\end{align}\nThe form of \\eqref{eqn:bispectrum_estimation_core} makes it clear that the bispectrum estimation is a linear regression in essence. Borrowing words from statistics, we specify the components of our analysis below.\n\\begin{itemize}\n\t\\item $\\vv{B}^{obs}$ is the \\textit{regressand}, in our case the noisy observed bispectrum samples $B^{obs}_\\vv{L}$ obtained for each \\textit{observation} $\\vv{L}$.\n\t\\item $\\vv{B}^{(i)}$s are the \\textit{regressors}, theoretical bispectra $B^{(i)}_\\vv{L}$ motivated from inflationary models.\n\t\\item $f^{(i)}_{NL}$s are the \\textit{regression coefficients} which parametrise how much each regressor contributes to the regressand. Our main objective is to estimate them.\n\t\\item $\\vv{\\epsilon}$ is the \\textit{error term} which represents the noise in bispectrum sample compared to the true underlying value. $\\epsilon_\\vv{L}$ can be sourced by the sampling error (from having limited number of samples) and/or inaccuracies in the measurements. \n\\end{itemize}\n\nWe adopt the least squares method to estimate $f_{NL}$s from given $\\vv{B}^{obs}$ and $B^{(i)}_\\vv{L}$. Before doing so, each element of the regressand and regressors needs to be normalised so that the expected variances in the error are constant across different observations $\\vv{L}$. We compute the theoretical variance in $B^{obs}_\\vv{L}$ under two assumptions. First, we work in a weak non-Gaussian limit where the dominant contributions to correlation functions come from the Gaussian part of $a_\\vv{l}$s. Wick's theorem then reduces the problem down to summing over all possible contractions. Second, we neglect inaccuracies in the $a_{lm}$ measurements, since their contributions to the total error is much smaller compared to the sampling errors.\n\nUnder these assumptions, the expected covariance of the observed bispectra is given by\n\\begin{align}\n\t\\left< B^{obs}_\\vv{L} B^{obs}_{\\vv{L}'} \\right> &= \\left< a_{\\vv{l}_1} a_{\\vv{l}_2} a_{\\vv{l}_3} a_{\\vv{l}'_1} a_{\\vv{l}'_2} a_{\\vv{l}'_3} \\right> \n\t\\label{eqn:bispectrum_variance_contractions1} \\\\\n\t&= \\left[ \\left< a_{\\vv{l}_1} a_{\\vv{l}'_1} \\right> \\left< a_{\\vv{l}_2} a_{\\vv{l}'_2} \\right> \\left< a_{\\vv{l}_3} a_{\\vv{l}'_3} \\right> + \\left< a_{\\vv{l}_1} a_{\\vv{l}'_1} \\right> \\left< a_{\\vv{l}_2} a_{\\vv{l}'_3} \\right> \\left< a_{\\vv{l}_3} a_{\\vv{l}'_2} \\right> + \\cdots \\right]^\\ddagger \\nonumber \\\\\n\t&\\;\\;\\;\\; + \\left[ \\left< a_{\\vv{l}_1} a_{\\vv{l}_2} \\right> \\left< a_{\\vv{l}'_1} a_{\\vv{l}'_2} \\right> \\left< a_{\\vv{l}_3} a_{\\vv{l}'_3} \\right> + \\left< a_{\\vv{l}_1} a_{\\vv{l}_2} \\right> \\left< a_{\\vv{l}'_2} a_{\\vv{l}'_3} \\right> \\left< a_{\\vv{l}_3} a_{\\vv{l}'_1} \\right> + \\cdots \\right]^{\\ddagger\\ddagger} \\label{eqn:bispectrum_variance_contractions2}.\n\\end{align}\n\\eqref{eqn:bispectrum_variance_contractions2} contains all possible contractions of the 6 $a_\\vv{l}$s, 3 from each of $B^{obs}_\\vv{L}$ and $B^{obs}_{\\vv{L}'}$. There are 15 such contractions: 6 consisting only of terms between the two bispectra (in $\\ddagger$) and 9 which also have internal contractions ($\\ddagger\\ddagger$). Our aim is to modify the regression variables so that the resulting covariance matrix reduces to the identity. The error in each $\\vv{L}$ is required to be independent and of unit variance.\n\nThe terms in ($\\ddagger$) originate from a symmetry present in the bispectrum; $B^{obs}_\\vv{L} = a_{\\vv{l}_1}  a_{\\vv{l}_2}  a_{\\vv{l}_3}$ is invariant under permutations of ${\\vv{l}_1, \\vv{l}_2, \\vv{l}_3}$. In order to remove duplicate elements, we restrict our $\\vv{L}$s to ones satisfying $\\vv{l}_1 \\le \\vv{l}_2 \\le \\vv{l}_3$. \\footnote{$(l_1,m_1) < (l_2,m_2)$ if and only if ($l_1 < l_2$) \\textbf{or} ($l_1 = l_2$ and $m_1 < m_2$).}\n\nOn the other hand, terms in ($\\ddagger\\ddagger$) reveal a more complex issue about our formulation. The observed anisotropies $a_\\vv{l}$ are not necessarily independent since various factors such as partial sky coverage and correlated noise can induce correlations between them. Even if they are independent, our construction of $B^{obs}_\\vv{L}$ can yield non-zero terms in ($\\ddagger\\ddagger$) when at least two out of $\\vv{l}_1, \\vv{l}_2, \\vv{l}_3$ are identical. This is similar, in essence, to incorrectly estimating the variance of a random variable $X$ from samples $X_i$ by computing $\\sum_i X_i^2$ instead of the correct $\\sum_i (X_i- \\left< X \\right>)^2$.\n\nWe redefine the observed bispectra in terms of the $a_\\vv{l}$s by subtracting off these extra contributions.\n\\begin{align}\n\t{B'}^{obs}_\\vv{L} := a_{\\vv{l}_1} a_{\\vv{l}_2} a_{\\vv{l}_3} - \\left< a_{\\vv{l}_1} a_{\\vv{l}_2} \\right> a_{\\vv{l}_3} - \\left< a_{\\vv{l}_2} a_{\\vv{l}_3} \\right> a_{\\vv{l}_1} - \\left< a_{\\vv{l}_3} a_{\\vv{l}_1} \\right> a_{\\vv{l}_2}. \\label{def:bispectrum_estimate_including_linear}\n\\end{align}\nThe newly introduced terms linear in $a_\\vv{l}$s have zero mean, since $\\left< a_\\vv{l} \\right> = 0$ except for the monopole $l=0$ which is excluded from the CMB bispectrum analysis. Thus ${B'}^{obs}_\\vv{L}$ is still an unbiased estimate of the underlying bispectra. Substituting into \\eqref{eqn:bispectrum_variance_contractions1}, all terms that were previously in ($\\ddagger\\ddagger$) now vanish.\n\nIn theory, we can compute \\eqref{eqn:bispectrum_variance_contractions1} using the full covariance matrix $C_{\\vv{l}_1 \\vv{l}_2} = \\left< a_{\\vv{l}_1} a_{\\vv{l}_2} \\right>$ and invert it to get the least squares estimate for $f_{NL}$s. In practice, however, this is a costly and numerically demanding operation. We instead approximate the non-diagonal covariances in \\eqref{def:bispectrum_estimate_including_linear} using the Monte Carlo method: $\\langle a_{\\vv{l}_1}^{G} a_{\\vv{l}_2}^{G} \\rangle_{MC}$ from an ensemble of realistic Gaussian simulations. In other places we assume $C_{\\vv{l}_1 \\vv{l}_2} \\approx C_{l_1} \\delta_{\\vv{l}_1 \\vv{l}_2}$ to simplify our calculations.\n\nEach element of the regressand is now independent;\n\\begin{align}\n\t\\left< {B'}^{obs}_\\vv{L} {B'}^{obs}_{\\vv{L}'} \\right> = C_{l_1} C_{l_2} C_{l_3} \\; \\Delta_{\\vv{l}_1 \\vv{l}_2 \\vv{l}_3} \\; \\delta_{\\vv{l}_1 \\vv{l}'_1} \\delta_{\\vv{l}_2 \\vv{l}'_2} \\delta_{\\vv{l}_3 \\vv{l}'_3},\n\\end{align}\nwhere $\\Delta_{\\vv{l}_1 \\vv{l}_2 \\vv{l}_3}$ is a symmetry factor equal to $6$ if $\\vv{l}_1 = \\vv{l}_2 = \\vv{l}_3$, $2$ if exactly two of them are identical, and $1$ if all three are distinct. The regressand and regressors are rescaled so that each element of the error term has unit variance;\n\\begin{align}\n\t\\tilde{B}^{obs}_\\vv{L} &:= \\frac{1}{\\sqrt{\\Delta_{\\vv{l}_1 \\vv{l}_2 \\vv{l}_3} C_{l_1} C_{l_2} C_{l_3}}} \\left[ a_{\\vv{l}_1} a_{\\vv{l}_2} a_{\\vv{l}_3} - \\left< a_{\\vv{l}_1} a_{\\vv{l}_2} \\right> a_{\\vv{l}_3} - \\left< a_{\\vv{l}_2} a_{\\vv{l}_3} \\right> a_{\\vv{l}_1} - \\left< a_{\\vv{l}_3} a_{\\vv{l}_1} \\right> a_{\\vv{l}_2} \\right] \\\\\n\t\\tilde{B}^{(i)}_\\vv{L} &:= \\frac{1}{\\sqrt{\\Delta_{\\vv{l}_1 \\vv{l}_2 \\vv{l}_3} C_{l_1} C_{l_2} C_{l_3}}} \\; \\mathcal{G}_{\\vv{L}} b^{(i)}_{L}\n\\end{align}\n\nThe ordinary least squares estimate for a linear model $\\vv{y} = X\\vv{\\beta} + \\vv{\\epsilon}$ is given by $\\hat{\\beta} = (X^T X)^{-1} X^T \\vv{y}$. We define the equivalent objects to $(X^T X)_{ij}$ and $(X^T \\vv{y})_i$ in our linear model \\eqref{eqn:bispectrum_estimation_core} as $F_{ij}$ and $S_i$, respectively. The matrix $F$ is given by\n\\begin{align}\n\tF_{ij} &:= \\tilde{\\vv{B}}^{(i)} \\cdot \\tilde{\\vv{B}}^{(j)} \\\\[0.5ex]\n\t&= \\sum_{\\vv{l}_1 \\le \\vv{l}_2 \\le \\vv{l}_3}  \\frac{\\mathcal{G}_{\\vv{L}}^2 \\; b^{(i)}_{L} b^{(j)}_{L}}{\\Delta_{\\vv{l}_1 \\vv{l}_2 \\vv{l}_3} \\; C_{l_1} C_{l_2} C_{l_3}}   \n\t= \\sum_{\\vv{l}_1 , \\vv{l}_2 , \\vv{l}_3}  \\frac{\\mathcal{G}_{\\vv{L}}^2 \\; b^{(i)}_{L} b^{(j)}_{L}}{6 \\; C_{l_1} C_{l_2} C_{l_3}}\n\t= \\sum_{l_1,l_2,l_3}  \\frac{h^2_L \\; b^{(i)}_{L} b^{(j)}_{L}}{6 \\; C_{l_1} C_{l_2} C_{l_3}}. \\label{eqn:bispectrum_estimation_fisher}\n\\end{align}\nThe symmetry factor in \\eqref{eqn:bispectrum_estimation_fisher} was removed by relieving the restriction $\\vv{l}_1 \\le \\vv{l}_2 \\le \\vv{l}_3$ in the summation. For the last equality we used the function $h^2_{l_1 l_2 l_3}$ defined in \\eqref{def:h2_using_gaunt_integral}.\n\nSimilarly, the vector $S$ can be written as\n\\begin{align}\n\tS_i &:= \\tilde{\\vv{B}}^{(i)} \\cdot \\tilde{\\vv{B}}^{obs} \\\\\n\t&= \\sum_{\\vv{l}_1 , \\vv{l}_2 , \\vv{l}_3} \\frac{\\mathcal{G}_{\\vv{L}} b^{(i)}_{L}}{6 \\; C_{l_1} C_{l_2} C_{l_3}} \\left[ a_{\\vv{l}_1} a_{\\vv{l}_2} a_{\\vv{l}_3} - \\left< a_{\\vv{l}_1} a_{\\vv{l}_2} \\right> a_{\\vv{l}_3} - \\left< a_{\\vv{l}_2} a_{\\vv{l}_3} \\right> a_{\\vv{l}_1} - \\left< a_{\\vv{l}_3} a_{\\vv{l}_1} \\right> a_{\\vv{l}_2} \\right].\n\t\\label{eqn:bispectrum_estimation_signal}\n\\end{align}\nWe finally have the least squares estimate of $f_{NL}$ in terms of $F$ and $S$;\n\\begin{align}\n\t\\hat{f}_{NL}^{(i)} = \\sum_j (F^{-1})_{ij} S_j. \\label{eqn:bispectrum_estimation_ols_estimate}\n\\end{align}\n\nOne of the main strengths of the ordinary least squares estimator lies in its \\textit{optimality}; it has the smallest possible variance among all unbiased estimators that are linear in data. That is to say, it saturates the Cramer-Rao bound. Since $\\left< S_i S_j \\right> = F_{ij}$, we have $\\text{Var}(\\hat{f}_{NL}^{(i)}) = (F^{-1})_{ii}$. This value is indeed equal to the Cramer-Rao bound computed from the Fisher information matrix $F$ here.\n\nThe Fisher matrix of the estimator naturally motivates the following definition of an inner product on the space of reduced bispectra.\n\\begin{align}\n\t\\left< \\vv{b}^{(i)}, \\vv{b}^{(j)} \\right> &:= \\sum_L \\frac{h^2_L b^{(i)}_L b^{(j)}_L}{6 \\; C_{l_1} C_{l_2} C_{l_3}}  = F_{ij}.\t\\label{def:bispectrum_estimation_fisher_inner_product}\n\\end{align}\nIn particular, the \\textit{correlation} between two bispectrum shapes can be defined as\n\\begin{align}\n\t\\text{Corr} \\left( \\vv{b}^{(i)}, \\vv{b}^{(j)} \\right) &:= \\frac{ \\left< \\vv{b}^{(i)}, \\vv{b}^{(j)} \\right>}{\\sqrt{ \\left< \\vv{b}^{(i)}, \\vv{b}^{(i)} \\right> \\left< \\vv{b}^{(j)} \\vv{b}^{(j)} \\right> }}.\n\\end{align}\nIf all bispectrum shapes under consideration are uncorrelated with respect to this metric so that $| \\text{Corr}(\\vv{b}^{(i)}, \\vv{b}^{(j)}) | \\ll 1$ whenever $i \\neq j$, then the Fisher matrix $F$ is approximately diagonal and $(F^{-1})_{ii} \\approx (F_{ii})^{-1}$ (no sum over $i$ implied). In this case, the estimated $\\hat{f}_{NL}^{(i)}$s in \\eqref{eqn:bispectrum_estimation_ols_estimate} are identical to the values obtained using a single regressor $\\vv{B}^{(i)}$. In other words, we may analyse individual bispectrum shapes independently.\n\nWe write down the estimator for single shape analysis and restore the shortened indices;\n\\begin{align}\n\t\\hat{f}_{NL} &= \\frac{1}{N} \\sum_{l_j,m_j} \\frac{\\mathcal{G}^{l_1 l_2 l_3}_{m_1 m_2 m_3} b_{l_1 l_2 l_3}}{C_{l_1} C_{l_2} C_{l_3}} \\left[ a_{l_1 m_1} a_{l_2 m_2} a_{l_3 m_3} - 3\\left< a_{l_1 m_1} a_{l_2 m_2} \\right> a_{l_3 m_3} \\right], \\label{eqn:bispectrum_estimator_single_shape} \\\\\n\tN &:= 6F = \\sum_{l_j,m_j} \\frac{h^2_{l_1 l_2 l_3} b^2_{l_1 l_2 l_3}}{C_{l_1} C_{l_2} C_{l_3}}, \\label{eqn:bispectrum_estimator_normalisation_single_shape}\n\\end{align}\nwhere the symmetry in indices was used to combine the linear terms into one. We also defined the normalisation factor $N$ to follow conventions in the literature. \n\n\\subsection{CMB bispectrum estimators}\nThe estimator \\eqref{eqn:bispectrum_estimator_single_shape} can be intimidating. The multipole moments $l$ can go up to $2500$ for the Planck survey \\cite{PlanckCollaboration2013paramters}, meaning that the sum over all possible $l_j, m_j$ contains $\\approx 2.7\\times 10^{15}$ terms.\\footnote{This number was calculated considering the symmetry ($l_1 \\ge l_2 \\ge l_3$), triangle inequality ($l_2+l_3 \\ge l_1$), and restrictions on $m_j$s from angular momentum conservation ($m_1+m_2+m_3=0$). } Direct evaluation of the Gaunt integral $\\mathcal{G}^{l_1 l_2 l_3}_{m_1 m_2 m_3}$ involves calculating Wigner 3-j symbols, which are expensive to compute and store. Not to mention that the number of terms scales as $\\propto l_{max}^5$.\n\nAll known CMB bispectrum estimation methods therefore deploy some ingenious techniques to reduce the computational cost. In this section, we review the three most common approaches: KSW \\cite{Komatsu2005,Creminelli2006limits}, Modal \\cite{Fergusson2010general,Fergusson2012}, and Binned \\cite{Bucher2010,Bucher2016}.\n\n\\subsubsection*{KSW estimator}\nThe Komatsu-Spergel-Wandelt (KSW) estimator was first introduced in \\cite{Komatsu2005} together with a construction of the bispectrum estimator and has been studied extensively since then \\cite{Creminelli2006limits,Babich2005optimal,Creminelli2007estimators} (see e.g, \\cite{Komatsu2010} for reviews). The core idea is to exploit the \\textit{separability} of the bispectrum. Consider the local shape for example:\n\\begin{align}\n\tS^{loc}(k_1, k_2, k_3) = 2A_\\Phi^2 \\left( \\frac{k_1^2}{k_2 k_3} + \\frac{k_2^2}{k_3 k_1} +  \\frac{k_3^2}{k_1 k_2} \\right),\n\\end{align}\nwhere $A_\\Phi$ is amplitude of the power spectrum of $\\Phi$ with the scalar spectral index $n_s$ set to $1$. Note that each term can be expressed as a product of three separate functions that only depend on one of the variables: $k_1^2/(k_2 k_3) = k_1^2 \\cdot k_2^{-1} \\cdot k_3^{-1}$, for example. The reduced bispectrum then simplifies to an integral of separable terms;\n\\begin{align}\n\tb^{loc}_{l_1 l_2 l_3} = 2A^2 \\int dr \\; r^2 \\left[ \\alpha_{l_1}(r) \\beta_{l_2}(r) \\beta_{l_3}(r) + \\beta_{l_1}(r) \\alpha_{l_2}(r) \\beta_{l_3}(r) + \\beta_{l_1}(r) \\beta_{l_2}(r) \\alpha_{l_3}(r) \\right], \\label{eqn:local_reduced_bispectrum}\n\\end{align}\nwhere\n\\begin{align}\n\t\\alpha_l(r) &:= \\frac{2}{\\pi} \\int dk \\; k^2 \\Delta_l(k) j_l(kr), \\label{def:KSW_estimator_alpha}\\\\\n\t\\beta_l(r) &:= \\frac{2}{\\pi} \\int dk \\; k^{-1} \\Delta_l(k) j_l(kr). \\label{def:KSW_estimator_beta}\n\\end{align}\nSubstituting \\eqref{eqn:local_reduced_bispectrum} into the bispectrum estimator \\eqref{eqn:bispectrum_estimator_single_shape} gives\n\\begin{align}\n\t\\hat{f}^{loc}_{NL} = \\frac{6A^2}{N} \\int dr \\; r^2 \\int d^2 \\hat{\\vv{n}} \\; \\left[ A(r,\\hat{\\vv{n}}) B(r,\\hat{\\vv{n}})^2 - 2 \\left <A(r,\\hat{\\vv{n}}) B(r,\\hat{\\vv{n}}) \\right> A(r,\\hat{\\vv{n}}) - \\left< B(r,\\hat{\\vv{n}})^2 \\right> A(r,\\hat{\\vv{n}})  \\right], \\label{eqn:KSW_estimator_local}\n\\end{align}\nwhere we have defined the \\textit{filtered maps}\n\\begin{align}\n\tA(r,\\hat{\\vv{n}}) &:= \\sum_{l,m} \\frac{\\alpha_l(r)}{C_l} a_{lm} Y_{lm}(\\hat{\\vv{n}}), \\label{eqn:KSW_estimator_filtered_map_1}\\\\\n\tB(r,\\hat{\\vv{n}}) &:= \\sum_{l,m} \\frac{\\alpha_l(r)}{C_l} a_{lm} Y_{lm}(\\hat{\\vv{n}}). \\label{eqn:KSW_estimator_filtered_map_2}\n\\end{align}\nThe estimator \\eqref{eqn:KSW_estimator_local} has significantly lower computational complexity compared to the original form. The integral over $\\hat{\\vv{n}}$ becomes a summation over map pixels, roughly 50 million in Planck-like settings. The filtered maps (\\ref{eqn:KSW_estimator_filtered_map_1}-\\ref{eqn:KSW_estimator_filtered_map_2}) are efficiently obtained using Spherical Harmonic Transforms (SHTs).\n\nWe are now only left with the normalisation factor. An integral representation of $h^2_{l_1 l_2 l_3}$ in \\eqref{def:h2_using_legendre_integral} allows a fast computation of $N$, as introduced in \\cite{Smith2011};\n\\begin{align}\n\tN = (2A^2)^2 \\int d\\mu \\int dr \\;r^2 \\int dr' \\; r'^2 \\left[ 3R_{\\alpha\\alpha}^2 R_{\\beta\\beta} + 6R_{\\alpha\\beta} R_{\\beta\\alpha} R_{\\alpha\\alpha} \\right],\n\\end{align}\nwhere\n\\begin{align}\n\tR_{XY} (r,r',\\mu) := \\sum_l \\frac{2l+1}{(8\\pi)^{2/3}} \\; X_l (r) Y_l (r') P_l(\\mu)\n\\end{align}\nfor $X,Y=\\alpha,\\beta$.\n\nThe KSW formalism can be used to constrain various other separable shapes by replacing $\\alpha_l$ and $\\beta_l$ with appropriate functions, which we refer to as \\textit{modes}. The equilateral and orthogonal shapes, for example, call for four such functions with $k^{-1}, 1, k$, and $k^2$ in place of $k^2$ in the integral \\eqref{def:KSW_estimator_alpha}. Constant feature models with shape function $S(k_1,k_2,k_3) = \\sin(\\omega(k_1+k_2+k_3)+\\phi)$ can be written in terms of the two modes $\\sin(\\omega k)$ and $\\cos(\\omega k)$ via trigonometric identities \\cite{Munchmeyer2014}.\n\nIn some cases, a non-separable function can be expanded to separable ones using an analytic formula. For instance, the Schwinger parametrisation\n\\begin{align}\n\t\\frac{1}{(k_1+k_2+k_3)^n} = \\frac{1}{(n-1)!} \\int_0^{\\infty} du \\; u^{n-1} e^{-u(k_1+k_2+k_3)}\n\\end{align}\nallows us to approximate the left hand side with a sum over separable terms parametrised by $u$ \\cite{Smith2011}. These numerical tricks, however, are restricted to cases where the integrand is relatively well-behaved. Otherwise, we require a large number of terms for an accurate expansion, and the trick causes a net increase in computation time instead of a net decrease.\n\n\\subsubsection*{Modal estimator}\nThe KSW estimator is fast and numerically stable but restrictive in the type of bispectra it can tackle. The Modal estimator, first developed in \\cite{Fergusson2010general} and expanded much further through \\cite{Fergusson2012,Fergusson2014,Shiraishi2014parityodd,Shiraishi2019cross}, builds on a simple but effective idea to address this issue; when the bispectrum shape cannot be factorised, we may instead \\textit{expand} it using a basis constructed from separable functions.\n\nThe essence of Modal estimator is captured in the following `modal' expansion;\n\\begin{align}\n\t\\frac{\\nu_{l_1} \\nu_{l_2} \\nu_{l_3}}{\\sqrt{C_{l_1} C_{l_2} C_{l_3}}} \\; b_{l_1 l_2 l_3} = \\sum_{n \\leftrightarrow (p_1,p_2,p_3)} \\alpha_n^Q Q_{n l_1 l_2 l_3}. \\label{eqn:modal_estimator_late_expansion}\n\\end{align}\nThe left hand side is the reduced bispectrum, rescaled using $C_l$s and $\\nu_l := (2l+1)^{1/6}$ for later convenience. On the right hand side is the mode expansion, where each triplet $(p_1,p_2,p_3)$ is associated with a number $n$. $\\alpha_n^Q$ is the expansion coefficient with respect to the basis function $Q$, which is defined as\n\\begin{align}\n\tQ_{n \\; l_1 l_2 l_3} := \\frac{1}{6} \\left[ q_{p_1}(l_1) q_{p_2}(l_2) q_{p_3}(l_3) + q_{p_1}(l_1) q_{p_2}(l_3) q_{p_3}(l_2) + \\cdots \\right],\n\\end{align}\nwith appropriate mode functions $q_p(l)$. Polynomials and Fourier modes are common choices for these mode functions, but the formalism itself is completely general. All we require is that the modal expansion \\eqref{eqn:modal_estimator_late_expansion} accurately describes the given bispectrum.\n\nAs seen from the KSW estimator, separability greatly simplifies \\eqref{eqn:bispectrum_estimator_single_shape}. We define the filtered maps analogous to the KSW ones up to some factors;\n\\begin{align}\n\tM_p (\\hat{\\vv{n}}) = \\sum_{l,m} \\frac{q_p(l)}{\\nu_l \\sqrt{C_l}} a_{lm} Y_{lm}(\\hat{\\vv{n}}), \\label{eqn:modal_estimator_filtered_map}\n\\end{align}\nNote that we do not have the line of sight integral $r$ appearing in the KSW formalism since the mode expansion was performed in the late-time $l$ space, instead of the primordial $k$ space.\n\nThe estimator \\eqref{eqn:bispectrum_estimator_single_shape} now becomes\n\\begin{align}\n\t\\hat{f}_{NL} = \\frac{1}{N} \\sum_{n \\newline \\leftrightarrow (p_1,p_2,p_3)} \\alpha_n^Q \\int d^2 \\vv{n} \\left[ M_{p_1}(\\hat{\\vv{n}}) M_{p_2}(\\hat{\\vv{n}}) M_{p_3}(\\hat{\\vv{n}}) - 3 \\left< M_{p_1}(\\hat{\\vv{n}}) M_{p_2}(\\hat{\\vv{n}}) \\right> M_{p_3}(\\hat{\\vv{n}})  \\right].\n\\end{align}\nOne of the Modal pipeline's key objectives is to compute\n\\begin{align}\n\t\\beta^Q_n := \\int d^2 \\vv{n} \\left[ M_{p_1}(\\hat{\\vv{n}}) M_{p_2}(\\hat{\\vv{n}}) M_{p_3}(\\hat{\\vv{n}}) - 3 \\left< M_{p_1}(\\hat{\\vv{n}}) M_{p_2}(\\hat{\\vv{n}}) \\right> M_{p_3}(\\hat{\\vv{n}})  \\right], \\label{def:modal_estimator_beta}\n\\end{align}\nso that the estimator simply becomes a dot product of $\\alpha$ and $\\beta$: $\\hat{f}_{NL} = \\frac{1}{N} \\sum_n \\alpha^Q_n \\beta^Q_n$. Note that $\\beta_n^Q$ depends on the observed data and choice of basis functions, but is independent of theoretical model in consideration. This is an important property of the Modal estimator; the time-consuming integral of \\eqref{def:modal_estimator_beta} only needs to be performed once per dataset. We can then constrain a wide range of models simultaneously by computing $\\alpha^Q_n$ for each bispectrum shape. The modal decomposition costs much less than the $f_{NL}$ estimation in general.\n\nBefore moving on to calculating the normalisation factor, we first modify the inner product defined in \\eqref{def:bispectrum_estimation_fisher_inner_product} as\n\\begin{align}\n\t\\left< \\vv{b}^{(i)}, \\vv{b}^{(j)} \\right> &:= \\sum_{l_j} \\frac{h^2_{l_1 l_2 l_3}}{\\nu_{l_1}^2 \\nu_{l_2}^2 \\nu_{l_3}^2 } \\; b^{(i)}_{l_1 l_2 l_3} b^{(j)}_{l_1 l_2 l_3}.\n\\end{align}\nThe weights appearing in the inner product above, $(h_{l_1 l_2 l_3}/v_{l_1} v_{l_2} v_{l_3})^2\\approx const.$, are now nearly uniform across the allowed $l$ configurations \\cite{Fergusson2010general}. This serves as a natural inner product for basis functions $\\vv{Q}_n$, especially for polynomial modes.\n\nExpanding the bispectrum in \\eqref{eqn:bispectrum_estimator_normalisation_single_shape} gives\n\\begin{align}\n\tN &= \\sum_{n_1} \\sum_{n_2} \\alpha^Q_{n_1} \\alpha^Q_{n_2} \\left( \\sum_{l_j} \\frac{h^2_{l_1 l_2 l_3}}{\\nu_{l_1}^2 \\nu_{l_2}^2 \\nu_{l_3}^2 } \\; Q_{n_1 \\; l_1 l_2 l_3} Q_{n_2 \\; l_1 l_2 l_3} \\right) \\\\\n\t&= \\sum_{n_1} \\sum_{n_2} \\alpha^Q_{n_1} \\alpha^Q_{n_2} \\left< \\vv{Q}_{n_1}, \\vv{Q}_{n_2} \\right>. \\label{eqn:modal_estimator_normalisation_Q}\n\\end{align}\nAnother key quantity to be computed in the Modal formalism is the matrix\n\\begin{align}\n\t\\gamma_{n_1 n_2} :=  \\left< \\vv{Q}_{n_1} , \\vv{Q}_{n_2} \\right>.\n\\end{align}\nEven if the mode functions $q_p(l)$ are chosen to be orthogonal, the three-dimensional basis functions $\\vv{Q}_n$ are not necessarily orthogonal with respect to the inner product. Once $\\gamma$ is computed, however, we may transform our basis functions to become orthonormal. By definition $\\gamma$ is symmetric and positive semi-definite. As long as we choose the basis $\\vv{Q}_n$s to be linearly independent, $\\gamma$ is always non-degenerate and hence invertible. Since $\\gamma^{-1}$ is also symmetric and positive-definite, we may perform a Cholesky decomposition on it;\n\\begin{align}\n\t\\gamma^{-1} = \\lambda \\lambda^T,\n\\end{align}\nfor some lower triangular matrix $\\lambda$. We now define a new set of basis\n\\begin{align}\n\t\\vv{R}_t := \\sum_n \\lambda_{nt} \\; \\vv{Q}_{n}.\n\\end{align}\nThe new basis functions are now orthonormal with respect to the inner product $\\langle \\cdot,\\cdot \\rangle$;\n\\begin{align}\n\t\\left< \\vv{R}_{t_1} , \\vv{R}_{t_2} \\right> = \\sum_{n_1,n_2} \\lambda_{n_1 t_1} \\left< \\vv{Q}_{n_1} , \\vv{Q}_{n_2} \\right> \\lambda_{n_2 t_2} = (\\lambda^T \\gamma \\lambda)_{t_1 t_2} = \\delta_{t_1 t_2}.\n\\end{align}\nOrthonormality of the basis is especially useful for the modal decomposition. Taking the inner product with $\\vv{R}_t$ in the modal expansion \\eqref{eqn:modal_estimator_late_expansion} for $R$,\n\\begin{align}\n\t\\alpha^R_t = \\left< \\frac{\\nu_{l_1} \\nu_{l_2} \\nu_{l_3}}{\\sqrt{C_{l_1} C_{l_2} C_{l_3}}} \\; b_{l_1 l_2 l_3} \\;,\\; \\vv{R}_t \\right>.\n\\end{align}\nAfter we obtain $\\alpha^R_t$, the expansion coefficients for $\\vv{Q}_n$ can be found by\n\\begin{align}\n\t\\alpha^Q_n = \\sum_t \\lambda_{nt} \\alpha^R_t,\n\\end{align}\nfrom which it is straightforward to check $\\sum_n \\alpha^Q_n \\vv{Q}_n = \\sum_t \\alpha^R_t \\vv{R}_t$. There is no new information gained from converting our basis from $\\vv{Q}$ to $\\vv{R}$; it is simply a change of basis.\n\nThe normalisation factor in \\eqref{eqn:modal_estimator_normalisation_Q} further simplifies when we use $R$;\n\\begin{align}\n\tN = \\sum_{t_1} \\sum_{t_2} \\alpha^R_{t_1} \\alpha^R_{t_2} \\left< \\vv{R}_{t_1}, \\vv{R}_{t_2} \\right> = \\sum_t \\left| \\alpha^R_{t} \\right|^2 \\label{eqn:modal_estimator_normalisation_R}\n\\end{align}\n\n\\hspace{10pt}\n\nSo far, we have been working on the late-time harmonic space directly related to the CMB observations. The theoretical bispectrum $B(k_1,k_2,k_3)$ predicted by inflation models, however, lies within the primordial Fourier space. The remaining work is about how to bridge this gap. In particular, we would like to obtain $\\alpha^R$ from a given shape function $S(k_1,k_2,k_3) = (k_1 k_2 k_3)^2 B(k_1, k_2, k_3)$ so that we can get an $f_{NL}$ estimate for $S(k_1,k_2,k_3)$.\n\nThe primordial and late-time spaces are treated symmetrically in the Modal formalism. We expand the shape function using an independent set of \\textit{primordial} basis functions;\n\\begin{align}\n\t&S(k_1,k_2,k_3) = \\sum_n \\bar{\\alpha}^{\\bar{Q}}_n \\bar{Q}_n (k_1, k_2, k_3), \\hspace{0.05\\textwidth} \\text{where}\\\\\n\t\\bar{Q}_{n} (k_1, k_2, k_3) := &\\frac{1}{6} \\left[ \\bar{q}_{p_1}(k_1) \\bar{q}_{p_2}(k_2) \\bar{q}_{p_3}(k_3) + \\bar{q}_{p_1}(k_1) \\bar{q}_{p_2}(k_3) \\bar{q}_{p_3}(k_2) + \\cdots \\right].\n\\end{align}\nA bar is placed above each variable to denote that they are primordial quantities. The inner product is defined following \\cite{Fergusson2010general};\n\\begin{align}\n\t\\left< S^{(i)}, S^{(j)} \\right> &:= \\int_{V_\\vv{k}} dk_1 dk_2 dk_3 \\; \\frac{1}{k_1+k_2+k_3} \\; B^{(i)}(k_1, k_2, k_3) B^{(j)}(k_1, k_2, k_3).\n\\end{align}\nThe mathematical formulation from here on is identical to that of the late-time case. We therefore simply write down the primordial counterparts;\n\\begin{align}\n\t\\bar{\\gamma}_{n_1 n_2} &:=  \\left< \\bar{\\vv{Q}}_{n_1} , \\bar{\\vv{Q}}_{n_2} \\right> \\\\\n\t\\bar{\\gamma}^{-1} &= \\bar{\\lambda} \\bar{\\lambda}^T \\\\\n\t\\bar{\\vv{R}}_t &:= \\sum_n \\bar{\\lambda}_{nt} \\; \\bar{\\vv{Q}}_{n} \\\\\n\t\\bar{\\alpha}^{\\bar{R}}_t &= \\left< S(k_1,k_2,k_3) \\;,\\; \\bar{\\vv{R}}_t \\right> \\\\\n\t\\bar{\\alpha}^{\\bar{Q}}_n &= \\sum_t \\bar{\\lambda}_{nt} \\bar{\\alpha}^{\\bar{R}}_t.\n\\end{align}\n\nA key step in connecting primordial results to late-time is the projection via transfer functions \\eqref{def:reduced_bispectrum}. Projecting $\\bar{Q}_n(k_1,k_2,k_3)$ yields\n\\begin{align}\n\t\\tilde{Q}_{n \\; l_1 l_2 l_3} := \\left( \\frac{2}{\\pi} \\right)^3 \\int dr dk_1 dk_2 dk_3 \\left(r k_1 k_2 k_3 \\right)^2 \\bar{Q}_n (k_1, k_2, k_3) \\prod_{j=1}^{3} \\left[ j_{l_j} (k_j r) \\Delta_{l_j} (k_j) \\right],\n\\end{align}\nwhere a tilde indicates that it is a projected quantity, as opposed to a bar for primordial quantities and none for inherently late-time variables. \n\nThe following inner product serves as the bridge between objects defined in early and late universe which all of us have been waiting for:\n\\begin{align}\n\t\\Gamma_{tn} = \\left< \\vv{R}_{t}, \\tilde{\\vv{Q}}_n \\right>.\n\\end{align}\nBy the virtue of the projected bispectrum's dual representation,\n\\begin{align}\n\t\\sum_t \\alpha^R_t R_{n \\; l_1 l_2 l_3} = \\frac{\\nu_{l_1} \\nu_{l_2} \\nu_{l_3}}{\\sqrt{C_{l_1} C_{l_2} C_{l_3}}} \\; b_{l_1 l_2 l_3} = \\sum_n \\bar{\\alpha}^{\\bar{Q}}_n \\tilde{Q}_{n \\; l_1 l_2 l_3}.\n\\end{align}\nTaking an inner product with $\\vv{R}_t$ on both size gives, at last,\n\\begin{align}\n\t\\alpha^R_t = \\sum_n \\Gamma_{tn} \\bar{\\alpha}^{\\bar{Q}}_n.\n\\end{align}\nThe matrix $\\Gamma$ therefore lets us convert the primordial modal expansion coefficients $\\bar{\\alpha_n}^{\\bar{Q}}$ to the late time ones $\\alpha_t^{R}$.\n\n\\hspace{10pt}\n\nWe have discussed the inner workings of the Modal estimator in great detail. Despite the long list of formulae here, the core idea of it is captured in the modal decomposition \\eqref{eqn:modal_estimator_late_expansion}. The main computational challenge in the Modal approach is precomputing $\\vv{\\beta}^Q$, which contains complete information about the fit between the basis and observed bispectrum. Afterwards, the bispectrum estimation problem reduces down to a matter of finding the modal coefficients $\\vv{\\alpha}$ for models under consideration. This decomposition is performed fast and efficiently using the orthonormal basis functions $\\vv{R}$ and $\\bar{\\vv{R}}$.\n\n\\subsubsection*{Binned estimator}\n\nThe binned bispectrum estimator, introduced in \\cite{Bucher2010} and used for Planck analyses \\cite{PlanckCollaboration2013,PlanckCollaboration2015,PlanckCollaboration2018,Bucher2016}, uses carefully chosen bins to reduce the computational complexity. In this section we highlight the main concepts of the formalism while relabelling some notations in the original literature \\cite{Bucher2010} in order to be consistent with our previous discussions.\n\nThe estimator \\eqref{eqn:bispectrum_estimation_signal} can be rewritten as \n\\begin{align}\n\tS_i &= \\sum_{l_1 l_2 l_3}  \\frac{b^{(i)}_{l_1 l_2 l_3}}{6 \\; C_{l_1} C_{l_2} C_{l_3}} \\sum_{m_1 m_2 m_3} \\mathcal{G}^{l_1 l_2 l_3}_{m_1 m_2 m_3} \\left[ a_{l_1 m_1} a_{l_2 m_2} a_{l_3 m_3} - \\left( \\left< a_{l_1 m_1} a_{l_2 m_2} \\right> a_{l_3 m_3} + \\text{2 cyc.} \\right) \\right] \\\\\n\t&= \\sum_{l_1 l_2 l_3}  \\frac{b^{(i)}_{l_1 l_2 l_3}}{6 \\; C_{l_1} C_{l_2} C_{l_3}} \\int d^2 \\hat{\\vv{n}} \\; \\left[ M_{l_1} (\\hat{\\vv{n}}) M_{l_2} (\\hat{\\vv{n}}) M_{l_3} (\\hat{\\vv{n}}) - \\left( \\left< M_{l_1} (\\hat{\\vv{n}}) M_{l_2} (\\hat{\\vv{n}}) \\right> M_{l_3} (\\hat{\\vv{n}}) + \\text{2 cyc.}\\right)  \\right], \\label{eqn:binned_estimator_formulation_1}\n\\end{align}\nwhere $M_l$s analogous to the filtered maps of the KSW and Modal estimators are defined as\n\\begin{align}\n\tM_l(\\hat{\\vv{n}}) := \\sum_{m=-l}^{l} a_{lm} Y_{lm}(\\hat{\\vv{n}}).\n\\end{align}\nThey correspond to the $l$-multipole component of the original map. We define the observed bispectrum $B^{obs}_{l_1 l_2 l_3}$ to be the integrand of \\eqref{eqn:binned_estimator_formulation_1}.\\footnote{This is the convention from the original literature \\cite{Bucher2010}, which is different to some conventions elsewhere by a factor of $h_{l_1 l_2 l_3}$. In terms of the theoretical reduced bispectrum $b_{l_1 l_2 l_3}$, we have $\\langle B^{obs}_{l_1 l_2 l_3} \\rangle = h^2_{l_1 l_2 l_3} b^{th}_{l_1 l_2 l_3}$.}\n\nThe core idea of this formulation is based on the fact that $a_{lm}$s with similar $l$s are distributed in a comparable fashion, and can be binned without a big loss of information. The multipole moments $l$ in the range $[l_{min},l_{max}]$ are divided into $N_{bin}$ intervals $\\Delta_i := [l_i,l_{i+1}-1]$, where $i=0,1,\\cdots,N_{bins}-1$.  The filtered map corresponding to the $i$th bin is given by\n\\begin{align}\n\t\tM_i(\\hat{\\vv{n}}) := \\sum_{l\\in\\Delta_i}\\sum_{m=-l}^{l} a_{lm} Y_{lm}(\\hat{\\vv{n}}).\n\\end{align}\nThe binned bispectrum take the form\n\\begin{align}\n\tB^{obs}_{i_1 i_2 i_3} = \\frac{1}{\\Xi_{i_1 i_2 i_3}} \\int d^2 \\hat{\\vv{n}} \\; \\left[ M_{i_1} (\\hat{\\vv{n}}) M_{i_2} (\\hat{\\vv{n}}) M_{i_3} (\\hat{\\vv{n}}) - \\left( \\left< M_{i_1} (\\hat{\\vv{n}}) M_{i_2} (\\hat{\\vv{n}}) \\right> M_{i_3} (\\hat{\\vv{n}}) + \\text{2 cyc.}\\right)  \\right],\n\\end{align}\nwhere $\\Xi_{i_1 i_2 i_3}$ counts the number of allowed $(l_1,l_2,l_3)$ triplets in the bin $(\\Delta_{i_1},\\Delta_{i_2},\\Delta_{i_3})$ satisfying the triangle inequality and parity condition $l_1+l_2+l_3 \\in 2\\mathbb{Z}$. We further impose that $i_1,i_2$, and $i_3$ are ordered in a way that $i_1 \\le i_2 \\le i_3$.\n\nWe now compute the expected variance of the binned bispectrum. Assuming that the covariance matrix of the $a_{lm}$s is diagonal, calculations similar to \\eqref{eqn:bispectrum_variance_contractions1} yield\n\\begin{align}\n\t\\langle B^{obs}_{i_1 i_2 i_3} B^{obs}_{i'_1,i'_2,i'_3} \\rangle &=  \\delta_{i_1 i'_1} \\delta_{i_2 i'_2} \\delta_{i_3 i'_3} \\; \\frac{g_{i_1 i_2 i_3}}{(\\Xi_{i_1 i_2 i_3})^2} \\sum_{l_1 \\in \\Delta_{i_1}} \\sum_{l_2 \\in \\Delta_{i_2}} \\sum_{l_3 \\in \\Delta_{i_3}} h^2_{l_1 l_2 l_3} C_{l_1} C_{l_2} C_{l_3} \\\\\n\t&=: \\delta_{i_1 i'_1} \\delta_{i_2 i'_2} \\delta_{i_3 i'_3} \\; V_{i_1 i_2 i_3},\n\\end{align}\nfor some $V_{i_1,i_2,i_3}$. The symmetry factor $g_{i_1 i_2 i_3}=6,2,$ and $1$ for 3, 2, and no identical numbers within $i_1,i_2,i_3$, respectively.\n\nWe write the theoretical binned bispectrum as\n\\begin{align}\n\tB^{th}_{i_1 i_2 i_3} =  \\frac{1}{\\Xi_{i_1 i_2 i_3}} \\sum_{l_1 \\in \\Delta_{i_1}} \\sum_{l_2 \\in \\Delta_{i_2}} \\sum_{l_3 \\in \\Delta_{i_3}} h^2_{l_1 l_2 l_3} h^2_{l_1 l_2 l_3} b^{th}_{l_1 l_2 l_3}, \\label{eqn:binned_estimator_theoretical_bispectra}\n\\end{align}\nwhere $b^{th}$ is the usual reduced bispectrum. Then the binned estimator takes the form\n\\begin{align}\n\t&\\hat{f}_{NL} = \\frac{\\langle \\vv{B}^{obs}, \\vv{B}^{th} \\rangle}{\\langle \\vv{B}^{th}, \\vv{B}^{th} \\rangle}, \\;\\;\\;\\;\\text{where} \\\\\n\t&\\langle \\vv{B}^{(1)}, \\vv{B}^{(2)} \\rangle = \\sum_{i_1 \\le i_2 \\le i_3} \\frac{B^{(1)}_{i_1 i_2 i_3} B^{(2)}_{i_1 i_2 i_3}}{V_{i_1 i_2 i_3}}. \\label{eqn:binned_estimator_inner_product}\n\\end{align}\nThe ordering $i_1 \\le i_2 \\le i_3$ can be removed similarly as before by replacing $g_{i_1 i_2 i_3}$ in the denominator of \\eqref{eqn:binned_estimator_inner_product} with $6$.\n\nBinning different multipoles together inevitably causes some information loss and hence increases the variance of the final estimate. This effect is quantified by the ratio\n\\begin{align}\n\tR := \\frac{\\text{Var}(\\hat{f}^\\text{ideal}_{NL})}{\\text{Var}(\\hat{f}^\\text{binned}_{NL})} = \\frac{\\langle \\vv{B}^{th}, \\vv{B}^{th} \\rangle^\\text{binned}}{\\langle \\vv{B}^{th}, \\vv{B}^{th} \\rangle^\\text{no binning}}, \n\\end{align}\nwhich always lies between $0$ and $1$. As long as $R$ is close to $1$, the binned estimator performs just as well as the full bispectrum estimator.\n\nThe main advantage of the binned estimator is the significant reduction in the computational complexity. Using optimised binning strategies outlined in \\cite{Bucher2016}, this can be done with minimal loss of information. The Binning formalism works particularly well for models with smooth bispectra or features in $l$-space. The full binned bispectrum can also be used for non-parametric studies of non-Gaussianity from observations after certain smoothing operations. It is also worth noting that the most computationally expensive part of the estimation process\\textemdash obtaining $B^{obs}_{i_1 i_2 i_3}$\\textemdash only needs to be done once per dataset. The result can then be used to constrain various models instantaneously as long as their theoretical bispectra are provided.\n\nMeanwhile, the binned estimator is not as effective for constraining models with general features or oscillations. This is not only because the binning smooths out high-frequency oscillations in the bispectrum, but also since evaluating the theoretical bispectra in $l$ space through \\eqref{eqn:binned_estimator_theoretical_bispectra} becomes numerically challenging. The reduced bispectrum needs to be computed for every $(l_1,l_2,l_3)$ triplet and then summed over within each bin. Such computation of the bispectrum is often practically intractable unless the given shape is separable. For the same reason, the binned estimator struggles to constrain non-separable shapes, even though the formalism itself applies to any shape.\n\n\n\\subsection{Other sources of non-Gaussianity.} \\label{section:other_sources_of_non_gaussianity}\n\nThe CMB is one of the cleanest probes of the primordial bispectrum. CMB anisotropy remains linear in initial perturbations to a very good approximation so that its bispectrum contains little contribution from non-linear evolution. Regardless, there are non-primordial sources of non-Gaussianity that requires close attention. In this section, we discuss both physical and experimental complications to the CMB bispectrum estimation. Instrumental effects including the measurement noise and the width of the probing beam will be covered in the next chapter (Section \\ref{section:beam_and_noise}).\n\n\n\\subsubsection*{Lensing bispectrum}\n\nAfter its departure from the last scattering surface, the CMB photons travel through the perturbed universe until they reach us. Overdense regions on their path act as gravitational lenses and alter the trajectories, which leave observable imprints to the CMB map. Overdensities magnify the CMB around them and thus shift the power spectrum towards larger scales. The deflection $\\vv{\\alpha}$ away from observation angle $\\hat{\\vv{n}}$ can be computed from the line-of-sight integral given by \n\\begin{align}\n\t\\vv{\\alpha} = - 2\\int_0^{\\chi_*} d\\chi \\; \\frac{\\chi_* - \\chi}{\\chi_* \\chi} \\nabla_{\\hat{\\vv{n}}} \\Psi_W (\\chi\\hat{\\vv{n}}; \\eta_0-\\chi), \n\\end{align}\nwhere the Weyl potential $\\Psi_W = (\\Psi + \\Phi)/2$ is defined as the average of two Newtonian potentials. The integral is performed along the unperturbed path, an assumption known as the Born approximation. This is valid as long as the deflection angle $\\vv{\\alpha}$ remains small. The angular derivative $\\nabla_{\\hat{\\vv{n}}}$ is taken orthogonal to $\\hat{\\vv{n}}$ and within the tangent plane on the sphere. The integration weight quantifies how earlier deflections cause greater displacements in the sky today. However, most contributions to the integral in fact come from the late-time universe with redshift $z\\lessapprox2$. We define the \\textit{lensing potential} as\n\\begin{align}\n\t\\psi := - 2\\int_0^{\\chi_*} d\\chi \\; \\frac{\\chi_* - \\chi}{\\chi_* \\chi}  \\Psi_W (\\chi\\hat{\\vv{n}}; \\eta_0-\\chi), \\label{def:lensing_potential}\n\\end{align}\nso that $\\vv{\\alpha}(\\hat{\\vv{n}}) = \\nabla_{\\hat{\\vv{n}}} \\psi$ in our regime. $\\psi$ is a secondary observable of the CMB which opens up a whole field by itself. We refer to \\cite{Bartelmann2001weaklensing,Lewis2006weaklensing,Hanson2010weaklensing} for detailed reviews on the topic of CMB lensing, including derivations of the equations above.\n\nAnother significant late-time contribution to CMB anisotropy comes from the Integrated Sachs-Wolfe (ISW) effect. This is the last term in \\eqref{eqn:line_of_sight_solution_approximated} with a simple relabelling of variables:\n\\begin{align}\n\t\\Theta_{ISW}(\\eta_0,\\vv{x}_0, \\hat{\\vv{n}}) = 2\\int_0^{\\chi_*} d\\chi \\; \\Psi'_W (\\chi\\hat{\\vv{n}}; \\eta_0-\\chi). \\label{eqn:ISW_effect}\n\\end{align}\nThe integrand is small except during the accelerated expansion phase at low redshift, again $z\\lessapprox2$. The two integrals \\eqref{def:lensing_potential} and \\eqref{eqn:ISW_effect} are highly correlated through $\\Psi_W$ and thus generate a non-trivial bispectrum, mainly in the squeezed limit. This lensing-ISW bispectrum is well approximated by the template given by \\cite{Lewis2011lensing};\n\\begin{align}\n\tb^{lens}_{l_1 l_2 l_3} = \\frac{1}{2}\\left[ l_1 (l_1 + 1) - l_2 (l_2 + 1) + l_3 (l_3 + 1) \\right] \\tilde{C}_{l_1}^{TT} C_{l_3}^{T\\psi} + \\text{5 perms.}, \\label{eqn:lensing_bispectrum_template}\n\\end{align}\nwhere $\\tilde{C}^{TT}_l$ is the \\textit{lensed} angular power spectrum and $C^{T\\psi}_l$ is the cross power spectrum between temperature ($T$) and $\\psi$. Assuming the standard $\\Lambda$CDM cosmology we expect to find the bispectrum above in the CMB without any additional factors. We can measure its amplitude in the CMB data through the usual bispectrum estimator \\eqref{eqn:bispectrum_estimator_single_shape}-\\eqref{eqn:bispectrum_estimator_normalisation_single_shape} by setting $\\vv{b} = \\vv{b}^{lens}$ so that $\\hat{f}^{lens}_{NL} = \\langle \\vv{b}^{lens}, \\; \\vv{b}^{obs} \\rangle / \\langle \\vv{b}^{lens}, \\; \\vv{b}^{lens} \\rangle$, where we used the inner product $\\langle \\cdot,\\cdot \\rangle$ from \\eqref{def:bispectrum_estimation_fisher_inner_product}. This value has been first detected in the Planck 2013 analysis to $2.5\\sigma$ level \\cite{PlanckCollaboration2013ISW}. The most recent Planck analysis estimates $f^{lens}_{NL} = 0.73 \\pm 0.27$ (68\\% CL) using the SMICA foreground-cleaned CMB temperature maps \\cite{PlanckCollaboration2018}.\n\nThe lensing-ISW bispectrum is an observable caused by the non-linear evolution of the CMB. When studying primordial contributions to the observed bispectrum, however, such late-time effects need to be subtracted. The lensing-ISW \\textit{bias} is given by\n\\begin{align}\n\t\\Delta f_{NL}^{(t)} = \\frac{ \\langle \\vv{b}^{(t)}, \\; \\vv{b}^{lens} \\rangle }{ \\langle \\vv{b}^{(t)}, \\; \\vv{b}^{(t)} \\rangle} \\label{eqn:lensing_ISW_bias}\n\\end{align}\nfor the bispectrum template $\\vv{b}^{(t)}$ of interest. This bias can be significant for templates with large squeezed limit, such as the local template, since they are highly correlated with the lensing-ISW bispectrum \\eqref{eqn:lensing_bispectrum_template}.\n\n\n\\subsubsection*{Sky mask and inpainting}\n\nCMB measurements are affected by various foreground contaminants. A number of component separation methods such as SMICA \\cite{Cardoso2008component}, NILC \\cite{Basak2012nilc}, SEVEM \\cite{Martinez2003sevem}, and Commander \\cite{Eriksen2008commander} have been developed to clean unwanted signals from data \\cite{PlanckCollaboration2018component}, but some regions with an overwhelming amount of contaminations need to be \\textit{masked} away. The corresponding parts of the sky are simply removed from any analysis. Even in a full-sky survey like Planck, only $\\approx 78\\%$ of the sky can be used for science \\cite{PlanckCollaboration2018component}.\n\nThe partial sky coverage due to masks induces multiple complications. For the CMB bispectrum analysis there are two main issues to manage. First, statistical isotropy of the data is broken due to the irregular mask shape. The covariance matrix $C_{l_1 m_1, l_2, m_2} = \\langle a^*_{l_1 m_1} a_{l_2 m_2} \\rangle$ is no longer diagonal. Using the full covariance matrix can be costly for bispectrum analysis, but the linear part of the bispectrum estimator introduced in \\eqref{def:bispectrum_estimate_including_linear} can handle most of the errors caused by off-diagonal covariances.\n\nSecond, the sky mask generates a non-vanishing bispectrum by itself which introduces additional noise in the estimation. Sharp cuts around the edges of the mask induce some high-frequency signals. A low-frequency mode from the overall mask shape then correlates with them to produce bispectrum in squeezed configurations. We follow \\cite{Gruetjen2017inpainting} and utilise a simple inpainting method to reduce the effect. In this approach, a linear diffusive method is used to interpolate and hence smoothen the mask edges; at each iteration, every pixel within previously masked regions takes the average value of its neighbouring pixels. The resulting inpainted map after a sufficient number of iterations is shown to contain little excess contamination from the mask. \n\nLastly, we note that not all contaminants can be masked away, especially if they are localised and scattered. As detailed in \\cite{PlanckCollaboration2013}, extra-Galactic point sources such as synchrotron emission and thermal emission from dust appear in the measured CMB data. Their reduced bispectrum is expected to be constant. Similarly to the case of the lensing bispectrum, these bispectrum contributions from point sources bias the $f_{NL}$ estimates and therefore need to be subtracted off. We use the bias given in \\eqref{eqn:lensing_ISW_bias} with $\\vv{b}^{PS}=1$ instead of $\\vv{b}^{lens}$ to account for this effect.\n\n\\newpage\n\\section*{Summary}\n\nIn this chapter, we introduced the theory of the bispectrum and explained why it is a key quantity for testing inflation against the CMB data. We first outlined how to compute the primordial bispectrum from the inflationary Lagrangian using the in-in formalism. The bispectrum is expected to be unobservably small for the simplest single-field, slow-roll inflation with a canonical kinetic term and Bunch-Davies vacuum. However, we showed using an example of a non-canonical kinetic term that breaking some of these assumptions can induce detectable non-Gaussianity with distinct shapes. Moving on to the late-time universe, we reviewed the theory of CMB bispectrum estimation while keeping an analogy to linear regression in mind. It was noted that the high-dimensional integrals appearing in the bispectrum estimator are computationally expensive and numerically challenging. Exploiting separability is the key to reducing computational complexity. We detailed the three main estimators used in the latest Planck analysis: KSW, Modal and binned.\n\nNo observations so far have found statistically significant non-Gaussianity of primordial origin. In the most recent Planck analysis however, there were some interesting `hints' from some oscillatory shapes that appear in the feature and resonance type models. The signal has not yet been decisive after accounting for the look-elsewhere effect \\cite{Fergusson2015b,PlanckCollaboration2018}. The constraining power of these oscillatory models has benefited considerably from inclusion of the E-mode polarisation data in the Planck analysis and are expected to improve further in the future CMB experiments with enhanced polarisation sensitivity. We present a forecast for oscillatory models in Chapter \\ref{chapter:CMB_state-4_forecast}.\n", "meta": {"hexsha": "3192bf72f1da42af1d612a62892a27d7f2140ded", "size": 89057, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapter3/chapter3.tex", "max_stars_repo_name": "Wuhyun/Thesis", "max_stars_repo_head_hexsha": "414d67052a60cf32cf69d533c40c05af7b42308d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter3/chapter3.tex", "max_issues_repo_name": "Wuhyun/Thesis", "max_issues_repo_head_hexsha": "414d67052a60cf32cf69d533c40c05af7b42308d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter3/chapter3.tex", "max_forks_repo_name": "Wuhyun/Thesis", "max_forks_repo_head_hexsha": "414d67052a60cf32cf69d533c40c05af7b42308d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 129.068115942, "max_line_length": 1051, "alphanum_fraction": 0.7206395904, "num_tokens": 30009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.31331261199117677}}
{"text": "%\\graphicspath{{13-procex/small_images/}}\n\\graphicspath{{13-procex/images/}}\n\n\\chapter{Procedural Extrusions}\n\\label{c:procex}\n\n\\greybox{This section is based on the paper \\emph{Interactive Architectural Modeling with Procedural Extrusions}\\cite{twak11}, co-authored with Peter Wonka.}\n\n\n%-------------------------------------------------------------------------\n\\section{Introduction}\n\n\n\nGiven the contribution of the skeleton to the success of modeling city block subdivision, a natural question is to ask which other urban domains it may contribute to the modeling of? \n\nRecall again the urban procedural modeling pipeline of Fig.~\\ref{fig:umPipeline}, in which streets subdivide land into blocks, algorithms such as those in the previous chapter divide the blocks into parcels, parcels are converted to footprints, and footprints are used to create mass models of buildings. Here we are interested in the final stage of this waterfall pipeline, creating solid 3D buildings from 2D footprints. To do this procedurally, that is for an arbitrary footprint or plan, without programming is the challenge we address here. To approach this problem we take inspiration from artists' plan and elevation drawings, and the flexibility of the mixed weighted straight skeleton of Chapter 3. The combination of these techniques allows us to interactively create robust 3D procedural models parameterised by the footprints. \n\n\n\nWe introduce an application of the MWSS to the interactive procedural modeling of architectural forms. The \\emph{procedural extrusion} (PE) system procedurally generates solid 3D meshes by extruding building footprints. Such an application of the straight skeleton to the creation of architectural surfaces allows for the generation of difficult architectural surfaces such as curved roofs, overhanging roofs, dormer windows, interior dormer windows, roof constructions with vertical walls, buttresses, chimneys, bay windows, columns, pilasters, and alcoves. The system comprises of a user interface to specify procedural extrusions manually as well as a tool for the automated generation of large procedural cityscapes from their footprints. Extensions to the the sweep plane algorithm of Chapter~\\ref{c:various_skels} are utilised to robustly compute a wide range of two-manifold architectural surfaces.\n\n\nThe procedural extrusion system is both an interactive and procedural modeling tool for such architectural surfaces. Procedural geometric modeling offers several advantages over traditional static modeling of architectural forms. PGM descriptions of objects allow us to edit meshes at a higher semantic level; for example, editing wall angles rather than vertex coordinates, whilst ensuring constraints are enforced, such as polygon planarity. Additionally we can preserve subsequent edits while allowing earlier edits to be modified; such as changing the slope of a roof after a chimney has been created upon it, without adjusting the chimney. Nevertheless, the biggest advantage of procedural modeling over static modeling is the creation of large scale cityscapes, without a proportional increase in designer effort. Many of the current PGM systems, such as CGA Shape\\cite{Pascal06}, require end user programming. In contrast, the PE system provides an interactive graphical tool, instead of a programming language, to specify geometry. This lowers the barriers of entry to PGM, allowing more people to create procedural content.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=1.0\\columnwidth]{SingleHouse.png}\n  \\caption[A house created using procedural extrusions.]{\\label{fig:SingleHouse}\nProcedural extrusions allow a footprint (2d plan) to be extruded to form the walls and roof of a house (inset). Meshes and procedural details can then be attached (main).}\n\\end{figure}\n\nArchitectural surfaces are often deeply concave and contain complex architectural features such as overhanging roofs, dormer windows, interior dormer windows, roof constructions with vertical walls, buttresses, chimneys, bay windows, columns, pilasters, and alcoves. These intricate surfaces have not previously been available as watertight meshes in procedural environments. Systems such as shape grammars\\cite{Stiny80,Mueller:2006:PMB,Lipp:2008:IEV} have tended to concentrate on the combinatorial, rather than the geometric aspects of architecture generation, and are not able to generate such geometry themselves. Typically these systems rely on pre-existing meshes that are instanced, positioned, and scaled to appropriate locations.\n\nGiven buildings, such as in Fig.~\\ref{fig:two_profiles}, it is not obvious how to construct 3D models of these structures. Procedural extrusions provide a novel parametrisation of such buildings by taking inspiration from architects' drawings consisting of floorplans and elevations. \n\n\\begin{figure}\n  \\centering\n  \\def\\svgwidth{1.0\\columnwidth}\n  \\includesvg{13-procex/images/two_profiles}\n  \\caption[Plans and profiles of two architectural models]{\\label{fig:two_profiles}\n  These two examples show architectural surfaces overlayed with the user input. Plans (green), profiles (blue), natural steps (orange) and offset events (red) are specified in the user interface. The output of our system is an architectural shell (grey). }\n\\end{figure}\n\nThe first major component of the system is presented in Sec.~\\ref{sec:UI} and allows the user to interactively draw a floorplan, and assign an arbitrary profiles to each plan edge. Nested sets of plans and profiles allow features such as dormer windows and alcoves (Fig.~\\ref{fig:two_profiles}, orange) to be modeled. Interactive modeling via the user interface allows the expressiveness of the system to be explored in depth. We evaluate the interactive portion of the PE system in Sec.~\\ref{Sec:Evaluation} by modeling $50$ various structures from a catalogue, as well as seeking opinions from users as to the properties of the system.\n\nIn order to combine arbitrary plans and profiles, the second component of the system is a collection of algorithms to construct 3D meshes from the specified plans and profiles. These algorithms utilise a variety of repeated applications of the MWSS (Chapter~\\ref{c:various_skels}, Sec.~\\ref{sec:mwss}) to create a geometry modeling system. We take the sweep-plane that is used to calculate the MWSS and introduce additional types of user specified events. These algorithms are presented in Sec.~\\ref{sec:method}. To study the real-world stability of these algorithms we evaluate PEs over a large scale data of $6000$ building footprints in Sec.~\\ref{Sec:Evaluation}. Here we note that the computational geometry community emphasises provably correct algorithms and therefore often favours rational arithmetic. In contrast, our work consists of heuristic algorithms that emphasise computational speed and are geared towards a floating point implementation. While our heuristics include various mechanisms to make the results more robust, it is possible that the computations can fail. For example, in the Atlanta data set of $6000$ footprints we noted that two roof planes were not computed correctly. The approximate nature of our floating point computation also results in roof planes being moved by millimetres.\n\nWe conclude  with a description of external applications to which others have successfully applied components of the PE system.\n\nThe contributions of our work are:\n\\begin{itemize}\n\\item the design of the system and tools to enable procedural modeling of complex architectural surfaces.\n\\item the set of tool choices to enable procedural modeling of complex architectural surfaces.\n\\item heuristic algorithms to generate a polygonal mesh from the user specification that is approximately consistent with the input data.\n\\item the evaluation of the system on a collection of examples to verify its practical utility, and to identify configurations that are difficult to model with our tools.\n\\end{itemize}\n\n\n%-------------------------------------------------------------------------\n\\section{Related work}\n%\\section{Similar Techniques}\n\\label{sec:alternatives}\n\nIn this section we describe and examine some common techniques applied to architectural modeling and analyse some of the properties of the resulting architectural meshes. \n\nWe may make the observation that many architectural and man-made objects have a common property: \\emph{There are many horizontal edges to the geometry, and the faces between such edges are rectangular and coplanar}. For example Fig.~\\ref{fig:horiz_lines} shows one building with many horizontal edges and associated faces.\n\n\\begin{figure}\n  \\centering\n  \\def\\svgwidth{1.0\\columnwidth}\n  \\includesvg{13-procex/images/horiz_lines}\n  \\caption[Horizontal edges are common in architectural form]{\\label{fig:horiz_lines}In many buildings' geometries, there are many horizontal edges (green). Many faces of such geometry are coplanar to one or two such edges. In this case, only the red faces do not do not have such a horizontal edge.}\n\\end{figure}\n\nThere are several properties that we find desirable in computer models of architectural structures. We assume to use polygonal mesh models, since these are common, somewhat standard in industry, and are those which hardware (GPU) acceleration is designed to accommodate. ``Nice'' 3D meshes commonly have the following properties: \n\\begin{itemize}\n\\item{Planar faces: Each face lies entirely within a single plane.}\n\\item{Water-tight: There are no holes in the mesh, all adjacent faces are connected via a shared edge, and all adjacent edges are connected via a shared vertex.}\n\\item{No self-intersections: No part of the mesh protrudes through another; the only parts of the mesh that touch are adjacent in the mesh data structure.}\n\\end{itemize} \n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=1.0\\columnwidth]{googleWarehouseComp.png}\n  \\caption[Examples of buildings modeled in Sketchup]{\\label{fig:googleWarehouseComp} Several typical building meshes created using Sketchup\\cite{Sketchup}, and found in Trimble Warehouse\\cite{GoogleWarehouse} using the search ``Victorian house''. From left to right the buildings were created by users wiccan, DILBERT, bob1938, Paulwall and bob1938. Buildings have had garden geometry and textures removed to allow comparison with our results. \\copyright 2013 Google.}\n\\end{figure}\n\n\nTo describe such meshes, basic 3D modeling tools such as as those introduced in Sec.~\\ref{sec:construction} may be used. Tools such as manual vertex modeling, extrusion, lofting, and constructive solid geometry have all been used to model architecture in 3D modeling tools such as Maya\\cite{Maya}, Sketchup\\cite{Sketchup}, and Blender\\cite{Blender}. Several examples of buildings created with the Sketchup modeling tool are shown in Fig.~\\ref{fig:googleWarehouseComp}.\n\n\n\\begin{itemize}\n\n\\item{Manual vertex and face specification gives users the tools to create and position verticies in $\\mathbb{R}^3$. These tools allow unrestricted mesh creation, but it is possible, and even common, for such tools to create non-planar polygons, non-watertight, or self-intersecting meshes. Often additional post-processing stages must be applied to check for these conditions, and resolving them is left to the user. Fig.~\\ref{fig:vertex_edit} illustrates how moving a single vertex may result in several non-planar faces.}\n\n\\begin{figure}\n  \\centering\n  \\def\\svgwidth{0.7\\columnwidth}\n  \\includesvg{13-procex/images/mesh_edit}\n  \\caption[Mesh editing may not preserve face planarity.]{\\label{fig:vertex_edit}Given a mesh (left), translating a single point(orange) may result in one or more non-planar faces(right).}\n\\end{figure}\n\n\\item{Extruding a plan-polygon either in a single direction or along a 3D path, Fig.~\\ref{fig:Extrude}, left, is another method to construct meshes with rectangular faces. Careful positioning of the plan and profile can produce meshes with the desired horizontal edge property. An extrusion tool creates an instance of the plan at each vertex of the path. It continues to create a rectangular face between the pairs of corresponding plan edges from adjacent plan-instances. \n\nHowever there are some problems with the extrusion tool. If the path rotates, the faces of the resulting geometry may not be planar, Fig.~\\ref{fig:Extrude}, centre. Additionally, when modelling walls and roofs, the plans and profiles are not changed in response to the geometry; self-intersections may occur, such as when modeling roofs --- the crest of the roof may either fall short, or overshoot as in Fig.~\\ref{fig:Extrude}, right. Such deficiencies with geometry created by the extrude tool must be identified and removed manually, possible with manual vertex and face edits.\n\n\\emph{Levelshop}\\cite{Fong11} is a rapid video game level prototyping tool that uses extrusions, together with user defined 2D plans. Because of the above problems with extrusion, it is limited to relatively simple geometry.}\n\n\\begin{figure}\n  \\centering\n  \\def\\svgwidth{1.0\\columnwidth}\n  \\includesvg{13-procex/images/extrude}\n  \\caption[Failure cases with extrude tool]{\\label{fig:Extrude}Left: A plan polygon (green) is extruded along a single segment path (blue). Rectangular faces are created between adjacent instances of the polygon. The above verticies $p^1_1$, $p^2_1$, from the first instance, and $p^1_2$ and $p^2_2$, from the second, form the orange rectangle. Centre: If the path rotates an instance, faces may not be planar. Note that the non-planar quads are depicted here as triangles. Right: Using a more complex path, geometry with strong horizontal lines can be created. However self-intersections and holes in the geometry are evident in this example, such as near the roof line of this mesh, and above the concavity in the plan.}\n\\end{figure}\n\n\\item{A modification to the extrusion algorithm allows for different profiles to be used at each vertex on the profile. This \\emph{loft tool} allows more  user  interaction, so that when the geometry does self-intersect, the profiles may be manually edited. Lofts are a modeling primitive extensively used in 3D modeling packages. As when extruding there are no guarantees that the result of a loft will not self-intersect. The manual editing of profiles can be quite involved as it requires the user to specify additional segments for some of the polyline instances as well as specifying corresponding topologies for face creation.}\n\n\\item{Another popular method for geometry creation is \\emph{constructive solid geometry}\\cite{Atherton83} to form objects from the addition and subtraction of geometry elements. CSG has been used by several systems since to create urban modeling tools. Sugihara and Hayashi\\cite{Sugihara08} create roofs on orthogonal geometry by unioning roofs after rectangular decomposition. This approach is adapted to building reconstruction in~\\cite{Lafarge10}, by computing the CSG union of elements from a library of 3D roof-form blocks.\n\nThe advantages of CSG are that manifold results are guaranteed, and that all the output faces are subsets of the input faces. Thus if the input faces are planar, then so will the result. The disadvantage is, however, that the range of results are limited by the available CSG primitives, as illustrated in Fig.~\\ref{fig:csg}.}\n\\end{itemize}\n\n\\begin{figure}\n  \\centering\n  \\def\\svgwidth{1.0\\columnwidth}\n  \\includesvg{13-procex/images/csg}\n  \\caption[CSG failure cases]{\\label{fig:csg}The expressiveness of a constructive solid approach, given a single input primitive (a) is limited. For example, we may wish to elongate the primitive. A CSG union operation could only construct a mesh with several peaks (b), while a scale operation would also adjust the slope of the roof in an unrealistic manner (c), however we probably prefer a result closer to the straight skeleton (d). In a second example, the union (e) is not the same as the SS (f), and introduces unwanted, water collecting, horizontal edges into the roof-line. More complex examples (g) cannot be created at all, since they are not locally similar to the available primitive.}\n\\end{figure}\n\n\\FloatBarrier\n\nAs introduced in Chapter~\\ref{c:readings} there are a wide range of languages and grammars for specifying geometry. Many of these systems, such as CGA Shape\\cite{Pascal06}, are concerned with the combinatorial and positional aspects of the modeling, rather than the geometric elements. For example, CGA may specify the location of the roof, but would rely on extrude operations to specify the mass model and other geometric routines to calculate the roof geometry.\n\n%Modeling packages. unlear algorithms.\n%Specialist architectural modeling tools... Procedural extrusions bear a resemblance to several modeling techniques available in commercial packages. Here we outline several of these techniques in relation to archiectural shell design. \\cite{Revit}\\cite{AutoCAD}.\n\n% deformation techniques\nSeveral systems exist to deform existing architectural meshes into new configurations~\\cite{Habbecke12, Cabral09, Gal09}, additional detail is given in Chapter~\\ref{c:readings}. For example, in \\cite{Habbecke12} Habbecke and Kobbelt introduce a mesh deformation tool that constrains specified edges to remain, for example, coplanar, horizontal or vertical. The system constructs a linear system that may be deformed in real time. These deformation tools, however, do not solve the problem of creating geometry to be deformed in the first place.\n\nPrevious systems have applied the straight skeleton to the modeling of architectural roofs. Laycock and Day\\cite{Laycock03} use the SS to define roofs over arbitrary floorplans, and adjust the positions of the verticies to create Gable roofs. Havemann\\cite{Havemann:2005:GMM} uses an application of the SS with uniform negative weights, followed by an application with uniform positive weights to create overhanging roofs. Our goals are similar to these approaches and we contribute new extensions to the straight skeleton to avoid the need for Laycock's vertex adjustment and to extend the skeleton beyond roof modeling to an interactive procedural modeling system for entire architectural meshes.\n\n\n\n\\begin{figure}\n  \\centering\n  \\def\\svgwidth{0.6\\columnwidth}\n  \\includesvg{13-procex/images/vsmedial}\n  \\caption[Modeling building roofs with the medial axis.]{\\label{fig:vsmedial}A comparison of modeling roofs with the medial axis, left, and the straight skeleton, right. The corresponding 2D geometries are shown above.}\n\\end{figure}\n\nAn alternative to the SS for offsetting areas is the medial axis\\cite{Blum67}. As discussed in Sec.~\\ref{sec:skeletonSubivision}, there are several technical limitations to using the medial axis in the polygonal domain. In addition we may wish to study the aesthetic reasons for not using the medial axis; we can ignore these technical limitations to create a model such as demonstrated in Fig.~\\ref{fig:vsmedial}. In this model we observe that there are many unrealistic curved roof ridges, both when viewing the model from the top or the sides. These unrealistic curved edges make the medial axis much less suitable for modeling the roofs of buildings than the straight skeleton. In addition we note that the method used to visualise the medial axis for Fig.~\\ref{fig:vsmedial} created 65,000 polygons, compared to the 80 polygons created by the SS algorithm. This large difference in model complexity was caused by the terrain used to model the roof from a 2D bitmap image of a medial axis computation. It may be possible to create such 3D models using the medial axis with fewer polygons, but we are unaware of any such published techniques.\n\n\n%%-------------------------------------------------------------------------\n%%\n\\section{User Interface Description}\n\\label{sec:UI}\n\nTo control the underlying application of MWSS instances, the PE system utilises a graphical user interface. This section introduces the interface, and how it can be used to model single instances of complex watertight architectural meshes, we call \\emph{shells}. The MWSS algorithms are largely motivated by the desirable user interface commands, and so the user interface provides a motivation for the technicalities in the following sections. These new event types specified by the UI are explained in Sec.~\\ref{sec:WSS}.\n\n\\subsection {Overview}\n\\label{sec:UI:overview}\n\nOur UI originates from the observation that simple roofs can be defined by a aerial plan, and an angle for the roof. We combined this line of enquiry with the study of architect's drawings that combine plan drawings from above, and elevation images from the four sides. The plan specifies the footprint of the structure, while the observed roof angle is often present in the elevations. Exploring this observation, one may extract angles and heights from other locations on the profile in an architectural elevation, such as the height of the walls. However, architects typically produce a small number of elevations, typically one for each cardinal direction, and this provides insufficient detail for reconstruction. For example when the footprint of the house contains concavities, cardinal elevations under-constrain the resulting solid shape. The premise of the PE system is to create solid geometry from a \\emph{plan} and per plan-edge \\emph{profiles}, as in Fig.~\\ref{fig:two_profiles}. \n\n\n\\begin{figure*}\n  \\centering\n \\def\\svgwidth{1.0\\columnwidth}\n\\includesvg{13-procex/images/ui_strip}\n\\caption[Example PE plans and profiles.]{\\label{fig:ui_strip} Three example buildings constructed in our user interface. We demonstrate multiple profiles on a simple plan (abcd), modeling overhangs (efghi) and anchors (jklmn). Simple profiles (ab) are applied to the green and purple edges of the plan (c) to create the geometry (d). Overhangs are defined using an additional pair of profile polylines associated with every edge (ef) to create typical roof geometry (hi). Anchors (magenta circles) are defined on the profile (j) and the plan (l) to position features. In this example the anchors position a rectangular natural step (m) with a profile (k) that creates a roof-window (n).\n}\n\\end{figure*}\n\nThe plans and profiles are evaluated by a rising sweep plane algorithm, in a manner similar MWSS, of Sec.~\\ref{sec:mwss}. As the sweep plane rises, it carries with it an \\emph{active plan} which combines the different profiles to create a solid polygonal mesh. \n\n\nThe complete UI, including the MWSS implementation, is available online\\cite{siteplan}.\n\n\n\\subsection{Plans and Profiles}\n\nThe complete user interface, as illustrated in Fig.~\\ref{fig:ui} and provides:\n\\begin{itemize}\n\\item{the current plan,}\n\\item{the current profile,}\n\\item{a 3D preview of the current architectural shell,}\n\\item{tools to add, remove and move verticies in the plan and profile,}\n\\item{tools to associate profiles with plan edges,}\n\\item{options to add and remove profiles}\n\\item{options to add \\emph{events} to the profile and plan using anchors. There are several different types of discrete UI events, introduced below, which are enacted as the sweep plane rises past them.}\n\\item{Finally the UI also provides standard save, load, and export functionality.}\n\\end{itemize}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=1.0\\columnwidth]{ui.png}\n  \\caption[The PE GUI.]{\\label{fig:ui}\nThe interactive interface during the design of a temple. The right window contains the output preview whilst the left window contains the plan and the profile editors.\n}\n\\end{figure}\n\nWe shall continue to use the definition of a plan introduced in Sec.~\\ref{sec:constring_skeletons} --- a linked list of verticies that define the counter-clockwise boundaries of enclosed regions. In the PE system, every edge in the plane is also associated with a \\emph{profile}. A profile is a collection of polyline segments that define a cross-section of the building through the associated plan edge. As the user edits the plan or profile, the system shows the resulting architectural shell in a 3D preview window. The following Sec.~\\ref{s:desc_pe_events} will introduce  \\emph{edge direction events} into the sweep plane algorithm, each of which is specified by a profiles vertex.\n\nFig.~\\ref{fig:ui_strip}, c, shows an example of a plan and two profiles, a \\& b. In the 2D plan, different colours show the association between the plan-edges and profiles. Each profile is automatically assigned a colour upon creation, and the plan-edge is drawn with this colour. \n%Every vertex in a profile poly-chain will create an edge-direction event (Sec.~\\ref{section:edgeDirecitonEvents}).\n\nBecause of the underlying sweep-plane algorithm we must constrain the profiles to be monotonic in the vertical ($z$) direction; horizontal polylines are allowed as a special case. The underlying procedural extrusions grow architecture upwards from an input-plan. Therefore, a downwards moving line-segment is meaningless. In order to creating buildings with overhanging roofs, such as the temple of Fig.~\\ref{fig:ui}, there were two design directions that could have been taken:\n\n\\begin{enumerate}\n\\item {Allow the user to draw arbitrary polylines as profiles that can go up or down in the vertical direction. These would be automatically decomposed into monotonic profiles;}\n\\item{Force the user to explicitly model profiles as multiple polylines where each polyline must be monotonic in the vertical direction.}\n\\end{enumerate}\n\nGiven several examples, it became clear that when design 1 was used it was difficult to coordinate different profiles, each with an overhang, to occur at the same height. This case is relatively common, so design 2 was chosen. All the polylines in a profile are, therefore, monotonic; polylines that represent overhangs on different profiles all start from the same height. The height is marked in the user interface by a white circle, as in Figs.~\\ref{fig:ui} \\& \\ref{fig:ui_strip} e \\& f. The height of all overhangs starting from the same elevation can be changed by moving the position of this circle.\n\nWe will explain the process of modeling overhangs using the second example in Fig.~\\ref{fig:ui_strip} efhg \\& i. The user creates the input floor plan shown in (g). The edges in this plan are colour coded as either red or blue. A red edge will be extruded according to the red profile (e) and the blue edges will be extruded according to the blue profile (f). The final architectural shell is shown in (h) and (i). The red profile and the blue profile each consist of three polylines. Each of these polylines is monotonic in the vertical direction.\nIn the red profile we can see that one of the polylines has two segments that are completely horizontal. Modeling horizontal segments is transparent to the user, but will be handled as special case later in the implementation.\nModeling overhangs is an explicit operation. The overhang is modeled by inserting two new polylines into both profiles at a certain height. \nIn the user interface this is one atomic insertion operation. When the user adds an overhang to one profile, via a right-click menu, then all profiles will obtain two new polylines at the same height. These two polylines bound the inside and outside of the overhanging area in the active plan. The user can independently edit the new polylines for each profile, whilst only the starting height remains synchronised. The interface allows users to disable edges so that they do not contribute to the offset boundary, an example of which is shown in Fig.~\\ref{fig:raising_roof}. The profile associated with edges adjoining such disabled edges is specified once for the entire offset. Both the edge disable option and adjoining edge profile are manipulated via the right-click menu.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=0.8\\columnwidth]{raising_roof.png}\n  \\caption[A non-monotonic profile]{\\label{fig:raising_roof}\nA profile offset event simulates a non-monotonic profile by manipulating the active plan at the height of the event and adding an additional overhanging region (top left). In this example the front and back edges of the roof have been disabled from taking part in the offset. One profile offset event (a,b) may define a shared starting height for one roof with two different angles. Coordinating this offset event between profiles allows for a single parameter to control the roof height (c; several heights shown).}\n\\end{figure}\n\nComputing these non-monotonic sections of the profiles is somewhat involved as the user interface does not specify the offset region in absolute coordinates, but rather relative to current edges in the active plan. Sec.~\\ref{section:profileOffsetEvents} will introduce these \\emph{profile offset events}, and a solution to computing the corresponding 3D meshes via sub-applications of the WSS to the current active plan outline.\n\n\\FloatBarrier\n\\subsection{Anchors}\n\nThere are several categories of UI operation that perform actions at specific locations on the 3D architectural model being constructed. For example we may wish to position a decorative mesh at a specific location, make local change to the active plan in order to induce dormer windows into a roof, or we may wish to divide the active plan into separate parts at a certain height. The difficulty here is that these locations must be persistent to changes in the input plan, profile changes and re-calculations of the architectural shell. This is called the \\emph{persistence problem} in procedural systems\\cite{Lipp:2008:IEV}, and we introduce \\emph{anchors} as a partial solution in our system.\n \nAn anchor is created, after specifying the event type, by selecting a point on the plan, or on the corresponding profile polylines. In Fig.~\\ref{fig:ui_strip} (jklm \\& n), the anchors are shown as magenta circles on a floor plan edge and a profile edge. A plan anchor and profile anchor together specify the location of a feature, in this case a roof window. Fig.~\\ref{fig:Marker_Product} shows how an anchor on the plan (a), and the profile (b), may be combined to specify a location (c). A profile anchor alone specifies an event at a the specified height, for example splitting the active plan into two halves. In either case, if the corresponding profile anchor is no longer associated with an edge in the active plan at the specified height, then it will not be instanced. Furthermore, if the edge on which an anchor was placed has been split, then the event may occur two or more times.\n\n\\begin{figure}\n  \\centering\n  \\def\\svgwidth{0.6\\columnwidth}\n  \\includesvg{13-procex/images/marker_product}\n  \\caption[An example of anchors]{\\label{fig:Marker_Product} Positioning a feature, c, using plan anchor a and profile anchor b on the complex surface of a bay window.}\n\\end{figure}\n\n\\subsection{Plan Edits}\n\nEditing the active plan at a specific location allows a wide range of local features to be created on the architectural shell. These edit-events are \\emph{plan edits}; they are specified by a plan-edit-plan and profile, a plan/profile anchor pair to position the edits, and a \\emph{step type}. The step type specifies one of two options for inserted edges into the active plan, with different advantages:\n\n\\begin{itemize}\n\\item{\\emph{Forced steps} insert an arbitrary set of edges into the plan.} \n\\item{\\emph{Natural steps} offer a range of simple shapes that can be inserted, and come with a guarantee not to cause self-intersecting geometry.}\n\\end{itemize}\n\nThe details of the differences between these two step types are discussed later. Fig.~\\ref{fig:ui_strip} (jklm \\& n) show a plan edit with a forced step being used to create a roof window.\n\n\\begin{figure}\n  \\centering\n \\def\\svgwidth{1.0\\columnwidth}\n  \\includesvg{13-procex/images/chimney}\n  \\caption[Adding a chimney using plan edits.]{\\label{fig:Chimney}\nLeft: The plan (solid green line) and profiles (blue lines) define the shape of the structure. The anchors (orange) locate the chimney (red). A natural step is inserted into the building at the anchored location (dashed green lines). Middle: The finished 3d geometry, showing the profiles for the new edges. Right: Alternative natural step which adds an additional rectangle into the plan (dashed green lines) to specify a chimney. }\n\\end{figure}\n\nFig.~\\ref{fig:Chimney} illustrates that, as well as adding additional regions into the plan, plan edits may also remove regions. Here we use a plan edit to specify a square portion of the roof to be removed. This square is replaced by a square plan region, and associated profiles, such that a chimney is formed as the sweep plane rises. \nIf the input plan has several repeated elements, such as bay windows or buttresses, plan edits give a convenient tool for defining the repeated plan and profile once, whilst repeating it at a number of different anchored locations; for example the creation of the buttresses of Fig.~\\ref{fig:multi}.\n\n\\subsection{Positioning Decorative Details}\n\nAnother application of anchors is to specify the location of architectural details. Sets of anchors can be used to mark the location of anchor points of decorative meshes. For example the top and bottom elements in a grid of windows of Fig.~\\ref{fig:windows_stretchy}. This figure also provides an example of re-using plan and profile anchors to ensure that the decorative meshes are positioned in a regular pattern. By using a pair of anchors to specify the top and bottom of each window mesh on the facade, the user specifies that the windows have a particular height. In general, we may use tuples of anchors to specify the position of control bones to provide a variety of deformations to decorative meshes. The mesh deformation takes place using per-bone vertex weights\\cite{Lewis00}, imported into the PE system in the MD5 file format. Typically these are created using an external modeling tool; the examples in this chapter were created with Blender\\cite{Blender}.\n\nA user interface parameter allows the users to specify the scale of the decorative meshes on the architectural shell. This is useful when working with decorative meshes from a library with varying scales.\n\n\\begin{figure}\n  \\centering\n \\def\\svgwidth{0.5\\columnwidth}\n  \\includesvg{13-procex/images/shared_anchors}\n  \\caption[Sharing anchors]{\\label{fig:windows_stretchy}Above: Plan (blue) and profile (green) anchors define the attachment points (purple) for decorative meshes. By sharing plan and profile anchors, the attachment points may be constrained to the same horizontal or vertical line. Below: The window and pillar meshes are deformed by the attachment points to increase the variety in the model.}\n\\end{figure}\n\nWhile pairs of anchors can be used to specify points on the architectural shell, individual faces of the shell can be identified by adding \\emph{tags} to the appropriate profile segment. These are shown as small triangles in the user interface, a cyan coloured example is shown in Fig.~\\ref{fig:subdivision_ui}. After the complete manifold is computed, the faces that were generated from the specified profile segment are post-processed in a particular way, for example to add tiles to the roof.\n\n\\FloatBarrier\n\\section{Splitting the active plan}\n\nA \\emph{subdivision event} splits the area enclosed by the active plan into several sections at a particular height. It is used to model buildings that rely on an internal structures, such as ``saw tooth'' roofs. The user defines a set of offsets, which bound the newly created regions on the active plan. As with profile offset events, the challenge in implementing subdivision events is in creating a robust result for all possible active plan topologies; again a second application of PE are used to define these offset region boundaries.\n\n\\begin{figure}\n  \\centering\n \\def\\svgwidth{1.0\\columnwidth}\n  \\includesvg{13-procex/images/subdivision_ui}\n  \\caption[The subdivision event UI]{\\label{fig:subdivision_ui}The subdivision event UI. Left: The plan and subdivision profile. Right: The UI for specifying the new profile map, and tags for specifying the new regions and associated profiles for their side, bottom and top edges. Inset: The resulting 3D model.}\n\\end{figure}\n\nWhen creating a subdivision event the user specifies the following using the interface of Fig.~\\ref{fig:subdivision_ui}:\n\\begin{itemize}\n\\item{A height for the subdivision event, specified by a profile anchor.}\n\\item{A map that defines the new profiles in the subdivision application of procedural extrusions, from the existing profiles.}\n\\item{A set of tags applied to these new profiles which specify the new regions of the subdivided plan.}\n\\item{A map that specifies new profiles for the new regions.}\n\\end{itemize}\n\n\\FloatBarrier\n\\section{Computing Procedural Extrusions}\n\\label{sec:WSS}\n\nGiven the UI input, this section details the procedural extrusion system which generates the output geometry. It begins by defining the terminology used, the inputs and the outputs of the main algorithm. The section continues with a description of the different events generated automatically and by the user, and how each event type is computed.\n\n\\subsection {Definitions}\n\\label{sec:method}\n\nWe shall use the terminology of Chapter~\\ref{c:various_skels}, briefly introducing it again, and extending it where appropriate. Broadly, the inputs are the plans and profiles defined, for example, by the UI, while the output of the system is an architectural shell in 3d Euclidean space with a $xyz$ world coordinate system. The up direction is along the $z$ axis. \n\nA \\emph{(floor) plan} is a  planar subdivision (a straight line planar embedding of a planar graph) that divides a plane into \\emph{inside} and \\emph{outside} regions. \nA plan has corners and oriented edges. \nA plan is embedded in a plane parallel to the $xy$-plane (the ground plane), so that all corners of a plan have the same $z$ (height) value. \nWe require that the boundaries of a plan are a non-intersecting collection of oriented polygons. \nThe inside is on the left-hand side of each oriented polygon edge. \nThe polygons are oriented counter-clockwise, but polygons describing holes are oriented clockwise. Additional bounded regions may be recursively located inside a hole.\nThe $j$th polygon is described by $n^j$ polygon corners $c^j_i \\in \\mathbb{R}^3$ with $1 \\leq i \\leq n^j$.  Each corner $c^j_i$ is connected to the next corner (according to the polygon orientation) by an implicitly defined \\emph{edge}, $e^j_i$. \nIn the following, indices should be treated cyclically, such that a polygon with corners $c^j_1$, $c^j_2$, and $c^j_3$, the corner $c^j_4$ means $c^j_1$.\n\nEach edge in a plan is associated with a \\emph{direction plane}, $dp^j_i$, which contains the edge. Since we will be using it to evaluate a MWSS, it is defined by an angle $\\theta$ such that $-\\pi/2 \\leq \\theta \\leq \\pi/2$. \n%We will use Greek letters in this paper to describe such angles. \nA vertical direction plane has $\\theta = 0$, whilst a direction plane oriented towards the inside (outside) satisfies  $\\theta > 0$ ($\\theta < 0$ respectively). The angle is measured between the direction plane and a vertical plane that also contains the edge, as in previous Fig.~\\ref{fig:wss_terms}.\n\nA \\emph{profile} is a set of polylines that is used to control the direction plane of an edge. A polyline is modeled in a local 2d  $wz$-coordinate system and consists of a list of $m$ points $t_i$. The location of point $i$ is $(t_i.w,t_i.z)$ and we require, for monotonicity, that $t_i.z \\leq t_{i+1}.z$. The polyline defines $m-1$ angles, $\\theta_1..\\theta_{m-1}$. The angle $\\theta_i$ is calculated as the clockwise angle between a vertical line and the line $t_i$ to $t_{i+1}$. The angle lies in the range $-\\pi/2 \\leq \\theta_i \\leq \\pi/2$, and the final angle is constrained such that $\\theta_{m-1} > 0$. This final condition ensures that the MWSS terminates.\n\n%A profile is associated with an edge and it can be mapped to 3d so that the $w$ axis is orthogonal to the edge and the local $z$ coordinate aligned with the $z$-coordinate of the world coordinate system. This mapping to an edge allows us to determine the active gradient (and active angle) for height $z$ in the world coordinate system.\n\n\n\n%A \\emph{profile} controls the active gradient. The profile consists of a list of $m$ 2D points, $t^{1..m}$ in the $wz$-plane. The location of point $i$ is $(t^i_w,t^i_z)$. The ordering of the list is constrained to fulfill  $t^i_z \\leq t^{i+1}_z$. Additionally $t^{(m-1)}_w > t^m_w$, such that the final $\\theta \\> 0$ . The profile defines $m-1$ gradients, $\\theta^1..\\theta^{m-1}$.  $\\theta^i$, is then calculated as the clockwise angle between the line $(0,0)$ to $(0,1)$ and the line $t^i$ to $\\theta^(i+1)$ in the range $-\\pi/2 \\leq \\theta \\leq \\pi/2$.\n\n\n% Each edge $e^p_i$ together with the associated angle $\\theta^p_i$ define a, possibly infinite, face $sp^p_i$. See Fig.~\\ref{fig:InputOutput}.\n\n% A \\emph{profile} is associated with an edge and consists of a sequence of 3d gradient vectors that define the extrusion directions of an edge. The gradient vectors are orthogonal to an edge and the length of a gradient vector indicates how long an edge is intending to move in the gradient direction. Through the use of profiles each edge in a plan has an (active) gradient. While a gradient is a 3d vector it is better defined by an angle $\\theta^j_i$ such that $-\\pi/2 \\leq \\theta^j_i \\leq \\pi/2$. A vertical gradient has $\\theta^j_i = 0$, whilst a gradient oriented towards the inside (outside) satisfies  $\\theta^j_i > 0$ ($\\theta^j_i < 0$ respectively).\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\subsection {Overview}\n\\label{sec:Overview}\n\nThis section describes the input, output, and an outline of the PE algorithm. \n\n\\subsubsection {Input}\n\nThe input of the algorithm is a (floor) plan, called the \\emph{input plan}, profiles associated with the edges of the input plan, profile offset events, and anchor events. Anchor events specify the location of plan edits, a mesh instance or subdivision event.\n\n% \\begin{figure}\n%  \\centering\n%  \\includegraphics[width=1.0\\columnwidth]{skel_into.png}\n%  \\caption{\\label{fig:InputOutput}\n%Our algorithm constructs the architectural shell, shown on the right, for an input plan, shown on the left. In this simple example, each profile only has a single segment; adding additional segments to the profile eventually allows us to model an entire building, including the walls. The input is defined by the corner positions $c^j_i$, the angles $\\theta^j_i$, and the corner connectivity. The output is a shell consisting of faces on the respective direction planes, $dp^j_i$.}\n%\\end{figure}\n\n\\subsubsection{Output} The main output of the algorithm is an \\emph{architectural shell} (3d mesh) in the $xyz$ world coordinate system. In the non-degenerate case the shell is watertight and two-manifold. The architectural shell is a polygonal mesh stored in a half-edge data structure. The half-edge data structure stores a set of vertices in $\\mathbb{R}^3$, a set of input edges and skeleton arcs between the vertices, and a set of planar faces which may contain holes. Faces are defined by a counter-clockwise ordering of arcs.\n\n\\subsubsection{Outline} \n\nThe algorithm is an extension of the MWSS algorithm introduced in Chapter~\\ref{c:various_skels}. As well as the automatic events that occur in the MWSS, the event queue also contains user interface events. As before, the core algorithm repeatedly takes the next event from the queue, allowing it to update the \\emph{active plan} as well as insert additional events into the queue if necessary. Fig.~\\ref{code:pecode} gives the algorithm in pseudocode form.\n\n\\begin{algorithm} [htb]\n\\begin{footnotesize}\n  Main \\Begin{\n   $Q$ = new priority queue\\; \n   $sweepZ$ = 0\\;\n\n    \\ForEach{ corner $c$ in active plan } {\n        CreateGIEEvents ( $c$, $Q$ )\\;\n    }\n\n    CreateUserEvents( queue $Q$)\n\n    \\While { !$Q$.empty() } {\n        event = FindNextEvent($Q$)\\;\n\n    event.updateActivePlan()\\;\n    event.updateEventQueue($Q$)\\;\n\n}\n    \\ForEach{ edge $e$ in input plan } {\n         ReconstructFace ($e$)\\;\n    }\n}\n\n  CreateUserEvents( queue $Q$ ) \\Begin{\n     \\ForEach{ Profile $p$ in user profiles } {\n\n     \\ForEach{ ProfileOffsetEvent $poe$ in $p$ } {\n       $Q$.insert (new ProfileOffsetEvent($poe$) )\\;\n     }\n\n     \\ForEach{ vertex $v$ in $p$} {\n        $Q$.insert (new EdgeDirectionEvent($p$, $v$) )\\;\n     }\n}\n\n    \\ForEach{ AnchorEvent $ae$ in user anchor events } {\n        $Q$.insert (new AnchorEvent($ae$) )\\;\n     }\n   }\n\n\\end{footnotesize}\n  \\caption[PE pseudocode]{Pseudo-code for main loop of the PE algorithm, an extension of Fig.~\\ref{code:skelcode}}\n  \\label{code:pecode}\n\\end{algorithm}\n\nThe priority queue orders events by their $z$ height, thus simulating the rising sweep plane. By allowing additional edges to be added by the user to the rising active plan, the MWSS is extended to describe a wide range of architectural forms. Therefore the PE algorithm is equivalent to a succession of MWSS skeletons stacked on top of each other, along the $z$ axis. \n\n\\begin{figure}\n  \\centering\n  \\def\\svgwidth{0.7\\columnwidth}\n  \\includesvg{13-procex/images/pointers}\n  \\caption[PE algorithm pointers]{\\label{fig:pointers}\n The plan data structure, shown part way through the sweep. A linked list of corners describes each enclosed region. In addition every corner has a reference to the previous and next direction planes, each associated with an edge on the active plan. Skeleton arcs are output by events, and are used to reconstruct the 3D architectural shell.}\n\\end{figure}\n\nOnce all the events in the priority queue have been processed the algorithm terminates. The skeleton faces defined by the events are post processed and output. This post processing involves identifying holes, positing decorative meshes and applying the textures specified by user tags. \n\n\n\\subsubsection{Data structures}\n\nThe first significant data structure is the \\emph{plan data structure}, which encodes the active plan on the sweep plane, as in \\cite{Felkel:1998:SKI} and Chapter~\\ref{c:various_skels}. This structure is a doubly linked list of corners. Each corner has a pointer to the next corner, the previous corner, and a pointer to its previous and next direction planes, Fig.~\\ref{fig:pointers}. \nAt the beginning of the algorithm the input plan is specified by the building floorplan. During the algorithm, the sweep rises from the input plan and this data structure is updated to encode any changes to the active plan. \n\nThe second important data structure is a priority queue, Fig.~\\ref{code:pecode} $Q$,  that sorts events by ascending height. GIE events are automatically created, while user events (edge direction events, profile offset events and anchor events) are defined by the user.\n\n\\subsection{Description of Events}\n\\label{s:desc_pe_events}\n\nAs the sweep plane ascends it encounters several different types of events, introduced in this section. The two major classes of events are those automatically inserted to ensure the area on the active plan remains well formed, and those specifically inserted by the user.\n\nThe automatic events are the general intersection events --- our generalisation of split, edge\\cite{Felkel:1998:SKI} and vertex events\\cite{Epp:98}, as introduced in Sec.~\\ref{s:gie}. These events are created whenever a new event is added to the active plan.\n\nThe user events are specified in various portions of the user interface. There are five types of UI event:\n\\begin{itemize}\n\\item{\\emph{Edge direction events} occur at profile polyline verticies. Such an event updates the direction plane associated with a set of edges in the active plane}\n\\item{\\emph{Profile offset events} occur at heights specified by user edits. Intuitively, a profile offset event results in additional inside regions being added to the active plan at the specified height. }\n\\item{\\emph{Anchor events} come in a further three varieties:\n   \\begin{itemize}\n        \\item {\\emph{Plan edit anchors} modify the active plan to insert architectural features such as chimneys, or dormer windows into the shell. }\n        \\item {\\emph{Mesh anchors} specify attachment points for decorative meshes.}\n        \\item {\\emph{Subdivision event anchors} divide the active plan into a number of pieces. They occur over the entire active plan at a height given by the anchor.}\n   \\end{itemize}\n}\n\\end{itemize}\n\nWe continue to detail each of these event types.\n\n\\subsection {Generalised Intersection Event}\n\\label{section:eventImpl}\n\nThe GIE is an automatic type of event, introduced previously in Sec.~\\ref{s:gie}. Here we introduce the implementation details required for a robust implementation in a floating point environment. We chose a double-precision floating point environment, instead of an exact computation paradigm, such as CGAL\\cite{cgal}, as it was both simpler to work with, and faster --- a benefit for the rapid computation of large environments. The main robustness tool we use are epsilon tolerances.\n\nGeneralised intersection events perform topological changes on the active plan to ensure that it never self-intersects as the sweep plane ascends. These events are automatic, and inserted whenever new edges are added to the active plan. For example, all user specified events that add edges to the output, will also check for potential GIE events involving those new edges.\n\nChapter~\\ref{c:various_skels} introduces the limitations of the GIE. Indeed there are many MWSS situations in which the GIE does succeed in forcing the active plan to remain well formed. Despite this we found the GIE a remarkably robust solution to the complex events created by architectural plans and profiles. \n\n{\\bf Input:} The input of a generalised intersection event is a point $l \\in \\mathbb{R}^3$, and a set of three or more direction planes, $f$, whose associated direction planes intersect at $l$. The point $l$ is calculated as the centre of the clustered volume.\n\n{\\bf Output:} The output of a generalised intersection event is an updated active plan. This represents the bounded region on the sweep plane after the event.\n\n\\subsubsection{Epsilon Tolerances} \n\nAs part of the GIE we remove any \\emph{out of bounds} edges from the edge set, $f$. It is possible for the line defined by the intersection of the direction plane and the sweep plane to pass close to $l$, however the line-segment defined by the associated active plan edge may not. Because the intersections are detected using unbounded direction planes, there may be edges in $f$ that do not approach $l$ on the active plan. Such edges are removed from $f$. \n\nA small epsilon range, $\\epsilon_1$, expands the active plan edge and ensures that collisions occur reliably over the floating point precision range. On our inputs of footprints measured in meters around the origin we found  $\\epsilon_1 = 10^{-5}$ a sufficient margin. If $\\epsilon_1$ becomes too large, the chances of the extended edges intersecting with unintended geometry increases.\n\nIn addition, we use expanded bounds for intersection location clustering. This addresses two stability problems:\n\\begin{itemize}\n\\item{In symmetrical inputs made up of regular polygons, such as often found in architectural plans, it is very common for more than three direction planes to meet at a point. To avoid degenerate output in a floating point situation it is necessary to identify intersections whose locations are close together, and treat these as a single event. Fig.~\\ref{fig:RobustEventDetection}, left, illustrates an example of such a building footprint.}\n\\item{Second, direction plane intersections that are far apart from each other can interfere if they are close to one other in height, Fig.~\\ref{fig:RobustEventDetection}, right. It is also necessary to detect and handle these events at the same height to resolve the parallel consecutive edge degeneracies.}\n\\end{itemize}\n\n\\begin{figure}\n  \\centering\n  \\def\\svgwidth{0.8\\columnwidth}\n  \\includesvg{13-procex/images/coheighted}\n  \\caption[Architectural footprints often lead to degenerate events]{Left: Five faces forming an intersection event. Right: Events can interfere with each other if they have the same height, in this case the four points that share a roof ridge.}\n\\label{fig:RobustEventDetection}\n\\end{figure}\n\nTo address the two previously mentioned event detection problems, we cluster the events in both vertical and horizontal directions. We poll the priority queue to collect all intersection events whose height, $z$, is within some threshold, $\\epsilon_2$, of the initial event. Second, we cluster all the events according to their location after projection onto the $xy$ sweep plane. The clustered volume is therefore a cylinder of radius $\\epsilon_3$ and height $\\epsilon_2$. Fig.~\\ref{fig:clustering} illustrates this clustering step. We found that values of $\\epsilon _2 = 10^{-4}$ and $\\epsilon _3 = 10^{-6}$ gave the best reliability. There are certain pathological inputs which cause this clustering stage to fail. An example would be a row of events, each within $\\epsilon_2$ of another, which could contain an arbitrary number of events.\n\n\\begin{figure}\n  \\centering\n  \\def\\svgwidth{0.6\\columnwidth}\n  \\includesvg{13-procex/images/clustering}\n  \\caption[Epsilon error parameters]{\\label{fig:clustering}\n  When an event is processed we simultaneously extract all intersection events within a height of $\\epsilon_2$. Then we cluster all events that are within a cylinder of radius $\\epsilon_3$ and height $\\epsilon_2$.}\n\\end{figure}\n\n\\subsubsection{PCE resolution}\n\n\\begin{figure}\n  \\centering\n  \\def\\svgwidth{0.8\\columnwidth}\n  \\includesvg{13-procex/images/ambig}\n  \\caption[PE ambiguities]{\\label{fig:ambig_demo}\nTwo identical bay windows that lead to the same two events (red circles) involved in a degenerate PCE situation (red line). \nTo resolve the PCE situation, a single edge must be chosen to replace the others. The building on the left (right) resolves the ambiguity using the volume maximising (respectively minimising) priority technique. The resulting unused section of the original profile is shown in orange. Note that in each case, two ambiguous events occur at the same height, and must create globally consistent output.}\n\\end{figure}\n\nAs introduced in Sec.~\\ref{s:pce_revisited}, the MWSS is poorly defined in several situations. Different modeling choices lead to different ambiguous-case resolution strategies, Fig.~\\ref{fig:ambig_demo}. In particular when modeling architecture the parallel consecutive edge degeneracies need to resolved in an architecture viable way. We found that the \\emph{volume maximising} approach tended to be the most desirable default for architecture situations; we take the lowest valued $\\theta$ when resolving the PCE. We hypothesise that this case is observed most commonly since it maximises the space inside the building.\n\n% The other useful case is when we want to ensure that two edges with angles $\\theta^p_1,\\theta^p_2$, give a reflection when the direction of the edge is reversed, and the angles are negated.\n\n\n%confirm: we don't need this?\n%If only one cluster of face intersections occurs at a given height this algorithm is sufficient, however when several events occur at one height we lose information from the corner data structure that we would otherwise use to determine if a collision has occurred on a face. PCE. this is $\\delta_2$.\n%For example, after a corner is moved to the position of a split-type event\n%For this reason all chains at one height are found before any are modified. However a chain may have been separated from  its intended collision by an earlier event at the same height. Before processing, each chain must then recover its new current set of corners.\n%In addition we add an epsilon expansion to the bounds check of Sec.~\\ref{sec:constring_skeletons}. is this the same as ``recoving its current set of corners''\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\FloatBarrier\n\\subsection {Edge Direction Events}\n\\label{section:edgeDirecitonEvents}\n\nA set of edge direction events are created for each profile. An edge direction event updates the angle and direction planes of a set of edges. There are two types of edge direction event, \\emph{standard} and \\emph{near horizontal}. Standard edge direction events are constructed from a single angle in the plan, while a near horizontal edge direction event is constructed from two consecutive angles and a distance. These values are calculated from the profile polyline.\n\n\\subsubsection{Standard edge direction events} {\\bf Input:} A set of edges, $f$, in the active plan, each associated with the same profile and a single new angle for all the edges, $\\gamma$. \n\n{\\bf Output:} A new active plan which replaces the original.\n\nFor each of these edges $e_i^j \\in f$, we update the associated direction plane by setting its angle, $\\theta_i^j$ to $\\gamma$. The implicit edge, $e_i^j$, continues to propagate over the sweep plane with a new speed, as defined by the new angle.\n\n\\subsubsection{Near horizontal edge direction events}\n\nWhen the angle associated with an edge, $\\theta$, approaches $ \\pm \\pi/2 $, standard edge direction events face a problem as two parallel (horizontal) direction planes do not intersect to form a line. Additionally, as the angle approaches these limits the algorithm computes the intersections of near coplanar planes, causing numerical instability. To resolve this issue, as illustrated in Fig.~\\ref{fig:horiz}, we use a secondary application of a MWSS to calculate the horizontal section of the profile. To do this we first increase the angles according to the length of the horizontal profile segment, then calculate the secondary MWSS, and finally project the result onto the original sweep plane.\n\n{\\bf Input:} A set of edges in the active plan, $f$, associated with the profile, a distance, $d$, a direction angle, $\\gamma$, and a following angle, $\\zeta$. The angle $\\gamma \\approx \\pi/2$ ($\\gamma \\approx -\\pi/2$) specifies the direction of the horizontal as towards the inside (respectively outside) of the active plan. $\\zeta$ specifies the angle of the following non-horizontal edge event. \n\n{\\bf Output:} A new active plan which replaces the original.\n\n\\begin{figure}\n  \\centering\n  \\def\\svgwidth{1.0\\columnwidth}\n  \\includesvg{13-procex/images/horiz_extrude}\n  \\caption[Near horizontal edge direction events]{\\label{fig:horiz}\nThe horizontal section desired (b) can be created by a secondary application of a MWSS to calculate the offset in the given direction. After flattening (c) unchanged edges (red, d) are ignored.}\n\\end{figure}\n\nFirst we create a temporary plan as a copy of the active plan. For each edge in the original plan, $e^j_i$, and associated angle $\\theta_i^j$, the temporary plan has an edge $E^j_i$, and associated angle $\\Theta_i^j$. Secondly we update the angles in the temporary plan according to the following mapping:\n\n$$\n\\Theta_i^j = \\left\\{ \\begin{array}{rl}\n \\tan^{-1}(d) &\\mbox{ if $e_i^j \\in f$  and $\\gamma > 0$ } \\\\\n -\\tan^{-1}(d) &\\mbox{ if $e_i^j \\in f$ and $\\gamma < 0$ } \\\\\n 0 &\\mbox{ otherwise}\n       \\end{array} \\right.\n$$\nThe secondary MWSS extrudes the temporary plan for a height of one unit. The temporary active plan is projected onto, and replaces, the active plan in the original procedural extrusion instance. That is, $e^j_i$ is replaced by $E^j_i$ if it exists in the updated plan, otherwise $e^j_i$ is removed from the active plan. The location of $E^j_i$ is projected onto the original active plan. Finally the values of $\\theta$ in the original skeleton are updated using the mapping:\n$$\n\\theta_i^j = \\left\\{ \\begin{array}{rl}\n \\zeta &\\mbox{ if $e_i^j \\in f$} \\\\\n  \\theta_i^j &\\mbox{ otherwise}\n       \\end{array} \\right.\n$$\n\n%% In addition to similar additions to output architectural shell as the standard edge direction event, a face representing the near-horizontal section of the profile is created. This is calculated from the output shell of the recursive procedural application, projected onto a plane at the height of the direction event.\n\nOccasionally multiple edge direction events occur at the same height. In this situation the direction events are sequenced by the order of user creation.\n\n\\FloatBarrier\n\\subsection {Profile Offset Events}\n\\label{section:profileOffsetEvents}\n\n\\begin{figure}\n  \\centering\n  \\def\\svgwidth{0.7\\columnwidth}\n  \\includesvg{13-procex/images/offset2}\n  \\caption[Profile Offset events]{\\label{fig:offset_triple} Some meshes that can be computed from an input plan (a) using profile offset events. Buildings b and c are shown in two orientations. By creating two offset boundaries (e) that define an offset region (h), an overhanging roof (b) can be generated from an arbitrary plan (a). If two edges are disabled in the profile offset event, open-ended roofs can be created (c,f,i). Finally, by offsetting inside the active plan, walled roofs can be created (d,g,j). }\n\n\\end{figure}\n\nProfile offset events specify the start of overhangs. The difficulty of specifying and handling profile offset events comes from the procedural definition. While it is easy to specify overhangs for a given region, the geometry must produce good results for a wide range of building footprints, and adjust itself according to the user editing the plan. Our technique must procedurally perform changes to the active plan without creating badly formed self-intersections.\n\nAt a profile offset event, an additional inside region, called an \\emph{offset region}, is inserted into the active plan (see Fig.~\\ref{fig:offset_triple}). Two offset boundaries are grown from the active plan to enclose the new offset region. We introduce new edges and corners into the active plan to represent this newly enclosed region on the sweep plane. The new edges are classified as inside, outside, or side, depending if the edge stems from the first boundary, the second boundary, or are at the side-edge of an offset region.\n\n\\begin{figure}\n  \\centering\n  \\def\\svgwidth{0.7\\columnwidth}\n  \\includesvg{13-procex/images/offset_recurisve}\n  \\caption[Calculating offset events]{\\label{fig:offset_recursive}The recursive application of procedural extrusions (b) to a plan (a) from Fig.~\\ref{fig:offset_triple} (c). The faces between $z=1$ and $z=2$ are projected onto the primary active plan (c), before being merged (d). Zero area faces (blue and purple) are removed, and profiles assigned based on the origin of the edge. In (d) green edges are assigned $profile\\_inside$, red $profile\\_outside$ and blue $profile\\_side$.\n}\n\\end{figure}\n\n{\\bf Input:} A map for each edge in the active plan, $e^j_i$ to a tuple, $t^j_i = $ \\{$disabled^j_i$, $dist\\_inside^j_i$, $dist\\_outside^j_i$, $profile\\_inside^j_i$, $profile\\_outside^j_i$\\} and a single \\newline $profile\\_side$. The variable $disabled^j_i$ is a Boolean value that specifies if the offset region associated with this edge is present in the output; $dist\\_inside^j_i$ and $dist\\_outside^j_i$ are real values that define distance and direction from the active plan of the inside and outside offset boundaries;  $profile\\_inside^j_i$, $profile\\_outside^j_i$ and $profile\\_side$ are profiles. We require that all values of $dist\\_inside^j_i$ and $dist\\_outside^j_i$ have the same sign; a positive (negative) sign indicates an offset (respectively inset) of the active plan. To ensure proper topology on the active plan, the distance, $dist\\_inside$, is constrained to be non-zero. \n\n{\\bf Output:} The output of an offset event is an updated active plan, typically with the additional region defined either inside or outside of the input active plan.\n\nWe create a temporary plan as a copy of the primary (input) active plan. For each edge in the primary plan, $e^j_i$, the temporary plan has an edge $E^j_i$, and an associated profile, $profile\\_recursive^j_i$. Edge $E^j_i$ is constructed by projecting $e^j_i$ onto the plane $z = 0$. The profile $profile\\_recursive^j_i$ defines the angles $\\Theta^j_i = tan^{-1}(dist\\_inside^j_i)$ at $z = 0$, and $\\Theta^j_i = tan^{-1}(dist\\_outside^j_i)$ at $z = 1$. We execute a recursive application of procedural extrusions using the temporary plan as input. It is executed from height $0$ to $2$, to create a temporary output shell.\n Before continuing we correct the orientation to ensure that counter-clockwise loops enclose an inside region; the orientation of each face in the shell is reversed (the counter-clockwise ordering of vertices in the half edge data structure is reversed to a clockwise ordering). \nFaces of the shell between the planes $z = 1$ and $z = 2$ are projected onto the primary active plan, forming the offset region. This process is illustrated in Fig.~\\ref{fig:offset_recursive}. \n\nThe projection associates each tuple, $t^j_i$, with an offset region in the primary active plan. The entire offset region is bounded by the projected edges, $r$. Additionally the projection defines a 1:1 mapping between the new edges, $e^k_l \\in r$, and a subset of the temporary shell's arcs $A^k_l$.\nWe remove from the primary active plan any edges in $r$ that enclose an offset region of area $0$ or that are associated with a tuple containing a value of $disabled^j_i = true$. We update the profile, $profile^j_i$, associated with each edge, $e^j_i$, in the primary active plan according to the function: $$ profile^j_i = \\left\\{ \\begin{array}{rl}\n profile^j_i &\\mbox{ if $e_i^j \\notin r$ } \\\\\n profile\\_inside^j_i &\\mbox{ if $A^j_i$ lies in the plane $z = 1$} \\\\\n profile\\_outside^j_i &\\mbox{ if $A^j_i$ lies in the plane $z = 2$} \\\\\n profile\\_side &\\mbox{ otherwise }\n       \\end{array} \\right.$$\n\nFinally we merge adjacent parts of the offset region to avoid self-intersections. We remove the corresponding edges and corners from the active plan.\n\n\\FloatBarrier\n\n\\subsection{Anchor events}\n\\label{sec:anchors}\n\nAnchors define the location of features, such as plan edits, decorative meshes, or subdivision events. The plan and profile anchors specified in the user interface are used in different combinations to define either an event that happens at a certain height, or an event that happens at a particular point on the mesh. Subdivision events are triggered at a certain height by a profile anchor on an active profile. In contrast, plan edits and decorative meshes are placed at points by both a profile and plan anchor.\n\nFinding parametrised locations on a surface that are robust to subsequent edits in the floor plan is challenging. The manifold of the structure may not reach any given point in space because, for example, the anticipated active plan edge may have been removed by previous events. Therefore, to position features in a manner robust to plan and profile edits the user positions a pair of two dimensional anchors, Fig.~\\ref{fig:Marker_Product}. \n\nThe profile anchor defines a plane parallel to the sweep plane, at the anchor's $z$ height. When the sweep plane reaches this height we trigger height-events. If there is an associated plan anchor, it is evaluated upon the current active-plan to give the $xy$ coordinates.\n\nWe allow the user to select from two types of plan anchor --- relative and absolute. \nA \\emph{relative anchor's} location is a fraction of its length on the active plan edge,  Fig.~\\ref{fig:anchor} middle row, left. If the edge is represented in the active plan at the specified height, the feature is instanced.\n\\emph{Absolute anchors} are defined on an input plan edge, and define a plane perpendicular to this edge, Fig.~\\ref{fig:anchor} bottom row, left. The intersection of this plane and the corresponding edge in the active plan at the height specified by the profile anchor defines the instance location. Because an active plan edge may grow, it is possible to position absolute anchors beyond the ends of the input plan edge.\n\nRelative and absolute anchors each define a different co-ordinate system on faces of the architectural shell, Fig.~\\ref{fig:anchor} centre column. Each system is a more natural way to express certain patterns with different geometric properties:\n\\begin{itemize}\n\\item{Relative plan edge anchors: if an edge is present at the height, the operation will occur at least once. If a split event has taken place on the corresponding edge, it may take place more than once, ~\\ref{fig:anchor}, middle row, right. This makes relative anchors suitable for features that must always exist, however having multiple instances of certain features may be inconvenient.}\n\\item{Absolute plan edge anchors: these may occur once or zero times at a certain height. At a certain height the corresponding plan anchor may no longer define a perpendicular plane that intersects the corresponding edge in the active plan. Hence the absolute anchors may not be suitable for referencing features that must exist, ~\\ref{fig:anchor}, bottom row, right.}\n\\end{itemize}\n\n\\begin{figure}\n  \\centering\n  \\def\\svgwidth{1.0\\columnwidth}\n  \\includesvg{13-procex/images/anchors}\n  \\caption[Anchors defining positions]{\\label{fig:anchor}Top row: plan anchors (green) and profile anchors (blue) combine to locate a feature (purple). If the edge is not in the active plan at a given height, the feature may not be instanced (red). \nMiddle row: Relative plan anchors define a proportional coordinate system relative to the input plan edge's length, $\\frac{x_1}{y_1}  = \\frac{x_2}{y_2}$  (left). However some features may be repeated (right). Bottom row: Absolute plan anchors define a rectilinear grid over the shell, however they may not be always instanced (red).}\n\\end{figure}\n\nIt is also desirable to be able to position features on the surfaces created by plan edits, introduced in the following section. In this situation we may define plan anchors for the new edges introduced by the plan edits, Fig.~\\ref{fig:pe_anchor_plan_event}. We translate instances of the profiles associated with the plan event by the height of the event. This also moves the associated profile anchors. These anchors may define additional plan edits, leading to a possibly recursive sequence of plan edits. \n\n\\begin{figure}\n  \\centering\n  \\def\\svgwidth{0.9\\columnwidth}\n  \\includesvg{13-procex/images/pe_anchor_plan_event}\n  \\caption[Anchors and plan edits]{\\label{fig:pe_anchor_plan_event}A plan edit may be defined by a plan segment and a profile (left). The geometry arising from the edit may be parametrised in several ways, here we show the use of relative plan anchors (middle). The profiles associated with the plan event are offset by some value, $\\alpha$, such that feature locations are positioned relative to the start of the plan event (right).}\n\\end{figure}\n\n\\FloatBarrier\n\\subsection {Plan Edit Events}\n\\label{s:plan_edits}\n\n\\begin{figure}\n  \\centering\n  \\def\\svgwidth{1.0\\columnwidth}\n  \\includesvg{13-procex/images/plan_edit}\n  \\caption[Plan edits update the corner data structure]{\\label{fig:plan_edit} Inserting a plan edit into the active plan during execution. a) The plan data structure (blue dots, green arrows) implicitly defines the active plan (cyan). b) To insert new edges into the active plan, corresponding edges are linked into the plan data structure. c) The resulting architectural shell. }\n\\end{figure}\n\n\\begin{figure}\n  \\centering\n  \\def\\svgwidth{1.0\\columnwidth}\n  \\includesvg{13-procex/images/natural_step}\n  \\caption[The advantages of natural steps]{\\label{fig:natural_step} Given an intricate plan, calculating a robust perturbation is challenging. Forced steps are positioned at the location of the anchors (a, orange). These are combined with the boundary. However many geometry artifacts are undesirable (c, red) in an architectural situation. Given natural steps at certain positions (a, orange), small changes to the boundary are made (d), which are then grown (e) using a recursive application of procedural extrusions, to create more natural geometry (f).\n }\n\\end{figure}\n\nPlan edits introduce discrete changes to the active plan at specified heights. We describe how plan edits operate efficiently and detail two methods to define them.\n\n{\\bf Input:} Plan and profile anchors defines the location, or locations of the step. In addition the step type (natural or forced), and step geometry is specified. Natural steps have an additional distance parameter.\n\n{\\bf Output:} The output of a plan edit event is an updated active plan, with its boundary altered by the step.\n\nWhen performing a plan edit, some edges are deleted, some edges are moved, and some edges are inserted, Fig.~\\ref{fig:plan_edit}. The new edges are at the height of the current sweep plane.\n\nOur user interface offers two types of plan edits. Inserting an arbitrary shape gives the largest variety of geometric designs. However these \\emph{forced steps} offer no guarantees that the resulting active plan will not self intersect and create an invalid topology. The challenge comes again from the procedural nature of our approach and the fact that the edit has to work for all input plans. \\emph{Natural steps} offer a solution to this problem by using a recursive application of procedural extrusions to insert edges into the active plan.\n\nNatural steps are calculated on the active plan at a given height by amending a small (typically $10^{-3}$ by $10^{-3}$) protrusion. This is offset by a recursive application of procedural extrusions such that it does self intersect, Fig.~\\ref{fig:natural_step}, similar to the edge direction events of Sec.~\\ref{section:edgeDirecitonEvents}. This recursive PE application is constructed by assigning $\\theta = 0$ to all edges not part of the feature, and a user defined $\\theta$ to those edges in the protrusion. The resulting temporary active plan is calculated at a specific height, and this is incorporated into the original active plan. The new edges in the active plan have the relevant profiles assigned to them.\n\nWe have discovered that natural steps can create a wide range of geometry in this robust manner. Buttresses and other disjoint regions can be created by growing the protrusion in such a manner that it disconnects itself, Fig.~\\ref{fig:pe_grow_butress}. The chimney plans of Fig.~\\ref{fig:Chimney}, can be grown by combining this disjoint region with an inwards step, Fig.~\\ref{fig:pe_grow_chimney}.\n\n\\begin{figure}\n  \\centering\n  \\def\\svgwidth{1.0\\columnwidth}\n  \\includesvg{13-procex/images/pe_grow_butress}\n  \\caption[Using the natural step for genus change]{\\label{fig:pe_grow_butress}Given a natural step feature location, a, we may insert a small protrusion, d, intro the active plan. It is possible to assign weights (black arrows) to the edges in such a way that the geometry becomes disconnected. This changes the genus of the active plan, and creates a suitable footprint for a buttress or similar (d).}\n\\end{figure}\n\n\\begin{figure}\n  \\centering\n  \\def\\svgwidth{0.8\\columnwidth}\n  \\includesvg{13-procex/images/pe_grow_chimney}\n  \\caption[An interior step with a genus change]{\\label{fig:pe_grow_chimney}If we combine an step towards the interior of the active plan with a genus change, we can create a suitable plan edit to represent a chimney or similar. Note that the length of the black arrows indicates the relative speeds of the natural step offset.}\n\\end{figure}\n\n\\FloatBarrier\n\\subsection{Mesh Anchors}\n\nIn order to add intricate details to the architectural shells, anchors may also be used to position decorative meshes. A range of simple parametrisations is given by positioning a number of bones which deform the mesh. For example we can increase the height of a pillar without deforming the capitals, as in Fig.~\\ref{fig:Meshes}, left.  \n\n{\\bf Input:} A mesh with $n$ bones, a scale factor, $g$, and $n$ anchor locations, where $n \\geq 1$. \n{\\bf Output:} As the sweep plane passes, the location and orientation of each anchor is recorded. During the post processing stage, if all $n$ anchors are recorded, the mesh is instanced with the scale factor $g$ applied to each bone.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=1.0\\columnwidth]{tt_meshes.png}\n  \\caption[Adding decorative meshes using anchors]{\\label{fig:Meshes} The four example meshes used in the evaluation. The meshes are parametrised via control points (blue and green circles) and can be instanced to different sizes.}\n\\end{figure}\n\n\\FloatBarrier\n\\subsection{Subdivision Events}\n\\label{sec:subdiv_events}\n\nWe may also wish to subdivide a given primary active plan into a number of discrete areas. Like profile offset events these occur over the entire active plan at a specific height, but are specified in the UI using profile anchors rather than the profile polylines. A recursive PE application is again used to ensure a robust manipulation of the active plan, Fig.~\\ref{fig:subdiv}. The boundaries of these new \\emph{subdivision regions} are then assigned profiles corresponding to a combination of their originating primary active plan edge profiles and their classification as {top, bottom} or \\emph{side} edges in the subdivision output shell.\n\n{\\bf Input:} A map from each profile present on the active plan to a \\emph{subdivision profile}, $m$, and a set of tags, $t_x \\in t_0..t_tmax$, attached to subdivision profile segments with properties, $(profile\\_bottom,$ $profile\\_top,$ $profile\\_side,$ $merge\\_bottom,$ $merge\\_top,$ $ merge\\_side)_x$. The map is specified such that $m(profile_1)=profile_2$, where $profile_1$ is a profile in the primary active plan before the subdivision event, and $profile_2$ is a subdivision profile. The Boolean values, $merge\\_bottom,$ $merge\\_top,$ $merge\\_side$, specify whether the subdivision region should be merged with the corresponding abutting region.  The tags, $t_x$, are optionally assigned to a set of polyline segments in the subdivision profiles to mark faces in the subdivision shell, Fig.~\\ref{fig:subdiv}. The profiles, $profile\\_bottom, profile\\_top$ and  $profile\\_side$ are assigned to the newly created subdivision regions in the primary plan. \n\n{\\bf Output:} The output of a subdivision event is a new primary active plan.\n\n\\begin{figure}\n  \\def\\svgwidth{0.9\\columnwidth}\n  \\includesvg{13-procex/images/subdivevents}\n  \\caption[Subdivision events]{\\label{fig:subdiv}The subdivision of the primary active plan is triggered at height by a profile anchor (left: grey circle) into two new regions to create a sawtooth roof. Given the primary profiles (left: purple green orange), the map $m$ specifies the subdivision profiles, (right, arrows), from which we can calculate the subdivision PE (right). The result is projected back to the original active plan, replacing the original geometry, and assigned new profiles. Finally the original sweep plane continues to rise, creating the final mesh (left).}\n\\end{figure}\n\nEach edge in an output shell can be classified as $top$, $bottom$ or $side$ according to to how it was created. Horizontal edges created by the input plan or edge direction events are classified as $top$ or $bottom$, depending on their orientation, while all other edges in the output shell are classified as $side$.\n\nWe create a new, recursive application of procedural extrusions, the \\emph{subdivision} application. Initially this is a copy of the primary active plan, translated to height 0. We update the profile associated with each edge in the subdivision active plan according to the map, $m$. We then execute this instance of procedural extrusions to create a 3d shell. Each face in the subdivision shell may have a subdivision tag, $t_x$ associated with it, which specifies how it is merged into the primary active plan, and which profiles the new edges have.\n\nEach secondary PE face is projected it onto the primary active plan, possibly combining with adjacent regions according to the $merge$ tags associated with $t_x$. The profiles of these new regions on the active plan are given by the $profile\\_bottom, profile\\_top$ and  $profile\\_side$ members of the tuple.\n\n\\begin{figure}\n  \\centering\n  \\def\\svgwidth{0.8\\columnwidth}\n  \\includesvg{13-procex/images/subdiv_rel_abs}\n  \\caption[The subdivision event for creating relative and absolute partitions]{\\label{fig:skel_subdiv_rel_abs} We may use different profiles to divide an irregular plan into regions defined by relative or absolute measures. Above: by assigning the angle on the profile of one edge to be twice the speed (red) of another (purple) we may create a region of relative size $\\frac{1}{3} = \\frac{\\alpha}{\\beta}$ (top left, pink). Below: By only using the lower section of a profile curve, an absolute subdivision of $\\gamma$ units may be created.}\n\\end{figure}\n\nWe note that subdivision events are a generalisation of profile offset events. That is, it is possible to create a profile offset event using a subdivision event. However subdivision events cannot be easily incorporated into the user interface profile curves, and are much more involved for the user because of the specification of $m$ and $t_x$.\n\nSubdivision events are a flexible method of creating relative or absolute portions of a plan. By assigning profiles with angles of a certain ratio, we can split the active plan into relatively sized areas, Fig.~\\ref{fig:skel_subdiv_rel_abs} top. Alternately we can only use a certain polyline segment of the profile to create an area of absolute dimension, Fig.~\\ref{fig:skel_subdiv_rel_abs} bottom. By combing both these techniques, a wide range of shapes can be created. Fig.~\\ref{fig:kensington} gives an example of a relative subdivision event in a modeling context.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=1.0\\columnwidth]{CurvedBuildingFront.png}\n  \\caption[An example of subdivision events for roofs]{\\label{fig:kensington}\n A procedural model that creates a row of houses from a spline. In this case the street was generated by four points defining the street's curve. Seed points were grown using another application of the skeleton to create the building footprints. Relative subdivision events were used to split the roof plan into three areas.}\n\\end{figure}\n\n%-------------------------------------------------------------------------\n\n\\section{Evaluation}\n\\label{Sec:Evaluation}\n\nGiven the PE system consisting of the user interface, and the algorithms to process the user specified events into an architectural shell, we continue to evaluate the usefulness of the system. Initial results such as Fig.~\\ref{fig:multi} shows many typical architectural shells that are not possible using just the straight skeleton, or extrude operations alone. The earlier Fig.~\\ref{fig:kensington} also illustrates how we may generate architecture along a curved street, a challenge for systems such as CGA Shape. We can also create buildings with horizontal roof overhangs, such as Fig.~\\ref{fig:condo}. The alcoves and columns illustrate how disconnected regions can merge together and interact. This is possible because the MWSS can grow as well as shrink, unlike the SS, which can only shrink. \n\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=0.7\\columnwidth]{multi.png}\n  \\caption[A range of structures possible with the PE systems]{\\label{fig:multi}\nFrom top, left: buttress, dormer windows, flying buttress, bay windows, curved plan, eight faces meeting on a symmetrical footprint with a chimney, hipped roof, curved roof, a horizontal overhang, an overhanging gable, standard gable and interior dormer windows}\n\\end{figure}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=1.0\\columnwidth]{condo.png}\n  \\caption[An PE American condo]{\\label{fig:condo}\nInset:  the output of our procedural extrusions using a complex footprint, horizontal sections and plan edits. We are able to create pillars, covered parking and alcoves respectively. Main: A procedural condo with roof texture surrounded by procedural trees}\n\\end{figure}\n\nMore eccentric uses of the PE system can also be imagined. Many other designed forms contain the strong horizontal edges that inspired this SS approach. By rotating the plan, such that the sweep plane moves horizontally rather than vertically, we may model objects such as windows or moldings, Fig.~\\ref{fig:architecture}. As an illustration of the ability to compute extrusions on complex plans we may use a thresholded image as a plan, as in Fig.~\\ref{fig:wonka}, to create artistic representations of images.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=1.0\\columnwidth]{architecture.png}\n  \\caption[PEs for architectural elements]{\\label{fig:architecture} Using a creative set of profiles, a wide range of architectural features can be modelled. By setting the input in a vertical plane, and carefully designing perpendicular profiles these  windows and details may be extruded.}\n\\end{figure}\n\n\\begin{figure*}\n  \\centering  \n  \\def\\svgwidth{0.6\\columnwidth}\n  \\includesvg{13-procex/images/wonka}\n  \\caption[The PE for artistic rendering]{\\label{fig:wonka}A thresholded image (inset) was used as the plan, with one of two profiles randomly assigned, to create this artistic image.}\n\\end{figure*}\n\nHowever, in order to perform a more objective evaluation of the PE system, three different approaches were taken. Firstly, Sec.~\\ref{Sec:GIS_Eval} we examine the use of PEs as an automated GIS procedural modeling system, secondly Sec.~\\ref{Sec:Results} describes our experiences of PEs as an interactive tool. Finally Sec.~\\ref{Sec:Art_Eval} describes the use of the PEs by artists, and documents their opinions of the system.\n\n\\FloatBarrier\n\\subsection{GIS Evaluation}\n\\label{Sec:GIS_Eval}\n\nIn order to evaluate the usefulness of the PE system for procedural modeling, we developed and evaluated a tool that generates 3D meshes given a  \\emph{Geographic Information System} data-set of building footprints. \n\n\\subsubsection{GIS User Interface}\n\nTo generate and apply appropriate profiles to the footprints, we developed a secondary GIS UI. The graphical interface allows users to to apply sets of profiles and anchors to existing plans semi-automatically. Given a set of floorplans from a GIS or similar database, Fig.~\\ref{fig:gis}, the user can specify a \\emph{machine} to assign profiles and anchors to each building plan. Each machine defines a certain style of building, such as Victorian, industrial or Dutch. The tools to assign machines are:\n\n\\begin{itemize}\n\\item{Directly: this sets the assigned machine to all the selected plans.}\n\\item{Painting: after selecting a set of plans to paint, the user selects a machine type from a palette, a brush size, and is then able to assign the machines to profiles by painting over the centrum of each plan with the brush.}\n\\item{By size: After selecting a set of plans, the user can execute a program that assigns machines based on the area enclosed by the floorplans. For example, the smallest buildings may become garden sheds and the largest become factories.}\n\\item{Randomly: The user is given an option to select a fraction of the currently selected plans randomly. This allows, for example, $10\\%$ of the plans in a particular area of the city are assigned machines to create Victorian properties.}\n\\end{itemize}\n\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=0.6\\columnwidth]{atlantis_input_data.png}\n  \\caption[GIS evaluation input data]{\\label{fig:gis}Typical GIS data. In this case this is a subset of the floorplans of buildings in Atlanta (black), which have subsequently been marked up with road data(green).}\n\\end{figure}\n\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=0.8\\columnwidth]{large_scale.png}\n  \\caption[The GIS UI for large scale profile assignment]{\\label{fig:large_scale}The GIS UI allows different sets of profiles (right) to be assigned to different footprints (left). Users are able to edit the sets of profiles that are used to generate the architectural shells.}\n\\end{figure}\n\nEach machine utilises several items of meta-data from the GIS database to enable the assignment of profiles to each edge and other features described by the anchors. The most important datum is an orientation label applied to each edge. This is assigned by an angle computed by orienting the building to the nearest street and mapping the normal vectors of the footprint edges to the unit disk. We assign labels for the \\emph{front, left, right} and \\emph{back} of the building, Fig.~\\ref{fig:assignment}. Furthermore \\emph{short} edges at the front and side of the building are assigned the appropriate profile for their direction. These labels are then mapped by each machine onto profiles.\n\n\\begin{figure}\n  \\centering\n  \\def\\svgwidth{1.0\\columnwidth}\n  \\includesvg{13-procex/images/profile_assignment}\n  \\caption[Automatic profile assignment]{\\label{fig:assignment} Left: Given a plan (solid green) and a road (thick grey line), we assign a set of different profiles (red: front, blue: back, green: right, yellow left, with light and dark shades specifying long and short edges). Centre: the naive ordering assigns a label based on the orientation. Right: the long and short labels are assigned by considering triples of consecutive edges. If the first and last edge of the triple have the same orientation, and the second has a shorter length than the first or third, then the assignment of the second edge is changed to a short edge of the same orientation as the first.}\n\\end{figure}\n\nThe positioning of anchors representing machines is also delegated by these labels. Profile anchors are specified on the associated profiles, while the plan-anchors are positioned by short Java programs which specify an interval to repeat anchors at --- for example to create a row of windows, or a door and several windows.\n\n\\subsubsection{GIS results}\n\nUsing our GIS UI tool we were able to apply PEs to a large scale cityscape. We created a procedural model using about 6000 footprints from Atlanta (see Fig.~\\ref{fig:Strip}). We used our interactive system to apply 4 different machines to generate different styles of architecture to the footprints.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=1.0\\columnwidth]{strip.png}\n  \\caption[Large scale GIS results]{\\label{fig:Strip} We present an interactive procedural modeling system that is able to model difficult architectural surfaces, such as roof constructions. This figure shows procedural extrusions applied to 6000 floorplans  synthesised from a GIS database of Atlanta. Procedural trees were added for decoration.}\n\\label{fig:teaser}\n\\end{figure}\n\nThe resulting geometry has three million polygons, 4 different building styles, took 20 minutes user modeling time, 10 minutes to compute the procedural extrusions, and 15 minutes to render. The automated system used GIEs, horizontal and normal edge direction events, as well as anchor events. One limitation was that we were not able to find a rendering infrastructure to render such a detailed model. We therefore had to omit the decorative meshes from all but the nearest structures. The PE system was implemented in Java and we measured the running times of our system on a $64$bit $2.6$GHz CPU.\n\nThe system efficiently created a large quantity of architectural geometry. However, we were able to identify several geometry failures by manual inspection, as in Fig.~\\ref{fig:failure_mode}. It is likely that these cases were caused by floating point errors, or our use of GIE for event resolution. Typically these errors expressed themselves as missing sections of roof, or very tall, self-inverted roof lines.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=1.0\\columnwidth]{failure_mode.png}\n  \\caption[Failure modes in the automated case]{\\label{fig:failure_mode}The two observed examples of missing geometry. Note the missing roof sections in both buildings.}\n\\end{figure}\n\n%-------------------------------------------------------------------------\n\\FloatBarrier\n\\subsection{Interactive Evaluation}\n\\label{Sec:Results}\n\nWhile procedural evaluation of the PE shows the algorithmic stability and potential for large scale cityscapes, it does not explore the range of forms that can be created. To this end we performed an evaluation of the range of forms that our user interface was able to successfully model. In order to do this we modeled 50 buildings, and recorded the issues encountered. \n\n\\begin{sidewaysfigure}\n\\centering\n\\includegraphics[width=1.0\\columnwidth]{13-procex/images/fifty_houses_1}\n\\caption[Results of interactive evaluation (1)]{\\label{fig:fifty_1}The example cases and modeling statistics. \\emph{v} Vertices in modeled plan (additional vertices); \\emph{l} Polygons in modeled plan (polygons in library plan); \\emph{p} Number of profile sections in model; \\emph{s} Number of natural steps designed (number of natural step applications); \\emph{o} Number of offset events.}\n\\end{sidewaysfigure}\n\n\\begin{sidewaysfigure}\n\\centering\n\\includegraphics[width=1.0\\columnwidth]{13-procex/images/fifty_houses_2}\n\\caption[Results of interactive evaluation (2)]{\\label{fig:fifty_2}Examples continued from Fig.~\\ref{fig:fifty_1}.}\n\\end{sidewaysfigure}\n\n\\begin{sidewaysfigure}\n\\centering\n\\includegraphics[width=1.0\\columnwidth]{13-procex/images/fifty_houses_3}\n\\caption[Results of interactive evaluation (3)]{\\label{fig:fifty_3}Examples continued from Fig.~\\ref{fig:fifty_2}.}\n\\end{sidewaysfigure}\n\n\nEach building was modeled from a plan and a perspective image. A set of four simple meshes were used to add detail to the structures, these meshes are illustrated earlier in Fig.~\\ref{fig:Meshes}. The events used for modeling were edge direction events, profile offset events, natural steps and decorative mesh anchors.\n\n\\begin{figure*}\n  \\centering\n  \\includegraphics[width=1.0\\columnwidth]{european_blocks.png}\n  \\caption[Further source material for interactive evaluation]{\\label{fig:european}Sample aerial photographs of buildings used for modeling examples 46 to 50 in Fig.~\\ref{fig:Meshes}. a,b) Stockholm, c) Copenhagen, d) Edinburgh, e) Vienna. \\copyright 2013 Google.}\n\\end{figure*}\n\nWe undertook the evaluation with the goal that all major geometric features from the elevation drawings should be present, although smaller details (such as cornices, plumbing and decorative windows) were excluded. We traced the plans into the interactive system directly, or via aerial views of the property. The construction of profiles and positioning of features was performed ``by eye'' by the author of this thesis.\n\nThe first 45 buildings were taken from a library of ready designed architectural styles for family homes\\cite{ePlans}, Appendix~\\ref{sec:50_plans}. We modeled the first example in each of the categories in the library. These categories included styles as diverse as \\emph{ranch} or \\emph{Dutch} (Fig.~\\ref{fig:fifty_1}, examples 13 and Fig.~\\ref{fig:fifty_2} 32 respectively), however much of the stylistic content was dependent on architectural details that were replaced with our simple meshes. \n\nBecause the library plans were generic American templates, they had predominantly $90^\\circ$ and $45^\\circ$ degree angles between floorplan edges. That is, the design was not constrained by environmental features. To provide more challenging examples, we chose an additional five buildings from European cities that had irregular plans (Fig.~\\ref{fig:fifty_3}, examples 46-50). These buildings were modeled from satellite and aerial views, Fig.~\\ref{fig:european}.\n\nThe modeling times ranged from 20 to 120 minutes with a mean time of 63 minutes. Features on the input plan smaller than approximately 30cm were not modeled. We also recorded a number of additional metrics for each building: the number of vertices in the input plan and in the model; the number of corner-loops in the input and in the model; the number of profiles in the model, the number of offset events, the number of natural step templates and the number of instances of those steps. These statistics are given in Fig.~\\ref{fig:fifty_1}--\\ref{fig:fifty_3}.\n\n\n\n\\subsubsection{Observations}\n\nIt was possible to model all the buildings using the PE system, although the long modeling times reflect the fact that constructing some roof lines was complex. The results are of a similar detail and use cases as those taken from Trimble Warehouse in Fig.~\\ref{fig:googleWarehouseComp}, when compared without textures or surrounding garden geometry. We continue to describe some of the problems encountered, and conclude with a breakdown of the modelling of a single building.\n\n\n\n\\begin{figure*}\n  \\centering\n  \\includegraphics[width=1.0\\columnwidth]{problem_cases.png}\n  \\caption[Usability issues with PEs]{\\label{fig:problems}a) The red roof face is not described in the input polygon(left). By creating a small change to the input polygon we can create the desired face (green). b) left: edges can be expected to collide at a certain height (green polygons), right: however when these edges are involved in other events (such as those from the red polygon), there may be undesired consequences, here a non-terminating polygon. c) Some structures (such as dormer windows and chimneys) do not obey the volume-maximising resolution to the ambiguous case, in this situation we have to lower the ambiguous case priority of some edges (blue) to get the desired result. d) A face (yellow) may be shared between two profiles (blue lines), defining co-planar profile sections requires patience on behalf of the user.}\n\\end{figure*}\n\nThe most common issue when modeling was the construction of structures that contained edges not specified in the input plan, as shown in Fig.~\\ref{fig:problems} a. In these circumstances it was necessary to add extra edges to model these features. These would either be added in the plan, leading to the difference between the vertices in the input plans and the model in several of the examples, or by natural steps at certain heights.\n\nIn several circumstances one face relies upon another, spatially separated, face to halt its propagation at the correct time; that is, an edge is fated to meet another, as in Fig.~\\ref{fig:problems}, b. When another feature blocks, or changes the course of one of these faces, the other may not terminate, or collide in an unexpected location. These fated edges lead to potentially undesirable intermediate outputs while editing.\n\nModeling circular arches was difficult because any adjustment in the width of the arch, would have to be accompanied by a re-scaling of the profiles. Modeling techniques such as shape grammars are able to retain such semantic information to automate such a process, and it is possible to imagine a similar system for the procedural extrusions.\n\nIt is not convenient to model a roof that is held only by a large number of pillars, because it is not easy to model the transition from pillars to the roof. For example, \\emph{pergolas}, such as those in Fig.~\\ref{fig:fifty_2}, example 31, contain no walls to allow the plan to generate a roof. These were not a large part of our data set, and were approximated by walled structures of similar volume.\n\nIt was occasionally necessary to override our default of a volume maximising priority in the ambiguous case. For example, in the case of a chimney stack or a dormer window of Fig.~\\ref{fig:problems}, c. To do this we used tags to specify high priority and low priority profile segments. This approach proved simple compared to the alternative of specifying a priority for every pair of segments.\n\nIt was relatively easy to split one edge into two by inserting a step event in the edge. In contrast, we found the reverse case quite tricky; allowing two profiles to merge to one. This situation is illustrated in Fig.~\\ref{fig:problems}, d. We see this architectural feature as two different profiles to merge at the top of a shorter roof in Fig.~\\ref{fig:fifty_1}, example 3, and Fig.~\\ref{fig:fifty_2}, example 20. To design a profile with a face co-planar to another is difficult, especially if the second edge starts from an edge parallel, but not colinear to the first.\n\nNatural steps proved very versatile for inserting edges into the polygons. For example, Fig.~\\ref{fig:fifty_2} example 34, required a new edge internal to the plan for the back-facing wall of the tower. By positioning a wide square natural step on the end of the building, it was possible to split the polygon into two. One partition became the tower, and the other the remainder of the roof structure.\n\n\n\nMost small edits to the plans and profile lead to small changes in the geometry and topology of the output mesh. However while modeling these example buildings there were noticeable situations where there were \\emph{discontinuities} --- small user edits causing large changes such as altering the number of output faces, or their connectivity. From a geometric perspective these occur in the MWSS when two or more reflex verticies (or a non-reflex vertex with negative weights) pass each other. From a user perspective we have identified several situations where such discontinuities have affected the modeling process. \n\n\nThe first type of discontinuity arise from the PCE degeneracy of Sec.~\\ref{s:ssd}. When two adjacent edges, which are nearly parallel have different $\\theta$ values, the behaviour of the resulting roof can be erratic as the angle between the edges is set to slightly greater than, or less than zero. In practice these edges do not appear often in architecture. When they do, it is often possible to add a perpendicular edge to lessen the chaotic behaviour, illustrated in Fig.~\\ref{fig:problems}, a. Another class of discontinuity emerges when an overhanging roof suddenly merges with some adjacent geometry, as in Fig.~\\ref{fig:discontinuities}, left. In this situation, moving a single vertex a short distance can cause the active plan to gain or lose several verticies. Finally, we observed the discontinuities in the straight skeleton identified by Eppstein in \\cite{Epp:98}, illustrated here by Fig.~\\ref{fig:skel_reflex_combine}, in several configurations while constructing models. A simplified version of such a case is illustrated in Fig.~\\ref{fig:discontinuities}, right. \n\nWhile modeling we typically encountered one or two of these cases in each of the examples. However, given the interactive feedback of the system, it was relatively simple to adjust verticies to understand, and so avoid the degeneracy.\n\n\\begin{figure}\n  \\centering\n  \\def\\svgwidth{1.0\\columnwidth}\n  \\includesvg{13-procex/images/discontinuities}\n  \\caption[Discontinuities in the modeling space]{\\label{fig:discontinuities}Small changes in the plans can cause large changes in the results. Left: One such discontinuity caused by two portions of an overhanging roof merging. Right: Reflex skeleton arcs can also cause discontinuities.}\n\\end{figure}\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\subsubsection{The Modeling Process}\n\\label{s:the_modeling_process}\n\n\n\nAfter a number of models were created, several distinct phases of modeling became clear. A description of these stages during an 80 minute modeling workflow for a model similar to number 34 follows:\n\n\\begin{enumerate}\n\n\\item{\\label{tmp_first}5 minutes --- Planning and creation of a rough mass model with a single profile, consisting of only 2 segments, on all plan edges. The plan is traced from the given example plan, and the profile is heavily edited to achieve the best fit.}\n\\item{10 minutes --- Massive features requiring natural steps were inserted, in the case of model 34, this was the tower over the garage, but in other models features such as overhangs without matching footprints are created at this stage. }\n\\item {\\label{tmp_third}5 x 5  Minutes --- For each major edge in the plan, the profile was updated to match the example images. Once the new profile was created it was copied to other edges with similar profiles in the plan. Often a profile could be re-used or edited, because similar profiles were found around a building. Portions of the profile could also be shared. For example, the bottom of a \\facade{} without an adjoining roof may be re-used on another edge of the profile that does require a roof. This stage was iterated through five times, each time making smaller additions, corrections, and taking into account previous changes.}\n\\item{10 minutes --- Additional smaller edges were added to the profile. Again, interactive feedback enables feedback as to the result of each change.}\n\\item {\\label{tmp_five}15 minutes --- Smaller natural steps were positioned for decorative elements such as roof elements and chimneys. It was possible to re-use main-plan profiles for several of the new plan edges introduced by the steps.}\n\\item{\\label{tmp_last}15 minutes --- The meshes were positioned using anchors. This was complicated by concave faces, with the need to switch between different anchor types. In addition, the user interface required manually selecting the file to apply, and selecting the appropriate anchors for each window. For grids of windows this was time consuming, but could be easily automated in future work.}\n\n\\end{enumerate}\n\nThese \\ref{tmp_last} stages were typical of many of the 50 models. However there where exceptions; in one example it was necessary to re-start after it became clear that a feature that was modeled by a stage in a profile polychain, would have to be modelled by a natural step instead. In another example, a deviation from this workflow was caused by problematic discontinuities becoming a problem in stage \\ref{tmp_five}, which meant that the user had to return to stage \\ref{tmp_first}.\n\nAfter stage one, a reasonable low-quality model was almost always present. While the resemblance to the given example model was sometime dubious, the results at this stage were obviously ``house-like''. In general, throughout the modeling process, the 3D output that the user worked was obviously a building, and the mesh was mostly watertight. When modeling in a non-domain-specific tool, such as with Blender in Sec.~\\ref{sec:construction}, this is rarely the case. These tools often leave non-planar faces, gaps in geometry and intermediate geometry visible throughout the workflow to distract the user from the object being constructed.\n\nA particularly useful feature of the UI is the fast iteration that it allows in all workflow stages. For example, in stage \\ref{tmp_first} it was useful to quickly examine the results of several different profiles in quick succession, and make a decision as to which was best. In stage \\ref{tmp_third} it was useful to be able to slowly reduce the scale of edits, converging in on a solution with each iteration. Finally fast interactive iteration also helps negates some of the problems with discontinuities that may occur; it is easy to quickly backtrack and explore the geometry which causes a particular discontinuity, whether it is desired or not.\n\n\n\n%However, our modeling system is more specialized than most commercial polygonal modeling packages. The virtual model of Atlanta is unique and we argue that no existing approach can model a city of comparable (roof) complexity in reasonable time.\n\n\\FloatBarrier\n\\subsection{Artistic Evaluation}\n\\label{Sec:Art_Eval}\n\nThe final evaluation technique was intended to investigate the usability of the system by those unfamiliar with procedural modeling. We employed two artists to use the system part time for four weeks. These users reported that it took between 5 hours and 3 weeks to become competent with the tool, given a short three page user guide. Brief telephone calls were made with the artists, and no direct tutoring occurred. \n\nDuring this training the artists were able to create a number of interesting forms, Fig.~\\ref{fig:chase_galen_funtime}. Finally they were asked to create some complex example meshes, Fig.~\\ref{fig:chase_galen}. To create these complex examples the artists created their own custom meshes to attach. This took the total modeling time to 30 hours for both artists, although the time spend using the procedural extrusion system ranged from 5-10 hours. The time saved compared to standard mesh modeling techniques was estimated by the artists to be between 5 and 15 hours.\n\nWhilst this approach only gives a coarse qualitative metric, it shows the applicability of the procedural extrusions in the real world. The final interviews with the artists are recorded in Sec.~\\ref{sec:artists_comments}. Both artists commented that the PE system was faster to use than commercial generic mesh modeling packages.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=1.0\\columnwidth]{chase_galen_funtime.png}\n  \\caption[Artist's use of PEs]{\\label{fig:chase_galen_funtime}The artists' example work while learning to use procedural extrusions. Note the wide range of roof shapes easily expressed in the system.}\n\\end{figure}\n\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=0.7\\columnwidth]{chase_galen.png}\n  \\caption[Further artistic use of PEs]{\\label{fig:chase_galen} The final projects from user 1 (above) and user 2 (below). These took ``10 hours'' and ``5-10'' of work with the PE system.}\n\\end{figure}\n\n\\FloatBarrier\n\\subsection{Notable external applications}\n\nProcedural extrusions have been used in external academic and commercial projects.\n\n Fig.~\\ref{fig:clockwork_empires} illustrates the intended use of procedural extrusions in the video game \\emph{Clockwork Empires}\\cite{clockworkEmpires}. This project, which is still in development, extends on the work presented here by including texturing, and forced termination at specified height --- ``caps'', stop the user creating run-away geometry that may become very tall.\n\n\\begin{figure}\n  \\centering\n  \\def\\svgwidth{1.0\\columnwidth}\n  \\includesvg{13-procex/images/clockwork_empires}\n  \\caption[Clockwork Empires video game.]{\\label{fig:clockwork_empires}\\copyright 2012, 2013, Gaslamp Games. Clockwork Empires\\cite{clockworkEmpires} uses procedural extrusions to generate buildings from user specified footprints. Top: The user designs a footprint. Bottom Left: the resulting mesh. Bottom Right: Another in-game building in context.}\n\\end{figure}\n\nIn an academic project, our PE library has been integrated into the skylineEngine\\cite{skyline}, implemented in Houdini3D\\cite{houdini}. This project allows basic plans and profiles to be defined inside the Houdini environment, as in Fig.~\\ref{fig:houdini_integration}.\n\n\\begin{figure}\n  \\centering\n  \\def\\svgwidth{1.0\\columnwidth}\n  \\includesvg{13-procex/images/houdini_integration}\n  \\caption[Integration with Houdini.]{\\label{fig:houdini_integration}\\copyright Gustavo Patow 2012. The integration of our PE implementation with Houdini. Top: Two views of a Raccolet style house, and the graph that generates it. Bottom: Two views of a ``sea view'' style house.}\n\\end{figure}\n\n\\FloatBarrier\n\\section{Comments}\n\nA significant decision made early on in the development of the PE system was to choose between an exact arithmetic or a floating point implementation. Our floating point implementation is well suited to interactive modeling applications because it prioritises interactive update speeds over high precision. An exact arithmetic approach may be important to give theoretical guarantees and such an alternative implementation would be very valuable. Posing a particular problem to such a rigorous approach is the lack of a solution for a generic MWSS -- the pincushion problem of Sec.~\\ref{sec:pincushion}.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=1.0\\columnwidth]{comparison.png}\n  \\caption[Comparison of PEs with previous systems]{\\label{fig:Comparison}Left: Straight skeleton; Middle: Straight Skeleton with angle changes; Right: Procedural extrusions}\n\\end{figure}\n\nAn informative perspective on the PE system is to consider the MWSS as a system for automated and domain-appropriate information loss. The user inserts data into the system, in the form of UI specified events, and the MWSS removes it in an architecturally appropriate manner. As the sweep plane rises, MWSS events such as split and edge events remove edges (and information) from the active plan. Concurrently the input plan, edge direction events, profile offset events and subdivision events insert additional information into the active plan. This contrast invites the description of PE as an \\emph{automated information loss} system. The user specifies the places to insert additional data, while the MWSS is utilised to remove it in an architecturally-meaningful manner. An example is given in  Fig.~\\ref{fig:complexity_reduction}.\n\n\\begin{figure}\n  \\centering\n  \\def\\svgwidth{0.7\\columnwidth}\n  \\includesvg{13-procex/images/complexity_reduction}\n  \\caption[The PE as an automated data-loss system]{\\label{fig:complexity_reduction} A procedural extrusion model of a haunted house. The green lines show where data is inserted into the rising sweep plane, and the red lines show where an user event removes data.}\n\\end{figure}\n\nAn interesting challenge is that it is possible, and indeed probable, that the \\facades{} generated the PE system are not rectangular. The large variety of shapes that a \\facade{} can take leads to issues integrating the PE system with other approaches which expect shapes to be rectangular, such as CGA Shape. While the system of deformable meshes and anchors has been successful in positioning elements, describing a repeating facade over an irregular polygon is still a matter for research. This problem has been particularly evident when integrating PEs with Houdini.\n\n\\FloatBarrier\n\\section{Summary}\n\nIn contrast to the previous chapter, which used the straight skeleton for modeling parcel subdivisions, this chapter has introduced an application of the MWSS to the modeling of complex architectural shells. \n\n\n\nWe took inspiration from the range of man-made objects that contain offset surfaces, and observed that the strong horizontal edges in many common architectural forms can be generated by offsetting the plan of such a building. This lead us to the same conclusion of many architects: that plans and elevations (profiles) are a very effective way of representing a wide range of structures. Given the theoretical foundations of straight skeletons in Chapter 3, and the success in implementing a block subdivision scheme in Chapter 4, it was possible to envisage a system where the geometric self-sensitivity and expressive power of the MWSS was exploited to combine a plan and multiple profiles into a 3D mesh. The 3D terrain model of the MWSS itself proved very capable at creating mass models of many complex buildings, and in particular roof structures.\n\nExisting modeling techniques, such as the extrude operation and Havemann's\\cite{Havemann:2005:GMM} roof modeling constrain the direction of the extrudes to angles above the sweep plane. By using profile offset events and horizontal edge direction events, the PE system can simulate arbitrary non-monotonic elevations. This dramatically increases the range of shapes possible. Theoretically it is possible to encode an arbitrary mesh into a system of PEs, with an arbitrary sweep plane direction. This is, however, future work.\n\nThere were several limitations of this basic approach, which necessitated various innovations. In order to create overhanging and even hollow roofs, we used various sub-applications of the straight skeleton to define the required geometry in a procedural manner. Another issue was that the \\facades{} of the output geometry were not rectangular, making it difficult for conventional systems, such as split shape grammars, to position windows and doors. To resolve this issue we introduced several types of anchors, giving different parametrisations of skeleton faces. To model the windows and doors themselves we resorted to a bone based technique which could deform and position decorative meshes across buildings.\n\nBecause the entire PE input was geometrically defined, it was possible to describe the system entirely with a graphical editor for plans and profiles. We were able to illustrate that the complete PE system is both usable and useful to people without significant programming experience. The expressibility of the system was successfully evaluated by modeling a large number of sample buildings from a catalogue with our user interface. We were eventually able to model all of our sample buildings using our UI.\n\nIn addition to demonstrating that the PE system is suitable for interactive architectural modeling, we also illustrate that it is suitable for kilometer scale procedural cityscape visualisation. We built a framework to generate large scale geometry given a set of floorplans provided from a GIS source. In this system we observed minimal errors and proved that the PE system was robust enough for large scale procedural geometry creation.\n\n\n\n\n%In addition, we have introduced a novel improvement to mesh instancing in procedural modeling. Arrangements of anchors securing deformable meshes to the shell allow a larger variety of decorative elements to be specified than the traditional techniques of translation and scaling.\n\nThe theoretical problems underlying the specification of MWSS events have had minimum impact on the usefulness of the PE system. While a few failures cases were encountered in the large scale GIS test case, this issue has not caused significant problems during software development or evaluation.\n\nWe believe that the PE system is the first to provide a solution for the procedural modeling of walls, roofs, and complex architectural elements from arbitrary building footprints. The main contribution of this chapter is the design of a set of tools that extend the basic extrude operation into one that is geometrically self-sensitive. These tools are able to model a wide range of architectural surfaces that may have not been expressible with previous PGM systems.\n\n%-------------------------------------------------------------------------\n\\begin{comment}\n\n\\section{Recursive procedural extrusions}\n\nAnother view of the procedural extrusion system is that we have defined a language of WSS applications. We describe a sequence of operations that detail how to build a particular structure. \n\nThis sequence of operations is recursive. A plan edit can be viewed as a function call; It introduces another set of edges into the plan that, in turn, may call other functions (plan edits). \n\nIf a plan edit contains a use (plan anchor and profile anchor) of itself, we would describe this as a \\emph{recursive function}. In our case, there is a condition associated with the recursive call. If the edge associated with the plan anchor is removed from the active plan before we reach the profile anchor, the call may not occur.\n\nFig.~\\ref{fig:recursive} shows an example of a recursive procedural extrusion function. \n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=1.0\\columnwidth]{recursive.png}\n  \\caption[Recursive PEs as a growth system]{\\label{fig:recursive}Left to right and top to bottom: A never ending sequence of plans generated by a simple procedural extrusion function. A diamond shaped plan edit introduces two instances of itself at different heights. The profile associated with the diamond edit first expands itself, then shrinks. The seed shape is a trapezium.}\n\\end{figure}\n\n\\section{Shape simplification}\n\\label{sec:shape_simplification}\n\nHere we note that an application of an offset surface (a straight skeleton with all edges of $\\theta = const, const \\neq 0$) is sufficient to simplify reflex ($\\theta < 0$) or convex corners ($ \\theta > 0$), Fig.~\\ref{fig:simplify_outlines}. If we apply both offsets in sequence we have a fairly robust polygon simplification tool, Fig~\\ref{fig:simplify}.\n\nThere are several drawbacks with the straight skeleton as a simplification tool. It does not introduce new edges to the polygon, so polygons that do not contain an edge with a good approximation for the local region are not simplified well. ``Very'' reflex corners have a disproportionate effect on the result. However this may be rectified using a variation of the linear axis. The computational complexity is also higher than that of existing algorithms.\n\nThe advantages are that it is very conceptually simple, robust to any input shape and compatible with the other approaches given in this document. We also gain some ability to mark edges as important, buy manipulating their weights when using the weighted straight skeleton. The theory extends easily into higher dimensions.\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=1.0\\columnwidth]{simplify_outlines.png}\n  \\caption[Shape simplification using PEs]{\\label{fig:simplify_outlines} Taken an input shape (a), we may shrink it, to create an simplified version (b), however concave corners remain unsimplified. Alternately we may grow it (b), but convex corners remain unsimplified. However if we shrink, then grow the shape (d) both concave and convex verticies are eliminated.}\n\\end{figure}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=1.0\\columnwidth]{simplify.png}\n  \\caption[Results of shape simplification]{\\label{fig:simplify}The operations in Fig.~\\ref{fig:simplify_outlines} a, c and d shown in solid 3d (above) and wireframe (below).}\n\\end{figure}\n\n\n\n\n\\subsection{Notes: Pseudocode}\n\\label{sec:pseudocode}\n\n\n\n\\begin{algorithm} \n\\begin{footnotesize}\n\\begin{minipage}{0.45\\textwidth}\n  Main \\Begin{\n    \\ForEach{ corner $c_i$ } {\n        InsertCornerInPriorityList( $c_i$ )\\;\n    }\n\n    sweepZ = 0;\n\n    \\While { !EventPriorityQueue.Empty() } {\n        event = PriorityList.FindNextEventsWithin( $\\epsilon_2$ )\\;\n\t\\If { event.height() $>$ sweepZ }\n        {\n\tsweepZ = event.height()\\;\n        eventClusterList = Cluster( event, $\\epsilon_3$ )\\;\n\n        \\ForEach{ cluster cl in eventClusterList } {\n            HandleEvent( cl )\\;\n        }\n        }\n    }\n}\n\n  InsertCornerInPriorityList( corner $c$ ) \\Begin{\n     p1 = c.NextEdge.GetPlane()\\;\n     p2 = c.PrevEdge.GetPlane()\\;\n     \\ForEach{ roof-plane p3 in the input} {\n        PriorityList.insert(\\\\\n\t    IntersectAndCreateEvent(p1, p2, p3))\\;\n     }\n   }\n\\end{minipage}\n\\end{footnotesize}\n  \\caption{Pseudo-code for the main part of the algorithm\n  }\n  \\label{code:pseudocode1}\n %\\vspace{-0.6cm}\n\\end{algorithm}\n\n\\begin{algorithm} \n\\begin{footnotesize}\n%\\begin{scriptsize}\n\\begin{minipage}{0.45\\textwidth}\n  HandleEvent( EventCluster $ec$ ) \\Begin{\n    RemoveAllInactiveEdgesFromCluster( $ec$ )\\;\n    $chainList$ = BuildEdgeChains( $ec$ )\\;\n    \\If { $chainList$.countEdges() $<$ 3} {\n\treturn\\;\n    }\n    \\ForEach{ chain $chain_j$ in $chainList$ } {\n            \\ForEach{ consecutivePairOfCorners $c_k,c_l$ in $chain_j$ }\n            {\n                AddSkeletonEdge($ec.location,c_l$)\\;\n                $c_l$.inactive = true\\;\n            }\n        }\n\n    \\ForEach{ consecutive $chain_j, chain_k$ in $chainList$ } {\n            $c1$ = firstCornerOfLastEdgeOf $chain_j$\\;\n            $c2$ = firstCornerOfSecondEdgeOf $chain_k$\\;\n            $cnew$ = createNewCorner( $ec.location$ )\\;\n\t    $cnew$.PrevEdge = $c1$.NextEdge\\;\n            $cnew$.NextEdge = $c2$.NextEdge\\;\n            InsertCornerBetween( cnew, c1, c2 )\\;\n    }\n\n    FindEventsForNewCorners()\\;\n    FindRemoveUnusedEdges()\\;\n}\n\\end{minipage}\n\\end{footnotesize}\n  \\caption{Algorithm for the generalised intersection event.\n  }\n  \\label{code:pseudocode2}\n\\end{algorithm}\n\\end{comment}\n%FIXME: following algorithm doesn't fit on one page\n\\begin{comment}\n\\begin{algorithm} \n\\begin{footnotesize}\n\\begin{minipage}{0.45\\textwidth}\nResolve \\Begin{\nListOfCorner $chains$ = ChainsOfAmbiguousBisectors()\\;\n\\ForEach{ $g$ in $chains$ } {\n    SetOfCorner $f$ = FindHighestPriorityFirstCorners(g)\\;\n    Boolean $inside$ = ! ( $f$ contains (FirstIn($g$)) )\\;\n    \\ForEach{ $c_i$ in $g$ }{\n        \\If {$c_i$ member of $f$}{\n          \\If {!$inside$}{\n            $inside$ = false\\;\n            AddSkeletonEdge ($c_i$, Raise ($c_i$))\\;\n          }\n        }\n\t\\Else  {\n            \\If {$inside$}\n            {\n              $inside$ = false\\;\n              AddSkeletonEdge ($c_i$, Raise ($c_i$))\\;\n            }\n            AddSkeletonEdge(Raise($c_i$),Raise ($c_i$.nextCorner))\\;\n        }\n    }\n}\n\nCorner $first$ = Raise(FirstIn($g$))\\;\nCorner $last$ = Raise (LastIn($g$).nextCorner)\\;\nInsertCornerBefore($g$, $first$)\\;\nInsertCornerAfter($g$, $last$)\\;\nRemoveCorners($g$)\\;\n$first$.nextEdge = FindOneEdge($f$)\\;\n$last$.prevEdge = FindOneEdge($f$)\\;\n$first$.nextCorner = $last$\\;\n$last$.previousCorner = $first$\\;\n\n}\n\n\nFindHighestPriorityEdges \\Begin (g)\n{\n  \\If{ VolumeMaximizing } {return members of g with largest angle\\;}\n  \\ElseIf { VolumeMinimizing } {return members of g with smallest angle\\; }\n}\n\nRaise \\Begin (Corner $c_i$) {\n   \\If { cache contains $c_i$} {\n\treturn cache.get($c_i$)\\; }\n   $raised$ = new Corner ( Collide ( $sweep plane$, $c_i$.previousEdge, $c_i$.nextEdge ) )\\;\n   return $raised$\\;\n}\n\n\n\\end{minipage}\n\\end{footnotesize}\n  \\caption{Pseudo-code for the resolving the ambiguous case. Calculates a geometrically consistent solution to the ambiguity given a chain of corners that start edges which become coincident and adjacent at a the sweep plane's height.}\n  \\label{code:ambig}\n\\end{algorithm}\n\n\n\\subsection{Notes from Architectural Geometry, Pottman, Asperl et al.}\n\nextrusion / translational / rotational surfaces\nruled surface: generated by moving a straight line spiral ramps, cones, cylinders, mobius strips. can be created by drawing lines between two arbitrary parametrised curves in r3\nsweeping along a path. (Parametrised path defines a parametrised path for the frennet frame).\nskinning: filling in between arbitrary curves. a very under constrained problem\n\nis there something of a hierarchy here:\nextrusion is translation along a straight line\nruled surface is an extrusion surface with a straight line profile\nrotational surface is an extrusions surface with a circular plan\n\ncurve evolution - Darboux's polygon evolution (1878). always moves verticies of polygon to a point. or changing the offset in a level-set.\n\nosculating circle - curve of circle approaches local curvature of 3 points on a curve (as the three points move together in the limit). It forms one type of an offset - an evolute. \n\n\nconcepts of local trimming and global trimming required for offset curves to be slightly sensible\n\nphoto chapters page 339.\n\n\n\n%% XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n\n%\\section{Algorithm}\n%\\label{sec:WSS}\n%\n%In this section we give an overview of the algorithm to create the procedural extrusions defined by the user interface. This algorithm extrudes the plan according to a set of profiles. We begin with an overview of the algorithm, before discussing the many possible events that drive the extrusion algorithm, and finally giving details of the computation.\n%\n%\\section {Overview}\n%\\label{sec:method}\n%We describe the input, the output, define the terminology, and give an outline of the algorithm. \n%\n%\n%{\\bf Input:} The main input of the algorithm is a non intersecting collection of oriented polygons in the plane. These polygons defines a bounded area on the left-hand side of each directed polygon line segment. A polygon, $p$, is described by $n$ polygon corners $c^p_i \\in R^3$ with $1 \\leq i \\leq n$. All input corners are restricted to the same height value, that is they lie in a plane parallel to the $xy$-plane.  Each corner $c^p_i$ is connected to its counter-clockwise neighbor by an \\emph{edge} $e^p_i$. Additionally, each edge is associated with a gradient, defined by an angle $\\theta^p_i$ such that $-\\pi/2 \\leq \\theta^p_i \\leq \\pi/2$. A vertical gradient has $\\theta^p_i = 0$, whilst a gradient oriented towards the interior (or exterior) of the bounded area satisfies  $\\theta^p_i > 0$ (respectively  $\\theta^p_i < 0$). Each edge $e^p_i$ together with the associated angle $\\theta^p_i$ define a, possibly infinite, face $sp^p_i$. See Fig.~\\ref{fig:InputOutput}.\n%\n%In everything that follows, indices should be treated cyclically, so that in a triangle with corners $c^p_1$, $c^p_2$, and $c^p_3$, the vertex $c^p_4$ means $c^p_1$.\n%\n%Note that the orientation for polygons that define holes is reversed (clockwise) and that we can have an arbitrary nesting of oriented polygons (another loop inside a hole). Without loss of generality we describe the algorithm for a single polygon, as multiple polygons can just be interpreted as a single polygon with multiple disconnected loops. \n%\n%In addition to the collection of polygons, our input contains a set of \\emph{events} are defined (generalized intersection events, edge direction events, profile offset events and anchor events).\n%\n%\\begin{figure}\n%  \\centering\n%  \\includegraphics[width=1.0\\columnwidth]{skel_into.png}\n%  \\caption{\\label{fig:InputOutput}\n%\n%In this example our algorithm constructs a set of faces, shown on the right, for input polygons, shown on the left. In this simple example, each profile only has a single segment; Adding additional segments to the profile eventually allows us to model an entire house, including the walls. The input is defined by the corner positions $c_i$, the gradient $\\theta^p_i$, and the corner connectivity. The plane in which each face $sp^p_i$ lies in is calculated from the edges and gradients. The arcs correspond to sides of the output polygon that are not edges.}\n%\n%\\end{figure}\n%\n%\n%{\\bf Output:} The output of the algorithm is a graph of \\emph{arcs} (after Aicholzer\\cite{Aichholzer95:ANT}) connecting the corners, which includes the input plan corners and new corners stemming from intersection points. Each arc is associated with two edges, and defines a portion of the edge's face boundary. A single edge and the associated arcs together define the boundary of each face.  In the non-degenerate case we obtain a watertight 2-manifold polygonal mesh. This output can then be post-processed to apply textures, add procedural geometry, and attach meshes at anchor points.\n%\n%It is important to emphasise that an edge introduces a new face into the execution, as well as forming one of the boundaries of its face in the output, while an arc is simply an method of storing the output, a boundry of two faces.\n%\n%%\\begin{algorithm} \n%\n%\\begin{footnotesize}\n%%\\begin{scriptsize}\n%\\begin{minipage}{0.45\\textwidth}\n%  main \\Begin{\n%    $Q$ = new priority queue\\; \n%    \\ForEach{ corner $c_i$ in $input$} {\n%\\tcc{Queue ordered by z-height}\n%        $Q$.insert ( $c_i$, $c_i.z$ )\\;\n%    }\n%\n%    sweepZ = 0;\n%\n%    \\While { ! $Q$.empty() } {\n%        $event$ = Q.nextEvent()\\;\n%\t\\If { $event$.position.z $\\geq$ sweepZ }\n%        {\n%\t  sweepZ = $event$.position.z\\;\n%          \\tcc{handleEvents may insert additional events into $Q$}\n%          handleEvent(event)\\;\n%        }\n%    }\n%}\n%\\end{minipage}\n%\\end{footnotesize}\n%  \\caption{Pseudo-code for the main dispatch loop.}\n%  \\label{code:main_loop}\n%% \\vspace{-0.6cm}\n%\\end{algorithm}\n%\n%{\\bf Outline:} \n%\n%The algorithm describes a moving \\emph{wavefront} over a sweep plane that rises from the (input) edges. The wavefront defines a 2d cross-section through an architectural solid.\n%\n%Starting from the input polygon a wavefront propagates from each edge, moving according to their gradient as the sweep plane rises. This movement and implicitly defined geometry is straightforward until an \\emph{event} occurs. During events, modifications to the wavefront occur, such as the creation and deletion of new edges, corners or arcs. \n%\n%The core algorithm, Fig.~\\ref{code:main_loop}, is a loop that handles events according to their height from the plane in which the edges are embedded\\cite{Felkel:1998:SKI}. The resulting architectural solid consists of regions of the faces $sp^p_i$ bounded by corners, and the input polygon\n%\n%DELETE: The algorithm uses a sweep plane that is initially defined as the plane containing the input edges, and moves upwards in the $z$ direction, remaining parallel to the input plane. During the sweep, a multitude of \\emph{events} are encountered and processed. These can be basic topological changes or user driven events such as offset or anchor events.  \n%\n%\\begin{figure}\n%  \\centering\n%  \\includegraphics[width=1.0\\columnwidth]{split_edge_vertex.png}\n%  \\caption{\\label{fig:AlgorithmExample}\n% An example construction demonstrating basic topolgoical events, and the wavefront (blue, green and red lines) on the sweep plane after each event is processed. In (1) three adjacent faces collide at an \\emph{edge event}. In (3) we see a \\emph{split event} that divides the area bounded by the wavefront. Finally, (2) shows a vertex event where more than three faces collide at one point. The sides of the mesh, that do not form the input polygon (a-i), are the resulting \\emph{arcs}.  \n%  }\n%\\end{figure}\n%\n%\\begin{figure}\n%  \\centering\n%  \\includegraphics[width=0.8\\columnwidth]{pointers.png}\n%  \\caption{\\label{fig:pointers}\n% The data structure used to build the skeleton, shown midway through the sweep}\n%\\end{figure}\n%\n%{\\bf Data structures:}\n%The plan data structure implicitly defines the wavefront on the sweep plane, $sp_s$. This structure is a doubly linked list of corners. Each corner has a pointer to the next corner and the previous corner (assuming counter-clockwise order) and a pointer to its previous and next edges, Fig.~\\ref{fig:pointers}. Like the input polygons, the wavefront is a non intersecting collection of oriented polygons. Each corner and following corner define a single \\emph{wavefront-edge}, (not to be confused with the \\emph{edges} in the input) on the sweep plane. Each wavefront-edge has propagated from an edge. We calculate the wavefront for each polygon, $p$, by processing all corners, $c^p_i$. Given $c^p_i$, and the following corner, $c^p_{i+1}$, we find the associated faces with edges $e^p_{i-1}, e^p_i, e^p_{i+1}$, that is $sp^p_{i-1}, sp^p_i, sp^p_{i+1}$. We intersect the planes in which faces $sp^p_{i-1}, sp^p_i$ are embedded, and the sweep plane $sp^p_s$ to form the start of the wavefront-edge. Similarly $sp^p_{i}, sp^p_{i+1}$ and $sp^p_s$ are intersected to find the end of the wavefront-edge.\n%\n% At the beginning of the algorithm the data structure encodes the input. During the sweep the data structure is updated to define which corners and which portions of which edges define the bounds of the solid.\n%\n%A second important data structure is an priority queue that sorts events by ascending height. The strategy of our algorithm is to use a lazy evaluation of events. We fill the priority queue with a large number of potential intersection events. Wherever three or more of the unbounded faces intersect, there is a potential generalized intersection event. In addition there may be other, user-defined events (edge direction events, profile offset events or anchor events). \n\n\n\\end{comment}\n\n", "meta": {"hexsha": "b51e890b1b9d6f2b855312a0ab83892c05a528f1", "size": 135102, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "13-procex/procex.tex", "max_stars_repo_name": "twak/unwritten_tex", "max_stars_repo_head_hexsha": "f3f05310e749887a5d149bd416f8c791c21010e7", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-02T00:32:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-02T00:32:05.000Z", "max_issues_repo_path": "13-procex/procex.tex", "max_issues_repo_name": "twak/unwritten_tex", "max_issues_repo_head_hexsha": "f3f05310e749887a5d149bd416f8c791c21010e7", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "13-procex/procex.tex", "max_forks_repo_name": "twak/unwritten_tex", "max_forks_repo_head_hexsha": "f3f05310e749887a5d149bd416f8c791c21010e7", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 97.6876355748, "max_line_length": 1313, "alphanum_fraction": 0.7780639813, "num_tokens": 31186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.31331261199117677}}
{"text": "%-----------------------------------------------------------------------------------------------\n\\section{Conclusions}\n\n    This     work     has     illustrated     the     validity     of      Carnot's      general\n    proposition~\\cite{1897-ThurstonRH-Wiley} by using a parametric, reversible  Stirling  engine\n    model from the literature~\\cite{2012-ChengCH+YangHS-ApEnergy} that takes into account engine\n    geometry and working fluid properties. Moreover, the analytic nature of the model, with  its\n    exact solution, helps in keeping the illustration concise and exact, and generic up  to  the\n    model's modeling space.\n\n    In one hand, the example illustrated herein is less generic and less conceptual (i.e.,  more\n    instantiated) than the canonical proof by contradiction using only general concepts, usually\n    presented  in   thermodynamics   courses   and   textbooks~\\cite{2013-CengelYA+BolesMA-AMGH,\n    2002-MoranMJ+ShapiroHN-LTC, 1986-JonesJB+HawkinsGA-Wiley}, and therefore, evidently does not\n    serve as a general replacement of the proof by contradiction.\n\n    On the other hand, the illustration based on a reversible model of a \\emph{real}  engine  is\n    more defined and hopefully more palpable and interesting  to  inquiring  students.  One  can\n    argue that at least the illustration complements the proof by contradiction  and  may  boost\n    interest by the more concrete approach.\n\n%-----------------------------------------------------------------------------------------------\n\n", "meta": {"hexsha": "351bf533ccd301f5fe93c8607ba9f1259494a58a", "size": 1523, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "01-04-conclusions.tex", "max_stars_repo_name": "cnaak/man-CarnotPrinciple", "max_stars_repo_head_hexsha": "b258fa7508d8049d2c1a958ffab58ff9b17c78ff", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "01-04-conclusions.tex", "max_issues_repo_name": "cnaak/man-CarnotPrinciple", "max_issues_repo_head_hexsha": "b258fa7508d8049d2c1a958ffab58ff9b17c78ff", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "01-04-conclusions.tex", "max_forks_repo_name": "cnaak/man-CarnotPrinciple", "max_forks_repo_head_hexsha": "b258fa7508d8049d2c1a958ffab58ff9b17c78ff", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 63.4583333333, "max_line_length": 96, "alphanum_fraction": 0.6506894288, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3133126119911767}}
{"text": "\\chapter{Introduction}\nThe energy difference between an uncharged species and its negative ion, referred to as an electron affinity (EA), is an important property of atoms and molecules. \\cite{oldpaper}\nThe application of EA spreads over many chemical areas including gas-phase ion chemistry \\cite{gasion}, pure chemistry \\cite{pure}, material science and environmental chemistry \\cite{environment}. EA also plays an important role in silicon \\cite{silicon} and quantum dot \\cite{quantumdot} semiconductor chemistry and polymer photo-luminescence \\cite{luminescence}.\n\nExperimentally, EA can be measured by a photon source of energy $h\\nu$ to detach an electron from molecular anion $\\text{A}^{-}$.\nBy determining the minimum photon energy needed to detach an electron, one determines the EA.\nThe most direct technique for determining negative EAs is to use electron transmission spectroscopy in which a beam of electrons having kinetic energy impinges on a neutral molecule.\nIf the negative kinetic energy matches the (negative) EA of the molecule, one of the beam’s electrons can be captured into an empty orbital of the neutral to form the metastable anion, which can be detected either by measuring attenuation of the incident electron beam or by probing the electron ejected at right\nangles to this beam.\n\nHowever, theoretical study of EA is still important.\nFirst, many of chemical substances are constituents in many ionic compounds and materials, so their stability, spectra, sizes, and other chemical properties need to be characterized, and often it is difficult to study them experimentally.\nFor example, the ubiquitous sulfate anion $\\text{SO}_4^{2-}$ cannot be studied experimentally as an isolated species because it undergoes spontaneous electron loss within a very short time (less than $10^{-14}$ s), but it has been studied theoretically \\cite{SO4} using special tools to handle its metastable character.\n\nIn addition, anions bind their outermost electrons rather weakly , and hence their valence-range electron densities are diffuse.\nThis causes them to interact strongly with their environment (e.g., in solution or in crystals), making their behavior strongly influenced by the surroundings and causing them to be excellent probes of their environment.\n\nHowever, theoretical study of EA is not a easy task compared with ground state energy.\nThe reason is that EA is only a very small part of total ground state energy.\nThus, the energies of neutron and anion must be determined to high orders.\nFor example, EA usually lies between 0-5 eV, while the ground state energy of very small molecule like $\\text{C}_2\\text{H}_6$ is more than 2000 eV.\n\nIn history, the early work of Pekeris obtained a theoretical EA for a single hydrogen atom, which matched really well with experiments. \\cite{pekeris}\nHowever, a lot of difficulties have been met when it comes to EA of other atoms or molecules, ending up with many negative EA results.\nAs is pointed out by Blondel \\cite{blondel}, the existence of negative ions depends significantly upon the instantaneous correlation of the motions of electrons, which means Hartree-Fock will not give even qualitatively correct result.\n\nBy far, the most popular method for EA is density functional theory (DFT) because of its wide application to many problems, high reliability and also because it is easy to use and computationally cheap.\nHowever, DFT does not give very good result compared with high-level electronic structure methods like Coupled Cluster (CC).\nCC explicitly include consideration of electron affinity and can thus give very impressive results.\nHowever, CC is a computationally very expensive method because nonlinear equations need to be solved.\nThus, applications of CC are limited to medium sized systems with up to 60 atoms.\n\nAnother prominent quantum chemistry method to study EA of small and medium-sized molecules is the algebraic diagrammatic construction scheme (ADC).. \\cite{implementation, ADCpp}\nDue to its size-consistency and Hermitian structure, the ADC scheme is known to be an accurate and reliable approach for the calculation of anion states and their properties.\nGenerally, the approach is based on a Green’s function formalism in combination with the typical M{\\o}ller-Plesset (MP) partitioning of the Hamiltonian.\nI implemented restricted calculation of Non-dyson ADC algorithm into a developmental version of \\emph{adcman}, which is a part of Q-Chem program package.\nThe results match well with that of CC, while consuming less time.\n\nThe thesis is organized as follows:\n\nIn chapter 2, I will present important and popular quantum chemistry methods and give a comparison between them from computational complexity, size consistency and performance to include electron correlation.\nIn chapter 3, I will introduce the theory of ADC from Green function and perturbation theory.\nI will discuss both Dyson approach and Non-dyson approach and give a comparison of both methods.\nI will also introduce intermediate state representation (ISR) for a better understanding of the efficiency and size consistency of ADC.\nIn chapter 4, I will give an overview of Q-chem and how does \\emph{adcman} work.\nI will also discuss my implementation of EA Non-dyson ADC to Q-Chem and the results of benchmark calculations.\n\n\n", "meta": {"hexsha": "effc4f1a34b6ba57c437a423392119f27d1a3f36", "size": 5295, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/introduction.tex", "max_stars_repo_name": "SUSYUSTC/bachelor_thesis", "max_stars_repo_head_hexsha": "6ed40c7edf566436e9083f67172bba966732026c", "max_stars_repo_licenses": ["LPPL-1.3c"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/introduction.tex", "max_issues_repo_name": "SUSYUSTC/bachelor_thesis", "max_issues_repo_head_hexsha": "6ed40c7edf566436e9083f67172bba966732026c", "max_issues_repo_licenses": ["LPPL-1.3c"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/introduction.tex", "max_forks_repo_name": "SUSYUSTC/bachelor_thesis", "max_forks_repo_head_hexsha": "6ed40c7edf566436e9083f67172bba966732026c", "max_forks_repo_licenses": ["LPPL-1.3c"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 108.0612244898, "max_line_length": 364, "alphanum_fraction": 0.8094428706, "num_tokens": 1084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6791787121629465, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.31311278245884805}}
{"text": "\\chapter{Introduction}\nDigits recognition is a well-known and thoroughly explained subject in the image processing field. The outcome of those studies has significant impact for many aspects in people's lives. We used to provide credit curd number by hand some time ago, until the cell phones started to do it for us with the help of the camera. Automatic opening the gate basing on the plates numbers for entitled cars in the parking or motorway gates for those whose owners paid the toll upfront. These examples are just a pick of an iceberg of the potential digits recognition use cases. \n\nImage recognition and deep learning algorithms became globally available not only for scientists, but also for ordinary individuals, especially because of high level libraries like Tensorflow or PyTorch where the exact knowledge of how the particular algorithm works is often irrelevant for the sake of the API. Developer has to invoke proper function with the desired parameters, but the function itself which for example creates and trains neural network is in the form of the black box. Enormous amount of tutorials and resources also make the entry threshold relatively low for the person without prior knowledge in the topic.\n\\paragraph{MNIST}\nCrucial role in many if not the most image recognition algorithms and deep learning plays a dataset. It is necessary to gather significant amount of training data to properly teach for example the neural network and subsequently test in order to evaluate the quality of recognition. The process of gathering such a huge amount of data is more often the not tedious and takes a lot of time. This way MNIST database emerged for the sake of digits recognition. It contains 70000 handwritten digits, where 60000 and 10000 are consequently images for training and testing purposes \\cite{lecun-mnisthandwrittendigit-2010}. Digits were written by high school students and employees of the United States Census Bureau. \\figurename{} \\ref{fig:mnist_example} shows several images from the MNIST dataset.\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\scalebox{.7}{\\includegraphics{./pictures/mnist_example.png}}\n\t\\end{center}\n\t\\caption{MNIST dataset example}\n\n\t\\label{fig:mnist_example}\n\\end{figure}\nTo give an impression of the current level of digits recognition algorithms basing on MNIST dataset, several machine learning methods are juxtaposed on the \\tablename{}~\\ref{tab:mnist_comparison}.\n\\begin{table}[h!]\n\\centering\n\\begin{tabular}{    |l|c|c|c|  }\n\\hline\n  Type & Classifier & Error rate (\\%)  \\\\\n \\hline\n  Linear classifier & Pairwise linear classifier & \\num{7.6} \\cite{b:Lecun} \\\\\n \\hline\n  K-Nearest Neighbors & K-NN with non-linear deformation (P2DHMDM) & \\num{0.52} \\cite{b:Keysers} \\\\\n \\hline\n   Deep neural network (DNN) & 2-layer 784-800-10 & \\num{1.6} \\cite{b:Simard} \\\\\n \\hline\n   Deep neural network (DNN) & 6-layer 784-2500-2000-1500-1000-500-10 & \\num{0.35} \\cite{b:Cire_an_2010} \\\\\n \\hline\n\\end{tabular}\n \\caption{Several deep learning algorithms comparison in the digits recognition basing on MNIST database}\n\\label{tab:mnist_comparison}\n\\end{table}\nIt is very easy to take an advantage of this database, whilst working with for example Tensorflow, because the dataset can be downloaded directly using the library API. In this paper MNIST dataset will be exploited only for the training purposes.\n\n\\paragraph{How it works}\nTo goal is to recognise individual handwritten digits (outside the MNIST database) in real time by the camera. The images are captured in Python, resized to the 28x28 size and sent to the embedded system through UART, where deep feed forward neural network is implemented. Detected digit is displayed on the 7 segment display. System provides two ways of preprocessing the images. Adaptive Gaussian thresholding with the help of Open CV's API and Otsu thresholding implemented from the basis both in pure Python and C (in embedded system). Desired preprocessing might be chosen in the main script of communication application (main.py):\n\\begin{minted}[frame=single, linenos]{python}\nclass Preprocessing():\n    ADAPTIVE_THRESHOLD = 1\n    OTSU = 2\n    OTSU_ORIGINAL_IMAGE_NO_SERIAL = 3 # no data transfer to the uC -- just \n                                      # for the visualisation. OTSU\n                                      # on not resized image, high quality\n    OTSU_EMBEDDED = 4\n    \n###################################################\n# configuration part:\n###################################################\nSERIAL = False\nPREPROCESSING = Preprocessing.OTSU_ORIGINAL_IMAGE_NO_SERIAL\n\\end{minted}\nTwo variables are to be adapted by the user. If the SERIAL flag is true, data are being sent to the microcontroller, otherwise all process of recognition is done on the PC. User chooses the preprocessing algorithm with the PREPROCESSING variable.\n\nResults evaluation and the whole process of recognition is thoroughly discussed in the following parts of the paper. \n\n\\paragraph{Project structure}\nFigure \\ref{fig:project structure} presents project structure. It is divided into two main sub projects -- neural\\_network with Python and C feed forward implementation in two version: one and two hidden layers, and video, which is an communication project -- main.py contains aforementioned SERIAL and PREPROCESSING configuration, so it directly sends an image content to the microcontroller. 1\\_hidden and 2\\_hidden contains the same content, but with different amount of neural network hidden layers. \n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\scalebox{.7}{\\includegraphics{./pictures/structure.pdf}}\n\t\\end{center}\n\t\\caption{Project structure}\n\n\t\\label{fig:project structure}\n\\end{figure}\n\n\\begingroup\n\\renewcommand{\\cleardoublepage}{}\n\\renewcommand{\\clearpage}{}\n\\chapter{Preprocessing}\n\\endgroup\nTraining images are provided in the 28x28 array already preprocessed in the MNIST database, however images provided in the real time even though conceptually the same are significantly different. Two first pictures from the left of the \\figurename{} \\ref{fig:7_images} present digit 7. First one comes from the MNIST database, second one is a raw picture taken by the camera. The difference is in the background of the digit, which is not purely white, what introduces huge distortion in the process of recognition. Background of the original MNIST image in gray scale is zero, background of the raw image is bigger than zero, maybe not high, but still, it makes the neural network which was trained on the MNIST dataset incapable of detecting the digits correctly. Therefore thresholding is necessary.\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\scalebox{.09}{\\includegraphics[origin=c]{./pictures/7_images.png}}\n\t\\end{center}\n\t\\caption{Set of preprocessed images. From the left: MNIST example, taken by the camera (raw), adaptive thresholding, Otsu on the original image, Otsu on the previously resized.}\n\t\\label{fig:7_images}\n\\end{figure}\nImage in the centre shows the outcome of adaptive thresholding. This algorithm helps when the lighting conditions are not always the same, which is exactly the case here. The idea is to mute the background and express the digit. Algorithm calculates the threshold for every pixel based on a small region around it. More narrowly it is a gaussian-weighted sum of the pixel's neighbourhood. Pixel with higher value than the threshold is cast to 255 (black), with lower to 0 (white). Open CV provides an API to take an advantage of this thresholding:\n\\begin{minted}[frame=single, linenos]{python}\narr   = np.asarray(cv2.imread('7.jpg', cv2.IMREAD_GRAYSCALE))\narr2  = cv2.resize(arr, (28, 28))\ntrunc = cv2.adaptiveThreshold(arr2, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, \n    cv2.THRESH_BINARY_INV, 11, 9)\n\\end{minted}\n\n\\begingroup\n\\renewcommand{\\cleardoublepage}{}\n\\renewcommand{\\clearpage}{}\n\\section{Otsu}\n\\endgroup\nOtsu method is named after its author Nobuyuki Otsu. Calculated threshold separates the pixels into two classes foreground and background \\cite{b:otsu}. The method bases on minimising the between class variance or equally by maximising within class variance, but the first one is significantly faster. \\figurename{} \\ref{fig:otsu_example} shows the result of Otsu thresholding for the image captured by laptop build-in camera.\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\scalebox{.5}{\\includegraphics[origin=c]{./pictures/otsu_full_quality.png}}\n\t\\end{center}\n\t\\caption{Image captured by build-in laptop camera processed by Otsu}\n\t\\label{fig:otsu_example}\n\\end{figure}\n\\subsection{Algorithm}\nThe outcome of the method comes down to the division of the whole set of pixels into two classes, foreground and background. Otsu proposed to separate the pixel clusters by maximising the withing class variances, what means maximising the clusters separation. The variance is calculated on the distribution of the pixel intensities, so the histogram of the image, what leads to the probability distribution. This is given by the formula \\ref{eq:otsu_1}, where $\\sigma_W$ represents within class variance, $\\sigma_{b}^{2}$ and $\\sigma_{f}^{2}$ variances of the background and foreground classes, $W_b$ and $W_f$ are the probabilities that the classes are separated by the threshold T.\n\\begin{equation} \\label{eq:otsu_1}\n\\sigma_{W}^{2}(T) = W_b(T)\\sigma_{b}^{2}(T) + W_f(T)\\sigma_{f}^{2}(T)\n\\end{equation}\nBetween class variance is given by the relation \\ref{eq:otsu_2}\n\\begin{equation} \\label{eq:otsu_2}\n    \\sigma_{B}^{2}(T) = \\sigma^{2} - \\sigma_{W}^{2}(T)\n\\end{equation}\nWhat finally results (after the calculations) in the relation \\ref{eq:otsu_3}, where $\\mu_b$ and $\\mu_f$ are the weighted means of the particular cluster.\n\\begin{equation} \\label{eq:otsu_3}\n    \\sigma_{B}^{2}(T) = W_b(T)W_f(T)(\\mu_{b}(T) - \\mu_{f}(T))^2\n\\end{equation}\nThe following listing shows the algorithm implementation in C:\n\\begin{minted}[frame=single, linenos]{C}\nvoid otsu(int image[], int size) {\n    int histogram[BINS_NUMBER] = {0};\n    calculate_histogram(histogram, image, size);\n    \n    float sum = 0;\n    for(int i = 0; i < BINS_NUMBER; i++) sum += i*histogram[i];\n    \n    float sumB = 0, wB = 0, wF = 0, varMax = 0, \n    int threshold = 0;\n    for(int t = 0; t < size; t++) {\n        wB += histogram[t];\n        if(wB == 0) continue;\n        wF = size - wB;\n        if(wF == 0) break;\n        \n        sumB += (float)t*histogram[t];\n        float mB = sumB / wB;\n        float mF = (sum-sumB) / wF;\n        float varBetween = wB * wF * (mB-mF)*(mB-mF);\n        \n        if(varBetween > varMax) {\n            varMax = varBetween;\n            threshold = t;\n        }\n    }\n    printf(\"threshold = %d\\n\", threshold);\n    for(int i = 0; i < size; i++) image[i] = image[i] > threshold ? 0 : 255;\n}\n\\end{minted}\nWhere the histogram is calculated in the following way:\n\\begin{minted}[frame=single, linenos]{C}\nvoid calculate_histogram(int histogram[], int image[], int size) {\n\tfor(int i = 0; i < size; i++) {\n\t\thistogram[image[i]]++;\n\t}\n}\n\\end{minted}\nTwo last images from the picture \\ref{fig:7_images} present consecutively the result of original image Otsu thresholding and the same image, but previously resized to 28x28 pixels. Adaptive threshold for this image gives better results, however it is not always the case.\n\\begingroup\n\\renewcommand{\\cleardoublepage}{}\n\\renewcommand{\\clearpage}{}\n\\chapter{Neural network}\n\\endgroup\nDeep feed forward was chosen as a neural network. Feed forward pass was implemented in pure Python without high level libraries like NumPy or Tensorflow, then reimplemented in C in order to be placed in the microcontroller. However the process of training was outsourced to the Tensorflow in version 2. Weights and biases from the trained multilayer perceptron then are saved in the C header files. \n\n\\section{Feedforward neural network}\nFeedforward neural network is a multilayer perceptron with several hidden layers extensively used in machine learning along with deep convolutional neural networks and recurrent neural networks. The forward pass, so the process of thinking is relatively simple and performance effective. \\figurename{} \\ref{fig:feedforward} shows deep feedforward neural network with multiple inputs and outputs. In the feed forward pass all inputs are multiplied by weights in the connection with the first hidden node what results in the net input $z_1[0]=i[0]w_1[0][0]+i[1]w_1[1][0]+\\dots+i[k]w_1[k][0] + b_1[0]$. Subsequently the net input $z$ is applied to the activation function. The process is performed for every node in every hidden and output layer, where output from the particular node is an input of the next node. It is worth noting that the number of nodes in the hidden layers not necessarily has to be equal. Formal process of the feed forward pass for particular the node is written in \\ref{eq:feedforward}, where $f_k$ represents activation function for the layer $k$ which is either ReLU for hidden layers or sigmoid for the output one. Rectified linear unit (ReLU) has an advantage over sigmoid function used in the output layer, because it does not have vanishing gradient, which prevents neural network from efficient learning. In fact ReLU has the constant gradient. Sigmoid activation function is given by \\ref{eq:sigmoid}, whereas ReLU by \\ref{eq:ReLU}.\n\n\\begin{equation} \\label{eq:feedforward}\n\\begin{aligned}\n    z_k[0]&=n_{k-1}[0]w_k[0][0]+n_{k-1}[1]w_k[1][0]+\\dots+n_{k-1}[m]w_k[m][0] + b_k[0] \\\\\n    n_k[0]&=f_k(z_k[0]) \\\\\n\\end{aligned}\n\\end{equation}\n\n\\begin{equation} \\label{eq:sigmoid}\nf(z)=\\frac{1}{1-e^{-z}}\n\\end{equation}\n\n\\begin{equation} \\label{eq:ReLU}\nf(z)=max(0, z)\n\\end{equation}\n\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\scalebox{.6}{\\includegraphics{./pictures/feedforward.pdf}}\n\t\\end{center}\n\t\\caption{Feedforward neural network with multiple inputs and outputs. On the bottom of every layer, activation function was presented.}\n\n\t\\label{fig:feedforward}\n\\end{figure}\nPython implementation of the feedforward pass is presented on the following listing. This function is invoked for every hidden and output layer. Then the result of particular layer is passed to the consecutive one.\n\\begin{minted}[frame=single, linenos]{python}\ndef feedForward(self, inputs, weights_matrix, biases, activationFunction):\n    input_length = len(weights_matrix)\n    output_length = len(weights_matrix[0])\n    x = inputs\n    y = []\n    z = []  # without activation\n    \n    for o in range(0, output_length):  # calculate each output in order\n        y.append(0)\n        z.append(0)\n        for i in range(0, input_length): \n            y[o] += weights_matrix[i][o] * x[i]\n    \n        z[o] = y[o] + biases[o]\n    \n    for o in range(0, output_length):\n        y[o] = activationFunction(z[o])\n    \n    return y, z\n\\end{minted}\nAnd the process of thinking, so the way of feedForward invocation for the consecutive layers. In the example 1 hidden layer.\n\\begin{minted}[frame=single, linenos]{python}\ndef think(self, x):\n    (self.l1_output, self.l1_z) = self.feedForward(x, self.w1, self.b1, \n        self.ReLU)\n    (self.output, self.output_z) = self.feedForward(self.l1_output, self.w2, \n        self.b2, self.sigmoid)\n    return self.output\n\\end{minted}\nFollowing two listings show the implementation in C which are directly used by the microcontroller. Moving from Python to C is not trivial in this case, because two dimensional weights matrix is expressed in one dimension. Otherwise it would not be possible to pass different sizes of this matrix. Particular weight is obtained in the line 9. Activation function is passed as a function pointer. \n\\begin{minted}[frame=single, linenos]{C}\nvoid feedforward(const double x[], double z[], const double weights_matrix[], \n    int ROW, int COL, const double biases[], double y[],\n    double (*activationFunction)(double)) {\n\tint o, i;\n\tdouble cur_w;\n\n\tfor(o = 0; o < COL; o++) {\n\t\tfor(i = 0; i < ROW; i++) {\n\t\t\tcur_w = *(weights_matrix + i*COL + o);\n\t\t\ty[o] += cur_w * x[i];\n\t\t}\n\n\t\tz[o] = y[o] + biases[o];\n\t}\n\n\tfor(o = 0; o < COL; o++) {\n\t\ty[o] = (*activationFunction)(z[o]);\n\t}\n}\n\\end{minted}\nAnd the process of thinking:\n\\begin{minted}[frame=single, linenos]{C}\nvoid think(const double x[], double y[], double z[]) {\n\tdouble l1_output[128] = {0}, z1[128] = {0};\n\tfeedforward(x        , z1, w1[0], 784, 128, b1, l1_output, &ReLU);\n\tfeedforward(l1_output, z,  w2[0], 128, 10,  b2, y, &sigmoid);\n}\n\\end{minted}\n\\section{Training process}\nTraining was performed using Tensorflow library in the version 2.2 however implementation in pure Python is also provided (check Appendix \\ref{ch:back}). Time of the training varies between several seconds to roughly a few minutes, depending on the amount of epochs, nodes in the particular layer and the layers itself. Neural network is fully connected. As a lost function sparse categorical cross entropy was used, because the classes are mutually exclusive. It is given by the formula \\ref{eq:bce}, where $y_a$ and $y_d$ are the actual outputs of the neural network respectively and $L$ is the loss function.\n\\begin{equation} \\label{eq:bce}\nL(y_a,y_d)=-\\frac{1}{N}\\sum_{i=1}^{N}[y_{a_i}log(y_{d_i})+(1-y_{a_i})log(1-y_{d_i})]\n\\end{equation}\nThe training process starts with the model definition, goes through the training itself and finally finishes on the model saving as well as the weights and biases in the proper format. The following listing shows the training implementation for 1 hidden layer with 128 nodes, input with $28\\cdot28=784$ nodes and 10 output neurons.\n\\begin{minted}[frame=single, linenos]{python}\ndef createModel(self):\n    self.model = keras.Sequential([ # layers in sequence\n                 keras.layers.Flatten(input_shape=(28, 28)),\n                 keras.layers.Dense(128, activation=\"relu\"),  # fully connected\n                 keras.layers.Dense(10, activation=\"sigmoid\")\n            ])\n    self.model.compile(optimizer=\"adam\", \n    loss=\"sparse_categorical_crossentropy\", metrics=[\"accuracy\"])\n\ndef trainModel(self, epochs_num, save=True):\n    self.model.fit(self.train_data, self.train_labels, epochs=epochs_num)\n    test_loss, test_acc = self.model.evaluate(self.test_data, self.test_labels)\n\\end{minted}\nTraining takes an advantage of MNIST database as it was already aforementioned. When loaded, images are scaled to the range of 0-1.\n\\begin{minted}[frame=single, linenos]{python}\n(self.train_data, self.train_labels), (self.test_data, self.test_labels) = \n    keras.datasets.mnist.load_data()\nself.train_data = self.train_data / 255.0\nself.test_data = self.test_data / 255.0\n\\end{minted}\nWeights and biases are saved in the proper format, more narrowly they are exported to the .txt file along with the whole model and then transformed to the header files with the help of regexp and specially designed bash script.\n\n\n\\begingroup\n\\renewcommand{\\cleardoublepage}{}\n\\renewcommand{\\clearpage}{}\n\\chapter{PC side}\n\\endgroup\nIn this project camera is directly connected to the PC, but may be external one. The images are captured in real time, resized and depending on the need directly sent to the microcontroller or previously preprocessed. All of that is implemented in Python 3 with the help of OpenCV and serial package. The following listing shows the serial configuration.\n\\begin{minted}[frame=single, linenos]{python}\nser = serial.Serial(\n    port='/dev/ttyACM0',\n    baudrate=115200,\n    parity=serial.PARITY_NONE,\n    stopbits=serial.STOPBITS_ONE,\n    bytesize=serial.EIGHTBITS\n)\n\\end{minted}\nWhen the picture is ready to be sent it is flattened, that is changed to one dimensional array. Then every pixel is packed in 3 bytes format and sent. Synchronisation with the microcontroller is sygnalised by 2 special values: \"aaa\" stands for the beginning of the transfer and \"bbb\" for the end. Right after the beginning characters 3 bytes distinguishing the process of preprocessing are sent -- \"OOO\" in case of Otsu implemented on embedded system, \"AAA\" otherwise (outside microcontroller) for example adaptive thresholding. \n\\begin{minted}[frame=single, linenos]{python}\ndef send(ser, data, type):\n    ser.write(\"aaa\".encode())\n    if type == Preprocessing.OTSU_EMBEDDED:\n        ser.write(\"OOO\".encode())\n    else:\n        ser.write(\"AAA\".encode())\n\n    for i in data.flatten():\n        to_send = '{:3d}'.format(i)\n        ser.write(to_send.encode())\n    ser.write(\"bbb\".encode())\n\\end{minted}\nIt is worth to mention, that the bottleneck of the system is exactly the communication part. Even with the maximum baud rate accessible for UART, sending roughly $28\\cdot28\\cdot3 + 6$ bytes takes significant amount of time (around \\num{1.5} second) which stops systems fluency. Time of neural network computation comparing to this is negligible. \n\n\\begingroup\n\\renewcommand{\\cleardoublepage}{}\n\\renewcommand{\\clearpage}{}\n\\chapter{Microcontroller}\n\\endgroup\nNeural network and the whole process of recognition is implemented on the microcontroller STM32H743ZIT6U. Embedded system is placed on the Nucleo board, which is directly connected to the computer through USB. The board was chosen mostly because of high volume of memory. It has 2 Mbytes of Flash memory, where weights and biases resides in the constant arrays and 1 Mbyte SRAM where is the rest of the program, image array for instance. Moreover the core of this device is highly efficient ARM Cortex-M7 at 480MHz, which is desired from the neural network calculations point of view. Figure \\ref{fig:STM32H743ZIT6U} presents the Nucleo board with 7 segment display showing number 5.\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\scalebox{.18}{\\includegraphics[origin=c]{./pictures/uC.jpg}}\n\t\\end{center}\n\t\\caption{STM32H743ZIT6U with 7 segment display, which shows number 5 as a result of the image recognition}\n\t\\label{fig:STM32H743ZIT6U}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\scalebox{.4}{\\includegraphics[origin=c]{./pictures/cube_config.png}}\n\t\\end{center}\n\t\\caption{Peripherals STM32CubeMX configuration}\n\t\\label{fig:cube}\n\\end{figure}\nThe explanation of the whole process of peripherals configuration is omitted to focus mainly on the program logic. Nevertheless STM32CubeMX peripherals assignment is presented on the \\figurename{} \\ref{fig:cube}.\nMicrocontroller's main loop is responsible mainly for the neural network feed forward pass. Nevertheless apart from that there are a few operation worth to explain. First of all \"done\" flag indicates the end of the image transfer through UART. This flag is set in the interrupt callback, hence volatile. Subsequently Otsu preprocessing is done depending if it is requested via UART message (\"OOO\" bytes), this flag is also set in the interrupt callback handler. When it is done, image is rescaled and the process of recognition is performed. The result is displayed on the 7 segment display and finally the readiness of transfer is signalised by setting done flag to false. \n\\begin{minted}[frame=single, linenos]{C}\n#define IMAGE_SIZE 784\nuint8_t Received[3];\ndouble image[IMAGE_SIZE];\nvolatile bool done = false;\nvolatile bool is_otsu = false;\n////\nwhile (1) {\n    if(done) {\n        if(is_otsu) {\n            otsu(image, IMAGE_SIZE);\n        }\n        \n        for(int i = 0; i < IMAGE_SIZE; i++) {\n            image[i] = image[i] / 255.0;\n        }\n    \n        think(image, y, z);\n        display_digit(max_idx(y));\n        done = false;\n    }\n}\n\\end{minted}\nInterrupt handler for the UART receive event is presented on the following listing. The logic is similar to the process of sending the messages in the communication program, discussed previously. Start and finish flag, \"a\" (first letter of \"aaa\"), \"b\" consecutively. Type of the preprocessing, and the image content itself. Passing around 2000 bytes through UART is a bottleneck of the system as it was already stated. Interrupts introduce the notion of overlapping of the two images transmission -- during the detection of the first one, second image may be being transmitted. However the question is why not to exploit the DMA? Unfortunately there are several issues with DMA in this type of STM32 \\footnote{\\url{https://community.st.com/s/article/FAQ-DMA-is-not-working-on-STM32H7-devices}}, so the notion of using it was abandoned.\n\\begin{minted}[frame=single, linenos]{C}\nint counter = 0;\n\nvoid HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {\n\tif(Received[0] == 'a') {\n\t\tcounter = 0;\n\t} else\n\tif(Received[0] == 'b') {\n\t\tdone = true;\n\t} else\n\tif(Received[0] == 'O') {\n\t\tis_otsu = true;\n\t} else\n\tif(Received[0] == 'A') {\n\t\tis_otsu = false;\n\t} else {\n\t\tint value = atoi((const char*)Received);\n\t\timage[counter++] = (double)value;\n\t}\n\n\tHAL_UART_Receive_IT(&huart3, Received, 3);\n}\n\\end{minted}\n\n\\begingroup\n\\renewcommand{\\cleardoublepage}{}\n\\renewcommand{\\clearpage}{}\n\\chapter{Experiments and results}\n\\endgroup\nFeed forward with one hidden and 2 hidden layers was tested. More layers could not fit in the microcontroller's flash memory. First of all accuracy of the training process on the MNIST database is presented on the \\tablename{}~\\ref{tab:mnist_comparison2}.\n\\begin{table}[h!]\n\\centering\n\\begin{tabular}{    |l|c|c|c|c|  }\n\\hline\n  Type & Classifier & Accuracy (\\%)  & Epochs number & Loss \\\\\n \\hline\n   Feed forward & 1-layer 784-800-10 & \\num{0.9721} & 5 & \\num{0.0864} \\\\\n \\hline\n   Deep feed forward & 2-layer 784-512-128-10 & \\num{0.9793} & 5 & \\num{0.0727} \\\\\n \\hline\n\\end{tabular}\n \\caption{1 hidden and 2 hidden layers training results}\n\\label{tab:mnist_comparison2}\n\\end{table}\nAdmittedly the training quality rates, namely accuracy and loss (sparse categorical cross entropy) are similar. However one has to remember, that the training was performed on the MNIST database, but the real testing is in the real time, with hand written, subsequently preprocessed images. From the quality point of view, so how two neural networks behave in such conditions, they are capable of detecting the digits correctly. Deep feed forward neural network from the user experience behaves better than 1 hidden layer neural network, in the same time characterising by the similar performance. It is difficult to evaluate the efficiency quantitatively without huge set of images. Same applies to the preprocessing algorithms. Both of them are able to preprocessed the images satisfactory nonetheless. However as it might have been observed on the Figure \\ref{fig:7_images}, Otsu is highly vulnerable for lighting differences, hence from time to time some part of the digit may not be exposed correctly (last two images on the Figure \\ref{fig:7_images}). As an attachment to this report several test recordings may be found in the projects repository\\footnote{\\url{https://gitlab-stud.elka.pw.edu.pl/jwieczo1/numbers_detection}}.\n\n\\begingroup\n\\renewcommand{\\cleardoublepage}{}\n\\renewcommand{\\clearpage}{}\n\\chapter{Conclusions}\n\\endgroup\nIn this project deep feed forward neural network was implemented on the embedded system for the sake of visual recognition. Nowadays the biggest obstacle for deep learning algorithms is not the performance of the microcontroller, but the memory volume. Even with 2 Mbytes of the flash memory, it was possible to place there only 2 hidden layers. The bottleneck of the system is the image transfer to the STM32, therefore in the future improvement USB protocol is worth considering. Neural networks were trained basing on MNIST dataset instead of specially prepared images. Nevertheless preprocessing approximated the images captured in the real time, so it was not a problem for the detection. It is worth noting, that a digit should be placed in the centre of the camera to be correctly read.\n\nIn addition to the neural network two preprocessing algorithms were compared, where Otsu was implemented from the basis and placed onto microcontroller. Adaptive threshold is more resistant to the light differences, so it behaves slightly better. \n\n\\begin{appendices}\n\n\\begingroup\n\\renewcommand{\\cleardoublepage}{}\n\\renewcommand{\\clearpage}{}\n\\chapter{Back propagation} \\label{ch:back}\n\\endgroup\nThe following appendix shows an implementation of the one hidden layer feed forward back propagation algorithm. Without high level libraries, just pure Python. The difficulties in algorithm implementation grow with the number of layers, because back propagation bases on the gradient calculation, where particular gradient in the layer depends on many factors in the following layers. Thus, for the need of the project back propagation was outsourced to the Tensorflow.\n\\section{Output layer}\n\\begin{minted}[frame=single, linenos]{python}\ndef gradientsOutput(self, inputs, dedo, w, dActivationFunction, acti_arg1):\n    \"\"\"\n    @param inputs, The outputs of the last hidden layer\n    @param dedo,   Error gradient with respect to the output\n    @param w,      An array of weights between output and the \n                   hidden layer. Is constant\n    @param dActivationFunction in the case of this layer is \n                   dSigmoid \n    @param acti_arg1 Argument for dActivationFunction. In this case\n                   an output of the last layer\n    \"\"\"\n    outputs_length = len(w[0])\n    inputs_length = len(w)\n\n    dedw = [[0 for o in range(outputs_length)] for i in range(inputs_length)]\n    dedb = [0 for o in range(outputs_length)]\n    for o in range(0, outputs_length): \n        for i in range(0, inputs_length):\n            dedw[i][o] = dedo[o] * dActivationFunction(acti_arg1[o])*inputs[i]\n        \n        dedb[o] = dedo[o] * dActivationFunction(acti_arg1[o]) * 1\n    return dedw, dedb\n\\end{minted}\n\\section{Hidden layer}\n\\begin{minted}[frame=single, linenos]{python}\ndef gradients(self, inputs, dedo, w, w2, dActivationFunction, acti_arg1, \n    dActivationFunction_2, acti_arg1_2):\n    \"\"\"\n    @param inputs, The input of the nn\n    @param dedo,   Error gradient with respect to the output\n    @param w,      An array of weights between input and the \n                   hidden layer. Is constant\n    @param w2,     An array of weights between hidden layer\n                   and the output. Gradient of w depends on them.\n                   Is constant\n    @param dActivationFunction activation for the hidden layer\n    @param acti_arg1 Argument for dActivationFunction. If ReLU then\n           should be net inputs z.\n    @param dActivationFunction2 activation for the output layer\n    @param acti_arg2 Argument for dActivationFunction2. \n    \"\"\"\n    outputs_length = len(w[0]) # of w!\n    inputs_length = len(w)\n\n    dedw = [[0 for o in range(outputs_length)] for i in range(inputs_length)]\n    dedb = [0 for o in range(outputs_length)]\n    \n    dedohw = [[0 for o in range(outputs_length)] for i in range(inputs_length)]\n    dedohb = [0 for o in range(outputs_length)]\n    \n    outputs_length2 = len(w2[0])\n    inputs_length2 = len(w2)\n\n    for o2 in range(0, outputs_length2):\n        dEdActiv = dedo[o2] * dActivationFunction_2(acti_arg1_2[o2])\n        for o in range(0, outputs_length):\n            dedoh = dEdActiv * w2[o][o2]\n            for i in range(0, inputs_length):\n                dedohw[i][o] += dedoh\n            \n            dedohb[o] += dedoh\n\n    for o in range(0, outputs_length):\n        dActiv = dActivationFunction(acti_arg1[o])\n        for i in range(0, inputs_length):\n            dedw[i][o] = dedohw[i][o] * dActiv * inputs[i]\n        \n        dedb[o] = dedohb[o] * dActiv * 1\n\n    return dedw, dedb\n\\end{minted}\n\\section{Back propagation chain}\n\\begin{minted}[frame=single, linenos]{python}\ndef learn(self, x, y_desired):\n    y = self.think(x)\n    dedo = self.dSqe(y, y_desired)\n\n    (dedw2, dedb2) = self.gradientsOutput(self.l1_output, dedo, self.w2, \n        self.dSigmoid, self.output)\n    (dedw1, dedb1) = self.gradients(x, dedo, self.w1, self.w2, \n        self.dReLU, self.l1_z, self.dSigmoid, self.output)\n    \n    self.update(self.w2, self.b2, dedw2, dedb2)\n    self.update(self.w1, self.b1, dedw1, dedb1)\n\\end{minted}\n\n\\section{Update function}\n\\begin{minted}[frame=single, linenos]{python}\ndef update(self, w, b, dedw, dedb):\n    outputs_length = len(w[0])\n    inputs_length = len(w)\n    \n    for o in range(0, outputs_length):\n        for i in range(0, inputs_length):\n            w[i][o] += dedw[i][o] * self.lr\n        \n        b[o] += dedb[o] * self.lr\n\\end{minted}\n\n\\end{appendices}", "meta": {"hexsha": "727d12e79b349e86da20f04f846c7e005ae04b50", "size": 32147, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/doc/report.tex", "max_stars_repo_name": "jakubwieczorek/numbers_detection", "max_stars_repo_head_hexsha": "d090795c4f4fa7ca85d9b3547ebdd225b7e99ddf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/doc/report.tex", "max_issues_repo_name": "jakubwieczorek/numbers_detection", "max_issues_repo_head_hexsha": "d090795c4f4fa7ca85d9b3547ebdd225b7e99ddf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/doc/report.tex", "max_forks_repo_name": "jakubwieczorek/numbers_detection", "max_forks_repo_head_hexsha": "d090795c4f4fa7ca85d9b3547ebdd225b7e99ddf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 61.7024952015, "max_line_length": 1463, "alphanum_fraction": 0.7359318132, "num_tokens": 8206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3130867168774901}}
{"text": "\\section{Perils of disregard}\n\\label{sec:graph-importance}\n\nAs stated in Section \\ref{sec:intro}, transportation demand models are used to evaluate the impact of policies on a certain\ntransportation demand related outcome. As an example, consider the proposals from the following fictitious scenarios:\n\\begin{itemize}\n \\item Based on input from the public, a certain Department of Transportation (DOT) is considering implementing a new parking policy.\n This proposed policy would change prices and restrict availability to discourage individuals from parking in the central business district.\n The DOT and its constituents believe that this policy will encourage people to use more active transportation modes (e.g., walking, biking, etc.) and cause them to drive less.\n \\item The DOT is considering constructing a streetcar (trolley, tram) line in a low/mid-income area in its jurisdiction.\n Citing examples from other cities and countries, the DOT claims that the new streetcar line will create more transit oriented developments and increase economic activity in the areas surrounding the proposed project.\n \\end{itemize}\n\n%% TODO: Present an example or two of real life project proposals?\n\nThinking more closely about these proposals, it is clear that they assume a causal relationship between the proposed project/policy and the desired goals.\nThe DOT in question analyzed data, concluding that such a policy or project would cause the desired output and achieve the desired goal.\nIn the presented scenarios, the DOT claims that implementing the new parking policy will cause an increase the share of\nactive transportation modes in the central business district and that constructing the proposed streetcar line will\ncause more transit oriented developments and economic activity.\n\nPolicymakers base their analyses and conclusions on hypotheses or beliefs of how the world operates.\nIn other words, the data analysis is based on specific beliefs about the data generating process.\nHowever, policymakers often do not present these beliefs in a clear and concise manner.\nAs a result, these proposals maintain an obscure representation of how the policy or project will achieve their desired goals.\n\nDAGs allow one to clearly encode their assumptions about the data generating process and the problem at hand.\nResearchers and practitioners have made use of DAGs in fields ranging from medicine and epidemiology (\\citet{shrier_2008_reducing, sung_2012_reducing}) to economics (\\citet{white_2011_covariate}) and have found them to be practical.\n\nLikewise, DAGs could prove useful in addressing transportation policy questions.\n\\citet{brathwaite_2018_causal} have proposed a framework illustrating how practitioners and researchers can use DAGs to answer such transportation modelling questions in a causal context.\nHowever, \\citet{brathwaite_2018_causal} did not show an empirical application of their framework.\n\nIn this section, we will present an empirical example illustrating the importance of using DAGs in transportation demand modelling.\nSpecifically, we will illustrate how different assumptions about the data generating process result in different conclusions, even while assuming the same outcome model.\nBefore going any further, we note that this example is not meant to be all-encompassing.\nThat is, it does not reflect all complexities in a typical transportation choice modelling problem.\nIndeed, it is not our primary goal in this section to recover the causal effect of the proposed intervention.\nInstead, we are most interested in showing how different DAGs would result in different conclusions about the effect of the proposed intervention.\n\nLet us assume that a company wants to reduce its workforce carbon footprint by moving its employees closer to their campus.\nWe would like to forecast how such an intervention would change the share of employees driving to work.\nWe model this travel mode choice problem based on a dataset from \\citet{brathwaite_asymmetric}.\nThis dataset is based on the 2012 California Household Travel Survey, and it\ncontains approximately 4000 home-based school or work tours made by approximately 3850 individuals in the San Francisco Bay Area, California.\nThe dataset includes eight travel modes.\nFor our illustrative purposes, we focus on the following car-centric modes:\n\n\\begin{itemize}\n   \\item Drive Alone: The individual uses a private vehicle to make the trip\n   \\item Shared Ride 2: The individual shares an automobile ride with one more individual\n   \\item Shared Ride 3+: The individual shares an automobile ride with two or more individuals\n\\end{itemize}\n\nReaders interested in a more detailed description of the dataset can refer to \\citet{brathwaite_asymmetric}.\nFor the purposes of this exercise, we treat the multinomial logit model (MNL) defined in \\citet{brathwaite_asymmetric} as the true outcome generating model.\n\nIn this model, the systematic utility equations of the car-centric modes defined above are specified as follows:\n\\begin{equation}\n   \\begin{aligned}\n   \\label{eq:DA}\n   \\textrm{Utility} \\left(\\textrm{Drive Alone}\\right) &= \\beta_{\\textrm{travel\\_time}} \\times \\textrm{Travel\\_Time} + \\beta_{\\textrm{cost\\_per\\_distance\\_drive\\_alone}} \\times \\textrm{Cost\\_per\\_Distance}_{\\textrm{da}} \\\\\n   &\\quad + \\beta_{\\textrm{autos\\_per\\_licensed\\_driver}} \\times \\textrm{Autos\\_per\\_Licensed\\_Driver} \\\\\n   &\\quad + \\beta_{\\textrm{cross\\_bay\\_da}} \\times \\textrm{Cross\\_Bay}\n   \\end{aligned}\n\\end{equation}\n\n\\begin{equation}\n   \\begin{aligned}\n   \\label{eq:SR2}\n   \\textrm{Utility} \\left(\\textrm{Shared Ride 2}\\right) &= ASC_{\\textrm{shared\\_ride\\_2}} + \\beta_{\\textrm{time\\_drive}} \\times \\textrm{Travel\\_Time} \\\\\n   &\\quad + \\beta_{\\textrm{cost\\_per\\_distance\\_shared\\_ride\\_2}} \\times \\textrm{Cost\\_per\\_Distance}_{ \\textrm{sr2} } \\\\\n   &\\quad + \\beta_{\\textrm{autos\\_per\\_licensed\\_driver}}  \\times \\textrm{Autos\\_per\\_Licensed\\_Driver} \\\\\n   &\\quad + \\beta_{\\textrm{cross\\_bay\\_shared\\_ride}} \\times \\textrm{Cross\\_Bay} \\\\\n   &\\quad + \\beta_{\\textrm{hh\\_size}} \\times \\textrm{Household\\_Size} \\\\\n   &\\quad + \\beta_{\\textrm{n\\_kids\\_hh}} \\times \\textrm{Number\\_of\\_kids}\n   \\end{aligned}\n\\end{equation}\n\n\\begin{equation}\n   \\begin{aligned}\n   \\label{eq:SR3+}\n   \\textrm{Utility} \\left(\\textrm{Shared Ride 3+}\\right) &= ASC_{\\textrm{sr3+}} + \\beta_{\\textrm{time\\_drive}} \\times \\textrm{Travel\\_Time} \\\\\n   &\\quad + \\beta_{\\textrm{cost\\_per\\_distance\\_sr3+}} \\times \\textrm{Cost\\_per\\_Distance}_{\\textrm{sr3+}} \\\\\n   &\\quad + \\beta_{\\textrm{autos\\_per\\_licensed\\_driver}}  \\times \\textrm{Autos\\_per\\_Licensed\\_Driver} \\\\\n   &\\quad + \\beta_{\\textrm{cross\\_bay\\_shared\\_ride}} \\times \\textrm{Cross\\_Bay} \\\\\n   &\\quad + \\beta_{\\textrm{hh\\_size}} \\times \\textrm{Household\\_Size} \\\\\n   &\\quad + \\beta_{\\textrm{n\\_kids\\_hh}} \\times \\textrm{Number\\_of\\_kids}\n   \\end{aligned}\n\\end{equation}\n\nNote that, since we consider this model to be the true outcome model, there are no latent variables we need to account for.\nBelow is a description of the key variables included in the model:\n\n\\begin{itemize}\n  \\item Total Travel Distance: the total travel distance for individual i and mode j, for all available modes for individual i during trip t of tour l.\n  \\item Total Travel Cost: the travel cost in dollars for individual i and mode j, for all available modes for individual i during trip t of tour l.\n  \\item Total travel time: the travel time in minutes for individual i and mode j, for all available modes for individual i during trip t tour l.\n  \\item Number of Autos: the number of automobiles owned by individual i's household.\n  \\item Number of Licensed Drivers: is the number of licensed drives in individual i's household.\n  \\item Number of Kids: the number of kids in individual i's household.\n  \\item Cross-bay trip: a binary variable indicating whether the trip t in tour l for individual i is a cross-bay trip.\n\\end{itemize}\n\nFigure \\ref{fig:IND_GRAPH} illustrates the DAG where all explanatory variables in each utility equation are marginally independent.\nThis DAG is equivalent to what an analyst assumes when they only update the variables directly impacted by a given policy, without considering the dependencies between the explanatory variables.\nTo illustrate the problem with this approach, consider the case where the ``true'' data generating process that reflects the dependencies between the covariates is as shown in Figures \\ref{fig:DA_causal_2} through \\ref{fig:SR3_causal_2}.\nUnder this generative model, intervening on one variable would also result in changes to other variables that are dependent on it.\nThe goal of our simulation exercise is to show that ignoring the true generative model of the data (Figures \\ref{fig:DA_causal_2} through \\ref{fig:SR3_causal_2}) can result in arbitrarily biased treatment effects, even if the analyst knows the true outcome model (Equations \\ref{eq:DA} through \\ref{eq:SR3+}).\n\n\\begin{figure}\n\\centering\n\\begin{subfigure}[b]{0.75\\textwidth}\n   \\includegraphics{Independent_graph}\n   \\caption{Causal Graph with Independent Covariates}\n   \\label{fig:IND_GRAPH}\n\\end{subfigure}\n\n\\begin{subfigure}[b]{0.75\\textwidth}\n   \\includegraphics{DA_interacting_graph}\n   \\caption{Causal Graph for the Drive Alone Utility Function}\n   \\label{fig:DA_causal_2}\n\\end{subfigure}\n\n\\begin{subfigure}[b]{0.75\\textwidth}\n   \\includegraphics{SR2_interacting_graph}\n   \\caption{Causal Graph for the Shared Ride 2 Utility Function}\n   \\label{fig:SR2_causal_2}\n\\end{subfigure}\n\n\\begin{subfigure}[b]{0.75\\textwidth}\n   \\includegraphics{SR3_interacting_graph}\n   \\caption{Causal Graph for the Shared Ride 3+ Utility Function}\n   \\label{fig:SR3_causal_2}\n\\end{subfigure}\n\n\\end{figure}\n\nTo achieve this goal, we follow these simulation steps, using the same outcome model defined in Equations \\ref{eq:DA} to \\ref{eq:SR3+}:\n\\begin{itemize}\n   \\item Simulate data from the DAGs shown in Figure \\ref{fig:DA_causal_2} through Figure \\ref{fig:SR3_causal_2}.\n   \\item In one scenario, only modify the travel distance variable in all graphs to emulate a company's decision to move its employees closer to campus. This is similar to assuming the DAG in Figure \\ref{fig:IND_GRAPH} as the true data generating model.\n   \\item In the other scenario, modify the travel distance variable in all utility graphs, as well as all the variables that are dependent on it based on the DAGs in Figure \\ref{fig:DA_causal_2} through Figure \\ref{fig:SR3_causal_2}. This case is meant to reflect the ``correct'' approach needed to quantify the effects of the company's policy.\n   \\item Predict the probabilities of choosing car-centric modes before and after modifying the data to emulate the proposed intervention under each of the two scenarios above, and compute the differences in mode choice probabilities.\n\\end{itemize}\n\nReaders interested in exploring the details of our simulation exercise can refer to our GitHub repository \\citep{brathwaite_etal_2020}.\n\n\nWe then plot histograms of the computed differences between the average probability of an individual\nin our sample choosing a car centric mode before and after implementing a policy or intervention\naimed at reducing travel distance.\nRecall that these differences are plotted under the assumptions that the outcome model is the same in both scenarios, and the only difference between the two scenarios is the set of variables assumed to be affected by the proposed intervention.\nThis difference in the set of variables affected by the proposed intervention is a result of the two different causal graphs representing each scenario (Figures \\ref{fig:IND_GRAPH} - \\ref{fig:SR3_causal_2}).\nFigure \\ref{fig:histogram_probability} highlights the resulting bias between the estimated probability of an average individual choosing a car centric mode.\nThe histograms show that the distribution of inferred treatment effects based on the ``true'' causal graph includes both positive and negative treatment effects.\nWith low but non-trivial probability, using the wrong causal graph in one's analyses could result in not only wrong magnitudes of the treatment effect of interest but also the wrong sign.\nThis plotted discrepancy shows the importance of using causal graphs in the estimation of treatment effects.\nOf course, the importance of a correct causal graph does not and should not take away from the importance of correctly specified outcome choice models.\n\n\\begin{figure}[h!]\n   \\centering\n   \\includegraphics[width=0.95\\textwidth]{histogram_selection_on_obs}\n   \\caption{Histograms of the probability of choosing Car Centric Modes under Different Data Generating processes.}\n   \\label{fig:histogram_probability}\n\\end{figure}\n\nWe have shown in this simulation exercise how causal graphs can be helpful in avoiding biased causal effect inferences.\nSpecifically, two situations highlight this fact; having mediating or confounding variables relative to the variable being intervened on in our outcome model.\nIn the case of mediating variables relative to the node the treatment intervenes on, we need to be careful about constructing our treatment effect estimator.\nIn particular, we need to ensure that we appropriately use total effect estimators instead of natural direct effect estimators.\nEnacting a certain treatment shows its effect through the mediating variable.\nTherefore, when ``changing'' the value of the intervention node, we need to make sure the values and distributions of any downstream nodes reflect this change.\nFor more information on mediating mechanisms, please refer to work by \\citet{pearl_2012_mediation} and references therein.\nIn the case of confounding variables, we need to consider the treatment assignment mechanism when building choice models.\nAs \\citep{hahn_2020_bayesian} show, one way to account for the treatment assignment mechanism is to estimate the propensity score in our sample and adjust for that in our outcome model.\n\nIn contrast to the example shown in this section, the data generating process might not be easily distinguishable in the majority of situations, mainly due to the complexity of the real world.\nTherefore, constructing a causal graph that represents the data generating process as closely as possible is not an easy task.\nTo prepare readers to create causal graphs, the next section will provide a brief overview of them and their history in choice modelling.\nThen, Section \\ref{sec:graph-construction} explores this topic and includes detailed guidance on how to build causal graphs representing the researchers' beliefs about the data generating process.\nSection \\ref{sec:graph-testing} follows up with guidance on how to test one's causal graphs against one's data.\n", "meta": {"hexsha": "bc44381639bd5b153b53f073825b04a6d4a39545", "size": 14673, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "article/sections/_2_graph_importance.tex", "max_stars_repo_name": "hassanobeid1994/tr_b_causal_2020", "max_stars_repo_head_hexsha": "1ffaeb7dcefccf5e1f24c459e9a2f140b2a052a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "article/sections/_2_graph_importance.tex", "max_issues_repo_name": "hassanobeid1994/tr_b_causal_2020", "max_issues_repo_head_hexsha": "1ffaeb7dcefccf5e1f24c459e9a2f140b2a052a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 89, "max_issues_repo_issues_event_min_datetime": "2020-02-10T02:52:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-23T03:50:27.000Z", "max_forks_repo_path": "article/sections/_2_graph_importance.tex", "max_forks_repo_name": "hassan-obeid/tr_b_causal_2020", "max_forks_repo_head_hexsha": "1ffaeb7dcefccf5e1f24c459e9a2f140b2a052a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 80.1803278689, "max_line_length": 344, "alphanum_fraction": 0.7941116336, "num_tokens": 3429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.31308670820176576}}
{"text": " \n\\section{Conditions and sub-boxes}\n  \nIn this section we expand on some topics mentioned briefly in Section 1.  As such, it would be useful to look again at\nFIXME(Definitions 1.8, 1.12, and 1.22, and Remark 1.9),\nwhere ${\\cal P}$, ${\\cal T}$ and their partners (under exponentiation)\n${\\cal W}$, ${\\cal S}$ are introduced, and at\nFIXME(Definition 1.18)\n where the notion of a killerword is introduced (the\ndefinition is phrased in terms of ${\\cal P}$, but the definition also makes sense for ${\\cal W}$).  Note that working with\nthe region\n${\\cal P}$ is intuitively appealing, but working with the box ${\\cal W}$ is vastly superior computationally (see Remark\n1.21).\n\nFIXME(Theorem 0.2),\nhence\nFIXME(Theorem 0.1), follows from\nFIXME(Propositions 1.28, 2.8, 3.1, and 3.2).\n  The computational aspects of the proofs of each of these propositions are similar.  We will focus on\nFIXME(Proposition 1.28)\n here.\nIts proof   amounts to decomposing \n ${\\cal W}$ into a collection of sub-boxes of two types:\n\\begin{itemize}\n\\item[1)]   The 11 sub-boxes which comprise the \nexceptional boxes $X_0, X_1, \\ldots, X_6.$ \n\n\\item[2)]   Sub-boxes each of which has an associated {\\it condition} that will describe how to kill that entire sub-box,\nperhaps with the help of a killerword.  To {\\it kill} a sub-box means to show that \n${\\cal S} - \\bigcup_{n = 0,\\dots, 6} X_n$ has no point in the sub-box. \n\\end{itemize}\n\\noindent The set-up for efficiently describing these sub-boxes will be given in Construction FIXME(5.3). \n \n\nWe now list the conditions used to kill the nonexceptional sub-boxes.  There are two types of conditions: the trivial and\nthe interesting.  The trivial conditions kill sub-boxes in ${\\cal W}$ since the sub-boxes in question miss \n$\\exp({\\cal P}).$  The interesting conditions are where the real work is done, and they require a killerword in $f, w,\nf^{-1}, w^{-1}$ to work their magic (see\nFIXME(Remark 1.17)\n).\n\nTo be consistent with the computer program {\\it verify} we use the following notation: $L^{\\prime} = z_0 + i z_3$,\n$D^{\\prime} = z_1 + i z_4,$ and $R^{\\prime} = z_2 + i z_5.$  Here $(L^{\\prime}, D^{\\prime}, R^{\\prime}) \\in {\\cal W}$ and\n$L^{\\prime} = \\exp(L) = \\exp(l+it),\\   D^{\\prime} = \\exp(D) = \\exp(d+ib),\\  \nR^{\\prime} = \\exp(R) = \\exp(r+ia).$\n\\vglue10pt\n {{\\bf The trivial conditions  \nFIXME(5.1)\n}}.\n\\vglue6pt\n{\\it Condition} `s' ({\\it short}):  Tests that all points in the sub-box have $|z_0 + i z_3| < 1.10274.$  This ensures that  \n$$\\exp(l) = |\\exp(L)| = |L^{\\prime}| = |z_0 + i z_3| < 1.10274 < \\exp(0.0978),$$  and\nFIXME(Definition 1.12)\n tells us that we are\noutside of $\\exp({\\cal P}).$\n\\vglue6pt\n{\\it Condition} `l' ({\\it long}): Tests that all points in the sub-box have $|z_0 + i z_3| > 3.63201.$  This ensures that  \n$$\\exp(l) = |\\exp(L)| = |L^{\\prime}| = |z_0 + i z_3| > 3.63201 > \\exp(1.289785)$$ and we are outside of $\\exp({\\cal P}).$  \n\\vglue6pt\n{\\it Condition} `n' ({\\it near}): Tests that all points in the sub-box have $|z_1 + i z_4| < 1.$  This ensures that \n$$\\exp(d) = |\\exp(D)| = |D^{\\prime}| = |z_1 + i z_4| <1= \\exp(0)$$ and we are outside of $\\exp({\\cal P}).$\n\\vglue6pt\n{\\it Condition} `f' ({\\it far}): Tests that all points in the sub-box have $|z_1 + i z_4| > 3.$  This ensures that \n$$\\exp(d) = |\\exp(D)| = |D^{\\prime}| = |z_1 + i z_4|  > 3= \\exp(\\ln 3)$$ and we are outside of $\\exp({\\cal P}).$  \n\\eject\n\n{\\it Condition} `w' ({\\it whirle  big}): Tests that all points in the sub-box have $|z_2 + i z_5|^2 > |z_0 + i z_3| $  This\nensures that $$\\exp(r) = |\\exp(R)| = |R^{\\prime}| = |z_2 + i z_5|  > \\sqrt{|z_0 + i z_3|} =  \\sqrt {\\exp(l)} = \\exp(l/2)$$ and\nwe are outside of $\\exp({\\cal P}).$  \n\\vglue6pt\n{\\it Condition} `W' ({\\it whirle  small}): Tests that all points in the sub-box have $|z_2 + i z_5| < 1. $  This ensures that\n$$\\exp(r) = |\\exp(R)| = |R^{\\prime}| = |z_2 + i z_5|  < 1 = \\exp(0)$$ and we are outside of $\\exp({\\cal P}).$\n\n\\vglue12pt\n {{\\bf The interesting conditions \nFIXME(5.2)\n}}.\n\\vglue6pt\n{\\it Condition}  `L': This condition comes equipped with a killerword $k$ in $f, w, f^{-1}, w^{-1},$ and tests that all\npoints in the sub-box have $|\\exp({\\rm length}(k))| <  |L^{\\prime}| = |\\exp(L)|,$ where ${\\rm length}(k)$ means the length\nof the isometry determined by $k.$   This, of course, contradicts the fact that $L$ is the length of the shortest geodesic.\n\nIt is easy to carry out the test $|\\exp({\\rm length}(k))| <  |L^{\\prime}|$ because\nLemma FIXME(1.25a)) can be used.\nNote that in {\\it verify} the function which computes $\\exp({\\rm length})$ is called {\\it length}.  \n\nOf course, Condition `L' also checks that the isometry corresponding to the word $k$ is not the identity.\n\\vglue6pt\n{\\it Condition}   `O':   This condition comes equipped with a killerword \n$k$ in $f, w, f^{-1}, w^{-1},$ and tests that all points in the sub-box have \n$$|\\exp({\\rm distance}(k(B_{(0,\\infty)}),\nB_{(0,\\infty)}))| <  |D^{\\prime}| = |\\exp(D)|.$$    (Recall that \n$B_{(0;\\infty)}$ denotes the oriented geodesic $\\{(0,0,z): 0< z < \\infty \\}$,\nwith negative endpoint $(0,0,0).$)\nThis, of course, contradicts the ``nearest\" condition.\n\nIt is easy to carry out the test $|\\exp({\\rm distance}(k(B_{(0,\\infty)}), B_{(0,\\infty)}))| <  |D^{\\prime}|$ because\nLemma FIXME(1.25b)) can be used. Note that in {\\it verify} the function which computes the quantity\n$\\exp({\\rm distance}(k(B_{(0,\\infty)}), B_{(0,\\infty)}))$ is called {\\it orthodist}.  \n\nAlso, Condition `O' checks that the isometry corresponding to the word $k$ does not take the axis of $f$ to itself.\n\\vglue6pt\n{\\it Condition}   `2':  This is just the `L' condition without the ``not-the-identity\" check, but with the additional\nproviso that the killerword $k$ is of the form $f^p w^q.$ This ensures that $k$ is not the identity, because for $k$ to be\nthe identity $f$ and $w$ would have to have the same axis, which contradicts the fact that $d$ can be taken to be\ngreater than or equal to $l/4.$\n\\eject\n\n{\\it Condition}  `conjugate':  There is one other condition that is used to eliminate points in ${\\cal W}.$  Following\nFIXME(Definition 1.12)\n (and \nFIXME(Lemma 1.13)\n) we eliminate all boxes with $0 < t \\le \\pi.$  Of course, after exponentiating $L = l+it,$\nthis corresponds to eliminating all boxes with $z_3 > 0.$ Specifically, we toss all sub-boxes of ${\\cal W}$ whose fourth\nentry is a 1. This condition does not appear in {\\it verify} because it is applied ``outside\" of these\nprograms, as described in Construction \nFIXME(5.3).\n\\vglue6pt\n {\\it Construction} FIXME(5.3): \nWe now give the method for describing the roughly 930 million sub-boxes that the initial box ${\\cal W}$ is subdivided into.\n\nAll sub-boxes are obtained by subdivision of a previous sub-box along a real\nhyper-plane midway between parallel faces of the sub-box before\nsubdivision.  Of course, these midway planes are of the form $x_i = $ a\nconstant.   We use $0$'s and $1$'s to describe which half of a subdivided\nsub-box to take ($0$ corresponds to lesser $x_i$ values).  For example, 0\ndescribes \nthe sub-box $${\\cal W} \\cap \\{(x_0,x_1,x_2,x_3,x_4,x_5): x_0 \\le 0 \\},$$ \n$010$ describes the sub-box \n$$W \\cap \\{(x_0,x_1,x_2,x_3, x_4,x_5) : x_0 \\le 0,\\ x_1 \\ge 0,\\ x_2 \\le 0 \\},$$\nand so on.\n\nIn this way, we get a one-to-one correspondence\nbetween strings and sub-boxes.\nIf $s$ is a string of $0$'s and $1$'s, then let $Z(s)$ denote\nthe sub-box corresponding to $s$.\nThe range of values for the $i^{\\rm th}$ coordinate in the sub-box $Z(s)$ is related\nto the binary fraction $0.s_{i}s_{i+6}\\ldots s_{i+6k}$.\nThe two sub-boxes gotten from\nsubdividing $Z(s)$ are $Z(s0)$ and $Z(s1)$.\n\nThe directions of subdivision cycle among the various coordinate axes:\nthe $n^{\\rm th}$ subdivision is across the $(n \\bmod 6)^{\\rm th}$ axis.\nThe dimensions of the top-level box ${\\cal W}$ were chosen so that subdivision\nis always done across the longest dimension of the box,\nand so that all of the sub-boxes are similar.  \nThe dimensions of ${\\cal W}$ have the beneficial effect of making the sub-boxes as ``round\" as possible, hence making the Taylor approximation calculations efficient and fast.\nThis explains the factor of $2^{(5-i)/6}$ in Definition \nFIXME(1.22)\n.\n\nTo kill a sub-box $Z(s)$, the checker program has two (recursive) options:\nuse a condition and, if necessary, an associated killerword  to kill $Z(s)$ directly, or first kill $Z(s0)$ and then kill $Z(s1)$.\nAt this point, it may seem as if the second option is not necessary,\nbecause surely a condition which kills two halves also kills the whole.\nThe answer to this has been hinted at in \nFIXME(Remarks 1.17 and 1.35)\n where\nit is noted that our evaluation of a function arising\nfrom a killerword  is via first-order Taylor\napproximation, complete with remainder/error term.\n(Note that the remainder/error term incorporates bounds on\nboth the theoretical error arising from using a first-order Taylor\napproximation to approximate a function, and the accumulated\nround-off error; see \nFIXME(Sections 6, 7,  and 8)\n.)\nEven if a killerword could theoretically kill off a sub-box,\nit is quite possible that our\nfirst-order Taylor approximation approach would not be\nable to prove this \nbecause its remainder/error term is too large.\nHowever, if we subdivide the sub-box, then the first-order\nTaylor approximations on the two halves should be more accurate.  \nThus,\nwe want to have the recursive subdivision option at our\ndisposal.\nNote that because the checker program does in fact do such \nrecursive subdivisions, the actual number of sub-boxes in the\nultimate subdivision is larger (perhaps substantially larger)\nthan the 930 million sub-boxes of the initial data tree.\n\nIt is also possible that the checker program will employ\nneither of the two options described in the previous\nparagraph, and will instead employ  \na third option: do not kill $Z(s)$, and instead\nmark $s$ as omitted.\nAny omitted sub-boxes are checked with another instance\nof the checker program,\nunless the sub-box is one of the 11 exceptional\nsub-boxes (which produce the seven exceptional boxes after joining abutters).\nNote that according to the definition of ``kill\" given at the beginning of this section, the exceptional boxes are\nautomatically killed.   \n\nThus, a typical output from {\\it verify} would be \n\\begin{eqnarray*}\n&&{\\rm verified} 000000111101111111 \\\\\n&&\\qquad\\qquad\\quad- \n\\{ 0000001111011111110 \\ \\ 000000111101111111110 \\} .\n\\end{eqnarray*}\nwhich means that the sub-box $Z(000000111101111111)$ was killed except for its sub-boxes\n$Z(0000001111011111110)$  and $Z(000000111101111111110).$  The output \n\\begin{eqnarray*}\n&&{\\rm verified} 0000001111011111110 - \\{\\ \\}.\\\\\n\\noalign{\\noindent and}\n&&{\\rm verified} 000000111101111111110 - \\{\\ \\}.\n\\end{eqnarray*} shows that these sub-boxes were subsequently killed as well, and thus the entire sub-box\n$Z(000000111101111111)$ has been killed. \n\n\nInstead of immediately working on killing the top-level box, we subdivide in the six co-ordinate directions to get the 64 sub-boxes $$Z(000000),Z(000001),Z(000010),Z(000011),\\ldots, Z(111111).$$ \n\\noindent We then throw out\nthe ones with fourth co-ordinate equal to 1 (see condition `conjugate'), leaving  the 32 sub-boxes\n$$Z(000000),Z(000001),Z(000010),Z(000011),\\ldots, Z(111011).$$  \\noindent We then use {\\it verify} to kill these.\n\\eject\n\nThe choices in {\\it verify} are made for it by a sequence\nof integers given as input.  The sequence of integers containing the directions for killing $Z(000000)$ is contained in the file data/000000 (actually, data/000000.d).\nIn such a sequence, \n$0$ tells {\\it verify} to subdivide the present box (by $x_i = c$),  to position itself on the ``left-hand\" box ($x_i \\le c$)\ncreated by that subdivision, and to read in the next integer in the sequence. A  positive integer $n$ tells {\\it verify} to\nkill directly the sub-box it is positioned at, using the condition (and killerword, if necessary) on line $n$ in the\n``conditionlist\" file,  and then to position itself at the ``next\" natural sub-box.  Now,\n$-1$ tells {\\it verify} to omit the sub-box, and mark it as skipped\n(the sequence of integers used in killing the skipped box $Z(s)$ is contained in a file data/s).\n\n\nThe checker program {\\it verify}, its inputs, and the list of conditions\nare available from the {\\it Annals of Mathematics} web site.\n\\vglue7pt\nFIXME({\\it Example} 5.4.)\nTo illustrate the checking process in action, this is a (non-representative)\nexample, which shows how the sub-box $Z(s)$ (minus a hole) is killed,\nwhere\n\\begin{eqnarray*}\n&&s=0010001100011101110011110001011111111011111\\\\\n&&\\hskip2in 00111001111000001111011110111. \n\\end{eqnarray*}\n\nThe input associated with this sub-box is\n$$(0, 0, 0, 1929, 12304, 0, 0, 7, 0, 1965, 0, 1929, 1929, 1996, -1),$$\nwhich causes the program to kill $Z(s)$ in the following fashion:\n{\\noindent\\obeylines\n\\def\\>{\\hskip 0.05in}\n kill $Z(s)$:\n\\>kill $Z(s0)$:\n\\>\\>kill $Z(s00)$:\n\\>\\>\\>kill $Z(s000)$ with condition 1929 = ``L(FwFWFWfWFWFwFwfww)''\n\\>\\>\\>kill $Z(s001)$ with condition 12304 = ``L(FwfWFFWFwFwfwfWfwfw)''\n\\>\\>kill $Z(s01)$:\n\\>\\>\\>kill $Z(s010)$:\n\\>\\>\\>\\>kill $Z(s0100)$ with condition 7 = ``L(w)''\n\\>\\>\\>\\>kill $Z(s0101)$:\n\\>\\>\\>\\>\\>kill $Z(s01010)$ with condition 1965 = ``L(fwFwFWFFWFwFwfwww)''\n\\>\\>\\>\\>\\>kill $Z(s01011)$:\n\\>\\>\\>\\>\\>\\>kill $Z(s010110)$ with condition 1929\n\\>\\>\\>\\>\\>\\>kill $Z(s010111)$ with condition 1929\n\\>\\>\\>kill $Z(s011)$ with condition 1996 = ``L(FwFwFWFWfWFWFwFwfww)''\n\\>omit $Z(s1)$\n\\noindent as shown in \nFIXME(Figure 5.1).\n}\n\n \n \\centerline{\\BoxedEPSF{fig5.1.eps scaled 1250}}\n\n \\begin{quote}{\nFIXME(Figure 5.1)\n.  Six levels of subdivision, in two projections,\n with all the trimmings.}\n \\end{quote}\n\n$Z(s1)$ is ignored, so the checker would indicate this omission\nin its report.  In fact, $Z(s1)$ is one of the 11 exceptional sub-boxes (seven boxes after joining abutters), specifically\n$X_{5a},$ hence killed automatically.\n\nThe use of condition ``L(w)'' so deep in the tree is unusual.\nIn this case, it is because the manifold in the exceptional sub-box\nhas ${\\rm length}(f) = {\\rm length}(w)$, so that the program will frequently\ncome to places where it can bound ${\\rm length}(f) > {\\rm length}(w)$ nearby.\n\nThe sequence $\\ 0, 1929, 1929\\ $ in the \ninput for $Z(s)$ tells the checker to\nsubdivide $Z(s01011)$, and then use the condition 1929\non both halves to kill   them separately, \nthereby killing $Z(s01011)$.\nAs mentioned above,\nthe reason for carrying out this  subdivision \nis that the remainder/error bound in the calculation\n for $Z(s01011)$ using condition 1929 was not good enough\nto prove that the sub-box is killed directly. \n \n \n\n\nIn the input for $Z(s)$ we could have\nreplaced \n $\\ 0, 1929, 1929\\ $ with 1929 alone\nand then the checker\nprogram itself would be smart enough to carry out\nthe subdivision after 1929 failed to kill the sub-box\n$Z(s01011).$\nThis recursive subdivision tool is quite useful when dealing with the \nremainder/error term---if a killerword barely misses killing off a sub-box, then recursively subdivide the sub-box and\nuse the same killerword on the pieces until it succeeds.   We note that the theoretical error arising from using a\nfirst-order Taylor approximation is likely to be significantly improved by subdivision, whereas the\nround-off error is relatively unaffected because the killerword\nused is unchanged (hence the number of mathematical operations\nperformed is unchanged).\n\nThe binary numbers used by the computer require too much space to print.\nIn the example calculation which follows, we instead use decimal \nrepresentations (although we print fewer digits than could\nbe gotten from the 53 binary digits used for the actual calculations).\n\nThe sub-box $Z(s01011)$ is the region where \n$$\\left(\\begin{array}{c} \n-1.381589027741\\ldots  \\le  {\\rm Re}(L')  \\le  -1.379848991182\\ldots\\cr\n-1.378124546093\\ldots  \\le  {\\rm Re}(D')  \\le  -1.376574349753\\ldots\\cr\n0.999893182771\\ldots  \\le {\\rm Re}(R')  \\le  1.001274250703\\ldots\\cr\n-2.535837191243\\ldots  \\le  {\\rm Im}(L')  \\le  -2.534606799593\\ldots\\cr\n\\phantom{-}2.535404997792\\ldots  \\le  {\\rm Im}(D')  \\le  -2.534308843448\\ldots\\cr\n-0.001953125000\\ldots  \\le  {\\rm Im}(R')  \\le  0.000000000000\\ldots\\phantom{-}\\cr\n\\end{array}\\right)$$\n\n\nAt this point, we would like to compute $$f,\\ w,\\ g = f^{-1}wf^{-1}w^{-1}f^{-1}w^{-1}fw^{-1}f^{-1}w^{-1}f^{-1}wf^{-1}wfww, \\ {\\rm length}(g),$$ \n\\noindent \nand so on.  \nHowever, these items take on values over an entire sub-box and thus are computed via AffApproxes (first-order Taylor\napproximations with remainder/error bounds), which are not formally defined until the next section.  We\ncomplete\nFIXME(Example 5.4)\n at the end of \nFIXME(Section 6).\n\n\\vglue9pt \nFIXME({\\it Remark} 5.5)\n.  For those planning on looking at the program {\\it verify}\nwe now tie in the above description of its workings to a portion of the actual code in the program.  We note that the CWeb version of {\\it verify} is extensively documented, and is organized so that the most important details are presented first.\n\nIf the executable version of {\\it verify} is called {\\it verify} and we are in the correct place with respect to the location of the data, then a typical UNIX command line would be \n$$\n\\hbox{\\tt zcat data/000000.gz | verify 000000 > output000000} \n$$\nThis would run {\\it verify} at the node 000000, and, when needed, would pipe in the unzipped data from \\hbox{\\tt\ndata/000000.gz}.  This unzipped data contains the tree decomposition of the parameter space at the sub-box 000000. \nThe output from {\\it verify} would be redirected to the file \\hbox{\\tt output000000}.\n\nIn {\\it verify}, \\hbox{\\tt main} would check for syntax errors in the command line, and if there were no such errors, would read the location 000000 into the character array \\hbox{\\tt where}  and compute that the \\hbox{\\tt depth} of \\hbox{\\tt where} was 6, which means that 000000 contains\nsix subdivisions.   It would then immediately print \n$$\n\\hbox{\\tt verified 000000 - } \\{$$\ninto the file \\hbox{\\tt output000000}, and then call the function {\\it verify}, as follows:\n$$\n\\hbox{\\tt verify(where, depth, 0);}\n$$\n\nThe function \\hbox{\\tt verify(where, depth, autocode)} is now invoked; this time with \\hbox{\\tt autocode} equal to 0.  {\\it Verify} would first check that \\hbox{\\tt depth} was not too deep.  Next, {\\it verify} checks if \\hbox{\\tt autocode} is equal to 0, which it is, so it reads in the next (in this case, the first) integer from the unzipped file \\hbox{\\tt data/000000.gz}, and sets \\hbox{\\tt code} equal to this integer.  Now, {\\it verify} recursively calls itself on the left child (0000000) of the \\hbox{\\tt where} box and the right child (0000001) of the\n \\hbox{\\tt where} box:\n\\begin{eqnarray*}\n\\noalign{\\vskip-12pt}\n&&\n\\hbox{\\tt where[depth] = \\hbox{`}0\\hbox{'};}\n\\\\\n&& \\hbox{\\tt verify(where, depth + 1, code);}\n\\\\\n&&\n\\hbox{\\tt where[depth] = \\hbox{`}1\\hbox{'};}\n\\\\\n&&\\hbox{\\tt verify(where, depth + 1, code);}\n\\end{eqnarray*}\nIn general, \\hbox{\\tt verify(where, depth, autocode)} does the following.  It checks to see that \\hbox{\\tt depth} is not too deep.  Then if \\hbox{\\tt autocode} is equal to 0, it recursively calls itself on its left and right children.  If \\hbox{\\tt autocode} is not equal to 0, then \\hbox{\\tt code} is set equal to \\hbox{\\tt autocode}, and\nthree possibilities can occur.  Either, \n\\vglue9pt\n1)  \\hbox{\\tt code} is less than zero, in which case we are at \na sub-box to be skipped, \n and {\\it verify} prints out its location  (\\hbox{\\tt where}) in \\hbox{\\tt output000000} and recursively moves on to the next node in the tree, or \n\\vglue9pt\n2) \\hbox{\\tt code} is greater than zero and it invokes a condition/killerword from the file {\\it conditionlist} which kills the entire sub-box \\hbox{\\tt where}\nin which case \\hbox{\\tt verify} simply recursively moves on to the next node in the tree, or \n\\vglue9pt\n3) \\hbox{\\tt code} is greater than zero and it invokes a condition/killerword from the file {\\it conditionlist} which does not kill the entire sub-box \\hbox{\\tt where}, in which case\n\\hbox{\\tt verify} subdivides the sub-box \\hbox{\\tt where} and recursively calls itself on the left child and the right child, using the same \\hbox{\\tt code}:\n\\begin{eqnarray*}\n&&\\hbox{\\tt where[depth] = \\hbox{`}0\\hbox{'};}\n\\\\ &&\\hbox{\\tt verify(where, depth + 1, code);}\n\\\\ &&\\hbox{\\tt where[depth] =\\hbox{`}1\\hbox{'};}\n\\\\ &&\\hbox{\\tt verify(where, depth + 1, code);}\n\\end{eqnarray*}\nIn this way {\\it verify} tests the entire starting box, in this case the sub-box 000000, and if successful at killing\nit minus the omissions which it prints out, it finishes \\hbox{\\tt main} by printing out a right bracket into \\hbox{\\tt output000000}. \n  \n", "meta": {"hexsha": "5fe236ca25dad91fea9fea1b4ccbb3636e44a86f", "size": 20640, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/TeX_and_Figures_Files/Chapter_3.tex", "max_stars_repo_name": "njt99/findingkillerwords", "max_stars_repo_head_hexsha": "71271dca14a9986d631608929544bcd6d68813f0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thesis/TeX_and_Figures_Files/Chapter_3.tex", "max_issues_repo_name": "njt99/findingkillerwords", "max_issues_repo_head_hexsha": "71271dca14a9986d631608929544bcd6d68813f0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis/TeX_and_Figures_Files/Chapter_3.tex", "max_forks_repo_name": "njt99/findingkillerwords", "max_forks_repo_head_hexsha": "71271dca14a9986d631608929544bcd6d68813f0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.385786802, "max_line_length": 560, "alphanum_fraction": 0.705620155, "num_tokens": 6464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3130867082017657}}
{"text": "\\part{Lecture 03: Dynamic Programming}\r\n\\title[RL Lecture 03]{Lecture 03: Dynamic Programming}  \r\n\\date{}  \r\n\\frame{\\titlepage} \r\n\\frame{\\frametitle{Table of Contents}\\tableofcontents} \r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\section{Introduction} \r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% What is Dynamic Programming? %%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{What is Dynamic Programming (DP)?}\r\n\r\n\\begin{block}{Basic DP definition}\r\n\\begin{itemize}\r\n\t\\item \\hl{Dynamic}: sequential or temporal problem structure\r\n\t\\item \\hl{Programming}: mathematical optimization, i.e., numerical solutions\r\n\\end{itemize}\r\n\\end{block}\r\n\\pause\r\n\\vspace{1cm}\r\nFurther characteristics:\r\n\\begin{itemize}\r\n\t\\item DP is a collection of algorithms to solve MDPs and neighboring problems.\r\n\t\\begin{itemize}\r\n\t\t\\item \\hl{We will focus only on finite MDPs.}\r\n\t\t\\item In case of continuous action/state space: apply quantization.\r\n\t\\end{itemize}\\pause\r\n\t\\item Use of value functions to organize and structure the search for an optimal policy.\r\n\t\\item Breaks problems into subproblems and solves them.\r\n\\end{itemize}\r\n}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Requirements %%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{Requirements for DP}\r\nDP can be applied to problems with the following characteristics.\r\n\\begin{itemize}\r\n\t\\item Optimal substructure:\r\n\t\\begin{itemize}\r\n\t\t\\item Principle of optimality applies.\r\n\t\t\\item Optimal solution can be derived from subproblems.\r\n\t\\end{itemize}\\pause\r\n\\end{itemize}\r\n\\begin{itemize}\r\n\t\\item Overlapping subproblems:\r\n\t\\begin{itemize}\r\n\t\t\\item Subproblems recur many times.\r\n\t\t\\item Hence, solutions can be cached and reused.\r\n\t\\end{itemize}\r\n\\end{itemize}\\pause\r\n\\vspace{1cm}\r\nHow is that connected to MDPs?\r\n\\begin{itemize}\r\n\t\\item MDPs satisfy above's properties:\r\n\t\\begin{itemize}\r\n\t\t\\item Bellman equation provides recursive decomposition.\r\n\t\t\\item Value function stores and reuses solutions.\r\n\t\\end{itemize}\r\n\\end{itemize}\r\n}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Example: DP vs. Exhaustive Search (1)%%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{Example: DP vs. Exhaustive Search (1)}\r\n\\begin{figure}\t\t\r\n\t\\animategraphics[loop,controls,width=10cm]{0.75}{fig/lec03/gif/PB_Bi_ES-}{0}{6}\r\n\t\\caption{Shortest path problem to travel from Paderborn to Bielefeld: Eshaustive search requires 14 travel segment evaluations since every possible travel route is evaluated independently.}\r\n\t\\label{fig:PB_Bi_ES}\r\n\\end{figure}\r\n}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Example: DP vs. Exhaustive Search (2)%%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{Example: DP vs. Exhaustive Search (2)}\r\n\\begin{figure}\t\t\r\n\t\\animategraphics[loop,controls,width=10cm]{0.75}{fig/lec03/gif/PB_Bi_DP-}{0}{5}\r\n\t\\caption{Shortest path problem to travel from Paderborn to Bielefeld: DP requires only 10 travel segment evaluations in order to calculate the optimal travel policy due to the reuse of subproblem results.}\r\n\t\\label{fig:PB_Bi_DP}\r\n\\end{figure}\r\n}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Utility DP %%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{Utility of DP in the RL Context}\r\nDP is used for iterative \\hl{planning} (i.e., \\hl{model-based} prediction and control) in an MDP.\r\n\\begin{itemize}\r\n\t\\item Prediction:\r\n\t\\begin{itemize}\r\n\t\t\\item Input: MDP $\\left\\langle\\mathcal{X}, \\mathcal{U}, \\bm{\\mathcal{P}}, \\mathcal{R}, \\gamma \\right\\rangle$ and policy $\\pi$\r\n\t\t\\item Output: (estimated) value function $\\hat{v}_{\\pi} \\approx v_{\\pi}$\r\n\t\\end{itemize}\\pause\r\n\t\\item Control:\r\n\t\\begin{itemize}\r\n\t\t\\item Input: MDP $\\left\\langle\\mathcal{X}, \\mathcal{U}, \\bm{\\mathcal{P}}, \\mathcal{R}, \\gamma \\right\\rangle$\r\n\t\t\\item Output: (estimated) optimal value function $\\hat{v}_{\\pi}^* \\approx v_{\\pi}^*$ or policy $\\hat{\\pi}^*\\approx\\pi^*$\r\n\t\\end{itemize}\\pause\r\n\\end{itemize}\r\n\\vspace{1cm}\r\nIn both applications \\hl{DP requires full knowledge of the MDP} structure.\r\n\\begin{itemize}\r\n\t\\item Feasibility in real-world engineering applications (model vs. system) is therefore limited.\\pause\r\n\t\\item But: \\hl{following DP concepts are largely used in modern data-driven RL algorithms.}\r\n\\end{itemize}\r\n}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\section{Policy Evaluation} \r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\begin{frame}\r\n\\frametitle{Table of Contents}\r\n\\tableofcontents[currentsection]\r\n\\end{frame}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Policy Evaluation Background (1) %%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{Policy Evaluation Background (1)}\r\n\\begin{itemize}\r\n\t\\item Problem: evaluate a given policy $\\pi$ to predict $v_\\pi$. \\pause\r\n\t\\item Recap: Bellman equation for $x_k\\in\\mathcal{X}$ is given as\r\n\t\\begin{align*}\r\n\tv_\\pi(x_k) &= \\El{G_k|X_k=x_k}{\\pi},\\\\\r\n\t\t\t\t\t\t\t\t\t&= \\El{R_{k+1}+ \\gamma G_{k+1}|X_k=x_k}{\\pi},\\\\\r\n\t\t\t\t\t\t\t\t\t&= \\El{R_{k+1}+ \\gamma v_\\pi(X_{k+1})|X_k=x_k}{\\pi}.\r\n\t\\end{align*}\\vspace{-0.5cm}\\pause\r\n\t\\item Or in matrix form:\r\n\t\t\\begin{equation*}\r\n\t\t\t\\begin{split}\r\n\t\t\t\t\t\\bm{v}_{\\mathcal{X}}^{\\pi}&=\\bm{r}_{\\mathcal{X}}^{\\pi}+\\gamma\\bm{\\mathcal{P}}_{xx'}^{\\pi}\\bm{v}_{\\mathcal{X}}^{\\pi},\\\\\r\n\t\t\t\t\t\\begin{bmatrix} v_{1}^{\\pi} \\\\ \\vdots \\\\ v_{n}^{\\pi} \\end{bmatrix} &= \\begin{bmatrix} \\mathcal{R}_{1}^{\\pi} \\\\ \\vdots \\\\ \\mathcal{R}_{n}^{\\pi} \\end{bmatrix} + \\gamma\\begin{bmatrix} p_{11}^{\\pi} & \\cdots & p_{1n}^{\\pi}\\\\ \\vdots &  & \\vdots\\\\ p_{n1}^{\\pi} & \\cdots & p_{nn}^{\\pi}\\end{bmatrix}\\begin{bmatrix} v_{1}^{\\pi} \\\\ \t\t\t\\vdots \\\\ v_{n}^{\\pi} \\end{bmatrix}.\r\n\t\t\t\\end{split}\r\n\t\t\t\\end{equation*}\\pause\r\n\t\t\t\\item Solving the Bellman equation for $v_\\pi$ requires handling a linear equation system with $n$ unknowns (i.e., number of states).\r\n\t\t\t\\item Remember that the reward function $\\mathcal{R}_{x}^{\\pi}$ might also contains stochastic influences depending on the MDP structure (see \\defref{defi:Markov_decision_process}).\r\n\\end{itemize}\r\n}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Policy Evaluation Background (2) %%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{Policy Evaluation Background (2)}\r\n\\begin{itemize}\r\n\t\\item Problem: directly calculating $v_\\pi$ is numerically costly for high-dimensional state spaces (e.g., by matrix inversion). \\pause\r\n\t\\item General idea: \\hl{apply iterative approximations} $\\hat{v}_{i}(x_{k})=v_{i}(x_{k})$ of $v_\\pi(x_{k})$ with decreasing errors:\r\n\t\\begin{equation}\r\n\t\\left\\|v_{i}(x_{k}) - v_\\pi\\right\\|_{\\infty}\\rightarrow 0 \\quad \\mbox{for} \\quad i=1,2,3,\\ldots\r\n\\end{equation}\\pause\r\n\t\\item The Bellman equation in matrix form can be rewritten as:\r\n\t\\begin{equation}\r\n\t\\label{eq:Bellman_matrix_Ab}\r\n\t\\underbrace{\\left(\\bm{I}-\\gamma\\bm{\\mathcal{P}}_{xx'}^{\\pi}\\right)}_{\\bm{A}}\\underbrace{\\bm{v}_{\\mathcal{X}}^{\\pi}}_{\\bm{\\zeta}} =\\underbrace{\\bm{r}_{\\mathcal{X}}^{\\pi}}_{\\bm{b}}.\r\n\\end{equation}\\pause\r\n\\item To iteratively solve this linear equation $\\bm{A}\\bm{\\zeta}=\\bm{b}$, one can apply numerous methods such as\r\n\\begin{itemize}\r\n\t\\item General gradient descent,\r\n\t\\item Richardson iteration,\r\n\t\\item Kyrlov subspace methods.\r\n\\end{itemize}\r\n\\end{itemize}\r\n}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Richardson Iteration (1)%%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{Richardson Iteration (1)}\r\nIn the MDP context, the Richardson iteration became the default solution approach to iteratively solve:\r\n\\begin{equation*}\r\n\t\\bm{A}\\bm{\\zeta} =\\bm{b}.\r\n\\end{equation*}\r\nThe \\hl{Richardson iteration} is \r\n\\begin{equation}\r\n\\label{eq:richardson_general}\r\n\t\\bm{\\zeta}_{i+1}= \\bm{\\zeta}_{i} + \\omega(\\bm{b}-\\bm{A}\\bm{\\zeta}_i)\r\n\\end{equation}\r\nwith $\\omega$ being a scalar parameter that has to be chosen such that the sequence $\\bm{\\zeta}_{i}$ converges. \\pause To choose $\\omega$ we inspect the series of approximation errors $\\bm{e}_i=\\bm{\\zeta}_{i}-\\bm{\\zeta}$ and apply it to \\eqref{eq:richardson_general}:\r\n\\begin{equation}\r\n\t\\bm{e}_{i+1}= \\bm{e}_{i} - \\omega\\bm{A}\\bm{e}_i=\\left(\\bm{I}-\\omega\\bm{A}\\right)\\bm{e}_{i}.\r\n\\end{equation}\\pause\r\nTo evaluate convergence we inspect the following norm:\r\n\\begin{equation}\r\n\\label{eq:richardson_error_sequence}\r\n\t\\left\\|\\bm{e}_{i+1}\\right\\|_{\\infty}= \\left\\|\\left(\\bm{I}-\\omega\\bm{A}\\right)\\bm{e}_{i}\\right\\|_{\\infty}.\r\n\\end{equation}\r\n}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Richardson Iteration (2)%%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{Richardson Iteration (2)}\r\nSince any induced matrix norm is sub-multiplicative, we can approximate \\eqref{eq:richardson_error_sequence} by the inequality:\r\n\\begin{equation}\r\n\t\\left\\|\\bm{e}_{i+1}\\right\\|_{\\infty} \\leq \\left\\|\\left(\\bm{I}-\\omega\\bm{A}\\right)\\right\\|_{\\infty} \\left\\|\\bm{e}_{i}\\right\\|_{\\infty}.\r\n\\end{equation}\\pause\r\nHence, the series converges if \r\n\\begin{equation} \r\n\t\\left\\|\\left(\\bm{I}-\\omega\\bm{A}\\right)\\right\\|_{\\infty}<1 .\r\n\\end{equation}\\pause\r\nInserting from \\eqref{eq:Bellman_matrix_Ab} leads to:\r\n\\begin{equation} \r\n\t\\left\\|\\left(\\bm{I}(1-\\omega)+\\omega\\gamma\\bm{\\mathcal{P}}_{xx'}^{\\pi}\\right)\\right\\|_{\\infty}<1 .\r\n\\end{equation}\\pause\r\nFor $\\omega =1$ we receive:\r\n\\begin{equation} \r\n\t\\gamma\\left\\|\\left(\\bm{\\mathcal{P}}_{xx'}^{\\pi}\\right)\\right\\|_{\\infty}<1 .\r\n\\end{equation}\\pause\r\nSince the row elements of $\\bm{\\mathcal{P}}_{xx'}^{\\pi}$ always sum up to 1,\r\n\\begin{equation} \r\n\t\\gamma < 1 \r\n\\end{equation}\r\nfollows. Hence, \\hl{when discounting the Richardson iteration always converges for MDPs} even if we assume $\\omega=1$.\r\n}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Iterative Policy Evaluation by Richardson Iteration (1)%%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{Iterative Policy Evaluation by Richardson Iteration (1)}\r\nGeneral form for any $x_k\\in\\mathcal{X}$ at iteration $i$ is given as:\r\n\\begin{equation}\r\n\tv_{i+1}(x_k)\t= \\sum_{u_k\\in\\mathcal{U}}\\bm{\\pi}(u_k|x_k)\\left(\\mathcal{R}^u_x + \\gamma\\sum_{x_{k+1}\\in\\mathcal{X}}p_{xx'}^u v_{i}(x_{k+1})\\right)\\, .\r\n\\end{equation}\\pause\r\nMatrix form then is:\r\n\\begin{equation}\r\n\\label{eq:iterative_policy_eval_matrix}\r\n\t\\bm{v}_{\\mathcal{X},i+1}^{\\pi} =\\bm{r}_{\\mathcal{X}}^{\\pi}+\\gamma\\bm{\\mathcal{P}}_{xx'}^{\\pi}\\bm{v}_{\\mathcal{X},i}^{\\pi}\\, .\r\n\\end{equation}\\pause\r\n\\vspace{0.5cm}\r\n\\begin{figure}\t\t\r\n\t%\\hspace*{-1.5cm}\r\n\t\\includegraphics[width=7cm]{fig/lec03/Back_Up_Value_Policy_Evaluation.pdf}\r\n\t\\caption{Backup diagram for iterative policy evaluation}\r\n\t\\label{fig:Back_Up_Value_Policy_Evaluation}\r\n\\end{figure}\r\n}\r\n\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Iterative Policy Evaluation by Richardson Iteration (2)%%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{Iterative Policy Evaluation by Richardson Iteration (2)}\r\n\\begin{itemize}\r\n\t\\item During one Richardson iteration the 'old' value of $x_k$ is replaced with a 'new' value from the 'old' values of the successor state $x_{k+1}$.\r\n\t\\begin{itemize}\r\n\t\t\\item Update $v_{i+1}(x_k)$ from $v_{i}(x_{k+1})$, see \\figref{fig:Back_Up_Value_Policy_Evaluation}.\r\n\t\t\\item Updating estimates $(v_{i+1})$ on the basis of other estimates $(v_{i})$ is often called \\hl{bootstrapping}.\r\n\t\\end{itemize}\\pause\r\n\t\\item The Richardson iteration can be interpreted as a gradient descent algorithm for solving \\eqref{eq:Bellman_matrix_Ab}.\\pause\r\n\t\\item This leads to \\hl{synchronous, full backups} of the entire state space $\\mathcal{X}$.\\pause\r\n\t\\item Also called \\hl{expected update} because it is based on the expectation over all possible next states (utilizing full knowledge).\\pause\r\n\t\\item In subsequent lectures, the expected update will be supplemented by data-driven samples from the environment.\r\n\\end{itemize}\r\n\r\n}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Iterative Policy Evaluation Example: Forest Tree MDP%%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{Iterative Policy Evaluation Example: Forest Tree MDP}\r\nLet's reuse the forest tree MDP example from \\figref{fig:Forest_Markov_Decision_Process_State_Value} with \\textit{fifty-fifty policy} and discount factor $\\gamma=0.8$\r\nplus disaster probability $\\alpha=0.2$:\r\n\\begin{equation*}\r\n\t\\bm{\\mathcal{P}}_{xx'}^{\\pi} = \\begin{bmatrix}0 & \\frac{1-\\alpha}{2} & 0 & \\frac{1+\\alpha}{2}  \\\\ 0 & 0 &\\frac{1-\\alpha}{2} & \\frac{1+\\alpha}{2} \\\\ 0 & 0 &\\frac{1-\\alpha}{2} & \\frac{1+\\alpha}{2} \\\\ 0 & 0 & 0 & 1\\end{bmatrix}, \\quad\\bm{r}_{\\mathcal{X}}^{\\pi} = \\begin{bmatrix}0.5 \\\\ 1 \\\\ 2 \\\\ 0 \\end{bmatrix} \\, .\r\n\\end{equation*}\r\n\\pause\r\n\\begin{table}\r\n\t\\centering\r\n\t\t\\begin{tabular}{l|l|l|l|l}\r\n\t\t\t$i$ & $v_i(x=1)$ & $v_i(x=2)$ & $v_i(x=3)$ & $v_i(x=4)$\\\\\r\n\t\t\t\\hline\r\n\t\t\t0  & 0 & 0 & 0 & 0\\\\ \\pause\r\n\t\t\t1  & 0.5 & 1 & 2 &0\\\\ \\pause\r\n\t\t\t2  & 0.82 & 1.64 & 2.64 & 0\\\\ \\pause\r\n\t\t\t3  & 1.03 & 1.85 & 2.85 & 0\\\\ \\pause\r\n\t\t\t\\vdots & \\vdots & \\vdots & \\vdots & \\vdots \\\\\r\n\t\t\t$\\infty$ & 1.12 & 1.94 & 2.94 & 0\r\n\t\t\\end{tabular}\t\r\n\t\\label{tab:Forest_tree_policy_eval}\r\n\t\\caption{Policy evaluation by Richardson iteration \\eqref{eq:iterative_policy_eval_matrix} for forest tree MDP}\r\n\\end{table}\r\n}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Variant: In-Place Updates %%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{Variant: In-Place Updates}\r\nInstead of applying \\eqref{eq:iterative_policy_eval_matrix} to the entire vector $\\bm{v}_{\\mathcal{X},i+1}^{\\pi}$ in 'one shot' (synchronous backup), an elementwise \\hl{in-place} version of the policy evaluation can be carried out: \r\n\\setlength{\\algomargin}{0.5em}\r\n\\begin{algorithm}[H]\r\n\\SetKwInput{Input}{input} \r\n\\SetKwInput{Output}{output}\r\n\\SetKwInput{Init}{init}\r\n\\SetKwInput{Param}{parameter}\r\n\\Input{full model of the MDP, i.e., $\\left\\langle\\mathcal{X}, \\mathcal{U}, \\bm{\\mathcal{P}}, \\mathcal{R}, \\gamma \\right\\rangle$ including policy $\\pi$}\r\n\\Param{$\\delta>0$ as accuracy termination threshold}\r\n\\Init{$v_0(x)\\, \\forall \\, x\\in\\mathcal{X}$ arbitrary except $v_0(x)=0$ if $x$ is terminal}\r\n \\Repeat{$\\Delta<\\delta$}{\r\n\t\t$\\Delta \\leftarrow 0 $\\;\r\n\t\t\\For{$\\forall \\, x_k\\in\\mathcal{X}$}{\r\n\t\t\t$\\tilde{v}\\leftarrow \\hat{v}(x_k)$\\;\r\n\t\t\t$\\hat{v}(x_k)\\leftarrow  \\sum_{u_k\\in\\mathcal{U}}\\pi(u_k|x_k)\\left(\\mathcal{R}^u_x + \\gamma\\sum_{x_{k+1}\\in\\mathcal{X}}p_{xx'}^u \\hat{v}(x_{k+1})\\right)$\\;\r\n\t\t\t$\\Delta \\leftarrow \\max\\left(\\Delta, |\\tilde{v}-\\hat{v}(x_k)|\\right)$\\;\r\n\t\t}\r\n\t}\r\n\\caption{\r\n Iterative policy evaluation using in-place updates (output: estimate of $\\bm{v}_{\\mathcal{X}}^{\\pi}$)}\r\n\\label{algo:in_place_policy_update}\r\n\\end{algorithm}\r\n}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% In-Place Policy Evaluation Updates for Forest Tree MDP%%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{In-Place Policy Evaluation Updates for Forest Tree MDP}\r\n\\begin{itemize}\r\n\t\\item In-place algorithms allow to update states in a beneficial order. \\pause\r\n\t\\item May converge faster than regular Richardson iteration if state update order is chosen wisely (sweep through state space).\\pause\r\n\t\\item For forest tree MDP: reverse order, i.e., start with $x=4$.\\pause\r\n\t\\item As can be seen in \\tabref{tab:Forest_tree_policy_eval_in_place} the in-place updates especially converge faster for the 'early states'.\r\n\\end{itemize}\r\n\r\n\\begin{table}\r\n\t\\centering\r\n\t\t\\begin{tabular}{l|l|l|l|l}\r\n\t\t\t$i$ & $v_i(x=1)$ & $v_i(x=2)$ & $v_i(x=3)$ & $v_i(x=4)$\\\\\r\n\t\t\t\\hline\r\n\t\t\t0  & 0 & 0 & 0 & 0\\\\\r\n\t\t\t1  & 1.03 & 1.64 & 2 &0\\\\\r\n\t\t\t2  & 1.09 & 1.85 & 2.64 & 0\\\\\r\n\t\t\t3  & 1.11 & 1.91 & 2.85 & 0\\\\\r\n\t\t\t\\vdots & \\vdots & \\vdots & \\vdots & \\vdots \\\\\r\n\t\t\t$\\infty$ & 1.12 & 1.94 & 2.94 & 0\r\n\t\t\\end{tabular}\t\r\n\t\\caption{In-place updates for forest tree MDP}\r\n\t\\label{tab:Forest_tree_policy_eval_in_place}\r\n\\end{table}\r\n}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\section{Policy Improvement} \r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\begin{frame}\r\n\\frametitle{Table of Contents}\r\n\\tableofcontents[currentsection]\r\n\\end{frame}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% General Idea on Policy Improvement%%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{General Idea on Policy Improvement}\r\n\\vspace{-0.1cm}\r\n\\begin{itemize}\r\n\t\\item If we know $v_{\\pi}$ of a given MDP, how to improve the policy?\\pause\r\n\t\\item The simple idea of policy improvement is:\r\n\t\\begin{itemize}\r\n\t\t\\item Consider a new (non-policy conform) action $u\\neq{\\pi}(x_k)$.\r\n\t\t\\item Follow thereafter the current policy $\\pi$.\r\n\t\t\\item Check the action-value of this 'new move'. If it is better than the 'old' value, take it.\r\n\t\\end{itemize}\r\n\\end{itemize}\r\n\t\\begin{equation}\r\n\t\\label{eq:policy_improv_theo01}\r\n\t\t\tq_\\pi(x_k,u_k)\t= \\E{R_{k+1} + \\gamma \tv_{\\pi}(X_{k+1})|X_{k}=x_{k},U_{k}=u_{k}}\\,.\r\n\t\\end{equation}\\pause\\vspace{-0.3cm}\r\n\t\\setcounter{mytheo}{0}\r\n\\vspace{-0.1cm}\r\n\\begin{theo}{Policy improvement}{Policy_improvement}\r\nIf for any deterministic policy pair $\\pi$ and $\\pi'$\r\n\\begin{equation}\r\n\\label{eq:policy_improv_theo02}\r\n\tq_{\\pi}(x,\\pi'(x))\\geq v_{\\pi}(x) \\quad \\forall x\\in\\mathcal{X}\r\n\\end{equation}\r\napplies, then the policy $\\pi'$ must be as good as or better than $\\pi$. Hence, it obtains greater or equal expected return\r\n\\begin{equation}\r\n\\label{eq:policy_improv_theo03}\r\n\tv_{\\pi'}(x) \\geq v_{\\pi}(x) \\quad \\forall x\\in\\mathcal{X} .\r\n\\end{equation}\r\n\\end{theo}\r\n}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Proof of Policy Improvement Theorem %%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{Proof of Policy Improvement Theorem}\r\nStart with \\eqref{eq:policy_improv_theo02} and recursively reapply \\eqref{eq:policy_improv_theo01}:\r\n\\begin{equation}\r\n\\hspace{-0.35cm}\r\n\t\\begin{split}\r\n\t\tv_{\\pi}(x_k) &\\leq q_{\\pi}(x_k,\\pi'(x_k)),\\\\\r\n\t\t\t\t\t\t\t\t\t\t\t&= \\E{R_{k+1} + \\gamma \tv_{\\pi}(X_{k+1})|X_{k}=x_{k},U_{k}=\\pi'(x_{k})},\\\\\r\n\t\t\t\t\t\t\t\t\t\t\t&= \\El{R_{k+1} + \\gamma \tv_{\\pi}(X_{k+1})|X_{k}=x_{k}}{\\pi'},\\\\\r\n\t\t\t\t\t\t\t\t\t\t\t&\\leq \\El{R_{k+1} + \\gamma \tq_{\\pi}(x_{k+1},\\pi'(x_{k+1}))|X_{k}=x_{k}}{\\pi'},\\\\\r\n\t\t\t\t\t\t\t\t\t\t\t&= \\El{R_{k+1} + \\gamma \t\\El{R_{k+2} + \\gamma \tv_{\\pi}(X_{k+2})|X_{k+1},\\pi'(x_{k+1})}{\\pi'}|X_{k}=x_{k}}{\\pi'},\\\\\r\n\t\t\t\t\t\t\t\t\t\t\t&= \\El{R_{k+1} + \\gamma \tR_{k+2} + \\gamma^2 v_{\\pi}(X_{k+2})|X_{k}=x_{k}}{\\pi'},\\\\\r\n\t\t\t\t\t\t\t\t\t\t\t&\\leq \\El{R_{k+1} + \\gamma \tR_{k+2} + \\gamma^2 R_{k+3}+ \\gamma^3 v_{\\pi}(X_{k+3})|X_{k}=x_{k}}{\\pi'},\\\\\r\n\t\t\t\t\t\t\t\t\t\t\t&\\hspace{0.2cm}\\vdots\\\\\r\n\t\t\t\t\t\t\t\t\t\t\t&\\leq \\El{R_{k+1} + \\gamma \tR_{k+2} + \\gamma^2 R_{k+3}+ \\gamma^3 R_{k+4}+\\cdots|X_{k}=x_{k}}{\\pi'},\\\\\r\n\t\t\t\t\t\t\t\t\t\t\t&=v_{\\pi'}(x_k).\r\n\t\\end{split}\r\n\\end{equation}\r\n}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Greedy Policy Improvement (1) %%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{Greedy Policy Improvement (1)}\r\n\\begin{itemize}\r\n\t\\item So far, policy improvement addressed only changing the policy at a single state.\\pause\r\n\t\\item Now, extend this scheme to all states by selecting the best action according to $q_\\pi(x_{k}, u_{k})$ in every state (\\hl{greedy policy improvement}):\\pause\r\n\\end{itemize}\r\n\\vspace{0.25cm}\r\n\\begin{equation}\r\n\t\\begin{split}\r\n\t\t\\pi'(x_{k})&\t=\\argmax_{u_k\\in\\mathcal{U}} q_\\pi(x_{k}, u_{k}),\\\\\r\n\t\t\t\t\t\t\t\t\t\t& = \\argmax_{u_k\\in\\mathcal{U}} \\E{R_{k+1} + \\gamma \tv_{\\pi}(X_{k+1})|X_{k}=x_{k},U_{k}=u_{k}},\\\\\r\n\t\t\t\t\t\t\t\t\t\t& = \\argmax_{u_k\\in\\mathcal{U}} \\mathcal{R}^u_x + \\gamma \\sum_{x_{k+1}\\in\\mathcal{X}}p_{xx'}^u v_\\pi(x_{k+1}) \\, .\r\n\t\\end{split}\r\n\\end{equation}\r\n\\begin{itemize}\r\n\t\\item Again, consider that $\\mathcal{R}^u_x$ could be of deterministic or stochastic nature.\r\n\\end{itemize}\r\n}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Greedy Policy Improvement (2) %%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{Greedy Policy Improvement (2)}\r\n\\begin{itemize}\r\n\t\\item Each greedy policy improvement takes the best action in a one-step look-ahead search and, therefore, satisfies \\theoref{theo:Policy_improvement}.\\pause\r\n\t\\item If after a policy improvement step $v_{\\pi}(x_k) = v_{\\pi'}(x_k)$ applies, it follows:\r\n\\end{itemize}\r\n\\vspace{0.25cm}\r\n\\begin{equation}\r\n\t\\begin{split}\r\n\t\tv_{\\pi'}(x_k) &=\t\\max_{u_k\\in\\mathcal{U}} \\E{R_{k+1} + \\gamma \tv_{\\pi'}(X_{k+1})|X_{k}=x_{k},U_{k}=u_{k}},\\\\\r\n\t\t\t\t\t\t\t\t\t\t& = \\max_{u_k\\in\\mathcal{U}} \\mathcal{R}^u_x + \\gamma \\sum_{x_{k+1}\\in\\mathcal{X}}p_{xx'}^u v_{\\pi'}(x_{k+1}) \\, .\r\n\t\\end{split}\r\n\\end{equation}\\pause\r\n\\begin{itemize}\r\n\t\\item This is the Bellman optimality equation, which guarantees that $\\pi'=\\pi$ must be optimal policies.\\pause\r\n\t\\item Although proof for policy improvement theorem was presented for deterministic policies, transfer to stochastic policies $\\pi(u_k|x_k)$ is possible.\\pause\r\n\t\\item Takeaway message: \\hl{policy improvement theorem guarantees finding optimal policies in finite MDPs} (e.g., by DP).\r\n\\end{itemize}\t\r\n}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\section{Policy and Value Iteration} \r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\begin{frame}\r\n\\frametitle{Table of Contents}\r\n\\tableofcontents[currentsection]\r\n\\end{frame}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Concept of Policy Iteration %%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{Concept of Policy Iteration}\r\n\\begin{itemize}\r\n\t\\item Policy iteration \\hl{combines the previous policy evaluation and policy improvement} in an iterative sequence: \r\n\\end{itemize}\r\n\\vspace{0.25cm}\r\n\\begin{equation}\r\n\\label{eq:policy_iter}\r\n\t\\pi_0 \\rightarrow v_{\\pi_0} \\rightarrow \\pi_1 \\rightarrow v_{\\pi_1} \\rightarrow \\cdots \\pi^* \\rightarrow v_{\\pi^*}\r\n\\end{equation}\r\n\\begin{itemize}\r\n\t\\item Evaluate $\\rightarrow$ improve $\\rightarrow$ evaluate $\\rightarrow$ improve ...\\pause\r\n\t\\item In the 'classic' policy iteration, each policy evaluation step in \\eqref{eq:policy_iter} is fully executed, i.e., for each policy $\\pi_i$ an exact estimate of $v_{\\pi_i}$ is provided either by iterative policy evaluation with a sufficiently high number of steps or by any other method that fully solves \\eqref{eq:Bellman_matrix_Ab}.\r\n\\end{itemize}\r\n}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Policy Iteration Example: Forest Tree MDP (1) %%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{Policy Iteration Example: Forest Tree MDP (1)}\r\n\\begin{figure}\t\t\r\n\t\\includegraphics[width=11cm]{fig/lec03/Forest_Markov_Decision_Process.pdf}\r\n\\end{figure}\r\n\\begin{itemize}\r\n\t\\item Two actions possible in each state:\r\n\t\\begin{itemize}\r\n\t\t\\item Wait $u=w$: let the tree grow.\r\n\t\t\\item Cut $u=c$: gather the wood.\r\n\t\\end{itemize}\r\n\\end{itemize}\r\n}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Policy Iteration Example: Forest Tree MDP (2) %%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{Policy Iteration Example: Forest Tree MDP (2)}\r\nAssume $\\alpha=0.2$ and $\\gamma=0.8$ and start with \\hl{'tree hater' initial policy}:\\pause\r\n\\begin{enumerate}\r\n\t\\item $\\pi_0=\\pi(u_k =\\mbox{c}|x_k) \\quad \\,\\forall x_k\\in\\mathcal{X}$.\\pause\r\n\t\\item Policy evaluation: $v_\\mathcal{X}^{\\pi_0}=\\begin{bmatrix}1 & 2 & 3 & 0\\end{bmatrix}^T$\\pause\r\n\t\\item Greedy policy improvement: \r\n\t\\begin{equation*}\r\n\t\\begin{split}\r\n\t\t\\pi_1(x_{k})& = \\argmax_{u_k\\in\\mathcal{U}} \\E{R_{k+1} + \\gamma \tv_{\\pi_0}(X_{k+1})|X_{k}=x_{k},U_{k}=u_{k}},\\\\\r\n\t\t\t\t\t\t\t\t\t\t& = \\left\\{\\pi(u_k =\\mbox{w}|x_k=1), \\pi(u_k =\\mbox{c}|x_k=2), \\pi(u_k =\\mbox{c}|x_k=3)\\right\\}\r\n\t\\end{split}\r\n\\end{equation*}\\pause\r\n\\item Policy evaluation: $v_\\mathcal{X}^{\\pi_1}=\\begin{bmatrix}1.28 & 2 & 3 & 0\\end{bmatrix}^T$\\pause\r\n\\item Greedy policy improvement: \r\n\t\\begin{equation*}\r\n\t\\begin{split}\r\n\t\t\\pi_2(x_{k})& = \\argmax_{u_k\\in\\mathcal{U}} \\E{R_{k+1} + \\gamma \tv_{\\pi_1}(X_{k+1})|X_{k}=x_{k},U_{k}=u_{k}},\\\\\r\n\t\t\t\t\t\t\t\t\t\t& = \\left\\{\\pi(u_k =\\mbox{w}|x_k=1), \\pi(u_k =\\mbox{c}|x_k=2), \\pi(u_k =\\mbox{c}|x_k=3)\\right\\},\\\\\r\n\t\t\t\t\t\t\t\t\t\t& = \\pi_1(x_{k})\\\\\r\n\t\t\t\t\t\t\t\t\t\t& = \\pi^*\r\n\t\\end{split}\r\n\\end{equation*}\r\n\\end{enumerate}\r\n}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Policy Iteration Example: Forest Tree MDP (3) %%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{Policy Iteration Example: Forest Tree MDP (3)}\r\nAssume $\\alpha=0.2$ and $\\gamma=0.8$ and start with \\hl{'tree lover' initial policy}:\\pause\r\n\\begin{enumerate}\r\n\t\\item $\\pi_0=\\pi(u_k =\\mbox{w}|x_k) \\quad \\,\\forall x_k\\in\\mathcal{X}$.\\pause\r\n\t\\item Policy evaluation: $v_\\mathcal{X}^{\\pi_0}=\\begin{bmatrix}1.14 & 1.78 & 2.78 & 0\\end{bmatrix}^T$\\pause\r\n\t\\item Greedy policy improvement: \r\n\t\\begin{equation*}\r\n\t\\begin{split}\r\n\t\t\\pi_1(x_{k})& = \\argmax_{u_k\\in\\mathcal{U}} \\E{R_{k+1} + \\gamma \tv_{\\pi_0}(X_{k+1})|X_{k}=x_{k},U_{k}=u_{k}},\\\\\r\n\t\t\t\t\t\t\t\t\t\t& = \\left\\{\\pi(u_k =\\mbox{w}|x_k=1), \\pi(u_k =\\mbox{c}|x_k=2), \\pi(u_k =\\mbox{c}|x_k=3)\\right\\}\r\n\t\\end{split}\r\n\\end{equation*}\\pause\r\n\\item Policy evaluation: $v_\\mathcal{X}^{\\pi_1}=\\begin{bmatrix}1.28 & 2 & 3 & 0\\end{bmatrix}^T$\\pause\r\n\\item Greedy policy improvement: \r\n\t\\begin{equation*}\r\n\t\\begin{split}\r\n\t\t\\pi_2(x_{k})& = \\argmax_{u_k\\in\\mathcal{U}} \\E{R_{k+1} + \\gamma \tv_{\\pi_1}(X_{k+1})|X_{k}=x_{k},U_{k}=u_{k}},\\\\\r\n\t\t\t\t\t\t\t\t\t\t& = \\left\\{\\pi(u_k =\\mbox{w}|x_k=1), \\pi(u_k =\\mbox{c}|x_k=2), \\pi(u_k =\\mbox{c}|x_k=3)\\right\\},\\\\\r\n\t\t\t\t\t\t\t\t\t\t& = \\pi_1(x_{k})\\\\\r\n\t\t\t\t\t\t\t\t\t\t& = \\pi^*\r\n\t\\end{split}\r\n\\end{equation*}\r\n\\end{enumerate}\r\n}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Policy Iteration Example: Jack's Car Rental (1) %%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{Policy Iteration Example: Jack's Car Rental (1)}\r\n\\begin{figure}\t\t\r\n\t\\includegraphics[width=2cm]{fig/lec03/car_rental.pdf}\r\n\\end{figure}\r\n\\begin{itemize}\r\n\t\\item States: Two rental locations, maximum of 20 cars each\\pause\r\n\t\\item Actions: Move up to 5 cars between locations overnight\\pause\r\n\t\\item Reward: \r\n\t\\begin{itemize}\r\n\t\t\\item  +10 \\$ for each car rented (if available at location)\r\n\t\t\\item -2 \\$ for each overnight car transfer\r\n\t\t\\item Discount: $\\gamma=0.9$\r\n\t\\end{itemize}\\pause \r\n\t\\item Dynamics: Cars returned and requested randomly following Poisson distribution\r\n\t\\begin{itemize}\r\n\t\t\\item $P_\\lambda(n)=\\frac{\\lambda^n}{n!}e^{-\\lambda}$\r\n\t\t\\item $P_\\lambda(n)=$ probability of observing $n$ events with mean event rate $\\lambda$\r\n\t\t\\item 1st location: $\\lambda_{\\mbox{req.}}=3$, $\\lambda_{\\mbox{ret.}}=3$\r\n\t\t\\item 2nd location: $\\lambda_{\\mbox{req.}}=4$, $\\lambda_{\\mbox{ret.}}=2$\r\n\t\\end{itemize}\r\n\\end{itemize}\r\n}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Policy Iteration Example: Jack's Car Rental (2) %%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{Policy Iteration Example: Jack's Car Rental (2)}\r\n\\begin{figure}\r\n\t\t\\includegraphics[width=9cm]{fig/lec03/Jack_Car_Rental.pdf}\r\n\t\t\\caption{Sequence of policies found by policy iteration including optimal state value after termination (source: R. Sutton and G. Barto, Reinforcement learning: an introduction, 2018, \\href{https://creativecommons.org/licenses/by-nc-nd/2.0/}{CC BY-NC-ND 2.0})}\r\n\t\t\\label{fig:Jack_Car_Rental}\r\n\t\\end{figure}\r\n}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Value Iteration (1) %%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{Value Iteration (1)}\r\n\\begin{itemize}\r\n\t\\item Policy iteration involves full policy evaluation steps between policy improvements.\r\n\t\\item In large state-space MDPs the full policy evaluation may be numerically very costly.\\pause\r\n\t\\item Using a limited number of iterative policy evaluations steps and then apply policy improvement may speed up the entire DP process.\\pause\r\n\t\\item \\hl{Value iteration}: One step iterative policy evaluation followed by policy improvement.\\pause\r\n\t\\item Allows simple update rule which \\hl{combines policy improvement with truncated policy evaluation}:\r\n\t\\begin{equation}\r\n\t\\begin{split}\r\n\t\tv_{i+1}(x_k) &=\t\\max_{u_k\\in\\mathcal{U}} \\E{R_{k+1} + \\gamma \tv_{i}(X_{k+1})|X_{k}=x_{k},U_{k}=u_{k}},\\\\\r\n\t\t\t\t\t\t\t\t\t\t&= \\max_{u_k\\in\\mathcal{U}} \\mathcal{R}^u_x + \\gamma \\sum_{x_{k+1}\\in\\mathcal{X}}p_{xx'}^u v_{i}(x_{k+1}) \\, .\r\n\t\\end{split}\r\n\\end{equation}\r\n\\end{itemize}\r\n}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Value Iteration (2) %%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{Value Iteration (2)}\r\n\\setlength{\\algomargin}{0.5em}\r\n\\begin{algorithm}[H]\r\n\\SetKwInput{Input}{input} \r\n\\SetKwInput{Output}{output}\r\n\\SetKwInput{Init}{init}\r\n\\SetKwInput{Param}{parameter}\r\n\\Input{full model of the MDP, i.e., $\\left\\langle\\mathcal{X}, \\mathcal{U}, \\bm{\\mathcal{P}}, \\mathcal{R}, \\gamma \\right\\rangle$}\r\n\\Param{$\\delta>0$ as accuracy termination threshold}\r\n\\Init{$v_0(x)\\, \\forall \\, x\\in\\mathcal{X}$ arbitrary except $v_0(x)=0$ if $x$ is terminal}\r\n \\Repeat{$\\Delta<\\delta$}{\r\n\t\t$\\Delta \\leftarrow 0 $\\;\r\n\t\t\\For{$\\forall \\, x_k\\in\\mathcal{X}$}{\r\n\t\t\t$\\tilde{v}\\leftarrow \\hat{v}(x_k)$\\;\r\n\t\t\t$\\hat{v}(x_k)\\leftarrow  \\max_{u_k\\in\\mathcal{U}}\\left(\\mathcal{R}^u_x + \\gamma\\sum_{x_{k+1}\\in\\mathcal{X}}p_{xx'}^u \\hat{v}(x_{k+1})\\right)$\\;\r\n\t\t\t$\\Delta \\leftarrow \\max\\left(\\Delta, |\\tilde{v}-\\hat{v}(x_k)|\\right)$\\;\r\n\t\t}\r\n\t}\r\n\\Output{Deterministic policy $\\pi\\approx\\pi^*$, such that}\r\n\t$\\pi(x_k)\\leftarrow  \\argmax_{u_k\\in\\mathcal{U}}\\left(\\mathcal{R}^u_x + \\gamma\\sum_{x_{k+1}\\in\\mathcal{X}}p_{xx'}^u \\hat{v}(x_{k+1})\\right)$\\;\r\n\\caption{Value iteration (note: compared to policy iteration, value iteration doesn't require an initial policy but only a state-value guess)}\r\n\\end{algorithm}\r\n}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Value Iteration for Forest Tree MDP %%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{Value Iteration for Forest Tree MDP}\r\n\\begin{figure}\t\t\r\n\t\\includegraphics[width=6cm]{fig/lec03/Forest_Markov_Decision_Process.pdf}\r\n\\end{figure}\r\n\\begin{itemize}\r\n\t\\item Assume again $\\alpha=0.2$ and $\\gamma=0.8$.\\pause\r\n\t\\item Similar to in-place update policy evaluation, reverse order and start value iteration with $x=4$.\\pause\r\n\t\\item As shown in \\tabref{tab:Forest_tree_value_iteration} value iteration converges in one step (for the given problem) to the optimal state-value. \r\n\\end{itemize}\r\n\\begin{table}\r\n\t\\centering\r\n\t\t\\begin{tabular}{l|l|l|l|l}\r\n\t\t\t$i$ & $v_i(x=1)$ & $v_i(x=2)$ & $v_i(x=3)$ & $v_i(x=4)$\\\\\r\n\t\t\t\\hline\r\n\t\t\t0  & 0 & 0 & 0 & 0\\\\\r\n\t\t\t1  & 1.28 & 2 & 3 &0\\\\\r\n\t\t\t*  & 1.28 & 2 & 3 &0\r\n\t\t\\end{tabular}\t\r\n\t\\caption{Value iteration for forest tree MDP}\r\n\t\\label{tab:Forest_tree_value_iteration}\r\n\\end{table}\r\n}\r\n\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\section{Further Aspects} \r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\begin{frame}\r\n\\frametitle{Table of Contents}\r\n\\tableofcontents[currentsection]\r\n\\end{frame}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Summarizing DP Algorithms %%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{Summarizing DP Algorithms}\r\n\\begin{itemize}\r\n\t\\item All DP algorithms are based on the state-value $v(x)$.\r\n\t\\begin{itemize}\r\n\t\t\\item Complexity is $\\mathcal{O}(m\\cdot n^2)$ for $m$ actions and $n$ states.\r\n\t\t\\item Evaluate all $n^2$ state transitions while considering up to $m$ actions per state.\r\n\t\\end{itemize}\\pause\r\n\t\\item Could be also applied to action-values $q(x,u)$.\r\n\t\\begin{itemize}\r\n\t\t\\item Complexity is inferior with $\\mathcal{O}(m^2\\cdot n^2)$.\r\n\t\t\\item There are up to $m^2$ action-values which require $n^2$ state transition evaluations each.\r\n\t\\end{itemize}\r\n\\end{itemize}\r\n\\pause\r\n\\begin{table}\r\n\t\\centering\r\n\t\t\\begin{tabular}{|M{1.65cm}||M{4.75cm}|M{4cm}|}\r\n\t\t\t\\hline\r\n\t\t\tProblem & Relevant Equations & Algorithm\\\\\r\n\t\t\t\\hline\\hline\r\n\t\t\tprediction & Bellman expectation eq. &  policy evaluation\\\\\r\n\t\t\t\\hline\r\n\t\t\tcontrol & Bellman expectation eq. \\& greedy policy improvement & policy iteration\\\\\r\n\t\t\t\\hline\r\n\t\t\tcontrol & Bellman optimality eq. & value iteration\\\\\r\n\t\t\t\\hline\r\n\t\t\\end{tabular}\t\r\n\t\t\\caption{Short overview addressing the treated DP algorithms}\r\n\t\t\\label{tab:DP_syn_algos}\r\n\\end{table}\r\n}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%%Asynchronous DP%%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{Asynchronous DP}\r\n\\begin{itemize}\r\n\t\\item DP algorithms considered so far used \\hl{synchronous backups}:\r\n\t\\begin{itemize}\r\n\t\t\\item In one iteration the entire state space is updated.\r\n\t\t\\item May be computational expensive for large MDPs.\r\n\t\t\\item Some state-values or policy parts may converge faster than other but are updated as often as slowly converging states.\r\n\t\\end{itemize}\r\n\t\\vspace{0.5cm}\\pause\r\n\t\\item In contrast, \\hl{asynchronous backups} update states individually in an (arbitrary) order:\r\n\t\\begin{itemize}\r\n\t\t\\item Choose smart order to achieve faster overall convergence rate.\r\n\t\t\\item Some states may be updated more frequently than others.\\pause\r\n\t\t\\item Overall algorithms converges if all states are still visited to some extent (\\hl{important requirement to ensure convergence}).\\pause\r\n\t\t\\item Simple example: in-place policy evaluation where only a subset of all states are updated each iterations (cf. \\algoref{algo:in_place_policy_update}).\r\n\t\\end{itemize}\r\n\\end{itemize}\r\n}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Asynchronous DP: Prioritized Sweeping %%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{Asynchronous DP: Prioritized Sweeping}\r\n\\begin{itemize}\r\n\t\\item Use magnitude of \\hl{Bellman error} as an indicator which state should be updated next:\r\n\t\\begin{equation}\r\n\t\t\\argmax_{x_k\\in\\mathcal{X}}\\left|\\max_{u_k\\in\\mathcal{U}} \\left(\\mathcal{R}^u_x + \\gamma \\sum_{x_{k+1}\\in\\mathcal{X}}p_{xx'}^u v_{i}(x_{k+1})\\right) - v_i(x_k)\\right|\\, .\r\n\t\\end{equation}\\pause\r\n\t\\item Update the state with the largest Bellman error first. \r\n\t\\item Build up a priority queue of most relevant states by refreshing the Bellman error after each state update.\r\n\\end{itemize}\r\n}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Asynchronous DP: Real-Time Updates %%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{Asynchronous DP: Real-Time Updates}\r\n\\begin{itemize}\r\n\t\\item Update those states which are frequently visited by the agent.\r\n\t\\item Utilizes agent's experience to guide the asynchronous DP updates.\r\n\t\\item After each time step $\\left\\langle x_k, u_k, r_{k+1}\\right\\rangle$ update $x_k$:\r\n\t\\begin{equation}\r\n\t\tv_i(x_k) \\leftarrow \\max_{u_k\\in\\mathcal{U}} \\left(\\mathcal{R}^u_{x} + \\gamma \\sum_{x_{k+1}\\in\\mathcal{X}}p_{xx'}^u v_{i}(x_{k+1})\\right).\r\n\t\\end{equation}\r\n\\end{itemize}\r\n\\begin{figure}\r\n\t\t\\includegraphics[width=5.5cm]{fig/lec03/RTDP.pdf}\r\n\t\t\\caption{Real-time DP updates focus on reachable states (source: R. Sutton and G. Barto, Reinforcement learning: an introduction, 2018, \\href{https://creativecommons.org/licenses/by-nc-nd/2.0/}{CC BY-NC-ND 2.0})}\r\n\t\t\\label{fig:RTDP}\r\n\\end{figure}\r\n}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Generalized Policy Iteration %%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{Generalized Policy Iteration (GPI)}\r\n\\begin{itemize}\r\n\t\\item Almost all RL methods are well-described as GPI.\r\n\t\\item \\hl{Push-pull}: Improving the policy will deteriorate value estimation.  \r\n\t\\item Well balanced \\hl{trade-off between evaluating and improving} is required.\r\n\\end{itemize}\r\n\\begin{figure}\r\n\t\\subfloat{\r\n\t\t\\includegraphics[height=4cm]{fig/lec03/GPI_01.pdf}\r\n\t}\r\n\t\\hspace{1cm}\r\n\t\\subfloat{\r\n\t\t\\includegraphics[height=4cm]{fig/lec03/GPI_02.pdf}\r\n\t}\r\n\\caption{Interpreting generalized policy iteration to switch back and forth between (arbitrary) evaluations and improvement steps (source: R. Sutton and G. Barto, Reinforcement learning: an introduction, 2018, \\href{https://creativecommons.org/licenses/by-nc-nd/2.0/}{CC BY-NC-ND 2.0})}\r\n\\end{figure}\r\n}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Curse of Dimensionality %%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{Curse of Dimensionality}\r\n\\begin{itemize}\r\n\t\\item DP is much more efficient than an exhaustive search over all $n$ states and $m$ actions in finite MDPs in order to find an optimal policy.\r\n\t\\begin{itemize}\r\n\t\t\\item Exhaustive search for deterministic policies: $m^n$ evaluations.\r\n\t\t\\item DP results in polynomial complexity regarding $m$ and $n$. \r\n\t\\end{itemize}\r\n\t\\pause\r\n\t\\item Nevertheless, DP uses full-width backups:\r\n\t\\begin{itemize}\r\n\t\t\\item For each state update, every successor state and action is considered.\r\n\t\t\\item While utilizing full knowledge of the MDP structure.\r\n\t\\end{itemize}\r\n\t\\pause\r\n\t\\item Hence, DP is can be effective up to medium-sized MDPs (i.e., million states)\\pause\r\n\t\\item For large problems DP suffers from the \\hl{curse of dimensionality}:\r\n\t\\begin{itemize}\r\n\t\t\\item Number of finite states $n$ grows exponentially with the number of state variables.\r\n\t\t\\item Also: if continuous variables need quantization typically a large number of states results. \r\n\t\t\\item Single state update may become computational infeasible. \r\n\t\\end{itemize}\r\n\\end{itemize}\r\n}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Summary %%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\begin{frame}\r\n\\frametitle{Summary: What You've Learned Today}\r\n\\begin{itemize}\r\n\t\\item DP is applicable for prediction and control problems in MDPs.\\pause\r\n\t\\item But requires always full knowledge about the environment (i.e., it is a model-based solution also called planning).\\pause\r\n\t\\item DP is more efficient than exhaustive search.\\pause\r\n\t\\item But suffers from the curse of dimensionality for large MDPs.\\pause\r\n\t\\item (Iterative) policy evaluations and (greedy) improvements solve MDPs.\\pause\r\n\t\\item Both steps can be combined via value iteration.\\pause\r\n\t\\item This idea of (generalized) policy iteration is a basic scheme of RL.\\pause\r\n\t\\item Implementing DP algorithms comes with many degrees of freedom.\r\n\t\\item For example how to order the state updates (asyn. vs. sync.).\r\n\\end{itemize}\r\n\\end{frame}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%% Final Slide %%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\frame{\\frametitle{The End for Today}\r\n\\begin{figure}\r\n\\includegraphics[width=10cm]{fig/lec03/dilbert.jpg}\r\n\\end{figure}\r\n\\vspace{1cm}\r\n\\centering\r\nThanks for your attention and have a nice week!\r\n}\r\n", "meta": {"hexsha": "8a5da46c4b689396ac17f5ce67c6afea90d197a9", "size": 39333, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "lecture_slides/tex/Lecture03.tex", "max_stars_repo_name": "adilsheraz/reinforcement_learning_course_materials", "max_stars_repo_head_hexsha": "e086ae7dcee2a0c1dbb329c2b25cf583c339c75a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 557, "max_stars_repo_stars_event_min_datetime": "2020-07-20T08:38:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T19:30:35.000Z", "max_issues_repo_path": "lecture_slides/tex/Lecture03.tex", "max_issues_repo_name": "speedhunter001/reinforcement_learning_course_materials", "max_issues_repo_head_hexsha": "09a211da5707ba61cd653ab9f2a899b08357d6a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-07-22T07:27:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-12T14:37:08.000Z", "max_forks_repo_path": "lecture_slides/tex/Lecture03.tex", "max_forks_repo_name": "speedhunter001/reinforcement_learning_course_materials", "max_forks_repo_head_hexsha": "09a211da5707ba61cd653ab9f2a899b08357d6a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 115, "max_forks_repo_forks_event_min_datetime": "2020-09-08T17:12:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:13:08.000Z", "avg_line_length": 47.1618705036, "max_line_length": 366, "alphanum_fraction": 0.5929880762, "num_tokens": 12177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3130867082017657}}
{"text": "\\documentclass[a4paper,12pt]{article} % declaration\n\\usepackage[utf8]{inputenc}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{amsfonts}\n\\usepackage{xcolor}\n\\usepackage{enumitem}\n\\usepackage{graphicx}\n\\usepackage{fancyhdr}\n\\usepackage{color}\n\\usepackage{amsthm}\n\\usepackage{CJKutf8}\n\n%\\def\\pgfsysdriver{pgfsys-dvipdfmx.def}\n\\usepackage{tikz}\n\n\\newtheorem{definition}{Definition}[section]\n\\newtheorem{example}{Example}[section]\n\\newtheorem{theorem}{Theorem}[section]\n\\newtheorem{proposition}{Proposition}[section]\n\\newtheorem{lemma}[theorem]{Lemma}\n\\newtheorem{corollary}[theorem]{Corollary}\n\n\\title{Introduction}\n\\author{Guoning Wu}\n\n\\begin{document}\n\\graphicspath{{../Figs/}}\n\n%\\tableofcontents\n\\setcounter{tocdepth}{2}\n\n%\\listoffigures\n%\\listoftables\n\n\\maketitle\n\n\\section{The Creation of the Calculus}\n\\begin{quote}\n    {\\color{red}Who, by a vigor of mind almost divine, the motions and figures \n    of the planets, the paths of comets, and the tides of seas first \n    demonstrated. -----Newton's Epitaph}\n\\end{quote}\n\\subsection{The Motivation for the Calculus}\nFollowing hard on the adoption of the function concept came the \ncalculus, which, next to Euclidean geometry, is the greatest \nin all of mathematics. Though it was to some extent the answer  \nto problems already tackled by the Greeks, the calculus was \ncreated primarily to treat the major scientific problems of the \nseventeenth century.\n\nThere were four major types of problems. The first was: Given \nthe formula for the distance a body covers as a function of time,\nto find the velocity and acceleration at any instant; and, \nconversely, given the formula describing the acceleration of a \nbody as a function of the time, to find the velocity and the \ndistance traveled. This problem arose directly in the study of motion and the difficulty it posed was that the velocities and the acceleration of concern to the seventeenth century varied from instant to instant. In calculating an instantaneous velocity, for example, one cannot, as one can in the case of average velocity, divide the distance traveled by the time of travel, because at a given instant both the distance traveled and time are zero, and $0/0$ is meaningless. Nevertheless, it was clear on physical grounds that moving objects do have a velocity at each instant of their travel. The inverse problem of finding the distance covered, knowing the formula for velocity, involves the corresponding difficulty; one cannot multiply the velocity at any one instant by the time of travel to obtain the distance traveled because the velocity varies from instant to instant.\n\nThe second type of problem was to find the tangent to a curve.\nIt was a problem of pure geometry, and it was of great importance \nfor scientific applications. Optics, as we know, was one of the major scientific pursuits of the seventeenth century; the design of lenses was direct interest for Fermat, Descartes, Huygens, and Newton.\n\nThe third problem was that of finding the maximum or minimum \nvalue of a function. When a cannonball is shot from a cannon, the distance it will travel horizontally-the range-depends on the angle at which the cannon is inclined to the ground. One \"practical\" problem was to find the angle that would maximize the range. Early in the seventeenth century, Galileo determined that(in a vacuum) the maximum range is obtained for an angle of fire of 45 degree. The study of the motion of the planets \ninvolved maxima and minima problems, such as finding the \ngreatest and least distances of a planet from the sun.\n\nThe fourth problem was finding the lengths of curves, for \nexample, the distance covered by a planet in a given period \nof time; the area bounded by curves; volumes bounded by \nsurfaces; centers of gravity of bodies; and the gravitational \nattraction that extended body, a planet for example, exerts on \nanother body. The Greeks had used the method of exhaustion to find some areas and volumes. Despite the fact that they used it for relatively simple areas and volumes, they had to apply much ingenuity, because the method lack generality. Nor did they often come up with numerical answers. Interest in finding lengths, areas, volumes, and centers of gravity was revived when the work of Archimedes became known in Europe. The method of exhaustion was first modified gradually, and then radically by the invention of the calculus.\n\n\\subsection{Early Seventeenth-Century Work on the Calculus}\n\nThe problems of the calculus were tackled by at least a dozen \nof the greatest mathematicians of the seventeenth century and \nby several dozen minor ones. All of their contributions were \ncrowned by the achievements of Newton and Leibniz. Here we shall \nbe able to note only the principle contributions of the precursors \nof these two masters.\n\nSeveral methods were advanced to find the tangent to a curve.\nGilles Persone de Roberval(1602-75) generalized a method Archimedes \nhad used to find the tangent at any point on his spiral, which \nthe tangent line of a projectile shot from a canon is the resultant \ndiagonal line of the vertical and horizontal velocities.\n\nWhile the notion of a tangent as a line having the direction of the \nresultant velocity was more complicated than the Greek definition \nof a line touching a curve, this newer concept applied to many \ncurves for which the older one failed.\n\n\n\\section{Sets and Elementary Operations on them}\n\nIn this note, we introduce some basic concepts for real \nanalysis.\n\n\\subsection{The Concept of a Set}\nSince the late nineteenth and early twentieth centuries \nthe most universal language of mathematics has been the \nlanguage of set theory. This is even manifest in one of \nthe definitions of mathematics as the science that \nstudies different structures (relations) on sets.\n\n\\emph{\"We take a set to be an assemblage of definite, \nperfectly distinguishable objects of our intuition or \nour thought into a coherent whole.\"} Thus did Georg \nCantor\\footnote{G.Cantor(1845-1918) - German \nmathematician, the creator of the theory of infinite \nsets and the progenitor of set theoretic language in \nmathematics.}, describe the concept of a set.\n\n\\begin{itemize}\n    \\item A set may be consist of any distinguishable \n        objects.\n    \\item A set is unambiguously determined by the \n        collection of objects that comprise it.\n    \\item Any property defines the set of objects \n        having that property.\n\\end{itemize}\n\nIf $x$ is an object, $P$ is a property, and $P(x)$ \ndenotes the assertion that $x$ has property $P$, \nthen the class of objects having the property\n$P$ is denoted $\\{x\\lvert P(x)\\}$\n\nAnd in fact the concept of the set of all sets, for \nexample, is simply contradictory. This is the \nclassical paradox of \\textbf{Russell}. \\footnote{B.Russell (1872-1970) - British logician,\nphilosopher, sociologist ans social activist.}\n\n\\subsection{The Inclusion Relation}\nThe statement, \"$x$ is an element of the set $X$\" is written \nbriefly as\n\\[ \n    x\\in X\n\\]\nand its negation as\n\\[\n    x \\notin X\n\\]\n\nWhen statements about sets are written, frequent use is \nmade of the logical operators $\\exists$ (\"there exists\" or \"there\nare\") and $\\forall$ (\"every\" or \"for all\") which are called the\n\\emph{existence} and \\emph{generalization} respectively.\n\nThus two sets are equal if they consist of the same \nelements, this statement is usually written briefly as \n\\[\n    A=B,\n\\]\nread as \"$A$ equals $B$\". The negation of equality is usually \nwritten as \n\\[\n    A \\ne B.\n\\]\nIf every element of $A$ is an element of $B$, we write\n$A\\subset B$ and say that $A$ is a subset of \n$B$ or that $B$ contains $A$.\n\nThus \n\\[\n    A\\subset B := \\forall x\\in A \\Rightarrow x\\in B\n\\]\nIf $A\\subset B$ and $A\\ne B$, we shall say that the inclusion $A\\subset B$ is \n\\emph{strict} or that $A$ is a proper subset of $B$.\n\nUsing these definitions, we can now conclude that\n\\[A=B \\Leftrightarrow A\\subset B \\wedge B\\subset A\\]\nIf $M$ is a set, any property of $P$ distinguishes in M the subset\n\\[\\{x\\in M \\vert P(x)\\}\\]\nconsisting of the elements of $M$ that have the property.\n\nFor example, it is obvious that \n\\[ M=\\{x\\in M \\vert x\\in M\\},\\]\nand the \\emph{empty} subset of $M$ is \n\\[\\emptyset = \\{x\\in M \\vert x\\ne x\\}\\]\n\n\\subsection{Elementary Operations on Sets}\n\\begin{figure}[htbp]\n    \\centering\n    \\begin{tikzpicture}[scale=0.75]\n    \\draw  (0,0) rectangle  (4,3);\n        \\node [below,black] at (2, 0) {(a)};\n    \\draw (2.5,1.5) circle (1);\n    \\draw (1.5,1.5) circle (1);\n    \\node [above left,green] at (1.5, 1.5) {$A$};\n    \\node [above right,blue] at (2.5, 1.5) {$B$};\n    \\clip (1.5,1.5) circle (1);\n    \\clip (2.5,1.5) circle (1);\n    \\draw [fill, blue!100] (0, 0) rectangle (4, 3);\n    \\node [black] at (2, 1.5) {$ A\\cap B$};\n\\end{tikzpicture}\n    \\begin{tikzpicture}[scale=0.75]\n    \\draw  (0,0) rectangle  (4,3);\n        \\node [below,black] at (2, 0) {(b)};\n    \\draw [fill=green](2.5,1.5) circle (1);\n    \\draw [fill=green] (1.5,1.5) circle (1);\n    \\node [above left,black] at (1.5, 1.5) {$A$};\n    \\node [above right,black] at (2.5, 1.5) {$B$};\n    \\clip (1.5,1.5) circle (1);\n    \\clip (2.5,1.5) circle (1);\n    \\draw [fill, green] (0, 0) rectangle (4, 3);\n\\end{tikzpicture}\n    \\begin{tikzpicture}[scale=0.75]\n    \\draw  (0,0) rectangle  (4,3);\n        \\node [below,black] at (2, 0) {(c)};\n    \\draw [fill=red](1.5,1.5) circle (1);\n    \\draw (2.5,1.5) circle (1);\n    \\node [above left,black] at (1.5, 1.5) {$A$};\n    \\clip (0,0) rectangle  (4,3);\n    \\clip (2.5,1.5) circle (1);\n    \\draw [fill,black!0] (0, 0) rectangle (4, 3);\n    \\node [above right,black] at (2.5, 1.5) {$B$};\n\\end{tikzpicture}\n    \\begin{tikzpicture}[scale=0.75]\n    \\draw [fill=yellow] (0,0) rectangle  (4,3);\n        \\node [below,black] at (2, 0) {(d)};\n    \\draw (1.5,1.5) circle (1);\n    \\clip (1.5,1.5) circle (1);\n    \\draw [fill,yellow!0] (0, 0) rectangle (4,3);\n    \\node [above left,black] at (1.5, 1.5) {$A$};\n\\end{tikzpicture}\n\\label{sets}\n    \\caption{(a) Intersection. (b) Union. (c) Difference. (d) Complement. }\n\\end{figure}\n\nLet $A$ and $B$ be subsets of a set $M$.\n\\begin{enumerate}[label={\\rm (\\alph*)}]\n    \\item The {\\color{red}\\textbf{union}} of $A$ and $B$ is the set \n        $\\displaystyle A \\cup B \\triangleq \\left\\{ x \\in M \\vert x \\in A \\vee x \\in B \\right\\}$\n    \\item The {\\color{red}\\textbf{intersection}} of $A$ and $B$ is the set \n        $\\displaystyle A \\cap B \\triangleq \\left\\{ x \\in M \\wedge x \\in A \\vee x \\in B \\right\\}$\n    \\item The {\\color{red}\\textbf{difference}} of $A$ and $B$ is the set \n        $\\displaystyle A \\setminus B \\triangleq \\left\\{ x \\in M \\vert x \\in A \\vee x \\notin B \\right\\}$\n    \\item The {\\color{red}\\textbf{direct(Cartesian) product of sets.}}\n        For any two sets $A$ and $B$ one can form a new set, namely \n        the pair $\\left\\{A, B\\right\\} = \\left\\{B, A\\right\\}$, which consists of the sets \n        $A$ and $B$ and no others.This set has two elements if $A \\ne B$ and \n        one element if $A = B.$\n        This set is called the unordered pair of sets $A$ and $B$, to \n        be distinguished from the ordered pair $(A, B)$ in which \n        the elements are endowed with additional properties to \n        distinguish the first and the second elements of the pair \n        $\\left\\{A, B\\right\\}$. The equality \n        \\[\n            (A, B) = (C, D)\n            \\]\n        between two ordered pairs means by definition that $A = C$ \n        and $B = D$. In particular, if $A \\ne B$, then $(A, B) \\ne (B, A)$.\n\n        Now let $X$ and $Y$ be arbitrary sets. The set \n        \\[\n            X \\times Y \\triangleq \\left\\{(x, y) \\vert (x \\in X) \\wedge (y \\in Y) \\right\\}\n            \\]\n        formed by the ordered pairs $(x, y)$ whose first element belongs \n        to $X$ and whose second element belongs to $Y$, is called the \n        {\\color{red} Cartesian product} of the set $X$  and $Y$.\n\\end{enumerate}\n\n\\section{Functions}\n\\subsection{The Concept of a Function (Mapping)}\nThe term \\textit{function} first appeared in the years from 1673 to 1692 in\nworks of G.Leibniz. By the year 1698 the term had become established\nin a sense close to the modern one through the correspondence \nbetween Leibniz and Johann Bernoulli.\n\\footnote{Johann Bernoulli (1667-1748) - one of the early representatives\nof the distinguished Bernoulli family of Swiss scholars, he studied \nanalysis, geometry and mechanics. He was one of the founders of the \ncalculus of variations. He gave the first systematic exposition of \nthe differential and integral calculus.}\n\nLet $X$ and $Y$ be certain sets. We say that there is a function defined \non $X$ with values in $Y$ if, by virtue of some rule $f$, to each element \n$x \\in X$ there corresponds an element $y \\in Y$. In this case the set $X$\nis called the {\\color{red} \\textbf{domain}} of the function.\nThe symbol $x$ used to denote a general element of the domain is \ncalled the argument of the function. The element $y_0 \\in Y$ corresponding \nto a particular value $x_0 \\in X$ is called the value of the function \nat $x_0$, and is denoted as $f(x_0)$. As the argument $x \\in X$ varies, the value\n$y = f(x) \\in Y$, in general, varies depending on the values of $x$.\nFor that reason, the quality $y = f(x)$ is often called the dependent \nvariable.\n\nThe set \n\\[\n    f(X) = \\left\\{y \\in Y \\vert \\exists x, x \\in X \\wedge y = f(x) \\right\\}\n\\]\nof values assumed by a function on elements of the set $X$ will \nbe called the set of values or the range of the function.\n\nFor a function the following notations are standard:\n\\[\n    f: X \\to Y,  X \\xrightarrow{f} Y\n    \\]\n\nTwo functions (mapping) $f_1$ and $f_2$ are identical or equal \nif the have the same domain $X$ and each element $x \\in X$ the values \n$f_1(x)$ and $f_2(x)$ are the same. In this case we write $f_1 = f_2$.\n\n\\begin{example}\n    The formulas $l = 2\\pi r$ and $V = \\frac{4}{3}\\pi r^3$ establish \n    functional relationships between the circumference $l$\n    of a circle and its radius $r$ and between the volume $V$\n    of a ball and its radius $r$. Each of these formulas provides \n    a particular function $f: \\mathbb{R}_+ \\to \\mathbb{R}_+$\n    defined on the set $\\mathbb{R}_+$ of the positive real numbers \n    with values in the same set.\n\\end{example}\n\n\\begin{example}\n    The mapping $G: \\mathbb{R}^2 \\rightarrow \\mathbb{R}^2$ (the direct product \n    $\\displaystyle \\mathbb{R}^2 = \\mathbb{R} \\times mathbb{R} = \\mathbb{R}_t \n    \\times \\mathbb{R}_x$) into itself defined by the foumulas:\n    \\[\n    \\begin{array}{ll}\n        x' & = x - vt \\\\\n        t' & = t\n    \\end{array}\n    \\]\n   is the classical Galilean transformation for transition from \n    one inertial coordinate system $(x,t)$ to another system $(x', t')$\n    that is in motion relative to the first speed $v$.\n\n    The same purpose is served by the mapping $L: \\mathbb{R}^2 \n    \\to \\mathbb{R}^2$ defined by the relations:\n    \\[\n    \\begin{array}{ll}\n        x' = \\frac{x - vt}{\\sqrt{1 - \\left(\\frac{v}{c}\\right)^2}},\\\\\n        t' = \\frac{t - \\frac{v}{c^2}x}{\\sqrt{1-\\left(\\frac{v}{c}\\right)^2}}\n     \\end{array}\n     \\]\n     is the well known (one-dimensional) Lorentz transformation,\n     which play a fundamental role in the special theory of\n     relativity. The speed $c$ is the speed of light.\n\\end{example}\n\n\\begin{example}\n    The projection $pr_1: X_1 \\times X_2 \\to X_1$ and $pr_2: X_1 \\times X_2 \\to X_2$\n    are obvious functions.\n\\end{example}\n\n\\subsection{Elementary Classification of Mapping}\nA mapping $f: X \\to Y$ is said to be \n\n{\\color{red} surjective} if $f(X) = Y$;\n\n{\\color{red} injective} if for any elements $x_1, x_2 \\in X$\n\\[\n    f(x_1) = f(x_2) \\Rightarrow x_1 = x_2\n    \\]\n\n{\\color{red} bijective} if it is both surjective and injective.\n\n\\subsection{Some Special Functions}\n\\begin{example}{The absolute value function}\n    \\[\n        \\left|x\\right| = \\left\\{ \\begin{array} {cc}\n                          x, & x \\ge 0 \\\\\n                         -x, & x < 0\n        \\end{array}\\right.\n        \\]\n\\end{example}\n\n\\begin{figure}[h!]\n    \\centering\n    \\includegraphics[width=0.5\\textwidth]{absolutefun.png}\n    \\caption{The absolute function.}\n    \\label{fig:absolutefun}\n\\end{figure}\n\n\\begin{example}{The Greatest Integer Function}\n    This function whose value at any number $x$ is the greatest \n    integer less than or equal to $x$ is called the greatest \n    integer function or the integer floor function. It is \n    denoted as $\\lfloor x \\rfloor$\n\\end{example}\n\\begin{figure}[h!]\n    \\centering\n    \\includegraphics[width=0.5\\textwidth]{gintfun.png}\n    \\caption{The greatest integer function.}\n    \\label{fig:gintfun}\n\\end{figure}\n\n\\begin{example}{The Least Integer Function}\n    This function whose value at any number $x$ is the smallest \n    integer great than or equal to $x$ is called the leastest \n    integer function or the integer ceiling function. It is \n    denoted as $\\lceil x \\rceil$\n\\end{example}\n\\begin{figure}[h!]\n    \\centering\n    \\includegraphics[width=0.5\\textwidth]{lintfun.png}\n    \\caption{The least integer function.}\n    \\label{fig:lintfun}\n\\end{figure}\n\n\\begin{example}{The Sign Function or Signum Function}\n    The signum function of a real number $x$ is defined as \n    follows:\n    \\[\n        \\rm{sgn} (x) = \\left\\{\\begin{array}{cc} \n                   -1,  & x < 0\\\\\n                    0,  & x = 0\\\\\n                    1,  & x = 1\n        \\end{array}\\right.\n        \\]\n\\end{example}\n\n\\begin{figure}[h!]\n    \\centering\n    \\includegraphics[width=0.5\\textwidth]{signumfun.png}\n    \\caption{The singnum function.}\n    \\label{fig:singnum}\n\\end{figure}\n\n\\begin{example}{The Dirichlet Function}\n    \\[\n        \\rm D(x) = \\left\\{\\begin{array}{cc} \n            1, & x \\in \\mathbb{Q},\\\\\n            0, & x \\in \\mathbb{R} \\setminus \\mathbb{Q}\n        \\end{array}\\right.\n        \\]\n\\end{example}\n\n\\begin{example}{The Riemann Function}\n    \\[\n        \\rm R(x) = \\left\\{ \\begin{array}{cc} \n            \\frac{1}{q}, & x = \\frac{p}{q}, p, q \\in \\mathbb{Z}^+, (p, q) = 1\\\\\n                   0,    & x = 0, 1, (0,1) \\setminus \\mathbb{Q}\n        \\end{array}\\right.\n        \\]\n\\end{example}\n\\begin{figure}[h!]\n    \\centering\n    \\includegraphics[width=0.5\\textwidth]{rimannfun.pdf}\n    \\caption{The Rimann function.}\n    \\label{fig:rimann}\n\\end{figure}\n\n\n\n\n\\section{The Real Numbers}\nIn mathematics, a real number is a value of a continuous quantity \nthat can represent a distance along a line. The adjective \\textbf{real}\nin this context was introduced in the 17th century by Rene \\textbf{Descartes},\nwho distinguished between real and imaginary roots of polynomials.\n\nThe discovery of a suitable rigorous definition of the real numbers,\nindeed, was one of the most important developments of 19th-century \nmathematics. The current standard axiomatic definition is that \nreal numbers forms the unique Dedkind-complete ordered field, up to \nan isomorphism, whereas popular constructive definitions of \nreal numbers include declaring them as equivalence classes of \nCauchy sequences of rational numbers, Dedekind cuts, \nor infinite decimal representations, together with precise \ninterpretations for the arithmetic operations and the order \nrelation. All these definitions satisfy the axiomatic \ndefinition and thus equivalent.\n\n\\subsection{The Definition of Real Numbers}\nThe real number system $\\mathbb{R}$, can be defined axiomatically \nup to isomorphism, which is described hereafter. There are also \nmany ways to construct the real number system, for example, starting\nfrom natural numbers, then defining rational numbers algebraically,\nand finally defining real numbers as equivalence classes of their \nCauchy sequences or as Dedekind cuts, which are certain subsets \nof rational numbers. Another possibility is to start from some \nrigorous axiomatization of Euclidean geometry and then define \nthe real number system geometrically. All these constructions \nare on equal footing.\n\n\\subsection{The Axiom System and some General Properties of the \nSet of Real Numbers}\n\\begin{definition} {A set $\\mathbb{R}$ is called the set of \\textit{real numbers}\nand its elements are \\textit{real numbers} if the following list of conditions\nholds, called the axiom system of the real numbers.}\n\\end{definition}\n\n\\begin{center}\n    (I) AXIOMS FOR ADDITION\n\\end{center}\nAn operation \n\\[+:\\mathbb{R}\\times\\mathbb{R} \\to \\mathbb{R}\\]\nis defined, assigning to each ordered pair $(x,y)$ of elements \n$x,y$ of $\\mathbb{R}$ a certain element $x+y\\in\\mathbb{R}$, called \nthe sum of $x$ and $y$. The operation satisfies the following \nconditions:\n\\begin{enumerate}\n    \\item There exists a neutral, or identity element 0 \n        (called zero) such that \n    \\[x+0=0+x=x\\]\n    for every $x\\in\\mathbb{R}$.\n    \\item For every element $x\\in \\mathbb{R}$ there exists an element \n    $-x\\in\\mathbb{R}$ called the negative of $x$ such that\n        \\[x+(-x)=(-x)+x=0\\].\n    \\item The operation is associative, that is, the relation\n        \\[x+(y+z) = (x+y)+z\\] for any elements of $x,y,z$ of $\\mathbb{R}$.\n    \\item The operation is commutative, that is \n        \\[x+y=y+x\\] for any elements $x,y$ of $\\mathbb{R}$.\n\\end{enumerate}\n\nIf an operation is defined on a set $G$ satisfying axiom 1, 2 and 3, we\nsay that a group structure is defined on $G$ or that $G$ is a group. \nIf the operation is called addition, the group is called an additive \ngroup. If it is also known that the operation is commutative, that is, \ncondition 4 holds, the group is called commutative or \\textit{Abelian} is a group. \nIf the operation is called addition, the group is called an additive \ngroup. If it is also known that the operation is commutative, that is, \ncondition 4 holds, the group is called commutative or \\textit{Abelian}.\n\n\\begin{center}\n    (II) AXIOMS FOR MULTIPLICATION\n\\end{center}\nAn operation \\[\\bullet:\\mathbb{R}\\times\\mathbb{R}\\to\\mathbb{R}\\]\n(the operation of multiplication) is defined, assigning to \neach ordered pair $(x,y)$ of elements of $\\mathbb{R}$ a certain\nelement $x\\cdot y\\in \\mathbb{R}$, called the product of $x$ and \n$y$. This operation satisfies the following conditions:\n\\begin{enumerate}\n    \\item There exists a neutral, or identity element \n        $1\\in \\mathbb{R}\\setminus 0$ (called one) such that \n        \\[x\\cdot 1 = 1\\cdot x=x\\] for every $x\\in \\mathbb{R}$\n    \\item For every element $x\\in\\mathbb{R}\\setminus 0 $ \n        there exists an element $x^{-1}\\in \\mathbb{R}$ ,\n        called the inverse or reciprocal of $x$, such that\n        \\[x\\cdot x^{-1}=x^{-1}\\cdot x=1\\]\n    \\item The operation $\\bullet$ is commutative, that is \n        \\[x\\cdot(y\\cdot z) = (x\\cdot y)\\cdot z\\] holds \n        for every elements $x,y,z$ of $\\mathbb{R}$.\n    \\item The operation $\\bullet$ is commutative, that is \n        \\[ x\\cdot y = y\\cdot x\\] for every elements $x,y$ of $\\mathbb{R}$.\n\\end{enumerate}\n\n\\begin{center}\n    (I, II) THE CONNECTION BETWEEN ADDITION AND MULTIPLICATION\n\\end{center}\nMultiplication is distributive with respect to addition, that\nis \\[(x+y)z = xz+yz\\] for all $x,y,z\\in \\mathbb{R}$\n\nWe remark that if two operations satisfies these axioms \nare defined on a set $G$, then $G$ is called a field.\n\n\\begin{center}\n    (III) ORDER AXIOMS\n\\end{center}\nBetween elements of $\\mathbb{R}$ there is a relation $\\le$,\nthat is, for elements $x,y\\in\\mathbb{R}$ one can determine \nwhether $x\\le y$ or not. Here the following conditions must \nhold:\n\\begin{enumerate}\n    \\item $\\forall x\\in \\mathbb{R}(x\\le x)$\n    \\item $(x\\le y)\\wedge (y\\le x) \\Rightarrow (x=y)$\n    \\item $(x\\le y) \\wedge(y\\le z) \\Rightarrow (x\\le z)$\n    \\item $\\forall x\\in \\mathbb{R} ,\\forall y\\in \\mathbb{R} (x\\le y) \\vee (y\\le x)$\n\\end{enumerate}\n\n\\begin{center}\n    (I, III) THE CONNECTION BETWEEN ADDITION AND ORDER ON $\\mathbb{R}$\n\\end{center}\nIf $x,y,z$ are elements of $\\mathbb{R}$, then \n\\[(x\\le y) \\Rightarrow (x+z) \\le (y+z)\\]\n\n\\begin{center}\n    (II, III) THE CONNECTION BETWEEN MULTIPLICATION AND \n    ORDER ON $\\mathbb{R}$\n\\end{center}\nIf $x$ and $y$ are elements of $\\mathbb{R}$, then\n\\[(0\\le x)\\wedge(0\\le y) \\Rightarrow (0\\le x\\cdot y)\\]\n\n\\begin{center}\n    (IV) THE AXIOM OF COMPLETENESS (CONTINUITY)\n\\end{center}\nIf $X$ and $Y$ are nonempty subsets of $\\mathbb{R}$ having \nthe property that $x\\le y$ for every $x\\in X$ and every $y\\in Y$,\nthen there exists $c\\in\\mathbb{R}$ such that $x\\le c \\le y$  for \nall $x\\in X$ and $y\\in Y$.\n\nWe now have a complete list of axioms such that any set on \nwhich those axioms hold can be considered a concrete \nrealization or model of the real numbers.\n\nIn relation to any abstract system of axioms, at least two questions\narise immediately.\nFist, are these axioms consistent? That is, does there exists a set \nsatisfying all the conditions just listed? This is the problem of \nconsistency of the axioms.\nSecond, does the given system of axiom determine the mathematical \nobject uniquely?  Here the uniqueness must be understood as follows.\nIf two people A and B construct models independently, say of number \nsystems $\\mathbb{R}_A$ and $\\mathbb{R}_B$, satisfying the axioms, then a \nbijective correspondence can be established between the system \n$\\mathbb{R}_A$ and $\\mathbb{R}_B$, say $\\displaystyle f: \\mathbb{R}_A \\to \n\\mathbb{R}_B$, preserving the arithmetic operations and the order, that \nis \n\\begin{enumerate}\n    \\item $\\displaystyle f(x+y) = f(x) + f(y)$\n    \\item $\\displaystyle f(x \\cdot y) = f(x)\\cdot f(y)$ \n    \\item $\\displaystyle x \\le y \\iff f(x) \\le f(y)$ \n\\end{enumerate}\n\n\\subsection{Dedekind Cut}\nA Dedekind cut is a pair $\\displaystyle (A, B)$, where $A$\nand $B$ are both subsets of rationals. This pair has to satisfy \nthe following properties:\n\\begin{enumerate}[label={\\rm(\\arabic*)}]\n    \\item $A$ is nonempty.\n    \\item $B$ is nonempty.\n    \\item If $a \\in A$ and $c < a$ then $c \\in A$.\n    \\item If $b \\in B$ and $c > b$ then $c \\in B$.\n    \\item If $b \\notin B$ and $a < b$ then $a \\in A$.\n    \\item If $a \\notin A$ and $b > a$ then $b \\in B$.\n    \\item For each $a \\in A$ there is some $b > a$ so that $b \\in A$.\n    \\item For each $b \\in B$ there is some $a < b$ so that $a \\in B$.\n\\end{enumerate}\nThat's the definition. A real number is defined to be a Dedekind cut.\n\n\\subsection{The Most Important Classes of Real Numbers}\n\\subsubsection{The Natural Numbers and the Principle of Mathematical \nInduction}\n\\begin{definition} \n    The numbers of the form $1,1+1,(1+1)+1,$ and so forth are denoted \n    respectively by $1,2,3,\\cdots$ and so forth and are called natural\n    numbers.\n\\end{definition}\n\\begin{definition}\n    A set $X\\subset\\mathbb{R}$ is inductive if for each number $x\\in X$, \n    it also contains $x+1$.\n\\end{definition}\nThe intersection $\\displaystyle X=\\bigcap_{\\alpha \\in A} X_{\\alpha}$\n, if not empty, is an inductive set. \n\n\\subsubsection{Rational and Irrational Numbers}\n\\paragraph{a. The Integers}\n\\begin{definition}\n    The union of the set of natural numbers, the set of negatives of \n    natural numbers, and zero is called the set of \\textit{integers}\n    and is denoted $\\mathbb{Z}$.\n\\end{definition}\n\nThe set $\\mathbb{Z}$  is an Abelian group with respective to addition.\nWith respective to Multiplication $Z$ is not a group, nor is $Z\\setminus 0$, \nsince the reciprocals of the integers are not in $\\mathbb{Z} $(except \nthe reciprocal of 1 and -1).\n\nWhen $k=m\\cdot n^{-1}\\in\\mathbb{Z}$ for two integers $m,n\\in\\mathbb{Z}$ ,\nthat is, when $m=k\\cdot n$ for some $k\\in \\mathbb{Z} $, we say that \n$m$ is divisible by $n$ or a multiple of $n$, or that $n$ is a divisor \nof $m$.\n\nA number $p\\in \\mathbb{N},p\\ne 1,$ is prime if it has no divisors in \n$\\mathbb{N} $except 1 and $p$.\n\n\\paragraph{The fundamental theorem of arithmetic.} Each natural number \nadmits a representation as a product \n\\[n=p_1\\cdots p_k\\]\nwhere $p_1,\\cdots,p_k$ are prime numbers. This representation is unique\nexcept for the order of the factors.\n\nNumbers $m,n\\in \\mathbb{Z}$ are said to be relatively prime if they \nhave no common divisor except 1 and -1.\n\nIt follows in particular from this theorem that if the product $m\\cdot n$\nof relatively prime numbers $m$ and $n$ is divisible by a prime $p$ ,\nthen one of the two numbers is also divisible by $p$.\n\n\\paragraph{b. The Rational Numbers}\n\\begin{definition}\n    Numbers of the form $m\\cdot n^{-1}$, where $m,n\\in \\mathbb{Z}$, are called \n    rational.\n\\end{definition}\n\nWe denotes the set of rational numbers by $\\mathbb{Q}$.\n\nThe number $q=m\\cdot n^{-1}$ can also be written as a quotient \n\\footnote{The notation $\\mathbb{Q}$ from the first letter of the English \nword quotient, which in turn comes from the Latin \\textit{quota}, meaning \nthe unit part of something, and \\textit{quot}, meaning how many.} \nof $m$ and $n$, that is, as a so-called rational fraction $\\displaystyle \\frac{m}{n}.$\n\\paragraph{c. The Irrational Numbers}\n\\begin{definition}\n    The real numbers that are not rational are called irrational.\n\\end{definition}\n\nThe classical example of an Irrational real number is $\\sqrt{2}$\n\nWe shall soon see that in a certain sense nearly all real numbers \nare irrational. It will be shown that the cardinality of the set \nof the Irrational numbers is larger than that of the cardinality \nof the set of rational numbers and thus in fact the former equals\nthe cardinality of the set of real numbers.\n\nA real number is called \\textit{algebraic} if it is the root of an algebraic \nequation \\[a_0 x^n+\\cdots a_{n-1}x+a_0=0\\]\nwith rational (or equivalently, integer) coefficients. Otherwise the \nreal number is called \\textit{transcendental}.\n\n\\subsection{Basic Lemmas Connected with the Completeness of the Real Numbers}\nIn this section we shall establish some simple useful principles, each of \nwhich could have been used as the axiom of completeness in our construction\nof the real numbers.\n\n\\subsubsection{The nested Interval Lemma (Cauchy-Cantor Principle)}\n\\begin{definition}\n    A function $f:\\mathbb{N}\\to X$ of a natural-number argument is called\n    a sequence or, more fully, a sequence of elements of $X$.\n\\end{definition}\n\nThe value $f(n)$ of the function $f$ corresponding to the number \n$n\\in\\mathbb{N}$ is often denoted $x_n$ and called the $n$th term of \nthe sequence.\n\n\\begin{definition}\n    Let $X_1,X_2,\\cdots,X_n,\\cdots$ be a sequence of sets. If $X_1\\supset X_2\\supset \n    \\cdots\\supset X_n \\supset \\cdots,$ that is $X_n \\supset X_{n+1}$ for all $n\\in \\mathbb{N}$\n    , we say the sequence is nested.\n\\end{definition}\n\n\\begin{lemma}{Cauchy-Cantor.}\n    For any nested sequence $I_1 \\supset I_2 \\supset \\cdots \\supset I_n  \\supset \\cdots$\n    of closed intervals, there exists a point $c\\in \\mathbb{R}$\n    belonging to all these intervals.\n\n    If in addition it is known that for any $\\epsilon >0  $\n    there is an interval $I_k$ whose length $|I_k|$\n    is less than $\\epsilon$, then $c$ is the unique point common to all\n    the intervals.\n\\end{lemma}\n\n\\subsubsection{The Finite Covering Lemma (Borel-Lebesge Principle,\nor Heine-Borel Theorem)}\n\\begin{definition}\n    A system $S=\\{X\\}$ of sets $X$ is said to cover a set $Y$ if \n    $\\displaystyle Y \\subset \\bigcup_{X \\in S} X$, (that is, if every element \n    $y\\in Y$ belongs to at least one of the sets $X$ in the system $S$).\n\\end{definition}\n\nA subset of a set $S = \\{X\\}$ that is a system of sets will be called \na \\textit{subsystem} of $S$. Thus a subsystem of a system of sets is itself a\nsystem of sets of the same type.\n\n\\begin{lemma}{\\rm (Borel-Lebesge)}. \\footnote{$\\Acute{E}$.Borel \n    (1871-1956) and H.Lebesgue (1875-1941) well known French \n    mathematicians who worked in the theory of functions.}\n     Every system of open intervals covering a closed interval \n     contains a finite subsystem that covers the closed interval.\n\\end{lemma}\n\n\\subsubsection{The Limit Point Lemma (Bolzano-Weierstras Principle)}\n\\begin{definition}\n    A point $p\\in \\mathbb{R}$ is a \\textit{limit point} of the set $X \\subset \\mathbb{R} $\n    if every neighborhood of the point contains an infinite subset of $X$.\n\\end{definition}\n\n    This condition is obviously equivalent to the assertion that \n    every neighborhood of $p$ contains at least one point of $X$ different from \n    $p$ itself.\n\n\\begin{lemma}\n    Every bounded infinite set of real numbers has at least one limit point.\n\\end{lemma}\n\n\\subsubsection{The supremum and infimum}\nWe review the definition of the supremum and infimum and \nsome of their properties.\n\n\\begin{definition}\n    A set $A \\subset \\mathbb{R}$ of real numbers is bounded from \n    above if there exists a real number $M \\in \\mathbb{R}$, \n    called an upper bound of $A$, such that $x \\le M$ for \n    every $x \\in A$. Similarly, $A$ is bounded from below if \n    there exists $m \\in \\mathbb{R}$, called a lower bound of \n    $A$, such that $x \\ge m$ for every $x \\in A$. A set is bounded \n    if it is bounded both from above and below.\n\\end{definition}\n\n\\begin{definition}\n    Suppose that $A \\subset \\mathbb{R}$ is a set of real numbers. If\n    $M \\in \\mathbb{R}$ is an upper bound of $A$ such that $M \\le M'$ for \n    every upper bound $M'$ of $A$, then $M$ is called the supremum of \n    $A$, denoted $M = \\sup A$. If $m \\in \\mathbb{R}$ is a lower bound \n    of $A$ such that $m \\ge m'$ for every lower bound $m'$ of $A$, then \n    $m$ is called the infimum of $A$, denoted $m = \\inf A$.\n\\end{definition}\n\nIf $A$ is not bounded from above, then we write $\\sup A = \\infty$, \nand if $A$ is not bounded from below, we write $\\inf A = -\\infty$.\n\n\\begin{proposition}\n    The supremum or infimum of a set $A$ is unique if it exists.\n    Moreover, if both exist, then $\\inf A \\le \\sup A$.\n\\end{proposition}\n\n\\begin{proposition}\n    If $A \\subset \\mathbb{R}$, then $M = \\sup A$ if and only if \n    (a) $M$ is an upper bound of $A$; (b) for every $M' < M$,\n    then exists $x \\in A$ such that $x > M'$ . Similarly, \n    $m = \\inf A$ if and only if: (a) $m$ is a lower bound of $A$;\n    (b) for every $m' > m$ there exists $x \\in A$ such that $x < m'$.\n\\end{proposition}\n\n\\begin{theorem}\n    Every non-empty set of real numbers that is bounded from\n    above has a supremum, and every non-empty set of real \n    numbers that is bounded from below has an infimum.\n\\end{theorem}\n\\subsection{Countable and Uncountable Sets}\n\\subsubsection{Countable Sets}\n\\begin{definition}\n    A set $X$ is countable if it is equivalent with the set $\\mathbb{N}$ \n    of natural numbers, that is, ${\\rm card} X = {\\rm card}\\mathbb{N} $.\n\\end{definition}\n\n\\begin{proposition}\n    a) An infinite subset of a countable set is countable.\n\n    b) The union of the sets of a finite or countable system of countable \n    sets is a countable set.\n\\end{proposition}\n\n\\begin{corollary}\n    1) ${\\rm card} \\mathbb{Z} = {\\rm card} \\mathbb{N}$\n    \n    2) ${\\rm card} \\mathbb{N}^2 = {\\rm card} \\mathbb{N}$ .\n\\end{corollary}\n\n\\subsection{The Cardinality of the Coninuum}\n\\begin{definition}\n    The set $R$ of real numbers is also called the number continuum, \n    \\footnote{From the Latin continuum, meaning continuous, or solid.}\n    and its cardinality the cardinality of the continuum.\n\\end{definition}\n\n\\section{Max, Min, Sup, Inf}\nWe would like to begin by asking for the maximum of the set $(0,1)$.\nIt is clear that all the elements of the set less than 1. Furthermore, \n1 is the smallest number which is greater than all the values of the set \n$(0,1)$. \n\nLoosely speaking, one might say that 1 is the 'maximum value' of the \nset $(0,1)$. The problem is that 1 is not a value of the set at all. \nIn this situation, we use the word '\\textbf{supremum}' instead of the \nword '\\textbf{maximum}'. The distinction between these two concepts is \ndescribed in the following.\n\n\\begin{definition}\n    Let $S$ be a set of real numbers. An upper bound for $S$ is a \n    number $B$ such that $x \\le B$ for all $x \\in S$. The supremum,\n    if it exists(\"sup\", \"LUB\", \"least upper bound\") of $S$ is the \n    smallest upper bound for $S$. An upper bound which actually belongs \n    to the set is called a maximum.\n\\end{definition}\n\nProving that a certain number $M$ is the LUB of a set $S$ is often \ndone in two steps:\n\\begin{enumerate}\n    \\item Prove that $M$ is an upper bound for $S$, i.e. show that \n        $s \\le M$ for all $s \\in S$.\n    \\item Prove that $M$ is the least upper bound for $S$. This is \n        done by assuming that for any $\\epsilon >0$, such that $M - \n        \\epsilon$ is not an upper bound. In other words, there \n        exists an element $s_0 \\in S$ such that $s_0 > M - \\epsilon$.\n\\end{enumerate}\n\n\\begin{example}\n    Find the least upper bound for the following set and prove that your answer is correct.\n    \\[\n        S = \\left\\{\\dfrac{1}{2}, \\dfrac{2}{3}, \\dfrac{3}{4}, \\cdots,\n        \\dfrac{n}{n+1}, \\cdots \\right\\}\n    \\]\n\\end{example}\n\n\\begin{proposition}\n    Suppose that $M$ is an upper bound for a set $S$ such that $M \\in S$, then $M = \\sup\\left\\{S\\right\\}$\n\\end{proposition}\n\n\n\\begin{example}\n    Find the least upper bound for the following set and prove that your answer is correct.\n    \\[\n        S = \\left\\{1, \\dfrac{1}{2}, \\dfrac{2}{3}, \\dfrac{3}{4}, \\cdots,\n        \\dfrac{n}{n+1}, \\cdots \\right\\}\n    \\]\n\\end{example}\n\n\\begin{example}\n    Find the max, min, sup and inf of the following set and prove that your answer is correct.\n    \\[\n        S = \\left\\{ \\dfrac{2n+1}{n+1}\\left| n \\in N \\right.\\right\\}\n    \\]\n\\end{example}\n\nThe central question in this section is \"Does every non-empty set \nof numbers have a sup?\" The simple answer is No. The set $\\mathcal{N}$\nof natural numbers does not have a sup because it is not bound form above. \"Does every set of numbers which is bounded from above have a sup?\"\nThe answer, it turns out, depends upon what we mean by the word \"number\".\nIf the set is rational, the answer is No!\n\nNow, let $S$ be the set of all positive rational numbers $r$ such that \n$r^2 < 2$, that is \n\\[\n    S = \\left\\{0 < r < \\sqrt{2} \\left| r \\in \\mathcal{Q} \\right.\\right\\}\n\\]\nThe fact that $S$ does not have a sup in $\\mathcal{Q}$ can be thought \nof as saying that the rational numbers do not completely fill up the \nnumber line; there is a missing number \"directly to the right\" of $S$.\nThe fact that the set $\\mathcal{R}$ of all real numbers does fill up \nthe line is such a fundamentally important property that we take it as \nan axiom: the completeness axiom.\n\n\\begin{theorem}\\textbf{Least upper Bound Axion}\n    Every non-empty set of real numbers which is bounded from above has a supremum.\n\\end{theorem}\n\n\\begin{definition}\n    Let $S$ be a set of real numbers. A lower bound for $S$ is a number $B$ such that $B \\le x$ for all $x \\in S$. The infimum(\"inf\", \"GLB\", \n    \"greatest lower bound\") of $S$, if it exists, is the largest lower bound for $S$. A lower bound which actually belongs to the set is \n    called a minimum.\n\\end{definition}\n\n\\begin{theorem}\\textbf{Greatest Lower Bound Property}\n    Every non-empty set of real numbers which is bounded form below \n    has a infimum.\n\\end{theorem}\n\nProving that a certain number $M$ is the GLB of a set $S$ is often \ndone in two steps:\n\\begin{enumerate}\n    \\item Prove that $M$ is an lower bound for $S$, i.e. show that \n        $s \\ge M$ for all $s \\in S$.\n    \\item Prove that $M$ is the largest lower bound for $S$. This is \n        done by assuming that for any $\\epsilon >0$, such that $M + \n        \\epsilon$ is not an upper bound. In other words, there \n        exists an element $s_0 \\in S$ such that $s_0 < M + \\epsilon$.\n\\end{enumerate}\n\n\\begin{CJK*}{UTF8}{bsmi}\n    實數連續性：確界存在原理\n\n    實數完備性：柯西收斂原理。\n\n    確界收斂原理$\\Rightarrow $ 單調有界原理 $\\Rightarrow$\n    閉區間套定理 $\\Rightarrow$ Bolzano-Weierstrass定理 $\\Rightarrow $Cauchy收斂原理\n    $\\Rightarrow$ 閉區間套定理 $\\Rightarrow$ 確界原理。\n    \n    連續性 $\\iff$ 完備性。\n\\end{CJK*}\n\\end{document}\n\n", "meta": {"hexsha": "2f7e246835ab5c8624a89e298ab835b69ad58254", "size": 39615, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "files/analysis/ch00/introduction.tex", "max_stars_repo_name": "wuguoning/wuguoning.github.io", "max_stars_repo_head_hexsha": "e77af557063be72710b44e886749b25b80c51ad7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-13T18:18:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T18:18:51.000Z", "max_issues_repo_path": "files/analysis/ch00/introduction.tex", "max_issues_repo_name": "wuguoning/wuguoning.github.io", "max_issues_repo_head_hexsha": "e77af557063be72710b44e886749b25b80c51ad7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "files/analysis/ch00/introduction.tex", "max_forks_repo_name": "wuguoning/wuguoning.github.io", "max_forks_repo_head_hexsha": "e77af557063be72710b44e886749b25b80c51ad7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-09-08T06:46:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-02T15:10:59.000Z", "avg_line_length": 41.4816753927, "max_line_length": 878, "alphanum_fraction": 0.6890319323, "num_tokens": 11876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.5851011542032313, "lm_q1q2_score": 0.31308669952604135}}
{"text": "\\section*{Summary}\n\nIn summary, this chapter presented the novel theory behind the $\\Omega$-methods;\nthe metrics by which the $\\Omega$-methods will be compared with existing hybrid\nmethods; and the software that was modified to implement the $\\Omega$-methods\ninto an existing codebase. Two variants of the $\\Omega$-methods were presented:\nCADIS-$\\Omega$ and FW-CADIS-$\\Omega$, which are referred to together as\nFW/CADIS-$\\Omega$. CADIS-$\\Omega$ is a modification of CADIS, and is designed to\ngenerate VR parameters for local solutions in problems with strong anisotropy.\nFW-CADIS-$\\Omega$ is a modification of FW-CADIS, and is designed for generating\nVR parameters for global solutions in problems with strong anisotropy.\n\nBoth CADIS-$\\Omega$ and FW-CADIS-$\\Omega$ are implemented in well-used,\nwell-documented, massively-parallel, state-of-the-art radiation\ntransport and hybrid methods software. The\nradiation transport code suite Exnihilo is modified to generate the\n$\\Omega$-fluxes. The hybrid methods package ADVANTG is modified to generate\nVR parameters for the $\\Omega$-methods using the $\\Omega$-fluxes.\n\nTo understand the performance of the $\\Omega$-methods and compare it\nconsistently to existing methods, several performance metrics were proposed. First,\na few variants of the FOM were described. They include: FOM$_{MC,avg}$,\nFOM$_{MC,max}$, FOM$_{hybrid,avg}$, FOM$_{hybrid,avg}$. Together, they provide\nan overall picture of the performance of the $\\Omega$-method's performance with\nrespect to relative error and time, rather than of a\nsingle criteria. Because anisotropy has the ability to affect energy groups\ndifferently, resulting in different relative errors achieved in different energy\nbins, separating out different FOMs helps to isolate interesting behavior\nin the methods.\n\nThe $\\Omega$-methods are designed to work in problems with strong\nanisotropies in the flux. As a result, several anisotropy metrics\nwith which to investigate flux anisotropy were proposed.\nUsing these metrics and comparing them to\nthe relative errors or FOMs in each\ntally region, we can try to understand the effect that anisotropy has on the\n$\\Omega$-method performance. Each metric quantifies the anisotropy in cells\ndifferently, so each has the potential to capture different information. Denovo\nwas modified to output angular fluxes to generate the $\\Omega$-flux for the\n$\\Omega$-methods.\nAs a result, the anisotropy metrics use data generated from the existing\n$\\Omega$-method calculation.\n\nUsing the methodology described in this chapter, the $\\Omega$-methods'\nperformance can be fully characterized. Further, the characterization presented\nin this chapter has been\nextended from standard FOM performance metrics to include anisotropy\nquantification.\nBy implementing the $\\Omega$-methods into production-level software, it is\naccessible to any user beyond the author. The generation of the anisotropy\nmetrics is also incorporated into the codebase, meaning that any user could\nfeasibly perform an investigation of the $\\Omega$-performance consistent with\nwhat is proposed herein. The use of the various FOMs and of the aniostropy\nmetrics helps the understanding of the $\\Omega$-method performance as a function\nof time, error, and anisotropy.\n", "meta": {"hexsha": "52db5e10cd2dc27517d5028d427ea6f1f3a77e66", "size": 3248, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/methodology/summary.tex", "max_stars_repo_name": "rachelslaybaugh/munk-disseration", "max_stars_repo_head_hexsha": "e6dc6d6a8d5613cb30bca7dc4a2d419ad1b36e65", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/methodology/summary.tex", "max_issues_repo_name": "rachelslaybaugh/munk-disseration", "max_issues_repo_head_hexsha": "e6dc6d6a8d5613cb30bca7dc4a2d419ad1b36e65", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/methodology/summary.tex", "max_forks_repo_name": "rachelslaybaugh/munk-disseration", "max_forks_repo_head_hexsha": "e6dc6d6a8d5613cb30bca7dc4a2d419ad1b36e65", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 58.0, "max_line_length": 83, "alphanum_fraction": 0.802955665, "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3130620886141517}}
{"text": "\\documentclass[10pt]{article}\n\n\\usepackage{amsmath}\n\n\\begin{document}\n\n\\section{Fast image pre-processing}\n\nThe objective of the pre-processing is to provide data whose values\nare proportional to the incident flux and their respective precision.\nThis can be time-consuming ($\\sim 5 - 7$ operations per pixel are\nneeded) and, at least for real-time applications, it is desirable to\nhave the fastest pre-processing code.\n\nOur strategy: implement several variants (as discussed below) and tune\nthe compiler options to find the best combination of compiler (GCC or\nCLang), optimization options and code variant.  Once the best\ncombination has been identified, one may consider vectorizing the code\nby hand (using intrinsics functions or software like the Vector Class\nLibrary).  Note that the results depend on the compiler brand and\nversion but also on the processor.  The tests must therefore be easy\nto reproduce on different architectures and for different settings.\n\nTo remain quite general, the assumed prototype of the pre-processing\nfunction is:\n\\begin{verbatim}\nvoid PREPROCESSING(INT width, INT height, INT stride,\n                   FLOAT* restrict wgt,\n                   FLOAT* restrict dat,\n                   PIXEL const* restrict img,\n                   FLOAT const* restrict a,\n                   FLOAT const* restrict b,\n                   FLOAT const* restrict q,\n                   FLOAT const* restrict r);\n\\end{verbatim}\nwhere:\n\\begin{itemize}\n\\item \\verb+INT+ is the integer type for indexation (e.g.,\n  \\verb+size_t+).  As expected from what others have written on the\n  subject (e.g., Agner Fog, in a nutshell: ``\\emph{index computations\n    in loops involving vectorized floating-point operations are almost\n    free with modern processors and compilers with optimization}''),\n  using 32-bit or 64-bit signed/unsigned integers for \\verb+INT+ did\n  not change our results on a modern 64-bit processor.\n\n\\item \\verb+PIXEL+ is the pixel type of the acquired image \\verb+img+.\n\n\\item \\verb+FLOAT+ is the floating-point type for the preprocessed\n  data.  Single precision (C \\verb+float+ type) should be preferred\n  for faster computations (single/double precision makes no\n  differences for scalar operations on modern processors but\n  vectorized, SIMD, instructions can deal with twice as many values in\n  single precision compared to double precision).\n\n\\item \\verb+width+ and \\verb+height+ are the dimensions of the arrays,\n  \\verb+stride+ is the number of pixel to the next image row in the\n  acquired image \\verb+img+, other arrays are assumed to be stored\n  contiguously. To simplify the pseudo-code, we assume the following\n  macros have been defined to account for the considered colum-major\n  order and strides (they can be changed to account for other\n  conventions and the index expresions should be optimized out by any\n  good compiler):\n  \\begin{verbatim}\n  #define img(x,y)  img[(x) + (y)*stride]\n  #define wgt(x,y)  wgt[(x) + (y)*width]\n  #define dat(x,y)  dat[(x) + (y)*width]\n  #define a(x,y)      a[(x) + (y)*width]\n  #define b(x,y)      b[(x) + (y)*width]\n  #define q(x,y)      q[(x) + (y)*width]\n  #define r(x,y)      r[(x) + (y)*width]\n  \\end{verbatim}\n\n\\item \\verb+dat+ and \\verb+wgt+ are output arrays to store the data\n  and their respective weights.\n\n\\item \\verb+a+ and \\verb+b+ are input arrays specifying the pixel\n  correction terms which are used as follows:\n  \\begin{equation}\n    \\mathtt{dat}(x,y) = (\\mathtt{img}(x,y) - \\mathtt{b}(x,y))\n    \\times\\mathtt{a}(x,y)\n    \\label{eq:affine-correction}\n  \\end{equation}\n  where the bias $\\mathtt{b}(x,y)$ is in the same units as the\n  acquirred image $\\mathtt{img}(x,y)$; using another definition for\n  $\\mathtt{b}(x,y)$ and to exploit \\emph{fused multiply-add} (FMA)\n  instructions of the processor, we also consider using the following\n  formula:\n  \\begin{equation}\n    \\mathtt{dat}(x,y) = \\mathtt{img}(x,y)\\times\\mathtt{a}(x,y)\n    + \\mathtt{b}(x,y)\n    \\label{eq:affine-correction-fma}\n  \\end{equation}\n\n\\item \\verb+q+ and \\verb+r+ are input arrays providing the terms to\n  compute the weights according to the formula:\n  \\begin{equation}\n    \\mathtt{wgt}(x,y) = \\frac{\\mathtt{q}(x,y)}{\n      \\max\\{0, \\mathtt{dat}(x,y)\\} + \\mathtt{r}(x,y)}\n    \\label{eq:weights}\n  \\end{equation}\n  where $\\max\\{0,u\\}$ is implemented by a fast in-line function\n  $\\mathtt{nonnegative}(u)$ which avoids branching; for instance:\n  \\begin{verbatim}\n  static inline float nonnegative_f(float x) {\n      float zero = 0.0f;\n      return (x > zero ? x : zero);\n  }\n  static inline double nonnegative_d(double x) {\n      double zero = 0.0;\n      return (x > zero ? x : zero);\n  }\n  #define nonnegative(x) \\\n      _Generic((x), float: nonnegative_f, double: nonnegative_d)(x)\n  \\end{verbatim}\n  Another possibility is to compute the weights as:\n  \\begin{equation}\n    \\mathtt{wgt}(x,y) = \\frac{\\mathtt{q}(x,y)}{\n    \\max\\{\\mathtt{r}(x,y) + \\mathtt{dat}(x,y), \\mathtt{r}(x,y)\\}}\n    \\label{eq:weights-2}\n  \\end{equation}\n\n\\item The \\verb+restrict+ keyword is used to let the compiler assume\n  that there is no aliasing (it is the caller's reponsibility to\n  ensure that this holds).\n\\end{itemize}\n\nThere are 3 kinds of operation to consider:\n\\begin{enumerate}\n\\item convert pixel values (integers) to floating-point;\n\\item apply pixel correction formula~\\eqref{eq:affine-correction} or\n  \\eqref{eq:affine-correction-fma};\n\\item compute the weights according to formula~\\eqref{eq:weights} or\n  \\eqref{eq:weights-2}.\n\\end{enumerate}\nThe efficiency of vectorized instructions for converting integers to\nfloats strongly depend on the considered types and on the available set\nof instructions.\n\nIt may seem that for given input and output types (\\verb+PIXEL+ and\n\\verb+FLOAT+), there are only 4 possibilities depending on which\nvariants of the pixel correction and weights formula are chosen.\nAnother flexibility is whether the operations are all applied to a\npixel before processing the next one or are each applied to a group of\npixels.  The former is summarized by the following version of the code:\n\\begin{verbatim}\n    // Version 1.  Apply all operations to each pixel in turn.\n    for (INT y = 0; y < height; ++y) {\n        for (INT x = 0; x < width; ++x) {\n            FLOAT val = apply_correction((FLOAT)img(x,y), a(x,y), b(x,y));\n            dat(x,y) = val;\n            wgt(x,y) = compute_weight(val, q(x,y), r(x,y));\n        }\n    }\n\\end{verbatim}\nwhere the macros or inline functions \\verb+apply_correction+ and\n\\verb+compute_weight+ implement one of the processing formula.\n\n\\begin{verbatim}\nstatic inline FLOAT apply_correction_v1(FLOAT u, FLOAT a, FLOAT b) {\n    return (u - b)*a;\n}\nstatic inline FLOAT apply_correction_v2(FLOAT u, FLOAT a, FLOAT b) {\n    return u*a + b; // candidate for FMA instruction\n}\nstatic inline FLOAT compute_weight_v1(FLOAT u, FLOAT q, FLOAT r) {\n    FLOAT const zero = 0;\n    return q/((u > zero ? u : zero) + r);\n}\nstatic inline FLOAT compute_weight_v2(FLOAT u, FLOAT q, FLOAT r) {\n    FLOAT v = u + r;\n    return q/(v > r ? v : r);\n}\n\\end{verbatim}\n\nIt may be advantageous to perform a given operation for a group of\npixels to avoid cache misses and to benefit from better pipelining of\nthe instructions.  The other 6 possibilities are listed in\nAppendix~\\ref{sec:split-pre-processing}.  Combining all possibilities,\nthere are $4\\times7 = 28$ possible variants of the code for\npre-processing images.\n\nMinimum times (in microseconds) measured for \\verb+niau+ with\n$\\mathtt{width} = 380$, $\\mathtt{height} = 380$ and $\\mathtt{stride} =\n400$:\n\n% \\CLANG{func}{min}{max}{avg}{std}{units}\n\\newcommand{\\CLANG}[6]{CLang (AVX2) & #1 & $#2$ \\\\}\n% \\GNUCC{func}{min}{max}{avg}{std}{units}\n\\newcommand{\\GNUCC}[6]{GCC (AVX2) & #1 & $#2$ \\\\}\n\n{\\small\n\\begin{tabular}{rcc}\n  \\hline\n  Compiler (instr. set) & Variant & Min. time \\\\\n  \\hline\n  \\hline\n  \\CLANG{11}{56.970}{ 74.530}{ 58.058186}{ 1.605700}{µs}\n  \\CLANG{12}{53.110}{ 81.671}{ 54.620167}{ 1.720122}{µs}\n  \\CLANG{13}{59.351}{140.521}{ 61.005435}{ 3.051151}{µs}\n  \\CLANG{14}{81.251}{178.312}{ 85.348006}{10.007648}{µs}\n  \\CLANG{15}{53.741}{ 87.721}{ 55.202642}{ 2.355055}{µs}\n  \\CLANG{16}{56.170}{ 96.170}{ 57.526538}{ 2.233562}{µs}\n  \\CLANG{17}{63.581}{105.000}{ 64.952477}{ 2.190579}{µs}\n  \\hline\n  \\CLANG{21}{53.171}{ 87.361}{ 54.481988}{ 2.307893}{µs}\n  \\CLANG{22}{52.381}{ 92.280}{ 54.173267}{ 2.169050}{µs}\n  \\CLANG{23}{56.631}{ 97.441}{ 58.096858}{ 2.050985}{µs}\n  \\CLANG{24}{66.371}{145.831}{ 68.360545}{ 4.243564}{µs}\n  \\CLANG{25}{52.070}{283.432}{ 57.394765}{ 9.062245}{µs}\n  \\CLANG{26}{53.740}{ 88.871}{ 55.447496}{ 1.946086}{µs}\n  \\CLANG{27}{63.930}{100.861}{ 65.434994}{ 2.572050}{µs}\n  \\hline\n  \\CLANG{31}{57.100}{ 89.121}{ 58.416060}{ 1.986981}{µs}\n  \\CLANG{32}{54.430}{ 72.571}{ 56.579088}{ 1.769608}{µs}\n  \\CLANG{33}{58.191}{169.201}{ 60.013186}{ 3.250281}{µs}\n  \\CLANG{34}{66.820}{ 92.631}{ 68.123130}{ 1.921881}{µs}\n  \\CLANG{35}{52.610}{ 86.950}{ 54.536280}{ 2.711644}{µs}\n  \\CLANG{36}{55.920}{ 92.291}{ 57.693083}{ 2.388796}{µs}\n  \\CLANG{37}{63.300}{182.862}{ 65.823999}{ 4.582080}{µs}\n  \\hline\n  \\CLANG{41}{53.330}{ 73.971}{ 55.054576}{ 1.705375}{µs}\n  \\CLANG{42}{65.540}{153.911}{ 69.425782}{ 9.363764}{µs}\n  \\CLANG{43}{57.410}{ 74.531}{ 58.776598}{ 1.568815}{µs}\n  \\CLANG{44}{66.430}{179.071}{ 76.198362}{13.123401}{µs}\n  \\CLANG{45}{51.670}{229.022}{ 60.313979}{10.400270}{µs}\n  \\CLANG{46}{55.120}{ 86.741}{ 56.904224}{ 1.945661}{µs}\n  \\CLANG{47}{62.621}{ 82.680}{ 64.097832}{ 1.729211}{µs}\n  \\hline\n\\end{tabular}\n\\begin{tabular}{rcc}\n  \\hline\n  Compiler (instr. set) & Variant & Min. time \\\\\n  \\hline\n  \\hline\n  \\GNUCC{11}{  77.041}{ 226.231}{ 86.575946}{16.793423}{µs}\n  \\GNUCC{12}{  82.000}{ 155.871}{ 84.398167}{ 4.693786}{µs}\n  \\GNUCC{13}{  88.841}{ 235.132}{ 91.888392}{ 5.530952}{µs}\n  \\GNUCC{14}{  95.631}{ 108.971}{ 97.598377}{ 1.984801}{µs}\n  \\GNUCC{15}{  76.570}{ 119.111}{ 78.358241}{ 3.038277}{µs}\n  \\GNUCC{16}{  85.621}{ 126.381}{ 88.861668}{ 5.500124}{µs}\n  \\GNUCC{17}{  89.731}{ 338.433}{ 92.428650}{ 5.443398}{µs}\n  \\hline\n  \\GNUCC{21}{  75.551}{ 202.081}{ 78.376814}{ 5.953618}{µs}\n  \\GNUCC{22}{  79.580}{  97.511}{ 81.202480}{ 1.775103}{µs}\n  \\GNUCC{23}{  86.210}{ 121.861}{ 88.116059}{ 2.160855}{µs}\n  \\GNUCC{24}{  93.270}{ 278.442}{ 97.339100}{ 7.174303}{µs}\n  \\GNUCC{25}{  77.111}{ 320.342}{ 88.242220}{12.914786}{µs}\n  \\GNUCC{26}{  84.860}{ 195.262}{ 87.793884}{ 5.403702}{µs}\n  \\GNUCC{27}{  90.411}{ 137.171}{ 92.016684}{ 1.993308}{µs}\n  \\hline\n  \\GNUCC{31}{  74.910}{ 139.421}{ 76.976665}{ 2.730088}{µs}\n  \\GNUCC{32}{  81.000}{ 224.232}{102.370571}{13.946480}{µs}\n  \\GNUCC{33}{  90.591}{ 267.332}{ 96.051259}{11.169465}{µs}\n  \\GNUCC{34}{  94.941}{ 170.371}{ 97.205497}{ 3.213725}{µs}\n  \\GNUCC{35}{  80.531}{ 103.271}{ 81.894702}{ 1.863712}{µs}\n  \\GNUCC{36}{  86.521}{ 136.181}{ 88.580517}{ 3.045327}{µs}\n  \\GNUCC{37}{  91.321}{ 234.212}{ 94.426342}{ 6.659262}{µs}\n  \\hline\n  \\GNUCC{41}{  71.531}{ 159.252}{ 74.088624}{ 5.326842}{µs}\n  \\GNUCC{42}{  95.580}{ 211.052}{100.368879}{12.620478}{µs}\n  \\GNUCC{43}{  88.490}{ 133.591}{ 90.390562}{ 2.380617}{µs}\n  \\GNUCC{44}{  94.511}{ 140.811}{ 96.525544}{ 2.188096}{µs}\n  \\GNUCC{45}{  79.471}{ 124.901}{ 80.739104}{ 1.922186}{µs}\n  \\GNUCC{46}{  85.511}{ 124.211}{ 87.588812}{ 3.054086}{µs}\n  \\GNUCC{47}{  91.700}{ 145.671}{ 93.715253}{ 2.316825}{µs}\n  \\hline\n\\end{tabular}\n}\n\nThe first digit in the Variant column indicates the formulae used to\napply the pixel correction and to compute the weights:\n\\begin{itemize}\n\\item[1 =] formulae~\\eqref{eq:affine-correction} and \\eqref{eq:weights};\n\\item[2 =] formulae~\\eqref{eq:affine-correction-fma} and \\eqref{eq:weights};\n\\item[3 =] formulae~\\eqref{eq:affine-correction} and \\eqref{eq:weights-2};\n\\item[4 =] formulae~\\eqref{eq:affine-correction-fma} and \\eqref{eq:weights-2};\n\\end{itemize}\nThe second digit is the loop splitting variant (see\nAppendix~\\ref{sec:split-pre-processing}).  A bout 20\\,ns should be\nsubtarcted to the measured time to account the calls to\n\\verb+clock_gettime+.\n\nFirst conclusions: (1) These times are much shorter than what has been\npreviously measured with Julia (about 170 microseconds). (2) CLang\nyields a better optimzed code than GCC (this can be seen in the\nassembler code) which is about 33\\,\\% faster.  I suspect that is due\nto the inability of GCC to unroll vectorized loops.  (4) The 2nd and\n5th strategies for loop splitting work the best for CLang, the 1st or\nthe 5th work the best for GCC. (4) All these results have to be\nreproduced on the RTC (\\verb+ko+).\n\n\\appendix\n\\section{Splitting of the pre-processing operations}\n\\label{sec:split-pre-processing}\n\nWe first consider performing part of the pre-processing operations\nto rows of pixels.  There are 3 possibilities.\n\\begin{verbatim}\n    // Version 2.  Convert and apply correction to a row of pixels,\n    // then compute weights for this row of pixels.\n    for (INT y = 0; y < height; ++y) {\n        for (INT x = 0; x < width; ++x) {\n            dat(x,y) = apply_correction((FLOAT)img(x,y), a(x,y), b(x,y));\n        }\n        for (INT x = 0; x < width; ++x) {\n            wgt(x,y) = compute_weight(dat(x,y), q(x,y), r(x,y));\n        }\n    }\n\\end{verbatim}\n\n\\begin{verbatim}\n    // Version 3.  Convert a row of pixels, then apply correction\n    // and compute weights for this row of pixels.\n    for (INT y = 0; y < height; ++y) {\n        for (INT x = 0; x < width; ++x) {\n            dat(x,y) = img(x,y);\n        }\n        for (INT x = 0; x < width; ++x) {\n            FLOAT val = apply_correction(dat(x,y), a(x,y), b(x,y));\n            dat(x,y) = val;\n            wgt(x,y) = compute_weight(val, q(x,y), r(x,y));\n        }\n    }\n\\end{verbatim}\n\n\\begin{verbatim}\n    // Version 4.  Convert a row of pixels, then apply correction\n    // for this row of pixels, finally compute weights for this row\n    // of pixels.\n    for (INT y = 0; y < height; ++y) {\n        for (INT x = 0; x < width; ++x) {\n            dat(x,y) = img(x,y);\n        }\n        for (INT x = 0; x < width; ++x) {\n            dat(x,y) = apply_correction(dat(x,y), a(x,y), b(x,y));\n        }\n        for (INT x = 0; x < width; ++x) {\n            wgt(x,y) = compute_weight(dat(x,y), q(x,y), r(x,y));\n        }\n    }\n\\end{verbatim}\n\nSplitting can also be done for the complete image (not for the rows).\nThe following versions assumes that pixels are contiguous in other\narrays than the input image.  If these loops are vectorized, this\navoids \\emph{prologue and epilogue loop peeling} between rows.\n\n\\begin{verbatim}\n    // Version 5.  Convert and apply correction to the full image,\n    // then compute the weights for the image.\n    for (INT y = 0; y < height; ++y) {\n        for (INT x = 0; x < width; ++x) {\n            dat(x,y) = apply_correction((FLOAT)img(x,y), a(x,y), b(x,y));\n        }\n    }\n    INT const n = width*height;\n    for (INT i = 0; i < n; ++i) {\n        wgt[i] = compute_weight(dat[i], q[i], r[i]);\n    }\n\\end{verbatim}\n\n\\begin{verbatim}\n    // Version 6.  Convert the full image to floating-point,\n    // then apply the correction and compute the weights for the image.\n    for (INT y = 0; y < height; ++y) {\n        for (INT x = 0; x < width; ++x) {\n            dat(x,y) = img(x,y);\n        }\n    }\n    INT const n = width*height;\n    for (INT i = 0; i < n; ++i) {\n        FLOAT val = apply_correction(dat[i], a[i], b[i]);\n        dat[i] = val;\n        wgt[i] = compute_weight(val, q[i], r[i]);\n    }\n\\end{verbatim}\n\n\\begin{verbatim}\n    // Version 7.  Convert the full image to floating-point,\n    // then apply the correction to the image and finally\n    // compute the weights for the image.\n    for (INT y = 0; y < height; ++y) {\n        for (INT x = 0; x < width; ++x) {\n            dat(x,y) = img(x,y);\n        }\n    }\n    INT const n = width*height;\n    for (INT i = 0; i < n; ++i) {\n        dat[i] = apply_correction(dat[i], a[i], b[i]);\n    }\n    for (INT i = 0; i < n; ++i) {\n        wgt[i] = compute_weight(dat[i], q[i], r[i]);\n    }\n\\end{verbatim}\n\n\n\n\n\n\n\n\n\\end{document}\n", "meta": {"hexsha": "bb0e49f58b2f017d9c4528f8a7fb8f6e85a5de87", "size": 15950, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/fastops.tex", "max_stars_repo_name": "emmt/PVC", "max_stars_repo_head_hexsha": "61bac62ee2c1f28c8bab59d63f39037d2bd17f63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-25T00:28:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-25T00:28:44.000Z", "max_issues_repo_path": "doc/fastops.tex", "max_issues_repo_name": "emmt/PVC", "max_issues_repo_head_hexsha": "61bac62ee2c1f28c8bab59d63f39037d2bd17f63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/fastops.tex", "max_forks_repo_name": "emmt/PVC", "max_forks_repo_head_hexsha": "61bac62ee2c1f28c8bab59d63f39037d2bd17f63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4801980198, "max_line_length": 78, "alphanum_fraction": 0.6453291536, "num_tokens": 5455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819874558604, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3128543147981975}}
{"text": "\\documentclass[10pt]{article}\n\\usepackage{cite}\n\\usepackage{a4}\n\n\\usepackage[utf8]{inputenc}\n\\usepackage[english]{babel}\n\\usepackage{amsmath,amssymb,amsthm}\n\n\\usepackage{url}\n\\usepackage{pgf}\n\\usepackage{tikz}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% layout commands\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\newtheorem{thm}{Theorem}[section]\n\\newtheorem{lem}[thm]{Lemma}\n\n\\newcommand{\\prog}[3]{\\langle #1, #2, #3\\rangle}\n\\newcommand{\\slp}[1]{\\mathbb{#1}}\n\\newcommand{\\slpterm}[3]{\\slp{#1}_{#2} = #3}\n\\newcommand{\\slpnonterm}[4]{\\slp{#1}_{#2} = \\slp{#1}_{#3} \\cdot \\slp{#1}_{#4}}\n\\newcommand{\\substr}[2]{[#1\\dots#2]}\n\\newcommand{\\subslp}[3]{\\slp{#1}[#2\\dots#3]}\n\n\\newcommand{\\problem}[3]{\n            \\noindent {\\sc Problem:} \\textbf{#1} \\newline\n            \\noindent {\\sc Input:} #2 \\newline\n            \\noindent {\\sc Output:} #3\n}\n\n\\renewcommand{\\emptyset}{\n    \\font\\msbm = msbm10 at 12pt \n    \\mbox{\\msbm \\char 63}\n}\n\n\\begin{document}\n\n\\title{Computing All Squares in Compressed Texts}\n\\author{Lesha Khvorost\\thanks{The author acknowledges support from the Russian Foundation for Basic Research, grant\n10-01-00793.}\\\\\nUral Federal University\\\\\njaamal@mail.ru}\n\\date{}\n\\maketitle\n\n\\begin{abstract}\nWe consider the problem of computing all squares in a string represented by a straight-line program (SLP). An\ninstance of the problem is an SLP $\\slp{S}$ that derives some string $S$ and we seek a solution in the form of a table\nthat contains information about all squares in $S$ in a compressed form. We present an algorithm that solves the\nproblem in $O(|\\slp{S}|^4\\cdot \\log^2{|S|})$ time and requires $O(|\\slp{S}|\\cdot \\max\\{ |\\slp{S}|, \\log{|S|}\\})$ space,\nwhere $|\\slp{S}|$ (respectively $|S|$) is the size of the SLP $\\slp{S}$ (respectively the length of the string $S$).\n\\end{abstract} \n\n\\section{Introduction}\n\nVarious compressed representations of strings are known: straight-line programs (SLPs),\ncollage-systems, string representations using antidictionaries, etc. Nowadays text compression\nbased on context-free grammars such as SLPs attracts much attention. The reason for this is not only that grammars\nprovide well-structured compression but also that the SLP-based compression is in a sense polynomially equivalent\nto the compression achieved by the Lempel-Ziv algorithm that is widely used in practice. It means that, given a\nstring $S$, there is a polynomial relation between the size of an SLP that derives $S$ and the size of the\ndictionary stored by the Lempel-Ziv algorithm \\cite{18}.\n\nWhile compressed representations save storage space, there is a price to pay: some classical problems on strings\nbecome computationally hard when one deals with compressed data and measures algorithms' speed in terms of the\nsize of compressed representations. As examples we mention here the problems \\textbf{Hamming distance} \\cite{15} and\n\\textbf{Literal shuffle} \\cite{4}. On the other hand, there exist problems that admit algorithms working rather well on\ncompressed representations: \\textbf{Pattern matching} \\cite{15}, \\textbf{Longest common substring} \\cite{16}, \n\\textbf{Computing all palindromes} \\cite{16}. This dichotomy gives rise to the following research direction: to\nclassify important string problems by their behavior with respect to compressed data.\n\nThe \\textbf{Computing All Squares} (\\textbf{CAS}) problem is a well-known problem on strings. It is of importance, for\nexample, in molecular biology. Up to recently it is was not known whether or not \\textbf{CAS} admits an algorithm polynomial \nin the size of a compressed representation of a given string.\\footnote{A polynomial algorithm that solves \\textbf{CAS} \nfor strings represented by Lempel-Ziv encodings was announced in~\\cite{8}. This representation is slightly more general \nthan that by SLPs. However no details of the algorithm have ever been appeared.} In general, a string can have \nexponentially many squares with respect to the size of its compressed representation. For example, the string $a^n$ \nhas $\\Theta(n^2)$ squares, while it is easy to build an SLP of size $O(\\log n)$ that derives $a^n$. So we must \nstore information about squares in a compressed form. Also this implies that we cannot search for squares \nconsecutively by moving from one square to the ``next'' one.\n\n\\section{Preliminaries}\n\nWe consider strings of characters from a fixed finite alphabet $\\Sigma$. The \\emph{length} of a string $S$ is the number\nof its characters and is denoted by $|S|$. The \\emph{concatenation} of strings $S_1$ and $S_2$ is denoted by $S_1 \\cdot\nS_2$.  A \\emph{position} in a string $S$ is a point between consecutive characters. We number positions from left to \nright by $1,2,\\dots,|S|-1$. It is convenient to consider also the position 0 preceding the text and the position $|S|$ \nfollowing it. For a string $S$ and an integer $i$ where $0 \\leq i \\leq |S|$ we define $S[i]$ as the character between the positions\n$i$ and $i+1$ of $S$. A \\emph{substring} of $S$ starting at a position $\\ell$  and ending at a position $r$ where $0\\leq \\ell < r \\leq |S|$ \nis denoted by $S[\\ell \\dots r]$. We say that a substring $S[\\ell \\dots r]$ \\emph{touches} a position $t$ if $\\ell \\leq t \\leq r$. \nA string is called a \\emph{square} if it can be obtained\nby concatenating two copies of some string. The position $|x|$ of a square $xx$ is called the \\emph{center} of $xx$ and\n$x$ is referred to as the \\emph{root} of $xx$. A square $xx$ is called \\emph{pure} if $x$ occurs exactly two times in\n$xx$. A string $S$ is called \\emph{p-periodic} if for a given integer $p$ and every position $i$ such that $0 \\leq i\n\\leq |S| - p$ one has $S[i] = S[i + p]$. The integer $p$ is called the \\emph{period} of $S$.\n\nA \\emph{straight-line program} (SLP) $\\slp{S}$ is a sequence of assignments of the form: \n$\\slp{S}_1 = expr_1,\\ \\slp{S}_2 = expr_2, \\dots, \\slp{S}_n = expr_n,$ where $\\slp{S}_i$ are \\emph{rules} and $expr_i$ \neither is a symbol of $\\Sigma$ (we call such rules \\emph{terminal}), or $expr_i = \\slp{S}_\\ell\\cdot \\slp{S}_r \\ (\\ell, r < i)$ \n(we call such rules \\emph{nonterminal}). Every SLP $\\slp{S}$ generates exactly one string $S\\in\\Sigma^+$ and \nwe refer to $S$ as the \\emph{text} generated by $\\slp{S}$.\n\nWe adopt the following conventions in the paper: every SLP is denoted by a capital blackboard bold letter, for\nexample, $\\slp{S}$. Every rule of this SLP is denoted by the same letter with indices, for example,\n$\\slp{S}_1,\\slp{S}_2,\\dots$. The text that is derived from a rule is denoted by the same indexed capital letter in\nthe standard font, for example, the text that is derived from $\\slp{S}_i$ is denoted by $S_i$. The \\emph{size} of an SLP $\\slp{S}$ is \nthe number of its rules and is denoted by $|\\slp{S}|$. The \\emph{cut position} of a nonterminal rule \n$\\slp{S}_i = \\slp{S}_\\ell\\cdot \\slp{S}_r$ is the position $|S_\\ell|$ in the text $S_i$.\n\n\\section{Basic operations}\n\nIn this section we present some basic operations over SLPs widely used in the paper. The operations are well-known and presented \nhere for the reader's convenience.\n\n\\vspace{5pt}\n\n\\problem{Subgrammar cutting (SubCut)}\n{an SLP $\\slp{S}$ that derives a text $S$, integers $\\ell$ and $r$ such that $0 \\leq \\ell < r \\leq |\\slp{S}|$.}\n{an SLP $\\slp{S}\\substr{\\ell}{r}$ which derives the text $S\\substr{\\ell}{r}$.}\n\n\\noindent \\textsc{Complexity:} There is an algorithm that solves \\textbf{SubCut} using $O(|\\slp{S}|)$ time and $O(|\\slp{S}|)$ space.\n\n\\vspace{5pt}\n\n\\problem{Pattern matching (PM)}\n{SLPs $\\slp{S}$ and $\\slp{T}$ that derives texts $S$ and $T$ respectively, $|S| \\leq |T|$.}\n{$O(|\\slp{T}|)$ arithmetic progressions that describe the start positions of all occurrences of $S$ in $T$.}\n\n\\noindent \\textsc{Complexity:} There is an algorithm \\cite{15} that solves \\textbf{PM} using $O(|\\slp{T}|^2|\\slp{S}|)$ time and\n$O(|\\slp{T}||\\slp{S}|)$ space.\n\n\\vspace{5pt}\n\n\\problem{Substrings extending (SubsExt)}\n{an SLP $\\slp{S}$, integers $\\ell_1, r_1, \\ell_2$ and $r_2$ where $0 \\leq \\ell_1 < r_1 \\leq |\\slp{S}|, 0\n\\leq \\ell_2 < r_2 \\leq |\\slp{S}|$ such that $S\\substr{\\ell_1}{r_1} = S\\substr{\\ell_2}{r_2}$.}\n{integers $\\ell_{ex}$ and $r_{ex}$ where $\\ell_{ex}$ is the length of the longest common suffix of $S\\substr{1}{r_1}$ and $S\\substr{1}{r_2}$,\n$r_{ex}$ is the length of the longest common prefix of $S\\substr{\\ell_1}{|S|}$ and $S\\substr{\\ell_2}{|S|}$.}\n\n\\noindent \\textsc{Complexity:} There is an algorithm that solves \\textbf{SubsExt} using $O(|\\slp{S}|^3 \\log|S|)$ time \nand $O(|\\slp{S}|^2)$ space.\n\n\\vspace{5pt}\n\n\\problem{Period termination}\n{an SLP $\\slp{S}$, an integer $p > 0$ and positions $\\ell, r$ where $0 \\leq \\ell < r \\leq |\\slp{S}|$ such that $S\\substr{\\ell}{r}$ is $p$-periodic substring.}\n{positions $t_L, t_R$ in the text $S$ where $p$-periodicity of $S\\substr{\\ell}{r}$ terminates from the left and from the right correspondingly.\nIt means that $S\\substr{t_L}{r}$ is $p$-periodic while $S\\substr{t_L+1}{r}$ is not $p$-periodic.}\n\n\\noindent \\textsc{Complexity:} There exists an algorithm that solves \\textbf{Period termination} using $O(|\\slp{S}|^3 \\log|S|)$ time \nand $O(|\\slp{S}|^2)$ space.\n\n\\section{Square-freeness checking algorithm}\n\n\\problem{Square-freeness}{an SLP $\\slp{S}$ that derives a text $S$;}{ true/false, whether or not $S$ is square-free?}\n\n\\vspace{5pt}\n\n\\noindent \\textbf{Squares location idea.} Suppose $xx$ is a square that occurs in $S$ and $c$ is the center of $xx$. \nThere is a unique rule $\\slp{S}_j$ such that $xx$ fully occurs in $S_j$ and $xx$ touches the cut position of $\\slp{S}_j$. \nSo for every integer $j \\in \\{1, 2, \\dots, |\\slp{S}|\\}$ the algorithm looks for squares that touch the cut position of $\\slp{S}_j$ only.\n\nWe use the following simple idea to obtain squares. If $B$ is a substring of $x$ then $B$ occurs at least two times in\n$xx$. So the algorithm may fix some substring $B$ and look for other occurrences of $B$. Every pair of occurrences of\n$B$ indicates that some squares are possible. Hence the algorithm has an additional step to check whether or\nnot a pair of substrings indeed corresponds to squares. We would like to note that such an algorithm is unable to find\nall squares that touches the cut position of $\\slp{S}_j$ directly. The algorithm partitions all squares into groups by length of\nroot. There is a unique integer $i_0$ such that $2^{i_0-1} \\leq |x| < 2^{i_0}$. So for a fixed integer $j$ and every integer \n$i \\in \\{1, \\dots, \\lceil \\log_2 |S| \\rceil\\}$ the algorithm looks for squares $xx$ that touch the cut position of $\\slp{S}_j$ and \n$2^{i-1} \\leq |x| < 2^i$.\n\n\\vspace{5pt}\n\n\\noindent \\textbf{Local search idea.} Suppose $j$ and $i$ are fixed. Let $\\gamma$ be the cut position of $\\slp{S}_j$. \nThe algorithm partitions the $2^{i+1}$-neighborhood of $\\gamma$ into 16 text blocks of equal length. Thus the length of each block is\nequal to $2^{i-2}$. Let us enumerate the blocks from $B_1$ to $B_{16}$. For example, the left block that\ntouches $\\gamma$ is $B_8$, the block left of $B_8$ is $B_7$ and the block right of $B_8$ is $B_9$. Depending\non the length of $S_j$ the neighborhood may contain less than 16 blocks or extreme blocks may have lengths less than\n$2^{i-2}$. For squares whose centers locate at the blocks $B_{1}, B_{2}, \\dots, B_{4}$ and $B_{13}, B_{14}, \\dots, B_{16}$ \nwe get a contradiction with restrictions on length of squares or with the condition that squares touch $\\gamma$.\nTherefore the algorithm looks for squares whose centers locate at blocks $B_{5}, B_{6}, \\dots, B_{12}$ only.\n\nLet $c$ be the center of a square $xx$ and lec $c$ belong to one of the eight central blocks $B_k$. Since $2^{i-1}\n\\leq |x|$, we conclude that $xx$ contains at least three consecutive blocks $B_{k-1}, B_{k}$ and $B_{k+1}$. All occurrences of $B_{k-1}$ \nin $B_{k+1}\\cdot B_{k+2}$ can be obtained using the \\textbf{PM} algorithm. So the algorithm takes every pair consisting of a block\n$B_{k-1}$ and its occurrence in $B_{k+1}\\cdot B_{k+2}$ and extends them to check whether or not they form any square.\n\n\\begin{lem}[{\\rm\\cite{2}}]\n\\label{lem:blocks}\nAssume that the period of a string $B$ is $p$. If $B$ occurs only at positions $p_1 < p_2 < \\dots < p_k$ of a text\n$S$ and $p_k - p_1 \\leq \\frac{|B|}{2}$ then the $p_i$'s form an arithmetic progression with difference $p$.\n\\end{lem}\n\n\\noindent \\textsc{Algorithm:} For every block $B_{k-1}$ the algorithm computes $\\slp{B}_{k-1}$ and $\\slp{B}_{k+1} \\cdot \\slp{B}_{k+2}$\nusing \\textbf{SubCut}. Next it invokes \\textbf{PM} with $\\slp{B}_{k-1}$ and $\\slp{B}_{k+1} \\cdot \\slp{B}_{k+2}$. \nLemma~\\ref{lem:blocks} implies that the occurrences can be represented using at most four arithmetic\nprogressions. The algorithm compresses the occurrences into four arithmetic progressions. Finally it verifies whether or\nnot $B_{k-1}$ and a progression $\\prog{a}{p}{t}$ of its occurrences form any square. There are the following cases:\n\n\\begin{itemize}\n\\item If $t = 0$ then there are no squares that satisfy the restrictions and the algorithm moves to the next block;\n\n\\item If $t = 1$ then the algorithm computes $\\ell_{ex}$, $r_{ex}$ invoking \\textbf{SubsExt} with $B_{k-1}$ and $S_j[a\\dots\na + 2^{i-2}]$. If $\\ell_{ex} + r_{ex} > a - (k-1)\\cdot 2^{i-2}$ then there exists at least one square and the algorithm\nreturns $\\bf{false}$. Otherwise there are no squares that satisfy the restrictions and it moves to the next block;\n\n\\item If $t \\geq 2$ there exists at least one square and the algorithm returns $\\bf{false}$. \n\\end{itemize}\n\n\\noindent \\textsc{Complexity:} For each of the eight central blocks the algorithm invokes \\textbf{SubCut} two times, \n\\textbf{PM} once and \\textbf{SubsExt} at most four times. Hence the main step requires $O(|\\slp{S}|^3 \\cdot \\log |S|)$ time \nand $O(|\\slp{S}|^2)$ space. The algorithm makes at most $|\\slp{S}| \\cdot \\log |S|$ steps. Altogether we get the following theorem: \n\n\\begin{thm}\nThere is an algorithm that solves square-freeness problem using $O(|\\slp{S}|^4\\cdot \\log^2{|S|})$ time and\n$O(|\\slp{S}|^2)$ space.\n\\end{thm}\n\n\\section{S-table and its properties}\n\nThe \\emph{squares table} (shortly S-table) is a rectangular table $S(\\slp{S})$ that holds information about all \nsquares in the text in a compressed form. The size of $S(\\slp{S})$ is equal to $(\\lfloor\\log |S|\\rfloor+1) \\times\n(|\\slp{S}|+1)$. It is convenient to start numbering rows and columns of S-tables with 0. We denote the cell in the\n$i$-th row and $j$-th column of table by $S(i,j)$. The cell $S(0,0)$ is always left blank. The cells $S(0,j)$ with\n$j>0$ hold the rules of the SLP $\\slp{S}$ ordered such that the lengths of the texts they derive increase. (If some\nrules derive texts of the same length then the rules are listed in an arbitrary but fixed order). Thus, the first cells\nof the 0-th row hold terminal rules followed by rules that derive texts of length~2, etc. The cells $S(i,0)$ with\n$i>0$ hold segments $[2^{i-1}, 2^i - 1]$. Every cell $S(i, j)$ with $i,j>0$ holds information about families of squares.\n\nThere exist four types of families: an empty family (stored as $\\emptyset$), a simple family of squares (stored using \n4-tuple $\\{|x|, p, c_\\ell, c_r \\}$ where $|x|$ is the length of root, $c_\\ell$ is the position of the leftmost square, \n$c_r$ is the center position of the rightmost square), a dynamic family of pure squares, a dynamic family of squares. \nBoth types of dynamic families contain squares with different root lengths and different centers. We are unable to master \nan explicit compressed representation for the dynamic families that would be easy to handle with. This fact restricts the range of problems \nthat we can solve by usage of S-tables. But both dynamic families support the following properties: \n\\emph{total} (total number of squares that is contained in the family), \\emph{reduction by length of root} \n(for a fixed value of $|x|$, this property reduces a dynamic family to an array of simple families), \n\\emph{reduction by position} (for a fixed position $\\ell$ of $S$ this property returns range of roots of squares that start from $\\ell$).\n\nUsing information from an S-table it is easy to find information about all squares of fixed length, to compute total number of squares \nthat are contained in $S$, to find information about all squares that start from a fixed position, to find the longest square in $S$,\nto check whether on not a text $S$ is square-free. At the same time there are problems that are not easy to decide via S-tables.\nAs an example one can take the following problem: for a given $\\slp{S}$ that derives a text $S$ to construct an SLP that derives \nthe concatenation of all squares that are contained in $S$. \nThe example shows that an S-table accumulates a quantitative information about squares rather than information\nappropriate for searching some fixed squares. It is a common feature of algorithms over SLPs that accumulate information \nabout all objects of a specified type. The similar situation appears in \\textbf{Computing all palindromes}~\\cite{16}.\n\n\\section{Computing all squares algorithm}\n\n\\problem{CAS}{an SLP $\\slp{S}$ that derives a text $S$;}{a data structure (an S-table) that contains\ninformation about all squares in $S$ in a compressed form.}\n\n\\noindent \\textsc{Algorithm:} To solve the problem it remains to recognize all squares among a block $B_k$ and an\narithmetic progression $\\prog{a}{p}{t}$ of its occurrences. Since $t$ can be exponentially large relative to\nsize of $\\slp{S}$, the algorithm cannot consecutively check every occurrence of $B_k$.\n\nLet $\\alpha_L, \\alpha_R$ be the output of \\textbf{Period termination} for $\\slp{S}_j, B_k = \nS_j\\substr{(k-1)\\cdot2^{i-2}}{k\\cdot 2^{i-2} -1}$. The positions $\\alpha_L, \\alpha_R$ are called \\emph{defined} if they satisfy the\nfollowing inequalities: $(2k-1)\\cdot2^{i-2} - (a + p\\cdot t) \\leq \\alpha_L$, $\\alpha_R < a + 2^{i-2}$.\nOtherwise they are called \\emph{undefined}. Since $2^{i} - 1$ is the greatest length of a root, the start\npositions of pure squares cannot be further right than $(2k-1)\\cdot2^{i-2} - (a + p\\cdot t)$. Analogously let $\\gamma_L, \\gamma_R$ be the output of\n\\textbf{Period termination} for $\\slp{S}_j, S_j\\substr{a}{a + p\\cdot t}$. The positions $\\gamma_L, \\gamma_R$ are called\n\\emph{defined} if they satisfy the following inequalities: $(k-1)2^{i-2} \\leq \\gamma_L$ and $\\gamma_R < 2(a + p\\cdot\nt) - (k-1)2^{i-2}$. Otherwise they are called \\emph{undefined}. The following lemmas present crucial relations between \n$\\alpha_L, \\alpha_R, \\gamma_L$ and $\\gamma_R$.\n\n\\begin{lem}[{\\rm\\cite{2}}]\nIf one of $\\alpha_R$ or $\\gamma_L$ is defined then the other one is defined as well and $\\alpha_R - \\gamma_L \\leq p$.\n\\end{lem}\n\n\\noindent \\textbf{Case 1: both {\\boldmath $\\alpha_R$} and {\\boldmath $\\gamma_L$} are defined.} \n\n\\begin{lem}[{\\rm\\cite{2}}]\nIf both $\\alpha_R, \\gamma_L$ are defined then:\n\n\\begin{enumerate}\n\\item Squares that contain $B_k$ and are centered at positions $h$ such that $h \\leq \\gamma_L$ may exist only if\n$\\alpha_L$ is defined. These squares constitute a family of squares that corresponds to the difference\n$|x| = a + t'\\cdot p - (k-1)2^{i-2}$, provided that there exists some $t' \\in \\{0\\dots t\\}$ such that\n$\\gamma_L - \\alpha_L = a + t'\\cdot p - (k-1)2^{i-2}$.\n\\item Squares that contain $B_k$ and are centered at positions $h$ such that $\\alpha_R < h$ may exist only if\n$\\gamma_R$ is defined. These squares constitute a family of squares that corresponds to the difference\n$|x| = a + t''\\cdot p - (k-1)2^{i-2}$, provided that there exists some $t'' \\in \\{0\\dots t\\}$ such that\n$\\gamma_L - \\alpha_L = a + t''\\cdot p - (k-1)2^{i-2}$.\n\\end{enumerate}\nNotice that if $\\alpha_R < \\gamma_L$, then squares whose center $h$ satisfies $\\alpha_R < h \\leq\\gamma_L$ may\nexist only if both $\\alpha_L$ and $\\gamma_R$ are defined and $\\gamma_R - \\alpha_R = \\gamma_L - \\alpha_L$.\n\\label{lem:simple_squares}\n\\end{lem}\n\nUsing Lemma~\\ref{lem:simple_squares} the algorithm finds simple families of squares. \nIf $\\alpha_R < \\gamma_L$ the algorithm may find at most three simple families of squares: \n$\\{\\gamma_L - \\alpha_L, p, k \\cdot 2^{i-2}, \\alpha_R\\}, \\{\\gamma_R - \\alpha_R, p, \\alpha_R + 1, \\gamma_L\\},\n\\{\\gamma_L - \\alpha_L, p, \\gamma_L + 1, \\min\\{a,(k+1) \\cdot 2^{i-2}\\}\\}$. Otherwise it may find at most two simple\nfamilies of squares: $\\{\\gamma_L - \\alpha_L, p, k \\cdot 2^{i-2}, \\gamma_L - 1\\}, \\{\\gamma_R - \\alpha_R, p, \\alpha_R,\n\\min\\{a,(k+1) \\cdot 2^{i-2}\\}\\}$.\n\n\\begin{lem}[{\\rm\\cite{2}}]\nIf $\\alpha_R, \\gamma_L$ are defined and $\\gamma_L < \\alpha_R$, then there might be a family of squares\nassociated with each of the differences $|x| = a + p\\cdot t' - (k-1)\\cdot 2^{i-2}$ where $t' \\in \\{0\\dots t\\}$\nwith centers at positions $h$ such that $\\gamma_L < h \\leq \\alpha_R$. The squares in each such family are all\npure squares and they are centered at positions $h$ such that $\\max(\\alpha_L + |x|, \\gamma_L) < h \\leq\n\\min(\\alpha_R, \\gamma_R-|x|)$. Notice that such a family is not empty only if $|x| < \\min(\\alpha_R-\\alpha_L,\n\\gamma_R-\\gamma_L)$.\n\\label{lem:dynamic_pure_squares}\n\\end{lem}\n\nUsing Lemma~\\ref{lem:dynamic_pure_squares} the algorithm finds at most one dynamic family of pure squares and stores\nit in the following way: $\\{k, \\prog{a}{p}{t}, \\alpha_L, \\alpha_R, \\gamma_L, \\gamma_R\\}$. \n\n\\noindent \\textbf{Case 2: both {\\boldmath $\\alpha_R$} and {\\boldmath $\\gamma_L$} are undefined.}\n$S\\substr{\\alpha_L}{\\gamma_R}$ is $p$-periodic and contains squares with different centers and different lengths of\nroots. The algorithm accumulates all squares into a single dynamic family of squares that is stored in the following way: $\\{k,\n\\prog{a}{p}{t}, \\alpha_L, \\gamma_R\\}$.\n\n\\noindent \\textsc{Complexity:} For each central block the algorithm computes four arithmetic progressions that describe all \noccurrences of the block. So the algorithm invokes \\textbf{SubCut} two times and \\textbf{PM} once. For each arithmetic progression and the\nblock, the algorithm calculates $\\alpha_L, \\alpha_R, \\gamma_L$ and $\\gamma_R$. So the algorithm invokes\n\\textbf{Period termination} two times. After that it extracts families of squares and adds them to the S-table. Totally at\nthe main step the algorithm invokes \\textbf{SubCut} at most 16 times, \\textbf{PM} at most 8 times and \\textbf{Period termination} at\nmost 64 times. The main step requires $O(|\\slp{S}|^3 \\cdot \\log |S|)$ time and $O(|\\slp{S}|^2)$ space. The algorithm\nmakes $|\\slp{S}| \\cdot \\log |S|$ steps. Altogether we get the following theorem:\n\n\\begin{thm}\nThere is an algorithm that solves Computing all squares problem using $O(|\\slp{S}|^4 \\cdot \\log^2{|S|})$ time and\n$O(|\\slp{S}| \\cdot \\max(|\\slp{S}|, \\log{|S|}))$ space.\n\\end{thm}\n\n\\section{Conclusion}\n\nWe have presented an algorithm that for a given SLP $\\slp{S}$ deriving a text $S$ fills out a table containing\ninformation about all squares that occur in $S$ in time $O(|\\slp{S}|^4\\cdot \\log^2{|S|})$ using\n$O(|\\slp{S}|\\cdot \\max\\{ |\\slp{S}|, \\log{|S|}\\})$ space. \n\nWe emphasize main features of the algorithm. The algorithm presents a new technique for SLPs processing. \nIt is divided into independent steps in contrast to classical algorithms in this area which consecutively accumulate information. \nAs a result it can be parallelized. The algorithm is quite difficult for practical implementation. \nIt is not excluded that constants hidden in the \"O\" notation are actually very big. The present upper bound for the time complexity \nis rather high and is not matched by any known lower bound. The question whether the upper bound can be lowered to cubic in $|\\mathbb{S}|$ \nremains open.\n\n{\\footnotesize\n\\bibliography{cas_problem_rufidim}{}\n\\bibliographystyle{plain}\n}\n\n\\end{document}", "meta": {"hexsha": "39feef9f6e0aac983295c508eff85147a4fdedde", "size": 23640, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "texfiles/Khvorost/cas_problem_rufidim/cas_problem_rufidim.tex", "max_stars_repo_name": "jaamal/overclocking", "max_stars_repo_head_hexsha": "b40db5a72710c691ca558e22626c5c382fd3677a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "texfiles/Khvorost/cas_problem_rufidim/cas_problem_rufidim.tex", "max_issues_repo_name": "jaamal/overclocking", "max_issues_repo_head_hexsha": "b40db5a72710c691ca558e22626c5c382fd3677a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-04-11T12:58:50.000Z", "max_issues_repo_issues_event_max_datetime": "2015-04-12T10:54:35.000Z", "max_forks_repo_path": "texfiles/Khvorost/cas_problem_rufidim/cas_problem_rufidim.tex", "max_forks_repo_name": "jaamal/overclocking", "max_forks_repo_head_hexsha": "b40db5a72710c691ca558e22626c5c382fd3677a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 67.7363896848, "max_line_length": 158, "alphanum_fraction": 0.7131133672, "num_tokens": 7325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.31282343380725786}}
{"text": "\\documentclass[main_montangero.tex]{subfiles}\n\\begin{document}\n\n\\section{Time-dependent perturbation theory}\n\nWe have an atom or some quantum system, and we manipulate it by sending an EM pulse against it. How will it change?\n\nSay we have some discrete energy levels, and a continuous spectrum after some threshold energy.\nThe photon can excite the ground state \\(\\ket{i} \\) to some excited state \\(\\ket{f} \\), or vice versa.\nThis can happen between discrete energies, or with the continuous energies.\n\nWe need to solve the time-dep Schrödinger equation:\n\n\\begin{equation}\n    i \\hbar \\dv{}{t} \\ket{\\psi(t)} = \\qty[H_0 + \\lambda W(t)]\\ket{\\psi(t)}\n\\end{equation}\n\nWe work with the unperturbed eigenstates \\(H_0 \\ket{\\varphi_n}  = E_n \\ket{\\varphi_n}  \\), we assume \\(\\lambda \\ll 1\\),\nand we say that the starting state at \\(t=0\\) is an unperturbed eigenstate.\n\nWhat is the probability of getting a state \\(f\\)?\n\n\\begin{equation}\n    \\P _{if}(t) = \\abs{\\braket{\\varphi_f}{\\psi(t)} }^2\n\\end{equation}\n\nwe can get resonance.\nFor continuous states this changes a bit but we can generalize.\n\nWe expand\n\n\\begin{equation}\n    \\ket{\\psi(t)} = \\sum c_n(t) \\ket{\\varphi_n}   \\qquad c_n(t) = \\braket{\\varphi_n}{\\psi(t)}\n\\end{equation}\n\nWe can compute the matrix elements of the perturbation: \\(\\bra{\\varphi_n} W(t) \\ket{\\varphi_k} = W_{nk}(t)\\) and of the Hamiltonian:\n\\(\\bra{\\varphi_n} H_0 \\ket{\\varphi_k} = \\delta_{nk} E_n\\). Putting these in the Schrödinger equation, we get\n\n\\begin{equation}\n    i \\hbar \\dv{}{t} c_n(t) = E_n c_n(t) + \\sum _{k} \\lambda W_{nk} c_k (t)\n\\end{equation}\n\nWe go in interaction picture: \\(b_n(t) = c_n(t) \\exp(+i E_n t / \\hbar) \\), which nullifies the unperturbed evolution.\nPutting this inside the equation we get\n\n\\begin{equation}\n    i \\hbar \\dot{b}_n(t) = \\lambda \\sum _k \\exp(i \\omega_{nk}) W_{nk} b_k (t)\n\\end{equation}\n\nwith \\(\\omega_{nk = (E_n - E_k) / \\hbar}\\). We can expand the \\(b_n(t)\\) in \\(\\lambda\\):\n\n\\begin{equation}\n    b_n(t) = \\sum _{i}  b_n ^{(i)} \\lambda^i (t)\n\\end{equation}\n\nWe know that for some \\(i\\) we must have \\(b_n ^{(r)}(t=0) = \\delta_{ni} \\delta_{r0} \\) and so:\n\n\\begin{align}\n    i \\hbar \\dot{b}_n ^{(0)}(t) &= 0  \\\\\n    i \\hbar \\dot{b}_n ^{(r)}(t) &= \\sum _{k} \\exp(i \\omega_{nk} t) W_{nk} b_n ^{r-1}(t)\n\\end{align}\n\nThen to order \\(\\lambda^1\\):\n\n\\begin{equation}\n    i \\hbar \\dot{b}_n (t) = \\exp(i \\omega_{nk}t) W_{nk}(t)\n\\end{equation}\n\n\\begin{equation}\n    b_n^{(1)}(t) = \\frac{1}{i \\hbar} \\int _{0}   ^{t} \\dd{\\tau} \\exp(i \\omega_{ni} \\tau)W_{ni}(\\tau)\n\\end{equation}\n\nSo \\(\\P _{if}(t) = \\abs{c_f(t)}^2 = \\abs{b_f(t)}^2\\)\n\n\\begin{equation}\n    \\P _{if}(t) = \\frac{\\lambda^2}{\\hbar^2} \\abs{\\int _{0}   ^{t} \\dd{\\tau} \\exp(i \\omega_{fi} \\tau)W_{gi}(\\tau)  }^2\n\\end{equation}\n\n\\paragraph{Example}\n\nLet us take a \\(W(t) = - W \\sin(\\omega t)\\). Then,\n\n\\begin{equation}\n    b_n^{(1)}(t) = - \\frac{W_{ni}}{2 \\hbar} \\int _{0}   ^{t} \\dd{\\tau} \\qty(\\exp(i (\\omega_{ni} - \\omega) \\tau) - \\exp(-i (\\omega_{ni} - \\omega) \\tau))\n\\end{equation}\n\nSo,\n\n\\begin{equation}\n    \\P _{if} (t, \\omega) = \\frac{\\abs{W_{if}}^2 }{4 \\hbar^2} F(t, \\omega - \\omega_{fi})\n\\end{equation}\n\nwhere\n\n\\begin{equation}\n    F(\\omega, t) = \\qty(\\frac{\\sin(\\omega t/2)}{\\omega/2})^2\n\\end{equation}\n\nThis is a sinc squared.\n\n\\subsection{Fermi's golden rule}\n\nIs applying what we saw to continuous spectrums. Now we have some \\(\\braket{\\alpha}{\\alpha'} = \\delta(\\alpha - \\alpha') \\). We want to see what is the probability of the final state being in a neighbourhood of \\(\\alpha\\).\n\nWe define the state density by \\(\\dd{\\alpha} = \\rho(\\beta, E ) \\dd{\\beta} \\dd{E} \\) where the index \\(\\beta\\) takes account of the degeneracy, which can be continuous.\n\n\\begin{equation}\n    \\delta \\P \\qty(\\alpha_f, t) = \\int   \\dd{\\alpha} \\abs{\\braket{\\alpha}{\\psi(t)} }^2\n\\end{equation}\n\nwhere \\(\\alpha \\in D_f\\). So, we can change variable into\n\n\\begin{equation}\n    \\delta \\P \\qty(\\alpha_f, t) = \\int  \\abs{\\braket{\\beta, E}{\\psi(t)} }^2 \\rho(E, \\beta)  \\dd{E} \\dd{\\beta}\n\\end{equation}\n\nWe can write\n\n\\begin{equation}\n    \\abs{\\braket{\\beta, E}{\\psi(t)} }^2\n    = \\frac{1}{\\hbar^2} \\abs{\\bra{\\beta, E} W \\ket{\\varphi_i}  }^2 F\\qty(t, \\frac{E-E_i}{\\hbar})\n\\end{equation}\n\nwhere \\(\\lim_{t \\rightarrow \\infty} F\\qty(t, \\frac{E-E_i}{\\hbar}) = 2 \\pi i \\hbar \\delta(E - E_i)\\).\nThen\n\n\\begin{equation}\n    \\delta \\P (\\varphi_i, \\alpha_f, t)\n    = \\delta \\beta_f \\frac{2 \\pi i t}{\\hbar} \\abs{\\bra{\\beta_f, E_f = E_i} W \\ket{\\varphi_i}}^2\n    \\rho(\\beta, E_f)\n\\end{equation}\n\nThen\n\n\\begin{equation}\n    W(\\varphi_i, \\alpha_f) = \\dv{}{t} \\fdv{\\P}{\\beta} = \\frac{\\pi}{2 \\hbar}\n    \\abs{\\bra{\\beta_f, E_f = E_i + \\hbar \\omega} W \\ket{\\varphi_i}}^2\n    \\rho (\\beta_f, E_f = E_i + \\hbar \\omega)\n\\end{equation}\n\nThe more states we have in the final configuration, the greater the probability. We are assuming here that the state density is constant in the degeneracy, and we can split the degeneracy and energy contributions.\n\n\\section{How to build a quantum computer}\n\nDi Vincenzo criteria (2000): what is needed to have a true quantum computer.\n\n\\begin{enumerate}\n    \\item Scalability, well defined qubit;\n    \\item Reset: we must be able to reset the computer surely into a state \\(\\ket{0} \\);\n    \\item Long coherence time wrt gate duration;\n    \\item Universal set of gates;\n    \\item Efficient readout;\n\\end{enumerate}\n\nIf our decoherence time is \\(\\tau_d\\) and our gate time is \\(\\tau_g\\), we need \\(\\tau_d / \\tau_g \\gtrsim 10^4\\) in order to have time to do error correction.\n\nProposals:\n\n\\begin{itemize}\n    \\item Cauidiy: QED;\n    \\item Solid-state electron spins;\n    \\item Cold atoms;\n    \\item Trapped ions;\n    \\item Superconductive circuits.\n\\end{itemize}\n\n\\subsection{Trapped ions}\n\nWe can trap them with electric fields: Paul trap. We cannot do the intuitive thing, because of Gausses' law. We can work around it by making them time-dependent. Think of it like this: saddle which spins, an object in the saddle point will be stable if the rotation is fast enough.\n\nWe get three harmonic oscillators, with \\(\\omega_{x,y} \\gg \\omega_z\\). The \\(z\\) direction is the 'quantum' degree of freedom: the state comes from the atom state \\(i\\) and the oscillator state \\(n\\).\n\nCan we put many qubits in there? Our Hamiltonian will be\n\n\\begin{equation}\n    H  = \\sum  \\frac{p_i^2}{2m} + \\sum  \\frac{1}{2} \\omega_z^2 z_i^2\n    + \\sum_i \\sum_{j<i} \\frac{q^2}{4 \\pi \\varepsilon_0 \\abs{r_i - r_j} }\n\\end{equation}\n\nThey repel each other, we can diagonalize this matrix and get the modes of oscillation.\n\nSo we have \\(\\ket{\\alpha_1 \\alpha_2 \\dots \\alpha_N n} \\) where the \\(n\\) is the global oscillation. Our single qubit is \\(\\ket{\\alpha_i n} \\). We have the states \\(\\ket{g, 0} \\), \\(\\ket{g, 1} \\), \\(\\ket{g, 2} \\) \\dots and \\(\\ket{e, 0} \\), \\(\\ket{e, 1} \\) \\dots\n\nWe can use a laser to excite the ground state into a vibrational excited state... we choose the right frequency to go from \\(\\ket{g, k} \\) to \\(\\ket{e, k-1} \\) which spontaneously decays into \\(\\ket{g, k-1} \\). This is \\emph{side-band cooling}. This can prepare a state with \\(\\P > 99.9\\%\\).\n\nCirac-Zoller Gate: allows us to entangle states with stuff like a CPHASE by interacting with the global vibration.\n\n\\subsection{Superconductive qubit}\n\nSomething like Bose-condensing electrons: Cooper pairs, with opposing momentums: so the entanglement is in the Fourier space, they are very delocalized in the position space.\nCooper pair currents are the superconductive currents.\n\nWe use Josephson juctions inside regular circuits:\ntwo superconductors, separated by a thin insulant. Cooper pairs can tunnel through the insulant.\n\nCharge qubit: quantum numbers inside the superconductor are \\(n\\), \\(\\varphi\\), with \\([n, \\varphi] = i\\).\n\n\\begin{equation}\n    H = E_C \\qty(n-n_g)^2 - E_J \\cos \\varphi\n\\end{equation}\n\nwith \\(n_g - c_g V /(2e)\\), and \\(E_C = (2e)^2 / (2(C_J + C_g))\\). We can write the eigenstates as \\(\\ket{n} \\), and\n\n\\begin{equation}\n    H = E_C \\sum  (n-n_g) \\dyad{n} - \\frac{1}{2} E_J \\sum \\qty(\\ketbra{n+1}{n} + \\ketbra{n}{n+1}  )\n\\end{equation}\n\n\\end{document}\n", "meta": {"hexsha": "17293daaca4d94e128f034b887844ace55b796ca", "size": 8035, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "info_Q/montangero/12-6-19.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "info_Q/montangero/12-6-19.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "info_Q/montangero/12-6-19.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 38.4449760766, "max_line_length": 291, "alphanum_fraction": 0.6568761668, "num_tokens": 2821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3128234261417961}}
{"text": "\\documentclass[a4paper,10pt]{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage{amssymb,amsmath,amsfonts}\n\\usepackage{hyperref}\n\\usepackage[a4paper, margin=.5in]{geometry}\n\n%opening\n\\title{Documentation: A Unifying Mechanistic Model of Excitatory-Inhibitory Interactions in the Auditory Cortex}\n\\author{Youngmin Park}\n\n\\newcommand{\\y}[1]{{\\texttt{#1}}}\n\n\\begin{document}\n\n\\maketitle\n\n%\\begin{abstract}\n\n%\\end{abstract}\n\n\\section{Introduction}\nThe primary tools of this paper are Python (with numpy, scipy, matplotlib), XPPAUTO (XPPAUT or XPP for short) \\cite{ermentrout2002simulating}, a Python binding for XPP, \\y{Py\\_XPPCALL} \\cite{xppy}, and Brian2 \\cite{Stimberg595710}. Please contact me with any questions about these programs: \\y{ympark1988@gmail.com}\\footnote{I used XPP extensively in my PhD, and XPP was created by and continues to be developed by Bard Ermentrout, my doctoral advisor. In addition, I am one of the primary contributors to \\y{Py\\_XPPCALL}.}.\n\nI highly recommend using Ubuntu, since the most stable versions of XPP are currently on Ubuntu. At the time of writing, I have used Ubuntu 16.04 (Python 2.7.12, numpy 1.15.2, scipy 1.1.0, matplotlib 2.2.3), Ubuntu 18.04.2 (Python 2.7.15rc1, numpy 1.15.2, scipy 1.1.0, matplotlib 2.2.3), and XPPAUT version 8 to successfully run all code.\n\n\\section{Rate Models}\n\nRate models are implemented in XPPAUTO. In order to plot the simulations, I run XPPAUTO through the Python binding \\y{Py\\_XPPCALL}. \n\n\\subsection{XPPAUTO}\nAll rate models were implemented in \\texttt{XPPAUTO} for convenience. XPP auto uses an almost plain-text file format for simulating ordinary differential equations (ODEs). There is extensive documentation on XPPAUTO on Bard's website:\n\\url{http://www.math.pitt.edu/~bard/xpp/help/xppodes.html}. The linked page provides full documentation of ode file syntax. XPPAUTO also comes with a graphical user interface (GUI), but this will not be needed for this documentation. The XPP .ode files for this project are located in the directory \\url{https://github.com/geffenlab/park_geffen/rate_models/xpp}.\n\nLet us take a look at one of the ode files, \\texttt{cols3\\_fs.ode}, which is the three-unit rate model for the forward suppression paradigm. The file begins with a function definition and a bunch of parameters:\n\\begin{verbatim}\nf(x)=al*heav(x)*x*heav(1/al-x)+heav(x-1/al)\ndan(x)=exp(-tl*x)\np al = 3\n\np wee=1.1,wep=2,wes=1\n# either wpe=1.2, or wpp=1.8 to reduce SOM disinhibition activity.\np wpe=1.,wpp=2,wps=2\n\np wse=6,wss=0,wsp=0\np wee2=1,wpe2=1.25,wse2=.125\n#p wee2=1,wpe2=1.5,wse2=.25\n\npar tau1=1,tau2=1\npar et=.7,pt=1,st=1\npar pv_opto=0,som_opto=0\n\np q=1.3,tl=1\np taud1=150,taud2=10\np tde1=150,tde2=2\np lat=.65\n\\end{verbatim}\nComment lines are denoted by the pound symbol (\\#). The function \\texttt{f} is the firing-rate function, which corresponds to Equation (2) in the manuscript (There is a typo in the current manuscript. All simulations were run using the correct $f$ as shown in the code). The function is zero until $x=0$, at which point the function increases linearly with slope $\\text{al}=3$ as a function of $x$, until the function reaches the value 1 (when $x=1/\\text{al}$, at which point the function ``saturates'' at the value 1. The second function, which I named \\y{dan}, is a decaying exponential with rate \\y{tl}, which we will later use to modulate the square-wave inputs into the model. We use the same firing rate function for all models, which is a common choice in modeling studies \\cite{natan2015complementary,yarden2017stimulus}.\n\nThe notation \\texttt{p} and \\texttt{par} both denote a line consisting of parameters. The first set of parameters:\n\\begin{verbatim}\np wee=1.1,wep=2,wes=1\np wpe=1.,wpp=2,wps=2\n\np wse=6,wss=0,wsp=0\np wee2=1,wpe2=1.25,wse2=.125\n\\end{verbatim}\nare for recurrent excitation (\\texttt{wee}), PV-to-Pyr inhibition (\\texttt{wep}), SOM-to-Pyr inhibition (\\texttt{wes}), Pyr-to-PV excitation (\\texttt{wpe}), recurrent PV inhibition (\\y{wpp}), SOM-to-PV inhibition (\\y{wps}), Pyr-to-SOM excitation (\\y{wse}), PV-to-SOM inhibition (\\y{wsp}), and recurrent SOM inhibition (\\y{wss}). The remaining terms are for the lateral weights. Lateral Pyr-to-Pyr (\\y{wee2}), lateral Pyr-to-PV (\\y{wpe2}), and lateral Pyr-to-SOM (\\y{wse2}). These parameters appear in Equation 4, and in the unit equations on page 2.\n\nThe next set of parameters:\n\\begin{verbatim}\npar tau1=1,tau2=1\npar et=.7,pt=1,st=1\npar pv_opto=0,som_opto=0\n\\end{verbatim}\nAre time constants \\y{tau1} and \\y{tau2} are for the inhibitory populations, PV, and SOM, respectively. This rate model is written so that 1 time unit is 10ms, i.e., \\y{tau1=1} means $\\tau_1 = 10$ms \\cite{tsodyks1997neural,natan2015complementary}. If needed, one could perform the necessary transformation in time so the model displays the correct time units by default.\n\nThe next line is for thresholds in the excitatory activity \\y{et}, PV activity \\y{pt}, and SOM activity \\y{st}. These thresholds are minimum values beyond which the population activity can influence the postsynaptic population. Finally, the \\y{pv\\_opto} and \\y{som\\_opto} parameters set the level of optogenetic \\textit{inactivation}, i.e., positive values of \\y{pv\\_opto} inactivation PVs, and likewise for \\y{som\\_opto}. In the paper I flip these numbers for readability.\n\nNext up:\n\\begin{verbatim}\np q=1.3,tl=1\np taud1=150,taud2=10\np tde1=150,tde2=2\np lat=.65 \n\\end{verbatim}\n\\y{q} is the strength of the thalamic inputs into the model. \\y{tl} is the decay time constant in the exponential function \\y{dan}. The depression time constants are \\y{taud1} and \\y{taud2}, again in the same units, so $\\tau_{D_1} = 1500$ms and $\\tau_{D_2} = 100$ms. We can ignore \\y{tde1,tde2} as they are not used in the code. The parameter \\y{lat} determines the strength of lateral thalamic inputs.\n\nThe next chunk of code sets up the stimuli in the forward suppression paradigm.\n\\begin{verbatim}\npar t0=10,dur=5,isi=2\n\nt1on=t0\nt1off=t1on+dur\nt2on=t1off+isi\nt2off=t2on+dur\n\nt3on=t2off+isi\nt3off=t3on+dur\nt4on=t3off+isi\nt4off=t4on+dur\n\nt5on=t4off+isi\nt5off=t5on+dur\nt6on=t5off+isi\nt6off=t6on+dur\n\nt7on=t6off+isi\nt7off=t7on+dur\nt8on=t7off+isi\nt8off=t8on+dur\n\n# thalamic inputs with fast timescale depression\ngt1(x)=heav(x-t1on)*heav(t1off-x)*dan(x-t1on)\ngt2(x)=heav(x-t2on)*heav(t2off-x)*dan(x-t2on)\ngt3(x)=heav(x-t3on)*heav(t3off-x)*dan(x-t3on)\ngt4(x)=heav(x-t4on)*heav(t4off-x)*dan(x-t4on)\n\ngt5(x)=heav(x-t5on)*heav(t5off-x)*dan(x-t5on)\ngt6(x)=heav(x-t6on)*heav(t6off-x)*dan(x-t6on)\ngt7(x)=heav(x-t7on)*heav(t7off-x)*dan(x-t7on)\ngt8(x)=heav(x-t8on)*heav(t8off-x)*dan(x-t8on)\n\npar mode=1\ni1(x)=g1*q*if(mode-1)then(0)else(gt1(x))\ni2(x)=g2*q*if(mode-2)then(gt2(x))else(gt1(x)+gt2(x))\ni3(x)=g3*q*if(mode-3)then(0)else(gt1(x))\n\\end{verbatim}\n\nThe functions \\y{gt1(x)} through \\y{gt8(x)} represent 8 different stimuli with stimulus onset times of \\y{t1on} through \\y{t8on}, stimulus offset times of \\y{t1off} through \\y{t8off}. The \\y{heav} functions are heaviside functions, and the multiplication of two of them as written forms a square pulse. This pulse is then modulated by the exponential decay function \\y{dan}. For the forward suppression paradigm, we only need two stimuli, so we only use \\y{gt1} and \\y{gt2} for the rest of the code.\n\nThe \\y{mode} parameter sets which unit receives the first input. If \\y{mode=1}, then\n\\begin{verbatim}\ni1(x)=g1*q*gt1(x)\ni2(x)=g2*q*gt2(x)\ni3(x)=0\n\\end{verbatim}\nFor more information on how the if statement works in XPP, see the bottom of \\url{http://www.math.pitt.edu/~bard/xpp/help/xppodes.html}. If the \\y{mode} parameter is set to \\y{mode=2}, then\n\\begin{verbatim}\ni1(x)=0\ni2(x)=g2*q*(gt1(x)+gt2(x))\ni3(x)=0\n\\end{verbatim}\nand so on. The terms \\y{g1} and \\y{g2} are variables and satisfy the equations\n\\begin{verbatim}\ng1'=(1-g1)/taud1-i1(y)/taud2\ng2'=(1-g2)/taud1-i2(y)/taud2\ng3'=(1-g3)/taud1-i3(y)/taud2\n\\end{verbatim}\nwhere \\y{y'=1} and all \\y{g1,g2,g3} are initialized with a value of 1. The trivial ODE \\y{y'=1} is needed for technical reasons related to XPP that isn't too important for now. Anyway, as \\y{i1(y)} activates, it ``depletes'' vesicles and forces \\y{g1} to decay on a fast timescale. With no other activation of \\y{i1}, \\y{g1} recovers slowly back to its original value of 1.\n\nNow we finally reach the actual model equations:\n\\begin{verbatim}\nu1'=-u1+f(wee*u1-(wep-damp*(1-g1))*p1-(wes+samp*(1-g1))*s1-et+i1(y)+i2(y)*lat+wee2*u2/1.5)\np1'=(-p1+f(wpe*u1-wpp*p1-wps*s1-pt +i1(y)+i2(y)*lat +wpe2*u2-pv_opto ))/tau1\ns1'=(-s1+f(wse*u1-wsp*p1-wss*s1-st                  +wse2*u2-som_opto ))/tau2\n\nu2'=-u2+f(wee*u2-(wep-damp*(1-g2))*p2-(wes+samp*(1-g2))*s2-et+(i1(y)+i3(y))*lat+i2(y)+wee2*(u1+u3)/2)\np2'=(-p2+f(wpe*u2-wpp*p2-wps*s2-pt +(i1(y)+i3(y))*lat+i2(y)+wpe2*(u1+u3)/2 -pv_opto ))/tau1\ns2'=(-s2+f(wse*u2-wsp*p2-wss*s2-st                         +wse2*(u1+u3)/2 -som_opto ))/tau2\n\nu3'=-u3+f(wee*u3-(wep-damp*(1-g3))*p3-(wes+samp*(1-g3))*s3-et+i2(y)*lat+i3(y)+wee2*u2/1.5)\np3'=(-p3+f(wpe*u3-wpp*p3-wps*s3-pt +i2(y)*lat+i3(y) +wpe2*u2-pv_opto ))/tau1\ns3'=(-s3+f(wse*u3-wsp*p3-wss*s3-st                  +wse2*u2-som_opto ))/tau2\n\\end{verbatim}\nThese are the implemented versions of the 3 unit equations from the manuscript:\nTh first or left unit satisfies\n\\begin{align*}\n \\tau_u u_1' &= -u_1 + f( w_{ee} u_1 - (w_{ep}(t)-aD_1)p_1 - (w_{es}(t)+b F_1)s_1 + qI_1(t) + w_{ee}^* u_2),\\\\\n \\tau_p p_1' &= -p_1 + f( w_{pe} u_1 - w_{pp}p_1 - w_{ps}s_1 + I_\\text{Opt,PV} + qI_1(t) + w_{pe}^* u_2),\\\\\n \\tau_s s_1' &= -s_1 + f( w_{se} u_1 - w_{sp}p_1 - w_{ss}s_1 + I_\\text{Opt,SOM} + w_{se}^* u_2),\n\\end{align*}\nwhere $I_1 = i_1(t) +i_2(t)\\alpha$. The second, or center unit, satisfies\n\\begin{align*}\n \\tau_u u_2' &= -u_2 + f( w_{ee} u_2 - (w_{ep}(t)-aD_2)p_2 - (w_{es}(t)+b F_2)s_2 + qI_2(t) + w_{ee}^* (u_1+u_3)/2),\\\\\n \\tau_p p_2' &= -p_2 + f( w_{pe} u_2 - w_{pp}p_2 - w_{ps}s_2 + I_\\text{Opt,PV} + qI_2(t) + w_{pe}^* (u_1+u_3)/2),\\\\\n \\tau_s s_2' &= -s_2 + f( w_{se} u_2 - w_{sp}p_2 - w_{ss}s_2 + I_\\text{Opt,SOM} + w_{se}^* u_2),\n\\end{align*}\nwhere $I_2(t) = (i_1(t)+i_3(t))\\alpha +i_2(t)$. Finally, the third, or right unit, satisfies\n\\begin{align*}\n \\tau_u u_3' &= -u_3 + f( w_{ee} u_3 - (w_{ep}(t)-aD_3)p_3 - (w_{es}(t)+b F_3)s_3 + qI_3(t) + w_{ee}^* u_2),\\\\\n \\tau_p p_3' &= -p_3 + f( w_{pe} u_3 - w_{pp}p_3 - w_{ps}s_3 + I_\\text{Opt,PV} + qI_3(t) + w_{pe}^* u_2),\\\\\n \\tau_s s_3' &= -s_3 + f( w_{se} u_3 - w_{sp}p_3 - w_{ss}s_3 + I_\\text{Opt,SOM} + w_{se}^* u_2), \n\\end{align*}\nwhere $I_3 = i_2(t) +i_3(t)\\alpha$.\n\nThe remaining lines are mostly related to using the XPPAUTO GUI. Choices that affect the integration are\n\\begin{verbatim}\n@ bounds=100000\n@ maxstor=1000000\n@ total=200\n@ dt=.1\n\\end{verbatim}\n\\y{bounds} is simply the maximum possible value of any solution before XPPAUTO gives up. \\y{maxstor} sets the max storage XPPAUTO is allowed to take from memory. \\y{total} is the total time of the simulation, and \\y{dt} is the time step.\n\n\\subsection{Python Visualization}\nThese XPP ode files can be run using the XPP GUI, but we will run them using Python using \\y{Py\\_XPPCALL}. I have tried to include enough documentation to help users understand the basics \\url{https://github.com/youngmp/Py_XPPCALL}. The Python files that run the XPP files are are located in \\url{https://github.com/geffenlab/park_geffen/rate_models}. The Python file that reads the ODE file from the example above is called \\y{cols3\\_fs.py}. You should be able to run the python file directly.\n\\begin{verbatim}\n$ python cols3_fs.py\n\\end{verbatim}\nThere will be lots of text that appears. These were mostly for debugging purposes and can be turned off by commenting the print statements in this file and in \\y{xppcall.py}. After the script runs, a few plots should appear. I like to set up the plotting framework in the individual Python files before finalizing them in \\y{generate\\_figures.py}.\n\nThe \\y{main} function calls all the relevant files. In brief, the loop runs three different stimulus patterns. The first stimulates the left unit then the center unit with 50ms tones and a 20ms inter-stimulus-interval. The second stimulates the center unit twice with the same time intervals. The third stimulates the right unit then the center unit with the same time intervals. This is a simple version of the forward suppression paradigm. These three sets of stimuli are repeated for PV inactivation and SOM inactivation. The max firing rate response is then recorded into a matrix and plotted.\n\nMuch of this logic appears in its final form in the function \\y{r3\\_s3\\_fs\\_full} in \\y{generate\\_figures.py}. The difference is that the function \\y{r3\\_s3\\_fs\\_full} includes the spiking model simulation and plots. I've tried to comment on most things... Let me know if you have any questions.\n\nThe remaining Python files for simulating the rate model, \\y{cols3\\_ssa} and \\y{natan2015\\_simple\\_linear} have a similar construction. The \\y{main} function in each script contains all the preliminary plotting/visualization code, which you can use to tinker and learn the ins and outs of the python/xpp interface. Seriously, play with those all you want.\n\nThe final version of the plotting functions appear in \\y{generate\\_figures.py}. Don't change those unless you're familiar with the code.\n\n\n\\section{Spiking Models}\n\n\\section{Generating Figures}\n\n\\y{generate\\_figures.py} is the master plotting function for the paper. Most figure papers are generated here, except for a couple that were created in Inkscape. This file serves as a technical documentation of the code. In the main function, comments note which function belong to which figure.\n\n\\begin{thebibliography}{1}\n\n\\bibitem{ermentrout2002simulating}\nBard Ermentrout.\n\\newblock {\\em Simulating, analyzing, and animating dynamical systems: a guide\n  to XPPAUT for researchers and students}, volume~14.\n\\newblock Siam, 2002.\n\n\\bibitem{natan2015complementary}\nRyan~G Natan, John~J Briguglio, Laetitia Mwilambwe-Tshilobo, Sara~I Jones, Mark\n  Aizenberg, Ethan~M Goldberg, and Maria~Neimark Geffen.\n\\newblock Complementary control of sensory adaptation by two types of cortical\n  interneurons.\n\\newblock {\\em Elife}, 4, 2015.\n\n\\bibitem{xppy}\nIlya Prokin and Youngmin Park.\n\\newblock Pyxppcall.\n\\newblock \\url{https://github.com/iprokin/Py_XPPCALL}, 2017.\n\n\\bibitem{Stimberg595710}\nMarcel Stimberg, Romain Brette, and Dan F.~M. Goodman.\n\\newblock Brian 2: an intuitive and efficient neural simulator.\n\\newblock {\\em bioRxiv}, 2019.\n\n\\bibitem{tsodyks1997neural}\nMisha~V Tsodyks and Henry Markram.\n\\newblock The neural code between neocortical pyramidal neurons depends on\n  neurotransmitter release probability.\n\\newblock {\\em Proceedings of the national academy of sciences},\n  94(2):719--723, 1997.\n\n\\bibitem{yarden2017stimulus}\nTohar~S Yarden and Israel Nelken.\n\\newblock Stimulus-specific adaptation in a recurrent network model of primary\n  auditory cortex.\n\\newblock {\\em PLoS computational biology}, 13(3):e1005437, 2017.\n\n\\end{thebibliography}\n\\end{document}\n", "meta": {"hexsha": "7d757833c7066f176e6eabdea47ab21a2131f192", "size": 14956, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/documentation_standalone.tex", "max_stars_repo_name": "geffenlab/park_geffen", "max_stars_repo_head_hexsha": "c19671d9ce05db11423723c45dc85be389878ea9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-07T15:23:54.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-07T15:23:54.000Z", "max_issues_repo_path": "docs/documentation_standalone.tex", "max_issues_repo_name": "geffenlab/park_geffen", "max_issues_repo_head_hexsha": "c19671d9ce05db11423723c45dc85be389878ea9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/documentation_standalone.tex", "max_forks_repo_name": "geffenlab/park_geffen", "max_forks_repo_head_hexsha": "c19671d9ce05db11423723c45dc85be389878ea9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-02T16:01:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-02T16:01:03.000Z", "avg_line_length": 58.1945525292, "max_line_length": 829, "alphanum_fraction": 0.7326156726, "num_tokens": 5149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3128234261417961}}
{"text": "%\\documentclass[fleqn]{article}\n%\\usepackage{mathptmx}\n%\n%\\DeclareMathSymbol{\\Gamma}  {\\mathalpha}{letters}{\"00}\n%\\DeclareMathSymbol{\\Delta}  {\\mathalpha}{letters}{\"01}\n%\\DeclareMathSymbol{\\Theta}  {\\mathalpha}{letters}{\"02}\n%\\DeclareMathSymbol{\\Lambda} {\\mathalpha}{letters}{\"03}\n%\\DeclareMathSymbol{\\Xi}     {\\mathalpha}{letters}{\"04}\n%\\DeclareMathSymbol{\\Pi}     {\\mathalpha}{letters}{\"05}\n%\\DeclareMathSymbol{\\Sigma}  {\\mathalpha}{letters}{\"06}\n%\\DeclareMathSymbol{\\Upsilon}{\\mathalpha}{letters}{\"07}\n%\\DeclareMathSymbol{\\Phi}    {\\mathalpha}{letters}{\"08}\n%\\DeclareMathSymbol{\\Psi}    {\\mathalpha}{letters}{\"09}\n%\\DeclareMathSymbol{\\Omega}  {\\mathalpha}{letters}{\"0A}\n%\n%\\DeclareMathSymbol{\\alpha}  {\\mathalpha}{letters}{\"0B}\n%\\DeclareMathSymbol{\\beta}   {\\mathalpha}{letters}{\"0C}\n%\\DeclareMathSymbol{\\gamma}  {\\mathalpha}{letters}{\"0D}\n%\\DeclareMathSymbol{\\delta}  {\\mathalpha}{letters}{\"0E}\n%\\DeclareMathSymbol{\\epsilon}{\\mathalpha}{letters}{\"0F}\n%\\DeclareMathSymbol{\\zeta}   {\\mathalpha}{letters}{\"10}\n%\\DeclareMathSymbol{\\eta}    {\\mathalpha}{letters}{\"11}\n%\\DeclareMathSymbol{\\theta}  {\\mathalpha}{letters}{\"12}\n%\\DeclareMathSymbol{\\iota}   {\\mathalpha}{letters}{\"13}\n%\\DeclareMathSymbol{\\kappa}  {\\mathalpha}{letters}{\"14}\n%\\DeclareMathSymbol{\\lambda} {\\mathalpha}{letters}{\"15}\n%\\DeclareMathSymbol{\\mu}     {\\mathalpha}{letters}{\"16}\n%\\DeclareMathSymbol{\\nu}     {\\mathalpha}{letters}{\"17}\n%\\DeclareMathSymbol{\\xi}     {\\mathalpha}{letters}{\"18}\n%\\DeclareMathSymbol{\\pi}     {\\mathalpha}{letters}{\"19}\n%\\DeclareMathSymbol{\\rho}    {\\mathalpha}{letters}{\"1A}\n%\\DeclareMathSymbol{\\sigma}  {\\mathalpha}{letters}{\"1B}\n%\\DeclareMathSymbol{\\tau}    {\\mathalpha}{letters}{\"1C}\n%\\DeclareMathSymbol{\\upsilon}{\\mathalpha}{letters}{\"1D}\n%\\DeclareMathSymbol{\\phi}    {\\mathalpha}{letters}{\"1E}\n%\\DeclareMathSymbol{\\chi}    {\\mathalpha}{letters}{\"1F}\n%\\DeclareMathSymbol{\\psi}    {\\mathalpha}{letters}{\"20}\n%\\DeclareMathSymbol{\\omega}  {\\mathalpha}{letters}{\"21}\n%\\DeclareMathSymbol{\\varepsilon} {\\mathalpha}{letters}{\"22}\n%\\DeclareMathSymbol{\\vartheta}   {\\mathalpha}{letters}{\"23}\n%\\DeclareMathSymbol{\\varpi}      {\\mathalpha}{letters}{\"24}\n%\\DeclareMathSymbol{\\varrho}     {\\mathalpha}{letters}{\"25}\n%\\DeclareMathSymbol{\\varsigma}   {\\mathalpha}{letters}{\"26}\n%\\DeclareMathSymbol{\\varphi}     {\\mathalpha}{letters}{\"27}\n%\n%\\DeclareMathSymbol{\\dit}{\\mathord}{letters}{`d}\n%\\DeclareMathSymbol{\\dup}{\\mathord}{operators}{`d}\n%\n%\\nofiles\n%\n%\\parindent 0pt\n%\\mathindent 1em\n\n\\def\\test#1{#1}\n\n\\def\\testnums{%\n  \\test 0 \\test 1 \\test 2 \\test 3 \\test 4 \\test 5 \\test 6 \\test 7\n  \\test 8 \\test 9 }\n\\def\\testupperi{%\n  \\test A \\test B \\test C \\test D \\test E \\test F \\test G \\test H\n  \\test I \\test J \\test K \\test L \\test M }\n\\def\\testupperii{%\n  \\test N \\test O \\test P \\test Q \\test R \\test S \\test T \\test U\n  \\test V \\test W \\test X \\test Y \\test Z }\n\\def\\testupper{%\n  \\testupperi\\testupperii}\n\n\\def\\testloweri{%\n  \\test a \\test b \\test c \\test d \\test e \\test f \\test g \\test h\n  \\test i \\test j \\test k \\test l \\test m }\n\\def\\testlowerii{%\n  \\test n \\test o \\test p \\test q \\test r \\test s \\test t \\test u\n  \\test v \\test w \\test x \\test y \\test z \n  \\test\\imath \\test\\jmath }\n\\def\\testlower{%\n  \\testloweri\\testlowerii}\n\n\\def\\testupgreeki{%\n  \\test A \\test B \\test\\Gamma \\test\\Delta \\test E \\test Z \\test H\n  \\test\\Theta \\test I \\test K \\test\\Lambda \\test M }\n\\def\\testupgreekii{%\n  \\test N \\test\\Xi \\test O \\test\\Pi \\test P \\test\\Sigma \\test T\n  \\test\\Upsilon \\test\\Phi \\test X \\test\\Psi \\test\\Omega \n  \\test\\nabla }\n\\def\\testupgreek{%\n  \\testupgreeki\\testupgreekii}\n\n\\def\\testlowgreeki{%\n  \\test\\alpha \\test\\beta \\test\\gamma \\test\\delta \\test\\epsilon\n  \\test\\zeta \\test\\eta \\test\\theta \\test\\iota \\test\\kappa \\test\\lambda\n  \\test\\mu }\n\\def\\testlowgreekii{%\n  \\test\\nu \\test\\xi \\test o \\test\\pi \\test\\rho \\test\\sigma \\test\\tau\n  \\test\\upsilon \\test\\phi \\test\\chi \\test\\psi \\test\\omega }\n\\def\\testlowgreekiii{%\n  \\test\\varepsilon \\test\\vartheta \\test\\varpi \\test\\varrho\n  \\test\\varsigma \\test\\varphi}\n\\def\\testlowgreek{%\n  \\testlowgreeki\\testlowgreekii\\testlowgreekiii}\n\n\n%\\begin{document}\n\n\\section{Math Alphabets}\n\nMath Italic (\\texttt{\\string\\mathnormal})\n\\def\\test#1{\\mathnormal{#1},}\n\\begin{eqnarray*}\n  && {\\testnums}\\\\\n  && {\\testupper}\\\\\n  && {\\testlower}\\\\ \n  && {\\testupgreek}\\\\\n  && {\\testlowgreek}\n\\end{eqnarray*}%\n\nMath Roman (\\texttt{\\string\\mathrm})\n\\def\\test#1{\\mathrm{#1},}\n\\begin{eqnarray*}\n  && {\\testnums}\\\\\n  && {\\testupper}\\\\\n  && {\\testlower}\\\\ \n  && {\\testupgreek}\n\\end{eqnarray*}%\n\n%Math Italic Bold\n%\\def\\test#1{\\mathbm{#1},}\n%\\begin{eqnarray*}\n%  && {\\testnums}\\\\\n%  && {\\testupper}\\\\\n%  && {\\testlower}\\\\ \n%  && {\\testupgreek}\\\\\n%  && {\\testlowgreek}\n%\\end{eqnarray*}%\n\n%Math Bold (\\texttt{\\string\\mathbf})\n%\\def\\test#1{\\mathbf{#1},}\n%\\begin{eqnarray*}\n%  && {\\testnums}\\\\\n%  && {\\testupper}\\\\\n%  && {\\testlower}\\\\ \n%  && {\\testupgreek}\n%\\end{eqnarray*}%\n\nCaligraphic (\\texttt{\\string\\mathcal})\n\\def\\test#1{\\mathcal{#1},}\n\\begin{eqnarray*}\n  && {\\testupper}\n\\end{eqnarray*}%\n\n%Script (\\texttt{\\string\\mathscr})\n%\\def\\test#1{\\mathscr{#1},}\n%\\begin{eqnarray*}\n%  && {\\testupper}\n%\\end{eqnarray*}%\n\n%Fraktur (\\texttt{\\string\\mathfrak})\n%\\def\\test#1{\\mathfrak{#1},}\n%\\begin{eqnarray*}\n%  && {\\testupper}\\\\\n%  && {\\testlower}\n%\\end{eqnarray*}%\n\n%Blackboard Bold (\\texttt{\\string\\mathbb})\n%\\def\\test#1{\\mathbb{#1},}\n%\\begin{eqnarray*}\n%  && {\\testupper}\n%\\end{eqnarray*}%\n\n\n\\clearpage\n\\section{Character Sidebearings}\n\n\\def\\test#1{|#1|+}\n\\begin{eqnarray*}\n  && {\\testupperi}\\\\\n  && {\\testupperii}\\\\\n  && {\\testloweri}\\\\ \n  && {\\testlowerii}\\\\ \n  && {\\testupgreeki}\\\\\n  && {\\testupgreekii}\\\\\n  && {\\testlowgreeki}\\\\\n  && {\\testlowgreekii}\\\\\n  && {\\testlowgreekiii}\n\\end{eqnarray*}%\n%\n\\def\\test#1{|\\mathrm{#1}|+}%\n\\begin{eqnarray*}\n  && {\\testupperi}\\\\\n  && {\\testupperii}\\\\\n  && {\\testloweri}\\\\ \n  && {\\testlowerii}\\\\ \n  && {\\testupgreeki}\\\\\n  && {\\testupgreekii}\n\\end{eqnarray*}%\n%\n%\\def\\test#1{|\\mathbm{#1}|+}%\n%\\begin{eqnarray*}\n%  && {\\testupperi}\\\\\n%  && {\\testupperii}\\\\\n%  && {\\testloweri}\\\\ \n%  && {\\testlowerii}\\\\ \n%  && {\\testupgreeki}\\\\\n%  && {\\testupgreekii}\\\\\n%  && {\\testlowgreeki}\\\\\n%  && {\\testlowgreekii}\\\\\n%  && {\\testlowgreekiii}\n%\\end{eqnarray*}%\n%%\n%\\def\\test#1{|\\mathbf{#1}|+}%\n%\\begin{eqnarray*}\n%  && {\\testupperi}\\\\\n%  && {\\testupperii}\\\\\n%  && {\\testloweri}\\\\ \n%  && {\\testlowerii}\\\\ \n%  && {\\testupgreeki}\\\\\n%  && {\\testupgreekii}\n%\\end{eqnarray*}%\n%\n\\def\\test#1{|\\mathcal{#1}|+}%\n\\begin{eqnarray*}\n  && {\\testupperi}\\\\\n  && {\\testupperii}\n\\end{eqnarray*}%\n\n\n\\clearpage\n\\section{Superscript positioning}\n\n\\def\\test#1{#1^{2}+}%\n\\begin{eqnarray*}\n  && {\\testupperi}\\\\\n  && {\\testupperii}\\\\\n  && {\\testloweri}\\\\ \n  && {\\testlowerii}\\\\ \n  && {\\testupgreeki}\\\\\n  && {\\testupgreekii}\\\\\n  && {\\testlowgreeki}\\\\\n  && {\\testlowgreekii}\\\\\n  && {\\testlowgreekiii}\n\\end{eqnarray*}%\n%\n\\def\\test#1{\\mathrm{#1}^{2}+}%\n\\begin{eqnarray*}\n  && {\\testupperi}\\\\\n  && {\\testupperii}\\\\\n  && {\\testloweri}\\\\ \n  && {\\testlowerii}\\\\ \n  && {\\testupgreeki}\\\\\n  && {\\testupgreekii}\n\\end{eqnarray*}%\n%\n%\\def\\test#1{\\mathbm{#1}^{2}+}%\n%\\begin{eqnarray*}\n%  && {\\testupperi}\\\\\n%  && {\\testupperii}\\\\\n%  && {\\testloweri}\\\\ \n%  && {\\testlowerii}\\\\ \n%  && {\\testupgreeki}\\\\\n%  && {\\testupgreekii}\\\\\n%  && {\\testlowgreeki}\\\\\n%  && {\\testlowgreekii}\\\\\n%  && {\\testlowgreekiii}\n%\\end{eqnarray*}%\n%\n%\\def\\test#1{\\mathbf{#1}^{2}+}%\n%\\begin{eqnarray*}\n%  && {\\testupperi}\\\\\n%  && {\\testupperii}\\\\\n%  && {\\testloweri}\\\\ \n%  && {\\testlowerii}\\\\ \n%  && {\\testupgreeki}\\\\\n%  && {\\testupgreekii}\n%\\end{eqnarray*}\n%\n\\def\\test#1{\\mathcal{#1}^{2}+}%\n\\begin{eqnarray*}\n  && {\\testupperi}\\\\\n  && {\\testupperii}\n\\end{eqnarray*}%\n\n\n\\clearpage\n\\section{Subscript positioning}\n\n\\def\\test#1{\\mathnormal{#1}_{i}+}%\n\\begin{eqnarray*}\n  && {\\testupperi}\\\\\n  && {\\testupperii}\\\\\n  && {\\testloweri}\\\\ \n  && {\\testlowerii}\\\\ \n  && {\\testupgreeki}\\\\\n  && {\\testupgreekii}\\\\\n  && {\\testlowgreeki}\\\\\n  && {\\testlowgreekii}\\\\\n  && {\\testlowgreekiii}\n\\end{eqnarray*}%\n%\n\\def\\test#1{\\mathrm{#1}_{i}+}%\n\\begin{eqnarray*}\n  && {\\testupperi}\\\\\n  && {\\testupperii}\\\\\n  && {\\testloweri}\\\\ \n  && {\\testlowerii}\\\\ \n  && {\\testupgreeki}\\\\\n  && {\\testupgreekii}\n\\end{eqnarray*}%\n%\n%\\def\\test#1{\\mathbm{#1}_{i}+}%\n%\\begin{eqnarray*}\n%  && {\\testupperi}\\\\\n%  && {\\testupperii}\\\\\n%  && {\\testloweri}\\\\ \n%  && {\\testlowerii}\\\\ \n%  && {\\testupgreeki}\\\\\n%  && {\\testupgreekii}\\\\\n%  && {\\testlowgreeki}\\\\\n%  && {\\testlowgreekii}\\\\\n%  && {\\testlowgreekiii}\n%\\end{eqnarray*}\n%%\n%\\def\\test#1{\\mathbf{#1}_{i}+}%\n%\\begin{eqnarray*}\n%  && {\\testupperi}\\\\\n%  && {\\testupperii}\\\\\n%  && {\\testloweri}\\\\ \n%  && {\\testlowerii}\\\\ \n%  && {\\testupgreeki}\\\\\n%  && {\\testupgreekii}\n%\\end{eqnarray*}%\n%\n\\def\\test#1{\\mathcal{#1}_{i}+}%\n\\begin{eqnarray*}\n  && {\\testupperi}\\\\\n  && {\\testupperii}\n\\end{eqnarray*}%\n\n\n\\clearpage\n\\section{Accent positioning}\n\n\\def\\test#1{\\hat{#1}+}%\n\\begin{eqnarray*}\n  && {\\testupperi}\\\\\n  && {\\testupperii}\\\\\n  && {\\testloweri}\\\\ \n  && {\\testlowerii}\\\\ \n  && {\\testupgreeki}\\\\\n  && {\\testupgreekii}\\\\\n  && {\\testlowgreeki}\\\\\n  && {\\testlowgreekii}\\\\\n  && {\\testlowgreekiii}\n\\end{eqnarray*}%\n%\n\\def\\test#1{\\hat{\\mathrm{#1}}+}%\n\\begin{eqnarray*}\n  && {\\testupperi}\\\\\n  && {\\testupperii}\\\\\n  && {\\testloweri}\\\\ \n  && {\\testlowerii}\\\\ \n  && {\\testupgreeki}\\\\\n  && {\\testupgreekii}\n\\end{eqnarray*}%\n%\n%\\def\\test#1{\\hat{\\mathbm{#1}}+}%\n%\\begin{eqnarray*}\n%  && {\\testupperi}\\\\\n%  && {\\testupperii}\\\\\n%  && {\\testloweri}\\\\ \n%  && {\\testlowerii}\\\\ \n%  && {\\testupgreeki}\\\\\n%  && {\\testupgreekii}\\\\\n%  && {\\testlowgreeki}\\\\\n%  && {\\testlowgreekii}\\\\\n%  && {\\testlowgreekiii}\n%\\end{eqnarray*}%\n%%\n%\\def\\test#1{\\hat{\\mathbf{#1}}+}%\n%\\begin{eqnarray*}\n%  && {\\testupperi}\\\\\n%  && {\\testupperii}\\\\\n%  && {\\testloweri}\\\\ \n%  && {\\testlowerii}\\\\ \n%  && {\\testupgreeki}\\\\\n%  && {\\testupgreekii}\n%\\end{eqnarray*}\n%\n\\def\\test#1{\\hat{\\mathcal{#1}}+}%\n\\begin{eqnarray*}\n  && {\\testupperi}\\\\\n  && {\\testupperii}\n\\end{eqnarray*}%\n\n\n\\clearpage\n\\section{Differentials}\n\n\\begin{eqnarray*}\n\\gdef\\test#1{\\dit #1+}%\n  && {\\testupperi}\\\\\n  && {\\testupperii}\\\\\n  && {\\testloweri}\\\\ \n  && {\\testlowerii}\\\\ \n  && {\\testupgreeki}\\\\\n  && {\\testupgreekii}\\\\\n  && {\\testlowgreeki}\\\\\n  && {\\testlowgreekii}\\\\\n  && {\\testlowgreekiii}\\\\\n\\gdef\\test#1{\\dit \\mathrm{#1}+}%\n  && {\\testupgreeki}\\\\\n  && {\\testupgreekii}\n\\end{eqnarray*}%\n%\n\\begin{eqnarray*}\n\\gdef\\test#1{\\dup #1+}%\n  && {\\testupperi}\\\\\n  && {\\testupperii}\\\\\n  && {\\testloweri}\\\\ \n  && {\\testlowerii}\\\\ \n  && {\\testupgreeki}\\\\\n  && {\\testupgreekii}\\\\\n  && {\\testlowgreeki}\\\\\n  && {\\testlowgreekii}\\\\\n  && {\\testlowgreekiii}\\\\\n\\gdef\\test#1{\\dup \\mathrm{#1}+}%\n  && {\\testupgreeki}\\\\\n  && {\\testupgreekii}\n\\end{eqnarray*}%\n%\n\\begin{eqnarray*}\n\\gdef\\test#1{\\partial #1+}%\n  && {\\testupperi}\\\\\n  && {\\testupperii}\\\\\n  && {\\testloweri}\\\\ \n  && {\\testlowerii}\\\\ \n  && {\\testupgreeki}\\\\\n  && {\\testupgreekii}\\\\\n  && {\\testlowgreeki}\\\\\n  && {\\testlowgreekii}\\\\\n  && {\\testlowgreekiii}\\\\\n\\gdef\\test#1{\\partial \\mathrm{#1}+}%\n  && {\\testupgreeki}\\\\\n  && {\\testupgreekii}\n\\end{eqnarray*}%\n\n\n\\clearpage\n\\section{Slash kerning}\n\n\\def\\test#1{1/#1+}\n\\begin{eqnarray*}\n  && {\\testupperi}\\\\\n  && {\\testupperii}\\\\\n  && {\\testloweri}\\\\ \n  && {\\testlowerii}\\\\ \n  && {\\testupgreeki}\\\\\n  && {\\testupgreekii}\\\\\n  && {\\testlowgreeki}\\\\\n  && {\\testlowgreekii}\\\\\n  && {\\testlowgreekiii}\n\\end{eqnarray*}\n\n\\def\\test#1{#1/2+}\n\\begin{eqnarray*}\n  && {\\testupperi}\\\\\n  && {\\testupperii}\\\\\n  && {\\testloweri}\\\\ \n  && {\\testlowerii}\\\\ \n  && {\\testupgreeki}\\\\\n  && {\\testupgreekii}\\\\\n  && {\\testlowgreeki}\\\\\n  && {\\testlowgreekii}\\\\\n  && {\\testlowgreekiii}\n\\end{eqnarray*}\n\n\n\\clearpage\n\\section{Big operators}\n\n\\def\\testop#1{#1_{i=1}^{n} x^{n} \\quad}\n\\begin{displaymath}\n  \\testop\\sum \n  \\testop\\prod \n  \\testop\\coprod \n  \\testop\\int \n  \\testop\\oint\n\\end{displaymath}\n\\begin{displaymath}\n  \\testop\\bigotimes \n  \\testop\\bigoplus\n  \\testop\\bigodot\n  \\testop\\bigwedge \n  \\testop\\bigvee \n  \\testop\\biguplus \n  \\testop\\bigcup \n  \\testop\\bigcap \n  \\testop\\bigsqcup \n% \\testop\\bigsqcap\n\\end{displaymath}\n\n\n\\section{Radicals}\n\n\\begin{displaymath}\n  \\sqrt{x+y} \\qquad \\sqrt{x^{2}+y^{2}} \\qquad \n  \\sqrt{x_{i}^{2}+y_{j}^{2}} \\qquad\n  \\sqrt{\\left(\\frac{\\cos x}{2}\\right)} \\qquad \n  \\sqrt{\\left(\\frac{\\sin x}{2}\\right)}\n\\end{displaymath}\n  \n\\begingroup\n\\delimitershortfall-1pt\n\\begin{displaymath}\n  \\sqrt{\\sqrt{\\sqrt{\\sqrt{\\sqrt{\\sqrt{\\sqrt{x+y}}}}}}}\n\\end{displaymath}\n\\endgroup % \\delimitershortfall\n\n\n\\section{Over- and underbraces}\n\n\\begin{displaymath}\n  \\overbrace{x} \\quad\n  \\overbrace{x+y} \\quad\n  \\overbrace{x^{2}+y^{2}} \\quad\n  \\overbrace{x_{i}^{2}+y_{j}^{2}} \\quad\n  \\underbrace{x} \\quad\n  \\underbrace{x+y} \\quad\n  \\underbrace{x_{i}+y_{j}} \\quad\n  \\underbrace{x_{i}^{2}+y_{j}^{2}} \\quad\n\\end{displaymath}\n\n\n\\section{Normal and wide accents}\n\n\\begin{displaymath}\n  \\dot{x} \\quad \n  \\ddot{x} \\quad \n  \\vec{x} \\quad \n  \\bar{x} \\quad\n  \\overline{x} \\quad\n  \\overline{xx} \\quad\n  \\tilde{x} \\quad\n  \\widetilde{x} \\quad\n  \\widetilde{xx} \\quad\n  \\widetilde{xxx} \\quad\n  \\hat{x} \\quad \n  \\widehat{x} \\quad \n  \\widehat{xx} \\quad \n  \\widehat{xxx} \\quad\n\\end{displaymath}\n\n\n\\section{Long arrows}\n\n\\begin{displaymath}\n  \\leftarrow \\mathrel{-} \\rightarrow \\quad\n  \\leftrightarrow \\quad\n  \\longleftarrow  \\quad\n  \\longrightarrow \\quad\n  \\longleftrightarrow \\quad\n  \\Leftarrow = \\Rightarrow \\quad\n  \\Leftrightarrow \\quad\n  \\Longleftarrow  \\quad\n  \\Longrightarrow \\quad\n  \\Longleftrightarrow \\quad\n\\end{displaymath}\n\n\n\\section{Left and right delimters}\n\n\\def\\testdelim#1#2{ - #1 f #2 - }\n\\begin{displaymath}\n  \\testdelim() \n  \\testdelim[] \n  \\testdelim\\lfloor\\rfloor \n  \\testdelim\\lceil\\rceil \n  \\testdelim\\langle\\rangle \n  \\testdelim\\{\\} \n\\end{displaymath}\n\n\\def\\testdelim#1#2{ - \\left#1 f \\right#2 - }\n\\begin{displaymath}\n  \\testdelim() \n  \\testdelim[] \n  \\testdelim\\lfloor\\rfloor \n  \\testdelim\\lceil\\rceil \n  \\testdelim\\langle\\rangle \n  \\testdelim\\{\\} \n% \\testdelim\\lgroup\\rgroup\n% \\testdelim\\lmoustache\\rmoustache\n\\end{displaymath}\n\\begin{displaymath}\n  \\testdelim)(\n  \\testdelim][\n  \\testdelim// \n  \\testdelim\\backslash\\backslash\n  \\testdelim/\\backslash \n  \\testdelim\\backslash/\n\\end{displaymath}\n\n\n\\clearpage\n\\section{Big-g-g delimters}\n\n\\def\\testdelim#1#2{%\n  - \\left#1\\left#1\\left#1\\left#1\\left#1\\left#1\\left#1\\left#1 - \n  \\right#2\\right#2\\right#2\\right#2\\right#2\\right#2\\right#2\\right#2 -}\n\n\\begingroup\n\\delimitershortfall-1pt\n\\begin{displaymath}\n  \\testdelim\\lfloor\\rfloor \n  \\qquad \n  \\testdelim()\n\\end{displaymath}\n\\begin{displaymath}\n  \\testdelim\\lceil\\rceil \n  \\qquad \n  \\testdelim\\{\\} \n\\end{displaymath}\n\\begin{displaymath}\n  \\testdelim[] \n  \\qquad \n  \\testdelim\\lgroup\\rgroup\n\\end{displaymath}\n\\begin{displaymath}\n  \\testdelim\\langle\\rangle\n  \\qquad \n  \\testdelim\\lmoustache\\rmoustache\n\\end{displaymath}\n\\begin{displaymath}\n  \\testdelim\\uparrow\\downarrow \\quad\n  \\testdelim\\Uparrow\\Downarrow \\quad\n\\end{displaymath}\n\\endgroup % \\delimitershortfall\n\n\n\n%\\end{document}\n\n%%% Local Variables: \n%%% mode: latex\n%%% TeX-master: t\n%%% End: \n", "meta": {"hexsha": "0cc7c2e60ea919fd5f0ed489edac31883559823b", "size": 14898, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "200+ beamer 模板合集/TeXTemplates(论文，报告，beamer，学术报告)/2_Math_Tests/Obsolete/mathtestx.tex", "max_stars_repo_name": "lemoxiao/Awesome-Beamer-Collection", "max_stars_repo_head_hexsha": "3ab28a23fb60cb0a97fcec883847e2d8728b98c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2019-07-30T04:09:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-24T09:27:26.000Z", "max_issues_repo_path": "200+ beamer 模板合集/TeXTemplates(论文，报告，beamer，学术报告)/2_Math_Tests/Obsolete/mathtestx.tex", "max_issues_repo_name": "lemoxiao/Awesome-Beamer-Collection", "max_issues_repo_head_hexsha": "3ab28a23fb60cb0a97fcec883847e2d8728b98c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "200+ beamer 模板合集/TeXTemplates(论文，报告，beamer，学术报告)/2_Math_Tests/Obsolete/mathtestx.tex", "max_forks_repo_name": "lemoxiao/Awesome-Beamer-Collection", "max_forks_repo_head_hexsha": "3ab28a23fb60cb0a97fcec883847e2d8728b98c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2019-11-02T03:10:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-12T04:13:23.000Z", "avg_line_length": 23.1335403727, "max_line_length": 70, "alphanum_fraction": 0.6194120016, "num_tokens": 5859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3128234261417961}}
{"text": "Now that we have defined the EF1 objective for filter optimization, we need to find efficient ways to (approximately) optimize it.  To this end, this section first describes two scalable and efficient greedy algorithms to optimize EF1.\n%used to build filters setting for querying large data graphs in order to retrieve relevant UI elements that are of interest to the users.  \nFollowing this, we describe an optimization-based approach based on Mixed Integer Linear Programming (MILP) to benchmark the performance of the proposed greedy algorithms on moderate-sized problems.\n\n\\subsection{Greedy search}\n\n% Should discuss greedy algorithm generically as having a metric and at each step\n% a choice of k restrictions, which are each scored against the metric with the\n% highest score chosen at each step.  Then each individual filter only has to\n% specify what the choices are and how the choice restricts the set of emails\n% selected.  What is a good succinct notation for this?\n\nAs discussed previously, we assume that three types of ``sub-filters'' are used to select a subset of relevant information in a VID: Keyword Filter, Time Filter, and Space Filter.  A Global Filter is generated by \\emph{conjoining} these three sub-filters. In the following, we describe how to greedily build each of these sub-filters, and then how to combine them into a Global Filter.\n\n\\subsubsection{Greedy Keyword Filter algorithm}\n\nGiven a set of information elements, the greedy Keyword Filter algorithm aims to select a set of keywords to form a negation query in order to exclude a subset of elements containing these keywords for the purpose of maximizing the EF1-Score.\n\nFormally, given a keyword query representation $Q_k$, the algorithm aims to select an\noptimal subset of $k$ terms $T_{k}^{*}\\subset E$ (where $|T_{k}^{*}|=k$ and $E$ is the initial set of elements) to build a negation keyword query $Q_k$, i.e. $Q_k=\\{\\neg t_{1}^{*},\\dots \\neg t_{k}^{*}\\}$, in order to optimize the EF1-score. This is achieved by\nbuilding $T_{k}^{*}$ in a greedy manner by choosing the next optimal\nterm $t_{k}^{*}$ given the previous set of optimal term selections\n$T_{k-1}^{*}=\\{t_{1}^{*},\\ldots,t_{k-1}^{*}\\}$ (assuming $T_{0}^{*}=\\emptyset$)\nusing the following selection criterion:\n\\begin{equation}\nt_{k}^{*}=\\argmax_{t_{k}\\notin T_{k-1}^{*}}\\hspace{-0.3mm}[EF1(E^{*} \\textrm{ that satisfies } Q_k=\\{\\neg t_{1}^{*},\\dots \\neg t_{k}^{*}\\})]\n\\end{equation}\nwhere  $E^{*}$ is a subset of the initial element set $E$ that satisfy the negation keyword query $Q_k$. In order to reduce the keyword search space, we propose to use the top 100 terms ranked using Mutual Information to identify the keywords that are predictive of the ``supervised'' relevance measure.  We remark that other metrics like frequency would be more appropriate for unsupervised tasks.  We further remark that we have chosen to use a negation query as a means to effectively prune (or filter) the content as more terms are selected.  \n%mainly for technical reasons as a negation query generates queries with much fewer terms. \nThe best indexing strategy to support this greedy search is the inverted index data structure~\\cite{Zobel2006}.\n\n\\subsubsection{Greedy Time Filter algorithm}\n\nThe idea behind the time-based greedy filter algorithm is as simple as finding a time window range $Q_t=[t_{start},t_{end}]$, which allows to select a subset of elements $E^{*}\\subseteq E$ falling in that time window, with $E^{*}$ having the highest EF1-Score.\n\nFormally, a list of elements $E=\\{j_{t_1}\\leq \\dots \\leq j_{t_n}\\}$, where \"$\\leq$\" specifies the timestamp order, we propose the following two time greedy algorithms:\n\n\\subfour{Naive greedy algorithm:} First, at each iteration of this algorithm, an early ranked element $j_{t_i}$ is removed, and then, the remaining set is assessed using EF1-Score. If the remaining set has a lower EF1-score value than the set of the previous iteration, the algorithm assigns $t_i$ to the lower time bound of the time query, i.e., $t_{start}=t_i$. \nNext, the algorithm does the same set of operations, by removing at each iteration a lastly ranked element  $j_{t_i}$, and by stopping once the removal of  $j_{t_i}$ causes a decrease in the EF1-Score value. Then, the algorithm assigns $t_i$ to the upper time bound of the time query, i.e., $t_{end}=t_i$. \nLastly, the algorithm returns the  time query $Q_t=[t_{start},t_{end}]$, with obviously $EF1(E^{*} \\textrm{ that satisfies } Q_t=[t_{start},t_{end}]) \\geq EF1(E)$.\n\n\\subfour{Binary Partition Search algorithm:} Large datasets with sparse positive data (e.g., 0.5\\% of alerts in a security graph) will cause the previous algorithm to take a large number of iterations to terminate since it greedily adjusts filter settings in a minimal way at each step.  A way to address this problem is to use binary partitioning search (BPS).  Hence, instead of removing a single element $j$ at each iteration, this algorithm operates by selecting between two distinct alternatives (binary partitions) at each iteration. \n\n\\begin{algorithm}[t]\n%\\scriptsize\n\\caption{Binary Partition Search (BPS) Algorithm}\n\\SetAlgoLined\n\\SetKwData{Left}{left}\\SetKwData{This}{this}\\SetKwData{Up}{up}\n\\SetKwFunction{Union}{Union}\\SetKwFunction{FindCompress}{FindCompress}\n\\SetKwInOut{Input}{input}\\SetKwInOut{Output}{output}\n\\Input{A set of ordered elements $E=\\{j_{v_1} \\dots j_{v_n}\\}$ }\n\\Output{A timestamp $t$;}\n\\BlankLine\n\\label{alg:Dichotomy}\n\n$v_{min}=v_1$; $v_{max}=v_n$;  $v_{mid}=\\tfrac{v_1+v_n}{2}$;\n\n\\While {$v_{min}!=v_{mid}!=v_{max}$}{\n\n\\eIf{$[EF1(\\{j_{v_{min}} \\dots  j_{v_n}\\}) \\geq EF1(\\{j_{v_{mid}} \\dots  j_{v_n}\\})]$}{\n$v_{max}=v_{mid}$;\n$v_{mid}=\\tfrac{v_{min}+v_{mid}}{2}$;\n}{\n$v_{min}=v_{mid}$; \n$v_{mid}=\\tfrac{v_{min}+v_{max}}{2}$;\n}\n}\n\\Return  $v_{mid}$;\n\n\\label{alg:return}\n\\end{algorithm} \n\n%Therefore, the algorithm first sets the values $t_{min}=t_1$, $t_{max}=t_n$,  and $t_{mid}=\\tfrac{t_1+t_n}{2}$. Then, for each iteration, if $[EF1(\\{d_{t_{min}}\\leq \\dots \\leq d_{t_n}\\}) \\geq EF1(\\{d_{t_{mid}}\\leq \\dots \\leq d_{t_n}\\})]$, the algorithm sets $t_{max}=t_{mid}$, $t_{mid}=\\tfrac{t_{min}+t_{mid}}{2}$ and makes a new iteration, else, the algorithm sets $t_{min}=t_{mid}$,  $t_{mid}=\\tfrac{t_{min}+t_{max}}{2}$  and makes a new iteration. The algorithm keeps iterating until $t_{min}=t_{mid}=t_{max}$, where it assigns $t_{mid}$ to the lower time bound of the time query, i.e., $t_{start}=t_{mid}$.\n\n\nAs an example of the BPS approach for the time sub-filter, the algorithm first sorts $E$ in increasing order of time stamp. Then, it applies the procedure described by Algorithm \\ref{alg:Dichotomy}. This procedure will return  the lower time bound of the time query, i.e., $t_{start}=t_{mid}$.\nNext, the algorithm sorts $E$ in decreasing order of time stamp, and then, it applies again the procedure described by Algorithm \\ref{alg:Dichotomy} to get the upper time bound of the time query, i.e., $t_{end}=t_i$. Lastly, the algorithm returns the  time query $Q_t=[t_{start},t_{end}]$, such that $EF1(E^{*} \\textrm{ that satisfies } Q_t=[t_{start},t_{end}]) \\geq EF1(E)$. Note that this algorithm proceeds in a total of $log(n)$ iterations in the best case, and $2\\times log(n)$ iterations in the worst case.\n\nFor both the naive and time-based greedy algorithms, we use the red-black tree as the indexing data structure \\cite{Guibas1978}.\n\n\n\\subsubsection{Greedy Spatial Filter algorithm}\n\nThe aim of this algorithm is to return coordinates $Q_p=[(x_{min},y_{min},(x_{max},y_{max})]$ representing the EF1-Score maximizing bounding box represented by the lower and upper bound coordinates -- respectively $(x_{min},y_{min})$ and $(x_{max},y_{max})$. This 2D problem is similar to the previous one dimensional problem of finding the best time window. Therefore, the two greedy algorithms described above can be adapted for this problem by first applying each algorithm on the x-axis to determine $(x_{min},x_{max})$, then on the y-axis to determine $(y_{min},y_{max})$. \n% We need to ditch some citations and this removes the complaint that we did not provide all details -- we claim it is obvious.  -Scott\n%We omit the description of these two algorithms for lack of space, but a detailed description can be found in the technical report~\\cite{Bouadjenek2018}.\nWe use the R-tree as a data structure for indexing multi-dimensional continuous data~\\cite{Guttman1984}.\n\n\n\\subsubsection{Global Filter algorithm} To obtain a Global Filter combining all sub-filters, we propose a greedy algorithm, which at each iteration applies all sub-filters and chooses the one that most reduces EF1.  The selected filter is updated with its new setting and the iteration continues.  Iterations termination when no sub-filter can unilaterally improve EF1 and the final filter settings are returned as the Global Filter.\n%to, theselects the best sub-filter to apply (according to its reduction in EF1-Score), then checks if that filter improves the EF1-Score. If so, the algorithm continues with the updated filter settings, otherwise, it terminates. \n% Don't get the following -- seems non-essential, at least for submission.  -Scott\n%Note that here, we use  $k=1$ for the keywords greedy algorithm.\n%The algorithm will then determine a sequence of filters to apply on the initial set, and the final query is then built by combining these filters by types.\n\n %such as: $\\{Keyword \\to Time -> Position \\to Time \\to Keyword\\} $\n\n% I don't follow this example, but I think the algorithm is intuitive enough and we need space.  -Scott\n% For example, let's suppose the algorithm determines the following filter sequence: $\\{Q_{k_1}=\\{ \\neg natural\\} \\to Q_{t_1}=[50,2030] \\to Q_{p_1}=[(10,60), (50,100)] \\to Q_{t_2}=[60,1230] \\to Q_{k_2}=\\{ \\neg fictive\\}  \\to  Q_{p_2}=[(10,60), (30,85)] \\to  Q_{t_3}=[60,800] \\}$. \n% The final query is built by combining these filters by types as follows: $Q_k=Q_{k_1} \\cup Q_{k_2}=\\{\\neg natural,\\neg fictive\\}$, $Q_t =Q_{t_1} \\cap Q_{t_2} \\cap Q_{t_3}=[60,800]$, and  $ Q_p=Q_{p_1}  \\cap Q_{p_2}=[(10,60),$ $(30,85)]$, which gives $Q=[Q_k=\\{\\neg natural,\\neg fictive\\}\\wedge Q_t=[60,800]\\wedge Q_p = [(10,60),$ $(30,85)]]$.\n\nFinally, we note that the Global Filter algorithm can use the Greedy Keyword Filter with the naive Greedy Time and Spatial Filters, which we refer to experimentally as {\\bf Greedy}, or the Binary Partition Search variants, which we refer to experimentally as {\\bf BPS}.  \n%time and position naive greedy algorithms to which we refer as Greedy Algorithm, or the keywords greedy algorithm with the time and position Binary Partition Search algorithms to which we refer as BPS Algorithm.\n\n\n\n\\subsection{Optimal MILP Solutions for Benchmarking}\n\nNext, we propose an exact Mixed Integer Linear Progamming (MILP) optimization-based formulation to maximize EF1 and provide a benchmark for evaluating the two previous Global Filter algorithms (Greedy and BPS).  %Given the trivial solution of optimizing the expected precision (singleton) and expected recall (the whole collection), we consider in the following only the optimization of EF1.  \n\n\\subsubsection{Fractional MILP Formulation} \\hfill \\\\\nWe begin by reformulating the EF1 objective to prepare for further optimization steps by replacing the global sum of scores of all information elements with a constant $C = \\sum_{j=1}^m S(j)$:\n\\begin{equation}\n\\begin{aligned}\n    \\emph{$EF1$} &= \\dfrac{2\\times \\sum_{j=1}^m S(j)I(j)}{\\sum_{j=1}^m I(j) + \\sum_{j=1}^m S(j)} = \\dfrac{2 \\times \\sum_{j=1}^m S(j)I(j)}{\\sum_{j=1}^m I(j) + C}\n\\end{aligned}\n\\end{equation}\n\nIn order to obtain the EF1-optimal Global Filter, we let binary variables $\\emph{I\\textsubscript{filter}}($j$) \\in \\{0, 1\\}$ indicate whether an information element $j$ is selected in each sub-filter and constrain that to be selected in the Global Filter (i.e., $I(j)=1$), $j$ must be selected in all filters (i.e., a conjunction).  This leads to the following fractional MILP formulation with sub-filter constraints to be defined later:\n%intend to directly optimize the EF1 metric in terms of decision indication variables  for filter setting as follows:\n% Don't use I(i)... confusing!  \n%\\begin{align}\n%\\max_{\\textit{filter vars}} \\;\\;\n%& \\dfrac{\\sum_{j=1}^m S(i)I(j)}{\\sum_{j=1}^m I(j) + C} \\nonumber \\\\\n%& \\textrm{subject to constraints between {\\it filter vars} and $I(j)$}   \n%\\end{align}\n\\begin{equation}\n\\begin{aligned}\n& \\underset{I_{\\mathit{filter}}(j)}{\\text{maximize}}\n& & \\dfrac{\\sum_{j=1}^m S(j)I(j)}{\\sum_{j=1}^m I(j) + C} \\\\\n& s.t\n& & I(j) = \\bigwedge I_{\\mathit{filter}}(j) \\\\\n\\end{aligned} \\label{eq:frac_milp}\n\\end{equation}\n\n% Not necessary.  -Scott\n%Note that our goal is to optimize the element set in terms of \\emph{filters settings}. This means elements in the interface sharing the same property needs to be simultaneously added to the selected set. This is a unique property of our filter-based UI problem, which is different from the independent retrieval of each document in standard IR system.\n\n\\subsubsection{Transformation to a MILP} \\hfill \\\\\nWhile there are no direct solvers for fractional MILPs, we can transform~\\eqref{eq:frac_milp} into a pure MILP form for which we have efficient and optimal solvers.  To do this, we use the Charnes-Cooper method \\cite{Charnes1962} and Glover linearization method \\cite{Glover1975} with big-M constraints, where auxiliary variables \\emph{w(j)} and \\emph{u} are  introduced\\footnote{https://optimization.mccormick.northwestern.edu/index.php/Mixed-integer\\_linear\\_fractional\\_programming\\_(MILFP)}. Here, $w(j)$ is defined as $w(j)=I(j)\\times u$ with $u$ defined as follows:\n\\begin{equation}\nu = \\dfrac{1}{\\sum_{j=1}^m I(j) + C}\n\\end{equation}\n\nThen, the EF1 optimization problem is able to be transformed into the following MILP problem:\n\\begin{equation}\n\\begin{aligned}\n& \\underset{w,u}{\\text{maximize}}\n& & \\sum_{j=1}^m S(j)w(j) \\\\\n& s.t\n& & \\sum_{j=1}^m w(j) + uC = 1 \\\\\n& & & w(j) \\leqslant u, \\quad w(j) \\leqslant M\\times I(j)  \\\\\n& & & w(j) \\geqslant u - M\\times [1-I(j)] \\\\\n& & & u > 0,  \\quad I(j) \\in \\{0, 1\\}, \\quad w(j) \\geqslant 0 \\label{eq:milp}\n\\end{aligned}\n\\end{equation}\n\n\\subsubsection{Constraints} \\hfill \\\\\nAs our goal is to select elements through three sub-filters, we add three constraints to the above optimization.\n\\begin{enumerate}\n\\item {\\bf Time Filter Constraint:} a two-element tuple ($t_{start}$, $t_{end}$) indicating respectively the start and the end of the time window.\n\\begin{equation}\n\\begin{aligned}\n  I_{\\mathit{time}}(j) &=\n   \\begin{cases}\n     1, & \\text{if $(t_{start} \\leqslant t(j)) \\land (t(j) \\leqslant t_{end})$}  \\\\\n     0, & \\text{otherwise}\n  \\end{cases} \\label{eq:cons1}\n\\end{aligned}\n\\end{equation}\n\n\\item {\\bf Spatial Filter Constraint:} a four-element tuple ($x_{min}$, $y_{min}$, $x_{max}$, $y_{max}$) to create a bounding box filter in visualization interface.\n\\begin{equation}\n\\begin{aligned}\nI_{\\mathit{pos}}(j) & =\\begin{cases}\n1, & \\text{if \\ensuremath{(x_{min}\\leqslant x(j))\\land(x(j)\\leqslant x_{max})\\land}}\\\\\n & (y_{min}\\leqslant y(j))\\land(y(j)\\leqslant y_{max})\\\\\n0, & \\text{otherwise}\n\\end{cases} \\label{eq:cons2}\n\\end{aligned}\n\\end{equation}\n\n\\item {\\bf Keyword Filter Constraint:} a boolean vector of terms $t^*_k$ with size $m$ - the size of the dictionary of the global collection.\n\\begin{equation}\n  I_{\\mathit{term}}(j) = \\bigwedge_{t^*_k \\in j} t^*_k \\qquad \\textnormal{for s = 1, 2, $\\cdots$, m} \\label{eq:cons3}\n\\end{equation}\nAll terms with $I_{\\mathit{term}}=0$ are included in the negation query.\n\n\n\\item {\\bf Global Filter Constraint:} for information element $j$ to be selected globally, it must be simultaneously selected by the three sub-filters.\n%, all filter constraints have to be satisfied in this element. In others words, an AND operator is required between all the sub-filter constraints.\n%{\\bf TODO: mention how to apply to all filters... need to say an email j is selected if \\emph{all} filters say it is selected, so an AND constraint.  \\textcolor{red}{[PLEASE COMPLETE YIHAO]}.\n%} \n\\begin{equation}\n  I(j) = I_{\\mathit{time}}(j) \\land I_{\\mathit{pos}}(j) \\land I_{\\mathit{keyword}}(j) \\label{eq:cons4}\n\\end{equation}\n\n\\end{enumerate}\nWe refer to the above MILP formulation in~\\eqref{eq:milp} with all filter constraints~\\eqref{eq:cons1}--\\eqref{eq:cons4} as the {\\bf Optimal} Global Filter.\n\n\\subsection{Multiple Filter Selection Wrapper}\n\n%The Global Filter selects a single best filter setting.  However, what if we want to display multiple possible Global Filters.  \nIn practice a single Global Filter chosen by the previously described algorithms will narrow the user in on a single \\textquotedblleft event\\textquotedblright{}. However, there will likely be multiple anomalous events and so the user should have a choice of multiple filters.  \nConsider Figure~\\ref{Fig:UseCase}: this actually shows three different spatial bounding boxes corresponding to three different events provided by Global Filters.\nIn this work, we provide an initial greedy approach for providing a ranked list of multiple filters (that is a wrapper approach working with any of the previously defined filtering algorithms -- Greedy, BPS, or Optimal); we leave it to future work to develop improved filtering and ranking methods for multiple filters.\n\nThe algorithm itself is quite simple.  After the first filter is produced, all selected elements by the filter have their scores $S(j)$ zeroed out.  The filtering algorithm is then run again, where it will inherently focus on a different content set.  This procedure is repeated until the desired number of filters is reached, or a metric / coverage score for high scoring content is reached.  The user should then be able to choose among the multiple filters in the VID. \t\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "3189deca6463f319c158f296ca0a3e5633f7ea14", "size": 17768, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Documents/CIKM2018/Algorithms.tex", "max_stars_repo_name": "D3Mlab/visir", "max_stars_repo_head_hexsha": "cd1860984dee8d7aba368857e734ad11c14124c8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-10T07:40:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-10T07:40:04.000Z", "max_issues_repo_path": "Documents/CIKM2018/Algorithms.tex", "max_issues_repo_name": "D3Mlab/viz-ir", "max_issues_repo_head_hexsha": "cd1860984dee8d7aba368857e734ad11c14124c8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Documents/CIKM2018/Algorithms.tex", "max_forks_repo_name": "D3Mlab/viz-ir", "max_forks_repo_head_hexsha": "cd1860984dee8d7aba368857e734ad11c14124c8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 81.1324200913, "max_line_length": 611, "alphanum_fraction": 0.73643629, "num_tokens": 5088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6406358685621719, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.3128118570498334}}
{"text": "% !TEX root = ../main.tex\n% chktex-file 21\n\\section{Conclusion}%\n\\label{sec:conclusion}\n\nIn this paper we presented two approaches to speed up hyperparameter optimization: Fabolas and learning curve extrapolation.\nBoth use probabilistic models to estimate values of the error function.\nThen four approaches to speed up training were presented: Bag of Little Bootstraps, subsample size selection for gradient descent, subsampling for logistic regression and \\(k\\)-means clustering for SVMs.\\\nAll presented approaches are able to speedup training significantly on big datasets.\nSince those approaches optimize different aspects of the training process, various combinations of them are possible to get further speedups.\nWe will now take a brief look at promising combinations.\n\\begin{itemize}\n\t\\item Since Fabolas is a hyperparameter optimizer that does not make assumptions about the learner, it can be combined trivially with any of the training optimization approaches presented in Section~\\ref{sec:params}.\n\t\\item The learning curve extrapolation method described in Section~\\ref{sec:hyperparams:earlyterm} requires a learner using gradient descent.\n\t\tIt can thus be combined with the subsample size selection method described in Section~\\ref{sec:params:samplesize}.\n\t\\item Learning curve extrapolation could additionally be combined with Fabolas to guide the hyperparameter search.\n\t\tThis would however require changing the covariance kernel of the cost model \\(c\\) since probes at suboptimal positions are likely to be terminated early, making them less costly and thus more attractive for the aquisition function \\(a_F\\).\n\t\tOne possible approach to adapt the cost model is to add a dependence on the loss model \\(f\\).\n\t\tThis would essentially merge the two Gaussian processes \\(c\\) and \\(f\\) into a single cost-loss model over the parameter space \\(\\Theta = \\Lambda \\times [0, 1] \\times \\{\\mathrm{cost}, \\mathrm{loss}\\}\\) where information about the loss of a configuration is indicative about its cost.\n\t\tFinding a suitable kernel function for this joint GP model could be a subject of further research.\n\t\\item In principle Bag of Little Bootstraps (Section~\\ref{sec:params:blb}) could be combined with the other three training optimization methods since it is a general purpose bagging method.\n\t\tHowever the combination of BLB with subsample size selection for gradient descent is problematic since the latter relies on dynamically adapting the sample size during training to reduce the expected variance.\n\t\tThis approach does not work well if the training data is a resampled BLB bootstrap that does not allow for significant variance reduction since it only contains a small fraction of datapoints.\n\t\tThe combinations of BLB with OSMAC and of BLB with WKM-SVM are more promising.\n\t\tIn the case of OSMAC the sampling weights \\(\\pi_i\\) could be used to sample the small bootstraps \\(\\check{X}\\) (compare~\\citet{Norazan2009}).\n\t\\item Another promising combination is that of subsample size optimization (Section~\\ref{sec:params:samplesize}) with OSMAC (Section~\\ref{sec:params:osmac}).\n\t\tSince logistic regression is often implemented using gradient descent, both methods can be combined by simply using OSMAC to get the subsample for each SGD step.\n\\end{itemize}\nEvaluating those combinations could be a subject of future work.\n", "meta": {"hexsha": "dccd62dd29b413dd672b92ebfefe59b37525239b", "size": 3335, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/content/chapter-conclusion.tex", "max_stars_repo_name": "Cortys/aml-seminar", "max_stars_repo_head_hexsha": "29f27bebceaaa6c3ac054d0719a389978bc717b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paper/content/chapter-conclusion.tex", "max_issues_repo_name": "Cortys/aml-seminar", "max_issues_repo_head_hexsha": "29f27bebceaaa6c3ac054d0719a389978bc717b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/content/chapter-conclusion.tex", "max_forks_repo_name": "Cortys/aml-seminar", "max_forks_repo_head_hexsha": "29f27bebceaaa6c3ac054d0719a389978bc717b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 111.1666666667, "max_line_length": 285, "alphanum_fraction": 0.8008995502, "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.3125680634325904}}
{"text": "\\chapter{datareset} \\label{datareset}\n\n\\section{Introduction}\n\nThe \\texttt{datareset} command assumes that certain parameters of the LPE determine which summands can be followed by which summands.\nThese parameters determine the control-flow of the LPE, and are therefore called \\emph{control-flow parameters}.\n\n\\emph{Data parameters}, on the other hand, are used to store values, and often temporarily, which means that their values may not be used anymore after a particular state.\nData parameters can typically have different values after such a state, which causes them to add states to the state space for each of those values -- \\emph{without} adding any new behavior!\n\nThe \\texttt{datareset} command attempts to detect LPE control-flows and determine the parts of those control-flows where data parameters are no longer used.\nAt these locations, data parameters are set to a default value (`reset').\nThis removes states from the state space, potentially improving performance of subsequent computations.\n\n\\section{Formal background}\n\nThe control-flow analysis is based on work done in \\cite{van2009state}.\n\n\\subsection{Parameter properties}\n\nEach parameter $p$ of a summand $s$ has the following properties:\n\\begin{itemize}\n\n\\item Is the value of $p$ potentially altered by $s$?\nIf so, $p$ receives the label `changed'.\n\n\\item Does $p$ occur in the guard of $s$?\nIf so, $p$ receives the label `directly used'.\n\n\\item Has $p$ received the label `directly used' in $s$?\nOr does $p$ occur in the assignment by $s$ to a parameter that has received the label as `changed'?\nIn either case, $p$ also receives the label `used'.\n\n\\item Must the value of $p$ have a specific (unique) value $v$ in order for $s$ to be enabled?\nIf so, $p$ receives the label `having a source' for $s$, with the source being $v$.\n\n\\item Does the value of $p$ have a specific (unique) value $v$ immediately after $s$ has been applied?\nIf so, $p$ receives the label `having a destination' for $s$, with the source being $v$.\n\n\\item Does $p$ have both a source and a destination for $s$?\nThen $p$ is called a \\emph{ruling parameter}, and $p$ is said to `rule' summand $s$.\n\n\\end{itemize}\n\n\\subsection{Control-flow graphs}\n\nA parameter of the LPE is a \\emph{control-flow parameter} of the LPE if for all summands it is either a ruling parameter or not \\labeledas{changed} (or both).\nA parameter that is not a control-flow parameter is defined as a \\emph{data parameter}.\n\n\\vspace{1mm}\n\nFor each control-flow parameter $f$ of the LPE, a control-flow graph is constructed.\nThere is a state in the control-flow graph for each source and destination of $f$ (across all summands).\nTwo states $s_1$ and $s_2$ are connected by an edge $(s_1, i, s_2)$ if there is a summand $i$ where the source of $f$ is represented by one of the states and where the destination of $f$ is represented by the other state.\nThe direction of such an edge is from source state to destination state.\n\n\\subsection{Belongs-to function}\n\nHere, the \\emph{belongs-to} function is introduced.\nThe belongs-to function maps each data parameter $d$ to some set of control-flow parameters $b(d)$ as follows\n\n\\begin{align*}\nb(d) = F \\cap \\bigcap\\limits_{s \\in S}^{} \\text{ruling}(s)\n\\end{align*}\n\nwhere\n\n\\begin{itemize}\n\\item $F$ is the set of all control-flow parameters;\n\\item $S$ is the set of all summands in which $d$ is \\labeledaseither{changed}{used};\n\\item $\\text{ruling}(s)$ is the set of all parameters that rule summand $s$.\n\\end{itemize}\n\n\\section{Algorithm}\n\nThe algorithm executes 3 phases: the preparatory phase, the iterative phase, and the deletion phase.\n\n\\subsection{Preparatory phase}\n\nIn this phase, the parameter properties, control-flow graphs and belongs-to function are computed.\n\n\\subsection{Iterative phase}\n\nIn the iterative phase, the so-called \\emph{relevance relation} is computed.\nThis relation, with symbol $R$, relates a data parameter $d$, a control-flow parameter $f$, and a value $v$ if $d$ is `relevant' after a state in which $f$ has value $v$.\nThis is denoted $R(d, f, v)$.\nIntuitively, this is a situation in which $d$ should \\emph{not} be reset because its value may be needed in the future.\n\nThe computation of $R$ is a fixpoint algorithm: modifications are applied iteratively until $R$ no longer changes.\nThe initial value of $R$ is set to\n\\begin{align*}\nR_0 = \\bigcup\\limits_{\\substack{i \\in S \\\\ d_k \\in \\text{directlyUsed}(i)}}^{} \\;\\{\\; (d_k, d_j, \\text{source}(i, d_j)) \\;|\\; d_j \\in b(d_k) \\;\\}\n\\end{align*}\n\nwhere\n\n\\begin{itemize}\n\\item $S$ is the set of all summands;\n\\item $\\text{directlyUsed}(i)$ is a function that gives the set of all parameters that are \\labeledas{directly used} in a summand $i$;\n\\item $\\text{source}(i, f)$ is a function that gives the source value of a control-flow parameter $f$ for a summand $i$.\n\\end{itemize}\n\nEach iteration can be split into two steps.\nThe first step checks for control-flow graphs in which a data parameter $d$ has already been \\labeledas{relevant} whether this implies that $d$ is also relevant in preceding states (of the same control-flow graph).\nIf so, the appropriate triples are added to $R$:\n\\begin{align*}\nR_{n}{'} = R_{n-1} \\cup \\bigcup\\limits_{\\substack{i \\in S}}^{} \\;\\left\\{\\; (d_k, d_j, s) \\;\\middle|\\; \\substack{(d_l, d_j, t) \\in R_{n-1} \\\\ d_j \\in b(d_k) \\\\ d_k \\in \\text{vars}(v_i(d_l)) \\\\ (s, i, t) \\in E_{d_j}} \\;\\right\\}\n\\end{align*}\n\nwhere\n\n\\begin{itemize}\n\\item $E_{f}$ is the set of edges that are part of the control-flow graph of control-flow parameter $f$.\n\\end{itemize}\n\nThe second step is similar, but data parameters that are found to be relevant are added as triples to $R$ in relation to \\emph{another} control-flow parameter:\n\\begin{align*}\nR_{n} = R_{n}{'} \\cup \\bigcup\\limits_{\\substack{i \\in S}}^{} \\;\\left\\{\\; (d_k, d_j, \\text{source}(i, d_j)) \\;\\middle|\\; \\substack{(d_l, d_p, t) \\in R_{n}{'} \\\\ d_j \\in b(d_k),\\; d_j \\notin b(d_l) \\\\ d_k \\in \\text{vars}(v_i(d_l)) \\\\ (r, i, t) \\in E_{d_p}} \\;\\right\\}\n\\end{align*}\n\n\\subsection{Deletion phase}\n\nFinally, each summand of an LPE is subject to modification.\nModifications are made by making use of the belongs-to function $b$ and the relevance relation $R$.\nIntuitively, we check whether the value of a parameter is `relevant' after a specific summand $i$ has been applied.\nIf so, the parameter should not be reset.\nOtherwise, the parameter can be reset, for example to its initialization value:\n\n\\begin{align*}\nv_{i}{'}(d_k) = \\begin{cases}\nv_{i}(d_k) & \\text{if } \\bigwedge\\limits_{\\substack{d_j \\in \\text{ruling}(i) \\\\ d_j \\in b(d_k)}}^{} R(d_k, d_j, \\text{dest}(i, d_j)) \\\\\nv_{I}(d_k) & \\text{otherwise}\n\\end{cases}\n\\end{align*}\n\nwhere\n\n\\begin{itemize}\n\\item $\\text{ruling}(s)$ is the set of all parameters that rule summand $s$;\n\\item $\\text{source}(i, f)$ is a function that gives the destination value of a control-flow parameter $f$ for a summand $i$.\n\\end{itemize}\n\n\\section{Benchmark results}\n\nThe following durations were measured with a benchmark for several models:\n\\begin{itemize}\n\\item The average duration of \\txs{} to make 500 steps in a model after it has been converted to LPE form;\n\\item The average duration of \\txs{} to make 500 steps in a model after it has been converted to LPE form and after the \\texttt{datareset} operation has been applied.\n\\end{itemize}\n\nWhen plotting the second series of measurements against the first (see Figure~\\ref{datareset-vs-lpe-only:fig}), it is easy to see that the impact is insignificant in most cases.\n\n\\begin{figure}[!ht]\n\\begin{center}\n\\includegraphics[width=0.7\\linewidth]{charts/datareset-vs-lpe-only}\n\\caption{Benchmark results: datareset vs LPE transformation}\n\\label{datareset-vs-lpe-only:fig}\n\\end{center}\n\\end{figure}\n\n", "meta": {"hexsha": "68cdd8c1cec0ac5251176b31c166dd276bfcb5c8", "size": 7704, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "sys/lpeops/tex/lpeopsDoc/datareset.tex", "max_stars_repo_name": "ikbendedjurre/TorXakis", "max_stars_repo_head_hexsha": "a791ce9960e88df576733404fe4d60114c35e50a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 44, "max_stars_repo_stars_event_min_datetime": "2017-06-09T08:17:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-08T02:17:01.000Z", "max_issues_repo_path": "sys/lpeops/tex/lpeopsDoc/datareset.tex", "max_issues_repo_name": "ikbendedjurre/TorXakis", "max_issues_repo_head_hexsha": "a791ce9960e88df576733404fe4d60114c35e50a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 746, "max_issues_repo_issues_event_min_datetime": "2017-06-13T07:36:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T19:14:31.000Z", "max_forks_repo_path": "sys/lpeops/tex/lpeopsDoc/dataReset.tex", "max_forks_repo_name": "ikbendedjurre/txs-develop", "max_forks_repo_head_hexsha": "bc11f4b93a15e220bf6941d395d5b4cd361bfe74", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2017-11-16T11:33:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-26T16:33:36.000Z", "avg_line_length": 47.850931677, "max_line_length": 265, "alphanum_fraction": 0.730529595, "num_tokens": 2216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3125228985987003}}
{"text": "% Copyright 2019 by Till Tantau\n%\n% This file may be distributed and/or modified\n%\n% 1. under the LaTeX Project Public License and/or\n% 2. under the GNU Free Documentation License.\n%\n% See the file doc/generic/pgf/licenses/LICENSE for more details.\n\n\n\\section{Three Dimensional Drawing Library}\n\n\\begin{tikzlibrary}{3d}\n    This package provides some styles and options for drawing three dimensional\n    shapes.\n\\end{tikzlibrary}\n\n\n\\subsection{Coordinate Systems}\n\n\\begin{coordinatesystem}{xyz cylindrical}\n    The |xyz cylindrical| coordinate system allows to you specify a point in\n    terms of cylindrical coordinates, sometimes also referred to as cylindrical\n    polar coordinates or polar cylindrical coordinates. It is very similar to\n    the |canvas polar| and |xy polar| coordinate systems with the difference\n    that you provide an elevation over the $xy$-plane using the |z| key.\n    %\n    \\begin{key}{/tikz/cs/angle=\\meta{degrees} (initially 0)}\n        The angle of the coordinate interpreted in the ellipse whose axes are\n        the $x$-vector and the $y$-vector.\n    \\end{key}\n    %\n    \\begin{key}{/tikz/cs/radius=\\meta{number} (initially 0)}\n        A factor by which the $x$-vector and $y$-vector are multiplied prior to\n        forming the ellipse.\n    \\end{key}\n    %\n    \\begin{key}{/tikz/cs/z=\\meta{number} (initially 0)}\n        Factor by which the $z$-vector is multiplied.\n    \\end{key}\n    %\n\\begin{codeexample}[preamble={\\usetikzlibrary{3d}}]\n\\begin{tikzpicture}[->]\n  \\draw (0,0,0) -- (xyz cylindrical cs:radius=1);\n  \\draw (0,0,0) -- (xyz cylindrical cs:radius=1,angle=90);\n  \\draw (0,0,0) -- (xyz cylindrical cs:z=1);\n\\end{tikzpicture}\n\\end{codeexample}\n    %\n\\end{coordinatesystem}\n\n\\begin{coordinatesystem}{xyz spherical}\n    The |xyz spherical| coordinate system allows you to specify a point in\n    terms of spherical coordinates.\n    %\n    \\begin{key}{/tikz/cs/radius=\\meta{number} (initially 0)}\n        Factor by which the $x$-, $y$-, and $z$-vector are multiplied.\n    \\end{key}\n    %\n    \\begin{key}{/tikz/cs/latitude=\\meta{degrees} (initially 0)}\n        Angle of the coordinate between the $y$- and $z$-vector, measured from\n        the $y$-vector.\n    \\end{key}\n    %\n    \\begin{key}{/tikz/cs/longitude=\\meta{degrees} (initially 0)}\n        Angle of the coordinate between the $x$- and $y$-vector, measured from\n        the $y$-vector.\n    \\end{key}\n    %\n    \\begin{key}{/tikz/cs/angle=\\meta{degrees} (initially 0)}\n        Same as |longitude|.\n    \\end{key}\n    %\n\\begin{codeexample}[preamble={\\usetikzlibrary{3d}}]\n\\begin{tikzpicture}[->]\n  \\draw (0,0,0) -- (xyz spherical cs:radius=1);\n  \\draw (0,0,0) -- (xyz spherical cs:radius=1,latitude=90);\n  \\draw (0,0,0) -- (xyz spherical cs:radius=1,longitude=90);\n\\end{tikzpicture}\n\\end{codeexample}\n    %\n\\end{coordinatesystem}\n\n\n\\subsection{Coordinate Planes}\n\nSometimes drawing with full three dimensional coordinates is not necessary and\nit suffices to draw in two dimensions but in a different coordinate plane.  The\nfollowing options help you to switch to a different plane.\n\n\n\\subsubsection{Switching to an arbitrary plane}\n\n\\begin{key}{/tikz/plane origin=\\meta{point} (initially {(0,0)})}\n    Origin of the plane.\n\\end{key}\n\n\\begin{key}{/tikz/plane x=\\meta{point} (initially {(1,0)})}\n    Unit vector of the $x$-direction in the new plane.\n\\end{key}\n\n\\begin{key}{/tikz/plane y=\\meta{point} (initially {(0,1)})}\n    Unit vector of the $y$-direction in the new plane.\n\\end{key}\n\n\\begin{key}{/tikz/canvas is plane}\n    Perform the transformation into the new canvas plane using the units above.\n    Note that you have to set the units \\emph{before} calling\n    |canvas is plane|.\n    %\n\\begin{codeexample}[preamble={\\usetikzlibrary{3d}}]\n\\begin{tikzpicture}[\n    ->,\n    plane x={(0.707,-0.707)},\n    plane y={(0.707,0.707)},\n    canvas is plane,\n]\n    \\draw (0,0) -- (1,0);\n    \\draw (0,0) -- (0,1);\n\\end{tikzpicture}\n\\end{codeexample}\n    %\n\\end{key}\n\n\n\\subsubsection{Predefined planes}\n\n\\begin{key}{/tikz/canvas is xy plane at z=\\meta{dimension}}\n    A plane with\n    %\n    \\begin{itemize}\n        \\item |plane origin={(0,0,|\\meta{dimension}|)}|,\n        \\item |plane x={(1,0,|\\meta{dimension}|)}|, and\n        \\item |plane y={(0,1,|\\meta{dimension}|)}|.\n    \\end{itemize}\n\\end{key}\n\n\\begin{key}{/tikz/canvas is yx plane at z=\\meta{dimension}}\n    A plane with\n    %\n    \\begin{itemize}\n        \\item |plane origin={(0,0,|\\meta{dimension}|)}|,\n        \\item |plane x={(0,1,|\\meta{dimension}|)}|, and\n        \\item |plane y={(1,0,|\\meta{dimension}|)}|.\n    \\end{itemize}\n\\end{key}\n\n\\begin{key}{/tikz/canvas is xz plane at y=\\meta{dimension}}\n    A plane with\n    %\n    \\begin{itemize}\n        \\item |plane origin={(0,|\\meta{dimension}|,0)}|,\n        \\item |plane x={(1,|\\meta{dimension}|,0)}|, and\n        \\item |plane y={(0,|\\meta{dimension}|,1)}|.\n    \\end{itemize}\n\\end{key}\n\n\\begin{key}{/tikz/canvas is zx plane at y=\\meta{dimension}}\n    A plane with\n    %\n    \\begin{itemize}\n        \\item |plane origin={(0,|\\meta{dimension}|,0)}|,\n        \\item |plane x={(0,|\\meta{dimension}|,1)}|, and\n        \\item |plane y={(1,|\\meta{dimension}|,0)}|.\n    \\end{itemize}\n\\end{key}\n\n\\begin{key}{/tikz/canvas is yz plane at x=\\meta{dimension}}\n    A plane with\n    %\n    \\begin{itemize}\n        \\item |plane origin={(|\\meta{dimension}|,0,0)}|,\n        \\item |plane x={(|\\meta{dimension}|,1,0)}|, and\n        \\item |plane y={(|\\meta{dimension}|,0,1)}|.\n    \\end{itemize}\n\\end{key}\n\n\\begin{key}{/tikz/canvas is zy plane at x=\\meta{dimension}}\n    A plane with\n    %\n    \\begin{itemize}\n        \\item |plane origin={(|\\meta{dimension}|,0,0)}|,\n        \\item |plane x={(|\\meta{dimension}|,0,1)}|, and\n        \\item |plane y={(|\\meta{dimension}|,1,0)}|.\n    \\end{itemize}\n\\end{key}\n\n\n\\subsection{Examples}\n\n\\begin{codeexample}[preamble={\\usetikzlibrary{3d}}]\n\\begin{tikzpicture}[z={(10:10mm)},x={(-45:5mm)}]\n  \\def\\wave{\n    \\draw[fill,thick,fill opacity=.2]\n     (0,0) sin (1,1) cos (2,0) sin (3,-1) cos (4,0)\n           sin (5,1) cos (6,0) sin (7,-1) cos (8,0)\n           sin (9,1) cos (10,0)sin (11,-1)cos (12,0);\n    \\foreach \\shift in {0,4,8}\n    {\n      \\begin{scope}[xshift=\\shift cm,thin]\n        \\draw (.5,0)  -- (0.5,0 |- 45:1cm);\n        \\draw (1,0)   -- (1,1);\n        \\draw (1.5,0) -- (1.5,0 |- 45:1cm);\n        \\draw (2.5,0) -- (2.5,0 |- -45:1cm);\n        \\draw (3,0)   -- (3,-1);\n        \\draw (3.5,0) -- (3.5,0 |- -45:1cm);\n      \\end{scope}\n    }\n  }\n  \\begin{scope}[canvas is zy plane at x=0,fill=blue]\n    \\wave\n    \\node at (6,-1.5) [transform shape] {magnetic field};\n  \\end{scope}\n  \\begin{scope}[canvas is zx plane at y=0,fill=red]\n    \\draw[help lines] (0,-2) grid (12,2);\n    \\wave\n    \\node at (6,1.5) [rotate=180,xscale=-1,transform shape] {electric field};\n  \\end{scope}\n\\end{tikzpicture}\n\\end{codeexample}\n\n\\begin{codeexample}[preamble={\\usetikzlibrary{3d}}]\n\\begin{tikzpicture}\n  \\begin{scope}[canvas is zy plane at x=0]\n    \\draw (0,0) circle (1cm);\n    \\draw (-1,0) -- (1,0) (0,-1) -- (0,1);\n  \\end{scope}\n\n  \\begin{scope}[canvas is zx plane at y=0]\n    \\draw (0,0) circle (1cm);\n    \\draw (-1,0) -- (1,0) (0,-1) -- (0,1);\n  \\end{scope}\n\n  \\begin{scope}[canvas is xy plane at z=0]\n    \\draw (0,0) circle (1cm);\n    \\draw (-1,0) -- (1,0) (0,-1) -- (0,1);\n  \\end{scope}\n\\end{tikzpicture}\n\\end{codeexample}\n\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: \"pgfmanual-pdftex-version\"\n%%% End:\n", "meta": {"hexsha": "79bb47a2f76ba9bf58f2d89483796b38fac2fd70", "size": 7412, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Texlive_Windows_x32/2020/texmf-dist/doc/generic/pgf/text-en/pgfmanual-en-library-3d.tex", "max_stars_repo_name": "waqas4afzal/LatexUrduBooksTools", "max_stars_repo_head_hexsha": "52fe6e0cd5af6b4610fd344a7392cca11bc5a72e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Texlive_Windows_x32/2020/texmf-dist/doc/generic/pgf/text-en/pgfmanual-en-library-3d.tex", "max_issues_repo_name": "waqas4afzal/LatexUrduBooksTools", "max_issues_repo_head_hexsha": "52fe6e0cd5af6b4610fd344a7392cca11bc5a72e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Texlive_Windows_x32/2020/texmf-dist/doc/generic/pgf/text-en/pgfmanual-en-library-3d.tex", "max_forks_repo_name": "waqas4afzal/LatexUrduBooksTools", "max_forks_repo_head_hexsha": "52fe6e0cd5af6b4610fd344a7392cca11bc5a72e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1300813008, "max_line_length": 79, "alphanum_fraction": 0.6150836481, "num_tokens": 2532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.3125228910109688}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\section{Dynamics of inflation}\n\n\\marginpar{Monday\\\\ 2020-10-19, \\\\ compiled \\\\ \\today}\n\nOur action will be in the form \n%\n\\begin{align}\nS = S_{EH} + S_\\varphi + S _{\\text{matter}}\n\\,,\n\\end{align}\n%\nwhere \\(S_{EH}\\) is the Einstein-Hilbert action for the metric, \\(S_\\varphi \\) is the action for the field \\(\\varphi \\), while ``matter'' encompasses all the other fields:\n%\n\\begin{align}\nS = \\frac{1}{16 \\pi G} \\int \\dd[4]{x} \\sqrt{-g} R \n+ \\int \\dd[4]{x} \\sqrt{-g} \\mathscr{L}_\\varphi [\\varphi , g_{\\mu \\nu }]\n+ S _{\\text{matter}}\n\\,.\n\\end{align}\n\nWe are using the invariant volume element \\(\\dd[4]{x} \\sqrt{-g}\\), which represents the physical 4-volume regardless of the coordinates.\n\nThe simplest possibility for the Lagrangian of a scalar field which is able to drive inflation reads: \n%\n\\begin{align}\n\\mathscr{L}_{\\varphi } = -\\frac{1}{2} g^{\\mu \\nu } \\nabla_{\\mu } \\varphi \\nabla_{\\nu } \\varphi  - V(\\varphi )\n\\,,\n\\end{align}\n%\nfor a \\emph{real} scalar field \\(\\varphi \\).\nAlso, note that we did not consider any explicit coupling of \\(\\varphi \\) with gravity or other fields: these kinds of terms, which go by the name ``nonminimal coupling'', might look like \\(\\xi \\varphi^2 R\\).\n\nThese kinds of nonminimal theories represent one of the simplest extensions of GR: they are \\emph{scalar-tensor} theories, and in them the field \\(\\varphi \\) as well as \\(g_{\\mu \\nu }\\) can mediate gravity. \nOne of the theories which currently fits the cosmological data best is of this kind. \n\nWhat could we put in the potential? The mass is given by \\(m_\\varphi^2 = \\pdv*[2]{V}{\\varphi }\\), so a simple mass term would look like \\(m^2 \\varphi^2 / 2\\), but we could also have quartic terms like \\(\\lambda \\varphi^{4} / 4\\): these are self-interaction terms. \n\nThe other fields will typically be negligible during inflation since their energy density is quickly ``redshifted away''. \nSometimes some of them are non-negligible: this happens if they are coupled to the scalar field, and we must consider them; we typically do so in an ``effective'' way, by inserting them into the potential \\(V(\\varphi )\\). \n\nWe can associate an energy-momentum tensor to the scalar field: in general, it is defined by \n%\n\\begin{align}\nT_{\\mu \\nu }^{(\\varphi )} = - \\frac{2}{\\sqrt{-g}} \\fdv{S_{\\varphi }}{g^{\\mu \\nu }}\n\\,.\n\\end{align}\n\nThis comes from the way we write the Einstein equations from a variational principle. \nFor our scalar field, integrating by parts inside the action, we find \n%\n\\begin{align}\nT_{\\mu \\nu } = \\frac{2}{\\sqrt{-g}} \\qty[\n    -\\pdv{(\\sqrt{-g} \\mathscr{L}_\\varphi )}{g^{\\mu \\nu }}\n    +\n    \\partial_{\\alpha }\n    \\pdv{(\\sqrt{-g} \\mathscr{L}_\\varphi )}{\\tensor{g}{^{\\mu \\nu }_{,\\alpha }}} \n    + \\text{higher order terms}\n]\n\\,.\n\\end{align}\n\n% \\todo[inline]{Is the derivative covariant?}\n\nThe reason for the alternating signs is that we must integrate by parts in order to get the expression in this form. \nWe then get \n%\n\\begin{align}\nT^{(\\varphi )}_{\\mu \\nu } = \n- 2 \\frac{\\partial\\mathscr{L}_\\varphi }{\\partial g^{\\mu \\nu }} + \\frac{2}{\\sqrt{-g}} \\mathscr{L}_\\varphi \\pdv{\\sqrt{-g}}{g^{\\mu \\nu }}\n\\,,\n\\end{align}\n%\nsince there is no dependence on the derivative(s) of the metric in our case.\n\\begin{claim}\nThe following expression holds:\n% We need the explicit expression \n%\n\\begin{align}\n\\pdv{\\sqrt{-g}}{g^{\\mu \\nu }} = - \\frac{1}{2} \\sqrt{-g} g_{\\mu \\nu }\n\\,.\n\\end{align}\n\\end{claim}\n\n\\begin{proof}\nThe expression can be derived from the general matrix relation  \\(\\Tr \\log M = \\log \\det M\\), applied taking \\(M = g^{\\mu \\nu }\\): abusing the notation a bit with the indices\n%\n\\begin{align}\n\\Tr \\log g^{\\mu \\nu } = \\log \\det g^{\\mu \\nu } \n\\,,\n\\end{align}\n%\nwhich we then differentiate, using \\(g = \\det g_{\\mu \\nu }\\), the fact that the trace is linear, and the matrix logarithmic derivative expression \\(\\delta \\log M = M^{-1} \\delta M\\):\\footnote{Which holds as long as \\(M^{-1}\\) and \\(\\delta M\\) commute. }\n%\n\\begin{align}\n\\Tr \\qty(M^{-1} \\delta M) &= \\frac{ \\delta \\det g^{\\mu \\nu }}{\\det g^{\\mu \\nu }} = \\frac{ \\delta (1/g)}{ 1/g}  \\\\\n\\Tr \\qty(g_{\\mu \\nu } \\delta g^{\\nu \\rho }) &= - \\frac{ \\delta g}{g}  \\\\\ng_{\\mu \\nu } \\delta g^{\\mu \\nu } &= - \\frac{ \\delta g}{g}\n\\marginnote{Symmetry of the metric's indices.}\n\\,.\n\\end{align}\n\nLet us now consider a variation of \\(\\sqrt{-g}\\): \n%\n\\begin{align}\n\\delta \\sqrt{-g} &= - \\frac{1}{2} \\frac{1}{\\sqrt{-g}} \\delta g = + \\frac{1}{2} \\underbrace{\\frac{1}{\\sqrt{-g}} g}_{-\\sqrt{-g}} g_{\\mu \\nu } \\delta g^{\\mu \\nu }   \\\\\n\\fdv{\\sqrt{-g}}{g^{\\mu \\nu }} &= - \\frac{\\sqrt{-g}}{2} g_{\\mu \\nu }\n\\,.\n\\end{align}\n\nThis is the final result. We used the fact that \\(g / \\sqrt{-g} = - \\sqrt{-g}\\), which is the correct solution of \\((g / \\sqrt{-g})^2 = -g\\) because we know  \\(g\\) to be negative.\n\\end{proof}\n\nThis yields \n%\n\\begin{align}\nT^{(\\varphi )}_{\\mu \\nu }  &= \n- 2 \\pdv{\\mathscr{L}_\\varphi }{g^{\\mu \\nu }} + \\mathscr{L}_\\varphi g_{\\mu \\nu }\n\\\\\n&= \\partial_{\\mu } \\varphi \\partial_{\\nu } \\varphi \n+ g_{\\mu \\nu } \\qty[- \\frac{1}{2} g^{\\alpha \\beta } \\varphi_{, \\alpha } \\varphi_{, \\beta } - V(\\varphi )] \n\\,.\n\\end{align}\n\n\\begin{claim}\nIn general, this is a perfect fluid stress energy tensor, with \n%\n\\begin{align}\nP &= -\\frac{1}{2} g^{\\alpha \\beta } \\varphi_{, \\alpha } \\varphi_{, \\beta } - V(\\varphi )  \\\\\n\\rho &= - \\frac{1}{2} g^{\\alpha \\beta } \\varphi_{, \\alpha } \\varphi_{, \\beta }  + V(\\varphi ) \\\\\nu_\\mu &= \\frac{\\partial_{\\mu}\\varphi}{\\abs{\\partial \\varphi }}  \\\\\n\\abs{\\partial \\varphi} &= \\sqrt{- g^{\\alpha \\beta } \\varphi_{, \\alpha } \\varphi_{, \\beta }}\n\\,.\n\\end{align}\n\\end{claim}\n\n\\begin{proof}\nAs the parameters are given, we only need to verify that the expressions are equivalent: \n%\n\\begin{align}\nT_{\\mu \\nu } &= (\\rho + P ) u_\\mu u_\\nu + P g_{\\mu \\nu }   \\\\\n&= \\underbrace{(- g^{\\alpha \\beta } \\varphi_{, \\alpha } \\varphi_{, \\beta } )}_{\\abs{\\partial \\varphi}^2} u_\\mu u_\\nu + \\qty( -\\frac{1}{2} g^{\\alpha \\beta } \\varphi_{, \\alpha } \\varphi_{, \\beta } - V(\\varphi ) ) g_{\\mu \\nu }  \\\\\n&= \\varphi_{, \\mu } \\varphi_{, \\nu } - \\qty(\\frac{1}{2} g^{\\alpha \\beta } \\varphi_{, \\alpha } \\varphi_{, \\beta } + V(\\varphi )) g_{\\mu \\nu }\n\\,.\n\\end{align}\n\\end{proof}\n\nWe start by considering a homogeneous and isotropic case, and then perturb it. This is done by splitting the field into the average classical background motion of \\(\\varphi \\), called \\(\\varphi_0 \\) \n%\n\\begin{align}\n\\varphi = \\varphi (\\vec{x}, t) = \\varphi_0 (t) + \\delta \\varphi (\\vec{x}, t)\n\\,,\n\\end{align}\n%\nwhere \\(\\varphi_0 \\) will be the VEV of the field: \\(\\varphi_0 = \\bra{0} \\varphi (\\vec{x}, t) \\ket{0}\\), while \\(\\delta \\varphi \\) encompasses the quantum fluctuations. \n\nAre we allowed to do this kind of split?\nFormally yes, but we need to guarantee that the perturbations are indeed small compared to the classical trajectory: \\(\\expval{ \\delta \\varphi^2} \\ll \\varphi_0^2 (t)\\).\nWe consider the variance since it is the first nonzero moment, as \\(\\expval{ \\delta \\varphi }= 0\\). \n\nThis will not always be the case, sometimes the fluctuation will be dominating; however usually for an inflationary model to work we expect that the condition is satisfied.\nThe fluctuations are what generates the density fluctuations which create the anisotropies in the CMB photons: we know that the size of these anisotropies is of the order of one part in \\num{e5}, so we can give a qualitative argument for the perturbations of the scalar field to be relatively small compared to the mean value. \n\nIf we do the explicit computation for the energy-momentum tensor of the classical background \\(\\varphi_0\\) only we find:\n%\n\\begin{align} \\label{eq:energy-momentum-scalar-field}\nT^{0}_{0} &= - \\qty( \\frac{1}{2} \\dot{\\varphi}_0(t)^2 + V(\\varphi_0 )) = - \\rho_\\varphi (t)   \\\\\nT^{i}_{j} &= \\qty( \\frac{1}{2} \\dot{\\varphi}_0^2 (t) - V(\\varphi_0 )) \\delta^{i}_{j} = P_\\varphi \\delta^{i}_{j}\n\\,.\n\\end{align}\n\nThis is a perfect-fluid energy-momentum tensor. \nIf we are in a regime for which \n%\n\\begin{align}\n\\frac{1}{2} \\dot{\\varphi}_0^2 (t) \\ll V(\\varphi_0 )\n\\,\n\\end{align}\n%\nwhen we have \\(P_\\varphi \\approx - \\rho _\\varphi \\): this is a \\emph{quasi De Sitter} expansion, with \\(w_\\varphi \\approx -1\\). \n\nThis is achieved if the potential for the scalar field is ``flat enough'': then, we reach a \\emph{friction-domination} regime, which is commonly called \\emph{slow-roll} inflation. \n\n\\todo[inline]{Insert picture of flat potential}\n\nIf \\(V(\\varphi )\\) is approximately a constant, then it mimics a cosmological constant. \nInflation is driven by the vacuum energy density associated with the scalar field. \n\nLet us look at the slow-roll dynamics in more detail. \nWhat is the equation of motion for this (quantum!) scalar field?\n\n\\begin{claim}\n\nIt is just the Klein-Gordon equation, which can be derived by functional differentiation of the action with respect to \\(\\varphi \\): \n%\n\\begin{align}\n\\square \\varphi = \\pdv{V}{\\varphi }\n\\,.\n\\end{align}\n\\end{claim}\n\nThe Dalambertian operator here reads \n%\n\\begin{align}\n\\square \\varphi = \\frac{1}{\\sqrt{-g}} \\qty(g^{\\mu \\nu } \\sqrt{-g} \\varphi_{, \\mu })_{, \\nu }\n\\,.\n\\end{align}\n\n\\begin{proof}\nFunctionally differentiating the action yields\n%\n\\begin{align}\n\\fdv{S}{\\varphi } &= \\fdv{}{\\varphi } \\int \\dd[4]{x} \\sqrt{-g} \\qty(- \\frac{1}{2} g^{\\alpha \\beta } \\varphi_{, \\alpha } \\varphi_{, \\beta } - V(\\varphi ))  \\\\\n&= \\fdv{}{\\varphi } \\int \\dd[4]{x} \\qty(\\qty( \\frac{\\sqrt{-g}}{2} g^{\\alpha \\beta } \\varphi_{, \\alpha })_{,\\beta } \\varphi  - V(\\varphi ) \\sqrt{-g})  \\\\\n&= \\sqrt{-g} \\qty( \\frac{1}{\\sqrt{-g}} \\partial_{\\beta } \\qty( \\sqrt{-g} g^{\\alpha \\beta } \\partial_{\\alpha } \\varphi ) - \\pdv{V}{\\varphi }) = 0\n\\,.\n\\end{align}\n\n\n\\end{proof}\n\nLet us see what this reduces to in a \\textbf{flat FLRW} metric: then \\(\\sqrt{-g} = a^3\\), so \n%\n\\begin{align}\n\\square \\varphi = \\frac{1}{a^3} \\qty(g^{00} a^3\\varphi_{, 0})_{, 0}\n+ \\frac{1}{a^3} \\qty(g^{ii} a^3\\varphi_{, i})_{, i} &= \\pdv{V}{\\varphi }  \\\\\n- \\ddot{\\varphi} - \\dot{\\varphi} 3\\frac{\\dot{a}}{a}\n+ \\frac{\\nabla^2}{a^2} \\varphi \n&= \\pdv{V}{ \\varphi }  \\\\\n\\ddot{\\varphi} + 3 H \\dot{\\varphi} - \\frac{\\nabla^2 \\varphi }{a^2} &= - \\pdv{V}{\\varphi }\n\\,.\n\\end{align}\n\nThe term \\(3 H \\dot{\\varphi}\\) is a kind of \\emph{friction} term: the propagation of the field is ``held back'' by the expansion. \nIf we consider the background field, it will be constant in space, so it will evolve as \n%\n\\begin{align} \\label{eq:klein-gordon-scalar-field-flat-FLRW}\n\\ddot{\\varphi}_0 + 3 H \\dot{\\varphi}_0 = - \\pdv{V}{\\varphi_0 }\n\\,.\n\\end{align}\n\nWe then must solve this equation combined with the Friedmann equation \n%\n\\begin{align}\nH^2 = \\frac{8 \\pi G}{3} \\qty(\\rho _\\varphi + \\rho _m + \\rho _r) - \\frac{k}{a^2}\n\\,.\n\\end{align}\n\nThe matter and radiation densities scale like \\(a^{-3}\\) for \\(\\rho _m\\), \\(a^{-4}\\) for \\(\\rho _r\\); in this early phase the scalar field will dominate the dynamics, so the equation will simplify to \n%\n\\begin{align} \\label{eq:hubble-rate-scalar-field-flat-FLRW}\nH^2 \\approx \\frac{8 \\pi G}{3} V(\\varphi_0 )\n\\,.\n\\end{align}\n\nUnder these slow-roll conditions, we also have \\(\\ddot{\\varphi}_0 \\ll 3 H \\dot{\\varphi}_0\\): therefore equation \\eqref{eq:klein-gordon-scalar-field-flat-FLRW} simplifies to\n%\n\\begin{align} \\label{eq:approx-EOM-scalar-field-flat-FLRW}\n3 H \\dot{\\varphi}_{0} \\approx - \\pdv{V}{\\varphi_0 }\n\\,.\n\\end{align}\n\nWe also expect that \\(V\\) and all of its derivatives change very slowly with \\(\\varphi \\). \nThis means that in this equation we have \\(\\pdv{V}{\\varphi_0 } \\approx \\const\\), as well as \\(H \\approx \\const\\): this is the same equation which is obeyed by a particle under a constant force and friction: it will then reach the asymptotic ``\\textbf{terminal velocity}'' and move with a constant \\(\\dot{\\varphi}_0 \\). This solution is an attractor. \n\nWe typically write this as \\(\\dot{\\varphi} = - V' (\\varphi_0 ) / 3H\\), and \\(H^2 = \\frac{8 \\pi G}{3} V(\\varphi )\\). \n\n\\subsection{Slow-roll parameters}\n\nThese are parameters we need to quantify how much the potential indeed looks like we expected. \n\nThe first parameter we define is\n%\n\\begin{align} \\label{eq:slow-roll-epsilon-alternative}\n\\epsilon \n= - \\frac{\\dot{H}}{H^2} = \n+ 4 \\pi G \\frac{\\dot{\\varphi}^2}{H^2} \\approx \\frac{3}{2} \\frac{\\dot{\\varphi}^2}{V} = \\frac{1}{16 \\pi G} \\qty(\\frac{V'}{V})^2\n\\,,\n\\end{align}\n%\nwhere the manipulations follow from equations \\eqref{eq:approx-EOM-scalar-field-flat-FLRW} and \\eqref{eq:hubble-rate-scalar-field-flat-FLRW}.\n\n\\begin{proof}\nLet us show that the manipulations work. We start by differentiating equation \\eqref{eq:hubble-rate-scalar-field-flat-FLRW} with respect to time: \n%\n\\begin{align}\n2 H \\dot{H} &= \\frac{8 \\pi G}{3} \\pdv{V}{\\varphi } \\dot{\\varphi}  \\\\\n\\dot{H} &= 4 \\pi G \\underbrace{\\frac{V'}{3 H}}_{- \\dot{\\varphi}} \\dot{\\varphi} = - 4 \\pi G \\dot{\\varphi}^2 \\label{eq:hdot-phidot-relation}\n\\,,\n\\end{align}\n%\nwhich, divided by \\(H^2\\), yields the first equality. \n\nThe second equality comes from the substitution of the expression for \\(H^2\\) from equation \\eqref{eq:hubble-rate-scalar-field-flat-FLRW}. \nThen, we can square the relation \\(\\dot{\\varphi} = - V' / 3 H\\) to get \n%\n\\begin{align}\n\\dot{\\varphi}^2 = \\qty(\\frac{V'}{3H})^2\n\\,,\n\\end{align}\n%\nwhich allows us to manipulate \n%\n\\begin{align}\n\\frac{3}{2} \\frac{\\dot{\\varphi}^2}{V} &= \\frac{3}{2V} \\qty(\\frac{V'}{3H})^2  \\\\\n&= \\frac{3 (V')^2}{2V \\frac{8 \\pi G}{3} V}  \\\\\n&= \\frac{1}{16 \\pi G} \\qty( \\frac{V'}{V})^2\n\\,.\n\\end{align}\n\\end{proof}\n\n\\begin{claim}\nThe relation \\(\\dot{H} = - 4 \\pi G \\dot{\\varphi}^2\\) holds exactly in the case of a single scalar field with the action we have been using so far. \n\\end{claim}\n\n\\begin{proof}\n\nWe start from the Friedmann equation for flat spacetime: \n%\n\\begin{align}\nH^2 &= \\frac{8 \\pi G}{3} \\rho = \\frac{8 \\pi G}{3} \\qty(V(\\varphi ) + \\frac{1}{2} \\dot{\\varphi}^2 \n% - \\frac{1}{2} \\frac{\\abs{\\nabla\\varphi}^2}{a^2} \n) \n\\,.\n\\end{align}\n\nNow, we proceed as we did previously, by differentiating everything with respect to time: \n%\n\\begin{align}\n2 H \\dot{H} &= \\frac{8 \\pi G}{3} \\qty( V' \\dot{\\varphi} + \\ddot{\\varphi} \\dot{\\varphi})  \\\\\n% - \\frac{1}{a^2} \\underbrace{\\partial_{i} \\varphi \\partial_{i} \\dot{\\varphi}}_{= -\\dot{\\varphi} \\nabla^2 \\varphi }\n&= \\frac{8 \\pi G}{3} \\dot{\\varphi} \\qty(- 3 H \\dot{\\varphi}) \\marginnote{Equation of motion.}  \\\\\n\\dot{H} &= - 4 \\pi G \\dot{\\varphi}^2\n\\,,\n\\end{align}\n%\nwhere we assumed homogeneity. The derivation seems not to work if we do not assume it. \n\\end{proof}\n\n\nRequiring \\(\\epsilon \\ll 1\\) can also be stated as asking that\\footnote{A note on the dimensionality: the potential \\(V\\) has the dimensions of the Lagrangian: in natural units, \\SI{}{m^{-4}}. The field \\(\\varphi \\) has the dimensions of an inverse length (a mass), just like the Hubble rate.}\n%\n\\begin{align}\n\\frac{(V')^2}{16 \\pi G V^2} &\\ll 1  \\\\\n\\frac{(V')^2}{V} &\\ll 16 \\pi G V = \\frac{2}{3} H^2 \\\\ \n\\frac{1}{V} \\qty(\\pdv{V}{\\varphi })^2 &\\ll H^2\n\\,.\n\\end{align}\n\nSo, \\(\\epsilon \\) gives a bound on the first derivative of the potential; the second derivative is controlled by the parameter \n%\n\\begin{align}\n\\eta = - \\frac{\\ddot{\\varphi}}{H \\dot{\\varphi}\n}\n\\,,\n\\end{align}\n%\nand we can also define \n%\n\\begin{align}\n\\eta _V = \\frac{1}{3} \\frac{V''}{H^2} = \\frac{1}{8 \\pi G} \\frac{V''}{V}\n\\,.\n\\end{align}\n\nAsking that \\(\\eta _V \\ll 1 \\) is equivalent to \\(V'' \\ll H^2\\). \n\n\\begin{claim}\nThese three parameters are related by \\(\\eta = \\eta _V - \\epsilon \\).\n\\end{claim}\n% We also can ask that \\(\\abs{\\eta _V} < 1\\).\n\n\\begin{proof}\nWe start from the relation \\(\\dot{\\varphi} \\approx - V' / (3H)\\). Differentiating it with respect to time will yield the desired relation: \n%\n\\begin{align}\n\\ddot{\\varphi} &\\approx - \\dv{}{t} \\qty( \\frac{V'}{3H})  \\\\\n&= - \\frac{1}{3H} V'' \\dot{\\varphi} - \\frac{V'}{3} \\underbrace{\\qty(- \\frac{\\dot{H}}{H^2})}_{\\epsilon }  \\\\\n&= - \\dot{\\varphi} H \\frac{V''}{3H^2} - \\frac{V'}{3} \\epsilon  \\\\\n&= - \\dot{\\varphi} H \\eta _V - \\frac{V'}{3} \\epsilon  \\\\\n\\underbrace{-\\frac{\\ddot{\\varphi}}{H \\ddot{\\varphi}}}_{\\eta } &= \\eta _V - \\epsilon  \n\\,.\n\\end{align}\n\\end{proof}\n\n\\todo[inline]{Is it ok to differentiate this, even though we \\emph{know }that \\(\\ddot{\\varphi} = - V' - 3 H \\dot{\\varphi}\\) from the EOM?}\n\n\\end{document}\n", "meta": {"hexsha": "0061dd82b69fba9d895394aaba590a5214f44bc2", "size": 16149, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ap_third_semester/early_universe/oct19.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "ap_third_semester/early_universe/oct19.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ap_third_semester/early_universe/oct19.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 41.4076923077, "max_line_length": 350, "alphanum_fraction": 0.6451792681, "num_tokens": 5750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3125228910109688}}
{"text": "%!TEX root = ../COSCFair.tex\n\\section{Related Work} \\label{sec:related}\n\nIn this section, we discuss various fairness metrics defined in the literature and the mitigation algorithms proposed. We start by discussing the different fairness metrics.\n\n\\subsection{Fairness Metrics}\nThere are various fairness metrics in the literature that are developed to quantify the fairness/unfairness in a dataset or the outcomes of a system. They can be used to measure the fairness in different stages of the machine learning pipeline. \n% There are two fundamental viewpoints or approaches to the notion of fairness due to its nature, which are axiomatically defined as \"What You See Is What You Get (WYSIWYG)\" and \"We Are All Equal (WAE)\"  \\cite{friedler2016possibility}. \n% \\citeauthor{friedler2016possibility} \\cite{friedler2016possibility} formalized fairness as the mapping from \"construct space\" (the space that captures the whole population's meaningful attributes) to \"observed space\" (the space that can capture only some observable parts of the construct-space), and then to the \"decision space\" (the space of outcomes that are predicted). According to WYSIWYG, the collected dataset should reflect the original distribution and the characteristics of the population, while the WAE says that all groups are essentially the same.  The metrics regarding demographic parity-related metrics reflect the WAE view, whereas the equality of odds-related metrics reflect WYSIWYG. The other metrics do not have a certain choice of worldview but they are located in between these two ideas. \n\n\\stitle{Statistical fairness metrics:} the first category of fairness metrics is called \\emph{statistical fairness metrics} or \\emph{associational fairness} metrics \\cite{salimi2019interventional}.  The main idea behind the statistical fairness metrics is that there must be some parity with a small amount of difference in the measurements between the different groups \\cite{chouldechova2018frontiers}. These statistical metrics are always applied to groups of people identified in the dataset so they are called group-based metrics. A set of these metrics consider only the predicted outcome while other metrics consider both predicted and actual outcomes, or predicted probabilities and actual outcomes \\cite{verma2018fairness_explained}.\n\n\nAn example of statistical fairness metrics is the \\emph{demographic parity}, which states that a classification algorithm is fair if the different groups according to a sensitive attribute have the same probability to be assigned to the positive outcome \\cite{dwork2012fairness,kamishima2011fairness}. It means that the sensitive attribute and the outcome should be statistically independent of each other. The \\emph{conditional statistical parity} considers a small additional set of \"legitimate\" attributes while checking the parity in the outcome \\cite{corbett2017algorithmic}. In other words, the sensitive attribute(s) should be independent of the outcome given (a set of) legitimate attributes. \n\nA metric emanated from a legal rule \\cite{US_guideline} and formulated in \\cite{feldman2015certifying} is called \\emph{disparate impact}. A dataset is said to have a disparate impact if the ratio of the probability of getting a positive outcome given the unprivileged group to the probability of getting a positive outcome given the privileged group is smaller than $0.8$. This metric is applied to the actual outcomes or predicted outcomes separately. \n\nThe \\emph{Predictive parity} metric considers the actual outcomes (original class labels) and compare them to the predicted outcomes to quantify fairness \\cite{verma2018fairness_explained}. A classifier is considered fair if both unprivileged and privileged groups have the same Positive Predictive Value (PPV). \\emph{Equalized odds} is similar to predictive parity, which deems a classifier fair when the true positive rates and the false positive rates for both unprivileged and privileged groups are equal \\cite{zafar2017fairness}. A relaxed version of equalized odds is the \\emph{equal opportunity} \\cite{hardt2016equal_odds_opport}, which only considers one part of the definition of equalized odds. A classifier is fair by equal opportunity if it yields an equal true positive rate for both unprivileged and privileged groups. \n\n\nMore statistical fairness metrics can also be found in the literature such as the \\emph{overall accuracy equality} \\cite{berk2018fairness}, which considers that true negative outcomes are as desirable as true positive outcomes \\cite{berk2018fairness}. Another metric defined in \\cite{berk2018fairness} is \\emph{treatment equality}, which requires a classifier to produce equal false negative and false positive ratios. The treatment term is used to convey that these ratios can be a policy lever to achieve different kinds of fairness depending on the domain \\cite{berk2018fairness}.\n\n\n% The last type of statistical fairness metrics is based on both predicted probability scores calculated by a classifier and actual outcomes, or original labels, of a dataset. \\emph{Test fairness}, or also named as calibration, is one of these metrics that requires a classifier to produce equal prediction probabilities for both protected and unprotected groups to truly belong to the positive class to be deemed as well-calibrated \\cite{chouldechova2017fair}. Well-calibrated means that a classifier does not contain any predictive bias. It is a widely used metric as a standard for fairness assessment in the literature \\cite{chouldechova2017fair}. Another metric in this called \\emph{well-calibration}, which is an expanded version of the calibration metric. According to this metric, next to the equality conditions in calibration, the predicted probability value should also be equal to some value \\emph{P}. This metric means that if a classifier finds that a set of samples in a dataset have a certain probability value \\emph{p} of being assigned to the positive class, then also \\emph{p} percentage of these samples (people) should originally have a positive class label. \n\n% The third fairness metric in this type is called \\emph{the balance for positive class}, which deems a classifier fair if samples with the positive class label from both protected and unprotected groups have an equal predicted probability score \\cite{kleinberg2017inherent}. \\citeauthor{kleinberg2017inherent} have also formalized another fairness metric called \\emph{the balance fore negative class} which is the opposite version of the previous fairness metric. This time, a classifier should provide an equal predicted probability score for the samples from both protected and unprotected groups constituting the negative class in a dataset. Thus, to satisfy the \"balance for negative class\" metric, people with negative class labels should have the same expected probability score, no matter what their sensitive attribute value is. It is important to note that these statistical metrics that require predicted probability scores can only be used with a limited number of classifiers that can calculate such scores, such as logistic regression or support vector machines.\n\n\n% There are several more metrics defined in the literature, however, most of them have different names for the same metric formalization, as shown above with some examples. At the first glance, statistical fairness metrics seem very attractive due to their easy-to-understand nature. \n\nIt should be noted that statistical fairness metrics cannot guarantee fairness for individuals or more fine-grained sub-groups of the unprivileged  groups \\cite{chouldechova2018frontiers}. Furthermore, there is a disagreement among different statistical fairness metrics since their goals and the considered criteria are different, which is formalized and proven with the \\emph{impossibility theorem} \\cite{chouldechova2017fair,kleinberg2017inherent,pleiss2017calibration}. According to this theorem, it is impossible to satisfy both \\emph{equalized odds} and  \\emph{predictive parity} or calibration for a classifier simultaneously if the base rates of groups are different. \n% Only one of them can be satisfied at a time, unless the dataset has the same base rate for both protected and unprotected groups, which means that both groups have precisely the same number of samples with the positive class label, or unless the classifier in question is a perfect classifier which never makes any errors. Only in these two specific and rare cases, these three fairness metrics can be satisfied simultaneously. Due to all of these limitations mentioned above, researchers have come up with new fairness metrics that have different points of view. In the next sections, other proposed metrics that tackle these limitations and try to solve in respective papers are further explained.\n\n\n\n\\stitle{Individual fairness metrics:} This type of metrics consider the outcomes on the individual level. For example, the  \\emph{fairness through unawareness} \\cite{kusner2017counterfactual} and \\emph{individual fairness} \\cite{dwork2012fairness} are based on the fact that similar individuals should be treated similarly in classification tasks. Joseph et al. in  \\cite{joseph2016fairness_qualified} brought the \\emph{contextual multi-armed bandit} problem to the fairness domain to ensure that any individual who has worse qualities than another individual will not be favored by the algorithm. According to~\\cite{galhotra2017causal_discr}, an algorithm is considered fair if it provides the same output for two individuals who have different values only in the sensitive attributes.\nIndividual fairness approaches show promising improvements for the domain of fairness. However, they have a fundamental limitation due to the assumption that the underlying distance metric for the given dataset is known. Furthermore, using a specific distance metric involve making assumptions regarding the relationship between the features and the labels in the dataset.\n\n% \\stitle{Sub-group Fairness Metrics}\n\nBoth statistical fairness metrics and individual fairness metrics have specific shortcomings that can be addressed by considering fairness metrics on the the sub-group level \\cite{mehrabi2019survey}.\nThe \\emph{metric multifairness} has been introduced in \\cite{kim2018fairness} to treat the individuals in a given sub-population similarly, which can be considered as combining the individual and group fairness notions. \nTo address the problem  when a classifier is fair on each group existing in a sensitive attribute but unfair for one or more subgroups in the dataset defined over multiple sensitive attributes, \\emph{fairness gerrymandering} was introduced in~\\cite{kearns2018preventing}. \nAlthough this approach is very promising since it does not need specific assumptions regarding the data just like the group-based or statistical metrics, one shortcoming of this approach is that it is not certain which function classes are feasible or reasonable to use for each dataset at hand, and there is no clear guidance about which attributes should be included as protected attributes to define the subgroups later \\cite{chouldechova2018frontiers}.\n\n\n% \\stitle{Causal reasoning metrics:} investigating the causal relationships between the attributes and the outcome labels leads to the introduction of causal reasoning metrics. These metrics requires additional understanding and knowledge of how the world is structured in the form of a causal model \\cite{loftus2018causal}. The required knowledge is substantial to understand how a change in an attribute can cause a change in the system. \n% \\citeauthor{kusner2017counterfactual} \\cite{kusner2017counterfactual} have proposed \\emph{counterfactual fairness}, which considers a dataset as counterfactually fair if a decision regarding an individual is identical in the actual world as well as a counterfactual world where that individual belongs to a different demographic sub-population. Another counterfactual fairness metric was introduced by \\citeauthor{kilbertus2017avoiding_discr} \\cite{kilbertus2017avoiding_discr} that highlights the importance to distinguish the sensitive attributes from their related proxy attributes so that the underlying effects of sensitive attributes on the decision attribute can be revealed.  Causal reasoning metrics assume that sensitive and proxy attributes can be identified and resolved correctly and the appropriate causal graph for a given dataset can be also constructed accurately. \n\n\\subsection{Mitigation Algorithms:}\nResearchers have been not only working on finding the best metric but also working on finding an appropriate technique to eliminate the discrimination identified in a dataset or a model. Thus, there are several proposed bias mitigation techniques to eliminate or mitigate unfairness considering the accuracy performance.\n\n\\stitle{Pre-processing algorithms:} the first category of bias mitigation algorithms is \\emph{pre-processing} algorithms, or techniques, where the dataset is altered before training a classifier in order to obtain a fair dataset as an input. \\emph{Fairness through unawareness} is an example of this category, which considers a predictor model fair if none of the protected attributes are used in the prediction process \\cite{gajane2017formalizing}. A more sophisticated approach to pre-process a dataset is re-sampling the data instances. In \\cite{kamiran2010preferential_samp},  the \"preferential sampling\" approach was proposed, where they sample the data objects with replacement in order to eliminate bias.  \nInterventional fairness was proposed in~\\cite{salimi2019capuchin}, where the training data is \"repaired\" by inserting or removing tuples to alter the probability distribution in the dataset. In this way, any causal relationship between sensitive attributes and the decision variable is removed. \n\\emph{Massaging} \\cite{kamiran2012data-preproc} changes the actual class labels of some of the instances in the training set to ensure fairness. A ranker algorithm is used to choose the appropriate instances to relabel.\nIn \\cite{feldman2015certifying} the massaging approach is used on attributes (variables) other than the sensitive attribute(s) of a dataset. \n\nAnother pre-processing technique uses \\emph{reweighing} \\cite{calders2009reweighing}, which assigns weights to each instance in the training set. Basically, this approach assigns higher weights to the instances from the unprivileged group with positive outcomes than the instances from the unprivileged group with negative outcome and vice versa. \n\nThe \\emph{learning fair representations} (LFR) \\cite{zemel2013fair_learning} is defined as an optimization problem to find the appropriate intermediate representation that encodes the data as accurate as possible. Information about the sensitive attributes of individuals is concealed. \nA similar study to LFR \\cite{zemel2013fair_learning} is conducted in \\cite{calmon2017optimized_pre}, which also considers unfairness as an optimization problem with a probabilistic framework. However, test data are also transformed probabilistically before they are given to a classifier model as well as the training data. \nA fair data oversampling technique called \\emph{fair class balancing} \\cite{yan2020fair-balance} was proposed to address the class imbalance problem in datasets. This approach does not use any information regarding the sensitive attributes.  \n\n\n\\stitle{In-Processing Algorithms:}\nthese algorithms tune or adjust the classification algorithm in order to make the model output fair. There are several classifiers that are altered for in-processing such as Support Vector Machines (SVM), logistic regression, and random forests. In processing algorithms are mostly limited to the chosen classifier. Kamiran et al.  in \\cite{kamiran2010decision-tree} uses decision trees as a classifier that is  adjusted, or \\emph{constrained}, to ensure fairness.\nZafar et al.~\\cite{zafar2017fairness-cons} implemented an in-processing algorithm based on constraining classifiers, which is formulated as a regularized optimization problem, using logistic regression and SVM algorithms. Kamishima et al.~\\cite{kamishima2011fairness} proposed regularized prejudice remover, which can be applied on any probabilistic classifier to mitigate bias. The proposed technique enforces classifiers to make the predictions independent from a sensitive attribute. \nAdversarial learning is used as an in-processing technique to ensure fairness. \nZhang et al. \\cite{zhang2018adversarial} have proposed a framework with adversarial debiasing to mitigate bias, which can be implemented with gradient-based models for both classification and regression tasks. \nRistanoski~\\cite{ristanoski2013discr-aware} proposed an empirical loss-based tuning on SVM, which also considers the imbalance in the number of samples with positive and negative class labels. \n\n\n\\stitle{Post-Processing Algorithms:}\npost-processing algorithms change the predicted outcomes of classifiers based on certain rules or constraints to ensure fairness. Thus, the goal is to eliminate the discrimination from the final predictions instead of the input dataset or within the models. Kamiran et al. \\cite{kamiran2012ROC} implemented \\emph{reject option classification} (ROC) to change the predicted class labels of the instances that are close to the decision boundary. \nThe ROC algorithm in \\cite{kamiran2012ROC} can be considered as a \\emph{thresholding} technique since it considers a certain threshold and a critical region to modify the predicted outcomes of classifiers.\nAnother approach based on thresholding is proposed in \\cite{hardt2016equal_odds_opport}, where the equalized odds (EO) is used as the core fairness metric. The predictions of a classifier obtained at the end of the training step are adjusted to ensure the EO fairness. \n\n\nFinally, Kilbertus et al. \\cite{kilbertus2017avoiding_discr} have proposed two post-processing algorithms, namely avoiding proxy discrimination and avoiding unresolved discrimination, to eliminate unfairness on the predictions of a classifier based on causal perspective and two causal definitions. \nUnfortunately, most of the post-processing algorithms have a common limitations in practice. For example, the post-processing algorithms which make corrections on the classifier predictions by randomizing them cannot be used in specific domains due to ethical reasons. Furthermore, post-processing algorithms might deliver sub-optimal performance in terms of accuracy compared to the other fairness techniques \\cite{woodworth2017post-learning}. \n\n% Thus, post-processing algorithms are not the best options for the practitioners who would like to achieve fairness while obtaining as high accuracy as possible.\n\n\n", "meta": {"hexsha": "fc0cb4d00b6350034e346cff2f4c04a7949c2713", "size": 18796, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "FairnessPaper/Sections/RelatedWork.tex", "max_stars_repo_name": "bendiste/Algorithmic-Fairness", "max_stars_repo_head_hexsha": "7e3b54e38eddb7572777be6f9772e3b2a8e398ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FairnessPaper/Sections/RelatedWork.tex", "max_issues_repo_name": "bendiste/Algorithmic-Fairness", "max_issues_repo_head_hexsha": "7e3b54e38eddb7572777be6f9772e3b2a8e398ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FairnessPaper/Sections/RelatedWork.tex", "max_forks_repo_name": "bendiste/Algorithmic-Fairness", "max_forks_repo_head_hexsha": "7e3b54e38eddb7572777be6f9772e3b2a8e398ec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 221.1294117647, "max_line_length": 1180, "alphanum_fraction": 0.8265056395, "num_tokens": 3812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.3125228910109688}}
{"text": "\\section{Experiments}\n\n% As with other methods, we observe that introducing a silhouette term into the network loss before the model's pose has been somewhat solved can result in unsatisfactory local minima. We overcome this by using a pre-training stage with the following loss terms:\n\n\nIn this section, the WLDO method is compared against competitive baselines. The protocol for evaluation is described first, followed by a quantitative and qualitative evaluation.\n\n\\subsection{Evaluation protocol}\n\nEvaluation is based on the StanfordExtra dataset introduced earlier in the chapter, which contains 8,476 images for 120 breeds. These images are divided per-breed into an 80\\%/20\\% train and test split.\n\nTwo primary evaluation metrics are considered. IoU is the intersection-over-union of the projected model silhouette compared to the ground truth annotation and indicates the quality of the reconstructed 3D shape. Percentage of Correct Keypoints (PCK) computes the percentage of joints which are within a normalized distance (based on square root of 2D silhouette area) to the ground truth locations, and evaluates the quality of reconstructed 3D pose. In addition, PCK results are produced for various joint groups (legs, tail, ears, face) in order to compare the reconstruction accuracy for different parts of the dog. Also used for evaluation is a new comparison metric \\emph{PCK-MAX}. This protocol is similar to the Percentage of Correct Keypoints (PCK) metric~\\cite{yang2013articulated} but incorporates the `invisible' ground-truth points. The standard PCK metric ignores these points, meaning even correct 3D reconstructions will receive no credit. PCK-MAX instead assumes reconstructed 3D points for missing ground-truth data are correct, providing an interesting upper bound.\n\n\\subsection{Training procedure}\n\nThe WLDO network is trained in two stages. The first omits the silhouette loss which tends to lead the network to unsatisfactory local minima if applied too early. With the silhouette loss turned off, it is satisfactory to use the simple unimodal prior (and without EM) for this preliminary stage since there is no loss to specifically encourage a strong shape alignment. After this, the silhouette loss and mixture prior with $M=10$ clusters are introduced, and expectation maximization updates are applied every 50 epochs. The first stage is trained for 250 epochs and the second stage for 150. The entire training procedure takes approximately 96 hours on a single P100 GPU.\n\nRecall that the training objective for our end-to-end system for predicting SMBLD parameters consistent with a monocular dog input image is given by:\n\n\\begin{equation}\n    \\L{opt}=\\L{joints}+\\L{sil}+\\L{pose}+\\L{shape}+\\L{mixture}\n\\end{equation}\n\nEach loss term is weighted with a scalar $\\W{}$. The following details the specific weights used for each training stage:\n\n\\ss{Stage 1.} $\\W{joints}=10.0,\\W{pose}=1.0,\\W{shape}=1.0,\\W{sil}=0.0,\\W{mixture}=0.0$. This stage is trained for 250 epochs using the Adam optimizer, with learning rate set to $10^{-4}$. \n\\ss{Stage 2.} $\\W{joints}=10.0,\\W{pose}=0.5,\\W{shape}=0.0,\\W{sil}=100.0,\\W{mixture}=0.1$. This stage is trained for 150 epochs and run the described EM update step every $K=50$ epochs. The number of clusters $M=10$ was selected based on a grid search over $M=1,5,10,25$ with IoU scores compared. The Adam optimizer is again applied with learning rate to $10^{-5}$.\n\nTo begin, WLDO is compared with various baseline methods. 3D Menagerie (3D-M)~\\cite{zuffi2017menagerie} is an approach which fits the 3D SMAL model using per-image energy minimization. Creatures Great and SMAL (CGAS)~\\cite{biggs2018creatures} is a three-stage method, which employs a joint predictor on silhouette renderings from synthetic 3D dogs, applies a genetic algorithm to clean predictions, and finally applies the SMAL optimizer to produce the 3D mesh.\n\nAt test-time both 3D-M and CGAS rely on manually-provided segementation masks, and 3D-M also relies on hand-clicked keypoints. In order to produce a fair comparison, we produce a set of \\emph{predicted} keypoints for StanfordExtra by training the Stacked Hourglass Network~\\cite{newell2016stacked} with 8 stacks and 1 block, and \\emph{predicted} segmentation masks using DeepLab v3+~\\cite{deeplabv3plus}. The Stacked Hourglass Network achieves 71.4\\% PCK score, DeepLab v3+ achieves 83.4\\% IoU score and the CGAS joint predictor achieves 41.8\\% PCK score. \n\n%All methods are trained from scratch and evaluated on our Stanford Dog validation set.\n\n% \\input{eccv2020kit/tab_othernetworks}\n% \\input{tab_othernetworks}\n\nTable~\\ref{tab:baselinesfix}, \\Cref{fig:comparison_1} and \\Cref{fig:comparison_2} show the comparison against competitive methods. For full examination, results for 3D-M and CGAS are additionally provided in the scenario that ground-truth keypoints and/or segmentations are available at test time. \n\nThe results show our end-to-end method outperforms the competitors when they are provided with predicted keypoints/segmentations (white rows). The WLDO method therefore achieves a new state-of-the-art on this 3D reconstruction task. In addition, the method is shown to achieve improved average IoU/PCK scores than competitive methods, even when competitors are provided ground truth annotations at test time (grey rows). Also demonstrated is the wider applicability of two contributions of this chapter (scale parameters and improved prior) in the improved performance of the 3D-M method when these are incorporated. Finally, WLDO's test-time speed is significantly faster than competitive methods as no subsequent energy minimization procedure is required. \n\n\\input{Chapter5/Tables/tab_baselines_pckfix.tex}\n\n\n\\input{Chapter5/FigTex/fig_comparison_1.tex}\n\\input{Chapter5/FigTex/fig_comparison_2.tex}\n\n%xxx: Note that CGAS does badly as it can't clean up using video\n\\subsection{Generalization to unseen dataset}\n\nTable~\\ref{tab:animalposefix} shows an experiment to compare how well our model generalizes to a new data domain. We test our model against the 3D-M~\\cite{zuffi2017menagerie} method (using predicted keypoints and segmentations as above for fairness) on the recent Animal Pose dataset~\\cite{animalpose}. The data preparation process is the same as for StanfordExtra and no fine-tuning was used for either method. Good results are achieved in this unseen domain and still improve over the 3D-M optimizer.\n\n\\input{Chapter5/Tables/tab_anipose_fix.tex}\n\\input{Chapter5/Tables/tab_anipose_abl_fix.tex}\n\n\\subsection{Ablation study}\n\nSecondly, an ablation of the individual components of the WLDO method is provided in order to examine the effect of each contribution on the PCK/IoU performance. Three variants are evaluated: (1) \\textbf{Ours w/o EM} that omits EM updates, (2) \\textbf{Ours w/o MoG} which replaces the mixture shape prior with a unimodal prior, (3)~\\textbf{Ours w/o Scale} which removes the scale parameters. \n\nThe results in Table~\\ref{tab:ablationfix} indicate that each individual component has a positive impact on the overall method performance. In particular, it can be seen that the inclusion of the EM and Mixture of Gaussians prior leads to an improvement in IoU, suggesting that the shape prior refinements steps help the model accurately fit the exact dog shape. Interestingly, adding the Mixture of Gaussians prior but omitting EM steps slightly hinders performance, most likely due to an sub-optimal initialization for the $M$ clusters. However, adding EM updates to the Mixture of Gaussian model improves all metrics except the ear keypoint accuracy. It is observed that the error here is caused by the shape prior learning slightly imprecise shapes for dogs with extremely ``floppy'' ears. Although there is good silhouette coverage for these regions, the fact the SMBLD model has only a single articulation point per ear causes a lack of flexibility that results in occasionally misplaced ear tips for these instances. This could be improved in future work by adding additional model joints to the ear. Finally, the increased model flexibility afforded by the SMBLD scale parameters is shown to improve the IoU/PCK scores. \n\n\\subsection{PCK-MAX results}\n\nThe final evaluation metric analyses PCK-MAX, a protocol which provides an upper bound on the PCK score by assuming invisible keypoints were successfully recovered.\n\n\\input{Chapter5/Tables/tab_baselines_pckmax.tex}\n\\input{Chapter5/Tables/tab_anipose_pckmax.tex}\n\\input{Chapter5/Tables/tab_anipose_abl_pckmax.tex}\n\n\n% \\input{eccv2020kit/tab_ablation}\n\n\n% We are able to use the dataset to examine which dog parts are the most challenging to position. \n% \\input{eccv2020kit/fig_jointspreads}\n% \\anote{TODO: PCK tables and errors visualized on 3D dog.}\n% \\paragraph{Analysis over breeds}\n% A significant benefit of our dog dataset is that the supplied breed labels allows for reconstruction performance to be evaluated over particular breeds. \\anote{Figure} ranks the breeds by error.\n% \\input{eccv2020kit/tab_breed}\n\n\\subsection{Qualitative evaluation}\n\nFigures \\ref{fig:qualresults_se_1}, \\ref{fig:qualresults_se_2} and \\ref{fig:qualresults_se_3} shows a range of example system outputs when tested on range of StanfordExtra dogs with varying pose and shape and in challenging conditions. Figure \\ref{fig:qualresults_ani} shows results on the Animal Pose dataset. Note that only StanfordExtra is used for training.\n\n\n% \\input{fig_comparison}\n\n% \\input{fig_qualresults}\n\n% \\input{fig_qual_results_animal_pose}\n% \\section{Failure Cases}\n\n% \\footnotetext[4]{PCK results in tables have been updated to match definitions of Yang and Ramanan~\\cite{yang2013articulated} normalized by 2D silhouette area. Please see original tables and further details in the appendix.}\n", "meta": {"hexsha": "982bffbef2a0755c1d02d5acdeedb40d9837ce0e", "size": 9762, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapter5/6_experiments.tex", "max_stars_repo_name": "benjiebob/phd-thesis-template", "max_stars_repo_head_hexsha": "2fd86bb807b830c06944d9c59962939d9a95ca7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter5/6_experiments.tex", "max_issues_repo_name": "benjiebob/phd-thesis-template", "max_issues_repo_head_hexsha": "2fd86bb807b830c06944d9c59962939d9a95ca7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter5/6_experiments.tex", "max_forks_repo_name": "benjiebob/phd-thesis-template", "max_forks_repo_head_hexsha": "2fd86bb807b830c06944d9c59962939d9a95ca7a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 103.8510638298, "max_line_length": 1228, "alphanum_fraction": 0.8026019258, "num_tokens": 2328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.629774621301746, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3124273035851813}}
{"text": "\\chapter{Relative Entropy Model Policy Search}\n\\label{chapter4}\n\\thispagestyle{empty}\n\n\\begin{quotation}\n{\\footnotesize\n\\noindent{\\emph{Our beliefs are based on our experience, which gives us a very incomplete picture of the world, and it's easy to jump to false conclusions.}}\n\\begin{flushright}\nPedro Domingos, The Master Algorithm\n\\end{flushright}\n}\n\\end{quotation}\n\\vspace{0.5cm}\n\nIn this chapter, we will present a novel \\textit{information theoretic} approach to solve CMDPs, namely \\textit{Relative Entropy Model Policy Search} (REMPS). REMPS is an extension of REPS (see \\cref{sec:reps}) for the case of model-policy learning, it is able to overcome local maxima/minima and provides an exact update step. REMPS formulates the learning problem as a constrained optimization problem for which we find the solution in closed form. \\newline\nIn \\cref{sec:remps} we formalize the optimization problem, we derive the solution and we propose several projection strategies able to work with continuous state and action spaces. In \\cref{sec:remps-theory} we propose a theoretical study of the REMPS property, providing a bound on the difference of performance between the ideal formulation of REMPS and the samples approximation formulation.\n\n\\section{Motivations}\nWhen an agent interacts with the environment there is a tight connection between the policy and the model configuration. In standard RL applications, where the environment is assumed to be fixed during the learning process, it is common to treat model configuration as instance of hyperparameters selection problem. In this case it is possible to use standard techniques like Bayesian Optimization. Using these techniques we are solving a slightly different problem with respect to the CMDP learning problem (\\cref{sec:cmdp}) that is defined as:\n$$\nP^*,\\pi^* \\in \\underset{P \\in \\mathcal{P}_{\\boldsymbol{\\omega}}, \\pi \\in \\Pi_{\\boldsymbol{\\theta}}}{\\arg \\max}J^{P,\\pi}.\n$$\nIf the model configuration is selected before the training phase we are actually searching for the best policy given a model. If the model configuration is selected after the training process we are searching for the best model for a given policy.\nIn general a model configuration induces an optimal policy and a policy induces an optimal configuration but the pairs model-policy found in these ways are, in general, different from the pair model-policy yielding the optimal performance. For this reasons treating model parameters as hyperparameters it is not the correct way to proceed. Furthermore the model-policy learning problem is a different problem with respect to the ones usually solved in the literature.\n\\newline\nIn principle we can act with gradient methods over the policy and the model (see \\cref{sec:policy-search} and \\cref{gradient_cmdp}) but we argue that this is not a smart way to tackle the CMDP probelm. Gradient methods tackle local optima in the return landscape by using policies with a huge number of parameters, multiple restarts and stochastic gradient ascent updates. However, these methods for avoiding local optima are not theoretically justified. Moreover, while a policy can have an arbitrarily large number of parameters, in the context of CMDP the model parameters are fixed given a problem and usually the cardinality of model parameters is much smaller with respect to the cardinality of policy parameters. Moreover multiple restarts using different values for the model parameters might cause dangerous behaviours. \\newline\nWe describe the rationale behind the choice of an information theoretic approach with an example.\nSuppose the agent found itself in the model $P_{\\bm{\\omega}_0}$ with the best policy $\\pi_{\\bm{\\theta}^*(\\bm{\\omega}_0)}$ for that model. A good choice for the update of the model is $P_{\\bm{\\omega}_1}$ such that the learning process starting from $\\pi_{\\bm{\\theta}^*(\\bm{\\omega}_0)}$ in $P_{\\bm{\\omega}_1}$ yields good results. In other words the update of a component (model) of a CMDP should take into account future updates of the other (policy). \nBy acting with gradient updates we do not obtain this behaviour: the gradient of the performance in $(P_{\\bm{\\omega}_0}, \\pi_{\\bm{\\theta}^*(\\bm{\\omega}_0)})$ with respect to the policy parameters yields zero value (since it is a local optima) and the gradient with respect to the model parameters points towards the direction where the performance of the \\textit{current} policy are improved. As said before, we do not want to consider the current policy in the model update, we should consider future policies. \\newline\nThe two issues of gradient methods explained above can be solved by information theoretic approaches. \nOur REMPS formulation, as we will see later, considers jointly the model and the policy yielding an exact model-policy update in the neighbourhood of the current model-policy pair.\nREMPS is based on two phases: \\textit{optimization} and \\textit{projection}. In the optimization phase we seek for the best stationary distribution $d$ (in the space of \\textit{all} possible distribution) that is not far from the current distribution more than $\\epsilon>0$ in terms of KL-divergence. The distribution $d$, might fall outside the space of representable stationary distributions given our model and policy spaces. Therefore, like in \\citep{danielhierarchicalnodate}, in the \\textit{projection} phase we perform a projection onto the representable space finding the actual distribution $\\widehat{d}$.\n\n\\section{Relative Entropy Model Policy Search}\\label{sec:remps}\nIn this section we present the optimization phase and the projection phase of REMPS.\nWe consider a CMDP with parametric model and policy spaces. Model parameters are denoted with $\\boldsymbol{\\omega}$ and policy parameters with $\\boldsymbol{\\theta}$. \nThe performance of a configuration-policy pair $(P,\\pi)$ is defined in terms of the long-term expected reward:\n$$\nJ^{P,\\pi} = \\underset{H \\rightarrow + \\infty}{\\lim \\inf} \\underset{\\begin{subarray}{c}\n\ta_t \\sim \\pi(\\cdot | s_t) \\\\\n\ts_{t+1} \\sim P(\\cdot | s_t, a_t)\n\\end{subarray}}{\\mathbb{E}} \\left[ \\frac{1}{H} \\sum_{t=0}^{H-1} R(s_t,a_t,s_{t+1}) \\right] .\n$$\nWe express the state-action-next-state stationary distribution as:\n$$\n d^{P,\\pi}(s,a,s') = d^{P,\\pi}(s)\\pi(a|s)P(s' | s, a) .\n$$\n\\subsection{Optimization}\n We define the following constrained optimization problem:\n\\begin{align}\n\t\\max_{d} & \\sas d(s,a,s')\tR(s,a,s') \\mathrm{d}s \\mathrm{d}a \\mathrm{d}s' \\\\\n\t\\text{subject to:} &\\\\\n\t& D_{KL}(d || d^{P,\\pi}) \n\t%=  \\sas d_{\\mu,\\gamma}^{P,\\pi}(s,a,s') \\log \\frac{d_{\\mu,\\gamma}^{P,\\pi}(s,a,s')}{\\widetilde{d}_{\\mu,\\gamma}^{P,\\pi}(s,a,s')} ds da ds'\n\t\\leq \\epsilon \\\\\n\t& \\sas d(s,a,s') \\mathrm{d}s \\mathrm{d}a \\mathrm{d}s' = 1 \\, ,\n\t\\label{eq:remps}\n\\end{align}\nwhere $d^{P,\\pi}(\\cdot, \\cdot, \\cdot)$ is the sampling distribution and $\\epsilon$ is a parameter controlling how large a model-policy update can be. \\newline\nThis formulation is derived from the REPS formulation but it takes into account also the model parameters by considering the joint distribution obtained by the model and the policy. The objective is the maximization of the average reward.\nThe KL--constraint prevents the optimized joint distribution from moving too far from the sampling distribution. The last constraint is only needed to ensure that the obtained distribution is well formed. It is worth noting that, differently from REPS, we do not impose a constraint on the validity of the stationary distribution with respect to to the transition model, as we have the possibility to change it, configuring the environment. \n\\paragraph{REMPS Dual}\nThe dual problem is given by:\n\\begin{align}\n\t\\min_{\\eta \\in [0,+\\infty)} g(\\eta) &= \\eta \\log \\left( \\sas d^{P,\\pi}(s,a,s') \\exp \\left(\\epsilon + \\frac{R(s,a,s')}{\\eta} \\right)\\mathrm{d}s \\mathrm{d}a \\mathrm{d}s' \\right) ,\t\n\t\\label{eq:remps-dual}\n\\end{align}\nwhich is convex in $\\eta^{-1}$.\n\nIn real cases we do not have access to the real sampling distribution $d^{P,\\pi}$, so we cannot compute the exact solution of the dual problem. Like in REPS, all components of REMPS can be estimated from samples. \nThe dual function can be rewritten as:\n\\begin{align}\n\tg(\\eta) &= \\eta \\log \\underset{(s,a,s') \\sim d^{P,\\pi}(\\cdot, \\cdot, \\cdot)}{\\mathbb{E}} \\left[\\exp \\left( \\epsilon + \\frac{R(s,a,s')}{\\eta} \\right) \\right] \\\\\n\t& \\approx \\eta \\log \\left[ \\frac{1}{N}\\sum_{(s,a,s') \\in D} \\exp \\left( \\epsilon + \\frac{R(s,a,s')}{\\eta} \\right) \\right] \\, ,\n\t\\label{eq:dual-sample}\n\\end{align} \nwhere $D$ is dataset of triples $(s,a,s')$ collected with the distribution $d^{P,\\pi}$.\nFrom this formulation it is easy to obtain a sample estimation of the dual since it is the empirical mean of the above exponential function with samples coming from the the current model $P$ and the current policy $\\pi$. We refer to the approximated dual function with $\\widetilde{g}$.\n\\newline\nThe following theorem derives the solution of the constrained optimization problem in terms of the sampling distribution $d^{P,\\pi}$, the reward associated to each sample $R(s,a,s')$, the Lagrange multiplier $\\eta$ and the $\\epsilon$ parameter.\n\\begin{theorem}[REMPS solution]\nThe solution of the REMPS problem is:\n\\begin{equation}\n\td(s,a,s') = \\frac{d^{P,\\pi}(s,a,s') \\exp \\left(\\frac{R(s,a,s')}{\\eta} \\right)}{\\sas d^{P,\\pi}(s,a,s') \\exp \\left( \\frac{R(s,a,s')}{\\eta} \\right) \\mathrm{d}s \\mathrm{d}a \\mathrm{d}s' } \\,\n\\end{equation}\nwhich is induced by the optimal model and policy:\n\\begin{align}\n\t\\pi'(a | s) &= \\frac{\\pi(a | s) \\int_\\mathcal{S} P(s' | s,a) \\exp \\left( \\epsilon + \\frac{R(s,a,s')}{\\eta} \\right) \\mathrm{d}s'}{\\int_\\mathcal{A} \\pi(a | s) \\int_\\mathcal{S} P(s' | s,a) \\exp \\left( \\epsilon + \\frac{R(s,a,s')}{\\eta} \\right) \\mathrm{d}s' \\mathrm{d}a} \\\\\n\tP'(s' | a, s) & = \\frac{P(s' | s,a) \\exp \\left( \\epsilon + \\frac{R(s,a,s')}{\\eta} \\right)}{\\int_\\mathcal{S} P(s' | s,a) \\exp \\left( \\epsilon + \\frac{R(s,a,s')}{\\eta} \\right) \\mathrm{d}s'}  \\, .\n\\end{align}\nwhere $\\eta$ is the minimizer of the dual problem \\ref{eq:remps-dual}.\n\\end{theorem}\nThe proof is given in \\cref{sec:remps_deriv}.\n\n\\subsection{Projection}\nThe REMPS problem is solved in closed form but the solution might lie outside the space of the feasible models and policies. Therefore there is the need to obtain a solution that can be represented. \\newline\nWe consider the case in which both the model and the policy are parametric: $\\mathcal{P}_{\\Omega} = \\{ P_{\\mathbr{\\omega}}: \\mathbr{\\omega} \\in \\Omega \\subseteq \\mathbb{R}^k \\}$ and $\\Pi_{\\Theta} = \\{ \\pi_{\\mathbr{\\theta}}: \\mathbr{\\theta} \\in \\Theta \\subseteq \\mathbb{R}^p \\}$, the space of joint distributions induced by $\\mathcal{P}_{\\Omega}$ and $\\Pi_{\\Theta}$ is $\\mathcal{D}_{\\Omega , \\Theta}=\\{d^{P,\\pi}: P \\in \\mathcal{P}_{\\Omega}, \\pi \\in  \\Pi_{\\Theta}\\}$. We denote with $d^{\\mathbr{\\omega}, \\mathbr{\\theta}}$ a distribution belonging to $\\mathcal{D}_{\\Omega , \\Theta}$ to highlight the dependence on the model and policy parameters. \\newline \nWe decide to perform a \\textit{moment projection} searching, inside the space $\\mathcal{D}_{\\Omega , \\Theta}$, for the solution that best represents $d$, the solution of the optimization problem. \\newline\nThis decision is based on the following bound, relating the performance gap of two distributions to the KL--divergence.\n\\begin{theorem}[Joint bound]\nLet us denote with $d^{P,\\pi}$ the stationary distribution induced by the model $P$ and policy $\\pi$ and $d^{P',\\pi'}$ the stationary distribution induced by the model $P'$ and policy $\\pi'$. Let us assume that the reward is uniformly bounded, that is for $s, s' \\in \\mathcal{S}$, $a \\in \\mathcal{A}$ it holds that $|R(s,a,s')| < R_{\\max}$. The norm of the difference of performance can be upper bounded as:\n\\begin{equation}\n\t|J^{P,\\pi} - J^{P',\\pi'}| \\leq R_{\\max} \\sqrt{2 D_{KL} (d^{P,\\pi} \\| d^{P',\\pi'})}.\n\\end{equation}\n\\end{theorem}\n\\begin{proof}\n\tStarting from the definition of the difference of the performance:\n\\begin{align}\n\t\t|J^{P,\\pi} - J^{P',\\pi'}| &  \\le  \\left| \\int_{\\mathcal{X}} d^{P,\\pi}(x) R(x) \\mathrm{d}x - \\int_{\\mathcal{X}} d^{P',\\pi'}(x) R(x) \\mathrm{d}x \\right| \\\\\n& \\le  R_{\\max} \\left| \\int_{\\mathcal{X}} d^{P,\\pi}(x) - d^{P', \\pi'}(x)\\mathrm{d}x \\right| \\\\\n& \\le R_{\\max} \\, TV(d^{P,\\pi}, d^{P', \\pi'}) \\label{eq:tv} \\\\\n& \\le R_{\\max} \\, \\sqrt{2D_{KL}(d^{P,\\pi} \\| d^{P', \\pi'})}, \\label{eq:pinsker}\n\t\\end{align}\nwhere we denote with $\\mathcal{X}$ the space $\\mathcal{S}\\times \\mathcal{A}\\times  \\mathcal{S}$, and with $x$ a tuple $(s,a,s')$ for ease of notation. \\cref{eq:tv} follows from the definition of Total Variation Distance and \\cref{eq:pinsker} follows from the Pinsker inequality.\n\\end{proof}\nThe previous bound relates the difference of performance between the stationary distributions to the KL--divergence between the two distributions, considering jointly the effect of the model and the policy. Now we derive a similar bound, that uses corollary 3.1 of \\citep{cmdp} and its extension to the case of undiscounted reward.\n\\begin{theorem}[Disjoint bound]\nLet us denote with $d^{P,\\pi}$ the stationary distribution induced by the model $P$ and policy $\\pi$, $d^{P',\\pi'}$ the stationary distribution induced by the model $P'$ and policy $\\pi'$. Let us assume that the reward is uniformly bounded, that is for $s, s' \\in \\mathcal{S}$, $a \\in \\mathcal{A}$ it holds that $|R(s,a,s')| < R_{\\max}$. If $(P',\\pi')$ admits group invertible state kernel $P'^{\\pi'}$ the norm of the difference of performance can be upper bounded as:\n\\begin{equation}\n\t|J^{P,\\pi} - J^{P',\\pi'}| \\le R_{\\max} \\, c_1 \\mathbb{E}_{s,a \\sim d^{P,\\pi}} \\left[ \\sqrt{2D_{KL}(\\pi'\\|\\pi)} + \\sqrt{2D_{KL}(P'\\|P)} \\right],\n\\end{equation}\nwhere $c_1 = 1 + ||A'^{\\#}||_{\\infty}$ and $A'^{\\#}$ is the group inverse of the state kernel $P'^{\\pi'}$.\n\\end{theorem}\n\\begin{proof}\n\tStarting from the definition of the difference of the performance:\n\\begin{align}\n|J^{P,\\pi} - J^{P',\\pi'}| &  \\le  \\left| \\int_{\\mathcal{X}} d^{P,\\pi}(x) R(x) \\mathrm{d}x - \\int_{\\mathcal{X}} d^{P',\\pi'}(x) R(x) \\mathrm{d}x \\right| \\\\\n& \\le  R_{\\max} \\left| \\int_{\\mathcal{X}} d^{P,\\pi}(x) - d^{P', \\pi'}(x)\\mathrm{d}x \\right| \\\\\n& \\le R_{\\max} \\, TV(d^{P,\\pi}, d^{P', \\pi'}) \\label{eq:dtv} \\\\\n& \\le R_{\\max} \\, c_1 \\mathbb{E}_{s,a \\sim d^{P,\\pi}} \\left[ \\sqrt{2D_{KL}(\\pi'\\|\\pi)} + \\sqrt{2D_{KL}(P'\\|P)} \\right] \\label{eq:dpinsker}\n\t\\end{align}\nwhere we denote with $\\mathcal{X}$ the space $\\mathcal{S}\\times \\mathcal{A}\\times  \\mathcal{S}$, and with $x$ a tuple $(s,a,s')$ for ease of notation. \\cref{eq:dtv} follows from the definition of Total Variation Distance and \\cref{eq:dpinsker} follows from the Pinsker inequality.\n\\end{proof}\nWe propose three techniques to project the REMPS solution over the space of the feasible distributions $\\mathcal{D}_{\\Omega , \\Theta}$.\n\n\n\\begin{figure}[tb!]\n\t\\includegraphics{pictures/Information_projection}\n\t\\caption{Illustration of REMPS and information projection. The ball centred in $d^{P,\\pi}$ with radius $\\epsilon$ represents the KL constraint over the space of distributions. The surface $\\mathcal{D}_{\\Omega , \\Theta}$ represents the space of available distributions. Distances are not euclidean since measured with the KL divergence.}\n\\end{figure}\n\n\\subsubsection{Projection of the stationary distribution}\nIn principle, as REMPS works on the stationary distribution, we should project it directly, \\ie finding the parameters that induce the most similar stationary distribution. The projection problem is:\n\\begin{align*}\n\t& \\widehat{\\mathbr{\\theta}}, \\widehat{\\mathbr{\\omega}} = \\argmin_{\\mathbr{\\theta} \\in \\Theta, \\mathbr{\\omega} \\in \\Omega} D_{KL} \\left(d(s,a,s') \\| d^{\\mathbr{\\omega}, \\mathbr{\\theta}}(s,a,s')\\right)  \\\\\n    & s.t. \\; d^{\\mathbr{\\omega}, \\mathbr{\\theta}}(s) =\\int_{\\mathcal{S}} \\int_{\\mathcal{A}}d^{\\mathbr{\\omega}, \\mathbr{\\theta}}(s') \\pi_{\\mathbr{\\theta}}(a|s') P_{\\mathbr{\\omega}}(s'|s,a) \\mathrm{d}a \\mathrm{d}s'.\n\\end{align*}\nHowever this problem is impractical as the constraint is difficult to enforce in continuous state-spaces even if replaced with the matching of the expectations of some features. Differently, in finite state-action spaces it is possible to enforce its sample based version by introducing a variable for each $d^{\\mathbr{\\omega}, \\mathbr{\\theta}}(s)$.\n\\subsubsection{Projection of the state kernel $P^{\\pi}$}\nThe projection of the state kernel $P^{\\pi}$ is a relaxed version with respect to the stationary distribution projection.\nWe minimize the expected KL--divergence between $P^{\\pi}$ of the distribution $d$ recovered by REMPS and $P_{\\mathbr{\\omega}}^{\\pi_{\\mathbr{\\theta}}}$, that is the state kernel distribution defined by our parametric space:\n\\begin{align*}\n\t\\widehat{\\mathbr{\\theta}}, \\widehat{\\mathbr{\\omega}} & = \\argmin_{\\mathbr{\\theta} \\in \\Theta, \\mathbr{\\omega} \\in \\Omega} \\int_{\\mathcal{S}} d(s) D_{KL} (P^{\\pi}(\\cdot|s) \\| P_{\\mathbr{\\omega}}^{\\pi_{\\mathbr{\\theta}}}(\\cdot|s)) \\mathrm{d}s \\\\\n    & = \\argmax_{\\mathbr{\\theta} \\in \\Theta, \\mathbr{\\omega} \\in \\Omega} \\int_{\\mathcal{S}} d(s) \\int_{\\mathcal{S}} P^{\\pi}(s'|s) \\log P_{\\mathbr{\\omega}}^{\\pi_{\\mathbr{\\theta}}}(s'|s) \\mathrm{d}s' \\mathrm{d}s \\\\\n    & = \\argmax_{\\mathbr{\\theta} \\in \\Theta, \\mathbr{\\omega} \\in \\Omega} \\int_{\\mathcal{S}} d(s) \\int_{\\mathcal{S}} \\int_{\\mathcal{A}} \\pi'(a|s)P'(s'|s, a) \\log P_{\\mathbr{\\omega}}^{\\pi_{\\mathbr{\\theta}}}(s'|s) \\mathrm{d}s' \\mathrm{d}s \\\\\n    & = \\argmax_{\\mathbr{\\theta} \\in \\Theta, \\mathbr{\\omega} \\in \\Omega} \\int_{\\mathcal{S}}\\int_{\\mathcal{A}}\\int_{\\mathcal{S}} d(s,a,s') \\log \\int_{\\mathcal{A}} P_{\\mathbr{\\omega}}(s'|s,a') \\pi_{\\mathbr{\\theta}}(a'|s) \\mathrm{d}a' \\mathrm{d}s \\mathrm{d}a \\mathrm{d}s'\n\\end{align*}\nThe sample-based version requires to compute the state kernel from samples, this can be done for the case of finite actions (and possibly continuous state-space):\n\\begin{align*}\n\t\\widehat{\\mathbr{\\theta}}, \\widehat{\\mathbr{\\omega}} & = \\argmax_{\\mathbr{\\theta} \\in \\Theta, \\mathbr{\\omega} \\in \\Omega} \\sum_{(s,a,s') \\in \\mathcal{D}} \\frac{d(s,a,s')}{d^{P,\\pi}(s,a,s')} \\log \\sum_{a' \\in \\mathcal{A}} P_{\\mathbr{\\omega}}(s'|s,a') \\pi_{\\mathbr{\\theta}}(a'|s) \\\\\n& = \\argmax_{\\mathbr{\\theta} \\in \\Theta, \\mathbr{\\omega} \\in \\Omega} \\sum_{(s,a,s') \\in \\mathcal{D}} \\exp\\left(\\frac{R\n(s,a,s')}{\\eta} \\right)  \\log \\sum_{a' \\in \\mathcal{A}} P_{\\mathbr{\\omega}}(s'|s,a') \\pi_{\\mathbr{\\theta}}(a'|s) ,\n\\end{align*}\nwhere $\\mathcal{D}$ is a dataset collected with the distribution $d^{P,\\pi}$ and we use importance sampling in order to recover the expected value under the distribution $d$ from samples coming from the sampling distribution $d^{P,\\pi}$ and we rewrite the ratio $d/d^{P,\\pi}$ as:\n$$\n \\frac{d(s,a,s')}{d^{P,\\pi}(s,a,s')} \\propto \\exp\\left(\\frac{R\n(s,a,s')}{\\eta}\\right) \\; ,\n$$\nneglecting a constant.\n\\subsubsection{Projection of policy and model independently}\n\\label{sec:disjproj}\nIn this simpler version of the projection problem we minimize the expected KL--divergence between the distributions $\\pi'$ and $P'$ and their corresponding parametric distributions $\\pi_{\\mathbr{\\theta}}$ and $P_{\\mathbr{\\omega}}$.\n\\begin{align}\n\t\\widehat{\\mathbr{\\theta}} & = \\argmin_{\\mathbr{\\theta} \\in \\Theta} \\int_{\\mathcal{S}} d(s) D_{KL} (\\pi'(\\cdot|s) \\| \\pi_{\\mathbr{\\theta}} (\\cdot|s)) \\mathrm{d}s = \\\\\n    & = \\argmin_{\\mathbr{\\theta} \\in \\Theta} \\int_{\\mathcal{S}} d(s) \\int_{\\mathcal{A}} \\pi'(a|s) \\log \\frac{\\pi(a|s)}{\\pi_{\\mathbr{\\theta}} (a|s)} \\mathrm{d}a \\mathrm{d}s = \\\\\n    & = \\argmin_{\\mathbr{\\theta} \\in \\Theta} \\int_{\\mathcal{S}} \\int_{\\mathcal{A}}  \\int_{\\mathcal{S}}  d(s,a,s') \\log \\frac{\\pi'(a|s)}{\\pi_{\\mathbr{\\theta}} (a|s)} \\mathrm{d}s \\mathrm{d}a \\mathrm{d}s' = \\\\\n    & = \\argmax_{\\mathbr{\\theta} \\in \\Theta} \\int_{\\mathcal{S}} \\int_{\\mathcal{A}}  \\int_{\\mathcal{S}} d(s,a,s') \\log \\pi_{\\mathbr{\\theta}} (a|s) \\mathrm{d}s \\mathrm{d}a \\mathrm{d}s',\n\\end{align}\nthat can be estimated from samples:\n\\begin{align}\n\t\\widehat{\\mathbr{\\theta}} & = \\argmin_{\\mathbr{\\theta} \\in \\Theta} \\sum_{(s,a,s') \\in \\mathcal{D}} \\exp\\left(\\frac{R(s,a,s')}{\\eta} \\right) \\log \\pi_{\\mathbr{\\theta}} (a|s),\n\\end{align}\nwhere $\\mathcal{D}$ is a dataset collected with $d^{P,\\pi}$.\nSymmetrically, for the transition model:\n\\begin{align*}\n\t\\widehat{\\mathbr{\\omega}} & = \\argmin_{\\mathbr{\\omega} \\in \\Omega} \\int_{\\mathcal{S}} \\int_{\\mathcal{A}} d(s,a) D_{KL} (P'(\\cdot|s,a), P_{\\mathbr{\\omega}} (\\cdot|s,a)) \\mathrm{d}s \\mathrm{d}a= \\\\\n    & = \\argmax_{\\mathbr{\\omega} \\in \\Omega} \\int_{\\mathcal{S}} \\int_{\\mathcal{A}}  \\int_{\\mathcal{S}} d(s,a,s') \\log P_{\\mathbr{\\omega}} (s'|s,a) \\mathrm{d}s \\mathrm{d}a \\mathrm{d}s',\n\\end{align*}\nand the sample based optimization works as for the policy. This optimization problem can be easily solved in a sample-based form for both finite and continuous state and action spaces.\n\n%\\begin{algorithm}[tb]\n%  \\caption{Relative Entropy Model Policy Search\n%    \\label{alg:remps}}\n%  \\begin{algorithmic}[1]\n%  \\Require{$\\epsilon$: KL constraint, $\\tilde{P}$: model approximation.}\n%  \\State Initialize $\\pi^{(0)}, P^{(0)}$ randomly\n%  \\For{t = 0,1,... until convergence}\n%  \\State Collect samples from $\\pi^{(t)}, P^{(t)}$\n%  \\State Obtain $\\eta^*$, the minimizer of the estimated dual problem: \n%  \\begin{align*} \n%  \\eta^* &= \\min_{\\eta \\geq 0} \\widetilde{g}(\\epsilon, \\eta) \\\\\n%  & = \\min_{\\eta \\geq 0} \\eta \\log \\left[ \\frac{1}{N}\\sum_{(s,a,s') \\sim d^{P,\\pi}} \\exp \\left( \\epsilon + \\frac{R(s,a,s')}{\\eta} \\right) \\right].\t\n% \\end{align*}\n%%  \\State Calculate the optimal distribution $d'$:\n%%  $$\n%%  d'(s,a,s') = \\frac{d^{P,\\pi}(s,a,s') \\exp \\left(\\frac{R(s,a,s')}{\\eta^*} \\right)}{\\sas d^{P,\\pi}(s,a,s') \\exp \\left( \\frac{R(s,a,s')}{\\eta^*} \\right) \\mathrm{d}s \\mathrm{d}a \\mathrm{d}s'}\n%%  $$\n%  \\State Project the optimal distribution $d'$ onto $\\mathcal{D}_{\\Omega, \\Theta}$ according to the projection strategy. %\\newline \\hspace*{1.25em} \n%\\begin{description}\n%  \t\\item[a.]   Projection of the stationary distribution: \\begin{align*}\n%\t& \\widehat{\\mathbr{\\theta}}, \\widehat{\\mathbr{\\omega}} = \\argmin_{\\mathbr{\\theta} \\in \\Theta, \\mathbr{\\omega} \\in \\Omega} D_{KL} (d(s,a,s') \\| d^{\\mathbr{\\omega}, \\mathbr{\\theta}}(s,a,s'))  \\\\\n%    & s.t. \\; d^{\\mathbr{\\omega}, \\mathbr{\\theta}}(s) =\\int_{\\mathcal{S}} \\int_{\\mathcal{A}}d^{\\mathbr{\\omega}, \\mathbr{\\theta}}(s') \\pi_{\\mathbr{\\theta}}(a|s') \\widetilde{P}_{\\mathbr{\\omega}}(s'|s,a) \\mathrm{d}s' \\mathrm{d}a.\n%\\end{align*}\n%  \t\\item[b.]  Projection of the state kernel: $$\n%  \\widehat{\\mathbr{\\theta}}, \\widehat{\\mathbr{\\omega}} = \\argmax_{\\mathbr{\\theta} \\in \\Theta, \\mathbr{\\omega} \\in \\Omega} \\sum_{(s,a,s') \\sim d^{P,\\pi}} \\exp\\left(\\frac{R(s,a,s')}{\\eta^*} \\right) \\log \\sum_{a' \\in \\mathcal{A}} \\widetilde{P}_{\\mathbr{\\omega}}(s'|s,a') \\pi_{\\mathbr{\\theta}}(a'|s) .\n%  $$\n%  \\item[c.] Projection of policy and model indendently \n%\\begin{align}\n%\t\\widehat{\\mathbr{\\theta}} & = \\argmin_{\\mathbr{\\theta} \\in \\Theta} \\sum_{(s,a,s') \\sim d^{P,\\pi}} \\exp\\left(\\frac{R(s,a,s')}{\\eta} \\right) \\log \\pi_{\\mathbr{\\theta}} (a|s), \\\\\n%\t\\widehat{\\mathbr{\\omega}} & = \\argmin_{\\mathbr{\\omega} \\in \\Omega} \\sum_{(s,a,s') \\sim d^{P,\\pi}} \\exp\\left(\\frac{R(s,a,s')}{\\eta} \\right) \\log \\widetilde{P}_{\\mathbr{\\omega}} (s' \\mid s, a) .\n%\\end{align} \n%\\end{description}\n%  \\State Update policy: $\\mathbr{\\theta}^{(t+1)} \\leftarrow \\widehat{\\mathbr{\\theta}}$ \n%  \\State Update model: $\\mathbr{\\omega}^{(t+1)} \\leftarrow \\widehat{\\mathbr{\\omega}}$\n%  \\EndFor \\\\\n%  \\Return{Policy-Model Pair ($P^{(t)},\\pi^{(t)}$)\n%  } \t\n%  \\end{algorithmic}\n%\\end{algorithm}\n\n\n\\begin{algorithm}[tb]\n  \\caption{Relative Entropy Model Policy Search\n    \\label{alg:remps}}\n  \\begin{algorithmic}[1]\n  \\Require{$\\epsilon$: KL constraint, $P$: model.}\n  \\State Initialize $\\pi_{\\bm{\\theta}_0}, P_{\\bm{\\omega}_0}$ randomly\n  \\For{t = 0,1,... until convergence}\n  \\State Collect samples from $\\pi_{\\bm{\\theta}_t}, P_{\\bm{\\omega}_t}$\n  \\State Obtain $\\eta^*$, the minimizer of the dual problem: \n \\begin{align}\n\t\\eta^* = &\\min_{\\eta \\in [0,+\\infty)} g(\\eta) \\\\\n\t&= \\min_{\\eta \\in [0,+\\infty)} \\eta \\log \\left( \\sas d^{P,\\pi}(s,a,s') \\exp \\left(\\epsilon + \\frac{R(s,a,s')}{\\eta} \\right)\\mathrm{d}s \\mathrm{d}a \\mathrm{d}s' \\right).\n\\end{align}\n%  \\State Calculate the optimal distribution $d'$:\n%  $$\n%  d'(s,a,s') = \\frac{d^{P,\\pi}(s,a,s') \\exp \\left(\\frac{R(s,a,s')}{\\eta^*} \\right)}{\\sas d^{P,\\pi}(s,a,s') \\exp \\left( \\frac{R(s,a,s')}{\\eta^*} \\right) \\mathrm{d}s \\mathrm{d}a \\mathrm{d}s'}\n%  $$\n  \\State Project the optimal distribution $d$ onto $\\mathcal{D}_{\\Omega, \\Theta}$ according to the projection strategy. %\\newline \\hspace*{1.25em} \n\\begin{description}\n  \t\\item[a.]   Projection of the stationary distribution: \\begin{align*}\n\t& \\widehat{\\mathbr{\\theta}}, \\widehat{\\mathbr{\\omega}} = \\argmin_{\\mathbr{\\theta} \\in \\Theta, \\mathbr{\\omega} \\in \\Omega} D_{KL} (d(s,a,s') \\| d^{\\mathbr{\\omega}, \\mathbr{\\theta}}(s,a,s'))  \\\\\n    & s.t. \\; d^{\\mathbr{\\omega}, \\mathbr{\\theta}}(s) =\\int_{\\mathcal{S}} \\int_{\\mathcal{A}}d^{\\mathbr{\\omega}, \\mathbr{\\theta}}(s') \\pi_{\\mathbr{\\theta}}(a|s') P_{\\mathbr{\\omega}}(s'|s,a) \\mathrm{d}s' \\mathrm{d}a.\n\\end{align*}\n  \t\\item[b.]  Projection of the state kernel: $$\n  \\widehat{\\mathbr{\\theta}}, \\widehat{\\mathbr{\\omega}} = \\argmax_{\\mathbr{\\theta} \\in \\Theta, \\mathbr{\\omega} \\in \\Omega} \\int_{\\mathcal{S}}\\int_{\\mathcal{A}}\\int_{\\mathcal{S}} d(s,a,s') \\log \\int_{\\mathcal{A}} P_{\\mathbr{\\omega}}(s'|s,a') \\pi_{\\mathbr{\\theta}}(a'|s) \\mathrm{d}a' \\mathrm{d}s \\mathrm{d}a \\mathrm{d}s' .\n  $$\n  \\item[c.] Projection of policy and model independently: \n\\begin{align}\n\t\\widehat{\\mathbr{\\theta}} & = \\argmax_{\\mathbr{\\theta} \\in \\Theta} \\int_{\\mathcal{S}} \\int_{\\mathcal{A}}  \\int_{\\mathcal{S}} d(s,a,s') \\log \\pi_{\\mathbr{\\theta}} (a|s) \\mathrm{d}s \\mathrm{d}a \\mathrm{d}s' \\\\\n\t\\widehat{\\mathbr{\\omega}} & = \\argmax_{\\mathbr{\\omega} \\in \\Omega} \\int_{\\mathcal{S}} \\int_{\\mathcal{A}}  \\int_{\\mathcal{S}} d(s,a,s') \\log P_{\\mathbr{\\omega}} (s'|s,a) \\mathrm{d}s \\mathrm{d}a \\mathrm{d}s'.\n\\end{align} \n\\end{description}\n  \\State Update policy: $\\mathbr{\\theta}_{t+1} \\leftarrow \\widehat{\\mathbr{\\theta}}$ \n  \\State Update model: $\\mathbr{\\omega}_{t+1} \\leftarrow \\widehat{\\mathbr{\\omega}}$\n  \\EndFor \\\\\n  \\Return{Policy-Model Pair $\\left( \\pi_{\\bm{\\theta}_t}, P_{\\bm{\\omega}_t} \\right)$\n  } \t\n  \\end{algorithmic}\n\\end{algorithm}\n\n\n\\subsection{Model Approximation}\nIn the previous sections we presented REMPS in the case of known environment. However, the perfect knowledge of the environment is difficult, or even impossible, in practice. Even in cases where an environment model is available it might be too approximate or hardy usable being very complex and computationally expansive. \\newline In REMPS it is possible to use any model approximation method, the only requirement is that it must be possible to learn the mapping $(s, a , \\boldsymbol{\\omega}) \\rightarrow s'$, from state, action and environment configuration to a distribution over the next states. Notice that in REMPS the environment model is used only the projection phase, while the optimization phase is model-free. \\newline\nIn order to learn an environment approximation we use a maximum likelihood (ML) approach. We collect a dataset composed by tuples $(s, a,\\boldsymbol{\\omega}, s')$ and given a parametric model defining a distribution over the state space we find the parameters by maximizing the log-likelihood of the seen transitions. The parametric model can be a Gaussian Process, a Neural Network or some other function approximator model. We denote the model approximation with $\\widetilde{P}$. \\newline\n\\subsection{Discussion}\nIn this section we discuss the main benefits and limitations of REMPS.\nBeing an information theoretic approach, REMPS, has the main goal of maximizing the performance while staying close to the observed data. This translates into the KL constraint between the sampling distribution $d^{P,\\pi}$ and the optimized distribution $d$. REMPS considers jointly the effect of the two CMDP components and finds a distribution, in the space of all possible distributions, maximizing the average reward while satisfying the KL constraint using a primal-dual formulation. However, due to a possible limitation in the representation power of the model and the policy this distribution might be unfeasible. Notice that a lack in representation power of the policy can be easily addressed (e.g. using more parameters), while a limited representation power in the model has to be expected since the number of parameters and their influence is fixed given a task. REMPS solves this problem by performing a KL--projection, that is finding the model-policy pair minimizing the KL distance between their joint distribution $\\hat{d}$ and $d$. \\newline\nHaving access to infinite samples we are sure that $d$ is close the sampling distribution, that is $D_{KL}(d \\| d^{P,\\pi}) \\le \\epsilon$. This constraint might be, in practice, not satisfied due to wrong estimations. \nWe also highlight the fact that performing the Moment Projection we can actually find a suboptimal distribution. By a simple inspection we can easily prove that $D_{KL}(d \\| \\widehat{d}) \\le \\epsilon$. However, being the KL--divergence not symmetric, we have no insight on $D_{KL}(\\widehat{d} \\| d^{P,\\pi})$ that is a more relevant quantity. \\newline\nIn practice we can add a regularization in the projection phase penalizing some type of distance between the new model-policy parameters and the sampling parameters, even if this is not theoretically justified. \\newline\nThe REMPS pseudocode is reported in \\cref{alg:remps}.\n\n\\clearpage\n%%%%%%%%%%%%%%%%%%%% THEORY %%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\\section{Theoretical Analysis}\\label{sec:remps-theory}\n%In this section we derive some theoretical guarantees for REMPS when it is executed starting from a finite number of samples $N$. In the following table are compared the exact and approximate version of REMPS. We denote as $\\mathcal{X}=\\mathcal{S} \\times \\mathcal{A} \\times \\mathcal{S}$ the state-action-next-state space, with $x=(s,a,s') \\in \\mathcal{X}$. For ease of notation we use $w(x)=\\widetilde{p}(x)/q(x)$.\n%This analysis is based on \\citep{cortes2010}.\n%\n%\\begin{small}\n%\\begin{tabular}{|m{5.3cm}|m{5.3cm}|}\n%\\hline\n%  \t\\begin{center}\t\\remps\t\\end{center}\n%    {\\begin{align*}\n%\t& \\max_p J_p = \\int_\\mathcal{X} p(x)R(x) dx \\\\\n%\ts.t. \\quad & D_{KL}(p||q) = \\int_\\mathcal{X} p(x) \\log \\frac{p(x)}{q(x)} dx \\leq \\epsilon \\\\\n%\t& \\int_\\mathcal{X} p(x) dx = 1\n%\t\\end{align*}} & \n%\t\\begin{center}\t\\rempstilde\t\\end{center}\n%\t{\\begin{align*}\n%\t\t& \\max_{\\widetilde{p}} J_{\\widetilde{p}/q}^N = \\frac{1}{N} \\sum_i w(x_i)R(x_i) dx \\\\\n%\t\ts.t. \\quad &  \\widetilde{D}_{KL, \\widetilde{p}/q}(\\widetilde{p}||q) = \\sum_i w(x_i) \\log w(x_i) dx \\leq \\epsilon \\\\\n%\t\t& \\frac{1}{N} \\sum_i w(x_i) = 1\n%\t\\end{align*}} \\\\\n%\t\\hline\n%\t\\begin{center} $\\mathrm{DUAL}$ \\end{center}\n%\t{\\begin{equation*}\n%\t\t\\min_{\\eta \\geq 0} \\frac{1}{\\eta} \\log \\int_\\mathcal{X} q(x) \\exp(\\eta R(x) + \\epsilon) dx\n%\t\\end{equation*}}\n%\t&\n%\t\\begin{center} $\\mathrm{\\widetilde{DUAL}}$ \\end{center}\n%\t{\\begin{equation*}\n%\t\t\\min_{\\widetilde{\\eta} \\geq 0} \\frac{1}{\\widetilde{\\eta}} \\log \\frac{1}{N}\\sum_i \\exp (\\widetilde{\\eta} R(x) + \\epsilon)\n%\t\\end{equation*}\n%\t} \\\\\n%\t\\hline\n%\t\\begin{center} $\\mathrm{PROJ}$ \\end{center}\n%\t{\\begin{equation*}\n%\t\t\\min_{p' \\in \\mathcal{P}} D_{KL}(p || p') = \\int_\\mathcal{X} p(x) \\log \\frac{p(x)}{p'(x)} dx\n%\t\\end{equation*}}\n%\t& \\begin{center} $\\mathrm{\\widetilde{PROJ}}$ \\end{center}\n%\t{\n%\t\\begin{equation*}\n%\t\t\\min_{\\widetilde{p}' \\in \\mathcal{P}} D_{KL, \\widetilde{p}/q}^N(\\widetilde{p} || \\widetilde{p}') = \\frac{1}{N} \\sum_i w(x_i) \\log \\frac{\\widetilde{p}(x_i)}{\\widetilde{p}'(x_i)}\n%\t\\end{equation*}} \\\\\n%\t\\hline\n%\\end{tabular}\n%\\end{small}\n%Thus we have defined an exact version and an approximate version of the REMPS problem. We have that the approximated version approaches to the exact one when an infinite number of samples is available. In this section we want to formalize this idea.\n%The approximated version deals with an off-policy estimation of the relevant quantities, performed by means of an importance weighting like technique.\n%The solution of the exact version of REMPS and the approximated version are:\n%\\begin{align*}\n%\t& p(x)=\\frac{q(x)\\exp(\\eta R(X))}{\\int_\\mathcal{X}q(x)\\exp(\\eta R(x)dx}\n%\t& \\widetilde{p}(x)=\\frac{q(x)\\exp(\\widetilde{\\eta} R(x)}{\\frac{1}{N}\\sum_i \\exp(\\widetilde{\\eta} R(x))}  \\; .\n%\\end{align*} \n%We denote with $\\hat{w}(x)$ the ratio importance weight, and with $\\widetilde{w}(x)$ the self normalized importance weight:\n%\\begin{align*}\n%\t& \\hat{w}(x)=\\frac{\\exp(\\eta R(X))}{\\int_\\mathcal{X}q(x)\\exp(\\eta R(x))dx}\n%\t& \\widetilde{w}(x) = \\frac{\\exp(\\widetilde{\\eta} R(x))}{\\sum_i \\exp(\\widetilde{\\eta} R(x))} = \\frac{w(x)}{N}  \\; .\n%\\end{align*} \n%We can notice that the quantity being maximized in $\\mathrm{\\widetilde{REMPS}}$ it is actually a self-normalized importance weighting estimate, opposed to the ratio importance weighting estimate $\\hat{J}$ not appearing in the optimization problems:\n%\\begin{align*}\n%\t& \\hat{J} = \\frac{1}{N}\\sum_i \\hat{w}(x_i)R(x_i)\n%\t& \\widetilde{J} = \\sum_i \\widetilde{w}(x_i) R(x_i) \\; .\n%\\end{align*}\n%The ratio estimate is unbiased while the self-normalized estimate is biased but consistent.\n%\n%\\subsection{Preliminaries}\n%In this section, we provide some results that will be used in the following sections.\n%\\paragraph{Preliminary results} Our analysis use the notion of Rényi divergence, an information theoretical measure of the difference between two distributions. It is very important in the study of importance weighting. We denote the Rényi divergence with $D_\\alpha (p || q)$:\n%\\begin{equation}\t\n%D_\\alpha (p || q) = \\frac{1}{\\alpha - 1}log_2 \\sum_x p(x) \\left( \\frac{p(x)}{q(x)} \\right)^{\\alpha -1} \\, ,\n%\\end{equation} \n%for $\\alpha \\geq 0$.\n%The Rènyi divergence is a non negative quantity for any $\\alpha>0$ and it coincides with the Relative entropy with $\\alpha=1$. It is important also the exponential base 2 of the Rènyi, denoted as $d_\\alpha (p || q)$:\n%\\begin{equation}\n%\td_\\alpha (p || q)= \\left[ \\sum_x p(x) \\frac{p(x)}{q(x)}^{\\alpha-1} \\right]^{\\frac{1}{\\alpha - 1}}\n%\\end{equation}\n%The exponentiated 2-Rényi divergence has the following form:\n%\\begin{equation}\n%\td_2 (p || q)= \\left[ \\sum_x p(x) \\frac{p(x)}{q(x)} \\right]\n%\\end{equation}\n%The following identities are standard results from the analysis of importance weights:\n%\\begin{align}\n%\t&\\mathbb{E} \\hat{w}=1 \\\\ &\\mathbb{E}\\left[ \\hat{w}^2 \\right]=d_2(p || q) \\\\  &\\sigma^2( \\hat{w}) = d_2 (p || q) - 1\n%\\end{align}\n%Let us demonstrate the second identity:\n%\\begin{align}\n%\t\\mathbb{E} \\left[ \\hat{w}^2 \\right] &= \\sum \\hat{w}(x)^2 q(x) \\\\\n%\t\t\t\t\t\t\t\t\t\t&= \\sum \\left( \\frac{p(x)}{q(x)} \\right)^2 q(x) \\\\\n%\t\t\t\t\t\t\t\t\t\t&= \\sum \\frac{p(x)^2}{q(x)}\n%\\end{align}\n%\n%\\paragraph{Learning bound for self-normalized importance weighting} We start observing that in our peculiar case the choice of $p$ in the hypothesis space $\\mathcal{P}$ has an effect on the weights $p(x)$ rather than on the loss function of a single sample, which is fixed being the reward function $R(x)$.\n%We consider the more general case in which both the loss function and the weights can vary. We denote as $d_{\\mathcal{P}, \\mathcal{F}}=Pdim(\\{\\widetilde{w}(x)f(x) : \\widetilde{w}(x) = p(x)/q(x), p \\in \\mathcal{P}, f \\in \\mathcal{F}\\})$,  $d_{\\mathcal{P}}=Pdim(\\{\\widetilde{w}(x) : \\widetilde{w}(x) = p(x)/q(x), p \\in \\mathcal{P}\\})$ the pseudo dimension of the class of weights, $d = \\max\\{d_{\\mathcal{P}, \\mathcal{F}},d_{\\mathcal{P}}\\}$. We assume that $d < \\infty$.\n%We derive the following bounds for self-normalized importance weights, which combines Theorem3 of [cortes2010] and the result of the relationship between ratio importance weights and self normalized importance weights:\n%\n%\\begin{theorem}\n%\tLet $d$ as defined before, $d_2(p || q)$ the exponentiated Rényi 2 divergence and $\\hat{d}_2(p || q) = \\frac{1}{N} \\sum_i \\hat{w}(x_i)$ its estimate. Define $M=\\sup_{p \\in \\mathcal{P}}\\max\\{\\sqrt{d_2(p||q)},\\sqrt{\\hat{d}_2(p||q)}$, the suprema over the distribution family of the maximum between the true $d_2$ and its estimated version. Assume that $d_2(p||q) < \\infty$, and for all $f \\in \\mathcal{F}$, we have that $||f||_\\infty < \\infty$. Then for any $\\delta$ with probability at least $1-\\delta$, the following bound holds:\n%\t\\begin{equation}\n%\t\t\\left| \\underset{x \\sim p}{\\mathbb{E}} \\left[ f(x) \\right] - \\sum_i \\widetilde{w}(x_i)f(x_i) \\right| \\leq 2 ||f||_\\infty \\min \\left\\{ 1, \\frac{M}{8} \\left( \\frac{d\\log \\frac{2eN}{d} + \\log \\frac{16}{\\delta}}{N} \\right)^{3/8} \\right\\}\n%\t\\end{equation}\n%\t\\label{thr:learning-theory}\n%\\end{theorem}\n%\n%This bound relates the difference between the expected value of a quantity and its empirical expectation using a self-normalized importance weighting technique.\n%\n%\\begin{proof}\n%\tBeing $|f(x)| \\leq ||f||_\\infty$ the bound cannot be larger than $2||f||_\\infty$. The idea of the proof is to use the ratio estimator and bound in probability its difference with the self-normalized estimator and its variance.\n%\t\\begin{equation}\n%\t\t\\left| \\underset{x \\sim p}{\\mathbb{E}} \\left[ f(x) \\right] - \\sum_i \\widetilde{w}(x_i)f(x_i) \\right| \\leq  \\left| \\underset{x \\sim p}{\\mathbb{E}} \\left[ f(x) \\right] - \\frac{1}{N}\\sum_i \\hat{w}(x_i)f(x_i) \\right| + \\left| \\frac{1}{N}\\sum_i \\hat{w}(x_i)f(x_i) -  \\sum_i \\widetilde{w}(x_i)f(x_i) \\right| \\, .\n%\t\\end{equation}\n%\tThe first term is the difference between the expected value of a function and its empirical expectation using the ratio importance weighting. This can be bounded using theorem 3 of cortes:\n%\t\\begin{equation}\n%\t\t\\left| \\underset{x \\sim p}{\\mathbb{E}} \\left[ f(x) \\right] - \\frac{1}{N}\\sum_i \\hat{w}(x_i)f(x_i) \\right| \\leq 2^{5/4} ||f||_\\infty M \\left( \\frac{d_{\\mathcal{P},\\mathcal{F}} \\log \\frac{2eN}{d_{\\mathcal{P},\\mathcal{F}}} + \\log \\frac{8}{\\delta}}{N} \\right)^{3/8} \\, .\n%\t\\end{equation}\n%\tConsider now the second term, we can use the following inequality and apply again the same theorem as before:\n%\t\\begin{align}\n%\t\t\\left| \\frac{1}{N}\\sum_i \\hat{w}(x_i)f(x_i) -  \\sum_i \\widetilde{w}(x_i)f(x_i) \\right| &= \\left| \\sum_i\\widetilde{w}(x_i)f(x_i) \\left( 1 - \\frac{\\sum_i \\hat{w}(x_i)}{N} \\right) \\right| \\\\\n%\t\t& \\leq ||f||_\\infty \\left| 1 - \\frac{\\sum_i \\hat{w}(x_i)}{N} \\right| \\\n%\t\\end{align}\n%\tWe have that, as demonstrated before, $1$ is the mean of the ratio estimator. So this is the discrepancy between the average weight and its mean. We can apply theorem 3 both sides, and w.p. at least $1-\\delta$:\n%\t\\begin{equation}\n%\t\t\\left| \\frac{1}{N}\\sum_i \\hat{w}(x_i)f(x_i) -  \\sum_i \\widetilde{w}(x_i)f(x_i) \\right| \\leq 2^{5/4} ||f||_\\infty M \\left( \\frac{d_{\\mathcal{P}} \\log \\frac{2eN}{d_{\\mathcal{P}}} + \\log \\frac{8}{\\delta}}{N} \\right)^{3/8}\n%\t\\end{equation}\n%\tWe can now use a union bound obtaining, w.p. $1-2\\delta$:\n%\t\\begin{equation}\n%\t\t\\left| \\underset{x \\sim p}{\\mathbb{E}} \\left[ f(x) \\right] - \\sum_i \\widetilde{w}(x_i)f(x_i) \\right| \\leq 2 ||f||_\\infty \\min \\left\\{ 1, \\frac{M}{8} \\left( \\frac{d\\log \\frac{2eN}{d} + \\log \\frac{8}{\\delta}}{N} \\right)^{3/8} \\right\\}\n%\t\\end{equation}\n%\tReplacing $\\delta$ with $\\delta/2$ we obtain the result.\n%\\end{proof}\n%\n%\\paragraph{Sensitivity Analysis on the KL divergence constraint} Since the KL constraint of REMPS is estimated from samples too, we need to understand how the performance of the solution changes when using a different $\\epsilon$. \\newline\n%\n%$\\epsilon' < \\epsilon$ In this case the constraint is more restrictive, thus we expect $J_p' < J_p$ where $p'$ is the optimal solution (with infinite samples) having $\\epsilon'$ as KL constraint and $p$ the solution with $\\epsilon$. \n%Consider a new \\textit{class distributions} $p_\\alpha = \\alpha p + (1 - \\alpha)q$, a convex combination of $p$ and $q$. Ideally, we could increase $\\alpha$ until we satisfy the constraint $\\epsilon'$ getting the best representation of $p$ fullfilling the constraint, yielding a certain $\\alpha'$. We are able to provide a lower bound on $\\alpha'$ depending on the two coefficients $\\epsilon$ and $\\epsilon'$.\n%\n%\\begin{lemma}\n%\tLet $p_\\alpha = \\alpha p + (1 - \\alpha)q$, the value of $\\alpha'$ s.t. $D_{KL}(p_\\alpha' || q) = \\epsilon'$ can be lower bounded as:\n%\t\\begin{equation}\n%\t\t\\alpha \\geq \\frac{\\epsilon'}{\\epsilon} \n%\t\\end{equation}\n%\\end{lemma}\n%\\begin{proof}\n%\tWe use the convexity of the KL divergence: $D_{KL}(\\alpha \\mu_1 + (1-\\alpha) \\mu_2 || \\alpha \\nu_1 + (1-\\alpha) \\nu_2) \\leq \\alpha D_{KL}(\\mu_1 || \\nu_1) + (1-\\alpha) D_{KL}(\\mu_2 || \\nu_2)$. Take $\\mu_1=p, \\mu_2 = \\nu_1 = \\nu_2 = q$:\n%\t\\begin{align}\n%\t\t\\epsilon' &= D_{KL}(p_\\alpha || q) \\leq \\alpha D_{KL}(p || q) \\\\\n%\t\t\t\t  & \\leq \\alpha \\epsilon\n%\t\\end{align}\n%\tBy inverting the relation the result follows.\n%\\end{proof}\n%Now we are ready to state the main result. \n%\\begin{prop}\n%Let $p$ and $p'$ defined before. The following bound holds:\n%\\begin{equation}\n%\tJ_p - J_p' \\leq R_{max} \\left( 1 - \\frac{\\epsilon'}{\\epsilon} \\right) || p - q ||_1\n%\\end{equation}\t\n%\\end{prop}\n%\n%\\begin{proof}\n%\tWe observe that being $p'$ the optimal solution with constraint $\\epsilon'$ and since $p_{\\alpha'}$ fullfills the constraint we surely have $J_{p'} \\geq J_{p_\\alpha'}$.\n%\t\\begin{align}\n%\t\tJ_p - J_{p'} &\\leq J_p - J_{p_\\alpha'} \\\\\n%\t\t\t\t\t &\\leq R_{max} ||p - p_{\\alpha'}||_1 \\\\\n%\t\t\t\t\t & \\leq R_{max} ||(1-\\alpha')(p - q)||_1 \\\\\n%\t\t\t\t\t & \\leq  R_{max} (1-\\alpha') ||p-q||_1\n%\t\\end{align}\n%\tBy using the previous lower bound on $\\alpha$:\n%\t\\begin{equation}\n%\t\t1 - \\alpha' \\leq 1 - \\frac{\\epsilon'}{\\epsilon} \\, .\n%\t\\end{equation}\n%\tCombining the two previous inequality we obtain the result.\n%\\end{proof} \n%\n%$\\epsilon' > \\epsilon$ We have a more relaxed constraint. We do not need to bound this quantity.\n%\n%\\subsection{Finite-sample analysis}\n%Before going into the details of the analysis let us focus on the main hypothesis space we will consider and the main assumptions we are going to make. \n%\\begin{itemize}\n%\t\\item $\\mathcal{P}_q = \\{p(x) \\propto q(x) \\exp (\\eta R(x) : \\eta \\in [0,+\\infty] \\}$. This is the space of distributions considered int he optimization of REMPS and the dual.\n%\t\\item $\\mathcal{P}$ as defined before is a subspace of distributions.\n%\\end{itemize}\n%\\begin{ass}\n%\tWe assume the following:\n%\t\\begin{itemize}\n%\t\t\\item (Finite dimension) We assume $d=\\max\\{Pdim(\\{p(x)/q(x), p \\in \\mathcal{P}_q\\}), Pdim(\\{(p(x)/q(x))R(x), p \\in \\mathcal{P}_q\\}\\} < \\infty$. Moreovere $\\tilde{d} = Pdim(\\mathcal{P}) < \\infty$.\n%\t\t\\item (Finite Rényi divergence) There exists $\\beta>2$ s.t. $d_\\beta(p||q) < \\infty$ for all $p \\in \\mathcal{P}_q$.\n%\t\t\\item (Uniformly bounded reward) $sup_{x \\in \\mathcal{X}} |R(x)| \\leq R_{max} < \\infty$.\n%\t\\end{itemize}\n%\t\\label{ass:remps}\n%\\end{ass}\n%\n%\\paragraph{Goal} Our main goal is to provide a bound to the quantity $J_p - J_{\\tilde{p}'}$, i.e. the difference on the performance between the exact solution and the projection of solution using a finite number of samples. In order to this we decompose the problem into the REMPS problem and the projection problem:\n%\\begin{equation}\n%\tJ_p - J_{\\tilde{p}'} = \\underbrace{J_p - J_{\\widetilde{p}}}_{\\mathrm{REMPS/dual}} + \\underbrace{J_{\\widetilde{p}}- J_{\\widetilde{p}'}}_{\\mathrm{proj}}.\n%\\end{equation}\n%\n%\\paragraph{First term:} $J_p - J_{\\widetilde{p}}$. This is the difference in (true) performance between the optimal solution having infinite number of samples and the performance of the empirical risk minimizer (ERm). A typical approach from Empirical Risk Minimization (ERM) is to add and subtract the empirical risk of the ERm exploiting the fact that this quantity is larger than (smaller in supervised learning) than the empirical risk of any other hypothesis in the hypothesis space (from the definition of the ERm), in particular $p$. In our framework the hypothesis space changes since the KL constraint is estimated from samples and it can impose more relaxed or tight conditions. We introduce a new distribution $\\bar{p}$ which is the optimal solution of the exact REMPS problem using the sample constraint. For this reason $\\bar{p}$ and $\\tilde{p}$ are searched in the same hypothesis space and we can apply theory from ERM. \n%We need to define the discrepancy in the constraint for a given hypothesis $p$:\n%\\begin{equation}\n%\t\\Delta\\epsilon(p) = D_{KL}(p||q) - \\tilde{D}_{KL, p/q}^N(p||q).\n%\\end{equation} \n%As a consequence:\n%\\begin{align}\n%\t  \\tilde{D}_{KL, p/q}^N(p||q) \\leq \\epsilon \\iff D_{KL}(p||q) \\leq \\epsilon + \\Delta\\epsilon(p) .\n%\\end{align}\n%Finally we define $\\Delta\\epsilon = sup_{p \\in \\mathcal{P}_q} \\Delta\\epsilon(p)$.In other words $\\Delta\\epsilon$ is the suprema, over all hypothesis considered of the discrepancy between the exact KL and the estimated one using the self-normalized importance weights.\n%We have two cases: \\begin{itemize}\n%\t\\item $\\Delta\\epsilon \\leq 0$, the exact constraint is always tighter, thus $J_{\\bar{p}} \\geq J_p$. \n%\t\\item $\\Delta\\epsilon > 0$, there exists at least one hypothesis in $\\mathcal{P}_q$ such that the exact constraint is looser, it might be $J_{\\bar{p}} < J_p$. \n%\\end{itemize} \n%The following result hold in general:\n%\\begin{lemma}\n%Let $p$ and $\\bar{p}$ as defined before:\n%\\begin{equation}\n%\tJ_p - J_{\\bar{p}} \\leq \\frac{2R_{\\max}}{\\epsilon} \\Delta \\epsilon_{+} \\, ,\n%\\end{equation}\n%where $\\Delta \\epsilon_{+} = \\max\\{0, \\Delta\\epsilon\\}$ .\n%\\end{lemma}\n%\\begin{proof}\n%If $J_p - J_{\\bar{p}} < 0$ the theorem holds. Otherwise it must be $\\Delta\\epsilon(p) \\geq 0$.\n%\tWe define $p_\\alpha$ as in the previous proposition:\n%\t\\begin{align}\n%\t\tJ_p - J_{\\bar{p}} & \\leq J_p - J_{p_\\alpha} \\\\\n%\t\t& \\leq R_{\\max} \\left( 1 - \\frac{\\epsilon}{\\epsilon + \\Delta \\epsilon(p)} \\right) ||p - q||_1 \\\\\n%\t\t& \\leq R_{\\max} \\frac{\\Delta\\epsilon(p)}{\\epsilon + \\Delta\\epsilon(p)} || p - q||_1 \\\\\n%\t\t& \\leq R_{\\max} \\frac{\\Delta \\epsilon(p)}{\\epsilon}||p - q||_1 \\\\\n%\t\t& \\leq R_{\\max} \\frac{\\Delta \\epsilon}{\\epsilon}||p - q||_1 \\\\\n%\t\t& \\leq 2R_{\\max} \\frac{\\Delta \\epsilon}{\\epsilon} \\, ,\n%\t\\end{align}\n%\twhere we used the fact that $||p-q||_1 \\leq 2$ ($||p-q||_1$ is total divergence between $p$ and $q$), $\\frac{\\Delta\\epsilon(p)}{\\epsilon + \\Delta\\epsilon(p)} \\leq \\frac{\\Delta\\epsilon(p)}{\\epsilon}$ being $\\Delta\\epsilon(p) \\geq 0$ and finally $\\Delta\\epsilon(p) \\leq \\Delta\\epsilon$. Taking the maximum between the two cases we get the result.\n%\\end{proof}\n%\n%\\paragraph{Bounding $\\Delta\\epsilon_{+}$} Notice that $\\max_{0,\\Delta\\epsilon} \\leq | \\Delta\\epsilon | = \\sup_{p \\in \\mathcal{P}} | \\tilde{D}_{KL, p/q}^N(p||q) - D_{KL}(p||q)|$, which can be used with ERM theory. Assume that $\\Delta\\epsilon_{+} \\leq \\epsilon_2$.\n%\n%We are ready now to give our main result of this theoretical analysis. The following theorem bounds the difference between the performance of the optimal solution and the performance of the solution found with a finite number of samples.\n%\n%\\begin{theorem}[REMPS bound]\n%Let $p$ and $\\tilde{p}$ be the solution of \\remps and \\rempstilde problems, the latter using N i.i.d. samples collected from $q$. Let $\\epsilon > 0$ be the KL constraint. Then, under Assumptions \\ref{ass:remps}, for any $\\delta \\in (0,1)$, w.p. at least $1-\\delta$, it holds that:\n%\\begin{equation}\n%\tJ_p - J_{\\tilde{p}} \\leq 4R_{\\max} \\min \\left\\{1, \\frac{M}{8} \\left( \\frac{d\\log \\frac{2eN}{d} + \\log \\frac{16}{\\delta}}{N} \\right)^{3/8} \\right\\} + \\frac{2R_{\\max}}{\\epsilon} \\epsilon_2 \t\\, .\n%\\end{equation}\n%\\end{theorem}\n%\\begin{proof}\n%\tWe use very simple arguments of ERM. Let $\\bar{p}$ as defined before, remember that $\\tilde{p}$ is the ERm.\n%\t\\begin{align}\n%\tJ_p - J_{\\tilde{p}} &\\leq J_{\\bar{p}} - J_{\\tilde{p}} + \\frac{2R_{\\max}}{\\epsilon} \\Delta \\epsilon_{+} \\\\\n%\t& \\leq J_{\\bar{p}} - J_{\\tilde{p}} +\\frac{2R_{\\max}}{\\epsilon} \\Delta \\epsilon_{+} \\pm \\widetilde{J}_{\\tilde{p}} \\\\\n%\t& \\leq J_{\\bar{p}} - \\widetilde{J}_{\\tilde{p}} + \\widetilde{J}_{\\tilde{p}} - J_{\\tilde{p}} + \\frac{2R_{\\max}}{\\epsilon} \\Delta \\epsilon_{+} \\\\\n%\t& \\leq J_{\\bar{p}} - \\widetilde{J}_{\\bar{p}} + \\widetilde{J}_{\\tilde{p}} - J_{\\tilde{p}} + \\frac{2R_{\\max}}{\\epsilon} \\Delta \\epsilon_{+} \\\\\n%\t& \\leq 2\\sup_{p \\in \\mathcal{P}} |J_p - \\widetilde{J}_p| + \\frac{2R_{\\max}}{\\epsilon} \\Delta \\epsilon_{+} \\, ,\n%\t\\end{align}\n%\twhere we used the fact that $\\widetilde{J}_{\\bar{p}} \\leq \\widetilde{J}_{\\tilde{p}}$, being $\\tilde{p}$ the ERm over the same hypothesis space. \n%\tNow we can apply theorem \\ref{thr:learning-theory} in order to bound the first term:\n%\t\\begin{equation}\n%\t\t\\sup_{p \\in \\mathcal{P}} |J_p - \\widetilde{J}_p| \\leq 2 R_{\\max} \\min \\left\\{1, \\frac{M}{8} \\left( \\frac{d\\log \\frac{2eN}{d} + \\log \\frac{16}{\\delta}}{N} \\right)^{3/8} \\right\\}\t\\end{equation} \\, .\n%\\end{proof}\n%\n%\\paragraph{Second Term: $J_{\\tilde{p}} - \\tilde{J}_{\\tilde{p}'}$} This second term is related to the power of the approximation approximation space considered for the projection. It is useful to recall the property of the KL divergence:\n%\\begin{equation}\n%\tD_{KL}(p||q) = H(p||q) - H(p) \\, ,\n%\\end{equation}\n%where $H(p||q)$ is the cross-entropy between p and q, $H(p||q) = \\int_\\mathcal{X} p(x) \\log q(x)$, and $H(p)$ is the entropy of $p$. When performing the projection, minimizing the KL divergence, we are actually minimizing the cross-entropy term, since the entropy does not depend on $q$.\n\n\\section{Theoretical Analysis}\\label{sec:remps-theory}\nIn this section we derive some theoretical guarantees for the single step of REMPS when it is executed starting from a finite number of samples $N$. This analysis is based on \\citep{cortes2010}.\n\\paragraph{Notation}\nLet $d$ be a stationary distribution, we will denote with \\newline $\\mathcal{D}_d = \\left\\{d'=\\frac{d \\exp \\left( \\frac{1}{\\eta}r \\right)}{\\int d \\exp \\left( \\frac{1}{\\eta}r \\right)}: \\eta \\in [0,+\\infty) \\right\\}$. Given a policy hypothesis space $\\Pi$ and a transition model hypothesis space $\\mathcal{P}$, we will denote with $\\mathcal{D}_{\\mathcal{P}, \\Pi} = \\{ d_{P,\\pi} : P \\in \\mathcal{P}, \\pi \\in \\Pi \\}$ the set of stationary distributions induced by the policy and model hypothesis spaces.\nFor the sake of brevity we will denote with $\\mathcal{X} = \\mathcal{S} \\times \\mathcal{A} \\times \\mathcal{S}$ the state-action-next state space and with $x = (s, a, s')$ a state-action-next-state triple. Given a set $\\mathcal{X}$, we denote with $\\Delta(\\mathcal{X})$ the set of probability distributions on $\\mathcal{X}$.\n\n\\subsection{Problem Formulation}\nIn this section we revisit the REMPS problem formulation in order to understand better its component to perform a theoretical analysis.\nThe REMPS problem takes as input a KL-divergence threshold and provides as output a new stationary distribution on the space $\\mathcal{D}_{\\mathcal{P},\\Pi}$.\nAs we said before, our algorithm is divided in two phases: \\textit{optimization} and \\textit{projection}.\n\\paragraph{Optimization} The problem we aim to solve in the optimization phase can be stated as follows. Given a KL-divergence threshold $\\epsilon>0$, let $(P,\\pi) \\in \\mathcal{P} \\times \\Pi$ be the current configuration-policy pair inducing a stationary distribution $d^{P,\\pi}$, we seek for a new stationary distribution $d$ that solves the optimization problem $\\text{OPT}_{P,\\pi}(\\epsilon)$:\n\\begin{align}\n\t\\underset{d \\in \\Delta{\\mathcal{X}}}{\\max} J_d &= \\underset{x \\sim d}{\\mathbb{E}} \\left[ R(x) \\right] \\\\\n\t\\text{s.t.} & \\;\\; D_{KL}(d||d^{P,\\pi}) = \\underset{x \\sim d}{\\mathbb{E}} \\left[ \\log \\frac{d(x)}{d^{P,\\pi}(x)} \\right] \\leq \\epsilon.\n\\end{align}\nThe solution of $\\text{OPT}_{P,\\pi}(\\epsilon)$ is:\n\\begin{equation}\n\td(x) = \t\\frac{d^{P,\\pi}(x) \\exp \\left( \\frac{1}{\\eta}R(x) \\right)}{\\int_{\\mathcal{X}}d^{P,\\pi}(x) \\exp \\left( \\frac{1}{\\eta}R(x) \\right) \\mathrm{d}x}, x \\in \\mathcal{X},\n\\end{equation}\nwhere $\\eta$ is the unique solution of the dual problem $\\text{DUAL}_{P,\\pi}(\\epsilon)$:\n\\begin{equation}\n\t\\min_{\\eta \\in [0, +\\infty)} \\eta \\log \\underset{x \\sim d^{P,\\pi}}{\\mathbb{E}} \\exp  \\left( \\frac{1}{\\eta} R(x) + \\epsilon \\right).\n\\end{equation}\n\nIn practice we have access neither to $d^{P,\\pi}$ nor to $d$. Therefore we need to estimate expectations with samples averages from samples collected with the distribution $d^{P,\t\\pi}$. Notice that we have only access to an empirical estimate of $d^{P,\t\\pi}$, which is $\\widehat{d}^{P,\t\\pi} = \\frac{1}{N} \\sum_{i=1}^{N} \\delta(x - x_i)$ uniform on the seen $x$s. For this purpose we perform an importance sampling procedure. We define the weights $w(x_i) = \\frac{d(x_i)}{\\widehat{d}^{P,\\pi}(x_i)} = N d(x_i)$. Thus, the approximated problem we need to solve is actually $\\widetilde{\\text{OPT}}_{P,\\pi}(\\epsilon)$:\n\\begin{align}\n\\max_{d \\in \\Delta(\\{x_i : i \\in \\{1,2,...,N\\} \\} )} & \\widetilde{J}_d = \\frac{1}{N} \\sum_{i=1}^N w(x_i) R(x_i) = \\sum_{i=1}^N d(x_i) R(x_i) \\\\\n\\text{s.t.} & \\; \\; \\widetilde{D}_{KL}(d||d^{P,\\pi}) = \\frac{1}{N} \\sum_{i=1}^N w(x_i) \\log w(x_i) = \\\\ & \\qquad \\qquad \\qquad \\; = \\sum_{i=1}^N d(x_i) \\log d(x_i) + \\log N \\leq \\epsilon .\n\\end{align}\nThis problem yields a solution which is defined only over the seen state-action-next state triples:\n\\begin{equation}\n\td(x_i) = \\frac{\\exp \\left( \\frac{1}{\\widetilde{\\eta}} R(x_i) \\right)}{\\frac{1}{N}\\sum_{j=1}^N \\left( \\frac{1}{\\widetilde{\\eta}} R(x_j) \\right)} , \\; \\; i \\in \\{1,2,..., N\\},\n\\end{equation}\nwhere $\\widetilde{\\eta}$ is the unique solution of the approximated dual problem $\\widetilde{\\text{DUAL}}_{P,\\pi}(\\epsilon)$:\n\\begin{equation}\n\t\\min_{\\eta \\in [0,+\\infty)} \\eta \\log \\frac{1}{N} \\sum_{i=1}^N \\left( \\frac{1}{\\widetilde{\\eta}} R(x_i) + \\epsilon \\right) .\n\\end{equation}\nOnce solved this problem, the new distribution over the whole space $\\mathcal{X}$ is characterized only by the Lagrange multiplier $\\widetilde{\\eta}$:\n\\begin{equation}\n\t\\widetilde{d}(x) = \\frac{d^{P,\\pi}(x) \\exp \\left( \\frac{1}{\\widetilde{\\eta}} R(x) \\right)}{\\int_{\\mathcal{X}} d^{P,\\pi}(x) \\exp \\left( \\frac{1}{\\widetilde{\\eta}} R(x) \\right)} , \\; x \\in \\mathcal{X} .\n\\end{equation}\nWe denote the performance of the new stationary distribution $\\widetilde{d}$ as with $J_{\\widetilde{d}}= \\mathbb{E}_{x \\sim \\widetilde{d}} \\left[ R (x) \\right]$. As expected we would like find $\\widetilde{d}$ maximizing $J_{\\widetilde{d}}$ but we actually use an empirical estimate $\\widetilde{J}_{\\widetilde{d}}$.\n\n\\paragraph{Projection} In the \\textit{Projection} phase we aim to find the best representation of the stationary distribution we got from the optimization phase given hypothesis space $\\mathcal{D}_{\\mathcal{P}, \\Pi}$. Let $d$ be the solution of $\\text{OPT}_{P,\\pi}(\\epsilon)$, the projection problem $\\text{PROJ}_{\\mathcal{D}_{P,\\Pi}}(d)$ can be stated as the moment-projection of $d$ onto $\\mathcal{D}_{\\mathcal{P},\\Pi}$:\n\\begin{equation}\n\t\\max_{d' \\in \\mathcal{D}_{\\mathcal{P}, \\Pi}} H(d||d') = \\underset{x \\sim d}{\\mathbb{E}} \\left[ \\log d'(x) \\right],\n\\end{equation}\nwhere we considered the cross-entropy $H(d||d')$ instead of the KL--divergence, since \\newline $D_{KL}(d||d')= H(d||d') - H(d)$ and the entropy term $H(d)$ is independent on $d'$. We call $d'$ the solution of this problem, which can be considered the solution of the complete problem $\\text{REMPS}_{P,\\pi}(\\epsilon) = \\text{PROJ}_{\\mathcal{D}_{\\mathcal{P}, \\Pi}}(\\cdot) \\circ \\text{OPT}_{P,\\pi}(\\epsilon)$. Clearly, also in the projection phase we need to consider the Monte Carlo estimates again obtained by the very same samples $\\{x_i\\}_{i=1}^N$ collected with the sampling distribution $d^{P,\\pi}$. Let $\\widetilde{d}$ be the solution of $\\widetilde{\\text{OPT}}_{P,\\pi}(\\epsilon)$, the approximated projection problem $\\widetilde{\\text{PROJ}}_{\\mathcal{D}_{\\mathcal{P},\\Pi}}(\\widetilde{d})$ becomes:\n\n\\begin{equation}\n\t\\max_{d' \\in \\mathcal{D}_{\\mathcal{P}, \\Pi}} \\widetilde{H}(\\widetilde{d}||d') = \\frac{1}{N} \\sum_{i=1}^N w(x_i) \\log d'(x_i) .\n\\end{equation}\nWe call $\\widetilde{d}'$ the solution of this problem, which can be considered the solution of the complete approximated problem $\\widetilde{REMPS}_{P,\\pi}(\\epsilon) = \\widetilde{\\text{PROJ}}_{\\mathcal{D}_{\\mathcal{P},\\Pi}}(\\cdot) \\circ \\widetilde{\\text{OPT}}_{P,\\pi}(\\epsilon)$.\n\n\\paragraph{Off-distribution estimation}\nGiven a value of the Lagrange multiplier $\\eta$ inducing the distribution $d$, let us define the ratio importance weight $\\widehat{w}(x)$ and the self-normalized importance weight $\\widetilde{w}(x)$ as:\n\\begin{align*}\n\t\\widehat{w}(x) &= \\frac{d(x)}{d^{P,\\pi}(x)} =\\\\ &= \\frac{\\exp \\left( \\frac{1}{\\eta} R(x) \\right)}{\\int_{\\mathcal{X}} d^{P,\\pi}(x) \\exp \\left( \\frac{1}{\\eta} R(x) \\right) \\mathrm{d}x}, \\\\\n\t \\widetilde{w}(x) &= \\frac{\\widehat{w}(x)}{\\sum_{i=1}^N \\widehat{w}(x_i)} = \\\\ &= \\frac{\\exp \\left( \\frac{1}{\\eta} R(x) \\right)}{ \\sum_{i=1}^N \\exp \\left( \\frac{1}{\\eta} R(x_i) \\right) }.\n\\end{align*}\nThus, the off-distribution estimator $\\widetilde{J}_d$, which is optimized by $\\widetilde{\\text{OPT}}_{P,\\pi}(\\epsilon)$ is actually a \\textit{self-normalized importance weighting} estimate, opposed to the \\textit{ratio importance weighting estimate} $\\widehat{J}_d$ which does not appear in the optimization problems, but will be useful in the following:\n\\begin{align*}\n\t\\widehat{J}_d &= \\frac{1}{N} \\sum_{i=1}^N \\widehat{w}(x_i) R(x_i), \\\\ \\widetilde{J}_d &= \\sum_{i=1}^N \\widetilde{w}(x_i) R(x_i).\n\\end{align*}\nAnalogously, we define the KL-divergence estimators:\n\\begin{align*}\n\t\\widehat{D}_{KL}(d \\| d^{P,\\pi} ) &= \\frac{1}{N} \\sum_{i=1}^N \\widehat{w}(x_i) \\log \\widehat{w}(x_i), \\\\ \\widetilde{D}_{KL}(d \\| d^{P,\\pi} ) &= \\sum_{i=1}^N  \\widetilde{w}(x_i) \\log  \\left( N \\widetilde{w}(x_i)\\right),\n\\end{align*}\nand, given $d' \\in \\mathcal{D}_{\\mathcal{P},\\Pi}$, we define the cross-entropy estimators:\n\\begin{align*}\n\t\\widehat{H} (d \\| d') &= \\frac{1}{N} \\sum_{i=1}^N \\widehat{w}(x_i) \\log d'(x_i), \\\\ \\widetilde{H} (d \\| d') &=  \\sum_{i=1}^N \\widetilde{w}(x_i) \\log d'(x_i).\n\\end{align*}\nIt is well known that the ratio estimation is unbiased while the self-normalized estimator is biased but consistent.\n\n\\subsection{Assumptions}\nWe start providing two assumptions that we will consider in the whole analysis:\n\\begin{ass}[Uniformly bounded reward]\n\\label{ass:reward}\n\tFor any $s,s' \\in \\mathcal{S}$, $a \\in \\mathcal{A}$, it holds that: $|R(s,a,s')| \\leq r_{\\max}$.\n\\end{ass}\n\\begin{ass}[Finite pseudo-dimension]\n\\label{ass:dim}\n\tGiven a policy $\\pi \\in \\Pi$ and a transition model $P \\in \\mathcal{P}$, the pseudo-dimensions of the hypothesis spaces $\\{ \\frac{d}{d^{P,\\pi}} : d \\in D_{d^{P,\\pi}}\\}$, $\\{ \\frac{d}{d^{P,\\pi}}R : d \\in D_{d^{P,\\pi}}\\}$, $\\{ \\frac{d}{d^{P,\\pi}} \\log \\left( \\frac{d}{d^{P,\\pi}} \\right) : d \\in D_{d^{P,\\pi}}\\}$ and $\\{ \\frac{d}{d^{P,\\pi}} \\log \\left( d' \\right) : d \\in D_{d^{P,\\pi}}, d' \\in \\mathcal{D}_{\\mathcal{P}, \\Pi} \\}$ are bounded by $v < + \\infty$. The first is the space of non-normalized weights. The second is the space average reward estimators, the third is the space of KL--divergence estimators and the last is the space of cross-entropy estimators.\n\t\\end{ass}\n\n\\subsection{Sensitivity to the KL constraint}\nIn this section, we analyze how the performance of the solution of the problem $\\text{OPT}_{P,\\pi}(\\epsilon)$ changes when we change the KL-divergence threshold. Suppose that $\\epsilon' \\leq \\epsilon$, the constraint is more restrictive, thus we expect that $J_{d'} \\leq J_{d}$, where $d'$ is the solution of $\\text{OPT}_{P,\\pi}(\\epsilon')$ and $d$ is the solution of $\\text{OPT}_{P,\\pi}(\\epsilon)$, since we are in the ideal case. Let us consider a new class distributions $d_\\alpha = \\alpha d + (1-\\alpha) d_{P,\\pi}$, with $\\alpha \\in [0,1]$. Ideally we could increase $\\alpha$ until we satisfy the constraint $\\epsilon'$ getting the best representation of $d$ fulfilling the constraint (a projection).\n\\begin{lemma}\n\\label{L:alphaBound}\n\tLet $d$ and $d'$ be the solution of the problems $\\text{OPT}_{P,\\pi}(\\epsilon)$ and $\\text{OPT}_{P,\\pi}(\\epsilon')$ with $\\epsilon' \\leq \\epsilon$. Let $d_\\alpha = \\alpha d + (1-\\alpha) d^{P,\\pi}$ with $\\alpha \\in [0,1]$. If $D_{KL}(d_\\alpha \\| d^{P,\\pi}) = \\epsilon'$, then $\\alpha \\geq \\frac{\\epsilon'}{\\epsilon}$.\n\\end{lemma}\n\t\\begin{proof}\n\t\tWe use the convexity of the KL-divergence:\n\t\t $D_{KL}(\\alpha \\mu_1 + (1-\\alpha) \\mu_2 \\|  \\alpha \\nu_1 + (1-\\alpha) \\nu_2) \\le \\alpha D_{KL}(\\mu_1 \\| \\nu_1) + (1-\\alpha) D_{KL}(\\mu_2 \\| \\nu_2)$ for $\\alpha \\in [0,1]$. Take $\\mu_1 = d$, $\\mu_2 = \\nu_1 = \\nu_2 = d^{P,\\pi}$:\n\t\\begin{align*}\n\t\t\\epsilon' = D_{KL}(d_{\\alpha} \\| q) & = D_{KL} (\\alpha d + (1-\\alpha) d^{P,\\pi} \\| \\alpha d^{P,\\pi} + (1-\\alpha) d^{P,\\pi}) \\le \\\\\n\t\t& \\le \\alpha D_{KL} (d \\| d^{P,\\pi}) + (1-\\alpha) D_{KL} (d^{P,\\pi} \\| d^{P,\\pi}) = \\alpha D_{KL} (d \\| d^{P,\\pi}).\n\t\\end{align*}\n\tTherefore, observing that $D_{KL} (d \\| d^{P,\\pi}) \\le \\epsilon$:\n\t\\begin{equation}\n\t\t\\alpha \\ge \\frac{\\epsilon'}{D_{KL} (d \\| d^{P,\\pi})} \\ge \\frac{\\epsilon'}{\\epsilon}.\n\t\\end{equation}\n\\end{proof}\nThe following results upper bound the reduction of performance.\n\\begin{prop}[$\\epsilon$ sensitivity]\n\tLet $d$ and $d'$ the solutions of \\opt{\\epsilon} and \\opt{\\epsilon '} respectively starting from $d^{P,\\pi}$ and with $\\epsilon' \\le \\epsilon$. Then:\n\t\\begin{equation}\n\t\tJ_d - J_{d'} \\le r_{\\max} \\| d - d^{P,\\pi} \\|_1 \\left( 1 - \\frac{\\epsilon'}{\\epsilon} \\right) .\n\t\\end{equation}\n\\end{prop}\n\\begin{proof}\n\tConsider the $\\alpha' \\in [0,1]$ such that $D_{KL}(d_{\\alpha'} \\| d^{P,\\pi}) = \\epsilon'$. We start observing that being $d'$ the optimal solution with constraint $\\epsilon'$ and since $d_{\\alpha'}$ fulfills the constraint, we surely have $J_{d'} \\ge J_{d_{\\alpha'}}$. Consider the following sequence of inequalities:\n\t\\begin{align*}\n\t\tJ_d - J_{d'} & \\le J_d - J_{d_{\\alpha'}}  \\\\\n\t\t\t& \\le r_{\\max} \\|d - d_{\\alpha'} \\|_1  \\\\\n\t\t\t& \\le r_{\\max} \\|(1-\\alpha') (d - d^{P,\\pi}) \\|_1  \\\\\n\t\t\t& = r_{\\max} (1-\\alpha') \\| d - d^{P,\\pi} \\|_1.\n\t\\end{align*}\n\tApplying Lemma~\\ref{L:alphaBound} we get $1-\\alpha' \\le 1 - \\frac{\\epsilon'}{\\epsilon}$, from which the result follows.\n\\end{proof}\n\n\\subsection{Finite-Sample Analysis}\nWe have seen in the previous section that we need to solve using samples both phases of the \\remps problem. Starting from $d^{P,\\pi}$, \\opt{\\epsilon} yields the solution $d$ whereas \\rempskappahat{\\epsilon} provides the solution $\\widetilde{d}'$ which is derived from the \\opthat{\\epsilon} problem yielding $\\widetilde{d}$ and the \\projhat{\\widetilde{d}} problem. There are two sources of error in this process. First, $\\widetilde{d}$ is obtained from a finite sample and thus it might differ from $d$ (\\emph{estimation error}). Second, we limit to a hypothesis space $\\mathcal{D}_{\\mathcal{P},\\Pi}$ that might not be able to represent $\\widetilde{d}$ (\\emph{approximation error}). The goal of this analysis is to  provide a bound to the quantity $J_d - J_{\\widetilde{d}'}$. For this purpose, we consider the following decomposition to isolate the contribution of the \\opt{\\epsilon} and \\dual{\\epsilon} from the contribution of \\proj{\\cdot}:\n\\begin{equation}\n\tJ_d - J_{\\widetilde{d}'} = \\underbrace{J_d - J_{\\widetilde{d}}}_{\\text{OPT}} + \\underbrace{J_{\\widetilde{d}}- J_{\\widetilde{d}'}}_{\\mathrm{PROJ}}.\n\\end{equation}\n\n\\paragraph{$J_d - J_{\\widetilde{d}}$}\nA typical approach, from Empirical Risk Minimization (ERM), for bounding the estimation error is to sum and subtract the empirical risk of the empirical risk minimizer $\\widetilde{J}_{\\widetilde{d}}$ and exploit the fact that this quantity is larger (smaller in supervised learning) than the empirical risk of any other hypothesis in the hypothesis space (being ERM), in particular $d$. However, in our framework the hypothesis space changes since the constraint con the KL--divergence is estimated from samples and, in principle, it can impose more relaxed/tight conditions. For this purpose we introduce a new distribution $\\overline{d}$ which is the optimal solution of the \\opt{\\epsilon} problem using the sample constraint. For this reason, $\\widetilde{d}$ and $\\overline{d}$ are searched in the same hypothesis space and thus we can apply theory from ERM. Clearly, we need to manage the discrepancy between $\\overline{d}$ and $d$; for this, we use the sensitivity analysis we presented before. Let us define the discrepancy in the constraint for a given hypothesis $d$:\n\\begin{equation}\n\t\\Delta \\epsilon(d) = D_{KL}(d\\|d^{P,\\pi}) - {\\widetilde{D}}_{KL}(d\\|d^{P,\\pi}).\n\\end{equation}\nAs a consequence ${\\widetilde{D}}_{KL}(d\\|d^{P,\\pi}) \\le \\epsilon  \\iff  D_{KL}(d\\|d^{P,\\pi}) \\le \\epsilon + \\Delta \\epsilon(d)$. Finally, we define $\\Delta \\epsilon = \\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}} \\Delta \\epsilon(d)$.\nWe have the usual two cases. i) If $\\Delta \\epsilon \\le 0$ then the exact constraint is always (i.e., for every hypothesis) tighter and thus $J_{\\overline{d}} \\ge J_d$. ii) If $\\Delta \\epsilon > 0$ then there exist at least one hypothesis for which the constraint is looser; thus it might be that $J_{\\overline{d}} \\le J_d$. In general, the following result holds.\n\\begin{lemma}\n\tLet $d$, $\\overline{d}$ as defined before. The following bound holds:\n\t\\begin{equation}\n\t\tJ_d  \\le J_{\\overline{d}} + 2 r_{\\max} \\max \\left\\{0, \\min\\left\\{\\frac{1}{2}, \\frac{\\Delta \\epsilon}{\\epsilon} \\right\\} \\right\\}.\n\t\\end{equation}\n\\end{lemma}\n\n\\begin{proof}\n\tIf $J_d - J_{\\overline{d}} \\le 0$ then the theorem holds. Otherwise, it must be that $\\Delta \\epsilon(d) \\ge 0$ (this is because we find $\\overline{d}$ as optimal solution having smaller performance with respect to $d$). We define $d_{\\alpha}$ as in the previous proposition so we get:\n\t\\begin{align*}\n\t\tJ_{d} - J_{\\overline{d}} & \\le J_{d} - J_{d_{\\alpha}}  \\\\\n\t\t\t& \\le r_{\\max}  \\left(1 - \\frac{\\epsilon}{\\epsilon + \\Delta \\epsilon(d)} \\right) \\|d - d^{P,\\pi} \\|_1  \\\\\n\t\t\t& \\le r_{\\max} \\frac{\\Delta \\epsilon(d)}{\\epsilon + \\Delta \\epsilon(d)}  \\|d -  d^{P,\\pi}\\|_1  \\\\\n\t\t\t& \\le 2 r_{\\max} \\min \\left\\{ \\frac{1}{2}, \\frac{\\Delta \\epsilon(d)}{\\epsilon} \\right\\}  \\\\\n\t\t\t& \\le 2 r_{\\max}  \\min \\left\\{ \\frac{1}{2}, \\frac{\\Delta \\epsilon}{\\epsilon} \\right\\},\n\t\\end{align*}\n\twhere we exploited the fact that $\\|d - d^{P,\\pi} \\|_1 \\le 2$,  $\\frac{\\Delta \\epsilon(d)}{\\epsilon + \\Delta \\epsilon(d)} \\le  \\frac{\\Delta \\epsilon(d)}{\\epsilon}$, being $\\Delta \\epsilon(d) \\ge 0$, and $\\frac{\\Delta \\epsilon(d)}{\\epsilon + \\Delta \\epsilon(d)} \\le  \\frac{1}{2}$ being $\\Delta\\epsilon(d) \\leq \\epsilon$ and finally $\\Delta \\epsilon(d) \\le \\Delta \\epsilon$. Taking the max between the two cases we get the result.\n\\end{proof}\n\nNotice that $\\max \\left\\{0, \\min\\left\\{\\frac{1}{2}, \\frac{\\Delta \\epsilon}{\\epsilon} \\right\\} \\right\\} \\le \\frac{|\\Delta \\epsilon|}{\\epsilon}$ and  \\newline $\\frac{|\\Delta \\epsilon|}{\\epsilon} = \\frac{1}{\\epsilon} \\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}} \\left| {\\widetilde{D}}_{KL}(d \\|d^{P,\\pi})- D_{KL}(d \\|d^{P,\\pi})\\right|$, which is convenient for using ERM theory. Now we are ready to bound $J_d - J_{\\widetilde{d}}$.\n\n\\begin{lemma}\n\\label{lemma:first}\n\tLet $d$ and $\\widetilde{d}$ be the solutions of the \\opt{\\epsilon} and \\opthat{\\epsilon} problems, the latter using $N$ i.i.d. samples collected from $d^{P,\\pi}$. Let $\\epsilon > 0$ be the KL--constraint. Then, it holds that:\n\t\\begin{equation}\n\t\tJ_d - J_{\\widetilde{d}} \\le 2 \\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}} | J_d - \\widetilde{J}_d | + \\frac{2 r_{\\max}}{\\epsilon} \\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}} \\left| {\\widetilde{D}}_{KL}(d \\|d^{P,\\pi})- D_{KL}(d \\|d^{P,\\pi})\\right|.\n\t\\end{equation}\n\\end{lemma}\n\n\\begin{proof}\nWe use a very simple argument of ERM combined with the previous result. Let $\\overline{p}$ as defined before, we have:\n\t\\begin{align*}\n\t\tJ_d - J_{\\widetilde{d}} & \\le J_{\\overline{d}} - J_{\\widetilde{d}} + \\frac{2 r_{\\max}}{\\epsilon}\\max \\left\\{0, \\min\\left\\{\\frac{1}{2}, \\frac{\\Delta \\epsilon}{\\epsilon} \\right\\} \\right\\}  \\\\\n\t\t& \\le J_{\\overline{d}} - J_{\\widetilde{d}} + \\frac{2 r_{\\max}}{\\epsilon} |\\Delta\\epsilon| \\\\\n\t\t& = J_{\\overline{d}} - J_{\\widetilde{d}} + \\frac{2 r_{\\max}}{\\epsilon} |\\Delta\\epsilon| \\pm \\widetilde{J}_{\\widetilde{d}} \\\\\n\t\t& \\le J_{\\overline{d}} - \\widetilde{J}_{\\overline{d}} + \\widetilde{J}_{\\widetilde{d}} - J_{\\widetilde{d}} + \\frac{2 r_{\\max}}{\\epsilon} |\\Delta\\epsilon|   \\\\\n\t\t& \\le 2 \\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}} | J_d - \\widetilde{J}_d | + \\frac{2 r_{\\max}}{\\epsilon} \\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}}  \\left| {\\widetilde{D}}_{KL}(d \\|d^{P,\\pi})- D_{KL}(d \\|d^{P,\\pi})\\right|, \n\t\\end{align*}\n\twhere we exploited the fact that $\\widetilde{J}_{\\overline{d}} \\le \\widetilde{J}_{\\widetilde{d}} $, being $\\widetilde{d}$ the ERM over the same hypothesis space.\n\\end{proof}\n\n\\paragraph{$J_{\\widetilde{d}}- J_{\\widetilde{d}'}$}\nFor bounding this second term is useful to recall the property of the KL--divergence\t$D_{KL} (d \\| d') = H(d \\| d') - H(d)$, where $H(d \\| d')$ is the cross--entropy (likelihood when computed on finite samples) between $d$ and $d'$ and $H(d)$ is the entropy of $d$. When performing the projection we are minimizing the term $H(d \\| d')$ since $H(d)$ does not depend on $d'$. We can state the following result.\n\n\\begin{lemma}\n\\label{lemma:second}\n\tLet $\\widetilde{d}$ and $\\widetilde{d}'$ be the solutions of the \\opthat{\\epsilon} and \\projhat{\\widetilde{d}} problems using $N$ i.i.d. samples collected from $d^{P,\\pi}$. Let $\\epsilon > 0$ be the KL--constraint. Then, it holds that:\n\t\t\\begin{align}\n\tJ_{\\widetilde{d}} - J_{\\widetilde{d}'} \\le &r_{\\max} \\sqrt{2 \\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}}  \\inf_{d' \\in \\mathcal{D}_{\\mathcal{P}, \\Pi}} D_{KL}( d \\| d')} +\\\\ &+ r_{\\max} \\sqrt{2 \\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}} \\sup_{d' \\in \\mathcal{D}_{\\mathcal{P}, \\Pi}} \\left| \\widehat{H} (d \\| d') -  H(d \\| d') \\right|}.\n\t\t\\end{align}\n\\end{lemma}\n\n\\begin{proof}\nLet us call:\n\\begin{equation}\n\t\\nu_1 = \\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}} \\sup_{d' \\in \\mathcal{D}_{\\mathcal{P}, \\Pi}} \\left| \\widehat{H} (d \\| d') -  H(d \\| d') \\right|.\n\\end{equation}\nConsider the best approximation of $\\widetilde{d}$ contained in $\\mathcal{D}_{\\mathcal{P}, \\Pi}$, let us call it $d^*$ \t\\newline ($d^* = \\argmin_{d' \\in \\mathcal{D}_{\\mathcal{P}, \\Pi}} H(\\widetilde{d} \\| d')$).\nThen we can state the following inequalities:\n\\begin{align}\n\tJ_{\\widetilde{d}} - J_{\\widetilde{d}'} & \\le r_{\\max} \\| \\widetilde{d} - \\widetilde{d}' \\|_1  \\label{line:1}\\\\\n\t\t& \\le r_{\\max} \\sqrt{2 D_{KL} ( \\widetilde{d} \\| \\widetilde{d}') }  \\label{line:2}\\\\\n\t\t& \\le r_{\\max} \\sqrt{2 H ( \\widetilde{d} \\| \\widetilde{d}') - 2H(\\widetilde{d})}  \\label{line:3}\\\\\n\t\t& \\le r_{\\max} \\sqrt{2 \\widehat{H} ( \\widetilde{d} \\| \\widetilde{d}') - 2H(\\widetilde{d}) + \\nu_1} \\label{line:4} \\\\\n\t\t& \\le r_{\\max} \\sqrt{2 \\left( \\frac{1}{N} \\sum_{i=1}^{N} \\widehat{w}(x_i) \\right) \\widetilde{H} ( \\widetilde{d} \\| \\widetilde{d'}) - 2H(\\widetilde{d}) + \\nu_1}  \\label{line:5}\\\\\n\t\t& \\le r_{\\max} \\sqrt{2 \\left( \\frac{1}{N} \\sum_{i=1}^{N} \\widehat{w}(x_i) \\right) \\widetilde{H} ( \\widetilde{d} \\| d^*) - 2H(\\widetilde{d}) + \\nu_1}  \\label{line:6}\\\\\n\t\t& \\le r_{\\max} \\sqrt{2 \\widehat{H} ( \\widetilde{d} \\| d^*) - 2H(\\widetilde{d}) + \\nu_1}  \\label{line:7}\\\\\n\t\t& \\le r_{\\max} \\sqrt{2 D_{KL}( \\widetilde{d} \\| d^*) + 2 \\nu_1}  \\label{line:7}\\\\\n\t\t& \\le r_{\\max} \\sqrt{2 D_{KL}( \\widetilde{d} \\| d^*)} + r_{\\max} \\sqrt{2 \\nu_1}  \\label{line:8}\\\\\n\t\t& \\le r_{\\max} \\sqrt{2 \\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}}  \\inf_{d' \\in \\mathcal{D}_{\\mathcal{P}, \\Pi}}  D_{KL}( d \\| d')} + r_{\\max} \\sqrt{2 \\nu_1}, \\label{line:9}\n\\end{align}\nwhere line~\\eqref{line:2} follows from Pinsker inequality, lines~\\eqref{line:4} and~\\eqref{line:7} follow from the hypothesis, line~\\eqref{line:5} follows from the fact that $\\widetilde{d}'$ is ERM, line~\\eqref{line:8} follows from the inequality $\\sqrt{a+b} \\le \\sqrt{a}+\\sqrt{b}$ and lines~\\eqref{line:5} and \\eqref{line:6} follows from the fact that $\\left( \\frac{1}{N} \\sum_{i=1}^{N} \\widehat{w}(x_i) \\right) \\widetilde{H} ( \\widetilde{d} \\| \\widetilde{d'}) = \\widehat{H}( \\widetilde{d} \\| \\widetilde{d'})$.\n\\end{proof}\n\nPutting all together we get the following result.\n\n\\begin{theorem}[Error Decomposition]\n\\label{thr:decomposition}\nLet $\\pi \\in \\Pi$ and $P \\in \\mathcal{P}$ be the current policy and transition model respectively. Let $\\epsilon > 0$ be the KL--divergence constraint. Let $d \\in \\mathcal{D}_{d^{P,\\pi}}$ be the solution of the $OPT_{P,\\pi}(\\epsilon)$ problem and $\\widetilde{d}' \\in \\mathcal{D}_{\\mathcal{P}, \\Pi}$ be the solution of the \\rempskappahat{\\epsilon} problem computed with $N>0$ samples collected with $d^{P,\\pi}$. Then, under Assumptions~\\ref{ass:reward}, it holds that:\n\\begin{align*}\n\t J_{d} - J_{\\widetilde{d}'} & \\le 2 \\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}} | J_d - \\widetilde{J}_d | + \\\\ & \\quad + \\frac{2 r_{\\max}}{\\epsilon} \\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}} \\left| {\\widetilde{D}}_{KL}(d \\|d^{P,\\pi})- D_{KL}(d \\|d^{P,\\pi})\\right| + \\\\\n\t & \\quad + r_{\\max} \\sqrt{2 \\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}}  \\inf_{\\overline{d} \\in \\mathcal{D}_{\\mathcal{P}, \\Pi}} D_{KL}( \\overline{d} \\| d')} +  \\\\\n\t & \\quad + r_{\\max} \\sqrt{2 \\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}} \\sup_{d' \\in \\mathcal{D}_{\\mathcal{P}, \\Pi}} \\left| \\widehat{H} (d \\| d') -  H(d \\| d') \\right|}.\n\\end{align*}\n\\end{theorem}\n\n\\begin{proof}\n\tPut together Lemma~\\ref{lemma:first} and Lemma~\\ref{lemma:second}.\n\\end{proof}\n\n\\subsection{Analysis for bounded probability densities}\nIn the following, we will provide a finite--sample analysis of \\remps under the following restrictive assumption.\n\\begin{ass}\n\\label{ass:finite}\n\t(Finite $\\inf$, Non--zero $\\sup$) For every $\\pi \\in \\Pi$ and a transition model $P \\in \\mathcal{P}$, for every $d \\in \\mathcal{D}_{d^{P,\\pi}}$ and for every $s,s' \\in \\mathcal{S}$ and $a \\in \\mathcal{A}$ it holds that $0 < m \\le d(s,a,s') \\le M < +\\infty$ and  $0 < m \\le d^{P,\\pi}(s,a,s') \\le M < +\\infty$.\n\\end{ass}\n\nThis assumption ensures that all loss function we are considering are uniformly bounded and allows us to state a sequence of useful facts.\n\n\\begin{lemma}\n\\label{lemma:max}\n\tFor any $d \\in \\mathcal{D}_{d^{P,\\pi}}$ and for any $d' \\in \\mathcal{D}_{\\mathcal{P},\\Pi}$. The following facts hold:\n\t\\begin{enumerate}\n\t\t\\item The importance weights are bounded above and below: $\\frac{m}{M} \\le \\widehat{w}(x) \\le \\frac{M}{m}$.\n\t\t\\item The empirical KL divergence is bounded: $\\left| \\widehat{D}_{KL} (d \\| d^{P,\\pi}) \\right| \\le \\max \\left\\{ \\frac{1}{e}, \\frac{M}{m} \\log \\frac{M}{m} \\right\\}$;\n\t\t\\item The empirical cross--entropy is bounded: $\\left| \\widehat{H} (d' \\| d) \\right|  \\le \\max \\left\\{ - \\frac{M}{m} \\log m, \\frac{M}{m} \\log M \\right\\}$;\n\t\t\\item $\\left| \\widehat{D}_{KL} (d \\| d^{P,\\pi}) - \\widetilde{D}_{KL} (d \\| d^{P,\\pi}) \\right| \\le \\Lambda(M,m,N) \\left| \\frac{1}{N} \\sum_{i=1}^N \\widehat{w}(x_i)- 1 \\right| $, where $\\Lambda(M,m,N) = \\max\\left\\{ \\log \\frac{M}{m} + 1,  -\\log \\frac{m}{M} - 1, \\log N + 1 \\right\\}$.\n%\t\t\\item $\\left| \\widehat{H} (d' \\| d) - \\widetilde{H} (d' \\| d) \\right| \\le \\max\\left\\{-\\log m, \\log M\\right\\} \\left| \\frac{1}{N} \\sum_{i=1}^N \\widehat{w}(x_i)- 1 \\right| $.\n\t\t\\item $\\left| \\widehat{J}_d - \\widetilde{J}_d \\right| \\le r_{\\max} \\left| \\frac{1}{N} \\sum_{i=1}^N \\widehat{w}(x_i)- 1 \\right| $.\n\t\\end{enumerate}\n\\end{lemma}\n\n\\begin{proof}\n\\begin{enumerate}\n\t\\item Immediate consequence of Assumption~\\ref{ass:finite}, just observing that $\\widehat{w}(x) = d(x) / d^{P,\\pi}(x)$.\n\t\\item $|\\widehat{D}_{KL} (d \\| d^{P,\\pi}) | \\le  \\frac{1}{N} \\sum_{i=1}^N \\left| \\widehat{w}(x) \\log \\widehat{w}(x) \\right| $. Now, we know that $\\widehat{w}(x) \\le \\frac{M}{m}$ and that the function $|y\\log y|$ has a local maximum whose value is $1/e$. As a consequence, $|\\widehat{w}(x) \\log \\widehat{w}(x)| \\le \\max\\{1/e, M/m\\}$.\n\t\\item $|\\widehat{H} (d \\| d') | \\le  \\frac{1}{N} \\sum_{i=1}^N \\left| \\widehat{w}(x) \\log d'(x) \\right| $. The maximum is attained when both $\\widehat{w}(x)$ and $|\\log d'(x)|$ are maximum. $\\widehat{w}(x) \\le M/m$, while $|\\log d'(x)| \\le \\max\\{-\\log m, \\log M\\}$.\n\t\\item The absolute derivative of $y \\log y$ is $|\\log y + 1|$. Consider the term $\\widehat{w}(x_i) \\log \\widehat{w}(x_i)$, we know that $m/M \\le \\widehat{w}(x_i) \\le M/m$, therefore the maximum absolute derivative has value $\\max\\{ \\log(M/m)+1, -\\log(m/M) - 1 \\}$. Consider the term $N \\widetilde{w}(x_i) = N \\widehat{w}(x_i)/ \\sum_{i=1}^N \\widehat{w}(x_i) $. We know that $m/M \\le N \\widetilde{w}(x_i) \\le N$, thus the maximum absolute derivative has value $\\max\\{ \\log(N)+1, -\\log(m/M) - 1 \\}$. Since the Lipschitz constant of an average is smaller or equal to the Lipschitz constant of each term, we get the result.\n\t\\item Consider the inequalities:\n\t\\begin{align*}\n\\left| \\widehat{H} (d' \\| d) - \\widetilde{H} (d' \\| d) \\right| &=  \\left| \\frac{1}{N} \\sum_{i=1}^N \\widehat{w}(x_i) r(x_i)  - \\frac{\\sum_{i=1}^N \\widehat{w}(x_i) r(x_i)}{\\sum_{i=1}^N \\widehat{w}(x_i)} \\right| \\\\\n& = \\left| \\frac{\\sum_{i=1}^N \\widehat{w}(x_i) r(x_i)}{\\sum_{i=1}^N \\widehat{w}(x_i)} \\left( \\frac{1}{N} \\sum_{i=1}^N \\widehat{w}(x_i) - 1 \\right) \\right| \\\\\n& \\le r_{\\max} \\left| \\frac{1}{N} \\sum_{i=1}^N \\widehat{w}(x_i) - 1\\right| \n\t\\end{align*}\n\\end{enumerate}\n\\end{proof}\n\nWe report now a standard result of learning theory that we are going to use extensively throughout the analysis~\\cite{mohri2012foundations}.\n\n\\begin{theorem}\n\\label{thr:ermFinite}\n\tLet $\\mathcal{H}$ be a family real-valued functions and let $\\mathcal{G} = \\{ L_h(x) : h \\in \\mathcal{H} \\}$ be the family of loss functions associated to $\\mathcal{H}$. Assume that $\\mathrm{Pdim}(\\mathcal{G}) = v$. and that the loss function $L$ is bounded by $M$.Then, for any $\\delta \\in (0,1)$, with probability at least $1 - \\delta$, the following holds for all $h \\in \\mathcal{H}$:\n\t\\begin{align}\n\t\t& \\ev_X \\left[ L_h(X) \\right] \\le \\frac{1}{N} \\sum_{i=1}^N L_h(x_i) + M \\sqrt{\\frac{8v \\log\\frac{2eN}{v} + 8 \\log \\frac{4}{\\delta}}{N}}. \\\\\n\t\t& \\frac{1}{N} \\sum_{i=1}^N L_h(x_i) \\leq \\ev_X \\left[ L_h(X) \\right] M \\sqrt{\\frac{8v \\log\\frac{2eN}{v} + 8 \\log \\frac{4}{\\delta}}{N}}. \n\t\\end{align}\t\n\\end{theorem}\n\nUsing this result, we immediately derive the following.\n\n\\begin{lemma}\n\\label{lemma:bounds}\n\tEach of these events hold with probability at least $1-\\delta$:\n\t\\begin{description}\n\t\t\\item[$\\displaystyle (\\mathcal{E}_1)$]\n\t\t$ \\forall d \\in \\mathcal{D}_{d^{P,\\pi}}:  \\left| \\frac{1}{N} \\sum_{i=1}^N \\widehat{w}(x_i) - 1 \\right| \\le \\frac{M}{m} \\sqrt{\\frac{8v \\log\\frac{2eN}{v} + 8 \\log \\frac{8}{\\delta}}{N}}\t\n\t\t$;\n\t\t\\item[$\\displaystyle (\\mathcal{E}_1)$]\n\t\t$ \\forall d \\in \\mathcal{D}_{d^{P,\\pi}}: \\left| \\widehat{J}_d - J_d \\right| \\le r_{\\max} \\frac{M}{m} \\sqrt{\\frac{8v \\log\\frac{2eN}{v} + 8 \\log \\frac{8}{\\delta}}{N}}\t\n \t\t$;\n\t\t\\item[$\\displaystyle (\\mathcal{E}_3)$] $\n\t\t  \\forall d \\in \\mathcal{D}_{d^{P,\\pi}}: \\left| \\widehat{D}_{KL}(d \\| d^{P,\\pi}) - D_{KL}(d \\| d^{P,\\pi}) \\right| \\le \\bar{K} \\sqrt{\\frac{8v \\log\\frac{2eN}{v} + 8 \\log \\frac{8}{\\delta}}{N}},$ where $\\bar{K}=\\max \\left\\{ \\frac{1}{e}, \\frac{M}{m} \\log \\frac{M}{m} \\right\\}$;\n\t\t\\item[$\\displaystyle (\\mathcal{E}_4)$] $\\forall d \\in \\mathcal{D}_{d^{P,\\pi}}, \\forall d' \\in \\mathcal{D}_{\\mathcal{P},\\Pi}: \\quad \\left| \\widehat{H}(d' \\| d) - H (d' \\| d) \\right| \\le \\frac{M}{m} \\bar{M} \\sqrt{\\frac{8v \\log\\frac{2eN}{v} + 8 \\log \\frac{8}{\\delta}}{N}}$, where $\\bar{M}= \\max \\left\\{ -\\log m, \\log M \\right\\}$.\n\t\\end{description}\n\\end{lemma}\n\n\\begin{proof}\n\tIt is a trivial application of Theorem~\\ref{thr:ermFinite} after symmetrization, by carefully defining the max of each function involved and exploiting Assumption~\\ref{ass:dim}.\n\\end{proof}\n\nWe can now put all together.\n\n\\begin{theorem}[Finite--Sample Bound under Assumption \\ref{ass:finite}]\n\tLet $\\pi \\in \\Pi$ and $P \\in \\mathcal{P}$ be the current policy and transition model respectively. Let $\\epsilon > 0$ be the KL--divergence constraint. Let $d \\in \\mathcal{D}_{d^{P,\\pi}}$ be the solution of the $OPT_{P,\\pi}(\\epsilon)$ problem and $\\widetilde{d}' \\in \\mathcal{D}_{\\mathcal{P}, \\Pi}$ be the solution of the \\rempskappahat{\\epsilon} problem computed with $N>0$ samples collected with $d^{P,\\pi}$. Then, under Assumptions~\\ref{ass:reward}, \\ref{ass:dim} and~\\ref{ass:finite}, there exists a constant $\\phi$ and function $\\psi(N) = \\mathcal{O} \\left( \\log N \\right)$, such that for any $\\delta \\in (0,1)$, with probability at least $1-4\\delta$ it holds that:\n\t\\begin{align*}\n\t\tJ_{d} - J_{\\widetilde{d}'} \\le & \\sqrt{2} r_{\\max} \\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}}  \\inf_{\\overline{d} \\in \\mathcal{D}_{\\mathcal{P},\\Pi}} \\sqrt{D_{KL}( d \\| \\overline{d})} +\\\\&\n\t\t+ r_{\\max} \\phi \\sqrt[4]{\\frac{8v \\log\\frac{2eN}{v} + 8 \\log \\frac{8}{\\delta}}{N}} + \\\\&\n\t\t+  r_{\\max} \\psi(N) \\sqrt{\\frac{8v \\log\\frac{2eN}{v} + 8 \\log \\frac{8}{\\delta}}{N}}.\n\t\\end{align*}\n\\end{theorem}\n\n\\begin{proof}\n\tWe start from Theorem~\\ref{thr:decomposition} and we bound each term using Lemma~\\ref{lemma:max} and Lemma~\\ref{lemma:bounds}. Let us start with $\\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}} | J_d - \\widetilde{J}_d |$:\n\t\\begin{align*}\n\t\t\\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}} | J_d - \\widetilde{J}_d | & = \\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}} | J_d - \\widetilde{J}_d \\pm \\widehat{J}_d| \\\\\n\t\t& \\le \\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}} | J_d - \\widehat{J}_d | + \\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}} | \\widehat{J}_d - \\widetilde{J}_d |\\\\\n\t\t& \\le \\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}} | J_d - \\widehat{J}_d | + r_{\\max} \\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}}  \\left| \\frac{1}{N} \\sum_{i=1}^N \\widehat{w}(x_i) - 1  \\right| \\\\\n\t\t& \\le 2r_{\\max} \\frac{M}{m} \\sqrt{\\frac{8v \\log\\frac{2eN}{v} + 8 \\log \\frac{8}{\\delta}}{N}},\n\t\\end{align*}\n\twhere we exploited events $(\\mathcal{E}_1)$ and $(\\mathcal{E}_2)$. Consider $\\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}} \\left| {\\widetilde{D}}_{KL}(d \\|d^{P,\\pi})- D_{KL}(d \\|d^{P,\\pi})\\right|$:\n\t\\begin{align*}\n\t\t\\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}} \\left| {\\widetilde{D}}_{KL}(d \\|d^{P,\\pi})- D_{KL}(d \\|d^{P,\\pi})\\right| & = \\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}} \\left| {\\widetilde{D}}_{KL}(d \\|d^{P,\\pi})- D_{KL}(d \\|d^{P,\\pi}) \\pm {\\widehat{D}}_{KL}(d \\|d^{P,\\pi})\\right| \\\\\n\t\t& \\le \\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}} \\left| {{D}}_{KL}(d \\|d^{P,\\pi})- {\\widehat{D}}_{KL}(d \\|d^{P,\\pi})\\right| + \\\\ & \\quad + \\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}} \\left| {\\widetilde{D}}_{KL}(d \\|d^{P,\\pi})- {\\widehat{D}}_{KL}(d \\|d^{P,\\pi})\\right| \\\\\n\t\t& \\le \\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}} \\left| {{D}}_{KL}(d \\|d^{P,\\pi})- {\\widehat{D}}_{KL}(d \\|d^{P,\\pi})\\right| \\\\\n\t\t& \\quad + \\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}} \\Upsilon(M,m,N) \\left| \\frac{1}{N} \\sum_{i=1}^N \\widehat{w}(x_i)- 1 \\right| \\\\\n\t\t& \\le \\left( \\max \\left\\{ \\frac{1}{e}, \\frac{M}{m} \\log \\frac{M}{m} \\right\\} + \\Upsilon(M,m,N) \\right) \\sqrt{\\frac{8v \\log\\frac{2eN}{v} + 8 \\log \\frac{8}{\\delta}}{N}} \\\\\n\t\t& \\le f(N) \\sqrt{\\frac{8v \\log\\frac{2eN}{v} + 8 \\log \\frac{8}{\\delta}}{N}},\n\t\\end{align*}\n\twhere we defined $\\Upsilon(M,m,N) = \\max\\left\\{ \\log \\frac{M}{m} + 1,  -\\log \\frac{m}{M} - 1, \\log N + 1 \\right\\}$, \\newline $f(N) = \\left( \\max \\left\\{ \\frac{1}{e}, \\frac{M}{m} \\log \\frac{M}{m} \\right\\} + \\Upsilon(M,m,N) \\right)$ and we exploited events $(\\mathcal{E}_1)$ and $(\\mathcal{E}_3)$. Finally, the term $\\sup_{d \\in \\mathcal{D}^{d^{P,\\pi}}} \\sup_{d' \\in \\mathcal{D}_{\\Pi,\\mathcal{P}}} \\left| \\widehat{H} (d \\| d') -  H(d \\| d') \\right|$ can be bounded using Lemma \\ref{lemma:bounds}. Let us define $c=\\frac{M}{m} \\max\\{-\\log m, \\log M \\}$ and $\\nu=\\sqrt{\\frac{8v \\log\\frac{2eN}{v} + 8 \\log \\frac{8}{\\delta}}{N}}$ and we put all together obtaining:\n\t\\begin{align*}\n\t\tJ_{d} - J_{\\widetilde{d}'} & \\le 4 r_{\\max} \\nu + \\frac{2 r_{\\max}}{\\epsilon} f(N) \\nu + r_{\\max} \\sqrt{2}  \\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}}  \\inf_{\\overline{d} \\in \\mathcal{D}_{\\mathcal{P},\\Pi}} \\sqrt{D_{KL}( d \\| \\overline{d})} + r_{\\max} \\sqrt{2c \\nu} \\\\\n\t\t& =  r_{\\max} \\sqrt{2}  \\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}}  \\inf_{\\overline{d} \\in \\mathcal{D}_{\\Pi,\\mathcal{P}}} \\sqrt{D_{KL}( d \\| \\overline{d})}  + r_{\\max} \\sqrt{\\nu} \\left( \\left( 4 + \\frac{2}{\\nu} f(N) \\right) \\sqrt{\\nu} + \\sqrt{2c} \\right) \\\\\n\t\t& =  r_{\\max} \\sqrt{2}  \\sup_{d \\in \\mathcal{D}_{d^{P,\\pi}}}  \\inf_{\\overline{d} \\in \\mathcal{D}_{\\Pi,\\mathcal{P}}} \\sqrt{D_{KL}( d \\| \\overline{d})}  + r_{\\max} \\phi \\sqrt{\\nu} + r_{\\max} \\psi_{\\epsilon}(N) \\nu,\n\t\\end{align*}\n\twhere we renamed $\\psi_{\\epsilon}(N) = 4 + \\frac{2}{\\epsilon} f(N)$ and $\\phi = \\sqrt{2c}$. Notice that $\\psi_{\\epsilon}(N) = \\mathcal{O}(\\log N)$. Since we made a union bound over the events  $(\\mathcal{E}_1)$,  $(\\mathcal{E}_2)$,  $(\\mathcal{E}_3)$ and  $(\\mathcal{E}_4)$, the statement holds with probability $1-4\\delta$.\n\\end{proof}", "meta": {"hexsha": "c3223d86a947fd839a2b99c81e0dfa404c03093b", "size": 84301, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/capitolo4.tex", "max_stars_repo_name": "EmanueleGhelfi/thesis-remps-cmdp", "max_stars_repo_head_hexsha": "1b512b1684cfa6c8bac9a513b7f0f2e9cbc1eed5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thesis/capitolo4.tex", "max_issues_repo_name": "EmanueleGhelfi/thesis-remps-cmdp", "max_issues_repo_head_hexsha": "1b512b1684cfa6c8bac9a513b7f0f2e9cbc1eed5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis/capitolo4.tex", "max_forks_repo_name": "EmanueleGhelfi/thesis-remps-cmdp", "max_forks_repo_head_hexsha": "1b512b1684cfa6c8bac9a513b7f0f2e9cbc1eed5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 96.4542334096, "max_line_length": 1075, "alphanum_fraction": 0.6621629637, "num_tokens": 29930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.31234891060511166}}
{"text": "%\\documentstyle[6001]{article}\n% Document Type: LaTeX\n% Master File: ps3rsa.tex\n\n%Warning: This was Latex'ed on a Mac in order to include the figures\n% this next is to generate figures on the Mac\n\n%\\def\\picture here\n\n\\def\\picture #1 by #2 (#3){\n  $${\\vbox to #2{\n    \\hrule width #1 height 0pt depth 0pt\n    \\vfill\n    \\special{picture #3} % this is the low-level interface\n    }}$$\n  }\n\\input ../6001mac\n%\\input /zu/u6001/6001mac\n%\\input /b/meyer/6001/94-dir/pub-dir-F94/6001mac\n\n\\let\\to\\rightarrow\n\\let\\union\\cup\n\\let\\cross\\times\n\\def\\SN{\\mbox{Sch-\\-Num}}\n\\def\\SB{\\mbox{Sch-Bool}}\n\\def\\Empty{\\mbox{Empty}}\n\\def\\SI{\\mbox{Sch-Int}}\n\\def\\SNI{\\mbox{Sch-Nonneg-Int}}\n\\def\\CRV{\\mbox{Curve}}\n\\def\\UI{\\mbox{Unit-Interval}}\n\\def\\PT{\\mbox{Point}}\n\\def\\UT{\\mbox{Curve-Transform}}\n\\def\\BT{\\mbox{Binary-Transform}}\n\n\\def\\fbox#1{%\n  \\vtop{\\vbox{\\hrule%\n     \\hbox{\\vrule\\kern3pt%\n \\vtop{\\vbox{\\kern3pt#1}\\kern3pt}%\n \\kern3pt\\vrule}}% \n \\hrule}}\n\n\n\n\\begin{document} \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\psetheader{SAMPLE} {Graphing Problem Set}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\begin{center}\\large\n{\\bf Graphing with Higher-order Procedures}\n\\end{center}\n\n\\medskip\n\nOne of the things that makes Scheme different from other common\nprogramming languages is the ability to operate with {\\em higher-order\nprocedures}, namely, procedures that manipulate and generate other\nprocedures.  This problem set will give you extensive practice with\nhigher-order procedures, in the context of a language for graphing\ntwo-dimensional curves and other shapes.  Sections 1 and 2 give some\nbackground on the essential ideas, with exercises included.\nSection 3, the actual programming assignment, describes the graphics\nlanguage and gives applications to generating fractal designs.  There\nis also an optional design problem.\n\n\n\\section{1. Procedure Types and Procedure Constructors}\n\nIn this assignment we use many procedures which may be applied to many\ndifferent types of arguments and may return different types of values.  To\nkeep track of this, it will be helpful to have some simple notation to\ndescribe types of Scheme values.\n\nTwo basic types of values are \\SN, the Scheme numbers such as 3,\n-4.2, 6.931479453e89, and \\SB, the truth values {\\tt \\#t,\\#f}.\nThe procedure {\\tt square} may be applied to a \\SN\\ and will return\nanother \\SN.  We indicate this with the notation:\n\\[{\\tt square} : \\SN \\to \\SN \\]\n\nIf {\\tt f} and {\\tt g}  are procedures of type $\\SN \\to \\SN$, then we may\n{\\em compose} them:\n\n\\beginlisp\n(define (compose f g)\n  (lambda (x)\n    (f (g x))))\n\\endlisp\n\n\\noindent\nThus, for example {\\tt (compose square log)} is the procedure of type $\\SN\n\\to \\SN$ that returns the square of the logarithm of its argument, while\n{\\tt (compose log square)} returns the logarithm of the square of its\nargument:\n\n\\beginlisp\n(log 2)\n;Value: .6931471805599453\n\\null\n((compose square log) 2)\n;Value: .4804530139182014\n\\null\n((compose log square) 2)\n;Value: 1.3862943611198906\n\\endlisp\n\n\\noindent\nAs we have used it above, the procedure {\\tt compose} takes as arguments\ntwo procedures of type $F = \\SN \\to \\SN$, and returns another such\nprocedure.  We indicate this with the notation:\n\\[{\\tt compose} : (F, F) \\to F\\]\n\nJust as squaring a number multiplies the number by itself, {\\tt thrice} of\na function composes the function three times.  That is, {\\tt ((thrice f)\nn)} will return the same number as {\\tt (f(f(f n)))}:\n\n\\beginlisp\n(define (thrice f)\n  (compose (compose f f) f))\n\\null\n((thrice square) 3)\n;Value: 6561\n\\null\n(square (square (square 3)))\n;Value: 6561\n\\endlisp\n\nAs used above, {\\tt thrice} is of type $(F \\to F)$.  That is, it takes as\ninput a function from numbers to numbers and returns the same kind of\nfunction.  But {\\tt thrice} will actually work for other kinds of input\nfunctions.  It is enough for the input function to have a type of the form\n$T\\to T$, where $T$ may be any type.  So more generally, we can write\n\\[\\hbox{\\tt thrice} : (T\\to T) \\to (T\\to T) \\]\n\nComposition, like multiplication, may be iterated.  Consider \nthe following:\n\n\\beginlisp\n(define (identity x) x)\n\\null\n(define (repeated f n)\n  (if (= n 0)\n      identity\n      (compose f (repeated f (- n 1)))))\n\n\\null\n\n((repeated sin 5) 3.1)\n;Value: 4.1532801333692235e-2\n\n\\null\n\n(sin(sin(sin(sin(sin 3.1)))))\n;Value: 4.1532801333692235e-2\n\\endlisp\n\n\\[\\hbox{\\tt repeated} : ((T\\to T),\\SNI) \\to (T\\to T)\\]\n\n\\paragraph{Exercise 1.A} The type of {\\tt thrice} is of the form\n$(T'\\to T')$ (where $T'$ happens to equal $(T\\to T)$), so we can\nlegitimately use {\\tt thrice} as an input to {\\tt thrice}!\n\nFor what value of {\\tt n} will {\\tt (((thrice thrice) f) 0)} return the\nsame value\\footnote{``Sameness'' of procedure values is a sticky issue\nwhich we don't want to get into here.  We can avoid it by assuming that\n{\\tt f} is bound to a value of type $F$, so evaluation of {\\tt (((thrice\nthrice) f) 0)} will return a number.} as {\\tt ((repeated f n) 0)}?\n\nSee if you can now predict what will happen when the following expressions\nare evaluated.  Briefly explain what goes on in each case.\n\\begin{enumerate}\n\\item {\\tt (((thrice thrice) 1+) 6)}\n\\item {\\tt (((thrice thrice) identity) compose)}\n\\item {\\tt (((thrice thrice) square) 1)}\n\\item {\\tt (((thrice thrice) square) 2)}.\n\\end{enumerate}\n\n\\paragraph{Exercise 1.B}  Test your predictions.  ({\\bf Warning}:\nBefore you do this, make sure you understand how to {\\em interrupt} a \nScheme evaluation.)\n\n\\section{2. Curves as Procedures and Data}\n\nWe're going to develop a language for defining and drawing planar curves.\nWe'd like to plot points, construct graphs of functions, transform curves\nby scaling and rotating, and so on.  One of the key ideas that we'll\nstress throughout 6.001 is that a well-designed language has parts that\ncombine to make new parts that themselves can be combined.  This property\nis called {\\em closure}.\n\nA planar curve in ``parametric form'' can be described mathematically as a\nfunction from parameter values to points in the plane.  For example, we\ncould describe the {\\em unit-circle} as the function taking $t$ to $(\\cos\n2 \\pi t, \\sin 2 \\pi t)$ where $t$ ranges over the unit interval $[0,1]$.  In Scheme,\nwe let \\UI\\ be the type of Scheme-numbers between 0 and 1, and we\nrepresent curves by procedures of Scheme type \\CRV, where\n\\[\\CRV = \\UI\\to \\PT\\]\nand \\PT\\ is some representation of pairs of \\SN's.\n\nTo work with \\PT, we need a {\\em constructor}, {\\tt make-point}, which\nconstructs \\PT's from \\SN's, and {\\em selectors}, {\\tt x-of} and {\\tt y-of},\nfor getting the $x$ and $y$ coordinates of a \\PT.  We require only that\nthe constructors and selectors obey the rules\n\\begin{eqnarray*}\n(\\hbox{\\tt x-of}\\, (\\hbox{\\tt make-point}\\, n\\, m)) & = & n\\\\\n(\\hbox{\\tt y-of}\\, (\\hbox{\\tt make-point}\\, n\\, m)) & = & m\n\\end{eqnarray*}\nfor all \\SN's $m,n$.  Here is one way to do this (we'll learn several\nother, better ways, in two weeks.)\n\n\\beginlisp\n(define (make-point x y)\n  (lambda (bit)\n    (if (zero? bit) x y)))\n\\null\n(define (x-of point)\n  (point 0))\n\\null\n(define (y-of point)\n  (point 1))\n\\endlisp\n\n\\begin{eqnarray*}\n\\hbox{\\tt make-point} & : & (\\SN,\\SN) \\to \\PT,\\\\\n\\hbox{\\tt x-of}, \\hbox{\\tt y-of} & : & \\PT\\to \\SN.\n\\end{eqnarray*}\n\nFor example, we can define the \\CRV\\ {\\tt unit-circle} and the \\CRV\\ {\\tt\nunit-line} (along the $x$-axis):\n\n\\beginlisp\n(define (unit-circle t)\n  (make-point (sin (* 2pi t))\n              (cos (* 2pi t))))\n\\null\n(define (unit-line-at y)\n  (lambda (t) (make-point t y)))\n\\null\n(define unit-line (unit-line-at 0))\n\n\\endlisp\n\n\\paragraph{Exercise 2:}\n\n\\begin{enumerate}\n\\item What is the type of {\\tt unit-line-at}?\n\n\\item Define a procedure {\\tt vertical-line} with two arguments, a point and a\nlength, and returns a vertical line of that length beginning at the point.\n\n\\item What is the type of {\\tt vertical-line}?\n\n\\end{enumerate}\n\\medskip\n\nIn addition to the direct construction of \\CRV's such as {\\tt unit-circle}\nor {\\tt unit-line}, we can use elementary Cartesian geometry in designing\nScheme procedures which {\\em operate} on \\CRV's.  For example, the mapping\n$(x,y)\\longrightarrow (-y,x)$ rotates the plane by $\\pi/2$, so\n\n\\beginlisp\n(define (rotate-pi/2 curve)\n  (lambda (t)\n    (let ((ct (curve t)))\n      (make-point\n       (- (y-of ct))\n       (x-of ct)))))\n\\endlisp\ndefines a procedure which takes a curve and transforms it into another,\nrotated, curve.  The type of {\\tt rotate-pi/2} is\n\\[\\UT = \\CRV \\to \\CRV.\\]\n\n\\paragraph{Exercise 3:}\nWrite a definition of a \\UT\\ {\\tt reflect-through-y-axis}, which turns a\ncurve into its mirror image.\n\n\\medskip\n\nWe have provided a variety of other procedure \\UT's and procedures which\nconstruct \\UT's in the file {\\tt curves.scm}.  For example,\n\\begin{itemize}\n\n\\item \n{\\tt translate} returns a \\UT\\ which rigidly moves a curve given distances\nalong the $x$ and $y$ axes,\n\n\\item {\\tt scale-x-y}\nreturns a \\UT\\ which stretches a curve along the $x$ and $y$ coordinates\nby given scale factors, and\n\n\\item {\\tt rotate-around-origin}\nreturns a \\UT\\ which rotates a curve by a given number of radians.\n\n\\end{itemize}\nA convenient, if somewhat more complicated, \\UT\\ is {\\tt\nput-in-standard-position}.  We'll say a curve is in {\\em standard\nposition} if its start and end points are the same as the unit-line,\nnamely it starts at the origin, $(0,0)$, and ends at the point $(1,0)$.\nWe can put any curve whose start and endpoints are not the same into\nstandard position by rigidly translating it so its starting point is at\nthe origin, then rotating it about the origin to put its endpoint on the\n$x$ axis, then scaling it to put the endpoint at $(1,0)$:\n\n\\beginlisp\n(define (put-in-standard-position curve)\n  (let* ((start-point (curve 0))\n         (curve-started-at-origin\n          ((translate (- (x-of start-point))\n                      (- (y-of start-point)))\n           curve))\n         (new-end-point (curve-started-at-origin 1))\n         (theta (atan (y-of new-end-point) (x-of new-end-point)))\n         (curve-ended-at-x-axis\n          ((rotate-around-origin (- theta)) curve-started-at-origin))\n         (end-point-on-x-axis (x-of (curve-ended-at-x-axis 1))))\n    ((scale (/ 1 end-point-on-x-axis)) curve-ended-at-x-axis)))\n\\endlisp\n\nIt is useful to have operations which combine curves into new ones.  We\nlet \\BT\\ be the type of binary operations on curves, \\[\\BT =\n(\\CRV,\\CRV)\\to \\CRV.\\] The procedure {\\tt connect-rigidly} is a simple\n\\BT.  Evaluation of {\\tt (connect-rigidly curve1 curve2)} returns a curve\nconsisting of {\\tt curve1} followed by {\\tt curve2}; the starting point of\nthe curve returned by {\\tt (connect-rigidly curve1 curve2)} is the same as\nthat of {\\tt curve1} and the end point is the same as that of {\\tt\ncurve2}.\n\n\\beginlisp\n(define (connect-rigidly curve1 curve2)\n  (lambda (t) \n    (if (< t (/ 1 2))\n        (curve1 (* 2 t))\n        (curve2 (- (* 2 t) 1)))))\n\\endlisp\n\n\\paragraph{Exercise 4:} There is another, possibly more\nnatural, way of connecting curves.  The curve returned by {\\tt\n(connect-ends curve1 curve2)} consists of a copy of {\\tt curve1}\nfollwed by a copy of {\\tt curve2} after it has been rigidly translated\nso its starting point coincides with the end point of {\\tt curve1}.\n\nWrite a definition of the \\BT\\ {\\tt connect-ends}.\n\n\\section{3. Drawing Curves}\n\nUse {\\tt M-x load-problem-set} to load the code for problem set 2.  This\nwill create three graphics windows called {\\tt g1}, {\\tt g2} and {\\tt g3}.\nThe window coordinates go from 0 to 1 in both $x$ and $y$ with $(0,0)$ at\nthe lower left.\n\nA {\\em drawing procedure} takes a curve argument and automagically\ndisplays points on the curve in a window\\footnote{{\\em The Hacker's\nDictionary} (see the Jargon file) defines ``automagically'' as\n``automatically, but in a way which, for some reason (typically because it\nis too complicated, or too ugly, or perhaps even too trivial), the speaker\ndoesn't feel like explaining.''  In this case, we don't want to explain\nthe bletcherous (see Jargon) details of how points are plotted.}.  We've\nprovided several procedures that take a window (for example {\\tt g1}) and\na number of points, and return a drawing procedure, namely,\n\\begin{itemize}\n\\item {\\tt draw-points-on},\n\\item {\\tt draw-connected},\n\\item {\\tt draw-points-squeezed-to-window}, and\n\\item {\\tt draw-connected-squeezed-to-window}.\n\\end{itemize}\n\n\\paragraph{Exercise 5:}\nApply {\\tt (draw-connected g1 200)} to {\\tt unit-circle}, and {\\tt\n(draw-connected g2 200)} to {\\tt alternative-unit-circle}.  Can you see a\ndifference?  Now try using {\\tt draw-points-on} instead of {\\tt\ndraw-connected}.  Also try {\\tt draw-points-squeezed-to-window}.  Print\nout the resulting figures.\n\n\\subsection{Fractal Curves}\n\nTo show off the power of our drawing language, let's use it to explore\nfractal curves.  Fractals have striking mathematical\nproperties.\\footnote{A fractal curve is a ``curve'' which, if you\nexpand any small piece of it, you get something similar to the\noriginal.  The Gosper curve, for example, is neither a true\n1-dimensional curve, nor a 2-dimensional region of the plane, but\nrather something in between.} Fractals have received a lot of\nattention over the past few years, partly because they tend to arise\nin the theory of nonlinear differential equations, but also because\nthey are pretty, and their finite approximations can be easily\ngenerated with recursive computer programs.\n\nFor example, Bill Gosper\\footnote{Bill Gosper is a mathematician now\nliving in California.  He was one of the original hackers who worked\nfor Marvin Minsky in the MIT Artificial Intelligence Laboratory during\nthe '60s.  He is perhaps best known for his work on the Conway Game of\nLife---a set of rules for evolving cellular automata.  Gosper invented\nthe ``glider gun'', resolving Conway's question as to whether it is\npossible to produce a finite pattern that evolves into an unlimited\nnumber of live cells.  He used this result to prove that the Game of\nLife is Turing universal, in that it can be used to simulate any other\ncomputational process!} discovered that the infinite repetition of a\nvery simple process creates a rather beautiful image, now called the\n{\\em Gosper C Curve}.  At each step of this process there is an\napproximation to the Gosper curve.  The next approximation is obtained\nby adjoining two scaled copies of the current approximation, each\nrotated by 45 degrees.\n\nFigure~\\ref{Gosper} shows the first few approximations to the Gosper\ncurve, where we stop after a certain number of levels: a level-0 curve\nis simply a straight line; a level-1 curve consists of two level-0\ncurves; a level 2 curve consists of two level-1 curves, and so on.\nThe figure also illustrates a recursive strategy for making the next\nlevel of approximation: a level-$n$ curve is made from two\nlevel-$(n-1)$ curves, each scaled to be ${\\sqrt 2}/2$ times the length\nof the original curve.  One of the component curves is rotated by\n$\\pi/4$ (45 degrees) and the other is rotated by $-\\pi/4$.  After each\npiece is scaled and rotated, it must be translated so that the ending\npoint of the first piece is continuous with the starting point of the\nsecond piece.\n\nWe assume that the approximation we are given to improve (named {\\tt\ncurve} in the procedure) is in standard position.  By doing some\ngeometry, you can figure out that the second curve, after being scaled\nand rotated, must be translated right by .5 and up by .5, so its beginning\ncoincides with the endpoint of the rotated, scaled first curve.  This leads\nto the \\UT\\ {\\tt gosperize}:\n\n%\\label{Gosper} here\n\n\\begin{figure}\n\\picture 4.50 in by 2.54 in (C-curve)\n\\caption{{\\protect\\footnotesize\nExamples of the Gosper C curve at various levels, and \nthe recursive transformation that produces each level from the previous\nlevel.}}\n\\label{Gosper}\n\\end{figure}\n\n\\beginlisp\n(define (gosperize curve)\n  (let ((scaled-curve ((scale (/ (sqrt 2) 2)) curve)))\n    (connect-rigidly ((rotate-around-origin (/ pi 4)) scaled-curve)\n                     ((translate .5 .5)\n                      ((rotate-around-origin (/ -pi 4)) scaled-curve)))))\n\\endlisp\n\nNow we can generate approximations at any level to the Gosper curve by\nrepeatedly gosperizing the unit line,\n\n\\beginlisp\n(define (gosper-curve level)\n    ((repeated gosperize level) unit-line))\n\\endlisp\n\nTo look at the level {\\tt level} gosper curve, evaluate {\\tt\n(show-connected-gosper level)}:\n\n\\beginlisp\n(define (show-connected-gosper level)\n  ((draw-connected g1 200)\n   ((squeeze-rectangular-portion -.5 1.5 -.5 1.5)\n    (gosper-curve level))))\n\\endlisp\n\n\\paragraph{Exercise 6.A} Define a procedure {\\tt show-points-gosper}\nsuch that evaluation of\n\n\\beginlisp\n(show-points-gosper window level number-of-points initial-curve)\n\\endlisp\n\n\\noindent\nwill plot {\\tt number-of-points} unconnected points of the level {\\tt\nlevel} gosper curve in {\\tt window}, but starting the gosper-curve\napproximation with an arbitrary {\\tt initial-curve} rather than the unit\nline.  For instance,\n\n\\beginlisp\n(show-points-gosper g1 level 200 unit-line)\n\\endlisp\n\n\\noindent should display the same points as {\\tt\n(show-connected-gosper level)}, but without connecting them.  But you\nshould also be able to use your procedure with arbitrary curves.  (You can\nfind the description of procedure {\\tt squeeze-rectangular-portion} in the\nfile {\\tt curves.scm}; you don't need to understand it in detail to do\nthis exercise.)\n\n\\paragraph{Exercise 6.B}\nTry gosperizing the arc of the unit circle running from 0 to $\\pi$.  Find\nsome examples that produce interesting designs.  (You may also want to\nchange the scale in the plotting window and the density of points\nplotted.)\\footnote{One of the things you should notice is that, for larger\nvalues of $n$, all of these curves look pretty much the same.  As with\nmany fractal curves, the shape of the Gosper curve is determined by the\nGosper process itself, rather than the particular shape we use as a\nstarting point.  In a sense that can be made mathematically precise, the\n``infinite level'' Gosper curve is a fixed point of the Gosper process,\nand repeated applications of the process will converge to this fixed\npoint.}\n\n\\medskip\n\nThe Gosper fractals we have been playing with have had the angle of\nrotation fixed at 45 degrees. This angle need not be fixed.  It need not\neven be the same for every step of the process.  Many interesting shapes\ncan be created by changing the angle from step to step.\n\nWe can define a procedure {\\tt param-gosper} that generates Gosper curves\nwith changing angles.  {\\tt Param-gosper} takes a level number (the number\nof levels to repeat the process) and a second argument called {\\tt\nangle-at}. The procedure {\\tt angle-at} should take one argument, the level\nnumber, and return an angle (measured in radians) as its answer\n\\[\\hbox{\\tt angle-at} : \\SNI \\to \\SN.\\]\nProcedure {\\tt param-gosper} can use this to calculate the angle to be\nused at each step of the recursion.\n\n\\beginlisp\n(define (param-gosper level angle-at)\n  (if (= level 0)\n      unit-line\n      ((param-gosperize (angle-at level))\n       (param-gosper (- level 1) angle-at))))\n\\endlisp\n\n\nThe procedure {\\tt param-gosperize} is almost like {\\tt gosperize}, except\nthat it takes an another argument, the angle of rotation, and implements\nthe process shown in figure~\\ref{param-geo}:\n        \n\\beginlisp        \n(define (param-gosperize theta)\n  (lambda (curve)\n    (let ((scale-factor (/ (/ 1 (cos theta)) 2)))\n      (let ((scaled-curve ((scale scale-factor) curve)))\n        (connect-rigidly ((rotate-around-origin theta) scaled-curve)\n                         ((translate .5 (* (sin theta) scale-factor))\n                          ((rotate-around-origin (- theta)) scaled-curve)))))))\n\\endlisp\n\n% \\label{param-geo} here\n\\begin{figure}\n\\picture 4.14 in by 1.69 in (Param-geo)\n\\caption{{\\protect\\footnotesize\nA parameterized version of the Gosper process, where the\nangle can vary.  Note that the endpoints of the transformed figure\nshould be the same as the endpoints of the original figure, and\nthe interior endpoints should match.}}\n\\label{param-geo}\n\\end{figure}\n\n\nFor example, the ordinary Gosper curve at level {\\tt level} is returned by\n\n\\beginlisp\n(param-gosper level (lambda (level) pi/4))\n\\endlisp\n\n\\paragraph{Exercise 7.A}  Designing {\\tt param-gosperize} required\nusing some elementary trigonometry to figure out how to shift the pieces\naround so that they fit together after scaling and rotating.  It's easier\nto program if we let the computer figure out how to do the shifting.  Show\nhow to redefine {\\tt param-gosperize} using the procedures {\\tt\nput-in-standard-position} and {\\tt connect-ends} from Exercise 4 to handle\nthe trigonometry.  Your definition should be of the form\n\n\\beginlisp\n(define (param-gosperize theta)\n  (lambda (curve)\n    (put-in-standard-position\n      (connect-ends\n        ...\n        ...))))\n\\endlisp\n\n\n\\paragraph{Exercise 7.B}\nGenerate some parameterized Gosper curves where the angle changes with the\nlevel $n$.  We suggest starting with $\\pi/(n+2)$ and $\\pi/(1.3^n)$.\nSubmit sample printouts with your problem solutions.\n\n\\paragraph{Exercise 7.C}\nWe now have three procedures to compute gosper curves: {\\tt gosper-curve},\nand {\\tt param-gosper} with argument {\\tt (lambda (level) (/ pi 4)))}\nusing the ``hand-crafted'' definition of {\\tt param-gosperize} above, or\nusing your version of {\\tt param-gosperize} in 7.A based on {\\tt\nput-in-standard-position}.  Compare the speed of these procedures for\ncomputing selected points on the curve at a few levels.  Is there a speed\nadvantage for the more customized procedures?\n\nThe procedure {\\tt show-time} will report the time in milliseconds\nrequired to evaluate a procedure of no arguments (a ``thunk'').  For\nexample, evaluating\n\n\\beginlisp\n(show-time (lambda () ((gosper-curve 10) .1))\n\\endlisp\nwill print out the time to compute the point at .1 on the level 10 gosper-curve.\n\n\\medskip\n\n\\paragraph{Exercise 8.A}\nBen Bitdiddle isn't entirely happy with the style of several of the Scheme\ndefinitions on this problem set. In particular, he feels the code goes\noverboard in inventing names for values that are used infrequently, and\nthis lengthens the code and burdens someone reading the code with\nremembering the invented names.  For example, Ben thinks the definition\n\n\\beginlisp\n(define (rotate-around-origin theta)\n  (let ((cth (cos theta))\n        (sth (sin theta)))\n    (lambda (curve)\n      (lambda (t)\n        (let ((ct (curve t)))      ;Ben eliminates the declaration of ct\n          (let ((x (x-of ct))\n                (y (y-of ct)))\n            (make-point\n             (- (* cth x) (* sth y))\n             (+ (* sth x) (* cth y)))))))))\n\\endlisp\n\nwould be a bit more readable if the name {\\tt ct} for the value of {\\tt\n(curve t)} was dropped.  He proposes instead:\n\n\\beginlisp\n(define (bens-rotate theta)\n  (let ((cth (cos theta))\n        (sth (sin theta)))\n    (lambda (curve)\n      (lambda (t)\n        (let ((x (x-of (curve t)))      ;Ben writes (curve t)\n              (y (y-of (curve t))))     ;twice\n          (make-point\n           (- (* cth x) (* sth y))\n           (+ (* sth x) (* cth y))))))))\n\\endlisp\n\nIs Ben's definition correct?\n\nAlyssa P. Hacker warns Ben that the {\\tt let} declarations are more\nsignificant computationally than mere abbreviations.  Briefly explain why\nusing {\\tt bens-rotate} as a subprocedure in place of the original {\\tt\nrotate-around-origin} in the definition of {\\tt gosper-curve} will turn a\nprocess whose time is linear in the level into one which is exponential in\nthe level.\n\n\\paragraph{Exercise 8.B}\nLook up the online documentation of the {\\tt trace-entry} procedure in the\nScheme Users Manual.  Trace {\\tt x-of} to show how dramatically Alyssa's\nwarning is confirmed when computing points on the gosper curve using {\\tt\nbens-rotate} as a subprocedure in place of the original {\\tt\nrotate-around-origin}.  Turn in a table summarizing the number of calls to\n{\\tt x-of} by {\\tt gosper-curve} using the two different rotating\nprocedures at four or five illustrative levels.  (A simple way to switch\nto use of {\\tt bens-rotate} in place of {\\tt rotate-around-origin} is to\nevaluate\n\n\\beginlisp\n(define rotate-around-origin bens-rotate)\n\\endlisp\nOf course, you had better save the procedure {\\tt rotate-around-origin}\nunder some other name so you can restore it.  Otherwise, you may have to\nreload the problem set.)\n\n\\medskip\n\nWe can now invent other schemes like the Gosper process, and use them\nto generate fractal curves.\n\n\\paragraph{Exercise 9.A}  The {\\em Koch curve} is produced by a\nprocess similar to the Gosper curve, as shown in figure~\\ref{Koch}.\nWrite a procedure {\\tt kochize} that generates Koch curves.\n% \\label{Koch} here\n\n\\begin{figure}\n\\picture 5.15 in by 1.85 in (Koch)\n\\caption{{\\protect\\footnotesize\nThe Koch at various levels, and a ``snowflake'' curve formed from\nthree Koch curves.  As with the C curve, each level approximation\nto the Koch curve is obtained by\napplying the a transformation to the previous level.}}\n\\label{Koch}\n\\end{figure}\n\n(Teaser: You can generate the Koch curve by using {\\tt param-gosper} with\nan appropriate argument.  Can you find this?)\n\n\n\\paragraph{Exercise 9.B} Print some pictures of your Koch curve at\nvarious levels.\n\n\\paragraph{Exercise 10 (Optional)}\n\nYou now have a lot of elements to work with: scaling, rotation,\ntranslation, curve plotting, Gosper processes, Koch processes, and\ngeneralizations.  For example, you can easily generalize the\nparameterized Gosper process to start with something other than an\nhorizontal line.  The Gosper curve is continuous but {\\em nowhere\ndifferentiable}, so it may be interesting to display its derivatives\nat various levels and numbers of points (see the procedure {\\tt\nderiv-t} in the file {\\tt curves.scm}).  Or you can create new fractal\nprocesses.  Or you can combine the results of different processes into\none picture.  Spend some time playing with these ideas to see what you\ncan come up with.\n\n\\end{document}\n\n", "meta": {"hexsha": "8a4cca2042852f894573442b0b2d3d5ace930d13", "size": 26006, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "additional-assignments/ps2/ps2.tex", "max_stars_repo_name": "Buxus/sicp", "max_stars_repo_head_hexsha": "8fbea7e0def60eda5f8b4be7a9d20635de95b4af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "additional-assignments/ps2/ps2.tex", "max_issues_repo_name": "Buxus/sicp", "max_issues_repo_head_hexsha": "8fbea7e0def60eda5f8b4be7a9d20635de95b4af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "additional-assignments/ps2/ps2.tex", "max_forks_repo_name": "Buxus/sicp", "max_forks_repo_head_hexsha": "8fbea7e0def60eda5f8b4be7a9d20635de95b4af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.783592645, "max_line_length": 84, "alphanum_fraction": 0.7142967008, "num_tokens": 7156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.31234891060511166}}
{"text": "Advances in sequencing technologies have enabled novel insights into microbial niche differentiation, from analyzing environmental samples, to understanding human diseases and informing dietary studies.  However, identifying the microbial taxa that differentiate these samples can be challenging. These issues stem from the compositional nature of 16S \\gls{rrna} gene data (or, more generally, taxon or functional gene data), which changes in the relative abundance of one taxon influence the apparent abundance of the others.  Here we acknowledge that inferring properties of individual bacteria is a difficult problem, and instead introduce the concept of balances to infer meaningful properties of sub-communities, rather than properties of individual species.  We show that balances can yield insights about niche differentiation across multiple microbial environments including soil environments and lung sputum. These techniques have the potential to reshape how we carry out future ecological analyses aimed at revealing differences in relative taxonomic abundance across different samples.\n\\section{Introduction}\nThe ultimate goal for many microbial ecologists is to fully characterize niches of microbial organisms and understand interactions among taxa.  An understanding of how microbial communities are affected by environmental conditions could yield insights into microbial interactions and their role in macro-ecological processes, such as nitrogen fixation \\cite{nitrogen_fixation} and acidification \\cite{acidification}. But despite the extraordinary increase in available data brought about by advances in DNA sequencing, characterizing niche differentiation in microbes remains an outstanding problem, partly due to the difficulty of correctly interpreting compositional data.  Broadly speaking, a compositional dataset is represented by relative abundances, or proportions that individually carry no meaning on the absolute abundance of a specific feature (i.e. 20\\% of 100 and 20\\% of 10,000 are very different absolute abundances).  The constraints associated with compositional data are well known, but unfortunately often neglected in microbial ecology, leading to conflicting interpretations and irreproducible analyses \\cite{gloor_epi, fodor_coda} .\\par\n\\begin{figure}[H]\n        \\centering\n        \\includegraphics[width=1\\textwidth]{ch3/Figure1.pdf}\n        \\caption[An explanation of balances and how to interpret them.]\n        {An explanation of balances and how to interpret them. (a, b) A hypothetical scenario where 2 samples of 2 proportions could explain two different scenarios in the environment.  The balance between these 2 proportions is consistent for both scenarios.  (c) The balance of Red and Blue species abundances.  (d) balances of Red and Blue individuals across an environmental variable.  (e, f) The comparison of proportions and balances of two environments in the scenario where the Purple Orange population (i.e. the most right bin) triples. The balances were calculated using the groupings specified by the tree.\\index{SanDiego8}}\n        \\label{figc1}\n\\end{figure}\nWe illustrate an example of this problem in Figure \\ref{figc1}.  In this scenario, there are two species, “Red” and “Blue”. At the first time point, there are 100 Red individuals and 100 Blue individuals (Figure \\ref{figc1}a). At the next time point, the number of Red individuals doubles, yielding 200 Red individuals, and the proportion of Red and Blue individuals becomes 2/3 and 1/3, respectively (Figure \\ref{figc1}b). Suppose that we do not know the true total number of individuals in the given environment, and can only make inferences about the observed proportions -- a common scenario in microbial ecology, where absolute quantification is rarely performed.  In Figure \\ref{figc1}b, the community has the exact same proportions at Time 1 and Time 2 as Figure \\ref{figc1}a; however, instead of the Red individuals doubling at the second time point, the number of Blue individuals is halved (Figure \\ref{figc1}c).\\par\nThis is the problem with compositionality -- based on proportions alone, it is impossible to determine whether the growth or decline of any individual species has truly occurred \\cite{Lovell_David_Muller_Warren_Taylor_Jennifer_Zwart_Alec_Helliwell2010-na}, and the inherent feature of one change in abundance driving abundance changes in another species violates assumptions of independence.  Analyses that rely on such assumptions, as many statistical approaches do, are thus prone to misinterpretation. For example, traditional correlation metrics such as Pearson and Spearman can be misleading when estimating microbe-microbe correlations \\cite{sparcc, proportionality, spiec_easi, weiss_normalization}.  As a result, it becomes a major challenge to specify types of interactions between microbes, such as parasitism, competition, predation or mutualism, as shown in correlations studies in oral, fecal and vaginal samples from the Human Microbiome Project \\cite{faust_microbial_interactions} \\cite{sparcc}.  Even more advanced correlation-detection techniques such as SparCC \\cite{sparcc} and SPIEC-EASI \\cite{spiec_easi}, struggle with this, and typically require additional assumptions such as sparse \\gls{otu} correlations (i.e. few \\gls{otu}s are actually correlated with each other).  Furthermore, interpreting the resulting network is a major challenge, making it difficult to differentiate between true ecological relationships and random processes \\cite{faust_microbial_interactions}.\\par\nThe compositionality problem is also problematic for statistically detecting differentially abundant microbes across environments or between groups — consequently, it is a major barrier to reliably drawing conclusions about realized microbial niches using community sequencing data. Conventional statistical tools such as t-test and Mann-Whitney can incorrectly identify nearly 100\\% of the taxa present in samples to be significantly different across environments (Figure S1), and univariate tests such as t-tests and ZIG \\cite{metagenomeSeq} have been shown to mislabel microbes as significantly different across sample groups up to 60\\% of the time \\cite{ancom}. More advanced tools for differential abundance detection such as (\\gls{ancom}) \\cite{ancom}, are typically designed to control for false-positives and reliably detect differentially abundant species, but require multiple assumptions (i.e. the number of changing microbes across environments is small) and may require complex parameter tuning. To help overcome these issues of compositionality, we explore using the concept of balances, by moving away from inferring changes of individual species to instead inferring changes of microbial sub-communities to study niche differentiation of microbial communities.\\par\n\\section{Concept}\nBalances were first introduced as an exploratory technique in geology \\cite{groups_of_parts, coda_dendrogram}. Fundamentally, they overcome the prhoblem of inferring changes in abundance from compositional data by sidestepping it, and instead inferring changes in the balance between particular subsets of the community. To understand the concept, let us revisit the scenario in Figure \\ref{figc1}a and \\ref{figc1}b.  Instead of examining proportion changes, we can investigate the balance between Red and Blue individuals by taking the log ratio of Red and Blue counts (Figure \\ref{figc1}c).  By looking at the balance of these two species, we avoid incorrectly attempting to infer absolute increases or decreases in their abundances.  Instead, we can focus on the balance of the Red and Blue individuals, and directly infer the transition of dominance between these species.\\par\nThese balances can also be useful for understanding species distributions across different covariates — a key proximate goal of microbial ecology, and one that is both crucial to the larger goal of niche characterization and heavily impacted by problems inherent in compositionality.  In Figure \\ref{figc1}d, the Red individuals tend to exist in the low pH end of the spectrum, while the Blue individuals tend to exist in the high pH end of the spectrum.  A single balance can capture information about the transition from a high relative abundance of Red individuals in low pH environments to a high relative abundance of Blue individuals in high pH environments.  In low pH environments, the balance is positive, since there are proportionally more Red individuals than Blue individuals.  When the Red and Blue individuals are present in roughly equal proportions, the balance is roughly zero, representing a turning point, transitioning from a Red dominated community to a Blue dominated community.  As the pH increases, the balances become increasingly negative, since there are more Blue individuals than Red individuals. This balance effectively encodes for the niche separation of Red and Blue individuals across the pH gradient. \\par\nThis idea of balances can be extended to multiple dimensions — and more than two taxa — using bifurcating trees.  A bifurcating tree can be built relating microbial taxa to each other using any criterion, and balances can be calculated on the internal nodes of the tree from the geometric means of the corresponding sub-trees. The appropriate criterion to build a tree depends on the question at hand.  A phylogenetic tree could be used to investigate evolutionary relationships of microbes \\cite{Silverman2018-ql, Washburne2017-up}, or hierarchical clustering of environmental variables could be used to explore environmental niches of microbes.  To gain more intuition about this, consider Figure \\ref{figc1}e, in which there are five species and 11 individuals. The four balances (internal nodes in the tree) are calculated by taking the log ratio of geometric means of sub-trees, also known as the isometric log ratio (\\gls{ilr}) transform.  The full equation to calculate balances for a single sample is as follows,\n\\begin{equation}\nb_{i}=\\sqrt{\\frac{\\left| i_{L}\\right| \\left| i_{R}\\right|}{\\left| i_{L}\\right|+ \\left| i_{R}\\right|}}log \\frac{g(i_{L})}{g(i_{R})}\n\\end{equation}\nwhere $b_{i}$ is the balance of the at internal node i ,  $i_{L}$, is the set of all species proportions contained in the left sub-tree at internal node i, $i_{R}$,  is the set of all species proportions contained in the right subtree at the internal node  i, g(x),  is the geometric mean of all of the proportions contained in vector $x$, $ \\left| i_{R}\\right|$,  is the number of species contained in  $i_{R}$ , and  $ \\left| i_{L}\\right|$ is the number of species contained in $ i_{L}$ (see Materials and Materials for more details). Following this equation, in Figure \\ref{figc1}f  $b_{1}$ is calculated by taking the log ratio of the Yellow species and the geometric mean of the Red, Green, Blue, and Purple species.  \\par\n It's also important to note that the some of the balances don't impact each other.  For instance, the changes in b4 do not impact the changes in b3, just because these balances don't share any common tips.  This is crucial, because this property allows us to ignore some of the variance of the balances towards the tips of the tree, and focus on the balances closer to the root of the tree.  These balances toward the root of tree capture the most information, since they contain a significant proportion of tree tips.  As a result, these high level balances have the potential to explain large shifts in these microbial communities.  The choice of the tree can allow for analysts to embed prior knowledge into the structure of the tree to test for these large community shifts.\\par\n Here, we will discuss two studies from which novel insights were gained from this application.  While there are many compositionally aware tools available that are designed to identify microbial interactions and abundance fluctuations, we will refrain from benchmarking balances against these tools, as balances answer a conceptually different question.  These analyses are not restricted to analyzing ratios of individual \\gls{otu}s and can be easily extended to analyze ratios of subcommunities.  \\par\n\\section{ Results}\n \\subsection{Case Study \\#1 – Balances of pH-driven subcommunities in soils}\n In this study \\cite{soil_pyro}, 88 soil samples were collected from North and South America, along with many edaphic measurements.  The study reported that there was a strong correlation between pH and species richness, suggesting that pH was a strong driver behind fluctuations in soil microbial communities. Acidobacteria were found to be negatively correlated with pH and Actinobacteria and Bacteroidetes to be positively correlated with pH, while Alpha/Beta/Gammaproteobacteria were not correlated with pH at all.  These correlation analyses are a little misleading, since the pH was correlated with each of the phyla independently.  The problem with this approach is that it does not account for all of the other phyla: similar to the argument made in Figure \\ref{figc1}b, the change in a single phylum could also be explained by correlated changes in all of the other phyla.  Here, the negative correlation between Acidobacteria and pH could also be caused by the positive correlation between Bacteroidetes and pH.  Additionally, we cannot determine whether the Alpha/Beta/Gammaproteobacteria are correlated with pH or not.  Another possibility is that these three phyla could be positively correlated with pH, while Acidobacteria is not correlated with pH.  However, Bacteroidetes may be so strongly correlated with pH that Acidobacteria appears to be negatively correlated with pH, and the other three phyla not correlated with pH at all.  This scenario is one of the infinite possible underlying relationships that can explain these observed correlations. \\par\n \\begin{figure}[H]\n        \\centering\n        \\includegraphics[width=1\\textwidth]{ch3/Figure2.pdf}\n        \\caption[The application of balances on a soil microbial dataset to identify\n          microbial partitioning with respect to pH.]\n        {The application of balances on a soil microbial dataset to identify microbial partitioning with respect to pH.(a) Hierarchical clustering of closed ref \\gls{otu}s based on mean pH. (b) The balance of low pH associated organisms (3.8 $<$ mean pH $<$ 6.7) and high pH associated organisms (6.8 $<$ mean pH $<$ 8.2). (c) Observed \\gls{otu} counts sorted by pH. (d) Predicted \\gls{otu} proportions from ordinary least squares linear regression on balances sorted by pH. The coefficient of determination was 35\\%, showing that 35\\% of the variation in the microbial community abundance data can be predicted by pH alone.\\index{SanDiego8}}\n        \\label{figc2}\n \\end{figure}\n At a first glance, uncovering the true correlations correctly appears to be a hopeless cause.  This is where balances become useful.  Rather than attempting to correlate individual phyla against pH, we will group \\gls{otu}s together according to their difference in mean pH (Figure \\ref{figc2}a), and investigate how these balances of groups changes with respect to pH (See Materials and Methods on hierarchical clustering).  This circumvents the dependence issue noted previously.  We do not need to worry about subgroups within the left and right subtrees of a balance to be influencing each other, due to the independence property shown in Figure \\ref{figc1}ef.  \\par\n The balance concept proves to be a very powerful technique for investigating how these groups of organisms change relative to each other as pH increases.  Recall the cartoon example in Figure \\ref{figc1}d.  If there are two distinct unimodal species distributions, the balance pivots from being weighted by Red in low pH, to being weighted by Blue in high pH.  The exact same phenomenon is occurring here, except there are multiple species on the left end of the balance, and multiple species on the right end of the balance.\\par\n As shown in Figure \\ref{figc2}b, there is a well defined trend of low pH \\gls{otu}s (3.8 $<$ mean pH $<$ 6.6) gradually being overtaken by high pH \\gls{otu}s (6.7 $<$ mean pH $<$ 8.2) as the pH increases, forming a nice linear trend defined by the top balance in the tree shown in Figure \\ref{figc2}a.  If we were to sort the samples by their mean pH, and the \\gls{otu}s by their mean pH (Equation 3), a well defined band pattern appears.  Here, it is clear that \\gls{otu}s with a mean pH less than 3 rarely have nonzero counts above 8.  Likewise, \\gls{otu}s that have a mean pH more than 8 rarely have nonzero counts below 3.  If we were to tie in this band pattern in Figure \\ref{figc2}c together with the balance vs pH trends shown in Figure \\ref{figc2}b, we would obtain a very different interpretation from the original study.  \\gls{otu}s tend to be observed in very specific pH ranges, but not commonly observed outside of these ranges.  This ties together with some concepts in niche theory - \\gls{otu}s are more suited to live within a designated range of pHs.  And if they are placed outside of this pH range, they are outcompeted by other organisms who are more suited to live within the given pH range.  \\par\n These patterns were completely missed when only looking at the phylum level in the original study.  In fact, based on the calculated mean pH values for each \\gls{otu}s, it is observed that \\gls{otu}s from all of the phyla mentioned in the study are widely distributed across the pH gradient (Supplemental Table 1).  As an extreme example, \\gls{otu}s from the family Bradyrhizobiaceae were observed to be present in both ends of the spectrum, some present at pH values as low as 5.36, while others present at a pH as high as 6.75.  These are astronomical differences, considering\n that 95\\% of the \\gls{otu}s have a mean pH that falls between this range. This provides additional justification for building a tree based on mean pH, rather than bacterial phylogeny.\\par\n  Finally, these balances can be used to build predictive models.  Using ordinary least squares on the calculated balances, the entire microbial community profile can be predicted using pH alone with an $R^2$ of 0.35. This means that pH alone explains over 35\\% of the total variation in entire soil microbial communities across North and South America. The resulting fit can be transformed back to proportions to yield the predicted proportions (Figure \\ref{figc2}d).  From this heatmap, the key patterns are still retained, such as the band pattern apparent in Figure \\ref{figc2}c. There are many regression techniques published that attempt to use microbial abundances to predict covariates, such as the post-mortem interval \\cite{mammalian_corpse} or body mass index \\cite{microbial_regression}. This approach is the first of its kind to attempt to address the reverse problem to predict entire microbial community distributions based on environmental variables. These predictions were enabled by the powerful fundamental properties of balances.\\par\n  \\subsection{Case Study \\#2 – Balances of pH-driven subcommunities in a lung sputum culture microcosm}\n In this study, lung sputum samples were collected from 16 cystic fibrosis (\\gls{cf}) patients.  These sputum samples were then grown in a capillary tube culture system (Winogradsky Cystic Fibrosis system) that mimics the conditions of a lung bronchiole \\cite{wincf}.  These samples were placed into separate tubes and the pH of the media was adjusted from 5 to 8.5 at intervals of 0.5 to determine how the microbial community changed with respect to pH.  After growth in the capillary tubes, the communities were assessed using 16S \\gls{rrna} gene amplicon sequencing.\\par\n One of the difficulties in this study was characterizing pathogenic bacteria.  Early on in this case study, the only significant finding discovered was that patients had different lung sputum microbiomes (Figure \\ref{figc3}a). It was hypothesized that there was a subcommunity of low pH organisms and a subcommunity of high pH organisms that periodically appeared and disappeared in \\gls{cf} lung sputum.  However, these changes could not be detected using available statistics, likely due to the compositionality problem.  Since the different \\gls{cf} patients had idiosyncratic lung communities, they ended up having different \\gls{otu}s responding across the laboratory pH gradient, yielding insufficient statistical power to detect changes in any given \\gls{otu}.  As a result, when these lung sputum communities were placed into different media and studied, it was not clear exactly what organisms were a part of this low pH or high pH subcommunity.  \\par\n Balances are a natural solution to this problem.  In addition to probing for similar patterns to those observed in the previous study, balances are well adapted as a transformation for standard statistical analyses.  Since Euclidean operations directly translate into perturbation and powering operations on proportions \\cite{ilr, Pawlowsky-Glahn2015-qb}, many publicly available statistical tools can be applied to directly to balances.  For this study, we opted to use Linear Mixed Effects models to test for pH differences while simultaneously accounting for all of the differences between lung microbiomes across \\gls{cf} patients.   Based on prior analyses with pH in soils, the tree was built using the exact same strategy (See Methods and Materials).   Significant balances testing for pH were determined with a p-value cutoff at 0.05 after Bonferroni correction.  \\par\n  \\begin{figure}[H]\n        \\centering\n        \\includegraphics[width=1\\textwidth]{ch3/Figure3.pdf}\n        \\caption[The application of balances on a cystic fibrosis dataset to identify\n          microbial partitioning with respect to pH.]\n        {The application of balances on a cystic fibrosis dataset to identify microbial partitioning with respect to pH.(a) A bifurcating tree generated from hierarchical clustering of \\gls{otu}s based on mean pH.   The size of the internal nodes is inversely proportional to the p-value of the linear mixed effects model test on pH for that given balance.  A heatmap of all of the \\gls{otu} abundances sorted by patient. \\gls{otu}s were log transformed and centered across rows and columns. These abundances are aligned with the tips of the tree.  (c) The progression of the top balance over the pH for all of the patients.  (d) The progression of the second top balance over pH for all of the patients.\\index{SanDiego8}}\n        \\label{figc3}\n \\end{figure}\n A heatmap relating pH to \\gls{otu} abundances across these samples does not yield clear trends (Fig 3a).  But even though we don't see a clear pattern in the heatmap, with the balance approach, we can still observe niche differentiation across the pH gradient.  In Figure \\ref{figc3}b, y0 represents the log ratio of all of the high pH \\gls{otu}s (7.6 $<$ mean pH $<$ 8.12) over all of the low pH \\gls{otu}s (5.4 $<$ mean pH $<$ 7.4).  As the pH of the samples increases, the balance increases, likely because the low pH \\gls{otu}s are becoming increasingly less abundant compared to the high pH \\gls{otu}s (p-value=$7.5 \\times 10^{-46}$).  The same pattern is even more apparent in y1 (Figure \\ref{figc3}c). The low pH \\gls{otu}s (5.4 $<$ mean pH $<$ 6.4) become increasingly less abundant than high pH \\gls{otu}s (6.5 $<$ mean pH $<$ 7.4) as the sample pH increases (p-value=$2.25 x 10^{-67}$).  When Bonferroni multiple hypothesis correction was applied to these tests, the p-values were rounded down to zero.  While these patterns were not obvious when looking at the raw proportions, the balance tree approach shows very well defined trends among groups of \\gls{otu}s. This can be done because even though individual \\gls{otu}s may be sporadically distributed across the original samples, \\gls{otu}s that thrive in similar pH niches grouped together on the environmental balance tree.  It is clear from Figure \\ref{figc3}b and c that there is a transition from low pH organisms to high pH organisms along the pH gradient.  Even though the \\gls{cf} patients don't have the same lung microbiomes, they contain \\gls{otu}s that behave the same with respect to pH.  This pattern would not have been nearly as apparent without clustering the \\gls{otu}s by mean pH and accounting for the patient effects in the linear mixed models.\n \\section{ Discussion}\n In this study, we have demonstrated the benefits of applying balances to infer niche differentiation in microbes.  In the first case study, we have outlined the challenge of performing correlations of \\gls{otu}s versus environmental variables, and showed how balances can capture information about species turnover across the pH gradient, which allowed us to build a model to predict microbial proportions based on pH alone.  In the second case study, we identified the challenges of studying individual \\gls{otu}s due to similar niches being occupied by drastically different \\gls{otu}s across different patients. Balances coupled with linear mixed models allowed us to obtain more statistically robust results, which were also more informative with respect to the differences in distribution of microbes across environmental niches.\\par\n There are numerous additional benefits of analyzing species balances instead of individual species counts.  First, balances are known to be scale-invariant, so balance trees naturally correct for differences in sequencing depth without requiring rarefaction (Equation S1) and avoid many of the limitations associated with this procedure \\cite{waste_not}. Second, balances are sub-compositionally coherent, which means that changes in non-overlapping sub-communities do not impact each other.  For instance, in Figures 1e and 1f, the Purple population triples and balances change because they explicitly contain the Purple species.  In contrast, the balance red and green log ratio does not change between these two scenarios because it does not relate to the Purple species (in fact, it only accounts for the Red and Green species).  This is not the case when observing the raw proportions, from which it appears as though everything is changing, even though the Purple species is the only changing species.  This phenomenon has previously been noted \\cite{ancom} and can lead to extremely high false positive rates with some standard statistical techniques such as Pearson correlations or t-tests on proportions.  More discussion about this issue can be found in Figure S1. Third, arithmetic operations on balances directly translate into perturbation and powering operations on proportions \\cite{ilr, Pawlowsky-Glahn2015-qb}, which can capture information about relative growth and decay of species.  This ultimately opens the door for applying standard statistical techniques, such as multiple linear regression \\cite{c24} and linear mixed effects models nested design statistics directly to balances, providing additional justification for the analyses performed in the case studies.  We have shown this in the two case studies.  Finally, balances are permutation invariant.  Species can be sorted in any order deemed appropriate.  Along the same lines, these species can be rearranged into any arbitrary grouping represented as a bifurcating tree.  These trees can be built to address the questions at hand, whether it be studying species turnover across pH gradients, or even uncovering the relationships between phylogenetic clades.  In fact, balances can be thought as being utilized as an ordination technique, since every bifurcating tree forms an orthonormal basis in the Aitchison Simplex \\cite{groups_of_parts}.\\par\n Although the concept of balances does not address questions about properties of individual bacteria, it does answer higher-level questions concerning interactions among groups of organisms, which are arguably much more interesting from an ecological point of view. These questions can be based either on the phylogenetic tree of the bacterial community, or on environmental clustering.  There is still room for improvement on utilizing balances.  For example, the issue of zeroes still remains, because the logarithm of zero is undefined.  Currently, the common approach is to add a pseudo-count \\cite{dealing_with_zeros}.  However, an appropriate tree choice can mitigate this issue, because the zeroes can be explicitly aggregated in some scenarios (Figure S2 and Figure S3).  Along the same lines, issues can arise from low-coverage samples.  If sampling is not saturated, many \\gls{otu}s have low read counts, and the balances towards the tips of the trees can be highly volatile.  This is because the absolute change between one or two reads may be small for low abundance \\gls{otu}s, but this will lead to large changes in log ratios, which lead to spurious signals at the tips of the tree.  As a rule of thumb, balances towards the root of the tree are more trustworthy than those at the tips of the tree.\\par\n The balances approach will be key for analyzing functional roles of \\gls{otu}s.  It is known that in environments like the human gut, people share very few \\gls{otu}s with each other, but have roughly the same proportions of functional genes \\cite{soil_pyro}.  This suggests that there is substantial functional redundancy across \\gls{otu}s, which has been observed previously in time series studies in the context of infection \\cite{microbiome_timeseries} — in other words, in these microbial communities many players might be sporadically distributed across similar niches.  This phenomenon could explain the sparse nature of 16S relative abundance data, and why similar environments such as human guts share few common \\gls{otu}s.  Such distributions pose tremendous challenge to analyses based around identifying the niche occupancy of individual \\gls{otu}s. By instead permitting the statistical comparisons to be performed across nested groups of \\gls{otu}s with similar distributions, it becomes possible to robustly identify patterns of niche differentiation without requiring sufficient information be present in the abundances of each individual taxon. Identifying common functional roles of potentially diverse organisms, and analyzing the balances between these groups could significantly simplify analyses in future amplicon studies.  The ability to construct such trees would enable rapid characterizations of environmental niches, and the corresponding functional roles of the microbes occupying in these niches.\\par\n All in all, balance trees are an extremely powerful tool for analyzing relative abundances and uncovering patterns associated with niche differentiation, while avoiding the issues associated with compositionality and enabling the application of conventional statistical tools.  This will ultimately open the doors for extensive mining of ecologically relevant patterns.\n \\section{Methods and Materials}\n All analyses can be found in the attached IPython notebooks.  The core functions required to perform the balance basis calculations, tree visualization tools, and statistical analyses can be found in \\url{https://github.com/biocore/gneiss}.  The IPython notebooks used to carry out all of the analyses can be found in the gneiss repository.  All code has been extensively unit-tested and documented. \\par\n The core compositional statistics and tree data structures were are part of scikit-bio 0.4.1 and beyond. The hierarchical clustering was performed using Scipy.  Pandas and \\gls{biom} \\cite{biom} were used to store and manipulate the \\gls{otu} tables and the metadata files.  Seaborn, matplotlib and ETE \\cite{ete} were used for the visualizations.\\par\n The isometric log ratio transform is an isomorphism (i.e. a function) that can map proportions to balances one to one \\cite{ilr}.  These balances can be calculated as shown in Equation 1. Alternatively, they can be calculated using a linear transformation with an orthonormal basis e. This orthonormal basis can be calculated as follows\n \\begin{equation}\n        e_{l}=C\\left [\\exp(\\: \\: \\underset{k}{\\underbrace{0,...0}},\\underset{r}{\\underbrace{a,...a}},\\underset{s}{\\underbrace{b,...b}}, \\underset{t}{\\underbrace{0,...0}}) \\right]\n \\end{equation}\n \\begin{equation}\n        a=\\frac{\\sqrt{s}}{\\sqrt{r(r+s)}} \\quad  and \\quad b=\\frac{-\\sqrt{r}}{\\sqrt{s(r+s)}}\\notag\n \\end{equation}\n where $e_{l}$ refers to the balance axis aligned with the internal node \\textit{l}. $C[x]$ denotes the normalization operation to normalize all of the \\gls{otu} abundances to proportions that add up to 1.  $r$ refers to the number of tips in the left subtree, $s$ refers to the number of tips in the right subtree, $k$ refers to number of tips to the left of the left subtree and $t$ refers to the number of tips to the right of the right subtree. Since $e$ forms an orthonormal basis, it must have unit norm and every pair of axes in $e$ must be orthogonal.  The square root term   in Equation 1 is a normalization factor which was required for unit norm in Equation 2 (12).    Since it is not possible to take a logarithm of zero, a pseudocount of 1 was added to all of the abundance.  While this is a problem being addressed by the field, this technique is one of the more commonly used techniques \\cite{dealing_with_zeros}.\\par\n The mean pH used for the 2 case studies was calculated as follows.\n \\begin{equation}\n        \\overline{g}_{x}=\\sum_{i=1}^{N}g_{i}\\frac{x_{i}}{\\sum_{j=1}^{D}x_{j}}\n \\end{equation}\n Where $x_{i}$ is the proportion of \\gls{otu} \\textit{x} in sample \\textit{i} , $g_{x}$ is the mean pH of \\gls{otu} \\textit{x}, and $g_{i}$ is the sample pH at sample \\textit{i}. This calculation can be found in the gneiss package under the function \\textbf{mean\\_niche\\_estimator}. The function used to sort the tables in Figure \\ref{figc2}c used \\textbf{niche\\_sort}. The resulting tree was built using UPGMA \\cite{upgma} is shown in Figure \\ref{figc2}a and Figure \\ref{figc3}a, and can be generated using the scipy linkage function.\\par\n This regression model is implemented in gneiss under the \\textbf{ols} function.  The analysis can be found in the IPython notebooks on the gneiss repository under the ipynb folder in \\textbf{88soils.ipynb}. To focus on the highest abundant organisms, only \\gls{otu}s that had more than 100 reads in the entire study were considered.\\par\n The linear mixed effects model is implemented in gneiss under the \\textbf{mixed} functions, and the analyses can also be found in the IPython notebooks in the ipynb folder in \\textbf{cfstudy.ipynb} In case study 2, only \\gls{otu}s that had more than 500 reads were considered.   \\par\n The Win\\gls{cf} system was used according to the methods in \\cite{wincf}, except only the pH dye media variable was used. The media was buffered at 0.5 units of pH from 5 to 8.5 using calculated proportions of phosphate buffer and NaOH or HCl. Sputum samples were collected from \\gls{cf} patients after expectoration or induced expectoration of sputum according to the UCSD IRB approved project \\#081500, and were inoculated in triplicate into capillary tubes containing the eight different pH buffered media. These eight sets of tubes in triplicate from 18 patients was then incubated at $37^{o}$C for 48 hours. The media was then removed, bacterial DNA extracted, and variable region 4 of the 16S \\gls{rrna} gene was amplified and sequenced on the Illumina MiSeq platform using Earth Microbiome Project benchmarked protocols \\cite{illumina_microbes, global_patterns}.  Data were processed using QIITA and \\gls{otu}s were calculated using closed reference clustering at the 97\\% identity cutoff for both the 88 soils and the \\gls{cf} study.\n\\section{ Data availability}\nData for case study 1 was retrieved from Qiita (study ID 103). Data from case study 2 was retrieved from Qiita (study ID 10511).\n\\section{Acknowledgements}\nWe first acknowledge Jonathan Friedman for the original idea of applying balances to analyze microbial communities. We also acknowledge Justin Silverman and Lawrence David, in addition to Liam Toran, Tomasz Kosciolek, and Amnon Amir, for their insights and discussion on balances. In addition, we are grateful for the input from Christian Lauber and Noah Fierer concerning case study 1. Finally, we thank all of the scikit-bio developers, especially Jorge Cañardo Alastuey, Evan Bolyen, Jai Rideout, and Greg Caporaso, for reviewing the compositional statistics submodule in scikit-bio.\n\nJ.T.M. was funded by NSF grant GRFP DGE-1144086 and NSF grant IGERT 1144807 under the IQ Biology program at the University of Colorado Boulder. R.A.Q. was funded under the Cystic Fibrosis Research Innovation Award from Vertex Pharmaceuticals. This work was funded under Alfred P. Sloan Foundation grants G-2015-13933 and G-2015-13979 and National Institute of Diabetes and Digestive and Kidney Diseases (NIDDK) grant P01DK078669.\n\nJ.T.M. led the software development, benchmarking, and manuscript writing and developed the idea of applying regression to balances. J.S. contributed the idea of applying linear mixed-effects models to balances and named the software package. R.A.Q. collected the \\gls{cf} lung sputum samples. D.M., A.G., J.A.N.-M., and Y.V.-B. reviewed the code in Gneiss. M.L. reviewed the mathematical notation. All authors wrote and proofread the manuscript.\n\nChapter 3, in full, is a reprint of the material as it appears in\n``Balance Trees Reveal Microbial Niche Differentiation''\nJames T. Morton, Jon Sanders, Robert A. Quinn, Daniel McDonald, Antonio Gonzalez,\nYoshiki Vázquez-Baeza, Jose A. Navas-Molina, Se Jin Song, Jessica L. Metcalf,\nEmbriette R. Hyde, Manuel Lladser, Pieter C. Dorrestein, Rob Knight\n\\emph{mSystems}, 2, 2017.  The dissertation author was the primary investigator and first author of this paper.\n\n", "meta": {"hexsha": "6e5f8c34cc31829c3786088eea4beb338ba53eae", "size": 37776, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ch3_balances.tex", "max_stars_repo_name": "mortonjt/phd-thesis", "max_stars_repo_head_hexsha": "f2b381322236b2591b51e4f9fca5899e0922654c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch3_balances.tex", "max_issues_repo_name": "mortonjt/phd-thesis", "max_issues_repo_head_hexsha": "f2b381322236b2591b51e4f9fca5899e0922654c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch3_balances.tex", "max_forks_repo_name": "mortonjt/phd-thesis", "max_forks_repo_head_hexsha": "f2b381322236b2591b51e4f9fca5899e0922654c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 397.6421052632, "max_line_length": 2429, "alphanum_fraction": 0.7980728505, "num_tokens": 8521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6150878414043816, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.31234890343903066}}
{"text": "\\section{Tracking Substitutions}\n\nThen we define the notion of tracking substitutions.\nIn Figure~\\ref{fig:proofs:tracking} we extend the operational\nsemantics with a state $\\sigma$, \\ie a mapping from variables to \nexpressions that tracks evaluation of its expressions\n\n\\input{proofs/tracksemantics}\n\nFirst we prove that evaluation to a constant exists \\textit{iff} \ntracking evaluation to the same constant exists.\n\\begin{lemma}\\label{lemma:teval}\n$\\forall\\theta, e, c, \\exists\\theta'. \\evals{\\thetasub{\\theta}{e}}{c} \\Leftrightarrow \n\t\\tevals{\\theta}{e}{\\theta'}{c}$.\n\\end{lemma}\n\\showproofsketch{\n\\begin{proofsketch}\n\\begin{itemize} We prove each direction:\n\\item $\\Rightarrow$.\nGiven the derivation $\\evals{\\thetasub{\\theta}{e}}{v}$, we can track the appearances \nof each expressions $\\theta(x_i)$ and its derivatives and replace them with $x_i$.\nThus, given the initial derivation we can transverse it\n(left-to-right and post-order); \nfor every tracked appearance we use the appropriate rules \nthat update the stack every time a tracked expressions evaluates, ie., \nappears in the left hand side of a rule; \nand remove the multiple evaluations of expressions in the stack\nand construct the evaluation \n\\tevals{\\theta}{e}{\\theta'}{c}.\n\nNote that if $\\theta(x_i)$ goes to a value, then \n$\\theta(x_i) \\equiv e_0 \\hookrightarrow \\dots e_i \\dots e_n \\equiv v$.\nBy the way we transverse the tree, \nafter the stack is updated to $e_k$ and before it is updated to $e_{k+1}$\nall tracked computations for $x_i$ are $e_j, j \\leq k$.\n\nIf $\\theta(x_i)$ does not go to a value, it cannot appear in the left hand side of \na rule, because evaluation would diverge, thus the stack is not updated for $x_i$.\n\nWhen a tracked expression reaches a value, we use the appropriate value to \nsubstitute (and untrack) the value.\nSince the result of the initial evaluation is a constant, \nthen the result of the tracked computation is the same constant. \n\n\\item $\\Leftarrow$.\nGiven $\\tevals{\\theta}{e}{\\theta'}{c}$\nwe can construct the derivation \\evals{\\thetasub{\\theta}{e}}{c} replacing each query to the \nstack with the initial computation of the expression.\n\\end{itemize}\n\\end{proofsketch}\n}\n\nThen we define a \\textit{bottomize} function \\mkbot{\\bullet}\nthat replaces non-evaluated expressions with \\ebot:\n\\begin{definition}{[Bottomize]}\n$$\n\\mkbot{\\theta}(x) = \n\\left\\{\n\t\\begin{array}{ll}\n\t\tD\\ \\overline{\\mkbot{\\theta}(y)}  & \\mbox{if } \\theta(x) = D\\ \\overline{y}\\\\\n\t\tv  & \\mbox{if } \\theta(x) = v \\not = D\\ \\overline{y}\\\\\n\t\t\\ebot & \\mbox{otherwise}\n\t\\end{array}\n\\right.\n$$\n\\end{definition}\n\nUsing the bottomize function we show that evaluation does not depend \non non-evaluated expressions:\n\\begin{lemma}\\label{lemma:mkbot}\nIf \\tevals{\\theta}{e}{\\theta'}{c}, \nthen \\evals{\\mkbot{\\theta'}\\ e}{c}.\n\\end{lemma}\n\\showproofsketch{\n\\begin{proofsketch}\nSince \\tevals{\\theta}{e}{\\theta'}{c}$(1)$, \nthen \\tevals{\\theta'}{e}{\\theta'}{c}$(2)$:\nFrom the evaluation tree $(1)$ we can construct the evaluation tree $(2)$.\nThe trees differ on store related rules.\n\nSay that in $(1)$ the store in $x$ is updated, for an arbitrary $x$: \n\\teval{(x,e_x)\\theta_x}{x}{(x,e'_x)\\theta_x}{x}\nSince $(1)$ is finite, it should be that\n$\\tevals{\\theta_x}{e_x}{\\theta_x}{v} (3)$.\nCall $v_x = D\\ \\overline{y}$ if $v = D\\ \\overline{e}$, $v$ otherwise.\nThen in $(1)$ there should be a ``subtree'' with $(3)$\nafter which the value of $x$ cannot change in the store.\nOr $\\theta'(x) = v_x$.\nWe construct $(2)$ by removing the ``subtree'' with $(3)$.\nAfter that all rules that relate store with $x$ will be the same\non $(1)$ and $(2)$.\n\nIf $x$ is not updated in $(1)$ then \n$x$ does not appear in the left hand side of a rule; \nthus $\\theta'(x) = \\theta(x)$.\n\nWe construct $\\theta''(x)= \\left\\{\n\t\\begin{array}{ll}\n\t\tv  & \\mbox{if}\\ \\theta'(x)= v\\\\\n\t\t\\ebot & \\mbox{otherwise}\n\t\\end{array}\n\\right.$\n\nThen \\tevals{\\theta''}{e}{\\theta''}{c}.\nIf $\\theta'(x)$ is not a value, then it does not appear in the left hand side \nof any rule in $(2)$, thus evaluation of $e$ cannot depend on $x$.\n\nThen by Lemma \\ref{lemma:teval}, \\evals{\\thetasub{\\theta''}{e}}{c}.\nBut $\\mkbot{\\theta'} e = \\thetasub{\\theta''}{e}$, so \\evals{\\thetasub{\\mkbot{\\theta'}}{e}}{c}.\n\\end{proofsketch}\n}\n\nAlso, replacing \\ebot with any expression yields the same evaluation:\n\\begin{lemma}\\label{lemma:rmbot}\nIf \\evals{\\thetasub{\\mkbot{\\theta}}{e}}{c}, \nthen \\evals{\\thetasub{\\theta}{e}}{c}.\n\\end{lemma}\n\\showproofsketch{\n\\begin{proof}\nSince \\evals{\\thetasub{\\mkbot{\\theta}}{e}}{c}$(1)$, then\n\\tevals{\\mkbot{\\theta}}{e}{\\theta'}{c}$(2)$.\n\\ebot expressions in \\mkbot{\\theta} are not evaluated, \notherwise $(2)$ would get stuck.\nThus they can be instantiated with any expression.\n$\\theta$ provides such an instantiation, thus\n\\tevals{\\theta}{e}{\\theta''}{c}$(3)$.\nBy Lemma \\ref{lemma:teval}, \\evals{\\thetasub{\\theta}{e}}{c}.\n\\end{proof}\n}\n\nFinally, we define lifting substitutions\n%\n\\begin{definition}{[Lifting Substitutions]}\n$\n\\trackevals{\\sto}{\\botsto} \\doteq \n\\exists e, e', \\theta' \\tevals{\\theta}{e}{\\theta'}{e'} \\land \\botsto = \\mkbot{\\theta'}\n$\n\\end{definition}\n\nand prove the Lifting Lemma\n\\begin{lemma}{[Lifting]}\\label{lemma:proofs:lifting}\n$\\evals{\\thetasub{\\sto}{e}}{c}$ iff $\\exists \\trackevals{\\sto}{\\botsto}$ s.t. \n$\\evals{\\thetasub{\\botsto}{e}}{c}$.\n\\end{lemma}\n\\showproofsketch{\n\\begin{proofsketch}\nThe $\\Rightarrow$ direction follows immediately from Lemmata~\\ref{lemma:teval} and~\\ref{lemma:mkbot}.\nThe $\\Leftarrow$ direction follows immediately from Lemmata~\\ref{lemma:teval} and~\\ref{lemma:rmbot}.\n\\end{proofsketch}\n}\n\n\n", "meta": {"hexsha": "a11169e06057373d2cdd21e854554f70e3efed00", "size": 5552, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "text/refinedhaskell/proofs/tracking.tex", "max_stars_repo_name": "nikivazou/thesis", "max_stars_repo_head_hexsha": "a12f2e857a358e3cc08b657bb6b029ac2d500c3b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2016-12-02T00:46:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-20T07:04:01.000Z", "max_issues_repo_path": "text/refinedhaskell/proofs/tracking.tex", "max_issues_repo_name": "nikivazou/thesis", "max_issues_repo_head_hexsha": "a12f2e857a358e3cc08b657bb6b029ac2d500c3b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "text/refinedhaskell/proofs/tracking.tex", "max_forks_repo_name": "nikivazou/thesis", "max_forks_repo_head_hexsha": "a12f2e857a358e3cc08b657bb6b029ac2d500c3b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-12-02T00:46:51.000Z", "max_forks_repo_forks_event_max_datetime": "2016-12-02T00:46:51.000Z", "avg_line_length": 36.2875816993, "max_line_length": 101, "alphanum_fraction": 0.7002881844, "num_tokens": 1772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.31218525440306655}}
{"text": "\\newcommand{\\anglevars}{x,y,z,E_g,\\theta,\\varphi}\n\\newcommand{\\scalarvars}{x,y,z,E_g}\n\n\n\\section{Computational Success Metrics}\n\\label{sec:successmetrics}\n\\subsection{Anisotropy Quantification}\n\\label{sec:anisotropy_quant}\n\nAs the $\\Omega$-methods are analyzed, it is important to determine the\ntypes of problems in which the methods are successful. In addition to describing\nthe physics that induce anisotropy in the flux, quantifying the degree of\nanisotropy of the problem is useful in characterizing the method. In this\nsection, a number\nof methods by which the anisotropy can be quantified in these problems are\nproposed. A brief description of how these methods capture anisotropy in the\nproblem is also included. While each metric proposes an avenue by which the\nproblem can be analyzed, there are certainly other methods that one may propose.\nThe methods described in the following\nsubsections are proposed because they use data generated from the existing\nmethod. The degree to which they impose a computational burden will be addressed\nin their analysis.\n\n\\subsubsection{The Scalar Contributon Ratio}\n\nThe hybrid methods software that will be used for this project is ADVANTG,\ndeveloped at ORNL. Section \\ref{sec:software} explains how the software used\ninteracts with other pieces of software\nand how they were modified to execute this method.\nThe standard release of ADVANTG provides the contributon flux as an output\noption, which can then be used to analyze problem physics by a user.\nIf this option is selected as an output, a SILO file containing\nthe contributon fluxes for each discretized cell in space and energy  is\ncreated. This is useful for problem analysis as the user may see\npreferential streaming paths for particles in the problem using this metric.\nThe contributon flux generated in this process is given by the product\nof the scalar adjoint and forward fluxes (Eq. \\eqref{eq:adv_contributon}).\n\nAs mentioned in Section \\ref{sec:ContributonImportance}, the\ncontributon flux can be calculated by using\nthe product of the forward and adjoint fluxes. In standard software packages\nthat calculate the contributon flux, like ADVANTG, the scalar contributon flux is calculated by the product\nof the scalar adjoint and forward fluxes. This can be written as\n%\n\\begin{equation}\n  \\phi^{c}(\\vec {r} ,E)  = \\phi^{\\dagger}(\\vec {r} ,E)\\phi(\\vec {r} ,E) .\n\\label{eq:adv_contributon}\n\\end{equation}\n%\nA more precise calculation of the contributon flux could be generated from\nintegrating the angular contributon flux over all angle, as\n%\n\\begin{equation}\n  \\begin{split}\n    \\Phi^{c}(\\vec {r} ,E)  & = \\int_{\\Omega}{\\psi^{c}(\\vec{r}, E, \\hat \\Omega)}\n                               d\\hat\\Omega \\\\\n             & = \\int_{\\Omega}{\\psi^{\\dagger}(\\vec{r}, E, \\hat\\Omega)\n                 \\psi(\\vec{r}, E, \\hat\\Omega)} d\\hat\\Omega .\n  \\end{split}\n\\label{eq:full_contributon}\n\\end{equation}\n\nBoth Eqs. \\eqref{eq:adv_contributon} and \\eqref{eq:full_contributon} calculate\nthe contributon flux as a function of space and energy, but the\ndifferences in their calculation is addressed in their notation, namely using\n$\\phi^{c}$ or $\\Phi^{c}$. The standard release of ADVANTG only has\naccess to the scalar\nfluxes, so Eq. \\eqref{eq:full_contributon} is not an accessible option for a\nuser. Because the $\\Omega$ calculations require full angular flux map,\nthe scalar contributon flux can be calculated with the latter\nformulation, rather than the former in the modified version developed to support\nthis work.\n\nThe first measure of anisotropy quantification that will be evaluated is the\nratio between these two quantities, as described by Eq. \\eqref{eq:metric_one}.\nThe ratio between these two values is evaluated for every cell, $x,y,z$, and energy\ngroup, $E_g$.\nIf the adjoint or forward angular flux is significantly\npeaked in $\\Omega$, this will result in a deviation between $\\phi^{c}$ and\n$\\Phi^{c}$, because there will be a multiplicative effect in the angular flux\ncaptured in $\\Phi^{c}$ but not $\\phi^{c}$. The more isotropic the\nflux in $\\vec{r}$ and $E$, the closer these\nvalues will be and the quantity will approach unity.\n\n\\begin{equation}\n  % M_{1} = \\frac{\\phi^{c}_{\\vec {r} ,E}}{\\Phi^{c}_{\\vec {r} ,E}}\n  M_{1} = \\frac{\\phi^{c}}{\\Phi^{c}}\\bigg\\rvert_{\\scalarvars}\n  \\label{eq:metric_one}\n\\end{equation}\n\n\\subsubsection{The Ratio of Adjoint Fluxes}\n\nAs discussed in previous sections, the $\\Omega$-methods use the $\\Omega$-scalar\nflux in place of the standard adjoint scalar flux. Therefore the ratio between\nthese two quantities would also provide a useful metric for comparing which\nregions have significantly differing bias parameters in standard-adjoint and\n$\\Omega$-adjoint situations. This metric will deviate from unity if the forward\nflux is anisotropic. This metric is calculated for\nevery cell and every energy group in the problem, as shown in Eq.\n\\eqref{eq:metric_two}.\n%\n\\begin{equation}\n  M_{2} = \\frac{\\phi^{\\dagger}_{\\Omega}}{\\phi^{\\dagger}}\\bigg\\rvert_{\\scalarvars}\n  \\label{eq:metric_two}\n\\end{equation}\n%\nMetrics one and two both reasonably appear to compute the anisotropy in the flux\nusing versions of the contributon and adjoint fluxes, respectively. However, by\nexpanding the $\\Omega$-adjoint scalar flux in metric two,\n%\n\\begin{align*}\n% \\begin{equation*}\n%  \\begin{split*}\n  M_{2} & = \\frac{\\phi^{\\dagger}_{\\Omega}}{\\phi^{\\dagger}}\\bigg\\rvert_{\\scalarvars} \\\\\n  & = \\frac{\\int_{\\Omega}{\\psi^{\\dagger}(\\hat\\Omega) \\psi(\\hat\\Omega)}\n      d\\hat{\\Omega}}{\\int_{\\Omega}{\\psi(\\hat\\Omega) d\\hat{\\Omega}}}\n           \\frac{1}{\\phi^{\\dagger}}\\bigg\\rvert_{\\scalarvars}, \\\\\n\\intertext{integrating the forward angular flux over all angle,} \\\\\n  & = \\frac{\\int_{\\Omega}{\\psi^{\\dagger}(\\hat\\Omega) \\psi(\\hat\\Omega)}\n      d\\hat{\\Omega}}{\\phi}\n           \\frac{1}{\\phi^{\\dagger}}\\bigg\\rvert_{\\scalarvars}, \\\\\n\\intertext{and rearranging the terms,}\\\\\n  & = \\frac{\\int_{\\Omega}{\\psi^{\\dagger}(\\hat\\Omega) \\psi(\\hat\\Omega)}\n      d\\hat{\\Omega}}{\\phi \\phi^{\\dagger}}\\bigg\\rvert_{\\scalarvars}\\\\\n  & = \\frac{\\Phi^{c}}{\\phi^{c}}\\bigg\\rvert_{\\scalarvars}\\\\\n  & = \\frac{1}{M_{1}}\\bigg\\rvert_{\\scalarvars},\n%  \\end{split*}\n% \\end{equation*}\n\\end{align*}\n%\nit becomes evident that the ratio of adjoint fluxes is the inverse of the scalar\ncontributon ratio. As a result, metric one will not be used in the analyses of\nthe characterization problems.\n\n\n\\subsubsection{The Maximum to Average Flux Ratio}\n\nAn alternative metric to quantify anisotropy is to calculate the ratio between\nthe maximum and average angular contributon flux in each $\\vec{r} , E$ voxel.\nThe higher this quantity, the more peaked the contributon flux is in $\\Omega$.\nNote that while using the $\\Omega$-flux would seem like the natural choice,\nno angular information is directly accessible once the $\\Omega$ scalar flux has\nbeen calculated. One can compare the standard adjoint scalar flux and the\n$\\Omega$-adjoint scalar flux and infer how anisotropic the flux in the cell might be, but\ndue to the normalization that occurs in Eq. \\eqref{eq:omega_basic}, the\nvariation of angular $\\Omega$ fluxes throughout $\\Omega$ for a cell\nin $\\scalarvars$ is not\ncalculated. As such, the contributon flux must be relied\nupon as a next-best evaluator of that metric:\n%\n\\begin{equation}\n  M_{3} = \\frac{\\psi^{c}_{Max}}{\\psi^{c}_{\n          Avg}}\\bigg\\rvert_{\\scalarvars}  .\n  \\label{eq:metric_three}\n\\end{equation}\n\nWhile Eq. \\eqref{eq:metric_three} directly measures the anisotropy in the problem using\nthe angular contributon fluxes, it doesn't compare the difference\nbetween the fluxes used\nin the $\\Omega$-  and the standard adjoint methods. Metric three\ncan be\nreformulated to incorporate this information using\n%\n\\begin{equation}\n  \\begin{split}\n    M_{4} & = \\frac{\\frac{\\psi^{c}_{Max}}{\\psi^{c}_{\n                  Avg}}}{\\frac{\\psi^{\\dagger}_{\n                  Max}}{\\psi^{\\dagger}_{Avg}}} \\Bigg\\rvert_{\\scalarvars} \\\\\n          & = \\frac{M_{3}}{\\frac{\\psi^{\\dagger}_{Max}}\n                  {\\psi^{\\dagger}_{Avg}}} \\Bigg\\rvert_{\\scalarvars},\n  \\end{split}\n  \\label{eq:metric_four}\n\\end{equation}\n%\nas a measure between the anisotropies of the standard and contributon fluxes.\nThis equation is a logical progression from metric two and\nmetric three. This metric contains more information on how perturbed the\ncontributon flux is when compared to the original adjoint flux that is normally\nused in CADIS and FW-CADIS.\nIn the case of a strongly anisotropic\nforward flux, the forward flux  would significantly\nchange the distribution of the contributon\nfluxes in a cell, but it would not affect the flux distribution of the standard\nadjoint angular fluxes. By comparing the anisotropy in the contributon\nfluxes to those in the standard adjoint, the perturbation of the $\\Omega$ flux by\nthe forward flux\nin the cell can be evaluated. In regions where the forward flux is\nnot anisotropic, then the contributon anisotropy ratio should be approximately\nthe same as the standard adjoint anisotropy ratio.\n\nFurther, because the\ncontributon flux incorporates directionality of the forward and adjoint fluxes,\nthe maximum to average ratio of the contributon flux can differ from the adjoint\nflux. In regions where the adjoint\nangular flux and the forward angular flux are traveling in the same direction,\nthe contributon ratio should be greater than the adjoint ratio, and this metric\nwill be greater than one. In regions where they are travelling in opposite or\nperpendicular directions, the contributon flux will evaluate to a more isotropic\nstate, and metric four will be less than unity. This metric\nprovides substantially more information than metric two because\nit compares the behavior of the directional contributon and adjoint fluxes,\nrather than comparing the overall behavior of the flux in the cell.\n\nBoth Eqs. \\eqref{eq:metric_three} and \\eqref{eq:metric_four} compare the maximum\nangular flux in a cell to the average flux in the same cell. Because the average\nangular flux is the normalization factor, the maximum flux in the cell is\ncompared to some relative measure of the total flux behavior in that cell. If,\nfor example, the flux has several directional peaks, the average will reflect\nthat.\nThe fact that Eq. \\eqref{eq:metric_four} contains information on the global\nbehavior in the contributon and average cell, the directionality of the fluxes,\nand the degree of isotropy of the forward flux is attractive. However,\nthis is also a fairly computationally expensive calculation and it may\nnot be worth the computational cost when compared to metrics two and three.\n\n\\subsubsection{The Maximum to Minimum Flux Ratio}\n\nAn additional metric to quantify anisotropy in the contributon flux distribution\nis to calculate the ratio between the maximum and minimum angular fluxes for\neach region of $\\scalarvars$ phase-space, as described in metric\nfive, or Eq. \\eqref{eq:metric_five}. This\nquantity incorporates information about the\nbehavior of the local maximum relative to the local\nminimum angular flux in each cell.\n\n\\begin{equation}\n  M_{5} = \\frac{\\psi^{c}_{Max}}{\\psi^{c}_{\n          Min}}\\bigg\\rvert_{\\scalarvars}\n  \\label{eq:metric_five}\n\\end{equation}\n\nThis metric may be more appropriate to describe the anisotropy of the flux in\ncells where the distribution of flux values in the cell are not well\nreflected by the average flux in the cell. As with metric three (Eq.\n\\eqref{eq:metric_three}), metric five (Eq. \\eqref{eq:metric_five}) only quantifies\nthe anisotropy of the contributon flux in the cell. There is no comparison or\nnormalization to compare the anisotropy with respect to another method. To\ncompare it to the anisotropy of the flux in the standard adjoint\nproblem, a ratio similar to that of Eq. \\eqref{eq:metric_four} may be\nformulated:\n\n\\begin{equation}\n  \\begin{split}\n    M_{6} & =  \\frac{\\frac{\\psi^{c}_{Max}}{\\psi^{c}_{\n                  Min}}}{\\frac{\\psi^{\\dagger}_{\n                  Max}}{\\psi^{\\dagger}_{Min}}} \\Bigg\\rvert_{\\scalarvars} \\\\\n          & = \\frac{M_{5}}{\\frac{\\psi^{\\dagger}_{Max}}\n                  {\\psi^{\\dagger}_{Min}}} \\Bigg\\rvert_{\\scalarvars}  .\n  \\end{split}\n  \\label{eq:metric_six}\n\\end{equation}\n\nAs with Eq. \\eqref{eq:metric_four}, Eq. \\eqref{eq:metric_six} uses a ratio from\nthe standard adjoint formulation to normalize the anisotropy of the\ncontributon flux. Equation \\eqref{eq:metric_six} is consistent with Eq.\n\\eqref{eq:metric_five} and normalizes using the maximum to minimum\nratio of angular fluxes of the adjoint. These two\nmetrics will show the relative behavior of the flux in the cell, but because\nneither incorporates information about the total flux behavior within the cell,\nthey may be very sensitive to the variance of the angular flux within the\ncell. Using the ratio of both the contributon and adjoint fluxes may\nhelp to smooth this if the variance of flux distributions within the contributon\nand standard adjoint is similar in a particular cell. However, if these two\ndiffer significantly, then metric six (Eq. \\eqref{eq:metric_six}) may have a\nsynergistic effect\nand will over-emphasize the variance when quantifying the anisotropy of the\ncell.\n\nMetrics one through six quantify anisotropy\nin the problem solved by using different parameters to capture the problem\nphysics. These metrics will be compared to one another to determine which is the\nmost consistently correlated with predicting the $\\Omega$-method's success. A\nuser may want to know if the $\\Omega$-method will effectively generate variance\nreduction parameters for a Monte Carlo simulation, and this may be a\nprescriptive solution for that issue. However, all of these metrics do require\nfull angular flux solutions for both the forward- and adjoint- problem, so some\ncomputational burden will be required.\nThe analysis of using these metrics will include some information of\nbenefit to burden, which likely will come at the cost of time.\nThat said, because the Monte Carlo solution is more computationally\ndemanding, generating these metrics from the deterministic solution should be\nsubstantially less of an obstacle.\n\n\\subsection{Figure of Merit}\n\\label{sec:FOMvariants}\n\nThe FOM is a commonly used metric to measure Monte Carlo\nruntimes and to gauge the effectiveness of various hybrid methods. As discussed\nin Section \\ref{sec:MCvar}, the FOM relates the relative error of a solution to the\ntime required to achieve that variance. This was introduced in Eq.\n\\eqref{eq:FOM} as:\n\\begin{equation*}\n  \\text{FOM} = \\frac{1}{R^{2}T} ,\n\\end{equation*}\nwhere $T$ is the time and $R^{2}$ is the square of the relative error.\n\n\\subsubsection{Relative Error}\n\nIn tallies with multiple regions and/or energy bins, the FOM is usually calculated\nfrom the tally average relative error, or $R_{avg}$. This value is meaningful as\nit reflects the overall tally behavior. However, it is often desirable that all\nportions of the tally lie below a desired relative error threshold. A region\nwith very low particle contribution may have a much higher relative error than\nthe tally average, and may also converge much slower to a desired relative\nerror. This results in a substantially different FOM than\nthe tally average. In the results presented in later chapters, both relative\nerrors will be used to calculate different FOMs, respectively\n\\begin{subequations}\n  \\begin{equation}\n    \\text{FOM}_{avg} = \\frac{1}{R_{avg}^{2}T},\n  \\label{eq:FOMavg}\n  \\end{equation}\nand\n  \\begin{equation}\n    \\text{FOM}_{max} = \\frac{1}{R_{max}^{2}T} .\n  \\label{eq:FOMmax}\n  \\end{equation}\n  \\label{eq:FOMerror}\n\\end{subequations}\n\nIn addition to reporting both FOMs for the entire problem, comparing the\ndistribution of values of the relative error for problems will be a useful\nmetric in method characterization. If, for example, FW-CADIS acquires desirable\nresults in a calculation, then the problem should have a relatively even uncertainty\ndistribution for all cells. Comparing the distribution of relative errors\nbetween the analog case and the hybrid case reveals whether the method is\neffectively generating variance reduction parameters for the entire problem or\nif it is more effective in particular regions.\n\n\\subsubsection{Timing}\n\nThe previous section described two different means by which the FOM could be\ncalculated using different relative errors. The question that one must\nnow consider is: what time should be used to\ncalculate the FOM? In an analog Monte Carlo simulation, this time is the runtime\nof the Monte Carlo simulation, $T = T_{MC}$. In a hybrid method, one could choose\neither\n\\begin{equation}\n  T_{Hybrid} = T_{MC} + T_{Deterministic},\n\\label{eq:hybridtime}\n\\end{equation}\nor\n\\begin{equation}\n  T_{Hybrid} = T_{MC} .\n\\end{equation}\n\nThe FOM should remain a constant--with the exception of very early on in an MC\ncalculation where statistics are very poor--for a problem. The issue with using\nEq. \\eqref{eq:hybridtime} to calculate the FOM is that the deterministic runtime\ndoes not change the relative error of the Monte Carlo simulation. Thus, the FOM\nis not a constant throughout the Monte Carlo simulation when using Eq.\n\\eqref{eq:hybridtime} as the time.\nHowever, it would be disingenuous to not include the deterministic runtime into\nreports for the hybrid method, as the total computational time required to\nachieve some desired relative error is ultimately what the user is seeking. As\nsuch, two reports of the FOM are included with the results for each simulation:\n\\begin{subequations}\n  \\begin{equation}\n    \\text{FOM}_{MC} = \\frac{1}{R^{2}T_{MC}},\n  \\label{eq:FOMMC}\n  \\end{equation}\nand\n  \\begin{equation}\n    \\text{FOM}_{Hybrid} = \\frac{1}{R^{2}(T_{MC} + T_{Deterministc})} .\n  \\label{eq:FOMHybrid}\n  \\end{equation}\n  \\label{eq:FOMtime}\n\\end{subequations}\n\nNote that the deterministic time used in Eq. \\eqref{eq:FOMHybrid} is the time\nto run the transport and generate source biasing and weight window values for\neach problem. It will not include the time used to quantify the anisotropy as\noutlined in Section \\ref{sec:anisotropy_quant}, as those parameters will be\ncomputationally demanding but not normally included in a hybrid method\ncomputation.\n\nIn this section, four different equations to calculate the FOM were presented: two\nusing different relative errors, and two using different quantities\nfor time. In analyzing the method, all four will be presented: FOM$_{MC,avg}$,\nFOM$_{MC,max}$, FOM$_{Det,avg}$, and FOM$_{Det,max}$. Further, the improvement\nin the FOM for each problem will be reported as those values normalized by\nFOM$_{analog,avg}$ for the two FOMs calculated with the tally average relative\nerror and FOM$_{analog,max}$ for the FOMs calculated with the tally maximum\nrelative error. The success of the $\\Omega$-method will depend on its ability\nto improve\neach one of these FOM values.\n\n", "meta": {"hexsha": "4c683dab7b48dc4ff271ca80d245368410b024e6", "size": 18756, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/methodology/success_metrics.tex", "max_stars_repo_name": "rachelslaybaugh/munk-disseration", "max_stars_repo_head_hexsha": "e6dc6d6a8d5613cb30bca7dc4a2d419ad1b36e65", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/methodology/success_metrics.tex", "max_issues_repo_name": "rachelslaybaugh/munk-disseration", "max_issues_repo_head_hexsha": "e6dc6d6a8d5613cb30bca7dc4a2d419ad1b36e65", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/methodology/success_metrics.tex", "max_forks_repo_name": "rachelslaybaugh/munk-disseration", "max_forks_repo_head_hexsha": "e6dc6d6a8d5613cb30bca7dc4a2d419ad1b36e65", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.3402061856, "max_line_length": 107, "alphanum_fraction": 0.7609831521, "num_tokens": 4931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331606115021, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.31218525304446704}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\marginpar{Tuesday\\\\ 2021-11-30}\n\nWe want to introduce some thermodynamic quantities for the plasma. \n\nLet us start from the MHD equations: \n%\n\\begin{align}\n\\pdv{\\rho }{t} + \\vec{\\nabla} \\cdot (\\rho \\vec{u}) &=  0 \\\\\n\\rho \\dv{\\vec{u}}{t} + \\rho \\vec{u} \\cdot \\vec{\\nabla} \\vec{u} &= - \\vec{\\nabla} P + \\frac{1}{4 \\pi } \\qty(\\vec{\\nabla} \\times \\vec{B}) \\times \\vec{B}\n\\,.\n\\end{align}\n\nWe introduce the additional assumption that the plasma is isentropic: \n%\n\\begin{align}\n\\qty[ \\pdv{}{t} + \\vec{u} \\cdot \\vec{\\nabla}] P \\rho^{-\\gamma } = 0\n\\,,\n\\end{align}\n%\nas well as the magnetic field equations: \n%\n\\begin{align}\n\\vec{\\nabla} \\cdot \\vec{B} &= 0  \\\\\n\\pdv{\\vec{B}}{t} + \\vec{\\nabla} \\times \\qty(\\vec{u} \\times \\vec{B}) &= 0\n\\,.\n\\end{align}\n\nWe can always put ourselves in a frame which is at equilibrium: \\(\\vec{u} = 0\\), which we then perturb with \\(\\delta \\vec{u}\\). \n\nThen, we move to Fourier space and do first-order perturbation theory: we find \n%\n\\begin{align}\n-i \\omega \\delta \\rho + i \\vec{k} \\cdot \\delta \\vec{u} \\rho &= 0  \n\\,.\n\\end{align}\n\nThe entropy equation becomes \n%\n\\begin{align}\n\\pdv{P }{t} \\rho^{-\\gamma } - \\gamma \\rho^{-\\gamma -1} P \\pdv{\\rho }{t} &= 0  \\\\\n- i \\omega \\delta P + \\gamma \\rho^{-\\gamma -1} P i \\omega \\delta \\rho  &= 0  \\\\\n- i \\omega \\delta P + \\gamma \\frac{P}{\\rho } i \\omega \\delta \\rho &= 0  \\\\\n\\pdv{ \\delta P}{ \\delta \\rho } &= \\gamma \\frac{P}{\\rho } = c_s^2\n\\,,\n\\end{align}\n%\nso we have found acoustic perturbations by allowing the plasma to be compressible. \n\nThe no-monopoles equation becomes \\(i \\vec{k} \\cdot \\delta \\vec{B} = 0\\); while the last one can only be perturbed like \n%\n\\begin{align}\n- i \\omega \\delta \\vec{B} &= i \\vec{k} \\times \\qty( \\delta \\vec{u} \\times \\vec{B})  \\\\\n\\delta \\vec{B} &= - \\frac{\\vec{k}}{\\omega } \\times \\qty( \\delta \\vec{u} \\times \\vec{B}) \n\\,.\n\\end{align}\n\nThe momentum conservation law becomes \n%\n\\begin{align}\n- i \\omega  \\rho \\delta \\vec{u}  &= - i \\vec{k} \\delta P + \\frac{i \\vec{k}}{4 \\pi } \\times \\delta \\vec{B} \\times \\vec{B}_0   \\\\\n&= - i \\vec{k} c_s^2 \\delta \\rho - \\frac{i}{4 \\pi \\omega } \\vec{k} \\times \\qty(\\vec{k} \\times \\qty( \\delta \\vec{u} \\times \\vec{B}_0)) \\times \\vec{B}_0  \\\\\n- i \\omega \\rho \\delta \\vec{u} &= \n- i \\vec{k} c_s^2 \\frac{\\rho}{\\omega } \\vec{k} \\cdot \\delta \\vec{u} - \\frac{i}{4 \\pi \\omega } \\vec{k} \\times \\qty(\\vec{k} \\times \\qty( \\delta \\vec{u} \\times \\vec{B}_0)) \\times \\vec{B}_0\n\\marginnote{Used \\(\\delta \\rho = (\\rho / \\omega ) \\vec{k} \\cdot \\delta \\vec{u}\\).} \n\\,.\n\\end{align}\n\nThis is now all written in terms of \\(\\delta \\vec{u}\\), and it contains all MHD perturbations. \n\nLet us look at some specific cases: first, assume \\(\\vec{B}_0 = B_0 \\hat{z}\\), and that \\(\\vec{k}\\) is parallel to it, so \\(\\vec{k} = k \\hat{z}\\). \n\nThe cross product term reads:\n%\n\\begin{align}\n\\delta \\vec{u} \\times \\vec{B}_0 &= \\left[\\begin{array}{c}\n\\delta u_y B_0  \\\\ \n- \\delta u_x B_0  \\\\ \n0\n\\end{array}\\right]  \\\\\n\\vec{k} \\times (\\delta \\vec{u} \\times \\vec{B}_0) &= \\left[\\begin{array}{c}\nk \\delta u_x B_0  \\\\ \nk \\delta u_y B_0  \\\\ \n0\n\\end{array}\\right] \\\\\n\\vec{k} \\times \\qty(\\vec{k} \\times (\\delta \\vec{u} \\times \\vec{B}_0)) &= \\left[\\begin{array}{c}\n-k^2 \\delta u_y B_0  \\\\ \nk^2 \\delta u_x B_0  \\\\ \n0\n\\end{array}\\right] \n\\\\\n\\qty[\\vec{k} \\times \\qty(\\vec{k} \\times (\\delta \\vec{u} \\times \\vec{B}_0))]\\times \\vec{B}_0 &= \\left[\\begin{array}{c}\nk^2 \\delta u_x B_0^2  \\\\ \nk^2 \\delta u_y B_0^2s  \\\\ \n0\n\\end{array}\\right] \n\\,.\n\\end{align}\n\nThe equation is therefore \n%\n\\begin{align}\n- i \\omega \\rho \\left[\\begin{array}{c}\n\\delta u_x \\\\ \n\\delta u_y \\\\ \n\\delta u_z\n\\end{array}\\right]\n&= -i c_s^2 \\frac{\\rho}{\\omega } \n\\left[\\begin{array}{c}\n0 \\\\ \n0 \\\\ \nk\n\\end{array}\\right] k \\delta u_z \n- \\frac{i}{4 \\pi \\omega } \n\\left[\\begin{array}{c}\nk^2 \\delta u_x B_0^2  \\\\ \nk^2 \\delta u_y B_0^2s  \\\\ \n0\n\\end{array}\\right] \n\\,,\n\\end{align}\n%\nwhere we can see that the perpendicular and parallel modes are decoupled: the \\(z\\) mode reads \n%\n\\begin{align}\n\\omega \\rho \\delta u_z = c_s^2 \\frac{\\rho}{\\omega } k^2 \\delta u_z \\implies \\omega^2 = k^2 c_s^2\n\\,,\n\\end{align}\n%\ntherefore the \\emph{longitudinal} modes are \\emph{sound waves}! \nFor those modes the magnetic field is irrelevant since \\(\\delta \\vec{u} \\times \\vec{B}_0 = 0\\). \n\nWhat about the other directions? We find \n%\n\\begin{align}\n\\omega \\rho = \\frac{k^2B_0^2}{4 \\pi \\omega } \\implies \\omega^2 = k^2 \\frac{B_0^2}{4 \\pi \\rho } = k^2 v_A^2\n\\,,\n\\end{align}\n%\nso these are Alfén waves. \nThis tells us that these are \\emph{transverse} waves, but still propagating \\emph{along} the magnetic field. \n\nWhat is the magnetic field perturbation? \n%\n\\begin{align}\n\\delta \\vec{B} &= - \\frac{1}{\\omega } \\vec{k} \\times \n\\qty( \\delta \\vec{u} \\times \\vec{B}_0)  \\\\\n&= - \\frac{1}{\\omega } \\left[\\begin{array}{c}\nk B_0 \\delta u_x \\\\ \nk B_0 \\delta u_y \\\\ \n0\n\\end{array}\\right]\n\\,,\n\\end{align}\n%\nwhich means that the magnetic field is also only oscillating along the \\(x\\) and \\(y\\) directions. \n\nWe can also compute the induced electric field: \n%\n\\begin{align}\n\\delta \\vec{E} = - \\frac{1}{c} \\delta \\vec{u} \\times \\vec{B}_0 = \\left[\\begin{array}{c}\n \\delta u_y B_0 / c \\\\ \n\\delta u_x B_0 / c \\\\ \n0\n\\end{array}\\right]\n\\,.\n\\end{align}\n\nThe perturbations in the magnetic field, \\(\\sim B_0  \\delta u / v_A\\) are \\emph{larger} than the ones in the electric field, \\(\\sim B_0 \\delta u /c\\)! \nThis can be also checked when looking at the Lorentz force expression. \n\nLet us then look at the perpendicular modes: \\(\\vec{k} \\perp B_0 \\), specifically \\(\\vec{k} = k \\hat{x}\\). \n\n%\n\\begin{align}\n\\delta \\vec{u} \\times \\vec{B}_0 &= \\left[\\begin{array}{c}\n\\delta u_y B_0  \\\\ \n- \\delta u_x B_0  \\\\ \n0\n\\end{array}\\right]  \\\\\n\\vec{k} \\times (\\delta \\vec{u} \\times \\vec{B}_0) &= \n\\left[\\begin{array}{c}\n0 \\\\ \n0 \\\\ \n- k \\delta u_x B_0 \n\\end{array}\\right] \\\\\n\\vec{k} \\times \\qty(\\vec{k} \\times (\\delta \\vec{u} \\times \\vec{B}_0)) &= \n\\left[\\begin{array}{c}\n0 \\\\ \nk^2 \\delta u_x B_0  \\\\ \n0\n\\end{array}\\right] \\\\\n\\qty[\\vec{k} \\times \\qty(\\vec{k} \\times (\\delta \\vec{u} \\times \\vec{B}_0))]\\times \\vec{B}_0 &= \n\\left[\\begin{array}{c}\nk^2 \\delta u_x B_0^2 \\\\ \n0  \\\\ \n0\n\\end{array}\\right]\n\\,.\n\\end{align}\n\nPlugging this into the equation yields \n%\n\\begin{align}\n- i \\omega \\rho \\left[\\begin{array}{c}\n\\delta u_x \\\\ \n\\delta u_y \\\\ \n\\delta u_z\n\\end{array}\\right]\n= - i \\left[\\begin{array}{c}\nk \\\\ \n0 \\\\ \n0\n\\end{array}\\right]\nc_s^2 \\frac{\\rho}{\\omega } k \\delta u_x\n- \\frac{i}{4 \\pi \\omega } \\left[\\begin{array}{c}\nk^2 B_0^2 \\delta u_x \\\\ \n0 \\\\ \n0\n\\end{array}\\right]\n\\,,\n\\end{align}\n%\nwhich means that the only nonzero component, along \\(x\\), reads \n%\n\\begin{align}\n\\omega^2 = \\qty(c_s^2 + \\frac{B_0^2}{4 \\pi \\rho })k^2 = \\qty(c_s^2 + v_A^2) k^2\n\\,,\n\\end{align}\n%\nwhich is commonly called a ``fast'' \\textbf{magnetosonic mode}. \n\nFor the rest of the course we will focus on the Alfvén modes. \n\n\\section{High energy particles}\n\nWe start by assuming we already have a non-thermal, high energy particle. \n\nThe momentum of the particle is \\(\\vec{p} = m \\vec{v} \\gamma \\), while the field is \\(\\vec{B}_0 = B_0 \\hat{z}\\). \n\nThe energy of this particle will not change under the action of the magnetic field; the Lorentz force's action means we will have \n%\n\\begin{align}\n\\dv{\\vec{p}}{t} = q \\frac{\\vec{v}}{c} \\vec{B}_0\n\\,,\n\\end{align}\n%\ntherefore \n%\n\\begin{align}\nm \\gamma \\dv{v_x}{t} = q \\frac{v_y}{c} B_0 \\marginnote{\\(\\gamma \\) is a constant: the energy cannot change.}\\\\\nm \\gamma \\dv{v_y}{t} = - q \\frac{v_x}{c} B_0 \\\\\n\\dv{v_z}{t} = 0\n\\,.\n\\end{align}\n\nPutting these together we get \n%\n\\begin{align}\n\\qty(\\frac{m \\gamma }{q B_0 })^2 \\dv[2]{v_x}{t} &= - v_x  \\\\\n\\dv[2]{v_x}{t} &= - \\Omega^2 v_x\n\\,. \n\\end{align}\n\nIf \\(\\gamma = 1\\), this is the cyclotron frequency; otherwise, it is just \\(\\Omega = q B_0 / (m c \\gamma )\\). \n\nIf \\(\\mu \\) is the cosine of the angle between the initial velocity and the magnetic field, the solution will read \n%\n\\begin{align}\nv_x (t) &= v_0 (1 - \\mu^2)^{1/2} \\cos( \\Omega t) \\\\\nv_y (t) &= v_0 (1 - \\mu^2)^{1/2} \\sin( \\Omega t)  \\\\\nv_z (t) &= v_0 \\mu \n\\,.\n\\end{align}\n\nWhat happens if this trajectory is perturbed, say, by an Alfvén wave? \nThe field will now be \\(\\vec{B} = \\vec{B}_0 + \\delta \\vec{B}\\), and we will work to first order in \\(\\delta \\vec{B}\\). \n\nLet us assume one of these two things: \n\\begin{enumerate}\n    \\item we sit in a reference frame moving with the waves, so that the electric field perturbation vanishes;\n    \\item we decide to neglect the electric field since we know its effect to be small.\n\\end{enumerate}\n\nThere is a subtle difference between the two. \n\nWe assume that the polarization of the electric field perturbation is circular: \\(\\delta E_y = \\pm i \\delta E_x\\), so that \\(\\delta B_x = \\mp \\delta B_y\\). \n\nWe take \n%\n\\begin{align}\n\\delta B_y &= \\exp(i \\qty(kz - \\omega t + \\varphi )) \n\\,,\n\\end{align}\n%\nwhere we insert an arbitrary initial phase we will later average over. \n\nIf we take the real part of the perturbation, we get \n%\n\\begin{align}\n\\delta B_x &= \\pm \\sin(kz - \\omega t + \\varphi ) \\\\ \n\\delta B_y &= \\pm \\cos(kz - \\omega t + \\varphi ) \n\\,.\n\\end{align}\n\nThis is an Alfvén wave, so \\(\\omega = k v_A\\). \n\nIf we assume that the electric field is negligible, the equations of motion for the particle will be modified as \n%\n\\begin{align}\n\\dv{\\vec{p}}{t} = q \\frac{\\vec{v}}{c} \\times \\qty(\\vec{B}_0 + \\delta \\vec{B})  &= \\frac{q}{c} \\left[\\begin{array}{ccc}\n\\hat{x}  & \\hat{y} & \\hat{z} \\\\ \nv_x & v_y & v_z \\\\ \n\\delta B_x & \\delta B_y & B_0 \n\\end{array}\\right]  \\\\\nm \\gamma \\dv{}{t} \\left[\\begin{array}{c}\nv_x \\\\ \nv_y \\\\ \nv_z\n\\end{array}\\right]\n&= \n\\left[\\begin{array}{c}\nv_y B_0 - v_z \\delta B_y \\\\ \n- v_x B_0 + \\delta B_x v_z \\\\ \nv_x \\delta B_y - v_y \\delta B_x\n\\end{array}\\right]\n\\,.\n\\end{align}\n\nLooking at the \\(z\\) component, we see that the perturbation changes \\(v_z\\), but \\(v_0 \\) is constant, so the pitch angle \\(\\mu \\) must be changeing. \n\nWhy is this relevant? We know that spallation must occur, so the cosmic rays must remain in the galaxy for a while. \nThis can be a mechanism to explain that. \n\nWe focus on the \\(z\\) equation: \n%\n\\begin{align}\nm \\gamma \\dv{v_z}{ t} &= \n\\frac{q}{c} \\delta B v_0 (1 - \\mu^2)^{1/2} \n\\qty(\n\\cos(\\Omega t) \\cos( k z  - \\omega t + \\varphi ) \n\\pm \n\\sin(\\Omega  t) \\sin(k z - \\omega t + \\varphi )  )\n\\\\\nm \\gamma v_0 \\dv{\\mu }{t} &= \\frac{q \\delta B}{mc \\gamma } v_0 (1 - \\mu^2)^{1/2}  \n\\qty(\\cos(\\Omega t) \\cos(k z - \\omega t + \\varphi ) \\pm \\sin(\\Omega t) \\sin(kz - \\omega t + \\varphi ))  \\\\\n\\dv{\\mu }{t}&= \\frac{q \\delta B}{mc \\gamma } v_0 (1 - \\mu^2)^{1/2}\n\\cos(\\Omega t \\mp kz \\pm \\omega t \\mp \\varphi ) \n\\marginnote{Used some ugly prostapheresis formulae.}\n\\,.\n\\end{align}\n\nNow, however, \\(kz \\approx k v_0 \\mu t\\); however, \\(\\omega t \\approx k v_A t\\), so unless \\(\\mu \\lesssim v_A /c \\) the latter is negligible. \n\nIn normal conditions, \\(v_A \\ll v_0 \\sim c\\), and this is a requirement of the order of \\(\\num{e-6}\\). \n\nThe falsifying example is a particle moving basically moving in a circle without any \\(z\\) component to its velocity, but this is very unlikely. \n\nThe wave, for the relativistic particle, is basically stationary. \n\nSo, \n%\n\\begin{align}\n\\dv{\\mu }{t} = \\frac{q \\delta B}{mc \\gamma } (1 - \\mu )^{1/2} \\cos(\\Omega t \\mp kv_0 \\mu t \\mp \\varphi ) \n\\,.\n\\end{align}\n\nTo find out what the effect of this is over a long period of time we need to integrate. \n\nThe mean value of the cosine vanishes, however, we can have a diffusion-like process. \nOn average, \\(\\expval{ \\Delta \\mu }= 0\\), but we might want to compute \\(\\expval{ \\Delta \\mu \\Delta \\mu }\\):\nthis will be \n%\n\\begin{align}\n\\expval{\\Delta \\mu  \\Delta \\mu } = \\qty(\\frac{q \\delta B}{mc \\gamma })^2 (1 - \\mu^2) \\int_0^{T} \\dd{t} \\int_0^{T} \\dd{t'} \n\\cos ( (\\Omega \\mp v_0 k \\mu ) t \\mp \\varphi )\n\\cos ( (\\Omega \\mp v_0 k \\mu ) t' \\mp \\varphi )\n\\,,\n\\end{align}\n%\nwhere the first thing we want to do is to also take an average over \\(\\varphi \\): \n%\n\\begin{align}\n\\expval{\\Delta \\mu  \\Delta \\mu } &= \\qty(\\frac{q \\delta B}{mc \\gamma })^2 (1 - \\mu^2) \\frac{1}{2} \\int_0^{T} \\dd{t} \\int_0^{T} \\dd{t'} \n\\cos ( (\\Omega \\mp v_0 k \\mu ) (t-t'))  \\\\\n&= \\qty(\\frac{q \\delta B}{mc \\gamma }) (1 - \\mu^2) \\frac{2 \\pi }{2} T \\delta (\\Omega \\mp v_0 k \\mu )  \\\\\n&= \\qty(\\frac{q \\delta B}{mc \\gamma }) (1 - \\mu^2) \\pi T \\delta (k \\mp \\frac{\\Omega}{v_0 \\mu })\n\\,,\n\\end{align}\n%\nso we do indeed get a diffusion-like motion with variance \\(\\sim T\\). \n\nHowever, this is only the case if \n%\n\\begin{align}\nk = \\pm \\frac{\\Omega }{v_0 \\mu } = \\pm \\frac{1}{r_L \\mu }\n\\,.\n\\end{align}\n\nSo, only if the wave is \\emph{resonant} with the Larmor radius then its pitch angle \\emph{diffuses}. \n\nThis remains quite close to being true even if the assumption of small \\(\\delta B\\) is relaxed. \n\nMore specifically, \n%\n\\begin{align}\nk = \\pm \\frac{\\text{sign}\\ q}{\\abs{r_L} \\mu }\n\\,.\n\\end{align}\n\nIt is customary to introduce a \\emph{diffusion coefficient}: \n%\n\\begin{align}\nD_{\\mu \\mu } &= \\frac{1}{2} \\expval{\\frac{\\Delta \\mu \\Delta \\mu }{\\Delta t}} \n= \\frac{1}{2} \\qty(\\frac{q \\delta B}{mc \\gamma })^2 (1 - \\mu^2)  \\frac{\\pi}{v_0 \\mu } \\delta (k \\mp \\frac{\\Omega }{v_0 \\mu } )  \\\\\n&= \\qty( \\frac{q B_0 }{mc \\gamma })^2 \\frac{ \\delta B^2}{B_0^2} (1 - \\mu^2) \\frac{\\pi }{2 v_0 \\mu } \\delta (k \\mp \\frac{\\Omega}{\\mu v_0 }) \n\\,.\n\\end{align}\n\nThis is useful since in general \\(\\delta B\\) will depend on the scale: there are no monochromatic Alfvén waves in nature. \nTherefore, \n%\n\\begin{align}\nD_{\\mu \\mu } &= \\Omega^2 (1 - \\mu^2) \\frac{\\pi}{2 v_0 \\mu } \\int \\dd{k} \\frac{ \\delta B^2 (k)}{B_0^2} \\delta (k \\mp \\frac{\\Omega}{v_0 \\mu })  \\\\\n&= \\Omega^2 (1 - \\mu^2) \\frac{\\pi }{2 v_0 \\mu } \\frac{ \\delta B^2 (k _{\\text{res}})}{B_0^2}  \\\\\n&= \\frac{\\pi}{2} \\Omega (1 - \\mu^2) k _{\\text{res}} F(k _{\\text{res}})\n\\,,\n\\end{align}\n\nwhere \n%\n\\begin{align}\nF (k _{\\text{res}}) = \\frac{1}{B_0^2} \\delta B^2 (k _{\\text{res}})\n\\,.\n\\end{align}\n\nWe can also compute \\(D_{\\theta \\theta }\\): \n%\n\\begin{align}\nD_{\\theta \\theta } = \\frac{\\pi}{2} \\Omega k _{\\text{res}} F(k _{\\text{res}})\n\\,.\n\\end{align}\n\nHow long does it take to have a diffusion by, say, 1 radian? it will be \n%\n\\begin{align}\n\\tau \\sim \\frac{1}{D_{\\theta \\theta }} \\sim \\frac{1}{\\Omega k _{\\text{res}} F(k _{\\text{res}})}\n\\,.\n\\end{align}\n\n\\begin{figure}[ht]\n\\centering\n\\includegraphics[width=\\textwidth]{figures/diffusion_over_time}\n\\caption{Diffusion over time. The evolution is shown for a relativistic proton with \\(\\gamma = 10\\), moving across a field \n\\(B_0 = \\SI{2}{\\micro\\gauss}\\) \nwith a perturbation \\(\\delta B = \\num{e-4} B_0 \\), with the \\(+\\) circular polarization (i.\\ e.\\ all the \\(\\pm\\) become \\(+\\), all the \\(\\mp\\) become \\(-\\)). A white mark on the wavenumber scale marks \\(k = \\Omega v_0 \\cos \\theta \\), at which the ``resonance'' happens.}\n\\label{fig:diffusion_over_time}\n\\end{figure}\n\n\\begin{figure}[ht]\n\\centering\n\\includegraphics[width=\\textwidth]{figures/final_point_variation}\n\\caption{\\(\\Delta \\theta \\) corresponding to the end of the integrated curves in figure \\ref{fig:diffusion_over_time}.}\n\\label{fig:final_point_variation}\n\\end{figure}\n\n\\todo[inline]{There seems to be a high tail at high \\(k\\)!}\n\n\\end{document}\n", "meta": {"hexsha": "d05e2597b6f59ffd9525b06a2e71f8bc3c718356", "size": 15082, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "phd_courses/theoretical_high_energy_astroparticle/nov30.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "phd_courses/theoretical_high_energy_astroparticle/nov30.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phd_courses/theoretical_high_energy_astroparticle/nov30.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 31.9533898305, "max_line_length": 270, "alphanum_fraction": 0.6214693012, "num_tokens": 5753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3121852455350198}}
{"text": "\\documentclass[12pt]{article}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{geometry}\n\\usepackage{enumerate}\n\\usepackage{natbib}\n\\usepackage{float}%稳定图片位置\n\\usepackage{graphicx}%画图\n\\usepackage[english]{babel}\n\\usepackage{a4wide}\n\\usepackage{indentfirst}%缩进\n\\usepackage{enumerate}%加序号\n\\usepackage{multirow}%合并行\n\\title{\\large UM-SJTU JOINT INSTITUTE\\\\Advanced Lasers and Optics Laboratory\\\\(VE438)\\\\\\ \\\\\\ \\\\\\ \\\\\\ \\\\\\ \\\\\\ \\\\\\ \\\\\\ \\\\\\ \\\\\\ \\\\\\\nPre Lab Assignment\\\\\\ \\\\\\ LAB 6\\\\\\ Acoustic-Optic Modulator \\\\\\ \\\\\\ \\\\\\ \\\\\\ \\\\\\ }\n\\author{Name: Pan Chongdan \\\\ID: 516370910121}\n\\date{Date: \\today}\n\n\\begin{document}\n\\maketitle\n\\newpage\n\\section{Answers for Pre Lab Questions}\n\\subsection{Question 1}\nAOM is equivalent to a granting with period $d=\\lambda_{sound}$, so that the relationship can be expressed as $\\lambda_{sound}(\\sin\\theta\\pm\\sin i)=m\\lambda$ where $i$ is the incident angle and $\\theta$ is the diffraction angle, $m$ is the order, $\\lambda$ is the wavelength of light and $\\lambda_{sound}$ is the wavelength of sound. According to Bragg condition, we can obtain the biggest diffraction angle with $\\sin\\theta=m\\frac{\\lambda}{\\lambda_{sound}}$. If we apply the frequency the sound, then the relation becomes $\\frac{v_{sound}}{f_{sound}}(\\sin\\theta\\pm\\sin i)=m\\lambda$, where $v_{sound}$ is the velocity of sound and $f_{sound}$ is sound's frequency.\n\\par When the light passes through the sound, its frequency $f'=f_{light}+f_{sound}$, then it's wavelength becomes $\\lambda'=\\frac{c}{f_{light}+mf_{sound}}$\n\\subsection{Question 2}\nThe frequency shift is equal to $m\\omega$ where $m=0, \\pm1, \\pm2$ and the wavelength becomes $\\frac{c\\lambda}{c+m\\omega\\lambda}$, so the coherent length becomes $L=\\frac{\\lambda^2}{n(\\lambda-\\frac{c\\lambda}{c+m\\omega\\lambda})}$ where $n$ is the refractive index.\n\\end{document}", "meta": {"hexsha": "7f0f0b7555c680afcf31e6b6778da99be77df7c9", "size": 1820, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "VE438Optics/HW/L6/PreLab/PreLab6.tex", "max_stars_repo_name": "PANDApcd/Physics", "max_stars_repo_head_hexsha": "ed8171e5872ecef1d3e3e81935d71bc65063fc95", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "VE438Optics/HW/L6/PreLab/PreLab6.tex", "max_issues_repo_name": "PANDApcd/Physics", "max_issues_repo_head_hexsha": "ed8171e5872ecef1d3e3e81935d71bc65063fc95", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "VE438Optics/HW/L6/PreLab/PreLab6.tex", "max_forks_repo_name": "PANDApcd/Physics", "max_forks_repo_head_hexsha": "ed8171e5872ecef1d3e3e81935d71bc65063fc95", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 65.0, "max_line_length": 664, "alphanum_fraction": 0.7241758242, "num_tokens": 570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.31218523802557263}}
{"text": "\\documentclass[draft]{report}\n\\usepackage{trsym} \n\\usepackage{trmath} \n\n\\usepackage[T2A]{fontenc}\n\\usepackage[russian]{babel}\n\n\\begin{document}\n\n\\section{$\\mathcal{M\\!AT\\!H}$\\protect\\footnote{patched one}}\n\n\\subsection{Proofs}\n\\label{sub:proofs}\n\n\n\n\\begin{tproof}[kek?]\n  $\\sin\\pi=0$ (o'rly?)\n  \\begin{lproof}[nested]\n    another one\n    \\begin{pproof}[another crazy statement]\n      $\\Pi\\neq\\pi$\n      {%\n        \\fboxsep=0pt\n        \\fbox{$\\bigcirc$}\\fbox{$\\mathord{\\Rightarrow}\\vphantom{<}$}\n      }%\n      \\circlearound{$\\mathord{\\Rightarrow}\\vphantom{>}$}%\n      $\\circlearound{\\alpha}\\,\\circlearound{1}$\n    \\end{pproof}\n  \\end{lproof}\n\\end{tproof}\n\n\n\\begin{thrm}$1+1=2$\\end{thrm}\\begin{prf}obvious, unless you are a Bourbakist\\end{prf}\n\\begin{lem}$1\\neq2$\\end{lem}\\begin{prf}see above\\end{prf}\n\n\n\n\n\\subsection{Vectors (\\coori, \\conori)}\n\n\n\\end{document}\n", "meta": {"hexsha": "15c19d5feb3d53dc419520f9aee21b812fbf0208", "size": 861, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "t/sty/math/math.tex", "max_stars_repo_name": "taxus-d/tarantas", "max_stars_repo_head_hexsha": "acbfc86d2348cec5f68bbd5861be1cda23893b8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-01-14T13:18:17.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T13:18:17.000Z", "max_issues_repo_path": "t/sty/math/math.tex", "max_issues_repo_name": "taxus-d/tarantas", "max_issues_repo_head_hexsha": "acbfc86d2348cec5f68bbd5861be1cda23893b8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-01-14T13:14:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-14T13:14:58.000Z", "max_forks_repo_path": "t/sty/math/math.tex", "max_forks_repo_name": "taxus-d/tarantas", "max_forks_repo_head_hexsha": "acbfc86d2348cec5f68bbd5861be1cda23893b8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.5681818182, "max_line_length": 85, "alphanum_fraction": 0.6504065041, "num_tokens": 320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.31210950787039177}}
{"text": "\\chapter{System call based detection}\n\\label{chap:syscalltheory}\nIn this chapter, the overall strategy of our second approach for malware detection is discussed, which uses system call traces of applications to predict malicious activity. The next chapter (chapter~\\ref{chap:syscallexperiment}) discusses the implementation details of this model. The results achieved in the experiment using this model is detailed and explained in chapter~\\ref{chap:results}.\\\\\n\nThe central idea is to run an application for a specific amount of time. During its execution, the details about the system calls it makes to the operating system are recorded. We developed a machine learning model/classifier that can detect malware based on its system call trace. The syscall records of known malwares and known non-malwares are used to train the classifier. There are two phases: training and classification. How the known malware and non-malware traces will be used to train the classifier is described in section ~\\ref{sec:syscalltheorytrain}. Section~\\ref{sec:syscalltheoryclassify} decribes how the model will classify an unknown app using its syscall trace.\\\\\n\n\\section{Training}\n\\label{sec:syscalltheorytrain}\nWe used a set of applications consisting both known malwares and known non-malwares as the training dataset. We collected system call traces of all applications of the training dataset (all of the applications are run for a specific amount of time). The system call trace of a single application is a list of system calls the application used during execution. For example: \\textbf{\\{recv, semget, msgget, \\ldots \\}}; where \\textbf{recv}, \\textbf{semget}, \\textbf{msgget} are system calls.\\\\\n\nAfter collecting system call traces, We aggregate this traces to create two binary relation matrices $M_{mal}$ and $M_{nmal}$. $M_{mal}$ shows relation between system calls and malware applications, Where $M_{nmal}$ shows relationship between system calls and non-malwares. $M_{mal}$ and $M_{nmal}$ matrices are defined as follows:\\\\\n\\[ M_{mal}(i,j) =\n  \\begin{cases}\n      1       & \\quad \\text{if } i^{th} \\text{ malware uses } j^{th} \\text{ syscall}\\\\\n      0       & \\quad \\text{otherwise}\\\\\n  \\end{cases}\n\\]\\\\\n\\[ M_{nmal}(i,j) =\n  \\begin{cases}\n      1       & \\quad \\text{if } i^{th} \\text{ non-malware uses } j^{th} \\text{ syscall}\\\\\n      0       & \\quad \\text{otherwise}\\\\\n  \\end{cases}\n\\]\n\\\\\\\\\nThen we calculate the Goodness Rating of $j^{th}$ syscall, $\\gamma_j$ as follows,\n\\[\n\\gamma_j = \\frac{1}{N_{nmal}}\\sum_{i=1}^{N_{nmal}} M_{nmal}(i,j) - \\frac{1}{N_{mal}}\\sum_{i=1}^{N_{mal}} M_{mal}(i,j)\n\\]\nwhere $N_{nmal}$ and $N_{mal}$ are number of non-malware and malware samples.\n\\\\\n\\section{Classification}\n\\label{sec:syscalltheoryclassify}\nTo classify an unknown application as \\emph{malware} or \\emph{non-malware}, first, we execute the application for the same time duration duration we used with each training application. We collect the system call trace of that application during that execution, same as before. But this time, we also record the frequency of each syscall used by the application during execution. So now, the syscall trace of an application during classification phase can be expressed as a list of pairs of syscalls and their frequencies. For example: \\textbf{\\{(recv,1032), (semget, 143), \\ldots \\}} is a trace of an application which called the \\textbf{recv} routine 1032 times, \\textbf{semget} 143 times and so on.\n\nThen we define the Goodness Rating of that application, $\\gamma_{app}$ as follows,\n\\[\n\\gamma_{app} = \\sum_{s \\in S_{app}} \\gamma_s \\times f_s\n\\]\n\nWhere, $S_{app}$ is the set of system calls used by $app$, $\\gamma_s$ is the Goodness rating of syscall $s$ and $f_s$ is the frequency of syscall $s$ in $app$.\n\nIf we assume that malwares uses similar system calls which are distinctive from those used by non-malwares; It is logical to assume that a malware will use more syscalls those has lower goodness ratings and less syscalls having higher goodness ratings. The opposite can be said for non-malware applications. So this will result in higher goodness ratings of non-malware applications and lower goodness rating for malware applications.\n\nNow for classification, we check if the goodness rating of the application under inspection exceeds some threshold. If so, we classify it as non-malware. Otherwise we flag it as malware. \n\\[\n\\begin{cases}\n      \\text{app is not a malware}  & \\quad \\text{if } \\gamma_{app} > \\tau\\\\\n      \\text{app is a malware} & \\quad \\text{otherwise}\\\\\n  \\end{cases}\n\\]\n\nWhere, $\\tau$ is a threshold. Theoretically, the threshold should be zero. But it actually depends on the experiment and the training data used. We used this approach to classify apps in our validation dataset and calculated \\textbf{accuracy} ($\\alpha$), \\textbf{recall} ($\\rho$), \\textbf{specificity} ($\\sigma$), \\textbf{precision} ($\\phi$) and \\textbf{f-measure} ($F$). These metrics are defined in section~\\ref{sec:netanalysisresults}.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\\chapter{Experiment on System call based classifier}\n\\label{chap:syscallexperiment}\nIn this chapter, we went into details on the experiment we conducted to validate our model. \n\n\\section{Preparing experiment}\n\\label{sec:syscallexpprepare}\nWe collected system call traces of all applications using a single device. The reason behind this is we intended to provide identical environments for all applications to execute in. The device was reset to factory default configuration and the device needed to be \\emph{rooted}. We used standard linux utility \\emph{strace} to trace system call of applications. We also used \\emph{timeout} command to run every application for a fixed duration of time. Although \\emph{strace} and \\emph{timeout} are standard linux utilities, they are not included in standard Android builds. So we had to collect the source code of this tools and cross-compile them for the CPU architecture of the device on which the experiment was run. The compilation task required \\emph{Android NDK}. After the binaries are created for our desired CPU architecture (in our case \\textbf{ARMv7}), they are put in the \\textbf{/system/xbin} of our device, so that they can be accessed by a shell script run through \\emph{ADB}. Copying any binary into \\textbf{/system} requires superuser permission, that is one of the reasons why we needed to \\emph{root} our device at the first place. Additionally, necessary drivers and Android SDK are required on the host machine, where the script would run.\n\n\\section{Experiment}\n\\label{sec:syscallexpsim}\nWe planned to collect system call traces of a total of 453 malwares and 227 non-malwares. The number of apps used in validation and training is shown in table~\\ref{table:numofapps}. \n\n\\begin{table}[h]\n    \\centering\n    \\bgroup\n    \\def\\arraystretch{1.9}%\n    \\begin{tabular}{ |c|c|c|c|} \n    \\hline\n    & Training & Validation & Total\\\\ \n    \\hline\n    Malware & 403 & 50 & 453\\\\  \n    \\hline\n    Non-malware & 177 & 50 & 227\\\\  \n    \\hline\n    \\end{tabular}\n    \\caption{Number of apps used in the experiment}\n    \\label{table:numofapps}\n    \\egroup\n\\end{table}\n\n\nWe wrote a batch script that automates the whole process. The script executes commands in the device using \\emph{ADB}. The workflow of the script is outlined in Algorithm~\\ref{algo:mainsimulation}.\n\n\\begin{algorithm}\n\\caption{Syscall trace collect script}\\label{algo:mainsimulation}\n\\begin{algorithmic}[1]\n\\Procedure{Collect-All-Syscall-Trace}{$directory$}\n\\For{each apk file in $directory$}\n\\State $pckgname \\gets$ get package name from that apk using \\textbf{aapt}\n\\State Install the apk in the device.\n\\State Launch the app\n\\State $pid \\gets$ ps($pckgname$)\n\\State $stracelogs[pckgname] \\gets$ output of \\textbf{strace($pid$)} with 20 seconds timeout \n\\State Force close the app\n\\State Uninstall the app\n\\EndFor\n\\State \\textbf{return} $stracelogs$\n\\EndProcedure\n\\end{algorithmic}\n\\end{algorithm}\n\nThe exact script is given in appendix~\\ref{chap:script}.\\\\\n\nWe have two directories, one containing 453 malwares apks and another containing 227 non-malware apks. The malware samples are collected from \\emph{Android Malware Genome Project}. The non-malwares are directly downloaded from Google Play Store. We run the script twice. Once given the directory of malwares, and again for directory of non-malwares. After the execution, we are left with 453 malware trace files and 227 non-malware trace files. A sample single trace file is shown in figure~\\ref{fig:single-strace-log}.\n\n\\begin{figure}[h!]\n    \\centering\n    \\includegraphics[width=1\\textwidth]{single-strace-log.png}\n    \\caption{System call trace of an application}\n    \\label{fig:single-strace-log}\n\\end{figure}\n\n\\section{Evaluating our model}\n\\label{sec:syscalleval}\n\nWe wrote a java program which further processes these files and assess our model. The code is given in appendix~\\ref{chap:code}.\n\nThe program divides the trace files into two datasets, training and validation. 50 malwares and 50 non-malware traces are chosen randomly and put in the validation dataset. The rest of the traces are used to train the classifier. The details of the training and classification steps are described in the following sub-sections.\n\n\\subsection{Training}\n\\label{subsec:syscallevaltrain}\n\nThe program aggregates all the traces in the training dataset and produce two relation matrices $M_{mal}$ and $M_{nmal}$. $M_{mal}$ and $M_{nmal}$ are defined in the previous chapter. A sample relation matrix is shown in figure~\\ref{fig:sample-matrix}.\n\n\\begin{figure}[h!]\n    \\centering\n    \\includegraphics[width=1\\textwidth]{relation_matrix2.png}\n    \\caption{A sample relation matrix between syscalls and apps}\n    \\label{fig:sample-matrix}\n\\end{figure}\n\nThe two relation matrices are used to calculate the \\textbf{Goodness rating}s of all syscalls.\n\n\\subsection{Classification}\n\\label{subsec:syscallevalclassify}\nAfter \\textbf{Goodness rating}s of all apps have been calculated, our model is ready to calssify an unlabeled app as malware or non-malware, given its system call trace. The same program calculates Goodness raings of all applications in the validation dataset, using the equation given in section~\\ref{sec:syscalltheoryclassify}. If the Goodness rating of an app is lower than a \\textbf{Threshold ($T$)}, our model/program flags the app as a malware, otherwise the app is considered to be non-malware.\\\\\n\nIn this chapter, we discussed the experiment for a single run. Actually the experiment was run multiple times, with different \\textbf{Threshold} values. The reason behind this and the results achieved from our experiment is outlined in the following chapter.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\\chapter{Results}\n\\label{chap:results}\nThe results achieved from our experiment described in chapter~\\ref{chap:syscallexperiment} is discussed in detail in this chapter.\\\\\n\nIn section~\\ref{sec:syscalltheoryclassify}, we introduced a \\textbf{Threshold} ($\\tau$) and stated that the value of this threshold should be derived experimentally. It is dependent on the training dataset. Therefore, to find a reasonable value for $\\tau$, we tried different thresholds and for each threshold, we ran our classifier for all validation apps and calculated different metrics like \\textbf{accuracy} ($\\alpha$), \\textbf{recall} ($\\rho$), \\textbf{specificity} ($\\sigma$), \\textbf{precision} ($\\phi$) and \\textbf{F-measure} ($F$). These metrics are defined in section~\\ref{sec:netanalysisresults}. We started from a threshold value of $-200$ and ended with $1500$, with step $10$. So the classifier was run a total of 171 times (each time with all validation apps).\\\\\n\nIdeally, the \\textbf{Threshold ($\\tau$)} should be zero, but our experiment showed better accuracy for other values. To be exact, the best accuracy (87\\%) is achieved when we use a threshold value between 300-340.\\\\\n\nThe \\textbf{Threshold ($\\tau$)} vs \\textbf{Accuracy} ($\\alpha$) graph is shown in Figure~\\ref{fig:thvsacc}.\\\\\n\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=1\\textwidth]{thvsacc2.png}\n    \\caption{\\textbf{Threshold ($\\tau$)} vs \\textbf{Accuracy} ($\\alpha$) graph}\n    \\label{fig:thvsacc}\n\\end{figure}\n\nThe effect of threshold on other performance metrics of the classifier is shown in Figure~\\ref{fig:thvsppv} to~\\ref{fig:thvsfm}.\\\\\n\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=1\\textwidth]{thvsprecision.png}\n    \\caption{\\textbf{Threshold ($\\tau$)} vs \\textbf{precision} ($\\phi$) graph}\n    \\label{fig:thvsppv}\n\\end{figure}\n\nWith increasing threshold, the classifier would tend to classify more apps as malware. So precision falls with increasing threshold. \\textbf{Threshold} ($\\tau$) vs \\textbf{precision} ($\\phi$) graph in figure~\\ref{fig:thvsppv} shows $\\phi = 87.8\\%$ for $\\tau = 320$, which is more than acceptable.\\\\\n\n\\textbf{Specificity} ($\\sigma$), also decreases as threshold increases. In figure~\\ref{fig:thvsspc}, \\textbf{Threshold} ($\\tau$) vs \\textbf{specificity} ($\\sigma$) graph shows $\\sigma = 82.7\\%$ for $\\tau = 320$. So $320$ is a good value for threshold considering specificity.\\\\\n\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=1\\textwidth]{thvsspc2.png}\n    \\caption{\\textbf{Threshold ($\\tau$)} vs \\textbf{specificity} ($\\sigma$) graph}\n    \\label{fig:thvsspc}\n\\end{figure}\n\nDetection rate of known malwares as malwares (recall) increases with threshold. Again, the \\textbf{Threshold ($\\tau$)} vs \\textbf{recall} ($\\rho$) graph in figure~\\ref{fig:thvstpr} shows an excellent value of \\textbf{recall}, $\\rho = 90.1\\%$ for $\\tau = 320$.\\\\\n\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=1\\textwidth]{thvsrecall.png}\n    \\caption{\\textbf{Threshold ($\\tau$)} vs \\textbf{recall} ($\\rho$) graph}\n    \\label{fig:thvstpr}\n\\end{figure}\n\nAnd at last, Figure~\\ref{fig:thvsfm} also shows an excellent \\textbf{f-measure} of $0.889$ for $\\tau = 320$.\\\\\n\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=1\\textwidth]{thvsfm2.png}\n    \\caption{\\textbf{Threshold ($\\tau$)} vs \\textbf{f-measure} ($F$) graph}\n    \\label{fig:thvsfm}\n\\end{figure}\n\nAccording to all these performance metrics, $320$ seems to be a very plausible value as \\textbf{Threshold}, ($\\tau$) for our model. The \\textbf{Confusion Matrix} of our model resulted from using $\\tau = 320$ is shown in Figure~\\ref{fig:confmatrix}.\\\\\n\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=0.75\\textwidth]{confmatrix.png}\n    \\caption{\\textbf{Confusion Matrix} with $\\tau = 320$}\n    \\label{fig:confmatrix}\n\\end{figure}\n\nAlthough we used widely variying types of malware and non-malware application samples in training and validation of our data, it is very difficult to amass a set of malware and non-malware apps that correctly emulates the distribution of all malwares in the wild and all non-malware apps in Google Play Store. So our experimentally achieved value for parameters like threshold might not be a good choice in all cases. But if we can feed the classifier a decent representative set of malwares and non-malwares, it should produce very usable results.\n\n", "meta": {"hexsha": "60491af07c4470da8ba3ddc5470bb31b2bfcc41d", "size": 15038, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "SyscallAnalysis/SyscallAnalysis.tex", "max_stars_repo_name": "devmhd/thesis-report-malware-detection-android", "max_stars_repo_head_hexsha": "65bb6ea3b06fa19b2534b072d01d624b978732b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-09-16T17:25:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-31T05:36:16.000Z", "max_issues_repo_path": "SyscallAnalysis/SyscallAnalysis.tex", "max_issues_repo_name": "devmhd/thesis-report-malware-detection-android", "max_issues_repo_head_hexsha": "65bb6ea3b06fa19b2534b072d01d624b978732b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SyscallAnalysis/SyscallAnalysis.tex", "max_forks_repo_name": "devmhd/thesis-report-malware-detection-android", "max_forks_repo_head_hexsha": "65bb6ea3b06fa19b2534b072d01d624b978732b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.4387351779, "max_line_length": 1262, "alphanum_fraction": 0.7506317329, "num_tokens": 3995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.31204981137321697}}
{"text": "$\\dagger$ Corresponding author: wkmor1@gmail.com\\\\\n1. School of BioSciences, the University of Melbourne, Parkville 3010, Victoria.\\\\\n2. Patuxent Wildlife Research Center, US Geological Survey, Laurel, MD 20708.\n\n\\newpage\n\n\\section*{Abstract}\\label{abstract}\n\\addcontentsline{toc}{section}{Abstract}\n\nValue of information (VOI) analyses reveal the expected benefit of reducing uncertainty to a decision maker. Most ecological VOI analyses have focused on population models rarely addressing more complex community models. We performed a VOI analyses for a complex state and transition model of Box-Ironbark Forest and Woodland management. With three management alternatives (limited harvest/firewood removal, ecological thinning and no management), managing the system optimally (for 150 years) with the original information, would on average, increase the amount of forest in a desirable state from 19 to 35\\% (a 16 percentage point increase). Resolving all uncertainty would, on average, increase the final percentage to 42\\% (a 19 percentage point increase). However, only resolving the uncertainty for a single parameter was worth almost two-thirds the value of resolving all uncertainty. We found the VOI to depend on the number of management options, increasing as the management flexibility increased. Our analyses show it is more cost-effective to monitor low-density regrowth forest than other states, and more cost-effective to experiment with the no management alternative than the other management alternatives. Importantly, the most cost-effective strategies did not include either the most desired forest states, nor the least understood management strategy, ecological thinning. This implies that managers cannot just rely on intuition to tell them where the most value of information will lie, as critical uncertainties in a complex system are sometimes cryptic.\n\nKeywords: Box-Ironbark, decision theory, monitoring, multivariate adaptive regression splines, optimization.\n", "meta": {"hexsha": "7537e9627a75f8c55754d7e675992f52be972d95", "size": 1989, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "abstract.tex", "max_stars_repo_name": "wkmor1/voiWoodland", "max_stars_repo_head_hexsha": "8780f764c5bee8f2d31e35e8c6ef28841b736dfc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "abstract.tex", "max_issues_repo_name": "wkmor1/voiWoodland", "max_issues_repo_head_hexsha": "8780f764c5bee8f2d31e35e8c6ef28841b736dfc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "abstract.tex", "max_forks_repo_name": "wkmor1/voiWoodland", "max_forks_repo_head_hexsha": "8780f764c5bee8f2d31e35e8c6ef28841b736dfc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 153.0, "max_line_length": 1577, "alphanum_fraction": 0.8200100553, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.4843800842769843, "lm_q1q2_score": 0.3120498113732169}}
{"text": "\\section{Obstacles Objective}\n\n\t\\begin{frame}\n\t\t\\frametitle{Robot Environment}\n\t\t\\begin{columns}[T]\n\t\t\t\\begin{column}{0.3\\textwidth}\n\t\t\t\t\\begin{itemize}\n\t\t\t\t\t\\item Static obstacles location \\\\[1.0cm]\n\t\t\t\t\t\\item Dynamic obstacles trajectory\n\t\t\t\t\\end{itemize}\n\t\t\t\\end{column}\n\t\t\t\\begin{column}{0.7\\textwidth}\n\t\t\t\t\\centering\n\t\t\t\t\\animategraphics[loop,controls,width=0.79\\textwidth]{2}{pictures/robot_env_group/robot_env-}{0}{8}\n\t\t\t\t%\\includegraphics[scale=0.7]{pictures/robot_env.pdf}\n\t\t\t\\end{column}\n\t\t\\end{columns}\n\t\\end{frame}\n\n\t\\begin{frame}\n\t\t\\frametitle{Laser Scanner}\n\t\t\\begin{columns}[T]\n\t\t\t\\begin{column}{0.42\\textwidth}\n\t\t\t\t\\centering\n\t\t\t\t\\onslide<1->{\\includegraphics[scale=0.45]{pictures/laser_ranges.pdf}}\n\t\t\t\t\\onslide<3->{\n\t\t\t\t\\begin{block}{Laser scanner message}\n\t\t\t\t\t\\[\\overrightarrow{data}(k) = \\left\\{\n\t\t\t\t\t\\begin{array}{lr}\n\t\t\t\t\tangle_{min} \\\\\n\t\t\t\t\tangle_{max} \\\\\n\t\t\t\t\t\\overrightarrow{angle}_{inc}, \\quad \\qquad \\forall \\enspace \\delta \\in \\overrightarrow{angle}_{inc} \\\\\n\t\t\t\t\trange_{min} \\\\\n\t\t\t\t\trange_{max} \\\\\n\t\t\t\t\t\\overrightarrow{ranges}, \\qquad \\qquad \\forall \\enspace \\sigma \\in \\overrightarrow{ranges}\n\t\t\t\t\t\\end{array}\n\t\t\t\t\t\\right.\n\t\t\t\t\t\\]\n\t\t\t\t\\end{block}\n\t\t\t\t}\n\t\t\t\\end{column}\n\t\t\t\\begin{column}{0.52\\textwidth}\n\t\t\t\t\\centering\n\t\t\t\t \\onslide<2->{\\includegraphics[scale=0.51]{pictures/robot_laser.pdf}}\n\t\t\t\\end{column}\n\t\t\\end{columns}\n\t\\end{frame}\n\n\t\\begin{frame}\n\t\t\\frametitle{Homogeneous Transformation}\n\t\t\\begin{columns}[T]\n\t\t\t\\begin{column}{0.4\\textwidth}\n\t\t\t\t\\onslide<2->{\n\t\t\t\t\\begin{block}{Rotation Matrix regarding $Z$-axis}\n\t\t\t\t\t\\[\n\t\t\t\t\t\tT_z = \n\t\t\t\t\t\t\\begin{pmatrix}\n\t\t\t\t\t\t\t\\cos\\theta_z & -\\sin\\theta_z & 0 & x_{trns} \\\\\n\t\t\t\t\t\t\t\\sin\\theta_z &  \\cos\\theta_z & 0 & y_{trns}  \\\\\n\t\t\t\t\t\t\t0\t\t   & 0 \t\t\t & 1 & z_{trns}  \\\\\n\t\t\t\t\t\t\t0\t\t   & 0\t\t\t & 0 & 1 \\\\\n\t\t\t\t\t\t\\end{pmatrix}\n\t\t\t\t\t\\]\n\t\t\t\t\\end{block}\n\t\t\t\t}\n\t\t\t\t\\onslide<3->{\n\t\t\t\t\\begin{block}{Co-ordinate Transformation}\n\t\t\t\t\t\\[\n\t\t\t\t\t\tT_{obst\\_map} = \n\t\t\t\t\t\tT_{ft\\_map} T_{r\\_ft} T_{lsr\\_r}\n\t\t\t\t\t\t\\begin{pmatrix}\n\t\t\t\t\t\t\tx_{obst} \\\\\n\t\t\t\t\t\t\ty_{obst} \\\\\n\t\t\t\t\t\t\tz_{obst} \\\\\n\t\t\t\t\t\t\t1 \n\t\t\t\t\t\t\\end{pmatrix}\n\t\t\t\t\t\\]\n\t\t\t\t\\end{block}\n\t\t\t\t}\n\t\t\t\\end{column}\n\t\t\t\\begin{column}{0.55\\textwidth}\n\t\t\t\t\\centering\n\t\t\t\t\\onslide<1->{\\includegraphics[scale=0.9]{pictures/laser_robot_frame.pdf}}\n\t\t\t\\end{column}\n\t\t\\end{columns}\n\t\\end{frame}\n\n\t\\begin{frame}\n\t\t\\frametitle{Saved Obstacles Frame}\n\t\t\\centering\n\t\t\\includegraphics[scale=0.46]{pictures/intial_map.eps}\n\t\\end{frame}\n\n\t\\begin{frame}\n\t\t\\onslide<1->{\n\t\t\\begin{block}{Density-Based Spatial Clustering of Applications with Noise (DBSCAN) \n\t\t\t\t\\footnote[1]{Ester, M., Kriegel, H.-P., Sander, et al.\n\t\t\t\t\t\\say{\\textcolor{tudark}{A density-based algorithm for discovering clusters in large spatial databases with noise}}.}}\n\t\t\tStatistical search algorithm\n\t\t\\end{block}\n\t\t\\begin{block}{Least Square Fitting Ellipse (LSFE) \n\t\t\t\t\\footnote[2]{{Fitzgibbon, A. W., Pilu, M., and Fisher, R. B. \\say{\\textcolor{tudark}{Direct least squares fitting of ellipses}}.}}}\n\t\t\tNumerical fitting algorithm for each set of data.\n\t\t\\end{block}\n\t\t}\n\t\t\\begin{columns}[T]\n\t\t\t\\onslide<2->{\n\t\t\t\\begin{column}{0.32\\textwidth}\n\t\t\t\t\\begin{itemize}\n\t\t\t\t\t\\item Edged data points\n\t\t\t\t\\end{itemize}\n\t\t\t\t\\includegraphics[scale=0.55]{pictures/lsellipse1.pdf}\n\t\t\t\\end{column}\n\t\t\t}\n\t\t\t\\onslide<3->{\n\t\t\t\\begin{column}{0.32\\textwidth}\n\t\t\t\t\\begin{itemize}\n\t\t\t\t\t\\item Concave data points\n\t\t\t\t\\end{itemize}\n\t\t\t\t\\includegraphics[scale=0.55]{pictures/lsellipse2.pdf}\n\t\t\t\\end{column}\n\t\t\t}\n\t\t\t\\onslide<4->{\n\t\t\t\\begin{column}{0.32\\textwidth}\n\t\t\t\t\\begin{itemize}\n\t\t\t\t\t\\item Lined-curved data points\n\t\t\t\t\\end{itemize}\n\t\t\t\t\\includegraphics[scale=0.55]{pictures/lsellipse3.pdf}\n\t\t\t\\end{column}\n\t\t\t}\n\t\t\\end{columns}\n\t\\end{frame}\n\n\t\\begin{frame}\n\t\t\\frametitle{Fitted Frame}\n\t\t\\centering\n\t\t\\includegraphics[scale=0.13]{pictures/map_clustered.eps}\n\t\\end{frame}\n\n\t\\begin{frame}\n\t\t\\frametitle{Dynamic Obstacles Tracking \t\\footnote[1]{{Redmon, J. and Farhadi, A. \\say{\\textcolor{tudark}{YOLO9000: better, faster, stronger}}.}}}\n\t\t\\begin{columns}[T]\n\t\t\t\\begin{column}{0.4\\textwidth}\n\t\t\t\t\\onslide<2->{\n\t\t\t\t\\begin{block}{Dyn. obstacles estimation}\n\t\t\t\t\t\\parbox[c][6.5\\baselineskip][t]{\\textwidth}{\n\t\t\t\t\t\\begin{align*}\n\t\t\t\t\t\t&\\hat{\\mathbf{x}}_{i,k} = \n\t\t\t\t\t\t\\begin{pmatrix}\n\t\t\t\t\t\t\t\\hat{x}_{i,k} \\\\\n\t\t\t\t\t\t\t\\hat{y}_{i,k} \\\\\n\t\t\t\t\t\t\t\\hat{\\theta}_{i,k}\n\t\t\t\t\t\t\\end{pmatrix},\n\t\t\t\t\t\t\\qquad \\qquad \\hat{\\mathbf{v}}_{i,k} =\n\t\t\t\t\t\t\\begin{pmatrix}\n\t\t\t\t\t\t\t\\hat{v}_{i,k} \\\\\n\t\t\t\t\t\t\t\\hat{\\omega}_{i,k}\n\t\t\t\t\t\t\\end{pmatrix}\n\t\t\t\t\t\t\\\\\n\t\t\t\t\t\t&\\hat{\\mathbf{X}}_{i,k} := \\{ \\hat{\\mathbf{x}}_{i,k}, \\hat{\\mathbf{x}}_{i,k+1}, \\cdots, \\hat{\\mathbf{x}}_{i,k+N_p} \\} \\\\\n\t\t\t\t\t\t&\\bar{\\mathbf{X}}_{i,k} := \\{ \\bar{\\mathbf{x}}_{i,k}, \\bar{\\mathbf{x}}_{i,k+1}, \\cdots, \\bar{\\mathbf{x}}_{i,k+N_p}\\}\n\t\t\t\t\t\\end{align*}\n\t\t\t\t\t}\n\t\t\t\t\\end{block}\n\t\t\t\t}\n\t\t\t\t\\onslide<3->{\n\t\t\t\t\\begin{block}{Dynamic obstacles vector}\n\t\t\t\t\t\\[\n\t\t\t\t\t\\hat{\\mathbf{Z}}_{i,k} = \n\t\t\t\t\t\\begin{cases}\n\t\t\t\t\t\t\\hat{\\mathbf{X}}_{i,k}, & \\text{if } i \\in I_{un} \\\\\n\t\t\t\t\t\t\\bar{\\mathbf{X}}_{i,k}, & \\text{if } i \\in I_{robots}.\n\t\t\t\t\t\\end{cases}\n\t\t\t\t\t\\]\n\t\t\t\t\\end{block}\n\t\t\t\t}\n\t\t\t\\end{column}\n\t\t\t\\begin{column}{0.56\\textwidth}\n\t\t\t\t\\centering\n\t\t\t\t\\onslide<1->{\\includegraphics[scale=0.7]{pictures/robot_env_diff.pdf}}\n\t\t\t\\end{column}\n\t\t\\end{columns}\n\t\\end{frame}\n\n\t\\begin{frame}\n\t\t\\frametitle{Dynamic Obstacle Estimation}\n\t\t\\centering\n\t\t\\movie[width=0.83\\textwidth, height=0.47\\textwidth]\n\t\t{\\includegraphics[width=0.83\\textwidth]{pictures/kalman_filter_2.png}}{videos/klmn_best.mov}\n\t\\end{frame}\n\n\t\\begin{frame}\n\t\t\\frametitle{Obstacles Detection}\n\t\t\\centering\n\t\t\\includegraphics[scale=0.9]{pictures/block_diagram_obst_1.pdf}\n\t\\end{frame}\n", "meta": {"hexsha": "f9a0bdb3d2e858791b7089d40275a52812ad8a40", "size": 5598, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Kapitel_3.tex", "max_stars_repo_name": "smababou/latex_presentation", "max_stars_repo_head_hexsha": "c38b668cff733fc6feacbc135b5a785e6c7b32ef", "max_stars_repo_licenses": ["Beerware"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Kapitel_3.tex", "max_issues_repo_name": "smababou/latex_presentation", "max_issues_repo_head_hexsha": "c38b668cff733fc6feacbc135b5a785e6c7b32ef", "max_issues_repo_licenses": ["Beerware"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Kapitel_3.tex", "max_forks_repo_name": "smababou/latex_presentation", "max_forks_repo_head_hexsha": "c38b668cff733fc6feacbc135b5a785e6c7b32ef", "max_forks_repo_licenses": ["Beerware"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4162436548, "max_line_length": 147, "alphanum_fraction": 0.6145051804, "num_tokens": 2133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.3118106498231194}}
{"text": "\\section{RiceFOR}{\nRice is an algorithm that shows compression ratio\nperformance~\\cite{zhang:2008:www} close to the interpolative coding, which is\nan algorithm that provides the best compression ratio. However its complexity\nis so high that it is used only as a comparison basis between algorithms.\nRiceFOR is an attempt to take the best from both Rice and FOR algorithms: the\ncompression ratio of Rice and the highly CPU optimised FOR execution flow.\n}\n\n\\subsection{Algorithm}\n\nIn the one hand, Rice computes the average of a block of values. Thanks to a\nparameter $b$ being the power of 2 closest to this average, it computes the\nEuclidean division of each values by b. The remainder is compressed using b\nbits, and the quotient is encoded into an unary format. On the other hand, FOR\ncompress a block of values by applying a compression routine on sub-blocks of\n32 integers, where the values across the sub-blocks are encoded into a same\nnumber of bits. By computing the remainders in Rice all together, we achieve the\nsame use case as FOR, if the number of remainders is a multiple of 32.\nThe FOR algorithm is only used to compress with CPU optimized routines the\nremainders. The compression ratio is the one that we can have thanks to Rice.\n\nThe RiceFOR algorithm works as follows. First we compute the remainders given a\nparameter $b$ of all values to be compressed. We might have to add some fake\nvalues (i.e., zeros) if the block's size is not a multiple of 32. These\nremainders are outputted into a temporary block that will be compressed using\nthe FOR algorithm with b for the bit frame. Then the quotient of all values\nare to be encoded with the unary format, as they would have been with the\noriginal Rice algorithm.\n\nThe decompression algorithm works in the same way as the original Rice, the\ndifference being that the remainders are to be decompressed with FOR.\n\n\\subsection{Implementation}\n\nRice provides a good compression ratio~\\cite{zhang:2008:www}, however the\ncomputation of the statistics and unary encoding slow its compression and\ndecompression speed. Along with the optimization provided by the AFOR highly\nperforming routines, two optimized algorithms have been developed in order to\nencode and decode efficiently values in unary format: an optimized routine to\nencode a value into unary format, and a routine to decode unary values at the\nbyte level inspired from the Rice implementation in \\cite{Yan:2009:sigir}.\n\n\\begin{description}\n\\item[Compression]\nUsing FOR to compress the remainders computed for the Rice\nalgorithm, RiceFOR is implemented as follows:\n\\begin{enumerate}\n  \\item[] Given a block B of integers\n  \\item the power of 2 directly lower to the mean of B is used as the bit frame.\n  \\item each sub-blocks of 32 remainders are compressed with that bit frame\n  using the FOR routines such as the one presented in the\n  Listings~\\ref{lst:compression-routine}.\n  \\item the quotient of each integer (with the division by the bit frame) are\n  encoded in unary format, using the optimized routine reported in the\n  Listings~\\ref{lst:optimized-unary-enc}.\n\\end{enumerate}\n\\item[Decompression] The remainders are decompressed with the\nFOR routines, and the quotients are decoded using a byte-based decoding method\npresented in the Listings~\\ref{lst:block-unary-dec}. Indeed a byte is likely to\nencode multiple values in unary format (e.g. 4 ones are encoded in one byte as\n$0101\\;0101$), thus it is possible to decode multiple values by reading a byte\na single time.\n\\end{description}\n\nIn the method \\emph{encodeUnary} presented in the\nListings~\\ref{lst:optimized-unary-enc}, the loop encode the quotient $q$ into\nthe array of byte $b$ of compressed data. The variable \\emph{bit} is global and\nrecords the number of bit already compressed. On line 3, the local variable\n\\emph{r} holds the number of bits in the current byte that are still unused.\nThe variable \\emph{ones} holds the number of bits that will be set to 1. The\nswitch structure displays 8 hard coded cases to write from 1 to 8 bits at 1.\nWith the example of case 3 on line 7, the current byte, i.e., $bit / 8$, has\n3 bits (7 in binary format: $111$) appended to it. These operations will repeat\nuntil the quotient q has been completely encoded. The termination criterion of\nthe unary encoding, i.e., bit at zero, is computed on line 15. This suggests\nthat the current byte has been previously initialized to zero.\n\nThe method presented in the Listings~\\ref{lst:block-unary-dec} reads a byte\ncontaining values in unary format and decode them into an int array, starting\nat the position \\emph{offset}. All the unary encoded values are quotient\ncomputed by the Rice algorithm, with a same parameter \\emph{frameBit}. The\nswitch structure contains all 256 possibilities of bits configurations, and\nhard codes for each cases the corresponding updates. For example the 26 case,\nwhich in binary base equals $0001\\;1010$, encodes 5 values which respectively\nare from the least to the most significant bit $0$, $1$, $2$, 0 and 0. Thus the\nquotients are respectively 0, $1^{bitFrame}$, $2\\times1^{bitFrame}$, 0 and 0,\nwith $bitFrame$ the divisor parameter used in Rice.\n\n\\begin{fileformat}\n  \\centering\n  \\begin{minipage}[t]{0.47\\linewidth}\n\\begin{lstlisting}[frame=lines,language=Java,numbers=left,caption=Unary\nformat encoding.,label=lst:optimized-unary-enc]\nencodeUnary(int q, byte[] b)\n\twhile (q > 0) {\n\t\tint r = 8 - (bit % 8);\n\t\tint ones = r > v ? v : r;\n\t\tswitch (ones) {\n\t\t\t...\n\t\t\tcase 3:\n\t\t\t\tb[bit / 8] |= (7 << (bit % 8));\n\t\t\t\tbit += 3;\n\t\t\t\tbreak;\n\t\t\t...\n\t\t}\n\t\tq -= ones;\n\t}\n\tbit += 1\n\\end{lstlisting}\n  \\end{minipage}\n  \\quad%\n  \\begin{minipage}[t]{0.47\\linewidth}\n\\begin{lstlisting}[frame=lines,language=Java,numbers=left,caption=Byte-based\nunary format decoding.,label=lst:block-unary-dec]\ndecodeUnary(byte b, int[] i)\n\tswitch (b) {\n\t\t...\n\t\tcase 26: // 26 = 0001 1010\n\t\t\ti[offset] += 0;\n\t\t\ti[offset + 1] += 1^frameBit;\n\t\t\ti[offset + 2] += 2*1^frameBit;\n\t\t\ti[offset + 3] += 0;\n\t\t\ti[offset + 4] += 0;\n\t\t\toffset += 5;\n\t\t\tbreak;\n\t\t...\n\t}\n\\end{lstlisting}\n  \\end{minipage}\n\\end{fileformat}\n\n\\section{Adaptive Frame Of Reference}{\nThe Adaptive Frame Of Reference (AFOR) attempts to retain the best of FOR,\ni.e., a very efficient compression and decompression using highly-optimised\nroutines to avoid branching conditions, while providing a better tolerance\nagainst outliers and therefore achieving a higher compression ratio. Compared\nto PFOR, AFOR does not rely on the encoding of exceptions in the presence of\noutliers. Instead, AFOR partitions a block into multiple frames of variable\nlength, the partition and the length of the frames being chosen appropriately\nin order to adapt the encoding to the value distribution.\n}\n\\label{sec:afor}\n\n\\subsection{Algorithm}\n\nAFOR extends the FOR algorithm and runs as follows. Given a block $B$ of $n$\nintegers, AFOR partitions it into $m$ distinct frames and encodes each frame\nusing highly-optimised routines similarly to FOR. Each frame is independent\nfrom one an other, i.e., each one has its own \\emph{bit frame}, and each one\nencodes a variable numbers of values. This is depicted in\nFigure~\\ref{fig:compression:afor} by \\emph{AFOR-2}. AFOR encodes along with\nthe frame the associated bit frame with respect to a given encoder, e.g., a\nbinary encoder. In fact, AFOR encodes (respectively decodes) a block of values\nby:\n\\begin{enumerate}\n\\item encoding (respectively decoding) the bit frame;\n\\item selecting the compression (respectively decompression) routine associated\nto the bit frame;\n\\item encoding (respectively decoding) the frame using the selected routine.\n\\end{enumerate}\n\n\\begin{figure*}\n  \\centering\n\t\\includegraphics[width=0.7\\linewidth]{pics/afor-encoding}\n\t\\caption{Block compression comparison between FOR and AFOR. We alternate\n\tcolours to differentiate independent frames. AFOR-1 denotes a first\n\timplementation of AFOR using a fixed frame length. AFOR-2 denotes a second\n\timplementation of AFOR using variable frame lengths. AFOR-3 denotes a third\n\timplementation using variable frame lengths and the frame stripping technique.\n \t\\emph{BFS} denotes the byte storing the bit frame selector associated to the\n\tnext frame.}\n\t\\label{fig:compression:afor}\n\\end{figure*}\n\nFinding the right partitioning, i.e., the optimal configuration of frames and\nframe lengths per block, is essential for achieving high compression\nratio~\\cite{rossano:2010:vse}. If a frame is too large, the encoding becomes\nmore sensitive to outliers and wastes bits by using a too big bit frame for\nall the other integers. On the contrary, if the frames are too small, the\nencoding wastes too much space due to the overhead of storing a larger numbers\nof bit frames. The appropriate strategy is to rely \n\\begin{enumerate}\n  \\item on large frames in the presence of a homogeneous sequence of values.\n  \\item on small frames in the presence of outliers.\n\\end{enumerate}\nAlso, alternating\nbetween large and small frames is not only important for achieving high\ncompression ratio but also for achieving high performance. If the frames are\ntoo small, the encoding has to perform more branching conditions to select the\nappropriate routine for each bit frame, and therefore the compression and\ndecompression performance decrease. Therefore, it is better to rely on large\nframes instead of multiple smaller frames when it is possible. Our solution\nuses a greedy local optimization algorithm which is explained in the next\nsection.\n\n\\subsection{Partitioning Blocks into Variable Frames}\n\nFinding the optimal configuration of frames and frame lengths for a block of\nvalues is a combinatorial problem. For example, with three different frame\nlengths (32, 16 and 8) and a block of size 1024 integers, there are $1.18\n\\times 10^{30}$ possible combinations. While such a combinatorial problem can\nbe solved via Dynamic Programming algorithms~\\cite{rossano:2010:vse}, the\ncomplexity of such algorithms is still $O(n \\times k)$, with the term $n$\nbeing the number of integers and the term $k$ the size of the largest frame,\ntherefore it greatly impacts the compression performance. Since we are not\nonly interested by a fast decompression speed and a high compression ratio,\nbut also by a fast compression speed, this approach is not used in our\nexperiments. Instead, we use a local optimization algorithm that provides a\nsatisfactory compression rate while being efficient to efficient to compute.\n\n\\begin{description}\n\\item[Local Optimization algorithm]\nAFOR computes the block partitioning by using a sliding window over a block\nand determines the optimal configuration of frames and frame lengths for the\ncurrent window.\n\nGiven a window of size $w$ and a list of possible frame\nlengths, we first compute beforehand the possible configurations. For example,\nfor a window size of 32 and three different frame lengths, 32, 16 and 8, there\nare six configurations: $[32],[16,16],[16,8,8],[8,16,8],[8,8,16],[8,8,8,8]$.\nThen, given a list of possible configurations for a window, we\nestimate the size of each configuration by doing one pass over the values of\nthe window as shown in the Algorithm~\\ref{algo:afor2-opt} (Lines 1-5). This\nfirst step performs $w \\times k$ comparisons with $k$ the number of possible\nconfigurations. The second step, Lines 6-12 in Algorithm~\\ref{algo:afor2-opt},\nperforms a pass over the possible configuration and estimates the size of each\nconfiguration in order to find the best one. The \\texttt{EstimateSize}\nfunction computes the cost of encoding the window given one configuration,\naccounting also the overhead of storing the bit frames. For example, for the\nconfiguration $[8,8,8,8]$ with four frames of size 8 each, and with four\nassociated bit frames, $b_{1}$ to $b_{4}$, the size of the encoding is\ncomputed as follow: $4 + 8 \\times \\sum_{i=1\\ldots4} log(b_i + 1)$, where $8\n\\times \\sum_{i=1\\ldots4} log(b_i + 1)$ is the size of the four encoded frames\nand $4$ is the overhead to store the four bit frames.\n\\end{description}\n\nThis simple algorithm is efficient to compute, in particular if the\nwindow size is small and the frame lengths are restricted to a few number.\nHowever, it is easy to see that such method does not provide the optimal\nconfiguration for a complete block. There is a trade-off between optimal\npartitioning and complexity of the algorithm. However, one can possibly use a\nmore complex method for achieving higher compression ratio if the compression\nspeed is not critical. We decided to use this method since in our experiment\nwe found that a small window size of 32 values and three frame lengths, 32, 16\nand 8, were providing satisfactory results in term of compression speed and\ncompression ratio. In the next Section is presented a more detailed explanation\nof the AFOR implementation.\n\n\\SetAlFnt{\\sf}\n\\IncMargin{.5em}\n\\begin{algorithm}\n\\SetAlgoLined\n\\LinesNumbered\n\\SetKwData{Conf}{c}\n\\SetKwData{BestConf}{bestConf}\\SetKwData{BestSize}{bestSize}\n\\SetKwInOut{Input}{input}\\SetKwInOut{Output}{output}\n\\SetKwFunction{GetBitFrame}{GetBitFrame}\\SetKwFunction{SetBitFrame}{SetBitFrame}\n\\SetKwArray{BitFrames}{bitFrames}\n\\SetKwFunction{EstimateSize}{EstimateSize}\n\n\\Input{A window $W$ of size $w$}\n\\Input{The smallest frame length $l$}\n\\Output{The best configuration for the window}\n\n\\BlankLine\n\\BlankLine\n\n\\For{$i \\leftarrow 0$ \\KwTo $\\frac{w}{l}$}{\n  \\For{$j \\leftarrow i \\times l$ \\KwTo $(i + 1) \\times l$}{\n    \\BitFrames{i} $\\leftarrow \\max($\\BitFrames{i}$, \\lceil \\log_2(W[j] + 1) \\rceil)$\\;\n  }\n}\n\\BestSize $\\leftarrow$ $MaxSize$\\;\n\\ForEach{configuration \\Conf of the possible configurations}{\n  \\If{\\EstimateSize{\\Conf, \\BitFrames} $<$ \\BestSize}{\n    \\BestSize $\\leftarrow$ \\EstimateSize{\\Conf}\\;\n\t\\BestConf $\\leftarrow$ \\Conf\\;\n  }\n}\n\\caption{The algorithm that finds the best configuration of frames and frame\nlengths for a window $W$ of size $w$.}\n\\label{algo:afor2-opt}\n\\end{algorithm}\n\\DecMargin{.5em}\n\n\\subsection{Frame Stripping}\n\\label{sec:compression:stripping}\n\nIn an inverted list, it is common to encounter a long sequence of 1 to encode,\ni.e., the delta gap value. For example, this occurs with terms that appear\nfrequently in many entities. With RDF data, such a very common term might be a\npredicate URI or a widely present class URI. As a consequence, the list of\nentity identifiers is composed of many consecutive identifiers, which is\nencoded as a list of 1 using the delta representation. Also, the schema used\nacross the entity descriptions coming from a same dataset is generally\nsimilar. When indexing batch of entities coming from a same dataset, we\nbenefit from a ``term clustering'' effect: all the schema terms are associated\nwith long runs of consecutive entity identifiers in the inverted index. There\nis also other cases where a long run of 1 is common, for example in:\n\\begin{itemize}\n\\item the list of term frequencies for terms that appear frequently a single\ntime in the entity description, e.g., class URIs;\n\\item the list of value identifiers for terms that appear frequently in\nsingle-valued attributes;\n\\item the list of term positions for nodes holding a single term, e.g., URIs. \n\\end{itemize}\n\nIn presence of such long runs of 1, AFOR still needs to encode each value\nusing 1 bit. For example, a frame of 32 values will encode a sequence of 1\nusing 32 bits. The goal of the \\emph{Frame Stripping} method is to avoid the\nencoding of such frames. Our solution is to \\emph{strip} the content of a\nframe if and only if the frame is exclusively composed of 1. We encode such a\ncase using a special bit frame.\n\n\\subsection{Frame Skipping}\n\\label{sec:afor-skip}\n\nBlock-based compression techniques encode the configuration a block of integers\nhas been compressed with. When the length of the compressed block is unknown,\nthis compression header possesses information about the block that can be used\nto skip this block and so not to decompress it.\n\nWith the AFOR algorithm, this method enables the possibility to skip a frame by\nreading a BFS. This is not possible with techniques such as Rice, VByte or\nPFOR. Since the BFS encodes the bit frame used to compress a frame, the size\nin bytes of a compressed frame is found by the formula\n\\begin{displaymath}\n\\mid F \\mid \\times BFS\n\\end{displaymath}\nwhere $\\mid F \\mid$ is the length of a frame. For instance the bit frame 1\n(i.e., 1 bit) encodes a frame of 32 integers into 4 bytes.\n\nWith self-indexing structures (presented in Chapter~\\ref{sec:self-indexing}),\nthe difference in bytes between two points in a stream is necessary in order to\nknow at which position data has to be read. These \\emph{file pointers} have to\nbe stored, taking a considerable space. Thanks to the frame skipping method, it\nis possible to get rid of the additional file pointers information, since the\nsize in bytes of a frame is known by reading its BFS.\n\n\\subsection{Implementations}\n\nWe present three different implementations of the AFOR encoder class. We can\nobtain many variations of AFOR by using various sets of frame lengths and\ndifferent parameters for the partitioning algorithm. We tried many of them\nduring our experimentation and report here only the ones that are promising\nand interesting to compare.\n\n\\paragraph{AFOR-1}\n\nThe first implementation of AFOR, referred to as AFOR-1 and depicted in\nFigure~\\ref{fig:compression:afor}, is using a single frame length of 32\nvalues. To clarify, this approach is identical to FOR applied on small blocks\nof 32 integers. This first implementation shows the benefits of using short\nframes instead of long frames of 1024 values as in our original FOR\nimplementation. In addition, AFOR-1 is used to compare and judge the benefits\nprovided by AFOR-2, the second implementation using variable frame lengths.\nConsidering that, with a fixed frame length, a block is always partitioned in\nthe same manner, AFOR-1 does not rely on the partitioning algorithm presented\npreviously.\n\n\\paragraph{AFOR-2}\n\nThe second implementation, referred to as AFOR-2 and depicted in\nFigure~\\ref{fig:compression:afor}, relies on three frame lengths: 32, 16 and\n8. We found that these three frame lengths give the best balance between\nperformance and compression ratio. Additional frame lengths were rarely\nselected and the performance was decreasing due to the larger number of\npartitioning configurations to compute. Reducing the number of possible frame\nlengths was providing slightly better performance but slightly worse\ncompression ratio. There is a trade-off between performance and compression\neffectiveness when choosing the right set of frame lengths. Our implementation\nrelies on the partitioning algorithm presented earlier, using a window's size\nof 32 values and six partitioning configurations\n$[32],[16,16],[16,8,8],[8,16,8],[8,8,16],[8,8,8,8]$.\n\n\\paragraph{AFOR-3}\n\nThe third implementation, referred to as AFOR-3 and depicted in\nFigure~\\ref{fig:compression:afor}, is identical to AFOR-2 but employs the\n\\emph{frame stripping} technique. Compared to AFOR-2, the compressed block can\ncontain frames which is then encoded by a single bit frame as depicted in\nFigure~\\ref{fig:compression:afor}. AFOR-3 implementation relies on the same\npartitioning algorithm as AFOR-2 with an additional step to find and strip\nframes composed of a sequence of 1 in the partitions.\n\n\\subsubsection{Compression and decompression routines}\n\nOur implementations rely on highly-optimised routines such as the ones\npresented in Listing~\\ref{lst:compression-routine} and\n\\ref{lst:decompression-routine}, where each routine is loop-unrolled to encode\nor decode a fixed number of values using shift and mask operations only. There\nis one routine per bit frame and per frame length. For example, with a frame\nlength of 8 values, the routine encodes 8 values using 3 bits each as shown in\nListing~\\ref{lst:compression-routine}, while for a frame length of 32, the\nroutine encodes 32 values using 3 bits each.\n\nSince AFOR-1 uses a single frame length, it only needs 32 routines for\ncompression and 32 routines for decompression, i.e., one routine per bit frame\n(1 to 32). With respect to AFOR-2, since it relies on three different frame\nlengths, it needs 96 routines for compression and 96 routines for\ndecompression. As for AFOR-3, one additional routine for handling a\nsequence of 1 is added per frame length. The associated compression routine is\nempty and does nothing since the content of the frame is not encoded.\nTherefore the cost is reduced to a single function call. The decompression\nroutine consists of returning an array of ones. This last routine is very fast\nto execute since there are no shift or mask operations.\n\n\\subsubsection{Bit frame encoding}\n\nAs a reminder the bit frame is encoded along with the frame, so that, at\ndecompression time, the decoder can read the bit frame and select the\nappropriate routine to decode the frame. In the case of AFOR-1, the bit frame\nvaries between 1 to 32. For AFOR-2, there are 96 cases to be encoded, where\ncases 1 to 32 refer to the bit frames for a frame length of 8, cases 33 to 63\nfor a frame length of 16, and cases 64 to 96 for a frame length of 32. In\nAFOR-3, we encode one additional case per frame length with respect to the\nframe stripping method. Therefore, there is a total of 99 cases to be encoded.\nThe cases 97 to 99 refer to a sequence of 1 for a frame length of 8, 16 and 32\nrespectively.\n\nIn our implementation, the bit frame is encoded using one byte. While this\napproach wastes some bits each time a bit frame is stored, more precisely 3\nbits for AFOR-1 and 1 bit for AFOR-2 and AFOR-3, the choice is again for a\nquestion of efficiency. Since bit frames and frames are interleaved in the\nblock, storing the bit frame using one full byte enables the frame to be\naligned with the start and the end of a byte boundary. Another implementation\nto avoid wasting bits is to pack all the bit frames at the end of the block. We\ntried this approach and report that it provides slightly better compression\nratio, but slightly worse performance. Since the interleaved approach was\nproviding better performance, we decided to use it in our benchmarks.\n\n\\subsubsection{Routine selection}\n\nA precomputed lookup table is used by the encoder and decoder to quickly\nselect the appropriate routine given a bit frame. Compared to AFOR-1, AFOR-2\nand AFOR-3 have to perform more table lookups for selecting routines since\nthey are likely to rely on small frames of 8 or 16 values when the value\ndistribution is sparse. While these lookups cost additional CPU cycles, we\nwill see in the experiments that the overhead is minimal.\n", "meta": {"hexsha": "55d1ded63ac465e177717591af5e8f216aa952df", "size": 22527, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Methods/compression.tex", "max_stars_repo_name": "scampi/report-compression-skiplists", "max_stars_repo_head_hexsha": "6ec36c77177642434a6ac4890d394ac2afea2c43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Methods/compression.tex", "max_issues_repo_name": "scampi/report-compression-skiplists", "max_issues_repo_head_hexsha": "6ec36c77177642434a6ac4890d394ac2afea2c43", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Methods/compression.tex", "max_forks_repo_name": "scampi/report-compression-skiplists", "max_forks_repo_head_hexsha": "6ec36c77177642434a6ac4890d394ac2afea2c43", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.0816326531, "max_line_length": 86, "alphanum_fraction": 0.7818617659, "num_tokens": 5604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.31181064239247486}}
{"text": "\\graphicspath{{Pics/combi/coloring/}}\n\n\n\\newpage\n\\subsection{Coloring Problems}\n\n\n\\prob{https://artofproblemsolving.com/community/c6h1424942p8024575}{EGMO 2017 P2}{M}{Find the smallest positive integer $ k $ for which there exists a colouring of the positive integers $ \\mathbb{Z}_{>0} $ with $ k $ colours and a function $ f:\\mathbb{Z}_{>0}\\to \\mathbb{Z}_{>0} $ with the following two properties:\n\n    \\begin{enumerate}\n\n        \\item For all positive integers $ m,n $ of the same colour, $ f(m+n)=f(m)+f(n). $\n        \\item There are positive integers $ m,n $ such that $ f(m+n)\\ne f(m)+f(n). $\n\n    \\end{enumerate}\n\nIn a colouring of $ \\mathbb{Z}_{>0} $ with $ k $ colours, every integer is coloured in exactly one of the $ k $ colours. In both $ (i) $ and $ (ii) $ the positive integers $ m,n $ are not necessarily distinct.}\\label{problem:extremal_case_whole_4}\n\n\\solu{Firstly a modular coloring shows that $ 1<k\\leq 2 $. For $ k=2 $ we do some trivial case works.}\n\n\n\n\\prob{https://artofproblemsolving.com/community/c6h17337p118712}{ISL 2002 C2}{E}{For $n$ an odd positive integer, the unit squares of an $n\\times n$ chessboard are coloured alternately black and white, with the four corners coloured black. A it tromino is an $L$-shape formed by three connected unit squares. For which values of $n$ is it possible to cover all the black squares with non-overlapping trominos? When it is possible, what is the minimum number of trominos needed?}\\label{problem:bijection_12}\n\n\\solu{First find the first ans and a configuration that works. Then guess the second ans, and see from where that might come from, usually these anses come from some special set of problems, where bijection is applicable.}\n\n\n\n\\prob{http://codeforces.com/gym/101954/problem/G}{Codeforces 101954/G}{E/H}{Two Knights are given on a chessboard, one black one white. Which player has a winning possibility?}\\label{problem:coloring_4}\n\n\\solu{A knight's move always changes the color of the cell.}\n\n\n\\prob{https://artofproblemsolving.com/community/c6h417987p2356844}{ARO 1993 P10.4}{M}{Thirty people sit at a round table. Each of them is either smart or dumb. Each of them is asked: \"Is your neighbor to the right smart or dumb?\" A smart person always answers correctly, while a dumb person can answer both correctly and incorrectly. It is known that the number of dumb people does not exceed $ F $. What is the largest possible value of $ F $ such that knowing what the answers of the people are, you can point at at least one person, knowing he is smart?}\\label{problem:extreme_object_8}\n\n\\solu{We see that the strings of truth only exist either when all people are dumb or the last one is the truthful one. Now we take the longest such string, and this sting has to be of the second kind. To prove this, we use bounding with the given constraint.}\n\n\n\\prob{https://artofproblemsolving.com/community/c6h1389041p7736715}{Tournament of Towns 2015S S6}{E}{An Emperor invited $2015$ wizards to a festival. Each of the wizards knows who of them is good and who is evil, however the Emperor doesn’t know this. A good wizard always tells the truth, while an evil wizard can tell the truth or lie at any moment. The Emperor gives each wizard a card with a single question, maybe different for different wizards, and after that listens to the answers of all wizards which are either “yes” or “no”. Having listened to all the answers, the Emperor expels a single wizard through a magic door which shows if this wizard is good or evil. Then the Emperor makes new cards with questions and repeats the procedure with the remaining wizards, and so on. The Emperor may stop at any moment, and after this the Emperor may expel or not expel a wizard. Prove that the Emperor can expel all the evil wizards having expelled at most one good wizard.}\n\n\\solu{There is only one problem with the cyclic arrangement, that is what if all the answers are `yes'? We get rid of this problem by trying small case with $ n=3 $ and trying the most simple way to connect this strategy to any $ n $. Simplicity is the key.}\n\n\n\\prob{https://artofproblemsolving.com/community/c6h214707p1187174}{ISL 2007 C1}{E}{Let $ n > 1$ be an integer. Find all sequences $ a_1, a_2, \\ldots a_{n^2 + n}$ satisfying the following conditions:\n\n    \\begin{enumerate}\n        \\item $ a_i \\in \\left\\{0,1\\right\\} $ for all $ 1 \\leq i \\leq n^2 + n $\n        \\item for all $ 0 \\leq i \\leq n^2 - n $\n            \\[a_{i + 1} + a_{i + 2} + \\ldots + a_{i + n} < a_{i + n + 1} + a_{i + n + 2} + \\ldots + a_{i + 2n}\\]\n\\end{enumerate}}\n\n\\solu{$ n+1 $ blocks of $ n $, each strictly greater than the previous one. means the sums of the blocks have to be $ 0, 1, \\dots n $. construction's easy from examples of $ 2, 3 $.}\n\n\n\n\\prob{https://artofproblemsolving.com/community/c6h1480692p8639256}{ISL 2016 C2}{E}{Find all positive integers $n$ for which all positive divisors of $n$ can be put into the cells of a rectangular table under the following constraints:\n    each cell contains a distinct divisor;\\\\\n    the sums of all rows are equal; and\\\\\nthe sums of all columns are equal.}\n\n\\solu{Check the sizes.}\n\n\n\n\\prob{https://artofproblemsolving.com/community/c6h214709p1187179}{ISL 2007 C3}{E}{Find all positive integers $ n$ for which the numbers in the set $ S = \\{1,2, \\ldots,n \\}$ can be colored red and blue, with the following condition being satisfied: The set $ S \\times S \\times S$ contains exactly $ 2007$ ordered triples $ \\left(x, y, z\\right)$ such that:\n    \\begin{enumerate}\n        \\item the numbers $ x$, $ y$, $ z$ are of the same color\n        \\item the number $ x + y + z$ is divisible by $ n$.\n\\end{enumerate}}\n\n\\solu{Trying out small cases, noticing patter. It doesn't matter `which' numbers are red, but `how' many numbers are red.}\n\n\n\n\\prob{https://artofproblemsolving.com/community/c6h1113185p5083550}{ISL 2014 C4}{EM}{Construct a tetromino by attaching two $2 \\times 1$ dominoes along their longer sides such that the midpoint of the longer side of one domino is a corner of the other domino. This construction yields two kinds of tetrominoes with opposite orientations. Let us call them $S$- and $Z$-tetrominoes, respectively.\n\nAssume that a lattice polygon $P$ can be tiled with $S$-tetrominoes. Prove that no matter how we tile $P$ using only $S$- and $Z$-tetrominoes, we always use an even number of $Z$-tetrominoes.}\n\n\\solu{So after we are determined to do coloring, it is not very hard to come up with a coloring. Start from stracth type coloring. Color one square at a time, this might take several tries. \n\\figdf{.5}{ISL2014C4}{}}\n", "meta": {"hexsha": "ab707490111d468d3c6bcc9b7336fa983375d673", "size": 6574, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "combi/sec9_1_coloring_problems.tex", "max_stars_repo_name": "M-Ahsan-Al-Mahir/BCS_Question_Bank", "max_stars_repo_head_hexsha": "83ff9b542999386ea182863e4f25f0b488d3984f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 48, "max_stars_repo_stars_event_min_datetime": "2020-10-14T17:15:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T19:47:04.000Z", "max_issues_repo_path": "combi/sec9_1_coloring_problems.tex", "max_issues_repo_name": "AnglyPascal/BCS_Question_Bank", "max_issues_repo_head_hexsha": "83ff9b542999386ea182863e4f25f0b488d3984f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "combi/sec9_1_coloring_problems.tex", "max_forks_repo_name": "AnglyPascal/BCS_Question_Bank", "max_forks_repo_head_hexsha": "83ff9b542999386ea182863e4f25f0b488d3984f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-10-15T08:59:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T15:19:26.000Z", "avg_line_length": 81.1604938272, "max_line_length": 977, "alphanum_fraction": 0.7336477031, "num_tokens": 1831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521307073646, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.31181064089324867}}
{"text": "\\section{Related Work}\n\\label{sec:related-work}\n\n\\begin{figure}[t]\n\t\\centering\n\t\\vspace*{-0.3cm}\n\t\\hspace*{-0.4cm}\n\t\\begin{minipage}[t]{0.3\\textwidth}\n\t\t\\includegraphics[width=0.9\\textwidth]{fig_main_illustration3}\n\t\\end{minipage}\n\t\\begin{minipage}[t]{0.12\\textwidth}\n\t\t\\includegraphics[width=1.2\\textwidth]{fig_main_illustration2} \n\t\\end{minipage}\n\t\\vspace*{-10px}\n\t\\caption{\\textbf{Measuring Flatness.} \\textbf{Left:} Illustration of measuring flatness in a random (\\ie, average-case, {\\color{colorbrewer2}blue}) direction by computing the difference between \\RCE $\\tilde{\\mathcal{L}}$ \\emph{after} perturbing weights (\\ie, $w + \\nu$) and the ``reference'' \\RCE $\\mathcal{L}$ given a local neighborhood $B_\\xi(w)$ around the found weights $w$, see \\secref{subsec:main-flatness}. In practice, we average across/take the worst of several random/adversarial directions.\n\t\\textbf{Right:} Large changes in \\RCE around the ``sharp'' minimum causes poor generalization from training ({\\color{colorbrewer0}black}) to test examples ({\\color{colorbrewer1}red}).\n\t}\n\t\\label{fig:main-illustration}\n\t\\vspace*{-6px}\n\\end{figure}\n\n\\textbf{Adversarial Training (AT):}\nDespite a vast amount of work on adversarial robustness, \\eg, see \\cite{SilvaARXIV2020,YuanARXIV2017,AkhtarACCESS2018,BiggioCCS2018,XuARXIV2019}, adversarial training (AT) has become the de-facto standard for (empirical) robustness. Originally proposed in different variants in \\cite{SzegedyICLR2014,MiyatoICLR2016,HuangARXIV2015}, it received considerable attention in \\cite{MadryICLR2018,robustness} and has been extended in various ways:\n\\cite{LambAISEC2019,CarmonNIPS2019,UesatoNIPS2019} utilize interpolated or unlabeled examples, \\cite{TramerNIPS2019,MainiICML2020} achieve robustness against multiple threat models, \\cite{StutzICML2020,LaidlawARXIV2019,WuICML2018} augment AT with a reject option, \\cite{YeNIPS2018,LiuICLR2019b} use Bayesian networks, \\cite{TramerICLR2018,GrefenstetteARXIV2018} build ensembles, \\cite{BalajiARXIV2019,DingICLR2020} adapt the threat model for each example, \\cite{Wong2020ICLR,AndriushchenkoNIPS2020,VivekCVPR2020} perform AT with single-step attacks, \\cite{HendrycksNIPS2019} uses self-supervision and \\cite{PangNIPS2020} additionally regularizes features  -- to name a few directions. However, AT is slow \\cite{ZhangNIPS2020} and suffers from increased sample complexity \\cite{SchmidtNIPS2018} as well as reduced (clean) accuracy \\cite{TsiprasICLR2019,StutzCVPR2019,ZhangICML2019,RaghunathanARXIV2019}. Furthermore, progress is slowing down. In fact, ``standard'' AT is shown to perform surprisingly well on recent benchmarks \\cite{CroceICML2020,CroceARXIV2020b} when tuning hyper-parameters properly \\cite{PangARXIV2020b,GowalARXIV2020}. In our experiments, we consider several popular variants \\cite{WuNIPS2020,WangICLR2020,ZhangICML2019,CarmonNIPS2019,HendrycksNIPS2019}.\n\n\\textbf{Robust Overfitting:} Recently, \\cite{RiceICML2020} identified \\emph{robust} overfitting as a crucial problem in AT and proposed early stopping as an effective mitigation strategy. This motivated work \\cite{SinglaARXIV2021,WuNIPS2020} trying to mitigate robust overfitting. While \\cite{SinglaARXIV2021} studies the use of different activation functions, \\cite{WuNIPS2020} proposes AT with \\emph{adversarial weight perturbations} (AT-AWP) explicitly aimed at finding flatter minima in order to reduce overfitting. While the results are promising, early stopping is still necessary. Furthermore, flatness is merely assessed visually, leaving open whether AT-AWP \\emph{actually} improves flatness in adversarial weight directions. We consider both average- and worst-case flatness, \\ie, random and adversarial weight perturbations, to answer this question.\n\n\\textbf{Flat Minima} in the loss landscape, \\wrt changes in the weights, are generally assumed to improve \\emph{standard} generalization \\cite{HochreiterNC1997}. \\cite{LiNIPS2018} shows that residual connections in ResNets \\cite{HeCVPR2016} or weight decay lead to \\emph{visually} flatter minima. \\cite{NeyshaburNIPS2017,KeskarICLR2017} formalize this concept of flatness in terms of \\emph{average-case} and \\emph{worst-case} flatness. \\cite{KeskarICLR2017,JiangICLR2020} show that worst-case flatness correlates well with better generalization, \\eg, for small batch sizes, while \\cite{NeyshaburNIPS2017} argues that generalization can be explained using both an average-case flatness measure and an appropriate capacity measure. Similarly, batch normalization is argued to improve generalization by allowing to find flatter minima \\cite{SanturkarNIPS2018,BjorckNIPS1018}. These insights have been used to explicitly regularize flatness \\cite{ZhengARXIV2020c}, improve semi-supervised learning \\cite{CicekICCVWOR2019} and develop novel optimization algorithms such as Entropy-SGD \\cite{ChaudhariICLR2017}, local SGD \\cite{TinICLR2020} or weight averaging \\cite{IzmailovUAI2018}.\n\\cite{DinhICML2017}, in contrast, criticizes some of these flatness measures as not being scale-invariant.\nWe transfer the intuition of flatness to the \\emph{robust} loss landscape, showing that flatness is desirable for adversarial robustness, while using scale-invariant measures.", "meta": {"hexsha": "ae976985e55c2b17496244dff0115638f311e128", "size": 5194, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/sec_related_work.tex", "max_stars_repo_name": "davidstutz/iccv2021-robust-flatness", "max_stars_repo_head_hexsha": "d63daf8fc0221d07d8cfc8b7a5bcdc213403a17b", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-11-08T21:27:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T19:09:04.000Z", "max_issues_repo_path": "paper/sec_related_work.tex", "max_issues_repo_name": "davidstutz/iccv2021-robust-flatness", "max_issues_repo_head_hexsha": "d63daf8fc0221d07d8cfc8b7a5bcdc213403a17b", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/sec_related_work.tex", "max_forks_repo_name": "davidstutz/iccv2021-robust-flatness", "max_forks_repo_head_hexsha": "d63daf8fc0221d07d8cfc8b7a5bcdc213403a17b", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 173.1333333333, "max_line_length": 1274, "alphanum_fraction": 0.8124759338, "num_tokens": 1555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.3118072787661869}}
{"text": "%{{{1\n\\documentclass[10pt]{article} % 12-point font\n\n\\usepackage[margin=1cm]{geometry} % set page to 1-inch margins\n\\usepackage{amsmath} % for math\n\\usepackage{amssymb} % like \\Rightarrow\n\\setlength\\parindent{0pt} % Suppresses the indentation of new paragraphs.\n\\pagenumbering{gobble} % suppress page numbers\n\n% Big display\n\\newcommand{\\ds}{ \\displaystyle }\n% Parenthesis\n\\newcommand{\\norm}[1]{\\left\\lVert#1\\right\\rVert}\n\\newcommand{\\p}[1]{\\left(#1\\right)}\n\\newcommand{\\bk}[1]{\\left[#1\\right]}\n\\newcommand{\\bc}[1]{ \\left\\{#1\\right\\} }\n\\newcommand{\\abs}[1]{ \\left|#1\\right| }\n% Derivatives\n\\newcommand{\\df}[2]{ \\frac{d#1}{d#2} }\n\\newcommand{\\ddf}[2]{ \\frac{d^2#1}{d{#2}^2} }\n\\newcommand{\\pd}[2]{ \\frac{\\partial#1}{\\partial#2} }\n\\newcommand{\\pdd}[2]{\\frac{\\partial^2#1}{\\partial{#2}^2} }\n% Distributions\n\\newcommand{\\Normal}{ \\text{Normal} }\n\\newcommand{\\Beta}{ \\text{Beta} }\n\\newcommand{\\Gam}{ \\text{Gamma} }\n\\newcommand{\\InvGamma}{ \\text{Inv-Gamma} }\n\\newcommand{\\Uniform}{ \\text{Uniform} }\n\\def\\Dir{\\text{Dirichlet}}\n\\def\\TN{\\text{TN}}\n% Statistics\n\\newcommand{\\E}{\\text{E}}\n\\newcommand{\\iid}{\\overset{iid}{\\sim}}\n\\newcommand{\\ind}{\\overset{ind}{\\sim}}\n\n% Graphics\n\\usepackage{graphicx}  % for figures\n\\usepackage{float} % Put figure exactly where I want [H]\n\n% Uncomment if using bibliography\n% Bibliography\n\\usepackage{natbib}\n\\bibliographystyle{plainnat}\n\n% Adds settings for hyperlinks. (Mainly for table of contents.)\n\\usepackage{hyperref}\n\\hypersetup{\n  pdfborder={0 0 0} % removes red box from links\n}\n%}}}1\n\n\n% Macros for this project\n\\def\\true{\\text{TRUE}}\n\\usepackage[dvipsnames,usenames]{color}\n\\newcommand{\\bbh}{\\color{blue}\\textbf}  % blue bold highlight\n\\newcommand{\\bch}{\\color{blue}\\it}  % blue italics\n\\newcommand{\\ech}{\\color{black}\\rm}\n\\def\\imgdir{../../results/test-sim-6-7-20}\n\\input{imgtemplate.tex}\n\n% Title Settings\n\\title{Simulation Study 6.7.20}\n\\author{Arthur Lui}\n\\date{\\today} % \\date{} to set date to empty\n\n% MAIN %\n\\begin{document}\n\n\\maketitle\n\n% \\tableofcontents \\newpage % Comment to remove table of contents\n\n% \\section{Objective}\\label{sec:objective}\n% TODO\n\n\\section{Data Generation}\\label{sec:data-generation}\nIn this study, we generate data with two samples, each containing 2000 cells,\nand 21 markers. Figure~\\ref{fig:Z-true} and Table~\\ref{tab:W-true}\nrespectively show the true $Z$ and $W$ used to generate the simulated data in\nthis study. Note the following:\n\\begin{itemize}\n  \\item Three $Z$'s, shown in Figure~\\ref{fig:Z-true}, were used in this study.\n  \\begin{itemize}\n    \\item In $Z^{1,\\true}$, each column is different from the other columns exactly\n    by exactly two bits. In this sense, all columns are \"close\" to each\n    other.\n    \\item In $Z^{2,\\true}$, each column is different from the other columns exactly\n    by exactly six bits. In this sense, all columns are \"far\" to each\n    other.\n    \\item In $Z^{3,\\true}$, the first three columns are similar. Columns 4 and 5 are \n    close to each other. And columns 6 and 7 are distinct from other columns. \n  \\end{itemize}\n  \\item Figure~\\ref{tab:W-true} shows the true $W$ used for this study. It\n    contains feature abundances that are small in both samples, large in both\n    samples, and large in only one sample. For example, feature $k=7$, \n    has an abundance of $3\\%$ in sample 1, and is absent in feature 2. \n    Moreover, it has the smallest aggregate abundance across both samples. \n    Hence, we can expect it will be least likely recovered in the analysis. \n    Feature $k=3$, on the other hand is abundant in both samples, so we expect\n    it to be easily recovered.\n\\end{itemize}\n\n\\begin{figure}[H]\n  \\begin{center}  % 6 x 5\n    \\begin{tabular}{ccc}\n      \\includegraphics[scale=0.4]{\\imgdir/dataseed1-mcmcseed1-phi1.0-Zind1/img/Z_true.pdf} &\n      \\includegraphics[scale=0.4]{\\imgdir/dataseed1-mcmcseed1-phi1.0-Zind2/img/Z_true.pdf} &\n      \\includegraphics[scale=0.4]{\\imgdir/dataseed1-mcmcseed1-phi1.0-Zind3/img/Z_true.pdf} \\\\\n      %\n      (a) $Z^{1,\\true}$ &\n      (b) $Z^{2,\\true}$ &\n      (c) $Z^{3,\\true}$ \\\\\n      %\n      column-distances of 2 bits &\n      column-distances of 6 bits &\n      mix of similar and distinct columns \\\\\n    \\end{tabular}\n  \\end{center}\n  \\caption{Simulation truth of $Z$ for three scenarios.}\n  \\label{fig:Z-true}\n\\end{figure}\n\n% latex table generated in R 3.4.4 by xtable 1.8-3 package\n% Wed Feb 12 14:53:27 2020\n\\begin{table}[ht]\n  \\centering\n  \\begin{tabular}{rrrrrrrr}\n    \\hline\n    & $k=1$ & $k=2$ & $k=3$ & $k=4$ & $k=5$ & $k=6$ & $k=7$ \\\\\n    \\hline\n    Sample 1 & 0.04 & 0.05 & 0.39 & 0.00 & 0.06 & 0.43 & 0.03 \\\\\n    Sample 2 & 0.00 & 0.05 & 0.54 & 0.20 & 0.14 & 0.07 & 0.00 \\\\\n    \\hline\n  \\end{tabular}\n  \\caption{$W^\\true$}\n  \\label{tab:W-true}\n\\end{table}\n\n\\subsection{More on data generation / MCMC setup}\n\\begin{itemize}\n  \\item We generated $y_{inj}$ from skew Normal distributions. Specifically,\n  \\begin{itemize}\n    \\item Location parameter: $(\\mu_{0,j}^\\star)^\\true=-1 + \\epsilon_j$, $\\epsilon_j \\sim \\Uniform(-0.3, 0.3)$\n    \\item Location parameter: $(\\mu_{1,j}^\\star)^\\true=1 + \\epsilon_j$, $\\epsilon_j \\sim \\Uniform(-0.3, 0.3)$\n    \\item Scale parameter: ($\\sigma^2_i)^\\true=0.5$, $N=(2000, 2000)$\n    \\item The skewness parameter $\\zeta$ was set to -0.9. Note that $\\zeta$\n          corresponds to $\\delta \\in \\p{-1, 1}$ in \\cite{fruhwirth2010bayesian}.\n  \\end{itemize}\n  \\item 6000 burn-in, followed by 3000 iterations (no thinning).\n  \\item Computation time for each chains was was approximately 12.6 hours.\n  \\item \\textbf{Some Priors / setup:}\n  \\begin{itemize}\n    \\item $w^\\star_{i,k} \\sim \\Gam(\\text{shape}=1, \\text{rate}=1/2)$\n    \\item $p_c \\sim \\text{Beta}(1, 9)$\n    \\item $L_0=L_1=3$\n    \\item $\\alpha \\sim \\Gam(0.1, 0.1)$\n    \\item $\\delta_0 \\sim \\TN^-(1, 0.1)$\n    \\item $\\delta_1 \\sim \\TN^+(1, 0.1)$\n    % \\item $\\eta_{z, i,j,\\ell} \\sim \\Dir_{L_z}(1)$\n    % \\item $\\sigma^2_i \\sim \\InvGamma(3, 1)$\n    \\item $\\phi \\in \\bc{0, 1, 10}$\n    \\item The simulation study was done for each of the true $Z$'s in \n          Figure~\\ref{fig:Z-true}.\n    \\item Three chains (different random seeds) were run for each $\\phi$ and data set.\n    \\item 5\\% of data in each sample are used to sample from trained prior, and\n      $M=5$ was used.\n    \\item This dataset contains missing data\n  \\end{itemize}\n\\end{itemize}\n\n\\newpage\n\\section{Log likelihood (post-burn)}\n\\begin{figure}[H]\n  \\begin{center}  % 6 x 5\n    \\imgtemplate{loglike_postburn.pdf}{.15}\n  \\end{center}\n  \\caption{Log-likelihood for 3000 iterations after burn-in of 6000 for each\n  simulation setup. \\textbf{More burn-in} is needed in at least three of the runs\n  (e.g. (k), (l), (t)).}\n  \\label{fig:ll}\n\\end{figure}\n\n\\newpage\n\\section{Posterior mean of $Z$}\n\\begin{figure}[H]\n  \\begin{center}  % 6 x 5\n    \\imgtemplate{Zmean.pdf}{0.15}\n  \\end{center}\n  % TODO: Write more?\n  \\caption{Posterior means of $Z$ for each run. When $\\phi=0$, the number of\n  recovered features is 0 to 1, for $Z^{1,\\true}$. In contrast, number of\n  recovered features when $\\phi > 0$ is between 6 and 7, with the missing\n  feature being feature 7. This is perhaps due to the added left-skew in the observed\n  data, making it more feasible for features to be explained by mixture components\n  with negative means. The $\\sigma_2^i$ learned when $\\phi=0$ tended to be\n  much larger as well. Again, mixing may also be better when $\\phi>0$ because \n  the exploration of different configurations of $Z$ is encourage. There is a\n  tendency for $Z$ to be extremely sparse when $\\phi=0$, due to the IBP prior.\n  %\n  For $Z^{2,\\true}$, between 2 and 6 features were recovered when $\\phi=0$.\n  When $\\phi > 0$, all features were recovered. But in $(n)$, \n  eight features were recovered, the extra feature being similar to one of the\n  features. However, it's estimated abundance was less than 1\\%.\n  %\n  For Data 3, when $\\phi=0$, the only features that were recovered are\n  features 3, 5, 6, and 7, which are the most representative features. i.e.\n  Features 1 and 2, which are rare, are merged with feature 3, which is\n  abundant and similar to the former features. When $\\phi>0$, 6 to 7 features were\n  recovered. The missing features were either feature 1 or 2, which is similar to \n  and merged with feature 3. Feature 7, though rare, was recovered, likely because\n  it is distinct.}\n  \\label{fig:zmean}\n\\end{figure}\n \n\\newpage\n\\section{Posterior estimate of $Z_1$}\n\\begin{figure}[H]\n  \\begin{center}  % 6 x 5\n    \\imgtemplate{Z1.pdf}{0.15}\n  \\end{center}\n  % TODO: Write more?\n  \\caption{}\n  \\label{fig:z1est}\n\\end{figure}\n\n\\newpage\n\\section{Posterior estimate of $Z_2$}\n\\begin{figure}[H]\n  \\begin{center}  % 6 x 5\n    \\imgtemplate{Z2.pdf}{0.15}\n  \\end{center}\n  % TODO: Write more?\n  \\caption{}\n  \\label{fig:z2est}\n\\end{figure}\n\n\\newpage\n\\section{Posterior estimate of $y_1$}\n\\begin{figure}[H]\n  \\begin{center}  % 6 x 5\n    \\imgtemplate{y1.pdf}{0.15}\n  \\end{center}\n  % TODO: Write more?\n  \\caption{}\n  \\label{fig:y1est}\n\\end{figure}\n\n\\newpage\n\\section{Posterior estimate of $y_2$}\n\\begin{figure}[H]\n  \\begin{center}  % 6 x 5\n    \\imgtemplate{y2.pdf}{0.15}\n  \\end{center}\n  % TODO: Write more?\n  \\caption{}\n  \\label{fig:y2est}\n\\end{figure}\n\n\\newpage\n\\section{Box plots for $p_i$}\n\\begin{figure}[H]\n  \\begin{center}  % 6 x 5\n    \\imgtemplate{p.pdf}{0.15}\n  \\end{center}\n  % TODO: Write more?\n  \\caption{The posterior mean of $p_i$ is usually between 0.2 and 0.4, and\n  sometimes between 0.4 and 0.5. The spread is large.}\n  \\label{fig:ppost}\n\\end{figure}\n\n\\newpage\n\\section{Trace plots for $p_1$}\n\\begin{figure}[H]\n  \\begin{center}  % 6 x 5\n    \\imgtemplate{p1_trace.pdf}{0.15}\n  \\end{center}\n  % TODO: Write more?\n  \\caption{}\n  \\label{fig:p1trace}\n\\end{figure}\n\n\\newpage\n\\section{Trace plots for $p_2$}\n\\begin{figure}[H]\n  \\begin{center}  % 6 x 5\n    \\imgtemplate{p2_trace.pdf}{0.15}\n  \\end{center}\n  % TODO: Write more?\n  \\caption{}\n  \\label{fig:p2trace}\n\\end{figure}\n\n\\newpage\n\\section{Trace plots for $\\mu^\\star$}\n\\begin{figure}[H]\n  \\begin{center}  % 6 x 5\n    \\imgtemplate{mus_trace.pdf}{0.15}\n  \\end{center}\n  % TODO: Write more?\n  \\caption{Trace plots for $\\mu^\\star_z$. Note that in (a) and (j) the variance\n  for the positive mean components is large because they are not used. Effectively,\n  they are being sampled from the prior.}\n  \\label{fig:mus-trace}\n\\end{figure}\n\n\\newpage\n\\section{Posterior distributions for $\\mu^\\star$}\n\\begin{figure}[H]\n  \\begin{center}  % 6 x 5\n    \\imgtemplate{mus.pdf}{0.15}\n  \\end{center}\n  % TODO: Write more?\n  \\caption{}\n  \\label{fig:mus}\n\\end{figure}\n\n\n\\newpage\n\\section{Trace plots for $\\sigma^2$}\n\\begin{figure}[H]\n  \\begin{center}  % 6 x 5\n    \\imgtemplate{sig2_trace.pdf}{0.15}\n  \\end{center}\n  % TODO: Write more?\n  \\caption{Trace plots for $\\sigma^2_i$. Note the jump in (t) is similar\n  to the jump in the log likelihood.}\n  \\label{fig:sig2-trace}\n\\end{figure}\n\n\\newpage\n\\section{Posterior distributions for $\\sigma^2$}\n\\begin{figure}[H]\n  \\begin{center}  % 6 x 5\n    \\imgtemplate{sig2.pdf}{0.15}\n  \\end{center}\n  % TODO: Write more?\n  \\caption{}\n  \\label{fig:sig2}\n\\end{figure}\n\n\\newpage\n\\section{Posterior distributions for sample 1 marker 1}\n\\begin{figure}[H]\n  \\begin{center}  % 6 x 5\n    \\imgtemplate{dden/dden_i1_j1.pdf}{0.15}\n  \\end{center}\n  % TODO: Write more?\n  \\caption{Data fit is rather good.}\n  \\label{fig:ddi1j1}\n\\end{figure}\n\n\\newpage\n\\section{Posterior distributions for sample 1 marker 2}\n\\begin{figure}[H]\n  \\begin{center}  % 6 x 5\n    \\imgtemplate{dden/dden_i1_j2.pdf}{0.15}\n  \\end{center}\n  % TODO: Write more?\n  \\caption{}\n  \\label{fig:ddi1j2}\n\\end{figure}\n\n\\newpage\n\\section{Posterior distributions for sample 2 marker 1}\n\\begin{figure}[H]\n  \\begin{center}  % 6 x 5\n    \\imgtemplate{dden/dden_i2_j1.pdf}{0.15}\n  \\end{center}\n  % TODO: Write more?\n  \\caption{}\n  \\label{fig:ddi2j1}\n\\end{figure}\n\n\\newpage\n\\section{Posterior distributions for sample 2 marker 2}\n\\begin{figure}[H]\n  \\begin{center}  % 6 x 5\n    \\imgtemplate{dden/dden_i2_j2.pdf}{0.15}\n  \\end{center}\n  % TODO: Write more?\n  \\caption{}\n  \\label{fig:ddi2j2}\n\\end{figure}\n\n\\newpage\n\\section{Posterior distributions for sample 2 marker 6}\n\\begin{figure}[H]\n  \\begin{center}  % 6 x 5\n    \\imgtemplate{dden/dden_i1_j6.pdf}{0.15}\n  \\end{center}\n  % TODO: Write more?\n  \\caption{}\n  \\label{fig:ddi1j6}\n\\end{figure}\n\n\\newpage\n\\section{Posterior distributions for sample 2 marker 6}\n\\begin{figure}[H]\n  \\begin{center}  % 6 x 5\n    \\imgtemplate{dden/dden_i2_j6.pdf}{0.15}\n  \\end{center}\n  % TODO: Write more?\n  \\caption{}\n  \\label{fig:ddi2j6}\n\\end{figure}\n\n\\newpage\n\\section{Missing Mechanism}\n\\begin{figure}[H]\n  \\begin{center}  % 6 x 5\n    \\begin{tabular}{cc}\n      \\includegraphics[scale=.5]{\\imgdir/dataseed1-mcmcseed1-phi1.0-Zind1/img/missmech_1.pdf} &\n      \\includegraphics[scale=.5]{\\imgdir/dataseed1-mcmcseed1-phi1.0-Zind1/img/missmech_2.pdf} \\\\\n      \\includegraphics[scale=.5]{\\imgdir/dataseed1-mcmcseed1-phi1.0-Zind2/img/missmech_1.pdf} &\n      \\includegraphics[scale=.5]{\\imgdir/dataseed1-mcmcseed1-phi1.0-Zind2/img/missmech_2.pdf} \\\\\n      \\includegraphics[scale=.5]{\\imgdir/dataseed1-mcmcseed1-phi1.0-Zind3/img/missmech_1.pdf} &\n      \\includegraphics[scale=.5]{\\imgdir/dataseed1-mcmcseed1-phi1.0-Zind3/img/missmech_2.pdf} \\\\\n    \\end{tabular}\n  \\end{center}\n\\label{fig:missmech}\n\\end{figure}\n\n% Uncomment if using bibliography:\n\\bibliography{sim}\n\n\\end{document}\n", "meta": {"hexsha": "66cad6d8db80e40d6ecd827e2adbcb0dc13cc93a", "size": 13335, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "runs/sim-study/notes/test-sim-6-7-20/test-sim-6-7-20.tex", "max_stars_repo_name": "luiarthur/CytofRepFAM.jl", "max_stars_repo_head_hexsha": "1f997d1620d74861c5bde5559ebdd1e6c449b9e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "runs/sim-study/notes/test-sim-6-7-20/test-sim-6-7-20.tex", "max_issues_repo_name": "luiarthur/CytofRepFAM.jl", "max_issues_repo_head_hexsha": "1f997d1620d74861c5bde5559ebdd1e6c449b9e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-02-05T01:26:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-16T04:13:03.000Z", "max_forks_repo_path": "runs/sim-study/notes/test-sim-6-7-20/test-sim-6-7-20.tex", "max_forks_repo_name": "luiarthur/CytofRepFAM.jl", "max_forks_repo_head_hexsha": "1f997d1620d74861c5bde5559ebdd1e6c449b9e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1565420561, "max_line_length": 110, "alphanum_fraction": 0.6753655793, "num_tokens": 4708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.3118072787661869}}
{"text": "% !TEX root=/home/tavant/these/manuscript/src/manuscript.tex\n\n% \\FloatBarrier\n\n\\section{Comparison of the sheath model with PIC simulations} \\label{subsec-picandmodel}\n\n  % \\begin{figure}[hbt]\n  %   \\centering\n  %   \\includegraphics[width=\\textwidth]{dphi_polytropic_noSEE}\n  %   \\caption{PIC simulation results (with SEE) compared to the polytropic limit without SEE.}\n  %   \\label{fig-polytropic_pic_noSEE}\n  % \\end{figure}\n  % \n  % \\begin{figure}[hbt]\n  %   \\centering\n  %   \\includegraphics[width=\\textwidth]{Summary_polytropic_SEE.pdf}\n  %   \\caption{Comparison of the PIC simulation results with the polytropic model with SEE.}\n  %   \\label{fig-polytropic_see_summary}\n  % \\end{figure}\n\n  We compare in this section the characteristics of the plasma wall interaction observed in the \\ac{PIC} simulations with the fluid model developed in \\cref{sec-fluid_poly_see}.\n  We first compare the mean values in the parametric study over the crossover energy $\\crover$, then we investigate the oscillations of regime {\\bf II}.\n\n  \\subsection{Parametric study of the modified sheath model} \\label{subsec-param_sheath_see}\n\n    The variables of interest to characterize the plasma-wall interaction are the averaged electron emission rate $\\rate$ and the plasma potential drop to the wall.\n    The only inputs of the modified sheath model are the electron mean temperature in the bulk $\\Teb$, as well as the polytropic index $\\gamma$.\n    As seen in \\cref{subsec-fluid_see_polyfit}, the polytropic index of the total electron population is measured in the \\ac{PIC} simulations to be $\\gamma=1.36$.\n    However, the electrons going toward the wall present a different index, measured from the bulk \\ac{EVDF} to $\\gamma=1.28$.\n    These two values will be compared.\n\n    \\paragraph{One polytropic index: $\\gamma=1.36$\\\\}\n    \n    Using the mean electron temperature measured in the \\ac{PIC} simulations, we first compute the plasma potential drop $\\dphi$ by solving \\cref{eq-costseepoly} with $\\gamma=1.36$.\n    As shown in \\cref{fig-Te2_epsi}, up to three solutions are possible.\n    The emission rate $\\rate$ is computed using \\cref{eq-seemaxw_poly}.\n    As discussed previously, the rate is limited to $\\ratecr=0.982$ to take into account the \\ac{SCL} regime.\n\n    The results of the sheath modeled are compared to the \\ac{PIC} simulation results in \\Cref{fig-Poly_model_vs_pic}.\n    The plasma potential drop in \\cref{fig-Poly_model_vs_pic}.{\\bf a} is increased by $\\sqrt{\\gamma} \\Teb/2$ to account for the pre-sheath drop.\n    \n    \\begin{figure}[!hbt]\n      \\centering\n      \\includegraphics[width=\\textwidth]{Poly_model_vs_pic_gamma136.pdf}\n      \\caption{Comparison of the PIC simulations and the sheath model using $\\gamma=1.28$ for ({\\bf a}) the plasma potential drop from the center to the wall, and ({\\bf b}) the electron emission yield calculated with \\cref{eq-seemaxw_poly}. On the panel ({\\bf b}) the red dotted line correspond to the value of $\\ratemaxw$ obtained with \\cref{eq-seemaxw_poly} using the value of $\\dphi$ showed on the panel ({\\bf a}).   }\n      \\label{fig-Poly_model_vs_pic}\n    \\end{figure}\n\n    Concerning $\\dphi$, we see that the sheath model combining the polytropic state law and the electron emission is in good agreement with the \\ac{PIC} simulations.\n    We see that the region where the three solutions coexist corresponds well with the regime {\\bf II}.\n\n    Concerning the emission rate $\\rate$, we observe that the value $\\gamma=1.36$ under estimates $\\rate$ compared to the values of the \\ac{PIC} simulations for $\\crover > 70\\,\\volt$.\n    On the other hand, $\\gamma=1.28$ is in very good agreement on the whole range of $\\crover$.\n    Interestingly, the saturation of the mean electron emission rate for low values of $\\crover$ in the \\ac{PIC} simulation is greater than the critical value $\\ratecr$.\n    This is because the critical value corresponds to the start of the \\ac{SCL} regime, with a radial electric at the wall equal to zero.\n    However, we observe in the \\ac{PIC} simulation a small potential well, meaning that the \\ac{SEE} rate is slightly above $\\ratecr$.\n    \n    \\paragraph{Two polytropic index: $\\gamma=1.36$ and $1.28$\\\\}\n    We saw in \\cref{fig-Poly_model_vs_pic} that $\\rate$ is better described using $\\gamma=1.28$.\n    Therefore, we modify the sheath model to take into account two polytropic index\\string: $\\gamma=1.36$ is used to described the electron density, but now $\\gamma=1.28$ is used to compute the temperature at the wall of the forward electron population, hence the  \\ac{SEE} rate.\n    The results of the modified sheath model is shown in \\Cref{fig-Poly_model_vs_pic2}.\n    We see that the modified sheath modeled using two values of $\\gamma$ does not affect significantly the value of the sheath potential drop $\\dphi$.\n    However, the secondary electron emission rate is in better agreement with the \\ac{PIC} simulation results.\n    \n    \\begin{figure}[!hbt]\n      \\centering\n      \\includegraphics[width=\\textwidth]{Poly_model_vs_pic_2gamma.pdf}\n      \\caption{Comparison of the PIC simulations and the sheath model using two values of $\\gamma$ ($\\gamma=1.36$ for the electron density, and $\\gamma=1.28$ for the forward electron temperature at the wall) for ({\\bf a}) the plasma potential drop from the center to the wall, and ({\\bf b}) the electron emission yield calculated with \\cref{eq-seemaxw_poly}. }\n      \\label{fig-Poly_model_vs_pic2}\n    \\end{figure}\n    \n    \n    \n  \\subsection{Sheath oscillations of regime {\\bf II}} \\label{subsec-pic_scheath_RSO}\n  \n    The regime {\\bf II} is characterized by the presence of oscillations between two meta-stable regimes {\\bf III} and {\\bf I}, one with a low emissivity and the other with a high emissivity.\n    \\Cref{fig-long_time} shows the temporal evolution of the electron temperature and the plasma potential relative to the wall for $\\crover=45\\,\\volt$.\n    The electron temperature is computed over the whole electron population in the \\ac{PIC} simulations.\n    Both the radial temperature $\\Te_{,R}$ and the total temperature $\\Te$ are shown (see \\cref{eq-3Te} for their definition).\n    The plasma potential $\\dphi$ shown is measured at the center of the radial direction of the simulation, averaged over the azimuthal direction.\n    \n     \\renewcommand\\subfigurewidth{0.7\\textwidth}\n    \\begin{figure}[!hbt]\n      \\centering\n      % \\begin{tabular}{@{} c }\n      %   %\\subfigure{long_time_dphi}{a}{20,20}\\\\\n      %   \\subfigure{long_time_Te}{b}{20,20} \n      % \\end{tabular}\n      \\includegraphics[width=\\textwidth]{long_time_Te}\n      \\caption{Temporal evolution of ({\\bf a}) the plasma potential $\\dphi$ and ({\\bf b}) the electron temperatures\\string: $\\Te_{,R}$ is the radial temperature, and $\\Te$ is the total temperature.}\n      \\label{fig-long_time}\n    \\end{figure}\n    \\renewcommand\\subfigurewidth{0.47\\textwidth}\n    \n    We clearly see in \\cref{fig-long_time} the quasi-periodic oscillations between the two states.\n    We observe that the electron temperature is slightly anisotropic, with the radial temperature smaller than the axial temperature.\n    This anisotropy observed was not taken into account in the sheath model developed in this chapter.\n    More precisely, the radial temperature $\\Te_{,R}$ is linked to the thermal flux of electron toward the wall, while the total temperature $\\Te$ changes the electron emission rate $\\ratemaxw$.\n    However, the degree of anisotropy is not very high, as it is of the order of 10\\% when the sheath is not inverted.\n    When the sheath is inverted, the anisotropy is of the order of 25\\%, as the electrons with a large radial energy are quickly absorbed.\n    However in the \\ac{SCL} regime, we assume that the electron emission rate saturates at $\\rate=\\ratecr$, hence in this regime the impact of the total energy is less important with respect of the radial energy.\n    Hence, we will compare the prediction using only the radial temperature $\\Te_{,R}$ or the total, averaged, temperature $\\Te$, but not the two of them together.\n    \n    \\Cref{fig-dphi_te_PIc2} shows the potential drop as a function of the radial electron temperature $\\Te_R$ and the total electron temperature $\\Te = (\\Te_R + \\Te_{\\theta} + \\Te_z)/3$ measured in the \\ac{PIC} simulation (same case as \\cref{fig-long_time}).\n    Is also shown the theoretical solutions obtained with the model of \\cref{sec-fluid_poly_see} using constant polytropic indexes $\\gamma=1.36$ and $1.28$, and $\\crover=45\\,\\volt$, and a pre-sheath potential drop of $\\Teb/2$.\n    \n    \\begin{figure}[hbt]\n      \\centering\n      \\includegraphics[width=0.5\\textwidth]{parametric_PIC_dphi_Te_two_gamma_bis}\n      \\caption{Plasma potential as a function of (left) the radial electron temperature $\\Te_R$ and (right) the total electron temperature. The blue line is the \\acs{PIC} results presented in \\cref{fig-long_time}, the orange dashed lines correspond to the theoretical values with $\\gamma=1.36$, and the green dotted-dashed line is computed with $\\gamma=1.28$.}\n      \\label{fig-dphi_te_PIc2}\n    \\end{figure}\n    % \n    % \n    % \\begin{figure}[hbt]\n    %   \\centering\n    %   \\includegraphics[width=\\textwidth]{parametric_PIC_dphi_Te_bis}\n    %   \\caption{Plasma potential as a function of (left) the radial electron temperature and (right) the total electron temperature. The blue markers represent the \\acs{PIC} results presented in \\cref{fig-long_time}, and the orange dashed lines correspond to the theoretical values with $\\gamma=1.35$.}\n    %   \\label{fig-dphi_te_PIc}\n    % \\end{figure}\n    \n    We see in \\cref{fig-dphi_te_PIc2} that the sheath characteristics observed in the \\ac{PIC}  simulations match relatively well the theoretically values obtained from the sheath model.\n    In particular, we see the co-existence of the two solutions of $\\dphi$ observed for the same electron temperature, which corresponds to the domain of electron temperature for which the sheath model also predicts multiple solutions.\n    \n    During the state corresponding to regime {\\bf III} (high value of  $\\dphi$), the \\ac{PIC} values are too noisy to clearly determine if the sheath follows the first or the second branch of the solutions.\n    On the other hand, we see relatively well the correspondence between the \\ac{PIC} results and the theory for the regime {\\bf I} (low value of $\\dphi$.\n    The agreement with the polytropic sheath model using $\\gamma = 1.36$ is better during the standard sheath regime, as the maximum electron temperature $\\Te^{(1)}$ observed in the simulation is higher than the value at $\\gamma=1.28$.\n    However, during the \\ac{SCL} regime the two values return the same plasma potential.\n    \n    % As discussed previously, the value of the polytropic index computed by propagating the \\ac{EVDF}, is $\\gamma=1.28$.\n    % \\Cref{fig-dphi_te_PIc2} shows the same results as \\cref{fig-dphi_te_PIc}, but  the theoretical values of $\\dphi$ using $\\gamma=1.28$ are overlaid.\n    % We see that using the value $\\gamma=1.28$ does not change significantly the value of the solution, except for the maximum value of the electron temperature $\\Te^{(1)}$ for the first branch of the solution, hence the domain of temperature where the three solutions coexist.\n    % In the case of $\\gamma=1.28$, the \\ac{PIC} simulation result agreement with the theory is worse than for $\\gamma=1.35$.\n    \n    % \\begin{figure}[hbt]\n    %   \\centering\n    %   \\includegraphics[width=\\textwidth]{parametric_PIC_dphi_Te_two_gamma_bis}\n    %   \\caption{Similarly to \\cref{fig-dphi_te_PIc}, Plasma potential as a function of (left) the radial electron temperature and (right) the total electron temperature. The blue markers represent the \\acs{PIC} results presented in \\cref{fig-long_time}, the orange dashed lines correspond to the theoretical values with $\\gamma=1.35$, and the green dotted-dashed line is computed with $\\gamma=1.28$.}\n    %   \\label{fig-dphi_te_PIc2}\n    % \\end{figure}\n    \n    \\paragraph{Electron power balance\\\\}\n    The total electron power balance integrated aver the simulation domain can be expressed as\n    \\begin{equation} \\label{eq-GMel}\n      \\deriv{}{t} \\lp \\frac{3}{2} V n_e e \\Te \\rp = P_{\\rm abs} - P_{\\rm loss},\n    \\end{equation}\n    with $V$ the  volume of the simulation domain, $n_e$ the average electron density,  $P_{\\rm abs}$ the total absorbed power, and $P_{\\rm loss}$ the total power lost.\n    The absorbed power $P_{\\rm abs}$ is assumed to be the Joule heating\n    \\begin{equation} \\label{eq-pabs}\n      P_{\\rm abs} = V n_e e \\vect{v_e} \\cdot \\vect{E} = V n_e e v_{e, z} E_z = V n_e e \\mu_e  E_z^2\n    \\end{equation}\n    with $E_z$ the imposed axial electric field and $\\mu_e$ the electron axial mobility.\n    From the parametric study of \\cref{ch-2}, we have $\\mu_e \\simeq 5.6 \\,\\meter\\squared\\per\\volt\\per\\second$.\n    As $E_z$ is imposed and the electron density is constant, then the absorbed power is constant.\n    \n    The power loss $P_{\\rm loss}$ is assumed to be governed by losses at the wall.\n    Hence, as developed in \\cref{sec-fluid}\n    \\begin{equation} \\label{eq-Ploss}\n      P_{\\rm loss} = S \\frac{1}{4} h n_e u_b 2 e\\Tew\n    \\end{equation}\n    with $S$ the surface of the wall of the simulation domain, $h \\sim 1$ is the ratio between the mean plasma density and the plasma density at the sheath edge, $u_b = \\sqrt{\\frac{\\gamma e \\Te}{m_i}}$ is the modified Bohm velocity and $\\Tew$ is the electron temperature at the wall.\n    Hence, we have\n    \\begin{equation} \\label{eq-MG_bis}\n    \\deriv{}{t} \\Te = \\frac{2}{3} \\mu_e  E_z^2 - \\frac{S}{V} \\frac{1}{3} \\sqrt{\\frac{\\gamma e \\Te}{m_i}}  \\lp \\Te - \\frac{\\gamma - 1}{\\gamma} \\dphi \\rp,\n    \\end{equation}\n    where $\\frac{V}{S} = L_R$.\n    \\Cref{eq-MG_bis} is coupled with the sheath model that returns $\\dphi$ as a function of $\\Te$.\n    Concerning the three co-existing solutions, we assume that the sheath follows the same branch until the threshold temperature $\\Te^{(2)}$, or $\\Te^{(1)}$, is reached when the electron temperature increases, or decreases, respectively.\n    When $\\Te^{(1)}$ or $\\Te^{(2)}$ is reached, the sheath jumps to the other solution.\n    \n    \n    \\begin{figure}[!hbt]\n      \\centering\n      \\includegraphics[width=0.9\\textwidth]{Power_balance_Te.pdf}\n      \\caption{Evolution of the power balance $P_{\\rm abs}-P_{\\rm loss}$ as a function of the electron temperature for ({\\bf a}) $L_R=2\\,\\centi\\meter$ and ({\\bf b}) $L_R=4\\,\\centi\\meter$, with $\\crover=45\\,\\volt$. The blue line corresponds to the increasing temperature for the standard sheath solution, and the orange line correspond to the decreasing temperature in the inverted sheath solution. The markers represent the limit values of the power balance.}\n      \\label{fig-powerbalance}\n    \\end{figure}\n    \n    \\Cref{fig-powerbalance} shows the evolution of the power balance with the electron temperature for two values of $L_R=2$ and $4\\,\\centi\\meter$.\n    We see for $L_R=2\\,\\centi\\meter$ in \\cref{fig-powerbalance}.{\\bf a} that starting from $\\Te=20\\,\\volt$ the power balance is positive until $\\Te\\simeq50\\,\\volt$.\n    In this condition, the system present a stable solution at that temperature.\n    In contrast for $L_R=4\\,\\centi\\meter$ in \\cref{fig-powerbalance}.{\\bf b} the power balance is positive along all of the blue curve, meaning that the electron temperature will rise until the sheath jumps to the \\ac{SCL} regime.\n    There, the power balance is negative, so the electron temperature will decreases until $\\Te\\simeq35\\,\\volt$ for which the power is balanced.\n    \n    The power balance of \\cref{eq-MG_bis} cannot present an oscillating evolution, as there is a temperature for which the power is balance.\n    This is because the maximum power balance in the \\ac{SCL} regime (blue circle markers in  \\cref{fig-powerbalance}) is above the minimum value in the standard regime (black triangular markers)\n    In order to observe the oscillations, one should have the circle marker below the triangular one.\n    \n    \n    % \\begin{figure}[hbtp]\n    %   \\centering\n    %   \\includegraphics[width=\\textwidth]{global_model.pdf}\n    %   \\caption{Results of the electron power balance. ({\\bf a}) shows the temporal evolution of the electron power balance from \\cref{eq-MG_bis}, ({\\bf b}) shows the temporal evolution of the electron temperature, and ({\\bf c}) shows the evolution of the plasma potential $\\dphi$ as a function of $\\Te$. }\n    %   \\label{fig-GM_results}\n    % \\end{figure}\n    % \n    % \\Cref{fig-GM_results} shows the results obtained by using the electron power balance.\n    % \\cref{fig-GM_results}.{\\bf a} and {\\bf b} shows the temporal evolution of the power balance and the electron temperature $\\Te$, and \\cref{fig-GM_results}.{\\bf c} shows the plasma potential as a function of $\\Te$.\n    % Starting from an initial value $\\Te=10\\,\\volt$, the electron temperature increases until reaching $\\Te^{(1)}$.\n    % Then, the sheath enters the \\ac{SCL} regime and $\\Te$ decreases until reaching $\\Te^{(2)}$.\n    % \n    % The period of the oscillation is of the order of $0.1\\,\\micro\\second$, which is significantly shorter than the \\ac{PIC} simulation.\n    % Indeed, the period of the sheath oscillations observed in \\cref{fig-long_time} is approximately $T = 2\\,\\micro\\second$.\n    \n    \\paragraph{ Ion dynamics \\\\}\n\n    One has to note that the modified sheath model is stationary, while the oscillations observed are relatively fast.\n    The ion dynamics can be estimated to be\n    \\begin{equation} \\label{eq-ti}\n      \\tau_i = \\frac{2 \\pi}{\\opi} = 0.1 \\,\\micro\\second.\n    \\end{equation}\n    \n    Another estimation of the ion time scale is the time needed by an ion to reach the sheath edge from the center of the discharge.\n    Assuming a constant electric field $E_{\\rm ps} = \\frac{\\Te}{L_R}$ in the pre-sheath, we have\n    \\begin{equation} \\label{eq-tof}\n      t_{\\rm flight} = L_R \\sqrt{\\frac{m_i}{e \\Te}} = 3.7 \\,\\micro\\second.\n    \\end{equation}\n    with $L_R=2\\,\\centi\\meter$ and $\\Te=40\\,\\volt$.\n    The period of the sheath oscillations observed $T = 2\\,\\micro\\second$ is between $\\tau_i$ and $t_{\\rm flight}$.\n    Hence, we can expect the ion dynamics to affect the plasma sheath characteristics during the sheath oscillations of the regime {\\bf II}.\n    \n    \n    The sheath oscillations of regime {\\bf II} have been observed in \\citet{croes2017} with three different ion masses: xenon, krypton and argon.\n    The results are shown in \\cref{fig-RSO_altern}.\n    We see that the period of the oscillations vary with the ion mass.\n    More precisely, the period of oscillations decreases with the decrease of the ion mass.\n    This observation confirms that the ions have a role in the dynamics of the oscillations.\n    \n    \\begin{figure}[hbt]\n      \\centering\n      \\includegraphics[width=\\defaultwidth]{SEE_RSOs.png}\n      \\caption{Temporal evolution of the SEE rate $\\rate$ measured in the PIC simulations for different gases (xenon, krypton, and argon), taken from \\citet{croes2017}.}\n      \\label{fig-RSO_altern}\n    \\end{figure}\n    \n    ", "meta": {"hexsha": "43d5a31a4c789a6363c8530f059a820e9f0cb93d", "size": 19025, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/Chapitre4/43-model_vs_PIC.tex", "max_stars_repo_name": "antoinetavant/PhD_thesis_manuscript", "max_stars_repo_head_hexsha": "1fdaf99356f75abc488edf1f30b5dd65f22bcdca", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Chapitre4/43-model_vs_PIC.tex", "max_issues_repo_name": "antoinetavant/PhD_thesis_manuscript", "max_issues_repo_head_hexsha": "1fdaf99356f75abc488edf1f30b5dd65f22bcdca", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Chapitre4/43-model_vs_PIC.tex", "max_forks_repo_name": "antoinetavant/PhD_thesis_manuscript", "max_forks_repo_head_hexsha": "1fdaf99356f75abc488edf1f30b5dd65f22bcdca", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 80.6144067797, "max_line_length": 459, "alphanum_fraction": 0.7207358739, "num_tokens": 5145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.311757023638045}}
{"text": "\\documentclass[a4paper,11pt]{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage{algorithmic}\n\\usepackage{algorithm}\n\\usepackage{pst-plot}\n\\usepackage{graphicx}\n\\usepackage{endnotes}\n\\usepackage{graphics}\n\\usepackage{floatflt}\n\\usepackage{wrapfig}\n\\usepackage{amsfonts}\n\\usepackage{amsmath}\n\\usepackage{verbatim}\n\\usepackage{hyperref}\n\\usepackage{multirow}\n\\usepackage{pdflscape}\n \\usepackage{enumitem}\n\n\\usepackage{hyperref}\n\\hypersetup{pdfborder={0 0 0 0}}\n\n\\pdfpagewidth 210mm\n\\pdfpageheight 297mm \n\\setlength\\topmargin{0mm}\n\\setlength\\headheight{0mm}\n\\setlength\\headsep{0mm}\n\\setlength\\textheight{250mm}\t\n\\setlength\\textwidth{159.2mm}\n\\setlength\\oddsidemargin{0mm}\n\\setlength\\evensidemargin{0mm}\n\\setlength\\parindent{7mm}\n\\setlength\\parskip{0mm}\n\n\\newenvironment{exercise}[3]{\\paragraph{Exercise #1: #2 (#3pt)}\\ \\\\}{\n\\medskip}\n\\newcommand{\\question}[2]{\\setlength\\parindent{0mm}\\ \\\\$\\mathbf{Q_#1:}$ #2\\ \\\\}\n\n\\author{\\large{Ilya Kuzovkin, Raul Vicente}}\n\\title{\\huge{Introduction to Computational Neuroscience}\\\\\\LARGE{Practice on Single Neuron Models}}\n\n\\begin{document}\n\\maketitle\n\n\\textbf{A request:} Please track how long it will take to complete this set of exercises. Add this time to your final report.\n\\ \\\\\n\n%\n% Intro\n%\nIn this session we will have a brief look on three different computational models of a neuron: McCulloch-Pitts, Intergrate-and-Fire and Hodgkin-Huxley.\n\n%\n% Logic gates\n%\n\\begin{exercise}{1}{Logic gates}{1}\nOn the lecture we have seen how to construct \\texttt{AND}, \\texttt{OR} and \\texttt{NOT} logic gates using the the McCulloch-Pitts model of a neuron. Your task is to construct more. Please construct the following two gates:\n\\begin{enumerate}\n\\itemsep 0em\n\t\\item \\texttt{NAND}\n\t\\item \\texttt{XOR}\n\\end{enumerate}\n\\paragraph{Hint 1}For the \\texttt{XOR} gate you will need more than one neuron.\n\\paragraph{Hint 2}Same input can go simultaneously to several neurons.\n\\end{exercise}\n\n%\n% Integrate and Fire\n%\n\\begin{exercise}{2}{Integrate and Fire neuron model}{2.5}\nIntegrate and Fire neuron accumulates voltage until it reaches the \\emph{threshold}. After that it fires and resets voltage back to initial value. In this exercise we will model behaviour of such neuron and study its properties. Follow the instructions in the \\texttt{integratefire.m} file and report all figures, essential pieces of code, answers, interpretations and conclusions you will make during the work.\n\n\\paragraph{Note} The \\texttt{TODO} marker will indicate the places where you have to do something: complete the code, plot and report a figure, give an interpretation, etc.\\\\\n\\ \\\\\nThe very final result in this exercise should look something like this\n\\begin{figure}[H]\n   \\centering\n   \\includegraphics[width=0.8\\textwidth]{raster_plot.png} \n   \\caption{10 trials of data generated using Integrate-and-Fire neuron model.}\n   \\label{fig:rasterplot}\n\\end{figure}\n\\end{exercise}\n\n\n%\n% Hodgkin-Huxley\n%\n\\begin{exercise}{3}{Hodgkin-Huxley neuron model}{1.5}\nHodgkin-Huxley model is considered to be the most important computational neuronal model in the neuroscience today. We have the model already implemented in the file \\texttt{HH0.m}, study it. Follow the instructions in the \\texttt{hodgkinhuxley.m} file and report all figures, thoughts, interpretations and conclusions you will have during the work.\n\n\\paragraph{Note} The \\texttt{TODO} marker will indicate places where you have to do something: complete the code, plot and report a figure, give an interpretation, etc.\n\\end{exercise}\n\n\n%\n% Integrate and Fire with synapses\n%\n\\begin{exercise}{4}{Integrate and fire with synapses}{1}\nIn this exercise we will play with somewhat more realistic version of integrate-and-fire model, which receives input not from constant current as we did before, but from incoming (\\emph{presynaptic}) spikes. \\emph{Temporal summation} can lead to the voltage reaching the threshold and then the \\emph{postsynaptic} neuronal response (firing) occurs. Read the tutorial\\footnote{\\url{http://www.dreamincode.net/forums/topic/72868-a-simple-neuron-model-the-integrate-and-fire-neuron}} and study the code given there. Slightly modified code is provided to you in the file \\texttt{integratefiresynapses.m}. Your task is to compe up with three different configurations of spikes on the line 41:\n\\begin{enumerate}\n\t\\item Inside the time window from 0 to 200 ms there will be 4 incoming spikes and 1 output spike.\n\t\\item Inside the time window from 200 to 400 ms there will 5 incoming spikes and 0 output spikes.\n\t\\item Is is possible to produce 2 output spikes with 5 incoming spikes? If yes, then produce it in time window 400 to 600 ms, if not show the maximal voltages you can achieve with 5 input spikes.\n\\end{enumerate}\n\\end{exercise}\n\n\n%\n% SR latch\n%\n\\begin{exercise}{5*}{Simulate memory with $\\neg S$-$\\neg R$ latch}{bonus 2}\nIn electronics there is a circuit, which can \\emph{store} a state. This means that after we \\emph{set} it to some state, it will remain there until we \\emph{reset} it. The whole thing is called \\emph{D latch}, it has a sub-part called \\emph{SR latch}, which again has a subpart called \\emph{$\\neg S$-$\\neg R$ latch}.\n\\begin{enumerate}\n\\itemsep 0em\n\t\\item Watch this video \\url{https://www.youtube.com/watch?v=PCT76PsDr6g} (until 12:26)\n\t\\item and build $\\neg S$-$\\neg R$ latch using McCulloch-Pitts neurons. \n\\end{enumerate}\n\\end{exercise}\n\n\n\\ \\\\\n\\ \\\\\n\\ \\\\\n\\ \\\\\n\\ \\\\\nPlease submit a \\texttt{pdf} report with answers to the questions and comments about your solutions. Include figures, explanations and essential pieces of code. Do not include the code itself as a separate file, your report should give good understanding of what you have done. Please mark how long it took to complete this set of exercises. Upload the \\texttt{pdf} to the practice session page on the course website.\n\n\\end{document}\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "ef66e6c85156b2e6f95ae996064052c06c71d6d9", "size": 5831, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "2015/Practices/05 - Single Neuron Models/text/cns-singleneuron.tex", "max_stars_repo_name": "kuz/Computational-Neuroscience-Course", "max_stars_repo_head_hexsha": "b5657c8672397fa845dca88c2740277e7206cb5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2015-01-24T01:14:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T20:40:00.000Z", "max_issues_repo_path": "2015/Practices/05 - Single Neuron Models/text/cns-singleneuron.tex", "max_issues_repo_name": "NeuroCSUT/Computational-Neuroscience-Course", "max_issues_repo_head_hexsha": "cef9ef2dfc83cbfa91aa9b9ea1f23556aba2e9a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2015/Practices/05 - Single Neuron Models/text/cns-singleneuron.tex", "max_forks_repo_name": "NeuroCSUT/Computational-Neuroscience-Course", "max_forks_repo_head_hexsha": "cef9ef2dfc83cbfa91aa9b9ea1f23556aba2e9a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2018-02-20T12:20:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-08T20:09:22.000Z", "avg_line_length": 42.2536231884, "max_line_length": 687, "alphanum_fraction": 0.7681358258, "num_tokens": 1613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.63341024983754, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.31175701001398215}}
{"text": "\n\\documentclass[notitlepage,11pt]{article}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\usepackage{amsfonts}\n\\usepackage{amsmath}\n\\usepackage{geometry}\n\\usepackage{graphicx}\n\\usepackage{amssymb}\n\\usepackage{makeidx}\n\\usepackage{multicol}\n\n\\setcounter{MaxMatrixCols}{10}\n%TCIDATA{OutputFilter=Latex.dll}\n%TCIDATA{Version=5.50.0.2960}\n%TCIDATA{<META NAME=\"SaveForMode\" CONTENT=\"1\">}\n%TCIDATA{BibliographyScheme=Manual}\n%TCIDATA{LastRevised=Monday, October 19, 2020 03:11:11}\n%TCIDATA{<META NAME=\"GraphicsSave\" CONTENT=\"32\">}\n%TCIDATA{Language=American English}\n\n\\geometry{left=1in,right=1in,top=1.25in,bottom=1in}\n\\input{tcilatex}\n\\begin{document}\n\n\\author{Richard Dennis\\thanks{%\nAddress for Correspondence: Adam Smith Business School, University of\nGlasgow, Main Building, University Avenue, Glasgow G12 8QQ; email:\nrichard.dennis@glasgow.ac.uk.} \\\\\n%EndAName\nUniversity of Glasgow and CAMA}\n\\title{SolveDSGE v0.3.10 --- A User Guide}\n\\date{October 2020}\n\\maketitle\n\n\\begin{abstract}\nSolveDSGE is a Julia package for solving nonlinear Dynamic Stochastic\nGeneral Equilibrium models. \\ A varietry of solution methods are available,\nand they are interchangable so that one solution can be used subsequently as\nan initialization to obtain a more accurate solution.\\noindent\\ \\ The\npackage can compute one- second- and third-order perturbation solutions and\nChebyshev-based, Smolyak-based and piecewise linear-based projection\nsolutions. \\ Once a model has been solved, the package can used used to\nsimulate data and/or compute impulse response functions.\n\n\\vspace{0.12in}\\noindent {JEL Classification: E3, E4, E5.}\n\\end{abstract}\n\n\\thispagestyle{empty}\\newpage \\setlength{\\baselineskip}{18.95pt}%\n\\setcounter{page}{1}\n\n\\section{Introduction}\n\nSolveDSGE is a framework for solving and analyzing Dynamic Stochastic\nGeneral Equilibrium (DSGE) models that is implemented in the programming\nlanguage Julia. \\ SolveDSGE will solve nonlinear DSGE models using\nperturbation methods, producing solutions that are accurate to first,\nsecond, and third order, but this is not its focus. \\ The package's focus is\non applying projection methods to obtain solutions that are globally\naccurate.\n\nObtaining globally accurate solutions to nonlinear DSGE models is\nnotoriously difficult. \\ Solutions are invariably slow to obtain and\nmodel-specific characteristics are often exploited to speed up the solution\nprocess. \\ SolveDSGE does not exploit model-specific characteristics in\norder to solve a model. \\ Instead, SolveDSGE applies the same general\nsolution strategy to all models. \\ Nonetheless, making use of Julia's speed,\nSolveDSGE allows models to be solved \\textquotedblleft relatively\nquickly\\textquotedblright , and it provides users with an easy, unified, way\nof organizing and expressing their model. \\ At the user's request, globally\naccurate\\ solutions can be obtained using Chebyshev polynomials, Smolyak\npolynomials, or piecewise linear approximations, with the solution obtained\nfrom one approximation scheme able to be used as an initialization for the\nothers, allowing greater speed and accuracy to be obtained via a form of\nhomotophy.\n\nTo use SolveDSGE to solve a model, two files must be supplied. \\ The first\nfile (the model file) summarizes the model to be solved. \\ The second file\n(the solution file) reads the model file, solves the model, and performs any\npost-solution analysis.\n\nQuite a lot of time and effort has gone into writing SolveDSGE, together\nwith the underlying modules: ChebyshevApprox, SmolyakApprox, and\nPiecewiseLinearApprox, but it is far from perfect. \\ SolveDSGE may not be\nable to solve your model, or it may not obtain a solution quickly enough to\nbe useful to you. \\ You are welcome to suggest improvements to fix bugs or\nadd functionality. \\ At the same time, I am hopeful that you will find the\npackage useful for your research. \\ If it is, then please cite this User\nGuide and add an acknowledgement of SolveDSGE to your paper/report.\n\n\\section{What types of models can be solved?}\n\nSolveDSGE is designed to solve models that can be written in the following\nstandard form:%\n\\begin{equation}\nE_{t}\\left[ \\mathbf{f}\\left( \\mathbf{x}_{t},\\mathbf{y}_{t},\\mathbf{x}_{t+1},%\n\\mathbf{y}_{t+1},\\mathbf{\\varepsilon }_{t+1}\\right) \\right] =\\mathbf{0},\n\\end{equation}%\nwhere $\\mathbf{x}_{t}$ is a vector of state variables, $\\mathbf{y}_{t}$ is a\nvector of jump variables, and $\\mathbf{\\varepsilon }_{t+1}$ is a vector of\nshocks. \\ The first-order conditions and constraints for the DSGE model are\nspecified equation-by-equation. \\ The shocks, state variables, and jump\nvariables are defined and then SolveDSGE takes the model and expresses it in\nthe form of equation (1) in preparation for solution. \\ Equation (1) covers\na wide set of models, but obviously not all models. \\ In principle SolveDSGE\ncan handle standard business cycle models of the real and new Keynesian\nvarieties, and it can handle models with volatility shocks, but it cannot\nhandle heterogeneous agents models, nor models with generalized Euler\nequation like those that emerge from discretionary policy problems or from\nmodels with quasi-geometric discounting. \\ Allowing for models that contain\ngeneralized Euler equations is a topic for future work. \\ Another set of\nmodels that are not fully accommodated are those where the shocks are\ncontemporaneously correlated. \\ Such models can be solved via the\nperturbation methods, but not via the projection methods (due to the\ntechniques used for quadrature).\n\n\\section{The model file}\n\nSolveDSGE requires that the model that is to be solved be stored in a model\nfile. \\ The model file is simply a text file so there is nothing\nparticularly special about it. \\ Every model file must contain the following\nfive information categories: \\textquotedblleft states:\\textquotedblright ,\n\\textquotedblleft jumps:\\textquotedblright , \\textquotedblleft\nshocks:\\textquotedblright , \\textquotedblleft parameters:\\textquotedblright\n, and \\textquotedblleft equations:\\textquotedblright ; each category name\nmust end with a colon. \\ Each category will begin with its name, such as\n\\textquotedblleft states:\\textquotedblright\\ and conclude with an\n\\textquotedblleft end\\textquotedblright . \\ The model file can present these\nfive categories in any order.\n\nThe information in each category can be presented with one element per line,\nor with multiple elements on each line with each element separated by either\na comma or a semi-colon. \\ So if the jump variables in the model are labor,\nconsumption, and output, then this could be presented in a variety of ways,\nsuch as:\n\n\\bigskip\n\n\\textit{jumps:}\n\n\\textit{labor}\n\n\\textit{consumption}\n\n\\textit{output}\n\n\\textit{end}\n\n\\bigskip\n\nor:\n\n\\textit{jumps:}\n\n\\textit{labor, consumption, output}\n\n\\textit{end}\n\n\\bigskip\n\nor:\n\n\\textit{jumps:}\n\n\\textit{labor; consumption, output}\n\n\\textit{end}\n\n\\bigskip\n\nThe first lag of a variable is denoted with a -1, so the lag of consumption\nis consumption(-1). \\ Similarly the first lead of a variable is denoted with\na +1, so the lead of consumption is denoted consumption(+1). \\ The first lag\nof any model variable is automatically included as a state variable, second\nand higher lags should be given a name, defined by an equation, and included\nas state variables explicitly. \\ The package may allow higher lags to\nprocessed automatically at a later stage.\n\nShocks in the model refers to the innovations to the shock processes, so if\nthe shock process is given by%\n\\begin{equation*}\ntech(+1)=rho\\ast tech+sd\\ast epsilon,\n\\end{equation*}%\nthen \\textquotedblleft $tech$\\textquotedblright\\ will be a state variable,\n\\textquotedblleft $epsilon$\\textquotedblright\\ will be a shock, and\n\\textquotedblleft $rho$\\textquotedblright\\ and \\textquotedblleft $sd$%\n\\textquotedblright\\ will be parameters. \\ If the model is deterministic,\nthen it will contain no shocks.\n\nEvery element in the parameters category and the equations category must\ncontain an \\textquotedblleft $=$\\textquotedblright\\ sign, such as\n\\textquotedblleft $alpha=0.33$\\textquotedblright\\ in the case of the\nparameters category and \\textquotedblleft $output=exp(tech)\\ast capital%\n\\symbol{94}alpha\\ast labor\\symbol{94}(1.0-alpha)$\\textquotedblright\\ in the\ncase of the equations category.\n\n\\subsection{Example}\n\nThe following is an example of a model file for the stochastic growth model:\n\n\\bigskip\n\n\\textit{states:}\n\n\\textit{cap, tech}\n\n\\textit{end}\n\n\\textit{\\bigskip }\n\n\\textit{jumps:}\n\n\\textit{cons}\n\n\\textit{end}\n\n\\textit{\\bigskip }\n\n\\textit{shocks:}\n\n\\textit{epsilon}\n\n\\textit{end}\n\n\\textit{\\bigskip }\n\n\\textit{parameters:}\n\n\\textit{betta = 0.99}\n\n\\textit{sigma = 1.1}\n\n\\textit{delta = 0.025}\n\n\\textit{alpha = 0.30}\n\n\\textit{rho = 0.8}\n\n\\textit{sd = 0.01}\n\n\\textit{end}\n\n\\textit{\\bigskip }\n\n\\textit{equations:}\n\n\\textit{cap(+1) = (1.0 - delta)*cap + exp(tech)*cap\\symbol{94}alpha - cons}\n\n\\textit{cons\\symbol{94}(-sigma) = betta*cons(+1)\\symbol{94}(-sigma)*(1.0 -\ndelta + alpha*exp(tech(+1))*cap(+1)\\symbol{94}(alpha - 1.0))}\n\n\\textit{tech(+1) = rho*tech + sd*epsilon}\n\n\\textit{end}\n\n\\section{Solving a model}\n\nSolving a model is straightforward; it consists of the following steps:\n\n\\begin{enumerate}\n\\item Read and process the model file. \\ During the processing the order of\nvariables in the system may be changed, typically the changes are to place\nthe shocks at the top of the system. \\ After processing is complete you will\nbe told what the variable-order is.\n\n\\item Solve for the model's steady state.\n\n\\item Specify a SolutionScheme. \\ A SolutionScheme specifies the solution\nmethod along with any parameters needed to implement that solution method.\n\n\\item Solve the model according to the chosen SolutionScheme.\n\\end{enumerate}\n\n\\subsection{Reading the model and solving for its steady state}\n\nTo read and process a model file we simply supply the path/filename to the\nget\\_model() function, for example:\n\n\\bigskip\n\n\\textit{process\\_model(\"c:/desktop/model.txt\")}\n\n\\bigskip\n\nThe processed model is saved in the same folder as the model file, which in\nthen retrieved and stored in a structure:\n\n\\bigskip \n\n\\textit{dsge = retrieve\\_processed\\_model(\"c:/desktop/model\\_processed.txt\")}\n\n\\bigskip \n\nWe can then solve for the model's steady state as follows:\n\n\\bigskip\n\n\\textit{ss = compute\\_steady\\_state(dsge,tol,maxiters)}\n\n\\bigskip\n\nwhere \\textit{dsge} is the model whose steady state is to be computed, \n\\textit{tol} is a convergence tolerance, and \\textit{maxiters} is an integer\nspecifying the maximum number of iterations before the function exits.\n\n\\subsection{Specifying a SolutionScheme}\n\nTo solve a model a SolutionScheme must be supplied. \\ A SolutionScheme\nspecifies the solution method and the parameters upon which that solution\nmethod relies. \\ The solution methods in SolveDSGE are either perturbation\nmethods or projection methods. \\ Accordingly, the SolutionSchemes can be\ndivided into PerturbationSchemes or ProjectionSchemes. \\ We present each in\nturn.\n\n\\subsubsection{PerturbationSchemes}\n\nTo solve a model using a perturbation method requires and\nPerturbationScheme. \\ Regardless of the model or the order of the\nperturbation, a PerturbationScheme is a structure with three fields: the\npoint about which to perturb the model (the steady state), a cutoff\nparameter that separates unstable from stable eigenvalues (eigenvalues whose\nmodulus is greater than cutoff will be placed in the model's unstable\nblock), and the order of the perturbation. \\ For a first-order perturbation,\na typical PerturbationScheme might be the following\n\n\\bigskip\n\n\\textit{N = PerturbationScheme(ss,cutoff,\"first\")}\n\n\\bigskip\n\nwhile those for second and third order perturbations might be\n\n\\bigskip\n\n\\textit{NN = PerturbationScheme(ss,cutoff,\"second\")}\n\n\\bigskip\n\nand\n\n\\bigskip\n\n\\textit{NNN = PerturbationScheme(ss,cutoff,\"third\")}\n\n\\bigskip\n\nThe method used to compute a first-order perturbation follows Klein (2000),\nthat for a second-order perturbation follows Gomme and Klein (2011), while\nthat for a third-order perturbation follows Binning (2013) with a refinement\nfrom Levintal (2017). \\ At this point, perturbation solutions higher than\nthird order are not supported.\n\n\\subsubsection{ProjectionSchemes}\n\nProjectionSchemes are either ChebyshevSchemes, SmolyakSchemes, or\nPiecewiseLinearSchemes, and for each of these there is a stochastic (for\nstochastic models) and a deterministic (for deterministic models) version. \\\nThe SolutionScheme for the deterministic case is a special case of the\nstochastic one, so we focus on the stochastic case in what follows.\n\n\\paragraph{ChebyshevSchemes}\n\nSolutions based on Chebyshev polynomials rely on and make use of all of the\nfunctionality of the module ChebyshevApprox. \\ This means that an arbitrary\nnumber of state variables can be accommodated (if you have enough time!) and\nboth tenser-product and complete polynomials can be used. \\ A stochastic\nChebyshevScheme requires the following arguments:\n\n\\begin{itemize}\n\\item initial\\_guess --- This will usually be a vector containing the\nmodel's steady state. \\ It is used as the initial guess at the solution for\nthe case where an initializing solution is not provided (see the section on\nmodel solution below).\n\n\\item node\\_generator --- This is the name of the function used to generate\nthe nodes for the Chebyshev polynomial. \\ Possible options include:\nchebyshev\\_nodes and chebyshev\\_extrema.\n\n\\item node\\_number --- This gives the number of nodes to be used for each\nstate variable. \\ If there is only one state variables then node\\_number\nwill be an integer. \\ When there are two of more state variables it will be\na vector of integers.\n\n\\item num\\_quad\\_nodes --- This is an integer specifying the number of\nquadrature points used to compute expectations.\n\n\\item order --- This defines the order of the Chebyshev polynomial to be\nused in the approximating functions. \\ For a complete polynomial order will\nbe an integer; for a tenser-product polynomial order will be a vector of\nintegers.\n\n\\item domain --- This contains the domain for the state variables over which\nthe solution is obtained. \\ Domain will be a $2-$element vector in the\none-state-variable case and a $2\\times n$ array in the $n$-state-variable\ncase, with the first row of the array containing the upper values of the\ndomain and the second row containing the lower values of the domain. \\ If an\ninitializing solution is provided, then the domain associated with that\ninitializing solution can be used by setting domain to an empty array,\nFloat64[].\n\n\\item tol\\_fix\\_point\\_solver --- This specifies the tolerance to be used in\nthe inner loop to determine convergence at each solution node.\n\n\\item tol\\_variables --- This specifies the tolerance to be used in the\nouter loop to determine convergence of the overall solution.\n\n\\item maxiters --- This is an integer specifying the maximum number of\nouter-loop iterations before the solution exits.\n\\end{itemize}\n\n\\bigskip\n\nAn example of a stochastic ChebyshevScheme is:\n\n\\bigskip\n\n\\textit{C = ChebyshevSchemeStoch(ss,chebyshev\\_nodes,[21,21], 9, 4,[0.1\n30.0; -0.1 20.0],1e-8,1e-6,1000)}\n\n\\bigskip\n\nIn the deterministic case the number of quadrature nodes is not needed, i.e.,\n\n\\bigskip\n\n\\textit{Cdet = ChebyshevSchemeDet(ss,chebyshev\\_nodes,[21,21],4,[0.1 30.0;\n-0.1 20.0],1e-8,1e-6,1000)}\n\n\\paragraph{SmolyakSchemes}\n\nUnderlying the Smolyak polynomial based solution is the module\nSmolyakApprox. \\ This module allows for both isotropic polynomials and\nansiotropic polynomials and several different methods for producing nodes. \\\nSolveDSGE exploits all of this functionality. \\ A stochastic SmolyakScheme\nrequires the following arguments:\n\n\\begin{itemize}\n\\item initial\\_guess --- This will usually be a vector containing the\nmodel's steady state. \\ It is used as the initial guess at the solution for\nthe case where an initializing solution is not provided (see the section on\nmodel solution below).\n\n\\item node\\_generator ---This is the name of the function used to generate\nthe nodes for the Smolyak polynomial. \\ Possible options include:\nchebyshev\\_gauss\\_lobatto and clenshaw\\_curtis\\_equidistant\n\n\\item num\\_quad\\_nodes --- This is an integer specifying the number of\nquadrature points used to compute expectations.\n\n\\item layer --- This is an integer (isotropic case) or a vector of integers\n(ansiotropic case) specifying the number of layers to be used in the\napproximation.\n\n\\item domain --- This contains the domain for the state variables over which\nthe solution is obtained. \\ Domain will be a $2-$element vector in the\none-state-variable case and a $2\\times n$ array in the $n$-state-variable\ncase, with the first row of the array containing the upper values of the\ndomain and the second row containing the lower values of the domain. \\ If an\ninitializing solution is provided, then the domain associated with that\ninitializing solution can be used by setting domain to an empty array,\nFloat64[].\n\n\\item tol\\_fix\\_point\\_solver --- This specifies the tolerance to be used in\nthe inner loop to determine convergence at each solution node.\n\n\\item tol\\_variables --- This specifies the tolerance to be used in the\nouter loop to determine convergence of the overall solution.\n\n\\item maxiters --- This is an integer specifying the maximum number of\nouter-loop iterations before the solution exits.\n\\end{itemize}\n\n\\bigskip\n\nAn example of a stochastic SmolyakScheme is:\n\n\\bigskip\n\n\\textit{S = SmolyakSchemeStoch(ss,chebyshev\\_gauss\\_lobatto,9,3,[0.1 30.0;\n-0.1 20.0],1e-8,1e-6,1000)}\n\n\\bigskip\n\nIn the deterministic case the number of quadrature nodes is not needed, i.e.,\n\n\\bigskip\n\n\\textit{Sdet = SmolyakSchemeDet(ss,chebyshev\\_gauss\\_lobatto,3,[0.1 30.0;\n-0.1 20.0],1e-8,1e-6,1000)}\n\n\\paragraph{PiecewiseLinearSchemes}\n\nTo obtain piecewise linear solutions, SolveDSGE employs the module\nPiecewiseLinearApprox, which allows approximations over an arbitrary number\nof state variables. \\ A stochastic PiecewiseLinearScheme requires the\nfollowing arguments:\n\n\\begin{itemize}\n\\item initial\\_guess --- This will usually be a vector containing the\nmodel's steady state. \\ It is used as the initial guess at the solution for\nthe case where an initializing solution is not provided (see the section on\nmodel solution below).\n\n\\item node\\_number --- This gives the number of nodes to be used for each\nstate variable. \\ If there is only one state variables then node\\_number\nwill be an integer. \\ When there are two of more state variables it will be\na vector of integers.\n\n\\item num\\_quad\\_nodes --- This is an integer specifying the number of\nquadrature points used to compute expectations.\n\n\\item domain --- This contains the domain for the state variables over which\nthe solution is obtained. \\ Domain will be a $2-$element vector in the\none-state-variable case and a $2\\times n$ array in the $n$-state-variable\ncase, with the first row of the array containing the upper values of the\ndomain and the second row containing the lower values of the domain. \\ If an\ninitializing solution is provided, then the domain associated with that\ninitializing solution can be used by setting domain to an empty array,\nFloat64[].\n\n\\item tol\\_fix\\_point\\_solver --- This specifies the tolerance to be used in\nthe inner loop to determine convergence at each solution node.\n\n\\item tol\\_variables --- This specifies the tolerance to be used in the\nouter loop to determine convergence of the overall solution.\n\n\\item maxiters --- This is an integer specifying the maximum number of\nouter-loop iterations before the solution exits.\n\\end{itemize}\n\n\\bigskip\n\nAn example of a stochastic PiecewiseLinearScheme is:\n\n\\bigskip\n\n\\textit{P = PiecewiseLinearStoch(ss,[21,21],9,[0.1 30.0; -0.1\n20.0],1e-8,1e-6,1000)}\n\n\\bigskip\n\nIn the deterministic case the number of quadrature nodes is not needed, i,e,,\n\n\\bigskip\n\n\\textit{Pdet = PiecewiseLinearDet(ss,[21,21],9,[0.1 30.0; -0.1\n20.0],1e-8,1e-6,1000)}\n\n\\subsection{Model solution}\n\nOnce a SolutionScheme is specified we are in a position to solve the model.\n\\ In order to do so we use the solve\\_model() function, which takes either\ntwo or three arguments. \\ For a perturbation solution solve\\_model()\nrequires two arguments: the model to be solved and the SolutionScheme, as\nfollows:\n\n\\bigskip\n\n\\textit{soln\\_first\\_order = solve\\_model(dsge,N)}\n\n\\bigskip\n\n\\textit{soln\\_second\\_order = solve\\_model(dsge,NN)}\n\n\\bigskip\n\n\\textit{soln\\_third\\_order = solve\\_model(dsge,NNN)}\n\n\\bigskip\n\nAlternatively, for a projection solution solve\\_model() takes either two or\nthree arguments. \\ To provide a concrete example, suppose we wish to solve\nour model using Chebyshev polynomials. \\ If we want the projection solution\nto be initialized using the steady state, then solve\\_model() requires only\ntwo arguments: the model to be solved and the SolutionScheme:\n\n\\bigskip\n\n\\textit{soln\\_chebyshev = solve\\_model(dsge,C)}\n\n\\bigskip\n\nIf we want the projection solution to be initialized using the third order\nperturbation solution, then solve\\_model() requires three arguments: the\nmodel to be solved, the initializing solution, and the SolutionScheme:\n\n\\bigskip\n\n\\textit{soln\\_chebyshev = solve\\_model(dsge,soln\\_third\\_order,C)}\n\n\\bigskip\n\nAlthough this example uses a third order perturbation as the initializing\nsolution, any solution (first order, second order, third order, Chebyshev,\nSmolyak, or piecewise linear) can be used.\n\n\\subsubsection{A comment on third-order perturbation}\n\nSometimes it can be useful to add skewness to the shocks, but this is not\neasy to do through the model file. \\ If you want your shocks to be skewed,\nthen you can access the third order perturbation solution by calling:\n\n\\bigskip\n\n\\textit{soln\\_third\\_order = solve\\_third\\_order(dsge,NNN,skewness)}\n\n\\bigskip\n\nwhere skewness is a 2D array containing the skewness coefficients. \\ If\nthere is only one shock, then the skewness array is:%\n\\begin{equation*}\nskewness=E\\left[ \\epsilon _{1}\\epsilon _{1}\\epsilon _{1}\\right] .\n\\end{equation*}%\nIf there are two shocks, then the skewness array is:%\n\\begin{equation*}\nskewness=E\\left[ \n\\begin{array}{cccc}\n\\epsilon _{1}\\epsilon _{1}\\epsilon _{1} & \\epsilon _{1}\\epsilon _{1}\\epsilon\n_{2} & \\epsilon _{1}\\epsilon _{2}\\epsilon _{1} & \\epsilon _{1}\\epsilon\n_{2}\\epsilon _{2} \\\\ \n\\epsilon _{2}\\epsilon _{1}\\epsilon _{1} & \\epsilon _{2}\\epsilon _{1}\\epsilon\n_{2} & \\epsilon _{2}\\epsilon _{2}\\epsilon _{1} & \\epsilon _{2}\\epsilon\n_{2}\\epsilon _{2}%\n\\end{array}%\n\\right] .\n\\end{equation*}%\nEtc.\n\n\\subsubsection{Solution structures}\n\nWhen a model is solved the solution is returned in the form of a structure.\n\\ The exact structure returned depends on the solution method.\n\n\\paragraph{First-order perturbation}\n\nThe first-order perturbation solution takes the following form:%\n\\begin{eqnarray*}\n\\mathbf{x}_{t+1} &=&\\mathbf{h}_{\\mathbf{x}}\\mathbf{x}_{t}+\\mathbf{k\\epsilon }%\n_{t+1}, \\\\\n\\mathbf{y}_{t} &=&\\mathbf{g}_{\\mathbf{x}}\\mathbf{x}_{t}.\n\\end{eqnarray*}%\nThe solution structure for a stochastic first-order perturbation has the\nfollowing fields:\n\n\\begin{itemize}\n\\item hbar --- The steady state of the state variables\n\n\\item hx --- The first-order coefficients in the state-transition equation\n\n\\item k --- The loading matrix on the shocks in the state-transition\nequation.\n\n\\item gbar --- The steady state of the jump variables\n\n\\item gx --- The first-order coefficients in the jump's equation\n\n\\item sigma --- An identy matrix\n\n\\item grc --- The number of eigenvalues with modulus greater than cutoff.\n\n\\item Soln\\_type --- Either \\textquotedblleft determinate\\textquotedblright\n, \\textquotedblleft indeterminate\\textquotedblright , or \\textquotedblleft\nunstable\\textquotedblright .\n\\end{itemize}\n\nThe solution to a deterministic model has the same fields as the stochastic\nsolution with the exceptions of $\\mathbf{k}$ and sigma.\n\n\\paragraph{Second-order perturbation}\n\nThe second-order perturbation solution takes the following form:%\n\\begin{eqnarray*}\n\\mathbf{x}_{t+1} &=&\\mathbf{h}_{\\mathbf{x}}\\mathbf{x}_{t}+\\frac{1}{2}\\mathbf{%\nh}_{\\mathbf{ss}}+\\frac{1}{2}\\left( \\mathbf{I}\\otimes \\mathbf{x}_{t}\\right) \n\\mathbf{h}_{\\mathbf{xx}}\\left( \\mathbf{I}\\otimes \\mathbf{x}_{t}\\right) +%\n\\mathbf{k\\epsilon }_{t+1}, \\\\\n\\mathbf{y}_{t} &=&\\mathbf{g}_{\\mathbf{x}}\\mathbf{x}_{t}+\\frac{1}{2}\\mathbf{g}%\n_{\\mathbf{ss}}+\\frac{1}{2}\\left( \\mathbf{I}\\otimes \\mathbf{x}_{t}\\right) \n\\mathbf{g}_{\\mathbf{xx}}\\left( \\mathbf{I}\\otimes \\mathbf{x}_{t}\\right) .\n\\end{eqnarray*}\n\nThe solution structure for a stochastic second-order perturbation has the\nfollowing fields:\n\n\\begin{itemize}\n\\item hbar --- The steady state of the state variables\n\n\\item hx --- The first-order coefficients in the state-transition equation\n\n\\item hss --- The second-order stochastic adjustment to the mean in the\nstate-transion equation\n\n\\item hxx --- The second-order coefficients in the state-transition equation\n\n\\item k --- The loading matrix on the shocks in the state-transition\nequation.\n\n\\item gbar --- The steady state of the jump variables\n\n\\item gx --- The first-order coefficients in the jump's equation\n\n\\item gss --- The second-order stochastic adjustment to the mean in the\njump's equation\n\n\\item gxx --- The second-order coefficients in the jump's equation\n\n\\item sigma --- An identy matrix\n\n\\item grc --- The number of eigenvalues with modulus greater than cutoff.\n\n\\item Soln\\_type --- Either \\textquotedblleft determinate\\textquotedblright\n, \\textquotedblleft indeterminate\\textquotedblright , or \\textquotedblleft\nunstable\\textquotedblright .\n\\end{itemize}\n\nThe solution to a deterministic model has the same fields as the stochastic\nsolution with the exceptions of $\\mathbf{h}_{\\mathbf{ss}}$, $\\mathbf{k}$, $%\n\\mathbf{g}_{\\mathbf{ss}}$, and sigma.\n\n\\paragraph{Third-order perturbation}\n\nThe third-order perturbation solution takes the following form:%\n\\begin{eqnarray*}\n\\mathbf{x}_{t+1} &=&\\mathbf{h}_{\\mathbf{x}}\\mathbf{x}_{t}+\\frac{1}{2}\\mathbf{%\nh}_{\\mathbf{ss}}+\\frac{1}{2}\\mathbf{h}_{\\mathbf{xx}}\\left( \\mathbf{x}%\n_{t}\\otimes \\mathbf{x}_{t}\\right) +\\frac{1}{6}\\mathbf{h}_{\\mathbf{sss}}+%\n\\frac{1}{6}\\mathbf{h}_{\\mathbf{ssx}}\\mathbf{x}_{t}+\\frac{1}{6}\\mathbf{h}_{%\n\\mathbf{xxx}}\\left( \\mathbf{x}_{t}\\otimes \\mathbf{x}_{t}\\otimes \\mathbf{x}%\n_{t}\\right) +\\mathbf{k\\epsilon }_{t+1}, \\\\\n\\mathbf{y}_{t} &=&\\mathbf{g}_{\\mathbf{x}}\\mathbf{x}_{t}+\\frac{1}{2}\\mathbf{g}%\n_{\\mathbf{ss}}+\\frac{1}{2}\\mathbf{g}_{\\mathbf{xx}}\\left( \\mathbf{x}%\n_{t}\\otimes \\mathbf{x}_{t}\\right) +\\frac{1}{6}\\mathbf{g}_{\\mathbf{sss}}+%\n\\frac{1}{6}\\mathbf{g}_{\\mathbf{ssx}}\\mathbf{x}_{t}+\\frac{1}{6}\\mathbf{g}_{%\n\\mathbf{xxx}}\\left( \\mathbf{x}_{t}\\otimes \\mathbf{x}_{t}\\otimes \\mathbf{x}%\n_{t}\\right) .\n\\end{eqnarray*}\n\nThe solution structure for a stochastic third-order perturbation has the\nfollowing fields:\n\n\\begin{itemize}\n\\item hbar --- The steady state of the state variables\n\n\\item hx --- The first-order coefficients in the state-transition equation\n\n\\item hss --- The second-order stochastic adjustment to the mean in the\nstate-transion equation\n\n\\item hxx --- The second-order coefficients in the state-transition equation\n\n\\item hsss --- The third-order stochastic adjustment to the mean in the\nstate-transition equation\n\n\\item hssx --- The skewness adjustment \\ othe state-transition equation\n\n\\item hxxx --- The third-order coefficents in the state-transition equation\n\n\\item k --- The loading matrix on the shocks in the state-transition\nequation.\n\n\\item gbar --- The steady state of the jump variables\n\n\\item gx --- The first-order coefficients in the jump's equation\n\n\\item gss --- The second-order stochastic adjustment \\ othe mean in the\njump's equation\n\n\\item gxx --- The second-order coefficients in the jump's equation\n\n\\item gsss --- The third-order stochastic adjustment to the mean in the\njump's equation\n\n\\item gssx --- The skewness adjustment in the jump's equation\n\n\\item gxxx --- The third-order coefficients in the jump's equation\n\n\\item sigma --- An identy matrix\n\n\\item grc --- The number of eigenvalues with modulus greater than cutoff.\n\n\\item Soln\\_type --- Either \\textquotedblleft determinate\\textquotedblright\n, \\textquotedblleft indeterminate\\textquotedblright , or \\textquotedblleft\nunstable\\textquotedblright .\n\\end{itemize}\n\nThe solution to a deterministic model has the same fields as the stochastic\nsolution with the exceptions of $\\mathbf{h}_{\\mathbf{ss}}$, $\\mathbf{h}_{%\n\\mathbf{sss}}$, $\\mathbf{h}_{\\mathbf{ssx}}$, $\\mathbf{k}$, $\\mathbf{g}_{%\n\\mathbf{ss}}$, $\\mathbf{g}_{\\mathbf{sss}}$, $\\mathbf{g}_{\\mathbf{ssx}}$, and\nsigma.\n\n\\paragraph{Chebyshev solution}\n\nThe solution structure for the Chebyshev solution has the following fields:\n\n\\begin{itemize}\n\\item variables \\ --- A vector of arrays containing the solution for each\nvariable\n\n\\item weights --- A vector of arrays containing the weights for the\nChebyshev polynomials\n\n\\item nodes --- A vector of vectors containing the Chebyshev nodes\n\n\\item order --- The order of the Chebyshev polynomials\n\n\\item domain --- The domain for the state variables\n\n\\item sigma --- The variance-covariance matrix for the shocks\n\n\\item iteration\\_count --- The number of iterations needed to achieve\nconvergence\n\\end{itemize}\n\nThe solution to a deterministic model has the same fields with the exception\nof sigma.\n\n\\paragraph{Smolyak solution}\n\nThe solution structure for the Smolyak solution has the following fields:\n\n\\begin{itemize}\n\\item variables --- A vector of arrays containing the solution for each\nvariable\n\n\\item weights: --- A vector of vectors containing the weights for the\nChebyshev polynomials\n\n\\item grid --- A matrix containing the Smolyak grid\n\n\\item multi\\_index --- A matrix containing the multi-index underlying the\npolynominals\n\n\\item layer --- The number of layers in the approximation\n\n\\item domain --- The domain for the state variables\n\n\\item sigma --- The variance-covariance matrix for the shocks\n\n\\item iteration\\_count --- The number of iterations needed to achieve\nconvergence\n\\end{itemize}\n\nThe solution to a deterministic model has the same fields with the exception\nof sigma.\n\n\\paragraph{Piecewise linear solution}\n\nThe solution structure for the piecewise linear solution has the following\nfields:\n\n\\begin{itemize}\n\\item variables --- A vector of arrays containing the solution for each\nvariable\n\n\\item nodes --- A vector of vectors containing the Chebyshev nodes\n\n\\item domain --- The domain for the state variables\n\n\\item sigma --- The variance-covariance matrix for the shocks\n\n\\item iteration\\_count --- The number of iterations needed to achieve\nconvergence\n\\end{itemize}\n\nThe solution to a deterministic model has the same fildls with the exception\nof sigma.\n\n\\section{Post-solution analysis}\n\nOnce you have solved your model there are many things that you might want to\nuse the solution for. \\ Some of the more obvious things, such as simulating\ndata from the solution and computing impulse response functions have been\nbuilt into SolveDSGE to make things easier for you.\n\n\\subsection{Simulation}\n\nTo simulate data from the solution to a model the function to use is\nsimulate(), whose arguments are a model solution, an initial state, and the\nnumber of observations to simulate. \\ An optimal final argument is the seed\nfor the random number generator. \\ An example of simulate() in action would\nbe:\n\n\\bigskip\n\n\\textit{data\\_states, data\\_jumps = simulate(soln,[0.0, 25.0],100000)}\n\n\\bigskip\n\nAs this example makes clear, the simulate function returns two 2D arrays. \\\nThe first array contains simulated data for the state variables, the second\narray contains simulated data for the jump variables. \\ The simulate\nfunction can be applied to both stochastic and deterministic models.\n\n\\subsection{Impulse response functions}\n\nImpulse responses are obtained using the impulses() function, which takes\nthree arguments: the model solution, the length of the impulse response\nfunction (number of periods), the nature of the impulse to apply, and the\nnumber of repetitions to use for the Monte Carlo integration. \\ Responses to\nboth a positive and a negative innovation are generated. \\ An optimal final\nargument is the seed for the random number generator. \\ For a model with two\nshocks, an example of impulses() in use would be:\n\n\\bigskip\n\n\\textit{pos\\_responses, neg\\_responses = impulses(soln,50,[2,0],10000)}\n\n\\bigskip \n\nwhich applies a two standard deviation impulse to the first shock and no\nimpulse to the second shock. \\ For the nonlinear solutions (second-order\nperturbation, third-order perturbation, and the projection-based solutions)\nthe initial state is \\textquotedblleft integrated-out\\textquotedblright\\ via\na Monte Carlo that averages over draws taken from the unconditional\ndistribution of the state variables. \\ At this stage in the package's\ndevelopment, the impulses need to be computed one shock at a time; this will\nprobably change at some point.\n\n\\subsection{PDFs and CDFs}\n\nSolveDSGE contains functions for approximating the probability density\nfunction and the cumulative distribution function of a variable, where the\napproximation is based on Fourier series (Kronmal and Tarter, 1968). \\ Most\nof the functionality relates to the univariate case, but some functionality\nis included to approximate and evaluate the PDF\\ in the multivariate case.\n\n\\subsubsection{Univariate}\n\nTo approximate the probability density function and evaluate the\napproximated function at a point the function is:\n\n\\bigskip\n\n\\textit{f =\napproximate\\_density(sample,point,order,lower\\_bound,upper\\_bound)}\n\n\\bigskip\n\nwhere \\textit{sample} is a vector of data, \\textit{point} is the value at\nwhich the PDF is evaluated, \\textit{order} is the order of the Fourier\nseries approximation, and \\textit{lower\\_bound} and \\textit{upper\\_bound}\nspecify the support over which the PDF is constructed. \\ If an approximation\nof the entire PDF is sought, then the function is:\n\n\\bigskip\n\n\\textit{nodesf, f =\napproximate\\_density(sample,order,lower\\_bound,upper\\_bound)}\n\n\\bigskip\n\nSimilarly, the cumulative distribution function is approximated and\nevaluated at a point using the function:\n\n\\bigskip\n\n\\textit{F =\napproximate\\_distribution(sample,point,order,lower\\_bound,upper\\_bound)}\n\n\\bigskip\n\nwhere \\textit{sample} is a vector of data, \\textit{point} is the value at\nwhich the CDF is evaluated, \\textit{order} is the order of the Fourier\nseries approximation, and \\textit{lower\\_bound} and \\textit{upper\\_bound}\nspecify the support over which the CDF is constructed. \\ If an approximation\nof the entire CDF is sought, then the function is:\n\n\\bigskip\n\n\\textit{nodesF, F =\napproximate\\_distribution(sample,order,lower\\_bound,upper\\_bound)}\n\n\\bigskip\n\n\\subsubsection{Multivariate}\n\nIn the multivaraite case the PDF can be approximated and evaluated at a\npoint using the function:\n\n\\bigskip\n\n\\textit{f =\napproximate\\_density(sample,point,order,lower\\_bound,upper\\_bound)}\n\n\\bigskip\n\nwhere \\textit{sample} is a 2D array of data, \\textit{point} is a vector, \n\\textit{order} is a vector of integers, and \\textit{lower\\_bound} and \n\\textit{upper\\_bound} are vectors. \\ Similarly, the CDF can be approximated\nand evaluated at a point using the function:\n\n\\bigskip\n\n\\textit{F =\napproximate\\_distribution(sample,point,order,lower\\_bound,upper\\_bound)}\n\n\\bigskip\n\nwhere \\textit{sample} is a 2D array of data, \\textit{point} is a vector, \n\\textit{order} is a vector of integers, and \\textit{lower\\_bound} and \n\\textit{upper\\_bound} are vectors.\n\n\\subsection{Evaluating accuracy}\n\nAt this point SolveDSGE doesn't have routines to assess numerical accuracy\naccording to conventional metrics like Euler equation errors. \\ What\nSolveDSGE does do, however, is compare two solutions and assess the\nmagnitudes of any differences. \\ This facilitates an adaptive approach to\napproximation and it allows robustness of the solution to be assessed across\napproximation schemes. \\ When comparing two models, SolveDSGE looks at the\npredicted values for the jump variables, returning the maximum absolute\ndifference for each jump variable found for a random sample of 100,000\nrealizations of the state variables. \\ We compare two solution according to:\n\n\\bigskip\n\n\\textit{errors = compare\\_solutions(solna,solnb,domain,seed)}\n\n\\bigskip\n\nwhere \\textit{solna} and \\textit{solnb} are the two solutions to be\ncompared, \\textit{domain} is the domain for the state variables over which\nthe comparison takes place, and \\textit{seed} is an optional argument that\nsets the seed for the random number generator.\n\n\\begin{thebibliography}{99}\n\\bibitem{} Andreasen, M., Fern\\'{a}ndez-Villaverde, J., and J.\nRubio-Ramirez, (2017), \\textquotedblleft The Pruned State-Space System for\nNon-Linear DSGE Models: Theory and Empirical Applications\\textquotedblright\n, \\textit{Review of Economic Studies}, 0, pp. 1---49.\n\n\\bibitem{} Binning, A., (2013), \\textquotedblleft Third-order approximation\nof dynamic models without the use of tensors\\textquotedblright , \\textit{%\nNorges Bank Working Paper} 2013--13.\n\n\\bibitem{} Gomme, P., and P. Klein, (2011), \\textquotedblleft Second-Order\nApproximation of Dynamic Models Without the Use of Tensors\\textquotedblright\n, \\textit{Journal of Economic Dynamics and Control}, 35, pp. 604---615.\n\n\\bibitem{} Judd, K. (1992), \\textquotedblleft Projection Methods for Solving\nAggregate Growth Models\\textquotedblright , \\textit{Journal of Economic\nTheory}, 58, pp.410---452.\n\n\\bibitem{} Judd, K., Maliar, L., Maliar, S., and R. Valero, (2014),\n\\textquotedblleft Smolyak Method for Solving Dynamic Economic Models:\nLagrange Interpolation, Anisotropic Grid and Adaptive\nDomain\\textquotedblright , \\textit{Journal of Economic Dynamics and Control}%\n, 44, pp. 92---123.\n\n\\bibitem{} Judd, K., Maliar, L., Maliar, S., and I. Tsener, (2017),\n\\textquotedblleft How to Solve Dynamic Stochastic Models Computing\nExpectations just Once\\textquotedblright , \\textit{Quantitative Economics},\n8, pp.851---893.\n\n\\bibitem{} Klein, P., (2000), \\textquotedblleft Using the Generalized Schur\nForm to Solve a Multivariate Linear Rational Expectations\nModel\\textquotedblright , \\textit{Journal of Economic Dynamics and Control},\n24, pp. 1405---1423.\n\n\\bibitem{} Kronmal, R., and M. Tarter, (1968), \\textquotedblleft The\nEstimation of Probability Densities and Cumulatives by Fourier Series\nMethods\\textquotedblright , \\textit{Journal of the American Statistical\nAssociation}, 63, 323, pp.925--952.\n\n\\bibitem{} Levintal, O., (2017), \\textquotedblleft Fifth-Order Perturbation\nSolution to DSGE models\\textquotedblright , \\textit{Journal of Economic\nDynamics and Control}, 80, pp. 1--16.\n\n\\bibitem{} Potter, S., (2000), \\textquotedblleft Nonlinear Impulse Response\nFunctions\\textquotedblright , \\textit{Journal of Economic Dynamics and\nControl}, 24, pp. 1425---1446.\n\\end{thebibliography}\n\n\\end{document}\n", "meta": {"hexsha": "4bf95352df8eec227bec532aef78de60324b9eab", "size": 38873, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "user_guide/SolveDSGE_guide_v030.tex", "max_stars_repo_name": "azev77/SolveDSGE.jl", "max_stars_repo_head_hexsha": "41245dd87389ba322f26db8f7779bdc2dd0a963e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "user_guide/SolveDSGE_guide_v030.tex", "max_issues_repo_name": "azev77/SolveDSGE.jl", "max_issues_repo_head_hexsha": "41245dd87389ba322f26db8f7779bdc2dd0a963e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "user_guide/SolveDSGE_guide_v030.tex", "max_forks_repo_name": "azev77/SolveDSGE.jl", "max_forks_repo_head_hexsha": "41245dd87389ba322f26db8f7779bdc2dd0a963e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1273234201, "max_line_length": 252, "alphanum_fraction": 0.7679880637, "num_tokens": 10230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.31172903260357326}}
{"text": "\\XtoCBlock{L2Norm}\r\n\\label{block:L2Norm}\r\n\\begin{figure}[H]\\includegraphics{L2Norm}\\end{figure} \r\n\r\n\\begin{XtoCtabular}{Inports}\r\nu1 & Input u1\\tabularnewline\r\n\\hline\r\nu2 & Input u2\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n\r\n\\begin{XtoCtabular}{Outports}\r\nOut & Euclidean norm of u1 and u2\\tabularnewline\r\n\\hline\r\n\\end{XtoCtabular}\r\n\r\n\\subsubsection*{Description:}\r\nCalculation of L2-norm (euclidean norm).\r\n\n% include optional documentation file\r\n\\InputIfFileExists{\\XcHomePath/Library/Math/Doc/L2Norm_Info.tex}{\\vspace{1ex}}{}\r\n\r\n\\subsubsection*{Implementations:}\r\n\\begin{tabular}{l l}\r\n\\textbf{FiP8} & 8 Bit Fixed Point Implementation\\tabularnewline\r\n\\textbf{FiP16} & 16 Bit Fixed Point Implementation\\tabularnewline\r\n\\textbf{FiP32} & 32 Bit Fixed Point Implementation\\tabularnewline\r\n\\textbf{Float32} & 32 Bit Floating Point Implementation\\tabularnewline\r\n\\textbf{Float64} & 64 Bit Floating Point Implementation\\tabularnewline\r\n\\end{tabular}\r\n\r\n\\XtoCImplementation{FiP8}\r\n\\index{Block ID!5056}\r\n\\nopagebreak[0]\r\n% Implementation details\r\n\\begin{tabular}{l l}\r\n\\textbf{Name} & FiP8 \\tabularnewline\r\n\\textbf{ID} & 5056 \\tabularnewline\r\n\\textbf{Revision} & 0.1 \\tabularnewline\r\n\\textbf{C filename} & L2Norm\\_FiP8.c \\tabularnewline\r\n\\textbf{H filename} & L2Norm\\_FiP8.h \\tabularnewline\r\n\\end{tabular}\r\n\\vspace{1ex}\r\n\r\n8 Bit Fixed Point Implementation\r\n\r\n% Implementation data structure\r\n\\XtoCDataStruct{Data Structure:}\r\n\\begin{lstlisting}\r\ntypedef struct {\r\n     uint16        ID;\r\n     int8          *u1;\r\n     int8          *u2;\r\n     int8          Out;\r\n} L2NORM_FIP8;\r\n\\end{lstlisting}\r\n\r\n\\ifdefined \\AddTestReports\r\n\\InputIfFileExists{\\XcHomePath/Library/Math/Doc/Test_L2Norm_FiP8.tex}{}{}\r\n\\fi\r\n\\XtoCImplementation{FiP16}\r\n\\index{Block ID!5057}\r\n\\nopagebreak[0]\r\n% Implementation details\r\n\\begin{tabular}{l l}\r\n\\textbf{Name} & FiP16 \\tabularnewline\r\n\\textbf{ID} & 5057 \\tabularnewline\r\n\\textbf{Revision} & 0.1 \\tabularnewline\r\n\\textbf{C filename} & L2Norm\\_FiP16.c \\tabularnewline\r\n\\textbf{H filename} & L2Norm\\_FiP16.h \\tabularnewline\r\n\\end{tabular}\r\n\\vspace{1ex}\r\n\r\n16 Bit Fixed Point Implementation\r\n\r\n% Implementation data structure\r\n\\XtoCDataStruct{Data Structure:}\r\n\\begin{lstlisting}\r\ntypedef struct {\r\n     uint16        ID;\r\n     int16         *u1;\r\n     int16         *u2;\r\n     int16         Out;\r\n} L2NORM_FIP16;\r\n\\end{lstlisting}\r\n\r\n\\ifdefined \\AddTestReports\r\n\\InputIfFileExists{\\XcHomePath/Library/Math/Doc/Test_L2Norm_FiP16.tex}{}{}\r\n\\fi\r\n\\XtoCImplementation{FiP32}\r\n\\index{Block ID!5058}\r\n\\nopagebreak[0]\r\n% Implementation details\r\n\\begin{tabular}{l l}\r\n\\textbf{Name} & FiP32 \\tabularnewline\r\n\\textbf{ID} & 5058 \\tabularnewline\r\n\\textbf{Revision} & 0.1 \\tabularnewline\r\n\\textbf{C filename} & L2Norm\\_FiP32.c \\tabularnewline\r\n\\textbf{H filename} & L2Norm\\_FiP32.h \\tabularnewline\r\n\\end{tabular}\r\n\\vspace{1ex}\r\n\r\n32 Bit Fixed Point Implementation\r\n\r\n% Implementation data structure\r\n\\XtoCDataStruct{Data Structure:}\r\n\\begin{lstlisting}\r\ntypedef struct {\r\n     uint16        ID;\r\n     int32         *u1;\r\n     int32         *u2;\r\n     int32         Out;\r\n} L2NORM_FIP32;\r\n\\end{lstlisting}\r\n\r\n\\ifdefined \\AddTestReports\r\n\\InputIfFileExists{\\XcHomePath/Library/Math/Doc/Test_L2Norm_FiP32.tex}{}{}\r\n\\fi\r\n\\XtoCImplementation{Float32}\r\n\\index{Block ID!5059}\r\n\\nopagebreak[0]\r\n% Implementation details\r\n\\begin{tabular}{l l}\r\n\\textbf{Name} & Float32 \\tabularnewline\r\n\\textbf{ID} & 5059 \\tabularnewline\r\n\\textbf{Revision} & 0.1 \\tabularnewline\r\n\\textbf{C filename} & L2Norm\\_Float32.c \\tabularnewline\r\n\\textbf{H filename} & L2Norm\\_Float32.h \\tabularnewline\r\n\\end{tabular}\r\n\\vspace{1ex}\r\n\r\n32 Bit Floating Point Implementation\r\n\r\n% Implementation data structure\r\n\\XtoCDataStruct{Data Structure:}\r\n\\begin{lstlisting}\r\ntypedef struct {\r\n     uint16        ID;\r\n     float32       *u1;\r\n     float32       *u2;\r\n     float32       Out;\r\n} L2NORM_FLOAT32;\r\n\\end{lstlisting}\r\n\r\n\\ifdefined \\AddTestReports\r\n\\InputIfFileExists{\\XcHomePath/Library/Math/Doc/Test_L2Norm_Float32.tex}{}{}\r\n\\fi\r\n\\XtoCImplementation{Float64}\r\n\\index{Block ID!5060}\r\n\\nopagebreak[0]\r\n% Implementation details\r\n\\begin{tabular}{l l}\r\n\\textbf{Name} & Float64 \\tabularnewline\r\n\\textbf{ID} & 5060 \\tabularnewline\r\n\\textbf{Revision} & 0.1 \\tabularnewline\r\n\\textbf{C filename} & L2Norm\\_Float64.c \\tabularnewline\r\n\\textbf{H filename} & L2Norm\\_Float64.h \\tabularnewline\r\n\\end{tabular}\r\n\\vspace{1ex}\r\n\r\n64 Bit Floating Point Implementation\r\n\r\n% Implementation data structure\r\n\\XtoCDataStruct{Data Structure:}\r\n\\begin{lstlisting}\r\ntypedef struct {\r\n     uint16        ID;\r\n     float64       *u1;\r\n     float32       *u2;\r\n     float64       Out;\r\n} L2NORM_FLOAT64;\r\n\\end{lstlisting}\r\n\r\n\\ifdefined \\AddTestReports\r\n\\InputIfFileExists{\\XcHomePath/Library/Math/Doc/Test_L2Norm_Float64.tex}{}{}\r\n\\fi\r\n", "meta": {"hexsha": "55788117646ae86c26fcf50d2b7fb7deab6d243f", "size": 4776, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Library/Math/Doc/L2Norm.tex", "max_stars_repo_name": "AlexisTM/X2C", "max_stars_repo_head_hexsha": "31f39b598afe271a7fd46ef1ee9e06c410b1120c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Library/Math/Doc/L2Norm.tex", "max_issues_repo_name": "AlexisTM/X2C", "max_issues_repo_head_hexsha": "31f39b598afe271a7fd46ef1ee9e06c410b1120c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Library/Math/Doc/L2Norm.tex", "max_forks_repo_name": "AlexisTM/X2C", "max_forks_repo_head_hexsha": "31f39b598afe271a7fd46ef1ee9e06c410b1120c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8314606742, "max_line_length": 81, "alphanum_fraction": 0.7102177554, "num_tokens": 1537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.31172903260357326}}
{"text": "\\chapter{Core Theories}\\label{HOLtheories}\n\n% LaTeX macros in HOL manuals\n%\n% \\holtxt{..}     for typewriter text that is HOL types or terms.  To\n%                 produce backslashes, for /\\, \\/ and \\x. x + 1, use \\bs\n% \\ml{..}         for typewriter text that is ML input, including the\n%                 names of HOL API functions, such as mk_const\n% \\theoryimp{..}  for names of HOL theories.\n\n% Inside \\begin{verbatim}, indent contents three spaces, unless\n% displaying a HOL session in a box (boxed or session environments).\n% In that case, put the session flush against the left margin\n\n% Rather than wrapping begin{verbatim} blocks in \\small, which does\n% terrible things to line-spacing in the vicinity, use the hol\n% environment, thus \\begin{hol}\\begin{verbatim}...\\end{verbatim}\\end{hol}\n\n\\setcounter{sessioncount}{0}\n\n\n\\newcommand{\\konst}[1]{\\ensuremath{\\mbox{\\small{\\textbf{\\sf{#1}}}}}}\n\\newcommand{\\nil}{\\mathbf{[} \\;\\mathbf{]}}\n\\newcommand{\\cons}[2]{{#1}\\mathbf{:}\\mathbf{:}{#2}}\n\n\\index{theories, in HOL logic@theories, in \\HOL{} logic!hierarchies\nof}%\nThe \\HOL{} system provides a collection of theories on which to base verification tools or further theory development.\nIn the rest of this section, these theories are briefly described.\nThe sections that follow provide an overview of the contents of each theory.\nFor a complete list of all the axioms, definitions and theorems in \\HOL, see the online resources distributed with the system.\nIn particular, the HTML file \\url{help/HOLindex.html} is a good place to start browsing the available theories.\nFor a graphical picture of the theory hierarchy, see \\url{help/theorygraph/theories.html}.\n\n\\section{The Theory {\\tt min}}\\label{minTheory}\n\nThe starting theory of \\HOL{} is the theory \\ml{min}.\n\\index{min, the HOL theory@\\ml{min}, the \\HOL{} theory|(}\nIn this theory, the type constant {\\small\\verb+bool+} of booleans,\nthe binary type operator $(\\alpha,\\beta)${\\small\\verb+fun+} of functions, and the type\nconstant {\\small\\verb+ind+} of individuals are declared. Building on\nthese types, three primitive constants\n\\index{constants, in HOL logic@constants, in \\HOL{} logic!primitive logical}%\n\\index{primitive constants, of HOL logic@primitive constants, of \\HOL{} logic}%\nare declared: equality, implication, and a choice operator:\n\\index{ equality, in HOL logic@\\ml{=} (equality, in \\HOL{} logic)}\n\\index{equality, in HOL logic@equality, in \\HOL{} logic}\n\\begin{description}\n\\item [Equality] Equality ({\\small\\verb+= : 'a -> 'a -> bool+}) is an\n  infix operator.\n\\index{equality, in HOL logic@equality, in \\HOL{} logic}\n\\item [Implication] Implication\n  ({\\small\\verb+==> : bool -> bool -> bool+}) is the\n  \\emph{material implication} and is an infix operator that is\n  right-associative, \\ie, \\verb+x ==> y ==> z+ parses to the same term\n  as \\verb+x ==> (y ==> z)+.\n\\index{implication, in HOL logic@implication, in \\HOL{} logic}\n\\item [Choice] Equality\nand implication are standard predicate calculus notions, but choice is\nmore exotic: if $t$ is a term having type $\\sigma${\\small\\verb+->bool+},\nthen {\\small\\verb+@x.+}$t${\\small\\verb+ x+} (or, equivalently,\n{\\small\\verb+$@+}$t$) denotes \\emph{some} member of the set whose\ncharacteristic\\index{characteristic predicate, of type definitions}\n function is $t$. If the set is empty, then\n{\\small\\verb+@x.+}$t${\\small\\verb+ x+} denotes an arbitrary member of the\nset denoted by $\\sigma$. The constant {\\small\\verb+@+} is a higher order\nversion of Hilbert's\n\\index{Hilbert, D.}%\n\\index{epsilon operator}%\n $\\hilbert$-operator; it is related to the constant\n$\\iota$ in Church's formulation of higher order logic. For more details,\nsee Church's\n\\index{Church, A.}\noriginal paper \\cite{Church}, Leisenring's\n\\index{Leisenring, A.}\nbook on Hilbert's $\\hilbert$-symbol \\cite{Leisenring}, or Andrews'\ntextbook on type theory \\cite{Andrews}.\n\\end{description}\n\n\\medskip\n\n\\noindent No theorems or axioms are placed in theory \\theoryimp{min}.\nThe primitive rules of inference of \\HOL{} depend on the presence of\n\\theoryimp{min}.\n%\n\\index{min, the HOL theory@\\ml{min}, the \\HOL{} theory|)}\n\n\\section{Basic Theories}\n\nThe most basic theories in HOL provide support for a standard\ncollection of types. The theory \\theoryimp{bool} defines the basis of\nthe \\HOL{} logic, including the boolean operations and\nquantifiers. On this platform, quite a bit of theorem-proving\ninfrastructure can already be built. Further basic types are developed\nin the theory of pairs (\\theoryimp{prod}), disjoint sums\n(\\theoryimp{sum}), the one-element type (\\theoryimp{one}), and the\n(\\theoryimp{option}) type.\n\n\n\\subsection{The theory \\theoryimp{bool}}\\label{boolfull}\n\n\\index{axioms!primitive, of HOL logic@primitive, of \\HOL{} logic|(}\n%\nAt start-up, the initial theory for users of the \\HOL{} system is\ncalled \\ml{bool}\\index{HOL@\\HOL{}}, which is constructed when the\n\\HOL{} system is built. The theory \\theoryimp{bool} is an extension of\nthe combination of the ``conceptual'' theories \\theory{LOG} and\n\\theory{INIT}, described in \\LOGIC.  Thus it contains the four axioms\n%\n\\index{axioms!in bool theory@in \\ml{bool} theory}\n%\nfor higher order logic. These axioms, together with the rules of\ninference described in Section~\\ref{rules}, constitute the core of the\n\\HOL{} logic.  Because of the way the \\HOL{} system evolved from \\LCF%\n%\n\\index{LCF@\\LCF}%\n%\n\\footnote{To simplify the porting of the LCF theorem-proving tools to\n  the HOL system, the HOL logic was made as like PP$\\lambda$ (the\n  logic built-in to LCF) as possible.}, the particular axiomatization\nof higher order logic it uses differs from the classical\naxiomatization due to Church\\index{Church, A.}  \\cite{Church}.  The\nbiggest difference is that in Church's formulation type variables\n%\n\\index{type variables, in HOL logic@type variables, in \\HOL{} logic!differences from classical}\n%\nare in the meta-language, whereas in the \\HOL{} logic they are part of\nthe object language.\n\nThe logical constants\n%\n\\index{logical constants, in HOL logic@logical constants, in \\HOL{} logic}\n%\n\\holtxt{T}~(truth),\n%\n\\index{truth values, in HOL logic@truth values, in \\HOL{} logic!constants for}\n%\n\\holtxt{F}~(falsity),\n\\holtxt{\\~{}}~(negation),\n%\n\\index{ negation, in HOL logic@\\holtxt{\\~{}} (negation, in \\HOL{} logic)}\n%\n\\holtxt{/\\bs} (conjunction),\n%\n\\index{ conjunction, in HOL logic@\\holtxt{/\\bs} (conjunction, in \\HOL{} logic)}\n%\n\\holtxt{\\bs/} (disjunction),\n%\n\\index{ disjunction, in HOL logic@\\holtxt{\\bs/} (disjunction, in \\HOL{} logic)}\n%\n\\holtxt{!} (universal quantification),\n%\n\\index{ universal quantifier, in HOL logic@\\holtxt{\"!} (universal quantifier, in \\HOL{} logic)}\n%\n\\holtxt{?} (existential quantification),\n%\n\\index{ existential quantifier, in HOL logic@\\holtxt{?} (existential quantifier, in \\HOL{} logic)}\n%\nand \\holtxt{?!} (unique existence quantifier)\n%\n\\index{ exists unique, in HOL logic@\\holtxt{?\"!} (exists unique, in \\HOL{} logic)}\n%\ncan all be defined in terms of equality,\n%\n\\index{equality, in HOL logic@equality, in \\HOL{} logic}\n%\nimplication and choice.  The definitions listed below are fairly\nstandard; each one is preceded by its \\ML{} name.  Later definitions\nsometimes build on earlier ones.\n\n\\begin{hol}\n\\index{truth values, in HOL logic@truth values, in \\HOL{} logic!definition of}\n\\index{T@\\holtxt{T}!definitional axiom for}\n\\index{disjunction, in HOL logic@disjunction, in \\HOL{} logic!definitional axiom for}\n\\index{conjunction, in HOL logic@conjunction, in \\HOL{} logic!definitional axiom for}\n\\index{iff, in HOL logic@iff, in \\HOL{} logic!definitional axiom for}\n\\index{negation, in HOL logic@negation, in \\HOL{} logic!definitional axiom for}\n\\index{ exists unique, in HOL logic@\\holtxt{?\"!} (exists unique, in \\HOL{} logic)}\n\\index{F (falsity), the HOL constant@\\holtxt{F} (falsity), the \\HOL{} constant!definitional axiom for}\n\\index{conjunction, in HOL logic@conjunction, in \\HOL{} logic!definitional axiom for}\n\\index{disjunction, in HOL logic@disjunction, in \\HOL{} logic!definitional axiom for}\n\\index{equality, in HOL logic@equality, in \\HOL{} logic!primitive axiom for}\n\\index{existential quantifier, in HOL logic@existential quantifier, in \\HOL{} logic!definitional axiom for}\n\\index{universal quantifier, in HOL logic@universal quantifier, in \\HOL{} logic!definitional axiom for}\n\\index{exists unique, in HOL logic@exists unique, in \\HOL{} logic!definitional axiom for}\n\\begin{verbatim}\n   T_DEF              |- T  = ((\\x:bool. x) = (\\x. x))\n\n   FORALL_DEF         |- !  = \\P:'a->bool. P = (\\x. T)\n\n   EXISTS_DEF         |- ?  = \\P:'a->bool. P($@ P)\n\n   AND_DEF            |- /\\ = \\t1 t2. !t. (t1 ==> t2 ==> t) ==> t\n\n   OR_DEF             |- \\/ = \\t1 t2. !t. (t1 ==> t) ==> (t2 ==> t) ==> t\n\n   F_DEF              |- F  = !t. t\n\n   NOT_DEF            |- ~  = (\\t. t ==> F)\n\n   EXISTS_UNIQUE_DEF  |- ?! = (\\P. $? P /\\ (!x y. P x /\\ P y ==> (x = y)))\n\\end{verbatim}\n\\end{hol}\n\n\nThere are four\n%\n\\index{universal quantifier, in HOL logic@universal quantifier, in \\HOL{} logic!in four primitive axioms}\n%\naxioms in the theory \\theoryimp{bool};\n%\n\\index{bool, the HOL theory@\\ml{bool}, the \\HOL{} theory}\n%\nthe first three are the following:\n\n\\begin{hol}\n\\index{BOOL_CASES_AX@\\ml{BOOL\\_CASES\\_AX}}\n\\index{ETA_AX@\\ml{ETA\\_AX}}\n\\index{SELECT_AX@\\ml{SELECT\\_AX}}\n\\index{implication, in HOL logic@implication, in \\HOL{} logic!primitive axiom for}\n\\index{ choice function, in HOL logic@\\holtxt{\"@} (choice function, in \\HOL{} logic)}\n\\index{choice axiom}\n\\index{axiom of choice}\n\\index{axioms!of choice}\n\\index{choice operator, in HOL logic@choice operator, in \\HOL{} logic!primitive axiom for}\n\\begin{verbatim}\n   BOOL_CASES_AX   |- !t. (t = T) \\/ (t = F)\n\n   ETA_AX          |- !t. (\\x. t x) = t\n\n   SELECT_AX       |- !P:'a->bool x. P x ==> P($@ P)\n\\end{verbatim}\n\\end{hol}\n\n\\noindent\nThe fourth and last axiom of the \\HOL{} logic is the Axiom of\nInfinity\\index{axiom of infinity}. Its statement is phrased in terms of\nthe function properties {\\small\\verb+ONE_ONE+} and {\\small\\verb+ONTO+}. The\ndefinitions are:\n\n\\begin{hol}\n\\index{ONE_ONE_DEF@\\ml{ONE\\_ONE\\_DEF}}\n\\index{ONTO_DEF@\\ml{ONTO\\_DEF}}\n\\index{one-to-one predicate, in HOL logic@one-to-one predicate, in \\HOL{} logic!definitional axiom for}\n\\index{onto predicate, in HOL logic@onto predicate, in \\HOL{} logic!definitional axiom for}\n\\begin{verbatim}\n   ONE_ONE_DEF |- ONE_ONE f = (!x1 x2. (f x1 = f x2) ==> (x1 = x2))\n\n   ONTO_DEF    |- ONTO f    = (!y. ?x. y = f x)\n\\end{verbatim}\n\\end{hol}\n\n\\noindent The Axiom of Infinity\\index{axioms!in bool theory@in \\ml{bool} theory} is\n%\n\\begin{hol}\n\\index{INFINITY_AX@\\ml{INFINITY\\_AX}}\n\\index{axiom of infinity}\n\\index{existential quantifier, in HOL logic@existential quantifier, in \\HOL{} logic!in infinity axiom}\n\\begin{verbatim}\n  INFINITY_AX  |- ?f:ind->ind. ONE_ONE f /\\ ~(ONTO f)\n\\end{verbatim}\n\\end{hol}\n%\n\\noindent\nThis asserts that there exists a one-to-one map from \\holtxt{ind} to\nitself that is not onto. This implies that the type \\holtxt{ind}\ndenotes an infinite set.\n%\n\\index{axioms!primitive, of HOL logic@primitive, of \\HOL{} logic|)}\n\nThe three other axioms of the theory \\theoryimp{bool}, the rules of\ninference in Section~\\ref{rules} and the Axiom of Infinity are,\ntogether, sufficient for developing all of standard mathematics. Thus,\nin principle, the user of the \\HOL{} system should never need to make a\nnon-definitional\n%\n\\index{axioms!dispensibility of adding}%\n\\index{definitional theories}%\n%\ntheory. In practice, it is often very tempting to take the risk of\nintroducing new axioms because deriving them from definitions can be\ntedious---proving that `axioms' follow from definitions amounts to\nproving their consistency.\n\n\\paragraph {Further definitions}\n\nThe theory \\theoryimp{bool} also supplies the definitions of a number of\nuseful constants.\n\\begin{hol}\n\\index{COND, the HOL constant@\\holtxt{COND}, the \\HOL{} constant}\n\\index{LET, the HOL constant@\\ml{LET}, the \\HOL{} constant}\n\\index{conditionals, in HOL logic@conditionals, in \\HOL{} logic!definitional axiom for}\n\\begin{verbatim}\n   LET_DEF  |- LET  = \\f x. f x\n   COND_DEF |- COND = \\t t1 t2. @x. ((t=T)==>(x=t1)) /\\ ((t=F)==>(x=t2))\n   IN_DEF   |- IN   = \\x (f:'a -> bool). f x\n\\end{verbatim}\n\\end{hol}\n\nThe constant \\holtxt{LET}\n%\n\\index{let-terms, in HOL logic@\\holtxt{let}-terms, in \\HOL{} logic!constant for}\n%\nis used in representing terms containing local variable bindings (\\ie\\\n\\holtxt{let}-terms).\n%\n\\index{let-terms, in HOL logic@\\holtxt{let}-terms, in \\HOL{} logic!definitional axiom for}\n%\nFor example, the concrete syntax \\holtxt{let v = M in N} is translated\nby the parser to the term \\holtxt{LET (\\bs{}v.N) M}. For the full\ndescription of how \\holtxt{let} expressions are translated, see\nSection \\ref{prod}.\n\nThe constant \\holtxt{COND} is used to represent conditional\nexpressions. The concrete syntax\n%\n\\index{terms, in HOL logic@terms, in \\HOL{} logic!conditional}%\n\\index{conditionals, in HOL logic@conditionals, in \\HOL{} logic}%\n%\n$\\holtxt{if}\\;t_1\\;\\holtxt{then}\\;t_2\\;\\holtxt{else}\\;t_3$ abbreviates\nthe application \\holtxt{COND $t_1$ $t_2$ $t_3$}.\n\nThe constant \\holtxt{IN} (written as an infix) is the basis of\nthe modelling of sets by their characteristic functions.  The term\n$x\\holtxt{ IN }P$ can be read as ``$x$ is an element of the set\n$P$'', or (more in line with its definition) as ``the predicate $P$ is\ntrue of $x$''.\n\nFinally, the polymorphic constant $\\holtxt{ARB}:\\alpha$ denotes a\nfixed but arbitrary element. \\holtxt{ARB} is occasionally useful when\nattempting to deal with the issue of partiality.\n\n\\subsubsection{Restricted quantifiers}\\label{res-quant}\n\n\\index{restricted quantification}\n%\nThe theory \\theoryimp{bool} also defines constants that implement\n\\emph{restricted quantification}. This provides a means of simulating\nsubtypes and dependent types with predicates. The most heavily used\nare restrictions of the existential and universal quantifiers:\n%\n\\begin{verbatim}\n   RES_FORALL_DEF |- RES_FORALL = \\P m. !x. x IN P ==> m x\n\n   RES_EXISTS_DEF |- RES_EXISTS = \\P m. ?x. x IN P /\\ m x\n\n   RES_ABSTRACT_DEF |- (!P m x. x IN P ==> (RES_ABSTRACT P m x = m x) /\\\n                       (!P m1 m2.\n                           (!x. x IN P ==> (m1 x = m2 x)) ==>\n                            (RES_ABSTRACT P m1 = RES_ABSTRACT P m2)\n\\end{verbatim}\n%\nThe definition of \\ml{RES\\_ABSTRACT} is a characterising formula, rather\nthan a direct equation.  There are two important properties\n\\begin{itemize}\n\\item if $y$ is an element of $P$ then $(\\bs{}x :: P.\\; M)\n  y = M[y/x]$\n\\item If two restricted abstractions agree on all values over their\n  (common) restricting set, then they are equal.\n\\end{itemize}\n\nFor completeness, restricted versions of unique existence and\nindefinite description are provided, although hardly used.\n\\begin{verbatim}\n   RES_EXISTS_UNIQUE_DEF\n    |- RES_EXISTS_UNIQUE = \\P m. (?x :: P. m x) /\\\n                                 (!x y :: P. m x /\\ m y ==> (x = y))\n\n   RES_SELECT_DEF\n     |- RES_SELECT = \\P m. @x. x IN P /\\ m x\n\\end{verbatim}\n\nThe definition of \\ml{RES\\_EXISTS\\_UNIQUE} uses the restricted\nquantification syntax with the {\\small\\verb+::+} symbol, referring to\nthe earlier definitions \\ml{RES\\_EXISTS} and \\ml{RES\\_FORALL}.\nThe \\texttt{::} syntax is used with restricted quantifiers to allow\narbitrary predicates to restrict binding variables. The \\HOL{} parser\nallows restricted quantification of all of a sequence of binding\nvariables by putting the restriction at the end of the sequence, thus\nwith a universal quantification:\n%\n\\[\n\\forall x \\, y \\, z \\, {\\tt ::} \\; P \\, . \\; Q(x,y,z)\n\\]\n%\nHere the predicate $P$ restricts all of $x$, $y$ and $z$.\n\n\\subsubsection{Derived syntactic forms}\\label{derived-terms}\n\n\\index{quotation, in HOL logic@quotation, in \\HOL{} logic!of non-primitive terms|(}\n% don't refill the \\index entries above, it's important to keep each\n% entry on one line\nThe \\HOL{} quotation parser\n%\n\\index{quotation, in HOL logic@quotation, in \\HOL{} logic!parser for}\n%\ncan translate various standard logical\nnotations\n%\n\\index{parsing, of HOL logic@parsing, of \\HOL{} logic!of standard notations}\n%\ninto primitive terms. For example, if \\ml{+} has been declared an\ninfix\n%\n\\index{infixes, in HOL logic@infixes, in \\HOL{} logic}\n%\n(as explained in Section~\\ref{theoryfns}), as it is when\n\\ml{arithmeticTheory} has been loaded, then \\ml{``x+1``} is\ntranslated to \\ml{``\\$+~x~1``}. The escape character \\ml{\\$}\n%\n\\index{ escape, in HOL logic parser@\\ml{\\$} (escape, in \\HOL{} logic parser)}%\n\\index{declared constants, in HOL logic@declared constants, in \\HOL{} logic}%\n\\index{infixes, in HOL logic@infixes, in \\HOL{} logic}%\n%\nsuppresses the infix behaviour of \\ml{+} and prevents the quotation\nparser getting confused.  In general, \\ml{\\$} can be used to suppress\nany special syntactic behaviour a token (such as \\texttt{if},\n\\texttt{+} or \\texttt{let})\n%\n\\index{tokens!suppressing parsing behaviour of}\n%\nmight have. This is illustrated in the table below, in which the terms\nin the column headed \\textit{`\\ML{} quotation'} are translated by the\nquotation parser to the corresponding terms in the column headed\n\\textit{`Primitive term'}.  Conversely, the terms in the latter column\nare always printed in the form shown in the former one.  The \\ML{}\nconstructor expressions in the rightmost column evaluate to the same\nvalues (of type \\ml{term}) as the other quotations in the same row.\n\n\\bigskip\n\n\\begin{center}\n\\index{choice operator, in HOL logic@choice operator, in \\HOL{} logic!syntax of}\n\\index{ negation, in HOL logic@\\holtxt{\\~{}} (negation, in \\HOL{} logic)}\n\\index{ disjunction, in HOL logic@\\holtxt{\\bs/} (disjunction, in \\HOL{} logic)}\n\\index{ conjunction, in HOL logic@\\holtxt{/\\bs} (conjunction, in \\HOL{} logic)}\n\\index{ implication, in HOL logic@\\holtxt{==>} (implication, in \\HOL{} logic)}\n\\index{ equality, in HOL logic@\\ml{=} (equality, in \\HOL{} logic)}\n\\index{ universal quantifier, in HOL logic@\\holtxt{\"!} (universal quantifier, in \\HOL{} logic)}\n\\index{ existential quantifier, in HOL logic@\\holtxt{?} (existential quantifier, in \\HOL{} logic)}\n\\index{ choice function, in HOL logic@\\holtxt{\"@} (choice function, in \\HOL{} logic)}\n\\index{terms, in HOL logic@terms, in \\HOL{} logic!non-primitive}\n\\index{terms, in HOL logic@terms, in \\HOL{} logic!constructors for}\n\\index{conditionals, in HOL logic@conditionals, in \\HOL{} logic}\n\\index{conjunction, in HOL logic@conjunction, in \\HOL{} logic!constructor for}\n\\index{disjunction, in HOL logic@disjunction, in \\HOL{} logic!constructor for}\n\\index{equality, in HOL logic@equality, in \\HOL{} logic!syntax of}\n\\index{negation, in HOL logic@negation, in \\HOL{} logic!syntax of}\n\\index{negation, in HOL logic@negation, in \\HOL{} logic!constructor for}\n\\index{existential quantifier, in HOL logic@existential quantifier, in \\HOL{} logic!syntax of}\n\\index{universal quantifier, in HOL logic@universal quantifier, in \\HOL{} logic!syntax of}\n\\index{implication, in HOL logic@implication, in \\HOL{} logic!syntax of}\n\\index{mk_neg@\\ml{mk\\_neg}}\n\\index{mk_disj@\\ml{mk\\_disj}}\n\\index{mk_conj@\\ml{mk\\_conj}}\n\\index{mk_imp@\\ml{mk\\_imp}}\n\\index{mk_eq@\\ml{mk\\_eq}}\n\\index{mk_forall@\\ml{mk\\_forall}}\n\\index{mk_exists@\\ml{mk\\_exists}}\n\\index{mk_select@\\ml{mk\\_select}}\n\\index{mk_cond@\\ml{mk\\_cond}}\n\\index{mk_let@\\ml{mk\\_let}}\n\\index{conjunction, in HOL logic@conjunction, in \\HOL{} logic!syntax of}\n\\begin{tabular}{|l|l|l|l|} \\hline\n\\multicolumn{4}{|c|}{ } \\\\\n\\multicolumn{4}{|c|}{\\bf Non-primitive terms} \\\\\n\\multicolumn{4}{|c|}{ } \\\\\n{\\it Kind of term} & {\\it \\ML\\ quotation} &\n{\\it Primitive term} &\n{\\it Constructor expression} \\\\ \\hline\n & & & \\\\\nNegation & {\\small\\verb+~+}$t$ & {\\small\\verb+$~ +}$t$ & {\\small\\verb+mk_neg(+}$t${\\small\\verb+)+} \\\\ \\hline\nDisjunction & $t_1${\\small\\verb+\\/+}$t_2$ & {\\small\\verb+$\\/ +}$t_1\\ t_2$ &\n{\\small\\verb+mk_disj(+}$t_1${\\small\\verb+,+}$t_2${\\small\\verb+)+} \\\\ \\hline\n%\nConjunction & $t_1$\\holtxt{/\\bs}$t_2$ & $\\holtxt{\\$/\\bs}\\ t_1\\ t_2$ &\n{\\small\\verb+mk_conj(+}$t_1${\\small\\verb+,+}$t_2${\\small\\verb+)+} \\\\\n\\hline\n%\nImplication & $t_1${\\small\\verb+==>+}$t_2$ & {\\small\\verb+$==> +}$t_1\\ t_2$ &\n{\\small\\verb+mk_imp(+}$t_1${\\small\\verb+,+}$t_2${\\small\\verb+)+} \\\\ \\hline\n%\nEquality & $t_1${\\small\\verb+=+}$t_2$ & {\\small\\verb+$= +}$t_1\\ t_2$ &\n{\\small\\verb+mk_eq(+}$t_1${\\small\\verb+,+}$t_2${\\small\\verb+)+} \\\\ \\hline\n%\n$\\forall$-quantification & {\\small\\verb+!+}$x${\\small\\verb+.+}$t$ &\n\\holtxt{\\$!(\\bs}$x${\\small\\verb+.+}$t${\\small\\verb+)+} & {\\small\\verb+mk_forall(+}$x${\\small\\verb+,+}$t${\\small\\verb+)+} \\\\ \\hline\n%\n$\\exists$-quantification & {\\small\\verb+?+}$x${\\small\\verb+.+}$t$ &\n\\holtxt{\\$?(\\bs}$x${\\small\\verb+.+}$t${\\small\\verb+)+} & {\\small\\verb+mk_exists(+}$x${\\small\\verb+,+}$t${\\small\\verb+)+} \\\\ \\hline\n%\n$\\hilbert$-term & {\\small\\verb+@+}$x${\\small\\verb+.+}$t$ &\n\\holtxt{\\$@(\\bs}$x${\\small\\verb+.+}$t${\\small\\verb+)+} & {\\small\\verb+mk_select(+}$x${\\small\\verb+,+}$t${\\small\\verb+)+} \\\\ \\hline\n%\nConditional & {\\small\\verb+if +}$t\\ ${\\small\\verb+then +}$t_1${\\small\\verb+ else +}$t_2$ &\n{\\small\\verb+COND +}$t\\ t_1\\ t_2$ & {\\small\\verb+mk_cond(+}$t${\\small\\verb+,+}$t_1${\\small\\verb+,+}$t_2${\\small\\verb+)+}\n \\\\ \\hline\n%\n{\\small\\verb+let+}-expression & {\\small\\verb+let +}$x${\\small\\verb+=+}$t_1${\\small\\verb+ in +}$t_2$ &\n\\holtxt{LET(\\bs}$x${\\small\\verb+.+}$t_2${\\small\\verb+)+}$t_1$ &\n\\holtxt{mk\\_let(mk\\_abs($x$,$t_2$),$t_1$)} \\\\ \\hline\n\\end{tabular}\n\\end{center}\n\n\\bigskip\n\nThere are constructors, destructors and indicators for all the obvious\nconstructs. (Indicators, \\eg\\ \\ml{is\\_neg}, return truth values\nindicating whether or not a term belongs to the syntax class in\nquestion.) In addition to the constructors listed in the table there\nare constructors, destructors, and indicators for pairs and lists,\nnamely \\ml{mk\\_pair},\n%\n\\index{mk_pair@\\ml{mk\\_pair}}\n%\n\\ml{mk\\_cons}\n%\n\\index{mk_cons@\\ml{mk\\_cons}}\n%\nand \\ml{mk\\_list}\n%\n\\index{mk_list@\\ml{mk\\_list}}\n%\n(see \\REFERENCE).  The constants \\holtxt{COND} and \\holtxt{LET} are\nexplained in Section~\\ref{boolfull}.  The constants \\holtxt{\\bs/},\n%\n\\index{disjunction, in HOL logic@disjunction, in \\HOL{} logic!syntax of}\n%\n\\holtxt{/\\bs}, \\holtxt{==>} and \\holtxt{=} are examples of\n\\textit{infixes} and represent $\\vee$, $\\wedge$, $\\imp$ and equality,\nrespectively. If $c$ is declared to be an infix, then the \\HOL{}\nparser will translate $t_1\\ c\\ t_2$ to {\\small\\verb+$+}$c\\ t_1\\ t_2$.\n\nThe constants {\\small\\verb+!+}, {\\small\\verb+?+} and {\\small\\verb+@+}\nare examples of \\label{binder} \\textit{binders}\n%\n\\index{binders, in HOL logic@binders, in \\HOL{} logic}\n%\nand represent $\\forall$, $\\exists$ and $\\hilbert$, respectively.  If\n$c$ is declared to be a binder, then the \\HOL{} parser will translate\n\\holtxt{$c$ $x$.$t$} to the combination \\holtxt{\\$$c$(\\bs$x$.$t$)}\n(\\ie\\ the application of the constant $c$ to the representation of the\nabstraction $\\lquant{x}t$).\n\\index{ function abstraction binder, in HOL logic@\\holtxt{\\bs} (function abstraction binder, in \\HOL{} logic)}\n\n\\begin{center}\n\n\\index{variables, in HOL logic@variables, in \\HOL{} logic!multiple bound}\n\\index{list_mk_comb@\\ml{list\\_mk\\_comb}|pin}\n\\index{list_mk_abs@\\ml{list\\_mk\\_abs}|pin}\n\\index{list_mk_forall@\\ml{list\\_mk\\_forall}|pin}\n\\index{list_mk_exists@\\ml{list\\_mk\\_exists}|pin}\n\\index{combinations, in HOL logic@combinations, in \\HOL{} logic!abbreviation for multiple}\n\\index{existential quantifier, in HOL logic@existential quantifier, in \\HOL{} logic!abbreviation for multiple}\n\\index{universal quantifier, in HOL logic@universal quantifier, in \\HOL{} logic!abbreviation for multiple}\n\\begin{tabular}{|l|l|l|} \\hline\n\\multicolumn{3}{|c|}{ } \\\\\n\\multicolumn{3}{|c|}{\\bf Syntactic abbreviations} \\\\\n\\multicolumn{3}{|c|}{ } \\\\\n{\\it Abbreviated term} & {\\it Meaning} &\n{\\it Constructor expression} \\\\ \\hline\n & &  \\\\\n$t\\ t_1 \\cdots t_n$ &\n{\\small\\verb+(+}$\\cdots${\\small\\verb+(+}$t\\ t_1${\\small\\verb+)+}$\\cdots t_n${\\small\\verb+)+} &\n{\\small\\verb+list_mk_comb(+}$t${\\small\\verb+,[+}$t_1${\\small\\verb+, +}$\\ldots${\\small\\verb+ ,+}$t_n${\\small\\verb+])+} \\\\ \\hline\n\\holtxt{\\bs}$x_1\\cdots x_n${\\small\\verb+.+}$t$ &\n\\holtxt{\\bs}$x_1${\\small\\verb+. +}$\\cdots$\\holtxt{ \\bs}$x_n${\\small\\verb+.+}$t$ &\n{\\small\\verb+list_mk_abs([+}$x_1${\\small\\verb+, +}$\\ldots${\\small\\verb+ ,+}$x_n${\\small\\verb+],+}$t${\\small\\verb+)+}\n\\\\ \\hline\n{\\small\\verb+!+}$x_1\\cdots x_n${\\small\\verb+.+}$t$ &\n{\\small\\verb+!+}$x_1${\\small\\verb+. +}$\\cdots${\\small\\verb+ !+}$x_n${\\small\\verb+.+}$t$ &\n{\\small\\verb+list_mk_forall([+}$x_1${\\small\\verb+, +}$\\ldots${\\small\\verb+ ,+}$x_n${\\small\\verb+],+}$t${\\small\\verb+)+}\n\\\\ \\hline\n{\\small\\verb+?+}$x_1\\cdots x_n${\\small\\verb+.+}$t$ &\n{\\small\\verb+?+}$x_1${\\small\\verb+. +}$\\cdots${\\small\\verb+ ?+}$x_n${\\small\\verb+.+}$t$ &\n{\\small\\verb+list_mk_exists([+}$x_1${\\small\\verb+, +}$\\ldots${\\small\\verb+ ,+}$x_n${\\small\\verb+],+}$t${\\small\\verb+)+} \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\n\\noindent There are also constructors\n\\ml{list\\_mk\\_conj}\\index{list_mk_conj@\\ml{list\\_mk\\_conj}},\n\\ml{list\\_mk\\_disj}\\index{list_mk_disj@\\ml{list\\_mk\\_disj}},\n\\ml{list\\_mk\\_imp}\\index{list_mk_imp@\\ml{list\\_mk\\_imp}} and\nfor conjunctions, disjunctions, and implications respectively.\nThe corresponding destructor functions are called \\ml{strip\\_comb} \\etc\n%\n\\index{term constructors, in HOL logic@term constructors, in \\HOL{} logic|)}\n%\n\\index{terms, in HOL logic@terms, in \\HOL{} logic!constructors for|)}\n%\n\\index{quotation, in HOL logic@quotation, in \\HOL{} logic!of non-primitive terms|)}\n\n\\subsubsection{Theorems}\n\nA large number of theorems involving the logical constants are\npre-proved in the theory \\theoryimp{bool}. The following theorems\nillustrate how higher order logic allows concise expression of\ntheorems supporting quantifier movement.\n\n\\begin{holboxed}\n\\begin{verbatim}\n LEFT_AND_FORALL_THM  |- !P Q. (!x. P x) /\\ Q = !x. P x /\\ Q\n RIGHT_AND_FORALL_THM |- !P Q. P /\\ (!x. Q x) = !x. P /\\ Q x\n\n LEFT_EXISTS_AND_THM  |- !P Q. (?x. P x /\\ Q) = (?x. P x) /\\ Q\n RIGHT_EXISTS_AND_THM |- !P Q. (?x. P /\\ Q x) = P /\\ ?x. Q x\n\n LEFT_FORALL_IMP_THM  |- !P Q. (!x. P x ==> Q) = (?x. P x) ==> Q\n RIGHT_FORALL_IMP_THM |- !P Q. (!x. P ==> Q x) = P ==> !x. Q x\n\n LEFT_EXISTS_IMP_THM  |- !P Q. (?x. P x ==> Q) = (!x. P x) ==> Q\n RIGHT_EXISTS_IMP_THM |- !P Q. (?x. P ==> Q x) = P ==> ?x. Q x\n\n LEFT_FORALL_OR_THM   |- !Q P. (!x. P x \\/ Q) = (!x. P x) \\/ Q\n RIGHT_FORALL_OR_THM  |- !P Q. (!x. P \\/ Q x) = P \\/ !x. Q x\n\n LEFT_OR_EXISTS_THM   |- !P Q. (?x. P x) \\/ Q = ?x. P x \\/ Q\n RIGHT_OR_EXISTS_THM  |- !P Q. P \\/ (?x. Q x) = ?x. P \\/ Q x\n\n EXISTS_OR_THM        |- !P Q. (?x. P x \\/ Q x) = (?x. P x) \\/ ?x. Q x\n FORALL_AND_THM       |- !P Q. (!x. P x /\\ Q x) = (!x. P x) /\\ !x. Q x\n\n NOT_EXISTS_THM       |- !P. ~(?x. P x) = !x. ~P x\n NOT_FORALL_THM       |- !P. ~(!x. P x) = ?x. ~P x\n\n SKOLEM_THM           |- !P. (!x. ?y. P x y) = ?f. !x. P x (f x)\n\\end{verbatim}\n\\end{holboxed}\n\nAlso, a theorem justifying Skolemization ({\\small\\verb+SKOLEM_THM+}) is\nproved. Many other theorems may be found in \\theoryimp{bool} theory.\n\n\n\\subsection{Combinators}\n\\label{sec:combinTheory}\n\n\\index{function composition, in HOL logic@function composition, in \\HOL{} logic|(}\n\nThe theory \\theoryimp{combin}\n\\index{combin@\\theoryimp{combin}}%\n\\index{combinators, in HOL logic@combinators, in \\HOL{} logic}%\ncontains the definitions of function composition (infixed \\ml{o}),\n\\index{ function composition operator, in HOL logic@\\ml{o} (function composition operator), in \\HOL{} logic|(}\na reversed function application operator,\n\\index{ function application operator, in HOL logic@\\ml{:>} ((reversed) function application operator), in \\HOL{} logic}\nfunction override (infixed \\ml{=+}),\n\\index{ function override operator, in HOL logic@\\ml{=+} (function override opreator), in \\HOL{} logic}\nand the combinators\n\\ml{S},\n\\index{S, the HOL constant@\\ml{S}, the \\HOL{} constant}\n\\ml{K},\n\\index{K, the HOL constant@\\ml{K}, the \\HOL{} constant}\n\\ml{I},\n\\index{I, the HOL constant@\\ml{I}, the \\HOL{} constant}\n\\ml{W},\n\\index{W, the HOL constant@\\ml{W}, the \\HOL{} constant}\nand \\ml{C},\n\\index{C, the HOL constant@\\ml{C}, the \\HOL{} constant}\n\n\\begin{hol}\n\\begin{verbatim}\n     o_DEF |- f o g = (\\x. f(g x))\n   APP_DEF |- x :> f = f x\nUPDATE_DEF |- (k =+ v) = (\\f c. if k = c then v else f c)\n     K_DEF |- K = (\\x y. x)\n     S_DEF |- S = (\\f g x. f x(g x))\n     I_DEF |- I = S K K\n     W_DEF |- W = (\\f x. f x x)\n     C_DEF |- C = (\\f x y. f y x)\n\\end{verbatim}\n\\end{hol}\n\n\\noindent The following elementary properties are proved in the theory\n\\ml{combin}:\n\n\\begin{hol}\n\\begin{verbatim}\n   o_THM   |- !f g x. (f o g) x = f(g x)\n   o_ASSOC |- !f g h. f o (g o h) = (f o g) o h\n\n   UPDATE_EQ\n           |- !f a b c. (a =+ c) ((a =+ b) f) = (a =+ c) f\n   UPDATE_COMMUTES\n           |- !f a b c d. a <> b ==>\n                          ((a =+ c) ((b =+ d) f) = (b =+ d) ((a =+ c) f))\n\n   K_THM   |- !x y. K x y = x\n   S_THM   |- !f g x. S f g x = f x (g x)\n   I_THM   |- !x. I x = x\n   W_THM   |- !f x. W f x = f x x\n   C_THM   |- !f x y. C f x y = f y x\n\\end{verbatim}\n\\end{hol}\n\n\\index{ function application operator, in HOL logic@\\ml{:>} ((reversed) function application operator), in \\HOL{} logic}\nThere are no theorems about \\ml{:>}; its use is as a convenient syntax for function applications.\nFor example, chains of updates can lose some parentheses if written\n\\begin{hol}\n\\begin{verbatim}\n   f :> (k1 += v1) :> (k2 += v2) :> (k3 += v3)\n\\end{verbatim}\n\\end{hol}\nThis presentation also makes the order in which functions are applied read from left-to-right.\n\nHaving the symbols \\ml{o}, \\ml{S}, \\ml{K}, \\ml{I}, \\ml{W}, and \\ml{C}\nas built-in constants\n%\n\\index{variables, in HOL logic@variables, in \\HOL{} logic!with constant names}\n%\nis sometimes inconvenient because they are often wanted as mnemonic\nnames for variables (\\eg\\ \\ml{S} to range over sets and \\ml{o} to\nrange over outputs).\\footnote{Constants declared in new theories can\n  freely re-use these names, with ambiguous inputs resolved by type\n  inference.}  Variables with these names can be used in the current\nsystem if \\ml{o}, \\ml{S}, \\ml{K}, \\ml{I}, \\ml{W}, and \\ml{C} are first\nhidden (see Section~\\ref{hidden}).  In fact, this happens so often\nwith the constant \\holtxt{C} that it is ``hidden'' by default.  While\nhidden, it must be written in fully-qualified form, as\n\\holtxt{combin\\$C}.\n%\n\\index{ function composition operator, in HOL logic@\\ml{o} (function composition operator), in \\HOL{} logic|)}\n\\index{function composition, in HOL logic@function composition, in \\HOL{} logic|)}\n\\index{constants, in HOL logic@constants, in \\HOL{} logic!fully-qualified names of}\n\n\n\\subsection{Pairs}\\label{prod}\n\n\\index{representing types, in HOL logic@representing types, in \\HOL{} logic!pair example of|(}\n\\index{pairs, in HOL logic@pairs, in \\HOL{} logic|(}\n\\index{product types!in HOL logic@in \\HOL{} logic|(}\n%\nThe Cartesian  product  type  operator\n%\n\\index{type operators, in HOL logic@type operators, in \\HOL{} logic!for pairs}\n%\n\\holtxt{prod}\n%\n\\index{prod, the HOL type operator@\\holtxt{prod}, the \\HOL{} type operator}\n%\nis defined in the theory \\theoryimp{pair}. Values of type\n\\holtxt{($\\sigma_1$,$\\sigma_2$)prod} are ordered pairs whose first\ncomponent has type $\\sigma_1$ and whose second component has type\n$\\sigma_2$.  The \\HOL{} type parser\n%\n\\index{parsing, of HOL logic@parsing, of \\HOL{} logic!of pairs}\n%\nconverts type expressions of the form \\holtxt{:$\\sigma_1$\\#$\\sigma_2$}\n%\n\\index{ product type operator, in HOL logic@\\holtxt{\\#} (product type operator, in \\HOL{} logic)}\n%\ninto \\holtxt{($\\sigma_1$,$\\sigma_2$)prod},\n%\n\\index{ pair constructor, in HOL logic@\\ml{,} (pair constructor, in \\HOL{} logic)}\n%\nand the printer inverts this transformation. Pairs\n%\n\\index{pairing constructor, in HOL logic@pairing constructor, in \\HOL{} logic}\n%\nare constructed with an infixed comma symbol\n\n\\begin{hol}\n\\begin{verbatim}\n   $, : 'a -> 'b -> 'a # 'b\n\\end{verbatim}\n\\end{hol}\n\n\\noindent\nso, for example, if $t_1$ and $t_2$ have types $\\sigma_1$ and\n$\\sigma_2$ respectively, then $t_1$\\ml{,}$t_2$ is a term with type\n$\\sigma_1$\\holtxt{\\#}$\\sigma_2$. Usually, pairs are written within\nbrackets: \\holtxt{($t_1$,$t_2$)}. The comma symbol associates\n%\n\\index{pairing constructor, in HOL logic@pairing constructor, in \\HOL{} logic!associativity of}\n%\nto the right, so that \\holtxt{($t_1$,$t_2$,$\\ldots$,$t_n$)} means\n\\holtxt{($t_1$,($t_2$,$\\ldots$,$t_n$))}.\n\n\\paragraph {Defining the product type}\n\nThe type of Cartesian products is defined by representing a pair\n{\\small\\verb%(%}$t_1${\\small\\verb%,%}$t_2${\\small\\verb%)%}\nby the function\n%\n\\begin{hol}\n\\begin{alltt}\n   \\bs{}a b. (a=\\m{t\\sb{1}}) /\\bs (b=\\m{t\\sb{2}})\n\\end{alltt}\n\\end{hol}\n%\n\\noindent The representing type of\n$\\sigma_1${\\small\\verb%#%}$\\sigma_2$ is thus\n$\\sigma_1${\\small\\verb%->%}$\\sigma_2${\\small\\verb%->bool%}.\nIt is easy to prove the following theorem.\\footnote{This theorem has\nan un-reduced $\\beta$-redex in order to meet the interface\nrequired by the type definition principle.}\n%\n\\begin{hol}\n\\begin{verbatim}\n   |- ?p:'a->'b->bool. (\\p. ?x y. p = \\a b. (a = x) /\\ (b = y)) p\n\\end{verbatim}\n\\end{hol}\n%\nThe type operator {\\small\\verb%prod%} is defined by invoking \\ml{new\\_type\\_definition}\\index{new_type_definition@\\ml{new\\_type\\_definition}} with this theorem which results in the definitional axiom\n\\index{axioms!non-primitive, of HOL logic@non-primitive, of \\HOL{} logic!for products}%\n\\index{axioms!in bool theory@in \\ml{bool} theory}%\n\\ml{prod\\_TY\\_DEF} shown below being asserted in the theory \\ml{pair}.\n%\n\\begin{hol}\n\\begin{verbatim}\n   prod_TY_DEF\n     |- ?rep. TYPE_DEFINITION (\\p. ?x y. p = (\\a b. (a = x) /\\ (b = y))) rep\n\\end{verbatim}\n\\end{hol}\n%\nNext, the representation and abstraction functions \\holtxt{REP\\_prod}\nand \\holtxt{ABS\\_prod} for the new type are introduced, along with the\nfollowing characterizing theorem, by use of the function\n\\ml{define\\_new\\_type\\_bijections}.\n%\n\\begin{hol}\n\\begin{verbatim}\n  |- (!a. ABS_prod (REP_prod a) = a) /\\\n     (!r. (\\p. ?x y. p = (\\a b. (a=x) /\\ (b=y)) r = (REP_prod(ABS_prod r) = r)\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph {Pairs and projections}\n\nThe infix constructor `{\\small\\verb%,%}' is then defined\nto be an application of the abstraction function. Subsequently, two\ncrucial theorems are proved: {\\small\\verb+PAIR_EQ+} asserts that equal\npairs have equal components and {\\small\\verb+ABS_PAIR_THM+} shows that\nevery term having a product type can be decomposed into a pair of terms.\n\\begin{hol}\n\\index{pairing constructor, in HOL logic@pairing constructor, in \\HOL{} logic!definition of}\n\\index{PAIR_EQ@\\ml{PAIR\\_EQ}}\n\\index{ABS_PAIR_THM@\\ml{ABS\\_PAIR\\_THM}}\n\\begin{verbatim}\n   COMMA_DEF    |- !x y. $, x y = ABS_prod (\\a b. (a = x) /\\(b = y))\n\n   PAIR_EQ      |- ((x,y) = (a,b)) = (x=a) /\\ (y=b)\n\n   ABS_PAIR_THM |- !x. ?q r. x = (q,r)\n\\end{verbatim}\n\\end{hol}\n%\nBy Skolemizing {\\small\\verb+ABS_PAIR_THM+} and making constant specifications\nfor {\\small\\verb+FST+} and {\\small\\verb+SND+}, the following theorems\nare proved.\n%\n\\begin{hol}\n\\index{PAIR@\\ml{PAIR}}\n\\index{FST, the HOL constant@\\ml{FST}, the \\HOL{} constant!definition of}\n\\index{SND, the HOL constant@\\ml{SND}, the \\HOL{} constant!definition of}\n\\index{selectors, in HOL logic@selectors, in \\HOL{} logic!for pairs}\n\\begin{verbatim}\n   PAIR     |- !x. (FST x,SND x) = x\n   FST      |- !x y. FST(x,y) = x\n   SND      |- !x y. SND(x,y) = y\n\\end{verbatim}\n\\end{hol}\n\\index{pairs, in HOL logic@pairs, in \\HOL{} logic|)}\n\\index{product types!in HOL logic@in \\HOL{} logic|)}\n\\index{representing types, in HOL logic@representing types, in \\HOL{} logic!pair example of|)}\n\n\\paragraph{Pairs and functions}\n\nIn \\HOL{}, a function of type $\\alpha \\# \\beta\\to\\gamma$ always has a\ncounterpart of type $\\alpha\\to\\beta\\to\\gamma$, and \\emph{vice versa}.\nThis conversion is accomplished by the functions \\holtxt{CURRY} and\n\\holtxt{UNCURRY}. These functions are inverses.\n%\n\\begin{hol}\n\\index{CURRY, the HOL constant@\\ml{CURRY}, the \\HOL{} constant}\n\\index{UNCURRY, the HOL constant@\\ml{UNCURRY}, the \\HOL{} constant}\n\\begin{verbatim}\n   CURRY_DEF    |- !f x y. CURRY f x y = f (x,y)\n   UNCURRY_DEF  |- !f x y. UNCURRY f (x,y) = f x y\n\n   CURRY_UNCURRY_THM |- !f. CURRY (UNCURRY f) = f\n   UNCURRY_CURRY_THM |- !f. UNCURRY (CURRY f) = f\n\\end{verbatim}\n\\end{hol}\n\n\n\\paragraph {Mapping functions over a pair}\n\nFunctions $f : \\alpha \\to \\gamma_1$ and $g : \\beta\\to\\gamma_2$ can be\napplied component-wise ({\\small\\verb+##+}, infix) over a pair of type\n$\\alpha \\# \\beta$ to obtain a pair of type $\\gamma_1 \\# \\gamma_2$.\n%\n\\begin{hol}\n\\index{mapping functions, in the HOL logic@mapping functions, in the \\HOL{} logic!for pairs}\n\\index{ PAIR_MAP function@\\ml{\\#\\#} (\\holtxt{PAIR\\_MAP} function)}\n\\begin{verbatim}\n   PAIR_MAP_THM  |- !f g x y. (f ## g) (x,y) = (f x,g y)\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph {Binders and pairs}\n\nWhen doing proofs, statements involving tuples may take the form of a\nbinding (quantification or $\\lambda$-abstraction) of a variable with a\nproduct type. It may be convenient in subsequent reasoning steps to\nreplace the variables with tuples of variables. The following theorems\nsupport this.\n%\n\\begin{hol}\n\\begin{verbatim}\n  FORALL_PROD  |- (!p. P p) = !p_1 p_2. P (p_1,p_2)\n  EXISTS_PROD  |- (?p. P p) = ?p_1 p_2. P (p_1,p_2)\n  LAMBDA_PROD  |- !P. (\\p. P p) = \\(p1,p2). P (p1,p2)\n\\end{verbatim}\n\\end{hol}\n%\nThe theorem \\ml{LAMBDA\\_PROD} involves a \\emph{paired\n abstraction}, discussed in Section \\ref{HOL-varstruct}.\n\n\n\\paragraph {Wellfounded relations on pairs}\n\nWellfoundedness, defined in Section \\ref{prim-rec-conseq},\nis a useful notion, especially for proving termination of\nrecursive functions. For pairs, the lexicographic combination\nof relations ({\\small\\verb+LEX+}, infix) may be defined by using\npaired abstractions. Then the theorem that lexicographic combination\nof wellfounded relations delivers a wellfounded relation is easy to\nprove.\n%\n\\begin{hol}\n\\begin{verbatim}\n   LEX_DEF =\n      |- !R1 R2. R1 LEX R2 = (\\(s,t) (u,v). R1 s u \\/ (s = u) /\\ R2 t v)\n   WF_LEX\n      |- !R Q. WF R /\\ WF Q ==> WF (R LEX Q)\n\\end{verbatim}\n\\end{hol}\n\n\\subsubsection{Paired abstractions}\n\\label{HOL-varstruct}\n\\index{pairs, in HOL logic@pairs, in \\HOL{} logic!in abstractions|(}\n\\index{pairs, in HOL logic@pairs, in \\HOL{} logic!parsing of}\n\\index{terms, in HOL logic@terms, in \\HOL{} logic!pair|(}\n\\index{parsing, of HOL logic@parsing, of \\HOL{} logic!of paired abstractions}\n\\index{function abstraction, in HOL logic@function abstraction, in \\HOL{} logic!paired|(}\n\\index{function abstraction, in HOL logic@function abstraction, in \\HOL{} logic!uncurrying, in paired|(}\n\nIt is notationally convenient to include pairing in the lambda\nnotation, as a simple pattern-matching mechanism. The quotation parser\n\\index{parsing, of HOL logic@parsing, of \\HOL{} logic!of function abstractions}\n\\index{function abstraction, in HOL logic@function abstraction, in \\HOL{} logic!abbreviation for multiple}\n\\index{terms, in HOL logic@terms, in \\HOL{} logic!function abstraction}\nwill convert the term\n{\\small\\bs\\texttt{(}}$x_1${\\small\\verb%,%}$x_2${\\small\\verb%).%}$t$\nto {\\small\\verb%UNCURRY(%\\bs}$x_1\\ x_2${\\small\\verb%.%}$t${\\small\\verb%)%}.\nThe transformation is done recursively so that, for example,\n%\n\\begin{hol}\n\\begin{alltt}\n   \\bs(\\m{x\\sb{1}},\\m{x\\sb{2}},\\m{x\\sb{3}}).\\m{t}\n\\end{alltt}\n\\end{hol}\n%\n\\noindent is converted to\n%\n\\begin{hol}\n\\begin{alltt}\n   UNCURRY (\\bs\\m{x\\sb{1}}. UNCURRY(\\bs\\m{x\\sb{2}} \\m{x\\sb{3}}.\\m{t}))\n\\end{alltt}\n\\end{hol}\n%\n\\noindent More generally, the quotation parser repeatedly applies the\ntransformation:\n%\n\\begin{hol}\n\\begin{alltt}\n   \\bs(\\m{v\\sb{1}},\\m{v\\sb{2}}).\\m{t}\\m{\\quad \\leadsto\\quad}UNCURRY(\\bs\\m{v\\sb{1}}.\\bs\\m{v\\sb{2}}.\\m{t})\n\\end{alltt}\n\\end{hol}\n%\n\\noindent until no more variable structures remain. For example:\n\n\\vspace{1ex}\n\\begin{tabular}{ll}\n\\texttt{\\bs($x$,$y$).$t$} &\n  $\\leadsto$ \\texttt{UNCURRY(\\bs$x\\,y$.$t$)}\\\\\n%\n\\texttt{\\bs($x_1$,$x_2$,$\\ldots$,$x_n$).$t$} &\n  $\\leadsto$ \\texttt{UNCURRY(\\bs$x_1$.\\bs($x_2$,$\\ldots$,$x_n$).$t$)}\\\\\n%\n\\texttt{\\bs(($x_1$,$\\ldots$,$x_n$),$y_1$,$\\ldots$,$y_m$).$t$} &\n  $\\leadsto$\n  \\texttt{UNCURRY(\\bs($x_1$,$\\ldots$,$x_n$).\\bs($y_1$,$\\ldots$,$y_m$).$t$)}\\\\\n\\end{tabular}\n\n\\vspace{1ex}\n\n\\noindent As a result of this parser translation, a variable structure, such as \\ml{(x,y)} in\n\\ml{\\bs(x,y).x+y}, is not a subterm of the abstraction\n\\index{function abstraction, in HOL logic@function abstraction, in \\HOL{} logic!subterms of}\nin which it occurs; it disappears on parsing.\n\\index{binders, in HOL logic@binders, in \\HOL{} logic!parsing of}%\n\\index{parsing, of HOL logic@parsing, of \\HOL{} logic!of binders}%\nThis can lead to unexpected errors (accompanied by obscure error\nmessages).  For example, antiquoting a pair into the bound variable\nposition of a lambda abstraction fails:\n\n\\begin{session}\n\\begin{verbatim}\n- ``\\(x,y).x+y``;\n> val it = `\\(x,y). x + y` : term\n\n- val p = Term `(x:num,y:num)`;\n> val p = `(x,y)` : term\n\n- Lib.try Term `\\^p.x+y`;\n\nException raised at Term.dest_var:\nnot a var\n! Uncaught exception:\n\\end{verbatim}\n\\end{session}\nIf $b$ is a binder, then \\ml{$b$($x_1$,$x_2$).$t$} is parsed as\n\\ml{$b$(\\bs($x_1$,$x_2$).$t$)}, and hence transformed as above.  For\nexample,\n\\ml{!(x,y).\\ x > y}\nparses to\n\\ml{\\$!(UNCURRY(\\bs{}x.\\bs{}y.\\ x > y))}.\n\\index{function abstraction, in HOL logic@function abstraction, in \\HOL{} logic!paired|)}\n\\index{function abstraction, in HOL logic@function abstraction, in \\HOL{} logic!uncurrying, in paired|)}\n\\index{pairs, in HOL logic@pairs, in \\HOL{} logic!in abstractions|)}\n\\index{terms, in HOL logic@terms, in \\HOL{} logic!pair|)}\n\n\n\\subsubsection{\\texttt{let}-terms}\n\\label{let-exp}\n\nThe quotation parser\n%\n\\index{parsing, of HOL logic@parsing, of \\HOL{} logic!of let-terms@of \\holtxt{let}-terms}\n%\naccepts \\ml{let}-terms\n\\index{terms, in HOL logic@terms, in \\HOL{} logic!let-@\\holtxt{let}-}%\n\\index{let-terms, in HOL logic@\\holtxt{let}-terms, in \\HOL{} logic!as abbreviations}%\nsimilar to those in \\ML. For example, the following terms are allowed:\n\n\\begin{hol}\n\\begin{verbatim}\n   let x = 1 and y = 2 in x+y\n\n   let f(x,y) = (x*x)+(y*y) and a = 20*20 and b = 50*49 in f(a,b)\n\\end{verbatim}\n\\end{hol}\n\n\\ml{let}-terms are actually abbreviations for ordinary terms which are\nspecially supported by the parser and pretty printer.\nThe constant \\ml{LET}\n%\n\\index{LET, the HOL constant@\\ml{LET}, the \\HOL{} constant}\n%\nis defined (in the theory \\ml{bool}) by:\n\n\\begin{hol}\\index{function abstraction, in HOL logic@function abstraction, in \\HOL{} logic!relation to let-terms@relation to \\ml{let}-terms}\n\\begin{verbatim}\n   LET = (\\f x. f x)\n\\end{verbatim}\n\\end{hol}\n\n\\noindent and is used to encode \\ml{let}-terms in the logic. The parser\nrepeatedly applies the transformations:\n\n\\bigskip\n\n{\\small\\begin{tabular}{ll}\n\\texttt{let~$f\\,v_1\\,\\ldots\\,v_n$~=~$t_1$~in~$t_2$} &\n$\\leadsto$~~\\texttt{LET(\\bs$f$.$t_2$)(\\bs$v_1\\,\\ldots\\,v_n$.$t_1$)}\\\\\n%\n\\texttt{let~($v_1$,$\\ldots$,$v_n$)~=~$t_1$~in~$t_2$} &\n$\\leadsto$~~\\texttt{LET(\\bs($v_1$,$\\ldots$,$v_n$).$t_2$)$t_1$}\\\\\n%\n\\texttt{let~$v_1$=$t_1$~and~$\\ldots$~and~$v_n$=$t_n$~in~$t$} &\n$\\leadsto$~~\\texttt{LET($\\ldots$(LET(LET(\\bs$v_1\\ldots v_n$.$t$)$t_1$)$t_2$)$\\ldots$)$t_n$}\\\\\n\\end{tabular}}\n\n\\bigskip\n\n\n\\noindent The underlying structure of the term can be seen by applying\ndestructor operations.  For example:\n\n\\begin{session}\n\\begin{verbatim}\n- Term `let x = 1 and y = 2 in x+y`;\n> val it = `let x = 1 and y = 2 in x + y` : term\n\n- dest_comb it;\n> val it = (`LET (LET (\\x y. x + y) 1)`, `2`) : term * term\n\n- Term `let (x,y) = (1,2) in x+y`;\n> val it = `let (x,y) = (1,2) in x + y` : Term.term\n\n- dest_comb it;\n> val it = (`LET (\\(x,y). x + y)`, `(1,2)`) : Term.term * Term.term\n\\end{verbatim}\n\\end{session}\n\nReaders are encouraged to convince themselves that the translations of\n\\ml{let}-terms represent the intuitive meaning suggested by the\nsurface syntax.%\n%\n\n\\subsection{Disjoint sums}\n\\label{sum}\n\\index{disjoint unions, the HOL theory of@disjoint unions, the \\HOL{} theory of|(}\n\\index{sums (disjoint unions), the HOL theory of@sums (disjoint unions), the \\HOL{} theory of|(}\n\n\nThe theory \\theoryimp{sum} defines the binary disjoint union type\noperator \\holtxt{sum}.  A type \\holtxt{($\\sigma_1$,$\\sigma_2$)sum}\ndenotes the disjoint union of types $\\sigma_1$ and $\\sigma_2$.  The\ntype operator \\holtxt{sum} can be defined, just as \\holtxt{prod} was,\nbut the details are omitted here.\\footnote{The definition of disjoint\n  unions in the HOL system is due to Tom Melham. The technical details\n  of this definition can be found in~\\cite{Melham-banff}.}  The \\HOL{}\nparser\n%\n\\index{parsing, of HOL logic@parsing, of \\HOL{} logic!of sum types}\n%\nconverts \\holtxt{``:$\\sigma_1$+$\\sigma_2$``}\n%\n\\index{ disjoint union type operator, in HOL logic@\\ml{+} (disjoint union type operator, in HOL logic)}\n%\ninto \\holtxt{``:($\\sigma_1$,$\\sigma_2$)sum``}, and the printer inverts\nthis.\n\nThe standard operations on sums are:\n\n\\begin{hol}\n\\index{INL, the HOL constant@\\ml{INL}, the \\HOL{} constant}\n\\index{INR, the HOL constant@\\ml{INR}, the \\HOL{} constant}\n\\index{ISL, the HOL constant@\\ml{ISL}, the \\HOL{} constant}\n\\index{ISR, the HOL constant@\\ml{ISR}, the \\HOL{} constant}\n\\index{OUTL, the HOL constant@\\ml{OUTL}, the \\HOL{} constant}\n\\index{OUTR, the HOL constant@\\ml{OUTR}, the \\HOL{} constant}\n\\begin{verbatim}\n   INL  : 'a -> 'a + 'b\n   INR  : 'b -> 'a + 'b\n   ISL  : 'a + 'b -> bool\n   ISR  : 'a + 'b -> bool\n   OUTL : 'a + 'b -> 'a\n   OUTR : 'a + 'b -> 'b\n\\end{verbatim}\n\\end{hol}\n\n\\noindent These are all defined as constants in the theory \\ml{sum}.  The\nconstants \\ml{INL} and \\ml{INR} inject into the left and right summands,\nrespectively. The constants \\ml{ISL} and \\ml{ISR} test for membership of the\nleft and right summands, respectively. The constants \\ml{OUTL} and \\ml{OUTR}\nproject from a sum to the left and right summands, respectively.\n\nThe following theorem is proved in the theory \\ml{sum}. It provides a\ncomplete and abstract characterization of the disjoint sum type, and\nis used to justify the definition of functions over sums.\n\n\\begin{hol}\n\\begin{verbatim}\n  sum_Axiom  |- !f g. ?! h. (!x. h(INL x) = f x) /\\ (!x. h(INR x) = g x)\n\\end{verbatim}\n\\end{hol}\n\n\\noindent Also provided are the following theorems having to\ndo with the discriminator functions \\ml{ISL} and \\ml{ISR}:\n\n\\begin{hol}\n\\begin{verbatim}\n   ISL         |- (!x. ISL(INL x)) /\\ (!y. ~ISL(INR y))\n   ISR         |- (!x. ISR(INR x)) /\\ (!y. ~ISR(INL y))\n\n   ISL_OR_ISR  |- !x. ISL x \\/ ISR x\n\\end{verbatim}\n\\end{hol}\n\n\\noindent The \\ml{sum} theory also provides the following theorems\nrelating the projection functions and the discriminators.\n\n\\begin{hol}\n\\begin{verbatim}\n   OUTL        |- !x. OUTL(INL x) = x\n   OUTR        |- !x. OUTR(INR x) = x\n\n   INL         |- !x. ISL x ==> (INL(OUTL x) = x)\n   INR         |- !x. ISR x ==> (INR(OUTR x) = x)\n\\end{verbatim}\n\\end{hol}\n\n\\index{disjoint unions, the HOL theory of@disjoint unions, the \\HOL{} theory of|)}\n\\index{sums (disjoint unions), the HOL theory of@sums (disjoint unions), the \\HOL{} theory of|)}\n\n\n\\subsection{The one-element type}%\n\\index{one, the HOL theory and type@\\ml{one}, the \\HOL{} theory and type}%\n\nThe theory \\ml{one} defines  the type  \\ml{one} which  contains one element.\nThe constant  \\ml{one}  is specified  to denote  this element.   The pre-proved\ntheorems in the theory \\ml{one} are:\n\n\\begin{hol}\n\\index{one_Axiom@\\ml{one\\_Axiom}}\n\\begin{verbatim}\n   one_axiom   |- !(f:'a->one) (g:'a->one). f = g\n   one         |- !(v:one). v = one\n   one_Axiom   |- !(e:'a). ?!(fn:one->'a). fn one = e\n\\end{verbatim}\n\\end{hol}\n\n\\noindent These three theorems are equivalent characterizations of the type\nwith only one value. The theory \\ml{one} is typically used in\nconstructing more elaborate types.  The one value of the type\n\\ml{one}, can also be written as \\ml{()} by analogy with the unit\nvalue in \\ML.  This is also the default way in which this value is\nprinted by the system pretty-printer.\n\n\\subsubsection{The itself type}\n\\index{itself, the HOL type operator@\\holtxt{itself}, the \\HOL{} type operator}%\nThe unary \\holtxt{itself} type operator provides a family of singleton types akin to \\holtxt{one}.\nThus, for every type $\\alpha$, \\holtxt{$\\alpha$~itself} is a type containing just one value.\nThis value's name is \\holtxt{the\\_value}, but the parser and pretty-printer are set up so that for the type \\holtxt{$\\alpha$~itself}, \\holtxt{the\\_value} can be written as \\holtxt{(:$\\alpha$)} (the syntax includes the parentheses).\nFor example, \\holtxt{(:num)} is the single value inhabiting the type \\holtxt{num~itself}.\n\nThe point of the itself type is that if one defines a function with \\holtxt{$\\alpha$~itself} as the domain, the function picks out just one value in its range,  and so one can think of the function as being one from the type to a value for the whole type.\n\nFor example, one could define\n\\begin{hol}\n\\begin{verbatim}\n   finite_univ (:'a) = FINITE (UNIV :'a set)\n\\end{verbatim}\n\\end{hol}\nIt would then be straightforward to prove the following theorems\n\\begin{hol}\n\\begin{alltt}\n   \\(\\vdash\\) finite_univ(:bool)\n   \\(\\vdash\\) \\(\\neg\\)finite_univ(:num)\n   \\(\\vdash\\) finite_univ(:'a) \\(\\land\\) finite_univ(:'b) \\(\\Rightarrow\\) finite_univ(:'a # 'b)\n\\end{alltt}\n\\end{hol}\n\nThe itself type is used in the Finite Cartesian Product construction that underlies the fixed-width word type (see Section~\\ref{sec:bit-vectors} below).\n\n\\subsection{The option type}\n\\index{options, the HOL theory of@options, the \\HOL{} theory of}\n\nThe theory \\theoryimp{option} defines a type operator \\verb+option+\nthat `lifts' its argument type, creating a type with all of the\nvalues of the argument and one other, specially distinguished value.\nThe constructors of this type are\n\\begin{hol}\n\\begin{verbatim}\n   NONE : 'a option\n   SOME : 'a -> 'a option\n\\end{verbatim}\n\\end{hol}\nOptions can be used to model partial functions.  If a function of type\n$\\alpha\\rightarrow\\beta$ does not have useful $\\beta$ values for all\n$\\alpha$ inputs, then this distinction can be marked by making the\nrange of the function $\\beta\\,\\konst{option}$, and mapping the\nundefined $\\alpha$ values to \\holtxt{NONE}.\n\nAn inductive type, options have a recursion theorem supporting the\ndefinition of primitive recursive functions over option values.\n%\n\\begin{hol}\n\\begin{verbatim}\n   option_Axiom\n     |- !e f.\n         ?h:'a option -> 'b.\n           (!x. h (SOME x) = f x) /\\\n           (h NONE = e)\n\\end{verbatim}\n\\end{hol}\nThe \\theoryimp{option} theory also defines a case constant that allows\none to inspect option values in a ``pattern-matching'' style.\n\\begin{hol}\n\\begin{verbatim}\n   case e of\n     NONE => u\n   | SOME x => f x\n\\end{verbatim}\n\\end{hol}\n%\nThe constant underlying this syntactic sugar is \\verb+option_case+\nwith definition\n\\begin{hol}\n\\begin{verbatim}\n   option_case_def |- (option_case u f NONE = u) /\\\n                      (option_case u f (SOME x) = f x)\n\\end{verbatim}\n\\end{hol}\n%\nAnother useful function maps a function over an option:\n%\n\\index{mapping functions, in the HOL logic@mapping functions, in the \\HOL{} logic!for options}\n\\begin{hol}\n\\begin{verbatim}\n   OPTION_MAP_DEF  |- (OPTION_MAP f NONE = NONE) /\\\n                      (OPTION_MAP f (SOME x) = SOME (f x))\n\\end{verbatim}\n\\end{hol}\nFinally, the \\holtxt{THE} function takes a \\holtxt{SOME}\nvalue to that constructor's argument, and is unspecified on\n\\holtxt{NONE}:\n\\begin{hol}\n\\begin{verbatim}\n   THE_DEF   |- THE (SOME x) = x\n\\end{verbatim}\n\\end{hol}\n\n\\section{Numbers}\n\nThe natural numbers, integers, and real numbers are provided in a\nseries of theories. Also available are theories of $n$-bit words\n(numbers modulo $2^n$), floating point and fixed point numbers.\n\n\\subsection{Natural numbers}\n\nThe natural numbers are developed in a series of theories:\n\\theoryimp{num}, \\theoryimp{prim\\_rec}, \\theoryimp{arithmetic}, and\n\\theoryimp{numeral}. In \\theoryimp{num}, the type of numbers is\ndefined from the Axiom of Infinity, and Peano's axioms are derived. In\n\\theoryimp{prim\\_rec} the Primitive Recursion theorem is proved. Based\non that, a large theory treating the standard arithmetic operations is\ndeveloped in \\theoryimp{arithmetic}. Lastly, a theory of numerals is\ndeveloped.\n\n\\subsubsection{The theory \\theoryimp{num}}\n\nThe theory \\theoryimp{num}\n\\index{num, the theory in HOL logic@\\ml{num}, the theory in \\HOL{} logic}\ndefines the type \\ml{num} of natural numbers to be\nisomorphic to a countable subset of the primitive type \\ml{ind}.  In this\ntheory, the constants \\ml{0}\n\\index{ zero, in HOL logic@\\ml{0} (zero, in \\HOL{} logic)}\nand \\ml{SUC} (the successor function) are defined\nand Peano's axioms\n\\index{axioms!in num theory@in \\ml{num} theory}%\n\\index{Peano's axioms}%\n\\index{axioms!non-primitive, of HOL logic@non-primitive, of \\HOL{} logic!for natural numbers}%\npre-proved in the form:\n\n\\begin{hol}\n\\index{NOT_SUC@\\ml{NOT\\_SUC}}\n\\index{INV_SUC@\\ml{INV\\_SUC}}\n\\index{induction theorems, in HOL logic@induction theorems, in \\HOL{} logic!for natural numbers}\n\\begin{verbatim}\n   NOT_SUC    |- !n. ~(SUC n = 0)\n   INV_SUC    |- !m n. (SUC m = SUC n) ==> (m = n)\n   INDUCTION  |- !P. P 0 /\\ (!n. P n ==> P(SUC n)) ==> (!n. P n)\n\\end{verbatim}\n\\end{hol}\n\nIn higher order logic, Peano's axioms are sufficient for developing\nnumber theory because addition and multiplication can be defined. In\nfirst order logic these must be taken as primitive.  Note also that\n\\ml{INDUCTION} could not be stated as a single axiom in first order\nlogic because predicates (\\eg\\ \\holtxt{P}) cannot be quantified.\n\n\\subsubsection{The theory \\theoryimp{prim\\_rec}}\n\\label{sec:prim-rec}\n\n\\index{primitive recursion theorem!for numbers}\n\\index{prim_rec, the HOL theory@\\ml{prim\\_rec}, the \\HOL{} theory|(}\nIn classical logic, unlike domain theory logics such as \\PPL,\n%\n\\index{PPlambda (same as PPLAMBDA), of LCF system@\\ml{PP}$\\lambda$ (same as \\ml{PPLAMBDA}), of \\ml{LCF} system}\n%\narbitrary recursive definitions\n%\n\\index{recursive definitions, in classical logics}\n%\nare not allowed. For example, there is no function $f$ (of type\n\\ml{num->num}) such that\n\n\\begin{alltt}\n   !\\(x\\). \\(f\\) \\(x\\) = (\\(f\\) \\(x\\)) + 1\n\\end{alltt}\nCertain restricted forms of recursive\n%\n\\index{primitive recursive functions}\n%\ndefinition do, however, uniquely define functions. An important\nexample are the \\emph{primitive recursive} functions.\\footnote{In\n  higher order logic, primitive recursion is much more powerful than\n  in first order logic; for example, Ackermann's function can be\n  defined by primitive recursion in higher order logic.} For any $x$\nand $f$ the \\emph{primitive recursion theorem} tells us that there is\na unique function \\holtxt{fn} such that:\n\n\\begin{alltt}\n   (fn 0 = \\(x\\)) /\\bs (!\\(n\\). fn(SUC \\(n\\)) = f (fn \\(n\\)) \\(n\\))\n\\end{alltt}\n\nThe primitive recursion theorem, named \\ml{num\\_Axiom} in \\HOL,\nfollows from Peano's\n%\n\\index{Peano's axioms}\n%\naxioms.\n\n\\begin{hol}\\index{num_Axiom@\\ml{num\\_Axiom}}\n\\index{characterizing theorem!for numbers}\n\\begin{verbatim}\n   num_Axiom  |- !x f. ?fn. (fn 0 = x) /\\ (!n. fn(SUC n) = f n (fn n))\n\\end{verbatim}\n\\end{hol}\n\n\\noindent The theorem states the validity of primitive recursive\ndefinitions on the natural numbers: for any \\ml{x} and \\ml{f} there exists a\ncorresponding total function \\ml{fn} which satisfies\nthe primitive recursive definition whose form is determined by \\ml{x} and\n\\ml{f}.\n\n\\paragraph{The less-than relation}\n\nThe less-than relation `\\holtxt{<}'\n\\index{ less than, in HOL logic@\\ml{<} (less than, in \\HOL{} logic)}%\n\\index{less than, in HOL logic@less than, in \\HOL{} logic}%\nis most naturally defined by primitive recursion. However, in our\ndevelopment it is needed for the proof of the\n  primitive recursion theorem, so it must be defined before definition\n  by primitive recursion is available. The theory \\theoryimp{prim\\_rec}\n  therefore contains the following non-recursive definition of \\ml{<}:\n\n\\begin{hol}\n\\index{LESS@\\ml{LESS}}\n\\begin{verbatim}\n   LESS  |- !m n. m < n = ?P. (!n. P(SUC n) ==> P n) /\\ P m /\\ ~P n\n\\end{verbatim}\n\\end{hol}\n\n\\noindent\nThis definition says that {\\small\\verb%m < n%} if there exists a set (with\ncharacteristic function {\\small\\verb%P%}) that is downward\nclosed\\footnote{A set of numbers is \\textit{downward closed} if whenever it\ncontains the successor of a number, it also contains the number.} and\ncontains {\\small\\verb%m%} but not {\\small\\verb%n%}.\n\\index{prim_rec, the HOL theory@\\ml{prim\\_rec}, the \\HOL{} theory|)}\n\n\n\\subsubsection{Mechanizing primitive recursive definitions}\n\\label{num-prim-rec}\n\n\\index{recursive definitions, in HOL logic@recursive definitions, in \\HOL{} logic!automated, for numbers}\n\\index{primitive recursion theorem!automated use of, in HOL system@automated use of, in \\HOL{} system|(}\nThe primitive\n\\index{primitive recursive definitions, in HOL logic@primitive recursive definitions, in \\HOL{} logic!justification of}\nrecursion theorem can be used to justify any definition of a function\non the natural numbers by primitive recursion.  For example, a\nprimitive recursive definition in higher order logic of the form\n\n\\begin{hol}\n\\begin{alltt}\n   fun 0       x\\(\\sb{1}\\) \\m{\\dots} x\\(\\sb{i}\\) = \\m{f\\sb{1}[}x\\(\\sb{1}\\)\\m{,\\ldots,\\,} x\\(\\sb{i}]\\)\n   fun (SUC n) x\\(\\sb{1}\\) \\m{\\dots} x\\(\\sb{i}\\) = \\m{f\\sb{2}[}fun n \\m{t\\sb{1} \\dots t\\sb{i},} n\\m{,} x\\(\\sb{1}\\)\\m{,\\ldots,\\,}x\\(\\sb{i}]\\)\n\\end{alltt}\n\\end{hol}\n\n\\noindent where all the free variables in the  terms $t_1$,\n\\dots, $t_i$ are contained in $\\{$\\ml{n}, $\\ml{x}_1$, \\dots, $\\ml{x}_i\\}$,\nis logically equivalent to:\n\n\\begin{hol}\n\\begin{alltt}\n   fun 0       = \\bs{}x\\(\\sb{1}\\) \\m{\\dots} x\\(\\sb{i}\\).\\m{f\\sb{1}[}x\\(\\sb{1}\\)\\m{,\\ldots,\\,}x\\(\\sb{i}]\\)\n   fun (SUC n) = \\bs{}x\\(\\sb{1}\\) \\m{\\dots} x\\(\\sb{i}\\).\\m{f\\sb{2}[}fun n \\m{t\\sb{1} \\dots t\\sb{i},} n\\m{,}x\\(\\sb{1}\\)\\m{,\\ldots,\\,}x\\(\\sb{i}]\\)\n               = (\\bs{}f n x\\(\\sb{1}\\) \\m{\\dots} x\\(\\sb{i}\\).\\m{f\\sb{2}[}f \\m{t\\sb{1} \\dots t\\sb{i},} n\\m{,} x\\(\\sb{1}\\)\\m{,\\ldots,\\,}x\\(\\sb{i}]\\)) (fun n) n\n\\end{alltt}\n\\end{hol}\n\nThe existence  of  a  recursive  function  \\ml{fun} which  satisfies these two\nequations follows directly from the primitive recursion theorem\n\\ml{num\\_Axiom} shown above.   Specializing the  quantified variables \\verb!x!\nand \\verb!f!  in  a suitably  type-instantiated version  of \\ml{num\\_Axiom} so\nthat\n\n\\begin{hol}\n\\begin{alltt}\n   x\\m{=}\\bs{}x\\(\\sb{1}\\) \\(\\dots\\) x\\(\\sb{i}\\).\\m{f\\sb{1}[}x\\(\\sb{1}\\)\\(,\\ldots,\\,\\)x\\(\\sb{i}]\\)  {\\rm and}  f\\(=\\)\\bs{}f n x\\(\\sb{1}\\) \\(\\dots\\) x\\(\\sb{i}\\).\\m{f\\sb{2}[}f \\m{t\\sb{1} \\dots t\\sb{i},} n\\(,\\) x\\(\\sb{1}\\)\\(,\\ldots,\\,\\)x\\(\\sb{i}]\\))\n\\end{alltt}\n\\end{hol}\n\n\\noindent yields the existence theorem shown below:\n\n\\begin{hol}\n\\begin{alltt}\n   |- ?fn. fn 0       = \\bs{}x\\(\\sb{1}\\) \\(\\dots\\) x\\(\\sb{i}\\).\\m{f\\sb{1}[}x\\(\\sb{1}\\)\\(,\\ldots,\\,\\)x\\(\\sb{i}]\\) /\\bs{}\n           fn (SUC n) = (\\bs{}f n x\\(\\sb{1}\\) \\(\\dots\\) x\\(\\sb{i}\\).\\m{f\\sb{2}[}f \\m{t\\sb{1} \\dots t\\sb{i},} n\\(,\\) x\\(\\sb{1}\\)\\(,\\ldots,\\,\\)x\\(\\sb{i}]\\)) (fn n) n\n\\end{alltt}\n\\end{hol}\n\n\\noindent This theorem allows a constant \\ml{fun} to be introduced (via the\ndefinitional mechanism of constant specifications---see Section~\\ref{conspec})\nto denote the recursive function that satisfies the two equations in the body\nof the theorem. Introducing a constant \\ml{fun} to name the function asserted\nto exist by the theorem shown above, and simplifying using $\\beta$-reduction,\nyields the following theorem:\n\n\\begin{hol}\n\\begin{alltt}\n   |- fun 0       = \\bs{}x\\(\\sb{1}\\) \\(\\dots\\) x\\(\\sb{i}\\).\\m{f\\sb{1}[}x\\(\\sb{1}\\)\\(,\\ldots,\\,\\)x\\(\\sb{i}]\\) /\\bs{}\n      fun (SUC n) = \\bs{}x\\(\\sb{1}\\) \\(\\dots\\) x\\(\\sb{i}\\).\\m{f\\sb{2}[}fun n \\m{t\\sb{1} \\dots t\\sb{i},} n\\(,\\) x\\(\\sb{1}\\)\\(,\\ldots,\\,\\)x\\(\\sb{i}]\\)\n\\end{alltt}\n\\end{hol}\n\n\\noindent It follows immediately from this theorem that the constant \\ml{fun}\nsatisfies the primitive recursive defining equations given by the theorem shown\nbelow:\n\n\\begin{hol}\n\\begin{alltt}\n   |- fun 0 x\\(\\sb{1}\\) \\(\\dots\\) x\\(\\sb{i}\\) = \\m{f\\sb{1}[}x\\(\\sb{1}\\)\\(,\\ldots,\\,\\)x\\(\\sb{i}]\\)\n      fun (SUC n) x\\(\\sb{1}\\) \\(\\dots\\) x\\(\\sb{i}\\) = \\m{f\\sb{2}[}fun n \\m{t\\sb{1} \\dots t\\sb{i},} n\\(,\\) x\\(\\sb{1}\\)\\(,\\ldots,\\,\\)x\\(\\sb{i}]\\)\n\\end{alltt}\n\\end{hol}\n\nTo automate the use of the primitive recursion theorem in deriving\nrecursive definitions of this kind, the \\HOL{} system provides a function\nwhich automatically proves the existence of primitive recursive\nfunctions and then makes a constant specification to introduce the constant\nthat denotes such a function:\n\n\\begin{holboxed}\n\\index{new_recursive_definition@\\ml{new\\_recursive\\_definition}|pin}\n\\begin{verbatim}\n   new_recursive_definition :\n      {def : term, name : string, rec_axiom : thm} -> thm\n\\end{verbatim}\n\\end{holboxed}\n\n\\noindent In fact, \\ml{new\\_recursive\\_definition} handles\nprimitive recursive definitions over a range of types, not just the\nnatural numbers. For details, see the \\REFERENCE\\ documentation.\n\nMore conveniently still, the \\ml{Define} function (see\nSection~\\ref{sec:high-level-proof-steps}) supports primitive\nrecursion, along with other styles of recursion, and does not require\nthe user to quote the primitive recursion axiom. It may, however,\nrequire termination proofs to be performed; fortunately, these need\nnot be done for primitive recursions.\n\n\\subsubsection{Dependent choice and wellfoundedness}\n\\label{prim-rec-conseq}\n\nThe primitive recursion theorem is useful beyond its main purpose of\njustifying recursive definitions. For example, the theory\n\\theoryimp{prim\\_rec} proves the Axiom of Dependent Choice ({\\small\\verb+DC+}).\n\n\\begin{hol}\n\\index{axiom of dependent choice (DC)@axiom of dependent choice (\\ml{DC})}\n\\index{axioms!of choice}\n\\begin{verbatim}\n   DC  |- !P R a.\n            P a /\\ (!x. P x ==> ?y. P y /\\ R x y)\n             ==>\n           ?f. (f 0 = a) /\\ !n. P (f n) /\\ R (f n) (f (SUC n))\n\\end{verbatim}\n\\end{hol}\n\nThe proof uses {\\small\\verb+SELECT_AX+}. The theorem {\\small\\verb+DC+}\nis useful when one wishes to build a function having a certain\nproperty from a relation. For example, one way to define the\nwellfoundedness of a relation $R$ is to say that it has no infinite\ndecreasing $R$ chains.\n%\n\\begin{hol}\n\\index{wellfounded@\\ml{wellfounded}}\n\\begin{verbatim}\n   wellfounded_def\n     |- wellfounded (R:'a->'a->bool) = ~?f. !n. R (f (SUC n)) (f n)\n\n   WF_IFF_WELLFOUNDED\n     |- !R. WF R = wellfounded R\n\\end{verbatim}\n\\end{hol}\nBy use of {\\small\\verb+DC+}, this statement can be proved\nto be equal to the notion of wellfoundedness {\\small\\verb+WF+}\n(namely, that every set has an $R$-minimal element) defined in the theory\n\\theoryimp{relation}.\n\nTheorems asserting the wellfoundedness of the predecessor relation and\nthe less-than relation, as well as the wellfoundedness of measure\nfunctions are also proved in \\theoryimp{prim\\_rec}.\n\n\\begin{hol}\n\\index{WF_PRED@\\ml{WF\\_PRED}}\n\\index{WF_LESS@\\ml{WF\\_LESS}}\n\\index{measure_def@\\ml{measure\\_def}}\n\\index{WF_measure@\\ml{WF\\_measure}}\n\\begin{verbatim}\n   WF_PRED     |- WF (\\x y. y = SUC x)\n   WF_LESS     |- WF $<\n\n   measure_def |- measure = inv_image $<\n   measure_thm |- !f x y. measure f x y = f x < f y\n   WF_measure  |- !m. WF (measure m)\n\\end{verbatim}\n\\end{hol}\n\n\n\\subsection{Arithmetic}\n\\index{arithmetic, the HOL theory of@arithmetic, the \\HOL{} theory of}\n\nThe \\HOL{} theory \\theoryimp{arithmetic} contains primitive recursive\ndefinitions of the following standard arithmetic operators.\n\n\\begin{hol}\n\\index{ADD@\\ml{ADD}}\n\\index{SUB@\\ml{SUB}}\n\\index{MULT@\\ml{MULT}}\n\\index{EXP, the HOL constant@\\holtxt{EXP}, the \\HOL{} constant}\n\\index{ subtraction, in HOL logic@\\holtxt{-} (subtraction, in \\HOL{} logic)}\n\\index{ multiplication, in HOL logic@\\holtxt{*} (multiplication, in \\HOL{} logic)}\n\\index{ exponentiation, in HOL logic@\\holtxt{**} (exponentiation, in \\HOL{} logic)}\n\\begin{verbatim}\n   ADD    |- (!n. 0 + n = n) /\\\n             (!m n. (SUC m) + n = SUC(m + n))\n\n   SUB    |- (!m. 0 - m = 0) /\\\n             (!m n. (SUC m) - n = if m < n then 0 else SUC(m - n))\n\n   MULT   |- (!n. 0 * n = 0) /\\\n             (!m n. (SUC m) * n = (m * n) + n)\n\n   EXP    |- (!m. m EXP 0 = 1) /\\\n             (!m n. m EXP (SUC n) = m * (m EXP n))\n\\end{verbatim}\n\\end{hol}\n%\nNote that \\holtxt{EXP} is an infix. The infix notation\n\\holtxt{**} may be used in place of \\holtxt{EXP}. Thus\n(\\holtxt{x EXP y}) means $x^y$, and so does (\\holtxt{x ** y}).\n\n\\paragraph{Comparison operators}\n\nA full set of comparison operators is defined in terms of \\verb+<+.\n\n\\begin{hol}\n\\index{ greater than, in HOL logic@\\ml{>} (greater than, in \\HOL{} logic)}\n\\index{ less or equal, in HOL logic@\\ml{<=} (less or equal, in \\HOL{} logic)}\n\\index{ greater or equal, in HOL logic@\\ml{>=} (greater or equal, in \\HOL{} logic)}\n\\begin{verbatim}\n   GREATER_DEF    |- !m n. m > n = (n < m)\n   LESS_OR_EQ     |- !m n. m <= n = (m < n \\/ (m = n))\n   GREATER_OR_EQ  |- !m n. m >= n = (m > n \\/ (m = n))\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph{Division and modulus}\n\nA constant specification is used to introduce division ({\\small\\verb+DIV+}, infix) and\nmodulus ({\\small\\verb+MOD+}, infix) operators, together with their\ncharacterizing property.\n\\begin{hol}\n\\index{MOD, the HOL constant@\\ml{MOD}, the \\HOL{} constant}\n\\index{DIV, the HOL constant@\\ml{DIV}, the \\HOL{} constant}\n\\begin{verbatim}\n   DIVISION\n     |- !n. 0 < n ==> !k. (k = ((k DIV n) * n) + (k MOD n)) /\\ (k MOD n) < n\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph{Even and odd}\n\nThe properties of a number being even or odd are defined recursively.\n%\n\\begin{hol}\n\\index{EVEN, the HOL constant@\\ml{EVEN}, the \\HOL{} constant}\n\\index{ODD, the HOL constant@\\ml{ODD}, the \\HOL{} constant}\n\\begin{verbatim}\n   EVEN |- (EVEN 0 = T) /\\ !n. EVEN (SUC n) = ~EVEN n\n\n   ODD  |- (ODD 0 = F) /\\ !n. ODD (SUC n) = ~ODD n\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph{Maximum and minimum}\n\nThe minimum and maximum of two numbers are defined in the usual way.\n%\n\\begin{hol}\n\\index{MIN, the HOL constant@\\ml{MIN}, the \\HOL{} constant}\n\\index{MAX, the HOL constant@\\ml{MAX}, the \\HOL{} constant}\n\\begin{verbatim}\n   MAX_DEF |- !m n. MAX m n = (if m < n then n else m)\n   MIN_DEF |- !m n. MIN m n = (if m < n then m else n)\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph{Factorial}\n\\index{FACT, the HOL constant@\\ml{FACT}, the \\HOL{} constant}\n\nThe factorial of a number is a primitive recursive definition.\n%\n\\begin{hol}\n\\begin{verbatim}\n   FACT |- (FACT 0 = 1) /\\ !n. FACT (SUC n) = SUC n * FACT n\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph{Function iteration}\n\\index{FUNPOW, the HOL constant@\\ml{FUNPOW}, the \\HOL{} constant}\n\nThe iterated application $f^n x$ of a function $f : \\alpha \\to\n\\alpha$ is defined by primitive recursion. The definition\n(\\ml{FUNPOW}) is tail-recursive, which can be awkward to reason\nabout. An alternative characterization (\\ml{FUNPOW\\_SUC}) may be easier\nto apply when doing proofs.\n%\n\\begin{hol}\n\\begin{verbatim}\n   FUNPOW\n     |- (!f x. FUNPOW f 0 x = x) /\\\n        (!f n x. FUNPOW f (SUC n) x = FUNPOW f n (f x))\n   FUNPOW_SUC\n     |- !f n x. FUNPOW f (SUC n) x = f (FUNPOW f n x)\n\\end{verbatim}\n\\end{hol}\n\n\\medskip\n\nOn this basis, an \\adhoc\\ but useful collection of over two hundred\nand fifty elementary theorems of arithmetic are proved when \\HOL{} is\nbuilt and stored in the theory \\theoryimp{arithmetic}.  For a complete\nlist of the available theorems, see \\REFERENCE.  See also\nSection~\\ref{sec:while-loops} for discussion of the \\holtxt{LEAST}\noperator, which returns the least number satisfying a predicate.\n\n\\subsubsection{Grammar information}\n\nThe following table gives the parsing status of the arithmetic\nconstants.\n\n\\begin{center}\n{\\small\n\\begin{tabular}{@{}ccc}\nOperator & Strength & Associativity \\\\ \\hline\n\\holtxt{>=} & 450 & non \\\\\n\\holtxt{<=} & 450 & non \\\\\n\\holtxt{>} & 450 & non \\\\\n\\holtxt{<} & 450 & non \\\\\n\\holtxt{+} & 500 & left \\\\\n\\holtxt{-} & 500 & left \\\\\n\\holtxt{*} & 600& left \\\\\n\\holtxt{DIV} & 600 & left \\\\\n\\holtxt{MOD} & 650 & left \\\\\n\\holtxt{EXP} & 700 & right \\\\\n\\end{tabular}}\n\\end{center}\n\n\\subsection{Numerals}\\label{sec:numerals}\n\nThe type \\ml{num}\n\\index{num, the type in \\HOL{} logic@\\ml{num}, the type in \\HOL{} logic}\nis usually thought of as being supplied with an infinite collection of\nnumerals: \\ml{1}, \\ml{2}, \\ml{3}, etc. However, the \\HOL{} logic has\nno way to define such infinite families of constants; instead, all\nnumerals other than $0$ are actually built up from the constants\nintroduced by the following definitions:\n\\begin{verbatim}\n   NUMERAL_DEF |- !x. NUMERAL x = x\n\n   BIT1        |- !n. BIT1 n = n + (n + SUC 0)\n   BIT2        |- !n. BIT2 n = n + (n + SUC(SUC 0))\n\n   ALT_ZERO    |- ZERO = 0\n\\end{verbatim}\n\n\\noindent For example, the numeral $5$ is represented by the term\n\\[\n   \\ml{NUMERAL}(\\ml{BIT1}(\\ml{BIT2}\\;\\ml{ZERO}))\n\\]\nand the \\HOL{} parser and pretty-printer make such terms appear as\nnumerals. This binary representation for numerals allows for\nasymptotically efficient calculation. Theorems supporting arithmetic\ncalculations on numerals can be found in the \\theoryimp{numeral}\ntheory; these are mechanized by the \\verb+reduce+ library. Thus,\narithmetic calculations are performed by deductive steps in \\HOL.  For\nexample the following calculation of $2 ^{(1023 + 14)/9}$ takes\napproximately 4,200 primitive inference steps and returns in 30\nmilli-seconds.\n%\n\\setcounter{sessioncount}{0}\n\\begin{session}\n\\begin{verbatim}\n- reduceLib.REDUCE_CONV ``2 EXP ((1023 + 14) DIV 9)``;\n\n> val it = |- 2 ** ((1023 + 14) DIV 9) = 41538374868278621028243970633760768\n\\end{verbatim}\n\\end{session}\n\n\\paragraph {Construction of numerals}\n\\index{numerals, in HOL logic@numerals, in \\HOL{} logic!construction of}\n\nNumerals may of course be built using \\ml{mk\\_comb}, and taken apart with\n\\ml{dest\\_comb}; however, a more convenient interface to this\nfunctionality is provided by the functions \\ml{mk\\_numeral},\n\\ml{dest\\_numeral}, and \\ml{is\\_numeral} (found in the structure\n\\ml{numSyntax}). These entry-points make use of an \\ML{} structure\n\\ml{Arbnum} which implements arbitrary precision numbers {\\verb+num+}. The\nfollowing session shows how \\HOL{} numerals are constructed from elements of\ntype \\verb+num+ and how numerals are destructed. The structure\n{\\small\\verb+Arbnum+} provides a full collection of arithmetic\noperations, using the usual names for the operations, \\eg \\verb|+|,\n\\verb|*|, \\verb|-|, \\etc\n\n\\begin{session}\n\\begin{verbatim}\n- numSyntax.mk_numeral\n     (Arbnum.fromString \"3432432423423423234\");\n> val it = ``3432432423423423234`` : term\n\n- numSyntax.dest_numeral it;\n> val it = 3432432423423423234 : num\n\n- Arbnum.+(it,it);\n> val it = 6864864846846846468 : num\n\\end{verbatim}\n\\end{session}\n\n\\paragraph{Numerals and the parser}\n%\n\\index{parsing, of HOL logic@parsing, of \\HOL{} logic!of numerals}\n\\index{tokens!parsing numerals}\n\\index{numerals, in HOL logic@numerals, in \\HOL{} logic!parsing}\n%\nSimple digit sequences are parsed as decimal numbers, but the parser\nalso supports the input of numbers in binary, octal and hexadecimal\nnotation.  Numbers may be written in binary and hexadecimal form by\nprefixing them with the strings \\holtxt{0b} and \\holtxt{0x} respectively.  The\n`digits' A--F in hexadecimal numbers may be written in upper or lower\ncase.  Binary numbers have their most significant digits left-most. In\nthe interests of backwards compatibility, octal numbers are not\nenabled by default, but if the reference\n\\ml{base\\_tokens.allow\\_octal\\_input} is set to \\ml{true}, then octal\nnumbers are those that appear with leading zeroes.\n\nFinally, all numbers may be padded with underscore characters\n(\\ml{\\_}).  These can be used to groups digits for added legibility\nand have no semantic effect.\n\nThus\n\\begin{session}\n\\begin{verbatim}\n- ``0xAA``;\n> val it = ``170`` : term\n\n- ``0b1010_1011``;\n> val it = ``171`` : term\n\n- base_tokens.allow_octal_input := true;\n> val it = () : unit\n\n- ``067``;\n> val it = ``55`` : term\n\\end{verbatim}\n\\end{session}\n\n\\paragraph{Numerals and Peano numbers}\n\nNumerals are related to numbers built from \\holtxt{0} and \\holtxt{SUC}\nvia the derived inference rule \\ml{num\\_CONV}, found in the\n\\ml{numLib} library.\n\n\\begin{holboxed}\n\\index{num_CONV@\\ml{num\\_CONV}|pin}\n\\begin{verbatim}\n   num_CONV : term -> thm\n\\end{verbatim}\n\\end{holboxed}\n\n\\noindent \\ml{num\\_CONV} can be used to generate the `\\ml{SUC}'\nequation for any non-zero numeral.  For example:\n\n\\begin{session}\n\\begin{verbatim}\n- load \"numLib\"; open numLib;\n\n- num_CONV ``2``;\n> val it = |- 2 = SUC 1 : thm\n\n- num_CONV ``3141592653``;\n> val it = |- 3141592653 = SUC 3141592652 : thm\n\\end{verbatim}\n\\end{session}\n\n\\noindent The \\ml{num\\_CONV} function works purely by inference.\n\n\\subsubsection{Overloading of arithmetic operators}\n\\label{arith-overloading}\n\nWhen other numeric theories are loaded (such as those for the reals or\nintegers), numerals are overloaded so that the numeral {\\small\\verb+1+} can\nactually stand for a natural number, an integer or a real value. The\nparser has a pass of overloading resolution in which it attempts to\ndetermine the actual type to give to a numeral. For example, in the\nfollowing session, the theory of integers is loaded, whereupon the\nnumeral \\verb+2+ is taken to be an integer.\n%\n\\begin{session}\n\\begin{verbatim}\n- load \"integerTheory\";\n> val it = () : unit\n\n- ``2``;\n<<HOL message: more than one resolution of overloading was possible.>>\n> val it = `2` : term\n\n- type_of it;\n> val it = `:int` : hol_type\n\\end{verbatim}\n\\end{session}\n\n In order to precisely specify the desired type, the user can use single\ncharacter suffixes (`\\ml{n}' for the natural numbers, and `\\ml{i}' for\nthe integers):\n\\begin{session}\n\\begin{verbatim}\n- type_of ``2n``;\n> val it = `:num` : hol_type\n\n- type_of ``42i``;\n> val it = `:int` : hol_type\n\\end{verbatim}\n\\end{session}\n\nA numeric literal for a \\HOL{} type other than \\verb+num+, such as\n\\verb+42i+,  is represented by the application of an\n\\emph{injection} function of type {\\small\\verb+num -> ty+} to a\nnumeral. The injection function is different for each type\n{\\small\\verb+ty+}. See Section \\ref{integers} for further discussion.\n\nThe functions {\\verb+mk_numeral+}, {\\verb+dest_numeral+}, and\n{\\verb+is_numeral+} only work for numerals, and not for numeric\nliterals with character suffixes other than {\\small\\verb+n+}. For\ninformation on how to install new character suffixes, consult the\n\\ml{add\\_numeral\\_form} entry in \\REFERENCE.\n\n\\subsection{Integers}\n\\label{integers}\n\\index{integers, the HOL theory of@integers, the \\HOL{} theory of}\n\nThere is an extensive theory of integers in \\HOL. The type of integers\nis constructed as a quotient on pairs of natural numbers. A standard\ncollection of operators are defined. These are overloaded with\nsimilar operations on the natural numbers, and on the real numbers.\nThe constants defined in the integer theory include those found in the\nfollowing table.\n\n\\begin{center}\n{\\small\n\\begin{tabular}{@{}cccc}\nConstant & Overloaded symbol & Strength & Associativity \\\\ \\hline\n{\\small\\verb+int_ge+} &{\\small\\verb+>=+} & 450 & non \\\\\n{\\small\\verb+int_le+} &{\\small\\verb+<=+} & 450 & non \\\\\n{\\small\\verb+int_gt+} &{\\small\\verb+>+}  & 450 & non \\\\\n{\\small\\verb+int_lt+} &{\\small\\verb+<+}  & 450 & non \\\\\n{\\small\\verb+int_add+} &{\\small\\verb%+%} & 500 & left \\\\\n{\\small\\verb+int_sub+} &{\\small\\verb%-%} & 500 & left \\\\\n{\\small\\verb+int_neg+} &{\\small\\verb%~%} & 900 & trueprefix \\\\\n{\\small\\verb+int_mul+} &{\\small\\verb%*%} & 600 & left \\\\\n{\\small\\verb%/%} & & 600 & left \\\\\n{\\small\\verb+%+} & & 650 & left \\\\\n{\\small\\verb+int_exp+} &{\\small\\verb%**%} & 700 & right \\\\\n{\\small\\verb+int_of_num+} &{\\small\\verb%&%} & & prefix \\\\\n\\end{tabular}}\n\\end{center}\n\nThe overloaded symbol {\\small\\verb+& : num -> int+} denotes the\ninjection function from natural numbers to integers. The following\nsession illustrates how overloading and integers literals are treated.\n\n\\setcounter{sessioncount}{0}\n\\begin{session}\n\\begin{verbatim}\nTerm `1i = &(1n + 0n)`;\n> val it = `1 = & (1 + 0)` : term\n\n- show_numeral_types := true;\n> val it = () : unit\n\n- Term `&1 = &(1n + 0n)`;\n<<HOL message: more than one resolution of overloading was possible.>>\n> val it = `1i = & (1n + 0n)` : Term.term\n\\end{verbatim}\n\\end{session}\n\n\n\\subsection{Rational numbers}\\label{rationals}\n\\index{rational numbers, the HOL theory of@rationals, the \\HOL{} theory of|(}\n\nThe type of rationals is constructed as a quotient on ordered pairs of\nintegers (the numerator and the denominator of a fraction) whose second\ncomponent must not be zero. To make things easier in the \\HOL\\ theory,\nthe sign of a rational number is always moved to the numerator.\nSo, the denominator is always positive.\n\nA standard collection of operators, which are overloaded with similar\noperations on the integers, are defined. These include those found in\nthe following table. Injection from natural numbers is supported\nby the overloaded symbol {\\small\\verb+& : num -> rat+} and the\nsuffix {\\small\\verb+q+}.\n\n\n\\begin{center}\n{\\small\n\\begin{tabular}{@{}cccc}\nConstant & Overloaded symbol & Strength & Associativity \\\\ \\hline\n{\\small\\verb+rat_geq+} &{\\small\\verb+>=+} & 450 & non \\\\\n{\\small\\verb+rat_leq+} &{\\small\\verb+<=+} & 450 & non \\\\\n{\\small\\verb+rat_gre+} &{\\small\\verb+>+}  & 450 & non \\\\\n{\\small\\verb+rat_les+} &{\\small\\verb+<+}  & 450 & non \\\\\n{\\small\\verb+rat_add+} &{\\small\\verb%+%} & 500 & left \\\\\n{\\small\\verb+rat_sub+} &{\\small\\verb%-%} & 500 & left \\\\\n{\\small\\verb+rat_ainv+} &{\\small\\verb%~%} & 900 & trueprefix \\\\\n{\\small\\verb+rat_minv+} & & & \\\\\n{\\small\\verb+rat_mul+} &{\\small\\verb%*%} & 600 & left \\\\\n{\\small\\verb+rat_div+} &{\\small\\verb%/%} & 600 & left \\\\\n{\\small\\verb+rat_of_num+} &{\\small\\verb%&%} & & \\\\\n\\end{tabular}}\n\\end{center}\n\nThe theorems in the theory of rational numbers include field properties,\narithmetic rules, manipulation of (in)equations and their reduction to\n(in)equations between integers, properties of less-than relations and the\ndensity of rational numbers. For details, consult \\REFERENCE\\ and the\nsource files.\n\n\\index{rational numbers, the HOL theory of@rationals, the \\HOL{} theory of|)}\n\n\\subsection{Real numbers}\\label{reals}\n\\index{real numbers, the HOL theory of@real numbers, the \\HOL{} theory of|(}\n\nThere is an extensive collection of theories that make up the\ndevelopment of real numbers and analysis in HOL, due to John Harrison\n\\cite{jrh:thesis}. We will only give a sketchy overview of the\ndevelopment; the interested reader should consult \\REFERENCE\\ and\nHarrison's thesis.\n\nThe axioms for the real numbers are derived from the `half reals' which\nare constructed from the `half rationals'. This part of the development\nis recorded in {\\small\\verb+hratTheory+} and\n{\\small\\verb+hrealTheory+}, but is not used once the reals have been\nconstructed. The real axioms are derived in the theory\n{\\small\\verb+realaxTheory+}. A standard collection of operators on the\nreals, and theorems about them, is found in {\\small\\verb+realaxTheory+}\nand {\\small\\verb+realTheory+}. The operators and their parse status are\nlisted in the following table.\n\n\\begin{center}\n{\\small\n\\begin{tabular}{@{}cccc}\nConstant & Overloaded symbol & Strength & Associativity \\\\ \\hline\n{\\small\\verb+real_ge+} &{\\small\\verb+>=+} & 450 & non \\\\\n{\\small\\verb+real_lte+} &{\\small\\verb+<=+} & 450 & non \\\\\n{\\small\\verb+real_gt+} &{\\small\\verb+>+}  & 450 & non \\\\\n{\\small\\verb+real_lt+} &{\\small\\verb+<+}  & 450 & non \\\\\n{\\small\\verb+real_add+} &{\\small\\verb%+%} & 500 & left \\\\\n{\\small\\verb+real_sub+} &{\\small\\verb%-%} & 500 & left \\\\\n{\\small\\verb+real_neg+} &{\\small\\verb%~%} & 900 & trueprefix \\\\\n{\\small\\verb+real_mul+} &{\\small\\verb%*%} & 600 & left \\\\\n{\\small\\verb+real_div+} & {\\small\\verb%/%} & 600 & left \\\\\n{\\small\\verb+pow+} & &700 & right \\\\\n{\\small\\verb+real_of_num+} &{\\small\\verb%&%} & & prefix \\\\\n\\end{tabular}}\n\\end{center}\n\nOn the basis of {\\small\\verb+realTheory+}, the following  sequence of\ntheories is constructed:\n\n\\begin{description}\n\\item [topology] Topologies and metric spaces, including metric on\nthe real line.\n\\item [nets] Moore-Smith convergence nets, and special cases like\nsequences.\n\\item [seq] Sequences and series of real numbers.\n\\item [lim] Limits, continuity and differentiation.\n\\item [powser] Power series.\n\\item [transc] Transcendental functions, e.g., exp, sin,\ncos, ln, root, sqrt, pi, tan, asn, acs, atn. Also the Kurzweil-Henstock\ngauge integral the fundamental theorem of calculus, and McLaurin's\ntheorem.\n\n\\end{description}\n\\index{real numbers, the HOL theory of@real numbers, the \\HOL{} theory of|)}\n\n\\index{complex numbers, the HOL theory of@complex numbers, the \\HOL{} theory of}\n\\noindent\n\\HOL{} also includes a basic theory of the complex numbers (\\ml{complexTheory}), where the type \\holtxt{complex} is a type abbreviation for a pair of real numbers.\nThe $\\sqrt{-1}$ value is the \\HOL{} constant \\holtxt{i}.\nNumerals are supported (with the suffix \\holtxt{c} available to force numerals to be parsed as complex numbers).\nThe standard arithmetic operations are defined, with the appropriate theorems proved about them.\n\n\\subsection{Probability theory}\\label{prob}\n\\index{probability, the HOL theory of@probability, the \\HOL{} theory of}\n\nA foundational construction of probability theory developed by Joe\nHurd~\\cite{hurd-thesis}. First a type of boolean sequences is defined\nto model an infinite sequence of coin flips. Next a probability\nfunction is formalized which takes as input a set of boolean\nsequences, and returns a real number between 0 and 1. Unfortunately\nnot all sets can be assigned a probability (the Banach-Tarski\nparadox), rather the sets that can be assigned a probability are\ncalled \\emph{measurable sets}, and this is also formalized in the\nHOL theory.\n\nBuilding on this foundation, the probability theory is used to define\na sampling function that takes an infinite sequence of coin flips and\na positive integer $N$, and returns an integer $n$ in the range $0\\le\nn < N$, picked uniformly at random from the available choices. This\nsampling function for the uniform distribution is later used to verify\nthe Miller-Rabin primality test.\n\n\\subsection{Bit vectors}\n\\label{sec:bit-vectors}\n\\index{bit vectors, the HOL theory of@bit vectors, the \\HOL{} theory of|(}\n\n{\n\\newcommand{\\fcp}[2]{\\ty{#1}[\\ty{#2}]}\n\\newcommand{\\worda}{\\fcp{\\bool}{\\ensuremath\\alpha}}\n\\newcommand{\\wordb}{\\fcp{\\bool}{\\ensuremath\\beta}}\n\\newcommand{\\wordc}{\\fcp{\\bool}{\\ensuremath\\gamma}}\n\\newcommand{\\rarr}{\\ensuremath\\rightarrow}\n\\newcommand{\\hash}{\\,\\holtxt{\\#}\\,}\n\\newcommand{\\oo}[2]{\\mbox{\\holtxt{#1\\,'\\,#2}}}\n\n\\HOL{} provides a theory of bit vectors, or $n$-bit words.  For example, in computer architectures one finds:\nbytes/octets ($n = 8$), half-words ($n = 16$), words ($n = 32$) and long-words\n($n = 64$).  In the theory \\theoryimp{words}, bit vectors are represented as\n\\emph{finite Cartesian products}: an $n$-bit word is given type $\\worda$\nwhere the \\emph{size} of the type $\\alpha$ determines the word length $n$.    This\napproach comes from an idea of John Harrison, which was presented at TPHOLs\n2005.\\footnote{The current theory subsumes previous word theories -- it evolved from a development based on an equivalence class construction.  Wai Wong's word theory, which was based on Paul Curzon's \\ml{rich\\_list} theory, is no longer distributed with HOL.  The principle advantages of the current theory are that there is just one theory for all word sizes and that word length side conditions are not required.}\n\n\\subsubsection{Finite Cartesian products}\n\nThe \\HOL{} theory \\theoryimp{fcp} introduces an infix type operator\n\\holtxt{**}, which is used to represent finite Cartesian products.\\footnote{The theory of\nfinite Cartesian products was ported from HOL Light.}  The type \\holtxt{'a ** 'b}, or equivalently \\fcp{'a}{'b}, is conceptually equivalent to:\n\\begin{hol}\n$\\underbrace{\\ty{'a}\\;\\hash\\;\\ty{'a}\\;\\hash\\;\\cdots\\;\\hash\\;\\ty{'a}}_{\\holtxt{dimindex('b)}}$\n\\end{hol}\nwhere \\holtxt{dimindex('b)} is the cardinality of \\holtxt{univ(:'b)} when \\ty{'b} is finite and is one when it is infinite.  Thus, \\fcp{'a}{\\num} is similar to \\ty{'a}, and \\fcp{'a}{\\bool} is similar to \\ty{'a}\\hash\\ty{'a}.  Numeral type names are supported, so one can freely work with indexing sets of any size, \\eg{} the type \\ty{32} has thirty-two elements and \\fcp{\\bool}{32} represents 32-bit words.\n\nThe \\emph{components} of a finite Cartesian product are accessed with an\nindexing function\n\\begin{hol}\n\\begin{alltt}\n   fcp_index : \\fcp{'a}{'b}\\rarr\\num\\rarr\\ty{'a}\n\\end{alltt}\n\\end{hol}\nwhich is typically written with an infixed apostrophe:\n\\oo{x}{i} denotes the value of vector \\holtxt{x} at position \\holtxt{i}.\nTypically, indices are constrained to be less than the size of \\ty{'b}.\n\nThe following theorem shows that two Cartesian products \\holtxt{x} and\n\\holtxt{y} are equal if, and only if, all of their components \\oo{x}{i} and\n\\oo{y}{i} are equal:\n\\begin{hol}\n\\begin{verbatim}\nCART_EQ: |- !x y. (x = y) = !i. i < dimindex (:'a) ==> (x ' i = y ' i)\n\\end{verbatim}\n\\end{hol}\n\nIn order to construct Cartesian products, the theory \\theoryimp{fcp} introduces a\nbinder \\holtxt{FCP}, which is characterised by the following theorems:\n\\begin{hol}\n\\begin{verbatim}\nFCP_BETA: |- !i. i < dimindex (:'a) ==> ($FCP g ' i = g i)\nFCP_ETA:  |- !x. (FCP i. x ' i) = x\n\\end{verbatim}\n\\end{hol}\nThe theorem \\ml{FCP\\_BETA} shows that the components of \\holtxt{\\$FCP g} are\ndetermined by the function \\holtxt{g:\\num\\rarr\\ty{'a}}.  The theorem\n\\ml{FCP\\_ETA} shows that a binding can be eliminated when all of the components\nare identical to that of \\holtxt{x}.\nThese two theorems, together with \\ml{CART\\_EQ}, can be found in the\n\\emph{simpset} fragment \\ml{fcpLib.FCP\\_ss}.\n\nFinite Cartesian products provide a good means to model $n$-bit words.  That is\nto say, the type \\fcp{bool}{'a} can represent a binary word whose length $n$\ncorresponds with the size of the type \\ty{'a}.  The binder \\holtxt{FCP}\nprovides a flexible means for defining words -- one can supply a function\n\\holtxt{f:\\num\\rarr\\bool} that gives the word's bit values, each of which can be accessed using the indexing map \\holtxt{fcp\\_index}.\n\n\\subsubsection{Bit theory}\n\nThe theory \\theoryimp{bit} defines some bit operations over the natural numbers,\ne.g.\\ \\holtxt{BITS}, \\holtxt{SLICE}, \\holtxt{BIT}, \\holtxt{BITWISE} and\n\\holtxt{BIT\\_MODIFY}. In this context, natural numbers are treated as binary words of\nunbounded length.  The operations in \\theoryimp{bit} are primarily defined using \\holtxt{DIV}, \\holtxt{MOD} and \\holtxt{EXP}.  For example, from the definition of \\holtxt{BIT}, the following theorem holds:\n\\begin{hol}\n\\begin{verbatim}\n|- !b n. BIT b n = ((n DIV 2 ** b) MOD 2 = 1)\n\\end{verbatim}\n\\end{hol}\n\nThis theory is used in the development of the word theory and it also provides\na mechanism for the efficient evaluation of some word operations via the theory\n\\theoryimp{numeral\\_bit}.\n\n\\subsubsection{Words theory}\n\nThe theory \\theoryimp{words} introduces a selection of polymorphic constants and operations, which can be type instantiated to any word size.  For example, word addition\nhas type:\n\\begin{hol}\n+:\\worda\\rarr\\worda\\rarr\\worda\n\\end{hol}\nIf \\ty{'a} is instantiated to \\ty{32} then this operation corresponds with 32-bit addition.\nAll theorems about word operations apply for any word length.\\footnote{Note\nthat it is impossible to introduce words of length zero because all types\nmust be inhabited, and hence their size will always be greater than or equal to\none.}\n\n\\paragraph{Some basic operations}\n\nThe function \\holtxt{w2n:\\worda\\rarr\\num} gives the natural number value of a\nword.  If $x\\in\\bools^{\\{0, 1, \\ldots, n - 1\\}}$ is a finite Cartesian product\nrepresenting an $n$-bit word then its natural number value is:\n\\[ \\mathrm{w2n}(x) = \\sum_{i = 0}^{n - 1} \\textbf{if } x_i \\textbf{ then } 2^i\n\\textbf{ else } 0\\ .\\]\nThe length of a word (the number $n$) is given by the function\n\\holtxt{word\\_len:\\worda\\rarr\\num}.\nThe function \\holtxt{n2w:\\num\\rarr\\worda} maps from a number to a word and is\ndefined in \\HOL{} by:\n\\begin{hol}\n\\begin{verbatim}\n|- !n. n2w n = FCP i. BIT i n\n\\end{verbatim}\n\\end{hol}\nThe suffix \\holtxt{w} is used to denote word literals, \\eg{}\n\\holtxt{255w} is the same as \\holtxt{n2w 255}.\n\nThe function \\holtxt{w2w:\\worda\\rarr\\wordb} provides word-to-word conversion (casting):\n\\begin{hol}\n\\begin{verbatim}\n|- !w. w2w w = n2w (w2n w)\n\\end{verbatim}\n\\end{hol}\nIf $\\beta$ is smaller than $\\alpha$ then the higher bits of \\holtxt{w} will be\nlost (it performs bit extraction), otherwise the longer word will have the same value as the original (in effect providing zero padding).\nHowever, if one were treating \\holtxt{w} as a two's complement number then the\nword needs to be sign extended, \\ie{}\n\\begin{eqnarray*}\n\\mbox{\\small ($-$ve)}\\quad 1b_{n-2} \\cdots b_0\\ \\mapsto \\ 1 \\cdots 1 1 b_{n-2}\n\\cdots b_0 \\\\\n\\mbox{\\small ($+$ve)}\\quad 0b_{n-2} \\cdots b_0\\ \\mapsto \\ 0 \\cdots 0 0 b_{n-2}\n\\cdots b_0\n\\end{eqnarray*}\nThe function \\holtxt{sw2sw:\\worda\\rarr\\wordb} provides this sign extending version of\n\\holtxt{w2w}.\n\nA collection of operations are provided for mapping to and from strings and number (digit) lists, \\eg{}\n\\begin{hol}\n\\begin{verbatim}\n|- word_to_dec_string 876w = \"876\"\n\\end{verbatim}\n\\end{hol}\nand\n\\begin{hol}\n\\begin{verbatim}\n|- word_to_hex_list 876w = [12; 6; 3]\n\\end{verbatim}\n\\end{hol}\nThese function are specialised versions of \\holtxt{w2s} and \\holtxt{w2l} respectively.\n\n\\paragraph{Concatenation}\n\nThe operation \\holtxt{word\\_concat:\\worda\\rarr\\wordb\\rarr\\wordc} concatenates words.  Note that the return type is not constrained.  This means that two sixteen bit words can be concatenated to give a word of any length -- which may be smaller or larger than the expect value of 32.   The related function \\holtxt{word\\_join} does return a word of the expected length, \\ie{} of type \\fcp{\\bool}{$\\alpha+\\beta$};  however, the concatenation operation is more useful because we often want \\fcp{\\bool}{\\ty{32}} and not the logically distinct \\fcp{\\bool}{\\ty{16}+\\ty{16}}.\n\n\\paragraph{Signed and unsigned words}\n\nWords can be \\emph{viewed} as being either signed (using the two's\ncomplement representation) or as being unsigned.  However, this is not\nmade explicit within the theory\\footnote{Words are not tagged as being\n  signed/unsigned.  Mappings to/from the integers (\\holtxt{w2i} and\n  \\holtxt{i2w}) are provided in the theory \\theoryimp{integer\\_word}.}\nand all of the arithmetic operations are defined using the natural\nnumbers, \\ie{} via \\holtxt{w2n} and \\holtxt{n2w}.  In particular,\naddition and multiplication work naturally (have the same definition)\nunder the two's complement representation.  This is not the case\nhowever with word-to-word conversion, orderings, division and right\nshifting, where signed and unsigned variants are needed.  When\noperating over the natural numbers, some of the two's complement\nversions have slightly unnatural looking presentations.  For example,\nwith the signed (two's complement) version of ``less than'' we have\n\\holtxt{255w < (0w:word8)} because the word \\holtxt{255w} is actually\ntaken to be representing the integer $-1$, whereas the unsigned\nversion is more natural: \\holtxt{0w <+ (255w:word8)}.\n\n\\paragraph{Bit field operations}\n\nThe standard Boolean bit field operations are provided, \\ie{} bitwise negation\n(one's complement), conjunction, disjunction and exclusive-or.  These functions\nare defined quite naturally using the Cartesian product binder; for example,\nbitwise conjunction is defined by:\n\\begin{hol}\n\\begin{verbatim}\n|- !v w. v && w = FCP i. v ' i /\\ w ' i .\n\\end{verbatim}\n\\end{hol}\nThere is also a collection of word \\emph{reduction} operations, which reduce bit vectors to 1-bit words, e.g.\n\\[ \\mathrm{reduce\\_and}(x)\\;'\\; 0= \\bigwedge_{i = 0}^{n - 1} x_i\\ .\\]\n\nThe functions \\holtxt{word\\_lsb}, \\holtxt{word\\_msb} and \\holtxt{word\\_bit(i)}\ngive the bit value of a word at positions $0$, $n - 1$ and $i$\nrespectively.  Four operations are provided for selecting bit\nfields, or sub-words: \\holtxt{word\\_bits} (\\holtxt{--}),  \\holtxt{word\\_signed\\_bits} (\\holtxt{---}), \\holtxt{word\\_slice} (\\holtxt{''}) and\n\\holtxt{word\\_extract} (\\holtxt{><}).  For example, \\holtxt{word\\_bits 4 1} will select four bits starting from bit position 1.  The slice function is an in-place variant (it zeroes bits outside of the bit range) and the extract function combines \\holtxt{word\\_bits} with a word cast (\\holtxt{w2w}).  The operation \\holtxt{word\\_signed\\_bits} is similar to \\holtxt{word\\_bits}, except that it sign-extends the bit field.\n\nThe \\holtxt{bit\\_field\\_insert} operation inserts a bit field.  For example,\n\\begin{hol}\n\\begin{verbatim}\nbit_field_insert 5 2 a b\n\\end{verbatim}\n\\end{hol}\nis word \\holtxt{b} with bits 5--2 replaced by bits 3--0 of \\holtxt{a}.\n\nA word's bit ordering can be flipped over with \\holtxt{word\\_reverse}, \\ie{} bit zero is swapped with bit $n - 1$ and so forth.\n\nThe function\n\\holtxt{word\\_modify:(\\num\\,\\rarr\\,\\bool\\,\\rarr\\,\\bool)\\,\\rarr\\,\\worda\\,\\rarr\\,\\worda} changes\na word by applying a map at each bit position.\nThis operation provides a very flexible and convenient mechanism for\nmanipulating words, \\eg{}\n\\begin{hol}\n\\holtxt{word\\_modify ($\\lambda$i b.\\,if EVEN i then $\\sim$b else b) w}\n\\end{hol}\nnegates the bits of \\holtxt{w} that are in even positions.  Of course, the\nbinder \\holtxt{FCP} also provides a very general means to represent words using\na predicate \\eg{} \\holtxt{\\$FCP ODD} represents a word where all the odd bits\nare set.\n\n\\paragraph{Shifts}\n\nSix types of shifts are provided: logical shift left/right (\\holtxt{<<} and\n\\holtxt{>>>}), arithmetic shift right (\\holtxt{>>}), rotate left/right\n(\\holtxt{\\#<<} and \\holtxt{\\#>>}) and rotate right extended by 1 place\n(\\holtxt{word\\_rrx}).  These shifts are illustrated in Figure~\\ref{fig:shifts} and are defined in a similar manner to the other bit field operations.  For\nexample, rotating right is defined by:\n\\begin{hol}\n\\begin{verbatim}\n|- !w n. w #>> x = FCP i. w ' (i + x) MOD dimindex (:'a) .\n\\end{verbatim}\n\\end{hol}\nRotating left by $x$ places is defined as rotating right by $n - x \\bmod n$\nplaces.\n\n\\begin{figure}\n\\begin{center}\n\\small\n\\begin{tabular}{ll}\n\\scalebox{.8}{\\includegraphics{figs/lsl}} &\n\\scalebox{.8}{\\includegraphics{figs/lsr}} \\\\\n(a) Logical shift left: \\holtxt{w = v << x}. & (b) Logical shift right:\n\\holtxt{w = v >>> x}. \\\\[12pt]\n\\scalebox{.8}{\\includegraphics{figs/asr}} &\n\\hspace{-5mm}\\scalebox{.8}{\\includegraphics{figs/ror}} \\\\\n(c) Arithmetic shift right: \\holtxt{w = v >> x}. & (d) Rotate right: \\holtxt{w\n= v \\#>> x}. \\\\[12pt]\n\\multicolumn{2}{c}{\\scalebox{.8}{\\includegraphics{figs/rrx}}} \\\\\n\\multicolumn{2}{c}{(e) Rotate right extended by 1 place: \\holtxt{(d,w) =\nword\\_rrx (c,v)}.}\n\\end{tabular}\n\\caption{Shift operations.}\n\\label{fig:shifts}\n\\end{center}\n\\end{figure}\n\n\\paragraph{Arithmetic and orderings}\n\nThe arithmetic operations are: addition, subtraction, unary minus (two's\ncomplement), logarithm (base-2), multiplication, modulus and division (signed and\nunsigned).\nThese operations are defined with respect to the natural numbers.  For example,\nword addition is defined by:\n\\begin{hol}\n\\begin{verbatim}\n|- !v w. v + w = n2w (w2n v + w2n w)\n\\end{verbatim}\n\\end{hol}\nThe \\holtxt{+} on the left-hand side is word addition and on the right it is\nnatural number addition.\n\nAll of the standard word orderings are provided, with signed and unsigned\nversions of $<$, $\\leq$, $>$ and $\\geq$.  The unsigned versions are suffixed\nwith a plus; for example, \\holtxt{<+} is unsigned ``less than''.\n\n\\paragraph{Constants}\n\nThe word theory also defines a few word constants:\n\\begin{center}\\small\n\\begin{tabular}{lll}\n\\multicolumn{1}{l}{Constant} & \\multicolumn{1}{l}{Value}  &\n\\multicolumn{1}{l}{Binary} \\\\\n\\noalign{\\smallskip}\n\\hline\n\\noalign{\\smallskip}\n\\holtxt{word\\_T} or \\holtxt{UINT\\_MAXw} & $2^l - 1$ & $11\\cdots 11$ \\\\\n\\holtxt{word\\_L} or \\holtxt{INT\\_MINw} & $2^{l - 1}$ & $10\\cdots 00$ \\\\\n\\holtxt{word\\_H} or \\holtxt{INT\\_MAXw} & $2^{l - 1} - 1$ & $01\\cdots 11$\n\\end{tabular}\n\\end{center}\n\n\\paragraph{List of bit vector operations}\n\nA list of operations is provided in the table below.\n{\n\\setlength{\\tabcolsep}{4pt}\n\\begin{center}\n\\tablefirsthead{%\n\\hline\n\\multicolumn{1}{|c}{Operation\\rule{0pt}{14pt}} &\n\\multicolumn{1}{c}{Symbol} &\nType &\n\\multicolumn{1}{c|}{Description} \\\\[4pt]\n\\hline}\n\\tablehead{%\n\\hline\n\\multicolumn{4}{|l|}{\\small\\sl continued from previous page}\\\\\n\\hline\n\\multicolumn{1}{|c}{Operation\\rule{0pt}{14pt}} &\n\\multicolumn{1}{c}{Symbol} &\nType &\n\\multicolumn{1}{c|}{Description} \\\\[4pt]\n\\hline}\n\\tabletail{%\n\\hline\n\\multicolumn{4}{|r|}{\\small\\sl continued on next page}\\\\\n\\hline}\n\\tablelasttail{\\hline}\n\\small\n\\begin{supertabular}{|l|c|l|l|}\n\\holtxt{n2w} & & \\num\\rarr\\worda & Map from a natural number \\\\\n\\holtxt{w2n} & & \\worda\\rarr\\num & Map to a natural number \\\\\n\\holtxt{w2w} & & \\worda\\rarr\\wordb & Map word-to-word (unsigned) \\\\\n\\holtxt{sw2sw} & & \\worda\\rarr\\wordb & Map word-to-word (signed) \\\\\n\\holtxt{w2l} & & \\num\\rarr\\worda\\rarr\\num~\\ty{list} & Map word to digit list \\\\\n\\holtxt{l2w} & & \\num\\rarr\\num~\\ty{list}\\rarr\\worda & Map digit list to word \\\\\n\\holtxt{w2s} & & \\num\\rarr(\\num\\rarr\\ty{char})\\rarr\\worda\\rarr\\ty{string} & Map word to string \\\\\n\\holtxt{s2w} & & \\num\\rarr(\\ty{char}\\rarr\\num)\\rarr\\ty{string}\\rarr\\worda & Map string to word \\\\\n\\holtxt{word\\_len} & & \\worda\\rarr\\num & The word length \\\\\n\\holtxt{word\\_lsb} & & \\worda\\rarr\\bool & The least significant bit \\\\\n\\holtxt{word\\_msb} & & \\worda\\rarr\\bool & The most significant bit \\\\\n\\holtxt{word\\_bit} & & \\num\\rarr\\worda\\rarr\\bool & Test bit position \\\\\n\\holtxt{word\\_bits} & \\holtxt{--} & \\num\\rarr\\num\\rarr\\worda\\rarr\\worda & Select a bit field \\\\\n\\holtxt{word\\_signed\\_bits} & \\holtxt{---} & \\num\\rarr\\num\\rarr\\worda\\rarr\\worda & Sign-extend selected bit field \\\\\n\\holtxt{word\\_slice} & \\holtxt{''} & \\num\\rarr\\num\\rarr\\worda\\rarr\\worda &  Set bits outside field to zero \\\\\n\\holtxt{word\\_extract} & \\holtxt{><} & \\num\\rarr\\num\\rarr\\worda\\rarr\\wordb & Extract (cast) a bit field \\\\\n\\holtxt{word\\_reverse} & & \\worda\\rarr\\worda & Reverse the bit order \\\\\n\\holtxt{bit\\_field\\_insert} & & {\\setlength{\\tabcolsep}{0pt}\\begin{tabular}[t]{ll}\\num\\rarr\\num\\rarr\\worda\\rarr\\\\\\wordb\\rarr\\wordb\\end{tabular}} & Insert a bit field \\\\\n\\holtxt{word\\_modify} & & {\\setlength{\\tabcolsep}{0pt}\\begin{tabular}[t]{ll}(\\num\\rarr\\bool\\rarr\\bool)\\rarr\\\\\\worda\\rarr\\worda\\end{tabular}} & Apply a function to each bit \\\\\n\\holtxt{word\\_join} & & \\worda\\rarr\\wordb\\rarr\\fcp{\\bool}{$\\alpha+\\beta$} & Join words \\\\\n\\holtxt{word\\_concat} & \\holtxt{@@} & \\worda\\rarr\\wordb\\rarr\\wordc & Concatenate words \\\\\n\\holtxt{concat\\_word\\_list} & & \\worda~\\ty{list}\\rarr\\wordb & Concatenate list of words \\\\\n\\holtxt{word\\_replicate} & & \\num\\rarr\\worda\\rarr\\wordb & Replicate word \\\\\n\\holtxt{word\\_or} & \\holtxt{||} & \\worda\\rarr\\worda\\rarr\\worda & Bitwise disjunction \\\\\n\\holtxt{word\\_xor} & \\holtxt{??} & \\worda\\rarr\\worda\\rarr\\worda & Bitwise exclusive-or \\\\\n\\holtxt{word\\_and} & \\holtxt{\\&\\&} & \\worda\\rarr\\worda\\rarr\\worda & Bitwise conjunction \\\\\n\\holtxt{word\\_nor} & \\holtxt{\\~{}||} & \\worda\\rarr\\worda\\rarr\\worda & Bitwise NOR \\\\\n\\holtxt{word\\_xnor} & \\holtxt{\\~{}??} & \\worda\\rarr\\worda\\rarr\\worda & Bitwise XNOR \\\\\n\\holtxt{word\\_nand} & \\holtxt{\\~{}\\&\\&} & \\worda\\rarr\\worda\\rarr\\worda & Bitwise NAND \\\\\n\\holtxt{word\\_reduce} & & {\\setlength{\\tabcolsep}{0pt}\\begin{tabular}[t]{ll}(\\bool\\rarr\\bool\\rarr\\bool)\\rarr\\\\\\worda\\rarr\\fcp{\\bool}{1}\\end{tabular}} & Word reduction \\\\\n\\holtxt{reduce\\_or} & & \\worda\\rarr\\fcp{\\bool}{1} & Disjunction reduction \\\\\n\\holtxt{reduce\\_xor} & & \\worda\\rarr\\fcp{\\bool}{1} & Exclusive-or reduction \\\\\n\\holtxt{reduce\\_and} & & \\worda\\rarr\\fcp{\\bool}{1} & Conjunction reduction \\\\\n\\holtxt{reduce\\_nor} & & \\worda\\rarr\\fcp{\\bool}{1} & NOR reduction \\\\\n\\holtxt{reduce\\_xnor} & & \\worda\\rarr\\fcp{\\bool}{1} & XNOR reduction \\\\\n\\holtxt{reduce\\_nand} & & \\worda\\rarr\\fcp{\\bool}{1} & NAND reduction \\\\\n\\holtxt{word\\_{}1comp} & \\holtxt{\\~} & \\worda\\rarr\\worda & One's complement \\\\\n\\holtxt{word\\_{}2comp} & \\holtxt{-} & \\worda\\rarr\\worda & Two's complement \\\\\n\\holtxt{word\\_add} & \\holtxt{+} & \\worda\\rarr\\worda\\rarr\\worda & Addition \\\\\n\\holtxt{word\\_sub} & \\holtxt{-} & \\worda\\rarr\\worda\\rarr\\worda & Subtraction \\\\\n\\holtxt{word\\_mul} & \\holtxt{*} & \\worda\\rarr\\worda\\rarr\\worda & Multiplication \\\\\n\\holtxt{word\\_div} & \\holtxt{//} & \\worda\\rarr\\worda\\rarr\\worda & Division (unsigned) \\\\\n\\holtxt{word\\_sdiv} & \\holtxt{/} & \\worda\\rarr\\worda\\rarr\\worda & Division (signed) \\\\\n\\holtxt{word\\_mod} & & \\worda\\rarr\\worda\\rarr\\worda & Modulus \\\\\n\\holtxt{word\\_log2} & & \\worda\\rarr\\worda & Logarithm base-2 \\\\\n\\holtxt{word\\_lsl} & \\holtxt{<<} & \\worda\\rarr\\num\\rarr\\worda & Logical shift left \\\\\n\\holtxt{word\\_lsr} & \\holtxt{>>>} & \\worda\\rarr\\num\\rarr\\worda & Logical shift right \\\\\n\\holtxt{word\\_asr} & \\holtxt{>>} & \\worda\\rarr\\num\\rarr\\worda & Arithmetic shift right \\\\\n\\holtxt{word\\_ror} & \\holtxt{\\#>>} & \\worda\\rarr\\num\\rarr\\worda & Rotate right \\\\\n\\holtxt{word\\_rol} & \\holtxt{\\#<<} & \\worda\\rarr\\num\\rarr\\worda & Rotate left \\\\\n\\holtxt{word\\_rrx} & & \\bool\\#\\worda\\rarr\\bool\\#\\worda & Rotate right extended by 1 place \\\\\n\\holtxt{word\\_lt} & \\holtxt{<} & \\worda\\rarr\\worda\\rarr\\bool & Signed ``less than'' \\\\\n\\holtxt{word\\_le} & \\holtxt{<=} & \\worda\\rarr\\worda\\rarr\\bool & Signed ``less than or equal'' \\\\\n\\holtxt{word\\_gt} & \\holtxt{>} & \\worda\\rarr\\worda\\rarr\\bool & Signed ``greater than'' \\\\\n\\holtxt{word\\_ge} & \\holtxt{>=} & \\worda\\rarr\\worda\\rarr\\bool & Signed ``greater than or equal'' \\\\\n\\holtxt{word\\_lo} & \\holtxt{<+} & \\worda\\rarr\\worda\\rarr\\bool & Unsigned ``less than''  \\\\\n\\holtxt{word\\_ls} & \\holtxt{<=+} & \\worda\\rarr\\worda\\rarr\\bool & Unsigned ``less than or equal'' \\\\\n\\holtxt{word\\_hi} & \\holtxt{>+} & \\worda\\rarr\\worda\\rarr\\bool & Unsigned ``greater than'' \\\\\n\\holtxt{word\\_hs} & \\holtxt{>=+} & \\worda\\rarr\\worda\\rarr\\bool & Unsigned ``greater than or equal'' \\\\\n\\end{supertabular}\n\\end{center}}\n\n\\index{bit vectors, the HOL theory of@bit vectors, the \\HOL{} theory of|)}\n} % matches bracket at beginning of n-bit section, where some n-bit\n  % specific macros are defined\n\n\\section{Sequences}\n\n\\HOL{} provides theories for various kinds of sequences: finite lists, lazy lists,\npaths, and finite strings.\n\n\\subsection{Lists}\\label{sec:list}\n\\index{list, the type operator in HOL logic@\\ml{list}, the type operator in \\HOL{} logic}\n\\index{types, in HOL logic@types, in \\HOL{} logic!tools for construction of}\n\\index{lists, the HOL theory of@lists, the \\HOL{} theory of|(}\n\\index{ lists, the HOL theory of@\\ml{[} $\\cdots$ \\ml{;} $\\cdots$ \\ml{]} (lists, the \\HOL{} theory of)|(}\n\n\\HOL{} lists are inductively defined finite sequences where each\nelement in a list has the same type. The theory \\ml{list} introduces\nthe unary type operator $\\alpha \\; \\konst{list}$ by a type definition\nand a standard collection of list processing functions are\ndefined. The primitive constructors {\\small\\verb+NIL+} and {\\small\\verb+CONS+}\n%\n\\begin{hol}\n\\index{NIL, the HOL constant@\\holtxt{NIL}, the \\HOL{} constant}\n\\index{CONS, the HOL constant@\\holtxt{CONS}, the \\HOL{} constant}\n\\begin{verbatim}\n   NIL  : 'a list\n   CONS : 'a -> 'a list -> 'a list\n\\end{verbatim}\n\\end{hol}\n%\nare used to build lists and have been defined from the representing type for\nlists. The \\HOL{} parser\n%\n\\index{parsing, of HOL logic@parsing, of \\HOL{} logic!of list expressions}\n%\nhas been specially modified to parse the expression \\holtxt{[]} into\n\\holtxt{NIL}, to parse the expression \\holtxt{h::t} into \\holtxt{CONS\n  h t}, and to parse the expression \\holtxt{[$t_1$;$t_2$;\\dots;$t_n$]}\ninto \\holtxt{CONS $t_1$ (CONS $t_2$ $\\cdots$ (CONS $t_n$ NIL)\n  $\\cdots$)}.  The \\HOL{} printer\n%\n\\index{printing, in HOL logic@printing, in \\HOL{} logic!of list expressions}\n%\nreverses these transformations.\n\n\\index{list theorems, in HOL logic@list theorems, in \\HOL{} logic}\nBased on the inductive characterization of the type, the following\nfundamental theorems about lists are proved and stored in the theory\n\\ml{list}.\n\n\\begin{hol}\n\\index{list_Axiom@\\ml{list\\_Axiom}}\n\\index{axioms!non-primitive, of HOL logic@non-primitive, of \\HOL{} logic!for lists}\n\\index{induction theorems, in HOL logic@induction theorems, in \\HOL{} logic!for lists}\n\\index{characterizing theorem!for lists}\n\\begin{verbatim}\n   list_Axiom\n     |- !x f. ?fn. (fn [] = x) /\\ (!h t. fn (h::t) = f(fn t)h t)\n   list_INDUCT\n     |- !P. P [] /\\ (!t. P t ==> (!h. P(h::t))) ==> (!l. P l)\n   list_CASES\n     |- !l. (l = []) \\/ (?t h. l = h::t)\n   CONS_11\n     |- !h t h' t'. (h::t = h'::t') = (h = h') /\\ (t = t')\n   NOT_NIL_CONS\n     |- !h t. ~([] = h::t)\n   NOT_CONS_NIL\n     |- !h t. ~(h::t = [])\n\\end{verbatim}\n\\end{hol}\n\nThe theorem \\ml{list\\_Axiom} shown above is analogous to the primitive\nrecursion theorem\n%\n\\index{primitive recursion theorem!for lists}\n%\non the natural numbers discussed above in Section~\\ref{num-prim-rec}.\nIt states the validity of primitive recursive definitions on lists,\nand can be used to justify any such definition.  The \\ML{} function\n\\ml{new\\_recursive\\_definition} uses this theorem to do\nautomatic\n%\n\\index{primitive recursion theorem!automated use of, in HOL system@automated use of, in \\HOL{} system|)}\n%\nproofs of the existence of primitive recursive functions on lists and\nthen make constant specifications to introduce constants that denote\nsuch functions.\n\nThe induction theorem for lists, \\ml{list\\_INDUCT}, provides the main\nproof tool used to reason about operations that manipulate lists. The\ntheorem \\ml{list\\_CASES} is used to perform case analysis on whether a\nlist is empty or not.\n\nThe theorem {\\small\\verb+CONS_11+} shows that {\\small\\verb+CONS+} is injective;\nthe theorems {\\small\\verb+NOT_NIL_CONS+} and {\\small\\verb+NOT_CONS_NIL+} show that\n{\\small\\verb+NIL+} and {\\small\\verb+CONS+} are distinct, \\ie,\ncannot give rise to the same structure. Together, these three theorems\nare used for equational reasoning about lists.\n\nThe predicate \\ml{NULL} and the selectors\n%\n\\index{selectors, in HOL logic@selectors, in \\HOL{} logic!for lists}\n%\n\\ml{HD} and \\ml{TL} are defined in the theory \\theoryimp{list} by\n%\n\\begin{hol}\n\\index{NULL, the HOL constant@\\ml{NULL}, the \\HOL{} constant}\n\\index{HD, the HOL constant@\\ml{HD}, the \\HOL{} constant}\n\\index{TL, the HOL constant@\\ml{TL}, the \\HOL{} constant}\n\\begin{verbatim}\n   NULL |- NULL [] /\\ (!h t. ~NULL(h::t))\n   HD   |- !h t. HD(h::t) = h\n   TL   |- !h t. TL(h::t) = t\n\\end{verbatim}\n\\end{hol}\n\n\\noindent The following functions on lists are also defined in the theory \\ml{list}.\n%\n%\n\\paragraph{Case expressions}\n\\index{case expressions!over lists}\n\nCompound \\HOL{} expressions that branch based on whether a term is an\nempty or non-empty list have the surface syntax (roughly borrowed from\nML)\n\\begin{hol}\n\\begin{verbatim}\n   case e1\n    of [] => e2\n     | (h::t) => e3\n\\end{verbatim}\n\\end{hol}\n%\nSuch an expression is translated to\n$\\holtxt{list\\_CASE}\\ e_1\\ e_2\\ (\\lambda h\\; t.\\ e_3)$ where the constant\n\\holtxt{list\\_CASE} is defined as follows:\n\\begin{hol}\n\\begin{verbatim}\n   list_case_def\n     |- (!v f. list_CASE [] v f = v) /\\\n        (!v f a0 a1. list_CASE (a0::a1) v f = f a0 a1)\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph{List membership}\n\\index{MEM, the HOL constant@\\ml{MEM}, the \\HOL{} constant}\n\nMembership in a list, \\ml{MEM}, is defined as follows:\n%\n\\begin{hol}\n\\begin{verbatim}\n   MEM |- (!x. MEM x [] = F) /\\\n          (!x h t. MEM x (h::t) = (x = h) \\/ MEM x t)\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph {Concatenation of lists}\n\\index{APPEND, the HOL constant@\\ml{APPEND}, the \\HOL{} constant}\n\\index{concatenation, of lists!in HOL logic@in \\HOL{} logic}\n\\index{FLAT, the HOL constant@\\ml{FLAT}, the \\HOL{} constant}\n\nBinary list concatenation ({\\small\\verb+APPEND+}) may also be denoted by\nthe infix operator {\\small\\verb|++|}; thus the expression\n{\\small\\verb|L1 ++ L2|} is translated into {\\small\\verb+APPEND L1 L2+}.\nThe concatenation of a list of lists into a list is achieved by\n{\\small\\verb+FLAT+}.\n%\n\\begin{hol}\n\\begin{verbatim}\n   APPEND\n     |- (!l. APPEND [] l = l) /\\\n        (!l1 l2 h. APPEND (h::l1) l2 = h::APPEND l1 l2)\n   FLAT\n     |- (FLAT [] = []) /\\ (!h t. FLAT(h::t) = h ++ FLAT t)\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph {Numbers and lists}\n\\index{LENGTH, the HOL constant@\\ml{LENGTH}, the \\HOL{} constant}\n\\index{EL, the HOL constant@\\ml{EL}, the \\HOL{} constant}\n\\index{list_size, the HOL constant@\\ml{list\\_size}, the \\HOL{} constant}\n\nThe length (\\holtxt{LENGTH}) and size (\\holtxt{list\\_size}) of a list\nare related notions. The size of a list takes account of the size of\neach element of the list (given by parameter\n$f:\\alpha\\to\\konst{num}$), while the length of the list ignores the\nsize of each list element. The alternate length definition\n(\\holtxt{LEN}) is tail-recursive.  Numbers can also be used to index\ninto lists, extracting the element at the specified position.\n%\n\\begin{hol}\n\\begin{verbatim}\n   LENGTH\n     |- (LENGTH [] = 0) /\\ (!h t. LENGTH (h::t) = SUC(LENGTH t))\n   LEN_DEF\n     |- (!n. LEN [] n = n) /\\ !h t n. LEN (h::t) n = LEN t (n + 1)\n   list_size_def\n     |- (!f. list_size f [] = 0) /\\\n        !f a0 a1. list_size f (a0::a1) = 1 + (f a0 + list_size f a1))\n   EL\n     |- (!l. EL 0 l = HD l) /\\ (!l n. EL (SUC n) l = EL n (TL l))\n\\end{verbatim}\n\\end{hol}\n\n\\noindent\nNote that the extraction of the $n$th element (\\holtxt{EL}) of a list\nstarts its indexing from 0.  If the length of the list $\\ell$ is less\nthan or equal to $n$, the result of \\holtxt{EL~$n$~$\\ell$~} is\nunspecified.\n\n\\paragraph {Mapping functions over lists}\n\\index{MAP, the HOL constant@\\ml{MAP}, the \\HOL{} constant}\n\\index{MAP2, the HOL constant@\\ml{MAP2}, the \\HOL{} constant}\n\\index{mapping functions, in the HOL logic@mapping functions, in the \\HOL{} logic!for lists}\n\nThere are functions for mapping a function $f : \\alpha \\to \\beta$ over\na single list (\\holtxt{MAP}) or a function $f : \\alpha \\to \\beta\n\\to \\gamma$ over two lists (\\holtxt{MAP2}).\n\\begin{hol}\n\\begin{verbatim}\n   MAP\n     |- (!f. MAP f [] = []) /\\\n        (!f h t. MAP f (h::t) = f h::MAP f t)\n   MAP2\n     |- (!f. MAP2 f [] [] = []) /\\\n        !f h1 t1 h2 t2. MAP2 f (h1::t1) (h2::t2) = f h1 h2::MAP2 f t1 t2\n\\end{verbatim}\n\\end{hol}\nThe behaviour of \\holtxt{MAP2} in the cases when it is given lists of\nunequal lengths is unspecified.\n\n\\paragraph {Predicates over lists}\n\\index{FILTER, the HOL constant@\\ml{FILTER}, the \\HOL{} constant}\n\\index{EVERY, the HOL constant@\\ml{EVERY}, the \\HOL{} constant}\n\\index{ALL_DISTINCT, the HOL constant@\\ml{ALL\\_DISTINCT}, the \\HOL{} constant}\n\\index{EXISTS, the HOL constant (over lists)@\\ml{EXISTS}, the \\HOL{}\n  constant (over lists)}\n\nPredicates can be applied to lists in a universal sense (the predicate\nmust hold of every element in the list) or an existential sense (the\npredicate must hold of some element in the list). This functionality\nis supported by \\holtxt{EVERY} and \\holtxt{EXISTS}, respectively. The\nelimination of all elements in list not satisfying a given predicate\nis performed by \\holtxt{FILTER}.\n\\begin{hol}\n\\begin{verbatim}\n   EVERY_DEF\n     |- (!P. EVERY P [] = T) /\\\n        (!P h t. EVERY P (h::t) = P h /\\ EVERY P t)\n   EXISTS_DEF\n     |- (!P. EXISTS P [] = F) /\\\n        (!P h t. EXISTS P (h::t) = P h \\/ EXISTS P t)\n   FILTER\n     |- (!P. FILTER P [] = []) /\\\n        (!P h t. FILTER P (h::t) = if P h then h::FILTER P t else FILTER P t)\n   ALL_DISTINCT\n     |- (ALL_DISTINCT [] = T) /\\\n        (!h t. ALL_DISTINCT (h::t) = ~MEM h t /\\ ALL_DISTINCT t)\n\\end{verbatim}\n\\end{hol}\nThe predicate \\holtxt{ALL\\_DISTINCT} holds on a list just in case no\nelement in the list is equal to any other.\n\n\\paragraph {Folding}\n\\index{FOLDL, the HOL constant@\\ml{FOLDL}, the \\HOL{} constant}\n\\index{FOLDR, the HOL constant@\\ml{FOLDR}, the \\HOL{} constant}\n\nApplying a binary function $f : \\alpha\\to\\beta\\to\\beta$ pairwise\nthrough a list and accumulating the result is known as\n\\emph{folding}. At times, it is necessary to do this operation\nfrom left-to-right (\\holtxt{FOLDL}), and at others the\nright-to-left direction (\\holtxt{FOLDR}) is required.\n\\begin{hol}\n\\begin{verbatim}\n   FOLDL\n     |- (!f e. FOLDL f e [] = e) /\\\n        (!f e x l. FOLDL f e (x::l) = FOLDL f (f e x) l)\n   FOLDR\n     |- (!f e. FOLDR f e [] = e) /\\\n        (!f e x l. FOLDR f e (x::l) = f x (FOLDR f e l))\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph {List reversal}\n\nThe reversal of a list (\\holtxt{REVERSE}) and its tail recursive\ncounterpart \\holtxt{REV} are defined in \\theoryimp{list}.\n\\begin{hol}\n\\begin{verbatim}\n   REVERSE_DEF\n     |- (REVERSE [] = []) /\\\n        (!h t. REVERSE (h::t) = REVERSE t ++ [h])\n   REV_DEF\n     |- (!acc. REV [] acc = acc) /\\\n        (!h t acc. REV (h::t) acc = REV t (h::acc))\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph {Removal of duplicates}\nThe \\holtxt{nub} function removes all duplicate entries from a list.\n\\begin{hol}\n\\begin{verbatim}\n   nub_DEF\n     |- (nub [] = []) /\\\n        (!x l. nub (x::l) = if MEM x l then nub l else x::nub l)\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph {Conversion to sets}\n\nLists can be converted to sets (\\ml{LIST\\_TO\\_SET}) by partial\napplication of \\holtxt{MEM}. The somewhat terse definition is used to\nderive the theorem \\ml{IN\\_LIST\\_TO\\_SET}.\n%\n\\begin{hol}\n\\begin{verbatim}\n  LIST_TO_SET\n    |- LIST_TO_SET = combin$C MEM\n  IN_LIST_TO_SET\n    |- x IN LIST_TO_SET l = MEM x l\n\\end{verbatim}\n\\end{hol}\n%\nFurther support for translating between different kinds of\ncollections may be found in the \\theoryimp{container} theory.\n\n\\paragraph {Pairs and lists}\n\nTwo lists of equal length may be component-wise paired by\nthe {\\small\\verb+ZIP+} operation. The result is unspecified\nwhen the lists are not the same length. The inverse operation,\n{\\small\\verb+UNZIP+}, translates a list of pairs into a pair of\nlists.\n\\begin{hol}\n\\begin{verbatim}\n  ZIP\n    |- (ZIP ([],[]) = []) /\\\n       (!x1 l1 x2 l2. ZIP (x1::l1,x2::l2) = (x1,x2)::ZIP (l1,l2))\n  UNZIP_THM\n    |- (UNZIP [] = ([],[])) /\\\n       (UNZIP ((x,y)::t) = let (L1,L2) = UNZIP t in (x::L1,y::L2))\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph {Alternate access}\n\\index{LAST, the HOL constant@\\ml{LAST}, the \\HOL{} constant}\n\\index{FRONT, the HOL constant@\\ml{FRONT}, the \\HOL{} constant}\n%\nLists are essentially treated in a stack-like manner. However, at\ntimes it is convenient to access the last element\n(\\holtxt{LAST}) of a non-empty list directly. The last element\nof a non-empty list is dropped by \\holtxt{FRONT}.\n\\begin{hol}\n\\begin{verbatim}\n  LAST_DEF\n    |- !h t. LAST (h::t) = if t = [] then h else LAST t\n  FRONT_DEF\n    |- !h t. FRONT (h::t) = if t = [] then [] else h::FRONT t\n  APPEND_FRONT_LAST\n    |- !l. ~(l = []) ==> (FRONT l ++ [LAST l] = l)\n\\end{verbatim}\n\\end{hol}\n%\nJoining the front part and the last element of a non-empty list yields\nthe original list.  Both \\holtxt{LAST} and \\holtxt{FRONT}\nare unspecified on empty lists.\n\n\n\\paragraph {Prefix checking}\n\n\\index{isPREFIX, the HOL constant@\\ml{isPREFIX}, the \\HOL{} constant}\nThe relation capturing whether a list $\\ell_1$ is a prefix of $\\ell_2$\n({\\holtxt{isPREFIX}) can be defined by recursion. The infix\n\\holtxt{<{}<=} can also be used as notation for this partial order.\n% use of {} above is just a trick to stop Emacs font-lock colouring\n% this file disgustingly\n%\n\\begin{hol}\n\\begin{verbatim}\n   isPREFIX_THM\n     |- ([] <<= l <=> T) /\\\n        (h::t <<= [] <=> F) /\\\n        (h1::t1 <<= h2::t2 <=> (h1 = h2) /\\ t1 <<= t2)\n\\end{verbatim}\n\\end{hol}\nThe above theorem states that: the empty list is a prefix of any other\nlist (clause 1); that no non-empty list is a prefix of the empty list\n(clause 2); and that a non-empty list is a prefix of another non-empty\nlist if the first elements of the lists are the same, and if the tail\nof the first is a prefix of the tail of the second.\n\n\\vspace{1ex}\n\\noindent For a complete list of available theorems in\n\\theoryimp{list}, see \\REFERENCE.  Further development of list\ntheory can be found in \\theoryimp{rich\\_list}.\n\n\n\\subsubsection{List permutations and sorting}\n\\index{permutations (of lists), the HOL theory of@permutations (of lists), the \\HOL{} theory of}\n\\index{sorting, the HOL theory of@sorting, the \\HOL{} theory of}\n\nThe \\theoryimp{sorting} theory defines a notion of two lists being\npermutations of each other, then defines a general notion of sorting,\nthen shows that Quicksort is a sorting function. The\n\\theoryimp{mergesort} theory defines Merge sort and shows that it is a stable\nsorting function.\n\n\\paragraph{List permutation}\n\nTwo lists are in permutation if they have exactly the same members,\nand each member has the same number of occurrences in both lists. One\ndefinition (\\holtxt{PERM}) that captures this relationship is the\nfollowing:\n%\n\\begin{hol}\n\\begin{verbatim}\n   PERM_DEF\n     |- !L1 L2. PERM L1 L2 = !x. FILTER ($= x) L1 = FILTER ($= x) L2\n   PERM_IND =\n     |- !P.\n          P [] [] /\\\n          (!x l1 l2. P l1 l2 ==> P (x::l1) (x::l2)) /\\\n          (!x y l1 l2. P l1 l2 ==> P (x::y::l1) (y::x::l2)) /\\\n          (!l1 l2 l3. P l1 l2 /\\ P l2 l3 ==> P l1 l3)\n         ==>\n         !l1 l2. PERM l1 l2 ==> P l1 l2\n\\end{verbatim}\n\\end{hol}\n%\nA derived induction theorem (\\holtxt{PERM\\_IND}) is very\nuseful in proofs about permutations.\n\n\\paragraph{Sorting}\n\nA list is $R$-sorted if $R$ holds pairwise through the list. This\nnotion (\\holtxt{SORTED}) is captured by a recursive definition. Then\na function of type\n%\n\\begin{hol}\n\\begin{verbatim}\n   ('a -> 'a -> bool) -> 'a list -> 'a list\n\\end{verbatim}\n\\end{hol}\n%\nis a sorting function (\\holtxt{SORTS}) with respect to $R$ if\nit delivers a permutation of its input, and the result is $R$-sorted.\n%\n\\begin{hol}\n\\begin{verbatim}\n   SORTED_DEF\n     |- (SORTED R [] = T) /\\\n        (SORTED R [x] = T) /\\\n        (SORTED R (x::y::rst) = R x y /\\ SORTED R (y::rst))\n   SORTS_DEF\n     |- !f R. SORTS f R = !l. PERM l (f R l) /\\ SORTED R (f R l)\n\\end{verbatim}\n\\end{hol}\n%\nQuicksort is defined in the usual functional programming style, and\nit is indeed a sorting function, provided $R$ is a transitive and\ntotal relation.\n%\n\\begin{hol}\n\\begin{verbatim}\n   QSORT_DEF =\n     |- (QSORT ord [] = []) /\\\n        (QSORT ord (h::t) =\n           let (l1,l2) = PARTITION (\\y. ord y h) t\n           in\n             QSORT ord l1 ++ [h] ++ QSORT ord l2)\n   QSORT_SORTS\n     |- !R. transitive R /\\ total R ==> SORTS QSORT R\n\\end{verbatim}\n\\end{hol}\n\n\n\n\\index{lists, the HOL theory of@lists, the \\HOL{} theory of|)}\n\\index{ lists, the HOL theory of@\\ml{[} $\\cdots$ \\ml{;} $\\cdots$ \\ml{]} (lists, the \\HOL{} theory of)|)}\n\n\\subsection{Possibly infinite sequences (\\theoryimp{llist})}\n\n\\index{lazy lists, the HOL theory of@``lazy'' lists, the \\HOL{} theory of|(}\n\nThe theory \\theoryimp{llist} contains the definition of a type of\npossibly infinite sequences.  This type is similar to the ``lazy\nlists'' of programming languages like Haskell, hence the name of the\ntheory.  The \\theoryimp{llist} theory has a number of constants that\nare analogous to constants in the theory of finite\nlists.  The \\theoryimp{llist} versions of these constants have the\nsame names, but with a capital `L\\/' prepended.  Thus, some of the core\nconstants in this theory are:\n\\begin{hol}\n\\begin{verbatim}\n   LNIL  : 'a llist\n   LCONS : 'a -> 'a llist -> 'a llist\n   LHD   : 'a llist -> 'a option\n   LTL   : 'a llist -> 'a llist option\n\\end{verbatim}\n\\end{hol}\n\nThe \\ml{LHD} and \\ml{LTL} constants return \\ml{NONE} when applied to\nthe empty sequence, \\ml{LNIL}.  This use of an option type is another\nway of modelling the essential partiality of these constants.  (In the\ntheory of lists, the analogous \\ml{HD} and \\ml{TL} functions simply\nhave unspecified values when applied to empty lists.)\n\nThe type \\ml{llist} is not inductive, and there is no primitive\nrecursion theorem supporting the definition of functions that have\ndomains of type \\ml{llist}.  Rather, \\ml{llist} is a coinductive type,\nand has an axiom that justifies the definition of (co-)recursive\nfunctions that map \\emph{into} the \\ml{llist} type:\n\\begin{hol}\n\\begin{verbatim}\n   llist_Axiom\n      |- !f : 'a -> ('a # 'b) option.\n           ?g : 'a -> 'b llist.\n             (!x. LHD (g x) = OPTION_MAP SND (f x)) /\\\n             (!x. LTL (g x) = OPTION_MAP (g o FST) (f x))\n\\end{verbatim}\n\\end{hol}\n\\noindent An equivalent form of the above is\n\\begin{hol}\n\\begin{verbatim}\n   llist_Axiom_1\n      |- !f. ?g.\n           !x. g x =\n               case f x\n                of NONE => LNIL\n                 | SOME (x',y) => LCONS y (g x')\n\\end{verbatim}\n\\end{hol}\n\nOther constants in the theory \\theoryimp{llist} include \\ml{LMAP}, \\ml{LFINITE},\n\\ml{LNTH}, \\ml{LTAKE}, \\ml{LDROP}, and \\ml{LFILTER}. Their types are\n%\n\\index{mapping functions, in the HOL logic@mapping functions, in the \\HOL{} logic!for possibly infinite sequences}\n\\begin{hol}\n\\begin{verbatim}\n   LMAP    : ('a -> 'b) -> 'a llist -> 'b llist\n   LFINITE : 'a llist -> bool\n   LNTH    : num -> 'a llist -> 'a option\n   LTAKE   : num -> 'a llist -> 'a list option\n   LDROP   : num -> 'a llist -> 'a llist option\n   LFILTER : ('a -> bool) -> 'a llist -> 'a llist\n\\end{verbatim}\n\\end{hol}\nThey are characterised by the following theorems\n\\begin{hol}\n\\begin{verbatim}\n   LMAP\n      |- (LMAP f LNIL = LNIL) /\\\n         (LMAP f (LCONS h t) = LCONS (f h) (LMAP f t))\n   LFINITE_THM\n      |- (LFINITE LNIL = T) /\\\n         (LFINITE (LCONS h t) = LFINITE t)\n   LNTH_THM\n      |- (!n. LNTH n LNIL = NONE) /\\\n         (!h t. LNTH 0 (LCONS h t) = SOME h) /\\\n         (!n h t. LNTH (SUC n) (LCONS h t) = LNTH n t)\n   LTAKE_THM\n      |- (LTAKE 0 l = SOME []) /\\\n         (LTAKE (SUC n) LNIL = NONE) /\\\n         (LTAKE (SUC n) (LCONS h t) = OPTION_MAP (CONS h) (LTAKE n t)\n   LDROP_THM\n      |- (LDROP 0 ll = SOME ll) /\\\n         (LDROP (SUC n) ll = NONE) /\\\n         (LDROP (SUC n) (LCONS h t) = LDROP n t)\n   LFILTER_THM\n      |- (LFILTER P LNIL = LNIL) /\\\n         (LFILTER P (LCONS h t) = if P h then LCONS h (LFILTER P t)\n                                         else LFILTER P t)\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph{Concatenation}\n\nTwo lazy lists may be concatenated by \\ml{LAPPEND}. If the first lazy\nlist is infinite, elements of the second are inaccessible in the\nresult.  A lazy list of lazy lists can be flattened to a lazy list by\n\\ml{LFLATTEN}.\n\\begin{hol}\\begin{verbatim}\n   LAPPEND\n      |- (!x. LAPPEND LNIL x = x) /\\\n         (!h t x. LAPPEND (LCONS h t) x = LCONS h (LAPPEND t x))\n   LFLATTEN_THM\n      |- (LFLATTEN LNIL = LNIL) /\\\n         (!tl. LFLATTEN (LCONS LNIL t) = LFLATTEN t) /\\\n         (!h t tl. LFLATTEN (LCONS (LCONS h t) tl) =\n                      LCONS h (LFLATTEN (LCONS t tl)))\n\\end{verbatim}\\end{hol}\n\n\\paragraph{Lists and lazy lists}\n\nMapping back and forth from lists to lazy lists is accomplished\nby \\ml{fromList} and \\ml{toList}:\n\\begin{hol}\\begin{verbatim}\n   fromList\n      |- (fromList [] = LNIL) /\\\n         (!h t. fromList (h::t) = LCONS h (fromList t))\n   toList_THM\n      |- (toList LNIL = SOME []) /\\\n         (!h t. toList (LCONS h t) = OPTION_MAP (CONS h) (toList t))\n\\end{verbatim}\\end{hol}\n\n\\paragraph{Proof principles}\n\nFinally, there are two very important proof principles for proving\nthat two \\ml{llist} values are equal.  The first states that two\nsequences are equal if they return the same prefixes of length $n$ for\nall possible values of $n$:\n\\begin{hol}\n\\begin{verbatim}\n   LTAKE_EQ |- (ll1 = ll2) = (!n. LTAKE n ll1 = LTAKE n ll2)\n\\end{verbatim}\n\\end{hol}\nThis theorem is subsequently used to derive the bisimulation\nprinciple:\n\\begin{hol}\n\\begin{verbatim}\n   LLIST_BISIMULATION\n            |- (ll1 = ll2) =\n               ?R. R ll1 ll2 /\\\n                   !ll3 ll4. R ll3 ll4 ==>\n                             (ll3 = LNIL) /\\ (ll4 = LNIL) \\/\n                             (LHD ll3 = LHD ll4) /\\\n                             R (THE (LTL ll3)) (THE (LTL ll4))\n\\end{verbatim}\n\\end{hol}\nThe principle of bisimulation states that two \\ml{llist} values $l_1$\nand $l_2$ are equal if (and only if) it is possible to find a\nrelation $R$ such that\n\\begin{itemize}\n\\item $R$ relates the two values, i.e., $R\\;l_1\\;l_2$; and\n\\item if $R$ holds of any two values $l_3$ and $l_4$, then either\n  \\begin{itemize}\n  \\item both $l_3$ and $l_4$ are empty; or\n  \\item the head elements of $l_3$ and $l_4$ are the same, and the\n    tails of those two values are again related by $R$\n  \\end{itemize}\n\\end{itemize}\nOf course, a possible $R$ would be equality itself, but the strength\nof this theorem is that other, more convenient relations can also be\nused.\n\\index{lazy lists, the HOL theory of@``lazy'' lists, the \\HOL{} theory of|)}\n\n\\subsection{Labelled paths (\\theoryimp{path})}\n\nThe theory \\theoryimp{path}\n%\n\\index{labelled paths, the HOL theory of@labelled paths, the \\HOL{} theory of|(}%\n\\index{reduction sequences, the HOL theory of@reduction sequences, the \\HOL{} theory of|(}%\n\\index{paths (reduction sequences), the HOL theory of@paths (reduction sequences), the \\HOL{} theory of|(}%\n%\ndefines a binary type operator $(\\alpha,\\beta)\\ml{path}$, which\nstands for possibly infinite paths of the following form\n\\[\n  \\alpha_1 \\stackrel{\\beta_1}{\\longrightarrow}\n  \\alpha_2 \\stackrel{\\beta_2}{\\longrightarrow}\n  \\alpha_3 \\stackrel{\\beta_3}{\\longrightarrow} \\cdots\n  \\alpha_n \\stackrel{\\beta_n}{\\longrightarrow}\n  \\alpha_{n+1} \\stackrel{\\beta_{n+1}}{\\longrightarrow}  \\cdots\n  \\]\nThe \\ml{path} type is thus an appropriate model for reduction\nsequences, where the $\\alpha$ parameter corresponds to ``states'', and\nthe $\\beta$ parameter corresponds to the labels on the arrows.\n\nThe model of $(\\alpha,\\beta)\\ml{path}$ is $\\alpha \\times\n((\\alpha\\times\\beta)\\ml{llist})$.  The type of paths has two\nconstructors:\n\\begin{hol}\n\\begin{verbatim}\n   stopped_at : 'a -> ('a,'b) path\n   pcons      : 'a -> 'b -> ('a,'b) path -> ('a,'b) path\n\\end{verbatim}\n\\end{hol}\nThe \\holtxt{stopped\\_at} constructor returns a path containing just one\nstate, and no transitions.  (Thus, the reduction sequence has\n``stopped at'' this state.)  The \\ml{pcons} constructor takes a state,\na label, and a path, and returns a path which is now headed by the\nstate argument, and which moves from that state via the label argument\nto the path.  Graphically, $\\ml{pcons}\\;x\\;l\\;p$ is equal to\n\\[\nx \\stackrel{l}{\\longrightarrow}\n\\underbrace{p_1 \\stackrel{l_1}{\\longrightarrow} p_2\n  \\stackrel{l_2}{\\longrightarrow} \\cdots\\quad}_p\n\\]\nOther constants defined in theory \\theoryimp{path} include\n%\n\\index{mapping functions, in the HOL logic@mapping functions, in the \\HOL{} logic!for labelled paths}\n%\n\\begin{hol}\n\\begin{verbatim}\n   finite  : ('a,'b) path -> bool\n   first   : ('a,'b) path -> 'a\n   labels  : ('a,'b) path -> 'b llist\n   last    : ('a,'b) path -> 'a\n   length  : ('a,'b) path -> num option\n   okpath  : ('a -> 'b -> 'a -> bool) -> ('a,'b) path -> bool\n   pconcat : ('a,'b) path -> 'b -> ('a,'b) path -> ('a,'b) path\n   pmap    : ('a -> 'c) -> ('b -> 'd) -> ('a,'b)path -> ('c,'d)path\n\\end{verbatim}\n\\end{hol}\n\nThe \\ml{first} function returns the first element of a path.\nThere always is such an element, and the defining equations are\n\\begin{hol}\n\\begin{verbatim}\n   first_thm  |- (first (stopped_at x) = x) /\\\n                 (first (pcons x l p) = x)\n\\end{verbatim}\n\\end{hol}\n\nOn the other hand, the \\ml{last} function does not always have a\nwell-specified value, though it still has nice characterising\nequations:\n\\begin{hol}\n\\begin{verbatim}\n   last_thm   |- (last (stopped_at x) = x) /\\\n                 (last (pcons x l p) = last p)\n\\end{verbatim}\n\\end{hol}\n\nThe theorem for \\ml{finite} has a similar feel, but has a definite\nvalue (\\ml{F}, or \\emph{false}) on infinite paths), whereas the\nvalue of \\ml{last} on such paths is unspecified:\n\\begin{hol}\n\\begin{verbatim}\n   finite_thm |- (finite (stopped_at x) = T) /\\\n                 (finite (pcons x l p) = finite p)\n\\end{verbatim}\n\\end{hol}\n\nThe function \\ml{pconcat} concatenates two paths, linking them\nwith a provided label.  If the first path is infinite, then the result\nis equal to that first path.  The defining equation is\n\\begin{hol}\n\\begin{verbatim}\n   pconcat_thm |- (pconcat (stopped_at x) lab p2 = pcons x lab p2) /\\\n                  (pconcat (pcons x r p) lab p2 =\n                       pcons x r (pconcat p lab p2)\n\\end{verbatim}\n\\end{hol}\n%\nThese equations are true even when the first argument to\n\\ml{pconcat} is an infinite path.\n\nThe \\ml{okpath} predicate tests whether or not a path is a valid\ntransition given a ternary transition relation.  Its characterising\ntheorem is\n\\begin{hol}\n\\begin{verbatim}\n  okpath_thm |-\n     (okpath R (stopped_at x)) /\\\n     (okpath R (pcons x r p) = R x r (first p) /\\ okpath R p)\n\\end{verbatim}\n\\end{hol}\n%\nThere is also an induction principle that simplifies reasoning about\nfinite $R$-paths:\n%\n\\begin{hol}\n\\begin{verbatim}\n   finite_okpath_ind |-\n       (!x. P (stopped_at x)) /\\\n       (!x r p. okpath R p /\\ finite p /\\ R x r (first p) /\\ P p ==>\n                P (pcons x r p)) ==>\n       !p. okpath R p /\\ finite p ==> P p\n\\end{verbatim}\n\\end{hol}\n\nOne can show that a set \\holtxt{P} of paths are all $R$-paths with the\nco-induction principle:\n\\begin{hol}\n\\begin{verbatim}\n   okpath_co_ind |-\n      !P.\n         (!x r p. P (pcons x r p) ==> R x r (first p) /\\ P p) ==>\n         !p. P p ==> okpath R p\n\\end{verbatim}\n\\end{hol}\n\\index{labelled paths, the HOL theory of@labelled paths, the \\HOL{} theory of|)}\n\\index{reduction sequences, the HOL theory of@reduction sequences, the \\HOL{} theory of|)}\n\\index{paths (reduction sequences), the HOL theory of@paths (reduction sequences), the \\HOL{} theory of|)}\n\n\n\\subsection{Character strings (\\theoryimp{string})}\n\\index{strings, the HOL theory of@strings, the \\HOL{} theory of|(}\n\nThe theory \\theoryimp{string} defines a type of characters and a type\nof finite strings built from those characters, along with a useful suite of\ndefinitions for operating on strings.\n\n\\paragraph {Characters}\n\\index{characters, the HOL theory of@characters, the \\HOL{} theory of}\n\nThe type \\holtxt{char} is represented by the numbers less than 256. Two\nconstants are defined: {\\small\\verb+CHR +}$: \\konst{num}\\to\\konst{char}$ and\n{\\small\\verb+ORD +}$: \\konst{char}\\to\\konst{num}$. The following theorems\nhold:\n\\begin{hol}\n\\begin{verbatim}\n  CHR_ORD  |- !a. CHR (ORD a) = a\n  ORD_CHR  |- !r. r < 256 = (ORD (CHR r) = r)\n\\end{verbatim}\n\\end{hol}\n\n\\index{character literals}\nCharacter literals can also be entered using \\ML{} syntax, with a hash\ncharacter immediately followed by a string literal of length one.\nThus:\n\\setcounter{sessioncount}{0}\n\\begin{session}\n\\begin{verbatim}\n- val t = ``f #\"c\" #\"\\n\"``;\n<<HOL message: inventing new type variable names: 'a>>\n> val t = ``f #\"c\" #\"\\n\"`` : term\n\n- dest_term ``#\"\\t\"``;\n> val it = COMB(``CHR``, ``9``) : lambda\n\\end{verbatim}\n\\end{session}\n\n\n\n\\paragraph {Strings}\n\nThe type \\holtxt{string} is an alias for the type \\holtxt{char list}.\nAll functions and predicates over lists are thus available for use\nover strings.  Some of these constants are overloaded so that they are\nprinted (and can be parsed) with names that are more appropriate for\nthe particular case of lists of characters.\n\nFor example, \\holtxt{NIL} and \\holtxt{CONS} over strings have\nalternative names \\holtxt{EMPTYSTRING} and \\holtxt{STRING}\nrespectively:\n%\n\\begin{hol}\n\\index{EMPTYSTRING, the HOL constant@\\holtxt{EMPTYSTRING}, the \\HOL{} constant}\n\\index{STRING, the HOL constant@\\holtxt{STRING}, the \\HOL{} constant}\n\\begin{verbatim}\n   EMPTYSTRING : string\n   STRING      : char -> string -> string\n\\end{verbatim}\n\\end{hol}\n\\index{string literals}\nThe \\HOL{} parser maps the syntax \\holtxt{\"\"} to \\holtxt{EMPTYSTRING},\nand the \\HOL{} printer inverts this.  The parser expands string\nliterals of the form \\holtxt{\"$c_1 c_2 \\ldots c_n$\"} to the compound\nterm\n\\[\n\\holtxt{STRING} \\;c_1\\; (\\holtxt{STRING}\\;c_2\\,\\ldots\\,\n (\\holtxt{STRING} \\;c_{n-1} \\; (\\holtxt{STRING}\\;\nc_n \\; \\holtxt{EMPTYSTRING})) \\,\\ldots\\, )\n\\]\nOf course, one could also write\n\\begin{session}\n\\begin{verbatim}\n- ``[#\"a\"; #\"b\"]``;\n> val it = ``\"ab\"`` : term\n\\end{verbatim}\n\\end{session}\n\nString literals can be constructed using the various special escape\nsequences that are used in \\ML{}.  For example, \\ml{\\bs{}n} for the\nnewline character, and a backslash followed by three decimal digits\nfor characters of the given number.\n\\begin{session}\n\\begin{verbatim}\n- val t = ``\"foo bar\\n\\001\"``;\n> val t = ``\"foo bar\\n\\^A\"`` : term\n\\end{verbatim}\n\\end{session}\nNote that if one wants to use the control-character syntax with the\ncaret that the pretty-printer has chosen to use in printing the given\nstring, and this occurs inside a quotation, then the caret will need\nto be doubled.  (See Section~\\ref{sec:quotation-antiquotation}.)\n\nThere is also a destructor function {\\small\\verb+DEST_STRING+} for\nstrings which returns an option type.\n\\begin{hol}\n\\begin{verbatim}\n   DEST_STRING\n     |- (DEST_STRING \"\" = NONE) /\\\n        (DEST_STRING (STRING c rst) = SOME(c,rst))\n\\end{verbatim}\n\\end{hol}\n\n\n\\paragraph{Case expressions}\n\\index{case expressions!over strings}\n\nCompound \\HOL{} expressions that branch based on\nwhether a term is an empty or non-empty string can be written with the\nsurface syntax\n\\begin{hol}\n\\begin{verbatim}\n   case s\n    of \"\" => e1\n     | STRING c rst => e2\n\\end{verbatim}\n\\end{hol}\n\nSuch an expression is actually a case-expression over the underlying list, and so the underlying constant is that for lists.\n\n\\paragraph {Length and concatenation}\n\nA standard function \\holtxt{LENGTH} can be written \\holtxt{STRLEN}\nwhen applied to a string, and \\holtxt{APPEND} can be written as\n\\holtxt{STRCAT}.  There are also theorems characterising these\nconstants in \\ml{stringTheory}, though they are simply instantiations\nof results from \\ml{listTheory}:\n\\begin{hol}\n\\begin{verbatim}\n   STRLEN_THM\n     |- (STRLEN \"\" = 0) /\\\n        (STRLEN (STRING c s) = 1 + STRLEN s)\n\n   STRCAT_EQNS =\n     |- (STRCAT \"\" s = s) /\\\n        (STRCAT s \"\" = s) /\\\n        (STRCAT (STRING c s1) s2 = STRING c (STRCAT s1 s2))\n\\end{verbatim}\n\\end{hol}\n\n\n\\index{strings, the HOL theory of@strings, the \\HOL{} theory of|)}\n\n\\section{Collections}\n\nSeveral different notions of a collection of elements are available in\n\\HOL: sets, multisets, relations, and finite maps.\n\n\\subsection{Sets (\\theoryimp{pred\\_set})}\n\\label{sec:theory-of-sets}\n\\index{sets, the HOL theory of@sets, the \\HOL{} theory of}\n\nAn extensive development of set theory is available in the theory\n\\theoryimp{pred\\_set}. Sets are represented by functions of the type\n$\\alpha \\to \\konst{bool}$, \\ie, they are so-called characteristic\nfunctions.\n%\n\\index{characteristic functions!as basis for \\HOL{} theory of sets}\n%\nOne can use the type abbreviation $\\alpha\\; \\konst{set}$\ninstead of $\\alpha \\to \\konst{bool}$. Sets may be finite or\ninfinite. All of the elements in a set must have the same type.\n\n\\emph{Set membership} is the basic notion that formalized set theory\nis based on. In \\HOL, membership is represented by a the infix\nconstant \\holtxt{IN}, defined in theory \\theoryimp{bool} for\nconvenience.\n\\begin{hol}\n\\begin{verbatim}\n   IN_DEF   |- IN = \\x f. f x\n\\end{verbatim}\n\\end{hol}\nThe \\holtxt{IN} operator is merely a way of applying the\ncharacteristic function to an item, as the following trivial\nconsequence of the definition shows:\n\\begin{hol}\n\\begin{verbatim}\n   SPECIFICATION   |- !P x. x IN P = P x\n\\end{verbatim}\n\\end{hol}\nTwo sets are equal if they have the same elements.\n\\begin{hol}\n\\begin{verbatim}\n   EXTENSION   |- !s t. (s = t) = (!x. (x IN s) = (x IN t))\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph{Empty and universal sets}\n\\index{universal set}\nThe empty set is the characteristic function that is constantly false. The constant \\holtxt{EMPTY} denotes the empty set; it may be written as \\holtxt{\\{\\}} and \\holtxt{$\\emptyset$} (U+2205).\nThe universal set, \\holtxt{UNIV}, on a type is the characteristic function that is always true for elements of that type.\n\\begin{hol}\n\\begin{verbatim}\n   EMPTY_DEF   |- {} = (\\x. F)\n   UNIV_DEF    |- UNIV = (\\x. T)\n\\end{verbatim}\n\\end{hol}\nIn addition to \\holtxt{UNIV} (perhaps with a type annotation \\holtxt{:'a~set}), one may also write \\holtxt{univ(:'a)} to represent the universal set over type \\holtxt{:'a}.\nThe Unicode syntax \\holtxt{$\\mathbb{U}$(:'a)} means the same.\nThe Unicode symbol for $\\mathbb{U}$ is U+1D54C, and may not exist in many fonts.\n\n\\index{traces, controlling HOL feedback@traces, controlling \\HOL{} feedback!universal sets}One of these forms will be used to print \\holtxt{UNIV} by default.\nThe user trace (see Section~\\ref{sec:traces}) \\ml{\"Univ~pretty-printing\"} can be set to zero to cancel this behaviour.\nAdditionally, the trace \\ml{\"Unicode Univ printing\"} can be used to stop the U+1D54C syntax from being used, even if the Unicode trace is set.\n\nThe symbols \\holtxt{univ} and \\holtxt{$\\mathbb{U}$} are high-priority prefixes (see Section~\\ref{sec:parseprint:fixities}), and overloaded patterns (see Section~\\ref{sec:parser:syntactic-patterns}) mapping a value of the itself type to the corresponding \\holtxt{UNIV} constant.\nOne effect is that one can write things like\n\\begin{hol}\n\\begin{verbatim}\n   FINITE univ(:'a)\n\\end{verbatim}\n\\end{hol}\nwithout the need for parentheses around \\holtxt{FINITE}'s argument.\n\n\\paragraph{Insertion, union, and intersection}\n\nThe insertion ({\\small\\verb+INSERT+}, written infix) of an element\ninto a set is defined with a set comprehension. Set comprehension is\ndiscussed in the next subsection. Set union ({\\small\\verb+UNION+},\nwritten infix) and intersection ({\\small\\verb+INTER+}, also infix)\nare given their usual definitions by set comprehension.\n\\begin{hol}\n\\begin{verbatim}\n   INSERT_DEF  |- !x s. x INSERT s = {y | (y = x) \\/ y IN s}\n   UNION_DEF   |- !s t. s UNION t = {x | x IN s \\/ x IN t}\n   INTER_DEF   |- !s t. s INTER t = {x | x IN s /\\ x IN t}\n\\end{verbatim}\n\\end{hol}\n\\holtxt{UNION} and \\holtxt{INTER} are binary\noperations. Indexed union and intersection operations, \\ie,\n$\\bigcup_{i \\in P}$ and $\\bigcap_{i \\in P}$ are provided by the\ndefinitions of  \\holtxt{BIGUNION} and \\holtxt{BIGINTER}.\n\\begin{hol}\n\\begin{verbatim}\n   BIGUNION    |- !P. BIGUNION P = {x | ?s. s IN P /\\ x IN s}\n   BIGINTER    |- !P. BIGINTER P = {x | !s. s IN P ==> x IN s}\n\\end{verbatim}\n\\end{hol}\nBoth \\holtxt{BIGUNION} and \\holtxt{BIGINTER} reduce a set of sets to a\nset and thus have the type\n$((\\alpha\\to\\konst{bool})\\to\\konst{bool})\\to (\\alpha\\to\\konst{bool})$.\n\n\\paragraph{Subsets}\n\nSet inclusion (\\holtxt{SUBSET}, infix), proper set inclusion\n(\\holtxt{PSUBSET}, infix), and power set (\\holtxt{POW}) are defined as\nfollows:\n%\n\\begin{hol}\n\\begin{verbatim}\n   SUBSET_DEF  |- !s t. s SUBSET t = !x. x IN s ==> x IN t\n   PSUBSET_DEF |- !s t. s PSUBSET t = s SUBSET t /\\ ~(s = t)\n   POW_DEF     |- !set. POW set = {s | s SUBSET set}\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph{Set difference and complement}\n\nThe difference between two sets (\\holtxt{DIFF}, infix) is defined by a\nset comprehension. Based on that, the deletion of a single element\n(\\holtxt{DELETE}, infix) from a set is straightforward. Since the\nuniverse of a type is always available via \\holtxt{UNIV}, the\ncomplement (\\holtxt{COMPL}) of a set may be taken.\n\\begin{hol}\n\\begin{verbatim}\n   DIFF_DEF    |- !s t. s DIFF t = {x | x IN s /\\ ~(x IN t)}\n   DELETE_DEF  |- !s x. s DELETE x = s DIFF {x}\n   COMPL_DEF   |- !P. COMPL P = UNIV DIFF P\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph{Functions on sets}\nThe image of a function $f :\\alpha \\to \\beta$ on\na set (\\holtxt{IMAGE}) is defined with a set comprehension.\n\\begin{hol}\n\\begin{verbatim}\n   IMAGE_DEF   |- !f s. IMAGE f s = {f x | x IN s}\n\\end{verbatim}\n\\end{hol}\n%\nInjections, surjections, and bijections between sets are defined\nas follows:\n%\n\\begin{hol}\n\\begin{verbatim}\n   INJ_DEF\n        |- !f s t.\n             INJ f s t =\n             (!x. x IN s ==> f x IN t) /\\\n             !x y. x IN s /\\ y IN s ==> (f x = f y) ==> (x = y)\n   SURJ_DEF\n        |- !f s t.\n             SURJ f s t =\n             (!x. x IN s ==> f x IN t) /\\\n             !x. x IN t ==> ?y. y IN s /\\ (f y = x)\n\n   BIJ_DEF |- !f s t. BIJ f s t = INJ f s t /\\ SURJ f s t\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph{Finite sets}\n\\index{finiteness!of sets}\nThe finite sets (\\holtxt{FINITE}) are defined inductively as those\nbuilt from the empty set by a finite number of insertions.\n%\n\\begin{hol}\n\\begin{verbatim}\n   FINITE_DEF\n     |- !s. FINITE s = !P. P {} /\\ (!s. P s ==> !e. P (e INSERT s)) ==> P s\n\\end{verbatim}\n\\end{hol}\n%\n\\noindent\nA set is infinite iff it is not finite, and there is an abbreviation in the system that parses \\holtxt{\\holquote{INFINITE~s}} into  \\holtxt{\\holquote{\\td{}FINITE~s}}.\nThe pretty-printer reverses this transformation.\n\n\\medskip\\noindent\nThe finite sets have an induction theorem:\n%\n\\index{induction theorems, in HOL logic@induction theorems, in \\HOL{} logic!for finite sets}\n%\n\\begin{hol}\n\\begin{verbatim}\n   FINITE_INDUCT\n     |- !P. P {} /\\\n           (!s. FINITE s /\\ P s ==> !e. ~(e IN s) ==> P (e INSERT s))\n           ==>  !s. FINITE s ==> P s\n\\end{verbatim}\n\\end{hol}\n%\nAs mentioned, set operations apply to both finite and infinite\nsets. However, some operations, such as cardinality\n(\\holtxt{CARD}), are only defined for finite sets.  The\ncardinality of an infinite set is not specified.\n\\index{cardinality of (finite) sets}\n%\n\\begin{hol}\n\\begin{verbatim}\n   CARD_DEF\n     |- (CARD {} = 0) /\\\n        !s. FINITE s ==>\n            !x. CARD (x INSERT s) = if x IN s then CARD s else SUC (CARD s)\n\\end{verbatim}\n\\end{hol}\n%\nSince the finite and infinite sets are dealt with uniformly in\n\\theoryimp{pred\\_set}, properties of operations on finite sets must\nexplicitly include constraints about finiteness. For example the\nfollowing theorem relating cardinality and subsets is only true for\nfinite sets.\n%\n\\begin{hol}\n\\begin{verbatim}\n   CARD_PSUBSET\n     |- !s. FINITE s ==> !t. t PSUBSET s ==> CARD t < CARD s\n\\end{verbatim}\n\\end{hol}\n%\nAn extensive suite of theorems dealing with finiteness and cardinality\nis available in \\theoryimp{pred\\_set}.\n\n\\paragraph{Cross product}\nThe product of two sets ({\\small\\verb+CROSS+}, infix) is defined\nwith a set comprehension.\n%\n\\begin{hol}\n\\begin{verbatim}\n   CROSS_DEF   |- !P Q. P CROSS Q = {p | FST p IN P /\\ SND p IN Q}\n\\end{verbatim}\n\\end{hol}\n%\n\\noindent Cardinality and cross product are related by the following theorem:\n\\begin{hol}\n\\begin{verbatim}\n   CARD_CROSS\n     |- !P Q. FINITE P /\\ FINITE Q ==> (CARD (P CROSS Q) = CARD P * CARD Q)\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph{Recursive functions on sets}\n\nRecursive functions on sets may be defined by wellfounded\nrecursion. Usually, the totality of such a function is established by\nmeasuring the cardinality of the (finite) set. However, another\ntheorem may be used to justify a fold ({\\small\\verb+ITSET+}) for finite sets.\nProvided a function $f:\\alpha\\to\\beta\\to\\beta$ obeys a condition\nknown as \\emph{left-commutativity}, namely, $f\\;x\\;(f\\;y\\;z) =\nf\\;y\\;(f\\;x\\;z)$, then $f$ can be applied by folding it on the set\nin a tail-recursive fashion.\n\\begin{hol}\n\\begin{verbatim}\n   ITSET_EMPTY\n     |- !f b. ITSET f {} b = b\n   COMMUTING_ITSET_INSERT\n     |- !f s. (!x y z. f x (f y z) = f y (f x z)) /\\ FINITE s ==>\n              !x b. ITSET f (x INSERT s) b = ITSET f (s DELETE x) (f x b)\n\\end{verbatim}\n\\end{hol}\nA recursive version is also available:\n\\begin{hol}\n\\begin{verbatim}\n   COMMUTING_ITSET_RECURSES\n     |- !f e s b.\n          (!x y z. f x (f y z) = f y (f x z)) /\\ FINITE s ==>\n          (ITSET f (e INSERT s) b = f e (ITSET f (s DELETE e) b))\n\\end{verbatim}\n\\end{hol}\nFor the full derivation, see the sources of {\\small\\verb+pred_set+}.\nThe definition of {\\small\\verb+ITSET+} allows, for example, the\ndefinition of summing the results of a function on a finite set of\nelements, from which a recursive characterization and other useful\ntheorems are derived.\n%\n\\begin{hol}\n\\begin{verbatim}\n   SUM_IMAGE_DEF\n     |- !f s. SIGMA f s = ITSET (\\e acc. f e + acc) s 0\n   SUM_IMAGE_THM\n     |- !f. (SIGMA f {} = 0) /\\\n            !e s. FINITE s ==>\n                  (SIGMA f (e INSERT s) = f e + SIGMA f (s DELETE e))\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph{Other definitions and theorems}\n\nThere are more definitions in \\theoryimp{pred\\_set}, but they are not\nas heavily used as the ones presented here. Similarly, most theorems\nin \\theoryimp{pred\\_set} relate the various common set operations to\neach other, but do not express any deep theorems of set theory.\n\nHowever, one notable theorem is Koenig's Lemma, which states that\nevery finitely branching infinite tree has an infinite path. There are\nmany ways to formulate this theorem, depending on how the notion of\ntree is formalized. In \\theoryimp{pred\\_set}, finite branching is\ndefined as a predicate on a relation.\n%\n\\begin{hol}\n\\begin{verbatim}\n   finite_branching_def\n     |- !R. finitely_branching R = !x. FINITE {y | R x y}\n\\end{verbatim}\n\\end{hol}\n%\nFrom this, the following version of Koenig's Lemma is stated and\nproved:\n\\begin{hol}\n\\begin{verbatim}\n   KoenigsLemma\n     |- finitely_branching R ==>\n          !x. ~FINITE {y | RTC R x y} ==>\n              ?f. (f 0 = x) /\\ !n. R (f n) (f (SUC n))\n\\end{verbatim}\n\\end{hol}\n\n\n\\subsubsection{Syntax for sets}\\index{set theory notation}\\label{sec:set-syntax}\n\nThe special purpose set-theoretic notations\n{\\small\\verb%{%}$t_1 ;t_2 ; \\ldots ; t_n${\\small\\verb%}%} and\n{\\small\\verb%{%}$t${\\small\\verb% | %}$p${\\small\\verb%}%} are recognized\nby the \\HOL{} parser and printer when the theory \\theoryimp{pred\\_set}\nis loaded.\n\nThe normal interpretation of \\lb$t_1 ;t_2 ; \\ldots ; t_n$\\rb{} is the finite set\ncontaining just $t_1,t_2,\\ldots,\nt_n$. This can be modelled by starting with the empty set and\nperforming a sequence of insertions. For example, \\holtxt{\\lb{}1;2;3;4\\rb{}}\nparses to\n\n\\begin{hol}\n\\begin{verbatim}\n   1 INSERT (2 INSERT (3 INSERT (4 INSERT EMPTY)))\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph {Set comprehensions}\n\nThe normal interpretation of\n{\\small\\verb%{%}$t${\\small\\verb% | %}$p${\\small\\verb%}%} is\nthe set of all $t$s such that $p$. In \\HOL, such syntax parses to:\n%\n\\ml{GSPEC(\\bs($x_1$,$\\ldots$,$x_n$).($t$,$p$))}\n%\n\\noindent where $x_1, \\ldots, x_n$ are those free variables that\noccur in both $t$ and $p$ if both have at least one free variable. If\n$t$ or $p$ has no free variables, then $x_1,\\ldots,x_n$ are taken to\nbe the free variables of the other term.  If both terms have free\nvariables, but there is no overlap, then an error results. The order\nin which the variables are listed in the variable structure of the\npaired abstraction is an unspecified function of the structure of $t$\n(it is approximately left to right). For example,\n%\n\\begin{hol}\n\\begin{verbatim}\n   {p+q | p < q /\\ q < r}\n\\end{verbatim}\n\\end{hol}\n%\nparses to:\n%\n\\begin{hol}\n\\begin{verbatim}\n   GSPEC(\\(p,q). ((p+q), (p < q /\\ q < r)))\n\\end{verbatim}\n\\end{hol}\n%\nwhere \\ml{GSPEC} is characterized by:\n%\n\\begin{hol}\n\\begin{verbatim}\n   GSPECIFICATION  |- !f v. (v IN GSPEC f) = (?x. (v,T) = f x)\n\\end{verbatim}\n\\end{hol}\n\nThis somewhat cryptic specification can be understood by exercising an\nexample. The syntax\n%\n\\begin{hol}\n\\begin{verbatim}\n   a IN {p+q | p < q /\\ q < r}\n\\end{verbatim}\n\\end{hol}\n%\nis mapped by the \\HOL{} parser to\n\\begin{hol}\n\\begin{verbatim}\n   a IN GSPEC(\\(p,q). ((p+q), (p < q /\\ q < r)))\n\\end{verbatim}\n\\end{hol}\n%\nwhich, by \\ml{GSPECIFICATION}, is equal to\n\\begin{hol}\n\\begin{verbatim}\n   ?x. (a,T) = (\\(p,q). ((p+q), (p < q /\\ q < r))) x\n\\end{verbatim}\n\\end{hol}\n%\nThe existentially quantified variable \\verb+x+ has a pair type,\nso it can be replaced by a pair \\verb+(p,q)+ and a\npaired-$\\beta$-reduction can be performed, yielding\n%\n\\begin{hol}\n\\begin{verbatim}\n   ?(p,q). (a,T) = ((p+q), (p < q /\\ q < r))\n\\end{verbatim}\n\\end{hol}\n%\nwhich is equal to the intended meaning of the original\nsyntax:\n%\n\\begin{hol}\n\\begin{verbatim}\n   ?(p,q). (a = p+q) /\\ (p < q /\\ q < r)\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph{Unambiguous set comprehensions} There is also\nan unambiguous set comprehension syntax, which allows the user to\nspecify which variables are to be quantified over in the abstraction\nthat is the argument of \\holtxt{GSPEC}.  Terms of the form\n\\begin{hol}\n\\begin{verbatim}\n   { t | vs | P }\n\\end{verbatim}\n\\end{hol}\ngenerate sets containing values of the form given by \\holtxt{t}, where\nthe variables mentioned in \\holtxt{vs} must satisfy the constraint\n\\holtxt{P}.  For example, the set\n\\begin{hol}\n\\begin{verbatim}\n   { x + y | x | x < y }\n\\end{verbatim}\n\\end{hol}\nis the set of numbers from \\holtxt{y} up to but not including\n\\holtxt{2~*~y}.  The set can be ``read'' computationally: draw out all\nthose \\holtxt{x} that are less than \\holtxt{y}, and to each such\n\\holtxt{x} add \\holtxt{y}, thereby generating a set of numbers.\n\nIn the example above, the underlying \\holtxt{GSPEC} term will be\n\\begin{hol}\n\\begin{verbatim}\n   GSPEC (\\x. (x + y, x < y))\n\\end{verbatim}\n\\end{hol}\n\nThe \\holtxt{vs} component of the unambiguous notation must be a single\n``variable structure'' that might appear underneath a possibly paired\nabstraction as in section~\\ref{HOL-varstruct}.  In other words, this\n\\begin{hol}\n\\begin{verbatim}\n   { x + y | (x,y) | x < y }\n\\end{verbatim}\n\\end{hol}\nis fine, but this\n\\begin{hol}\n\\begin{verbatim}\n   { x + y | x y | x < y }\n\\end{verbatim}\n\\end{hol}\nwill raise an error.  (Additionally, the outermost parentheses around\npairs in the \\holtxt{vs} position can be omitted.)\n\nThe unambiguous notation is printed by the pretty-printer whenever the\nset to be printed can not be expressed with the default notation, or\nif the trace variable with name \\ml{pp\\_unambiguous\\_comprehensions}\nis set to \\ml{1}.\n(If the same trace is set to \\ml{2}, then the unambiguous notation will never be used.)\n\\index{traces, controlling HOL feedback@traces, controlling \\HOL{} feedback!set comprehensions}\n\n\\subsection{Multisets (\\theoryimp{bag})}\\label{multiset}\n\nMultisets, also known as \\emph{bags}, are similar to sets, except that\nthey allow repeat occurrences of an element. Whereas sets are\nrepresented by functions of type $\\alpha\\to\\konst{bool}$, which signal\nthe presence, or absence, of an element, multisets are represented\nby functions of type $\\alpha\\to\\konst{num}$, which give the\nmultiplicity of each element in the multiset. Multisets may be finite\nor infinite.\n\nThe type abbreviations $\\alpha\\;\\konst{multiset}$ and\n$\\alpha\\;\\konst{bag}$ can be used instead of $\\alpha\\to\\konst{num}$.\n\n\\paragraph {Empty multiset}\n\nThe empty bag has no elements. Thus, the function implementing it\nreturns $0$ for every input.\n%\n\\begin{hol}\n\\begin{verbatim}\n   EMPTY_BAG  |- EMPTY_BAG = K 0\n\\end{verbatim}\n\\end{hol}\n\n\\noindent The special syntax {\\verb+{||}+} can be used to represent the empty\nbag.\n\n\\paragraph {Membership}\n\nMuch of the theory can be based on the notion of membership in a\nbag. There are two notions: does an element occur at least $n$ times\nin a bag ({\\small\\verb+BAG_INN+}); and does an element occur in a bag\nat all ({\\small\\verb+BAG_IN+}).\n%\n\\begin{hol}\n\\begin{verbatim}\n   BAG_INN  |- BAG_INN e n b = (b e >= n)\n   BAG_IN   |- BAG_IN e b = BAG_INN e 1 b\n\\end{verbatim}\n\\end{hol}\n%\nTwo bags are equal if all elements have the same tally.\n%\n\\begin{hol}\n\\begin{verbatim}\n   BAG_EXTENSION\n     |- !b1 b2. (b1 = b2) = (!n e. BAG_INN e n b1 = BAG_INN e n b2)\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph{Sub-multiset}\n\nA sub-bag relationship (\\holtxt{SUB\\_BAG}) holds between $b_1$ and\n$b_2$ provided that every element in $b_1$ occurs at least as often in\n$b_2$. The notion of a proper sub-bag (\\holtxt{PSUB\\_BAG}) is easily\ndefined.\n%\n\\begin{hol}\n\\begin{verbatim}\n   SUB_BAG\n     |- SUB_BAG b1 b2 = !x n. BAG_INN x n b1 ==> BAG_INN x n b2\n   PSUB_BAG\n     |- PSUB_BAG b1 b2 = SUB_BAG b1 b2 /\\ ~(b1 = b2)\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph{Insertion}\n\nInserting an element into a bag (\\holtxt{BAG\\_INSERT}) updates the\ntally for that element and leaves the others unchanged.\n%\n\\begin{hol}\n\\begin{verbatim}\n   BAG_INSERT\n     |- BAG_INSERT e b = (\\x. if (x = e) then b e + 1 else b x)\n\\end{verbatim}\n\\end{hol}\n\nExplicitly-given multisets are supported by the syntax\n{\\small\\verb%{|%}$t_1 ;t_2 ; \\ldots ; t_n${\\small\\verb%|}%}, where\nthere may, of course, be repetitions. This is modelled by starting with the empty\nmultiset and performing a sequence of insertions. For example,\n\\verb+{|1; 2; 3; 2; 1|}+ parses to\n\n\\begin{hol}\n\\begin{verbatim}\n   BAG_INSERT 1 (BAG_INSERT 2 (BAG_INSERT 3\n                                 (BAG_INSERT 2 (BAG_INSERT 1 {||}))))\n\\end{verbatim}\n\\end{hol}\n\n\n\\paragraph{Union and difference}\n\nThe union (\\holtxt{BAG\\_UNION}) and difference (\\holtxt{BAG\\_DIFF})\noperations on bags both reduce to an arithmetic calculation on their\nelements. Deleting a single element from a bag may be expressed by\ntaking the multiset difference with a single-element multiset;\nhowever, there is also a relational presentation\n(\\holtxt{BAG\\_DELETE}) which relates its first and last arguments only\nif the first contains exactly one more occurrence of the middle\nargument than the last.  This is not the same as using\n\\holtxt{BAG\\_DIFF} to remove a one-element bag because it insists that\nthe element being removed actually appear in the larger bag.\n%\n\\begin{hol}\n\\begin{verbatim}\n   BAG_UNION\n     |- BAG_UNION b c = \\x. b x + c x\n   BAG_DIFF\n     |- BAG_DIFF b1 b2 = \\x. b1 x - b2 x\n   BAG_DELETE\n     |- BAG_DELETE b0 e b = (b0 = BAG_INSERT e b)\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph {Intersection, merge, and filter}\n\nThe intersection of two bags (\\holtxt{BAG\\_INTER}) takes the pointwise\nminimum. The dual operation, merging (\\holtxt{BAG\\_MERGE}), takes the\npointwise maximum. A bag can be `filtered' by a set to return the bag\nwhere all the elements not in the set have been dropped\n(\\holtxt{BAG\\_FILTER}).\n%\n\\begin{hol}\n\\begin{verbatim}\n   BAG_INTER\n     |- BAG_INTER b1 b2 = (\\x. if (b1 x < b2 x) then b1 x else b2 x)\n   BAG_MERGE\n     |- BAG_MERGE b1 b2 = (\\x. if (b1 x < b2 x) then b2 x else b1 x)\n   BAG_FILTER_DEF\n     |- BAG_FILTER P b = (\\e. if P e then b e else 0)\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph {Sets and Multisets}\n\nMoving between bags and sets is accomplished by the following two\ndefinitions.\n%\n\\begin{hol}\n\\begin{verbatim}\n   SET_OF_BAG\n     |- SET_OF_BAG b = \\x. BAG_IN x b\n   BAG_OF_SET\n     |- BAG_OF_SET P = \\x. if x IN P then 1 else 0\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph {Image}\n\nTaking the image of a function on a multiset to get a new multiset\nseems to be simply a matter of applying the function to each element\nof the multiset. However, there is a problem if $f$ is non-injective\nand the multiset is infinite. For example, take the multiset\nconsisting of all the natural numbers and apply $\\lambda x.\\; 1$ to\neach element. The resulting multiset would hold an infinite number of\n$1$s. To avoid this requires some constraints: for example,\nstipulating that the function be only finitely non-injective, or that\nthe input multiset be finite. Such conditions would be onerous in\nproof; the compromise is to map the multipicity of problematic\nelements to $0$.\n%\n\\begin{hol}\n\\begin{verbatim}\n   BAG_IMAGE_DEF\n     |- BAG_IMAGE f b =\n          \\e. let sb = BAG_FILTER (\\e0. f e0 = e) b\n              in\n                if FINITE_BAG sb then BAG_CARD sb else 0\n\\end{verbatim}\n\\end{hol}\n\n\n\\paragraph {Finite multisets}\n\\index{finiteness!of multi-sets}\nThe finite multisets (\\holtxt{FINITE\\_BAG}) are defined inductively as\nthose built from the empty bag by a finite number of insertions.\n%\n\\begin{hol}\n\\begin{verbatim}\n   FINITE_BAG\n     |- FINITE_BAG b =\n          !P. P EMPTY_BAG /\\\n              (!b. P b ==> (!e. P (BAG_INSERT e b))) ==> P b\n\\end{verbatim}\n\\end{hol}\n%\nThe finite multisets have an induction theorem, and also a strong\ninduction theorem.\n%\n\\index{induction theorems, in HOL logic@induction theorems, in \\HOL{} logic!for finite bags}\n%\n\\begin{hol}\n\\begin{verbatim}\n   FINITE_BAG_INDUCT\n     |- !P. P {||} /\\\n            (!b. P b ==> (!e. P (BAG_INSERT e b)))\n            ==> (!b. FINITE_BAG b ==> P b)\n\n   STRONG_FINITE_BAG_INDUCT\n     |- !P. P {||} /\\\n            (!b. FINITE_BAG b /\\ P b ==> !e. P (BAG_INSERT e b))\n            ==> (!b. FINITE_BAG b ==> P b)\n\\end{verbatim}\n\\end{hol}\n%\nThe cardinality (\\holtxt{BAG\\_CARD}) of a multiset counts the\ntotal number of occurrences. It is only specified for finite multisets.\n%\n\\begin{hol}\n\\begin{verbatim}\n   BAG_CARD_THM\n     |- (BAG_CARD {||} = 0) /\\\n        (!b. FINITE_BAG b ==>\n               !e. BAG_CARD (BAG_INSERT e b) = BAG_CARD b + 1)\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph{Recursive functions on multisets}\n\nRecursive functions on multiset may be defined by wellfounded\nrecursion. Usually, the totality of such a function is established by\nmeasuring the cardinality of the (finite) multiset. However, a fold\n(\\holtxt{ITBAG}) for finite sets is provided.  Provided a function\n$f:\\alpha\\to\\beta\\to\\beta$ obeys a condition known as\n\\emph{left-commutativity}, namely, $f\\;x\\;(f\\;y\\;z) =\nf\\;y\\;(f\\;x\\;z)$, then $f$ can be applied by folding it on the\nmultiset in a tail-recursive fashion.\n%\n\\begin{hol}\n\\begin{verbatim}\n   ITBAG_EMPTY\n     |- !f acc. ITSET f {||} acc = acc\n   COMMUTING_ITBAG_INSERT\n     |- !f b. (!x y z. f x (f y z) = f y (f x z)) /\\ FINITE_BAG b ==>\n              !x a. ITBAG f (BAG_INSERT x b) a = ITBAG f b (f x a)\n\\end{verbatim}\n\\end{hol}\n%\nA recursive version is also available:\n\\begin{hol}\n\\begin{verbatim}\n   COMMUTING_ITBAG_RECURSES\n     |- !f e b a. (!x y z. f x (f y z) = f y (f x z)) /\\ FINITE_BAG b ==>\n                  (ITBAG f (BAG_INSERT e b) a = f e (ITBAG f b a))\n\\end{verbatim}\n\\end{hol}\n\n\\subsection{Relations (\\theoryimp{relation})}\\label{relation}\n\nMathematical relations can be represented in \\HOL{} by the type\n$\\alpha \\to\\beta\\to\\konst{bool}$. (In most applications, the type of a\nrelation is an instance of $\\alpha \\to\\alpha\\to\\konst{bool}$, but the\nextra generality doesn't hurt.) The theory \\theoryimp{relation}\nprovides definitions of basic properties and operations on relations,\ndefines various kinds of orders and closures, defines wellfoundedness\nand proves the wellfounded recursion theorem, and develops some\nbasic results used in Term Rewriting.\n\n\\paragraph {Basic properties}\n\nThe following basic properties of relations are defined.\n%\n\\begin{hol}\n\\begin{verbatim}\n   transitive_def\n     |- transitive R = !x y z. R x y /\\ R y z ==> R x z\n   reflexive_def\n     |- reflexive R = (!x. R x x)\n   irreflexive_def\n     |- irreflexive R = (!x. ~R x x)\n   symmetric_def\n     |- symmetric R = (!x y. R x y = R y x)\n   antisymmetric_def\n     |- antisymmetric R = (!x y. R x y /\\ R y x ==> (x = y))\n   equivalence_def\n     |- equivalence R = reflexive R /\\ symmetric R /\\ transitive R\n   trichotomous\n     |- trichotomous R = !a b. R a b \\/ R b a \\/ (a = b)\n   total_def\n     |- total R = (!x y. R x y \\/ R y x)\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph{Basic operations}\n\nThe following basic operations on relations are defined: the empty\nrelation (\\holtxt{EMPTY\\_REL}), relation composition (\\holtxt{O},\ninfix), inversion (\\holtxt{inv}), domain (\\holtxt{RDOM}), and range\n(\\holtxt{RRANGE}).\n%\n\\begin{hol}\n\\begin{verbatim}\n   EMPTY_REL_DEF\n     |- !x y. EMPTY_REL x y = F\n   O_DEF\n     |- $O R1 R2 x z = ?y. R1 x y /\\ R2 y z\n   inv_DEF\n     |- inv R x y = R y x\n   RDOM_DEF\n     |- RDOM R x = ?y. R x y\n   RRANGE\n     |- RRANGE R y = ?x. R x y\n\\end{verbatim}\n\\end{hol}\n\n\\noindent Set operations lifted to work on relations include subset\n(\\holtxt{RSUBSET}, infix), union (\\holtxt{RUNION}, infix),\nintersection (\\holtxt{RINTER}, infix), complement (\\holtxt{RCOMPL}),\nand universe (\\holtxt{RUNIV}).\n%\n\\begin{hol}\n\\begin{verbatim}\n   RSUBSET\n     |- $RSUBSET R1 R2 = !x y. R1 x y ==> R2 x y\n   RUNION\n     |- $RUNION R1 R2 x y = R1 x y \\/ R2 x y\n   RINTER\n     |- $RINTER R1 R2 x y = R1 x y /\\ R2 x y\n   RCOMPL\n     |- RCOMPL R x y = ~R x y\n   RUNIV\n     |- RUNIV x y = T\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph {Orders}\n\nA sequence of definitions capturing various notions of order are made\nin \\theoryimp{relation}.\n%\n\\begin{hol}\n\\begin{verbatim}\n   PreOrder\n     |- PreOrder R = reflexive R /\\ transitive R\n   Order\n     |- Order Z = antisymmetric Z /\\ transitive Z\n   WeakOrder\n     |- WeakOrder Z = reflexive Z /\\ antisymmetric Z /\\ transitive Z\n   StrongOrder\n     |- StrongOrder Z = irreflexive Z /\\ antisymmetric Z /\\ transitive Z\n   LinearOrder\n     |- LinearOrder R = Order R /\\ trichotomous R\n   WeakLinearOrder\n     |- WeakLinearOrder R = WeakOrder R /\\ trichotomous R\n   StrongLinearOrder\n     |- StrongLinearOrder R = StrongOrder R /\\ trichotomous R\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph {Closures}\n\nThe transitive closure (\\holtxt{TC}) of a relation $R : \\alpha\n\\to\\alpha\\to\\konst{bool}$ is defined inductively, as the least\nrelation including $R$ and closed under transitivity.\nSimilarly, the\nreflexive-transitive closure (\\holtxt{RTC}) is defined to be the least\nrelation closed under transitivity and reflexivity.\nThe ASCII syntax for the transitive closure \\holtxt{R\\^{}+} is meant to suggest the prettier \\holtxt{R${}^+$}.\nSimilarly, \\holtxt{R\\^{}*} is meant to suggest \\holtxt{R${}^*$}.\nIndeed, with Unicode enabled, transitive closure will print with a superscript \\texttt{+}.\n%\n\\begin{hol}\n\\begin{verbatim}\n   TC_DEF\n     |- R^+ a b =\n          !P. (!x y. R x y ==> P x y) /\\\n              (!x y z. P x y /\\ P y z ==> P x z) ==> P a b\n   RTC_DEF\n     |- R^* a b =\n          !P. (!x. P x x) /\\\n              (!x y z. R x y /\\ P y z ==> P x z) ==> P a b\n\\end{verbatim}\n\\end{hol}\n\n\\noindent\nFrom these definitions, one can recover the initial rules.\n%\n\\begin{hol}\n\\begin{verbatim}\n   TC_RULES\n     |- !R. (!x y. R x y ==> R^+ x y) /\\\n            (!x y z. R^+ x y /\\ R^+ y z ==> R^+ x z)\n   RTC_RULES\n     |- !R. (!x. R^* x x) /\\\n            (!x y z. R x y /\\ R^* y z ==> R^* x z)\n   RTC_RULES_RIGHT1\n     |- !R. (!x. R^* x x) /\\\n            (!x y z. R^* x y /\\ R y z ==> R^* x z)\n\\end{verbatim}\n\\end{hol}\n%\nNotice that {\\small\\verb+RTC_RULES+}, in keeping with the definition\nof {\\small\\verb+RTC+}, extends an \\verb+R+-step from \\verb+x+ to\n\\verb+y+ with a sequence of \\verb+R+-steps from \\verb+y+ to \\verb+z+\nto construct \\verb+R^* x z+. The theorem\n{\\small\\verb+RTC_RULES_RIGHT1+} first makes a sequence of \\verb+R+\nsteps and then a single \\verb+R+ step to form \\verb+R^* x z+. Similar\nalternative theorems are proved for case analysis and induction.\n\nFor example, {\\small\\verb+TC_CASES1+} and {\\small\\verb+TC_CASES2+} in the\nfollowing decompose {\\small\\verb!R^+ x z!} to either\n{\\small\\verb+R x y+} followed by {\\small\\verb!R^+ y z!}\n({\\small\\verb+TC_CASES1+})\nor\n{\\small\\verb!R^+ x y!} followed by {\\small\\verb+R y z+}\n({\\small\\verb+TC_CASES2+}).\n\n%\n\\begin{hol}\n\\begin{verbatim}\n   TC_CASES1\n     |- !R x z. R^+ x z ==> R x z \\/ ?y. R x y /\\ R^+ y z\n   TC_CASES2\n     |- !R x z. R^+ x z ==> R x z \\/ ?y. R^+ x y /\\ R y z\n\n   RTC_CASES1\n     |- !R x y. R^* x y = (x = y) \\/ ?u. R x u /\\ R^* u y\n   RTC_CASES2\n     |- !R x y. R^* x y = (x = y) \\/ ?u. R^* x u /\\ R u y\n   RTC_CASES_RTC_TWICE\n     |- !R x y. R^* x y = ?u. R^* x u /\\ R^* u y\n\\end{verbatim}\n\\end{hol}\n\nAs well as the basic induction theorems for {\\small\\verb+TC+} and\n{\\small\\verb+RTC+}, there are so-called \\emph{strong} induction\ntheorems, which have stronger induction hypotheses.\n%\n\\begin{hol}\n\\begin{verbatim}\n   TC_INDUCT\n     |- !R P. (!x y. R x y ==> P x y) /\\\n              (!x y z. P x y /\\ P y z ==> P x z)\n              ==> !u v. R^+ u v ==> P u v\n   RTC_INDUCT\n     |- ! R P. (!x. P x x) /\\\n               (!x y z. R x y /\\ P y z ==> P x z) ==>\n               (!x y. R^* x y ==> P x y)\n   TC_STRONG_INDUCT\n     |- !R P. (!x y. R x y ==> P x y) /\\\n              (!x y z. P x y /\\ P y z /\\ R^+ x y /\\ R^+ y z ==> P x z) ==>\n              (!u v. R^+ u v ==> P u v)\n   RTC_STRONG_INDUCT\n     |- !R P. (!x. P x x) /\\\n              (!x y z. R x y /\\ R^* y z /\\ P y z ==> P x z) ==>\n              (!x y. R^* x y ==> P x y)\n\\end{verbatim}\n\\end{hol}\nVariants of these induction theorems are also available which break\napart the closure from the left or right, as for the case analysis theorems.\n\n\\medskip\n\nThe reflexive~(\\holtxt{RC}) and symmetric closures~(\\holtxt{SC}) are\nstraightforward to define. The equivalence closure\n({\\small\\verb+EQC+}) is the symmetric then transitive then reflexive\nclosure of $R$.\nWhen applied to an argument, as in \\holtxt{EQC~R}, \\holtxt{EQC} is written with the suffix \\holtxt{\\^{}=}.\nNote how the suffix binds more tightly than function application, so that in \\ml{EQC_DEF}, \\holtxt{RC} really is applied to the transitive closure of the symmetric closure of \\holtxt{R}.\n%\n\\begin{hol}\n\\begin{verbatim}\n   RC_DEF   |- RC R x y = (x = y) \\/ R x y\n   SC_DEF   |- SC R x y = R x y \\/ R y x\n   EQC_DEF  |- R^= = RC (SC R)^+\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph {Wellfounded relations}\n\nA relation $R$ is wellfounded ({\\small\\verb+WF+}) if every non-empty set\nhas an $R$-minimal element. Wellfoundedness is used to justify the\nprinciple of wellfounded induction ({\\small\\verb+WF_INDUCTION_THM+}).\n%\n\\begin{hol}\n\\begin{verbatim}\n   WF_DEF\n     |- !R. WF R = !B. (?w. B w) ==> ?min. B min /\\ !b. R b min ==> ~B b\n   WF_INDUCTION_THM\n     |- !R WF R ==> !P. (!x. (!y. R y x ==> P y) ==> P x) ==> !x. P x\n\\end{verbatim}\n\\end{hol}\n\nThe \\emph{wellfounded part} ({\\small\\verb+WFP+}) of a relation can be\ninductively defined, from which its rules, case-analysis theorem and\ninduction theorems may be derived.\n%\n\\begin{hol}\n\\begin{verbatim}\n   WFP_DEF\n     |- WFP R a = !P. (!x. (!y. R y x ==> P y) ==> P x) ==> P a\n   WFP_RULES\n     |- !R x. (!y. R y x ==> WFP R y) ==> WFP R x\n   WFP_CASES\n     |- !R x. WFP R x = !y. R y x ==> WFP R y\n   WFP_INDUCT\n     |- !R P. (!x. (!y. R y x ==> P y) ==> P x)\n              ==> !x. WFP R x ==> P x\n   WFP_STRONG_INDUCT\n     |- !R. (!x. WFP R x /\\ (!y. R y x ==> P y) ==> P x)\n            ==> !x. WFP R x ==> P x\n\\end{verbatim}\n\\end{hol}\n\nWellfoundedness can also be used to justify a general recursion\ntheorem. Intuitively, a collection of recursion equations can be\nadmitted into the \\HOL{} logic with no loss of consistency provided\nthat every possible sequence of recursive calls is finite. Wellfounded\nrelations are used to capture this notion: if there is a wellfounded\nrelation $R$ on the domain of the desired function such that every\nsequence of recursive calls is $R$-decreasing, then the recursion\nequations specify a unique total function and the equations can be\nadmitted into the logic.\n\nThe recursion theorems {\\small\\verb+WFREC_COROLLARY+} and\n{\\small\\verb+WF_RECURSION_THM+} use the notion of a function\nrestriction ({\\small\\verb+RESTRICT+}) in order to force the recursive\nfunction to be applied to $R$-smaller arguments in recursive calls..\n%\n\\begin{hol}\n\\begin{verbatim}\n   RESTRICT_DEF\n     |- !f R x. RESTRICT f R x = \\y. if R y x then f y else ARB\n\n   WFREC_COROLLARY\n     |- !M R f. (f = WFREC R M) ==> WF R ==> !x. f x = M (RESTRICT f R x) x\n\n   WF_RECURSION_THM\n     |- !R. WF R ==> !M. ?!f. !x. f x = M (RESTRICT f R x) x\n\\end{verbatim}\n\\end{hol}\n\n\\noindent The theorems {\\small\\verb+WF_INDUCTION_THM+} and\n{\\small\\verb+WFREC_COROLLARY+} are used to automate recursive\ndefinitions; see Section \\ref{TFL}. A few basic operators for\nwellfounded relations are also defined, along with theorems stating\nthat they propagate wellfoundedness.\n\n\\begin{hol}\n\\begin{verbatim}\n   inv_image_def  |- !R f. inv_image R f = \\x y. R (f x) (f y)\n\n   WF_inv_image   |- !R f. WF R ==> WF (inv_image R f)\n   WF_SUBSET      |- !R P. WF R /\\ (!x y. P x y ==> R x y) ==> WF P\n   WF_TC          |- !R. WF R ==> WF (TC R)\n   WF_Empty       |- WF EMPTY_REL\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph {Term Rewriting}\n\nA few basic definitions from Term Rewriting theory\n(the diamond property (\\verb+diamond+), the Church-Rosser\nproperty ({\\small\\verb+CR+} and {\\small\\verb+WCR+}), and Strong\nNormalization ({\\small\\verb+SN+})) appear\nin \\theoryimp{relation}.\n%\n\\begin{hol}\n\\begin{verbatim}\n   diamond_def\n     |- diamond R = !x y z. R x y /\\ R x z ==> ?u. R y u /\\ R z u\n   CR_def\n     |- CR R = diamond (RTC R)\n   WCR_def\n     |- WCR R = !x y z. R x y /\\ R x z ==> ?u. RTC R y u /\\ RTC R z u\n   SN_def\n     |- SN R = WF (inv R)\n\\end{verbatim}\n\\end{hol}\n%\nFrom those, Newman's Lemma is proved.\n%\n\\begin{hol}\n\\begin{verbatim}\n   Newmans_lemma  |- !R. WCR R /\\ SN R ==> CR R\n\\end{verbatim}\n\\end{hol}\n\n\\subsection{Finite maps (\\theoryimp{finite\\_map})}\n\\label{sec:finite-map}\n\nThe theory \\theoryimp{finite\\_map} formalizes a type\n$(\\alpha,\\beta)\\,\\holtxt{fmap}$ of finite functions. These notionally\nhave type $\\alpha\\to\\beta$, but additionally have only finitely many\nelements in their domain. Finite maps are useful for formalizing\nsubstitutions and arrays. The representing type is $\\alpha\\to\\beta +\n\\konst{one}$, where only a finite number of the $\\alpha$ map to a\n$\\beta$ and the rest map to \\verb+one+. The syntax\n$\\alpha\\,\\holtxt{|->}\\,\\beta$ is recognized by the parser as an\nalternative to $(\\alpha,\\beta)\\,\\holtxt{fmap}$.\n\n\\paragraph {Basic notions}\n\nThe empty map (\\holtxt{FEMPTY}), the updating of a map\n(\\holtxt{FUPDATE}), the application of a map to an argument\n(\\holtxt{FAPPLY}), and the domain of a map (\\holtxt{FDOM}) are the\nmain notions in the theory.\n\\begin{hol}\n\\begin{verbatim}\n   FEMPTY  : 'a |-> 'b\n   FUPDATE : ('a |-> 'b) -> 'a # 'b -> ('a |-> 'b)\n   FAPPLY  : ('a |-> 'b) -> 'a -> 'b\n   FDOM    : ('a |-> 'b) -> 'a set\n\\end{verbatim}\n\\end{hol}\n\nThe \\HOL{} parser and printer will treat the syntax \\holtxt{f\\,'\\,x} as\nthe application of finite map \\verb+f+ to argument \\verb+x+, \\ie, as\n\\holtxt{FAPPLY\\,f\\,x}. The notation \\holtxt{f\\,|+\\,(x,y)} represents\n\\holtxt{FUPDATE\\,f\\,(x,y)}, \\ie, the updating of finite map\n\\verb+f+ by the pair \\verb+(x,y)+.\n\nThe basic constants have obscure definitions, from which more useful\nproperties are then derived. {\\small\\verb+FAPPLY_FUPDATE_THM+} relates\nmap update with map application.  {\\small\\verb+fmap_EXT+} is an\nextensionality result: two maps are equal if they have the same domain\nand agree when applied to arguments in that domain. One can prove\nproperties of finite maps by induction on the construction of the map\n({\\small\\verb+fmap_INDUCT+}).  The cardinality of a finite map is\njust the cardinality of its domain ({\\small\\verb+FCARD_DEF+}); from\nthis a recursive characterization ({\\small\\verb+FCARD_FUPDATE+}) is\nderived.\n\\begin{hol}\n\\begin{verbatim}\n   FAPPLY_FUPDATE_THM\n     |- !f a b x. (f |+ (a,b)) ' x = (if x = a then b else f ' x)\n   fmap_EXT\n     |- !f g. (f = g) =\n              (FDOM f = FDOM g) /\\ (!x. x IN FDOM f ==> (f ' x = g ' x))\n   fmap_INDUCT\n     |- !P. P FEMPTY /\\\n            (!f. P f ==> !x y. ~(x IN FDOM f) ==> P (f |+ (x,y))) ==> !f. P f\n   FCARD_DEF  |- FCARD fm = CARD (FDOM fm)\n   FCARD_FUPDATE\n     |- !fm a b. FCARD(fm |+ (a,b)) =\n                   if a IN FDOM fm then FCARD fm else 1 + FCARD fm\n\\end{verbatim}\n\\end{hol}\nIterated updates (\\holtxt{FUPDATE\\_LIST}) to a map are useful. The\ninfix notation \\holtxt{|++} may also be used.  For example, \\holtxt{fm\\,|++\\,[(k1,v1);\\,(k2,v2)]} is equal to \\holtxt{(fm\\,|+\\,(k1,v1))\\,|+\\,(k2,v2)}.\n\\begin{hol}\n\\begin{verbatim}\n   FUPDATE_LIST  |- FUPDATE_LIST = FOLDL FUPDATE\n   FUPDATE_LIST_THM\n     |- !f. (f |++ [] = f) /\\\n            (!h t. f |++ (h::t) = (f |+ h) |++ t)\n\\end{verbatim}\n\\end{hol}\n\n\n\\paragraph {Domain and range}\n\nThe domain of a finite map is the set of elements that it applies to;\nthis can be characterized recursively\n({\\small\\verb+FDOM_FUPDATE+}). The range of a map is defined in the\nusual way.\n\\begin{hol}\n\\begin{verbatim}\n   FDOM_FUPDATE\n     |- !f a b. FDOM (f |+ (a,b)) = a INSERT (FDOM f)\n   FRANGE_DEF\n     |- FRANGE f = {y | ?x. x IN FDOM f /\\ (f ' x = y)}\n\\end{verbatim}\n\\end{hol}\n%\nA finite map may have its domain ({\\small\\verb+DRESTRICT+})\nor range ({\\small\\verb+RRESTRICT+}) restricted by intersection with a\nset. These notions have recursive versions as well\n({\\small\\verb+DRESTRICT_FUPDATE+} and {\\small\\verb+RRESTRICT_FUPDATE+}).\n%\n\\begin{hol}\n\\begin{verbatim}\n   DRESTRICT_DEF\n     |- !f r. (FDOM (DRESTRICT f r) = (FDOM f) INTER r) /\\\n              (!x. DRESTRICT f r ' x =\n                     (if x IN ((FDOM f) INTER r) then f ' x else FEMPTY'x))\n   RRESTRICT_DEF\n     |- !f r. (FDOM (RRESTRICT f r) = {x | x IN FDOM f /\\ f ' x IN r}) /\\\n              (!x. RRESTRICT f r ' x =\n                     (if x IN (FDOM f) /\\ f ' x IN r then f ' x\n                      else FEMPTY ' x))\n   DRESTRICT_FUPDATE\n     |- !f r x y.\n           DRESTRICT (f |+ (x,y)) r =\n             if x IN r then (DRESTRICT f r) |+ (x,y) else DRESTRICT f r\n   RRESTRICT_FUPDATE\n     |- !f r x y.\n           RRESTRICT (f |+ (x,y)) r =\n             if y IN r then (RRESTRICT f r) |+ (x,y)\n                       else RRESTRICT (DRESTRICT f (COMPL {x})) r)\n\\end{verbatim}\n\\end{hol}\nThe removal of a single element from the domain of a map\n(\\holtxt{\\bs\\bs}, infix) is a simple application of\n(\\holtxt{DRESTRICT}), but sufficiently useful to deserve its own\ndefinition. Again, this concept has a alternate recursive presentation\n(\\holtxt{DOMSUB\\_FUPDATE\\_THM}).\n%\n\\begin{hol}\n\\begin{verbatim}\n   fmap_domsub\n     |- (fm \\\\ k) = DRESTRICT fm (COMPL {k})\n   DOMSUB_FUPDATE_THM\n     |- !fm k1 k2 v. (fm |+ (k1,v)) \\\\ k2 =\n                      if (k1 = k2) then (fm \\\\ k2) else (fm \\\\ k2) |+ (k1, v)\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph {Union and sub-maps}\n\nUnlike set union, the union of two finite maps\n(\\holtxt{FUNION\\_DEF}) is not symmetric: the domain of the first map\ntakes precedence. The notion of a finite map being a submap of another\n(\\holtxt{SUBMAP}, infix) is an extension of how subsets are\nformalized.\n\\begin{hol}\n\\begin{verbatim}\n   FUNION_DEF\n     |- !f g.\n          (FDOM (FUNION f g) = FDOM f UNION FDOM g) /\\\n          !x. FUNION f g ' x = (if x IN FDOM f then f ' x else g ' x)\n   SUBMAP_DEF\n     |- !f g. (f SUBMAP g) = (!x. x IN FDOM f ==> x IN FDOM g /\\\n                             (f ' x = g ' x))\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph {Finite maps and functions}\n\nAs much as possible, finite maps should be like ordinary functions.\nThus, if \\holtxt{f} is a finite map, then \\holtxt{FAPPLY f} is an\nordinary function. Similarly, there is an operation for\n\\emph{totalizing} a finite map (\\holtxt{lookup}) so that an\napplication of it returns an ordinary function, the range of which is\nthe option type.  An ordinary function can be turned into a finite map\nby restricting the function to a finite set of arguments\n(\\ml{FUN\\_FMAP\\_DEF}).\n%\n\\begin{hol}\n\\begin{verbatim}\n   lookup_DEF\n     |- FLOOKUP f x = (if x IN FDOM f then SOME (f ' x) else NONE)\n   FUN_FMAP_DEF\n     |- !f P. FINITE P ==>\n             (FDOM (FUN_FMAP f P) = P) /\\\n             (!x. x IN P ==> (FUN_FMAP f P ' x = f x))\n\\end{verbatim}\n\\end{hol}\n\n\\paragraph {Composition of maps}\n\\index{function composition, in HOL logic@function composition, in \\HOL{} logic!of finite maps}\n\nThere are three new definitions of composition, determined by whether\nthe composed functions are finite maps or not. The composition of two\nfinite maps (\\verb+f_o_f+, infix) has domain constraints\nattached. Composition of a finite map with an ordinary function\n(\\verb+o_f+, infix) applies the finite map first, then the ordinary\nfunction.  Composition of an ordinary function with a finite map\n(\\verb+f_o+, infix) applies the ordinary function and then the finite\nmap; the application of the ordinary function is achieved by turning\nit into a finite map.\n%\n\\begin{hol}\n\\begin{verbatim}\n   f_o_f_DEF\n     |- !f g.\n          (FDOM (f f_o_f g) = (FDOM g) INTER {x | g ' x IN FDOM f}) /\\\n          !x. x IN FDOM (f f_o_f g) ==> ((f f_o_f g) ' x = f ' (g ' x))\n   o_f_DEF\n     |- !f g.\n          (FDOM (f o_f g) = FDOM g) /\\\n          !x. x IN FDOM (f o_f g) ==> ((f o_f g) ' x = f (g ' x))\n   f_o_DEF\n     |- (f f_o g) = f f_o_f (FUN_FMAP g {x | g x IN FDOM f})\n\\end{verbatim}\n\\end{hol}\n\n\\section{While Loops}\n\\label{sec:while-loops}\n\nIt is a curious fact that higher order logic, although a logic of\ntotal functions, allows the definition of functions that don't\nseem total, at least from a computational perspective. An example\nis \\holtxt{WHILE}-loops. The following equation is derived in theory\n\\theoryimp{while}:\n%\n\\begin{hol}\n\\begin{verbatim}\n   WHILE  |- !P g x. WHILE P g x = if P x then WHILE P g (g x) else x\n\\end{verbatim}\n\\end{hol}\n%\nClearly, if \\holtxt{P} in this theorem was instantiated to $\\lambda\nx.\\;\\konst{T}$, the resulting instance of \\holtxt{WHILE} would `run\nforever' if executed. Why is such an ``obviously'' partial function\ndefinable in HOL?\n%\nThe answer lies in a subtle definition of \\holtxt{WHILE},\n\\footnote{The original idea is due to J Moore,\n          who suggested it for use in ACL2.}\nwhich uses the expressive power of HOL to surprising effect. Consider\nthe following total and non-recursive function:\n%\n\\begin{hol}\n\\begin{verbatim}\n  \\x. if (?n. P (FUNPOW g n x))\n       then FUNPOW g (@n. P (FUNPOW g n x) /\\\n                          !m.  m < n ==> ~P (FUNPOW g m x)) x\n       else ARB\n\\end{verbatim}\n\\end{hol}\n%\nThis function does a case analysis on the iterations of function\n\\holtxt{g}: the finite ones return the first value in the iteration at\nwhich \\holtxt{P} holds (\\ie, when the iteration stops); the infinite\nones are mapped to \\holtxt{ARB}. This function is used as the witness\nfor \\verb+f+ in the proof of the following theorem:\n%\n\\begin{hol}\n\\begin{verbatim}\n   ITERATION\n     |- !P g. ?f. !x. f x = if P x then x else f (g x)\n\\end{verbatim}\n\\end{hol}\n%\nFrom this, it is a simple application of Skolemization and\n\\holtxt{new\\_specification} to obtain the equation for \\holtxt{WHILE}.\n\n\\paragraph{Reasoning about \\holtxt{WHILE} loops}\n\nThe induction theorem for \\holtxt{WHILE} loops is proved by\nwellfounded induction, and carries wellfoundedness constraints\nlimiting its application. In order to apply \\verb+WHILE_INDUCTION+,\nthe instantiations for \\verb+B+ and \\verb+C+ must be known before\na wellfounded relation for \\verb+R+ is found and used to eliminate the\nconstraints.\n%\n\\begin{hol}\n\\begin{verbatim}\n   WHILE_INDUCTION\n     |- !B C R.\n          WF R /\\ (!s. B s ==> R (C s) s) ==>\n          !P. (!s. (B s ==> P (C s)) ==> P s) ==> !v. P v\n\\end{verbatim}\n\\end{hol}\n%\nA more refined level of support is provided by the standard Hoare\nLogic \\holtxt{WHILE} rule, phrased in terms of Hoare triples\n(\\holtxt{HOARE\\_SPEC}).\n%\n\\begin{hol}\n\\begin{verbatim}\n   HOARE_SPEC_DEF\n     |- !P C Q. HOARE_SPEC P C Q = !s. P s ==> Q (C s)\n   WHILE_RULE\n     |- !R B C.\n           WF R /\\ (!s. B s ==> R (C s) s) ==>\n           HOARE_SPEC (\\s. P s /\\ B s) C P ==>\n           HOARE_SPEC P (WHILE B C) (\\s. P s /\\ ~B s)\n\\end{verbatim}\n\\end{hol}\n%\nAs a follow-on, an operator for finding the least number with property\n\\verb+P+ is defined.\n%\n\\begin{hol}\n\\begin{verbatim}\n   LEAST_DEF  |- !P. $LEAST P = WHILE ($~ o P) SUC 0\n\\end{verbatim}\n\\end{hol}\n%\nA few theorems for reasoning about \\holtxt{LEAST} may be found in\ntheory \\theoryimp{while}.\n\n\n%\\section{Partial orders}\n\n\\section{Further Theories}\nOther theories of interest in \\HOL{} are listed and briefly described\nin Figure~\\ref{fig:further-hol-theories}.\n\n\\begin{figure}[hbtp]\n\\renewcommand{\\arraystretch}{1.5}\n\\begin{tabular}{|p{0.2\\textwidth}p{0.7\\textwidth}|}\n  \\hline\n  \\theoryimp{poset} & Partial Orders, Knaster-Tarski theorem\n  \\\\\n  \\theoryimp{divides}, \\theoryimp{gcd} &\n  Divisibility and the greatest common divisor.\n  \\\\\n  \\theoryimp{poly} &\n  A theory of polynomials over $\\mathbb{R}$, providing\n  a collection of operations on polynomials, and theorems about them.\n  \\\\\n  \\theoryimp{Temporal\\_Logic},\\newline \\theoryimp{Omega\\_Automata}\n  &\n  Klaus Schneider's development of temporal logic and\\newline $\\omega$-automata.\n  \\\\\n  \\theoryimp{ctl}, \\theoryimp{mu}\n  &\n  Computation Tree Logic and the $\\mu$-calculus. See Hasan Amjad's\n  thesis. \\\\\n  \\theoryimp{lbtree} & Possibly infinitely deep (\\ie, co-algebraic) binary trees.\\\\\n  \\theoryimp{inftree} & Possibly infinitely branching, algebraic trees\\\\\n  \\hline\n\\end{tabular}\n\\caption{A selection of \\HOL{} theories}\n\\label{fig:further-hol-theories}\n\\end{figure}\n\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: \"description\"\n%%% End:\n", "meta": {"hexsha": "4eeb035a66bd0df03b482692ce25b25e22d45a8c", "size": 179892, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Manual/Description/theories.tex", "max_stars_repo_name": "jeremydaw/HOL", "max_stars_repo_head_hexsha": "c4cbc5cadd6a8ce9bafae60077c359c60764f72f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Manual/Description/theories.tex", "max_issues_repo_name": "jeremydaw/HOL", "max_issues_repo_head_hexsha": "c4cbc5cadd6a8ce9bafae60077c359c60764f72f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Manual/Description/theories.tex", "max_forks_repo_name": "jeremydaw/HOL", "max_forks_repo_head_hexsha": "c4cbc5cadd6a8ce9bafae60077c359c60764f72f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3529900332, "max_line_length": 568, "alphanum_fraction": 0.6766004047, "num_tokens": 58701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.3117290243970687}}
{"text": "% !TEX root = thesis.tex\n\\documentclass[thesis]{subfiles}\n\n\\begin{document}\n\\chapter[Co-adaption in Deep Neural Networks]{Co-adaption in\\texorpdfstring{\\\\}{ }Deep Neural Networks}\\label{pairablation}\nAs discussed in \\cref{optimizationlink}, there is a link between structural priors and a failure in our current optimization methods. Dropout\\index{dropout} in particular seems like it may have a link to structural priors given that it is claimed to be randomly sampling `thinner' network architectures composed of subsets of the neurons from the model. It can also be argued, as we will demonstrate, that dropout is an optimization trick rather than a form of regularization. Here we will present work that, while not being substantial enough for publication, may provide an interesting insight into the problem of `co-adaption' as discussed by \\citet{Hinton2012} and the mechanism of dropout.\n\n\\section{The Limitations of First Order Optimization}\nWith the increasing number of practical applications of deep learning, the optimization of deep neural networks is of critical importance, with generalization, accuracy and training time all direct consequences. Due to practical considerations of training large state-of-the-art models with limited computational resources, network optimization is restricted to first order methods in practice -- typically stochastic gradient descent with momentum. With breakthroughs in initialization~\\citep{glorot2010understanding,He2015b} and maintenance of numerical precision during training~\\citep{Ioffe2015} alleviating the `vanishing gradient' problem, such methods have surpassed human accuracy on large scale image recognition datasets, amongst other breakthrough results. This success has overshadowed any weakness of the current methods of training deep networks.\n\nThere has been much evidence to suggest that the optimization of deep networks remains a concern however. \\citet{NIPS2014_5484} showed that shallow networks could be regressed from deep networks, and claim that the success of deep networks could be explained by our inability to properly train shallow networks from scratch. More recently, \\citet{He2015,He2016} in particular have shown that the optimization of very deep networks can expose fundamental optimization issues where training loss \\emph{increases} for deeper networks, whereas even the trivial solution to maintain training loss --- the identity mapping --- is not discovered by the optimization. They suggest a work-around for this problem is to utilize residual layers, incorporating the identity explicitly. Why the optimization fails so spectacularly without identity connections remains unexplained however.\n\n\\citet{martens2010deep} suggests that `pathological curvature (see \\cref{pathological}) is a possible explanation for the difficulty of training deep networks. For some networks, the error surface can have a complex curvature  and the solution is to use a second order optimization, proposing a more efficient method, `Hessian-free' optimization.\n\nIn this \\namecref{pairablation} we will demonstrate that some of the contemporary issues in training deep networks may be explained as being caused by this pathological curvature in the high dimensional error surfaces, and our use of first-order optimization methods. We will show that in particular dropout, which has empirically been shown to improve generalization in deep networks can also be explained in this light, and why this improvement diminishes in the presence of batch normalization\\index{batch normalization}, as observed by \\citet{Ioffe2015}.\n% - can't learn identity, because this would have many neurons with close distance! like in \\citet{martens2010deep}, this results in bad curvature\n\n\\section{Co-adpation of Hidden Units in Deep Networks}\n\\citet{dropout,dropoutjmlr} proposed dropout as a regularization method for neural networks. In randomly dropping out hidden units --- zeroing out a random subset on each layer --- it was claimed that complex co-adaptions of these hidden units on training data, which do not generalize to the test set, are prevented. In practice dropout has seen remarkable success in improving the generalization of large neural networks, especially in the context of large fully-connected layers. Several follow-up methods have similarly suggested alternative methods of preventing this co-adaption~\\citep{Cogswell2016}.\n\nAlthough empirically dropout works well, the claim that hidden units learn to co-adapt has not itself been well demonstrated, and seemingly straightforward methods of doing have serious drawbacks. Showing the covariance/correlation between pairs of hidden units doesn't give the full story, since covariance shows the linear relationship between the units, but in a deep network this relationship is likely to be highly non-linear. Mutual information cannot be used either since most modern networks need to use unbounded activation functions, such as \\glspl{relu}, in order to train effectively.\n\nA crude but effective method of analyzing the importance of hidden units in neural networks is ablation -- zeroing out certain units in a trained network of interest, and observing the effect on the training and test loss. This method can be extended to empirically evaluate the importance of pairs of hidden units in trained neural networks. For each pair of hidden units, zero out the parameters of both units, and observe the effect on the loss calculated over the training/test set: pairwise ablation. This is however very expensive since each pair of hidden units must be evaluated over the entire dataset.\n\nWe will focus on layer-wise filter co-dependence, and thus only needed to evaluate the pairwise ablation within each layer. In addition for large datasets, such as \\gls{ilsvrc}2012~\\citep{ILSVRC2015}, a random subset of the dataset was evaluated.\n\n\\paragraph{ResNet-50}\n\\Cref{fig:resnet50ablation_conv1_top5} shows the results of pairwise ablation on a \\gls{resnet}\\index{ResNet}-50 \\citet{He2015} network trained on \\gls{ilsvrc}2012, on both the training set (\\cref{fig:resnet50ablation_conv1_top5_train}) and validation set (\\cref{fig:resnet50ablation_conv1_top5_test}).\n\n\\begin{figure}[tbp]\n\\begin{subfigure}[b]{0.33\\textheight}\n\\centering\n\\begin{tikzpicture}\n\\begin{axis}[\n    height=0.27\\textheight,\n    axis equal image,\n%    axis lines=none,\n    enlargelimits=false,\n    %colorbar,\n    %colorbar style={\n    %    yticklabel={\\pgfmathprintnumber\\tick\\,\\%},\n    %    yticklabel style={font=\\footnotesize}\n    %},\n%    colormap name={Paired-12},\n    %colormap name={RdYlBu-9},\n    baseline,\n    scale only axis,\n    xmax = 64,\n    xmin = 0,\n    ymax = 64,\n    ymin = 0,\n]\n%\\addplot[surf,\n%    view={0}{90},\n\\addplot [\n    matrix plot*,\n    point meta=explicit,\n    point meta min=-1.6E-02,\n    point meta max=1.0E-02,\n] file [\n    x index=0,\n    y index=1,\n    meta index=2,\n]{ablationdata/resnet50/ablation_train_top5_conv1_square.dat};\n\\end{axis}\n\\end{tikzpicture}\n\\caption{Top-5 training acc.\\ diff.\\ for filter pairs}\n\\label{fig:resnet50ablation_conv1_top5_train_hist}\n\\end{subfigure}\n\\begin{subfigure}[b]{0.33\\textheight}\n\\centering\n\\begin{tikzpicture}\n\\begin{axis}[\n    height=0.27\\textheight,\n    axis equal image,\n%    axis lines=none,\n    enlargelimits=false,\n    colorbar,\n    colorbar style={\n        yticklabel={\\pgfmathprintnumber\\tick\\,\\%},\n        yticklabel style={font=\\footnotesize\\sffamily\\sansmath}\n    },\n    %colormap name={RdYlBu-9},\n    baseline,\n    scale only axis,\n    xmax = 64,\n    xmin = 0,\n    ymax = 64,\n    ymin = 0,\n]\n%\\addplot[surf,\n%    view={0}{90},\n\\addplot [\n    matrix plot*,\n    point meta=explicit,\n    point meta min=-1.6E-02,\n    point meta max=1.0E-02,\n] file [\n    x index=0,\n    y index=1,\n    meta index=2,\n]{ablationdata/resnet50/ablation_test_top5_conv1_square.dat};\n\\end{axis}\n\\end{tikzpicture}\n\\caption{Top-5 validation acc.\\ diff.\\ for filter pairs}\n\\label{fig:resnet50ablation_conv1_top5_test_hist}\n\\end{subfigure}\\\\\n\\begin{subfigure}[c]{0.47\\textwidth}\n\\centering\n\\includegraphics[height=0.23\\textheight]{resnet50histtrain}\n\\caption{Histogram of change in top-5 train.\\ acc.}\n\\label{fig:resnet50ablation_conv1_top5_train}\n\\end{subfigure}\n\\hfill\n\\begin{subfigure}[c]{0.47\\textwidth}\n\\centering\n\\includegraphics[height=0.24\\textheight]{resnet50histtest}\n\\caption{Histogram of change in top-5 val.\\ acc.}\n\\label{fig:resnet50ablation_conv1_top5_test}\n\\end{subfigure}\n\n%\\input{resnet50fig.tex}\n\\caption[Pairwise filter ablations in ResNet 50]{Histogram of the change in top-5 accuracy for all pairwise filter ablations of a 2500 randomly sampled images from the \\glsfmttext{ilsvrc} training/validation set in \\texttt{conv1} of \\glsfmttext{resnet}\\index{ResNet}-50.}\n\\label{fig:resnet50ablation_conv1_top5}\n\\end{figure}\n\nWhile, as expected, most pairwise ablations result in a decrease in accuracy, a small but significant number of pairwise ablations result in an \\emph{increase} in accuracy (and decrease in loss). For the validation set this seems to provide clear evidence of hidden units co-adapting, and hence overfitting to the training data. Surprisingly however, this effect is also evident when evaluating on the training set, and by definition cannot be explained by overfitting. We observed similar effects on all other layers of the network.\n\n\\paragraph{\\Gls{mnist}} This effect is not limited to large state-of-the-art deep networks, or indeed even deep networks. Surprisingly this effect is reproducible with a minimal single hidden-layer \\gls{mnist} network. With a fully-connected network with one hidden layer, \\gls{relu} activation functions, and a variety of optimization methods, we find that this co-adaption is still present above a minimal number of hidden units.  \n\\begin{figure}[tbp]\n\\begin{subfigure}[b]{0.95\\linewidth}\n\\centering\n\\begin{tikzpicture}\n% \\begin{axis}[\n%     axis x line=bottom,\n%     axis y line=left,\n%     \\setplotcyclecat{5},\n%     scale only axis,\n%     width=0.8\\linewidth,\n%     height=0.16\\textheight,\n%     ylabel={$\\max\\left(-\\Delta L\\right)$},\n%     xmin = 10,\n%     xmax = 300,\n%     ymode=log,\n% %    xmode=log,\n%     legend columns=-1,\n%     legend style={at={(0.5,1.1)},anchor=south,text depth=.5ex},\n% ]\n% \\addplot +[mark=none] table [x index=0, y expr=-\\thisrowno{1}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-stats_train_loss.log};\n% \\addplot +[mark=none] table [x index=0, y expr=-\\thisrowno{1}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-momentum-stats_train_loss.log};\n% \\addplot +[mark=none] table [x index=0, y expr=-\\thisrowno{1}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-wd-stats_train_loss.log};\n% \\addplot +[mark=none] table [x index=0, y expr=-\\thisrowno{1}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-dropout-stats_train_loss.log};\n% \\addplot +[mark=none] table [x index=0, y expr=-\\thisrowno{1}, col sep=comma]{ablationdata/mnist/hessianfree-ablate-mnist-stats_train_loss.log};\n% \\legend{\\gls{sgd}, momentum, weight decay, dropout, HF}\n% \\end{axis}\n\\begin{axis}[\n    axis y line=left,\n    axis x line=bottom,\n    % axis x line=none,\n    \\setplotcyclecat{5},\n    scale only axis,\n    width=0.8\\linewidth,\n    height=0.14\\textheight,\n    xlabel={Hidden Units},\n    ylabel={$\\max\\left(\\Delta L\\right)$},\n    xmin = 10,\n    xmax = 300,\n    ymode=log,\n%    xmode=log,,\n     legend columns=-1,\n     legend style={at={(0.5,1.1)},anchor=south,text depth=.5ex},\n]\n\\addplot +[mark=none] table [x index=0, y expr=\\thisrowno{2}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-stats_train_loss.log};\n\\addplot +[mark=none] table [x index=0, y expr=\\thisrowno{2}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-momentum-stats_train_loss.log};\n\\addplot +[mark=none] table [x index=0, y expr=\\thisrowno{2}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-wd-stats_train_loss.log};\n\\addplot +[mark=none] table [x index=0, y expr=\\thisrowno{2}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-dropout-stats_train_loss.log};\n%\\addplot +[mark=none] table [x index=0, y expr=\\thisrowno{2}, col sep=comma]{ablationdata/mnist/hessianfree-ablate-mnist-stats_train_loss.log};\n\\legend{\\gls{sgd}, momentum, weight decay, dropout, HF}\n\\end{axis}\n\\end{tikzpicture}\n\\caption{Training loss change: maximum increase}\n%Maximum decrease (solid/left axis), and maximum increase (dotted/right axis).}\n\\label{fig:mnist_ablation_train_loss}\n\\end{subfigure}\n\\begin{subfigure}[b]{0.95\\linewidth}\n\\centering\n\\begin{tikzpicture}\n% \\begin{axis}[\n%     axis y line=left,\n%     axis x line=bottom,\n%     \\setplotcyclecat{5},\n%     scale only axis,\n%     width=0.8\\linewidth,\n%     height=0.16\\textheight,\n%     xlabel={Hidden Units},\n%     ylabel={$\\max\\left(\\Delta \\textrm{Acc.}\\right)$},\n%     xmin = 10,\n%     xmax = 300,\n%     ymode=log,\n% %    xmode=log,\n% ]\n% \\addplot +[mark=none] table [x index=0, y expr=\\thisrowno{2}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-stats_train_acc.log};\n% \\addplot +[mark=none] table [x index=0, y expr=\\thisrowno{2}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-momentum-stats_train_acc.log};\n% \\addplot +[mark=none] table [x index=0, y expr=\\thisrowno{2}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-wd-stats_train_acc.log};\n% \\addplot +[mark=none] table [x index=0, y expr=\\thisrowno{2}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-dropout-stats_train_acc.log};\n% \\addplot +[mark=none] table [x index=0, y expr=\\thisrowno{2}, col sep=comma]{ablationdata/mnist/hessianfree-ablate-mnist-stats_train_acc.log};\n% \\end{axis}\n\\begin{axis}[\n    axis y line=left,\n    axis x line=bottom,\n    % axis x line=none,\n    \\setplotcyclecat{5},\n    scale only axis,\n    width=0.8\\linewidth,\n    height=0.14\\textheight,\n    xlabel={Hidden Units},\n    ylabel={$\\max\\left(-\\Delta \\textrm{Acc.}\\right)$},\n    xmin = 10,\n    xmax = 300,\n    ymode=log,\n%    xmode=log,\n]\n\\addplot +[mark=none] table [x index=0, y expr=-\\thisrowno{1}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-stats_train_acc.log};\n\\addplot +[mark=none] table [x index=0, y expr=-\\thisrowno{1}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-momentum-stats_train_acc.log};\n\\addplot +[mark=none] table [x index=0, y expr=-\\thisrowno{1}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-wd-stats_train_acc.log};\n\\addplot +[mark=none] table [x index=0, y expr=-\\thisrowno{1}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-dropout-stats_train_acc.log};\n%\\addplot +[mark=none] table [x index=0, y expr=-\\thisrowno{1}, col sep=comma]{ablationdata/mnist/hessianfree-ablate-mnist-stats_train_acc.log};\n\\end{axis}\n\\end{tikzpicture}\n\\caption{Training accuracy: maximum decrease}\n%Maximum increase (solid/left axis), and maximum decrease (dotted/right axis).}\n\\label{fig:mnist_ablation_train_acc}\n\\end{subfigure}\n\\begin{subfigure}[b]{0.95\\linewidth}\n\\centering\n\\begin{tikzpicture}\n% \\begin{axis}[\n%     axis y line=left,\n%     axis x line=bottom,\n%     \\setplotcyclecat{5},\n%     scale only axis,\n%     width=0.8\\linewidth,\n%     height=0.16\\textheight,\n%     xlabel={Hidden Units},\n%     ylabel={$\\max\\left(-\\Delta L\\right)$},\n%     xmin = 10,\n%     xmax = 300,\n%     ymode=log,\n% %    xmode=log,\n% ]\n% \\addplot +[mark=none] table [x index=0, y expr=-\\thisrowno{1}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-stats_test_loss.log};\n% \\addplot +[mark=none] table [x index=0, y expr=-\\thisrowno{1}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-momentum-stats_test_loss.log};\n% \\addplot +[mark=none] table [x index=0, y expr=-\\thisrowno{1}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-wd-stats_test_loss.log};\n% \\addplot +[mark=none] table [x index=0, y expr=-\\thisrowno{1}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-dropout-stats_test_loss.log};\n% \\addplot +[mark=none] table [x index=0, y expr=-\\thisrowno{1}, col sep=comma]{ablationdata/mnist/hessianfree-ablate-mnist-stats_test_loss.log};\n% \\end{axis}\n\\begin{axis}[\n    axis y line=left,\n    axis x line=bottom,\n    % axis x line=none,\n    \\setplotcyclecat{5},\n    scale only axis,\n    width=0.8\\linewidth,\n    height=0.14\\textheight,\n    xlabel={Hidden Units},\n    ylabel={$\\max\\left(\\Delta L\\right)$},\n    xmin = 10,\n    xmax = 300,\n    ymode=log,\n%    xmode=log,\n]\n\\addplot +[mark=none] table [x index=0, y expr=\\thisrowno{2}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-stats_test_loss.log};\n\\addplot +[mark=none] table [x index=0, y expr=\\thisrowno{2}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-momentum-stats_test_loss.log};\n\\addplot +[mark=none] table [x index=0, y expr=\\thisrowno{2}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-wd-stats_test_loss.log};\n\\addplot +[mark=none] table [x index=0, y expr=\\thisrowno{2}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-dropout-stats_test_loss.log};\n%\\addplot +[mark=none] table [x index=0, y expr=\\thisrowno{2}, col sep=comma]{ablationdata/mnist/hessianfree-ablate-mnist-stats_test_loss.log};\n\\end{axis}\n\\end{tikzpicture}\n\\caption{Test loss: maximum increase}\n%Maximum decrease (solid/left axis), and maximum increase (dotted/right axis).}\n\\label{fig:mnist_ablation_test_loss}\n\\end{subfigure}\n\\begin{subfigure}[b]{0.95\\linewidth}\n\\centering\n\\begin{tikzpicture}\n% \\begin{axis}[\n%     axis x line=bottom,\n%     axis y line=left,\n%     \\setplotcyclecat{5},\n%     scale only axis,\n%     width=0.8\\linewidth,\n%     height=0.16\\textheight,\n%     xlabel={Hidden Units},\n%     ylabel={$\\max\\left(\\Delta \\textrm{Acc.}\\right)$},\n%     xmin = 10,\n%     xmax = 300,\n%     ymode=log,\n% %    xmode=log,\n% ]\n% \\addplot +[mark=none] table [x index=0, y expr=\\thisrowno{2}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-stats_test_acc.log};\n% \\addplot +[mark=none] table [x index=0, y expr=\\thisrowno{2}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-momentum-stats_test_acc.log};\n% \\addplot +[mark=none] table [x index=0, y expr=\\thisrowno{2}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-wd-stats_test_acc.log};\n% \\addplot +[mark=none] table [x index=0, y expr=\\thisrowno{2}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-dropout-stats_test_acc.log};\n% \\addplot +[mark=none] table [x index=0, y expr=\\thisrowno{2}, col sep=comma]{ablationdata/mnist/hessianfree-ablate-mnist-stats_test_acc.log};\n% \\end{axis}\n\\begin{axis}[\n    axis y line=left,\n    axis x line=bottom,\n    % axis x line=none,\n    \\setplotcyclecat{5},\n    scale only axis,\n    width=0.8\\linewidth,\n    height=0.14\\textheight,\n    xlabel={Hidden Units},\n    ylabel={$\\max\\left(-\\Delta \\textrm{Acc.}\\right)$},\n    xmin = 10,\n    xmax = 300,\n    ymode=log,\n%    xmode=log,\n]\n\\addplot +[mark=none] table [x index=0, y expr=-\\thisrowno{1}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-stats_test_acc.log};\n\\addplot +[mark=none] table [x index=0, y expr=-\\thisrowno{1}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-momentum-stats_test_acc.log};\n\\addplot +[mark=none] table [x index=0, y expr=-\\thisrowno{1}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-wd-stats_test_acc.log};\n\\addplot +[mark=none] table [x index=0, y expr=-\\thisrowno{1}, col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-dropout-stats_test_acc.log};\n%\\addplot +[mark=none] table [x index=0, y expr=-\\thisrowno{1}, col sep=comma]{ablationdata/mnist/hessianfree-ablate-mnist-stats_test_acc.log};\n\\end{axis}\n\\end{tikzpicture}\n\\caption{Test accuracy: maximum decrease}\n%Maximum increase (solid/left axis), and maximum decrease (dotted/right axis).}\n\\label{fig:mnist_ablation_test_acc}\n\\end{subfigure}\n\\caption[Pairwise filter ablation for MNIST]{Maximum increase and decrease in training/test loss/accuracy for a single-layer hidden MNIST classification network under pairwise ablation of the hidden units. \n%Solid lines show the maximum decrease in loss or increase in accuracy for all pairs of neurons. \n%Dotted lines\nThe plots show the maximum increase in loss or decrease in accuracy. Both are measures of the level of neural co-adpation in the trained networks.}\\label{fig:mnist_ablation}\n\\end{figure}\n\\begin{figure}[tbp]\n\\begin{subfigure}[b]{0.95\\linewidth}\n\\centering\n\\begin{tikzpicture}\n\\begin{axis}[\n    ybar,\n    bar width=0.1,\n    axis x line=bottom,\n    axis y line=left,\n    \\setplotcyclecat{5},\n    scale only axis,\n    width=0.8\\linewidth,\n    height=0.3\\textheight,\n    xlabel={Hidden Units},\n    ylabel={\\% of pairwise units where $\\Delta L < 0$},\n    yticklabel=\\pgfmathprintnumber{\\tick}\\,\\%,\n    xmin = 10,\n    xmax = 100,\n%    ymode=log,\n%    xmode=log,\n    legend columns=-1,\n    legend style={at={(0.5,1.1)},anchor=south,text depth=.5ex},\n]\n\\addplot +[mark=none] table [x index=0, y expr=100*\\thisrowno{5} / (\\thisrowno{0}*\\thisrowno{0}), col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-stats_train_loss.log};\n\\addplot +[mark=none] table [x index=0, y expr=100*\\thisrowno{5} / (\\thisrowno{0}*\\thisrowno{0}), col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-momentum-stats_train_loss.log};\n\\addplot +[mark=none] table [x index=0, y expr=100*\\thisrowno{5} / (\\thisrowno{0}*\\thisrowno{0}), col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-wd-stats_train_loss.log};\n\\addplot +[mark=none] table [x index=0, y expr=100*\\thisrowno{5} / (\\thisrowno{0}*\\thisrowno{0}), col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-dropout-stats_train_loss.log};\n%\\addplot +[mark=none] table [x index=0, y expr=100*\\thisrowno{5} / (\\thisrowno{0}*\\thisrowno{0}), col sep=comma]{ablationdata/mnist/hessianfree-ablate-mnist-stats_train_loss.log};\n\\legend{\\gls{sgd}, momentum, weight decay\\index{weight decay}, dropout, HF}\n\\end{axis}\n\\end{tikzpicture}\n\\caption{Training Loss: Percentage of pairs of hidden units that exhibit adverse co-adaption.}\n\\label{fig:mnist_ablation_stats_train_loss_lt}\n\\end{subfigure}\n\\begin{subfigure}[b]{0.95\\linewidth}\n\\centering\n\\begin{tikzpicture}\n\\begin{axis}[\n    ybar,\n    bar width=0.1,\n    axis x line=bottom,\n    axis y line=left,\n    \\setplotcyclecat{5},\n    scale only axis,\n    width=0.8\\linewidth,\n    height=0.3\\textheight,\n    xlabel={Hidden Units},\n    ylabel={\\% of pairwise units where $\\Delta L = 0$},\n    yticklabel=\\pgfmathprintnumber{\\tick}\\,\\%,\n    xmin = 10,\n    xmax = 100,\n%    ymode=log,\n%    xmode=log,\n]\n\\addplot +[mark=none] table [x index=0, y expr=100*\\thisrowno{4} / (\\thisrowno{0}*\\thisrowno{0}), col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-stats_train_loss.log};\n\\addplot +[mark=none] table [x index=0, y expr=100*\\thisrowno{4} / (\\thisrowno{0}*\\thisrowno{0}), col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-momentum-stats_train_loss.log};\n\\addplot +[mark=none] table [x index=0, y expr=100*\\thisrowno{4} / (\\thisrowno{0}*\\thisrowno{0}), col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-wd-stats_train_loss.log};\n\\addplot +[mark=none] table [x index=0, y expr=100*\\thisrowno{4} / (\\thisrowno{0}*\\thisrowno{0}), col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-dropout-stats_train_loss.log};\n%\\addplot +[mark=none] table [x index=0, y expr=100*\\thisrowno{4} / (\\thisrowno{0}*\\thisrowno{0}), col sep=comma]{ablationdata/mnist/hessianfree-ablate-mnist-stats_train_loss.log};\n\\end{axis}\n\\end{tikzpicture}\n\\caption{Training Loss: Percentage of pairs of hidden units that are independent.}\n\\label{fig:mnist_ablation_stats_train_loss_eq}\n\\end{subfigure}\n% \\begin{subfigure}[b]{0.95\\linewidth}\n% \\centering\n% \\begin{tikzpicture}\n% \\begin{axis}[\n%     ybar,\n%     bar width=0.1,\n%     axis x line=bottom,\n%     axis y line=left,\n%     \\setplotcyclecat{5},\n%     scale only axis,\n%     width=0.8\\linewidth,\n%     height=0.16\\textheight,\n%     xlabel={Hidden Units},\n%     ylabel={\\% of pairwise units where $\\Delta L > 0$},\n%     yticklabel=\\pgfmathprintnumber{\\tick}\\,\\%,\n%     xmin = 10,\n%     xmax = 100,\n% %    ymode=log,\n% %    xmode=log,\n% ]\n% \\addplot +[mark=none] table [x index=0, y expr=100*\\thisrowno{6} / (\\thisrowno{0}*\\thisrowno{0}), col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-stats_train_loss.log};\n% \\addplot +[mark=none] table [x index=0, y expr=100*\\thisrowno{6} / (\\thisrowno{0}*\\thisrowno{0}), col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-momentum-stats_train_loss.log};\n% \\addplot +[mark=none] table [x index=0, y expr=100*\\thisrowno{6} / (\\thisrowno{0}*\\thisrowno{0}), col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-wd-stats_train_loss.log};\n% \\addplot +[mark=none] table [x index=0, y expr=100*\\thisrowno{6} / (\\thisrowno{0}*\\thisrowno{0}), col sep=comma]{ablationdata/mnist/chainer-mnist-ablate-dropout-stats_train_loss.log};\n% \\addplot +[mark=none] table [x index=0, y expr=100*\\thisrowno{6} / (\\thisrowno{0}*\\thisrowno{0}), col sep=comma]{ablationdata/mnist/hessianfree-ablate-mnist-stats_train_loss.log};\n% \\end{axis}\n% \\end{tikzpicture}\n% \\caption{Training Loss: Percentage of pairs of hidden units that are codependent.}\n% \\label{fig:mnist_ablation_stats_train_loss_gt}\n% \\end{subfigure}\n\\caption[Pairwise filter ablation counts for MNIST]{Number of pairs of hidden units in a single-layer hidden MNIST classification network which under ablation, are adversely dependent ($\\Delta L < 0$) or independent ($\\Delta L = 0$) for the training set.}\n\\label{fig:mnist_ablation_stats}\n\\end{figure}\n\\Cref{fig:mnist_ablation} shows the minimum and maximum increase in training loss/accuracy and test loss/accuracy for the MNIST network with different numbers of hidden units, when pairwise filters are ablated, as evaluated on the entire MNIST training/test sets. The effect of training with weight decay\\index{weight decay} dropout and momentum are also compared with vanilla \\gls{sgd}. Weight decay\\index{weight decay} and dropout are considered to be regularization methods, while momentum is an optimization trick that is intended to help avoid some issues of using a first order optimization --- it can help speed up learning in the presence of some types of pathological curvature that would otherwise lead to slow optimization or a poor local minima with vanilla \\gls{sgd}.\n\nIn \\cref{fig:mnist_ablation} momentum clearly helps avoid co-adaption as compared to vanilla \\gls{sgd}, where co-adaption is significant. Weight decay\\index{weight decay} on the other hand, does not seem to have a helpful effect on co-adaption, giving almost identical results to vanilla \\gls{sgd}. As a form of regularization, this might be expected, as it should help generalization, not training fit.\n\nTaken by itself, this observation suggests that co-adaption may be a symptom of an optimization problem, and thus an optimization trick like momentum helps while regularization does not. On the other hand, dropout seems to reduce the number of co-adapted units significantly, and is even effective at reducing co-adaption at \\emph{training time}. If dropout is a regularization method, then this seems to conflict with our findings with weight decay\\index{weight decay} and momentum.\n\n\\section{Dropout as an Optimization Trick}\\label{dropoutasopttrick}\nDropout can also be thought of as a orthogonal projection of the error surface onto a random lower-dimensional subspace, in which the curvature of the error surface may no longer exhibit pathological issues, and optimization may be easier. For example, if in a subset of the dimensions, a deep valley exists (as illustrated in \\cref{fig:pathological}), and these dimensions are dropped-out, first-order optimization will be substantially easier. Random projection is a well established method for dimensionality reduction of high dimensional spaces~\\citep{kaski1998dimensionality,fodor2002survey}.\nIf a layer has $N$ nodes, and a width matrix $W$, and input vector $x$, then dropout on the layer of $K/N$ nodes may be defined as the transformation:\n\\begin{equation}\n    \\textrm{dropout}(\\mathbf{W}) = \\mathbf{D}_{i} \\mathbf{W},\n\\end{equation}\nwhere $D$ is a diagonal binary matrix, with rank $K$, defining an orthogonal projection onto a $K$-dimensional subspace. \n\nTo demonstrate that it is this projection, rather than the zeroing out of neurons itself, that is responsible for performance improvements with dropout, we can instead perform a random projection in a different orthogonal co-ordinate basis, which does not dropout (zero) any neurons. To do this we can first rotate the parameters with random rotation matrix into a non-axis aligned co-ordinate basis, and perform dropout (orthogonal projection) in the rotated space, and then rotate back into the original co-ordinate basis:\n\\begin{equation}\n    \\textrm{dropproject}(\\mathbf{W}_l) = \\mathbf{R}^{-1}\\textrm{dropout}(\\mathbf{R} \\mathbf{W}_l),\n\\end{equation}\nfor a random rotation matrix $\\mathbf{R}\\in \\textrm{SO}_N$. This ``dropproject'' method avoids zeroing out any of the units, while still performing an equivalent projection as that in dropout.\n\n\\begin{figure}[tbp]\n\\begin{subfigure}[b]{0.95\\linewidth}\n\\centering\n\\begin{tikzpicture}\n\\begin{axis}[\n    thick,\n    \\setplotcyclecat{5},\n    scale only axis,\n    axis x line=bottom,\n    axis y line=left,\n    %axis line style={thick},\n    width=0.8\\linewidth,\n    height=0.14\\textheight,\n    xlabel={Epochs},\n    ylabel={Log Loss},\n    ymode=log,\n    legend columns=-1,\n    legend style={at={(0.5,1.1)},anchor=south,text depth=.5ex},\n]\n\\addplot +[mark=none] table [x=epoch, y expr=\\thisrow{main/loss}, col sep=comma]{ablationdata/dropproject/train_standard.csv};\n\\addplot +[mark=none] table [x=epoch, y expr=\\thisrow{main/loss}, col sep=comma]{ablationdata/dropproject/train_dropout.csv};\n\\addplot +[mark=none] table [x=epoch, y expr=\\thisrow{main/loss}, col sep=comma]{ablationdata/dropproject/train_dropproject.csv};\n\\addplot +[mark=none] table [x=epoch, y expr=\\thisrow{main/loss}, col sep=comma]{ablationdata/dropproject/train_dropproject10.csv};\n\\addplot +[mark=none] table [x=epoch, y expr=\\thisrow{main/loss}, col sep=comma]{ablationdata/dropproject/train_dropprojectrandom.csv};\n\\legend{\nstandard, \ndropout, \ndropproject,\nDP-Random 10,\nDP-Random}\n\\end{axis}\n\\end{tikzpicture}\n\\caption{CIFAR Training Log Loss}\n\\label{fig:cifar_dropproject_train_loss}\n\\end{subfigure}\n\\begin{subfigure}[b]{0.95\\linewidth}\n\\begin{tikzpicture}\n\\begin{axis}[\n    thick,\n    \\setplotcyclecat{5},\n    scale only axis,\n    axis x line=bottom,\n    axis y line=left,\n    %axis line style={thick},\n    width=0.8\\linewidth,\n    height=0.14\\textheight,\n    xlabel={Epochs},\n    ylabel={Log Loss},\n    ymode=log,\n%    ymax=1,\n    ymin=0,\n]\n\\addplot +[mark=none] table [x=epoch, y expr=\\thisrow{validation/main/loss}, col sep=comma]{ablationdata/dropproject/train_standard.csv};\n\\addplot +[mark=none] table [x=epoch, y expr=\\thisrow{validation/main/loss}, col sep=comma]{ablationdata/dropproject/train_dropout.csv};\n\\addplot +[mark=none] table [x=epoch, y expr=\\thisrow{validation/main/loss}, col sep=comma]{ablationdata/dropproject/train_dropproject.csv};\n\\addplot +[mark=none] table [x=epoch, y expr=\\thisrow{validation/main/loss}, col sep=comma]{ablationdata/dropproject/train_dropproject10.csv};\n\\addplot +[mark=none] table [x=epoch, y expr=\\thisrow{validation/main/loss}, col sep=comma]{ablationdata/dropproject/train_dropprojectrandom.csv};\n\\end{axis}\n\\end{tikzpicture}\n\\caption{CIFAR Test Log Loss}\n\\label{fig:cifar_dropproject_test_loss}\n\\end{subfigure}\n\\begin{subfigure}[b]{0.95\\linewidth}\n\\begin{tikzpicture}\n\\begin{axis}[\n    thick,\n    \\setplotcyclecat{5},\n    scale only axis,\n    axis x line=bottom,\n    axis y line=left,\n    %axis line style={thick},\n    width=0.8\\linewidth,\n    height=0.14\\textheight,\n    xlabel={Epochs},\n    ylabel={Training Error},\n%    ymax=1,\n%    ymin=0,\n]\n\\addplot +[mark=none] table [x=epoch, y expr=1-\\thisrow{main/accuracy}, col sep=comma]{ablationdata/dropproject/train_standard.csv};\n\\addplot +[mark=none] table [x=epoch, y expr=1-\\thisrow{main/accuracy}, col sep=comma]{ablationdata/dropproject/train_dropout.csv};\n\\addplot +[mark=none] table [x=epoch, y expr=1-\\thisrow{main/accuracy}, col sep=comma]{ablationdata/dropproject/train_dropproject.csv};\n\\addplot +[mark=none] table [x=epoch, y expr=1-\\thisrow{main/accuracy}, col sep=comma]{ablationdata/dropproject/train_dropproject10.csv};\n\\addplot +[mark=none] table [x=epoch, y expr=1-\\thisrow{main/accuracy}, col sep=comma]{ablationdata/dropproject/train_dropprojectrandom.csv};\n\\end{axis}\n\\end{tikzpicture}\n\\caption{\\Glsfmttext{cifar10} Training Error}\n\\label{fig:cifar_dropproject_train_acc}\n\\end{subfigure}\n\\begin{subfigure}[b]{0.95\\linewidth}\n\\begin{tikzpicture}\n\\begin{axis}[\n    thick,\n    \\setplotcyclecat{5},\n    scale only axis,\n    axis x line=bottom,\n    axis y line=left,\n    %axis line style={thick},\n    width=0.8\\linewidth,\n    height=0.14\\textheight,\n    xlabel={Epochs},\n    ylabel={Test Error},\n%    ymin = 0,\n]\n\\addplot +[mark=none] table [x=epoch, y expr=1-\\thisrow{validation/main/accuracy}, col sep=comma]{ablationdata/dropproject/train_standard.csv};\n\\addplot +[mark=none] table [x=epoch, y expr=1-\\thisrow{validation/main/accuracy}, col sep=comma]{ablationdata/dropproject/train_dropout.csv};\n\\addplot +[mark=none] table [x=epoch, y expr=1-\\thisrow{validation/main/accuracy}, col sep=comma]{ablationdata/dropproject/train_dropproject.csv};\n\\addplot +[mark=none] table [x=epoch, y expr=1-\\thisrow{validation/main/accuracy}, col sep=comma]{ablationdata/dropproject/train_dropproject10.csv};\n\\addplot +[mark=none] table [x=epoch, y expr=1-\\thisrow{validation/main/accuracy}, col sep=comma]{ablationdata/dropproject/train_dropprojectrandom.csv};\n\\end{axis}\n\\end{tikzpicture}\n\\caption{\\Glsfmttext{cifar10} Test Error}\n\\label{fig:cifar_dropproject_test_acc}\n\\end{subfigure}\n\\caption[Dropout \\vs dropproject for \\glsfmttext{vgg}/\\glsfmttext{cifar10}]{Training and test curves for a \\glsfmttext{vgg} network on \\glsfmttext{cifar10} comparing dropout to dropproject.}\n\\label{fig:cifar_dropproject}\n\\end{figure}\n\n\\Cref{fig:cifar_dropproject} compares the effect of dropout, and various forms of dropproject, on a large VGG model trained on the \\gls{cifar10}~\\citep{CIFAR10} dataset. Both dropout and dropproject are only applied to the two large fully-connected layers of the VGG network. With \\textbf{dropproject} (DP), one random rotation matrix is generated and used for the duration of training. For \\textbf{DP-Random10}, 10 random rotation matrices are generated and a single rotation matrix is randomly chosen from these for each mini-batch during training. Finally, \\textbf{DP-Random} generates a random rotation matrix for each mini-batch.\n\nBoth methods have close to identical effect on training loss/error, and are drastically different than the plots of the standard network without dropout/dropproject. At test time, both methods also achieve comparable minimum error, but in the loss curve it can be seen that dropproject appears to start overfitting earlier than dropout. While the projection (and not regularization) appears to be responsible for the increased generalization and speed of training, the zeroing out of units for dropout also has a small regularization effect not seen in dropproject. None of the variants of dropproject seem to be different, indicating that the random projection itself rather than the random rotation into a different co-ordinate basis is important for the effect.\n\n\\paragraph{Dropout and Batch Normalization}\nIt has been observed empirically by \\citet{Ioffe2015} and others that when used with batch normalization\\index{batch normalization}, dropout is not as effective. In light of our understanding of dropout as being an optimization method for error surfaces with highly complex curvature, we can explain this. As explained by~\\citep{martens2010deep}, an important property of second order optimization methods is `scale invariance' --- robustness to any linear rescaling of the model parameters. For example, if we are in an elliptically shaped local minima of the error surface, ideally we would want different a higher learning rate for parameters in the direction of the major axis, as compared to those in the direction of the minor axis, as RMSprop~\\citep{rmsprop} attempts. When using batch normalization\\index{batch normalization}, the layer-wise error surface is whitened, reducing the importance of scale-invariance in optimization, and any related optimization tricks.\n% \\mynote{Questions to answer:\n% \\begin{itemize}\n% \\item Do residual connections alleviate neural co-adaption?\n% \\item Learning identity mapping is difficult due to bad curvature, exact situation cited as example by \\citet{martens2010deep}.\n% \\item Is learning deep networks easier than learning wide networks because of neural co-adaption?\n% \\end{itemize}}\n\n\\end{document}\n", "meta": {"hexsha": "1b2bcf6d849c945967c65f1679f310061bfeb4ee", "size": 36613, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "coadaption.tex", "max_stars_repo_name": "yanii/phd-thesis", "max_stars_repo_head_hexsha": "8d21690458f77c0cfefcb6ba528d421a83408b0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-02-16T21:51:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T08:47:40.000Z", "max_issues_repo_path": "coadaption.tex", "max_issues_repo_name": "yanii/phd-thesis", "max_issues_repo_head_hexsha": "8d21690458f77c0cfefcb6ba528d421a83408b0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "coadaption.tex", "max_forks_repo_name": "yanii/phd-thesis", "max_forks_repo_head_hexsha": "8d21690458f77c0cfefcb6ba528d421a83408b0e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-02-16T21:52:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-03T09:19:46.000Z", "avg_line_length": 62.5863247863, "max_line_length": 974, "alphanum_fraction": 0.7493240106, "num_tokens": 10618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.31171026583597455}}
{"text": "\\section{Semantic simplification}\n\\label{sec-comp}\n\nThe subsections \\ref{sec-ss-intro}, \\ref{sec-ss-model} and \\ref{sec-ss-repr} \nof this section have been taken from \\cite{rww3}.\n\n\n\\subsection{Introduction}\n\\label{sec-ss-intro}\n\n{\\GF} is intended to express a variety of methods of human reasoning.\nThough the word \"reasoning\" usually connotes a logical deductive process of \nusing facts and assertions to obtain conclusions, much of human intelligence \nrelies more upon observation than upon deduction.\nWe look at a book. The book is seen to be \"green\", as an immediate observation,\nnot as a deduction involving, say, analysis of wavelengths of light and \nsensory receptors  in the eye. Similarly, humans cross streets without \nconscious analysis of the traffic flow, add numbers without resorting to basic\nset theory, and play chess without considering each move in terms of the \ngeometry of the board. \n\nAny system which hopes to express a variety of reasoning processes, therefore \nneeds a method of doing purely computational tasks.\nIn {\\GF}, the {\\bf semantic interpretation mechanism}, which provides this \nability, consists of two parts:\n\\begin{itemize}\n\\item {\\GF}'s {\\bf semantic attachment mechanism} permits the user to define a\n      ``correspondence'' between the various constants (function symbols,\n      predicate constants, individual constants) of the language and\n      corresponding objects of the programming language {\\HG}.\n\\item facts about the {\\HG} structure can be used directly in the proof\n      via the {\\bf semantic simplification mechanism}, eliminating the \n      necessity of a possibly complicated deduction.\n\\end{itemize}\nFor example, obvious attachments to the function symbol $+$ and to the \nindividual constants $17$, $34$, $51$ would allow to conclude $17+34=51$ in \none step, instead of computing $34$ successors of $17$.\nIn order to explain this more clearly we first give an informal account of the \ntechnical details.\n\n\\subsection{``Intended'' and ``computational'' models}\n\\label{sec-ss-model}\n\nThe declarations made by a {\\GF} user specify a first order language \n$L=\\langle P,F,C\\rangle$, where $P$ is the list of {\\predconst}s, $F$ the list \nof {\\funconst}s, and $C$ the list of {\\indconst}s (see section \\ref{sec-decl}).\n\nA model for such a language is a structure $M=\\langle D,P',F',C'\\rangle$ where\n$D$ is a set and $P'$,$F'$ and $C'$ are lists of predicates over $D$, functions \nover $D$, and individuals of $D$ such that the arities of the symbols in $P$ and \n$F$ match the arities of the predicates and functions at the correspondent \npositions in $P'$ and $F'$.\nThe idea here is that the language $L$ is used for making statements about \nstructures such as $M$ (what we call {\\bf ``intended'' or ``standard'' model}). \nIn particular, when the user writes down a theory in {\\GF}, he generally has \nin mind some particular model for his language, and the axioms of his theory \nare intended to express the properties of this particular model.\n\nThe fact that {\\GF} is really a {\\HG} program running in a LISP \nenvironment, inspires the following idea: some parts of a model for a {\\GF} \nlanguage can often be expressed computationally in the sense that the elements \nof $D$ can be represented by s-expressions, and the predicates and functions \non $D$ can be represented by {\\HG} functions and predicates.\nIt should then be possible to use the computational representation to aid \n{\\GF} deductions concerning the model.\nFor example, suppose the theory we are interested in, is first order number \ntheory, and the model that we have in mind is the set of natural numbers \ntogether with the operations of successor, addition and multiplication.\nThe numerals have natural representations as {\\HG} numbers, and the \nfunctions in question have {\\tt PLUS1}, {\\tt PLUS}, {\\tt TIMES} as their {\\HG}\ncounterparts.\nAs mentioned above it should then be possible to use the computational \nrepresentation to provide swift deductions of such statements as $25+37=52$.\n\nThe semantic attachment mechanism in {\\GF} allows the user to set up these \ncomputational representations of his subject matter, and the semantic\ninterpretation mechanism allows to use these representations to aid deduction \nin {\\GF}.\n\nWith the above overview in mind, let us proceed to the details.\n\nGiven a language $L=\\langle P,F,C\\rangle$ and a model \n$M=\\langle D,P',F',C'\\rangle$, we define an interpretation function $I$.\nFor each {\\term} $t$ of $L$ in which no free variable occurs, $I(t)$ is the \nindividual in $D$ which $t$ denotes.\nIn particular we define the interpretation of an {\\indconst} $c$ to be the \nindividual $c'$ in $D$, and where $f$ is a {\\funconst}, and the interpretation \nof {\\term} $t_1,\\ldots,t_n$ are defined, we inductively define the \ninterpretation of the {\\term} \n$f(t_1,\\ldots,t_n)$ to be $f'(I(t_1),\\ldots,I(t_n))$.\nWe may extend the interpretation function to formulas (again without free \nvariables) over $L$ by defining $I(w)$ to be the object {\\tt TRUE} exactly \nwhen the formula $w$ is true of the model (for a technical definition \nsee \\cite{kleene2}).\n\nWhen $f'$ is the function in a model corresponding to the {\\funconst} $f$ in \n$L$, we will also say that $f'$ is the interpretation of $f$, and similarly \nfor predconsts.\n\nNow we define a {\\bf computational model} to be an object\n$K=\\langle D',P'',F'',C''\\rangle$, where it is understood that $D'$ is a set\nof s-expressions, and $P''$, $F''$ and $C''$ are lists of {\\HG} predicates,\nfunctions and s-expressions respectively, with the appropriate restrictions on \narities.\n\nFrom the extensional point of view, a computational model is for a language\njust like a set-theoretic model for a language, except that we do not require\nthat the functions and predicates concerned be total; that is functions and\npredicates may be undefined (non-terminating) for some elements\nof $D'$.\n\nWe define an {\\bf attachment map} $att$ from terms and formulas of $L$ into\n$K$ in a manner exactly analogous to the definition of $I$ given above.\n\nWe have one last map to worry about, the map {\\bf $rep$} which gives, for each\nobject in the domain $D'$ of the computational model $K$, the object it\nrepresents in the domain $D$ of the model $M$.\n\nNow we may define precisely the meaning of attachments made in the {\\GF}\nsystem: the attachment of an {\\indconst} $c$ to an s-expression $c''$\nsignifies that $c$ and $c''$ represent the same object in the model, that is\nto say, $I(c)=rep(c'')$.\nSimilarly, the attachment of a {\\funconst} $f$ to a {\\HG} function $f''$\nsignifies that the result of applying $f''$ to an s-expression $c''$ which\nrepresents an individual $c'$ in the model, is a s-expression which represents\nthe individual $f'(c')$ in the model.\nThe analogous statements hold for attachments to {\\predconst}s.\n\nThe above conditions are equivalent to the statement that the \ndiagram in figure \\ref{fig-ss} commutes.\n\n\\begin{figure}[htb]\n\\begin{center}\n\\setlength{\\unitlength}{0.0125in}%\n\\begin{picture}(288,260)(92,540)\n\\thicklines\n\\put(340,580){\\oval(80,80)}\n\\put(160,580){\\oval(80,80)}\n\\put(160,760){\\oval(80,80)}\n\\put(200,580){\\vector( 1, 0){100}}\n\\put(194,726){\\vector( 1,-1){112}}\n\\put(160,720){\\vector( 0,-1){100}}\n\\put(340,559){\\makebox(0,0)[b]{\\raisebox{0pt}[0pt][0pt]{\\twlrm model}}}\n\\put(340,577){\\makebox(0,0)[b]{\\raisebox{0pt}[0pt][0pt]{\\twlrm of intended}}}\n\\put(340,595){\\makebox(0,0)[b]{\\raisebox{0pt}[0pt][0pt]{\\twlrm Domain }}}\n\\put(160,562){\\makebox(0,0)[b]{\\raisebox{0pt}[0pt][0pt]{\\twlrm sexpr}}}\n\\put(160,580){\\makebox(0,0)[b]{\\raisebox{0pt}[0pt][0pt]{\\twlrm {\\HG}}}}\n\\put(160,752){\\makebox(0,0)[b]{\\raisebox{0pt}[0pt][0pt]{\\twlrm Terms}}}\n\\put(160,770){\\makebox(0,0)[b]{\\raisebox{0pt}[0pt][0pt]{\\twlrm {\\GF}}}}\n\\put(250,560){\\makebox(0,0)[b]{\\raisebox{0pt}[0pt][0pt]{\\twlrm Representation}}}\n\\put(280,660){\\makebox(0,0)[b]{\\raisebox{0pt}[0pt][0pt]{\\twlrm I}}}\n\\put(120,660){\\makebox(0,0)[b]{\\raisebox{0pt}[0pt][0pt]{\\twlrm attachment}}}\n\\end{picture}\n\\end{center}\n\\label{fig-ss}\n\\caption{intended model - computational model mappings}\n\\end{figure}\n\n\n\\subsection{Multiple representation functions}\n\\label{sec-ss-repr} \n\nThe semantic attachment mechanism allows several representation of the model \nby {\\HG} s-expressions to be in force at the same time.\nWe will seek to motivate this aspect of the semantic attachment mechanism \nby means of an example: consider a theory of chess with includes a general \ntheory of lists as a subtheory (this subtheory would be applied in arguments \nabout lists of pieces, lists of game positions and so on).\nThe intended model of such a theory includes at least two kinds of objects: \nchess positions and lists.\nLists and positions form disjoint domains in the model, though it may be \npossible to build lists of chess position.\nIf we are going to build a computational representation of this model, we will\nneed to represent positions and lists by s-expressions in such a way that no \ns-expression represents both a list and a position.\nThe natural representation of a chess position as an s-expression is as a \nlist of eight lists, each of which is a list of eight piece names (one of \nwhich is \"empty\" or some such), and the natural representation of lists as \ns-expressions is the direct representation as {\\HG} lists.\nThis representation scheme cannot be used, since it will not be possible to \ndecide whether a given list of eight lists of eight piece names represents a \nchess board or a list of list of pieces. \nThat is to say, the map $rep$ will not be well defined. \nIt is of course not hard to solve this problem by the use of some slightly \nfancier coding, but a general solution to the problem of disambiguating \ncomputational representations is available.\nSuppose that the intended model of a {\\GF} theory $T$ includes the disjoint \ndomains $D_1,\\ldots,D_n$, and suppose further that we have a different coding \nfunction for each of these domains.\nThat is we have $n$ different {\\bf representation functions} $rep_i$ which map \nthe domain of s-expressions into domain of the model, with the property that \nthe range of $rep_i$ is a subset of $D_i$.\nThen it is possible that a single s-expression codes two different objects \n$d_i$, $d_j$ in the model, but as long as we know what coding function $rep_i$\nto apply, there is no ambiguity. \n\n\nThen the definition of the $att$ map may be extended to take account of the \npossibility of multiple representations in the following way: the domain of \nthe $att$ map will still consist of the set of {\\GF} terms and formulas, but\nits range will now lie in the set of pairs of the form $\\langle$ representation\nfunction, s-expression $\\rangle$.\n\nThe soundness condition for the $att$ map is now that, when \n$att(t)=\\langle rep, c'' \\rangle$, we have $rep(c'')=I(t)$.\nIn order to specify this new more complicated $att$ map, the user of the {\\GF}\nsystem must give representation information concerning his attachments.\n\nSpecifically, each representation function must be given a name and when the \nattachment to an {\\indconst} is given, the name of the associate \nrepresentation function must be given as well.\nSimilarly, when the attachment $f''$ to a {\\funconst} $f$ is specified, the \n(names of the) representations of its arguments and of the value it returns \nmust be given, and when the attachment to a {\\predconst} is specified, the \nrepresentations of its arguments must also be specified.\n\nThe significance of specifying that the representations of the arguments and \nvalue of the attachment $f''$ to a {\\funconst} $f$ are \n$R_1,\\ldots,R_n$ and $R_{n+1}$ respectively, is that \n$R_{n+1}(f''(c''_1,\\ldots,c''_n))=f'(R_1(c''_1),\\ldots,R_n(c''_n))$ \nwhere $f'$ is the interpretation of $f$, whenever $c''_1$,..,$c''_n$ are \ns-expressions in the domains of $R_1$,..,$R_n$.\nThe same holds for attachments to {\\predconst}, mutatis mutandis.\nGiven the attachments with representation information for individual symbols,\nthe map $att$ on the domain of terms and formulas is defined inductively in \nthe obvious way: if $f$ is attached to $f''$ and the declared representation \nof the arguments of $f''$ are $R_1,\\ldots,R_n$ and terms $t_1$,..,$t_n$ have \nattachments with representations $R_1$,..,$R_n$ then \n$att(f(t_1,\\ldots,t_n))=f''(att(t_1),\\ldots,att(t_n))$.\nUnder this definition the diagram above commutes for each individual \nrepresentation function.\n\nNote that if the representation of the attachment of any term $t_i$ does not \nmatch that of its place in the argument list, then \n$f''(att(t_1),\\ldots,att(t_n))$ cannot be expected to represent the \ninterpretation of $f(t_1,\\ldots,t_n)$.\nThe reason for this is that the correctness of a computation which purports to\nrepresent a mathematical function depends on the representation of the \narguments of the function as data objects.\nFor example, no one would expect a floating point multiplication algorithm to \nbehave correctly if its arguments were encoded as integers rather than \nfloating point numbers.\n\nFinally, note that the attachment map, as well as the s-expressions which \nrepresent functions, may be partial.\nThe user is never required to provide an attachment for any {\\GF} symbol, nor is\nany attachment to a {\\funconst} or {\\predconst} required to be complete.\n\nThe semantic simplification mechanism will use whatever information is \navailable and if there will be insufficient information, it will return this \nfact to the user. \n\n\n", "meta": {"hexsha": "3ff30447d861ce5cf33e40b6a495182f4d0032af", "size": 13406, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/user/eval/introsema.tex", "max_stars_repo_name": "getfol/GETFOL", "max_stars_repo_head_hexsha": "b861b00f2301b826f058010b42555789e2a9401d", "max_stars_repo_licenses": ["DOC", "Unlicense"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-08-25T01:02:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T05:17:17.000Z", "max_issues_repo_path": "doc/user/eval/introsema.tex", "max_issues_repo_name": "namin/GETFOL", "max_issues_repo_head_hexsha": "bf42caf61799578eb82e9f17b3342bc2ee638a22", "max_issues_repo_licenses": ["DOC", "Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/user/eval/introsema.tex", "max_forks_repo_name": "namin/GETFOL", "max_forks_repo_head_hexsha": "bf42caf61799578eb82e9f17b3342bc2ee638a22", "max_forks_repo_licenses": ["DOC", "Unlicense"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-04T19:04:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-04T19:04:40.000Z", "avg_line_length": 52.7795275591, "max_line_length": 81, "alphanum_fraction": 0.7472773385, "num_tokens": 3546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.31171026583597455}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\section*{Fri Jan 10 2020}\n\nWhy does the photon have two degrees of freedom? \n\nWe know that we can express \n%\n\\begin{align}\n\\vec{B} = \\nabla \\times \\vec{A} \\qquad \\text{and} \\qquad\n\\vec{E} = - \\vec{\\nabla} \\phi - \\pdv{}{t} \\vec{A} \n\\,,\n\\end{align}\n%\nand if we define the 4-vector \\(A^{\\mu } = (\\phi , \\vec{A})\\) then this potential is invariant under the gauge transformation \\(A_{\\mu } \\rightarrow A_{\\mu } + \\partial_{\\mu } \\xi\\) for any function \\(\\xi \\). \n\nThis is the defining property of electromagnetism! If we have a potential \\(A_{\\mu }\\) we can define the covariant derivative \\(D_{\\mu } = \\partial_{\\mu } + ie A_{\\mu }\\): then the Lagrangian is written as \n%\n\\begin{align}\n\\mathcal{L} = D_{\\mu } \\phi  D^{\\mu } \\phi^{*} - m^2 \\phi^2 - F_{\\mu \\nu } F^{\\mu \\nu }\n\\,,\n\\end{align}\n%\nand this field theory has \\(U(1)\\) symmetry, \\(\\phi \\rightarrow e^{i \\xi } \\phi \\), which corresponds to \\(A_{\\mu } \\rightarrow A_{\\mu } + \\partial_{\\mu } \\xi \\)! This is actually the defining property of electromagnetism in the QED formulation.\n\nSimilarly, GR follows from the invariance under a certain kind od gauge transformation: in this case, the gauge transformations are \\emph{diffeomorphisms} \\(x \\rightarrow x' (x)\\). \n\nIn electromagnetism, we have the 4 component for the potential, but we can fix the gauge by setting \\(\\partial_{\\mu }  A^{\\mu } = 0\\) and the residual gauge by setting \\(A^{0} = 0\\): then we are left with 2 degrees of freedom. \n\nThis is completely analogous to the way we found the graviton to have 2 degrees of freedom, that is, two polarizations. \n\nNow we discuss how we actually detected the presence of gravitons. \n\n\\subsection{Interferometric GW detection}\n\nGWs are detected interferometrically since interferometers are our most accurate way to measure distances. \n\nThe setup is a Michelson-Morley interferometer. \nCall \\(\\Delta L\\) the difference in the two paths the light takes, if \\(\\Delta L = n \\lambda \\) with \\(n \\in \\mathbb{N} \\) and \\(\\lambda \\) begin the wavelength of light, then we have perfectly constructive interference. \nIf instead \\(\\Delta L = (n + 1/ 2) \\lambda \\) we have perfectly destructive interference. \n\nIn actual GW experiments we will have \\(\\Delta L \\ll \\lambda \\), so we will not go from in-phase to counter-phase, but there will be a slight decrease of power, by which we will be able to detect the GW.\n\nWe take the mirrors to be suspended and free to move in the horizontal direction. So, for our purposes (to linear order in the displacement), the mirrors are free particles which move along geodesics. \n\nSo we have two mirrors at \\(\\vec{x}_{1} \\) and \\(\\vec{x}_{2}\\): let us say that the \\(x\\) axis is along their distance. \n\nThen, their distance will be given by \n%\n\\begin{align}\nd = \\int_{x_1 }^{x_2 } \\dd{x} \\sqrt{g_{11} }\n\\,.\n\\end{align}\n\nIn principle, the GW can change \\(d\\) by changing \\(x_1 \\) and \\(x_2 \\) and \\emph{also} by changing the metric element \\(\\sqrt{g_{11} }\\) in the space between them. \n\n\\begin{claim}\nThe effect of the change of the positions \\(x_1 \\) and \\(x_2 \\) is at most \\(\\mathcal{O}(h^2)\\). \n\\end{claim}\n\n\\begin{proof}\nFirst, let us assume that there is no GW and we have just one mirror in a fixed position in Minkowski spacetime. \nThen, the initial 4-velocity of the mirror (before the arrival of the GW) is \\(u^{\\alpha }_{\\tau =0} = [1, \\vec{0}]\\). \n\nThen, the GW arrives and the mirror will follow the geodesic equation: \n%\n\\begin{align}\n\\dv{ u^{\\alpha }  }{\\tau } + \\Gamma^{\\alpha }_{\\beta \\gamma } u^{\\beta } u^{\\gamma } = 0\n\\,.\n\\end{align}\n\nWe want to consider this at first order in \\(h\\). \nThe Christoffel sybols at order \\(h^{0}\\) are zero since in Minkowski spacetime there is no curvature. \n\nSo, if we want a nonzero first-order Christoffel term, we need to consider the zeroth order in the 4-velocity. \n\nThen, we are left with \\(u^{\\alpha } = u^{\\alpha }_{\\tau =0}\\), or \n%\n\\begin{align}\n\\dv{ u^{i }}{\\tau } = - \\Gamma^{i }_{00}\n\\,,\n\\end{align}\n%\nsince the \\(\\Gamma^{0}_{00}\\) is zero. Now we can compute \n%\n\\begin{align}\n\\Gamma^{i}_{00} = \\frac{1}{2} \\eta^{i \\lambda } \\qty(h_{\\lambda 0, 0} + h_{\\lambda 0,0} - h_{00 , \\lambda }) = 0 \n\\,,\n\\end{align}\n%\nbecause in our gauge \\(h_{0 \\mu } = 0\\). \n\\end{proof}\n\nA note: this is only true in our gauge. In other gauges, the result is the same but there is also a first-order contribution to the change in the distance between the mirrors from the change in their coordinate positions. \n\nWe set the mirrors at \\(\\vec{x}_{1}\\) and \\(\\vec{x}_{2} = \\vec{x}_{1} + T \\hat{L}_{12}\\), where \\(\\hat{L}_{12}\\) is a unit vector while \\(T\\) is the (unperturbed) travel time (or distance, since \\(c=1\\)) between the two mirrors. \n\nThe worldline of the laser light is given by \\(t = t_1 + \\lambda \\) and \\(\\vec{x} = \\vec{x}_{1} \\hat{L}_{12} \\lambda \\), for \\(\\lambda \\in [0,T]\\). \n\nThe photons move with \\(\\dd{s^2} =0\\), which means \n%\n\\begin{subequations}\n\\begin{align}\n0 &= - \\dd{t^2} + \\qty(\\delta_{ij} + h_{ij}) \\dd{x^{i}} \\dd{x^{j}}  \\\\\n&= - \\dd{t^2} + \\qty(\\delta_{ij} + h_{ij}) \\hat{L}_{12}^{i} \\hat{L}_{12}^{j} \\dd{\\lambda^2} \n\\,,\n\\end{align}\n\\end{subequations}\n%\nbut \\(\\hat{L}_{12}^{i} \\hat{L}_{12}^{j} \\delta_{ij} = 1\\) since it is a unit vector, so we get \n%\n\\begin{align}\n0 &= - \\dd{t^2} + \\qty(1 + \\hat{L}_{12}^{i} \\hat{L}_{12}^{j} h_{ij})  \\dd{\\lambda^2}\n\\,,\n\\end{align}\n%\nso we get \n%\n\\begin{subequations}\n\\begin{align}\n\\dd{t} &= \\sqrt{1 + \\hat{L}_{12}^{i} \\hat{L}_{12}^{j} h_{ij}} \\dd{\\lambda }  \\\\\n& \\approx \\qty(1 + \\frac{1}{2} \\hat{L}_{12}^{i} \\hat{L}_{12}^{j} h_{ij}) \\dd{\\lambda }\n\\,.\n\\end{align}\n\\end{subequations}\n\nSo, we need to evaluate this along the trajectory: we find \n%\n\\begin{align}\nT_{12} = \\int_{0}^{T} \\dd{\\lambda } \\qty(1 + \\frac{1}{2} \\hat{L}_{12}^{i} \\hat{L}_{12}^{j} \\sum _{r = +, \\times } h_{r} e_{ij, r} \\cos(k (t_1 + \\lambda t) - \\vec{k} \\cdot \\qty(\\vec{x}_{1} + \\hat{L}_{12} \\lambda )))\n\\,,\n\\end{align}\n%\nwhich just amounts to plugging in our expressions for \\(t\\) and \\(\\vec{x}\\) into the formula for \\(h_{ij} (t, \\vec{x})\\). \n\nWe set the phase to zero for brevity, a more general consideration will include it. \n\nThe first term is the unperturbed travel time  \\(T\\). Then, we can bring the constants outside the integral: \n%\n\\begin{align}\nT_{12} = T + \\frac{1}{2} \\hat{L}_{12}^{i} \\hat{L}_{12}^{j} \\sum _{r = +, \\times } h_{r} e_{ij, r}  \\int_{0}^{T} \\dd{\\lambda }  \\cos(k (t_1 + \\lambda ) - \\vec{k} \\cdot \\qty(\\vec{x}_{1} + \\hat{L}_{12} \\lambda ))\n\\,.\n\\end{align}\n\nNow, we can make an approximation which is applicable to ground-based interferometers: the \\emph{short-arm} approximation. The arguments of the cosine depend on \\(\\lambda \\), but we can assume \\(k \\lambda  < kT \\ll 1\\). This means that the travel time of the laser is much smaller than the period of the GW. Then, the cosine is approximately \\(\\lambda \\)-independent and can be brought outside of the integral. So we find \n%\n\\begin{align}\nT_{12} = T + \\frac{1}{2} \\hat{L}_{12}^{i} \\hat{L}_{12}^{j} \\sum _{r = +, \\times } h_{r} e_{ij, r} \\cos(k t_1 - \\vec{k} \\cdot \\vec{x}_{1}) T\n\\,.\n\\end{align}\n\nLet us justify the approximation: \\(k \\sim \\SI{100}{Hz}\\), while \\(L \\sim \\SI{4}{km}\\). So, \\(kT \\approx 2 \\pi \\times \\SI{4}{km} \\times \\SI{100}{km} / c \\approx \\num{8e-3}\\), which is small. \n\nWe have three points in the interferometer: \\(\\vec{x}_{1}\\) is the beamsplitter, \\(\\vec{x}_{2}\\) and \\(\\vec{x}_{3}\\) are the ends of the arms. We need to compute the difference between the times \\(\\vec{x}_{1} \\rightarrow \\vec{x}_{2} \\rightarrow \\vec{x}_{1}\\) and \\(\\vec{x}_{1} \\rightarrow \\vec{x}_{3} \\rightarrow \\vec{x}_{1}\\), repeated a few hundred times (the number of bounces of the beam is called the \\emph{finesse factor}). Let us just compute \\(\\Delta T = T_{12} - T_{13} \\) for a single ``bounce'', to see what the effect looks like. We actually compute \\(\\Delta T / T\\), in order to see what fraction of difference of travel time we are looking at. It will be given by \n%\n\\begin{align}\n\\frac{\\Delta T}{T} = \\cos(kt - \\vec{k} \\vec{x}) \\sum _{r = + , \\times } h_{r} e_{ij, r} \\frac{\\hat{L}_{12}^{i}\\hat{L}_{12}^{j} - \\hat{L}_{13}^{i}\\hat{L}_{13}^{j}}{2}\n\\,.\n\\end{align}\n\nWriting it this way is convenient, since we do not need to consider a single geometry: there are \\SI{90}{\\degree} interferometers such as LIGO, and \\SI{60}{\\degree} ones such as LISA, or the Einstein telescope. \n\nLet us say that \n%\n\\begin{align}\n\\hat{L}_{12} = [\\cos \\alpha , \\sin \\alpha , 0]^{\\top} \\qquad \\text{and} \\qquad \\hat{L}_{13} = [\\cos(\\alpha + \\pi /2), \\sin(\\alpha + \\pi /2) , 0]^{\\top}\n\\,.\n\\end{align}\n\nWe need to compute the following products: \n%\n\\begin{subequations}\n\\begin{align}\n\\hat{L}_{12}^{\\top} e_{+} \\hat{L}_{12} &= \\cos^2\\alpha - \\sin^2\\alpha = \\cos(2 \\alpha )\n\\\\\n\\hat{L}_{12}^{\\top} e_{ \\times } \\hat{L}_{12} &= 2 \\sin \\alpha \\cos \\alpha = \\sin(2 \\alpha )\n\\,,\n\\end{align}\n\\end{subequations}\n%\nand similarly for \\(\\hat{L}_{13} \\), where we can substitute \\(\\alpha \\rightarrow \\alpha + \\pi /2\\). We get: \n%\n\\begin{subequations}\n\\begin{align}\n\\frac{\\Delta T}{T} &= \\frac{1}{2} \\cos(kt - \\vec{k} \\cdot \\vec{x}) \nh_{+}\\qty(  \\qty(\\cos(2 \\alpha ) - \\cos(2 \\alpha  + \\pi ))) + \nh_{ \\times } \\qty(  \\qty(\\sin(2 \\alpha ) - \\sin(2 \\alpha  + \\pi )))  \\\\\n&= \\cos(kt - \\vec{k} \\cdot \\vec{x}) \\qty(\nh_{+}\\cos(2 \\alpha ) + \nh_{\\times} \\sin(2 \\alpha )) \\marginnote{Simplified factors of 2}\n\\,,\n\\end{align}\n\\end{subequations}\n%\nwhere we used the fact that \\(\\cos(x + \\pi ) = - \\cos(x)\\) and similarly for the sine.\n\nSo, this is a \\(\\mathcal{O}(h)\\) effect, with \\(h \\sim \\num{e-21}\\), which means \\(\\Delta L  \\sim \\SI{4}{km} \\times \\num{e-21} \\sim \\SI{4e-18}{m}\\). \n\nThe fact that we have many photons in the laser helps, and the fact that they bounce several times also does. \n\n\\end{document}", "meta": {"hexsha": "af941ab45c5b1c785d4e819cd5b892f80ccac2fb", "size": 9764, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ap_first_semester/general_relativity/10jan.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "ap_first_semester/general_relativity/10jan.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ap_first_semester/general_relativity/10jan.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 48.3366336634, "max_line_length": 678, "alphanum_fraction": 0.6428717739, "num_tokens": 3407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3117102658359745}}
{"text": "\\chapter{Community Detection using Node Attributes: A Non-Negative Matrix Factorization Approach.}\n\n\n\\section{Introduction}\n% no \\IEEEPARstart\nExploratory Data Analysis [E.D.A.] is a domain on the\nintersection of fields such as machine learning, pattern\nrecognition and information retrieval. The key goal of this\ndomain is to generate effective summarizations, visualizations,\ninformation discovery and retrievals from data with a goal of reducing the exponential\ncosts involved in its storage. The main task performed in E.D.A. is\nclustering analysis. Cluster analysis is a type of unsupervised\nlearning as cluster labels are not provided apriori or rather\nare implicit in the data itself. The term \"Cluster\" doesn't have a\nstandard definition and hence there is subjectivity in the\ndeciding what forms a \"Cluster\". This has led to proliferation in the literature of clustering algorithms. Distance based definition of clusters have been explored\nand have created a family of techniques such as partition\nbased clustering \\cite{aps:3} , hierarchical clustering \\cite{aps:4}, mixture\nmodel based clustering \\cite{aps:4}, fuzzy clustering \\cite{aps:8} amongst\nothers. In contrast to a line of previous work a second\ndefinition of clusters was proposed based on density, this\ncreated popular algorithms such as DBSCAN, OPTICS \\cite{aps:46}.\\\\\n\nA related field is Community Detection which involves\nidentification of latent groups of entities in data. These groups\ncorrespond to autonomous regions in the network which are known to have a higher\ndegree of homogeneity within its members than with members\nof other groupings in the same network. In Network sciences such sub\ngroups are called communities and these are identified using\nnetwork topology. A vast area of literature has uncovered\nseveral state of the art community detection algorithms that\naim to find such communities in un-directed as well as\ndirected graphs \\cite{aps:2} . This literature is based\non concepts related to Information Theory or the trajectory of Random walks\non graphs or the Map Equation \\cite{aps:10} \\cite{aps:9}. Apart from\nthis, community detection also developed a concept called\nmodularity and a new family of algorithms were developed\nthat detected communities in graphs by optimizing modularity in a greedy manner \\cite{aps:2} \\cite{aps:8}.\\\\\n\nLatent Dirichlet Allocation was another concept\nthat emerged and led to a new line of research on detecting\ncommunities by utilizing meta-data that is associated with\nthe entities (nodes). This led to novel techniques that utilized the\ninformation about network topology along with meta data\nfor obtaining generative models of networks \\cite{aps:52} \\cite{aps:51}. However even with such methods there\nwere drawbacks such as the limited applicability, as they\ncould not detect overlapping communities. A second drawback\nis that they assumed soft node-community memberships, which\nwas not appropriate for modeling communities because they\ndid not allow a node to have high membership strength to\nmultiple communities simultaneously. Finally, such methods\nhad a large time complexity and couldn't be scaled to graphs\nhaving more than 1000 nodes.\\\\\n\nNon negative matrix factorization of the\nterm document matrix was found to be effective in document\nclustering \\cite{aps:56}. NMF was later extended to clustering by\naiming to learn the adjacency matrix of a graph. NMF\nresearch did not pay attention to the interpretation of latent\nfactors which are used to find out the matrix. This led to\ndevelopment of BIGCLAM which aimed to learn latent\nfactors which the authors argued represented strengths of\ncommunity affiliations of nodes. BIGCLAM and NMF both\nused community affiliation knowledge of the nodes so that their membership strengths could be\nestimated. While most existing literature \\cite{aps:53}\nfocuses either on using the meta data or entity annotation for\nimproving the quality of community detection. \\\\\n\nThe paper is organized as follows. Section II briefly surveys\nrelated work. In Section III, the statistical model of the\napproach is defined, and in Section IV, the parameter fitting\nprocedure is provided in detail. This is followed by describing\nexperimental evaluation in Section V and the conclusion.\\\\\n\n\\section{Related Work}\n\nClustering approaches have their own biases in identifying\nclusters in data but none is considered a universal\nbest fit. For example, the objective function to be minimized\nin the k-partitioning algorithms is variance or $SSE$ i.e. Sum of Squared Distance. $  SSE = \\sum_{k=1}^{k} \\sum_{x_i \\epsilon c_k} \\left \\| x_i - c_k \\right \\| ^2 $ where $c_k$ = centroid of the cluster. In this case the clusters are convex\nbut the optimization function converges to a local optima as the objective\nfunction is non convex \\cite{aps:2}. Hierarchical\nClustering algorithms are a category of algorithms\nhaving a completely unsupervised approach to clustering.\nThey do not require the users to specify the number of clusters\nin advance and are broadly of two types: Agglomerative\nand divisive. To measure the dissimilarity between clusters\nobtained in hierarchical clustering, linkage methods were\ndeveloped with several popular techniques being listed in the\nliterature \\cite{aps:2} \\cite{aps:8} \\cite{aps:4}. But it difficult to decide on a suitable linkage method and at times the selection of a distance measure too isn't clear.\\\\\n\nFuzzy clustering (FCM) minimizes the objective function given as\n$\\sum_{j=1}^{k}\\sum_{x_i \\in C_j} u_{ij}^m (x_i - u_j)^2 $\n with $\\mu$ being the fuzzifier and\n$m$ defining the level of cluster fuzziness. The drawbacks seen in k-means such as non convex objective function, difficulty in detecting non linearly separable clusters etc. are also seen in FCM. The MST clustering\nalgorithm discussed in \\cite{aps:54} is known to be capable of\ndetecting clusters with irregular boundaries. Unlike traditional\nclustering algorithms, the MST clustering algorithm does\nnot assume a spherical shaped clustering structure of the\nunderlying data. If the\nnumber of clusters $k$ is given in advance, the simplest way to\nobtain $k$ clusters is to sort the edges of the minimum spanning\ntree in descending order of their weights, and remove the\nedges with the first $(k-1)$ heaviest weights. Undesired clustering\nstructures and an unnecessarily large number of clusters are\nproblems commonly faced by MST based clustering. \\\\\n\n\nIn \\cite{aps:45} Mixture Model based clustering is discussed which\nunlike the traditional clustering algorithms doesn't rely on\nheuristics but assumes that the data has been generated from\na mixture of multiple probability distributions (Gaussian or\nmultinomial) whose parameters have\nto be estimated. This is done using a technique called Expectation Maximization. Subspace clustering \\cite{aps:2} \\cite{aps:4} is based on key principle which\nis to discretize the data-space into grids and estimate the\ndensity by counting the number of points in a grid cell. Other\nmethods in the literature are Affinity propagation \\cite{aps:3} which is based on concept of message passing, Spectral clustering \\cite{aps:2}\nin which the ﬁrst $k$ eigenvectors $u_1,u_2,...,u_k$ corresponding to the $k$ smallest eigenvalues are computed to get matrix $U \\in R^{n*k}$ which has $u_1,u_2,...,u_k$ as columns. Then for $y_i \\in R^k$ which is the $i^{th}$ row of $U$, all rows are treated as points and clustered by k-means to get $k$ clusters. DB-SCAN,\nOPTICS are based on the concept of density and treat clusters\nare dense regions connected by less dense regions. However, none of this literature is applicable for clustering in networks.\\\\\n\nCommunity detection is a field that deals with\nobtaining coarse grained descriptions of large networks as real\nworld graphs are too large to be analyzed efficiently. \nThis is done by utilizing network topology to detect communities\nof nodes while ignoring node attributes. Topic Link LDA and Block LDA were the first to cluster graphs by jointly modeling links and node attributes. Topic\nlink LDA aims to quantify the effect of topic similarity\nand community similarity to the formation of a link \\cite{aps:52} \\cite{aps:51}.\nBlock LDA is a joint model of two components, with one\nthat models links between pairs of entities represented as\nedges in a graph with a block structure, and the second that\nmodels text documents, through shared latent topics. There\nhas also been limited work on combining graph and content\ninformation for community discovery leading to techniques\nsuch as CESNA and BIGCLAM. CESNA was for statistically\nmodeling the interaction between the network structure\nand the node attributes. The authors argued that this\nwould lead to more accurate community detection as well as\nimproved robustness in the presence of noise in the network\nstructure \\cite{aps:53}. BIGCLAM is another approach that detects\nboth 2-mode as well as cohesive communities which may\noverlap or be hierarchically nested and is based on affiliation\ngraph models.\\\\\n\nTo the best\nour knowledge, in the research no mention could be found\nof using the attributes of a data point for calculating the\nlatent features on the basis of which communities shall be\ndetected. The work in this paper is based on BIGCLAM framework but\nthe critical difference with existing techniques such as CESNA, AGMFIT and BIGCLAM is that attributes shall be used instead of community affiliations. The intuition here is that attributes are useful in determining the cluster affiliations and as such this intuition is also consistent with the phenomenon of \"homophily\" that is seen in human networks.\\\\\n\n\n\n\n\\section{Mathematical Model}\nThe stochastic generative model for generating communities\nis presented in this section in which the probability of two\nentities in data being present in the same community is\ndependent on the attributes or the annotated text data\nassociated with these nodes. An efficient model fitting\nprocedure is the presented which allows for detecting\ncommunities in the network. The current work is based on\nthe assumption that attributes of the data are categorical. The aim is to build upon BIGCLAM, an affiliation model for\ncommunity detection, however the objective is using attribute\ninformation in place of affiliation information for building a bipartite graph which will be partitioned.\\\\\n\n\\textbf{Directed Attribute Affiliation Model:} BIGCLAM and AGMFIT are build on the Affiliation Graph Model based algorithms which use Maximum Likelihood Estimation to create a AGM from the network. Both however ignore importance of attributed of the nodes being responsible for community\ncreation. In Social networks, Homophily is the tendency to be associated with\nothers who share similar preferences and therefore attribute\nassociated with the entity in a network play an important\nrole in deciding communities. The hypothesis of correlation\nbetween attributes and communities is reasonable as its\npresence is also seen in empirical evidence provided in\nthe literature \\cite{aps:53}. Based on this reasoning, a simple\nconceptual model called Directed Attribute Affiliation Model\nis formulated. This builds on the family of affiliation network\nmodels, but in this work affiliation models are extended to\nconsider attributes.\\\\\n\nTo represent node and attribute affiliation a bipartite\naffiliation graph is created where nodes are the bottom layer\nand attributes to which they belong are shown as the top\nlayer as seen in Fig.\\ref{fig 1}. A directed edge is created between an attribute and a node if the node has the attribute present in it. Such a bipartite graph can be constructed easily if attributes are binary valued. In case the attributes are continuous or categorical, a different mechanism might be needed. In this paper only binary attributes are considered. Cluster affiliation can then be modeled using such a\nbipartite graph where directed edges are formed between\nnodes and attributes to denote that those nodes contain\nthat attribute. \\\\\n\n\\begin{figure}[H]\n\\centering\n\\fbox{\\includegraphics[scale=0.5]{bap.PNG}}\n\\caption{Bipartite Attribute Affiliation Graph}\n\\label{fig 1}\n\\end{figure}\n\nA Bipartite Attribute Affiliation Graph is denoted as $B(X,C,M)$,\nwith $X$ as the nodes, $C$ as the attribute value and $M$ denotes\nthe directed edge from $X$ to $C$ if node $X$ has attribute\nvalue $C$. The problem now is to create a set of communities\n$S = S_1, S_2, ..., S_k$ given $B(X,C,M)$. A parameter $p_c$ is\nassigned to an attribute value $c \\in C$. This is for calculating\nthe probability that a node $x_i$ has the attribute value $c$. This\ncan also be called the probability that a node $x_i$ belongs to\nthe same community as another $x_j$ having the value of a\nparticular attribute as $c$. The $P_A(i, j)$ denotes that the nodes\n$i, j$ belong to the same community $A$. This can be shown by\nthe below equation.\n\n\\begin{equation}\nP_A(i,j) = 1 - \\prod_{c \\in M_i \\cap M_j} (1 - p_c)\n\\end{equation} \n\nWhere,\n\n\\begin{itemize}\n\\item $M_i$ = node $i$ has membership to attribute value $c$.\n\\item $M_j$ = node $j$ has membership to attribute value $c$.\\\\\n\\end{itemize}\n\nIn Eqn. 1, the value of $P_A(i, j)$ is set to $\\varepsilon$, following\nthe BIGCLAM procedure the value of $\\varepsilon$ can be set as\n$2|E|/|V|(|V| - 1)$ [21].\n\n\n\\subsection{Calculate the latent weights of the attributes}\n\nEvery attribute has its own importance or strength in\ndetermining the cluster to which the node should belong to,\nthis is denoted here formally as $F_{uC}$. This is the strength\nthat attribute $C$ has for node $u$ in determining its cluster.\nConsidering this membership strength the Eqn. 1 can be\nmodified as follows:\n\n\\begin{equation}\nP_A(i,j) = 1 - exp(-F_{uC}.F_{vC}^T)\n\\end{equation}\n\n$F_{uC}$ is the membership strength of a single attribute,\nsimilarly it is assumed that every node $i$ has a attribute\nmembership vector $F_i$ which contains the membership\nstrengths to all attributes in the data. The modified probability\nthat nodes $i, j$ now share a cluster is Eqn 2.\\\\\n\n\nThe intuition behind the above formula is simple, Consider\na node having attribute values same as the attribute values\nof another node, in such a case the likelihood of both\nnodes belonging to a particular community increases. This\nmeans that for each attribute a pair of nodes shares we\nget an independent chance of grouping the nodes. Thus,\nnaturally, the more attributes a pair of nodes shares, the\nhigher the probability of sharing the same community and\nbeing connected.\\\\\n\n\n \nIf $M_u \\cap M_v = 0$ then $P(u,v) = \\varepsilon$ this is done to consider\ncases where nodes might not share attributes but still are\nconnected. $F_u$ is the vector that denotes the strengths of\nassociation of a node $u$ with each attribute community in the network.\nThe task is to find the matrix of memberships $F$ that\nmaximizes the likelihood of generating the graph $G(V,E)$.\nThe log-likelihood of this is Eqn. 5. The Gradient update\nalgorithm is used to find the value of $F$ as shown in Eqn. 6 \\\\\n\n\\begin{equation}\nl(F) = \\sum_{u,v \\in E} log(1 - \\exp(-F_u.F_v^T)) - \\sum_{u,v \\notin E}(F_u.F_v^T)\n\\end{equation}\n\\begin{equation}\n\\bigtriangledown l(F_u) = \\sum_{v \\in N(u)} F_v \\frac{\\exp(-F_u.F_v^T)}{1 - \\exp(-F_u.F_v^T)} - \\sum_{v \\notin N(u)} F_v\n\\end{equation}\n\n\\textbf{Decide Community Affiliation:} The membership strengths\nmatrix $F$ is computed from above and the next step is to\ndetermine a suitable threshold above which it is possible to\ndetermine whether the node $i$ belongs to a community. This\nthreshold is $\\delta$ set at $\\sqrt{−log(1 - \\varepsilon)}$ [21]. The initialization\nisn't done using locally minimal neighborhoods approach of\nBIG-CLAM \\cite{aps:53} as entity annotated attributes are used to get\ninitial values of the membership strengths $F_i$. The value of\n$F_{i,k}$ is 0 if attribute $k$ is present and 0 if absent.\\\\\n\n$\\textbf{Choosing the number of communities:}$ This is done by\nprocedure specified in \\cite{aps:53} where the model is trained using\nan initial value of K. Then we detect K communities on the\n80\\% of node pairs and then evaluate the likelihood on the hold\nout set. The K with the best hold out likelihood is used.\\\\\n\n\\section{Experiments}\nIn this section, evaluation of the performance of the variant of BIG-CLAM and other state-of-the-art community detection methods is done. The data-set used in this work consists of an artificially generated network with node attributes created using the tool described in the work of  Christine Largeron \\textit{et. al.} \\cite{aps:55}. Community detection methods such as Louvain and Fastgreedy technique were not applied as the graph was directed.\n\n\\subsection{Dataset and Evaluation Criteria}\nThe Artificially generated data-set is described below. The comparison metrics used are Variation of information (VI), Normalized mutual information, Split-join distance, Rand index (RI) and Adjusted Rand index (ARI). NMI, RI and ARI are in the range (0 - 1) with higher value indicating better clustering. The split-join distance between partitions A and B is the sum of the projection distance of A from B and the projection distance of B from A and should be low. VI should also ideally have a low value.\n\n\\begin{table}[H]\n\\renewcommand{\\arraystretch}{1.3}\n\\caption{Description of the dataset}\n\\label{table}\n\\centering\n\\begin{tabular}{|c|c|c|}\n  \\hline\n\\multicolumn{1}{|c|}{\\textbf{Sr. No}} & \\multicolumn{1}{c|}{\\textbf{Parameter}} & \\multicolumn{1}{c|}{\\textbf{Value}} \\\\\n  \\hline\n  1 & Node Attributes &  3 \\\\\n   \\hline\n  2 & Nodes &  200 \\\\\n   \\hline\n  3 & Communities &  4 \\\\\n   \\hline\n  4 & Observed homophily &  0.74 \\\\\n   \\hline\n  5 & Modularity &  0.51 \\\\\n   \\hline\n  6 & Avg. Clustering Coeff &  0.33 \\\\\n   \\hline\n  7 & Avg. Degree &  5 \\\\\n   \\hline\n  8 & Edges &  500 \\\\\n   \\hline\n  9 & Network Type &  Directed-Unweighted \\\\\n  \\hline\n\\end{tabular}\n\\end{table}\n\n\\begin{figure}[H]\n\\centering\n\\fbox{\\includegraphics[scale=0.5]{dataset.png}}\n\\caption{Artificially generated Network dataset}\n\\end{figure}\n\n\\subsection{Experimental Results}\n\n\\subsubsection{InfoMap}\n\"infomap.community\" detected multiple communities in the network with few nodes leading to the conclusion that it split large clusters. The clustering is of poor quality as seen in Fig.\\ref{InfoMap} as observed in the performance metrics.\n\n\\begin{table}[H]\n\\renewcommand{\\arraystretch}{1.3}\n\\caption{Results}\n\\label{table}\n\\centering\n\\begin{tabular}{|c|c|c|}\n  \\hline\n\\multicolumn{1}{|c|}{\\textbf{Sr. No}} & \\multicolumn{1}{c|}{\\textbf{Parameter}} & \\multicolumn{1}{c|}{\\textbf{Value}} \\\\\n  \\hline\n  1 & Execution Time &  0.6 secs \\\\\n   \\hline\n  2 & Modularity &  0.567 \\\\\n   \\hline\n  3 & Variation of information &  1.72 \\\\\n   \\hline\n  4 & Normalized mutual information &  0.565 \\\\\n   \\hline\n  5 & Split-join distance &  115 \\\\\n   \\hline\n  6 & Rand index &  0.717 \\\\\n   \\hline\n  7 & Adjusted Rand index &  0.231 \\\\\n  \\hline\n   8 & Detected Communities &  22 \\\\\n  \\hline\n\\end{tabular}\n\\end{table}\n\n\\subsubsection{Leading Eigenvector}\n\"leading.eigenvector.community\" has uncovered a community structure with less communities as seen in Fig.\\ref{leadg} and its performance is good on the metrics. \n\n\\begin{table}[H]\n\\renewcommand{\\arraystretch}{1.3}\n\\caption{Results}\n\\label{table}\n\\centering\n\\begin{tabular}{|c|c|c|}\n  \\hline\n\\multicolumn{1}{|c|}{\\textbf{Sr. No}} & \\multicolumn{1}{c|}{\\textbf{Parameter}} & \\multicolumn{1}{c|}{\\textbf{Value}} \\\\\n  \\hline\n  1 & Execution Time &  0.53 secs \\\\\n   \\hline\n  2 & Modularity &  0.551 \\\\\n   \\hline\n  3 & Variation of information &  0.88 \\\\\n   \\hline\n  4 & Normalized mutual information &  0.67 \\\\\n   \\hline\n  5 & Split-join distance &  74 \\\\\n   \\hline\n  6 & Rand index &  0.795 \\\\\n   \\hline\n  7 & Adjusted Rand index &  0.510 \\\\\n  \\hline\n   8 & Detected Communities &  6 \\\\\n  \\hline\n\\end{tabular}\n\\end{table}\n\n\\subsubsection{Label Propagation}\n\"label.propagation.community\" has detected low number of communities as seen in Fig.\\ref{labelp}. Performance of this technique is better than other approaches. \n\n\\begin{table}[H]\n\\renewcommand{\\arraystretch}{1.3}\n\\caption{Results}\n\\label{table}\n\\centering\n\\begin{tabular}{|c|c|c|}\n  \\hline\n\\multicolumn{1}{|c|}{\\textbf{Sr. No}} & \\multicolumn{1}{c|}{\\textbf{Parameter}} & \\multicolumn{1}{c|}{\\textbf{Value}} \\\\\n  \\hline\n  1 & Execution Time &  0.06 secs \\\\\n   \\hline\n  2 & Modularity &  0.545 \\\\\n   \\hline\n  3 & Variation of information &  0.597 \\\\\n   \\hline\n  4 & Normalized mutual information &  0.778 \\\\\n   \\hline\n  5 & Split-join distance &  35 \\\\\n   \\hline\n  6 & Rand index &  0.91 \\\\\n   \\hline\n  7 & Adjusted Rand index &  0.81 \\\\\n  \\hline\n   8 & Detected Communities &  8 \\\\\n  \\hline\n\\end{tabular}\n\\end{table}\n\n\\subsubsection{Walktrap}\n\"walktrap.community\" uncovers a community structure with higher modularity as seen in Fig.\\ref{walkt}. Large number of small communities have been created and so this technique has low values on the performance metrics. \n\n\\begin{table}[H]\n\\renewcommand{\\arraystretch}{1.3}\n\\caption{Results}\n\\label{table}\n\\centering\n\\begin{tabular}{|c|c|c|}\n  \\hline\n\\multicolumn{1}{|c|}{\\textbf{Sr. No}} & \\multicolumn{1}{c|}{\\textbf{Parameter}} & \\multicolumn{1}{c|}{\\textbf{Value}} \\\\\n  \\hline\n  1 & Execution Time &  0.11 secs \\\\\n   \\hline\n  2 & Modularity &  0.579 \\\\\n   \\hline\n  3 & Variation of information &  1.32 \\\\\n   \\hline\n  4 & Normalized mutual information &  0.548 \\\\\n   \\hline\n  5 & Split-join distance &  76 \\\\\n   \\hline\n  6 & Rand index &  0.777 \\\\\n   \\hline\n  7 & Adjusted Rand index &  0.446 \\\\\n  \\hline\n   8 & Detected Communities &  15 \\\\\n  \\hline\n\\end{tabular}\n\\end{table}\n\n\\subsubsection{Spinglass and Clique Percolation}\n\"spinglass.community\" detects high number of communities and has low values on VI, Split join and ARI metrics. Hence clustering quality is low as seen in Fig.\\ref{sping}. Clique percolation with $k=3$ detected community structure given in as seen in Fig.\\ref{cliquep} but 10\\% of the nodes were unclassified.\n\n\\begin{table}[H]\n\\renewcommand{\\arraystretch}{1.3}\n\\caption{Results}\n\\label{table}\n\\centering\n\\begin{tabular}{|c|c|c|}\n  \\hline\n\\multicolumn{1}{|c|}{\\textbf{Sr. No}} & \\multicolumn{1}{c|}{\\textbf{Parameter}} & \\multicolumn{1}{c|}{\\textbf{Value}} \\\\\n  \\hline\n  1 & Execution Time &  13.91 secs \\\\\n   \\hline\n  2 & Modularity &  0.35 \\\\\n   \\hline\n  3 & Variation of information &  1.12 \\\\\n   \\hline\n  4 & Normalized mutual information &  0.638 \\\\\n   \\hline\n  5 & Split-join distance &  94 \\\\\n   \\hline\n  6 & Rand index &  0.772 \\\\\n   \\hline\n  7 & Adjusted Rand index &  0.419 \\\\\n  \\hline\n   8 & Detected Communities &  8 \\\\\n  \\hline\n\\end{tabular}\n\\end{table}\n\n\\subsection{Community Structures}\nThe figures below show the community structures uncovered by different approaches.\n\n\\begin{figure}[H]\n  \\begin{subfigure}[b]{0.3\\linewidth}\n    \\includegraphics[width=\\linewidth]{infomap.png}\n    \\caption{infomap}\n    \\label{InfoMap}\n  \\end{subfigure}\n  \\hfill %%\n  \\begin{subfigure}[b]{0.3\\linewidth}\n    \\includegraphics[width=\\linewidth]{leadg.png}\n    \\caption{Leading Eigenvector}\n    \\label{leadg}\n  \\end{subfigure}\n\\caption{Community structures in Network}\n\\end{figure}\n\n\n\\begin{figure}[H]\n  \\begin{subfigure}[b]{0.3\\linewidth}\n    \\includegraphics[width=\\linewidth]{labelp.png}\n    \\caption{Label propagation}\n    \\label{labelp}\n  \\end{subfigure}\n  \\hfill %%\n  \\begin{subfigure}[b]{0.3\\linewidth}\n    \\includegraphics[width=\\linewidth]{walkt.png}\n    \\caption{Walktrap}\n    \\label{walkt}\n  \\end{subfigure}\n \\caption{Community structures in Network}\n\\end{figure}\n\n\\begin{figure}[H]\n  \\begin{subfigure}[b]{0.3\\linewidth}\n    \\includegraphics[width=\\linewidth]{sping.png}\n    \\caption{Spinglass}\n    \\label{sping}\n  \\end{subfigure}\n  \\hfill %%\n  \\begin{subfigure}[b]{0.3\\linewidth}\n    \\includegraphics[width=\\linewidth]{cliquep.png}\n    \\caption{Clique Percolation}\n    \\label{cliquep}\n  \\end{subfigure}\n  \\caption{Community structures in Network}\n\\end{figure}\n\n\\subsection{Variation of BIGCLAM}\nWith the above experimental results as baselines, the variation of BIGCLAM approach suggested in the paper was applied. The attributes were used to create a Bipartite graph as given by Jure Lescovec \\textit{et. al} \\cite{aps:53}, however the key difference was that the nodes were now having edges with the attributes. Network topology was thus ignored and BIGCLAM now used the Non negative matrix factorization to calculate the strength of memberships of the nodes to the attributes. These would be used to decide memberships of nodes to communities. As seen in Fig.\\ref{bigc} the hold out set has highest likelihood at $k=6$. One advantage of this approach was large communities were formed and so it was inferred that splitting into smaller communities was avoided. As BIGCLAM is highly scalable, the network of $10^5$ nodes can be processed efficiently.\n\n\\begin{table}[H]\n\\renewcommand{\\arraystretch}{1.3}\n\\caption{Results}\n\\label{table}\n\\centering\n\\begin{tabular}{|c|c|c|}\n  \\hline\n\\multicolumn{1}{|c|}{\\textbf{Sr. No}} & \\multicolumn{1}{c|}{\\textbf{Parameter}} & \\multicolumn{1}{c|}{\\textbf{Value}} \\\\\n  \\hline\n  1 & Execution Time &  8.51 secs \\\\\n   \\hline\n  2 & Maximum likelihood Estimate &  -1070 \\\\\n  \\hline\n   3 & Detected Communities &  6 \\\\\n  \\hline\n\\end{tabular}\n\\end{table}\n\n\\begin{figure}[H]\n\\centering\n\\fbox{\\includegraphics[scale=0.3]{bigc.png}}\n\\caption{Clustering Structure using Variant of BIGCLAM}\n\\label{bigc}\n\\end{figure}\n\n\n\n\\section{Conclusion}\nCommunity detection using a joint model of node attributes and network topology is a challenging task as additional information has to be factored while maintaining efficiency criteria. The model implemented in this paper uses Non negative matrix factorization on Bipartite Attribute Affiliation model for community detection. This approach allows for nodes to have high membership strengths simultaneously to various attribute communities. This allows for creating nested, overlapping and hierarchical communities in networks. The intuition behind this technique is that if the number of attributes shared by two nodes are high then the nodes have a higher probability of belonging to a single community. As this approach is relying on the optimization principle of BIGCLAM hence it is possible to state that this method can also be scaled to large networks efficiently.    \n\n\n", "meta": {"hexsha": "4883c0270eb37e979621af17e88407c88c4c9a75", "size": 26274, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "APS/APS2_4Sep/Chapter4/chapter4.tex", "max_stars_repo_name": "pranavn91/PhD", "max_stars_repo_head_hexsha": "ac44783a1c7c418cafcfc7eb35ef2fc9641688bc", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "APS/APS2_4Sep/Chapter4/chapter4.tex", "max_issues_repo_name": "pranavn91/PhD", "max_issues_repo_head_hexsha": "ac44783a1c7c418cafcfc7eb35ef2fc9641688bc", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "APS/APS2_4Sep/Chapter4/chapter4.tex", "max_forks_repo_name": "pranavn91/PhD", "max_forks_repo_head_hexsha": "ac44783a1c7c418cafcfc7eb35ef2fc9641688bc", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.0947368421, "max_line_length": 875, "alphanum_fraction": 0.7603714699, "num_tokens": 6953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3116539745084412}}
{"text": "%!TEX root = ../TTT4150-Summary.tex\n\\section{Introduction}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{A brief history of navigation}\n\nYou want to know where you are. Latitude is easy to determine with a sextant, with e.g. the North star or the sun at its highest point. By keeping the home port time with a clock onboard, and measuring time where you are, you can estimate longitude. But clocks (or ``marine chronometers'' if you're a huge nerd) were too inaccurate until John Harrison made a really nice one in the 18th century. Some guys also computed time by observing the moons of Saturn.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Radionavigation}\n\nGround waves are below HF and hug the terrain. Sky waves are in the same frequency range and reflect back down from the ionosphere. Can communicate past the horizon, but hard to determine propagation time, which is necessary for navigation. Space waves are VHF and up, and go straight.\n\n\\subsubsection{Trilateration}\nUse propagation time to estimate distance from source. Compute position from several distances. You need three sources for 2D positioning (or two sometimes). For 3D positioning, you need at least one beacon with a large $\\Delta h$, which you have with satellites but not ground beacons.\n\n\\subsubsection{Hyperbolic positioning}\nYou get signals from two transmitters, and measure the difference in propagation time. If the difference is zero, your position is equally far from both, and therefore somewhere on a straight line. If the difference is nonzero, your position is a bit closer to one transmitter, and will be along a hyperbolic line. If you have another transmitter pair, each pair gives a line of possible positions, and your location should be at their intersection. Figure \\ref{fig:hyperbolic-navigation} illustrates this, with time differences of $0.3$ units between antenna 1 and 2, and $-0.1$ units between 1 and 3. Since you only worry about differences, your clock offset cancels, assuming all transmitter clocks are synced.\n\n\\begin{figure}[htbp]\n    \\centering\n    \\includegraphics[width=.8\\linewidth]{img/hyperbolic-navigation}\n    \\caption{The principle of hyperbolic navigation}\n    \\label{fig:hyperbolic-navigation}\n\\end{figure}\n\n\\subsubsection{Doppler positioning}\nObserve the doppler shift of a satellite. If you know the orbit, you can determine your position.\n", "meta": {"hexsha": "a669418f8bdb61aab2de143359189d9865383f42", "size": 2418, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "TTT4150 Navigation systems/tex/1-introduction.tex", "max_stars_repo_name": "jakoblover/ntnu-course-summaries", "max_stars_repo_head_hexsha": "8ba859de2349b93c5079ca10a4cf2ec49c1f5dc0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-05-30T09:19:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-11T02:42:40.000Z", "max_issues_repo_path": "TTT4150 Navigation systems/tex/1-introduction.tex", "max_issues_repo_name": "jakoblover/ntnu-course-summaries", "max_issues_repo_head_hexsha": "8ba859de2349b93c5079ca10a4cf2ec49c1f5dc0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TTT4150 Navigation systems/tex/1-introduction.tex", "max_forks_repo_name": "jakoblover/ntnu-course-summaries", "max_forks_repo_head_hexsha": "8ba859de2349b93c5079ca10a4cf2ec49c1f5dc0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 83.3793103448, "max_line_length": 713, "alphanum_fraction": 0.7518610422, "num_tokens": 527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3116539745084412}}
{"text": "\\documentclass[a4paper,11pt]{article}\n\\usepackage{amsmath, amsthm, amssymb, commath, graphicx, bbold, endnotes, graphicx, subfigure, multirow, setspace}\n\\usepackage[font=footnotesize]{caption}\n\\usepackage[top=1.25in, bottom=1.25in, left=1.25in, right=1.25in]{geometry}\n\\linespread{1}\n\\setlength{\\parindent}{30pt}\n\n\\title{Cross Phase Calculation Memo}\n\\author{Ruby Byrne}\n\\date{April 2018}\n\n\\begin{document}\n\n\\maketitle\n\n\n\\section{Background}\n\nOne degree of freedom in polarized calibration is the overall phase offset between the $x$- and $y$-dipoles. This phase offset, called $\\phi$ for the purposes of this memo, corresponds to a mixing between the Stokes U and V modes. As we do not expect sky emission to be circularly polarized, we can constrain $\\phi$ by minimizing Stokes V emission. \n\nWe use pseudo-Stokes parameters to simplify the calculation, allowing us to work in visibility space without gridding. Pseudo-Stokes parameters are calculated from the visibilities as follows:\n\n\\begin{equation}\n\\begin{bmatrix}\n\tI^{\\text{pseudo}} \\\\\n\tQ^{\\text{pseudo}} \\\\\n\tU^{\\text{pseudo}} \\\\\n\tV^{\\text{pseudo}} \\\\\n\\end{bmatrix}\n=\n\\begin{bmatrix}\n\t1 & 1 & 0 & 0 \\\\\n\t1 & -1 & 0 & 0 \\\\\n\t0 & 0 & 1 & 1 \\\\\n\t0 & 0 & i & -i \\\\\n\\end{bmatrix}\n\\begin{bmatrix}\n\txx^* \\\\\n\tyy^* \\\\\n\txy^* \\\\\n\tyx^* \\\\\n\\end{bmatrix}\n\\end{equation}\n\nIt is clear that the transformation $x \\rightarrow x e^{-i \\phi/2}$ and $y \\rightarrow y e^{i \\phi/2}$ leaves pseudo-I and pseudo-Q unchanged, but affects the pseudo-U and pseudo-V parameters.\n\n\n\\section{Calculating the Cross Phase}\n\nTo calculate $\\phi$, we minimize the quantity $\\sum_n |V^{\\text{pseudo}}_n|^2$ where $n$ denotes the visibility index. We write the visibilities in terms of an amplitude and phase, such that $(xy^*)_n = A_n e^{i\\delta_n} \\rightarrow A_n e^{i\\delta_n - i\\phi}$ and $(yx^*)_n = B_n e^{i\\gamma_n} \\rightarrow B_n e^{i\\gamma_n + i\\phi}$. Now \n\\begin{equation}\nV^{\\text{pseudo}}_n = A_n e^{i(\\delta_n - \\phi + \\pi/2)} + B_n e^{i(\\gamma_n + \\phi - \\pi/2)}\n\\end{equation}\nIt follows that\n\\begin{equation}\n|V^{\\text{pseudo}}_n|^2 = A_n^2 + B_n^2 - 2 A_n B_n \\left[ \\cos(\\delta_n - \\gamma_n) \\cos(2 \\phi) + \\sin(\\delta_n - \\gamma_n) \\sin(2 \\phi) \\right]\n\\end{equation}\nNow to find $\\phi$ we set $\\frac{\\partial}{\\partial \\phi} \\sum_n |V^{\\text{pseudo}}_n|^2 = 0$. This gives\n\\begin{equation}\n\\tan(2 \\phi) = \\frac{\\sum_n A_n B_n \\sin(\\delta_n - \\gamma_n)}{\\sum_n A_n B_n \\cos(\\delta_n - \\gamma_n)}\n\\end{equation}\nRewriting this in terms of the visibilities, we get\n\\begin{equation}\n\\tan(2 \\phi) = \\frac{\\sum_n \\text{Im} \\left[ (xy^*)_n (yx^*)_n{}^* \\right]}{\\sum_n \\text{Re} \\left[ (xy^*)_n (yx^*)_n{}^* \\right]}\n\\end{equation}\n\n\n\\section{Implementation in FHD}\n\nThis calculation is implemented in FHD in the full-pol branch with the function \\linebreak[4] \\texttt{vis\\_calibrate\\_crosspol\\_phase}. \n\nIt is important to note that FHD convention stores visibilities in the \\texttt{vis\\_ptr} object, where counterintuitively \\texttt{vis\\_ptr[0]} corresponds to $yy^*$, \\texttt{vis\\_ptr[1]} corresponds to $xx^*$, \\texttt{vis\\_ptr[2]} corresponds to $yx^*$, and \\texttt{vis\\_ptr[3]} corresponds to $xy^*$.\n\nThe calculated value of $\\phi$ is stored in the \\texttt{cal.cross\\_phase} object and the correct transformation is applied to the antenna gains. Since the raw visibilities are divided by the gains, the transformation $x \\rightarrow x e^{-i \\phi/2}$ is equivalent to $g_x \\rightarrow g_x e^{i \\phi/2}$ and $y \\rightarrow y e^{i \\phi/2}$ is equivalent to $g_y \\rightarrow g_y e^{-i \\phi/2}$. Here $g_x$ is the $x$-dipole gain (\\texttt{cal.gain[1]}) and $g_y$ is the $y$-dipole gain (\\texttt{cal.gain[0]}).\n\n\\end{document}", "meta": {"hexsha": "b4b9e9707589f392eab42f4bbe9ae84a275cfc22", "size": 3658, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "003_Polarized_Cal_Cross_Phase/Polarized_Cal_Cross_Phase.tex", "max_stars_repo_name": "EoRImaging/Memos", "max_stars_repo_head_hexsha": "216dbda634c1686be25cda25bb258664067a3aad", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-05T08:38:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-05T08:38:01.000Z", "max_issues_repo_path": "003_Polarized_Cal_Cross_Phase/Polarized_Cal_Cross_Phase.tex", "max_issues_repo_name": "EoRImaging/Memos", "max_issues_repo_head_hexsha": "216dbda634c1686be25cda25bb258664067a3aad", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-03-07T22:45:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-20T20:19:43.000Z", "max_forks_repo_path": "003_Polarized_Cal_Cross_Phase/Polarized_Cal_Cross_Phase.tex", "max_forks_repo_name": "EoRImaging/Memos", "max_forks_repo_head_hexsha": "216dbda634c1686be25cda25bb258664067a3aad", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-03-07T01:12:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-07T01:12:56.000Z", "avg_line_length": 48.1315789474, "max_line_length": 503, "alphanum_fraction": 0.6973756151, "num_tokens": 1224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3116539745084412}}
{"text": "Now we've pinned down the mechanics of how we will incorporate our signal functions into real working code, we can write our first example. Save a copy of \\hask{YampaUtils.hs} in your working directory, for your use in these examples. Our first example, Listing \\ref{lst:helloYampa}, is the Hello, World of Yampa.\n\n\\lstinputlisting[caption={HelloYampa.hs}, label=lst:helloYampa]{./src/HelloYampa.hs}\n\nOur discussion in the introduction about \\hask{reactimate}, and our tidied version \\yampaMain, should give you a rough idea of what is going on here. \\yampaMain first calls \\hask{initialise}, which prints some text to the screen, but provides no input (or, more precisely, provides as input \\hask{()}). The input function passed to \\yampaMain is just \\hask{return Nothing}, which again provides no input to the system.\n\n\\hask{waitTwo} is a signal function, and is the new code in this listing. For the moment, lets just observe that it converts a signal of values of type \\hask{()} into a signal of values of type \\hask{Bool}, which is what its type signature \\hask{SF () Bool} is meant to indicate (`` a signal function from signals of type \\hask{()} to signals of type \\hask{Bool}'').\n\nThe output function, \\hask{output}, takes this boolean value, and if its false, just instructs \\yampaMain to continue by passing out a \\hask{False} value in the \\hask{IO} monad. However, if the boolean value is true, the output function first prints a message to the screen, and then returns an \\hask{IO} value of \\hask{True}, which instructs \\yampaMain to stop executing, and the program finishes.\n\nPrecisely when the value \\hask{True} emerges from \\yampaMain is determined in the signal function \\hask{waitTwo}. So lets take a look at this object.\n\n\\begin{lstlisting}\nwaitTwo :: SF () Bool\nwaitTwo = time >>> arr (>=2)\n\\end{lstlisting}\n\nThe specification for \\hask{waitTwo} is that it should take the input signal (which here is constantly taking value \\hask{()}), and if \\hask{waitTwo} has been transforming input values for less than 2 seconds, it should transform the input into a value \\hask{False}, and otherwise, it should transform the input signal into a value \\hask{True}. This boils down to saying, \\yampaMain should receive a value \\hask{True} to give to \\hask{output}, precisely when \\yampaMain has been running for 2 seconds. Compiling and running this code seems to confirm this.\n\nSo how has \\hask{waitTwo} been defined? It consists of two parts combined together with the operator \\hask{>>>}. First lets take a look at \\hask{time}.\n\n\\begin{lstlisting}\ntime :: SF a Time\n\\end{lstlisting}\n\n\\noindent \\hask{time} takes a signal of any value, and replaces it with a value of type \\hask{Time}, a synonym for \\hask{Double}. The value is the time the particular instantiation of \\hask{time} has been in use, starting from $0$. So in our case, it takes the value \\hask{()}, and replaces it with the time that \\yampaMain has been using \\hask{waitTwo}, which is the length of time \\yampaMain has been running.\n\nSecondly, we have \\hask{arr (>=2)}. Now inspecting the type of this in ghci reveals \\hask{arr} is a function which makes use of the \\hask{Arrow} type class. \\hask{SF} is an instance of this type class, and specialising its type signature to \\hask{SF}, we have:\n\n\\begin{lstlisting}\narr :: (a -> b) -> SF a b \n\\end{lstlisting}\n\n\\noindent \\hask{arr} is a way of lifting pure functions into \\hask{SF}, analogous to how \\hask{return} lifts values in a monad, and \\hask{pure} lifts values for applicative functors. More precisely, if \\hask{f :: a -> b}, then \\hask{arr f} takes a signal of values of type \\hask{a}, and transforms it into a signal of values of type \\hask{b}, by applying \\hask{f} to each value of type \\hask{a}. In some sense, it is the continuous signal analogue of \\hask{fmap} for the functor typeclass.\n\nIn our example, we have the signal function \\hask{arr (>=2)}, which by specialising to types \\hask{SF} again has type:\n\n\\begin{lstlisting}\narr (>=2) :: (Num a, Ord a) => SF a Bool\n\\end{lstlisting}\n\n\\noindent \\hask{arr (>=2)} takes a signal with numerical and orderable values, and applies \\hask{(>=2)} to these values. So our transformed signal will output \\hask{True} precisely when the input signal takes on values greater than or equal to 2.\n\nSo we have two signal functions, with an operator which combines them (a \\emph{combinator}). Lets inspect the type of \\hask{>>>}, specialised to \\hask{SF} again.\n\n\\begin{lstlisting}\n(>>>) :: SF a b -> SF b c -> SF a c\n\\end{lstlisting}\n\n\\noindent The type signature (and the fact that the more general version is for objects from the typeclass \\hask{Category}), is a giveaway for what \\hask{(>>>)} does. \\hask{(>>>)} is the \\hask{SF} analogue of composition. Given a way of transforming signals of value type \\hask{a} into signals of value type \\hask{b}, and a way of transforming signals of value type \\hask{b} into signals of value type \\hask{c}, by performing each transformation in order, I can transform signals of value type \\hask{a} into signals of value type \\hask{c}. This is the function of the \\hask{(>>>)} combinator. More precisely, \\hask{f >>> g} first transforms with \\hask{f}, and then with \\hask{g} (recall \\hask{f.g} first applies g \\emph{then} applies \\hask{f}).\n\nSo now we can analyse what \\hask{waitTwo} actually does. \\hask{waitTwo} takes an input signal of values \\hask{()}, and replaces these values with the time which \\yampaMain has been running. It then takes this time, and if it is less than 2 seconds, replaces this time value with a \\hask{False}. Otherwise, it replaces this time value with \\hask{True}. In total, \\hask{waitTwo} transforms \\hask{()} into \\hask{False} if \\yampaMain has been running less than 2 seconds, and \\hask{True} once its been running at least two seconds.\n\n\\begin{observation}\nObserve that \\hask{arr (f.g) = arr g >>> arr f}. Observe that \\hask{time} is not the \\hask{arr} of a pure function.\n\\end{observation}\n\n\\section{Building signal functions}\n\nOur first example is intentionally not the most intricate or complicated of examples. We build a very simple signal function, with the intention of showing how a Yampa program fits together.\n\nThe bulk of the Yampa library is concerned with building signal functions. Rather than building signal functions explicitly, Yampa supplies a basic set of signal functions (we saw for instance, \\hask{time}, above), and a set of \\emph{combinators} for combining various signal functions (for instance, signal function composition \\hask{>>>}).\n\n\\section{Some basic signal functions and combinators}\n\nLets begin with some of the basic signal functions which Yampa provides. As one might expect from a library based around transformations, one has analogues for the identity map, and constant maps.\n\n\\begin{lstlisting}\nidentity :: SF a a\nconstant :: b -> SF a b\n\\end{lstlisting}\n\n\\noindent Of course, \\hask{identity} preserves the value of a signal, and \\hask{constant v} takes a signal, and replaces its value by the value \\hask{v}.\n\n\\begin{exercise}\nWrite definitions for \\hask{identity} and \\hask{constant} in terms of \\hask{arr}.\n\\end{exercise}\n\nIn our first example, we saw the signal function \\hask{time}. \\hask{time} takes a signals value, and replaces it with the \\emph{local} time, that is the time a signal function has been processing a signal. For the moment, this would appear to be the same time as \\yampaMain has been running, and with what has been covered so far, it is, but later we will see that signal functions can be switched in and out in response to events, at which point the time counter starts over from zero. For the sake of completeness (recall \\hask{Time} is a synonym for Double):\n\n\\begin{lstlisting}\ntime :: SF a Time\n\\end{lstlisting}\n\nAn interesting built in function is \\hask{integral}. This performs numerical integratation of a signal over time. Of course this is useful for describing dynamical systems!\n\n\\begin{lstlisting}\nintegral :: SF Double Double\n\\end{lstlisting}\n\n\\hask{integral} actually has a more general type than the above, but this suffices for now. Yampa provides an similar signal function for derivatives also.\n\n\\begin{observation}\n\\hask{time = constant 1.0 >>> integral}.\n\\end{observation}\n\nWe also have, as we have seen already, a way of lifting pure functions \\hask{a -> b} to values of type \\hask{SF a b}:\n\n\\begin{lstlisting}\narr :: (a -> b) -> SF a b\n\\end{lstlisting}\n\n\\noindent \\hask{arr f} will take a signal of type \\hask{a}, and process its value with \\hask{f}, to create a signal of type \\hask{b}.\n\nNow that we have a basic collection of arrows, we woud like some ways to combine them, to form more interesting arrows. The type constructor \\hask{SF} is an instance of the \\hask{Arrow} typeclass, a generalisation of the \\hask{Monad} type class, so we have all the combinators from \\hask{Arrow} available for use. We have already seen \\hask{arr} above, which is part of the \\hask{Arrow} interface, and earlier we saw \\hask{(>>>)}.\n\n\\hask{(>>>)} is the composition operator for signal functions. \\hask{(f >>> g)} applies \\hask{f} to a signal, then \\hask{g} (note the order is reverse of \\hask{.}). Similarly, \\hask{(<<<)} is the composition operator the other way around, so \\hask{(f <<< g)} performs \\hask{g} then \\hask{f}.\n\n\\begin{lstlisting}\n(>>>) :: SF a b -> SF b c -> SF a c\n(<<<) :: SF b c -> SF a b -> SF a c\n\\end{lstlisting}\n\nSometimes we want to process a signal in two different ways. The combinator \\hask{(\\&\\&\\&)} is designed to allow us to do exactly that.\n\n\\begin{lstlisting}\n(&&&) :: SF a b -> SF a c -> SF a (b,c)\n\\end{lstlisting}\n\n\\noindent Here \\hask{(f \\&\\&\\& g)} is intended to mean take the value of a signal, and apply \\hask{f} to it, placing the output in the first component of a tuple. Also apply \\hask{g} to the value of the signal, and place the output in the second component of the tuple.\n\nSince we can produce a signal which takes a tuple for values, (which we can think of as being two signals captured in one), we have combinators for processing them.\n\nFirst we have \\hask{(***)}, which allows us to take two signal functions and make each act on a particular element of a tuple.\n\n\\begin{lstlisting}\n(***) :: SF a1 b1 -> SF a2 b2 -> SF (a1, a2) (b1, b2)\n\\end{lstlisting}\n\n\\noindent \\hask{(f *** g)} acts on a signal which takes a tuple for values, by applying \\hask{f} to the first component, and \\hask{g} to the second component.\n\nSometimes, we only want to transform one of the elements of a signal of tuple type. While something of the form \\hask{(f *** identity)} would do, Yampa defines such combinators for us:\n\n\\begin{lstlisting}\nfirst :: SF a b -> SF (a, c) (b, c)\nsecond :: SF b c -> SF (a, b) (a, c)\n\\end{lstlisting}\n\n\\noindent \\hask{first f} transforms only the first component of a signal of tuple values with \\hask{f}, and \\hask{second g} transforms only the second component of a signal with tuple values with \\hask{g}.\n\n\\begin{exercise}\nWrite \\hask{second} in terms of \\hask{first} and \\hask{arr}.\n\\end{exercise}\n\n\\begin{observation}\n\\hask{ (f *** g) = (first f) >>> (second g) }.\n\\end{observation}\n\nOur last combinator is \\hask{loop}. \\hask{loop} allows us to build recursive signal functions. It has type\n\n\\begin{lstlisting}\nloop :: SF (a, c) (b, c) -> SF a b\n\\end{lstlisting}\n\n\\noindent \\hask{(loop f)} is obtained from \\hask{f} by looping its values' second component back in to \\hask{f} for the next sample.\n\n\\section{Arrow notation}\n\nThe above primitives and combinators allow us to form more complex signal functions. In fact, any combination of basic signal functions can be formed. However, using the combinators directly can often lead to code which is difficult to read. For this reason, the arrow syntax was developed. This is the arrow analogue of monadic do notation. It allows us to express more clearly how we wish to process the values which signals take. A preprocessor transforms this notation into a description using the combinators we described above. When using arrow notation in ghci, load ghci with the -XArrows option, e.g. \\hask{ghci -XArrows}. Similarly, when compiling with ghc, use the -XArrows option, e.g. \\hask{ghc -XArrows main.hs}.\n\nLet us first inspect the general form of a block in arrow syntax. Also, take a look at the example that follows the discussion, since this will make it clearer. The basic form of arrow syntax is given in the following.\n\n\\begin{lstlisting}\nsigFun :: SF a b\nsigFun = proc input -> do\n  processedSample1 <- sigFun1 -< sample1\n  processedSample2 <- sigFun2 -< sample2\n  ...\n  returnA -< finalSample\n\\end{lstlisting}\n\n\\hask{proc} is a keyword to indicate that the following is a block written in arrow syntax. \\hask{input} represents a sample of type \\hask{a}, and can be pattern matched against. A line of the form\n\n\\begin{lstlisting}\nprocessedSample <- sigFun -< sample\n\\end{lstlisting}\n\n\\noindent takes the sample (from a signal) named \\hask{sample}, processes it with \\hask{sigFun}, and binds the resulting value to \\hask{processedSample}. We can pattern match in the position of \\hask{processedSample}. The line\n\n\\begin{lstlisting}\nreturnA -< finalSample\n\\end{lstlisting}\n\n\\noindent yields \\hask{finalSample} as the final transformed sample. Note there is no binding, just like (and for the same reason as) a monadic \\hask{do} block. As with \\hask{do} blocks, \\hask{let} bindings are also allowed in arrow syntax. As a word of warning, recursive definitions in arrow syntax must be preceeded by the keyword \\hask{rec}. We will investigate this fully later.\n\nBy way of example, lets describe a signal function which receives a signal of type \\hask{Double}, which is intended to represent the acceleration of an object, and is intended to output a signal describing its position (assuming it starts at $0$, lets say). Using the normal combinators we could write the following:\n\n\\begin{lstlisting}\naccToPos :: SF Double Double\naccToPos = integral >>> integral\n\\end{lstlisting}\n\n\\noindent which to be fair, is clear enough. In arrow syntax however, we can write this as\n\n\\begin{lstlisting}\naccToPos :: SF Double Double\naccToPos = proc acc -> do\n  vel <- integral -< acc\n  pos <- integral -< vel\n  returnA -< pos\n\\end{lstlisting}\n\n\\noindent So we obtain \\hask{vel} (velocity) by integrating the input \\hask{acc} (acceleration), and we obtain \\hask{pos} (position) by integrating the velocity \\hask{vel}. \\hask{pos} is the value we want, so we return that. It is not too hard to imagine signal functions where using the arrow syntax can greatly aid clarity. Observe that the wiring of samples through signal functions is represented in an intuitive manner.\n\nThe above example would potentially be used in an animation program, or a simulation of some kind. We will build these kinds of programs later, but for the moment it would be nice to have some working code. We will develop our ``Hello, Yampa!'' program a little further. Here, we start by asking the user to specify a time to delay finishing the greeting, and feed this value in to \\yampaMain via the initialisation value.\n\n\\lstinputlisting[caption={askAndPause.hs}, label=lst:askingAndPausing]{./src/askAndPause.hs}\n", "meta": {"hexsha": "e1994223048d5133b9a9f407b0b9ae8ef586c5a7", "size": 15107, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "helloYampa.tex", "max_stars_repo_name": "rlupton20/yampaTutorial", "max_stars_repo_head_hexsha": "c5d6c462cc54a36a0100163d27c4db321b30ecad", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2016-02-06T14:37:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-11T17:56:49.000Z", "max_issues_repo_path": "helloYampa.tex", "max_issues_repo_name": "rlupton20/yampaTutorial", "max_issues_repo_head_hexsha": "c5d6c462cc54a36a0100163d27c4db321b30ecad", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2016-02-06T14:42:30.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-21T16:45:18.000Z", "max_forks_repo_path": "helloYampa.tex", "max_forks_repo_name": "rlupton20/yampaTutorial", "max_forks_repo_head_hexsha": "c5d6c462cc54a36a0100163d27c4db321b30ecad", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 72.6298076923, "max_line_length": 744, "alphanum_fraction": 0.7457470047, "num_tokens": 4074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3116539745084412}}
{"text": "\\chapter{Algorithm for Herbrand Analysis}\n\\label{chap:chapter4}\n\nThis chapter presents an algorithm for Herbrand analysis. The pseudocode  \nmentioned here is an updated version of the algorithm mentioned in \\cite{Babu} \nfor Herbrand equivalence analysis. The corresponding implementation done for \nLLVM compiler framework and a toy language can be found on \n\\href{https://www.github.com/himanshu520/HerbrandEquivalence}{GitHub}.\nAlso, see \\autoref{chap:chapter7} and \\autoref{chap:chapter8} for more details.\n\nOne important distinction must be clear between the general Herbrand analysis problem\nand the one that the algorithm in this chapter addresses. The universe for the Herbrand \nequivalence problem is the set of all expressions that can be formed using constants, \nvariables and operators used in the program. But as already mentioned, the algorithm \nhere is concerned with a restricted universe - set of expressions of length atmost two \nformed using constants, variables and operators in the program. \n\n\\section{Notation}\n\\label{sec:NotationPseudocode}\n\nLet $\\mathcal C$ and $\\mathcal X$ be the set of constants and variables used in the program;\n$\\mathcal W$ be our working set, which is the set of all expressions of length at most two \nthat can be formed using ($\\mathcal C \\cup \\mathcal X$). Also, $V$ be the set of all program \npoints, with a special point \\texttt{START} denoting the beginning of the program.\n\\bigbreak \\noindent Three global variables are maintained - \n\\begin{itemize} \\tightlist\n    \\item \\texttt{Partitions} : It is two-dimensional integer array indexed by the \n                                elements of sets $V$ and $\\mathcal W$ respectively. It \n                                helps to keep track of partitions at some $v \\in V$ by\n                                holding same integer at \\texttt{Partitions[$v$][$e$]} and\n                                \\texttt{Partitions[$v$][$e'$]}, for $e, e' \\in \\mathcal W$ \n                                if they belongs to the same equivalence class at $v$.\n                                Basically, the array maintains set identifiers which helps \n                                to identify whether two expressions belong to the same sets \n                                (equivalence classes).\n    \\item \\texttt{SetCnt} : It helps to keep track of the next set identifier (an integer)\n                            to be used. Whenever, a set identifier is needed the current \n                            value of \\texttt{SetCnt} is used and at the same time it is \n                            incremented so that the same number is never used again.\n    \\item \\texttt{Parent} : It is \\texttt{map} indexed by a tuple of three elements - an   \n                            operator and two set identifiers. Whenever an expression \n                            ($x + y$) is assigned a set identifier $c$, $c$ is stored in \n                            \\texttt{Parent} with $\\{+, a, b\\}$ as key, where $a$ and $b$ are \n                            the set identifiers of $x$ and $y$ respectively. Next time \n                            when a set identifier for an expression ($x' + y'$) is needed, \n                            where $x'$ and $y'$ have identifiers $a$ and $b$ respectively, \n                            $c$ is used instead of using a new set identifier - the \\texttt\n                            {Parent} of $\\{+, a, b\\}$ that was earlier stored in the map.\n\\end{itemize}\n\n\\bigbreak \\noindent There are a few functions whose definitions are not required explicitly - \n\\begin{itemize} \\tightlist\n    \\item \\texttt{OPERATOR($e$)} : Returns operator used in expression $e \\in (\\mathcal W \\setminus (\\mathcal C \\cup \\mathcal X))$\n    \\item \\texttt{LEFT($e$)} : Returns left operand of expression $e \\in (\\mathcal W \\setminus (\\mathcal C \\cup \\mathcal X))$\n    \\item \\texttt{RIGHT($e$)} : Returns right operand of expression $e \\in (\\mathcal W \\setminus (\\mathcal C \\cup \\mathcal X))$\n    \\item \\texttt{PREDECESSORS($v$)} : Returns the set of predecessors of program point $v \\in V$\n\\end{itemize}\n\n\\bigbreak \\noindent \\textbf{NOTE} - For implementation, the identifiers corresponding to \n$\\top$ partition should be such that they don't occur in normal partitions and are also \neasily distinguishable from them. An easy choice for consistency is to use non-negative \nintegers as normal set identifiers and an array of -1 to refer $\\top$ partition.\n\n\\section{Pseudocode}\n\\label{sec:Pseudocode}\n\n\\begin{algorithm}\n    \\caption{Main Herbrand Equivalence Analysis Function}\n    \\label{alg:HerbrandEquivalenceAnalysis}\n    \\begin{algorithmic}\n        \\Procedure{HerbrandAnalysis}{$ $}\n            \\State \\Comment{\\% Initialise \\texttt{Partitions} for all program points \\%}\n            \\For{$v \\in V$}\n                \\State \\texttt{Partitions[$v$]} $\\gets \\top$\n            \\EndFor\n            \\State \\Comment{\\% Update \\texttt{Partitions} for \\texttt{START} point \\%}\n            \\State \\Call{findInitialPartition}{$ $}\n            \\State \\Comment{\\% Process all program points till convergence \\%}\n            \\State \\textbf{converged} $\\gets$ \\texttt{false}\n            \\While{\\texttt{converged} \\textit{is False}}\n                \\State \\texttt{converged $\\gets$ true}\n                \\For{$v \\in (V \\setminus \\{\\texttt{START}\\})$}\n                    \\State \\textbf{oldPartition} $\\gets$ \\texttt{Partitions[$v$]}\n                    \\State \\Comment{\\% Update \\texttt{Partitions} at $v$ \\%}\n                    \\If{$v$ \\textit{is a Transfer Point}}\n                        \\State \\Call{TransferFunction}{$v$}\n                    \\Else\n                        \\State \\Call{ConfluenceFunction}{$v$}\n                    \\EndIf\n                    \\State \\Comment{\\$ Update \\texttt{convergence} flag \\%}\n                    \\If{\\textit{not} \\Call{SamePartition}{\\texttt{oldPartition, Partitions[$v$]}}}\n                        \\State \\texttt{converged $\\gets$ false}\n                    \\EndIf\n                \\EndFor\n            \\EndWhile\n        \\EndProcedure\n    \\end{algorithmic}\n\\end{algorithm}\n\n\\begin{algorithm}\n    \\caption{Transfer Function}\n    \\label{alg:TransferFunction}\n    \\begin{algorithmic}\n        \\Procedure{TransferFunction}{$v : x \\gets e$}\n            \\State \\textbf{u} $\\gets$ \\Call{Predecessors}{$v$}\n            \\State \\texttt{Partitions[$v$] $\\gets$ Partitions[$u$]}\n            \\State \\Comment{\\% Update set identifier for $x$ \\%}\n            \\If{$e$ \\textit{is Deterministic}}\n                \\State \\texttt{Partitions[$v$][$x$] $\\gets$ Partitions[$v$][$e$]}\n            \\Else \n                \\State \\texttt{Partitions[$v$][$x$] $\\gets$ SetCtr++}\n            \\EndIf\n            \\State \\Comment{\\% Update set identifiers for expressions containing $x$ \\%}\n            \\For{$\\{e' \\in (\\mathcal W \\setminus (\\mathcal C \\cup \\mathcal X)) \\mid x \\in e'\\}$}\n                \\State \\texttt{Partitions[v][$e'$]} $\\gets$ \\Call{GetSetId}{$v$, $e'$}\n            \\EndFor\n        \\EndProcedure\n    \\end{algorithmic}\n\\end{algorithm}\n\n\\begin{algorithm}\n    \\caption{Confluence Function}\n    \\label{alg:ConfluenceFunction}\n    \\begin{algorithmic}\n        \\Procedure{ConfluenceFunction}{$v$}\n            \\State \\Comment{If all predecessor partitions are $\\top$ then current partition will also be $\\top$}\n            \\State \\textbf{continueFlag} $\\gets$ false\n            \\For{$u \\in$ \\Call{Predecessors}{$v$}}\n                \\If{\\texttt{Partitions[$u$] $\\neq \\top$}}\n                    \\State \\texttt{continueFlag $\\gets$ true}\n                \\EndIf\n            \\EndFor\n            \\State\n            \\If{\\texttt{continueFlag} \\textit{is False}}\n                \\State \\texttt{Partitions[$v$] $\\gets \\top$}\n                \\State \\Return{}\n            \\EndIf\n            \\State \\Comment{\\texttt{accessFlag} keeps track of processed expressions}\n            \\For{$e \\in \\mathcal W$}\n                \\State \\textbf{accessFlag}[$e$] $\\gets$ \\texttt{false}\n            \\EndFor\n            \\State \\Comment{Process all expressions if they are still unprocessed}\n            \\For{$e \\in \\mathcal W$}\n                \\If{\\texttt{accessFlag[$e$]} \\textit{is False}}\n                    \\State \\Comment{\\texttt{PredIDs} is the set of set identifiers of $e$ at its predecessors}\n                    \\State \\textbf{PredIDs} $\\gets \\phi$\n                    \\For{$u \\in$ \\Call{Predecessors}{$v$}}\n                        \\If{\\texttt{Partitions[u] $\\neq \\top$}}\n                            \\State \\texttt{PredIDs $\\gets$ (PredIDs $\\cup$ Partitions[$u$][$e$])}\n                        \\EndIf\n                    \\EndFor\n                    \\State\n                    \\If{\\texttt{PredIDs} \\textit{is Singleton}}\n                        \\State \\texttt{Partitions[$v$][$e$] $\\gets$ PredIDs}\n                        \\State \\texttt{accessFlag[$e$] $\\gets$ true}\n                    \\Else\n                        \\State \\Comment{\\texttt{expClass} holds $e' \\in \\mathcal W$ that are equivalent to $e$ at all predecessors of $v$}\n                        \\State \\textbf{expClass} $\\gets \\mathcal W$\n                        \\For{$u \\in$ \\Call{Predecessors}{$v$}}\n                            \\If{\\texttt{Partitions[u] $\\neq \\top$}}\n                                \\State \\texttt{expClass $\\gets$ (expClass} $\\cap$ \\Call{GetClass}{$u$, $e$})\n                            \\EndIf\n                        \\EndFor\n                        \\State \\Comment{Update \\texttt{Partitions} map}\n                        \\State \\textbf{newSetID} $\\gets$ \\texttt{SetCnt++}\n                        \\For{\\texttt{$e' \\in$ expClass}}\n                            \\State \\texttt{Partitions[$v$][$e'$] $\\gets$ newSetID}\n                            \\State \\texttt{acessFlag[$e'$] $\\gets$ true}\n                        \\EndFor\n                    \\EndIf\n                \\EndIf\n            \\EndFor\n            \\State\n            \\State \\Comment{Update \\texttt{Parent} map}\n            \\For{$e \\in (\\mathcal W \\setminus (\\mathcal C \\cup \\mathcal X))$}\n                \\State \\textbf{op} $\\gets$ \\Call{Operator}{$e$}\n                \\State \\textbf{leftSetID} $\\gets$ \\texttt{Partitions}[\\Call{Left}{$e$}]\n                \\State \\textbf{rightSetID} $\\gets$ \\texttt{Partitions}[\\Call{Right}{$e$}]\n                \\State \\texttt{Parent[\\{op, leftSetID, rightSetID\\}] $\\gets$ Partitions[v][$e$]}\n            \\EndFor\n        \\EndProcedure\n    \\end{algorithmic}\n\\end{algorithm}\n\n\\begin{algorithm}\n    \\caption{Checks whether two partitions are same or not}\n    \\label{alg:SamePartition}\n    \\begin{algorithmic}\n        \\Procedure{SamePartition}{\\texttt{first, second}}\n            \\For{$e \\in \\mathcal W$}\n                \\If{\\Call{GetClass}{\\texttt{first}, $e$} $\\neq$ \\Call{GetClass}{\\texttt{second}, $e$}}\n                    \\State \\Return{\\texttt{false}}\n                \\EndIf\n            \\EndFor\n            \\State \\Return{\\texttt{true}}\n        \\EndProcedure\n    \\end{algorithmic}\n\\end{algorithm}\n\n\\begin{algorithm}\n    \\caption{Finds equivalence class of an expression in a partition}\n    \\label{alg:GetClass}\n    \\begin{algorithmic}\n        \\Procedure{GetClass}{\\texttt{partition}, $e$}\n            \\State \\textbf{expClass} $\\gets \\phi$\n            \\For{$e' \\in \\mathcal W$}\n                \\If{\\texttt{partition[$e'$] == partition[$e$]}}\n                    \\State \\texttt{expClass $\\gets$ (expClass $\\cup$ $\\{e'\\}$)}\n                \\EndIf\n            \\EndFor\n            \\State \\Return{\\texttt{expClass}}\n        \\EndProcedure\n    \\end{algorithmic}\n\\end{algorithm}\n\n\\begin{algorithm}\n    \\caption{Initialises partition for START point}\n    \\label{alg:FindInitialPartition}\n    \\begin{algorithmic}\n        \\Procedure{FindInitialPartition}{$ $}\n            \\For{$x \\in (\\mathcal C \\cup \\mathcal X)$}\n                \\State \\texttt{Partitions[START][$x$] $\\gets$ SetCtr++}\n            \\EndFor\n            \\For{$e \\in (\\mathcal W \\setminus (\\mathcal C \\cup \\mathcal X))$}\n                \\State \\texttt{Partitions[START][$e$]} $\\gets$ \\Call{GetSetID}{\\texttt{Partitions[START], $e$}}\n            \\EndFor\n        \\EndProcedure\n    \\end{algorithmic}\n\\end{algorithm}\n\n\\begin{algorithm}\n    \\caption{Finds and returns set identifier for a two length expression in a partition, by\n             looking at its operands and operator}\n    \\label{alg:GetSetID}\n    \\begin{algorithmic}\n        \\Procedure{GetSetID}{\\texttt{partition, $e$}}\n            \\State \\textbf{op} $\\gets$ \\Call{Operator}{$e$}\n            \\State \\textbf{leftSetID} $\\gets$ \\texttt{partition}[\\Call{Left}{$e$}]\n            \\State \\textbf{rightSetID} $\\gets$ \\texttt{partition}[\\Call{Right}{$e$}]\n            \\State\n            \\If{\\textit{not defined} \\texttt{Parent[\\{op, leftSetID, rightSetID\\}]}}\n                \\State \\texttt{Parent[\\{op, leftSetID, rightSetID\\}] $\\gets$ SetCtr++}\n            \\EndIf \n            \\State\n            \\State \\Return{\\texttt{Parent[\\{op, leftSetID, rightSetID\\}]}}\n        \\EndProcedure\n    \\end{algorithmic}\n\\end{algorithm}\n\n\\section{Updates Over Original Algorithm}\n\\label{sec:UpdatesOverOriginalAlgorithm}\nFollowing major improvements/corrections have been made to the original algorithm \nmentioned in \\cite{Babu}.\n\\begin{itemize} \\tightlist\n    \\item \\textbf{Representing Partitions}\\\\\n    The original algorithm uses \\texttt{ID structure} to maintain equivalence information. A two-dimensional array \\texttt{Partitions} having an entry for each program point and each expression, stores a pointer to an \\texttt{ID object}. At a program point, two expressions are equivalent if they contain pointers to the same object. Though this approach is correct, it adds a lot of overhead in the implementation both in terms of time and space - the \\texttt{ID object}s have to be created and destroyed during runtime, their data fields have to be maintained properly etc.\\\\\n    The updated algorithm solves this problem by using just integer set identifiers instead of pointers to some dynamically created objects and the \\texttt{Parent map}. Again same as before, two expressions are equivalent at a program point if \\texttt{Partitions} array stores same set identifiers for the expressions at that program point. \\texttt{Parent} map captures the relation between the set identifiers. This modification makes the actual implementation to be more simpler, efficient and intuitive.\n    \\item \\textbf{Confluence Function}\\\\\n    The \\texttt{Confluence} function in the original algorithm processes only the set $\\mathcal C \\cup \\mathcal V$ in its main loop. This is wrong and instead the whole working set $\\mathcal W$ should be considered.\\\\\n    As an example, consider the test case in \\autoref{sec:tc15}. At the confluence point, $y$ and $x + 2$ must be equivalent, but the original algorithm assigns them pointers to different \\texttt{ID objects} indicating they are not equivalent.\n    \\item \\textbf{Non-deterministic Assignment}\\\\\n    Non-deterministic assignment need not be handled separately and a single transfer function is sufficent (see \\autoref{alg:TransferFunction}).\n\\end{itemize}\n", "meta": {"hexsha": "172acd8c8197732149ca86ca8c529759f1eea900", "size": 15032, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "reports/Rep_End_8/chapter4.tex", "max_stars_repo_name": "himanshu520/HerbrandEquivalence", "max_stars_repo_head_hexsha": "bfe056d9d370d9e5fe2782381b872bf102a960ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "reports/Rep_End_8/chapter4.tex", "max_issues_repo_name": "himanshu520/HerbrandEquivalence", "max_issues_repo_head_hexsha": "bfe056d9d370d9e5fe2782381b872bf102a960ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "reports/Rep_End_8/chapter4.tex", "max_forks_repo_name": "himanshu520/HerbrandEquivalence", "max_forks_repo_head_hexsha": "bfe056d9d370d9e5fe2782381b872bf102a960ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.9393939394, "max_line_length": 577, "alphanum_fraction": 0.5979909526, "num_tokens": 3851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961013, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.31165397450844107}}
{"text": "%!TEX root = ../thesis.tex\n%*******************************************************************************\n%****************************** Second Chapter *********************************\n%*******************************************************************************\n\n\\chapter{Lattice QCD}\\label{chapter:LatticeQCD}\n\n\\ifpdf\n    \\graphicspath{{Chapter2/Figs/Raster/}{Chapter2/Figs/PDF/}{Chapter2/Figs/}}\n\\else\n    \\graphicspath{{Chapter2/Figs/Vector/}{Chapter2/Figs/}}\n\\fi\nCurrently, lattice QCD represents the only technique able to perform accurate low-energy QCD calculations from first principles. The lattice prescription allows for the explicit calculation of path integrals present in continuum QCD, at the cost of introducing finite-spacing errors that must be systematically accounted for. In this chapter we will discuss the behaviour of QCD in the continuum, and demonstrate how the transition can be made to a finite set of coordinates on a lattice. We will then briefly detail how this formulation can be used to generate simulations of the QCD vacuum. Finally, we use this framework to describe how our generated configurations can be fixed to Landau gauge, one of the two gauge choices used in this research.\n\n\\section{QCD in the Continuum}\n\\subsection{Quarks and Gauge Invariance}\nQCD is the gauge field theory that describes the interactions of quarks and gluons. Like all gauge theories, it has an internal symmetry group under which the Lagrangian is invariant. In the case of QCD there are three quark colours, which leads to the symmetry group being $SU(3)$, the group of $3\\times 3$ unitary matrices of determinant 1. Note that this description of $SU(3)$ is only true in the fundamental representation, however it is this representation that the quarks inhabit and is therefore a useful and intuitive way to initially consider the group. We can observe this $SU(3)$ symmetry by inspecting the free quark Lagrangian\n%\n\\begin{equation}\n\\mathcal{L}_0 = \\bar{\\psi}(x)\\,(i\\slashed{\\partial}-m)\\,\\psi(x)\\,.\n\\label{eq:GlobalQuarkLagrangian}\n\\end{equation}\n%\nwhere $\\psi(x)$ and $\\bar{\\psi}(x)$ contain the three quark and anti-quark fields respectively, $m$ is the quark mass and $\\slashed{\\partial}=\\partial_\\mu\\,\\gamma^\\mu$. We make use of the Dirac representation for the gamma matrices, given in Appendix~\\ref{app:GellMann}. If we apply an $SU(3)$ transformation $\\Omega$ to the three colour indices of the quark and anti-quark fields such that\n%\n\\begin{align}\n\\psi(x)&\\rightarrow\\Omega\\,\\psi(x)\\\\\n\\bar{\\psi}(x)&\\rightarrow \\bar{\\psi}(x)\\,\\Omega^\\dagger\\, ,\n\\end{align}\n%\nwe see that\n%\n\\begin{align}\n\\mathcal{L}_0\\rightarrow\\mathcal{L'}_0&=\\bar{\\psi}(x)\\,\\Omega^\\dag\\,(i\\slashed{\\partial}-m)\\,\\Omega\\,\\psi(x)\\nonumber\\\\\n&= \\bar{\\psi}(x)\\,(i\\slashed{\\partial}-m)\\,\\Omega^\\dag\\,\\Omega\\,\\psi(x)\\nonumber\\\\\n&= \\bar{\\psi}(x)\\,(i\\slashed{\\partial}-m)\\,\\psi(x)\\nonumber\\\\\n&= \\mathcal{L}_0\\, ,\n\\end{align}\n%\nwhere we have made use of the unitarity property, $\\Omega\\,\\Omega^\\dag = I$. If this symmetry were all we required then $\\mathcal{L}_0$ would be our Lagrangian and our theory would be pleasantly simple. However, we find that we need our gauge symmetry to be \\textit{local}; that is, we demand that our gauge transformation itself be a function of $x$~\\cite{peskin2018introduction}. In this case, we find that the derivative in Eq.~\\eqref{eq:GlobalQuarkLagrangian} acting on the gauge transformation results in a loss of $SU(3)$ symmetry. We can write an arbitrary local $SU(3)$ gauge transformation as an exponential of the eight traceless, Hermitian group generators $\\lambda_a$, known as the Gell-Mann matrices (see Appendix~\\ref{app:GellMann} for their values), such that \n%\n\\begin{equation}\n\\Omega(x)=\\exp\\left(i\\omega^a(x)\\,\\frac{\\lambda_a}{2}\\right)\\, .\n\\label{eq:LocalGaugeTransformation}\n\\end{equation}\n%\nNote that we make use of the summation convention to imply a sum over the repeated indices. In this form, the spatial dependence is encapsulated entirely in the eight parameters, $\\omega^a(x)$.  Using this form for $\\Omega(x)$, we find that under a gauge transformation the Lagrangian is now\n%\n\\begin{align}\n\\mathcal{L}_0\\rightarrow\\mathcal{L^\\prime}_0&=\\bar{\\psi}(x)\\,\\Omega^\\dag(x)\\,(i\\slashed{\\partial}-m)\\,\\Omega(x)\\,\\psi(x)\\nonumber\\\\\n&=\\bar{\\psi}(x)\\,\\Omega^\\dag(x)\\left[-\\frac{\\lambda_a}{2}\\,(\\slashed{\\partial}\\,\\omega^a(x))\\,\\Omega(x)\\,\\psi(x)+ i\\,\\Omega(x)\\,(\\slashed{\\partial}\\,\\psi(x))-m\\,\\Omega(x)\\,\\psi(x)\\right]\\nonumber\\\\\n&= \\mathcal{L}_0-\\bar{\\psi}(x)\\,\\Omega^\\dag(x)\\,\\frac{\\lambda_a}{2}\\,(\\slashed{\\partial}\\,\\omega^a(x))\\,\\Omega(x)\\,\\psi(x)\\, .\n\\label{eq:LocalTrans}\n\\end{align}\n%\nIt is apparent then that gauge invariance is lost under a local gauge transformation. To restore gauge invariance, we introduce the notion of the gauge-covariant derivative\n%\n\\begin{equation}\nD_\\mu = \\partial_\\mu + ig A_\\mu(x)\\, ,\n\\label{eq:CovariantDerivative}\n\\end{equation}\n%\nwhere $A_\\mu(x)=A_\\mu^a(x)\\,\\frac{\\lambda_a}{2}$ encapsulates the eight new `gauge potentials' and $g$ is the strong coupling constant. As the gauge potentials are a linear combination of $\\lambda_a$, they belong not to the group $SU(3)$, but to the Lie algebra $\\mathfrak{su}(3)$. In the context of QCD, these gauge potentials are also known as the gluon field. For the sake of cleanliness, we will stop explicitly writing the dependence of our fields and gauge transformations on $x$ from here on, but it should be remembered that all gauge transformations are local unless explicitly stated otherwise.\\\\\n\nMaking the substitution $\\partial_\\mu\\rightarrow D_\\mu$, we obtain the new Lagrangian\n%\n\\begin{equation}\n\\mathcal{L}_\\text{quark} = \\bar{\\psi}\\,(i\\slashed{D}-m)\\,\\psi\\,.\n\\end{equation}\n%\nThis substitution introduces a new interaction term into the Lagrangian that gives rise to an interaction between our quark and gauge fields.\n%\n\\begin{equation}\n\\mathcal{L}_\\text{int} = -g\\,\\bar{\\psi}\\,A_\\mu\\,\\psi\n\\label{eq:InteractingLagrangian}\n\\end{equation}\n%\nTo preserve the gauge invariance of the Lagrangian, we need the gauge transformation property of Eq.~\\eqref{eq:InteractingLagrangian} to counteract the last term of Eq.~\\eqref{eq:LocalTrans}. Hence we require that\n%\n\\begin{align}\n-g\\,\\bar{\\psi}\\,A_\\mu\\,\\psi \\rightarrow -g\\,\\bar{\\psi}\\,A_\\mu\\,\\psi + \\bar{\\psi}\\,\\Omega^\\dag\\,\\frac{\\lambda_a}{2}(\\partial_\\mu\\,\\omega^a)\\,\\Omega\\,\\psi\\, .\n\\end{align}\n%\nMaking use of the transformation properties of $\\psi$ and $\\bar{\\psi}$, this implies that\n%\n\\begin{equation}\nA_\\mu\\rightarrow \\Omega\\,A_\\mu\\,\\Omega^\\dag + \\frac{i}{g}\\,(\\partial_\\mu\\,\\Omega)\\,\\Omega^\\dag\\, . \n\\label{eq:GaugePotentialTrans}\n\\end{equation}\n%\nThis transformation property can also be expressed in terms of the covariant derivative. Doing so, we find that\n%\n\\begin{align}\nD_\\mu\\,\\psi \\rightarrow &\\left(\\partial_\\mu +ig\\,\\Omega\\,A_\\mu\\,\\Omega^\\dag - (\\partial_\\mu\\,\\Omega)\\,\\Omega^\\dag\\right)\\,\\Omega\\,\\psi\\nonumber\\\\\n&= (\\partial_\\mu\\,\\Omega)\\,\\psi + \\Omega\\,(\\partial_\\mu\\,\\psi) + ig\\,\\Omega\\,A_\\mu\\,\\psi - (\\partial_\\mu\\,\\Omega)\\psi\\nonumber\\\\\n&=\\Omega\\,D_\\mu\\,\\psi\\, .\\label{eq:CovariantTransformation}\n\\end{align}\n%\nAnd therefore\n%\n\\begin{equation}\nD_{\\mu}\\rightarrow\\Omega\\,D_\\mu \\Omega^\\dag\n\\end{equation}\n%\nEq.~\\eqref{eq:CovariantTransformation} tells us that the covariant derivative of a quark field transforms in the same way as the quark field itself. This implies that the covariant derivative can be understood as a connection between two points that may have a different underlying gauge. For example, if we consider an infinitesimal translation in the quark field\n%\n\\begin{equation}\nd\\psi(x) = \\psi(x+dx)-\\psi(x)\\, ,\n\\end{equation} \n%\nwe note that the gauge at the point $x$ and at $x+dx$ in general will differ. It therefore does not make sense to compare the field values through the usual understanding of the derivative, as this ignores the change in local gauge. Instead, the covariant derivative accounts for this underlying gauge structure, `transporting' the field from one position to another. This is entirely analogous to the covariant derivative present in general relativity, however in this case the transport occurs over an internal gauge manifold, rather than an external curved space-time.\\\\\n\n\\subsection{Field Strength Tensor}\nUsing local gauge invariance as a guide, we can now seek other gauge invariant terms to insert into the Lagrangian. We define the gluon field strength tensor to be\n\n%If we consider the commutator of the covariant derivative, we have\n%\n%\\begin{align*}\n%[D_\\mu,\\, D_\\nu]\\rightarrow &[\\Omega\\,D_\\mu\\,\\Omega^\\dag,\\,\\Omega\\,D_\\nu\\,\\Omega^\\dag]\\\\\n%&= \\Omega\\,D_\\mu\\, D_\\nu\\,\\Omega^\\dag - \\Omega\\,D_\\nu\\, D_\\mu\\,\\Omega^\\dag\\\\\n%&= \\Omega\\,[D_\\mu,\\,D_\\nu]\\,\\Omega^\\dag\\, .\n%\\end{align*}\n%\n\n%\n\\begin{equation}\nF_{\\mu\\nu}=\\partial_\\mu A_\\nu - \\partial_\\nu A_\\mu + ig[A_\\mu,\\,A_\\nu]\\, .\n\\label{eq:FieldStrengthTensor}\n\\end{equation}\n%\nAlternatively, $F_{\\mu\\nu}$ may also be written\n%\n\\begin{align}\nF_{\\mu\\nu} = -\\frac{i}{g}\\,[D_\\mu,\\, D_\\nu]\\, .\n\\end{align}\n%\nBy making use of the gauge transformation property of $A_\\mu$, given in Eq.~\\eqref{eq:GaugePotentialTrans}, we find that the field strength tensor transforms as\n%\n\\begin{equation}\nF_{\\mu\\nu}\\rightarrow \\Omega\\,F_{\\mu\\nu}\\, \\Omega^\\dagger\\, .\n\\end{equation}\n%\nThe proof of this is given in Appendix~\\ref{app:GTF}. To obtain a gauge invariant quantity, we take the trace of the contracted field strength tensor. This allows us to make use of the cyclic property of the trace to obtain\n%\n\\begin{align}\n\\Tr(F_{\\mu\\nu}F^{\\mu\\nu})\\rightarrow &\\Tr\\left(\\Omega\\,F_{\\mu\\nu}\\, \\Omega^\\dagger\\,\\Omega\\,F^{\\mu\\nu}\\, \\Omega^\\dagger\\right)\\nonumber\\\\\n&=\\Tr\\left(\\Omega^\\dagger \\, \\Omega\\,F_{\\mu\\nu}\\,F^{\\mu\\nu}\\right)\\nonumber\\\\\n&=\\Tr(F_{\\mu\\nu}F^{\\mu\\nu})\n\\end{align}\nThus we define the full gauge invariant QCD Lagrangian to be\n%\n\\begin{equation}\n\\mathcal{L_{\\text{QCD}}}=\\bar{\\psi}(x)\\,(i\\slashed{D}-m)\\,\\psi(x)-\\frac{1}{2}\\,\\Tr(F_{\\mu\\nu}(x)\\,F^{\\mu\\nu}(x))\\, .\n\\label{eq:QCDLagrangian}\n\\end{equation}\\\\\n\nThis gluon term is not the only gauge invariant quantity we could construct; for example, $\\bar{\\psi}\\,\\psi\\,\\bar{\\psi}\\,\\psi$ is clearly gauge invariant. However, it turns out that there is a further condition that must be satisfied by each term in the Lagrangian; each term must be \\textit{renormalisable}~\\cite{peskin2018introduction}. A complete discussion of renormalisation is unnecessary for this work, but renormalisability can be quickly summarised by looking at the dimensionality of each term in the Lagrangian. The Lagrangian must have units of $(\\text{Energy})^4$, which in natural units is $(\\text{mass})^4$,  hereafter referred to as just dimension $D=4$. We therefore require that each term and its accompanying coupling constant give the same dimensionality. The fermion field has dimension $\\frac{3}{2}$, the gauge potential has dimension 1 and $\\partial_\\mu$ has dimension 1. Thus, the terms present in Eq.~\\eqref{eq:QCDLagrangian} have dimension\n%\n\\begin{align}\n\\text{D}[\\bar{\\psi}(x)\\,\\gamma^\\mu\\,\\partial_\\mu\\,\\psi(x)]&=\\frac{3}{2}+1+\\frac{3}{2}=4\\\\\n\\text{D}[\\bar{\\psi}(x)\\,\\gamma^\\mu\\,A_\\mu\\,\\psi(x)]&=\\frac{3}{2}+1+\\frac{3}{2}=4\\\\\n\\text{D}[m\\bar{\\psi}(x)\\,\\psi(x)]&=1+\\frac{3}{2}+\\frac{3}{2}=4\\\\\n\\text{D}[F_{\\mu\\nu}\\,F^{\\mu\\nu}] &= 2+2=4\\, ,\n\\end{align}\n%\nas required. This also tells us that the coupling constant $g$ is dimensionless. If a new gauge invariant term $h\\bar{\\psi}\\,\\psi\\,\\bar{\\psi}\\,\\psi$ with coupling constant $h$ is introduced then by the above rules we would require that $h$ have dimension $-2$. It turns out that if the dimensionality of the coupling constant is less than 0 then the term in non-renormalisable. This means that integrals involving this new term will diverge in such a way that they cannot be systematically be made finite through the use of a renormalisation scheme, and hence they cannot form part of any physical theory. By applying the requirements of gauge invariance and renormalisability, it is apparent that Eq.~\\eqref{eq:QCDLagrangian} is the full QCD Lagrangian.\n\n\\subsection{Pure Gauge Action}\nFor the purpose of this research, we are interested in the behaviour of gluons in the absence of any quarks, and as such we need to develop a description of pure gauge fields. In the continuum, a pure gauge field has the Lagrangian~\\cite{ryder1996quantum}\n%\n\\begin{equation}\n\\mathcal{L}_{\\text{gluon}}=\\frac{1}{2}\\Tr(F_{\\mu\\nu}\\,F^{\\mu\\nu})\\, ,\n\\label{eq:GaugeLagrangian}\n\\end{equation}\n%\nwhich we observe to be the last term in Eq.~\\eqref{eq:QCDLagrangian}. This Lagrangian has the corresponding action\n%\n\\begin{equation}\n\\mathcal{S}=\\int~d^4x~\\mathcal{L_\\text{gluon}}\\, .\n\\label{eq:QCDAction}\n\\end{equation}\n%\nWhen considering the path integral formulation of a gauge field theory, integrals such as the generating functional,\n%\n\\begin{equation}\n\\mathcal{Z} =\\int \\mathcal{D} A_\\mu \\exp\\left(i\\,\\mathcal{S}\\,[A_\\mu]\\right),\n\\label{eq:GeneratingFunctional}\n\\end{equation}\n%\nand others of a similar form appear frequently. This integral closely resembles the partition function found in statistical mechanics, $\\mathcal{Z}_{\\text{classical}}=\\int d^3x\\,d^3p\\,\\exp\\left(-\\beta\\,H(x,p)\\right)$, with the notable exception of the factor of $i$ in the exponential. From the statistical mechanics perspective, the exponential in Eq.~\\eqref{eq:GeneratingFunctional} is a probability weighting for a given gauge potential. However, unlike the classical case, the factor of $i$ in Eq.~\\eqref{eq:GeneratingFunctional} results in an oscillatory weighting, rendering numerical simulations untenable. To ensure that the weight factor is purely real, it is necessary to perform a Wick rotation to Euclidean space~\\cite{Schafer:1996wv,Wilson:1974sk} such that\n\\begin{equation}\nt \\rightarrow -it \\qquad A^0 \\rightarrow iA^0\\, .\n\\end{equation}\n%\nThis has the result of changing the action such that\n%\n\\begin{equation}\ni\\mathcal{S}_\\text{Minkowski} \\rightarrow -\\mathcal{S}_\\text{Euclidean}\\, ,\n\\end{equation} \nso that the generating functional now becomes \n%\n\\begin{equation}\n\\mathcal{Z}=\\int \\mathcal{D} A_\\mu \\exp\\left(-\\mathcal{S}_E\\,[A_\\mu]\\right).\n\\end{equation}\n%\nThis enables us to now truly consider the generating functional to be a probability weighting for a given configuration.\\\\\n\nIn Euclidean space, we can make use of the generating functional to write the expectation value of an arbitrary operator $Q[A_\\mu]$ as~\\cite{Luscher:1984xn}\n%\n\\begin{equation}\n\\langle Q \\rangle = \\frac{1}{\\mathcal{Z}}\\int \\mathcal{D} A_\\mu\\, Q[A_\\mu]\\, \\exp\\left(-\\mathcal{S}_E\\,[A_\\mu]\\right)\\, .\n\\end{equation}\n%\nThis definition of the expectation value, whilst potentially difficult or even impossible to calculate analytically, has an intuitive interpretation. To calculate the expectation value of some operator, we integrate over every possible configuration of $A_\\mu(x)$, weighted by the action of that configuration. In the case where the coupling constant $g$ of the theory is sufficiently small, as is the case for QED or high-energy QCD, it is possible to expand $\\exp\\left(-\\mathcal{S}_E\\,[A_\\mu]\\right)$ in terms of the coupling constant, leading to a perturbative expansion. Alternatively, if the only relevant configurations in the theory are those near the classical action satisfying $\\frac{\\delta S[A_\\mu]}{\\delta A_\\mu}=0$, then the action can be expanded around the classical solution. However, in the case of low-energy QCD, both of these approximations are invalid, and as such it becomes essential to sample possible configurations of $A_\\mu(x)$ and generate a representative finite subset that can be used to approximate the continuum expectation value. Obtaining this subset on which we can perform calculations is one of the key aims of lattice QCD.\n\n\\section{Lattice Discretisation}\\label{sec:LatticeDiscretisation}\nUsing the continuum understanding developed in the previous section, we can now consider discretising space-time into a finite lattice. The lattice is a hypercube with $N_s$ lattice sites in the spacial directions and $N_t$ sites in the time direction. Each lattice site is separated by a spacing $a$, resulting in a total lattice volume $V=(N_s\\,a)^3\\times N_t\\,a$. A two dimensional example of a discrete lattice with spacing $a$ is shown in Fig.~\\ref{fig:LatticeExample}. The lattice notation $\\hat{\\mu}$ is used to denote the unit vector in the $\\mu$ direction; for example, $\\hat{y} = (0,0,1,0)$. We also must impose boundary conditions for the lattice; in this work we utilise periodic boundary conditions such that $x+N_\\mu a\\hat{\\mu}=x$.\\\\\n%\n\\begin{figure}[ht]\n\\centering\n\\input{Chapter2/Figs/LatticeExample.tex}\n\\caption[An example of a 2D lattice with lattice spacing $a$.]{\\label{fig:LatticeExample} An example of a 2D lattice with lattice spacing $a$. From site $x$ we define $x+a\\hat{\\mu}$ to refer to the next lattice site in the $\\hat{\\mu}$ direction. The gauge links $U_\\mu(x)$ (see Eq.~\\eqref{eq:GaugeLink}) are defined on the links between sites. The plaquette $P_{\\mu\\nu}(x)$ (see Eq.~\\eqref{eq:Plaquette}) is the product of the four gauge links around a $1\\times 1$ loop.}\n\\end{figure}\n%\n\nWhen space-time is discretised, it becomes necessary to consider derivatives as finite differences and integrals as finite sums, such that.\n\\begin{align}\n\\partial_\\mu\\,f(x)&\\rightarrow \\frac{f(x+a\\hat{\\mu})-f(x-a\\hat{\\mu})}{2a}\\\\\n\\int d^4x~f(x) &\\rightarrow a^4\\sum_x \\,f(x)\\, .\n\\end{align}\nFor example, we can construct the lattice form of Eq.~\\eqref{eq:FieldStrengthTensor} as\n%\n\\begin{align}\nF_{\\text{Lat}}^{\\mu\\nu}(x) = &\\frac{A_\\nu(x+a\\hat{\\mu})-A_\\nu(x-a\\hat{\\mu})}{2a}-\\frac{A_\\mu(x+a\\hat{\\nu})-A_\\mu(x-a\\hat{\\nu})}{2a}\\nonumber\\\\\n&+ig[A_\\mu(x),\\,A_\\nu(x)]\\, .\n\\label{eq:DiscreteFST}\n\\end{align}\n%\nThe notation $A_\\nu(x+a\\hat{\\mu})$ denotes the field $A_\\nu$ located at the site one lattice spacing in the $\\hat{\\mu}$ direction from $x$. We could continue to reformulate our lattice theory by imposing this method of discretisation, and indeed this is historically how the lattice framework was constructed~\\cite{Wilson:1974sk}. However, it is useful to instead formulate our lattice theory in terms of gauge {\\it links}. Analogous to how we introduced the covariant derivative to compensate for the fact that the quark field at infinitesimally different points in space has a different underlying gauge, we now want to have a mechanism for comparing gluon fields at some finite separation. This requires us to solve the parallel transport equation of our gauge field~\\cite{peskin2018introduction}\n%\n\\begin{equation}\n\\frac{dx^\\mu(t)}{dt}\\,D_\\mu \\,U(x(t),y)=0\\, ,\n\\label{eq:ParallelTransport}\n\\end{equation}\n%\nwhere $U(x(t),y)$ is an $SU(3)$ element and $x(t)$ is some path parametrised by $t\\,\\in\\,[0,1]$ satisfying $x(0)=y$. We further require that $U(x(0),y)=I$, as the parallel transport for a fixed point is trivial. We can now make use of the explicit parametrisation of the path between two adjacent lattice sites, $x^\\mu(t;\\nu) = y^\\mu+a\\,t\\,\\delta_\\nu^\\mu$, where $y^\\mu$ is a fixed position and $\\nu$ is the direction we are transporting the field. Substituting this parametrisation into Eq.~\\eqref{eq:ParallelTransport} we have\n\\begin{align}\n&a\\, \\delta_\\nu^\\mu\\, (\\partial_\\mu + igA_\\mu)\\,U(x(t;\\nu),y)=0\\nonumber\\\\\n&a\\, \\partial_\\nu\\, U(x(t;\\nu),y) = -iag\\, A_\\nu\\,U(x(t;\\nu),y)\\nonumber\\\\\n&\\frac{\\partial}{\\partial t}\\, U(x(t;\\nu),y) = -iag\\,A_\\nu\\, U(x(t;\\nu),y)\\, .\n\\label{eq:PathOrderedDE}\n\\end{align}\nFor a non-Abelian field, Eq.~\\eqref{eq:PathOrderedDE} is precisely the differential equation solved by the path-ordered exponential, known as the Wilson line\n%\n\\begin{equation}\nU(x(t;\\nu),y) = \\mathcal{P}\\exp\\left(-iag\\int_0^t \\,dt^\\prime \\,A_\\nu(x(t^\\prime;\\nu))\\right)\n\\end{equation}\n%\nHence, for each direction $\\hat{\\mu}$, we define the gauge links between adjacent lattice sites to be\n%\n\\begin{equation}\nU_\\mu(x) = \\mathcal{P}\\exp\\left(-iag\\int_0^1 \\,dt \\,A_\\mu(x + at\\hat{\\mu})\\right)\\, .\n\\label{eq:GaugeLink}\n\\end{equation}\n%\nFrom this definition we also see that we can write the gauge link in the opposite direction, i.e. from $x+a\\hat{\\mu}$ to $x$, as\n%\n\\begin{align}\n\\mathcal{P}\\exp\\left(-iag\\int^0_1 \\,dt\\,A_\\mu(x + at\\hat{\\mu})\\right) &= \\mathcal{P}\\exp\\left(+iag\\int_0^1 \\,dt\\,A_\\mu(x + at\\hat{\\mu})\\right)\\nonumber\\\\\n&=U^\\dag_\\mu(x)\\, .\n\\end{align}\n%\nThese gauge links have the simple gauge transformation property~\\cite{Lepage:1998dt} (see Appendix~\\ref{app:WilsonLineGT})\n%\n\\begin{equation}\nU_\\mu(x)\\rightarrow \\Omega(x)\\,U_\\mu(x)\\,\\Omega^\\dag(x+a\\hat{\\mu})\\, .\n\\label{eq:LinkTransformation}\n\\end{equation}\n%\nMaking use of this gauge transformation property, we can construct gauge invariant Wilson loops by taking the trace of the product of the $U_\\mu$'s around a closed loop. These Wilson loops form an essential building block of the lattice action, and  appear in later chapters as quantity of interest in their own right. The simplest such loop, the $1\\times 1$ square, is called the \\textit{plaquette}, and is defined as\n\\begin{equation}\nP_{\\mu\\nu}(x) = U_\\mu(x)\\,U_\\nu(x+a\\hat{\\mu})\\, U_\\mu^\\dag(x+a\\hat{\\nu})\\, U_\\nu^\\dag(x)\\, .\n\\label{eq:Plaquette}\n\\end{equation}\nCalculating the Wilson loop by taking the trace of the plaquette we see that, by the cyclic property of the trace, the Wilson loop is gauge invariant\n\\begin{align}\n\\Tr\\left(P_{\\mu\\nu}(x)\\right)\\rightarrow& \\Tr \\left(\\Omega(x)\\,U_\\mu(x)\\Omega^\\dag(x+a\\hat{\\mu})\\,\\Omega(x+a\\hat{\\mu})\\,U_\\nu(x+a\\hat{\\mu})\\,\\Omega^\\dag(x+a\\hat{\\mu}+a\\hat{\\nu})\\right.\\nonumber\\\\\n&~~~~~\\left.\\Omega(x+a\\hat{\\mu}+a\\hat{\\nu})\\,U_\\mu^\\dag(x+a\\hat{\\nu})\\,\\Omega^\\dag(x+a\\hat{\\nu})\\,\\Omega(x+a\\hat{\\mu})\\, U_\\nu^\\dag(x)\\,\\Omega^\\dag(x)\\right)\\nonumber\\\\\n=&\\Tr\\left(P_{\\mu\\nu}(x)\\right)\\, .\n\\end{align}\nBoth the gauge links and the plaquette are also visualised in Fig.~\\ref{fig:LatticeExample}.\\\\\n\nWe now return to the lattice formulation of QCD, making use of the gauge links to define our quantities of interest. Firstly, we approximate our gauge links on the lattice by using a midpoint definition, such that\n\\begin{equation}\nU_\\mu^\\text{lat}(x) = \\exp\\left(-iag\\, A_\\mu\\left(x+\\frac{a}{2}\\hat{\\mu}\\right)\\right)\\, .\n\\label{eq:GaugeLinkLat}\n\\end{equation}\nFrom this definition, we can also recover the midpoint gauge potential~\\cite{Leinweber:1998im,Alles:1996ka}\n\\begin{equation}\nA_\\mu\\left(x+\\frac{a}{2}\\hat{\\mu}\\right) = \\frac{i}{2ag}\\left(U_\\mu(x) - U_\\mu^\\dag(x)\\right) - \\frac{i}{6ag}\\Tr\\left(U_\\mu(x) - U_\\mu^\\dag(x)\\right)I + \\mathcal{O}(a^2)\\, .\n\\label{eq:GaugePotentialLat}\n\\end{equation}\nWe then note that we can write $F_{\\mu\\nu}$ in terms of the plaquette by Taylor expanding Eq.~\\eqref{eq:Plaquette} (see Appendix \\ref{app:TEPlaquette}) to obtain~\\cite{Gupta:1997nd}\n%\n\\begin{equation}\nP_{\\mu\\nu} = I-ia^2g\\, F_{\\mu\\nu} - \\frac{a^4 g^2}{2}F^2_{\\mu\\nu} +\\mathcal{O}(a^6)\\, ,\n\\label{eq:PlaquetteExpansion}\n\\end{equation} \n%\nand hence to $\\mathcal{O}(a^2)$\n%\n\\begin{align}\n\\frac{a^4}{2}\\Tr\\left(F_{\\mu\\nu}F^{\\mu\\nu}\\right) = \\sum_{\\mu,\\,\\nu}\\frac{1}{g^2}\\Tr\\left(I-\\frac{1}{2}\\left(P_{\\mu\\nu}+P_{\\mu\\nu}^\\dag\\right)\\right)\\, .\n\\label{eq:FieldStrengthPlaquette}\n\\end{align}\n%\nWe have now arrived at a definition of the contracted field strength tensor that can be used to define our lattice action. We can make a further simplification by noting that because $P_{\\mu\\nu}=P_{\\nu\\mu}^\\dagger$, $\\Re(P_{\\mu\\nu}) = \\Re(P_{\\nu\\mu})$ and therefore we only need to sum over the 6 plaquettes for which $\\mu<\\nu$, so long as we introduce a factor of $2$. This gives us the definition of the Wilson action, \n%\n\\begin{equation}\n\\mathcal{S}_\\text{W} = \\beta\\sum_x\\,\\sum_{\\mu<\\nu} \\frac{1}{3}\\Tr\\left(I-\\frac{1}{2}\\left(P_{\\mu\\nu}+P_{\\mu\\nu}^\\dag\\right)\\right)\\, ,\n\\label{eq:WilsonAction}\n\\end{equation}\n%\nwhere $\\beta = \\frac{6}{g^2}$ is the lattice coupling constant. To remove higher order errors from the lattice action, it is possible to take into account terms containing larger Wilson loops, following procedure similar to the one outlined above~\\cite{Alford:1995hw,Symanzik:1983dc,Symanzik:1983gh}.\\\\\n\nFor the purpose of this work, the gauge fields were generated using the $\\mathcal{O}(a^2)$-improved L\\\"uscher-Weisz action~\\cite{Luscher:1984xn}, \n%\n\\begin{align}\n\\mathcal{S} _ { LW } = &\\sum_x \\left[ \\frac { 5 \\beta } { 9 } \\sum _ { \\mu < \\nu } \\operatorname { Tr } \\left\\{ 1 - \\frac { 1 } { 2 } \\left( P _ { \\mu \\nu } + P _ { \\mu \\nu } ^ { \\dagger } \\right) \\right\\}\\right. \\nonumber\\\\\n& \\left.- \\frac { \\beta } { 36 u _ { 0 } ^ { 2 } } \\sum _ { \\text { rect } } \\operatorname { Tr } \\left\\{ 1 - \\frac { 1 } { 2 } \\left( R _ { \\mu \\nu } + R _ { \\mu \\nu } ^ { \\dagger } \\right) \\right\\}\\right]\\, ,\n\\end{align}\n%\nwhere\n\\begin{equation}\nu_0 = \\left(\\frac{1}{3}\\operatorname{ Re } \\Tr\\langle P_{\\mu\\nu} \\rangle\\right)^{\\frac{1}{4}}\\, ,\n\\end{equation}\nand $R_{\\mu\\nu}$ is the $2\\times 1 + 1\\times 2$ rectangular Wilson loop, defined similarly to the plaquette \n\\begin{align}\n R _ { \\mu \\nu } ( x ) = \\, &  U_\\mu( x )\\, U_\\nu( x + \\hat { \\mu } )\\, U_\\nu( x + \\hat { \\nu } + \\hat { \\mu } )\\, U_\\mu^\\dagger ( x + 2 \\hat { \\nu } )\\, U _\\nu^\\dagger( x + \\hat { \\nu } )\\, U_\\nu^\\dagger( x )\\nonumber\\\\\n&+ U_\\mu ( x )\\, U_\\mu ( x + \\hat{\\mu} )\\, U_\\nu( x + 2 \\hat { \\mu } )\\, U_\\mu^\\dagger ( x + \\hat { \\mu } + \\hat { \\nu } )\\, U_\\mu^\\dagger ( x + \\hat { \\nu } )\\, U_\\nu^\\dagger( x ) \\, .\n\\end{align}\nThe presence of the `tadpole' improvement factor $u_0$ is necessary to ensure the perturbatively defined coefficient is accurate~\\cite{Lepage:1992xa}. This choice of action provides reduced errors in comparison to the Wilson action.\\\\\n\nThis lattice framework provides the tools necessary to explicitly calculate quantities of interest from a first-principles standpoint. Firstly, the gauge links are generated by Markov-chain Monte Carlo methods, using $\\exp\\left(-\\mathcal{S}\\right)$ as a probability weighting in the Metropolis accept/reject for a given configuration. Once these configurations are generated, gauge fixing can be performed (Sec.~\\ref{sec:LandauGauge}, \\ref{sec:MCG}), and quantities of interest such as the gluon propagator (Chapter~\\ref{chapter:GluonPropagator}) can be obtained.\n\n\\section{Gauge Fixing}\nThe choice of gauge is crucial when performing calculations of quantities which are gauge dependent. There are two choices of gauge relevant to this study: Landau gauge and maximal centre gauge. Maximal centre gauge is best explored in the context of centre vortices, and will therefore be detailed in Chapter~\\ref{sec:MCG}, however the Landau gauge fixing condition provides a good introduction to the gauge-fixing procedure, and as such will be described here.\n\n\\subsection{Landau Gauge}\\label{sec:LandauGauge}\n\nIn the continuum, Landau gauge corresponds to imposing the condition\n\\begin{equation}\n\\partial_\\mu A^\\mu = 0\\, .\n\\label{eq:LandauGaugeCont}\n\\end{equation}\n%\nOn the lattice, we can approximate this condition by imposing\n\\begin{equation}\n\\Delta(x) = \\sum _ { \\mu } A _ { \\mu } \\left( x + \\frac{a}{2}\\hat { \\mu } \\right) - A _ { \\mu } \\left( x-\\frac{a}{2}\\hat { \\mu } \\right) = 0\\, .\n\\label{eq:LandauGaugeLat}\n\\end{equation}\nHere the fact that we have defined the lattice gauge potential to be at the midpoint of the link produces an improved continuum limit when we consider Eq.~\\eqref{eq:LandauGaugeLat} in momentum space~\\cite{Alles:1996ka}. The Landau gauge condition is imposed on the lattice by finding extrema of the $\\mathcal{O}(a^2)$-improved functional~\\cite{Bonnet:1999mj}\n%\n\\begin{equation}\n\\mathcal{F} =  \\frac{4}{3}\\mathcal{F}_1 - \\frac{1}{12u_0}\\mathcal{F}_2\\, ,\n\\label{eq:LGFunctional}\n\\end{equation}\n%\nwhere\n%\n\\begin{align}\n\\mathcal{F}_1 &= \\sum _ { \\mu , x } \\frac { 1 } { 2 } \\operatorname { Tr } \\left\\{ U _ { \\mu } ^ { \\Omega } ( x ) + U _ { \\mu } ^ { \\Omega } ( x ) ^ { \\dagger } \\right\\}\\\\\n\\mathcal{F}_2 &= \\sum _ { \\mu , x } \\frac { 1 } { 2 } \\operatorname { Tr } \\left\\{ U _ { \\mu } ^ { \\Omega } ( x ) \\,U _ { \\mu } ^ { \\Omega } ( x + a\\hat { \\mu } ) + U _ { \\mu } ^ { \\Omega } ( x + a\\hat { \\mu } )^\\dagger\\, U _ { \\mu } ^ { \\Omega } ( x )^\\dagger  \\right\\}\\, .\n\\end{align}\n%\nWe explicitly write $U^\\Omega_\\mu$ to emphasise that we are considering gauge links under an as yet unknown gauge transformation $\\Omega$. It becomes apparent why we seek the extrema of this particular functional when we take the functional derivative with respect to the free parameters of the gauge transformation , $\\omega^a(x)$ (see Eq.~\\eqref{eq:LocalGaugeTransformation}).\n%\n\\begin{equation}\n\\frac { \\delta \\left\\{ \\frac { 4 } { 3 } \\mathcal { F } _ { 1 } - \\frac { 1 } { 12 u _ { 0 } } \\mathcal { F } _ { 2 } \\right\\} } { \\delta \\omega ^ { a } ( x ) } = g a ^ { 2 } \\sum _ { \\mu } \\operatorname { Tr } \\left\\{ \\left[ \\partial _ { \\mu } A _ { \\mu } ( x ) - \\frac { 4 } { 360 } a ^ { 4 } \\partial _ { \\mu } ^ { 5 } A _ { \\mu } ( x ) + \\mathcal { O } \\left( a ^ { 6 } \\right) \\right] \\frac{\\lambda^a}{2} \\right\\} + \\mathcal { O } \\left( g ^ { 3 } a ^ { 4 } \\right)\\, .\n\\label{eq:LGFunctionalDeriv}\n\\end{equation}\n%\nIf Eq.~\\eqref{eq:LGFunctionalDeriv} is at an extrema, then \n%\n\\begin{equation}\n\\sum_\\mu \\partial_\\mu A_\\mu(x) = \\sum_\\mu \\frac{4}{360}a^4 \\partial_\\mu^5\\,A_\\mu(x) + \\mathcal{O}(a^6)+\\mathcal{O}(g^3a^4)\\, .\n\\end{equation}\n%\nHence up to errors of order $\\mathcal{O}(a^4)$, finding the extrema of Eq.~\\eqref{eq:LGFunctionalDeriv} is equivalent to satisfying the continuum Landau gauge condition given in Eq.~\\eqref{eq:LandauGaugeCont}. This Landau gauge fixing method gives an example of how a gauge choice can be implemented on a discrete lattice such that it approximates the continuum condition. This in turn enables us to use the continuum Landau gauge definition of the gluon propagator as described in Chapter~\\ref{chapter:GluonPropagator}, which forms a vital component of this research.\n", "meta": {"hexsha": "1dc084d92e15bf15d4715289dbf74e5435b7b493", "size": 29731, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapter2/chapter2.tex", "max_stars_repo_name": "jamesbiddle/Masters_Thesis", "max_stars_repo_head_hexsha": "275177c3167b490d678575f0078cc6c87614b7bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter2/chapter2.tex", "max_issues_repo_name": "jamesbiddle/Masters_Thesis", "max_issues_repo_head_hexsha": "275177c3167b490d678575f0078cc6c87614b7bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter2/chapter2.tex", "max_forks_repo_name": "jamesbiddle/Masters_Thesis", "max_forks_repo_head_hexsha": "275177c3167b490d678575f0078cc6c87614b7bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 76.2333333333, "max_line_length": 1161, "alphanum_fraction": 0.7092596953, "num_tokens": 9335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.31165396644679083}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\section*{Fri Oct 11 2019}\n\n\\subsection{Bases}\n\nIn Euclidean 2D geometry we can choose,  for example, the basis \\(e_1 = (1,0)^\\top\\) and \\(e_2 = (0,1)^\\top\\). This basis is  orthonormal with respect to the scalar product \\(g_{\\mu \\nu} = \\delta_{\\mu \\nu}\\): \\(e_{(\\alpha)} \\cdot e_{(\\beta)} = e_{(\\alpha)}^{\\mu} e_{(\\beta)}^{\\nu} g_{\\mu \\nu} =  g_{(\\alpha) (\\beta)}\\).\n\n\nI use parentheses around indices to denote the fact that they are not tensorial indices, but instead denote which basis vector we are considering.\nWe express our vectors in components with respect to this basis.\n\nIn SR, we can do the same: our coordinate basis can be given by \\(e_{(\\alpha)}^{\\mu} = \\delta_{(\\alpha)}^{\\mu}\\).\nNow, the orthonormality \\(e_{(\\alpha)} \\cdot e_{(\\beta)} = g_{(\\alpha) (\\beta)}\\) holds with respect to \\(g_{\\mu \\nu} = \\eta_{\\mu \\nu}\\).\n\n% what's your name? my name is $e_1$...\n\n\\subsection{Observers \\& observations} \n\nEvery observer will be characterized by their trajectory \\(x^{\\mu}(\\tau)\\).\nWe can associate a coordinate system with the observer: the one in which the observer's own  4-velocity \\(u^{\\mu}\\) is the time-like unit vector (rescaled by a factor of \\(c\\): \\(u^{\\mu} = ce_{(0)}\\)).\n\nWhen the observer sees a particle with \\(p^{\\mu} = (E_p / c, p^i)\\) they measure the energy of the particle to be \\(p^{0}c\\): in this frame this is \\(E_{\\text{measured}} = - e_{(0)}^\\mu p_{\\mu} c = - u^{\\mu} p_{\\mu} c\\). \nDo note that this is a covariant expression, while \\(p^{0}\\) is not: the energy of a particle with 4-momentum \\(p^{\\mu}\\) measured by an observer with 4-velocity \\(u^{\\mu}\\) is an invariant. \n\nIn the rest frame of the observer, their own 4-velocity is \\((c, \\vec{0}) = c (1, \\vec{0})\\).\nIn the rest frame of the particle, its own energy is measured to be \\(mc^2\\).\nThe measured energy by an observer such that the product of the 4-velocities of the particle and of the observer is \\(-\\gamma c^2\\) is \\(m \\gamma c^2\\).\n\nThe Earth moves with speed \\(\\num{e-4}  c\\) around the Sun.\n\n% wooooo\n\nNow we can start using \\(c=1\\). We can put the \\(c\\) back whenever we want with dimensional analysis.\n\n\\section{Newtonian Gravity}\n\n\\subsection{The Equivalence Principle}\n\nJust like Newton supposedly thought about universal gravity when, while looking at the sky, an apple fell on his head; Einstein supposedly thought up the equivalence principle when he saw a man falling from a rooftop.\n\n\\begin{proposition}[Equivalence principle]\nExperiments in a small free falling system over a short amount of time give the same result as experiments in an inertial frame in empty space.\n\\end{proposition}\n\nWhy ``small''? The gravitational field is not really homogeneous.\nThe idea is that gravity can only be removed \\emph{locally}, if we consider an extended system there are \\emph{tidal effects}.\n\nIf we were to see that objects fall differently even in the same neighbouhood then we would lose the EP.\n\n\\begin{definition}\nThe \\emph{inertial} mass is an object's resistance to motion: \\(m _{\\text{inertial}} = F^{i}/ a^{i}\\).\n\\end{definition}\n\n\\begin{definition}\nThe \\emph{gravitational} mass is the one which defines the gravitational force on an object: \\(m _{\\text{gravitational}} = \\abs{F} r^2 / (G M)\\).\n\\end{definition}\n\nThese are \\emph{a priori} different, but experimentally equal: in general the gravitational acceleration is given by\n\\begin{equation}\na^{i} = \\frac{GM r^{i} }{r^3} \\frac{m _{\\text{gravitational}}}{m _{\\text{inertial}}}  \n\\end{equation}\n\nIf the ratio of masses depended on the material, this could vary.\n\nWe can do a torsion pendulum experiment: the torsion applied by the Coriolis effect on a pendulum depends on the inertial mass, while its restoring force depends on the gravitational mass.\nExperimentally we have measured them to be equal with an accuracy of \\(\\num{e-12} \\).\n\nA person on a rocket accelarating at \\(g\\) experiences the same acceleration as a person standing on Earth.\n\n\\subsection{Gravitational redshift}\n\nWe treat it now in a weak field approximation.\n\n% now with gender roles!\n\nAlice sends radiation to Bob from a higher altitude on Earth. Alice sends it with frequency \\(f\\), Bob receives it with \\(f'\\). They are at rest with respect to one another: there is no kinematic Doppler effect here.\n\nWe do this by applying the equivalence principle! We imagine A and B to be standing in a rocket which is accelerating at \\(g\\):\nthere is no more gravity.\n\nBob will receive a greater frequency: \\(f'>f\\). This can be seen by imagining two consecutive wavefronts as two particles. Alice sends them \\(\\Delta t_A = 1/f\\) apart, Bob receives them as \\(\\Delta t_B=1/f'\\) apart.\n\nIf the rocket is at rest, the time for the radiation to reach B is \\(h/c\\); if the rocket is moving then the time is \\(<h/c\\).\n\nWhen the second wavefront starts moving the rocket is already going: the second wave starts later but it has less distance to travel. Therefore \\(\\Delta t_A > \\Delta t_B\\), which implies \\(f'>f\\).\n\n\\begin{claim}\n    The first terms in the expansion are:\n    \\begin{equation}\n        f' = f \\qty(1+ \\frac{gh}{c^2} + O \\qty(\\qty(\\frac{gh}{c^2})^2))\\,.\n    \\end{equation}\n\\end{claim}\n    \n\\subsection{Potentials}\n\nIn electromagnetism, the potential energy between a charge \\(Q\\) and a test charge \\(q\\) is \\(U = k Qq/r\\): then we define the electromagnetic potential \\(V = U/q\\) which has the advantage of being test-charge independent.\n\nSimilarly, we define the gravitational potential \\(\\Phi = U/m \\approx gh\\) in the regime in which we are far enough from the object that the gravitational field can be well approximated as a constant vector field.\n\nThen, the second order term in the formula for the redshift becomes \\(\\Delta \\Phi c^{-2}\\): now we can properly say that this \\emph{weak field} means \\(\\Delta \\Phi c^{-2} \\ll 1\\).\n\nThis is surely the case for the cases we can treat concretely.\nIf two people are separated by \\SI{1}{km} of difference in altitude, they have \\(\\Delta \\Phi c^{-2} \\approx \\num{e-13} \\): the difference they will experience is one second in a million years.\n\nOur expression from \\(\\Phi \\) in the newtonian approximation is \\(\\Phi = GM /r\\).\n\nWe can say even now by dimensional analysis that \\(GM / (rc^2)\\) is the parameter which tells us how relevant the gravitational effects are: if it is similar to 1 we must consider GR, if it is much smaller than 1 the GR effects will be negligible.\n\nThis is very close to the expression for the Schwarzschild radius: it is \\(r=GM\\) in units \\(c=1\\), while the correct expression is \\(r= 2GM\\): that one can actually be recovered exactly if we calculate the radius at which the escape velocity is equal to \\(c\\).\n\n\\end{document}\n", "meta": {"hexsha": "bc39378490c413ffd495f3d6f47a00c29909f1ac", "size": 6698, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ap_first_semester/general_relativity/11oct.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "ap_first_semester/general_relativity/11oct.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ap_first_semester/general_relativity/11oct.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 58.7543859649, "max_line_length": 319, "alphanum_fraction": 0.7160346372, "num_tokens": 1844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.5506073655352403, "lm_q1q2_score": 0.3116539664467908}}
{"text": "\\documentclass[12pt]{article}\n\\usepackage[arabmaths]{luabidi}\n\\begin{document}\n\\setRTLmain\n\\section{ghesmate 1}\n\nin yek ghesmat ast ke an ra dar inja minevisam\n\n\\begin{equation}\n1+2=3\n\\end{equation}\nin ham dobare masalei ast ke man minevisam va shoma an ra mibinid.\n\\end{document}\n", "meta": {"hexsha": "1b51109ad46169da4e1bbcee583a106d63c82d9f", "size": 281, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/test.tex", "max_stars_repo_name": "jspitz/luabidi", "max_stars_repo_head_hexsha": "c4b786c318421f3db7328f470b7e292e7cb4747d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-11-06T03:49:54.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-19T15:21:10.000Z", "max_issues_repo_path": "doc/test.tex", "max_issues_repo_name": "jspitz/luabidi", "max_issues_repo_head_hexsha": "c4b786c318421f3db7328f470b7e292e7cb4747d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2019-07-23T15:00:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-21T13:36:23.000Z", "max_forks_repo_path": "doc/test.tex", "max_forks_repo_name": "jspitz/luabidi", "max_forks_repo_head_hexsha": "c4b786c318421f3db7328f470b7e292e7cb4747d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-08-24T15:55:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-24T15:55:45.000Z", "avg_line_length": 20.0714285714, "max_line_length": 66, "alphanum_fraction": 0.7722419929, "num_tokens": 104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3115601855377086}}
{"text": "Recurrent neural networks (RNNs) are Turing-Complete models that can perform\r\ncomplex transformations on the data over an extended period of time\r\n\\cite{siegelmann1995computational}. Since RNNs are Turing-Complete, it is\r\nevident that these models in theory can be used to solve any problems a\r\nTuring machine can solve. However, a given problem may require a very specific\r\nand complex setup of an RNN. Therefore we do not take the time to set up\r\nRNNs manually in a way that it solves a specific problem. Rather, we design\r\nrich architectures with the means of learning how to solve a problem in\r\nan efficient manner. RNNs and models alike are trained using gradient descent\r\nso that it solves a given problem with greater accuracy than before.\r\n\r\n\\section{Neural Turing Machines}\r\nThe Neural Turing Machine (NTM) is an RNN with a rich design that enables it to\r\nlearn how to solve problems better than basic RNNs. The NTM is an RNN with the\r\nmeans of addressing a differentiable memory unit external to that of the model\r\nitself \\cite{DBLP:journals/corr/GravesWD14}.\r\nBecause of this differentiable memory unit, the model can learn what is most\r\nimportant to store in memory. An efficient model would learn what information\r\nis most useful and store that in memory to be read at a later timestep with the\r\nassumption that the read results in a better solution to the task.\r\nThis creates a model that can more strongly refer to important imformation\r\nthat was present much earlier than a given timestep.\r\n\r\nThe NTM can be described as four main components: controller, read heads,\r\nwrite heads, memory. The data flow of these four components is described\r\nin Figure ~\\ref{fig:NTMArchitecture}. Even though these components work in a\r\nnon-traditional manner, the model as a whole can be interacted with and\r\ntrained the same way you would any other RNN. The model simply receives\r\nsome external input at each timestep and will produce an external output\r\nat each timestep. The components of the NTM are comparable to that of a\r\nTuring machine, such that it contains read and write heads that interact\r\nwith a memory unit \\cite{DBLP:journals/corr/GravesWD14}. Unlike a Turing\r\nmachine however, the NTM is end to end differentiable\r\n\\cite{DBLP:journals/corr/GravesWD14}. This feature gives the model a lot of\r\npower in the field of Deep Learning research.\r\n\r\n\\begin{figure}[!htb]\r\n    \\centering\r\n    \\includegraphics[width=0.9\\linewidth]{resources/NTM.png}\r\n    \\caption{\r\n        The components inside the dotted line represent everything the NTM\r\n        is. The arrows represent the control flow of the data starting\r\n        as \\textit{External Input} fed into the \\textit{Controller}. The\r\n        \\textit{Controller} can then activate either \\textit{Read Heads} or\r\n        \\textit{Write Heads}. The \\textit{Read Heads} do not receive any\r\n        information about the \\textit{External Input}, but is rather told what\r\n        to read in \\textit{Memory} by the \\textit{Controller}. The\r\n        \\textit{Controller} can send information from the\r\n        \\textit{External Input} to the \\textit{Write Heads} which then\r\n        write that information into memory. The \\textit{Controller} receives\r\n        data back from the \\textit{Read Heads} and then produces an\r\n        \\textit{External Output} \\cite{DBLP:journals/corr/GravesWD14}.\r\n    }\r\n    \\label{fig:NTMArchitecture}\r\n\\end{figure}\r\n\r\nThe memory unit is a matrix where the rows represent a memory location and the\r\nnumber of columns correspond to how large each memory location is\r\n\\cite{DBLP:journals/corr/GravesWD14}. The read head emits a weighting vector\r\nthe length of the number of memory locations at each timestep\r\n\\cite{DBLP:journals/corr/GravesWD14}. A read operation on the memory matrix\r\nis then a convex combination between this weighting and the contents of the\r\nmemory matrix \\cite{DBLP:journals/corr/GravesWD14}. Using a weighting vector\r\nhere empowers the read head to narrowly focus on a single memory location's\r\ninformation or to use a wider focus by using a little bit of information\r\nfrom many different memory locations. The differentiability of the model allows\r\nthe read heads to learn the best weighting vectors to emit at a given state for\r\nsome timestep.\r\n\r\nWriting to memory in the NTM is done with an erase operation followed by an\r\naddition operation \\cite{DBLP:journals/corr/GravesWD14}. The write head\r\nemits three vectors at each timestep: \\textit{weighting vector, erase vector,\r\nadd vector} \\cite{DBLP:journals/corr/GravesWD14}. Assuming a weighting of $1$\r\nfor a memory location, a value of $1$ in the \\textit{erase vector} at location\r\n$j$ would mean to set the memory to $0$ in column $j$ within that memory\r\nlocation \\cite{DBLP:journals/corr/GravesWD14}. However, an\r\n\\textit{erase vector} with a value of $1$ can possibly not erase any\r\ninformation in a memory location if the weighting for that memory location is\r\n$0$ \\cite{DBLP:journals/corr/GravesWD14}. So the \\textit{erase vector}\r\nrepresents the degree to which information in columns for weighted memory\r\nlocations shall be erased. As one would suspect, the \\textit{add vector} works\r\nquite oppositely from that of the \\textit{erase vector}. Again assuming a\r\nweighting of $1$ for a memory location, a value of $1$ in the\r\n\\textit{add vector} at location $j$ would mean to add $1$ to whatever value\r\nis already stored in that memory location in column $j$\r\n\\cite{DBLP:journals/corr/GravesWD14}. Similarly to that of the\r\n\\textit{erase vector}, the weighting can overrule the \\textit{add vector} by\r\nhaving a value of $0$ for some location \\cite{DBLP:journals/corr/GravesWD14}.\r\nIn other words, a value of $0$ in the \\textit{weighting vector} means it does\r\nnot matter what the \\textit{add vector} is because nothing will be added to\r\nthat memory location.\r\n\r\nThe weighting vectors emitted by both read and write heads are done so\r\nthrough two different addressing mechanisms: \\textit{content-based addressing},\r\n\\textit{location-based addressing} \\cite{DBLP:journals/corr/GravesWD14}.\r\nContent-based addressing compares a key vector with all of the memory locations\r\n\\cite{DBLP:journals/corr/GravesWD14}. This produces a weighting that has\r\ngreater values in locations that are most similar to that key vector and\r\nlesser values in locations that are least similar to that key vector\r\n\\cite{DBLP:journals/corr/GravesWD14}. This addressing mechanism is useful for\r\neasily identifying data in the memory matrix simply by producing an\r\napproximation of that data. The location-based addressing mechanism is better\r\nsuited for iterating through sequence data or even jumping to a specific\r\nmemory location that may have a range of unknown data stored there. If the\r\nprevious weighting for a head was focused on location $j$, the location-based\r\naddressing mechanism can easily produce a new weighting that focuses on\r\nlocation $j-1$, $j$, or $j+1$. The choice between using these two addressing\r\nmechanisms is controlled through a gating parameter emitted by the controller.\r\nIf this gating parameter is equal to $0$, then it will only use location-based\r\naddressing. If the gating parameter is equal to $1$, then it will only use\r\ncontent-based addressing. If the gating parameter is somewhere between\r\n$0$ and $1$, it will use a mixture of both addressing mechanisms.\r\n\r\n\\section{Differentiable Neural Computers}\r\nThe Differentiable Neural Computer (DNC) is similar to that of the NTM, but\r\nenhanced in it's ability to address the augmented external memory. These\r\nenhancements make the DNC more capable than the NTM at solving complex,\r\nstructured tasks. Similarly to the NTM, the DNC is differentiable end-to-end\r\nexcept one operation in which the researchers claim do not make a significant\r\nimpact on the model as a whole \\cite{graves2016hybrid}.\r\n\r\nA NTM is allowed any number of read and write heads, but the DNC limits\r\nthe number of write heads to be only one \\cite{graves2016hybrid}. The NTM\r\nwas only able to iterate through consecutive written locations until a\r\ncontent-based addressing write occured \\cite{graves2016hybrid}. The DNC,\r\nhowever, can continue iterating through consecutive written locations because\r\nit has, what the researchers call, a temporal linkage matrix\r\n\\cite{graves2016hybrid}. The temporal linkage matrix, $L$, is $N \\times N$ with\r\nweighted values between zero and one \\cite{graves2016hybrid}. A value closer\r\nto one at position $(i, j)$ means memory location $i$ was written to directly\r\nafter memory location $j$ was written to \\cite{graves2016hybrid}. Otherwise,\r\nthe value should be near zero \\cite{graves2016hybrid}. So given a weighting\r\nvector, $\\bf{w}$, the vector produced by $L\\bf{w}$ augments the weighting to\r\nfocus on memory locations written to directly \\textit{after} those\r\nlocations focused on by weighting $\\bf{w}$ \\cite{graves2016hybrid}.\r\nConveniently, the vector produced by $L^\\top \\bf{w}$ augments the weighting to\r\nfocus on memory locations written to directly \\textit{before} those\r\nlocations focused on by weighting $\\bf{w}$ \\cite{graves2016hybrid}. This\r\ninteraction between the temporal linkage matrix and the external memory is one\r\nof the three differentiable attention mechanisms in the DNC\r\n\\cite{graves2016hybrid}. This attention mechanism replaces the location-based\r\naddressing method from the NTM. The temporal linkage matrix allows the DNC to\r\nbetter handle sequential data that is not necessarily written to in sequential\r\nmemory locations. This is a more powerful concept than that of the NTM's\r\nlocation-based addressing mechanism which was limited to sequential\r\nmemory locations.\r\n\r\nLike the NTM, the DNC uses a content-based addressing mechanism that produces\r\na weighting vector focusing on memory locations most similar to some\r\nemitted key vector \\cite{graves2016hybrid}. Similarity in both cases are\r\ndefined as cosine similarity\r\n\\cite{DBLP:journals/corr/GravesWD14,graves2016hybrid}. If the DNC controller\r\nemits a key vector with only part of the information it needs, this\r\ncontent-based addressing mechanism can be used to read the complete\r\ninformation related to it. In theory this allows the DNC to iterate\r\nthrough data structures in which memory locations reference other memory\r\nlocations through a key-value address mechanism.\r\n\r\nUnlike the NTM, the DNC uses a \\textit{usage vector} to find the best memory\r\nlocations to write to and to identify any important memory locations not to\r\nwrite to \\cite{graves2016hybrid}. The vector's values range between zero and\r\none, where values closer to one means the memory locations have greater usages\r\n\\cite{graves2016hybrid}. The weighting vector given to a write head focuses on\r\nunused locations, where the usage vector has low values\r\n\\cite{graves2016hybrid}. When the write head writes to a memory location, the\r\nusage vector is updated at that memory location by increasing the value\r\n\\cite{graves2016hybrid}. The usage vector is also capable of decreasing values\r\nin a memory location after it is read \\cite{graves2016hybrid}. For example,\r\nconsider a task which provides a sequence of numbers and then asks what that\r\nsequence was. After asking for what a sequence was, it will provide a new\r\nsequence of numbers and repeat itself. The DNC can learn to write that\r\nsequence of numbers in the external memory using the write heads. At that\r\npoint, the usage vector will have greater values in those locations written\r\nto and lower values in the locations not needed. When the task asks for the\r\nsequence of numbers, the DNC would use the read heads to read those locations\r\nwritten to. After the reads, the usage vector will update the memory locations\r\nto have low usage. This effectively reallocates the memory locations for\r\nlater usage.\r\n\r\nThe DNC is very comparable to how a human interacts with what we think of as\r\na modern day computer. Much of the human interaction with computers are done\r\nautomatically with a trained DNC. For instance, a human controls more or less\r\nexactly what to read and write in memory. The DNC however, learns what\r\ninformation is most useful to read and write in memory without being controled\r\nby an external force. When a human deletes data on a computer, they are\r\nessentially reallocating space in their memory for future data to be stored.\r\nIn this same manner, the DNC automatically learns when to reallocate memory\r\nbased on the task given. So as the name suggests, the DNC can be thought of\r\nas a differentiable computer. This does not mean that a DNC will ever take the\r\nplace of a modern day computer because the applications are different. When\r\nwe interact with a computer, we expect the memory to always be there regardless\r\nof how often we may use it. Having the computer automatically erase data\r\nbecause it thinks you do not need it would be very unfavorable for many users.\r\nHowever, a DNC is a model that learns how to represent complex data\r\nstructures to solve difficult tasks that cannot otherwise be solved.\r\n\r\nThe DNC has been found to be useful in a variety of experimental applications.\r\nThe researchers show that the DNC outperforms the previous best models in\r\na synthetic question answering task using the bAbI dataset\r\n\\cite{graves2016hybrid}. The following example shows that the DNC is able to\r\ncombine supporting facts together to come up with a solution\r\n\\cite{graves2016hybrid}:\r\n\\begin{align*}\r\n\\textnormal{\\bf{Input: }}  & \\quad \\textnormal{John is in the playground. John\r\n                                               picked up the football.} \\\\\r\n\\textnormal{\\bf{Input: }}  & \\quad \\textnormal{Where is the football?} \\\\\r\n\\textnormal{\\bf{Output: }} & \\quad \\textnormal{playground.}\r\n\\end{align*}\r\nAn even more complex task is to still be able to combine supporting facts\r\nbut also have resilience to distractors in the input \\cite{graves2016hybrid}:\r\n\\begin{align*}\r\n\\textnormal{\\bf{Input: }}  & \\quad \\textnormal{Sheep are afraid of wolves.\r\n                             Gertrude is a sheep.} \\\\\r\n                           & \\quad \\textnormal{Mice are afraid of cats.} \\\\\r\n\\textnormal{\\bf{Input: }}  & \\quad \\textnormal{What is Gertrude afraid of?} \\\\\r\n\\textnormal{\\bf{Output: }} & \\quad \\textnormal{wolves.}\r\n\\end{align*}\r\nThis example requires the DNC to have textual reasoning and be able to ignore\r\nthe last sentence that is unecessary to answer the question. This shows that\r\nthe differentiable attention mechanisms in the DNC are working and capable\r\nof handling complex tasks such as this.\r\n\r\nTo test how the DNC handles data structures, the researchers explored\r\nperformance on graph problems: \\textit{traversal}, \\textit{shortest path},\r\n\\textit{inference} \\cite{graves2016hybrid}. Before the model was asked to solve\r\none of these problems, it would first receive a graph as input. The model would\r\nlearn how to represent this graph in external memory. When the model is asked\r\nto complete a traversal task, it receives a starting node and a path in the\r\ngraph \\cite{graves2016hybrid}. The model must then output the ending node of\r\nthe path, requiring a traversal through the graph \\cite{graves2016hybrid}.\r\nThe shortest path problem was given by a start and end node\r\n\\cite{graves2016hybrid}. The model must output the in-order path from start to\r\nend. The inference task is given by an incomplete triple\r\n(\\quotes{from node}, \\quotes{to node}, \\quotes{relation}), where one of the\r\nthree were missing \\cite{graves2016hybrid}. For example, if \\quotes{to node} is\r\nmissing from the input, the model must infer what node has the given\r\nrelationship with \\quotes{from node}. In the example of a family tree, one\r\nmight ask (\\quotes{Jen}, \\quotes{\\_}, \\quotes{MaternalGreatUncle}). For which,\r\nif Joe is Jen's Maternal-Great-Uncle, then the model is expected to output\r\nthe triple (\\quotes{Jen}, \\quotes{Joe}, \\quotes{MaternalGreatUncle}). This task\r\nrequires the model to not only learn how to traverse the graphs, but to learn\r\nthe meaning of relationships.\r\n\r\nWhen the three graph problems were tested on the DNC and a baseline LSTM, the\r\nDNC produced much better results while the LSTM failed to even learn the\r\neasiest task of traversal \\cite{graves2016hybrid}. When tested on randomly\r\ngenerated paths of length seven, the DNC performed with an accuracy of 98.8\\%\r\nand the LSTM performed with an accuracy of 37\\% \\cite{graves2016hybrid}. This\r\nshows how the DNC can solve problems otherwise unsolvable because the DNC has\r\nan external memory with read and write access. The DNC performed at an accuracy\r\nof 55.3\\% when tested on shortest paths of length four \\cite{graves2016hybrid}.\r\nOn the last task, inference, the DNC performed with accuracy 81.8\\% when tested\r\non relationships that connect nodes with distance four \\cite{graves2016hybrid}.\r\n", "meta": {"hexsha": "eff2ae548c171f2959deb41c3d021520571aca59", "size": 16745, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/sections/background.tex", "max_stars_repo_name": "derrowap/DNC-TensorFlow", "max_stars_repo_head_hexsha": "3e9ad109f8101265ae422ba9c20e058aa70ef7df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-10-29T18:42:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-02T16:39:32.000Z", "max_issues_repo_path": "paper/sections/background.tex", "max_issues_repo_name": "derrowap/DNC-TensorFlow", "max_issues_repo_head_hexsha": "3e9ad109f8101265ae422ba9c20e058aa70ef7df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-10-11T00:28:05.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-11T00:30:11.000Z", "max_forks_repo_path": "paper/sections/background.tex", "max_forks_repo_name": "derrowap/DNC-TensorFlow", "max_forks_repo_head_hexsha": "3e9ad109f8101265ae422ba9c20e058aa70ef7df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 65.9251968504, "max_line_length": 80, "alphanum_fraction": 0.7761122723, "num_tokens": 3944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.31153849708867426}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This work is licensed under the Creative Commons Attribution 4.0 International %\n% License. To view a copy of this license, visit                                 %\n% http://creativecommons.org/licenses/by/4.0/.                                   %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\documentclass[11pt]{article}\n\\usepackage[cm]{fullpage}\n%%AVC PACKAGES\n\\usepackage{avcgreek}\n\\usepackage{avcfonts}\n\\usepackage{avcmath}\n\\usepackage[numberby=section]{avcthm}\n\\usepackage{qcmacros}\n\\usepackage{goldstone}\n%%MACROS FOR THIS DOCUMENT\n\\numberwithin{equation}{section}\n\\usepackage[\n  margin=1.5cm,\n  includefoot,\n  footskip=30pt,\n  headsep=0.2cm,headheight=1.3cm\n]{geometry}\n\\usepackage{fancyhdr}\n\\pagestyle{fancy}\n\\fancyhf{}\n\\fancyhead[LE,RO]{Quiz 2, Handout 1: Roothaan-Hall/Pople-Nesbet}\n\\fancyfoot[CE,CO]{\\thepage}\n\\usepackage{url}\n\n\\begin{document}\n\n\\setlength{\\abovedisplayskip}{3pt}\n\\setlength{\\belowdisplayskip}{3pt}\n\n\\setcounter{section}{1}\n\\section{The Roothaan-Hall and Pople-Nesbet equations}\n\n\\subsection{Spin and spin-orbitals}\n\n\nA spin-orbital $\\y$ can be expressed as $\\y(\\bo{r},s)=\\f(\\bo{r})\\w(s)$, where $\\f(\\bo{r})$ is a spatial orbital and $\\w(s)$ is a spin function.\nSpin functions live in a two-dimensional space spanned by $\\{\\a(s),\\b(s)\\}$, which are orthonormal eigenfunctions of one component of $\\op{\\bo{S}}$, the spin angular momentum operator.\n\\begin{align}\n  \\op{S}_z\\a\n=\n  +\\fr{1}{2}\\a\n&&\n  \\op{S}_z\\b\n=\n  -\\fr{1}{2}\\b\n&&\n  \\ip{\\a|\\a}=\\ip{\\b|\\b}=1\n&&\n  \\ip{\\a|\\b}=\\ip{\\b|\\a}=0\n\\end{align}\nThe ``spin-coordinate'' $s$ is either $+$ or $-$, identifying the component of $\\w(s)$ along $\\a(s)$ and $\\b(s)$.\nYou can think of it as the index of a coordinate vector in spin space\n\\begin{align*}\n  \\ma{\\w(+)\\\\\\w(-)}\n=\n  \\ma{\\ip{\\a|\\w}\\\\\\ip{\\b|\\w}}\n\\end{align*}\nso that $\\a(+)=\\b(-)=1$ and $\\a(-)=\\b(+)=0$.\nUsing this spin coordinate, the inner product in spin space can be defined explicitly as $\\ip{\\w|\\w'}=\\sum_s\\w^*(s)\\w'(s)$.\nThis is commonly referred to as a ``spin integration'', even though it looks more like a dot product.\n\nA complete set of one-electron functions (spin-orbitals) comes in $\\a,\\b$-pairs.\n\\begin{align}\\label{eq:spin-orb-general}\n\t\\y_{2p-1}(\\bo{r},s)\n=\n  \\f_{p_\\a}(\\bo{r})\\a(s)\n&&\n  \\y_{2p}(\\bo{r},s)\n=\n  \\f_{p_\\b}(\\bo{r})\\b(s)\n\\end{align}\nThe spatial components of these functions can be expanded in terms of a set of AO basis functions $\\{\\x_\\nu\\}$ as\n\\begin{align}\\label{eq:space-orb}\n  \\f_{p_\\a}\n=\n  \\sum_\\mu \\x_\\mu C_{\\mu p_\\a}\n&&\n  \\f_{p_\\b}\n=\n  \\sum_\\mu \\x_\\mu C_{\\mu p_\\b}\n\\end{align}\nwhere the AOs basis set consists of atom-centered Gaussian functions (cc-pVTZ, 6-31G, etc.).\n\n\n\n\\subsection{Spin-integration of the canonical Hartree-Fock equations}\n\nFor a system with $n_\\a$ spin-up and $n_\\b$ spin-down electrons, the spin-orbital canonical Hartree-Fock equation takes the following form.\n\\begin{align}\\label{eq:canonical-hf}\n&\n  \\op{f}\\y_p\n=\n  \\ev_p\\y_p\n&&\n  \\op{f}\n=\n  \\op{h}\n+\n  \\sum_{i_\\a}^{n_\\a}\n  (\\op{J}_{i_\\a}-\\op{K}_{i_\\a})\n+\n  \\sum_{i_\\b}^{n_\\b}\n  (\\op{J}_{i_\\b}-\\op{K}_{i_\\b})\n\\end{align}\nThis equation can be expanded in the spin basis as\n\\begin{align*}\n  \\ma{\n    \\ip{\\a|\\op{f}|\\a}&\\ip{\\a|\\op{f}|\\b}\\\\\n    \\ip{\\b|\\op{f}|\\a}&\\ip{\\b|\\op{f}|\\b}}\n  \\ma{\n    \\ip{\\a|\\y_p}\\\\\n    \\ip{\\b|\\y_p}}\n=\n  \\ev_p\n  \\ma{\n    \\ip{\\a|\\y_p}\\\\\n    \\ip{\\b|\\y_p}}\n\\end{align*}\nwhere we are integrating over the spin coordinate.\nThe operators in $\\op{f}$ then become\n\\begin{align*}\n&\n  \\op{h}\n\\mapsto\n  \\ma{\n    \\ip{\\a|\\op{h}|\\a}&0\\\\\n    0&\\ip{\\b|\\op{h}|\\b}}\n&&\n\\begin{array}{r@{\\ }l@{\\hspace{1cm}}r@{\\ }l}\n  \\op{J}_{i_\\a}\n&\\mapsto\n  \\ma{\n    \\ip{\\a|\\op{J}_{i_\\a}|\\a}&0\\\\\n    0&\\ip{\\b|\\op{J}_{i_\\a}|\\b}}\n&\n  \\op{K}_{i_\\a}\n&\\mapsto\n  \\ma{\n    \\ip{\\a|\\op{K}_{i_\\a}|\\a}&0\\\\\n    0&\\makebox[\\widthof{\\ip{\\b|\\op{K}_{i_\\b}|\\b}}]{0}}\n\\\\[10pt]\n  \\op{J}_{i_\\b}\n&\\mapsto\n  \\ma{\n    \\ip{\\a|\\op{J}_{i_\\b}|\\a}&0\\\\\n    0&\\ip{\\b|\\op{J}_{i_\\b}|\\b}}\n&\n  \\op{K}_{i_\\b}\n&\\mapsto\n  \\ma{\n    \\makebox[\\widthof{\\ip{\\a|\\op{K}_{i_\\a}|\\a}}]{0}&0\\\\\n    0&\\ip{\\b|\\op{K}_{i_\\b}|\\b}}\n\\end{array}\n\\end{align*}\nwhere the core and Coulomb operators can be evaluated as $\\ip{\\w|\\op{h}|\\w'}=\\op{h}\\ip{\\w|\\w'}$, since they don't act on spin coordinates.\nThe exchange operator, however, does act on spin coordinates by its coordinate-swapping operation.\n\\begin{align*}\n  \\op{K}_{i_\\a}(\\bo{r})\\a(s)\n=&\\\n  \\sum_{s'}\n  \\ip{\\f_{i_\\a}(\\bo{r}')\\a(s')|\\op{g}(\\bo{r},\\bo{r}')|\\cdot(\\bo{r}')\\a(s')}\\,\n  \\f_{i_\\a}(\\bo{r})\\a(s)\n=\n  \\ip{\\f_{i_\\a}(\\bo{r}')|\\op{g}(\\bo{r},\\bo{r}')|\\cdot(\\bo{r}')}\\,\n  \\f_{i_\\a}(\\bo{r})\\a(s)\n\\\\\n  \\op{K}_{i_\\b}(\\bo{r})\\a(s)\n=&\\\n  \\sum_{s'}\n  \\ip{\\f_{i_\\b}(\\bo{r}')\\b(s')|\\op{g}(\\bo{r},\\bo{r}')|\\cdot(\\bo{r}')\\a(s')}\\,\n  \\f_{i_\\b}(\\bo{r})\\b(s)\n=\n  0\n\\end{align*}\nHere, the $\\cdot$ means ``fill in spatial function here'' and the matrix elements are integrated over $\\bo{r}'$.\nThis shows why $\\ip{\\a|\\op{K}_{i_\\b}|\\a}=\\ip{\\b|\\op{K}_{i_\\b}|\\a}=\\ip{\\b|\\op{K}_{i_\\a}|\\a}=0$ and $\\ip{\\a|\\op{K}_{i_\\a}|\\a}\\neq0$.\nThe remaining components can be derived in the same way.\n\nSince all of the off-diagonal elements in the spin basis vanish, we can separate \\cref{eq:canonical-hf} into two equations.\n\\begin{align}\\label{eq:canonical-uhf-equation-alpha}\n&\n  \\op{f}_\\a \\f_{p_\\a}\n=\n  \\ev_{p_\\a} \\f_{p_\\a}\n&&\n  \\op{f}_\\a\n=\n  \\op{h}\n+\n  \\sum_{i_\\a}^{n_\\a}\n  (\\op{J}_{i_\\a} - \\op{K}_{i_\\a})\n+\n  \\sum_{i_\\b}^{n_\\b}\n  \\op{J}_{i_\\b}\n\\\\\\label{eq:canonical-uhf-equation-beta}\n&\n  \\op{f}_\\b \\f_{p_\\b}\n=\n  \\ev_{p_\\b} \\f_{p_\\b}\n&&\n  \\op{f}_\\b\n=\n  \\op{h}\n+\n  \\sum_{i_\\a}^{n_\\a}\n  \\op{J}_{i_\\a}\n+\n  \\sum_{i_\\b}^{n_\\b}\n  (\\op{J}_{i_\\b} - \\op{K}_{i_\\b})\n\\end{align}\n\n\n\n\n\\subsection{RHF: The Roothaan-Hall Equations}\n\nAssuming a closed-shell system with $n_\\a=n_\\b=n/2$, we can impose the restriction that $\\f_{i_\\a}=\\f_{i_\\b}$ for each pair of electrons.\nThen equations~\\ref{eq:canonical-uhf-equation-alpha} and~\\ref{eq:canonical-uhf-equation-beta} collapse into a single expression.\n\\begin{align*}\n  \\op{f}_\\textsc{r}\\f_p\n=\n  \\ev_p\\f_p\n&&\n  \\op{f}_\\textsc{r}\n=\n  \\op{h}\n+\n  \\sum_i^{n/2}\n  (2\\op{J}_i - \\op{K}_i)\n\\end{align*}\nwhere the R stands for ``restricted''.\nExpanding $\\f_p$ in the AO basis and projecting by $\\x_\\mu$, we get\n\\begin{align*}\n  \\sum_\\nu\n  \\ip{\\x_\\mu|\\op{f}_\\textsc{r}|\\x_\\nu}\n  C_{\\nu p}\n=\n  \\sum_\\nu\n  \\ip{\\x_\\mu|\\x_\\nu}C_{\\mu p}\\ev_p\n\\end{align*}\nwhich are the \\textit{Roothaan-Hall equations}.\nIn matrix notation, these can be written as follows.\n\\begin{align}\\label{eq:roothaan-hall}\n&\n  \\bo{F}\\bo{C}\n=\n  \\bo{S}\\bo{C}\\bm{\\ev}\n&&\n  F_{\\mu\\nu}\n=\n  \\ip{\\x_\\mu|\\op{f}_\\textsc{r}|\\x_\\nu}\n&&\n  S_{\\mu\\nu}\n=\n  \\ip{\\x_\\mu|\\x_\\nu}\n&&\n  (\\bm{\\ev})_{pq}\n=\n  \\ev_p\\d_{pq}\n\\end{align}\nNote that if the AO basis contains $m$ functions, then $\\bo{C}=[C_{\\mu p}]$ is an $m\\times m$ matrix with each column vector containing the expansion coefficients for an orbital $\\f_p$.\nAlso, note that only the $n/2$ MOs of lowest energy ($\\ev_p$) will be ``occupied'' -- the remaining virtual orbitals will not enter into the Coulomb and exchange parts of $\\op{f}_\\textsc{R}$.\nExpanding $\\op{f}_\\textsc{R}$ in its core, Coulomb, and exchange parts, we find\n\\begin{align*}\n  F_{\\mu\\nu}\n=&\\\n  \\ip{\\x_\\mu|\\op{h}|\\x_\\nu}\n+\n  \\sum_i^{n/2}\n  (2\\ip{\\x_\\mu\\f_i|\\x_\\nu\\f_i}-\\ip{\\x_\\mu\\f_i|\\f_i\\x_\\nu})\n\\\\\n=&\\\n  \\ip{\\x_\\mu|\\op{h}|\\x_\\nu}\n+\n  \\sum_i^{n/2}\n  \\sum_{\\rho\\si}^m\n  C_{\\rho i}^*C_{\\si i}\n  (2\\ip{\\x_\\mu\\x_\\rho|\\x_\\nu\\x_\\si}-\\ip{\\x_\\mu\\x_\\rho|\\x_\\si\\x_\\nu})\n\\end{align*}\nwhich is conveniently given in terms of a ``density matrix'' $D_{\\mu\\nu}$.\n\\begin{align}\\label{eq:rhf-ao-basis-fock}\n  F_{\\mu\\nu}\n=&\\\n  \\ip{\\x_\\mu|\\op{h}|\\x_\\nu}\n+\n  \\sum_{\\rho\\si}^m\n  D_{\\rho\\si}\n  (2\\ip{\\x_\\mu\\x_\\rho|\\x_\\nu\\x_\\si}-\\ip{\\x_\\mu\\x_\\rho|\\x_\\si\\x_\\nu})\n&&\n  D_{\\mu\\nu}\n=\n  \\sum_i^{n/2}\n  C_{\\mu i}^*C_{\\nu i}\n\\end{align}\n\n\n\n\n\\subsubsection{Solving the Roothaan-Hall Equations}\n\nEquation~\\ref{eq:roothaan-hall} would look like an ordinary eigenvalue problem if $\\bo{S}$ were an identity matrix.\nThis would be the case if the AO basis were orthogonal, but that generally isn't the case.\nWe can get around this problem using the following algebraic trick:\nif we multiply both sides of equation~\\ref{eq:roothaan-hall} by $\\bo{S}^{-\\frac{1}{2}}$ and insert $\\bo{I}=\\bo{S}^{-\\frac{1}{2}}\\bo{S}^{\\frac{1}{2}}$ between $\\bo{F}$ and $\\bo{C}$, we can write\n\\begin{align}\n\\label{orthogonalized-roothaan-hall}\n&\n  \\tl{\\bo{F}}\n  \\tl{\\bo{C}}\n=\n  \\tl{\\bo{C}}\\bm\\ev\n&&\n  \\tl{\\bo{F}}\n=\n  \\bo{S}^{-\\frac{1}{2}}\\bo{F}\\bo{S}^{-\\frac{1}{2}}\n&&\n  \\tl{\\bo{C}}\n=\n  \\bo{S}^{\\frac{1}{2}}\\bo{C}\\ .\n\\end{align}\nThis is equivalent to a transformation to an orthogonalized AO basis $\\tl\\x_\\mu=\\sum_\\nu\\x_\\nu (\\bo{S}^{-\\frac{1}{2}})_{\\nu\\mu}$ which satisfies $\\ip{\\tl\\x_\\mu|\\tl\\x_\\nu}=\\d_{\\mu\\nu}$.\nAfter diagonalizing the transformed Fock matrix, $\\tl{\\bo{F}}$, the MO coefficients with respect to the original non-orthogonal AO basis can be recovered as $\\bo{C}=\\bo{S}^{-\\frac{1}{2}}\\tl{\\bo{C}}$.\n\n\\begin{samepage}\nEquation~\\ref{orthogonalized-roothaan-hall} is still not exactly an ordinary eigenvalue problem because $\\bo{F}$ depends on the MOs via the density matrix $\\bo{D}$.\nThe standard procedure for solving the Roothaan-Hall equations repeatedly diagonalizes $\\tl{\\bo{F}}$ and feeds in the new density until the equation becomes self-consistent.\nThe algorithm looks as follows.\n\\begin{enumerate}\n  \\item Get integrals $\\ip{\\x_\\mu|\\x_\\nu}, \\ip{\\x_\\mu|\\op{h}|\\x_\\nu}, \\ip{\\x_\\mu\\x_\\nu|\\x_\\rho\\x_\\si}$ and form orthogonalizer $\\bo{S}^{-\\frac{1}{2}}$\n  \\item Guess $\\bo{D}=\\bo{0}$\n  \\item\\label{loop} Build $\\bo{F}$ (equation~\\ref{eq:rhf-ao-basis-fock})\n  \\item Diagonalize $\\tl{\\bo{F}}=\\bo{S}^{-\\frac{1}{2}}\\bo{F}\\bo{S}^{-\\frac{1}{2}}$ to get $\\tl{\\bo{C}}$ and $\\bm\\ev$\n  \\item Backtransform to original basis: $\\bo{C}=\\bo{S}^{-\\frac{1}{2}}\\tl{\\bo{C}}$\n  \\item Form new density matrix: $D_{\\mu\\nu}=\\sum_i^{n/2} C_{\\mu i}^*C_{\\nu i}$\n  \\item If the new $\\bo{D}$ differs from the old $\\bo{D}$ by more than some threshold, return to step~\\ref{loop}\n\\end{enumerate}\n\\end{samepage}\n\n\n\\subsection{UHF: The Pople-Nesbet Equations}\n\nFor open-shell systems of arbitrary $n_\\a, n_\\b$, we can solve equations~\\ref{eq:canonical-uhf-equation-alpha} and~\\ref{eq:canonical-uhf-equation-beta} without requiring $\\f_{i_\\a}=\\f_{i_\\b}$.\nBy exactly the same procedure as was used for the Roothaan-Hall equations, this leads to \\textit{Pople-Nesbet equations}\n\\begin{align*}\n&\n  \\bo{F}^\\a\\bo{C}^\\a\n=\n  \\bo{S}\\bo{C}^\\a\\bm\\ev^\\a\n&&\n  F_{\\mu\\nu}^\\a\n=\n  \\ip{\\x_\\mu|\\op{f}_\\a|\\x_\\nu}\n&&\n  S_{\\mu\\nu}\n=\n  \\ip{\\x_\\mu|\\x_\\nu}\n&&\n  (\\bm\\ev^\\a)_{p_\\a q_\\a}\n=\n  \\ev_{p_\\a}\\d_{p_\\a q_\\a}\n\\\\\n&\n  \\bo{F}^\\b\\bo{C}^\\b\n=\n  \\bo{S}\\bo{C}^\\b\\bm\\ev^\\b\n&&\n  F_{\\mu\\nu}^\\b\n=\n  \\ip{\\x_\\mu|\\op{f}_\\b|\\x_\\nu}\n&&\n  S_{\\mu\\nu}\n=\n  \\ip{\\x_\\mu|\\x_\\nu}\n&&\n  (\\bm\\ev^\\b)_{p_\\b q_\\b}\n=\n  \\ev_{p_\\b}\\d_{p_\\b q_\\b}\n\\end{align*}\nwhere $\\bo{C}^\\a=[C_{\\mu p_\\a}]$ is an $m\\times m$ matrix of MO coefficients for $\\{\\f_{p_\\a}\\}$ and $\\bo{C}^\\b=[C_{\\mu p_\\b}]$ is an $m\\times m$ matrix of MO coefficients for $\\{\\f_{p_\\b}\\}$.\nExpanding the $\\a$ and $\\b$ Fock matrices as in equation~\\ref{eq:rhf-ao-basis-fock}, we find\n\\begin{align*}\n&\n  F_{\\mu\\nu}^\\a\n=\n  \\ip{\\x_\\mu|\\op{h}|\\x_\\nu}\n+\n  \\sum_{\\rho\\si}\n  D_{\\rho\\si}^\\a\n  \\ip{\\x_\\mu\\x_\\rho||\\x_\\nu\\x_\\si}\n+\n  \\sum_{\\rho\\si}\n  D_{\\rho\\si}^\\b\n  \\ip{\\x_\\mu\\x_\\rho|\\x_\\nu\\x_\\si}\n&&\n  D_{\\mu\\nu}^\\a\n=\n  \\sum_{i_\\a}^{n_\\a} C_{\\mu i_\\a}^*C_{\\nu i_\\a}\n\\\\\n&\n  F_{\\mu\\nu}^\\b\n=\n  \\ip{\\x_\\mu|\\op{h}|\\x_\\nu}\n+\n  \\sum_{\\rho\\si}\n  D_{\\rho\\si}^\\a\n  \\ip{\\x_\\mu\\x_\\rho|\\x_\\nu\\x_\\si}\n+\n  \\sum_{\\rho\\si}\n  D_{\\rho\\si}^\\b\n  \\ip{\\x_\\mu\\x_\\rho||\\x_\\nu\\x_\\si}\n&&\n  D_{\\mu\\nu}^\\b\n=\n  \\sum_{i_\\b}^{n_\\b} C_{\\mu i_\\b}^*C_{\\nu i_\\b}\n\\end{align*}\nwhere $\\bo{D}^\\a$ and $\\bo{D}^\\b$ are the $\\a$ and $\\b$ density matrices.\nThe procedure for solving the Pople-Nesbet equations is identical to the one given for RHF\\@.\nHowever, note that one must solve the $\\a$ and $\\b$ equations simultaneously because each Fock operator depends on both $\\bo{C}^\\a$ and $\\bo{C}^\\b$ (via $\\bo{D}^\\a$ and $\\bo{D}^\\b$).\n\n\n\n\\end{document}\n", "meta": {"hexsha": "41ea4f82ededfdc9713872d979b04a76c4698b40", "size": 12056, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "2017/tex/2q-1h-pople-nesbet.tex", "max_stars_repo_name": "GQCG-edu/chem-8950", "max_stars_repo_head_hexsha": "a5f58a5feacbae16b02fddd2c74723da1486b8d2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2017-09-29T20:25:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:40:32.000Z", "max_issues_repo_path": "2017/tex/2q-1h-pople-nesbet.tex", "max_issues_repo_name": "GQCG-edu/chem-8950", "max_issues_repo_head_hexsha": "a5f58a5feacbae16b02fddd2c74723da1486b8d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-07-13T12:11:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-13T15:31:47.000Z", "max_forks_repo_path": "2017/tex/2q-1h-pople-nesbet.tex", "max_forks_repo_name": "GQCG-edu/chem-8950", "max_forks_repo_head_hexsha": "a5f58a5feacbae16b02fddd2c74723da1486b8d2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2017-09-10T10:33:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T07:39:50.000Z", "avg_line_length": 28.1682242991, "max_line_length": 199, "alphanum_fraction": 0.6009455873, "num_tokens": 4977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.31139928855958415}}
{"text": "\\section{GPU-enabled parallel Schr\\\"odinger simulations}\n\\label{sec:3D_Stirap_parallel_Schrodinger_simulations}\n\nHere, we will introduce the problem of atomic transport in cold atomic systems, present the resulting model system, and give all the essential physics. Controlling the centre-of-mass movement of atoms has recently become a popular topic of investigation \\cite{AO:SAP_REVIEW_2016}. One family of techniques that aim to solve this are those of \\textit{spatial adiabatic passage}. In the following section we will describe the motivation, physical system, and the numerical implementation for the solution of the problem of transporting a single atom among three trapping potential wells. The fully three-dimensional numerical solution of this problem will then be provided using GPU computing methods, and the results discussed for both the physical and computing aspects.\n\nFor performance metrics, we will discuss the use of a GPU-enabled Schr\\\"odinger equation integrator developed by myself, based on and compared with the results of a multi-core MPI enabled version by T.~Morgan and N.~Crowley. The solution of the Schr\\\"odinger equation for a fully three-dimensional potential, will demonstrate the effectiveness and improved performance compared to standard HPC methods.\n\n\\subsection{Spatial adiabatic passage}\nControlling the internal degrees of freedom of atoms is well understood and many spectroscopic techniques exist. External degrees of freedom have, however, only recently become interesting due to the advancements in atom trapping, and techniques for controlling the centre of mass state of a single atom are still in development. One promising group of techniques for the generation of spatial superposition states or high fidelity transfer relies on ideas from spatial adiabatic passage (SAP) \\cite{AO:SAP_REVIEW_2016}, which are analogous to STIRAP in optical systems~\\cite{AO:Bergmann_jcp_2015}. These techniques are highly robust against variation in the system parameters \\cite{Eckert:04}, but suffer from being slow due to the adiabatic requirement. The use of SAP has recently been experimentally demonstrated in Lieb lattices \\cite{AO:Taie_oist_2016}, and many other accessible systems have been proposed \\cite{Eckert:06,Morgan:11,Kohler:13}.\n\nTo describe the method for SAP, we will first consider the case of a two-state system, which can be realised using two separated harmonic potential traps, with ground states $| L \\rangle$ and $| R \\rangle$. A reduction of the distance between the traps will increase the coupling, and hence tunneling rate, between them. This can be modelled with a two-level Hamiltonian as\n\\begin{equation}\n    H = -\\frac{\\hbar}{2}\n    \\begin{pmatrix}\n        0 & J_{LR} \\\\\n        J_{RL} & -2\\Delta\n    \\end{pmatrix},\n\\end{equation}\nwhere $J_{LR} = J_{RL}$ are the couplings between states, and $\\Delta$ is the detuning of state $| R \\rangle$, relative to $| L \\rangle$. Assuming an atom initially localised in $| L \\rangle$, and with an increase in coupling strength between the levels, the localised atom will tunnel from $| L \\rangle$ to $| R \\rangle $. However, this processes is difficult to control, as Rabi oscillations introduce an explicit time-dependence as\n\\begin{subequations}\n\\begin{align}\n    |c_L(t)|^2 &\\propto \\sin^2 \\frac{\\omega t}{2} ,\\\\\n    |c_R(t)|^2 &\\propto \\cos^2 \\frac{\\omega t}{2},\n\\end{align}\n\\end{subequations}\nwhere the $|c_{L,R}(t)|^2$ are the populations of the respective states. This time dependence causes the atomic population to continuously tunnel between both traps. It will therefore require precise timing and control to ensure a full, robust transfer of population. From this we see that a double-well potential is a difficult system in which to realise coherent control, though methods such as rapid adiabatic passage (RAP) exist and can allow for this~\\cite{AO:Vitanov_arpc_2001}. A more robust method, using three adjacent harmonic traps and the aforementioned matter-wave SAP process, can improve upon the standard double-well system. For this SAP technique, we model the trapping potentials arranged in a single line and coupled with their nearest neighbour only. For three equivalent potentials, $L,M,R$, with degenerate states $\\{|L \\rangle,|M\\rangle,|R\\rangle\\}$, the system can be described by the Hamiltonian\n\\begin{equation}\\label{eqn:sap_ham}\n    H = -\\frac{\\hbar}{2}\n    \\begin{pmatrix}\n        0 & J_{LM} & 0 \\\\\n        J_{LM} & 0 & J_{MR} \\\\\n        0 & J_{MR} & 0\n    \\end{pmatrix},\n\\end{equation}\nwhere $J_{LM},~J_{MR}$ describe the left-middle and middle-right couplings respectively. Diagonalising this Hamiltonian gives three distinct eigenstates,\n\n\\begin{subequations}\n\\begin{align}\n    | \\pm \\rangle &= \\frac{J_{LM} |L\\rangle \\pm \\sqrt{J_{LM}^2 + J_{MR}^2}|M\\rangle + J_{MR} |R\\rangle  }{\\sqrt{2(J_{LM}^2 + J_{MR}^2)}}, \\\\\n    | D \\rangle &= \\frac{J_{MR} |L\\rangle }{\\sqrt{J_{LM}^2 + J_{MR}^2}} - \\frac{J_{LM} |R\\rangle}{\\sqrt{J_{LM}^2 + J_{MR}^2}},\n\\end{align}\n\\end{subequations}\nwith respective eigenvalues $E_{\\pm} = \\pm {\\sqrt{J_{LM}^2 + J_{MR}^2}}$, $E_D = 0$.\nHere, only one eigenstate is of interest. For the zero-valued eigenstate of this Hamiltonian, $|D \\rangle$, known as the \\textit{dark state}, the dependence on the middle potential vanishes. The state can be written as\n\\begin{equation}\n | D \\rangle = \\cos\\ \\Theta| L \\rangle - \\sin \\Theta | R \\rangle,\n\\end{equation}\nwhere $\\tan \\Theta=J_{LM}/J_{MR}$ is the mixing angle, following directly from the trigonometric identities $\\cos (\\arctan (x)) = 1/\\sqrt{1+x^2}$, $\\sin (\\arctan (x)) = x/\\sqrt{1+x^2}$. From the adiabatic theorem of quantum mechanics, it is known that if a system has its Hamiltonian perturbed slowly enough, then we can follow its evolution ensuring that it always remains in an eigenstate of the Hamiltonian. By preparing the system in state $| L \\rangle$, and varying $\\Theta$ slowly, we can shift the population from the leftmost harmonic potential to the rightmost, without populating the center. To ensure full transfer from $|L \\rangle$ to $| R \\rangle$, the mixing angle must change smoothly from $\\Theta = 0 \\rightarrow \\pi/2$. From the properties of $\\arctan$, this can be achieved by applying the same spatial variation between $|M \\rangle$ and $| R\\rangle$, as between $|L \\rangle$ and $| M\\rangle$, with the latter coupling pulse following a delay, $\\tau$. A diagram of this is given by Fig.~\\ref{fig:ch3_stirap}. Due to the robustness of this process a variety of coupling profiles can be used \\cite{AO:Bergmann_jcp_2015}, as long as they have a smoothly varying background envelope $p$ given by \\cite{AO:Fewell_ausjp_1997}\n\\begin{subequations}\n\\begin{align}\n    J_{LM}(t) &= J_0 p(t-\\tau), \\\\\n    J_{MR}(t) &= J_0 p(t).\n\\end{align}\n\\end{subequations}\n\nVarying the couplings between the trapping potentials, and hence controlling this mixing angle, can be achieved by either lowering the barrier height of adjacent potentials, or decreasing the distance between them. Here, we will discuss varying the spatial separation of the traps.\n\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=0.65\\textwidth]{./ch3_numerics/stirap_delay}\n    \\caption{Three trapping potential model for matter-wave SAP. The atom (green) is initially localised in the leftmost potential, $|L\\rangle$, at $t=0$, with the couplings between adjacent traps controlled by varying the distance dependent parameters $J_{LM}$, $J_{MR}$. By varying the couplings between traps in the manner shown, with $J_{MR}$ increasing initially, followed by $J_{LM}$ after a delay $\\tau$, the atom is transferred completely from $|L\\rangle$ to $| R \\rangle$.}\n    \\label{fig:ch3_stirap}\n\\end{figure}\n\n%With the rate of transfer between trapping potentials controlled by the couplings between potentials, any adjustment of the spatial separation between traps will adjust the tunneling rate, and hence couplings, as shown by Fig.~\\ref{fig:ch3_stirap}.\nTypically, any method to adjust the couplings would be performed with time-dependent potentials. However, a static potential variant can be considered using parallel atomic waveguides, where the separation varies as a function of distance along the parallel axis. If we consider an atom that travels along such a waveguide, the couplings, and hence tunneling rates, seen by the atom in the waveguide are altered as the atom propagates. Such work has been discussed and considered in a realistic system for two spatial dimensions \\cite{OSullivan:10}. Although a two dimensional model is effective at describing much of the relevant dynamics, the realism of the model is reduced by the lack of a third dimension. This is due to the lack of effects stemming from dispersion, curvature of the waveguides, as well as the absence of any such eigenstates along this dimension.\n\n\\subsection{Atom-chip model}\n\nAs discussed previously, to fully understand ultracold atom dynamics in appropriately shaped waveguide systems we must investigate the fully three-dimensional model. One method of creating the required potential landscape in experiments is through the use of atom-chips \\cite{AO:Bartenstein_ieee_2000,AO:Folman_prl_2000}. These systems consist of micro-fabricated current-carrying wires, and can be used to create a variety of trapping potential shapes for controlled guidance of the atomic centre-of-mass \\cite{AO:Denschlag_prl_1999}. The currents produce a magnetic field around individual wires, each of which has a minima at the wire core. Assuming the wire thickness to be negligible, this magnetic field at position $\\mathbf{r}$ can be calculated using the Biot--Savart law\n\\begin{equation}\n    \\mathbf{B}(\\mathbf{r}) = \\frac{\\mu_0}{4\\pi}\\oint I \\frac{\\text{d}\\mathbf{l}\\times \\hat{\\mathbf{r}}^{'}}{|\\mathbf{r^{'}}|^2},\n\\end{equation}\nwhere $I$ is the current through the wire, $\\mu_0$ is the vacuum permeability, $\\text{d}\\mathbf{l}$ is the differential wire length, and $\\hat{\\mathbf{r}}^{'}$ is the unit vector along $\\mathbf{r^{'}} = \\mathbf{r} - \\mathbf{l}$. To be able to trap atoms the minima must be raised to a position above the wire surface. This can be done using an orthogonally applied bias field, ${B}_b$, which raises the minima to a height of\n\\begin{equation}\n    \\mathbf{r}_0 = \\frac{\\mu_0 I}{2\\pi {B}_b},\n\\end{equation}\nabove the surface. Though, an issue still remains with the presence of the magnetic minima. If the field drops to zero at the centre of the trap, the atoms can be lost due to Majorana spin flips~\\cite{AO:Brink_pra_2006}. This can be prevented with the application of an additional field, ${B}_{ip}$, parallel to the wire direction, lifting the degeneracy of the atomic states, and ensuring they remain trapped. Spatial and temporal adjustments of the potentials are possible, with a fine degree of control, either during the production process, or by using time-dependent currents. These have been studied extensively in recent years for highly controllable trapping potentials \\cite{AO:Yun_optexp_2006,AO:Gallego_optlett_2009}, and as atomic manipulators \\cite{AO:Bensky_qip_2011}.\n\nFor this work, we model the system as three adjacent wires on the atom-chip surface. The direction of propagation is along $z$, and an additional harmonic oscillator potential, $V_z = m\\omega_z^2 (z-z_0)^2/2$, is applied in the same direction to impart motion to the atom, which is initially at the $z=0$ position of the atom-chip. We set $z_0 = (\\max z)/2$ to ensure the oscillator potential is symmetric around the centre of the atomchip. This potential also conveniently guarantees that the wavefunction refocuses after the transition at the opposite side of the atom-chip. A schematic of the atom-chip device and the respective potentials is given by Fig.~\\ref{fig:schematic_atom-chip}.\n\n\\begin{figure}[tb]\n    \\centering\n  \\includegraphics[width=0.45\\textwidth]{ch3_numerics/MWSTIRAP/Schematic3}\n  \\includegraphics[width=0.45\\textwidth]{ch3_numerics/MWSTIRAP/3dpot_schem}\n  \\caption{Schematic of the atom-chip and the resulting potentials. Reprinted from Morgan {\\textit{et al}.}~\\cite{AO:Morgan_pra_2013}.}\n  \\label{fig:schematic_atom-chip}\n\\end{figure}\n\nThe initial state is created by localising the atom with the help of a barrier at one end of the potential ($z=0$), and in the leftmost waveguide using an additional barrier potential. After finding the ground state, the barriers are removed, and the atom is allowed to propagate along the length of the waveguide. The populations in each waveguide $|c_{X}|^2$ are tracked at each step of the process as\n\\begin{equation}\n    |c_X|^2 = \\int\\limits_{\\mathcal{V}_X} d\\mathbf{r}  \\Psi^{*} \\Psi\n\\end{equation}\nwhere $\\mathcal{V}_X$ is the volume encompassing each waveguide $X \\in \\{L,M,R\\}$, and $\\Psi$ is the state of the system.\nThe final populations were taken as the atom approached the other classical turning point of the harmonic oscillator along $z$. The fidelity of the process could then be calculated by comparing the initial populations in $| L \\rangle$ and final ones in $|R \\rangle$, as well as any ones left in $| M \\rangle$.\n\nGiven that fully three-dimensional simulations of the Schr\\\"odinger equation are numerically expensive, the use of GPU computing methods were ideal for accelerating the simulation \\cite{Num:Bauke_cpc_2011}. At the time of writing, as far as we had been aware, no other work using GPU computing to solve a three dimensional Schr\\\"odinger equation had been presented. We will now discuss the data and metadata of the simulations.\n\n\\subsection{3D Simulations}\n\\label{sec:Results}\n\nSimulations of the proposed system assumed a single $^{6}$Li atom localised in the left \\mbox{waveguide}. A localised harmonic oscillator potential was added along $z$, with the transverse guiding potential, and the resulting ground state solution found numerically. The harmonic oscillator width was chosen to closely match the expected size in the transverse direction. The atom was then allowed to propagate along the waveguide potential ($z$).\n\nAs the shift in magnetic moment of the atoms is given by $\\Delta E = -\\mu\\cdot\\mathbf{B}$, for regions with a larger magnetic field the atom will experience a greater energy shift, and thus the assumption of all traps being on resonance (degenerate) has to be carefully checked. In fact, the simulations showed that the addition of the magnetic fields stemming from the different wires at the center of the atom-chip leads to the central potential moving out of resonance with the outer two. To make SAP work, it therefore required adjusting the current in the central wire, such that the magnetic minima were in resonance within the tunneling region near the atom-chip centre. The resulting potentials for non-optimal (left) and optimal (middle) currents are shown in Fig.~\\ref{fig:equaloptcurrent}, which also depicts a three dimensional isosurface of the potential minima along the chip surface for both situations (right).\n\n\\begin{figure}[tb]\n    \\centering\n  \\includegraphics[width=0.55\\textwidth]{ch3_numerics/MWSTIRAP/potentials2.pdf}\n  \\includegraphics[width=0.3\\textwidth]{ch3_numerics/MWSTIRAP/3dpot.pdf}\n  \\caption{(Left) Two dimensional slices through the potential centre along $x-z$ (top) and tunneling region in $x-y$ (bottom). The out of resonance middle trapping potential can be seen where all three currents are the same. (Middle) Optimised currents which allow the same field value in the tunneling region ensure that the potentials are in resonance with each other. (Right) 3D isosurface plots of the numerically calculated magnetic minima potentials showing the out of resonance (a) and optimal (b) fields. Adapated from Morgan {\\textit{et al}.}~\\cite{AO:Morgan_pra_2013}.}\n  \\label{fig:equaloptcurrent}\n\\end{figure}\nThe populations for both the direct tunneling case, and the matter-wave SAP processes are shown in Fig.~\\ref{fig:mwsVsDT}. The direct tunneling case can be seen to show Rabi-type oscillations between the waveguides, while the matter-wave SAP process shows a much cleaner transfer, and only a minor occupation of the central potential. The dependence of the transfer probability on the current in the central wire is shown in Fig.~\\ref{fig:DIRVSMWSTIRAP}.\n\n\n\\begin{figure}[tb]\n    \\centering\n  \\includegraphics[width=0.47\\textwidth,trim=2cm 5cm 2cm 5cm]{ch3_numerics/MWSTIRAP/STIRAP_CINT_POP.pdf}\n  \\includegraphics[width=0.47\\textwidth,trim=2cm 5cm 2cm 5cm]{ch3_numerics/MWSTIRAP/STIRAP_INT_POP.pdf}\n  \\caption{Transfer fidelities for the three trapping potentials are given over time for both the matter-wave SAP process (left, particle starting in $ |L\\rangle$) and direct tunneling (right, particle starting in $ |L\\rangle$). Matter-wave SAP clearly shows greater population transfer in comparison with a direct tunneling approach. Reprinted from Morgan {\\textit{et al}.}~\\cite{AO:Morgan_pra_2013}.}\n  \\label{fig:mwsVsDT}\n\\end{figure}\n\n\\begin{figure}[tb]\n    \\centering\n  \\includegraphics[width=0.45\\textwidth]{ch3_numerics/MWSTIRAP/SAPvsDirect.pdf}\n  \\caption{The final state population versus middle wire current for direct tunneling and matter-wave SAP. The robustness of the SAP technique can be seen, and gives a large range of currents with population transfer fidelity $\\approx 99 \\%$. The oscillations in the direct tunneling regime are due to the presence of time-dependent Rabi couplings. Reprinted from Morgan {\\textit{et al}.}~\\cite{AO:Morgan_pra_2013}.}\n  \\label{fig:DIRVSMWSTIRAP}\n\\end{figure}\n\n\\subsection{GPU computing performance}\nGiven the large parameter space over which this system could be evaluated (e.g wire current, spatial separations, trap frequencies), a large number of simulations were required to determine optimal system behaviour. As discussed in Sec.~\\ref{sec:cuda_prog}, one example where GPU computing offers large performance gains are FFTs, which makes the Fourier split operator method an ideal candidate for GPU systems \\cite{Num:Bauke_cpc_2011}. The body of work for implementing this algorithm was using C, CUDA and Nvidia's CUFFT libraries for the Fourier transforms, whereas the MPI-enabled code was implemented using C.\n\nTo demonstrate the performance offered by GPU computing we compared it to using FFTW with MPI, a well used parallel programming library and paradigm. The MPI implementation allows code to be run across multiple machines, benefiting from the parallelism which may be offered by a supercomputing cluster. Although MPI-enabled FFTW is fast and supports extremely large grid sizes, it requires cluster access of a significant size to be a viable option for this type of system. The MPI work on this project was carried out on the Irish Center for High-End Computing (ICHEC) supercomputer system ``Stoney'' \\cite{Ichec_stoney} over the period 2011 to 2012, with all performance metrics data calculated therefrom. This cluster system had 64 available compute nodes, each housing two 2.8GHz Intel Xeon X5560 processors with 4-cores each, and a total of 48GB of RAM per node with inter-node communication using double data rate Infiniband.\n\nDue to the hardware limited memory on the GPU, and because the dynamics along the $x-z$ plane were of most importance, the grid-size of the simulations were scaled as $256\\times 64\\times1024$ ($x\\times y\\times z$). Of next importance were the choice of timesteps for the simulations. To ensure minimal loss in accuracy, the timesteps were chosen as $\\Delta t = 10^{-6}$ s. By approximating the waveguides as harmonic oscillators, the relevant timescales of the dynamics are of the order $T_{\\textrm{t}}\\approx 10^{-4}$ s, and so we can accurately capture all relevant dynamics in the transverse direction. The timescales in the longitudinal direction, which requires a large oscillation period compared to the transverse plane to ensure the adiabaticity condition ($T_{\\textrm{l}}\\approx 10^{-1}$ s), are also fulfilled. For the GPU simulations, the test system was an Intel Core i7 2600K CPU at stock frequency, 8GB DDR3 memory operating at 1600 MHz, 7200 RPM HDD, Nvidia GeForce GTX 580 with 3GB of onboard memory running at 783 MHz GPU core frequency, 1566 MHz shader processor frequency, and 2010 MHz memory frequency. For all simulations the desktop was running Ubuntu 11.10 64-bit operating system and all calculations were performed in double precision (64-bit floating point) where applicable.\n\nTable \\ref{tbl:timing} shows the approximate timings for the completion of runs using GPU and CPU codes. Not only does GPU computing offer a 6-fold improvement over a single CPU, it also allows us to achieve a performance level which is comparable to an 8-node 8-core (64 cores) core MPI enabled CPU calculation. Even for a modest choice of gaming GPU this offers substantial performance gains. Higher performance was achieved by using specific compute accelerators designed for double precision arithmetic. Making use of eight Nvidia M2090 GPUs available at OIST, terabytes of numerical results were generated, and allowed the problem to become tractable on a short timescale.\n\n\\begin{table}[tb]\n  \\begin{center}\n    \\begin{tabular}{|c||c|c|c|}\n      \\hline\n      Device & Num. Devices & Timing  & Rel. Improvement \\\\ \\hline\n      CPU (MPI) & 8 & $\\sim$6 Hr & 1.0$\\times$ \\\\\n      & 16 & $\\sim$4 Hr & 1.5$\\times$ \\\\\n      & 32 & $\\sim$1.5 Hr & 4.0$\\times$ \\\\\n      & 64 & $\\sim$1 Hr & 6.0$\\times$ \\\\ \\hline\n      GPU & 1 & $\\sim$1 Hr & 6.0$\\times$ \\\\ \\hline\n    \\end{tabular}\n  \\end{center}\n   \\caption{The approximate times taken to simulate the propagation of an atom through the atom chip system on both GPU and CPU. Reprinted from Morgan {\\textit{et al}.}~\\cite{AO:Morgan_pra_2013}.}\n   \\label{tbl:timing}\n\\end{table}\n", "meta": {"hexsha": "86e2fd9bdc2d9853004360ad1a3e0c52f766ea03", "size": 21660, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "MainText/ch3_numerics/num_stirap.tex", "max_stars_repo_name": "mlxd/PhDThesis", "max_stars_repo_head_hexsha": "1b5c6bfd1bfd073b47aa0b1b5abbc7bff5cd521e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MainText/ch3_numerics/num_stirap.tex", "max_issues_repo_name": "mlxd/PhDThesis", "max_issues_repo_head_hexsha": "1b5c6bfd1bfd073b47aa0b1b5abbc7bff5cd521e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MainText/ch3_numerics/num_stirap.tex", "max_forks_repo_name": "mlxd/PhDThesis", "max_forks_repo_head_hexsha": "1b5c6bfd1bfd073b47aa0b1b5abbc7bff5cd521e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 139.7419354839, "max_line_length": 1301, "alphanum_fraction": 0.772345337, "num_tokens": 5517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3113992885595841}}
{"text": "% Created 2020-09-21 lun 18:01\n% Intended LaTeX compiler: pdflatex\n\\documentclass[presentation,aspectratio=169, usenames, dvipsnames]{beamer}\n\\usepackage[utf8]{inputenc}\n\\usepackage[T1]{fontenc}\n\\usepackage{graphicx}\n\\usepackage{grffile}\n\\usepackage{longtable}\n\\usepackage{wrapfig}\n\\usepackage{rotating}\n\\usepackage[normalem]{ulem}\n\\usepackage{amsmath}\n\\usepackage{textcomp}\n\\usepackage{amssymb}\n\\usepackage{capt-of}\n\\usepackage{hyperref}\n\\usepackage{khpreamble}\n\\usepackage{amssymb}\n\\usepgfplotslibrary{groupplots}\n\\usepackage{pgfplotstable}\n\\newcommand*{\\shift}{\\operatorname{q}}\n\\definecolor{ppc}{rgb}{0.1,0.1,0.6}\n\\definecolor{iic}{rgb}{0.6,0.1,0.1}\n\\definecolor{ddc}{rgb}{0.1,0.6,0.1}\n\\usetheme{default}\n\\author{Kjartan Halvorsen}\n\\date{2020-09-21}\n\\title{Process Automation Laboratory - Anti windup}\n\\hypersetup{\n pdfauthor={Kjartan Halvorsen},\n pdftitle={Process Automation Laboratory - Anti windup},\n pdfkeywords={},\n pdfsubject={},\n pdfcreator={Emacs 26.3 (Org mode 9.3.6)}, \n pdflang={English}}\n\\begin{document}\n\n\\maketitle\n\n\\section{Context}\n\\label{sec:orgd19de8a}\n\\begin{frame}[label={sec:org69a135a}]{Two -tank model}\n\\begin{center}\n\\includegraphics[width=\\linewidth]{../../figures/two-tanks-shutoff-valve}\n\\end{center}\n\\end{frame}\n\n\\section{Repetition PID}\n\\label{sec:org795dfcf}\n\\begin{frame}[label={sec:org9f8e291}]{Feedback control}\n   \\begin{center}\n   \\begin{tikzpicture}[node distance=22mm, block/.style={rectangle, draw, minimum width=15mm}, sumnode/.style={circle, draw, inner sep=2pt}]\n  { \n  \\node[coordinate] (input) {};\n  \\node[sumnode, right of=input] (sum) {\\tiny $\\sum$};\n  \\node[block, right of=sum, node distance=2.6cm] (reg) {$F(s)$};\n  \\node[block, right of=reg, node distance=2.6cm] (plant) {$G(s)$};\n  \\node[coordinate, right of=plant, node distance=2cm] (output) {};\n  \\node[coordinate, below of=plant, node distance=12mm] (feedback) {};\n \n  \\draw[->] (plant) -- node[coordinate, inner sep=0pt] (meas) {} node[near end, above] {$y(t)$} (output);\n  \\draw[->] (meas) |- (feedback) -| node[very near end, left] {$-$} (sum);\n  \\draw[->] (input) -- node[very near start, above] {$r(t)$} (sum);\n  \\draw[->] (sum) -- node[above] {$e(t)$} (reg);\n  \\draw[->] (reg) -- node[above] {$u(t)$}(plant);\n}\n\\end{tikzpicture}\n\\end{center}\n\\end{frame}\n\n\n\n\\begin{frame}[label={sec:org99d6d2f}]{The PID - practical form}\n\\definecolor{ppc}{rgb}{0.1,0.1,0.6}\n\\definecolor{iic}{rgb}{0.6,0.1,0.1}\n\\definecolor{ddc}{rgb}{0.1,0.5,0.1}\n\n\\begin{center}\n  \\begin{tikzpicture}[node distance=22mm, block/.style={rectangle, draw, minimum width=15mm}, sumnode/.style={circle, draw, inner sep=2pt}]\n\n    \\node[coordinate] (input) {};\n    \\node[sumnode, right of=input, node distance=16mm] (sum) {\\tiny $\\Sigma$};\n    \\node[color=iic,block, right of=sum, node distance=28mm] (ii)  {$\\frac{1}{\\tau_is}$};\n    \\node[color=ppc, coordinate, above of=ii, node distance=10mm] (pp)  {};\n    \\node[color=ddc,block, below of=ii, node distance=13mm] (dd)  {$\\frac{\\tau_ds}{\\frac{\\tau_d}{N}s + 1}$};\n    \\node[sumnode, right of=ii, node distance=20mm] (sum2) {\\tiny $\\Sigma$};\n    \\node[block, right of=sum2, node distance=20mm] (gain)  {$k_c$};\n    \\node[coordinate, below of=sum, node distance=12mm] (feedback) {};\n    \\node[coordinate, right of=gain, node distance=20mm] (output) {};\n\n    \\draw[->] (input) -- node[above, pos=0.3] {$r(t)$} (sum);\n    \\draw[->] (sum) -- node[above, pos=0.2] {$e(t)$} node[coordinate] (mm) {}  (ii);\n    \\draw[->] (gain) -- node[above, near end] {$u(t)$} (output);\n    \\draw[->] (feedback) -- node[left, near start] {$y(t)$} node[right, pos=0.95] {-} (sum);\n    \\draw[->, color=ppc] (mm) |- (pp) -| node[right,] {$u_P(t)$} (sum2);\n    \\draw[->, color=ddc] (feedback |- dd) -- node[above, pos=0.95] {-} (dd);\n    \\draw[->, color=ddc] (dd) -| node[right,] {$u_D(t)$} (sum2)  ;\n    \\draw[->, color=iic] (ii)  -- node[above,] {$u_I(t)$} (sum2);\n    \\draw[->] (sum2) -- node[above, near end] {} (gain);\n\n  \\end{tikzpicture}\n\\end{center}\n\nThe parameter \\(N\\) is chosen to limit the influence of noisy measurements. Typically,\n\\[  3 < N < 20 \\]\n\\end{frame}\n\n\\begin{frame}[label={sec:org879c25a}]{The PID - practical aspects}\n{\\footnotesize Åström \\& Hägglund (1988) \\emph{PID controllers: Theory, design and tuning, 2nd ed} Instrument Society of America.}\n\n\\begin{block}{Approximating nonlinear systems with linear models}\n\\begin{itemize}\n\\item Model is accurate only in neighborhood of operating point for which system is approximated.\n\\item Solution: Divide operating range into many regions, with separate PID parameters for each region\n\\end{itemize}\n\\end{block}\n\n\\begin{block}{Approximating high-order systems with low-order models}\n\\begin{itemize}\n\\item Only accurate for low frequencies\n\\item Beware of behavior for high-frequency input to the closed-loop system\n\\end{itemize}\n\\end{block}\n\\end{frame}\n\n\\begin{frame}[label={sec:org2090f62}]{The PID - practical aspects, contd}\n\\begin{block}{When do PID controllers work well?}\n\\begin{itemize}\n\\item The plant dynamics can be well approximated with low-order model\n\\item Demands on performance not too high\n\\end{itemize}\n\\end{block}\n\\begin{block}{More sophisticated control needed when}\n\\begin{itemize}\n\\item Higher order dynamics\n\\item Oscillatory modes\n\\item Long deadtime\n\\end{itemize}\n\\end{block}\n\\end{frame}\n\n\\begin{frame}[label={sec:org2acf1f0}]{The PID - practical aspects, contd}\n\\begin{block}{Choice of controller}\n\\begin{enumerate}\n\\item P-controller if damping and steady-state error satisfied\n\\item PI-controller if steady-state error must be zero (often 1st order dynamics)\n\\item PID-controller if PI does not give sufficient damping (often 2nd order dynamics)\n\\item Tuning parameter \\(\\tau_c\\) for SIMC tuning method: \n\\begin{itemize}\n\\item Smaller (=faster) than \\(\\tau\\) if sufficiently damped and limitations on input signal not violated.\n\\item larger (=slower) than \\(\\tau\\) if more damping required or smaller input signal required.\n\\end{itemize}\n\\end{enumerate}\n\\end{block}\n\\end{frame}\n\n\n\\begin{frame}[label={sec:orgf21026c}]{The PID - Parallel form, solution}\n\\(u(t) = k_c\\Big( \\textcolor{ppc}{e(t)} + \\textcolor{iic}{\\overbrace{\\frac{1}{\\tau_i} \\int_0^{t} e(\\xi) d\\xi}^{u_I(t)}} + \\textcolor{ddc}{ \\underbrace{\\tau_d \\frac{d}{dt} \\big(-y(t)\\big)}_{u_D(t)}} \\Big)\\)\n   \\begin{center}\n   \\def\\TT{1}\n   \\begin{tikzpicture}\n   \\begin{axis}[\n    clip=false,\n    width=14cm,\n    height=5cm,\n    ylabel={},\n    xlabel={$t$},\n    ymax = 2,\n    ]\n      \\addplot[black, no marks, domain=-0.1:8, samples=200] {(x>0)*(1 - (1+x/\\TT)*exp(-x/\\TT)} node[coordinate, pin=-20:{$y(t)$}, pos=0.4] {};\n      \\addplot[magenta!70!black, no marks, domain=-0.1:8, samples=200] coordinates {(-0.1, 0) (0,0) (0,1) (8,1)} node[coordinate, pin=90:{$r(t)$}, pos=0.21] {};\n      \\addplot[color=ppc, no marks, domain=0:8, samples=200] {(x>=0)*( (1+x/\\TT)*exp(-x/\\TT)} node[coordinate, pin=20:{$e(t)$}, pos=0.7] {};\n      \\addplot[color=iic, no marks, domain=-0.1:8, samples=200] {(x>0)*(2*(1-exp(-x/\\TT)) - \\x/\\TT*exp(-x/\\TT))} node[coordinate, pin=-20:{$u_I(t)$}, pos=0.6] {};\n      \\addplot[color=ddc, no marks, domain=-0.1:8, samples=200] {(x>0)*(-\\x/\\TT*exp(-x/\\TT))} node[coordinate, pin=-20:{$u_D(t)$}, pos=0.4] {};\n    \\end{axis}\n\n \\end{tikzpicture}\n\\end{center}\n\\end{frame}\n\n\\begin{frame}[label={sec:org432862f}]{The PID - Integral signal}\n\\begin{center}\n  \\begin{tikzpicture}[node distance=22mm, block/.style={rectangle, draw, minimum width=15mm}, sumnode/.style={circle, draw, inner sep=2pt}, scale=0.6, every node/.style={scale=0.6}]\n\n    \\node[coordinate] (input) {};\n    \\node[sumnode, right of=input, node distance=16mm] (sum) {\\tiny $\\Sigma$};\n    \\node[color=iic,block, right of=sum, node distance=28mm] (ii)  {$\\frac{1}{\\tau_is}$};\n    \\node[color=ppc, coordinate, above of=ii, node distance=10mm] (pp)  {};\n    \\node[color=ddc,block, below of=ii, node distance=10mm] (dd)  {$\\tau_ds$};\n    \\node[sumnode, right of=ii, node distance=20mm] (sum2) {\\tiny $\\Sigma$};\n    \\node[block, right of=sum2, node distance=20mm] (gain)  {$k_c$};\n    \\node[coordinate, below of=sum, node distance=12mm] (feedback) {};\n    \\node[coordinate, right of=gain, node distance=20mm] (output) {};\n\n    \\draw[->] (input) -- node[above, pos=0.3] {$r(t)$} (sum);\n    \\draw[->] (sum) -- node[above, pos=0.2] {$e(t)$} node[coordinate] (mm) {}  (ii);\n    \\draw[->] (gain) -- node[above, near end] {$u(t)$} (output);\n    \\draw[->] (feedback) -- node[left, near start] {$y(t)$} node[right, pos=0.95] {-} (sum);\n    \\draw[->, color=ppc] (mm) |- (pp) -| node[right,] {$u_P(t)$} (sum2);\n    \\draw[->, color=ddc] (feedback |- dd) -- node[above, pos=0.95] {-} (dd) -| node[right,] {$u_D(t)$}   (sum2);\n    \\draw[->, color=iic] (ii)  -- node[above,] {$u_I(t)$} (sum2);\n    \\draw[->] (sum2) -- node[above, near end] {} (gain);\n\n  \\end{tikzpicture}\n  \\small\n  \\(  u(t) = k_c\\Big( \\textcolor{ppc}{e(t)} + \\textcolor{iic}{\\overbrace{\\frac{1}{\\tau_i} \\int_0^{t} e(\\xi) d\\xi}^{u_I(t)}} + \\textcolor{ddc}{ \\underbrace{\\tau_d \\frac{d}{dt} \\big(-y(t)\\big)}_{u_D(t)}} \\Big)\\)\n\\end{center}\n\n   \\begin{center}\n   \\def\\wn{2}\n   \\def\\zz{0.3}\n   \\pgfmathsetmacro{\\wwd}{\\wn*sqrt(1-\\zz*\\zz)}\n   \\pgfmathsetmacro{\\zwn}{\\zz*\\wn}\n  \\pgfmathsetmacro{\\thangle}{acos(\\zz)}\n   \\begin{tikzpicture}\n   \\begin{axis}[\n    clip=false,\n    width=14cm,\n    height=4.5cm,\n    ylabel={},\n    xlabel={$t$},\n    ymax = 2,\n    ymin = -0.5,\n    ]\n      \\addplot[black, no marks, domain=-0.4:8, samples=200] {(x>0)*(1 - exp(-x * \\zwn)/sqrt(1-\\zz*\\zz) * sin(deg(\\wwd*x) + \\thangle))} node[coordinate, pin=20:{$y(t)$}, pos=0.3] {};\n      \\addplot[magenta!70!black, no marks, domain=-0.4:8, samples=200] coordinates {(-0.4, 0) (0,0) (0,1) (8,1)} node[coordinate, pin=90:{$r(t)$}, pos=0.2] {};\n    \\end{axis}\n\n \\end{tikzpicture}\n\\end{center}\n\n\\alert{Activity} Sketch the error signal \\(e(t)\\) and the integral signal \\(u_I(t)\\) (use \\(\\tau_i=1\\))\n\\end{frame}\n\n\\begin{frame}[label={sec:org642bfac}]{The PID - Integral signal - Solution}\n   \\def\\wn{2}\n   \\def\\zz{0.3}\n   \\pgfmathsetmacro{\\wwd}{\\wn*sqrt(1-\\zz*\\zz)}\n   \\pgfmathsetmacro{\\zwn}{\\zz*\\wn}\n  \\pgfmathsetmacro{\\thangle}{acos(\\zz)}\n\\pgfplotstablenew[ create on use/x/.style={ create col/expr={\\pgfplotstablerow/50} },    create on use/y/.style={ create col/expr={ exp(-\\thisrow{x} * \\zwn)/sqrt(1-\\zz*\\zz) * sin(deg(\\wwd*\\thisrow{x}) + \\thangle)} }, create on use/int/.style={       create col/expr={\\pgfmathaccuma+(\\thisrow{y}+\\prevrow{y})/2*(\\thisrow{x}-\\prevrow{x})} }, columns={x,y,int}]{400} \\pidtable\n\n\n\n\\begin{center}\n  \\begin{tikzpicture}[node distance=22mm, block/.style={rectangle, draw, minimum width=15mm}, sumnode/.style={circle, draw, inner sep=2pt}, scale=0.6, every node/.style={scale=0.6}]\n\n    \\node[coordinate] (input) {};\n    \\node[sumnode, right of=input, node distance=16mm] (sum) {\\tiny $\\Sigma$};\n    \\node[color=iic,block, right of=sum, node distance=28mm] (ii)  {$\\frac{1}{\\tau_is}$};\n    \\node[color=ppc, coordinate, above of=ii, node distance=10mm] (pp)  {};\n    \\node[color=ddc,block, below of=ii, node distance=10mm] (dd)  {$\\tau_ds$};\n    \\node[sumnode, right of=ii, node distance=20mm] (sum2) {\\tiny $\\Sigma$};\n    \\node[block, right of=sum2, node distance=20mm] (gain)  {$k_c$};\n    \\node[coordinate, below of=sum, node distance=12mm] (feedback) {};\n    \\node[coordinate, right of=gain, node distance=20mm] (output) {};\n\n    \\draw[->] (input) -- node[above, pos=0.3] {$r(t)$} (sum);\n    \\draw[->] (sum) -- node[above, pos=0.2] {$e(t)$} node[coordinate] (mm) {}  (ii);\n    \\draw[->] (gain) -- node[above, near end] {$u(t)$} (output);\n    \\draw[->] (feedback) -- node[left, near start] {$y(t)$} node[right, pos=0.95] {-} (sum);\n    \\draw[->, color=ppc] (mm) |- (pp) -| node[right,] {$u_P(t)$} (sum2);\n    \\draw[->, color=ddc] (feedback |- dd) -- node[above, pos=0.95] {-} (dd) -| node[right,] {$u_D(t)$}   (sum2);\n    \\draw[->, color=iic] (ii)  -- node[above,] {$u_I(t)$} (sum2);\n    \\draw[->] (sum2) -- node[above, near end] {} (gain);\n\n  \\end{tikzpicture}\n  \\small\n  \\(  u(t) = k_c\\Big( \\textcolor{ppc}{e(t)} + \\textcolor{iic}{\\overbrace{\\frac{1}{\\tau_i} \\int_0^{t} e(\\xi) d\\xi}^{u_I(t)}} + \\textcolor{ddc}{ \\underbrace{\\tau_d \\frac{d}{dt} \\big(-y(t)\\big)}_{u_D(t)}} \\Big)\\)\n\\end{center}\n\n   \\begin{center}\n   \\def\\wn{2}\n   \\def\\zz{0.3}\n   \\pgfmathsetmacro{\\wwd}{\\wn*sqrt(1-\\zz*\\zz)}\n   \\pgfmathsetmacro{\\zwn}{\\zz*\\wn}\n  \\pgfmathsetmacro{\\thangle}{acos(\\zz)}\n   \\begin{tikzpicture}\n   \\begin{axis}[\n    clip=false,\n    width=14cm,\n    height=4.5cm,\n    ylabel={},\n    xlabel={$t$},\n    ymax = 2,\n    ymin = -0.5,\n    ]\n      \\addplot[black, no marks, domain=-0.4:8, samples=200] {(x>0)*(1 - exp(-x * \\zwn)/sqrt(1-\\zz*\\zz) * sin(deg(\\wwd*x) + \\thangle))} node[coordinate, pin=20:{$y(t)$}, pos=0.3] {};\n      \\addplot[color=ppc, no marks, domain=-0.4:8, samples=600] {(x>0)*(exp(-x * \\zwn)/sqrt(1-\\zz*\\zz) * sin(deg(\\wwd*x) + \\thangle))} node[coordinate, pin=200:{$e(t)$}, pos=0.3] {};\n      \\addplot [color=iic, thick] table [y=int] {\\pidtable};\n      \\addplot[magenta!70!black, no marks, domain=-0.4:8, samples=200] coordinates {(-0.4, 0) (0,0) (0,1) (8,1)} node[coordinate, pin=90:{$r(t)$}, pos=0.2] {};\n    \\end{axis}\n\n \\end{tikzpicture}\n\\end{center}\n\\end{frame}\n\n\\section{Windup}\n\\label{sec:orgdc284b6}\n\n\\begin{frame}[label={sec:org744d11d}]{Integral windup}\n\\href{https://tecdemonterrey.instructuremedia.com/embed/6fb197b1-38a6-4938-b622-b25d4a45efcc}{Video by Tomás Alejandro Lugo Salinas (MTY)} \n\\end{frame}\n\n\\section{Anti-windup}\n\\label{sec:org744d659}\n\n\\begin{frame}[label={sec:org60c71b8}]{Anti-windup using back-calculation}\n\\begin{center}\n\\includegraphics[width=1.02\\linewidth]{../../figures/anti-windup-back-calculation.png}\n\\end{center}\n\\end{frame}\n\\end{document}", "meta": {"hexsha": "9c363fe2942d66fc9d1026732a74901a135aaa5b", "size": 13663, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "pid/slides/lecture-pid-antiwindup.tex", "max_stars_repo_name": "kjartan-at-tec/mr2015", "max_stars_repo_head_hexsha": "1134f3a99ef72e4a17d44edb4d288daad84f3e70", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pid/slides/lecture-pid-antiwindup.tex", "max_issues_repo_name": "kjartan-at-tec/mr2015", "max_issues_repo_head_hexsha": "1134f3a99ef72e4a17d44edb4d288daad84f3e70", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pid/slides/lecture-pid-antiwindup.tex", "max_forks_repo_name": "kjartan-at-tec/mr2015", "max_forks_repo_head_hexsha": "1134f3a99ef72e4a17d44edb4d288daad84f3e70", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.5127388535, "max_line_length": 373, "alphanum_fraction": 0.6379272488, "num_tokens": 5069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.3113992812082249}}
{"text": "\\newpage\n\\section{Variables}\n\n\\begin{Variable}[assumptions]{ASSUMPTIONS}\n\\index{solve}\nAfter solving a linear or polynomial equation system\nwith parameters, the variable \\name{assumptions} contains a list \nof side relations for the parameters. The solution is valid only\nas long as none of these expression is zero.\n\\begin{Examples}\nsolve({a*x-b*y+x,y-c},{x,y});&\n\\{\\{x=\\rfrac{b*c}{a + 1},y=c\\}\\} \\\\\nassumptions; & \\{a + 1\\}\n\\end{Examples}\n\\end{Variable}\n\n\n\\begin{Variable}[card_no]{CARD_NO}\n\\index{FORTRAN}\\index{output}\n\\name{card_no} sets the total number of cards allowed in a Fortran\noutput statement when \\name{fort} is on.  Default is 20.\n\n\\begin{Examples}\non fort; \\\\\ncard_no := 4;                &         CARD_NO=4. \\\\\nz := (x + y)**15;            &\n\\begin{multilineoutput}{6cm}\n      ANS1=5005.*X**6*Y**9+3003.*X**5*Y**10+1365.*X**4*Y**\n     . 11+455.*X**3*Y**12+105.*X**2*Y**13+15.*X*Y**14+Y**15\n      Z=X**15+15.*X**14*Y+105.*X**13*Y**2+455.*X**12*Y**3+ \n     . 1365.*X**11*Y**4+3003.*X**10*Y**5+5005.*X**9*Y**6+\n     . 6435.*X**8*Y**7+6435.*X**7*Y**8+ANS1\n\\end{multilineoutput}\n\\end{Examples}\n\n\\begin{Comments}\nTwenty total cards means 19 continuation cards.  You may set it for more\nif your Fortran system allows more.  Expressions are broken apart in a\nFortran-compatible way if they extend for more than \\name{card_no}\ncontinuation cards.\n\\end{Comments}\n\\end{Variable}\n\n\n\\begin{Constant}[e]{E}\nThe constant \\name{e} is reserved for use as the base of the natural\nlogarithm.  Its value is approximately 2.71828284590, which REDUCE gives\nto the current decimal precision when the switch \\nameref{rounded} is on.\n\n\\begin{Comments}\n\\name{e} may be used as an iterative variable in a \\nameref{for} statement,\nor as a local variable or a \\nameref{procedure}.  If \\name{e} is defined\nas a local\nvariable inside the procedure, the normal definition as the base of the\nnatural logarithm would be suspended inside the procedure.\n\\end{Comments}\n\\end{Constant}\n\n\n\\begin{Variable}[eval\\_mode]{EVAL\\_MODE}\n\\index{algebraic}\\index{symbolic}\nThe system variable \\name{eval\\_mode} contains the current mode, either\n\\nameref{algebraic} or \\nameref{symbolic}.\n\n\\begin{Examples}\nEVAL\\_MODE;                  &        ALGEBRAIC\n\\end{Examples}\n\n\\begin{Comments}\nSome commands do not behave the same way in algebraic and symbolic modes.\n%You can determine what mode you are in without using this command by noting\n%that the numbered prompt in algebraic mode contains a colon (\\name{:}), while\n%the numbered prompt in symbolic mode contains an asterisk (\\name{*}).\n\\end{Comments}\n\\end{Variable}\n\n\n\\begin{Variable}[fort\\_width]{FORT\\_WIDTH}\n\\index{output}\\index{FORTRAN}\nThe \\name{fort\\_width} variable sets the number of characters in a line of\nFortran-compatible output produced when the \\nameref{fort} switch is on.\nDefault is 70.\n\n\\begin{Examples}\nfort_width := 30;            &         FORT\\_WIDTH := 30  \\\\\non fort; \\\\\ndf(sin(x**3*y),x);           &         \\begin{multilineoutput}{3cm}\n      ANS=3.*COS(X\n     . **3*Y)*X**2*\n     . Y\n\\end{multilineoutput}\n\\end{Examples}\n\n\\begin{Comments}\n\\name{fort\\_width} includes the usually blank characters at the beginning\nof the card.  As you may notice above, it is conservative and makes the\nlines even shorter than it was told.\n\\end{Comments}\n\\end{Variable}\n\n\n\\begin{Variable}[high_pow]{HIGH\\_POW}\n\\index{polynomial}\\index{degree}\nThe variable \\name{high\\_pow} is set by \\nameref{coeff} to the highest power\nof the variable of interest in the given expression.  You can access this\nvariable for use in further computation or display.\n\n\\begin{Examples}\ncoeff((x+1)^5*(x*(y+3)^2)^2,x); &\n\\begin{multilineoutput}{6cm}\n\\{0,\n 0,\n Y^{4} + 12*Y^{3} + 54*Y^{2} + 108*Y + 81,\n 5*(Y^{4} + 12*Y^{3} + 54*Y^{2} + 108*Y + 81),\n 10*(Y^{4} + 12*Y^{3} + 54*Y^{2} + 108*Y + 81),\n 10*(Y^{4} + 12*Y^{3} + 54*Y^{2} + 108*Y + 81),\n 5*(Y^{4} + 12*Y^{3} + 54*Y^{2} + 108*Y + 81),\n Y^{4} + 12*Y^{3} + 54*Y^{2} + 108*Y + 81\\}\n\\end{multilineoutput} \\\\\nhigh_pow;                    &        7\n\\end{Examples}\n\\end{Variable}\n\n\n\\begin{Constant}{I}\n\\index{complex}\nREDUCE knows \\name{i} is the square root of -1,\n and that \\IFTEX{$i^2 = -1$}{i^2 = -1}.\n\n\\begin{Examples}\n(a + b*i)*(c + d*i);         &      A*C + A*D*I + B*C*I - B*D \\\\\ni**2;                        &      -1\n\\end{Examples}\n\n\\begin{Comments}\n\\name{i} cannot be used as an identifier.  It is all right to use \\name{i}\nas an index variable in a \\name{for} loop, or as a local (\\name{scalar})\nvariable inside a \\name{begin...end} block, but it loses its definition as\nthe square root of -1 inside the block in that case.\n\nOnly the simplest properties of \\IFTEX{$i$}{i} are known by REDUCE unless\nthe switch \\nameref{complex} is turned on, which implements full complex\narithmetic in factoring, simplification, and functional values.\n\\name{complex} is ordinarily off.\n\\end{Comments}\n\\end{Constant}\n\n\n\\begin{Constant}[infinity]{INFINITY}\nThe name \\name{infinity} is used to represent the infinite positive number.\nHowever, at the present time, arithmetic in terms of this operator reflects\nfinite arithmetic, rather than true operations on infinity.\n\n\\end{Constant}\n\n\n\\begin{Variable}[low\\_pow]{LOW\\_POW}\n\\index{degree}\\index{polynomial}\nThe variable \\name{low\\_pow} is set by \\nameref{coeff} to the lowest power\nof the variable of interest in the given expression.  You can access this\nvariable for use in further computation or display.\n\n\\begin{Examples}\ncoeff((x+2*y)**6,y);        &\n\\begin{multilineoutput}{6cm}\n\\{X^{6},\n 12*X^{5},\n 60*X^{4},\n 160*X^{3},\n 240*X^{2},\n 192*X,\n 64\\}\n\\end{multilineoutput}\\\\\nlow_pow;                    &      0 \\\\\ncoeff(x**2*(x*sin(y) + 1),x); \n\t\t\t    &      \\{0,0,1,SIN(Y)\\} \\\\\nlow_pow;                    &      2\n\\end{Examples}\n\n\\end{Variable}\n\n\n\\begin{Constant}[nil]{NIL}\n\\index{false}\n\\name{nil} represents the truth value {\\it false} in symbolic mode, and is\na synonym for 0 in algebraic mode.  It cannot be used for any other\npurpose, even inside procedures or \\nameref{for} loops.\n\\end{Constant}\n\n\n\\begin{Constant}[pi]{PI}\nThe identifier \\name{pi} is reserved for use as the circular constant.\nIts value is given by 3.14159265358..., which REDUCE gives to the current\ndecimal precision when REDUCE is in a floating-point mode.\n\n\\begin{Comments}\n\\name{pi} may be used as a looping variable in a \\nameref{for} statement,\nor as a local variable in a \\nameref{procedure}.  Its value in such cases\nwill be taken from the local environment.\n\\end{Comments}\n\\end{Constant}\n\n\\begin{Variable}[requirements]{REQUIREMENTS}\n\\index{solve}\nAfter an attempt to solve an inconsistent equation system\nwith parameters, the variable \\name{requirements} contains a list \nof expressions. These expressions define a set of conditions implicitly\nequated with zero. Any solution to this system defines a setting for\nthe parameters sufficient to make the original system consistent.\n\\begin{Examples}\nsolve({x-a,x-y,y-1},{x,y}); & \\{\\}\\\\\nrequirements;&\\{a - 1\\}\n\\end{Examples}\n\\end{Variable}\n\n\\begin{Variable}[root\\_multiplicities]{ROOT\\_MULTIPLICITIES}\n\\index{root}\\index{solve}\\index{polynomial}\nThe \\name{root\\_multiplicities} variable is set to the list of the\nmultiplicities of the roots of an equation by the \\nameref{solve} operator.\n\n\\begin{Comments}\n\\nameref{solve} returns its solutions in a list.  The multiplicities of\neach solution are put in the corresponding locations of the list\n\\name{root\\_multiplicities}.\n\\end{Comments}\n\\end{Variable}\n\n\n\\begin{Constant}[t]{T}\nThe constant \\name{t} stands for the truth value {\\it true}.  It cannot be used\nas a scalar variable in a \\nameref{block}, as a looping variable in a\n\\nameref{for} statement or as an \\nameref{operator} name.\n\n\\end{Constant}\n\n", "meta": {"hexsha": "4c6567d2c9ed6c98e6707a7c9655181e0502c1c9", "size": 7694, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "variable.tex", "max_stars_repo_name": "nilqed/REDHELP", "max_stars_repo_head_hexsha": "0c98a32bf21fa060ccd67ce82f638d6a1bc47a52", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "variable.tex", "max_issues_repo_name": "nilqed/REDHELP", "max_issues_repo_head_hexsha": "0c98a32bf21fa060ccd67ce82f638d6a1bc47a52", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "variable.tex", "max_forks_repo_name": "nilqed/REDHELP", "max_forks_repo_head_hexsha": "0c98a32bf21fa060ccd67ce82f638d6a1bc47a52", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6016949153, "max_line_length": 79, "alphanum_fraction": 0.6931375097, "num_tokens": 2360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.3112603118600591}}
{"text": "\\hypertarget{structIir_1_1Butterworth_1_1HighShelf}{}\\doxysubsection{Iir\\+::Butterworth\\+::High\\+Shelf$<$ Filter\\+Order, State\\+Type $>$ Struct Template Reference}\n\\label{structIir_1_1Butterworth_1_1HighShelf}\\index{Iir::Butterworth::HighShelf$<$ FilterOrder, StateType $>$@{Iir::Butterworth::HighShelf$<$ FilterOrder, StateType $>$}}\n\n\n{\\ttfamily \\#include $<$Butterworth.\\+h$>$}\n\nInheritance diagram for Iir\\+::Butterworth\\+::High\\+Shelf$<$ Filter\\+Order, State\\+Type $>$\\+:\\begin{figure}[H]\n\\begin{center}\n\\leavevmode\n\\includegraphics[height=2.400000cm]{structIir_1_1Butterworth_1_1HighShelf}\n\\end{center}\n\\end{figure}\n\\doxysubsubsection*{Public Member Functions}\n\\begin{DoxyCompactItemize}\n\\item \nvoid \\mbox{\\hyperlink{structIir_1_1Butterworth_1_1HighShelf_a19a78cb96c9b2454ccb48745ed50500d}{setup}} (double sample\\+Rate, double cutoff\\+Frequency, double gain\\+Db)\n\\item \nvoid \\mbox{\\hyperlink{structIir_1_1Butterworth_1_1HighShelf_aa7fecdca7646acf8962c5d0106fb8b3c}{setup}} (int req\\+Order, double sample\\+Rate, double cutoff\\+Frequency, double gain\\+Db)\n\\item \nvoid \\mbox{\\hyperlink{structIir_1_1Butterworth_1_1HighShelf_af63e4f43001ae2d9faf44ba6496db562}{setupN}} (double cutoff\\+Frequency, double gain\\+Db)\n\\item \nvoid \\mbox{\\hyperlink{structIir_1_1Butterworth_1_1HighShelf_a7df553be87ce22541c6ffa8af7508898}{setupN}} (int req\\+Order, double cutoff\\+Frequency, double gain\\+Db)\n\\end{DoxyCompactItemize}\n\n\n\\doxysubsubsection{Detailed Description}\n\\subsubsection*{template$<$int Filter\\+Order = 4, class State\\+Type = Direct\\+Form\\+II$>$\\newline\nstruct Iir\\+::\\+Butterworth\\+::\\+High\\+Shelf$<$ Filter\\+Order, State\\+Type $>$}\n\n\\mbox{\\hyperlink{namespaceIir_1_1Butterworth}{Butterworth}} high shelf filter. Above the cutoff the filter has a specified gain and below it has 0 dB. \n\\begin{DoxyParams}{Parameters}\n{\\em Filter\\+Order} & Reserves memory for a filter of the order Filter\\+Order \\\\\n\\hline\n{\\em State\\+Type} & The filter topology\\+: \\mbox{\\hyperlink{classIir_1_1DirectFormI}{Direct\\+FormI}}, \\mbox{\\hyperlink{classIir_1_1DirectFormII}{Direct\\+Form\\+II}}, ... \\\\\n\\hline\n\\end{DoxyParams}\n\n\n\\doxysubsubsection{Member Function Documentation}\n\\mbox{\\Hypertarget{structIir_1_1Butterworth_1_1HighShelf_a19a78cb96c9b2454ccb48745ed50500d}\\label{structIir_1_1Butterworth_1_1HighShelf_a19a78cb96c9b2454ccb48745ed50500d}} \n\\index{Iir::Butterworth::HighShelf$<$ FilterOrder, StateType $>$@{Iir::Butterworth::HighShelf$<$ FilterOrder, StateType $>$}!setup@{setup}}\n\\index{setup@{setup}!Iir::Butterworth::HighShelf$<$ FilterOrder, StateType $>$@{Iir::Butterworth::HighShelf$<$ FilterOrder, StateType $>$}}\n\\doxyparagraph{\\texorpdfstring{setup()}{setup()}\\hspace{0.1cm}{\\footnotesize\\ttfamily [1/2]}}\n{\\footnotesize\\ttfamily template$<$int Filter\\+Order = 4, class State\\+Type  = Direct\\+Form\\+II$>$ \\\\\nvoid \\mbox{\\hyperlink{structIir_1_1Butterworth_1_1HighShelf}{Iir\\+::\\+Butterworth\\+::\\+High\\+Shelf}}$<$ Filter\\+Order, State\\+Type $>$\\+::setup (\\begin{DoxyParamCaption}\\item[{double}]{sample\\+Rate,  }\\item[{double}]{cutoff\\+Frequency,  }\\item[{double}]{gain\\+Db }\\end{DoxyParamCaption})\\hspace{0.3cm}{\\ttfamily [inline]}}\n\nCalculates the coefficients with the filter order provided by the instantiation \n\\begin{DoxyParams}{Parameters}\n{\\em sample\\+Rate} & Sampling rate \\\\\n\\hline\n{\\em cutoff\\+Frequency} & Cutoff \\\\\n\\hline\n{\\em gain\\+Db} & Gain in dB of the filter in the passband \\\\\n\\hline\n\\end{DoxyParams}\n\\mbox{\\Hypertarget{structIir_1_1Butterworth_1_1HighShelf_aa7fecdca7646acf8962c5d0106fb8b3c}\\label{structIir_1_1Butterworth_1_1HighShelf_aa7fecdca7646acf8962c5d0106fb8b3c}} \n\\index{Iir::Butterworth::HighShelf$<$ FilterOrder, StateType $>$@{Iir::Butterworth::HighShelf$<$ FilterOrder, StateType $>$}!setup@{setup}}\n\\index{setup@{setup}!Iir::Butterworth::HighShelf$<$ FilterOrder, StateType $>$@{Iir::Butterworth::HighShelf$<$ FilterOrder, StateType $>$}}\n\\doxyparagraph{\\texorpdfstring{setup()}{setup()}\\hspace{0.1cm}{\\footnotesize\\ttfamily [2/2]}}\n{\\footnotesize\\ttfamily template$<$int Filter\\+Order = 4, class State\\+Type  = Direct\\+Form\\+II$>$ \\\\\nvoid \\mbox{\\hyperlink{structIir_1_1Butterworth_1_1HighShelf}{Iir\\+::\\+Butterworth\\+::\\+High\\+Shelf}}$<$ Filter\\+Order, State\\+Type $>$\\+::setup (\\begin{DoxyParamCaption}\\item[{int}]{req\\+Order,  }\\item[{double}]{sample\\+Rate,  }\\item[{double}]{cutoff\\+Frequency,  }\\item[{double}]{gain\\+Db }\\end{DoxyParamCaption})\\hspace{0.3cm}{\\ttfamily [inline]}}\n\nCalculates the coefficients \n\\begin{DoxyParams}{Parameters}\n{\\em req\\+Order} & The actual order which can be less than the instantiated one \\\\\n\\hline\n{\\em sample\\+Rate} & Sampling rate \\\\\n\\hline\n{\\em cutoff\\+Frequency} & Cutoff \\\\\n\\hline\n{\\em gain\\+Db} & Gain in dB of the filter in the passband \\\\\n\\hline\n\\end{DoxyParams}\n\\mbox{\\Hypertarget{structIir_1_1Butterworth_1_1HighShelf_af63e4f43001ae2d9faf44ba6496db562}\\label{structIir_1_1Butterworth_1_1HighShelf_af63e4f43001ae2d9faf44ba6496db562}} \n\\index{Iir::Butterworth::HighShelf$<$ FilterOrder, StateType $>$@{Iir::Butterworth::HighShelf$<$ FilterOrder, StateType $>$}!setupN@{setupN}}\n\\index{setupN@{setupN}!Iir::Butterworth::HighShelf$<$ FilterOrder, StateType $>$@{Iir::Butterworth::HighShelf$<$ FilterOrder, StateType $>$}}\n\\doxyparagraph{\\texorpdfstring{setupN()}{setupN()}\\hspace{0.1cm}{\\footnotesize\\ttfamily [1/2]}}\n{\\footnotesize\\ttfamily template$<$int Filter\\+Order = 4, class State\\+Type  = Direct\\+Form\\+II$>$ \\\\\nvoid \\mbox{\\hyperlink{structIir_1_1Butterworth_1_1HighShelf}{Iir\\+::\\+Butterworth\\+::\\+High\\+Shelf}}$<$ Filter\\+Order, State\\+Type $>$\\+::setupN (\\begin{DoxyParamCaption}\\item[{double}]{cutoff\\+Frequency,  }\\item[{double}]{gain\\+Db }\\end{DoxyParamCaption})\\hspace{0.3cm}{\\ttfamily [inline]}}\n\nCalculates the coefficients with the filter order provided by the instantiation \n\\begin{DoxyParams}{Parameters}\n{\\em cutoff\\+Frequency} & Normalised cutoff frequency (0..1/2) \\\\\n\\hline\n{\\em gain\\+Db} & Gain in dB of the filter in the passband \\\\\n\\hline\n\\end{DoxyParams}\n\\mbox{\\Hypertarget{structIir_1_1Butterworth_1_1HighShelf_a7df553be87ce22541c6ffa8af7508898}\\label{structIir_1_1Butterworth_1_1HighShelf_a7df553be87ce22541c6ffa8af7508898}} \n\\index{Iir::Butterworth::HighShelf$<$ FilterOrder, StateType $>$@{Iir::Butterworth::HighShelf$<$ FilterOrder, StateType $>$}!setupN@{setupN}}\n\\index{setupN@{setupN}!Iir::Butterworth::HighShelf$<$ FilterOrder, StateType $>$@{Iir::Butterworth::HighShelf$<$ FilterOrder, StateType $>$}}\n\\doxyparagraph{\\texorpdfstring{setupN()}{setupN()}\\hspace{0.1cm}{\\footnotesize\\ttfamily [2/2]}}\n{\\footnotesize\\ttfamily template$<$int Filter\\+Order = 4, class State\\+Type  = Direct\\+Form\\+II$>$ \\\\\nvoid \\mbox{\\hyperlink{structIir_1_1Butterworth_1_1HighShelf}{Iir\\+::\\+Butterworth\\+::\\+High\\+Shelf}}$<$ Filter\\+Order, State\\+Type $>$\\+::setupN (\\begin{DoxyParamCaption}\\item[{int}]{req\\+Order,  }\\item[{double}]{cutoff\\+Frequency,  }\\item[{double}]{gain\\+Db }\\end{DoxyParamCaption})\\hspace{0.3cm}{\\ttfamily [inline]}}\n\nCalculates the coefficients \n\\begin{DoxyParams}{Parameters}\n{\\em req\\+Order} & The actual order which can be less than the instantiated one \\\\\n\\hline\n{\\em cutoff\\+Frequency} & Normalised cutoff frequency (0..1/2) \\\\\n\\hline\n{\\em gain\\+Db} & Gain in dB of the filter in the passband \\\\\n\\hline\n\\end{DoxyParams}\n\n\nThe documentation for this struct was generated from the following file\\+:\\begin{DoxyCompactItemize}\n\\item \niir/Butterworth.\\+h\\end{DoxyCompactItemize}\n", "meta": {"hexsha": "003fd8ec710d11fd72590c2b73c16b4f705ca330", "size": 7388, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/pdf/structIir_1_1Butterworth_1_1HighShelf.tex", "max_stars_repo_name": "DSP-Works/iir1-realtime-filter", "max_stars_repo_head_hexsha": "7e0a30f6872f3296c6d80d531401a4b4859d6a97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/pdf/structIir_1_1Butterworth_1_1HighShelf.tex", "max_issues_repo_name": "DSP-Works/iir1-realtime-filter", "max_issues_repo_head_hexsha": "7e0a30f6872f3296c6d80d531401a4b4859d6a97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-06T19:57:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-06T19:57:36.000Z", "max_forks_repo_path": "docs/pdf/structIir_1_1Butterworth_1_1HighShelf.tex", "max_forks_repo_name": "DSP-Works/iir1-realtime-filter", "max_forks_repo_head_hexsha": "7e0a30f6872f3296c6d80d531401a4b4859d6a97", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 67.7798165138, "max_line_length": 349, "alphanum_fraction": 0.7560909583, "num_tokens": 2751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.31126030402151633}}
{"text": "\\section{Results}\n\\paragraph{Modeling Allele Frequency Trajectories in Small Populations.} \nWe first tested the goodness of fit of the discrete versus Brownian motion (a \ncontinuous-state model) in modeling allele frequency trajectories, under \ngeneral E\\&R\nparameters.  For this purpose, we conducted $100$K simulations with\ntwo time samples $\\Tc=\\{0,\\tau\\}$ where $\\tau\\in \\{1,10,100\\}$ is the\nparameter controlling the density of sampling in time.  In addition,\nwe repeated simulations for different values of starting frequency\n$\\nu_0\\in\\{0.005,0.1\\}$ (i.e., hard and soft sweep) and selection\nstrength $s\\in\\{0,0.1\\}$ (i.e., neutral and selection). Then, given\ninitial frequency $\\nu_0$, we computed the expected distribution of\nthe frequency of the next sample $\\nu_\\tau$ under two models to make a\ncomparison.  \\ref{fig:markov}A-F shows that Brownian motion\n(continuous model) is inadequate when $\\nu_0$ is far from $0.5$, or\nwhen sampling times are sparse ($\\tau>1$). If the favored allele\narises from standing variation in a neutral population, it is unlikely\nto have frequency close to $0.5$, and the starting frequencies are\nusually much smaller (see \\ref{fig:sfs}). Moreover, in typical \\dmel\nexperiments for example, sampling is sparse. Often, the experiment is\ndesigned so that $10\\le\\tau\\le100$~\\cite{kofler2013guide,\n  orozco2012adaptation, zhou2011experimental,franssen2015patterns}.\n\n% XXX Not sufficient to say 'in contrast to brownian motion, markov...\n% Please check the rewrite of this part\nIn contrast to the Brownian motion approximation, discrete Markov\nchain predictions (Eq.~\\ref{eq:Qt}) are highly consistent with\nempirical data for a wide range of simulation parameters\n(\\ref{fig:markov}A-M). Moreover, the discrete markov chain can be\nmodified to model the case when the the allele is under\nselection. \n\n\\begin{figure*}\n\t\\centering\n\t\\includegraphics[width=\\textwidth]{{markovDists}.pdf}\n\t\\caption{{\\bf Comparison of empirical distributions of allele\n\t\t\tfrequencies (red) versus predictions from Brownian\n\t\t\tMotion (green), and Markov chain (blue).}\\\\\n\t\tComparison of empirical and theoretical distributions under\n\t\tneutral evolution (panels A-F) and selection (panels G-M)\n\t\twith different starting frequencies $\\nu_0\\in\\{0.005,0.1\\}$\n\t\tand sampling times of $\\Tc=\\{0,\\tau\\}$, where $\\tau \\in\n\t\t\\{1,10,100\\}$ and $N=1000\t$.  For each panel, the empirical \n\t\tdistribution\n\t\twas computed over 100,000 simulations.  Brownian motion\n\t\t(Gaussian approximation) provides poor approximations when\n\t\tinitial frequency is far from 0.5 (A) or sampling is sparse\n\t\t(B,C,E,F). In addition, Brownian motion can only provide\n\t\tapproximations under neutral evolution. In contrast, Markov\n\t\tchain consistently provides a good approximation in all\n\t\tcases.}\n\t\\label{fig:markov}\n\\end{figure*}\n\n\\paragraph{Detection Power.} \nWe compared the performance of \\comale\\ against other methods for\ndetecting selection. For each method we calculated detection power as\nthe percentage of true-positives identified with false-positive rate\n$\\le 0.05$. For each configuration (specified with values for\nselection coefficient $s$, starting allele frequency $\\nu_0$ and\ncoverage $\\lambda$), power of each method is evaluated over $2000$\ndistinct simulations, half of which modeled neutral evolution and the\nrest modeled positive selection.\n\n\n\nWe compared the power of \\comale\\ with Gaussian process\n(GP)~\\cite{Terhorst2015Multi}, FIT~\\cite{feder2014Identifying}, and\nCMH~\\cite{agresti2011categorical} statistics.  FIT and GP convert read\ncounts to allele frequencies prior to computing the test statistic.\n\\comale\\ shows the highest power in all cases and the power stays\nrelatively high even for low coverage (\\ref{fig:power} and\n\\ref{tab:power}). In particular, the difference in performance of\n\\comale\\ with other methods is pronounced when starting frequency is\nlow.  The advantage of \\comale\\ stems from the fact that favored\nallele with low starting frequency might be missed by low coverage\nsequencing. In this case, incorporating the signal from linked sites\nbecomes increasingly important. We note that methods using only two\ntime points, such as CMH, do relatively well for high selection values\nand high coverage. However, the use of time-series data can increase\ndetection power in low coverage experiments or when starting frequency\nis low. Moreover, time-series data provide means for estimating\nselection parameters $s,h$ (see below). Finally, as \\comale\\ is robust\nto change of coverage, our results (\\ref{fig:power}B,C) suggest that\ntaking many samples with lower coverage is preferable to sparse\nsampling with higher coverage. For comparison purposes, we also tested\n\\comale\\ using the single locus statistic ($L=1$). For the most part,\n\\comale\\ showed an improvement over other methods even with $L=1$, or\nshowed similar performance. The performance improved with higher $L$.\n\n\n\\begin{figure*}\n\t\\centering\n\t\\includegraphics[width=\\textwidth]{power.pdf}\n\t\\caption{ {\\bf Power calculations for detection of selection.}\\\\\n\t\tDetection power for \\comale ($\\Hc$), Frequency Increment\n\t\tTest (FIT), Gaussian Process (GP), and CMH under hard (A-C)\n\t\tand soft sweep (D-F) scenarios. $\\lambda$, $s$ denote the\n\t\tmean coverage and selection coefficient, respectively.\n\t\tOrange hexagons represent the performance of \\comale\\ when\n\t\tthe maximum of the single-locus statistic is used to make a\n\t\tdecision for the genomic region, while the red circle\n\t\tcorresponds to the performance of \\comale\\ when single locus\n\t\tstatistics are averaged over the region.  The $y$-axis\n\t\tmeasures power -- sensitivity with false positive rate FPR\n\t\t$\\le 0.05$ -- for $2,000$ simulations with $N=1,000$,\n\t\t$L=50$Kbp. The horizontal line reflects the power of a\n\t\trandom classifier.  In all simulations, 3 replicates are\n\t\tevolved and sampled at generations\n\t\t$\\Tc=\\{0,10,20,30,40,50\\}$.}\n\t\\label{fig:power}\n\\end{figure*}\n\\paragraph{Site-identification.}\nIn general, localizing the favored variant, using pool-seq data is a\nnontrivial task due to extensive linkage\ndisequilibrium~\\cite{tobler2014massive}.  To measure performance, we\nsorted variants by their $H$ scores and computed rank of the favored\nallele for each method. For each setting of $\\nu_0$ and $s$, we\nconducted $1000$ simulations and computed the rank of the favored\nmutation in each simulation. The cumulative distribution of the rank\nof the favored allele in 1000 simulation for each setting\n(\\ref{fig:rank}) shows that \\comale\\ outperforms other statistics.\n\nAn interesting observation is revisiting the contrast between\nsite-identification and\ndetection~\\cite{long2013massive,tobler2014massive}.  When selection\nstrength is high, detection is easier (\\ref{fig:power}A-F), but\nsite-identification is harder, due to the high LD between flanking\nvariants and the favored allele (\\ref{fig:rank}A-F).  Moreover,\nsite-identification becomes more difficult whenever the initial\nfrequency of the favored allele is low, i.e., at the onset of\nselection, LD between favored allele and its nearby variants is\nhigh. For example, when coverage $\\lambda=100$ and selection\ncoefficient $s=0.1$, the detection power is 75\\% for hard sweep, but\n100\\% for soft sweep (\\ref{fig:power}B-E). In contrast, the favored\nsite was ranked as the top in 14\\% of hard sweep cases, compared to\nand 95\\% of soft sweep simulations. \n\n\n\\begin{figure*}\n\t\\centering\n\t\\includegraphics[trim=.2in 0 .2in 0, \n\tclip,width=\\textwidth]{{rank100.0}.pdf}\n\t\\caption{{\\bf Ranking performance for 100$\\times$ coverage.}\\\\\n\t\tCumulative Distribution Function (CDF) of the distribution\n\t\tof the rank of the favored allele in 1000 simulations for\n\t\t\\comale\\ ($H$), Gaussian Process (GP), CMH, and Frequency\n\t\tIncrement Test (FIT), for different values of selection\n\t\tcoefficient $s$ and initial carrier frequency. Note that the\n\t\tindividual variant \\comale\\ score ($H$) is used to rank\n\t\tvariants.  The Area Under Curve (AUC) is computed as an overall\n\t\tquantitative measure to compare the performance of methods\n\t\tfor each configuration. In all simulations, 3 replicates with $N=1000$ \n\t\tare evolved and \n\t\tsampled at generations \n\t\t$\\Tc=\\{0,10,20,30,40,50\\}$.}\n\t\\label{fig:rank}\n\\end{figure*}\n\n\n\\paragraph{Estimating Parameters.}\n\\comale\\ estimates effective population size $\\hN$ and selection\nparameters, $\\hat{s}$ and $\\hat{h}$, as a byproduct of the hypothesis\ntesting. We computed bias of selection fitness ($s-\\hat{s}$) and\ndominance ($h-\\hat{h}$) for of \\comale\\ and GP for 1000 simulations in\neach setting. The distribution of the error (bias) for 100$\\times$\ncoverage is presented in \\ref{fig:bias100} for different\nconfigurations.  \\ref{fig:bias30} and \\ref{fig:biasinf} provide the\ndistribution of estimation errors for 30$\\times$, and 300$\\times$\ncoverage, respectively.  For hard sweep, \\comale\\ provides estimates\nof $s$ with lower variance of bias (\\ref{fig:bias100}A and\n\\ref{fig:biasNull}). In soft sweep, GP and \\comale\\ both provide unbiased\nestimates of $s$ with low variance\n(\\ref{fig:bias100}B). \\ref{fig:bias100}~C-D shows that \\comale\\\nprovides unbiased estimates of $h$ as well when $h\\in\\{0,0.5,1,2\\}$\nand $s=0.1$.  We also tested if \\comale\\ provide unbiased estimates of\n$N$, by estimating population size on 1000 simulations when $N\\in\n\\{200,600,1000\\}$. As shown in~\\ref{fig:estimateNMLE}-A \nand~\\ref{fig:estimateN}A-C, maximum\nlikelihood is attained at true value of the parameter.\n\n\n\\begin{figure*}\n\t\\centering\n\t\\includegraphics[width=0.7\\textwidth]{{bias.100}.pdf}\n\t\\caption{{\\bf Distribution of bias for 100$\\times$ coverage.}\\\\ The\n\t\tdistribution of bias ($s-\\hat{s}$) in estimating selection\n\t\tcoefficient over 1000 simulations using Gaussian Process (GP) and\n\t\t\\comale\\ ($H$) is shown for a range of choices for the selection\n\t\tcoefficient $s$ and starting carrier frequency $\\nu_0$, when\n\t\tcoverage $\\lambda=100$ (Panels A,B). GP and \\comale\\ have similar\n\t\tvariance in estimates of $s$ for soft sweep, while \\comale\\ provides\n\t\tlower variance in hard sweep. Also see \\ref{tab:biasdist}. Panels C,D\n\t\tshow the variance in the estimation of $h$. \n\t\tIn all simulations, 3 replicates are evolved and sampled at generations \n\t\t$\\Tc=\\{0,10,20,30,40,50\\}$.}\n\t\\label{fig:bias100}\n\\end{figure*}\n\n\\paragraph{Running Time.}\nAs \\comale\\ does not compute exact likelihood of a region (i.e., does\nnot explicitly model linkage between sites), the complexity of\nscanning a genome is linear in number of polymorphisms.  Calculating\nscore of each variant requires and $\\Oc(TRN^3)$ computation\nfor $\\Hc$. However, most of the operations\nare can be vectorized for all replicates to make the effective running\ntime for each variant.  We\nconducted $1000$ simulations and measured running times for computing site \nstatistics $H$, FIT, CMH and GP with different number of linked-loci.  Our\nanalysis reveals (\\ref{fig:runTime}) that \\comale\\ is orders of\nmagnitude faster than GP, and comparable to FIT. While slower than CMH\non the time per variant, the actual running times are comparable after\nvectorization and broadcasting over variants (see below).\n\nThese times can have a practical consequence. For instance, to run GP\nin the single locus mode on the entire pool-seq data of the \\dmel genome from a\nsmall sample ($\\approx$1.6M variant sites), it would take 1444 CPU-hours\n($\\approx$ 1 CPU-month). In contrast, after vectorizing and\nbroadcasting operations for all variants operations using\n\\texttt{numba} package, \\comale\\ took 75 minutes to perform an\nscan, including precomputation, while the fastest method, CMH, took 17 minutes.\n\n\\begin{figure*}\n\t\\centering\n\t\\includegraphics[width=0.75\\textwidth]{{runTime.pdf}}\n\t\\caption{{\\bf Running time.}\\\\ Box plots of running time per\n\t\tvariant (CPU-secs.) of \\comale ($\\Hc$), CMH, FIT, and\n\t\tGP with single, 3, 5, 7, and 10 loci over 1000 simulations\n\t\tconducted on a workstation with Intel Core i7\n\t\tprocessor. The average running time for each method is shown\n\t\ton the x-axis.\n\t\tIn all simulations, 3 replicates are evolved and sampled at generations \n\t\t$\\Tc=\\{0,10,20,30,40,50\\}$.}\n\t\\label{fig:runTime}\n\\end{figure*}\n\n\n\\subsection{Analysis of a \\dmel Adaptation to Alternating \nTemperatures}\\label{sec:dmel}\nWe applied \\comale\\ to the \n\\datadm~\\cite{orozco2012adaptation,franssen2015patterns}, where\n3 replicate samples were chosen from a population of \\dmel for 59\ngenerations under alternating 12-hour cycles of  hot stressful (28$^{\\circ}$C)\nand non-stressful (18$^{\\circ}$C) temperatures and sequenced.  In this dataset,\nsequencing coverage is different across replicates and generations\n(see S2 Fig of~\\cite{Terhorst2015Multi}) which makes variant depths\nhighly heterogeneous (\\ref{fig:depthHetero}). \n\nWe first filtered out heterochromatic, centromeric and telomeric\nregions~\\cite{fiston2010drosophila}, and those variants that have\ncollective coverage of more that 1500 in all 13 populations: three\nreplicates at the base population, two replicates at generation 15,\none replicate at generation 23, one replicate at generation 27, three\nreplicates at generation 37 and three replicates at generation\n59. After filtering, we ended up with 1,605,714 variants.\n\nNext, we estimated genome-wide population size $\\hN=250$\n(\\ref{fig:estimateNMLE}-B and \\ref{fig:estimateN}-E) which is consistent with \nprevious\nstudies~\\cite{orozco2012adaptation,jonas2016estimating}. The\nlikelihood curves of \\comale\\ are sharper around the optimum compared\nto that of Bollback et. al~\\cite{bollback2008estimation}'s method (see\nSupplementary Fig. 1 in~\\cite{orozco2012adaptation}).  Also,\nchromosomes 3L and 3R appear to have smaller population\nsize, $\\hN=200,150$, respectively. \nOthers have\nmade similar observations on this data. In particular,\nJ\\'{o}n\\'{a}s~\\emph{et al.}~\\cite{jonas2016estimating} shown that the \nchromosome-wise population\nsize varies even more when it is computed for each replicate\nseparately (see Table 1 in~\\cite{jonas2016estimating}). For instance,\n$\\hN$ is 131 for chromosome 3R replicate 1, while it is 328 for chromosome X \nreplicate 2.  \n\n\\begin{figure*}\n\t\\centering\n\t\\includegraphics[width=\\textwidth]{estimateNMLE.pdf}\n\t\\caption{{\\bf Estimating population size.}  (A) Distribution\n\t\tof bias in estimating $N$, computed on 1000 neutral\n\t\tsimulations for each $N\\in\\{200,600,1000\\}$ when $W=10$Mbp and \n\t\t$r=2\\times10^{-8}$. (B) \n\t\tEstimates\n\t\tof population size for \\datadm. For each case, the\n\t\tdistribution of estimator is computed by 100 bootstrap\n\t\tcomputations using 1000 variants each. The multiple modes\n\t\tare an artifact of grid search used to speed up\n\t\tcomputation. (C) Distribution of the population \tsize\n\t\testimates on the yeast dataset.  Despite large census\n\t\tpopulation size ($10^6-10^7$~\\cite{burke2014standing}), this\n\t\tdataset exhibits much smaller effective population size\n\t\t($\\hN=2000$). }\n\t\\label{fig:estimateNMLE}\n\\end{figure*}\n\nWhile it would be ideal to compute \\comale\\ statistic for each\nreplicate and chromosome separately, computing empirical $p$-values\nand significant regions become computationally intensive as empirical\nnull distribution of each replicate and each chromosome needs to be\ncomputed.  Hence, we use a single genome-wide estimate $\\hN=250$ in\nall analyses, but we normalize statistic $\\Hc^*$ separately for each\nchromosome.\n\nWe use a heuristic calculation (See~\\ref{sec:winSize}) to choose the\nsliding window size $L$ as the distance where the LD between the\nfavored mutation and a site $L/2$bp away remains strong. For \\dmel\nparameters, we obtained $L=30$Kbp. We computed the normalized test\nstatistic $\\Hc^*$ on sliding windows of size of 30Kbp and step size of\n5Kbp over the genome (See~\\ref{fig:man-dmel-region}-A).\n\nEmpirical null distribution of $\\Hc^*$ was estimated by creating 100\nwhole genome simulations (400K statistic values) as described in\nSection~\\ref{sec:sims}. Then, $p$-value of the test statistic in each\nregion in the experimental data was calculated as the fraction of the\nnull statistic values that are greater than or equal to the test\nstatistic(see~\\ref{fig:null-alt}).  After correcting for multiple\ntesting, we identified $5$ contiguous\nintervals~(\\ref{fig:man-dmel-region}) satisfying FDR$\\le0.05$, and\ncovering $2,829$ polymorphic sites. We further performed single-locus\nhypothesis testing on the $2,829$ sites to identify $174$ individual\nvariants with FDR $\\le0.01$~(\\ref{fig:man-dmel-region}-B).\n\nThe final set of 174 variants fall within 32 genes(\\ref{tab:genes})\nincluding many Serine inhibitory proteases (serpins), and other genes\ninvolved in endocytosis. Recycling of synaptic vesicles is seen to be\nblocked at high temperature in temperature sensitive Drosophila\nmutants~\\cite{kosaka1983reversible}. This is also supported by GO\nenrichment analysis, where a single GO term `inhibition of\nproteolysis' is found to enriched (corrected $p$-value:0.0041).  To\ntest for dominant selection, we computed $D$ statistic on simulated\nneutral and experimental data, and computed $p$-values accordingly.\nAfter correcting for multiple testing, 96 variants were discovered\nwith FDR$\\le 0.01$~(\\ref{fig:man-dmel-snp}). \n\n\n\\subsection{Analysis of Outcrossing Yeast Populations}\nWe also applied \\comale\\ to  $12$ replicate samples of\noutcrossing yeast populations~\\cite{burke2014standing}, where samples are \ntaken at\ngenerations $\\Tc=\\{0,180,360,540\\}$. We observed a significant\nvariation in the genome-wide site frequency spectrum of certain\npopulations over different time points for some\nreplicates~(\\ref{fig:yeast-sfs}). The variation does not have an\neasily identifiable cause. Therefore, we focused analysis on seven\nreplicates $r\\in\\{3,7,8,9,10,11,12\\}$ with genome-wide site-frequency\nspectrum over the time range~(\\ref{fig:yeast-pca}).\n\nWe estimated population size to be $\\hN=2000$ haplotypes \n(\\ref{fig:estimateNMLE}-C and \\ref{fig:estimateN}-F), and computed\n$\\hs$, $\\hh$ and $H$ statistic accordingly. To compute $p$-values, we\ncreated 1M single-locus neutral simulations according to experimental\ndata's initial frequency and coverage. By setting FDR cutoff to\n$0.05$, only 18 and 16 variants show significant signal for\ndirectional and dominant selection,\nrespectively~(\\ref{fig:man-dmel-snp}).  Selected variants for\ndirectional selection are clustered in two regions, which match $2$ of\nthe $5$ regions (regions C and E in Fig. 2-a\nin~\\cite{burke2014standing}) identified by Burke~\\emph{et al.} in\ntheir preliminary analysis. \n\n\\begin{figure*}\n\t\\centering\n\t\\begin{tabular}{c}\n\t\t(A)\\\\\n\t\t\\includegraphics[trim=0.4in 0.in 0.6in \n\t\t0in,clip,width=0.9\\textwidth]{man-dmel-region.pdf}\\\\\t\t\n\t\t(B)\\\\\t\n\t\t\\includegraphics[trim=0.3in 0.in 0.6in \n\t\t.0in,clip,width=0.9\\textwidth]{{topVariants.dmel.dir}.pdf}\n\t\\end{tabular}\n\t\\caption{{\\bf Scan of \\comale\\ statistic on \\datadm.}\n\t\t(A)         Manhattan plot of scan for $\\Hc^*$ statistic using sliding \n\t\twindow of \n\t\tsize $L=3000$ over the\n\t\tgenome.  The dashed line represents cutoff for genome-wide\n\t\tFDR$\\le0.05$, and identifies 5 contiguous intervals, I1-I5, \n\t\twhich are shaded in blue. (B) Trajectories of the selected \n\t\tvariants within \n\t\tintervals I1-I5.}\n\t\\label{fig:man-dmel-region}\n\\end{figure*}\n\n\n\n\\begin{figure*}\n\t\\centering\n\t\\begin{tabular}{cc}\n\t\t\\includegraphics[trim=0.4in 0.in 0.6in \n\t\t0.0in,clip,width=0.65\\textwidth]{man-yeast-snp.pdf}&\t\n\t\t\\raisebox{0.2in}{\n\t\t\t\\includegraphics[trim=0in 0.in 0in \n\t\t\t0.0in,clip,width=0.35\\textwidth]{{topVariants.yeast}.pdf}}\n\t\\end{tabular}\n\t\\caption{{\\bf Single locus analysis of the yeast outcrossing \n\t\t\tpopulations.}\\\\ Manhattan plot \n\t\tof scan single locus \\comale\\ statistic ($L=1$) for testing directional \n\t\tselection (A) and dominant \n\t\tselection \n\t\t(C).\n\t\tThe dashed line represents cutoff for  genome-wide FDR$\\le0.05$.\n\t\tTrajectories of the selected variants are depicted in panels (B) and \n\t\t(D).}\n\t\\label{fig:man-yeast-snp}\n\\end{figure*}\n\n\n\n", "meta": {"hexsha": "6fd3bdbd6de015de3bcdc73c906cb69885164dc5", "size": 19826, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "manuscript/results.tex", "max_stars_repo_name": "airanmehr/timeseries_paper", "max_stars_repo_head_hexsha": "9efc1c849883219fcf0236f64357092159c53140", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "manuscript/results.tex", "max_issues_repo_name": "airanmehr/timeseries_paper", "max_issues_repo_head_hexsha": "9efc1c849883219fcf0236f64357092159c53140", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "manuscript/results.tex", "max_forks_repo_name": "airanmehr/timeseries_paper", "max_forks_repo_head_hexsha": "9efc1c849883219fcf0236f64357092159c53140", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.7125307125, "max_line_length": 79, "alphanum_fraction": 0.7643498436, "num_tokens": 5591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3112296726045836}}
{"text": "\\mainsection{User Defined Local Functions}\n\\label{sec:Local}\nAs you write complex applications you will soon see the\nneed to execute local operations on each player which are\nrather complex. For example this might be formatting data,\nor performing some local arithmetic which does not need\nto be done securely. \nPrior to v1.5 there was two ways of doing this:\n\\begin{enumerate}\n\\item Write the local function in MAMBA or SCALE byte-codes\ndirectly. This is often both a pain from a programming point\nof view, and also produced highly inefficient code.\n\\item Use the calling application to execute the local\noperations, and then use the I/O class to interact\nbetween the two. This requires people to have calling\napplications, which any deployed application will have),\nbut which a quick experimental setup is unlikely to\nbother with.\nBut it also requires expensive interaction between the\nSCALE engine and the external application via the I/O\nclass.\n\\end{enumerate}\nHaving implemented the user defined circuits for Garbling\nwe decided to also, in a similar manner, add a third method\nof implementing local functions; namely via user-defined\nC++-code.\nTo see this in operation we suggest looking at the directory\n\\verb|src/Local/|, and looking at the files there. Here\nwe implement some basic linear algebra routines.\nLook at those files whilst reading this explanation.\n\n\\subsection{Defining Local Functions in C++}\nEvery local function is one which involves no interaction\nbetween the parties.\nIt can thus be {\\em any} function on clear data, and\nonly a {\\em linear} function on private data.\nA local function is defined using the C++ signature\n\\begin{lstlisting}\n    void apply_Function(int instr);\n\\end{lstlisting}\nWhere the variable \\verb|instr| is the instruction number; which is akin to the\nearlier circuit number for garbled circuits.\nWe reserve all numbers less than 65536 for use by the developers, leaving\nyou to define numbers greater than 65536.\nOnce again, if you have a good function which might be useful to others\nplease let us know.\n\nThe local function is registered with an instruction number in the\nsystem by adding the function pointer to the \\verb|functions| map\nin the file \\verb|src/Local/Local_Functions.cpp|.\nMust like user defined Garbled Circuits were added into the\nsystem earlier.\n\nEach local function obtains it arguments by popping any required\ndata off the stacks, the functions outputs are then placed on the\nstacks in a similar manner.\nSee the \\verb|BLAS.cpp| example linear algebra routines for\nsome examples.\n\n\\subsection{Defining Local Functions in the MAMBA/byte-code Language} \nOn the byte-code side of system we have one instruction\n\\verb|LF| which takes a single argument, namely the\nnumber of the local function being called.\n\n\\subsection{Floating Point Examples}\nThese functions (in most cases) load in values from the \n\\verb|regint| stack, treat them as floating point values, \nprocess the operation, and then push them back to the \\verb|regint| \nstack.\nThe first ones mirror the equivalent functions in the\n\\verb|GC| routines, and thus have the same numbers.\n\\begin{center}\n\\begin{tabular}{c|l}\nNumber & Function \\\\\n\\hline\n120 & IEEE floating point (double) addition \\\\\n121 & IEEE floating point (double) multiplication \\\\\n122 & IEEE floating point (double) division \\\\\n123 & IEEE floating point (double) equality \\\\\n124 & IEEE floating point (double) to sregint \\\\\n125 & sregint to IEEE floating point (double) \\\\\n126 & IEEE floating point (double) sqrt \\\\\n127 & IEEE floating point (double) lt \\\\\n128 & IEEE floating point (double) floor \\\\\n129 & IEEE floating point (double) ceil \\\\\n\\hline\n200 & IEEE floating point (double) acos \\\\\n201 & IEEE floating point (double) asin \\\\\n202 & IEEE floating point (double) atan \\\\\n203 & IEEE floating point (double) cos \\\\\n204 & IEEE floating point (double) cosh \\\\\n205 & IEEE floating point (double) sin \\\\\n206 & IEEE floating point (double) sinh \\\\\n207 & IEEE floating point (double) tanh \\\\\n208 & IEEE floating point (double) exp \\\\\n209 & IEEE floating point (double) log \\\\\n210 & IEEE floating point (double) log10 \\\\\n211 & IEEE floating point (double) fabs \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\n\\subsection{Floating Point Conversion}\nWe also have local routines that convert between IEEE format\nand \\verb|cfix| and \\verb|cfloat| format.\nIn the following table we mark the types of the arguments\nand outputs with `i' for \\verb|regint| and `p' for \\verb|cint|.\nThe left most argument is at the bottom of the stack\nin each case.\n\\begin{center}\n\\begin{tabular}{c|l|l}\nNumber & Function & Args \\\\\n\\hline\n\t500 & IEEE $\\rightarrow$ cfix & (x: i, k: i, f: i) $\\rightarrow$ (a: p) \\\\\n\t501 & cfix$\\rightarrow$IEEE & (x: p, k: i, f: i) $\\rightarrow$ (a: i) \\\\\n\t502 & IEEE$\\rightarrow$cfloat & (x: i, vlen: i, plen: i) $\\rightarrow$ (v: p, p: p, z: p, s: p, err: p) \\\\\n\t503 & cfloat$\\rightarrow$IEEE & (v: p, p: p, z: p, s: p, err: p) $\\rightarrow$ (x: i) \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\n\\subsection{BLAS Examples}\nIn our Basic Linear Algebra System (BLAS) we provide currently four\nroutines\n\\begin{center}\n\\begin{tabular}{c|l}\nInstruction Number & Function \\\\\n\\hline\n0 & cint n-by-k matrix A by cint k-by-m matrix B \\\\\n1 & sint n-by-k matrix A by cint k-by-m matrix B \\\\\n2 & cint n-by-k matrix A by sint k-by-m matrix B \\\\\n3 & Row Reduction of a n-by-m cint matrix A \\\\\n\\end{tabular}\n\\end{center}\nIn these examples the dimensions are passed via \npushing to the \\verb|regint| stack, with data\nbeing passed by pushing to the \\verb|cint| (resp.\n\\verb|sint|) stack.\nThe matrices are packed using a standard row-wise configuration.\nIn the following code example (given in \\verb|Programs/Local_test/|)\nwe illustrate this with the matrices\n\\[\n  A = \\left( \\begin{array}{ccc}\n  1 & 2 & 3 \\\\  \n  4 & 5 & 6 \\end{array} \\right) \\quad \\quad\n  B = \\left( \\begin{array}{cc}\n  7 & 8 \\\\\n  9 & 10 \\\\\n  11 & 12 \n  \\end{array} \\right).\n\\]\n\\begin{lstlisting}\ndef push_Cint_matrix(A,n,m):\n  regint.push(regint(n))\n  regint.push(regint(m))\n  for i in range(n):\n    for j in range(m):\n       cint.push(A[i][j])\n\ndef push_Sint_matrix(A,n,m):\n  regint.push(regint(n))\n  regint.push(regint(m))\n  for i in range(n):\n    for j in range(m):\n       sint.push(A[i][j])\n\ndef pop_Cint_matrix(A,n,m):\n  mm=regint.pop()\n  nn=regint.pop()\n  if_then(nn!=n or m!=mm)\n  print_ln(\"Something wrong\")\n  print_ln(\"%s %s\",nn,mm)\n  end_if()\n  for i in range(n-1,-1,-1):\n    for j in range(m-1,-1,-1):\n       A[i][j]=cint.pop()\n\ndef pop_Sint_matrix(A,n,m):\n  mm=regint.pop()\n  nn=regint.pop()\n  if_then(nn!=n or m!=mm)\n  print_ln(\"Something wrong\")\n  print_ln(\"%s %s\",nn,mm)\n  end_if()\n  for i in range(n-1,-1,-1):\n    for j in range(m-1,-1,-1):\n       A[i][j]=sint.pop()\n\n\nn=2\nl=3\nm=2\n\n# Mult the two matrices\n#  A = [1,2,3;4,5,6]\n#  B = [7,8;9,10;11,12]\n# which should give us\n#  C = [58,64; 139, 154]\n\nCp_A=cint.Matrix(n,l)\nCp_B=cint.Matrix(l,m)\nCp_out=cint.Matrix(n,m)\nCpGE_out=cint.Matrix(n,l)\nSp_A=sint.Matrix(n,l)\nSp_B=sint.Matrix(l,m)\nSp_out=sint.Matrix(n,m)\n\ncnt=1\nfor i in range(n):\n  for j in range(l):\n     Cp_A[i][j]=cint(cnt)\n     Sp_A[i][j]=sint(cnt)\n     cnt=cnt+1\n\nfor i in range(l):\n  for j in range(m):\n     Cp_B[i][j]=cint(cnt)\n     Sp_B[i][j]=sint(cnt)\n     cnt=cnt+1\n\npush_Cint_matrix(Cp_A,n,l)\npush_Cint_matrix(Cp_B,l,m)\nLF(0)\npop_Cint_matrix(Cp_out,n,m)\n\nprint_ln(\"Final CC Product is...\")\nfor i in range(n):\n  for j in range(m):\n    print_str('%s ', Cp_out[i][j])\n  print_ln('')\n\npush_Sint_matrix(Sp_A,n,l)\npush_Cint_matrix(Cp_B,l,m)\nLF(1)\npop_Sint_matrix(Sp_out,n,m)\n\nprint_ln(\"Final SC Product is...\")\nfor i in range(n):\n  for j in range(m):\n    print_str('%s ', Sp_out[i][j].reveal())\n  print_ln('')\n\npush_Cint_matrix(Cp_A,n,l)\npush_Sint_matrix(Sp_B,l,m)\nLF(2)\npop_Sint_matrix(Sp_out,n,m)\n\nprint_ln(\"Final CS Product is...\")\nfor i in range(n):\n  for j in range(m):\n    print_str('%s ', Sp_out[i][j].reveal())\n  print_ln('')\n\n\npush_Cint_matrix(Cp_A,n,l)\nLF(3)\npop_Cint_matrix(CpGE_out,n,l)\n\nprint_ln(\"Final Gauss Elim on A is...\")\nfor i in range(n):\n  for j in range(l):\n    print_str('%s ', CpGE_out[i][j])\n  print_ln('')\n\\end{lstlisting}\n\n\n\n\n\n\n\n", "meta": {"hexsha": "3fffbb6ae57c3bc52fce48a0566ec550540c9f6a", "size": 8114, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Documentation/Local.tex", "max_stars_repo_name": "karannewatia/SCALE-MAMBA", "max_stars_repo_head_hexsha": "467b33a6c80050789204ea3ee3b5cf0113354f85", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 196, "max_stars_repo_stars_event_min_datetime": "2018-05-25T11:41:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T05:49:50.000Z", "max_issues_repo_path": "Documentation/Local.tex", "max_issues_repo_name": "karannewatia/SCALE-MAMBA", "max_issues_repo_head_hexsha": "467b33a6c80050789204ea3ee3b5cf0113354f85", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 49, "max_issues_repo_issues_event_min_datetime": "2018-07-17T15:49:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-19T11:35:31.000Z", "max_forks_repo_path": "Documentation/Local.tex", "max_forks_repo_name": "karannewatia/SCALE-MAMBA", "max_forks_repo_head_hexsha": "467b33a6c80050789204ea3ee3b5cf0113354f85", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 90, "max_forks_repo_forks_event_min_datetime": "2018-05-25T11:41:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T19:15:10.000Z", "avg_line_length": 29.8308823529, "max_line_length": 107, "alphanum_fraction": 0.7098841509, "num_tokens": 2349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.31105437035956474}}
{"text": "\\chapter{Using PEA in end user mode}\r\n\\label{ch:pea_user_mode}\r\nWhen set to end user mode, the PEA component of Ginan will process each station separately. This mode will allow the estimation of parameters available to users with single receivers. \r\n\\begin{itemize}\r\n\t\\item Receiver position\r\n\t\\item Receiver clock offset\r\n\t\\item Tropospheric delay at receiver location\r\n\t\\item Ionospheric delay at the receiver location (not yet available)\r\n\t\\item Carrier phase ambiguities\r\n\\end{itemize}\r\nIn order to use the PEA in end-user mode, the \\textit{ processing\\_options : process\\_modes : user} parameter needs to be set to \\textit{true}.\r\nThe results of PEA run in end user mode are printed in the trace files.\r\nTrace file outputs can be activated by setting the \\textit{ output\\_files : output\\_trace} parameter to \\textit{true}.\r\nThe most commonly used outputs from the PEA used in end-user mode are expected to be: the receiver position, receiver velocity, receiver clocks and tropospheric delays.\r\n\r\n\\textbf{Receiver position}  results are preceded by the \"\\$POS\" label and thus, in Linux, can be extracted using the command:\r\n \\begin{lstlisting}\r\n$ grep \"$POS\" <path_to_trace_file>\r\n\\end{lstlisting}\r\nthe output line for the for receiver position will have 10 comma separated fields with the following format:\r\n\\begin{lstlisting}\r\n$POS,2166,278015.000,6,-4052053.0060,4212836.8682,-2545105.0796,0.0245227,0.0231919,0.0163678\r\n\\end{lstlisting}\r\nthe fields represent, from left to right:\r\n\\begin{enumerate}\r\n\t\\item  \"\\$POS\" label\r\n\t\\item  GPS week\r\n\t\\item  GPS TOW in seconds\r\n\t\\item  Solution type (6 for float PPP, 1 for ambiguity fixed PPP)\r\n\t\\item  Receiver ECEF X position in meters\r\n\t\\item  Receiver ECEF Y position in meters\r\n\t\\item  Receiver ECEF Z position in meters\r\n\t\\item  Standard deviation of ECEF X positions in meters\r\n\t\\item  Standard deviation of ECEF X positions in meters\r\n\t\\item  Standard deviation of ECEF X positions in meters\r\n\\end{enumerate}\r\n\r\n\\textbf{Receiver clock} offset results are preceded by the \"\\$CLK\" label and thus, in Linux, can be extracted using the command:\r\n \\begin{lstlisting}\r\n$ grep \"$CLK\" <path_to_trace_file>\r\n\\end{lstlisting}\r\nthe output line for the for receiver position will have 13 comma separated fields with the following format:\r\n\\begin{lstlisting}\r\n$CLK,2166,278015.000,6,14,3.1902,0.0000,1.1924,0.0000,0.0860,0.0000,0.0953,0.0000\r\n\\end{lstlisting}\r\nthe fields represent, from left to right:\r\n\\begin{enumerate}\r\n\t\\item  \"\\$CLK\" label\r\n\t\\item  GPS week\r\n\t\\item  GPS TOW in seconds\r\n\t\\item  Solution type (6 for float PPP, 1 for ambiguity fixed PPP)\r\n\t\\item  Number of satellites used in the solution\r\n\t\\item  Receiver clock offset for with respect to GPS clock, in nanoseconds\r\n\t\\item  Receiver clock offset for with respect to GLONASS clock, in nanoseconds\r\n\t\\item  Receiver clock offset for with respect to Galileo clock, in nanoseconds\r\n\t\\item  Receiver clock offset for with respect to Beidou clock, in nanoseconds\t\r\n\t\\item  Standard deviation of clock offset wrt. GPS, in nanoseconds\r\n\t\\item  Standard deviation of clock offset wrt. GLONASS, in nanoseconds\r\n\t\\item  Standard deviation of clock offset wrt. Galileo, in nanoseconds\r\n\t\\item  Standard deviation of clock offset wrt. Beidou, in nanoseconds\t\r\n\\end{enumerate}\r\nIf clock offsets for a particular constellation are not available both the offset and its variance will be set to 0.\r\n\r\n\\textbf{Tropospheric delays} at the receiver position are preceded by the \"\\$TROP\" label and thus, in Linux, can be extracted using the command:\r\n \\begin{lstlisting}\r\n$ grep \"$TROP\" <path_to_trace_file>\r\n\\end{lstlisting}\r\nthe tropospheric delay solutions will be represented to either a single line, with the \"\\$TROP\" or three lines, as follows:\r\n\\begin{lstlisting}\r\n$TROP,2166,278015.000,6,14,2.294950,0.0030977\r\n$TROP_N,2166,278015.000,6,14,-0.174797,0.0181385\r\n$TROP_E,2166,278015.000,6,14,-0.223868,0.0250276\r\n\\end{lstlisting}\r\neach of the troposphere output line will contain 7 comma separated field, of which the first five are:\r\n\\begin{enumerate}\r\n\t\\item  Label, \"\\$TROP\", \"\\$TROP\\_N\" or \"\\$TROP\\_E\"\r\n\t\\item  GPS week\r\n\t\\item  GPS TOW in seconds\r\n\t\\item  Solution type (6 for float PPP, 1 for ambiguity fixed PPP)\r\n\t\\item  Number of satellites used in the solution\r\n\\end{enumerate}\r\nThe line starting with \"\\$TROP\" contain the Zenith Tropospheric Delay (ZTD) and its standards deviation, both in meters, as their last two fields.  The line starting with \"\\$TROP\\_N\" contains the tropospheric delay gradient in north-south direction, and  the line starting with \"\\$TROP\\_E\" contains the tropospheric delay gradient in east-west direction.\r\n\r\nConfiguration files for specific examples have been added to the \\textit{examples} folder in the repository. Examples corresponding to end user processing are explained bellow. In order to \r\n\r\n\\subsection{Dual frequency PPP with floating ambiguities}\r\nAs the end-user processing mode cannot calculate satellite states, the satellite position and clock offset needs to be provided externally.\r\nThe PEA supports SP3 formatted satellite position inputs, specified in \\textit{input\\_files : sp3files}, and RINEX clock files, \\textit{input\\_files : clkiles}, as satellite clock inputs. \r\nANTEX files, with antenna information for both stations and satellites should be provided in  \\textit{input\\_files : atxfiles} \r\nSINEX files, with station antennas should be provided in  \\textit{input\\_files : snxfiles}\r\nRINEX 3.XX navigation files, with broadcast clocks should be provided in  \\textit{input\\_files : navfiles}\r\nBLQ formatted ocean tide  loading parameters for each station should be provided in \\textit{input\\_files : blqfiles} if available to correct for OTL, otherwise \\textit{processing\\_options : tide\\_otl} should be set to \\textit{false}.\r\nRINEX 3.XX observation files for the network stations should be provided in \\textit{station\\_data : rnxfiles} (* can be used as a wildcard).\\\\\r\n\r\nThe configuration files named \\textit{examples/ex11\\_pea\\_pp\\_user\\_gps.yaml} and \\textit{examples/ex12\\_pea\\_pp\\_user\\_gnss.yaml} set the PEA to calculate a post-process end user solution for a static receiver. \r\nThe constellations to be used in processing can be specified in the \\textit{processing\\_options : process\\_sys} field.\r\nThe tracking of a moving receiver can be done by setting the \\textit{default\\_filter\\_parameters : stations : pos : proc\\_noise} parameter to the maximum expected velocity.\r\nReceiver velocity can also be estimated by setting  \\textit{default\\_filter\\_parameters : stations : pos\\_rate : estimate} to \\textit{true}.\\\\\r\n\r\nTropospheric delays are estimated as a combination of hydrostatic and wet components, each component is in turn estimated as the products of the zenith delay and a mapping function.\r\n If \\textit{default\\_filter\\_parameters : stations : trop : estimate} is set to \\textit{true}, the PEA estimates the zenith wet delay.\r\n If \\textit{default\\_filter\\_parameters : stations : trop\\_grad : estimate} is set to \\textit{true}, the PEA also estimates azimutal components of tropospheric mapping functions.\r\nThe hydrostatic zenith delays and elevation dependent component of mapping functions are calculated based on pre-defined models.\r\nAvailable models, whic can be selected using the \\textit{processing\\_options : troposphere : model} parameter, are the GPT2 and VMF3 models.\r\nIf using the GPT2 model the path to the necessary grid file needs to be specified in  \\textit{processing\\_options : troposphere : gpt2grid}\r\nIf using the VMF3 model, the tropospheric parameters corresonding to the observatin times need to be provided in a directory specified by \\textit{processing\\_options : troposphere : vmf3dir}, and the orography file for atmospheric circulation models need to be specified in \\textit{processing\\_options : troposphere : orography}.\\\\\r\n \r\n\\subsection{Single frequency PPP}\r\nIt is possible to perform end user PPP processing using single frequency data (although at reduced accuracy) by providing extenal Ionospheric delay data.\r\nThe configuration files named \\textit{examples/ex13\\_pea\\_pp\\_user\\_gps\\_sf.yaml} set an example to process single frequency observations.\r\nThe PEA currently uses IONEX formatted VTEC maps as Ionosphere delay data. \r\nThe path to the IONEX file needs to be specified  in  \\textit{input\\_files : ionfiles}.\r\nIn order for the PEA to use the VTEC maps, the \\textit{processing\\_options : ionosphere : corr\\_mode} parameter should to be set to \\textit{total\\_electron\\_content}.\r\nIf provided separatelly, files containing the satellite DCB (either RINEX DCB or bias SINEX) should be specified in \\textit{input\\_files :dcbfiles} \\\\\r\n\r\n\\subsection{Dual frequency PPP with ambiguity resolution}\r\nThe PEA (in both network and user processing modes) can be specified to perform ambiguity resolution in an attempt to improve accuracy and convergence times.\r\nIn aside from the requirements for floating PPP ambiguities, information on satellite hardware biases needs to be provided order to allow correct ambiguity resolution in end user PEA processing.\r\nFor post-process, the PEA use bias SINEX formatted files as input channels for satellite hardware biases.\r\nThe bias SINEX file can be specified in \\textit{input\\_files :bsxfiles}.\r\n\r\nThe ambiguity resolution process is controlled by the \\textit{ambiguity\\_resolution\\_options} field.\r\nCurrently ambiguity resolution is only supported for GPS and Galileo satellited. \r\nAmbiguity resolution for GPS satellites can be activated by setting the \\textit{GPS\\_amb\\_resol} parameter to \\textit{true}.\r\nAmbiguity resolution for Galileo satellites can be activated by setting the \\textit{GAL\\_amb\\_resol} parameter to \\textit{true}.\r\nIn addition the ambiguity resolution algorithm needs to be specified for both the wide-lane ambiguity (\\textit{WL\\_mode}) and narrow-lane ambiguities (\\textit{NL\\_mode}.\r\nFor best results, \\textit{round} or \\textit{iter\\_rnd} are recommended for Wide-lane ambiguities and  \\textit{lambda\\_alt} or \\textit{lambda\\_bie} is recommended for narrow-lane ambiguities.\\\\\r\n\r\n\\subsection{Real-time PPP}\r\nThe PEA can also be used to process GNSS data in real-time. \r\nReal-time processing will make use of RTCM formatted streams for receiver observables and satellite data.\r\nCurrently the PEA can only get real-time data by connecting to an NTRIP caster.\r\nAn example of such a caster, can be accessed by registering at \\href{https://www.auscors.ga.gov.au/}.\r\nThe host name, user name and password corresponding to the NTRIP can shold be specified under \\textit{station\\_data : stream\\_root} using the format \\textit{http(s)://user:password@hostname/}.\r\nThe mountpoint corresponding to station observables need to be listed under \\textit{station\\_data : obs\\_streams}.\r\nEphemeris streams (broadcast ephemeris and SSR corrections) shold be listed under \\textit{station\\_data : nav\\_streams}.\r\nThe PEA support MSM4, MSM5, MSM6 and MSM7 messages for observations, and orbit and clock messages, code bias messages and phase bias messages for GPS and Galileo.\\\\\r\n\r\nReal-time outputs are not yet defined for PEA, the processed receiver solution are printed in real time on the TRACE files.\\\\", "meta": {"hexsha": "f18c882769392cd2643ec99f2f0d3dd00b96be10", "size": 11173, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/manual/Processing_in_User_mode.tex", "max_stars_repo_name": "RodrigoNaves/ginan-bitbucket-update-tests", "max_stars_repo_head_hexsha": "4bd5cc0a9dd0e94b1c2d8b35385e128404009b0c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 73, "max_stars_repo_stars_event_min_datetime": "2021-07-08T23:35:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:17:58.000Z", "max_issues_repo_path": "docs/manual/Processing_in_User_mode.tex", "max_issues_repo_name": "RodrigoNaves/ginan-bitbucket-update-tests", "max_issues_repo_head_hexsha": "4bd5cc0a9dd0e94b1c2d8b35385e128404009b0c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-09-27T14:27:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T23:50:02.000Z", "max_forks_repo_path": "docs/manual/Processing_in_User_mode.tex", "max_forks_repo_name": "RodrigoNaves/ginan-bitbucket-update-tests", "max_forks_repo_head_hexsha": "4bd5cc0a9dd0e94b1c2d8b35385e128404009b0c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 39, "max_forks_repo_forks_event_min_datetime": "2021-07-12T05:42:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:15:34.000Z", "avg_line_length": 80.381294964, "max_line_length": 355, "alphanum_fraction": 0.7805423789, "num_tokens": 2827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.3110515659663763}}
{"text": "\\label{sec:swaption}\nTo the best of our knowledge, Liu proposed the only implementation of atomic swaption which does not require either blockchain to support smart contracts \\cite{liu2018atomic}. Afterward, Tefagh~\\etal~ designed atomic bonded cross-chain debt (ABCD) as the first practical cross-chain bond platform in the form of atomic swaptions \\cite{tefagh2020atomic}. In this paper, we have designed a more general model of atomic swaption named \\emph{\\MetaSwaption} which is abstractly shown in Fig~\\ref{fig:moc-swaption}.\n\nIn what follows, we are going to briefly explain every module of the \\MetaSwaption, and through the rest of this paper, we will use this general form as the building block for making some new application-specific swaptions.\n\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=\\textwidth,height=\\textheight,keepaspectratio]{figures/meta-swaption.png}\n    \\caption{General overview of the \\MetaSwaption}\n    \\label{fig:moc-swaption}\n\\end{figure}\n\nSimilar to atomic swap and atomic swaption, HTLCs are used so that a party can make decisions by revealing a secret before a locktime or letting the locktime expire. In \\MetaSwaption also there are four types of such secrets:\n\\begin{itemize}\n    \\item \\Aone key\n    \\item \\keyone key\n    \\item \\Atwo key\n    \\item \\Delegation key\n\\end{itemize}\n\nNote that in HTLC contracts, generaly the locktime of the holder of the secret has to be greater than the other party.\n%\\ahC{It has to be greater}\n% We call the one who buys the swaption, the swpation \\SwaptionOwner. In our cases it is mostly Alice.\n\nIn the Fig~\\ref{fig:moc-swaption}, a \\MetaSwaption is \ndivided into five different parts, each representing a particular stage in the swaption process. \n\nNote that in every module introduced in this paper, all transactions in the execution process are exchanged and signed by their corresponding parties before anything goes on chain. During this not-yet-confirmed transactions sharing, all parties are assured that no one can steal their money.\n\n\n\\begin{itemize}\n\n    \\item \\textbf{Contract funding}: The funding for the swaption buyer (swaption owner) consists of premium and for the seller only margin. Depending on application, the \\SwaptionOwner may include margin in her funding.\n    The \\SwaptionOwner has a relatively small amount of time to reveal \\Aone key to buy the option. If she buys the option, premium goes to the seller and margins go to the principal deposition contracts.\n    %  Each party sends his margin to a HTLC contract. The swaption buyer also pays a premium to buy the option from the seller. After the exchange of funding transactions, it is time for the swaption buyer to decide weather she buys the option or not. If she reveals the \\Aone key, premium goes to the seller and margins go to the margin deposit contracts.\n    \n    \\item \\textbf{Principal deposition}: After buying the swpation, each party has to deposit his principal within a specified time interval. If both parties cooperate, the next stage begins.\n    The principal deposition transactions might have sighash type of any-one-can-pay\\footnote{ANYONECANPAY} since nobody knows all of its inputs in the first place. In this case, since we do not know all the inputs of this transaction at the time of signing, we would not have the correct transaction ID \\cite{bip143}. Therefore, we can not create the transactions that get their inputs form this transaction until we discover what all the inputs of the this transaction are going to be. These inputs are only known at the time of broadcasting, not at the time of creating the transactions. So, at the time of creating the transactions in the next stage, the ID of the principal deposition transaction is unknown.\n    \n    \\item \\textbf{Leader lock}: Depending on the application, the swaption \\SwaptionOwner may decide to use a portion of her option duration as the allowed period of her late principal deposition in order to make money for her principal. In this stage, the party who deposits his principal earlier, \\keyone key holder, locks his principal. After assurance of the owner's principal deposition, he is expected to reveal \\keyone key determining if the swaption goes to the next stage or not.\n    As mentioned in the last stage, the ID of the input of the transactions of this stage is not known at the time of creating. Thus, we have to use the sighash type of no-input\\footnote{NOINPUT}\\cite{bip118} that allows us to create a transaction where none of its inputs are known. So, by this sighash we can create the transactions in the leader lock stage without any inputs. Later, at the time of broadcast, since the inputs of the principal deposition transaction are known and consequently we have its ID, we can use this transaction as an input for the transactions of the leader lock stage and broadcast them.\n    \n    \\item \\textbf{Master lock}: In this stage, the \\SwaptionOwner (\\Atwo key holder) chooses weather she exercises the option or not using \\Atwo key. By exercising the option, principals are exchanged and the swaption ends. By not revealing \\Atwo key, letting the locktime expire, next stage begins. Like the last stage, since the inputs of the parent transaction of the transactions of this stage are not clear, we have to use the no-input sighash.\n    \n    \\item \\textbf{Option delegation}: This stage might be utilized in certain use-cases such as futures arbitrage discussed later. For fixing the problem of cyclic locktimes in master lock stage, we develop a method to delegate the option from \\SwaptionOwner to another desired party. The newly promoted party can later decide the execution of the swaption by the \\Delegation key. In this stage, like last two stages we have to use the no-input sighash.\n\n    % \\item \\textbf{Trust box}: In some cases, i.e. futures arbitrage, the \\SwaptionOwner needs to transfer the right of signing some transactions to a party other than swaption buyer or seller. The extents of trust box may differ for each use-cases of \\MetaSwaption instances.\n    % \\ahC{Is this paragraph needed anymore?}\n\\end{itemize}\n\nWhen using the no-input sighash, the party signs the transaction without specifying its inputs, so a malicious party has the ability to give any UTXO that belongs to the public key of this party. Hence, each party has to create a separate public key for each transaction that she makes.\nUsing the stages described above, we can generate new instances of \\MetaSwaption targeting swaptions or bonds. Based on different goals, we can choose which of these stages appear in our instance. In the following subsections, we describe different swaptions devised for a variety of use-cases:\n\\begin{itemize}\n    \\item Early deposition swaption\n    \\item Late deposition swaption\n    \\item Margin-free limited swaption\n\\end{itemize}\nNotice that in Fig~\\ref{fig:swaption-early-deposition}, Fig~\\ref{fig:swaption-late-deposition}, and Fig~\\ref{fig:swaption-margin-free-limited} the locktimes $P$,$T$,$M$,$E$, and $T'$ are calculated with respect to  a common origin of time. In other words, the current time of the swaption establishment has to be added to all the locktimes shown in these stages, because they are not relative but absolute times. \n% Each of these components has different procedure. For further analysing the effectiveness of each component, we design a time elapsed experiment aiming to analyse the worst case running time of them.\n\n\n% \\begin{experiment}\n% {Time Elapsed}\\\\\n% Given $p_{buyer}$ and $p_{seller}$ the buyer and the seller of the component $\\mathcal{C}$, the $\\mathcal{T}[\\mathcal{C}]$ is the minimum spend locktime during the execution runtime of $\\mathcal{C}$ if $p_{seller}$ adversarially waits in every steps until the last moments.\n% \\end{experiment}\n\n% We discus the second type in detail. The other types are discussed in \\Apn{\\ref{app:conv-swaption}} and \\Apn{\\ref{app:margin-free-swaption}}.\n\n% \\ahC{Somewhere we have to mention that we split the option time into two parts, one is time for revealing \\keyone key and the other one is \\Atwo key. Then we can say that Alice is settling other swaptions in the case of arbitrage during option time.}\n\n\n\n\\subsection{Early Deposition Swaption}\n\\label{app:conv-swaption}\n\nThis type of swaption is the conventional form that is first introduced in \\cite{liu2018atomic}. Alice wants to exchange her ACoins with Bob's BCoins. We rebuild this type with our \\MetaSwaption extended form in the way depicted in Fig~\\ref{fig:swaption-early-deposition}. We begin analysing each stage of this type by explaining every possible scenarios as follows:\n\n\\begin{itemize}\n    \\item \\textbf{Contract funding}: Alice and Bob broadcast their funding transactions. Alice's includes margin and premium and Bob's includes margin worth equal to Alice's margin.\n    \n    \\item \\textbf{Principal deposition}: In this stage, Bob is waiting for Alice to deposit her principal. There are two possible scenarios:\n    \\begin{itemize}\n        \\item Alice does not deposit her principal. In this case, Bob also defaults and their margins are exchanged.\n        \\item Alice deposits her principal but Bob does not. In this case, Alice is in master lock stage. So, she reveals \\Atwo and takes Bob's margin besides her own principal.\n        % Alice is already in option contract stage and she can take the ownership of both her principal and Bob's margin by revealing the \\Atwo key and broadcasting Bob's default transaction.\n    \\end{itemize}\n     But if Bob fails to deposit his principal, \n    \n    \\item \\textbf{Master lock}: If both parties go to this stage, Alice can then use her option as mentioned earlier.\n\\end{itemize}\n\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=\\textwidth]{figures/early dep.png}\n    \\caption{Early deposition swaption where the buyer (Alice) deposits her principal earlier than the seller (Bob). The pink-bordered transactions are broadcasted by Alice and the blue-bordered ones by Bob.}\n    \\label{fig:swaption-early-deposition}\n\\end{figure}\n% \\ahC{Shall we mention that 546 Satoshis can not be counted as margin?}\n\n\n\\subsection{Late Deposition Swaption}\nIn this type of swaption the swaption \\SwaptionOwner, Alice, needs the seller, Bob, to deposit his principal before her, so that she can settle other deals on other contracts before depositing her principal in this swaption. Alice can exploit this type of swaption in the situations where she does not own enough budget for her principal and she is going to make the required amount of capital using what she has takes from Bob. Since Bob has to wait a longer time for Alice to deposit, Alice has to pay more amount of premium compared to the early deposition swaption.\nOne example use-case can be the futures arbitrages which will be discussed later. The overview of this swaption is shown on Fig.~\\ref{fig:swaption-late-deposition}.\n\n\\begin{itemize}\n    \\item \\textbf{Contract funding:} The two parties broadcast their funding transactions. Alice includes margin in her funding and an amount of guarantee is added to Bob's funding besides his margin. We can use this guarantee amount to punish Bob in case of cheating. If he behaves normally, the guarantee will return back to him. The amount of guarantee is negotiable depending on the use-case.\n    \n    \\item \\textbf{Principal deposition:} When this stage begins Alice is waiting for Bob to deposit his principal. If Bob defaults, then Alice has two options to punish him:\n    \\begin{itemize}\n        \\item She defaults, loses her margin and takes Bob's guarantee and margin.\n        \\item She deposits her principal and enters the next stage.\n    \\end{itemize}\n\n    \\item \\textbf{Leader lock}: \n    There are four possible scenarios:\n    \\begin{itemize}\n        \\item In the last stage, Bob deposited his principal but Alice did not. Now Bob does not reveal \\keyone key, so that Alice's margin is exchanged with Bob's margin.\n        \\item Both have deposited their principals and Bob does not reveal \\keyone key. Broadcasting the Alice's leader lock transactions, Alice gets Bob's guarantee.\n        \\item In the last stage, Alice deposited her principal but Bob did not (Second way to punish Bob). Now Alice broadcasts the Alice's leader lock expiration transaction and takes all of her principal back in addition to Bob's margin and guarantee that she has previously taken in the last stage. \n        \\item Both have deposited their principals. Bob reveals \\keyone key and take back his guarantee. Afterward, they go to the next stage.\n    \\end{itemize}\n    \n    \\item \\textbf{Master lock}: It is the time for Alice to use her option. She either exercises and principals are exchanged or reveals nothing and each party gets his principal back.\n\\end{itemize}\n\n\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=\\textwidth,height=0.93\\textheight,keepaspectratio]{figures/late dep.png}\n    \\caption{Late deposition swaption where the seller (Bob) deposits his principal earlier than the buyer (Alice). Pink-bordered transactions are broadcast by Alice and blue-bordered ones by Bob.}\n    \\label{fig:swaption-late-deposition}\n\\end{figure}\n\n% Note that since Bob's only incentive is the premium (and not the margin), it is not possible that Alice uses this swaption alongside with other swaptions. For instance, in the case that Alice uses Bob's principal as her principal in another swaption, Bob can cheat on Alice by pretending to be a different person and act as the other party in the second swaption as well as the first one. Then he can steal Alice's premium in the second swaption by not exposing the \\keyone key. \n% Later we will prove that Alice can only use one premium guarantee in a set of swaptions which are expected to be exercised in one run simultaneously. Because every run must have only one \\keyone and \\Atwo and \\Aone key which is impossible when we use multiple premium guarantee boxes.\n% It is not possible to allow Alice to send the premium of other swaption in directly with usage of another Premium Guarantee \n%\\ahC{This section is changed and it is no longer standalone. Still move to appendix?}\n% The detailed process of this swaption is written in \\Apn{\\ref{app:margin-free-swaption}} \n% \\ref{app:margin-free-swaption}.\n\n\n\n% \\subsection{Atomic Non-collateralized Loan}\n% A modification of the {\\it Late-Deposition swaption} in which Alice does not have to deposit any margin before she gets Bob's principal has the functionality of a loan with no collateral needed. As mentioned in \\cite{liu2018atomic} it is not possible to have no margin for the buyer if the parties are on different blockchains. \\fatemeC{explain more} Hence, in order to have this loan, the parties have to be on the same chain. \n\n\n\n\\subsection{Margin-Free Limited Swaption}\n\n\\label{app:margin-free-swaption}\nUntil now, it was believed that Alice's margin deposit is necessary due to the limitations of HTLCs \\cite{liu2018atomic}. In this work, we propose a novel approach which allows Alice to participate in a swaption without depositing any margin.\nIn the beginning of contract, Bob deposits an amount of BCoin as guarantee which is sent to Alice directly by revealing \\Aone key. Alice also adds an amount of ACoin equal to Bob's guarantee to her premium, though none of them will be directly sent to Bob. Later, the premium and guarantee go to Bob in all possible situations except where Bob refuses to reveal the \\keyone key when Alice does not default, then he will be punished by not getting back his guarantee.\n% In Fig~ \\ref{fig:swaption-margin-free-limited} we use our getting a guarantee money from Bob to build the {\\it Margin Free} swaption.\n% In this type besides premium, Alice deposits an amount of ACoiun equal to Bob's guarantee. Her premium is not paid directly after revealing of \\Aone key, but instead will be locked until Bob acts honestly up to end of the Leader Lock stage.\n% Later the premium goes to Bob in all possible situations except where Bob refuses to reveal the \\keyone key and he will be punished by not paying back his guarantee. \nThe amount of guarantee can vary depending on the Alice's need. In next section, we will explain the limitation imposed on the amount of guarantee in details. The execution procedure of the margin-free swaption is as follows:\n\\begin{itemize}\n    \\item \\textbf{Contract funding}: Bob pays his margin plus an amount of guarantee which prevents him from cheating in later stages. Alice also pays extra premium which in the case of Bob's honest behaviour pays back the guarantee to Bob. Guarantee in the Bob's section is directly sent to Alice after revealing the \\Aone key. \n    \n    \\item \\textbf{Principal deposition}: This stage is the same as previous principal deposition stages for Bob. He has M locktime to deposit his principal. If he does not, Alice takes his margin. In Alice's section, either she defaults and gives Bob the premium or she deposits her principal and goes to the next stage waiting for Bob to reveal the \\keyone key.\n    % \\item \\textbf{Premium Guarantee}: Either Alice defaults and gives Bob the premium or she deposits her principal and goes to the next stage waiting for Bob to reveal the \\keyone key.\n    \n    \\item \\textbf{Leader key}: If Bob has not deposited his principal until M locktime, Alice will also avoid depositing her principal and gives Bob the premium and ACoin guarantee while getting his margin from him.\n    % and Alice has two options ahead: 1)She deposits her principal before M + T, then broadcasts the \\keyone key expiration transaction, in which her premium is refunded. Therefore, if Bob defaults and Alice does not, there would be no premium for Bob. In any other situation he gets the premium. \n    If both parties have deposited their principals when this stage begins, Bob's decision whether to reveal the \\keyone key or not, determines the future of the swaption. If he refuses to reveal, he takes his own money back and Alice takes her own money including premium back. In this case, Bob loses his guarantee as a punishment. Otherwise, if he reveals the \\keyone key, they both go to the next stage waiting for Alice to exercise her option. Additionally, by revealing the \\keyone key, Bob finishes his task and it is the time to send back his guarantee. Hence at the end of this stage, Bob's guarantee will be paid back to himself.\n    \n    \\item \\textbf{Option funding}: This stage is similar to the last versions of swpation.\n\\end{itemize}\n\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=\\textwidth,height=0.93\\textheight]{figures/swaption-margin-free.png}\n    \\caption{Margin-free limited swpation where the buyer (Alice) is not supposed to deposit any margin. Pink-bordered transactions are broadcasted by Alice and blue-bordered ones by Bob.}\n    \\label{fig:swaption-margin-free-limited}\n\\end{figure}\n% \\fatemeC{mention auction as an application for the margin-free swaption. you can use the aucion section primarily written}\n\nLocktimes in all of these swaptions have to stick to some general rules: \n\\begin{itemize}\n    \\item $T$ is the minimum amount of time or number of blocks needed for a mined transaction to be confirmed. In bitcoin it is $6$ blocks which is approximately achieved in 1 hour.\n    \n    \\item $M$ is the time for Bob to deposit principal. Hence, can be equal or greater than $T$.\n    \n    \\item $T'$ can be relatively large, since it gives Alice the time she needs to deposit her principal.\n    \n    \\item $P$ is the locktime that Bob has to reveal the \\keyone key. This has to be larger than $T'$ so that Alice has to deposit before Bob's revealing time elapses.\n    \n    \\item $E$ is the time for Alice's option exercise which can be relatively large, since it is an option.\n\\end{itemize}\nNote that we use $T$ to make two locktimes differ in a reasonable amount of time to prevent cheating. However, this is the minimum difference needed. Hence, everywhere $T$ is used, we can replace it with different larger values. We use $T$ for simplicity though.", "meta": {"hexsha": "2de660f492080fe3557c0ee1b7bed3e775fb82b3", "size": 20017, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "CFFA/sections/swaption.tex", "max_stars_repo_name": "incentivus/ICBTA", "max_stars_repo_head_hexsha": "da47329f322e20aa37a80ca71b75134c1f574427", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-04-08T02:06:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T09:11:33.000Z", "max_issues_repo_path": "CFFA/sections/swaption.tex", "max_issues_repo_name": "incentivus/articles", "max_issues_repo_head_hexsha": "da47329f322e20aa37a80ca71b75134c1f574427", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-10-12T16:28:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-20T05:06:18.000Z", "max_forks_repo_path": "CFFA/sections/swaption.tex", "max_forks_repo_name": "incentivus/articles", "max_forks_repo_head_hexsha": "da47329f322e20aa37a80ca71b75134c1f574427", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 105.3526315789, "max_line_length": 713, "alphanum_fraction": 0.7766898137, "num_tokens": 4557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.31105155923688455}}
{"text": "\\providecommand{\\tightlist}{%\n  \\setlength{\\itemsep}{0pt}\\setlength{\\parskip}{0pt}}\n\n\\subsection{Leabra Algorithm\nEquations}\\label{leabra-algorithm-equations}\n\nThe pseudocode for Leabra is given here, showing exactly how the pieces\nof the algorithm fit together, using the equations and variables from\nthe actual code. The implementation contains a number of optimizations\n(including vectorization and GPU code), but this provides the core math\nin simple form.\n\nSee the \\texttt{Matlab} directory in the emergent \\url{svn} source\ndirectory for a complete implementation of these equations in Matlab,\ncoded by Sergio Verduzco-Flores --- this can be a lot simpler to read\nthan the highly optimized C++ source code.\n\n\\subsubsection{Timing}\\label{timing}\n\nLeabra is organized around the following timing, based on an\ninternally-generated alpha-frequency (10 Hz, 100 msec periods) cycle of\nexpectation followed by outcome, supported by neocortical circuitry in\nthe deep layers and the thalamus, as hypothesized in the\n\\url{DeepLeabra} extension to standard Leabra:\n\n\\begin{itemize}\n\\tightlist\n\\item\n  A \\textbf{Trial} lasts 100 msec (10 Hz, alpha frequency), and\n  comprises one sequence of expectation --- outcome learning, organized\n  into 4 quarters.\n\n  \\begin{itemize}\n  \\tightlist\n  \\item\n    Biologically, the deep neocortical layers (layers 5, 6) and the\n    thalamus have a natural oscillatory rhythm at the alpha frequency.\n    Specific dynamics in these layers organize the cycle of expectation\n    vs. outcome within the alpha cycle.\n  \\end{itemize}\n\\item\n  A \\textbf{Quarter} lasts 25 msec (40 Hz, gamma frequency) --- the\n  first 3 quarters (75 msec) form the expectation / minus phase, and the\n  final quarter are the outcome / plus phase.\n\n  \\begin{itemize}\n  \\tightlist\n  \\item\n    Biologically, the superficial neocortical layers (layers 2, 3) have\n    a gamma frequency oscillation, supporting the quarter-level\n    organization.\n  \\end{itemize}\n\\item\n  A \\textbf{Cycle} represents 1 msec of processing, where each neuron\n  updates its membrane potential etc according to the above equations.\n\\end{itemize}\n\n\\subsubsection{Variables}\\label{variables}\n\nLeabraUnits are organized into LeabraLayers, which sometimes have unit\ngroups (which are now typically purely virtual, not actual Unit\\_Group\nobjects). The LeabraUnit has the following key parameters, along with a\nnumber of others that are used for other non-default algorithms and\nvarious optimizations, etc.\n\n\\begin{itemize}\n\\tightlist\n\\item\n  \\textbf{act} = activation sent to other units\n\\item\n  \\textbf{act\\_nd} = non-depressed activation --- prior to application\n  of any short-term plasticity\n\\item\n  \\textbf{net\\_raw} = raw netinput, prior to time-averaging\n\\item\n  \\textbf{net} = time-averaged excitatory conductance (net input)\n\\item\n  \\textbf{gc\\_i} = inhibitory conductance, computed from FFFB inhibition\n  function typically\n\\item\n  \\textbf{I\\_net} = net current, combining excitatory, inhibitory, and\n  leak channels\n\\item\n  \\textbf{v\\_m} = membrane potential\n\\item\n  \\textbf{v\\_m\\_eq} = equilibrium membrane potential --- not reset by\n  spikes --- just keeps integrating\n\\item\n  \\textbf{adapt} = adaptation current\n\\item\n  \\textbf{avg\\_ss} = super-short term running average activation\n\\item\n  \\textbf{avg\\_s} = short-term running average activation, integrates\n  over avg\\_ss, represents plus phase learning signal\n\\item\n  \\textbf{avg\\_m} = medium-term running average activation, integrates\n  over avg\\_s, represents minus phase learning signal\n\\item\n  \\textbf{avg\\_l} = long-term running average activation, integrates\n  over avg\\_m, drives long-term floating average for Hebbian learning\n\\item\n  \\textbf{avg\\_l\\_lrn} = how much to use the avg\\_l-based Hebbian\n  learning for this receiving unit's learning --- in addition to the\n  basic error-driven learning --- this can optionally be dynamically\n  updated based on the avg\\_l factor and average level of error in the\n  receiving layer, so that this Hebbian learning constraint can be\n  stronger as a unit gets too active and needs to be regulated more\n  strongly, and in proportion to average error levels in the layer.\n\\item\n  \\textbf{avg\\_s\\_eff} = effective avg\\_s value used in learning ---\n  includes a small fraction (.1) of the avg\\_m value, for reasons\n  explained below.\n\\end{itemize}\n\nUnits are connected via synapses parameterized with the following\nvariables. These are actually stored in an optimized vector format, but\nthe LeabraCon object contains the variables as a template.\n\n\\begin{itemize}\n\\tightlist\n\\item\n  \\textbf{wt} = net effective synaptic weight between objects ---\n  subject to contrast enhancement compared to fwt and swt\n\\item\n  \\textbf{dwt} = delta-wt --- change in synaptic weights due to\n  learning\n\\item\n  \\textbf{dwavg} = time-averaged absolute value of weight change, for\n  normalizing weight changes\n\\item\n  \\textbf{moment} = momentum integration of weight changes\n\\item\n  \\textbf{fwt} = fast weight --- used for advanced fast and slow weight\n  learning dynamic --- otherwise equal to swt --- stored as\n  non-contrast enhanced value\n\\item\n  \\textbf{swt} = slow weight --- standard learning rate weight ---\n  stored as non-contrast enhanced value --- optional\n\\end{itemize}\n\n\\subsubsection{Activation Update Cycle (every 1 msec): Net input,\nInhibition,\nActivation}\\label{activation-update-cycle-every-1-msec-net-input-inhibition-activation}\n\nFor every cycle of activation updating, compute the net input,\ninhibition, membrane potential, and activation:\n\n\\begin{itemize}\n\\tightlist\n\\item\n  \\textbf{Net input} (see LeabraUnitSpec.cpp for code):\n\n  \\begin{itemize}\n  \\tightlist\n  \\item\n    \\textbf{\\texttt{net\\_raw}}\\texttt{\\ +=\\ (sum\\ over\\ recv\\ connections\\ of:)\\ scale\\_eff\\ *\\ act\\ *\\ wt}\n\n    \\begin{itemize}\n    \\item\n      \\textbf{scale\\_eff} =\n      \\verb\\https://grey.colorado.edu/emergent/index.php/Leabra_Netin_Scaling\\ factor that includes 1/N to compute an average, plus\n      wt\\_scale.rel and abs relative and absolute scaling terms.\n    \\item\n      \\textbf{act} = sending unit activation\n    \\item\n      \\textbf{wt} = receiving connection weight value between sender and\n      receiver\n    \\item\n      does this very efficiently by using a sender-based computation,\n      that only sends \\emph{changes} (deltas) in activation values ---\n      typically only a few percent of neurons send on any given cycle.\n    \\end{itemize}\n  \\item\n    \\textbf{\\texttt{net}}\\texttt{\\ +=\\ dt.integ\\ *\\ dt.net\\_dt\\ *\\ (net\\_raw\\ -\\ net)}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      time integration of net input, using net\\_dt (1/1.4 default), and\n      global integration time constant, dt.integ (1 = 1 msec default)\n    \\end{itemize}\n  \\end{itemize}\n\\end{itemize}\n\n\\begin{itemize}\n\\tightlist\n\\item\n  \\textbf{Inhibition} (see LeabraLayerSpec.cpp for code) -- earlier versions of Leabra used an explicit k-Winners-Take-All inhibition function, but the FFFB equations here are much simpler and produce desirable flexibility in overall activation levels:\n\n  \\begin{itemize}\n  \\tightlist\n  \\item\n    \\textbf{\\texttt{ffi}}\\texttt{\\ =\\ ff\\ *\\ MAX(netin.avg\\ -\\ ff0,\\ 0)}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      feedforward component of inhibition with ff multiplier (1 by\n      default) --- has ff0 offset and can't be negative (that's what\n      the MAX(.. ,0) part does).\n    \\item\n      \\textbf{netin.avg} is average of net variable across unit group or\n      layer, depending on what level this is being computed at (both are\n      supported)\n    \\end{itemize}\n  \\item\n    \\textbf{\\texttt{fbi}}\\texttt{\\ +=\\ fb\\_dt\\ *\\ (fb\\ *\\ acts.avg\\ -\\ fbi)}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      feedback component of inhibition with fb multiplier (1 by default)\n      --- requires time integration to dampen oscillations that\n      otherwise occur --- fb\\_dt = 1/1.4 default\n    \\end{itemize}\n  \\item\n    \\textbf{\\texttt{gc\\_i}}\\texttt{\\ =\\ gi\\ *\\ (ffi\\ +\\ fbi)}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      total inhibitory conductance, with global gi multiplier ---\n      default of gi=1.8 typically produces good sparse distributed\n      representations in reasonably large layers (25 units or more)\n    \\end{itemize}\n  \\end{itemize}\n\\end{itemize}\n\n\\begin{itemize}\n\\tightlist\n\\item\n  \\textbf{Membrane potential} (see LeabraUnitSpec.cpp for code)\n\n  \\begin{itemize}\n  \\tightlist\n  \\item\n    \\textbf{\\texttt{I\\_net}}\\texttt{\\ =\\ net\\ *\\ (e\\_rev.e\\ -\\ v\\_m)\\ +\\ gc\\_l\\ *\\ (e\\_rev.l\\ -\\ v\\_m)\\ +\\ gc\\_i\\ *\\ (e\\_rev.i\\ -\\ v\\_m)\\ +\\ noise}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      net current = sum of individual ionic channels: e = excitatory, l\n      = leak (gc\\_l is a constant, 0.1 default), and i = inhibitory\n    \\item\n      e\\_rev are reversal potentials: in normalized values derived from\n      biophysical values, e\\_rev.e = 1, .l = 0.3, i = 0.25\n    \\item\n      noise is typically gaussian if added\n    \\end{itemize}\n  \\item\n    if ex:\n    \\textbf{\\texttt{I\\_net}}\\texttt{\\ +=\\ g\\_bar.l\\ *\\ exp\\_slope\\ *\\ exp((v\\_m\\ -\\ thr)\\ /\\ exp\\_slope)}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      this is the exponential component of AdEx, if in use (typically\n      only for discrete spiking), exp\\_slope = .02 default\n    \\end{itemize}\n  \\item\n    \\textbf{\\texttt{v\\_m}}\\texttt{\\ +=\\ dt.integ\\ *\\ dt.vm\\_dt\\ *\\ (I\\_net\\ -\\ adapt)}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      in , we use a simple midpoint method that evaluates v\\_m with a\n      half-step time constant, and then uses this half-step v\\_m to\n      compute full step in above I\\_net equation. vm\\_dt = 1/3.3\n      default.\n    \\item\n      v\\_m is always computed as in discrete spiking, even when using\n      rate code, with v\\_m reset to vm\\_r etc --- this provides a more\n      natural way to integrate adaptation and short-term plasticity\n      mechanisms, which drive off of the discrete spiking.\n    \\end{itemize}\n  \\item\n    \\textbf{\\texttt{I\\_net\\_r}}\\texttt{\\ =\\ net\\ *\\ (e\\_rev.e\\ -\\ v\\_m\\_eq)\\ +\\ gc\\_l\\ *\\ (e\\_rev.l\\ -\\ v\\_m\\_eq)\\ +\\ gc\\_i\\ *\\ (e\\_rev.i\\ -\\ v\\_m\\_eq)\\ +\\ noise}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      rate-coded version of I\\_net, to provide adequate coupling with\n      v\\_m\\_eq.\n    \\end{itemize}\n  \\item\n    \\textbf{\\texttt{v\\_m\\_eq}}\\texttt{\\ +=\\ dt.integ\\ *\\ dt.vm\\_dt\\ *\\ (I\\_net\\_r\\ -\\ adapt)}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      the \\emph{equilibrium} version of the membrane potential does\n      \\emph{not} reset with spikes, and is important for rate code per\n      below\n    \\end{itemize}\n  \\end{itemize}\n\\end{itemize}\n\n\\begin{itemize}\n\\tightlist\n\\item\n  \\textbf{Activation} (see LeabraUnitSpec.cpp for code)\n\n  \\begin{itemize}\n  \\tightlist\n  \\item\n    \\textbf{\\texttt{g\\_e\\_thr}}\\texttt{\\ =\\ (gc\\_i\\ *\\ (e\\_rev\\_i\\ -\\ thr)\\ +\\ gc\\_l\\ *\\ (e\\_rev\\_l\\ -\\ thr)\\ -\\ adapt)\\ /\\ (thr\\ -\\ e\\_rev.e)}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      the amount of excitatory conductance required to put the neuron\n      exactly at the firing threshold, thr = .5 default.\n    \\end{itemize}\n  \\item\n    \\texttt{if(v\\_m\\ \\textgreater{}\\ spk\\_thr)\\ \\{\\ spike\\ =\\ 1;\\ v\\_m\\ =\\ vm\\_r;\\ I\\_net\\ =\\ 0.0\\ \\}\\ else\\ \\{\\ spike\\ =\\ 0\\ \\}}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      spk\\_thr is spiking threshold (1.2 default, different from rate\n      code thr), vm\\_r = .3 is the reset value of the membrane potential\n      after spiking --- we also have an optional refractory period\n      after spiking, default = 3 cycles, where the vm equations are\n      simply not computed, and vm remains at vm\\_r.\n    \\item\n      if using spiking mode, then \\textbf{act} = spike, otherwise, rate\n      code function is below\n    \\end{itemize}\n  \\item\n    \\texttt{if(v\\_m\\_eq\\ \\textless{}=\\ thr)\\ \\{\\ }\\textbf{\\texttt{new\\_act}}\\texttt{\\ =\\ NXX1(v\\_m\\_eq\\ -\\ thr)\\ \\}\\ else\\ \\{\\ }\\textbf{\\texttt{new\\_act}}\\texttt{\\ =\\ NXX1(net\\ -\\ g\\_e\\_thr)\\ \\}}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      it is important that the time to first ``spike'' be governed by\n      v\\_m integration dynamics, but after that point, it is essential\n      that activation drive directly from the excitatory conductance\n      (g\\_e or net) relative to the g\\_e\\_thr threshold --- activation\n      rates are linear in this term, but not even a well-defined\n      function of v\\_m\\_eq --- earlier versions of Leabra only used the\n      v\\_m\\_eq-based term, and this led to some very strange behavior.\n    \\item\n      NXX1 = noisy-x-over-x+1 function, which is implemented using a\n      lookup table due to the convolving of the XX1 function with a\n      gaussian noise kernel\n    \\item\n      \\texttt{XX1(x)\\ =\\ gain\\ *\\ x\\ /\\ (gain\\ *\\ x\\ +\\ 1)}\n    \\item\n      gain = 100 default\n    \\end{itemize}\n  \\item\n    \\textbf{\\texttt{act\\_nd}}\\texttt{\\ +=\\ dt.integ\\ *\\ dt.vm\\_dt\\ *\\ (new\\_act\\ -\\ act\\_nd)}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      non-depressed rate code activation is time-integrated using same\n      vm\\_dt time constant as used in v\\_m, from the new activation\n      value\n    \\end{itemize}\n  \\item\n    \\textbf{\\texttt{act}}\\texttt{\\ =\\ act\\_nd\\ *\\ syn\\_tr\\ (or\\ just\\ act\\_nd)}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      if short-term plasticity is in effect, then syn\\_tr variable\n      reflects the synaptic transmission efficacy, and this product\n      provides the net signal sent to the receiving neurons. otherwise\n      syn\\_tr = 1.\n    \\end{itemize}\n  \\item\n    \\textbf{\\texttt{adapt}}\\texttt{\\ +=\\ dt.integ\\ *\\ (adapt.dt\\ *\\ (vm\\_gain\\ *\\ (v\\_m\\ -\\ e\\_rev.l)\\ -\\ adapt)\\ +\\ spike\\ *\\ spike\\_gain)}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      adaptation current --- causes rate of activation / spiking to\n      decrease over time, adapt.dt = 1/144, vm\\_gain = 0.04, spike\\_gain\n      = .00805 defaults\n    \\end{itemize}\n  \\end{itemize}\n\\end{itemize}\n\n\\subsubsection{Learning}\\label{learning}\n\nLearning is based on running-averages of activation variables, described\nfirst:\n\n\\begin{itemize}\n\\tightlist\n\\item\n  \\textbf{Running averages} computed continuously every cycle, and note\n  the compounding form (see LeabraUnitSpec.cpp for code)\n\n  \\begin{itemize}\n  \\tightlist\n  \\item\n    \\textbf{\\texttt{avg\\_ss}}\\texttt{\\ +=\\ dt.integ\\ *\\ ss\\_dt\\ *\\ (act\\_nd\\ -\\ avg\\_ss)}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      super-short time scale running average, ss\\_dt = 1/2 default ---\n      this was introduced to smooth out discrete spiking signal, but is\n      also useful for rate code\n    \\end{itemize}\n  \\item\n    \\textbf{\\texttt{avg\\_s}}\\texttt{\\ +=\\ dt.integ\\ *\\ act\\_avg.s\\_dt\\ *\\ (avg\\_ss\\ -\\ avg\\_s)}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      short time scale running average, s\\_dt = 1/2 default --- this\n      represents the ``plus phase'' or actual outcome signal in\n      comparison to avg\\_m\n    \\end{itemize}\n  \\item\n    \\textbf{\\texttt{avg\\_m}}\\texttt{\\ +=\\ dt.integ\\ *\\ act\\_avg.m\\_dt\\ *\\ (avg\\_s\\ -\\ avg\\_m)}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      medium time-scale running average, m\\_dt = 1/10 average --- this\n      represents the ``minus phase'' or expectation signal in comparison\n      to avg\\_s\n    \\end{itemize}\n  \\item\n    \\textbf{\\texttt{avg\\_l}}\\texttt{\\ +=\\ avg\\_l.dt\\ *\\ (avg\\_l.gain\\ *\\ avg\\_m\\ -\\ avg\\_l);\\ avg\\_l\\ =\\ MAX(avg\\_l,\\ min)}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      long-term running average --- this is computed just once per\n      learning trial, \\emph{not every cycle} like the ones above ---\n      gain = 2.5 (or 1.5 in some cases works better), min = .2, dt = .1\n      by default\n    \\item\n      same basic exponential running average as above equations\n    \\end{itemize}\n  \\item\n    \\textbf{\\texttt{avg\\_s\\_eff}}\\texttt{\\ =\\ m\\_in\\_s\\ *\\ avg\\_m\\ +\\ (1\\ -\\ m\\_in\\_s)\\ *\\ avg\\_s}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      mix in some of the medium-term factor into the short-term factor\n      --- this is important for ensuring that when neuron turns off in\n      the plus phase (short term), that enough trace of earlier\n      minus-phase activation remains to drive it into the LTD weight\n      decrease region --- m\\_in\\_s = .1 default.\n    \\item\n      this is now done at the unit level --- previously was done at the\n      connection level which is much less efficient!\n    \\end{itemize}\n  \\end{itemize}\n\\end{itemize}\n\n\\begin{itemize}\n  \\tightlist\n  \\item \\emph{Optional, on by default:} dynamic modulation of amount of\n    Hebbian learning, based on avg\\_l value and level of err in a given\n    layer --- these factors make a small (few percent) but reliable\n    difference in overall performance across various challenging tasks\n    --- they can readily be omitted in favor of a fixed avg\\_l\\_lrn\n    factor of around 0.0004 (with 0 for target layers --- it doesn't\n    make sense to have any Hebbian learning at output layers):\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      \\textbf{\\texttt{avg\\_l\\_lrn}}\\texttt{\\ =\\ avg\\_l.lrn\\_min\\ +\\ (avg\\_l\\ -\\ avg\\_l.min)\\ *\\ ((avg\\_l.lrn\\_max\\ -\\ avg\\_l.lrn\\_min)\\ /\\ avg\\_l.gain\\ -\\ avg\\_l.min))}\n\n      \\begin{itemize}\n      \\tightlist\n      \\item\n        learning strength factor for how much to learn based on avg\\_l\n        floating threshold --- this is dynamically modulated by\n        strength of avg\\_l itself, and this turns out to be critical\n        --- the amount of this learning increases as units are more\n        consistently active all the time (i.e., ``hog'' units).\n        avg\\_l.lrn\\_min = 0.0001, avg\\_l.lrn\\_max = 0.5. Note that this\n        depends on having a clear max to avg\\_l, which is an advantage\n        of the exponential running-average form above.\n      \\end{itemize}\n    \\item\n      \\textbf{\\texttt{avg\\_l\\_lrn}}\\texttt{\\ *=\\ MAX(1\\ -\\ cos\\_diff\\_avg,\\ 0.01)}\n\n      \\begin{itemize}\n      \\tightlist\n      \\item\n        also modulate by time-averaged cosine (normalized dot product)\n        between minus and plus phase activation states in given\n        receiving layer (cos\\_diff\\_avg), (time constant 100) --- if\n        error signals are small in a given layer, then Hebbian learning\n        should also be relatively weak so that it doesn't overpower it\n        --- and conversely, layers with higher levels of error signals\n        can handle (and benefit from) more Hebbian learning. The\n        MAX(0.01) factor ensures that there is a minimum level of .01\n        Hebbian (multiplying the previously-computed factor above). The\n        .01 * .05 factors give an upper-level value of .0005 to use for\n        a fixed constant avg\\_l\\_lrn value --- just slightly less than\n        this (.0004) seems to work best if not using these adaptive\n        factors.\n      \\end{itemize}\n    \\end{itemize}\n\\end{itemize}\n\n\\begin{itemize}\n\\tightlist\n\\item\n  \\textbf{Learning equation} (see LeabraConSpec.h for code) --- most of\n  these are intermediate variables used in computing final dwt value\n\n  \\begin{itemize}\n  \\tightlist\n  \\item\n    \\textbf{\\texttt{srs}}\\texttt{\\ =\\ ru-\\textgreater{}avg\\_s\\_eff\\ *\\ su-\\textgreater{}avg\\_s\\_eff}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      short-term sender-receiver co-product --- this is the\n      intracellular calcium from NMDA and other channels\n    \\end{itemize}\n  \\item\n    \\textbf{\\texttt{srm}}\\texttt{\\ =\\ ru-\\textgreater{}avg\\_m\\ *\\ su-\\textgreater{}avg\\_m}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      medium-term sender-receiver co-product --- this drives dynamic\n      threshold for error-driven learning\n    \\end{itemize}\n  \\item\n    \\textbf{\\texttt{dwt}}\\texttt{\\ +=\\ lrate\\ *\\ {[}\\ m\\_lrn\\ *\\ XCAL(srs,\\ srm)\\ +\\ ru-\\textgreater{}avg\\_l\\_lrn\\ *\\ XCAL(srs,\\ ru-\\textgreater{}avg\\_l){]}}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      weight change is sum of two factors: error-driven based on\n      medium-term threshold (srm), and BCM Hebbian based on long-term\n      threshold of the recv unit (ru-\\textgreater{}avg\\_l)\n    \\item\n      in earlier versions, the two factors were combined into a single\n      threshold value, using normalized weighting factors --- this was\n      more elegant, but by separating the two apart, we allow the\n      hebbian component to use the full range of the XCAL function (as\n      compared to the relatively small avg\\_l\\_lrn factor applied\n      \\emph{inside} the threshold computation). By multiplying by\n      avg\\_l\\_lrn outside the XCAL equation, we get the desired contrast\n      enhancement property of the XCAL function, where values close to\n      the threshold are pushed either higher (above threshold) or lower\n      (below threshold) most strongly, and values further away are less\n      strongly impacted.\n    \\item\n      m\\_lrn is a constant and is typically 1.0 when error-driven\n      learning is employed (but can be set to 0 to have a completely\n      Hebbian model).\n    \\item\n      XCAL is the ``check mark'' linearized BCM-style learning function\n      (see figure) that was derived from the Urakubo Et Al (2008) STDP\n      model, as described in more detail in the CCN textbook:\n      \\url{http://ccnbook.colorado.edu}\n    \\item\n      \\texttt{XCAL(x,\\ th)\\ =\\ (x\\ \\textless{}\\ d\\_thr)\\ ?\\ 0\\ :\\ (x\\ \\textgreater{}\\ th\\ *\\ d\\_rev)\\ ?\\ (x\\ -\\ th)\\ :\\ (-x\\ *\\ ((1-d\\_rev)/d\\_rev))}\n    \\item\n      d\\_thr = 0.0001, d\\_rev = 0.1 defaults\n    \\item\n      x ? y : z terminology is C syntax for: if x is true, then y, else\n      z\n    \\end{itemize}\n  \\end{itemize}\n\\end{itemize}\n\n\\begin{itemize}\n\\tightlist\n\\item\n  \\textbf{Momentum} --- as of version 8.2.0, momentum is turned on by\n  default, and has significant benefits for preventing hog units by\n  driving more rapid specialization and convergence on promising error\n  gradients.\n\n  \\begin{itemize}\n  \\tightlist\n  \\item\n    \\textbf{\\texttt{dwavg}}\\texttt{\\ =\\ MAX(dwavg\\_dt\\_c\\ *\\ dwavg,\\ ABS(dwt))}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      increment the running-average weight change magnitude (dwavg),\n      using abs (L1 norm) instead of squaring (L2 norm), and with a\n      small amount of decay: dwavg\\_dt\\_c = 1 - .001 --- software uses\n      dwavg\\_tau = 1000 as a time-constant of this decay:\n      \\texttt{dwavg\\_dt\\_c\\ =\\ 1\\ -\\ 1/dwavg\\_tau}.\n    \\end{itemize}\n  \\item\n    \\textbf{\\texttt{moment}}\\texttt{\\ =\\ m\\_dt\\_c\\ *\\ moment\\ +\\ dwt}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      increment momentum from new weight change ---\n      \\texttt{m\\_dt\\_c\\ =\\ 1\\ -\\ 1/m\\_tau} where m\\_tau = 20 trial time\n      constant for momentum integration by default, which works best\n      (i.e., m\\_dt\\_c = .95 --- .9 (m\\_tau = 10) is a\n      traditionally-used momentum value that also works fine but .95\n      (m\\_tau = 20) works better for most cases.\n    \\end{itemize}\n  \\item\n    \\texttt{if(dwavg\\ !=\\ 0)\\ dwt\\ =\\ moment\\ /\\ MAX(dwavg,\\ norm\\_min);\\ else\\ dwt\\ =\\ moment}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      set the weight change used by following weight update equation to\n      use momentum, normalized by dwavg if available (nonzero) --- this\n      normalization is used in RMSProp, ADAM, and other related\n      algorithms.\n    \\end{itemize}\n  \\end{itemize}\n\\end{itemize}\n\n\\begin{itemize}\n\\tightlist\n\\item\n  \\textbf{Weight update equation} (see LeabraConSpec.h for code) (see\n  below for alternative version using differential fast vs. slow\n  weights, not used by default)\n\n  \\begin{itemize}\n  \\tightlist\n  \\item\n    The \\textbf{fwt} value here is the linear, non-contrast enhanced\n    version of the weight value, while \\textbf{wt} is the sigmoidal\n    contrast-enhanced version, which is used for sending netinput to\n    other neurons. One can compute fwt from wt and vice-versa, but\n    numerical errors can accumulate in going back-and forth more than\n    necessary, and it is generally faster to just store these two weight\n    values (and they are needed for the slow vs. fast weights version\n    show below).\n  \\item\n    \\texttt{dwt\\ *=\\ (dwt\\ \\textgreater{}\\ 0)\\ ?\\ (1-fwt)\\ :\\ fwt}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      soft weight bounding --- weight increases exponentially\n      decelerate toward upper bound of 1, and decreases toward lower\n      bound of 0. based on linear, non-contrast enhanced fwt weights.\n    \\end{itemize}\n  \\item\n    \\textbf{\\texttt{fwt}}\\texttt{\\ +=\\ dwt}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      increment the linear weights with the bounded dwt term\n    \\end{itemize}\n  \\item\n    \\textbf{\\texttt{wt}}\\texttt{\\ =\\ SIG(fwt)}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      new weight value is sigmoidal contrast enhanced version of fast\n      weight\n    \\item\n      \\texttt{SIG(w)\\ =\\ 1\\ /\\ (1\\ +\\ (off\\ *\\ (1-w)/w)\\^{}gain)}\n    \\end{itemize}\n  \\item\n    \\textbf{\\texttt{dwt}}\\texttt{\\ =\\ 0}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      reset weight changes now that they have been applied.\n    \\end{itemize}\n  \\end{itemize}\n\\end{itemize}\n\n\\begin{itemize}\n\\tightlist\n\\item\n   \\emph{Optional, on by default:} \\textbf{Weight Balance} --- this option attempts to\n  maintain more balanced weights across units, to prevent some units\n  from hogging the representational space, by changing the rates of\n  weight increase and decrease in the soft weight bounding function, as\n  a function of the average receiving weights:\n\n  \\begin{itemize}\n  \\tightlist\n  \\item\n    \\texttt{dwt\\ *=\\ (dwt\\ \\textgreater{}\\ 0)\\ ?\\ wb\\_inc\\ *\\ (1-fwt)\\ :\\ wb\\_dec\\ *\\ fwt}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      wb\\_inc = weight increase modulator, and wb\\_dec = weight decrease\n      modulator (when these are both 1, this is same as standard, and\n      this is the default value of these factors)\n    \\end{itemize}\n  \\item\n    \\texttt{wt\\_avg\\ =\\ }\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      average of all the receiving weights --- computed \\emph{per\n      projection} (corresponding to a dendritic branch perhaps)\n    \\end{itemize}\n  \\item\n    \\texttt{if\\ (wt\\_avg\\ \\textgreater{}\\ hi\\_thr)\\ then\\ wbi\\ =\\ gain\\ *\\ (wt\\_avg\\ -\\ hi\\_thr);\\ wb\\_inc\\ =\\ 1\\ -\\ wbi;\\ wb\\_dec\\ =\\ 1\\ +\\ wbi}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      If the average weights are higher than a high threshold (hi\\_thr =\n      .4 default) then the increase factor wb\\_inc is reduced, and the\n      decrease factor wb\\_dec is increased, by a factor wbi that is\n      determined by how far above the threshold the average is. Thus,\n      the higher the weights get, the less quickly they can increase,\n      and the more quickly they decrease, pushing them back into\n      balance.\n    \\end{itemize}\n  \\item\n    \\texttt{if\\ (wt\\_avg\\ \\textless{}\\ lo\\_thr)\\ then\\ wbd\\ =\\ gain\\ *\\ (wt\\_avg\\ -\\ lo\\_thr);\\ wb\\_inc\\ =\\ 1\\ -\\ wbd;\\ wb\\_dec\\ =\\ 1\\ +\\ wbd}\n\n    \\begin{itemize}\n    \\tightlist\n    \\item\n      This is the symmetric version for case when weight averages are\n      below a low threshold (lo\\_thr = .2), and the weight balance\n      factors go in the opposite direction (wbd is negative), causing\n      weight increases to be favored over decreases.\n    \\end{itemize}\n  \\item\n    The hi\\_thr and lo\\_thr parameters are specified in terms of a\n    target weight average value \\texttt{trg\\ =\\ .3} with a threshold\n    \\texttt{thr=.1} around that target value, with these defaults\n    producing the default .4 and .2 hi and lo thresholds respectively.\n  \\item\n    A key feature of this mechanism is that it does not change the sign\n    of any weight changes, including not causing weights to change that\n    are otherwise not changing due to the learning rule. This is not\n    true of an alternative mechanism that has been used in various\n    models, which normalizes the total weight value by subtracting the\n    average. Overall this weight balance mechanism is important for\n    larger networks on harder tasks, where the hogging problem can be a\n    significant problem.\n  \\end{itemize}\n\\end{itemize}\n\n%%% Local Variables: \n%%% mode: latex\n%%% TeX-master: \"deep_leabra\"\n%%% End: \n", "meta": {"hexsha": "8c7a9ef0fd9643a3843d7566de74af1d192c0f42", "size": 27817, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "papers/psyrev/appendix.tex", "max_stars_repo_name": "ccnlab/deep-obj-cat", "max_stars_repo_head_hexsha": "8989ae654c8d0e2e142d28e4190d6d0938251191", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-03T04:57:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-03T04:57:52.000Z", "max_issues_repo_path": "papers/psyrev/appendix.tex", "max_issues_repo_name": "ccnlab/deep-obj-cat", "max_issues_repo_head_hexsha": "8989ae654c8d0e2e142d28e4190d6d0938251191", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "papers/psyrev/appendix.tex", "max_forks_repo_name": "ccnlab/deep-obj-cat", "max_forks_repo_head_hexsha": "8989ae654c8d0e2e142d28e4190d6d0938251191", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6495388669, "max_line_length": 252, "alphanum_fraction": 0.674371787, "num_tokens": 8143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.3109634841071231}}
{"text": "\\documentclass[12pt]{article}\n\\usepackage{natbib}\n\\usepackage[]{hyperref}\n\\usepackage{bm}\n\\usepackage{amsfonts}\n\\usepackage{graphicx}\n\n\n\\oddsidemargin 0.0mm\n\\evensidemargin 0.0mm\n\\textwidth 160mm\n\\topmargin -10mm\n\\textheight 230mm\n% \\pagestyle{empty}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\newcommand{\\threej}[6]\n{ \\left(\\begin{array}{ccc}\n#1&#2&#3\\\\\n#4&#5&#6\n\\end{array}\\right) }\n\n\\newcommand{\\sixj}[6]\n{ \\left\\{\\begin{array}{ccc}\n#1&#2&#3\\\\\n#4&#5&#6\n\\end{array}\\right\\} }\n\n\\def\\separation {0.5cm}\n\\def\\non{\\nonumber \\\\}\n\\def\\DnuD     {\\hbox{$\\Delta\\nu_D$}}\n\\def\\Jbar     {\\hbox{$\\bar J$}}\n\\def\\j        {\\hbox{$\\jmath$}}\n\\def\\N        {\\hbox{$\\cal N$}}\n\\def\\Ie       {\\hbox{$I_e$}}\n\\def\\Ji       {\\hbox{$\\bar J^i_\\mathrm{ext}$}}\n\\def\\about    {\\hbox{$\\sim$}}\n\\def\\x        {\\hbox{$\\times$}}\n\\def\\half     {\\hbox{$1\\over2$}}\n\\def\\Ncr      {\\hbox{$N'_{\\rm cr}$}}\n\\def\\mic      {\\hbox{$\\mu$m}}\n\\def\\ion#1#2  {#1\\,{\\small {#2}} }\n\\def\\tot      {\\tau_t}\n\\def\\t(#1){\\tau^{#1}}\n\\def\\a(#1){\\alpha^{#1}}\n\\def\\H{\\textsc{Hazel}}\n\\def\\HM{\\textsc{P-Hazel}}\n\\def\\LVG      {\\texttt{LVG}}\n\\def\\slab     {\\texttt{slab}}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n% For generation of the HTML manual with tth:\n\\def\\tthdump#1{#1}      % For generating TeX source; ignored by tth\n% Redefine symbols problematic for the browser:\n%%tth:\\def\\ga{\\hbox{$>\\sim$}}\n%%tth:\\def\\la{\\hbox{$<\\sim$}}\n%%tth:\\def\\Mo{\\hbox{$M_o$}}\n%%tth:\\def\\Lo{\\hbox{$L_o$}}\n%%tth:\\def\\Mdot{\\hbox{$M^{dot}$}}\n%%tth:\\def\\Ivezic{Ivezic}\n\n%%tth:\\begin{html}<TITLE>User Manual for MOLPOP-CEP</TITLE>\\end{html}\n%%tth: This HTML file was generated from the TeX source by\n%%tth: the translator TTH, which uses symbol fonts.  These fonts are\n%%tth: not normally enabled for Netscape running under X, because of\n%%tth: the way Netscape groups its fonts. If your browser has problems\n%%tth: displaying the math symbols in this manual, an easy fix can be found\n%%tth: on the TTH website at\n%%tth:\\begin{html}<A HREF=\"http://hutchinson.belmont.ma.us/tth/Xfonts.html\">http://hutchinson.belmont.ma.us/tth/Xfonts.html</A>\\end{html}\n%%tth:\\begin{html}<HR>\\end{html}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\begin{document}\n\n\\title                  {\\sc User Manual for \\H\\ and \\HM\\footnote{\\H\\ (an acronym for HAnle and ZEeman Light) is one of the IAC computer\nprograms for the synthesis and inversion of Stokes profiles resulting from the joint action of the Hanle and Zeeman effects.}}\n\n\\author{ A. Asensio Ramos \\\\\n         Instituto de Astrof\\'{\\i}sica de Canarias\\\\\n         38205, La Laguna, Tenerife, Spain\\\\ \\\\\n%         J. Trujillo Bueno\\footnote{Consejo Superior de Investigaciones Cient\\'{\\i}ficas (Spain)}\\\\\n% \tInstituto de Astrof\\'{\\i}sica de Canarias\\\\\n%          38205, La Laguna, Tenerife, Spain\\\\ \\\\\n% \tE. Landi Degl'Innocenti \\\\\n%         Universit\\`a degli Studi di Firenze \\\\\n% \tDipartimento di Astronomia e Scienza dello Spazio\\\\\n% \tLargo Enrico Fermi 2, I-50125 Florence, Italy\n        \\\\[0.5in] \\today}\n\\date{}\n\\maketitle\n\n\\newpage\n\n\\tableofcontents\n\n\\newpage\n\n\\section*{Disclaimer}\n\nThis software is distributed ``as is'' and the authors do not take any responsability for\npossible errors derived from its use by others. Apply it with care and\nnever trust the output without a careful meditation. \\H\\ can be freely used\nprovided that its origin is properly acknowledged and the reference Asensio Ramos, \nTrujillo Bueno \\& Landi Degl'Innocenti (2008; ApJ 683, 542) is cited and acknowledged in any\npublication achieved with it. Before using \\H\\ we recommend the user to read carefully this\npaper and the previous one by Trujillo Bueno \\& Asensio Ramos (2007; ApJ 655, 642). Please, \nsend us bug reports, comments and suggestions of possible improvements.\nWe point out that \\H\\ will be improved over the years (e.g., by extending it to more\nrealistic radiative transfer problems), but it is now ready for a number of\ninteresting applications in solar and stellar physics.\n\n\n\\newpage\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Introduction}\n\n\\subsection{Description}\n\\H\\ (an acronym for HAnle and ZEeman Light) is a computer program for the synthesis and inversion of Stokes profiles caused by the\njoint action of atomic level polarization and the Hanle and Zeeman effects. It is\nbased on the quantum theory of spectral line polarization, which takes into account\nrigorously all the relevant physical mechanisms and ingredients: optical pumping,\natomic level polarization, level crossings and repulsions, Zeeman, Paschen-Back and\nHanle effects. The code is written in standard Fortran 90. Its parameters \nare passed using four configuration files that can be manually edited. These\nconfiguration files are heavily commented, so that their edition should \nbe an easy task. In any case, two front-ends coded in IDL are given as a part of the \ndistribution in order to facilitate a user-friendly execution of the program.\nA parallel version of the code using Message Passing Interface (MPI) is\nalso available. This manual considers both distributions.\n\n\\subsection{Credits}\nThe code has grown since the first version thanks to the suggestions of many people. We\nthank Rebecca Centeno Elliot, Yukio Katsukawa, Marian Mart\\'{\\i}nez Gonz\\'alez, Rafael Manso Sainz and Tom Schad\nfor their help on testing the code and proposing (and partially coding, in some cases) some of the\noptions of the code.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Uncompressing and compiling \\H}\n\n\\subsection{Serial version}\nThe package comes in a single compressed file \\texttt{hazel.tar.gz}. After\nunpacking with \\texttt{tar zxvf hazel.tar.gz}, the \\H\\ directory\nwill contain the following subdirectories:\n\n\\begin{enumerate}\n\\item\n{\\tt Source} contains the Fortran 90 sources and a makefile that can be used\nto build the binary file.\n\\item\n{\\tt Run} contains a directory tree structure with the appropriate configuration files\nto run the code in command line mode.\n\\item\n{\\tt Widget\\_Synth} contains all the files that are needed to run the IDL front-end\nfor the synthesis problem.\n\\item\n{\\tt Widget\\_Inv} contains all the files that are needed to run the IDL front-end\nfor the inversion problem.  \n\\item\n{\\tt IDL\\_routines} contains some IDL routines that are needed by the \nfront-ends.\n\\item\n{\\tt Manual} contains this manual. \n\\end{enumerate}\n\nThe code has been tested on Linux platforms using the Intel Fortran\nCompiler (\\texttt{ifort}) and the free GFortran compiler. The\nsource code is in the \\texttt{Source/} directory. The compilation is performed\nwith the supplied \\texttt{makefile}. It is quite simple and easy to modify, and\ncontains additional comments about compiling. The\ndefault compiler is the \\texttt{ifort}, although you can use any other\ncompiler through the variable \\texttt{COMPILER}.\nIn order to obtain the executable file, just type:\n\\begin{verbatim}       \n       make all\n\\end{verbatim}\nAfter compiling and linking, the executable is copied to the \\H\\ \\texttt{Run/},\n\\texttt{Widget\\_Synth/} and \\texttt{Widget\\_Inv/} directories. Running the\nprogram in the \\texttt{Run/} directory should produce the correct output \ndepending on the exact form of the input files.\n\nThe generated object and module files can be cleaned typing:\n\\begin{verbatim}\n       make clean\n\\end{verbatim}\n\n\\subsection{Parallel version}\nThe package also decompresses the \\HM\\ directory tree that\nwill contain the following subdirectories:\n\n\\begin{enumerate}\n\\item\n{\\tt SourceMPI} contains the Fortran 90 sources and a makefile that can be used\nto build the binary file.\n\\item\n{\\tt RunMPI} contains a directory tree structure with the appropriate configuration files\nto run the code in command line mode.\n\\end{enumerate}\n\nThe source code is in the \\texttt{SourceMPI/} directory. The compilation depends\non the precompiled library NetCDF\\footnote{\\texttt{http://www.unidata.ucar.edu/software/netcdf/}}\nfor reading and writing output files. NetCDF is a standard for platform independent\nbinary files that you need to have installed in your system. The compilation is performed\nwith the supplied \\texttt{makefile}. It is quite simple and easy to modify, and\ncontains additional comments about compiling. The\ndefault compiler is \\texttt{mpif90}, although you can use any other\ncompiler through the variable \\texttt{COMPILER}.\nThe variables \\texttt{NETCDF\\_INCLUDE} and \\texttt{NETCDF\\_LIB} have to point to the\n\\texttt{include} and \\texttt{lib} directories of the NetCDF distribution.\n\nThe code makes use of the MPI package for parallelization, so it has\nto be installed on your system. \nIn order to obtain the executable file (for instance for the Intel compiler), just type:\n\\begin{verbatim}\n       make -f makefile.Intel\n\\end{verbatim}\nModify the \\texttt{makefile} to point the variables to the correct libraries and include\nfiles.\nAfter compiling and linking, the executable is copied to the \\HM\\ \\texttt{RunMPI/} \ndirectory, where the code is run. Running the\nprogram in the \\texttt{RunMPI/} directory should produce the correct output \ndepending on the exact form of the input files.\n\nThe generated object and module files can be cleaned typing:\n\\begin{verbatim}\n       make clean\n\\end{verbatim}\n\nThe code is run from the \\texttt{RunMPI} directory. Use your MPI launcher to select\nthe number of processors. For example:\n\\begin{verbatim}\nmpiexec -n 50 hazel_mpi config_inversion.dat 2000 5000\n\\end{verbatim}\nThe code admits up to three command line parameters:\n\\begin{itemize}\n\\item Filename with the main configuration file.\n\\item Starting pixel of the inversion. This is used if you want to rerun the inversion of\nsome pixels.\n\\item Final pixel of the inversion. This is used if you want to rerun the inversion of\nsome pixels.\n\\end{itemize}\nSee \\S\\ref{sec:phazel_files} for details on the input files.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{New input file}\nIn previous versions of the code, the code was controlled with four configuration files. The updated\nversion of the code is now controlled by one human-readable configuration file. The code can still be\nrun using the old configuration files but this option will be discontinued in the future so it is \nadvisable to to the shift to this configuration file. In order to use this option, you need\nto have the \\texttt{configparser} package installed in your system. It can be downloaded from \n\\texttt{http://www.voidspace.org.uk/python/configobj.html}.\nThe serial code is now run using:\n\\begin{verbatim}\n./run.py conf.ini\n\\end{verbatim}\nand the parallel code is run with\n\\begin{verbatim}\n./run.py conf.ini nProcessors\n\\end{verbatim}\n\nAn example of the file, that is self-explanatory, is:\n\\begin{verbatim}\n# Hazel configuration File\n\n#####################\n# General information\n#####################\n\n[Files]\nInput model file = 'ATOMS/helium.mod'\nFile with observations = 'OBSERVATION/test_2comp.prof'\nFile with inverted profiles = 'test.inversion'\nFile with inverted parameters = 'test.parameters'\n\n[Working mode]\nAction = 'inversion'    \t\t\t\t\t# 'synthesis' or 'inversion'\nVerbose = no\nLinear system solver = 'LU'       \t\t\t# 'LU' or 'CG'\nStopping volume for DIRECT = 0.001\n\n[General parameters]\nSynthesis mode = 'exact'   \t\t\t\t\t# 'thin' or 'exact'\nInclude stimulated emission = yes\nInclude magnetic field  = yes\nInclude Paschen-Back effect = yes\nInclude atomic level polarization = yes\nInclude magneto-optical effects in the RT = yes\nInclude stimulated emission in the RT = yes\nMultiplet = 10830     \t\t\t\t\t\t# 10830, 5876, 7065, 3889 A\nLine-of-sight angles = 0.0, 0.0, 90.0    \t# theta, chi, gamma deg\nWavelength axis = -3.0, 2.5, 200     \t\t# Minimum, maximum and number of grid points\n\n#####################\n# Synthesis parameters\n#####################\n[Synthesis]\nNumber of slabs = '1'   \t\t\t\t\t# '1' -> single slab, '1+1' -> two slabs with same field, '1+1B' -> 2 slabs with different field, '2' -> two slabs added with a filling factor\nBoundary condition = 4.098e-5, 0.0, 0.0, 0.0      # I0, Q0, U0, V0\na = 0.0\nheight = 3.0    \t\t\t\t\t\t\t# Real height if positive, apparent height if negative arcsec\nff = 0.0\n\t[[Slab 1]]\n\tB = \t\t0.0\t\t\t# G\n\tthetaB = \t0.0\t\t\t# deg\n\tchiB = \t\t0.0\t\t\t# deg\n\tvdopp = \t8.0\t\t\t# km/s\n\ttau = \t\t1.0\n\tvmac = \t\t0.0\t\t\t# Positive is redshift km/s\n\tbeta = \t\t1.0\n\t[[Slab 2]]\n\tB = \t\t0.0\t\t\t# G\n\tthetaB = \t0.0\t\t\t# deg\n\tchiB = \t\t0.0\t\t\t# deg\n\tvdopp = \t0.0\t\t\t# km/s\n\ttau = \t\t0.0\n\tvmac = \t\t0.0\t\t\t# Positive is redshift km/s\n\tbeta = \t\t1.0\n\n#####################\n# Ranges for the DIRECT method [min, max]\n#####################\n[Ranges]\na = \t\t\t0,0.5\nff = \t\t\t0.0,1.0\n\t[[Slab 1]]\n\tB = \t\t800,1100\n\tthetaB = \t0,180\n\tchiB = \t\t0,180\n\tvdopp = \t2,12\n\ttau = \t\t0.1,2\n\tvmac = \t\t-5,5\n\tbeta = \t\t0.5,2\n\t[[Slab 2]]\n\tB = \t\t800,1100\n\tthetaB = \t0,180\n\tchiB = \t\t0,180\n\tvdopp = \t2,12\n\ttau = \t\t0.1,2\n\tvmac = \t\t-5,5\n\tbeta = \t\t0.5,2\n\t\n#####################\n# Parameters to invert\n#####################\n[Inversion]\nIterations in LM = 20\nNumber of cycles = 4\nInversion modes = 'DIRECT', 'LM', 'DIRECT', 'LM'        # 'DIRECT' for DIRECT algorithm and 'LM' for Levenberg-Marquardt\n\t[[Cycles]]\n\ta =    \t\t\t1, 1, 0, 0\n\tff =   \t\t\t0, 0, 0, 0\n\t\t[[[Slab 1]]]\n\t\tB = \t\t0, 0, 1, 1\n\t\tthetaB = \t0, 0, 1, 1\n\t\tchiB = \t\t0, 0, 1, 1\n\t\tvdopp = \t1, 1, 0, 0\n\t\ttau = \t\t1, 1, 0, 0\n\t\tvmac = \t\t1, 1, 0, 0\n\t\tbeta = \t\t0, 0, 0, 0\n\t\t[[[Slab 2]]]\n\t\tB = \t\t0, 0, 0, 0\n\t\tthetaB = \t0, 0, 0, 0\n\t\tchiB = \t\t0, 0, 0, 0\n\t\tvdopp = \t0, 0, 0, 0\n\t\ttau = \t\t0, 0, 0, 0\n\t\tvmac = \t\t0, 0, 0, 0\n\t\tbeta = \t\t0, 0, 0, 0\n\t[[Weights]]\n\t\tStokes I = \t1.0, 1.0, 1.0, 1.0\n\t\tStokes Q = \t0.0, 0.0, 1.0, 1.0\n\t\tStokes U = \t0.0, 0.0, 1.0, 1.0\n\t\tStokes V = \t0.0, 0.0, 1.0, 1.0\n\\end{verbatim}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Input files}\n\\H\\ is controlled via four configuration files. All configuration files are fully\ncommented, so that changing any parameter should be an easy task. In the following, we describe them step by step.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{\\texttt{config\\_inversion.dat}}\nThis file can be considered as the main configuration file and it is the only\none that has to have a fixed name. This file is used to indicate the names of the\ninput files, the names of the output files, verbosity level and to decide\nwhether \\H\\ is to be applied to work in synthesis or inversion mode. Using the example included\nin the present version of \\H, we analyze one by one all the inputs.\n\n\\begin{verbatim}\n# Input model file\n'ATOMS/helium.mod'\n\\end{verbatim}\nDefinition of the file with the atomic model. See \\S\\ref{sec:atomic_model} for an explanation of\nthe file format.\n\n\\begin{verbatim}\n# Initial parameters file\n'init_parameters.dat'\n\\end{verbatim}\nDefinition of the file with the initial parameters of the problem. The values of the\nparameters in this file are taken as initial values for the inversion or for\nthe synthesis. See \\S\\ref{sec:init_parameters} for a detailed description of\nthe file.\n\n\\begin{verbatim}\n# Range of parameters for the DIRECT method\n'direct_range.dat'\n\\end{verbatim}\nThis file is used to define the lower and upper limits of the intervals inside which the\nDIRECT method searches for the minimum of the $\\chi^2$ function. See \\S\\ref{sec:direct_range}\nfor details.\n\n\\begin{verbatim}\n# Output for the upper level rho^K_Q(J,J') in the vertical reference frame\n'ATOMIC_POL/vertical_upper.rho'\n\n# Output for the lower level rho^K_Q(J,J') in the vertical reference frame\n'ATOMIC_POL/vertical_lower.rho'\n\n# Output for the upper level rho^K_Q(J,J') in the mag. field reference frame\n'ATOMIC_POL/magnetic_upper.rho'\n\n# Output for the lower level rho^K_Q(J,J') in the mag. field reference frame\n'ATOMIC_POL/magnetic_lower.rho'\n\\end{verbatim}\nThe previous lines define the output files where the spherical tensor components of the\ndensity matrix are saved. Note that the code stores only the density matrix elements of the upper and\nlower level of the desired transition. The elements of the atomic density matrix depend on the chosen\nreference system, and the two most desired reference systems are the one in which the\nquantization axis is chosen along the solar local vertical direction and the one\nin which the quantization axis is chosen along the magnetic field vector.\n\n\\begin{verbatim}\n# Output absorption/emission coefficients\n'INVERTED/rtcoef.emer'\n\n# Output absorption/emission coefficients neglecting atomic polarization\n'INVERTED/rtcoef_noatompol.emer'\n\\end{verbatim}\nThe emission coefficients $\\epsilon_{I,Q,U,V}$, the absorption coefficients $\\eta_{I,Q,U,V}$ and the anomalous\ndispersion coefficients $\\rho_{Q,U,V}$ for each wavelength point are saved in these files. The first file includes\nthe effects of atomic level polarization, while the second one neglects its influence.\n\n\\begin{verbatim}\n# File with the observed profiles\n'OBSERVATION/test.prof'\n\\end{verbatim}\nWhen using the code in the inversion mode, this file is the one used for the input\nof the observed Stokes profiles. The format of this file depends on which version of\nthe code is used. For \\H, it is very simple. The first line\nindicates the number of wavelength points and the normalization (use 'cont' or 'peak'). Then, a table with nine columns gives the value\nof the wavelength shift with respect to the center of the multiplet, the Stokes vector\nat each wavelength normalized to the maximum intensity, and an estimation of the noise standard deviation at each wavelength\nnormalized to the maximum intensity. See the example file contained in the \\H\\ distribution for more details.\nNote that these lines have to be present in the input file even if \\H\\ is used in synthesis mode.\n\nWhen using \\HM, the input file is more complicated and is described in \\S\\ref{sec:phazel_files}.\n\n\\begin{verbatim}\n# File with the inverted profiles\n'test.inversion'\n\n# File with the parameters from the inversion\n'test.parameters'\n\\end{verbatim}\nThe final Stokes profiles resulting from the synthesis or inversion options is saved in\nthe file indicated in the first line. The format is the same as that explained for the \nfile containing the observation. When \\H\\ is run in inversion mode, the final inferred\nparameters of the model are saved in the file indicated in the second line.\nAgain, for \\HM\\ the output files are described in \\S\\ref{sec:phazel_files}.\n\n\\begin{verbatim}\n# File that sets the parameters to invert\n'invert_parameters.dat'\n\\end{verbatim}\nThis file defines which parameters to invert in the inversion mode, together with the\nalgorithm to be used in each cycle and the weight used for each Stokes parameter.\n\n\\begin{verbatim}\n# Verbose mode (0-> no, 1-> yes)\n0\n\\end{verbatim}\nFlag to connect or disconnect the verbose mode. For the inversion of Stokes profiles\naffected by atomic level polarization it is sometimes useful to turn\nthe verbose mode on for analyzing the process of the code while calculating.\n\n\\begin{verbatim}\n# Linear system solver (0-> LU, 1-> CG)\n0\n\\end{verbatim}\nThis flag is used to choose the algorithm that solves the linear system of statistical equilibrium\nequations. For relatively simple models, the LU decomposition does a very good job in terms\nof speed. If the number of unknowns (i.e., of $\\rho^K_Q(J,J')$ elements) turns out to be of the order of or larger than\n$10^3$, conjugate gradients (CG) methods are a much better option. We recommend to use the LU \ndecomposition when possible and move to the CG solution only when necessary. The CG solution\nare based on routines developed by Dr. Mark K. Seager from Lawrence Livermore National Lab.\n\n\\begin{verbatim}\n# Optically thin (0), slab no-MO (1), M-E (2), slab DELOPAR (3), \n                       simplified slab (4), exact slab (5)\n5\n\\end{verbatim}\nThis flag is used to choose the level of approximation for the solution of the radiative transfer\nequation. The meaning of each option is explained below in \\S\\ref{sec:radiative_transfer}.\n\n\\begin{verbatim}\n# Synthesis mode -> 0 , Inversion mode -> 1\n0\n\\end{verbatim}\nThis flag controls the working mode of the code (synthesis or inversion).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{\\texttt{init\\_parameters.dat}}\n\\label{sec:init_parameters}\nThis important file establishes the parameters\nof the model, together with the definition of the scattering geometry. It includes also\nflags to turn on or discard different physical mechanisms. In the synthesis mode, the values in\nthis file are used to carry out the synthesis. In the inversion mode, the values in \nthis file are chosen as initial conditions for the inversion for those parameters that\nare left free. For those that are left fixed, the code uses the values defined in this\nfile. We explain them step by step.\n\n\\begin{verbatim}\n# Include stimulated emission (0-> no, 1-> yes)\n1\n\\end{verbatim}\nThis flag is used to take into account or discard the effect of stimulated emission in the emergent\nStokes profiles. Although stimulated emission is negligible for most solar \nit can be of importance for very strong radiation \nfields. We recommend to use always 1 since the computational time is barely affected by\nthis flag.\n\n\\begin{verbatim}\n# Include magnetic field (0-> no, 1-> yes)\n1\n\\end{verbatim}\nThis flag is used to slightly reduce the computational work for the non-magnetic case because,\nif set to zero, the magnetic kernel [see Eq. (\\ref{eq:see})] is not calculated.\n\n\\begin{verbatim}\n# Include depolarization rates (0-> no, 1-> yes)\n0\n\n# Value of delta if depol. rates are included (not used if prev. value = 0)\n1.d14\n\\end{verbatim}\nIn the present version of \\H\\ it is possible to include the effect of depolarizing collisions only in the ground\nlevel of the atomic system. In case the effect of collisions is to be accounted for, set \nthe first parameter to 1 and give the collisional\nrate in the next parameter in units of s$^{-1}$.\n\n\\begin{verbatim}\n# Include Paschen-Back effect (0-> no, 1-> yes)\n1\n\\end{verbatim}\nThe effect of a magnetic field on the energy levels of the atomic system can be calculated\nunder the approximation of the linear Zeeman effect or in the general case of \nthe intermediate Paschen-Back effect. If this flag is set to 0, the approximation of the linear Zeeman \neffect is used and no perturbations between different $J$ levels of a term are taken into\naccount. If the flag is set to 1, the general theory of the Paschen-Back effect is used to\ncalculate the wavelength positions and the strengths of the $\\pi$ and $\\sigma$ components. \nThe difference in the computational work between both approaches is rather small.\n\n\\begin{verbatim}\n# Number of slabs (1-> 1 slab, 2-> 2 slabs with same B, \n3-> 2 slabs with different B, -2 -> 2 slabs with filling factor)\n\\end{verbatim}\n\\H\\ can be used using one slab (option 1) of constant physical properties or two (options 2 and 3 and -2). The\ndifference between options 2 and 3 is that option 2 considers both slabs to have exactly the\nsame field while option 3 considers two different fields. As a consequence, the computing time\nis smaller in option 2. In both options, the second slab is placed in front of the first one, so that\nthe boundary condition of the second slab is the emergent radiation from the first. In option -2, the\nradiation emerging from both slabs is added weighted with a filling factor, which is indicated below.\n\n\\begin{verbatim}\n# Magnetic field strength [G], thetaB [degrees], chiB [degrees]\n0.3d0 90.d0 90.d0\n\\end{verbatim}\nThe magnetic field vector is defined here. The strength in G and the inclination and\nazimuth angles in degrees define the magnetic field vector. The angles are defined with respect to the \nvertical direction in the atmosphere, as shown in Fig. \\ref{fig:geometry}. Note that, if\nthe azimuth of the field is set to 999, the random azimuth solution is obtained following\nthe strategy explained in Appendix C of \\cite{belluzzi07}.\nIf two slabs are used (setting option 3 or -2 above), put the two field vectors next to each one in the format $(B,\\theta_B,\\chi_B)_1 (B,\\theta_B,\\chi_B)_2$.\n\n\\begin{verbatim}\n# Apparent height (if <0) or real height (if >0) of the atoms in arcsec\n3.d0\n\\end{verbatim}\nThe tensors $J^0_0$ and $J^2_0$ that quantify the mean intensity of the radiation field and its anisotropy\nare calculated assuming a standard solar center-to-limb variation (CLV) and taking into account \ngeometrical effects. This parameter\ngives the height at which the slab of atoms is placed with respect to the surface of the Sun.\n\n\\begin{small}\n\\begin{verbatim}\n# Optical depth of the slab in the maximum of I (slab) or strength of the line (ME)\n1.0d0\n\\end{verbatim}\n\\end{small}\nThis quantity is the optical depth of the slab at the wavelength position of the maximum absorption\nor emission in Stokes $I$. For example, for the 10830 \\AA\\ multiplet of He \\textsc{i}, this is the \nposition of the red blended component. If two slabs with option 2 or 3 are used, put the two optical depths together. If option -2 is\nused, then add the filling factor as a third number.\n\n\\begin{verbatim}\n# Source function increase\n1.d0\n\\end{verbatim}\nThe source function of the slab will be multiplied by this number. This is a way to generate\nlines in emission even when the slab is seen on the solar disk.\nIf two components (one after the other) are used, this number only modifies the source \nfunction of the second component. This allows us to simulate self-absorption in the code.\n\n\\begin{verbatim}\n# Boundary Stokes parameters (I0,Q0,U0,V0)\n4.098d-5 0.d0 0.d0 0.d0\n\\end{verbatim}\nBoundary conditions for the Stokes vector used in the solution of the radiative transfer equation.\nIf the radiation field is the photospheric continuum, the IDL routine \\texttt{IDL\\_routines/solar\\_field.pro}\ncan be used to return an estimation.\n\n\\begin{verbatim}\n# Transition where to compute the emergent Stokes profiles\n1\n\\end{verbatim}\nFrom the transitions defined in the atomic model, the code calculates the emergent Stokes profiles\nfor the chosen transition. For the moment, only one transition at a time is allowed. We plan to\nextend this to synthesize several lines.\n\n\\begin{verbatim}\n# Include atomic level polarization? (0-> no, 1-> yes)\n1\n\\end{verbatim}\nThe synthesis or inversion options can be used taking into account or neglecting the presence of \natomic level polarization. This flag controls it.\n\n\\begin{verbatim} \n# Observation angle with respect to the local solar vertical theta,chi,gamma [degrees]\n0.d0 0.d0 90.d0\n\\end{verbatim}\nThe line-of-sight direction is defined using the angles described\nin Fig. \\ref{fig:geometry}. All angles are given in degrees.\n\n\\begin{verbatim}\n# Wavelength axis: minimum, maximum and number of grid points\n-3.d0 2.5d0 200\n\\end{verbatim}\nIn case the code is run in synthesis mode, this line is used to set the lower and upper\nlimits (in cm$^{-1}$) of the wavelength axis. The last parameter gives the number of wavelength\npoints to be used. In the inversion mode, the wavelength axis is chosen automatically from \nthe observation and these numbers are overridden.\n\n\\begin{verbatim}\n# Line wavelength [A], Doppler velocity [km/s] and damping [a]\n10829.0911d0   6.5d0   0.d0\n\\end{verbatim}\nThis line is used to define the wavelength of the multiplet (wavelength of the \n$(L,S) \\to (L',S')$ transition), the Doppler width of the\nline in km s$^{-1}$ and the reduced damping constant.\nIf two slabs (through options 3 or -2) are used, add the Doppler width of the second component\nnext to the first one.\nConcerning the reduced damping constant, if its value is negative, it is computed using the natural\ndamping and using the Doppler broadening. The absolute value of the input value is used then as\nan enhancement factor (so you should use $-1$ is you want to use the natural width).\n\n\\begin{verbatim} \n# Macroscopic velocity [km/s] (>0 is a redshift)\n0.d0\n\\end{verbatim}\nThis defines the wavelength shift produced by the presence of a bulk motion of the plasma.\nNote that positive velocities imply redshifts. If two components (options 2, 3 or -2)\nare used, put the two bulk velocities.\n\n\\begin{verbatim} \n# Include magneto-optical effects in the RT\n1\n\\end{verbatim}\nIt is possible to include (1) or neglect (0) the influence of the anomalous dispersion coefficients $\\rho_{Q,U,V}$\nin the calculation of the emergent Stokes profiles.\n\n\\begin{verbatim}\n# Include stimulated emission in the RT\n1\n\\end{verbatim}\nThis flag controls whether we include (1) or neglect (0) the influence of the stimulated emission \nin the calculation of the emergent Stokes profiles.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{\\texttt{direct\\_range.dat}}\n\\label{sec:direct_range}\nThe DIRECT global optimization method is used to give a first estimation of the parameters from\nwhich the Levenberg-Marquardt method is applied to locate the minimum of the $\\chi^2$ surface.\nThe behavior of the DIRECT method is controlled with this file, in which we must specify\nthe upper and lower limits of the model parameters, together with details about the stopping\ncriterion. In the following, we describe all the options in detail.\n\n\\begin{verbatim}\n# Output file\n'direct.location'\n\\end{verbatim}\nThe DIRECT method tries to evaluate the merit function $\\chi^2$ as few times as\npossible. The code saves in this file the values of the parameters at which\nthe algorithm has carried out the evaluation of the merit function. This can\nbe useful for analyzing the presence of ambiguities. In this case, the method\nwill clearly mark the position of the possible solutions by evaluating the merit\nfunction more times in the surroundings of the compatible solutions.\nNote that this lines are absent on the \\HM\\ configuration file.\n\n\\begin{verbatim}\n# Maximum number of function evaluations (<0 -> don't use this criteria)\n-1\n\n# Reduction in the volume (<0 -> don't use this criteria, typically 0.01)\n0.001\n\\end{verbatim}\nThe previous two lines are used to indicate the stopping criterion for the\nDIRECT method. An early stop will probably give a first estimation of the \nsolution that is far from the final result. Letting the code run for many\niterations may degrade too much the computing time because of the poor\nlocal convergence properties of the DIRECT scheme. The first option permits\nthe user to stop after a fixed number of evaluations of the merit function.\nThe second option permits\nthe user to stop when the ratio between the hypervolume where\nthe global minimum is located and the original hypervolume is smaller than the\ngiven threshold. We have verified that 0.001 gives very good results.\nSetting one of the two parameters to values $< 0$ will disconnect it.\n\n\\begin{verbatim}\n# Magnetic field (0-Bmax)\n800.d0  1100.d0\n\n# thetab  (0 .. 180)\n30.d0  180.d0\n\n# chib (0 .. 180)\n-180.d0  0.d0\n\n# vdopp (0 .. 20)\n2.d0  7.d0\n\n# dtau (0 .. 5)\n0.d0  1.d0\n\n# delta_collision (0 .. 18)\n0.d0  18.d0\n\n# vmacro (-10 .. 10)\n-10.d0  10.d0\n\n# damping (0 .. 4)\n0.d0  4.d0\n\n# beta (0 .. 10)\n0.d0  1.d0\n\n# height (0 .. 100)\n0.d0  100.d0\n\n# dtau2 (0 .. 5)\n0.d0  2.d0\n\n# vmacro2 (-10 .. 10)\n25.d0  35.d0\n\n# Magnetic field 2 (0-Bmax)\n800.d0  1100.d0\n\n# thetab 2 (0 .. 180)\n30.d0  180.d0\n\n# chib 2 (0 .. 180)\n-180.d0  0.d0\n\n# vdopp 2 (0 .. 20)\n2.d0  12.d0\n\\end{verbatim}\nThe previous lines define the space of parameters where the DIRECT method will look for the\nglobal minimum.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{\\texttt{invert\\_parameters.dat}}\n\\label{sec:invert_parameters}\nThis file is used to set the behavior of the inversion mode: the structure of the inversion cycle,\nsetting the free and the fixed parameters.\n\n\\begin{verbatim}\n# Maximum number of iterations\n20\n\\end{verbatim}\nThis parameter sets the maximum number of Levenberg-Marquardt (LM) iterations to be carried out\nin each cycle. Sometimes the LM scheme stops before reaching the maximum number of iterations\nbecause the relative change in the parameters from one iteration to the next is below 10$^{-4}$.\n\n\\begin{verbatim}\n# Number of cycles\n2\n\\end{verbatim}\nThe optimal iteration scheme is composed of combinations of cycles. In the first cycle, the DIRECT method\nis used to give a first estimation of the solution. In the second cycle, the LM method is used to refine\nthe solution until arriving to the final one. This parameter sets the number of cycles used.\n\n\\begin{verbatim}\n# Invert the magnetic field strength\n1 1 1 1\n\n# Invert the magnetic field inclination\n1 1 1 1\n\n# Invert the magnetic field azimuth\n1 1 0 0\n\n# Invert the Doppler width\n0 0 0 0\n\n# Invert the optical depth or strength of the line\n0 0 0 0\n\n# Invert the D^2 of the lower level\n0 0 0 0\n\n# Invert the macroscopic velocity\n0 0 0 0\n\n# Invert the damping\n0 0 0 0\n\n# Invert the source function gradient\n0 0 0 0\n\n# Invert the height of the He atoms\n0 0 0 0\n\n# Invert the optical depth or strength of the line of component 2\n0 0 0 0\n\n# Invert the macroscopic velocity of component 2\n0 0 0 0\n\n# Invert the magnetic field strength of component 2\n0 0 1 1\n\n# Invert the magnetic field inclination of component 2\n0 0 1 1\n\n# Invert the magnetic field azimuth of component 2\n0 0 1 1\n\n# Invert the Doppler width of component 2\n0 0 0 0\n\\end{verbatim}\nDepending on the number of cycles, the previous lines define whether a parameter is inverted (setting a 1 in the\ncorresponding cycle) or kept fixed to the value given in the \\texttt{init\\_parameters.dat} file (setting a 0\nin the corresponding cycle). The number of 0s/1s in each line has to be larger or equal to the number of cycles.\n\n\\begin{verbatim}\n# Weights for Stokes I in each cycle\n1.d0 1.d0 1.d0 1.d0\n\n# Weights for Stokes Q in each cycle\n1.d0 1.d0 1.d0 1.d0\n\n# Weights for Stokes U in each cycle\n1.d0 1.d0 1.d0 1.d0\n\n# Weights for Stokes V in each cycle\n1.d0 1.d0 1.d0 1.d0\n\\end{verbatim}\nSince the inversion is based on the gradient descent minimization of the $\\chi^2$ merit function and not on\nsampling methods, it is important to modify sometimes the weight of each Stokes vector in order to\nincrease the sensitivity of the $\\chi^2$-function to some model parameters. The code allows to change the relative\nweight of each Stokes vector in each cycle.\n\n\\begin{verbatim}\n# Inversion modes (1-> LM, 2-> DIRECT, 3-> PIKAIA)\n2 1 2 1\n\\end{verbatim}\nThe optimization method used in each cycle is set in this line. Note that the scheme DIRECT+LM has been\nempirically proved to be quite optimal. The possibility to use genetic optimization based on the Pikaia\nalgorithm is still in a preliminary phase. However, the large number of function evaluations that any genetic\nalgorithm needs makes it difficult to beat the DIRECT+LM combination.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Atomic models}\n\\label{sec:atomic_model}\nAtomic models have to be defined in \\H\\ in order to carry out a calculation. This\nsection describes the model atom file in detail by using the example \\texttt{helium.mod}\nthat is included in the present version of \\H.\n\n\\begin{verbatim}\n 2\n 5\n\\end{verbatim}\nThe previous two numbers define the general properties of the atom.\nThe first line of the file is equal to $2S$, where $S$ is the value of the spin of the\nterms. In the example, $S=1$. At present, the code does not treat transitions between terms of different multiplicity which are,\notherwise, of reduced importance due to their small transition probability. The second\nline contains the number of terms included in the model atom. This example represents\nthe triplet system of He \\textsc{i} with the lowest five terms, 2s$^3$S, 3s$^3$S, 2p$^3$P, 3p$^3$P and 3d$^3$D\n\n\\begin{verbatim}\n 1        0\n                    0.00\n 2        2\n                    0.00\n                   -0.987913\n                   -1.064340\n 3        0\n                    0.00\n 4        2\n                    0.00\n                   -0.270647\n                   -0.292616\n 5        4\n                    0.00\n                   -0.044187\n                   -0.046722\n\\end{verbatim}\nThe previous lines define the term levels included in the model. The information for each term\nconsist of a line with an index (0,1,2,\\ldots) that is used just to label each term and\nthe value of $2L$, where $L$ is the value of the electronic orbital angular momentum. Then, for \neach term, we must supply a list containing the energy separation in cm$^{-1}$ between each $J$-level\nand the level with the smallest absolute value of $J$. In case only one value of $J$ is possible\nin the term, just put 0 in the energy difference.\n\n\\begin{verbatim}\n 4\n1    1    2    1.022d7    10829.0911    1.0000000    1.0000000    0.0000000\n2    1    4    9.478d6    3888.6046    0.2000000    1.0000000    0.0000000\n3    2    3    2.780d7    7065.7085    1.0000000    1.0000000    0.0000000\n4    2    5    7.060d7    5875.9663    1.0000000    1.0000000    0.0000000\n\\end{verbatim}\nFinally, the list of transitions has to be supplied. The first number indicates the number\nof radiative transitions included in the model. Then, the list contains the following \nnumbers for each transition: index number, index of lower level, index of upper level, Einstein\ncoefficient for spontaneous emission $A_{ul}$ of the transition, modification factor $f(\\bar{n})$,\nmodification factor $f(w)$ and value of $J^1_0/J^0_0$. The modification factors $f(\\bar{n})$ and\n$f(w)$ are multiplied by the mean number of photons per mode $\\bar{n}$ and the anisotropy factor $w$,\nrespectively. Since \\H\\ uses the value of $\\bar{n}$ and $w$ calculated from the tabulated solar CLV\nand taking into account geometrical effects,\nthese factors can be used to analyze the behavior of the emergent Stokes profiles when, for some\nreason, the anisotropy or the intensity of the radiation field is increased or decreased by an\narbitrary factor. Finally, if the radiation illuminating the atoms has non-zero net circular polarization,\nit is possible to include its effect in the statistical equilibrium equations by giving the value of \n$J^1_0/J^0_0$.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{figure}\n\\includegraphics[width=\\columnwidth]{f5.eps}\n\\caption{Screen dump of the graphical front-end used for the synthesis.\n\\label{fig:synthesis_GUI}}\n\\end{figure}\n\n\\section{Graphical front-ends}\nAlthough the code can be run in command line by modifying by hand the input files, \n\\H\\ contains also two user friendly front-ends (GUI) for the simple execution and\nanalysis of the results. Note that the directory \\texttt{IDL\\_routines} has to be\nin your IDL path.\n\n\\begin{figure}[!t]\n\\includegraphics[width=0.48\\columnwidth]{inv1.eps}%\n\\hspace{0.1cm}\n\\includegraphics[width=0.48\\columnwidth]{inv2.eps}\n\\includegraphics[width=0.48\\columnwidth]{inv3.eps}%\n\\hspace{0.5cm}\n\\includegraphics[width=0.48\\columnwidth]{inv4.eps}\n\\caption{Screen dump of the graphical front-end used for the inversion.\n\\label{fig:inversion_GUI}}\n\\end{figure}\n\n\n\\subsection{Synthesis}\nIt is placed in the directory \\texttt{Widget\\_Synth} and it is invoked with the following commands:\n\\begin{verbatim}\nIDL> .r hazel\nIDL> hazel \n\\end{verbatim}\nFigure \\ref{fig:synthesis_GUI} shows the GUI for the synthesis mode. All the parameters explained in\nthe previous sections (fundamentally those in \\S\\ref{sec:init_parameters}) are present in the\nGUI. All the parameters are very simple to modify (when changing numerical values in the\nGUI, always remember to press \\texttt{Return} to activate the change) and clicking on \\textbf{Calculate},\nthe window is updated with the new Stokes profiles.\nThe GUI also shows the value of the solar radiation field when the inclination of the line-of-sight\nand the wavelength of the multiplet is changed. The value (which can be introduced in the\nvalue of $I_0$ as a boundary condition) is given next to the height of the slab and\nindicated with the label ``Allen''. In case of crashes, the GUI can be restarted with the following\ncommand:\n\\begin{verbatim}\nIDL> .r hazel\nIDL> hazel, /reset\n\\end{verbatim}\n\n\\subsection{Inversion}\nIt is placed in the directory \\texttt{Widget\\_Inv} and it is invoked with the following commands:\n\\begin{verbatim}\nIDL> .r hazel_inv\nIDL> hazel_inv\n\\end{verbatim}\nAgain, in case of crashes, the GUI can be restarted with the following command:\n\\begin{verbatim}\nIDL> .r hazel_inv\nIDL> hazel_inv, /reset\n\\end{verbatim}\nThe GUI for the inversion is more complex because of the large amount of parameters that have\nto be changed. For this reason, the GUI is composed of 4 pages, as indicated in \nFig. \\ref{fig:inversion_GUI}. \n\nThe first page is used to select the output file, together with the \natomic system and multiplet to be used. Finally, the button \\textbf{Run inversion} will call\n\\H\\ and update the state of the best model in the plot window.\n\nThe second page is used simply to load the file with the observed Stokes profile. A button\nis also available to plot the observed data.\n\nThe third page controls the behavior of the DIRECT algorithm. It is essentially a graphical\nrepresentation of the \\texttt{direct\\_range.dat} file.\n\nFinally, the fourth page controls the behavior of the cycles, the value of the fixed parameters,\nthe weights for each Stokes parameter and the level of physical realism introduced in the\nsimulation.\n\n\\section{\\HM\\ input/output files}\n\\label{sec:phazel_files}\nBoth input and output files for \\HM\\ are NetCDF files. \n\n\\subsection{Input files}\nThe input file constains the\nobservations and information about the observing position and boundary condition. The file\nconsists of the following variables:\n\\begin{itemize}\n\\item lambda: vector of size \\textit{nlambda} containing the wavelength axis with respect to the center of the multiplet.\n\\item map: array of size \\textit{(npixel,8,nlambda)} containing the Stokes vector $(I,Q,U,V)$ and\nthe associated standard deviation of the noise $(\\sigma_I,\\sigma_Q,\\sigma_U,\\sigma_V)$.\n\\item boundary: array of size \\textit{(npixel,4)} containing the boundary condition for every inverted pixel.\n\\item height: vector of size \\textit{npixel} which contains the height of the slabs for every pixel.\n\\item obs\\_theta: vector of size \\textit{npixel} which contains the observing angle $\\theta$ for every pixel.\n\\item obs\\_gamma: vector of size \\textit{npixel} which contains the observing angle $\\gamma$ that defines the positive\nreference for Stokes $Q$ for every pixel.\n\\item mask: array of size \\textit{nx,ny} which tells whether this pixel will be inverted.\n\\item normalization: variable indicating whether the profiles are normalized to the peak amplitude or the continuum of Stokes $I$.\n\\item pars: array of size \\textit{npixel,npars} which contains the initial value for the model parameters. These will be\nused to reinvert some pixels or, for instance, to refine the ambiguous solutions.\n\\end{itemize}\nThe routine \\texttt{gen\\_netcdf.pro} on the directory \\texttt{IDL\\_routines} and the \\texttt{genNetCDF.py} on \\texttt{pyRoutines} shows functions that\ngenerate such a file by passing all the variables as parameters.\nThe order of pars is the following, depending on the number of slabs:\n\\begin{itemize}\n\\item 1-component (vector of size 8): $B$, $\\theta_B$, $\\chi_B$, $\\tau$, $v_\\mathrm{dop}$, $a$, $v_\\mathrm{mac}$, $\\beta$\n\\item 2-component 1+1 with same field (vector of size 11): $B$, $\\theta_B$, $\\chi_B$, $\\tau_1$, $\\tau_2$, $v_\\mathrm{dop}$, $a$, $v_\\mathrm{mac1}$, $v_\\mathrm{mac2}$, $\\beta$, $\\beta_2$\n\\item 2-component 1+1 with different field (vector of size 15): $B_1$, $\\theta_{B1}$, $\\chi_{B1}$, $B_2$, $\\theta_{B2}$, $\\chi_{B2}$, $\\tau_1$, $\\tau_2$, $v_\\mathrm{dop}$, $v_\\mathrm{dop2}$, $a$, $v_\\mathrm{mac1}$, $v_\\mathrm{mac2}$, $\\beta$, $\\beta_2$\n\\item 2-component 2 with different field with filling factor (vector of size 16): $B_1$, $\\theta_{B1}$, $\\chi_{B1}$, $B_2$, $\\theta_{B2}$, $\\chi_{B2}$, $\\tau_1$, $\\tau_2$, $v_\\mathrm{dop}$, $v_\\mathrm{dop2}$, $a$, $v_\\mathrm{mac1}$, $v_\\mathrm{mac2}$, $\\mathrm{ff}$, $\\beta$, $\\beta_2$\n\\end{itemize}\n\n\n\\subsection{Output files}\nThe results of the inversion are saved on two files defined on the \\texttt{config\\_inversion.dat} configuration\nfile. The file with the inverted profiles contains the following variables:\n\\begin{itemize}\n\\item lambda: vector of size \\textit{nlambda} containing the wavelength axis with respect to the center of the multiplet.\n\\item map: array of size \\textit{(npixel,4,nlambda)} containing the synthetic Stokes vector $(I,Q,U,V)$ for every pixel.\n\\end{itemize}\nThe file with the inverted parameters contains the following variable:\n\\begin{itemize}\n\\item map: array of size \\textit{(npixel,ncolumns)} containing the parameters of the inversion. \n\\end{itemize}\nThe number of columns depends on the selected model:\n\\begin{itemize}\n\\item One-slab: nine columns with the vector $(B,\\theta_B,\\chi_B,h,\\tau,v_\\mathrm{th},a,v_\\mathrm{mac},\\beta)$.\n\\item Two-slab with same magnetic field: eleven columns with the vector \\\\ $(B,\\theta_B,\\chi_B,h,[\\tau]_1,[\\tau]_2,v_\\mathrm{th},a,[v_\\mathrm{mac}]_1,\n[v_\\mathrm{mac}]_2,\\beta)$.\n\\item Two-slab with different magnetic field: fifteen columns with the vector \\\\ $([B]_1,[\\theta_B]_1,[\\chi_B]_1,[B]_2,[\\theta_B]_2,[\\chi_B]_2,\nh,[\\tau]_1,[\\tau]_2,[v_\\mathrm{th}]_1,[v_\\mathrm{th}]_2,a,[v_\\mathrm{mac}]_1,[v_\\mathrm{mac}]_2,\\beta)$.\n\\end{itemize}\nThe file \\texttt{read\\_results.pro} on the \\texttt{RunMPI} directory shows how to read the\nfiles from IDL.\n\n\\subsection{Ambiguities}\nYou have to remember that the results of Hazel are potentially affected by ambiguities and you have\nto take them into account. There is an utility written in IDL that, given an inverted map, obtains\nall the other solutions which are ambiguous in the saturation regime. This can be called, including the\nappropriate paths and discarding the final \\texttt{.nc} extension, by:\n\\begin{verbatim}\nIDL> disamb, 'file_with_inversions', 'file_with_observations', angleObs\n\\end{verbatim}\nwhere \\texttt{angleObs} is the observation angle $\\theta$ (so that it is 90$^\\circ$ for an observation\nexactly at the limb.\nThis program can be called with the additional \\texttt{/gen\\_files\\_inversion}, which then generates\na set of observations, configuration files and a file to run \\HM. This is useful in case the line is not\nin the saturation regime. In this case, the ambiguous solutions that are found by the code are\nnot strictly valid and one should refine them with a final LM cycle in which $B$, $\\theta_B$ and $\\chi_B$\nare left free. The solution to the ambiguities in the saturation regime is shown in Section \\ref{sec:ambiguities}.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Calling Hazel from Python}\nWe have developed a wrapper to allow the user to call the synthesis routines of Hazel in Python.\nTo do so, just enter into the directory \\texttt{SourcePy} and type\n\\begin{verbatim}\npython setup.py build_ext --inplace\n\\end{verbatim}\nand a library \\texttt{pyhazel.so} will be generated (and also copied to the directory\n\\texttt{RunPy}. In this very same directory you can see the \\texttt{test.py} file that\nshows how to call the code to wrapper.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Basic Equations}\nWe consider a constant-property slab of atoms, located at a height\n$h$ above the \nvisible solar ``surface\", in the presence of a deterministic magnetic field of\narbitrary strength $B$, \ninclination $\\theta_B$ and azimuth $\\chi_B$ (see Fig. 1). The slab's optical\nthickness at the wavelength \nand line of sight under consideration is $\\tau$.\nWe assume that all the atoms inside this slab are illuminated from below by the\nphotospheric solar continuum radiation field, whose center-to-limb variation has\nbeen tabulated by \\cite{pierce00}. The ensuing anisotropic radiation pumping\nproduces population imbalances and quantum coherences between pairs of magnetic\nsublevels, even among those pertaining to the different $J$-levels of the\nadopted atomic model. This atomic level polarization and the Zeeman-induced\nwavelength shifts between the $\\pi$ ($\\Delta{M}=M_u-M_l=0$), $\\sigma_{\\rm blue}$\n($\\Delta{M}=+1$) and $\\sigma_{\\rm red}$ ($\\Delta{M}=-1$) transitions produce\npolarization in the emergent spectral line radiation.\n\nIn order to facilitate the understanding of the code, in \nthe following we summarize the basic equations which allow us to \ncalculate the spectral line polarization taking rigorously into account the \njoint action of atomic level polarization and the Hanle and Zeeman effects. To this end, we have applied the \nquantum theory of spectral line polarization, which is described in great detail \nin the monograph by \\cite{landi_landolfi04}. We have also applied several methods \nof solution of the Stokes-vector transfer equation, some of which can be \nconsidered as particular cases of the two general methods explained in \\S6 of \\cite{trujillo03}.\n\n\\begin{figure}\n\\includegraphics[width=\\columnwidth]{f1.eps}\n\\caption{The geometry for the scattering event. The $Z$-axis is placed along the vertical\nto the solar atmosphere. The magnetic field vector,\n$\\mathbf{B}$,\nis characterized by its modulus $B$, the inclination angle $\\theta_B$ and\nthe azimuth $\\chi_B$. The line-of-sight, indicated by the unit vector\n$\\mathbf{\\Omega}$,\nis characterized by the two angles $\\theta$ and $\\chi$.\nThe reference direction for Stokes $Q$ is defined by the vector $\\mathbf{e}_1$\non the plane\nperpendicular to the line-of-sight. This vector makes an angle $\\gamma$ with\nrespect to the plane formed by\nthe vertical and the line-of-sight. In the figures showing examples of the\nemergent Stokes profiles, our\nchoice for the positive reference direction for Stokes $Q$ is $\\gamma=90^\\circ$, unless otherwise stated.\nFor off-limb observations, we have $\\theta=90^\\circ$, while for observations\non the solar disk, we have $\\theta<90^\\circ$. Note also that $\\chi$ is generally taken to be $0^\\circ$.\n\\label{fig:geometry}}\n\\end{figure}\n\n\\subsection{The radiative transfer approach}\n\\label{sec:radiative_transfer}\nThe emergent Stokes vector $\\mathbf{I}(\\nu,\\mathbf{\\Omega})=(I,Q,U,V)^{\\dag}$\n(with $\\dag$=transpose, $\\nu$ the frequency and $\\mathbf{\\Omega}$ the unit vector indicating \nthe direction of propagation of the ray) is obtained by solving the radiative transfer equation\n\n\\begin{equation}\n\\frac{d}{ds}\\mathbf{I}(\\nu,\\mathbf{\\Omega}) =\n\\bm{\\epsilon}(\\nu,\\mathbf{\\Omega}) - \\mathbf{K}(\\nu,\\mathbf{\\Omega}) \n\\mathbf{I}(\\nu,\\mathbf{\\Omega}),\n\\label{eq:rad_transfer}\n\\end{equation}\nwhere $s$ is the geometrical distance along the ray under consideration,\n$\\bm{\\epsilon}(\\nu,\\mathbf{\\Omega})=({\\epsilon}_I,{\\epsilon}_Q,{\\epsilon\n}_U,{\\epsilon}_V)^{\\dag}$ is the emission vector and\n\\begin{equation}\n\\mathbf{K} = \\left( \\begin{array}{cccc}\n\\eta_I & \\eta_Q & \\eta_U & \\eta_V \\\\\n\\eta_Q & \\eta_I & \\rho_V & -\\rho_U \\\\\n\\eta_U & -\\rho_V & \\eta_I & \\rho_Q \\\\\n\\eta_V & \\rho_U & -\\rho_Q & \\eta_I\n\\end{array} \\right)\n\\label{eq:propagation}\n\\end{equation}\nis the propagation matrix. Alternatively, introducing the optical distance along the ray,  \n${\\rm d}{\\tau}=-{\\eta_I}{\\rm d}s$, one can write the Stokes-vector \ntransfer Eq. (\\ref{eq:rad_transfer}) in the following two ways:\n\n\\begin{itemize}\n\n\\item The first one, whose formal solution requires the use of the evolution operator introduced by \\cite{landi_landi85}, is \n\\begin{equation}\n{{d}\\over{d{\\tau}}}{\\bf I}\\,=\\,{\\bf K}^{*}\n{\\bf I}\\,-\\,{\\bf S}, \n\\label{eq:rad_transfer_peo}\n\\end{equation}\nwhere ${\\bf K}^{*}={\\bf K}/{\\eta_I}$ and ${\\bf S}=\\bm{\\epsilon}/{\\eta_I}$. \nThe formal solution of this equation can be seen in eq. (23) of \\cite{trujillo03}.\n\n\\item The second one, whose formal solution does not require the use of the above-mentioned evolution operator is \\citep[e.g.,][]{rees_delo89}\n\\begin{equation}\n{{d}\\over{d{\\tau}}}{\\bf I}\\,=\\,{\\bf I}\\,-\\,{\\bf S}_{\\rm eff},  \n\\label{eq:rad_transfer_delo}\n\\end{equation}\nwhere the effective source-function vector\n$\\,{\\bf S}_{\\rm eff}\\,=\\,{\\bf S}\\,-\\,\n{\\bf K}^{'}{\\bf I},\\,\\,\\,$ being $\\,{\\bf K}^{'}={\\bf K}^{*}-{\\bf 1}$\n(with $\\bf 1$ the unit matrix). The formal solution of this equation can be seen in eq. (26) of \\cite{trujillo03}.\n\n\\end{itemize}\n\nOnce\nthe coefficients $\\epsilon_I$ and $\\epsilon_X$ (with\n$X=Q,U,V$) of the emission vector \nand the coefficients $\\eta_I$, $\\eta_X$, and\n$\\rho_X$ of the $4\\times4$ propagation matrix are known \nat each point within the medium it is possible to solve formally Eq.\n(\\ref{eq:rad_transfer_peo}) or Eq.\n(\\ref{eq:rad_transfer_delo}) for\nobtaining the emergent Stokes profiles for any desired line of sight.\nOur computer program considers the following levels of sophistication for the solution of the radiative transfer equation: \n\n\\begin{itemize}\n\n\\item {\\em Numerical Solutions}.\nThe most general case, where the properties of the slab vary\nalong the ray path, has to be solved numerically. To this\nend, two efficient and accurate methods of solution of \nthe Stokes-vector transfer equation are those proposed by \\cite{trujillo03} (see his eqs. (24) and (27), respectively). The starting points for the development of these two numerical methods were Eq. (\\ref{eq:rad_transfer_peo}) and Eq. (\\ref{eq:rad_transfer_delo}), respectively. Both methods can be considered as generalizations, to the Stokes-vector transfer case, of the well-known short characteristics method for the solution of the standard (scalar) transfer equation. \n\n\\item {\\em Exact analytical solution of the problem of a constant-property slab including the magneto-optical terms of the propagation matrix}. For the general case of a constant-property slab of arbitrary optical thickness we actually have the following analytical solution, which can be easily obtained as a particular case of eq. (24) of \\cite{trujillo03}:\n\n\\begin{equation}\n{\\bf I}={\\rm e}^{-{\\mathbf{K}^{*}}\\tau}\\,{\\bf I}_{\\rm sun}\\,+\\,\\left[{\\mathbf{K}^{*}}\\right]^{-1}\\,\n\\left( \\mathbf{1} - {\\rm e}^{-{\\mathbf{K}^{*}}\\tau} \\right) \\,\\mathbf{S},\n\\label{eq:slab_peo}\n\\end{equation}\nwhere $\\mathbf{I}_{\\rm sun}$ is the Stokes\nvector that illuminates the slab's boundary that is most distant from the\nobserver. We point out that the exponential of the propagation \nmatrix ${\\mathbf{K}^{*}}$ has an analytical expression similar to eq. (8.23) in \\cite{landi_landolfi04}.\n\n\\item {\\em Approximate analytical solution of the problem of a constant-property slab including the magneto-optical terms of the propagation matrix}. An approximate analytical solution to the constant-property slab problem can be easily obtained as a particular case of eq. (27) of \\cite{trujillo03}:\n\n\\begin{equation}\n\\mathbf{I} = \\left[ \\mathbf{1}+\\Psi_0 \\mathbf{K}' \\right]^{-1} \\left[ \\left(\ne^{-\\tau} \\mathbf{1} - \\Psi_M \\mathbf{K}' \\right) \\mathbf{I}_{\\rm sun} +\n(\\Psi_M+\\Psi_0) \\mathbf{S} \\right],\n\\label{eq:slab_delo}\n\\end{equation}\nwhere the coefficients $\\Psi_M$ and $\\Psi_0$ depend only on the optical thickness of the slab at the frequency and line-of-sight under consideration, since their expressions are:\n\\begin{eqnarray}\n\\Psi_M&=& \\frac{1-e^{-\\tau}}{\\tau} - e^{-\\tau},\\nonumber \\\\\n\\Psi_0 &=&1-\\frac{1-e^{-\\tau}}{\\tau}.\n\\end{eqnarray}\n\nNote that Eq. (\\ref{eq:slab_delo}) for the emergent Stokes vector is the one used by \\cite{trujillo_asensio07} for \ninvestigating the impact of atomic level polarization on the Stokes profiles of the He {\\sc i} 10830 \\AA\\ multiplet. \nWe point out that, strictly speaking, it can be considered only as the exact analytical solution of the optically-thin \nconstant-property slab problem\\footnote{More precisely, when the optical thickness of the slab is small in comparison \nwith the eigenvalues of the matrix $\\mathbf{K}'$.}. The reason why Eq. (\\ref{eq:slab_delo}) is, in general, an approximate \nexpression for calculating the \nemergent Stokes vector is because  \nits derivation assumes that the Stokes vector within the slab varies linearly with the optical distance. However, it provides \na fairly good approximation to the emergent Stokes profiles (at least for all the problems we have investigated in this paper). \nMoreover, the results of fig. 2 of \\cite{trujillo_asensio07} remain also virtually the same when using instead the exact \nEq. (\\ref{eq:slab_peo}), which from a computational viewpoint is significantly less efficient than the approximate Eq. (\\ref{eq:slab_delo}).\n\n\\item {\\em Exact analytical solution of the problem of a constant-property slab when neglecting the second-order terms of the Stokes-vector transfer equation}. Simplified expressions for the emergent Stokes vector can be obtained when \n$\\epsilon_I{\\gg}\\epsilon_X$ and $\\eta_I{\\gg}(\\eta_X,\\rho_X)$, which justifies to neglect the second-order terms of Eq. (\\ref{eq:rad_transfer}). The resulting approximate formulae for the emergent Stokes parameters are given by eqs. (9) and (10) of \\cite{trujillo_asensio07}, which are identical to those used by \\cite{trujillo_merenda05} for modeling the Stokes profiles observed in solar chromospheric spicules. We point out that there is a typing error in the sentence that introduces such eqs. (9) and (10) in \\cite{trujillo_asensio07}, since they are obtained only when the above-mentioned second-order terms are neglected in Eq. (\\ref{eq:rad_transfer}), although it is true that there are no magneto-optical terms in the resulting equations. \n\n\\item {\\em Optically thin limit}. Finally, the most simple solution \nis obtained when taking the optically thin limit ($\\tau{\\ll}1$) in the equations reported in the previous point, which lead to the equations (11) and (12) of \\cite{trujillo_asensio07}. Note that if $\\mathbf{I}_{\\rm sun}=0$ (i.e., $I_0=X_0=0$), then such optically thin equations imply that ${X/I}\\,{\\approx}\\,{\\epsilon_X}/{\\epsilon_I}$. \n\n\\end{itemize}\n\nThe coefficients of the emission vector and of the propagation matrix\ndepend on the multipolar components, $\\rho^K_Q(J,J^{'})$, of the atomic density\nmatrix. Let us recall now the meaning of these physical quantities and how to\ncalculate them in the presence of an arbitrary magnetic field under given\nillumination conditions.  \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{The multipolar components of the atomic density matrix}\n\nWe quantify the atomic polarization of the atomic levels using the multipolar components \nof the atomic density matrix. We assume that the atom can be correctly described under \nthe framework of the $L$-$S$ coupling \\citep[e.g.,][]{condon_shortley35}. The  \ndifferent $J$-levels are grouped in terms with well defined values of the\nelectronic angular momentum $L$ and the spin $S$. We neglect the influence of\nhyperfine structure and assume that the energy\nseparation between the $J$-levels pertaining to \neach term is very small in comparison with the energy difference between\ndifferent terms. Therefore, we allow for coherences between\ndifferent \n$J$-levels pertaining to the same term but not between the $J$-levels\npertaining to \ndifferent terms. As a result, we can represent the atom under the \nformalism of the multi-term atom discussed by \\cite{landi_landolfi04}.\n\nIn the absence of magnetic fields the energy eigenvectors can be written using\nDirac's notation as $|\\beta L S J M\\rangle$, where\n$\\beta$ indicates a set of inner quantum numbers specifying the electronic\nconfiguration. In general, if a magnetic field of \narbitrary strength is present, the vectors $|\\beta L S J M\\rangle$ are no longer\neigenfunctions of the total Hamiltonian and $J$ is no longer a good quantum\nnumber. In this\ncase, the eigenfunctions of the full Hamiltonian can be written as the following\nlinear combination:\n\\begin{equation}\n\\label{eq:eigenfunctions_total_hamiltonian}\n|\\beta L S j M\\rangle = \\sum_J C_J^j(\\beta L S, M) |\\beta L S J M\\rangle,\n\\end{equation}\nwhere $j$ is a pseudo-quantum number which is used for labeling the energy\neigenstates belonging to the subspace corresponding to assigned values of the\nquantum numbers $\\beta$, $L$, $S$, and $M$, and where the coefficients $C_J^j$\ncan be chosen to be real. \n\nIn the presence of a magnetic field sufficiently weak so that the magnetic\nenergy is much smaller than the energy intervals between the $J$-levels, the energy eigenvectors are still\nof the form $|\\beta L S J M\\rangle$ ($C_J^j(\\beta L S, M) \\approx \\delta_{Jj}$), and the\nsplitting of the magnetic sublevels pertaining to each $J$-level is linear with the magnetic field strength. \nFor stronger magnetic fields, we enter the incomplete Paschen-Back effect regime in which the energy eigenvectors are\nof the general form given by Eq. (\\ref{eq:eigenfunctions_total_hamiltonian}),\nand the splitting among the various $M$-sublevels is no longer linear with the\nmagnetic strength. If the magnetic field strength is further increased we\neventually reach the so-called complete Paschen-Back effect regime, where the\nenergy eigenvectors are of the form $|L S M_L M_S\\rangle$ and each $L$-$S$ term\nsplits into a number of components, each of which corresponding to particular\nvalues of ($M_L+2M_S$).\n\nWithin the framework of the multi-term atom model the atomic polarization of the\nenergy levels is described with the\naid of the density matrix elements\n\\begin{equation}\n\\rho^{\\beta L S}(jM,j'M') = \\langle \\beta L S j M | \\rho | \\beta L S j' M'\\rangle,\n\\end{equation}\nwhere $\\rho$ is the atomic density matrix operator. Using the expression of the\neigenfunctions of the\ntotal Hamiltonian given by Eq. (\\ref{eq:eigenfunctions_total_hamiltonian}), the\ndensity matrix \nelements can be rewritten as:\n\\begin{equation}\n\\rho^{\\beta L S}(jM,j'M') = \\sum_{JJ'} C_J^j(\\beta L S, M) C_{J'}^{j'}(\\beta L\nS, M') \\rho^{\\beta L S}(JM,J'M'),\n\\end{equation}\nwhere $\\rho^{\\beta L S}(JM,J'M')$ are the density matrix elements on the basis of\nthe eigenvectors $| \\beta L S J M\\rangle$.\n\nFollowing \\cite{landi_landolfi04}, it is helpful to use the spherical\nstatistical tensor \nrepresentation, which is related to the previous one by the following linear\ncombination:\n\\begin{eqnarray}\n{^{\\beta LS}\\rho^K_Q(J,J')} &=& \\sum_{jj'MM'} C_J^j(\\beta L S, M)\nC_{J'}^{j'}(\\beta L S, M') \\nonumber \\\\\n&\\times& (-1)^{J-M} \\sqrt{2K+1} \\threej{J}{J'}{K}{M}{-M'}{-Q} \n\\rho^{\\beta L S}(jM,j'M'),\n\\end{eqnarray}\nwhere the 3-j symbol is defined as indicated by any\nsuitable textbook on Racah algebra.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Statistical equilibrium equations}\nIn order to obtain the\n${^{\\beta LS}\\rho^K_Q(J,J')}$ elements we have to solve the  \nstatistical equilibrium equations. These equations, written in a reference\nsystem in which \nthe quantization axis ($Z$) \nis directed along the\nmagnetic field vector and\nneglecting the \ninfluence of collisions, can be written as \\citep{landi_landolfi04}:\n\\begin{eqnarray}\n\\frac{d}{dt} {^{\\beta LS}\\rho^K_Q(J,J')} &=& -2\\pi \\mathrm{i} \\sum_{K' Q'}\n\\sum_{J'' J'''} N_{\\beta LS}(KQJJ',K'Q'J''J''') {^{\\beta LS}\\rho^{K'}_{Q'}(J'',J''')}\n\\nonumber \\\\\n&+& \\sum_{\\beta_\\ell L_\\ell K_\\ell Q_\\ell J_\\ell J_\\ell'} {^{\\beta_\\ell L_\\ell\nS}\\rho^{K_\\ell}_{Q_\\ell}(J_\\ell,J_\\ell')} \n\\mathbb{T}_A(\\beta L S K Q J J', \\beta_\\ell L_\\ell S K_\\ell Q_\\ell J_\\ell\nJ_\\ell') \\nonumber \\\\\n&+& \\sum_{\\beta_u L_u K_u Q_u J_u J_u'} {^{\\beta_u L_u\nS}\\rho^{K_u}_{Q_u}(J_u,J_u')} \n\\Big[ \\mathbb{T}_E(\\beta L S K Q J J', \\beta_u L_u S K_u Q_u J_u J_u') \\nonumber \\\\\n& &\\qquad \\qquad \\qquad \\qquad \\qquad + \\mathbb{T}_S(\\beta L S K Q\nJ J', \\beta_u L_u S K_u Q_u J_u J_u') \\Big] \\nonumber \\\\\n&-& \\sum_{K' Q' J'' J'''} {^{\\beta L S}\\rho^{K'}_{Q'}(J'',J''') } \\Big[\n\\mathbb{R}_A(\\beta L S K Q J J' K' Q' J'' J''') \\nonumber \\\\\n& & + \\mathbb{R}_E(\\beta L S K Q J J' K'\nQ' J'' J''') + \\mathbb{R}_S(\\beta L S K Q J J' K' Q' J'' J''') \\Big].\n\\label{eq:see}\n\\end{eqnarray}\nThe first term in the right hand side of Eq. (\\ref{eq:see}) takes into account\nthe \ninfluence of the magnetic field on the atomic level polarization. This term has \nits simplest expression in the chosen magnetic field\nreference frame \\citep[see eq. 7.41 of][]{landi_landolfi04}. \nIn any other reference system, a more complicated expression\narises.\nThe second, third and fourth terms account, respectively, for coherence transfer due\nto \nabsorption from lower levels ($\\mathbb{T}_A$), spontaneous emission from upper\nlevels \n($\\mathbb{T}_E$) and stimulated emission from upper levels ($\\mathbb{T}_S$).\nThe remaining terms account for the relaxation of coherences due to absorption to\nupper \nlevels ($\\mathbb{R}_A$), spontaneous emission to lower levels ($\\mathbb{R}_E$) \nand stimulated emission to lower levels ($\\mathbb{R}_S$), respectively. \n\nThe stimulated emission and absorption transfer and relaxation rates depend explicitly on \nthe radiation field properties \\citep[see eqs. 7.45 and 7.46 of][]{landi_landolfi04}.\nThe symmetry properties of the\nradiation \nfield are accounted for by the spherical components of the radiation field\ntensor:\n\n\\begin{equation}\nJ^K_Q(\\nu) = \\oint \\frac{d\\Omega}{4\\pi} \\sum_{i=0}^3\n\\mathcal{T}^K_Q(i,\\mathbf{\\Omega}) S_i(\\nu,\\mathbf{\\Omega}).\n\\label{eq:jkq}\n\\end{equation}\nThe quantities $\\mathcal{T}^K_Q(i,\\mathbf{\\Omega})$ are spherical tensors that\ndepend\non the reference frame and on the  \nray direction $\\mathbf{\\Omega}$. They are given by\n\\begin{equation}\n\\mathcal{T}^K_Q(i,\\mathbf{\\Omega}) = \\sum_P t^K_P(i) \\mathcal{D}^K_{PQ}(R'),\n\\label{eq:tkq}\n\\end{equation}\nwhere $R'$ is the rotation that carries the reference system defined by\nthe line-of-sight $\\mathbf{\\Omega}$ and by the polarization unit vectors $\\mathbf{e}_1$ and\n$\\mathbf{e}_2$ into the reference system of the magnetic field, \nwhile $\\mathcal{D}^K_{PQ}(R')$\nis the usual rotation matrix \\citep[e.g.,][]{edmonds60}.\nTable 5.6 in \\cite{landi_landolfi04} gives the\n$\\mathcal{T}^K_Q(i,\\mathbf{\\Omega})$ values for each Stokes parameter $S_i$ (with $S_0=I$, $S_1=Q$, $S_2=U$ and $S_3=V$).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Emission and absorption coefficients}\nOnce the multipolar components ${^{\\beta L S}\\rho^{K}_{Q}(J,J') }$ are known, the\ncoefficients $\\epsilon_I$ and $\\epsilon_X$ (with\n$X=Q,U,V$) of the emission vector \nand the coefficients $\\eta_I$, $\\eta_X$, and\n$\\rho_X$ of the propagation matrix\nfor a given transition between an upper \nterm $(\\beta L_u S)$ and an lower term $(\\beta L_\\ell S)$ can be\ncalculated with the expressions of \\S7.6.b in  \n\\cite{landi_landolfi04}. \nThese radiative transfer coefficients are proportional to the number density of \\ion{He}{1} atoms, $\\mathcal{N}$. Their defining expressions contain also the Voigt profile and the Faraday-Voigt profile \\citep[see \\S5.4 in][]{landi_landolfi04}, which involve the following parameters: $a$ (i.e., the reduced damping constant), $v_\\mathrm{th}$ (i.e., the velocity  that characterizes the thermal motions, which\nbroaden the line profiles), and $v_\\mathrm{mac}$ (i.e., the velocity of possible bulk motions in the plasma, which produce a Doppler shift). \n\nIt is important to emphasize that the expressions for \nthe emission and absorption coefficients and those of the statistical\nequilibrium equations are written in the reference system whose quantization\naxis is parallel to the magnetic field. The following equation indicates how to\nobtain the density matrix elements in a new reference system:\n\\begin{equation}\n\\left[ {^{\\beta L S}\\rho^{K}_{Q}(J,J') } \\right]_\\mathrm{new} = \\sum_{Q'} \\left[\n{^{\\beta L S}\\rho^{K}_{Q'}(J,J') } \\right]_\\mathrm{old}\n\\mathcal{D}^K_{Q' Q}(R)^*,\n\\end{equation}\nwhere $\\mathcal{D}^K_{Q' Q}(R)^*$ is the complex conjugate of the rotation matrix for the rotation $R$ that carries the \nold reference system into the new one.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Inversion}\nOur inversion strategy is based on the minimization of a merit function \nthat quantifies how well the Stokes profiles calculated in our atmospheric model\nreproduce the observed Stokes\nprofiles. To this end, we have \nchosen the standard $\\chi^2$--function, defined as:\n\\begin{equation}\n\\chi^2 = \\frac{1}{4N_\\lambda} \\sum_{i=1}^4 \\sum_{j=1}^{N_\\lambda} \n\\frac{\\left[S_i^\\mathrm{syn}(\\lambda_j)-S_i^\\mathrm{obs}(\\lambda_j) \\right]^2}{\n\\sigma_i^2(\\lambda_j)} ,\n\\end{equation}\nwhere $N_\\lambda$ is the number of wavelength points and $\\sigma_i^2(\\lambda_j)$ is the\nvariance associated to the $j$-th wavelength point of the $i$-th Stokes profiles. The minimization \nalgorithm tries to find the value of the parameters of our model that lead to\nsynthetic Stokes profiles $S_i^\\mathrm{syn}$ with the best possible fit to the \nobservations. \nFor our slab model, the number of\nparameters (number of dimensions of the $\\chi^2$ hypersurface) lies between 5\nand\n7, the maximum value corresponding to the optically thick case. \nThe magnetic field vector \n($B$, $\\theta_B$ and $\\chi_B$), the thermal velocity ($v_\\mathrm{th}$) and the\nmacroscopic velocity ($v_\\mathrm{mac}$) are always required. This set of\nparameters is enough \nfor the case of an optically thin slab. In order to account for radiative\ntransfer \neffects, we need to define the optical depth of the slab along its normal\ndirection and at a suitable\nreference wavelength (e.g., the central wavelength of the red blended component\nfor the \\ion{He}{1} 10830 \\AA\\ multiplet). In addition, \nwe may additionally need to include the damping parameter ($a$) of the Voigt profile if\nthe wings of the observed Stokes profiles cannot be fitted \nusing Gaussian line profiles.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Global Optimization techniques}\nIn order to avoid the possibility of getting trapped in a local minimum of the\n$\\chi^2$ hypersurface, global \noptimization methods have to be used. \nWe have chosen the DIRECT algorithm \n\\citep{Jones_DIRECT93}, whose name derives from one of its main \nfeatures: \\emph{di}viding \\emph{rect}angles. The idea is to recursively sample \nparts of the space of parameters, improving in each iteration the location of\nthe part of the space \nwhere the global minimum is potentially located. The decision algorithm is based\non the assumption that the function is Lipschitz continuous \\citep[see][for details]{Jones_DIRECT93}.\nThe method works very well in practice and can indeed find the minimum in \nfunctions that do not fulfill the condition of Lipschitz continuity. The reason\nis that the DIRECT algorithm does not require the explicit calculation of the \nLipschitz constant but it uses all possible values of such a constant to determine\nif a region of the parameter space should be broken into subregions because of\nits potential interest \\citep[see][for details]{Jones_DIRECT93}. \n\nSince the \nintensity profile is not very sensitive to\nthe presence of a magnetic field (at least for magnetic field \nstrengths of the order of or smaller than 1000 G), we have decided to estimate\nthe optical\nthickness of the slab, the thermal and the macroscopic velocity of the\nplasma and the damping constant by using only the Stokes $I$ profile, and then to determine the magnetic\nfield\nvector by using the polarization profiles. \nThe full inversion scheme\nbegins by applying the DIRECT method to obtain a first estimation of the\nindicated four\nparameters by using only Stokes $I$.  Afterwards, \nsome LM iterations are carried out to refine the initial values of the  \nmodel's parameters obtained in the previous step. Once the LM method \nhas converged, the inferred values of $v_\\mathrm{th}$, $v_\\mathrm{mac}$ \n(together with $a$ and $\\Delta \\tau$, when these are parameters of the model)\nare kept fixed in the next steps, \nin which the DIRECT method is used again for obtaining an initial approximation\nof \nthe magnetic field vector \n($B$,$\\theta_B$,$\\chi_B$). \nAccording to our experience,\nthe first estimate of the magnetic field vector given by the DIRECT algorithm \nis typically very close to the final solution. Nevertheless, some iterations of\nthe LM method are performed to refine the value of the magnetic field strength,\ninclination and azimuth.\nIn any case, although we have found very good results with this procedure, the\nspecific inversion scheme\nis fully configurable and can be tuned for specific problems.\n\nOur experience has proved that the following strategy is appropriate for inverting\nprominences. Two initial DIRECT+LM cycles with weights $(1,0,0,0)$ to\ninvert the thermodynamical parameters. Then, two DIRECT+LM cycles in which $B$, $\\theta_B$\nand $\\chi_B$ are left free with weights $(0,0.1,0.1,1)$ which tries to set the\ncorrect polarity of the field given by Stokes $V$. An additional LM cycle in which\nwe fit only $\\theta_B$ and $\\chi_B$ with the weights $(0,1,1,0.3)$ and a last\nLM cycle with weights $(0,0.3,0.3,1)$ leaving the full magnetic field vector free.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Convergence}\n\\label{sec:convergence}\nWe let the DIRECT algorithm\nlocate the global minimum in a region whose hypervolume is $V$. This hypervolume is \nobtained as the product of the length $d_i$ of each dimension associated with\neach of the $N$ parameters:\n\\begin{equation}\nV = \\prod_i^N d_i.\n\\end{equation}\nWhen the hypervolume decreases by a factor $f$ after the DIRECT algorithm\nhas discarded some of the hyperrectangles, its size along each dimension is\napproximately decreased by a factor $f^{1/N}$. \nIn order to end up with a small region\nwhere the global minimum is located, many subdivisions are \nnecessary, thus requiring many function evaluations. \n\nThe most time consuming part of any optimization procedure is the evaluation of\nthe merit function. The DIRECT algorithm needs only a reduced number of evaluations \nof the merit function to find\nthe region where the global minimum is located. For this reason, we have\nchosen it as the initialization part of the LM method. Since the initialization\npoint is close to the global minimum, the LM method, thanks to its quadratic behavior,\nrapidly converges to the minimum.\n\n\\subsection{Stopping criterium}\nWe have used two stopping criteria for the\nDIRECT algorithm. The first one is stopping when the ratio between the\nhypervolume where\nthe global minimum is located and the original hypervolume is smaller than a\ngiven threshold.\nThis method has been chosen when using the DIRECT \nalgorithm as an initialization for the LM method, giving very good results. The\nother good\noption, suggested by \\cite{Jones_DIRECT93}, is to stop after a fixed number of\nevaluations of the merit function.  \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Ambiguities in the Hanle effect in the saturation regime}\n\\label{sec:ambiguities}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nIn the saturation regime of the Hanle effect, Stokes $Q$ and $U$ are insensitive to the field\nstrength, but are sensitive to the geometry of the field. For a $J=0 \\to J=1$ transition, the linear\npolarization can be written as:\n\\begin{eqnarray}\nQ &=& \\frac{q}{2} \\left( 3 \\cos^2 \\theta_B-1 \\right) \\sin^2\\Theta_B \\cos 2\\Phi_B \\nonumber \\\\\nU &=& \\frac{q}{2} \\left( 3 \\cos^2 \\theta_B-1 \\right) \\sin^2\\Theta_B \\sin 2\\Phi_B.\n\\end{eqnarray}\nThese expressions contain a mixture of angles to make it clear that the polarization amplitude\ndepends on both the angle between the vertical and the magnetic field and between the magnetic\nfield and the line-of-sight (LOS).\n\nThe coordinates of the magnetic field vector $\\mathbf{B}$ in the reference system of the vertical\nand the reference system of the LOS are:\n\\begin{eqnarray}\n\\mathbf{B} &=& B \\left(\\sin \\theta_B \\cos \\phi_B \\mathbf{i}+\\sin \\theta_B \\sin \\phi_B \\mathbf{j}+\\cos \\theta_B \\mathbf{k} \\right) \\nonumber \\\\\n\\mathbf{B} &=& B \\left(\\sin \\Theta_B \\cos \\Phi_B \\mathbf{i}'+\\sin \\Theta_B \\sin \\Phi_B \\mathbf{j}'+\\cos \\Theta_B \\mathbf{k}' \\right),\n\\end{eqnarray}\nwhere the unit vectors are related by a simple rotation:\n\\begin{eqnarray}\n\\mathbf{i}' &=& \\cos \\theta \\mathbf{i} - \\sin \\theta \\mathbf{k} \\nonumber \\\\\n\\mathbf{k}' &=& \\sin \\theta \\mathbf{i} + \\cos \\theta \\mathbf{k}.\n\\end{eqnarray}\nIntroducing these relations on the expression for the magnetic field, we find that the\nfollowing has to be fulfilled, given that the magnetic field vector is the same in both reference systems:\n\\begin{eqnarray}\n\\sin \\theta_B \\cos \\phi_B &=& \\sin \\Theta_B \\cos \\Phi_B \\cos \\theta + \\cos \\Theta_B + \\sin \\theta \\nonumber \\\\\n\\sin \\theta_B \\sin \\phi_B &=& \\sin \\Theta_B \\sin \\Phi_B \\nonumber \\\\\n\\cos \\theta_B &=& \\cos \\Theta_B \\cos \\theta - \\sin \\Theta_B \\cos \\Phi_B \\sin \\theta.\n\\end{eqnarray}\nSolving the previous three equations in the two directions, we find the following transformations\nbetween the angles in the vertical reference system and the LOS reference system:\n\\begin{eqnarray}\n\\cos \\Theta_B &=& \\cos\\theta \\cos\\theta_B + \\sin\\theta \\sin\\theta_B \\cos\\phi_B \\nonumber \\\\\n\\sin \\Theta_B &=& +\\sqrt{1-\\cos^2\\Theta_B} \\nonumber \\\\\n\\cos \\Phi_B &=& \\frac{\\cos\\theta \\sin\\theta_B \\cos\\phi_B - \\cos\\theta_B \\sin\\theta}{\\sin \\Theta_B} \\nonumber \\\\\n\\sin \\Phi_B &=& \\frac{\\sin\\theta_B \\sin\\phi_B}{\\sin\\Theta_B}\n\\end{eqnarray}\nand\n\\begin{eqnarray}\n\\cos \\theta_B &=& \\cos\\theta \\cos\\Theta_B - \\sin\\theta \\sin\\Theta_B \\cos\\Phi_B \\nonumber \\\\\n\\sin \\theta_B &=& +\\sqrt{1-\\cos^2\\theta_B} \\nonumber \\\\\n\\cos \\phi_B &=& \\frac{\\cos\\theta \\sin\\Theta_B \\cos\\Phi_B + \\cos\\Theta_B \\sin\\theta}{\\sin \\theta_B} \\nonumber \\\\\n\\sin \\phi_B &=& \\frac{\\sin\\Theta_B \\sin\\Phi_B}{\\sin\\theta_B}.\n\\end{eqnarray}\nNote that, since $\\Theta_B \\in [0,\\pi]$, we can safely use the square root and take the positive value.\nIn order to transform from one reference system to the other, we can compute the\ninclination easily by inverting the sinus or the cosinus. However, the situation is different\nfor the azimuth, because the range of variation is $[-\\pi,\\pi]$. Therefore, one has to compute the \ncosinus and the sinus separately and the decide which is the correct quadrant fo the angle in terms\nof the signs of both quantities.\n\n% \\begin{center}\n% \\input{figure_geometry}\n% \\end{center}\n\nFour possible kinds of ambiguities can exist for the Stokes $Q$ and $U$ parameters. The idea is that $\\Phi_B$\ncan be modified and still obtain the same $Q$ and $U$ by properly adjusting the value of $\\Theta_B$. It is\nclear that, given that the term that can be used to compensate for the change in the azimuth on the LOS\nreference system is the same for Stokes $Q$ and $U$, we can only compensate for changes in the sign. Therefore,\nwe have the following potential ambiguities:\n\\begin{eqnarray}\n\\Phi_B' &=& \\Phi_B \\nonumber \\\\\n\\Phi_B' &=& \\Phi_B -\\pi/2 \\nonumber \\\\\n\\Phi_B' &=& \\Phi_B + \\pi/2 \\nonumber \\\\\n\\Phi_B' &=& \\Phi_B + \\pi.\n\\end{eqnarray}\nFor each case, we have to compute the value of $\\Theta_B'$ that keeps the value of $Q$ and $U$ unchanged. Therefore,\nonce we find a solution to the inversion problem in the form of the pair $(\\theta_B,\\phi_B)$, we can find\nthe remaining solutions in the saturation regime following the recipes that we present now. Remember that, unless\none knows the polarity of the field, or in other words, the sign $\\cos\\Theta_B$, the number of potential\nambiguous solutions is 8. If the polarity of the field is known, the number is typically reduced to 4 (or 2\nif no 90$^\\circ$ ambiguity is present).\n\n\\section{\\texorpdfstring{$\\Phi_B' = \\Phi_B$}{PhiB'=PhiB}}\nUnder this change, we have that\n\\begin{equation}\n\\cos 2\\Phi_B' = \\cos 2\\Phi_B, \\quad \\sin 2\\Phi_B' = \\sin 2\\Phi_B, \\quad \\cos \\Phi_B' = \\cos \\Phi_B, \\quad \\sin \\Phi_B' = \\sin \\Phi_B.\n\\end{equation}\nMaking use of the previous relations between the angles wrt to the vertical and the LOS, we have to solve the \nfollowing equation:\n\\begin{equation}\n\\left( 3 \\cos^2\\theta_B'-1 \\right) \\sin^2 \\Theta_B' = \\left( 3 \\cos^2\\theta_B-1 \\right) \\sin^2 \\Theta_B,\n\\end{equation}\nwhich can be written as:\n\\begin{equation}\n\\left[ 3 \\left( \\cos \\Theta_B' \\cos \\theta - \\sin\\theta \\sin\\Theta_B' \\cos\\Phi_B\\right)^2-1 \\right] \\sin^2 \\Theta_B' = \n\\left[ 3 \\left( \\cos \\Theta_B \\cos \\theta - \\sin\\theta \\sin\\Theta_B \\cos\\Phi_B\\right)^2-1 \\right] \\sin^2 \\Theta_B.\n\\end{equation}\nAfter some algebra and doing the substitution $t=\\sin\\Theta_B'$, we end up with the following equation to be\nsolved:\n\\begin{equation}\nA t^4 + Bt^2 + C t^3 \\sqrt{1-t^2} = K,\n\\end{equation}\nwhere\n\\begin{eqnarray}\nA &=& -3\\cos^2 \\theta + 3\\sin^2 \\theta \\cos^2 \\Phi_B \\nonumber \\\\\nB &=& 3\\cos^2 \\theta - 1 \\nonumber \\\\\nC &=& -6 \\cos\\theta \\sin\\theta \\cos \\Phi_B \\nonumber \\\\\nK &=& \\left[ 3 \\left( \\cos \\Theta_B \\cos \\theta - \\sin\\theta \\sin\\Theta_B \\cos\\Phi_B\\right)^2-1 \\right] \\sin^2 \\Theta_B.\n\\end{eqnarray}\nThe previous equation can be solved if we make the change of variables $t=\\pm \\sqrt{Z}$, resulting in:\n\\begin{equation}\n(C^2+A^2) Z^4 + (-C^2+2AB) Z^3 + (-2AK+B^2) Z^2 - 2BKZ + K^2 = 0.\n\\end{equation}\nThis polynomial of 4-th order can have four different solutions. From these solutions, we have to take only\nthe real solutions which are larger than 0, given the range of variation of $\\Theta_B$:\n\\begin{equation}\nt \\in \\mathbb{R}, \\qquad 0 \\leq t \\leq 1.\n\\end{equation}\nOnce the solutions for $t$ are found, we make $\\Theta_B' = \\arcsin t$. Note that, for a fixed value of $t$,\ntwo values of $\\Theta_B'$ are possible. We choose the correct one by evaluating the expressions for \n$Q$ and $U$ and testing which of the two possible choices give the values equal (or very similar) to the original ones.\n\nThe angles $(\\theta_B,\\phi_B)$ are obtained by doing the transformation from $(\\Theta_B',\\Phi_B)$ to the\nvertical reference system.\n\n\\section{\\texorpdfstring{$\\Phi_B' = \\Phi_B+\\pi$}{PhiB'=PhiB+pi}}\nUnder this change, we have:\n\\begin{equation}\n\\cos 2\\Phi_B' = \\cos 2\\Phi_B, \\quad \\sin 2\\Phi_B' = \\sin 2\\Phi_B, \\quad \\cos \\Phi_B' = -\\cos \\Phi_B, \\quad \\sin \\Phi_B' = -\\sin \\Phi_B.\n\\end{equation}\nFollowing the same approach, we have to solve for $\\Theta_B'$ in \n\\begin{equation}\n\\left[ 3 \\left( \\cos \\Theta_B' \\cos \\theta + \\sin\\theta \\sin\\Theta_B' \\cos\\Phi_B\\right)^2-1 \\right] \\sin^2 \\Theta_B' = \n\\left[ 3 \\left( \\cos \\Theta_B \\cos \\theta - \\sin\\theta \\sin\\Theta_B \\cos\\Phi_B\\right)^2-1 \\right] \\sin^2 \\Theta_B.\n\\end{equation}\nThe solution are obtained as the roots of the same equations as before but now\n\\begin{eqnarray}\nA &=& -3\\cos^2 \\theta + 3\\sin^2 \\theta \\cos^2 \\Phi_B \\nonumber \\\\\nB &=& 3\\cos^2 \\theta - 1 \\nonumber \\\\\nC &=& 6 \\cos\\theta \\sin\\theta \\cos \\Phi_B \\nonumber \\\\\nK &=& \\left[ 3 \\left( \\cos \\Theta_B \\cos \\theta - \\sin\\theta \\sin\\Theta_B \\cos\\Phi_B\\right)^2-1 \\right] \\sin^2 \\Theta_B.\n\\end{eqnarray}\n\nThe angles $(\\theta_B,\\phi_B)$ are obtained by doing the transformation from $(\\Theta_B',\\Phi_B+\\pi)$ to the\nvertical reference system.\n\n\\section{\\texorpdfstring{$\\Phi_B' = \\Phi_B+\\pi/2$}{PhiB'=PhiB+pi/2}}\nUnder this change, we have:\n\\begin{equation}\n\\cos 2\\Phi_B' = -\\cos 2\\Phi_B, \\quad \\sin 2\\Phi_B' = -\\sin 2\\Phi_B, \\quad \\cos \\Phi_B' = -\\sin \\Phi_B, \\quad \\sin \\Phi_B' = \\cos \\Phi_B.\n\\end{equation}\nFollowing the same approach, we have to solve for $\\Theta_B'$ in \n\\begin{equation}\n\\left[ 3 \\left( \\cos \\Theta_B' \\cos \\theta + \\sin\\theta \\sin\\Theta_B' \\sin\\Phi_B\\right)^2-1 \\right] \\sin^2 \\Theta_B' = \n\\left[ 3 \\left( \\cos \\Theta_B \\cos \\theta - \\sin\\theta \\sin\\Theta_B \\cos\\Phi_B\\right)^2-1 \\right] \\sin^2 \\Theta_B.\n\\end{equation}\nThe solution are obtained as the roots of the same equations as before but now\n\\begin{eqnarray}\nA &=& -3\\cos^2 \\theta + 3\\sin^2 \\theta \\sin^2 \\Phi_B \\nonumber \\\\\nB &=& 3\\cos^2 \\theta - 1 \\nonumber \\\\\nC &=& 6 \\cos\\theta \\sin\\theta \\sin \\Phi_B \\nonumber \\\\\nK &=& -\\left[ 3 \\left( \\cos \\Theta_B \\cos \\theta - \\sin\\theta \\sin\\Theta_B \\cos\\Phi_B\\right)^2-1 \\right] \\sin^2 \\Theta_B.\n\\end{eqnarray}\n\nThe angles $(\\theta_B,\\phi_B)$ are obtained by doing the transformation from $(\\Theta_B',\\Phi_B+\\pi/2)$ to the\nvertical reference system.\n\n\n\\section{\\texorpdfstring{$\\Phi_B' = \\Phi_B-\\pi/2$}{PhiB'=PhiB-pi/2}}\nUnder this change, we have:\n\\begin{equation}\n\\cos 2\\Phi_B' = -\\cos 2\\Phi_B, \\quad \\sin 2\\Phi_B' = -\\sin 2\\Phi_B, \\quad \\cos \\Phi_B' = \\sin \\Phi_B, \\quad \\sin \\Phi_B' = -\\cos \\Phi_B.\n\\end{equation}\nFollowing the same approach, we have to solve for $\\Theta_B'$ in \n\\begin{equation}\n\\left[ 3 \\left( \\cos \\Theta_B' \\cos \\theta + \\sin\\theta \\sin\\Theta_B' \\sin\\Phi_B\\right)^2-1 \\right] \\sin^2 \\Theta_B' = \n\\left[ 3 \\left( \\cos \\Theta_B \\cos \\theta - \\sin\\theta \\sin\\Theta_B \\cos\\Phi_B\\right)^2-1 \\right] \\sin^2 \\Theta_B.\n\\end{equation}\nThe solution are obtained as the roots of the same equations as before but now\n\\begin{eqnarray}\nA &=& -3\\cos^2 \\theta + 3\\sin^2 \\theta \\sin^2 \\Phi_B \\nonumber \\\\\nB &=& 3\\cos^2 \\theta - 1 \\nonumber \\\\\nC &=& -6 \\cos\\theta \\sin\\theta \\sin \\Phi_B \\nonumber \\\\\nK &=& -\\left[ 3 \\left( \\cos \\Theta_B \\cos \\theta - \\sin\\theta \\sin\\Theta_B \\cos\\Phi_B\\right)^2-1 \\right] \\sin^2 \\Theta_B.\n\\end{eqnarray}\n\nThe angles $(\\theta_B,\\phi_B)$ are obtained by doing the transformation from $(\\Theta_B',\\Phi_B-\\pi/2)$ to the\nvertical reference system.\n\n\n\\section*{Acknowledgements}\nWe would like to thank Egidio Landi Degl'Innocenti and Marco Landolfi\nfor sharing with us their deep knowledge on the physics of the spectral line polarization,\nwhich they have described in great detail in their\nrigorous monograph on ``Polarization in Spectral Lines\". Finantial support by \nthe Spanish Ministry of Education and Science through projects AYA2007-63881 and \nthe European Commission through the SOLAIRE network (MTRN-CT-2006-035484) is gratefully acknowledged.\n\n\n\\bibliographystyle{apj}\n% \\bibliography{apjmnemonic,/scratch/Dropbox/biblio}\n\n\\begin{thebibliography}{11}\n\\expandafter\\ifx\\csname natexlab\\endcsname\\relax\\def\\natexlab#1{#1}\\fi\n\n\\bibitem[{{Belluzzi} {et~al.}(2007){Belluzzi}, {Trujillo Bueno}, \\& {Landi\n  Degl'Innocenti}}]{belluzzi07}\n{Belluzzi}, L., {Trujillo Bueno}, J., \\& {Landi Degl'Innocenti}, E. 2007, ApJ,\n  666, 588\n\n\\bibitem[{{Condon} \\& {Shortley}(1935)}]{condon_shortley35}\n{Condon}, E.~U., \\& {Shortley}, G.~H. 1935, The Theory of Atomic Spectra\n  (Cambridge: Cambridge University Press)\n\n\\bibitem[{{Edmonds}(1960)}]{edmonds60}\n{Edmonds}, A.~R. 1960, Angular Momentum in Quantum Mechanics (Princeton\n  University Press)\n\n\\bibitem[{{Jones} {et~al.}(1993){Jones}, {Perttunen}, \\&\n  {Stuckmann}}]{Jones_DIRECT93}\n{Jones}, D.~R., {Perttunen}, C.~D., \\& {Stuckmann}, B.~E. 1993, Journal of\n  Optimization Theory and Applications, 79, 157\n\n\\bibitem[{{Landi Deglinnocenti} \\& {Landi Deglinnocenti}(1985)}]{landi_landi85}\n{Landi Deglinnocenti}, E., \\& {Landi Deglinnocenti}, M. 1985, Sol. Phys., 97,\n  239\n\n\\bibitem[{{Landi Degl'Innocenti} \\& {Landolfi}(2004)}]{landi_landolfi04}\n{Landi Degl'Innocenti}, E., \\& {Landolfi}, M. 2004, Polarization in Spectral\n  Lines (Kluwer Academic Publishers)\n\n\\bibitem[{{Pierce}(2000)}]{pierce00}\n{Pierce}, K. 2000, in Allen's Astrophysical Quantities, ed. A. N. Cox (New\n  York: Springer Verlag and AIP Press)\n\n\\bibitem[{{Rees} {et~al.}(1989){Rees}, {Durrant}, \\& {Murphy}}]{rees_delo89}\n{Rees}, D.~E., {Durrant}, C.~J., \\& {Murphy}, G.~A. 1989, ApJ, 339, 1093\n\n\\bibitem[{{Trujillo Bueno}(2003)}]{trujillo03}\n{Trujillo Bueno}, J. 2003, in Stellar Atmosphere Modeling, ed. I.~{Hubeny},\n  D.~{Mihalas}, \\& K.~{Werner}, ASP Conf. Ser. 288 (San Francisco: ASP), 551\n\n\\bibitem[{{Trujillo Bueno} \\& {Asensio Ramos}(2007)}]{trujillo_asensio07}\n{Trujillo Bueno}, J., \\& {Asensio Ramos}, A. 2007, ApJ, 655, 642\n\n\\bibitem[{{Trujillo Bueno} {et~al.}(2005){Trujillo Bueno}, {Merenda},\n  {Centeno}, {Collados}, \\& {Landi Degl'Innocenti}}]{trujillo_merenda05}\n{Trujillo Bueno}, J., {Merenda}, L., {Centeno}, R., {Collados}, M., \\& {Landi\n  Degl'Innocenti}, E. 2005, ApJ, 619, L191\n\n\\end{thebibliography}\n\n\n\\end{document}\n", "meta": {"hexsha": "fde7fb2da369788c7c414e4c056fcbf781684be7", "size": 87920, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/manual.tex", "max_stars_repo_name": "fluxtransport/hazel2", "max_stars_repo_head_hexsha": "4121df2fa6bf96bf8f193f287bbf11c70c5a519e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2018-08-31T11:13:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T02:30:56.000Z", "max_issues_repo_path": "docs/manual.tex", "max_issues_repo_name": "fluxtransport/hazel2", "max_issues_repo_head_hexsha": "4121df2fa6bf96bf8f193f287bbf11c70c5a519e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 26, "max_issues_repo_issues_event_min_datetime": "2018-04-03T15:09:21.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-27T10:10:45.000Z", "max_forks_repo_path": "docs/manual.tex", "max_forks_repo_name": "fluxtransport/hazel2", "max_forks_repo_head_hexsha": "4121df2fa6bf96bf8f193f287bbf11c70c5a519e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2016-02-25T19:35:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-01T17:12:52.000Z", "avg_line_length": 47.1926999463, "max_line_length": 747, "alphanum_fraction": 0.7219290264, "num_tokens": 24807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802471698041, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.3109634779698624}}
{"text": "The first three chapters explain in detail how the simulation application was developed. I now\nturn to its evaluation and explain how I showed that the program works as required.\n\n\\section{Testing strategy\\label{testingStrategy}}\n\nAn application as large as the one developed in this project is almost impossible to get right\nentirely by advance planning. Although I took much care during the preparation and implementation,\nI anticipated that testing and debugging would be necessary.\n\nAs mentioned in section~\\ref{engineering}, I prototyped most numerical algorithms in\n\\textsl{Octave} which allowed rapid interpretation of results through its plotting facilities,\nand hence a rapid edit--test--debug cycle. For each major algorithmic part of the project\nI modelled a physical system which placed a particular emphasis on one part of the simulation,\nthus allowing me to test and debug each feature before working on the next feature:\n\\begin{itemize}\n\\item a gyroscope (section~\\ref{evalGyroscope}) to test rigid body dynamics,\n\\item a double pendulum to test articulated bodies/constraints,\n\\item Newton's cradle (section~\\ref{evalCollisions}) to test colliding contact handling,\n\\item a simulation of boxes falling onto a table to test resting contact handling.\n\\end{itemize}\n\nI developed the \\textsl{Java} version of each feature only after it was working to satisfaction in\nthe \\textsl{Octave} prototype. The \\textsl{Java} implementation usually introduced new bugs, which\nI could locate by implementing the same test cases in \\textsl{Java}, and using step-by-step\ncomparison with the \\textsl{Octave} computation. This testing and debugging strategy turned out\nto be fruitful and effective.\n\n\n\\section{Quantitative evaluation}\n\nI performed several quantitative tests on the program by simulating simple mechanical systems and\ncomparing their numerical outcome to the physical predictions.\n\n\\subsection{Gyroscope simulation\\label{evalGyroscope}}\nThe first set of tests simulates a \\emph{gyroscope} (figure~\\ref{gyroscope}), which was also used\nas a general test case (section~\\ref{testingStrategy}). A gyroscope consists of a single rotating\nrigid body and a `nail' constraint (appendix~\\ref{constrNail}) holding one end of its axis in\nplace. In a gravitational field the gyroscope exhibits a precession movement. Although this\nbehaviour seems counter-intuitive at first, it can be characterized analytically~\\cite{Julian:notes}.\nThere are not many interesting systems of rigid bodies which have an exact solution, so a\ngyroscope is a good choice for quantitative evaluation.\n\n\\begin{figure}\n\\centerline{\\includegraphics{figures/gyroscope}}\n\\caption{Schematic drawing of a gyroscope. The disc rapidly rotates about its own axis, and\n    gravity causes a slower precession movement (shown as a dotted line) about a vertical axis.\n    \\label{gyroscope}}\n\\end{figure}\n\nI set up initial conditions similar to the values one might find in a toy gyroscope (20\nrevolutions per second about the gyroscope axis, one full circle of precession in 8 seconds). I\nthen ran the simulation for 8~s, using an average time step length of about $2.3\\cdot 10^{-4}$~s.\nThe simulation performed one full circle of precession in 7.953~s, which\nis within 0.6~\\% of the theoretical value. Over the course of 8~s, the body rotated by $320.36\\pi$\nradians about its own axis, which differs from the theoretical value by only 0.1~\\%. These errors\nvaried little even in simulations using larger time steps. The effects of nutation\\footnote{Having\nnothing in common with \\emph{mutation}, \\emph{nutation} is an oscillation about an axis\northogonal to the two main axes of rotation. \\cite{Feynman:63}} were small for the chosen initial\nconditions but may have contributed towards the errors.\n\nIt is interesting to also observe a different error, namely the amount by which the constraint\ndrifts apart. Usually this drift is compensated in the Lagrange multiplier method so that it\nnever manifests itself, but temporarily deactivating this\ncorrection\\footnote{by setting $k=d=0$ in equation~\\ref{lagrangeEquation}.} makes the error\nintroduced by the ODE solver observable.\n\n\\begin{figure}\n\\centerline{\\input{figures/errorplot}}\n\\caption{Errors introduced by the ODE solver for different step sizes $h$, as observed in the\n    gyroscope simulation.\n    Solid line: difference between $O(h^4)$ and $O(h^5)$ Runge-Kutta approximations for each time\n    step. Dashed line: cumulative drift of the gyroscope's `nail' constraint after 8~s simulation\n    time.\\label{errorplot}}\n\\end{figure}\n\nFigure~\\ref{errorplot} shows by what distance the gyroscope's `nail' constraint drifted apart\nafter 8~s of simulation time, for a wide range of different step sizes. There are some noteworthy\nfeatures about this plot:\n\n\\begin{itemize}\n\\item The logarithmic axes are scaled such that one order of magnitude in the horizontal has the\n    same length as five orders of magnitude in the vertical. Observe that in this scaling, the\n    solid line (error per time step) is an almost perfect straight line with gradient~1. This\n    shows that the error is indeed an $O(h^5)$ function of the step size, as expected.\n\\item Over a wide range of step sizes, the plot of the total accumulated error is parallel to the\n    solid line. This means the total error is also $O(h^5)$, which is even better than\n    expected: although the approximation in each time step is $O(h^5)$, the number of steps\n    required is inversely proportional to the step length, so one might expect a larger overall\n    error. This relationship indicates that the ODE solver's target error can in fact be used\n    as a reliable estimate of the overall error to within a constant factor.\n\\item As step sizes $h$ become very small~-- below about $3\\cdot 10^{-4}$~s~-- the error in each\n    step continues to scale order $O(h^5)$, but due to the huge number of steps, the accumulated\n    error cannot be reduced much further. However, the errors here are in the range of nanometres,\n    so they should be of little concern for computer graphics purposes.\n\\end{itemize}\n\nIn summary, the results for the simple gyroscope simulation inspire confidence that the\nimplementation is reliable and will continue to produce realistic results for complicated systems\nwhich lack an exact solution. They also show that the target error can conveniently be adjusted\nto match the requirements, because more CPU time does~-- within sensible bounds~-- buy higher\naccuracy.\n\n\n\\subsection{Collision handling\\label{evalCollisions}}\n\nThe analysis in the last section is relevant for continuous systems, but says nothing about\nsimulations involving collisions. For this purpose I simulated a different kind of physics toy,\n\\emph{Newton's cradle} (figure~\\ref{cradleFigure}). This system does not have an exact analytical\nsolution, but it does have characteristic behaviour patterns which may be observed.\n\n\\begin{figure}\n\\centerline{\\includegraphics{figures/cradle}}\n\\caption{Newton's cradle. By conservation of momentum and energy, if $k$ balls collide with one\n    end of the chain of balls, the same number of balls bounce up on the opposite side. The other\n    balls stay stationary.\\label{cradleFigure}}\n\\end{figure}\n\nNewton's cradle works best when the elasticity is large ($\\varepsilon \\approx 1$). I simulated\nit using $\\varepsilon = 1.0$ and $\\varepsilon = 0.9$, with one ball initially raised and the other\nfour at rest. The comparison of the two simulation results is shown in figure~\\ref{cradlePlots}.\nThe energy is calculated as the sum of potential, linear and angular kinetic energies of all five\nballs, with zero potential when all balls are at their equilibrium position. Fully elastic\ncollisions conserve energy in the simulation (constant to within $1$ part in $10^8$), while\nimperfect collisions instantaneously dissipate energy.\n\nThe momentum of balls 2--4 stays zero (within $1$ part in $10^{10}$, except for transient peaks,\nwhich are immediately neutralized again) with full elasticity; with $\\varepsilon = 0.9$, they\nincreasingly begin to swing, as expected. The bottommost plots in figure~\\ref{cradlePlots}\nshow how the step size is reduced to find the exact time of collision, and large time steps\nare taken otherwise.\n\n\\begin{figure}\n\\centerline{\\input{figures/cradle}}\n\\caption{Plot of various time-varying properties of Newton's cradle. Left column: using ideal,\n    fully elastic collisions ($\\varepsilon = 1.0$). Right column: imperfect collisions\n    ($\\varepsilon = 0.9$).\\label{cradlePlots}}\n\\end{figure}\n\nAll behaviour exhibited by this system matches the behaviour observed in reality, so it\nconstitutes a good demonstration that the algorithm of section~\\ref{collidingContact}\nworks correctly: it respects the constraints which attach the balls to the frame of Newton's\ncradle, and it propagates impulses along the chain of contacts. The simulation works equally\nwell with more than one ball in motion.\n\n\\subsection{Run-time cost}\n\nProfiling of the application revealed that the simulation spends about 93~\\% of its time running\nthe biconjugate gradient algorithm to solve the constraint equations. To round off the quantitative\nevaluation, I wanted to know how the computational cost relates to the size of the problem.\n\nThe biconjugate gradient algorithm is an iterative procedure which stops when some error\ncriterion is met. In theory, if exact arithmetic was being used, a solution would always be found\nin $O(N)$ iterations for a system of $N$ constraints\\footnote{or rigid bodies, but since we are\ndealing with articulated bodies, we can assume a linear dependence between the numbers of bodies\nand constraints.}~\\cite{NRinC}. Each iteration requires a constant number of multiplications of a\nmatrix with a vector, and these multiplications dominate (86~\\%) the cost of the algorithm. Such\na multiplication has a cost of $O(N^2)$ for a general matrix, but only\n$O(N)$ for the type of sparse matrix we are dealing with. Hence a theoretical estimate of the\noverall cost of the algorithm would be $O(N\\cdot N) = O(N^2)$.\n\nIn practice, the algorithm converges more slowly when using floating-point arithmetic.\nI measured the ratio of CPU time to simulation time for a range of different-sized systems and\nfound an overall relationship of about $O(N^{2.5})$. Note that the use of sparse matrices still\ncauses a significant benefit, since a simpler implementation would require the same number of\niterations and hence be about $O(N^{3.5})$. In absolute terms, a small simulation~-- of a\ndouble pendulum, say~-- runs almost in real-time on my PC\\footnote{AMD Athlon~XP~2000+},\nwhile one with 100 constraints requires approximately one hour of CPU time per second of\nsimulation time.\n\n\\subsection{Numerical stability}\n\nI had very few problems with numerical stability throughout this project. The ODE solving turned\nout to be very robust; this is particularly satisfying since ODE stability would have been the\ngreatest problem if a penalty method had been used instead of Lagrange multipliers\n(section~\\ref{approachesToConstraints}). I occasionally observed divergence of the biconjugate\ngradient algorithm; this seemed to occur only if there were contradictory constraints in the\nsystem. In complicated collision geometries such contradictions did sometimes occur. I solved this\nproblem by keeping track of the approximate solution with the smallest error amongst all\niterations; if the algorithm starts diverging, it is aborted and the `best guess' is used.\nThis procedure is not mathematically justified, but in all my simulations it produced good results.\n", "meta": {"hexsha": "e742128c206430984360790666493127b621f29a", "size": 11594, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/evaluation.tex", "max_stars_repo_name": "ept/maniation", "max_stars_repo_head_hexsha": "546b78cec5cf3a83986a94086b97f4236b76df2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2016-05-09T00:54:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T00:40:52.000Z", "max_issues_repo_path": "report/evaluation.tex", "max_issues_repo_name": "ept/maniation", "max_issues_repo_head_hexsha": "546b78cec5cf3a83986a94086b97f4236b76df2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/evaluation.tex", "max_forks_repo_name": "ept/maniation", "max_forks_repo_head_hexsha": "546b78cec5cf3a83986a94086b97f4236b76df2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-04-17T14:39:12.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-08T05:38:45.000Z", "avg_line_length": 64.0552486188, "max_line_length": 101, "alphanum_fraction": 0.7922201139, "num_tokens": 2669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.31095133407065795}}
{"text": "\\documentclass[11pt]{beamer}\n\\usepackage[utf8]{inputenc}\n\\usepackage{amsmath}\n\\usepackage{amsfonts}\n\\usepackage{amssymb}\n\\usepackage{graphicx}\n\\usepackage{listings}\n\\usepackage{tikz}\n\\usetikzlibrary{calc,shapes.geometric, arrows}\n\\usetheme{Hannover}\n\\begin{document}\n\t\\author{Wang Xuanyu}\n\t\\title{High Performance Parallel FDTD Computation by Using Vector Processor and CUDA}\n\t%\\subtitle{}\n\t%\\logo{}\n\t\\institute{University of Electronic Science and Technology of China}\n\t\\date{June 4 2016}\n\t\\subject{Fundamental Science}\n\t%\\setbeamercovered{transparent}\n\t%\\setbeamertemplate{navigation symbols}{}\n\t\\frame[plain]{\\maketitle}\n\t\\lstset{breaklines,tabsize=4,language=C,numbers=left,numberstyle=\\tiny,backgroundcolor=\\color{lightgray!40!white},extendedchars=false,keywordstyle=\\color{blue!70}\\bfseries,basicstyle=\\tiny,commentstyle=\\ttfamily\\color{green!40!black}}\n\t\n\t\n\\section{Introduction}\n\t\\begin{frame}\n\t\t\\frametitle{FDTD}\n\t\tFDTD: Finite Difference Time Domain.\n\t\t\\begin{figure}[hp]\n\t\t\t\\centering\n\t\t\t\\begin{tikzpicture}\n\t\t\t\\def \\len {3}\n\t\t\t\\def \\hlen {1.5}\n\t\t\t\\def \\coe {-0.75}\n\t\t\t\n\t\t\t%back rectangle wigh dashline\n\t\t\t\\draw(0,0) rectangle +(\\len,\\len);\n\t\t\t\\draw [dashed] ($(0,0)+0.5*(0,\\len)$) -- +(\\len,0);\n\t\t\t\\draw [dashed] ($(0,0)+0.5*(\\len,0)$) -- +(0,\\len);\n\t\t\t\n\t\t\t%front rectangle wigh dashline\n\t\t\t\\draw($(0,0)+\\coe*(\\hlen,\\hlen)$) rectangle +(\\len,\\len);\n\t\t\t\\draw [dashed] ($(0,0)+(0,\\hlen)+\\coe*(\\hlen,\\hlen)$) -- +(\\len,0);\n\t\t\t\\draw [dashed] ($(0,0)+(\\hlen,0)+\\coe*(\\hlen,\\hlen)$) -- +(0,\\len);\n\t\t\t\n\t\t\t%connect two rectangle\n\t\t\t\\draw (0,0) -- ($(0,0)+\\coe*(\\hlen,\\hlen)$);\n\t\t\t\\draw ($(0,0)+(0,\\len)$) -- ($(0,0)+(0,\\len)+\\coe*(\\hlen,\\hlen)$);\n\t\t\t\\draw ($(0,0)+(\\len,0)$) -- ($(0,0)+(\\len,0)+\\coe*(\\hlen,\\hlen)$);\n\t\t\t\\draw ($(0,0)+(\\len,\\len)$) -- ($(0,0)+(\\len,\\len)+\\coe*(\\hlen,\\hlen)$);\n\t\t\t\n\t\t\t%all dashline\n\t\t\t\\draw [dashed] ($(0,0)+(0,\\hlen)$) -- ($(0,0)+(0,\\hlen)+\\coe*(\\hlen,\\hlen)$);\n\t\t\t\\draw [dashed] ($(0,0)+(\\hlen,0)$) -- ($(0,0)+(\\hlen,0)+\\coe*(\\hlen,\\hlen)$);\n\t\t\t\\draw [dashed] ($(0,0)+(\\len,\\hlen)$) -- ($(0,0)+(\\len,\\hlen)+\\coe*(\\hlen,\\hlen)$);\n\t\t\t\\draw [dashed] ($(0,0)+(\\hlen,\\len)$) -- ($(0,0)+(\\hlen,\\len)+\\coe*(\\hlen,\\hlen)$);\n\t\t\t\n\t\t\t\\draw [dashed] ($(0,0)+0.5*\\coe*(\\hlen,\\hlen)$) -- ++(\\len,0) -- ++(0,\\len) -- ++(-\\len,0) -- cycle;\n\t\t\t\n\t\t\t%axis\n\t\t\t\\draw [->] (0,0) -- +(1.1*\\len,0) node[right]{$y$};\n\t\t\t\\draw [->] (0,0) -- +(0,1.1*\\len) node[above]{$z$};\n\t\t\t\\draw [->] (0,0) -- +($(0,0)-(\\hlen,\\hlen)$) node[below,left]{$x$};\n\t\t\t\n\t\t\t%nodes\n\t\t\t\\begin{tiny}\n\t\t\t%Hx\n\t\t\t\\node[shape=circle,fill=cyan,inner sep=0pt] at (\\hlen,\\hlen) {$H_x$};\n\t\t\t\\node[shape=circle,fill=cyan,inner sep=0pt] at ($(\\hlen,\\hlen)+\\coe*(\\hlen,\\hlen)$) {$H_x$};\n\t\t\t%Hz\t\t\n\t\t\t\\node[shape=circle,fill=cyan,inner sep=0pt] at ($(0,0)+(\\hlen,0)+0.5*\\coe*(\\hlen,\\hlen)$) {$H_z$};\n\t\t\t\\node[shape=circle,fill=cyan,inner sep=0pt] at ($(0,0)+(\\hlen,0)+0.5*\\coe*(\\hlen,\\hlen)+(0,\\len)$) {$H_z$};\n\t\t\t%Hy\n\t\t\t\\node[shape=circle,fill=cyan,inner sep=0pt] at ($(0,0)+(0,\\hlen)+0.5*\\coe*(\\hlen,\\hlen)$) {$H_y$};\n\t\t\t\\node[shape=circle,fill=cyan,inner sep=0pt] at ($(0,0)+(0,\\hlen)+0.5*\\coe*(\\hlen,\\hlen)+(\\len,0)$) {$H_y$};\n\t\t\t%Ez\n\t\t\t\\node[shape=circle,fill=pink,inner sep=0pt] at ($(0,\\hlen)$) {$E_z$};\n\t\t\t\\node[shape=circle,fill=pink,inner sep=0pt] at ($(0,\\hlen)+\\coe*(\\hlen,\\hlen)$) {$E_z$};\n\t\t\t\\node[shape=circle,fill=pink,inner sep=0pt] at ($(0,\\hlen)+(\\len,0)$) {$E_z$};\n\t\t\t\\node[shape=circle,fill=pink,inner sep=0pt] at ($(0,\\hlen)+\\coe*(\\hlen,\\hlen)+(\\len,0)$) {$E_z$};\n\t\t\t%Ex\n\t\t\t\\node[shape=circle,fill=pink,inner sep=0pt] at ($(0,\\hlen)+0.5*\\coe*(\\hlen,\\hlen)+(0,\\hlen)$) {$E_x$};\n\t\t\t\\node[shape=circle,fill=pink,inner sep=0pt] at ($(0,\\hlen)+0.5*\\coe*(\\hlen,\\hlen)+(\\len,0)+(0,\\hlen)$) {$E_x$};\n\t\t\t\\node[shape=circle,fill=pink,inner sep=0pt] at ($(0,\\hlen)+0.5*\\coe*(\\hlen,\\hlen)+(0,-\\hlen)$) {$E_x$};\n\t\t\t\\node[shape=circle,fill=pink,inner sep=0pt] at ($(0,\\hlen)+0.5*\\coe*(\\hlen,\\hlen)+(\\len,0)+(0,-\\hlen)$) {$E_x$};\n\t\t\t%Ey\n\t\t\t\\node[shape=circle,fill=pink,inner sep=0pt] at ($(\\hlen,\\hlen)+(0,\\hlen)$) {$E_y$};\n\t\t\t\\node[shape=circle,fill=pink,inner sep=0pt] at ($(\\hlen,\\hlen)+\\coe*(\\hlen,\\hlen)+(0,\\hlen)$) {$E_y$};\n\t\t\t\\node[shape=circle,fill=pink,inner sep=0pt] at ($(\\hlen,\\hlen)+(0,-\\hlen)$) {$E_y$};\n\t\t\t\\node[shape=circle,fill=pink,inner sep=0pt] at ($(\\hlen,\\hlen)+\\coe*(\\hlen,\\hlen)+(0,-\\hlen)$) {$E_y$};\n\t\t\t\\end{tiny}\n\t\t\t\\end{tikzpicture}\n\t\t\t\\caption{The spatial discrete structure of Yee cell}\\label{yee cell}\n\t\t\\end{figure}\n\t\\end{frame}\n\t\n\t\\begin{frame}{Vector Processor}\n\t\\begin{figure}[hp]\n\t\t\\centering\n\t\t\\def \\xl {2cm}\n\t\t\\def \\m {1.76cm}\n\t\t\\def \\s {0.8cm}\n\t\t\\def \\t {0.4cm}\n\t\t\\def \\fth {0.25}\n\t\t\\begin{tikzpicture}\n\t\t\\begin{tiny}\n\t\t\n\t\t\n\t\t\\tikzstyle{lbox} = [rectangle, minimum size = \\xl,text centered, draw=black,align=center,fill=lightgray!20]\n\t\t\n\t\t\\tikzstyle{sbox} = [rectangle, minimum size = \\s,text centered, draw=black,align=center,fill=orange!20]\n\t\t\n\t\t\\tikzstyle{mbox} = [rectangle, minimum width = \\m, minimum height=\\s,text centered, draw=black,align=center,fill=orange!20]\n\t\t\n\t\t\\tikzstyle{tbox} = [rectangle, minimum size = \\t,text centered, draw=black,align=center,fill=orange!20]\n\t\t\n\t\t\\tikzstyle{recbox} = [rectangle, minimum width = \\xl, minimum height=\\s,text centered, draw=black,align=center,fill=orange!20]\n\t\t%part1\n\t\t\\node (cpu) at (0,0) [lbox, label=above:CPU] {};\n\t\t\\node (core0) at (-\\fth*\\xl,\\fth*\\xl) [sbox] {core 0};\n\t\t\\node (core1) at (\\fth*\\xl,\\fth*\\xl) [sbox,fill=orange!40] {core 1};\n\t\t\\node (core2) at (-\\fth*\\xl,-\\fth*\\xl) [sbox] {core 2};\n\t\t\\node (core3) at (\\fth*\\xl,-\\fth*\\xl) [sbox] {core 3};\n\t\t\\draw (1.8*\\fth*\\xl,1.8*\\fth*\\xl) -- (4*\\fth*\\xl,2*\\fth*\\xl);\n\t\t\\draw (1.8*\\fth*\\xl,0.2*\\fth*\\xl) -- (4*\\fth*\\xl,-2*\\fth*\\xl);\n\t\t\n\t\t%part2\n\t\t\\node (core) [lbox, right of=cpu, xshift=\\xl, label=above:Core] {};\n\t\t\\node (sp) at (5.0*\\fth*\\xl,-\\fth*\\xl) [sbox] {SP};\n\t\t\\node (vp) at (7.0*\\fth*\\xl,-\\fth*\\xl) [sbox] {VP};\n\t\t\\node (cache) at (6*\\fth*\\xl,\\fth*\\xl) [mbox] {Cache};\n\t\t\\draw [-stealth](7*\\fth*\\xl,-1.8*\\fth*\\xl) -- (7.5*\\fth*\\xl,-3*\\fth*\\xl);\n\t\t\\draw [-stealth](4.5*\\fth*\\xl,-1.8*\\fth*\\xl) -- (1.5*\\fth*\\xl,-4.2*\\fth*\\xl);\n\t\t\n\t\t%part3\n\t\t\\node (SP) [recbox, yshift=-\\xl,below of=cpu, label=above:scalar processor] {};\n\t\t\\node [tbox,fill=gray!50] at (0,-6*\\fth*\\xl) {};\n\t\t\\node  at (-0.7*\\fth*\\xl,-6*\\fth*\\xl) {+};\n\t\t\\node [tbox,fill=gray!30] at (-1.4*\\fth*\\xl,-6*\\fth*\\xl) {};\n\t\t\\node  at (0.7*\\fth*\\xl,-6*\\fth*\\xl) {=};\n\t\t\\node [tbox,fill=gray!80] at (1.4*\\fth*\\xl,-6*\\fth*\\xl) {};\n\t\t\n\t\t%part4\n\t\t\\node (VP) [lbox, below of=core, yshift=-\\xl, label=above:vector processor] {};\n\t\t\\foreach \\y in {1,2,3,4}{\n\t\t\t\\node [tbox,fill=gray!30] at (4.6*\\fth*\\xl,-\\y*\\fth*\\xl-3.5*\\fth*\\xl) {};\t\n\t\t}\n\t\t\\foreach \\y in {1,2,3,4}{\n\t\t\t\\node at (5.3*\\fth*\\xl,-\\y*\\fth*\\xl-3.5*\\fth*\\xl) {+};\t\n\t\t}\n\t\t\\foreach \\y in {1,2,3,4}{\n\t\t\t\\node [tbox,fill=gray!50] at (6*\\fth*\\xl,-\\y*\\fth*\\xl-3.5*\\fth*\\xl) {};\t\n\t\t}\n\t\t\\foreach \\y in {1,2,3,4}{\n\t\t\t\\node at (6.7*\\fth*\\xl,-\\y*\\fth*\\xl-3.5*\\fth*\\xl) {=};\t\n\t\t}\n\t\t\\foreach \\y in {1,2,3,4}{\n\t\t\t\\node [tbox,fill=gray!80] at (7.4*\\fth*\\xl,-\\y*\\fth*\\xl-3.5*\\fth*\\xl) {};\t\n\t\t}\n\t\t\n\t\t%arrows\n\t\t\n\t\t\\end{tiny}\n\t\t\\end{tikzpicture}\n\t\t\\caption{The spatial discrete structure of Yee cell}\\label{ch2 fig: yee cell}\n\t\\end{figure}\n\n\t\\end{frame}\n\t\n\t\\begin{frame}{CUDA}\n\t\tCUDA: Compute Unified Device Architecture.\n\t\t\n\t\tCharacteristics:\n\t\t\\begin{itemize}\n\t\t\t\\item Massive threads.\n\t\t\t\\item Independent device.\n\t\t\\end{itemize}\n\t\\end{frame}\n\t\n\t\\section{FDTD with VP}\n\t\\begin{frame}{FDTD with VP}{New model}\n\t\t\\begin{figure}\n\t\t\t\\centering\n\t\t\t\\begin{minipage}{0.45\\textwidth}\n\t\t\t\t\\centering\n\t\t\t\t\\includegraphics[width=\\textwidth]{old}\n\t\t\t\t\\caption{The traditional computational model}\n\t\t\t\\end{minipage}\n%\t\t\t\\hspace*{10pt}\n\t\t\t\\begin{minipage}{0.4\\textwidth}\n\t\t\t\t\\centering\n\t\t\t\t\\includegraphics[width=\\textwidth]{new}\n\t\t\t\t\\caption{The modified computational model}\n\t\t\t\\end{minipage}\n\t\t\t\\caption{The traditional and new computational model}\n\t\t\\end{figure}\n\t\\end{frame}\n\t\n\t\\begin{frame}{FDTD with VP}{Comparasions}{Number of discrete field points}\n\t\t\\begin{table}\n\t\t\t\\includegraphics[width=0.8\\textwidth]{oldnumber}\n\t\t\t\\caption{The number of traditional scheme}\n\t\t\\end{table}\n\t\t\\begin{table}\n\t\t\t\\includegraphics[width=0.8\\textwidth]{newnumber}\n\t\t\t\\caption{The number of modified scheme}\n\t\t\\end{table}\n\t\\end{frame}\n\t\n\t\\begin{frame}{FDTD with VP}{Comparasions}{Time elapsed}\n\t\t\\begin{table}\n\t\t\t\\includegraphics[width=0.8\\textwidth]{vprlst}\n\t\t\t\\caption{The comparison between traditional and new computational model}\n\t\t\\end{table}\n\t\\end{frame}\n\t\n\t\\begin{frame}{FDTD with VP}{In different conditions}\n\t\tThe relation between elapsed time and simulation size:\n\t\t\\begin{description}\n\t\t\t\\item[Space size] The size of space scale is as\n\t\t\tn times as before, the time-consuming will be about $0.92n + 0.08$ times than before.\n\t\t\t\\item[Time size] The size of time scale is as\n\t\t\t$n$ times as before, the time-consuming will be about $0.99n$ times than before.\n\t\t\\end{description}\n\t\\end{frame}\n\t\n\t\\section{FDTD with CUDA}\n\t\\begin{frame}[containsverbatim]{FDTD with CUDA}{Implementation}\n\t\\begin{lstlisting}\n\tint x, y, tid, number;\n\tfloat dif_Hy, dif_Hx;\n\ttid = threadIdx.x + blockIdx.x*blockDim.x;\n\twhile (tid < ele_ex*size_Ez_y)\n\t{\n\t\tnumber = tid + 1;\n\t\ty = number % ele_ex;//row\n\t\tx = number - (y*ele_ex);//column\n\t\t//Hy(i,j)\t-\tHy(i-1,j)\n\t\tdif_Hy = Hy[y*ele_hy + x] - Hy[(y - 1)* ele_hy + x];\n\t\t//Hx(i,j-1)\t-\tHx(i,j)\n\t\tdif_Hx = Hx[y*ele_hx + (x - 1)] - Hx[y*ele_hx + x];\n\t\tEz[y*ele_ex + x] += coe_Ez * (dif_Hx + dif_Hy);\n\t\ttid += blockDim.x*gridDim.x;\n\t}\n\t\\end{lstlisting}\n\t\\end{frame}\n\t\n\t\\begin{frame}{FDTD with CUDA}{Comparison}\n\t\t\\begin{table}\n\t\t\t\\includegraphics[width=0.8\\textwidth]{cuda}\n\t\t\t\\caption{The comparison between the modified data parallelism and using CUDA}\n\t\t\\end{table}\n\t\\end{frame}\n\t\n\t\\begin{frame}{FDTD with CUDA}{In different conditions}\n\t\tIn all conditions, time elapsed in a single running time is less that 0.01.\n\t\\end{frame}\n\t\n\t\\section{Conclusion}\n\t\\begin{frame}{Conclusion}\n\t\tIn this, we did following contributions:\n\t\t\\begin{description}\n\t\t\t\\item[FDTD with VP] Proposed a new computational model, which can save about 3.45\\% time. The result had been sent to a journal.\n\t\t\t\\item[FDTD with CUDA] Implemented the Mur ABC with CUDA. In the profiling result we can see how powerful the GPU is in parallel computation.\n\t\t\\end{description}\n\t\\end{frame}\n\t\n\t\\section{Thanks}\n\t\\begin{frame}{Acknowledgements}\n\t\tThanks for your patience and attention.\n\t\\end{frame}\n\\end{document}", "meta": {"hexsha": "cf44152243b5c9e5b89164bb04068ed7a46a6e9d", "size": 10419, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ppt/document.tex", "max_stars_repo_name": "obserthinker/bachelorgraduatethesis", "max_stars_repo_head_hexsha": "445351447c95a48b5f8af4b1081c3dcf0018045c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ppt/document.tex", "max_issues_repo_name": "obserthinker/bachelorgraduatethesis", "max_issues_repo_head_hexsha": "445351447c95a48b5f8af4b1081c3dcf0018045c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ppt/document.tex", "max_forks_repo_name": "obserthinker/bachelorgraduatethesis", "max_forks_repo_head_hexsha": "445351447c95a48b5f8af4b1081c3dcf0018045c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3051470588, "max_line_length": 235, "alphanum_fraction": 0.6177176313, "num_tokens": 4225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.3109513340706579}}
{"text": "\\title{\\bf Images}\n\n\\section{Basics \\& Nomenclature}\n\nTwo-dimensional array-based detectors at the focal planes of\ntelescopes produce images --- two-dimension rasters of values.  Here\nwe consider the basic properties such images with an emphasis on the\nsorts of issues affecting ultraviolet, optical, and infrared imaging\ninstruments. Many of the principles hold for other sorts of data sets.\n\nThese images can be thought of as noisy samplings of an {\\it image\nfunction} which is the convolution of the image coming from space with\na response function known as the {\\it point spread function}\n(PSF). The PSF can have contributions from the Earth's atmosphere, the\ntelescope's physical and geometric optics, and the detector.\n\nThe width of the PSF is usually characterized by its full-width\nhalf-maximum (FWHM). An important property of an imaging system is its\nsampling density relative to the FWHM. If this density is high enough,\ntypically greater than 2 pixels per FWHM, the PSF will be close to\n{\\it Nyquist sampled}, meaning that if the image were noiseless it\nwould preserve all of the information in the image function. The\nexercises describe the origin of this criterion, which is related to\nthe true Nyquist sampling criterion of a particular band-limited\nfunction (one with constant Fourier amplitudes out to some\nwavenumber). Typically instruments do not truly Nyquist sample the\nimage function, but in certain circumstances it can be possible.\n\nImages taken outside the Galactic Plane which are not extraordinarily\ndeep usually allow one to separate the flux into individual objects,\nwhich are generally classifiable as {\\it point sources} or {\\it\nextended sources}. The point sources are those whose images are\nconsistent with the PSF. With ordinary imaging capability, stars are\npoint sources. Galaxies are often extended sources, with FWHM larger\nthan the PSF FWHM. High redshift, luminous quasars usually appear as\npoint sources, though with high contrast imaging from space their\nextended host galaxies can be detected.\n\nThe image locations can be quantified by their $x$ and $y$ pixel\nvalues. The center of each object is typically determined by the mode\nof the light distribution, or sometimes by a weighted centroid of the\nflux distribution (which is less precise but for extended sources may\nbe more desirable at times). The relationship between these $x$ and\n$y$ pixel values and the RA and Dec locations they correspond to is\ncalled the {\\it astrometric solution}. Usually the astrometric\nsolution is expressed in terms of a World Coordinate System\n(\\citealt{greisen02a}) description of the image, which provides the\nmetadata encoding an approximate projection of the image and\ndistortions in that projection.\n\nThe raw image is usually obtained in some uncalibrated form. In terms\nof the specific intensity of the image $I_\\nu(\\alpha, \\delta)$ coming\nfrom outside the Earth's atmosphere convolved with the instrumental\nresolution, the raw image in DN$(x,y)$ in pixel coordinates may be\nwritten:\n\\begin{equation}\n\\mathrm{DN}(x, y, t) = \\mathrm{DN}_{\\mathrm{back}}(x, y, t) + \n\\int \\frac{\\dd{\\nu}}{\\nu} Q(\\nu, {\\rm alt}, {\\rm az}, x, y, t)\n\\left[I_\\nu(\\nu, \\alpha, \\delta) + S_{\\nu}(\\nu, {\\rm alt}, {\\rm az},\nt)\\right]\n\\end{equation}\n$Q$ is a general response function written to depend on the pixels\ndetecting the objects, the local sky coordinates (though it might have\na more general form in some cases), frequency, and time. $S_{\\nu}$ is\nbackground, generally due to sky emission, and written in terms of\naltitude and azimuth, to suggest the important axes, but also in terms\nof time (e.g. where the Moon is). DN$_{\\mathrm{back}}$ is the\ninstrumental background.\n\nOften the response $Q$ is at least roughly separable as follows\n\\begin{equation}\nQ(\\nu) = R(\\nu) A({\\rm alt}, {\\rm az}, \\nu) F(x, y)\n\\end{equation}\nwhere $R(\\nu)$ is the instrumental bandpass, $A$ is the atmospheric\nthroughput, and $F$ is the flat-field. $R$ is often defined to\nincorporate the dependence of the atmosphere on wavelength at some\nnominal altitude, so that $A$ would express only the differences from\nthat. $F$ is often defined to include the determinant of the Jacobian\nbetween $(\\alpha, \\delta)$ and $(x, y)$ which would otherwise need to\nappear and which primarily depends on the instrument. $F$ is usually\ndefined to have a mean around unity.\n\nA final common approximation is that the functions are sufficiently\nseparable or the dependence on angle is sufficient small over the\nfield of view of the image that we can write:\n\\begin{equation}\n\\mathrm{DN}(x, y, t) = \\mathrm{DN}_{\\mathrm{back}}(x, y, t) + \n\\bar{A} F(x, y) \\left[\\mu(\\alpha, \\delta) + \\mu_S({\\rm alt}, {\\rm az},\nt)\\right]\n\\end{equation}\nHere, $\\bar{A}$ is the throughput of the instrument and atmosphere\naveraged over wavelength.  We separate DN$_{\\rm back}$ and $\\mu_S$\nbecause they are from different physical sources. For example, in a\nCCD, DN$_{\\rm back}$ is due to dark current and and bias in the\ndevice, whereas $\\mu_S$ is emission from the sky itself.\n\nThe process of {\\it photometric calibration} is the conversion of the\nobserved DN to $\\mu$. In its most basic form, calibration requires\nsubtracting the instrumental background, scaling the remaining flux by\nthe overall factor $1/\\bar{A}$, dividing by the flat field, and then\nsubtracting the sky. Typically, the instrumental background is\ndetermined through bias frames taken with the shutter shut.  The flat\nfield is determined by observing either the sky in twilight or by\nobserving a screen (sometimes just the dome wall) illuminated such\nthat it mimics light uniformly entering the telescope aperture.\n\nIt is somewhat less standard how $\\mu_S$ and $\\bar{A}$ are\ndetermined. In most cases, determining either one requires some\ndetection and measurement of objects in the image to occur, and their\ndetermination is usually somewhat iterative.\n\nFor $\\mu_s$, usually one takes an initial stab at the background level\n(e.g. just a median), detecting the bright objects, and then\nredetermining the background and its variation across the image when\nexcluding ``detected'' pixels; one can then iterate this\nprocedure. Typically this procedure subtracts not just the atmospheric\nsky emission, but also other sources such as zodiacal light, and also\nsome fraction of the light from detected stars and galaxies. Whether\nthese other sources should or should not be subtracted depends on what\nis wanted out of the image.\n\nFor $\\bar{A}$, the concept is to use detected objects in the field\nwhose $\\mu$ is known from a catalog of standards to calibrate the\nentire image. Sometimes the objects used for calibration are not in\nthe same field but are objects observed close in time to the field of\ninterest with the same instrument; in such cases the difference in\nairmass of the field and the standard field needs to be accounted\nfor. Often in these cases the standards are not known in exactly the\nsame filters as the observations, and these color-dependent effects\nmust be taken into account. Sometimes there are no standards as such,\nbut instead a suite of overlapping observations can be calibrated onto\na self-consistent scale (e.g., \\citealt{finkbeiner15a}).\n\nOnce an image is calibrated, the stars, galaxies, or other objects may\nbe measured for their fluxes and other properties. The fluxes may be\nmeasured through fixed apertures, or one may fit models to the data\nand infer fluxes from those models.\n\n\\section{Commentary}\n\nThe description above of calibration procedures is roughly accurate,\nbut is more illustrative than anything. There are many different\ntechniques in use, driven by the nature of the instrument and\nobservations as well as individual tastes. In part because each\nindividual experiment is so different, astronomers (including myself)\ntend to learn about this subject in the context of a particular set of\nobservations rather than from a generalized perspective. Keep that in\nmind when people (including me!) are telling you how this process\nworks!\n\nAt the highest precision, the calibration effects described above are\nnot truly separable. For example, the astrometric solution depends on\nthe definition of the PSF, because that determines what exactly you\nconsider the location of each object, and the flat-fielding, which can\nalso affect the centroiding.\n\nA more subtle example is that the flux definitions cannot truly be\nseparated from the calibration. The calibration must assume some\neffective aperture for the fluxes of the calibrating sources, but some\nflux will leak outside the aperture, in ways that can vary across the\nimages used in the calibration. These aperture effects need to be\naccounted for for percent level calibration accuracy.\n\n\\section{Key References}\n\n\\begin{itemize}\n  \\item\n    {\\it Design and Construction of Large Telescopes},\n      \\citet{bely03a}\n  \\item\n    {\\it Astrophysical Techniques}, \\citet{kitchin09a}\n\\end{itemize}\n\n%\\section{Order-of-magnitude Exercises}\n%%\n%\\begin{enumerate} \n%\\item Proper motion of galaxies \n%\\end{enumerate} \n\n\\section{Analytic Exercises}\n\n\\begin{enumerate}\n\\item {\\it Origin of the Nyquist criterion}. The Nyquist\n    sampling criterion is based on the concept of a ``band\n    limit.''\n    \\begin{enumerate}\n    \\item Show that if the 2D Fourier\n    transform $f(\\vec{k})$ of the point spread function has zero power\n    higher than the band limit $k_{\\rm max}$, then it can be perfectly\n    described using a discrete Fourier transform that extends only up\n    to that $k_{\\rm max}$. What is the necessary configuration-space\n    sampling for the discrete Fourier transform?\n    \\item Assume $f(\\vec{k}) = {\\rm constant}$\n    below the band limit, and zero above it. What is the resulting PSF\n    $f(\\vec{x})$?\n    \\item Under what circumstances might the criterion in part (b)\n    hold, given what you know about how telescopes work?\n    \\item What is the FWHM of $f(\\vec{x})$ in units of the sampling?\n    This sets the Nyquist criterion for sampling.\n    \\end{enumerate}\n\\item {\\it Interpolation}. Imagine starting with an image sampled on a\n    rectangular grid. Interpolation is the process of inferring\n    the value of an image in between the given sampled points of the\n    image. The case of Nyquist sampled, band limited images motivates\n    a particular method of interpolation.\n    \\begin{enumerate}\n    \\item Explain how linear interpolation can be recast as\n    constructing a model of the image using a set of basis functions,\n    or ``kernels,'' centered on the original grid points.\n    \\item Explain why a (noiseless) Nyquist sampled, band limited\n    image contains all the information necessary for perfect\n    interpolation.\n    \\item If you interpolate perfectly in that situation, what is the\n    effective kernel you are using? Note that this is called {\\it\n    sinc interpolation}.\n    \\item Explain why using exactly that interpolation kernel might be\n    problematic.\n    \\end{enumerate}\n\\item Following the methods of Section 2 of \\citet{vakili16a}, show\n    how the best possible centroiding accuracy depends on the FWHM and\n    on the total signal-to-noise ratio ($S/N$) of a Gaussian point\n    source.\n\\end{enumerate}\n\n\\section{Numerics and Data Exercises}\n\n\\begin{enumerate}\n\\item {\\it Interpolation}. Create an image of a critically sampled\n    Gaussian PSF centered at the middle of a pixel. Create another\n    image of the same PSF, but with its center offset some fraction of\n    a pixel from the first case. We will test how well different types\n    of interpolation work by trying to shift the first image using\n    interpolation and comparing it to the second image.\n\\begin{enumerate}\n\\item Use linear interpolation to try to shift the first image\n    so the PSF has the same center as in the second image. Compare the\n    absolute and fractional differences (pixel-by-pixel) between first\n    image shifted and the second image.\n\\item\n    Perform the same test with sinc interpolation.\n\\item Perform the same test with a ``damped'' version of sinc\n    interpolation, which multiplies the kernel by a broad Gaussian\n    (say, a few FWHM broad).\n\\end{enumerate}\n\\item CCD images from SDSS are available\nas \\href{https://www.sdss.org/dr14/imaging/images/#corr}{corrected\nframes}. Those images have valid WCS headers associated with\nthem. Using the tools from {\\tt astropy}, take RA and Dec values from\nobjects in a randomly chosen field (get these from the {\\tt photoObj}\ntable in CAS) and overplot their locations on the CCD $r$-band image.\n\\item This problem tests the measurement of image centroids.\n\\begin{enumerate}\n\\item Write a piece of code to generate a fake, critically-sampled\nimage of a double Gaussian, with a center that isn't necessarily at\nthe center of a pixel. For the second Gaussian, use $A_2 = 0.1 A_1$\nand $\\sigma_2 = 2.47\\sigma_1$, where $A$ indicates the value at the\ncenter of the Gaussian. This choice is an approximate description of\nthe atmospheric PSF (Jim Gunn, private communication).\n\\item Write a routine to find the light-weighted centroid of the\nimage. Start by using the maximum pixel value, and use your knowledge\nof the PSF FWHM to calculate the center based on the light within 3\nFWHM, and iterate to convergence.\n\\item Write a routine to find the mode of the image. Start by using\nthe maximum pixel value, but then use the 3$\\times$3 grid of pixels in\nthe center to perform a quadratic interpolation to find the peak. \n\\item Now add noise to the images, and use a Monte Carlo test to\nevaluate how the precision of each estimate depends on the total $S/N$\nwithin 3 FWHM.\n\\end{enumerate}\n\\item It is common to use the measured signal from a Poisson process\nto estimate the noise. Use a Monte Carlo technique to estimate the\nbias that this causes as a function of the expectation value $\\bar N$\nfor the Poisson process.\n\\end{enumerate}\n\n\\bibliographystyle{apj}\n\\bibliography{exex}  \n", "meta": {"hexsha": "8662de51f74059918559cac036751d8f582cba56", "size": 13872, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/images-text.tex", "max_stars_repo_name": "blanton144/exex", "max_stars_repo_head_hexsha": "b4d9d52b4fe8af761783f49b2c197a109d94cfdf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tex/images-text.tex", "max_issues_repo_name": "blanton144/exex", "max_issues_repo_head_hexsha": "b4d9d52b4fe8af761783f49b2c197a109d94cfdf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/images-text.tex", "max_forks_repo_name": "blanton144/exex", "max_forks_repo_head_hexsha": "b4d9d52b4fe8af761783f49b2c197a109d94cfdf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.8992805755, "max_line_length": 70, "alphanum_fraction": 0.7722029988, "num_tokens": 3283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.31081122517088966}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%\n%\n%   Thesis template by Youssif Al-Nashif\n%\n%   May 2020\n%\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Processing Text into Graphs}\n\n\\hspace*{0.3cm} For both datasets, the reddit comments and the SCI papers, the text data is collected and stored in its raw form for reproducibility. The text is then cleaned and prepared for analysis using a suite of text processing tools from the \\texttt{\\{tidytext\\}} package for R \\cite{silge2016tidytext}. Using this package, the text undergoes tokenization into skip-grams, stop word removal, and filtering to remove punctuation, numbers, short words, etc. \\\\\n\nSkip-grams are produced for $k=2,3,4$, where $k$ is the window width of the skip-gram for which bigrams are formed. Stop words are gathered from popular lexicons: ``snowball\", ``SMART\", and ``onix\" \\cite{silge2016tidytext}. As stated above, all numeric values, and lingering punctuation were also removed through use of the \\texttt{\\{stringR\\}} package \\cite{wickham2010stringr}. This processing is an essential preprocessing step for using graph kernels to gauge similarity of documents, because words and strings (like punctuation or numbers) that get repeated frequently across many documents in the set do not actually mean the documents are similar\\textemdash they just have common reoccurring words. Removing these types of words forces the text data to be more unique across the document set.  \\\\\n\nThe result of the skip-gram tokenizer is a data frame where each observation is a bigram, a pair of words, that the skip-gram window captured. The data frame is then cleaned of stop words through using anti-joins on each bigram; any row with the appearance of a stop word in either position, the first or second word, was removed. The same method was applied for punctuation and numbers. The result was a data frame of bigrams which appeared in a fixed window width, $k$, of one another and where both words are of a length greater than 3 letters, not a stop word, and do not contain numbers or punctuation. This cleaned dataset is now ready to be converted into a graph object. \\\\\n\nNow that the skip-grams are cleaned, the data frame can be converted to a graph object, through use of the \\texttt{\\{igraph\\}} package \\cite{csardi2013package}. To do this, each word pair in the data frame is converted to an edge and vertex pair in the graph object. For example, the word pair ``data frame\" will become two vertices, labeled ``data\" and ``frame\", with an undirected edge connecting them. In this study, directed graph edges are not used, but could be considered in future iterations of this work. When this completed for all the skip-gram pairs that were generated, it produces a singular connected graph, however a great deal of filtering occurred and there may be disconnected portions. When words are removed from the graph, a vertex will disappear and can potentially split the graph. This is not too common in the NHTSA dataset for two reasons. First, the text data is quite long, and so if a word is reused at a later time in the text there will be an additional connection to keep it included in the main graph. Secondly, the benefit of the skip-gram, as opposed to plain bigrams, is that the larger window width means words get connected and can ``skip\" over words that will get removed through the data cleaning process. So at this point, if there is a group of words that are isolated and not connected to the main graph, they are often quite small and are only several words. To keep computation simple, these lingering small isolated graphs are removed. The vertices that are not members of the main graph are removed from the graph object and that leaves a single connected graph for each text document. These graphs can be compared with graph kernels easily now. \n\n\n", "meta": {"hexsha": "a01d26a0a9ac1c853b6d31d8f7ba3e5d6bd113e1", "size": 3802, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Thesis_Tex/Content/02_Chapters/Chapter 03/Sections/01_TextProcessing.tex", "max_stars_repo_name": "Levi-Nicklas/GraphDocNLP", "max_stars_repo_head_hexsha": "dec1acb24a2ab42b46d161c92b69ad3a55fcc5ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-27T02:08:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-27T02:08:34.000Z", "max_issues_repo_path": "Thesis_Tex/Content/02_Chapters/Chapter 03/Sections/01_TextProcessing.tex", "max_issues_repo_name": "Levi-Nicklas/GraphDocNLP", "max_issues_repo_head_hexsha": "dec1acb24a2ab42b46d161c92b69ad3a55fcc5ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2021-02-18T16:07:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-25T14:18:51.000Z", "max_forks_repo_path": "Thesis_Tex/Content/02_Chapters/Chapter 03/Sections/01_TextProcessing.tex", "max_forks_repo_name": "Levi-Nicklas/GraphDocNLP", "max_forks_repo_head_hexsha": "dec1acb24a2ab42b46d161c92b69ad3a55fcc5ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 190.1, "max_line_length": 1694, "alphanum_fraction": 0.7777485534, "num_tokens": 844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.31081121748456}}
{"text": "\\paragraph{}\nThe SBFEM developed by Song and Wolf \\citep{Wolf1996} provides a promising semi-analytical method to analyze problem in fracture mechanics and unbounded domain.\nAs a method developed based on the FEM and the BEM, the SBFEM is a fundamental-solution-less boundary element method which keeps the benefits of the both as well as provides some effective solutions to the limitations to the FEM and the BEM \\citep{Wol1999}.\nIn contrast to the FEM, only the boundary is discretized using the conventional FEM interpolating function which leads to a decline in the number of unknowns.\nIt also allows solving the problem involving bimaterial interfaces and crack faces without the discretization of them.\nCompared to the BEM, the fundamental solution is no longer required.\nThe infinite boundary can be achieved naturally as the radiation condition at infinity is satisfied in the SBFEM \\citep{Wol2003}..\n\n\\paragraph{}\nFig.~\\ref{lr_fig:sbfem_intro} illustrates a basic concept of the SBFEM.\nA scaling center $O$ is selected at a point from which the whole boundary of the domain is visible (scaling requirement).\nThis condition is automatically satisfied for all convex polygons and many concave polygons.\nThe scaling requirement is equivalent to the notion of ``star convexity'' \\citep{Bishop2014}.\nFor the domain that does not meet the scaling requirement, the requirement can always be satisfied by sub-structuring, i.e. dividing the structure into smaller subdomains, for example, scaled boundary polygon formulation \\citep{NATARAJAN2014101}.\nThe problem domain can be covered by scaling the boundary in the radial direction respect to the scaling center with a ratio $\\xi \\in [0,1]$.\nIn the domain, only the boundary at $\\xi=1$ is discretized with the conventional shape functions.\n\n\\begin{figure}[!ht]\n    \\centering\n    \\scalebox{0.5}{\n        \\includegraphics{literature/images/sbfem_intro.eps}\n    }\n    \\caption[Two dimensional scaled boundary coordinates]{Two dimensional scaled boundary coordinates, where O is the scaling center and $\\xi$ is the radial coordinate with $\\xi=0$ at the scaling center and $\\xi=1$ on the boundary.}\n    \\label{lr_fig:sbfem_intro}\n\\end{figure}\n\n\\paragraph{}\nThe method proved to be far more versatile and was applied to static problems in bounded domains and extended to take into account prescribed displacements \\citep{DEEKS20041153} and concentrated loads \\citep{Vu2014}.\nA simple derivation of the necessary equations based on the virtual work principle is also presented \\citep{Dee2002}.\nThis spurred the interest among researchers, as the similarity with the virtual work-based FEM derivation was highlighted.\nThe method is further developed by deriving a stress recovery technique that was later adopted in adaptive refinement techniques, such as h- and p-adaptive SBFEM \\citep{NME:NME439, doi:10.1002/nme.440, Vu2008441, YANG20111417}.\nThe wave interaction with a cylindrical structure is investigated \\citep{TAO2007232} and the method is also extended to structural dynamics \\citep{Song2009} where the dynamic stiffness matrix was obtained as a continued fraction solution.\nThe main advantage of this approach is that the inertial effect at high frequencies can be modeled by high-order terms of the continued fraction without introducing an internal mesh.\nA higher order spectral element was used in computation of the dispersion curves of the elastic wave using the SBFEM \\citep{GRAVENKAMP201446} and a superior accuracy compared to the conventional approaches is shown.\n\n\\paragraph{}\nThe conventional FEM is known to be inefficient to deal with internal discontinuities such as material interfaces or singularities.\nIn an effort to overcome the limitations of the FEM, mesh-free methods and enrichment techniques such as the extended finite element method (XFEM) were introduced.\nTreatment of evolving discontinuities in mesh-free methods \\citep{doi:10.1002/nme.1151,Rabczuk2007} and enrichment techniques \\citep{Babuška20031,doi:10.1002/nme.1966,CHAUDINH2012242,AREIAS2013113} is more straightforward because it does not require conforming mesh or frequent mesh adaptation as the discontinuities evolve.\nOn the other front, by exploiting the unique feature of the scaling center, the method allows the computation of stress intensity factors directly from their definitions \\citep{Dee2005,SONG2002183}.\nThis has emerged to be an attractive alternate to the already established methods such as the XFEM and the meshless methods to model crack propagation.\n\n\\paragraph{}\nChidgzey et al. \\citep{CHIDGZEY20081198,BIRD2010599} coupled the SBFEM with the BEM for computations in fracture mechanics.\nThis framework combines the semi-analytical solution accuracy of the SBFEM with the geometric flexibility provided by the BEM.\nNatarajan and Song \\citep{doi:10.1002/nme.4557} combined the extended FEM and the SBFEM, thus, circumventing the need to know a priori the enrichment functions, required by the former.\nRecently, Ooi et al. \\citep{doi:10.1002/nme.4284} and Natarajan et al.\\citep{NATARAJAN2014101} employed scaled boundary formulation in polygonal elements to study crack propagation and compared the performance with other displacement based formulations, respectively.\nLi et al.\\citep{LI201352} applied SBFEM to analyze two-dimensional fracture problems in piezoelectric materials.\nOoi et al.\\citep{doi:10.1002/nme.4284,OOI20101178,OOI20131} developed an efficient methodology for automatic crack propagation simulation using the SBFEM.\n\n\\paragraph{}\nIt can be seen that, since the inception of the method, the SBFEM has been applied to various problems in engineering and science.\nIt should be noted that most of the above studies employed Lagrange interpolants to approximate the unknown fields in the circumferential direction. He et al.\n\\citep{HE201228,HE2014152} employed moving least square (MLS) shape functions and Fourier series expansion to approximate the displacement fields in the circumferential direction.\nIt should be noted that the MLS and Fourier basis functions do not satisfy Kronecker δ property and that special care must be employed to enforce the boundary conditions.\nIt was shown that the SBFEM with MLS and Fourier shape functions yielded more accurate results than the MLS.\nVery recently, Lin et al.\\citep{Lin2014} employed non-uniform rational B-splines to approximate the unknown field in the circumferential direction.\nHowever, their study was limited to 2D elastostatics.\n", "meta": {"hexsha": "1b580cc38b233d05151c44d58cd474b565dbaacb", "size": 6467, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "literature/lr_sbfem.tex", "max_stars_repo_name": "fa93hws/thesis", "max_stars_repo_head_hexsha": "c397ddc18e5ff5d6e9b8d6de2e53be4c9c7b7a2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-10-30T12:14:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-30T12:14:47.000Z", "max_issues_repo_path": "literature/lr_sbfem.tex", "max_issues_repo_name": "fa93hws/thesis", "max_issues_repo_head_hexsha": "c397ddc18e5ff5d6e9b8d6de2e53be4c9c7b7a2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "literature/lr_sbfem.tex", "max_forks_repo_name": "fa93hws/thesis", "max_forks_repo_head_hexsha": "c397ddc18e5ff5d6e9b8d6de2e53be4c9c7b7a2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 109.6101694915, "max_line_length": 324, "alphanum_fraction": 0.8150610793, "num_tokens": 1472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.31081121748456}}
{"text": "\\documentclass{article}\n\n% math stuff\n\\usepackage{amsmath}\n\\usepackage{amsthm}\n\\usepackage{amssymb}\n\\usepackage{xcolor}\n\n\\usepackage{mathtools}\n\n\\usepackage{float}\n\\usepackage{subcaption}\n\n% to insert images\n\\usepackage{graphicx}\n\n% to correctly insert stressed characters\n\\usepackage[T1]{fontenc}\n\\usepackage[utf8]{inputenc}\n\n\\usepackage{multirow}\n\n% Bibliography\n% \\usepackage[style=alphabetic]{biblatex}\n% \\usepackage[nottoc]{tocbibind}\n% \\usepackage{bibentry}\n% \\setcounter{biburllcpenalty}{9000}\n% \\usepackage{nameref}\n\n% to put links in table of contents\n\\usepackage{hyperref}\n\\hypersetup{colorlinks=false, %set true if you want colored links\n\tlinktoc=all,     %set to all if you\n}\n\n% Add symbols\n% \\usepackage{textcomp}\n\n% Add command for Real and Z sets\n% \\usepackage{dsfont}\n% \\newcommand{\\Rset}{$\\mathds{R}$}\n% \\newcommand{\\Zset}{$\\mathds{Z}$}\n\n% Code highlighting\n% \\usepackage{minted}\n% \\usemintedstyle{perldoc}\n% \\setminted{\n%     frame=single,\n%     breaklines,\n% }\n\n% tikz figures\n\\usepackage{tikz}\n\\usepackage{tikzit}\n\\input{style.tikzstyles}\n\\usetikzlibrary{positioning}\n\n\n\\newtheorem{theorem}{Theorem}\n\\newtheorem{claim}[theorem]{Claim}\n\n\\begin{document}\n\n\\section{Approximability of Echo Chamber Problem}%\n\\label{sec:approximability_of_echo_chamber_problem}\n\n\\begin{theorem}\n\t\\label{th:approximability}\n\tEcho Chamber Problem (ECP) has no $n^{1-\\epsilon} $-approximation algorithm for\n\tany $\\epsilon$ unless $\\mathcal{P} = \\mathcal{NP}  $\n\\end{theorem}\n\n\\begin{proof}\n\tWe show this by presenting a direct reduction from \\textsc{Maximum\n\t\tIndependent Set} (MIS), which is known having the mentioned hardness factor.\n\n\t\\bigskip\n\tLet $G_{1}  = (V_{1} ,E_{1} )$ be an undirected and unweighted graph and\n\t$\\lambda \\geq \\frac{\\alpha }{1 - \\alpha }$, $\\lambda \\in \\mathbb{N}$ and\n\t$n_{1} \\coloneqq |V_{1}| $.\n\tWe construct the \\emph{interaction} graph ${G}_{2}  = (V_{2} , E^{+}_{2} , E\n\t\t\t^{-}_{2} ) $ as follows\n\n\t\\begin{itemize}\n\t\t\\item for each vertex $v_{i}  \\in V_{1} $ we add a vertex in $G_{2} $\n\t\t\\item for each edge $e_{ij}  \\in\n\t\t\t      E_{1} $ we add $\\lambda n_{1} $ negative edges between $v_{i} $ and $v_{j} $\n\t\t\\item add a vertex $v_r$ and a positive edge between it and any other\n\t\t      vertex that we already inserted in $G_2$\n\t\t\\item add a vertex $v_x$ and $\\lambda n_{1} $ negative edges between $v_x$\n\t\t      and $v_{r} $\n\t\\end{itemize}\n\n\tFurthermore, all the edges in $G_{2} $ are associated to the same content\n\t$C$ and the same thread $T \\in \\mathcal{T}_{C}  $.\n\tAn illustration of the conversion can be found in \\autoref{fig:construction}.\n\n\t\\begin{figure}[hbt]\n\t\t\\begin{center}\n\t\t\t\\begin{subfigure}[b]{0.4\\textwidth}\n\t\t\t\t\\centering\n\t\t\t\t\\caption{$G_{1}$, undirected graph}\n\t\t\t\t\\tikzfig{tikz/approximability1}\n\t\t\t\t\\label{fig:g1_example}\n\t\t\t\\end{subfigure}\n\t\t\t\\begin{subfigure}[b]{0.4\\textwidth}\n\t\t\t\t\\centering\n\t\t\t\t\\tikzfig{tikz/approximability2}\n\t\t\t\t\\caption{$G_{2}$, directed signed graph, for $\\lambda = 1$}\n\t\t\t\t\\label{fig:g2_example}\n\t\t\t\\end{subfigure}\n\t\t\\end{center}\n\t\t\\caption{Example construction of the interaction graph $G_{2} $ from\n\t\t\t$G_{1} $, for $\\alpha = \\frac{1}{2} $}\n\t\t\\label{fig:construction}\n\t\\end{figure}\n\n\t\\begin{claim}\n\t\t\\label{th:claim-controversial}\n\t\tContent $C$ is controversial.\n\t\\end{claim}\n\t\\begin{proof}\n\t\tLet $m_{2}^{-} $ and $m_{2}^{+} $ be the number of negative and\n\t\tpositive edges in $G_2$, respectively.\n\n\t\tBy construction $m_{2}^{+} = n_{1} $ and $m_{2}^{-} \\geq \\lambda n_{1}\n\t\t$. Also, for $a, b, c \\in \\mathbb{R}^{+}$ it holds that $\\frac{a +\n\t\t\t\tb}{a + b + c} \\geq \\frac{a}{a + c} $. Consequently\n\n\t\t\\begin{align}\n\t\t\t\\eta(C) = \\frac{m_{2}^{-} }{m_{2}^{-} +\n\t\t\t\tm_{2}^{+} } \\geq \\frac{\\lambda n_{1}}{\\lambda n_{1}\n\t\t\t\t+ n_{1} } = \\frac{\\lambda }{\\lambda + 1} =\n\t\t\t\\frac{ \\frac{\\alpha }{1 - \\alpha }  }{ \\frac{\\alpha }{1 - \\alpha }\n\t\t\t\t+ 1 } \\geq \\alpha\n\t\t\\end{align}\n\t\\end{proof}\n\n\tSo content C is controversial. This reduces the Echo Chamber Problem on $G_2$ to the maximization of\n\n\t\\begin{equation}\n\t\t\\label{eq:score}\n\t\t\\xi(U) = \\sum^{}_{T \\in S_{C}(U) } | T[U] |\n\t\\end{equation}\n\n\t\\begin{claim}\n\t\t\\label{th:opt-equality}\n\t\t\\begin{equation}\n\t\t\tOPT(ECP) = OPT(MIS)\n\t\t\\end{equation}\n\t\\end{claim}\n\n\t\\begin{proof}\n\t\tLet $I \\subseteq V_{1} $ be an independent set of $G_1$ of size $|I| >\n\t\t\t1$. Consider the associated solution in $G_2$ in which $U = I\n\t\t\t\\cup \\{v_{r} \\}$. By construction it will contain $|I|$ positive\n\t\tedges, so $T$ will not be controversial and also\n\n\t\t\\begin{equation}\n\t\t\tOPT(ECP) \\geq \\xi(U) = |T[U]| = |I| \\implies OPT(ECP) \\geq OPT(MIS)\n\t\t\\end{equation}\n\n\t\tNow let $S \\subseteq V_2$ be a solution of the Echo Chamber problem on\n\t\t$G_2$, and suppose $\\xi(S) > 0$. It is easy to see that $v_{r} \\in S$\n\t\tand that $v_{x} \\not\\in S $. Let $J \\coloneqq S \\setminus \\{v_r\\}$.\n\n\t\tSuppose that $2$ vertices $v_{i} $, $v_{j} \\in J$ are linked in\n\t\t$G_1$. By construction there are at least $\\lambda n_1$ negative edges\n\t\tin $T[S]$, thus\n\n\t\t\\begin{equation}\n\t\t\t\\eta(T[S]) \\geq \\frac{\\lambda n_1}{\\lambda n_1 + |S-1|} \\geq \\frac{\\lambda n_1}{\\lambda n_1 + n_1} = \\frac{\\lambda\n\t\t\t}{\\lambda + 1} \\geq \\alpha\n\t\t\\end{equation}\n\n\t\tThis means that $T[S]$ is controversial $\\implies \\xi(S) = 0\n\t\t\t\\implies contradiction$. Consequently $J$\n\t\tcontains vertices which are independent in $G_1$. Therefore $T[S]$ contains\n\t\tonly positive edges; more specifically\n\n\t\t\\begin{equation}\n\t\t\t\\xi(S) = |T[S]| = |S| - 1 = |S \\setminus \\{v_r\\}| = |J|\n\t\t\\end{equation}\n\n\t\tThus\n\n\t\t\\begin{equation}\n\t\t\tOPT(MIS) \\geq |J| \\implies OPT(MIS) \\geq OPT(ECP)\n\t\t\\end{equation}\n\n\t\tSo the optimal value of the constructed instance of Echo Chamber Problem\n\t\texactly equals that of the \\textsc{Maximum Independent Set} instance, so it\n\t\thas an hardness factor at least as large as that of MIS.\n\t\\end{proof}\n\n\tThis concludes the proof of \\autoref{th:approximability}.\n\\end{proof}\n\n\\newpage\n\n\\section{Approximability of Densest Echo Chamber Problem}%\n\\label{sec:approximability_of_densest_echo_chamber_problem}\n\n\\begin{theorem}\n\t\\label{th:approximability-densest}\n\tDensest Echo Chamber Problem (D-ECP) has no $n^{1-\\epsilon} $-approximation algorithm for\n\tany $\\epsilon$ unless $\\mathcal{P} = \\mathcal{NP}  $\n\\end{theorem}\n\n\\begin{proof}\n\tWe again show this by presenting a direct reduction from \\textsc{Maximum\n\t\tIndependent Set}.\n\n\t\\bigskip\n\tLet $G_{1}  = (V_{1} ,E_{1} )$ be an undirected and unweighted graph and\n\t$\\lambda \\geq \\frac{\\alpha }{1 - \\alpha }$, $\\lambda \\in \\mathbb{N}$ and\n\t$n_{1} \\coloneqq |V_{1}| $.\n\tWe construct the \\emph{interaction} graph ${G}_{2}  = (V_{2} , E^{+}_{2} , E\n\t\t\t^{-}_{2} ) $ as follows\n\n\t\\begin{itemize}\n\t\t\\item for each vertex $v_{i}  \\in V_{1} $ we add a vertex in $G_{2} $\n\t\t\\item for each edge $e_{ij}  \\in\n\t\t\t      E_{1} $ we add $\\lambda (n_{1}+1)^{2}  $ negative edges between $v_{i} $ and $v_{j} $\n\t\t\\item for each edge $e_{ij} \\in V_1 \\times V_1, e_{ij} \\not\\in\n\t\t\t      E_{1} $ we add $2$ positive edges between $v_{i} $ and $v_{j} $\n\t\t\\item add a vertex $v_r$ and $2$ positive edges between it and any other\n\t\t      vertex that we already inserted in $G_2$\n\t\t\\item add a vertex $v_x$ and $\\lambda n_{1}^{2}  $ negative edges between $v_x$\n\t\t      and $v_{r} $\n\t\\end{itemize}\n\n\tFurthermore, all the edges in $G_{2} $ are associated to the same content\n\t$C$ and the same thread $T \\in \\mathcal{T}_{C}  $.\n\tAn illustration of the conversion can be found in\n\t\\autoref{fig:construction-densest}.\n\n\t\\begin{figure}[hbt]\n\t\t\\begin{center}\n\t\t\t\\begin{subfigure}[b]{0.4\\textwidth}\n\t\t\t\t\\centering\n\t\t\t\t\\caption{$G_{1}$, undirected graph}\n\t\t\t\t\\tikzfig{tikz/approximability1-densest}\n\t\t\t\t\\label{fig:g1_example}\n\t\t\t\\end{subfigure}\n\t\t\t\\begin{subfigure}[b]{0.4\\textwidth}\n\t\t\t\t\\centering\n\t\t\t\t\\tikzfig{tikz/approximability2-densest}\n\t\t\t\t\\caption{$G_{2}$, directed signed graph}\n\t\t\t\t\\label{fig:g2_example}\n\t\t\t\\end{subfigure}\n\t\t\\end{center}\n\t\t\\caption{Example construction of the interaction graph $G_{2} $ from\n\t\t\t$G_{1} $}\n\t\t\\label{fig:construction-densest}\n\t\\end{figure}\n\n\t\\begin{claim}\n\t\t\\label{th:claim-controversial-densest}\n\t\tContent $C$ is controversial.\n\t\\end{claim}\n\t\\begin{proof}\n\t\t% Let $m_{2}^{-} $ and $m_{2}^{+} $ be the number of negative and\n\t\t% positive edges in $G_2$, respectively.\n\t\t%\n\t\tBy construction $m_{2}^{+} \\leq n_{1}^{2}  $ and $m_{2}^{-} \\geq\n\t\t\t\\lambda n_{1}^{2} $.\n\t\tThus\n\n\t\t\\begin{align}\n\t\t\t\\eta(C) = \\frac{m_{2}^{-} }{m_{2}^{-} +\n\t\t\t\tm_{2}^{+} } \\geq \\frac{\\lambda n_{1} ^{2} }{\\lambda n_{1}^{2}\n\t\t\t\t+ n_{1}^{2}  } = \\frac{\\lambda }{\\lambda + 1} =\n\t\t\t\\frac{ \\frac{\\alpha }{1 - \\alpha }  }{ \\frac{\\alpha }{1 - \\alpha }\n\t\t\t\t+ 1 } \\geq \\alpha\n\t\t\\end{align}\n\t\\end{proof}\n\n\tSo content C is controversial. This reduces the Densest Echo Chamber Problem on $G_2$ to the maximization of\n\n\t\\begin{equation}\n\t\t\\label{eq:score-densest}\n\t\t\\psi(U) = \\sum^{}_{T \\in S_{C}(U) } \\frac{| T[U] |}{|U|}\n\t\\end{equation}\n\n\t\\begin{claim}\n\t\t\\label{th:opt-equality-densest}\n\t\t\\begin{equation}\n\t\t\tOPT(D-ECP) = OPT(MIS)\n\t\t\\end{equation}\n\t\\end{claim}\n\n\t\\begin{proof}\n\t\tLet $I \\subseteq V_{1} $ be an independent set of $G_1$ of size $n_{I}\n\t\t\t\\coloneqq |I| > 1$. Consider the associated solution in $G_2$ in\n\t\twhich $U = I \\cup \\{v_{r} \\}$.\n\n\t\tBy construction it will contain\n\t\t\\begin{itemize}\n\t\t\t\\item $2 \\cdot n_{I} $ positive edges between $v_{r} $ and $v_{i} \\in I$\n\t\t\t\\item $n_{I}(n_{I}  -1)$\n\t\t\t      positive edges between vertices $v_{i} \\in I$\n\n\t\t\\end{itemize}\n\t\t$|I|$ positive\n\t\tthus $T$ will not be controversial and also\n\n\t\t\\begin{equation}\n\t\t\t\\label{eq:score-densest-mip}\n\t\t\t\\psi(U) = \\frac{|T[U]|}{|U|}  = \\frac{2n_{I}  +\n\t\t\t\t\\cdot n_{I}(n_{I}  -1) }{n_{I} + 1} = \\frac{n_{I}^{2} +\n\t\t\t\tn_{I}}{n_{I} + 1} = n_{I}\n\t\t\\end{equation}\n\n\t\tConsequently\n\n\t\t\\begin{equation}\n\t\t\tOPT(D-ECP) \\geq \\psi(U) = |I| \\implies OPT(D-ECP) \\geq OPT(MIS)\n\t\t\\end{equation}\n\n\t\tNow let $S \\subseteq V_2$ be a solution of the Densest Echo Chamber\n\t\tproblem on $G_2$, and suppose $\\psi(S) > 0$. It is easy to see that\n\t\t$v_{r} \\in S$ and that $v_{x} \\not\\in S $. Let $J \\coloneqq S \\setminus\n\t\t\t\\{v_r\\}$.\n\n\t\tSuppose that $2$ vertices $v_{i} $, $v_{j} \\in J$ are linked in $G_1$.\n\t\tBy construction there are at least $\\lambda (n_1 + 1)^{2} $ negative edges in\n\t\t$T[S]$, thus\n\n\t\t\\begin{equation}\n\t\t\t\\eta(T[S]) \\geq \\frac{\\lambda (n_1+1)^2}{\\lambda (n_1+1)^2 + n(n+1)} \\geq\n\t\t\t\\frac{\\lambda (n_1+1)^{2} }{\\lambda (n_1+1)^2 + (n_1+1)^2} = \\frac{\\lambda }{\\lambda +\n\t\t\t\t1} \\geq \\alpha\n\t\t\\end{equation}\n\n\t\tThis means that $T[S]$ is controversial $\\implies \\psi(S) = 0\n\t\t\t\\implies contradiction$. Consequently $J$\n\t\tcontains vertices which are independent in $G_1$. Therefore $T[S]$ contains\n\t\tonly positive edges. As shown previously in\n\t\t\\autoref{eq:score-densest-mip}\n\n\t\t\\begin{equation}\n\t\t\t\\psi(S) = \\frac{|T[S]|}{|S|} = |J|\n\t\t\\end{equation}\n\n\t\tThus\n\n\t\t\\begin{equation}\n\t\t\tOPT(MIS) \\geq |J| \\implies OPT(MIS) \\geq OPT(D-ECP)\n\t\t\\end{equation}\n\n\t\tSo the optimal value of the constructed instance of Densest Echo Chamber Problem\n\t\texactly equals that of the \\textsc{Maximum Independent Set} instance, so it\n\t\thas an hardness factor at least as large as that of MIS.\n\t\\end{proof}\n\n\tThis concludes the proof of \\autoref{th:approximability-densest}.\n\\end{proof}\n\n\\end{document}\n", "meta": {"hexsha": "c9a3aaad73ec5b7228140090100a9dfac2bbde35", "size": 11142, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/approximability.tex", "max_stars_repo_name": "morpheusthewhite/master-thesis", "max_stars_repo_head_hexsha": "2ab4c0509a119d7b5f332b842a4101470a884351", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-15T14:01:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-15T14:01:29.000Z", "max_issues_repo_path": "docs/approximability.tex", "max_issues_repo_name": "morpheusthewhite/master-thesis", "max_issues_repo_head_hexsha": "2ab4c0509a119d7b5f332b842a4101470a884351", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/approximability.tex", "max_forks_repo_name": "morpheusthewhite/master-thesis", "max_forks_repo_head_hexsha": "2ab4c0509a119d7b5f332b842a4101470a884351", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.864265928, "max_line_length": 117, "alphanum_fraction": 0.6464728056, "num_tokens": 4201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.31081121748456}}
{"text": "\\chapter{Introduction}\r\nFitting is the process of optimising the parameters of a 3DMM when a 2D image is given. There are different approaches on how to do that. Some use a mask with labels for each pixel of the image that determine whether or not the pixel represents a part of the imaged face. An additional difficulty is partial occlusion of the facial region, which must be excluded from the mask too. To achieve satisfying fits, the segmentation has to cut out the face as accurately as possible. There are different approaches to algorithmically generate such a mask. Due to the variety and diversity of such occlusions, this is not a simple problem. In this thesis, the quality of such segmentations by machine-learning-algorithms is measured. We compare the neural network of Nirkin er al \\cite{nirkin2018_faceswap} and the existing model-based top-down approach by Egger et al \\cite{egger_paper}.\r\n\r\n\r\n\\section{Artificial Neural Networks}\r\nThe idea of artificial neural networks was somehow influenced by biology. These networks consist of a variety of neurons which are grouped in layers. The way each neuron works is very simple. It takes multiple inputs of varying strength from other neurons, sums them up, puts the sum into a non-linear function (e.g. Maxout, Sigmoid, ReLu) [\\Cref{fig:chap1:ActivFunctions}], and decides depending on the output if it should send a stimulus itself and if so, in which strength. Each layer is somehow connected to the next layer. Some layers are fully connected (each neuron of a layer is connected to every other neuron in the next layer) while others are convolutional. Convolutional means that a neuron only gets an input of spatially close neighbours in the previous layer. There are many different architectures which mainly differ in the number of layers, number of neurons per layer, and the interconnectivity of the neurons. A classical convolutional neural network (CNN) is depicted in [Figure \\ref{fig:chap1:classicalCNN}].\r\n\r\n\\begin{figure}[H]\r\n\t\\centering\r\n\t\\includegraphics[width=1\\linewidth]{Figures/chap1/ActivFunctions.png}\r\n\t\\caption[Caption for LOF]{Six often used activation functions\\footnotemark. The most commonly used activation function is ReLU because of its simplicity. The disadvantage of this function is if one input has a negative sign, then all following neurons output a signal of 0. An improvement of ReLU is Leaky ReLU.}\r\n\t\\label{fig:chap1:ActivFunctions}\r\n\\end{figure}\r\n\r\n\\footnotetext{Jadon S. (2015 March). Introduction to Different Activation Functions for Deep Learning. Retrieved July 19, 2018 from \\textit{https://medium.com/@shrutijadon10104776/survey-on-activation-functions-for-deep-learning-9689331ba092}}\r\n\r\n\\begin{figure}[H]\r\n\t\\centering\r\n\t\\includegraphics[width=1\\linewidth]{Figures/chap1/classicalCNN.JPG}\r\n\t\\caption{An example of a classical convolutional neural network (CNN). After a certain number of convolutions, a pooling layer extracts the most important information of the image and writes it into the next layer. That is why the picture is getting smaller and smaller until just a vector is left.}\r\n\t\\label{fig:chap1:classicalCNN}\r\n\\end{figure}\r\n\r\nAlready in 1943, Warren McCulloch and Walter Pitts \\cite{mcculloch} showed that even simple networks of this kind can simulate every possible logical formula. For this, they used a neuron model which consisted of simple logic gates and could only process binary input and output signals.\r\n\r\n\\begin{figure}[H]\r\n\t\\centering\r\n\t\\includegraphics[width=1\\linewidth]{Figures/chap1/bio_vs_arti_neuron.png}\r\n\t\\caption[Caption for LOF]{The left-hand side of the image\\footnotemark\\ shows a biological neuron. It is a nerve cell which occurs in almost every animal. On the right-hand side, an artificial neuron is depicted. It sums up the stimuli of the previous neurons, applies an activation function to the sum, and forwards the output.}\r\n\t\\label{fig:test1}\r\n\\end{figure}\r\n\r\n\\footnotetext{Willems K. (2017 May, 2nd). Keras Tutorial: Deep Learning in Python. Retrieved July 10, 2018 from \\textit{https://www.datacamp.com/community/tutorials/deep-learning-python}}\r\n\r\n\\begin{figure}[H]\r\n\t\\centering\r\n\t\\includegraphics[width=1\\linewidth]{Figures/chap1/JLongEtAl.png}\r\n\t\\caption{The transformation from a CNN into an FCN. This is a schematic diagram of Long et al \\cite{jlong}, which fine-tuned the network used in this work. They call this process \"convolutionalization\". They turn the fully connected layers into convolution layers which produces an efficient machine for end-to-end dense learning. }\r\n\t\\label{fig:chap1:JLongEtAl}\r\n\\end{figure}\r\n\r\n\\section{The Fully Convolutional Network Used}\r\n\\label{sec:theFCN}\r\nFor this thesis, a pretrained fully convolutional network from \\cite{nirkin2018_faceswap} is used. A fully convolutional network (often called: FCN) is basically a CNN but with a modified architecture. An FCN does not have the fully connected layers which are usually found at the end of an CNN [compare \\Cref{fig:chap1:classicalCNN} and \\Cref{fig:chap1:JLongEtAl}]. These layers would enable the network to make decisions based on global information. A CNN for example can be used for classification. Nevertheless, for image analysis we want local information of the input image (we do not want to know if there is a face in the image, but where the face is in the image). Therefore, a FCN uses only convolutional and pooling layers. In the whole fully convolutional network only the following structure is repeated: One or more convolution layers and a pooling layer which downsamples the picture. This constellation is recurring several times.\\\\\r\n\\\\\r\nThe assembly of the network used for this thesis follows the FCN-8s-VGG architecture with extensions of Long et al \\cite{jlong} [\\Cref{fig:chap1:JLongEtAl}]. The first part 'FCN' stands for 'fully convolutional network', '8s' means that the result gets upsampled eight times (because of the pooling layers), and 'VGG' means that the popular 16-layer network by Oxford's visual geometry group \\cite{ksimonyan} is used [\\Cref{fig:chap1:VGGnet}]. The original task of the network was to find the name of an object in an input image. The network could distinguish between 1000 different objects. Each cell in the final vector (1*1000 in size) was a boolean variable for one specific item. A schematic representation of this architecture can be found in [\\Cref{fig:chap1:classicalCNN}].\\\\\r\n\\\\\r\nFor our experiments a pretrained fully convolutional network (FCN) of \\cite{nirkin2018_faceswap} is used. It was shown that even with a widespread network, good segmentation can be made and that the network does not have to be specially tailored for the future purpose. However, the network must have been trained with a large enough data set. Nirkin et al used the FCN for intra- and inter-subject face swapping on the Labeled Faces in the Wild (LFW) dataset and showed that intra-subject swapped faces remain as recognisable as before the swap and that in the inter-subject version better face swapping  leads to less perceptibility.\\\\\r\n\\\\\r\nNirkin et al used a semi-supervised approach to produce training data in order to train the FCN. To make large quantities of them, 2'043 face videos of the IARPA Janus CS2 dataset of Klare et al \\cite{IARPAJanus} were used. To avoid searching for the face in every frame of the video, they used motion queues which tracked the face given an initial segmentation based on the approach of \\cite{grundmann} which enriched their training set to 9'818 images. To enlarge the collection of images, they rendered 3D Shapes of various objects (e.g. sunglasses, hands) into existing images. Each occlusion adds 9'500 images to their training set.\\\\\r\n\r\n\\begin{figure}[H]\r\n\t\\centering\r\n\t\\includegraphics[width=1\\linewidth]{Figures/fcn_1.png}\r\n\t\\caption{In the lower-left corner, the 16 layers of the well known VGGnet are shown. In the top-right, you can see the meaning of the '8s' term of the FCN-name. It means that the resulting image has to be 8x upsampled, to get a replica of it which is equal in size to the input image.}\r\n\t\\label{fig:chap1:VGGnet}\r\n\\end{figure}\r\n\r\n\\section{Occlusion aware 3DMM}\r\n\r\nEgger et al propose a fully automated, probabilistic and occlusion-aware 3D morphable face model adaptation framework \\cite{egger_paper}. These methods use an iterative approach to label each pixel whether it belongs to the face or to the background. This approach can handle multiple labels and differentiate between multiple occlusion types, for example, face specific ones (eg. beards) and background. For updating the z-labels they use an algorithm which classifies a pixel based on the probabilities for each possible label, but for our experiments, we limited ourselves to two. We only need to distinguish between the face (including skin and beard) and the background.\\\\\r\n\r\n\\pagebreak\r\n\r\nThe algorithm does two things at the same time. In addition to creating a face mask (segmentation), it estimates the parameters of the popular Basel face Model to reconstruct the given face. It is an EM-algorithm-like method to solve two problems simultaneously. In the E-steps Egger et al update the z-labels and in the M-steps they update the face model  parameters based on the current estimate of the z-labels. For face model adaptation they apply a stochastic sampling strategy based on the Metropolis–Hastings algorithm (Markov Chain Monte Carlo). The likelihood of each pixel is split up into a background model ($X_{BG}$) and a foreground model ($X_{FG}$).\r\n\\[ \r\n\\underbrace{p(\\Theta |I)=p(I| \\Theta)*p(\\Theta)}_{\\mathclap{\\text{\\parbox{4.5cm}{posterior probability of face model parameters $\\Theta$ given an image $I$}}}}\\quad\\quad\\text{ with: }p(I|\\Theta)=\\prod_{X \\in \\text{pixels}}p(X_{BG}|\\Theta)^{z-1}*p(X_{FG}|\\Theta)^z\r\n\\]\r\nConventional approaches for occlusion-segmentation often fail on important parts of the face such as the eyes, eyebrows or the oral region due to their strong variability in colour and shape. The segmentation of Egger et al has difficulties with these aspects too as Figure \\ref{fig:iterations} shows. The algorithm starts with an initial guess and then alternating updates the parameters $\\Theta$ and the z-labels. From the updated parameter set (M-Step) the algorithm renews the z-labels (E-Step) and vice versa (see Figure \\ref{fig:EGGER's_method}).\\\\\r\n\r\n\\begin{figure}[H]\r\n\t\\begin{center}\r\n\t\t\\newcolumntype{C}{>{\\centering\\arraybackslash} m{2.4cm} }  %# New column type\r\n\t\t\\begin{tabular}{SC|SC|SC|SC|SC}\r\n\t\t\ttarget image & 0 iterations & 10 iterations & 20 iterations & FCN\\\\ \\hline\r\n\t\t\t\\subfloat{\\includegraphics[width=0.16\\textwidth]{Figures/chap1/angie_original.png}} &\r\n\t\t\t\\subfloat{\\includegraphics[width=0.16\\textwidth]{Figures/chap1/EGGER_Segmentation_Nr_0.png}} &\r\n\t\t\t\\subfloat{\\includegraphics[width=0.16\\textwidth]{Figures/chap1/EGGER_Segmentation_Nr_9.png}} &\r\n\t\t\t\\subfloat{\\includegraphics[width=0.16\\textwidth]{Figures/chap1/EGGER_Segmentation_Nr_19.png}}&\r\n\t\t\t\\subfloat{\\includegraphics[width=0.16\\textwidth]{Figures/chap1/angie_FCN.png}} \\\\\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\t\\caption{This picture shows the development of the labels after 0, 10 and 20 iterations. Noticeable in this sample image are not only the eyes as mentioned before but also the shadow of the nose, which is first segmented as a background. Only after a certain number of iterations these errors are partially recognised and provided with the correct label.}\r\n\t\\label{fig:iterations}\r\n\\end{figure}\r\n\r\n\\begin{figure}[H]\r\n\t\\centering\r\n\t\\includegraphics[width=1\\linewidth]{Figures/chap1/EGGER's_method.png}\r\n\t\\caption[Caption for LOF]{\\footnotemark \\  Algorithm overview: As input, the algorithm takes a target image and fiducial points. The external Clandmark library for automated fiducial point detection from still images [U\\v ri\\v c\\' a\\v r et al (2015) \\cite{Uricar}] is used. The algorithm starts with an initial face model fit of our average face with a pose estimation. Then, a robust illumination estimation for initialisation of the segmentation labels z and the illumination settings is performed. For this task, a random sample consensus (RANSAC) algorithm is used. RANSAC methods estimate parameters of a mathematical model from a set of observed data that contains outliers. Then the face model and the segmentation are simultaneously adapted to the target image I. The result is a set of face model parameters $\\Theta$ and a segmentation into face and non-face regions. The presented target image is from the LFW database (Huang et al (2007))}\r\n\t\\label{fig:EGGER's_method}\r\n\\end{figure}\r\n\r\n\\footnotetext{Figure \\ref{fig:EGGER's_method} is copied from Fig.4 of the \"Occlusion-aware  3D  Morphable  Models and Illumination Prior for Face Image Analysis\" paper of Egger et al. \\cite{egger_paper}}\r\n\r\n% Soll ich auch die 'stable illumination estimation' in ein chapter machen? Wenn ja, was ist das 'consensus set' ?\r\n\r\n% The source for this table was this post: https://stackoverflow.com/questions/2771856/centering-text-horizontally-and-vertically-in-latex\r\n% To add padding for the cell contents: https://tex.stackexchange.com/questions/31672/column-and-row-padding-in-tables\r\nAn approach using convolutional neural networks to segment occluded faces has already been described by \\cite{SaitoEtAl}. The big difference to our approach is that multiple frames are needed for the final segmentation. Another approach of Morel-Forster et al \\cite{MorelForster} uses random forests to detect facial-occlusions by hair. These are integrated into the fitting process in order to model uncertainty. Unlike us, Morel-Forster et al integrate the occlusion in the face likelihood of the evaluator.", "meta": {"hexsha": "a5869bdf0a2b0dc348a07a8cfc1e1bb7b215b6a2", "size": 13667, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapters/Chapter1.tex", "max_stars_repo_name": "Arneli/latex-bscThesis", "max_stars_repo_head_hexsha": "4b5d4b0608db54f92ae473819045fd8c5f1146b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-04T21:22:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-04T21:22:05.000Z", "max_issues_repo_path": "Chapters/Chapter1.tex", "max_issues_repo_name": "eliasarnold/latex-bscThesis", "max_issues_repo_head_hexsha": "4b5d4b0608db54f92ae473819045fd8c5f1146b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapters/Chapter1.tex", "max_forks_repo_name": "eliasarnold/latex-bscThesis", "max_forks_repo_head_hexsha": "4b5d4b0608db54f92ae473819045fd8c5f1146b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 136.67, "max_line_length": 1032, "alphanum_fraction": 0.7868588571, "num_tokens": 3358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.31061634772752067}}
{"text": "\\section{A Worklist Algorithm for Polymorphic Subtyping}\\label{algorithmic_subtyping}\n\nThis section presents our algorithm for polymorphic\nsubtyping. A novel aspect of our algorithm is the use of worklist\njudgments: a form of judgment that facilitates the propagation \nof information. \n\n\n%-------------------------------------------------------------------------------\n\\subsection{Syntax and Well-Formedness of the Algorithmic System}\nFigure~\\ref{fig:ITP:alg:syntax} shows the\nsyntax and the well-formedness judgment.  \n\n% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n\\paragraph{Existential Variables}\nIn order to solve the unknown types $\\tau$, the algorithmic system extends the\ndeclarative syntax of types with \\emph{existential variables} $\\al$.  They\nbehave like unification variables, but are not globally defined. Instead, the\nordered \\emph{algorithmic context}, inspired by \\citet{dunfield2013complete},\ndefines their scope. Thus \nthe type $\\tau$ represented by the corresponding existential variable is\nalways bound in the corresponding declarative context $\\Psi$.\n\n%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n\\paragraph{Worklist judgments} The form of our algorithmic judgments is\nnon-standard. \n%tracks the (partial) solutions of existential variables\n%in the algorithmic context; they denote a delayed substitution that is\n%incrementally applied to outstanding work as it is encoutered.  \n%Instead of reifying the substitution, \nOur algorithm keeps track of an explicit list of\noutstanding work: the list $\\Omega$ of (reified) \\emph{algorithmic judgments} \nof the form $A \\leq B$,\nto which a substitution can be applied once and for all to propagate the solution\nof an existential variable. \n\n\\begin{figure}[t]\n\\[\n\\begin{array}{l@{\\qquad}lcl}\n\\text{Type variables} & a, b\\\\\n\\text{Existential variables} & \\al, \\bt\\\\[3mm]\n\\text{Algorithmic types} &A, B, C &::=&\\quad 1 \\mid a \\mid \\al \\mid \\forall a. A \\mid A\\to B\\\\\n\\text{Algorithmic context}&\\Gamma &::=&\\quad \\cdot \\mid \\Gamma, a \\mid \\Gamma, \\al\\\\\n\\text{Algorithmic judgments}&\\exps &::=&\\quad \\cdot \\mid \\jcons{A \\le B}{\\exps}\n\\end{array}\n\\]\n\\centering \\framebox{$\\Gamma \\vdash A$}\n\\begin{gather*}\n\\inferrule*[right=$\\mathtt{{wf_a}unit}$]\n  {~}\n  {\\Gamma \\vdash 1}\n\\qquad\n\\inferrule*[right=$\\mathtt{{wf_a}var}$]\n  {a\\in\\Gamma}\n  {\\Gamma\\vdash a}\n\\qquad\n\\inferrule*[right=$\\mathtt{{wf_a}exvar}$]\n  {\\al\\in\\Gamma}\n  {\\Gamma\\vdash \\al} \\\\\n\\inferrule*[right=$\\mathtt{{wf_a}{\\to}}$]\n  {\\Gamma\\vdash A \\\\ \\Gamma\\vdash B}\n  {\\Gamma\\vdash A\\to B}\n\\qquad\n\\inferrule*[right=$\\mathtt{{wf_a}\\forall}$]\n  {\\Gamma, a\\vdash A}\n  {\\Gamma\\vdash \\forall a. A}\n\\end{gather*}\n\\caption{Syntax and Well-Formedness judgment for the Algorithmic System.}\\label{fig:ITP:alg:syntax}\n\\end{figure}\n\n\\begin{comment}\n\\begin{figure}[t]\n\\centering \\framebox{$\\Gamma \\vdash A$}\n\\begin{gather*}\n\\inferrule*[right=$\\mathtt{{wf_a}unit}$]\n  {~}\n  {\\Gamma \\vdash 1}\n\\qquad\n\\inferrule*[right=$\\mathtt{{wf_a}var}$]\n  {a\\in\\Gamma}\n  {\\Gamma\\vdash a}\n\\qquad\n\\inferrule*[right=$\\mathtt{{wf_a}exvar}$]\n  {\\al\\in\\Gamma}\n  {\\Gamma\\vdash \\al} \\\\\n\\inferrule*[right=$\\mathtt{{wf_a}{\\to}}$]\n  {\\Gamma\\vdash A \\\\ \\Gamma\\vdash B}\n  {\\Gamma\\vdash A\\to B}\n\\qquad\n\\inferrule*[right=$\\mathtt{{wf_a}\\forall}$]\n  {\\Gamma, a\\vdash A}\n  {\\Gamma\\vdash \\forall a. A}\n\\end{gather*}\n\\caption{Well-Formedness judgment of the Algorithmic System}\\label{fig:alg:wf}\n\\end{figure}\n\\end{comment}\n\n\\paragraph{Hole Notation}\nTo facilitate context manipulation, we use the syntax $\\Gamma[\\Gamma_M]$ to\ndenote a context of the form $\\Gamma_L, \\Gamma_M, \\Gamma_R$ where $\\Gamma$ is\nthe context $\\Gamma_L, \\bullet, \\Gamma_R$ with a hole ($\\bullet$).\nHole notations with the same name implicitly share the same $\\Gamma_L$ and $\\Gamma_R$. A multi-hole notation like $\\Gamma[\\al][\\bt]$ means $\\Gamma_1,\\al,\\Gamma_2,\\bt,\\Gamma_3$.\n\n%-------------------------------------------------------------------------------\n\\subsection{Algorithmic Subtyping}\n\nThe algorithmic subtyping judgment, defined in Figure~\\ref{fig:ITP:alg}, has the form $\\Gamma\\vdash\\exps$, where\n$\\exps$ collects multiple subtyping judgments $A\\le B$. \n% \\bruno{Text comparing to Dunfield. Maybe mention in RW instead?:\n% In contrast to the\n% original formulation---which features 3 interdepenent judgments---our\n% algorithmic rules are all part of the same judgment. This is better for\n% formalization in proof assistants and avoids mutual dependencies. \n% }\nThe algorithm treats $\\exps$ as a worklist. In every step\nit takes one task from the worklist for processing, possibly\npushes some new tasks on the worklist, and repeats this\nprocess until the list is empty. This last and single base case\nis handled by Rule~$\\mathtt{a\\_nil}$.\nThe remaining rules all deal with the first task in the worklist.\nLogically we can discern 3 groups of rules.\n\n\\begin{figure}[t]\n\\centering \\framebox{$\\Gamma \\vdash \\exps$}\n\\begin{gather*}\n\\inferrule*[right=$\\mathtt{{\\le_a}nil}$]\n  {~}\n  {\\Gamma \\vdash \\cdot} \n\\\\ \\\\\n\\inferrule*[right=$\\mathtt{{\\le_a}unit}$]\n  {\\Gamma \\vdash \\exps}\n  {\\Gamma \\vdash \\jcons{1\\le 1}{\\exps}}\n\\qquad\n\\inferrule*[right=$\\mathtt{{\\le_a}var}$]\n  {a\\in\\Gamma \\\\ \\Gamma \\vdash \\exps}\n  {\\Gamma \\vdash \\jcons{a\\le a}{\\exps}}\n\\qquad\n\\inferrule*[right=$\\mathtt{{\\le_a}exvar}$]\n  {\\al\\in\\Gamma \\\\ \\Gamma \\vdash \\exps}\n  {\\Gamma \\vdash \\jcons{\\al\\le \\al}{\\exps}}\n\\\\\n\\inferrule*[right=$\\mathtt{{\\le_a}{\\to}}$]\n  {\\Gamma \\vdash \\jcons{B_1\\le A_1}{\\jcons{A_2\\le B_2}{\\exps}}}\n  {\\Gamma \\vdash \\jcons{A_1\\to A_2\\le B_1\\to B_2}{\\exps}}\n\\\\\n\\inferrule*[right=$\\mathtt{{\\le_a}\\forall L}$]\n  {\\al \\text{ fresh} \\\\ \\Gamma,\\al \\vdash \\jcons{[\\al/a]A\\le B}{\\exps}}\n  {\\Gamma\\vdash \\jcons{\\forall a. A\\le B}{\\exps}}\n\\qquad\n\\inferrule*[right=$\\mathtt{{\\le_a}\\forall R}$]\n  {b \\text{ fresh} \\\\ \\Gamma,b \\vdash \\jcons{A\\le B}{\\exps}}\n  {\\Gamma\\vdash \\jcons{A\\le \\forall b. B}{\\exps}}\n\\\\\n\\\\\n\\inferrule*[right=$\\mathtt{{\\le_a}instL}$]\n  {\\al\\notin \\mathit{FV}(A)\\cup FV(B)\\quad\n  \t\\Gamma[\\al[1], \\al[2]]\\vdash \\jcons{\\al[1]\\to \\al[2]\\le A\\to B}{ [\\al[1]\\to \\al[2]/\\al]\\exps}}\n  {\\Gamma[\\al] \\vdash \\jcons{\\al\\le A\\to B}{\\exps}}\n\\\\\n\\inferrule*[right=$\\mathtt{{\\le_a}instR}$]\n  {\\al\\notin FV(A)\\cup FV(B)\\quad\n\t\\Gamma[\\al[1], \\al[2]]\\vdash \\jcons{A\\to B\\le \\al[1]\\to \\al[2]}{ [\\al[1]\\to \\al[2]/\\al]\\exps}}\n  {\\Gamma[\\al] \\vdash \\jcons{A\\to B\\le \\al}{\\exps}}\n\\\\\n\\\\\n\\inferrule*[right=$\\mathtt{{\\le_a}solve\\_ex}$]\n  {\\Gamma[\\al][]\\vdash [\\al/\\bt]\\exps}\n  {\\Gamma[\\al][\\bt]\\vdash \\jcons{\\al\\le \\bt}{\\exps}}\n\\qquad\n\\inferrule*[right=$\\mathtt{{\\le_a}solve\\_ex'}$]\n  {\\Gamma[\\al][]\\vdash [\\al/\\bt]\\exps}\n  {\\Gamma[\\al][\\bt]\\vdash \\jcons{\\bt\\le \\al}{\\exps}}\n\\\\\n\\inferrule*[right=$\\mathtt{{\\le_a}solve\\_var}$]\n  {\\Gamma[a][]\\vdash [a/\\bt]\\exps}\n  {\\Gamma[a][\\bt]\\vdash \\jcons{a\\le \\bt}{\\exps}}\n\\qquad\n\\inferrule*[right=$\\mathtt{{\\le_a}solve\\_var'}$]\n  {\\Gamma[a][]\\vdash [a/\\bt]\\exps}\n  {\\Gamma[a][\\bt]\\vdash \\jcons{\\bt\\le a}{\\exps}}\n\\\\\n\\inferrule*[right=$\\mathtt{{\\le_a}solve\\_unit}$]\n  {\\Gamma[]\\vdash [1/\\al]\\exps}\n  {\\Gamma[\\al]\\vdash \\jcons{\\al\\le 1}{\\exps}}\n\\qquad\n\\inferrule*[right=$\\mathtt{{\\le_a}solve\\_unit'}$]\n  {\\Gamma[]\\vdash [1/\\al]\\exps}\n  {\\Gamma[\\al]\\vdash \\jcons{1\\le \\al}{\\exps}}\n\\end{gather*}\n\\caption{Algorithmic Subtyping}\n\\label{fig:ITP:alg}\n\\end{figure}\n\nFirstly, we have five rules that are similar to those in the declarative\nsystem, mostly just adapted to the worklist style. For instance, Rule\n$\\mathtt{{\\le_a}{\\to}}$ consumes one judgment and pushes two to the\nworklist.  A notable difference with the declarative Rule $\\mathtt{{\\le}\\forall\nL}$ is that Rule $\\mathtt{{\\le_a}\\forall L}$ requires no guessing of a type $\\tau$ to instantiate\nthe polymorphic type $\\forall a. A$, but instead\nintroduces an existential variable $\\al$ to the context and to $A$. In\naccordance with the declarative system, where \nthe monotype $\\tau$ should be bound in the context $\\Psi$, here $\\al$ should only\nbe solved to a monotype bound in $\\Gamma$. More generally, for any algorithmic context $\\Gamma[\\al]$, the algorithmic variable $\\al$ \ncan only be solved to a monotype that is well-formed with respect to $\\Gamma_L$.\n\nSecondly, Rules $\\mathtt{{\\le_a}instL}$ and $\\mathtt{{\\le_a}instR}$ partially\ninstantiate existential types $\\al$, to function types. The domain and range\nof the new function type are undetermined: they are set to two\nfresh existential variables $\\al[1]$ and $\\al[2]$. To make sure that\n$\\al[1] \\to \\al[2]$ has the same scope as $\\al$, the new variables\n$\\al[1]$ and $\\al[2]$ are inserted in the same position in the context\nwhere the old variable $\\al$ was. To propagate the instantiation to the remainder\nof the worklist, $\\al$ is substituted for $\\al[1] \\to \\al[2]$ in $\\Omega$.\nThe \\emph{occurs-check} side-condition is necessary to prevent a diverging\ninfinite instantiation. For example\n$1 \\to \\al \\le \\al$ would diverge with no such check.\nNote that the algorithm does not choose to instantiate $\\al$ directly with\n$A \\to B$, since the type is not guaranteed to be a monotype,\nand such instantiation will be inconsistent with our predicative declarative system.\n\nThirdly, in the remaining six rules an existential variable can be immediately\nsolved. Each of the six similar rules removes an existential variable from the\ncontext,  performs a substitution on the remainder of the worklist and\ncontinues.\n\nThe algorithm on judgment list is designed to share the context across all judgments.\nHowever, the declarative system does not share a single context in its derivation.\nThis gap is filled by strengthening and weakening lemmas of both systems,\nwhere most of them are straightforward to prove,\nexcept for the strengthening lemma of the declarative system, which is a little trickier.\n\n\\begin{figure}[t]\n$$\n\t\\inferrule*[Right=$\\mathtt{{\\le_a}\\forall L}$]\n\t{\\inferrule*[Right=$\\mathtt{{\\le_a}{\\to}}$]\n\t\t{\\inferrule*[Right=$\\mathtt{{\\le_a}\\forall L}$]\n\t\t\t{\\inferrule*[Right=$\\mathtt{{\\le_a}instR}$]\n\t\t\t\t{\\inferrule*[Right=$\\mathtt{{\\le_a}{\\to}}$]\n\t\t\t\t\t{\\inferrule*[Right=$\\mathtt{{\\le_a}solve\\_ex}$]\n\t\t\t\t\t\t{\\inferrule*[Right=$\\mathtt{{\\le_a}solve\\_ex}$]\n\t\t\t\t\t\t\t{\\inferrule*[Right=$\\mathtt{{\\le_a}unit}$]\n\t\t\t\t\t\t\t\t{\\inferrule*[Right=$\\mathtt{a\\_nil}$]\n\t\t\t\t\t\t\t\t\t{~}\n\t\t\t\t\t\t\t\t\t{\\al[1] \\vdash \\cdot}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t{\\al[1] \\vdash \\jcons{1 \\le 1}{\\cdot}}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t{\\al[1], \\al[2] \\vdash \\jcons{\\al[1] \\le \\al[2]}{\\jcons{1 \\le 1}{\\cdot}}}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t{\\al[1], \\al[2], \\bt \\vdash \\jcons{\\al[1] \\le \\bt}{\\jcons{\\bt \\le \\al[2]}{\\jcons{1 \\le 1}{\\cdot}}}}\n\t\t\t\t\t}\n\t\t\t\t\t{\\al[1], \\al[2], \\bt \\vdash \\jcons{\\bt \\to \\bt \\le \\al[1] \\to \\al[2]}{\\jcons{1 \\le 1}{\\cdot}}}\n\t\t\t\t}\n\t\t\t\t{\\al, \\bt \\vdash \\jcons{\\bt \\to \\bt \\le \\al}{\\jcons{1 \\le 1}{\\cdot}}}\n\t\t\t}\n\t\t\t{\\al \\vdash \\jcons{\\forall a.\\ a \\to a \\le \\al}{\\jcons{1 \\le 1}{\\cdot}}}\n\t\t}\n\t\t{\\al \\vdash \\jcons{\\al \\to 1 \\le (\\forall a.\\ a \\to a) \\to 1}{\\cdot}}\n\t}\n\t{\\cdot \\vdash \\jcons{\\forall a.\\ a\\to 1\\le (\\forall a.\\ a\\to a)\\to 1}{\\cdot }}\n$$\n  %\\label{fig:alg_sample}\n\\caption{A Success Derivation for the Algorithmic Subtyping Relation}\n\\label{fig:alg_sample_success}\n\\end{figure}\n\n\\begin{figure}[t]\n\t$$\n\t\\inferrule*[Right=$\\mathtt{{\\le_a}\\forall L}$]\n\t{\\inferrule*[Right=$\\mathtt{{\\le_a}{\\to}}$]\n\t\t{\\inferrule*[Right=$\\mathtt{{\\le_a}unit}$]\n\t\t\t{\\inferrule*[Right=$\\mathtt{{\\le_a}\\forall R}$]\n\t\t\t\t{\\inferrule*[Right=$\\mathtt{?}$]\n\t\t\t\t\t{stuck\n\t\t\t\t\t}\n\t\t\t\t\t{\\al, b \\vdash \\jcons{\\al \\le b}{\\cdot}}\n\t\t\t\t}\n\t\t\t\t{\\al \\vdash {\\jcons{\\al \\le \\forall b.\\ b}{\\cdot}}}\n\t\t\t}\n\t\t\t{\\al \\vdash \\jcons{1\\le 1}{\\jcons{\\al \\le \\forall b.\\ b}{\\cdot}}}\n\t\t}\n\t\t{\\al \\vdash \\jcons{1 \\to \\al \\le 1\\to \\forall b.\\ b}{\\cdot}}\n\t}\n\t{\\cdot\\vdash \\jcons{\\forall a.\\ 1\\to a \\le 1\\to \\forall b.\\ b}{\\cdot }}\n\t$$\n\\caption{A Failing Derivation for the Algorithmic Subtyping Relation}\n\\label{fig:alg_sample_fail}\n\\end{figure}\n\n\\paragraph{Example}\nWe illustrate the subtyping rules through a sample derivation in\nFigure~\\ref{fig:alg_sample_success},\nwhich shows that that $\\forall a.\\ a\\to 1\\le (\\forall a.\\ a\\to\na)\\to 1$. Thus the derivation starts with an empty context and a\njudgment list with only one element.\n\n\n% \\begin{center}\n% \t\\begin{tabular}{|c|c|c|c|}\\hline\n% \t\t\\# & Context & Worklist & Rule\\\\\\hline\n% \t\t1&$\\cdot$ & $\\forall x.\\ x\\to 1\\le (\\forall x.\\ x\\to x)\\to 1$ & $\\mathtt{{\\le_a}\\forall L}$\\\\\\hline\n% \t\t2&$\\al$ & $\\al\\to 1\\le (\\forall x.\\ x\\to x)\\to 1$ & $\\mathtt{{\\le_a}{\\to}}$\\\\\\hline\n% \t\t3&$\\al$ & $\\forall x.\\ x\\to x\\le \\al : 1\\le 1$ & $\\mathtt{{\\le_a}\\forall L}$\\\\\\hline\n% \t\t4&$\\al,\\bt$ & $\\bt\\to \\bt\\le \\al : 1\\le 1$ & $\\mathtt{instR}$\\\\\\hline\n% \t\t5&$\\al[1],\\al[2], \\bt$ & $\\bt\\to \\bt\\le \\al[1]\\to \\al[2] : 1\\le 1$ & $\\mathtt{{\\le_a}{\\to}}$\\\\\\hline\n% \t\t6&$\\al[1],\\al[2], \\bt$ & $\\al[1]\\le \\bt : \\bt\\le \\al[2] : 1\\le 1$ & $\\mathtt{{\\le_a}solve\\_ex (\\bt\\leftarrow \\al[1])}$\\\\\\hline\n% \t\t7&$\\al[1],\\al[2]$ & $\\al[1]\\le \\al[2] : 1\\le 1$ & $\\mathtt{{\\le_a}solve\\_ex (\\al[2]\\leftarrow \\al[1])}$\\\\\\hline\n% \t\t8&$\\al[1]$ & $1\\le 1$ & $\\mathtt{{\\le_a}unit}$\\\\\\hline\n% \t\\end{tabular}\n% \\end{center}\n\nIn step 1, we have only one judgment, and that one has a top-level $\\forall$ on\nthe left hand side. So the only choice is Rule $\\mathtt{{\\le_a}\\forall L}$, which\nopens the universally quantified type with an unknown existential variable\n$\\al$. Variable $\\al$ will be solved later to some monotype that is well-formed\nwithin the context before $\\al$. That is, the empty context $\\cdot$ in this\ncase.\nIn step 2, Rule $\\mathtt{{\\le_a}{\\to}}$ is applied to the worklist,\nsplitting the first judgment into two.\nStep 3 is similar to step 1, where the left-hand-side $\\forall$ of the first\njudgment is opened according to Rule $\\mathtt{{\\le_a}\\forall L}$ with a fresh\nexistential variable.\nIn step 4, the first judgment has an arrow on the left hand side, but the\nright-hand-side type is an existential variable. It is obvious\nthat $\\al$ should be solved to a monotype of the form\n$\\sigma \\to \\tau$. Rule $\\mathtt{instR}$ implements this, but avoids\nguessing $\\sigma$ and $\\tau$ by ``splitting'' $\\al$ into two existential\nvariables, $\\al[1]$ and $\\al[2]$, which will be solved to some $\\sigma$ and\n$\\tau$ later.\nStep 5 applies Rule $\\mathtt{{\\le_a}{\\to}}$ again. Notice that after the\nsplit, $\\bt$ appears in two judgments. When the first $\\bt$ is solved\nduring any step of the derivation, the next $\\bt$ will be substituted by that\nsolution.  This propagation mechanism ensures the consistent solution of the\nvariables, while keeping the context as simple as possible.\nSteps 6 and 7 solve existential variables. The existential\nvariable that is right-most in the context is always solved in terms of the other. Therefore in step 6,\n$\\bt$ is solved in terms of $\\al[1]$, and in step 7, $\\al[2]$ is solved in terms of $\\al[1]$.\nAdditionally, in step 6, when $\\bt$ is solved, the substitution $[\\al[1] /\n\\bt]$ is propagated to the rest of the judgment list, and thus the second\njudgment becomes $\\al[1]\\le\\al[2]$.\nSteps 8 and 9 trivially finish the derivation. Notice that $\\al[1]$ is not\ninstantiated at the end. This means that any well-scoped instantiation is fine.\n\n\\paragraph{A Failing Derivation} We illustrate the role of ordered contexts through another example: $\\forall a.\\ 1\\to a \\le 1\\to \\forall b.\\ b$. From the declarative perspective, $a$ should be instantiated to some $\\tau$ first, then $b$ is introduced to the context, so that $b\\notin FV(\\tau)$. As a result, we cannot find $\\tau$ such that $\\tau \\le b$. Figure~\\ref{fig:alg_sample_fail} shows the algorithmic derivation, which also fails due to the scoping---$\\al$ is introduced earlier than $b$, thus it cannot be solved to $b$.\n\n\n\n\n\n", "meta": {"hexsha": "ab407142f0016be8fdd2c66342df6391862f5bf0", "size": 15557, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Sources/ITP/sec3.tex", "max_stars_repo_name": "JimmyZJX/Dissertation", "max_stars_repo_head_hexsha": "823bfe90e4b5cc5b7d90c045670bdf4b087877cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sources/ITP/sec3.tex", "max_issues_repo_name": "JimmyZJX/Dissertation", "max_issues_repo_head_hexsha": "823bfe90e4b5cc5b7d90c045670bdf4b087877cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sources/ITP/sec3.tex", "max_forks_repo_name": "JimmyZJX/Dissertation", "max_forks_repo_head_hexsha": "823bfe90e4b5cc5b7d90c045670bdf4b087877cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.4485714286, "max_line_length": 530, "alphanum_fraction": 0.663881211, "num_tokens": 5364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3106163408055177}}
{"text": "%!TEX root=../main.tex\n\\chapter{Numerical Implementation} \\label{chap:numerics}\n\\minitoc\n\nThis chapter is devoted to the numerical implementation of the dynamic gradient damage model outlined in \\cref{def:dynagraddama}. Semi-spatial discretization is performed in \\cref{sec:spatial} based on the classical $C^0$ finite element method. The coupled two-field evolution problem is then discretized in the time domain based on the general $\\beta$-Newmark scheme, see \\cref{sec:timedis}. Some implementation issues are indicated in \\cref{sec:implementation}.\n\nIn this contribution the spatial and temporal discretization is as usual decoupled and will be discussed below separately. Space-time finite element methods, see \\cite{HughesHulbert:1988}, exploits fully the variational nature of the formulation \\eqref{eq:vi} and can be considered as a possible improvement in the future. The elastic energy density split \\eqref{eq:elasticTC} is adopted to take into account tension-compression asymmetry. The two damage constitutive laws \\eqref{eq:at2} and \\eqref{eq:at1} will be used. In this work the irreversibility condition and the variational inequality \\eqref{eq:vi} will be effectively implemented, which amounts to solve numerically the weak wave equation \\eqref{eq:weakform} and the minimality principle for damage \\eqref{eq:crackmin} at every time step.\n\n\\section{Spatial Discretization} \\label{sec:spatial}\nThe spatial discretization described here constitutes a dynamic extension of the work of \\cite{BourdinFrancfortMarigo:2008,PhamAmorMarigoMaurini:2011} for the regularized fracture model \\eqref{eq:Pualpha} and the quasi-static gradient damage model outlined in \\cref{def:qsgraddama}. A discussion on the large-displacement situations is indicated at the end. The thematic subjects covered here are thus summarized in \\cref{tab:summsd}.\n\\begin{table}[htbp]\n\\centering\n\\caption{Thematic subjects covered in this section} \\label{tab:summsd}\n\\begin{tabular}{ccccc} \\toprule\n& Going dynamical & $\\alpha\\leftrightarrow\\phi$ & $\\nabla\\alpha\\to\\Gamma$ & Experimental validation \\\\ \\midrule\nTheoretics & & & & \\\\\nNumerics & \\rightthumbsup & & & \\\\ \\bottomrule\n\\end{tabular}\n\\end{table}\n\nA semi spatial discretization is performed from a mesh $\\Omega_h$ of the original domain $\\Omega$. It should be ideally unstructured and uniform in mesh sizes otherwise some directions may be preferred when cracks propagate, see \\cite{Negri:1999,PhamAmorMarigoMaurini:2011} and references therein for a discussion on the ideal mesh properties in order to achieve a better modeling of fracture via gradient-damage approaches. In particular, the typical element size $h$ of the mesh should be preferably smaller with respect to the internal length $\\ell$ in order to calculate correctly the damage band profile, the dissipation energy \\eqref{eq:surface} and the material response inside the crack process zone of order $\\mathcal{O}(\\ell)$. It leads often to a computationally demanding calculation which requires massive parallelization.\n\nThe displacement $\\vec{u}_t$ and the damage field $\\alpha_t$ will be both discretized with classical $C^0$ isoparametric finite elements based on $\\Omega_h$. For two-dimensional plane problems, an arbitrary element possesses at every node 3 nodal degrees of freedom corresponding to 2 components of the displacement and 1 scalar value of the damage, see for example \\cref{fig:q4}.\n\\begin{figure}[htbp]\n\\centering\n\\includegraphics[width=0.25\\textwidth]{q4.pdf}\n\\caption{Local interpolation of $(\\vec{u},\\alpha)$ based on nodal values inside the element} \\label{fig:q4}\n\\end{figure}\nThe symbols $\\uvec$ and $\\dvec$ are used to denote the current global displacement and damage nodal vectors. Inside a given physical element $\\Omega_\\me\\in\\Omega_h$, their local nodal vectors $\\uvec^\\me$ and $\\dvec^\\me$ achieve an interpolation of the displacement and damage fields as well as their derivatives\n\\begin{equation} \\label{eq:interpolation}\n\\begin{aligned}\n& \\vec{u}_t(\\vec{x})=\\vec{N}(\\vec{x})\\uvec^\\me\\quad\\text{and}\\quad\\eps(\\vec{u}_t)(\\vec{x})=\\vec{B}(\\vec{x})\\uvec^\\me\\, , \\\\\n& \\alpha_t(\\vec{x})=\\vec{N}_\\alpha(\\vec{x})\\dvec^\\me\\quad\\text{and}\\quad\\nabla\\alpha_t(\\vec{x})=\\vec{B}_\\alpha(\\vec{x})\\dvec^\\me\n\\end{aligned}\n\\end{equation}\nwhere $\\vec{N}$'s and $\\vec{B}$'s are respectively the interpolation and differentiation matrices. The Voigt notation is assumed for the strain tensor $\\eps(\\vec{u}_t)$ and the damage gradient $\\nabla\\alpha_t$, which are written as column vectors. \\emph{Linear} interpolation is used due to its low computational cost in a dynamic calculation. According to \\cite{BourdinFrancfortMarigo:2008}, linear elements for the displacement and damage fields perform equally well compared to higher-order elements in terms of $\\Gamma$-convergence of the damage dissipation energy. Finally this P1-P1 finite element discretization is not forbidden according to \\cite{SimoneAskesPeerlingsSluys:2003}.\n\n\\paragraph{Displacement problem}\nPlugging \\eqref{eq:interpolation} into the weak elastic-damage dynamic wave equation \\eqref{eq:weakform} and adopting the same interpolation for the testing function $\\vec{w}_t$, we obtain the following spatially discretized dynamic evolution equation\n\\begin{equation} \\label{eq:waveeqsdis}\n\\vec{M}\\ddot{\\uvec}=\\vec{F}_\\mathrm{ext}-\\vec{F}_\\mathrm{int}(\\uvec,\\dvec)\n\\end{equation}\nwith $\\vec{M}$ the consistent mass matrix, $\\vec{F}_\\mathrm{ext}$ the external force vector corresponding to the potential \\eqref{eq:power} and $\\vec{F}_\\mathrm{int}$ the internal force vector. The mass matrix is assembled from the elementary mass matrices which reads inside $\\Omega_\\mathrm{e}$\n\\[\n\\vec{M}=\\int_{\\Omega_\\mathrm{e}}\\rho\\vec{N}^\\mT\\vec{N}\\dx.\n\\]\nFor explicit dynamic situations, this matrix is lumped $\\vec{M}\\mapsto \\overline{\\vec{M}}$ using the classical row-summing techniques to improve computational efficiency and spectral properties, see \\cite{Hughes:1987}. The global internal force vector is constructed from its elementary counterparts which are given by\n\\begin{equation} \\label{eq:Fint}\n\\begin{aligned}\n& \\vec{F}_\\mathrm{int}^\\me=\\int_{\\Omega_\\me}\\vec{B}^\\mT\\sig\\bigl(\\vec{B}\\uvec^\\me,\\vec{N}_\\alpha\\dvec^\\me\\bigr)\\dx \\\\\n&= \\int_{\\Omega_\\me}\\vec{B}^\\mT\\bigl(\\mathsf{a}(\\vec{N}_\\alpha\\dvec^\\me)\\sig_0^+(\\vec{B}\\uvec^\\me)+\\sig_0^-(\\vec{B}\\uvec^\\me)\\bigr)\\dx\\,,\n\\end{aligned}\n\\end{equation}\nwhere the stress expression \\eqref{eq:stressposneg} that takes into account tension-compression asymmetry is used. In explicit dynamics a residual stiffness $k_\\mathrm{res}$ is not needed in the stiffness degradation function since no matrix inversion is needed, contrary to the implicit cases \\cite{PhamAmorMarigoMaurini:2011,SchlueterWillenbuecherKuhnMueller:2014}.\n\nFor simplex finite elements (triangular and tetrahedral elements) the Jacobian of the transformation (between the reference and the physical elements) as well as the differentiation matrix $\\vec{B}$ are constant, thus \\eqref{eq:Fint} can be integrated exactly using an effective stress\n\\begin{equation} \\label{eq:FintSim}\n\\vec{F}_\\mathrm{int}^\\me=\\abs{\\Omega_\\me}\\vec{B}^\\mT\\sig_\\mathrm{eff}=\\abs{\\Omega_\\me}\\vec{B}^\\mT(\\mathsf{a}_\\mathrm{eff}\\sig_0^++\\sig_0^-)\\,,\n\\end{equation}\nwhere $\\abs{\\Omega_\\me}$ denotes the measure (area of volume) of $\\Omega_\\me$ and $\\mathsf{a}_\\mathrm{eff}$ stands for the effective stiffness degradation\n\\begin{equation} \\label{eq:aeff}\n\\mathsf{a}_\\mathrm{eff}=\\frac{1}{\\abs{\\Omega_\\me}}\\int_{\\Omega_\\me}\\mathsf{a}(\\vec{N}_\\alpha\\dvec)\\dx.\n\\end{equation}\nExplicit expression of $\\mathsf{a}_\\mathrm{eff}$ can be readily computed and are given as follows.\n\\begin{itemize}\n\\item Triangular elements\n\\[\n\\mathsf{a}_\\mathrm{eff}=\\frac{1}{3}\\left(\\left(1-\\frac{\\alpha_1}{2}-\\frac{\\alpha_2}{2}\\right)^2+\\left(1-\\frac{\\alpha_2}{2}-\\frac{\\alpha_3}{2}\\right)^2+\\left(1-\\frac{\\alpha_1}{2}-\\frac{\\alpha_3}{2}\\right)^2\\right)\n\\]\n\n\\item Tetrahedral elements\n\\[\n\\mathsf{a}_\\mathrm{eff}=1+\\frac{1}{10}\\sum_{i=1}^4\\sum_{j=1}^4\\alpha_i\\alpha_j-\\frac{1}{2}\\sum_{i=1}^4\\alpha_i\n\\]\n\\end{itemize}\nThe use of the effective stress $\\sig_\\mathrm{eff}$ improves computational efficiency and may also be served as an output of the current element.\n\nFor tensor product finite elements, a loop on the Gauss points is necessary and our experience suggests that 4 Gauss points for quadrilateral elements and 8 for hexagonal elements are sufficient. An effective stress can no longer be defined and the stress evaluated at these Gauss points will be used as the output variable.\n\n\\begin{remark}[Extension to large-displacements]\nNumerical implications of the large-displacement extension proposed in \\cref{sec:extensions} are discussed here. It is based on the explicit dynamics situations, where at the beginning of every time step the current configuration $\\vphi_t(\\Omega)$ is known and is updated from the last iteration. The Eulerian elastic-damage dynamic wave equation \\eqref{eq:waveeq} will be naturally solved in the current deformed mesh obtained by constantly updating the mesh coordinates $\\vec{x}_t=\\vec{x}+\\vec{u}_t(\\vec{x})\\in\\Omega_t$.\n\nThis implies that the interpolation of the displacement and the damage \\eqref{eq:interpolation}, as well as the calculation of the global internal force vector \\eqref{eq:Fint} should be performed in the deformed element $\\vphi_t(\\Omega_\\mathrm{e})$. If the interpolation $\\vec{N}$'s can always be transformed to a reference element, the differentiation matrices $\\vec{B}$'s should be evaluated with respect to the current deformed element geometry and hence require being constantly updated at the beginning of every time step.\n\nThe Hencky logarithmic strain $\\vec{h}_t$ defined in \\eqref{eq:logstrain} replaces the use of the linearized strain in the calculation of the stress tensor in \\eqref{eq:Fint}. Although the polar decomposition is indeed unnecessary by remarking that $\\log\\vec{V}_t=\\frac{1}{2}\\log\\vec{B}_t$, spectral decomposition of the left Cauchy-Green tensor $\\vec{B}_t=\\vec{F}_t\\vec{F}_t^\\mT$ is unavoidable.\n\\end{remark}\n\n\\paragraph{Damage problem}\nPlugging the interpolation expression \\eqref{eq:interpolation} into the energy minimization principle \\eqref{eq:crackmin} and using the elastic energy density split \\eqref{eq:elasticTC} leads to the following spatially discretized variational inequality\n\\begin{equation} \\label{eq:crackdis}\nq_{\\uvec}(\\dvec)\\leq q_{\\uvec}(\\underline{\\vec{\\beta}})\\text{ for all $\\underline{\\vec{\\beta}}$ that $0\\leq\\dvec\\leq\\underline{\\vec{\\beta}}\\leq 1$}\n\\end{equation}\nwhich involves the following discrete functional which reads inside each element\n\\begin{equation} \\label{eq:qdiscrete}\nq_{\\uvec}^\\mathrm{e}(\\dvec)=\\int_{\\Omega_\\mathrm{e}}\\bigl(\\mathsf{a}(\\vec{N}_\\alpha\\dvec^\\me)\\psi_0^+(\\vec{B}\\uvec^\\me)+w(\\vec{N}_\\alpha\\dvec^\\me)+w_1\\eta^2\\dvec^{\\me\\mT}\\vec{B}_\\alpha^\\mT\\vec{B}_\\alpha\\dvec^\\me\\bigr)\\dx.\n\\end{equation}\nFor sophisticated damage constitutive laws such as that used in \\cite{LorentzGodard:2011}, it is a nonlinear convex functional where the Hessian matrix depends on the damage state during numerical solving. Fortunately, using the damage constitutive laws \\eqref{eq:at2} and \\eqref{eq:at1}, this functional $q_{\\uvec}(\\dvec)$ is quadratic with respect to the damage vector $\\dvec$ and is given by\n\\begin{equation} \\label{eq:Hb}\nq_{\\uvec}(\\dvec)=\\frac{1}{2}\\dvec^\\mT\\vec{H}(\\uvec)\\dvec-\\vec{b}(\\uvec)^\\mT\\dvec.\n\\end{equation}\nThe Hessian matrix $\\vec{H}$ and the second member vector $\\vec{b}$ depend solely on the current deformation state $\\uvec$ and hence are constant during the solving process of the damage problem. Their exact forms depend on the damage constitutive law used:\n\\begin{itemize}\n\\item For the \\eqref{eq:at1} law for instance, they can be assembled from the elementary matrix and vector given by\n\\begin{align*}\n\\vec{H}^\\me &= \\int_{\\Omega_\\me}\\left(2\\psi_0^+(\\vec{B}\\uvec^\\me)\\vec{N}_\\alpha^\\mT\\vec{N}_\\alpha+2w_1\\eta^2 \\vec{B}_\\alpha^\\mT\\vec{B}_\\alpha\\right)\\dx, \\\\\n\\vec{b}^\\me &= \\int_{\\Omega_\\me}\\left(2\\psi_0^+\\bigl(\\vec{B}\\uvec^\\me\\bigr)-w_1\\right)\\vec{N}_\\alpha\\dx.\n\\end{align*}\n\n\\item For the \\eqref{eq:at2} model, they are given by\n\\begin{align*}\n\\vec{H}^\\me &= \\int_{\\Omega_\\me}\\left(2\\left(\\psi_0^+\\bigl(\\vec{B}\\uvec\\bigr)+w_1\\right)\\vec{N}_\\alpha^\\mT \\vec{N}_\\alpha+2w_1\\eta^2\\vec{B}_\\alpha^\\mT \\vec{B}_\\alpha\\right), \\\\\n\\vec{b}^\\me &= \\int_{\\Omega_\\me}2\\psi_0^+\\bigl(\\vec{B}\\uvec\\bigr)\\vec{N}_\\alpha.\n\\end{align*}\n\\end{itemize}\nThese quantities can be evaluated exactly for simplex finite elements. For quadrilateral and hexahedral elements, an approximated using a numerical integration with respectively 4 and 8 Gauss points will be used.\n\n\\begin{remark}[Extension to large-displacements]\nAccording to \\eqref{eq:crackmin}, the damage minimality condition is naturally formulated in the initial reference configuration. From a physical point of view, this corresponds to the fact that the damage dissipation energy is destined to measure the length or the area of cracks defined in the reference configuration. Technically the concerned energetic functional can be written in the deformed mesh (at the expense of additional unpleasant $\\vec{F}_t$ and $J_t$ terms), however it is not necessary \\cite{PieroLancioniMarch:2007}.\n\nFrom a implementation point of view, it implies that the interpolation and differentiation matrices $\\vec{N}$'s and $\\vec{B}$'s that corresponds to the initial configuration should be stored and will be used throughout the calculation.\n\\end{remark}\n\n\\section{Temporal Discretization} \\label{sec:timedis}\nThis section described a temporal discretization of the dynamic gradient damage model. The thematic subjects covered here are thus summarized in \\cref{tab:summtd}.\n\\begin{table}[htbp]\n\\centering\n\\caption{Thematic subjects covered in this section} \\label{tab:summtd}\n\\begin{tabular}{ccccc} \\toprule\n& Going dynamical & $\\alpha\\leftrightarrow\\phi$ & $\\nabla\\alpha\\to\\Gamma$ & Experimental validation \\\\ \\midrule\nTheoretics & & & & \\\\\nNumerics & \\rightthumbsup & & & \\\\ \\bottomrule\n\\end{tabular}\n\\end{table}\n\nConsider an arbitrary discretization $(t^n)$ of the time interval $I=[0,T]$ where the superscript $n$ denotes a quantity evaluated at the $n$-th time step. We will mainly focus on the time stepping procedures bringing the current known states $(\\uvec^n,\\dot{\\uvec}^n,\\ddot{\\uvec}^n,\\dvec^n)$ to the next time step $(\\uvec^{n+1},\\dot{\\uvec}^{n+1},\\ddot{\\uvec}^{n+1},\\dvec^{n+1})$. In the time-continuous model the weak elastic-damage dynamic wave equation \\eqref{eq:weakform} and the damage minimality condition \\eqref{eq:crackmin} are coupled in the first-order stability principle \\eqref{eq:vi}. After temporal discretization $\\uvec$ and $\\dvec$ evaluated at the last time step $t=t^n$ and the current time step $t=t^{n+1}$ are in general involved in an implicit fashion. However, we observe that the energy minimization principle \\eqref{eq:crackmin} for damage is not a genuine time evolution problem since time dependence is only introduced via the irreversibility condition. After a temporal discretization \\eqref{eq:crackdis} at time $t=t^{n+1}$ reads\n\\begin{equation} \\label{eq:crackstdis}\nq_{\\,\\uvec^{n+1}}(\\dvec^{n+1})\\leq q_{\\,\\uvec^{n+1}}(\\underline{\\vec{\\beta}}) \\text{ for all $\\underline{\\vec{\\beta}}$ that $0\\leq\\dvec^n\\leq\\underline{\\vec{\\beta}}\\leq 1$}\n\\end{equation}\nwhere the Hessian matrix and the second member vector in \\eqref{eq:Hb} are evaluated at $\\uvec^{n+1}$. The equation \\eqref{eq:crackstdis} can be interpreted as a numerical minimization problem of the quadratic functional $q$ under the irreversible constraint that the current sought damage state $\\dvec^{n+1}$ is pointwise within the bound $[\\dvec^n,1]$\n\\begin{equation} \\label{eq:cracknummin}\n\\dvec^{n+1}=\\operatorname{arg min}q_{\\,\\uvec^{n+1}}(\\cdot)\\text{ subject to the constraints $0\\leq\\dvec^n\\leq\\dvec^{n+1}\\leq 1$}.\n\\end{equation}\nThe next damage state $\\dvec^{n+1}$ can thus be accurately calculated as long as the next deformation state $\\uvec^{n+1}$ is known.\n\nIt remains then to specify the temporal discretization method used for the $\\vec{u}$-problem. In this work we adopt the classical second-order accurate Newmark-$\\beta$ integrator, which assumes the following time-stepping procedure\n\\begin{align}\n\\dot{\\uvec}^{n+1} &= \\dot{\\uvec}^n+\\frac{\\Delta t}{2}\\left(\\ddot{\\uvec}^n+\\ddot{\\uvec}^{n+1}\\right)\\,, \\label{eq:un2} \\\\\n\\uvec^{n+1} &= \\uvec^n+\\Delta t\\dot{\\uvec}^n+\\frac{1-2\\beta}{2}\\Delta t^2\\ddot{\\uvec}^n+\\beta\\Delta t^2\\ddot{\\uvec}^{n+1}. \\label{eq:un1}\n\\end{align}\nThe implicit method $0<\\beta\\leq\\frac{1}{2}$ may be suitable for intermediate situations between a quasi-static and an explicit dynamic calculation. In the present work it will be used to numerically investigate the quasi-static limit of the dynamic model, see \\cref{sec:antiplane}. The explicit method $\\beta=0$ with a lumped mass matrix $\\overline{\\vec{M}}$ should be preferred mainly in terms of computational efficiency for applications where the loading speed or the crack propagation speed is comparable to the material sound speed, since in general the time scale involved is typically of order $\\mathcal{O}(\\SI{1}{ms})\\ll\\mathcal{O}(\\SI{1}{s})$. The explicit method is conditionally stable. The constraint prescribed on the current time increment $\\Delta t$ is often determined by the CFL condition $\\Delta t<\\Delta t_\\mathrm{CFL}=\\min(h/c)$ where $h$ is the mesh size, $c$ is the material sound speed and the smallest value is chosen among all elements. This is not a very inconvenient feature since in the presence of high geometrical and material nonlinearities even unconditionally stable implicit schemes need a small time increment comparable to $\\Delta t_\\mathrm{CFL}$. In the calculation of the material sound speed, the current damage state $\\alpha_t$ as well as the tension-compression split formulation \\eqref{eq:elasticTC} is taken into account. Thus a totally damaged element under tension does not penalize the total computational time.\n\nThe spatially discretized elastic-damage equation reads\n\\begin{equation} \\label{eq:waveeqsdistdis}\n\\vec{M}\\ddot{\\uvec}^{n+1}=\\vec{F}_\\mathrm{ext}^{n+1}-\\vec{F}_\\mathrm{int}(\\uvec^{n+1},\\dvec^{n+1}).\n\\end{equation}\nIt can be seen that the determination of the the new acceleration $\\ddot{\\uvec}^{n+1}$ requires the knowledge of the new deformation state $\\uvec^{n+1}$ which itself determines the new damage field at time $t=t^{n+1}$ via \\eqref{eq:cracknummin}. For the implicit Newmark method $\\beta\\neq 0$, \\eqref{eq:un1} can thus be regarded as a nonlinear equation in $\\uvec^{n+1}$, where nonlinearity results from the irreversibility condition when minimizing the total energy \\eqref{eq:cracknummin}. To decouple the $(\\uvec^{n+1},\\dvec^{n+1})$ problem, we use a staggered time-stepping procedure as used in \\cite{Bourdin:2011,BordenVerhooselScottHughesLandis:2012,HofackerMiehe:2012} among others. The idea is to update the acceleration $\\ddot{\\uvec}^{n+1}$ while fixing the damage state at its \\emph{previous} known value $\\dvec^n$. Hence \\eqref{eq:waveeqsdistdis} becomes\n\\begin{equation} \\label{eq:waveeqsdistdis2}\n\\vec{M}\\ddot{\\uvec}^{n+1}\\approx\\vec{F}_\\mathrm{ext}^{n+1}-\\vec{F}_\\mathrm{int}(\\uvec^{n+1},\\dvec^n).\n\\end{equation}\nWhen a relatively small time-step is used, it is expected that the damage increment $\\dvec^{n+1}-\\dvec^n$ is bounded and the staggered time-discrete model will converge to the continuous one, cf. \\cite{LarsenOrtnerSuli:2010}. Introducing the displacement prediction at time $t=t^{n+1}$\n\\[\n\\tilde{\\uvec}^{n+1}=\\uvec^n+\\Delta t\\dot{\\uvec}^n+\\frac{1-2\\beta}{2}\\Delta t^2\\ddot{\\uvec}^n\\,,\n\\]\nfrom \\eqref{eq:un1} we obtain the equation for $\\uvec^{n+1}$\n\\begin{equation} \\label{eq:getuvecnp1}\n\\vec{M}\\frac{\\uvec^{n+1}-\\tilde{\\uvec}^{n+1}}{\\Delta t^2}=\\beta\\bigl(\\vec{F}_\\mathrm{ext}^{n+1}-\\vec{F}_\\mathrm{int}(\\uvec^{n+1},\\dvec^n)\\bigr).\n\\end{equation}\nIn general due to the use of tension-compression asymmetry models \\eqref{eq:elasticTC}, it is a nonlinear equation which requires several Newton iterations and the evaluation of the current tangent stiffness. The time-stepping procedure for the dynamic gradient damage model based on the implicit Newmark-$\\beta$ method in a prediction-correction form is summarized in \\cref{algo:implicit}.\n\\begin{algorithm}[htbp]\n\\caption{Staggered time-stepping procedure for the dynamic gradient damage model based on the implicit Newmark-$\\beta$ method} \\label{algo:implicit}\n\\begin{algorithmic}[1]\\linespread{1.2}\\selectfont\\normalsize\n\\For{every successive time step $n\\geq 0$}\n  \\State Prediction $\\tilde{\\uvec}^{n+1}=\\uvec^n+\\Delta t\\dot{\\uvec}^n+\\frac{1-2\\beta}{2}\\Delta t^2\\ddot{\\uvec}^n$.\n  \\State Prediction $\\tilde{\\underline{\\vec{v}}}^{n+1}=\\dot{\\uvec}^n+\\frac{\\Delta t}{2}\\ddot{\\uvec}^n$.\n  \\State Solve $\\uvec^{n+1}$ via \\eqref{eq:getuvecnp1}.\n  \\State Update $\\ddot{\\uvec}^{n+1}=(\\uvec^{n+1}-\\tilde{\\uvec}^{n+1})/(\\beta\\Delta t^2)$.\n  \\State Update $\\dot{\\uvec}^{n+1}=\\tilde{\\underline{\\vec{v}}}^{n+1}+\\frac{\\Delta t}{2}\\ddot{\\uvec}^{n+1}$.\n  \\State Solve $\\dvec^{n+1}$ via \\eqref{eq:cracknummin}.\n\\EndFor\n\\end{algorithmic}\n\\end{algorithm}\n\n\\begin{remark}\nAfter temporal discretization, the elastic-damage dynamic wave equation \\eqref{eq:weakform} and the damage minimality condition \\eqref{eq:crackmin} can also be solved in a monolithic fashion inside a nonlinear Newton solver described for example in \\cite{BordenVerhooselScottHughesLandis:2012,SchlueterWillenbuecherKuhnMueller:2014}. The irreversible condition contained in \\eqref{eq:cracknummin} should be included in the monolithic solver to ensure that the damage variable is subject to a bound constraint during solving. Future work could be devoted to a detailed analysis of these schemes in terms of computational efficiency.\n\\end{remark}\n\n\\begin{remark}\nIn the staggered time-stepping procedure, the approximation $\\ddot{\\uvec}^{n+1}\\approx\\ddot{\\uvec}^{n}$ simplifies the coupled solving of the displacement and the damage. However, we admit that the $(\\uvec^{n+1},\\dvec^{n+1})$ couple obtained at the end of the current time step do not necessarily satisfy the weak elastic-damage dynamic wave equation \\eqref{eq:weakform} and the damage minimality condition \\eqref{eq:crackmin}. Following the alternate minimization procedure common for quasi-static models, see \\cite{PhamAmorMarigoMaurini:2011}, several alternate iterations could also be performed here until convergence. However in dynamics, since the time-step is in general close to the critical time-step (\\emph{i.e.} very small), convergence could be reached within the first iteration. In any case when $\\Delta t\\to 0$, the discrete staggered model converges to the continuous one, see the remark given at the end of this section.\n\\end{remark}\n\nIn the explicit case when $\\beta=0$, it turns out that the time evolution system in $(\\uvec,\\dvec)$ is automatically decoupled and the two subproblems separately in $\\uvec^{n+1}$ and in $\\dvec^{n+1}$ can be solved in a sequence at every time step, see \\cref{fig:updatestate}.\n\\begin{figure}[htbp]\n\\centering\n\\[\n\\xymatrix{ & \\vec{H}(\\uvec^{n+1}) \\ar[dr] & & & & & \\\\\n\\uvec^{n+1} \\ar[ur] \\ar[r] & \\vec{b}(\\uvec^{n+1}) \\ar[r] & \\dvec^{n+1} \\ar[r] & \\vec{F}_\\mathrm{int}(\\uvec^{n+1},\\dvec^{n+1}) \\ar[r] & \\ddot{\\uvec}^{n+1} \\ar[r] & \\dot{\\uvec}^{n+3/2} \\ar[r] & \\uvec^{n+2} \\\\\n& \\dvec^n \\ar[ur] & & \\vec{F}_\\mathrm{ext}^{n+1} \\ar[ur] & \\dot{\\uvec}^{n+1/2} \\ar[ur] & \\uvec^{n+1} \\ar[ur] &}\n\\]\n\\caption{Updating flow of the explicit time-stepping procedure for the discretized dynamic gradient damage model at the time step $t^{n+1}$}\n\\label{fig:updatestate}\n\\end{figure}\nIndeed according to \\eqref{eq:un1}, the current displacement state $\\uvec^{n+1}$ can be directly determined from the previous kinematic states, which itself determines then the damage state via \\eqref{eq:cracknummin}. Introducing the middle-step velocity\n\\[\n\\dot{\\uvec}^{n+1/2}=\\dot{\\uvec}^n+\\frac{\\Delta t}{2}\\ddot{\\uvec}^n\\,,\n\\]\nthe Newmark time-stepping \\eqref{eq:un2} and \\eqref{eq:un1} reads\n\\begin{align*}\n\\uvec^{n+1} &= \\uvec^n+\\Delta t\\dot{\\uvec}^{n+1/2}\\,, \\\\\n\\dot{\\uvec}^{n+1} &= \\dot{\\uvec}^{n+1/2}+\\frac{\\Delta t}{2}\\ddot{\\uvec}^{n+1}\\,, \\\\\n\\dot{\\uvec}^{n+1/2} &= \\dot{\\uvec}^{n-1/2}+\\Delta t\\ddot{\\uvec}^{n}.\n\\end{align*}\nThe explicit time-stepping procedure for the discretized dynamic gradient damage model is then summarized in \\cref{algo:explicit}. It is implemented by the author in the explicit dynamics software EPX, see \\cite{EPX:2015}.\n\\begin{algorithm}[htbp]\n\\caption{Explicit time-stepping procedure for the dynamic gradient damage model} \\label{algo:explicit}\n\\begin{algorithmic}[1]\\linespread{1.2}\\selectfont\\normalsize\n\\For{every successive time step $n\\geq 0$}\n  \\State Update $\\dot{\\uvec}^{n+1/2}=\\dot{\\uvec}^{n}+\\frac{\\Delta t}{2}\\ddot{\\uvec}^n$.\n  \\State Update $\\uvec^{n+1}=\\uvec^n+\\Delta t\\dot{\\uvec}^{n+1/2}$.\n  \\State Solve $\\dvec^{n+1}$ via \\eqref{eq:cracknummin}.\n  \\State Solve $\\ddot{\\uvec}^{n+1}$ via \\eqref{eq:waveeqsdistdis} with the lumped mass matrix $\\overline{\\vec{M}}$.\n  \\State Update $\\dot{\\uvec}^{n+1}=\\dot{\\uvec}^{n+1/2}+\\frac{\\Delta t}{2}\\ddot{\\uvec}^{n+1}$.\n\\EndFor\n\\end{algorithmic}\n\\end{algorithm}\n\nThe initialization phase for the above implicit and explicit time-stepping procedure is described in \\cref{algo:init}. We observe that the initial damage is recomputed $\\dvec^{-1}\\mapsto\\dvec^0$ in the step 2. The role of $\\dvec^{-1}$ is to bring some \\emph{a priori} knowledge of the damage field resulting from a previous calculation or more frequently to represent an initial crack $\\dvec^{-1}=1$ on $\\Gamma_0$. This step thus renders it compatible with the initial displacement condition and the energy minimization structure. Remark that in phase field approaches for example in \\cite{BordenVerhooselScottHughesLandis:2012}, the initial crack is introduced via an initial history field $\\mathcal{H}_0$ which is localized along the desired initial defect. It is due to the fact that the irreversible constraint is dropped during energy minimization \\eqref{eq:crackmin} in their models.\n\\begin{algorithm}[htbp]\n\\caption{Initialization for the implicit and explicit time-stepping procedure described in \\cref{algo:implicit,algo:explicit}} \\label{algo:init}\n\\begin{algorithmic}[1]\\linespread{1.2}\\selectfont\\normalsize\n\\State Given initial conditions $\\uvec^0$, $\\dot{\\uvec}^0$ and $\\dvec^{-1}$.\n\\State Reinitialize the damage $\\dvec^0=\\operatorname{arg min}q_{\\,\\uvec^0}(\\cdot)$ subjected to constraints $0\\leq\\dvec^{-1}\\leq\\dvec^0\\leq 1$.\n\\State Initialize the acceleration $\\vec{M}\\ddot{\\uvec}^0=\\vec{F}_\\mathrm{ext}^0-\\vec{F}_\\mathrm{int}(\\uvec^0,\\dvec^0)$.\n\\end{algorithmic}\n\\end{algorithm}\n\n\\begin{remark}[Temporal convergence]\nRemark that only the irreversiblity condition $\\dot{\\alpha}_t\\geq 0$ and the variational inequality \\eqref{eq:vi} is effectively implemented. The former condition is reinforced during energy minimization \\eqref{eq:cracknummin}. It is shown in \\cite{LarsenOrtnerSuli:2010} that the time-discrete numerical model summarized by \\cref{algo:implicit,algo:explicit} will converge to the continuous model, \\emph{i.e.} \\cref{def:dynagraddama}. In particular, it will thus also balance energy as required in \\eqref{eq:dyngdeb}, when the time increment becomes small. Their constructive proof makes use of the implicit Euler scheme used in \\cite{Bourdin:2011}, however our experience suggests the same for the implicit and explicit Newmark schemes.\n\\end{remark}\n\n\\begin{remark}[Approximation of the Hencky logarithmic strain]\nAn approximation of the Hencky strain based on the following remarkable property established in \\cite{XiaoBruhnsMeyers:1997} can be used: within a proper corotational frame the rate of the Hencky strain equals the stretching tensor. An increment of the Hencky strain can thus be given by $\\Delta\\vec{h}^n\\approx\\symgrad(\\Delta\\vec{u}^n)$ where $\\symgrad$ denotes the symmetrized gradient operator and the displacement increment $\\Delta\\vec{u}^n=\\vec{u}^n-\\vec{u}^{n-1}$ is written in the current deformed configuration. To have better accuracy, a second-order approximation based on the incremental Almansi strain is used\n\\[\n\\Delta\\vec{h}^n\\approx\\frac{1}{2}\\bigl(\\nabla\\Delta\\vec{u}^n+\\nabla^\\mT\\Delta\\vec{u}^n-(\\nabla^\\mT\\Delta\\vec{u}^n)(\\nabla\\Delta\\vec{u}^n)\\bigr).\n\\]\nFinally the current Hencky strain is incremented $\\vec{h}^n=\\vec{h}^{n-1}+\\Delta\\vec{h}^n$.\n\\end{remark}\n\n\\section{Implementation} \\label{sec:implementation}\nThis section provides some details on the implementation of the discretized numerical model summarized by \\cref{algo:implicit,algo:explicit}. The thematic subjects covered here are thus summarized in \\cref{tab:summim}.\n\\begin{table}[htbp]\n\\centering\n\\caption{Thematic subjects covered in this section} \\label{tab:summim}\n\\begin{tabular}{ccccc} \\toprule\n& Going dynamical & $\\alpha\\leftrightarrow\\phi$ & $\\nabla\\alpha\\to\\Gamma$ & Experimental validation \\\\ \\midrule\nTheoretics & & & & \\\\\nNumerics & \\rightthumbsup & & & \\\\ \\bottomrule\n\\end{tabular}\n\\end{table}\n\n\\subsection{Numerical solving of the damage problem}\nIn this work, the damage energy minimization problem \\eqref{eq:cracknummin} will be directly solved at the structural scale. It could be converted into an equivalent local problem defined for each element. This possibility requires introduction of Lagrange multipliers at every Gauss points and an identification between the nodal damage field and the damage defined at Gauss points, see \\cite[p.~49]{Beaurain:2011}. The principal motivation of this kind of Lagriangian modeling is the ability in the software Code-Aster to impose more naturally the irreversibility condition, however the computational cost is higher due to additional unknown variables.\n\nConsequently, \\eqref{eq:cracknummin} can be regarded as a large scale bound-constrained minimization problem defined at the structural level. Due to the damage constitutive requirement, the problem is convex and gradient-based numerical algorithms can be applied. These methods call for the evaluation of the objective functional \\eqref{eq:Hb} as well as its first and second derivatives (Hessian matrix $\\vec{H}$). An efficient storage and manipulation of these objects is essential especially in an explicit dynamics context.\n\nHere the library PETSc is adopted due to its optimized efficiency, see \\cite{PETSc:2015}. As a high-level C++/Fortran numerical linear algebra backend, PETSc provides in particular the \\texttt{Vec} and the \\texttt{Mat} classes for defining vectors and matrices. The actual storage format is not fixed in advance and it suffices to call the function \\texttt{Vec/MatSetType} to affect a particular format. The computational arrays (the CSR format for example) can be extracted for output but in general all operations of these objects \\texttt{Vec}/\\texttt{Mat} are independent of the storage format used and thus transparent to the user. As an example, a unique interface is available to conduct a matrix-vector product\n\\begin{lstlisting}[language=Fortran]\nCALL MATMULT(H,X,GRAD,PETSCERR)\n\\end{lstlisting}\nwhere the vector \\texttt{GRAD} stocks the result of $\\vec{H}\\dvec$. PETSc is built on the Message Passing Interface (MPI) standard and only one generic version exists which can be run either in sequential or parallel. The calling functions are almost the same in both cases, thus the code could be parallelized with minor interface changes.\n\nSpecifically the Gradient Projection Conjugate Gradient (GPCG) algorithm proposed in \\cite{MoreToraldo:1991} is used to numerically solve \\eqref{eq:cracknummin} in an iterative fashion. It is already implemented in the TAO package of PETSc and is designed for quadratic bound-constrained minimization problems. Due to the bound constraint, approximate solutions $\\bvec$ to \\eqref{eq:cracknummin} can be defined using the projected gradient $[\\vec{g}]$ of which the $i$-th component is given by\n\\[\n0\\overset{?}{\\approx}[\\vec{g}]_i=\\begin{cases}\n\\partial_i q & \\text{if $\\bvec_i\\in(\\dvec_i^n,1)$}\\,, \\\\\n\\min(\\partial_i q, 0) & \\text{if $\\bvec_i=\\dvec_i^n$}\\,, \\\\\n\\max(\\partial_i q, 0) & \\text{if $\\bvec_i=1$}.\n\\end{cases}\n\\]\nAt each solving iteration, the method consists of several gradient projections\n\\[\n\\bvec\\gets\\mathbb{P}\\bigl(\\bvec-c\\nabla q(\\bvec)\\bigr)\n\\]\nto \\emph{approximately} identify the \\emph{active} nodes, \\emph{i.e.} those either $\\dvec_i^{n+1}=\\dvec_i^n$ or $\\dvec_i^{n+1}=1$. Note that here we perform a gradient descent followed by a projection $\\mathbb{P}$ onto the bound to ensure that $\\dvec^n\\leq\\bvec\\leq 1$. Then it applies the preconditioned conjugate gradient method to minimize an unconstrained reduced problem of the \\emph{free} variables, \\emph{i.e.} those satisfying $\\dvec_i^n<\\dvec_i^{n+1}<1$. The method proceeds to the next iteration until convergence. Interested readers are referred to \\cite{MoreToraldo:1991} for a more detailed explanation of the algorithm. The incomplete Cholesky factorization preconditioner is applied block-wise into each decomposed subdomain. Computational load is also well balanced in parallel computations based on domain decomposition, see \\cite{BensonMcInnesMore:2001}.\n\nUsing the PETSc library, both the implicit and explicit time-stepping \\cref{algo:implicit,algo:explicit} are implemented by the author as a Python package named ``FEniCS Dynamic Gradient Damage'', see \\cite{LiMaurini:2015}. It is based on the FEniCS Project \\cite{LoggMardalWells:2012} for automated solution of partial differential equations. A specific C++ interface \\texttt{PETScTAOSolver} is developed by the author which brings various mathematical optimization algorithms defined in PETSc/TAO into FEniCS. In this implementation the tension-compression asymmetry is not taken into account. A linearized strain theory is also assumed.\n\nThe explicit time-stepping procedure for the dynamic gradient damage model summarized in \\cref{algo:explicit} is also implemented in EPX by the author, an explicit dynamics program dedicated to transient phenomena involving fluid-structure interaction \\cite{EPX:2015}. Here all the tension-compression asymmetry models discussed in \\cref{sec:TC} are implemented. The large-displacement extension, see \\cref{sec:extensions}, is also by default activated in the software.\n\n\\subsection{Details of implementation in EPX} \\label{sec:epx}\n\\paragraph{Initialization}\nThe initialization \\texttt{INIT\\_ENDOGRAD} of the gradient damage model is performed at the end of the routine \\texttt{initia.ff}. It has several objectives\n\\begin{itemize}\n\\item Allocate various Fortran arrays needed in the model: the damage field \\texttt{ALPHA}, the damage dissipation energy for all elements \\texttt{EFISS}\\ldots\n\n\\item Initialize the PETSc solver and several objects: the minimization solver \\texttt{TAOSOLV}, the global Hessian matrix for damage \\texttt{HALPHA}, the PETSc viewer \\texttt{VIEWER} to have access to convergence information\\ldots\n\\end{itemize}\n\nTo guarantee a good efficiency when assembling sparse matrices, it is essential that we preallocate enough memory by indicating to PETSc the number of non-zero elements at every row of the matrix. In parallel, the non-zeros elements should be treated separately depending whether they appear in the diagonal or off the diagonal of the current processor. If this preallocation phase is omitted, PETSc will allocate the needed memory by calling \\texttt{PetscMalloc} every time it encounters a new unexpected non-zero term, which causes the execution time to increase significantly, see \\cite{PETSc:2015}. An overestimation of the sparse structure of the mesh connectivity is performed: for every node in the mesh, we consider all the elements containing that node and count the total node numbers possessed by these elements. Only one loop on all the elements is needed during the initialization. This overestimation does virtually no harm to the overall computational efficiency, as during the final assembly of matrices in PETSc, the routines \\texttt{MatAssemblyBegin/End} will be called to release all unnecessary preallocated memories.\n\nDuring a MPI parallel computation, a permutation of nodes is needed according to the PETSc convention described by the documentation of the routine \\texttt{MatMPIAIJSetPreallocation}. It is achieved during initialization by a loop on all the processors based on the mesh partition performed by EPX. At the end two integer Fortran arrays are provided: \\texttt{CONV\\_EP(I)} which gives the position of the $i$-th EPX node in the PETSc convention, while \\texttt{CONV\\_PE} converts the PETSc node ordering to the EPX one.\n\n\\paragraph{Time-stepping} The change to the EPX time iteration routines \\texttt{calcul.ff} and \\texttt{d\\_calcul.ff} is minimal. We simply add the following pseudo code concerning the assembly and the solving of the damage problem before the elastodynamics part.\n\\begin{lstlisting}[language=Fortran]\n...\nIF (L_ENDOGRAD) THEN\n  CALL SEQ/MPI_ASSEM_ALPHA(...)\n  CALL RESO_ALPHA(...)\nEND IF\n...\nCALL CELEM(...)\n...\n\\end{lstlisting}\n\nWe note that the routine \\texttt{SEQ/MPI\\_ASSEM\\_ALPHA} constructs the Hessian matrix $\\vec{H}$ and the second member $\\vec{b}$ associated to the quadratic damage minimization problem by performing a first loop on all the elements. The copy and the correspondence between the global damage vector and the local damage vector specific to each element are conducted without modifying the arguments of all existing routines: \\texttt{celem.ff}, \\texttt{loopelm.ff}, \\texttt{wpgen.ff} and all element routines \\texttt{triang.ff} for example. The elementary variables associated with the current element $\\alpha^\\mathrm{e}$, $\\vec{H}^\\mathrm{e}$ and $\\vec{b}^\\mathrm{e}$ are all stored globally inside the module \\texttt{m\\_endograd\\_data.ff}. They are preallocated during the initialization phase depending on the maximum local nodes. This current implementation is not thread-safe, thus OpenMP parallelization is not available.\n\n\\paragraph{Element routines} At every time step, the following two loops on elements are needed:\n\\begin{enumerate}\n\\item Knowing the current configuration $\\vec{x}^n$ and $\\vec{u}^n$, the routine \\texttt{SEQ/MPI\\_ASSEM\\_ALPHA} opens a first loop on elements to calculate the elementary matrices $\\vec{H}^\\me$ and vectors $\\vec{b}^\\me$ for the damage problem \\eqref{eq:cracknummin}. During this first loop, the current damage field is not yet known.\n\n\\item After energy minimization \\eqref{eq:cracknummin}, the current damage is solved in \\texttt{RESO\\_ALPHA}. We then open a loop for the second time in \\texttt{CELEM} on all the elements to calculate the internal force vector $\\vec{F}_\\mathrm{int}^\\me$ which depends on the current damage state.\n\\end{enumerate}\n\nSince it is needed to perform two loops on elements at every time step, the element routines should be carefully restructured to minimize the computational cost. Some logical indicators are specially used and introduced to partition the code:\n\\begin{itemize}\n\\item \\texttt{MATPRI(NTH) == 115} indicates if the current element is affected by a gradient damage material. If so, the following two logical indicators are then relevant.\n\n\\item \\texttt{L\\_FIRSTLOOP} encloses the lines that should be run during the calling of \\texttt{SEQ/MPI\\_ASSEM\\_ALPHA}, \\emph{i.e.} in order to calculate the elementary matrices $\\vec{H}^\\me$ and vectors $\\vec{b}^\\me$ for the damage problem. In particular, the strain tensor will be calculated at this stage via \\texttt{DSDX2D} or \\texttt{DSDX3D}. The tension-compression asymmetry is also performed here to calculate $\\sig_0^+$ and $\\sig_0^-$. The positive stress is stored temporarily in the \\texttt{SIG} array while the negative stress in the \\texttt{ECR} vector.\n\n\\item \\texttt{L\\_SECONDLOOP} encloses the lines that should be run during the calling of \\texttt{CELEM} where the stress tensor and the internal force vector $\\vec{F}_\\mathrm{int}^\\me$ will be calculated. In particular the stress tensor will be updated via \\eqref{eq:stressposneg}\n\\end{itemize}\n\n\\paragraph{Improved method of calculating eigenvalues}\nFor the tension-compression asymmetry model described in \\cite{MieheHofackerWelschinger:2010,FreddiRoyer-Carfagni:2010}, we need to perform the spectral decomposition of the strain tensor, see for example \\cref{algo:epspos3d,algo:epspos2d}. The \\texttt{DSYEV} routine of LAPACK is purely numerical (iterative method) and consequently robust but slow. Here we use and implement an analytical method described in \\cite{Scherzinger:2008aa} that is both robust (in the presence of two or three identical or near eigenvalues) and computationally efficient. Consider the problem\n\\[\n\\vec{A}\\approx\\mathbb{I}=\\begin{bmatrix}\n1 & &  \\\\\n& 1+\\frac{\\epsilon}{4} & \\frac{3\\sqrt{\\epsilon}}{4} \\\\\n& \\frac{3\\sqrt{\\epsilon}}{4} & 1+\\frac{3\\epsilon}{4}\n\\end{bmatrix}\n\\]\nwith $\\epsilon=\\num{1e-7}$. Theoretical solution $(d_i,\\vec{v}_i)$ is given by\n\\begin{equation} \\label{eq:eigenvalueana}\n\\begin{aligned}\n& d_1=1+\\epsilon\\,,\\quad d_2=d_3=1, \\\\\n& \\vec{v}_1=(0, 1/2, \\sqrt{3}/2)\\,,\\quad \\vec{v}_2=(-1, 0, 0)\\quad\\text{and}\\quad\\vec{v}_3=(0, \\sqrt{3}/2, -1/2).\n\\end{aligned}\n\\end{equation}\n\nThe analytical solution \\eqref{eq:eigenvalueana} is compared with the numerical ones given by \\texttt{DSYEV} and the method described in \\cite{Scherzinger:2008aa}:\n\\begin{itemize}\n\\item \\texttt{DSYEV}: 15 significant figures for eigenvalues and eigenvectors, within \\SI{63.7}{s} for \\num{1e8} calculations.\n\\item New method: 15 significant figures for eigenvalues and 10 for eigenvectors, within \\SI{23.5}{s} for \\num{1e8} calculations.\n\\end{itemize}\nAs can be seen, a factor of 2.7 in time is gained.\n\n\\section*{Summary of this Chapter}\nIn this chapter we describe a direct numerical implementation of the dynamic gradient damage model. It applies to both 1-d, 2-d and 3-d physical problems. Its efficiency will be demonstrated via simulation results in \\cref{chap:simulation}. The spatial discretization is based on classical $C^0$ finite element method and is presented in \\cref{sec:spatial}. It is decoupled from the time-stepping scheme described in \\cref{sec:timedis} for the $\\vec{u}$-problem governed by the discrete elastic-damage dynamic wave equation \\eqref{eq:waveeqsdistdis}. The explicit Newmark method will be used whenever inertial effects are dominant. Implicit methods parametrized by the $\\beta$-parameter are applied for intermediate cases between explicit dynamic and quasi-static situations. Due to the same mathematical structure for the damage problem (bound-constrained convex optimization problem), \\eqref{eq:cracknummin} is solved at the structural scale similarly to the quasi-static settings. The discrete numerical model is summarized in \\cref{algo:implicit,algo:explicit}.\n\nThe computational architecture is summarized in \\cref{sec:implementation}. The numerical solving of the damage problem is based on the numerical linear algebra library PETSc. It is introduced to the explicit dynamics software EPX for storage and manipulation of sparse matrices and vectors. The Gradient Projection Conjugate Gradient method is used to numerically solve \\eqref{eq:cracknummin}.", "meta": {"hexsha": "50efefeb8c86de7c89532fa53c2516bf5cdf9cec", "size": 43090, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ressources/example/litianyi-thesis-manuscript-a7b94b463ca5/chapters/numerics.tex", "max_stars_repo_name": "antoinetavant/PhD_thesis_manuscript", "max_stars_repo_head_hexsha": "1fdaf99356f75abc488edf1f30b5dd65f22bcdca", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-10-16T01:38:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-31T08:26:20.000Z", "max_issues_repo_path": "chapters/numerics.tex", "max_issues_repo_name": "tianyikillua/thesis-manuscript", "max_issues_repo_head_hexsha": "3d41f049377aed4e987756811b5b6a232e5af514", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/numerics.tex", "max_forks_repo_name": "tianyikillua/thesis-manuscript", "max_forks_repo_head_hexsha": "3d41f049377aed4e987756811b5b6a232e5af514", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 120.0278551532, "max_line_length": 1458, "alphanum_fraction": 0.7669760965, "num_tokens": 12227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.3106163408055177}}
{"text": "\\chapter{{\\bf Summary and Outlook}}\n\\label{sec:summaryandoutlook}\n\n\\section{Summary}\nThe LHCb experiment was built to test the predictions of the SM and search for NP effects through the study of $\\mathcal{CP}$ violating and rare decays of $b$-hadrons. So far measurements performed using the LHCb experiment, and other LHC experiments, have not revealed conclusive evidence for NP effects, although some interesting anomalies have been seen in measured results in heavy flavour physics~\\cite{PhysRevLett.118.111801,Aaij:2014pli, Aaij:2015oid, ATLAS-CONF-2017-023,CMS-PAS-BPH-15-008,Aaij:2015esa,PhysRevLett.113.151601,Aaij:2017vbb,Aaij:2015yra,Huschle:2015rga, Lees:2012xj,Lees:2013uzd, Sato:2016svk,Altmannshofer:2017yso,Capdevila:2017bsm,Amhis:2016xyh}. \n%~\\cite{PhysRevLett.118.111801,Aaij:2014pli,Aaij:2015yra,Lees:2013uzd,Huschle:2015rga,Lees:2012xj,Aaij:2015oid,Aaij:2015esa,PhysRevLett.113.151601, R_K_star}. %show no significant deviations from predictions and confirm the predictive power of the SM. \nThe search for \\bmumu decays was identified as one of the key measurements to be made with the LHCb experiment~\\cite{Adeva:2009ny} as an indirect search for NP.\nIn 2011 LHCb joined the search for these decays, that began over 30 years ago, using the unprecedented energies available at the LHC. The first evidence for \\bsmumu decays was found by the LHCb experiment with 2.1 \\fb of Run~1 data from $pp$ collisions~\\cite{Aaij:2012nna}. A combined analysis of the Run~1 data from the CMS and LHCb experiments produced the first observation of \\bsmumu decays and the first evidence for \\bdmumu decays~\\cite{CMS:2014xfa}. The measured branching fractions of these decays are consistent with the SM predictions and place constraints on BSM theories. However, the precision of the measurements still leaves room for NP effects to be revealed, therefore it is important to improve the precision of the \\BF measurements. With the observation of the \\bs mode the search for \\bsmumu decays is complete and properties of this decay, including the effective lifetime, can now be studied. The effective lifetime offers a new observable to test the SM in \\bsmumu decays that is complementary to the \\BF. \n\nThe measurements of the \\bmumu \\BFs and the \\bsmumu effective lifetime with 4.4~\\fb of Run~1 and Run~2 data collected by the LHCb experiment are presented in this dissertation. Figure~\\ref{fig:BDT} shows a summary of the fit used to measure the \\bmumu \\BFs for candidates in Run~1 and Run~2 data with a global BDT value of BDT > 0.5. The measured \\BFs are\n\\begin{equation}\n%\\begin{align}                                                                            \n\\begin{split}\n  \\mathcal{B}(B^{0}_{s} \\to \\mu^{+} \\mu^{-}) &= (3.0 \\pm 0.6^{+0.3}_{-0.2}) \\times 10^{-9\\\n} \\\\\n  \\mathcal{B}(B^{0} \\to \\mu^{+} \\mu^{-}) &= (1.5^{+1.2 +0.2}_{-1.0 -0.1})    \\times 10^{-\\\n10}.\n%\\end{align}                                                                              \n\\end{split}\n\\label{eq:BFresults2}\n\\end{equation}\nThe \\bs mode is observed with a statistical significance of 7.8$\\sigma$, making this result the first single experiment observation of this decay and the most precise measurement to date. The \\bd mode has a significance of 1.6$\\sigma$, therefore a limit is placed on the \\BF of $\\mathcal{B}$(\\bdmumu)$ < 3.4 \\times 10^{-10}$ at the 95$\\%$ confidence level. The measured values are consistent with the SM predictions. %and Figure~\\ref{fig:BDT} shows \\bmumu candidates with a global BDT value of BDT > 0.5. %plot of Bd bv Bs?? with the others superimposed?\n\\begin{figure}[tbp]\n    \\centering\n        \\includegraphics[width=0.8\\textwidth]{./Figs/Summary/BDT_plot.pdf}\n    \\caption{\\bmumu candidates with a global BDT value of BDT > 0.5 in 4.4~\\fb of Run~1 and Run~2 data collected by the LHCb experiment and the mass fit used to measure the \\bmumu \\BFs overlaid.}\n    \\label{fig:BDT}\n\\end{figure}\n\nThe effective lifetime of \\bsmumu decays is measured for the first time to be \n\\begin{equation}\n\\tau_{\\mu\\mu} = 2.04 \\pm 0.44 \\pm 0.05 \\text{ ps},\n\\end{equation}\nwhich is within 1.0$\\sigma$ of the SM prediction. The result is consistent with \\ADG = +1 hypothesis at 1.0$\\sigma$ and with \\ADG = $-1$ hypothesis at 1.4$\\sigma$. Although the current precision of the measurement does not enable constraints to be placed on BSM theories it is important to illustrate the ability of the LHCb experiment to make this measurement.\n\nThe measured values of the \\BF presented in this dissertation have already been used to help constrain parameters in BSM theories~\\cite{Altmannshofer:2017wqy,Fleischer:2017ltw,Bobeth:2017xry,Chiang:2017etj}. \nThe possible values available for the parameters $P$ and $S$, defined in Section~\\ref{sec:BFdef}, are shown in Figure~\\ref{fig:NPcontss}, where the values are constrained from the \\BF results in Equation~\\ref{eq:BFresults2} and the results from the CMS collaboration in reference~\\cite{Chatrchyan:2013bka}. The current measurements produce a circular band of possible $P$ and $S$ values, and a precise measurement of \\ADG through the \\bsmumu \\el will help resolve the ambiguities.\n\n\n\\begin{figure}[tbp]\n    \\centering\n        \\includegraphics[width=0.7\\textwidth]{./Figs/Summary/fig3.pdf}\n    \\caption{Constraints in the $P$ - $S$ plane where $P$ and $S$ are defined in Section~\\ref{sec:BFdef}. The blue band corresponds to constraints from the \\bmumu \\BF measurements presented in this dissertation and the CMS experiment Run~1 results in reference~\\cite{Chatrchyan:2013bka}. The dashed lines show different values for \\ADG and the constraints assume $\\varphi_{P}, \\varphi_{S}\\in {0, \\pi}$. The figure is taken from~\\cite{Fleischer:2017ltw}.}\n    \\label{fig:NPcontss}\n\\end{figure}\n\n\n\\section{Outlook}\nThe measured values of the branching fractions and the effective lifetime still leave plenty of room for NP effects to be observed with these decays. At the end of Run~2 of the LHC, the LHCb dataset will have almost doubled to 8~\\fb, enabling the precision of these measurements to be improved. Looking further ahead, LHCb is expected to collect 50~\\fb of data by the end of Run~4 and with the high luminosity LHC up to 300~\\fb could be recorded. \n\nWith more data, the expected precision of the \\BF measurements is expected to be reduced to $\\sim 0.19 \\times 10^{-9}$ with 50~\\fb~\\cite{LHCb-PUB-2014-040}. Not only are the \\BF measurements in themselves interesting to test the SM but the ratio of the \\BFs of the two modes is also useful to test the SM, in particular the MFV hypothesis. The current precision of the ratio of \\BFs is $\\sim 60\\%$~\\cite{CMS:2014xfa}, and future runs of the LHC will enable the precision of the ratio of \\BFs to be reduced to 40$\\%$ with 50~\\fb of $pp$ data and 20$\\%$ with 300~\\fb of data~\\cite{Aaij:2244311}. \n\nThe expected uncertainty achievable by the LHCb experiment for the \\el at the end of Run~2 and after future runs of the LHC is estimated using pseudoexperiments based on the observed numbers of decays with 4.4~\\fb and the current measurement strategy. At the end of Run~2, with 8~\\fb, the median uncertainty of the \\el will be $\\sim$0.2 \\ps which is reduced to $\\sim$0.08~\\ps with 50~\\fb and $\\sim$0.03~\\ps with 300~\\fb. Therefore, with 300~\\fb the precision on the effective lifetime will enable \\ADG = +1 to be distinguished from \\ADG = $-1$ with a statistical significance of 5$\\sigma$. The expected mass and decay time distributions for 8, 50 and 300~\\fb are shown in Figure~\\ref{fig:expected_dist}. The expected uncertainties for the \\el measurement are conservative estimates because they are based on the current measurement strategy which was designed for low expected statistics. Therefore the precision of the measurement could be much better as different analysis methods can be taken advantage of with more statistics. \n\n\n\\begin{figure}[tbp]\n    \\centering\n        \\includegraphics[width=0.49\\textwidth]{./Figs/Summary/8fb_mass.pdf}\n        \\includegraphics[width=0.49\\textwidth]{./Figs/Summary/8fb_time.pdf}\n        \\includegraphics[width=0.49\\textwidth]{./Figs/Summary/50fb_mass.pdf}\n        \\includegraphics[width=0.49\\textwidth]{./Figs/Summary/50fb_time.pdf}\n        \\includegraphics[width=0.49\\textwidth]{./Figs/Summary/300fb_mass.pdf}\n        \\includegraphics[width=0.49\\textwidth]{./Figs/Summary/300fb_time.pdf}\n    \\caption{The expected mass and decay time distributions for \\bsmumu candidates to measure the \\el with 8, 50 and 300~\\fb. The signal and background yields are determined from the observed number of \\bsmumu and combinatorial background decays and the expected number of mis-identified backgrounds and \\bdmumu decays in 4.4~\\fb of Run~1 and Run~2 data.}\n    \\label{fig:expected_dist}\n\\end{figure}\n\n\n\n\n\nThe current systematic uncertainty on the \\el is 0.05 \\ps which is too large to allow possible NP effects to be observed. However, several components contributing to the total, such as the fit accuracy and the acceptance function systematic, will be reduced with the availability of more data enabling greater precision on the measurement. With more data, an alternative analysis approach could be used which would reduce the systematic uncertainties on the \\el; the selection criteria can be designed so that it does not bias \\bsmumu decay time distribution, therefore removing the need for an acceptance function and the associated systematic.\n%Do I want to include more discussion on this?? Or prehaps add as a appendix? I don't think a long discussion will add much here but prehaps the details could be useful or someone will ask about it ....\n\n\nThe study of \\bmumu decays has been in progress for over 30 years and with the energy and luminosity available at the LHC, the study of these decays is just as interesting as it ever was. As more data is collected by the LHCb experiment NP effects will have less and less space to hide. It will either be seen in \\bmumu decays or these decays will place ever tighter constraints on BSM theories. \n", "meta": {"hexsha": "cafd499631efade284e8425c32ac087feffe5fbc", "size": 9972, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Summary/summary.tex", "max_stars_repo_name": "haevans/Thesis", "max_stars_repo_head_hexsha": "f930fcb2d9682beae829f11fe7c7fce4caeaee33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Summary/summary.tex", "max_issues_repo_name": "haevans/Thesis", "max_issues_repo_head_hexsha": "f930fcb2d9682beae829f11fe7c7fce4caeaee33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Summary/summary.tex", "max_forks_repo_name": "haevans/Thesis", "max_forks_repo_head_hexsha": "f930fcb2d9682beae829f11fe7c7fce4caeaee33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-02-19T16:03:23.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-19T16:03:23.000Z", "avg_line_length": 129.5064935065, "max_line_length": 1031, "alphanum_fraction": 0.754713197, "num_tokens": 2775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3106163408055177}}
{"text": "\\chapter{Yield extraction}\n\\label{chap:prod:fitting}\n\nSignal charm mesons can be distinguished from combinatorial background in the \ninvariant mass distribution, as shown in \\cref{fig:prod:sel:D0ToKpi:offline} \nfor example.\nHowever, the contributions from prompt and secondary charm are identical in the \ninvariant mass, and so another distribution must be used to distinguish between \nthe two sources of charm decays.\n\nThis analysis uses the logarithm of the \\chisq\\ of the \\acl{IP}, \\lnipchisq, to \nobtain the prompt charm yields.\nThe momentum vector of prompt charm should point back to the \\ac{PV}, and so \nthe \\lnipchisq\\ distribution is expected be centred around zero.\nFor secondary charm the \\lnipchisq\\ distribution is expected to peak at higher \nvalues.\nThis separation is exploited to distinguish between prompt and secondary charm, \nwhere the prompt signal yield in each \\pTy\\ bin is measured by a binned, \nextended maximum likelihood fit to the \\lnipchisq\\ distribution.\nThe prompt and secondary models in this fit are described analytically as \npeaking functions.\nThe combinatorial background is described by a non-parametric model taken from \nthe data outside the signal peak in the mass distribution.\nThis background model is normalised in the \\lnipchisq\\ fit to the number of \ncombinatorial background candidates in a signal window defined in the mass \ndistribution, measured in a fit to the charm hadron mass spectrum.\n\nFor all cases but the \\PDstarp\\ measurement, it is the mass of the charm hadron \nthat is used to discriminate all signal from combinatorial background.\nFor the \\PDstarp\\ measurement, the delta mass distribution is used instead, \ndefined as the difference \\deltam\\ between the reconstructed \\PDstarp\\ mass and \nthe reconstructed \\PDzero mass\n\\begin{equation}\n  \\deltam = m(\\PKminus\\Ppiplus\\Ppiplussoft) - m(\\PKminus\\Ppiplus).\n  \\label{eqn:prod:fitting:delta_mass}\n\\end{equation}\nThis has a nominal value of \\SI{145.4}{\\MeVcc}~\\cite{PDG2014}.\nThe narrower signal peak allows for a better signal-to-background ratio.\n\n\\section{Signal-background discrimination}\n\\label{chap:prod:fitting:mass}\n\nFor each one-dimensional mass and \\deltam\\ fit, one PDF is defined per \ndiscriminatory species: signal and combinatorial background.\nIn both the mass and \\deltam\\ distributions, the prompt and secondary signal \nshapes are assumed to be identical, and for the \\deltam\\ fits the combinatorial \nbackground is assumed to be indistinguishable from random soft pion \nbackgrounds, where a true \\PDzero is combined with a random track in the event.\nThe total \\ac{PDF} is constructed as the sum of the per-species \\acp{PDF}, each $f_{s}$, \neach weighted by the respective yield $N_{s}$\n\\begin{align}\n  f(m) &= \\frac{1}{\\sum_{\\textnormal{s}} N_{\\textnormal{s}}}\n          \\sum_{\\textnormal{s}} N_{\\textnormal{s}}\n          f_{\\textnormal{s}}(m),\\\\\n  f(\\deltam) &= \\frac{1}{\\sum_{\\textnormal{s}} N_{\\textnormal{s}}}\n                \\sum_{\\textnormal{s}} N_{\\textnormal{s}}\n                f_{\\textnormal{s}}(\\deltam).\n\\end{align}\n\nFor every mass fit, the background PDF $f_{\\textnormal{Bkg.}}(m)$ is taken to \nbe a first-order polynomial, and the signal PDF $f_{\\textnormal{Sig.}}(m)$ is \ndependent on the charm hadron candidate, with details given in \nSection~\\ref{chap:prod:fitting:details}.\nThe combinatorial and random soft pion background in the \\deltam\\ fits are \nmodelled as a single empirical threshold function of the (un-normalised) form\n\\begin{equation}\n  % (dm - dm0)^A * exp(B*dm)\n  % The exponential factor has been omitted, as we just set B = 0\n  R(x; \\deltam_{0}, A) = {(x - \\deltam_{0})}^A,\n\\end{equation}\nwhere $\\deltam_{0}$ is the threshold value, fixed to the charged pion rest mass \n$m_{\\Ppipm} = \\SI{139.57}{\\MeVcc}$~\\cite{PDG2014}.\nThe signal PDF in \\deltam\\ is the sum of three normal distributions, sharing a \ncommon mean but allowed to have different widths.\n\nOne mass or \\deltam\\ PDF, $f(m)$ or $f(\\deltam)$, is constructed per \\pTy\\ bin, \nand the likelihood is formed as the product of these such that each PDF is \nfitted simultaneously when the \\ac{NLL} is minimised.\n\n\\section{Prompt-secondary discrimination}\n\\label{chap:prod:fitting:ipchisq}\n\nThe prompt and secondary signal distributions are modelled by continuous, \nparametric \\acp{PDF}.\nRather than attempting to parameterise the combinatorial background \ndistribution, a \\acf{KDE} \\ac{PDF}~\\cite{Poluektov:2014rxa}, or `template', is \ncreated from a histogram of the \\lnipchisq\\ distribution in the lower and upper \nsidebands of the reconstructed charm hadron mass.\nIn the case of the \\PDstarp measurements, the data in the upper sideband of the \n\\deltam\\ distribution are used instead.\nThis approach assumes that the mass and \\lnipchisq\\ are uncorrelated in the \nbackground sample, such that the \\lnipchisq\\ shape in the signal region is the \nsame as that in the sidebands.\n\nThe signal region in each long-lived charm hadron mass distribution is defined \nas a \\SI{40}{\\MeVcc}-wide window centred on the nominal rest mass of the given \ncharm hadron, taken to be \\SI{1864.84}{\\MeVcc}, \\SI{1869.61}{\\MeVcc}, and \n\\SI{1968.30}{\\MeVcc} for \\PDzero, \\PDplus, and \\PDsplus~\\cite{PDG2014}.\nThe lower sideband is a \\SI{20}{\\MeVcc}-wide window centred \\SI{50}{\\MeVcc} \nbelow the centre of the signal window, and the upper sideband is a \n\\SI{20}{\\MeVcc}-wide window centred \\SI{50}{\\MeVcc} above the centre of the \nsignal window.\nFor the \\PDstarp\\ measurements, the signal region is defined as a window \n\\SI{6}{\\MeVcc} wide, centred on the nominal \\deltam\\ value of \n\\SI{145.43}{\\MeVcc}~\\cite{PDG2014}.\nThe upper sideband, or just `sideband' as a lower sideband region is not \ndefined in \\deltam, is defined as the region from \\SI{4.5}{\\MeVcc} to \n\\SI{9}{\\MeVcc} above the centre of the signal region.\n\\Cref{fig:prod:fitting:regions_A,fig:prod:fitting:regions_B}\nshow the signal and sideband regions for each mode.\n\nThe integral of the \\lnipchisq\\ background template \\ac{PDF} is \nGaussian-constrained to the number of background candidates in the mass or \n\\deltam\\ signal region.\nTo avoid any complications due to correlations between the background template \n\\ac{PDF} and the fitted data, only the data in signal region are used in the \n\\lnipchisq\\ fit.\nFor the \\PDstarp\\ measurements, this signal region requirement is made in both \nthe \\PDzero mass and the \\deltam\\ distributions.\n\nFor each one-dimensional \\lnipchisq\\ fit, one \\ac{PDF} $f_{s}$ per \ndiscriminatory species is assigned: prompt signal, secondary signal, and \ncombinatorial background.\nThe total \\acp{PDF} are constructed as the sum of per-species \\acp{PDF}, \neach weighted by the respective yield $N_{s}$\n\\begin{equation}\n  f(\\lnipchisq) = \\frac{1}{\\sum_{\\textnormal{s}} N_{\\textnormal{s}}}\n                  \\sum_{\\text{s}} N_{\\text{s}}\n                  f_{\\text{s}}(\\lnipchisq).\n\\end{equation}\nThe constraint on the background yield \\nbkg\\ is applied by multiplying the \nlikelihood by a normal distribution in \\nbkg, whose mean is the number of \nbackground candidates measured by the mass fit and whose width is the \nuncertainty on that value.\nThis penalises the likelihood by reducing its value when the fitted \\nbkg\\ \nparameter is far away from the value found in the mass fit.\n\nOne \\lnipchisq\\ \\ac{PDF} and background constraint is constructed per \\pTy\\ \nbin, and the likelihood is formed as the product of these such that each \n\\ac{PDF} is fitted simultaneously when the negative log-likelihood is \nminimised.\nThe benefit of this construction is that some shape parameters can be shared \nacross bins, reducing the uncertainty on the fit parameters.\nWhich parameters are shared across bins and which are fitted independently is \ndependent on the type of charm meson.\nThe shared and independent parameters are enumerated in \n\\cref{chap:prod:fitting:details}.\n\nThe prompt signal model $H$ in the \\lnipchisq\\ distribution is a modified \nnormal distribution, where the width is allowed to be asymmetric with respect \nto the mean, and the tails are described by exponential functions,\n\\begin{equation}\n  H(x; \\mu, \\sigma, \\epsilon, \\rho_{L}, \\rho_{R}) =\n  \\begin{cases}\n    \\exp\\left(\\frac{\\rho_{L}^{2}}{2} + \\rho_{L}\\frac{x - \\mu}{(1 - \n    \\epsilon)\\sigma}\\right) & x < \\mu - (\\rho_{L}\\sigma(1 - \n        \\epsilon)), \\\\\n    \\exp\\left(-\\left(\\frac{x - \\mu}{\\sqrt{2}\\sigma(1 - \n    \\epsilon)}\\right)^{2}\\right) & \\mu - (\\rho_{L}\\sigma(1 - \\epsilon)) \n          \\leq x < \\mu, \\\\\n    \\exp\\left(-\\left(\\frac{x - \\mu}{\\sqrt{2}\\sigma(1 + \n    \\epsilon)}\\right)^{2}\\right) & \\mu \\leq x < \\mu + (\\rho_{R}\\sigma(1 + \n          \\epsilon)), \\\\\n    \\exp\\left(\\frac{\\rho_{R}^{2}}{2} - \\rho_{R}\\frac{x - \\mu}{(1 + \n    \\epsilon)\\sigma}\\right) & x \\geq \\mu + (\\rho_{R}\\sigma(1 + \n        \\epsilon)),\n  \\end{cases}\n  \\label{eqn:prod:fitting:ipchisq:signal_model}\n\\end{equation}\nwhere the parameter $\\mu$ is the mode of the distribution; $\\sigma$ is the \naverage of the left and right widths; $\\epsilon$ is the asymmetry between the \nleft and right widths; and $\\rho_{L(R)}$ is the exponent for the left (right) \ntail.\nThe secondary signal distribution is modelled by a normal distribution.\nThese shapes are motivated by the \\lnipchisq\\ distributions for prompt and \nsecondary signal decays observed in the \\ac{MC} samples.\n\nGiven the large number of parameters to be fitted, some shape parameters in the \nprompt and secondary signal \\lnipchisq\\ \\acp{PDF} are fixed to values obtained \nfrom `prefits' to the pure samples of prompt and secondary signal \\ac{MC} \ndescribed in \\cref{chap:prod:data:mc}.\nThe set of parameters that is fixed is dependent on the charm meson species.\n\n\\section{Mode-specific details}\n\\label{chap:prod:fitting:details}\n\nAs different final states exhibit different features in the mass, \\deltam, and \n\\lnipchisq\\ distributions, several aspects of the fits are different between \nmodes.\nThis \\lcnamecref{chap:prod:fitting:details} gives the list of parameters that \nare split across \\pTy\\ bins, and the list of parameters that are allowed to \nfloat after the \\ac{MC} prefits, for each mode.\n\nInitially, no knowledge is assumed on which parameters should be independent \n(to be `split') across the \\pTy\\ bins, nor of whether the \\lnipchisq\\ \ndistribution is well-modelled by the \\ac{MC}.\nThe chosen parameterisation is that which best describes the data.\nFor the mass fits, all parameters are initially fixed such that they are same \nacross all \\pTy\\ bins, and are then split one by one when it is observed that a \nfeature varies across the bins, such as the width of the signal peak.\nAll parameters of the \\lnipchisq\\ fits are first kept fixed to values found \nfrom the fits to the simulated data, and then individual parameters are floated \nif the total PDF does not model the data well.\nParameters are then split across \\pTy\\ bins in the same manner as described \nbelow.\n\n\\subsection{Fit details for \\PDzero}\n\\label{chap:prod:fitting:details:D0ToKpi}\n\nFor the \\DzToKpi\\ mode, the signal shape in the mass fit is the sum of a normal \nand a Crystal Ball distribution~\\cite{Skwarnicki:1986xj}, sharing a common mode \nbut allowed to have different widths.\nThe Crystal Ball function $C$ is a normal distribution but with a power-law \ntail on one side, defined (un-normalised) as\n\\begin{equation}\n  C(x; \\mu, \\sigma, \\alpha, n) = \\begin{cases}\n    e^{-\\frac{{(x - \\mu)}^{2}}{2\\sigma^{2}}}                          & \\frac{x - \\mu}{\\sigma} > -\\alpha, \\\\\n    e^{-\\frac{|\\alpha|^{2}}{2}}\n      {\\left(\\frac{n}{|\\alpha|}\\right)}^{n}\n      {\\left(\\frac{n}{|\\alpha|} - |\\alpha| - \\frac{x - \\mu}{\\sigma}\\right)}^{-n} & \\frac{x - \\mu}{\\sigma} \\leq -\\alpha,\n  \\end{cases}\n  \\label{eqn:prod:fitting:crystal_ball}\n\\end{equation}\nwhere $\\alpha$ defines where the power-law tail begins, in units of the width \nof the core Gaussian $\\sigma$, and $n$ is the power law exponent.\nThe mode and width of the total signal \\ac{PDF} are split across \\pTy\\ bins, as \nis the slope of the background \\ac{PDF}.\nThe mode of the \\lnipchisq\\ prompt signal \\ac{PDF} and the width of the \nsecondary signal \\ac{PDF} are also split across \\pTy\\ bins.\nThe mode and width of the prompt signal \\lnipchisq\\ \\ac{PDF} and all parameters \nof the secondary signal \\lnipchisq\\ \\ac{PDF} are floated in the fit to data, \nand all other \\lnipchisq\\ shape parameters are fixed to the values from \n\\ac{MC}.\n\nPrefits to the prompt signal and secondary signal \\ac{MC} samples are given in \n\\cref{fig:prod:fitting:prefits:D0ToKpi}.\n\n\\subsubsection*{Fit details for \\PDplus}\n\\label{chap:prod:fitting:details:DpToKpipi}\n\nFor the \\DpToKpipi\\ mode, the signal shape in the mass fit is the sum of a \nnormal and a Crystal Ball distribution, sharing a common mode but allowed to \nhave different widths.\nThe mode of the signal mass \\ac{PDF} as well as the width of the Crystal Ball \ncomponent in the mass \\ac{PDF} are split across \\pTy\\ bins, as is the slope of \nthe background mass \\ac{PDF}.\nThe mode of the \\lnipchisq\\ prompt signal and secondary signal distributions \nare split across \\pTy\\ bins.\nThe mode and tail parameters of the signal \\lnipchisq\\ \\ac{PDF}, are floated \nduring the fit to data, with all other shape parameters fixed to the values \nfrom \\ac{MC}.\n\nPrefits to the prompt signal and secondary signal data samples in \\lnipchisq\\ \nare given in \\cref{fig:prod:fitting:prefits:DpToKpipi}.\n\n\\subsubsection*{Fit details for \\PDsplus}\n\\label{chap:prod:fitting:details:DsToKKpi}\n\nFor the \\DspTophipi\\ mode, the signal shape in the mass fit is the sum of a two \nnormal distributions, sharing a common mean but allowed to have different \nwidths.\nThe mean and width of the signal mass \\ac{PDF} and the slope of the background \nmass \\ac{PDF}, along with the mode of the \\lnipchisq\\ prompt signal \\ac{PDF}, \nare split across \\pTy\\ bins.\nThe mode of the prompt signal \\lnipchisq\\ \\ac{PDF} and all parameters of the \nsecondary \\ac{PDF} are floated during the fit to data, with all other shape \nparameters fixed to the values from \\ac{MC}.\n\nPrefits to the prompt signal and secondary signal data samples in \\lnipchisq\\ \nare given in \\cref{fig:prod:fitting:prefits:DsToKKpi}.\n\n\\subsubsection*{Fit details for \\PDstarp}\n\\label{chap:prod:fitting:details:DstToD0pi}\n\nFor the \\PDstarp-tagged \\DzToKpi\\ mode, the width of the widest component of \nthe \\deltam\\ signal model, described in \\cref{chap:prod:fitting:mass}, is split \nacross \\pTy\\ bins, along with the mean of the prompt signal \\lnipchisq\\ \n\\ac{PDF}.\nThe mean of the prompt signal \\lnipchisq\\ \\ac{PDF} and all parameters of the \nsecondary \\ac{PDF} are floated during the fit to data, with all other shape \nparameters fixed to the values from \\ac{MC}.\n\nPrefits to the prompt signal and secondary signal data samples in \\PDzero \n\\lnipchisq\\ are given in \\cref{fig:prod:fitting:prefits:DstToD0pi_D0ToKpi}.\n\n\\subsection{Fit results}\n\\label{chap:prod:fitting:results}\n\nFor all fits, the covariance matrix is checked to be positive definite, and the \ngoodness-of-fit within each \\pTy\\ bin is checked visually to ensure that the \n\\ac{NLL} minimisation stopped at a sensible parameter value set.\nMass, \\deltam, and \\lnipchisq\\ fits are given in \n\\cref{fig:prod:fitting:D0ToKpi,fig:prod:fitting:DpToKpipi,fig:prod:fitting:DsToKKpi,fig:prod:fitting:DstToD0pi_D0ToKpi}, \nwhere the data and models shown are the sums of the data and models over all \n\\pTy\\ bins.\nPrompt signal yields per \\pTy\\ bin are given in \n\\cref{tab:prod:fitting:D0ToKpi,tab:prod:fitting:DpToKpipi,tab:prod:fitting:DsToKKpi,tab:prod:fitting:DstToD0pi_D0ToKpi}, \nand those integrated across all bins in \\cref{tab:prod:fitting:integrated}.\n\nThe plots show that the models match the data well, but there are some \nsignificant discrepancies such as in \n\\cref{fig:prod:fitting:DsToKKpi:ipchisq,fig:prod:fitting:DstToD0pi_D0ToKpi:delta_mass}.\nHowever, the discrepancies in these integrated plots are exaggerations of those \nin the individual \\pTy\\ bin fits: they indicate that there is a consistent bias \nin the individual bins, but do not necessarily indicate that these are \nstatistically significant.\nFor comparison, \n\\cref{fig:prod:fitting:D0ToKpi:sig_bkg,fig:prod:fitting:DpToKpipi:sig_bkg,fig:prod:fitting:DsToKKpi:sig_bkg,fig:prod:fitting:DstToD0pi_D0ToKpi:sig_bkg} \nshow the mass (or \\deltam) and \\lnipchisq\\ fits for each meson in the \\pTy\\ bin \nwith the highest prompt signal yield and in the \\pTy\\ bin with the highest \ncombinatorial background yield.\nThese show that, in the individual \\pTy\\ bins, the fits model the data \nsignificantly better than the integrated plots would suggest, and also that the \nfit is flexible enough to model both high prompt signal and high combinatorial \nbackground datasets.\nThe effect on the cross-section measurements of mis-modelling will be discussed \nfurther in \\cref{chap:prod:syst:fitting}.\n\nIn some \\pTy\\ bins, it is not possible to make a prompt signal yield \nmeasurement due to insufficient data in those bins.\nAt this stage in the analysis, a cross-section measurement in a bin is \nconsidered unfeasible if there is either no data (zero candidates), or if the \nprompt signal yield $N_{i} \\pm \\sigma_{N_{i}}$ in that bin as determined in the \nfit does not satisfy $N_{i} > 3\\sigma_{N_{i}}$.\n\n\\begin{figure}\n  \\begin{subfigure}{0.5\\textwidth}\n    \\includegraphics[width=\\textwidth]{production/fitting/D0ToKpi_mass_offline_selection_regions}\n    \\caption{\\DzToKpi}\n    \\label{fig:prod:fitting:regions:D0ToKpi}\n  \\end{subfigure}\n  \\begin{subfigure}{0.5\\textwidth}\n    \\includegraphics[width=\\textwidth]{production/fitting/DpToKpipi_mass_offline_selection_regions}\n    \\caption{\\DpToKpipi}\n    \\label{fig:prod:fitting:regions:DpToKpipi}\n  \\end{subfigure}\n  \\caption{%\n    Definition of signal window, in blue, and sidebands, in red, for \n    \\DzToKpi~(\\subref*{fig:prod:fitting:regions:D0ToKpi}) and \n    \\DpToKpipi~(\\subref*{fig:prod:fitting:regions:DpToKpipi}) candidates.\n    The boundaries of the different regions are defined in \n    \\cref{chap:prod:fitting:ipchisq}.\n    The full dataset is shown.\n  }\n  \\label{fig:prod:fitting:regions_A}\n\\end{figure}\n\n\\begin{figure}\n  \\begin{subfigure}{0.5\\textwidth}\n    \\includegraphics[width=\\textwidth]{production/fitting/DsToKKpi_mass_offline_selection_regions}\n    \\caption{\\DspTophipi}\n    \\label{fig:prod:fitting:regions:DsTophipi}\n  \\end{subfigure}\n  \\begin{subfigure}{0.5\\textwidth}\n    \\includegraphics[width=\\textwidth]{production/fitting/DstToD0pi_D0ToKpi_delta_mass_offline_selection_regions}\n    \\caption{\\DstToDzpi}\n    \\label{fig:prod:fitting:regions:DstToD0pi_D0ToKpi}\n  \\end{subfigure}\n  \\caption{%\n    Definition of signal window, in blue, and sidebands, in red, for \n    \\DspTophipi~(\\subref*{fig:prod:fitting:regions:DsTophipi}) and \n    \\DstToDzpi~(\\subref*{fig:prod:fitting:regions:DstToD0pi_D0ToKpi}) \n    candidates.\n    The boundaries of the different regions are defined in \n    \\cref{chap:prod:fitting:ipchisq}.\n    The full dataset is shown.\n  }\n  \\label{fig:prod:fitting:regions_B}\n\\end{figure}\n\n\\begin{figure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/D0ToKpi_ipchisq_fit_pT_integrated_y_integrated_sig}\n    \\caption{Prompt}\n    \\label{fig:prod:fitting:prefits:D0ToKpi:prompt}\n  \\end{subfigure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/D0ToKpi_ipchisq_fit_pT_integrated_y_integrated_sec}\n    \\caption{Secondary}\n    \\label{fig:prod:fitting:prefits:D0ToKpi:secondary}\n  \\end{subfigure}\n  \\caption{%\n    Distributions of \\lnipchisq\\ for simulated \\DzToKpi\\ decays: prompt signal \n    \\PDzero (\\subref*{fig:prod:fitting:prefits:D0ToKpi:prompt}) and secondary \n    signal \\PDzero (\\subref*{fig:prod:fitting:prefits:D0ToKpi:secondary}).\n    The sum of the simultaneous likelihood fits in each \\pTy\\ bin is overlaid.\n  }\n  \\label{fig:prod:fitting:prefits:D0ToKpi}\n\\end{figure}\n\n\\begin{figure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/DpToKpipi_ipchisq_fit_pT_integrated_y_integrated_sig}\n    \\caption{Prompt}\n    \\label{fig:prod:fitting:prefits:DpToKpipi:prompt}\n  \\end{subfigure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/DpToKpipi_ipchisq_fit_pT_integrated_y_integrated_sec}\n    \\caption{Secondary}\n    \\label{fig:prod:fitting:prefits:DpToKpipi:secondary}\n  \\end{subfigure}\n  \\caption{%\n    Distributions of \\lnipchisq\\ for simulated \\DpToKpipi\\ decays: prompt \n    signal \\PDplus (\\subref*{fig:prod:fitting:prefits:DpToKpipi:prompt}) and \n    secondary signal \\PDplus \n    (\\subref*{fig:prod:fitting:prefits:DpToKpipi:secondary}).\n    The sum of the simultaneous likelihood fits in each \\pTy\\ bin is overlaid.\n  }\n  \\label{fig:prod:fitting:prefits:DpToKpipi}\n\\end{figure}\n\n\\begin{figure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/DsToKKpi_ipchisq_fit_pT_integrated_y_integrated_sig}\n    \\caption{Prompt}\n    \\label{fig:prod:fitting:prefits:DsToKKpi:prompt}\n  \\end{subfigure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/DsToKKpi_ipchisq_fit_pT_integrated_y_integrated_sec}\n    \\caption{Secondary}\n    \\label{fig:prod:fitting:prefits:DsToKKpi:secondary}\n  \\end{subfigure}\n  \\caption{%\n    Distributions of \\lnipchisq\\ for simulated \\DspTophipi\\ decays: prompt \n    signal \\PDsplus (\\subref*{fig:prod:fitting:prefits:DsToKKpi:prompt}) and \n    secondary signal \\PDsplus \n    (\\subref*{fig:prod:fitting:prefits:DsToKKpi:secondary}).\n    The sum of the simultaneous likelihood fits in each \\pTy\\ bin is overlaid.\n  }\n  \\label{fig:prod:fitting:prefits:DsToKKpi}\n\\end{figure}\n\n\\begin{figure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/DstToD0pi_D0ToKpi_ipchisq_fit_pT_integrated_y_integrated_sig}\n    \\caption{Prompt}\n    \\label{fig:prod:fitting:prefits:DstToD0pi_D0ToKpi:prompt}\n  \\end{subfigure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/DstToD0pi_D0ToKpi_ipchisq_fit_pT_integrated_y_integrated_sec}\n    \\caption{Secondary}\n    \\label{fig:prod:fitting:prefits:DstToD0pi_D0ToKpi:secondary}\n  \\end{subfigure}\n  \\caption{%\n    Distributions of \\PDzero \\lnipchisq\\ for simulated \\DstToDzpi, with \n    \\DzToKpi, decays: prompt signal \\PDstarp\\\n    (\\subref*{fig:prod:fitting:prefits:DstToD0pi_D0ToKpi:prompt}) and secondary \n    signal \\PDstarp\\\n    (\\subref*{fig:prod:fitting:prefits:DstToD0pi_D0ToKpi:secondary}).\n    The sum of the simultaneous likelihood fits in each \\pTy\\ bin is overlaid.\n  }\n  \\label{fig:prod:fitting:prefits:DstToD0pi_D0ToKpi}\n\\end{figure}\n\n\\begin{figure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/D0ToKpi_mass_fit_pT_integrated_y_integrated}\n    \\caption{Mass}\n    \\label{fig:prod:fitting:D0ToKpi:mass}\n  \\end{subfigure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/D0ToKpi_ipchisq_fit_pT_integrated_y_integrated}\n    \\caption{\\lnipchisq}\n    \\label{fig:prod:fitting:D0ToKpi:ipchisq}\n  \\end{subfigure}\n  \\caption{%\n    Distributions for fully selected \\DzToKpi\\ candidates: \\PDzero\\ invariant \n    mass (\\subref*{fig:prod:fitting:D0ToKpi:mass}) and \\PDzero\\ \\lnipchisq\\ \n    (\\subref*{fig:prod:fitting:D0ToKpi:ipchisq}) for a mass window of \n    $\\pm\\SI{20}{\\MeVcc}$ around the nominal \\PDzero mass.\n    The sum of the simultaneous likelihood fits in each \\pTy\\ bin is shown, \n    with components as indicated in the legends.\n  }\n  \\label{fig:prod:fitting:D0ToKpi}\n\\end{figure}\n\n\\begin{figure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/DpToKpipi_mass_fit_pT_integrated_y_integrated}\n    \\caption{Mass}\n    \\label{fig:prod:fitting:DpToKpipi:mass}\n  \\end{subfigure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/DpToKpipi_ipchisq_fit_pT_integrated_y_integrated}\n    \\caption{\\lnipchisq}\n    \\label{fig:prod:fitting:DpToKpipi:ipchisq}\n  \\end{subfigure}\n  \\caption{%\n    Distributions for fully selected \\DpToKpipi\\ candidates: \\PDplus\\ invariant \n    mass (\\subref*{fig:prod:fitting:DpToKpipi:mass}) and \\PDplus\\ \\lnipchisq\\ \n    (\\subref*{fig:prod:fitting:DpToKpipi:ipchisq}) for a mass window of \n    $\\pm\\SI{20}{\\MeVcc}$ around the nominal \\PDplus mass.\n    The sum of the simultaneous likelihood fits in each \\pTy\\ bin is shown, \n    with components as indicated in the legends.\n  }\n  \\label{fig:prod:fitting:DpToKpipi}\n\\end{figure}\n\n\\begin{figure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/DsToKKpi_mass_fit_pT_integrated_y_integrated}\n    \\caption{Mass}\n    \\label{fig:prod:fitting:DsToKKpi:mass}\n  \\end{subfigure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/DsToKKpi_ipchisq_fit_pT_integrated_y_integrated}\n    \\caption{\\lnipchisq}\n    \\label{fig:prod:fitting:DsToKKpi:ipchisq}\n  \\end{subfigure}\n  \\caption{%\n    Distributions for fully selected \\DspTophipi\\ candidates: \\PDsplus\\ \n    invariant mass (\\subref*{fig:prod:fitting:DpToKpipi:mass}) and \\PDsplus\\ \n    \\lnipchisq\\ (\\subref*{fig:prod:fitting:DpToKpipi:ipchisq}) for a mass \n    window of $\\pm\\SI{20}{\\MeVcc}$ around the nominal \\PDsplus mass.\n    The sum of the simultaneous likelihood fits in each \\pTy\\ bin is shown, \n    with components as indicated in the legends.\n  }\n  \\label{fig:prod:fitting:DsToKKpi}\n\\end{figure}\n\n\\begin{figure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/DstToD0pi_D0ToKpi_mass_fit_pT_integrated_y_integrated}\n    \\caption{\\PDzero mass}\n    \\label{fig:prod:fitting:DstToD0pi_D0ToKpi:mass}\n  \\end{subfigure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/DstToD0pi_D0ToKpi_delta_mass_fit_pT_integrated_y_integrated}\n    \\caption{Delta mass}\n    \\label{fig:prod:fitting:DstToD0pi_D0ToKpi:delta_mass}\n  \\end{subfigure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/DstToD0pi_D0ToKpi_ipchisq_fit_pT_integrated_y_integrated}\n    \\caption{\\lnipchisq}\n    \\label{fig:prod:fitting:DstToD0pi_D0ToKpi:ipchisq}\n  \\end{subfigure}\n  \\caption{%\n    Distributions for fully selected \\PDstarp\\ candidates, with \\DzToKpi: \n    \\PDzero\\ invariant mass \n    (\\subref*{fig:prod:fitting:DstToD0pi_D0ToKpi:mass}); $\\deltam = m(\\PDstarp) \n    - m(\\PDzero)$ (\\subref*{fig:prod:fitting:DstToD0pi_D0ToKpi:delta_mass}) for \n    a mass window of $\\pm\\SI{20}{\\MeVcc}$ around the nominal \\PDzero mass; and \n    \\PDzero\\ \\lnipchisq\\ (\\subref*{fig:prod:fitting:DstToD0pi_D0ToKpi:ipchisq}) \n    with an additional mass window of $\\pm\\SI{3}{\\MeVcc}$ around the nominal \n    \\deltam\\ value.\n    The sum of the simultaneous likelihood fits in each \\pTy\\ bin is shown, \n    with components as indicated in the legends.\n  }\n  \\label{fig:prod:fitting:DstToD0pi_D0ToKpi}\n\\end{figure}\n\n\\begin{table}\n  \\caption{%\n    Prompt signal yields in the fully selected dataset, summed over all\n    \\pTy\\ bins in which a measurement is made.\n  }\n  \\label{tab:prod:fitting:integrated}\n  \\centering\n  \\input{tables/production/fitting/integrated_signal_yields}\n\\end{table}\n\n\\begin{figure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/D0ToKpi_mass_fit_pT_3_y_2}\n    \\caption{Mass}\n    \\label{fig:prod:fitting:D0ToKpi:mass_high_sig}\n  \\end{subfigure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/D0ToKpi_ipchisq_fit_pT_3_y_2}\n    \\caption{\\lnipchisq}\n    \\label{fig:prod:fitting:D0ToKpi:ipchisq_high_sig}\n  \\end{subfigure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/D0ToKpi_mass_fit_pT_0_y_3}\n    \\caption{Mass}\n    \\label{fig:prod:fitting:D0ToKpi:mass_high_bkg}\n  \\end{subfigure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/D0ToKpi_ipchisq_fit_pT_0_y_3}\n    \\caption{\\lnipchisq}\n    \\label{fig:prod:fitting:D0ToKpi:ipchisq_high_bkg}\n  \\end{subfigure}\n  \\caption{%\n    Distributions for fully selected \\DzToKpi\\ candidates: \\PDzero\\ invariant \n    mass (\\subref*{fig:prod:fitting:D0ToKpi:mass_high_sig} and \n    \\subref*{fig:prod:fitting:D0ToKpi:mass_high_bkg}); and \\PDzero\\ \\lnipchisq\\ \n    (\\subref*{fig:prod:fitting:D0ToKpi:ipchisq_high_sig} and \n    \\subref*{fig:prod:fitting:D0ToKpi:ipchisq_high_bkg}) for a mass window of \n    $\\pm\\SI{20}{\\MeVcc}$ around the nominal \\PDzero mass.\n    The top Figures (\\subref*{fig:prod:fitting:D0ToKpi:mass_high_sig} and \n    \\subref*{fig:prod:fitting:D0ToKpi:ipchisq_high_sig}) show the data and fits \n    in the region \\pTyrange{2}{2.5}{3}{3.5}, whilst the bottom Figures \n    (\\subref*{fig:prod:fitting:D0ToKpi:mass_high_bkg} and \n    \\subref*{fig:prod:fitting:D0ToKpi:ipchisq_high_bkg}) show the data and fits \n    in the \\pTyrange{0}{1}{3.5}{4} region.\n  }\n  \\label{fig:prod:fitting:D0ToKpi:sig_bkg}\n\\end{figure}\n\n\\begin{figure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/DpToKpipi_mass_fit_pT_4_y_2}\n    \\caption{Mass}\n    \\label{fig:prod:fitting:DpToKpipi:mass_high_sig}\n  \\end{subfigure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/DpToKpipi_ipchisq_fit_pT_4_y_2}\n    \\caption{\\lnipchisq}\n    \\label{fig:prod:fitting:DpToKpipi:ipchisq_high_sig}\n  \\end{subfigure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/DpToKpipi_mass_fit_pT_3_y_3}\n    \\caption{Mass}\n    \\label{fig:prod:fitting:DpToKpipi:mass_high_bkg}\n  \\end{subfigure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/DpToKpipi_ipchisq_fit_pT_3_y_3}\n    \\caption{\\lnipchisq}\n    \\label{fig:prod:fitting:DpToKpipi:ipchisq_high_bkg}\n  \\end{subfigure}\n  \\caption{%\n    Distributions for fully selected \\DpToKpipi\\ candidates: \\PDplus\\ invariant \n    mass (\\subref*{fig:prod:fitting:DpToKpipi:mass_high_sig} and \n    \\subref*{fig:prod:fitting:DpToKpipi:mass_high_bkg}); and \\PDplus\\ \n    \\lnipchisq\\ (\\subref*{fig:prod:fitting:DpToKpipi:ipchisq_high_sig} and \n    \\subref*{fig:prod:fitting:DpToKpipi:ipchisq_high_bkg}) for a mass window of \n    $\\pm\\SI{20}{\\MeVcc}$ around the nominal \\PDplus mass.\n    The top Figures (\\subref*{fig:prod:fitting:DpToKpipi:mass_high_sig} and \n    \\subref*{fig:prod:fitting:DpToKpipi:ipchisq_high_sig}) show the data and \n    fits in the region \\pTyrange{2.5}{3}{3}{3.5}, whilst the bottom Figures \n    (\\subref*{fig:prod:fitting:DpToKpipi:mass_high_bkg} and \n    \\subref*{fig:prod:fitting:DpToKpipi:ipchisq_high_bkg}) show the data and \n    fits in the \\pTyrange{2}{2.5}{3.5}{4} region.\n  }\n  \\label{fig:prod:fitting:DpToKpipi:sig_bkg}\n\\end{figure}\n\n\\begin{figure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/DsToKKpi_mass_fit_pT_6_y_1}\n    \\caption{Mass}\n    \\label{fig:prod:fitting:DsToKKpi:mass_high_sig}\n  \\end{subfigure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/DsToKKpi_ipchisq_fit_pT_6_y_1}\n    \\caption{\\lnipchisq}\n    \\label{fig:prod:fitting:DsToKKpi:ipchisq_high_sig}\n  \\end{subfigure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/DsToKKpi_mass_fit_pT_2_y_3}\n    \\caption{Mass}\n    \\label{fig:prod:fitting:DsToKKpi:mass_high_bkg}\n  \\end{subfigure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/DsToKKpi_ipchisq_fit_pT_2_y_3}\n    \\caption{\\lnipchisq}\n    \\label{fig:prod:fitting:DsToKKpi:ipchisq_high_bkg}\n  \\end{subfigure}\n  \\caption{%\n    Distributions for fully selected \\DspTophipi\\ candidates: \\PDsplus\\ \n    invariant mass (\\subref*{fig:prod:fitting:DsToKKpi:mass_high_sig} and \n    \\subref*{fig:prod:fitting:DsToKKpi:mass_high_bkg}); and \\PDsplus\\ \n    \\lnipchisq\\ (\\subref*{fig:prod:fitting:DsToKKpi:ipchisq_high_sig} and \n    \\subref*{fig:prod:fitting:DsToKKpi:ipchisq_high_bkg}) for a mass window of \n    $\\pm\\SI{20}{\\MeVcc}$ around the nominal \\PDsplus mass.\n    The top Figures (\\subref*{fig:prod:fitting:DsToKKpi:mass_high_sig} and \n    \\subref*{fig:prod:fitting:DsToKKpi:ipchisq_high_sig}) show the data and \n    fits in the region \\pTyrange{4}{5}{2.5}{3}, whilst the bottom Figures \n    (\\subref*{fig:prod:fitting:DsToKKpi:mass_high_bkg} and \n    \\subref*{fig:prod:fitting:DsToKKpi:ipchisq_high_bkg}) show the data and \n    fits in the \\pTyrange{2}{2.5}{3.5}{4} region.\n  }\n  \\label{fig:prod:fitting:DsToKKpi:sig_bkg}\n\\end{figure}\n\n\\begin{figure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/DstToD0pi_D0ToKpi_delta_mass_fit_pT_7_y_2}\n    \\caption{Delta mass}\n    \\label{fig:prod:fitting:DstToD0pi_D0ToKpi:delta_mass_high_sig}\n  \\end{subfigure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/DstToD0pi_D0ToKpi_ipchisq_fit_pT_7_y_2}\n    \\caption{\\lnipchisq}\n    \\label{fig:prod:fitting:DstToD0pi_D0ToKpi:ipchisq_high_sig}\n  \\end{subfigure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/DstToD0pi_D0ToKpi_delta_mass_fit_pT_2_y_3}\n    \\caption{Delta mass}\n    \\label{fig:prod:fitting:DstToD0pi_D0ToKpi:delta_mass_high_bkg}\n  \\end{subfigure}\n  \\begin{subfigure}[b]{0.5\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{production/fitting/DstToD0pi_D0ToKpi_ipchisq_fit_pT_2_y_3}\n    \\caption{\\lnipchisq}\n    \\label{fig:prod:fitting:DstToD0pi_D0ToKpi:ipchisq_high_bkg}\n  \\end{subfigure}\n  \\caption{%\n    Distributions for fully selected \\DstToDzpi, with \\DzToKpi, candidates: \n    $\\deltam = m(\\PDstarp) - m(\\PDzero)$ \n    (\\subref*{fig:prod:fitting:DstToD0pi_D0ToKpi:delta_mass_high_sig} and \n    \\subref*{fig:prod:fitting:DstToD0pi_D0ToKpi:delta_mass_high_bkg}) for a \n    mass window of $\\pm\\SI{20}{\\MeVcc}$ around the nominal \\PDzero mass; and \n    \\PDzero\\ \\lnipchisq\\ \n    (\\subref*{fig:prod:fitting:DstToD0pi_D0ToKpi:ipchisq_high_sig} and \n    \\subref*{fig:prod:fitting:DstToD0pi_D0ToKpi:ipchisq_high_bkg}) with an \n    additional mass window of $\\pm\\SI{3}{\\MeVcc}$ around the nominal \n    \\PDstarp-\\PDzero\\ mass difference.\n    The top Figures \n    (\\subref*{fig:prod:fitting:DstToD0pi_D0ToKpi:delta_mass_high_sig} and \n    \\subref*{fig:prod:fitting:DstToD0pi_D0ToKpi:ipchisq_high_sig}) show the \n    data and fits in the region \\pTyrange{4}{5}{3}{3.5}, whilst the bottom \n    Figures (\\subref*{fig:prod:fitting:DstToD0pi_D0ToKpi:delta_mass_high_bkg} \n    and \\subref*{fig:prod:fitting:DstToD0pi_D0ToKpi:ipchisq_high_bkg}) show the \n    data and fits in the \\pTyrange{1.5}{2}{3.5}{4} region.\n  }\n  \\label{fig:prod:fitting:DstToD0pi_D0ToKpi:sig_bkg}\n\\end{figure}\n", "meta": {"hexsha": "3010813b5228c7cad924be38a793e5ef17bd3f49", "size": 35372, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/production/fitting.tex", "max_stars_repo_name": "alexpearce/Thesis", "max_stars_repo_head_hexsha": "d727d04b7ee619ba0eb45c7faf1004eb418e046e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-18T00:58:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T00:58:34.000Z", "max_issues_repo_path": "chapters/production/fitting.tex", "max_issues_repo_name": "alexpearce/Thesis", "max_issues_repo_head_hexsha": "d727d04b7ee619ba0eb45c7faf1004eb418e046e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/production/fitting.tex", "max_forks_repo_name": "alexpearce/Thesis", "max_forks_repo_head_hexsha": "d727d04b7ee619ba0eb45c7faf1004eb418e046e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-05-13T07:54:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-06T23:42:27.000Z", "avg_line_length": 47.0998668442, "max_line_length": 152, "alphanum_fraction": 0.7453918353, "num_tokens": 11592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154239957834732, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.31048075364596983}}
{"text": "\\section{Hyperchains}\n\n\\textbf{todo: reorganize, mention commitments earlier, images!}\n\nThe previous approaches had a lot to offer, but considering they cons it is hard\nto scale them in a reasonable way. PoW seems to work well only with big\ncomputational effort being burned and PoS suffers from huge amount of security\nholes that require very complicated algorithms that usually either don't solve\nthe problem at all or just move it further to another layer of abstraction.\n\nHere we present a hybrid strategy which will benefit from stability of PoW\nsolutions but will offer the scalability of PoS systems. A Hyperchain is a\nspecial kind of blockchain that sticks to an already existing chain. They are\ngoing to be called respectively child- and parent-chain\n\\footnote{https://medium.com/@yanislav/hyperchains-secure-cheap-scalable-blockchain-technology-for-everyone-3ddec96a4152}.\n\nThe parent chain can be almost any blockchain in the world. In general, we want\nto use some big existing PoW based chains (at the time of writing, preferably\nBitcoin or Ethereum, but not limited to) to reuse their burned work to maintain\nthe stability of the childchain. We would also like to have\nPoS-like election system to choose the leaders on the hyperchain. In this case\nhowever we have a really reliable – and most important, unpredictable – source\nof randomness – the keyblock hash of the parent chain. The idea is not very new\nthough – there is already some research made in this direction\n\\footnote{https://eprint.iacr.org/2015/1015.pdf}.\nThe critics say that it is still possible to exploit it to mine blocks in such a\nmanner that the outcome would be beneficial, but in reality that reduces to\ncompound PoW – most likely the difficulty of mining such a block will go\nsquared, so in order to have actual control over the entropy one needs to\ncontrol the parent chain anyway.\n\nHaving this machinery it seems natural to start a new election each time a\nkeyblock was mined on the parent chain. The next leader shall be chosen\ndepending on the hash of that block and selected with proportional chances to\ntheir stake. The selection algorithm is going to be straightforward – we take\nthe hash (let's say, MD5) and consider a whole MD5 counterdomain as a closed\nline segment divided into intervals of lengths proportional to the stakes of the\ndelegates. The intervals are going to be sorted by the order of the respective\ncommitments that appeared on the parent chain. The generated hash will then\npoint into some subsection which will determine the winner.\n\n$$Insert\\ some\\ nice\\ image\\ here$$\n\nOne of the important concepts of the commitment idea is to be able to rely on\nthe parent chain's stability. Therefore we want to treat it as a rigid skeleton\nof the hyperchain which can be achieved by proper blockhash linking. Each\ncommitment must declare over which block is the delegating going to compete.\nTherefore the commitment must consist of:\n\\begin{itemize}\n\\item The subject of delegation on the child chain\n\\item The block over the delegate is going to build\n\\item Singature of the delegate from the child chain\n\\end{itemize}\n\nOne dillema that rises at this point is whether should the commitment reference\nthe latest keyblock or the microblock of the child chain. Referencing microblock\non the first sight looks more consistent, but we believe that in reality would\nlead to massive forking (especially when some peers wouldn't receive all of the\nblocks). The problem with referencing keyblock is that the next leader could\nsteal the transactions and post them in their microblocks. This however can be\nfaced with the smarter feeing strategy: instead of giving the full fee to the\nminer we can split it up and give the bigger part to the next leader that did\ninclude the previous leader's microblocks in their continuation of the history.\n\n$$Insert\\ some\\ nice\\ image\\ here$$\n\n\n", "meta": {"hexsha": "26e9c4decce78c09cf596d1e499147f2179624fc", "size": 3874, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "hyperchains.tex", "max_stars_repo_name": "gorbak25/hyperchains-whitepaper", "max_stars_repo_head_hexsha": "84a32f7451cf7536bd7049a6b0cfa3b9ff216143", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-14T13:46:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-14T13:46:48.000Z", "max_issues_repo_path": "hyperchains.tex", "max_issues_repo_name": "gorbak25/hyperchains-whitepaper", "max_issues_repo_head_hexsha": "84a32f7451cf7536bd7049a6b0cfa3b9ff216143", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hyperchains.tex", "max_forks_repo_name": "gorbak25/hyperchains-whitepaper", "max_forks_repo_head_hexsha": "84a32f7451cf7536bd7049a6b0cfa3b9ff216143", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.9705882353, "max_line_length": 122, "alphanum_fraction": 0.8048528653, "num_tokens": 851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.31042523809270994}}
{"text": "\\chapter{AWP model set of equations}\n\\label[secinapp]{chap:awp-eqn}\n\\resetallacronyms\n\nThis appendix presents the set of equations for the model presented in\n\\cpref{sec:awp-model} with \\cpref{fig:awp-exp-analysis-model}. The\nknown variables are:\n\n\\begin{multicols}{5}\n  \\begin{itemize}\n    \\item $\\dotE{el}{14}$\n    \\item $\\dotM{02}{26}$\n    \\item $\\dotM{03}{07}$\n    \\item $\\dotM{17}{15}$\n    \\item $\\text{\\textit{Cp}}_{15,in}$\n    \\item $\\text{\\textit{Cp}}_{15,out}$\n    \\item $h_{02,out}$\n    \\item $h_{03,in}$\n    \\item $h_{03,out}$\n    \\item $h_{04,in}$\n    \\item $h_{04,out}$\n    \\item $h_{18,out}$\n    \\item $h_{20,out}$\n    \\item $h_{21,out}$\n    \\item $h_{25,out}$\n    \\item $h_{26,out}$\n    \\item $h_{28,out}$\n    \\item $\\eta_{in}$\n    \\item $\\eta_{rad}$\n    \\item $\\eta_{axi}$\n  \\end{itemize}\n\\end{multicols}\n\n$\\eta_{mot}$ is set directly by the solver. $\\eta_{rad}$ and\n$\\eta_{axi}$ are determined with the gas bearings losses model\nimplemented by \\citet{schiffmann-2008a}.\n\n\\begin{flalign}\n  & \\dotQ{03}{15} = \\dotM{17}{15} \\left( \\text{\\textit{Cp}}_{15,out} \\, T_{15,out} - \\text{\\textit{Cp}}_{15,in} \\, T_{15,in} \\right) \\label{eq:cd-eb-01} \\\\\n  & \\dotM{20}{03} = \\dfrac{\\dotQ{03}{15}}{h_{03,in} - h_{03,out}} \\label{eq:cd-eb-02} \\\\\n  & \\dotM{03}{05} = \\dotM{20}{03} - \\dotM{03}{07} \\label{eq:cd-eb-03} \\\\\n  & \\dotM{05}{08} = \\dotM{03}{05} \\nonumber \\\\\n  & \\dotM{02}{20} = \\dotM{03}{05} \\nonumber \\\\\n  & \\dotM{07}{09} = \\dotM{03}{07} \\nonumber \\\\\n  & \\dotM{26}{21} = f_{01} \\dotM{02}{26} & 0 < f_{01} < 1 \\hspace{2.1cm} \\nonumber \\\\\n  & \\dotQ{21}{at} = \\dotM{26}{21} \\left( h_{26,out} - h_{21,out} \\right) \\nonumber \\\\\n  & \\dotQ{26}{at} = \\dotM{02}{26} \\left( h_{02,out} - h_{26,out} \\right) \\nonumber \\\\\n  & \\dotQ{20}{at} = \\dotM{20}{03} \\left( h_{02,out} - h_{20,out} \\right) \\nonumber \\\\\n  & \\dotQ{14}{at} = \\left( 1 - \\eta_{in} \\right) \\dotE{el}{14} \\nonumber \\\\\n  & \\dotQ{16}{at} = \\dotQ{03}{15} - \\dotE{el}{14} - \\dotQ{21}{at} - \\dotQ{26}{at} - \\dotQ{20}{at} - \\dotQ{14}{at} \\label{eq:ev-eb-01} \\\\\n  & \\dotM{09}{04} = \\dfrac{\\dotQ{16}{04}}{h_{04,out} - h_{04,in}} \\label{eq:ev-eb-02} \\\\\n  & \\dotM{06}{09} = \\dotM{09}{04} - \\dotM{07}{09} \\label{eq:sc-mf} \\\\\n  & \\dotM{19}{06} = \\dotM{06}{09} \\nonumber \\\\\n  & \\dotM{08}{19} = \\dotM{06}{09} \\nonumber \\\\\n  & \\dotM{04}{18} = \\dotM{09}{04} \\nonumber \\\\\n  & \\dotM{18}{22} = \\dotM{04}{18} \\nonumber\n\\end{flalign}\n\n\\begin{flalign}\n  & \\dotM{26}{13} = \\left( 1 - f_{01} \\right) \\dotM{02}{26} \\nonumber \\\\\n  & \\dotM{21}{12} = \\dotM{26}{21} \\nonumber \\\\\n  & \\dotM{13}{12} = \\dotM{26}{13} \\nonumber \\\\\n  & \\dotM{12}{24} = \\dotM{13}{12} + \\dotM{21}{12} \\nonumber \\\\\n  & \\dotM{24}{11} = \\dotM{12}{24} \\nonumber \\\\\n  & \\dotM{11}{23} = f_{02} \\dotM{24}{11} & 0 < f_{02} < 1 \\hspace{2.1cm} \\nonumber \\\\\n  & \\dotM{11}{22} = \\left( 1 - f_{02} \\right) \\dotM{24}{11} \\nonumber \\\\\n  & \\dotM{23}{29} = \\dotM{11}{22} + \\dotM{18}{22} \\nonumber \\\\\n  & \\dotM{29}{01} = \\dotM{23}{29} + \\dotM{22}{29} \\nonumber \\\\\n  & \\dotM{01}{25} = \\dotM{29}{01} \\nonumber \\\\\n  & \\dot{M}_{cp1} = \\dotM{01}{25} \\nonumber\n\\end{flalign}\n\n\nThe mass flow rate in the second stage impeller $\\dot{M}_{cp2}$ is\nequal to $\\dotM{02}{26} + \\dotM{02}{20} + \\dotM{02}{10}$.\n$\\dotM{02}{10}$, the leakage flow rate through the labyrinth\nseal, needs to be determined.\n\n\\begin{flalign}\n  & \\dotM{02}{10} = f_{03} \\dot{M}_{cp2} & 0 < f_{03} < 1 \\hspace{1cm} \\label{eq:awp-f03}\n\\end{flalign}\n\nWith the introduction of the parameter $f_{03}$ in \\cref{eq:awp-f03},\nthe equation of the mass flow rate in the second stage impeller\n$\\dot{M}_{cp2}$ is equal to\n$f_{03} \\dot{M}_{cp2} + \\dotM{02}{26} + \\dotM{02}{20}$. Which implies\nthe \\cref{eq:awp-dotM_cp2}.\n\n\\begin{flalign}\n  & \\dot{M}_{cp2} = \\dfrac{\\dotM{02}{20} + \\dotM{02}{26}}{1 - f_{03}} \\label{eq:awp-dotM_cp2} \\\\\n  & \\dotM{10}{25} = \\dotM{02}{10} \\nonumber \\\\\n  & \\dotM{25}{27} = f_{04} \\left( \\dotM{10}{25} + \\dotM{01}{25} \\right) & 0 < f_{04} < 1 \\hspace{2.1cm} \\nonumber \\\\\n  & \\dotM{25}{08} = \\left( 1 - f_{04} \\right) \\left( \\dotM{10}{25} + \\dotM{01}{25} \\right) \\nonumber \\\\\n  & \\dotM{27}{28} = \\dotM{25}{27} \\nonumber \\\\\n  & \\dotM{08}{28} = \\dotM{25}{08} + \\dotM{05}{08} - \\dotM{08}{19} \\nonumber \\\\\n  & \\dotM{28}{02} = \\dotM{27}{28} + \\dotM{08}{28} \\nonumber \\\\\n  & \\dotE{14}{13} = \\eta_{in} \\dotE{el}{14} \\nonumber\n\\end{flalign}\n\nIf we consider the energy balance on component \\#13, we get\n$\\dotE{14}{13} - \\dotE{13}{12} - \\dotQ{13}{12} - \\dotQ{13}{07} +\n\\dotMh{26}{13} - \\dotMh{13}{12} = 0$.\n$h_{13,out}$ is unknown and needs to be determined. In order to do\nthis, $\\dotE{13}{12}$, $\\dotQ{13}{12}$ and $\\dotQ{13}{07}$ are\nrequired.\n\n\\begin{flalign}\n  & \\dotE{13}{12} = \\eta_{mot} \\dotE{14}{13} & 0 < \\eta_{mot} < 1 \\hspace{1.9cm} \\nonumber \\\\\n  & \\dotQ{13}{12} = f_{05} \\left( 1 - \\eta_{mot} \\right) \\dotE{14}{13} & 0 < f_{05} < 1 \\hspace{2.1cm} \\nonumber \\\\\n  & \\dotQ{13}{07} = f_{06} \\left( 1 - \\eta_{mot} \\right) \\dotE{14}{13} & 0 < f_{06} < 1 \\hspace{2.1cm} \\nonumber \\\\\n  & h_{13,out} = \\dfrac{\\dotE{14}{13} - \\dotE{13}{12} - \\dotQ{13}{12} - \\dotQ{13}{07} + \\dotMh{26}{13}}{\\dotM{13}{12}}\n\\end{flalign}\n\nAccording to their definitions, we observe that $f_{05}$ and $f_{06}$\nhave to respect the relation $0 < f_{05} + f_{06} < 1$.\n\nIf we consider the energy balance on component \\#12, we get\n$\\dotE{13}{12} + \\dotQ{13}{12} + \\dotMh{13}{12} +\n\\dotMh{21}{12} - \\dotMh{12}{24} - \\dotE{12}{11} -\n\\dotQ{12}{11} = 0$.\n$\\dotE{12}{11}$ and $h_{12,out}$ need to be determined to get\n$\\dotQ{12}{11}$.\n\n\\begin{flalign}\n  & \\dotE{12}{11} = \\eta_{ra} \\dotE{13}{12} \\nonumber \\\\\n  & T_{12,out} = \\left( 1 + f_{07} \\right) T_{13,out} & \\Rightarrow h_{12,out} \\hspace{2.1cm} \\nonumber \\\\\n  & \\dotQ{12}{11} = \\dotE{13}{12} + \\dotQ{13}{12} + \\dotMh{13}{12} \\nonumber \\\\\n  &  \\text{\\hspace{1.25cm}} + \\dotMh{21}{12} - \\dotMh{12}{24} - \\dotE{12}{11}\n\\end{flalign}\n\nIf we consider the energy balance on component \\#11, we get\n$\\dotQ{12}{11} + \\dotE{12}{11} - \\dotE{11}{01} - \\dotQ{11}{01} -\n\\dotQ{11}{23} - \\dotQ{11}{24} - \\dotMh{11}{23} +\n\\dotMh{24}{11} - \\dotMh{11}{22} = 0$.\nIn order to determine $h_{11,out}$, the variables $\\dotE{11}{01}$, $h_{24,out}$,\n$\\dotQ{11}{24}$, $\\dotQ{11}{01}$ and $\\dotQ{11}{23}$ need to be\ndetermined.\n\n\\begin{flalign}\n  & \\dotE{11}{01} = \\eta_{axi} \\dotE{12}{11} \\nonumber \\\\\n  & T_{24,out} = \\left( 1 + f_{08} \\right) T_{12,out} & \\Rightarrow h_{24,out} \\hspace{2.1cm} \\nonumber\n\\end{flalign}\n\nThe energy balance on component \\#24 gives us the equation\n$\\dotMh{12}{24} - \\dotMh{24}{11} + \\dotQ{11}{24} =\n0$, which gives \\cref{eq:awp-dotQ_11_24}.\n\n\\begin{flalign}\n  & \\dotQ{11}{24} = \\dotMh{24}{11} - \\dotMh{12}{24} \\label{eq:awp-dotQ_11_24} \\\\\n  & \\dotQ{11}{01} = f_{09} \\dotQ{12}{11} & 0 < f_{09} < 1 \\hspace{2.1cm} \\nonumber \\\\\n  & \\dotQ{11}{23} = f_{10} \\dotQ{12}{11} & 0 < f_{10} < 1 \\hspace{2.1cm} \\nonumber \\\\\n\\end{flalign}\n\n\\begin{flalign}\n  & h_{11,out} = \\dfrac{\\dotQ{12}{11} + \\dotE{12}{11} - \\dotE{11}{01} - \\dotQ{11}{01} - \\dotQ{11}{23} - \\dotQ{11}{24} + \\dotMh{24}{11}}{\\dotM{11}{23} + \\dotM{11}{22}} & \\nonumber\n\\end{flalign}\n\nThe energy balance on component \\#22 gives the equation $\\dotMh{18}{22} + \\dotMh{11}{22} - \\dotMh{22}{29} = 0$, which gives \\cref{eq:awp-hout22}.\n\n\\begin{flalign}\n  & h_{22,out} = \\dfrac{\\dotMh{18}{22} + \\dotMh{11}{22}}{\\dotM{22}{29}} & \\label{eq:awp-hout22}\n\\end{flalign}\n\nThe energy balance on components \\#29 and \\#23 give the balance equations\n$\\dotMh{22}{29} + \\dotMh{23}{29} - \\dotMh{29}{01} = 0$ and\n$\\dotMh{11}{23} + \\dotQ{11}{23} - \\dotMh{23}{29} = 0$\nwhich give \\cref{eq:awp-hout29}.\n\n\\begin{flalign}\n  & h_{29,out} = \\dfrac{\\dotMh{22}{29} + \\dotMh{23}{29}}{\\dotM{29}{01}} & \\label{eq:awp-hout29}\n\\end{flalign}\n\nThe energy balance on component \\#1 gives the equation\n$\\dotE{11}{01} - \\dotMh{01}{25}  + \\dotMh{29}{01} + \\dotQ{11}{01} - \\dotQ{01}{02} - \\dotE{01}{02} = 0$.\n\nWe need a relationship between $T_{01,out}$ and $T_{25,out}$, in order\nto go further. This results in the equation\n\\cref{eq:awp-T01out}. Knowing $T_{01, out}$ gives access to\n$h_{01,out}$ through a computation with REFPROP.\n\n\\begin{flalign}\n  & T_{01,out} = \\dfrac{T_{25,out}}{1 + f_{11}} & 0 < f_{11} < 1 \\hspace{1cm} \\label{eq:awp-T01out}\n\\end{flalign}\n\n\\Cref{eq:awp-T01out} allows to write the equation\n$\\dotE{11}{01} - \\dotE{01}{02} = \\dot{M}_{cp1} \\, \\left( h_{01,out} -\n  h_{29,out} \\right)$, which gives \\cref{eq:awp-E0102}.\n\n\\begin{flalign}\n  & \\dotE{01}{02} = \\dotE{11}{01} - \\dot{M}_{cp1} \\, \\left( h_{01,out} -\n  h_{29,out} \\right) & \\label{eq:awp-E0102} \\\\\n  & \\dotQ{01}{02} = \\dotE{11}{01} - \\dotMh{01}{25} + \\dotMh{29}{01} + \\dotQ{11}{01} - \\dotE{01}{02} \\nonumber\n\\end{flalign}\n\n\nThe energy balance on component \\#02 gives the equation\n$- \\dotMh{02}{10} - \\dotMh{02}{26} - \\dotMh{02}{20} + \\dotMh{28}{02} - \\dotQ{02}{10} + \\dotQ{01}{02} + \\dotE{01}{02} = 0$,\nwhich gives \\cref{eq:awp-Q0210}.\n\n\\begin{flalign}\n  & \\dotQ{02}{10} = \\dotQ{01}{02} + \\dotE{01}{02} - \\dotMh{02}{10} - \\dotMh{02}{26} - \\dotMh{02}{20} + \\dotMh{28}{02} & \\label{eq:awp-Q0210} \\\\\n  & \\dotQ{19}{18} = \\dotM{18}{22} \\left( h_{18,out} - h_{04,out} \\right) \\nonumber\n\\end{flalign}\n\n\\FloatBarrier\n\\bibliographystyle{plainnat}\n\\bibliography{main}\n\\label[secinapp]{sec:awp-eqn-refs}\n", "meta": {"hexsha": "f29c126efe0be7eb6adcac89a8d164c1596fd5ea", "size": 9177, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/awp-eqn.tex", "max_stars_repo_name": "speredenn/epfl-leni-oilfree-radial-cp-hp", "max_stars_repo_head_hexsha": "d3cea3a238c7cccc309400b5686b6ef8ad1d72af", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-09-01T13:30:55.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-01T13:30:55.000Z", "max_issues_repo_path": "tex/awp-eqn.tex", "max_issues_repo_name": "speredenn/epfl-leni-oilfree-radial-cp-hp", "max_issues_repo_head_hexsha": "d3cea3a238c7cccc309400b5686b6ef8ad1d72af", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/awp-eqn.tex", "max_forks_repo_name": "speredenn/epfl-leni-oilfree-radial-cp-hp", "max_forks_repo_head_hexsha": "d3cea3a238c7cccc309400b5686b6ef8ad1d72af", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.9090909091, "max_line_length": 178, "alphanum_fraction": 0.5840688678, "num_tokens": 4216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.3104224805720249}}
{"text": "\\section{Conclusions and future work}\n\\label{sec:conclusions}\n\nThis paper presents a novel framework for predicting the \\gls{rul} of mechanical components. While the method was tested on the jet-engine specific dataset \\gls{cmaps}, the method is general enough so that it can be applied to other kind of similar systems. The framework makes use of a strided moving time window to generate the training and test sets, a shallow \\gls{mlp} to make the predictions of the \\gls{rul} and an evolutionary algorithm (\\gls{de}) which needs to be run just once in order to find the best data-related parameters that optimize the scoring functions used in this study.  The results presented in this paper demonstrate that the proposed framework is accurate and computationally efficient, which makes this framework suitable for applications that have limited computational resources such as embedded systems. Furthermore, a comparison with other state-of-the-art methods shown that the proposed method is the best overall performer. \n\nTwo major features of the proposed framework are its generality and scalability. While for this paper very specific regressors and evolutionary algorithms were chosen, many other combinations are possible and may be more suitable for different applications. Furthermore, the framework here presented can, in principle, be used for model-construction, i.e. generating the best possible neural network architecture tailored to a specific application. Both issues are to be addressed in future work.", "meta": {"hexsha": "4ad7afadc4c26744959cd73c8ec06bface51efea", "size": 1520, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Papers/RUL_NN_DE_paper/jmlr_submission/rul_paper_conclusions.tex", "max_stars_repo_name": "dlaredo/NASA_RUL_-CMAPS-", "max_stars_repo_head_hexsha": "b4fc4267e2abb4b0542e4658fd8ee931ba848fd1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2018-05-09T09:18:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T06:37:53.000Z", "max_issues_repo_path": "Papers/RUL_NN_DE_paper/jmlr_submission/rul_paper_conclusions.tex", "max_issues_repo_name": "hard10086/NASA_RUL_-CMAPS-", "max_issues_repo_head_hexsha": "b4fc4267e2abb4b0542e4658fd8ee931ba848fd1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-06-11T09:09:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-08T21:23:07.000Z", "max_forks_repo_path": "Papers/RUL_NN_DE_paper/jmlr_submission/rul_paper_conclusions.tex", "max_forks_repo_name": "hard10086/NASA_RUL_-CMAPS-", "max_forks_repo_head_hexsha": "b4fc4267e2abb4b0542e4658fd8ee931ba848fd1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-07-06T03:40:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T07:30:26.000Z", "avg_line_length": 253.3333333333, "max_line_length": 959, "alphanum_fraction": 0.8190789474, "num_tokens": 295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.310422474121176}}
{"text": "%% ESyS-Particle Reference Manual\n\n\\documentclass{report}\n\n\\begin{document}\n\\title{ESyS-Particle Scripting Reference Manual}\n\\author{Steffen Abe}\n\\date{\\today}\n\\maketitle\n\\tableofcontents\n\n\\chapter{Introduction}\n\\chapter{Functions}\n\n\\section{Initialization and Setup}\n\n\\subsection{makeLattice}\n\n\\textsf{makeLattice(ParticleType, $\\mathsf{dt}$, nrange, $\\mathsf{\\alpha}$ )}\n\\par \\medskip\n\nSet the basic parameters of the Model. The parameters are:\n\\begin{itemize}\n\\item \\textbf{ParticleType} : The type of particle used in the model. Currently supported are :\n\\begin{itemize}\n\\item ``Basic'' a spherical, non-rotational particle with 3 (translational) degrees of freedom\n\\item \\textit{planned} ``Rotational'' a spherical particle with 6 (translational + rotational) degrees of freedom. \n\\end{itemize}   \n\\item $\\mathbf{dt}$ : The time step used in the time integration scheme.\n\\item \\textbf{nrange}  and $\\mathbf{\\alpha}$ : The parameters determining the search range of the neighbor table. nrange is the cut-off for individual particle pairs to be added to a dynamic interaction group. The neighbour table is rebuilt if any particle moves further than $\\alpha / 2 $ since the last rebuild.\n\\end{itemize}\n \n%% --- setProcessDims ----\n\\subsection{setProcessDims}\n\n\\textsf{setProcessDim(nx,ny,nz)}\n\\par \\medskip\n\nSet the process dimensions. \n\n%% --- setSpatialDomain ---\n\\subsection{setSpatialDomain}\n\n\\textsf{setSpatialDomain($x_{min}$,$y_{min}$,$z_{min}$,$x_{max}$,$y_{max}$,$z_{max}$)}\n\\par \\medskip\n\n%% --- readGeometryFile ----\n\\subsection{readGeometryFile}\n\n\\textsf{readGeometryFile(FileName)}\n\\par \\medskip\nRead in a geometry description file and initialize the model accordingly. The parameter is:\n\\begin{itemize}\n\\item \\textbf{FileName} The name of the geometry file. It has to be either relative to the directory from which the program is run or an absolute pathname.  \n\\end{itemize}\nFor a description the format of the geometry file see \\textit{Doc/FileFormat.tex} in the source distribution. \n\n\\subsection{readMeshFile}\n\\label{sec:readMeshFile}\n\\textsf{resdMeshFile(MeshName,FileName)}\n\\par \\medskip \nRead a mesh file in Finley format and setup a triangle mesh.\n\\begin{itemize}\n\\item \\textbf{MeshName} The name under which the mesh made accessible.\n\\item \\textbf{FileName} The name of the mesh file. It has to be either relative to the directory from which the program is run or an absolute pathname.  \n\\end{itemize}\n \n\\subsection{tagParticleNearestTo}\n\n\\textsf{tagParticleNearestTo(tag,mask,x,y,z)}\n\\par \\medskip\nTag the particle closest to a given position.\n\\begin{itemize}\n\\item \\textbf{tag}\n\\item \\textbf{mask}\n\\item \\textbf{x,y,z}\n\\end{itemize}\n\n\\section{Interactions}\n\n\n\\subsection{AddPairInteractions}\n\n\\textsf{AddPairInteractions(InteractionType, InteractionName, InteractionParameters)}\n\\par \\medskip\n\nAdd a group of interactions between pairs of particles to the model. The InteractionType determines the number and format of the InteractionParameters. The parameters are:\n\\begin{itemize}\n\\item \\textbf{InteractionType} : The type of interaction. \\par\n\\begin{tabular}{|l|l|}\n\\hline\nType of interaction & Supported Particle Type \\\\\n\\hline\n\\hline\nElastic & Basic \\\\\n\\hline\nFriction & Basic \\\\\n\\hline\nFractalFriction & Basic \\\\\n\\hline\nAdhesiveFriction & Basic \\\\\n\\hline\n\\end{tabular} \n\n\\item \\textbf{InteractionName}\n\\item \\textbf{InteractionParameters} The parameters for the interaction. The number and format of the parameters depends on the type of interaction.\n\\begin{itemize}\n\n\\item Elastic : k\n\\begin{itemize}\n\\item k : The spring constant for the elastic interaction\n\\end{itemize}\n\n\\item Friction : k, $\\mu$, $k_s$,dt \\\\\nConstant Coulomb friction. Implementation follow standard Cundall \\& Strack DEM approach\n\\begin{itemize}\n\\item k - elastic spring constant\n\\item $\\mu$ - coefficient of friction\n\\item $k_s$ - shear stiffness (Cundall)\n\\item dt - time step\n\\end{itemize}\n\n\\item FractalFriction : k, $\\mu$, $k_s$, dt \\\\\n\\textit{there are some problems with fractal friction currently (hardcoded filename)}\n\\begin{itemize}\n\\item k - elastic spring constant\n\\item $\\mu$\n\\item $k_s$\n\\item dt\n\\end{itemize}\n\n\\item AdhesiveFriction : k, $\\mu$, $k_s$, dt, $r_{cut}$ \\\\\nCoulomb friction with some adhesion added in. For $r_{ij} < r_0$ it is identical to normal friction, for $r_0 \\le r_{ij} \\le r_{cut}$ there is no friction but an attractive elastic force.\n\\begin{itemize}\n\\item k - elastic spring constant\n\\item $\\mu$ - coefficient of friction\n\\item $k_s$ - shear stiffness (Cundall)\n\\item dt - time step\n\\item $r_{cut}$ - cutoff distance for adhesive elastic interactions \n\\end{itemize} \n\n\\end{itemize}\n\\end{itemize}\n\n\\subsection{AddBondedInteractions}\n\n\\textsf{AddBondedInteractions(Tag, InteractionName, $k$, $r_{break}$)}\n\\par \\medskip\nGenerate a group of bonded interactions from the interaction list read from the geometry file. Only interactions with a given tag will be added to the group.\n\\begin{itemize}\n\\item \\textbf{Tag} : The tag of the interactions which should be in this group \n\\item \\textbf{InteractionName} : The name of the generated interaction group\n\\item \\textbf{$k$} : the elastic spring constant\n\\item \\textbf{$r_{break}$} : the relative extension at which a bond breaks  \n\\end{itemize} \n\n\\subsection{AddRotPairInteractions}\n\n\\textsf{AddRotPairInteractions(InteractionType, InteractionName, InteractionParameters)}\n\\par \\medskip\n\nAdd a group of interactions between pairs of particles to the model.\nThe InteractionType determines the number and format of the InteractionParameters.\nThe parameters are:\n\\begin{itemize}\n  \\item \\textbf{InteractionType} : The type of interaction. \\par\n  \\begin{tabular}{|l|l|}\n  \\hline\n  Type of interaction & Supported Particle Type \\\\\n  \\hline\n  \\hline\n  RotElastic & Rot \\\\\n  \\hline\n  RotFriction & Rot \\\\\n  \\hline\n  \\end{tabular} \n\n  \\item \\textbf{InteractionName} Name of the interaction.\n  \\item \\textbf{InteractionParameters} The parameters for the interaction.\n    The number and format of the parameters depends on the type of interaction.\n    \\begin{itemize}\n      \\item Elastic : k\n      \\begin{itemize}\n        \\item k : The spring constant for the elastic interaction\n      \\end{itemize}\n\n      \\item RotFriction : $k$, $\\mu_s$, $\\mu_d$, $k_s$, $\\delta t$ \\\\\n      Constant Coulomb friction. Implementation follow standard Cundall \\& Strack DEM approach\n      \\begin{itemize}\n        \\item $k$ - elastic spring constant\n        \\item $\\mu_s$ - static coefficient of friction\n        \\item $\\mu_d$ - dynamic coefficient of friction\n        \\item $k_s$ - shear stiffness (Cundall)\n        \\item $\\delta t$ - time step\n      \\end{itemize}\n    \\end{itemize}\n\\end{itemize}\n\n\\subsection{AddRotBondedInteractions}\n\\label{sec::AddRotBondedInteractions}\n\n\\newcommand{\\brkForce}[1]{f^{\\rm max}_{#1}}\n\\newcommand{\\brkTorque}[1]{t^{\\rm max}_{#1}}\n\\textsf{AddRotBondedInteractions(Tag, InteractionName, $k_r$, $k_s$, $k_t$, $k_b$, $\\brkForce{r}$, $\\brkForce{s}$, $\\brkForce{t}$, $\\brkForce{b}$)}\nGenerate a group of rotational bonded interactions from the interaction\nlist read from the geometry file. Only interactions with a given tag\nwill be added to the group.\n\\begin{itemize}\n\\item{\\textbf Tag}\n\\item{\\textbf InterationName}\n\\item{$k_r$} : radial (normal) spring constant,\n\\item{$k_s$} : shearing (tangent) spring constant,\n\\item{$k_t$} : torsional spring constant,\n\\item{$k_b$} : bending spring constant,\n\\item{$\\brkForce{r}$} : maximum normal force for bond breakage,\n\\item{$\\brkForce{s}$} : maximum shear force for bond breakage,\n\\item{$\\brkTorque{t}$} : maximum torsion torque for bond breakage,\n\\item{$\\brkTorque{b}$} : maximum bending torque for bond breakage.\n\\end{itemize}\n\n\n\\subsection{AddExclusion}\n\\label{sec::AddExclusion}\n\n\\textsf{AddExclusion(InteractionName1, InteractionName2)}\n\\par \\medskip\nPrevent particle pair which are in one interaction group to be also in another interaction group. An common example would be that two particles which are linked together, i.e. the pair is in a bonded interaction group, can not also be in elastic or frictional interaction.\nThe parameters are:\n\\begin{itemize}\n\\item \\textbf{InteractionName1} : The name of the interaction group the pair is excluded from.\n\\item \\textbf{InteractionName2} : The name of the interaction group in which the pair has to be to be excluded from InteractionGroup1\n\\end{itemize} \n\n\\subsection{AddDamping}\n\n\\textsf{AddDamping(InteractionName, $\\nu$, $dt$, $N_{max}$)}\n\\par \\medskip\n\n%%=== addTriMeshInteraction ===\n\\subsection{addTriMeshInteraction}\n\n\\textsf{addTriMeshInteactions(InteractionType,InteractionName,MeshName,Parameters)}\n\\par\\medskip\nAdd a group of interactions between a triangle mesh and the particles. The mesh needs to be read in with a call to \\textbf{readMeshFile}(see section \\ref{sec:readMeshFile}) before.\n\n\\begin{itemize}\n\\item \\textbf{InteractionType} : The type of interaction. \\par\n\\begin{tabular}{|l|l|}\n\\hline\nType of interaction & Supported Particle Type \\\\\n\\hline\n\\hline\nElastic & Basic \\\\\n\\hline\n\\end{tabular}\n\n\\item \\textbf{InteractionName} The name of the new interaction group\n\\item \\textbf{MeshName} The name of the mesh (see \\ref{sec:readMeshFile}) with wh ich the particles interact\n\\item \\textbf{InteractionParameters} The parameters for the interaction. The number and format of the parameters depends on the type of interaction.\n\\begin{itemize}\n\\item Elastic : k\n\\begin{itemize}\n\\item k : The spring constant for the elastic interaction\n\\end{itemize} %% Elastic\n\n\\end{itemize} %% parameters\n\n\n\\end{itemize}\n\n%%=== addBondedTriMeshInteractions ===\n\\subsection{addBondedTriMeshInteractions}\n\n\\textsf{addBondedTriMeshInteractions(InteractionName,MeshName,k,$r_{break}$,BuildType,BuildParams)}\n\\par\\medskip\nAdd a group of bonded interactions between a triangle mesh and the particles. The mesh needs to be read in with a call to \\textbf{readMeshFile}(see section \\ref{sec:readMeshFile}) before.\n\n\\begin{itemize}\n\\item BuildByTag : tag,mask\n\\item BuildByGap : gap\n\\end{itemize}\n%%=== SetParticleNonDynamic ===\n\\subsection{SetParticleNonDynamic}\n\n\\textsf{SetParticleNonDynamic(Tag)}\n\\par \\medskip\nMake all particles with the given tag non-dynamic, i.e. interactions involving those particles will still generate forces, but the particles will not move in response to this forces. This is achieved by setting $1/mass=0$, i.e. have infinite mass in the calculation of particle acceleration but also have $mass=0$ for the calculation of kinetic energy.\nThe parameter is:\n\\begin{itemize}\n\\item \\textbf{Tag} : The tag which the particles need to have.\n\\end{itemize}\n\n%%=== SetParticleNonRot ===\n\\subsection{SetParticleNonRot}\n\n\\textsf{SetParticleNonRot(Tag)}\n\\par \\medskip\nMake all particles with the given tag non-rotational, i.e. interactions involving those particles will still generate forces, but the particles will not rotate in response to this forces. This is achieved by setting the inverse moment of inertia to 0; \nThe parameter is:\n\\begin{itemize}\n\\item \\textbf{Tag} : The tag which the particles need to have.\n\\end{itemize}\n \n\\section{Walls}\n\n``Walls'' in the Lattice Solid Model are used to represent the boundary conditions of the models .They behave as rigid, planar objects which interact with the particles, but aren't dynamically moving in response to the resulting forces themselves. They could, in a sense be considered to be of infinite mass.  \\par\nAll the walls generated by initWall and related functions, i.e. initWall (\\ref{sec::initWall}), initBondedWall (\\ref{sec::initBondedWall}) and initSoftBondedWall(\\ref{sec::initSBWall}) will have ids assigned in order of their construction, beginning with 0, i.e. the first call generates the wall with id 0, the second call generates the wall with id 1 and so on.\n\n\\subsection{initWall}\n\\label{sec::initWall}\n\n\\textsf{initWall($P_x$, $P_y$, $P_z$, $N_x$, $N_y$, $N_z$,k)}\n\\par \\medskip\nAdd a infinite, planar, elastic wall with a defined position. The geometry of the wall is described by a point on the plane and the normal vector. Any particles which are in contact with the wall, i.e. the separation between the particle position and the plane is smaller than the particle radius interact with the wall by a repulsive linear elastic interaction, $F=k(r-r_0)\\mathbf{n}$ where $F$ is the force applied to the particle, $k$ the spring constant, $r$ the distance between the plane and the particle position, $r_0$ the particle radius and $\\mathbf{n}$ the normal vector of the plane. \\par\nThe parameters are:\n\\begin{itemize}\n\\item $\\mathbf{P_x}$, $\\mathbf{P_y}$, $\\mathbf{P_z}$ : A point on the plane (x, y and z component).\n\\item $\\mathbf{N_x}$, $\\mathbf{N_y}$, $\\mathbf{N_z}$ : The normal vector (x, y and z component).\n\\item \\textbf{k} : The spring constant for the elastic interactions between the wall and the particles.\n\\end{itemize}\n\n\\subsection{initBondedWall}\n\\label{sec::initBondedWall}\nAdd a infinite, planar wall bonded to some particles. The geometry of the wall is described by a point on the plane and the normal vector. \n\n\\textsf{initBondedWall($P_x$, $P_y$, $P_z$, $N_x$, $N_y$, $N_z$,k,Tag)}\n\\par\\medskip\nThe parameters are:\n\\begin{itemize}\n\\item $\\mathbf{P_x}$, $\\mathbf{P_y}$, $\\mathbf{P_z}$ : A point on the plane (x, y and z component).\n\\item $\\mathbf{N_x}$, $\\mathbf{N_y}$, $\\mathbf{N_z}$ : The normal vector (x, y and z component).\n\\item \\textbf{k} : The spring constant for the elastic interactions between the wall and the particles.\n\\item \\textbf{Tag}\n\\end{itemize}\n\n\\subsection{initViscWall}\n\\label{sec::initViscWall}\nAdd a infinite, planar wall exerting viscous drag to the tagged particles if moved. The geometry of the wall is described by a point on the plane and the normal vector. \n\n\\textsf{initViscWall($P_x$, $P_y$, $P_z$, $N_x$, $N_y$, $N_z$,k,$\\nu$,Tag)}\n\\par\\medskip\nThe parameters are:\n\\begin{itemize}\n\\item $\\mathbf{P_x}$, $\\mathbf{P_y}$, $\\mathbf{P_z}$ : A point on the plane (x, y and z component).\n\\item $\\mathbf{N_x}$, $\\mathbf{N_y}$, $\\mathbf{N_z}$ : The normal vector (x, y and z component).\n\\item \\textbf{k} : The spring constant for the elastic interactions between the wall and the particles.\n\\item $\\mathbf{\\nu}$\n\\item \\textbf{Tag}\n\\end{itemize}\n\n\\subsection{initSoftBondedWall}\n\\label{sec::initSBWall}\nAdd a infinite, planar wall bonded to some particles. The geometry of the wall is described by a point on the plane and the normal vector. The spring coefficients for the interaction between particles and the wall are dependent on the direction.\n\n\\textsf{initSoftBondedWall($P_x$, $P_y$, $P_z$, $N_x$, $N_y$, $N_z$,$k_x$,$k_y$,$k_z$,Tag)}\n\\par\\medskip\nThe parameters are:\n\\begin{itemize}\n\\item $\\mathbf{P_x}$, $\\mathbf{P_y}$, $\\mathbf{P_z}$ : A point on the plane (x, y and z component).\n\\item $\\mathbf{N_x}$, $\\mathbf{N_y}$, $\\mathbf{N_z}$ : The normal vector (x, y and z component).\n\\item $\\mathbf{k_x}$, $\\mathbf{k_y}$, $\\mathbf{k_z}$ : The spring constants for the bonded elastic interactions between the wall and the particles in x-, y- and z-directions.\n\\item \\textbf{Tag}\n\\end{itemize}\n\n\n\\section{Moving things around and applying forces}\n\n\\subsection{MoveParticleTo}\n\n\n\\subsection{SetParticleVelocity} \n\n\\textsf{SetParticleVelocity(Id,$v_x$,$v_y$,$v_z$)}\n\\par\\medskip\n\nSet the velocity of a particle to a given value.\nThe parameters are:\n\\begin{itemize}\n\\item \\textbf{Id} : the id of the particle\n\\item $\\mathbf{v_x}$,$mathbf{v_y}$,$mathbf{v_z}$ : the velocity\n\\end{itemize}\n \n\\subsection{moveWall}\n\n\\textsf{moveWall(Id,$D_x$, $D_y$, $D_z$)}\n\\par\\medskip\n\nThe parameters are:\n\n\\begin{itemize}\n\\item \\textbf{Id} :\n\\item $D_x$, $D_y$, $D_z$ :\n\\end{itemize}\n\n\n\\subsection{applyForceToWall}\nApply a given force to a wall. The force is only applied during the current timestep, i.e. the function needs to be called within the Loading function in the script.\n\\textit{Not implemented for SoftBonded (\\ref{sec::initSBWall}) walls.}\n\n\\textsf{applyForceToWall(Id,$F_x$, $F_y$, $F_z$)}\n\\par\\medskip\n\nThe parameters are:\n\n\\begin{itemize}\n\\item \\textbf{Id} : The Id of the wall. \n\\item $F_x$, $F_y$, $F_z$ : The force to be applied (x, y and z component).\n\\end{itemize}\n\n\\subsection{setVelocityOfWall}\n\n\\section{Saving Stuff}\n\n\\subsection{Fields Overview}\n\nThe fields which can be saved are distinguished by two properties: the objects they are defined on, i.e. particles or interactions and the data type of the field, i.e. scalar or vector (tensor to come). \n\n\\subsection{Available Fields}\n        \n\\subsubsection{Fields available on Particles}\n\\par \\medskip\n\n\\begin{tabular}{|l|p{3.5cm}|l|p{2.5cm}|}\n\\hline\nName & Field & Data type & Supported Particle Types \\\\\n\\hline \\hline\n\\verb{e_kin{ & kinetic energy & scalar & Basic \\\\\n\\hline\n\\verb{displacement{ & total displacement & vector & Basic \\\\\n\\hline\n\\verb{velocity{ & linear velocity & vector & Basic \\\\\n\\hline \n\\verb{v_abs{ & absolute value of linear velocity & scalar & Basic \\\\\n\\hline \n\\verb{force{ & force applied to the particle & vector & Basic \\\\\n\\hline\n\\end{tabular}\n\n\\subsubsection{Fields available on Interactions}\n\\par \\medskip\n\n\\begin{tabular}{|l|p{2.6cm}|l|p{2.5cm}|c|}\n\\hline\nName & Field & Data type & Supported Interaction Types & checked\\\\\n\\hline \\hline\n\\verb{potential_energy{ & potential energy & scalar & Bonded, Friction, FractalFriction &\\\\\n\\hline\n\\verb{slipping{ & number of frictional interactions in a dynamic state & scalar & Friction, FractalFriction &\\\\\n\\hline\n\\verb{F_fric{ & current frictional force & scalar & Friction & x \\\\\n\\hline\n\\verb{muF_n{ & product of coefficient of friction and normal force & scalar & Friction & x \\\\\n\\verb{F_fric{ & current frictional force & scalar & Friction & x \\\\\n\\hline\n\\verb{strain{ & relative strain on interaction, compression positive & scalar & Bonded & \\\\ \n\\hline\n\\end{tabular}\n\n\\subsubsection{Fields available on Triangles}\n\\par \\medskip\n\n\\begin{tabular}{|l|p{3.5cm}|l|}\n\\hline\nName & Field & Data type \\\\\n\\hline \\hline\n\\verb{force{ & total force & vector \\\\\n\\hline\n\\verb{pressure{ & pressure & scalar \\\\\n\\hline\n\\end{tabular}\n\n\n\\subsection{Output Formats}\n\\label{sec::OutputFormats}\n\nAll field can be saved in different formats. The following formats are currently supported:\n   \n\\begin{itemize}\n\\item \\textbf{DX} : The complete field is saved in one OpenDX compatible file for each timestep. For particle based fields  the position of the particle and the value of the field at that particle are saved. For interaction based fields the position of the centre of the interaction, i.e. in case of a 2-particle interaction the middle point between the particles, and the value of the field for this interaction is saved.\n\\item \\textbf{SUM} : The sum over all data in the field is saved into one continuous file, one value per timestep.\n\\item \\textbf{MAX} : The maximum over all data in the field is saved into one continuous file, one value per timestep. \n\\item \\textbf{RAW\\_SERIES} : The complete field is saved in one file, one row of values per time step. \\textit{not yet implemented for interaction fields} \n\\end{itemize}\n\n\\section{Fields Defined on Interactions} \n\n\\subsection{addScalarInteractionFieldSaver}\n\\textsf{addScalarInteractionFieldSaver(FileName, FieldName, InteractionType, InteractionName, SaveType, $T_0$, $T_{max}$, $dT$)}\n\\par \\medskip\nAdd a saver for a scalar field defined on an interaction. The parameters are:\n\n\\begin{itemize}\n\\item \\textbf{FileName} : The name of the file into which the field is saved. If the  \\textbf{SaveType} is such that the field is saved into a separate file for each time step, for example ``DX'', the \\textbf{FileName} is used as the base for forming the individual filenames as FileName.N.Ext, were N is the number of the file (0....$(T_{max}-T_0)/dT$) and Ext the file extension for the SaveType, such as dx for ``DX''.\n\\item \\textbf{FieldName} : The name of the field to be saved. The name has to be of the fields supported by the Interaction for which it is saved, otherwise an error message will result.\n\\item \\textbf{InteractionType} The type of the interaction for which the field is saved.\n\\item \\textbf{InteractionName} The name of the interaction group for which the field is saved.\n\\item \\textbf{SaveType} The way the field is saved. Currently supported are ``DX'', ``SUM'' and ``MAX''. See section \\ref{sec::OutputFormats}.\n\\item \\textbf{$T_0$} The first timestep for which the field is saved.\n\\item \\textbf{$T_{max}$} The last timestep for which the field is saved.\n\\item \\textbf{$dT$} The number of timesteps between savings. For example if $T_0$=1, $T_{max}$=31 and $dT$=5 the field would be saved for the timesteps 1,6,11,16,21,26,31.\n\\end{itemize}\n\n\\subsection{addTaggedScalarInteractionFieldSaver}\n\\label{sec::TaggedSIFSaver}\n\\textsf{addTaggedScalarInteractionFieldSaver(FileName, FieldName, InteractionType, InteractionName, SaveType, $T_0$, $T_{max}$, $dT$,Tag,Mask)}\n\\par \\medskip\n\nAdd a saver for a scalar field defined on an interaction. The field is only saved for interaction involving at least one particle with a tag fulfilling the given criteria. The parameters are:\n\n\\begin{itemize}\n\\item \\textbf{FileName} : The name of the file into which the field is saved. If the  \\textbf{SaveType} is such that the field is saved into a separate file for each time step, for example ``DX'', the \\textbf{FileName} is used as the base for forming the individual filenames as FileName.N.Ext, were N is the number of the file (0....$(T_{max}-T_0)/dT$) and Ext the file extension for the SaveType, such as dx for ``DX''.\n\\item \\textbf{FieldName} : The name of the field to be saved. The name has to be of the fields supported by the Interaction for which it is saved, otherwise an error message will result.\n\\item \\textbf{InteractionType} The type of the interaction for which the field is saved.\n\\item \\textbf{InteractionName} The name of the interaction group for which the field is saved.\n\\item \\textbf{SaveType} The way the field is saved. Currently defined are ``DX'', ``SUM'' and ``MAX''. See section \\ref{sec::OutputFormats}.\n\\item \\textbf{$T_0$} The first timestep for which the field is saved.\n\\item \\textbf{$T_{max}$} The last timestep for which the field is saved.\n\\item \\textbf{$dT$} The number of timesteps between savings. \n\\item \\textbf{Tag} The particle tag.\n\\item \\textbf{Mask} The mask used in the tag comparison, i.e. a interaction is included if for at least one of the particles involved the following is true: $(particle->getTag() | Mask ) == (Tag | Mask)$, i.e. the mask is used to determine which bits in the tag are compared. For example if Tag=5 (binary 101) and Mask=4 (binary 100), particles with a tag in which bit 3 is 1 would be used, i.e. 5 (101) or 6 (110), but not 8 (1000). A Mask of -1 (binary all 1) will lead to an exact comparison of the tags.     \n\\end{itemize}\n\n\\subsection{addCheckedScalarInteractionFieldSaver}\n\n\\textsf{addCheckedScalarInteractionFieldSaver(FileName, FieldName, InteractionType, InteractionName, SaveType, $T_0$, $T_{max}$, $dT$)}\n\\par \\medskip\n\nAdd a saver for a checked scalar field defined on an interaction, i.e. the field is only saved for interactions where the field access function returns ``true''.  The parameters are:\n\n\\begin{itemize}\n\\item \\textbf{FileName} : The name of the file into which the field is saved. If the  \\textbf{SaveType} is such that the field is saved into a separate file for each time step, for example ``DX'', the \\textbf{FileName} is used as the base for forming the individual filenames as FileName.N.Ext, were N is the number of the file (0....$(T_{max}-T_0)/dT$) and Ext the file extension for the SaveType, such as dx for ``DX''.\n\\item \\textbf{FieldName} : The name of the field to be saved. The name has to be of the fields supported by the Interaction for which it is saved, otherwise an error message will result.\n\\item \\textbf{InteractionType} The type of the interaction for which the field is saved.\n\\item \\textbf{InteractionName} The name of the interaction group for which the field is saved.\n\\item \\textbf{SaveType} The way the field is saved. Currently supported are ``DX'', ``SUM'' and ``MAX''. See section \\ref{sec::OutputFormats}.\n\\item \\textbf{$T_0$} The first timestep for which the field is saved.\n\\item \\textbf{$T_{max}$} The last timestep for which the field is saved.\n\\item \\textbf{$dT$} The number of timesteps between savings.\n\\end{itemize}\n\n\n\\subsection{addTaggedCheckedScalarInteractionFieldSaver}\n\n\\textsf{addTaggedCheckedScalarInteractionFieldSaver(FileName, FieldName, InteractionType, InteractionName, SaveType, $T_0$, $T_{max}$, $dT$,Tag,Mask)}\n\\par \\medskip\n\nChecked version of \\textsf{addTaggedScalarInteractionFieldSaver} (see \\ref{sec::TaggedSIFSaver}). The parameters are:\n\n\\begin{itemize}\n\\item \\textbf{FileName} : The name of the file into which the field is saved. If the  \\textbf{SaveType} is such that the field is saved into a separate file for each time step, for example ``DX'', the \\textbf{FileName} is used as the base for forming the individual filenames as FileName.N.Ext, were N is the number of the file (0....$(T_{max}-T_0)/dT$) and Ext the file extension for the SaveType, such as dx for ``DX''.\n\\item \\textbf{FieldName} : The name of the field to be saved. The name has to be of the fields supported by the Interaction for which it is saved, otherwise an error message will result.\n\\item \\textbf{InteractionType} The type of the interaction for which the field is saved.\n\\item \\textbf{InteractionName} The name of the interaction group for which the field is saved.\n\\item \\textbf{SaveType} The way the field is saved. Currently defined are ``DX'', ``SUM'' and ``MAX''. See section \\ref{sec::OutputFormats}.\n\\item \\textbf{$T_0$} The first timestep for which the field is saved.\n\\item \\textbf{$T_{max}$} The last timestep for which the field is saved.\n\\item \\textbf{$dT$} The number of timesteps between savings. \n\\item \\textbf{Tag} The particle tag.\n\\item \\textbf{Mask} The mask used in the tag comparison.     \n\\end{itemize}\n\\subsection{addVectorInteractionFieldSaver}\n\n\\textsf{addVectorInteractionFieldSaver(FileName,FieldName,IGType,IGName,SaveType,$t_0$,$t_{end}$,$dt$)}\n\n\\subsection{addTaggedVectorInteractionFieldSaver}\n\n\\textsf{NOT IMPLEMENTED}\n\n\\section{Fields Defined on Particles}\n\n\\subsection{addScalarParticleFieldSaver}\n\n\\textsf{addScalarParticleFieldSaver(FileName, FileName, SaveType, $T_0$, $T_{max}$, $dt$)}\n\\par \\medskip\n\nAdd a saver for a scalar field defined on the particles. The parameters are:\n\n\\begin{itemize}\n\\item \\textbf{FileName} : The name of the file into which the field is saved. If the  \\textbf{SaveType} is such that the field is saved into a separate file for each time step, for example ``DX'', the \\textbf{FileName} is used as the base for forming the individual filenames as FileName.N.Ext, were N is the number of the file (0....$(T_{max}-T_0)/dT$) and Ext the file extension for the SaveType, such as dx for ``DX''.\n\\item \\textbf{FieldName} : The name of the field to be saved. The name has to be of the fields supported by the Interaction for which it is saved, otherwise an error message will result.\n\\item \\textbf{SaveType} The way the field is saved. Currently supported are ``DX'' and ``SUM''. See section \\ref{sec::OutputFormats}.\n\\item \\textbf{$T_0$} The first timestep for which the field is saved.\n\\item \\textbf{$T_{max}$} The last timestep for which the field is saved.\n\\item \\textbf{$dT$} The number of timesteps between savings. For example if $T_0$=1, $T_{max}$=31 and $dT$=5 the field would be saved for the timesteps 1,6,11,16,21,26,31.\n\\end{itemize}\n\n\\subsection{addTaggedScalarParticleFieldSaver}\n\n\\textsf{addTaggedScalarParticleFieldSaver(FileName, FieldName, FileFormat, $T_0$, $T_{max}$, $dt$, Tag, Mask)}\n\\par \\medskip\n\nAdd a saver for a scalar field defined on the particles. The field is only saved for particles with a tag fulfilling the given criteria. The parameters are:\n\n\\begin{itemize}\n\\item \\textbf{FileName} : The name of the file into which the field is saved. If the  \\textbf{SaveType} is such that the field is saved into a separate file for each time step, for example ``DX'', the \\textbf{FileName} is used as the base for forming the individual filenames as FileName.N.Ext, were N is the number of the file (0....$(T_{max}-T_0)/dT$) and Ext the file extension for the SaveType, such as dx for ``DX''.\n\\item \\textbf{FieldName} : The name of the field to be saved. The name has to be of the fields supported by the Interaction for which it is saved, otherwise an error message will result.\n\\item \\textbf{SaveType} The way the field is saved. Currently defined are ``DX'' and ``SUM''. See section \\ref{sec::OutputFormats}.\n\\item \\textbf{$T_0$} The first timestep for which the field is saved.\n\\item \\textbf{$T_{max}$} The last timestep for which the field is saved.\n\\item \\textbf{$dT$} The number of timesteps between savings. \n\\item \\textbf{Tag} The particle tag.\n\\item \\textbf{Mask} The mask used in the tag comparison, i.e. the field is saved for particles for which the following is true: $(particle->getTag() | Mask ) == (Tag | Mask)$, i.e. the mask is used to determine which bits in the tag are compared. For example if Tag=5 (binary 101) and Mask=4 (binary 100), particles with a tag in which bit 3 is 1 would be used, i.e. 5 (101) or 6 (110), but not 8 (1000). A Mask of -1 (binary all 1) will lead to an exact comparison of the tags.     \n\\end{itemize}\n\n\\subsection{addVectorParticleFieldSaver}\n\n\\textsf{addVectorParticleFieldSaver(FileName, FieldName, FileFormat, $T_0$, $T_{max}$, $dt$)}\n\\par \\medskip\n\nAdd a saver for a vector field defined on the particles. The parameters are:\n\n\\begin{itemize}\n\\item \\textbf{FileName} : The name of the file into which the field is saved. If the  \\textbf{SaveType} is such that the field is saved into a separate file for each time step, for example ``DX'', the \\textbf{FileName} is used as the base for forming the individual filenames as FileName.N.Ext, were N is the number of the file (0....$(T_{max}-T_0)/dT$) and Ext the file extension for the SaveType, such as dx for ``DX''.\n\\item \\textbf{FieldName} : The name of the field to be saved. The name has to be of the fields supported by the Interaction for which it is saved, otherwise an error message will result.\n\\item \\textbf{SaveType} The way the field is saved. Currently supported are ``DX'' and ``SUM''. See section \\ref{sec::OutputFormats}.\n\\item \\textbf{$T_0$} The first timestep for which the field is saved.\n\\item \\textbf{$T_{max}$} The last timestep for which the field is saved.\n\\item \\textbf{$dT$} The number of timesteps between savings. For example if $T_0$=1, $T_{max}$=31 and $dT$=5 the field would be saved for the timesteps 1,6,11,16,21,26,31.\n\\end{itemize}\n\n\n\\subsection{addTaggedVectorParticleFieldSaver}\n\n\\textsf{addTaggedVectorParticleFieldSaver(FileName, FieldName, FileFormat, $T_0$, $T_{max}$, $dt$, Tag, Mask)}\n\\par \\medskip\n\nAdd a saver for a vector field defined on the particles. The field is only saved for particles with a tag fulfilling the given criteria. The parameters are:\n\n\\begin{itemize}\n\\item \\textbf{FileName} : The name of the file into which the field is saved. If the  \\textbf{SaveType} is such that the field is saved into a separate file for each time step, for example ``DX'', the \\textbf{FileName} is used as the base for forming the individual filenames as FileName.N.Ext, were N is the number of the file (0....$(T_{max}-T_0)/dT$) and Ext the file extension for the SaveType, such as dx for ``DX''.\n\\item \\textbf{FieldName} : The name of the field to be saved. The name has to be of the fields supported by the Interaction for which it is saved, otherwise an error message will result.\n\\item \\textbf{SaveType} The way the field is saved. Currently defined are ``DX'' and ``SUM''. See section \\ref{sec::OutputFormats}.\n\\item \\textbf{$T_0$} The first timestep for which the field is saved.\n\\item \\textbf{$T_{max}$} The last timestep for which the field is saved.\n\\item \\textbf{$dT$} The number of timesteps between savings. \n\\item \\textbf{Tag} The particle tag.\n\\item \\textbf{Mask} The mask used in the tag comparison, i.e. the field is saved for particles for which the following is true: $(particle->getTag() | Mask ) == (Tag | Mask)$, i.e. the mask is used to determine which bits in the tag are compared. For example if Tag=5 (binary 101) and Mask=4 (binary 100), particles with a tag in which bit 3 is 1 would be used, i.e. 5 (101) or 6 (110), but not 8 (1000). A Mask of -1 (binary all 1) will lead to an exact comparison of the tags.     \n\\end{itemize}\n\n\\section{Other fields}\n\n\\subsection{addVectorTriangleFieldSaver}\n\\textsf{addVectorTriangleFieldSaver(FileName,FieldName,MeshName,SaveType,$t_0$,$t_{end}$,$dt$)}\n\\par \\medskip\n\nAdd a saver for a vector field defined on the triangles of a given mesh. The parameters are:\n\\begin{itemize}\n\\item \\textbf{FileName}\n\\item \\textbf{FieldName}\n\\item \\textbf{MeshName}\n\\item \\textbf{SaveType}\n\\item \\textbf{$t_0$} The first timestep for which the field is saved.\n\\item \\textbf{$t_{max}$} The last timestep for which the field is saved.\n\\item \\textbf{$dt$} The number of timesteps between savings. \n\n\\end{itemize}\n\n\\subsection{addScalarrTriangleFieldSaver}\n\\textsf{addScalarTriangleFieldSaver(FileName,FieldName,MeshName,SaveType,$t_0$,$t_{end}$,$dt$)}\n\\par \\medskip\n\nAdd a saver for a scalar field defined on the triangles of a given mesh. The parameters are:\n\\begin{itemize}\n\\item \\textbf{FileName}\n\\item \\textbf{FieldName}\n\\item \\textbf{MeshName}\n\\item \\textbf{SaveType}\n\\item \\textbf{$t_0$} The first timestep for which the field is saved.\n\\item \\textbf{$t_{max}$} The last timestep for which the field is saved.\n\\item \\textbf{$dt$} The number of timesteps between savings. \n\n\\end{itemize}\n\n\\chapter{Examples}\n\n\\end{document}\n", "meta": {"hexsha": "795f84eeb59512b82005b43d20172d2e845123ef", "size": 33646, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Doc/Deprecated/Refman/refman.tex", "max_stars_repo_name": "danielfrascarelli/esys-particle", "max_stars_repo_head_hexsha": "e56638000fd9c4af77e21c75aa35a4f8922fd9f0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Doc/Deprecated/Refman/refman.tex", "max_issues_repo_name": "danielfrascarelli/esys-particle", "max_issues_repo_head_hexsha": "e56638000fd9c4af77e21c75aa35a4f8922fd9f0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Doc/Deprecated/Refman/refman.tex", "max_forks_repo_name": "danielfrascarelli/esys-particle", "max_forks_repo_head_hexsha": "e56638000fd9c4af77e21c75aa35a4f8922fd9f0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.6986706056, "max_line_length": 600, "alphanum_fraction": 0.7469832967, "num_tokens": 9443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.3103537519138299}}
{"text": "\\chapter{Protostellar Evolution}\n\\label{ch:protostar_evol}\n\n\\marginnote{\n\\textbf{Suggested background reading:}\n\\begin{itemize}\n\\item \\href{http://adsabs.harvard.edu/abs/2014prpl.conf..173L}{Dunham, M.~M., et al. 2014, in \"Protostars and Planets VI\", ed.~H.~Beuther et al., pp.~195-218}, sections 5-9 \\nocite{dunham14a}\n\\end{itemize}\n\\textbf{Suggested literature:}\n\\begin{itemize}\n\\item \\href{http://adsabs.harvard.edu/abs/2011ApJ...738..140H}{Hosokawa, T., Offner, S.~S.~R., \\& Krumholz, M,~R., 2011, ApJ, 738, 140} \\nocite{hosokawa11a}\n\\end{itemize}\n}\n\nThis chapter considers the behavior of the stellar objects that form at the centers of collapsing clouds. Our goal is to understand how the usual theory of stellar structure can be adapted to the case of protostars that are not yet on the main sequence. Since stellar structure is a vast topic by itself, and there are numerous textbooks covering it, we will not attempt to re-derive it in its entirety here. Instead, we will focus on how the theory must be modified for protostars, and to follow the implications of this modification.\n\n\\section{Fundamental Theory}\n\n\\subsection{Time Scales}\n\nThe fundamental reason that stars can be hydrostatic objects is that the time they require to reach a mechanical equilibrium where the inward force of gravity is balanced by outward pressure is small compared to the time required for their energies, and thus pressures, to change. This is in contrast to molecular clouds, which cannot be hydrostatic because they are able to radiate away energy faster than they can reach force balance. We therefore begin our discussion by verifying that the mechanical and thermal equilibration timescales for protostars are, like those timescale for main sequence stars, very well separated.\n\nThe time required for a star to reach mechanical equilibrium is the sound crossing time, $t_s\\sim R/c_s$, where $R$ is the stellar radius and $c_s$ is the sound speed. The virial theorem tells use that the sound speed inside the star (potentially including the contribution from radiation pressure) must be of order $\\sqrt{GM/R}$, where $M$ is the stellar mass. Thus the mechanical equilibration timescale is\n\\begin{equation}\nt_s \\sim \\sqrt{\\frac{R^3}{GM}} = 35\\, M_0^{-1/2} R_1^{3/2}\\mbox{ hours},\n\\end{equation}\nwhere $M_0 = M / \\msun$ and $R_{1} = R/(10\\rsun)$. Here the radius to which we have scaled is a typical one for protostars, as we will see below.\n\nIn contrast, the time required to reach thermal equilibrium is the Kelvin-Helmholtz (KH) time, which is defined as roughly the time required for the star to radiate away its own binding energy,\n\\begin{equation}\nt_{\\rm KH} = \\frac{GM^2}{RL} = 3\\times 10^5\\, M_0^2 R_1^{-1} L_1^{-1}\\mbox{ yr},\n\\end{equation}\nwhere $L_1 = L/(10 \\lsun)$; again this is a typical protostellar value, as we show below. Thus the star reaches mechanical equilibrium essentially instantaneously compared to the time required to reach thermal equilibrium. It is therefore reasonable to assume that at all times the star is in hydrostatic balance, and then to describe its subsequent evolution as movement from one hydrostatic state to another, with the change in state dictated by the evolution of the energy and entropy of the gas. \n\nFor future reference, it is also useful to think about how long accretion will last. At an accretion rate of $10^{-5}$ $\\msun$ yr$^{-1}$, the formation of a 1 $\\msun$ star takes $10^5$ yr. Thus, the accretion time is generally shorter than the KH time, so that stars will cease accreting before they reach thermal equilibrium. Note that this is true only for low mass stars, not high mass ones. We will discuss the case of high mass stars further in Chapter \\ref{ch:massivestar}.\n\n\\subsection{Evolution Equations}\n\nNow that we have shown that we can treat protostars as hydrostatic equilibrium objects, let us proceed to write down the evolution equations that govern the protostar. These should be familiar from stellar structure. An important caveat is that what we cover here represents an extremely simple approach to stellar structure, and that all of the complications that arise in real stellar structure calculations (e.g., rotation, convective overshooting, real stellar atmospheres, etc.) apply equally well to protostellar evolution. The goal here is simply to sketch the basic theory, so that we can understand how it changes for protostars as opposed to main sequence stars.\n\nAs in other stellar structure calculations, it is most convenient to work in Lagrangian coordinates, where we let $M_r$ be the mass interior to radius $r$, so that $M_r$ runs from 0 to $M$. We then solve for stellar properties as a function of $M_r$. The first equation is the standard definition of mass in terms of density and radius:\n\\begin{equation}\n\\label{mass}\n\\frac{\\partial r}{\\partial M_r} = \\frac{1}{4\\pi r^2 \\rho}.\n\\end{equation}\nThe second equation is the equation of hydrostatic balance. In Eulerian coordinates it is\n\\begin{equation}\n\\label{eq:hydrobalance}\n\\frac{\\partial P}{\\partial r} = -\\frac{G M_r \\rho}{r^2},\n\\end{equation}\nand converting to Lagrangian coordinates by dividing by the relationship between $r$ and $M_r$ gives\n\\begin{equation}\n\\frac{\\partial P}{\\partial M_r} = -\\frac{G M_r}{4\\pi r^4}.\n\\end{equation}\n\nThe third equation is the equation of radiation diffusion:\n\\begin{equation}\nF = \\frac{L}{4\\pi r^2} = -\\frac{c}{3\\rho\\kappa_{\\rm R}} \\frac{\\partial E}{\\partial r},\n\\end{equation}\nwhere $F$ is the radiation flux, $L$ is the luminosity passing through radius $r$, and $\\kappa_{\\rm R}$ is the Rosseland mean opacity of the gas. Writing $E=a_R T^4 = 4 \\sigma_{\\rm SB} T^4/(c)$ and again converting to Lagrangian coordinates by dividing by $\\partial r/\\partial M_r$ gives\n\\begin{equation}\nT^3 \\frac{\\partial T}{\\partial M_r} = - \\frac{3\\kappa_{\\rm R} L}{256 \\pi^2 \\sigma_{\\rm SB} r^4}.\n\\end{equation}\nThis applies only as long as the protostar is stable against convection, $\\partial s/\\partial M_r > 0$, i.e., the entropy increases outward. If it is unstable to convection, we instead have\n\\begin{equation}\n\\frac{\\partial s}{\\partial M_r} = 0,\n\\end{equation}\nor some more sophisticated treatment of convection based on mixing-length theory.\n\nFinally, the last equation describes how the internal energy of the fluid evolves:\\footnote{This evolution equation is simply a form of the fundamental thermodynamic relationship $dU = T\\, dS - P\\, dV$, where $dU$ is the change in internal energy, $dS$ is the change in total entropy, and $dV$ is the change in volume. The term on the left hand side is $T \\, dS$, and the term on the right hand side is the change in internal energy due to nuclear reactions ($\\rho \\epsilon$) plus the change due to radiative transfer ($-\\nabla \\mathbf{F} = (1/r^2) (\\partial/\\partial r)(r^2 F)$ in spherical symmetry). Since the system is hydrostatic, the change in volume $dV$ is zero.}\n\\begin{equation}\n\\rho T\\frac{\\partial s}{\\partial t} = \\rho \\epsilon - \\frac{1}{r^2}\\frac{\\partial}{\\partial r}(r^2 F),\n\\end{equation}\nwhere $s$ is the entropy per unit mass of the gas and $\\epsilon$ is the rate of nuclear energy generation per unit mass. Substituting $L = 4 \\pi r^2 F$ gives\n\\begin{equation}\n\\frac{\\partial L}{\\partial r} = 4\\pi r^2 \\rho \\left(\\epsilon - T\\frac{\\partial s}{\\partial t}\\right),\n\\end{equation}\nand dividing once more by $\\partial r/\\partial M_r$ gives\n\\begin{equation}\n\\label{heat}\n\\frac{\\partial L}{\\partial M_r} = \\epsilon - T\\frac{\\partial s}{\\partial t}.\n\\end{equation}\nThis equation is the only one that is different for a protostar than it is for a main sequence star. For a main sequence star, we simply assume that the entropy per unit mass is constant, so we drop the $\\partial s/\\partial t$ term. We are justified in doing this for a main sequence star, because the star is in energy equilibrium between radiative losses and internal energy generation. Thus the entropy distribution in the star changes only in response to changes in chemical composition produced by nuclear burning. That is not the case for a protostar, which is not in energy equilibrium.\n\nThis constitutes four equations in the four unknowns $r$, $P$, $T$, and $L$.  We also require functions specifying the equation of state $P(\\rho)$, the opacity $\\kappa_{\\rm R}(\\rho,T)$, the energy generation rate $\\epsilon(\\rho,T)$, and the entropy $s(\\rho,T)$. Since radiation, degeneracy pressure, and relativistic effects are generally unimportant for protostars, the equation of state is just the usual ideal gas law\n\\begin{equation}\nP = \\frac{\\rho k_B T}{\\mu m_{\\rm H}},\n\\end{equation}\nwhere $\\mu$ is the mean mass for particle in units of hydrogen masses. For constant $\\mu$ the entropy is\n\\begin{equation}\ns = \\frac{k_B}{\\mu m_{\\rm H}} \\ln \\left(\\frac{T^{3/2}}{\\rho}\\right) + \\mbox{const}.\n\\end{equation}\nFor a fully ionized gas $\\mu=0.61$, but in numerical calculations we generally use a numerically tabulated value of $\\mu(\\rho, T)$ and $s(\\rho,T)$. The terms describing the opacity and nuclear energy generation rate are exactly the same as in the case of a main sequence star, with one important exception for nuclear energy generation that we will discuss below.\n\n\\subsection{Boundary Conditions}\n\nThe four structure equations require four boundary conditions to solve. Two are obvious, and are the same for protostars as main sequence stars: at $M_r=0$\n\\begin{eqnarray}\nr(0) & = & 0\\\\\nL(0) & = & 0.\n\\end{eqnarray}\nThe remaining two are less obvious. Thus far everything we have written down is completely identical to the case of a main sequence star, except for the time derivative in the heat equation, but the remaining two boundary conditions, describing the pressure and luminosity at the edge of the star, are different.\n\n\\paragraph{Spherical Accretion Flows.} First consider the simplest case, where we assume spherical symmetry everywhere. A main sequence star effectively has vacuum of negligible pressure outside it, but a protostar does not. It is bounded by an accretion flow, and  the pressure at the stellar surface must be sufficient to halt the flow. The accretion rate onto the star $\\dot{M}$ is related to the density $\\rho_i$ and velocity $v$ of the infalling material by\n\\begin{equation}\n\\dot{M} = 4\\pi r^2 \\rho_i v,\n\\end{equation}\nand the ram pressure at the stellar surface is therefore\n\\begin{equation}\nP(M) = \\rho_i v^2 = \\frac{\\dot{M} v}{4\\pi r^2},\n\\end{equation}\nwhere the right hand side is to be evaluated at $r=R$. If the incoming gas is in free-fall, then we can set $v = v_{\\rm ff} = \\sqrt{2GM/R}$, which gives\n\\begin{equation}\n\\label{pbound1}\nP(M) = \\frac{\\dot{M}}{4\\pi} \\sqrt{\\frac{2 G M}{R^5}},\n\\end{equation}\nwhere $M$ is the total stellar mass. \n\nThe final boundary condition is on the luminosity. For a non-accreting star, in the simplest case we treat the star as radiating as a blackbody, and require that\n\\begin{equation}\n\\label{lbound2}\nL(M)=4\\pi R^2 \\sigma_{\\rm SB} T(M)^4.\n\\end{equation}\nIn more sophisticated computations we derive the luminosity from a stellar atmosphere calculation. The situation is more complex for an accreting star, because the accreting gas carries a non-negligible energy flux with it. The question therefore becomes what fraction of this energy will be radiated away at the stellar surface and what fraction will be advected or radiated into the stellar interior. We will not derive these results in detail, just sketch out the issues. The boundary condition must take the form\n\\begin{equation}\n\\label{lbound1}\nL(M) = L_{\\rm acc} + L_{\\rm bb} - L_{\\rm in},\n\\end{equation}\nwhere $L_{\\rm acc}=G M \\dot{M}/R$ is the mechanical luminosity of the accreting gas, $L_{\\rm bb} = 4\\pi R^2 \\sigma_{\\rm SB} T(M)^4$ represents the blackbody radiation from the stellar surface, and $L_{\\rm in}$ represents the inward flux of energy due to advection and radiation from the shocked gas. One way to think about $L_{\\rm in}$ is that it specifies what fraction of the kinetic energy of the accreting gas escapes promptly as radiation, with the remaining portion assumed to be advected into the stellar interior with the accreting gas. The correct value of $L_{\\rm in}$ is a subtle question, since it depends on the structure of the shock at the stellar surface, and on its geometry. For spherical accretion, \\citet{stahler80a, stahler80b, stahler81a} show that $L_{\\rm in}\\approx 3 L_{\\rm acc}/4$. \n\n\\paragraph{Cold versus Hot Accretion.} Thus far we have assumed that the accretion flow is spherically symmetric, but this assumption may not be even close to correct. In particular, there is good observational evidence for T Tauri stars that accretion occurs only over a small portion of the stellar surface, likely because the star's magnetic field exerts enough pressure to prevent accretion over much of the surface. It is unknown, and a subject of great current debate, whether this is also the case during the optically-hidden main accretion phase, when the accretion rate is much higher than during the later T Tauri phase.\n\nIf the accretion is confined to a small portion of the stellar surface, this has two implications. First, the pressure boundary condition should revert to the usual vacuum one that applies to main sequence stars, since there will be no ram pressure over most of the stellar surface. We can write down this condition by integrating the equation of hydrostatic balance (equation \\ref{eq:hydrobalance}) to obtain \n\\begin{equation}\nP(M) = \\frac{G M}{R}^2 \\int_{R}^{\\infty} \\rho \\, dr.\n\\end{equation}\nIf $\\kappa_{\\rm R}$ changes relatively little past the stellar photosphere, then \n\\begin{equation}\n\\int _{R}^{\\infty} \\rho \\, dr \\approx \\frac{\\tau_{\\rm phot}}{\\kappa_{\\rm R, phot}},\n\\end{equation}\nwhere $\\tau_{\\rm phot}$ is the optical depth from infinity to the photosphere and $\\kappa_{\\rm R, phot}$ is the opacity at the edge of the photosphere. Since the edge of the star is roughly where $\\tau_{\\rm phot} = 2/3$, the boundary condition becomes\n\\begin{equation}\n\\label{pbound2}\nP(M) = \\frac{2 G M}{3 R^2 \\kappa_{\\rm R, phot}}.\n\\end{equation}\nThe second implication of non-spherical accretion is that $L_{\\rm in}$ might be much larger than in the spherical case. This is because, if the accretion shock covers only a small portion of the stellar surface, radiation will be able to escape out the \"sides\" of the shock in a way that it cannot for a fully-confined sphere. There has yet to be a fully detailed calculation of this case, and instead the usual practice in the protostellar evolution community is to parameterize the uncertainty by adopting a value of $L_{\\rm in}$ that lies somewhere between the minimum possible value, corresponding to the spherical case, and the maximum possible value, in which $L_{\\rm in}$ is chosen so as to set the specific entropy of the material being added to the star equal to either the specific entropy of material at the stellar surface, or the mean specific entropy of all material in the star. We refer to cases where the value of $L_{\\rm in}$ is chosen equal or close to the spherical value as \"hot accretion\" models, because the material being added to the star is hot in this case. We refer to models where $L_{\\rm in}$ is chosen so that the specific entropy of accreting material matches that of material already in the star as \"cold accretion\" models, since the material in this case is cold.\n\nIn the absence of a first-principles theoretical calculation, it is difficult to determine whether reality is closer to the hot or cold accretion assumption, and whether the answer to this question might be different for different stars. Approaches to settling this problem have generally relied on the empirical approach of generating synthetic tracks from hot or cold accretion assumptions and then comparing to observations to see what gives the best fit. The method by which we can generate these tracks we defer to Section \\ref{ssec:protostar_numeric}.\n\n\\subsection{Deuterium Burning}\n\nBefore discussing how the structure equations can be solved numerically, it is worth delving a little further into the term $\\epsilon$, representing nuclear energy generation. For a main sequence star, $\\epsilon$ comes from fusion of hydrogen into helium, either via the pp-chain or the CNO cycle. However, hydrogen burning does not occur until just before the star reaches the main sequence.\n\nThere is, however, an energetically-important nuclear reaction that can occur at lower temperatures, before the star is hot enough to burn hydrogen: fusion of deuterium, via the reaction\n\\begin{equation}\n^2\\mbox{H} + \\,^1\\mbox{H}\\, \\rightarrow \\, ^3\\mbox{He} + \\gamma.\n\\end{equation}\nThis reaction begins to occur at an appreciable rate once the temperature reaches $10^6$ K, and the reaction releases $5.5$ MeV per deuterium nucleus burned. The energy generation rate from deuterium fusion is reasonably well-approximated by \\citep{kippenhahn94a}\n\\begin{equation}\n\\epsilon \\approx \n\\left\\{\n\\begin{array}{ll}\n0, & T < 10^6\\mbox{ K} \\\\\n4.19\\times 10^7\\, [\\mbox{D}/\\mbox{H}] \\rho_0 T_6^{11.8} \\mbox{ erg g}^{-1}\\mbox{ s}^{-1}\n\\qquad & T > 10^6\\mbox{ K},\n\\end{array}\n\\right.\n\\end{equation}\nwhere $[\\mbox{D}/\\mbox{H}]$ is the ratio of D to H in the gas, $\\rho_0=\\rho/(1\\mbox{ g cm}^{-3})$, and $T_6=T/(10^6\\mbox{ K})$. For interstellar gas in the Milky Way, $[\\mbox{D}/\\mbox{H}]\\approx 2\\times 10^{-5}$, which is only slightly below the primordial abundance.\n\nStrictly speaking the expression we have for $T>10^6$ K is only valid for temperatures near $10^6$ K, but, as we shall see, this good enough for our purposes. If we wish to run a model past the start of H burning, we need an analogous expression for it, which is the same as one used for normal main sequence stellar structure calculations.\n\n\\subsection{Numerical Solution}\n\\label{ssec:protostar_numeric}\n\nWe have now fully specified the equations describing our protostar. To construct a numerical model, we need to specify the accretion rate $\\dot{M}$ that appears in the boundary condition equations (\\ref{pbound1}) and (\\ref{lbound1}) describing the pressure and luminosity at the stellar surface. In general $\\dot{M}$ can be a function of time, although usually it is taken to be constant until accretion halts at some specified final stellar mass $M_*$, at which point we switch to boundary conditions (\\ref{pbound2}) and (\\ref{lbound2}) for the boundary pressure and luminosity.\n\nWe must also start with an initial condition, which we usually take to be a simple polytrope. This gives us initial profiles of $r$, $P$, $T$, and $L$, from which we can obtain other derived variables like $\\rho$ and $s$, as a function of $M_r$. The choice of initial condition might matter a little or a lot, depending on the choice of boundary conditions, as we will see.\n\nGiven these boundary conditions, we construct the solution at each time using a shooting method in much the same way as we would for a main sequence star. We first guess a central temperature $T$ and pressure $P$, which of course also gives us the central density $\\rho$ and entropy $s$. Usually a good first guess is the value of $\\rho$ and $s$ at the last time step. Then we integrate equations (\\ref{mass}) - (\\ref{heat}) outward in radius until we reach the outer mass shell $M$ (which is a function of time).\n\nTo obtain the time derivative of the entropy term that appears in the internal energy equation (\\ref{heat}), we just compute the difference between the entropy $s(M_r,t)$ for mass shell $M_r$ at the current time $t$ and the value for $s(M_r,t-\\Delta t)$ that we had in the previous time step. In general the solution we have constructed will not satisfy the outer boundary conditions (\\ref{pbound1}/\\ref{pbound2}) and (\\ref{lbound1}/\\ref{lbound2}), so we must modify our guesses for $T$ and $P$ in the center and try again.\n\nWe repeat this until we converge, and then we proceed to the next time step, adding new mass shells on the outside as necessary to account for new material deposited by accretion. We continue the calculation until the star's radius converges to its main sequence value. In this manner, we can generate a full evolutionary track for a given accretion rate.\n\n\\section{Evolutionary Phases for Protostars}\n\nWe have now outlined the basic equations describing protostellar evolution, as well as the numerical method used to solve them. We will now discuss the results of these calculations. There are generally a few distinct stages though with forming stars pass, which can be read off from how the radius evolves as the star gains mass. We will use as our primary example the case of a star undergoing hot accretion at $10^{-5}$ $M_\\odot$ yr$^{-1}$, as illustrated in Figure \\ref{fig:kippenhahn_hosokawa09}. However, note that the ordering of the phases we describe below can vary somewhat depending on the accretion rate and the boundary conditions assumed. Moreover, for low mass stars, some of the later phases may not occur at all, or occur only after the end of accretion.\n\n\\begin{figure}\n\\includegraphics[width=\\linewidth]{kippenhahn_hosokawa09}\n\\caption[Kippenhahn diagram for an accretion protostar]{\n\\label{fig:kippenhahn_hosokawa09}\nKippenhahn and composition diagrams for a protostar accreting at $10^{-5}$ $M_\\odot$ yr$^{-1}$. In the top panel, the thick curve shows the protostellar radius as a function of mass, and gray and white bands show convective and radiative regions, respectively. Hatched areas show regions of D and H burning, as indicated. Thin dotted lines show the radii containing $0.1$, $0.3$, $1$, $3$, and $10$ $M_\\odot$, as indicated. Shaded regions show four evolutionary phases: (I) convection, (II) swelling, (III) KH-contraction, and (IV) the main sequence. In the lower panel, the solid line shows the mean deuterium fraction in the star, normalized to the starting value, while the dashed line shows the D fraction only considering the convective parts of the star. The dot-dashed line shows the maximum temperature. Credit: \\citet{hosokawa09a}, \\copyright AAS. Reproduced with permission.\n}\n\\end{figure}\n\n\\subsection{Initial Contraction}\n\nThe initial phase of evolution is visible in Figure \\ref{fig:kippenhahn_hosokawa09} as what takes place up to a mass of $\\approx 0.2$ $M_\\odot$ for the example shown. The first thing that happens during this phase is that the star reaches a radius that is a function solely of $M$ and $\\dot{M}$. This occurs regardless of the initial radius with which we initiate the model, as long as we are using the hot accretion boundary condition. The physical reason for this behavior is easy to understand. The radius of the star is determined by the entropy profile $s(M_r)$. High entropy leads to high radius. Since the internal energy generated by the star is small compared to the accretion power when the stellar mass is low (i.e., $L_{\\rm bb} \\ll L_{\\rm acc}$), once gas is incorporated into the star it does not lose significant energy by radiation. The only entropy it loses is due to the radiation that occurs at the shock on the star's surface. We could have guessed this result from the large value of $t_{\\rm KH}$ compared to the accretion time -- in effect, this means that, once a fluid element reaches the stellar surface it will be buried and reach a nearly constant entropy quite quickly. Consequently, we can treat the material falling onto the star during this phase as having an entropy per unit mass that depends only on two factors: (1) the entropy it acquires by striking the stellar surface, and (2) how much it radiates before being buried.\n\nThe latter factor is just determined by the accretion rate. Higher accretion rates bury accreted material more quickly, leaving it with higher entropy and producing larger radii. The former depends on the velocity of the infalling material just before it strikes the stellar surface, and thus on $v_{\\rm ff}\\propto \\sqrt{M/R}$. However, this second factor self-regulates. If at fixed $M$ the radius $R$ is very large, then $v_{\\rm ff}$ is small, and the incoming material gains very little entropy in the shock. Small entropy leads to a smaller radius. Conversely, if $R$ is very small, then $v_{\\rm ff}$ and the post-shock entropy will be large, and this will produce rapid swelling of the protostar. This effect means that the radius rapidly converges to a value that depends only on $M$ and $\\dot{M}$.\n\nThis self-regulation does not happen if the material is assumed to accrete cold. In this case, the radial evolution of the star is determined solely by the amount of entropy that is assumed to remain in the accretion flow when it joins onto the star. As mentioned above, one common practice is to assume that the entropy of the accreting material is equal to the entropy of the gas already in the star, and, under this assumption, the choice of initial condition completely determines the subsequent evolution, since the choice of initial condition then determines the entropy content of the star thereafter.\n\nRegardless of the boundary condition assumed, during this phase there is no nuclear burning in the star, as the interior is too cold for any such activity. Since there is no nuclear burning, and this phase generally lasts much less than the Kelvin-Helmholtz timescale on which radiation changes the star's structure, during this phase the entropy content of the star is nearly constant. This phase can therefore be referred to as the adiabatic stage in the star's evolution.\n\n\n\\subsection{Deuterium Ignition and Convection}\n\nIn Figure \\ref{fig:kippenhahn_hosokawa09}, the next evolutionary phase begins at $\\approx 0.25$ $M_\\odot$, and continues to $\\approx 0.7$ $M_\\odot$. This stage is marked by two distinct but interrelated phenomena: the onset of nuclear burning and the onset of convection. The driving force behind both phenomena is that, as the protostar gains mass, its interior temperature rises. Recall the results of our calculation from chapter \\ref{ch:protostar_form}: for a polytrope, which is not an unreasonable description of the accreting protostar, the central temperature rises with mass to the $T_c\\propto M^{(2\\gamma-2)/(3\\gamma-2)}$. Thus even at fixed entropy the central temperature must rise as the star gains mass.\n\nOnce $T_c$ reaches $\\sim 10^6$ K, deuterium will ignite at the center of the protostar. This has three significant effects. The first is that deuterium acts as a thermostat for the star's center, much as hydrogen does in a main sequence star. Because the energy generation rate is so incredibly sensitive to $T$ (rising as the 11.8 power!), any slight rise in the temperature causes it to jump enough to raise the pressure and adiabatically expand the star, reducing $T$. Thus, $T_c$ becomes fixed at $10^6$ K -- which is part of the reason we did not need an expression for $\\epsilon$ that would work at higher temperatures. The star adjusts its radius accordingly, which generally requires that the radius increase as the mass rises. Thus deuterium burning temporarily halts core contraction. Both effects are visible in Figure \\ref{fig:kippenhahn_hosokawa09}. The halting of core contraction is apparent from the way the dotted lines showing constant mass enclosed bends upward at $\\approx 0.3$ $M_\\odot$, and the nearly constant core temperature is visible from the fact that, between $\\approx 0.25$ $M_\\odot$ and $3-4$ $M_\\odot$, a factor of more than 10 in mass, the central temperature stays within a factor of 2 of $10^6$ K.\n\nThe second effect of deuterium burning that it causes a rapid rise in the entropy at the center of the star: looking at the heat equation (\\ref{heat}), we can see that if $\\epsilon$ is large, then $\\partial s/\\partial t$ will be as well. This has the effect of starting up convection in the star. Before deuterium burning the star is generally stable against convection. That is because the entropy profile is determined by infall, and since shells that fall onto the star later arrive at higher velocities (due to the rising mass), they have higher entropy. Thus $s$ is an increasing function of $M_r$, which is the condition for convective stability. Deuterium burning reverses this, and convection follows, eventually turning much of the star convective. This also ensures the star a continuing supply of deuterium fuel, since convection will drag gas from the outer parts of the star down to the core, where they can be burned.\n\nAn important caveat here is that, although D burning encourages convection, it is not necessary for it. In the absence of D, or for very high accretion rates, the onset of convection is driven by the increasing luminosity of the stellar core as it undergoes KH contraction. This energy must be transported outwards, and as the star's mass rises and the luminosity goes up, eventually the energy that must be transported exceeds the ability of radiation to carry it. Convection results. For very high accretion rates, this effect drives the onset of convection even before the onset of D burning.\n\nA third effect of the deuterium thermostat is that it forces the star to obey a nearly-linear mass-radius relation, and thus to obey a particular relationship between accretion rate and accretion luminosity. One can show that for a polytrope the central temperature and surface escape speed are related by\n\\begin{equation}\n\\psi = \\frac{GM}{R} = \\frac{1}{2}v_{\\rm esc}^2 = T_n \\frac{k_B T_c}{\\mu m_{\\rm H}},\n\\end{equation}\nwhere $T_n$ is a dimensionless constant of order unity that depends only on the polytropic index. For $n=3/2$, expected for a fully convective star, $T_n = 1.86$. Plugging in this value of $T_n$, $\\mu=0.61$ (the mean molecular weight for a fully ionized gas of H and He in the standard abundance ratio), and $T_c = 10^6$ K, one obtains $\\psi = 2.5\\times 10^{14}$ erg g$^{-1}$ as the energy yield from accretion.\n\n\\subsection{Deuterium Exhaustion and Formation of a Radiative Barrier}\n\nThe next evolutionary phase, which runs from $\\approx 0.6 - 3$ $M_\\odot$ in Figure \\ref{fig:kippenhahn_hosokawa09}, is marked by the exhaustion of deuterium in the stellar core. Deuterium can only hold up the star for a finite amount of time. The reason is simply that there is not that much of it. Each deuterium burned provides $5.5$ MeV of energy, comparable to the $7$ MeV provided by burning hydrogen, but there are only $2\\times 10^{-5}$ D nuclei per H nuclei. Thus, at fixed luminosity the \"main sequence\" lifetime for D burning is shorter than that for H burning by a factor of $2\\times 10^{-5} \\times 5.5/7 = 1.6\\times 10^{-5}$.\n\nWe therefore see that, while a main sequence star can burn hydrogen for $\\sim 10^{10}$ yr, a comparable pre-main sequence star of the same mass and luminosity burning deuterium can only do it for only a few times $10^5$ yr. To be more precise, the time required for a star to exhaust its deuterium is\n\\begin{equation}\nt_{\\rm D} = \\frac{[\\mbox{D}/\\mbox{H}] \\Delta E_{\\rm D} M}{m_{\\rm H} L} = 1.5\\times 10^5 M_{0} L_1^{-1}\\mbox{ yr},\n\\end{equation}\nwhere $\\Delta E_{\\rm D}= 5.5$ MeV. Thus deuterium burning will briefly hold up a star's contraction, but cannot delay it for long. However, a brief note is in order here: while this delay is not long compared to the lifetime of a star, it is comparable to the formation time of the star. Recall that typical accretion rates are of order a few times $10^{-6}$ $\\msun$ yr$^{-1}$, so a 1 $\\msun$ star takes a few times $10^5$ yr to form. Thus stars may burn deuterium for most of the time they are accreting.\n\nThe exhaustion of deuterium does not mean the end of deuterium burning, since fresh deuterium that is brought to the star as it continues accreting will still burn. Instead, the exhaustion of core deuterium happens for a more subtle reason. As the deuterium supply begins to run out, the rate of energy generation in the core becomes insufficient to prevent it from undergoing further contraction, leading to rising temperatures. The rise in central temperature lowers the opacity, which is governed by a Kramers' law: $\\kappa_{\\rm R} \\propto \\rho T^{-3.5}$. This in turn makes it easier for radiation to transport energy outward. Eventually this shuts off convection somewhere within the star, leading to formation of what is called a radiative barrier.\n\nThe formation of the barrier ends the transport of D to the stellar center. The tiny bit of D left in the core is quickly consumed, and, without D burning to drive an entropy gradient, convection shuts off through the entire core. This is the physics behind the nearly-simultaneous end of central D burning and central convection that occurs near $0.6$ $M_\\odot$ in Figure \\ref{fig:kippenhahn_hosokawa09}. After this transition, the core is able to resume contraction, and D continues to burn as fast as it accretes. However, it now does so in a shell around the core rather than in the core.\n\n\\subsection{Swelling}\n\nThe next evolutionary phase, which occurs from $\\approx 3-4$ $M_\\odot$ in Figure \\ref{fig:kippenhahn_hosokawa09}, is swelling. This phase is marked by a marked increase in the star's radius over a relatively short period of time. The physical mechanism driving this is the radiative barrier discussed above. The radiative barrier forms because increasing temperatures drive decreasing opacities, allowing more rapid transport of energy by radiation. The decreased opacity allows the center of the star to lose entropy rapidly, and the entropy to be transported to the outer parts of the star via radiation. The result is a wave of luminosity and entropy that propagates outward through the star.\n\nOnce the wave of luminosity and entropy gets near the stellar surface, which is not confined by the weight of overlying material, the surface undergoes a rapid expansion, leading to rapid swelling. The maximum radius, and the mass at which the swelling phase occurs, is a strong function of the accretion rate (Figure \\ref{fig:rt_hosokawa09}). However, even at very low accretion rates, swelling does not occur until the mass exceeds $1$ $M_\\odot$, and thus this phase occurs only for stars more massive than the Sun.\n\n\\begin{marginfigure}\n\\includegraphics[width=\\linewidth]{rt_hosokawa09}\n\\caption[Protostellar mass-radius relation for different accretion rates]{\n\\label{fig:rt_hosokawa09}\nRadius versus mass (top panel) and maximum interior temperature versus mass (bottom panel) for protostars accreting at different rates. The accretion rate is indicated by the line style, as illustrated in the top panel. For each accretion rate there are two lines, one thick and one thin. The thick line is for the observed Milky Way deuterium abundance, while the thin line is the result assuming zero deuterium abundance.  Credit: \\citet{hosokawa09a}, \\copyright AAS. Reproduced with permission.\n}\n\\end{marginfigure}\n\n\\subsection{Contraction to the Main Sequence}\n\nThe final stage of protostellar evolution is contraction to the main sequence. Once the entropy wave hits the surface, the star is able to begin losing energy and entropy fairly quickly, and it resumes contraction. This marks the final phase of protostellar evolution, visible above $\\approx 4$ $M_\\odot$ in Figure \\ref{fig:kippenhahn_hosokawa09}. Contraction ends once the core temperature becomes hot enough to ignite hydrogen, landing the star at least on the main sequence.\n\n\\section{Observable Evolution of Protostars}\n\n\nWe have just discussed the interior behavior of an evolving protostar. While this is important, it is also critical to predict the observable properties of the star during this evolutionary sequence. In particular, we wish to understand the star's luminosity and effective temperature, which dictate its location in the Hertzsprung-Russell diagram. The required values can simply be read off from the evolutionary models (Figure \\ref{fig:pms_siess00}), giving rise to a track of luminosity versus effective temperature in the HR diagram.\n\n\\begin{figure}\n\\includegraphics[width=\\linewidth]{pms_siess00}\n\\caption[Pre-main sequence evolutionary tracks]{\n\\label{fig:pms_siess00}\nSolid lines show tracks taken by stars of varying masses, from $0.1$ $M_\\odot$ (rightmost line) to $7.0$ $M_\\odot$ (leftmost line) in the theoretical HR diagram of luminosity versus effective temperature. Stars begin at the upper right of the tracks and evolve to the lower left; tracks end at the main sequence. Dashed lines represent isochrones corresponding to $10^6$, $10^7$, and $10^8$ yr, from top right to bottom left. Credit: \\citeauthor{siess00a}, A\\&A, 358, 593, 2000, reproduced\nwith permission \\copyright\\, ESO.\n}\n\\end{figure}\n\nThe two most important applications of models of this sort is in determining the mass and age distributions of young stars. The former is critical to determining the IMF, as discussed in chapter \\ref{ch:imf_obs}, while the latter is critical to questions of both how clusters form, and to the problems of disk dispersal and planet formation (chapters \\ref{ch:late_disk} and \\ref{ch:planets}).\n\n\\subsection{The Birthline}\n\nBefore delving into the tracks themselves, we have to ask what is actually observable. As long as a star is accreting from its parent core, it will probably not be visible in the optical, due to the high opacity of the dusty gas in the core. Thus we are most concerned with stars' appearance in the HR diagram only after they have finished their main accretion phase. We refer to stars that are still accreting and thus not generally optically-observable as protostars, and those that are in this post-accretion phase as pre-main sequence stars. \n\nFor stars below $\\sim 1$ $M_\\odot$, examining Figure \\ref{fig:kippenhahn_hosokawa09}, we see that the transition from protostar to pre-main sequence star will occur some time after the onset of deuterium burning, either during the core or shell burning phases depending on the mass and accretion history. More massive stars will become visible only during KH contraction, or even after the onset of hydrogen burning. The lowest mass stars might be observable even before the start of deuterium burning. However, for the majority of the pre-main sequence stars that we can observe, they first become visible during the D burning phase.\n\n\\begin{marginfigure}\n\\includegraphics[width=\\linewidth]{birthline_palla90}\n\\caption[The protostellar birthline]{\n\\label{fig:birthline_palla90}\nThin lines show tracks taken by stars of varying masses (indicated by the annotation, in $M_\\odot$) in the theoretical HR diagram of luminosity versus effective temperature. Stars begin at the upper right of the tracks and evolve to the lower left; tracks end at the main sequence. The thick line crossing the tracks is the birthline, the point at which the stars stop accreting and become optically visible. Squares and circles represent the properties of observed young stars. Credit: \\citet{palla90a}, \\copyright AAS. Reproduced with permission.\n}\n\\end{marginfigure}\n\nSince there is a strict mass-radius relation during core deuterium burning (with some variation due to varying accretion rates), there must be a corresponding relationship between $L$ and $T$, just like the main sequence. We call this line in the HR diagram, on which protostars first appear, the birthline; it was first described by \\citet{stahler83a} (Figure \\ref{fig:birthline_palla90}). Since young stars are larger and more luminous that main sequence stars of the same mass, this line lies at higher $L$ and lower $T$ than the main sequence.\n\n\\subsection{The Hayashi Track}\n\nNow that we understand what is observable, let us turn to the tracks themselves. The tracks shown in Figures \\ref{fig:pms_siess00} and \\ref{fig:birthline_palla90} have several distinct features. One is that, for low mass stars, the initial phases of evolution in the HR diagram are nearly vertically, i.e., at constant $T_{\\rm eff}$. The vertical tracks for different masses are very close together. This vertical part of the evolution is called the Hayashi track, after its discoverer, who predicted it theoretically \\citep{hayashi61a}. For low mass stars, the majority of the Hayashi track lies after the birthline, so it is directly observable.\n\nThe origin of the Hayashi track is in the physics of opacity in stellar atmospheres at low temperature. At temperatures below about $10^4$ K, hydrogen becomes neutral, and the only free electrons available come from metal atoms with lower ionization energies. Some of these electrons become bound with hydrogen atoms, forming H$^-$, and this ion is the dominant source of opacity.  Thus the opacity depends on the number of free electrons provided by metal atoms, which in turn depends extremely sensitively on the temperature.\n\nIf the temperature falls too low, the opacity will be so low that, even integrating through the rest of the star's mass, the optical depth to infinity will be $<2/3$. Since the photosphere must always be defined by a surface of optical depth unity, this effectively establishes a minimum surface temperature for the star required to maintain $\\tau \\approx 1$. This minimum temperature depends weakly on the star's mass and radius, but to good approximation it is simply $T_{\\rm min} = T_{\\rm H} = 3500$ K, where $T_{\\rm H}$ is the Hayashi temperature. Low mass protostars, due to their large radii, wind up right against this limit, which is why they all contract along vertical tracks that are packed close together in $T_{\\rm eff}$.\n\nWe can make this argument a bit more quantitative as follows.\\footnote{This argument is taken from \\citet{prialnik09a}.} Let us approximate the stellar photosphere at radius $R$ as producing blackbody emission and obeying a simple ideal gas law equation of state. In this case we have\n\\begin{eqnarray}\n\\label{eq:bb}\n\\log L & = & 4 \\log T_R - 2 \\log R + \\mbox{constant} \\\\\n\\label{eq:idealgas}\n\\log P_R & = & \\log \\rho_R + \\log T_R + \\mbox{constant},\n\\end{eqnarray}\nwhere the subscript $R$ indicates that a quantity is to be evaluated at the stellar outer radius, and we are writing things in terms of logarithms rather than powerlaw scalings for future convenience. Now let us consider a star that is a polytrope, following $P\\propto K_P \\rho^{(n+1)/n}$, where $n$ is the polytropic index. The polytropic constant $K_P$ is related to the stellar mass and radius by\n\\begin{equation}\nK_P \\propto M^{(n-1)/n}R^{(3-n)/n}.\n\\end{equation}\nThus we have\n\\begin{equation}\n\\log K_P = \\left(\\frac{n-1}{n}\\right) \\log M + \\left(\\frac{3-n}{n}\\right)\\log R + \\mbox{constant},\n\\end{equation}\nand the pressure scales with $M$ and $R$ as\n\\begin{equation}\n\\label{eq:polytrope}\n\\log P = \\left(\\frac{n-1}{n}\\right) \\log M + \\left(\\frac{3-n}{n}\\right) \\log R + \\left(\\frac{n+1}{n}\\right) \\log \\rho + \\mbox{constant}.\n\\end{equation}\nHydrostatic balance at the photosphere requires\n\\begin{equation}\n\\frac{dP}{dr} = \\rho_R \\frac{GM}{R^2} \\qquad\\Longrightarrow\\qquad\nP_R = \\frac{GM}{R^2} \\int_R^\\infty \\rho \\, dr,\n\\end{equation}\nwhere $P_R$ is the pressure at the photosphere and we are approximating the $GM/R^2$ is essentially constant through the photosphere. The photosphere is defined by the condition\n\\begin{equation}\n\\kappa_{\\rm R} \\int_R^\\infty \\rho\\,dr \\approx 1,\n\\end{equation}\nwhere we are also approximating $\\kappa_{\\rm R}$ as constant, so putting this together we have\n\\begin{equation}\nP_R \\approx \\frac{GM}{R^2\\kappa_{\\rm R}} \\qquad\\Longrightarrow\\qquad\n\\log P_R \\approx \\log M - 2 \\log R - \\log \\kappa_{\\rm R}.\n\\end{equation}\n\nTo make further progress, we will assume that we can approximate the opacity as some powerlaw in the temperature, $\\kappa_{\\mathrm{R}} \\propto \\rho T^b$. For Kramers opacity, for example, $b=-3.5$. Substituting this into the equation for $P_R$, we have\n\\begin{equation}\n\\label{eq:opacity}\n\\log P_R = \\log M - 2\\log R - \\log \\rho_R - b\\log T_R + \\mbox{constant}.\n\\end{equation}\nEquations (\\ref{eq:bb}), (\\ref{eq:idealgas}), (\\ref{eq:polytrope}) and (\\ref{eq:opacity}) constitute a system of four linear equations in the four unknowns $\\log P_R$, $\\log \\rho_R$, $\\log T_R$, and $\\log L$. Solving this linear system yields the result\n\\begin{equation}\n\\log L = \\left(\\frac{9 - 2 n + b}{2-n}\\right) \\log T_R - \\left(\\frac{2n-1}{2-n}\\right) \\log M + \\mbox{constant}.\n\\end{equation}\nThis equation describes the shape of a track in the HR diagram, because it relates $\\log L$ to $\\log T_R$, the photospheric temperature. To see what it implies, we can assume that young low mass stars will be fully convective thanks to D burning, so $n\\approx 1.5$.\n\nThis leaves only $b$. As mentioned previously, the H$^{-}$ opacity has the property that it rises sharply with temperatures of a few thousand K, because at these temperatures collisional velocities are not high enough to dissociate H$^-$, but they are able to dissociate other atoms, which in turn produces free electrons that can yield H$^{-}$. The higher the temperature, the more free electrons available, and thus the higher the H$^{-}$ opacity. The net result is that, in this temperature range, $b$ takes on a fairly large value: $\\sim 4-9$ depending on exactly where in the temperature range we are. Note that this is the opposite of the normal behavior for stellar opacities (e.g., Kramer's opacity), where the opacity falls with increasing temperature.\n\nIf we plug $b = 9$ and $n=1.5$ into the equation we have just derived, we find obtain\n\\begin{equation}\n\\log L = 30\\log T_R - 4 \\log M + \\mbox{constant}.\n\\end{equation}\nUsing $b=4$ changes the 30 to a 20. Either way, we conclude that $\\log L$ changes extremely steeply with $\\log T_R$, which implies that the HR diagram track for stars with this low $T_{\\rm eff}$ must be nearly vertical -- hence the Hayashi track. We also see that the location of the Hayashi tracks for stars of different masses will be slightly offset, because of the $4\\log M$ term. This qualitatively explains what the numerical models produce.\n\n\\subsection{The Heyney Track}\n\nContraction at nearly constant $T_{\\rm eff}$ continues until the star contracts enough to raise its surface temperature above $T_{\\rm H}$. This increase in temperature also causes the star to transition from convective to radiative, since the opacity drops with temperature at high temperatures, and a lower opacity lets radiation rather than convection carry the energy outward.\n\nIn the HR diagram, the contraction and increase in $T_{\\rm eff}$ produces a vaguely horizontal evolutionary track. This is called the Heyney track. The star continues to contract until its center becomes warm enough to allow H burning to begin.\nAt that point it may contract a small additional amount, but the star is essentially on the main sequence. The total time required depends on the stellar mass, but it ranges from several hundred Myr for $0.1$ $\\msun$ stars to essentially zero time for very massive stars, which reach the main sequence while still accreting.\n\n\n", "meta": {"hexsha": "a0dabe055fec4d46be4ad212b1716a9a44638970", "size": 46732, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/chapter17.tex", "max_stars_repo_name": "Open-Astrophysics-Bookshelf/star_formation_notes", "max_stars_repo_head_hexsha": "d1c8a10f84fc1676b492ddb4f3bd8b73455b5d07", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 67, "max_stars_repo_stars_event_min_datetime": "2015-05-05T22:43:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-02T02:02:57.000Z", "max_issues_repo_path": "chapters/chapter17.tex", "max_issues_repo_name": "keflavich/star_formation_notes", "max_issues_repo_head_hexsha": "d1c8a10f84fc1676b492ddb4f3bd8b73455b5d07", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2015-05-31T17:15:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T02:07:47.000Z", "max_forks_repo_path": "chapters/chapter17.tex", "max_forks_repo_name": "keflavich/star_formation_notes", "max_forks_repo_head_hexsha": "d1c8a10f84fc1676b492ddb4f3bd8b73455b5d07", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2015-05-22T17:47:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-08T15:58:05.000Z", "avg_line_length": 130.1727019499, "max_line_length": 1456, "alphanum_fraction": 0.7707994522, "num_tokens": 11926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.31031124935820775}}
{"text": "\t%!TEX root = ../thesis.tex\n%*******************************************************************************\n%*********************************** Theory chapter *****************************\n%*******************************************************************************\n\n\\chapter{Theory}\n\n\\graphicspath{{chapter-theory/Figs/}}\n\n\\glsreset{sm}\n\nThe \\gls{sm} of particle physics, introduced in the following section, is a theoretical framework providing a description of nature on the level of elementary particles. Although experimentally well-validated, a number of open questions are left unanswered by the \\gls{sm}.\nFor this reason, the second part of this chapter introduces Supersymmetry, a class of theories that could provide answers to some of these open questions. As searching for Supersymmetry will be the guiding thread throughout this thesis, this chapter will highlight the phenomenological consequences of supersymmetric theories.\nThe mathematical description in the following sections largely follows \\references\\cite{Brock:1354959, Peskin:1995ev} for the \\gls{sm} and \\references\\cite{Martin:1997ns,Bustamante:2009us} for Supersymmetry.\n\n\\section{The Standard Model of particle physics}\n\nBy the end of the 1920s, quantum mechanics and general relativity had been relatively well established, and the consensus among physicists was that matter is composed of nuclear atoms consisting of electrons and protons.\nDuring the 1930s, a multitude of new experimental discoveries and theoretical puzzles excited physicists in, among others, three important directions of research: nuclear physics, cosmic rays and relativistic quantum mechanics~\\cite{brown1986the}.\nAt this time, open questions in these fields included, \\eg, the continuous spectrum of the $\\beta$-decay, the nature of cosmic rays, or the negative energy states in Dirac's relativistic electron theory. As a result of these directions ultimately flowing together, the following decades saw elementary particle physics, emerge as a new field of research.\n\nSince these early times of particle physics, significant progress has been made in describing nature at the subatomic scale.\nToday, a century later, the resulting theoretical framework, the \\gls{sm}, is the most fundamental, experimentally validated theory of nature known to mankind.\nIt provides an extremely precise description of the interactions of elementary particles, and has been experimentally tested to an unprecedented level of accuracy. Given the remarkable success of the \\gls{sm}, it is not surprising that its history is paved with numerous awards for both experimental and theoretical work.\nIn 1964, the Nobel prize was awarded to Feynman, Schwinger and Tomonoga for their fundamental work on \\gls{qed}, a quantum field theory allowing the precise calculation of fundamental processes like, \\eg, the anomalous magnetic moment of the electron that is known to a relative experimental uncertainty of $2.3 \\times 10^{-10}$~\\cite{Mohr:2015ccw}.\nIn 1979, Glashow, Weinberg and Salam were awarded the Nobel prize for their work towards electroweak unification.\nThe most prominent recent progress is undoubtedly the discovery of the Higgs boson, not only resulting in the Nobel prize being awarded to Englert and Higgs, but also completing the \\gls{sm}, roughly 50 years after the existence of the Higgs boson had been postulated. \n\t\t\n\\subsection{Particle content of the Standard Model}\n\n\\begin{table}\n\t\\centering\n\t\\setlength\\heavyrulewidth{0.2ex}\n\t\\small\n\t\\caption{Names, electric charges (in units of the elementary charge $e$) and masses (rounded to three significant digits if known to that precision) of all observed fermions in the SM~\\cite{pdg2020}. The symbols used in the following are indicated in parentheses after the particle names.}\n\t\\begin{tabular} {l c c c r}\n\t\t\n\t\t\\toprule\n\t\t\t\t& generation & particle & electric charge [$e$] & mass \\\\ \n\t\t\\midrule \n\t\t\t\t\\multirow{6}{*}{leptons}& \\multirow{2}{*}{1} & electron ($e$)& $-1$ & \\SI{511}{\\keV}\\\\\n\t\t\t\t& & electron neutrino ($\\nu_e$) & 0 & < \\SI{1.1}{\\eV} \\\\\n\t\t\t\t& \\multirow{2}{*}{2} & muon ($\\mu$)& $-1$ & \\SI{106}{\\MeV}\\\\\n\t\t\t\t& & muon neutrino ($\\nu_\\mu$) & 0 & < \\SI{0.19}{\\MeV} \\\\\n\t\t\t\t& \\multirow{2}{*}{3} & tau ($\\tau$)& $-1$ & \\SI{1.78}{\\GeV}\\\\\n\t\t\t\t& & tau neutrino ($\\nu_\\tau$) & 0 & < \\SI{18.2}{\\MeV} \\\\\n\t\t\\midrule \n\t\t\t\t\\multirow{6}{*}{quarks}& \\multirow{2}{*}{1} & up ($u$)& $\\frac{2}{3}$ & \\SI{2.16}{\\MeV}\\\\\n\t\t\t\t& & down ($d$) & $-\\frac{1}{3}$ & \\SI{4.67}{\\MeV} \\\\\n\t\t\t\t& \\multirow{2}{*}{2} & charm ($c$)& $\\frac{2}{3}$ & \\SI{1.27}{\\GeV}\\\\\n\t\t\t\t& & strange ($s$) & $-\\frac{1}{3}$ &\\SI{93}{\\MeV} \\\\\n\t\t\t\t& \\multirow{2}{*}{3} & top ($t$)& $\\frac{2}{3}$ & \\SI{173}{\\GeV}\\\\\n\t\t\t\t& & bottom ($b$) & $-\\frac{1}{3}$ & \\SI{4.18}{\\GeV} \\\\\n\t\t\\bottomrule\n\t\\end{tabular}\\vspace{2mm}\n\t\\label{tab:particles_fermions}   \n\\end{table}\n\nApart from the experimentally non-vanishing neutrino masses, the SM successfully describes ordinary matter and their interactions, namely the electromagnetic, weak and strong interactions, leaving gravity as the only fundamental force not described within the \\gls{sm}.\nThe particles in the SM are classified into two main categories, depending on their spin.\nParticles with half-integer spin follow the Fermi-Dirac statistics and are called \\textit{fermions}. As they are subject to the Pauli exclusion principle, they make up ordinary matter.\nParticles with integer spin are called \\textit{bosons}, follow Bose-Einstein statistics and mediate the fundamental interactions. \n\n%\\subsubsection*{Fermions} \n\nFermions are further divided into leptons and quarks, that each come in three generations with increasing masses\\footnote{Neutrinos might not exist in a normal mass hierarchy but could also have an inverted mass hierarchy.}.\nEach of the three electrically charged leptons is associated to a corresponding neutral neutrino (more on this association in~\\cref{sec:ewk_interaction}). While the SM assumes massless neutrinos, the observation of neutrino oscillations~\\cite{Fukuda:1998mi} implies the existence of at least two massive neutrinos.\nBy extending the SM to allow non-vanishing neutrino masses, neutrino oscillations can be introduced through lepton generation mixing, described by the \\gls{pmns} matrix~\\cite{PMNS:1962mu}.\nApart from an electric charge, the six quarks also carry a colour charge, of which three types exist: \\textit{red}, \\textit{green} and \\textit{blue}, as well as their respective anti-colours.\nThe mixing in the quark sector through the weak interaction can be described by the \\gls{ckm} matrix~\\cite{PhysRevLett.10.531,CKM:1973fv}.\nFinally, each fermion comes with its own anti-particle with same mass and spin, but inverted charge-like quantum numbers\\footnote{The exact nature of anti-neutrinos is still an open question and ties into whether or not the neutrino mass matrix contains non-vanishing Majorana mass terms.}.\nAll fermions in the SM are listed in \\cref{tab:particles_fermions}.\n\n%\\subsubsection*{Bosons}\n\n\\begin{table}\n\t\\centering\n\t\\setlength\\heavyrulewidth{0.2ex}\n\t\\small\n\t\\caption{Names, electric charges (in units of the elementary charge $e$) and masses (rounded to three significant digits if known to that precision) of all observed bosons in the SM~\\cite{pdg2020}. The symbols used in the following are indicated in parentheses after the particle names.}\n\t\\begin{tabular} {c c c c}\n\t\\toprule\n\t\tparticle & spin & electric charge [$e$]& mass \\\\ \n\t\\midrule\n\t\tphoton ($\\gamma$) & 1 & 0 & 0\\\\\n\t\tgluon ($g$) & 1 & 0 & 0 \\\\\n\t\t$W^\\pm$ & 1 & $\\pm 1$ & \\SI{80.4}{\\GeV} \\\\\n\t\t$Z^0$ & 1 & 0 & \\SI{91.2}{\\GeV} \\\\\n\t\tHiggs boson ($h$) & 0 & 0 & \\SI{125}{\\GeV} \\\\\n\t\\bottomrule\t\t\t\t\t\n\t\\end{tabular}\\vspace{2mm}\n\t\\label{tab:particles_bosons}   \n\\end{table}\n\nThe fundamental forces described by the SM are propagated by bosons with spin-1\\footnote{Natural units $\\hbar = c = 1$ are used henceforth.}.\nThe photon~$\\gamma$ couples to electrically charged particles and mediates the electromagnetic interaction.\nAs the photon is massless, the electromagnetic force has infinite range.\nThe strong force is mediated by gluons carrying one unit of colour and one unit of anti-colour.\nDue to colour-confinement, colour charged particles like quarks and gluons cannot exist as free particles and, instead, will form colour-neutral bound states.\nAlthough nine gluon states would theoretically be possible, only eight of them are realised in nature---the colour-singlet state $\\frac{1}{\\sqrt{3}}(\\ket{r\\bar{r}}+\\ket{g\\bar{g}}+\\ket{b\\bar{b}})$ would result in long-range strong interactions, which have not been observed.\nFinally, the weak force is mediated by a total of three bosons, two charged $W^\\pm$ bosons and a neutral $Z$ boson\\footnote{Due to the electroweak unification, offering a unified description of the electromagnetic and weak interactions in the \\gls{sm}, the $Z$ boson technically has an electromagnetic component and thus is not a \\textit{pure} mediator of the weak interaction. Electroweak unification will be discussed in \\cref{sec:ewk_interaction}.}.\nThe mediators of the weak force are massive, resulting in a finitely ranged interaction. They gain their masses through the Higgs mechanism, discussed in chapter~\\cref{sec:ssb}. All bosons known to the SM are listed in \\cref{tab:particles_bosons}.\n\n\\subsection{The Standard Model as a gauge theory}\\label{ch:gauge_theory}\n\nFormally, the SM is a collection of a special type of \\glspl{qft}, called gauge theories. In the same way that quantum mechanics is the quantisation of dynamical systems of particles, \\gls{qft} is the application of quantum mechanics to dynamical systems of fields, providing a uniform description of quantum mechanical particles and classical fields, while including special relativity.\n\nIn classical mechanics, the fundamental quantity  is the action $S$, which is the time integral of the Lagrangian $L$, a functional characterising the state of a system of particles in terms of generalised coordinates $q_1, \\dots, q_n$. In field theory, the Lagrangian can be written as spatial integral of a Lagrangian density $\\Lagr(\\phi_i,\\uppartial_\\mu\\phi_i)$, which is a function of fields $\\phi_i$ and their spacetime derivatives $\\uppartial_\\mu\\phi_i$. In the following, the Lagrangian density $\\Lagr$ will simply be referred to as the \\textit{Lagrangian}. The action can then be written as\n\\begin{equation}\n\tS = \\int L\\diff t = \\int\\Lagr\\left(\\phi_i,\\uppartial_\\mu\\phi_i\\right)\\Diff4 x.\n\\end{equation}\n\nUsing the principle of least action $\\updelta S = 0$, the equation of motions for each field are given by the Euler-Lagrange-equation,\n\\begin{equation}\n\t\\uppartial_\\mu\\left(\\frac{\\uppartial\\Lagr}{\\uppartial\\left(\\uppartial_\\mu\\phi_i\\right)}\\right)-\\frac{\\uppartial\\Lagr}{\\uppartial\\phi_i}=0.\n\t\\label{eq:euler_lagrange}\n\\end{equation}\nAs opposed to the Hamiltonian formalism, the Lagrange formulation of field theory is especially well suited for the relativistic dynamics in particle physics, as it exhibits explicit Lorentz-invariance~\\cite{Peskin:1995ev}. This is a direct consequence of the principle of least action, since Lorentz-transformed extrema in the action will still be extrema for Lorentz-invariant Lagrangians.\n\nSymmetries are of central importance in the \\gls{sm}. As Emmy Noether has famously shown in 1918 for classical mechanics, every continuous symmetry of the action has a corresponding conservation law~\\cite{physics/0503066}. In the context of classical field theory, each generator of a continuous internal or spacetime symmetry transformation leads to a conserved current, and thus to a conserved charge. In \\glspl{qft}, quantum versions of Noether's theorem, called Ward--Takahashi identities~\\cite{PhysRev.78.182,Takahashi1957} for Abelian theories and Slavnov--Taylor identities~\\cite{THOOFT1971173,TAYLOR1971436,Slavnov1972} for non-Abelian theories relate the conservation of quantum currents and charge-like quantum numbers to continuous symmetries of the Lagrangian.\n\nFrom a theoretical point of view, the SM is a collection of three gauge theories based on the symmetry group\n\\begin{equation*}\n\tSU(3)_C \\otimes SU(2)_\\mathrm{L} \\otimes U(1)_Y,\n\\end{equation*}\nwhere $U(n)$ ($SU(n)$) describes (special) unitary groups, \\ie the Lie groups of $n\\times n$ unitary matrices (with determinant 1, if special). $SU(3)_C$ generates \\gls{qcd}, describing the interaction of particles with colour charge $C$ through exchange of gluons, and $SU(2)_\\mathrm{L} \\otimes U(1)_Y$ generates the electroweak interaction. Here, the subscript `$Y$' represents the weak hypercharge, while the subscript `L' indicates that $SU(2)_\\mathrm{L}$ only couples to left-handed particles (right-handed antiparticles).\n\n\\subsubsection{Feynman diagrams}\n\nTransitioning from classical field theory to quantum field theory is typically either done through canonical quantisation or through the usage of the path integral formalism. As only the simplest field theories can be solved analytically, \\ie those containing only free fields and no interactions, perturbation theory is used for calculating scattering cross sections and decay rates for any \\gls{qft} containing interactions. Any transition matrix can then be written as a series expansion in the coupling constant, with each term represented by Feynman diagrams. \n\nUsing appropriate Feynman rules dictating the possible vertices (representing interactions between fields) and propagators (representing the propagation of fields), an infinite number of Feynman diagrams can be written down. All possible combinations of propagators and vertices (\\ie all possible Feynman diagrams) that can be used to connect given incoming and outgoing particles then represent the full perturbation series. Only the lowest order in the series is considered at \\gls{lo}, the next-lowest at \\gls{nlo}, and so on.\n\n\n\\subsubsection{Gauge principle}\n\\label{sec:gauge_principle}\n\nThe gauge principle is fundamental to the SM and dictates that the existence of gauge fields is directly related to symmetries under local gauge transformations. \\gls{qed}, being the simplest gauge theory, can be taken to illustrate this important principle. The free Dirac Lagrangian for a single, non-interacting fermion with mass $m$ is given by\n\\begin{equation}\n\t\\Lagr_\\mathrm{Dirac}=\\bar{\\psi}\\left(i\\gamma^\\mu\\uppartial_\\mu - m\\right)\\psi,\n\t\\label{eq:dirac_lagrangian}\n\\end{equation}\nwhere $\\psi$ is a four-component complex spinor field, $\\bar{\\psi} = \\psi^\\dagger\\gamma^0$, and $\\gamma^\\mu$ with $\\mu = 0,1,2,3 $ are the Dirac matrices with the usual anticommutation relations, generating a matrix representation of the Dirac algebra, \n\\begin{equation}\n\t\\{\\gamma^\\mu,\\gamma^\\nu\\} \\equiv \\gamma^\\mu\\gamma^\\nu + \\gamma^\\nu\\gamma^\\mu = 2\\eta^{\\mu\\nu}\\mathbb{1}_4.\n\\end{equation}\nHere, $\\eta^{\\mu\\nu} = \\mathrm{diag}(+1, -1, -1, -1)$ is the Minkowski metric.\nIt is worth noting that the free Dirac Lagrangian is invariant under a global $U(1)$ transformation\n\\begin{equation}\n\t\\psi \\rightarrow \\mathrm{e}^{i\\theta}\\psi,\n\\end{equation}\nwhere the phase $\\theta$ is spacetime independent and real-valued. In order to produce the physics of electromagnetism, the free Dirac Lagrangian, has to be invariant under \\textit{local} $U(1)$ phase transformations with a spacetime dependent phase $\\theta(x)$. This is, however, not the case, as the transformed Lagrangian picks up an additional term from the spacetime derivative of the phase,\n\\begin{equation}\n\t\\Lagr_\\mathrm{Dirac} \\to \\Lagr_\\mathrm{Dirac} - (\\uppartial_\\mu\\theta(x))\\bar{\\psi}\\gamma^\\mu\\psi.\n\\end{equation}\n\nFor the Dirac Lagrangian to become invariant under a local gauge transformation, a new vector field $A_\\mu(x)$ has to be introduced and the partial derivative $\\uppartial_\\mu$ has to be replaced with the covariant derivative $\\codiff_\\mu$, such that\n\\begin{equation}\n\t\\uppartial_\\mu \\rightarrow \\codiff_\\mu \\equiv \\uppartial_\\mu + ieA_\\mu,\n\\end{equation}\nwhere $e$ can be identified with the elementary charge, representing the coupling of the fermion field to the gauge field $A_\\mu$. The prescription of achieving local gauge invariance by replacing $\\uppartial_\\mu$ with $D_\\mu$ is called \\textit{minimal coupling} and leads to a Lagrangian that is invariant under the transformations\n\\begin{equation}\n\t\\psi \\rightarrow \\mathrm{e}^{i\\theta\\left(x\\right)}\\psi,\\, \\, \\, \\, \\, \\, \\, \\, \\, \\, A_\\mu \\rightarrow A_\\mu - \\frac{1}{e}\\uppartial_\\mu\\theta(x).\n\t\\label{eq:gauge_field}\n\\end{equation}\nThe modified Lagrangian now includes a term for interactions between the gauge field and the fermion field,\n\\begin{equation}\n\\begin{split}\n\t\\Lagr &= \\Lagr_\\mathrm{Dirac} + \\Lagr_\\mathrm{int} \\\\\n\t\t&= \\bar{\\psi}\\left(i\\gamma^\\mu\\uppartial_\\mu - m\\right)\\psi - \\left(e\\bar{\\psi}\\gamma^\\mu\\psi\\right)A_\\mu,\n\t\\label{eq:modified_lagrangian}\n\\end{split}\n\\end{equation}\nand is indeed invariant under a local phase transformation. Yet, it cannot be complete, as it is still missing a term describing the kinematics of the free gauge field $A_\\mu$. For a vector field, the kinetic term is described by the Proca Lagrangian\n\\begin{equation}\n\t\\Lagr_\\mathrm{Proca} = -\\frac{1}{4}F_{\\mu\\nu}F^{\\mu\\nu} + \\frac{1}{2}m_A^2A^\\nu A_\\nu,\n\\end{equation}\nwhere $F^{\\mu\\nu}\\equiv\\left(\\uppartial^\\mu A^\\nu-\\uppartial^\\nu A^\\mu\\right)$ is the field strength tensor that is invariant under the transformation in \\cref{eq:gauge_field}. Since $A^\\nu A_\\nu$ is not invariant under the local transformation of above, the only way to keep the full Lagrangian invariant under a local phase transformation is by requiring $m_A=0$, \\ie the gauge field $A_\\mu$ introduced has to be massless, resulting in the Maxwell Lagrangian\n\\begin{equation}\n\t\\Lagr_\\mathrm{Maxwell} = -\\frac{1}{4}F_{\\mu\\nu}F^{\\mu\\nu},\n\\end{equation}\nthat ultimately generates the well-known Maxwell equations.\n\nThis finally yields the full Lagrangian\n\\begin{equation}\n\\begin{split}\n\t\t\\Lagr_\\mathrm{QED} & = \\Lagr_\\mathrm{Dirac} + \\Lagr_\\mathrm{Maxwell} + \\Lagr_\\mathrm{int} \\\\\n\t  \t\t\t\t& = \\bar{\\psi}\\left(i\\gamma^\\mu\\uppartial_\\mu\\right)\\psi - m\\bar{\\psi}\\psi - \\frac{1}{4}F^{\\mu\\nu}F_{\\mu\\nu} - \\left(e\\bar{\\psi}\\gamma^\\mu\\psi\\right)A_\\mu,\n\\end{split}\n\\end{equation}\nwhich can be identified to be the full Lagrangian of \\gls{qed}. The gauge field $A_\\mu$ introduced is therefore nothing else than the electromagnetic potential with its associated massless particle, the photon. Thus, by applying the gauge principle on the free Dirac Lagrangian, \\ie forcing a global phase invariance to hold locally, a new massless gauge field has to be introduced, including interaction terms with the existing fields in the Lagrangian. In the case of the free Dirac Lagrangian, local gauge invariance produces all of \\gls{qed}.\n\nAs Yang and Mills have shown in 1954~\\cite{PhysRev.96.191}, requiring a global phase invariance to hold locally is perfectly possible in the case of any continuous symmetry group. Considering a general non-Abelian symmetry group $G$, represented by a set of $n\\times n$ unitary matrices $U(\\alpha^1,\\dots,\\alpha^N)$, parametrised by $N$ real parameters $\\alpha^1,\\dots,\\alpha^N$, then a gauge-invariant Lagrangian can be constructed with a similar prescription~\\cite{Brock:1354959} as previously in the case of $U(1)$. \n\nA total of $n$ fermion fields with mass $m$ are needed, arranged in an $n$-dimensional multiplet $\\Psi = (\\psi_1,\\dots,\\psi_n)^T$. The free Lagrangian,\n\\begin{equation}\n\t\\Lagr_\\mathrm{free} = \\bar{\\Psi}\\left(i\\gamma^\\mu\\uppartial_\\mu -m\\right)\\Psi,\n\t\\label{eq:free_lagrangian}\n\\end{equation}\nis invariant under a global phase transformation of the form\n\\begin{equation}\n\t\\Psi(x) \\rightarrow U(\\alpha^1,\\dots,\\alpha^N)\\Psi(x).\n\\end{equation}\nEach element in the set of transformations $U$ can be written in terms of the group generators $T^a$ as\n\\begin{equation}\n\tU(\\alpha^1,\\dots,\\alpha^N) = \\mathrm{e}^{i\\alpha^aT^a},\n\\end{equation}\nwhere the group indices $a = 1,\\dots,N$ are to be summed over. The group generators $T^a$ satisfy the commutation relations\n\\begin{equation}\n\t[T^a,T^b] = i f^{abc}T^c,\n\\end{equation}\nwhere $f^{abc}$ are the so-called structure constants quantifying the lack of commutativity between the generators. By convention, the basis for the generators $T^a$ is typically chosen such that $f^{abc}$ is completely anti-symmetric~\\cite{Brock:1354959}. In order to make the Lagrangian invariant under local phase transformations, \\ie under transformations with a set of spacetime-dependent real parameters $\\alpha^a(x)$, a vector field $\\makemebold{W}_{\\hspace{-0.25em}\\mu}$ together with a coupling constant $g$ have to be introduced through the covariant derivative  \n\\begin{equation}\n\t\\uppartial_\\mu \\rightarrow \\codiff_\\mu = \\uppartial_\\mu - ig\\makemebold{W}_{\\hspace{-0.25em}\\mu}.\n\\end{equation}\nAs $\\codiff_\\mu$ acts on the $n$-dimensional multiplet $\\Psi$, the introduced gauge field $\\makemebold{W}_{\\hspace{-0.25em}\\mu}$ has to be a $n\\times n$ matrix and can thus be expanded in terms of the generators\n\\begin{equation}\n\t\\makemebold{W}_{\\hspace{-0.25em}\\mu}(x) = T^a W_\\mu^a(x),\n\\end{equation}\nthereby explicitly illustrating, that a total of $N$ gauge fields $W^a_\\mu$ are introduced through the covariant derivative. Similar to \\gls{qed} above, the covariant derivative also introduces an interaction term of the form\n\\begin{equation}\n\t\\Lagr_\\mathrm{int} = g\\bar{\\Psi}\\gamma^\\mu\\makemebold{W}_{\\hspace{-0.25em}\\mu}\\Psi,\n\\end{equation}\ninto the Lagrangian in \\cref{eq:free_lagrangian}, coupling the gauge fields $W^a_\\mu$ to the fermion multiplet. For infinitesimal $\\alpha^a(x)$, the gauge fields gauge transform according to\n\\begin{equation}\n\tW_\\mu^a \\rightarrow W_\\mu^a + \\frac{1}{g}\\uppartial_\\mu\\alpha^a + f^{abc} W_\\mu^b \\alpha^c,\n\\end{equation}\nwhere the term with $\\alpha^a$ looks familiar to the $U(1)$ example and corresponds to the Abelian case, while the term with $f^{abc}$ introduces the non-Abelian structure into the theory~\\cite{Brock:1354959}. The same non-Abelian structure is again clearly visible when introducing a kinetic term for the gauge fields into the Lagrangian\n\\begin{equation}\n\t\\Lagr_{W} = -\\frac{1}{4} F^a_{\\mu\\nu} F^{\\mu\\nu,a},\n\\end{equation} \nwith the field-strength tensor now $F^a_{\\mu\\nu} = \\uppartial_\\mu W^a_\\nu - \\uppartial_\\nu W^a_\\mu + gf^{abc}W^b_\\mu W^c_\\nu$. As was already the case for \\gls{qed}, the above Lagrangian contains Abelian terms quadratic in $W$, describing the propagation of the free gauge fields. This time, the Lagrangian additionally includes non-Abelian terms cubic and quartic in $W$, leading to self-interaction of the gauge fields.\n\n\\subsubsection{Quantum chromodynamics}\n\n\\gls{qcd}, the gauge theory describing the strong interaction between quarks and gluons in the SM, is an example for a non-Abelian Yang-Mills theory~\\cite{PhysRev.96.191}. \\gls{qcd} is based on the gauge group $SU(3)_C$, with the subscript $C$ indicating that the quantum number associated with the symmetry group is the \\textit{colour}. Each quark is described by a triplet of fermion fields $q = (q_r,q_g,q_b)^T$, where the subscripts refer to the three different colours. The symmetry group $SU(3)$ has a total of $n^2-1 = 8$ generators, usually expressed in terms of the Gell-Mann matrices $\\lambda^a$~\\cite{Peskin:1995ev}. The covariant derivative introducing the gauge fields $G_\\mu^a$ acting on the quark triplets is then\n\\begin{equation}\n\t\\codiff_\\mu = \\uppartial_\\mu - ig_s \\frac{\\lambda^a}{2\t}G_\\mu^a,\n\\end{equation}\nwith $g_s$ the coupling constant of the strong interaction, typically written as $\\alpha_s = g_s^2 / (4\\uppi)$ in analogy to the fine-structure constant in \\gls{qed}. Gauge invariance thus introduces a total of $N=8$ gauge fields that can be identified with the eight gluons, leading to the full Lagrangian of \\gls{qcd}\n\\begin{equation}\n\t\\Lagr_\\mathrm{QCD} = \\sum_q{\\bar{q}(i\\gamma^\\mu\\codiff_\\mu - m_q)q} - \\frac{1}{4}G^a_{\\mu\\nu}G^{\\mu\\nu,a},\n%\t\\Lagr_\\mathrm{QCD} = \\sum_q{\\bar{q}(i\\gamma^\\mu\\uppartial_\\mu - m_q)q} - \\sum_q{g_s\\bar{q}\\gamma^\\mu\\frac{\\lambda^a}{2}qG^a_\\mu} - \\frac{1}{4}G^a_{\\mu\\nu}G^{\\mu\\nu,a},\n\\end{equation}\nwhere $q = u,d,s,c,b,t$ and $G^a_{\\mu\\nu}$ are the gluon field strengths given by\n\\begin{equation}\n\tG^a_{\\mu\\nu} = \\uppartial_\\mu G^a_\\nu - \\uppartial_\\nu G^a_\\mu + g_s f^{abc}G^b_\\mu G^c_\\nu.\n\\end{equation}\nAs expected from the previous section, $\\Lagr_\\mathrm{QCD}$ contains terms that are cubic and quartic in the gluon fields, resulting in gluon self-interaction in the theory. All possible \\gls{qcd} interaction vertices involving gluons and quarks are shown in \\cref{fig:qcd_vertices}. The gluon self-interaction leads to a number of phenomena unknown to Abelian theories, rendering the kinematics of \\gls{qcd} highly non-trivial.\n\nIn \\gls{qcd}, an effect similar to the electric charge screening in \\gls{qed} happens through quark-antiquark pairs, resulting in a screening of the colour charge. However, the existence of gluon loops in the gluon propagator due to gluon self-interaction creates an opposing \\textit{antiscreening} effect of colour charges. At short distances or large momentum scales, colour-charged particles essentially become free particles, a phenomenon called \\textit{asymptotic freedom}. In this regime, where $\\alpha_s$ is sufficiently small, \\gls{qcd} processes can be calculated using perturbation theory. At large distances or small moment scales, however, $\\alpha_s$ becomes large, and gluons interact very strongly with colour-charged particles, meaning that no free gluons or quarks can exist. This phenomenon is called \\textit{confinement} and implies that free quarks and gluons will be subject to \\textit{hadronisation}, \\ie form colourless bound states by combining with other quarks or gluons (that can be created from the vacuum). In a particle detector, hadronisation manifests itself as collimated showers of particles, called \\textit{jets}. At momentum scales where the strong coupling constant $\\alpha_s$ becomes large ($\\alpha_s \\approx \\mathcal{O}(1)$), \\gls{qcd} processes can no longer be calculated using perturbation theory and instead lattice \\gls{qcd} is used~\\cite{PhysRevD.10.2445,DeGrand:1055545}. \n\n\n\\begin{figure}\n\t\\centering\n\t\\begin{subfigure}[b]{0.30\\linewidth}\n\t\t\\centering\\includegraphics[width=0.7\\textwidth]{gluon_quark_vertex}\n%\t\t\\caption{\\label{fig:gluon_quark_vertex}}\n\t\\end{subfigure}%\n\t\\begin{subfigure}[b]{0.30\\linewidth}\n\t\t\\centering\\includegraphics[width=0.7\\textwidth]{gluon_vertex}\n%\t\t\\caption{\\label{fig:gluon_vertex}}\n\t\\end{subfigure}\t\n\t\\begin{subfigure}[b]{0.30\\linewidth}\n\t\t\\centering\\includegraphics[width=0.7\\textwidth]{gluon_quartic_vertex}\n%\t\t\\caption{\\label{fig:gluon_quartic_vertix}}\n\t\\end{subfigure}\n\t\\caption{Possible vertices in \\gls{qcd}.}\n\t\\label{fig:qcd_vertices}\n\\end{figure}\n\n\\subsubsection{Electroweak interaction}\n\\label{sec:ewk_interaction}\n\nDuring the 1960s, Glashow, Weinberg and Salam~\\cite{GLASHOW1961579,PhysRevLett.19.1264,Salam1959} developed a unified theory of the electromagnetic and weak interactions, based on the $SU(2)_\\mathrm{L}\\otimes U(1)_Y$ symmetry group. Known already experimentally from the Wu experiment~\\cite{PhysRev.105.1413} in 1956, weak interaction violates parity, \\ie the symmetry transformations have to act differently on the left-handed and right-handed fermion fields. The left- and right-handed components of a fermion field can be projected out using\n\\begin{equation}\n\t\\psi_\\mathrm{L} = \\frac{1-\\gamma^5}{2}\\psi , \\ \\ \\qquad \t\\psi_\\mathrm{R} = \\frac{1+\\gamma^5}{2}\\psi,\n\\end{equation}\nwith $\\gamma^5 = i\\gamma^0\\gamma^1\\gamma^2\\gamma^3$. As the weak interaction only acts on left-handed fermions, they can be ordered as $SU(2)$ doublets\n\\begin{equation}\n\t\\begin{pmatrix}\n\t\t\\nu_e \\\\\n\t\te\n\t\\end{pmatrix}_\\mathrm{L},\n\t\\quad\n\t\\begin{pmatrix}\n\t\tu \\\\\n\t\td\n\t\\end{pmatrix}_\\mathrm{L},\n\t\\qquad\n\t\\begin{pmatrix}\n\t\t\\nu_\\mu \\\\\n\t\t\\mu\n\t\\end{pmatrix}_\\mathrm{L},\n\t\\quad\n\t\\begin{pmatrix}\n\t\tc \\\\\n\t\ts\n\t\\end{pmatrix}_\\mathrm{L},\n\t\\qquad\n\t\\begin{pmatrix}\n\t\t\\nu_\\tau \\\\\n\t\t\\tau\n\t\\end{pmatrix}_\\mathrm{L},\n\t\\quad\n\t\\begin{pmatrix}\n\t\tt \\\\\n\t\tb\n\t\\end{pmatrix}_\\mathrm{L}.\n\\end{equation} \nThe quantum number associated with $SU(2)$ symmetry transformations is called weak isospin $I$ with the third component denoted as $I_3$. Fermion doublets have $I=1/2$, with the upper component having $I_3 = 1/2$ and the lower component $I_3=-1/2$. Right-handed fermion fields have $I=0$, \\ie are singlet states in weak isospin space\n\\begin{equation}\n\te_\\mathrm{R},\\,  u_\\mathrm{R},\\,  d_\\mathrm{R}, \\qquad \\mu_\\mathrm{R},\\,  c_\\mathrm{R},\\,  s_\\mathrm{R}, \\qquad \\tau_\\mathrm{R},\\,  t_\\mathrm{R},\\,  b_\\mathrm{R}, \n\\end{equation}\nand thus do not couple to the weak interaction. In the electroweak theory, neutrinos are assumed to be strictly massless, therefore no right-handed neutrino singlets exist. \n\nThe fermion doublets can be written in a free Lagrangian similar to \\cref{eq:free_lagrangian,eq:dirac_lagrangian},\n\\begin{equation}\n\t\\Lagr = \\bar{\\psi}_\\mathrm{L}i\\gamma^\\mu\\uppartial_\\mu\\psi_\\mathrm{L},\n\\end{equation}\nwith one crucial difference---the omission of the fermion masses. As $\\bar{\\psi}\\psi = \\bar{\\psi}_\\mathrm{L}\\psi_\\mathrm{R} + \\bar{\\psi}_\\mathrm{R}\\psi_\\mathrm{L}$, mass terms would mix left- and right-handed terms and break gauge invariance. \\Cref{sec:ssb} will illustrate how fermion masses will instead be generated in the electroweak theory. For left-handed fermion fields, local $SU(2)_\\mathrm{L}$ transformations can be written as\n\\begin{equation}\n\t\\psi_\\mathrm{L} \\rightarrow \\mathrm{exp}\\left(ig_2\\alpha^a\\frac{\\sigma^a}{2}\\right)\\psi_\\mathrm{L},\n\\end{equation}  \nwhere $g_2$ is the coupling constant, $\\alpha^a$ (with $a=1,2,3$) are real parameters and the Pauli matrices $\\sigma^a$ are the generators of $SU(2)_\\mathrm{L}$. By introducing the covariant derivative $\\codiff_\\mu = \\uppartial_\\mu + ig_2\\frac{\\sigma^a}{2}W^a_\\mu$ and including the usual kinetic term for the gauge fields, the Lagrangian becomes invariant under $\\mathrm{SU}(2)_\\mathrm{L}$ transformations and reads\n\\begin{equation}\n\t\\Lagr = \\bar{\\psi}_\\mathrm{L}i\\gamma^\\mu\\codiff_\\mu\\psi_\\mathrm{L} - \\frac{1}{4}W^a_{\\mu\\nu}W^{\\mu\\nu,a},\n\\end{equation}\nwith the gauge field strength tensors $W^a_{\\mu\\nu} = \\uppartial_\\mu W^a_\\nu - \\uppartial_\\nu W^a_\\mu + g_2 \\epsilon^{abc}W^b_\\mu W^c_\\nu$, where $\\epsilon^{abc}$ are the structure constants. As previously in the case of \\gls{qcd}, the non-Abelian structure of the symmetry group causes self-interactions of the gauge fields.\n\nIn order to include electromagnetic interactions, the weak isospin group is extended with the $U(1)_Y$ group, corresponding to the multiplication of a phase factor $e^{i\\alpha\\frac{Y}{2}}$ to each of the preceding doublets and singlets. Here, $Y$ is the weak hypercharge as given by the Gell-Mann--Nishijima relation~\\cite{Gell-Mann1956,10.1143/PTP.13.285,10.1143/PTP.10.581},\n\\begin{equation}\n\tQ = I_3 + \\frac{Y}{2},\n\t\\label{eq:gell-mann-nishijima}\n\\end{equation}\nwith $Q$ the electric charge.\nAs will be discussed in \\cref{sec:ssb}, the spontaneous breaking of the \\mbox{$SU(2)_\\mathrm{L}\\otimes U(1)_Y$} gauge symmetry will recover the electromagnetic gauge group $U(1)_\\mathrm{em}$~\\cite{Peskin:1995ev}.\n\nBy modifying the covariant derivative to include a $U(1)_Y$ gauge field and ensuring that $U(1)_Y$ acts the same on left-handed and right-handed fermions with coupling constant $g_1$, it can be written as $\\codiff_\\mu = \\uppartial_\\mu + ig_2\\frac{\\sigma^a}{2}W^a_\\mu + ig_1\\frac{Y}{2}B_\\mu$ for left-handed fermions and $\\codiff_\\mu = \\uppartial_\\mu + ig_1\\frac{Y}{2}B_\\mu$ for right-handed fermions. The full electroweak Lagrangian then is\n\\begin{equation}\n\\begin{split}\n\t\\Lagr_\\mathrm{electroweak} = & \\sum_j{\\bar{\\psi}_\\mathrm{L}^j i \\gamma^\\mu \\left(\\uppartial_\\mu -ig_2\\frac{\\sigma^a}{2} W^a_\\mu + ig_1 \\frac{Y}{2} B_\\mu \\right) \\psi^j_\\mathrm{L}} \\\\\n\t& + \\sum_j{\\bar{\\psi}_\\mathrm{R}^j i \\gamma^\\mu \\left(\\uppartial_\\mu + ig_1 \\frac{Y}{2} B_\\mu \\right) \\psi^j_\\mathrm{R}}, \n\\end{split}\n\\end{equation}\nwhere $B_{\\mu\\nu} = \\uppartial_\\mu B_\\nu - \\uppartial_\\nu B_\\mu$, and the two sums run over the left- and right-handed fermions, respectively.\n\n\\subsubsection{Spontaneous symmetry breaking}\n\\label{sec:ssb}\n\nIn the electroweak theory a total of three vector fields $W^a_\\mu$ and one vector field $B_\\mu$ are associated with the gauge groups $SU(2)_\\mathrm{L}$ and $U(1)_Y$, respectively. As has been shown explicitly through the example of \\gls{qed} in \\cref{sec:gauge_principle}, the gauge fields need to be massless for the resulting Lagrangian to be gauge invariant under the respective symmetry group. In addition, the electroweak symmetry group does not allow for fermion masses. Both gauge bosons of the weak interaction and the fermions are, however, manifestly massive, and therefore the electroweak symmetry has to be broken in the \\gls{sm}.\n\nThe spontaneous symmetry breaking of the $SU(2)_\\mathrm{L}\\otimes U(1)_Y$ gauge group is achieved through the Brout--Englert--Higgs   mechanism~\\cite{PhysRevLett.13.321,PhysRevLett.13.508,PhysRev.145.1156}. In the SM, an isospin doublet of complex scalar fields, called Higgs doublet, is introduced\n\\begin{equation}\n\t\\Phi(x) = \\begin{pmatrix}\n\t\t\\phi^+(x) \\\\\n\t\t\\phi^0(x)\n\t\\end{pmatrix}.\n\\end{equation}\nThe Higgs doublet has hypercharge $Y=1$, and thus, according to the Gell-Mann--Nishijima relation, $\\phi^+$ has electric charge +1 while $\\phi^0$ is electrically neutral. With the covariant derivative introduced in \\cref{sec:ewk_interaction}, the Higgs doublet gets corresponding terms in the SM Lagrangian, \n\\begin{equation}\n\t\\Lagr_h = (\\codiff_\\mu\\Phi)^\\dagger(\\codiff^\\mu\\Phi) - V(\\Phi),\n\t\\label{eq:higgs_lagrangian}\n\\end{equation}\nwhere $V(\\Phi)$ is a gauge invariant potential of the form\n\\begin{equation}\n\tV(\\Phi) = -\\mu^2\\Phi^\\dagger\\Phi + \\frac{\\lambda}{4}(\\Phi^\\dagger\\Phi)^2.\n\t\\label{eq:higgs_potential}\n\\end{equation}\nFor positive and real parameters $\\mu^2$ and $\\lambda$, this potential has the form of a \\textit{Mexican hat} and an infinite number of minima for field configurations with $\\Phi^\\dagger\\Phi=2\\mu^2/\\lambda$. In the vacuum, \\ie in the ground state of the theory with minimal potential energy of the field, one of these minima is chosen such that the Higgs  receives a \\gls{vev},\n\\begin{equation}\n\t\\braket{\\Phi} = \\frac{1}{\\sqrt{2}}\\begin{pmatrix}\n\t\t0 \\\\\n\t\tv\n\t\\end{pmatrix} \\qquad \\textrm{with} \\quad v = \\frac{2\\mu}{\\sqrt{\\lambda}} \\approx \\SI{246}{\\GeV}.\n\t\\label{eq:higgs_vev}\n\\end{equation}\n\\Cref{eq:higgs_vev} is neither invariant under a $SU(2)_\\mathrm{L}$ transformation of the form $U = \\mathrm{exp}(i\\alpha^a\\frac{\\sigma^a}{2})$, nor under a $U(1)_Y$ phase factor of the form $\\mathrm{exp}(i\\alpha\\frac{Y}{2})$. Thus, the Lagrangian has a symmetry that the vacuum state does not share, thereby spontaneously breaking the $SU(2)_\\mathrm{L}\\otimes U(1)_Y$ symmetry. As the \\gls{vev} of $\\phi^+$ vanishes and $\\phi^0$ is invariant under $U(1)_\\mathrm{em}$, the $SU(2)_\\mathrm{L}\\otimes U(1)_Y$ symmetry group is broken down to $U(1)_\\mathrm{em}$~\\cite{Brock:1354959}.\n\nThe Higgs doublet can be expressed as excitations around the ground state\n\\begin{equation}\n\t\\Phi(x) = \\frac{1}{\\sqrt{2}} \\begin{pmatrix}\n\t\t\\phi_1(x)+i\\phi_2(x) \\\\\n\t\tv + h(x) + i\\chi(x)\n\t\\end{pmatrix},\n\t\\label{eq:higgs_expansion}\n\\end{equation}\nwhere $h$, $\\chi$, $\\phi_1$ and $\\phi_2$ are real-valued scalar fields with vanishing \\glspl{vev}. Inserting \n\\cref{eq:higgs_expansion} back into the potential $V(\\Phi)$ in \\cref{eq:higgs_potential} yields\n\\begin{equation}\n\tV = \\mu^2h^2 + \\frac{\\mu^2}{v} h (h^2 + \\chi^2 + \\phi_1^2+\\phi_2^2)+ \\frac{\\mu^2}{4v^2}(h^2 + \\chi^2 + \\phi_1^2 + \\phi_2^2),\n\t\\label{eq:higgs_potential_excitation}\n\\end{equation}\nwhere only \\textit{h} gets a mass term, thus corresponding to an electrically neutral scalar particle with mass $m_h = \\sqrt{2}\\mu$.\nThe other scalar fields remain massless, which is in accordance with the Nambu-Goldstone theorem~\\cite{Nambu:1960tm,Goldstone:1961eq}, stating that every spontaneously broken continuous symmetry generates a massless Goldstone boson. These bosons are unphysical and can be gauged away through a $SU(2)_\\mathrm{L}$ transformation, such that the expansion around the vacuum from \\cref{eq:higgs_expansion}, involves only the physical scalar $h$ in the so-called \\textit{unitary gauge}~\\cite{Brock:1354959}.\n\\begin{figure}\n\t\\centering\n\t\\begin{subfigure}[b]{0.30\\linewidth}\n\t\t\\centering\\includegraphics[width=0.8\\textwidth]{w_fermion_vertex}\n\t\\end{subfigure}\n\t\\begin{subfigure}[b]{0.30\\linewidth}\n\t\t\\centering\\includegraphics[width=0.8\\textwidth]{z_fermion_vertex}\n\t\\end{subfigure}\n\t\\begin{subfigure}[b]{0.30\\linewidth}\n\t\t\\centering\\includegraphics[width=0.8\\textwidth]{gamma_fermion_vertex}\n\t\\end{subfigure}\n\t\\par\\medskip\n\t\\begin{subfigure}[b]{0.30\\linewidth}\n\t\t\\centering\\includegraphics[width=0.7\\textwidth]{w_boson_quartic_vertex}\n\t\\end{subfigure}\n\t\\begin{subfigure}[b]{0.30\\linewidth}\n\t\t\\centering\\includegraphics[width=0.7\\textwidth]{wz_boson_quartic_vertex}\n\t\\end{subfigure}\t\n\t\\begin{subfigure}[b]{0.30\\linewidth}\n\t\t\\centering\\includegraphics[width=0.8\\textwidth]{w_boson_cubic_vertex}\n\t\\end{subfigure}\n\t\\caption{Possible vertices in the electroweak interaction.}\n\t\\label{fig:ewk_vertices}\n\\end{figure}\n\n\nInserting \\cref{eq:higgs_expansion} and the potential $V$ from \\cref{eq:higgs_potential_excitation} back into the Lagrangian $\\Lagr_h$ in \\cref{eq:higgs_lagrangian} leads to mass terms for the gauge fields through their couplings to the \\textit{h} field. The \\textit{physical} fields corresponding to the physically observable $W^\\pm$, $Z$ and $\\gamma$ bosons in the electroweak theory are then given by the linear combinations\n\\begin{align*}\n\tW^\\pm_\\mu \t& = \\frac{1}{\\sqrt{2}}(W^1_\\mu\\mp i W^2_\\mu) \t\t\t\t& \\textrm{with} \\quad m_W  & = \\frac{g_2}{2}v, \\\\\n\tZ_\\mu \t\t& = \\cos\\theta_W W_\\mu^3 - \\sin\\theta_W B_\\mu \t& \\textrm{with} \\quad m_Z  & = \\frac{1}{2}\\sqrt{g_1^2+g_2^2}v, \\\\\n\tA_\\mu \t\t& = \\sin\\theta_W W_\\mu^3 + \\cos\\theta_W B_\\mu \t& \\textrm{with} \\quad m_A  & = 0,\n\\end{align*}\nwhere $\\theta_W$ is the weak mixing angle. It is related to the masses of the $W$ and $Z$ bosons and the electroweak coupling constants by\n\\begin{equation}\n\t\\cos{\\theta_W} = \\frac{g_2}{\\sqrt{g_1^2 + g_2^2}} = \\frac{m_W}{m_Z}.\n\\end{equation} \n\n%The Higgs potential can then be written as\n%\\begin{equation}\n%\tV = \\mu^2h^2 + \\frac{\\mu^2}{v} h (h^2 + \\chi^2 + \\phi_1^2+\\phi_2^2)+ \\frac{\\mu^2}{4v^2}(h^2 + \\chi^2 + \\phi_1^2 + \\phi_2^2),\n%\\end{equation}\n%where only $h$ gets a mass term, thus describing an electrically neutral scalar particle with mass $m_h = \\sqrt{2}\\mu$. The remaining scalar fields remain massless, in accordance with the Nambu-Goldstone theorem~\\cite{Nambu:1960tm,Goldstone:1961eq}, stating that every spontaneously broken continuous symmetry generates a massless Goldstone boson. These bosons are unphysical and can be gauged away through a $SU(2)_\\mathrm{L}$ transformation, such that the expansion around the vacuum from \\cref{eq:higgs_expansion} involves only the physical scalar $H(x)$,\n%\\begin{equation}\n%\t\\Phi(x) = \\frac{1}{\\sqrt{2}} \\begin{pmatrix}\n%\t\t0 \\\\\n%\t\tv + h(x)\n%\t\\end{pmatrix}.\t\n%\\end{equation}\n%The gauge transformation bringing \\cref{eq:higgs_expansion} into the above form is called the \\textit{unitary gauge}~\\cite{Brock:1354959}. In this gauge, the Higgs potential from \\cref{eq:higgs_potential} has the form\n%\\begin{equation}\n%\tV = \\frac{m_h^2}{2} h^2 + \\frac{m_h^2}{2v} h^3 + \\frac{m_h^2}{8v^2} h^4,\n%\\end{equation}\n%containing cubic and quartic self-interactions of the Higgs field proportional to $m^2_h$. Inserting the excitation around the vacuum state in the kinetic term of $\\Lagr_\\mathrm{h}$ yields mass terms for the vector bosons,\n%\\begin{equation}\n%\t\\Lagr_{h} \\propto \\frac{v^2}{8}g^2_2\\left(W_\\mu^1W^{1,\\mu} + W_\\mu^2W^{2,\\mu}\\right) + \\frac{v^2}{8} \\begin{pmatrix}\n%\t\tW^3_\\mu & B_\\mu\n%\t\\end{pmatrix}\n%\t\\begin{pmatrix}\n%\t\tg_2^2 & g_1g_2   \\\\\n%\t\tg_1g_2 & g_1^2\n%\t\\end{pmatrix}\n%\t\\begin{pmatrix}\n%\t\tW^{3,\\mu} \\\\\n%\t\tB^\\mu\n%\t\\end{pmatrix}.\n%\\end{equation}\n%Instead of expressing the Lagrangian in terms of the fields $W^a_\\mu$ and $B_\\mu$ that make the original gauge invariance manifest, it can also be written in terms of the \\textit{physical} fields that correspond to the physical $W^\\pm$, $Z$ and $\\gamma$ bosons in the electroweak theory,\n%\\begin{align*}\n%\tW^\\pm_\\mu \t& = \\frac{1}{\\sqrt{2}}(W^1_\\mu\\mp i W^2_\\mu) \t\t\t\t& \\textrm{with} \\quad m_W  & = \\frac{g_2}{2}v, \\\\\n%\tZ_\\mu \t\t& = \\frac{1}{\\sqrt{g_1^2+g_2^2}}(g_2W^3_\\mu - g_1 B_\\mu) \t& \\textrm{with} \\quad m_Z  & = \\frac{\\sqrt{g_1^2+g_2^2}}{2}v, \\\\\n%\tA_\\mu \t\t& = \\frac{1}{\\sqrt{g_1^2+g_2^2}}(g_1W^3_\\mu + g_2 B_\\mu) \t& \\textrm{with} \\quad m_A  & = 0.\n%\\end{align*}\n%It is worth noting, that the massless photon field $A_\\mu$ associated with the electromagnetic $U(1)_\\mathrm{em}$ gauge symmetry is automatically recovered. All possible vertices between fermions and the physical electroweak gauge bosons are shown in \\cref{fig:ewk_vertices}. The change of basis from $(W^3_\\mu, B_\\mu)$ to $(Z_\\mu,A_\\mu)$~\\cite{Peskin:1995ev} can also be written as a basis rotation with the weak mixing angle $\\theta_W$, \\improvement{Write somewhere SU2xU1 to U1 breakdown}\n%\\begin{equation}\n%\t\\begin{pmatrix}\n%\t\tZ_\\mu \\\\\n%\t\tA_\\mu\n%\t\\end{pmatrix} =\n%\t\\begin{pmatrix}\n%\t\t\\cos{\\theta_W} & \\sin{\\theta_W} \\\\\n%\t\t- \\sin{\\theta_W} & \\cos{\\theta_W}\n%\t\\end{pmatrix}\n%\t\\begin{pmatrix}\n%\t\tW^3_\\mu \\\\\n%\t\tB_\\mu\n%\t\\end{pmatrix} \\qquad \\textrm{with } \\cos{\\theta_W} = \\frac{g_2}{\\sqrt{g_1^2 + g_2^2}} = \\frac{m_W}{m_Z}.\n%\\end{equation}\n\n\\begin{figure}\n\t\\centering\n\t\\begin{subfigure}[b]{0.30\\linewidth}\n\t\t\\centering\\includegraphics[width=0.75\\textwidth]{h_boson_quartic_vertex}\n\t\\end{subfigure}%\n\t\\begin{subfigure}[b]{0.30\\linewidth}\n\t\t\\centering\\includegraphics[width=0.85\\textwidth]{h_boson_cubic_vertex}\n\t\\end{subfigure}%\n\t\\begin{subfigure}[b]{0.30\\linewidth}\n\t\t\\centering\\includegraphics[width=0.9\\textwidth]{h_boson_digauge_vertex}\n\t\\end{subfigure}\n\t\\par\\medskip\n\t\\begin{subfigure}[b]{0.30\\linewidth}\n\t\t\\centering\\includegraphics[width=0.9\\textwidth]{h_boson_gauge_vertex}\n\t\\end{subfigure}%\n\t\\begin{subfigure}[b]{0.30\\linewidth}\n\t\t\\centering\\includegraphics[width=0.85\\textwidth]{h_boson_fermion_vertex}\n\t\\end{subfigure}\t\n\t\\caption{Possible vertices involving the Higgs boson.}\n\t\\label{fig:higgs_vertices}\n\\end{figure}\n\nIn the \\gls{sm} the $W^\\pm$ and $Z$ bosons hence acquire masses through spontaneous breaking of the electroweak gauge symmetry $SU(2)_\\mathrm{L}\\otimes U(1)_Y$ through the Higgs mechanism. The massless photon field $A_\\mu$ associated with the electromagnetic $U(1)_\\mathrm{em}$ gauge symmetry is automatically recovered. All possible vertices between fermions and the physical gauge bosons described by the electroweak theory are shown in \\cref{fig:ewk_vertices}. \n\nFurthermore, the masses of fermion fields are related to gauge-invariant Yukawa interactions with the Higgs field. For one fermion generation, the respective Yukawa terms in the Lagrangian are\n\\begin{equation}\n\t\\Lagr_\\mathrm{Yukawa,gen} = - \\lambda_\\ell \\bar{L}_\\mathrm{L}\\Phi\\ell_\\mathrm{R} - \\lambda_d \\bar{Q}_\\mathrm{L}\\Phi d_\\mathrm{R} - \\lambda_u \\bar{Q}_\\mathrm{L} \\Phi^\\dagger u_\\mathrm{R} + \\mathrm{h.c.},\n\\end{equation}\nwhere $\\lambda_f$ with $f = \\ell,d,u$ are the dimensionless Yukawa couplings and $L_\\mathrm{L} = (\\nu_\\mathrm{L},\\ell_\\mathrm{L})^T$ and $Q_\\mathrm{L} = (u_\\mathrm{L},d_\\mathrm{L})^T$ are the left-handed lepton and quark doublets, respectively. The non-vanishing \\gls{vev} of the Higgs field then gives rise to fermion mass terms of the form \n\\begin{equation}\n m_f = \\lambda_f \\frac{v}{\\sqrt{2}},\n\\end{equation}\nyielding fermion couplings to the Higgs field proportional to the fermion masses $m_f$. All \\gls{sm} interaction vertices involving the Higgs boson are shown in \\cref{fig:higgs_vertices}.\n% The \\gls{vev} of the Higgs field then gives rise to fermion mass terms in the Lagrangian, which, in the unitary gauge, yields for a single fermion generation\n%\\begin{equation}\n% \t\\Lagr_\\mathrm{Yukawa, gen} = - \\sum_{f=\\ell,d,u}{\\left(m_f\\bar{\\psi}_f\\psi_f + \\frac{m_f}{v}h\\bar{\\psi}_f\\psi_f\\right)} \\qquad \\textrm{with} \\quad m_f = \\frac{1}{\\sqrt{2}}\\lambda_f v.\n%\\end{equation}\n\nWhen introducing all three fermion generations, additional Yukawa terms mixing fermions of different generations appear in the Lagrangian~\\cite{Brock:1354959}. The terms involving quark fields can be parametrised using the \\gls{ckm} matrix~\\cite{PhysRevLett.10.531,CKM:1973fv}, quantifying the transition probability between quark generations. Since no right-handed neutrinos exist in the SM, no generation mixing in the lepton sector occurs and hence no neutrino mass terms are allowed in the \\gls{sm}. Neutrino oscillations have, however, been observed experimentally, thus at least two massive neutrino generations need to exist. Their mixing can be described\\footnote{Technically, this is already an extension of the \\gls{sm}.} with the \\gls{pmns} matrix~\\cite{PMNS:1962mu}, allowing neutrinos to acquire mass \\eg through the see-saw mechanism~\\cite{Brdar:2019iem}.\n \n\\subsection{Renormalisation and divergencies}\n\\label{ch:renormalisation}\n\nAt lowest order in the perturbative expansion, the momenta of the internal lines in the Feynman diagrams are fixed by the external particles. For higher orders where the diagrams involve loops, the momenta of the internal lines need to be integrated over as they are not fixed by energy-momentum conservation. Some examples of loop corrections to propagators and vertices are shown in \\cref{fig:loop_corrections}. As each vertex in the Feynman diagrams is associated with a coupling constant that is usually much smaller than 1 (apart from the non-perturbative regime of \\gls{qcd}), higher orders in the perturbative expansion contribute less and less to the total amplitude of the full expansion.\n\n\\begin{figure}\n\t\\centering\n\t\\begin{subfigure}[b]{0.33\\linewidth}\n\t\t\\centering\\includegraphics[width=0.85\\textwidth]{gluon_loop}\n\t\t\\caption{\\label{fig:gluon_loop}}\n\t\\end{subfigure}%\n\t\\begin{subfigure}[b]{0.33\\linewidth}\n\t\t\\centering\\includegraphics[width=0.85\\textwidth]{wz_propagator}\n\t\t\\caption{\\label{fig:wz_propagator}}\n\t\\end{subfigure}\t\n\t\\begin{subfigure}[b]{0.33\\linewidth}\n\t\t\\centering\\includegraphics[width=0.85\\textwidth]{cubic_vertex}\n\t\t\\caption{\\label{fig:cubic_vertex}}\n\t\\end{subfigure}\n\t\\caption{Examples of loop corrections to (a) the gluon propagator, (b) the $W$ or $Z$ propagator and (c) the cubic gauge boson vertex.}\\label{fig:loop_corrections}\n\\end{figure}\n\nThe momentum integrals in loop corrections, however, lead to \\textit{ultraviolet divergencies} for large momenta. In order to eliminate the divergencies, the integrals have to be \\textit{regularised}, \\eg by applying a cut-off scale $\\Lambda$, or calculating the integrals in a number $D = 4-\\epsilon$ of dimensions where they converge. The potential divergencies are then absorbed in parameters of the Lagrangian, such as coupling constants and masses, after which the regulator is removed again (\\eg by setting $\\epsilon\\rightarrow 0$) and a \\textit{renormalisation} procedure is applied, replacing the bare parameter values with the physical, measured values~\\cite{Brock:1354959}. Renormalisation effectively absorbs the effects of quantum fluctuations, acting on much smaller scales than the scale of the given problem, into the parameters of the theory.\n As Veltmann and t'Hooft~\\cite{THOOFT1972189,THOOFT1971173} have shown, all Yang-Mills theories with massive gauge fields are renormalisable, rendering the \\gls{sm} as a whole a renormalisable theory.  \n\n\\section{Supersymmetry}\n\nOriginally developed in the late 1960s and early 1970s as an attempt to combine the Poincaré group with internal symmetries into a single symmetry group~\\cite{kane2000the}, \\glsfirst{susy} is a class of theories transforming fermionic states into bosonic ones, and vice-versa. Since its theoretical discovery, driven purely by theoretical developments rather than by pressure of existing data~\\cite{kane2000the}, \\gls{susy} was found to have far-reaching phenomenological consequences that could solve some of the shortcomings of the \\gls{sm}. \n\nThis section starts with an overview of the shortcomings of the \\gls{sm} and illustrates how they could be solved by supersymmetric theories. This is followed by an introduction to the mathematical description and phenomenological consequences of \\gls{susy}. While the following sections are intended to highlight the most important concepts and relations, a much more complete and detailed introduction to \\gls{susy} can be found, \\eg, in \\references\\cite{Martin:1997ns,Bustamante:2009us}.\n\n%Among the properties a quantum field theory might possess to make it more mathematically tractable, one specific higher symmetry reveals particularly far-reaching implications; a symmetry relating fermions and bosons, known as \\gls{susy}. In the following, the basic concepts of \\gls{susy}, a class of theories that could solve some of the shortcomings of the \\gls{sm}. \n\n%First, some of the shortcomings of the \\gls{sm} are highlighted, and possible solutions through supersymmetric theories are illustrated.  highlighting some of the open questions of the SM. This is followed by an introduction to the mathematical description and phenomenological consequences of supersymmetric theories. The following sections are intended to highlight the most important concepts and relations, a much more complete and detailed introduction to \\gls{susy} can be found in \\references\\cite{Martin:1997ns,Bustamante:2009us}.\n\n\\subsection{Shortcomings of the Standard Model}\\label{sec:shortcomings_sm}\n\nAlthough the \\gls{sm} is a remarkably successful theory that is able to predict and describe the interactions between elementary particles with unprecedented precision, there are still phenomena in nature that cannot be suitable understood within the theoretical framework of the \\gls{sm}. \n\nThose limitations and open questions are the reason for numerous searches looking for new physics beyond the \\gls{sm}, such as the one presented in this thesis. Some of these open questions are described in the following. \n\n\\subsubsection{Dark Matter}\n\nThe existence of \\glsfirst{dm}, \\ie non-luminous and non-absorbing matter is nowadays well established~\\cite{pdg2020}. Some of the earliest hints for the existence of \\gls{dm} came from the observation that the rotation curves of luminous objects are not consistent with the expected velocities based on the gravitational attraction of the visible objects around them. Zwicky already postulated in 1933 the existence of \\gls{dm}~\\cite{Zwicky:437297} based on rotation curves of galaxies in the Coma cluster. In 1970, Rubin measured rotation curves of spiral galaxies~\\cite{Rubin:1970zza}, revealing again a significant disagreement with the theoretically expected curves given the visible matter in the galaxies. Based on Newtonian dynamics, the circular velocity of stars outside the bulge of galaxies is expected to fall off with increasing radius as $v(r) \\propto 1/\\sqrt{r}$~\\cite{Bertone:2004pz}. Rubin's observations, however, revealed that the velocities of stars outside the bulge stay approximately constant, strongly suggesting the existence of a non-luminous (or \\textit{dark}) matter halo around the galaxies. Surveys of galaxy clusters and observations of gravitational lensing effects, \\eg, in the bullet cluster~\\cite{Clowe:2006eq} or the Abell 1689 cluster~\\cite{Taylor:1998uk}, have since then further consolidated the existence of large accumulations of non-luminous matter in the universe.\n\nThe anisotropies in the \\gls{cmb}, studied by the COBE~\\cite{Bennett:1996ce,COBE}, WMAP~\\cite{WMAP2,WMAP1} and Planck missions~\\cite{Planck} are well described by the \\gls{lcdm} model~\\cite{Liddle:1976476}, which includes a density for cold dark matter. Planck's latest results~\\cite{Aghanim:2018eyx} for the cold \\gls{dm} relic density $\\Omega_c h^2$ and baryonic density $\\Omega_b h^2$ of\n\\begin{align}\n\\begin{split}\n\t\\Omega_c h^2 &= 0.1200\\pm0.0012, \\\\\n\t\\Omega_b h^2 &= 0.02237\\pm0.00015,\n\\end{split}\n\\end{align}\nsuggest that ordinary baryonic matter only makes up $\\sim 4.9\\%$ of the universe's matter content, while \\gls{dm} accounts for $\\sim 26.1\\%$. The remaining $\\sim 69\\%$ are taken up by \\textit{dark energy}, the nature of which is yet another open question.\n\nCandidates for cold \\gls{dm} need to satisfy certain conditions: they have to be stable on cosmological timescales (otherwise they would have decayed by now), they have to couple only very weakly to the electromagnetic interaction (if at all, otherwise they would be \\textit{luminous} matter) and they need to have the right relic density. Analyses of structure formations in the Universe have furthermore shown that most \\gls{dm} should have been \\textit{cold}, \\ie non-relativistic, at the beginning of galaxy formation~\\cite{Bertone:2004pz}. Candidates for \\gls{dm} particles are \\eg sterile neutrinos, axions, primordial black holes, or \\glspl{wimp}.\n\nIn the SM, the only \\gls{dm} candidate particle is the neutrino. Given the upper limits on the neutrino masses, an upper bound on their relic density can be computed, revealing that neutrinos are not abundant enough to be a dominant component of \\gls{dm}~\\cite{Bertone:2004pz}. Furthermore, due to their low masses, neutrinos would still have been relativistic particles at the beginning of galaxy formation, preventing the \\textit{bottom-up}\\footnote{The \\textit{bottom-up} structure formation begins with small objects that subsequently merge into ever larger structures and corresponds to the structure formation process favoured in a universe dominated by cold \\gls{dm}.} structure formation, favoured by a cold \\gls{dm} dominated universe.\n\n Many \\gls{bsm} theories naturally predict new \\glspl{wimp} with masses in the GeV to TeV range. In many \\gls{susy} models with exact R-parity conservation (a quantity introduced in \\cref{sec:rparity}), the lightest supersymmetric particle is neutral and stable and could be a good candidate for \\gls{dm}.\n\n\\subsubsection{Unification of forces}\n\n\nAlthough the \\gls{sm} provides a good description of nature up to the energy scale probed with today's accelerators, some of its peculiar aspects hint to a more fundamental theory. A prominent example is the question why the electric charges of the electrons and the charges of the quarks in the protons and neutrons in the nuclei exactly cancel, making for electrically neutral atoms~\\cite{Brock:1354959}. Or in other words: why are the charges of all observed particles simple multiples of the fundamental charge? And why are they quantised in the first place?\n\nAn explanation to many of these peculiarities comes naturally when describing the \\gls{sm} as a unified theory with a single non-Abelian gauge group, \\eg $SU(5)$~\\cite{PhysRevLett.32.438}. The larger symmetry group with a single coupling constant is then thought to be spontaneously broken at very high energy, such that the known \\gls{sm} interactions are recovered at the lower energies probed in today's experiments. In such a \\gls{gut}, the particles in the \\gls{sm} are arranged in anomaly-free\\footnote{In the sense that loop corrections do not break symmetries that the Lagrangian has.}, irreducible representations of the gauge group, thereby, for example, naturally ensuring the fractional charges of quarks~\\cite{Peskin:1995ev}.\n\n\\begin{figure}\n\\floatbox[{\\capbeside\\thisfloatsetup{capbesideposition={right,center},capbesidewidth=0.4\\textwidth}}]{figure}[\\FBwidth]\n{\\caption{Evolution of the inverse coupling constants in the \\gls{sm} (dashed lines) and the \\gls{mssm} (solid lines) in function of the energy scale $Q$. Here, the masses of the supersymmetric particles are treated as common threshold and varied between $\\SI{750}{\\GeV}$ (blue lines) and $\\SI{2.5}{\\TeV}$ (red lines). Figure taken from \\reference\\cite{Martin:1997ns}.}\\label{fig:unification_forces}}\n{\\includegraphics[width=0.5\\textwidth]{unification}}\n\\end{figure}\n\nIn the \\gls{sm}, the coupling constants run towards each other with increasing energy scale, but never exactly meet. In the \\glsfirst{mssm}, introduced in \\cref{sec:mssm_intro}, the running couplings meet within their current uncertainties if the supersymmetric particles are at the $\\SI{}{\\TeV}$ scale, hinting that a supersymmetric \\gls{gut} could be a good candidate for describing physics at the unification scale. \\Cref{fig:unification_forces} shows that the running coupling constants in the \\gls{mssm} are modified such that they meet at $\\SI{e16}{\\GeV}$.\n\n\\subsubsection{The Hierarchy Problem}\n\nAs the \\gls{sm} is a renormalisable gauge theory, finite results are obtained for all higher-order loop corrections, making the \\gls{sm} a theory that is, in principle, well-defined up to infinite energies. In renormalisation terms, this means that the cut-off scale $\\Lambda$ is theoretically allowed to go to arbitrarily high values. It is clear though, that the \\gls{sm} cannot be a complete theory of nature and that, at some unknown high-energy scale $\\Lambda$, \\textit{new physics} has to appear. At the very least, a new theoretical framework becomes necessary at the Planck scale $M_P \\approx \\SI{e19}{\\GeV}$~\\cite{Bustamante:2009us}, where quantum gravitational effects can no longer be ignored.\n\nThe mass parameters of fermions and massive vector bosons are protected from large quantum corrections by chiral symmetry and gauge symmetry, respectively~\\cite{Aitchison:2007fn}. The mass parameter of the scalar Higgs field, on the other hand, receives loop corrections proportional at least to the scale at which new physics sets in. The Yukawa coupling of the Higgs field to a fermion $f$ with mass $m_f$, depicted in \\cref{fig:fermion_loop}, yields a one-loop correction term to the Higgs square mass~\\cite{Bustamante:2009us} given by\n\\begin{align}\n\t\\upDelta m_h^2 = -\\frac{\\lambda_f^2}{8\\uppi^2} \\Lambda^2 + \\dots\\, .\n\t\\label{eq:fermion_correction}\n\\end{align}\nThe Higgs mass thus quadratically diverges with the scale $\\Lambda$. If the \\gls{sm} is to be valid up to the Planck scale, then $\\Lambda = M_P$, and the correction to the Higgs squared mass becomes more than $10^{30}$ times larger than the expected value in the order of $(\\SI{e2}{\\GeV})^2$~\\cite{Martin:1997ns}.\nSimilar quantum corrections arise from the Higgs quartic coupling to a heavy scalar boson $S$ with mass $m_S$, shown in \\cref{fig:scal_loop}, yielding a one-loop correction~\\cite{Bustamante:2009us} given by \n\\begin{align}\n\t\\upDelta m_h^2 = \\frac{\\lambda_S}{16\\uppi^2}\\Lambda^2 + \\dots\\, .\n\t\\label{eq:scalar_correction}\n\\end{align}\nIn order to obtain the experimentally measured value of the Higgs mass, the quantum corrections to the bare Higgs parameter have to be tuned in such a way that they almost cancel, leading to a \\textit{fine-tuning} problem that is considered to be unnatural.\n\nInterestingly, the terms quadratically divergent in $\\Lambda$ in \\cref{eq:fermion_correction} and \\cref{eq:scalar_correction} enter with opposite signs. If, for every fermionic loop, there are two bosonic loops with $\\lambda_S = \\lambda_f^2$, the quadratically diverging terms neatly cancel. As will be discussed, this is exactly the case in supersymmetric theories. Additional correction terms omitted above are at most logarithmic in $\\Lambda$, and cancel if the scalar bosons and the fermion have the same masses (this is further discussed in \\cref{sec:susy_breaking}).\n\n\\begin{figure}\n\t\\centering\n\t\\begin{subfigure}[b]{0.5\\linewidth}\n\t\t\\centering\\includegraphics[width=0.75\\textwidth]{fermion_loop}\n\t\t\\caption{\\label{fig:fermion_loop}}\n\t\\end{subfigure}%\n\t\\begin{subfigure}[b]{0.5\\linewidth}\n\t\t\\centering\\includegraphics[width=0.75\\textwidth]{scalar_loop}\n\t\t\\caption{\\label{fig:scal_loop}}\n\t\\end{subfigure}\t\n\t\\caption{A massive fermion \\subref{fig:fermion_loop} and a hypothetical massive scalar particle \\subref{fig:scal_loop} coupling to the Higgs boson.}\\label{fig:loop_corrections_higgs}\n\\end{figure}\n\n%In SUSY, the Higgs mass is automatically protected from the large quantum corrections by the introduction of two complex scalar partners to each \\gls{sm} fermion. The quantum corrections from a hypothetical heavy complex scalar particle $S$ with mass $m_S$ as in \\cref{fig:scal_loop} yields a one-loop correction~\\cite{Martin:1997ns} given by \n%\\begin{align}\n%\t\\upDelta m_h^2 = \\frac{\\lambda_S}{16\\uppi^2}\\left[\\Lambda^2 - 2m_S^2\\ln\\left(\\Lambda/m_S\\right)+ \\dots\\right].\n%\t\\label{eq:scalar_correction}\n%\\end{align}\n\n%Interestingly, the corrections in \\cref{eq:fermion_correction} and \\cref{eq:scalar_correction} enter with opposite signs. Thus, if $\\lambda_S = \\vert\\lambda_f\\vert^2$, then the large quantum corrections neatly cancel and no excessive fine-tuning is needed. The requirement $\\lambda_S = \\vert\\lambda_f\\vert^2$ means that the fermions and their supersymmetric bosonic partners would have same masses. Such particles would have been discovered long ago in particle physics experiments, meaning that SUSY must be a broken symmetry (see \\cref{sec:susy_breaking} for a discussion on \\gls{susy} breaking) such that the supersymmetric particles acquire masses well above those of their \\gls{sm} partners. \n\n\\subsubsection{Anomalous magnetic moment of the muon}\n\nOne of the longest standing disagreements between experiment and theory in the \\gls{sm} is the anomalous magnetic moment of the muon~\\cite{pdg2020}. The magnetic moment of the muon $\\vec{\\mu}_\\mu$ is related to its intrinsic spin $\\vec{S}$ through the gyromagnetic ratio $g_\\mu$ by\n\\begin{equation}\n\t\\vec{\\mu}_\\mu = g_\\mu \\frac{q}{2m} \\vec{S}.\n\\end{equation}\nFor a structureless spin-1/2 particle with mass $m$ and charge $q=\\pm e$, the gyromagnetic ratio is \\mbox{$g_\\mu = 2$} \\cite{Bennett:2006fi}. Loop corrections coupling the muon spin to virtual fields cause small deviations, parameterised by the anomalous magnetic moment\n\\begin{equation}\n\ta_\\mu = \\frac{1}{2}(g_\\mu-2).\n\\end{equation}\nThe anomalous magnetic moment can be precisely predicted within the SM and experimentally measured with high accuracy. A comparison between experimental data and theoretical prediction thus directly tests the \\gls{sm} at quantum loop level and may hint to effects from new physics in case of discrepancies~\\cite{baer_tata_2006}.\nIn the SM, the most dominant contribution to $a_\\mu$ comes from \\gls{qed} corrections involving photon and fermion loops.\nA representative diagram is shown in \\cref{fig:qed_anomalous_moment}. Weak contributions involving the heavy $W^\\pm$, $Z$ and Higgs particles are suppressed by their masses~\\cite{Aoyama:2020ynm}.\nAlthough the contributions from \\gls{qcd} are relatively small, they give rise to the main theoretical uncertainties, since they cannot be calculated from first principles but rely either on data-driven calculations or lattice \\gls{qcd} evaluations~\\cite{Aoyama:2020ynm}.\n\nThe muon $g$--2 experiment at the Fermi National Accelerator Laboratory (FNAL)~\\cite{Abi:2021gix} has recently measured the anomalous magnetic moment of the muon, updating the results from the E821 experiment at Brookhaven National Laboratory (BNL)~\\cite{Bennett:2006fi}, obtained in 2004. The combined experimental average of both experiments finds a deviation from the \\gls{sm} expectation\\footnote{The \\gls{sm} value of $a_\\mu$ adopted in \\reference\\cite{Abi:2021gix} relies on the data-driven evaluation of the hadronic contributions using $e^+e^-$ collider data, recommended by the muon $g$--2 theory initiative~\\cite{Aoyama:2020ynm}.} of\n\\begin{equation}\n\t\\upDelta a_\\mu = a^\\mathrm{exp}_\\mu - a^\\mathrm{SM}_\\mu = (251\\pm59)\\times 10^{-11},\n%\t\\upDelta a_\\mu = a^\\mathrm{exp}_\\mu - a^\\mathrm{SM}_\\mu = 261(63)(48)\\times 10^{-11},\n\\end{equation}\nwhich is quantified to have a significance of $4.2\\sigma$~\\cite{Abi:2021gix}. These results strongly hint at the existence of new physics beyond the \\gls{sm}.\n\n\\begin{figure}\n\t\\centering\n\t\\begin{subfigure}[b]{0.33\\linewidth}\n\t\t\\centering\\includegraphics[width=1.0\\textwidth]{qed_anomalous_moment}\n\t\t\\caption{\\label{fig:qed_anomalous_moment}}\n\t\\end{subfigure}%\n\t\\begin{subfigure}[b]{0.33\\linewidth}\n\t\t\\centering\\includegraphics[width=1.0\\textwidth]{susy_anomalous_moment_1}\n\t\t\\caption{\\label{fig:susy_anomalous_moment_1}}\n\t\\end{subfigure}%\n\t\\begin{subfigure}[b]{0.33\\linewidth}\n\t\t\\centering\\includegraphics[width=1.0\\textwidth]{susy_anomalous_moment_2}\n\t\t\\caption{\\label{fig:susy_anomalous_moment_2}}\n\t\\end{subfigure}\t\n\t\\caption{Electromagnetic \\subref{fig:qed_anomalous_moment} and supersymmetric \\subref{fig:susy_anomalous_moment_1}, \\subref{fig:susy_anomalous_moment_2} contributions to $a_\\mu$. Supersymmetric particles are drawn in red. Adapted from~\\reference\\cite{baer_tata_2006}.}\\label{fig:loop_corrections_anomalous_moment}\n\\end{figure}\n\nIn many supersymmetric models, the measured deviation in $a_\\mu$ can easily be accommodated through additional Feynman diagrams involving the supersymmetric partners of the muon, the muon neutrino and the electroweak gauge bosons~\\cite{Czarnecki:2001pv,Feng:2001tr}. Two lowest-order diagrams involving supersymmetric particles (introduced in \\cref{sec:mssm_particle_content}) are shown in \\cref{fig:susy_anomalous_moment_1,fig:susy_anomalous_moment_2}.\n\n\n\\subsection{Supersymmetric Algebra}\\label{sec:susy_algebra}\n\nThe Coleman--Mandula no-go theorem~\\cite{PhysRev.159.1251} dictates that the symmetry group generating a consistent spacetime \\gls{qft} must be the direct product of the internal symmetry group with the Poincaré group, which in principle rules out the possibility for SUSY. The Coleman--Mandula proof, however, assumes the new symmetry to be generated by bosonic integer spin generators. The Haag--Lopuszanski--Sohnius extension~\\cite{Haag:1974qh} showed that the only possible way of non-trivially combining internal and spacetime symmetry groups is to use a Lie superalgebra and fermionic spin-1/2 generators.\n\nA generator of supersymmetric transformations is thus an anti-commuting spinor $Q$ that turns fermionic states $\\ket{f}$ into bosonic states $\\ket{b}$ and vice-versa,\n\\begin{equation}\n\tQ\\ket{f} = \\ket{b}, \\qquad \\qquad \\qquad Q\\ket{b}=\\ket{f}.\n\\end{equation}\nAs spinors are complex objects, $Q^\\dagger$ is also a symmetry operator. In order to obey the Haag--Lopuszanski--Sohnius loophole of the Coleman--Mandula theorem, both $Q$ and $Q^\\dagger$ are necessarily fermionic and thus must carry half-integer spin, meaning that \\gls{susy} must be a spacetime symmetry, \\ie a Poincaré symmetry. To simultaneously allow for parity-violating interactions, the \\gls{susy} generators have to satisfy the following algebra of commutation and anti-commutation relations~\\cite{Bustamante:2009us},\n\\begin{equation}\n\\begin{split}\n\t\\{ Q,Q^\\dagger \\} & \\quad = \\quad  2\\sigma_\\mu P^\\mu,\\\\\n\t\\{ Q,Q \\} &  \\quad = \\quad \\{ Q^\\dagger,Q^\\dagger \\} = 0, \\\\\n\t\\left[P^\\mu,Q \\right] &  \\quad = \\quad \\left[ P^\\mu,Q^\\dagger \\right] = 0, \\\\\n\t\\{ M^{\\mu\\nu}, Q \\} & \\quad = \\quad \\sigma^{\\mu\\nu} Q,\\\\\n\t\\{ M^{\\mu\\nu},Q^\\dagger \\} & \\quad = \\quad \\bar{\\sigma}^{\\mu\\nu} Q^\\dagger,\n  \\label{eq:commute}\n\\end{split}\n\\end{equation}\nwhere $P^\\mu$ is the four-momentum generator of spacetime translations, $\\sigma_\\mu = (\\mathbb{1}_2,\\sigma_i)$, $\\bar{\\sigma}_\\mu = (\\mathbb{1}_2,-\\sigma_i)$ with $i=1,2,3$ and the Pauli matrices $\\sigma_i$, and $\\sigma^{\\mu\\nu} = \\frac{i}{4}(\\sigma^\\mu\\bar{\\sigma}^\\nu - \\sigma^\\nu\\bar{\\sigma}^\\mu)$ as well as $\\bar{\\sigma}^{\\mu\\nu} = \\frac{i}{4}(\\bar{\\sigma}^\\mu\\sigma^\\nu - \\bar{\\sigma}^\\nu\\sigma^\\mu)$. This is the simplest version of SUSY, called $\\mathcal{N}=1$ symmetry, as it introduces only one pair of generators. Supersymmetric theories with $\\mathcal{N}\\geq 2$ pairs of generators also exist and generally have some theoretical advantages as, \\eg, fewer divergencies in the case of $\\mathcal{N}=2$, or even no divergencies at all in the case of $\\mathcal{N}=4$~\\cite{Bustamante:2009us}. \\gls{susy} models with $\\mathcal{N}\\geq 2$, however, do not allow for parity violation and thus fail to describe the physics of the SM, disqualifying them from a phenomenological point of view~\\cite{Bustamante:2009us}.\n\nAs both \\gls{susy} generators commute with spacetime translations (see \\cref{eq:commute}), they also both commute with the squared mass operator $-P^2$. Consequently, particles related by the generators, called \\textit{superpartners}, must have equal eigenvalues under $-P^2$, \\ie they must have equal masses. Furthermore, the \\gls{susy} generators also commute with the gauge transformation generators, hence superpartners must have same electric charge, weak isospin and degrees of freedom in colour space~\\cite{Martin:1997ns}.\n\n\\subsection{Supermultiplets}\\label{sec:supermultiplets}\n\nThe \\gls{sm} and \\gls{susy} particles are arranged in irreducible representations of the \\gls{susy} algebra, called \\textit{supermultiplets}, each containing both fermionic and bosonic states that are superpartners of each other. It can be shown that each supermultiplet has an equal number of fermion and boson degrees of freedom, $n_f = n_b$~\\cite{Martin:1997ns}.\n\nThe simplest supermultiplet $\\Psi$ that can be constructed contains a single Weyl fermion $\\psi$ and two real scalars, described by a single complex field $\\phi$, called the \\textit{sfermion}. The Weyl fermion has two spin helicity states, hence $n_f=2$, and the complex scalar field has two components with $n_b=1$ each. An additional complex scalar field $F$, called \\textit{auxiliary field} and not corresponding to a physical particle, has to be introduced in order to allow the \\gls{susy} algebra to close off-shell\\footnote{Henceforth, the term \\textit{on-shell} describes fields that obey the equations of motion and correspond to real particles, while the term \\textit{off-shell} refers to fields that do not obey the equations of motion and correspond to virtual particles. Often, the term \\textit{off-shell} is used in an inclusive fashion, \\ie to designate particles that can also be on the mass-shell, but do not necessarily have to be.}, where the energy-momentum relation does not hold~\\cite{Martin:1997ns}. The supermultiplet $\\Psi$ thus reads\n\\begin{equation}\n\t\\Psi = (\\phi,\\psi,F).\n\\end{equation}\nBeing a pure bookkeeping device, the auxiliary field does not propagate and can be eliminated on-shell with the equations of motion $F=F^*=0$. This supermultiplet is called a \\textit{chiral} or \\textit{scalar} supermultiplet~\\cite{Martin:1997ns}. \n\nThe next-simplest supermultiplet for which $n_f = n_b$ holds, is the \\textit{vector} or \\textit{gauge} supermultiplet~$\\Phi$ containing a spin-1 gauge boson $A^\\mu_a$, where $a$ is the index of the gauge group. In order for the theory to be renormalisable, this gauge boson must be massless before spontaneous breaking of the symmetry.\nAs a massless spin-1 boson has two helicity states, \\ie $n_b = 2$, the superpartner, called \\textit{gaugino}, must be a massless spin-1/2 Weyl fermion $\\lambda_a$ with two helicity states such that $n_f = 2$~\\cite{Martin:1997ns}. An auxiliary real bosonic field $D_a$ is needed to balance the degrees of freedom off-shell~\\cite{Bustamante:2009us}, completing the supermultiplet to be\n\\begin{equation}\n\t\\Phi = (\\lambda_a,A^\\mu_a,D_a).\n\\end{equation}\n Like the chiral auxiliary field, the gauge auxiliary field does not correspond to a physical particle and can be eliminated on-shell through its equations of motion~\\cite{Martin:1997ns}.\n \n\\subsection{Supersymmetric Lagrangian}\\label{sec:susy_lagrangian}\n\nThe simplest supersymmetric model that can be shown to realise the superalgebra is the massless, non-interacting Wess--Zumino model~\\cite{Wess:1974tw} with the action~\\cite{Bustamante:2009us,Martin:1997ns} \n\\begin{equation}\n\\begin{split}\nS & = \\int \\diff^4x(\\Lagr_\\mathrm{scalar} + \\Lagr_\\mathrm{fermion}), \\\\\n\t\\Lagr_\\mathrm{scalar} & = - \\uppartial^\\mu\\phi^*\\uppartial_\\mu\\phi, \\\\\n\t\\Lagr_\\mathrm{fermion} & = - i\\psi^\\dagger\\bar{\\sigma}^\\mu\\uppartial_\\mu\\psi , \\\\\n\t\\label{eq:wess_zumino_free}\n\\end{split}\n\\end{equation}\nwith a massless complex scalar $\\phi$ and a spin-1/2 fermion $\\psi$, corresponding to a single chiral supermultiplet. As discussed in \\cref{sec:supermultiplets}, in order for this Lagrangian to satisfy the supersymmetry off-shell where the equations of motion cannot be used, an auxiliary complex scalar field $F$ has to be added. The free Lagrangian~\\cite{Bustamante:2009us} in the action thus reads\n\\begin{equation}\n\\begin{split}\n\t\\Lagr_\\mathrm{free} & = \\Lagr_\\mathrm{scalar} + \\Lagr_\\mathrm{fermion} + \\Lagr_\\mathrm{aux},  \\qquad \\mathrm{with} \\quad \\Lagr_\\mathrm{aux} = F^{*i}F_i.\n%\t & = \\uppartial^\\mu\\phi^{*i}\\uppartial_\\mu\\phi_i + i\\psi^{\\dagger i}\\bar{\\sigma}^\\mu\\uppartial_\\mu\\psi_i + F^{*i}F_i,\n\\end{split}\n\\label{eq:free_wess_zumino}\n\\end{equation} \nThe auxiliary term $\\Lagr_\\mathrm{aux}$ implies the trivial equations of motion $F = F^* = 0$, which are needed to remove the auxiliary field in the on-shell case. The next step involves adding terms for non-gauge interactions for the chiral supermultiplets. Non-gauge interactions for chiral supermultiplets at most quadratic in the fermion fields can be achieved by introducing the term~\\cite{Bustamante:2009us},\n\\begin{equation}\n\t\\Lagr_\\mathrm{int} = - \\frac{1}{2}W^{ij}(\\phi,\\phi^*)\\psi_i \\psi_j + V(\\phi,\\phi^*) + c.c.,\n\t\\label{eq:wess_zumino_int}\n\\end{equation}\nwhere $W^{ij}$ is a holomorphic\\footnote{A holomorphic function is a complex-valued function in one or more complex variables that is complex differentiable in a neighbourhood for every point of its domain.} function of the complex scalar fields $\\phi_i$ of the form~\\cite{Bustamante:2009us}\n\\begin{equation}\n\tW^{ij} = \\frac{\\uppartial^2 W}{\\uppartial\\phi_i\\uppartial\\phi_j}. \n\\end{equation}\nHere, $W$ is called the \\textit{superpotential}. For the final Lagrangian to be renormalisable, the superpotential can at most be cubic~\\cite{Bustamante:2009us}, and thus can be written as\n\\begin{equation}\n\tW = \\frac{1}{2}m^{ij}\\phi_i \\phi_j + \\frac{1}{6}y^{ijk}\\phi_i \\phi_j \\phi_k,\n\t\\label{eq:wess_zumino_potential}\n\\end{equation}\nwhere $y^{ij}$ are the Yukawa couplings between the scalar and the two fermions, thus containing all non-gauge interactions. The term quadratic in the fields contains the fermion mass matrix $m^{ij}$, which is equal to the mass matrix of the scalar bosons due to supersymmetry, as will be shown below. Requiring $\\Lagr_\\mathrm{int}$ to be invariant under supersymmetry transformations further defines the potential $V$. The equations of motion of the auxiliary fields $F$ can be written as\n\\begin{equation}\n\tF_i = -\\frac{\\uppartial W(\\phi)}{\\uppartial \\phi^i} = - W^*_i, \\qquad F^{*i} = - \\frac{\\uppartial W(\\phi)}{\\uppartial \\phi_i} = - W^i,\n\t\\label{eq:wess_zumino_F}\n\\end{equation} \nwhich thus yields for the potential $V = W^*_iW^i = F_iF^{*i}$, allowing to write the Lagrangian without explicitly introducing the auxiliary fields. The full Lagrangian of the Wess-Zumino model, with general chiral interactions between the scalar and fermion fields in the chiral supermultiplets~\\cite{Bustamante:2009us}, is then given by\n\\begin{equation}\n\t\\Lagr = -\\uppartial^\\mu\\phi^{*i}\\uppartial_\\mu\\phi_i - i\\psi^{\\dagger i}\\bar{\\sigma}^\\mu\\uppartial_\\mu\\psi_i - \\frac{1}{2} m^{ij}\\psi_i \\psi_j - \\frac{1}{2} m_{ij}^* \\psi^{\\dagger i} \\psi^{\\dagger j} - \\frac{1}{2} y^{ijk} \\phi_i \\psi_j \\psi_k - \\frac{1}{2} y^*_{ijk} \\phi^{*i} \\psi^{\\dagger j} \\psi^{\\dagger k} - V(\\phi,\\phi^*),\n\t\\label{eq:wess_zumino_lagrangian}\n\\end{equation}\nobtained by adding the interaction term $\\Lagr_\\mathrm{int}$ from~\\cref{eq:wess_zumino_int} to the free Lagrangian in~\\cref{eq:wess_zumino_free} and inserting the expression for the superpotential from~\\cref{eq:wess_zumino_potential} and the auxiliary fields from~\\cref{eq:wess_zumino_F}.\n\nThe Lagrangian in \\cref{eq:wess_zumino_lagrangian} immediately reveals that, as expected by supersymmetry, the masses of the fermions and bosons in the same supermultiplet are identical. In order to incorporate gauge supermultiplets and consider the interactions between fermions and gauge bosons observed in the SM, the usual minimal coupling rule has to be applied, replacing $\\uppartial_\\mu$ with $\\codiff_\\mu$. This leads to equations of motion for the auxiliary fields,\n\\begin{equation}\n\tD^a = -g(\\phi^*T^a\\phi),\n\\end{equation}\nwhere $T^a$ are the generators of the gauge group and $g$ is the coupling constant~\\cite{Bustamante:2009us}. The potential then becomes\n\\begin{equation}\n\tV(\\phi,\\phi^*) = F^{*i}F_i + \\frac{1}{2} \\sum_a{D^aD^a} = W^*_iW^i + \\frac{1}{2}\\sum_a{g^2_a(\\phi^*T^a\\phi)^2} ,\n\\end{equation}\nwhere $a$ runs over the gauge groups that generally have differing gauge couplings~\\cite{Bustamante:2009us}.\n\n\n \n\\subsection{The Minimal Supersymmetric Standard Model}\\label{sec:mssm_intro}\n\n\\glsreset{mssm}\n\nThe \\gls{mssm} is the simplest $\\mathcal{N}=1$ supersymmetric extension of the \\gls{sm} in the sense that it introduces a minimal set of additional particles.\n\n\\subsubsection{Particle content and interactions}\\label{sec:mssm_particle_content}\n\nThe \\gls{mssm} arranges all \\gls{sm} particles in chiral (all the fermions and quarks) and gauge (all spin-1 bosons) supermultiplets. As supersymmetric partners have the same quantum numbers apart from spin, none of the \\gls{sm} particles can be superpartners of each other.\nThus, all supersymmetric partners have to be new, unseen particles. \\Cref{tab:particles_MSSM} summarises the names, notations and spins of all superpartners introduced in the \\gls{mssm}.\nThe naming convention is to prepend the names of the superpartners of fermions with an `s' (\\eg \\textit{selectron}, \\textit{stop}, ...) and append `-ino' to the names of the superpartners of the bosons (\\eg \\textit{Wino}, \\textit{Higgsino}, ...).\nSupersymmetric particles (\\textit{sparticles}) are generally denoted by adding a tilde to the symbol of \\gls{sm} particles (\\eg $\\tilde{e}$, $\\tilde{u}$, $\\tilde{g}$). \n\n\\begin{table}\n\t\\centering\n\t\\small\n\t\\setlength\\heavyrulewidth{0.2ex}\n\t\\caption{Particle content of the \\gls{mssm}. The spin refers to the spin of the superpartner. Adapted from~\\cite{Bustamante:2009us}.}\n\t\\begin{tabular} {l l c}\n\t\t\n\t\t\\toprule\n\t\tParticle & superpartner 0 & Spin \\\\ \n\t\t\\midrule \n\t\tquarks $q$ & squarks $\\tilde{q}$ & 0 \\\\\n\t\t$\\rightarrow$ top $t$ & stop $\\tilde{t}$ & \\\\\n\t\t$\\rightarrow$ bottom $t$ & sbottom $\\tilde{b}$ & \\\\\n\t\t$\\dots$ & & \\\\\n\t\tleptons $\\ell$ & sleptons $\\tilde{\\ell}$ & 0 \\\\\n\t\t$\\rightarrow$ electron $e$ & selectron $\\tilde{e}$ & \\\\\n\t\t$\\rightarrow$ muon $\\mu$ & smuon $\\tilde{\\mu}$ & \\\\\n\t\t$\\rightarrow$ tau $\\tau$ & stau $\\tilde{\\tau}$ & \\\\\n\t\t$\\rightarrow$ neutrinos $\\nu_\\ell$ & stop $\\tilde{\\nu}_\\ell$ & \\\\\n\t\t\\midrule\n\t\tgauge bosons & gauginos & 1/2 \\\\\n\t\t$\\rightarrow$ photon $\\gamma$ & photino $\\tilde{\\gamma}$ & \\\\\n\t\t$\\rightarrow$ boson $Z$ & Zino $\\tilde{Z}$ & \\\\\n\t\t$\\rightarrow$ boson $B$ & Bino $\\tilde{B}$ & \\\\\n\t\t$\\rightarrow$ boson $W$ & Wino $\\tilde{W}$ & \\\\\n\t\t$\\rightarrow$ gluon $g$ & gluino $\\tilde{g}$ & \\\\\n\t\t\\midrule\n\t\tHiggs bosons $H^{\\pm,0}_i$ & higgsinos $\\tilde{H}^{\\pm,0}_i$ & 1/2 \\\\\n\t\t\\bottomrule\n\t\\end{tabular}\\vspace{3mm}\n\t\\label{tab:particles_MSSM}   \n\\end{table}\n\nAn important detail to note is that right-handed and left-handed fermions get their own chiral supermultiplets and thus have distinct superpartners, as otherwise the preference of the weak interaction for left-handed particles would be violated. \nFor example, left-handed and right-handed quarks \\mbox{($q_\\mathrm{L}$, $q_\\mathrm{R}$)} get two different superpartners ($\\tilde{q}_\\mathrm{L}$, $\\tilde{q}_\\mathrm{R}$), denoted with subscript `L' and `R'.\nThe index here refers to the handiness of the SM particle as scalar particles have only one helicity state. Additionally, the superpartners of the left-handed and right-handed fermions will mix to form physical mass eigenstates.\n\nIt is also worth asking why the superpartners of SM particles are of lower spin in the first place, as \\eg spin-1 superpartners of the SM fermions could also have been considered. The introduction of spin-1 bosons would entail the introduction of new gauge interactions, rendering the \\gls{mssm} non-minimal~\\cite{Bustamante:2009us}. Furthermore, introducing superpartners with spin greater than 1 would make the resulting theory non-renormalisable~\\cite{Bustamante:2009us}.\n\nIn the \\gls{mssm}, two Higgs doublets are needed in order to give masses to the up-type and down-type quarks via Yukawa couplings. A single Higgs field $h$ cannot be used for this as it would require Yukawa terms including the complex conjugate $h^*$, which is forbidden as the superpotential, being a holomorphic function of the fields, cannot depend on the complex conjugates of the same fields~\\cite{Bustamante:2009us}. Additionally, the use of a single Higgs doublet would lead to gauge anomalies in the electroweak gauge symmetry~\\cite{PhysRevD.6.429}. Instead two complex Higgs doublets with hypercharge $Y = \\pm 1/2$ are used in the \\gls{mssm}. The two Higgs doublets can be written as\n\\begin{equation}\n\tH_u = \\begin{pmatrix}\n\t\tH^0_u \\\\\n\t\tH^-_u\n\t\\end{pmatrix}, \\qquad \\qquad\n\tH_d = \\begin{pmatrix}\n\t\tH^+_d \\\\\n\t\tH^0_d\n\t\\end{pmatrix}.\n\t\\label{eq:Higgs_doublets}\n\\end{equation}\n\nAs illustrated in \\cref{sec:susy_lagrangian} using the Wess--Zumino model, interactions are introduced using the superpotential. In the \\gls{mssm}, the superpotential reads\n\\begin{equation}\n\tW_\\mathrm{MSSM} = \\bar{u}\\makemebold{y_u}QH_u - \\bar{d}\\makemebold{y_d}QH_d - \\bar{e}\\makemebold{y_e}LH_d + \\mu H_uH_d,\n\t\\label{eq:mssm_superpotential}\n\\end{equation}\nwhere $Q$ and $L$ correspond to the supermultiplets containing the left-handed quarks and leptons as well as their superpartners, respectively. Likewise, $\\bar{u}$, $\\bar{d}$, $\\bar{e}$ correspond to the supermultiplets containing the right-handed up-type quarks, down-type quarks and leptons as well as their superpartners, respectively. The parameters $\\makemebold{y_u}$, $\\makemebold{y_d}$ and $\\makemebold{y_e}$ are the $3\\times 3$ Yukawa coupling matrices. Except for the third generation, the Yukawa couplings are known to be relatively small~\\cite{Martin:1997ns} and are thus not of direct interest for the phenomenology of the theory. Phenomenologically more interesting are the supersymmetric gauge interactions that dominate the production and decay process of superpartners in the \\gls{mssm}~\\cite{Martin:1997ns}. The superpotential in \\cref{eq:mssm_superpotential} illustrates again why two Higgs doublets are needed in the \\gls{mssm}, since terms like $\\bar{u}QH_d^*$ or $\\bar{e}LH_u^*$ are not allowed due to the holomorphism of the superpotential. The term $\\mu H_u H_d$ contains the \\textit{higgsino mass parameter} $\\mu$ and is the supersymmetric version of the Higgs mass term in the SM Lagrangian.\n\n\n\\subsubsection{Soft supersymmetry breaking}\\label{sec:susy_breaking}\n\nAs stated in \\cref{sec:susy_algebra}, all superpartners must have the same quantum numbers apart from their spin. They especially also should have the same masses. As such particles would have been discovered a long time ago, \\gls{susy} must be a broken symmetry. If broken \\gls{susy} is, however, still to provide a solution to the Hierarchy problem, \\ie cancel the quadratic divergencies in the loop corrections to the Higgs mass parameter, then the relations between the dimensionless couplings of the SM particles and their superpartners have to be maintained~\\cite{Martin:1997ns}. Hence, only symmetry breaking terms with positive mass dimension are allowed in the Lagrangian, especially also forbidding the presence of dimensionless SUSY-breaking couplings~\\cite{Martin:1997ns}. Such a breaking of \\gls{susy} is called \\textit{soft} breaking and can be written as\n\\begin{equation}\n\t\\Lagr = \\Lagr_\\mathrm{SUSY} + \\Lagr_\\mathrm{soft},\n\\end{equation}\nwhere $\\Lagr_\\mathrm{soft}$ contains all the symmetry breaking terms, whilst $\\Lagr_\\mathrm{SUSY}$ is the \\gls{susy} invariant Lagrangian with all the gauge and Yukawa interactions. In a softly broken SUSY, the loop corrections to the Higgs mass parameter depend quadratically on the largest mass scale associated with the soft terms ($m_\\mathrm{soft}$). As the fine-tuning problem reappears if $m_\\mathrm{soft}$ becomes too large, superpartners with masses not too far above the TeV scale are generally assumed~\\cite{Martin:1997ns}.\n\nA total of 105 new parameters with no counterpart in the SM are introduced through $\\Lagr_\\mathrm{soft}$~\\cite{Martin:1997ns,Dimopoulos:1995ju}:\n\\begin{itemize}\n\t\\item Wino, bino and gluino mass parameters $M_1$, $M_2$ and $M_3$.\n\t\\item Trilinear scalar couplings, parametrised by $3\\times 3$ matrices in generation space $\\makemebold{a_u}$, $\\makemebold{a_d}$, $\\makemebold{a_e}$, representing Higgs-squark-squark and Higgs-slepton-slepton interactions.\n\t\\item Hermitian $3\\times 3$ matrices in generation space \\boldmath $m_Q^2$, $m^2_{\\bar{u}}$, $m^2_{\\bar{d}}$, $m^2_L$, $m^2_{\\bar{e}}$ \\unboldmath that represent the sfermion masses.\n\t\\item \\gls{susy} breaking parameters contributing to the Higgs potential $m^2_{H_u}$, $m^2_{H_d}$ and $b$.\n\\end{itemize}\n\nThe sfermion mass matrices and the trilinear scalar couplings may introduce additional flavour mixing and CP violation, both of which are heavily constrained by experimental results. Flavour mixing in the lepton sector is for example constrained by an upper limit on \\mbox{$\\mathrm{BR}(\\mu\\rightarrow e\\gamma)<\\SI{4.2e-12}{}$} \\cite{Mori:2016vwi}. Bounds on additional CP violation as well as squark mixing terms come from measurements of the electron and neutron electric moments and neutral meson systems~\\cite{pdg2020}. Formally, in order to avoid these terms, \\gls{susy} breaking can be assumed to be \\textit{flavour-blind}, meaning that the mass matrices are approximately diagonal. The large Yukawa couplings for the third generation squarks and sfermions can then be achieved by assuming that the trilinear scalar couplings are proportional to the corresponding Yukawa coupling matrix~\\cite{Martin:1997ns}.\n\nAs most of the parameters in the \\gls{mssm} are related to soft \\gls{susy} breaking, it is not surprising that the phenomenology of the \\gls{mssm} strongly depends on the exact breaking mechanism. The breaking is usually assumed to happen in a \\textit{hidden sector} and the effects of the breaking are then typically mediated by messenger fields from the hidden sector to the \\textit{visible sector} containing all the particles of the \\gls{mssm}. Since the hidden sector is assumed to be only weakly or indirectly coupled to the visible sector, the phenomenology mostly depends on the mechanism mediating the breaking. The two most popular mechanisms are \\textit{gravity-mediated} and \\textit{gauge-mediated} \\gls{susy} breaking.\n\nMediating \\gls{susy} breaking through gravity is an attractive approach, since all particles share gravitational interactions. This makes it easy to imagine gravitational effects to be the only connection between the hidden and the visible sectors. In such models, \\gls{susy} breaking is mediated through effects of gravitational strength, suppressed by inverse powers of the Planck mass~\\cite{pdg2020}. The mass of the gravitino---the superpartner of the hypothetical mediator particle of gravity, called \\textit{graviton}---is typically of electroweak scale~\\cite{Nilles:1983ge,LAHANAS19871}. Due to its couplings of gravitational strengths, it usually does not play a role in collider physics~\\cite{pdg2020}.\n\nIn gauge-mediated \\gls{susy} breaking (GMSB), additional messenger fields sharing gauge interactions with the \\gls{mssm} fields are transmitting the breaking from the hidden to the visible sector. In such models, the gravitino is typically the \\gls{lsp}, as its mass ranges from a few $\\SI{}{\\eV}$ to a few $\\SI{}{\\GeV}$, making it a candidate for \\gls{dm}~\\cite{Feng:2003xh}.\n\n\\subsubsection{Mass spectrum}\n\nElectroweak symmetry breaking in the \\gls{mssm} is generalised to the two Higgs doublets introduced in \\cref{eq:Higgs_doublets}. In total, the two doublets have eight degrees of freedom, three of which are used to give masses to the $W^\\pm$ and $Z$ bosons during the breaking of $SU(2)_\\mathrm{L}\\otimes U(1)_Y$ to $U(1)_\\mathrm{em}$ (see \\cref{sec:ssb}). Thus, five physical Higgs bosons appear in the \\gls{mssm}; two neutral Higgs bosons even under CP transformation, called $h^0$ and $H^0$, one neutral Higgs boson odd under CP transformation, called $A^0$, and finally two charged Higgs bosons, called $H^\\pm$. The two Higgs doublets $H_u$ and $H_d$ each get a \\gls{vev} ($v_u$ and $v_d$, respectively) that are connected to the \\gls{vev} $v$ of the SM Higgs field by\n\\begin{equation}\n\tv_u^2 + v_d^2 = v^2.\n\\end{equation}\nPhenomenologically, the ratio of the two \\glspl{vev} is usually considered, conventionally called $\\tan{\\beta}$,\n\\begin{equation}\n\t\\tan{\\beta} = \\frac{v_u}{v_d}.\n\\end{equation}\n\nDue to electroweak symmetry breaking, the gauginos and higgsinos are not mass eigenstates but mix to form \\textit{electroweakinos}: \n\\begin{itemize}\n\t\\item The two charged higgsinos mix with the two charged winos to form two charged mass eigenstates $\\tilde{\\chi}_1^\\pm$, $\\tilde{\\chi}_2^\\pm$, called \\textit{charginos}.\n\t\\item The remaining neutral higgsinos mix with the bino and neutral wino to form four neutral mass eigenstates $\\tilde{\\chi}_1^0$, $\\tilde{\\chi}_2^0$, $\\tilde{\\chi}_3^0$, $\\tilde{\\chi}_4^0$, called \\textit{neutralinos}.\n\\end{itemize}\nBoth charginos and neutralinos are by convention labeled in ascending mass order. As the exact diagonalised forms of their mass mixing matrices are, in general, relatively complicated~\\cite{Choi:2001ww}, they are typically evaluated in limits where one component dominates. Neutralinos with a dominant wino, bino or higgsino component will be called wino-, bino- or higgsino-like, respectively, in the following. Likewise, charginos will be called wino- or higgsino-like, if the respective component dominates.\n%Both charginos and neutralinos are by convention labeled in ascending mass order. In the gauge-eigenstate basis $\\psi^0 = (\\tilde{B},\\tilde{W}^0,\\tilde{H}^0_d,\\tilde{H}^0_u)$, the neutralino mixing matrix reads~\\cite{Martin:1997ns}\n%\\begin{equation}\n%\t\\makemebold{M}_{\\tilde{\\chi}}^0 = \t\\begin{pmatrix}\n%\t\tM_1 & 0 & -g_1v_d/\\sqrt{2} & g_1 v_u/\\sqrt{2} \\\\\n%\t\t0 & M_2 & g_2 v_d/\\sqrt{2} & - g_2 v_u/\\sqrt{2} \\\\\n%\t\t- g_1 v_d/\\sqrt{2} & g_2 v_d/\\sqrt{2} & 0 & -\\mu \\\\\n%\t\tg_1 v_u/\\sqrt{2} & -g_2 v_u/\\sqrt{2} & -\\mu & 0\n%\t\\end{pmatrix},\n%\t\\label{eq:neutralino_mixing}\n%\\end{equation}\n%where $M_1$ and $M_2$ stem directly from the soft SUSY breaking terms while the $-\\mu$ terms are the higgsino mass terms. Entries with $g_1$ and $g_2$ come from Higgs-higgsino-gaugino couplings. The neutralino mixing matrix can be diagonalized to obtain the neutralino masses, which can be expressed in terms of the parameters $M_1$, $M_2$, $\\mu$ and $\\tan{\\beta}$~\\cite{Martin:1997ns}. As the exact forms of the mass expressions are relatively complicated~\\cite{pdg2020}, they are typically evaluated in limits where one of the mass parameters is significantly smaller than the other two. This is possible because $M_1$ and $M_2$ can be chosen to be real and positive through an appropriate phase redefinition of $\\tilde{B}$ and $\\tilde{W}$\\footnote{This makes the phase of $\\mu$ in that convention a physical parameter that can no longer be rotated away through basis rotation.}. If neutralinos are dominated by the wino, bino or higgsino component, they are called wino-, bino- or higgsino-like, respectively, in the following.\n%\n%The chargino mixing matrix can be written in a similar fashion. In the gauge-eigenstate $\\psi^\\pm = (\\tilde{W}^\\pm , \\tilde{H}^+_u, \\tilde{W}^-, \\tilde{H}^-_d)$, it can be written as\n%\\begin{equation}\n%\t\\makemebold{M}_{\\tilde{\\chi}^\\pm} = \\begin{pmatrix}\n%\t\t\\mathbb{0}_2 & \\makemebold{X}^T \\\\\n%\t\t\\makemebold{X} & \\mathbb{0}_2\n%\t\\end{pmatrix}\n%\t\\qquad \\textrm{with} \\quad \\makemebold{X} = \\begin{pmatrix}\n%\t\tM_2 & g_2 v_u\\\\\n%\t\tg_2 v_d & \\mu\n%\t\\end{pmatrix}.\n%\\end{equation}\n%The masses of the charginos are then the eigenvalues of the doubly degenerate $4\\times 4$ matrix $\\makemebold{M}^{\\dagger}_{\\tilde{\\chi}^\\pm}\\makemebold{M}_{\\tilde{\\chi}^\\pm}$ and can be expressed in terms of $M_2$, $\\mu$ and $\\sin{2\\beta}$~\\cite{Martin:1997ns}. \n\nSquarks and sleptons also mix, respectively. As in principle any scalars with the same electric charge, colour charge and R-parity (see~\\cref{sec:rparity}) can mix with each other, the mass eigenstates of the sleptons and squarks should a priori be obtained through diagonalisation of three $6\\times 6$ mixing matrices (one for up-type squarks, one for down-type squarks and one for charged sleptons) and one $3\\times 3$ matrix (for sneutrinos). The assumption of flavour-blind soft \\gls{susy} breaking terms leads to most of the mixing angles being very small. As opposed to the first and second generation, the third generation sfermions have relatively large Yukawa couplings, therefore the superpartners of the left- and right-handed fermions mix to mass eigenstates $(\\tilde{t}_1,\\tilde{t}_2)$, $(\\tilde{b}_1,\\tilde{b}_2)$, $(\\tilde{\\tau}_1,\\tilde{\\tau}_2)$, again labeled in ascending mass order. The first and second generation sfermions, on the other hand, having very small Yukawa couplings, end up in nearly mass-degenerate, unmixed pairs.\n\nThe gluino, being the only colour octet fermion of the unbroken $SU(3)_C$ gauge group, cannot mix with another fermion and is thus a mass eigenstate with mass $m_{\\tilde{g}} = \\vert M_3 \\vert$ at tree level~\\cite{Martin:1997ns,baer_tata_2006}.\n\n\\subsubsection{R-parity}\\label{sec:rparity}\n\nThe superpotential of the \\gls{mssm} in principle allows additional gauge-invariant terms that are holomorphic in the chiral superfields but violate either lepton number (L) or baryon number (B). However, L- or B-violating processes have not been observed.\nAlso, the L- and B-violating terms would cause a finite lifetime of the proton by allowing for it to decay, \\eg, via $p\\rightarrow e^+ \\pi^0$, a process that is heavily constrained to have a lifetime longer than $1.6\\times 10^{34}$ years~\\cite{Miura:2016krn}, as found by the Super-Kamiokande experiment.\n\nIn order to avoid these terms, a new symmetry, called \\textit{R-parity}, is introduced. R-parity is a multiplicatively conserved quantum number defined to be\n\\begin{equation}\n\tP_\\mathrm{R} = (-1)^{3(B-L)+2s},\n\t\\label{eq:rparity}\n\\end{equation}\nwhere $s$ is the spin of the particle. Given this definition, all SM particles and the Higgs bosons have even R-parity ($P_\\mathrm{R} = +1$) while all superpartners have odd R-parity ($P_\\mathrm{R} = -1$). Assuming R-parity to be exactly conserved at each vertex in the \\gls{mssm} leads to a number of interesting phenomenological consequences:\n\\begin{itemize}\n\t\\item Sparticles are always produced in pairs.\n\t\\item Heavier sparticles decay into lighter ones.\n\t\\item The number of sparticles at each vertex must be even.\n\t\\item The \\gls{lsp} must be stable as it cannot decay any further without violating R-parity.\t\n\\end{itemize}\nThe nature of the \\gls{lsp} can be further constrained by cosmological observations~\\cite{Ellis:1998eh}. If it were electrically charged or coupled to the strong interaction, it would have dissipated its energy and mixed with ordinary matter in the galactic disks, where it would have formed anomalous heavy isotopes.\nUpper limits on such supersymmetric relics~\\cite{Ellis:1983ew} heavily favour an electrically neutral and at most weakly interacting \\gls{lsp}. This excludes in particular the gluino as an \\gls{lsp}.\nAnother possible \\gls{lsp}, the sneutrino, is ruled out by \\gls{lep} and direct searches~\\cite{PhysRevLett.61.510,PhysRevD.48.5505,Akerib:2005zy}. Gauge-mediated supersymmetric theories often predict a light gravitino \\gls{lsp} with a mass ranging from a few $\\SI{}{\\eV}$ to a few $\\SI{}{\\GeV}$.\nAnother promising option, and the one considered in the following, is a neutralino \\gls{lsp}. In large portions of the \\gls{mssm} parameter space, a neutralino \\gls{lsp} produces a \\gls{dm} relic density that is compatible with the \\gls{dm} relic density measured by Planck~\\cite{Aghanim:2018eyx,Ellis:1983ew}.\n\nAlthough both R-parity conserving and R-parity violating models exist and are searched for in ATLAS, for the phenomenological reasons explained above, only R-parity conserving \\gls{susy} models with neutralino \\glspl{lsp} are considered in the following.\n\n\\begin{table}\n\t\\centering\n\t\\setlength\\heavyrulewidth{0.2ex}\n\t\\small\n\t\\caption{Parameters of the \\gls{pmssm}.}\n\t\\begin{tabular} {l l}\n\t\\toprule\n\t\tParameter & Meaning \\\\ \n\t\\midrule\n\t$\\tan{\\beta}$ & ratio of the Higgs doublet \\glspl{vev} \\\\\n\t$M_A$ & mass of the CP-odd Higgs boson \\\\\n\t$\\mu$ & Higgs-higgsino mass parameter \\\\\n\t$M_1$, $M_2$, $M_3$ & wino, bino and gluino mass parameters \\\\\n\t$m_{\\tilde{q}}$, $m_{\\tilde{u}_\\mathrm{R}}$, $m_{\\tilde{d}_\\mathrm{R}}$, $m_{\\tilde{\\ell}}$, $m_{\\tilde{e}_\\mathrm{R}}$ & first and second generation sfermion masses \\\\\n\t$m_{\\tilde{Q}}$, $m_{\\tilde{t}_\\mathrm{R}}$, $m_{\\tilde{b}_\\mathrm{R}}$, $m_{\\tilde{L}}$, $m_{\\tilde{\\tau}_\\mathrm{R}}$ & third generation sfermion masses \\\\\n\t$A_t$, $A_b$, $A_\\tau$ & third generation trilinear couplings \\\\\n\t\\bottomrule\t\t\t\t\t\n\t\\end{tabular}\\vspace{3mm}\n\t\\label{tab:parameters_pmssm}   \n\\end{table}\n\n\\subsection{The phenomenological MSSM}\\label{sec:theory_pmssm}\n\nIn addition to the 19 parameters of the SM, the \\gls{mssm} adds a total of 105 additional parameters, too much to allow for a full exploration of the \\gls{mssm} in experimental analyses. However, as discussed in \\cref{sec:susy_breaking}, not all values of the 105 additional parameters lead to phenomenologically viable models. By requiring a set of phenomenological constraints, the 105 free parameters can be reduced to only 19 free parameters, spanning a model space called the \\gls{pmssm}~\\cite{Djouadi:2002ze,Berger_2009}. The free parameters in the \\gls{pmssm} are listed in \\cref{tab:parameters_pmssm}.\n\nThe reduction of free parameters is obtained by applying the following constraints on the \\gls{mssm}:\n\\begin{itemize}\n\t\\item No new source of CP violation, as discussed in \\cref{sec:susy_breaking}, achieved by assuming all soft breaking parameters to be real.\n\t\\item Minimal flavour violation, meaning that \\glspl{fcnc}, heavily constrained by experiment, are not allowed and the flavour physics is governed by the \\gls{ckm} matrix.\n\t\\item First and second sfermion generations are mass-degenerate.\n%\\footnote{This is motivated by \\eg Kaon mixing measurements and holds unless first and second generation squarks are significantly heavier than $\\mathcal{O}(\\SI{}{\\TeV})$.}.\n\t\\item The trilinear couplings and Yukawa couplings are negligible for the first and second sfermion generations.\n\\end{itemize}\nThe \\gls{pmssm} does not make any assumptions on the physics above the TeV scale, and therefore does not assume a specific \\gls{susy} breaking mechanism. With its 19 free parameters, and the typical complexity of a search for SUSY, the \\gls{pmssm} is still computationally extremely challenging to probe. Using appropriate approximations, the computational complexity can be simplified enough for exhaustive scans and comparisons to experimental data to become possible. Two such approximations are discussed in \\cref{ch:preservation,ch:simplify}, respectively, and applied on the \\gls{pmssm} in \\cref{ch:pmssm}.\n\n\\subsection{Simplified models}\\label{sec:simplified_models}\n\n%\\begin{figure}\n%\\floatbox[{\\capbeside\\thisfloatsetup{capbesideposition={right,center},capbesidewidth=0.45\\textwidth}}]{figure}[\\FBwidth]\n%{\\caption{Signal grids composed of discrete signal points. Each point represents a different signal model with a unique set of model parameters, here the $\\charg/\\neutr$ and $\\lsp$ masses.}\\label{fig:signalgrid}}\n%{\\includegraphics[width=0.5\\textwidth]{signalgrid}}\n%\\end{figure}\n\nIn searches for \\gls{bsm} physics at the \\gls{lhc}, it is common to use simplified models~\\cite{SimplifiedModels1:2008ag,SimplifiedModels2:2011wf,Alves:2011sq} as a way of reducing the available parameter space to a manageable level.\n%Simplified models do not aim to represent complete supersymmetric models but are mostly defined by the empirical objects and kinematic variables used in the searches, typically allowing only a small number of sparticles to be involved in the decay chain (usually only two or three).\nSimplified models do not aim to represent complete supersymmetric models but are mostly defined by a single (or a few selected) decay chain(s) allowing only a small number of participating sparticles, usually only two or three.\nOther sparticles are decoupled by setting their masses to be kinematically inaccessible at current collider experiments. The decay chains of the participating sparticles are determined by fixed branching ratios, often set to be 100\\%.\nExperimental bounds from non-observation of a given model are then typically presented in function of the physical masses of the sparticles involved in the decay chain.\nThe model space spanned by the free parameters of the simplified model is typically called a \\textit{signal grid}, as each set of distinct mass parameter values, called \\textit{signal point}, occupies a single discrete point in this space. \\Cref{fig:signalgrid} illustrates the signal grid used in \\cref{part:simplified_model_analysis} of this thesis. The exact details of the signal grid are further discussed in \\cref{sec:models_used}.\n \nSimplified models have the inherent advantage that they circumvent the issue of having to search for \\gls{susy} in a vast parameter space where many of the parameters may only have small effects on observables. Their interpretation in terms of limits on individual \\gls{susy} production and decay topologies in function of sparticle masses is straightforward and very convenient.\nThe hope is, that simplified models are a reasonable approximation of sizeable regions of parameter space of the more complete model they are embedded in~\\cite{pdg2020}. The obvious downside is, however, that the limits obtained in simplified models are not automatically a good approximation of the true underlying constraint on the respective model parameter when interpreted in more complete \\gls{susy} models.\nOften, the constraints set on sparticle masses in simplified models, significantly overestimate the true constraints obtained in more complex \\gls{susy} spectra, especially when the usually assumed 100\\% branching fractions are no longer realised in more complete models (see \\eg~\\cite{Ambrogi:2017lov,Buchmueller:2013exa}).\n\n\\begin{figure}\n\\floatbox[{\\capbeside\\thisfloatsetup{capbesideposition={right,center},capbesidewidth=0.45\\textwidth}}]{figure}[\\FBwidth]\n{\\caption{Cross sections of different \\gls{susy} production processes at $\\sqrt{s}=\\SI{13}{\\TeV}$ in $pp$ collisions. Cross sections for pair production of electroweakinos are significantly smaller than, \\eg, those for pair production of gluinos. The shaded bands correspond to the theory uncertainty of each cross section. Cross sections taken for coloured and electroweak sector taken from \\references\\cite{Beenakker:2016lwe,Beneke:2009ye} and \\references\\cite{Fiaschi:2018hgm,Fuks:2012qx,Fiaschi:2018xdm}, respectively.}\\label{fig:SUSY_xsecs}}\n{\\includegraphics[width=0.5\\textwidth]{SUSY_xsecs}}\n\\end{figure}\n\nOne way of circumventing these issues, while sticking to the simplified model approach, is to ensure that the limits obtained in different simplified models involving different production and decay mechanisms are combined into limits representing more complex \\gls{susy} spectra.\nIn such an approach, the simplified model limits can be seen as building blocks for more realistic \\gls{susy} models that include many different production processes and decay modes.\nAnother possibility is to perform reinterpretations of \\gls{susy} searches---optimised for one ore more such simplified models---in more complete (and high-dimensional) \\gls{susy} model spaces, like \\eg, in the \\gls{pmssm}. This cannot only demonstrate the sensitivity of existing \\gls{susy} searches beyond simplified models, but also potentially identify blind spots and model regions not covered by current searches.\nIn addition, connections to (in)direct \\gls{dm} searches and various \\gls{sm} measurements can be explored this way. Recent efforts in this direction include, \\eg, \\references\\cite{Ambrogi:2017lov, Aaboud:2016wna, pMSSM-scan-run1:2015baa}. As will be discussed in \\cref{part:reinterpretation} of this thesis, efforts reinterpreting ATLAS searches for \\gls{susy} in the \\gls{pmssm} are currently ongoing. In \\cref{ch:pmssm}, a reinterpretation of the search for electroweakinos presented herein using a set of \\gls{pmssm} models, is discussed.\n\n\n\\section{Search for electroweakinos}\n\n\\begin{figure}\n\t\\centering\n\t\\begin{subfigure}[b]{0.33\\linewidth}\n\t\t\\centering\\includegraphics[width=.9\\textwidth]{electroweakino_production_1}\n\t\t\\caption{\\label{fig:electroweakino_production_1}}\n\t\\end{subfigure}%\n\t\\begin{subfigure}[b]{0.33\\linewidth}\n\t\t\\centering\\includegraphics[width=.9\\textwidth]{electroweakino_production_2}\n\t\t\\caption{\\label{fig:electroweakino_production_2}}\n\t\\end{subfigure}%\n\t\\begin{subfigure}[b]{0.33\\linewidth}\n\t\t\\centering\\includegraphics[width=.9\\textwidth]{electroweakino_production_3}\n\t\t\\caption{\\label{fig:electroweakino_production_3}}\n\t\\end{subfigure}\t\n\t\\caption{Dominant diagrams for production of electroweakino pairs at the Large Hadron Collider. Adapted from \\reference\\cite{Martin:1997ns}.}\\label{fig:electroweakino_production}\n\\end{figure}\n\nWhile both the ATLAS experiment~\\cite{ATL-PHYS-PUB-2021-007} and CMS experiment~\\cite{CMSsummary} at the \\gls{lhc} at CERN set strong limits on the presence of gluinos and squarks at the TeV scale, the limits on electroweakinos are mostly still below $\\SI{1}{\\TeV}$. \nThe reason for the relatively low limits on electroweakinos are the low cross-sections of electroweakino production, compared to those of squark and gluino production.\nAs can be seen in \\cref{fig:SUSY_xsecs}, the cross sections for $\\charg\\neutr$ pair production (the main production process considered in the following) is more than two orders of magnitude smaller than that for gluino pair production.  \n\nApart from the electroweakino mass limits set by the current collider experiments, some additional limits from the LEP experiments are still relevant in some corners of the phase space. Combining the results from all four LEP experiments leads to a general lower chargino mass limit of $\\SI{103.5}{\\GeV}$, except for scenarios with a low sneutrino mass~\\cite{lep_susy_results}. For small mass splittings between the chargino and the \\gls{lsp}, the lower limit is a little weaker, with dedicated searches excluding charginos with $m(\\charg) < \\SI{91.9}{\\GeV}$~\\cite{lep_susy_results}. For mass splittings larger than $\\SI{1.5}{\\GeV}$ and up to $\\SI{50}{\\GeV}$, the \\gls{lep} chargino limits have recently been superseded by a dedicated ATLAS search for compressed \\gls{susy} scenarios~\\cite{SUSY-2018-16}, excluding chargino masses up to $\\SI{240}{\\GeV}$ for a mass splitting of $\\SI{7}{\\GeV}$. For the neutralino, a lower limit on the lightest neutralino mass comes from limits on the invisible width of the $Z$ boson, excluding $m(\\lsp) < \\SI{45.5}{\\GeV}$, depending on the $Z$--neutralino coupling~\\cite{pdg2020}.\n\n\\subsection{Production of electroweakinos at the Large Hadron Collider}\n\nIf gluinos and squarks are heavier than a few TeV, \\ie too heavy to be within reach of the \\gls{lhc}, the direct production of electroweakinos might be the dominant production mode of SUSY. At hadron colliders, electroweakinos can be pair-produced directly via electroweak processes. The direct production of electroweakino pairs dominantly happens through electroweak gauge bosons from \\textit{s}-channel $q\\bar{q}$ annihilation, as shown in \\cref{fig:electroweakino_production}. Contributions from \\textit{t}-channels via squark exchange are typically of less importance~\\cite{Martin:1997ns}.\n\n\n\\subsection{Models used within this work}\\label{sec:models_used}\n\n%\\begin{figure}\n%\t\\centering\\includegraphics[width=.4\\textwidth]{C1N2-WhN1N1}\n%\t\\caption{Diagram for $\\charg\\neutr$ pair production with subsequent decays into $\\charg\\rightarrow W^\\pm\\lsp$ and $\\neutr\\rightarrow h\\lsp$.}\\label{fig:Wh_model}\n%\\end{figure}\n\n\\begin{figure}\n\t\\centering\n\t\\begin{subfigure}[b]{0.45\\linewidth}\n\t\t\\centering\\includegraphics[width=.85\\textwidth]{c1n2_wh}\t\t\n\t\t\\vspace{1em}\n\t\t\\caption{\\label{fig:Wh_model}}\n\t\\end{subfigure}\\hfill\n\t\\begin{subfigure}[b]{0.55\\linewidth}\n\t\t\\centering\\includegraphics[width=.9\\textwidth]{signalgrid}\n\t\t\\caption{\\label{fig:signalgrid}}\n\t\\end{subfigure}\t\n\t\\caption{Simplified model used in this thesis. Fig.~\\subref{fig:Wh_model} shows a diagram for $\\charg\\neutr$ pair production with subsequent decays into $\\charg\\rightarrow W^\\pm\\lsp$ and $\\neutr\\rightarrow h\\lsp$. Fig.~\\subref{fig:signalgrid} shows the signal grid used. Each discrete point represents a different signal model with a unique set of $\\charg$/$\\neutr$ and $\\lsp$ mass parameters.}\\label{fig:models_used}\n\\end{figure}\n\n%\\begin{figure}\n%\\floatbox[{\\capbeside\\thisfloatsetup{capbesideposition={right,center},capbesidewidth=0.4\\textwidth}}]{figure}[\\FBwidth]\n%{\\caption{Diagram for $\\charg\\neutr$ pair production with subsequent decays into $\\charg\\rightarrow W^\\pm\\lsp$ and $\\neutr\\rightarrow h\\lsp$.}\\label{fig:Wh_model}}\n%{\\includegraphics[width=0.5\\textwidth]{C1N2-WhN1N1}}\n%\\end{figure}\n\nIn \\gls{susy} scenarios where the sleptons and charged and pseudoscalar Higgs bosons are heavier than the charginos and neutralinos, a relatively pure wino lightest chargino decays predominantly through $\\charg\\rightarrow W^\\pm\\lsp$, while the next-to-lightest neutralino decays via $\\neutr\\rightarrow Z/h\\lsp$. If, in addition, the higgsinos are much heavier than the wino, and the mass splitting between the two lightest neutralinos is larger than the Higgs boson mass, the decay $\\neutr\\rightarrow h\\lsp$ can be the dominant decay mode of the $\\neutr$. In this case, both the $\\charg$ and $\\neutr$ are wino-like and nearly mass-degenerate.\n\nThe main model used in the following is a simplified model considering direct production of a $\\charg\\neutr$ pair, where the lightest chargino decays via $\\charg\\rightarrow W^\\pm\\lsp$ and the next-to-lightest neutralino decays via $\\neutr\\rightarrow h\\lsp$, each with 100\\% branching ratio.\nThe lightest chargino $\\charg$ and the next-to-lightest neutralino $\\neutr$ are assumed to be degenerate in mass and pure wino states, while the lightest neutralino $\\lsp$ is considered to be a pure bino \\gls{lsp}.\nThe mass parameter hierarchy for this model is thus \\mbox{$\\vert M_1 \\vert < \\vert M_2 \\vert \\ll \\vert\\mu\\vert$}. \n\nThe $\\charg$/$\\neutr$ and $\\lsp$ masses are free parameters that are systematically varied, creating a two-dimensional signal grid to be scanned and compared to data. \\Cref{fig:signalgrid} shows the two-dimensional signal grid used in \\cref{part:simplified_model_analysis} of this thesis. In the simplified model, the Higgs boson mass is set to $\\SI{125}{\\GeV}$ in accordance with the measured value~\\cite{HIGG-2012-27,CMS-HIG-12-028} and its branching ratios are the ones from the \\gls{sm}. A diagram for the simplified model considered is shown in \\cref{fig:Wh_model}.\n\nIn addition to the simplified model targeted by the \\gls{susy} search presented in the following, an additional class of models is considered in the second part of this work. These models are sampled directly from the \\gls{pmssm} parameter space and are used to reinterpret the aforementioned search for direct pair production of electroweakinos. The mass spectrum of a representative \\gls{pmssm} model point used is shown in \\cref{fig:slha_example}. Additional details on the sampling and phenomenology of the \\gls{pmssm} models are given in~\\cref{ch:pmssm}. \n\n\n\\begin{figure}\n\t\\centering\\includegraphics[width=.6\\textwidth]{thesis_plot_9127}\n\t\\caption{\nMass spectrum of an representative \\gls{pmssm} model. The branching fractions of the different decays are indicated through the width and and greyscale colour (black being 100\\%, white being 0\\%) of the arrows. Branching fractions smaller than 10\\% are suppressed for the sake of visibility. Figure generated using \\texttt{pyslha}~\\cite{pyslha:2013jua}.}\n\\label{fig:slha_example}\n\\end{figure}\n\n%\\begin{figure}\n%\\floatbox[{\\capbeside\\thisfloatsetup{capbesideposition={right,center},capbesidewidth=0.4\\textwidth}}]{figure}[\\FBwidth]\n%{\\caption{Diagram for $\\charg\\neutr$ pair production with subsequent decays into $\\charg\\rightarrow W^\\pm\\lsp$ and $\\neutr\\rightarrow h\\lsp$.}\\label{fig:slha}}\n%{\\includegraphics[width=0.5\\textwidth]{slha}}\n%\\end{figure}\n\n\n\n", "meta": {"hexsha": "aceeaa300e1f58518f91bad63185d2788743d67c", "size": 112688, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapter-theory/theory.tex", "max_stars_repo_name": "eschanet/phd-thesis", "max_stars_repo_head_hexsha": "607efdd3d48ec4def49ba41188c4453b04dd99d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapter-theory/theory.tex", "max_issues_repo_name": "eschanet/phd-thesis", "max_issues_repo_head_hexsha": "607efdd3d48ec4def49ba41188c4453b04dd99d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter-theory/theory.tex", "max_forks_repo_name": "eschanet/phd-thesis", "max_forks_repo_head_hexsha": "607efdd3d48ec4def49ba41188c4453b04dd99d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 103.0054844607, "max_line_length": 1417, "alphanum_fraction": 0.7616516399, "num_tokens": 32957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3102137585508639}}
{"text": "\\documentclass[a4paper]{article}\n\\usepackage{graphicx}\n\\usepackage[latin1]{inputenc}\n\\usepackage{amsmath}\n\\usepackage{fancyhdr}\n\\pagestyle{fancy}\n\\lhead{\\textsc{URIsolve App}}\n\\rhead{\\textsc{Node Voltage Method (Supernode approach)}}\n\\cfoot{www.isep.ipp.pt}\n\\lfoot{DEE - ISEP}\n\\rfoot {\\thepage}\n\\renewcommand{\\headrulewidth}{0.4pt}\n\\renewcommand{\\footrulewidth}{0.4pt}\n\n\\title{\n\\raisebox{-.2\\height}{\\includegraphics[height=1cm, keepaspectratio]{logo}} URIsolve APP \\\\\n\\newline\n\\textsc{Node Voltage Method} \\\\\n\\textsc{(Supernode approach)} \\\\\nStep by Step Solution \\\\\n\\vspace*{1\\baselineskip}\n}\n\n\\author{\n\\begin{tabular}[t]{c@{\\extracolsep{8em}}c}\nLino Sousa           & Mário Alves          \\\\\n1140355@isep.ipp.pt  & mjf@isep.ipp.pt      \\\\\n\t\t\t\t\t &                      \\\\\nAndré Rocha          & Francisco Pereira    \\\\\nanr@isep.ipp.pt      & fdp@isep.ipp.pt      \\\\\n\\end{tabular}\n}\n\n\\date{}\n\n\\begin{document}\n\n\\maketitle\n\\thispagestyle{empty}\n\n\\vspace{\\fill}\n\\begin{abstract}\n\\centering\nThis document provides a step by step solution for the submitted circuit, using the Node Voltage Method (NVM). If possible, it's implemented the Supernode approach to simplify the circuit analysis.\n\\end{abstract}\n\\vspace{\\fill}\n\n\\begin{center}\n\\today\n\\end{center}\n\n\\clearpage\n\\pagenumbering{arabic}\n\n\\newpage\n\n\\section{Circuit Image}\n\n\\begin{figure}[hbt]\n\\centering{\\includegraphics[height=12cm, keepaspectratio]{circuit}}\n\\caption{Circuit image}\n\\label{circuitimage}\n\\end{figure}\n\n\\section{Circuit Information}\n\n\\begin{table}[h!]\n\\centering\n\\begin{tabular}{clclclc}\n\\textbf{Frequency {[}F{]}} &  & \\textbf{Current Sources {[}I{]}} &  & \\textbf{Ammeters {[}A{]}} &  & \\textbf{Simulation {[}AC/DC{]}} \\\\\nF=1GHz                     &  & I=1                              &  & 15/15                     &  & AC\n\\end{tabular}\n\\end{table}\n\n\\section{Fundamental Variables}\n\n\\begin{table}[hbt!]\n\\centering\n\\begin{tabular}{clclclc}\n\\textbf{Branches {[}R{]}} &  & \\textbf{Nodes {[}N{]}} &  & \\textbf{Isolated Voltage Sources {[}T{]}} &  & \\textbf{Equations {[}E{]}} \\\\\nR=15                      &  & N=9                    &  & T=6                                       &  & E=N-T-1=2\n\\end{tabular}\n\\end{table}\n\n\\section{Supernodes}\n\n\\subsection{Floating}\n\n\\subsubsection{SNf1}\n\n\n\\paragraph{} Formed by Nodes: {A, B, E, J, H, D}\n\\par\n\n\\paragraph{} Equations:\n\n\\begin{gather*}\n\\begin{cases}\nV_{B} = \\mathrm{V_{A}}-5\\\\V_{E} = \\mathrm{V_{A}}-4\\\\V_{J} = \\mathrm{V_{A}}-13\\\\V_{H} = \\mathrm{V_{A}}-13\\cdot\\left( i+1\\right)\\\\V_{D} = \\mathrm{V_{A}}-4\\\\\n\\end{cases}\n\\end{gather*}\n\\par\n\n\\paragraph{} Steps:\n\n\\begin{gather*}\n\\begin{cases}V_{B} = \\mathrm{V_{A}}- V2\\\\[0.7em] V_{D} = \\mathrm{V_{A}}- V3\\\\[0.7em] V_{E} = \\mathrm{V_{A}}- V2+ V12\\\\[0.7em] V_{J} = \\mathrm{V_{A}}- V6- V2+ V12\\\\[0.7em] V_{H} = - V2- V10- V6+\\mathrm{V_{A}}+ V12\\end{cases}\n\\end{gather*}\n\n\\subsubsection{SNf2}\n\n\\paragraph{} Formed by Nodes: {T, M}\n\\par\n\n\\paragraph{} Equations:\n\n\\begin{gather*}\n\\begin{cases}\nV_{M} = \\mathrm{V_{T}}-1\n\\end{cases}\n\\end{gather*}\n\\par\n\n\\paragraph{} Steps:\n\n\\begin{gather*}\n\\begin{cases}V_{M} = \\mathrm{V_{T}}- V11\\end{cases}\n\\end{gather*}\n\\par\n\n\\subsection{Grounded}\nNot found in this circuit.\n\n\\newpage\n\\section{Circuit Currents}\n\n\\subsection{General information}\n\n\\begin{table}[ht]\n\\caption{List of the circuit currents and its properties/components}\n\\centering\n\\begin{tabular}{cccc}\n\\textbf{Reference} & \\textbf{Start Node} & \\textbf{End Node} & \\textbf{Components} \\\\ \\hline\nI01                & A                   & GND               & V1, L1, V7          \\\\\nI02                & GND                 & B                 & R6                  \\\\\nI03                & GND                 & H                 & C1, I3, R7          \\\\\nI04                & A                   & B                 & V2                  \\\\\nI05                & B                   & H                 & R4                  \\\\\nI06                & H                   & J                 & V10                 \\\\\nI07                & B                   & E                 & V12                 \\\\\nI08                & A                   & D                 & V3                  \\\\\nI09                & D                   & T                 & R1                  \\\\\nI10                & E                   & T                 & R10, C2             \\\\\nI11                & T                   & M                 & R2                  \\\\\nI12                & J                   & M                 & R3                  \\\\\nI13                & D                   & E                 & R9                  \\\\\nI14                & E                   & J                 & V6                  \\\\\nI15                & T                   & M                 & V11\n\\end{tabular}\n\\end{table}\n\n\\subsection{Equivalent Impedances and Voltages}\n\\paragraph{} Branch from A to gnd\n\\begin{gather*}\n\\begin{cases}\nVeqAgnd =  - V1 - V7 = -11\\;V\n\\end{cases}\n\\end{gather*}\n\\par\n\n\\paragraph{} Branch from D to T\n\\begin{gather*}\n\\begin{cases}\nVeqDT =  - V4 - V5 = -8\\;V\n\\end{cases}\n\\end{gather*}\n\\par\n\n\\paragraph{} Branch from E to T\n\\begin{gather*}\n\\begin{cases}\nZeqgndH = R10 + C2  = 50 - 159.155i\\;\\Omega\n\\end{cases}\n\\end{gather*}\n\\par\n\n\\paragraph{} Branch from gnd to H\n\\begin{gather*}\n\\begin{cases}\nZeqgndH = C1 + R7  = 5 - 159.155i\\;\\Omega\n\\end{cases}\n\\end{gather*}\n\\par\nnewpage\n\\subsection{Equations}\nEquations using the Kirchhoff Nodes Law (KNL)\n\n\\subsubsection{Node SNf1}\n\\begin{figure}[hbt]\n\\centering{\\includegraphics[height=4cm, keepaspectratio]{snf1}}\n\\caption{Node SNf1 currents}\n\\label{snf1currents}\n\\end{figure}\n\\begin{equation}\n  I01+I09+I10+I12=I02+I03\n\\end{equation}\n\n\\subsubsection{Node SNf2}\n\\begin{figure}[hbt]\n\\centering{\\includegraphics[height=4cm, keepaspectratio]{snf2}}\n\\caption{Node SNf2 currents}\n\n\\label{snf2currents}\n\\end{figure}\n\\begin{equation}\n  I09+I10+I12=0\n\\end{equation}\n\n\\newpage\n\\section{Equation System}\n\n\\paragraph{} Equations:\n\\begin{gather*}\n\\begin{cases}\\frac{\\left(\\mathrm{V_{A}}- V1- V7\\right)}{ XL1}+\\left(\\frac{\\mathrm{V_{B}}}{ R6}\\right)+\\frac{\\left( V_{D}- V4- V5-\\mathrm{V_{T}}\\right)}{ R1}+\\frac{\\left( V_{E}-\\mathrm{V_{T}}\\right)}{ XC2}+\\frac{\\left(\\mathrm{V_{J}}- V_{M}\\right)}{ R3}-0.001 = 0 \\\\[0.7em] \\frac{\\left( V_{D}- V4- V5-\\mathrm{V_{T}}\\right)}{ R1}+\\frac{\\left( V_{E}-\\mathrm{V_{T}}\\right)}{ XC2}+\\frac{\\left(\\mathrm{V_{J}}- V_{M}\\right)}{ R3} = 0\\end{cases}\n\\end{gather*}\n\\par\n\n\\paragraph{} Steps:\n\n%\\hfill\\begin{minipage}{\\dimexpr\\textwidth-1cm}\n\\begin{small}\\textbf{\\textit{Step 1:}}\\end{small}  Reorder current equations\n\\begin{gather*}\n\\begin{cases}I01 - I02 + I09 + I10 + I12 - I03 = 0 \\\\[0.7em] I09 + I10 + I12 = 0\\end{cases}\n\\end{gather*}\n\n\\begin{small}\\textbf{\\textit{Step 2:}}\\end{small}  Substitute the known currents\n\\begin{gather*}\n\\begin{cases}I01 - I02 + I09 + I10 + I12 - 0.001 = 0 \\\\[0.7em] I09 + I10 + I12 = 0\\end{cases}\n\\end{gather*}\n\n\\begin{small}\\textbf{\\textit{Step 3:}}\\end{small}  Compute the remaining currents using Ohm's Law\n\\begin{gather*}\n\\begin{cases}I01 = \\frac{\\left(\\mathrm{V_{A}}- V1 -  V7\\right)}{ XL1} \\\\[0.7em] I02 = -\\left(\\frac{\\mathrm{V_{B}}}{ R6}\\right) \\\\[0.7em] I09 = \\frac{\\left( V_{D}- V4 -  V5 - \\mathrm{V_{T}}\\right)}{ R1} \\\\[0.7em] I10 = \\frac{\\left( V_{E}-\\mathrm{V_{T}}\\right)}{ XC2} \\\\[0.7em] I12 = \\frac{\\left(\\mathrm{V_{J}}- V_{M}\\right)}{ R3}\\end{cases}\n\\end{gather*}\n\n\\begin{small}\\textbf{\\textit{Step 4:}}\\end{small}  Substitute each current by its equation\n\\begin{gather*}\n\\begin{cases}\\frac{\\left(\\mathrm{V_{A}}- V1- V7\\right)}{ XL1}+\\left(\\frac{\\mathrm{V_{B}}}{ R6}\\right)+\\frac{\\left( V_{D}- V4- V5-\\mathrm{V_{T}}\\right)}{ R1}+\\frac{\\left( V_{E}-\\mathrm{V_{T}}\\right)}{ XC2}+\\frac{\\left(\\mathrm{V_{J}}- V_{M}\\right)}{ R3}-0.001 = 0 \\\\[0.7em] \\frac{\\left( V_{D}- V4- V5-\\mathrm{V_{T}}\\right)}{ R1}+\\frac{\\left( V_{E}-\\mathrm{V_{T}}\\right)}{ XC2}+\\frac{\\left(\\mathrm{V_{J}}- V_{M}\\right)}{ R3} = 0\\end{cases}\n\\end{gather*}\n\n\\begin{small}\\textbf{\\textit{Step 5:}}\\end{small}  Replace the constants with their value\n\\begin{gather*}\n\\begin{cases}\\frac{\\mathrm{V_{A}}-11}{\\frac{ i\\cdot62830}{10000}}+\\frac{\\mathrm{V_{B}}}{12}+\\frac{-8-\\mathrm{V_{T}}+ V_{D}}{20}+\\frac{ V_{E}-\\mathrm{V_{T}}}{\\frac{ i\\cdot-7.9577\\cdot10^{+7}}{5\\cdot10^{+5}}}+\\frac{\\mathrm{V_{J}}- V_{M}}{30}+\\frac{-1}{1000} = 0 \\\\[0.7em] \\frac{-8-\\mathrm{V_{T}}+ V_{D}}{20}+\\frac{ V_{E}-\\mathrm{V_{T}}}{\\frac{ i\\cdot-7.9577\\cdot10^{+7}}{5\\cdot10^{+5}}}+\\frac{\\mathrm{V_{J}}- V_{M}}{30} = 0\\end{cases}\n\\end{gather*}\n\n\\begin{small}\\textbf{\\textit{Step 6:}}\\end{small} Set a reference for each floating supernode\n\\newline\nIn supernode SNf1 the node A was chosen as a reference. \\\\\nIn supernode SNf2 the node T was chosen as a reference.\n\n\\newline\n\\begin{footnotesize}\n\\textbf{\\textit{Notes:}} \\\\\nThe voltage of each node from a floating supernode must be expressed as a function of the reference node. \\\\\nIn the Supernodes section, you can confirm that node equations are already referenced to the chosen node. \\\\\nUse these expressions to perform the substitution in the equation system.\n\\end{footnotesize}\n\n\n%\\end{minipage}\n\\par\n\n\\newpage\n\n\\section{Results}\n\n\\subsection{Node Voltages}\n\\begin{gather*}\n\\begin{cases}V_{A} = 9.712-2.461i\\;V \\\\[0.7em] V_{T} = -2.243-1.861i\\;V \\\\[0.7em] V_{B} = 4.712-2.461i\\;V \\\\[0.7em] V_{D} = 5.712-2.461i\\;V \\\\[0.7em] V_{M} = -3.243-1.861i\\;V \\\\[0.7em] V_{E} = 5.712-2.461i\\;V \\\\[0.7em] V_{J} = -3.288-2.461i\\;V \\\\[0.7em] V_{H} = -3.288-15.461i\\;V\\end{cases}\n\\end{gather*}\n\n\\subsection{Circuit Currents}\n\\begin{gather*}\n\\begin{cases}I03 = 0.001\\;A\\end{cases}\n\\end{gather*}\n\\begin{footnotesize}\n\\textbf{\\textit{Note:}} \\\\\nCurrents were obtained by an existing current source in their branch.\n\\end{footnotesize}\n\n\\begin{gather*}\n\\begin{cases}I01 = \\frac{\\mathrm{V_{A}}-11}{\\frac{ i\\cdot1.256\\cdot10^{+7}}{2\\cdot10^{+6}}} \\\\[0.7em] I05 = \\frac{\\mathrm{V_{B}}-\\mathrm{V_{H}}}{10} \\\\[0.7em] I02 = \\frac{\\mathrm{V_{B}}\\cdot-1}{12} \\\\[0.7em] I13 = \\frac{ V_{D}- V_{E}}{25} \\\\[0.7em] I09 = \\frac{-8-\\mathrm{V_{T}}+ V_{D}}{20} \\\\[0.7em] I10 = \\frac{ V_{E}-\\mathrm{V_{T}}}{-\\left(159.154\\cdot i\\right)} \\\\[0.7em] I12 = \\frac{\\mathrm{V_{J}}- V_{M}}{30} \\\\[0.7em] I11 = \\frac{\\mathrm{V_{T}}- V_{M}}{20}\\end{cases} \\Leftrightarrow\\large \\begin{cases}I01 = -0.392\\;A \\\\[0.7em] I05 = 0.8\\;A \\\\[0.7em] I02 = -0.393\\;A \\\\[0.7em] I13 = 0\\;A \\\\[0.7em] I09 = -0.002\\;A \\\\[0.7em] I10 = 0.004\\;A \\\\[0.7em] I12 = -0.002\\;A \\\\[0.7em] I11 = 0.05\\;A\\end{cases}\n\\end{gather*}\n\\begin{footnotesize}\n\\textbf{\\textit{Note:}} \\\\\nCurrents were obtained by their Ohm's Law equation.\n\\end{footnotesize}\n\n\\begin{gather*}\n\\begin{cases}I08 = I13 + I09 \\\\[0.7em] I06 = I05 + I03 \\\\[0.7em] I15 = -I12 - I11 \\\\[0.7em] I04 = -I01 - I08 \\\\[0.7em] I07 = -I05 + I04 + I02 \\\\[0.7em] I14 = -I10 + I07 + I13\\end{cases} \\Leftrightarrow\\large \\begin{cases}I08 = -0.002\\;A \\\\[0.7em] I06 = 0.801\\;A \\\\[0.7em] I15 = -0.048\\;A \\\\[0.7em] I04 = 0.394\\;A \\\\[0.7em] I07 = -0.799\\;A \\\\[0.7em] I14 = -0.803\\;A\\end{cases}\n\\end{gather*}\n\\begin{footnotesize}\n\\textbf{\\textit{Note:}} \\\\\nCurrents were obtained by their KNL equation, since they belong to branches with isolated voltage sources.\n\\end{footnotesize}\n\n\\end{document}", "meta": {"hexsha": "3d363374adbb8c3b39d5b774b2957ed7302f3fd6", "size": 11123, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "sample.tex", "max_stars_repo_name": "txroot/latexprinter", "max_stars_repo_head_hexsha": "8d193b0e49a9633ed92f0fd6ffe2c3872e9e933c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sample.tex", "max_issues_repo_name": "txroot/latexprinter", "max_issues_repo_head_hexsha": "8d193b0e49a9633ed92f0fd6ffe2c3872e9e933c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sample.tex", "max_forks_repo_name": "txroot/latexprinter", "max_forks_repo_head_hexsha": "8d193b0e49a9633ed92f0fd6ffe2c3872e9e933c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2312703583, "max_line_length": 707, "alphanum_fraction": 0.5796098175, "num_tokens": 4262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5234203340678568, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.31021374973882004}}
{"text": "\\section{Dynamical Core for Cartesian C-grid} \\label{sec:atmos_dyn_cartesC}\n%------------------------------------------------------\nIn this section, the dynamical core for the Cartesian C-grid is described.\nThe Cartesian C-grid is employed in \\scalerm.\nIn the Cartesian C-grid, scalar quantities, such as density, thermodynamics variable and vapor, is defined at the cell center, while components of vector quantities, such as the momentums and fluxes, are defined at staggered point.\nSee the description document of \\scalerm for more details.\n\n\n\n\\subsection{Setting Integration Numerical Method}  %\\label{subsec:atmos_dyn_sover}\n%------------------------------------------------------\nThe numerical method for time integration in the dynamical process is specified in \\nmitem{ATMOS_DYN_TYPE} in \\namelist{PARAM_ATMOS} in the configuration file.\n\\editboxtwo{\n\\verb|&PARAM_ATMOS  | & \\\\\n\\verb| ATMOS_DYN_TYPE    = \"HEVE\", | & ; Choose from Table \\ref{tab:nml_dyn}.\\\\\n\\verb|/             | & \\\\\n}\n\nTime step depends on the sound speed in the case of using the explicit method, while it does not in the case of using the implicit method.\nIn most real atmospheric simulations, vertical grid spacing is much smaller than the horizontal ones.\nThus, fully explicit scheme, that is ``HEVE'', requires a quite small time step, which depends on vertical grid spacing and sound speed.\nTherefore, ``HEVI'' is often used for the real atmospheric simulations.\n\n\n\n\\begin{table}[bth]\n\\begin{center}\n  \\caption{Options of methods for time integration in dynamical process}\n  \\label{tab:nml_dyn}\n  \\begin{tabularx}{150mm}{llX} \\hline\n    \\rowcolor[gray]{0.9}  Scheme name & Description of scheme & Note\\\\ \\hline\n      \\verb|HEVE|  & Fully explicit method & \\\\\n      \\verb|HEVI|  & Horizontally explicit and vertically implicit methods & Recommended for real experiment\\\\\n    \\hline\n  \\end{tabularx}\n\\end{center}\n\\end{table}\n\n\n\\subsection{Setting Temporal and Spatial Schemes} \\label{subsec:atmos_dyn_scheme}\n%------------------------------------------------------\n\nThe temporal and spatial schemes are configured in \\namelist{PARAM_ATMOS_DYN}.\nAn example of setting, which is recommended for real atmospheric simulations,\nis shown below.\n\\editboxtwo{\n \\verb|&PARAM_ATMOS_DYN  | & \\\\\n \\verb|ATMOS_DYN_TINTEG_SHORT_TYPE          = RK4,|          & ; Choose from temporal schemes in Table \\ref{tab:nml_atm_dyn}\\\\\n \\verb|ATMOS_DYN_TINTEG_TRACER_TYPE         = RK3WS2002,|    & ; Choose from temporal schemes\\\\\n \\verb|ATMOS_DYN_FVM_FLUX_TYPE              = UD3,|          & ; Choose from temporal spatial schemes in Table \\ref{tab:nml_atm_dyn}\\\\\n \\verb|ATMOS_DYN_FVM_FLUX_TRACER_TYPE       = UD3KOREN1993,| & ; Choose from spatial schemes\\\\\n \\verb|ATMOS_DYN_FLAG_FCT_TRACER            = .false.,|      & ; Use FCT scheme (.true.) or not (.false.)\\\\\n \\verb|ATMOS_DYN_NUMERICAL_DIFF_COEF        = 0.D0, |        & \\\\\n \\verb|ATMOS_DYN_NUMERICAL_DIFF_COEF_TRACER = 0.D0, |        & \\\\\n \\verb|ATMOS_DYN_wdamp_height               = 15.D3,|        & ; height [m] of the bottom of sponge layer (for Rayleigh damping)\\\\\n\\verb|/             | & \\\\\n}\n\nThe other options for temporal and spatial schemes are shown in Table \\ref{tab:nml_atm_dyn}.\nNote that the time step should be set according to the used schemes in order to ensure numerical stability.\nAn criteria to determine the time step is described in Section \\ref{sec:timeintiv}.\n\n\n\\begin{table}[bth]\n\\begin{center}\n  \\caption{Setting temporal and spatial schemes}\n  \\label{tab:nml_atm_dyn}\n  \\begin{tabularx}{150mm}{lllX} \\hline\n    \\rowcolor[gray]{0.9} & \\multicolumn{1}{l}{Scheme name} & \\multicolumn{1}{l}{Description of scheme} & \\\\ \\hline\n    \\multicolumn{3}{l}{Temporal scheme} &  \\\\ \\hline\n    & \\multicolumn{1}{l}{\\verb|RK3|} & \\multicolumn{2}{l}{Heun-type 3 stage and 3rd-order Runge--Kutta scheme} \\\\\n    & \\multicolumn{1}{l}{\\verb|RK3WS2002|} & \\multicolumn{2}{l}{3 stage and generraly 2nd-order Runge--Kutta scheme in \\citet{Wicker_2002}} \\\\\n    & \\multicolumn{1}{l}{\\verb|RK4|} & \\multicolumn{2}{l}{4 stage and 4th-order Runge--Kutta scheme} \\\\\n    & \\multicolumn{1}{l}{\\verb|RK7s6o|} & \\multicolumn{2}{l}{7 stage and 6th-order Runge--Kutta scheme in Lawson (1967) (supported only for HEVE)} \\\\\n    & \\multicolumn{1}{l}{\\verb|RK11s8o|} & \\multicolumn{2}{l}{11 stage and 8th-order Runge--Kutta scheme in Cooper and Verner (1972) (supported only for HEVE)} \\\\\n    \\hline\n    \\multicolumn{3}{l}{Spatial scheme} & Minimum number of halos\\\\ \\hline\n    & \\multicolumn{1}{l}{\\verb|CD2|} & \\multicolumn{1}{l}{2nd-order central flux} & \\multicolumn{1}{l}{1}\\\\\n    & \\multicolumn{1}{l}{\\verb|CD4|} & \\multicolumn{1}{l}{4th-order central flux} & \\multicolumn{1}{l}{2}\\\\\n    & \\multicolumn{1}{l}{\\verb|CD6|} & \\multicolumn{1}{l}{6th-order central flux} & \\multicolumn{1}{l}{3}\\\\\n    & \\multicolumn{1}{l}{\\verb|CD8|} & \\multicolumn{1}{l}{8th-order central flux} & \\multicolumn{1}{l}{3}\\\\\n    & \\multicolumn{1}{l}{\\verb|UD3|} & \\multicolumn{1}{l}{3rd-order upwind flux} & \\multicolumn{1}{l}{2}\\\\\n    & \\multicolumn{1}{l}{\\verb|UD5|} & \\multicolumn{1}{l}{5th-order upwind flux} & \\multicolumn{1}{l}{3}\\\\\n    & \\multicolumn{1}{l}{\\verb|UD7|} & \\multicolumn{1}{l}{7th-order upwind flux} & \\multicolumn{1}{l}{3}\\\\\n    & \\multicolumn{1}{l}{\\verb|UD3KOREN1993|} & \\multicolumn{1}{l}{3rd-order upwind flux + \\citet{Koren_1993}'s filter} & \\multicolumn{1}{l}{2}\\\\\n\\hline\n  \\end{tabularx}\n\\end{center}\n\\end{table}\n\nThe default setting for advection scheme used for the prognostic variables in dynamics, spcified by \\nmitem{ATMOS_DYN_FVM_FLUX_TYPE}),\nis the 4th-order central flux (\\verb|CD4|) in the \\scalerm.\nWhen using \\verb|CD4| in a simulation with a steep terrain,\nan artificial grid-scale vertical flow is often seen at the peak of mountains.\nThis grid-scale flow may be reduced by using \\verb|UD3|.\nSo, the use of \\verb|UD3| is recommended for experiments with steep terrains.\n\n\n\\subsection{Numerical Diffusions}\n\nThe numerical stability depends on schemes used in simulations.\nNumerical diffusion may improve the stability.\n\\scalerm has the hyper-diffusion and divergence dumping as the numerical diffusion.\nThe setting for them is the following:\n\\editboxtwo{\n \\verb|&PARAM_ATMOS_DYN  | & \\\\\n \\verb|ATMOS_DYN_NUMERICAL_DIFF_LAPLACIAN_NUM = 2,    |        & \\\\\n \\verb|ATMOS_DYN_NUMERICAL_DIFF_COEF          = 1.D-4,|        & \\\\\n \\verb|ATMOS_DYN_NUMERICAL_DIFF_COEF_TRACER   = 0.D0, |        & \\\\\n \\verb|ATMOS_DYN_DIVDMP_COEF                  = 0.D0, |        & \\\\\n\\verb|/                  | & \\\\\n}\n\n\nThe number of laplacian operator associated with hyper-diffusion is specified by \\\\\n\\nmitem{ATMOS_DYN_NUMERICAL_DIFF_LAPLACIAN_NUM}. \n\\nmitem{ATMOS_DYN_NUMERICAL_DIFF_COEF} and \\\\\n\\nmitem{ATMOS_DYN_NUMERICAL_DIFF_COEF_TRACER} is a non-dimensional coefficient of the hyper-diffusion.\nThe two-grid scale noise is dumped to $1/e$ in one time step if the coefficient is unity.\nThe dumping is stronger for larger coefficient.\nThe hyper-diffusion itself would be numerically unstable if the coefficient is larger than 1.\n\\nmitem{ATMOS_DYN_NUMERICAL_DIFF_COEF} is for the dynamical prognostic variables, such as density, momentum and potential temperature, and \\nmitem{ATMOS_DYN_NUMERICAL_DIFF_COEF_TRACER} is for the tracer variables, such as specific humidity, hydrometeors, and turbulent kinetic energy.\n\\nmitem{ATMOS_DYN_NUMERICAL_DIFF_COEF} can be set to zero when using the upwind schemes, such as \\verb|UD3, UD5|, which has implicit numerical diffusion.\n\n\nThe divergence dumping can also be available to improve numerical stability.\nIts coefficient can be set with \\nmitem{ATMOS_DYN_DIVDMP_COEF}.\n\n\n\\subsection{Positive Definite}\n\nFor tracer advection, guaranteeing a non-negative value is required in most cases.\\\\\nThe \\verb|UD3KOREN1993| scheme guarantees a non-negative value, whereas other schemes do not.\nWhen schemes other than \\verb|UD3KOREN1993| are used the FCT filter can be used to guarantee the non-negative value.\nThe advection scheme is specified by \\nmitem{ATMOS_DYN_FVM_FLUX_TRACER_TYPE}, and switch for the FCT filter is \\nmitem{ATMOS_DYN_FLAG_FCT_TRACER}$=$\\verb|.true.|.\n\n\n\\subsection{Halos}\n\nThe necessary number of halos grid depends on the spatial difference scheme as shown in Table \\ref{tab:nml_atm_dyn}.\nSet \\nmitem{IHALO} and \\nmitem{JHALO} in \\namelist{PARAM_ATMOS_GRID_CARTESC_INDEX} for the number of halos grid for the x- and y-directions, respectively.\nBy default, the number of the grid is 2, which is suitable for ``UD3'', ``UD3KOREN1993'', and ``CD4''.\nFor example, the configuration of the halo for the fifth-order upwind difference scheme is as follows:\n\n\\editboxtwo{\n \\verb|&PARAM_ATMOS_GRID_CARTESC_INDEX | &  \\\\\n \\verb| IHALO = 3,|   &\\\\\n \\verb| JHALO = 3,|   &\\\\\n \\verb|/ | & \\\\\n}\n\n\n\\subsection{Setting for Coriolis Force} \\label{subsec:coriolis}\n%----------------------------------------------------------\n\nIn this subsection, treatments of the Coriolis force in \\scalerm is explained.\nThe Coriolis parameter is zero as the default, so that you have to set (some) parameter(s) to introduce the Coriolis force in the simulation.\nThere are two types of setting for the Coriolis parameter: $f$-/$\\beta$-plane and sphere.\nThe type can be specified by \\nmitem{CORIOLIS_type} in \\namelist{PARAM_CORIOLIS}.\n\n\\subsubsection{$f$-/$\\beta$-plane}\nIf \\nmitem{CORIOLIS_type} is set to ``PLANE'', the Coriolis parameter $f$ is $f=f_0 + \\beta (y-y_0)$.\nWhen $f_0=0$ and $\\beta=0$, which is default, no Coriolis force is taken into account.\n\nThe plane for $\\beta=0$ is called $f$-plane, otherwise it is called $\\beta$-plane.\nThe parameters of $f_0, \\beta$ and $y_0$ is set with the parameters of \\namelist{PARAM_CORIOLIS} as follows:\n\\editbox{\n  \\verb|&PARAM_CORIOLIS| \\\\\n  \\verb| CORIOLIS_type = 'PLANE',| ! PLANE or SPHERE \\\\\n  \\verb| CORIOLIS_f0   = 1.0D-5, | ! $f_0$ \\\\\n  \\verb| CORIOLIS_beta = 0.0D0,  | ! $\\beta$ \\\\\n  \\verb| CORIOLIS_y0   = 0.0D0,  | ! $y_0$ \\\\\n  \\verb|/| \\\\\n}\n\nThe default values of the \\nmitem{CORIOLIS_f0}, \\nmitem{CORIOLIS_beta}, \nand \\nmitem{CORIOLIS_y0} are 0.0, 0.0, and $y$ at the domain center, respectively.\n\nIf you want to add the geostrophic pressure gradient force that is in balance with the Coriolis force accompanied by the geostrophic wind, you need to modify the user specific file \\verb|mod_user.f90| (see Section \\ref{sec:mod_user}).\nThe test case of \\verb|scale-rm/test/case/inertial_oscillation/20km| is an example of a simulation on the $f$-plane with the geostrophic pressure gradient force.\n\n\n\\subsubsection{Sphere}\nOn the sphere, the Coriolis parameter depends on the latitude as $f = 2\\Omega \\sin(\\phi)$, where $\\Omega$ and $\\phi$ are angular velocity of the sphere and latitude, respectively.\nIn this case, you have to set \\nmitem{CORIOLIS_type} = ``SPHERE''.\nThe angular velocity of the sphere is set by \\nmitem{CONST_OHM} parameter of \\namelist{PARAM_CONST} (see Section \\ref{subsec:const}).\nThe latitude of the individual grids is determined depending on the map projection, which is explained in Section \\ref{subsec:adv_mapproj}.\n\n\n\n\\subsubsection{Lateral Boundary Condition for Coriolis Force}\n\nIf there exists geostrophic wind, the periodic boundary conditions cannot be applied in its perpendicular direction, since the wind is not periodic.\nFor the $f$-plane, the double periodic boundary conditions can be applied with no geostrophic wind.\nFor the $\\beta$-plane or sphere, the periodic boundary condition cannot be used in the y-direction, since the Coriolis parameter differs at the southern and northern boundaries.\nIn the absent of meridional geostrophic wind, the periodic boundary in the x-direction is allowed for the all the settings (i.e., the $f$-plane, $\\beta$-plane, and sphere).\n\n\nThe nudge lateral boundary conditions at the south and north boundaries might be used for $f$- and $\\beta$-plane experiment.\nFor the details of the nudging boundary, see Sections \\ref{subsec:buffer}.\nThe test case of \\verb|scale-rm/test/case/rossby_wave/beta-plane| is an example of a simulation on the $\\beta$-plane with the south and north nudging boundaries.\n\n", "meta": {"hexsha": "36d664fb3cbff73c672c0848dcc391d19d4219df", "size": 12064, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/users-guide/en/57_setting_dynamics.tex", "max_stars_repo_name": "slayoo/scale", "max_stars_repo_head_hexsha": "ca4b476ad55cb728b2009f0427ce3f7161ecfcf7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-06-14T11:12:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T05:29:55.000Z", "max_issues_repo_path": "doc/users-guide/en/57_setting_dynamics.tex", "max_issues_repo_name": "slayoo/scale", "max_issues_repo_head_hexsha": "ca4b476ad55cb728b2009f0427ce3f7161ecfcf7", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-07-29T03:38:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-30T05:08:47.000Z", "max_forks_repo_path": "doc/users-guide/en/57_setting_dynamics.tex", "max_forks_repo_name": "slayoo/scale", "max_forks_repo_head_hexsha": "ca4b476ad55cb728b2009f0427ce3f7161ecfcf7", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-10T10:39:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-28T22:20:41.000Z", "avg_line_length": 59.4285714286, "max_line_length": 284, "alphanum_fraction": 0.7176724138, "num_tokens": 3613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.3100699889590739}}
{"text": "\\chapter{KG-RNN: Our Architecture}\r\n\\label{chap:KG-RNN}\r\nIn this chapter we introduce our own architecture, based on the previous chapter where we present our \\textbf{Evolving Entity Encoder}. This novel architecture leverage different graph theory techniques and machine learning to encompass information from other entities and thus further boost the predictive power of the model. \\\\\r\n\r\nThe first section will highlight the different steps of the pipeline, then the following section describes the process of constructing the weighted knowledge graph from internal (MIMIC-III) as well as external information. Right after, we develop the idea of ``extracting`` other entities of interest from the knowledge graph that will improve the prediction for a given input entity. Finally, we expose our \\emph{KG-RNN} deep learning architecture to leverage the input entity as well as the ones we extracted in the previous stage.\r\n\r\n\\section{Overview}\r\nOur ``KG-RNN`` architecture extends on the previous baseline described in chapter~\\ref{chap:Baseline}. The novelty and improvement rely on neighboring entities of interest (i.e. admissions in our use-case) to encompass more information than solely the input entity. \\\\\r\n\r\nTo do so, the first phase consists in creating an appropriate knowledge graph from our dataset but also external information to enrich the linkage structure between entities. This can be done in many different ways, in a weighted or unweighted fashion ($w=1$), and we will describe here how we proceeded in the healthcare use-case. \\\\\r\n\r\nRight after, from this enhanced knowledge graph, weighted or not, we have to extract neighboring entities of interest. For this purpose, we can employ any graph sampling technique (leveraging edge weight or not) and we will go through the one we chose. Finally, from the extracted neighbors and the input entity, we build a machine learning model extending from the baseline one to convey information from these neighbors.\r\n\r\n\\section{Weighted Knowledge Graph Construction}\r\nAs a first step and to the end of building our weighted knowledge graph, the main field of interest is~\\emph{DIAGNOSIS} (that we will call ``prediagnosis`` hereafter to avoid confusion with ICD9 diagnoses) in the admission table. Firstly, we clean the prediagnosis: \\begin{enumerate*}\\item Converting to lower-case. \\item Remove non-alphabetic characters. \\item Remove multi-spaced as well as leading and trailing ones.\\end{enumerate*} \\\\\r\n\r\nOn top of this \\textit{prediagnosis}, we leverage external information from a recent paper that creates a mapping between diseases and symptoms~\\cite{Rotmensch2017}. This external knowledge graph is built from Electronic Health Records (EHR) and links diseases with their respective symptoms, while providing a symptom relevance weight (between 0 and 1). An example of entry from this external source is: \\emph{Migraine: Headache ($w=0.384$), nausea ($w=0.316$), sensitivity to light ($w=0.223$), ...} These diseases and symptoms are cleaned in the exact same way as the prediagnosis and assembled to create our \\textbf{dictionary}. \\\\ \r\n\r\nOur goal now is to link the external information with our internal information to create an enriched knowledge graph. We want to link prediagnosis with symptoms and diseases, while these latter two are intrinsically linked directly by the external information (cf. \\textit{Migrain} example above). \\\\\r\n\r\nTo this end we have to cope with the problem of spelling mistakes as well as quasi-similar prediagnosis and diseases/symptoms (e.g. ``Coronary heart disease`` vs. ``Arteries heart disease``), we create a character N-grams~\\footnote{\\url{https://en.wikipedia.org/wiki/N-gram}} (where the size of the n-gram has to be tuned) list from the cleaned entries of the dictionary (prediagnosis, disease and symptoms). From this n-grams list, we create a TF-IDF~\\footnote{\\href{https://en.wikipedia.org/wiki/Tf\\%E2\\%80\\%93idf}{https://en.wikipedia.org/wiki/Tf\\_idf}} vector with a minimum document frequency of 1. \\\\\r\n\r\nFinally, we match prediagnosis with diseases and symptoms based on the cosine similarity between their n-grams + TF-IDF vectors. Namely, we link a prediagnosis with a disease and a symptom if their cosine similarity score is above a given threshold (to manually filter out noise), and we link diseases and symptoms based on the external information while also applying a threshold on the symptoms relevance weight provided out-of-the-box by the external source. The final knowledge graph is represented in the figure~\\ref{fig:kg-healthcare}, including both internal and external information. \\\\\r\n\r\n\\begin{figure}[H]\r\n \\centering\r\n \\includegraphics[width=0.9\\textwidth]{figures/kg-healthcare.pdf}\r\n \\caption{Final knowledge graph made of external and internal information that will be used in the experiments and discussions.}\r\n \\label{fig:kg-healthcare}\r\n\\end{figure}\r\n\r\nOn a practical note, for the rest of the discussions and experiments, we set n-grams to \\textbf{3 characters}, the minimum cosine similarity score of \\textbf{0.6} and a relevance weight between diseases and symptoms of \\textbf{0.2}.\r\n\r\n\\newpage\r\n\\section{Weighted Knowledge Graph Extraction}\r\nSecondly, from this weighted knowledge graph, we want to extract relevant neighboring entities to enrich our input entity with additional information. For this purpose, one can use any graph sampling technique~\\cite{DBLP:journals/corr/HuL13, Leskovec:2006:SLG:1150402.1150479}, making use of the weights defined during \\textit{Graph Construction} or not. \\\\\r\n\r\nThis graph sampling will be very important for the downstream model and also the number of neighbors is a critical hyper-parameter that has to be tuned. In that regard, relevant experiments can be found in the appropriate chapter. Some common sampling techniques could be \\begin{enumerate*}\\item Random sampling on 1-hop neighbors. \\item Snow-Ball sampling. \\item Forest Fire sampling.\\end{enumerate*}. \\\\\r\n\r\nFor our use-case at hand, we decided to employ some \\textit{importance sampling} based algorithm. This technique is inspired from a paper~\\cite{DBLP:journals/corr/abs-1806-01973} by Pinterest and Stanford, it relies on random walks to create an importance score for each entity and take the top scoring entities as neighbors of interest. \\\\\r\n\r\nConcretely, the process is to simulate many random walks \\emph{starting from input entity} and compute the $L_1$-normalized visit count as the importance score. Now, instead of simulating thousands of random walks it can be proven that in the limit of an infinity of simulations, the normalized $L_1$ visit count is equivalent to a Personalized PageRank score. Henceforth, we decided to compute the Weighted Personalized PageRank score (personalized on the input entity) using \\textit{Oracle PGX} for each input entity. \\\\\r\n\r\nFinally, and as stated previously, the top-$M$ scoring entities are extracted for each input admission and we define a minimum score of \\textbf{0.0001} as an arbitrary threshold. Otherwise, there would always have exactly M neighbors sampled even if some are isolated and thus have a score of 0. This threshold allows for more flexibility and to have $0 \\leq \\mbox{neighbors} \\leq M$ for a given input admission. A made-up example resulting from this whole process is available in figure~\\ref{fig:kg-healthcare-extraction}.\\\\\r\n\r\nFrom a practical standpoint, we also make sure not to sample neighbors from the testing or validation set when we are training, or respectively sampling entities from the training or testing set during validation. Equivalently, we make sure not to sample entities from training and validation when we do the final evaluation on the test set.\r\n\r\n\\begin{figure}[H]\r\n\t\\centering\r\n\t\\includegraphics[width=0.9\\textwidth]{figures/kg-healthcare-extraction.pdf}\r\n\t\\caption{Example of potential \\textit{WPPR} scoring for the knowledge graph in figure~\\ref{fig:kg-healthcare}. If we set $M=1$, only ``Admission 2`` would be extracted, whereas if we set $M=2$ both admissions 1 and 2 would be extracted as neighbors of ``Admission 1``.}\r\n\t\\label{fig:kg-healthcare-extraction}\r\n\\end{figure}\r\n\r\n\\newpage\r\n\\section{Graph Machine Learning}\r\nThe machine learning model encapsulating information from neighboring entities as well as the input entity relies on the building block described in the chapter~\\ref{chap:Baseline}. Indeed, the input admission is first encoded using the \\textbf{Evolving Entity Encoder} from which the final embedding vector $\\bm{\\tilde{h}} \\in \\mathbb{R}^{b}$ is fed to the main module. The main module job lies in blending information from extracted neighbors with the input admission vector $\\bm{\\tilde{h}}_i^m$. \\\\\r\n\r\nTo better understand the mechanics, the extracted neighbors can be seen as made of static information throughout admission (e.g. patient age) and dynamic information (e.g. their respective events). The main module can either process dynamic information and static information, or just one or the other. Explicitly, the extracted neighbors entities can also go through the Evolving Entity Encoder to embed their dynamic behavior in a vector $\\bm{\\tilde{h}} \\in \\mathbb{R}^{b}$ that will be then concatenated with static information vectors. \\\\\r\n\r\nEventually, the embedded vector is concatenated with static information vectors, and fed through a fully-connected layer (\\textit{encoder}) to obtain the final neighbor encoding vector. These vectors are then fed through an aggregator of the same kind as the one described in chapter~\\ref{chap:Baseline}, that is \\textit{sum}, \\textit{mean} or \\textit{max}. hHe purpose of this aggregator is to squash the data along the $M$ dimension to squeeze out information from neighbors. The final prediction diagnoses are made from the concatenation of the aggregated neighbors and input entity encoding, that is finally fed into a fully-connected layer mapping to our \\emph{50} classes. \\\\\r\n\r\nOn our use-case at hand, we decided to discard dynamic behavior of neighbors and solely take into account the final diagnoses of those as our static information. Additionally, for a one-hot encoded vector of a neighbor final diagnoses $\\bm{y}=[0, 0, 1, 0, 1, 0, \\dots, 1]\\mbox{, where }|\\bm{y}|=50$ we decided to make use of the \\textbf{SEQ\\_NUM} field by transforming this one-hot vector using the function $1/x$. That is, our new static information vector becomes $\\bm{\\tilde{y}}=[0, 0, 1/1, 0, 1/3, 0, \\dots, 1/2]\\mbox{, where }|\\bm{\\tilde{y}}|=50$ if we respectively have a \\textbf{SEQ\\_NUM} of 1, 3 and then 2. \\\\\r\n\r\nA schematic visualization of the general machine learning model is available on the figure~\\ref{fig:kg-rnn-general}, while the applied model can be found on the figure~\\ref{fig:kg-rnn-healthcare}.\r\n\r\n\\newpage\r\n\\subsection{Schematic Visualizations}\r\nIn order to provide the reader an overview of the mechanics behind KG-RNN, the following visualization summarizes the textual description of the previous section.\r\n\r\n\\begin{figure}[H]\r\n \\centering\r\n \\includegraphics[width=0.7\\textwidth]{figures/kg-rnn-general.pdf}\r\n \\caption{The general module of our architecture, where \\textbf{Evolving Entity Encoder} relies on work from previous chapter. The static properties and information from neighbors are concatenated and fed through an \\emph{Encoder}, consisting of a simple fully-connected layers to blend the concatenated information. All encoding vectors from neighbors are aggregated along the $M$ dimension and concatenated with the input entity. This vector is then further fed into a fully-connected layer, here hidden in the \\emph{Concatenate} block, to output the predictions.}\r\n \\label{fig:kg-rnn-general}\r\n\\end{figure}\r\n\r\nThe following figure is a special case of the general approach available in the previous figure. Indeed, in our practical application we decided to get rid of the dynamic information from neighbors, leading to the following adapted schema:\r\n\r\n\\begin{figure}[H]\r\n \\centering\r\n \\includegraphics[width=0.6\\textwidth]{figures/kg-rnn-healthcare.pdf}\r\n \\caption{Similar to the previous schema, except that only static information from neighbors is encoded and squashed. Here the static information consist of only the diagnoses of these neighboring admissions.}\r\n \\label{fig:kg-rnn-healthcare}\r\n\\end{figure}\r\n\r\nAs mentioned previously, in our case we decided to discard dynamic information from neighbors but we argue that this is heavily application-dependent, thus validating on different tasks and knowledge graphs would be insightful.", "meta": {"hexsha": "c106cf2772078c60424482ebc827ef7682fb53b7", "size": 12505, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/kg_rnn.tex", "max_stars_repo_name": "Timonzimm/masters-thesis", "max_stars_repo_head_hexsha": "dea9569735fc73365f4d0da67aae5e3d7a577845", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/kg_rnn.tex", "max_issues_repo_name": "Timonzimm/masters-thesis", "max_issues_repo_head_hexsha": "dea9569735fc73365f4d0da67aae5e3d7a577845", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/kg_rnn.tex", "max_forks_repo_name": "Timonzimm/masters-thesis", "max_forks_repo_head_hexsha": "dea9569735fc73365f4d0da67aae5e3d7a577845", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-27T07:47:20.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-27T07:47:20.000Z", "avg_line_length": 143.7356321839, "max_line_length": 682, "alphanum_fraction": 0.787684926, "num_tokens": 2832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.30996758994267415}}
{"text": "%\n% This is Chapter 1 file (chap1.tex)\n%\n\\chapter{Introduction}\\label{chap:chap1}\n\n    \\section{Prologue to Plasma}\\label{sec:plas0}\n\n        Our daily life is dominated by our interactions with the three classical states of matter:\n        solid, liquid and gas. Plasma is the fourth state of matter and by far the most abundant\n        one. In fact the observable universe is almost entirely made up of plasma (99.9\\% of the\n        universe) \\citep{Boulos1994}. From the HII region around a huge star to the surface of a\n        star, from the super hot Inter Galactic Medium to the inside of a plasma TV, plasma is\n        everywhere. Given its abundance and ubiquitous nature, it becomes vitally important to study\n        and understand plasma. In the rest of this chapter we define what constitutes a plasma\n        (\\Cref{sec:plas1}) and  discuss some of its salient properties and the laws of physics that\n        govern it. We also shed some light on the local regions around Earth that are made up of\n        plasma (\\Cref{sec:plas2}) and discuss studying them (\\Cref{sec:plas3}). We conclude the\n        chapter with with a brief discussion of topics covered in this thesis. (\\Cref{sec:plas4}).\n\n    \\section{Introduction To Plasma} \\label{sec:plas1}\n\n        The term ``plasma\" comes from the ancient Greek word ``$\\pi \\lambda \\acute{\\alpha} \\sigma\n        \\mu \\alpha$\" that means something that is moldable. It was first used in the modern context\n        by \\citet{Langmuir1928} to describe the ``region (around electrodes) containing balanced\n        charges of ion and electrons\".\n        \n        A plasma is a sub-type of ionized gas; a gas where significant fraction of the atoms have\n        been ionized. There are specific criteria that distinguishes plasmas from other ionized\n        gases (discussed later in this section), but first we consider the equations that govern the\n        dynamics of charged particles (electrons and ions).\n\n        As is with everything that has mass in the universe, a plasma's dynamics is governed by\n        Newton's equation of motion:\n        \\begin{align}\n            %\\begin{split}\n            \\mathbf{F}_{\\rm net} = \\frac{d \\mathbf{P}}{d t} & = m \\frac{d^2 \\mathbf{x}}{d t^2} \\protect\\footnotemark \\label{eq:nwtn1}\n        \\end{align}\n        \\footnotetext{$\\mathbf{F}_{\\rm net} = m \\frac{d^2 \\mathbf{x}}{d t^2}$ is only valid when the\n        particle is moving at speed much smaller than the speed of light.} where $\\mathbf{F}_{\\rm\n        net}$ is the net external force acting on the system and \\textbf{P} is its momentum. t is\n        time, \\textbf{x} is the position vector and $\\frac{d}{dt}$ is the derivative with respect to\n        time.\n        \n        For a charged particle with charge \\textit{q}, moving with velocity \\textbf{v} in an\n        electromagnetic field with electric and magnetic field as \\textbf{E} and \\textbf{B}\n        respectively, the electromagnetic force or Lorentz force is given as:\n        \\begin{align}\n            \\mathbf{F}_{\\rm EM} = q \\left( \\mathbf{E} + \\mathbf{v} \\times \\mathbf{B} \\right)\n            \\label{eq:lorentz}\n        \\end{align}\n        These equations (\\Crefrange{eq:nwtn1}{eq:lorentz}) coupled with the four Maxwell's equations\n        (\\Crefrange{eq:maxwell1}{eq:maxwell4}) define the complete dynamics of a plasma.\n        \\begin{align}\n            \\nabla \\cdot \\mathbf{E} & = \\frac{\\rho}{\\epsilon_\\circ} \\label{eq:maxwell1}\\\\\n            \\nabla \\cdot \\mathbf{B} & = 0 \\label{eq:maxwell2}\\\\\n            \\nabla \\times \\mathbf{E} & = -\\frac{\\partial \\mathbf{B}}{\\partial t} \\label{eq:maxwell3}\\\\\n            \\nabla \\times \\mathbf{B} & = \\mu_\\circ \\mathbf{J} + \\frac{1}{c^2} \\frac{\\partial \\mathbf{E}}{\\partial t} \\label{eq:maxwell4}\n            %\\end{split}\n        \\end{align}\n        where, $\\rho$ is the charge density, $\\epsilon_\\circ$ is the permittivity of free space,\n        $\\frac{\\partial}{\\partial t}$ is the partial derivative with respect to time, $\\mathbf{J}$\n        is the current density, and c is the speed of light in vacuum.\n\n        The most accurate way to study the behaviour of plasma is to track each particle\n        individually using \\Crefrange{eq:nwtn1}{eq:maxwell4}, all while accounting for all the\n        fields, external as well as those arising because of the charge and motion of particles\n        themselves. However, that method is almost impossible to implement not only because of\n        difficulty in computing the field arising because of mutual interactions but also because of\n        the huge number of particles involved. Consequently, scientists often fall back to\n        statistical methods in their studies, such as applying kinetic equations that use physics\n        based on ensemble averages (see \\Cref{chap:chap2}) or by approximating the plasma as a fluid\n        as is done in Magneto-hydrodynamics (MHD).\n\n        Since even the lightest ion, a proton, is nearly 2000 times more massive than an electron\n        and the dynamics of particles are often governed by their masses, both the time and length\n        scales at which dynamics occur in plasmas are extremely diverse, even when one is studying\n        the same phenomena for ions and electrons. Values of some of the parameters associated with\n        plasma (generally referred to as \\textit{plasma parameters}) can help in understanding the\n        scales one is dealing with. Also, as will become apparent in \\Cref{chap:chap2,chap:chap3},\n        one may choose to focus on a specific scale depending on the interest or scope of the study.\n        Here, we list some of the most relevant plasma parameters, what each one of them mean, and\n        their mathematical expressions.\\\\\n        \\\\\n        \\textbf{Debye Length} ($\\lambda_{\\rm D}$): The Debye length \\index{Debye length} is the scale above which a\n        plasma (with no net charge) maintains near charge neutrality --- $\\rho \\approx 0$ when\n        $\\rho$ is smoothed over a scale $\\gtrsim \\lambda_{\\rm D}$. On scales smaller than\n        $\\lambda_{\\rm D}$, particles behave as if it were interacting with other moving charges\n        individually instead of a smooth macroscopic electromagnetic field. If we have sufficiently\n        large number of particles inside a spherical volume with $\\lambda_{\\rm D}$ as the radius\n        ($n_{\\rm p} \\lambda_{\\rm D}^3 > 1$), then particles are shielded by its neighbours from the\n        surrounding plasma (called \\textit{Debye shielding}). On scales $\\lesssim \\lambda_{\\rm D}$,\n        random thermal motions of the particles give rise to isolated regions of non-zero charge\n        density.  We would then expect $\\lambda_{\\rm D}$ to increase with plasma temperature.\n        Indeed, for a plasma consisting of ionized hydrogen for which the protons and electrons have\n        comparable temperatures, we define Debye length as:\n        \\begin{align}\n            \\lambda_{\\rm D} & = \\frac{\\epsilon_\\circ k_{\\rm B} T_{\\rm p}}{n_{\\rm e} e^2}^{1/2} \\label{eq:debye}\n        \\end{align}\n        where $k_{\\rm B}$ is the Boltzmann constant, $n_{\\rm e}$ is the electron number density and\n        $T_{\\rm p}$ is the proton temperature. In order for a system to be classified as plasma, we\n        must have the physical length scale (L) of the system much larger than its Debye length.\n        \\begin{align}\n            \\lambda_{\\rm D} \\ll L \\label{eq:lambda}\n        \\end{align}\n        \\\\\n        \\textbf{Ion-inertial Length \\index{Ion-inertial Length}($d_{\\rm j}$):} This is the length scale in plasma at which the\n        electrons are decoupled from ions and the magnetic field is frozen in with the electrons.\n        For species `$j$' of plasma (where $j = p^{+}$ for protons and $j = i^{n+}$ for any other\n        ion with n positive charge)\\footnote{In this thesis unless otherwise specified ion will\n        refer to protons and two terms will be used interchangeably}, it can be written in terms of\n        ion plasma frequency ($\\omega_{\\rm pj}$) as:\n        \\begin{align}\n            d_{\\rm j} = \\frac{c}{\\omega_{\\rm pj}} \\label{eq:ionint}\n        \\end{align}\n        \\\\\n        \\textbf{Plasma Frequency \\index{Frequency!plasma} ($\\omega_{\\rm pj}$)}\\footnote{Note that `p' in $\\omega_{\\rm pj}$\n        refers to plasma and not proton.}: It is the frequency at which any given species in plasma\n        oscillates and is given by:\n        \\begin{align}\n            \\omega_{\\rm pj} & = \\left(\\frac{n_{\\rm j} q_{\\rm j}^2}{\\epsilon_\\circ m_{\\rm j}}\\right)^{\\frac{1}{2}} \\label{eq:plasf}\n        \\end{align}\n        \\\\\n        \\textbf{Cyclotron Frequency \\index{Frequency!cyclotron} ($\\Omega_{\\rm cj}$):} In a magnetized plasma (a plasma which has\n        a background magnetic field), due to the perpendicular direction of the magnetic force with\n        respect to the particle's velocity, any non-stationary charged particle in a magnetic field\n        gyrates around a point called the center of gyration. The frequency of gyration or cyclotron\n        frequency is given by:\n        \\begin{align}\n            \\Omega_{\\rm cj} & = \\frac{q_{\\rm j} B}{m_{\\rm j}} \\label{eq:cyclf}\n        \\end{align}\n        where \\textbf{B} is the background magnetic field. \\\\\n        \\\\\n        \\textbf{Gyroradius \\index{Gyroradius}}\\textbf{($\\rho_{\\rm j}$)}: This is the radius of the circular path that a particle takes in\n        the presence of a magnetic field, and is dependent on the ratio of thermal speed to that of\n        cyclotron frequency.\n        \\begin{align}\n            \\rho_{\\rm j} = \\frac{w_{\\rm j}}{\\Omega_{\\rm cj}} \\label{eq:rho}\n        \\end{align}\n        where $w_{\\rm j}$ is the thermal speed of the particle. \\\\\n        \\\\\n        \\textbf{Alfv\\'en Speed \\index{Alfv\\'en Speed} ($V_{\\rm Aj}$)}: It is the speed at which magnetic signals, like a\n        fluctuation in the field, travel in a plasma. It depends on the strength of the magnetic\n        field in the plasma as well the density and mass of the species and has the following\n        expression:\n        \\begin{align}\n            v_{\\rm Aj} = \\frac{B}{\\sqrt{\\mu_\\circ \\sum_{\\rm j} n_{\\rm j} m_{\\rm j}}} \\label{eq:alfv}\n        \\end{align}\n\n    \\section{Plasma in Near-Earth Environment} \\label{sec:plas2}\n\n        The Sun is the largest source of plasma in our solar system. Huge amounts of charged\n        particles emanate from the Sun originating in its outermost atmospheric layer, called the\n        Corona \\citep{Parker1958,Parker1960,Parker1963,Gringauz1960,Neugebauer1962}. This constant\n        outflow of particles is commonly called solar wind. The solar wind is often highly\n        magnetized, is weakly collisional, travels at supersonic speed and is primarily composed of\n        ionized hydrogen (i.e., protons) \\citep{Marsch1982}. \\Cref{tab:plaspar1} lists out some of\n        the plasma parameters and their typical values for the solar wind at 1\\,au.\n        \\Cref{fig:plas_para_wnd} shows the distribution of some of the parameters listed in\n        \\Cref{tab:plaspar1}.\n        \\begin{figure}\n            \\begin{center}\n                \\includegraphics[width=1\\textwidth]{figures/chap1/plasma_parameters_wnd.pdf}\n                \\caption[Plasma parameter distributions at 1\\,au ]{Distribution of various plasma\n                parameters near Earth, based on data from Wind spacecraft. Top row shows\n                distribution for (from left to right) proton-inertial length ($d_{\\rm i}$), Debye\n                length ($\\lambda_{\\rm D}$), proton-gyrofrequency ($\\Omega_{\\rm cp}$) and the lower\n                row shows (from left to right) proton-gyroradius ($\\rho_{\\rm i}$), proton-plasma\n                frequency ($\\omega_{\\rm pp}$) and alfv\\'en speed ($v_{\\rm A}$). Red line shows the\n                median value of each parameter, whereas the shaded region shows $10^{\\rm th}$ to\n                $90^{\\rm th}$ (cyan) and $25^{\\rm th}$ to $75^{\\rm th}$ percentile (magenta) of each\n                parameter.\\protect\\footnotemark}\n                \\label{fig:plas_para_wnd}\n            \\end{center}\n        \\end{figure}\n        \\footnotetext{\\Cref{fig:plas_para_wnd} is based on data from Wind Spacecraft. See\n        \\Cref{sec:wind} for more details on data and spacecraft.}\n\n        The Earth's local magnetic field, which arises as a result of dynamo action of its molten\n        core \\citep{Elsasser1956}, extends far into space (roughly 10 earth radii in the direction\n        of the sun and $\\sim$ 300 earth radii in the anti-sunward direction) and interacts with the\n        incoming solar wind. This interaction gives rise to a plethora of structures.\n        \\Cref{fig:ms_earth} shows an artistic rendition of Earth's magnetosphere. The layer along\n        which solar wind transitions from supersonic to subsonic speed is called the bow shock\n        (region 1). The region immediately after the bow shock is called the magnetosheath (region\n        2) and is comprised mostly of shock treated solar wind. This region is of special importance\n        to the present work (see \\Cref{chap:chap5,chap:chap7}). The region beyond the magnetosheath,\n        towards Earth, where the pressure exerted by the solar wind and Earth's magnetic field are\n        in equilibrium is called the magnetopause (region 3) and forms the boundary between Earth's\n        magnetosphere (volume  around  Earth  where the influence  of  its magnetic field is felt\n        (region 4)) and the solar wind. There is also a long magnetotail further away from the Sun,\n        which extends far beyond the surface of the Earth (regions 5 and 6). The region closest to\n        the surface (region 7) is called the plasmasphere, which is made up of relatively cooler\n        plasma and is located above the ionosphere. The shape and size of all these structures vary\n        greatly depending on the velocity and density of the incoming plasma, the strength of\n        magnetic field, and solar activity.\n\n        %Another distinct region of plasma close to the Earth is the ionosphere. It is part of the\n        %upper region of Earth's atmosphere and forms because of photoionization of atoms by\n        %ultraviolet radiation from Sun \\cite[\\S 4.4.3]{Wallace2006}. These radiation get absorbed\n        %by around 90\\,km above the surface and have enough energy and intensity to ``give rise to\n        %sufficient number of free electrons\" which helps in propagation of radio waves \\cite[\\S\n        %4.4.3]{Wallace2006}. The structure of ionosphere is quite complicated and has a lot of\n        %variability, both diurnal and seasonal. Owing to its complicated structure and dynamics it\n        %is its own huge field of research and holds considerable interest for both geophysicists\n        %and climatologists.\\\\\n\n        \\begin{table}[ht]\n            \\centering\n            \\caption[Plasma Parameters - Median values]{Plasma parameters and their typical values for different space plasmas.\\protect\\footnotemark}\n            \\begin{tabular}{ p{0.15\\linewidth}  p{0.25\\linewidth}  p{0.25\\linewidth}\n            p{0.25\\linewidth}  }\n                \\hline\n                \\\\\n                Parameter & Solar Wind (0.15\\,au ) & Solar Wind (1\\,au ) & Magnetosheath \\\\ \\\\\n                \\hline\n                \\\\\n                $d_{\\rm i}$ & 15,510 $\\pm$ 6,200 m & 91,920 $\\pm$ 42,000 m & 45,600 $\\pm$ 9,900 m\\\\\n                \\\\\n                %\\hline\n                \\\\\n                $\\lambda_{\\rm D}$ & 2.87 $\\pm$ 1.98 m & 6.41 $\\pm$ 6.20 m & 23.18 $\\pm$ 8.00 m\\\\ \\\\\n                %\\hline\n                \\\\\n                $\\Omega_{\\rm cp}$ & 6.47 $\\pm$ 2.70 1/s & 0.45 $\\pm$ 0.26 1/s & 2.16 $\\pm$ 1.00\n                1/s\\\\ \\\\\n                %\\hline\n                \\\\\n                $\\omega_{\\rm pp}$ & 19,328 $\\pm$ 7,300 1/s & 3,261 $\\pm$ 1,500 1/s & 6,574 $\\pm$\n                1,500 1/s\\\\ \\\\\n                %\\hline\n                \\\\\n                $\\rho_{\\rm p}$ & 12,793 $\\pm$ 8,500 m & 68,615 $\\pm$ 48,000 m & 97,795 $\\pm$ 69,000\n                m\\\\ \\\\\n                %\\hline\n                \\\\\n                $V_{\\rm A}$ & 102,503 $\\pm$ 39,000 m/s & 43,390 $\\pm$ 26,000 m/s & 94,256 $\\pm$\n                50,000 m/s\\\\ \\\\\n                \\hline\n            \\end{tabular}\n            \\label{tab:plaspar1}\n        \\end{table}\n        \\footnotetext{These values are based on datasets as described in \\Cref{chap:chap4}.}\n\n        \\begin{figure}\n            \\begin{center}\n                \\includegraphics[width=1\\textwidth]{figures/chap1/Magnetosphere_Levels.pdf}\n                \\caption[Earth's Magnetosphere's structure]{Artistic rendition of Earth's magnetosphere, its structure and different layers. The name of each numbered layer is 1.bow shock, 2. magnetosheath, 3. magnetopause, 4. magnetosphere, 5 and 6. tail lobes, 7. plasmasphere.\\protect\\footnotemark}\n                \\label{fig:ms_earth}\n            \\end{center}\n        \\end{figure}\n        \\footnotetext{Picture credit: https://commons.wikimedia.org/wiki/File:Magnetosphere\\_Levels.svg}\n\n    \\section{Studying Space Plasmas} \\label{sec:plas3}\n\n        In the previous section (\\Cref{sec:plas2}) we discussed two different kinds of naturally\n        occurring plasma regions close to Earth. A complete theory of plasma would require us to\n        understand the commonality as well as the uniqueness of each of these regions. Consequently,\n        over the last century or so the scientific community has devised several methods to study\n        them. From Guglielmo Marconi using an antenna on a kite to receive radio signals in 1901 to\n        NASA launching a spacecraft costing more than a billion dollars (Parker Solar Probe (PSP))\n        in 2018 to study the Sun from a closer distance than ever before, the community has been in\n        a constant pursuit to understand them. \n        %\\Cref{tab:spcmsn} lists out some of the major programs and missions along with mission\n        %objectives, dedicated to such studies.\\\\\n        %\\begin{table}[ht] \\centering \\caption[Major space missions to study space plasmas]{Some of\n        %    the major space missions to study space %plasmas \\todo{update the table with full\n        %    list}} \\begin{tabular}{ | p{0.15\\linewidth} | p{0.15\\linewidth} | p{0.45\\linewidth}|}\n        %    \\hline Spacecraft & Years Active & Major Objective \\\\\n        %        \\hline Voyager 1 \\newline Voyager 2 & 1977 - \\newline 1977 - & Study outer planets\n        %         and interplanetary %medium \\\\\n        %        \\hline Wind & 1994 - & Study plasma processes in the solar wind near earth and in\n        %        magnetosphere and %ionosphere\\\\\n        %        \\hline Helios A \\newline Helios B & 1974 - 1982 \\newline 1976 - 1985 & Observation\n        %        of solar wind, electromagnetic fields, cosmic rays\\\\\n        %        \\hline MMS & 2016 - & Understanding magnetic reconnection and turbulence\\\\\n        %        \\hline Parker Solar Probe & 2018 - & Understanding Coronal heating\\\\\n        %        \\hline SoHo & 2018 - & Understanding Coronal heating\\\\\n        %        \\hline Ace & 2018 - & Understanding Coronal heating\\\\\n        %        \\hline STEREO & 2018 - & Understanding Coronal heating\\\\\n        %        \\hline \\end{tabular} \\label{tab:spcmsn} \\end{table}\n\n    \\section{In This Thesis} \\label{sec:plas4}\n\n        Work done towards this thesis presents an incremental contribution towards understanding the\n        nature and behaviour of space plasmas. \\Cref{chap:chap2,chap:chap3} provide a theoretical\n        background on plasma microkinetics and turbulence, respectively. \\Cref{chap:chap4} gives a\n        brief overview of all the datasets used in the present document and explains some of the\n        data analysis techniques employed in \\Crefrange{chap:chap5}{chap:chap7}.\n\n        \\Crefrange{chap:chap5}{chap:chap8} report the author's original work. \\Cref{chap:chap5}\n        discusses the intermittency in space plasmas and simulations as well as its co-development\n        with linear instabilities. \\Cref{chap:chap6} explores the heating of ions close to the Sun\n        as a consequence of intermittent structures. \\Cref{chap:chap7} discusses the competition\n        between linear and non-linear processes using a statistical approach on six different\n        datasets. \\Cref{chap:chap8} presents an exploratory study of magnetic field reconstruction\n        using machine learning (ML) techniques. \\Cref{chap:chap9} provides a summary of the entire\n        thesis and a guide for future work.", "meta": {"hexsha": "aa3dde98dfa2371ad8d0216ea55b6c732b464943", "size": 20497, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chap1.tex", "max_stars_repo_name": "qudsiramiz/ud-phd-thesis", "max_stars_repo_head_hexsha": "5ee6e2ff80ebc0192f4f2bc592273eb9c3712796", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chap1.tex", "max_issues_repo_name": "qudsiramiz/ud-phd-thesis", "max_issues_repo_head_hexsha": "5ee6e2ff80ebc0192f4f2bc592273eb9c3712796", "max_issues_repo_licenses": ["FSFAP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chap1.tex", "max_forks_repo_name": "qudsiramiz/ud-phd-thesis", "max_forks_repo_head_hexsha": "5ee6e2ff80ebc0192f4f2bc592273eb9c3712796", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 69.0134680135, "max_line_length": 301, "alphanum_fraction": 0.6556081378, "num_tokens": 5375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3099675831025719}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\subsection{Statistical descriptions of plasmas}\n\n\\marginpar{Thursday\\\\ 2021-11-18}\n\nIf the length scales we consider are larger than the Debye length, we can safely neglect the effect of the Coulomb potential of each individual particle. \nThis does not mean that there are no electric fields, but the electric fields are mesoscopic or larger. \n\nThis is ``desirable'', in that we'd like to use statistical descriptions of the plasma.\nSuch a statistical description will necessarily work in phase space. \n\nLet us start out in the nonrelativistic approximation: if we only have one particle, we can write its phase space distribution function as \n%\n\\begin{align}\nN(\\vec{x}, \\vec{v}, t) = \\delta (\\vec{x} - \\vec{X}(t)) \\delta (\\vec{v} - \\vec{\\dot{X}}(t))\n\\,.\n\\end{align}\n\nIf we have several particles, this can be readily generalized: \n%\n\\begin{align}\nN(\\vec{x}, \\vec{v}, t) =\n\\sum _{i} \\delta (\\vec{x} - \\vec{X}_i(t)) \\delta (\\vec{v} - \\vec{\\dot{X}}_i(t))\n\\,,\n\\end{align}\n%\nbut this only describes a single particle species: we know that at the very least we will have electrons and protons, in order to preserve charge neutrality. \nSo, let us call the quantity defined above \\(N_s\\), where \\(s\\) is an index spanning \\(\\qty{e, i}\\) for electrons and ions respectively. \n\nWe want to describe the evolution of this quantity: its \\textbf{total} time derivative can be computed through the chain rule, and if we set it to zero we find that \\(\\dv*{N_s}{t} = 0\\) is equivalent to:\n%\n\\begin{align}\n\\pdv{N_s}{t} (\\vec{x}, \\vec{v}, t) = \n- \\sum _{i} \n\\vec{\\dot{X}} \\cdot\n\\nabla_x \\delta (\\vec{x} - \\vec{X}_i(t)) \n\\delta (\\vec{v} - \\vec{V}_i (t) ) \n- \\sum _{i} \n\\delta (\\vec{x} - \\vec{X}_i(t)) \n\\vec{\\dot{V}}_i(t) \\cdot\n\\nabla_v \\delta (\\vec{v} - \\vec{V}_i(t)) \n\\,.\n\\end{align}\n\nNow, these charges will evolve under the actions of the electric and magnetic fields: but we also need to describe what is the source of these fields. \n\nThe action of these fields on a particle with velocity \\(\\vec{V}_i\\) will be described by the Lorentz force, \n%\n\\begin{align}\nm_s \\vec{\\dot{V}}_i (t) = q_s \\vec{E}^{\\text{microscopic}} (\\vec{x}) + \\frac{q_s}{c} \\vec{V}_i \\times \\vec{B}^{\\text{microscopic}} (\\vec{x}, t)\n\\,.\n\\end{align}\n\nThis acceleration term will then be put into the aforementioned evolution equation. \nWe can already understand why this problem will be hard: the fields acting on a particle will be sourced by all the others. \n\nThe microscopic EM fields will satisfy Maxwell's equations: \n%\n\\begin{align}\n\\vec{\\nabla} \\cdot \\vec{E}^{\\text{micro}} (\\vec{x}, t) \n&= 4 \\pi \\zeta^{\\text{micro}}  \\\\\n\\vec{\\nabla} \\cdot \\vec{B}^{\\text{micro}} &= 0  \\\\\n\\vec{\\nabla} \\times E^{\\text{micro}} &= - \\frac{1}{c} \\pdv{\\vec{B}^{\\text{micro}}}{t}  \\\\\n\\vec{\\nabla} \\times \\vec{B}^{\\text{micro}} &= \\frac{4 \\pi }{c} \\vec{J}^{\\text{micro}} + \\frac{1}{c} \\pdv{\\vec{E}^{\\text{micro}}}{t} \n\\,,\n\\end{align}\n%\nwhere the density and current density read \n%\n\\begin{align}\n\\zeta^{\\text{micro}} (\\vec{x}, t) &= \\sum _{s=i, e} q_s \n\\int \\dd[3]{\\vec{v}} N_s (\\vec{x}, \\vec{v}, t)  \\\\\n\\vec{J}^{\\text{micro}} &= \\sum _{s=i, e} q_s \n\\int \\dd[3]{\\vec{v}} \\vec{v} N_s (\\vec{x}, \\vec{v}, t)\n\\,.\n\\end{align}\n\nThe Boltzmann equation plus the Lorentz one can be more compactly written as \n%\n\\begin{align}\n\\pdv{N_s}{t} \n= - \\vec{v} \\cdot \\vec{\\nabla}_x N_s \n- \\sum _{i=1}^{N} \\frac{q_s}{m_s} \n\\qty[ \\vec{E}^{\\text{micro}} + \\frac{1}{c} \\vec{v} \\times \\vec{B}^{\\text{micro}}] \\cdot \\vec{\\nabla}_v \\qty[\n    \\delta (\\vec{v} - \\vec{\\dot{X}}_i(t))\n    ]\n\\delta (\\vec{x} - \\vec{X}_i(t)) \n\\,.\n\\end{align}\n\nThe EM fields are \\emph{a priori} computed at the position and velocity of the \\(i\\)-th particle, \\((\\vec{X}_i, \\vec{V}_i)\\), but because of the \\(\\delta \\)-functions at each point we can substitute this position for the generic one \\((\\vec{x}, \\vec{v})\\). \n\n% where we have done a nontrivial step: the gradient \\dots\n\n% \\todo[inline]{That's wrong! Or maybe not? it's because the velocity dependence is mediated through the delta-function\\dots }\n\nThe equation then becomes \n%\n\\begin{align}\n\\pdv{N_s}{t} + \\vec{v} \\cdot \\vec{\\nabla}_x N_s \n&= - \\frac{q_s}{m_s} \\qty[\\vec{E}^{\\text{micro}} + \\frac{\\vec{v} \\times \\vec{B}^{\\text{micro}}}{c}] \\cdot \\nabla_v N_s\n\\,.\n\\end{align}\n\nThis equation is called the Klimontovich-Dupree equation.\\footnote{As many things done during the Cold War, it was developed by military personnel independently in the two blocks. } \n\nThis equation, however, is basically useless, unless we do a mean-field approximation. \n\nLet us introduce the quantity \\(f_s (\\vec{x}, \\vec{v}, t)\\), which we want to compute through average on mesoscopic scales: \n%\n\\begin{align}\nf_s (\\vec{x}, \\vec{v}, t) = \\expval{N_s (\\vec{x}, \\vec{v}, t)}_{\\Delta V}\n\\,.\n\\end{align}\n\nThe true phase space density will then be \n%\n\\begin{align}\nN_s (\\vec{x}, \\vec{v}, t) = f_s (\\vec{x}, \\vec{v}, t) + \\delta f_s\n\\,,\n\\end{align}\n%\nwhere the fluctuations are assumed to average to zero. \nWe can write a similar expression for the electric and magnetic fields: \n%\n\\begin{align}\n\\vec{E}^{\\text{micro}} &= \\vec{E} + \\delta \\vec{E} \\\\\n\\vec{B}^{\\text{micro}} &= \\vec{B} + \\delta \\vec{B}\n\\,.\n\\end{align}\n\nThe averaged KD equation then becomes: \n%\n\\begin{align}\n\\dv{f_s}{t} + \\vec{v} \\cdot \\nabla_x f_s + \\frac{q_s}{m_s} \n\\qty[\\vec{E} + \\frac{1}{c} \\vec{v} \\times \\vec{B}] \\vec{\\nabla}_v f_s = - \\frac{q_s}{m_s} \\expval{\n    \\qty( \\delta \\vec{E} + \\frac{1}{c} \\vec{v} \\times \\delta \\vec{B} ) \\cdot \\vec{\\nabla}_v \\delta f_s\n}\n\\,.\n\\end{align}\n\nThe interaction and collision terms are \\emph{quadratic} in the fluctuations. \nIf we neglect this term (which is typically called a ``correlation'' term), we get the \\textbf{Vlasov} equation: \n%\n\\begin{align}\n\\pdv{f_s}{t} + \\vec{v} \\cdot \\vec{\\nabla}_x f_s + \\frac{q_s}{m_s} \\cdot \\qty[ \\vec{E} + \\frac{\\vec{v} \\times \\vec{B}}{c}] \\vec{\\nabla}_v f_s = 0\n\\,.\n\\end{align}\n\nWe can do the same thing to the Maxwell equations, using an averaged version of the charge and current densities.\n\nWe will need to generalize to the relativistic case: we move to \\((\\vec{x}, \\vec{p})\\) phase space. \nFor relativistic particles, the Lorentz force reads \n%\n\\begin{align}\n\\vec{\\dot{p}} = q_s \\qty[\\vec{E} + \\frac{\\vec{v} \\times \\vec{B}}{c}]\n\\,.\n\\end{align}\n\nThe source terms in the Maxwell equations will be integrated in \\(\\dd[3]{p}\\), but for the charge current we will have an integral \\(\\int \\dd[3]{p} \\vec{v} f_s\\). \n\nThe relativistic Vlasov equation is then readily derived with minor modifications, and reads \n%\n\\begin{align}\n\\pdv{f_s}{t} + \\vec{v} \\cdot \\vec{\\nabla}_x f_s + q_s \\qty[ \\vec{E} + \\frac{\\vec{v} \\times \\vec{B}}{c}] \\vec{\\nabla}_p f_s = 0 \n\\,.\n\\end{align}\n\nLet us now move to the nonrelativistic plasma again, and assume we are at zero temperature. \nWe will then make a small perturbation: the ions will be stationary in first approximation. \nWill the Vlasov equation contain the plasma waves we derived earlier? \n\nWe only write it for electrons, so \n%\n\\begin{align}\n\\pdv{f}{t} + \\vec{v} \\cdot \\vec{\\nabla}_x f_s \n- \\frac{e}{m_e} \\qty[\\vec{E} + \\frac{\\vec{v} \\times \\vec{B}}{c}]_\\alpha \\pdv{f}{v_\\alpha } = 0\n\\,,\n\\end{align}\n%\nwhere in the second term we are adopting the Einstein convention, summing over \\(\\alpha \\). \n\nWe will assume that there is no magnetic field perturbation: this is the same thing we did in the plasma waves, specifically in assuming that \\(\\mathbb{K}\\) is diagonal.\n\n\\todo[inline]{is this correct?}\n\nIn the stationary configuration there is \\(\\vec{E} = 0\\). \nTo linear order, the perturbed equation will read \n%\n\\begin{align}\n\\pdv{ \\delta f}{t} + \\vec{v} \\cdot \\nabla \\delta f + \\frac{e}{m_e} \\nabla \\varphi _\\alpha \\pdv{f}{v_\\alpha } = 0\n\\,.\n\\end{align}\n\n\\todo[inline]{But isn't \\(f = \\text{const}\\) at zeroth order?}\nWe want to assume that the plasma is cold! \n\nThe electric potential \\(\\varphi \\) will satisfy \n%\n\\begin{align}\n- \\nabla^2 \\varphi = - 4 \\pi e \\int \\dd[3]{v} \\delta f\n\\,.\n\\end{align}\n\nWe then move to Fourier space: \n%\n\\begin{align}\n- i \\omega \\widetilde{\\delta f} + \ni \\vec{k} \\cdot \\vec{v} \\widetilde{\\delta f} \n+ \\frac{e}{m_e} i k_\\alpha  \\widetilde{\\varphi} \\pdv{f}{v_\\alpha } = 0\n\\,,\n\\end{align}\n%\nbut the electric potential will satisfy \n%\n\\begin{align}\nk^2 \\widetilde{\\varphi} = - 4 \\pi e \\int \\dd[3]{v} \\widetilde{\\delta f} \n\\,,\n\\end{align}\n%\nso we get \n%\n\\begin{align}\n\\widetilde{\\delta f} \\qty[ i \\vec{k} \\cdot \\vec{v} - i \\omega ] &= \n- \\frac{e}{m_e} \\widetilde{\\varphi} k_\\alpha \\pdv{f}{v_\\alpha }  \\\\\n\\widetilde{\\delta f} &= - \\frac{e}{m_e} \\widetilde{\\varphi} \\frac{k_\\alpha \\pdv*{f}{v_\\alpha }}{\\vec{k} \\cdot \\vec{v} - \\omega }  \n\\,,\n\\end{align}\n%\nwhich we substitute into the integral for \\(\\widetilde{\\varphi}\\): \n%\n\\begin{align}\n\\widetilde{\\varphi} = \\frac{4 \\pi e^2}{k^2m_e} \\widetilde{\\varphi} k_\\alpha \\int \\dd[3]{v}  \\pdv{f}{v_\\alpha } \\frac{1}{\\vec{k} \\cdot \\vec{v} - \\omega }\n\\,,\n\\end{align}\n%\nso the allowed perturbations are those which make this equation true (for arbitrary \\(\\varphi \\)). \nFor now we have not assumed that the electrons are cold: this will enter in how we write the unperturbed \\(f\\). \n\nThe assumptions of the electrons being cold can be modelled as \\(f = n_0 \\delta (\\vec{v})\\): therefore, we need to integrate by parts. \n\nSuppose that the \\(z\\) axis is along \\(k\\): then, the integrand reads \n%\n\\begin{align}\n\\int \\dd{v_x} \\dd{v_y} \\dd{v_z} \\pdv{f}{v_\\alpha } \\frac{1}{k v_z - \\omega } &=\n\\int \\dd{v_x} \\dd{v_y} \\dd{v_z} f \\frac{1}{(k v_z - \\omega)^2 }  \\\\\n&= \\int \\dd{v_x} \\dd{v_y} \\delta (v_x) \\delta (v_y) n_0 \\frac{k}{\\omega^2} = \\frac{n_0 k }{ \\omega^2}\n\\,,\n\\end{align}\n%\nso the equation just reads \n%\n\\begin{align}\n1 - \\frac{4 \\pi e^2 n_0 }{k^2 m_e} \\frac{k^2}{\\omega^2} \\implies \\omega^2 = \\frac{4 \\pi e^2 n_0 }{m_e} = \\omega_p^2\n\\,.\n\\end{align}\n\nAt the very least, this more complicated approach allows us to recover the results we expected. \n\n% \\subsection{}\n\\section{Alfvén waves}\n\nNext time, we will add one complication: a global, ordered magnetic field. \n\nWe know that this happens, for example, in spiral galaxies like our own: we observe large-scale magnetic fields.  \n\nMuch of the physics of the transport of non-thermal particles will be affected by these magnetic fields. \n\nThe perturbation of the two coupled Vlasov equations under the effect of this external \\(\\vec{B}\\) field will yield what are called \\textbf{Alfvén waves}.\n\n% We will also find a simplification of the \n\n\\end{document}\n", "meta": {"hexsha": "b22c14f9eaf927d1594a2e2902422ccb4b491a21", "size": 10436, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "phd_courses/theoretical_high_energy_astroparticle/nov18.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "phd_courses/theoretical_high_energy_astroparticle/nov18.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phd_courses/theoretical_high_energy_astroparticle/nov18.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 37.8115942029, "max_line_length": 257, "alphanum_fraction": 0.6647182829, "num_tokens": 3663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.30994656581204544}}
{"text": "\\subsubsection{\\stid{3.03} LLNL ATDM Math Libraries}\r\n\r\n\\paragraph{Overview}\r\n\r\nThe LLNL ATDM Mathematical Libraries project performs work in the MFEM library\r\n\\cite{MFEM} that is focused on providing high-performance mathematical algorithms\r\nand finite element discretizations to next-gen high-order ECP/ATDM\r\napplications. A main component of these efforts is the development of\r\nATDM-specific physics enhancements in the finite element algorithms in MFEM and\r\nthe MFEM-based BLAST Arbitrary Lagrangian-Eulerian (ALE) code \\cite{BLAST}, in\r\norder to provide efficient discretization components for LLNL's ATDM efforts,\r\nincluding the MARBL application (ECP's LLNLApp).\r\n\r\nA second main task in the project is the development of unique unstructured\r\nadaptive mesh refinement (AMR) algorithms in MFEM, that focus on generality,\r\nparallel scalability, and ease of integration in unstructured mesh\r\napplications. The new AMR capabilities can benefit a variety of ECP apps that\r\nuse unstructured meshes, as well as many other applications in industry and the\r\nSciDAC program.\r\n\r\nAnother aspect of the work is the preparation of the MFEM finite element library\r\nand related codes for exascale platforms by using mathematical algorithms and\r\nsoftware implementations that exploit increasing on-node concurrency targeting\r\nmultiple complex architectures (e.g. GPUs). This part of the project is\r\nsynergistic with and leverages efforts from the ECP CEED co-design center.\r\n\r\nMFEM is an open-source finite element library with ~3000 downloads/year from 70+\r\ncountries. It is freely available at \\url{mfem.org}, on GitHub\r\nat \\url{github.com/mfem}, where the MFEM community includes more than 165\r\nmembers), as well as via Spack and OpenHPC. The application outreach and the\r\nintegration in the ECP ecosystem is further facilitated by MFEM's participation\r\nin ECP's xSDK project.\r\n\r\n\\paragraph{Key Challenges}\r\n\r\nThe key challenges addressed by the LLNL ATDM Mathematical Libraries project are:\r\n\r\n\\noindent\r\n{\\bf \\em Robust high-order finite element methods for ALE compressible flow.}\r\nWhile high-order methods offer significant advantages in terms of HPC performance,\r\ntheir application to complicated ALE problems requires careful considerations to\r\ncontrol oscillations and ensure accuracy.\r\n\r\n\\begin{figure}[htb]\r\n\\centering\r\n\\includegraphics[width=\\textwidth]{projects/2.3.3-MathLibs/2.3.3.03-LLNL-ATDM-MathLibs/mfem-amr}\r\n\\caption{\\label{fig:mfem-amr}AMR implementation in MFEM allows many applications to benefit from non-conforming adaptivity, without significant changes in their codes.}\r\n\\end{figure}\r\n\r\n\\noindent\r\n{\\bf \\em Scalable algorithms for unstructured adaptive mesh refinement.}\r\nAdaptive mesh refinement is a common way to increasing application efficiency\r\nin problems with localized features. While block-structured AMR has been\r\nwell-studied, applying AMR in unstructured settings is challenging, especially\r\nin terms of derefinement, anisotropic refinement, parallel rebalance and\r\nscalability.\r\n\r\n\\noindent\r\n{\\bf \\em GPU porting of finite element codes.}\r\nDue to the relatively high complexity of the finite element machinery, MFEM,\r\nBLAST and related codes use object-oriented C++ design that allows generality\r\nand flexibility, but poses challenges in terms of porting to GPU architectures.\r\nFinding the right balance between generality and performance in the GPU context\r\nis an important challenge for many finite element-based codes that remains\r\noutstanding in the current software and programming model environment.\r\n\r\n\\paragraph{Solution Strategy}\r\n\r\nThe MFEM team has performed and documented a lot of research in\r\nhigh-performance mathematical algorithms and finite element discretizations\r\nof interest to ATDM applications\r\n\\cite{BLAST18,BLASTFCT18,BLASTFCT17,BLAST16,BLAST14,BLAST13,BLAST12,BLAST11}.\r\nOur work has demonstrated that the high-order finite element approach can\r\nsuccessfully handle coupled multi-material ALE, radiation-diffusion and MHD.\r\nWe have also shown how high-order methods can be adapted for monotonicity\r\n(positivity preservation), handling of artificial viscosity (shock capturing),\r\nsub-zonal physics via closure models, etc.\r\n\r\nTo enable many applications to take advantage of unstructured mesh adaptivity,\r\nthe MFEM team is developing AMR algorithms at library level, targeting both\r\n{\\em conforming} local refinement on simplex meshes and {\\em non-conforming}\r\nrefinement for quad/hex meshes. Our approach is fairly general, allowing for\r\nany high-order finite element space, H1, H(curl), H(div), on any high-order\r\ncurved mesh in 2D and 3D, arbitrary order hanging nodes, anisotropic refinement,\r\nderifenement and parallel load balancing.\r\nAn important feature of our library approach is that it is independent of\r\nthe physics, and thus easy to incorporate in apps, see Figure \\ref{fig:mfem-amr}.\r\n\r\nAs part of the efforts in the ECP co-design Center for Efficient Exascale\r\nDiscretizations (CEED), the MFEM team is also developing mathematical algorithms\r\nand software implementations for finite element methods that exploit increasingq\r\non-node concurrency targeting multiple complex architectures (e.g. GPUs). This\r\nwork includes the libCEED low-level API library, the Laghos miniapp, and several\r\nother efforts available through CEED.\r\n\r\nTo reach its many customers and partners in NNSA, DOE Office of Science, academia\r\nand industry, the MFEM team delivers regular releases on GitHub (e.g. mfem-3.3 and\r\nmfem-3.3.2 in 2017) that include detailed documentation and many example codes.\r\nCode quality is ensured by smoke tests with Travis CI on Linux, Mac, Windows and\r\nnightly regression testing at LLNL.\r\n\r\n\\paragraph{Recent Progress}\r\n\r\nSelected recent highlights:\r\n\\begin{itemize}\r\n\\item\r\nNew optimized version of parallel AMR in MFEM, including construction of parallel interpolation, parallel refinement and rebalancing, demonstrated excellent weak and strong scalability during runs on the full Vulcan BG/Q machine at LLNL (400K MPI tasks).\r\n\\item\r\nAn interface for the new TMOP mesh optimization capabilities from mfem-3.3.2 was completed in the BLAST code, so that its remesh phase can use the TMOP functionality.\r\n\\item\r\nCompleted initial version of multi-group radiation-diffusion in BLAST.\r\n\\item\r\nParticipated in the ATDM L2 milestone for MARBL, ``Demonstration of Modular Transport Capability in a Multi-Physics Code'', which included MFEM support for high-order (HO) to low-order-refined (LOR) field transfer.\r\n\\item\r\nBLAST's closure model was improved by separating the material energies into finite element and point-based parts, avoiding L2 projections of highly oscillatory modes.\r\n\\item MFEM v3.3.2 was released with many new features including: support for high-order mesh optimization, xSDK support, integration with STRUMPACK, 5 new examples and miniapps, physical-to-reference space mapping, continuous integration testing on Linux, Mac and Windows, and more.\r\n\\item MFEM v3.3 was released with many new features including: support for PETSc, SUNDIALS, CMake, matrix-free preconditioning, parallel mesh format, 36 new integrators, 16 new examples, and more.\r\n\\item Moved main MFEM development to GitHub, including many internal branches and pull requests.\r\n\\end{itemize}\r\n\r\n\\paragraph{Next Steps}\r\n\r\nOur next steps include:\r\nprepare and release mfem-3.4; continue to attend and contribute to the weekly MARBL and BLAST meetings;\r\ncomplete an initial draft of MFEM's unified interface extensions to support GPUs and other accelerators;\r\nand provide support for the upcoming MARBL L2 milestones.\r\n\r\n", "meta": {"hexsha": "e39a2657c7a12e652c3861a635fc6e438997fed6", "size": 7583, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "projects/2.3.3-MathLibs/2.3.3.03-LLNL-ATDM-MathLibs/2.3.3.03-LLNL-ATDM-MathLibs.tex", "max_stars_repo_name": "tgamblin/ECP-ST-CAR-PUBLIC", "max_stars_repo_head_hexsha": "74d6fb18bae7ff1c32b78dd8cd7ae29e91218c33", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "projects/2.3.3-MathLibs/2.3.3.03-LLNL-ATDM-MathLibs/2.3.3.03-LLNL-ATDM-MathLibs.tex", "max_issues_repo_name": "tgamblin/ECP-ST-CAR-PUBLIC", "max_issues_repo_head_hexsha": "74d6fb18bae7ff1c32b78dd8cd7ae29e91218c33", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "projects/2.3.3-MathLibs/2.3.3.03-LLNL-ATDM-MathLibs/2.3.3.03-LLNL-ATDM-MathLibs.tex", "max_forks_repo_name": "tgamblin/ECP-ST-CAR-PUBLIC", "max_forks_repo_head_hexsha": "74d6fb18bae7ff1c32b78dd8cd7ae29e91218c33", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.2421875, "max_line_length": 283, "alphanum_fraction": 0.8035078465, "num_tokens": 1659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.30994656581204544}}
{"text": "\\documentclass{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage[super,square]{natbib}\n\\usepackage{tabularx}\n\\usepackage{parskip}\n\\usepackage[margin=1.4in]{geometry}\n\\usepackage{csquotes}\n\\usepackage{mathrsfs}\n\\usepackage{amsmath}\n\\usepackage{amsfonts}\n\\usepackage{amsthm}\n\\usepackage{amssymb}\n\\usepackage{hyperref}\n\\usepackage{graphicx}\n\\usepackage{float}\n\\usepackage{mdframed}\n\\usepackage[dvipsnames]{xcolor}\n\n% Book headers\n\\usepackage{fancyhdr}\n\\pagestyle{fancy}\n\\fancyhf{}\n\\fancyhead[L]{\\rightmark}\n\\fancyhead[R]{\\thepage}\n\\renewcommand{\\headrulewidth}{0pt}\n\n\n\\definecolor{blueish}{HTML}{CAC8FA}\n\n\\newcommand{\\comment}[1]{}\n\\newtheorem{theorem}{Theorem}[section]\n\\newtheorem{corollary}{Corollary}[theorem]\n\\newtheorem{proposition}{Proposition}[theorem]\n\\newtheorem{lemma}[theorem]{Lemma}\n\\newtheorem{identity}[theorem]{Identity}\n\n\\theoremstyle{definition}\n\\newtheorem{defn}[theorem]{Definition}\n\\newtheorem{example}[theorem]{Example}\n\\newenvironment{definition}\n  {\\vspace{8pt}\\begin{mdframed}[backgroundcolor=blueish]\\begin{defn}}\n  {\\end{defn}\\end{mdframed}\\vspace{4pt}}\n\n\n\\title{\\vspace{-3cm} Differential Geometry }\n\\author{}\n\\date{}\n\n\n\\begin{document}\n\\maketitle\n\\vspace{-1.5cm}\n\\tableofcontents\n\\newpage\n\n\\section{Prerequisites}\n\n\n\\subsection{Topology of Manifolds Intro}\nThe fundamental objects of study in differential geometry are manifolds. Roughly, an n-dimensional manifold is a mathematical object that ``locally'' looks like $\\mathbb R^n$.  Manifolds in euclidean space are described with a \\textit{regular level set}, $S = f^{-1}(a)$ which defines a smooth hypersurface $S \\subseteq R^n$. For example, the n-dimensional sphere described by:\n\\[\n    S^n = \\{ (x^0, \\dots, x^n) \\in \\mathcal R^{n+1} | (x^0)^2 + \\dots + (x^n)^2  = 1\\}.\n\\]\nAnother example is the 2-Torus, $T^2$. Given real numbers $r, R$ with $0 < r < R$, take a circle of radius $r$ in the $x-z$ plane, with center at $(R,0)$, and rotate about the $z$-axis:\n\\[\n    T^2 = \\{ (x,y,z) | (\\sqrt{x^2 + y^2} - R)^2 + z^2 + r\\}\n\\]\n\nThe sphere, the torus, the double torus, triple torus, and so on are \\textit{orientable} surfaces, which essentially means that they have two sides which you might paint in two different colors. It turns out that these are all orientable surfaces, if we consider the surfaces intrinsically and only consider surfaces that are compact in the sense that they don’t go off to infinity and do not have a boundary (thus excluding a cylinder, for example).\n\nNot all surfaces can be realized as 'embedded' in $\\mathbb R^3$; for \\textit{non-orientable surfaces} one needs to allow for self-intersections. This type of realization is referred to as an immersion: We don’t allow edges or corners, but we do allow that different parts of the surface pass through each other.  An example is the Klein bottle, which is not possible to represent as a regular level set $f^{-1}(0)$ of a function $f$ since any suface has one side where $f$ is positive and another side where $f$ is negative.\n\nThe projective plane or projective space is denoted $\\mathbb{R} P^2$ and is defined as the set of all lines (i.e., 1-dimensional subspaces) in $\\mathbb{R}^3$. we can also think of $\\mathbb{R} P^2$ as the set of antipodal (i.e., opposite) points on $S^2$. Splitting the points into those with distance $< \\epsilon$ from the equator and those $\\geq \\epsilon$ produces a Mobius strip and a two-dimensional disc. Generating a smooth curve by gluing the boundary of a Mobius strip to the boundary of a disk is depicted in what's known as Boy’s surface.\n\nAnother operation for surfaces, generalizing the procedure of ‘attaching handles’, is the connected sum Given two surfaces $\\sigma_1$ and $\\sigma_2$, remove small disks around given points $p_1 \\in \\sigma_1$ and $p_2 \\in \\sigma_2$, to create two surfaces with boundary circles. Then glue-in a cylinder connecting the two boundary circles, without creating edges. The resulting surface is denoted $\\sigma_1\\#\\sigma_2$.\n\nIt turns out that all closed, connected surfaces are obtained from either the 2-sphere $S^2$, the Klein bottle, or  $\\mathbb{R} P^2$, by attaching handles with the connected sum.\n\n\n\\subsection{Algebras}\n\nAn algebra (over the field $\\mathbb R$ of real numbers) is a \\textit{vector space} $\\mathscr{A}$, together with a \\textit{multiplication} (product) $\\mathscr{A} \\times \\mathscr{A} \\rightarrow \\mathscr{A}$, $(a,b) \\mapsto ab$ such that\n\n\\begin{enumerate}\n    \\item The multiplication is associative.\n    \\item  The multiplication map is linear in both arguments.\n\\end{enumerate}\nThe algebra is called commutative if $ab = ba$ for all $a,b \\in A$. A unital algebra is an algebra $A$ with a distinguished element $1_{\\mathscr{A}} \\in \\mathscr{A}$ (called the unit), with $1_{\\mathscr{A}} a = a = a1_{\\mathscr{A}}$ for all $a \\in \\mathscr{A}$.\n\nOne can also consider non-associative product operations on vector spaces, most importantly one has the class of \\textit{Lie algebras}. Some examples include: The space of complex numbers which is a unital, commutative algebra. $\\mathbb H \\cong \\mathbb R^4$ of quaternions which is a unital, non-commutative algebra. The space of $n\\times n$ matricies which is a noncommutative unital algebra. Given a topological space $X$, one has the algebra $C(X)$ of continuous $\\mathbb R$-valued functions.\n\nA \\textit{homomorphism} of algebras $\\phi : \\mathscr{A} \\rightarrow \\mathscr{A}'$ is a linear map preserving products: $\\phi(ab) = \\phi(a)\\phi(b)$. It is called an \\textit{isomorphism} of algebras if $\\phi$ is invertible. For the special case $\\mathscr{A}' = A$ , these are also called algebra \\textit{automorphisms} of $\\mathscr{A}$. Note that the algebra automorphisms form a group under composition.\n\n\\subsection{Derivations}\n\\begin{definition}\nA derivation of an algebra $\\mathscr A$ is a linear map $D : \\mathscr A \\rightarrow \\mathscr A$ satisfying the product rule \n\\[\n    D(a_1 a_2) = D(a_1)a_2 +a_1D(a_2).\n\\].\n\\end{definition}\n\nIf $dim A < \\infty$, a derivation is an infinitesimal automorphism of an algebra.\n\nAny given $x \\in A$ defines a derivation $D(a) = [x,a] := xa-ax$. These are called inner derivations. If $A$ is commutative (for example $A = C ^\\infty(M)$) the inner derivations are all trivial. At the other extreme, for the matrix algebra $A = \\text{Mat}\\mathbb R(n)$, one may show that every derivation is inner.\n\nIf $A$ is a unital algebra, with unit $1_A$, then $D(1A) = 0$ for all derivations $D$.\n\nGiven two derivations $D_1,D_2$ of an algebra $A$, their commutator $[D_1,D_2] = D_1 D_2 - D_2 D_1$ is again a derivation.\n\nIf the algebra $A$ is commutative, then the space of derivations is a 'left-module over $A$'. That is, if $D$ is a derivation and $x \\in A$ then $a \\mapsto (xD)(a) := xD(a)$ is again a derivation\n\n\\subsection{Equivalence Relations}\n[Omitted]\n\n\\subsection{On relation to Physics}\nIn Albert Einstein’s theory of General Relativity from 1916, space-time was regarded as a 4-dimensional 'curved' manifold with no distinguished coordinates. A local observer may want to introduce local $xyz$ coordinates to perform measurements, but all physically meaningful quantities must admit formulations that are coordinate-free. At the same time, it would seem unnatural to try to embed the 4-dimensional curved space-time continuum into some higher-dimensional flat space, in the absence of any physical significance for the additional dimensions. Some years later, gauge theory once again emphasized coordinate-free formulations, and provided physics motivations for more elaborate constructions such as fiber bundles and connections. There are many subbranches of differential geometry, for example complex geometry, Riemannian geometry, or symplectic geometry, which further subdivide into sub-sub-branches.\n\n\\section{Manifolds}\n\\subsection{Atlases and Charts}\n\nManifolds will initially be described in intrinsic or manifestly  coordinate-free terms. The basic feature of manifolds is the existence of 'local coordinates'. The transition from one set of coordinates to another should be smooth.\n\\begin{definition} \\textbf{(Smoothness and diffeomophisms)}\n\nLet $U \\subseteq \\mathbb R^m$ and $V \\subseteq \\mathbb R^n$ be open subsets. A map $F : U \\rightarrow V$ is called \\textit{smooth} if it is infinitely differentiable. The set of smooth functions from $U$ to $V$ is denoted $C^{\\infty}(U,V)$. The map $F$ is called a \\textit{diffeomorphism} from $U$ to $V$ if it is invertible, and the inverse map $F^{-1}: V \\rightarrow U$ is again smooth.\n\\end{definition}\n\n\n\\begin{definition} \\textbf{(Jacobian matrix)}\n\nFor a smooth map $F \\in C^{\\infty}(U,V)$ between open subsets $U \\subseteq R^m$ and $V \\subseteq R^n$, and any $x \\in U$, one defines the Jacobian matrix $DF(x)$ to be the $n \\times m$ matrix of partial derivatives,\n\\[\n    (DF(x))^i_j = \\frac{\\partial F^i}{\\partial x^j}\n\\]\nIts determinant is called the Jacobian matrix of $F$ at $x$.\n\\end{definition}\n\n\\begin{theorem} \\textbf{(Inverse function theorem)}\n\nThe inverse function theorem states that $F$ is a diffeomorphism if and only if it is invertible, and for all $x \\in U$, the Jacobian matrix $DF(x)$ is invertible. This means one does not actually have to check smoothness of the inverse map.\n\\end{theorem}\n\n\n\n\\begin{definition} \\textbf{(Charts)}\n\nLet $M$ be a set.\n\\begin{enumerate}\n    \\item An $m$-dimensional (coordinate) chart $(U,\\phi)$ on $M$ is a subset $U \\subseteq M$ together with a map $\\phi : U \\rightarrow R^m$ , such that $\\phi(U) \\subseteq R^m$ is open and $\\phi$ is a bijection from $U$ to $\\phi(U)$.\n    \n    \\item  Two charts $(U,\\phi)$ and $(V,\\psi)$ are called compatible if the subsets $\\phi(U \\cap V)$ and $\\psi(U \\cap V)$ are open, and the transition map\n    \\[\n        \\psi \\circ \\phi^{-1}  = \\phi(U \\cap V) \\rightarrow \\psi(U \\cap V)\n    \\]\n    is a diffeomorphism known as a change of coordinates. As a special case, charts with $U\\cap V = \\emptyset $ are always compatible.\n\\end{enumerate}\n\\end{definition}\n\n\\begin{definition} \\textbf{(Atlas)}\n\nLet $M$ be a set. An $m$-dimensional atlas on $M$ is a collection of coordinate charts $\\mathscr{A} =  \\{(U_\\alpha, \\phi_\\alpha) \\}$ such that,\n\\begin{enumerate}\n    \\item The $U_\\alpha$ cover all of $M$, i.e. $\\bigcup_\\alpha U_\\alpha = M$.\n    \\item For all indicies $\\alpha, \\beta$, the charts $(U_\\alpha, \\phi_\\alpha)$ and $(U_\\beta, \\phi_\\beta)$ are compatible.\n\\end{enumerate}\n\n\\end{definition}\n\n\\begin{definition} \\textbf{(Sterographic projection)}\n\nRegard $\\mathbb R^2$ as the coordinate subspace of $\\mathbb R^3$ on which $z = 0$ runs through the center of the sphere; the ``equator'' is the intersection of the sphere with this plane.\nLet $N = (0, 0, 1)$ be the ``north pole'', and let $M$ be the rest of the sphere. For any point $P$ on $M$, there is a unique line through $N$ and $P$, and this line intersects the plane $z = 0$ in exactly one point $P'$. Define the stereographic projection of $P$ to be this point $P'$ in the plane. \n\\end{definition}\n\n\\begin{example} \\textbf{(Atlas on the 2-sphere)}\n\nLet $S^2 \\subseteq \\mathbb R^3$ be the unit sphere. Let $n = (0,0,1)$ be the north pole, and $s =(0,0,-1)$ be the south pole, and define an atlas with two charts $(U_+,\\phi_+)$ and $(U_-,\\phi_-)$, where\n\\[\nU_+ = S^2 - {s}, U_- = S^2 - {n}\n\\]\nand the stereographic projection from the south pole is given by,\n\\begin{align*}\n    \\phi_+ : U_+ \\rightarrow \\mathbb R^2, p \\mapsto \\phi_+(p)\\\\\n    \\phi_+(x, y,z) = \\bigg( \\frac{x}{1+z},\\frac{y}{1+z} \\bigg)\n\\end{align*}\nand the stereographic projection from the north pole is given by,\n\\begin{align*}\n    \\phi_- : U_+ \\rightarrow \\mathbb R^2, p \\mapsto \\phi_-(p)\\\\\n    \\phi_-(x, y,z) = \\bigg( \\frac{x}{1-z},\\frac{y}{1-z} \\bigg).\n\\end{align*}\nThe transition map on the overlap of the two charts is,\n\\begin{equation*}\n    \\phi_- \\circ \\phi_+^{-1} (u,v) =  \\bigg( \\frac{u}{u^2 + v^2}, \\frac{v}{u^2 + v^2} \\bigg).\n\\end{equation*}\n\n\\end{example}\n\n% \\begin{example} \\textbf{(Affine lines in $\\mathbb R^2)$}\n\n% Omitted\n% \\end{example}\n\nThe 2-sphere with the atlas given by stereographic projections onto the $x-y$-plane, and the 2-sphere with the atlas given by stereographic projections onto the $y-z$-plane, should be one and the same manifold $S^2$. To resolve this, we will use the following notion of compatibility.\n\n\\begin{definition} \\textbf{(Compatibility)}\n\nSuppose $\\mathscr{A} =  \\{(U_\\alpha, \\phi_\\alpha) \\}$ is an $m$-dimensional atlas on $M$, and let $(U,\\phi)$ be another chart. Then $(U,\\phi)$ is said to be \\textit{compatible} with $\\mathscr{A}$ if it is compatible with all charts $(U_\\alpha, \\phi_\\alpha)$ of $\\mathscr{A}$\n\\end{definition}\n\nNote that  $(U,\\phi)$ is compatible with the atlas $\\mathscr{A} =  \\{(U_\\alpha, \\phi_\\alpha) \\}$ if and only if the union $\\mathscr{A} \\cup {(U,\\phi)}$ is again an atlas on $M$. This suggests defining a bigger atlas, by using all charts that are compatible with the given atlas with the following lemma.\n\n\\begin{lemma}\n\nLet $\\mathscr{A} =  \\{(U_\\alpha, \\phi_\\alpha) \\}$ be a given atlas on the set $M$. If two charts $(U,\\phi), (V,\\psi)$ are compatible with $\\mathscr{A}$, then they are also compatible with each other.\n\\end{lemma}\n\n\\begin{theorem}\n\nGiven an atlas $\\mathscr{A} =  \\{(U_\\alpha, \\phi_\\alpha) \\}$ on $M$, let $\\Tilde{\\mathscr{A}}$ be the collection of all charts $(U,\\phi)$ that are compatible with $\\mathscr{A}$. Then $\\Tilde{\\mathscr{A}}$ is itself an atlas on $M$, containing $\\mathscr{A}$. In fact, $\\Tilde{\\mathscr{A}}$ is the largest atlas containing $\\mathscr{A}$.\n\\end{theorem}\n\n\\begin{definition} \\textbf{(Maximal and equivalent atlases)}\n\nAn atlas $\\mathscr{A}$ is called \\textit{maximal} if it is not properly contained in any larger atlas. Given an arbitrary atlas $\\mathscr{A}$, one calls $\\Tilde{\\mathscr{A}}$ the maximal\natlas determined by $\\mathscr{A}$.  Two atlases are called equivalent if every chart of one atlas is compatible with every chart in the other atlas. Any maximal atlas determines an equivalence class of atlases, and vice versa.\n\\end{definition}\n\n\n\\subsection{Definition of manifold}\n\n\\begin{definition}\nAn $m$-dimensional manifold is a set $M$, together with a maximal atlas $\\mathscr{A} =  \\{(U_\\alpha, \\phi_\\alpha) \\}$ with the following properties: \n\\begin{enumerate}\n    \\item \\textbf{(Countability condition)} $M$ is covered by countably many coordinate charts in $A$. That is, there are indices $\\alpha_1, \\alpha_2, \\dots$ with\n    \\[\n        M = \\bigcup_i U_{\\alpha_i}.\n    \\]\n    \\item \\textbf{(Hausdorff condition)} For any two distinct points $p,q \\in M$ there are coordinate charts $(U_\\alpha, \\phi_\\alpha)$ and $(U_\\beta, \\phi_\\beta)$ in $A$ such that $p \\in U_\\alpha, q \\in U_\\beta$, with\n    \\[\n        U_\\alpha \\cap U_\\beta = \\emptyset.\n    \\]\n\\end{enumerate}\n\\end{definition}\n\nThe charts $(U,\\phi) \\in A$ are called (coordinate) charts on the manifold $M$. The countability condition is used for various arguments involving a proof by induction. The Hausdorff condition rules out some strange examples that don’t quite fit the idea of a space that is locally like $\\mathbb R^n$.\n\n\\begin{lemma}\n\nLet $M$ be a set with a maximal atlas $\\mathscr{A} =  \\{(U_\\alpha, \\phi_\\alpha) \\}$, and suppose $p,q \\in M$ are distinct points contained in a single coordinate chart $(U,\\phi) \\in \\mathscr{A}$. Then we can find indices $\\alpha,\\beta$ such that $p \\in U_\\alpha, q \\in U_\\beta$, with $U_\\alpha \\cap U_\\beta = \\emptyset$.\n\\end{lemma}\n\n\\subsection{Examples of manifolds}\n\\subsubsection{N-spheres}\nThe construction of an atlas for the 2-sphere $S^2$, by stereographic projection, also works for the n-sphere\n\\[\n    S^n = \\{ (x^0, \\dots, x^n) \\in \\mathcal R^{n+1} | (x^0)^2 + \\dots + (x^n)^2  = 1\\}.\n\\]\nLet $U_{\\pm}$ be the subsets obtained by removing $(\\pm 1, 0,\\dots, 0)$. Stereographic projection defines bijections $\\phi_{\\pm} : U_{\\pm} \\rightarrow \\mathbb R^{n}$,  where $\\phi_{\\pm} (x^0, x^1, \\cdots, x^n) = (u^1, \\cdots, u^n)$ with $\\displaystyle u^{i} = \\frac{x^j}{1\\pm x^0}.$\n\nWriting $u = (u^1,\\dots,u^n)$, the transition functions are given by,\n\\[\n    (\\phi_- \\circ \\phi_+^{-1})(u) = \\frac{u}{||u||^2}.\n\\]\n\n\\subsubsection{Products and n-torus}\n\nGiven manifolds $M,M'$ of dimensions $m,m'$, with atlases $\\{(U_\\alpha,\\phi_\\alpha) \\}$ and $\\{(U_\\beta,\\phi_\\beta)\\}$, the cartesian product $M \\times M'$ is a manifold of dimension $m + m'$. An atlas is given by the product charts $U_\\alpha \\times U_\\beta$ with the product maps $\\phi_\\alpha \\times \\phi_\\beta' : (x, x') \\mapsto (\\phi_\\alpha(x), \\phi_\\beta'(x'))$. For example, the 2-torus $T^2 = S^1 \\times S^1$ becomes a manifold in this way, and likewise for the n-torus, $T^n = S^1 \\times \\dots \\times S^1$.\n\n\\subsubsection{Real projective spaces}\n\nThe n-dimensional projective space $\\mathbb R P^n$, is the set of all lines $l \\subseteq \\mathbb R^{n+1}$. It may also be regarded as a quotient space,\n\\[\n\\mathbb R P^n  = (\\mathbb R^{n+1} \\setminus \\{0\\}) / \\sim\n\\]\n$\\mathbb R P^n$ has a standard atlas, $\\mathscr{A} =  {(U_0,\\phi_0),\\dots,(U)n,\\phi_n)}$ defined as follows. For $j = 0,\\dots,n,$ let $U_j = \\{(x^0 : \\dots : x^n) \\in \\mathbb R P^n | x^j \\neq 0\\}$ be the set for which the j-th coordinate is non-zero, and put \n\\[\n\\phi_j : U_j \\rightarrow \\mathbb R^n, (x^0 : \\dots : x^n ) \\mapsto \\bigg ( \\frac{x^0}{x^j} ,\\dots, \\frac{x^n}{x^j} \\bigg).\n\\]\n\nGeometrically, viewing $\\mathbb RP^n$ as the set of lines in $\\mathbb R^{n+1}$, the subset $U_j \\subseteq \\mathbb RP^n$ consists of those lines $l$ which intersect the affine hyperplane $H_j = \\{x \\in \\mathbb R^{n+1} | x^j = 1\\}$ and the map $\\phi_j$ takes such a line $l$ to its unique point of intersection $l \\cap H_j$, followed\nby the identification $H_j \\cong  \\mathbb R^n$ (dropping the coordinate $x^j = 1$). In low dimensions, we have that $\\mathbb RP^0$ is just a point, while $\\mathbb RP^1$is a circle.\n\n\\subsubsection{Complex projective spaces}\n\nSimilar to the real projective space, one can define a complex projective space $\\mathbb C P^n$ as the set of complex 1-dimensional subspaces of $\\mathbb C^{n+1}$.\n\\[\n    \\mathbb C P^n = (\\mathbb C^{n+1} \\setminus \\{0\\})/ \\sim\n\\]\nAlternatively, letting $S^{2n+1} \\subseteq \\mathbb C^{n+1} = \\mathbb R^{2n+2}$ be the 'unit sphere' consisting of complex vectors of length $||z|| = 1$, we have\n\\[\n \\mathbb C P^n = S^{2n+1} / \\sim\n\\]\nOne defines charts $(U_j ,\\phi_j)$ similar to those for the real projective space:\n\\begin{align*}\n    U_j &= \\{(z^0 : \\dots : z^n) | z^j \\neq 0\\} \\\\\n    \\phi_j : U_j \\rightarrow \\mathbb C^{2n},& \\ \\ (z^0 : \\dots : z^n ) \\mapsto \\bigg ( \\frac{z^0}{z^j} ,\\dots, \\frac{z^n}{z^j} \\bigg).\n\\end{align*}\nThe transition maps between charts are given by similar formulas as for $\\mathbb RP^n$ (just replace $x$ with $z$).  The transition maps are not only smooth but even \\textit{holomorphic}, making $\\mathbb C P^n$ an example of a complex manifold (of complex dimension $n$).\n\n\\subsubsection{Grassmannians}\nThe set $Gr(k,n)$ of all $k$-dimensional subspaces of $\\mathbb R^n$ is called the Grassmannian of $k$-planes in $\\mathbb R^n$. As a special case, $Gr(1,n) = \\mathbb RP^{n-1}$. We will show that for general $k$, the Grassmannian is a manifold of dimension $dim(Gr(k,n)) = k(n-k)$. [Omitted]\n\n\\subsubsection{Complex Grassmannians}\n\nSimilar to the case of projective spaces, one can also consider the complex Grassmannian $Gr \\mathbb C(k,n)$ of complex $k$-dimensional subspaces of $\\mathbb C^n$ . It is a manifold of dimension $2k(n-k)$, which can also be regarded as a complex manifold of complex dimension $k(n-k)$.\n\n\\subsection{Oriented manifolds}\n\nThe notion of an orientation on a manifold will become crucial later, since integration of differential forms over manifolds is only defined if the manifold is oriented.\n\n\\begin{definition} \\textbf{(Oriented atlas and manfold)}\n\nThe compatibility condition between charts $(U,\\phi),(V,\\psi)$ on a set $M$ is that the change of coordinates map $\\phi \\circ \\psi^{-1})$ is a diffeomorphism. In particular, the Jacobian matrix $D(\\phi \\circ \\psi^{-1}))$ of the transition map is invertible, and hence has non-zero determinant.  If the determinant is $> 0$  everywhere, then we say $(U,\\phi),(V,\\psi)$ are \\textit{oriented-compatible}.  An \\textit{oriented atlas} on $M$ is an atlas such that any two of its charts are oriented-compatible; a \\textit{maximal oriented atlas} is one that contains every chart that is oriented-compatible with all charts in this atlas. An \\textit{oriented manifold} is a set with a maximal oriented atlas, satisfying the Hausdorff and countability conditions. A manifold is called orientable if it admits an oriented atlas.\n\n\\end{definition}\n\nThe spheres $S^n$ are orientable. To see this, consider the atlas with the two charts given by stereographic projections. The Jacobian matrix $D(\\phi_-, \\psi^{-1})_+)(u)$ has determinant of $-||u||^{-2n}$ which  is not an oriented atlas. To remedy this, simply compose one of the charts, with the map $(u_1,u_2,\\dots,u_n) \\mapsto (-u_1,u_2,\\dots,u_n)$; then with the resulting new coordinate map $\\Tilde{\\phi}_-$ the atlas $(U_+,\\phi_+),(U_-,\\Tilde{\\phi}_-)$ will be an oriented atlas.\n\nOne can show that the real projective space $\\mathbb R P^n$ is orientable if and only if $n$ is odd or $n = 0$. More generally, the Grassmannians space $Gr(k,n)$ is orientable if and only if $n$ is even or $n = 1$. The complex projective spaces $\\mathbb C P^n$ and complex Grassmannians $Gr \\mathbb C(k,n)$ are all orientable. This\nfollows because the transition maps for their standard charts, as maps between open subsets of $\\mathbb C^m$, are actually complex-holomorphic, and this implies that as real maps, their Jacobian has positive determinant.\n\n\n\\subsection{Open subsets}\n\nLet $M$ be a set equipped with an $m$-dimensional maximal atlas $\\mathscr{A} =  \\{(U_\\alpha, \\phi_\\alpha) \\}$.\n\n\\begin{definition} \\textbf{(Open subset)}\n\nA subset $U \\subseteq M$ is open if and only if for all charts $(U_\\alpha, \\phi_\\alpha) \\in \\mathscr{A}$ the set $\\phi_\\alpha(U  \\cap U_\\alpha)$ is open.\n\\end{definition}\n\n\\begin{proposition}\n\nGiven $U \\subseteq M$, let $ \\mathscr{B} \\subseteq \\mathscr{A}$ be any collection of charts whose union contains $U$. Then $U$ is open if and only if for all charts $(U_\\beta,\\phi_\\beta)$ from $\\mathscr{B}$, the sets $\\phi_{\\beta}(U \\cap U_\\beta)$ are open.\n\\end{proposition}\n\nThis means that to check that a subset $U$ is open, it is not actually necessary to verify this condition for all charts. As the above proposition shows, it is enough to check for any collection of charts whose union contains $U$. In particular, we may take $\\mathscr{A}$ to be any atlas, not necessarily a maximal atlas.\n\n\n\nIf $\\mathscr{A}$  is an atlas on $M$, and $U \\subseteq M$ is open, then $U$ inherits an atlas by restriction:\n\\[\n    \\mathscr{A}  = \\{ (U \\cap U_\\alpha, \\phi_\\alpha |_{U \\cap U_\\alpha } ) \\}\n\\]\n\n\\begin{proposition}\nAn open subset of a manifold is again a manifold.\n\\end{proposition}\n\n\\begin{proposition}\nLet $M$ be a set with an $m$-dimensional maximal atlas. The collection of all open subsets of M has the following properties\n\\begin{enumerate}\n    \\item $\\emptyset, M$ are open.\n    \\item The intersection $U \\cap U'$ of any two open sets $U,U'$ is again open.\n    \\item The union $\\cap_i U_i$ of an arbitrary collection $U_i, i \\in I$ of open sets is again open.\n\\end{enumerate}\n\\end{proposition}\n\n\nThese properties mean, by definition, that the collection of open subsets of $M$ define a \\textit{topology} on $M$. This allows us to adopt various notions from topology:\n\n\\begin{enumerate}\n    \\item A subset $A \\subseteq M$ is called \\textit{closed} if its complement $M \\setminus A$ is open.\n    \\item $M$ is called \\textit{connected} if the only subsets $A \\subseteq M$ that are both closed and open are $A = \\emptyset$ and $A = M$.\n    \\item If $U$ is an open subset and $p \\in U$, then $U$ is called an open neighborhood of $p$. More generally, if $A \\subseteq U$ is a subset contained in $M$, then $U$ is called an \\textit{open neighborhood} of $A$.\n\\end{enumerate}\n\nThe Hausdorff condition in the definition of manifolds can now be restated as the condition that any two distinct points $p,q \\in M$ have disjoint open neighborhoods. (It is not necessary to take them to be domains of coordinate charts.) It is immediate from the definition that domains of coordinate charts are open. Indeed, this gives an alternative way of defining the open sets.\n\n\\subsection{Compact subsets}\nAnother important concept from topology that we will need is the notion of \\textit{compactness}.\n\n\\begin{definition} \\textbf{(Compactness)}\n\nA subset $A \\subseteq \\mathbb R^m$ is compact if it has the following property: For every collection ${U_\\alpha}$ of open subsets of $R^m$ whose union contains $A$, the set $A$ is already covered by finitely many subsets from that collection. \n\\end{definition}\nIn short, $A \\subseteq M$ is compact if every open cover admits a finite subcover.\n\n\\begin{theorem} \\textbf{(Heine-Borel)}\n\nA subset $A \\subseteq R^m$ is compact if and only if it is closed\nand bounded.\n\\end{theorem}\n\n\\begin{proposition}\n\nIf $A \\subseteq M$ is contained in the domain of a coordinate chart $(U,\\phi)$, then $A$ is compact in $M$ if and only if $\\phi(A)$ is compact in $R^n$.\n\\end{proposition}\n\nThe proposition is useful, since we can check compactness of $\\phi(A)$ by using the Heine-Borel criterion. For more general subsets of $M$, we can often decide compactness by combining this result with the following:\n\n\\begin{proposition}\n\nIf $A_1,\\dots,A_k \\subseteq M$ is a finite collection of compact subsets, then their union $A = A_1 \\cap \\dots \\cap A_k$ is again compact.\n\\end{proposition}\n\nA simpler way of verifying compactness is by showing that they are closed and bounded subsets of $\\mathbb R^N$ for a suitable $N$.\n\n\\begin{proposition}\n\nLet $M$ be a set with a maximal atlas. If $A \\subseteq M$ is compact, and $C \\subseteq M$ is closed, then $A \\cap C$ is compact.\n\\end{proposition}\n\n\\begin{proposition}\nIf $M$ is a manifold, then every compact subset $A \\subseteq M$ is closed.\n\\end{proposition}\n\n\\newpage\n\\section{Smooth Maps}\n\\subsection{Smooth functions on manifolds}\nThe notion of smooth functions on open subsets of Euclidean spaces\ncarries over to manifolds: A function is smooth if its expression in local coordinates is smooth,\n\n\\begin{definition} \\textbf{(Smoothness)}\n\nA function $f : M \\rightarrow R$ on a manifold $M$ is called smooth if for all charts $(U,\\phi)$ the function\n\\[\n    f \\circ\\phi^{-1}: \\phi(U) \\rightarrow \\mathbb{R}\n\\]\nis smooth. The set of smooth functions on $M$ is denoted $C^{\\infty}(M)$.\n\\end{definition}\n\nSince transition maps are diffeomorphisms, it suffices to check the condition for the charts from any given atlas which need not be the maximal atlas.\n\nGiven an open subset $U \\subseteq M$, we say that a function $f$ is smooth on $U$ if its restriction $f |_U$ is smooth. (Here we are using that $U$ itself is a manifold.) Given $p \\in M$, we say that $f$ is smooth at $p$ if it is smooth on some open neighborhood\nof $p$.\n\n\\begin{lemma}\nSmooth functions $f \\in C^{\\infty}(M)$ are continuous: For every open subset $J \\subseteq \\mathbb R$, the pre-image $f^{-1}(J) \\subseteq M$ is open.\n\\end{lemma}\n\n\nFrom the properties of smooth functions on $\\mathbb R^m$, one immediately gets the following properties of smooth functions on manifolds $M$:\n\\begin{enumerate}\n    \\item If $f,g \\in C^{\\infty}(M)$ and $\\lambda, \\mu \\in \\mathbb R$, then $\\lambda f + \\mu g \\in C^\\infty(M)$.\n    \\item If $f,g \\in C^\\infty(M)$, then $f g \\in C^\\infty(M)$.\n    \\item $1 \\in C^{\\infty}(M)$ (where $1$ denotes the constant function $p \\mapsto 1$)\n\\end{enumerate}\n\nThese properties say that $C^{\\infty}(M)$ is an \\textit{algebra} with unit 1. \n\n\\begin{proposition}\nSuppose $M$ is any set with a maximal atlas, and $p \\neq q$ are two points in $M$. Then the following are equivalent:\n\\begin{enumerate}\n    \\item There are open subsets $U,V \\subseteq M$ with $p \\in U, q \\in V, U \\cap V = \\emptyset$\n    \\item There exists $f \\in C^\\infty(M)$ with $f(p) \\neq f(q)$.\n\\end{enumerate}\n\\end{proposition}\n\n\\begin{corollary} \\textbf{(Criterion for Haudorff condition)}\n\n\nA set $M$ with an atlas satisfies the Hausdorff condition if and only if for any two distinct points $p,q \\in M$, there exists a smooth function $f \\in C^\\infty(M)$ with $f(p) \\neq f(q)$. In particular, if there exists a smooth injective map $F : M \\rightarrow \\mathbb R^N$, then $M$ is Hausdorff.\n\\end{corollary}\n\n\\subsection{Smooth maps between manifolds}\n\\begin{definition} \n\nA map $F : M \\rightarrow N$ between manifolds is smooth at $p \\in M$ if there are coordinate charts $(U,\\phi)$ around $p$ and $(V,\\psi)$ around $F(p)$ such that $F(U) \\subseteq V$ and such that the composition\n\\[\n    \\psi \\circ F \\circ \\phi^{-1}: \\phi(U) \\rightarrow \\psi(V)\n\\]\nis smooth. The function $F$ is called a smooth map from $M$ to $N$ if it is smooth at all $p \\in M$.\n\n\\end{definition}\n\nThe condition for smoothness at p does not depend on the choice\nof charts. To check smoothness of $F$, it suffices to take any atlas of M with the property that $F(U_\\alpha) \\subseteq V_\\alpha$ and then check smoothness of the maps. Smooth maps $M \\rightarrow R$ are the same thing as smooth functions on $M$, $C^{\\infty} (M,R) = C^{\\infty}(M)$.\n\n\\begin{proposition}\nSuppose $F_1 : M_1 \\rightarrow M_2$ and $F_2 : M_2 \\rightarrow M_3$ are smooth maps. Then the composition $ F_2 \\circ F_1 : M_1 \\rightarrow M_3$ is smooth.\n\\end{proposition}\n\n\\subsection{Diffeomorphisms of manifolds}\n\n\\begin{definition} \\textbf{(Diffeomorphic manifolds)}\n\nA smooth map $F : M \\rightarrow N$ is called a \\textit{diffeomorphism} if it is invertible, with a smooth inverse $F^{-1} : N \\rightarrow M$. Manifolds $M,N$ are called diffeomorphic if there exists a diffeomorphism from $M$ to $N$.\n\\end{definition}\n\nIn other words, a diffeomorphism of manifolds is a bijection of the underlying sets that identifies the maximal atlases of the manifolds. Manifolds that are diffeomorphic are therefore considered 'the same manifolds'.\n\n\\begin{definition} \\textbf{(Homeomorphic manifolds)}\nA continuous map $F : M \\rightarrow N$ is called a \\textit{homeomorphism} if it is invertible, with a continuous inverse.  Manifolds $M,N$ are called homeomorphic if there exists a homeomorphism from $M$ to $N$.\n\\end{definition}\n\nManifolds that are homeomorphic are considered 'the same topologically'. Since every smooth map is continuous, every diffeomorphism is a homeomorphism.\n\n\\begin{example}\nThe standard example of a homeomorphism of smooth manifolds that is not a diffeomorphism is the map $\\mathbb R \\rightarrow \\mathbb R, x \\mapsto x^3$. Indeed, this map is smooth and invertible, but the inverse map $y \\mapsto y ^{\\frac{1}{3}}$ is not smooth.\n\\end{example}\n\nIt is quite possible for two manifolds to be homeomorphic but not diffeomorphic, these are known as \\textit{exotic manifolds}. An \\textit{exotic sphere} is homeomorphic but not diffeomorphic to the standard Euclidean n-sphere. It is known that there are no exotic manifold structures on $\\mathbb R^n$ for $\\mathbb R^n$ with $n \\neq 4$, where there are uncountably many such.\n\n\\subsection{Examples of smooth maps}\n\n\\subsubsection{Products, diagonal maps}\n\\begin{enumerate}\n    \\item  If $M,N$ are manifolds, then the projection maps are smooth. Take product charts  $U_\\alpha \\times V_\\beta$.\n    \\[\n        p^{T}_M : M \\times N  \\rightarrow M, \\ \\\n        p^{T}_N :  M \\times N \\rightarrow N\n    \\]\n    \n    \\item The diagonal inclusion is smooth. In a coordinate chart around a point, the map is the restriction to a subset of the diagonal inclusion.\n    \\[\n        \\Delta_M : M \\rightarrow  M \\times M\n    \\]\n    \n    \\item  Suppose $F : M \\rightarrow N$ and $F' : M' \\rightarrow N'$ are smooth maps. Then the direct product is smooth.\n    \\[\n        F \\times F' : M \\times M' \\rightarrow N \\times N'\n    \\]\n    \n\\end{enumerate}\n\n\\subsubsection{The diffeomorphism \\texorpdfstring{$\\mathbb R P^1 \\cong S^1$}{RP1 ∼= S1} }\n\nWe have seen that $\\mathbb R P^1 \\cong S^1$. To obtain a diffeomorphism, we construct a bijection between the standard atlases of both of the manifolds described previously\n\n\\subsubsection{The diffeomorphism \\texorpdfstring{$\\mathbb C P^1 \\cong S^2$}{CP1 ∼= S2}}\n\nBy a similar reasoning, we find $\\mathbb C P^1 \\cong S^2$. For $S^2$ we use the atlas given by stereographic projection.  Regarding $u$ as a complex number the normis just the absolute value of $u$, and the transition map becomes $u \\mapsto \\frac{1}{u}$. Note that it is not quite the same as the transition map for the standard atlas of $\\mathbb C P^1$,\nwhich is given by $u \\mapsto u^{-1}$. We obtain a unique diffeomorphism such that $\\phi_+ \\circ F \\circ \\phi_0^{-1}$ is the identity and $\\phi_- \\circ F \\circ \\phi_1^{-1}$ is complex conjugation\n\n\\subsubsection{Maps to and from projective space}\n\nThe quotient map $\\pi$ is smooth, as one verifies by checking in the standard atlas for $\\mathbb R P^n$.\n\\[\n    \\pi : \\mathbb R^{n+1} \\setminus \\{0\\} \\rightarrow \\mathbb R P^N, \\ \\ \n    x = (x^0, \\dots, x^n) \\mapsto (x^0, \\dots, x^n)\n\\]\nGiven a map $F : \\mathbb R P^n \\rightarrow N$ to a manifold $N$, let $\\Tilde{F} = F \\circ \\pi : \\mathbb R ^{n+1}\\setminus \\{0\\} \\rightarrow N$ be its composition with the projection map $\\pi : \\mathbb R ^{n+1}\\setminus \\{0\\} \\rightarrow \\mathbb R P^n$. That is, $\\Tilde{F} (x^0 , \\dots, x^n ) = F(x^0 : \\dots : x^n )$.\n\nWe claim that the map $F$ is smooth if and only the corresponding map $\\Tilde{F}$ is smooth. One direction is clear: If $F$ is smooth, then $\\Tilde{F} = F \\circ \\pi$ is a composition of smooth maps. For the other direction, assuming that $\\Tilde{F}$ is smooth, note that for the standard chart $(U_j ,\\phi_j)$, and the maps\n\\[\n    (F \\circ \\phi^{-1}_j )(u^1 ,\\dots, u^n ) = \\Tilde{F}(u^1 ,\\dots, u^i ,1,u ^{i+1} ,\\dots,u^n ),\n\\] are smooth. An analogous argument applies to the complex projective space $\\mathbb C P^n$ , taking the $x^i$ to be complex numbers $z^i$\n \n\n\\subsubsection{The Hopf fibration, a.k.a. the quotient map \\texorpdfstring{$S^{2n+1} \\rightarrow \\mathbb C P^n$}{S2n+1 to CPn}}\n\nAs mentioned above, quotient map $q : C^{n+1} \\setminus \\{0\\} \\rightarrow \\mathbb C P^n$ is smooth.  Since any class $[z] = (z 0 : \\dots : z^n )$ has a representative with $|z^0|^2 + \\dots +|z^n|^2 = 1$, and $|z^i|^2 = (x^i)^2 + (y^i)^2$ for $z^i = x^i + \\sqrt{-1}y^i$, we may also regard $\\mathbb C P^n$ as a set of equivalence classes in the unit sphere $S^{2n+1} \\subseteq \\mathbb R^{2n+2} = \\mathbb C^{n+1}$. The resulting quotient map\n\\[\n    \\pi : S^{2n+1} \\rightarrow \\mathbb C P^n \n\\]\nis again smooth, because it can be written as a composition of two smooth maps $\\pi = q \\circ \\tau$  where $\\tau : S ^{2n+1} \\mapsto \\mathbb R^{2n+2} \\setminus \\{0\\} = \\mathbb C^{n+1} \\setminus \\{0\\}$ is the inclusion map.\n\nFor any $p \\in \\mathbb C P^n$ , the corresponding fiber $\\pi^{-1} (p) \\subset S^{2n+1}$ is diffeomorphic to a circle $S^1$ (which we may regard as complex numbers of absolute value 1). Indeed, given any point $(z^0 , \\dots ,z^n ) \\in \\pi^{-1} (p)$ in the fiber, the other points are obtained as $(\\lambda z^0 ,\\dots, \\lambda z^n )$ where $|\\lambda| = 1$.\n\nIn other words, we can think of\n\\[\n    S^{2n+1} = \\bigcup_{p \\in \\mathbb C P^n} \\pi^{- 1}(p)\n\\]\nas a union of circles, parametrized by the points of $\\mathbb C P^n$. This is an example of a \\textit{fiber bundle} or \\textit{fibration}. \n\nAn import important case occurs when $n = 1$. Identifying $\\mathbb C P^1 \\cong  S^2$ as above, the map $\\pi$ becomes a smooth map $\\pi : S^3 \\rightarrow S^2$ with fibers diffeomorphic to $S^1$. This map appears in many contexts; it is called the\n\\textit{Hopf fibration}.\n\nLet $S \\in S^3$ be the 'south pole', and $N \\in S^3$ the 'north pole'. We have that $S^3 - \\{S\\} \\cong R^3$ by stereographic projection. The set $\\pi^{-1} (\\pi(S)) -  \\{S\\}$ projects to a straight line (think of it as a circle with 'infinite radius'). The fiber $\\pi ^{-1} (N)$ is a circle that goes around the straight line. If $Z \\subseteq S^2$ is a circle at a given 'latitude', then $\\pi^{-1} (Z)$ is is a 2-torus. For $Z$ close to north pole $N$ this 2-torus is very thin, while for $Z$ approaching the south pole $S$ the radius goes to infinity. Each such 2-torus is itself a union of circles $\\pi^{-1} (p), p \\in Z$. Those circles are neither the usual 'vertical' or 'horizontal' circles of a 2-torus in $\\mathbb R^3$ , but instead are 'tilted'. In fact, each such circle is a 'perfect geometric circle' obtained as the intersection of its 2-torus with a carefully positioned affine 2-plane. Moreover, any two of the circles $\\pi^{-1} (p)$ are 'linked' as though they were in a chain.\n\n\nA calculation shows that over the charts $U_+,U_-$ from stereographic projection, the Hopf fibration is just a product. That is, one has\n\\[\n    \\pi^{-1} (U_+) \\cong U_+ \\times S^1, \\ \\ \\pi^{-1} (U_-) \\cong U_- \\times S^1\n\\]\nIn particular, the pre-image of the closed upper hemisphere is a solid 2-torus $D^2 \\times S^1$ (with $D^2 = \\{ z \\in \\mathbb C| |z| \\leq 1 \\}$ the unit disk), geometrically depicted as a 2-torus in $\\mathbb R^3$ together with its interior. We hence see that the $S^3$ may be obtained by gluing two solid 2-tori along their boundaries $S^1 \\times S^1$.\n\n\\subsection{Submanifolds}\n\\begin{definition}\nA subset $S \\subseteq M$ is called a \\textit{submanifold} of dimension $k \\leq m$, if for all $p \\in S$ there exists a coordinate chart $(U,\\phi)$ around $p$ such that\n\\[\n    \\phi(U \\cap S) = \\phi(U) \\cap \\mathbb R^k .\n\\] \nCharts $(U,\\phi)$ of $M$ with this property are called submanifold charts for $S$.\n\\end{definition}\n\n\\begin{definition}\nA chart $(U, \\phi)$ such that $U \\cap S = \\emptyset$ and $\\phi (U) \\cap \\mathbb R^k = \\emptyset$ is considered a \\textit{submanifold chart}. The existence of submanifold charts is only required for points $p$ that lie in $S$. \n\\end{definition}\n\nStrictly speaking, a submanifold chart for $S$ is not a chart for $S$, but is a chart for $M$ which is adapted to $S$. Submanifold charts restrict to charts for $S$, and this may be used to construct an atlas for $S$.\n\n\\begin{proposition}\nSuppose $S$ is a submanifold of $M$. Then $S$ is a $k$-dimensional manifold in its own right, with atlas consisting of all charts $(U \\cap S, \\phi|U \\cap S)$ such that $(U,\\phi)$ is a submanifold chart.\n\\end{proposition}\n\n\\begin{example} (Open subsets). The $m$-dimensional submanifolds of an $m$-dimensional manifold are exactly the open subsets.\n\\end{example}\n\n\\begin{example} (Projective spaces). For $k < n$, regard $\\mathbb R P^k \\subseteq \\mathbb R P^n$ as the subset of all  $(x^0 : \\dots : x^n )$ for which $x^{k+1} = \\dots = x^n = 0$. These are submanifolds, with the standard charts $(U_i ,\\phi_i)$ for $\\mathbb R P^n$ as submanifold charts. Similarly, $\\mathbb C P^k \\subseteq \\mathbb C P^n$ are submanifolds, and for $n < n'$ we have $Gr(k,n) \\subseteq Gr(k,n')$ as a submanifold.\n\n\\end{example}\n\n\\begin{example} (Spheres). For $k < n$, regard $S^k \\subseteq S^n$ as the subset where the last $n-k$ coordinates are zero. These are submanifolds where the charts for $S^n$ given by stereographic projection are submanifold charts.\n\n\\end{example}\n\n\\begin{proposition}\nLet $F : M \\rightarrow N$ be a smooth map between manifolds of dimensions $m$ and $n$. Then \n\\[\n    graph(F) = \\{(F(p), p) | p \\in M \\} \\subseteq N \\times M \n\\]\nis a submanifold of $N \\times M$, of dimension equal to the dimension of $M$.\n\nThis result has the following consequence: If a subset of a manifold, $S \\subseteq M$, can be locally described as the graph of a smooth map, then $S$ is a submanifold.\n\\end{proposition}\n\n\\begin{proposition}\nThe inclusion map $i : S \\rightarrow M, p \\mapsto p,$ which takes any point of $S$ to the same point but viewed as a point of $M$, is smooth.\n\\end{proposition}\n\n\\begin{proposition}\nSuppose $S$ is a submanifold of $M$. Then the open subsets of $S$ for its manifold structure are exactly those of the form $U \\cap S$, where $U$ is an open subset of $M$.\n\\end{proposition}\n\nIn other words, the topology of $S$ as a manifold coincides with the 'subspace topology' as a subset of the manifold $M$.\n\nAs a consequence, if a manifold $M$ can be realized realized as a submanifold $M \\subseteq \\mathbb R^n$, then $M$ is compact with respect to its manifold topology if and only if it is compact as a subset of $R^n$, if and only if it is a closed and bounded subset of $\\mathbb R^n$.\n\n\\subsection{Smooth maps of maximal rank}\n\nLet $F \\in C^\\infty(M,N)$ be a smooth map. Then the fibers (level sets) $F^{-1}(q) = \\{x \\in M| F(x) = q\\}$ for $q \\in N$ need not be submanifolds, in general.\n\n\\subsubsection{The rank of a smooth map}\nLet $U \\subseteq \\mathbb R^m$ and $V \\subseteq \\mathbb R^n$ be open subsets, and $F \\in  C^\\infty(U,V)$ a smooth map.\n\n\\begin{definition}\nThe \\textit{derivative} of $F$ at $p \\in U$ is the linear map\n\\[\n    D_pF : \\mathbb R^m \\rightarrow \\mathbb R^n, \\ \\ v \\mapsto \\frac{d}{dt}\\Bigr|_{\\substack{ t=0 }} F(p+tv).\n\\]\n\nRecall that the \\textit{rank} of a linear map is the dimension of its range. The rank of $F$ at $p$ is the rank of this linear map:\n\\[\n    \\text{rank}_p(F) = \\text{rank}(D_p F).\n\\]\n\\end{definition}\n\nEquivalently, $D_p F$ is the $n \\times m$ matrix of partial derivatives and the rank of $F$ at $p$ is the rank of this matrix i.e., the number of linearly independent rows or the number of linearly independent columns.\n\n\\begin{definition}\n    Let $F \\in C^\\infty(M,N)$ be a smooth map between manifolds, and $p \\in M$. The rank of $F$ at $p \\in M$ is defined as\n    \\[\n        \\text{rank}_p(F) = \\text{rank}_{\\phi(p)}(\\psi \\circ F \\circ \\phi^{-1}).\n    \\]\n    for any two coordinate charts $(U,\\phi)$ around $p$ and $(V,\\psi)$ around $F(p)$ such that $F(U) \\subseteq V$.\n\\end{definition}\n\n\n\\begin{definition}\n    The map $F$ is said to have \\textit{maximal rank} at $p$ if\n    \\[\n        \\text{rank}_p(F) = \\text{min}(\\text{dim} M, \\text{dim} N).\n    \\]\n    A point $p \\in M$ is called a \\textit{critical point} for $F$ if $\\text{rank}_p(F) < \\text{min}(\\text{dim} M, \\text{dim} N)$.\n\\end{definition}\n\n\\subsubsection{Local diffeomorphisms}\n\n\\begin{theorem} (Inverse Function Theorem for $\\mathbb R^m$).\n\nLet $F \\in C^\\infty(U,V)$ be a smooth map between open subsets of $\\mathbb R^m$, and suppose that the derivative $D_pF$ at $p \\in U$ is invertible. Then there exists an open neighborhood $U_1 \\subseteq U$ of $p$ such that $F$ restricts to a diffeomorphism $U_1 \\rightarrow F(U_1)$.\n\\end{theorem}\n\nThe theorem tells us that for a smooth bijection, a sufficient condition for smoothness of the inverse map is that the differential (i.e., the first derivative) is invertible everywhere.\n\n\\begin{theorem} (Inverse function theorem for manifolds)\n\nLet $F \\in C^\\infty(M,N)$ be a smooth map between manifolds of the same dimension $m = n$. If $p \\in M$ is such that $\\text{rank}_p(F) = m$, then there exists an open neighborhood $U \\subseteq M$ of $p$ such that $F$ restricts to a diffeomorphism $U \\rightarrow F(U)$.\n\\end{theorem}\n\n\nA smooth map $F \\in C^\\infty(M,N)$ is called a local diffeomorphism if $\\text{dim} M = \\text{dim}N$, and $F$ has maximal rank everywhere. By the theorem, this is equivalent to the condition that every point $p$ has an open neighborhood $U$ such that $F$ restricts to a diffeomorphism $U \\rightarrow F(U)$.\n\n\\subsubsection{Level sets, submersions}\n\\begin{proposition}\nSuppose $F \\in C^\\infty(U,V)$ is a smooth map between open subsets $U \\subseteq R^m$ and $V \\subseteq R^n$, and suppose $p \\in U$ is such that the derivative $D_p F$ is surjective. Then there exists an open neighborhood $U_1 \\subseteq U$ of $p$ and a diffeomorphism $\\kappa : U_1 \\rightarrow \\kappa (U_1) \\subseteq \\mathbb R^m$ such that\n\\[\n   (F \\circ \\kappa - 1)(u^1, \\dots, u^m) = (u^{m-n+1},\\dots,u^m)\n\\]\n\nfor all $u = (u^1 ,\\dots,u^m) \\in \\kappa(U_1)$.\n\\end{proposition}\n\nAgain, this result has a version for manifolds:\n\n\\begin{theorem}\nLet $F \\in C ^\\infty(M,N)$ be a smooth map between manifolds of dimensions $m \\geq n$, and suppose $p \\in M$ is such that $\\text{rank}_p(F) = n$. Then there exist coordinate charts $(U,\\phi)$ around $p$ and $(V,\\psi)$ around $F(p)$, with $F(U) \\subseteq V$, such that \n\\[\n    (\\psi \\circ F \\circ \\phi^{-1} )(u' ,u'') = u'' \n\\]\nfor all $u = (u',u'') \\in \\phi(U)$. In particular, for all $q \\in V$ the intersection $F^{-1} (q)\\cap U$ is a submanifold of dimension $m-n$.\n\n\\end{theorem}\n\n\\begin{definition}\n    Let $F \\in C^\\infty(M,N)$. A point $q \\in N$ is called a \\textit{regular value} of $F \\in C^\\infty(M,N)$ if for all $x \\in F^{-1} (q)$, one has $\\text{rank}_x(F) = \\text{dim}N$. It is called a \\textit{singular value} if it is not a regular value.\n\\end{definition}\n\nNote that regular values are only possible if $\\text{dim}N \\leq \\text{dim}M$. Note also that all points of $N$ that are not in the image of the map F are considered regular values. We may\nrestate the theorem as follows:\n\\begin{theorem}\nFor any regular value $q \\in N$ of a smooth map $F \\in C^\\infty(M,N)$, the level set $S = F^{-1}(q)$ is a submanifold of dimension $\\text{dim}S = \\text{dim}M - \\text{dim}N$.\n\\end{theorem}\n\n\\begin{definition}\n    A smooth map $F \\in C^\\infty(M,N)$ is a \\textit{submersion} if $\\text{rank}_p(F) = \\text{dim}N$ for all $p \\in M$.\n    \n    Thus, for a submersion all level sets $F^{-1} (q)$ are submanifolds.\n\\end{definition}\n\n\\begin{example}\nRecall that $\\mathbb CP^n$ can be regarded as a quotient of $S^{2n+1}$. Using charts, one can check that the quotient map $\\pi : S^{2n+1} \\rightarrow \\mathbb C P^n$ is a submersion. Hence its fibers $\\pi^-1 (q)$ are 1-dimensional submanifolds. As discussed before these fibers are circles. As a special case, the Hopf fibration $S^3 \\rightarrow S^2$ is a submersion.\n\\end{example}\n\n\\begin{example}\n\nLet $\\mathbb H = \\mathbb C^2 = \\mathbb R^4$ be the \\textit{quaternionic numbers}. The unit quaternions are a 3-sphere $S^3$ . Generalizing the definition of $\\mathbb R P^n$ and $\\mathbb C P^n$, there are also quaternionic projective spaces, $\\mathbb H P^n$. These are quotients of the unit sphere inside $\\mathbb H^{n+1}$ , hence one obtains submersions \n\\[\n    S^{4n+3} \\mapsto \\mathbb H P^n;\n\\]\nthe fibers of this submersion are diffeomorphic to $S^3$. For $n = 1$, one can show that $\\mathbb HP^1 = S^4$, hence one obtains a submersion $\\pi : S^7 \\rightarrow S^4$ with fibers diffeomorphic to $S^3$.\n\\end{example}\n\n\n\\subsubsection{Example: The Steiner surface}\n\n[Omitted]\n\n\\subsubsection{Immersions}\n\n\\begin{proposition}\nSuppose $F \\in C^\\infty(U,V)$ is a smooth map between open subsets $U \\subseteq \\mathbb R^m$ and $V \\subseteq \\mathbb R^n$, and suppose $p \\in U$ is such that the derivative $D_p F$ is injective. Then there exist smaller neighborhoods $U_1 \\subseteq U$ of $p$ and $V_1 \\subseteq V$ of $F(p)$, with $F(U_1) \\subseteq V_1$, and a diffeomorphism $\\chi : V_1 \\rightarrow \\chi(V_1)$, such that $(\\chi \\circ F)(u) = (u,0) \\in R^m \\times R^{n-m}$\n\\end{proposition}\n\nThe manifolds version reads as follows: \n\\begin{theorem}\nLet $F \\in C^\\infty(M,N)$ be a smooth map between manifolds of dimensions $m \\infty n$, and $p \\in M$ a point with $\\text{rank}_p(F) = m$. Then there are coordinate charts $(U,\\phi)$ around $p$ and $(V,\\psi)$ around $F(p)$ such that $F(U) \\subseteq V$ and \n\\[\n    (\\psi \\circ F \\circ \\phi{-1})(u) = (u,0).\n\\]\n\nIn particular, $F(U) \\subseteq N$ is a submanifold of dimension $m$.\n\\end{theorem}\n\n\\begin{definition}\nA smooth map $F : M \\mapsto N$ is an immersion if $\\text{rank}_p(F) = \\text{dim}M$ for all $p \\in M$.    \n\\end{definition}\n\n\\begin{theorem}\nIf $M$ is a compact manifold, then every injective immersion $F : M \\rightarrow N$ is an embedding as a submanifold $S = F(M)$. By an embedding, we will mean an immersion given as the inclusion map for a submanifold.\n\\end{theorem}\n\n\\newpage\n\\section{The Tangent Bundle}\nFor embedded submanifolds $M \\subseteq \\mathbb R^n$, the tangent space $T_p M$ at $p \\in M$ can be defined as the set of all velocity vectors $v = \\gamma(0$), where $\\gamma : J \\rightarrow M$ is a smooth curve with $\\gamma(0) = p$; here $J \\subseteq R$ is an open interval around $0$. It turns out that $T_pM$ becomes a vector subspace of $\\mathbb R^n$. For a general manifold, we will define $T_pM$ as a set of directional derivatives.\n\n\\begin{definition} (Tangent spaces - first version)\n\nLet $M$ be a manifold, $p \\in M$. The \\textit{tangent space} $T_pM$ is the set of all linear maps $v : C^{\\infty}(M) \\rightarrow \\mathbb R$ of the form \n\\[\n    v(f) = \\frac{d}{dt}\\Bigr|_{\\substack{ t=0 }}  f(\\gamma(t))\n\\]\nfor some smooth curve $\\gamma \\in C^\\infty(J,M)$ with $\\gamma(0) = p$.\n\nThe elements $v \\in T_pM$ are called the \\textit{tangent vectors} to $M$ at $p$.\n\\end{definition}\n\nThe following local coordinate description makes it clear that $T_pM$ is a linear subspace of the vector space $L(C^\\infty(M),R)$ of linear maps $C^\\infty(M) \\rightarrow R$, of dimension equal to the dimension of $M$.\n\n\\begin{theorem}\nLet $(U,\\phi)$ be a coordinate chart around $p$. A linear map $v : C^\\infty(M) \\rightarrow \\mathbb R$ is in $T_pM$ if and only if it has the form, \n\\[\n    v(f) = m \\sum_{i=1}^m a^i \\frac{\\partial (f \\circ \\phi^{-1} )}{ \\partial u^i}\\Bigr|_{u = \\phi(p)}\n\\]\nfor some $a = (a^1 ,\\dots,a^m) \\in \\mathbb R^m$\n\\end{theorem}\n\nWe can use this result as an alternative definition of the tangent space, namely:\n\n\\begin{definition} (Tangent spaces - second version)\n\n\nLet $(U,\\phi)$ be a chart around $p$. The tangent space $T_pM$ is the set of all linear maps $v : C^\\infty(M) \\rightarrow \\mathbb R$ of the form \n\\[\n     v(f) = m \\sum_{i=1}^m a^i \\frac{\\partial (f \\circ \\phi^{-1} )}{ \\partial u^i}\\Bigr|_{u = \\phi(p)} \n\\]\nfor some $a = (a^1 ,\\dots,a^m) \\in \\mathbb R^m$.\n\\end{definition}\n\nIt is not immediately obvious from this second definition that $T_pM$ is independent of the choice of coordinate chart, but this follows from the equivalence with the first definition. Any choice of coordinate chart $(U,\\phi)$ around $p$ defines a vector space isomorphism $T_pM \\cong \\mathbb R^m$, taking $v$ to $a = (a^1 ,\\dots,a^m)$. In particular, we see that if $U \\subseteq \\mathbb R^m$ is an open subset, and $p \\in U$, then $T_pU$ is the subspace of the space of linear maps $C^\\infty(M) \\rightarrow \\mathbb R$ spanned by the partial derivatives at $p$.\n\nWe now describe yet another approach to tangent spaces which again characterizes ''directional derivatives'' in a coordinate-free way, but without reference to curves $\\gamma$. Note first that every tangent vector satisfies the product rule, also called the Leibniz rule:\n\\begin{lemma} (Leibniz rule)\n\nLet $v \\in T_pM$ be a tangent vector at $p \\in M$. Then \n\\[ \n    v(f g) = f(p) v(g) +v(f)g(p) \n\\]\nfor all $f,g \\in C ^\\infty(M)$.\n\\end{lemma}\nAlternatively, in local coordinates it is just the product rule for partial derivatives. It turns out that the product rule completely characterizes tangent vector:\n\n\\begin{theorem}\n\nA linear map $v : C^\\infty(M) \\rightarrow \\mathbb R$ defines an element of $T_pM$ if and only if it satisfies the Leibniz product rule.\n\\end{theorem}\n\n\\begin{definition} (Tangent spaces - third version)\n\nThe tangent space $T_pM$ is the space of linear maps $C^\\infty(M) \\rightarrow \\mathbb R$ satisfying the product rule, \n\\[\n    v(f g) = f(p)v(g) +v(f)g(p)\n\\]\nfor all $f,g \\in C^\\infty(M)$.\n\\end{definition}\n\n\\begin{definition} (Tangent Vectors)\n\nThe \\textit{velocity vectors} of curves are elements of the tangent space. Let $J \\subseteq \\mathbb R$ be an open interval, and $\\gamma \\in C^\\infty(J,M)$ a smooth curve. Then for any $t_0 \\in J$, the tangent (or velocity) vector $\\dot{\\gamma}(t_0) \\in T_{\\gamma(t_0)}M$ at time $t_0$ is given in terms of its action on functions by $(\\dot{\\gamma}(t_0))(f) = \\frac{d}{dt} \\Bigr |_{t=t_0} f(\\gamma(t))$. We will also use the notation $\\frac{d\\gamma}{dt} \\Bigr|_(t_0)$ or $\\frac{d\\gamma}{dt} \\Bigr |_{t_0}$ to denote the velocity vector.\n\\end{definition}\n\n\\subsection{Tangent map}\n\\subsubsection{Definition of the tangent map, basic properties}\n\nThe following definition generalizes the derivative to smooth maps between manifolds.\n\n\\begin{definition}\n\nLet $M,N$ be manifolds and $F \\in C^\\infty(M,N)$. For any $p \\in M$, we define the tangent map to be the linear map \n\\[\n    T_pF : T_pM \\rightarrow T_{F(p)}N\n\\]\ngiven by \n\\[\n    (T_{p}F(v))(g) = v(g \\circ F) \n\\]\nfor $v \\in T_pM$ and $g \\in C^\\infty(N)$\n\n\\end{definition}\n\n\\begin{proposition}\nIf $v \\in T_p M$ is represented by a curve $\\gamma : J \\rightarrow M$, then $(T_pF)(v)$ is represented by the curve $F\\circ \\gamma$.\n\\end{proposition}\n\n\\begin{definition}(Pull-backs, push-forwards)\n\nFor smooth maps $F \\in C^\\infty(M,N)$, one can consider various 'pull-backs' of objects on $N$ to objects on $M$, and 'push-forwards' of objects on $M$ to objects on $N$. Pull-backs are generally denoted by $F^{*}$, push-forwards by $F_{*}$. For example, functions on $N$ pull back, curves push forward on $M$, and tangent vectors to $M$ also push forward.\n\\end{definition}\n\n\n\\begin{proposition} (Chain rule)\nLet $M,N,Q$ be manifolds. Under composition of maps $F \\in C^\\infty(M,N)$ and $F0 \\in C^\\infty(N,Q)$,\n\\[\n    T_p(F'\\circ F) = T_{F(p)} F' \\circ T_pF. \n\\]\n\n\\end{proposition}\n\n\\subsubsection{Coordinate description of the tangent map}\n\\begin{proposition}\n\nLet $F \\in C^\\infty(U,V)$ is a smooth map between open subsets $U \\subseteq \\mathbb R^m $ and $V \\subseteq \\mathbb R^n$. For all $p \\in M$, the tangent map $T_pF$ is just the derivative (i.e., Jacobian matrix) $D_pF$ of $F$ at $p$.\n\\end{proposition}\n\nNow that we have recognized $TpF$ as the derivative expressed in a coordinate-free way, we may liberate some of our earlier definitions from coordinates:\n\\begin{itemize}\n    \\item  The rank of $F$ at $p \\in M$, denoted $\\text{rank}p(F)$, is the rank of the linear map $T_pF$.\n    \\item $F$ has maximal rank at $p$ if $\\text{rank}p(F) = min(dim M, dim N)$.\n    \\item $F$ is a submersion if $T_pF$ is surjective for all $p \\in M$,\n    \\item $F$ is an immersion if $T_pF$ is injective for all $p \\in M$,\n    \\item $F$ is a local diffeomorphism if $T_pF$ is an isomorphism for all $p \\in M$.\n    \\item $p \\in M$ is a critical point of $F$ is $T_pF$ does not have maximal rank at $p$.\n    \\item $q \\in N$ is a regular value of $F$ if $T_pF$ is surjective for all $p \\in F^{-1} (q)$ (in particular, if $q \\not\\in F(M))$\n    \\item $q \\in N$ is a singular value if it is not a regular value.\n\\end{itemize}\n\n\\subsection{Tangent spaces of submanifolds}\n\nSuppose $S \\subseteq M$ is a submanifold, and $p \\in S$. Then the tangent space $T_pS$ is canonically identified as a subspace of $T_pM$. \nIndeed, since the inclusion $i : S \\mapsto M$ is an immersion, the tangent map is an injective linear map, $T_pi : T_pS \\rightarrow T_pM$, and we identify $T_pS$ with the subspace given as the image of this map.\n\nRecall, the kernel of a linear mapping, also known as the null space or nullspace, is the set of vectors in the domain of the mapping which are mapped to the zero vector.\n\n\\begin{proposition}\n\nLet $F \\in C ^{\\infty}(M,N)$ be a smooth map, having $q \\in N$ as a regular value, and let $S^\\infty F^{-1} (q)$. For all $p \\in S$,\n\\[\n    T_pS = \\ker(T_pF),\n\\]\nas subspaces of $T_pM$.\n\n\\end{proposition}\n\n\\begin{corollary}\n\nSuppose $V \\subseteq \\mathbb R^n$ is open, and $q \\in \\mathbb R^k$ is a regular value of $F \\in C^\\infty(M, \\mathbb R^k)$, defining an embedded submanifold $M = F^{-1} (q)$. For all $p \\in M$, the tangent space $T_pM \\subseteq T_p \\mathbb R^n = \\mathbb R^n$ is given as \n\\[\n    T_p M = \\ker(T_pF) \\equiv \\ker(D_pF).\n\\]\n\\end{corollary}\n\n\\begin{example}\n\nVarious matrix Lie Groups are submanifolds $G \\subseteq \\text{Mat}_{\\mathbb R}(n)$, consisting of invertible matrices with the properties\n\\[\n    A,B \\in G \\implies AB \\in G, A \\in G \\implies A^{-1} \\in G.\n\\]\n\nThe tangent space to the identity (group unit) for such matrix Lie groups $G$ turns out to be important; it is commonly denoted by lower case Fraktur letters $\\mathfrak {g} = T_I G$.\n\n\\begin{enumerate}\n    \\item The \\textit{matrix Lie group} \n    \\[\n        GL(n,R) = \\{A \\in \\text{Mat} \\mathbb R(n) | \\det(A) \\neq 0 \\}\n    \\]\n    of all invertible matrices is an open subset of $\\text{Mat} \\mathbb R(n)$, hence \n    \\[\n        \\mathscr{gl}(n,R) = \\text{Mat} \\mathbb R(n)\n    \\]\n    is the entire space of matrices.\n    \n    \\item For the group $O(n)$, consisting of matrices with $F(A) := A ^T A = I$, we have computed $T_A F(X) = X^T A + AX ^T$. For $A = I$, the kernel of this map is \n    \\[\\mathfrak{o}(n) = \\{ X \\in \\text{Mat}_\\mathbb R(n) | X = -X \\}.\\]\n    \n    \\item For the \\textit{special linear group} $SL(n,R) = \\{A \\in \\text{MatR}(n)| \\det(A) = 1\\}$, given as the level set $F^{-1}(1)$ of the function $\\det : \\text{Mat}_\\mathbb R(n) \\rightarrow R$, we calculate \n    \\[\n        D_A F(X) = \\frac{d}{dt} \\Bigr |_{t=0} F(A+tX) =  \\frac{d}{dt} \\Bigr |_{t=0} \\det(A+tX) = \\frac{d}{dt} \\Bigr |_{t=0} \\det(I+tA^{-1}X) = tr(A^{-1} X),\n    \\]\n    where $tr : \\text{Mat}_\\mathbb R(n) \\rightarrow R$ is the trace (sum of diagonal entries). Hence \n    \\[ \\mathfrak{sl}(n,R) = \\{X \\in \\text{Mat}_\\mathbb R (n)| tr(X) = 0 \\}.\\]\n\\end{enumerate}\n\n\\end{example}\n\n\\subsubsection{Example: Steiner’s surface revisited}\n\n[Omitted]\n\n\\subsubsection{The tangent bundle}\n\n\\begin{proposition}\nFor any manifold $M$ of dimension $m$, the tangent bundle\n\\[\n    TM = \\bigsqcup_{p\\in M} T_p M\n\\]\n(disjoint union of vector spaces) is a manifold of dimension $2m$. The map \n\\[\n    \\pi : TM \\rightarrow M\n\\]\ntaking $v \\in TpM$ to the base point $p$, is a smooth submersion, with fibers in the tangent spaces.\n\n\\end{proposition}\n\n\\begin{proposition}\n\nFor any smooth map $F \\in C^\\infty(M,N)$, the map $T F : TM \\rightarrow TN$ given on $T_pM$ as the tangent maps $T_pF : T_pM \\rightarrow T_{F(p)}N$, is a smooth map\n\\end{proposition}\n\n\\newpage \n\\section{Vector Fields}\n\n\\subsection{Vector fields as derivations}\n\\begin{definition} (Vector Fields - first definition).\n\nA collection of tangent vectors $X_p, p \\in M$ defines a vector field $X \\in \\mathfrak X \\in M$ if and only if for all functions $f \\in C^\\infty(M)$ the function $p \\mapsto X_p(f)$ is smooth. The space of all vector fields on $M$ is denoted $\\mathfrak X(M)$. We hence obtain a linear map $X : C^\\infty(M) \\rightarrow C^\\infty(M)$ such that \n\\[\n    X (f)|_p = X_p(f).\n\\]\n\\end{definition}\nSince each $X_p$ satisfy the product rule (at $p$), it follows that $X$ itself satisfies a product rule. We can use this as an alternative definition:\n\n\\begin{definition} (Vector Fields - second definition).\n\nA vector field on $M$ is a linear map $X : C^\\infty (M) \\rightarrow C^\\infty (M)$ satisfying the product rule, \n\\[\n    X(f g) = X(f)g + f X(g)\n\\]\nfor $f,g \\in C^\\infty(M)$.\n\\end{definition}\n\nWe can also express the smoothness of the tangent vectors $X_p$ in terms of coordinate charts $(U,\\phi)$. Recall that for any $p \\in U$, and all $f \\in C^\\infty(M)$, the tangent vector $X_p$ is expressed as\n\\[\n    X_p(f) = \\sum_{i=1}^m a^i (u) \\frac{\\partial}{\\partial u^i} \\Bigr |_{u=\\phi(p)}  (f \\circ \\phi^{-1})\n\\]\n\n\\begin{proposition}\n\nThe collection of tangent vectors $X_p,\\  p \\in M$ define a vector field if and only if for all charts $(U,\\phi)$, the functions $a^i : \\phi(U) \\rightarrow \\mathbb R$ defined by \n\\[\n    X_{\\phi^{-1}(u)} (f) = \\sum_{i=1}^m a^i (u) \\frac{\\partial}{\\partial u^i} (f \\circ \\phi^{-1}),\n\\]\nare smooth.\n\n\\end{proposition}\n\n\\subsection{Vector fields as sections of the tangent bundle}\n\n\n\\begin{definition} (Vector fields – third definition).\n\nA vector field on $M$ is a smooth map $X \\in C^\\infty(M,TM)$ such that $\\pi \\circ X$ is the identity.\n\n\\end{definition}\n\nIt is common practice to use the same symbol X both as a linear map from smooth functions to smooth functions, i.e. $X : M \\rightarrow TM$, or as a map into the tangent bundle, $X : C^\\infty(M) \\rightarrow C^\\infty(M)$. The latter case can also be expressed as the 'Lie derivative' to avoid confusion: $L_X : C^\\infty(M) \\rightarrow C^\\infty(M)$\n\n\\subsection{Lie brackets}\n\\begin{theorem}\n\nFor any two vector fields $X,Y \\in \\mathfrak X(M)$ (regarded as derivations), the commutator \n\\[\n    [X,Y] := X \\circ Y - Y \\circ X : C^\\infty (M) \\rightarrow C^\\infty (M)\n\\]\nis again a vector field.\n\n\\end{theorem}\n\n\\begin{definition} (Lie Brackets)\n\nThe vector field $[X,Y] := X \\circ Y - Y \\circ X$ is called the \\textit{Lie bracket} of $X,Y \\in \\mathfrak X(M)$.\n\n\\end{definition}\n\nNote: When calculating Lie brackets $X \\circ Y - Y \\circ X$ of vector fields $X,Y$ in local coordinates, it is not necessary to work out the second order derivatives – we know in advance that these are going to cancel out.\n\nLet $S \\subseteq M$ be a submanifold. A vector field $X \\in \\mathfrak X(M)$ is called tangent to $S$ if for all $p \\in S$, the tangent vector $X_p$ lies in $T_pS \\subseteq T_pM$. (Thus $X$ restricts to a vector field $X|_S \\in \\mathfrak X(S)$.)\n\n\\begin{proposition}\nIf two vector fields $X,Y \\in \\mathfrak X(M)$ are tangent to a submanifold $S \\subseteq M$, then their Lie bracket is again tangent to $S$.\n\\end{proposition}\n\n\\subsection{Related vector fields}\n\n\\begin{definition} (F-related)\n\nLet $F \\in C^\\infty(M,N)$ be a smooth map. Vector fields $X \\in \\mathfrak X(M)$ and $Y \\in \\mathfrak X(N)$ are called $F$-related, written as $X \\sim_F Y$, if $T_pF(X_p) = Y_{F(p)}$ for all $p \\in M$.\n\n\\end{definition}\n\n\\begin{example}\n\nIf $F$ is a diffeomorphism, then $X \\sim_F Y$ if and only if $Y = F_* X$. In particular, if $N = M$, then an equation $X \\sim_F X$ means that $X$ is invariant under $F$.\n\n\\end{example}\n\nThe $F$-relation of vector fields also has a simple interpretation in terms of the 'differential operator' picture.\n\n\\begin{proposition}\nOne has $X \\sim_F Y$ if and only if for all $g \\in C^\\infty(N), \\ X(g \\circ F) = Y(g) \\circ F$.\n\n\\end{proposition}\n\n\\begin{theorem}\n\nLet $F \\in C ^\\infty(M,N)$ For vector fields $X_1,X_2 \\in \\mathfrak X(M)$ and $Y_1,Y_2 \\in \\mathfrak X(M)$, we have \n\\[\n    X_1 \\sim_F Y_1, \\ X_2 \\sim_F Y_2 \\rightarrow [X1,X2] \\sim_F [Y1,Y2].\n\\]\n\\end{theorem}\n\n\\subsection{Flows of vector fields}\nRecall, For any curve $\\gamma : J \\rightarrow M$, with $J \\subseteq \\mathbb R$ an open interval, and any $t \\in J$, the velocity vector $\\dot{\\gamma}(t) \\equiv \\frac{d\\gamma}{dt} \\in T_{\\gamma(t)}M$ is defined as the tangent vector, given in terms of its action on functions as $(\\dot{\\gamma}(t))(f) = \\frac{d}{dt} f(\\gamma(t))$. (The dot signifies a t-derivative.)\n\nEquivalently, one may think of the velocity vector as the image of $\\frac{\\partial}{\\partial t} |_{t} \\in T_tJ \\cong \\mathbb R$ under the tangent map $T_t \\gamma : \\dot{\\gamma}(t) = (T_t\\gamma)( \\frac{\\partial}{\\partial t}|_t)$.\n\n\\begin{definition}\n\nSuppose $X \\in \\mathfrak X(M)$ is a vector field on a manifold $M$. A smooth curve $\\gamma \\in C^\\infty(J, M)$, where $J \\subseteq R$ is an open interval, is called a solution curve to $X$ if $\\dot{\\gamma}(t) = X_{\\gamma(t)}$ for all $t \\in J$.\n\n\\end{definition}\n\n\nGeometrically, this means that at any given time $t$, the value of $X$ at $\\gamma(t)$ agrees with the velocity vector to $\\gamma$ at $t$, i.e. $\\frac{\\partial}{\\partial t} \\sim_\\gamma X$.\n\n\\begin{example}\nConsider first the case that $M = U \\subseteq \\mathbb R^m$. Here curves $\\gamma (t)$ are of the form,\n\\[\n    \\gamma(t) = x(t) = (x^1 (t),\\dots, x^m (t)),\n\\]\nhence,\n\\[\n    \\dot{\\gamma}(t) = \\sum_{i=1}^m \\frac{dx^i}{dt} \\frac{\\partial}{\\partial x^i} \\Bigr |_{x(t)}.\n\\]\nOn the other hand, the vector field has the form $X = \\sum_{i=1}^m a^i (x) \\frac{\\partial}{\\partial x i}$. This becomes the system of first order ordinary differential equations, \n\\[\n    \\frac{dx^i}{dt} = a^i (x(t)), i = 1,\\dots, m.\n\\]\n\\end{example}\n\n\\begin{theorem} (Existence and uniqueness theorem for ODE's)\n\nLet $U \\subseteq \\mathbb R$ m be an open subset, and $a \\in C^\\infty(U, \\mathbb R^m)$. For any given $x_0 \\in U$, there is an open interval $J_{x_0} \\subseteq \\mathbb R$ around $0$, and a solution $x : J_{x_0} \\rightarrow U$ of the ODE\n\\[\n    \\frac{d x^i}{dt} = a^i (x(t)), i = 1, \\dots, m\n\\]\nwith initial condition $x(0) = x_0$, and which is maximal in the sense that any other solution to this initial value problem is obtained by restriction to some subinterval of $J_{x0}$.\n\n\\end{theorem}\n\nThus, $J_{x_0}$ is the maximal open interval on which the solution is defined.\n\n\\begin{theorem}  (Dependence on initial conditions for ODE's)\n\nFor $a \\in C^\\infty(U,\\mathbb R^m)$ as above, the set \n\\[ \n    \\mathscr J = \\{(t, x) \\in \\mathbb R \\times U | t \\in J_x \\}.\n\\]\nis an open neighborhood of $\\{0\\} \\times U$ in $\\mathbb R \\times U$, and the map \n\\[\n    \\Phi : \\mathscr  J \\rightarrow U, \\  (t, x) \\mapsto \\Phi(t, x)\n\\]\nis smooth.\n\n\\end{theorem}\n\nFor a general vector field $X \\in \\mathfrak X(M)$ on manifolds, Equation $\\dot{\\gamma}(t) = X_{\\gamma(t)}$ becomes $\\frac{dx^i}{dt} = a^i (x(t)), i = 1,\\dots,m$ after introduction of local coordinates. The existence and uniqueness theorem for ODE’s extends to manifolds, as follows:\n\n\\begin{theorem}\n\nLet $X \\in \\mathfrak X(M)$ be a vector field on a manifold $M$. For any given $p \\in M$, there is an open interval $\\mathscr J_p \\subseteq \\mathbb R$ around $0$, and a solution $\\gamma : \\mathscr J_p \\rightarrow M$ of the initial value problem \n\\[\n    \\dot{\\gamma}(t) = X_{\\gamma(t)} ,\\  \\gamma(0) = p,\n\\]\nwhich is maximal in the sense that any other solution of the initial value problem is obtained by restriction to a subinterval. The set \n\\[\n    \\mathscr J = \\{(t, p) \\in\\mathbb R \\times M | t \\in \\mathscr J_p\\}\n\\]\nis an open neighborhood of $\\{0\\} \\times M$, and the map \n\\[\n    \\Phi : \\mathscr J \\rightarrow M,  \\ (t, p) \\mapsto  \\Phi(t, p)\n\\]\nsuch that $\\gamma(t) = \\Phi(t, p)$ solves the initial value problem mentioned above and is smooth.\n\\end{theorem}\n\nNote that the uniqueness part uses the Hausdorff property in the definition of manifolds. Indeed, the uniqueness part may fail for non-Hausdorff manifolds.\n\n\\begin{definition} (Flow)\n\nGiven a vector field $X$, the map $\\Phi : J \\rightarrow M$ is called the flow of $X$. For any given $p$, the curve $\\gamma(t) = \\Phi(t, p)$ is a solution curve.  One can also fix $t$ and consider the time-$t$ flow $\\Phi_t(p) \\equiv \\Phi(t, p).$\n\\end{definition}\n\n\nIntuitively, $\\Phi_t(p)$ is obtained from the initial point $p \\in M$ by flowing for time $t$ along the vector field $X$. One expects that first flowing for time $t$, and then flowing for time $s$, should be the same as flowing for time $t +s$. Indeed one has the following\nflow property\n\n\\begin{theorem}  (Flow property).\n\nLet $X \\in \\mathscr X(M)$, with flow $\\Phi : \\mathscr J \\rightarrow M$. Let $(t_2, p) \\in \\mathscr J$, and $t_1 \\in \\mathbb R$. Then \n\\[ \n    (t_1,\\Phi_{t_2} (p)) \\in \\mathscr J \\iff (t_1 +t_2, p) \\in \\mathscr J,\n\\]\nand one has \n\\[\n    \\phi_{t_1} (\\Phi_{t_2} (p)) = \\Phi_{t_1+t_2} (p).\n\\]\n\n\\end{theorem}\n\nWe see in particular that for any $t$, the map $\\Phi_t : U_t \\rightarrow M$ is a diffeomorphism onto its image $\\Phi_t(U_t) = U_{-t}$, with inverse $\\Phi_{-t}$. Let $X$ be a vector field, and $\\mathscr J = \\mathscr J^X$ be the domain of definition for the flow $\\Phi = \\Phi^X$ .\n\n\n\\begin{definition}\nA vector field $X \\in \\mathscr X (M)$ is called complete if $\\mathscr J^X = \\mathbb R \\times M$. Thus $X$ is complete if and only if all solution curves exist for all time.\n\\end{definition}\n\nA vector field may fail to be complete if a solution curve escapes to infinity in finite time. This suggests that a vector fields $X$ that vanishes outside a compact set must be complete, because the solution curves are 'trapped' and cannot escape to infinity:\n\n\\begin{proposition}\n\nIf $X \\in \\mathfrak X(M)$ is a vector field that has compact support, in the sense that $X |_{M-A} = 0$ for some compact subset $A$, then $X$ is complete. In particular, every vector field on a compact manifold is complete.\n\\end{proposition}\n\n\\begin{theorem}\n\nIf $X$ is a complete vector field, the flow $\\Phi_t$ defines a $1$-parameter group of diffeomorphisms. That is, each $\\Phi_t$ is a diffeomorphism and \n\\[\n    \\Phi_0 = id_M, \\  \\Phi_{t_1} \\circ \\Phi_{t_2} = \\Phi_{t_1+t_2}.\n\\]\n\nConversely, if $\\Phi_t$ is a $1$-parameter group of diffeomorphisms such that the map $(t, p) \\mapsto \\Phi_t(p)$ is smooth, the equation\n\\[\n    X_p(f) = \\frac{d}{dt} \\Bigr  |_{t=0} f(\\Phi_{t}(p)) \n\\]\ndefines a complete vector field $X$ on $M$, with flow $\\Phi_t$.\n\\end{theorem}\n\n\\begin{proposition}\nLet $F \\in C^\\infty(M,N)$, and let $X \\in \\mathscr X(M), Y \\in \\mathscr X(N)$ be complete vector fields, with flows $\\Phi^X_t , \\Phi^Y_t$.\n\\[\n    X \\sim_F Y \\iff F \\circ \\Phi^X_t = \\Phi^Y_t \\circ F\n\\]\nfor all $t$.\n\\end{proposition}\n\nIn short, vector fields are $F$-related if and only if their flows are $F$-related. $\\Phi^*_t : C^\\infty (M) \\rightarrow C^\\infty (M), \\Phi^* t : \\mathfrak X(M) \\rightarrow \\mathfrak X(M)$. \n\n\n\\subsection{Geometric interpretation of the Lie bracket}\n\nFor any smooth map $F \\in C^\\infty(M,N)$ we defined the pull-back\n\\[\n    F^* : C ^\\infty (N) \\rightarrow C ^\\infty (M), \\ g \\mapsto g \\circ F.\n\\]\nIf $F$ is a diffeomorphism, then we can also pull back vector fields: $F^* : X(N) \\rightarrow X(M), \\ Y \\mapsto F^*Y$, by the condition $(F^*Y)(F^* g) = F^* (Y(g))$ for all functions $g$. That is, $F^* Y \\sim_F Y$, or in more detail $(F^*Y)_p = (T_pF)^{ -1}Y_{F(p)}$. By Theorem 5.2, we have $F^*[X,Y] = [F^*X,F^*Y]$.\n\n\nAny complete vector field $X \\in \\mathfrak X(M)$ with flow $\\Phi_t$ gives rise to a families of pull-back map.\n\\[\n    \\Phi^*_t : C ^\\infty (M) \\rightarrow C^\\infty (M), \\  \\Phi^*_t : X(M) \\rightarrow X(M)\n\\]\n\n\\begin{definition}\nThe Lie derivative of a function f with respect to $X$ is the function\n\\[\n    L_X (f) = \\frac{d}{dt} \\Bigr |_{t=0} \\Phi^*_t f ;\n\\]\n\nthus $L_X (f) = X(f)$. The Lie derivative measures how $f$ changes in the direction of $X$. Similarly, for a vector field $Y$ one defines the Lie derivative  $L_X (Y)$ by\n\\[\n   L_X (Y) = \\frac{d} {dt}\\Bigr |_{t=0} \\Phi^*_t Y \\in X(M).\n\\]\n\\end{definition}\n\n\\begin{definition}\nFor any $X,Y \\in \\mathfrak X(M)$, the Lie derivative $L_X Y$ is just the Lie bracket: $L_X (Y) = [X,Y]$.\n\\end{definition}\n\nThus, the Lie bracket $[X,Y]$ measures 'infinitesimally' how the vector field $Y$ changes along the flow of $X$. Note that in particular, $L_XY$ is skew-symmetric in $X$ and $Y$ – this is not obvious from the definition. One can also interpret the Lie bracket as measuring how the flows of $X$ and $Y$ fail to commute.\n\n\\begin{theorem}\nLet $X,Y$ be complete vector fields, with flows $\\Phi_t ,\\Psi_s$. Then,\n\\begin{align*}\n    [X,Y] = 0 &\\iff \\Phi^*_t Y = Y \\text{for all t}\\\\\n    &\\iff \\Psi^*_s X = X \\text{for all s} \\\\\n    &\\iff  \\Phi_t \\circ \\Psi_s  = \\Psi_s \\circ \\Phi_t \\text{for all s,t.}\n\\end{align*}\n\n\\end{theorem}\n\n\n\\subsection{Frobenius theorem}\nWe saw that for any vector field $X \\in \\mathfrak X(M)$, there are solution curves through any given point $p \\in M$. The image of this curve is an (immersed) submanifold to which $X$ is everywhere tangent. One might similarly 'integral surfaces' for pairs of vector fields, and 'integral submanifolds' for collections of vector fields\n\n\\begin{definition} (Involutive)\n\nConsider a sub-bundle $E \\subseteq TM$ of rank $r$. Such a subbundle is called \\textit{involutive} if the Lie bracket of any two sections of E is again a section of $E$. For vector fields $X_i$ as above, the pointwise spans \n\\[\n    E_p = \\text{span} \\{X_1|_p,\\dots,X_r |_p\\}\n\\]\ndefine a subbundle with this property. Recall, an involution is a function that is its own inverse.\n\\end{definition}\n\n\n\\begin{definition} (Integral Submanifold)\n\nSuppose $X_1,\\dots,X_r$ are vector fields on the manifold $M$, such that the tangent vectors $X_1|_p,\\dots,X_r |_p \\in T_pM$ are linearly independent for all $p \\in M$. A $r$-dimensional submanifold $S \\subseteq M$ is called an \\textit{integral submanifold} if the vector fields $X_1,\\dots,X_r$ are all tangent to $S$.\n\nSuppose that there exists an integral submanifold $S$ through any given point $p \\in M$. Then each Lie bracket $[X_i ,X_j ] |_p \\in T_pS$, and hence is a linear combination of $X_1|_p,\\dots,X_r |_p.$ It follows that \n\\[ \n    [X_i ,X_j ] = \\sum_{k=1}^r c^k_{ij}X_k\n\\]\nfor certain (smooth) functions $c^k_{i j}$.\n\nIndeed, given $X = \\sum_{i=1}^m a^i X_i$ and $Y = \\sum^m_{i=1} b^i X_i$ with functions $a^i ,b^i$, the condition above guarantees that $E$ is involutive. Given any rank $r$ subbundle $E \\subseteq TM$ (not necessarily involutive), a submanifold $S \\subseteq M$ is\ncalled an integral submanifold if $E_p = T_pS$ for all $p \\in S$.\n\\end{definition}\n\n\n\\begin{theorem} (Frobenius theorem)\n\nLet $E \\subseteq TM$ be a subbundle of rank $r$. The following are equivalent: \n\\begin{enumerate}\n    \\item There exists an integral submanifold through every $p \\in M$.\n    \\item $E$ is involutive. \n\\end{enumerate}\n\nIn fact, if $E$ is involutive, then it is possible to find a coordinate chart $(U,\\phi)$ near any given $p$, in such a way that the subbundle $(T\\phi)(E|_U ) \\subseteq T\\phi(U)$ is spanned by the first $r \\leq m$ coordinate vector fields $\\frac{\\partial}{\\partial u^1},\\dots, \\frac{\\partial}{\\partial u^r}$.\n\n\\end{theorem}\n\n\nThus, for any involutive subbundle $E \\subseteq TM$, then any $p \\in M$ has an open neighborhood $U$ with a nice decomposition into $r$-dimensional submanifolds. One calls such a decomposition (or sometimes the involutive subbundle E itself) a (local) \\textit{foliation}. A foliation gives a decomposition into submanifolds on a neighborhood of any given point. Globally, the integral submanifolds are often only immersed submanifolds, given by immersions $i : S \\rightarrow M$ with $(T_pi)(T_pS) = E_p$ for\nall $p \\in S$.\n\n\\begin{example}\nLet $\\Phi : M \\rightarrow N$ be a submersion. Then the subbundle $E \\subseteq TM$ with fibers $E_p = \\text{ker}(T_p \\Phi) \\subseteq T_pM$ is an involutive subbundle of rank $\\dim M - \\dim N$. Every fiber $\\Phi^{-1}(q)$ is an integral submanifold.\n\\end{example}\n\n\n\\newpage\n\\section{Differential Forms}\n\n\n\n\\subsection{Review: Differential forms on \\texorpdfstring{$\\mathbb R^m$}{Rm}}\n\nDifferential forms are an approach to solving multivariable calculus problems that is independent of coordinates. They provide a unified approach to define integrands over curves, surfaces, solids, and higher-dimensional manifolds.\n\n\\begin{definition} (Wedge Product in $\\mathbb R^m$)\n\nThe \\textit{exterior product} or \\textit{wedge product} is the product operator in an exterior algebra. If $\\alpha$ and $\\beta$ are differential $k$-forms of degrees $p$ and $q$, respectively, then\n\\[\n    \\alpha \\wedge \\beta=(-1)^{pq} \\beta \\wedge \\alpha. \t\n\\]\nIt is not (in general) commutative, but it is associative, and bilinear. \n\n\\end{definition}\n\\begin{example}\nLet $\\alpha, \\beta \\in \\Omega^1(M)$. Then we define a wedge product $\\alpha \\wedge \\beta \\in \\Omega^2 (M)$, as follows:\n\\[\n    (\\alpha \\wedge \\beta)(X,Y) = \\alpha (X)\\beta(Y)-\\alpha(Y)\\beta(X).\n\\]\n\\end{example}\n\n\\begin{definition} (Differential $k$-form)\n\nA differential $k$-form on an open subset $U \\subseteq \\mathbb R^m$ is an expression of the form \n\\[\n    \\omega = \\sum_{i_1 \\dots i_k} \\omega i_1\\dots i_k dx^{i_1} \\wedge \\dots \\wedge  dx^{i_k}\n\\] \nwhere $\\omega_{i_1\\dots i_k} \\in C^\\infty(U)$ are functions, and the indices are numbers $1 \\leq i_1 < \\dots < i_k \\leq m$. The symbol $\\wedge$ denotes the exterior product of two differential forms.\n\\end{definition}\n\nLet $\\Omega^k (U)$ be the vector space consisting of such expressions, with pointwise addition. It is convenient to introduce a short hand notation $I = {i_1,\\dots,i_k}$ for the index set, and write $\\omega = \\sum_I \\omega_I dx^I$ with $\\omega_I = \\omega_{i_1 \\dots i_k}$, and $dx^I = dx^{i1} \\wedge \\dots \\wedge dx^{ik}$.\n\nSince a $k$-form is determined by these functions $\\omega_I$, and since there are $\\frac{m!}{k!(m-k)!}$ ways of picking $k$-element subsets from $\\{1,\\dots,m\\}$, the space $\\Omega^k (U)$ can be identified with vector-valued smooth functions, $\\Omega^k (U) = C^\\infty (U, \\mathbb R ^{\\frac{m!}{k!(m-k)!}})$.\n\nAn associative product operation $\\Omega^k (U) \\times \\Omega^l (U) \\rightarrow \\Omega^{k+l} (U)$ by the 'rule of computation' $dx^i \\wedge d x^j = -dx^j \\wedge d x^i$ for all $i, j$;  in particular $dx^i \\wedge dx^i = 0$.\n\n\\begin{definition}(Exterior Differential)\n\nUsing the product structure we may define the \\textit{exterior differential}\n\\[\n    d : \\Omega^k (U) \\rightarrow \\Omega^{k+1}(U),  \\ d \\bigg ( \\sum_I \\omega_I dx^I \\bigg ) = \\sum_{i=1}^m \\sum_I \\frac{\\partial \\omega_I}{\\partial x^i} dx^i \\wedge dx^I.\n\\]\n\\end{definition}\n\nThe key property of the exterior differential is the following fact:\n\\begin{proposition}\nThe exterior differential satisfies\n\\[\n    d \\circ d = 0,\n\\]\ni.e. $dd\\omega = 0$ for all $\\omega$.\n\\end{proposition}\n\n\n\\begin{example}\nConsider forms on $\\mathbb R^3$\n\\begin{itemize}\n    \\item The differential of a function $f \\in \\Omega^0 (\\mathbb R^3 )$ is a 1-form \n    \\[\n        df = \\frac{\\partial  f}{\\partial x} dx + \\frac{\\partial f}{\\partial y}  dy+ \\frac{\\partial f}{\\partial z} dz,\n    \\]\n    with components being the gradient, $\\text{grad} f = \\nabla f$.\n    \\item A 1-form $\\omega \\in \\Omega^1 (\\mathbb R^3 )$ is an expression $\\omega = f dx+gdy+hdz$ with functions $f,g,h$. The differential is \n    \\[\n        d\\omega = \\bigg( \\frac{\\partial g}{\\partial x} - \\frac{\\partial f}{\\partial y} \\bigg )\n        dx \\wedge dy +\n        \\bigg ( \\frac{\\partial h}{\\partial y} - \\frac{\\partial g}{\\partial  z} \\bigg)  dy\\wedge dz + \\bigg(\\frac{\\partial  f}{\\partial  z} - \\frac{\\partial h}{\\partial x} \\bigg )  dz\\wedge dx.\n    \\] \n    Thinking of the coefficients of $\\omega$ as the components of a function $F = (f,g,h) : U \\rightarrow \\mathbb R^3 $, we see that the coefficients of $d \\omega$ give the curl of $F$, $curl(F) = \\nabla \\times F$.\n    \n    \\item Finally, any 2-form $\\omega \\in \\Omega^2 (\\mathbb R^3 )$ may be written $\\omega = a dy \\wedge dz + b dz \\wedge dx + c dx \\wedge dy$, with $A = (a,b, c) : U \\rightarrow \\mathbb R^3$. We obtain \n    \\[\n        d\\omega = (\\frac{\\partial a}{\\partial x} + \\frac{\\partial b}{\\partial y} + \\frac{\\partial c}{\\partial z}) dx \\wedge dy \\wedge dz;\n    \\]\n    the coefficient is the divergence $div(A) = \\nabla A$ The usual properties $curl(grad(f)) = 0, div(curl(F)) = 0$ are both special cases of $d \\circ d = 0$.\n    \n\\end{itemize}\n\\end{example}\n\n\\begin{definition} (Support)\n\nThe support $supp(\\omega) \\subseteq U$ of a differential form is the smallest closed subset $Z$ so that $\\omega$ restricted to any point in the interior of $Z$ is not identically 0. Suppose $\\omega \\in \\Omega^m(U)$ is a compactly supported form of the top degree $k = m$, i.e. it is the set\n\\[\n    supp(\\omega )= \\{p\\in U : \\omega_p \\neq 0 \\}.\n\\]\nSuch a differential form is an expression $\\omega = f dx^1 \\wedge \\dots \\wedge dx^m$ where $f \\in C ^\\infty(U)$ is a compactly supported function\n\\end{definition}\n\n\\begin{definition} (Riemann Integral)\n\nOne defines the integral of $\\omega$ to be the Riemann integral:\n\\[ \n    \\int_U \\omega = \\int_{\\mathbb R^m} f(x^1 ,\\dots, x^m )dx^1 \\dots dx^m.\n\\]\n\\end{definition}\n\nNote that we can regard $\\omega$ as a form on all of $\\mathbb R^m$, due to the compact support condition.\n\nOur aim is now to define differential forms on manifolds, beginning with 1-forms. Even though 1-forms on $U \\subseteq \\mathbb R^m$ are identified with functions $U \\rightarrow \\mathbb R^m$, they should not be regarded as vector fields, since their transformation properties under coordinate changes are different. In fact, while vector fields are sections of the tangent bundle, the 1-forms are sections of its dual space, the cotangent bundle. We will thus begin with a review of dual spaces in general.\n\n\\subsection{Dual spaces}\n\n\\begin{definition} (Dual space)\n\nFor any real vector space $E$, we denote by $E^* = L(E,\\mathbb R)$ (the linear subspace) as its \\textit{dual space}, consisting of all linear maps $\\alpha : E \\rightarrow \\mathbb R$.\n\\end{definition}\n\nIf $E$ is finite-dimensional, then the dual space is also finite-dimensional, and $\\dim E^* = \\dim E$. It is common to write the value of $\\alpha \\in E^*$ on $v \\in E$ as a pairing, using the bracket notation  $\\langle \\alpha, v \\rangle := \\alpha(v);$. (In physics, it is common to use Dirac bra-ket notation $\\langle \\alpha | v \\rangle := \\alpha(v)$.)\n\n\\begin{definition} (Dual Basis)\n\nLet $e_1,\\dots, e_r$ be a basis of $E$. Any element of $E^*$ is determined by its values on these basis vectors. For $i = 1,\\dots,r$, let $e^i \\in E^*$ be the linear functional such that \n\\[\n    \\langle e^i , e_j \\rangle = \\partial^i_j = \n    \\begin{cases}\n        0, & \\text {if } i \\neq j \\\\ \n        1, & \\text{if } i = j\n    \\end{cases}\n\\]\nThe elements $e^1, \\dots, e^r$ are a basis of $E^*$; this is called the \\textit{dual basis}.\n\\end{definition}\n\nThe element $\\alpha \\in E^*$ is described in terms of the dual bases as $\\alpha = \\sum_{j=1}^r \\alpha_j e^j, \\  \\alpha_j = \\langle \\alpha, e_j \\rangle$. Similarly, for vectors $v \\in E$ we have $v = \\sum_{i=1}^r v^i e_i, \\ v^i = \\langle e^i , v \\rangle$.\n\n\\begin{definition} (Dual Map)\n\nGiven a linear map $R : E \\rightarrow F$ between vector spaces, one defines the dual map $R^* : F^* \\rightarrow E^*$ (note the direction), by setting $\\langle R^* \\beta, v \\rangle = \\langle \\beta ,R(v)\\rangle$ for $\\beta \\in F^*$ and $v \\in E$. \n\\end{definition}\n\nThis satisfies $(R^*)^* = R$, and under the composition of linear maps, $(R_1 \\circ R_2)^* = R^*_2 \\circ R^*_1$. In terms of basis $e_1,\\dots, e_r$ of $E$ and $f_1,\\dots, f_s$ of $F$, and the corresponding dual bases (with upper indices), a linear map $R : E \\rightarrow F$ is given by the matrix with entries $R_i^j = \\langle f^j , R(e_i)\\rangle$, while $R^*$ is described by the transpose of this matrix (the roles of $i$ and $j$ are reversed). Thus, $(R^*)^j_i = R_i^j$.\n\n\\subsection{Cotangent spaces}\n\n\\begin{definition} (Cotangent spaces, vectors, maps)\n\nThe dual of the tangent space $T_pM$ of a manifold $M$ is called the \\textit{cotangent space} at $p$, denoted $T^*_p M = (T_pM)^*$.\n\nElements of $T^*_p M$ are called \\textit{cotangent vectors}, or simply covectors. \n\nGiven a smooth map $F \\in C^\\infty(M, N)$, and any $p \\in M$ we have the \\textit{cotangent map} $T^*_p F = (T_pF)^* : T^*_{F(p)}N \\rightarrow T^*_p M$ defined as the dual to the tangent map.\n\n\\end{definition}\n\nThus, a co(tangent) vector at $p$ is a linear functional on the tangent space, assigning to each tangent vector at $p$ a number. The very definition of the tangent space suggests one such functional: Every function $f \\in C^\\infty(M)$ defines a linear map, $T_pM \\rightarrow \\mathbb R, v \\mapsto v(f)$. This linear functional is denoted $(d f)_p \\in T^*_p M$.\n\n\\begin{definition} (Differential)\n\nLet $f \\in C^\\infty(M)$ and $p \\in M$. The covector \n\\[\n    (d f)p \\in T^*_p M,  \\langle (d f)_p, v\\rangle = v(f).\n\\]\nis called the differential of $f$ at $p$.\n\n\\end{definition}\n\n\\begin{lemma}\nFor $F \\in C^\\infty(M,N)$ and $g \\in C^\\infty(N),$\n\\[\n    d(F^* g)_p = T^*_p F((dg)_{F(p)}).\n\\]\n\nLet $U \\subseteq \\mathbb R^m$ and $V \\subseteq \\mathbb R^n$ be open, with coordinates $x^1 , \\dots , x^m$ and $y^1,\\dots, y^n$. For $F \\in C^\\infty(U,V)$, the tangent map is described by the Jacobian matrix.\n\nThought of as matrices, the coefficients of the cotangent map are the transpose of the coefficients of the tangent map.\n\\end{lemma}\n\n\\subsection{1-forms}\n\nSimilar to the definition of vector fields, one can define co-vector fields, more commonly known as 1-forms: Collections of covectors $\\alpha_p \\in T^*_p M$ depending smoothly on the base point. \n\n\\begin{definition} (1-form)\n\nA 1-form on $M$ is a linear map \n\\[\n    \\alpha : \\mathfrak X(M) \\rightarrow C^\\infty (M), \\  X \\mapsto \\alpha(X) = \\langle \\alpha, X \\rangle,\n\\]\nwhich is $C^\\infty(M)$-linear in the sense that $\\alpha(f X) = f\\alpha(X)$ for all $f \\in C^\\infty(M), X \\in \\mathfrak X(M)$. The space of 1-forms is denoted $\\Omega^1 (M)$.\n\n\\end{definition}\n\nLet us verify that a 1-form can be regarded as a collection of covectors:\n\n\\begin{lemma}\nLet $\\alpha \\in \\Omega^1 (M)$ be a 1-form, and $p \\in M$. Then there is a unique covector in the cotangent space $\\alpha_p \\in T^*_p M$ such that $\\alpha(X)_p = \\alpha_p(X_p)$ for all $X \\in \\mathfrak X(M)$. Note, we indicate the value of the function $\\alpha(X)$ at $p$ by a subscript, just like we did for\nvector fields.\n\\end{lemma}\n\nThe first example of a 1-form is described in the following definition.\n\n\\begin{definition} (Exterior differential)\n\nThe exterior differential of a function $f \\in C^\\infty(M)$ is the 1-form $d f \\in \\Omega^1 (M)$, defined in terms of its pairings with vector fields $X \\in \\mathfrak X(M)$ as $\\langle d f, X\\rangle = X(f)$.\n\\end{definition}\n\n\n\\begin{lemma}\nLet $\\alpha : p \\mapsto \\alpha p \\in T^*_p M$ be a collection of covectors. Then $\\alpha$ defines a 1-form, with \n\\[\n    \\alpha(X)_p = \\alpha_p(X_p)\n\\]\nfor $p \\in M$, if and only if for all charts $(U,\\phi)$, the coefficient functions for $\\alpha$ in the chart are smooth\n\\end{lemma}\n\n\\subsection{Pull-backs of function and 1-forms}\n\nRecall that for any manifold $M$, the vector space $C^\\infty(M)$ of smooth functions is an algebra, with product the pointwise multiplication. Any smooth map $F : M \\rightarrow M'$ between manifolds defined an algebra homomorphism, called the pull-back\n\\[\n    F^* : C^\\infty (M') \\rightarrow C^\\infty (M), \\ \\ f \\mapsto F ^* (f) := f \\circ F. \n\\]\nThe fact that this preserves products is the following simple calculation: \n\\[\n(F^* (f)F^* (g))(p) = f(F(p))g(F(p)) = (f g)(F(p)) = F^* (f g)(p).\n\\]\nGiven another smooth map $F' : M' \\rightarrow M''$ we have $(F'\\circ F)^* \\circ F^* \\circ (F' )^*$.\n\nLet $F \\in C^\\infty(M,N)$ be a smooth map. Recall that for vector fields, there is no general 'push-forward' or 'pull-back' operation, unless $F$ is a diffeomorphism. For 1-forms the situation is better: for any $p \\in M$ one has the dual to the tangent map \n\\[\n    T^*_p F = (T_pF)^* : T^*_{F(p)}N \\rightarrow T^*_p M.\n\\]\nFor a 1-form $\\beta \\in \\Omega^1 (N)$, we can therefore define $(F^* \\beta)_p := (T^*_p F)(\\beta_{F(p)})$\n\n\\begin{lemma}\nThe collection of co-vectors $(F^*\\beta)_p \\in T^*_p M$ depends smoothly on $p$, defining a 1-form $F^*\\beta \\in \\Omega^1 (M)$.\n\\end{lemma}\n\nThe Lemma shows that we have a well-defined pull-back map $F^* : \\Omega^1 (N) \\rightarrow \\Omega^1  (M), \\beta \\mapsto F^* \\beta$. Under composition of two maps, $(F_1 \\circ F_2)^* = F^*_2 \\circ F^*_1 $. The pull-back of forms is related to the pull-back of functions, $g \\mapsto F^*g = g \\circ F$:\n\n\\begin{proposition}\nFor $g \\in C^\\infty(N)$, $F^* (dg) = d(F^* g)$.\n\\end{proposition}\n\nRecall once again that while $F \\in C^\\infty(M,N)$ induces a tangent map there is no natural push-forward operation for vector fields. By contrast, for cotangent bundles there is no naturally induced map from $T^*N$ to $T^*M$ (or the other way), yet there is a natural pull-back operation for 1-forms.  For any related vector fields $X \\sim_F Y$, and $\\beta \\in \\Omega^1 (N)$, we then have that $(F^* \\beta)(X) = F^* (\\beta(Y))$. Indeed, at any given $p \\in M$ this just becomes the definition of the pullback map.\n\n\\subsection{Integration of 1-forms}\nGiven a curve $\\gamma : J \\rightarrow M$ in a manifold, and any 1-form $\\alpha \\in \\Omega^1 (M)$, we can consider the pull-back $\\gamma^*\\alpha \\in \\Omega^1 (J)$. By the description of 1-forms on $\\mathbb R$, this is of the form $\\gamma^*\\alpha = f(t)dt$ for a smooth function $f \\in C^\\infty(J)$.\n\nTo discuss integration, it is convenient to work with closed intervals rather than open intervals. Let $[a,b] \\subseteq R$ be a closed interval. A map $\\gamma : [a,b] \\rightarrow M$ into a manifold will be called smooth if it extends to a smooth map from an open interval containing $[a,b]$. We will call such a map a smooth path.\n\n\\begin{definition} (Integral)\n\nGiven a smooth path $\\gamma : [a,b] \\rightarrow M$, we define the integral of a 1-form $\\alpha \\in \\Gamma^1 (M)$ along $\\gamma$ as\n\\[\n\\int_\\gamma \\alpha = \\int_b^a \\gamma^*\\alpha.\n\\]\n\n\\end{definition}\n\n\nThe fundamental theorem of calculus has the following consequence for manifolds. It is a special case of Stokes’ theorem\n\n\\begin{proposition}\nLet $\\gamma : [a,b] \\rightarrow M$ be a smooth path, with $\\gamma(a) = p, \\ \\gamma(b) = q$. For any $f \\in C^\\infty(M)$, we have $\\int_\\gamma d f = f(q) -  f(p)$. In particular, the integral of $d f$ depends only on the end points of the path, rather than the path itself.\n\n\\end{proposition}\n\n\\begin{definition}\n\nA 1-form $\\alpha \\in \\Omega^1(M)$ such that $\\alpha = d f$ for some function $f \\in C^\\infty(M)$ is called exact.\n\\end{definition}\n\n\\begin{example}\nConsider the $1$-form $\\alpha = y^2 e^x dx+2y e^x dy \\in \\Omega(\\mathbb R^2)$. Find the integral of $\\alpha$ along the path $\\gamma  : [0,1] \\rightarrow M, \\ t \\mapsto (sin(\\pi t/2),t^3 )$. Observe that the 1-form $\\alpha$ is exact: $\\alpha = d (y^2 e^x) = d f$ with $f(x, y) = y^2 e^x $. The path has end points $\\gamma (0) = (0,0)$ and $\\gamma (1) = (1,1)$. Hence, $\\int_\\gamma  \\alpha = f(\\gamma (1))- f(\\gamma (0)) = e$.\n\\end{example}\n\n\\subsection{2-forms}\n\\begin{definition}\nA 2-form on $M$ is a $C^\\infty(M)$-bilinear skew-symmetric map \n\\[\n    \\alpha : \\mathfrak X(M)\\times \\mathfrak X(M) \\rightarrow C^\\infty (M), (X,Y) \\mapsto \\alpha (X,Y)\n\\]\n\nHere skew-symmetry means that $\\alpha(X,Y) = -\\alpha(Y,X)$ for all vector fields $X,Y$, while $C^\\infty(M)$-bilinearity means \n\\[\n\\alpha(f X,Y) = f\\alpha(X,Y) = \\alpha(X, fY)\n\\] \nfor $f \\in C^\\infty(M)$, as well as $\\alpha(X' + X'' ,Y) = \\alpha(X',Y) + \\alpha(X'',Y)$, and similarly in the second argument. Also, if $\\alpha$ is a 2-form then so is $f\\alpha$ for any smooth function $f$.\n\\end{definition}\n\n\\begin{example}\nFor an open subset $U \\subseteq \\mathbb R^m$, a 2-form $\\omega \\in \\Omega^2 (U)$ is uniquely determined by its values on coordinate vector fields. By skew-symmetry the functions $\\omega_{i j} = \\omega  \\bigg ( \\frac{\\partial}{\\partial  x^i} , \\frac{\\partial}{ \\partial  x^j} \\bigg )$ satisfy $\\omega_{i j} = -\\omega_{ji}$; hence it suffices to know these functions for $i < j$. As a consequence, we see that the most general 2-form on $U$ is \n\\[\n    \\omega  = \\frac{1}{2} \\sum^m_{i, j=1} \\omega_{i j} dx^i \\wedge dx ^j = \\sum_{i<j} \\omega_{i j}dx^i \\wedge dx^j.\n\\]\n\n\\end{example}\n\n\\subsection{k-forms}\n\\subsubsection{Definition}\n\\begin{definition}\nLet $k$ be a non-negative integer. A k-form on $M$ is a $C^\\infty(M)$-multilinear, skew-symmetric map\n\\[\n    \\alpha : \\underbrace{\\mathfrak X(M) \\times \\dots \\times \\mathfrak X(M)}_\\text{k times} \\rightarrow C^\\infty (M).\n\\]\nThe space of k-forms is denoted $\\Omega^k (M)$; in particular $\\Omega^0 (M) = C^\\infty(M)$\n\\end{definition}\n\nHere, skew-symmetry means that $\\alpha(X_1,\\dots, X_k)$ changes sign under exchange of any two of its elements.  The $C^\\infty(M)$-multilinearity means $C^\\infty(M)$-linearity in each argument, similar to the condition for 2-forms. It implies $\\alpha$ is local in the sense that the value of $\\alpha(X_1,\\dots,X_k)$ at any given $p \\in M$ depends only on the values $X_1|p,\\dots,X_k |p \\in T_pM$. \n\nIf $\\alpha_1,\\dots,\\alpha_k$ are 1-forms, then one obtains a k-form $\\alpha =: \\alpha_1\\wedge\\dots\\wedge\\alpha_k$ by wedge product.\n\nUsing $C^\\infty$-multilinearity, a k-form on $U \\subseteq R$ m is uniquely determined by its values on coordinate vector fields. i.e. by the functions,\n\\[\n    \\alpha_{i_1\\dots i_k} = \\alpha \\bigg ( \\frac{\\partial}{\\partial x^{i_1}}, \\dots , \\frac{\\partial}{ \\partial x ^{i_k}} \\bigg )\n\\]\nMoreover, by skew-symmetry we only need to consider ordered index sets $I = {i_1,\\dots,i_k} \\subseteq {1,\\dots,m}$, that is, $i_1 < \\dots < i_k$. Using the wedge product notation, we obtain\n\\[\n\\alpha = \\sum_{i_1<\\dots<i_k} \\alpha_{i_1\\dotsi_k} dx^{i_1} \\wedge \\dots dx^{i_k}.\n\\]\n\n\\subsubsection{Wedge product}\n\n\\begin{definition} (k,l-shuffle )\n\nA permutation $s \\in \\mathfrak S_{k+l}$ is called a $k,l$-shuffle if it satisfies\n\\[\n   s(1) < \\dots < s(k), \\ \\ s(k +1) < \\dots < s(k +l).\n\\]\n\\end{definition}\n\n\\begin{definition} (Wedge product)\n\nThe wedge product of $\\alpha  \\in  \\Gamma^k (M)$, $\\beta  \\in  \\Gamma^l (M)$ is the element\n\\[\n    \\alpha \\wedge \\beta \\in  \\Gamma^{k+l} (M)\n\\] \ngiven as\n\\[\n    (\\alpha \\wedge\\beta )(X^1,\\dots ,X^{k+l}) = \\sum sign(s) \\alpha (X_{s(1)},\\dots ,X_{s(k)}) \\beta (X_{s(k+1)},...,X_{s(k+l)})\n\\]\nwhere the sum is over all $k,l$-shuffles.\n\\end{definition}\n\nThe wedge product is graded commutative: If $\\alpha \\in \\Omega^k (M)$ and $\\beta \\in \\Omega^l (M)$ then $\\alpha \\wedge \\beta = (-1) ^{kl}\\beta \\wedge \\alpha $. Furthermore, it is associative:\n\n\\begin{proposition}\nGiven $\\alpha_i \\in \\Omega_{k_i} (M)$ we have $(\\alpha_1 \\wedge \\alpha_2)\\wedge \\alpha_3 = \\alpha_1 \\wedge (\\alpha_2 \\wedge \\alpha_3)$\n\\end{proposition}\n\n\\subsubsection{Exterior differential}\nRecall that we defined the exterior differential on functions by the formula $(d f)(X) = X(f)$. We will now extend this definition to all forms.\n\n\\begin{theorem}\n\nThere is a unique collection of linear maps $d : \\Omega^k (M) \\rightarrow \\Omega^{k+1} (M)$, extending the map $(d f)(X) = X(f)$ for $k = 0$, such that $d(d f) = 0$ and satisfying the graded product rule, \n\\[\n    d(\\alpha \\wedge \\beta) = d\\alpha \\wedge \\beta + (-1) k\\alpha \\wedge d\\beta \n\\]\nfor $\\alpha \\in \\Omega^k (M)$ and $\\beta \\in \\Omega^l (M)$. This exterior differential satisfies $d \\circ d = 0$.\n\\end{theorem}\n\n\\begin{definition} (Exact, closed k-forms)\n\nA k-form $\\omega \\in \\Omega^k (M)$ is called \\textit{exact} if $\\omega = d\\alpha$ for some $\\alpha \\in \\Omega^{k-1} (M)$. It is called closed if $d\\omega = 0$.\n\\end{definition}\n\nSince $d\\circ d = 0$, the exact $k$-forms are a subspace of the space of closed $k$-forms; a necessary condition for $\\alpha$ to be exact is that it is closed.\n\n\\begin{example}\n\nThe quotient space (closed k-forms modulo exact k-forms) is a vector space called the k-th (de Rham) cohomology\n\\[\nH^k (M) = \\frac{\\{\\alpha \\in \\Omega^k (M)| \\alpha is closed \\}}{\\{\\alpha \\in \\Omega^k(M)| \\alpha is exact \\}}.\n\\]\n\nIt turns out that whenever $M$ is compact (and often also if $M$ is non-compact), $H ^k (M)$ is a finite-dimensional vector space. The dimension of this vector space $b_k(M) = \\dim H^k (M)$ is called the k-th Betti number of $M$; these numbers are important invariants of $M$ which one can use to distinguish non-diffeomorphic manifolds.\n\\end{example}\n\n\\subsection{Lie derivatives and contractions}\n\n\\begin{definition} (Contractions)\n\nGiven a vector field $X$, and a $k$-form $\\alpha  \\in \\omega k (M)$, we can define a $k-1$-form \n\\[\n    \\iota_X \\alpha \\in \\omega  k-1 (M)\n\\] by \\textit{contraction}: Thinking of $\\alpha $ as a multi-linear form, one simply puts $X$ into the first slot:\n\\[\n    (\\iota_X\\alpha )(X_1,...,X_{k-1}) = \\alpha (X,X_1,\\dots,X_{k-1}).\n\\]\nContractions have the following compatibility with the wedge product, similar to that for the exterior differential: \n\\[\n    \\iota_X (\\alpha  \\wedge \\beta ) = \\iota_X\\alpha  \\wedge \\beta  + (-1) k\\alpha  \\wedge \\iota_X \\beta , \n\\]\nfor $\\alpha  \\in \\omega^k (M)$,$\\beta  \\in \\omega^l (M)$, which one verifies by evaluating both sides on vector fields.\n\\end{definition}\n\nAnother important operator on forms is the Lie derivative:\n\n\\begin{theorem}\nGiven a vector field $X$, there is a unique collection of linear maps $L_X : \\Omega^k (M) \\rightarrow \\Omega^k (M)$, such that \n\\[ \n    L_X (f) = X(f), \\ L_X (d f) = dX(f),\n\\] \nand satisfying the product rule, \n\\[\nL_X (\\alpha  \\wedge \\beta ) = L_X \\alpha  \\wedge \\beta  +\\alpha  \\wedge L_X \\beta  \n\\] \nfor $\\alpha  \\in \\Omega^k (M)$ and $\\beta  \\in \\Omega^l (M)$.\n\\end{theorem}\n\nThese operators, $d, L_X, \\iota_X$, have the following compatibilities with the wedge product: For $\\alpha \\in \\Omega^k (M)$ and $\\beta \\in \\Omega^l (M)$ one has \n\\begin{align*}\nd(\\alpha \\wedge\\beta) &= (d\\alpha)\\wedge\\beta + (-1) k\\alpha \\wedge d\\beta,\\\\\nL_X (\\alpha \\wedge\\beta) &= (L_X\\alpha)\\wedge\\beta +\\alpha \\wedge L_X \\beta,\\\\\n\\iota_X (\\alpha \\wedge\\beta) &= (\\iota_X\\alpha)\\wedge\\beta + (-1) k\\alpha \\wedge\\iota_X \\beta.\n\\end{align*}\n  \nOne says that $L_X$ is an \\textit{even derivation} relative to the wedge product, whereas $d,\\iota_X$ are \\textit{odd derivations}. They also satisfy important relations among each other:\n\\begin{align*}\n    d \\circ d = 0 \\\\\n    L_X \\circ L_Y -L_Y \\circ L_X = L_{[X,Y]} \\\\\n    \\iota_X \\circ \\iota_Y +\\iota_Y \\circ \\iota_X = 0 \\\\\n    d \\circ L_X -L_X \\circ d = 0 \\\\\n    L_X \\circ \\iota_Y -\\iota_Y \\circ L_X = \\iota_[X,Y] \\\\\n    \\iota_X \\circ d+d \\circ \\iota_X = L_X .\n\\end{align*}\nThis collection of identities is referred to as the Cartan calculus, , and in particular the last identity is called the Cartan formula.\n\n\\subsubsection{Pull-backs}\n\n\\begin{definition} (k-form Pullbacks)\n\nSimilar to the pull-back of functions (0-forms) and 1-forms, we have a pull-back operation for k-forms, $F^* : \\Omega^k (N) \\rightarrow \\Omega^k (M)$ for any smooth map between manifolds, $F \\in C^\\infty(M,N)$. Its evaluation at any $p \\in M$ is given by\n\\[\n(F^* \\beta )_p(v_1,\\dots, v_k) = \\beta_{F(p)} (T_pF(v1),\\dots,T_pF(v_k)).\n\\]\n\\end{definition}\n\nThe pull-back map satisfies $d(F^*\\beta) = F^*d\\beta$, and for a wedge product of forms, $F^* (\\beta_1 \\wedge \\beta_2) = F^* \\beta_1 \\wedge F^* \\beta_2$.\n\n\\begin{proposition}\n\nLet $U \\subseteq \\mathbb R^m $with coordinates $x^i$ , and $V \\subseteq \\mathbb R^n $ with coordinates $y^j $. Suppose $m = j$, and $F \\in C^\\infty(U,V)$. Then \n\\[\nF^* (dy^1 \\wedge \\dots \\wedge dy^n ) = J dx^ 1 \\wedge \\dots \\wedge dx^n\n\\]\nwhere $J(x)$ is the determinant of the Jacobian matrix, \n\\[\n    J(x) = \\det \\bigg (\\frac{\\partial F^i}{\\partial  x^j} \\bigg ) ^n_{i, j=1}.\n\\]\n\n\\end{proposition}\n\nThe Lie derivative $L_X \\alpha $ of a differential form with respect to a vector field $X$ has an important interpretation in terms of the flow $\\Phi_t$ of $X$. Assuming for simplicity that $X$ is complete (so that $\\Phi_t$ is a globally defined diffeomorphism), one has the formula \n\\[\n    L_X\\alpha = \\frac{d}{dt} \\Bigr |_{t=0} \\Phi^*_t \\alpha.\n\\]\nThe formula shows that $L_X$ measures to what extent $\\alpha$ is invariant under the flow of $X$.\n\n\\subsubsection{Integration of differential forms}\n\nDifferential forms of top degree can be integrated over oriented manifolds. Let $M$ be an oriented manifold of dimension $m$, and $\\omega \\in \\Omega^m(M)$. Let $supp(\\omega)$ be the support of $\\omega$. If $supp(\\omega)$ is contained in an oriented coordinate chart $(U,\\phi)$, then one defines\n\\[\n\\int_M \\omega = \\int_{\\mathbb R^m} f(x)dx^1\\cdots dx^m \n\\]\n\nwhere $f \\in C^\\infty(\\mathbb R^m)$ is the function, with $supp(f) \\subseteq \\phi(U)$, determined from \n\\[\n(\\phi^{-1} )^* \\omega = f dx^1 \\wedge \\cdots \\wedge dx^m.\n\\]\nThis definition does not depend on the choice of oriented chart.\n\nIf $\\omega$ is not necessarily supported in a single oriented chart, we proceed as follows. Let  $ (U_i , \\phi^i), \\ i = 1,\\dots,r$ be a finite collection of oriented charts covering $supp(\\omega)$. Together with $U_0 = M \\setminus supp(\\omega)$ this is an open cover of $M$.\n\n\\begin{lemma}\nGiven a finite open cover of a manifold there exists a partition of unity subordinate to the cover, i.e. functions $\\chi_i \\in C^\\infty(M)$ with $supp(\\chi_i) \\subseteq U_i$ and $\\sum_{i=0}^r \\chi_i = 1$.\n\n\\end{lemma}\n\nIndeed, partitions of unity exists for any open cover, not only finite ones. Let $\\chi_0, \\dots, \\chi_r$ be a partition of unity subordinate to this cover. We define\n\\[\n    \\int_M \\omega = \\sum_{i=1}^r \\int_M \\chi_i \\omega\n\\] \nwhere the summands are defined as above, since $\\chi_i\\omega$ is supported in $U_i$ for $i \\geq 1$. It can be shown that this is well defined, independent of the choice of oriented coordinate charts.\n\n\\subsubsection{Integration over oriented submanifolds}\n\nLet $M$ be a manifold, not necessarily oriented, and $S$ is a k-dimensional oriented submanifold, with inclusion $i : S \\rightarrow M$. We define the integral over $S$, of any k-form $\\omega \\in \\Omega^k (M)$ such that $S \\cap supp(\\omega)$ is compact, as follows:\n\n\\[\n    \\int_S \\omega = \\int_S i^* \\omega.\n\\]\nOf course, this definition works equally well for any smooth map from $S$ into $M$. For example, the integral of compactly supported 1-forms along arbitrary paths $\\gamma : \\mathbb R \\rightarrow M$ is defined. Note also that $M$ itself does not have to be oriented, it suffices that $S$ is oriented.\n\n\\subsubsection{Stokes’ theorem}\nLet $M$ be an $m$-dimensional oriented manifold.\n\n\\begin{definition} (Boundary and interior of region)\n\nA region with (smooth) boundary in $M$ is a closed subset $D \\subseteq M$ with the following property: There exists a smooth function $f \\in C^\\infty(M,R)$ such that $0$ is a regular value of $f$ , and\n\\[\n    D = \\{p \\in M | f(p) \\leq 0 \\}.\n\\]\nWe do not consider $f$ itself as part of the definition of $D$, only the existence of $f$ is required. \n\nThe interior of a region with boundary, given as the largest open subset contained in $D$, is \n\\[\n   int(D) = \\{p \\in M| f(p) < 0,\n\\]\nand the boundary itself is\n\\[\n   \\partial D = \\{p \\in M| f(p) = 0 \\},\n\\]\na codimension 1 submanifold (i.e., hypersurface) in $M$.\n\n\\end{definition}\n\n\nRecall that we are considering $D$ inside an oriented manifold $M$. The boundary $\\partial D$ may be covered by oriented submanifold charts $(U,\\phi)$, in such a way that $\\partial D$ is given in the chart by the condition $x^1 = 0$, and $D$ by the condition $x^1 \\leq 0$:\n\\[ \n    \\phi (U \\cap D) = \\phi (U) \\cap \\{x \\in \\mathbb R^m | x ^1 \\leq 0 \\}.\n\\]\n\nWe call oriented submanifold charts of this kind \\textit{'region charts'}.\n\n\\begin{lemma}\nThe restriction of the region charts to $\\partial D$ form an oriented atlas for $\\partial D$.\n\\end{lemma}\nIn particular, $\\partial D$ is again an oriented manifold. To repeat: If $x^1 ,\\dots, x^m$ are local coordinates near $p \\in \\partial D$, compatible with the orientation and such that $D$ lies on the side $x^1 \\leq 0$, then $x^2 ,\\dots, x^m$ are local coordinates on $\\partial D$. This convention of ‘induced orientation’ is arranged in such a way that the Stokes’ theorem holds without extra signs.\n\nFor an $m$-form $\\omega$ such that $supp(\\omega)\\cap D$ is compact, the integral $\\int_D \\omega $ is defined similar to the case of $D = M$.\n\n\\begin{theorem} (Stokes' Theorem)\n\n\nLet $M$ be an oriented manifold of dimension $m$, and $D \\subseteq M$ a region with smooth boundary $\\partial D$. Let $\\alpha \\in  \\Omega^{m-1} (M)$ be a form of degree $m-1$, such that $supp(\\alpha)\\cap D$ is compact. Then \n\\[\n\\int_D d\\alpha = \\int_{\\partial D} \\alpha.\n\\]\n\\end{theorem}\n\nAs explained above, the right hand side means $\\int_{\\partial D} i^* \\alpha $, where $i : \\partial D \\rightarrow M$ is the inclusion map.\n\n\\begin{corollary}\nLet $\\alpha \\int \\Omega^{m-1}(M)$ be a compactly supported form on the oriented manifold $M$. Then\n\\[ \n    \\int_M d\\alpha = 0.\n\\]\n\\end{corollary}\n\nNote that it does not suffice that $d\\alpha$ has compact support. A typical application of Stokes’ theorem shows that for a closed form $\\omega \\in \\Omega^k (M)$, the integral of $\\omega$ over an oriented compact submanifold does not change with smooth deformations of the submanifold.\n\n\\begin{theorem}\n\nLet $\\omega \\in \\Omega^k (M)$ be a closed form on a manifold $M$, and $S$ a compact, oriented manifold of dimension $k$. Let $F \\in C^\\infty(R\\times S,M)$ be a smooth map, thought of as a smooth family of maps \n\\[\nF_t = F(t, \\cdot) : S \\rightarrow M.\n\\]\nThen the integrals $\\int_S F^* t \\omega$ do not depend on $t$.\n\\end{theorem}\n\nIf $F_t$ is an embedding, then this is the integral of $\\omega$ over the submanifold $F_t(S) \\subseteq M$.\n\n\\begin{definition} (Smooth isotopy)\n\nGiven a smooth map $\\phi : S \\rightarrow M$, one refers to a smooth map $F : R \\times S \\rightarrow M$ with $F_0 = \\phi $ as an \\textit{smooth deformation or isotopy} of $\\phi$. We say that $\\phi$ can be smoothly deformed into $\\phi'$ if there exists a smooth isotopy $F$ with $\\phi = F_0$ and $\\phi' = F_1$. \n\\end{definition}\n\nThe previous theorem shows that if $S$ is oriented, and if there is a closed form $\\omega \\in \\Omega^k (M)$ with\n\\[\n \\int_S \\phi^* \\omega \\neq \\int_S (\\phi' )^* \\omega \n\\]\nthen $\\phi$ cannot be smoothly deformed into $\\phi 0$.\n\n\n\\begin{example} (Winding number). \n\nLet$ \\omega \\in \\Omega^2 (\\mathbb R^2\\{0\\})$ be the 1-form $\\omega = \\frac{1}{x^2 +y^2} (xdy-ydx)$. In polar coordinates $x = r \\cos\\theta, y = r\\sin\\theta$, one has that $\\omega = d\\theta$. Using this fact one sees that $\\omega$ is closed (but not exact, since $\\theta$ is not a globally defined function on $\\mathbb R^2\\{0\\}$.) Hence, if $\\gamma : S^1 \\rightarrow \\mathbb R^2 \\{0\\}$ is any smooth map (a ‘loop’), then the integral $\\int_{S^1} \\gamma^*\\omega$ does not change under deformations (isotopies) of the loop. In particular, $\\gamma$ cannot be deformed into a constant map, unless the integral is zero. The number \n\\[ \n    w(\\gamma) = \\frac{1}{2\\pi} \\int_{S^1} \\gamma^*\\omega\n\\]\nis the \\textit{winding number} of $\\gamma$. (One can show that this is always an integer, and that two loops can be deformed into each other if and only if they have the same winding number.)\n\n\\end{example}\n\n\\subsubsection{Volume forms}\n\n\\begin{definition}\n\nA non vanishing 1-form $\\alpha$ at point $p$ means that there is a vector $v$ in $T_pM$ such that $\\alpha_p(v)\\neq 0$. Similarly for the $k$-form, it means that there is a set of $k$ vectors such the form is nonzero if evaluated on these vectors.\n\\end{definition}\n\n\\begin{definition} (Volume form)\n\nA top degree differential form $\\Gamma \\in \\Omega^m(M)$ is called a \\textit{volume form} if it is nonvanishing  everywhere: $\\Gamma_p \\neq 0$ for all $p \\in M$. In a local coordinate chart $(U,\\phi)$, this means that \n\\[ (\\phi^{-1} )^*\\Gamma = f dx^1 \\wedge \\cdots \\wedge dx^m \n\\]\nwhere $f(x) \\neq 0$ for all $x \\in  \\phi(U)$.\n\n\\end{definition}\n\n\n\\begin{lemma}\n\nA volume form $\\Gamma \\in \\Omega^m(M)$ determines an orientation on $M$, by taking as the oriented charts those charts $(U,\\phi)$ such that \n\n\\[\n    (\\phi^{-1})^*\\Gamma = f dx^1 \\wedge \\cdots \\wedge dx^m\n\\]\nwith $f > 0$ everywhere on $\\Phi(U)$.\n\\end{lemma}\n\n\n\\begin{theorem}\n\nA manifold $M$ is orientable if and only if it admits a volume form. In this case, any two volume forms compatible with the orientation differ by an everywhere positive smooth function: \n\\[\n    \\Gamma' = f \\Gamma , f > 0.\n\\]\n\n\\end{theorem}\n\n\\begin{definition} (Volume)\n\nFor a compact manifold $M$ with a given volume form $\\Gamma \\in \\Omega^m(M)$, one can define the volume of $M$, \n\\[\nvol(M) = \\int_M \\Gamma.\n\\]\nHere the orientation used in the definition of the integral is taken to be the orientation given by $\\Gamma$ . Thus $vol(M) > 0$.\n\\end{definition}\n\nNote that volume forms are always closed, for degree reasons (since $\\Omega^{m+1} (M) = 0$). But on a compact manifold, they cannot be exact:\n\n\\begin{theorem}\n\nLet $M$ be a compact manifold with a volume form $\\Gamma \\in \\Omega^m(M)$. Then $\\Gamma$ cannot be exact.\n\\end{theorem}\n\n\n\\section{De Rham Cohomology}\n\nThe exterior derivative converts the algebra of differential forms on a manifold into a graded differential algebra. The corresponding cohomology is called the de Rham cohomology algebra. \n\nSee Text for full details: \\begin{url}\nhttp://im0.p.lodz.pl/~kubarski/AnalizaIV/Wyklady/GHV/ITOM/G-H-V-1%20Connections,%20Curvature,%20and%20Cohomology.pdf\n\\end{url}\n\nIn article 1 it is shown that the de Rham cohomology satisfies the dimension, homotopy, disjoint union, and Mayer-Vietoris axioms. In article 2 various examples (retracts, PoincarC lemma, cohomology of Sn, and RP\") are discussed. In article 3 everything is done again (with the appropriate modifications) for differential forms with compact carrier. In article 4 the integral is used to establish the PoincarC duality theorem for a smooth orientable manifold. This theorem is applied in article 5 (sec. 5.13 and 5.14) to determine the nth de Rham cohomology space for any n-manifold (orientable or nonorientable). In sec. 5.15 the duality theorem is used to show that a compact manifold has finitedimensional de Rham cohomology. The de Rham cohomology of the product of two manifolds is computed in article 6 (Kunneth theorems). In article 7 one version of the de Rham theorem is established. The results of this article are not quoted elsewhere in the book. \n\n\\section{Overview of Riemannian Geometry}\nNote, there may be changes in notation from switching reading source.\n\nOn $\\mathbb R^n$ we have notions like:\n\\begin{enumerate}\n    \\item Length of vectors angles orthonormal/orthogonal geometry\n    \\item Areas volumes length of curves\n    \\item Distance between 2 points\n    \\item Parallel transport\n\\end{enumerate}\n\nObserve: All of the elements of Euclidean geometry on $\\mathbb R$ is entirely encoded in the inner product. We introduce geometry into smooth manifolds by making a choice of inner products on each $TpM$ that varies smoothly from point to point. This is an inner product.\n\n\\begin{definition}\n\n\\[\n    g: M \\rightarrow T^2 (T^*_pM), p\\mapsto g_p \\in T^2 (T^*_pM)\n\\]\nso that $g_p$ is an inner product on $T_pM$ and is bilinear symmetric, nondegenerative, and positive definite.\n\nThen $g_p \\in C^\\infty$ iff $g: \\mathfrak X(M) \\times \\mathfrak X(M) \\rightarrow C^\\infty(M)$, defined by  $g(x,y)(p )= g_p(x_p, y_p)$. Note, $g_p$ is non-linear.\n\\end{definition}\n\n\\begin{definition}\n\n(M, g) is called a Riemannian manifold.\n\\end{definition}\n\nThe manifold has the following properties: \n\\begin{enumerate}\n    \\item The length of vectors for $v \\in T_pm$, $||v|| = \\sqrt{g(v,v)}$, $\\cos (angle v w) = \\frac{g(v,w)}{||v||||w||} $.\n    \n    \\begin{lemma}\n    Near each point, there exists an orthonormal local frame.\n    \\end{lemma}\n\n    \\item The length of curve $\\gamma := \\int_a^b \\sqrt{g(\\gamma(t),\\gamma ' (t))} dt$.\n    \n    \\item Distance $d: M \\times M \\rightarrow [0, \\infty)$ is defined by $d(p,q) = \\inf(\\int_0^1 || \\gamma '(t)|| )dt $ where $\\gamma(0) = p, \\gamma(1) = q$.\n\n    This makes $(M,d)$ a metric space so that the metric topology is the same as the original topology. One can show that $(M,d)$ is complete as a metric space iff $d(p,q)$ is obtained by a curve $\\gamma$ for all $p,q \\in M$.\n    \n    \\item There is a natural isomorphism $\\Phi_p: T_pM \\rightarrow T^*_pM, \\ v \\mapsto (v^* : w \\mapsto g(v,w))$. So there is a module isomorphism $\\Phi : \\mathfrak X \\rightarrow \\Omega '(M)$.\n    \n    \\item Let $S \\subseteq M$ be a $k$-dimensional manifold. Then $i^*g$ (induced metric on S) is a Riemannian metric on $S$ giving $S$ the unique geometry inherited by $M$.\n    \n    \\item Suppose $M$ in oriented. There does not exist a nowhere vanishing n-form called the volume form satisfying $\\omega(x_1,\\dots, x_n) = 1$ whenever $x$ is a local orthonormal frame that has positive orientation. This allows for integration of functions for $f \\in C^\\infty(M)$ defined as $\\int_M f := \\int_m f \\omega $. Also, if $M$ is compact, we have $vol(M) = \\int_M 1 \\ \\int_M  \\omega $. Similarly, $Vol_{k-dim}(S) = \\int_S 1$ with respect to the induced metric $i^* g$ on $S$.\n    \n    \\item We say $(M, g)$, $(\\Tilde{M}, \\Tilde{g})$ are isometric if there exists a diffeomorphism $F: M \\rightarrow \\Tilde{M}$ such that $g = F^*\\Tilde{g}$\n\\end{enumerate}\n\n\\subsection{Covariant derivative and curvature}\n\nIf a parallel transport of a vector along a curve has the property that $D_{\\gamma'(t)} = 0$, then $\\gamma$ is the shortest distance between $p$ and $q$ so $\\gamma$ is a line.\n\nOn a sphere in $S^2$, parrallel transport is equivalent to $(\\delta _{\\gamma'(t)} X )^T = 0$ intrinsic to the round metric $(S^3, g)$. Then the shortest paths are the curves which form great circles.\n\n\n\nDefine $(\\Tilde{\\delta _{X}} Y)= (\\delta_X Y)^T $ as the connection operator for $X,Y\\in \\mathfrak{X}(S^2)$. This operator is intrinsic to $S^2$ and satisfies:\n\\begin{enumerate}\n    \\item $C^\\infty$-linear  w.r.t. $X$.\n    \\item $\\mathbb R$-linear  w.r.t. $Y$.\n    \\item $(\\Tilde{\\delta _{X}} fY) = X(f)Y + f\\Tilde{\\delta_X}Y$.\n    \\item $\\Tilde{\\delta_x}y - \\Tilde{\\delta_y X} = L_x Y$\n    \\item $Z(g(x,y)) - g(\\Tilde{\\delta_Z} X,Y) - g(x, \\Tilde{\\delta_Z}y) = 0$\n    \n\\end{enumerate}\n\nLet $\\gamma$ be a curve, then \n\\[\n\\frac{d}{dt} (g(X_\\gamma(t)), Y_\\gamma (T)) = g(\\Tilde{\\gamma'(t)}X, Y ) + g(X, \\Tilde{\\gamma'(t)} Y). \n\\]\n\n\\begin{theorem}\nOn a manifold $(M, g)$ there does not exist a connection $\\delta : \\mathfrak X \\times  \\mathfrak X \\rightarrow \\mathfrak X$ satisfying (4)\n\\[\n[X, Y] = \\delta_X Y - D_Y X\n\\]\nand (5)\n\\[\nZ(g(x,y)) - g(\\delta_Z X,Y) - g(x, \\delta_Z y) = 0\n\\]\ncompatible with the metric. (5) gives rise to the notion of parallel transport on Riemannian manifolds and is called the Levi-Civita connection.\n\nSo we say that $X$ is parrellel transported on a curve $\\gamma$ on $M$ if $\\delta_{\\gamma'(t)} X = 0$ for all $t$.\n\n\\end{theorem}\n\n\n\\begin{definition} (Geodesic)\n \n$\\gamma$ is a geodesic if  $\\delta_{\\gamma'(t)} X = 0$ for all $t$.\n\n\\end{definition}\n\n\\begin{theorem}\n\nIf $d(p,q)$ is attained by a curve $\\gamma$, then $\\gamma$ is a geodesic.\n\n\\end{theorem}\n\nNote, the converse is not true. A counter example of a great circle minus a small segment will not be the shortest distance between the two points.\n\nLet $(U, \\phi)$ be a chart.\n\\[\n    \\delta_{\\frac{\\partial}{\\partial x^i}} \\frac{\\partial }{\\partial x^i}  = \\sum_k \\Gamma_{ij}^k \\frac{\\partial}{\\partial x^k}\n\\]\nWhere $ \\Gamma_{ij}^k$ are the Levi-Civita connection coeffecients and are completely determined by the metric.\n\\[\n \\Gamma _{ij}^{k}={\\tfrac {1}{2}}g^{mk}\\left(\n \\frac{\\partial g_{im}}{\\partial x^j}\n + \\frac{ \\partial g_{jm}}{\\partial x^i}\n -\\frac{partial g_{ij}}{\\partial x ^m}\\right)\n\\]\n\n\\[\n    g_{ij} = g(\\frac{\\partial}{\\partial x^i}, \\frac{\\partial}{\\partial x^j})\n\\]\n\nThe term covariant derivative is often used for the Levi-Civita connection. The coefficients of this connection with respect to a system of local coordinates are called Christoffel symbols.\n\n\\subsection{Curvature}\n\nRecall $L_[X,Y] = [L_X, L_Y]$. If $[X,Y]=0$ commutes, then $L_X L_Y - L_Y L_X = 0$ This fails in general for the covariant derivative. This failure is measured by a tensor field that plays a central role in all of differential geometry.\n\n\\[\n    R(X,Y) Z = \\delta_X \\delta_Y Z - \\delta_Y \\delta_X Z - \\delta_[X,Y] Z\n\\]\n\nThis is a (1, 3) tensor field which can be proven by showing that $R$ is $C^\\infty$-linear with respect to each component.   \n\n\\section{Lie Groups}\nSee notebook on Lie Groups\n\n\\begin{url}\nhttps://github.com/lukepereira/notebooks/\n\\end{url}\n\n% The fundamental objects of study in differential geometry are manifolds. Roughly, an n-dimensional manifold is a mathematical object that ``locally'' looks like $\\mathbb R^n$.  Manifolds in euclidean space are described with a \\textit{regular level set}, $S = f^{-1}(a)$ which defines a smooth hypersurface $S \\subseteq R^n$. For example, the n-dimensional sphere described by:\n% \\[\n%     S^n = \\{ (x^0, \\dots, x^n) \\in \\mathcal R^{n+1} | (x^0)^2 + \\dots + (x^n)^2  = 1\\}.\n% \\]\n% Another example is the 2-Torus, $T^2$. Given real numbers $r, R$ with $0 < r < R$, take a circle of radius $r$ in the $x-z$ plane, with center at $(R,0)$, and rotate about the $z$-axis:\n% \\[\n%     T^2 = \\{ (x,y,z) | (\\sqrt{x^2 + y^2} - R)^2 + z^2 + r\\}\n% \\]\n\n% The sphere, the torus, the double torus, triple torus, and so on are ‘orientable’ surfaces, which essentially means that they have two sides which you might paint in two different colors. It turns out that these are all orientable surfaces, if we consider the surfaces ‘intrinsically’ and only consider surfaces that are compact in the sense that they don’t go off to infinity and do not have a boundary (thus excluding a cylinder, for example).\n\n% Not all surfaces can be realized as ‘embedded’ in $\\mathbb R^3$; for \\textit{non-orientable surfaces} one needs to allow for self-intersections. This type of realization is referred to as an immersion: We don’t allow edges or corners, but we do allow that different parts of the surface pass through each other.  An example is the Klein bottle, which is not possible to represent as a regular level set $f^{-1}(0)$ of a function $f$ since any suface has one side where $f$ is positive and another side where $f$ is negative.\n\n% The projective plane or projective space is denoted $\\mathbb{R} P^2$ and is defined as the set of all lines (i.e., 1-dimensional subspaces) in $\\mathbb{R}^3$. we can also think of $\\mathbb{R} P^2$ as the set of antipodal (i.e., opposite) points on $S^2$. Splitting the points into those with distance $< \\epsilon$ from the equator and those $\\geq \\epsilon$ produces a Mobius strip and a two-dimensional disc. Generating a smooth curve by gluing the boundary of a Mobius strip to the boundary of a disk is depicted in what's known as Boy’s surface.\n\n% Another operation for surfaces, generalizing the procedure of ‘attaching handles’, is the connected sum Given two surfaces $\\sigma_1$ and $\\sigma_2$, remove small disks around given points $p_1 \\in \\sigma_1$ and $p_2 \\in \\sigma_2$, to create two surfaces with boundary circles. Then glue-in a cylinder connecting the two boundary circles, without creating edges. The resulting surface is denoted $\\sigma_1\\#\\sigma_2$.\n\n% It turns out that all closed, connected surfaces are obtained from either the 2-sphere $S^2$, the Klein bottle, or  $\\mathbb{R} P^2$, by attaching handles with the connected sum.\n\n% “gauge equivariance.” This means that quantities in the world and their relationships don’t depend on arbitrary frames of reference (or “gauges”); they remain consistent whether an observer is moving or standing still, and no matter how far apart the numbers are on a ruler. Measurements made in those different gauges must be convertible into each other in a way that preserves the underlying relationships between things.\n\n\\newpage\n\\begin{thebibliography}{}\n\n\\bibitem[]{}\nE. Meinrenken and G. Gross, Introduction to Differential Geometry, Lecture Notes for MAT367. \n%http://www.math.utoronto.ca/~mein/teaching/MAT367/DiffGeomNotes.pdf\n\n\\bibitem[]{}\nSamelson, H. Review: Werner Greub, Stephen Halperin and Ray Vanstone, Connections, curvature, and cohomology. Bull. Amer. Math. Soc. 83 (1977), no. 5, 1011--1015. https://projecteuclid.org/euclid.bams/1183539466\n%http://im0.p.lodz.pl/~kubarski/AnalizaIV/Wyklady/GHV/ITOM/G-H-V-1%20Connections,%20Curvature,%20and%20Cohomology.pdf\n\n\\bibitem[]{}\nPaul Seidel. 18.950 Differential Geometry. Fall 2008. Massachusetts Institute of Technology: MIT OpenCourseWare, https://ocw.mit.edu. License: Creative Commons BY-NC-SA.\n%https://ocw.mit.edu/courses/mathematics/18-950-differential-geometry-fall-2008/index.htm#\n\n\\bibitem[]{}\nSigurdur Helgason. 18.755 Introduction to Lie Groups. Fall 2004. Massachusetts Institute of Technology: MIT OpenCourseWare, https://ocw.mit.edu. License: Creative Commons BY-NC-SA.\n%https://ocw.mit.edu/courses/mathematics/18-755-introduction-to-lie-groups-fall-2004/index.htm#\n\n%https://link.springer.com/book/10.1007/978-1-4612-0281-3\n\n\\end{thebibliography}\n\n\n\\end{document}\n", "meta": {"hexsha": "fe20b3a9d9d346b1b5fcbccbbb65e92c9f8b6d59", "size": 118963, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "documents/2020-differential-geometry/main.tex", "max_stars_repo_name": "lukepereira/latex-ci", "max_stars_repo_head_hexsha": "4390a2da344ec00a3f651f464c79b7e097cbabe6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-09-04T20:32:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T21:30:32.000Z", "max_issues_repo_path": "documents/2020-differential-geometry/main.tex", "max_issues_repo_name": "lukepereira/latex-ci", "max_issues_repo_head_hexsha": "4390a2da344ec00a3f651f464c79b7e097cbabe6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-07-13T01:21:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-13T02:09:19.000Z", "max_forks_repo_path": "documents/2020-differential-geometry/main.tex", "max_forks_repo_name": "lukepereira/latex-ci", "max_forks_repo_head_hexsha": "4390a2da344ec00a3f651f464c79b7e097cbabe6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.1676109537, "max_line_length": 991, "alphanum_fraction": 0.6878020897, "num_tokens": 37868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.30985973660344424}}
{"text": "\\section{AMR-Based Detonation Solver in OpenFOAM}\n\n\n\\begin{frame}{Tested Solvers}\nSolvers tested for their capability to model shocks and detonations:\n\\begin{itemize}\n\\item \\textbf{rhoReactingFoam}: included with OpenFOAM, a density-based combustion solver\n\\item \\textbf{rhoCentralFoam}: included with OpenFOAM and developed by Greenshields \\textit{et. al.} \\cite{greenshields}, a density-based solver that uses the central-upwind schemes of Kurganov and Tadmor \\cite{kurganov1} \n\\item \\textbf{rhoReactingCentralFoam}: a solver combined by Caelan Lapointe with previous work done by Nakul \\cite{nakul}, with AMR support\n\\end{itemize}\n\\end{frame}\n\n\\subsection{Governing Equations}\n\n\\begin{frame}[allowframebreaks]{Governing Equations}\nDetonations were modeled using the reacting Navier-Stokes equations \\cite{kuo,stokes}:\n\\begin{equation}\n\\frac{\\partial \\rho}{\\partial t} + \\nabla \\cdot \\left(\\rho \\bm{u}\\right) = 0\\,\n\\end{equation}\n\\begin{equation}\n\\frac{\\partial \\rho\\bm{u}}{\\partial t} + \\nabla \\cdot \\left(\\rho \\bm{u}\\otimes \\bm{u}\\right) + \\nabla p -\\mu\\nabla^2\\bm{u}= \\bm{0}\\,,\n\\end{equation}\n\\begin{equation}\n\\frac{\\partial \\rho E}{\\partial t} + \\nabla \\cdot \\left[\\left(\\rho E + p\\right)\\bm{u}\\right] -\\alpha\\nabla^2 e = \\dot{q}\\,,\n\\end{equation}\n\\begin{equation}\n\\frac{\\partial \\rho Y_i}{\\partial t} + \\nabla \\cdot \\left(\\rho Y_i \\bm{u}\\right) -\\mu\\nabla^2 Y_i= \\dot{\\omega}_i\\,,\n\\end{equation}\nwhere \n\\begin{equation}\n\\dot{q} = \\sum_{i = 1}^N \\dot{\\omega_i} \\Delta h_{f,i}^0\\,,\n\\end{equation}\n%is the heat flux, $\\dot{\\omega}_i$ is the species source reaction rate, $\\rho$ is the density, $\\bm{u}$ is the fluid velocity vector, $Y_i$ is the mass fraction of the $i$th species, $E$ is the total energy, $p$ is the pressure, $\\mu$ is the dynamic viscosity, $e$ is the internal energy, $\\alpha$ is the thermal diffusivity and $\\Delta h_{f,i}^0$ is the species formation enthalpy.\n\\end{frame}\n\n\n\\begin{frame}{Notes About Governing Equations}\n\\begin{itemize}\n\\item Specific heat $C_{p,i}=C_{p,i}(T)$ from NIST JANAF \\cite{janaf} lookup tables.  \n\\item No explicit turbulence modeling, but turbulence can form\n\\begin{itemize}\n    \\item subgrid-scale turbulence structures averaged out numerically\n    \\item akin to implicit LES\n\\end{itemize}\n\\item Not modeling inviscid Euler equations; viscosity is accounted for with Sutherland \\cite{sutherland} model:\n\\end{itemize}\n\\begin{equation}\n\\mu = \\frac{A_s \\sqrt{T_s}}{1 + \\frac{T_s}{T}} \\,,\n\\end{equation}\n\\end{frame}\n\n\\subsection{Chemistry Modeling}\n\n\\begin{frame}{Chemical Reactions}\nSingle-step stoichiometric hydrogen-air utilized for simplicity, which follows the following expression \\cite{kuo}:\n\\begin{center}\n\\ch{2 H2 + 2 (O2 + 3.76 N2) -> 2 H2O + 7.52 N2}\n\\end{center}\nwith\n\\begin{table}[t!]\n\\centering\n\\begin{tabular}{cc}\nSpecies & Mass Fraction \\\\ \\hline\nH\\(_2\\) & 0.02851 \\\\ \nH\\(_2\\)O & 0 \\\\\nN\\(_2\\) & 0.745 \\\\ \nO\\(_2\\) & 0.226 \\\\ \\hline\nTotal & 0.99951 \\\\ \n\\end{tabular}\n\\end{table}\nOpenFOAM allows for easy transitions between chemical models.\n\\end{frame}\n\n\\begin{frame}{Reaction Rate Modeling}\nArrhenius equation \\cite{arrhenius} takes the form \\cite{christ} \n\\begin{equation}\n\\dot{\\omega}_i = AT^\\beta \\exp\\left(\\frac{ -E_a}{R T}\\right)\\,,\n\\end{equation}\nwhere $Ta = Ea/R$. Simulation values were explored, but we settled on \n\\begin{equation}\n   A = 1.4 \\times 10^{13} ~ \\text{m}^3\\text{mol}^{-1}\\text{s}^{-1},\n   \\qquad \n   Ta = 12996 ~\\text{K},\n   \\qquad\n   \\beta = 0\\,.\n\\end{equation}\nwith \\(R = 368.9\\) J/Kg-K. As shown later these reasonably match Chapman-Jouguet detonation theory \\cite{chapman} along with other published values \\cite{towery1,hashemi}.\n\\end{frame}\n\n\\subsection{Domain Setup}\n\n\\begin{frame}{Simulation Domain Setup}\nBesides ignition region, domain is at 1 atm and 300 K\n\\begin{figure}[t!]\n\\centering\n\\includegraphics[width=0.8\\textwidth]{../figs/domainBC.png}\n%\\caption{Geometry and domain setup with boundary conditions}\n%\\label{fig:domainBC}\n\\end{figure}%\n\\end{frame}\n\n\\subsection{Parallel Computing}\n\n\\begin{frame}{Parallel Computing: Decomposition}\n%Domain is decomposed into chunks which are independently processed in parallel, communicating with MPI \\cite{walker}. Decomposition defined in \\texttt{decomposeParDict}. Several methods for decomposition:\n%\\begin{itemize}\n%\\item \\texttt{simple}: define splits in each direction \n%\\item \\texttt{hierarchical}: \\texttt{simple}, but with recursive ordering to splits\n%\\item \\texttt{scotch}: minimizes boundaries between processors, can set weighting\n%\\item \\texttt{manual}: manual cell allocation to each processor \n%\\end{itemize}\n%The \\texttt{simple} method was used here. \n\\begin{itemize}\n\\item Domain is decomposed into chunks which are independently processed in parallel, communicating with MPI \\cite{walker}\n\\item Decomposition defined in \\texttt{decomposeParDict}\n\\item Several methods for decomposing domain in OpenFOAM, but \\texttt{simple} method was utilized which simply splits number of times in each direction\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Parallel Computing: Load Balancing}\n\\begin{figure}[p]\n    \\centering\n    \\begin{subfigure}[]{0.45\\textwidth}\n        \\centering\n        \\includegraphics[width=0.9\\textwidth]{../figs/parallel_short.png}\n        \\caption{Domain decomposed into typical chunks, bad for detonation and AMR load balancing}\n        %\\label{sfig:shortdecomp}\n    \\end{subfigure}%\n    \\begin{subfigure}[]{0.45\\textwidth}\n        \\centering\n        \\includegraphics[width=0.9\\textwidth]{../figs/parallel_long.png}\n        \\caption{Domain decomposed into long chunks, better for detonation and AMR load balancing}\n        %\\label{sfig:longdecomp}\n    \\end{subfigure}\n    %\\caption{Example domain decomposition techniques for parallel computing}\n    %\\label{fig:decomp}\n\\end{figure}%\n\\end{frame}\n\n\\subsection{Adaptive Mesh Refinement}\n\n\\begin{frame}{Adaptive Mesh Refinement: Splitting}\nAdaptive meshing splits the cells using an octree splitting method:\n\\begin{figure}[]\n\\centering\n\\includegraphics[width=0.4\\textwidth]{../figs/amr_example.png}\n%\\caption{Adaptive mesh refinement octree splitting method}\n%\\label{fig:octree}\n\\end{figure}%\nThis makes the AMR inherently three-dimensional. \n\\end{frame}\n\n\n\\begin{frame}{Adaptive Mesh Refinement Parameters}\nAllows for the mesh to refine and unrefine based on set parameters:\n\\begin{itemize}\n\\item \\texttt{refineInterval}: frequency when active, based on time steps\n\\item \\texttt{field}: which parameter to track\n\\item \\texttt{lowerRefineLevel}: lower bound of active refinement \n\\item \\texttt{upperRefineLevel}: upper bound of active refinement\n\\item \\texttt{unrefineLevel}: upper bound of unrefinement\n%\\item \\texttt{nBufferLayers}: number of buffer cell layers between levels of refinement \n%\\item \\texttt{maxRefinement}: additional recursive refinement levels\n\\item \\texttt{maxCells}: maximum cell count to trigger AMR update\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Adaptive Mesh Refinement: Refinement Levels}\n\\begin{columns}\n\\column{0.5\\textwidth}\n\\texttt{maxRefinement}: Number of additional recursive refinement levels\n\\column{0.5\\textwidth}\n\\begin{center}\n\\includegraphics[width=0.8\\textwidth]{../figs/amr_refine.png}\n\\end{center}\n\\end{columns}\n\\end{frame}\n\n\n\\begin{frame}{Adaptive Mesh Refinement: Buffer Layers}\n\\begin{columns}\n\\column{0.5\\textwidth}\n\\texttt{nBufferLayers}: Number of buffer cell layers between levels of refinement\n\\column{0.5\\textwidth}\n\\begin{center}\n\\includegraphics[width=0.8\\textwidth]{../figs/amr_buffer.png}\n\\end{center}\n\\end{columns}\n\\end{frame}\n\n\n\\begin{frame}{Adaptive Mesh Refinement: Detonation Wave}\n\\begin{figure}\n\\centering\n\\includegraphics[width=0.7\\textwidth]{../figs/amr_cells.png}\n\\caption{Three-level adaptive mesh refinement over a pressure field surface contour, with the detonation wave traveling from the -x wall to +x exit}\n%\\label{fig:examr}\n\\end{figure}\n\\end{frame}\n\n\\begin{frame}{Initial Meshing}\n\\begin{figure}[]\n    \\centering\n    \\begin{subfigure}[]{0.5\\textwidth}\n        \\centering\n        \\includegraphics[width=\\textwidth]{../figs/mesh/2Dmesh.png}\n        \\caption{Two-dimensional mesh}\n    \\end{subfigure}%\n    \\begin{subfigure}[]{0.5\\textwidth}\n        \\centering\n        \\includegraphics[width=\\textwidth]{../figs/mesh/3Dmesh.png}\n        \\caption{Three-dimensional mesh}\n    \\end{subfigure}\n    %\\caption{Static meshes used in OpenFOAM for detonation modeling, at an exaggerated unrefined resolution for example purposes}\n    %\\label{fig:meshcompare}\n\\end{figure}\n\\end{frame}\n\n\\subsection{Initial Work and Testing}\n\n\\begin{frame}{Initial Detonation Attempts}\nFirst testing \\texttt{rhoReactingFoam}, methane-oxygen without nitrogen was used, with corner ignition to test shock reflection and exit \n\\begin{figure}[]\n\\centering\n\\includegraphics[width=0.9\\textwidth]{../figs/cornerdet.png}\n%\\caption{Initial methane and oxygen detonation boundary condition test with corner detonation. Velocity magnitude is plotted here without scale to just check the solver and boundary conditions for modeling potential. Detonation was initiated in the lower left corner.}\n%\\label{fig:cornerdet}\n\\end{figure}%\nTesting the detonation tube setup performed by Towery \\textit{et. al.} \\cite{towery1} was next, to be used as comparison. \n\\end{frame}\n\n\\begin{frame}{\\texttt{rhoReactingFoam} Problems}\n\\begin{columns}\n\\column{0.4\\textwidth}\n\\begin{itemize}\n\\item Different static mesh resolutions were tested with \\texttt{rhoReactingFoam}, but noise and instability in the solution was seen.\n\\item likely due to solver being more pressure-based than density-based\n\\end{itemize}\n\\column{0.6\\textwidth}\n\\begin{figure}[]\n\\centering\n\\includegraphics[width=\\textwidth]{../figs/rhoReactingFoam.png}\n%\\caption{Noise and instability in solution and shock capturing problems using the \\texttt{rhoReactingFoam} solver}\n%\\label{fig:rrf}\n\\caption*{Pressure vs. Grid Location}\n\\end{figure}%\n\\end{columns}\n\\end{frame}\n\n\\begin{frame}{\\texttt{rhoReactingCentralFoam} Selection and Validation}\n\\begin{columns}\n\\column{0.6\\textwidth}\n\\begin{figure}[]\n\\centering\n\\includegraphics[width=\\linewidth]{../figs/shocktube.png} \n%\\caption{Shock tube validated test case included with OpenFOAM compared to hybrid solver}\n%\\label{fig:sod}\n\\end{figure}%\n\n\\column{0.4\\textwidth}\n\\begin{itemize}\n\\item turned towards the solvers utilizing central-upwind schemes of Kurganov and Tadmor \\cite{kurganov1}\n\\item used the shock tube test to validate shock-capturing capability\n\\end{itemize}\n\\end{columns}\n\\end{frame}\n", "meta": {"hexsha": "3388e274d8851a834a6d4334be3e948dcb9d68d0", "size": 10448, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/presentation/chapter2.tex", "max_stars_repo_name": "duncanam/thesis", "max_stars_repo_head_hexsha": "95e0e590edec03672667f8d302d12fa4a222f258", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-05-05T17:55:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T13:37:02.000Z", "max_issues_repo_path": "doc/presentation/chapter2.tex", "max_issues_repo_name": "duncanam/thesis", "max_issues_repo_head_hexsha": "95e0e590edec03672667f8d302d12fa4a222f258", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/presentation/chapter2.tex", "max_forks_repo_name": "duncanam/thesis", "max_forks_repo_head_hexsha": "95e0e590edec03672667f8d302d12fa4a222f258", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-18T17:54:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-18T17:54:43.000Z", "avg_line_length": 39.1310861423, "max_line_length": 383, "alphanum_fraction": 0.748085758, "num_tokens": 3094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.30985973660344424}}
{"text": "\\subsubsection*{Discrete Fourier Transforms\\hspace*{\\fill}\\hyperlink{SignalProcessing}{(up)}\\hypertarget{fftFunctions}{}} \\addcontentsline{toc}{subsubsection}{Discrete Fourier Transforms}\nDiscrete Fourier transforms are done using a fast Fourier transform (FFT) algorithm. \n\\begin{table}[H]\n\\caption{Discrete Fourier Transform}\n\\label{tab:fftFunctions}\n\\begin{center}\n\\begin{tabular}{|l|l|}\n\\multicolumn{2}{c}{\\hyperlink{fftFunc}{\\rmfamily \\bfseries FFT Function Set}} \\\\ \\hline\nfft & Execute FFT\\\\\nfft\\_create & Create FFT Object\\\\\nfft\\_destroy & Free FFT object\\\\\nfft\\_getattr & Get attributes of FFT object\\\\\n\\hline\\end{tabular}\n\\end{center}\n%\\label{default}\n\\end{table}%", "meta": {"hexsha": "36f8b3e317273fcd6993f33ed8d08625b99d3c01", "size": 674, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/jvsip_book/FftFunctions.tex", "max_stars_repo_name": "rrjudd/jvsip", "max_stars_repo_head_hexsha": "56a965fff595b027139ff151d27d434f2480b9e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2016-01-16T04:10:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T02:17:44.000Z", "max_issues_repo_path": "doc/jvsip_book/FftFunctions.tex", "max_issues_repo_name": "rrjudd/jvsip", "max_issues_repo_head_hexsha": "56a965fff595b027139ff151d27d434f2480b9e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-09-11T04:48:03.000Z", "max_issues_repo_issues_event_max_datetime": "2015-09-11T13:44:29.000Z", "max_forks_repo_path": "doc/jvsip_book/FftFunctions.tex", "max_forks_repo_name": "rrjudd/jvsip", "max_forks_repo_head_hexsha": "56a965fff595b027139ff151d27d434f2480b9e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-06-13T21:48:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-26T15:07:44.000Z", "avg_line_length": 42.125, "max_line_length": 187, "alphanum_fraction": 0.765578635, "num_tokens": 197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.30985973660344424}}
{"text": "% !TEX root =main.tex\n\n\n%\\section{Further Remarks on  C-TLP Protocol}\\label{discussion-C-TLP}\n\n%In this section, we provide some remarks on  C-TLP scheme presented in Section \\ref{SO-PoR-Protocol}. \n\n\\begin{remark} To make each  puzzle instance, a \\emph{distinct} random generator: $r_{\\scriptscriptstyle j}$, is used. This is the reason, in  C-TLP protocol, before a puzzle  is  generated   in step \\ref{call-RTLP-GenPuz},  a new public key is set in step \\ref{set-pk-in-loop}.  Also, at the beginning of the protocol only $r_{\\scriptscriptstyle 1}$ is public and the rest of the generators are kept secret. They are found and used sequentially after their related puzzle is solved. \n\\end{remark}\n\n\n\\begin{remark} The commitments opening, including the commitment random values, are not known to other verifiers (than the puzzle generator) at the beginning of the protocol. At this point,  only the committed values are public. Once a solver solves each puzzle,  it  extracts one of the commitments' opening, and sends it to a public verifier who can check if the opening matches the commitment.  \n\\end{remark}\n\n\\begin{remark}\n In  C-TLP, we use the folklore hash-based commitment scheme, in the random oracle model, only to achieve more computation improvement than that can be achieved in the standard model. But C-TLP can utilise any efficient non-interactive commitment scheme in the \\emph{standard model} as well, e.g. Pedersen Commitment.\n\\end{remark}\n\n\n\\begin{remark}\nThe efficiency of  C-TLP scheme stems from three crucial factors: (a) removing computation overlaps when solving different puzzles: even though solving $j\\text{\\small{-th}}$ puzzle, where $j>1$, requires $jT$ squaring, $(j-1) T$ of the squaring is used to solve previous puzzles that leads to $\\frac{z+1}{2}$ times computation cost reduction at the server-side,  (b)  supporting reusable single  public parameter: $a=2^{\\scriptscriptstyle T}$, generated only once that costs $O(1)$, as opposed to the RSA-based TLP whose cost is linear: $O(z)$, and (c) supporting efficient verification: due to the way each message is encoded (i.e. embedding the opening in a solution). \n\\end{remark}\n\n\\begin{remark}\nC-TLP also can efficiently  be used in a multi-server setting,  where there are $z$ servers: $\\{S_{\\scriptscriptstyle 1},...,S_{\\scriptscriptstyle z}\\}$,  each $S_{\\scriptscriptstyle j}$ needs to solve puzzle $\\ddot{o}_{\\scriptscriptstyle j}$ at time $f_{\\scriptscriptstyle j}$ and passes on the solution to the next server $S_{\\scriptscriptstyle j+1}$ to solve the next puzzle by time $f_{\\scriptscriptstyle j+1}>f_{\\scriptscriptstyle j}$. In this setting,  due to the scalability property of C-TLP (and unlike using the existing time-lock puzzles naively), other servers do not need to start solving the puzzle   as soon as the client releases puzzles' public parameters. Instead, they can wait until the previous solution is issued that saves them a significant cost. Furthermore, a  server can first  verify the correctness  of the solution found by the previous server (due to the public verifiability of C-TLP),  if accepted then   it starts finding the next solution. \n\\end{remark}\n\n\n\\begin{remark}\nIn the following, we outline an  approach that looks an option to construct an efficient C-TLP; however, as we will show it would not be secure. In particular,  one uses the TLP to generate $z$ public and secret key pairs. Then, it uses the TLP to compute $z\\text{\\small{-th}}$ puzzle as $\\mathtt{TLP.GenPuZ}(m_{\\scriptscriptstyle z},pk_{\\scriptscriptstyle z},sk_{\\scriptscriptstyle z})\\rightarrow \\ddot{o}_{\\scriptscriptstyle z}$.  Then, it embeds $\\ddot{o}_{\\scriptscriptstyle z}$ into $(z-1)\\text{\\small{-th}}$ one, i.e. $\\mathtt{TLP.GenPuZ}(m_{\\scriptscriptstyle z-1}||\\ddot{o}_{\\scriptscriptstyle z},pk_{\\scriptscriptstyle z-1},sk_{\\scriptscriptstyle z-1})\\rightarrow \\ddot{o}_{\\scriptscriptstyle z-1}$. This process goes on until $\\ddot{o}_{\\scriptscriptstyle 1}$  is created. It sends the combined puzzles and public key (including all random generators) to the server; with the hope that puzzles can be solved sequentially and the time gap between finding two solutions will be $\\Delta$.  This approach is not secure, because as soon as the server accesses $\\ddot{o}_{\\scriptscriptstyle 1}$ and public parameters, it can in parallel perform $T$ squaring on every generator, i.e. $r^{\\scriptscriptstyle 2^{\\scriptscriptstyle T}}_{\\scriptscriptstyle i}$, for all $i, 1\\leq i\\leq z$. In this case, as soon as $\\ddot{o}_{\\scriptscriptstyle 1}$ is solved and  $\\ddot{o}_{\\scriptscriptstyle 2}$  is extracted, it has enough information to  immediately solve $\\ddot{o}_{\\scriptscriptstyle 2}$ and accordingly the rest of the puzzles without doing any further exponentiation. \n\\end{remark}\n", "meta": {"hexsha": "65daa66f4ef44ecfad0f21bb9fe38bb19cb5c25a", "size": 4773, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Paper/eprint-version/remarks.tex", "max_stars_repo_name": "AydinAbadi/CR-LP", "max_stars_repo_head_hexsha": "b2139df715f441a48eeae0b88e038fb6acc5d6e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Paper/eprint-version/remarks.tex", "max_issues_repo_name": "AydinAbadi/CR-LP", "max_issues_repo_head_hexsha": "b2139df715f441a48eeae0b88e038fb6acc5d6e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Paper/eprint-version/remarks.tex", "max_forks_repo_name": "AydinAbadi/CR-LP", "max_forks_repo_head_hexsha": "b2139df715f441a48eeae0b88e038fb6acc5d6e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 149.15625, "max_line_length": 1576, "alphanum_fraction": 0.7601089462, "num_tokens": 1252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.30985973660344424}}
{"text": "\\documentclass[aspectratio=169]{beamer}\n\\usepackage[utf8]{inputenc}\n\\usepackage{hyperref}\n\\usepackage{amsmath,amsfonts,amsthm,bm}\n\\usepackage{color}\n\\usepackage{minted}\n\\usepackage{graphicx} % Allows including images\n\\usepackage{booktabs} % Allows the use of \\toprule, \\midrule and \\bottomrule in tables\n\\usepackage{tikz}\n\\usepackage[version=3]{mhchem}\n\\usepackage{pgfplots}\n\\pgfplotsset{compat=1.16} \n\\setminted{fontsize=\\scriptsize}\n\n\\hypersetup{\n    colorlinks=true,\n    linkcolor=red,\n    filecolor=magenta,      \n    urlcolor=red,\n}\n\n\\DeclareMathOperator*{\\argmax}{argmax}\n\\DeclareMathOperator*{\\argmin}{argmin}\n\\let \\vec \\mathbf\n\n\\mode<presentation> {\n    \\usetheme{CambridgeUS}\n    %\\setbeamertemplate{footline} % To remove the footer line in all slides uncomment this line\n    \\setbeamertemplate{footline}[page number] % To replace the footer line in all slides with a simple slide count uncomment this line\n    \\setbeamertemplate{navigation symbols}{} % To remove the navigation symbols from the bottom of all slides uncomment this line\n}\n\n\n\\title[Linear Classification]{Linear Classification}\n\n\\author{Shyue Ping Ong}\n\\institute[UCSD]{University of California, San Diego\\\\\n\\medskip\n}\n\\date{NANO281} % Date, can be changed to a custom date\n\n\\begin{document}\n\n\n\\begin{frame}\n    \\titlepage % Print the title page as the first slide\n\\end{frame}\n\n\n\\begin{frame}{Overview}\n    \\tableofcontents\n\\end{frame}\n\n\n\\section{Preliminaries}\n\n\\begin{frame}{Preliminaries}\n    \\begin{itemize}\n        \\item Linear methods can also be used for classification, i.e., decision boundaries are linear.\n        \\item These methods are surprisingly effective across a large spectrum of datasets, even compared to more complex ML models.\n    \\end{itemize}\n\\end{frame}\n\n\n\\begin{frame}{Metal vs Insulator Dataset}\n    \\begin{itemize}\n        \\item To demonstrate the use of these methods, we will first discuss the ``toy'' dataset.\n        \\item 2000+ binary (\\ce{A_xB_y}) compounds with experimental band gaps.\n        \\item Class 0: metals; Class 1: insulators.\n        \\item Using pymatgen, we can generate some simple features. Here, we will create simply features based on the mean and absolute difference in electronegativity between A and B (why?).\n    \\end{itemize}\n    \\begin{figure}\n        \\centering\n        \\includegraphics[width=0.35\\textwidth]{figures/electronnegativity_bandgap.png}\n    \\end{figure}\n\\end{frame}\n\n\n\\begin{frame}[fragile]{Creating the features and classes}\n\\inputminted{python}{example_element_features.py}\n\\end{frame} \n\n\n\\section{Basic concepts}\n\n\\begin{frame}{Basic concepts}\n    \\begin{itemize}\n        \\item If there are $K$ classes, we have a $N \\times K$ indicator response matrix. Each row is a vector $Y = (Y_1, Y_2, ..., Y_K)$ where $Y_k = 1$ if the instance belongs to the $k$th class and all other $Y$s are 0.\n        \\begin{equation*}\n            \\vec{Y} = \\begin{pmatrix}\n            0 & 0 & ... & 1\\\\\n            1 & 0 & ... & 0\\\\\n            ...& & &\\\\\n            0 & 1 & ... & 0\\\\\n            \\end{pmatrix}\n        \\end{equation*}\n        \\item For the $k$th response variable, the fitted $\\hat{f_k}(x) = \\hat{\\beta_{k0}} + \\hat{\\beta_{k}^T}x$.\n        \\item Decision boundary between $k$ and $l$ class is given by $\\hat{f_k}(x) = \\hat{f_l}(x)$. \n        \\item Input is divided into regions.\n        \\item Similar to linear regression, we can augment the input space with polynomial (e.g., $X_1^2, X_2^s, X_1X_2$) and other basis functions, leading to boundaries that are non-linear.\n    \\end{itemize}\n\\end{frame} \n\n\n\\begin{frame}\n\\frametitle{Linear regression of indicator matrix}\n\\begin{columns}\n\\column{0.5\\textwidth}\n    \\begin{itemize}\n        \\item Treat each column of $\\vec{Y}$ as a target. Least squares solution:\n        \\begin{equation*}\n            \\hat{\\vec{Y}} = \\vec{X}(\\vec{X}^T\\vec{X})^{-1}\\vec{X}^T\\vec{Y}\n        \\end{equation*}\n        \\item For each new observation $x$, we compute $\\hat{f_k}(x) = (1, x^T)(\\vec{X}^T\\vec{X})^{-1}\\vec{X}^T\\vec{Y}$.\n        \\item Find the largest component, and that will result in the classification k, $G(x) = \\argmax_{k \\in G} \\hat{f_k}(x)$.\n        \\item Major issue: some categories may be masked for $K \\geq 3$.\n    \\end{itemize}\n\\column{0.5\\textwidth}\n    \\begin{figure}\n        \\centering\n        \\includegraphics[width=0.8\\textwidth]{figures/linearclassifier.pdf}\n    \\end{figure}\n\\end{columns}\n\\end{frame} \n\n\n\\section{Discriminant Analysis}\n\n\\begin{frame}{Discriminant Analysis}\n    \\begin{itemize}\n        \\item From Bayes rule, we have:\n        \\begin{equation*}\n            P(G = k|X = x) = \\frac{f_k(x)\\pi_k}{\\sum_{l=1}^K f_l(x)\\pi_l}\n        \\end{equation*}\n        \\item where $f_k(x)$ are the class conditional probability densities ($P(X = x | G=k)$) and $\\pi_k$ are the prior probabilities of being in class $k$.\n        \\item Most common approach - assume Gaussian class densities.\n        \\begin{equation*}\n            f_k(x) = \\frac{1}{(2\\pi)^{p/2}|\\Sigma_k|^{1/2}}\\exp{-\\frac{1}{2}(x-\\mu_k)^T\\Sigma_k^{-1}(x-\\mu_k)}\n        \\end{equation*}\n    \\end{itemize}\n\\end{frame} \n\n\n\\begin{frame}{Linear Discriminant Analysis}\n    \\begin{itemize}\n        \\item Assume all classes have a common covariance matrix, i.e., $\\Sigma_k = \\Sigma$.\n        \\item To compare two classes $k$ and $l$, we can compare the log ratios.\n        \\begin{eqnarray*}\n            \\log{\\frac{P(G = k|X = x)}{P(G = l|X = x)}} & = & \\log{\\frac{f_k(x)}{f_l(x)}} + \\log{\\frac{\\pi_k}{\\pi_l}}\\\\\n            & = & \\log{\\frac{\\pi_k}{\\pi_l}} -\\frac{1}{2}(\\mu_k+\\mu_l)^T\\Sigma^{-1}(\\mu_k-\\mu_l) \\\\\n            & & + x^T \\Sigma^{-1} (\\mu_k - \\mu_l)\n        \\end{eqnarray*}\n        \\item At the decision boundary, $P(G=k|X=x) = P(G=l|X=x)$, which leads to a linear equation in $x$.\n        \\item Equivalently, we have\n        \\begin{equation*}\n            G(x) = \\argmax_k \\left \\{ \\log{\\pi_k} -\\frac{1}{2}\\mu_k^T\\Sigma^{-1}\\mu_k + x^T \\Sigma^{-1} \\mu_k \\right \\}\n        \\end{equation*}\n    \\end{itemize}\n\\end{frame}\n\n\n\\begin{frame}{Linear Discriminant Analysis, contd.}\n    \\begin{itemize}\n        \\item In general, we do not know the prior distributions and covariance matrix. These are estimated from the data.\n        \\begin{itemize}\n            \\item $\\hat{\\pi_k} = N_k/N$\n            \\item $\\hat{\\mu_k} = \\sum_{g_i=k} x_i / N$\n            \\item $\\hat{\\Sigma} = \\sum_{k=1}^K \\sum_{g_i=k} (x_i - \\hat{\\mu_k})^T(x_i - \\hat{\\mu_k}) / (N - K)$\n        \\end{itemize}\n        \\item Avoids masking problem of linear regression classification.\n        \\item For the example data,\n        \\begin{figure}\n            \\centering\n            \\includegraphics[width=0.35\\textwidth]{figures/lda_metal_insulator.png}\n        \\end{figure}\n    \\end{itemize}\n\\end{frame}\n\n\n\\begin{frame}{Quadratic Discriminant Analysis}\n    \\begin{itemize}\n        \\item Covariances are not assumed equal.\n        \\begin{equation*}\n            G(x) = \\argmax_k \\left \\{ \\log{\\pi_k} -\\frac{1}{2}(x-\\mu_k)^T\\Sigma_k^{-1}(x-\\mu_k) -\\frac{1}{2} \\log{|\\Sigma_k|} \\right \\}\n        \\end{equation*}\n        \\item No cancellation of terms and decision boundaries are quadratic.\n        \\item Covariances must be estimated for each category.\n        \\item For the same metal-insulator example,\n        \\begin{figure}\n            \\centering\n            \\includegraphics[width=0.35\\textwidth]{figures/qda_metal_insulator.png}\n        \\end{figure}\n    \\end{itemize}\n\\end{frame}\n\n\n\\begin{frame}[fragile]{Discriminant analysis in scikit-learn}\n\\inputminted{python}{example_sklearn_discriminant_analysis.py}\n\\end{frame} \n\n\n\\begin{frame}{Logistic regression}\n    \\begin{itemize}\n        \\item Model posterior probabilities with linear function.\n        \\begin{eqnarray*}\n            \\log{\\frac{P(G=1|X=x)}{P(G=K|X=x)}} & = & \\beta_{10} + \\beta_1^T x\\\\\n            \\log{\\frac{P(G=2|X=x)}{P(G=K|X=x)}} & = & \\beta_{20} + \\beta_2^T x\\\\\n            & ... &\\\\\n            \\log{\\frac{P(G=K-1|X=x)}{P(G=K|X=x)}} & = & \\beta_{(k-1)0} + \\beta_{k-1}^T x\n        \\end{eqnarray*}\n        \\item Results in the following posterior probabilities:\n        \\begin{eqnarray*}\n            P(G=1|X=x) & = & \\frac{\\exp{(\\beta_{10} + \\beta_1^T x)}}{1 + \\sum_{l=1}^{K-1}\\exp{(\\beta_{l0} + \\beta_l^T x})}\\\\\n            P(G=K|X=x) & = & \\frac{1}{1 + \\sum_{l=1}^{K-1}\\exp{(\\beta_{l0} + \\beta_l^T x})}\n        \\end{eqnarray*}\n    \\end{itemize}\n\\end{frame} \n\n\n\\begin{frame}{Solving for the Logistic Regression Coefficients}\n    \\begin{itemize}\n        \\item Typically fitted using \\textit{maximum likelihood}.\n        \\begin{equation*}\n            l(\\beta) = \\sum_{i=1}^N \\log {P(G = k | X = x i; \\beta)}\n        \\end{equation*}\n        \\item Differentiation and setting $\\frac{\\partial{l}}{\\partial{\\beta}} = 0$ leads to equations that are non-linear in $\\beta$.\n        \\item These equations are solved using some optimization algorithm (e.g., Newton-Raphson, BFGS, etc.). \n    \\end{itemize}\n\\end{frame} \n\n\n\\begin{frame}[fragile]{Logistic regression on metal/insulator dataset}\n\\inputminted{python}{example_sklearn_logistic__regression.py}\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=0.5\\textwidth]{figures/logistic_metal_insulator.png}\n\\end{figure}\n\\end{frame} \n\n\\begin{frame}\n    \\Huge{\\centerline{The End}}\n\\end{frame}\n\n\\end{document}\n\n", "meta": {"hexsha": "6adb058807391a9ef538449f882cf99d228afa21", "size": 9245, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "lectures/slides_tex/04-Linear_Classification.tex", "max_stars_repo_name": "materialsvirtuallab/nano281", "max_stars_repo_head_hexsha": "d527c5049aab3da99237cbff0cc749640b2c9c06", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 38, "max_stars_repo_stars_event_min_datetime": "2019-12-23T13:14:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T23:59:33.000Z", "max_issues_repo_path": "lectures/slides_tex/04-Linear_Classification.tex", "max_issues_repo_name": "materialsvirtuallab/nano281", "max_issues_repo_head_hexsha": "d527c5049aab3da99237cbff0cc749640b2c9c06", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lectures/slides_tex/04-Linear_Classification.tex", "max_forks_repo_name": "materialsvirtuallab/nano281", "max_forks_repo_head_hexsha": "d527c5049aab3da99237cbff0cc749640b2c9c06", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2020-02-10T20:43:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T13:45:36.000Z", "avg_line_length": 37.581300813, "max_line_length": 222, "alphanum_fraction": 0.631151974, "num_tokens": 2935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.3098597366034442}}
{"text": "\\documentclass[a4paper, leqno]{article}\n\n\\usepackage{amsmath, amsthm, amssymb, amsfonts, subfiles}\n\\usepackage{enumerate}\n\\usepackage{times, mathptmx}\n\\usepackage{fancyhdr}\n\n\\newtheorem{theorem}{Theorem}\n\\newtheorem{proposition}{Proposition}\n\\newtheorem{identity}{Identity}\n\\newtheorem{corollary}{Corollary}\n\n\\theoremstyle{definition}\n\\newtheorem{definition}{Definition}\n\\newtheorem{problem}{Problem}\n\\newtheorem*{solution}{Solution}\n\n\\theoremstyle{remark}\n\\newtheorem*{example}{Example}\n\n\\newcommand{\\lcm}{\\text{lcm}}\n\n\\author{\\itshape Masum Billal}\n\\title{\\scshape Nurani Number Theory}\n\n\\pagestyle{fancy}\n\\fancyhf{}\n\\fancyhead[LE,RO]{Nurani Number Theory}\n\\fancyhead[RE,LO]{Masum Billal}\n\\fancyfoot[CE,CO]{\\thepage}\n\n\\begin{document}\n\t\\maketitle\n\t\\titlepage\n\t\\section*{Preface ($2016$ Edition)}\n\t\tThis is an edited version of a note I wrote in $2010-2011$ (approximately). The primary objective was not to write a note though. I used to write something everyday as a habit of practicing \\LaTeX, specially when I learned about a new feature. The end result was this note. For that reason, you can see that the original document structure (I lost the source file of that one, so I re-wrote it) is quite clumsy. Also, some topics seem random and not really connected to the main topic. I am keeping them here anyway since they may be useful after all.\n\t\t\n\t\tThe note was meant for BdMO math campers. However, it may be useful for any newcomer looking for interesting problems and ideas to solve them. This is not a textbook. And you should not use it as a reference for something rigorous such as definitions. The reason is that, I have focused more on making the sense rather than stating something rigorous that makes less sense. Moreover, I could not write too much at that time and even though I am writing it now, I hardly have the time to improve it or add more to it. You can see the references section for further reading.\n\t\t\n\t\tI want to take this chance to clear something up. From my personal experience, I have seen most of the beginners try to learn lots of theorems in order to be able to solve problems. They do this mostly as a mean of shortcut. I have tried a lot to change that thinking among the students. But it has become a tradition to follow that one must know thousands of theorems so everyone calls you master of number theory. There are two things to mention here. One is that you can never become a master of number theory. Second is that, even though the word \\texttt{theory} is juxtaposed with \\textbf{Number Theory}, by no means it implies that you must or should know a lot of theorems. \\textbf{Stop memorizing theorems just because you think it's cool to tell others you know this theorem or that theorem}.\n\t\t\n\t\tHere is a real life example. Probably the first book I ever read for problem solving was \\textit{Problem Solving Strategies} by \\textsc{Arthur Engel}. I could not understand any of the first five chapters, so I skipped to chapter $6$, Number Theory. I could understand the facts discussed in the early section of that chapter. Then I skipped to the exercises. There were some problems I could not solve.\n\t\t\t\\begin{enumerate}\n\t\t\t\t\\item If $a+b+c$ is divisible by $6$, then so is $a^3+b^3+c^3$.\n\t\t\t\t\\item If an integer can be expressed as a sum of squares, so can be the square of that integer.\n\t\t\t\\end{enumerate}\n\t\tNow, this turned into something embarrassing when I saw the solutions. One can find brute force solutions for them. For example, I posed this problem to someone. He mentioned parity and considering cases of remainders upon division by $3$ etc. See this ingenious solution now. $a^3-a=a(a-1)(a+1)$, these are three consecutive integers. So, one is divisible by $2$, another by $3$. Consequently, the product is divisible by $6$. Therefore, $a^3-a+b^3-b+c^3-c=a^3+b^3+c^3-(a+b+c)$ is divisible by $6$, no matter what. This does not require any theory or any knowledge except for pure thinking. And that is the case for number theory, not the other way around. When I told \\textit{Po-Shen Loh} this solution, he was like, \"It's really nice!\".\\footnote{Po-Shen Loh is the coach of USAIMO team.}\n\t\t\n\t\tWith that said, after you are done with this book, you may think that I am being two faced here. Therefore, I will explain it more. At first I have tried to show why you should solve problems as if you know nothing. That means, you will solve everything right from the start without any heads up. Once you think that you are at the point where you can find theorems or lemmas associated with a problem to solve, you will know what I mean. After that, you are ready to read about any book in number theory (though it depends on the pre-requisite of that book). The point is that, you should realize, we use theorems just to speed up our thinking process and save the time of doing the same thing twice all over again. We should not use theorems to actually solve problems. That is the reason why there is no choice but to discuss theorems when we talking about number theory. But this does not imply in any way that theorem is the core of number theory. It only means that we will study how the numbers dance and develop interesting properties. Although this is my personal opinion, I have found it to be true practically that, if you use theorems as means of solving problems rather than spending the time to gain your intuitive maturity, you can not solve problems beyond a certain level (roughly saying, I do not intend to argue about level of problems or anything). I hope you get my point. Even if you don't, it will not matter to me. But it will matter to me a lot if someone tries not to use theorems to make sense of something.\n\t\t\n\t\tSince this note was not reviewed or edited by anyone else, it may contain errors. One may find the definitions or some proofs too informal, but that is precisely the reason of creating this document. So, please do not brag about formality in this regard. Making better sense of something is more important to me than stating something that does not make a whole lot sense.\n\t\t\n\t\tFinally, I would like to mention that you can use or distribute it however you like as long as you don't use it for financial gain. Also, please don't share it after changing it yourself. If you want to change something, tell me first\\footnote{I have decided not to let anyone change it manually every time someone wants to include/edit something. Rather you should do it in \\textbf{Git} and create a pull request.}. Feel free to email me for making this better or if you want to be a contributor.\n\t\t\t\\begin{flushright}\n\t\t\t\t\\slshape Masum Billal\\\\\n\t\t\t\t\\date{October $10$, $2016$}\n\t\t\t\\end{flushright}\n\t\t\\newpage\n\t\\section{Divisibility}\n\t\tNote the following division of $97$ by $24$.\n\t\t\t\\begin{align*}\n\t\t\t\t97 & = 4\\cdot24+1\n\t\t\t\\end{align*}\n\t\tIn this division, we call $4$ the \\textit{quotient} (the result of the division) and $1$ the \\textit{remainder} (the part which was left) of this division. For the division $96 = 24 · 4 + 0$ we have the remainder $0$. In this case, we say that $96$ is divisible by $24$ (so by $4$ as well).\n\t\t\t\\begin{definition}\n\t\t\t\tLet $a$ and $b$ be two natural numbers such that $b$ leaves remainder $0$ upon division by $a$. Then $b$ is said to be divisible by $a$. We denote it by $a|b$. Sometimes, the notation $b\\vdots a$ is also used. But in this note, we shall make use of the notation of $a|b$ mostly.\n\t\t\t\t\n\t\t\t\tHere, $a$ is called a \\textit{divisor} or \\textit{factor} of $b$ and $b$ is called a \\textit{multiple} of $a$. If $b$ leaves $a$ remainder other than $0$, then $b$ is not divisible by $a$ and is denoted by $a\\nmid b$. Moreover, unless stated explicitly, we usually assume the associated integers are positive integers.\n\t\t\t\\end{definition}\n\t\t\t\n\t\t\t\\begin{example}\n\t\t\t\t$7|343$, $565655$ is a multiple of $5$, $29$ is a divisor of $841$ and so on.\n\t\t\t\\end{example}\n\t\tTry some more examples and make sure with the notations and definitions of divisibility. Because your further reading of this note requires this excellency.\n\t\t\t\\begin{definition}[Prime and Composite]\n\t\t\t\tA natural number $n$ is \\textit{prime} if it has exactly $2$ positive divisors. Any positive integer that has more than $2$ positive divisors is a \\textit{composite number}.\n\t\t\t\\end{definition}\n\t\tYou may notice that this definition is a bit different from what you know. But this definition clears up the ambiguity that keeps going around regarding $1$: is $1$ a prime or not?\n\t\t\t\\begin{example}\n\t\t\t\t$2$ is the only even prime. If an even number is greater than $2$, then it must be divisible by $2$. Thus, it can not be a prime. First $3$ odd primes are $3, 5, 7$.\n\t\t\t\\end{example}\n\t\\subsection{Parity}\n\t\t\\begin{definition}\n\t\t\tIf a number leaves remainder $0$ upon division by $2$, then it is \\textit{even}. If it leaves the remainder $1$, then it is  \\textit{odd}. The property of a number being even or odd is called \\textit{parity}. Two numbers are of the same parity if they both are odd or both are even. Otherwise they are of opposite parity. In other words, if two numbers give same remainder upon division by $2$, they are of the same parity, otherwise they are of opposite parity.\n\t\t\\end{definition}\n\t\t\n\t\t\\begin{example}\n\t\t\t$5$ and $7$ are of the same parity, whereas $4$ and $3$ are not.\n\t\t\\end{example}\n\t\t\n\t\t\\begin{proposition}\n\t\t\tThe following statements are true.\n\t\t\t\t\\begin{enumerate}[i.]\n\t\t\t\t\t\\item The sum and difference of two numbers of the same parity is even.\n\t\t\t\t\t\\item The sum and difference of two numbers of different parity is odd.\n\t\t\t\t\t\\item Increasing or decreasing a number by a multiple of 2 does not change\n\t\t\t\t\tthe parity.\n\t\t\t\t\t\\item Any odd multiple of a number has the same parity of the number, and\n\t\t\t\t\tfor even multiple has a parity even.\n\t\t\t\t\t\\item The parity remains unchanged after raising to a power.\n\t\t\t\t\\end{enumerate}\n\t\t\\end{proposition}\n\t\t\n\t\t\\begin{problem}\n\t\t\tThe difference of two odd numbers is divisible by $2$ but not by $4$. Prove\n\t\t\tthat their sum is divisible by $4$.\n\t\t\\end{problem}\n\tHow do we proceed to solve this? Since this involves divisibility by $2$, we should at least give parity a try. Here are two solutions.\n\t\t\\begin{solution}[$1$]\n\t\t\tWe have to take two odd number. So let us do the most obvious thing and assume that $2a+1$ and $2b+1$ are two odd numbers. From the condition, $2a+1-(2b+1)=2(a-b)$ is not divisible by $4$. This tells us that $a-b$ is odd. In that case, $a-b=2x+1$ for some integer $x$. We are required to show that $a+b$ must be divisible by $4$.\n\t\t\t\t\\begin{align*}\n\t\t\t\t\ta+b & =2a+1+2b+1\\\\\n\t\t\t\t\t\t& = 2(b+2x+1)+1+2b+1\\\\\n\t\t\t\t\t\t& = 4b+4x+4\\\\\n\t\t\t\t\t\t& = 4(b+x+1)\n\t\t\t\t\\end{align*}\n\t\t\tThis is certainly divisible by $4$.\n\t\t\\end{solution}\n\t\n\t\t\\begin{solution}[$2$]\n\t\t\tWhat would be a good alternative approach to prove this claim? Since we need to prove some divisibility regarding $4$, we should consider what happens when we divide odd numbers by $4$. And not very surprisingly we find that an odd number is either of the form $4k+1$ or of the form $4l+3$. Therefore, we have three cases.\n\t\t\t\t\\begin{enumerate}[(a)]\n\t\t\t\t\t\\item Both odd numbers are of the form $4k+1$. However, this can not hold. The reason is that this would imply their difference is divisible by $4$ since $4k+1-(4l+1)=4(k-l)$.\n\t\t\t\t\t\\item Both odd numbers are of the form $4k+3$. Same argument shows that this can not be true as well.\n\t\t\t\t\t\\item We are only left with the option where one is of the form $4k+1$ and the other is of the form $4l+3$. This indeed complies with the condition of the statement since $4k+1-(4l+3)=2(2k-2l+1)$ and $2k-2l+1$ is odd. And if we sum them now, $4k+1+4l+3=4(k+l+1)$ is found to be divisible by $4$.\n\t\t\t\t\\end{enumerate}\n\t\t\\end{solution}\n\tA clever reader would ask themselves, how do we jump to the third case without checking the first two manually? This kind of thinking can lead you to direct and better solutions, whereas others may find some tedious solutions.\n\t\t\\begin{proposition}\n\t\t\tLet $a$ and $b$ be two positive integers.\n\t\t\t\t\\begin{enumerate}[i.]\n\t\t\t\t\t\\item If $a|b$, then $\\dfrac{b}{a}$ is an integer. So, there is an integer $k$ such that $\\dfrac{b}{a}=k$ or $b=ak$. Moreover, we can say that $k|b$.\n\t\t\t\t\t\\item For any integer $a$, $a|a$ and $a|0$.\n\t\t\t\t\t\\item If $0|a$ then $a$ must be $0$.\n\t\t\t\t\t\\item If we assume that $a|b$ then $|b|\\geq |a|$ where $|a|$ denotes the absolute value of integer $b$.\\footnote{This claim has a flaw in it. Find it!}\n\t\t\t\t\t\\item The claim above is not entirely true. The only exception is that $b=0$.\n\t\t\t\t\t\\item Let $c$ be an integer such that $a|c$. If $a|b$ holds true as well, $a|b\\pm c$.\n\t\t\t\t\t\\item This proposition can be generalized. If $a|b$ and $a|c$ then for any two integers $x,y$ we have $a|bx+cy$.\n\t\t\t\t\t\\item[Euclid's Lemma] If $p$ is a prime and $a,b$ are positive integers such that $p$ divides $ab$, then at least one of $p|a$ or $p|b$ must be true.\n\t\t\t\t\t\\item The least positive remainder in a division is unique.\n\t\t\t\t\t\n\t\t\t\t\t{\\normalfont If $a|b$, then it must leave a remainder other than $0$. Say, it is $r$. Then, $b-r$ would be divisible by $a$. Let\n\t\t\t\t\t\t\\begin{align*}\n\t\t\t\t\t\t\tb-r=aq & \\iff b=aq+r\n\t\t\t\t\t\t\\end{align*}\n\t\t\t\t\tWhen we mention such a remainder $r$, we usually mean the least positive remainder. To explain this, take the example $23=5\\cdot4+3=5\\cdot3+8$. So technically both $3$ and $8$ are remainders. But $3$ is the least positive remainder when $23$ is divided by $5$. Moreover, notice that the least positive remainder is less than the dividing number.\n\t\t\t\t\t\n\t\t\t\t\tWhat the proposition says is that, for positive integer $a,b$ there are unique integer $q$ and a unique positive integer $r$ such that $b=aq+r$ and $0\\leq r<a$. We can prove this easily as well. And the uniqueness of $r$ can prove the uniqueness of $q$ as well (and vice versa). For the sake of contradiction, suppose that,\n\t\t\t\t\t\t\\begin{align*}\n\t\t\t\t\t\t\tb = aq_1+r_1 & = aq_2+r_2\n\t\t\t\t\t\t\\end{align*}\n\t\t\t\t\twhere both $0\\leq r_1,r_2<a$. From the latter, we get\n\t\t\t\t\t\t\\begin{align*}\n\t\t\t\t\t\t\ta(q_1-q_2) & = r_2-r_1\n\t\t\t\t\t\t\\end{align*}\n\t\t\t\t\tThis equation says that $a$ divides $r_2-r_1$. Unless $|r_2-r_1|=0$, this can not be true (why?). The conclusion follows.}\n\t\t\t\t\t\\item For all composite $n > 1$, $n$ has a prime divisor $p$ such that\n\t\t\t\t\t\t\\begin{align*}\n\t\t\t\t\t\t\tp & \\leq \\sqrt{n}\n\t\t\t\t\t\t\\end{align*}\n\t\t\t\t\t{\\normalfont First you should think for yourself why this has to be true. Actually, no. First you should think if this is even true at all or I am playing with you. After you play around with some examples and convince yourself that this might actually be true, only then you can work on proving it. And this goes for all problems in general. Take $n=12$ and $n=35$. They have prime divisors $2$ and $5$. Take some more and you should realize why this must be true.\n\t\t\t\t\t\n\t\t\t\t\tAssume that the smallest prime factor of $n$ is $p$. Then $n = pk$ for some\n\t\t\t\t\t$k\\geq p$. If $k < p$, then $k$ would have at least one prime factor less than\n\t\t\t\t\t$p$, but that is not possible. Therefore, $k \\geq p$. Then\n\t\t\t\t\t\t\\begin{align*}\n\t\t\t\t\t\t\tn & = kp\\\\\n\t\t\t\t\t\t\t  & \\geq p^2\\\\\n\t\t\t\t\t\t\t\\iff p& \\leq \\sqrt{n}\n\t\t\t\t\t\t\\end{align*}\n\t\t\t\t\tUsing this property, we can determine whether a number is a prime or\n\t\t\t\t\tnot. Though this is not an efficient approach at all, it is very useful for\n\t\t\t\t\tsmall numbers.}\n\t\t\t\t\\end{enumerate}\n\t\t\\end{proposition}\n\t\n\t\\section{GCD-LCM}\n\t\tTake the numbers $18$ and $12$ and consider their divisors. The list of their divisors is\n\t\t\t\\begin{align*}\n\t\t\t\t\\{1,2,3,6,9,18\\} & , \\{1,2,3,4,6,12\\}\n\t\t\t\\end{align*}\n\t\tSince $1$ belongs to both list, we will have at least one element common. But is there any other common element? In this case we have $1,2,3,6$. The greatest one among these common divisors is $6$. We call $6$ the \\textit{greatest common divisor} of $12$ and $18$. We denote the greatest common divisor of $a$ and $b$ by $\\gcd(a,b)$ or shortly $(a,b)$. In this note, we shall use this notation for brevity. When $(a,b) = 1$ that is two numbers do not have a common divisor other than $1$, then $a$ is called to be co-prime or relatively\n\t\tprime with $b$ and is denoted by $a \\bot b$.\n\t\t\t\\begin{example}\n\t\t\t\t$(6,28) = 2$, because $2$ is the most common part among them. $56\\bot 243$, since $56=2^3\\cdot7$ and $243=3^5$ do not share any common factor other than $1$.\n\t\t\t\\end{example}\n\t\tCan you prove that it must be unique for any two positive integer? \\textit{Least common multiple} follows from the idea of greatest common divisor. Both $a$ and $b$ have infinite multiples namely\n\t\t\t\\begin{align*}\n\t\t\t\ta\\cdot1,a\\cdot2,\\cdots\\\\\n\t\t\t\tb\\cdot1,b\\cdot2,\\cdots\n\t\t\t\\end{align*}\n\t\tFor example, the multiples of $12$ are $12,24,36,\\ldots$ The multiples of $18$ are $18,36,\\ldots$. Now, an analogous question to greatest common divisor would be, is there a multiple of $12$ that is a multiple of $18$ as well? Well, the answer is simple. Yes, $12\\cdot18$. Ok, but this makes us ask something not so obvious. What is the smallest possible positive integer that is a multiple of both $12$ and $18$? We know that such a multiple exists but the product of those two positive integers may not be the one we are looking for. In this case, $12\\cdot18=216$ but as we can see, $36$ is the number with the desired property. We call $36$ the least common multiple of $12$ and $18$. It is denoted by $\\lcm(a,b)$ or shortly $[a,b]$ sometimes.\n\t\t\t\\begin{definition}\n\t\t\t\t$\\gcd(a,b)$ is the greatest positive integer that divides both $a$ and $b$. $\\lcm(a,b)$ is the least positive integer that is divisible by both $a$ and $b$.\n\t\t\t\\end{definition}\n\t\t\t\n\t\t\t\\begin{proposition}\n\t\t\t\tAssume that $g$ and $l$ are the greatest common divisor and least common multiple of two positive integers $a$ and $b$ respectively.\n\t\t\t\t\t\\begin{enumerate}\n\t\t\t\t\t\t\\item By definition, $g|a,b$ and $a,b|l$.\n\t\t\t\t\t\t\\item $a$ divides $b$ if and only if $(a,b)=a$.\n\t\t\t\t\t\t\\item Consequently, $g|l$, therefore, $l\\geq a,b\\geq g$ holds.\n\t\t\t\t\t\t\\item If $p$ is a prime divisor of $a$ or $b$, then $p|l$. Similarly, if $q$ is a prime divisor of $g$, $q|a,b$.\n\t\t\t\t\t\t\\item For any integers $x,y$ $g|ax+by$.\n\t\t\t\t\t\t\\item $ab=gl$.\n\t\t\t\t\t\t{\\normalfont This is easy to make sense. Since $g$ is the greatest common divisor, we can divide both $a$ and $b$ by $g$. Assume that, $a=gm$ and $b=gn$. From the definition, $m$ and $n$ can not have any common factor. This also means that $l=gmn$ (why?). The rest follows.}\n\t\t\t\t\t\t\\item $(a,a)=a$ and $(a,0)=a$. Similarly, $[a,a]=a$ and $[a,0]=0$.\n\t\t\t\t\t\t\\item[Euclidean Algorithm] If $b=aq+r$, then $(a,b)=(a,r)$.\n\t\t\t\t\t\t{\\normalfont Probably you have already used it in $4$th or $5$th grade. But have you ever wondered why this works? Why does a same method not work for least common multiple? You can easily understand the reason if you think a bit. $g|a$ and $g|b=aq+r$. Then, $g|b-aq=r$ as well. This says that the greatest common divisor would be in the remainder too.}\n\t\t\t\t\t\t\\item For positive integers $m,n$ $a^m\\bot b^n$ if and only if $a\\bot b$.\n\t\t\t\t\t\\end{enumerate}\n\t\t\t\\end{proposition}\n\t\tProve the last proposition yourself.\n\t\t\\section{Some Identities}\n\t\t\t\\begin{identity}[Sophie Germain Identity]\n\t\t\t\tLet $a,b$ be positive integers.\n\t\t\t\t\t\\begin{align*}\n\t\t\t\t\t\ta^4+4b^4 & = (a^2+2ab+2b^2)(a^2-2ab+2b^2)\n\t\t\t\t\t\\end{align*}\n\t\t\t\tYou may have already seen this while learning how to factorize\\footnote{In Bangladesh, students are taught some factoring techniques such as \\textit{middle term factor, completing the square}.}.\n\t\t\t\\end{identity}\n\t\t\t\n\t\t\t\\begin{corollary}\n\t\t\t\tIf $a,b>1$ then $a^4+4b^4$ is composite.\n\t\t\t\\end{corollary}\n\t\tProve this. Also prove the opposite.\n\t\t\t\\begin{problem}\n\t\t\t\tIf $a^4+4b^4$ is a prime for natural number $a,b$, then $a=b=1$.\n\t\t\t\\end{problem}\n\t\tThe next identity is also taught in our high school. However, not many students of grade $9/10$ realize or know this.\n\t\t\t\\begin{identity}\\label{id:geodiv}\n\t\t\t\tLet $n$ be a positive integer.\n\t\t\t\t\t\\begin{align*}\n\t\t\t\t\t\ta^n-b^n & = (a-b)(a^{n-1}+a^{n-2}b+\\cdots+ab^{n-2}+b^{n-1})\n\t\t\t\t\t\\end{align*}\n\t\t\t\\end{identity}\n\t\tHow many ways can you prove this? Induction is certainly a way. How about trying to find the sum $a^{n-1}+a^{n-2}b+\\cdots+ab^{n-2}+b^{n-1}$? Moreover, can you find any similarity between this sum and a geometric series? Does that enable you to find a solution that is similar to finding the sum of a geometric series?\n\t\t\t\\begin{corollary}\n\t\t\t\tFor two positive integers $a,b$,\n\t\t\t\t\t\\begin{align*}\n\t\t\t\t\t\ta-b & |a^n-b^n\n\t\t\t\t\t\\end{align*}\n\t\t\t\twhere $n$ is a positive integer.\n\t\t\t\\end{corollary}\n\t\t\t\n\t\t\t\\begin{corollary}\n\t\t\t\tIf $n$ is an odd positive integer, then\n\t\t\t\t\t\\begin{align*}\n\t\t\t\t\t\ta+b & |a^n+b^n\n\t\t\t\t\t\\end{align*}\n\t\t\t\\end{corollary}\n\t\tProve this using \\eqref{id:geodiv}.\n\t\t\t\\begin{identity}[Fibonacci-Brahmagupta Identity]\\label{id:fib}\n\t\t\t\tThe product of two sum of squares is a sum of square as well.\n\t\t\t\t\t\\begin{align*}\n\t\t\t\t\t\t(a^2+b^2)(c^2+d^2) & = (ad+bc)^2+(ac-bd)^2\\\\\n\t\t\t\t\t\t\t\t\t\t\t&= (ac+bd)^2+(ad-bc)^2\n\t\t\t\t\t\\end{align*}\n\t\t\t\\end{identity}\n\t\tNote that this product has two representations. Remember the second problem I mentioned in preface? Just notice this. If $n=x^2+y^2$,\n\t\t\t\\begin{align*}\n\t\t\t\tn^2 & = (x^2+y^2)^2\\\\\n\t\t\t\t\t& = (x^2-y^2)^2+4x^2y^2\\\\\n\t\t\t\t\t& = (x^2-y^2)^2+(2xy)^2\n\t\t\t\\end{align*}\n\t\tHere we used the fact $(a+b)^2=(a-b)^2+4ab$. This is something students learn at $6/7$th grade in Bangladesh. Yet, none of the people I asked to prove it has been able to find this simple solution. So, if you still think that the amount of theory you know somehow defines your level\\footnote{If you believe in level theory, that is}, then feel free to contact me. Maybe I can show you a thing or two.\n\t\t\n\t\tAnyway, we can generalize identity \\eqref{id:fib}.\n\t\t\t\\begin{align*}\n\t\t\t\t(a^2+nb^2)(c^2+nd^2) & = (ac-bd)^2+n(ad+bc)^2\n\t\t\t\\end{align*}\n\t\tFind the other representation yourself.\n\t\t\t\\begin{identity}[Bhaskara's Lemma]\n\t\t\t\tLet $n$ be a square-free integer\\footnote{It does not have a divisor that is a perfect square other than $1$. However, we could take $n$ to be any integer and we would only end up with something like $x^2-y^2=l$.} and $k$ be an arbitrary integer. If $y^2-nx^2 = k$ then for any integer $m$,\n\t\t\t\t\t\\begin{align*}\n\t\t\t\t\t\t\\dfrac{(mx+ny)^2}{k}-n\\left(\\dfrac{mx+y}{k}\\right)^2 & = \\dfrac{m^2-n}{k}\n\t\t\t\t\t\\end{align*}\n\t\t\t\\end{identity}\n\t\tThis identity allows us to solve \\textit{Pell-Fermat equation} which is a type of \\textit{Diophantine equation}.\n\t\t\\subfile{mod.tex}\n\t\\begin{thebibliography}{99}\n\t\t\\bibitem{engel} \\textit{Arthur Engel}, Problem-Solving Strategies (Chapter $6$), 1998 Springer-Verlag New York, Inc.\n\t\t\n\t\t\\bibitem{paul} \\textit{Paul Zeitz}, The Art and Craft of Problem Solving (Chapter $7$), John Wiley \\& Sons, Inc.\n\t\t\\bibitem{titu} \\textit{Titu Andreescu, Dorin Andrica}, Number Theory: Structures, Examples, and Problems, Springer, $2009$.\n\t\t\n\t\\end{thebibliography}\n\\end{document}", "meta": {"hexsha": "546201b6ec72c24c3d574efa66059221c433b315", "size": 22819, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "bnt.tex", "max_stars_repo_name": "fifaboy/bnt", "max_stars_repo_head_hexsha": "9a150151c485936e37fe5852aa8d2703d5c87b29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bnt.tex", "max_issues_repo_name": "fifaboy/bnt", "max_issues_repo_head_hexsha": "9a150151c485936e37fe5852aa8d2703d5c87b29", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bnt.tex", "max_forks_repo_name": "fifaboy/bnt", "max_forks_repo_head_hexsha": "9a150151c485936e37fe5852aa8d2703d5c87b29", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 79.2326388889, "max_line_length": 1536, "alphanum_fraction": 0.7028791796, "num_tokens": 6823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.3098597366034442}}
{"text": "\\documentclass[simplex.tex]{subfiles}\n% DO NOT INCLUDE PREAMBLES/PACKAGES HERE!!\n% packages are inherited from preamble.tex; you can compile this on its own\n\\begin{document}\n\\subsection{Graph-testing}\n\nIn neuroimaging connectomics studies, it is often desired to determine\nwhether the observed network properties are statistically significant or\nnot. In order to correctly achieve this, we need to define a null\ndistribution. In order to generate the null distribution, the common\ntechnique is to  generate an average of 1000 samples of graphs with the\nsame degree sequence of the observed graphs. However, this technique\ndoes not yield a uniform sample from the null distribution, resulting in\nill-conditioned tests. Here, we investigate statistically accurate\nmethods in graph testing. \\\\\n\n\nOne strategy that we have explored is generating the null distribution\nby sampling from graphs with the same degree-sequence of the observed\ngraph. While the samples are not generated uniformly, we know how to\nrescale the samples such that we can estimate the mean of the uniform\ndistribution of the graphs. We are currently working on to extend this\nalgorithm to validly estimate the 95 percentile as well. \\\\\n\n\nAnother technique that we have explored is using parametric bootstrap to\nobtain the critical region for any significance level. Namely, we fit a\nstochastic block model to the data and use Generalized Likelihood Ratio\nTest to determine the number of blocks that best fit the data. In the\ninitial experiments, as expected, we see that the power of the test\nincreases as the graph size increase. As the next step, after finding\nthe model that best first the data, we can sample from that distribution\nmany times, compute the test statistic, and get the critical region for\nany significance level. In this strategy we are not conditioning the\ngraphs on their degree sequence, which is an advantage as the graphs\ntend to include noise so we cannot use the observed degree sequence as\nthe ground truth. \n\n%%%   EXAMPLE FIGURE BLOCK\n%\\begin{figure}[!h]\n%\\begin{cframed}\n%\\centering\n%\\includegraphics[width=0.15\\textwidth]{../../figs/neurodata_small.png}\n%\\caption{Please provide a detailed caption for your figure.}\n%\\label{fig:name}\n%\\end{cframed}\n%\\end{figure}\n\n\\clearpage\n\\end{document}\n", "meta": {"hexsha": "d48736917aa9d6979d282b3eca7ab74104604a27", "size": 2289, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Reporting/reports/2017-02/GraphTesting.tex", "max_stars_repo_name": "openconnectome/SIMPLEX_Q2", "max_stars_repo_head_hexsha": "f10a6c4b9548670f9bf8e177914aa8d25fa1230b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Reporting/reports/2017-02/GraphTesting.tex", "max_issues_repo_name": "openconnectome/SIMPLEX_Q2", "max_issues_repo_head_hexsha": "f10a6c4b9548670f9bf8e177914aa8d25fa1230b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Reporting/reports/2017-02/GraphTesting.tex", "max_forks_repo_name": "openconnectome/SIMPLEX_Q2", "max_forks_repo_head_hexsha": "f10a6c4b9548670f9bf8e177914aa8d25fa1230b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.8823529412, "max_line_length": 75, "alphanum_fraction": 0.8003494976, "num_tokens": 510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.30957582814909296}}
{"text": "\\documentclass[]{article}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{color}\n\\usepackage{fancybox}\n\\usepackage{graphicx}\n\\usepackage[pdftex,colorlinks]{hyperref}\n\\usepackage{pdfpages}\n\\renewcommand*\\rmdefault{cmdh}\n%\\usepackage[T1]{fontenc}\n\\newcommand{\\superscript}[1]{\\ensuremath{^{\\textrm{#1}}}}\n\\newcommand{\\subscript}[1]{\\ensuremath{_{\\textrm{#1}}}}\n\\renewcommand{\\thesection}{}\n\n\\def\\thesection{\\arabic{section}}\n\\def\\thesubsection{\\arabic{section}.\\arabic{subsection}}\n\\def\\thesubsubsection{\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}}\n\n\\begin{document}\n\\rmfamily\n\\setcounter{secnumdepth}{3}\n\n\t% Cover Page\n\t\\begin{titlepage}\n\t\t\\includepdf[pages={1}]{title_page.pdf}\t\n\t\\end{titlepage}\n\t\n\t% Introduction\n\t\n\t\\section{Introduction}\n\t\tAs the demand for mixed mode integrated circuits increases, the design of analog circuits such as operational amplifiers in CMOS technology becomes more critical. This technology has become an integral part of many integrated circuit chips fabricated today in a number of application areas. These amplifiers offer a number of advantages in terms of power dissipation, die area, and compatibility with digital circuits when compared to their bipolar counterparts.\n\t\n\t\tIn this paper we design and simulate a specific, widely used operational amplifier architecture, showing in detail how the formulation of the design variables takes place through a number of equations derived and calculated by hand. We then simulate the amplifier using HSPICE, presenting performance measures such as unity-gain bandwidth, open-loop gain, and settling time. We show how the proposed amplifier meets the specifications set in place by the project guidelines. We conclude with a discussion of the characteristics of the amplifier and the overall experience of the design project.\n\t\t\n\t\t% Circuit Schematic\n\t\t\\begin{figure}\n\t\t\t\\subsection{Circuit Schematic}\n\t\t\t\\includegraphics[width=1.2\\textwidth]{CMOS_complete.pdf}\n\t\t\t\\caption{Two stage op-amp considered in this paper.}\n\t\t\\end{figure}\n\t\t\\newpage\n\t\n\t% Hand Analysis Begins Here...\n\t\\section{Part I: Hand Analysis}\n\t\tFor the purposes of designing this amplifier, the design approach is as follows. First, we lay the groundwork for all important equations that must be considered in order to meet the specifications. We note dependencies and realize variables that enable design control. We then begin with the most rigorous specifications and choose our variables to be within margins that exceed the requirements, to provide a safety cushion against non-idealities. We keep all constraints in mind and finalize a design. We confirm that the requirements are met.\n\t\n\t\t\\subsection{Equations}\n\t\n\t\tIn this section, all of the relevant equations required to meet the specifications are listed for the purposes of demonstrating the interdependencies between variables and to illustrate the design process of the amplifier.\n\t\t$$$$\n\t\tSpecifications to be met:\n\t\n\t\t\\begin{itemize}\n\t\t\t\\item Gain $\\ge 1500 $\n\t\t\t\\item Output Swing : 1.2V\n\t\t\t\\item Settling Time : 8ns with 0.4V step\n\t\t\t\\item Unity Gain Frequency $\\ge 600 MHz$\n\t\t\t\\item Common Mode Input Range: 0.8V\n\t\t\t\\item CMRR $\\ge 75dB$\n\t\t\t\\item PSRR $\\ge 60dB |_{DC} \\ \\ 50dB$ at 1MHz\n\t\t\t\\item Power Dissipation: 1.5mW\n\t\t\\end{itemize}\n\t\n\t\t\\pagebreak \n\t\n\t\t\t\\subsubsection{Settling Time}\n\t\t\t\t$$$$\n\t\t\t\tTo meet this specification, we will design our amplifier to have a slew rate that is one tenth of the settling time. Although this is not a one to one correspondence with the specification, settling time and slew rate are closely related, and achieving the above margin is a good indication that the spec has been met.\\footnote{\\tiny C. T. Nguyen, Lecture 24, April 25, 2013}\n\n\n\t\t\t\t$$ SR = \\frac{10V_{0}}{T_{s|0.1\\%}}$$\n\t\t\t\t$$T_{s|0.1\\%} = 8ns \\ \\ with\\ \\  0.4V Step$$\n\t\t\t\t$$ SR = \\frac{10(0.4)}{8ns}$$\n\t\t\t\t$$SR = 500 \\frac{V}{\\mu S} $$\n\t\t\t\t$$SR = \\frac{I_{xm}}{C} $$\n\n\t\t\t\t\\begin{center}\\framebox{$\\frac{I_{xm}}{C_{}} \\ge 5\\times10^{8} V/s $}\\end{center}\n\t\t\t\twhere C is the largest capacitance in the circuit, and Ixm is the limiting current.\n\t\t\t\t$$$$\n\t\t\n\t\t\t\\subsubsection{Unity Gain Frequency}\n\t\t\t\t$$$$\n\t\t\t\t$$ugf= \\frac{gm_{I}}{C_{}} $$\n\t\t\t\t$$ugf = 2\\pi 600MHz$$\n\t\t\t\t\\begin{center}\\framebox{$\\frac{gm_{I}}{C_{}} \\ge 2\\pi 600 MHz $}\\end{center}\n\t\t\n\n\t\t\t\\subsubsection{Phase Margin}\n\t\t\t\t$$$$\n\t\t\t\tPhase margin, settling time, and unity gain frequency are all closely related and impact the stability of the circuit in feedback. Aiming for a target phase margin that is conducive to meeting the above two specs,\n\t\t\t\t$$PM = 65^{\\circ}$$\n\t\t\t\t$$\\omega_{p2} \\ge tan(65)\\times 2\\pi 600Mhz$$\n\t\t\t\t\\begin{center}\\framebox{$\\frac{gm_{II}}{C_{I}+C_{II}} \\ge tan(65)\\times 2\\pi 600MHz$}\\end{center}\n\t\t\t\t\\pagebreak\n\t\t\n\t\t\t\\subsubsection{Gain}\n\t\t\t\t$$$$\n\t\t\t\tTotal Gain: $A_{v} = A_{v_{1}}A_{v_{2}}$\n\n\t\t\t\t$$ A_{v_{1}} = gm_{3}\\left(\\frac{\\frac{V_{A4}}{I_{D3}}\\frac{V_{A5}}{I_{D3}}}{\\frac{V_{A4}}{I_{D3}}+\\frac{V_{A5}}{I_{D3}}}\\right) \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ A_{v_{2}} = -gm_{6}\\left(\\frac{\\frac{V_{A6}}{I_{D6}}\\frac{V_{A9}}{I_{D6}}}{\\frac{V_{A6}}{I_{D6}}+\\frac{V_{A9}}{I_{D6}}}\\right)$$\n\t\t\t\t\\newline\n\t\t\t\t$$ A_{v} = \\frac{-gm_{3}gm_{6}}{I_{D3}I_{D6}}\\left(\\frac{V_{A4}V_{A5}}{V_{A4}+V_{A5}}\\right)\\left(\\frac{V_{A6}V_{A9}}{V_{A6}+V_{A9}}\\right) \\footnote{\\tiny Paul Gray, Robert Meyer, \"Analysis and Design of Analog Integrated Circuits\" (Wiley and Sons, 2010), 423}$$\n\t\t\t\t\\newline\n\t\t\t\tUsing the relation $ \\frac{gm}{I_{D}} = \\frac{2}{r_{0}} $ gives us\n\t\t\t\t\\newline\n\t\t\t\t$$ A_{v} = \\frac{-4}{V_{ov3}V_{ov6}}\\left(\\frac{\\frac{1}{\\lambda_{n}}\\frac{1}{\\lambda_{p}}}{\\frac{1}{\\lambda_{n}}+\\frac{1}{\\lambda_{p}}}\\right)^2$$\n\t\t\t\t$$A_{v}= \\frac{32.65}{V_{ov3}V_{ov6}}$$\n\t\t\t\t\\begin{center}\\framebox{$\\frac{32.65}{V_{ov3}V_{ov6}} \\ge 1500$}\\end{center}\n\t\t\n\t\t\t\\subsubsection{Output Swing}\n\t\t\t\t$$$$\n\t\t\t\tIn order to satisfy an output swing of 1.2V we must satisfy the following:\n\t\t\t\t$$ V_{out, _{max}}  = V_{DD} - V_{ov_{9}} = 1.35 V $$\n\t\t\t\t$$ V_{out, _{min}}  =  V_{ov_{6}} = 0.15 V$$\n\t\t\t\t\\begin{center}\\framebox{$V_{ov9} \\le 0.15V$}\\end{center}\n\t\t\t\t\\begin{center}\\framebox{$V_{ov6} \\le 0.15V$}\\end{center}\n\t\t\t\t\\pagebreak\n\t\t\n\t\t\t\\subsubsection{Common Mode Rejection Ratio}\n\t\t\t\t$$$$\n\t\t\t\t\\begin{center}\n\t\t\t\tCMRR = $|\\frac{A_{dm}}{A{cm}}|$\n\t\t\t\t\\end{center}\n\t\t\n\t\t\t\tThe common mode rejection ratio is only dependent upon the first stage of the amplifier, because the second stage is a single ended input and output.\n\t\t\t\t\\newline\n\t\t\t\t\\begin{center}\n\t\t\t\tCMRR = $2gm_{3}r_{07}gm_{2}(r_{03} || r_{02})$\n\n\t\t\t\t= $\\frac{4}{V_{ov3}V_{ov2}}\\left(\\frac{\\frac{1}{\\lambda_{n}}\\frac{1}{\\lambda_{p}}}{\\frac{1}{\\lambda_{n}}+\\frac{1}{\\lambda_{p}}}\\right) \\footnote{\\tiny Paul Gray, Robert Meyer, \"Analysis and Design of Analog Integrated Circuits\" (Wiley and Sons, 2010), 427} $\n\n\t\t\t\t\\end{center}\n\t\t\t\t\\begin{center}\\framebox{$\\frac{11.43}{V_{ov3}V_{ov2}} \\ge 75dB$}\\end{center}\n\t\t\n\t\t\t\\subsubsection{Power Supply Rejection Ratio}\n\t\t\n\t\t\t\tIn calculating the PSRR, we will neglect the variations due to the positive supply, $V_{DD}$. This is because $PSRR_{+}\\rightarrow \\infty $ for low frequencies with perfect matching \\footnote{\\tiny Paul Gray, Robert Meyer, \"Analysis and Design of Analog Integrated Circuits\" (Wiley and Sons, 2010), 431}. This analysis is shown in G$\\&$M page 431.\n\n\t\t\t\tInstead, we will calculate the PSRR that emerges due to variations from the $V_{SS}$ supply, which in this case is ground.\n\t\t\t\t$$A_{-} = \\frac{v_{o}}{vss} = \\frac{r_{09}}{r_{06}+r_{09}} = \\frac{\\frac{1}{\\lambda_{p}}}{\\frac{1}{\\lambda_{n}}+\\frac{1}{\\lambda_{p}}} \\footnote{\\tiny Paul Gray, Robert Meyer, \"Analysis and Design of Analog Integrated Circuits\" (Wiley and Sons, 2010), 431}$$\n\t\t\t\t$$PSRR = \\frac{A_{dm}}{A_{-}}$$\n\t\t\t\t\\begin{center}\\framebox{$\\frac{A_{dm}}{0.5714} \\ge 60 dB$}\\end{center}\n\t\t\t\n\t\t\t\t\\pagebreak\n\t\t\n\t\t\t\\subsubsection{Common Mode Input Range}\n\t\t\n\t\t\t\tWhen $V_{IC}$ is reduced to the point where $ V_{GD_{3}} = V_{GD_{5}}  = V_{t_{3}} = V_{t_{5}}, M3 $ and $ M5 $ operate at the edge of saturation. \n\t\t\t\tThus, we define the lower end of the common mode input range to be :\n\n\t\t\t\t$$ V_{IC} \\ge V_{t_{3}} + V_{t_{2}}+V_{ov_{2}}  $$\n\t\t\t\t$$ V_{IC} \\ge V_{ov_{2}}  $$\n\n\t\t\t\tThe specification calls for a common mode input range that is $ 0.8V $ inside the output swing range. This gives us a constraint on $  V_{ov_{2}} $\n\n\t\t\t\t$$ V_{IC_{min}} = 0.125 V $$\n\t\t\t\t\\begin{center}\\framebox{$ V_{ov_{2}}  \\le 0.125V$}\\end{center}\n\n\t\t\t\tIf $ V_{IC} $ is too high, we have $M7$ falling into the triode region. Examining the drain voltage of $ M7,$\n\n\t\t\t\t$$ V_{DS_{7}} = V_{IC} - V_{GS_{3}} -V_{DD} = V_{IC} - V_{t3} - V_{ov_{3}} - V_{DD} $$\n\n\t\t\t\tTherefore, $ V_{IC} $ must satisfy the following:\n\n\t\t\t\t$$ V_{IC} < V_{DD_{}}  -\t| V_{t_{3}}| - |V_{ov_{3}}| - |V_{ov_{7}}| $$\n\t\t\t\t$$ V_{IC} < 1.5  -0.3 - |V_{ov_{3}}| - 0.15 $$\n\t\t\t\t$$ V_{IC} < 1.05 - |V_{ov_{3}}|  $$\n\t\t\t\tFrom the specification,\n\t\t\t\t$$V_{IC_{max}} = 0.925 V$$\n\t\t\t\t$$ 0.925 < 1.05 - |V_{ov_{3}}|  $$\n\t\t\t\t\\begin{center}\\framebox{$ |V_{ov_{3}}| < 0.125$}\\end{center}\n\t\n\t\t\t\t\\pagebreak\n\t\t\t\t\n\t\t\\subsection{Design Equations and Sizing}\n\t\t\tIn this section, we illustrate the design process of the amplifier. With the knowledge of the equations and constraints, we are able to make design decisions. These design decisions are based partly on intelligent speculations and in a large part on the equations and constraints. We complete the design with dimensions for each transistor and the value of the compensating capacitor, $C_{c}$.\n\t\t\t$$$$\n\t\t\tFor consistency with the load capacitance, we choose $C_{c}$ to be 2pF. This gives us the following:\n\t\t\t\\subsubsection{Slew Rate}\n\t\t\t\t$$\\frac{I_{xm}}{2pF} \\ge 500 000 000 $$\n\t\t\t\t$$I_{xm} \\ge 1mA$$\n\t\t\n\t\t\t\\subsubsection{Unity Gain Frequency}\n\t\t\t\t$$\\frac{gm_{I}}{2pF} \\ge 2\\pi 600 MHz $$\n\t\t\t\t$$gm_{I} \\ge 7.53mS$$\n\t\t\n\t\t\t\\subsubsection{Output Swing}\n\t\t\t$$V_{ov9} \\le 0.15V$$\n\t\t\t$$V_{ov6} \\le 0.15V$$\n\n\t\t\tTo have a comfortable margin, we set $V_{ov6,9} = 0.09 V$\t\n\t\t\n\t\t\t\\subsubsection{Gain}\n\t\t\t\t$$\\frac{32.65}{V_{ov3}V_{ov6}} \\ge 1500$$\n\t\t\t\tWith $V_{ov6} = 0.09$,\n\t\t\t\t$$v_{ov3} \\le 0.24 V $$\n\t\t\t\tSet $V_{ov3} = 0.1V$ to satisfy the common mode input range spec.\n\t\t\t\t$$$$\n\n\t\t\t\t\\pagebreak\n\t\t\n\t\t\t\\subsubsection{Sizing of M3, M5}\n\t\t\t\tTo reduce capacitances and minimize power and current consumption, set all channel lengths to the minimum value, $L_{min} = 130 nm$.\n\t\t\t\t$$ gm_{3} = k_{p}'W/L(V_{ov}) $$\n\t\t\t\t$$ 0.00753 = k_{p}'W/L(0.1) $$\n\t\t\t\t$$ W/L_{3,5} = 73712/130 $$\n\t\t\t\n\t\t\t\\subsubsection{Sizing of M7, M9}\n\t\t\t\t$$$$\n\t\t\t\tAs we can see from the settling time constraint, the circuit requires the maximum current we have available given the power restriction. With this in mind, we choose a reasonable value from experience and set the current through M9 to be 375 microamps and bias the output at half of the supply voltage. In addition, we match transistors 7 and 9 to ensure that the settling time specification is met, since both transistors supply current through large capacitors.\n\t\t\t\t$$0.5k_{p}'(W/L)_{}(V_{ov})^2(1+0.15(V_{SD}) = 375 \\mu A $$\n\t\t\t\t$$0.5k_{p}'(W/L)_{}(0.09)^2(1+0.15(0.75) = 375 \\mu A $$\n\t\t\t\t$$W/L_{7,9} = 81474/130$$\n\t\t\t\n\t\t\t\\subsubsection{Sizing of M1}\n\t\t\t\t$$$$\n\t\t\t\tIn order to meet the power dissipation requirement, the current through M1 must be no more than 250 microamps.\n\t\t\t\t$$0.5k_{p}'(W/L)_{}(V_{ov})^2(1+0.15(V_{ov}+V_{t}) = 250 \\mu A $$\n\t\t\t\t$$0.5k_{p}'(W/L)_{}(0.09)^2(1+0.15(0.39) = 250 \\mu A $$\n\t\t\t\t$$W/L_{1} = 57087/130$$\n\t\t\t\n\t\t\t\\subsubsection{Sizing of M6}\n\t\t\t\t$$0.5k_{n}'(W/L)_{}(V_{ov})^2(1+0.2(0.75) = 375 \\mu A $$\n\t\t\t\t$$0.5k_{n}'(W/L)_{}(0.09)^2(1+0.2(0.75) = 375 \\mu A $$\n\t\t\t\t$$ W/L_{6} = 31527/130 $$\n\t\t\t\n\t\t\t\\subsubsection{Sizing of M2, M4}\n\t\t\t\t$$$$\n\t\t\t\tFrom common mode input range,\n\t\t\t\t$$V_{ov2,4} \\le 0.15V $$\n\t\t\t\tAt equality we have,\n\t\t\t\t$$0.5k_{n}'(W/L)_{}(V_{ov})^2(1+0.2(V_{DS}) = 188 \\mu A $$\n\t\t\t\tThe drain-source voltage of M4 is the Vgs of M6. With this in mind,\n\t\t\t\t$$0.5k_{n}'(W/L)_{}(0.15)^2(1+0.2(0.39) = 188 \\mu A $$\n\t\t\t\t$$W/L_{2,4} = 6053/130 $$\n\t\t\t\n\t\t\t\\subsubsection{RHP Zero}\n\t\t\t\t$$$$\n\t\t\t\tWe want to set the resistor, $R_{z}$, to a value such that the zero introduced by the circuit is pushed out to infinity. To do this we set,\n\t\t\t\t$$ R_{z} = 1/gm_{II} $$\n\t\t\t\t$$ gm_{II} = k_{n}'W/L(V_{ov}) = 7.24 mS $$\n\t\t\t\t$$R_{z} = 138 \\Omega$$\n\t\t\t\t$$R_{z} = L/(Wk_{n}'(V_{GS}-V_{t})) $$\n\t\t\t\t$$ W/L_{r} = 2012/130 $$\n\t\t\t\n\t\t\t\\subsubsection{Frequency Response}\n\t\t\t\t$$$$\n\t\t\t\tWe would like to impart a phase margin of 60 degrees or better to offer a circuit that is stable under unity gain feedback and yields a quick settling time for sharp rising signals. To this end, we must push the second pole out past the value shown in the equations section above. In order to satisfy this, we must meet the following constraint,\n\t\t\t\t$$C_{I}+C_{II} \\le 8.96\\times 10^{-13}$$\n\t\t\t\tThe calculations involving the derivation of the capacitances is shown in a\\\\ MATLAB script below and we can see that the requirement is met. We have included the estimated areas and relevant perimeters of the drain and source of the transistors as per the project guidelines.\n\t\t\n\t\t\t\t\\pagebreak\n\t\t\t\t\\includepdf[pages={1}]{matlab_script.pdf}\n\t\t\t\t\\includepdf[pages={2}]{matlab_script.pdf}\t\n\t\t\n\t\\section{Part II: Simulation}\n\t\tWe go from the design parameters we have just derived and simulate the op-amp in hspice. We make adjustments to certain dimensions as necessary for biasing. For instance, the width of M6 had to be reduced in order to allow for saturation conditions for all transistors. Other transistors were adjusted to reduce power consumption. We make adjustments to certain dimensions as necessary for the fulfillment of specifications as well. Slight tweaking of all transistors is required in order to comply with the 65nm technology used for this design. Transistors were also sized to reduce or increase overdrive voltages. Through many iterations, the devices are sized in such a way that the project parameters are all met. Dimensions used in the simulation of the circuit are within 10 percent of the estimated values except where noted. Wherever variances lie, the hand calculated values rectify these disparities when the values in the equations used in the above calculations are substituted with values from the simulation.\\\\ \\\\\n\t\tWe have met all of the specifications called for in the design and have done so adequately. Graphs, tables and simulated values are now shown to substantiate the performance of this op-amp.\n\t\t\n\n\t\t\\begin{figure}\n\t\t\t\\subsection{Transistor and Bias Summary}\n\t\t\t\t$$$$\n\t\t\t\t\\subsubsection{Biasing and small signal parameters}\n\t\t\t\tAs we can see, all bias currents are within $10\\%$ of hand calculated values. The overdrive voltage of $M1,7,9$ were further reduced to increase efficiency.\n\t\t\t\t\n\t\t\t\t\\includegraphics[width=1.25\\textwidth]{operating_point.pdf}\n\t\t\\end{figure}\n\t\t\n\t\t\\begin{figure}\n\t\t\t\\includegraphics[width=1.3\\textwidth]{operating_point_page2.pdf}\n\t\t\t\\caption{Summary of biasing and small signal parameters simulated in hspice}\n\t\t\\end{figure}\n\t\t\\newpage\n\t\t\\begin{center}\n\t\t\t\\begin{figure}\n\t\t\t\t\\subsubsection{Transistor Dimensions}\n\t\t\t\tAll transistor sizes are within $10\\%$ of the expected values from the hand calculations with the exception of $M2,4,6$ and $MR$. $M6$ was manually resized to secure saturation conditions across all transistors. The simulation shows that this transistor is in the linear region when the size is in the range of the hand calculated value. The size of $M6$ was reduced until the transistor was saturated and the output voltage was biased at a value close to $0.75V$. A similar procedure was initially taken with $M2,4$. $MR$ was manually resized to provide a good phase margin. We are able to manually resize this device by pulling the newly simulated value of $gm_{II}$ and adjusting the width until the resistance is approximately equal to $1/gm_{II}$.The result is a circuit that matches all other expected values to within $10\\%$ or better.\n\t\t\t\t$$$$\n\t\t\t\t\n  \t\t\t\t\\begin{tabular}{ | l | l | l | p{5cm} |}\n   \t\t\t \t\t\\hline\n   \t\t\t \t\tTransistor & Width & Length &------------\\\\ \\hline\n   \t\t\t \t\tM1 & 61,100nm & 130nm & \\\\ \\hline\n    \t\t\t\t\tM2 & 2,535nm & 130nm & \\\\ \\hline\n    \t\t\t\t\tM4 & 2,535nm & 130nm & \\\\ \\hline\n\t\t\t\t\tM3 & 74,230nm & 130nm & \\\\ \\hline\n\t\t\t\t\tM5 & 74,230nm & 130nm & \\\\ \\hline\n\t\t\t\t\tM6 & 5,460nm & 130nm & \\\\ \\hline\n\t\t\t\t\tM7 & 88,400nm & 130nm & \\\\ \\hline\n\t\t\t\t\tM9 & 88,400nm & 130nm & \\\\ \\hline\n\t\t\t\t\tMR & 845nm & 130nm & \\\\ \\hline\t\t\t\t\n\t  \t\t\t  \t\\end{tabular}\n\t\t\t\\caption{Table of device dimensions.}\n\t\t\t\\end{figure}\n\t\t\t\\end{center}\n\t\t\t\\newpage\n\t\t\t\n\t\t\t\\begin{center}\n\t\t\t\\begin{figure}\n\t\t\t\t\\subsection{Performance Summary}\n  \t\t\t\t\\begin{tabular}{ | l | l | l | p{2cm} |}\n   \t\t\t \t\t\\hline\n   \t\t\t \t\tParameter & Specification & Circuit Performance & Spec Met? \\\\ \\hline\n   \t\t\t \t\tDC Gain & 1500 & 5121 & Yes\\\\ \\hline\n    \t\t\t\t\tCommon Mode Input Range & 0.8V & 1.35V & Yes\\\\ \\hline\n    \t\t\t\t\tOutput Swing & 1.2V & 1.275V & Yes\\\\ \\hline\n\t\t\t\t\tPower Dissipation & 1.5mW & 1.48mW & Yes\\\\ \\hline\n\t\t\t\t\tUnity Gain Frequency & 600 MHz & 725 MHz & Yes\\\\ \\hline\n\t\t\t\t\tSettling Time & 8ns & 7.8ns rising, 7.78ns falling & Yes\\\\ \\hline\n\t\t\t\t\tCMRR & 75dB & 83.2dB & Yes\\\\ \\hline\n\t\t\t\t\tPSRR at DC & 60dB & 92dB & Yes\\\\ \\hline\n\t\t\t\t\tPSRR at 1MHz & 50dB & 94.7dB & Yes\\\\ \\hline\n\t\t\t\t\tLmin & 130nm & 130nm & Yes\\\\ \\hline\n\t\t\t\t\tWmin & 195nm & 845nm & Yes\\\\ \\hline\n\t\t\t\t\tTemperature & 25C & 25C & Yes\\\\ \\hline\n  \t\t\t  \t\\end{tabular}\n\t\t\t\\caption{Table of simulated specifications}\n\t\t\t\\end{figure}\n\t\t\t\\end{center}\n\t\t\t\n\t\t\\newpage\n\t\t\n\t\t\n\t\t\\begin{figure}\n\t\t\t\\subsection{DC Gain, Phase Margin, and Unity Gain Frequency}\n\t\t\tThe graphs below show the simulated results of the amplifier's open loop gain, frequency response, and phase margin at unity gain.\n\t\t\t\t\\subsubsection{DC Gain}\n\t\t\t\t\\includegraphics[width=1.1\\textwidth]{diff_gain_DC.pdf}\n\t\t\t\t\\caption{The differential gain of the amplifier is $74.18dB$}\n\t\t\\end{figure}\n\t\t\n\t\t\\begin{figure}\n\t\t\t\\subsubsection{ Unity Gain Frequency}\n\t\t\t\\includegraphics[width=0.9\\textwidth]{diff_gain_UNITY.pdf}\n\t\t\t\\caption{The unity gain frequency of the amplifier is $725.98MHz$}\n\t\t\t\\subsubsection{Phase}\n\t\t\t\\includegraphics[width=0.9\\textwidth]{diff_gain_PHASE.pdf}\n\t\t\t\\caption{The phase at unity gain is $-113^{o}$. The phase margin at unity is $67^{o}$}\n\t\t\\end{figure}\n\t\t\n\t\t\\begin{figure}\n\t\t\t\\subsection{CMRR and PSRR}\n\t\t\tThe graph below shows the amplifier's common mode rejection ratio and power supply rejection ratio. By taking the ratio of the common mode gain to the differential mode gain, we compute the common mode rejection ratio. By taking the ratio of the power supply gain to the differential mode gain, we compute the power supply rejection ratio. These values can be found in figure 3 above.\\\\\n\t\t\t\\\\\n\t\t\tNote that the power supply gain from the negative source can be computed by the equation offered in section 2.1.7. With the amplifier providing a gain on the order of $74$dB at low frequencies and roughly $60$dB at $1MHz$, it is clear that $PSRR_{-} > 60dB$.\n\t\t\t\t\\subsubsection{Common mode gain}\n\t\t\t\t\\includegraphics[width=1.1\\textwidth]{cmrr_DC.pdf}\n\t\t\t\t\\caption{The common mode gain of the amplifier is $-9.03dB$}\n\t\t\\end{figure}\n\t\t\n\t\t\\begin{figure}\n\t\t\t\\subsubsection{ Power supply gain at DC}\n\t\t\t\\includegraphics[width=0.89\\textwidth]{psrr_DC.pdf}\n\t\t\t\\caption{The power supply gain at $DC$ is $-17.9dB$}\n\t\t\t\\subsubsection{Power supply gain at 1MHz}\n\t\t\t\\includegraphics[width=0.89\\textwidth]{psrr_1MHz.pdf}\n\t\t\t\\caption{The power supply gain at $1MHz$ is $-20.5dB$}\n\t\t\\end{figure}\n\t\t\n\t\t\\begin{figure}\n\t\t\t\\subsection{Common Mode Input Range}\n\t\t\tThis is defined as the range of voltages at which $dVout/dVin$ becomes $1/2$ in unity gain feedback. To show this, we put the op amp into unity gain configuration and sweep the $DC$ voltage at the input from 0 to $V_{DD}$. The graphs below show the maximum and minimum of this range. This amplifier exceeds the specification by a relatively large margin. This is partly due to tying the bulk to $V_{DD}$ in $M3,5$. This was done because the body effect on the input transistors can be used to increase the range\\footnote{\\tiny Paul Gray, Robert Meyer, \"Analysis and Design of Analog Integrated Circuits\" (Wiley and Sons, 2010), 428}. The total common mode input range of the amplifier is listed in figure 3.\n\t\t\t\t\\subsubsection{Common Mode Input Range, minimum}\n\t\t\t\t\\includegraphics[width=0.6\\textwidth]{common_mode_input_range_1.pdf}\n\t\t\t\t\\caption{The minimum value corresponds to an output voltage of $0.115V$}\n\t\t\t\t\\subsubsection{Common Mode Input Range, maximum}\n\t\t\t\t\\includegraphics[width=0.6\\textwidth]{common_mode_input_range_2.pdf}\n\t\t\t\t\\caption{The maximum value corresponds to an output voltage of $1.47V$}\n\n\t\t\\end{figure}\n\t\t\n\t\t\\begin{figure}\n\t\t\t\\subsection{Output Swing}\n\t\t\tThis is defined as the range of voltages at which $dVout/dVin$ becomes $1/10th$ the nominal differential gain. To show this, we sweep the $DC$ voltage at one of the inputs around its bias points and find the points on the curve where the derivative is approximately equal to $1/10th$ of the nominal gain. The graphs below show the minimum and maximum of this range. The total output swing of the amplifier is listed in figure 3.\n\t\t\t\t\\subsubsection{Output Swing, minimum}\n\t\t\t\t\\includegraphics[width=0.65\\textwidth]{output_swing.pdf}\n\t\t\t\t\\caption{The minimum value corresponds to an output voltage of $0.168V$}\n\t\t\t\t\\subsubsection{Output Swing, maximum}\n\t\t\t\t\\includegraphics[width=0.65\\textwidth]{output_swing_2.pdf}\n\t\t\t\t\\caption{The maximum value corresponds to an output voltage of $1.44V$}\n\n\t\t\\end{figure}\n\t\t\n\t\t\\begin{figure}\n\t\t\t\\subsection{Settling Time}\n\t\t\tThis is the most stringent specification to meet, as it requires relatively large amounts of current to be supplied from the current sources. We measure settling time by putting the op amp into unity gain feedback and applying a $0.4V$ step to the input. We then run a transient analysis in hspice to determine the time it takes for the amplifier's output to converge to within $0.1\\%$. The time it takes to converge must be under $8$ns.\\\\ \\\\\n\t\t\tIn order to meet this specification, some changes to device dimensions were made in order to increase the current to a value high enough to just meet the spec. Increasing the sizes of the current sources allowed for a better settling time; the drawback however, is that power consumption became excessive. To ameliorate this, the size of the biasing transistor was reduced and the bias resistor increased in order to preserve roughly the same overdrive voltage. The result is an amplifier that has a settling time of just under $8$ns and consumes less than $1.5$mW of power.\n\t\t\t\t\\subsubsection{Settling Time}\n\t\t\t\t\\includegraphics[width=1.1\\textwidth]{settling_time_zoomed_out.pdf}\n\t\t\t\t\\caption{$0.4V$ step input and amplifier response}\n\t\t\\end{figure}\n\t\t\n\t\t\\begin{figure}\n\t\t\t\t\\subsubsection{Settling Time, rising input}\n\t\t\t\t\\includegraphics[width=0.8\\textwidth]{settling_time_t1.pdf}\n\t\t\t\t\\caption{The time it takes to converge on a rising input is $7.88ns$}\n\t\t\\end{figure}\n\t\t\n\t\t\\begin{figure}\n\t\t\t\t\\subsubsection{Settling Time, falling input}\n\t\t\t\t\\includegraphics[width=0.8\\textwidth]{settling_time_t2.pdf}\n\t\t\t\t\\caption{The time it takes to converge on a falling input is $7.78ns$}\n\t\t\\end{figure}\n\t\t\\pagebreak\n\t\t...\n\t\t\\newpage\n\t\t\\section{Conclusion}\n\t\t\tWe have shown the design process of an analog integrated circuit CMOS operational amplifier, and we have shown how equations we have derived throughout the semester participate in this process. We have seen how tradeoffs must be made between certain parameters in order to provide an amplifier that is balanced and meets a wide range of specifications. For the most part, the amplifier considered in this paper is ideal for use in digital circuits or mixed signal circuits where the characteristics of the stages connected to the op-amp are known in advance. This amplifier provides a good gain for digital signals (digital signals typically do not require as much gain as their analog counterparts), a wide bandwidth, stellar phase margin for gains down to and below unity, a very quick settling time, and consumes very little power. Furthermore, the amplifier has a very good power supply rejection ratio which offers outstanding performance in digital circuits with high levels of switching noise. Overall, the amplifier we have designed is a stable, low power op-amp that is the quintessential CMOS operational amplifier utilized by engineers throughout the world.\n\t\t\t$$$$\n\t\t\tThe design of this op amp was a scrupulous and testing process, and a tremendous learning experience as well. To see how all of the many variables depended on each other required me to think in a way that I have never before and forced me to stretch and expand my mind to such great heights. Arguably, a better way to design a circuit like this is to write a geometric program and have a computer automatically compute a robust design given the parameters and specifications. This implies that the circuit designer can spend more time doing real design, $i.e.,$ carefully analyzing the optimal trade-offs between competing objectives and less time doing parameter tuning or wondering whether a certain set of specifications can be achieved. However, for the purposes of this course and the learning experience required to become a competent circuit designer, it is necessary to do this type of analysis by hand and think about the circuit ourselves, rather than have a computer do the thinking for us. At the end of the day, I can say that I have a solid grasp and comprehension of the way a relatively large MOS circuit like this operates. I realize the interdependencies between variables like dimension, transconductance, and overdrive voltage, and I acknowledge the tradeoffs required to satisfactorily meet an extensive range of specifications. Overall, the wisdom and erudition bestowed upon me as a result of successfully completing this project is immense, and it was undeniably worth the effort.\n\t\t\n\t\n\t\n\\end{document}", "meta": {"hexsha": "2e11fca34f605aec990c3d16be5685c1a0450851", "size": 25974, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "CMOSAmplifier/hand_analysis.tex", "max_stars_repo_name": "jasonaibrahim/AcademicWorks", "max_stars_repo_head_hexsha": "4c3e75f48bdafa02fabb551beb6ebf2fea871238", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CMOSAmplifier/hand_analysis.tex", "max_issues_repo_name": "jasonaibrahim/AcademicWorks", "max_issues_repo_head_hexsha": "4c3e75f48bdafa02fabb551beb6ebf2fea871238", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CMOSAmplifier/hand_analysis.tex", "max_forks_repo_name": "jasonaibrahim/AcademicWorks", "max_forks_repo_head_hexsha": "4c3e75f48bdafa02fabb551beb6ebf2fea871238", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 62.5879518072, "max_line_length": 1507, "alphanum_fraction": 0.7018942019, "num_tokens": 7995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.3095758281490929}}
{"text": "\\section{ODE solvers} \n\nODE solvers implement animation algorithms applied at each time step to integrate time and compute positions and velocities one time step forward in time.\n% Each step of the algorithm is implemented using a visitor to traverse the scenegraph starting from the node the solver is attached to.\nThe solvers do not directly address the physical models. \nThey apply abstract mechanical operations to state vectors represented by IDs, as illustrated in the algorithm shown in Figure~\\ref{fig:eulerexplicit}.\n\\begin{figure}\n\\begin{center}\n\\begin{algorithmic}\n\\STATE void  \\textbf{ExplicitEulerSolver::solve(VecId x, VecId v, double dt)}\n\\STATE create auxiliary vectors a,f\n\\STATE resetForce(f)\n\\STATE accumulateForce(f,x,v)\n\\STATE computeAcceleration(a,f)\n\\STATE project(a,a)\n\\STATE v += a * dt\n\\STATE x += v * dt\n\\end{algorithmic}\n\\caption{Euler's explicit time integration.}\n\\label{fig:eulerexplicit}\n\\end{center}\n\\end{figure}\nEach mechanical operation, such as allocating a state vector or accumulating the forces, is implemented using a specialized visitor parameterized on vector IDs or control values such as dt.\nThis allows to implement the solvers completely independenly of the physical model.\nEach vector used by a solver ID is actually scattered over all the state vector containers in the different nodes in the scope of the solver.\nSome vector operations such as the dot product apply only to the independent DOFs, stored in the state vectors not attached to a parent by a mapping.\nNotice that this design avoids the assembly of global state vectors (i.e. copying Vec3 and quaternions to and from  vectors of scalars).\nMoreover, the virtual function calls are resolved at the granularity of the state vectors (i.e. all the particles together, and all the moving frames together) rather than each primitive (i.e. each particle and each frame independently), and allow to optimize each implementation independently.\nThere is thus virtually no loss of efficiency when mixing arbitrary types in the same simulation.\n\n\n\n\n% The ODE solver creates visitors and applies them to its parent node.\n% The ComputeDf visitor presented in Figure~\\ref{fig:DfVisitor} finds no mapping nor DOF at the root level (functions are called only if the corresponding component is present in the node), and continues the traversal in the two child branches. \n% Each object computes its own force change df corresponding to its own displacement dx, as previously explained.\n% The objects are independent because there is no mapping to a commom DOF component at the scene level.\n% Each object manages its own state vectors.\n% Thus, using visitors allows the solver to transparently handle an arbitrary number of objects of arbitrary types in the same scene. \n% One can use visitors without knowing to which objects they apply.\n% This is a key feature of the SOFA design, which allows us design the algorithms once and to apply them to all types of simulated objects.\n% Notice that this design avoids the assembly of global state vectors (i.e. copying Vec3 and quaternions to and from  vectors of scalars).\n% Moreover, the virtual function calls are resolved at the granularity of the state vectors (i.e. all the particles together, and all the moving frames together) rather than each primitive (i.e. each particle and each frame independently), and allow to optimize each implementation independently.\n% There is thus virtually no loss of efficiency when mixing arbitrary types in the same simulation.\n% Hence the ``versatile yet efficient'' motto of SOFA.\n\n\nWe have identified two families of ODE solvers.\nThe first contains the explicit solvers, which compute the derivative at the beginning of the time step. They are variants of the Euler explicit solver presented in Figure~\\ref{fig:eulerexplicit}, and are easily implemented in Sofa using the same operators.\nThe second family contains the implicit solvers, which consider the derivative at the end or somewhere in the middle of the time step. They typically require the solution of equation systems such as:\n\\begin{equation}\n\\label{eq:linear-system}\n\\underbrace{\\left(\\alpha \\M  + \\beta \\B  + \\gamma \\K \\right)}_{\\mathbf{A}}   \\Vdv =  \\vec b\n%\\underbrace{\\P \\left(\\alpha \\M  + \\beta \\B  + \\gamma \\K \\right)}_{\\mathbf{A}}   \\Vdv =  \\vec b\n\\end{equation}\nwhere $\\M$ is the mass matrix, $\\K = \\frac{\\partial \\Vf}{\\partial \\Vx}$ and $\\B = \\frac{\\partial \\Vf}{\\partial \\Vv}$ respectively are the \\textit{stiffness} and \\textit{damping} matrices (the method is explicit if $\\beta$ and $\\gamma$ are null). In order to apply simple displacement constraints,  a projection matrix $\\P$ can be used, and the system becomes $\\P^T \\mathbf{A} \\P \\Vdv =\\P^T \\vec b $~\\cite{baraff98large}.\nImplicit integration has the advantage of being more stable for stiff forces or large time steps. However, solving these equation systems requires linear solvers, discussed in the next section.\nCurrently, eight ODE solvers have been implemented, including symplectic Euler and explicit Runge-Kutta4, implicit Euler and statics solution.\n\n\n\n\\section{Linear solvers} \n\\subsection{Conjugate Gradient} An interesting feature of visitor-based mechanical computations is their ability to efficiently and transparently compute matrix products.\nThus, we have proposed in SOFA an implementation of the Conjugate Gradient, based on the graph traversal. \nThe visitor shown in Figure~\\ref{fig:DfVisitor} computes the force change \\textit{df} based on a given displacement \\textit{dx}, as repeatedly performed in Conjugate Gradient algorithm. \nAn arbitrary number of forces and projections may be present in all the nodes, resulting in a complicated stiffness matrix, as shown in the following equation:\n\\begin{equation}\n \\label{eq:dfdx}\n\\vec{df} = \\sum_i  \\left( \\prod_{j \\in path(i)} \\mat J_j  \\right)^T \\K_i \\left( \\prod_{j \\in path(i)} \\mat J_j  \\right) \\vec{dx}\n\\end{equation}\nwhere $\\K_i$ is the stiffness matrix of force $i$, matrix $\\J$ encodes the first-order mapping relation of a node with respect to its parent, and $path(i)$ is the list of nodes from the solver to the node the force applies to.\n\\begin{figure}\n\\begin{center}\n\\begin{tabular}{c|c}\n\\begin{minipage}[t]{0.52\\linewidth}\n\\begin{algorithmic}\n\\STATE bool \\textbf{ComputeDfVisitor::topDown}():\n\\STATE dof.resetF(this.df)\n\\IF{mapping}\n\\STATE mapping.applyJ(this.dx)\n\\ENDIF\n% \\FORALL {projection P}\n% \\STATE P.project( this.dx,this.dx )\n% \\ENDFOR\n\\RETURN true\n\\end{algorithmic}\n\\end{minipage}\n&\n%  \\hspace{0.01\\linewidth}\n% &\n%  \\hspace{0.01\\linewidth}\n% &\n \\begin{minipage}[t]{0.46\\linewidth}\n\\begin{algorithmic}\n\\STATE void \\textbf{ComputeDfVisitor::bottomUp}():\n\\FORALL {forceField F}\n\\STATE F.addDF( this.df,this.dx )\n\\ENDFOR\n% \\FORALL {projection P}\n% \\STATE P.project( this.df,this.df )\n% \\ENDFOR\n\\STATE mapping.applyJT(this.df)\n\\end{algorithmic}\n \\end{minipage}\n\\end{tabular}\n\\caption{Computing $df$ given $dx$ using a visitor.}\n\\label{fig:DfVisitor}\n\\end{center}\n\\end{figure}\nThis complex product is computed using only matrix-vector products and with optimal factoring thanks to the recursive implementation.\nIt allows us to efficiently apply implicit time integration to arbitrary scenes using the Conjugate Gradient. \nThis method allows us to trade-off accuracy for speed by limiting the number of steps of the iterative solution.\n\n\n\\subsection{Direct Solvers} Direct solvers are also available in SOFA. They can be used as preconditionners of the conjugate gradient algorithm~\\cite{CADC10} or for directly solving equation \\ref{eq:linear-system}.\nTheir implementation are based on external libraries such as Eigen, MKL and Taucs. \nWhen dealing with Finite Element Models, the matrices are generally very sparse and \nefficient implementations based on sparse factorizations allow for fast computations. \nMoreover, when dealing with specific topologies, like wire-like structures, tri-diagonal band solvers can be used for extremely fast results in $\\mathcal{O}(n)$\nThese different linear solvers address matrices which  can be stored in different formats, adapted to the numerical library.\n%or even not explicitly stored when only matrix-vector products are applied.\nThe type of matrix is a parameter of the linear solver, and of the visitors the solver uses. \nTen linear solvers have been implemented in \\sofa{}. They can be interchanged to compare their efficiency.\n\n\\subsection{From ODE solver to linear solver}\n\nIn SOFA, all states of a mechanical object is described by its degree of freedom. The main works for the simulation are filling and inverting a matrix system in order to find the states of mechanical objects by steps of time. This system matrix can be described as below :\n \\[\n\\left[ \\textbf{MBK} \\right].a=f \\text{    ,  or at time n+1 :   }\\left[ \\textbf{MBK} \\right].a_{n+1}=f_{n+1}\n\\]\nwhere,\n\\[\n\\left\\{ \n\\begin{array}{l}\n\\textbf{M} \\text { : the mass matrix   }  \\\\\n\\textbf{B} \\text { : the damping matrix   }  \\\\\n\\textbf{K} \\text { : the stiffness matrix   }  \\\\\n\\left[ \\textbf{MBK} \\right] \\text {  : is a linear combination of MBK (not multiplication)   }  \\\\\na_{n+1} \\text { : accelerator field} \\\\\nf_{n+1} \\text { : force field} \n\\end{array}\\right.\n\\]\n Usually, \\textbf{M} is filled by \\textbf{mass} components, \\textbf{K} is filled by \\textbf{forcefield} or \\textbf{interactionforcefield} components, \\textbf{B} (often $\\alpha\\textbf{M}+\\beta\\textbf{K}$ ) and $\\left[ \\textbf{MBK} \\right]$ are computed by \\textbf{odesolver} components. The works left to invert the matrix system are done by \\textbf{linearsolver} components.\n\\begin{center}\n\\includegraphics[scale=0.3]{matrix_bloc.pdf}\n\\end{center}\nOn the case for example when there are two mechanical objects, we can see a global stiffness matrix describing the two mechanical states, composed diagonal blocs and non-diagonal blocs. The diagonal blocs are filled by \\textbf{mass},\\textbf{forcefield} components, and the non-diagonal ones are filled by \\textbf{interactionforcefield} if existed.\n\\paragraph{Mapping matrix contribution : } When existe a mapping on the simulation scene, the states of two mechanical objects are relied by : \n\\[\n\\begin{array}{rl}\n\\textbf{x}_{2} & = \\Im\\left(\\textbf{x}_{1}\\right)           \\text{      ,\tmapping::apply}             \\\\\n\\textbf{v}_{2} & = \\left[\\textbf{J}\\right] \\textbf{v}_{1}   \\text{      ,\tmapping::applyJ}  \n\\end{array}\n\\]\nThe $\\left[\\textbf{J}\\right]$ matrix is derivative of $\\Im$ operator and is defined by the \\textbf{mapping} components. The dynamic and matrix system of the two objects are relied by :   \n\\[\n\\begin{array}{rl}\n\\textbf{f}                  & += \\textbf{f}_{1}  +   \\left[\\textbf{J}\\right]^{t} \\textbf{f}_{2}         \\text{      ,\tmapping::applyJT}             \\\\\n\\left[ \\textbf{MBK} \\right] & += \\left[ \\textbf{MBK} \\right]_{1}  + \\left[\\textbf{J}\\right]^{t}  \\left[ \\textbf{MBK} \\right]_{2} \\left[\\textbf{J}\\right]\n\\end{array}\n\\]\nThe resolution of the system with the mapping is done in general :\n\\[\n\\left\\{ \n\\begin{array}{rl}\n\\textbf{a}^{n+1}        & = \\left[ \\textbf{MBK} \\right]^{-1}  \\textbf{f}^{n+1}    \\\\\n\\textbf{v}^{n+1}_{1}    & = \\textbf{v}^{n}_{1}     + dt.\\textbf{a}^{n+1}         \\\\\n\\textbf{x}^{n+1}_{1}    & = \\textbf{x}^{n}_{1}     + dt.\\textbf{v}^{n+1}         \\\\\n\\textbf{x}^{n+1}_{2}    &  \\text{ ,\tmapping::apply }     \\\\\n\\textbf{v}^{n+1}_{2}    &  \\text{ ,\tmapping::applyJ }          \n\\end{array}\n\\right.\n\\]\n\n\n\n\\subsection{Particular implementation in SOFA}\nThe direct solver demands to build explicitly the matrix, and invert this matrix after every step of time in order to solve the mechanical response after a solicitation. In SOFA, there are a little more complicated component called mapping, relying geometrical and mechanical properties by master-slave (DOF-mapped object) relation. All changes of geometry or solicitation to one object interfere to other and vice versa. If the mapped object have its own mechanical behavior, it must be counted on the mechanical propagation by the mapping.\n\\subsubsection{self-stiffness propagation }\n\\[\n\\begin{array}{cc}\n\\includegraphics[scale=0.3]{stiffness_propagation_matrix.pdf}        \n& \n\\includegraphics[scale=0.35]{stiffness_propagation.pdf} \n\\end{array}\n\\]\nIn the simple simulation scene, \\textbf{MS2} is a mapped object to the \\textbf{MS1} mechanical object by the mapping. The matrix to be inverted for all mechanical response is the filled colorized one ($K_{11}$), the matrix $K_{22}$ describing mechanical properties of the second objects must contribute to $K_{11}$ by the formula :\n\\[\n\\left\\{ \n\\begin{array}{ll}\nK_{11}       & += J^t * K_{22} * J               \\\\\n\\text{or,}   &         \\\\\nK_{tempo}    & =  J^t * K_{22}                   \\\\\nK_{11}       & += K_{tempo} * J                  \\\\         \n\\end{array}\n\\right.\n\\]\nBy doing this computation, we propagate the stiffness of the mapped mechanical object to its root mechanical object.\n\\subsubsection{interaction-stiffness propagation }\nIn the general case, the may have a simulation scene where there are many level of mapped mechanical states (mapped of mapped state ...) and many interaction forcefield interacting between them. Therefor the stiffness of interaction forcefield and the mapped mechanical state need to be propagated through the mappings. We can imagine for one propagation, there are two simple cases.\n\\paragraph{Interaction beweent Real Mechanical Object and Mapped Mechanical Object}\n\\[\n\\begin{array}{cc}\n\\includegraphics[scale=0.3]{interaction_Real_Mapped_Matrix}        \n& \n\\includegraphics[scale=0.35]{interaction_Real_Mapped} \n\\end{array}\n\\]\nIn the case where one of the two mechanical states in interaction is non-mapped, the propagation can be computed directly by the formula :\n\\[\n\\left\\{ \n\\begin{array}{ll}\nK_{11}       & += J^t * K_{33} * J               \\\\\n\\text{or,}   &                                   \\\\\nK_{tempo}    & =  J^t * K_{33}                   \\\\\nK_{11}       & += K_{tempo} * J                  \\\\ \n\\text{and,}&                 \\\\      \nI_{12}       & += J^t * I_{32}                   \\\\ \nI_{21}       & += I_{23} * J                        \n\\end{array}\n\\right.\n\\]\n\\paragraph{Interaction beweent Mapped Mechanical Object and Mapped Mechanical Object}\n\\begin{center}\n  \\includegraphics[scale=0.3]{interaction_Mapped_Mapped}\n\\end{center}\nIn the case where the two mechanical states in interaction are mapped, the propagation can be computed by two steps. The first consist to propagate the interaction $I_{34}$ to the interation $I_{14}$ :\n\\[\n\\left\\{ \n\\begin{array}{ll}\nK_{11}       & += J^t * K_{33} * J               \\\\\n\\text{or,}   &                                   \\\\\nK_{tempo}    & =  J^t * K_{33}                   \\\\\nK_{11}       & += K_{tempo} * J                  \\\\ \n\\text{and,}&                 \\\\      \nI_{14}       & += J^t_A * I_{34}                  \\\\ \nI_{41}       & += I_{43} * J_A                        \n\\end{array}\n\\right.\n\\]\nThe following step can compute as the one of above paragraph, propagating the interation $I_{14}$ to $I_{12}$.\n\n\n%In summary, ODE solution is performed using a hierarchy of algorithms and data structures with each level implemented in a different component: the main ODE solution algorithm , the auxiliary linear solver  parameterized by the type of matrix, and an optional preconditioner when the Conjugate Gradient linear solver is used.\n%Using a direct solver requires the explicit computation and storage of the system matrix \\mat A of Equation~\\ref{eq:linear-system}.\n%The mass and stiffness matrices are written by the components and summed at each node level. They are then multiplied by the projection and mapping matrices during visitor traversals, and stored in the solver.\n\n\\section{Constraint solvers} \n\\label{lm}\nTo handle different kinds of interactions (contact, friction, joints between particles..) between the simulated objects, SOFA allows the use of Lagrange multipliers~\\cite{DDKA06}. \n%see \\textit{e.g.}\\cite{Duriez_eurographics2008}.\n%The third family of solvers involves non-trivial constraints requiring additional equations, and additional unknowns called \nThey may be combined with explicit or implicit integration.\nEach constraint depends on the relative position of the interacting objects, and on optional parameters \n(such as a friction coefficient, etc.)\\footnote{For simplicity, we present the equations for two interacting objects \n(rigid or deformable) $1$ and $2$, but the solution applies to arbitrary number of interacting bodies.}:\n\\begin{equation}\n\\begin{array}{c}\n\\Phi(\\Vx_1, \\Vx_2, ...) = 0 \\\\ \n\\Psi(\\Vx_1, \\Vx_2, ... ) \\geq 0\n\\end{array}\n\\label{eq:constraints}\n\\end{equation} where $\\Phi$ represents the bilateral interaction laws (attachments, sliding joints, etc.) whereas $\\Psi$ represents unilateral interaction laws (contact, friction, etc.). These functions can be non-linear.\n% The solution uses Lagrange multipliers and a single linearization by time step (see~\\cite{DDKA06}). \nThe Lagrange multipliers are computed at each simulation step.\n%However, for interaction including deformations, there is often a temporal coherency on the multipliers values. \n%Thus, we can provide an estimate $\\tilde{\\lambda}$ at the beginning of each time step and compute a correction $\\Delta \\lambda$ so that $\\lambda = \\tilde{\\lambda} +\\Delta \\lambda$.  \nThey add force terms to Equation (\\ref{eq:linear-system}):\n\\begin{equation}\n\\begin{array}{c}\n\\mathbf{A}_1  \\Vdv_1 = \\mathbf{b}_1 + \\mathbf{H}_1^T \\lambda\\\\\n\\mathbf{A}_2  \\Vdv_2 = \\mathbf{b}_2 + \\mathbf{H}_2^T \\lambda\n\\label{eq:constraint-systeme}\n\\end{array}\n\\end{equation}\nwhere \n\\begin{equation}\n\\mathbf{H}_1 = [\\frac{\\delta \\Phi}{\\delta \\Vx_1} \\  ; \\  \\frac{\\delta \\Psi}{\\delta \\Vx_1}  ]\\qquad  \\mathbf{H}_2 = [\\frac{\\delta \\Phi}{\\delta \\Vx_2} \\  ; \\  \\frac{\\delta \\Psi}{\\delta \\Vx_2}  ].\n\\end{equation}\nMatrices $\\mathbf{H}_1$ and $\\mathbf{H}_2$ are stored in the mechanical state component of each node. Thus, when the constraint applies to a model that is mapped (see section \\ref{sec:mappings}), the constraints are recursively mapped upward like forces to be applied to the independent degrees of freedom~\\cite{Duriez_eurographics2008}. \n% An example that illustrates this concept can be found in \\cite{Duriez_eurographics2008}. \nSolving the constraints is done by following these steps:\n\n\n\\textbf{Step 1, Free Motion}: interacting objects are solved independently while setting $ \\lambda  = 0$. \nWe obtain what we call a \\textit{free motion} $\\Vdv_1^{\\mathrm{f}}$  and  $\\Vdv_2^{\\mathrm{f}}$ for each object. After integration, we obtain $\\Vx_{1}^{\\mathrm{f}}$ and $\\Vx_{2}^{\\mathrm{f}}$. \n%For the prediction, use $\\tilde{\\lambda} = \\lambda^{t}$. \nDuring this step, each object solves equation~(\\ref{eq:constraint-systeme}) with $ \\lambda  = 0$ independently using a dedicated solver.  \n\n\\vspace{2mm}\n\n\\textbf{Step 2, Constraint Solving}: \n%the constraint laws are linearized as follows:\n%\\begin{equation}\n%\\label{eq:const-lin}\n%\\underbrace{\n%\\left[ \\! \\! \\!\n%\\begin{array}{c}\n%\\Phi(\\Vx_{1}^{t+h}, \\Vx_{2}^{t+h})  \\\\\n%\\Psi(\\Vx_{1}^{t+h}, \\Vx_{2}^{t+h}) \n%\\end{array} \\! \\! \\!\n%\\right]}_{\\boldsymbol{\\delta}^{t+h}}  \\! \n%=  \\! \n%\\underbrace{\n%\\left[ \\! \\! \\!\n%\\begin{array}{c}\n%\\Phi(\\Vx_{1}^{\\mathrm{f}}, \\Vx_{2}^{\\mathrm{f}})  \\\\\n%\\Psi(\\Vx_{1}^{\\mathrm{f}}, \\Vx_{2}^{\\mathrm{f}}) \n%\\end{array}\\! \\! \\!\n%\\right]}_{\\boldsymbol{\\delta}^{\\mathrm{f}}}\n% + h\\mathbf{H}_1\\Vdv_1^{\\mathrm{c}}  +  h\\mathbf{H}_2\\Vdv_2^{\\mathrm{c}}\n%\\end{equation}\n%With $\\Vdv_1^{\\mathrm{c}}$ and $\\Vdv_2^{\\mathrm{c}}$ being the unknown corrective motion ($\\Vdv= \\Vdv^{\\mathrm{f}} + \\Vdv^{\\mathrm{c}}$) when solving equation \\ref{eq:constraint-systeme} with $\\mathbf{b}_1 = \\mathbf{b}_2 = 0$. By gathering equations \\ref{eq:constraint-systeme} and \\ref{eq:const-lin}, we have:\nThe constrained equations can be linearized and linked to the dynamics (see \\cite{CJADLC10} for details). \n\\begin{equation}\n\\left[\n\\begin{array}{c}\n\\Phi(\\Vx_{1}, \\Vx_{2})  \\\\\n\\Psi(\\Vx_{1}, \\Vx_{2}) \n\\end{array} \\! \\! \\!\n\\right]\n =\n % \\underbrace{\n\\left[ \\! \\! \\!\n\\begin{array}{c}\n\\Phi(\\Vx_{1}^{\\mathrm{f}}, \\Vx_{2}^{\\mathrm{f}})  \\\\\n\\Psi(\\Vx_{1}^{\\mathrm{f}}, \\Vx_{2}^{\\mathrm{f}}) \n\\end{array}\\! \\! \\!\n\\right]\n%}_{ \\delta^{\\mathrm{f}}  }\n + \n \\underbrace{\n h\\mathbf{H}_1\\Vdv_1^{\\mathrm{c}}  +  h\\mathbf{H}_2\\Vdv_2^{\\mathrm{c}}\n }_{h \\left[  \\mathbf{H}_1 \\mathbf{A}_1^{-1}  \\mathbf{H}_1^T + \\mathbf{H}_2 \\mathbf{A}_2^{-1}  \\mathbf{H}_2^T \\right]\\lambda\n }\n %=\n %\\delta^{\\mathrm{f}} +\n%\\underbrace{h \\left[  \\mathbf{H}_1 \\mathbf{A}_1^{-1}  \\mathbf{H}_1^T + \\mathbf{H}_2 \\mathbf{A}_2^{-1}  \\mathbf{H}_2^T \\right]}_{\\mathbf{W}} \\lambda\n\\label{eq:addjminvjt}\n\\end{equation}\nWith $\\Vdv^{\\mathrm{c}} = \\Vdv - \\Vdv^{\\mathrm{f}}$. \nTogether with equation (\\ref{eq:constraints}), these equations compose a Mixed Complementarity Problem that can be solved by a variety of solvers.\nWe compute the value of $ \\lambda$ using a projected Gauss-Seidel algorithm that iteratively checks and projects the various constraint laws contained in $\\Phi$ and  $\\Psi$ ~\\cite{DGMCG09}. \n\n\\textbf{Step 3, Corrective Motion}: when the value of $\\lambda$ is available, the corrective motion is computed as follows:\n%\n\\begin{equation}\n\\label{eq:corrective-motion}\n\\begin{array}{c}\n\\Vx_{1}^{t+h} =  \\Vx_{1}^{\\mathrm{f}} + h \\Vdv_1^{\\mathrm{c}} \\  \\  \\mathrm{ with } \\  \\  \\Vdv_1^{\\mathrm{c}} = \\mathbf{A}_1^{-1}  \\mathbf{H}_1^T \\lambda \\\\\n\\Vx_{2}^{t+h} =  \\Vx_{2}^{\\mathrm{f}} + h \\Vdv_2^{\\mathrm{c}} \\  \\  \\mathrm{ with } \\  \\  \\Vdv_2^{\\mathrm{c}} = \\mathbf{A}_2^{-1}  \\mathbf{H}_2^T \\lambda\n\\end{array}\n\\end{equation}\n%\n\nA Master Solver, which is generally placed at the top of the graph of SOFA has the role of imposing this new scheduling to the rest of the graph. \n%\n\\begin{figure}[!htb]\n\\centering\n% FreeMotionScheme is missing from SVN\n\\includegraphics[width= 0.9\\columnwidth]{ConstraintSolver.png}\n\\caption{Contact process using constraints: A unilateral constraint is placed at the level of the contact points. The constraint direction is mapped to the degrees of freedom of the objects to obtain matrix $ \\mathbf{H}^T$. The \\textit{ConstraintCorrections} components compute the compliance to obtain equation \\ref{eq:addjminvjt}. The Constraint solver found a new value of $\\lambda$ which is sent to the  \\textit{ConstraintCorrections} to compute an adequate corrective motion. The Master Solver is placed at the root of the simulation graph to impose the steps of the simulation process.  }\n\\label{shema_ToH}\n\\end{figure}\n\n\\textbf{Compliance computation} : Equations~\\ref{eq:addjminvjt} and~\\ref{eq:corrective-motion} involve the inverse of matrix $\\mathbf{A}$ (called compliance matrix), which changes at every time step namely in case of a non-linear model. \nDepending on the simulation case, computing this inverse could be time consuming for real-time simulation. \nWhen this is too time-consuming, we propose several strategies to improve the speed of the algorithm such as using the diagonal of $\\mathbf{A}$ instead of the hole matrix, or a precomputed inverse~\\cite{Saupin08}, or an asynchronous factorization on the GPU~\\cite{CourtecuisseMICCAI11}.  \nThese strategies are implemented in a category of components, called  \\textit{ConstraintCorrections} that provide different ways of computing $\\Vdv^{\\mathrm{c}}$ given a value of $\\lambda$. Given a simulation, it is very easy to make tests and chose the better solution.\n\n\n\n\n", "meta": {"hexsha": "6a4a7d2a1c8bf74decb9d2ecc3a303c288ae3387", "size": 23343, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/solvers/solvers.tex", "max_stars_repo_name": "sofa-framework/issofa", "max_stars_repo_head_hexsha": "94855f488465bc3ed41223cbde987581dfca5389", "max_stars_repo_licenses": ["OML"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/solvers/solvers.tex", "max_issues_repo_name": "sofa-framework/issofa", "max_issues_repo_head_hexsha": "94855f488465bc3ed41223cbde987581dfca5389", "max_issues_repo_licenses": ["OML"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/solvers/solvers.tex", "max_forks_repo_name": "sofa-framework/issofa", "max_forks_repo_head_hexsha": "94855f488465bc3ed41223cbde987581dfca5389", "max_forks_repo_licenses": ["OML"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 62.4144385027, "max_line_length": 594, "alphanum_fraction": 0.7181596196, "num_tokens": 6530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.30955791734402915}}
{"text": "%\\chapter{Bose--Einstein condensate dynamics}\nThe purpose of this chapter is to introduce the reader to vortex states of BECs, and eventually discuss manipulations of these states. In the following sections we will examine both the static and the dynamical solutions of the Gross--Pitaevskii equation (GPE), using the methods previously discussed. We will first briefly discuss few vortex solutions, with an analysis of their properties via an examination of the velocity field.\n\nWe will follow this by providing the details of the model system of a vortex lattice in a rapidly rotating BEC, using the theoretical framework developed in Chapter~\\ref{chp:background}. Next, we will discuss the application of two distinct ways for manipulating and controlling the condensate: (1) applying an external potential to the trapped condensate for a short timescale, and (2) direct manipulation of the wavefunction phase. Both of these are experimentally realistic, and though they can be experimentally implemented by similar means, they serve two very different purposes, and they will be treated as such.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Simulating Bose--Einstein condensate dynamics}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nIn Sections~\\ref{sub:gpederiv}~and~\\ref{sec:fso} we have outlined both the analytical Thomas--Fermi (TF) and numerical solutions of the GPE. It is instructive to compare the results from these two methods. For a stationary condensate in the ground state of a harmonic trapping potential the profile and width should be comparable, with the TF solution deviating only in the low-density regions. Fig.~\\ref{fig:gpe_tf_3} shows a comparison of the two-dimensional profile for both methods, for condensates of $^{87}$Rb with $N=10^{5}$ atoms, and trapping frequencies of $\\omega_{\\mathbf{r}}=2\\pi\\times (1, 1, 16 )$ Hz. Both solutions show good agreement, deviating only where expected, and hence showing a well developed numerical procedure.\n\\begin{figure}\\centering\n    \\includegraphics[width=\\textwidth,trim=0ex 0ex 0ex 0ex]{Images/ch4_vtx/gpe_tf_3.pdf}\n    \\caption{The numerical solution (left) and Thomas-Fermi (middle) solutions for a two-dimensional condensate of $^{87}$Rb with $N=1\\times 10^5$ atoms. The lineplot (right) is a central cut through both profiles showing the close match.}\\label{fig:gpe_tf_3}\n\\end{figure}\n\nWhile the Thomas--Fermi solution closely agrees with the numerical solution of the Gross--Pitaevskii equation, this solution is only applicable for stationary states with negligible kinetic energy, i.e.\\ when the nonlinear interaction dominates over the kinetic energy term. For more complex problems involving dynamics, full numerical integration of the Gross--Pitaevskii equation is required.\n\nOne example where the TF approach fails is when investigating superfluid vortex dynamics. To generate vortices in the condensate angular momentum must be added to the system. Seeding a single vortex in the condensate requires that the frequency of rotation, $\\Omega$, must be higher than the critical rotation frequency $\\Omega_c$, as discussed in Sec.~\\ref{ss:vorticesinbec}, and numerically, this is most easily simulated in the co-rotating frame as given by Eq.~\\eqref{eqn:gpe_rotation}. Experimentally, there are many ways to create vortices in a condensate, such as stirring with a blue-detuned laser beam \\cite{Vtx:Raman_prl_2001}, carefully inverting the trap bias field potential \\cite{VTX:Nakahara_physb_2000,VTX:Leanhardt_prl_2002,VTX:Kawaguchi_pra_2004_2, VTX:Kuwamoto_jpsj_2010,VTX:Masuda_pra_2016}, or through the use of artificial gauge fields \\cite{AO:Dalibard_rmp_2011}, to name but a few. In the next sections we will concentrate on solutions where the vortices are already present in the condensate and have settled into the lowest energy configuration.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Few vortex condensates}\\label{sec:fewvtx}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nAs discussed in Section~\\ref{sec:superfluid}, the study of quantum vortices remains an active area of research. As the condensate kinetic energy scales as $E_k \\propto l^2$ (Sec.~\\ref{ss:vorticesinbec}), increased angular momentum leads to the appearance of more singly charged vortices rather than one multiply charged vortex. For a single vortex in a rotating condensate the only stationary solution that exists is if the vortex resides at the exact centre of the trapping potential, making the system radially symmetric. For two vortices the radial symmetry of the system is broken, with the two vortices arranging themselves in the most favourable position to minimise the energy of the system, as with all higher vortex states. Placing vortices of the same sign into a condensate will allow them to behave as identically charged particles, and they will repel, and form ordered lattices with increasing vortex numbers (see Fig.~\\ref{fig:few_rho}). Similarly, if instead we pair a vortex and an antivortex, they will attract, and remain in constant motion, or disappear altogether in the presence of dissipation.\n\nThis stability and dynamical behaviour can be understood by examining the velocity fields of the vortices, as shown in Fig.~\\ref{fig:vel_field} for like-signed vortices, and Fig.~\\ref{fig:vel_pm} for a vortex-antivortex pair. The velocity fields of the vortices are additive, which for like-signed windings creates regions of zero flow, and for opposite-windings creates large flows between them respectively. From Eq.~\\ref{eqn:1_over_r} the velocity field of the irrotational quantum vortex scales as $v \\propto {1/r}$, and hence becomes singular at the vortex centre, giving rise to the large velocities close to the singularity. Fig.~\\ref{fig:vel_pm_contour} shows a clearer view of the velocity fields as depicted by Fig.~\\ref{fig:vel_field}, where the presence of maxima is easily observed at the cores, with field minima also observed due to the vortex-vortex interactions.\n\n\\begin{figure}\\centering\n    \\includegraphics[width=0.48\\textwidth]{Images/ch4_vtx/fewvortex_rho.pdf}\n    \\includegraphics[width=0.48\\textwidth]{Images/ch4_vtx/fewvortex_theta.pdf}\n    \\caption{Density (left) and phase (right) for condensates carrying 1,2,3,and 7 vortices respectively.}\n    \\label{fig:few_rho}\n\\end{figure}\n\n\\begin{figure}\\centering\n    \\includegraphics[width=0.95\\textwidth]{Images/ch4_vtx/velocity/velocity_fixedmag}\n    \\caption{Magnitude of the velocity field and the direction of rotation of the field for clockwise circulating vortices. As the velocity follows a $1/r$ profile the magnitude becomes singular at the centre of the vortices, which is capped here at $v=2.4\\times 10^{-3}$ (ms$^{-1}$).}\n    \\label{fig:vel_field}\n\\end{figure}\n\n\\begin{figure}\\centering\n    \\includegraphics[width=0.55\\textwidth]{Images/ch4_vtx/vtx_anti_velfield}\n    \\caption{Velocity field direction and magnitude originating from vortex and antivortex present in a condensate. Colour scale is in units of ($ms^{-1}$).}\n    \\label{fig:vel_pm}\n\\end{figure}\n\n\\iffalse\n\\begin{figure}\\centering\n    \\includegraphics[width=0.45\\textwidth]{Images/ch4_vtx/vtx_anti_velfield}\n    \\includegraphics[width=0.45\\textwidth]{Images/ch4_vtx/vtx_antivtx_traj}\n    \\caption{(Left) Velocity field originating from vortex and antivortex present in a condensate. (Right) Trajectories of vortex and antivortex in a condensate in the lab frame. Vortices travel on circulating paths which will always intersect through their starting position. Color is used to represent the same times for both vortex and antivortex, which is on the order of seconds.}\n    \\label{fig:vel_pm}\n\\end{figure}\n\\fi\n\n\\begin{figure}\\centering\n    %\\includegraphics[width=0.95\\textwidth]{Images/ch4_vtx/velocity/vel_axis_png}\n    \\includegraphics[width=0.95\\textwidth]{Images/ch4_vtx/velocity/vel.png}\n    \\caption{Magnitude of the velocity field for small numbers of like-signed vortices in a condensate. The velocity field can be seen to become singular at the centre, which here has its magnitude capped at a lower value than Figs.~\\ref{fig:vel_field} and~\\ref{fig:vel_pm} to aid visibility. Regions of minimal velocity are seen, wherein the opposing field lines compensate one another.}\n    \\label{fig:vel_pm_contour}\n\\end{figure}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Rapidly rotating vortex lattice}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Model system}\\label{sec:modelsystem}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\\todo[inline]{Fix velocity fields of all the plots and ensure they are all using the same units and similar ranges.}\n%\\todo[inline]{Explain away the antivortex wobble}\nFor the work to follow we assume a standard single component Bose--Einstein condensate in a radially symmetric trap of frequency $\\omega_\\perp = 2\\pi \\times 1$ Hz. By tightly confining the condensate along the $z$-dimension, with trapping frequency $\\omega_z = 2\\pi\\times 16$ Hz, such that $\\omega_z $ is greater than $ \\omega_\\perp$, the condensate enters the desired pancake-shaped geometry. The system is then modelled using the mean-field GPE Hamiltonian as\n\\begin{equation}\\label{eqn:gpe_h0}\n\tH_{\\mathrm{GP}} = -\\frac{\\hbar^2}{2m}\\nabla^2 + \\frac{1}{2}m\\omega_{\\perp}^2\\mathbf{r}^2 + g_{\\textrm{2D}}\\vert\\Psi(\\mathbf{r},t)\\vert^2.\n\\end{equation}\n\nHere, we define the two-dimensional effective interaction strength $g_{\\textrm{2D}}$ given by Eq.~\\eqref{eqn:g2d_efint}, as\n\\begin{equation}\ng_{\\textrm{2D}} = g\\sqrt{\\frac{m\\omega_z}{2\\pi\\hbar}} = 4g \\sqrt{\\frac{m}{\\hbar}}.\n\\end{equation}\n\nTo describe the system we enter the co-rotating frame, which is done by including the angular momentum operator $L_z$ in the Hamiltonian. The time dependent dynamics of the system are then given by the GPE as\n\\begin{equation}\\label{eqn:gpe2d_}\n\t\\textrm{i}\\hbar\\partial_t\\Psi(\\mathbf{r},t) = \\left[ H_{\\text{GP}}  -  \\Omega L_z \\right] \\Psi(\\mathbf{r},t).\n\\end{equation}\n\nIf the angular rotation frequency approaches the condensate trapping frequency, $\\Omega \\approx \\omega_\\perp$, the condensate gains a large triangular lattice of vortices.  The effect of setting $\\Omega=\\omega_\\perp$, can be partially understood in a mean-field setting by rewriting the GPE kinetic and rotation terms in the form\n\\begin{equation}\n    \\frac{\\mathbf{p}^2}{2m} + \\frac{m\\Omega\\mathbf{r}^2}{2} - \\Omega L_z = \\frac{\\mathbf{\\left(p -{\\textit{ m}}\\boldsymbol{\\Omega}\\times\\mathbf{r}\\right)^2}}{2m}.\n\\end{equation}\n\nThe resulting changes to the GPE are then given by\n\\begin{equation}\\label{eqn:vector_potential_gpe}\n    \\textrm{i}\\hbar\\partial_t \\Psi =\n    \\left(\\frac{1}{2m}(-i\\hbar\\nabla - m\\boldsymbol{\\Omega}\\times\\mathbf{r})^2 + \\frac{m}{2}(\\omega_\\perp^2 - \\Omega^2){r}^2 + g_{\\textrm{2D}}|\\Psi|^2 \\right)\\Psi.\n\\end{equation}\nThe above Hamiltonian demonstrates the correspondence between a rotating condensate and that of a non-relativistic charged particle in a magnetic field~\\cite{Vtx:Mueller_prl_2002}.\n%\\begin{equation}\n%     H_L = \\frac{1}{2m}\\left(-i\\hbar \\nabla  - q\\mathbf{A}\\right)^2 + q\\phi\n%\\end{equation}\n%where $q$ is the particle charge, $\\mathbf{A}$ is the respective gauge potential, and $\\phi$ the respective scalar potential.\nOne can see that when the rotation and trapping frequencies are equal, the condensate no longer sees a confining potential, due to the centrifugal force experienced, given by the term $-m\\Omega^2r^2/2$.\n\nAs stated earlier in Sec.~\\ref{sec:sec2_vtxlatt} as $\\Omega$ approaches $\\omega_\\perp$, the use of mean-field theory becomes less justified, and the system enters a strongly correlated regime. If the filling fraction $\\nu$ is in the range of $10 \\leq \\nu \\leq 1000$, the system enters the ``mean-field quantum Hall'' regime, where the Gross--Pitaevskii theory is still working well. The system examined here is well within this regime for a frequency of $\\Omega = 0.995\\omega_\\perp$. This allows us to work with systems that have a very large vortex lattice, and are still described by mean-field theory \\cite{BEC:Fetter_revmodphys_2009}.\n\nIn the following we will numerically solve Eq.~\\eqref{eqn:gpe2d_}, using the pseudospectral Fourier split operator method and making use of GPU computing as described in Sec.~\\ref{sec:GPUE}. For realistic experimental parameters we assume  $N\\approx 10^6$ atoms of $^{87}$Rb, with an $s$-wave scattering length of $a_s=4.76\\times10^{-9}$ m~\\cite{AO:Roberts_prl_1998}. The numerically evaluated ground-state for the given set of parameters is shown previously in Fig.~\\ref{fig:showingoff} and has a radius of approximately $3.5\\times 10^{-4}$ m. For these parameters, the number of vortices within the visible density region is approximately 600, giving a filling factor of $\\nu \\approx 800 $. This places the system within the mean-field quantum Hall regime, and therefore a description using Gross--Pitaevskii theory is adequate~\\cite{Vtx:Schweikhard_prl_2004}.\n\nFollowing an imaginary time-evolution as outlined in Sec.~\\ref{sec:timeev}, we first find the ground state of the condensate in a harmonic potential, starting with a condensate without vortices. We then linearly ramp the rotation frequency to avoid the lattice disordering issue discussed in Sec.~\\ref{ss:ang_mom_fso}. This allows us to follow the ground state solution at all times while the rotation frequency is increased, which has the added advantage of returning a ground state solution for any required rotation frequency. Examples of several states obtained during a single simulation are given in Fig.~\\ref{fig:inc_omega}. The previously discussed resolution considerations become apparent as the rotation rate is increased for both the position and momentum space representations of the wavefunction. A movie of the wavefunction density is available at the following URL~\\cite{YT:BEC_gen}, in which the frequency is ramped from $\\Omega/\\omega_\\perp = 0.39 \\to 0.995$.\n\nThe rapidly rotating vortex lattice is known to exhibit solid-body-like rotation \\cite{Vtx:AboShaeer_sci_2001}. This can be seen in Fig.~\\ref{fig:solidbody}, where the coarse-grained flow of the velocity field increases as a function of the distance from the lattice centre. This rigid-body behaviour allows us to treat the lattice as a solid object. Recalling the Feynman relation for vortex density Eq.~\\eqref{eqn:feynman}, $n_v = m\\Omega/(\\pi\\hbar)$, we choose an area over which the lattice spacing is almost constant and the vortex density closely matches this relation. In this rapidly rotating regime the vortices close to the centre will have an almost uniform profile~\\cite{VTX:Watanabe_pra_2006}; for the above system parameters this is fulfilled by a hard-walled radial boundary of $r=2\\times 10^{-4}$ m, in which the number of vortices are calculated to being $N_v \\approx 342$. Employing the vortex detection and tracking methods described in Sec.~\\ref{sec:vortrack}, within the same region gives $N_v = 341$ vortices, with a lattice spacing of $a_v \\approx 2.1\\times 10^{-5}$ m, and with a standard deviation of $\\sigma \\approx 2.7 \\times 10^{-7}$ m. These values indicate that within this region the lattice is well ordered. While the condensate has more vortices outside this boundary that are initially ordered, during time evolution many of these move more easily due to the large velocity fields closer to the edges. The above boundary gives a well ordered lattice that remains well ordered for several seconds of time evolution.\n\n\\begin{figure}\\centering\n    \\includegraphics[width=0.85\\textwidth]{Images/ch4_vtx/ramp_omega_2.pdf}\n    \\caption{Density distributions of the wavefunction in position (top) and momentum (bottom) space for increasing rotation frequencies (from left to right). The color axis differs for each plot for visibility, as with a constant axis it is difficult to view densities across all magnitudes. The growth rate of the condensate radius in both position and momentum space becomes large when $\\Omega_z \\approx \\omega_\\perp$.}\n    \\label{fig:inc_omega}\n\\end{figure}\n\n\\begin{figure}\\centering\n    \\includegraphics[width=0.47\\textwidth,clip,trim={0cm 0cm 0 0cm}]{Images/ch4_vtx/solidbody_v}\n    \\includegraphics[width=0.43\\textwidth,clip,trim={0cm 0cm 0 0cm}]{Images/ch4_vtx/solidbody_vel_r}\n    \\caption{(Left) Magnitude and direction of flow of the velocity field for a rapidly rotating vortex lattice in the rapidly rotating frame. (Right) The angle-averaged velocity field from condensate centre. The solid-body rotation can be seen, where the coarse-grained condensate velocity scales as $v \\propto r$ from the condensate centre. Close to the vortex cores the velocity field retains a $1/r_{\\textrm{vtx}}$ profile, becoming singular at the core centres, with $r_{\\textrm{vtx}}$ as the distance from the respective cores.}\n    \\label{fig:solidbody}\n\\end{figure}\n\nIf, however, the linear ramp is performed too quickly, or an initial state is chosen that already contains a large amount of angular momentum without being the eigenstate, the vortices tend to enter from the boundary all at once, and fail to converge to the well ordered ground state. A demonstration of this such issue is shown in Fig.~\\ref{fig:malformed_lattice}, and indicates the need for a slow ramp of $\\Omega$ that is essentially adiabatic in imaginary time. As higher rotation frequencies are reached, the rate at which vortices enter the condensate increases rapidly. While the rapid entry of vortices was a problem for reaching an ordered lattice without a ramp of rotation frequency, the presence of an existing lattice during ramping allows all newly entered vortices to order more easily. Therefore, a linear ramp is effective and does not require a more complex scaling.\n\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=0.65\\textwidth]{Images/ch4_vtx/toofast_099_1e7}\n    \\caption{Disordered lattice resulting from starting in imaginary time evolution at the required rotation rate (here $\\Omega=0.99\\omega_\\perp$). If the rotation frequency is chosen too large without allowing the lattice to form and order, the resulting vortices all enter instantaneously and compete for their final positions. The system only converges one timescales that exceed reasonable computing times.}\n    \\label{fig:malformed_lattice}\n\\end{figure}\n\nIn the following section we will discuss perturbations of the condensate in the presence and absence of vortices. For the above system, we will investigate the effect of perturbations to both the global and local condensate order due to changes in the lattice structure.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 1\n\\section{Condensate perturbations}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% a\n\\subsection{Trapping potential control}\\label{ss:pert_opt_latt}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nWith the model system outlined in Sec.~\\ref{sec:modelsystem}, we will now imagine an abrupt change to the Hamiltonian, such that, $H(t) = H_{\\textrm{GP}} + f(t) V_{\\textrm{ext}}$, where $V_{\\textrm{ext}}$ is an external potential, and $f(t)$ is some function of time to control the application of $V_{\\textrm{ext}}$. In this scenario the initial wavefunction, which is a stationary state of $H_{\\textrm{GP}}$, will no longer remain so provided that $H_{\\textrm{GP}}$ and $f(t) V_{\\textrm{ext}}$ are non-commuting. Assuming the time of application of the additional term is much shorter than any other timescale of the condensate dynamics, any modification of the Hamiltonian in this way can be viewed as a method for changing the phase of the wavefunction.\n%\\begin{equation}\n%    e^{i\\phi} \\mapsto \\exp\\left(-i\\frac{Ht}{\\hbar}\\right),\n%\\end{equation}\nThe resulting effect on the wavefunction can be given as\n\\begin{subequations}\n\\begin{align}\n    \\Psi(t=0) &= |\\Psi(t=0)|e^{\\textrm{i}\\theta_0} \\\\\n    \\Psi(t) &= \\Psi(t=0) e^{ - \\textrm{i} \\frac{ V_{\\textrm{ext}} \\Delta t}{\\hbar}} \\\\\n            &= |\\Psi(t=0)| e^{\\textrm{i}\\left(\\theta_0 - \\frac{V_{\\textrm{ext}} \\Delta t}{\\hbar}\\right)} \\nonumber\n\\end{align}\n\\end{subequations}\nwhere we have made use of Eq.~\\eqref{eqn:madelung}. After application of $V_{\\textrm{ext}}$ the wavefunction phase is given by\n\\begin{equation}\n    \\theta^{'} = \\theta_0 - \\frac{E_{\\textrm{ext}} \\Delta t}{\\hbar},\n\\end{equation}\nwhere $E_{\\textrm{ext}}$ is the perturbance energy. One commonly used method to manipulate the condensate is through the use of optical potentials, which offer a large degree of control over the respective system's Hamiltonian \\cite{BEC:Bloch_revmodphys_2008}. The electric field component of an arbitrary optical field, described by a wavevector $\\mathbf{k}$, and frequency, $\\omega$ is given by\n\\begin{equation}\n    \\mathbf{E}(\\mathbf{r},t) = \\varepsilon_0 e^{\\textrm{i}\\left(\\mathbf{k}\\cdot\\mathbf{r} - \\omega t\\right)} + \\ \\varepsilon_0^{*} e^{-\\textrm{i}\\left(\\mathbf{k}\\cdot\\mathbf{r} - \\omega t\\right)},\n\\end{equation}\nwhere $\\varepsilon_0$ is the field amplitude. Using the dipole approximation, the interaction of an atom with a laser field is given by~\\cite{BK:Foot_2005}\n\\begin{equation}\n\\mathcal{V} = -{\\mathbf{d}}\\cdot {\\mathbf{E}},\n\\end{equation}\nwhere ${\\mathbf{d}}$ is the electric dipole moment operator. For a two level atom with a ground state $| g \\rangle$, and an excited state $| e \\rangle$ with energy difference $\\hbar \\omega_0$, the dipole operator can be written as\n\\begin{align}\\label{eqn:dipole_approx}\n\\mathbf{d} &= \\langle g|\\mathbf{d}|e \\rangle | g \\rangle \\langle e | + \\langle e|\\mathbf{d}|g \\rangle | e \\rangle \\langle g | \\nonumber \\\\\n&= \\boldsymbol{\\mu}_{eg} | g \\rangle \\langle e | + \\boldsymbol{\\mu}_{eg}^{*} | e \\rangle \\langle g |,\n\\end{align}\nwhere we have made use of $\\langle g|\\mathbf{d}|g \\rangle = \\langle e|\\mathbf{d}|e \\rangle  = 0$, since the atoms have no permanent dipole moment. From Eq.~\\eqref{eqn:dipole_approx} the Hamiltonian of the two-level system can then be written as\n\\begin{align}\\label{eqn:dip_hamiltonian}\n    H &= H_0  + \\mathcal{V} \\nonumber \\\\\n      &=  \\hbar\\omega_0 |e\\rangle\\langle e | - (\\boldsymbol{\\mu}_{eg} | g \\rangle \\langle e | + \\boldsymbol{\\mu}_{eg}^{*} | e \\rangle \\langle g |)\\cdot ( \\varepsilon_0 e^{\\textrm{i}\\left(\\mathbf{k}\\cdot\\mathbf{r} - \\omega t\\right)} +  \\varepsilon_0^{*} e^{-\\textrm{i}\\left(\\mathbf{k}\\cdot\\mathbf{r} - \\omega t\\right)}).\n\\end{align}\nAfter expanding~\\eqref{eqn:dip_hamiltonian} we can then rewrite $\\boldsymbol{\\mu}_{eg}\\cdot \\varepsilon_0 = \\hbar\\Omega_r$, where $\\Omega_r$ is the Rabi-oscillation frequency between the states. Assuming that the detuning $\\Delta = \\omega - \\omega_0$ between the laser field and transition frequency is small, $\\Delta \\ll \\omega + \\omega_0$, allows use of the rotating wave approximation. For this we first perform a unitary transformation of the system into the interaction picture rotating with $H_0$ using the operator $U = e^{-\\textrm{i}\\omega_0 t|e\\rangle\\langle e|}$ as\n\\begin{align}\n    H_{\\textrm{int}} & = U^{\\dagger} \\mathcal{V} U.\n\\end{align}\nAll resulting terms featuring $\\omega + \\omega_0$ can be considered to be rapidly oscillating, and average out to zero. Following this approximation, the Hamiltonian can be transformed back into the Schr\\\"odinger picture, giving\n\\begin{align}\n H^{'} = \\hbar\\omega_0 - \\hbar\\Omega\\left(e^{\\textrm{i}\\omega t}|e\\rangle\\langle g|   + e^{-\\textrm{i}\\omega t}|g\\rangle\\langle e|  \\right).\n\\end{align}\nThe final shift of the energies is then given as\n\\begin{equation}\\label{eqn:acshift}\n\\mathcal{V} = -\\frac{\\alpha}{2}\\langle \\mathbf{E}^2\\rangle_t ,\n\\end{equation}\nwhere $\\alpha$ is the real component of the atomic polarisability, and $\\langle \\cdot \\rangle_t$ denotes the time average. If the electric field is spatially inhomogeneous, then this leads to a force of the form\n\\begin{equation}\n\\mathbf{F}_d = \\frac{\\alpha}{2}\\nabla\\langle \\mathbf{E}^2 \\rangle_t ,\n\\end{equation}\nwhich is known as the dipole force. Assuming counter propagating plane waves, we can then model a standing wave solution of the resulting optical potential as\n\\begin{equation}\n    V_{\\textrm{ext}} \\approx -\\frac{\\Omega_0^2(\\mathbf{r})}{4\\Delta}  = V_0 \\cos^2 (\\mathbf{k} \\cdot \\mathbf{r}),\n\\end{equation}\nwhere $V_0 = -\\Omega_0^2/4\\Delta$ is the field intensity, and $\\Omega_0 \\propto |\\varepsilon_0|^2$ is the Rabi-frequency of the standing wave. The optical potential forms a highly periodic system given an appropriately chosen $\\mathbf{k}$, and is known as an \\textit{optical lattice}. Optical lattices have become very common in BEC experiments as they allow for control of the kinetic energy term of the atoms to a very high degree~\\cite{OL:Greiner_nat_2002,OL:Reijnders_prl_2004,OL:Sorensen_prl_2005,Vtx:Tung_prl_2006,Vtx:Vignolo_pra_2007,BEC:Watanabe_entropy_2016}.\n\n%The optical lattice potential can be used to create one, two, or three-dimensional periodic trapping structures.\n%\\todo[inline]{Add full optical potential including polarisation terms}\nDifferent geometric potentials can be formed with optical lattices by using laser fields with different $\\mathbf{k}$ vectors. Assuming standing waves with different polarisation axes or slightly different wavelengths, the interference effects between two or more fields can be ignored, with the resulting optical field given by the summation of lattice potentials with wavevectors $\\mathbf{k}_{1,..,n}$. Creating a 2D lattice with $n$-fold rotational symmetry requires $n/2$ $\\mathbf{k}$-vectors separated by ${2\\pi/n}$, and with $n/2 \\in \\mathbb{Z}^{+}$. Taking a square lattice as an example, which has a 4-fold rotational symmetry, it can be created by two $\\mathbf{k}$-vectors, separated by $\\pi/2$, as\n\\begin{equation}\n    \\mathbf{k}_0 = \\left[ \\begin{array}{cc}\n    1 \\\\\n    0\n    \\end{array} \\right],~\n    \\mathbf{k}_1 =\n    \\left[ \\begin{array}{cc}\n     0 \\\\\n     1\n    \\end{array} \\right].\\label{eqn:sqlatt}\n\\end{equation}\nThe resulting potential is shown in Fig.~\\ref{fig:cos2xy}.\n\\begin{figure}\\centering\n    \\includegraphics[width=0.55\\textwidth]{./Images/ch4_vtx/VOPT/squarelatt}\n    \\caption{Square lattice generation using two orthogonal propagating laser fields with wavevectors $\\mathbf{k}_1$ and $\\mathbf{k}_2$, as defined by Eq.~\\eqref{eqn:sqlatt}.}\\label{fig:cos2xy}\n\\end{figure}\nThe time the optical lattice is applied to the condensate can be controlled by choosing the function $f(t)$. Applying a lattice for a finite, but short, time only will lead to a modification of the wavefunction phase, which then subsequently, and on a much longer time-scale, will have an effect on the density distribution. Of particular interest to us is the use of an optical potential that is pulsed one or several times, which can be described by $f(t)$ as a periodic delta function. The condensate phase profile is the only quantity immediately modified, and any change in the density distribution appears only in the following evolution.\n\n\\iffalse\nFor the purpose of my system, we intend to create a two-dimensional optical lattice, wherein the structure of the lattice matches that of the triangular Abrikosov vortex pattern. The triangular lattice has 6-fold rotational symmetry, and can be formed with wavevectors\n\n\\begin{subequations}\n    \\begin{align}\n        \\mathbf{k}_1 &= k_0\\left\\{\\frac{\\sqrt(3)}{2},\\frac{1}{2}\\right\\} \\\\\n        \\mathbf{k}_2 &= k_0\\{0,1\\} \\\\\n        \\mathbf{k}_3 &= k_0\\left\\{\\frac{\\sqrt(3)}{2},-\\frac{1}{2}\\right\\} \\\\\n    \\end{align}\n\\end{subequations}\nwhere $k_0 = 4\\pi/(\\sqrt(3)a_\\text{O})$, and $a_\\text{O}$ is the lattice spacing.\n\\fi\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% b\n\\subsection{Direct phase manipulation}\\label{sec:phase}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nWhile ground state condensates will have a flat phase across the system, there are two interesting examples where a spatially dependent phase exists: dark solitons~\\cite{BEC:Denschlag_science_2000} and vortices~\\cite{Vtx:Dobrek_pra_1999}. We have previously discussed the $2\\pi$ phase profile of a vortex that leads to the singularities in the wavefunction. In contrast, dark solitons feature a $\\pi$ phase jump profile. These excitations are unstable in dimensions higher than one, and will decay via the snake instability to paired vortices and antivortices~\\cite{Tikhonenko:96, PhysRevLett.86.2926, BEC:Brand_pra_2002}. Where so far we have only considered the short-term evolution of the wavefunction after being kicked by an optical potential, we will in the following consider what structures can be created in the condensate by careful phase manipulation techniques, besides dark solitons and vortices.\n\nFor this we will assume that the BEC allows for a short enough application of potentials so that only the phase is affected, and discuss direct manipulation of the wavefunction, as opposed to modification of the Hamiltonian. Following \\cite{BK:Pitaevskii_Stringari_2003} and taking Eq.~\\eqref{eqn:madelung}, the phase of the condensate can then be written as\n\\begin{equation}\n\\theta = \\theta_0 + \\theta_i,\n\\end{equation}\n\nwhere $\\theta_0$ is the unperturbed condensate phase, and $\\theta_i$ is the phase pattern to be imprinted. Upon solving for the initial condensate ground state with deterministic phase, an additional phase pattern can be imprinted at any time by simply multiplying the wavefunction by $e^{\\text{i}\\theta_i}$. However, without careful choice of the phase terms their addition can lead to unwanted dynamics, so care must be taken to choose a well defined initial and imprinted phase pattern.\n\nThe advantage of the phase imprinting model is that for topological defects, one can imprint the required winding instantaneously, allowing them to appear at predefined positions. The density also needs to only adjust itself locally to the phase singularity, with the remaining condensate seeing an almost constant shift in phase. The creation of vortices through application of localised $\\pm 2\\pi$ phase winding defects in the condensate therefore allows for direct control of the angular momentum and vorticity within the BEC. While discussed in the literature for the creation of vortices, it is worth noting that the phase imprinting method can also be used to annihilate a vortex from the condensate by applying a phase profile of opposite winding, removing the singularity. This will leave the condensate with a density depletion at the prior location of the phase singularity. Without the phase singularity this depletion will fill in and excite phonon modes in the condensate during time evolution. This process will form the basis for further discussions and analysis of vortex carrying condensates.\n\nExperimental realisation of arbitrary potential patterns to achieve the required phase is accessible through the use of spatial light modulators (SLM)~\\cite{VTX:Moulder_pra_2012}. These devices behave as digital displays, through which visual patterns can be expressed in a time dependent manner, allowing the application of a laser field in the required form. We will assume for all future discussions that the potentials we require are experimentally realisable with sufficient resolution, and focus on the resulting effect on the condensate. For the creation of a single vortex the $2\\pi$ phase winding pattern can be created spatially using the two-argument four-quadrant form of $\\arctan$ as given by\n\\begin{equation}\n    \\theta_i(\\mathbf{x},\\mathbf{y};x_0,y_0) = \\arctan(\\mathbf{y}-y_0,\\mathbf{x}-x_0),\n\\end{equation}\nwhich locates the singularity at the position $\\left(x_0,y_0\\right)$. The resulting phase is shown in Fig.~\\ref{fig:atan2phase}(left), and including the additional phase singularity term $\\theta_i$, the condensate wavefunction following an imprint is given as\n\\begin{equation}\n    \\Psi^{'}(\\mathbf{r},t) = |\\Psi(\\mathbf{r},t)|e^{\\text{i}(\\theta_0(\\mathbf{r},t) + \\theta_i(\\mathbf{r}))}.\n\\end{equation}\n\n\\begin{figure}\\centering\n    \\includegraphics[width=0.45\\textwidth]{Images/ch4_vtx/2pi.pdf}\n    \\includegraphics[width=0.435\\textwidth]{Images/ch4_vtx/3_2pi.pdf}\n    \\caption{$2\\pi$ phase winding shown for a single (left) and three separated (right) phase singularities. The application of separate phase singularities can be treated as summing each individual phase profile, $\\left(\\displaystyle\\sum\\limits_i \\theta_i \\right)\\mod 2\\pi$. Note that the resolution used in the numerical examples is much higher than can be obtained from currently available SLMs.}\\label{fig:atan2phase}\n\\end{figure}\n\nFollowing the imprint this process will create phonons in the condensate density that will radiate outwards from the singularity imprint. As imprinting is directly controlling the condensate phase, it can also be considered a direct manipulation of the kinetic energy since the superfluid velocity depends on the phase gradient (see Eq.~\\eqref{eqn:velocity}). This, in reverse, means that by applying spatially inhomogeneous phase profiles the atomic velocity can be adjusted to different values in different regions of the condensate. To demonstrate this we consider a simple example of a Gaussian phase profile applied to the condensate. The imprinted profile has the form\n\\begin{equation}\n    \\theta_{i}(\\mathbf{r}) = A\\exp\\left( -\\frac{ |\\mathbf{r}-\\mathbf{r}_0|^2 }{2\\sigma^2 } \\right) \\mod 2\\pi,\n\\end{equation}\nwhere $A$ is the phase profile amplitude, $\\mathbf{r}_0$ is the centre of the Gaussian curve, and $\\sigma$ is adjusted to match the condensate width. The modulo $2\\pi$ ensures that the phase wraps around for amplitudes exceeding the $(0,2\\pi)$ range. The Gaussian profile has large radial gradients in two-dimensions, so that an imprint on the condensate should lead to radial velocities and therefore an expansion or contraction of the cloud (see Fig.~\\ref{fig:gaussian}). This can be expected to lead to interference fringes, as the faster moving atoms have the possibility to overtake the slower ones for sufficiently large amplitudes~\\cite{BEC:Busch_pra_2002}. In Fig.~\\ref{fig:gaussian_wfc}, where a slice through the condensate centre is given for both position and momentum space, this can be clearly seen.\n\n\\begin{figure}\\centering\n    \\includegraphics[width=0.95\\textwidth]{Images/ch4_vtx/velocity/gaussian_imprint}\n    \\caption{Velocity fields and magnitude (left) and phase (right) for a condensate directly following a Gaussian phase imprint. The lengths of the arrows give the magnitude of the respective velocity components, with the color map indicating this also for clarity. The sign of the imprint changes the direction of the respective kinetic components, with a positive imprint initially creating a density contraction (top), and negative creating an expansion (bottom), with the arrows indicating the direction of the flow.}\\label{fig:gaussian}\n\\end{figure}\n\n\\begin{figure}\\centering\n    \\includegraphics[width=0.95\\textwidth]{Images/ch4_vtx/gaussian_imprint_B}\n    %\\includegraphics[width=0.95\\textwidth]{Images/ch4_vtx/velocity/gaussian_imprint_wfck}\n    \\caption{A cut through the condensate wavefunction density following the phase imprinting of a Gaussian with amplitudes $A=\\pm ( 2\\pi, 6\\pi, 10\\pi)$. The positive imprints create an initial contraction of the cloud (top), while the negative imprints lead to expansion (bottom). For the larger kicking strengths interference fringes can be observed during expansion and contractions.}\\label{fig:gaussian_wfc}\n\\end{figure}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Condensate analysis}\\label{sec:con_analysis}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nTo analyse the effects of the phase imprinting we will below introduce the decomposition of the kinetic energy to isolate the effect from phonons and vortices. Following this, for the vortex lattice we will introduce two closely linked methods to examine geometric structure --- Delaunay triangulation and Voronoi tessellation. These methods are dual to one another, and can be used to easily identify order, structure and local parameters within systems of many particles.\n\n\\subsection{Kinetic energy decomposition}\\label{sec:kinspec}\nGiven that the phase engineering modifies the condensate kinetic energy profile, it is instructive to quantify this effect. One can apply a spectral decomposition of the kinetic energy of the condensate into contributions solely from the vortices (incompressible), and those from the phonons (compressible)~\\cite{CT:Nore_prl_1997,CT:Nore_pof_1997,CT:Bradley_prx_2012}. For this, the wavefunction is again written in terms of amplitude $\\sqrt{\\rho(\\mathbf{r},t)}$ and phase $S(\\mathbf{r},t)$, which allows the kinetic part of the Gross--Pitaevskii energy functional Eq.~\\eqref{eqn:functional_full} to be calculated as\n\\begin{equation}\n    E_{\\text{kqp}} = \\int d\\mathbf{r} \\left( \\frac{\\hbar^2}{2m}| \\nabla\\sqrt{\\rho(\\mathbf{r},t)} |^2  + \\frac{m}{2}|\\sqrt{\\rho(\\mathbf{r},t)}\\mathbf{v}(\\mathbf{r},t) |^2\\right).\n\\end{equation}\nOne can then decompose this into the quantum pressure (first) and kinetic energy (second) terms. The kinetic energy term can be seen as a density-weighted velocity field, $\\mathbf{u}(\\mathbf{r},t) = \\sqrt{\\rho(\\mathbf{r},t)}\\mathbf{v}(\\mathbf{r},t)$, and it can be further decomposed into the sum of compressible and incompressible terms,\n\\begin{equation}\\label{eqn:kin_en}\n    \\mathbf{u(r},t) = \\mathbf{u}^c(\\mathbf{r},t) + \\mathbf{u}^i(\\mathbf{r},t).\n\\end{equation}\nThe two terms can be calculated by performing a Helmholtz decomposition of the field $\\mathbf{u}$, which separates terms that are longitudinal ($\\mathbf{u}^c$) and transversal ($\\mathbf{u}^i$) with\n\\begin{subequations}\\label{eqn:kinterms}\n\\begin{align}\n    \\nabla \\times \\mathbf{u}^c(\\mathbf{r},t) &= 0, \\\\\n    \\nabla \\cdot \\mathbf{u}^i(\\mathbf{r},t) &= 0.\n\\end{align}\n\\end{subequations}\nBy introducing the vector potential, $\\mathbf{A}$, and the scalar potential, $B$, such that\n\\begin{subequations}\n\\begin{align}\n    \\mathbf{u}^c = \\nabla B, \\\\\n    \\mathbf{u}^i = \\nabla \\times \\mathbf{A},\n\\end{align}\n\\end{subequations}\nwe can rewrite Eq.~\\eqref{eqn:kin_en} as\n\\begin{align}\n    \\nabla \\times \\mathbf{u}(\\mathbf{r},t) = -\\nabla^2 \\mathbf{A}, \\\\\n    \\nabla \\cdot \\mathbf{u}(\\mathbf{r},t) = \\nabla^2 {B}.\n\\end{align}\n\nTo solve the above equation we begin by seeking a solution for $B$ by performing a spectral decomposition of the full density-weighted velocity field as\n\\begin{equation}\n    B = \\displaystyle\\sum\\limits_{j} \\frac{k_j}{|\\mathbf{k}|^2}\\mathscr{F}[\\mathbf{u}],\n\\end{equation}\nwhere $k_j$ is the $j$-th component in $\\mathbf{k}$ space, and $\\mathscr{F}$ is the Fourier transform. The resulting solution for $\\mathbf{u}^c$ is then given by\n\\begin{equation}\n    \\mathscr{F}[\\mathbf{u}_i^c] = \\displaystyle\\sum\\limits_{j} \\frac{k_i k_j}{|\\mathbf{k}|^2} \\mathscr{F}[\\mathbf{u}],\n\\end{equation}\nwhich after taking note of Eq.~\\eqref{eqn:kin_en} gives\n\\begin{align}\n    \\mathscr{F}[\\mathbf{u}_i^i] &= \\mathscr{F}[\\mathbf{u}_i] - \\mathscr{F}[\\mathbf{u}_i^c]. \\\\\n    &= \\displaystyle\\sum\\limits_{j}\\left(\\delta_{i,j} - \\frac{k_ik_j}{|\\mathbf{k}|^2}\\right)\\mathscr{F}[\\mathbf{u}_i]. \\nonumber\n\\end{align}\n\nThis decomposition separates the energy contribution from phonons and vortex cores, represented by compressible and incompressible terms respectively~\\cite{CT:Horng_pra_2009}. By averaging over binned shells in $\\mathbf{k}$-space, the kinetic energy spectra, $E^{c,i}(k)$, are calculated as~\\cite{CT:Bradley_prx_2012}\n\\begin{equation}\\label{eqn:kin_spec_ic}\n\tE^{c,i}(k) = \\frac{mk}{2}\\sum\\limits_{j\\in\\mathbf{r}} \\int\\limits_{0}^{2\\pi}d\\phi_k \\frac{ |\\mathcal{U}_j^{c,i}(\\mathbf{k},t) |^2}{s_k},\n\\end{equation}\nwhere\n\\begin{equation}\n\t\\mathcal{U}_j^{c,i}(\\mathbf{k},t) = \\int d^2 \\mathbf{r} e^{-\\textrm{i}(\\mathbf{k}\\cdot\\mathbf{r})} u_j^{c,i}(\\mathbf{r},t).\n\\end{equation}\nThe terms $u_j^{c,i}(\\mathbf{r},t)$ represent the position-space density-weighted velocity components in the specified shell, where $\\phi_k$ is the polar angle, and $s_k$ is the number of values in the chosen shell.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Delaunay triangulation and Voronoi tessellation}\\label{sec:delaunay}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nA common method for examining the ordering and periodicity of large-scale crystalline structures is to generate a mesh with each vertex being the location of a particle. With this, one can easily observe ordered and disordered regions in a material; well defined straight lines indicate a perfect crystal, with any bends indicating the presence of imperfections. Some of the most widely used methods for this are the dual techniques from computational geometry of Delaunay triangulation and Voronoi tessellation.\n\nThe Delaunay triangulation of an arbitrary set of points in Euclidian space, $\\mathbf{R}$, which we will denote as $D(\\mathbf{R})$, is constructed in the following way:\n\\begin{enumerate}\n    \\item No point will fall within the interior of any circumcircle of 3 points where $\\mathbf{r}_{1..3} \\subset \\mathbf{R}$\n    \\item The Delaunay triangulation will maximise the minimum angle between points.\n    \\item If four points are on the same circumcircle, then both possible configurations give a Delaunay triangulation.\n\\end{enumerate}\n\n\\begin{figure}\\centering\n    %\\includegraphics[width=0.45\\textwidth]{Images/ch6_phasegineer/imgs/delaun}\n    \\includegraphics[width=0.45\\textwidth]{Images/ch4_vtx/deltri}\n    \\caption{Non-Delaunay $(a)$ and Delaunay $(b)$ triangulation of 4 Euclidian points.}\\label{fig:delaun}\n\\end{figure}\nThis concept is more easily explained visually. Fig.~\\ref{fig:delaun} shows two different triangulations of four points; situation $(a)$ is a non-Delaunay triangulation, as the points $\\mathbf{r}_1$ and $\\mathbf{r}_3$ each fall within the circumcircle of the other points. However, by simply flipping the central edge from $(\\mathbf{r}_2, \\mathbf{r}_4)$ to $(\\mathbf{r}_1, \\mathbf{r}_3)$ we can see in $(b)$ that we now have a valid Delaunay triangulation. No point falls within the circumcircle of the other points, and the minimum angle formed is maximised relative to configuration $(a)$. Following directly from this, one can see that Delaunay triangulation can be used to connect the closest vertices in a network. A nice side-effect of Delaunay triangulation is that one can examine when the number of edges from a vertex deviates from the expected value in the lattice, which is 6 for triangular lattices. This can be a useful means to locate defects in a crystal lattice, and we will make use of this during later discussions. This is performed using the built-in \\textsc{MATLAB} function ``delaunayTriangulation'', and counting the number of attachments to each individual vertex. A triangulation of the vortex lattice from Fig.~\\ref{fig:showingoff} within the previously discussed radial boundary of $r=2\\times 10^{-4}$ m is shown in Fig.~\\ref{fig:delaun_vtxlatt}.\n\n\\begin{figure}\\centering\n    \\includegraphics[width=0.45\\textwidth]{Images/ch4_vtx/Del_tr_VTXLATT}\n    \\caption{Delaunay triangulation of the vortex lattice ground state. The vertices away from the condensate boundary have the expected 6-edge structure.}\\label{fig:delaun_vtxlatt}\n\\end{figure}\n\nAn alternative representation, using the dual of the Delaunay triangulation, is that of the Voronoi tessellation (diagram). The characteristic of these diagrams is that they are composed of cells each encompassing an individual vertex, within which all enclosed points are closer to that particular vertex than any other. This representation can be generated from the Delaunay triangulation and vice-versa. Taking the centres of the circumcircles describing the Delaunay triangulations, and connecting these forms the boundaries of the Voronoi cells. A simple generation method can be seen as creating and expanding the radius of circles (or $n$-spheres in $n$-dimensions) centred on each vertex. Where the circles intersect with one another defines the boundary of each individual cell. An example of a Voronoi diagram compared with a Delaunay triangulation is given by Fig.~\\ref{fig:Voronoi}.\n\\begin{figure}\\centering\n    \\includegraphics[width=0.55\\textwidth]{Images/ch4_vtx/voronoi}\n    \\caption{Comparison of Delaunay triangulation $(a)$ with a Voronoi diagram $(b)$. These graphs are duals, which means that one can be used to generate the other.}\\label{fig:Voronoi}\n\\end{figure}\nThe area of each cell can be used as a metric of the strength of the interaction between particles in a many-body system, but also we may represent quantities local to each region in a system by the colour-scale of each cell. For the vortex lattice as given by Fig.~\\ref{fig:showingoff}, a sample Voronoi diagram is given in Fig.~\\ref{fig:voron_vtxlatt} with the color representing the area spanned by each Voronoi cell of the lattice.\n\n\\begin{figure}\\centering\n    \\includegraphics[width=0.55\\textwidth]{Images/ch4_vtx/Voronoi_area_VTXLATT}\n    \\caption{Voronoi tesselation of the vortex lattice. The area of each cell is represented by the color mapping. To avoid the tessellation tending to infinity, a buffer region of vortices is created close to the boundary. }\\label{fig:voron_vtxlatt}\n\\end{figure}\n", "meta": {"hexsha": "7400ffbd0fae06101c809ba430e56a8dba3a8cea", "size": 45386, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "MainText/ch4_vort/vort_lattice.tex", "max_stars_repo_name": "mlxd/PhDThesis", "max_stars_repo_head_hexsha": "1b5c6bfd1bfd073b47aa0b1b5abbc7bff5cd521e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MainText/ch4_vort/vort_lattice.tex", "max_issues_repo_name": "mlxd/PhDThesis", "max_issues_repo_head_hexsha": "1b5c6bfd1bfd073b47aa0b1b5abbc7bff5cd521e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MainText/ch4_vort/vort_lattice.tex", "max_forks_repo_name": "mlxd/PhDThesis", "max_forks_repo_head_hexsha": "1b5c6bfd1bfd073b47aa0b1b5abbc7bff5cd521e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 121.0293333333, "max_line_length": 1548, "alphanum_fraction": 0.7520380734, "num_tokens": 12264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.309538522118549}}
{"text": "\\chapter{Conclusions and future work}\n\\label{chp:chapter7}\n\\graphicspath{{figures/}{figures/chapter6/}}\n\\pgfplotsset{\n  table/search path={{figures/chapter6/data},{data}},\n}\n\nIn this dissertation, an isogeometric analysis based patch coupling framework for higher order PDEs is developed. Mathematical analysis and numerical examples veriefy the accuracy and robustness of this technology. The use of dual basis with compact support significantly increases the sparsity of the constrained linear system and reduces the computational cost. In addition, this technology provides a unified formulation when dealing with vertices with different valences, which makes it an ideal analysis technology for higher order problems over unstructured meshes. The main contributions can be summarized as:\n\\begin{itemize}\n  \\item Formulation of abstract dual mortar method for both homogeneous and non-homogeneous constraints.\n  \\item Development of \\Bezier dual mortaring framework for higher order problems, including biharmonic problem, phase-field problem and Kirchhoff-Love shell problem.\n  \\item Development and implementation of different vertex treatments for multi-patch coupling problem.\n  \\item Development of the enriched \\Bezier dual basis, which improves the approximation ability of the \\Bezier dual basis.\n  \\item Development and implementation of two locking-free formulations for both Timoshenko beam and linear elasticity problem. \n  \\item Implementation of a C++ based multi-thread isogeometric analysis code which is utilized in:\n  \\begin{itemize}\n    \\item Simulations of Poisson and biharmonic problems\n    \\item Simulations of wave propagation problems\n    \\item Simulations of coupling problems based on the discontinuous Galerkin method\n    \\item Simulations of linear elasticity and Timoshenko beam problems\n    \\item Simulations of phase field problems\n    \\item Simulations of Kirchhoff-Love shell problems\n  \\end{itemize}\n\\end{itemize}\n\nThere exist many potential future work we can perspect from this work. From the modelling aspect, a potential extension of the present work is to incorperate the constrained NURBS patches directly into the CAD process. The dual mortar formulation provides a direct access to locally supported basis functions in the constrained space, however, these basis functions are not guaranteed to be positive over their supports and form a partition of unity, which are of crucial importance for the CAD community. Hence, in order to use the constrained basis functions as the design space, a better formulation is needed to accommodate these two properties. The support size of the constrained basis function is directly linked to the support size of dual basis functions. However, current enrichment procedure improves the polynomial reproduction at the expense of support size of enriched \\Bezier dual basis functions. We believe there exists a better formulation that can achieve the same performance without any influences on the support size.\\par\n\nThere are many potential research topics in the analysis aspect as well. Since the focus of this research is on the development of a coupling formulation, we assume all materials tested in this work to be linear elastic. Hence, the verification of the dual mortar formulation over non-linear material is needed. The vibration example proved that the weak-$C^1$ coupling scheme can significantly reduce the highest eigenvalue. Hence, it is interested to see the performance of this work in explicit dynamics. $C^2$ continuous functions are required for solving $6^\\text{th}$ order PDEs, including the triharmonic equation~\\cite{tagliabue2014isogeometric, bartezzaghi2015isogeometric}, the phase-field crystal equation~\\cite{gomez2012unconditionally} and Kirchhoff-Love shell with strain gradient elasticity~\\cite{balobanov2019kirchhoff}. Fortunately, it seems that most of the theory and formulation developed in this dissertation can be directly applied in the formulation of weak-$C^2$ continuity. For the coupling of Kirchhoff-Love shell, the dual mortar compatible constraint in this work is slightly stronger than what is required by the problem and may lead to sub-optimal convergence for patches connected at a kink. Hence, the development of a better constraint for Kirchhoff-Love shell is still needed. In addition, shell structures are often connected with solid components (e.g. stiffner), an extension to handle solid-shell coupling is of crucial importance. Furthermore, in the development of dual basis based locking-free element, our study is restricted to the small deformation scenario, however, an extension to the large deformation scenario is of crucial importance. In all of these directions, the use of isogeometric analysis should lead to improvements in both efficiency and accuracy. As a result, these direction may become potentially fruitful research areas in the future.", "meta": {"hexsha": "c5b4137ef9f3c8f9f9254563a5095644598ff61b", "size": 4895, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "exampleFiles/chapter7.tex", "max_stars_repo_name": "miaodi/phd_dissertation", "max_stars_repo_head_hexsha": "80b8d49e46c1ef620f87b30fc45782fe0369c056", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exampleFiles/chapter7.tex", "max_issues_repo_name": "miaodi/phd_dissertation", "max_issues_repo_head_hexsha": "80b8d49e46c1ef620f87b30fc45782fe0369c056", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exampleFiles/chapter7.tex", "max_forks_repo_name": "miaodi/phd_dissertation", "max_forks_repo_head_hexsha": "80b8d49e46c1ef620f87b30fc45782fe0369c056", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 174.8214285714, "max_line_length": 1897, "alphanum_fraction": 0.8196118488, "num_tokens": 975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.309538522118549}}
{"text": "\\section{Zipper}\n\n% \\question{Add a visual example?}\n\nThe Zipper is a technique of representing a data structure by keeping track of how the data structure is being traversed through. The Zipper was first described by \\citeauthor{huet1997zipper}\\cite{huet1997zipper} and is a solution for efficiently updating pure recursive data structures in a purely functional programming language (e.g., Haskell). This is accomplished by keeping track of the downward current subtree and the upward path, also known as the \\textit{location}. \n\nTo keep track of the upward path, we need to store the path we traverse to the current subtree. The traversed path is stored in the \\texttt{Cxt} datatype. The \\texttt{Cxt} datatype represents three options the path could be at: the \\texttt{Top}, the path has traversed to the left (\\texttt{L}), or the path has traversed to the right (\\texttt{R}).\n\n\\begin{minted}{haskell}\ndata Cxt a = Top\n           | L (Cxt a) (Tree a) a\n           | R (Cxt a) (Tree a) a\n\ntype Loc a = (Tree a, Cxt a)\n\nenter :: Tree a -> Loc a\nenter t = (t, Top)           \n\\end{minted}\n\nUsing the \\texttt{Loc}, we can define multiple functions on how to traverse through the \\texttt{Tree}. Then, when we get to the desired location in the \\texttt{Tree}, we can call the \\texttt{modify} function to change the \\texttt{Tree} at the current location.\n\nEventually, when every value in the \\texttt{Tree} has been changed, the entire \\texttt{Tree} can then be rebuilt using the \\texttt{Cxt}. By recursively calling the \\texttt{up} function until the top is reached, the current subtree gets rebuilt. And when the top is reached, the entire tree is then returned.\n\n\\begin{minted}{haskell}\nleft :: Loc a -> Loc a\nleft (Node l x r, c) = (l, L c r x)\n\nright :: Loc a -> Loc a\nright (Node l x r, c) = (r, R c l x)\n\nup :: Loc a -> Loc a\nup (t, L c r x) = (Node t x r, c)\nup (t, R c l x) = (Node l x t, c)\n\nmodify :: (Tree a -> Tree a) -> Loc a -> Loc a\nmodify f (t, c) = (f t, c)\n\nleave :: Loc a -> a\nleave (t, Top) = t\nleave l        = top (up l)\n\n> leave $ modify (const (Leaf 4)) $ left $ enter (Node (Leaf 1) 2 (Leaf 3))\n    (Node (Leaf 4) 2 (Leaf 3))\n\\end{minted}\n\n\n\\subsection{Zipper \\texttt{TreeH}}\n\\label{subsec-zipper-treeh}\n\nThe implementation of the Zipper for the \\texttt{TreeH} datatype is the same as for the \\texttt{Tree} datatype. However, the \\texttt{TreeH} also contains the hash of the current and underlying data structure. Therefore, when a value is modified in the \\texttt{TreeH}, all the parent nodes of the modified value needs to be updated. \n\nThe \\texttt{updateLoc} function modifies the value at the current location, then checks if the location has any parents. If the location has any parents, go up to that parent, update the hash of that parent and recursively update the parents hashes until we are at the top of the data structure. Otherwise, return the modified locations, because all the other hashes are not affected by the change. \n\n\\begin{minted}{haskell}\nupdateLoc :: (TreeH a -> TreeH a) -> Loc a -> Loc a\nupdateLoc f l = if top l' then l' else updateParents (up l')\n  where\n    l' = modify f l\n    updateParents :: Loc a -> Loc a\n    updateParents (Loc x Top) = Loc (updateHash x) Top\n    updateParents (Loc x cs)  = updateParents $ up (Loc (updateHash x) cs)\n\\end{minted}\n\nThen, the \\texttt{update} function can be defined using the \\texttt{updateLoc} function, by first traversing through the data structure with the given directions. Then modifying the location using the \\texttt{updateLoc} function and then leave the location and the function results in the updated data structure.\n\n\\begin{minted}{haskell}\nupdate :: (TreeH a -> TreeH a) -> [Loc a -> Loc a] -> TreeH a -> TreeH a \nupdate f dirs t = leave $ updateLoc f l'\n  where\n    l' = applyDirs dirs (enter t)\n\\end{minted}", "meta": {"hexsha": "93fb87a57553834558295e1efe14320f42466e80", "size": 3813, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "sections/specific_implementation/zipper.tex", "max_stars_repo_name": "jortvangorkum/thesis-paper", "max_stars_repo_head_hexsha": "897946211f14901b656a89b2f56c624c84b4e810", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sections/specific_implementation/zipper.tex", "max_issues_repo_name": "jortvangorkum/thesis-paper", "max_issues_repo_head_hexsha": "897946211f14901b656a89b2f56c624c84b4e810", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sections/specific_implementation/zipper.tex", "max_forks_repo_name": "jortvangorkum/thesis-paper", "max_forks_repo_head_hexsha": "897946211f14901b656a89b2f56c624c84b4e810", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.7042253521, "max_line_length": 476, "alphanum_fraction": 0.7123000262, "num_tokens": 1078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.30953851404073446}}
{"text": "% Note that the text in the [] brackets is the one that will\n% appear in the table of contents, whilst the text in the {}\n% brackets will appear in the main thesis.\n\n%% APPENDIX HEADER ////////////////////////////////////////////////////////////////////////////////////\n\n\\chapter{Interfaces coupling matrix}\n\\label{app:algorithm}\n\n%% APPENDIX CONTENT ///////////////////////////////////////////////////////////////////////////////////\n\\begin{algorithm}[H]\n\t\\SetAlgoLined\n\t\\KwResult{coupling matrix \\textbf{G}}\n\t\\For{i = 1 \\KwTo 2}{\n\t\tcreate \\(n^{\\Gamma}\\times n^{s_i}\\) null matrix \n\t\t\\(\\mathbf{G}_i\\),\\\\\n\t\t\\For{j = 1 \\KwTo \\(n^{\\Gamma}\\)} {\n\t\t\tfind \\(ownerElement^j_i\\) in the structure \\(s_i\\) \n\t\t\tcontaining interface node \\(j\\) with global coordinates vector: \n\t\t\t\\(X_p=(x^j_p,y^j_p)\\)\\;\n\t\t\tassign vector \\(X_e=(x_e,y_e)\\) of coordinates of all nodes in \n\t\t\t\\(ownerElement^j_i\\)\\;\n\t\t\tassign initial coordinates \n\t\t\t\\(X_{\\kappa}=(x^j_{\\kappa},y^j_{\\kappa})\\) to the nearest node in\n\t\t\t\\(ownerElement^j_i\\) to node \\(j\\)\\;\n\t\t\ttransform global coordinates \\(X_{\\kappa}\\) to a local coordinate system \\(\\xi_{\\kappa}=\\xi(X_{\\kappa});\\quad \n\t\t\t\\eta_{\\kappa}=\\eta(X_{\\kappa})\\)\\;\n\t\t\t\\While{\\(\\left|X_p-X_{\\kappa}\\right|>tol\\)}{\n\t\t\t\t\\(\\xi_{\\kappa+1}=\\xi_{\\kappa}+(J^{-1}_{\\kappa})_{11}.*(x^j_p-x_{\\kappa}^j)\n\t\t\t\t+(J^{-1}_{\\kappa})_{12}.*(y^j_p-y_{\\kappa}^j)\\)\\;\n\t\t\t\t\\(\\eta_{\\kappa+1}=\\eta_{\\kappa}+(J^{-1}_{\\kappa})_{21}.*(x^j_p-x_{\\kappa}^j)\n\t\t\t\t+(J^{-1}_{\\kappa})_{22}.*(y^j_p-y_{\\kappa}^j)\\)\\;\n\t\t\t\t\\(X_{\\kappa}=N_{\\kappa+1}X_e\\)\\;\n\t\t\t\t}\n\t\t\t\\(\\mathbf{G}_i(j,n^{X_e})=N_{\\kappa+1}\\)\\;\n\t\t}\n\t\t\\uIf{\\(s_i\\) is 3D} {\n\t\t\t\\(\\mathbf{G}_i=\\left[\\begin{array}{ccc}\n\t\t\t\\mathbf{G}_i & \\mathbf{0} & \\mathbf{0}\\\\\n\t\t\t\\mathbf{0} & \\mathbf{G}_i & \\mathbf{0}\\\\\n\t\t\t\\mathbf{0} & \\mathbf{0} & \\mathbf{G}_i\n\t\t\t\\end{array} \\right]\n\t\t\t\\)\\;\n\t\t}\n\t\t\\ElseIf{\\(s_i\\) is 2D} {\n\t\t\t\\(\\mathbf{G}_i=\\left[\\begin{array}{ccccc}\n\t\t\t\\mathbf{G}_i & \\mathbf{0} & \\mathbf{0} & \n\t\t\t\\frac{h_i}{2}\\mathbf{G}_i & \\mathbf{0}\\\\\n\t\t\t\\mathbf{0} & \\mathbf{G}_i & \\mathbf{0} & \\mathbf{0} & \n\t\t\t\\frac{h_i}{2}\\mathbf{G}_i\\\\\n\t\t\t\\mathbf{0} & \\mathbf{0} & \\mathbf{G}_i & \\mathbf{0} & \n\t\t\t\\mathbf{0}\n\t\t\t\\end{array} \\right]\\)\\;\n\t\t}\n\t}\n\t\\(\\mathbf{G}=\\left[\\begin{array}{cc}\n\t\\mathbf{G}_1 & \\mathbf{G}_2\n\t\\end{array} \\right].\\)\n\t\\caption{Interface coupling matrix formulation}\n\t\\label{alg:G_matrix}\n\\end{algorithm}\nwhere \\(s_i\\) is the structure to, \\(n^{\\Gamma}\\) and \\(n^{s_i}\\) are numbers of nodes of the interface, respectively; \\(J_{\\kappa}\\) is the Jacobian evaluated at \\((\\xi_{\\kappa},\\eta_{\\kappa})\\) and \\(N_{\\kappa+1}\\) is the shape function evaluated at \\((\\xi_{\\kappa+1},\\eta_{\\kappa+1})\\), \\(n^{X_e}\\) is the vector of global order numbers of all nodes in the \\(ownerElements^j_i\\), \\(h_i\\) is a thickness of the structure \\(s_i\\) and \\(tol\\) is a termination criterion for iterations.", "meta": {"hexsha": "ea14a3ada4d7ed734df9ec5e7d90858c77287574", "size": 2837, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/proposal/Dissertation/Appendices/app2.tex", "max_stars_repo_name": "pfiborek/model_hc", "max_stars_repo_head_hexsha": "e27cf98e5d8a5a8ad2ba0c5e70520c281dfd384c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/proposal/Dissertation/Appendices/app2.tex", "max_issues_repo_name": "pfiborek/model_hc", "max_issues_repo_head_hexsha": "e27cf98e5d8a5a8ad2ba0c5e70520c281dfd384c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/proposal/Dissertation/Appendices/app2.tex", "max_forks_repo_name": "pfiborek/model_hc", "max_forks_repo_head_hexsha": "e27cf98e5d8a5a8ad2ba0c5e70520c281dfd384c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.7580645161, "max_line_length": 485, "alphanum_fraction": 0.5675008812, "num_tokens": 1124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.30953642752984306}}
{"text": "\\subsection{Contained class set field values}\n\\label{subsec:library_of_transformations:instance_level_transformations:contained_class_set_field_values}\n\n\\begin{figure}\n    \\centering\n    \\begin{subfigure}{0.95\\textwidth}\n        \\centering\n        \\includegraphics{images/05_library_of_transformations/03_instance_level_transformations/10_contained_class_set_field_values/contained_class_set_field_value.pdf}\n        \\caption{$Im_{ContainedClassSetField}$ with examples of different nodes with different values for $\\type{field}$}\n        \\label{fig:library_of_transformations:instance_level_transformations:contained_class_set_field_values:visualisation:ecore}\n    \\end{subfigure}\n    \\\\\n    \\begin{subfigure}{0.95\\textwidth}\n        \\centering\n        \\input{images/05_library_of_transformations/03_instance_level_transformations/10_contained_class_set_field_values/contained_class_set_as_edge_type_value.tikz}\n        \\caption{$IG_{ContainedClassSetField}$ with examples of different nodes with different values for $\\type{field}$}\n        \\label{fig:library_of_transformations:instance_level_transformations:contained_class_set_field_values:visualisation:groove}\n    \\end{subfigure}\n    \\caption{Visualisation of the transformation of field values from containment fields typed by a set of a proper class type}\n    \\label{fig:library_of_transformations:instance_level_transformations:contained_class_set_field_values:visualisation}\n\\end{figure}\n\nThis section introduces the instance level transformation belonging to the transformation of a containment field of a set of a proper class type. The type level transformation belonging to these fields can be found in \\cref{subsec:library_of_transformations:type_level_transformations:contained_class_set_fields}. On the instance level, values for these fields are introduced.\n\n\\begin{defin}[Instance model $Im_{ContainedClassSetField}$]\n\\label{defin:library_of_transformations:instance_level_transformations:contained_class_set_field_values:imod_contained_class_set_field}\nLet $Im_{ContainedClassSetField}$ be an instance model typed by $Tm_{ContainedClassSetField}$ (\\cref{defin:library_of_transformations:type_level_transformations:contained_class_set_fields:tmod_contained_class_set_field}). Define a set $objects$, which represent the objects that will get a value for the field introduced by $Tm_{DataField}$. Furthermore, define a function $obids$ which maps each of these objects to their corresponding identifier and a function $values$, which maps each of these objects to its value for the field introduced by $Tm_{DataField}$. Please note that $values$ returns a set of objects, as the field allows for this. $Im_{DataField}$ is defined as:\n\\begin{align*}\nObject =\\ &objects \\cup \\bigg(\\bigcup_{ob \\in objects} values(ob)\\bigg)\\\\\n\\mathrm{ObjectClass} =\\ & \\begin{cases}\n    (ob, classtype) & \\mathrm{if }\\ ob \\in objects\\\\\n    (ob, containedtype) & \\mathrm{if }\\ ob \\in \\bigcup_{ob \\in objects} values(ob)\n\\end{cases}\\\\\n\\mathrm{ObjectId} =\\ & \\begin{cases}\n    (ob, obids(ob)) & \\mathrm{if }\\ ob \\in objects\n\\end{cases}\\\\\n\\mathrm{FieldValue} =\\ & \\begin{cases}\n    \\Big((ob, (classtype, name)), \\big[\\type{setof}, \\langle [\\type{obj}, ob] \\mid ob \\in values(ob) \\rangle\\big]\\Big) & \\mathrm{if }\\ ob \\in objects\n\\end{cases} \\\\\n\\mathrm{DefaultValue} =\\ & \\{\\}\n\\end{align*}\n\\isabellelref{imod_contained_class_set_field}{Ecore-GROOVE-Mapping-Library.ContainedClassSetFieldValue}\n\\end{defin}\n\n\\begin{thm}[Correctness of $Im_{ContainedClassSetField}$]\n\\label{defin:library_of_transformations:instance_level_transformations:contained_class_set_field_values:imod_contained_class_set_field_correct}\n$Im_{ContainedClassSetField}$ (\\cref{defin:library_of_transformations:instance_level_transformations:contained_class_set_field_values:imod_contained_class_set_field}) is a valid instance model in the sense of \\cref{defin:formalisations:ecore_formalisation:instance_models:model_validity}.\n\\isabellelref{imod_contained_class_set_field_correct}{Ecore-GROOVE-Mapping-Library.ContainedClassSetFieldValue}\n\\end{thm}\n\nA visual representation of $Im_{ContainedClassSetField}$ with $objects = \\{ob_a, ob_b, ob_c\\}$ can be seen in \\cref{fig:library_of_transformations:instance_level_transformations:contained_class_set_field_values:visualisation:ecore}. This example is typed by $Tm_{ContainedClassSetField}$ in \\cref{fig:library_of_transformations:type_level_transformations:contained_class_set_fields:visualisation:ecore}. In this visualisation, the field value for $ob_a$ is defined as $values(ob_a) = \\{ob_x\\}$. Furthermore, the value for $ob_b$ is $values(ob_a) = \\{ob_y, ob_z\\}$. Finally, the value for $ob_c$ is $values(ob_c) = \\{\\}$, which is allowed because the lower bound of the multiplicity is set 0 by the example. Like the previous transformations for field values, the value needs to be set for all objects that are typed by the class type corresponding to the field. Failing to do so would result in an invalid instance model after it is combined with another model, as the next definition will show. The correctness proof of $Im_{ContainedClassSetField}$ only is already quite involved, but not be included here for conciseness. It can be found as part of the validated Isabelle proofs.\n\nIn order to make composing transformation functions possible, $Im_{ContainedClassSetField}$ should be compatible with the instance model it is combined with.\n\n\\begin{thm}[Correctness of $\\mathrm{combine}(Im, Im_{ContainedClassSetField})$]\n\\label{defin:library_of_transformations:instance_level_transformations:contained_class_set_field_values:imod_contained_class_set_field_combine_correct}\nAssume an instance model $Im$ that is valid in the sense of \\cref{defin:formalisations:ecore_formalisation:instance_models:model_validity}. Then $Im$ is compatible with $Im_{ContainedClassSetField}$ (in the sense of \\cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_instance_models:compatibility}) if:\n\\begin{itemize}\n    \\item All requirements of \\cref{defin:library_of_transformations:type_level_transformations:contained_class_set_fields:tmod_contained_class_set_field_combine_correct} are met, to ensure the combination of the corresponding type models is valid;\n    \\item The class type on which the field is defined by $Tm_{ContainedClassSetField}$ may not be extended by another class type in the type model corresponding to $Im$;\n    \\item The contained type and the class type cannot be the same, e.g. $classtype \\neq containedtype$.\n    \\item All of the objects in the set $objects$ must already be objects in $Im$;\n    \\item All of the referenced objects cannot be objects in $Im$, they are newly introduced by $Im_{ContainedClassSetField}$;\n    \\item All objects typed by the class type on which the field is defined must occur in the set $objects$ and thus have a value in $Im_{ContainedClassSetField}$;\n    \\item For all of the objects in the set $objects$, the identifier set by $obids$ must be the same identifier as set by $Im$ for that object;\n    \\item The object ids for the newly introduced objects must be unique with respect to each other and all other objects within $Im$;\n    \\item For all objects in set $valobjects$, the value set by the $values$ function must be valid and the amount of elements in each value must be within the multiplicity $mul$.\n\\end{itemize}\n\\isabellelref{imod_contained_class_set_field_combine_correct}{Ecore-GROOVE-Mapping-Library.ContainedClassSetFieldValue}\n\\end{thm}\n\n\\begin{proof}\nUse \\cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_instance_models:imod_combine_merge_correct}. It is possible to show that all assumptions hold. Now we have shown that $\\mathrm{combine}(Im, Im_{ContainedClassSetField})$ is consistent in the sense of \\cref{defin:formalisations:ecore_formalisation:instance_models:model_validity}.\n\\end{proof}\n\nPlease note that all objects referenced by any objects via this field are newly created. They may not exist on the existing model. This is enforced to ensure that the containment relations of objects remain acyclic, which is needed to keep the instance model valid. The proof is not included here for conciseness, but can be found as part of the validated proofs in Isabelle.\n\nThe definitions and theorems for introducing values for fields of data types within Ecore are now complete. \n\n\\subsubsection{Encoding as edges and nodes}\n\nIn the type level transformation of contained class set fields, a single containment edge type was introduced to encode the values for the containment field. On the instance level, the values for each object will be encoded using this edge type. The encoding corresponding to $Im_{ContainedClassSetField}$ can then be represented as $IG_{ContainedClassSetField}$, defined in the following definition:\n\n\\begin{defin}[Instance graph $IG_{ContainedClassSetField}$]\n\\label{defin:library_of_transformations:instance_level_transformations:contained_class_set_field_values:ig_contained_class_set_field_as_edge_type}\nLet $IG_{ContainedClassSetField}$ be the instance graph typed by type graph $TG_{ContainedClassSetField}$ (\\cref{defin:library_of_transformations:type_level_transformations:contained_class_set_fields:tg_contained_class_set_field_as_edge_type}). Reuse the set $objects$ from $Im_{ContainedClassSetField}$. Moreover, reuse the functions $obids$ and $values$ from $Im_{ContainedClassSetField}$.\n\nThe objects in the set $objects$ are converted to nodes in $Im_{ContainedClassSetField}$. For each of these objects, a edge is created for each referenced object within the value of that field. Each of these edges targets an node that encodes an object that was referenced by the value. Finally, the identity of the objects is defined using $obids$. $IG_{ContainedClassSetField}$ is defined as:\n\\begin{align*}\nN =\\ & objects \\cup \\bigg(\\bigcup_{ob \\in objects} values(ob)\\bigg)\\\\\nE =\\ & \\bigcup_{ob \\in objects} \\big\\{\\big(ob, (\\mathrm{ns\\_\\!to\\_\\!list}(classtype), \\langle name \\rangle, \\mathrm{ns\\_\\!to\\_\\!list}(containedtype)), v\\big) \\mid v \\in values(ob) \\big\\} \\\\\n\\mathrm{ident} =\\ & \\begin{cases}\n    (obids(ob), ob) & \\mathrm{if }\\ ob \\in objects \\cup \\Big(\\bigcup_{ob \\in objects} values(ob)\\Big)\n\\end{cases}\n\\end{align*}\nwith\n\\begin{align*}\n\\mathrm{type}_n =\\ & \\begin{cases}\n    (ob, \\mathrm{ns\\_\\!to\\_\\!list}(classtype)) & \\mathrm{if }\\ ob \\in objects\\\\\n    (v, \\mathrm{ns\\_\\!to\\_\\!list}(containedtype)) & \\mathrm{if }\\ v \\in \\bigcup_{ob \\in objects} values(ob)\n\\end{cases}\n\\end{align*}\n\\isabellelref{ig_contained_class_set_field_as_edge_type}{Ecore-GROOVE-Mapping-Library.ContainedClassSetFieldValue}\n\\end{defin}\n\n\\begin{thm}[Correctness of $IG_{ContainedClassSetField}$]\n\\label{defin:library_of_transformations:instance_level_transformations:contained_class_set_field_values:ig_contained_class_set_field_as_edge_type_correct}\n$IG_{ContainedClassSetField}$ (\\cref{defin:library_of_transformations:instance_level_transformations:contained_class_set_field_values:ig_contained_class_set_field_as_edge_type}) is a valid instance graph in the sense of \\cref{defin:formalisations:groove_formalisation:instance_graphs:instance_graph_validity}.\n\\isabellelref{ig_contained_class_set_field_as_edge_type_correct}{Ecore-GROOVE-Mapping-Library.ContainedClassSetFieldValue}\n\\end{thm}\n\nA visual representation of $IG_{ContainedClassSetField}$ with $objects = \\{ob_a, ob_b, ob_c\\}$ can be seen in \\cref{fig:library_of_transformations:instance_level_transformations:contained_class_set_field_values:visualisation:groove}. This example is typed by $TG_{ContainedClassSetField}$ in \\cref{fig:library_of_transformations:type_level_transformations:contained_class_set_fields:visualisation:groove}. In this visualisation, the field value for $ob_a$ is defined as $values(ob_a) = \\{ob_x\\}$. Furthermore, the value for $ob_b$ is $values(ob_a) = \\{ob_y, ob_z\\}$. Finally, the value for $ob_c$ is $values(ob_c) = \\{\\}$. Like the previous field encodings, one needs to set the values for the field for all objects of the encoded class type at once. Failing to do so would result in an invalid instance graph after it is combined with another graph, as the next definition will show. The correctness proof of $IG_{ContainedClassSetField}$ only is already quite involved, but not be included here for conciseness. It can be found as part of the validated Isabelle proofs.\n\nIn order to make composing transformation functions possible, $IG_{ContainedClassSetField}$ should be compatible with the instance graph it is combined with.\n\n\\begin{thm}[Correctness of $\\mathrm{combine}(IG, IG_{ContainedClassSetField})$]\n\\label{defin:library_of_transformations:instance_level_transformations:contained_class_set_field_values:ig_contained_class_set_field_as_edge_type_combine_correct}\nAssume an instance graph $IG$ that is valid in the sense of \\cref{defin:formalisations:groove_formalisation:instance_graphs:instance_graph_validity}. Then $IG$ is compatible with $IG_{ContainedClassSetField}$ (in the sense of \\cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_instance_graphs:compatibility}) if:\n\\begin{itemize}\n    \\item All requirements of \\cref{defin:library_of_transformations:type_level_transformations:contained_class_set_fields:tg_contained_class_set_field_as_edge_type_combine_correct} are met, to ensure the combination of the corresponding type graphs is valid;\n    \\item The node type on which the corresponding field is defined is not extended by other node types within the type graph corresponding to $IG$;\n    \\item The contained type and the class type cannot be the same, e.g. $classtype \\neq containedtype$.\n    \\item All nodes in $objects$ are also nodes in $IG_{ContainedClassSetField}$;\n    \\item All nodes referenced by the nodes in $objects$ are not already nodes in $IG_{ContainedClassSetField}$, e.g. the nodes referenced by values are newly introduced;\n    \\item All nodes typed by the node type on which the field is defined must occur in the set $objects$ and thus have a value in $IG_{ContainedClassSetField}$;\n    \\item The object ids for the newly introduced objects must be unique with respect to each other and all other objects within $IG$;\n    \\item For all nodes shared between $IG$ and $IG_{ContainedClassSetField}$, each node must have the same identifier in both $IG$ and $IG_{ContainedClassSetField}$;\n    \\item For all nodes in set $objects$, the value set by the $values$ function must be valid and the amount of elements in each value must be within the multiplicity $mul$.\n\\end{itemize}\n\\isabellelref{ig_contained_class_set_field_as_edge_type_combine_correct}{Ecore-GROOVE-Mapping-Library.ContainedClassSetFieldValue}\n\\end{thm}\n\n\\begin{proof}\nUse \\cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_instance_graphs:ig_combine_merge_correct}. It is possible to show that all assumptions hold. Now we have shown that $\\mathrm{combine}(IG, IG_{ContainedClassSetField})$ is valid in the sense of \\cref{defin:formalisations:groove_formalisation:instance_graphs:instance_graph_validity}.\n\\end{proof}\n\nThe next definitions define the transformation function from $Im_{ContainedClassSetField}$ to \\\\$IG_{ContainedClassSetField}$:\n\n\\begin{defin}[Transformation function $f_{ContainedClassSetField}$]\n\\label{defin:library_of_transformations:instance_level_transformations:contained_class_set_field_values:imod_contained_class_set_field_to_ig_contained_class_set_field_as_edge_type}\nThe transformation function $f_{ContainedClassSetField}(Im)$ is defined as:\n\\begin{align*}\nN =\\ & Object_{Im}\\\\\nE =\\ & \\bigcup_{ob \\in Object_{Im} \\land ob \\in objects} \\big\\{\\big(ob, (\\mathrm{ns\\_\\!to\\_\\!list}(classtype), \\langle name \\rangle, \\mathrm{ns\\_\\!to\\_\\!list}(containedtype)), v\\big) \\mid\\\\&\\qquad\\qquad\\qquad\\qquad\\qquad v \\in values(ob) \\big\\} \\\\\n\\mathrm{ident} =\\ & \\begin{cases}\n    (obids(ob), ob) & \\mathrm{if }\\ ob \\in Object_{Im}\n\\end{cases}\n\\end{align*}\nwith\n\\begin{align*}\n\\mathrm{type}_n =\\ & \\begin{cases}\n    (ob, \\mathrm{ns\\_\\!to\\_\\!list}(classtype)) & \\mathrm{if }\\ ob \\in Object_{Im} \\land ob \\in objects\\\\\n    (v, \\mathrm{ns\\_\\!to\\_\\!list}(containedtype)) & \\mathrm{if }\\ v \\in \\bigcup_{ob \\in Object_{Im} \\land ob \\in objects} values(ob)\n\\end{cases}\n\\end{align*}\n\\isabellelref{imod_contained_class_set_field_to_ig_contained_class_set_field_as_edge_type}{Ecore-GROOVE-Mapping-Library.ContainedClassSetFieldValue}\n\\end{defin}\n\n\\begin{thm}[Correctness of $f_{ContainedClassSetField}$]\n\\label{defin:library_of_transformations:instance_level_transformations:contained_class_set_field_values:imod_contained_class_set_field_to_ig_contained_class_set_field_as_edge_type_func}\n$f_{ContainedClassSetField}(Im)$ (\\cref{defin:library_of_transformations:instance_level_transformations:contained_class_set_field_values:imod_contained_class_set_field_to_ig_contained_class_set_field_as_edge_type}) is a valid transformation function in the sense of \\cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:transformation_function_instance_model_instance_graph} transforming $Im_{ContainedClassSetField}$ into $IG_{ContainedClassSetField}$.\n\\isabellelref{imod_contained_class_set_field_to_ig_contained_class_set_field_as_edge_type_func}{Ecore-GROOVE-Mapping-Library.ContainedClassSetFieldValue}\n\\end{thm}\n\nThe proof of the correctness of $f_{ContainedClassSetField}$ will not be included here. Instead, it can be found in the validated Isabelle theories.\n\nFinally, to complete the transformation, the transformation function that transforms \\\\$IG_{ContainedClassSetField}$ into $Im_{ContainedClassSetField}$ is defined:\n\n\\begin{defin}[Transformation function $f'_{ContainedClassSetField}$]\n\\label{defin:library_of_transformations:instance_level_transformations:contained_class_set_field_values:ig_contained_class_set_field_as_edge_type_to_imod_contained_class_set_field}\nThe transformation function $f'_{ContainedClassSetField}(IG)$ is defined as:\n\\begin{align*}\nObject =\\ &N_{IG} \\\\\n\\mathrm{ObjectClass} =\\ & \\begin{cases}\n    (ob, classtype) & \\mathrm{if }\\ ob \\in N_{IG} \\land ob \\in objects\\\\\n    (ob, containedtype) & \\mathrm{if }\\ ob \\in N_{IG} \\land ob \\in \\bigcup_{ob \\in objects} values(ob)\n\\end{cases}\\\\\n\\mathrm{ObjectId} =\\ & \\begin{cases}\n    (ob, obids(ob)) & \\mathrm{if }\\ ob \\in N_{IG}\n\\end{cases}\\\\\n\\mathrm{FieldValue} =\\ & \\begin{cases}\n    \\Big((ob, (classtype, name)), \\big[\\type{setof}, \\langle [\\type{obj}, ob] \\mid ob \\in values(ob) \\rangle\\big]\\Big) & \\mathrm{if }\\ ob \\in N_{IG}\\ \\land\\\\&\\quad ob \\in objects\n\\end{cases} \\\\\n\\mathrm{DefaultValue} =\\ & \\{\\}\n\\end{align*}\n\\isabellelref{ig_contained_class_set_field_as_edge_type_to_imod_contained_class_set_field}{Ecore-GROOVE-Mapping-Library.ContainedClassSetFieldValue}\n\\end{defin}\n\n\\begin{thm}[Correctness of $f'_{ContainedClassSetField}$]\n\\label{defin:library_of_transformations:instance_level_transformations:contained_class_set_field_values:ig_contained_class_set_field_as_edge_type_to_tmod_class_func}\n$f'_{ContainedClassSetField}(IG)$ (\\cref{defin:library_of_transformations:instance_level_transformations:contained_class_set_field_values:ig_contained_class_set_field_as_edge_type_to_imod_contained_class_set_field}) is a valid transformation function in the sense of \\cref{defin:transformation_framework:instance_models_and_instance_graphs:combining_transformation_functions:transformation_function_instance_graph_instance_model} transforming $IG_{ContainedClassSetField}$ into $Im_{ContainedClassSetField}$.\n\\isabellelref{ig_contained_class_set_field_as_edge_type_to_imod_contained_class_set_field_func}{Ecore-GROOVE-Mapping-Library.ContainedClassSetFieldValue}\n\\end{thm}\n\nOnce more, the correctness proof is not included here but can be found in the validated Isabelle proofs of this thesis.", "meta": {"hexsha": "b41f2553dc6c26ab552037a959808ef4aa87614b", "size": 19813, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/tex/05_library_of_transformations/03_instance_level_transformations/10_contained_class_set_field_values.tex", "max_stars_repo_name": "RemcodM/thesis-ecore-groove-formalisation", "max_stars_repo_head_hexsha": "a0e860c4b60deb2f3798ae2ffc09f18a98cf42ca", "max_stars_repo_licenses": ["AFL-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thesis/tex/05_library_of_transformations/03_instance_level_transformations/10_contained_class_set_field_values.tex", "max_issues_repo_name": "RemcodM/thesis-ecore-groove-formalisation", "max_issues_repo_head_hexsha": "a0e860c4b60deb2f3798ae2ffc09f18a98cf42ca", "max_issues_repo_licenses": ["AFL-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis/tex/05_library_of_transformations/03_instance_level_transformations/10_contained_class_set_field_values.tex", "max_forks_repo_name": "RemcodM/thesis-ecore-groove-formalisation", "max_forks_repo_head_hexsha": "a0e860c4b60deb2f3798ae2ffc09f18a98cf42ca", "max_forks_repo_licenses": ["AFL-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 101.6051282051, "max_line_length": 1182, "alphanum_fraction": 0.8064906879, "num_tokens": 5086, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.3095364209658642}}
{"text": "\\section{Additional preliminaries, lemmas and proofs}\n\\subsection{Signatures of Knowledge}\n\\label{sec:sok}\nA $\\SoK$ for an efficiently decidable binary relation $\\REL$ is defined as a tuple of PPT algorithms $\\SoK = (\\signsetup,  \\sign, \\allowbreak \\verify,  \\simsetup, \\simsign)$:\n\n\\begin{description}\n    \\item[$\\signsetup(1^\\secpar, \\REL) \\rightarrow  \\param$:]\n\tThe setup algorithm takes a security parameter $\\secpar$ and a binary relation $\\REL$\n\tand returns public parameters $ \\param$.  The input $ \\param$ is implicit to all subsequent algorithms. \n\n    \\item[$\\sign(\\mesage, \\inp, \\wit)  \\rightarrow \\signature$:]\nThe signing algorithm takes as input a message $ \\msg \\in \\{0,1\\}^{*}$, \na statement $\\inp$, and a witness $\\wit$.\n\tOutputs a signature $\\signature$.\n\n    \\item[$\\verify(\\mesage, \\inp, \\signature) \\rightarrow 1/ 0$:]\nThe verification algorithm takes as input \n a message $\\mesage$,  a statement $\\inp$ \n together with a signature $\\signature$,\n\toutputs $1$ if the the signature is valid, $0$ otherwise.\n\t\n    \\item[$\\simsetup(\\REL) \\rightarrow (\\param, \\td)$:]\n    \tA simulated setup algorithm which takes as input a relation $\\REL$ and returns public parameters $\\param$ and a trapdoor $\\td$. \n    \t\n   \\item[$\\simsign(\\td, \\mesage, \\inp) \\rightarrow \\signature'$:]\n   \tA simulated signing  that takes as input  a trapdoor $\\td$, a message $\\mesage$ and a statement $\\inp$ and returns a simulated signature $\\signature'$.\n\\end{description}\n \nA SoK scheme should satisfy correctness, extractability and simulatability:\n   \n\\begin{description}\n\\item[Perfect Correctness.] This guarantees that a signer with a valid witness can always produce a signature that\nwill convince the verifier: \nFor all $\\secpar\\in \\NN$, for\nall efficiently decidable binary relation $\\REL$,  \nfor all  $(\\inp, \\wit) \\in \\REL$, and for all $ \\mesage \\in \\{0,1\\}^{*}$:\n   \\[\n  \\condprob{\n\t  \\begin{matrix}\n~\\verify(\\mesage, \\inp, \\signature) = 1   \n\t \\end{matrix}\n}{\n\t  \\begin{matrix}\n~(\\param, \\td) \\gets \\signsetup(1^\\secpar, \\REL)\\\\\n~ \\signature \\gets  \\sign(\\mesage, \\inp, \\wit)\n \\end{matrix} }  =1. \n\\]\n%\n\\item[Simulation Extractability:] This guarantees that an adversary is not able to issue a new signature\nunless it knows a witness. This should hold even if the adversary gets to see signatures on\narbitrary messages under arbitrary statements. We model this notion in a strong sense, by\nletting the adversary see simulated signatures for arbitrary messages and statements, which\npotentially includes false statements. Even under this strong attack model, we require that\nwhenever the adversary outputs a valid signature not queried before, it is possible to extract a\nwitness for the signature. More formally,  for any PPT adversary $\\adv$ there exists a PPT extractor $\\ext_\\adv$ such that:\n   \\[\n  \\condprob{\n\t  \\begin{matrix}\n~ \\verify(\\mesage, \\inp, \\signature) = 1   \\\\\n\\land (\\inp, \\wit) \\notin \\REL \\\\\n\\land (\\mesage, \\inp, \\signature) \\notin Q^{\\simsign_\\td}\n\t \\end{matrix}\n}{\n\t  \\begin{matrix}\n~(\\param, \\td) \\gets \\simsetup(1^\\secpar, \\REL)\\\\\n~ (\\mesage, \\inp, \\signature) \\gets \\adv^{\\simsign_\\td} (\\param)\\\\\n\\wit \\gets \\ext_\\adv({\\sf trans}_\\adv)\n \\end{matrix}\n} \\leq \\negl\n\\]\nwhere the adversary has access to simulated signatures via the oracle $\\simsign_\\td(\\inp_i, \\mesage_i) \\coloneq \\simsign(\\td, \\inp_i, \\mesage_i)$ and the extractor $\\ext_\\adv$ takes as input the transcript ${\\sf trans}_\\adv$ of all queries made by $\\adv$ including its randomness.  \n\n\\vspace{4pt}\n%\n\\item[Perfect Simulatability:] The verifier should not learn anything  about the witness from the signature.  The secrecy of the witness is modelled by the ability to\nsimulate signatures without the witness. More precisely,  we say the signatures of knowledge\nare simulatable if there is a simulator that can create public parameters together with an associated trapdoor that enables producing signatures without a witness that are indistinguishable from real ones.  More formally, for any number of queried $\\mesage_i\\in \\{0,1\\}^{*}$ and $(\\inp_i, \\wit_i) \\in \\REL$:\n\n$\n\\Big\t\\vert\t   \\condprob{  \n\t\t\\begin{matrix}\n\t\t\\adv(\\param) = 1 \n\t\t\\end{matrix}\n\t\t}{\n\t\t\\begin{matrix}\n\t\\param \\gets  \\signsetup(1^\\secpar, \\REL)\\\\\n\t~\\signature_i \\gets \\sign(\\mesage_i, \\inp_i, \\wit_i)\n\t\t\\end{matrix}\n\t\t }\n\t\t- $\n\\[\t  \\condprob{\n\t\t\\begin{matrix}\n\t\t\\adv (\\param) = 1 \n\t\t\\end{matrix}\n}{\n\t\t\\begin{matrix}\n\t~(\\param,\\td) \\gets  \\simsetup(1^\\secpar, \\REL) \\\\\n\t~\\signature_i \\gets   \\simsign(\\td,\\mesage_i, \\inp_i)\n\t\t\\end{matrix}} \\Big\t\\vert\t\n\t\t \\leq \\negl.\n\t\t\\]\n  \\end{description}\n\n  \\subsection{Dlog assumptions}\n\\label{sec:dlog_assumptions}\n\\begin{definition}[$(q_1, q_2)\\mhyph\\dlog$ assumption]\n\tLet $\\adv$ be a $\\ppt$ adversary that gets as input\n  $\\gone{1, \\chi, \\ldots, \\chi^{q_1}}, \\gtwo{1, \\chi, \\ldots, \\chi^{q_2}}$, for\n  some randomly picked $\\chi \\in \\FF_p$, then\n\t\\[\n\t\t\\condprob{\\chi \\gets \\adv(\\gone{1, \\chi, \\ldots, \\chi^{q_1}}, \\gtwo{1, \\chi,\n        \\ldots, \\chi^{q_2} })}{\\chi \\sample \\FF_p} \\leq \\negl.\n\t\\]\n\\end{definition}\n\n\\begin{definition}[$(q_1, q_2)\\mhyph\\ldlog$ assumption]\n  Let $\\adv$ be a $\\ppt$ adversary that gets as input\n  $\\gone{\\chi^{-q_1}, \\ldots, 1, \\chi, \\ldots, \\chi^{q_1}}, \\gtwo{\\chi^{-q_2},\n    \\ldots, 1, \\chi, \\ldots, \\chi^{q_2}}$, for some randomly picked\n  $\\chi \\in \\FF_p$, then\n\t\\[\n    \\condprob{\\chi \\gets \\adv(\\gone{\\chi^{-q_1}, \\ldots, 1, \\chi, \\ldots,\n        \\chi^{q_1}}, \\gtwo{\\chi^{-q_2}, \\ldots, 1, \\chi, \\ldots, \\chi^{q_2}\n      })}{\\chi \\sample \\FF_p} \\leq \\negl.\n\t\\]\n\\end{definition}\n\n\\subsection{Uber assumption}\n\\label{sec:uber_assumption}\n\\ourpar{BBG uber assumption.}\nAlso, to be able to show trapdoor-less simulatability of\n$\\plonk$ in the standard model, what is required by our reduction, we rely on the\n\\emph{uber assumption} introduced by Boneh et\nal.~\\cite{EC:BonBoyGoh05} as presented by Boyen in \\cite{PAIRING:Boyen08}.\n\nLet $r, s, t, c \\in \\NN \\setminus \\smallset{0}$, Consider vectors of polynomials\n$\\pR \\in \\FF_p[X_1, \\ldots, X_c]^r$, $\\pS \\in \\FF_p[X_1, \\ldots, X_c]^s$ and\n$\\pT \\in \\FF_p[X_1, \\ldots, X_c]^t$. Write $\\pR = \\left( \\p{r}_1, \\ldots,\n  \\p{r}_r \\right)$, $\\pS = \\left( \\p{s}_1, \\ldots, \\p{s}_s \\right)$ and $\\pT =\n\\left( \\p{t}_1, \\ldots, \\p{t}_t \\right)$ for polynomials $\\p{r}_i, \\p{s}_j,\n\\p{t}_k$.\n\nFor a function $f$ and vector $(x_1, \\ldots, x_c)$ we write $f(\\pR)$ to\ndenote application of $f$ to each element of $\\pR$, i.e.\n\\(\n\tf(\\pR) = \\left( f(\\p{r}_1 (x_1, \\ldots, x_c), \\ldots, f(\\p{r}_r\n\t(x_1, \\ldots, x_c) \\right).\n\\)\nSimilarly for applying $f$ to $\\pS$ and $\\pT$.\n\n\\begin{definition}[Independence of $\\pR, \\pS, \\pT$]\n\t\\label{def:independence}\n\tLet $\\pR, \\pS, \\pT$ be defined as above. We say that polynomial $\\p{f} \\in\n  \\FF_p[X_1, \\ldots, X_c]$ is \\emph{dependent} on $\\pR, \\pS, \\pT$ if there\n  exists $rs + t$ constants $a_{i, j}, b_k$ such that $ \\p{f} = \\sum_{i = 1}^{r}\n  \\sum_{j = 1}^{s} a_{i, j} \\p{r}_i \\p{s}_j + \\sum_{k = 1}^{t} b_k \\p{t}_k. $ We\n  say that $\\p{f}$ is \\emph{independent} if it is not dependent.\n\\end{definition}\n\nTo show (standard-model) zero knowledge of $\\plonk$ we utilize a generalization\nof Boneh-Boyen-Goh's \\emph{uber assumption} \\cite{EC:BonBoyGoh05} stated as\nfollows (the changed element has been put into a \\dbox{dashbox})\n\\begin{definition}[$(\\pR, \\pS, \\pT, \\p{F}, 1)$-uber assumption]\n\t\\label{def:uber_assumption}\n\tLet $\\pR, \\pS, \\pT$ be defined as above,\n    $(x_1, \\ldots, x_c, y_1, \\ldots, y_{d}) \\sample \\FF_p^{c + d}$ and let\n    $\\p{F}$ be a cardinality-$d$ set of pair-wise independent polynomials which are also\n    independent of $(\\pR, \\pS, \\pT)$, cf.~\\cref{def:independence}.  Then, for\n    any $\\ppt$ adversary $\\adv$\n\t\\begin{multline*}\n      \\Pr\\left[\\adv(\\gone{\\pR(x_1, \\ldots x_c)}, \\gtwo{\\pS(x_1, \\ldots, x_c)},\n\t\t\\gtar{\\pT(x_1, \\ldots, x_c)}, \\dboxed{\\gone{\\p{F}(x_1, \\ldots, x_c)}}) = 1\\right] \\approx_\\secpar \\\\\n      \\Pr\\left[\\adv(\\gone{\\pR(x_1, \\ldots x_c)}, \\gtwo{\\pS(x_1, \\ldots, x_c)},\n        \\gtar{\\pT(x_1, \\ldots, x_c)}, \\dboxed{\\gone{y_1, \\ldots, y_{d}}}) =\n        1\\right].\n\t\\end{multline*}\n  \\end{definition}\n\n  Compared to the original uber assumptions, there are two major changes. First,\n  we require not target group $\\GRP_T$ elements to be indistinguishable, but\n  elements of $\\GRP_1$. Second, Boneh et al.'s assumption works for\n  distinguishers who are given only one challenge polynomial $\\p{f}$,\n  i.e.~$\\abs{\\p{F}} = 1$.\n  \nWe show security of our version of the uber assumption using the generic group\nmodel as introduced by Shoup \\cite{EC:Shoup97} where all group elements are\nrepresented by random binary strings of length $\\secpar$. That is, there are\nrandom encodings $\\xi_1, \\xi_2, \\xi_T$ which are injective functions from\n$\\ZZ_p^+$ to $\\bin^{\\secpar}$. We write\n$\\GRP_i = \\smallset{\\xi_i(x) \\mid x \\in \\ZZ_p^+}$, for\n$i \\in \\smallset{1, 2, T}$. For the sake of clarity  we denote by $\\xi_{i, j}$\nthe $j$-th encoding in group $\\GRP_i$.\n\nLet\n$\\p{P}_i = \\smallset{p_1, \\ldots, p_{\\tau_i}} \\subset \\FF_p[X_1, \\ldots, X_n]$,\nfor $i \\in \\smallset{1, 2, T}, \\tau_i, n \\in \\NN$, be sets of multivariate\npolynomials. Denote by $\\p{P}_i(x_1, \\ldots, x_n)$ a set of evaluations of\npolynomials in $\\p{P_i}$ at $(x_1, \\ldots, x_n)$. Denote by\n$L_i = \\smallset{(p_j, \\xi_{i, j}) \\mid j \\leq \\tau_i}$.\n\nLet $\\adv$ be an algorithm that is given encodings $\\xi_{i, j_i}$ of polynomials\nin $\\p{P}_i$ for $i \\in \\smallset{1, 2, T}, j_i = \\tau_i$. There is an oracle $\\oracleo$\nthat allows to perform $\\adv$ the following queries:\n\\begin{description}\n\\item[Group operations in $\\GRP_1, \\GRP_2, \\GRP_T$:] On input\n  $(\\xi_{i, j}, \\xi_{i, j'}, i, op)$, $j, j' \\leq \\tau_i$,\n  $op \\in \\smallset{\\msg{add}, \\msg{sub}}$, $\\oracleo$ sets $\\tau'_i \\gets \\tau_i + 1$,\n  computes\n  $p_{i, \\tau'_i} = p_{i, j}(x_1, \\ldots, x_n) \\pm p_{i, j'}(x_1, \\ldots, x_n)$\n  respectively to $op$. If there is an element  $p_{i, k} \\in L_i$ such \n  that $p_{i, k} = p_{\\tau'_i}$, then the oracle returns encoding of $p_{i,\n    k}$. Otherwise it sets the encoding $\\xi_{i, \\tau'_i}$ to a new unused\n  random string, adds $(p_{i, \\tau'_i}, \\xi_{i, \\tau'_i})$ to $L_i$, and returns\n  $\\xi_{i, \\tau'_i}$.\n\\item[Bilinear pairing:] On input $(\\xi_{1, j}, \\xi_{2, j'})$ the oracle sets\n  $\\tau' \\gets \\tau_T + 1$ and computes\n  $r_{\\tau'} \\gets p_{i, j}(x_1, \\ldots, x_n) \\cdot p_{i, j'}(x_1, \\ldots,\n  x_n)$. If $r_{\\tau'} \\in L_T$ then return encoding found in the list $L_T$,\n  else pick a new unused random string and set $\\xi_{T, \\tau'}$ to it. Return\n  the encoding to the algorithm.\n\\end{description}\n\nGiven that, we are ready to show security of our variant of the Boneh et\nal.~uber assumption. The proof goes similarly to the original proof given in\n\\cite{EC:BonBoyGoh05} with minor differences.\n\n\\begin{theorem}[Security of the uber assumption]\n  \\label{thm:uber_assumption}\n  Let $\\p{P}_i \\in \\FF_p[X_1, \\ldots, X_n]^{m_i}$, for\n  $i \\in \\smallset{1, 2, T}$ be $\\tau_i$ tuples of $n$-variate polynomials over\n  $\\FF_p$ and let $\\p{F} \\in \\FF_p[X_1, \\ldots, X_n]^m$. Let\n  $\\xi_0, \\xi_1, \\xi_T$, $\\GRP_1, \\GRP_2, \\GRP_T$ be as defined above. If\n  polynomials $f \\in \\p{F}$ are pair-wise independent and are independent of\n  $\\p{P}_1, \\p{P}_2, \\p{P}_T$, then for any $\\adv$ that makes up to $q$ queries to the\n  GGM oracle holds:\n  \\begin{equation*}\n    \\begin{split}\n     \\left|\\,\n    \\Pr\\left[\n    \\adv\\left(\n      \\begin{aligned}\n        \\xi_1(\\p{P}_1(x_1, \\ldots, x_n)), \\\\\n        \\xi_2(\\p{P}_2(x_1, \\ldots, x_n)), \\\\\n        \\xi_T(\\p{P}_T(x_1, \\ldots, x_n)), \\\\\n        \\xi_{1}(\\p{F}_0), \\xi_{1}(\\p{F}_1)\n      \\end{aligned}\n    \\right) = b\n    \\, \\left|\\,\n      \\begin{aligned}\n        x_1, \\ldots, x_n, y_1, \\ldots, y_m \\sample \\FF_p,\\\\\n        b \\sample \\bin, \\\\\n        \\p{F}_b \\gets \\p{F}(x_1, \\ldots, x_n),\\\\\n        \\p{F}_{1 - b} \\gets (y_1, \\ldots, y_m)\n      \\end{aligned}\n    \\right.  \\right] - \\frac{1}{2} \\, \\right| \\\\\n     \\leq \\frac{d(q + m_1 + m_2 + m_T +\n      m)^2 }{2p}\n    \\end{split}\n  \\end{equation*}\n\\end{theorem}\n\\begin{proof}\n  Let $\\cdv$ be a challenger that plays with $\\adv$ in the following\n  game. $\\cdv$ maintains three lists\n  \\[\n    L_i = \\smallset{(p_j, \\xi_{i, j}) \\mid j \\in \\range{1}{\\tau_i}},\n  \\]\n  for $i \\in \\smallset{1, 2, T}$. Invariant $\\tau$ states that\n  $\\tau_1 + \\tau_2 + \\tau_T = \\tau + m_1 + m_2 + m$.\n\n  Challenger $\\cdv$ answers $\\adv$'s oracle queries. However, it does it a bit\n  differently that the oracle $\\oracleo$ would:\n  \\begin{description}\n  \\item[Group operations in $\\GRP_1, \\GRP_2, \\GRP_T$:] On input\n    $(\\xi_{i, j}, \\xi_{i, j'}, i, op)$, $j, j' \\leq \\tau_i$,\n    $op \\in \\smallset{\\msg{add}, \\msg{sub}}$, $\\cdv$ sets\n    $\\tau' \\gets \\tau_i + 1$, computes\n    $p_{i, \\tau'}(X_1, \\ldots, X_n) = p_{i, j}(X_1, \\ldots, X_n) \\pm p_{i,\n      j'}(X_1, \\ldots, X_n)$ respectively to $op$. If there is a polynomial\n    $p_{i, k}(X_1, \\ldots, X_n) \\in L_i$ such that\n    $p_{i, k}(X_1, \\ldots, X_n) = p_{\\tau'}(X_1, \\ldots, X_n)$, then the\n    challenger returns encoding of $p_{i, k}$. Otherwise it sets the encoding\n    $\\xi_{i, \\tau'}$ to a new unused random string, adds\n    $(p_{i, \\tau'}, \\xi_{i, \\tau'})$ to $L_i$, and returns $\\xi_{i, \\tau'}$.\n  \\item[Bilinear pairing:] On input $(\\xi_{1, j}, \\xi_{2, j'})$ the challenger\n    sets $\\tau' \\gets \\tau_T + 1$ and computes\n    $r_{\\tau'}(X_1, \\ldots, X_n) \\gets p_{i, j}(X_1, \\ldots, X_n) \\cdot p_{i,\n      j'}(X_1, \\ldots, X_n)$. If $r_{\\tau'}(X_1, \\ldots, X_n) \\in L_T$, $\\cdv$\n    returns encoding found in the list $L_T$. Else it picks a new unused random\n    string and set $\\xi_{T, \\tau'}$ to it. Finally it returns the encoding to\n    the algorithm.\n\\end{description}\n  \nAfter at most $q$ queries to the oracle, the adversary returns a bit $b'$. At\nthat point the challenger $\\cdv$ chooses randomly $x_1, \\ldots, x_n, y_1 \\ldots, y_m$,\nrandom bit $b$, and sets $X_i = x_i$, for $i \\in \\range{1}{n}$, and $Y_i = y_i$,\nfor $i \\in \\range{1}{m}$; furthermore, $\\p{F}_b \\gets \\p{F}(x_1, \\ldots, x_n)$\nand $\\p{F}_{1 - b} \\gets (y_1, \\ldots, y_m)$. Note that $\\cdv$ simulates\nperfectly unless the chosen values $x_1, \\ldots, x_n, y_1, \\ldots, y_m$ result\nin equalities between polynomial evaluations that are not equalities between the\npolynomials. That is, the simulation is perfect unless for some $i, j, j'$ holds\n\\[\n  p_{i, j}(x_1, \\ldots, x_n) - p_{i, j'}(x_1, \\ldots, x_n) = 0,\n  \\]\n  for $p_{i, j}(X_1, \\ldots, X_n) \\neq p_{i, j'}(X_1, \\ldots, X_n)$.  Denote by\n  $\\bad$ an event that at least one of the three conditions holds. When $\\bad$\n  happens, the answer $\\cdv$ gives to $\\adv$ differs from an answer that a real\n  oracle would give. We bound the probability that $\\bad$ occurs in two steps.\n\n  First we set $\\p{F}_b = \\p{F}(X_1, \\ldots, X_n)$. Note that symbolic\n  substitutions do not introduce any new equalities in $\\GRP_1$. That is, if for\n  all $j, j'$ holds $p_{1, j} \\neq p_{1, j'}$, then $p_{1, j} \\neq p_{1, j'}$\n  even after setting $\\p{F}_b = \\p{F}(X_1, \\ldots, X_n)$. This follows since all\n  polynomials in $\\p{F}$ are pairwise independent and $\\p{F}$ independent on\n  $\\p{P}_1, \\p{P}_2, \\p{P}_T$. Indeed, $p_{1, j} - p_{1, j'}$ is a polynomial of\n  the form\n  \\[\n    \\sum_{j = 1}^{m_1}a_j p_{1, j} + \\sum_{j = 1}^{m} b_j f_j (X_1, \\ldots, X_n),\n  \\]\n  for some constants $a_j, b_j$. If the polynomial is non-zero, but setting\n  $\\p{F}_b = \\p{F}(X_1, \\ldots, X_n)$ makes this polynomial vanish, then some\n  $f_k$ must be dependent on some $\\p{P}_1, \\p{F} \\setminus \\smallset{f_k}$.\n\n  Now we set $X_1 \\ldots, X_n, \\p{F}_{1 - b}$ and bound probability that for\n  some $i$ and $j, j'$ holds\n  $(p_{i, j}(x_1, \\ldots, x_n) - p_{i, j'}(x_1, \\ldots, x_n) = 0$ for\n  $p_{i, j} \\neq p_{i, j'}$. By the construction, the maximum total degree of\n  these polynomials is\n  $d = \\max(d_{\\p{P}_1}+ d_{\\p{P}_2}, d_{\\p{P}_T}, d_{\\p{F}})$, where $d_f$ is\n  the total degree of some polynomial $f$ and for a set of polynomials\n  $F = \\smallset{f_1, \\ldots, f_k}$, we write\n  $d_F = \\smallset{d_{f_1}, \\ldots, d_{f_k}}$. Thus, for a given $j, j'$ probability that a random assignment to\n  $X_1, \\ldots, X_n, Y_1, \\ldots, Y_n$ is a root of $p_{i, j} - p_{i, j'}$ is,\n  by the Schwartz-Zippel lemma, bounded by $\\infrac{d}{p}$, which is\n  negligible. There is at most $2 \\cdot {q + m_0 + m_1 + m  \\choose 2}$ such\n  pairs $p_{i, j}, p_{i, j'}$ we have that\n  \\[\n    \\prob{\\bad} \\leq  {q + m_0 + m_1 + m  \\choose 2} \\cdot \\frac{2d}{p} \\leq (q\n    + m_0 + m_1 + m)^2 \\frac{d}{p}.\n  \\]\n\n  As noted, if $\\bad$ does not occur then the simulation is perfect. Also the\n  bit $b$ has been chosen independently on the $\\adv$'s view, thus $\\condprob{b\n    = b'}{\\neg \\bad} = \\infrac{1}{2}$. Hence,\n  \\[\n    \\begin{aligned}\n      \\prob{b = b'} & \\leq \\condprob{b = b'}{\\neg \\bad}(1 - \\prob{\\bad}) + \\prob{\\bad} =\n      \\frac{1}{2} + \\frac{\\prob{\\bad}}{2} \\\\\n      \\prob{b = b'} & \\geq \\condprob{b = b'}{\\neq \\bad}(1 - \\prob{\\bad}) =\n      \\frac{1}{2} - \\frac{\\prob{\\bad}}{2}.\n    \\end{aligned}\n  \\]\n  Finally,\n  \\[\n    \\abs{\\Pr[b = b'] - \\frac{1}{2}} \\leq \\prob{\\bad}/2 \\leq (q\n    + m_0 + m_1 + m)^2 \\frac{d}{2p}\n  \\]\n  as required.\n\\end{proof}\n\n\\subsection{Special simulation-extractability of sigma protocols and forking lemma}\n\\label{sec:forking_lemma}\n\\begin{theorem}[Special simulation extractability of the Fiat--Shamir transform\n  \\cite{INDOCRYPT:FKMV12}]\n\tLet $\\sigmaprot = (\\prover, \\verifier, \\simulator)$ be a non-trivial sigma\n  protocol with unique responses for a language $\\LANG \\in \\npol$. In the random\n  oracle model, the NIZK proof system $\\sigmaprot_\\fs = (\\prover_\\fs,\n  \\verifier_\\fs, \\simulator_{\\fs})$ resulting by applying the Fiat--Shamir\n  transform to $\\sigmaprot$ is special simulation extractable with extraction error\n  $\\eta = q/h$ for the simulator $\\simulator$. Here, $q$ is the number of random\n  oracle queries and $h$ is the number of elements in the range of $\\ro$.\n\\end{theorem}\n\nThe theorem relies on the following \\emph{general forking lemma} \\cite{JC:PoiSte00}.\n\n\\begin{lemma}[General forking lemma, cf.~\\cite{INDOCRYPT:FKMV12,CCS:BelNev06}]\n\t\\label{lem:forking_lemma}\n\tFix $q \\in \\ZZ$ and a set $H$ of size $h > 2$. Let $\\zdv$ be a $\\ppt$\n  algorithm that on input $y, h_1, \\ldots, h_q$ returns $(i, s)$, where $i\n  \\in\\range{0}{q}$ and $s$ is called a \\emph{side output}. Denote by $\\ig$ a\n  randomised instance generator. We denote by $\\accProb$ the probability\n\t\\[\n\t\t\\condprob{i > 0}{y \\gets \\ig; h_1, \\ldots, h_q \\sample H; (i, s) \\gets\n\t\t\\zdv(y, h_1, \\ldots, h_q)}\\,.\n\t\\]\n\tLet $\\forking_\\zdv(y)$ denote the algorithm described in\n  \\cref{fig:forking_lemma}, then the probability $\\frkProb$ defined as $\n  \\frkProb := \\condprob{b = 1}{y \\gets \\ig; (b, s, s') \\gets \\forking_{\\zdv}(y)}\n  $ holds\n\t\\[\n\t\t\\frkProb \\geq \\accProb \\brak{\\frac{\\accProb}{q} - \\frac{1}{h}}\\,.\n\t\\]\n\t%\n\t\\begin{figure}\n\t\t\\centering\n\t\t\\fbox{\n\t\t\\procedure{$\\forking_\\zdv (y)$}\n\t\t{\n\t\t\t\\rho \\sample \\RND{\\zdv}\\\\\n\t\t\th_1, \\ldots, h_q \\sample H\\\\\n\t\t\t(i, s) \\gets \\zdv(y, h_1, \\ldots, h_q; \\rho)\\\\\n\t\t\t\\pcif i = 0\\ \\pcreturn (0, \\bot, \\bot)\\\\\n\t\t\th'_{i}, \\ldots, h'_{q} \\sample H\\\\\n\t\t\t(i', s') \\gets \\zdv(y, h_1, \\ldots, h_{i - 1}, h'_{i}, \\ldots,  h'_{q};\n\t\t\t\\rho)\\\\\n\t\t\t\\pcif (i = i') \\land (h_{i} \\neq h'_{i})\\ \\pcreturn (1, s, s')\\\\\n\t\t\t\\pcind \\pcelse \\pcreturn (0, \\bot, \\bot)\n\t\t}}\n\t\t\\caption{Forking algorithm $\\forking_\\zdv$}\n\t\t\\label{fig:forking_lemma}\n\\end{figure}\n\\end{lemma}\n\n\\subsection{Proof of the generalized forking lemma (\\cref{lem:generalised_forking_lemma})}\n\\label{sec:forking_proof}\n\\begin{proof}\nFirst denote by $\\accProb(y)$ and $\\frkProb(y)$ the following probabilities\n\\begin{align*}\n\\accProb(y) & =  \\condprob{i \\neq 0}{h_1, \\ldots, h_q \\sample H;\\ (i, s)\n\\gets \\zdv(y, h_1, \\ldots, h_q)}\\,.\\\\\n\t\\frkProb(y) & = \\condprob{b = 1}{(b, \\vec{s}) \\gets\n\\genforking_{\\zdv}^{m}(y, h_1, \\ldots, h_q)}\\,.\n\\end{align*}\n\nWe start by claiming that for all $y$ \n\\begin{equation}\\label{eq:frkProb_y}\n\t\\frkProb(y) \\geq \n\t\\frac{\\accProb(y)^m}{q^{m - 1}} - \\accProb(y) \\cdot \\left(1 -\n  \\frac{h!}{(h - m)! \\cdot h^{m}}\\right)\n\t\\end{equation}\nThen with the expectation taken over $y \\sample \\ig$, we have\n\\begin{align}\n\t\\frkProb & = \\expected{\\frkProb(y)} \\geq\n\t\\expected{\\frac{\\accProb(y)^m}{q^{m - 1}} -  \\accProb(y) \\cdot \\left(1 -\n  \\frac{h!}{(h - m)! \\cdot h^{m}}\\right)} \\label{eq:use_eq1}\\\\\n\t& \\geq \\frac{\\expected{\\accProb(y)}^m}{q^{m - 1}} -\n\t\\expected{\\accProb(y)} \\cdot \\left(1 - \\frac{h!}{(h - m)! \\cdot\n  h^{m}}\\right) \\label{eq:by_lemma_jensen}\\\\\n\t& = \\frac{\\accProb^m}{q^{m - 1}} -  \\accProb \\cdot \\left(1 -\n  \\frac{h!}{(h - m)! \\cdot h^{m}}\\right)\\label{eq:by_accProb}\\,.\n\\end{align}\nWhere \\cref{eq:use_eq1} comes from \\cref{eq:frkProb_y};\n\\cref{eq:by_lemma_jensen} comes from linearity of expected value and \\cref{lem:jensen}; and\n\\cref{eq:by_accProb} holds by the fact that $\\expected{\\accProb(y)} =\n\\accProb$.\n\nWe now show \\cref{eq:frkProb_y}.\nDenote by $J = \\range{1}{m}^2 \\setminus \\smallset{(j, j)}_{j \\in \\range{1}{m}}$. \nFor any input $y$, with probabilities taken over the coin tosses of\n$\\genforking_{\\zdv}^{m}$ we have\n\\begin{align*}\n\t\\frkProb (y) & = \\prob{i_j = i_{j'} \\land i_j \\geq 1 \\land\nh_{i_j}^{j} \\neq h_{i_{j'}}^{j'} \\text{ for } (j, j') \\in J}\t\\\\\n\t& \\geq \\prob{i_j = i_{j'} \\land i_j \\geq 1 \\text{ for } (j, j') \\in J} %\\\\\n   - \\prob{i_j \\geq 1 \\land h_{i_j}^{j} = h_{i_{j'}}^{j'} \\text{ for some } (j, j') \\in J}\\\\\n\t& = \\prob{i_j = i_{j'} \\land i_j \\geq 1 \\text{ for } (j, j') \\in J} -\n\t\\prob{i_j \\geq 1} \\cdot \n  \\left(1 - \\frac{h!}{(h - m)! \\cdot h^{m}}\\right) \\\\ \n\t& = \\prob{i_j = i_{j'} \\land\n\ti_j \\geq 1 \\text{ for } (j, j') \\in J} - \\accProb(y) \\cdot \\left(1 -\n\\frac{h!}{(h - m)! \\cdot h^{m}}\\right)\\,.\n\\end{align*}\n\nProbability that for some $(j, j') \\in J$ and $i_j = i_{j'}$ holds\n$h_{i_j}^{j} \\neq h_{i_{j'}}^{j'}$ equals \n\\[\n  \\frac{h \\cdot (h - 1)\n\\cdot \\ldots \\cdot (h - m - 1)}{h^m} = \\frac{h!}{(h - m)! \\cdot h^m}.\n\\]\nThat is, it equals the number\nof all $m$-element strings where each element is different divided by\nthe number of all $m$-element strings, where elements are taken from a\nset of size $h$. \n\nIt remains to show that $\\prob{i_j = i_{j'} \\land i_j \\geq 1 \\text{ for } (j,\n  j') \\in J} \\geq \\infrac{\\accProb(y)^m}{q^{m - 1}}$. Let $\\RND{\\zdv}$ denote\nthe set from which $\\zdv$ picks its coins at random. For each $\\iota \\in\n\\range{1}{q}$ let $X_\\iota \\colon \\RND{\\zdv} \\times H^{\\iota - 1} \\to [0, 1]$ be\ndefined by setting $X_\\iota(\\rho, h_1, \\ldots, h_{\\iota - 1})$ to\n\\[\n  \\condprob{i = \\iota}{h_\\iota, \\ldots, h_q \\sample H; (i, s) \\gets \\zdv(y, h_1,\n    \\ldots, h_q; \\rho)}\n\\]\nfor all $\\rho \\in \\RND{\\zdv}$ and $h_1, \\ldots, h_{\\iota - 1} \\in H$. Consider\n$X_\\iota$ be a random variable over the uniform distribution on its domain. Then\n\\begin{align*}\n\t& \\prob{i_j = i_{j'} \\land i_j \\geq 1 \\text{ for } (j, j') \\in J} \n\t = \\sum_{\\iota = 1}^{q} \\prob{i_1 = \\iota \\land \\ldots \\land i_m = \\iota} \\\\\n\t& = \\sum_{\\iota = 1}^{q} \\prob{i_1 = \\iota} \\cdot \\condprob{i_2 = \\iota}{i_1 = \\iota} \\cdot \\ldots \\cdot \\condprob{i_m = \\iota}{i_1 = \\ldots = i_{m - 1} = \\iota} \\\\\n\t& = \\sum_{\\iota = 1}^{q} \\sum_{\\rho, h_1, \\ldots, h_{\\iota - 1}} X_{\\iota}\n   (\\rho, h_1, \\ldots, h_{\\iota - 1})^{m} \\cdot \\frac{1}{\\abs{\\RND{\\zdv}} \\cdot \\abs{H}^{\\iota - 1}}\n   = \\sum_{\\iota = 1}^{q} \\expected{X_\\iota^m} \\,.\n\\end{align*}\nImportantly, $\\sum_{\\iota = 1}^q \\expected{X_{\\iota}} = \\accProb(y)$.\n\nBy \\cref{lem:jensen} we get\n\\[\n\t\\sum_{\\iota = 1}^{q} \\expected{X_\\iota^m} \\geq \\sum_{\\iota = 1}^{q} \\expected{X_\\iota}^m\\,.\n\\]\nNote that for e.g.~$X_i = 1$, $i \\in \\range{1}{q}$ the inequality becomes equality, that is, it is tight.\n \nWe now use the H\\\"older inequality, cf.~\\cref{lem:holder}, for $x_i = \\expected{X_i}$, $y_i = 1$, $p = m$, and $q = m/(m - 1)$ obtaining\n\\begin{gather}\n\t\\left(\\sum_{i = 1}^{q} \\expected{X_i}\\right)^{m}  \\leq \\left(\\sum_{i = 1}^{q} \\expected{X_i}^m\\right) \\cdot q^{m - 1}\\\\\n\t\\frac{1}{q^{m - 1}} \\cdot \\accProb(y)^{m} \\leq \\sum_{i = 1}^{q} \\expected{X_i}^m\\,.\n\\end{gather}\nFinally, we get\n\\[\n\t\\frkProb(y) \\geq \\frac{\\accProb(y)^m}{q^{m - 1}} - \n\t \\accProb(y) \\cdot \\left(1 - \\frac{h!}{(h - m)! \\cdot h^m}\\right)\\,.\n\\]\n\\qed\n\\end{proof}\n\\begin{lemma}\\label{lem:jensen}\n\tLet $\\RND{\\zdv}$ denote the set from which $\\zdv$ picks its coins at random.\n\tFor each $\\iota \\in \\range{1}{q}$ let $X_\\iota \\colon \\RND{\\zdv} \\times\n\tH^{\\iota - 1} \\to [0, 1]$ be defined by setting $X_\\iota(\\rho, h_1, \\ldots,\nh_{\\iota - 1})$ to \n\\[\n  \\condprob{i = \\iota}{h_\\iota, \\ldots, h_q \\sample H; (i, s) \\gets \\zdv(y, h_1,\n    \\ldots, h_q; \\rho)}\n\t\\] \n\tfor all $\\rho \\in \\RND{\\zdv}$ and $h_1, \\ldots, h_{\\iota - 1} \\in H$. Consider\n  $X_\\iota$ as a random variable over the uniform distribution on its domain.\n  Then $\\expected{X_\\iota^m} \\geq \\expected{X_\\iota}^m$.\n\\end{lemma}\n\\begin{proof}\n\tFirst we recall the Jensen inequality \\cite{W:Weissten20}, if for some random\n  variable $X$ holds $\\abs{\\expected{X}} \\leq \\infty$ and $f$ is a Borel convex\n  function then\n\t\\[\n\t\tf(\\expected{X}) \\leq \\expected{f(X)}\\,.\n\t\\] \n\tFinally, we note that $\\abs{\\expected{X}} \\leq \\infty$ and taking to the\n  $m$-th power is a Borel convex function on $[0, 1]$ interval. \\qed\n\\end{proof}\n\n\\begin{lemma}[H\\\"older's inequality. Simplified.]\\label{lem:holder}\n\tLet $x_i, y_i$, for $i \\in \\range{1}{q}$, and $p, q$ be real numbers such that\n  $1/p + 1/q = 1$. Then\n\t\\begin{equation}\n    \\label{eq:tightness}\n\t\t\\sum_{i = 1}^{q} x_i y_i \\leq \\left(\\sum_{i = 1}^{q}\n      x_i^p\\right)^{\\frac{1}{p}} \\cdot \\left(\\sum_{i = 1}^{q}\n      y_i^p\\right)^{\\frac{1}{q}}\\,.\n\t\\end{equation}\n\\end{lemma}\n\n\\begin{remark}[Tightness of the H\\\"older inequality]\n\tIn is important to note that Inequality (\\ref{eq:tightness}) is tight. More\n  precisely, for $\\expected{X_i} = x$, $i \\in \\range{1}{q}$ we have\n\t\\begin{gather*}\n\t\t\\sum_{i = 1}^q x = \\left(\\sum_{i = 1}^{q} x^m\\right)^\\frac{1}{m} \\cdot \\left(\\sum_{i = 1}^{q} 1^{\\frac{m}{m - 1}}\\right)^{\\frac{m - 1}{m}} \\\\\n\t\tqx = \\left(qx^m\\right)^\\frac{1}{m} \\cdot q^{\\frac{m - 1}{m}} \\\\\n\t\t(qx)^m = qx^m \\cdot q^{m - 1} \\\\\n\t\t(qx)^m = (qx)^m\\,.\n\t\\end{gather*}\n\\end{remark}\n\n\\begin{lemma}\n  \\label{lem:root_prob}\n  Let $\\p{f}(X)$ be a random degree-$d$ polynomial over $\\FF_p[X]$. Then the\n  probability that $\\p{f}(X)$ has roots in $\\FF_p$ is at least $\\infrac{1}{d!}$.\n\\end{lemma}\n\\begin{proof}\n  First observe that there is $p^{d}$ canonical polynomials in $\\FF_p[X]$.  Each\n  of the polynomials may have up to $d$ roots. Consider polynomials which are\n  reducible to polynomials of degree $1$, i.e.~polynomials that have all $d$\n  roots. The roots can be picked in $\\bar{C}^{p}_{d}$ ways, where\n  $\\bar{C}^{n}_{k}$ is the number of $k$-elements combinations with repetitions\n  from $n$-element set. That is,\n  \\[\n    \\bar{C}^n_k = \\binom{n + k - 1}{k}\\,.\n  \\]\n  Thus, the probability that a randomly picked polynomial has all $d$ roots is\n  \\begin{multline*}\n    p^{-d} \\cdot \\bar{C}^p_d = p^{-d} \\cdot \\binom{p + d - 1}{d} =\n    p^{-d} \\cdot \\frac{(p + d - 1)!}{(p + d - 1 - d)! \\cdot d!} = \\\\\n    p^{-d} \\cdot \\frac{(p + d - 1) \\cdot \\ldots \\cdot p \\cdot (p - 1)!}{(p - 1)!\n      \\cdot d!} = p^{-d} \\cdot \\frac{(p + d - 1)\\cdot\n      \\ldots \\cdot p}{d!} \\\\\n    \\geq p^{-d} \\cdot {\\frac{p^d}{d!}} = \\frac{1}{d!}\n  \\end{multline*}\n  \\qed\n\\end{proof}\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: \"main\"\n%%% End:\n", "meta": {"hexsha": "eb1d075bb3a75262604eb5d8312c234e51178153", "size": 27246, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ECsubmission/110-additional-preliminaries-lemmas-and-proofs.tex", "max_stars_repo_name": "clearmatics/research-plonkext", "max_stars_repo_head_hexsha": "7da7fa2b6aa17142ef8393ace6aa532f3cfd12b4", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ECsubmission/110-additional-preliminaries-lemmas-and-proofs.tex", "max_issues_repo_name": "clearmatics/research-plonkext", "max_issues_repo_head_hexsha": "7da7fa2b6aa17142ef8393ace6aa532f3cfd12b4", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ECsubmission/110-additional-preliminaries-lemmas-and-proofs.tex", "max_forks_repo_name": "clearmatics/research-plonkext", "max_forks_repo_head_hexsha": "7da7fa2b6aa17142ef8393ace6aa532f3cfd12b4", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.1796610169, "max_line_length": 307, "alphanum_fraction": 0.6233208544, "num_tokens": 10753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.309469078594525}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\section{Post-Newtonian formalism}\n\n\\marginpar{Monday\\\\ 2021-6-21, \\\\ compiled \\\\ \\today}\n\nWe know that the scaling of the perturbation is typically \n%\n\\begin{align}\nh \\sim \\frac{R}{D} \\frac{GM}{c^2 R} \\qty( \\frac{v}{c})^2\n\\,.\n\\end{align}\n\nThe assumptions for this linearized gravity quadrupole formula are: \n\\begin{enumerate}\n    \\item fixed background;\n    \\item \\(v\\) is small;\n    \\item background and source are independent (this is true for non-selfgravitating sources).\n\\end{enumerate}\n\nHowever: this formula tells us that the most significant sources of GW are indeed self-gravitating, and not described by it! \n\nSo, how do we move forward, and get a formalism for compactness \\(GM / c^2R\\) approaching \\(1/2\\), such as BHs or NSs?\n\nA strongly self-gravitating source will also typically have high velocity, because of the virial theorem: \n%\n\\begin{align}\n\\qty( \\frac{v}{c})^2 \\sim \\frac{2GM}{c^2 R} = \\frac{R_s}{R}\n\\,.\n\\end{align}\n\n\nThe ``background'' for a strongly self-gravitating source is dependent on the source! It is not really a background. \n\nThe idea behind the PN formalism is to iteratively solve the Einstein equations, as an expansion in powers of \\(\\epsilon = v/c\\). \n\nWe will still refer to sources with \\emph{compact support} \\(r<R\\), and assume that \\(T^{00} \\) is the dominant component: \\(\\abs{T^{00} / T^{0i}} = \\order{\\epsilon }\\) and \\(\\abs{T^{00 } / T^{ij}} = \\order{\\epsilon^2}\\). \n\nThe expansion to order \\(\\order{\\epsilon^{2n}} = \\order{ (v/c)^{2n}}\\) is called the \\(n\\)-PN order expansion.\n\nSo we can talk about 1PN, 1.5 PN, 2.5PN and so on.\n\nA \\emph{historical remark}: the PN formalism started with Einstein; Landau and Lifshitz already included it in their book, also De Sitter and Chandrasekhar worked on it.\n\nEinsten-Infeld-Hoffmann developed the 1PN Lagrangian for the motion of \\(N\\) particles. \nPeter and Hathews (1963). \n\nThe formalism was really nailed down systematically by Blanchet and Damour. \nAlso, Will and Wisemann worked on it in the 90s. \n\nNaîvely, we'd work as such: calculate the motion to \\(\\epsilon^n\\), and then use linear theory to calculate the GWs emitted.\nThis is wrong: the background is nontrivial, there is a complicated dependence through the Einstein equations. \n\nWE emission subtracts energy to the motion, and GWs at a certain PN order are sources of GW at higher orders through the Isaacson tensor. \n\nThe equation \\(\\dv*{E}{t} = P_{gw}\\) is an ansatz: this is used but it not guaranteed to hold at each PN order. \n\nLet us start with the metric at 1PN order: \n%\n\\begin{align}\ng_{00} &= - 1 - 2\\phi = - 1 + \\frac{2 U}{c^2}  \\\\\ng_{0i} &= 0  \\\\\ng_{ij} &= \\delta_{ij}\n\\,,\n\\end{align}\n%\nwhere \\(U\\) is the solution to the Newtonian Poisson equation: \n%\n\\begin{align}\nU &= \\frac{G}{c^2} \\int \\dd[3]{y} \\frac{T^{00} (y)}{\\abs{x-y}}\n\\,.\n\\end{align}\n\nNow, we have seen that different components of \\(T_{\\mu \\nu }\\) have different orders of \\(c\\), so different metric coefficients must be expanded up to different powers, determined by how they appear in the EFE. \n\nIf \\(g_{00} \\) is expanded to order \\(\\epsilon^n\\), then \\(g_{0i} \\) must be expanded to order \\(\\epsilon^{n-1}\\) because it has a power \\(\\epsilon \\) intrinsically in it, and similarly \\(g_{ij} \\) must be expanded to the power \\(\\epsilon^{n-2}\\).\n\n\\todo[inline]{Understand this better. Look at Maggiore. }\n\nIn terms of time reversal symmetry, \\(g_{00}\\) and \\(g_{ij}\\) are even while \\(g_{0i}\\) are odd. \n\n\\begin{figure}\n\\centering\n\\begin{tabular}{c|ccc}\nComponent & Newton (0PN) & 1PN & 2PN \\\\\n\\hline\n\\(g_{00} \\) & \\(-1 + g_{00}^{(2)}\\) & \\(g_{00}^{(4)}\\) & \\(g_{00}^{(6)}\\) \\\\\n\\(g_{0i}\\) & 0 & \\(g_{0i}^{(3)}\\) & \\(g_{0i}^{(5)}\\) \\\\\n\\(g_{ij}\\) & \\(\\delta_{ij}\\) & \\(g_{ij}^{(2)}\\) & \\(g_{ij}^{(4)}\\) \n\\end{tabular}\n\\label{tab:PN-orders}\n\\caption{}\n\\end{figure}\n\nThis is correct up to when we must include radiation reaction, but it turns out that that comes in at 2.5PN order. \n\nSo, in order to write the metric at 1PN order, we can match the EFE at each order taking into account the power counting. \n\nDerivatives have orders \\(\\partial_{t} = \\order{v} \\partial_{i}\\), while \n%\n\\begin{align}\n- \\frac{1}{c^2} \\partial_{tt} + \\triangle = \\qty[1 + \\order{\\epsilon }] \\triangle  \n\\,,\n\\end{align}\n%\ntherefore the retardation effects are ``higher order''. \n\nTherefore, the lowest PN solutions are typically given in terms of \\emph{instantaneous potentials} (solution of Poisson equations).\n\nThis is expected: the PN expansion reads \n%\n\\begin{align}\nF(n) = F( t - \\frac{r}{c}) = F(t) - \\frac{r}{c} \\dot{F} (t) + \\frac{r^2}{2 c^2} \\ddot{F}( t) + \\dots \n\\,.\n\\end{align}\n\nIn Fourier terms: \n%\n\\begin{align}\n\\widetilde{F} &\\approx \\widetilde{F} \\qty(1 - \\frac{r \\omega }{c} + \\frac{r^2\\omega^2}{c^2} + \\dots)  \\\\\n&= \\widetilde{F} \\qty(1 - \\frac{r}{\\lambda } - \\frac{r^2}{2 \\lambda^2})\n\\,.\n\\end{align}\n%\n\\todo[inline]{the lambdas are barred --- characteristic length.}\n\nThis means that this is also an expansion for nearby fields: the expansion is in small velocities \\(\\epsilon = v/c \\ll 1\\), as well as in the \\emph{near-zone} \\(r / \\lambda  \\ll 1\\). \n\nTherefore, the PN expansion is \\textbf{not valid to compute GWs far away from the source}! \n\nLet us define a \\textbf{near zone} \\(r \\ll L\\), but \\(L \\gg R\\), such that \\(r / \\lambda \\ll 1\\), such that the aforementioned expansion makes sense. \n\nWe also have a \\textbf{far zone} \\(R < r < \\infty \\), and an \\textbf{overlap zone} \\(R < r < L\\) in which the near and far zones overlap. \n\nBack to the 1PN metric: we impose Harmonic gauge, so that \\(\\partial_{\\mu } \\qty(\\sqrt{-g} g^{\\mu \\nu }) = 0\\), and we start from the 0PN equation \\(\\triangle U = - (8 \\pi G/c^{4}) T^{00}_{(0)}\\). \nThen, to 1PN order we get: \n%\n\\begin{align}\n\\triangle g_{ij}^{(2)} &= - \\frac{8\\pi G}{c^{4}} \\delta_{ij} T^{00}_{(0)}  \\\\\n\\triangle g_{0i}^{(3)} &= \\frac{16 \\pi G}{c^{4}} T^{0i}_{(1)}  \\\\\n\\triangle g_{00}^{(4)} &= \\dots\n\\,,\n\\end{align}\n%\nso, assuming that \\(T^{\\mu \\nu }\\) is known, these can be solved in terms of Green's functions. \nAfter all the calculations one finds \n%\n\\begin{align}\n\\square_\\eta V &= - \\frac{4 \\pi G}{c^{4}} \\underbrace{\\qty(T^{00} + T^{ii})}_{\\mathclap{\\text{active gravitational mass density}}}  \\\\\n\\square_\\eta V^{i} &= \\dots\n\\,,\n\\end{align}\n%\nwhere we have  the 1PN potential \\(V\\) which defines the metric: \n%\n\\begin{align}\ng_{00} &= -1 + \\frac{2U}{c^2} + \\frac{2 V^2}{c^{4}}  \\\\\ng_{0i} &= - \\frac{4 V_{i}}{c^3}  \\\\\ng_{ij} &= \\delta_{ij} \\qty(1 + \\frac{2 V}{c^2})\n\\,.\n\\end{align}\n\nThe Einstein-Infeld-Hoffmann Lagrangian is the \\(N\\)-particle one for this metric: the corresponding stress-energy tensor is\n%\n\\begin{align}\nT^{\\mu \\nu } = \\frac{1}{\\sqrt{-g}} \\sum _a \\dv{\\tau_a}{t} m_a \\dv{x_a^{\\mu }}{t} \\dv{x^{\\nu }_a}{t} \\delta (x - x_a)\n\\,.\n\\end{align}\n\nThe action reads \n%\n\\begin{align}\nS = - mc^2 \\int \\dd{t} \\sqrt{- g_{00} -2 g_{0i} \\frac{v^{i}}{c} - g_{ij} \\frac{v^{i} v^{j}}{c^2}} \n\\,.\n\\end{align}\n\nThis can be written as \\(L= L _{\\text{Newt}} + L_{1PN}\\). \n\nIf one takes \\(N = 1\\) they get the two-body problem, the EOM for a relativistic binary at 1PN order. \nThis solution can be mapped to a Newtonian problem and solved: this has been done by Damour and Deruelle in 86, which is important since it was applied to the Hulse-Taylor pulsar: the equation they found was \n%\n\\begin{align}\n\\expval{\\dot{\\omega}} = \\num{2.11353} \\qty(\\frac{m_1 + m_2 }{M_{\\odot}})^{2/3} \\SI{}{deg / yr}\n\\,.\n\\end{align}\n\nThe orbital decay has been observed very accurately, which can be a way to determine the binary mass. \n\nWhat are the difficulties? We get Poisson equations in the form \n%\n\\begin{align}\n\\triangle g_{\\mu \\nu }^{(n)} = \\text{matter source} + \\text{metric source } g_{\\mu \\nu }^{(n-1)}\n\\,.\n\\end{align}\n\nThe second term does not have compact support! The Poisson integrals used so far are not good solutions. \nWe need different boundary conditions. \n\nFor example, consider \\(\\triangle u = \\rho = \\const\\). The Poisson integral is not a solution since \\(u \\neq 0\\) at infinity: it diverges.\n\nHowever, a solution exists: \\(u(r) = - (1/6) \\rho r^2\\). We need other formal solutions to the Poisson equation. \n\nHow is this solved? We do it by inverting the Poisson equation with boundary conditions by a suitable procedure which involves regularization of the divergences and analytic continuation. \nWe will not explore this in detail, but it is good to know that the problem exists. \n\nAnother difficulty is the following: \nthe PN expansion of the metric potential is valid in the near zone but it blows up for large \\(r \\to \\infty \\).\nIt is in the form \n%\n\\begin{align}\nF (\\epsilon , r) = \\sum _{n} c_n (r) \\epsilon^n\n\\,.\n\\end{align}\n\nThis is an expansion with two scales, and the series is \\emph{not} uniformly convergent. This is analogous to perturbation theory in quantum mechanics: asymptotic series. \n\nThe residuals eventually blow up, but there is an optimum \\(n\\) for the expansion. \nThe solution is to perform a post-Minkowskian expansion in the far zone: \n%\n\\begin{align}\nF = \\sum _{n} G^{n} F_n\n\\,,\n\\end{align}\n%\nand match the PN expansion in the near zone. \n\nAlso, there is the problem of \\textbf{backreaction}, GW influence on the motion. \nThis breaks the power-counting. \n\nWhen does it enter the game? We know that \n%\n\\begin{align}\nE = K + V \\approx - \\frac{V}{2} + V = \\frac{V}{2} = - K = - \\frac{M}{2} v^2\n\\,,\n\\end{align}\n%\ntherefore \\(\\dot{E} \\sim - M v \\dot{v}\\). \n\nFurther, we know that \n%\n\\begin{align}\nP_{gw} = \\dot{E}_{gw} \\approx \\frac{GM^2}{c^{5}} \\frac{v^{6}}{r}\n\\,,\n\\end{align}\n%\ntherefore \n%\n\\begin{align}\n\\dot{v} \\approx \\frac{GM}{r^2} \\qty( \\frac{v}{c} )^{5}\n\\,,\n\\end{align}\n%\nwhich gives the correct order of 5, meaning 2.5PN. \n\nWhat are the \\textbf{Relaxed EFE}? \nWe define \n%\n\\begin{align}\n\\mathfrak{h}^{\\mu \\nu  } = \\sqrt{-g } g^{\\mu \\nu } -\\eta^{\\mu \\nu }\n\\,,\n\\end{align}\n%\na  new field in the full theory. \nWe then rewrite the EFE in terms of it, using the gauge \\(\\partial_{\\mu } \\mathfrak{h}^{\\mu \\nu} = 0\\) (equivalent to harmonic gauge). \n\nThe EFE then read \n%\n\\begin{align}\n\\square \\mathfrak{h}^{\\mu \\nu } &= \\frac{16 \\pi G}{c^{4}} \\tau^{\\mu \\nu }  \\\\\n&= \\frac{16 \\pi G}{c^{4}} \\qty[-g T^{\\mu \\nu } + \\tau^{\\mu \\nu }_{u} + \\tau^{\\mu  \\nu }[ \\mathfrak{h}^{\\alpha \\beta }]]\n\\,,\n\\end{align}\n%\nwhere \\(\\tau_u \\) is the Landau-Liftschitz pseudotensor. \nThese are formally similar to the linearized equations, and in the weak-field limit \\(\\mathfrak{h}^{\\mu \\nu } = - \\overline{h}^{\\mu \\nu }\\). \n\nAll the nonlinearity is still there though, this makes no approximations: they are just made to look that way. \n\nThis \\(\\tau \\) satisfies \\(\\partial_{\\mu } \\tau^{\\mu \\nu } = 0\\) (notice the flat derivative). \nAlso, these are called ``relaxed'' because a solution of the relaxed equations alone does not imply the conservation of \\(\\tau^{\\mu \\nu }\\): one needs to add the gauge. \n\nThe formal solution of these REFE is \n%\n\\begin{align}\n\\mathfrak{h}^{\\mu \\nu } = - \\frac{4G}{c^2} \\int \\dd[3]{y} \n\\frac{\\tau^{\\mu \\nu }(t - \\abs{x-y} / c, y)}{\\abs{x-y}}\n\\,,\n\\end{align}\n%\nbut we do not truly know \\(\\tau \\); however we can solve this iteratively. \n\nWe start by finding a solution for the REFE in the far region with the multipolar formula: \n%\n\\begin{align}\n\\mathfrak{h}^{\\mu \\nu } = \\sum _{n} \\mathfrak{h}_{(n)}^{\\mu \\nu } G^{n}\n\\,,\n\\end{align}\n%\nthere for \\(r > R\\) we have the unspecified source multipole moments \\(\\mathfrak{h}^{\\mu \\nu }_{(n)}\\). \n\nThen we find a solution for the REFE in the near zone: \n%\n\\begin{align}\n\\mathfrak{h}^{\\mu \\nu } = \\sum _{n } \\frac{1}{c^{n}} \\mathfrak{h}^{\\mu \\nu }_{(n)}\n\\,.\n\\end{align}\n\nHere, for \\(r < L\\), we have \\(^{(n)} \\mathfrak{h}^{\\mu \\nu }\\), multipoles of \\(\\tau^{\\mu \\nu }\\). \nWe match the two in the overlapping zone to determine \\(\\tau\\). \n\nFinally, we compute the TT solution far away, with a gauge transformation from harmonic to radiative coordinates: from \\((I_L, J_L, W_L, \\dots)\\) to \\((U_L,V_L)\\), the radiative multipoles of \\(h_{ij}^{TT}\\).\n\nThe good thing is that this can all be done with a finite amount of terms, however in general one does not know how far the expansion can be pushed.  \n\n\\todo[inline]{What does the overlap region look like?}\n\n\n\n\\end{document}\n", "meta": {"hexsha": "f710ec34b1f73130c634b27bc6c628cd706fcee2", "size": 12190, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "phd_courses/gravitational_waves/jun21.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "phd_courses/gravitational_waves/jun21.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phd_courses/gravitational_waves/jun21.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 37.9750778816, "max_line_length": 247, "alphanum_fraction": 0.6605414274, "num_tokens": 4101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.3094690712196819}}
{"text": "\\documentclass[12pt]{paper}\n\\usepackage{geometry}                % See geometry.pdf to learn the layout options. There are lots.\n\\geometry{letterpaper}                   % ... or a4paper or a5paper or ... \n%\\geometry{landscape}                % Activate for for rotated page geometry\n%\\usepackage[parfill]{parskip}    % Activate to begin paragraphs with an empty line rather than an indent\n\\usepackage{graphicx}\n\\usepackage{amssymb}\n\\usepackage{epstopdf}\n\\usepackage{hyperref}\n\\usepackage{natbib}\n\\DeclareGraphicsRule{.tif}{png}{.png}{`convert #1 `dirname #1`/`basename #1 .tif`.png}\n\n\\newcommand{\\aap}{{\\it A\\&A}}\n%\\newcommand{\\aaps}{{\\it A\\&AS}}\n\\newcommand{\\aj}{{\\it AJ}}\n\\newcommand{\\apj}{{\\it ApJ}}\n\\newcommand{\\apjl}{{\\it ApJL}}\n\\newcommand{\\mnras}{{\\it MNRAS}}\n\\newcommand{\\pasp}{{\\it PASP}}\n\n\\title{Stellar Structure and Evolution Numerical Project}\n\\author{Samuel Factor}\n%\\date{}                                           % Activate to display a given date or no date\n\n\\begin{document}\n\\maketitle\n%\\section{}\n%\\subsection{}\n\nCode for this project can be found at \\\\\n\\url{https://github.com/sfxfactor/StellarNumericalProj}.\n\n\\section{ZAMS and Starting Model}\nFigure \\ref{fig:fig1} is a reproduction of Figure 1 of \\citet{BKL}. As I used the assumptions in the paper, and not real models, the curves are strait and not curved as in \\citet{BKL}. I used two prescriptions for the effective temperature to see if it would bring the curves into better agreement with the curves in \\citet{BKL}. One prescription was from Equation 6 of \\citet{BKL} and the other was from the Eddington luminosity,\n\\begin{equation}\\label{eq:tedd}\nT_{eff}=\\left(\\frac{L_{edd}}{4\\pi R^2 \\sigma_{SB}}\\right)^{1/4}.\n\\end{equation}\n\n\n\\begin{figure}\n\\begin{center}\n    \\includegraphics[width=0.6\\textwidth]{fig1.pdf}\n    \\caption{HR Diagram for high mass ($M=100-1000~M_\\odot$ in increments of $100~M_\\odot$) Pop III (left) and Pop I (right) stars. Different curves correspond to temperatures given by Equation 6 of \\citet{BKL} and the Eddington luminosity, Equation \\ref{eq:tedd}. }\n    \\label{fig:fig1}\n\\end{center}\n\\end{figure}\n\nUsing my code from Problem Set 2, I generated an $n=3$ polytropic model of a $100M_\\odot$ Pop III star. The pressure and density structure is shown in Figures \\ref{fig:pm} and \\ref{fig:dm} respectively. To calculate a temperature I assumed $\\beta=0.58$. This value comes from Equation 19.56 in KW$^2$ \n\\begin{equation}\\label{eq:beta}\n\\frac{1-\\beta}{\\mu^4\\beta^4}=3.02\\times10^-3\\left(\\frac{M}{M_\\odot}\\right)^2.\n\\end{equation}\nThe temperature is then \n\\begin{equation}\\label{eq:temp}\nT=\\left((1-\\beta)P\\frac{3}{a}\\right)^{1/4}\n\\end{equation}\nThis produces the temperature structure shown in Figure \\ref{fig:tm}.\n\n\\begin{figure}\n\\begin{center}\n    \\includegraphics[width=0.6\\textwidth]{pressure3p0.pdf}\n    \\caption{Pressure as a function of enclosed mass for an $n=3$ polytropic model of a $100~M_\\odot$ Pop III star.}\n    \\label{fig:pm}\n\\end{center}\n\\end{figure}\n\n\\begin{figure}\n\\begin{center}\n    \\includegraphics[width=0.6\\textwidth]{density3p0.pdf}\n    \\caption{Density as a function of enclosed mass for an $n=3$ polytropic model of a $100~M_\\odot$ Pop III star.}\n    \\label{fig:dm}\n\\end{center}\n\\end{figure}\n\n\\begin{figure}\n\\begin{center}\n    \\includegraphics[width=0.6\\textwidth]{temperature3p0.pdf}\n    \\caption{Temperature as a function of enclosed mass for an $n=3$ polytropic model of a $100~M_\\odot$ Pop III star.}\n    \\label{fig:tm}\n\\end{center}\n\\end{figure}\n\n\\section{Evolving off the MS}\nI worked together brielfy with Brianna and Ben on this part. \n\nI tried very hard to get the \\texttt{STELLAR} code to work with a $100~M_\\odot$ Pop III (metal free) star though was unsuccessful. You can see my commit history on GitHub to look at the specific changes I tried, but I will outline the important ones below. To see the specific changes I made, go to the link at the begining of this text and click on ``commits\" in the top left. You can then click on each commit individually and GitHub will highlight the changes made. If you would rather I attach to this document a copy of the code with changes highlighted send me an email and I can do that. \n\nFirst, the initial conditions and polytropic index (in \\texttt{polytr.inp}, \\texttt{pmsstar.start}, \\texttt{and pmsstar.inp}) and polytrope constants (in \\texttt{polytr.F}) must be changed to match the $n=3$ $100~M_\\odot$ metal free star we wish to model. I then changed the pressure prescription in \\texttt{invstate.F} to fix $\\beta$ at the value mentioned above (see Equation \\ref{eq:beta}. Second I replaced all calls to \\texttt{opacity} in \\texttt{gi.F} with Thompson scattering opacity $0.2(1+X)$. In \\texttt{atmos.F} I did the same thing but added H$^-$ opacity, $(1-X-Y)\\rho^{1/2}T^9$. This was of course added in inverse according to $1/\\kappa=1/\\kappa_T+1/\\kappa_{H^-}$. Finally I changed the luminosity prescription in \\texttt{polytr.F} to Equation 3 of \\citet{BKL}. \n\nWhen looking at the output of the failed stellar run I noticed that the energy generation predicted by the code from the CNO cycle was much too small ($\\sim 10^7$ erg/s when the luminosity is $\\sim10^{40}$). If this could be brought up the model may have converged. I probably could have changed this part of the code to simply use Equation 3 of \\citet{BKL} but that may have effected the chemical evoultion.\n\nIf the 100 $M_\\odot$ Pop III star would have evolved past the MS, the model would not have been able to model the pulsations caused by pair instability. This causes the rapid burning of oxygen and silicon, stopping the collapse with an enormous explosion. For stars $\\sim 140-260 M_\\odot$ \\citep{pop3}this completely disrupts the star leaving behind no remnent. For masses less than this but greater than $\\sim 100 M_\\odot$ the pulsations throw off large amounts of mass while the core collapses into a black hole. This is what would probably happen to the star we are modeling.\n\nSince I could not get the $100~M+\\odot$ Pop III star to work, I modeled a few solar metalicity stars and tried to push their mass up as high as I could. Shown in Figure \\ref{fig:HR} are evolution tracks for 1, 3, 4, 5, and 10 $M_\\odot$ solar metalicity stars. You will notice that the 5 and 10 $M_\\odot$ models fail when they reach the MS. The \\texttt{STELLAR} code seems to be very sensitive to the initial $R$ and $T_{eff}$ of the polytrope model. For example, the initial $R$ and $T_{eff}$ of the 3 and 4 $M_\\odot$ (which evolved past the MS) were almost identical. If I changed the 4 $M_\\odot$ initial conditions a small amount, the star would evolve to the MS and the model would fail, much like the 5 and 10 $M_\\odot$ models. \n\n\\begin{figure}\n\\begin{center}\n    \\includegraphics[width=\\textwidth]{HR.pdf}\n    \\caption{Evolutionary tracks for solar metalicity stars. The two highest mass models fail when they reach the MS, while the lower mass models evolve off the MS. }\n    \\label{fig:HR}\n\\end{center}\n\\end{figure}\n\nFigures \\ref{fig:pse}, \\ref{fig:dse}, and \\ref{fig:tse} show the initial and final pressure, density, and temperature structures for the 4 $M_\\odot$ model, the highest mass model that evolved off the MS.\n\n\\begin{figure}\n\\begin{center}\n    \\includegraphics[width=0.6\\textwidth]{pres.pdf}\n    \\caption{Pressure as a function of enclosed mass for a $4~M_\\odot$ Pop I star at the beginning and end of its life.}\n    \\label{fig:pse}\n\\end{center}\n\\end{figure}\n\n\\begin{figure}\n\\begin{center}\n    \\includegraphics[width=0.6\\textwidth]{dens.pdf}\n    \\caption{Density as a function of enclosed mass for a $4~M_\\odot$ Pop I star at the beginning and end of its life.}\n    \\label{fig:dse}\n\\end{center}\n\\end{figure}\n\n\\begin{figure}\n\\begin{center}\n    \\includegraphics[width=0.6\\textwidth]{temp.pdf}\n    \\caption{Temperature as a function of enclosed mass for a $4~M_\\odot$ Pop I star at the beginning and end of its life.}\n    \\label{fig:tse}\n\\end{center}\n\\end{figure}\n\n\\setlength\\bibsep{0pt}\n\\bibliographystyle{apj}\n\\bibliography{sources}\n\\end{document}  \n", "meta": {"hexsha": "6fa23cfa229e800a672be3cf8ddb9450873bed37", "size": 8010, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "TeX/numericalProj.tex", "max_stars_repo_name": "sfxfactor/StellarNumericalProj", "max_stars_repo_head_hexsha": "bece1d2aa7ed54c1670d0c495e3b7923cc9fc3ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TeX/numericalProj.tex", "max_issues_repo_name": "sfxfactor/StellarNumericalProj", "max_issues_repo_head_hexsha": "bece1d2aa7ed54c1670d0c495e3b7923cc9fc3ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TeX/numericalProj.tex", "max_forks_repo_name": "sfxfactor/StellarNumericalProj", "max_forks_repo_head_hexsha": "bece1d2aa7ed54c1670d0c495e3b7923cc9fc3ab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 60.2255639098, "max_line_length": 777, "alphanum_fraction": 0.7328339576, "num_tokens": 2376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.30946907121968187}}
{"text": "% -----------------------------------------------------------------\n% -----------------------------------------------------------------\n\\subsection{Additional figures}\\label{app:6:moreFigures}\n% -----------------------------------------------------------------\n\nWe give here plots showing the mean regret $R_t$ as a function of time, and histograms of the distributions of the final regret $R_T$, for the different problems of our benchmark.\n%\nFigures~\\ref{fig:6:meanRegretPb1} and \\ref{fig:6:histogramRegretPb1} above show that our two proposals are efficient against problem 1, and Figure~\\ref{fig:6:meanRegretPb2} concerns problem 2.\nThen we show similar results for problem 4 in Figure~\\ref{fig:6:meanRegretPb4}.\n\n% % -----------------------------------------------------------------\n% \\begin{figure}[h!]  % [htbp]\n%     \\centering\n%     \\includegraphics[width=1.09\\linewidth]{2-Chapters/6-Chapter/nonstatbandits/figures/SP__K3_T5000_N1000__9_algos_pb1/main_HistogramsRegret_shareX____env1-1_1316297932259102962.pdf}\n%     \\caption{Histograms of the distributions of regret $R_T$ ($T=5000$) for problem 1.}\n%     \\label{fig:6:histogramRegretPb1}\n% \\end{figure}\n\n% -----------------------------------------------------------------\n\\begin{figure}[h!]  % [htbp]\n    \\centering\n    \\includegraphics[width=1.05\\linewidth]{2-Chapters/6-Chapter/nonstatbandits/figures/SP__K3_T5000_N1000__9_algos_pb4/main____env1-1_7471744535647872376.pdf}\n    \\caption[Mean regret as a function of time, $R_t$ for horizon $T = 5000$, for problem 4. We see that after a ``long enough'' stationary interval, the algorithms designed for stationary problems lose track of the best arm, and suffer from linear regret for a long period.]{Mean regret as a function of time, $R_t$ for horizon $T = 5000$, for problem 4. We see that after a ``long enough'' stationary interval, the algorithms designed for stationary problems lose track of the best arm, and suffer from linear regret for a long period (\\eg, Thompson sampling in \\textcolor{gold}{yellow $\\diamond$}).}\n    \\label{fig:6:meanRegretPb4}\n\\end{figure}\n\n% -----------------------------------------------------------------\n\\begin{figure}[h!]  % [htbp]\n    \\centering\n    \\includegraphics[width=1.05\\linewidth]{2-Chapters/6-Chapter/nonstatbandits/figures/SP__K6_T20000_N500__9_algos_pb3/main____env1-1_8638317743626238996.pdf}\n    \\caption{Mean regret as a function of time, $R_t$ for horizon $T = 20000$, for problem 3.}\n    \\label{fig:6:meanRegretPb3}\n\\end{figure}\n\n% -----------------------------------------------------------------\n\\begin{figure}[h!]  % [htbp]\n    \\centering\n    \\includegraphics[width=1.05\\linewidth]{2-Chapters/6-Chapter/nonstatbandits/figures/SP__K5_T100000_N500__9_algos_pb5/main____env1-1_950848333706043320.pdf}\n    \\caption{Mean regret as a function of time, $R_t$ for horizon $T = 100000$, for problem 5.}\n    \\label{fig:6:meanRegretPb5}\n\\end{figure}\n\n\nFor harder problems, like problems 3 and 5, the stationary policy \\klUCB{} can outperform actively adaptive strategies, if the stationary intervals are too short or if the gap between arms are too small.\nIn other words, we illustrate in Figures~\\ref{fig:6:meanRegretPb3} and \\ref{fig:6:meanRegretPb5} that while the actively adaptive strategies can be very efficient when applied to problems that are not too difficult to track, they can become sub-optimal for difficult problems.\n\n\n% ----------------------------------------------------------------------------\n% ----------------------------------------------------------------------------\n\\subsection{Omitted proofs}\\label{proof:6:Conc}\n% ----------------------------------------------------------------------------\n\nThis Appendix gives some proofs omitted in the main text of this chapter.\nThe remaining missing proofs can be found in the article \\cite{Besson2019GLRT}.\n\n\n% % ----------------------------------------------------------------------------\n\\subsubsection{Simplified expression for the GLR statistic}\\label{app:6:GLR_with_kl}\n\n\n% \\begin{smallproof}\n    First, we consider the denominator in the expression of $\\GLR(n)$ \\eqref{eq:6:firstDefGLRT}, that is the $\\sup$ on $\\mu_0$.\n    We have $\\ell(X_1, \\dots, X_n ; \\mu_0) = \\prod\\limits_{i=1}^n \\ell(X_i ; \\mu_0)$ by independence of the observations $X_i$,\n    and $\\ell(X_i ; \\mu_0) = \\mu_0^{X_i} (1-\\mu_0)^{1-X_i}$ for Bernoulli distributions.\n    Therefore, taking the logarithm gives\n    \\begin{align*}\n        \\log \\left[ \\ell(X_1, \\dots, X_n ; \\mu_0) \\right]\n        &= \\sum_{i=1}^n \\log \\left[ \\ell(X_i ; \\mu_0) \\right]\n        = \\sum_{i=1}^n X_i \\log(\\mu_0) + (1-X_i) \\log(1-\\mu_0) \\\\\n        &= \\log(\\mu_0) \\times \\left( \\sum_{i=1}^n X_i \\right) + \\log(1-\\mu_0) \\times \\left( n - \\sum_{i=1}^n X_i \\right) \\\\\n        &= n \\left( \\widehat{\\mu}_{1:n} \\log(\\mu_0) + (1 - \\widehat{\\mu}_{1:n}) \\log(1-\\mu_0) \\right).\n    \\end{align*}\n    %\n    For a constant $a\\in[0,1]$, let $h(x) \\eqdef a \\log(x) + (1-a) \\log(1-x)$ on $(0,1)$,\n    and we are trying to solve $\\sup_{x\\in[0,1]} h(x)$.\n    If $a=0$ or $a=1$, $h$ is maximum at $x=a$.\n    Now if $a\\neq0$, As $h$ is of concave and of class $\\cC^1$, we can just differentiate and find the root of its derivative,\n    $h'(x) = a/x - (1-a)/(1-x)$, so $h'(x) = 0$ if and only if $x=a$.\n    Thus in all cases, $\\sup_{x\\in[0,1]} h(x) = h(a)$.\n    %\n    Here, we have $a = \\widehat{\\mu}_{1:n}$, and thus we solved the $\\sup_{\\mu_0}$ optimization problem found in the denominator of the $\\GLR(n)$ expression.\n    By replacing $\\mu_0 = \\widehat{\\mu}_{1:n}$, we obtained the following (unique) solution,\n    \\begin{equation}\\label{eq:6:solutionPbOpt_for_1n}\n        \\sup_{\\mu_0} \\log \\left[ \\ell(X_1, \\dots, X_n ; \\mu_0) \\right] = n \\left( \\widehat{\\mu}_{1:n} \\log(\\widehat{\\mu}_{1:n}) + (1 - \\widehat{\\mu}_{1:n}) \\log(1-\\widehat{\\mu}_{1:n}) \\right).\n    \\end{equation}\n\n    Now let us consider the nominator of the $\\GLR(n)$ expression, that is the $\\sup$ on $\\mu_0,\\mu_1,\\tau$.\n    We can again work with log-likelihoods, and so we have\n    %\n    \\begin{align*}\n        & \\log \\left[ \\ell(X_1, \\dots, X_n ; \\mu_0,\\mu_1,\\tau) \\right] \\\\\n        &= \\sum_{i=1}^{\\tau} X_i \\log(\\mu_0) + (1-X_i) \\log(1-\\mu_0) + \\sum_{i=\\tau+1}^n X_i \\log(\\mu_1) + (1-X_i) \\log(1-\\mu_1) \\\\\n        &= s \\bigl( \\widehat{\\mu}_{1:s} \\log(\\mu_0) + (1 - \\widehat{\\mu}_{1:s}) \\log(1-\\mu_0) \\bigr) \\\\\n        & \\;\\;\\;\\; + (n-s) \\bigl( \\widehat{\\mu}_{s+1:n} \\log(\\mu_1) + (1 - \\widehat{\\mu}_{s+1:n}) \\log(1-\\mu_1) \\bigr).\n    \\end{align*}\n    Because we solved in \\eqref{eq:6:solutionPbOpt_for_1n} the $\\sup$ for the denominator,\n    we have\n    \\begin{align*}\n        \\GLR(n)\n        % &= \\frac{\\sup\\limits_{\\mu_0,\\mu_1,\\tau < n}\\ell(X_1, \\dots, X_n ; \\mu_0,\\mu_1,\\tau)}{\\sup\\limits_{\\mu_0}\\ell(X_1, \\dots, X_n ; \\mu_0)}, \\\\\n        &= \\frac{\\sup\\limits_{\\mu_0,\\mu_1,\\tau < n}\\ell(X_1, \\dots, X_n ; \\mu_0,\\mu_1,\\tau)}{ \\exp\\left[ n \\left( \\widehat{\\mu}_{1:n} \\log(\\mu_0) + (1 - \\widehat{\\mu}_{1:n}) \\log(1-\\mu_0) \\right) \\right] }, \\\\\n        &= \\sup\\limits_{\\mu_0,\\mu_1,\\tau < n} \\frac{\\ell(X_1, \\dots, X_n ; \\mu_0,\\mu_1,\\tau)}{ \\exp\\left[ n \\left( \\widehat{\\mu}_{1:n} \\log(\\widehat{\\mu}_{1:n}) + (1 - \\widehat{\\mu}_{1:n}) \\log(1-\\widehat{\\mu}_{1:n}) \\right) \\right] }, \\\\\n        &= \\exp \\Bigl[ \\sup\\limits_{\\mu_0,\\mu_1,\\tau < n} \\Bigl[ \\log\\Bigl[ \\frac{\\ell(X_1, \\dots, X_n ; \\mu_0,\\mu_1,\\tau)}{ \\exp\\left[ n \\left( \\widehat{\\mu}_{1:n} \\log(\\widehat{\\mu}_{1:n}) + (1 - \\widehat{\\mu}_{1:n}) \\log(1-\\widehat{\\mu}_{1:n}) \\right) \\right] } \\Bigr] \\Bigr] \\Bigr],\n    \\end{align*}\n    When the last equation comes from the fact that $\\exp$ is increasing.\n    Thus by taking the logarithm of both sides, we obtain\n    \\begin{align*}\n        \\log \\GLR(n)\n        &= \\sup\\limits_{\\mu_0,\\mu_1,\\tau < n} \\Bigl[ \\log\\Bigl[ \\frac{\\ell(X_1, \\dots, X_n ; \\mu_0,\\mu_1,\\tau)}{ \\exp\\left[ n \\left( \\widehat{\\mu}_{1:n} \\log(\\widehat{\\mu}_{1:n}) + (1 - \\widehat{\\mu}_{1:n}) \\log(1-\\widehat{\\mu}_{1:n}) \\right) \\right] } \\Bigr] \\Bigr],  \\\\\n        &= \\sup\\limits_{\\mu_0,\\mu_1, s \\in [n-1]} \\Bigl[\n            s \\bigl( \\widehat{\\mu}_{1:s} \\log(\\mu_0) + (1 - \\widehat{\\mu}_{1:s}) \\log(1-\\mu_0) \\bigr) \\\\\n            & \\hspace{35pt} + (n-s) \\bigl( \\widehat{\\mu}_{s+1:n} \\log(\\mu_1) + (1 - \\widehat{\\mu}_{s+1:n}) \\log(1-\\mu_1) \\bigr) \\\\\n            & \\hspace{35pt} - n \\bigl( \\widehat{\\mu}_{1:n} \\log(\\widehat{\\mu}_{1:n}) + (1 - \\widehat{\\mu}_{1:n}) \\log(1-\\widehat{\\mu}_{1:n}) \\bigr)\n        \\Bigr].\n    \\end{align*}\n    By linearity and independence, we can separate the joint optimization problem on $\\mu_0,\\mu_1,s$ in two optimizations problems for $\\mu_0,s$ and $\\mu_1,s$, that can first be solved explicitly for $\\mu_0$ (resp. $\\mu_1$) and then left to be solved for $s$.\n    By definition, $n \\; \\widehat{\\mu}_{1:n} = \\sum_{i=1}^n X_i = s \\;\\widehat{\\mu}_{1:s} + (n-s) \\;\\widehat{\\mu}_{s+1:n}$, so the right hand side (negative) part involving $\\widehat{\\mu}_{1:n}$ can be distributed in the two left hand side (positive) terms,\n    which are both handled similarly.\n    For instance for $\\mu_0$, we use the same computation as above with the function $h$ to find the optimum:\n    $\\widehat{\\mu}_{1:s} \\log(\\mu_0) + (1 - \\widehat{\\mu}_{1:s}) \\log(1-\\mu_0)$\n    is optimum for $\\mu_0 = \\widehat{\\mu}_{1:s}$.\n    Similarly, the term for $\\mu_1$ gives that $\\sup_{\\mu_1} \\widehat{\\mu}_{s+1:n} \\log(\\mu_1) + (1 - \\widehat{\\mu}_{s+1:n}) \\log(1-\\mu_1)$\n    is attained for $\\mu_1 = \\widehat{\\mu}_{s+1:n}$.\n    Finally, by replacing the two expressions of the solutions for $\\mu_0$ and $\\mu_1$,\n    we obtain\n    \\begin{align*}\n        \\log \\GLR(n)\n        = \\sup\\limits_{s \\in [n-1]} \\Bigl[\n            s \\times \\Bigl(\n                    & \\widehat{\\mu}_{1:s} \\log(\\widehat{\\mu}_{1:s}) + (1 - \\widehat{\\mu}_{1:s}) \\log(1-\\widehat{\\mu}_{1:s}) \\\\\n                    & - \\widehat{\\mu}_{1:s} \\log(\\widehat{\\mu}_{1:n}) + (1 - \\widehat{\\mu}_{1:s}) \\log(1-\\widehat{\\mu}_{1:n})\n            \\Bigr) \\\\\n            + (n-s) \\times \\Bigl(\n                & \\widehat{\\mu}_{s+1:n} \\log(\\widehat{\\mu}_{s+1:n}) + (1 - \\widehat{\\mu}_{s+1:n}) \\log(1-\\widehat{\\mu}_{s+1:n}) \\\\\n                & - \\widehat{\\mu}_{s+1:n} \\log(\\widehat{\\mu}_{1:n}) + (1 - \\widehat{\\mu}_{s+1:n}) \\log(1-\\widehat{\\mu}_{1:n})\n            \\Bigr)\n        \\Bigr].\n    \\end{align*}\n    We conclude by recognizing the expressions of $s \\times \\kl(\\widehat{\\mu}_{1:s}, \\widehat{\\mu}_{1:n})$\n    and $(n-s) \\times \\kl(\\widehat{\\mu}_{s+1:n}, \\widehat{\\mu}_{1:n})$.\n% \\end{smallproof}\n\n\n% % Remember that the Generalized Likelihood Ratio statistic for the test presented in \\eqref{eq:6:firstDefGLRT} in Section~\\ref{sub:6:presentationOfGLRTest} is\n% % \\[\\GLR(n) \\eqdef \\frac{\\sup\\limits_{\\mu_0,\\mu_1,\\tau < n}\\ell(X_1, \\ldots, X_n ; \\mu_0,\\mu_1,\\tau)}{\\sup\\limits_{\\mu_0}\\ell(X_1, \\ldots, X_n ; \\mu_0)},\\]\n% % %\n% % where $\\ell(X_1, \\ldots, X_n ; \\mu_0)$ and $\\ell(X_1, \\ldots, X_n ; \\mu_0,\\mu_1,\\tau)$ respectively denote the likelihoods of the first $n$ observations under a model in $\\cH_0$ and $\\cH_1$.\n\n% The Generalized Likelihood Ratio statistic for the test is presented above in \\eqref{eq:6:firstDefGLRT} in Section~\\ref{sub:6:presentationOfGLRTest}.\n% %\n% We refer to \\cite{Basseville93} and reference therein for the generic proof, but we prove here the specific case of Bernoulli distributions.\n% % For any $k \\leq k'$, we denote $\\widehat{\\mu}_{k:k'} \\eqdef \\frac{1}{k - k' + 1} \\sum_{l=k}^{k'} X_l$ denotes the average of the observations $X_l$ collected between the instants $k$ and $k'$.\n% %\n% We prove below that the GLR test is equivalent to\n% \\begin{align*}\n%     \\GLR(n)\n%     &= \\frac{\\sup\\limits_{\\mu_0,\\mu_1,\\tau < n}\\ell(X_1, \\ldots, X_n ; \\mu_0,\\mu_1,\\tau)}{\\sup\\limits_{\\mu_0}\\ell(X_1, \\ldots, X_n ; \\mu_0)} \\\\\n%     &= \\exp\\Bigl[ \\sup_{s \\in [n-1]} \\left[s \\times \\kl\\left(\\widehat{\\mu}_{1:s},\\widehat{\\mu}_{1:n}\\right) + (n-s) \\times \\kl\\left(\\widehat{\\mu}_{s+1:n},\\widehat{\\mu}_{1:n}\\right)\\right] \\Bigr].\n% \\end{align*}\n% %\n% % Remember that the binary relative entropy $\\kl$, defined for $x,y\\in[0,1]$\n% % by $\\kl(x,y) \\eqdef x \\ln\\left(\\frac{x}{y}\\right) + (1-x)\\ln\\left(\\frac{1-x}{1-y}\\right)$,\n% % with the usual convention that $t \\log(t) = 0$ if $t=0$.\n\n% \\begin{proof}\n%     First, we consider the denominator in the expression of $\\GLR(n)$ \\eqref{eq:6:firstDefGLRT}, that is the $\\sup$ on $\\mu_0$.\n%     We have $\\ell(X_1, \\ldots, X_n ; \\mu_0) = \\prod_{i=1}^n \\ell(X_i ; \\mu_0)$ by independence of the observations $X_i$,\n%     and $\\ell(X_i ; \\mu_0) = \\mu_0^{X_i} (1-\\mu_0)^{1-X_i}$ for Bernoulli distributions.\n%     Therefore, taking the logarithm gives\n%     \\begin{align*}\n%         \\log\\ell(X_1, \\ldots, X_n ; \\mu_0)\n%         &= \\sum_{i=1}^n X_i \\log(\\mu_0) + (1-X_i) \\log(1-\\mu_0) \\\\\n%         &= \\log(\\mu_0) \\times \\left( \\sum_{i=1}^n X_i \\right) + \\log(1-\\mu_0) \\times \\left( n - \\sum_{i=1}^n X_i \\right) \\\\\n%         &= n \\left[ \\widehat{\\mu}_{1:n} \\log(\\mu_0) + (1 - \\widehat{\\mu}_{1:n}) \\log(1-\\mu_0) \\right].\n%     \\end{align*}\n%     %\n%     For a constant $a\\in[0,1]$, let $h(x) \\eqdef a \\log(x) + (1-a) \\log(1-x)$ on $(0,1)$,\n%     and we are trying to solve $\\sup_{x\\in[0,1]} h(x)$.\n%     If $a=0$ or $a=1$, $h$ is maximum at $x=a$.\n%     Now if $a\\neq0$, As $h$ is of class $\\cC^1$, we can just differentiate and find the root of its derivative:\n%     $h'(x) = a/x - (1-a)/(1-x)$, so $h'(x) = 0$ if and only if $x=a$.\n%     Thus in all cases, $\\sup_{x\\in[0,1]} h(x) = h(a)$.\n%     %\n%     Here, we have $a = \\widehat{\\mu}_{1:n}$, and thus we solve the $\\sup_{\\mu_0}$ optimization problem found in the denominator of the $\\GLR(n)$ expression.\n%     By replacing $\\mu_0 = \\widehat{\\mu}_{1:n}$, we obtained the following (unique) solution,\n%     \\begin{equation}\\label{eq:6:solutionPbOpt_for_1n}\n%         \\sup_{\\mu_0} \\log\\ell(X_1, \\ldots, X_n ; \\mu_0) = n \\left( \\widehat{\\mu}_{1:n} \\log(\\widehat{\\mu}_{1:n}) + (1 - \\widehat{\\mu}_{1:n}) \\log(1-\\widehat{\\mu}_{1:n}) \\right).\n%     \\end{equation}\n\n%     Now let us consider the nominator of the $\\GLR(n)$ expression.\n%     We can again work with log-likelihoods, and so we have\n%     \\begin{align*}\n%         \\log\\ell(X_1, \\ldots, X_n ; \\mu_0,\\mu_1,\\tau)\n%         &= \\sum_{i=1}^{\\tau} X_i \\log(\\mu_0) + (1-X_i) \\log(1-\\mu_0) + \\sum_{i=\\tau+1}^n X_i \\log(\\mu_1) + (1-X_i) \\log(1-\\mu_1) \\\\\n%         &= s \\bigl( \\widehat{\\mu}_{1:s} \\log(\\mu_0) + (1 - \\widehat{\\mu}_{1:s}) \\log(1-\\mu_0) \\bigr) \\\\\n%         & \\;\\;\\;\\; + (n-s) \\bigl( \\widehat{\\mu}_{s+1:n} \\log(\\mu_1) + (1 - \\widehat{\\mu}_{s+1:n}) \\log(1-\\mu_1) \\bigr).\n%     \\end{align*}\n%     Because we solved in \\eqref{eq:6:solutionPbOpt_for_1n} the $\\sup$ for the denominator,\n%     we have\n%     \\begin{align*}\n%         \\GLR(n)\n%         % &= \\frac{\\sup\\limits_{\\mu_0,\\mu_1,\\tau < n}\\ell(X_1, \\ldots, X_n ; \\mu_0,\\mu_1,\\tau)}{\\sup\\limits_{\\mu_0}\\ell(X_1, \\ldots, X_n ; \\mu_0)}, \\\\\n%         &= \\frac{\\sup\\limits_{\\mu_0,\\mu_1,\\tau < n}\\ell(X_1, \\ldots, X_n ; \\mu_0,\\mu_1,\\tau)}{ \\exp\\left[ n \\left( \\widehat{\\mu}_{1:n} \\log(\\mu_0) + (1 - \\widehat{\\mu}_{1:n}) \\log(1-\\mu_0) \\right) \\right] }, \\\\\n%         &= \\sup\\limits_{\\mu_0,\\mu_1,\\tau < n} \\frac{\\ell(X_1, \\ldots, X_n ; \\mu_0,\\mu_1,\\tau)}{ \\exp\\left[ n \\left( \\widehat{\\mu}_{1:n} \\log(\\widehat{\\mu}_{1:n}) + (1 - \\widehat{\\mu}_{1:n}) \\log(1-\\widehat{\\mu}_{1:n}) \\right) \\right] }, \\\\\n%         &= \\exp \\Bigl[ \\sup\\limits_{\\mu_0,\\mu_1,\\tau < n} \\Bigl[ \\log\\Bigl[ \\frac{\\ell(X_1, \\ldots, X_n ; \\mu_0,\\mu_1,\\tau)}{ \\exp\\left[ n \\left( \\widehat{\\mu}_{1:n} \\log(\\widehat{\\mu}_{1:n}) + (1 - \\widehat{\\mu}_{1:n}) \\log(1-\\widehat{\\mu}_{1:n}) \\right) \\right] } \\Bigr] \\Bigr] \\Bigr],  \\\\\n%         &= \\exp \\Bigl[ \\sup\\limits_{\\mu_0,\\mu_1, s \\in [n-1]} \\Bigl[\n%             s \\bigl( \\widehat{\\mu}_{1:s} \\log(\\mu_0) + (1 - \\widehat{\\mu}_{1:s}) \\log(1-\\mu_0) \\bigr) \\\\\n%             & \\hspace{35pt} + (n-s) \\bigl( \\widehat{\\mu}_{s+1:n} \\log(\\mu_1) + (1 - \\widehat{\\mu}_{s+1:n}) \\log(1-\\mu_1) \\bigr) \\\\\n%             & \\hspace{35pt} - n \\bigl( \\widehat{\\mu}_{1:n} \\log(\\widehat{\\mu}_{1:n}) + (1 - \\widehat{\\mu}_{1:n}) \\log(1-\\widehat{\\mu}_{1:n}) \\bigr)\n%         \\Bigr] \\Bigr].\n%     \\end{align*}\n%     By linearity and independence, we can separate the joint optimization problem on $\\mu_0,\\mu_1,s$ in two optimizations problems for $\\mu_0,s$ and $\\mu_1,s$, that can first be solved explicitly for $\\mu_0$ (resp. $\\mu_1$) and then left to be solved for $s$.\n%     By definition, $n \\; \\widehat{\\mu}_{1:n} = \\sum_{i=1}^n X_i = s \\;\\widehat{\\mu}_{1:s} + (n-s) \\;\\widehat{\\mu}_{s+1:n}$, so the right hand side (negative) part involving $\\widehat{\\mu}_{1:n}$ can be distributed in the two left hand side (positive) terms,\n%     which are both handled similarly.\n%     For instance for $\\mu_0$, we use the same computation as above with the function $h$ to find the optimum:\n%     $\\widehat{\\mu}_{1:s} \\log(\\mu_0) + (1 - \\widehat{\\mu}_{1:s}) \\log(1-\\mu_0)$\n%     is optimum for $\\mu_0 = \\widehat{\\mu}_{1:s}$.\n%     Similarly, the term for $\\mu_1$ gives that $\\sup_{\\mu_1} \\widehat{\\mu}_{s+1:n} \\log(\\mu_1) + (1 - \\widehat{\\mu}_{s+1:n}) \\log(1-\\mu_1)$\n%     is attained for $\\mu_1 = \\widehat{\\mu}_{s+1:n}$.\n%     Finally, by replacing the two expressions of the solutions for $\\mu_0$ and $\\mu_1$,\n%     we obtain\n%     \\begin{align*}\n%         \\GLR(n)\n%         = \\exp \\Bigl[ \\sup\\limits_{s \\in [n-1]} \\Bigl[\n%             s \\times \\Bigl(\n%                     & \\widehat{\\mu}_{1:s} \\log(\\widehat{\\mu}_{1:s}) + (1 - \\widehat{\\mu}_{1:s}) \\log(1-\\widehat{\\mu}_{1:s}) \\\\\n%                     & - \\widehat{\\mu}_{1:s} \\log(\\widehat{\\mu}_{1:n}) + (1 - \\widehat{\\mu}_{1:s}) \\log(1-\\widehat{\\mu}_{1:n})\n%             \\Bigr) \\\\\n%             + (n-s) \\times \\Bigl(\n%                 & \\widehat{\\mu}_{s+1:n} \\log(\\widehat{\\mu}_{s+1:n}) + (1 - \\widehat{\\mu}_{s+1:n}) \\log(1-\\widehat{\\mu}_{s+1:n}) \\\\\n%                 & - \\widehat{\\mu}_{s+1:n} \\log(\\widehat{\\mu}_{1:n}) + (1 - \\widehat{\\mu}_{s+1:n}) \\log(1-\\widehat{\\mu}_{1:n})\n%             \\Bigr)\n%         \\Bigr] \\Bigr].\n%     \\end{align*}\n%     We conclude by recognizing the expressions of $s \\times \\kl(\\widehat{\\mu}_{1:s}, \\widehat{\\mu}_{1:n})$\n%     and $(n-s) \\times \\kl(\\widehat{\\mu}_{s+1:n}, \\widehat{\\mu}_{1:n})$.\n% \\end{proof}\n\n\n% Consider $(Y_i)_{i\\in\\N}$ some data, and $t_0\\in\\N$, $t\\in\\N$ and any $s\\in[t_0,t)$.\n% For any $a<b$, define $\\mu_{a:b} \\eqdef \\frac{1}{b-a+1} \\sum_{i=a}^{b} Y_i$ the mean of samples from $a$ to $b$.\n\n% In a one dimensional exponential family, \\eg, Gaussian distributions of known variance ($\\sigma=1$) or Bernoulli distributions, the Kullback-Leibler divergence of two distributions is expressed with a $\\kl$ function of their mean.\n% That is, for two distributions $\\nu_1,\\nu_2$ of means $\\mu_1,\\mu_2$,\n% $$\\KL(\\nu_1,\\nu_2) = \\kl(\\mu_1,\\mu_2).$$\n\n% The \\GLR{} test is defined in \\cite{Maillard2018GLR}, and is written like this.\n% $$\\GLR^{\\kl}_{t_0 : s : t} = (s-t_0+1) \\kl(\\mu_{t_0:s}, \\mu_{t_0:t}) + (t-s) \\kl(\\mu_{s+1:t}, \\mu_{t_0:t}).$$\n\n% \\begin{lemma}[Simplified expression for $\\GaussianGLR$]\\label{lem:XXX}\n%     For $\\cN_1$, the exponential family of Gaussian distributions of variance $\\sigma^2=1$,\n%     the \\GLR{} test can be simplified:\n%     \\begin{align}\n%         \\forall t_0 \\leq s < t,\\; \\GaussianGLR_{t_0 : s : t} &= (s-t_0+1) \\kl(\\mu_{t_0:s}, \\mu_{t_0:t}) + (t-s) \\kl(\\mu_{s+1:t}, \\mu_{t_0:t})\\\\\n%         &= \\frac{(s-t_0+1)(t-s)}{t-t_0+1} \\kl(\\mu_{s+1:t}, \\mu_{t_0:s}) = \\frac{(s-t_0+1)(t-s)}{t-t_0+1} \\frac{(\\mu_{s+1:t}, \\mu_{t_0:s})^2}{2}.\n%     \\end{align}\n% \\end{lemma}\n% \\begin{proof}\n%     Define $k_1 \\eqdef \\kl(\\mu_{t_0:s}, \\mu_{t_0:t})$,\n%     $k_2 \\eqdef \\kl(\\mu_{s+1:t}, \\mu_{t_0:t})$,\n%     and $k_3 \\eqdef \\kl(\\mu_{s+1:t}, \\mu_{t_0:s})$.\n%     In this family $\\cN_1$, $\\kl(x,y) = \\frac{(x-y)^2}{2}$. Let us multiply everything by $2$ to avoid having this $\\frac{1}{2}$ on every line.\n%     % \\begin{small}\n%     \\begin{align*}\n%         &2 (s-t_0+1) k_1 + (t-s) k_2 \\\\\n%         &=\n%         (s-t_0+1)\\mu_{t_0:s}^2 + (t-s)\\mu_{s+1:t}^2 + (s-t_0+1+t-s)\\mu_{t_0:t}^2 \\\\\n%         &\\;\\;\\;\\;\\;\\;\\;\\;\\;- 2 (s-t_0+1)\\mu_{t_0:s}\\mu_{t_0:t}\n%         - 2 (t-s)\\mu_{s+1:t}\\mu_{t_0:t} \\\\\n%         &= (s-t_0+1)\\mu_{t_0:s}^2 + (t-s)\\mu_{s+1:t}^2 + (t-t_0+1)\\mu_{t_0:t}^2 \\\\\n%         &\\;\\;\\;\\;\\;\\;\\;\\;\\;- 2 (\\underbrace{(s-t_0+1)\\mu_{t_0:s}+(t-s)\\mu_{s+1:t}}_{=\\sum_{i=t_0}^{t} Y_i = (t-t_0+1) \\mu_{t_0:t}})\\mu_{t_0:t} \\\\\n%         &= (s-t_0+1)\\mu_{t_0:s}^2 + (t-s)\\mu_{s+1:t}^2 - (t-t_0+1)\\mu_{t_0:t}^2 \\\\\n%         &= \\frac{\\left(\\sum_{i=t_0}^{s} Y_i \\right)^2}{s-t_0+1} + \\frac{\\left(\\sum_{i=s+1}^{t} Y_i \\right)^2}{t-s} - \\frac{\\left(\\sum_{i=t_0}^{t} Y_i \\right)^2}{t-t_0+1} \\\\\n%         &= \\frac{1}{t-t_0+1} \\Bigl( \\frac{(s-t_0+1) + (t-s)}{s-t_0+1} \\left(\\sum_{i=t_0}^{s} Y_i \\right)^2 + \\frac{(s-t_0+1) + (t-s)}{t-s} \\left(\\sum_{i=s+1}^{t} Y_i \\right)^2 \\\\\n%         &\\;\\;\\;\\;\\;\\;\\;\\;\\;- \\left(\\sum_{i=t_0}^{s} Y_i + \\sum_{i=s+i}^{t} Y_i \\right)^2 \\Bigr) \\\\\n%         &= \\frac{1}{t-t_0+1} \\Bigl( \\left(\\sum_{i=t_0}^{s} Y_i \\right)^2 + \\frac{t-s}{s-t_0+1} \\left(\\sum_{i=t_0}^{s} Y_i \\right)^2 + \\left(\\sum_{i=s+1}^{t} Y_i \\right)^2 + \\frac{s-t_0+1}{t-s} \\left(\\sum_{i=s+1}^{t} Y_i \\right)^2 \\\\\n%         &\\;\\;\\;\\;\\;\\;\\;\\;- \\left(\\sum_{i=t_0}^{s} Y_i \\right)^2 - \\left(\\sum_{i=s+i}^{t} Y_i \\right)^2 - 2 \\left(\\sum_{i=t_0}^{s} Y_i \\right) \\left(\\sum_{i=s+i}^{t} Y_i \\right) \\Bigr) \\\\\n%         &= \\frac{1}{t-t_0+1} \\Bigl(\\frac{t-s}{s-t_0+1} \\left(\\sum_{i=t_0}^{s} Y_i \\right)^2 + \\frac{s-t_0+1}{t-s} \\left(\\sum_{i=s+1}^{t} Y_i \\right)^2 - 2 \\left(\\sum_{i=t_0}^{s} Y_i \\right) \\left(\\sum_{i=s+i}^{t} Y_i \\right) \\Bigr) \\\\\n%         &= \\frac{(s-t_0+1)(t-s)}{t-t_0+1} \\Bigl( \\frac{1}{(s-t_0+1)^2} \\left(\\sum_{i=t_0}^{s} Y_i \\right)^2 + \\frac{1}{(t-s)^2} \\left(\\sum_{i=s+1}^{t} Y_i \\right)^2 \\\\\n%         &\\;\\;\\;\\;\\;\\;\\;\\;\\;- 2 \\left(\\frac{1}{s-t_0+1} \\sum_{i=t_0}^{s} Y_i \\right) \\left(\\frac{1}{t-s} \\sum_{i=s+1}^{t} Y_i \\right) \\Bigr) \\\\\n%         &= \\frac{(s-t_0+1)(t-s)}{t-t_0+1} (\\mu_{s+1:t} - \\mu_{t_0:s})^2 = 2 \\frac{(s-t_0+1)(t-s)}{t-t_0+1} k_3.\n%     \\end{align*}\n%     as wanted.\n%     % \\end{small}\n% \\end{proof}\n\n% This is not true for all one dimensional exponential family, for instance for Bernoulli distributions it is almost never the case.\n% Imagine $t_0=0, t=2, s=1$ and data $Y_i = [0,1]$.\n% Then $\\mu_{t_0:s}=0$, $\\mu_{s+1:t}=1$, $\\mu_{t_0:t}=0.5$, and so $k_1 = \\kl(0,0.5) = \\log(2)$ and $k_2 = \\kl(1,0.5)=\\log(2)$ and $k_3=\\kl(0,1)=-\\infty$ so we do not have\n% $(s-t_0+1) \\kl(\\mu_{t_0:s}, \\mu_{t_0:t}) + (t-s) \\kl(\\mu_{s+1:t}, \\mu_{t_0:t}) = \\frac{(s-t_0+1)(t-s)}{t-t_0+1} \\kl(\\mu_{s+1:t}, \\mu_{t_0:s})$.\n\n\n\n% ----------------------------------------------------------------------------\n\\subsubsection{Proof of Lemma~\\ref{lem:6:ConcFirst}.}\n\\label{app:6:proofConcFirst}\n%\nUsing the same construction as in the proof of Theorem~14 in \\cite{KK18Martingales}, one can prove that for every $\\lambda \\in I$ (for an interval $I$), there exists a non-negative super-martingale $M^\\lambda (s)$ with respect to the filtration $\\cF_t \\eqdef \\sigma(X_1,\\dots,X_t)$ that satisfies $\\bE[M^\\lambda(s)] \\leq 1$ and\n\\[\\forall s \\in \\N^*, \\ \\ M^\\lambda (s) \\geq \\e^{\\lambda [s \\, \\kl(\\widehat{\\mu}_s,\\mu) - 3\\ln(1+\\ln(s))] - g(\\lambda)}\\]\nfor some function $g : I \\rightarrow \\R$. This super-martingale is of the form\n$M^\\lambda (s) \\eqdef \\int \\e^{\\eta\\sum_{i=1}^s X_i - \\phi_\\mu(\\lambda)s} d\\pi(\\eta)$,\nfor a well-chosen probability distribution $\\pi$, and the function $g$ can be chosen to be any\n\\begin{eqnarray*}\n    g_{\\xi} : \\left[0; 1/(1+\\xi)\\right] & \\longrightarrow & \\R \\\\\n    \\lambda & \\mapsto & \\lambda(1+\\xi) \\ln \\left(\\frac{\\pi^2}{3(\\ln(1+\\xi))^2}\\right) -  \\ln(1 - \\lambda(1 + \\xi))\n\\end{eqnarray*}\nfor a parameter $\\xi \\in [0,1/2]$.\n\nSimilarly, if we denote $\\cF_r'$ the filtration $\\sigma(Y_1,\\dots,Y_r)$,\nthere exists an independent super-martingale $W^\\lambda (r)$ w.r.t. the filtration $\\cF_r'$, such that\n\\[\\forall r \\in \\N^*, \\ \\ W^\\lambda (r) \\geq \\e^{\\lambda [r\\kl(\\widehat{\\mu}'_r,\\mu) - 3\\ln(1+\\ln(r))] - g(\\lambda)},\\]\nfor the same function $g(\\lambda)$.\nIn the terminology of \\cite{KK18Martingales},\nthe two following processes are $g$-DCC (for Doob-Cram\\'er-Chernoff),\n$\\bm{X}(s) \\eqdef s \\, \\kl(\\widehat{\\mu}_s,\\mu) - 3\\ln(1+\\ln(s))$ and $\\bm{Y}(s) \\eqdef r \\, \\kl(\\widehat{\\mu}_r,\\mu) - 3\\ln(1+\\ln(r))$,\nas for both processes Doob's inequality can be applied in combination with the Cram\\'er-Chernoff method to obtain deviation inequalities that are uniform in time.\n\nHere we have to modify the technique used in the Lemma~4 of \\cite{KK18Martingales} in order to take into account the two stochastic processes, and the presence of super-martingales instead of martingales (for which Doob inequality still works).\nOne can write\n%\n\\begin{align*}\n    &\\bP\\bigl( \\exists r \\in \\N^* : s \\, \\kl\\left(\\widehat{\\mu}_{s},\\mu\\right) + r \\, \\kl\\left(\\widehat{\\mu}_r',\\mu'\\right) > 3\\ln(1+\\ln(s)) + 3\\ln(1+\\ln(r)) + u \\bigr) \\\\\n    & \\leq \\bP\\left(\\exists r \\in \\N^* : M^\\lambda(s)W^\\lambda(r) > \\e^{\\lambda u - 2g(\\lambda)}\\right) \\\\\n    & = \\lim_{n \\rightarrow \\infty} \\bP\\left(\\exists r \\in [n] :  M^\\lambda(s)W^\\lambda(r) > \\e^{\\lambda u - 2g(\\lambda)}\\right) \\\\\n    & = \\lim_{n \\rightarrow \\infty} \\bP\\left(\\sup_{r \\in [n]}  M^\\lambda(s)W^\\lambda(r) > \\e^{\\lambda u - 2g(\\lambda)}\\right).\n\\end{align*}\n%\nUsing that $\\widetilde{M}(r) \\eqdef M^\\lambda(s)W^\\lambda(r)$ is a super-martingale with respect to the filtration $\\widetilde{\\cF}_r \\eqdef \\sigma(X_1,\\dots,X_s, Y_1,\\dots,Y_r)$, one can apply Doob's maximal inequality to obtain\n\\begin{eqnarray*}\n    \\bP\\left(\\sup_{r \\in [n]}  M^\\lambda(s)W^\\lambda(r) > \\e^{\\lambda u - 2g(\\lambda)}\\right) &\\leq& \\e^{-(\\lambda u - 2g(\\lambda))}\\bE[\\widetilde{M}(1))] \\\\\n    & = & \\e^{-(\\lambda u - 2g(\\lambda))}\\bE[M^\\lambda(s)W^\\lambda(1)] \\\\\n    & \\leq & \\e^{-(\\lambda u - 2g(\\lambda))},\n\\end{eqnarray*}\nusing that $M^\\lambda(s)$ and $W^\\lambda(1)$ are independent and have an expectation smaller than $1$.\n\nPutting things together yields\n\\[\\bP\\left(\\exists r \\in \\N^* : s \\, \\kl\\left(\\widehat{\\mu}_{s},\\mu\\right) + r \\, \\kl\\left(\\widehat{\\mu}_r',\\mu'\\right) > 3\\ln(1+\\ln(s)) + 3\\ln(1+\\ln(r)) + u\\right) \\leq \\e^{-\\left(\\lambda u - 2g_{\\xi}(\\lambda)\\right)},\\]\nfor any function $g_{\\xi}$ defined above.\n%\nThe conclusion follows by optimizing for both $\\lambda$ and $\\xi$, using Lemma~18 in \\cite{KK18Martingales}.\n\n\n% ----------------------------------------------------------------------------\n\\subsubsection{A concentration result involving two arms}\\label{proof:6:Chernoff2arms}\n\nThe following result is useful to control the probability of the good event in our two regret analyzes.\nIts proof follows from a straightforward application of the Cram\\'er-Chernoff method \\cite{Boucheron2013}, and is given below.\n\n\\begin{lemma}\\label{lem:6:Chernoff2arms}\n\\begin{leftbar}[lemmabar]  % XXX leftbar lemmabar, comment if needed\n    Let $\\widehat{\\mu}_{i,s}$ be the empirical mean of $s\\in\\N^*$ \\iid{} observations with mean $\\mu_i$, for $i \\in \\{a,b\\}$, that are $\\sigma^2$-sub-Gaussian.\n    Define $\\Delta \\eqdef \\mu_a - \\mu_b$. Then for any $s,r > 0$, we have\n    \\begin{equation}\n        \\bP\\left(\\frac{s \\; r}{s+r}\\Big(\\widehat{\\mu}_{a,s} - \\widehat{\\mu}_{b,r} - \\Delta\\Big)^2 \\geq u \\right) \\leq 2\\exp\\left(- \\frac{u}{2\\sigma^2}\\right).\n    \\end{equation}\n\\end{leftbar}  % XXX leftbar lemmabar, comment if needed\n\\end{lemma}\n\n\n\\paragraph{Proof of Lemma~\\ref{lem:6:Chernoff2arms}.}\n\nWe first note that\n\\begin{align}\\label{eq:6:Preparation}\n\t&\\bP\\left(\\frac{s \\; r}{s+r}\\Big(\\widehat{\\mu}_{a,s} - \\widehat{\\mu}_{b,r} - \\Delta\\Big)^2 \\geq u \\right) \\nonumber\\\\\n\t&\\leq \\bP\\left(\\widehat{\\mu}_{a,s} - \\widehat{\\mu}_{b,r} \\geq \\Delta + \\sqrt{\\frac{s+r}{sr}u} \\right) + \\bP\\left(\\widehat{\\mu}_{b,r} - \\widehat{\\mu}_{a,s} \\geq -\\Delta + \\sqrt{\\frac{s+r}{sr}u} \\right),\n\\end{align}\nand those two quantities can be upper-bounded similarly using the Cram\\'er-Chernoff method.\n\nLet $(X_i)$ and $(Y_i)$ be two \\iid{} sequences that are $\\sigma^2$-sub-Gaussian with mean $\\mu_1$ and $\\mu_2$ respectively. Let $n_1$ and $n_2$ be two integers and $\\widehat{\\mu}_{1,n_1}$ and $\\widehat{\\mu}_{2,n_2}$ denote the two empirical means based on $n_1$ observations from $X_i$, and $n_2$ observations from $Y_i$ respectively.\nThen for every $\\lambda > 0$, as $x \\mapsto \\exp(\\lambda x)$ is increasing, if $p \\eqdef \\bP\\left(\\widehat{\\mu}_{1,n_1} - \\widehat{\\mu}_{2,n_2} \\geq \\mu_1 - \\mu_2 + x \\right)$, we have\n\\begin{align*}\n    % \\bP\\left(\\widehat{\\mu}_{1,n_1} - \\widehat{\\mu}_{2,n_2} \\geq \\mu_1 - \\mu_2 + x \\right)\n    p\n    & \\leq \\bP\\left(\\frac{1}{n_1}\\sum_{i=1}^{n_1} (X_i-\\mu_1) - \\frac{1}{n_2}\\sum_{i=1}^{n_2} (Y_i - \\mu_2) \\geq x \\right)\\\\\n    & = \\bP\\left(\\exp \\left( \\lambda \\left(\\frac{1}{n_1}\\sum\\limits_{i=1}^{n_1} (X_i-\\mu_1) - \\frac{1}{n_2}\\sum\\limits_{i=1}^{n_2} (Y_i - \\mu_2)\\right) \\right) \\geq \\exp(\\lambda x) \\right).\n\\end{align*}\nAnd so thanks to Markov's inequality, we obtain\n\\begin{align*}\n    % \\bP\\left(\\widehat{\\mu}_{1,n_1} - \\widehat{\\mu}_{2,n_2} \\geq \\mu_1 - \\mu_2 + x \\right)\n    p\n    & \\leq \\exp(-\\lambda x) \\bE\\left[\\exp \\left(\\lambda \\frac{1}{n_1}\\sum\\limits_{i=1}^{n_1} (X_i-\\mu_1) \\right)\\right]\\bE\\left[\\exp \\left(-\\lambda \\frac{1}{n_2}\\sum\\limits_{i=1}^{n_2} (Y_i-\\mu_2) \\right)\\right] \\\\\n    & = \\exp\\left(- \\lambda x + n_1\\phi_{X_1 - \\mu_1}\\left(\\frac{\\lambda}{n_1}\\right) + n_2\\phi_{Y_1 - \\mu_2}\\left(-\\frac{\\lambda}{n_2}\\right)\\right) \\\\\n    & \\leq \\exp\\left(- \\lambda x + \\frac{\\lambda^2\\sigma^2}{2n_2} + \\frac{\\lambda^2\\sigma^2}{2n_1}\\right),\n\\end{align*}\n%\nwhere the last inequality uses the sub-Gaussian property,\non the two centered variables $X_1-\\mu_1$ and $Y_1-\\mu_2$.\n%\nIn order to obtain the tightest bound on the left-hand side probability,\nwe can look for the value of $\\lambda$ that minimizes the right-hand side of the inequality yields.\nBy differentiating and by convexity, we find the value\n\\[\\lambda \\eqdef \\frac{1}{2} \\frac{x}{\\sigma^2/(2n_1) + \\sigma^2/(2n_2)}\\]\nwhich yields the tighter inequality on this probability,\n\\[ p = \\bP\\left(\\widehat{\\mu}_{1,n_1} - \\widehat{\\mu}_{2,n_2} \\geq \\mu_1 - \\mu_2 + x \\right) \\leq \\exp\\left(- \\frac{n_1n_2}{n_1+n_2}\\frac{x^2}{2\\sigma^2}\\right).\\]\n%\nUsing this inequality twice in the right hand side of \\eqref{eq:6:Preparation} concludes the proof.\n\\hfill{} $\\qed$  % WARNING manually write this is a bad idea!\n\n% -----------------------------------------------------------------\n\n% -----------------------------------------------------------------\n% ------------------------------------------------------------------------------------\n% \\subsection{Proof for \\GLRklUCB{} with Local Changes}\n% \\label{proof:6:mainRegretBound}\n\n% \\TODOL{Si on veut gagner de la place, et éviter les redites, on peut dire que la preuve ressemble à celle pour Global changes, et qu'elle est traitée en annexe de \\cite{Besson2019GLRT} de toute façon !}\n\n% % \\subsubsection{Proof of Theorem~\\ref{thm:6:mainRegretBound}}\n\n% Our analysis for the other variant of \\GLRklUCB{} also relies on the general regret decomposition~\\eqref{eq:6:GeneRegretBound} and follows the proof skeleton presented in Section~\\ref{sub:6:proofSkeleton}, with the following appropriate ``good event'', that is shown to be likely in Lemma~\\ref{lem:6:GoodEvent} below.\n% %\n% \\begin{equation}\\label{def:6:GoodEvenLocal}\n%     \\cE_T(\\omega,\\delta) = \\left(\\forall i \\in \\{1, \\ldots, K\\}, \\forall \\ell \\in \\{1, \\ldots, \\NCi\\}, \\hat{\\tau}^{(\\ell)}_i \\in \\left[\\tau_i^{(\\ell)} + 1, \\tau_i^{(\\ell)} + d_i^{(\\ell)}\\right] \\right),\n% \\end{equation}\n% where $\\widehat{\\tau}_i^{(\\ell)}$ is defined as the $\\ell$-th change detected by the algorithm on arm $i$ and $d_i^{(\\ell)}=d_i^{(\\ell)}(\\omega,\\delta)$ is defined as in Assumption~\\ref{ass:6:LongPeriods}. Using this assumption, one can prove the following.\n\n% \\begin{lemma}\\label{lem:6:GoodEvent}\n%     The ``bad event'' is highly unlikely, as it satisfies $\\bP((\\cE_T(\\omega,\\delta))^c) \\leq 2 \\; \\delta \\; \\EffChange$.\n% \\end{lemma}\n\n\n% We now turn our attention to upper bounding terms $(A)$ and $(B)$ in \\eqref{eq:6:GeneRegretBound}.\n\n% \\paragraph{Upper bound on term $\\bm{(A)}$.}\n% %\n% \\begin{align*}\n%     (A) & \\leq \\bE\\left[\\indic(\\cE_T) \\sum_{t=1}^T \\indic\\left(n_{i_t^*}(t) \\kl\\left(\\widehat{\\mu}_{i_t^*}(t), \\mu_{i_t^*}(t)\\right) \\geq f(t - \\tau_{i_t^*}(t))\\right)\\right] \\\\\n%     & \\leq \\sum_{i=1}^K \\sum_{k=1}^{\\NCi}\\bE\\left[\\indic(\\cE_T) \\sum_{t=1}^T \\indic(i_t^* =i) \\indic(\\tau_i(t) = \\widehat{\\tau}_i^{(\\ell)})\\indic\\left(n_{i}(t) \\kl\\left(\\widehat{\\mu}_{i}(t), \\mu_{i}\\right) \\geq f(t - \\widehat{\\tau}_{i}^{(\\ell)})\\right)\\right] \\\\\n%     & \\leq \\sum_{i=1}^K \\sum_{\\ell=0}^{\\NCi}\\bE\\left[\\indic(\\cE_T) \\sum_{t=\\hat{\\tau}_i^{(\\ell)}}^{\\tau_i^{(\\ell+1)}} \\indic\\left(n_{i}(t) \\kl\\left(\\widehat{\\mu}_{i}(t), \\mu_{i}\\right) \\geq f(t - \\widehat{\\tau}_{i}^{(\\ell)})\\right) + d_i^{(\\ell)}(T)\\right] \\\\\n%     & \\leq \\sum_{i=1}^K \\sum_{\\ell=0}^{\\NCi}d_i^{(\\ell+1)}(T) + \\sum_{i=1}^K \\sum_{\\ell=0}^{\\NCi}\\bE\\left[\\indic(\\cC_i^{(\\ell)}) \\sum_{t=\\hat{\\tau}_i^{(\\ell)}}^{\\tau_i^{(\\ell+1)}}\\indic\\left(n_{i}(t) \\kl\\left(\\widehat{\\mu}_{i}(t), \\mu_{i}\\right) \\geq f(t - \\widehat{\\tau}_{i}^{(\\ell)})\\right)\\right],\n% \\end{align*}%\n% %\n% where we introduce the event $\\cC_i^{(\\ell)}$ that all the changes up to the $\\ell$-th have been detected:\n% \\begin{equation}\\cC_i^{(\\ell)} = \\left\\{\\forall j \\leq \\ell, \\widehat{\\tau}_i^{(j)} \\in \\left[\\tau_i^{(j)} + 1, \\tau_i^{(j)} + d_i^{(\\ell)} \\right] \\right\\}.\\label{def:6:EventCi}\\end{equation}\n% Clearly, $\\cE_T \\subseteq \\cC_i^{(\\ell)}$ and $\\cC_i^{(\\ell)}$ is $\\cF_{\\widehat{\\tau}_i^{(\\ell)}}$-measurable. Observe that conditionally to $\\cF_{\\widehat{\\tau}_i^{(\\ell)}}$, when $\\indic(\\cC_i^{(\\ell)})$ holds, $\\widehat{\\mu}_{i}(t)$ is the average of samples that have all mean $\\mu_i^{(\\ell)}$. Thus, introducing $\\widehat{\\mu}_s$ as a sequence of \\iid{} random variables with mean $\\mu_i^{(\\ell)}$, one can write\n% \\begin{align*}\n%     &\\bE\\left[\\left.\\indic(\\cC_i^{(\\ell)}) \\sum_{t=\\hat{\\tau}_i^{(\\ell)}}^{\\tau_i^{(\\ell+1)}} \\indic\\left(n_{i}(t) \\kl\\left(\\widehat{\\mu}_{i}(t), \\mu_{i}\\right) \\geq f(t - \\widehat{\\tau}_{i}^{(\\ell)})\\right) \\right| \\cF_{\\widehat{\\tau}_i^{(\\ell)}}\\right]\\\\\n%     & = \\indic(\\cC_i^{(\\ell)}) \\sum_{t=\\hat{\\tau}_i^{(\\ell)}}^{\\tau_i^{(\\ell+1)}} \\bE\\left[\\indic\\left(n_{i}(t) \\kl\\left(\\widehat{\\mu}_{i}(t), \\mu_{i}\\right) \\geq f(t - \\widehat{\\tau}_{i}^{(\\ell)})\\right) \\;|\\; \\cF_{\\widehat{\\tau}_i^{(\\ell)}}\\right] \\\\\n% % \\end{align*}%\n% % \\begin{align*}\n%     & \\leq \\indic(\\cC_i^{(\\ell)}) \\sum_{t=1}^{\\tau_i^{(\\ell+1)} - \\hat{\\tau}_i^{(\\ell)}} \\bP\\left(\\exists s \\leq t' : s \\times \\kl(\\widehat{\\mu}_{s},\\mu_i^{(\\ell)}) \\geq f(t')\\right) \\\\\n%     & \\leq \\sum_{t=1}^T \\frac{1}{t\\ln(t)} \\leq \\ln(\\ln(T)),\n% \\end{align*}%\n% %\n% where the last but one inequality relies on the concentration inequality given in Lemma 2 of \\cite{KLUCBJournal}, and the fact that $f(t) = \\ln(t) + 3 \\ln(\\ln(t))$. Finally, the law of total expectation gives\n% \\begin{equation}\n%     (A) \\leq \\sum_{i=1}^K \\sum_{\\ell=0}^{\\NCi}\\left[d_i^{(\\ell+1)}(T) + \\ln(\\ln(T))\\right].\n%     \\label{eq:6:TermAFinal}\n% \\end{equation}\n\n% \\paragraph{Upper bound on term $\\bm{(B)}$.}\n% %\n% Recall that $\\mu^*_{i,\\ell}$ is defined from the statement of Theorem~\\ref{thm:6:mainRegretBound} as the smallest value that still outperforms arm $i$ on the interval between the $\\ell$ and $(\\ell+1)$-st change of $i$. We let $\\tilde{\\mu}_{i,s}^{(\\ell)}$ denote the empirical mean of the first $s$ observations of arm $i$ made after time $t=\\hat{\\tau}_i^{(\\ell)}+1$. To upper bound Term B, we introduce a sum over all arms and rewrite the sum in $t$ as a sum of consecutive intervals $[\\tau_i^{(\\ell)}+1, \\tau_i^{(\\ell+1)}]$.\n% %\n% The decomposition follows by using furthermore that on $\\cE_T$, we have $\\tau_i^{\\ell} \\leq \\hat \\tau_i^ \\ell \\leq \\tau_i^{\\ell+1}$ for all changes, by Assumption~\\ref{ass:6:LongPeriods}.\n% %\n% \\begin{align*}\n%     (B) & \\leq \\sum_{i=1}^K\\bE\\Big[\\indic(\\cE_T)\\sum_{\\ell=1}^{\\NCi} \\sum_{t=\\tau_i^{(\\ell)}}^{\\tau_i^{(\\ell+1)}}\\left(\\mu_{i^*_t}(t) - \\overline{\\mu}_{i}^{(\\ell)}\\right)\\indic\\left(I_t = i, \\UCB_i(t) \\geq \\mu^*_{i,\\ell}\\right)\\Big] \\\\\n%     & \\leq \\sum_{i=1}^K\\sum_{\\ell=1}^{\\NCi}\\bE\\Big[\\indic(\\cE_T)\\hat{\\tau}_i^{(\\ell)} + \\indic(\\cE_T) \\sum_{t=\\widehat{\\tau}_i^{(\\ell)}+1}^{\\tau_i^{(\\ell+1)}}\\indic\\left(I_t = i, \\UCB_i(t) \\geq \\mu^*_{i,\\ell}\\right)\\Big] \\\\\n% %     & \\leq \\sum_{i=1}^K\\sum_{\\ell=1}^{\\NCi}d_i^{(\\ell)}+ \\sum_{\\ell=1}^{\\NCi}\\bE\\Big[\\indic(\\cE_T) \\sum_{t=\\hat{\\tau}_i^{(\\ell)}+1}^{\\tau_i^{(\\ell+1)}}\\sum_{s=1}^{t-\\widehat{\\tau}_i^{(\\ell)}}\\indic\\left(I_t = i,n_i(t) = s\\right) \\indic\\left(s \\times \\kl(\\tilde{\\mu}_{i,s}^{(\\ell)}, \\mu^*_{\\ell,i}) \\leq f(\\tau_i^{(\\ell+1)} - \\widehat{\\tau}_i^{(\\ell)})\\right)\\Big] \\\\\n%     & \\leq \\sum_{i=1}^K\\sum_{\\ell=1}^{\\NCi}d_i^{(\\ell)}+ \\sum_{i=1}^K\\sum_{\\ell=1}^{\\NCi}\\bE\\Big[\\indic(\\cC_i^{(\\ell)}) \\sum_{s=1}^{n_i(\\tau_i^{(\\ell+1)})}\\indic\\left(s \\times \\kl(\\tilde{\\mu}_{i,s}^{(\\ell)}, \\mu^*_{i,\\ell}) \\leq f(\\tau_i^{(\\ell+1)} - \\tau_i^{(\\ell)})\\right)\\Big].\n% \\end{align*}%\n% %\n% The last inequality relies on introducing a sum over $\\indic(n_i(t) = s)$ and swapping the sums. Conditionally to $\\cF_{\\widehat{\\tau}_i^{(\\ell)}}$, when $\\cC_i^{(\\ell)}$ holds, for $s \\in \\{1, \\ldots, n_i(\\tau_i^{(\\ell+1)})\\}$, $\\tilde{\\mu}_{i,s}^{(\\ell)}$ is the empirical mean from \\iid{} observations of mean $\\overline{\\mu}_i^{(\\ell)}$.\n% Therefore, introducing $\\widehat{\\mu}_s$ as a sequence of \\iid{} random variables with mean $\\overline{\\mu}_i^{(\\ell)}$, it follows from the law of total expectation that\n% %\n% \\begin{align*}\n%     (B) & \\leq \\sum_{i=1}^K\\sum_{\\ell=1}^{\\NCi} d_i^{(\\ell)}\n%     + \\sum_{i=1}^K\\sum_{\\ell=1}^{\\NCi} \\sum_{s=1}^{\\tau_i^{(\\ell+1)}-\\tau_i^{(\\ell)}} \\bP\\left(s \\times \\kl(\\widehat{\\mu}_{s}, \\mu^*_{i,\\ell}) \\leq f(\\tau_i^{(\\ell+1)} - \\tau_i^{(\\ell)})\\right).\n% \\end{align*}%\n% %\n% As $\\mu^*_{\\ell,i} > \\mu_i^{(\\ell)}$ by definition, we can use the same analysis as in the proof of Fact~2 in Appendix~A.2 of \\cite{KLUCBJournal} to show that\n% % \\begin{align*}\n% %     (B)_i & \\leq \\sum_{\\ell=1}^{\\NCi}d_i^{(\\ell)}+\\sum_{\\ell=1}^{\\NCi}\\left[ \\frac{\\ln(T) + 3\\ln\\ln(T)}{\\kl(\\mu_i^{(\\ell)}, \\mu^*_{\\ell,i})} + \\sqrt{\\frac{2\\pi(\\kl'(\\mu_i^{(\\ell)},\\mu^*_{\\ell,i}))^2}{(\\kl(\\mu_i^{(\\ell)}, \\mu^*_{\\ell,i}))^2}}\\sqrt{\\ln(T) + 3\\ln\\ln(T)} + 2\\left(\\frac{\\kl'(\\mu_i^{(\\ell)},\\mu^*_{\\ell,i})}{\\kl(\\mu_i^{(\\ell)}, \\mu^*_{\\ell,i})}\\right)^2\\right].\n% % \\end{align*}\n% \\begin{align}\\label{eq:6:TermBFinal}\n%     (B) & \\leq \\sum_{i=1}^K\\sum_{\\ell=1}^{\\NCi}d_i^{(\\ell)}+\\sum_{i=1}^K\\sum_{\\ell=1}^{\\NCi}\\left[ \\frac{\\ln(T) + 3\\ln\\ln(T)}{\\kl(\\overline{\\mu}_i^{(\\ell)},\\mu^*_{i,\\ell})} + O\\left(\\sqrt{\\log(T)}\\right)\\right].\n% \\end{align}\n% The result follows by combining the decomposition~\\eqref{eq:6:GeneRegretBound} with Lemma~\\ref{lem:6:GoodEvent} and the bounds \\eqref{eq:6:TermAFinal} and \\eqref{eq:6:TermBFinal}.\n\n\n% \\subsubsection{Proof of Lemma~\\ref{lem:6:GoodEvent}}\\label{proof:6:GoodEvent}\n\n% With the event $\\cC_i^{(\\ell)}$ defined in \\eqref{def:6:EventCi}, a simple union bound yields\n% \\begin{align*}\n%     \\bP(\\cE_T^c) & \\leq \\sum\\limits_{i=1}^K\\sum\\limits_{\\ell=1}^{\\NCi} \\underbrace{\\bP\\left(\\widehat{\\tau}_i^{(\\ell)} \\leq \\tau_i^{(\\ell)} \\;|\\; \\cC_i^{(\\ell-1)}\\right)}_{(a)} + \\sum\\limits_{i=1}^K\\sum\\limits_{\\ell=1}^{\\NCi} \\underbrace{\\bP\\left(\\widehat{\\tau}_i^{(\\ell)} \\geq \\tau_i^{(\\ell)} + d_i^{(\\ell)} \\;|\\; \\cC_i^{(\\ell-1)}\\right)}_{(b)}.\n% \\end{align*}\n\n% The final result follows by proving that the terms $(a)$ and $(b)$ are both upper bounded by $\\delta$.\n\n% \\paragraph{Upper bound on $(a)$: controlling the false alarms.}\n% Under the bandit algorithm, the change-point detector associated to arm $i$ is based on (possibly much) less than $t - \\tau_i(t)$ samples from arm $i$, which makes false alarm even less likely to occur. More precisely, we upper bound term $(a)$ by\n% %\n% \\begin{align*}\n%     (a) & \\leq \\bP\\left(\\exists s < t \\leq n_i(\\tau_i^{(\\ell)}) : s \\times \\kl\\left(\\tilde{\\mu}_{i,1:s}^{(\\ell-1)},\\tilde{\\mu}_{i,1:t}^{(\\ell-1)}\\right) + (t - s) \\times \\kl\\left(\\tilde{\\mu}_{i,s+1:t}^{(\\ell-1)},\\tilde{\\mu}_{i,1:t}^{(\\ell-1)}\\right) > \\beta(t, \\delta) \\;|\\; \\cC_i^{(\\ell-1)}\\right) \\\\\n%     & \\leq \\bP\\left(\\exists s < t : s \\times \\kl(\\widehat{\\mu}_{1:s},\\mu_i^{(\\ell-1)}) + (t - s) \\times \\kl(\\widehat{\\mu}_{s+1:t}, \\mu_{i}^{(\\ell-1)}) > \\beta(t, \\delta)\\right),\n% \\end{align*}\n% with $\\hat\\mu_{s:s'} = \\sum_{r=s}^{s'} Z_{i,r}$ where $Z_{i,r}$ is an \\iid{} sequence with mean $\\mu_i^{(\\ell-1)}$.\n% Indeed, conditionally to $\\cC_i^{(\\ell-1)}$, the $n_i(\\tau_i^{(\\ell)})$ successive observations of arm $i$ arm starting from $\\hat \\tau_i^{(\\ell)}$ are \\iid{} with mean $\\mu_i^{(\\ell-1)}$.\n% Using Lemma~\\ref{lem:6:ConcFirst}, term $(a)$ is upper bounded by $\\delta$.\n\n\n% \\paragraph{Upper bound on term $(b)$: controlling the delay.}\n% %\n% Controlling the detection delay on arm $i$ under an adaptive sampling scheme can be tricky. Here we need to leverage the forced exploration (Proposition~\\ref{prop:6:EnoughSamples}) to be sure we have enough samples to ensure detection: the effect is that delays will be scaled by the exploration parameter $\\omega$.\n\n% First, it follows from Proposition~\\ref{prop:6:EnoughSamples} that there exists $\\overline{t} \\in \\left\\{\\tau_i^{(\\ell)}, \\dots, \\tau_i^{(\\ell)} + d_i^{(\\ell)} \\right\\}$ such that\n% $n_i(\\overline{t}) - n_i(\\tau_i^{(\\ell)}) = \\overline{r}$ where $\\overline{r} = \\lfloor \\frac{\\omega}{K} d_i^{(\\ell)}\\rfloor$\n% (as the mapping $t\\mapsto n_i(t) - n_i(\\tau_i^{(\\ell)})$ is non-decreasing, is $0$ at $t=\\tau_i^{(\\ell)}$ and its value at $\\tau_i^{(\\ell)}+d_i^{(\\ell)}$ is larger than $\\overline{r}$).\n% Using that $(\\widehat{\\tau}_i^{(\\ell)} \\geq \\tau_i^{(\\ell)} + d_i^{(\\ell)}) \\subseteq (\\widehat{\\tau}_i^{(\\ell)} \\geq \\overline{t})$,\n% the event $(\\widehat{\\tau}_i^{(\\ell)} \\geq \\tau_i^{(\\ell)} + d_i^{(\\ell)})$ further implies that\n% \\[\n%     n_i(\\tau_i^{(\\ell)}) \\, \\kl\\left(\\tilde{\\mu}^{\\ell-1}_{i,n_i(\\tau_i^{(\\ell)})},\\tilde{\\mu}^{\\ell-1}_{i,n_i(\\overline{t})}\\right)\n%     +  \\overline{r} \\, \\kl\\left(\\tilde{\\mu}^{\\ell-1}_{i,n_i(\\tau_i^{(\\ell)}) : n_i(\\overline{t})},\\tilde{\\mu}^{\\ell-1}_{i,n_i(\\overline{t})}\\right) \\leq \\beta(n_i(\\tau_i^{(\\ell)}) + \\overline{r},\\delta),\n% \\]\n% where $\\tilde{\\mu}^{\\ell-1}_{i,s}$ denotes the empirical mean of the $s$ first observation of arm $i$ since the $(\\ell-1)$-th restart $\\hat{\\tau}_i^{(\\ell-1)}$ and  $\\tilde{\\mu}^{\\ell-1}_{i,s:s'}$ the empirical mean that includes observation number $s$ to number $s'$. Conditionally to $\\cC^{(\\ell-1)}_i$, $\\tilde{\\mu}^{\\ell-1}_{i,n_i(\\tau_i^{(\\ell)})}$ is the empirical mean of $n_i(\\tau_i^{(\\ell)})$ \\iid{} replications of mean $\\mu_i^{\\ell-1}$, whereas $\\tilde{\\mu}^{\\ell-1}_{i,n_i(\\tau_i^{(\\ell)}) : n_i(\\overline{t})}$ is the empirical mean of $\\overline{r}$ \\iid{} replications of mean $\\mu_i^{\\ell}$.\n\n% Moreover, due to Proposition~\\ref{prop:6:EnoughSamples}, $n_i(\\tau_i^{(\\ell)})$ lies in $\n% \\left\\{\\left\\lfloor \\frac{\\omega}{K}\\left(\\tau_i^{(\\ell)}-\\widehat{\\tau}_i^{(\\ell-1)}\\right)\\right\\rfloor, \\dots, \\tau_i^{(\\ell)}-\\widehat{\\tau}_i^{(\\ell-1)} \\right\\}$.\n% %\n% Conditionally to $\\cC_i^{(\\ell-1)}$, one obtains furthermore using that $d_i^{(\\ell-1)} \\leq (\\tau_i^{(\\ell)} - \\tau_i^{(\\ell-1)})/2$ -- which follows from Assumption~\\ref{ass:6:LongPeriods} -- that\n% \\begin{eqnarray*}\n%     n_i(\\tau_i^{(\\ell)})& \\in &  \\left\\{ \\left\\lfloor \\frac{\\omega}{K}\\left(\\tau_i^{(\\ell)}-\\tau_i^{(\\ell-1)} - d_i^{(\\ell-1)}\\right)\\right\\rfloor, \\dots, \\left(\\tau_i^{(\\ell)}-\\tau_i^{(\\ell-1)}\\right) \\right\\} \\\\\n%     n_i(\\tau_i^{(\\ell)})& \\in& \\left\\{ \\left\\lfloor \\frac{\\omega}{2K}\\left(\\tau_i^{(\\ell)}-\\tau_i^{(\\ell-1)}\\right)\\right\\rfloor, \\dots, \\left(\\tau_i^{(\\ell)}-\\tau_i^{(\\ell-1)}\\right) \\right\\} = \\cI_k.\n% \\end{eqnarray*}\n\n% Introducing $\\widehat{\\mu}_{a,s}$ (resp. $\\widehat{\\mu}_{b,s}$) the empirical mean of $s$ \\iid{} observations with mean $\\widehat{\\mu}_i^{(\\ell-1)}$ (resp. $\\widehat{\\mu}_i^{(\\ell)}$), such that $\\widehat{\\mu}_{a,s}$ and $\\widehat{\\mu}_{b,r}$ are independent, it follows that\n% \\[\n%     (b)  \\leq \\bP\\left(\\exists s \\in \\cI_k : s \\, \\kl\\left(\\widehat{\\mu}_{a,s},\\frac{s\\widehat{\\mu}_{a,s}+\\overline{r}\\widehat{\\mu}_{b,\\overline{r}}}{s+\\overline{r}} \\right) +  \\overline{r} \\, \\kl\\left(\\widehat{\\mu}_{b,\\overline{r}},\\frac{s\\widehat{\\mu}_{a,s}+\\overline{r}\\widehat{\\mu}_{b,\\overline{r}}}{s+\\overline{r}}  \\right)  \\leq \\beta(s+\\overline{r},\\delta)\\right),\n% \\]\n% where we have also used that $\\tilde{\\mu}^{\\ell-1}_{i,n_i(\\overline{t})} = \\frac{n_i(\\tau_i^{(\\ell)})\\tilde{\\mu}^{\\ell-1}_{i,n_i(\\tau_i^{(\\ell)})} + \\overline{r}\\tilde{\\mu}^{\\ell-1}_{i,n_i(\\tau_i^{(\\ell)}) : n_i(\\overline{t})}}{n_i(\\tau_i^{(\\ell)}) + \\overline{r}}$.\n\n% Using Pinsker's inequality, and introducing the gap $\\Delta_i^{(\\ell)} = \\mu_i^{(\\ell-1)} - {\\mu}_i^{(\\ell)}$, one can write\n% \\begin{align}\n%     (b) & \\leq \\bP\\left(\\exists s \\in \\cI_k : \\frac{2s\\overline{r}}{s+\\overline{r}}\\left(\\widehat{\\mu}_{a,s} - \\widehat{\\mu}_{b,\\overline{r}} \\right)^2  \\leq \\beta(s+\\overline{r},\\delta)\\right)\\nonumber\\\\\n%     & \\leq \\bP\\left(\\exists s \\in \\N : \\frac{2sr}{s+r}\\left(\\widehat{\\mu}_{a,s} - \\widehat{\\mu}_{b,s} - \\Delta_i^{(\\ell)}\\right)^2  \\geq \\beta(s+r,\\delta)\\right) \\nonumber\\\\\n%     & + \\bP\\left(\\exists s \\in \\cI_k : \\frac{2s\\overline{r}}{s+\\overline{r}}\\left(\\widehat{\\mu}_{a,s} - \\widehat{\\mu}_{b,\\overline{r}} - \\Delta_i^{(\\ell)}\\right)^2  \\leq \\beta(s+\\overline{r},\\delta), \\frac{2s\\overline{r}}{s+\\overline{r}}\\left(\\widehat{\\mu}_{a,s} - \\widehat{\\mu}_{b,\\overline{r}}\\right)^2  \\leq \\beta(s+\\overline{r},\\delta)\\right) \\nonumber\n% \\end{align}\n% %\n\n% Using Lemma~\\ref{lem:6:Chernoff2arms} stated in Appendix~\\ref{proof:6:Chernoff2arms}, and a union bound, the first term in the right hand side is upper bounded by $\\delta$ (as $\\beta(r+s,\\delta) \\geq \\beta(r,\\delta) \\geq \\log(3s\\sqrt{s}/\\delta)$). For the second term, we use the observation\n% \\[\\frac{2s \\; \\overline{r}}{s+\\overline{r}}\\left(\\widehat{\\mu}_{a,s} - \\widehat{\\mu}_{b,\\overline{r}} - \\Delta_i^{(\\ell)}\\right)^2  \\leq \\beta(s+\\overline{r},\\delta) \\ \\ \\Rightarrow \\ \\ |\\widehat{\\mu}_{a,s} - \\widehat{\\mu}_{b,\\overline{r}}| \\geq |\\Delta_i^{(\\ell)}| - \\sqrt{\\frac{s+\\overline{r}}{2\\overline{r}s}\\beta(s+\\overline{r},\\delta)}\\]\n% and finally get\n% %\n% \\begin{equation}\\label{eq:6:FromHere}\n%     (b) \\leq \\delta + \\bP\\left(\\exists s \\in \\cI_k : |\\Delta_i^{(\\ell)}| \\leq 2\\sqrt{\\frac{s+\\overline{r}}{2s\\overline{r}}\\beta(s+\\overline{r},\\delta)}\\right).\n% \\end{equation}\n% %\n% Define $s_{\\min} = \\left\\lfloor \\frac{\\omega}{K} (\\tau_i^{(\\ell)}-\\tau_i^{(\\ell-1)})/2\\right\\rfloor$. Using that the mappings $s \\mapsto (s+\\overline{r})/s\\overline{r}$ and $s \\mapsto \\beta(s + \\overline{r},\\delta)$ are respectively decreasing and increasing in $s$, one has, for all $s\\in \\cI_k$,\n% \\begin{eqnarray*}\n%     2\\frac{s+\\overline{r}}{s \\; \\overline{r}}\\beta\\left(s+\\overline{r}, \\delta\\right) & \\leq &\n%     2\\frac{s_{\\min}+\\overline{r}}{s_{\\min} \\; \\overline{r}}\\beta\\left(T, \\delta\\right) \\leq \\frac{4\\beta(T,\\delta)}{\\left\\lfloor \\frac{\\omega}{K}d_i^{(\\ell)}\\right\\rfloor},\n% \\end{eqnarray*}\n% %\n% where the last inequality follows from the fact that $\\overline{r} \\leq s_{\\min}$ as $d_i^{(\\ell)} \\leq (\\tau_i^{(\\ell)} - \\tau_i^{(\\ell-1)})/2$ by Assumption~\\ref{ass:6:LongPeriods}. Now the definition of $d_i^{(\\ell)}$ readily implies that\n% \\[\\left\\lfloor \\frac{\\omega}{K}d_i^{(\\ell)}\\right\\rfloor > 4\\beta(T,\\delta) / \\left(\\Delta_i^{(\\ell)}\\right)^2,\\]\n% which yields\n% \\[\\forall s \\in \\cI_k, \\ \\ 2\\frac{s+\\overline{r}}{s \\; \\overline{r}}\\beta\\left(s+\\overline{r}, \\delta\\right) \\leq \\left(\\Delta_i^{(\\ell)}\\right)^2.\\]\n% Hence, the probability in the right-hand side of \\eqref{eq:6:FromHere} is zero, which yields $(b) \\leq \\delta$.\n\n\n% % % -----------------------------------------------------------------\n% % % -----------------------------------------------------------------\n% \\subsection{Time and memory costs of \\GLRklUCB}\n% \\label{app:6:EmpiricalPerformances}\n\n% As demonstrated in Section~\\ref{sec:6:NumericalExperiments}, our proposal is empirically efficient in terms of regret, but it is important to also evaluate its cost in terms of both \\emph{time} and \\emph{memory}.\n% Remember that $\\Upsilon_T$ denotes the number of change-points.\n% If we denote $d_{\\max}$ the longest duration of a stationary sequence, for the question of the memory storage, the worst case is $d_{\\max} = T$ for a stationary problem, and the easiest case is $d_{\\max} \\simeq T / \\Upsilon_T$, typically obtained for $\\Upsilon_T$ evenly spaced change-points.\n% %\n% We begin by reviewing the costs of the algorithms designed for stationary problems and then of other approaches, similarly to what is presented in Section~\\ref{sec:3:timeAndMemoryCosts}.\n\n\n% \\textbf{Classical algorithms.}\n% %\n% For a stationary bandit problem, almost all \\emph{classical algorithms} (\\ie, designed for stationary problems) need and use a storage proportional to the number of arms, \\ie, $\\bigO{K}$, as most of them only need to store the number of pulls and the empirical mean of rewards for each arm.\n% They also have a time complexity $\\bigO{K}$ at every time step $t\\in[T]$, hence an optimal total time complexity of $\\bigO{KT}$.\n% In particular, this case includes \\UCB, Thompson sampling and \\klUCB.\n\n% \\textbf{Oracle algorithms.}\n% %\n% Most algorithms designed for abruptly changing environments are more costly, both in terms of storage and computation time, as they need more storage and time to test for changes.\n% The \\emph{oracle algorithm} presented in Section~\\ref{sec:6:NumericalExperiments}, combined with any efficient index policy, needs a storage at most $\\bigO{K \\Upsilon_T}$ as it stores the change-points, and have an optimal time complexity of $\\bigO{K T}$ too.\n% % \\footnote{Note that if implemented naively, that is if testing is $t$ is a change-points takes a time $\\bigO{\\Upsilon_T}$, its performance is sub-optimal, as it is of the order of $\\bigO{K T \\Upsilon_T}$. However, if the change-points are stored in a \\emph{dynamic linked list}, and the head is removed when it is found to be equal to the current time step, then the test at a time $t$ costs only a constant time $\\bigO{1}$, hence the total time complexity is bounded by $\\bigO{K T}$ and the oracle algorithm is indeed optimal in terms of time complexity.}.\n\n% \\textbf{Passively adaptive algorithms.}\n% %\n% Passively adaptive algorithms should intuitively be more efficient, but as they use a non-constant storage, they are actually as costly as the oracle.\n% For instance SW-UCB uses a storage of $\\bigO{K \\tau}$, increasing as $T$ increases, and similarly for other passively adaptive algorithms.\n% We highlight that to the best of our knowledge, the Discounted Thompson sampling algorithm (DTS) is the only algorithm tailored for abruptly changing problems that could be efficient in terms of regret (see the simulations results, even though it has no theoretical guarantee), and optimal in terms of both computational and storage costs. Indeed, it simply needs a storage proportional to the number of arms, $\\bigO{K}$, and a time complexity of $\\bigO{KT}$ for a horizon $T$ (see the pseudo-code in \\cite{RajKalyani17}).\n% % Note that the discounting scheme in Discounted-\\UCB{} (D-UCB) from \\cite{Kocsis06} requires to store the whole history, and not only empirical rewards of each arm, as after observing a reward, all previous rewards must be multiplied by $\\gamma^n$ if that arm was not seen for $n>0$ times. So the storage cannot be simply proportional to $K$, but needs to grow as $t$ grows. Therefore, D-UCB costs $\\bigO{K T}$ in memory and $\\bigO{K T^2}$ in time.\n\n\n% \\textbf{Actively adaptive algorithms.}\n% %\n% Limited memory actively adaptive algorithms, like \\MUCB, are even more costly.\n% For instance, \\MUCB{} would have the same cost of $\\bigO{K T d_{\\max}}$, except that \\cite{CaoZhenKvetonXie18} introduces a window-size $w$ and run their CPD algorithm only using the last $w$ observations of each arm. If $w$ is constant w.r.t. the horizon $T$, their algorithm has a storage cost bounded by $\\bigO{K w}$ and a running time of $\\bigO{K T w}$, being comparable to the cost $\\bigO{K T}$ of the oracle approach.\n% However in practice and in the theoretical results, the window size should depend on $T$, and a prior knowledge of the minimal change size $\\widehat{\\delta}$ (see Remark~1 in \\cite{CaoZhenKvetonXie18}), with $w = \\cO(\\log(T) / \\widehat{\\delta}^2)$.\n% Hence it makes more sense to consider that \\MUCB{} has a time cost bounded by $\\bigO{K T \\log(T)}$ and a memory costs bounded by $\\bigO{K \\log(T)}$, which is better than our proposal but more costly than the oracle or DTS or stationary algorithms.\n\n\n% \\paragraph{Time and memory cost of \\GLRklUCB.}\n% %\n% On the other hand, actively adaptive algorithms are more efficient (when tuned correctly) but at the price of being more costly, both in terms of time and memory.\n% The algorithms using the \\CUSUM{} or \\GLR{} tests (as well as \\PHT) are found to be efficient in terms of regret, when used with an efficient and low-cost index policy (that is, choosing the arm to play only costs $\\bigO{K}$ at any time $t$).\n% However, they need to store all past rewards and pulls history, to be able to reset them when the CPD algorithm indicates to do, so they have a memory cost of $\\bigO{K d_{\\max}}$, that is $\\bigO{K T}$ in the worst case (compared to $\\bigO{K}$ for algorithms designed for the stationary setting).\n% %\n% They are also costly in terms of computation time, as at current time $t$, when trying to detect a change with $n_i$ observations of arm $i$ (\\ie, $(Z_{i,n})_{1\\leq n \\leq n_i}$ in Algorithm~\\ref{algo:6:GLRklUCB}), the CPD algorithm (\\CUSUM{} or \\GLR) costs a time $\\bigO{n_i}$.\n% Indeed, it needs to compute sliding averages for every $s$ in an interval of size $n_i$ (\\ie, $\\mu_{\\text{left}}=\\mu_{1:s}$ and $\\mu_{\\text{right}}=\\mu_{s+1:n_i}$) and a test for each $s$ which costs a constant time $\\bigO{1}$ (\\eg, computing two $\\kl$ and checking for a threshold for our \\GLR{} test).\n% So for every $s$, the running time is $\\bigO{1}$, if the sliding averages are computed iteratively based on a simple scheme: first, one compute the total average $\\mu_{t_0:t}$ and set $\\mu_{\\text{left}}=0$ and $\\mu_{\\text{right}}=\\mu_{t_0:t}$. Then for every successive values of $s$, both the left and right sliding window means can be updated with a single memory access and two computations (\\ie, $\\bigO{1}$):\n% %\n% \\begin{equation}\n%     z \\leftarrow Z_{i, s + 1},\\,\\,\n%     \\mu_{\\text{left}} \\leftarrow \\frac{s \\mu_{\\text{left}} + z}{s + 1},\\,\\,\n%     \\mu_{\\text{right}} \\leftarrow \\frac{(n_i + 1 - s) \\mu_{\\text{right}} - z}{n_i - s},\\,\\,\n%     s \\leftarrow s + 1.\n% \\end{equation}\n% %\n% To sum up, at every time step the CPD algorithm needs a time $\\bigO{n_i}=\\bigO{d_{\\max}}$, and at the end, the time complexity of \\CUSUMklUCB{} as well as \\GLRklUCB{} is $\\bigO{K T d_{\\max}}$, which can be up-to $\\bigO{K T^2}$, much more costly than $\\bigO{K T}$ for \\klUCB{} for instance.\n\n% Our proposal \\GLRklUCB{} requires a storage of the order of $\\bigO{K d_{\\max}}$ and a running time of the order of $\\bigO{K T d_{\\max}}$, and the two bounds are validated experimentally, see Table~\\ref{table:6:TimeCosts}.\n\n% % \\TODOL{Also for detection delay? Also for false alarm probability?}\n\n\n% \\paragraph{Empirical measurements of computation times and memory costs.}\n% %\n% A theoretical analysis shows that there is a large gap between the costs of stationary or passively adaptive algorithms,\n% and the costs of actively adaptive algorithms, for both computation time and memory consumption.\n% % because the later need to store a large number of rewards and pulls history, while the first can keep a storage that grows as $\\bigO{K}$ independently on the horizon.\n% %\n% We include here an extensive comparison of memory costs of the different algorithms.\n% %\n% For instance on the same experiment as the one used for Table~\\ref{table:6:effectOptimizations}, that is problem 1 with $T=5000$, and then with $T=10000$ and $T=20000$, and $100$ independent runs,\n% in our Python implementation (using the SMPyBandits library, \\cite{SMPyBandits}), we can measure the (mean) real memory cost\\footnote{We used one core of an Intel $i5$ Core CPU, with GNU/Linux Ubuntu $18.04$, Python v$3.6$, and $8$ Gb of RAM.} of the different algorithms.\n% The Tables~\\ref{table:6:TimeCosts} and \\ref{table:6:MemoryCosts} included below give the mean ($\\pm$ 1 standard-deviation) of real computation time and memory consumption, used by the algorithms.\n% The computation time is normalized by the horizon, to reflect the (mean) time used for each time steps $t\\in[T]$.\n% %\n% We also found that our two optimizations described below in \\ref{sub:6:IdeasOptimizations} do not reduce the memory, thus we used $\\Delta n = \\Delta s = 20$ to speed-up the simulations.\n% %\n% The conclusions to draw for these two Tables~\\ref{table:6:TimeCosts} and \\ref{table:6:MemoryCosts} are twofold.\n\n\n% % \\begin{small} %XXX WARNING\n% \\begin{table}[ht]\n%     % \\begin{small} %XXX WARNING\n%     \\centering\n%     \\begin{tabular}{c|cccccc}\n%     \\textbf{Algorithms} & $T=5000$ & $T=10000$ & $T=20000$ \\\\\n%         \\hline\n%         Thompson sampling & \\textbf{\\SI{55}{\\micro\\second} $\\pm$ \\SI{11}{\\micro\\second}} & \\textbf{\\SI{51}{\\micro\\second} $\\pm$ \\SI{6}{\\micro\\second}} & \\textbf{\\SI{49}{\\micro\\second} $\\pm$ \\SI{4}{\\micro\\second}} \\\\\n%         DTS & \\SI{62}{\\micro\\second} $\\pm$ \\SI{11}{\\micro\\second} & \\SI{60}{\\micro\\second} $\\pm$ \\SI{8}{\\micro\\second} & \\SI{59}{\\micro\\second} $\\pm$ \\SI{7}{\\micro\\second} \\\\\n%         \\hline\n%         \\klUCB{} & \\SI{122}{\\micro\\second} $\\pm$ \\SI{13}{\\micro\\second} & \\SI{125}{\\micro\\second} $\\pm$ \\SI{13}{\\micro\\second} & \\SI{128}{\\micro\\second} $\\pm$ \\SI{11}{\\micro\\second} \\\\\n%         Discounted-\\klUCB{} & \\SI{94}{\\micro\\second} $\\pm$ \\SI{10}{\\micro\\second} & \\SI{97}{\\micro\\second} $\\pm$ \\SI{12}{\\micro\\second} & \\SI{103}{\\micro\\second} $\\pm$ \\SI{12}{\\micro\\second} \\\\\n%         SW-\\klUCB{} & \\SI{162}{\\micro\\second} $\\pm$ \\SI{21}{\\micro\\second} & \\SI{169}{\\micro\\second} $\\pm$ \\SI{18}{\\micro\\second} & \\SI{167}{\\micro\\second} $\\pm$ \\SI{12}{\\micro\\second} \\\\\n%         \\hline\n%         Oracle-Restart \\klUCB{} & \\SI{159}{\\micro\\second} $\\pm$ \\SI{31}{\\micro\\second} & \\SI{157}{\\micro\\second} $\\pm$ \\SI{21}{\\micro\\second} & \\SI{149}{\\micro\\second} $\\pm$ \\SI{15}{\\micro\\second} \\\\\n%         \\hline\n%         \\MklUCB{} & \\SI{202}{\\micro\\second} $\\pm$ \\SI{25}{\\micro\\second} & \\SI{220}{\\micro\\second} $\\pm$ \\SI{26}{\\micro\\second} & \\SI{230}{\\micro\\second} $\\pm$ \\SI{19}{\\micro\\second} \\\\\n%         \\CUSUMklUCB{} & \\SI{264}{\\micro\\second} $\\pm$ \\SI{53}{\\micro\\second} & \\SI{227}{\\micro\\second} $\\pm$ \\SI{31}{\\micro\\second} & \\SI{270}{\\micro\\second} $\\pm$ \\SI{33}{\\micro\\second} \\\\\n%         \\GLRklUCB{} & \\SI{314}{\\micro\\second} $\\pm$ \\SI{50}{\\micro\\second} & \\SI{399}{\\micro\\second} $\\pm$ \\SI{33}{\\micro\\second} & \\SI{920}{\\micro\\second} $\\pm$ \\SI{180}{\\micro\\second}\n%     \\end{tabular}\n%     \\caption{\\textbf{Normalized} computation time, for each time step $t\\in[T]$, for different horizons.}\n%     \\label{table:6:TimeCosts}\n%     % \\end{small} %XXX WARNING\n% \\end{table}\n% % \\end{small} %XXX WARNING\n\n% % \\begin{small} %XXX WARNING\n% \\begin{table}[ht]\n%     % \\begin{small} %XXX WARNING\n%     \\centering\n%     \\begin{tabular}{c|cccccc}\n%     \\textbf{Algorithms} & $T=5000$ & $T=10000$ & $T=20000$ \\\\\n%         \\hline\n%         Thompson sampling & \\SI{813}{\\byte} $\\pm$ \\SI{63}{\\byte} & \\SI{819}{\\byte} $\\pm$ 27 B & \\SI{818}{\\byte} $\\pm$ \\SI{35}{\\byte} \\\\\\\n%         DTS & \\SI{946}{\\byte} $\\pm$ \\SI{38}{\\byte} & \\SI{946}{\\byte} $\\pm$ \\SI{38}{\\byte} & \\SI{946}{\\byte} $\\pm$ \\SI{39}{\\byte} \\\\\n%         \\hline\n%         \\klUCB{} & \\SI{937}{\\byte} $\\pm$ \\SI{164}{\\byte} & \\SI{931}{\\byte} $\\pm$ \\SI{172}{\\byte} & \\SI{933}{\\byte} $\\pm$ \\SI{164}{\\byte} \\\\\n%         Discounted-\\klUCB{} & \\SI{1}{\\kibi\\byte} $\\pm$ \\SI{79}{\\byte} & \\SI{1}{\\kibi\\byte} $\\pm$ \\SI{94}{\\byte} & \\SI{1}{\\kibi\\byte} $\\pm$ \\SI{78}{\\byte} \\\\\n%         SW-\\klUCB{} & \\SI{6}{\\kibi\\byte} $\\pm$ \\SI{976}{\\byte} & \\SI{8}{\\kibi\\byte} $\\pm$ \\SI{1}{\\kibi\\byte} & \\SI{12}{\\kibi\\byte} $\\pm$ \\SI{2}{\\kibi\\byte} \\\\\n%         \\hline\n%         Oracle-Restart \\klUCB{} & \\SI{11}{\\kibi\\byte} $\\pm$ \\SI{3}{\\kibi\\byte} & \\SI{19}{\\kibi\\byte} $\\pm$ \\SI{7}{\\kibi\\byte} & \\SI{31}{\\kibi\\byte} $\\pm$ \\SI{17}{\\kibi\\byte} \\\\\n%         \\hline\n%         \\MklUCB{} & \\SI{4}{\\kibi\\byte} $\\pm$ \\SI{1}{\\kibi\\byte} & \\SI{6}{\\kibi\\byte} $\\pm$ \\SI{2}{\\kibi\\byte} & \\SI{9}{\\kibi\\byte} $\\pm$ \\SI{4}{\\kibi\\byte} \\\\\n%         \\CUSUMklUCB{} & \\SI{8}{\\kibi\\byte} $\\pm$ \\SI{4}{\\kibi\\byte} & \\SI{11}{\\kibi\\byte} $\\pm$ \\SI{6}{\\kibi\\byte} & \\SI{15}{\\kibi\\byte} $\\pm$ \\SI{10}{\\kibi\\byte} \\\\\n%         \\GLRklUCB{} & \\SI{19}{\\kibi\\byte} $\\pm$ \\SI{7}{\\kibi\\byte} & \\SI{32}{\\kibi\\byte} $\\pm$ \\SI{15}{\\kibi\\byte} & \\SI{75}{\\kibi\\byte} $\\pm$ \\SI{26}{\\kibi\\byte}\n%     \\end{tabular}\n%     \\caption{\\textbf{Non normalized} memory costs, for the same problem (Pb 1) with different horizons.}\n%     \\label{table:6:MemoryCosts}\n%     % \\end{small} %XXX WARNING\n% \\end{table}\n% % \\end{small} %XXX WARNING\n\n\n% First, we verify the results stated above for the time complexity of different algorithms, implemented in Python using SMPyBandits \\cite{SMPyBandits}.\n% The methodology of time and memory measurements is discussed in Section~\\ref{sec:3:timeAndMemoryCosts}.\n% On the one hand, stationary and passively adaptive algorithms all have a time complexity scaling as $\\bigO{T}$, as their normalized computation time is almost constant w.r.t. $T$.\n% We check that TS and DTS are the fastest algorithms, $2.5$ to $3$ times faster than \\klUCB-based algorithms, due to the fact that sampling from a Beta posterior is typically faster than doing a (small) numerical optimization step to compute the $\\sup$ in the \\klUCB{} indexes.\n% We also check that the passively adaptive algorithms add a non-trivial but constant overhead on the computation times of their based algorithm, \\eg, SW-\\klUCB{} compared to \\klUCB, or DTS compared to TS.\n% On the other hand, we also check that actively adaptive algorithms are most costly.\n% \\MklUCB{} normalized computation time is not increasing much when the horizon is doubled, as the window-size $M$ was set to a constant w.r.t. the horizon $T$ for this experiment.\n% The complexity of \\GLRklUCB{} follows the $\\bigO{K T^2}$ bound we presented above.\n\n% Second, we also verify the results for the memory costs of the different algorithms.\n% Similarly, stationary and passively adaptive algorithms based on a discount factor (D-UCB, DTS) have a memory cost constant w.r.t. the horizon $T$, as stated above,\n% while algorithms based on a sliding-window have a memory cost increasing w.r.t. the horizon $T$.\n% The Oracle-Restart and the actively adaptive algorithms see their memory costs increase similarly.\n% These measurements validate the upper-bound we gave on their memory costs, $\\bigO{K d_{\\max}}$, as $d_{\\max} \\simeq T / \\Upsilon$ for this problem with evenly spaced change-points.\n\n\n%-----------------------------------------------------------------------------\n\\subsection{Two numerical optimization tricks for \\GLRklUCB}\\label{sub:6:IdeasOptimizations}\n\nAs the main weakness of \\GLRklUCB{} is its numerical efficiency,\n%  as shown in Table~\\ref{table:6:TimeCosts},\n% In order to empirically improve\nwe suggest here two simple ideas to drastically speed-up its computation time.\n\n\\begin{enumerate}\n    \\item\n    The \\emph{first optimization}, parameterized by a constant $\\Delta n \\in\\N^*$, is the following idea.\n    We can test for statistical changes not at all time steps $t\\in[T]$ but only every $\\Delta n$ time steps (\\ie, for $t$ satisfying $t \\mod \\Delta n = 0$).\n    In practice, instead of sub-sampling for the \\emph{time} $t$, we propose to sub-sample for the number of samples of arm $i$ before calling \\GLR{} to check for a change on arm $i$, that is, $n_i(t)$ in Algorithm~\\ref{algo:6:GLRklUCB}.\n    %\n    Note that the first heuristic using $\\Delta n$ can be applied to \\MUCB{} as well as \\CUSUM-\\UCB{} and \\PHT-\\UCB{}, with similar speed-up and typically leading to similar consequences on the algorithm performance.\n\n    \\item\n    The \\emph{second optimization} is in the same spirit, and uses a parameter $\\Delta s \\in\\N^*$.\n    When running the \\GLR{} test with data $Z_1,\\dots,Z_t$, instead of considering every splitting time steps $s\\in[t]$, in the same spirit, we can skip some and test not at all time steps $s$ but only every $\\Delta s$ time steps.\n\\end{enumerate}\n\n% DONE Include precise reference to the point in the previous section when Emilie introduced this idea mathematically, with the sub-sampling ideas for $\\cT$ and $\\cS_t$\n\nThe new \\GLR{} test is using the stopping time $\\widetilde{T_\\delta}$ defined in \\eqref{def:6:GLRTricks},\nwith $\\cT = \\{t \\in [T], t \\mod \\Delta n = 0\\}$\nand $\\cS_t = \\{s \\in [t], s \\mod \\Delta s = 0\\}$.\nThe goal is to speed up the computation time of every call to the \\GLR{} test (\\eg, choosing $\\Delta s = 10$, every call should be about $10$ times faster), and to speed up the overhead cost of running the tests on top of the index policy (\\klUCB), by testing for changes \\emph{less} often (\\eg, choosing $\\Delta n = 10$ should speed up the all computation by a factor $10$).\n\n\n\\paragraph{Empirical validation of these optimization tricks.}\n%\nWe consider the problem 1 presented above (Figure~\\ref{fig:6:Problem_1}), with $T=5000$ and $100$ repetitions, and we give the means ($\\pm$ 1 standard-deviation) of both regret and computation time of \\GLRklUCB{} with \\textbf{Local} restarts, for different parameters $\\Delta n$ and $\\Delta s$, in Table~\\ref{table:6:effectOptimizations} below.\nThe other parameters of \\GLRklUCB{} are chosen as $\\delta = 1/\\sqrt{K \\Upsilon_T T}$ and $\\omega = 0.1\\sqrt{K\\log(T)/T}$ (from Corollary~\\ref{cor:6:Local}).\nThe algorithm analyzed in Section~\\ref{sec:6:RegretAnalysis} corresponds to $\\Delta n = \\Delta s = 1$.\n\n% \\begin{small} %XXX WARNING\n\\begin{table}[!h]\n    % \\begin{small} %XXX WARNING\n    \\centering\n    % \\begin{minipage}[b]{0.49\\linewidth}\\centering\n        \\begin{tabular}{c|cccc}\n            $\\Delta n$ $\\;$ \\textbackslash $\\;$ $\\Delta s$ & $1$ & $5$ & $10$ & $20$ \\\\\n            \\hline\n            $1$ & $44 \\pm 29$ & $44 \\pm 28$ & $50 \\pm 31$ & $53 \\pm 28$ \\\\\n            $5$ & $48 \\pm 29$ & $41 \\pm 30$ & $44 \\pm 28$ & $47 \\pm 31$ \\\\\n            $10$ & $51 \\pm 32$ & $43 \\pm 26$ & $47 \\pm 28$ & $46 \\pm 29$ \\\\\n            $20$ & $46 \\pm 31$ & $46 \\pm 34$ & $46 \\pm 31$ & $49 \\pm 31$\n        \\end{tabular}\n    % \\end{minipage}\n    \\hspace{0.5cm}\n\n    % \\begin{minipage}[b]{0.49\\linewidth}\\centering\n        \\begin{tabular}{c|cccc}\n            % \\backslashbox{$\\Delta n$}{$\\Delta s$}\n            $\\Delta n$ $\\;$ \\textbackslash $\\;$ $\\Delta s$\n            & $1$ & $5$ & $10$ & $20$ \\\\\n            \\hline\n            $1$ & \\textbf{\\SI{50}{\\second} $\\pm$ \\SI{4.5}{\\second}} & \\SI{11.1}{\\second} $\\pm$ \\SI{1.2}{\\second} & \\SI{5.8}{\\second} $\\pm$ \\SI{0.5}{\\second} & \\SI{3.3}{\\second} $\\pm$ \\SI{0.3}{\\second} \\\\\n            $5$ & \\SI{17.9}{\\second} $\\pm$ \\SI{1.6}{\\second} & \\SI{5.08}{\\second} $\\pm$ \\SI{3.3}{\\second} & \\SI{2.5}{\\second} $\\pm$ \\SI{0.3}{\\second} & \\SI{1.7}{\\second} $\\pm$ \\SI{0.2}{\\second}  \\\\\n            $10$ & \\SI{14.9}{\\second} $\\pm$ \\SI{1.9}{\\second} & \\SI{3.47}{\\second} $\\pm$ \\SI{0.4}{\\second} & \\SI{2.1}{\\second} $\\pm$ \\SI{0.2}{\\second} & \\SI{1.4}{\\second} $\\pm$ \\SI{0.2}{\\second} \\\\\n            $20$ & \\SI{12.1}{\\second} $\\pm$ \\SI{1.1}{\\second} & \\SI{3.02}{\\second} $\\pm$ \\SI{0.3}{\\second} & \\SI{1.9}{\\second} $\\pm$ \\SI{0.2}{\\second} & \\textbf{\\SI{0.2}{\\second} $\\pm$ \\SI{0.1}{\\second}}\n        \\end{tabular}\n    % \\end{minipage}\n    \\caption{Effects of the two optimizations parameters $\\Delta n$ and $\\Delta s$, on the mean regret $R_T$ (top) and mean computation time (bottom) for \\GLRklUCB{} on a simple problem. Using the optimizations with $\\Delta n = \\Delta s = 20$ does not reduce the regret much but speeds up the computations by about a \\textbf{factor} $\\mathbf{50}$.}\n    \\label{table:6:effectOptimizations}\n    % \\end{small} %XXX WARNING\n\\end{table}\n% \\end{small} %XXX WARNING\n\nOn the same problem,\nthe Oracle-Restart \\klUCB{} obtained a mean regret of $37$ for a running time of \\SI{711}{\\milli\\second},\nwhile \\klUCB{} obtained a regret of $270$ for a time of \\SI{587}{\\milli\\second}.\nIn comparison with the two other efficient approaches, M-\\klUCB{} obtained a regret of $290$ for a time of \\SI{943}{\\milli\\second},\nand \\CUSUMklUCB{} obtained a regret of $148$ for a time of \\SI{46}{\\second}.\n%\nThis shows that our proposal is very efficient compared to stationary algorithms, and comparable to the state-of-the-art actively adaptive algorithm.\nMoreover, this shows that two heuristics efficiently speed-up the computation times of \\GLRklUCB.\nChoosing small values, like $\\Delta n = 20, \\Delta s = 20$, can speed-up \\GLRklUCB, making it fast enough to be comparable to recent efficient approaches like \\MUCB{} and even comparable to the oracle policy.\n%\nIt is very satisfying to see that these optimizations do not reduce much the regret of \\GLRklUCB, as it still outperforms most state-of-the-art algorithms, and significantly reduces the computation time as wanted.\nWith such numerical optimization, \\GLRklUCB{} is not significantly slower than \\klUCB{} while being much more efficient for piece-wise stationary problems.\n\n\n% % ----------------------------------------------------------------------------\n% \\subsection{Sensitivity analysis of the exploration probability $\\omega$}\\label{sec:6:choosingAlpha0}\n\n% As demonstrated in our experiments in Section~\\ref{sec:6:NumericalExperiments},\n% the choice of $\\omega=\\omega_0\\sqrt{\\Upsilon_T\\log(T)/T}$ for the exploration probability is a good choice for \\GLRklUCB{} to be efficient (for the \\textbf{local restarts} option).\n% The dependency w.r.t. the horizon $T$ comes from Corollary~\\ref{cor:6:Local} when $\\Upsilon_T$ is unknown, and we observe in the Table~\\ref{table:6:sensibilityAlpha0} below that the value of $\\omega_0$ does not influence much the performance, as long as $\\omega_0\\leq1$.\n% Different values of $\\omega_0$ are explored, for problems $1$, $2$ and $4$, and we average the results over $100$ independent runs.\n% Other parameters are set to \\textbf{Local} restarts, $\\delta_T=1/\\sqrt{\\Upsilon_T T}$, and $\\Delta n = \\Delta s = 10$ to speed-up the experiments.\n% %\n% In the three experiments, \\GLRklUCB{} performs closely to the Oracle-Restart \\klUCB{}, and outperforms all or almost all the other approaches, for all choices of $\\omega_0$.\n% We observe in Table~\\ref{table:6:sensibilityAlpha0} that the parameter $\\omega_0$ does not have a significative impact on the performance,\n% and that surprisingly, choosing $\\omega_0 = 0$ does not reduce the empirical performance of \\GLRklUCB, which means that on some problems there is no need of a forced exploration.\n% However, the analysis of \\GLRklUCB{} is based on the forced exploration, and we found that for a larger number of arms, or for problems when the optimal arm change constantly, the forced exploration is required.\n% %\n% The same observations can be made for other variants of our algorithm, for instance with \\textbf{Global} restarts, or other values of $\\Delta n$, $\\Delta s$, or other values of $\\delta$.\n\n% % \\begin{small} %XXX WARNING\n% \\begin{table}[ht]\n%     % \\begin{small} %XXX WARNING\n%     \\centering\n%     \\begin{tabular}{l|cccccc}\n%         \\textbf{Choice of} $\\omega_0$ & Problem $1$ & Problem $2$ & Problem $4$ \\\\\n%         \\hline\n%         $\\omega_0=1$     & $51 \\pm 29$ & $79 \\pm 35$ & $82 \\pm 45$ \\\\\n%         $\\omega_0=0.5$   & $38 \\pm 29$ & $70 \\pm 35$ & $76 \\pm 39$ \\\\\n%         $\\omega_0=0.1$   & $33 \\pm 29$ & $69 \\pm 31$ & $68 \\pm 32$ \\\\\n%         $\\mathbf{\\omega_0=0.05}$  & $\\mathbf{36 \\pm 29}$ & $\\mathbf{65 \\pm 33}$ & $\\mathbf{67 \\pm 36}$ \\\\\n%         $\\omega_0=0.01$  & $38 \\pm 33$ & $66 \\pm 33$ & $71 \\pm 37$ \\\\\n%         $\\omega_0=0.005$ & $40 \\pm 27$ & $69 \\pm 30$ & $73 \\pm 56$ \\\\\n%         $\\omega_0=0.001$ & $38 \\pm 30$ & $69 \\pm 34$ & $67 \\pm 34$ \\\\\n%         $\\omega_0=0$     & $36 \\pm 32$ & $66 \\pm 36$ & $67 \\pm 33$\n%     \\end{tabular}\n%     \\caption{Mean regret $\\pm$ $1$ std-dev, for different choices of scaling factor for the forced exploration probability $\\omega_0\\in[0,1]$ (\\ie, $\\omega=\\omega_0 \\omega_T$), on three problems of horizon $T=5000$, for \\GLRklUCB{} with \\textbf{local restarts}, with $\\omega_T = \\omega_0\\sqrt{\\Upsilon_T \\log(T)/T}$.}\n%     \\label{table:6:sensibilityAlpha0}\n%     % \\end{small} %XXX WARNING\n% \\end{table}\n% % \\end{small} %XXX WARNING\n\n\n% % ----------------------------------------------------------------------------\n% \\subsection{Sensitivity analysis of the confidence level $\\delta$}\\label{sec:6:choosingDelta}\n\n% Similarly, the choice of $\\delta=\\delta_0 / \\sqrt{\\Upsilon_T T}$ for the confidence level is a good choice for \\GLRklUCB{} to be efficient (for the \\textbf{local restarts} option).\n% The dependency w.r.t. the horizon $T$ comes from Corollary~\\ref{cor:6:Local} when $\\Upsilon_T$ is unknown, and we observe in the Table~\\ref{table:6:sensibilityDelta} below that the value of $\\delta_0$ does not influence much the performance of our proposal, as long as $\\delta_0\\leq1$.\n% Different values of $\\delta_0$ are explored, for problems $1$, $2$ and $4$, and we average the results over $100$ independent runs.\n% Other parameters are set to \\textbf{Local} restarts, $\\omega_T = 0.1 \\sqrt{\\Upsilon_T\\log(T)/T}$, and $\\Delta n = \\Delta s = 10$ to speed-up the experiments.\n% %\n% We observe in Table~\\ref{table:6:sensibilityDelta} that the parameter $\\delta_0$ has no significative impact on the performance,\n% and that choosing $\\delta_0 = 1$ is indeed a valid choice.\n% Inspired by Occam's razor, we recommend this choice of $\\delta_0=1$ in practice.\n% %\n% The same observations can be made for other variants of our algorithm, for instance with \\textbf{Global} restarts, or other values of $\\Delta n$, $\\Delta s$, or other values of $\\omega$.\n\n% % \\begin{small} %XXX WARNING\n% \\begin{table}[ht]\n%     % \\begin{small} %XXX WARNING\n%     \\centering\n%     \\begin{tabular}{l|cccccc}\n%         \\textbf{Choice of} $\\delta_0$ & Problem $1$ & Problem $2$ & Problem $4$ \\\\\n%         \\hline\n%         $\\delta_0=1000$       & $\\mathbf{65 \\pm 31}$ & $106 \\pm 35$ & $\\mathbf{93 \\pm 34}$ \\\\\n%         $\\delta_0=500$        & $70 \\pm 28$ & $104 \\pm 35$ & $94 \\pm 33$ \\\\\n%         $\\delta_0=100$        & $72 \\pm 32$ & $105 \\pm 34$ & $95 \\pm 32$ \\\\\n%         $\\delta_0=50$         & $72 \\pm 32$ & $112 \\pm 31$ & $94 \\pm 31$ \\\\\n%         $\\delta_0=10$         & $75 \\pm 32$ & $107 \\pm 31$ & $97 \\pm 33$ \\\\\n%         $\\delta_0=5$          & $76 \\pm 31$ & $\\mathbf{103 \\pm 30}$ & $97 \\pm 32$ \\\\\n%         \\textcolor{blue}{$\\delta_0=1$}  & $72 \\pm 32$ & $111 \\pm 30$ & $96 \\pm 31$ \\\\\n%         $\\delta_0=0.5$        & $72 \\pm 30$ & $117 \\pm 35$ & $97 \\pm 31$ \\\\\n%         $\\delta_0=0.1$        & $70 \\pm 29$ & $111 \\pm 29$ & $99 \\pm 32$ \\\\\n%         $\\delta_0=0.05$       & $68 \\pm 29$ & $116 \\pm 37$ & $101 \\pm 30$ \\\\\n%         $\\delta_0=0.01$       & $74 \\pm 29$ & $114 \\pm 32$ & $101 \\pm 32$ \\\\\n%         $\\delta_0=0.005$      & $76 \\pm 26$ & $114 \\pm 34$ & $101 \\pm 31$ \\\\\n%         $\\delta_0=0.001$      & $76 \\pm 29$ & $117 \\pm 34$ & $102 \\pm 32$\n%     \\end{tabular}\n%     \\caption{Mean regret $\\pm$ $1$ std-dev, for different choices of scaling factor for the confidence level $\\delta_0$ (\\ie, $\\delta=\\delta_0 \\delta_T$), on three problems of horizon $T=5000$, for \\GLRklUCB{} with $\\delta=\\delta_0 / \\sqrt{\\Upsilon_T T}$.}\n%     \\label{table:6:sensibilityDelta}\n%     % \\end{small} %XXX WARNING\n% \\end{table}\n% % \\end{small} %XXX WARNING\n\n\n% ----------------------------------------------------------------------------\n\\subsection{Comparison of different threshold functions $\\beta$}\\label{sec:6:exploringDifferentThresholdFunctions}\n\n% In only one or two short numerical experiment, for example Pb 1 and 2, I can present in a table the regret obtained by \\GLRklUCB, both local and global or only local, for different values of the threshold functions.\n%\n% This is already coded, see https://smpybandits.github.io/docs/Policies.GLR_UCB.html?highlight=glr#Policies.GLR_UCB.threshold_BernoulliGLR\n\nWe compare different threshold functions, $\\beta_i(n,\\delta)$ for $i\\in\\{1,2,3,4\\}$, that can be used in the B-GLRT test used for the \\GLRklUCB{} algorithm (see the details in equation \\eqref{eq:whenDoesGLRklUCBrestart} and in Algorithm~\\ref{algo:6:GLRklUCB}).\n%\nIn the B-GLRT test, there is a $\\sup$ optimization problem on $s\\in[n-1]$, and this $\\sup$ is compared with the threshold $\\beta(n,\\delta)$. The threshold function given in \\eqref{def:6:beta} was chosen to obtain Lemma~\\ref{lem:6:FalseAlarm}, that is a false alarm probability bounded by $\\delta$.\n%\nWe note that we also considered the possibility of using a threshold that could be a function of both $n$ the sample size as well as $s\\in[n-1]$ the ``splitting index'' between means $\\widehat{\\mu}_{1:s}$ and $\\widehat{\\mu}_{s+1:n}$.\nWe did some preliminary experiments to explore this direction and did not find a significant difference, in terms of numerical efficient of the resulting \\GLRklUCB{} algorithm, and mathematically the analysis presented in Section~\\ref{subsec:6:PropGLR} is simpler to follow if the threshold are uniform on $s$.\n\n% \\begin{enumerate}%\\tightlist\n\\begin{enumerate}[label=$\\beta_{\\arabic*}$]\n    \\item\n    The first variant is the one we advised to use in practice for \\GLRklUCB,\n    it is very simple to compute numerically: $\\beta_1(n, \\delta) \\eqdef \\log\\left(\\frac{3 n^{3/2}}{\\delta}\\right) = -\\log(\\delta) + \\log(3) + 3/2 \\log(n)$.\n\n    \\item\n    The second variant is smaller without this power $3/2$: $\\beta_2(n, \\delta) \\eqdef \\log\\left(\\frac{1}{\\delta}\\right) + \\log(1 + \\log(n))$.\n\n    \\item\n    The third variant is using the function $\\cT$, as introduced by \\eqref{def:6:function_T}.\n    The function $\\cT$ is computed with a numerical approximation\\footnote{~The Lambert $\\cW$ function is available in Python as \\texttt{scipy.special.lambertw} from \\texttt{scipy} \\cite{scipy}.} of the Lambert function $\\cW$, as explained in Section~\\ref{par:6:falseAlarm}, $\\beta_3(n, \\delta) \\eqdef 2 \\mathcal{T}\\left(\\frac{\\log(2 n^{3/2}) / \\delta}{2}\\right) + 6 \\log(1 + \\log(n))$.\n\n    \\item\n    The forth variant is using the function $\\widetilde{\\mathcal{T}}(x) = x + 4 \\log(1 + x + \\sqrt{2x})$, as a simple approximation of $\\cT(x)$, which is valid and quite accurate as soon as $x \\geq 5$, $\\beta_4(n, \\delta) \\eqdef 2 \\widetilde{\\mathcal{T}}\\left(\\frac{\\log(2 n^{3/2}) / \\delta}{2}\\right) + 6 \\log(1 + \\log(n))$.\n\\end{enumerate}\n\nAs before, we consider the three problems $1$, $2$ and $4$, with time horizon $T=5000$,\nand we present in Table~\\ref{table:6:exploringDifferentThresholdFunctions} the mean results of $100$ independent runs.\nWe only consider the variant of \\GLRklUCB{} based on \\textbf{Local restarts}, and we used the parameters $\\omega_T,\\delta_T$ as given by the Corollary~\\ref{cor:6:Local},\nand with the deterministic exploration scheme.\n\n% \\begin{small} %XXX WARNING\n\\begin{table}[ht]\n    % \\begin{small} %XXX WARNING\n    \\centering\n    \\begin{tabular}{c|cccccc}\n        \\textbf{Threshold function} & Problem $1$ & Problem $2$ & Problem $4$ \\\\\n        \\hline\n        $\\beta_1(n,\\delta)$ & $\\mathbf{70 \\pm 30}$ & $109 \\pm 32$ & $99 \\pm 29$ \\\\\n        $\\beta_2(n,\\delta)$ & $73 \\pm 28$ & $99 \\pm 32$ & $\\mathbf{88 \\pm 32}$ \\\\\n        % \\hline\n        $\\beta_3(n,\\delta)$ & $77 \\pm 27$ & $\\mathbf{89 \\pm 32}$ & $134 \\pm 35$ \\\\\n        $\\beta_4(n,\\delta)$ & $77 \\pm 30$ & $101 \\pm 30$ & $135 \\pm 30$\n    \\end{tabular}\n    \\caption{Mean regret $\\pm$ $1$ standard-deviation, for different choices of threshold function $\\beta(n,\\delta)$, on three problems of horizon $T=5000$, for \\GLRklUCB.}\n    \\label{table:6:exploringDifferentThresholdFunctions}\n    % \\end{small} %XXX WARNING\n\\end{table}\n% \\end{small} %XXX WARNING\n\nAs we could expect, the four choices give comparable results, as well as $\\beta_3$ and $\\beta_4$. The first two choices give better performance in most cases, and they are computationally less costly.\nWe note that the threshold $\\beta_1$ is closer mathematically to the threshold $\\beta_3$, that was used in the analysis, and thus it is the one we advise to use in practice.\nThe sum-up of these experiments is that a practitioner should use the simplest and most explicit threshold $\\beta_1$, instead of the more complicated one that was used for the analysis.\nTherefore, the choice of threshold function $\\beta_1(n, \\delta) \\eqdef \\log\\left(3 n^{3/2} / \\delta\\right)$ for \\GLRklUCB{} presented in Algorithm~\\ref{algo:6:GLRklUCB} is validated by these experiments.\n% and this choice gives good empirical performance.\n\n\n% ----------------------------------------------------------------------------\n\\subsection{Comparison of mechanisms used to enforce uniform exploration}\\label{sec:6:exploringDifferentForcedExplorationMechanisms}\n\n% In only one or two short numerical experiment, for example Pb 1 and 2, I can present in a table the regret obtained by \\GLRklUCB, both local and global or only local, for different options of the forced exploration mechanism (uniform random, tracking, deterministic).\n%\n% This is already coded, see\n% https://smpybandits.github.io/docs/Policies.GLR_UCB.html?highlight=glr#Policies.GLR_UCB.GLR_IndexPolicy_WithTracking\n% https://smpybandits.github.io/docs/Policies.GLR_UCB.html?highlight=glr#Policies.GLR_UCB.GLR_IndexPolicy_WithDeterministicExploration\n\nWe compare different exploration mechanisms that can be used to enforce a sufficient exploration of all arms in the \\GLRklUCB{} algorithm.\nAll options are parameterized by a constant $\\omega\\in(0,1)$, which essentially represents the fraction of time steps spent in the forced exploration, either in average or in total.\n\n\\begin{enumerate}%\\tightlist\n    \\item\n    The \\textbf{deterministic exploration}\n    corresponds to the one described in Algorithm~\\ref{algo:6:GLRklUCB}.\n    At time $t$, if $t \\mod \\left\\lfloor \\frac{K}{\\omega}\\right\\rfloor \\in [K]$, then the arm $A_t = t \\mod \\left\\lfloor \\frac{K}{\\omega}\\right\\rfloor$ is played.\n    It is the simplest, both to compute numerically and to handle mathematically, as the proof of Proposition~\\ref{prop:6:EnoughSamples} is short and simple.\n    Its deterministic nature makes it the easiest choice for the proof skeleton given in Section~\\ref{sub:6:proofSkeleton}, as the set $\\cD(T,\\omega)$ used in the decomposition \\eqref{eq:6:GeneRegretBound} of the regret is deterministic, and thus it greatly simplifies the manipulation of expectations and random events.\n    Note that this mechanism is also the one used by \\MUCB{} \\cite{CaoZhenKvetonXie18}.\n\n    \\item\n    The \\textbf{uniform random exploration} is the one proposed for \\CUSUMUCB{} \\cite{LiuLeeShroff17}.\n    At time $t$, a random arm is played with probability $\\omega/K$. That is, first we sample a boolean variable from a Bernoulli law of mean $\\omega$, so that $1$ indicates a random play (with proba. $\\omega$), and $0$ indicates a play using the $\\UCB$ indexes (with proba. $1-\\omega$). Then if it is a random play, arm $i\\in[K]$ is selected uniformly at random (with probability $1/K$), and arm $A_t = i$ is played.\n    Proving a result like Proposition~\\ref{prop:6:EnoughSamples} is not much harder for this second mechanism,\n    but the difficulty lies in extending the proof skeleton we give in Section~\\ref{sub:6:proofSkeleton} to have a random set $\\cD(T,\\omega)$.\n\n    \\item\n    The \\textbf{tracking-based exploration} mechanism is inspired by the tracking trick used in \\cite{Garivier16BAI}, and it is actually quite intuitive.\n    At any time $t$, instead of having a uniform probability of forcing an exploration of every arm, it can make sense to force exploring arms that are currently not explored enough. This way, we actively enforce that each arm have enough samples.\n    At time $t$, the goal is for any arm $i$ to have been sampled more than $\\omega \\times (t - \\tau_i)$ time, if $t - \\tau_i$ represents the number of time steps since the last restart on this arm $i$.\n    So the tracking-based exploration samples an arm $i$ uniformly at random among the set of arms $i$ such that $n_i(t) < \\omega (t - \\tau_i)$, if it is not empty, otherwise it plays according to the $\\UCB$ indexes.\n    Numerically, it is not much more complicated than the two previous solutions.\n    It was the first direction we pursued for our analysis, but we dropped it since mathematically, it was harder to prove a result like Proposition~\\ref{prop:6:EnoughSamples}, and it was also harder to incorporate the randomness of this exploration scheme in the regret decomposition \\eqref{eq:6:GeneRegretBound}.\n\\end{enumerate}\n\nNote that the analysis we gave in Section~\\ref{sec:6:RegretAnalysis} is based on the deterministic exploration, but with a careful handling of random events and if we prove a result similar to Proposition~\\ref{prop:6:EnoughSamples}, we believe our analysis could also be extended to another exploration mechanism.\n\nAs before, we consider the three problems $1$, $2$ and $4$, with time horizon $T=5000$,\nand we present in Table~\\ref{table:6:exploringDifferentForcedExplorationMechanisms} the mean results of $100$ independent runs.\nWe include the two variants of \\GLRklUCB, based on \\textbf{Local restarts} or \\textbf{Global restarts}, for which we used the parameters $\\omega_T,\\delta_T$ as given by the two Corollaries~\\ref{cor:6:Global} and \\ref{cor:6:Local}.\n\n% \\begin{small} %XXX WARNING\n\\begin{table}[ht]\n    % \\begin{small} %XXX WARNING\n    \\centering\n    \\begin{tabular}{cc|ccc}\n        \\textbf{Exploration mechanism} & Variant & Problem $1$ & Problem $2$ & Problem $4$ \\\\\n        \\hline\n        \\multirow{2}{*}{Deterministic exploration}\n        & Local   & $\\mathbf{68 \\pm 33}$ & $116 \\pm 36$ & $99 \\pm 33$ \\\\\n        & Global  & $97 \\pm 28$ & $134 \\pm 36$ & $131 \\pm 32$ \\\\\n        \\hline\n        \\multirow{2}{*}{Uniform random exploration}\n        & Local  & $74 \\pm 30$ & $\\mathbf{108 \\pm 33}$ & $106 \\pm 31$ \\\\\n        & Global & $91 \\pm 30$ & $134 \\pm 33$ & $129 \\pm 33$ \\\\\n        \\hline\n        \\multirow{2}{*}{Tracking-based exploration}\n        & Local  & $73 \\pm 32$ & $104 \\pm 33$ & $\\mathbf{89 \\pm 29}$ \\\\\n        & Global & $96 \\pm 26$ & $133 \\pm 32$ & $120 \\pm 30$\n    \\end{tabular}\n    \\caption{Mean regret $\\pm$ $1$ standard-deviation, for different choices of exploration mechanisms, on three problems of horizon $T=5000$, for \\GLRklUCB, with local or global restarts.}\n    \\label{table:6:exploringDifferentForcedExplorationMechanisms}\n    % \\end{small} %XXX WARNING\n\\end{table}\n% \\end{small} %XXX WARNING\n\nAs expected, all options give similar results, and each of the three options was found to outperform the two others in one of the three problems considered for these experiments (problems $1$, $2$ and $4$).\nThe result highlighted in \\textbf{bold} in Table~\\ref{table:6:exploringDifferentForcedExplorationMechanisms} shows the best algorithm in each problem.\n% (\\ie, the algorithm and its option that obtains the smaller mean regret in the considered column).\nWe note that in terms of its average regret on the different problems, the tracking-based exploration is the best choice.\n%\nThe sum-up of these experiments is that it is sufficient to use the simplest exploration scheme based on a deterministic exploration,\nrather than a more complicated exploration scheme based on tracking.\nTherefore, our choice of the deterministic exploration scheme for \\GLRklUCB{} presented in Algorithm~\\ref{algo:6:GLRklUCB} is validated by these experiments.\n%  and this choice gives good empirical performance.\n", "meta": {"hexsha": "e885c6cfc3ae67dbe3e6180f11eb387116acd84d", "size": 87724, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "2-Chapters/6-Chapter/nonstatbandits/NonStatB_appendix.tex", "max_stars_repo_name": "Naereen/phd-thesis", "max_stars_repo_head_hexsha": "0fa93ca0d738771f4215bc4aeb66157f2026ba00", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-11-18T12:22:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T19:29:48.000Z", "max_issues_repo_path": "2-Chapters/6-Chapter/nonstatbandits/NonStatB_appendix.tex", "max_issues_repo_name": "Naereen/phd-thesis", "max_issues_repo_head_hexsha": "0fa93ca0d738771f4215bc4aeb66157f2026ba00", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-11-18T09:19:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-08T14:13:08.000Z", "max_forks_repo_path": "2-Chapters/6-Chapter/nonstatbandits/NonStatB_appendix.tex", "max_forks_repo_name": "Naereen/phd-thesis", "max_forks_repo_head_hexsha": "0fa93ca0d738771f4215bc4aeb66157f2026ba00", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-05-28T20:56:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-13T11:11:57.000Z", "avg_line_length": 86.4275862069, "max_line_length": 609, "alphanum_fraction": 0.6274109708, "num_tokens": 31194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.30946907121968187}}
{"text": "\\section{The Importance of Parity Games}\n\nParity games are simple two-player games of perfect information played on directed graphs whose\nnodes are labeled with priorities. The name \\emph{parity game} is due to the fact that the winner\nof a play is determined according to the parities (even or odd) of the priorities occurring in\nthat play. In fact, it is determined by the maximal priority occurring infinitely often. % This\n% can be seen as an abstraction of a setting in which an agent attemps to visit certain configurations\n% infinitely often unless some other configurations are also visited infinitely often unless some\n% other configurations are als visited infinitely often \\ldots while another agent is making his/her\n% life difficult by steering into different directions from time to time.\n\nParity games are an interesting object of study in computer science, and the theory of formal languages\nand automata in particular, for (at least) the following reasons.\n\\begin{itemize}\n\\item They are closely related to other games of infinite duration like mean payoff games,\n      discounted payoff games, stochastic games, etc.\\ \\cite{Jurdzinski/98,purithesis,Stirling95}.\n\\item They are at the core of other important problems in computer science, for instance, solving a\n      parity game is known to be polynomial-time equivalent to model checking for the modal\n      $\\mu$-calculus \\cite{Emerson93a,Stirling95}. \n\\item They arise in complementation or determinisation problems for tree automata\n      \\cite{lncs2500,focs91*368} and in emptiness and word problems for various kinds of (alternating) \n      automata \\cite{focs91*368}.\n\\item Controller synthesis problems can be reduced to satisfiability problems for branching-time logics\n      \\cite{AVW03} which in turn require the solving of parity games because\n      of determinisations of B\\\"uchi word automata into parity automata \n      \\cite{conf/lics/Piterman06,conf/icalp/KahlerW08}.\n\\item Solving a parity game is one of the rare problems that belongs to the complexity class\n      NP$\\cap$co-NP and that is not (yet) known to belong to P \\cite{Emerson93a}. The variety of algorithms\n      that have been invented for solving parity games is surely due to the fact that many people believe\n      the problem to be in P.\n\\end{itemize}\n\n\\section{Aim and Content of \\pgsolver}\n\nThis variety of algorithms has provided a good understanding of the theory of parity games even though\nits computational complexity has possibly not yet been determined precisely. However, this theoretical\nknowledge is unmatched by the little amount of investigation into practical aspects of solving parity\ngames. The aim of this project is to provide a platform for this: it should enable the comparison\nbetween different algorithms not just by the Landau-terms for their worst-case time complexities but\nby their actual performance on various classes of parity games.\n\nThe current version of this tool contains implementations of the following algorithms found in\nthe literature:\n\\begin{itemize}\n\\item the recursive algorithm due to Zielonka \\cite{TCS::Zielonka1998},\n\\item the local model checking algorithm due to Stevens and Stirling \\cite{StevensStirling98},\n\\item the strategy-improvement algorithm due to Jurdzi{\\'n}ski and V\\\"oge \\cite{conf/cav/VogeJ00},\n\\item the strategy-improvement algorithm due to Schewe \\cite{conf/csl/Schewe08},\n\\item the strategy-improvement algorithm reduction to discounted payoff games due to Puri \\cite{purithesis},\n\\item the randomized strategy-improvement algorithm due to Bj{\\\"o}rklund and Vorobyov \\cite{BjoerklundVorobyov/2007},\n\\item another randomized strategy-improvement algorithm due to Bj{\\\"o}rklund, Sandberg and Vorobyov \\cite{DBLP:conf/stacs/BjorklundSV03},\n\\item the small progress measures algorithm due to Jurdzi{\\'n}ski \\cite{Jurdzinski/00},\n\\item the small progress measures reduction to SAT due to Lange \\cite{lange-gdv05},\n\\item the dominion decomposition algorithm due to Jurdzi{\\'n}ski, Paterson and Zwick \\cite{JPZ06},\n\\item the big-step variant of the latter due to Schewe \\cite{Schewe/07/Parity}.\n\\end{itemize}\nIn addition, there is a new local strategy improvement algorithm by ourselves. Moreover\nthere is a direct reduction to SAT based on strategy iteration due to Friedmann.\n\nFinally, there is one heuristic solvers. Such solvers are sound: the answers they provide are correct.\nBut they are not necessarily complete, for example because they may not terminate. Our heuristic\nalgorithm just guesses strategies for both players until a (partial) winning strategy has been found.\n\nThe heuristic is included because it can solve certain classes of parity games very quickly and\n-- most importantly -- in a time that is independent of the number of priorities present in the game.\nOn the other hand, it is easy to construct games on which it does not terminate, resp.\\ infinite families\nof games on which the probability of termination decreases exponentially.\n\n\n\n\\section{Structure of this Report}\n\nChapter~\\ref{chp:pgames} formally introduces parity games and standard notions around the problem of solving them\nlike winning regions and strategies, but also others that are needed in order to understand the constructions\nimplemented in various solvers like attractor strategies, decompositions into subgames, etc. It then\ndescribes implemented meta-level optimisations for solving parity games, i.e.\\ optimisations that apply to\n\\emph{any} solver. Next, it shortly describes the implemented algorithms and heuristics. For those known\nbefore we refer to the corresponding literature for a detailed introduction into these algorithms. Here we\nonly want to point out the rough functionality in order to be able to compare these algorithms and possibly\nattribute slow/fast solving to certain techniques.\n\nChapter~\\ref{chp:uguide} is the user's guide. It describes how to compile, install and run \\pgsolver, as well\nas how to specify parity games that it takes as input and how to read its output, etc.\n\n\\pgsolver comes with programs that generate benchmarks. These are for example random games, games\nconstructed in a way such that they are difficult for a certain algorithm to solve, or application-oriented\ngames. These are described in Chapter~\\ref{chp:benchmarks}.\n\nFinally, Chapter~\\ref{chp:devguide} contains the developer's guide. It explains how to\nintegrate another parity game solver -- implemented in OCaml -- into this tool.\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: \"main\"\n%%% End:\n", "meta": {"hexsha": "e98d765e5adc4d80a975dfafea27d3cb33e57f30", "size": 6518, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/intro.tex", "max_stars_repo_name": "tcsprojects/pgsolver", "max_stars_repo_head_hexsha": "88202c9452ccdcd4092280b4e76c31a16085d14c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2016-04-03T22:53:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T20:53:38.000Z", "max_issues_repo_path": "doc/intro.tex", "max_issues_repo_name": "tcsprojects/pgsolver", "max_issues_repo_head_hexsha": "88202c9452ccdcd4092280b4e76c31a16085d14c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2015-03-28T15:29:29.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-22T16:48:34.000Z", "max_forks_repo_path": "doc/intro.tex", "max_forks_repo_name": "tcsprojects/pgsolver", "max_forks_repo_head_hexsha": "88202c9452ccdcd4092280b4e76c31a16085d14c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2015-01-06T10:32:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T15:58:23.000Z", "avg_line_length": 67.8958333333, "max_line_length": 137, "alphanum_fraction": 0.7974838908, "num_tokens": 1468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3094639362827904}}
{"text": "%!TEX root = ../../report.tex\n\n\\subsubsection{Shape Grammars} % (fold)\n\\label{ssub:shape_grammars}\n\n\nShape Grammars can be considered grammars for design. In stead of having symbols or letters as components of the alphabet, it has shapes that can be in 2D or 3D. And have production rules that are composed by this shapes, and specify the evolution of the system. With this process, similar to the L-Systems explained before, the shape starts from a seed, i.e. a usually simple shape and can evolve to one big and/or complex shape.\n\nThe process is performed in two steps, the recognition of a shape and the replacement according to the rules that are previously defined. \n\nThe Figure~\\ref{fig:SGrammars} exemplify one shape grammar, with one rule and the evolution of the application of this rule to the shapes iteratively. In this image, it's shown that from very simple initial shape, can be generated a complex from with a few iterations.\n\n\\begin{figure}\n        \\centering\n\t\t\\begin{subfigure}[b]{0.7\\textwidth}\n\t\t\t\\includegraphics[width=\\textwidth]{img/Theory/Shape_Grammars/Grammar.png}\n\t\t\t\\caption{a)}\n\t\t\t\\label{fig:SGGrammar}\n\t\t\\end{subfigure}\n        \n         %add desired spacing between images, e. g. ~, \\quad, \\qquad, \\hfill etc.\n          %(or a blank line to force the subfigure onto a new line)\n\t\t\\begin{subfigure}[b]{0.7\\textwidth}\n\t\t\t\\includegraphics[width=\\textwidth]{img/Theory/Shape_Grammars/Recursion.png}\n\t\t\t\\caption{b)}\n\t\t\t\\label{fig:SGRecursion}\n\t\t\\end{subfigure}\n        \\caption{a) Grammar Tiles b) Recursion steps}\n        \\label{fig:SGrammars}\n\\end{figure}\n\nThis is applied to the generation of buildings in the CityEngine \\ref{sub:cityengine} system, using 3D blocks for the main form, and 2D shapes to design the facades.\n\n% \\begin{figure}[htbp]\n% \t\\centering\n% \t\\includegraphics[width=0.55\\textwidth]{img/Theory/Shape_Grammars/Edificio.png}\n% \t\\caption{Simple Building}\n% \t\\label{fig:SGBuilding}\n% \\end{figure}\n\nThe Figure~\\ref{fig:SGBuilding} shows a simple building that I modelled using CityEngine and it's CGA Shape Grammar. But CGA is powerful enough to model much more complex buildings like the Figure~\\ref{fig:CEBuilding}.\n\n\n% \\begin{figure}[htbp]\n% \t\\centering\n% \t\\includegraphics[width=0.55\\textwidth]{img/Theory/Shape_Grammars/Capturar.png}\n% \t\\caption{Complex Building \\cite{Muller2006}}\n% \t\\label{fig:CEBuilding}\n% \\end{figure}\n\n\\begin{figure}\n\\centering\n\\begin{minipage}{.5\\textwidth}\n  \\centering\n  \\includegraphics[width=.5\\linewidth]{img/Theory/Shape_Grammars/Edificio.png}\n  \\captionof{figure}{Simple Building}\n  \\label{fig:SGBuilding}\n\\end{minipage}%\n\\begin{minipage}{.5\\textwidth}\n  \\centering\n  \\includegraphics[width=.8\\linewidth]{img/Theory/Shape_Grammars/Capturar.png}\n  \\captionof{figure}{Complex Building \\cite{Muller2006}}\n  \\label{fig:CEBuilding}\n\\end{minipage}\n\\end{figure}\n\n\n\n\n\n\n\n\n\n\n% subsubsection shape_grammars (end)", "meta": {"hexsha": "54e0a793cffa0c249a503db659395a751680c3bc", "size": 2880, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "sections/overview/4-shape_grammars.tex", "max_stars_repo_name": "arturalkaim/ProceduralGeneration", "max_stars_repo_head_hexsha": "736fcb8a15291ede1db069ad968527508bc081c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sections/overview/4-shape_grammars.tex", "max_issues_repo_name": "arturalkaim/ProceduralGeneration", "max_issues_repo_head_hexsha": "736fcb8a15291ede1db069ad968527508bc081c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sections/overview/4-shape_grammars.tex", "max_forks_repo_name": "arturalkaim/ProceduralGeneration", "max_forks_repo_head_hexsha": "736fcb8a15291ede1db069ad968527508bc081c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8947368421, "max_line_length": 430, "alphanum_fraction": 0.7454861111, "num_tokens": 850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.30946392792215466}}
{"text": "% !TEX root = ../00_thesis.tex\n\n%-------------------------------------------------------------------------------\n\\section{Implementation and Scalability of \\triscale}\n\\label{sec:triscale_implementation}\n%-------------------------------------------------------------------------------\n\n%-------------------------------------------------------------------------------\n\\subsection{Python Package}\n\nWe implement \\triscale in Python ($\\approx$1000 lines of code) and make it open source~(\\cref{append:triscale_artifacts}).\n\\triscale's API contains one function for each timescale of the data analysis; \\ie the computation of metrics, KPIs, and variability scores.\nDocstrings contain detailed information about the functions usage.\nOur implementation relies on standard scientific packages such as NumPy~\\cite{numpy}, Pandas~\\cite{pandas}, SciPy~\\cite{scipy}.\nAs the use of non-parametric statistics is not (yet) widespread, we had to implement some of the statistics used by \\triscale (in particular the computation of CI using Thompson's method).\nWe hope to see these functions integrated in a future release of SciPy.\n\n\\squarepar{%\n  It is important to produce useful visualizations to support the experimenter.\n  Thus, we paid a particular attention to the plotting functions in \\triscale.\n  \\triscale uses Plotly~\\cite{plotly} to create interactive plots: one can zoom in and out in the plots, toggle the visibility of individual traces, read data point values on hover, \\etc\n  All the plots in this chapter are produced using \\triscale and are ``clickable'': figures are hyperlinks leading to dynamic versions of the plots.%\n}\n\n\n%-------------------------------------------------------------------------------\n\\subsection{Scalability of \\triscale Data Analysis}\n\\label{subsec:scalability}\n\nWe evaluate the scalability of \\triscale with respect to computation time; \\ie how does the data analysis time scales with increasing input sizes.\nWe only consider the time required for performing computations; other outputs such as logs and plots (\\eg \\Cref{fig:analysis_metric}) are excluded.\nThe complete scalability evaluation (including data, plots, and discussions) is available as complementary materials~(\\cref{append:triscale_artifacts}).\nGenerally, the computation time for the data analysis in \\triscale scales linearly with the input size~(\\Cref{table:scalability}): it is fast (less than 1\\s for one million data points on a commodity laptop) and overall negligible compared to the data collection time.\n\n\n\\begin{table}\n    \\centering\n    \\caption{Scalability evaluation.\n    \\capt{\\triscale data analysis is fast and scales well with increasing input sizes. The most time-consuming element is the convergence test~(\\cref{subsec:test_convergence}) which is performed before the computation of metrics. Still, it generally takes less than one second for inputs (\\ie the number of raw measurements in a run) of up to one million data points.}}\n    \\input{\\PathTab/triscale_scalability.csv}\n    \\label{table:scalability}\n\\end{table}\n", "meta": {"hexsha": "b189ec40a7c364444bd60cb20f5b856a7b5da26c", "size": 3033, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "20_TriScale/8_implem.tex", "max_stars_repo_name": "romain-jacob/doctoral-theis", "max_stars_repo_head_hexsha": "fd21e9f0cddeda91821eb061c9ab12df9f610da9", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "20_TriScale/8_implem.tex", "max_issues_repo_name": "romain-jacob/doctoral-theis", "max_issues_repo_head_hexsha": "fd21e9f0cddeda91821eb061c9ab12df9f610da9", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "20_TriScale/8_implem.tex", "max_forks_repo_name": "romain-jacob/doctoral-theis", "max_forks_repo_head_hexsha": "fd21e9f0cddeda91821eb061c9ab12df9f610da9", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 70.5348837209, "max_line_length": 369, "alphanum_fraction": 0.706231454, "num_tokens": 645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3094639279221546}}
{"text": "%!TEX root = ../gronskiy_phd_thesis.tex\r\n\\chapter{Concluding Remarks}\r\n\\label{ch:conclusion}\r\n\r\n\\hfill\r\n\\begin{minipage}[t]{.75\\textwidth}\r\n\\textit{``The measure of greatness in a scientific idea is the extent to which\r\nit stimulates thought and opens up new lines of research.''} \\\\\r\n  \\hrule\r\n  \\vspace{.2cm}\r\n  \\hfill\r\n  \\textsc{---  Paul DIRAC}\r\n\\end{minipage}\r\n\\\\[.5cm]\r\n\r\nIn this thesis, we addressed the problem of robust approximate optimization in\r\ndifferent settings: general, algorithmic and thermodynamic, and also looked into\r\nthe thermodynamic behavior of optimization problem in a more general (i.e. not\r\nrelated to approximation) sense. Because detailed remarks are given at the end\r\nof each chapter, here we give some very general thoughts about possible\r\ndirections of the further research.\r\n\r\n\\section{Approximate Optimization in General}\r\n\r\nIt would be interesting to extend the approaches presented in\r\nChapter~\\ref{ch:gen_appch} to the case of more than two instances.\r\nWhile some straightforward generalizations may exist~--- e.g. mechanistically\r\nextend the formula for ASC score, adding more terms in nominator and\r\ndenominator,~--- it becomes unclear how to justify it from the point of view of\r\ncoding theory. It can require modifying the definition of the channel which\r\nwe presented in that chapter.\r\n\r\nFurther, while we partially addressed the question of computing intersection\r\ncardinalities, this result relies on knowing distributions, which renders it\r\nunusable in practice or at least requires the use of plug-in estimators. It\r\nwould be beneficial to design a class of problems for which this issue\r\nis eliminated. We partially did this for algorithmic problems, but at the cost\r\nof worse performance, as noted in the discussion of that chapter.\r\n\r\nLast but not least, there is hope that one can integrate our approach into a\r\ntoolbox of stability-related approaches (see related work), because our approach\r\nessentially attacks the problem of identifying stability conditions (by imposing\r\napproximations). It would be interesting to see a connection of our approach\r\nwith more conventional techniques.\r\n\r\n\\section{Robust Algorithmic Optimization}\r\n\r\nAs we have seen, the ASC score establishes a ranking of algorithms, which also\r\nyields a corresponding ranking of their localization errors. Is this by chance or\r\ncan it be proven rigorously? Another question here arises. The\r\nReverse-Delete algorithm requires many more steps than Prim's and Kruskal's (see\r\nexperiments in Chapter~\\ref{ch:mst}), but gains much better robustness.\r\nObviously, this happens because Reverse-Delete is much more elaborate in\r\nexploring the graph: Prim's and Kruskal's algorithms eliminate unexplored edges\r\nmuch more aggressively, and thus ``skip'' a lot of opportunities without\r\nactually seeing them. We have a clear runtime vs. robustness trade-off, which\r\nraises a question: can one construct an intermediate algorithm using the above\r\nthree as building blocks?\r\n\r\nAnother massive task would be to study more algorithmic problems from this\r\nperspective. It must be recalled that the extension of ASC for algorithms was\r\nperformed in some sense ``blindly'', since proving the communication error\r\nbounds (in analogy to that of Chapter~\\ref{ch:gen_appch}) is hard in this case.\r\nConsequently, it might turn out that with other algorithmic problems this\r\napproach works much better/worse. Additional research would be beneficial here.\r\n\r\n\\section{Thermodynamic Behavior of Optimization Problems}\r\n\r\nAlthough we have proven (Chapter~\\ref{ch:free_energy}) the asymptotics of free\r\nenergy in two specific cases, we still did not devise a general\r\nmethodology. Although we are currently under an impression that there is no such\r\ngeneral methodology, more attempts should be made.\r\n\r\nNext, we made and experimentally backed up an attractive conjecture about the\r\nbehavior of free energy in more general cases than those where\r\ntheoretic results were obtained. We brought up an intuitive explanation for it,\r\nand it is extremely interesting to continue a line of research on that.\r\n\r\nFurther, it is still not clear how far one can go with the sparsity constraint\r\n(which, should be recalled, was introduced to reduce the influence of\r\ninteractions between solutions without fully eliminating it). Current\r\ncondition $\\log n \\ll d \\ll n^{2/7}$ might be extended, if one uses more\r\nadvanced bounding techniques.\r\n\r\nFinally, but no less importantly, the free energy behavior of Gibbs-regularized\r\ncombinatorial optimization problems like sMBP looks very similar to that of REM\r\n(Chapter~\\ref{ch:smbp_and_rem}). Is this coincidental or does this tell us\r\nanything about other aspects of their analogy? In particular, we see that they\r\nare obviously different from the algorithmic point of view: while REM represents\r\ntotal ``chaos'' with independent costs, the sMBP by definition has a certain\r\namount of cost dependence and thus intuitively should allow a more efficient\r\noptimum searching than REM. Is this so, and if yes~--- can this line of\r\nreasoning be further developed?\r\n\r\nTo understand that, one needs to properly estimate higher moments of the\r\nlog-partition function, which is highly non-trivial, but for sure a noble goal.\r\n\r\n", "meta": {"hexsha": "5f6826e1d49e1a0f29d243aec627e0804d6406e4", "size": 5249, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/ch_conclusion/ch_conclusion.tex", "max_stars_repo_name": "agronskiy/phd-thesis", "max_stars_repo_head_hexsha": "182fcc5c09c8aa20df54cf536eb87766bfb6c353", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thesis/ch_conclusion/ch_conclusion.tex", "max_issues_repo_name": "agronskiy/phd-thesis", "max_issues_repo_head_hexsha": "182fcc5c09c8aa20df54cf536eb87766bfb6c353", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis/ch_conclusion/ch_conclusion.tex", "max_forks_repo_name": "agronskiy/phd-thesis", "max_forks_repo_head_hexsha": "182fcc5c09c8aa20df54cf536eb87766bfb6c353", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.5612244898, "max_line_length": 82, "alphanum_fraction": 0.7900552486, "num_tokens": 1130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3094639279221546}}
{"text": "\\documentclass{article}\n\\usepackage{listings}\n\\usepackage{xcolor}\n\\usepackage{graphicx}\n\\usepackage{url}\n\\usepackage{pdfpages}\n\\usepackage{makecell}\n\\usepackage{tabularx}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{multirow}\n\\usepackage{array}\n\n\\title{Summary of the Biome Generation in \\\\ Minecraft 1.7 - 1.12}\n\n\\author{Cubitect}\n\n\\begin{document}\n\t\n\t\\maketitle\n\t\n\t\\begin{abstract}\n\t\tThis document is designed to provide an overview of how Minecraft biome generation works and how we may efficiently find seeds with desired properties.\n\t\\end{abstract}\n\t\n\t\\newpage\n\t\n\t\\tableofcontents\n\t\n\t\n\t\n\t\\newpage\n\t\n\t\n\t\\section{Biome Generator Layers}\n\n\tMinecraft biome generation occurs in layers. Many of these layers are chained together inside the generator, such that the output from one becomes the input for the next. A flowchart of this can be found on the next page.\n\t\n\tEach layer applies certain modifications to a map of integers, which change their use throughout the generation process. Initially the map only contains values 0 or 1, representing ocean or land masses. Later in the generator they represent temperature categories, until they are finally replaced by the actual biome IDs.\n\t\n\tSome of the layers resize the output of the previous layer. These Zoom-layers therefore change how much area is represented by a map entry. I will refer to this as \"scale\". For instance, 1:256 should be read as: one map entry ends up as an area of 256x256 blocks in the world.\n\t\n\t\\setcounter{subsection}{-1}\n\t\\subsection{Seed Finding}\n\t\n\tWhen constructing a seed finder, it may be useful to stop the generation at an earlier layer. For example if we require a swamp to be located near a given position, then we might want to generate up to layer 19: Biome first, and then check on a 1:256 scale if there is a swamp in the area. This is not enough to confirm that there will be a swamp at the given position, but we can rule out seeds that definitely don't have a swamp anywhere near the area. If the seed passes this cheap test, then we can go through the full expensive generation process and directly check the position for a swamp.\n\t\n\tUsually it is not practical to continue the search from a terminated generation and we have to start over again. The reason for this is that most layers require an additional 1 wide boarder from the previous layer, so the map sizes don't match up.\n\t\n\tAnother more involved, but very powerful way of creating early knock-out criteria is to check if there is a some condition in the layer chain that is independent of the rest of the biomes. For instance in the case of finding a swamp, we can notice that there is a pseudo-random number check in layer 19: Biome, that converts Lush temperature climates to swamplands. However, the pseudo-random number generator is seeded by a combination of the position and the world seed, so we can make sure the random number output gives the required value without going through the rest of the layers. The more expensive generator can afterwards be used to make sure that a Lush climate is actually present at that position.\n\t\n\t\n\tIn the summary below in sections 1.1 -- 1.44 I have laid out some of the properties of each layer, such as the scale of the layer and the possible values for the map entries with their respective average probability of occurrence (Note: these are estimates and may vary). When constructing a seed finder these values can be used as a reference to determine reasonable cut-off points for the generator.\n\t\n\t\n\t\\includepdf[pages={1}]{layers.pdf}\n\t\n\t\n\t\\subsection{Layer 1: Island}\n\t\\begin{tabular}{|l|l|l|}\\hline\n\t\tScale: & \\multicolumn{2}{|l|}{1:4096} \\\\\\hline\\hline\n\t\tValue  & Type   & Occurrence \\\\\\hline\n\t\t0      & Ocean  & 90.0\\%\\\\\\hline\n\t\t1      & Land   & 10.0\\%\\\\\\hline\n\t\\end{tabular}\n\t\n\t\\subsection{Layer 2: Zoom}\n\t\\begin{tabular}{|l|l|l|}\\hline\n\t\tScale: & \\multicolumn{2}{|l|}{1:2048} \\\\\\hline\\hline\n\t\tValue  & Type   & Occurrence \\\\\\hline\n\t\t0      & Ocean  & 90.0\\%\\\\\\hline\n\t\t1      & Land   & 10.0\\%\\\\\\hline\n\t\\end{tabular}\n\t\n\t\\subsection{Layer 3: Add Island}\n\t\\begin{tabular}{|l|l|l|}\\hline\n\t\tScale: & \\multicolumn{2}{|l|}{1:2048} \\\\\\hline\\hline\n\t\tValue  & Type   & Occurrence \\\\\\hline\n\t\t0      & Ocean  & 84.3\\%\\\\\\hline\n\t\t1      & Land   & 15.7\\%\\\\\\hline\n\t\\end{tabular}\n\n\t\\subsection{Layer 4: Zoom}\n\t\\begin{tabular}{|l|l|l|}\\hline\n\t\tScale: & \\multicolumn{2}{|l|}{1:1024} \\\\\\hline\\hline\n\t\tValue  & Type   & Occurrence \\\\\\hline\n\t\t0      & Ocean  & 84.9\\%\\\\\\hline\n\t\t1      & Land   & 15.1\\%\\\\\\hline\n\t\\end{tabular}\n\t\n\t\\subsection{Layer 5: Add Island}\n\t\\begin{tabular}{|l|l|l|}\\hline\n\t\tScale: & \\multicolumn{2}{|l|}{1:1024} \\\\\\hline\\hline\n\t\tValue  & Type   & Occurrence \\\\\\hline\n\t\t0      & Ocean  & 81.4\\%\\\\\\hline\n\t\t1      & Land   & 18.6\\%\\\\\\hline\n\t\\end{tabular}\n\t\n\t\\subsection{Layer 6: Add Island}\n\t\\begin{tabular}{|l|l|l|}\\hline\n\t\tScale: & \\multicolumn{2}{|l|}{1:1024} \\\\\\hline\\hline\n\t\tValue  & Type   & Occurrence \\\\\\hline\n\t\t0      & Ocean  & 77.5\\%\\\\\\hline\n\t\t1      & Land   & 22.5\\%\\\\\\hline\n\t\\end{tabular}\n\t\n\t\\subsection{Layer 7: Add Island}\n\t\\begin{tabular}{|l|l|l|}\\hline\n\t\tScale: & \\multicolumn{2}{|l|}{1:1024} \\\\\\hline\\hline\n\t\tValue  & Type   & Occurrence \\\\\\hline\n\t\t0      & Ocean  & 73.4\\%\\\\\\hline\n\t\t1      & Land   & 26.6\\%\\\\\\hline\n\t\\end{tabular}\n\n\t\\subsection{Layer 8: Remove Too Much Ocean}\n\t\\begin{tabular}{|l|l|l|}\\hline\n\t\tScale: & \\multicolumn{2}{|l|}{1:1024} \\\\\\hline\\hline\n\t\tValue  & Type   & Occurrence \\\\\\hline\n\t\t0      & Ocean  & 49.4\\%\\\\\\hline\n\t\t1      & Land   & 50.6\\%\\\\\\hline\n\t\\end{tabular}\n\t\n\t\n\t\\subsection{Layer 9: Add Snow}\n\t\\begin{tabular}{|l|l|l|}\\hline\n\t\tScale: & \\multicolumn{2}{|l|}{1:1024} \\\\\\hline\\hline\n\t\tValue  & Type     & Occurrence \\\\\\hline\n\t\t0      & Ocean    & 49.4\\%\\\\\\hline\n\t\t1      & Warm     & 33.7\\%\\\\\\hline\n\t\t3      & Cold     & 4.8\\%\\\\\\hline\n\t\t4      & Freezing & 12.4\\%\\\\\\hline\n\t\\end{tabular}\n\t\n\t\\medskip\\noindent\n\tChanges some of the land starting points to Cold and Freezing.\n\n\t\\subsection{Layer 10: Add Island}\n\t\\begin{tabular}{|l|l|l|}\\hline\n\t\tScale: & \\multicolumn{2}{|l|}{1:1024} \\\\\\hline\\hline\n\t\tValue  & Type    & Occurrence \\\\\\hline\n\t\t0      & Ocean   & 33.8\\%\\\\\\hline\n\t\t1      & Warm    & 37.6\\%\\\\\\hline\n\t\t3      & Cold    & 4.8\\%\\\\\\hline\n\t\t4      & Freeing & 23.9\\%\\\\\\hline\n\t\\end{tabular}\n\t\n\t\\medskip\\noindent\n\tSpreads out the continental areas, decreasing the amount of ocean.\n\n\t\\subsection{Layer 11: Edge, Cool/Warm}\n\t\\begin{tabular}{|l|l|l|}\\hline\n\t\tScale: & \\multicolumn{2}{|l|}{1:1024} \\\\\\hline\\hline\n\t\tValue  & Type     & Occurrence \\\\\\hline\n\t\t0      & Ocean    & 33.8\\%\\\\\\hline\n\t\t1      & Warm     & 13.6\\%\\\\\\hline\n\t\t2      & Lush     & 23.9\\%\\\\\\hline\n\t\t3      & Cold     & 4.8\\%\\\\\\hline\n\t\t4      & Freezing & 23.9\\%\\\\\\hline\n\t\\end{tabular}\n\t\n\t\\medskip\\noindent\n\tChanges Warm(1) lands which are adjacent to Cold(3) or Freezing(4) temperatures to Lush(2).\n\t\n\t\\subsection{Layer 12: Edge, Heat/Ice}\n\t\\begin{tabular}{|l|l|l|}\\hline\n\t\tScale: & \\multicolumn{2}{|l|}{1:1024} \\\\\\hline\\hline\n\t\tValue  & Type     & Occurrence \\\\\\hline\n\t\t0      & Ocean    & 33.8\\%\\\\\\hline\n\t\t1      & Warm     & 13.6\\%\\\\\\hline\n\t\t2      & Lush     & 23.9\\%\\\\\\hline\n\t\t3      & Cold     & 23.9\\%\\\\\\hline\n\t\t4      & Freezing & 4.8\\%\\\\\\hline\n\t\\end{tabular}\n\n\t\\medskip\\noindent\n\tChanges Freezing(4) lands which are adjacent to Warm(1) or Lush(2) temperatures to Cold(3).\n\n\t\\subsection{Layer 13: Edge, Special}\n\t\\begin{tabular}{|l|l|l|}\\hline\n\t\tScale: & \\multicolumn{2}{|l|}{1:1024} \\\\\\hline\\hline\n\t\tValue  & Type     & Occurrence \\\\\\hline\n\t\t0      & Ocean    & 33.8\\%\\\\\\hline\n\t\t1      & Warm     & 12.5\\%\\\\\\hline\n\t\t2      & Lush     & 22.1\\%\\\\\\hline\n\t\t3      & Cold     & 22.1\\%\\\\\\hline\n\t\t4      & Freezing & 4.4\\%\\\\\\hline\n\t\t-      & Special  & 5.1\\% / 60\\\\\\hline\n\t\\end{tabular}\n\t\n\t\\medskip\\noindent\n\tMarks every 1 in 13 lands (non-ocean) as special, by adding a 4-bit number in 0x0F00 to the value.\n\t\n\t\n\t\\subsection{Layer 14: Zoom}\n\t\\begin{tabular}{|l|l|l|}\\hline\n\t\tScale: & \\multicolumn{2}{|l|}{1:512} \\\\\\hline\\hline\n\t\tValue  & Type   & Occurrence \\\\\\hline\n\t\t0      & Ocean    & 35.6\\%\\\\\\hline\n\t\t1      & Warm     & 12.2\\%\\\\\\hline\n\t\t2      & Lush     & 21.9\\%\\\\\\hline\n\t\t3      & Cold     & 21.9\\%\\\\\\hline\n\t\t4      & Freezing & 4.2\\%\\\\\\hline\n\t\t-      & Special  & 4.2\\% / 60\\\\\\hline\n\t\\end{tabular}\n\n\t\\subsection{Layer 15: Zoom}\n\t\\begin{tabular}{|l|l|l|}\\hline\n\t\tScale: & \\multicolumn{2}{|l|}{1:256} \\\\\\hline\\hline\n\t\tValue  & Type   & Occurrence \\\\\\hline\n\t\t0      & Ocean    & 35.6\\%\\\\\\hline\n\t\t1      & Warm     & 11.9\\%\\\\\\hline\n\t\t2      & Lush     & 21.9\\%\\\\\\hline\n\t\t3      & Cold     & 21.9\\%\\\\\\hline\n\t\t4      & Freezing & 4.2\\%\\\\\\hline\n\t\t-      & Special  & 4.5\\% / 60\\\\\\hline\n\t\\end{tabular}\n\t\n\t\\subsection{Layer 16: Add Island}\n\t\\begin{tabular}{|l|l|l|}\\hline\n\t\tScale: & \\multicolumn{2}{|l|}{1:256} \\\\\\hline\\hline\n\t\tValue  & Type   & Occurrence \\\\\\hline\n\t\t0      & Ocean    & 31.4\\%\\\\\\hline\n\t\t1      & Warm     & 12.7\\%\\\\\\hline\n\t\t2      & Lush     & 22.4\\%\\\\\\hline\n\t\t3      & Cold     & 22.8\\%\\\\\\hline\n\t\t4      & Freezing & 6.2\\%\\\\\\hline\n\t\t-      & Special  & 4.5\\% / 60\\\\\\hline\n\t\\end{tabular}\n\t\n\t\n\t\\subsection{Layer 17: Add Mushroom Island}\n\t\\begin{tabular}{|l|l|l|l|}\\hline\n\t\tScale: & \\multicolumn{3}{|l|}{1:256} \\\\\\hline\\hline\n\t\tValue  & Type     & \\multicolumn{2}{l|}{Occurrence} \\\\\\hline\n\t\t0      & Ocean    & \\multicolumn{2}{l|}{31.4\\%}\\\\\\hline\n\t\t1      & Warm     & \\multicolumn{2}{l|}{12.8\\%}\\\\\\hline\n\t\t2      & Lush     & \\multicolumn{2}{l|}{22.5\\%}\\\\\\hline\n\t\t3      & Cold     & \\multicolumn{2}{l|}{22.7\\%}\\\\\\hline\n\t\t4      & Freezing & \\multicolumn{2}{l|}{6.08\\%}\\\\\\hline\n\t\t14     & Mushroom & \\multicolumn{2}{l|}{0.0773\\%}\\\\\\hline\\hline\n\t\t\n\t\t\\makecell[l]{ $(n<<8)+1$ \\\\ with $n = $ \\\\ $1, 4, 7, 10, 13$ } & - & \n\t\t\\makecell[l]{0.0690\\% \\\\each} & \\multirow{5}{*}{0.90\\%}\\\\\\cline{1-3}\n\t\t\n\t\t\\makecell[l]{ $(n<<8)+1$ \\\\ with $n = $ \\\\ $2, 3, 5, 6, 8, 9,$ \\\\ $11, 12, 14, 15$ } & - & \\makecell[l]{0.0553\\% \\\\ each} & \\\\\\hline\\hline\n\t\t\n\t\t\\makecell[l]{ $(n<<8)+2$ \\\\ with $n = $ \\\\ $1, 4, 7, 10, 13$ } & - & \n\t\t\\makecell[l]{0.1236\\% \\\\ each} & \\multirow{5}{*}{1.56\\%}\\\\\\cline{1-3}\n\t\t\n\t\t\\makecell[l]{ $(n<<8)+2$ \\\\ with $n = $ \\\\ $2, 3, 5, 6, 8, 9,$ \\\\ $11, 12, 14, 15$ } & - & \\makecell[l]{0.0961\\% \\\\ each} & \\\\\\hline\\hline\n\t\t\n\t\t\\makecell[l]{ $(n<<8)+3$ \\\\ with $n = $ \\\\ $1, 4, 7, 10, 13$ } & - & \n\t\t\\makecell[l]{0.1078\\% \\\\ each} & \\multirow{5}{*}{1.58\\%}\\\\\\cline{1-3}\n\t\t\n\t\t\\makecell[l]{ $(n<<8)+3$ \\\\ with $n = $ \\\\ $2, 3, 5, 6, 8, 9,$ \\\\ $11, 12, 14, 15$ } & - &\n\t\t\\makecell[l]{0.1037\\% \\\\ each} & \\\\\\hline\\hline\n\t\t\t\t\n\t\t\\makecell[l]{ $(n<<8)+4$ \\\\ with $n = $ \\\\ $1, 4, 7, 10, 13$ } & - & \n\t\t\\makecell[l]{0.0212\\% \\\\ each} & \\multirow{5}{*}{0.32\\%}\\\\\\cline{1-3}\n\t\t\n\t\t\\makecell[l]{ $(n<<8)+4$ \\\\ with $n = $ \\\\ $2, 3, 5, 6, 8, 9,$ \\\\ $11, 12, 14, 15$ } & - &\n\t\t\\makecell[l]{0.0212\\% \\\\ each} & \\\\\\hline\n\n\t\\end{tabular}\n\t\n\t\\medskip\\noindent\n\tChanges every 100th Ocean (adjacent to more Ocean) to Mushroom Island. The special land types are written out in full in the table above. (Note \"$<<$\" represents a left bit shit.) Added together, the special types make up an average of about 4.37\\% of the area.\n\t\n\t\n\t\\subsection{Layer 18: Deep Ocean}\n\t\\begin{tabular}{|l|l|l|}\\hline\n\t\tScale: & \\multicolumn{2}{|l|}{1:256} \\\\\\hline\\hline\n\t\tValue  & Type       & Occurrence \\\\\\hline\n\t\t0      & Ocean      & 22.0\\%\\\\\\hline\n\t\t1      & Warm       & 12.8\\%\\\\\\hline\n\t\t2      & Lush       & 22.5\\%\\\\\\hline\n\t\t3      & Cold       & 22.7\\%\\\\\\hline\n\t\t4      & Freezing   & 6.1\\%\\\\\\hline\n\t\t14     & Mushroom   & 0.0773\\%\\\\\\hline\n\t\t24     & Deep Ocean & 9.4\\%\\\\\\hline\n\t\t-      & Special    & 4.4\\% / 60\\\\\\hline\n\t\\end{tabular}\n\t\n\t\\medskip\\noindent\n\tChanges any Ocean which is surrounded by more Ocean to Deep Ocean.\\\\\n\t(Special lands still have the same statistics as shown for Layer 17.)\n\t\n\t\n\t\\subsection{Layer 19: Biome}\n\t\\begin{tabular}{|l|l|l|}\\hline\n\t\tScale: & \\multicolumn{2}{|l|}{1:256} \\\\\\hline\\hline\n\t\tValue  & Type           & Occurrence \\\\\\hline\n\t\t0      & ocean          & 22.0\\%\\\\\\hline\n\t\t1      & plains         & 11.6\\%\\\\\\hline\n\t\t2      & desert         & 6.41\\%\\\\\\hline\n\t\t3      & extremeHills   & 9.44\\%\\\\\\hline\n\t\t4      & forest         & 9.43\\%\\\\\\hline\n\t\t5      & taiga          & 5.68\\%\\\\\\hline\n\t\t6      & swampland      & 3.75\\%\\\\\\hline\n\t\t12     & icePlains      & 4.80\\%\\\\\\hline\n\t\t14     & mushroomIsland & 0.0773\\%\\\\\\hline\n\t\t21     & jungle         & 1.58\\%\\\\\\hline\n\t\t24     & deepOcean      & 9.38\\%\\\\\\hline\n\t\t27     & birchForest    & 3.75\\%\\\\\\hline\n\t\t29     & roofedForest   & 3.75\\%\\\\\\hline\n\t\t30     & coldTaiga      & 1.60\\%\\\\\\hline\n\t\t32     & megaTaiga      & 1.58\\%\\\\\\hline\n\t\t35     & savanna        & 4.28\\%\\\\\\hline\n\t\t38     & mesaPlateau\\_F & 0.598\\%\\\\\\hline\n\t\t39     & mesaPlateau    & 0.299\\%\\\\\\hline\n\t\\end{tabular}\n\n\t\\medskip\\noindent\n\tAssigns the actual biome IDs to the lands, based on the temperature category of the land. To be more specific the selection criteria are: \n\t\n\t\\begin{tabular}{l c c l}\n\t\n\tTemperature & & Weight & Biome \\\\\\hline\\hline\n\t\n\tWarm & $\\longrightarrow$ & \n\t\\makecell[c]{1/2 \\\\ 1/3 \\\\ 1/6} &\n\t\\makecell[l]{desert \\\\ savanna \\\\ plains} \\\\\\hline\n\t\n\tWarm, special & $\\longrightarrow$ &\n\t\\makecell[c]{1/3 \\\\ 2/3} &\n\t\\makecell[l]{mesaPlateau \\\\ mesaPlateau\\_F} \\\\\\hline\n\t\n\tLush & $\\longrightarrow$ & \n\t\\makecell[c]{1/6 \\\\ 1/6 \\\\ 1/6 \\\\ 1/6 \\\\ 1/6 \\\\ 1/6} &\n\t\\makecell[l]{forest \\\\ roofedForest \\\\ extremeHills \\\\ plains \\\\ birchForest \\\\ swampland} \\\\\\hline\n\t\n\tLush, special & $\\longrightarrow$ & \n\t\\makecell[c]{1/1} &\n\tjungle \\\\\\hline\n\n\tCold & $\\longrightarrow$ & \n\t\\makecell[c]{1/4 \\\\ 1/4 \\\\ 1/4 \\\\ 1/4} &\n\t\\makecell[l]{forest \\\\ extremeHills \\\\ taiga \\\\ plains} \\\\\\hline\n\t\n\tCold, special & $\\longrightarrow$ & \n\t\\makecell[c]{1/1} &\n\tmegaTaiga \\\\\\hline\n\t\n\tFreezing& $\\longrightarrow$ & \n\t\\makecell[c]{3/4 \\\\ 1/4} & \n\t\\makecell[l]{icePlains \\\\ coldTaiga}\n\t\n\t\\end{tabular}\n\t\n\t\\medskip\\noindent\n\tOcean and Mushroom types are not affected by this layer. The special category is selected when one of the higher bits (0xF00) are set. E.g. 0x603 has high bits and is thus a special Cold(3) category.\n\t\n\t\n\t\\subsection{Layer 20: Zoom}\n\t\\begin{tabular}{|l|l|l|}\\hline\n\t\tScale: & \\multicolumn{2}{|l|}{1:128} \\\\\\hline\\hline\n\t\tValue  & Type           & Occurrence \\\\\\hline\n\t\t0      & ocean          & 23.6\\%\\\\\\hline\n\t\t1      & plains         & 11.3\\%\\\\\\hline\n\t\t2      & desert         & 6.48\\%\\\\\\hline\n\t\t3      & extremeHills   & 9.28\\%\\\\\\hline\n\t\t4      & forest         & 9.28\\%\\\\\\hline\n\t\t5      & taiga          & 5.52\\%\\\\\\hline\n\t\t6      & swampland      & 3.61\\%\\\\\\hline\n\t\t12     & icePlains      & 4.94\\%\\\\\\hline\n\t\t14     & mushroomIsland & 0.0586\\%\\\\\\hline\n\t\t21     & jungle         & 1.62\\%\\\\\\hline\n\t\t24     & deepOcean      & 9.09\\%\\\\\\hline\n\t\t27     & birchForest    & 3.61\\%\\\\\\hline\n\t\t29     & roofedForest   & 3.61\\%\\\\\\hline\n\t\t30     & coldTaiga      & 1.45\\%\\\\\\hline\n\t\t32     & megaTaiga      & 1.62\\%\\\\\\hline\n\t\t35     & savanna        & 4.12\\%\\\\\\hline\n\t\t38     & mesaPlateau\\_F & 0.602\\%\\\\\\hline\n\t\t39     & mesaPlateau    & 0.279\\%\\\\\\hline\n\t\\end{tabular}\n\n\t\n\t\\subsection{Layer 21: Zoom}\n\t\\begin{tabular}{|l|l|l|}\\hline\n\t\tScale: & \\multicolumn{2}{|l|}{1:64} \\\\\\hline\\hline\n\t\tValue  & Type           & Occurrence \\\\\\hline\n\t\t0      & ocean          & 23.9\\%\\\\\\hline\n\t\t1      & plains         & 11.2\\%\\\\\\hline\n\t\t2      & desert         & 6.50\\%\\\\\\hline\n\t\t3      & extremeHills   & 9.23\\%\\\\\\hline\n\t\t4      & forest         & 9.23\\%\\\\\\hline\n\t\t5      & taiga          & 5.49\\%\\\\\\hline\n\t\t6      & swampland      & 3.56\\%\\\\\\hline\n\t\t12     & icePlains      & 5.00\\%\\\\\\hline\n\t\t14     & mushroomIsland & 0.0543\\%\\\\\\hline\n\t\t21     & jungle         & 1.62\\%\\\\\\hline\n\t\t24     & deepOcean      & 9.03\\%\\\\\\hline\n\t\t27     & birchForest    & 3.58\\%\\\\\\hline\n\t\t29     & roofedForest   & 3.57\\%\\\\\\hline\n\t\t30     & coldTaiga      & 1.43\\%\\\\\\hline\n\t\t32     & megaTaiga      & 1.62\\%\\\\\\hline\n\t\t35     & savanna        & 4.08\\%\\\\\\hline\n\t\t38     & mesaPlateau\\_F & 0.603\\%\\\\\\hline\n\t\t39     & mesaPlateau    & 0.275\\%\\\\\\hline\n\t\\end{tabular}\n\t\\subsection{Layer 22: Biome Edge}\n\t\\begin{tabular}{|l|l|l|}\\hline\n\t\tScale: & \\multicolumn{2}{|l|}{1:64} \\\\\\hline\\hline\n\t\tValue  & Type             & Occurrence \\\\\\hline\n\t\t0      & ocean            & 23.9\\%\\\\\\hline\n\t\t1      & plains           & 11.2\\%\\\\\\hline\n\t\t2      & desert           & 6.48\\%\\\\\\hline\n\t\t3      & extremeHills     & 9.23\\%\\\\\\hline\n\t\t4      & forest           & 9.23\\%\\\\\\hline\n\t\t5      & taiga            & 6.01\\%\\\\\\hline\n\t\t6      & swampland        & 3.47\\%\\\\\\hline\n\t\t12     & icePlains        & 5.00\\%\\\\\\hline\n\t\t14     & mushroomIsland   & 0.0543\\%\\\\\\hline\n\t\t21     & jungle           & 1.62\\%\\\\\\hline\n\t\t23     & jungleEdge       & 0.0144\\%\\\\\\hline\n\t\t24     & deepOcean        & 9.03\\%\\\\\\hline\n\t\t27     & birchForest      & 3.58\\%\\\\\\hline\n\t\t29     & roofedForest     & 3.57\\%\\\\\\hline\n\t\t30     & coldTaiga        & 1.43\\%\\\\\\hline\n\t\t32     & megaTaiga        & 1.11\\%\\\\\\hline\n\t\t34     & extremeHillsPlus & 0.0111\\%\\\\\\hline\n\t\t35     & savanna          & 4.09\\%\\\\\\hline\n\t\t37     & mesa             & 0.321\\%\\\\\\hline\n \t\t38     & mesaPlateau\\_F   & 0.385\\%\\\\\\hline\n\t\t39     & mesaPlateau      & 0.172\\%\\\\\\hline\n\t\\end{tabular}\n\t\n\t\\medskip\\noindent\n\tIntroduces the biomes jungleEdge, extremeHillsPlus and mesa. The conditional biome changes that take place in this layer are:\n\t\n\t\\begin{tabular}{l c l}\n\t\tmesaPlateau\\_F & $\\longrightarrow$ & mesa\\\\\n\t\tmesaPlateau & $\\longrightarrow$ & mesa\\\\\n\t\tmegaTaiga & $\\longrightarrow$ & taiga\\\\\n\t\tdesert & $\\longrightarrow$ & extremeHillsPlus\\\\\n\t\tswampland & $\\longrightarrow$ & jungleEdge \\\\\n\t\tswampland & $\\longrightarrow$ & plains\n\t\\end{tabular}\n\n\t\\subsection{Layer 23: River Init}\n\t\n\tStarts a new branch of off Layer 18: Deep Ocean. This layer overwrites each map entry that is not Ocean(0) with a pseudo random number between 2 and 300000 (inclusive).\n\t\n\t\\subsection{Layer 24: Zoom}\n\t\\subsection{Layer 25: Zoom}\n\t\n\t\\subsection{Layer 26: Hills}\n\tThis is a multilayer which joins the biome generation with the river generator branch at the layers Biome Edge (22) and Zoom (25). However at this stage the river branch is mostly just used as a pseudo random number source. \n\t\n\t\\medskip\\noindent\n\t\\begin{tabular}{|l|l|l|}\\hline\n\t\tScale: & \\multicolumn{2}{|l|}{1:64} \\\\\\hline\\hline\n\t\tValue  & Type             & Occurrence \\\\\\hline\n\t\t0      & ocean            & 17.5\\%\\\\\\hline\n\t\t1      & plains           & 9.86\\%\\\\\\hline\n\t\t2      & desert           & 4.83\\%\\\\\\hline\n\t\t3      & extremeHills     & 6.95\\%\\\\\\hline\n\t\t4      & forest           & 8.87\\%\\\\\\hline\n\t\t5      & taiga            & 4.67\\%\\\\\\hline\n\t\t6      & swampland        & 3.36\\%\\\\\\hline\n\t\t12     & icePlains        & 3.54\\%\\\\\\hline\n\t\t13     & iceMountains     & 1.30\\%\\\\\\hline\n\t\t14     & mushroomIsland   & 0.0543\\%\\\\\\hline\n\t\t17     & desertHills      & 1.46\\%\\\\\\hline\n\t\t18     & forestHills      & 2.68\\%\\\\\\hline\n\t\t19     & taigaHills       & 1.15\\%\\\\\\hline\n\t\t21     & jungle           & 1.15\\%\\\\\\hline\n\t\t22     & jungleHills      & 0.420\\%\\\\\\hline\n\t\t23     & jungleEdge       & 0.0140\\%\\\\\\hline\n\t\t24     & deepOcean        & 14.4\\%\\\\\\hline\n\t\t27     & birchForest      & 2.58\\%\\\\\\hline\n\t\t28     & birchForestHills & 0.800\\%\\\\\\hline\n\t\t29     & roofedForest     & 2.57\\%\\\\\\hline\n\t\t30     & coldTaiga        & 1.11\\%\\\\\\hline\n\t\t31     & coldTaigaHills   & 0.282\\%\\\\\\hline\n\t\t32     & megaTaiga        & 0.688\\%\\\\\\hline\n\t\t33     & megaTaigaHills   & 0.344\\%\\\\\\hline\n\t\t34     & extremeHillsPlus & 1.80\\%\\\\\\hline\n\t\t35     & savanna          & 3.05\\%\\\\\\hline\n\t\t36     & savannaPlateau   & 0.830\\%\\\\\\hline\n\t\t37     & mesa             & 0.486\\%\\\\\\hline\n\t\t38     & mesaPlateau\\_F   & 0.240\\%\\\\\\hline\n\t\t39     & mesaPlateau      & 0.107\\%\\\\\\hline\n\t\\end{tabular}\n\t\\newpage\\noindent\n\t\\begin{tabular}{|l|l|l|}\\hline\n\t\t129    & Sunflower Plains     & 0.4816\\%\\\\\\hline\n\t\t130    & Desert M             & 0.1971\\%\\\\\\hline\n\t\t131    & Extreme Hills M      & 0.2944\\%\\\\\\hline\n\t\t132    & Flower Forest        & 0.4904\\%\\\\\\hline\n\t\t133    & Taiga M              & 0.1897\\%\\\\\\hline\n\t\t134    & Swampland M          & 0.1109\\%\\\\\\hline\n\t\t140    & Ice Plains Spikes    & 0.1606\\%\\\\\\hline\n\t\t149    & Jungle M             & 0.0511\\%\\\\\\hline\n\t\t151    & Jungle Edge M        & 0.0005\\%\\\\\\hline\n\t\t155    & Birch Forest M       & 0.1154\\%\\\\\\hline\n\t\t156    & Birch Forest Hills M & 0.0854\\%\\\\\\hline\n\t\t157    & Roofed Forest M      & 0.1144\\%\\\\\\hline\n\t\t158    & Cold Taiga M         & 0.0461\\%\\\\\\hline\n\t\t160    & Mega Spruce Taiga    & 0.0365\\%\\\\\\hline\n\t\t161    & Redwood Taiga Hills  & 0.0366\\%\\\\\\hline\n\t\t162    & Extreme Hills+ M     & 0.1913\\%\\\\\\hline\n\t\t163    & Savanna M            & 0.1240\\%\\\\\\hline\n\t\t164    & Savanna Plateau M    & 0.0853\\%\\\\\\hline\n\t\t165    & Mesa (Bryce)         & 0.0263\\%\\\\\\hline\n\t\t166    & Mesa Plateau F M     & 0.0123\\%\\\\\\hline\n\t\t167    & Mesa Plateau M       & 0.0056\\%\\\\\\hline\n\t\\end{tabular}\n\t\n\t\\medskip\\noindent\n\tNine new biomes: iceMountains, desertHills, forestHills, taigaHills, jungleHills, birchForestHills, coldTaigaHills, megaTaigaHills and savannaPlateau. Also there are 21 new mutated variants which I have listed by their ingame display name.\n\t\n\tThis layer converts some map entries to related biomes, forming small biome patches. A list of the conversions that take place in this manor is shown below. Additionally, this layer adds 128 to some map entries, provided that the resulting biome ID is valid, forming mutated biome variants.\n\t\n\t\\begin{tabular}{l c l}\n\t\tdesert & $\\longrightarrow$ & desertHill\\\\\n\t\tforest & $\\longrightarrow$ & forestHills\\\\\n\t\tbirchForest & $\\longrightarrow$ & birchForestHills\\\\\n\t\troofedForest & $\\longrightarrow$ & plains\\\\\n\t\ttaiga & $\\longrightarrow$ & taigaHills\\\\\n\t\tmegaTaiga & $\\longrightarrow$ & megaTaigaHills\\\\\n\t\tcoldTaiga & $\\longrightarrow$ & coldTaigaHills\\\\\n\t\tplains & $\\longrightarrow$ & (1/3) forestHills, (2/3) forest\\\\\n\t\ticePlains & $\\longrightarrow$ & iceMountains\\\\\n\t\tjungle & $\\longrightarrow$ & jungleHills\\\\\n\t\tocean & $\\longrightarrow$ & deepOcean\\\\\n\t\textremeHills & $\\longrightarrow$ & extremeHillsPlus\\\\\n\t\tsavanna & $\\longrightarrow$ & savannaPlateau\\\\\n\t\tmesaPlateau\\_F & $\\longrightarrow$ & mesa\\\\\n\t\tdeepOcean & $\\longrightarrow$ & (1/2) plains, (1/2) forest\n\t\\end{tabular}\n\t\n\t\\subsection{Layer 27: Rare Biome}\n\t\\begin{tabular}{|l|l|l|}\\hline\n\t\tScale: & \\multicolumn{2}{|l|}{1:64} \\\\\\hline\\hline\n\t\tValue  & Type             & Occurrence \\\\\\hline\n\t\t1      & plains           & 9.68\\%\\\\\\hline\n\t\t129    & Sunflower Plains & 0.654\\%\\\\\\hline\n\t\t...    & ...              & ...\\\\\\hline\n\t\\end{tabular}\n\t\n\t\\medskip\\noindent\n\tThis layer converts 1/57 th of Plains to Sunflower Plains. It has no affect on other biomes.\n\t\n\t\\subsection{Layer 31: Shore}\n\t\\begin{tabular}{|l|l|l|}\\hline\n\t\tScale: & \\multicolumn{2}{|l|}{1:16} \\\\\\hline\\hline\n\t\tValue  & Type                & Occurrence \\\\\\hline\n\t\t0      & ocean               & 15.7\\%\\\\\\hline\n\t\t1      & plains              & 8.93\\%\\\\\\hline\n\t\t2      & desert              & 4.59\\%\\\\\\hline\n\t\t3      & extremeHills        & 6.68\\%\\\\\\hline\n\t\t4      & forest              & 8.67\\%\\\\\\hline\n\t\t5      & taiga               & 4.39\\%\\\\\\hline\n\t\t6      & swampland           & 3.44\\%\\\\\\hline\n\t\t12     & icePlains           & 3.44\\%\\\\\\hline\n\t\t13     & iceMountains        & 1.15\\%\\\\\\hline\n\t\t14     & mushroomIsland      & 0.0370\\%\\\\\\hline\n\t\t15     & mushroomIslandShore & 0.0208\\%\\\\\\hline\n\t\t16     & beach               & 3.81\\%\\\\\\hline\n\t\t17     & desertHills         & 1.27\\%\\\\\\hline\n\t\t18     & forestHills         & 2.27\\%\\\\\\hline\n\t\t19     & taigaHills          & 0.975\\%\\\\\\hline\n\t\t21     & jungle              & 1.03\\%\\\\\\hline\n\t\t22     & jungleHills         & 0.359\\%\\\\\\hline\n\t\t23     & jungleEdge          & 0.0853\\%\\\\\\hline\n\t\t24     & deepOcean           & 15.7\\%\\\\\\hline\n\t\t25     & stoneBeach          & 0.534\\%\\\\\\hline\n\t\t26     & coldBeach           & 0.311\\%\\\\\\hline\n\t\t27     & birchForest         & 2.45\\%\\\\\\hline\n\t\t28     & birchForestHills    & 0.800\\%\\\\\\hline\n\t\t29     & roofedForest        & 2.57\\%\\\\\\hline\n\t\t30     & coldTaiga           & 1.07\\%\\\\\\hline\n\t\t31     & coldTaigaHills      & 0.246\\%\\\\\\hline\n\t\t32     & megaTaiga           & 0.691\\%\\\\\\hline\n\t\t33     & megaTaigaHills      & 0.313\\%\\\\\\hline\n\t\t34     & extremeHillsPlus    & 2.84\\%\\\\\\hline\n\t\t35     & savanna             & 3.05\\%\\\\\\hline\n\t\t36     & savannaPlateau      & 0.715\\%\\\\\\hline\n\t\t37     & mesa                & 0.469\\%\\\\\\hline\n\t\t38     & mesaPlateau\\_F      & 0.242\\%\\\\\\hline\n\t\t39     & mesaPlateau         & 0.103\\%\\\\\\hline\n\t\\end{tabular}\n\t\\newpage\\noindent\n\t\\begin{tabular}{|l|l|l|}\\hline\n\t\t129    & Sunflower Plains     & 0.571\\%\\\\\\hline\n\t\t130    & Desert M             & 0.188\\%\\\\\\hline\n\t\t131    & Extreme Hills M      & 0.284\\%\\\\\\hline\n\t\t132    & Flower Forest        & 0.430\\%\\\\\\hline\n\t\t133    & Taiga M              & 0.176\\%\\\\\\hline\n\t\t134    & Swampland M          & 0.111\\%\\\\\\hline\n\t\t140    & Ice Plains Spikes    & 0.157\\%\\\\\\hline\n\t\t149    & Jungle M             & 0.0492\\%\\\\\\hline\n\t\t151    & Jungle Edge M        & 0.000451\\%\\\\\\hline\n\t\t155    & Birch Forest M       & 0.109\\%\\\\\\hline\n\t\t156    & Birch Forest Hills M & 0.0827\\%\\\\\\hline\n\t\t157    & Roofed Forest M      & 0.114\\%\\\\\\hline\n\t\t158    & Cold Taiga M         & 0.0477\\%\\\\\\hline\n\t\t160    & Mega Spruce Taiga    & 0.0358\\%\\\\\\hline\n\t\t161    & Redwood Taiga Hills  & 0.0354\\%\\\\\\hline\n\t\t162    & Extreme Hills+ M     & 0.184\\%\\\\\\hline\n\t\t163    & Savanna M            & 0.119\\%\\\\\\hline\n\t\t164    & Savanna Plateau M    & 0.0824\\%\\\\\\hline\n\t\t165    & Mesa (Bryce)         & 0.0236\\%\\\\\\hline\n\t\t166    & Mesa Plateau F M     & 0.0121\\%\\\\\\hline\n\t\t167    & Mesa Plateau M       & 0.00566\\%\\\\\\hline\n\t\\end{tabular}\n\t\n\t\\medskip\\noindent\n\tNew biomes: mushroomIslandShore, beach, stoneBeach, coldBeach.\n\n\t\\subsection{Layer 41: River}\n\t\\begin{tabular}{|l|l|l|}\\hline\n\t\tScale: & \\multicolumn{2}{|l|}{1:4} \\\\\\hline\\hline\n\t\tValue  & Type             & Occurrence \\\\\\hline\n\t\t-1     & none             & 94.3\\%\\\\\\hline\n\t\t7      & river            & 5.70\\%\\\\\\hline\n\t\\end{tabular}\n\t\n\t\\medskip\\noindent\n\tUses the zoomed pseudo random output of the river branch to determine the position of rivers in the world. All other values are set to -1.\n\n\t\\subsection{Layer 43: River Mix}\n\t\\begin{tabular}{|l|l|l|}\\hline\n\t\tScale: & \\multicolumn{2}{|l|}{1:4} \\\\\\hline\\hline\n\t\tValue  & Type                & Occurrence \\\\\\hline\n\t\t0      & ocean               & 13.9\\%\\\\\\hline\n\t\t1      & plains              & 9.69\\%\\\\\\hline\n\t\t2      & desert              & 4.80\\%\\\\\\hline\n\t\t3      & extremeHills        & 7.24\\%\\\\\\hline\n\t\t4      & forest              & 9.21\\%\\\\\\hline\n\t\t5      & taiga               & 4.47\\%\\\\\\hline\n\t\t6      & swampland           & 4.03\\%\\\\\\hline\n\t\t7      & river               & 4.19\\%\\\\\\hline\n\t\t11     & frozenRiver         & 0.0872\\%\\\\\\hline\n\t\t12     & icePlains           & 1.52\\%\\\\\\hline\n\t\t13     & iceMountains        & 0.495\\%\\\\\\hline\n\t\t14     & mushroomIsland      & 0.0257\\%\\\\\\hline\n\t\t15     & mushroomIslandShore & 0.0172\\%\\\\\\hline\n\t\t16     & beach               & 2.96\\%\\\\\\hline\n\t\t17     & desertHills         & 1.33\\%\\\\\\hline\n\t\t18     & forestHills         & 2.50\\%\\\\\\hline\n\t\t19     & taigaHills          & 0.994\\%\\\\\\hline\n\t\t21     & jungle              & 1.21\\%\\\\\\hline\n\t\t22     & jungleHills         & 0.421\\%\\\\\\hline\n\t\t23     & jungleEdge          & 0.101\\%\\\\\\hline\n\t\t24     & deepOcean           & 12.7\\%\\\\\\hline\n\t\t25     & stoneBeach          & 0.426\\%\\\\\\hline\n\t\t26     & coldBeach           & 0.132\\%\\\\\\hline\n\t\t27     & birchForest         & 2.96\\%\\\\\\hline\n\t\t28     & birchForestHills    & 0.849\\%\\\\\\hline\n\t\t29     & roofedForest        & 2.93\\%\\\\\\hline\n\t\t30     & coldTaiga           & 0.466\\%\\\\\\hline\n\t\t31     & coldTaigaHills      & 0.107\\%\\\\\\hline\n\t\t32     & megaTaiga           & 0.704\\%\\\\\\hline\n\t\t33     & megaTaigaHills      & 0.316\\%\\\\\\hline\n\t\t34     & extremeHillsPlus    & 1.69\\%\\\\\\hline\n\t\t35     & savanna             & 2.97\\%\\\\\\hline\n\t\t36     & savannaPlateau      & 0.750\\%\\\\\\hline\n\t\t37     & mesa                & 0.456\\%\\\\\\hline\n\t\t38     & mesaPlateau\\_F      & 0.251\\%\\\\\\hline\n\t\t39     & mesaPlateau         & 0.110\\%\\\\\\hline\n\t\\end{tabular}\n\t\\newpage\\noindent\n\t\\begin{tabular}{|l|l|l|}\\hline\n\t\t129    & Sunflower Plains     & 0.616\\%\\\\\\hline\n\t\t130    & Desert M             & 0.205\\%\\\\\\hline\n\t\t131    & Extreme Hills M      & 0.315\\%\\\\\\hline\n\t\t132    & Flower Forest        & 0.477\\%\\\\\\hline\n\t\t133    & Taiga M              & 0.184\\%\\\\\\hline\n\t\t134    & Swampland M          & 0.130\\%\\\\\\hline\n\t\t140    & Ice Plains Spikes    & 0.0681\\%\\\\\\hline\n\t\t149    & Jungle M             & 0.0582\\%\\\\\\hline\n\t\t151    & Jungle Edge M        & 0.000625\\%\\\\\\hline\n\t\t155    & Birch Forest M       & 0.136\\%\\\\\\hline\n\t\t156    & Birch Forest Hills M & 0.101\\%\\\\\\hline\n\t\t157    & Roofed Forest M      & 0.136\\%\\\\\\hline\n\t\t158    & Cold Taiga M         & 0.0196\\%\\\\\\hline\n\t\t160    & Mega Spruce Taiga    & 0.0371\\%\\\\\\hline\n\t\t161    & Redwood Taiga Hills  & 0.0369\\%\\\\\\hline\n\t\t162    & Extreme Hills+ M     & 0.203\\%\\\\\\hline\n\t\t163    & Savanna M            & 0.128\\%\\\\\\hline\n\t\t164    & Savanna Plateau M    & 0.0882\\%\\\\\\hline\n\t\t165    & Mesa (Bryce)         & 0.0257\\%\\\\\\hline\n\t\t166    & Mesa Plateau F M     & 0.0134\\%\\\\\\hline\n\t\t167    & Mesa Plateau M       & 0.00585\\%\\\\\\hline\n\t\\end{tabular}\n\t\n\t\\medskip\\noindent\n\tThis layer is actually used in parts of the Minecraft code where a faster alternative for the full biome generator is required. Note that this layer has a scale of 1:4 and the final map is just a zoomed version of this layer's output. The function of this layer is to apply the rivers to the main biome branch. A new biome is also added in this layer: frozenRiver.\n\t\n\n\t\\subsection{Layer 44: Voronoi Zoom}\n\t\\begin{tabular}{|l|l|l|}\\hline\n\t\tScale: & \\multicolumn{2}{|l|}{1:1} \\\\\\hline\\hline\n\t\tValue  & Type                & Occurrence \\\\\\hline\n\t\t0      & ocean               & 13.7\\%\\\\\\hline\n\t\t1      & plains              & 10.0\\%\\\\\\hline\n\t\t2      & desert              & 4.84\\%\\\\\\hline\n\t\t3      & extremeHills        & 7.50\\%\\\\\\hline\n\t\t4      & forest              & 9.54\\%\\\\\\hline\n\t\t5      & taiga               & 4.59\\%\\\\\\hline\n\t\t6      & swampland           & 4.22\\%\\\\\\hline\n\t\t7      & river               & 4.30\\%\\\\\\hline\n\t\t11     & frozenRiver         & 0.0806\\%\\\\\\hline\n\t\t12     & icePlains           & 1.40\\%\\\\\\hline\n\t\t13     & iceMountains        & 0.451\\%\\\\\\hline\n\t\t14     & mushroomIsland      & 0.0209\\%\\\\\\hline\n\t\t15     & mushroomIslandShore & 0.0137\\%\\\\\\hline\n\t\t16     & beach               & 2.92\\%\\\\\\hline\n\t\t17     & desertHills         & 1.33\\%\\\\\\hline\n\t\t18     & forestHills         & 2.59\\%\\\\\\hline\n\t\t19     & taigaHills          & 1.00\\%\\\\\\hline\n\t\t21     & jungle              & 1.26\\%\\\\\\hline\n\t\t22     & jungleHills         & 0.429\\%\\\\\\hline\n\t\t23     & jungleEdge          & 0.118\\%\\\\\\hline\n\t\t24     & deepOcean           & 11.2\\%\\\\\\hline\n\t\t25     & stoneBeach          & 0.433\\%\\\\\\hline\n\t\t26     & coldBeach           & 0.118\\%\\\\\\hline\n\t\t27     & birchForest         & 3.12\\%\\\\\\hline\n\t\t28     & birchForestHills    & 0.890\\%\\\\\\hline\n\t\t29     & roofedForest        & 3.09\\%\\\\\\hline\n\t\t30     & coldTaiga           & 0.428\\%\\\\\\hline\n\t\t31     & coldTaigaHills      & 0.0984\\%\\\\\\hline\n\t\t32     & megaTaiga           & 0.675\\%\\\\\\hline\n\t\t33     & megaTaigaHills      & 0.303\\%\\\\\\hline\n\t\t34     & extremeHillsPlus    & 1.74\\%\\\\\\hline\n\t\t35     & savanna             & 3.00\\%\\\\\\hline\n\t\t36     & savannaPlateau      & 0.751\\%\\\\\\hline\n\t\t37     & mesa                & 0.464\\%\\\\\\hline\n\t\t38     & mesaPlateau\\_F      & 0.238\\%\\\\\\hline\n\t\t39     & mesaPlateau         & 0.105\\%\\\\\\hline\n\t\\end{tabular}\n\t\\newpage\\noindent\n\t\\begin{tabular}{|l|l|l|}\\hline\n\t\t129    & Sunflower Plains     & 0.635\\%\\\\\\hline\n\t\t130    & Desert M             & 0.203\\%\\\\\\hline\n\t\t131    & Extreme Hills M      & 0.325\\%\\\\\\hline\n\t\t132    & Flower Forest        & 0.491\\%\\\\\\hline\n\t\t133    & Taiga M              & 0.190\\%\\\\\\hline\n\t\t134    & Swampland M          & 0.134\\%\\\\\\hline\n\t\t140    & Ice Plains Spikes    & 0.0625\\%\\\\\\hline\n\t\t149    & Jungle M             & 0.0612\\%\\\\\\hline\n\t\t151    & Jungle Edge M        & 0.000781\\%\\\\\\hline\n\t\t155    & Birch Forest M       & 0.144\\%\\\\\\hline\n\t\t156    & Birch Forest Hills M & 0.106\\%\\\\\\hline\n\t\t157    & Roofed Forest M      & 0.142\\%\\\\\\hline\n\t\t158    & Cold Taiga M         & 0.0181\\%\\\\\\hline\n\t\t160    & Mega Spruce Taiga    & 0.0356\\%\\\\\\hline\n\t\t161    & Redwood Taiga Hills  & 0.0354\\%\\\\\\hline\n\t\t162    & Extreme Hills+ M     & 0.210\\%\\\\\\hline\n\t\t163    & Savanna M            & 0.129\\%\\\\\\hline\n\t\t164    & Savanna Plateau M    & 0.0885\\%\\\\\\hline\n\t\t165    & Mesa (Bryce)         & 0.0258\\%\\\\\\hline\n\t\t166    & Mesa Plateau F M     & 0.0131\\%\\\\\\hline\n\t\t167    & Mesa Plateau M       & 0.00559\\%\\\\\\hline\n\t\\end{tabular}\n\t\n\t\\medskip\\noindent\n\tThis is the final layer in the biome generator and contains all the Overworld biomes except for frozenOcean, which does not generate in Mincraft 1.7 - 1.12.\n\t\n\\end{document}\n\n\n\n", "meta": {"hexsha": "056efa801a2e3e2d4ab0900802f94fea8b32d3a1", "size": 32680, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/LayerSummary.tex", "max_stars_repo_name": "MCPfannkuchenYT/cubiomes", "max_stars_repo_head_hexsha": "53059ed1ec193fb1da87d4940c18e46f86066370", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 263, "max_stars_repo_stars_event_min_datetime": "2016-04-19T10:20:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T11:30:31.000Z", "max_issues_repo_path": "docs/LayerSummary.tex", "max_issues_repo_name": "MCPfannkuchenYT/cubiomes", "max_issues_repo_head_hexsha": "53059ed1ec193fb1da87d4940c18e46f86066370", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 55, "max_issues_repo_issues_event_min_datetime": "2018-05-01T14:54:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T08:34:38.000Z", "max_forks_repo_path": "docs/LayerSummary.tex", "max_forks_repo_name": "MCPfannkuchenYT/cubiomes", "max_forks_repo_head_hexsha": "53059ed1ec193fb1da87d4940c18e46f86066370", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 79, "max_forks_repo_forks_event_min_datetime": "2016-04-19T13:14:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T21:02:01.000Z", "avg_line_length": 42.6075619296, "max_line_length": 712, "alphanum_fraction": 0.55125459, "num_tokens": 12888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3094639279221546}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\subsection{Cold Dark Matter relics}\n\n\\marginpar{Wednesday\\\\ 2020-12-9, \\\\ compiled \\\\ \\today}\n\nCDM particles, definitionally, decouple when they are \\emph{not} relativistic, so \\(z_f = m_\\psi / T > 1\\) at freezeout; recall that freezeout is defined as the moment when the inequality \\(\\Gamma _A / A \\lesssim 1\\) starts to be satisfied, where \\(\\Gamma _A\\) refers to the annihilation process \\(\\psi \\overline{\\psi} \\leftrightarrow X \\overline{X}\\). \n\nIf we define \\(y = n_\\psi / s\\), we can draw the usual decay curve \\(y = y(z)\\), which is constant and then has a decay (something like an inverted sigmoid); at decoupling the amount stops changing, and its value depends on \\(z\\) at that time. \nThe Boltzmann equation reads \n%\n\\begin{align}\n\\dv{y}{z} = \\frac{- zs \\expval{\\sigma _A \\abs{v}}}{H (z=1)} \\qty(y^2 - y^2 _{\\text{eq}})\n\\,.\n\\end{align}\n\nTypically we can model the term \\(\\expval{\\sigma_A \\abs{v}}\\) as a powerlaw: \n%\n\\begin{align}\n\\expval{\\sigma_A \\abs{v}} &\\sim T^{n} \\\\\n\\expval{\\sigma_A \\abs{v}} &= \\sigma_0 \\qty( \\frac{T}{m})^{n} = \\sigma_0 \\overline{z}^{-n}\n\\,,\n\\end{align}\n%\ntherefore the differential equation for the abundance \\(y\\) reads \n%\n\\begin{align}\n\\dv{y}{z} &= - \\frac{\\lambda}{z^{2 + n}} \\qty(y^2 - y^2 _{\\text{eq}}) \\\\\n\\lambda &= \\frac{z^3 s \\sigma_0 }{H(z=1)}\n\\,,\n\\end{align}\n%\nbut recall that \n%\n\\begin{align}\nz^3 &= \\qty( \\frac{m}{T})^3  \\\\\ns &= \\frac{2 \\pi^2}{45} g_* T^3  \\\\\nH(z=1) &=  \\qty(\\frac{8 \\pi G}{3})^{1/2} \\qty(\\frac{\\pi^2}{30})^{1/2}\ng_*^{1/2} \\underbrace{\\eval{T^2}_{z=1}}_{= m_\\psi^2}\n\\marginnote{See \\eqref{eq:decoupling-hubble-rate}.}\n\\,,\n\\end{align}\n%\nand with all these substitutions we can write \n%\n\\begin{align}\n\\lambda \\approx \\num{.264} m_P m_\\psi \\sigma_0 \\frac{g_{*s}}{g_*^{1/2}}\n\\,.\n\\end{align}\n\nFurther, we can model the equilibrium abundance as \n%\n\\begin{align}\ny _{\\text{eq}} = \\num{.145} \\qty(\\frac{g_*}{g_{*s}}) z^{3/2} e^{z}\n\\,,\n\\end{align}\n%\nwith \\(z > 1\\). \n\nNow, let us define \\(\\Delta = y - y _{\\text{eq}} \\); then, denoting derivatives with respect to \\(z\\) with primes we get\n%\n\\begin{align}\n\\Delta' = - y' _{\\text{eq}} - \\frac{\\lambda}{z^{2+n}} \\qty(\\Delta + 2 y _{\\text{eq}}) \\Delta \n\\,,\n\\end{align}\n%\nwhich can be solved by distinguishing two regimes: the first is for \\textbf{early times}, defined by \\(1 < z < z_f\\), meaning that the particle is relativistic but still coupled.\nThis tells us that both \\(\\Delta \\) and \\(\\Delta '\\) are small; with this we can write \n%\n\\begin{align}\\label{eq:differential-equation-equilibrium-deviation-boltzmann}\n\\Delta &\\approx \\frac{z^{2+n}}{\\lambda } \\frac{- y' _{\\text{eq}}}{\\Delta + 2 y _{\\text{eq}}}  \\\\\n&\\approx \\frac{z^{2+n}}{\\lambda } \\frac{- y' _{\\text{eq}}}{2 y _{\\text{eq}}}  \\\\\n&\\approx \\frac{z^{2+n}}{\\lambda }\n \\frac{y _{\\text{eq}}}{2 y _{\\text{eq}}} = \\frac{z^{2+n}}{2 \\lambda }\n\\,,\n\\end{align}\n%\nsince when we differentiate \\(y _{\\text{eq}}\\) one term is negligible.\n\\todo[inline]{I think, to check.}\n\nOn the other hand, at \\textbf{late times} \\(z \\gg z_f\\) we get \\(y(z) \\gg y _{\\text{eq}} (z)\\),\\footnote{This is true since \\(y\\) is the \\emph{actual} amount of particles in a comoving volume, while \\(y _{\\text{eq}}\\) is the amount which \\emph{would} be reached if there were equilibrium, which cannot happen due to decoupling.} therefore \\(\\Delta \\approx y\\). \nWith this approximation, we get \n%\n\\begin{align}\n\\Delta ' = - \\frac{\\lambda}{z^{2+n}} \\Delta^2\n\\,,\n\\end{align}\n%\nand solving this we find \n%\n\\begin{align}\n- \\frac{\\Delta '}{\\Delta^2} &\\approx \\frac{\\lambda }{z^{2 + n}}  \\\\\n\\frac{1}{\\Delta _\\infty } - \\frac{1}{\\Delta _f} &\\approx \\eval{- \\frac{\\lambda}{n+1} z^{-n-1}}_{z = z_f}^{z = \\infty } \\\\\n\\frac{1}{\\Delta_{\\infty }} - \\frac{1}{\\Delta _f} &\\approx  + \\frac{\\lambda }{z_f^{n+1} (n+1) }\n\\,,\n\\end{align}\n%\nbut \\(y_\\infty < y_f\\), meaning that we can neglect the \\(y_f\\) term and so \n%\n\\begin{align}\ny_\\infty \\approx \\frac{z_f^{n+1}(n+1)}{\\lambda } \\approx\n\\frac{\\num{3.79} (n+1) z_f^{n+1}}{(g_{*s} / g_*^{1/2}) m_P m_\\psi \\sigma_0 }\n\\,.\n\\end{align}\n\nFrom this, using \\(n_\\psi = s_0 y_\\infty \\) and the expression \\(s_0 \\approx \\SI{2e3}{cm^{-3}}\\) (if one neutrino species is relativistic today), then we can calculate \n%\n\\begin{align}\n\\Omega_{\\psi_0 } h^2 = \\frac{\\num{.75e9}(n+1)z_f^{n+1}}{(g_{*s} / g_*^{1/2}) m_P  \\sigma_0} \\SI{}{GeV^{-1}} \n\\,.\n\\end{align}\n\nHere we used \\(\\Omega _{\\psi_0 } = m_\\psi n_{\\psi_0 }  / \\rho _{\\text{crit}}\\), with \\(\\rho _{\\text{crit}} \\approx \\SI{e4}{eV cm^{-3} h^2}\\).\nWe appear to have eliminated the dependence on \\(m_\\psi \\), but this is not completely the case: \\(\\sigma_0\\), \\(z_f\\) and \\(g_*\\) still depend (at least weakly) on it. \n\nThe crucial result from this manipulation is \n%\n\\begin{align}\n\\Omega_{\\psi_0 } h^2 \\propto \\frac{1}{\\sigma_0 }\n\\,.\n\\end{align}\n\nThis is somewhat intuitive: if the particle interacts more then its abundance has more time to decrease with the Boltzmann suppression. \n\nManipulating the expression with some typical values, we get \n%\n\\begin{align}\n\\Omega_{\\psi_0} h^2 \\approx \\order{1} (n+1) \\qty(\\frac{z_f}{10})^{n+1}\n\\qty(\\frac{g_*}{100})^{1/2} \\qty(\\frac{100}{g_{*s}}) \\frac{\\SI{e-38}{cm^2}}{\\sigma_0 }\n\\,.\n\\end{align}\n\nThe natural normalization arising for \\(\\sigma_0\\) is \\SI{e-2}{pbn} (picobarns), a very small cross-section, which is the typical order of magnitude of weak-interaction cross-sections. \nThis is what is called the \\textbf{WIMP miracle}, where WIMP means Weakly-Interacting Massive Particle.\n\nThe freezout epoch is the one at which the abundance \\(y\\) departs from its equilibrium value: then, we ask that \\(\\Delta (z_f) = y(z_f) - y _{\\text{eq}} (z_f) = c y _{\\text{eq}}\\), with \\(c\\) being a coefficient of order unity.\n\nPlugging in the expression we derived earlier into \\eqref{eq:differential-equation-equilibrium-deviation-boltzmann}, we get \n%\n\\begin{align}\n\\Delta(z_f) = \\lambda^{-1} \\frac{z_f^{n+2} y_{\\text{eq}}(z_f)}{2 y _{\\text{eq}}(z_f) + \\Delta (z_f)} = \\frac{z_f^{n+2}}{\\lambda } \\frac{1}{2 + c}\n\\,,\n\\end{align}\n%\ntherefore \n%\n\\begin{align}\n\\frac{z_f^{n+2}}{\\lambda } \\frac{1}{2 + c}\n&= c a z_f^{3/2} e^{-z_f}  \\\\\na &= \\num{.145} \\frac{g_\\psi }{g_{*s}}\n\\,,\n\\end{align}\n%\na transcendental equation which can be solved iteratively, yielding \n%\n\\begin{align}\nz_f^{(0)} &= \\log \\qty[c (c+2) a \\lambda ]  \\\\\n&=\\log \\qty[\\num{.038} (n+1) m _{\\text{Pl}} m_\\psi \\sigma_0 \\frac{g_\\psi }{g_{*s}}]\n\\,,\n\\end{align}\n%\nand a good approximation is found to be \\(c ( c+ 2) = n+1\\). \nThe second iteration then yields \n%\n\\begin{align}\nz_f^{(1)} = \\log \\qty[c (c+2) a \\lambda ] - \\qty( \\frac{1}{2} + n) \\log \\qty[c (c+2) a \\lambda ]\n\\,,\n\\end{align}\n%\nwhich means that \\(z_f\\) does indeed depend on the mass of the particle, although it is a weak dependence since it is in the logarithm. \n\nAs an example, if \\(m_\\psi \\) were of the order of \\SI{100}{GeV} and if we had \\(\\sigma_0 \\sim \\SI{e-38}{cm^{-2}}\\), then we would get \n%\n\\begin{align}\nz_f \\approx \\begin{cases}\n    17 & \\text{for } n=0 \\\\\n    14 & \\text{for } n=1 \\\\\n    12 & \\text{for } n=2 \n\\end{cases}\n\\,.\n\\end{align}\n\nThis means that \\(T_f \\approx m_\\psi / 10\\), therefore \\(T_f \\approx 10 \\divisionsymbol \\SI{100}{GeV}\\) is the typical order of magnitude of the decoupling temperature. \nThe relics we discussed are \\emph{thermal}, but \\textbf{non-thermal} relics are also possible; their abundance is much more model-dependent. \nFor example, axions might be produced through a ``misalignment mechanism'', and other relics might be produced through a ``freeze-in mechanism''.\n\n\\todo[inline]{See picture from the slides: FIMP.}\n\n\\chapter{Cosmological perturbation within GR}\n\n\\section{The gauge issue}\n\nWe will treat the \\textbf{gauge issue} for perturbations. Einstein's equations are invariant under diffeomorphisms, so we must be careful and use invariant quantities. \nWe already used \n%\n\\begin{align}\n\\zeta  = - H \\frac{ \\delta \\rho}{\\dot{\\rho} } - \\hat{\\Phi}\n\\,,\n\\end{align}\n%\nwhere \\(\\hat{\\Phi}\\) is a scalar perturbation of the spatial part of the metric tensor, which will be discussed later. \n\nThen, we will try to get a proper treatment of cosmological perturbations within GR.\nWe have already seen how to treat them in a Newtonian way (i.e.\\ Jeans instability). \nThis is not ok when the wavelength of the perturbation is larger than the Hubble radius.\n\nThe Poisson equation, in terms of \\(\\delta = \\delta \\rho / \\rho \\), reads \n%\n\\begin{align}\n\\nabla^2 \\varphi = 4 \\pi G \\delta \\rho  = 4 \\pi G \\overline{\\rho} \\delta \n\\,,\n\\end{align}\n%\nso in terms of characteristic lengths we get \n%\n\\begin{align}\n\\frac{\\varphi}{\\lambda^2 _{\\text{phys}}} \\sim \\frac{3}{2} H^2 \\delta \n\\marginnote{From the Friedmann equations.}\n\\,,\n\\end{align}\n%\ntherefore, in terms of \\(\\lambda _H = 1 / H\\):\n%\n\\begin{align}\n\\varphi \\sim \\qty(\\frac{\\lambda _{\\text{phys}}}{\\lambda _H})^2 \\delta \n\\,,\n\\end{align}\n%\nand reintroducing the speed of light \n%\n\\begin{align}\n\\frac{\\varphi}{c^2} \\sim \\qty(\\frac{\\lambda _{\\text{phys}}}{\\lambda _H})^2 \\delta \n\\,.\n\\end{align}\n\nWhen \\(\\varphi / c^2\\) is of order 1 or larger we expect to see GR effects.\n\nWe know that typically \\(\\delta \\sim \\num{e-5}\\) for primordial perturbations, so when \\(\\lambda _{\\text{phys}} \\ll \\lambda _H\\) the Newtonian treatment is fine; while when the perturbations are outside the horizon the perturbations are frozen. \n\nWe will adopt a perturbative approach, which in GR is a perturbation of the geometry itself (as well as the fields). \nConsider a generic tensor field \\(T\\): a perturbation of this quantity is defined as \n%\n\\begin{align}\n\\Delta T = T - T_0 \n\\,,\n\\end{align}\n%\nwhere \\(T\\) is evaluated in the perturbed universe, while \\(T_0 \\) is evaluated in the unperturbed FLRW spacetime. \nWe are then comparing two tensors, but they will be defined at two different spacetime locations. \nThis is not allowed in differential geometry: in order to make the comparison meaningful we need a one-to-one correspondence between the perturbed and unperturbed spacetimes (denoted respectively as \\(\\mathcal{M}\\) and \\(\\mathcal{M}_0\\)); this amounts to making a specific gauge choice. \n\nA gauge transformation is a change of the map \\(\\mathcal{M}_0 \\to \\mathcal{M}\\) (which we denote as \\(\\psi \\), such that for \\(p \\in \\mathcal{M}_0\\) and \\(O\\in \\mathcal{M}\\) we have \\(p \\to O = \\psi (p)\\)) which \\emph{keeps the coordinates on \\(\\mathcal{M}_0\\) fixed}; this is different from a coordinate transformation.\n\nThe gauge issue comes from the freedom of always making a gauge transformation: changing the map \\(\\psi \\) to \\(\\psi' \\colon p \\to O' = \\psi '(p)\\). \n\nA coordinate system is defined by a threading of spacetime into lines (corresponding to fixed spatial coordinates) and by a slicing of spacetime into hypersurfaces (corresponding to fixed time).\n\nA gauge transformation can be defined in a completely coordinate-free way.\n\nWe can change our point of view: instead of changing the point in \\(\\mathcal{M}\\) to which our point in \\(\\mathcal{M}_0\\) maps, we can see the transformation as a change in the point in \\(\\mathcal{M}_0\\) from which we start to reach the fixed point in \\(\\mathcal{M}\\). \nIn terms of the points we defined before, this amounts to finding a \\(q \\in \\mathcal{M}_0\\) such that \\(\\psi' (q) = O\\), and then seeing the gauge transformation as a map which takes \\(p\\) to \\(q = \\psi^{\\prime, -1} (\\psi (p))\\). \n\nIf we have a quantity \\(T\\) which is a scalar under coordinate transformation, then it still \\emph{can} change if we make a gauge transformation. \n\n\\end{document}\n", "meta": {"hexsha": "4dfb6aeb5278e894f57673e22bf6d9aaf1083d0b", "size": 11480, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ap_third_semester/early_universe/dec09.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "ap_third_semester/early_universe/dec09.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ap_third_semester/early_universe/dec09.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 42.9962546816, "max_line_length": 361, "alphanum_fraction": 0.6677700348, "num_tokens": 3872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3094639279221546}}
{"text": "\\documentclass{aiaa-tc}\n\n\\usepackage{color}\n\\usepackage{amsmath}\n%\\usepackage{overcite}\n\\usepackage{graphicx}\n\\usepackage{subfig}\n\\usepackage{authblk}\n\\usepackage{amsfonts}\n\n\\input basic.ltx\n\\def\\directory{EPSF/}\n\n%------------------------------------------------------------------------------\n% MAS Additions\n\\newcommand{\\mas}[1]{\\textcolor{magenta}{#1}}\n\\newcommand{\\qw}[1]{\\textcolor{blue}{#1}}\n%useful for showing deleted text\n\\renewcommand{\\kill}[1]{\\textcolor{red}{\\sout{#1}}}                             \n\n\\usepackage[normalem]{ulem}  % mas addition\n\\newcommand{\\uvec}[1]{\\bar{#1}}\n\\newcommand{\\tens}[1]{\\underline{\\underline{#1}}}\n\\renewcommand{\\vec}[1]{\\underline{#1}}\n\\renewcommand{\\skew}[1]{\\widetilde{#1}}\n%------------------------------------------------------------------------------\n\n\\title{BeamDyn: A High-Fidelity Wind Turbine Blade Solver in the FAST\nModular Framework}\n\n\n\\author[1]{Qi Wang\\thanks{Research Engineer, National Wind Technology Center, AIAA Member. Email: Qi.Wang2@nrel.gov}}\n\\author[2]{Nick Johnson\\thanks{Graduate Research Assistant, Department of\nMechanical Engineering.}}\n \\author[1]{Michael A. Sprague\\thanks{Senior Research Scientist, \nComputational Science Center.}}\n \\author[1]{Jason Jonkman\\thanks{Senior Engineer, National Wind Technology Center, AIAA Professional Member.}}\n \\affil[1]{National Renewable Energy Laboratory, Golden, CO 80401}\n \\affil[2]{Colorado School of Mines, Golden, CO 80401}\n \n \\renewcommand\\Authands{, and }\n\n\\begin{document}\n\n\\maketitle\n\n\\begin{abstract}\n{BeamDyn, a Legendre-spectral-finite-element implementation of geometrically\nexact beam theory (GEBT), was developed to meet the design challenges\nassociated with highly flexible composite wind turbine blades. In this\npaper, the governing equations of GEBT are reformulated into a nonlinear\nstate-space form to support its coupling within the\nmodular framework of the FAST wind turbine\ncomputer-aided engineering (CAE) tool. Different time integration\nschemes (implicit and explicit) were implemented and examined for wind\nturbine analysis.  Numerical examples are presented to demonstrate the capability of this new beam solver. An example analysis of a realistic wind turbine blade, the CX-100, is also presented as validation.}     \n\\end{abstract}\n\n\\section{Introduction} In recent years, wind power installations in the United States have exceeded 60\ngigawatts in generation capacity, and have become an increasingly important part of the overall energy\nportfolio. Simultaneously, the size of wind turbines has also increased in\nthe quest for economies of scale.   To ensure the performance and\nreliability of wind turbines, it is crucial to use computer-aided engineering (CAE) tools that are capable of analyzing wind\nturbine blades accurately and efficiently. Although modern\ncomputers enable three-dimensional (3D) analysis\nof a fully resolved blade, such analyses are too\nexpensive for iterative and probabilistic design. However, composite wind\nturbine blades are well represented as nonlinear beam models, which can\ncapture the deformation response under realistic\noperating conditions with high fidelity, and in a small fraction of the time required by a\nfully resolved 3D simulation. \n\nBeam models are widely used to analyze structures in which one dimension is much larger than the other two.  Many engineering\nstructures such as  bridges, joists, and helicopter\nrotor blades may be modeled as beams.  Similarly, beam models are well suited for analyzing wind turbine blades, towers, and shafts.  Most wind turbine\nblades are constructed of composite materials, which are more complicated than isotropic beams to analyze because of elastic coupling\neffects, high flexibility, and initial twist/curvatures.  The geometrically exact beam theory (GEBT), first proposed by\nReissner\\cite{Ressiner1973}, is a beam-deformation model useful in efficient analysis of highly flexible composite structures.\nFor instance, GEBT has demonstrated efficacy in helicopter rotor analysis \\cite{Hodges:2007}. \nSimo\\cite{Simo1985} and Simo and Vu-Quoc\\cite{Simo1986} extended Reissner's\nwork to include 3D dynamic problems. Jeleni\\'c and\nCrisfield\\cite{Crisfield1999} derived a finite-element (FE) method that\ninterpolates the rotation field, thereby preserving the geometric exactness\nof this theory. Notably, Ibrahimbegovi\\'c and his colleagues\nimplemented this theory for static\\cite{Ibrahim1995} and\ndynamic\\cite{Ibrahim1998} analysis. Readers are referred to\nHodges\\cite{HodgesBeamBook}, in which comprehensive derivations and discussions\non nonlinear composite-beam theories can be found. Recently, a mixed\n FE formulation of GEBT along with the numerical implementation was presented by\nYu and Blair\\cite{YuGEBT}.  \n\nFAST is a CAE tool developed by the National Renewable Energy Laboratory\n(NREL) for analyzing both land-based and\noffshore wind turbines under realistic operating conditions.  The current\nbeam model in FAST is not capable of predictive analysis of highly flexible,\ncomposite wind turbine blades.\nRecently, FAST has been reformulated under a\nnew modularized framework that provides a rigorous means by which various\nmathematical systems are implemented in distinct modules. These modules are interconnected\nto solve for the globally coupled dynamic responses of wind turbines and wind\nplants \\cite{Jonkman:2013,website:FASTModularizationFramework}.\n\nIn this paper, a 3D displacement-based\nimplementation of geometrically exact beam theory using Legendre\nspectral finite elements is presented. The theory is reformulated in a\nnonlinear state-space form for the purpose of integrating with the FAST\nframework, thereby introducing an optional high-fidelity beam model as an\nalternative to the current beam model. Several first-order form time integrators, including the explicit fourth-order Runge-Kutta (RK4) and implicit second-order Adams-Moulton (AM2), are examined. This work builds on previous efforts\nthat demonstrated the implementation of GEBT and spatial discretization using Legendre spectral finite elements\n(LSFEs)\\cite{Wang:GEBT2013,Wang:SFE2013,Wang:GEBT2014,Sprague:FAST2014} in analyzing composite wind turbine blades. The paper is organized as\nfollows.  First, the theoretical foundation of the geometrically exact beam\ntheory along with the reformulation of the governing equations into a\nstate-space form is introduced. Coupling to the FAST framework is then\ndiscussed. Finally, numerical examples are\nprovided to verify and validate the accuracy and efficiency of the present model for\ncomposite wind turbine blades. \n\n~\n\n\\section{Geometrically Exact Beam Theory}\n\nThis section briefly reviews the geometrically exact beam theory. Further details on the content of this section can be found in many other papers and textbooks \\cite{HodgesBeamBook,Bauchau:2010,YuGEBT}.\nFigure~\\ref{Kinematics} shows a beam in its initial undeformed\nand deformed states. A reference frame $\\mathbf{b}_i$ is introduced along the\nbeam axis for the undeformed state and a frame $\\mathbf{B}_i$ is introduced\nalong each point of the deformed beam axis. The curvilinear coordinate $x_1$ defines the intrinsic parameterization of the reference line.\n\\begin{figure}\n\\centering\n\\includegraphics[width=5.0in]{\\directory Kinematics.eps}\n\\caption{A beam deformation schematic.} \\label{Kinematics}\n\\end{figure}\nIn this paper, matrix notation is used to denote vectorial or vectorial-like quantities. For example, an underline denotes a vector $\\underline{u}$, a bar denotes unit vector $\\bar{n}$, and a double underline denotes a tensor $\\underline{\\underline{\\Delta}}$. Note that sometimes the underlines only denote the dimension of the corresponding matrix. The governing equations of motion for geometrically exact beam theory can be written as \\cite{Bauchau:2010}\n\\begin{align}\n\t\\label{GovernGEBT-1}\n\t\\dot{\\underline{h}} - \\underline{F}^\\prime &= \\underline{f} \\\\\n\t\\label{GovernGEBT-2}\n\t\\dot{\\underline{g}} + \\dot{\\tilde{u}} \\underline{h} - \\underline{M}^\\prime + (\\tilde{x}_0^\\prime + \\tilde{u}^\\prime)^T \\underline{F} &= \\underline{m}\n\\end{align}\nwhere $\\vec{h}$ and $\\vec{g}$ are the linear and angular momenta resolved in the inertial coordinate system, respectively; $\\vec{F}$ and $\\vec{M}$ are the beam's sectional force and moment resultants, respectively; $\\vec{u}$ is the one-dimensional (1D) displacement of a point on the reference line; $\\vec{x}_0$ is the position vector of a point along the beam's reference line;  and $\\vec{f}$ and $\\vec{m}$ are the distributed force and moment applied to the beam structure.  The notation $(\\bullet)^\\prime$ indicates a derivative with respect to beam axis $x_1$ and $\\dot{(\\bullet)}$ indicates a derivative with respect to time. The tilde operator $(\\skew{\\bullet})$ defines a skew-symmetric tensor corresponding to the given vector. In the literature, it is also termed as ``cross-product matrix\". For example,\n\\[\n\t\\skew{n} = \n\t     \t\t\\begin{bmatrix}\n\t\t\t0 & -n_3 & n_2 \\\\\n\t\t\tn_3 & 0 & -n_1 \\\\\n\t\t\t-n_2 & n_1 & 0\\\\\n\t\t\t\\end{bmatrix}\t\n\\]\nThe constitutive equations relate the velocities to the momenta and the 1D strain measures to the sectional resultants as\n\\begin{align}\n\t\\label{ConstitutiveMass}\n\t\\begin{Bmatrix}\n\t\\underline{h} \\\\\n\t\\underline{g}\n\t\\end{Bmatrix}\n\t= \\underline{\\underline{\\mathcal{M}}} \\begin{Bmatrix}\n\t\\dot{\\underline{u}} \\\\\n\t\\underline{\\omega}\n\t\\end{Bmatrix} \\\\\n\t\\label{ConstitutiveStiff}\n\t\\begin{Bmatrix}\n\t\\underline{F} \\\\\n\t\\underline{M}\n\t\\end{Bmatrix}\n\t= \\underline{\\underline{\\mathcal{C}}} \\begin{Bmatrix}\n\t\\underline{\\epsilon} \\\\\n\t\\underline{\\kappa}\n\t\\end{Bmatrix}\n\\end{align}\nwhere $\\underline{\\underline{\\mathcal{M}}}$ and\n$\\underline{\\underline{\\mathcal{C}}}$ are the $6 \\times 6$ sectional mass\nand stiffness matrices, respectively (note that they are not really tensors);\n$\\underline{\\epsilon}$ and $\\underline{\\kappa}$ are the 1D strains and\ncurvatures, respectively; and, $\\underline{\\omega}$ is the angular velocity\nvector that is defined by the rotation tensor $\\underline{\\underline{R}}$ as\n$\\underline{\\omega} =\naxial(\\dot{\\underline{\\underline{R}}}~\\underline{\\underline{R}}^T)$. The axial vector $\\vec{a}$ associated with a second-order tensor $\\tens{A}$ is denoted $\\vec{a}=axial(\\tens{A})$ and its components are defined as\n\\begin{equation}\n    \\label{axial}\n    \\vec{a} = axial(\\tens{A})=\\begin{Bmatrix}\n    a_1 \\\\\n    a_2 \\\\\n    a_3\n    \\end{Bmatrix}\n    =\\frac{1}{2}\n    \\begin{Bmatrix}\n    A_{32}-A_{23} \\\\\n    A_{13}-A_{31} \\\\\n    A_{21}-A_{12}\n    \\end{Bmatrix}\n\\end{equation}\nThe 1D strain measures are defined as\n\\begin{equation}\n    \\label{1DStrain}\n    \\begin{Bmatrix}\n        \\vec{\\epsilon} \\\\\n        \\vec{\\kappa}\n    \\end{Bmatrix}\n    =\n    \\begin{Bmatrix}\n        \\vec{x}^\\prime_0 + \\vec{u}^\\prime - (\\tens{R} ~\\tens{R}_0) \\bar{\\imath}_1 \\\\\n        \\vec{k}\n    \\end{Bmatrix}\n\\end{equation}\nwhere $\\vec{k} = axial [(\\tens{R R_0})^\\prime (\\tens{R R_0})^T]$ is the sectional\ncurvature vector resolved in the inertial basis and $\\bar{\\imath}_1$ is the unit\nvector along $x_1$ direction in the inertial basis. Note that these\nthree sets of equations, including equations of motion\nEq.~\\eqref{GovernGEBT-1} and \\eqref{GovernGEBT-2}, constitutive equations\nEq.~\\eqref{ConstitutiveMass} and \\eqref{ConstitutiveStiff}, and kinematical\nequations Eq.~\\eqref{1DStrain}, provide a full mathematical description of elasticity problems. \n\nFor a displacement-based finite-element implementation, there are six\ndegrees of freedom at each node: three displacement components and three\nrotation components. Here, $\\vec{q}$ denotes the elemental\ndisplacement array as $\\underline{q}^T=\\left[\n\\underline{u}^T~~\\underline{p}^T\\right]$ where $\\vec{u}$ is the\ndisplacement and $\\vec{p}$ is the rotation-parameter vector. The\nacceleration array can thus be defined as $\\underline{a}^T=\\left[\n\\ddot{\\underline{u}}^T~~ \\dot{\\underline{\\omega}}^T \\right]$. For nonlinear\nfinite-element analysis, the discretized forms of\ndisplacement, velocity, and acceleration are written as\n\\begin{align}\n\t\\label{DiscretizedDisp}\n\t\\underline{q} (x_1) &= \\underline{\\underline{N}} ~\\hat{\\underline{q}}~~~~~~~~\\underline{q}^T = \\left[ \\underline{u}^T~~\\underline{p}^T \\right] \\\\\n\t\\label{DiscretizedVel}\n\t\\underline{v}(x_1) &= \\underline{\\underline{N}}~\\hat{\\underline{v}}~~~~~~~~\\underline{v}^T = \\left[\\underline{\\dot{u}}^T~~\\underline{\\omega}^T \\right] \\\\\n\t\\label{DiscretizedAcc}\n\t\\underline{a}(x_1) &= \\underline{\\underline{N}}~ \\hat{\\underline{a}}~~~~~~~~\\underline{a}^T = \\left[ \\ddot{\\underline{u}}^T~~\\dot{\\underline{\\omega}}^T \\right]\t\n\\end{align}\nwhere $\\tens{N}$ is the shape function matrix and $(\\hat{\\cdot})$ denotes a\ncolumn matrix of nodal values.\n\n\\section{State-Space Formulation}\nNREL has put considerable effort into improving the modularity of FAST. The modules in the new framework can be coupled in one of two ways in the time domain: loose and tight. In the loose coupling scheme, data are exchanged between the modules at each coupling step, but each module tracks its own states and integrates its own equations with its own solver. In a tightly coupled time-integration scheme, each module sets up its own equations, but the states are tracked and integrated by a solver common to all of the modules. To enable the most flexibility, it is useful to create modules (such as BeamDyn) so that they can support both loose and tight coupling. More details on the FAST modularization framework and an initial assessment of the numerical stability, numerical accuracy, and computational performance of various coupling schemes can be found in \\cite{Jonkman:2013,Sprague:2013,Sprague:FAST2014}. \n\nTo accommodate the tight coupling scheme in the FAST modular framework, the governing equations \n\\eqref{GovernGEBT-1} and \\eqref{GovernGEBT-2} needed to be reformulated\ninto a state-space form. First, these equations are recast in compact form\nas\n\\begin{equation}\n    \\label{CompactGovernGEBT}\n    \\underline{\\mathcal{F}}^I - (\\underline{\\mathcal{F}}^{C})^\\prime + \\underline{\\mathcal{F}}^D = \\underline{\\mathcal{F}}^{ext}\n\\end{equation}\nwhere $\\underline{\\mathcal{F}}^I, \\underline{\\mathcal{F}}^C$ and $\\underline{\\mathcal{F}}^D$, and $\\underline{\\mathcal{F}}^{ext}$ are the inertial force term, two elastic force terms, and externally applied force term, respectively; their definitions are\n\\begin{align}\n    \\label{InertialForce}\n    \\underline{\\mathcal{F}}^I &= \\begin{Bmatrix}\n    \\dot{\\underline{h}} \\\\\n    \\dot{\\underline{g}}\n    \\end{Bmatrix}\n    + \\begin{bmatrix}\n    \\underline{\\underline{0}} & \\underline{\\underline{0}} \\\\\n    \\dot{\\tilde{u}}  &  \\underline{\\underline{0}}\n    \\end{bmatrix}\n    \\begin{Bmatrix}\n    \\vec{h} \\\\\n    \\vec{g}\n    \\end{Bmatrix} \\\\\n    \\label{ElasticForceFc}\n     \\underline{\\mathcal{F}}^C &= \\begin{Bmatrix}\n    \\underline{F} \\\\\n    \\underline{M}\n    \\end{Bmatrix} \\\\\n    \\label{ElasticForceFd}\n    \\underline{\\mathcal{F}}^D &= \\begin{Bmatrix}\n    \\underline{0} \\\\\n    (\\tilde{x}^\\prime_0 + \\tilde{u}^\\prime)^T \\underline{F}\n    \\end{Bmatrix} \\\\\n    \\label{AppliedForce}\n    \\underline{\\mathcal{F}}^{ext} &= \\begin{Bmatrix}\n    \\underline{f} \\\\\n    \\underline{m}\n    \\end{Bmatrix}\n\\end{align}   \nAlong with the constitutive equations \\eqref{ConstitutiveMass} and \\eqref{ConstitutiveStiff}, the inertial force $\\underline{\\mathcal{F}}^I$ can be written explicitly as\n\\begin{align}\n    \\underline{\\mathcal{F}}^I &= \\begin{Bmatrix}\n    m \\ddot{\\underline{u}} + ( \\dot{\\tilde{\\omega}} + \\tilde{\\omega} \\tilde{\\omega} ) m \\underline{\\eta} \\\\\n    m \\tilde{\\eta} \\ddot{\\underline{u}} + \\underline{\\underline{\\varrho}} \\dot{\\underline{\\omega}} + \\tilde{\\omega}  \\underline{\\underline{\\varrho}} \\underline{\\omega} \n    \\end{Bmatrix} \\nonumber \\\\\n    \\label{InertialForce2}\n    &= \\begin{bmatrix}\n    m \\underline{\\underline{I}} & m \\tilde{\\eta}^T \\\\\n    m \\tilde{\\eta} & \\underline{\\underline{\\varrho}}\n    \\end{bmatrix}\n    \\begin{Bmatrix}\n    \\ddot{\\underline{u}} \\\\\n    \\dot{\\underline{\\omega}}\n    \\end{Bmatrix} + \n    \\begin{bmatrix}\n    \\underline{\\underline{0}} & m \\tilde{\\omega} \\tilde{\\eta}^T \\\\\n    \\underline{\\underline{0}} & \\tilde{\\omega}  \\underline{\\underline{\\varrho}}\n    \\end{bmatrix}\n    \\begin{Bmatrix}\n    \\dot{\\underline{u}} \\\\\n    \\underline{\\omega}\n    \\end{Bmatrix} \\\\\n    &  \\equiv \\tens{\\mathfrak{M}} \\underline{a} + \\underline{\\underline{\\mathcal{G}}} \\underline{v}  \\nonumber     \n\\end{align}\nwhere $m$ is the mass density per unit span; $\\underline{\\eta}$ is the\ncenter of mass location;  $\\underline{\\underline{\\varrho}}$ is the moment of\ninertia; and $\\tens{I}$ is the identity matrix. The definitions of the acceleration vector $\\underline{a}$ and velocity vector $\\underline{v}$ can be found in Eq.~\\eqref{DiscretizedAcc} and \\eqref{DiscretizedVel}, respectively. Using the newly introduced matrices, the compact form of the equations of motion can be rewritten as\n\\begin{equation}\n    \\label{CompactForm2}\n    \\underline{\\underline{\\mathfrak{M}}}~ \\underline{a} + f(\\underline{q},\\underline{v},t) = 0\n\\end{equation}\nwhere\n\\begin{equation}\n    \\label{CompactForm3}\n    f(\\underline{q},\\underline{v},t) = \\underline{\\mathcal{F}}^F - \\underline{\\mathcal{F}}^{C\\prime} + \\underline{\\mathcal{F}}^D - \\underline{\\mathcal{F}}^{ext}\n\\end{equation}\n\\begin{align}\n    \\underline{\\mathcal{F}}^F &= \\underline{\\underline{\\mathcal{G}}} \\underline{v}  \\nonumber \\\\\n    \\label{CompactForm4}\n    &= \\begin{bmatrix}\n    \\underline{\\underline{0}} & m \\tilde{\\omega} \\tilde{\\eta}^T \\\\\n    \\underline{\\underline{0}} & \\tilde{\\omega}  \\underline{\\underline{\\varrho}}\n    \\end{bmatrix}\n    \\begin{Bmatrix}\n    \\dot{\\underline{u}} \\\\\n    \\underline{\\omega}\n    \\end{Bmatrix} \n\\end{align}\n\nA weighted residual formulation is used to enforce the dynamic equilibrium conditions in Eq.~\\eqref{CompactForm2}\n\\begin{equation}\n    \\label{FEM-1}\n    \\int_0^l \\tens{N}^T (\\tens{\\mathfrak{M}} \\vec{a} + \\vec{\\mathcal{F}}^F - \\vec{\\mathcal{F}}^{C\\prime} + \\vec{\\mathcal{F}}^D - \\vec{\\mathcal{F}}^{ext}) d x_1=0\n\\end{equation}\nThe above equation can be recast as\n\\begin{equation}\n    \\label{FEM-2}\n    \\tens{M} \\hat{a} = F(\\vec{q},\\vec{v},t)\n\\end{equation}\nwhere\n\\begin{align}\n    \\label{FEM-3}\n    \\tens{M} &= \\int_0^l \\tens{N}^T \\tens{\\mathfrak{M}}~ \\tens{N}~dx_1 \\\\\n    \\label{FEM-4}\n    \\vec{F}(\\vec{q},\\vec{v},t) &= \\int_0^l \\tens{N}^T (-\\vec{\\mathcal{F}}^F + \\vec{\\mathcal{F}}^{C\\prime} - \\vec{\\mathcal{F}}^D + \\vec{\\mathcal{F}}^{ext}) d x_1\n\\end{align}\n\nTo derive the state-space form of the governing equations, the state variable in first-order form $\\vec{x}(t)$ is introduced as\n\\begin{equation}\n    \\label{StateSpaceX}\n    \\vec{x}(t) \\equiv \\begin{Bmatrix}\n    \\vec{q}(t) \\\\\n    \\vec{v}(t)\n    \\end{Bmatrix} \n\\end{equation}\nNote that the second component of $\\vec{x}(t)$ is not $\\vec{\\dot{q}}$ but $\\vec{v}$ because the angular velocity $\\vec{\\omega}$ cannot be calculated as the time derivative of the rotation parameter $\\vec{p}$. The angular velocity is related to the rotation parameter by the tangent matrix as $\\omega = \\tens{H}(p) \\dot{\\vec{p}}$ \\cite{Bauchau:2010}. Substituting the discretized quantities in Eqs.~\\eqref{DiscretizedDisp} to \\eqref{DiscretizedAcc} into Eq.~\\eqref{StateSpaceX} and using the relation\n\\begin{equation}\n    \\label{AccVel}\n    \\vec{a} = \\vec{\\dot{v}} = \\begin{Bmatrix}\n    \\vec{\\ddot{u}} \\\\\n    \\vec{\\dot{\\omega}}\n    \\end{Bmatrix}\n\\end{equation}\nThe state-space form can be obtained as\n\\begin{equation}\n    \\label{StateSpaceGov-1}\n    \\tens{A} ~\\dot{\\hat{\\vec{x}}}(t) = \\mathfrak{f}(\\hat{\\vec{x}}(t),t)\n\\end{equation}\nwith initial condition\n\\begin{equation}\n    \\label{StateSpaceGov-2}\n    \\hat{\\vec{x}}(0) = \\hat{\\vec{x}}_0\n\\end{equation}\nwhere\n\\begin{align}\n    \\label{StateSpaceGov-3}\n    \\tens{A} (\\hat{\\vec{x}}(t)) &= \\begin{bmatrix}\n    \\tens{D} & \\tens{0} \\\\\n    \\tens{0} & \\tens{M}\n    \\end{bmatrix}  \\\\\n    \\label{StateSpaceGov-4}\n    \\tens{D} (\\hat{\\vec{x}}(t)) &= \\int_0^l \\tens{N}^T \\begin{bmatrix}\n    \\tens{I}_3 & \\tens{0} \\\\\n    \\tens{0} & \\tens{H}\n    \\end{bmatrix} \n    \\tens{N}~dx_1 \\\\\n    \\label{StateSpaceGov-5}\n    \\mathfrak{f}(\\hat{\\vec{x}}(t),t) &=  \\begin{Bmatrix}\n    \\int_0^l \\tens{N}^T \\vec{v}~dx_1 \\\\\n    \\vec{F}(\\hat{\\vec{x}}(t),t)\n    \\end{Bmatrix} \\\\\n    \\label{StateSpaceGov-7}\n    \\hat{\\vec{x}}_0 &= \\begin{Bmatrix}\n    \\hat{\\vec{q}}_0 \\\\\n    \\hat{\\vec{v}}_0\n    \\end{Bmatrix}\n\\end{align}\nNote that the state-space form, in\nEq.~\\eqref{StateSpaceGov-1} and \\eqref{StateSpaceGov-2}, can be solved with\nany number of ordinary differential equations (ODE) integrators\nfor first-order-in-time systems. A viscous damping term is also implemented to account for the structural damping. The damping force is defined as\n\\begin{equation}\n   \\label{Damping}\n   \\vec{f}_d = \\tens{\\mu}~ \\tens{\\mathcal{C}} \\begin{Bmatrix}\n   \\dot{\\epsilon} \\\\\n   \\dot{\\kappa}\n   \\end{Bmatrix}\n\\end{equation}\nwhere $ \\tens{\\mu}$ is a user-provided damping-coefficient diagonal matrix. The damping force can be recast in two separate parts, like $\\vec{\\mathcal{F}}^C$ and $\\vec{\\mathcal{F}}^D$ in the elastic force, as\n\\begin{align}\n   \\label{DampingForce-1}\n   \\vec{\\mathcal{F}}^C_d &= \\begin{Bmatrix}\n   \\vec{F}_d \\\\\n   \\vec{M}_d\n   \\end{Bmatrix} \\\\\n   \\label{DampingForce-2}\n   \\vec{\\mathcal{F}}^D_d &= \\begin{Bmatrix}\n    \\vec{0} \\\\\n    (\\tilde{x}^\\prime_0 + \\tilde{u}^\\prime)^T \\underline{F}_d\n    \\end{Bmatrix}   \n\\end{align}\nReaders are refered to Ref.[16] for more details on the damping force and its linearization.\n\n\\section{Implementation of BeamDyn}\nThe state-space form of GEBT was numerically implemented into a beam solver, called BeamDyn. BeamDyn has two sources of input:  the user-prescribed parameters and per time step data from the FAST driver code. The input parameters from the users are:\n\\begin{enumerate}\n    \\item Key points that define the natural geometry of the beam; these key points are interpolated by cubic splines\n    \\item Sectional constants for a 1D beam model\n    \\item Finite-element mesh information (order of element)\n    \\item Selection of static \\cite{Wang:GEBT2014} or dynamic analysis\n    \\item Time integrators and associated parameters: RK4, AM2, or Generalized-$\\alpha$ (for loosing coupling only).\n\\end{enumerate}\n\nIt is intended to couple separate instances of BeamDyn to FAST for each blade.  Structurally, the coupling will involve passing motions of the blade root for each blade from FAST's ElastoDyn structural module to BeamDyn; including position, velocity, and acceleration (both translation and rotation); and passing root loads for each blade from BeamDyn to ElastoDyn (both forces and moments).  Aerodynamically, the coupling will involve passing motions of the nodes distributed along each blade from BeamDyn to FAST's AeroDyn aerodynamics module; including position, velocity, and acceleration (both translation and rotation); and passing aerodynamic loads distributed along the blade from AeroDyn to BeamDyn.  FAST will also send BeamDyn the gravity vector and initial hub motions at initialization to enable an initialization of BeamDyn's states.  While not needed to enable the coupling of BeamDyn to FAST, BeamDyn will also calculate the internal loads along the beam, calculated by subtracting the inertial loads from the externally applied loads.\n\nThe implementation of GEBT with RK4 is straightforward; however, for the AM2 scheme, a linearization is required because of its implicit nature. By applying the trapezoidal rule, the state-space form in Eq.~\\eqref{StateSpaceGov-1} can be recast as\n\\begin{equation}\n    \\label{AM2-Govn}\n%    \\tens{A}_{k+1} (\\hat{\\vec{x}}_{k+1}-\\hat{\\vec{x}}_{k})+\\tens{A}_k \\hat{\\vec{x}}_{k+1} - \\Delta t \\mathfrak{f}(\\hat{\\vec{x}}_{k+1},t_{k+1}) = \\tens{A}_k \\hat{\\vec{x}}_{k} + \\Delta t \\mathfrak{f}(\\hat{\\vec{x}}_{k},t_{k})\n    \\tens{A}_{k+1} (\\hat{\\vec{x}}_{k+1}-\\hat{\\vec{x}}_{k} - \\frac{\\Delta t}{2} \\vec{\\dot{\\hat{x}}}_k) =  \\frac{\\Delta t}{2} \\mathfrak{f}(\\hat{\\vec{x}}_{k+1},t_{k+1})  \n\\end{equation}\nwhere the subscript denotes the discretized time step in which the value is evaluated, and $\\Delta t$ is the time step size. A linearization is needed to solve this nonlinear equation. The linearized equation is as follows\n\\begin{equation}\n    \\label{AM2-Linearized}\n    \\begin{bmatrix}\n    \\hat{\\tens{K}}_1 & \\hat{\\tens{C}}_1 \\\\\n    \\hat{\\tens{K}}_2 & \\hat{\\tens{C}}_2\n    \\end{bmatrix}\n    \\begin{Bmatrix}\n    \\Delta \\hat{\\vec{q}} \\\\\n    \\Delta \\hat{\\vec{v}}\n    \\end{Bmatrix}\n    =\n    \\begin{Bmatrix}\n    \\hat{\\vec{F}}_1 \\\\\n    \\hat{\\vec{F}}_2\n    \\end{Bmatrix}\n\\end{equation}\nThe coefficient matrices are written as\n\\begin{align}\n    \\label{Linear-K1}\n    \\hat{\\tens{K}}_1 &= \\int_0^l \\tens{N}^T\\tens{K}_1~\\tens{N}~dx_1 \\\\\n    \\label{Linear-C1} \n    \\hat{\\tens{C}}_1 &= \\int_0^l \\tens{N}^T\\tens{C}_1~\\tens{N}~dx_1 \\\\\n    \\label{Linear-K2}\n    \\hat{\\tens{K}}_2 &= \\int_0^l  \\tens{N}^T (\\tens{A}_2 - \\tens{A}_3 + \\frac{\\Delta t}{2} \\tens{A}_1 + \\frac{\\Delta t}{2} \\tens{A}_5 + \\frac{\\Delta t}{2} \\mathcal{Q}) \\tens{N}~dx_1 \\nonumber \\\\\n    &+ \\int_0^l \\left( \\tens{N}^T \\frac{\\Delta t}{2} \\tens{\\mathcal{P}}~ \\tens{N}^\\prime + \\tens{N}^{\\prime T} \\frac{\\Delta t}{2} \\tens{\\mathcal{S}}~ \\tens{N}^\\prime + \\tens{N}^T \\frac{\\Delta t}{2} \\tens{\\mathcal{O}}~ \\tens{N}\\right) ~dx_1 \\\\\n    \\label{Linear-C2}\n    \\hat{\\tens{C}}_2 &= \\int_0^l \\tens{N}^T (\\tens{\\mathfrak{M}}+\\frac{\\Delta t}{2} \\tens{A}_4)~\\tens{N}~dx_1\n\\end{align}\nwhere the newly introduced matrices are\n\\begin{align}\n   \\label{K1}\n   \\tens{K}_1 &=\n   \\begin{bmatrix}\n   \\tens{I}_3 & \\tens{0} \\\\\n   \\tens{0} & \\tens{B}(\\vec{p},\\vec{p}) + \\tens{H} - \\tens{B}(\\vec{p},\\vec{p}_k) -\\frac{\\Delta t}{2} \\tens{B}(\\vec{p},\\vec{\\dot{p}}_k)\n   \\end{bmatrix} \\\\\n   \\label{C1}\n   \\tens{C}_1 &=\n   -\\frac{\\Delta t}{2} \\begin{bmatrix}\n   \\tens{I}_3 & \\tens{0} \\\\\n   \\tens{0} & \\tens{I}_3 \n   \\end{bmatrix} \\\\\n   \\label{A1}\n   \\tens{A}_1 &=\n    \\begin{bmatrix}\n   \\tens{0} & m \\dot{\\tilde{\\omega}}_k \\tilde{\\eta}^T \\\\\n   \\tens{0} & m \\ddot{\\tilde{u}}_k \\tilde{\\eta}+\\tens{\\rho} \\dot{\\tilde{\\omega}}_k-\\widetilde{\\tens{\\rho}{\\dot{\\vec{\\omega}}_k}}\n   \\end{bmatrix} \\\\\n   \\label{A2}\n   \\tens{A}_2 &=\n    \\begin{bmatrix}\n   \\tens{0} & m \\tilde{\\omega} \\tilde{\\eta}^T \\\\\n   \\tens{0} & m \\dot{\\tilde{u}} \\tilde{\\eta}+\\tens{\\rho} \\tilde{\\omega}-\\widetilde{\\tens{\\rho}\\vec{\\omega} }\n   \\end{bmatrix} \\\\\n   \\label{A3}\n   \\tens{A}_3 &=\n    \\begin{bmatrix}\n   \\tens{0} & m \\tilde{\\omega}_k \\tilde{\\eta}^T \\\\\n   \\tens{0} & m \\dot{\\tilde{u}}_k \\tilde{\\eta}+\\tens{\\rho} \\tilde{\\omega}_k-\\widetilde{\\tens{\\rho}\\vec{\\omega}_k}\n   \\end{bmatrix} \\\\\n   \\label{A4}\n   \\tens{A}_4 &=\n    \\begin{bmatrix}\n   \\tens{0} & \\widetilde{\\tilde{\\omega}m\\vec{\\eta}}^T+\\tilde{\\omega}m\\tilde{\\eta}^T \\\\\n   \\tens{0} & \\widetilde{\\tens{\\rho}\\vec{\\omega}}^T+\\tilde{\\omega}\\tens{\\rho}\n   \\end{bmatrix} \\\\\n   \\label{A5}\n   \\tens{A}_5 &=\n    \\begin{bmatrix}\n   \\tens{0} & \\tilde{\\omega} \\tilde{\\omega} m \\tilde{\\eta}^T \\\\\n   \\tens{0} & \\tilde{\\omega} (\\tens{\\rho} \\tilde{\\omega} - \\widetilde{\\tens{\\rho} \\vec{\\omega}}\n   \\end{bmatrix} \n\\end{align}\nThe $\\tens{\\mathcal{O}}$, $\\tens{\\mathcal{P}}$, $\\tens{\\mathcal{Q}}$, and $\\tens{\\mathcal{S}}$ can be found in previous work by Wang et al \\cite{Wang:GEBT2014}. It is also noted that the $\\tens{B}$ matrix is a linearization of the tangent matrix $\\tens{H}$ defined as\n\\begin{equation}\n    \\label{Bmatrix}\n    \\tens{B}(\\vec{p},\\vec{a}) = \\frac{\\partial (\\tens{H}(\\vec{p})) \\vec{a}}{\\partial \\vec{p}}\n\\end{equation}\n\nOne major difficulty in implementing geometrically nonlinear theory is the description of rotations in 3D space. As discussed in many articles \\cite{Crisfield:1999,Bauchau:2010,Bottasso:1998}, there will be a singular point for any type of vectorial parameterization. To address this singular point, we implemented an algorithm proposed by Crisfield and Jeleni\\'c \\cite{Crisfield:1999}, in which the relative rotations are interpolated instead of the total rotations within one element. Although the magnitude of the total rotation may be large, it is reasonable to assume that the relative rotation in one finite element is smaller than $\\pi$. In the time domain, all the nodal rotations need to be rescaled at the same time so the highly nonlinear governing equations in Eq.~\\eqref{GovernGEBT-1} and \\eqref{GovernGEBT-2} are linearized about the correct point.\n\nIn summary, the newly developed BeamDyn has the following features: \n\\begin{enumerate}\n    \\item It is based on the state-space form of geometrically exact beam theory, thus, it can be easily integrated into FAST as a structural module with both loose-coupling and tight-coupling schemes using time integrators for first-order form ordinary differential equations (ODEs)\n    \\item The spectral finite-element method is used to discretize the space domain; exponential convergence rate can be expected for a smooth solution\n    \\item It is compatible with the FAST modularization network. Variables are categorized into input, output, states, and parameters.\n\\end{enumerate}\n\n\\section{BeamDyn Verification and Validation}\nIn this section, several numerical cases to verify and validate BeamDyn against numerical solutions and experimental data are presented. As discussed in the introduction, modern wind turbine blade features include initial twists/curvatures, elastic coupling, and high flexibility. BeamDyn's capabilities in addressing these features are examined.\n\n\\subsection{Initially Twisted/Curved Beams}\n\nAn initially twisted beam was examined first. A straight beam ($k_2=k_3=0$) with an initial twist ($k_1\\neq 0$) is shown in Figure~\\ref{Twist1}. The beam is linearly twisted in the positive $\\theta_1$ direction from 0 degrees at the root to 90 degrees at the tip. Table~\\ref{E1Property} shows the material properties for A36 steel, the beam geometry, and the force applied at the free tip along $x_3$ direction. The height and base values reported in the table are the height and base of the rectangular cross section. The beam was discretized using a seventh-order LSFE to obtain a converged results. It is widely known that the well-refined 3D finite-element solution can be considered exact; here we use the 3D results as benchmark solutions. The results for the twisted beam are shown in Table~\\ref{E1u} and compared to the baseline results obtained from extremely refined 3D ANSYS analysis using SOLID186 elements. We see that the tip results are quite large (35\\% of total length) and that the agreement between the solid-element and beam-element solutions is very good.  These results also serve to validate the beam-modeling approach.\n\n\\begin{figure}\n\\centering\n\\includegraphics[width=5.0in]{\\directory twist_beam.eps}\n\\caption{Sketch of an initially twisted beam.} \n\\label{Twist1}\n\\end{figure}\n\n \\begin{table}\n\\caption{\\label{E1Property} Properties of twisted beam}\n\\begin{center}\n    \\begin{tabular}{| l | l |}\n    \t\\hline\n    \tProperty               & Value   \\\\ \\hline\n    \tElastic Modulus                      & 200 GPa \\\\ \\hline\n    \tShear Modulus                      & 79.3 GPa \\\\ \\hline\n    \tHeight                      & 0.5 m   \\\\ \\hline\n    \tBase                      & 0.25 m  \\\\ \\hline\n    \tLength                      & 10 m    \\\\ \\hline\n    \tForce                      & 4000 kN \\\\ \\hline\n    \\end{tabular}\n\\end{center}\n\\end{table}\n\n\\begin{table}\n\\caption{\\label{E1u} Comparison of tip displacements of an initially twisted beam} \n\\begin{center} \n    \\begin{tabular}{| l | l | l | l | l | l | l |}\n    \t\\hline\n    \t        & $u_1$ (m) & $u_2$ (m) & $u_3$ (m)  \\\\ \\hline\n    \tBeamDyn  & -1.132727     & -1.715123       & -3.578671      \\\\  \\hline\n    \tANSYS   & -1.134192     & -1.714467      & -3.584232     \\\\ \\hline\n    \tPercent Error   & 0.129\\%     & 0.038\\%      & 0.155\\%     \\\\ \\hline\n    \\end{tabular}\n\\end{center}\n\\end{table} \n\nNext, an initially curved beam was examined. It is clear that the initial curvature plays a major role in the distribution of the elastic forces within the beam. As such, it is very important to ensure that BeamDyn is capable of modeling this effect properly. A widely used benchmark problem for a curved beam is the case proposed by Bathe \\cite{Bathe1979}, which was analyzed for verification. Figure~\\ref{E1Curved} shows the configuration of the cantilevered curved beam being analyzed. The beam lies in the $x_1$, $x_2$ plane, the positive $x_1$ direction and the negative $x_2$ direction. A force of 600 pounds is applied in the positive $x_3$ direction. The beam is defined by the 45-degree arc with 100-inch radius centered at 100 inches in the negative $x_2$ direction.  The geometry of the cross section for the curved beam is square, and the material properties can be found in Ref.[20].  The beam was discretized by a fifth-order LSFE. The results of this static analysis are shown in Table~\\ref{E1CurvedDisp} and are compared to the results published in Bathe \\cite{Bathe1979}.\n\n\\begin{figure}\n\\centering\n\\includegraphics[width=2.5in]{\\directory E1Curved.eps}\n\\caption{Sketch of an initially curved beam.} \n\\label{E1Curved}\n\\end{figure}\n\n\\begin{table}\n\\caption{\\label{E1CurvedDisp} Comparison of tip displacements of an initially curved beam } \n\\begin{center}\n    \\begin{tabular}{| l | l | l | l | l | l | l |}\n    \t\\hline\n    \t        & $u_1$ (inches) & $u_2$ (inches) & $u_3$ (inches)  \\\\ \\hline\n    \tBeamDyn (one LSFE) & -23.7     & 13.5       & 53.4      \\\\  \\hline\n    \tBathe-Bolourchi \\cite{Bathe1979}   & -23.5     & 13.4       & 53.4     \\\\ \\hline\n    \\end{tabular}\n\\end{center}\n\\end{table} \n\nIt can be seen from these results that the simulations from BeamDyn for a initially curved beam match quite well with the published results. The results of these cases suggest that BeamDyn is capable of modeling beams with initial twist and curvatures.\n\n\\subsection{Static Analysis of CX-100 Blade}\nThe primary intended use of BeamDyn is analyzing anisotropic wind turbine blades, therefore, the CX-100 was chosen as a validation case. The CX-100 is a 9-m blade designed by Sandia National Laboratories \\cite{paquette2006modeling}. It was chosen for this analysis because it is well characterized, with a wealth of publicly available data regarding its construction and material properties.\n\nThe cross-sectional properties as derived from VABS for this beam were provided by D.J.\\ Luscher of Los Alamos National Laboratory. These properties were provided at 40 points along the beam. For example, a typical stiffness matrix corresponding to 2.2 m along the span of the blade is given by\n\\begin{align*}\nC =10^3 \\times \\begin{bmatrix}\n\t193,000 & -75.4   & 12.2   & -75.2  & -1970    & -3500    \\\\\n\t-75.4  & 19,500 & 4,760   & 62.6  & 67.3    & 11.3    \\\\\n\t12.2  & 4,760   & 7,210 & -450  & 17.0    & 2.68    \\\\\n\t-75.2  & 62.6   & -450   & 518 & 1.66    & -1.11    \\\\\n\t-1,970  & 67.3   & 17.0   & 1.66  & 2,280 & -879    \\\\\n\t-3,500  & 11.6   & 2.68   & -1.11  & -875    & 4,240\n\\end{bmatrix}\n\\end{align*}\nwhere the units associated with stiffness values are $C_{ij}$ (N), $C_{i,j+3}$ (N $\\cdot$ m), and $C_{i+3,j+3}$ (N $\\cdot$ m$^2$) for $i,j = 1,2,3$.\n\nFigure~\\ref{CX100Sketch} shows the various material layups and the geometry of the CX-100 blade. Each color represents a section with unique material properties. Figure~\\ref{normalized1} shows the normalized bending stiffness along the length of the blade where a sharp gradient in the beam axial direction can be observed. The graph shows that the bending stiffness jumped to about 10\\% of its root value in under 10\\% of the blade length.\n\n\\begin{figure}\n\\centering\n\\includegraphics[width=3.0in]{\\directory CX100Sketch.eps}\n\\caption{Material layup and geometry of the CX-100 wind turbine blade\\cite{paquette2006modeling}.} \n\\label{CX100Sketch}\n\\end{figure}\n\n\\begin{figure}\n\\centering\n\\includegraphics[width=3.0in]{\\directory normalized1.eps}\n\\caption{Normalized bending stiffness as a function of normalized blade length.} \n\\label{normalized1}\n\\end{figure}\n\nFigure~\\ref{CX100Setup} shows the test configuration for the static test performed at the National Wind Technology Center (NWTC) in Boulder, Colorado. The whiffle-tree configuration of the test apparatus applied the load at 3.00 m, 5.81 m, and 7.26 m from the root of the blade to achieve a maximum root moment of 128.6 kN m. The loads and positions are given in Table~\\ref{CX100Load} below.\n\n\n\\begin{figure}\n\\centering\n\\includegraphics[width=5.0in]{\\directory CX100Setup.eps}\n\\caption{Test configuration for the static pull test conducted at the NWTC \\cite{paquette2006modeling}.} \n\\label{CX100Setup}\n\\end{figure}\n\n\\begin{table} \n\\caption{\\label{CX100Load}Positions and applied loads during the CX-100 static loads testing at the NWTC  } \n\\begin{center}\n    \\begin{tabular}{| l | l |l |}\n    \t\\hline\n    \t Saddle \\# &     Radial Position (m) & Applied Load (kN)  \\\\ \\hline\n    1&\t3.00 & 16.9         \\\\  \\hline\n    2&\t5.81   & 5.47         \\\\ \\hline\n    3&\t    \t7.26   & 5.59         \\\\ \\hline\n    \\end{tabular}\n\\end{center}\n\\end{table}\n\nThe out-of-plane displacements, $u_3$, at each of the load points were tracked for the experiment and are given in Table~\\ref{CX100Results}. The BeamDyn simulation was completed using four seventh-order LSFEs and the results are given in Table~\\ref{CX100Results}.\n\\begin{table}\n\\caption{\\label{CX100Results}Experimental and BeamDyn simulation results for the CX-100 static test  } \n\\begin{center}\n    \\begin{tabular}{| l | l | l | l |}\n    \t\\hline\n    \t             & $u_3$ at saddle \\#1 (m) & $u_3$ at saddle \\#2 (m) & $u_3$ at saddle \\#3 (m) \\\\ \\hline\n    \tExperimental & 0.083530             & 0.381996               & 0.632460             \\\\ \\hline\n    \tBeamDyn      & 0.072056               & 0.381074                & 0.698850           \\\\ \\hline\n    \t    \tPercent Error      &        13.74\\%        & 0.24\\%                & 10.5\\%           \\\\ \\hline\n    \\end{tabular}\n\\end{center}\n\\end{table} \nThe displacements are plotted in Figure~\\ref{CX100Disp_New} and are overall in good agreement. One reason to explain the discrepancies between BeamDyn results and experimental data is that the coupling effects between the degrees of freedom was difficult to measure in the experiments. The results obtained by NLBeam, a nonlinear beam solver developed by Los Alamos National Laboratory, also can be found in Figure~\\ref{CX100Disp_New} \\cite{Luscher:2013}. While the NLBeam solution was understood to use the same sectional data as the BeamDyn solution, it is currently unknown why the NLBeam solution differs.  The focus of this case was to validate BeamDyn, not verify BeamDyn against NLBeam, and no attempt has been made to find the source of the differences.\n\n\\begin{figure}\n\\centering\n\\includegraphics[width=3.0in]{\\directory CX100Disp_New.eps}\n\\caption{Displacement $u_3$ along the length of the blade for experimental data and BeamDyn simulation.} \n\\label{CX100Disp_New}\n\\end{figure}\n\nNext, a convergence study of the tip displacements was completed for the CX-100 blade in BeamDyn. Figure~\\ref{CX100conv3} shows the error as a function of the number of nodes (5 nodes represents 2 nodes per each of the 4 elements, 9 nodes represents 3 nodes per each of the 4 elements, etc.). The percentage error was calculated against the experimental data in Table~\\ref{CX100Results}. It can be seen that the convergence rate is not exponential as desired. This is likely due to the fact that as more nodes are added, different material-property stations are used; those data are not smoothly distributed in space. For the next simulation, the blade was meshed such that the element boundaries coincide with the locations where the sectional properties are defined. As previously mentioned, the cross-sectional properties for the CX-100 blade were given at 40 locations along the length of the blade. To have an element coincide with each sectional property, 39 LSFEs were needed. Figure~\\ref{CX100elem2} shows the results of this simulation. Each circle on the plot indicates an additional order of the LSFE, with the maximum being six. These results demonstrated that  exponential convergence was achieved with this simulation, albeit with many elements. It can therefore be stated that for composite beams with sharp gradients and erratic data in the cross-sectional stiffness matrix, the spectral convergence is compromised, unless element boundaries coincident with the discontinuities. It should be noted here that although the convergence rate suffers as a result of sharp gradients and erratic data in the cross-sectional stiffness matrix as other finite element \\cite{Luscher:2013}, the simulations still return reasonable results in comparison to the experiment data, suggesting that a lack of exponential convergence does not compromise the utility of BeamDyn.\n  \n\n\\begin{figure}\n\\centering\n\\includegraphics[width=3.0in]{\\directory CX100conv3.eps}\n\\caption{ Percent error in $u_3$ as a function of the number of nodes.} \n\\label{CX100conv3}\n\\end{figure}\n\n\\begin{figure}\n\\centering\n\\includegraphics[width=3.0in]{\\directory CX100elem2.eps}\n\\caption{Percent error in $u_3$ compared to a highly refined solution in BeamDyn as a function of the number of nodes for 39 first- to sixth-order LSFEs, coincident with sectional properties.} \n\\label{CX100elem2}\n\\end{figure}\n\n\\subsection{Dynamics of a Cantilevered Beam}\nFor verification of BeamDyn's dynamic analysis capability using the AM2 integrator, a benchmark problem for damping effects in the Dymore release package is used as an example. This example involves a dynamic analysis of a uniform cantilevered beam under an impulsive excitation, which is shown in Figure~\\ref{Impulsive}. The excitation was applied at the free tip along both the $x_2$ and $x_3$ directions simultaneously. The simulation range was 0 to 1 second. The sectional stiffness constants can be found in Table~\\ref{E3Stiffness} and the units were the same as those used in the previous example. This beam is 2.4 meters long. The inertia properties were: $1.61$ kg/m for the unit mass density, $8.60 \\times 10^{-4}$ and $1.10 \\times 10^{-4}$ kg m$^{2}$ for the mass moment of inertia about $x_2$ and $x_3$ direction, respectively.   Two cases were analyzed: one without damping effects and the other with damping coefficients of $8.0 \\times  10^{-4}$ s for all the six degrees of freedom. The time steps for these two cases are $1 \\times 10^{-4}$ and $5 \\times 10^{-4}$ seconds, respectively, given that the damping will help the convergence and stability during simulation. The beam was discretized by one fifth-order element in BeamDyn analysis for a converged result. The time histories of all the displacement and rotation components are plotted in Figure~\\ref{E3U}. The damping effects can be clearly observed from these results. Furthermore, the accuracy of the present results of damped case were examined by the root-mean-square (RMS) errors, which aggregates the magnitudes of the errors in predictions for various times into a single measure of predictive performance. The error was calculated using\n\\begin{equation}\n\\varepsilon_{RMS}=\\sqrt{\\frac{\\sum_{k=0}^{n_{max}}[u_3^k-u_b(t^k)]^2}{\\sum_{k=0}^{n_{max}}[u_b(t^k)]^2}}\n\\label{RMSdefi}\n\\end{equation} \nwhere $u_b(t)$ is the benchmark solution given by Dymore using eight third-order elements and $5 \\times 10^{-4}$s time increment. The RMS error for three displacement components were $1.80 \\times 10^{-3}$, $1.32 \\times 10^{-3}$, and $2.70 \\times 10^{-3}$, respectively. \n \n\\begin{figure}\n\\centering\n\\includegraphics[width=3.0in]{\\directory AM2_Excitation.eps}\n\\caption{ Impulsive excitation.} \n\\label{Impulsive}\n\\end{figure}\n\n\\begin{table}\n\\caption{\\label{E3Stiffness} Stiffness constants of the cantilevered beam in Example C } \n\\begin{center}\n    \\begin{tabular}{| c | c | c | c | c | c |}\n    \t\\hline\n    \t       $C_{11}$      & $C_{22}$  & $C_{33}$ & $C_{44} $& $C_{55}$ & $C_{66}$ \\\\ \n\t       \\hline\n    \t4.35E+07 & 1.40E+07    &2.81E+06  & 2.81E+04 &2.33E+04 & 2.99E+05 \\\\ \n\t\\hline\n    \\end{tabular}\n\\end{center}\n\\end{table} \n\n\\begin{figure}\n    \\centering\n    \\begin{tabular}{c}\n    \\subfloat[$u_1$]{\\label{E3U:u1}\\includegraphics[width=3.0 in]{\\directory  AM2_u1.eps}} \\qquad\n\\subfloat[$u_2$]{\\label{E3U:u2}\\includegraphics[width=3.0in]{\\directory  AM2_u2.eps}} \\\\\n\\subfloat[$u_3$]{\\label{E3U:u3}\\includegraphics[width=3.0 in]{\\directory  AM2_u3.eps}} \\qquad\n\\subfloat[$p_1$]{\\label{E3U:p1}\\includegraphics[width=3.0 in]{\\directory  AM2_p1.eps}} \\\\\n\\subfloat[$p_2$]{\\label{E3U:p2}\\includegraphics[width=3.0 in]{\\directory  AM2_p2.eps}} \\qquad\n\\subfloat[$p_3$]{\\label{E3U:p3}\\includegraphics[width=3.0 in]{\\directory  AM2_p3.eps}} \\\\\n\\end{tabular}\n\\caption{Tip displacement and rotation histories of a cantilever beam under impulsive excitation.}\n\\label{E3U}\n\\end{figure}  \n\n\\subsection{Analysis of NREL 5-MW Blade}\nThe last example is to examine the efficiency and accuracy of the different time integrators that have been implemented in BeamDyn. The NREL 5-MW blade was analyzed in a cantilever condition, while a white-noise force is applied at the free tip along the flap direction. White noise was used to mimic the magnitude and frequency content of applied aerodynamic loads under realistic turbulent conditions. The damping coefficient is set to $10^{-3}$ s. Figure~\\ref{E4Force} shows the time history of the applied force and its power spectral density (PSD). The flap direction responses are plotted in Figure~\\ref{E4Displacement}. Four cases were conducted in BeamDyn: the first three cases were using the AM2 time integrator with time step size: $2.5 \\times 10^{-2}$ s, $5 \\times 10^{-3}$ s, and $5 \\times 10^{-4}$ s, respectively, while the fourth case was using RK4 time integrator with time step sizes $5 \\times 10^{-6}$ s.  It can be observed that for an implicit AM2 time step beyond 0.005 s, the solution is nearly identical to the fully resolved explicit RK4 solution.  For an AM2 time step of 0.025 s, the solution remains stable and tracks the other solutions, but error grows at higher frequencies.  The spikes at 0.7 Hz and 2 Hz correspond to the first and second blade flapwise natural frequencies, respectively.  The spike above 5 Hz--above the frequency range of excitation--is brought about by nonlinear effects.\n\\begin{figure}\n    \\centering\n    \\begin{tabular}{c}\n    \\subfloat[Time history of applied force]{\\label{E4Force:Force}\\includegraphics[width=5.0 in]{\\directory  5MW_Flap_Force_Final.eps}} \\\\\n\\subfloat[PSD of applied force]{\\label{E4Force:PSD}\\includegraphics[width=5.0in]{\\directory  5MW_Flap_Force_PSD_Final.eps}} \\\\\n\\end{tabular}\n\\caption{Applied white noise force at the tip of a cantilevered NREL 5-MW blade.}\n\\label{E4Force}\n\\end{figure} \n\n\\begin{figure}\n    \\centering\n    \\begin{tabular}{c}\n    \\subfloat[Time history of flap displacement]{\\label{E4Displacement:Disp}\\includegraphics[width=5.0 in]{\\directory  u_5MW_flap_final.eps}} \\\\\n\\subfloat[PSD of flap displacement]{\\label{E4Displacement:PSD}\\includegraphics[width=5.0in]{\\directory  u_5MW_flap_psd_final.eps}} \\\\\n\\end{tabular}\n\\caption{Flap direction responses of a cantilevered NREL 5-MW blade under white noise excitation.}\n\\label{E4Displacement}\n\\end{figure} \n\nThe convergence rate against time step size for the AM2 integrator is also examined. The result from the RK4 simulation is taken as the benchmark solution. The normalized RMS error defined in Eq.~\\eqref{RMSdefi} is plotted in Figure~\\ref{RMS_5MW}, in which second-order convergence as a function of time increment size can be observed. It is also pointed out that a full Newton-Raphson algorithm has been implemented in BeamDyn. The total and average numbers of linear system solves, which are related to the computational time required for the solution, are plotted in Figure~\\ref{E4NR}. It can be observed that while the total number of linear system solves reduces with increasing time step, the average number of solves per step increases.  This means that the computation time cannot be cut in two by doubling the time step.\n\\begin{figure}\n\\centering\n\\includegraphics[width=3.0in]{\\directory RMS_5MW.eps}\n\\caption{ Normalized RMS error of flapwise displacement histories as a function of time step size for AM2 time integrator. The dashed line shows ideal second-order convergence.} \n\\label{RMS_5MW}\n\\end{figure}\n\n\\begin{figure}\n    \\centering\n    \\begin{tabular}{c}\n    \\subfloat[Total number of linear system solves]{\\label{E4NR:Total}\\includegraphics[width=3.0 in]{\\directory  TotalNR.eps}} \\qquad\n\\subfloat[Average number of linear system solves per step]{\\label{E4NR:Average}\\includegraphics[width=3.0in]{\\directory  AveNR.eps}} \\\\\n\\end{tabular}\n\\caption{Total and average numbers of linear system solves in the simulations.}\n\\label{E4NR}\n\\end{figure} \n\n\n%For this 100s simulation with a time step size of $2.5 \\times 10^{-2}$ s, the total number of solved linear system is 37839; while this number for the RK4 simulation with a time step size of $5 \\times 10^{-6}$ s  is $8 \\times 10^{7}$. \n\n\n \\section{Summary}\n  This paper reported on the development of BeamDyn, a beam solver in the FAST modularization framework. Geometrically exact beam theory has been reformulated into the first-order state-space form so that first-order time integrators, as required by FAST framework for tight-coupling analysis, can be applied. Numerical examples are provided to verify and validate the capability of BeamDyn in analyzing initially curved/twisted beams. A validation example is also presented where the numerical results are compared with experimental data. In all the cases, good agreement was observed.  The convergence rate for analysis of realistic wind turbine blade is discussed. The features of BeamDyn can be summarized as follows:\n  \\begin{enumerate}\n  \\item Based on geometrically exact beam theory, BeamDyn is capable of dealing with geometric nonlinear beam problems with arbitrary magnitude of displacements and rotations for both static and dynamic analyses\n  \\item Along with a preprocessor like PreComp or VABS, BeamDyn takes full elastic coupling effects into account\n  \\item The governing equations are reformulated into state-space form, thus, making it amendable into FAST for tight-coupling analysis\n  \\item The space is discretized by spectral finite elements, which is a p-version finite element, so that exponential convergence rate can be expected for smooth solutions\n  \\item Different time integrators have been implemented in BeamDyn; users will have options based on their needs\n  \\item BeamDyn is implemented following the programming requirements (data structures and interfaces) of the FAST modularization framework.\n  \\end{enumerate}\n   Future work includes the proposal of a practical approach to smooth the geometry and sectional constants to help achieve the expected exponential convergence rate. In addition, this module will be coupled to FAST and verification and validation will be conducted on a full wind turbine system. \n  \n\\section*{Acknowledgments} \n\nThis work was supported by the U.S. Department of Energy under Contract No.\\\nDE-AC36-08GO28308 with the National Renewable Energy Laboratory. Funding for the work was provided by the DOE Office of Energy Efficiency and Renewable Energy, Wind and Water Power Technologies Office. Support\nwas also provided through a laboratory directed research and development grant\n\\textit{High-Fidelity Computational Modeling of Wind-Turbine Structural\nDynamics}. The authors would also like to acknowledge D.J. Luscher for CX-100 sectional data.\n  \n  \n\n\\bibliographystyle{aiaa}\n\\bibliography{references}\n\n\\end{document}\n", "meta": {"hexsha": "f4f1e81797db0a995467039ce3602740b1725d7c", "size": 51440, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/2015_SDM/2015_SDM.tex", "max_stars_repo_name": "NWTC/BeamDyn", "max_stars_repo_head_hexsha": "0820e102e69d16ba91221ef8c72a2351fd916190", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2016-10-11T13:19:21.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-10T07:53:28.000Z", "max_issues_repo_path": "docs/2015_SDM/2015_SDM.tex", "max_issues_repo_name": "NWTC/BeamDyn", "max_issues_repo_head_hexsha": "0820e102e69d16ba91221ef8c72a2351fd916190", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/2015_SDM/2015_SDM.tex", "max_forks_repo_name": "NWTC/BeamDyn", "max_forks_repo_head_hexsha": "0820e102e69d16ba91221ef8c72a2351fd916190", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-05-06T02:49:10.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-06T02:49:10.000Z", "avg_line_length": 64.4611528822, "max_line_length": 1874, "alphanum_fraction": 0.7235419907, "num_tokens": 15072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3094639279221546}}
{"text": "\\documentclass[12pt]{article}\r\n\\title{Discouragement Attacks}\r\n\\author{\r\n        Vitalik Buterin \\\\\r\n        Ethereum Foundation\r\n}\r\n\\date{\\today}\r\n\\usepackage{graphicx}\r\n\r\n\r\n\\begin{document}\r\n\\maketitle\r\n\\begin{abstract}\r\nWe explore ``discouragement attacks\" on economic consensus mechanisms. A discouragement attack consists of an attacker acting maliciously inside a consensus mechanism in order to reduce other validators' revenue, even at some cost to themselves, in order to encourage the victims to drop out of the mechanism. The motivations to conduct discouragement attacks are twofold. First, the attacks can increase the attacker's profit, as the mechanism may contain ``competitive\" dynamics where some validators dropping out increases revenue to the remaining ones. Second, the attacks can be part of a two-step strategy where the second step is to carry out a traditional $51\\%$ attack on the consensus algorithm against a now much smaller set of ``honest\" validators warding off the attacker, and hence pay a much lower cost for the attack.\r\n\\end{abstract}\r\n\r\n\\section{Introduction}\r\nConsider the following type of attack on a proof of stake blockchain. The rules of the chain are as follows: there is a maximum total reward $R$, and if there are $N$ validators (consider each validator as having deposited one coin) then each validator, during every 10-second slot, has a chance to earn a reward of $\\frac{R}{N}$ if they actually sign a message that contributes to the chain's consensus during that round. An attacker that controls $\\frac{N}{2} + 1$ validators starts refusing to include messages from all remaining validators. Initially, the attack reduces the victims' revenue to zero and leaves the attacker's revenue unchanged. However, the victims then see no incentive to continue to be validators and exit the proof of stake mechanism. The validator count reduces to $\\frac{N}{2} + 1$, and the attacker's revenue increases from $R * \\frac{\\frac{N}{2} + 1}{N}$ to $R$.\r\n\r\nHere is a possible alternative ending: once everyone but the attacker leaves, the attacker slowly exits their validators until only one validator remains. They then perform a double-spending attack, censorship attack or any other kind of attack on the chain. In either case, it's clear that this kind of two-step strategy is potentially a much cheaper way of bringing down blockchains than a direct frontal attack.\r\n\r\n\\section{Griefing factors}\r\n\r\nTo analyze attacks like these, a common tool that we use is the \\emph{griefing factor}. A mechanism in some equilibrium has a griefing factor of $N$ if the attacker has a mechanism by which they can sacrifice \\$1 of their own funds to cause \\$N of losses to the other participants. If attackers can harm others costlessly or profitably, the griefing factor is $\\infty$. With respect to attackers with $\\ge \\frac{1}{2}$ of all validators, the toy proof of stake mechanism we described above has griefing factor $\\infty$.\r\n\r\nHowever, it is possible to modify the mechanism to bound the griefing factor: if $M$ out of $N$ validators are seen signing a message, then each validator that signs only earns $\\frac{R}{N} * \\frac{M}{N}$. Then, if the possibility of victims withdrawing or depositing is not taken into account, an attacker with $\\frac{N}{2}$ validators censoring $k$ validators (for simplicity of analysis we'll assume that 51\\% attacks are possible with exactly 50\\%) cuts the reward of all online validators from $\\frac{R}{N}$ to $\\frac{R}{N} * \\frac{N-k}{N}$, and so causes:\r\n\r\n\\begin{itemize}\r\n\\item $\\frac{N}{2} * \\frac{R}{N} * \\frac{k}{N} = R * \\frac{k}{2N}$ losses to themselves due to reward reduction\r\n\\item $\\frac{R}{N} * k = R * \\frac{k}{N}$ losses to victims of censorship\r\n\\item $(\\frac{N}{2} - k) * \\frac{R}{N} * \\frac{k}{N} = R * (\\frac{k}{2N} - \\frac{k^2}{N^2})$ losses to others due to reward reduction \r\n\\end{itemize}\r\n\r\nAs $k$ approaches zero, the griefing factor approaches $\\frac{R * \\frac{k}{N} + R * \\frac{k}{2N}}{R * \\frac{k}{2N}} = 3$. As $k$ approaches $\\frac{N}{2}$, the griefing factor approaches $\\frac{\\frac{k}{N}}{\\frac{k}{2N}} = 2$. Minorities can also grief majorities by going offline, and for a minority attacker the griefing factor is limited to $1$ for small attacks and $\\frac{1}{2}$ for attacks with size approaching half the entire validator set. In the rest of our analysis, we will speak abstractly about proof of stake mechanisms with particular griefing factors; this will allow us to compartmentalize our analysis.\r\n\r\n\\section{Epsilon attacks}\r\n\r\nWe will start off examining a particular subclass of attack, where the extent of the attack is small. That is, the attacker selectively censors or otherwise interferes with a small portion of the messages of the victims, reducing their rewards but not enough to make them all leave.\r\n\r\nIn our naive examples above, the reward given to each validator was a $\\frac{1}{N}$ share of some fixed total pot, $R$, where $N$ is the total number of validators (or total deposit size). But this is really only one policy among many possible policies. We can categorize many of them with the equation $r = N^{-p}$, where:\r\n\r\n\\begin{itemize}\r\n\\item $p=0$: constant ``interest rate\", eg. under optimal conditions each validator earns a return of $8\\%$ per year.\r\n\\item $p=\\frac{1}{2}$: the rewards (and penalties) to validators scale with $\\frac{1}{\\sqrt{N}}$, so \\textit{total} rewards scale with $\\sqrt{N}$. This is a compromise between $p=0$ and $p=1$. \r\n\\item $p=1$: constant total reward, ie. the total payout of the protocol is dependent only on what percentage of validators take what actions, not on the total deposit size.\r\n\\item $p=\\infty$: the protocol is dead-set on ensuring that the total deposit size is some specific constant $N_k$ no matter what. If the total deposit size exceeds $N_k$, the protocol keeps decreasing rewards until it drops to $N_k$, and if the total deposit size is below $N_k$, the protocol keeps increasing rewards until it rises to $N_k$. Mathematically, we represent this as the reward curve being a vertical line at $x = N_k$, being equal $\\infty$ below $N_k$ and $0$ above $N_k$.\r\n\\end{itemize}\r\n\r\nNote that if revenues to validators are dominated by transaction fees, then $p=1$ will hold.\r\n\r\nWe now rephrase the problem into the language of supply and demand: there exist a set of players, each of which has some \\textit{reserve reward level} at which they are willing to become validators in the consensus mechanism. This is the supply curve, where the reward level is the price. The protocol, which offers rewards for participation in the consensus mechanism, sets the demand curve. If $p=0$, the demand curve is horizontal - the protocol offers that interest rate to an unlimited number of validators. If $p=\\infty$, the demand curve is vertical. For any other $p$, the demand curve is declining diagonally. For simplicity, we will suppose that the supply curve is $N = r^k$ for some $k$ (eg. $k = 1$) where $r$ is the per-validator reward offered. Absent any attacks, the status-quo values of $N$ and $r$ are the intersection of the supply curve offered by potential validators and the demand curve offered by the protocol.\r\n\r\n\\includegraphics[width=300px]{disc_chart1.png}\r\n\r\nWe model an attack as \\emph{pushing the entire demand curve down}, and in addition costing or benefiting the attacker. We can determine everyone's equilibrium profit by calculating the intersection of the (unchanged) supply curve and the new (depressed) demand curve, and then adding a term to take into account the fact that the attacker's profits as a percentage of their deposits may be less or more than everyone else's.\r\n\r\n\\includegraphics[width=300px]{disc_chart2.png}\r\n\r\nLocally, we can see the protocol reward curve as a straight line with slope $-p$, and the supply curve of users' willingness to participate as a straight line with slope $k$. If the reward curve is pushed down by $\\epsilon$, then the validator count is pushed left by $\\frac{\\epsilon}{k+p}$ and the reward is reduced by $\\epsilon * \\frac{k}{k + p}$ (another way to think about it is that everyone loses $\\epsilon$ from the attack and then \\emph{recovers} $\\frac{p}{k+p}$ from the equilibrium shifting left). Hence, for example, if $k = p = 1$, then because of the marginal validators the attack drives away, everyone (including victims and attacker) earns back an amount equal to half the original per-validator loss of each victim. If $k = 1$ and $p = \\frac{1}{2}$, then everyone only earns back a third.\r\n\r\nNote that the analysis does not change if the attacker makes a targeted attack, provided the attacker does not have special knowledge about the victim's willingness to be a validator (to preserve this assumption, we generally recommend proof of stake validators try to remain anonymous). The reason is that an attack on $\\frac{1}{M}$ of the validator set with the same griefing factor harms them $M$ times as much, driving $M$ times as many to leave, but the set affected is only $\\frac{1}{M}$ in size, so on net the same number of victims leave as a result of the attack.\r\n\r\nGriefing factors are highest when the attacker has exactly half of the validators. This is convenient, because it means that the size of the attacker and victim sets are the same, so the griefing factor is also the ratio of the losses of average rewards \\emph{of each validator}. Let us suppose the victims lose $\\epsilon$. If the mechanism has a griefing factor of $N$, then the attacker loses $\\epsilon * \\frac{1}{N}$. If everyone recovers $\\epsilon * r$ where $r = \\frac{p}{k+p}$, then the victims' losses become $\\epsilon * (1-r)$ and the attacker's losses $\\epsilon * (\\frac{1}{N} - r)$. Hence, an attack can be profitable if $\\frac{p}{k+p} > \\frac{1}{N}$.\r\n\r\n\\includegraphics[width=300px]{disc_chart3.png}\r\n\r\nIf $N = 3$, as is the case in the simplest collective-penalty scheme described above, and we assume $k=1$, then this implies we need $p \\le \\frac{1}{2}$ for epsilon attacks to be unprofitable.\r\n\r\n\\section{Total attacks}\r\n\r\nAttackers with less than 50\\% of the validator set, or attackers trying to make the attack \\emph{look} innocuous (eg. passing it off as abnormally high network latency) only have epsilon attacks at their disposal. An epsilon attack has the disadvantage that the attack must keep running, continuing to cost the attacker. But what if the attacker can drive \\emph{everyone} out (eg. attack enough to push victims' revenues to below zero)? Then, from inside the mechanism, it looks as though no one is attacking (as all victims are no longer participating), and so the attacker is claiming their full maximum rewards. In fact, if $p > 0$, the attacker is claiming \\emph{more} rewards than before.\r\n\r\nAdditionally, unlike epsilon attacks, total attacks can be used to drive the cost of doing an outright attack on the chain (eg. reverting finality) down to zero, although only blocks finalized after the non-attacking validators all leave can be reverted cheaply, so it may be philosophically more correct to consider such an attack an attack on \\emph{liveness} rather than \\emph{safety}.\r\n\r\nOne answer may be: if a total attack, driving the revenues of innocent validators to below zero, is taking place, clients can detect this, and coordinate a minority soft fork extra-protocol to remove the attacker. But can we do better?\r\n\r\nWe could choose $p < 0$ to make such attacks greatly unprofitable; however, this imposes great instability on the protocol because small shifts in demand for validating could lead to very large shifts in both the size of the validator set and the total issuance; indeed, as $p$ approaches $-k$ arbitrarily small shifts in demand can cause arbitrarily large shifts in validator set size. Hence, such an approach is likely nonviable.\r\n\r\nAnother approach is to limit the rate at which validators exit, making it difficult for many validators to leave at the same time. This would require an attacker to sustain an attack for a longer period of time, during which the community could mount a response, and costing the attacker more in the meantime. Particularly, one could freeze all validator withdrawals for the entire period during which the protocol detects that there is an attack and validators are not earning money. An attacker could still attack at zero cost in a richer economic model by \\emph{precommitting} to attack and letting other validators leave first, but this would be more complicated to implement.\r\n\r\nFinally, one can add an ``assurance contract'' mechanic into the deposit mechanism: a validator wishing to enter can specify the minimum validator set size at which they are willing to enter (eg. if there are 1000 validators currently in the validator set one could specify $\\le 1000$ to enter immediately or one could specify 1500). The deposit mechanism would try to induct as many validators as possible such that every validator would satisfy its constraint (eg. if there are currently 1000 validators waiting, and new validators want to join with specified minimums 1001 1003 1004 1004 1006, then the first four could be inducted, as that would increase the count to 1004 which would satisfy all four of them, but the remaining one would not be inducted as if all five joined the total validator count would become 1005, and $1005 < 1006$. This would allow validators to more easily coordinate to fight back against attacks, effectively by saying ``I'm willing to join only if enough others join at the same time to defeat this attacker with me\".\r\n\r\n\\section{Conclusion}\r\n\r\nDiscouragement attacks as a cheaper way of attacking a consensus algorithm are one of the hardest classes of attacks to come up with defenses against. This is even more true in proof of work: if a 51\\% attack succeeds, then there is a coordination problem opposing ``honest\" miners trying to recover the original fork, as none have the private incentive to participate in a fork unless everyone else does. There are some possible strategies for mitigating these attacks especially in a proof of stake system, including making them take longer to execute, easier to coordinate to defeat, and less profitable, but none are perfect. In general, this is still an active area of research, and more research on counter-strategies is desired.\r\n\r\n\\bibliographystyle{abbrv}\r\n\\bibliography{main}\r\n\r\n\\end{document}\r\n", "meta": {"hexsha": "259b041048771a35246d548de469745643275fbe", "size": 14383, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "papers/discouragement/discouragement.tex", "max_stars_repo_name": "kevaundray/research", "max_stars_repo_head_hexsha": "16f20848c614b580071fed3d2ff1dc69688fa4f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1351, "max_stars_repo_stars_event_min_datetime": "2015-09-22T08:17:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T22:48:07.000Z", "max_issues_repo_path": "papers/discouragement/discouragement.tex", "max_issues_repo_name": "kevaundray/research", "max_issues_repo_head_hexsha": "16f20848c614b580071fed3d2ff1dc69688fa4f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 42, "max_issues_repo_issues_event_min_datetime": "2016-08-31T14:43:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-05T23:10:31.000Z", "max_forks_repo_path": "papers/discouragement/discouragement.tex", "max_forks_repo_name": "LaudateCorpus1/research", "max_forks_repo_head_hexsha": "6e8b7b367e7f1b18b4b92151df01dfeaa0774a23", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 334, "max_forks_repo_forks_event_min_datetime": "2015-09-20T10:15:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T17:46:57.000Z", "avg_line_length": 158.0549450549, "max_line_length": 1052, "alphanum_fraction": 0.7654870333, "num_tokens": 3337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3094639199171549}}
{"text": "\\documentclass[11pt,letter]{article}\n\n\\usepackage{latexsym, color, graphicx, comment}\n\\usepackage[top=1in,bottom=1in,left=1in,right=1in]{geometry}\n\\usepackage{amssymb}\n\\usepackage{amsmath}\n\\usepackage{hyperref}\n\\usepackage{empheq}\n\\hypersetup{colorlinks=true,linkcolor=blue}\n\n\\newcommand{\\vect}[1]{\\mbox{\\boldmath $#1$}}\n\\newcommand{\\gyrophase}{\\varphi}\n\\newcommand{\\energy}{\\varepsilon}\n\\renewcommand{\\Re}{\\mathrm{Re}}\n\\renewcommand{\\Im}{\\mathrm{Im}}\n\\newcommand{\\todo}[1]{\\textcolor{red}{#1}}\n%\\newcommand{\\kxfac}{\\kappa_x}\n\\newcommand{\\kxfac}{\\mathtt{kxfac}}\n\\newcommand{\\bmag}{\\mathtt{bmag}}\n\\newcommand{\\smz}{\\mathtt{smz}}\n\\newcommand{\\gdstwo}{\\mathtt{gds2}}\n\\newcommand{\\gdstwoone}{\\mathtt{gds21}}\n\\newcommand{\\gdstwotwo}{\\mathtt{gds22}}\n\\newcommand{\\gbdrift}{\\mathtt{gbdrift}}\n\\newcommand{\\gbdriftO}{\\mathtt{gbdrift0}}\n\\newcommand{\\cvdrift}{\\mathtt{cvdrift}}\n\\newcommand{\\cvdriftO}{\\mathtt{cvdrift0}}\n\\newcommand{\\fprim}{\\mathtt{fprim}}\n\\newcommand{\\tprim}{\\mathtt{tprim}}\n\\newcommand{\\jtwist}{\\mathtt{jtwist}}\n\\newcommand{\\gradpar}{\\mathtt{gradpar}}\n\\newcommand{\\delthet}{\\mathtt{delthet}}\n\\newcommand{\\codedt}{\\mathtt{code\\_dt}}\n\n\n\\title{Definitions for GS2 full-flux-surface stellarator geometry}\n\\author{Matt Landreman}\n\n\\begin{document}\n\\maketitle\n\nIn this note, we state the definitions used for geometric quantities in the full-flux-surface\nversion of GS2, and we detail how these quantities are computed from the information\nin a VMEC output file. We also derive how the twist-and-shift parallel boundary condition\nand box size quantization conditions, familiar from flux tube simulations,\nare modified in a full-surface calculation.\n\n\\section{Review of GS2 geometry definitions}\n\n\\subsection{Definitions valid for any GS2 geometry}\nFirst, we review the definitions used in the flux tube version of GS2,\nas discussed in the note {\\ttfamily gs2\\_geometry\\_definitions.pdf}.\nThe Clebsch representation of the magnetic field is\n\\begin{equation}\n\\vect{B} = \\nabla\\psi\\times\\nabla\\alpha.\n\\label{eq:Clebsch}\n\\end{equation}\nWe take $\\psi$ to represent a flux surface label, but do not (yet) assume that it is necessarily the poloidal or toroidal flux. The $\\alpha$ coordinate is a field line label on the flux surface.\nNew coordinates $x=x(\\psi)$ and $y=y(\\alpha)$ are introduced that are scaled versions of $\\psi$ and $\\alpha$ \nwith dimensions of length. In a flux tube simulation where $x$ and $y$ only vary on a length scale comparable to the gyroradius, then\n\\begin{align}\n&x = \\frac{dx}{d\\psi} \\left[ \\psi - \\psi_0 \\right], \\\\\n&y = \\frac{dy}{d\\alpha} \\left[ \\alpha - \\alpha_0 \\right] \\nonumber,\n\\end{align}\nwhere $dx/d\\psi$ and $dy/d\\alpha$ are constant within the flux tube,\nand $\\psi_0$ and $\\alpha_0$\nare the coordinates around which the flux tube is centered.\n\nA reference magnetic field strength $B_{ref}$ and reference length $L_{ref}$ are introduced for normalization. \nThen the quantities needed to specify the geometry in GS2 are the following:\n\\begin{align}\n\\bmag & = \\frac{B}{B_{ref}}, \\label{eq:bmag} \\\\\n\\gradpar &= L_{ref} \\nabla_{||} z, \\\\\n\\gdstwo &= |\\nabla y |^2  = \\left( \\frac{dy}{d\\alpha} \\right)^2 |\\nabla\\alpha|^2 , \\\\\n\\gdstwoone &= \\hat{s} \\nabla x \\cdot \\nabla y = \\hat{s} \\frac{dx}{d\\psi} \\frac{dy}{d\\alpha} \\nabla\\psi\\cdot\\nabla\\alpha , \\\\\n\\gdstwotwo &= \\hat{s}^2|\\nabla x |^2  = \\hat{s}^2 \\left( \\frac{dx}{d\\psi} \\right)^2 |\\nabla\\psi |^2. \\\\\n\\gbdrift &= \\frac{2 B_{ref} L_{ref}}{B^3} \\vect{B}\\times\\nabla B\\cdot \\nabla y, \\\\\n\\gbdriftO &= \\hat{s} \\frac{2 B_{ref} L_{ref}}{B^3} \\vect{B}\\times\\nabla B\\cdot \\nabla x,  \\\\\n\\cvdrift &= \\frac{2 B_{ref} L_{ref}}{B^2} \\vect{B}\\times\\vect{\\kappa} \\cdot \\nabla y,  \\\\\n\\cvdriftO &= \\hat{s} \\frac{2 B_{ref} L_{ref}}{B^2} \\vect{B}\\times\\vect{\\kappa} \\cdot \\nabla x, \\label{eq:cvdrift0} \\\\\n\\kxfac & = B_{ref} \\frac{dx}{d\\psi} \\frac{dy}{d\\alpha}, \\label{eq:kxfac} \\\\\n\\fprim &=\nB_{ref} L_{ref}\n\\frac{dy}{d\\alpha} \\frac{dx}{d\\psi} \\frac{1}{n_s} \\frac{d n_s}{d x}, \\\\\n\\tprim &=\nB_{ref} L_{ref}\n\\frac{dy}{d\\alpha} \\frac{dx}{d\\psi} \\frac{1}{T_s} \\frac{d T_s}{d x}. \\label{eq:tprim}\n\\end{align}\nThese quantities are all dimensionless. In the definition of $\\gradpar$, $z$ is any parallel coordinate; the parallel coordinate\nis called {\\ttfamily theta} in GS2, although it need not be the poloidal angle.\nAlso $\\hat{s}$ is whichever number is used to define $\\theta_0=${\\ttfamily theta0} in the relation\n\\begin{equation}\n\\theta_0 = \\frac{k_x}{\\hat{s} k_y}.\n\\end{equation}\nThe above quantities (\\ref{eq:bmag})-(\\ref{eq:cvdrift0}) are functions of the parallel coordinate $z$.\nThe quantity $\\kxfac$ is a single number, and the quantities $\\fprim$ and $\\tprim$  are each single numbers\nfor each particle species.\n\nSince $\\vect{B}\\times\\vect{\\kappa}\\cdot\\nabla\\psi = \\vect{b}\\times\\nabla B\\cdot\\nabla\\psi$ for any\nstatic ideal MHD equilibrium (at any $\\beta$), then $\\cvdriftO=\\gbdriftO$.\n\n\\subsection{Definitions used previously for stellarator geometry in GS2}\n\nIn stellarator calculations that have been performed using the standard flux tube version of GS2\nand the GIST geometry interface,\nthe following additional definitions have been made. \nThe flux surface label $\\psi$ has been taken to be the toroidal flux divided by $2\\pi$.\nTherefore for consistency with (\\ref{eq:Clebsch}),\n$\\alpha = \\theta - \\iota \\zeta$ where $\\iota = 1/q$ is the rotational transform,\n$q$ is the safety factor, and $\\theta$ and $\\zeta$ are straight-field-line poloidal and toroidal angles.\nWhile the GIST GS2 interface takes $\\theta$ and $\\zeta$ to be Boozer\nangles, all the expressions below are equally valid for other straight-field-line angles such as PEST or Hamada coordinates.\n\nIn GIST, the parallel coordinate $z$ is presently taken to be the Boozer poloidal angle. However none of the expressions in this note are altered if a different choice is desired.\n\nIn GIST, the reference length $L_{ref}$ is taken to be the effective minor radius computed by VMEC, named Aminor\\_p in\nthe VMEC wout*.nc file.\nThe reference magnetic field is taken to be\n\\begin{equation}\nB_{ref} = \\frac{2 \\psi_{LCFS}}{L_{ref}^2}\n\\label{eq:Bref}\n\\end{equation}\nwhere $\\psi_{LCFS}$ is the value of $\\psi$ at the outermost VMEC flux surface. The choice (\\ref{eq:Bref}) is\nmotivated by the cylindrical limit: the toroidal flux enclosed by the outermost VMEC surface is equivalent to the flux of a field $B_{ref}$ through a circle of radius $L_{ref}$.\n\n\n\nThe radial coordinate $x$ is then chosen to be\n\\begin{equation}\nx = L_{ref} \\sqrt{\\frac{\\psi}{\\psi_{LCFS}}} = L_{ref} \\sqrt{s},\n\\label{eq:gist_x}\n\\end{equation}\nwhere $s = \\psi / \\psi_{LCFS} \\in [0,1]$ is the flux surface label coordinate\nused in VMEC. \nThe choice (\\ref{eq:gist_x}) is natural since \n$x$ then reduces to the usual minor radius in the cylindrical limit.\n%the toroidal flux $2\\pi\\psi$ scales like the square of the radius in the cylindrical limit.\nIt follows that\n\\begin{equation}\n\\frac{dx}{d\\psi} = \\frac{L_{ref}}{2 \\sqrt{ \\psi \\psi_{LCFS}}}\n= \\frac{1}{L_{ref} B_{ref}} \\sqrt{ \\frac{\\psi_{LCFS}}{\\psi}}.\n\\label{eq:psi_x_conversion}\n\\end{equation}\n\nAnother choice made in GIST is $\\kxfac=1$. According to (\\ref{eq:kxfac}), we are then required to take \n\\begin{equation}\n\\frac{d y}{d\\alpha} = L_{ref} \\sqrt{\\frac{\\psi}{\\psi_{LCFS}}} .\n\\label{eq:dy_dalpha}\n\\end{equation}\n\nGIST computes the global shear parameter $\\hat{s}$ using\n\\begin{equation}\n\\hat{s} = \\frac{x}{q} \\frac{dq}{dx}.\n\\end{equation}\n\nNow that $dx/d\\psi$ and $dy/d\\alpha$ are specified, equations (\\ref{eq:bmag})-(\\ref{eq:tprim}) \ncan be evaluated to obtain explicit expressions for the geometry arrays computed by GIST for GS2:\n\\begin{eqnarray}\n\\bmag &=& B/B_{ref}, \\label{eq:gist_Bref}\\\\\n\\gradpar &=& L_{ref} \\nabla_{||} z, \\\\\n\\gdstwo &=& |\\nabla y|^2 = |\\nabla\\alpha|^2 L_{ref}^2 \\frac{\\psi}{\\psi_{LCFS}}, \\\\\n\\gdstwoone &=& \\hat{s} \\nabla x \\cdot \\nabla y = \\frac{\\hat{s}}{B_{ref}} \\nabla\\psi\\cdot\\nabla\\alpha , \\\\\n\\gdstwotwo &=& \\hat{s}^2|\\nabla x |^2  = \\left( \\frac{\\hat{s}}{L_{ref} B_{ref}}\\right)^2 \\frac{\\psi_{LCFS}}{\\psi} |\\nabla\\psi |^2, \\\\\n\\gbdrift &=& \\frac{2 B_{ref} L_{ref}^2}{B^3} \\sqrt{\\frac{\\psi}{\\psi_{LCFS}}} \\vect{B}\\times\\nabla B\\cdot \\nabla \\alpha, \\\\\n\\gbdriftO &=& \\hat{s} \\frac{2 }{B^3}   \\sqrt{\\frac{\\psi_{LCFS}}{\\psi}} \\vect{B}\\times\\nabla B\\cdot \\nabla \\psi, \\\\\n\\cvdrift &=& \\frac{2 B_{ref} L_{ref}^2}{B^2} \\sqrt{\\frac{\\psi}{\\psi_{LCFS}}} \\vect{B}\\times\\vect{\\kappa} \\cdot \\nabla \\alpha, \\\\\n\\cvdriftO &=& \\hat{s} \\frac{2 }{B^2}  \\sqrt{\\frac{\\psi_{LCFS}}{\\psi}} \\vect{B}\\times\\vect{\\kappa} \\cdot \\nabla \\psi,  \\label{eq:gist_cvdrift0} \\\\\n\\fprim &=&   \\frac{L_{ref}}{n_s} \\frac{d n_s}{d x}, \\\\\n\\tprim &=&   \\frac{L_{ref}}{T_s} \\frac{d T_s}{d x}. \n\\end{eqnarray}\n\n\\section{VMEC coordinates}\n\nThe VMEC code uses a toroidal coordinate $\\zeta$ which is the conventional azimuthal angle of cylindrical coordinates. \n\nWe let $\\theta_v$ denote the poloidal angle used in VMEC, which is \\emph{not} a straight-field-line coordinate.\nWe also let $\\theta_p$ denote the PEST poloidal angle, i.e. the straight-field-line angle which results when\nthe toroidal angle is chosen to be the conventional azimuthal angle of cylindrical coordinates, as in VMEC.\nThe conversion between the two coordinates is\n\\begin{equation}\n\\theta_p = \\theta_v + \\Lambda,\n\\end{equation}\nwhere $\\Lambda$ is the quantity given by the {\\ttfamily lmns} and {\\ttfamily lmnc} arrays in VMEC.\nThus, the field line label we need for GS2 geometry quantities is\n\\begin{equation}\n\\alpha = \\theta_v + \\Lambda - \\iota \\zeta.\n\\label{eq:alpha_vmec}\n\\end{equation}\n\nVMEC provides many quantities as functions of the coordinates $(s, \\theta_v, \\zeta)$,\nwhere again $s = \\psi / \\psi_{LCFS}$.\nSpecifically, it provides the Fourier amplitudes for expansions in $\\theta_v$ and $\\zeta$,\non grid points equally spaced in $s$.\nThe quantities that are available include\n$\\Lambda$, $B$, the cylindrical coordinates $(R,Z)$, the components\n\\begin{align}\nB^\\theta &= \\vect{B}\\cdot\\nabla\\theta_v, \\nonumber \\\\\nB^\\zeta &= \\vect{B}\\cdot\\nabla\\zeta, \\nonumber \\\\\nB_s &= \\vect{B}\\cdot\\frac{\\partial\\vect{r}}{\\partial s}, \\nonumber \\\\\nB_\\theta &= \\vect{B}\\cdot\\frac{\\partial\\vect{r}}{\\partial \\theta_v}, \\nonumber \\\\\nB_\\zeta &= \\vect{B}\\cdot\\frac{\\partial\\vect{r}}{\\partial \\zeta}, \\nonumber\n\\end{align}\nand the Jacobian\n\\begin{equation}\n\\sqrt{g} = \\frac{\\partial \\vect{r}}{\\partial s} \\cdot \\frac{\\partial \\vect{r}}{\\partial\\theta_v} \\times \\frac{\\partial\\vect{r}}{\\partial\\zeta}\n= \\frac{1}{\\nabla s \\cdot \\nabla \\theta_v \\times\\nabla\\zeta}.\n\\label{eq:Jacobian}\n\\end{equation}\nHere $\\vect{r}(s,\\theta_v,\\zeta)$ is the position vector.\nThroughout this note, we will use $\\sqrt{g}$ to denote the Jacobian of the non-straight-field-line\nVMEC coordinates, as in (\\ref{eq:Jacobian}).\n\n%\\begin{align}\n%\\vect{B} &= \\nabla\\psi \\times \\nabla\\theta_p + \\iota \\nabla\\zeta \\times \\nabla\\psi \\nonumber \\\\\n%& = \\nabla\\psi \\times \\nabla\\theta_v + \\nabla\\psi \\times \\nabla \\Lambda + \\iota \\nabla\\zeta \\times \\nabla\\psi .\n%\\end{align}\n\n\\section{Computation of GS2 geometry quantities from VMEC data} \n\n\nGiven the desired central flux surface $\\psi_0$, and given a desired set of grid points in $\\alpha$ and $\\zeta$, \na 1D nonlinear root-finding algorithm is applied to solve (\\ref{eq:alpha_vmec}) for the \nvalue of $\\theta_v$ at each grid point. The $\\bmag$ array is then obtained by evaluating $B$\nat the $(\\theta_v, \\zeta)$ grid points, using VMEC's Fourier arrays {\\ttfamily bmnc} and {\\ttfamily bmns}.\n\nFor the full-flux-surface calculation, we will take the parallel coordinate $z$ to be the toroidal angle $\\zeta$.\nThen to evaluate $\\gradpar$, we use\n\\begin{equation}\n\\gradpar = L_{ref} \\frac{\\vect{B}\\cdot\\nabla\\zeta}{B} = L_{ref} \\frac{B^\\zeta}{B},\n\\end{equation}\n%\\begin{align}\n%\\gradpar\n%&=\\frac{\\vect{B}\\cdot\\nabla\\zeta}{B}\n%=\\frac{\\nabla\\psi\\times\\nabla\\alpha\\cdot\\nabla\\zeta}{B}\n%=\\frac{\\nabla\\psi\\times\\nabla(\\theta_v +\\Lambda - \\iota\\zeta)\\cdot\\nabla\\zeta}{B}\n%=\\frac{\\nabla\\psi\\times\\nabla(\\theta_v +\\Lambda)\\cdot\\nabla\\zeta}{B} \\nonumber \\\\\n%&=\\frac{1}{B \\sqrt{g}} \\left( 1 + \\frac{\\partial\\Lambda}{\\partial\\theta_v}\\right).\n%\\end{align}\nwhere $B^\\zeta$ is available in the VMEC output through the variables {\\ttfamily bsupvmnc} and {\\ttfamily bsupvmns}.\n\nTo evaluate the quantities {\\ttfamily gds*}, we must obtain the Cartesian components of\n$\\nabla\\psi$ and $\\nabla \\alpha$. To this end, we use the dual relations:\n\\begin{align}\n\\nabla s &=  \\frac{1}{\\sqrt{g}} \\frac{\\partial\\vect{r}}{\\partial\\theta_v} \\times \\frac{\\partial\\vect{r}}{\\partial\\zeta}, \\label{eq:nabla_s}\\\\\n\\nabla\\theta_v &= \\frac{1}{\\sqrt{g}} \\frac{\\partial\\vect{r}}{\\partial\\zeta} \\times \\frac{\\partial\\vect{r}}{\\partial s}\n\\label{eq:nabla_theta}.\n\\end{align}\nThe right hand sides of these two expressions can be evaluated in terms of Cartesian components using the VMEC\noutputs {\\ttfamily rmnc}, {\\ttfamily rmns}, {\\ttfamily zmnc}, and {\\ttfamily zmns}, yielding\nCartesian components for $\\nabla s$ and $\\nabla\\theta_v$. Also the Cartesian components of $\\nabla\\zeta$\nare known since $\\zeta$ is the standard toroidal angle.\nWe can then compute\n\\begin{equation}\n\\nabla\\psi = \\frac{d\\psi}{ds} \\nabla s = \\psi_{LCFS}  \\frac{1}{\\sqrt{g}} \\frac{\\partial\\vect{r}}{\\partial\\theta_v} \\times \\frac{\\partial\\vect{r}}{\\partial\\zeta}\n\\end{equation}\nand\n\\begin{align}\n\\nabla\\alpha \n&= \\nabla(\\theta_v + \\Lambda - \\iota \\zeta) \\nonumber \\\\\n&= \\left(\\frac{\\partial\\Lambda}{\\partial s} - \\zeta \\frac{d\\iota}{ds}\\right)\\nabla s\n+ \\left( 1 + \\frac{\\partial\\Lambda}{\\partial\\theta_v}\\right) \\nabla\\theta_v\n+ \\left( -\\iota + \\frac{\\partial\\Lambda}{\\partial\\zeta}\\right) \\nabla\\zeta.\n\\label{eq:grad_alpha}\n\\end{align}\n\\todo{Do we want to subtract {\\ttfamily zeta\\_center} from $\\zeta$ here so the secular $\\zeta$ term in $\\nabla\\alpha$ vanishes at the center of the domain? Or might we want it to vanish somehwhere other than the center of the domain?}\nNow that Cartesian components of $\\nabla\\psi$ and $\\nabla \\alpha$ are known, $\\gdstwo$, $\\gdstwoone$, and $\\gdstwotwo$ can be computed. \n\nTo evaluate $\\gbdriftO = \\cvdriftO$, we can use\n\\begin{align}\n\\vect{B}\\times\\nabla B\\cdot\\nabla\\psi \n&= \n\\vect{B}\\times\\nabla \\zeta \\cdot \\nabla \\psi \\frac{\\partial B}{\\partial \\zeta} + \\vect{B}\\times\\nabla \\theta_v \\cdot \\nabla \\psi \\frac{\\partial B}{\\partial \\theta_v} \\nonumber \\\\\n&=  \\left(\nB_\\theta \\nabla\\theta_v \\times\\nabla\\zeta\\cdot\\nabla s \\frac{\\partial B}{\\partial\\zeta} + B_\\zeta \\nabla\\zeta\\times\\nabla\\theta_v\\cdot\\nabla s \\frac{\\partial B}{\\partial\\theta_v} \\right) \\frac{d\\psi}{ds} \\nonumber \\\\\n&= \\left( B_\\theta \\frac{\\partial B}{\\partial\\zeta} - B_\\zeta \\frac{\\partial B}{\\partial\\theta_v} \\right) \\frac{\\psi_{LCFS} }{\\sqrt{g} }.\n\\end{align}\nTo obtain this result we have used\n\\begin{equation}\n\\nabla B = \\frac{\\partial B}{\\partial s} \\nabla s + \\frac{\\partial B}{\\partial\\theta_v} \\nabla\\theta_v + \\frac{\\partial B}{\\partial\\zeta} \\nabla\\zeta\n\\label{eq:gradB}\n\\end{equation}\nand\n\\begin{equation}\n\\vect{B} = B_s \\nabla s + B_\\theta \\nabla \\theta_v + B_\\zeta \\nabla\\zeta.\n\\label{eq:Bsub}\n\\end{equation}\nThe quantity $B_\\theta$ is available as the VMEC outputs {\\ttfamily bsubumnc} and {\\ttfamily bsubumns},\nand the quantity $B_\\zeta$ is available as the VMEC outputs {\\ttfamily bsubvmnc} and {\\ttfamily bsubvmns}.\n\n\nA couple of options are possible for computing $\\gbdrift$. One method is to compute the Cartesian components of $\\nabla B$ using\n(\\ref{eq:gradB})\ntogether with (\\ref{eq:nabla_s})-(\\ref{eq:nabla_theta}). Furthermore, the Cartesian components of $\\vect{B}$ can be computed from\n\\begin{align}\n\\vect{B} &= \\nabla\\psi \\times \\nabla (\\theta_v + \\Lambda) + \\iota \\nabla\\zeta\\times\\nabla\\psi \\nonumber \\\\\n&= \\frac{d\\psi}{ds} \\left[ \\left( 1 + \\frac{\\partial\\Lambda}{\\partial\\theta_v}\\right) \\nabla s \\times\\nabla\\theta_v \n+ \\left(\\iota - \\frac{\\partial\\Lambda}{\\partial\\zeta}\\right) \\nabla\\zeta\\times\\nabla s \\right] \\nonumber \\\\\n&= \\frac{\\psi_{LCFS}}{\\sqrt{g}} \\left[ \\left(1 + \\frac{\\partial\\Lambda}{\\partial\\theta_v}\\right) \\frac{\\partial\\vect{r}}{\\partial\\zeta}\n+ \\left( \\iota - \\frac{\\partial\\Lambda}{\\partial\\zeta}\\right) \\frac{\\partial\\vect{r}}{\\partial\\theta_v}\\right].\n\\end{align}\nNow that Cartesian components of $\\vect{B}$, $\\nabla B$, and $\\nabla \\alpha$ are all known, their cross product\nneeded for $\\gbdrift$ is straightforward. Alternatively, $\\gbdrift$ can be computed by substituting (\\ref{eq:gradB})-(\\ref{eq:Bsub}) and (\\ref{eq:grad_alpha}) into $\\vect{B}\\times\\nabla B \\cdot\\nabla\\alpha$, yielding\n\\begin{align}\n\\vect{B}\\times\\nabla B \\cdot\\nabla\\alpha\n=\n\\frac{1}{\\sqrt{g}} &\\left[\nB_s \\frac{\\partial B}{\\partial \\theta_v} \\left(\\frac{\\partial \\Lambda}{\\partial\\zeta} - \\iota \\right)\n+ B_\\theta \\frac{\\partial B}{\\partial\\zeta} \\left( \\frac{\\partial\\Lambda}{\\partial s} - \\zeta \\frac{d\\iota}{ds}\\right)\n+ B_\\zeta \\frac{\\partial B}{\\partial s} \\left( 1 + \\frac{\\partial \\Lambda}{\\partial \\theta_v}\\right) \\right. \\nonumber \\\\\n&\\left.-B_\\zeta \\frac{\\partial B}{\\partial\\theta_v} \\left( \\frac{\\partial\\Lambda}{\\partial s} - \\zeta \\frac{d\\iota}{ds}\\right)\n-B_\\theta \\frac{\\partial B}{\\partial s} \\left( \\frac{\\partial \\Lambda}{\\partial\\zeta}-\\iota\\right)\n-B_s \\frac{\\partial B}{\\partial\\zeta} \\left( 1 + \\frac{\\partial\\Lambda}{\\partial\\theta_v}\\right)\n\\right].\n\\end{align}\n\n\nThe last quantity we need to evaluate is $\\cvdrift$. Using\n\\begin{align}\n\\vect{B}\\times\\vect{\\kappa}\n&= \\vect{B}\\times(\\vect{b}\\cdot\\nabla \\vect{b}) \n= \\vect{B}\\times \\left[ (\\nabla\\times\\vect{b}) \\times\\vect{b}\\right] \\nonumber \\\\\n&= \\vect{B} \\times \\left[ -\\frac{1}{B^2} \\left( \\nabla B \\times\\vect{B}\\right)\\times\\vect{b} + \\frac{\\mu_0}{B^2} \\vect{j}\\times\\vect{B}\\right] \\nonumber \\\\\n&= \\frac{1}{B} \\vect{B}\\times\\nabla B + \\frac{\\mu_0}{B^2} \\frac{dp}{ds} \\vect{B}\\times\\nabla s,\n\\end{align}\n(where we have used the MHD equilibrium equation $\\vect{j}\\times\\vect{B} = \\nabla p$), we find\n\\begin{equation}\n\\cvdrift = \\gbdrift \n+ \\frac{2 B_{ref} L_{ref}^2}{B^2} \\sqrt{\\frac{\\psi}{\\psi_{LCFS}}} \\frac{\\mu_0}{B^2} \\frac{dp}{ds} \\vect{B}\\times\\nabla s \\cdot \\nabla \\alpha.\n\\end{equation}\nIn the last term, $\\vect{B}\\times\\nabla s \\cdot \\nabla \\alpha$ can either\nbe evaluated using the Cartesian components of $\\vect{B}$, $\\nabla s$, and $\\nabla \\alpha$,\nthe calculation of which has already been described,\nor by combining (\\ref{eq:grad_alpha}) and (\\ref{eq:Bsub}) to obtain\n\\begin{equation}\n\\vect{B}\\times\\nabla s \\cdot \\nabla \\alpha\n= \\frac{1}{\\sqrt{g}} \\left[\nB_\\zeta \\left( 1  + \\frac{\\partial\\Lambda}{\\partial\\theta_v}\\right)\n-B_\\theta \\left( \\frac{\\partial\\Lambda}{\\partial\\zeta} - \\iota \\right) \\right].\n\\end{equation}\n\n\n\n\n\\section{Parallel boundary condition and wavenumber quantization for a full surface calculation}\n\nLet us now consider a full-flux-surface calculations, using field-aligned coordinates. \nWe continue to use $\\psi$ and $\\alpha$ as perpendicular coordinates, and $\\zeta$ as the third (parallel) coordinate.\nIn a full-flux-surface calculation, the range of $\\alpha$ is $[0,\\; 2\\pi)$,\nwhich can be seen from the fact at fixed $\\psi$ and $\\zeta$, the $2\\pi$-periodicity of quantities in\n$\\theta_p$ implies $2\\pi$-periodicity in $\\alpha$.\n\nJust as in a flux tube code, fluctuating quantities such as the electrostatic potential $\\phi$ are represented as\n\\begin{equation}\n\\phi(\\psi,\\alpha,\\zeta)\n=\\sum_{k_\\psi, k_\\alpha} \\bar{\\phi}_{k_\\psi,k_\\alpha}(\\zeta) \\exp\\left( i k_\\alpha \\alpha + i k_\\psi \\left[ \\psi - \\psi_0\\right] \\right).\n\\label{eq:fluctuations}\n\\end{equation}\nAgain, $\\psi_0$ indicates the flux surface about which the numerical domain is centered.\nThe wavenumbers with respect to $(\\psi,\\alpha)$ are related to wavenumbers with respect to $(x,y)$ through\n\\begin{align}\n\\label{eq:k_conversion}\nk_x &= k_\\psi \\frac{d\\psi}{dx}, \\\\\nk_y &= k_\\alpha \\frac{d\\alpha}{dy} \\nonumber.\n\\end{align}\nNote that $k_\\alpha$ ranges over the integers, due to the $2\\pi$-periodicity in $\\alpha$ discussed above.\nThe choice of $y$ (\\ref{eq:dy_dalpha}) then implies the wavenumber grid in $y$ must be\n\\begin{equation}\nk_y \\rho_{ref} = \\frac{\\rho_{ref}}{L_{ref} \\sqrt{s(\\psi_0)}} \\times (\\mathrm{integers}).\n\\end{equation}\nWe take fluctuating quantities to be periodic in $\\psi$, just as in a flux tube code. The allowed values of $k_\\psi$ and associated `box size' in $\\psi$\nwill be derived below.\n\nWe take fluctuating quantities to be periodic in $\\zeta$ with period $2 \\pi P$ at fixed $\\psi$ and $\\theta_p$.\nHere, $P$ is a rational number, typically the inverse of the number of field periods (e.g. 5 for W7-X).\nOne could also choose $P=1$ to simulate the entire toroidal domain, or choose $P=$ integer / (number of field periods)\nfor an intermediate domain size. When $P=1$, this periodicity condition is the true periodicity of the torus.\nWhen $P=$ integer / (number of field periods), the periodicity imposed in the code is effectively a statement\nof statistical periodicity of the turbulence at geometrically equivalent points in the domain. To see the implications of imposing\nperiodicity in $\\zeta$ at fixed $\\theta_p$, we substitute $\\alpha = \\theta_p - \\iota \\zeta$ and the Taylor expansion\n\\begin{equation}\n\\iota \\approx \\iota(\\psi_0) + \\frac{d\\iota}{d\\psi} \\left[ \\psi - \\psi_0\\right]\n\\label{eq:Taylor_iota}\n\\end{equation}\ninto (\\ref{eq:fluctuations}). (We take $d\\iota/d\\psi$ to be evaluated at $\\psi_0$, and hence constant over the domain.) The result is\n\\begin{equation}\n\\phi\n=\\sum_{k_\\psi, k_\\alpha} \\bar{\\phi}_{k_\\psi,k_\\alpha}(\\zeta) \\exp\n\\left( i k_\\alpha \\theta_p  \n-i k_\\alpha \\iota(\\psi_0) \\zeta\n+i \\left[- k_\\alpha \\frac{d\\iota}{d\\psi}  \\zeta\n + k_\\psi\\right] \\left[ \\psi - \\psi_0\\right] \\right).\n\\end{equation}\nWhen a particular $(k_\\psi,k_\\alpha)$ Fourier mode gets to the end of the $\\zeta$ domain ($\\zeta = 2\\pi P$), we want\nthe mode to connect exactly to another Fourier mode in the simulation $(k'_\\psi,k'_\\alpha)$, with the latter evaluated\nat $\\zeta=0$. Mathematically, this condition is\n\\begin{align}\n&\\bar{\\phi}_{k_\\psi,k_\\alpha}(2\\pi P) \\exp\n\\left( i k_\\alpha \\theta_p  \n-i k_\\alpha \\iota(\\psi_0) 2\\pi P\n+i \\left[- k_\\alpha \\frac{d\\iota}{d\\psi}  2 \\pi P\n+ k_\\psi\\right] \\left[ \\psi - \\psi_0\\right] \\right) \\nonumber \\\\\n&=\n\\bar{\\phi}_{k'_\\psi,k'_\\alpha}(0) \\exp\n\\left( i k'_\\alpha \\theta_p  \n+i k'_\\psi\\left[ \\psi - \\psi_0\\right] \\right) .\n\\label{eq:parallelBC}\n\\end{align}\nFor this equation to hold for all $\\theta_p$ at fixed $\\psi$, we must have $k'_\\alpha = k_\\alpha$.\nFor equality to hold for all $\\psi$ at fixed $\\theta_p$, we must have\n\\begin{equation}\nk'_\\psi\n= k_\\psi - k_\\alpha \\frac{d\\iota}{d\\psi}  2 \\pi P.\n\\label{eq:twist_and_shift}\n\\end{equation}\nThis last result is analogous to the twist-and-shift condition used in flux-tube GS2. \nIf $k'_\\psi$ is to be included in the wavenumber grid, and assuming the $k_\\psi$ grid consists of integer multiples of some\n$k_{\\psi,min}$, then the difference $k'_\\psi - k_\\psi$ should\nbe an integer multiple of $k_{\\psi,min}$. \nIn particular this must be true for the smallest nonzero $k_\\alpha$, which is 1.\nThus, we conclude\n\\begin{equation}\n\\frac{d\\iota}{d\\psi} 2\\pi P = (\\jtwist) k_{\\psi,min}\n\\end{equation}\nwhere $\\jtwist$ is an integer. It follows that the `box size' in $\\psi$, denoted $L_\\psi$, is\n\\begin{equation}\nL_\\psi = \\frac{2\\pi}{k_{\\psi,min}} = \n\\frac{(\\jtwist)}{P} \\left( \\frac{d\\iota}{d\\psi} \\right)^{-1}.\n\\end{equation}\nUsing (\\ref{eq:k_conversion}) and (\\ref{eq:psi_x_conversion}), the equivalent box size in $x$ is\n\\begin{equation}\nL_x = \\frac{dx}{d\\psi} L_\\psi = \\frac{2\\pi}{k_{x,min}} = \n\\frac{(\\jtwist)}{ P L_{ref} B_{ref} \\sqrt{s}} \\left( \\frac{d\\iota}{d\\psi} \\right)^{-1}.\n\\label{eq:Lx}\n\\end{equation}\nUnfortunately, in low-shear stellarators like W7-X and HSX, $d \\iota/d\\psi$ in \n(\\ref{eq:Lx}) can be quite small, meaning $L_x$ must be quite large.\n\nEquation (\\ref{eq:parallelBC}) also indicates there should be a phase shift when two Fourier modes\nare connected:\n\\begin{equation}\n\\bar{\\phi}_{k_\\psi,k_\\alpha}(2\\pi P) \\exp\n\\left( -i k_\\alpha \\iota(\\psi_0) 2\\pi P \\right) \n=\n\\bar{\\phi}_{k'_\\psi,k_\\alpha}(0).\n\\label{eq:phase}\n\\end{equation}\n\n\\subsection{Continuity of geometric quantities}\n\n%It is interesting to check whether \nWe can verify that various terms in the gyrokinetic equation are continuous\n% when a Fourier mode is followed \nacross the parallel boundary condition. First, let us consider the magnetic drift term:\n\\begin{align}\n\\vect{v}_{m}\\cdot \\nabla h \n&= \\vect{v}_{m} \\cdot \\nabla \\left[\n\\sum_{k_\\psi,k_\\alpha} \\bar{h}_{k_\\psi,k_\\alpha}(\\zeta) \\exp \\left( i k_\\alpha \\alpha + i k_\\psi [\\psi - \\psi_0] \\right) \\right] \\nonumber \\\\\n&\\approx \n\\sum_{k_\\psi,k_\\alpha} \\bar{h}_{k_\\psi,k_\\alpha}(\\zeta)\n\\exp \\left( i k_\\alpha \\alpha + i k_\\psi [\\psi - \\psi_0] \\right)\n\\left[ i k_\\alpha \\vect{v}_{m}\\cdot \\nabla \\alpha + i k_\\psi \\vect{v}_{m}\\cdot\\nabla\\psi \\right] \\nonumber \\\\\n& =\n\\sum_{k_\\psi,k_\\alpha} \\bar{h}_{k_\\psi,k_\\alpha}(\\zeta)\n\\exp \\left( i k_\\alpha [\\theta_p - \\iota \\zeta] + i k_\\psi [\\psi - \\psi_0] \\right) \\nonumber \\\\\n& \\hspace{1in}\\times \\left[ i k_\\alpha \\vect{v}_{m}\\cdot \\left(\\nabla \\theta_p - \\iota \\nabla\\zeta - \\zeta \\frac{d\\iota}{d\\psi} \\nabla\\psi \\right) + i k_\\psi \\vect{v}_{m}\\cdot\\nabla\\psi \\right],\n\\label{eq:grad_B_drift_term}\n\\end{align}\nwhere $h$ is the nonadiabatic distribution function. (The $\\approx$ above comes from dropping the slow $\\zeta$ dependence of $\\bar{h}_{k_\\psi,\\zeta}$\nin the gradient.) As $\\zeta$ is increased, just before the boundary $\\zeta = 2\\pi P$ we have\n\\begin{align}\n\\left( \\vect{v}_{m}\\cdot \\nabla h \\right)_-\n& =\n\\sum_{k_\\psi,k_\\alpha} \\bar{h}_{k_\\psi,k_\\alpha}(2\\pi P)\n\\exp \\left( i k_\\alpha [\\theta_p - \\iota 2\\pi P] + i k_\\psi [\\psi - \\psi_0] \\right) \\nonumber \\\\\n& \\hspace{1in}\\times \\left[ i k_\\alpha \\vect{v}_{m}\\cdot \\left(\\nabla \\theta_p - \\iota \\nabla\\zeta - 2\\pi P \\frac{d\\iota}{d\\psi} \\nabla\\psi \\right) + i k_\\psi \\vect{v}_{m}\\cdot\\nabla\\psi \\right].\n\\label{eq:v_B_term_minus}\n\\end{align}\nThe subscript on the left hand side indicates that we have evaluated the result just to the left of the boundary.\nOn the other side of the boundary ($\\zeta = 0$), (\\ref{eq:grad_B_drift_term}) evaluates to\n\\begin{equation}\n\\left(\\vect{v}_{m}\\cdot \\nabla h \\right)_+\n= \n\\sum_{k_\\psi,k_\\alpha} \\bar{h}_{k'_\\psi,k_\\alpha}(0)\n\\exp \\left( i k_\\alpha \\theta_p  + i k'_\\psi [\\psi - \\psi_0] \\right) \n\\left[ i k_\\alpha \\vect{v}_{m}\\cdot \\left(\\nabla \\theta_p - \\iota \\nabla\\zeta \\right) + i k'_\\psi \\vect{v}_{m}\\cdot\\nabla\\psi \\right].\n\\end{equation}\nIn this last equation, we were free to put primes on $k_\\psi$ because it is summed over. Applying \n(\\ref{eq:twist_and_shift}) and (\\ref{eq:phase}),\n\\begin{align}\n\\left(\\vect{v}_{m}\\cdot \\nabla h \\right)_+\n=& \n\\sum_{k_\\psi,k_\\alpha} \\bar{h}_{k_\\psi,k_\\alpha}(2\\pi P) \n\\exp \\left( i k_\\alpha \\theta_p   -i k_\\alpha \\iota(\\psi_0) 2\\pi P+ i \\left[ k_\\psi - k_\\alpha \\frac{d\\iota}{d\\psi}  2 \\pi P\\right] [\\psi - \\psi_0] \\right) \\nonumber \\\\\n& \\hspace{1in} \\times \\left[ i k_\\alpha \\vect{v}_{m}\\cdot \\left(\\nabla \\theta_p - \\iota \\nabla\\zeta \\right) + i \\left[ k_\\psi - k_\\alpha \\frac{d\\iota}{d\\psi}  2 \\pi P\\right] \\vect{v}_{m}\\cdot\\nabla\\psi \\right].\n\\label{eq:v_B_term_plus}\n\\end{align}\nUsing (\\ref{eq:Taylor_iota}), it can be seen that (\\ref{eq:v_B_term_minus}) is identical to  (\\ref{eq:v_B_term_plus}),\nso the magnetic drift term is indeed continuous across the boundary.\n\n\\todo{Also show continuity for $\\langle \\phi \\rangle_R$...}\n\n\\begin{comment}\n\nperpendicular wavenumber appearing inside the Bessel functions:\n\\begin{equation}\nk_{\\perp}^2 = k_\\alpha^2 |\\nabla \\alpha|^2 + 2 k_\\alpha k_\\psi \\nabla\\alpha\\times\\nabla\\psi + k_\\psi^2 |\\nabla\\psi|^2.\n\\label{eq:kperp2}\n\\end{equation}\nUsing\n\\begin{equation}\n\\nabla\\alpha = \\nabla\\theta_p - \\iota \\nabla\\zeta - \\zeta \\frac{d\\iota}{d\\psi} \\nabla\\psi,\n\\end{equation}\nwe find that (\\ref{eq:kperp2}) \n\n\\end{comment}\n\n\\end{document} \n", "meta": {"hexsha": "c5d5e0af62cd5fc6bbf4df5c27e19b5b8c5f9074", "size": 27683, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/vmec_interface/doc/gs2_full_surface_stellarator_geometry.tex", "max_stars_repo_name": "SStroteich/stella-1", "max_stars_repo_head_hexsha": "104556a07b9736e7c28e6f1bf2f799384732f38b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-12-15T08:23:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T15:14:42.000Z", "max_issues_repo_path": "src/vmec_interface/doc/gs2_full_surface_stellarator_geometry.tex", "max_issues_repo_name": "SStroteich/stella-1", "max_issues_repo_head_hexsha": "104556a07b9736e7c28e6f1bf2f799384732f38b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 37, "max_issues_repo_issues_event_min_datetime": "2021-07-05T16:41:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T15:58:05.000Z", "max_forks_repo_path": "src/vmec_interface/doc/gs2_full_surface_stellarator_geometry.tex", "max_forks_repo_name": "SStroteich/stella-1", "max_forks_repo_head_hexsha": "104556a07b9736e7c28e6f1bf2f799384732f38b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2021-07-05T15:35:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T09:23:42.000Z", "avg_line_length": 53.4420849421, "max_line_length": 234, "alphanum_fraction": 0.7003576202, "num_tokens": 9746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.3093846322664934}}
{"text": "\\documentclass[12pt,a4paper]{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage{amsmath}\n\\usepackage{amsfonts}\n\\usepackage{amssymb}\n\\usepackage{makeidx}\n\\usepackage{graphicx}\n\\usepackage{lmodern}\n\\usepackage{url}\n\\usepackage{bm}\n\\usepackage{color}\n\\usepackage{booktabs}\n\\usepackage{float}\n\\usepackage[left=2cm,right=2cm,top=2cm,bottom=2cm]{geometry}\n\\author{Mudathir Mahgoub}\n\\title{Project report}\n\\begin{document}\n\n\\maketitle\n\n\\section{Description of PDL solver}\nThis PDL solver checks the satisfiability of formulas in propositional dynamic logic (PDL).\nThe input is a kripke frame, which is optional, followed by a formula in PDL. The output is the satisfiability result of this formula which is either \\textit{unsat}, \\textit{sat} or \\textit{unknown}. If the result is \\textit{sat}, the solver outputs a kripke frame that satisfies the formula. Furthermore, it specifies the set of states where the formula is satisfied. If this set is equal to $K$, the set of all states in the kripke frame, then the formula is valid in this kripke frame. Otherwise, this set satisfies the formula and its complement, with respect to $K$, falsifies the formula. \n\nTo check the validity of a formula in all kripke frames, its negation should be used as an input and if the result is \\textit{unsat}, then it is valid. If the result is \\textit{sat}, then the returned kripke frame is a counter example that falsifies the original formula.\n\n\\section{PDL Complexity}\n\nThe satisfiability problem for PDL formulas is decidable, and it is \\textit{EXPTIME-complete} (theorm 8.5 in \\cite{dynamic}). Therefore the solver may fail to determine the satisfiability within the time limit (by default it is 30 seconds), and hence it returns \\textit{unknown} result. \n\n% THEOREM 6.5 ( SMALL MODEL THEOREM): Let $\\varphi$ be a satisfiable formula of\n% PDL. Then $\\varphi$ is satisfied in a Kripke frame with no more than $2^{\\vert \\varphi \\vert}$ % states.\n\nOn the other hand the satisfiability of a PDL formula in a given Kripke frame can be determined in polynomial time (exercise 6.4 in \\cite{dynamic}). So one expects this to be easy for CVC4 when the model (Kripke frame) is given and ``check-sat\" is executed. Unfortunately, CVC4 doesn't terminate if the formula is \\textit{unsat} and uses transitive closure operation. After asking an expert (Andrew Reynolds), apparently CVC4 keeps  ``adding a repeating pattern of lemmas related to transitive closure\" which needs to be reviewed. Fortunately I found a work around by just removing the constraint related to the PDL formula and asserting only the frame constraints. After CVC4 finds the model, the PDL formula is evaluated. If the result is true, then it is \\textit{sat}, otherwise it is \\textit{unsat}.\n\n\n\\subsection{Exercise 6.4}\nExercise 6.4 in the book says: \n\\begin{quote}\nGive a polynomial time algorithm to check whether a given PDL formula\nis satisfied at a given state in a given Kripke frame. Describe briefly the data\nstructures you would use to represent the formula and the Kripke frame. Specify\nyour algorithm at a high level and give a brief complexity analysis\n\\end{quote}\n\nThe following is my reasoning for this exercise where $K$ is the set of all states in the frame:\n\\begin{itemize}\n\\item Formulas $\\textbf{0}$, $\\textbf{1}$, and atomic propositions are subsets of $K$, therefore they can be computed in $O(\\vert K \\vert)$.\n\\item Programs $\\textbf{skip}?$, $\\textbf{fail}?$, and atomic programs are subsets of $K \\times K$, therefore they can be computed in $O(\\vert K \\vert^2)$.\n\n\\item Boolean operators $\\neg, \\wedge, \\vee, \\rightarrow, \\leftrightarrow$ involve set operations $-, \\cap, \\cup: \\mathbb{P}(K) \\times \\mathbb{P}(K) \\rightarrow \\mathbb{P}(K)$ where $\\mathbb{P}$ denotes the power set. These set operations be computed in $O(\\vert K \\vert^2)$ or $O(\\vert K \\vert)$ if hash tables are used.\n\n\\item Program operators $;, \\cup, *$ and modal operators $[], \\langle \\rangle$ involve set operations and relation operations $\\circ, *: \\mathbb{P}(K \\times K) \\times \\mathbb{P}(K \\times K) \\rightarrow \\mathbb{P}(K \\times K)$. Both $\\circ$ and $*$ can be computed using graph data structures and DFS algorithm. \nFor $\\circ$ operation, the DFS algorithm stops at depth 2, and for $*$ it continues until the end. \nIf the graph is dense, both operations $\\circ, *$ require at most $O(\\vert K \\vert^3)$ to be computed for all states (all graph vertices). \n\n\\item If the number of operators in a given formula $\\varphi$ is $n$, then the formula semantics $m(\\varphi)$ can be evaluated in $O(n \\vert K \\vert ^3)$. Finally it takes constant time to evaluate $m(\\varphi) \\neq \\varphi$ to  determine the satisfiability answer. \n\\end{itemize}\n\nFrom the above discussion, the worst case scenario takes $O(n \\vert K \\vert ^3)$ time which is polynomial. \n\n\\section{Installation}\n\nThe following commands download the source code from github and compile it to generate the solver file ``pdl.jar\". \n\n\\begin{verbatim}\ngit clone https://github.com/mudathirmahgoub/pdl\ncd pdl\nchmod 777 gradlew\n./gradlew build\ncd bin\nchmod 777 cvc4_linux\njava -jar pdl.jar -i test.pdl \njava -jar plantuml.jar test.dot\n\\end{verbatim}\n\nThe last command ``java -jar plantuml.jar test.dot\" requires graphvis to be in the path. Installation instructions for graphvis are available in \\url{https://graphviz.gitlab.io/download/}. \n\n\\section{Software components}\n\\begin{figure}[H]\n\\center\n\\includegraphics[scale=0.35]{solver.png}\n\\caption{Software components}\n\\end{figure}\n\nAs shown in the figure above, the input string is parsed into PDL abstract syntax tree (AST) which is read by the translator. Then it gets translated into SMT AST which is sent to CVC4 as SMT-LIB code. CVC4 checks the satisfiability and returns either \\textit{sat}, \\textit{unsat} or \\textit{unknown}. When \\textit{sat} result is returned, CVC4 is asked to return the SMT model and the values of additional SMT expressions. The returned SMT model and values are parsed into SMT ASTs which are converted into a kripke frame and a set of states satisfied by the PDL formula. Finally kripke, and dot files are generated. \n\nThe project is written in Java 8 and available in github\\footnote{\\url{https://github.com/mudathirmahgoub/pdl}}. To build the project, Gradle is used to download and compile the project and generate the jar files. Graphviz software is needed to visualize the generated dot file\\footnote{\\url{https://www.graphviz.org}}. \n\n\\section{PDL formula translation}\n\nWhat does it mean to have a satisfiable formula in PDL ?\n\nA PDL formula $\\varphi$ is satisfiable if there exists a kripke frame $\\mathfrak{K}=(K, m_{\\mathfrak{K}})$ and a state  $u$ such that $u \\in m_{\\mathfrak{K}}(\\varphi) $, and we write $\\mathfrak{K}, u \\models \\varphi$. In simple words, a formula is satisfiable if its meaning is nonempty in some kripke frame (i.e. $m_{\\mathfrak{K}}(\\varphi) \\neq \\phi$). \n\nSince the PDL semantics uses set and relation operations, they are translated directly into their corresponding operations in the relation theory in CVC4. The only exception is the reflexive transitive closure $*$ which is not supported directly in CVC4, but supported through the built-in transitive closure. Table \\ref{tab:translation} summarizes this translation. Other PDL operators are defined using the basic operators in table \\ref{tab:translation}. The book \\cite{dynamic} introduces the converse operator $^{\\_}$ in page 177 for \\textit{backtracking} programs which was not covered in class. Its semantics is the transpose relation which is defined as:\n\\begin{align*}\nm_{\\mathfrak{K}}(a^{\\_}) = m_{\\mathfrak{K}}(a)^{\\_} = \\lbrace (v, u) \\; \\vert \\; (u, v) \\in m_{\\mathfrak{K}}(a) \\rbrace\n\\end{align*}\n\n\n\\begin{table}[H]\n\\begin{center}\n\\begin{tabular}{ll} \n\\toprule\nPDL & CVC4 \\\\    \n\\midrule    \n$K=\\lbrace u_0, u_1, \\cdots u_n \\rbrace$ &  \n$\\begin{matrix}\n\\text{\\textbf{Atom} : \\text{Uninterpreted sort}} \\\\\nu_0, u_1, \\cdots, u_n: \\textbf{Atom} \\\\\n\\textit{atomUniverse}: \\text{Set(Tuple (\\textbf{Atom}))} = \\lbrace \\langle u_0 \\rangle, \\langle u_1 \\rangle, \\cdots , \\langle u_n \\rangle \\rbrace \\\\\n\\textit{atomIdentity}:  = \\lbrace \\langle u_0, u_0 \\rangle, \\langle u_1, u_1 \\rangle, \\cdots , \\langle u_n, u_n \\rangle \\rbrace \\\\\n\\end{matrix}$ \\\\ \\midrule   \n\\textbf{0} & \\textit{emptyset} : (Set (Tuple \\textbf{Atom})) \\\\\n\\textbf{1} & \\textit{atomUniverse} \\\\\nAtomic propositions $p, q, r, \\cdots$ & $p, q, r, \\cdots : \\text{Set(Tuple (\\textbf{Atom}))}$ \\\\\nAtomic programs $a, b, c, \\cdots$ & $a, b, c \\cdots : \\text{Set(Tuple (\\textbf{Atom}$,$\\textbf{Atom}))}$ \\\\\n$p \\vee q$ & $p \\cup q$ \\\\\n$p \\wedge q$ & $p \\cap q$ \\\\\n$\\neg p$ & $\\textit{atomUniverse} - p$ \\\\\n$p \\rightarrow q$ & $(\\textit{atomUniverse}- p)\\cup q$ \\\\\n$a;b$ & $a \\circ b$ where $\\circ$ is the join operator\\\\\n$a \\cup b$ (choice) & $a \\cup b$ (union)\\\\\n$a^*$ (iteration) & $\\textit{atomIdentity} \\cup a^+$, (transitive closure)\\\\\n$p?$ (test) & $(p \\times p) \\cap \\textit{atomIdentity}$\\\\\n\\color{red}\n$a^{\\_}$ (converse) & \\color{red} $a^t (transpose)$\\\\\n\n\\bottomrule\n\\end{tabular}\n\\end{center}\n\\caption{PDL translation to CVC4.} \\label{tab:translation}\n\\end{table}\n\n\\subsection{The semantics of the equivalence operator $\\leftrightarrow$}\n\nThe textbook \\cite{dynamic} did not mention explicitly the semantics of the operator $\\leftrightarrow$. However in theorem 5.8 (and other theorems), the book proves the validity of the formula\n\\begin{align*}\n\\langle \\alpha \\cup \\beta \\rangle \\varphi \\leftrightarrow \\langle \\alpha \\rangle \\varphi \\vee \\langle \\beta \\rangle \\varphi\n\\end{align*}\nby proving this set equality \n\\begin{align*}\nm_\\mathfrak{K}( \\langle \\alpha \\cup \\beta \\rangle \\varphi ) = m_\\mathfrak{K}(\\langle \\alpha \\rangle\\varphi  \\vee  \\langle \\beta \\rangle \\varphi)\n\\end{align*}\n\nThis set equality $=_{\\mathbb{P}(K)} : \\mathbb{P}(K) \\times \\mathbb{P}(K) \\rightarrow \\lbrace \\textit{true, false} \\rbrace$ ($\\mathbb{P}(K)$ is the power set of $K$) is an operation that returns a boolean. This is different than the semantics of operators $\\rightarrow, \\wedge, \\vee: \\mathbb{P}(K) \\times \\mathbb{P}(K) \\rightarrow \\mathbb{P}(K)$ which returns a subset of $K$. It is possible to use the set equality in $CVC4$ with an $ite$ (\\textit{if-then-else}) expression to return a subset of $K$ as follows: \n\\begin{align*}\nm_\\mathfrak{K} (p \\leftrightarrow q) = ite(m_\\mathfrak{K} (p) =  m_\\mathfrak{K}(q), K,  K - \\left( (m_\\mathfrak{K}(p) - m_\\mathfrak{K}(q))  \\cup \n   (m_\\mathfrak{K}(q) - m_\\mathfrak{K}(p)) \\right)) \n\\end{align*}\n\nIn my translation, however,  I used the following semantics:\n\\begin{align*}\nm_\\mathfrak{K} (p \\leftrightarrow q) = m_\\mathfrak{K} ((p \\rightarrow q) \\wedge (q \\rightarrow p))\n\\end{align*}\nThe following two lemmas connect between these three approaches in PDL formulas. \n\n\\subsection*{Lemma 1}\n\n\\begin{align*}\nm_\\mathfrak{K} ((p \\rightarrow q) \\wedge (q \\rightarrow p)) = ite(m_\\mathfrak{K} (p) =  m_\\mathfrak{K}(q), K,  K - \\left( (m_\\mathfrak{K}(p) - m_\\mathfrak{K}(q))  \\cup \n   (m_\\mathfrak{K}(q) - m_\\mathfrak{K}(p)) \\right)) \n\\end{align*}\n\\subsubsection*{\\textit{Proof}}\n\\begin{enumerate}\n\\item Case $m_\\mathfrak{K} (p) =  m_\\mathfrak{K}(q)$:\n\\begin{align*}\nm_\\mathfrak{K} ((p \\rightarrow q) \\wedge (q \\rightarrow p)) &= \n((K - m_\\mathfrak{K}(p)) \\cup m_\\mathfrak{K} (q)) \\cap \n((K - m_\\mathfrak{K}(p)) \\cup m_\\mathfrak{K} (q)) \\\\\n&= K \\cap K  \\\\\n&=K  = ite(m_\\mathfrak{K} (p) =  m_\\mathfrak{K}(q), K,  K - \\left( (m_\\mathfrak{K}(p) - m_\\mathfrak{K}(q))  \\cup \n   (m_\\mathfrak{K}(q) - m_\\mathfrak{K}(p)) \\right)) \n\\end{align*}\n\\item Case $m_\\mathfrak{K} (p) \\neq  m_\\mathfrak{K}(q)$:\n\\begin{align*}\nm_\\mathfrak{K} ((p \\rightarrow q) \\wedge (q \\rightarrow p)) &= \n((K - m_\\mathfrak{K}(p)) \\cup m_\\mathfrak{K} (q)) \\cap \n((K - m_\\mathfrak{K}(p)) \\cup m_\\mathfrak{K} (q)) \\\\\n&= \\left( K - (m_\\mathfrak{K}(p) - m_\\mathfrak{K}(q) \\right)  \\cap \n   \\left( K - (m_\\mathfrak{K}(q) - m_\\mathfrak{K}(p) \\right) \\\\\n&=  K - \\left( (m_\\mathfrak{K}(p) - m_\\mathfrak{K}(q))  \\cup \n   (m_\\mathfrak{K}(q) - m_\\mathfrak{K}(p)) \\right) \\\\\n&= ite(m_\\mathfrak{K} (p) =  m_\\mathfrak{K}(q), K,  K - \\left( (m_\\mathfrak{K}(p) - m_\\mathfrak{K}(q))  \\cup \n   (m_\\mathfrak{K}(q) - m_\\mathfrak{K}(p)) \\right)) \n\\end{align*}\n\\end{enumerate}\n\n\n\\subsection*{Lemma 2}\n\nThe PDL formula $p \\leftrightarrow q$ is valid using the textbook definition $m_\\mathfrak{K}(p)= m_\\mathfrak{K}(q)$ if and only if the formula $\\neg ((p \\rightarrow q) \\wedge (q \\rightarrow p))$ is \\textit{unsatisfiable}.\n\\subsubsection*{\\textit{Proof}}\nAssume the formula $p \\leftrightarrow q$ is valid. This means $m_\\mathfrak{K}(p)= m_\\mathfrak{K}(q)$. Then\n\\begin{align*}\nm_\\mathfrak{K}(\\neg ((p \\rightarrow q) \\wedge (q \\rightarrow p))) \n&= K - m_\\mathfrak{K}((p \\rightarrow q) \\wedge (q \\rightarrow p)) \\\\\n&= K - ite(m_\\mathfrak{K} (p) =  m_\\mathfrak{K}(q), K,  K - \\left( (m_\\mathfrak{K}(p) - m_\\mathfrak{K}(q))  \\cup \n   (m_\\mathfrak{K}(q) - m_\\mathfrak{K}(p)) \\right))  \\tag{\\text{using lemma 1}} \\\\\n&= \\phi\n\\end{align*}\n\nAssume the formula $\\neg ((p \\rightarrow q) \\wedge (q \\rightarrow p))$ is \\textit{unsatisfiable}. Then \n\\begin{align*}\nm_\\mathfrak{K}(\\neg ((p \\rightarrow q) \\wedge (q \\rightarrow p))) &= \\phi \\Rightarrow \\\\\nK- m_\\mathfrak{K}((p \\rightarrow q) \\wedge (q \\rightarrow p)) &= \\phi \\Rightarrow \\\\\nK - ite(m_\\mathfrak{K} (p) =  m_\\mathfrak{K}(q), K,  K - \\left( (m_\\mathfrak{K}(p) - m_\\mathfrak{K}(q))  \\cup \n   (m_\\mathfrak{K}(q) - m_\\mathfrak{K}(p)) \\right)) &= \\phi \\Rightarrow \\\\\n   ite(m_\\mathfrak{K} (p) =  m_\\mathfrak{K}(q), K,  K - \\left( (m_\\mathfrak{K}(p) - m_\\mathfrak{K}(q))  \\cup \n   (m_\\mathfrak{K}(q) - m_\\mathfrak{K}(p)) \\right)) &= K \\Rightarrow \\\\\n   m_\\mathfrak{K} (p) =  m_\\mathfrak{K}(q)\n\\end{align*}\n\n\n\n\\section{Examples}\n\n\\subsection{A PDL formula without Kripke frame}\n\n\\subsubsection*{Input}\n\\begin{verbatim}\n(p and q) and\n<do p -> a | q -> b od>\n    (\n        (<b> (p and not q))  and\n        (<a> (q and not p))\n    )\n\\end{verbatim}\nThe above formula is equivalent to:\n\\begin{align*}\n((p \\wedge q) \\wedge \\langle\\textbf{ do }p \\rightarrow a \\vert q \\rightarrow b\\textbf{ od }\\rangle(\\langle b\\rangle(p \\wedge \\neg q) \\wedge \\langle a \\rangle(q \\wedge \\neg p)))\n\\end{align*}\n\\subsection*{Output (.kripke file)}\n\\begin{verbatim}\nK = {0, 2, 1, 3}\nm(p) = {0, 3}\nm(q) = {1, 3}\nm(a) = {(2,1), (3,2)}\nm(b) = {(2,0)}\nSatisfying states: [3]\n\\end{verbatim}\n\\subsection*{Output (.dot file)}\n\n\\begin{figure}[H]\n\\center\n\\includegraphics[scale=0.4]{example1.png}\n\n\\caption{The formula is satisfied in state $3$ (green) and unsatisfied in states $0, 1, 2$ (red). }\n\\end{figure}\n\n\n\\subsection{A PDL formula with Kripke frame}\n\n\\subsubsection*{Input}\n\\begin{verbatim}\nK = {01,2,3,4,5}\nm(p) = {01,2,4}\nm(q) = {01, 3}\nm(r) = {5}\nm(a) = {(01,2), (01,4), (2,4), (01,3)}\nm(b) = {(01,3), (3,3)}\nm(c) = {(5,5)}\n[a union b union c] (q and not p)\n\\end{verbatim}\nThe above formula is equivalent to:\n\\begin{align*}\n[((a \\cup b) \\cup c)](q \\wedge \\neg p)\n\\end{align*}\n\\subsection*{Output (.kripke file)}\n\\begin{verbatim}\nK = {s01, s2, s3, s4, s5}\nm(p) = {s01, s2, s4}\nm(q) = {s01, s3}\nm(r) = {s5}\nm(a) = {(s01,s2), (s01,s4), (s2,s4), (s01,s3)}\nm(b) = {(s01,s3), (s3,s3)}\nm(c) = {(s5,s5)}\nSatisfying states: [s3, s4]\n\\end{verbatim}\n\\subsection*{Output (.dot file)}\n\n\\begin{figure}[H]\n\\center\n\\includegraphics[scale=0.4]{example2.png}\n\n\\caption{The formula is satisfied in states $s3, s4$ (green) and unsatisfied in states $s01, s2, s5$ (red). }\n\\end{figure}\n\n\n\\subsection{A valid PDL formula}\n\\subsubsection*{Input}\n\\begin{verbatim}\nnot (<a converse> [a] p -> p)\n\\end{verbatim}\nThe above formula is equivalent to \n\\begin{align*}\n\\neg(\\langle a^{\\_} \\rangle [a] p \\rightarrow p)\n\\end{align*}\n\n\\subsubsection*{Output}\nunsat\n\n\nThis means the formula $\\langle a^{\\_} \\rangle [a] p \\rightarrow p$ is valid in all kripke frames.\n\\section{Benchmark}\nTo rigorously test the PDL solver, I used the valid formulas from chapter 5 as a benchmark. The total number of valid formulas in the benchmark is 42. The PDL solver managed to prove 24 formulas in less than 2 seconds, and timed out after 1 minute in 18 formulas.  I guess this benchmark can be used for the relation theory in CVC4. Table \\ref{tab:benchmark} summarizes the result. \n\n\\begin{table}[H]\n\\center\n\\begin{tabular}{lccr}\n\\toprule\nLabel & PDL formula & Output & Duration \\\\\n\\midrule\nBook formula 1 & $\\neg ([a](p \\wedge q) \\leftrightarrow  [a] p \\wedge [a]q)$   & unknown   & 60,000 ms \\\\\nBook formula 2 & $\\neg ([a;b]p  \\leftrightarrow  [a][b]p)$  & unknown   & 60,000 ms \\\\\nBook formula 3 & $\\neg ([\\textit{if }p\\textit{ then }a\\textit{ else }b]p  \\leftrightarrow  [\\textit{if }\\neg  p\\textit{ then }b\\textit{ else }a]p)$  & unknown   & 60,000 ms \\\\\n\t\nDeductive system 2 & $\\neg ([a](p \\rightarrow  q) \\rightarrow  ([a]p \\rightarrow  [a]q))$  & unsat & 100 ms \\\\\n\t\nDeductive system 3 & $\\neg ([a](p \\wedge q) \\rightarrow  ([a]p \\wedge [a]q))$  & unknown   & 60,000 ms \\\\\n\t\nDeductive system 4 & $\\neg ([a \\cup b]p  \\leftrightarrow  [a]p \\wedge [b]p)$  & unknown   & 60,000 ms \\\\\n\t\nDeductive system 5 & $\\neg ([a;b]p  \\leftrightarrow  [a][b]p)$  & unknown   & 60,000 ms \\\\\n\t\nDeductive system 6 & $\\neg ([q?]p  \\leftrightarrow  (q \\rightarrow  p))$  & unsat  & 77 ms \\\\\n\t\nDeductive system 7 & $\\neg (p \\wedge [a][a^{*}] p  \\leftrightarrow  [a^{*}]p)$  & unknown   & 60,000 ms \\\\\n\t\nDeductive system 8 & $\\neg (p \\wedge [a^{*}](p \\rightarrow  [a]p) \\rightarrow  [a^{*}]p)$  & unknown   & 60,000 ms \\\\\n\t\nDeductive system 9 MP & $\\neg ((p \\wedge (p \\rightarrow  q)) \\rightarrow  q)$  & unsat  & 73 ms \\\\\n\t\n\nTheorem 6.1 & $\\neg ( \\langle  a \\rangle  (p \\vee q)  \\leftrightarrow   \\langle  a \\rangle  p \\vee  \\langle  a \\rangle  q)$  & unsat & 90 ms \\\\\n\t\n\nTheorem 6.2 & $\\neg ([a](p \\wedge q)  \\leftrightarrow  [a]p \\wedge [a]q)$  & unknown   & 60,000 ms \\\\\n\t\n\nTheorem 6.3 & $\\neg ( \\langle  a \\rangle  p \\wedge [a] q \\rightarrow   \\langle  a \\rangle  (p \\wedge q))$  & unsat & 78 ms \\\\\n\t\n\nTheorem 6.4 & $\\neg ([a](p \\rightarrow  q) \\rightarrow  ([a]p \\rightarrow  [a] q))$  & unsat & 99 ms \\\\\n\t\n\nTheorem 6.5 & $\\neg ( \\langle  a \\rangle  (p \\wedge q) \\rightarrow   \\langle  a \\rangle   p \\wedge  \\langle  a \\rangle   q)$  & unsat & 67 ms \\\\\n\t\n\nTheorem 6.6 & $\\neg ([a]p \\vee [a] q \\rightarrow  [a] (p \\vee q))$  & unknown   & 60,000 ms \\\\\n\t\n\nTheorem 6.7 & $\\neg ( \\langle  a \\rangle   0  \\leftrightarrow  0)$  & unsat & 57 ms \\\\\n\t\n\nTheorem 6.8 & $\\neg ([a]p  \\leftrightarrow  \\neg   \\langle  a \\rangle   \\neg  p)$  & unsat & 95 ms \\\\\n\t\n\nTheorem 8.1 & $\\neg ( \\langle  a \\cup b \\rangle   p  \\leftrightarrow   \\langle  a \\rangle   p \\vee  \\langle  b \\rangle   p)$  & unsat & 82 ms \\\\\n\t\n\nTheorem 8.2 & $\\neg ([a \\cup b] p  \\leftrightarrow  [a] p \\wedge [b] p)$  & unknown   & 60,000 ms \\\\\n\t\n\nTheorem 10.1 & $\\neg ( \\langle  a ; b \\rangle   p  \\leftrightarrow   \\langle  a \\rangle   \\langle  b \\rangle   p)$  & unsat  & 93 ms  \\\\\n\t\n\nTheorem 10.2 & $\\neg ([a ; b] p  \\leftrightarrow  [a][b] p)$  & unknown   & 60,000 ms \\\\\n\t\n\nTheorem 11.1 & $\\neg ( \\langle  p? \\rangle   q  \\leftrightarrow  p \\wedge q)$  & unsat & 82 ms \\\\\n\t\n\nTheorem 11.2 & $\\neg ([p?] q  \\leftrightarrow  (p \\rightarrow  q))$  & unsat & 82 ms \\\\\n\t\n\nTheorem 12.1 & $\\neg ([p?] q  \\leftrightarrow  (p \\rightarrow  q))$  & unsat  & 80 ms \\\\\n\t\n\nTheorem 15.1 & $\\neg ([a^{*}]p \\rightarrow  p)$  & unsat  & 66 ms \\\\\n\t\n\nTheorem 15.2 & $\\neg (p \\rightarrow   \\langle  a^{*} \\rangle   p)$  & unsat & 68 ms \\\\\n\t\n\nTheorem 15.3 & $\\neg ([a^{*}]p \\rightarrow  [a]p)$  & unsat & 74 ms \\\\\n\t\n\nTheorem 15.4 & $\\neg ( \\langle  a \\rangle  p \\rightarrow   \\langle  a^{*} \\rangle  p)$  & unsat  & 71 ms \\\\\n\t\n\nTheorem 15.5 & $\\neg ([a^{*}]p  \\leftrightarrow  [a^{*};a^{*}]p)$  & unsat &  1,200 ms\\\\\n\t\n\nTheorem 15.6 & $\\neg ( \\langle  a^{*} \\rangle  p  \\leftrightarrow   \\langle  a^{*};a^{*} \\rangle  p)$  & unsat & 109ms \\\\\n\t\n\nTheorem 15.7 & $\\neg ([a^{*}]p  \\leftrightarrow  [(a^*)^*]p)$  & unknown   & 60,000 ms \\\\\n\t\n\nTheorem 15.8 & $\\neg ( \\langle  a^{*} \\rangle  p  \\leftrightarrow   \\langle  (a^*)^* \\rangle  p)$  & unknown   & 60,000 ms \\\\\n\t\n\nTheorem 15.9 & $\\neg ([a^{*}]p  \\leftrightarrow  p \\wedge [a][a^{*}]p)$  & unknown   & 60,000 ms \\\\\n\t\n\nTheorem 15.10 & $\\neg ( \\langle  a^{*} \\rangle  p  \\leftrightarrow  p \\vee  \\langle  a \\rangle   \\langle  a^{*} \\rangle  p)$  & unknown   & 60,000 ms \\\\\n\t\n\nTheorem 15.11 & $\\neg ([a^{*}]p  \\leftrightarrow  p \\wedge [a^{*}](p \\rightarrow  [a]p))$  & unknown   & 60,000 ms \\\\\n\t\n\nTheorem 15.12 & $\\neg ( \\langle  a^{*} \\rangle  p  \\leftrightarrow  p \\vee  \\langle  a^{*} \\rangle  (\\neg  p \\wedge  \\langle  a \\rangle  p))$  & unknown   & 60,000 ms \\\\\ntheorem 13.1 & $\\neg (p \\rightarrow  [a] \\langle  a^{\\_} \\rangle  p)$  & unsat & 375 ms \\\\\ntheorem 13.2 & $\\neg (p \\rightarrow  [a^{\\_}] \\langle  a \\rangle  p)$  & unsat & 73 ms \\\\\ntheorem 13.3 & $\\neg ( \\langle  a \\rangle  [a^{\\_}]p \\rightarrow  p)$  & unsat & 79 ms \\\\\ntheorem 13.4 & $\\neg ( \\langle  a^{\\_} \\rangle  [a]p \\rightarrow  p)$  & unsat & 74 ms \\\\  \n\\bottomrule \n\\end{tabular}\n\\caption{PDL solver results for 5 valid formulas in chapter 5 with  1 minute timeout.}\n\\label{tab:benchmark}\n\\end{table}\n\n\\bibliographystyle{plain}\n\n\\bibliography{references}\n\n\\end{document}\n", "meta": {"hexsha": "0cb1b7a622a01902cf22e694565826f84e83c84e", "size": 21114, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/report.tex", "max_stars_repo_name": "mudathirmahgoub/pdl", "max_stars_repo_head_hexsha": "8dfaeb438e2fbc9de18fa0299e492adac0f269ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "report/report.tex", "max_issues_repo_name": "mudathirmahgoub/pdl", "max_issues_repo_head_hexsha": "8dfaeb438e2fbc9de18fa0299e492adac0f269ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/report.tex", "max_forks_repo_name": "mudathirmahgoub/pdl", "max_forks_repo_head_hexsha": "8dfaeb438e2fbc9de18fa0299e492adac0f269ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.1023255814, "max_line_length": 803, "alphanum_fraction": 0.6637775883, "num_tokens": 7421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.542863297964157, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3093520897003085}}
{"text": "%%\n%% pytorch-neural-doodle/docs/content/chapters/introduction.tex\n%%\n%% Created by Paul Warkentin <paul@warkentin.email> on 21/08/2018.\n%% Updated by Bastian Boll <mail@bbboll.com> on 03/10/2018.\n%%\n\n\\section{Introduction}\n\\label{section:introduction}\n\n\\textbf{by Bastian Boll} \\\\\n\nIn light of meaningful advances in the field of image classification using convolutional neural networks (CNNs) \\cite{vgg2014}, interest has been sparked to exploit the inverse process for image generation. Because the intrinsic dimension of the input image space \\(I\\) is generally much larger than the intrinsic dimension of the label space \\(L\\), such a CNN cannot canonically be a bijective mapping. The inverse process can therefore be seen as selecting an element \\(x\\) of the preimage \\(\\mathrm{CNN}^{-1}(y)\\) for a fixed label \\(y\\in L\\) such that a measure of visual or artistic appeal is maximized.\n\nFor the purpose of a more fine-grained analysis of this process, suppose a given network which is discriminatively trained for object classification. Let \\(L_i\\) denote the feature space of said network at layer \\(i\\). The network can be characterized as functions \\(\\text{net}_i\\colon I \\to L_i\\) which encode a given input image into the feature space \\(L_i\\). Sampling the preimage \\(\\text{net}_i^{-1}(y_i)\\) of a given feature vector \\(y_i\\in L_i\\) can serve to visuallize the way in which such networks extract features from the input image. One can observe that the lower levels of the network capture mostly local texture information while higher levels encode more abstract information about the objects visible in the input image.\n\n% MAYBE: Leveraging encoding into these feature spaces for style transfer requires the combination of two general fields of expertise: style / texture and content.\n\nIn texture generation, a related area of research, efforts have been made to characterize texture as image statistics \\cite{julesz1962visual,heeger1995pyramid,rosenholtz2012summary}. Given a textured image, one can generate a different image which human observers percept to contain the same texture. This is done by looking for an image that reproduces the respective image statistics. However, careful hand-crafting of such image statistics is inherently limited and the results still fall short of being able to reproduce the full range of natural texture. In 2015, Gatys et al. \\cite{gatys2015texture} proposed using the feature encoding in lower levels of a VGG19 network \\cite{vgg2014} to provide the image statistics needed to capture texture. This particular architecture is especially well suited for generative tasks, as it does not aggressively optimize feature representation for the purpose of classification \\cite{nikulin2016exploring}. Training the network to classify objects also results in functions \\(\\text{net}_i\\) which encode low level image statistics such as texture. This new approach has had a large impact on the still young field of texture synthesis.\n\n% TODO: reference to early visual system as motivation for the following\n\nIn the same year, Gatys et al. also introduced a precise formulation of artistic style transfer as reproducing a given content image using texture from a different style image \\cite{gatys2015neural}. They achieve very convincing results by constructing an image which reproduces the low level texture statistics of the style image while also reproducing higher level statistics of the content image. \nThis requires an optimization process during which a target image is constructed to minimize a combined style- and content loss function.\nLet \\(p\\) denote the original (content) image and \\(x\\) denote the target image to be generated. \nConsider the activations \\(P^i\\in \\R^{M_i\\times N_i}\\) and \\(F^i\\in \\R^{M_i\\times N_i}\\) at layer \\(i\\) of the VGG network for the original image \\(p\\) and the target image \\(x\\) respectively.\nThe content loss is defined by Gatys et al. as a simple mean squared error loss between the activations of the content image and the target image.\n\\[\\mathcal{L}_\\text{c}(p,x,i) = \\frac{1}{2}\\sum_{j,k} (F^i_{jk}-P^i_{jk})^2\\]\nOn the other hand the style loss as described in \\cite{gatys2015texture} requires further preparation. We define Gram matrices \\(G^i\\in \\R^{M_i\\times M_i}\\) through\n\\[G^i_{jk} = \\sum_n F^i_{jn}F^i_{kn}\\]\nand set the style loss to be \n\\[\\mathcal{L}_\\text{s} = \\sum_i \\frac{w_i}{M_i^2N_i^2} \\sum_{jk} (G^i_{jk}-\\hat G^i_{jk})^2\\]\nHere, \\(G^i\\) refers to the Gram matrix computed from the activations of the target image and \\(\\hat G^i\\) to those for the style image. The weights \\(w_i\\) are adjusted to pronounce activations in lower network layers. In practice, many of these weights will be set to zero in order to save computational effort.\n\nInvestigating the motivation behind the Gram matrix representation and loss function construction\\footnote{This is detailed in a supplementary blog post to the paper \\cite{ulyanov2016texture}: \\url{https://dmitryulyanov.github.io/feed-forward-neural-doodle/}}, one can assume the activations \\(F^i\\) to follow an unknown true distribution \\(P\\). Choosing a Gaussian distribution with zero mean \\(Q\\sim \\mathcal{N}(0,\\Sigma)\\) as a model, we can compute the information projection\n\\[\\Sigma^\\ast = \\arg\\min_\\Sigma \\text{KL}(P||Q)\\]\nwhere \\(\\text{KL}(\\cdot)\\) denotes the Kullback-Leibler divergence. This in turn yields the solution\n\\[\\Sigma^\\ast = \\mathbb{E}_{x\\sim P} \\,x^Tx\\]\nBecause the true distribution \\(P\\) is not obtainable, we instead fit \\(Q\\) to the data by replacing the above with the empirical covariance and obtain\n\\[\\Sigma^\\ast \\approx \\frac{1}{MN} \\sum_{jk} G_{jk}\\]\nfor the respective layer of the network. In fact, Gatys et al. use a slightly different normalization constant, but we find this derivation to be more convincing.\n\nChoosing a weighting factor \\(\\alpha\\) yields the full loss function for artistic style transfer as \n\\[\\mathcal{L} = \\mathcal{L}_\\text{c}+\\alpha \\mathcal{L}_\\text{s}\\]\n\nBecause the Gram matrices describe global correlations between feature activations as detailed above, they do not retain local features of the texture at hand. This presents a problem for artistic style transfer, as local glitches in the generated image can hardly be addressed. As an alternative approach, one can define a patch based style loss function \\cite{mrf2016} which respects local pixel statistics. Let \\(\\Psi(x)\\) denote the list of all \\(k\\times k\\) patches of the activations for the input image \\(x\\) at a given layer of the network. We can define a style loss function as\n\\[\\mathcal{L}_{s,p}(x,p) = \\sum_i \\|\\Psi_i(x)-\\Psi_{\\text{NN}(i)}(p)\\|_2^2\\]\nwhere \\(\\text{NN}(i)\\) refers to the index of the nearest neighbour patch of \\(\\Psi_i(x)\\) in the set of patches \\(\\Psi(p)\\) with respect to normalized cross-correlation\n\\[\\text{NN}(i) = \\arg\\min_{j} \\frac{\\Psi_i(x)\\cdot \\Psi_j(p)}{\\|\\Psi_i(x)\\|\\|\\Psi_j(p)\\|}\\]\nUsing a patch-based style loss reduces the overall number of glitches in the generated image, as the algorithm respects local pixel statistics and is not exclusively guided by global correlations.\n\nHaving defined and explored the problem domain of artistic style transfer, subsequent work focuses on more practical and artistic aspects. While the number of glitches can and should be reduced by the means described above, one can certainly see the point of wanting to interact with the algorithm at work. Opening up hooks for interactive input from a user can potentially turn this algorithm into an artistic tool which can be led by human intuition. In this vein, Champandard proposes using semantic segmentation maps of both input style and content images \\cite{doodles2016}. The following main part of the present paper focuses on how to implement this approach.\n", "meta": {"hexsha": "07d193ef1631a86b2b9a597f03cf14f7a11fe199", "size": 7761, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/content/chapters/01_introduction.tex", "max_stars_repo_name": "paulwarkentin/pytorch-neural-doodle", "max_stars_repo_head_hexsha": "4b0c8da17351ef1662a0ce0bf5979027bafb130e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2018-10-07T14:54:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-09T11:22:14.000Z", "max_issues_repo_path": "docs/content/chapters/01_introduction.tex", "max_issues_repo_name": "paulwarkentin/pytorch-neural-doodle", "max_issues_repo_head_hexsha": "4b0c8da17351ef1662a0ce0bf5979027bafb130e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/content/chapters/01_introduction.tex", "max_forks_repo_name": "paulwarkentin/pytorch-neural-doodle", "max_forks_repo_head_hexsha": "4b0c8da17351ef1662a0ce0bf5979027bafb130e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-05-31T19:27:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-08T15:02:12.000Z", "avg_line_length": 146.4339622642, "max_line_length": 1179, "alphanum_fraction": 0.773611648, "num_tokens": 1882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.30935208127124647}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n%  problems remaining:\n%  #  why the z-vector equation only solved once? we do not need to solve 3N\n%      equations?\n%\n%\n%\n%\n%\n%\n\n\n\n\\chapter{Configuration Interaction Singles Method}\n%\n%\n%\n%\nIn the configuration interaction method, the most easiest way is to just take\nthe first excitation states into consideration. Such method is called\n``Configuration Interaction Singles Method'', so it's abbreviated as\n``CIS'' method.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{CIS Formulation}\n%\n%\n%\n%\nFirstly, let's go to investigate the formulation to calculate the CIS\nenergy. In the first step, we will only consider the restricted type\nof determinants so that to make things easier. \n\nSuggest we have $n$ occupied MOs, and the electrons are $2n$; then the\nground state Slater determinant is:\n\\begin{equation}\n  \\label{eq:CISeq:1}\n  \\Phi_{HF} =  |\\varphi_{1}(1)\\alpha(1)\\varphi_{1}(2)\\beta(2)\\cdots\n\\varphi_{n-1}(2n-1)\\alpha(2n-1)\\varphi_{n}(2n)\\beta(2n)|  \n\\end{equation}\n\nIt's energy is:\n\\begin{multline}\\label{CISeq:2}\n% \\nonumber to remove numbering (before each equation)\n  E\n  =\\sum_{i}^{occ}\\langle\\varphi_{i}(1)|\\hat{h}_{1}|\\varphi_{i}(1)\\rangle\n  +  \\\\\n  \\sum_{i < j}^{occ} \\left\\{\n    2\\langle\\varphi_{i}(1)\\varphi_{j}(2)|\\frac{1}{r_{12}}|\\varphi_{i}(1)\\varphi_{j}(2)\\rangle-\n    \\langle\\varphi_{i}(1)\\varphi_{j}(2)|\\frac{1}{r_{12}}|\\varphi_{j}(1)\\varphi_{i}(2)\\rangle\n  \\right\\}\n\\end{multline}\n\nMore specifically, the energy for the orbital is (here we suppose that\nthe orbital is in $\\alpha$ spin state):\n\\begin{eqnarray}\\label{CISeq:3}\n% \\nonumber to remove numbering (before each equation)\n  \\epsilon_{i} &=&  \\langle \\varphi_{i}| \\hat{F} | \\varphi_{i} \\rangle \\nonumber \\\\\n  &=& \\langle i|h|i \\rangle + \\sum_{j \\neq i} \\left\\{\n    2[ii|jj] - [ij|ij]\n  \\right\\}\n\\end{eqnarray}\nThis is for the occupied orbital, so we have to specify that $j \\neq\ni$. For the virtual orbital, it's energy is:\n\\begin{eqnarray}\\label{CISeq:4}\n% \\nonumber to remove numbering (before each equation)\n  \\epsilon_{a} &=&  \\langle \\varphi_{a}| \\hat{F} | \\varphi_{a} \\rangle \\nonumber \\\\\n  &=& \\langle a|h|a \\rangle + \\sum_{j}^{occ} \\left\\{\n    2[aa|jj] - [aj|aj]\n  \\right\\}\n\\end{eqnarray}\nHere we note that we use a, b, c etc. to designate the virtual\norbitals, the i, j, k etc. to refer to the occupied orbitals; and p,\nq, r etc. to specify the general orbitals.\n\nNow through the HF calculation, we have gotten $n$ occupied orbitals\nand another $m$ virtual orbitals ($n+m$ is the number of basis\nsets). The next question is, how to form the single excitation states\nfrom HF orbitals?\n\nIn this process, an electron from the occupied orbital is ``fired up''\ninto some virtual orbitals, so that to form some new determinant. Then\nthe new Slater determinant can be expressed as:\n\\begin{equation}\n    \\label{eq:CISeq:5}\n  \\Phi_{i}^{a} =  |\\cdots\\varphi_{a}(k)\\alpha(k)\\varphi_{i}(k+1)\\beta(k+1)\\cdots\n\\varphi_{n-1}(2n-1)\\alpha(2n-1)\\varphi_{n}(2n)\\beta(2n)|  \n\\end{equation}\nHere the electron $k$ with spin state of $\\alpha$ is excited into the\nvirtual orbital $\\varphi_{a}$, so we use the $\\varphi_{a}$ to replace\nthe original $\\varphi_{i}$ in the $\\alpha$ spin state (see the picture\nof \\ref{ris_pic}). \n\\begin{figure}[htbp]\n\\begin{center}\n\\includegraphics[scale=0.3]{ris1.eps}\\label{ris_pic}\n\\caption{single excitation state}\n\\end{center}\n\\end{figure}\n\nBy such configuration method, actually we can form $n\\times m$ Slater\ndeterminants. Then the trial wave function can be expressed as their\nlinear combinations:\n\\begin{equation}\n  \\label{CISeq:6}\n  \\Psi = \\sum_{i}^{occ}\\sum_{a}^{vir}C_{i}^{a}\\Phi_{i}^{a}\n\\end{equation}\n\nHere there are two points should be clarified. Firstly, we note that\nin the expression of (\\ref{CISeq:6}) the root determinant (ground\nstate determinant) is not included. Why?\n\nThis reason for this is from Brillouin theorem, which has been\ndemonstrated in the above content. The Brillouin theorem says that the\nHF determinant is unable to mix with the single excitation states, so\nthere's no coupling between them. If we include the HF determinant\ninto the expression of (\\ref{CISeq:6}), the Hamiltonian matrix will be\njust like the form below:\n\\begin{equation}\n  \\label{CISeq:7}\n  \\begin{bmatrix}\n    \\langle\\Phi_{HF}|\\hat{H}|\\Phi_{HF}\\rangle & 0  \\cdots & \\cdots \\\\\n    0 & \\langle \\Phi_{i}^{a}|\\hat{H}|\\Phi_{i}^{a} \\rangle & \\cdots \\\\\n    \\cdots & \\langle \\Phi_{i}^{a}|\\hat{H}|\\Phi_{i}^{a} \\rangle & \\cdots \\\\\n  \\end{bmatrix}\n\\end{equation}\nHere we can see that the first column and first low are all zero\nexcept the $\\langle\\Phi_{HF}|\\hat{H}|\\Phi_{HF}\\rangle$, hence it's no\nuse to put the $\\Phi_{HF}$ into the (\\ref{CISeq:6}). \n\nSecondly, we should pay attention to the spin state for each trial\nwave function. Actually there are many potential spin states for the\ntrial wave function, take $H_{2}$ molecule (close shell molecule) as\nan example, it's excitation states may be singlet ($S = 0$), or\ntriplet (S = 1). As what we have said in section \\ref{SIC4}, only the\nsame spin state determinant can mix together so that to form some\ntrial wave function of $\\Psi$:\n\\begin{align}\n  \\label{CISeq:8}\n\\Psi_{single} &= \\sum_{i}\\sum_{a}C_{i}^{a}\\Phi_{single} \\nonumber \\\\\n\\Psi_{triplet} &= \\sum_{i}\\sum_{a}C_{i}^{a}\\Phi_{triplet}  \n\\end{align}\nThat's what I want to say, however; so far we do not take spin into\naccount so to avoid adding complicity into our consideration.\n\nOn the other hand, we note that the forming method for the Slater\ndeterminant can also varied. It can also be unrestricted method, so\nthe $\\alpha$ electrons and $\\beta$ electrons are not arranging into\nthe same spatial orbitals space. However, just as what we have\ndemonstrated, there are spin contamination situation in the\nunrestricted method, so this method is not reliable.\n\nFinally let's take the trial wave function in (\\ref{CISeq:6}) into the\nSchroedinger equation:\n\\begin{equation}\n  \\label{CISeq:9}\n  \\sum_{i}^{occ}\\sum_{a}^{vir}\\hat{H}|\\Phi_{i}^{a}\\rangle C_{i}^{a} = \nE_{CIS} \\sum_{i}^{occ}\\sum_{a}^{vir}C_{i}^{a}|\\Phi_{i}^{a}\\rangle\n\\end{equation}\nFor short, we abbreviate the $\\sum_{i}^{occ}\\sum_{a}^{vir}$ as\n$\\sum_{ia}$. Then we multiply $\\Phi_{j}^{b}$ to the above equation, it\nbecomes: \n\\begin{equation}\n  \\label{CISeq:10}\n \\sum_{ia}\\langle\\Phi_{j}^{b}|\\hat{H}|\\Phi_{i}^{a}\\rangle C_{i}^{a}\n = E_{CIS}\\sum_{ia}C_{i}^{a}\\delta_{ij}\\delta_{ab}\n\\end{equation}\nThat's the equation we finally get.\n\nNext, we have to know that how to evaluate the matrix element for the\nequation of (\\ref{CISeq:10}).\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Matrix element in CIS equation}\n\\label{sec:ME_CIS}\n%\n%\n%\n%\nFrom the (\\ref{CISeq:10}), it's easily to know that there are only\nfour type of matrix element:\n\\begin{itemize}\n\\item $\\langle\\Phi_{i}^{a}|\\hat{H}|\\Phi_{i}^{a}\\rangle$\n\\item $\\langle\\Phi_{i}^{a}|\\hat{H}|\\Phi_{j}^{a}\\rangle$, where $i \n\\neq j$\n\\item $\\langle\\Phi_{i}^{a}|\\hat{H}|\\Phi_{i}^{b}\\rangle$, where $a \n\\neq b$\n\\item $\\langle\\Phi_{i}^{a}|\\hat{H}|\\Phi_{j}^{b}\\rangle$, where $i \n\\neq j$, $a \\neq b$\n\\end{itemize}\n\nfirstly, let's calculate the\n$\\langle\\Phi_{i}^{a}|\\hat{H}|\\Phi_{i}^{a}\\rangle$. For simplicity, we\nassume that we are in open shell situation, and the electron on the\norbital $i$ is fired up into the orbital $a$; just as demonstrated in\nthe picture below:\n\n\nBased on the HF results, we can have:\n\\begin{align}\n\\label{CISeq:11}\n  \\langle\\Phi_{i}^{a}|\\hat{H}|\\Phi_{i}^{a}\\rangle &= \\sum_{k\\neq\n    i}^{occ} \\bra{\\varphi_{k}}\\hat{h}_{1}\\ket{\\varphi_{k}} - \n\\bra{\\varphi_{i}}\\hat{h}_{1}\\ket{\\varphi_{i}} + \n\\bra{\\varphi_{a}}\\hat{h}_{1}\\ket{\\varphi_{a}} \\nonumber \\\\\n&+ \\sum_{k<l}^{occ}\\left\\{2[kk|ll] - [kl|kl] \\right\\} - \n\\sum_{k \\neq i}^{occ}\\left\\{2[kk|ii] - [ki|ki] \\right\\} \\nonumber \\\\\n&+ \\sum_{k}^{occ}\\left\\{2[kk|aa] - [ka|ka] \\right\\} + \n\\left\\{2[aa|ii] - [ai|ai] \\right\\}\n\\end{align}\n\nFirstly we note that in the (\\ref{CISeq:11}) it's correspondent to\ntriplet, where the electrons on the orbital $i$ and orbital $a$ have\nthe same spin state. On the other hand, if it's the singlet state,\nthen the exchange term between orbital $i$ and orbital $a$ is\nnaturally vanished, and the other terms are kept.\n\nThen according to the expression for orbital energy in (\\ref{CISeq:3})\nand (\\ref{CISeq:4}), we can rewrite the whole expression as:\n\\begin{equation}\n  \\label{CISeq:12}\n    \\langle\\Phi_{i}^{a}|\\hat{H}|\\Phi_{i}^{a}\\rangle = \\Big\\{ E_{HF} +\n    \\varphi_{a} - \\varphi_{i}\\Big\\} + (ii||aa)\n\\end{equation}\nWhere the $(ii||aa)$ is abbreviated as:\n\\begin{equation}\n  (ii||aa) = \\int dr d r^{'}\n  \\frac{\\varphi_{i}^{*}(r)\\varphi_{i}(r)\\varphi_{a}^{*}(r^{'})\\varphi_{a}(r^{'})\n   - \\varphi_{i}^{*}(r)\\varphi_{a}(r)\\varphi_{a}^{*}(r^{'})\\varphi_{i}(r^{'})}\n  {|r-r^{'}|}\n\\end{equation}\n\nSecondly, let's go to see the term of\n$\\langle\\Phi_{i}^{a}|\\hat{H}|\\Phi_{j}^{a}\\rangle$ and\n$\\langle\\Phi_{i}^{a}|\\hat{H}|\\Phi_{i}^{b}\\rangle$. For the single\nelectron energy part, it's easily to show that it's zero; because we\ncan always find that some orbital in the bra can not find its\ncounterpart in the ket. For example, in the\n$\\langle\\Phi_{i}^{a}|\\hat{H}|\\Phi_{j}^{a}\\rangle$ if the alpha\nelectron is fired up from the orbital $i$ to the orbital $a$, then we\nstill have a beta electron leaving in the orbital $i$. Then it forms\nsome vacant position in orbital $i$ with alpha spin state. However, we\nhave the alpha electron in the orbital $i$ in the ket, but its\ncounterpart in bra is disappeared. \n\nFor the second electron energy part, the same situation holds. In most\nof case, no matte how we compose the pair of orbitals, such as\n$(ai||ka)$, it's turned out that in the rest of orbitals, there's\nalways has some orbital that can not find its counterpart so that the\nwhole integral goes zero. There's only one exception, which is the\nintegral between occupied-virtual orbital pairs; only this integral\nsurvives. Hence we can finally have:\n\\begin{align}\n  \\label{CISeq:13}\n  \\langle\\Phi_{i}^{a}|\\hat{H}|\\Phi_{j}^{a}\\rangle &= (aa||ij)\n  \\nonumber \\\\\n  \\langle\\Phi_{i}^{a}|\\hat{H}|\\Phi_{i}^{b}\\rangle &= (ab||ii) \n\\end{align}\n \nFinally, for the $\\langle\\Phi_{i}^{a}|\\hat{H}|\\Phi_{j}^{b}\\rangle$,\nsimilarly we only have the $(ij||ab)$ integral does not go zero. So it\ncan be expressed as:\n\\begin{equation}\n  \\label{CISeq:14}\n  \\langle\\Phi_{i}^{a}|\\hat{H}|\\Phi_{j}^{b}\\rangle = (ab||ij)\n\\end{equation}\n\nAll in all, combined the results in the (\\ref{CISeq:12}),\n(\\ref{CISeq:13}) and (\\ref{CISeq:14}), we can have the matrix element\nin the CIS equation expressed as:\n\\begin{equation}\n  \\label{CISeq:15}\n  \\langle\\Phi_{i}^{a}|\\hat{H}|\\Phi_{j}^{b}\\rangle = \\Big\\{ E_{HF} +\n    \\varphi_{a} - \\varphi_{i}\\Big\\}\\delta_{ij}\\delta_{ab} + (ab||ij)\n\\end{equation}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{CIS Equation}\n\\label{sec:CIS_solution}\n%\n%\n%\n%\n%\nNow let's take the (\\ref{CISeq:15}) into the general form of\n(\\ref{CISeq:10}), we can have:\n\\begin{align}\n \\label{CISeq:16}\n \\sum_{ia}\\langle\\Phi_{j}^{b}\n\\left\\lbrace (\\varphi_{a} - \\varphi_{i})\\delta_{ij}\\delta_{ab} +\n(ab||ij)\\right\\rbrace  C_{i}^{a}\n &=  \\sum_{ia}(E_{CIS} -E_{HF})C_{i}^{a}\\delta_{ij}\\delta_{ab}\n\\nonumber \\\\\n\\left\\lbrace\n(\\varphi_{a} - \\varphi_{i})\\delta_{ij}\\delta_{ab} +\n(ab||ij)\\right\\rbrace  C_{i}^{a} &= \\sum_{ia}\\omega\nC_{i}^{a}\\delta_{ij}\\delta_{ab} \n\\end{align}\nHere, $\\omega$ is the $E_{CIS} -E_{HF}$ which just characterizes the\nexcitation energy.\n\nNow we have to enter into the coding procedure, so how can we code\nthe CIS equation?\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{The Analytical Gradient for CIS Equation}\n%\n%\n%\n%\nNow let's step into the gradient of CIS equation. For the expression in\n(\\ref{CISeq:16}), we have:\n\\begin{align}\n \\label{CIS_gradient:1}\n\\omega &= \\sum_{ai}\\sum_{bj}X_{ai}A_{ai,bj}X_{bj} \n\\end{align}\nWhere \n\\begin{equation}\n A_{ai,bj} = (\\epsilon_{a} - \\epsilon_{i})\\delta_{ij}\\delta_{ab} +\n(ai||bj)\n\\end{equation}\nAccording to the Winger's theorem, for the gradient expression the variational\nparameters does not go into it so that we have:\n\\begin{align}\n\\label{CIS_gradient:2}\n \\omega^{[x]} &= \\sum_{ai}\\sum_{bj}X_{ai}A^{[x]}_{ai,bj}X_{bj} \\nonumber \\\\\n&=   \\sum_{ai}\\sum_{bj}X_{ai} \\left\\lbrace( \\epsilon^{[x]}_{a} -\n\\epsilon^{[x]}_{i})\\delta_{ij}\\delta_{ab} +\n(ai||bj)^{[x]}\\right\\rbrace X_{bj}\n\\end{align}\nGiving by (\\ref{CPHF_hf_derivatives_eq:10}), which is:\n\\begin{align}\n  \\label{CIS_gradient:3}\n  \\epsilon^{[x]} &= F_{pp}^{[x]} = H^{x}_{pp} + \\sum_{k}^{occ}\\left\n\\{\\Pi^{x}_{ppkk} -\n    \\Pi^{x}_{pkkp} \\right\\}\n  \\nonumber \\\\\n  &- S^{x}_{pp}\\epsilon_{p} - \\sum_{k}^{occ}\\sum_{t}^{occ}S^{x}_{kt}\n  \\left\\{ \\Pi_{pptk} - \\Pi_{ptkp} \\right\\} \\nonumber \\\\\n  &+ \\sum_{k}^{occ}\\sum_{t}^{vir}U^{x}_{tk}\\left\\{ 2\\Pi_{pptk} -\n    \\Pi_{ptkp} - \\Pi_{pktp} \\right\\} \\nonumber \\\\\n&= F^{x}_{pp} - S^{x}_{pp}\\epsilon_{p}\n - \\sum_{k}^{occ}\\sum_{t}^{occ}S^{x}_{kt}(pp||tk) \\nonumber \\\\\n&+2\\sum_{k}^{occ}\\sum_{t}^{vir}U^{x}_{tk}(pp||tk) \n\\end{align}\nWhere the $F^{x}_{pp} $ is given as:\n\\begin{equation}\n \\label{CIS_gradient:10}\nF^{x}_{pp} = H^{x}_{pp} + \\sum_{k}^{occ}(pp||kk)^{x}\n\\end{equation}\n$p$ is referred to some general orbital.  For the $\\epsilon^{[x]}_{a} -\n\\epsilon^{[x]}_{i}$, given by the above expression it is:\n\\begin{equation}\n \\begin{split}\n\\epsilon^{[x]}_{a} - \\epsilon^{[x]}_{i} &=  (F^{x}_{aa} -\nF^{x}_{ii}) +\n(S^{x}_{ii}\\epsilon_{i} - S^{x}_{aa}\\epsilon_{a})  \\\\\n&+\\sum_{k}^{occ}\\sum_{l}^{occ}S_{kl}^{x}[(ii||lk) -\n(aa||lk)] +  2\\sum_{k}^{occ}\\sum_{c}^{vir}U_{ck}[(aa||ck) - (ii||ck)]\n \\end{split}\n\\label{CIS_gradient:11}\n\\end{equation}\n\nAs for the gradient expression for $(ai||bj)$ in\n(\\ref{two_electron_MO_INT_gradient_eq:1}), which is:\n\\begin{align}\n \\label{CIS_gradient:4}\n(ai||bj)^{[x]} &= (ai|bj)^{[x]} - (ab|ij)^{[x]} \\nonumber \\\\\n&= \\sum_{t}\\left[ \nU_{ta}(ti|bj) +\nU_{ti}(at|bj) + \nU_{tb}(ai|tj) + \nU_{tj}(ai|bt)  \n\\right] + (ai|bj)^{x} \\nonumber \\\\\n&-\n\\sum_{t}\\left[ \nU_{ta}(tb|ij) +\nU_{tb}(at|ij) + \nU_{ti}(ab|tj) + \nU_{tj}(ab|it)  \n\\right] - (ab|ij)^{x} \n%\\nonumber \\\\\n%&= \\sum_{t}\\left[ \n%U_{ta}(ti||bj) +\n%U_{ti}(at||bj) + \n%U_{tb}(ai||tj) + \n%U_{tj}(ai||bt)  \n%\\right] + (ai||bj)^{x}\n\\end{align}\nSince in section of \\ref{CPHF} we have derived the fact that within HF\nframework, for the orbital response matrix of $U$ only $U_{occ, vir}$ and\n$U_{vir, occ}$ exist, the $U_{occ,occ}$ and $U_{vir, vir}$ blocks are zero.\nHence we can safely set the $U_{occ,occ}$ and $U_{vir, vir}$ to zero, so the\n(\\ref{CIS_gradient:4}) can be transformed into:\n\\begin{equation}\n\\begin{split}\n(ai||bj)^{[x]} &=\n\\sum_{k}^{occ}\\left\\{ U_{ka}\\left[(ki|bj) - (kb|ij)\\right] \\right\\} +\n\\sum_{c}^{vir}\\left\\{ U_{ci}\\left[(ac|bj) - (ab|cj)\\right] \\right\\} \\nonumber\n\\\\\n&+\\sum_{k}^{occ}\\left\\{ U_{kb}\\left[(ai|kj)-(ak|ij)\\right] \\right\\} +\n\\sum_{c}^{vir}\\left\\{ U_{cj}\\left[(ai|bc)  - (ab|ic)\\right] \\right\\} \n\\nonumber \\\\\n&+  (ai|bj)^{x} - (ab|ij)^{x}\n\\end{split}\n \\label{CIS_gradient:12}\n\\end{equation}\nNow let's make some analysis. Since in the expression, the summation is over\nall the $i,j,a,b$ label, so actually we can see that:\n\\begin{align}\n\\sum_{abc}^{vir}\\sum_{i}^{occ}(ai|bc)  &= \\sum_{abc}^{vir}\\sum_{i}^{occ}(ab|ic)\n\\nonumber \\\\\n\\sum_{ijk}^{occ}\\sum_{b}^{occ}(ki|bj) &= \\sum_{ijk}^{occ}\\sum_{b}^{occ}(kb|ij)\n \\label{CIS_gradient:13}\n\\end{align}\nIn the first term, we only need to make $a\\leftrightarrow c$, and in the second\nterm to make $j \\leftrightarrow k$; then we can derive the equality relation. \n\nFinally the (\\ref{CIS_gradient:12}) becomes:\n\\begin{equation}\n \\begin{split}\n (ai||bj)^{[x]} &=\n  \\sum_{c}^{vir}\\left\\{ U_{ci}\\left[(ac|bj) - (ab|cj)\\right] \\right\\}\n+\\sum_{k}^{occ}\\left\\{ U_{kb}\\left[(ai|kj)-(ak|ij)\\right] \\right\\}  \\nonumber\n\\\\\n&+  (ai|bj)^{x} - (ab|ij)^{x} \n \\end{split}\n\\label{CIS_gradient:14}\n\\end{equation}\n\nFinally, we can see that the (\\ref{CIS_gradient:2}) becomes:\n\\begin{align}\n \\label{CIS_gradient:6}\n\\omega^{[x]} &= \\sum_{ai}\\sum_{bj}X_{ai}\\Bigg\\{\\Big[  (F^{x}_{aa} -\nF^{x}_{ii}) +\n(S^{x}_{ii}\\epsilon_{i} - S^{x}_{aa}\\epsilon_{a})  \\nonumber \\\\\n&+\\sum_{k}^{occ}\\sum_{l}^{occ}S_{kl}^{x}[(ii||kl) -\n(aa||kl)]\\Big]\\delta_{ij}\\delta_{ab} + (ai||bj)^{x} \\Bigg\\} X_{bj} \\nonumber\n\\\\\n&+\n\\sum_{ai}\\sum_{bj}X_{ai}\\Bigg\\{2\\delta_{ij}\\delta_{ab}\\sum_{k}^{occ}\\sum_{c}^{\nvir}U_{ck}[(aa||ck) - (ii||ck)]\\nonumber \\\\\n& +\\sum_{c}^{vir}\\left\\{ U_{ci}\\left[(ac|bj) - (ab|cj)\\right] \\right\\}\n+\\sum_{k}^{occ}\\left\\{ U_{kb}\\left[(ai|kj)-(ak|ij)\\right] \\right\\} \\Bigg\\}X_{bj}\n\\end{align}\nIn the expression of (\\ref{CIS_gradient:6}), there both has $U_{occ, vir}$\nand $U_{vir, occ}$ blocks, however; we can use the relation defined in\n(\\ref{overlap_MO_INT_gradient_eq:3}) to eliminate it:\n\\begin{align}\n \\label{CIS_gradient:7}\nU_{kb} &= -U_{bk} - S_{bk}^{x}\n\\end{align}\nThen the (\\ref{CIS_gradient:6}) becomes:\n\\begin{align}\n \\label{CIS_gradient:7}\n\\omega^{[x]} &= \\sum_{ai}\\sum_{bj}X_{ai}\\Bigg\\{\\Big[  (F^{x}_{aa} -\nF^{x}_{ii}) +\n(S^{x}_{ii}\\epsilon_{i} - S^{x}_{aa}\\epsilon_{a})  \\nonumber \\\\\n&+\\sum_{k}^{occ}\\sum_{l}^{occ}S_{kl}^{x}[(ii||kl) -\n(aa||kl)]\\Big]\\delta_{ij}\\delta_{ab} \\nonumber\n\\\\ \n& -\\sum_{k}^{occ}\\left\\{S^{x}_{bk}\\left[(ai|kj)-(ak|ij)\\right] \\right\\} +\n(ai||bj)^{x} \\Bigg\\} X_{bj} \n\\nonumber \\\\\n&+\n\\sum_{ai}\\sum_{bj}X_{ai}\\Bigg\\{2\\delta_{ij}\\delta_{ab}\\sum_{k}^{occ}\\sum_{c}^{\nvir}U_{ck}[(aa||ck) - (ii||ck)]\\nonumber \\\\\n&+\\sum_{c}^{vir}\\left\\{ U_{ci}\\left[(ac|bj) - (ab|cj)\\right] \\right\\}\n-\\sum_{k}^{occ}\\left\\{ U_{bk}\\left[(ai|kj)-(ak|ij)\\right] \\right\\} \\Bigg\\}X_{bj}\n\\end{align} \n\nNow we can abbreviate the term related to $U$ matrix as:\n\\begin{align} \n\\label{CIS_gradient:8}\n Y_{ck} &= 2\\sum_{ai}\\sum_{bj}X_{ai}X_{bj}\n\\delta_{ij}\\delta_{ab}[(aa||ck) - (ii||ck)]\\nonumber \\\\\n&+\\sum_{ab}\\sum_{j}X_{ak}X_{bj}\\left\\{\\left[(ac|bj)\n- (ab|cj)\\right] \\right\\} \\nonumber \\\\\n&-\\sum_{a}\\sum_{ij}X_{ai}X_{cj}\\left\\{\n\\left[(ai|kj)-(ak|ij)\\right] \\right\\} \n\\end{align}\n\nThen (\\ref{CIS_gradient:7}) becomes:\n\\begin{align}\n \\label{CIS_gradient:9}\n\\omega^{[x]} &=  \\sum_{ai}\\sum_{bj}X_{ai}\\Bigg\\{\\Big[  (F^{x}_{aa} -\nF^{x}_{ii}) +\n(S^{x}_{ii}\\epsilon_{i} - S^{x}_{aa}\\epsilon_{a})  \\nonumber \\\\\n&+\\sum_{k}^{occ}\\sum_{l}^{occ}S_{kl}^{x}[(ii||kl) -\n(aa||kl)]\\Big]\\delta_{ij}\\delta_{ab} \\nonumber\n\\\\ \n& -\\sum_{k}^{occ}\\left\\{S^{x}_{bk}\\left[(ai|kj)-(ak|ij)\\right] \\right\\} +\n(ai||bj)^{x} \\Bigg\\} X_{bj} \n\\nonumber \\\\\n&+\\sum_{c}^{vir}\\sum_{k}^{occ}U_{ck}Y_{ck}\n\\end{align}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Z-Vector Method}\n%\n%\n%\nNow the issue inside the (\\ref{CIS_gradient:9}) is that we have to solve the\n$U$ matrix so that to get the explicit derivative expression. By using the CPHF\nequation, which is shown in (\\ref{CPHF_hf_derivatives_eq:17}) and\n(\\ref{CPHF_hf_derivatives_eq:18}), we generally have:\n\\begin{equation}\n \\label{Zvector_CIS_eq:1}\nAU^{a} = B^{a}\\Leftrightarrow \\sum_{jb}A_{ij, ab}U^{a}_{bj} =\nB^{a}_{ia} \\Rightarrow AU = B\n\\end{equation}\nWhere matrix of $A$ is $(occ\\times vir)^{2}$ dimension, the U and $B$ are both\n$occ\\times vir$ dimension.\n\nFor the (\\ref{Zvector_CIS_eq:1}), it can be further expressed as:\n\\begin{equation}\n \\label{Zvector_CIS_eq:2}\nU = A^{-1}B\n\\end{equation}\nNow let's make a direct product between $U$ matrix and the $Y$ matrix defined\nin (\\ref{CIS_gradient:9}), combined with (\\ref{Zvector_CIS_eq:2}), it's (for\nmatching with the label in \\ref{CIS_gradient:8}, we use the label of $c,k$ etc.\nrather than $b,j$ etc.):\n\\begin{align}\n  \\label{Zvector_CIS_eq:3}\n\\sum_{c}^{vir}\\sum_{k}^{occ}U_{ck}Y_{ck} &=\n\\sum_{c}^{vir}\\sum_{d}^{vir}\\sum_{k}^{occ}\\sum_{l}^{occ}A_{kl,cd}^{-1}B^{a}_{ld}\nY_{ck} \\Rightarrow \\nonumber \\\\\n\\sum_{c}^{vir}\\sum_{k}^{occ}U_{ck}Y_{ck} &=\n\\sum_{d}^{vir}\\sum_{l}^{occ}Z_{dl}B^{a}_{ld}\n\\end{align}\nWhere the vector of $Z$ is given by:\n\\begin{equation}\n \\label{Zvector_CIS_eq:4}\nZ_{dl} = \\sum_{c}^{vir}\\sum_{k}^{occ}A_{kl,cd}^{-1}Y_{ck} \\Rightarrow\n\\sum_{d}^{vir}\\sum_{l}^{occ}A_{kl,cd}Z_{dl} = Y_{ck}\n\\end{equation}\n\nThe new vector of $Z$, compared with the MO rotation matrix of $U$, only has\nthe dimension of $occ*vir$ for all the perturbations; that means; the $Z$ vector \ncan be solved only once and used for all the $3\\times N$ atoms gradient\ncalculation. That's the advantages that why we solve the Z-vector rather than\nthe rotation matrix of $U$. \n\nNow let's expand the (\\ref{Zvector_CIS_eq:4}) into more detailed way:\n\\begin{equation}\n \\begin{split}\n&\\sum_{l}^{occ}\\sum_{d}^{vir}\\left\\lbrace   \\left(\\epsilon_{c} -\n\\epsilon_{k}\\right)\\delta_{kl}\\delta_{cd} + \\left[\n2(kc|dl) -(kd|lc) - (kl|dc) \\right] \\right\\rbrace Z_{dl} =  \\\\\n&2\\sum_{ai}\\sum_{bj}X_{ai}X_{bj}\n\\delta_{ij}\\delta_{ab}[(aa||ck) - (ii||ck)] \n+\\sum_{ab}\\sum_{j}X_{ak}X_{bj}\\left\\{\\left[(ac|bj)\n- (ab|cj)\\right] \\right\\}  \\\\\n&-\\sum_{a}\\sum_{ij}X_{ai}X_{cj}\\left\\{\n\\left[(ai|kj)-(ak|ij)\\right] \\right\\}\n \\end{split}\n \\label{Zvector_CIS_eq:5}\n\\end{equation}\n\nAfter getting the vector of $Z$, then we can get the gradient expression for CIS equation.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%% Local Variables: \n%%% mode: latex\n%%% TeX-master: \"../../main\"\n%%% End: \n\n\n", "meta": {"hexsha": "f58f94e00fd36323356c9307e1f2f917a46d7aa2", "size": 21018, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "theory/chemistry/cis.tex", "max_stars_repo_name": "murfreesboro/fenglai-note", "max_stars_repo_head_hexsha": "7bdf943f681e54948cd68775a31e4c93a53a13f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-16T07:23:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T07:23:48.000Z", "max_issues_repo_path": "theory/chemistry/cis.tex", "max_issues_repo_name": "murfreesboro/fenglai-note", "max_issues_repo_head_hexsha": "7bdf943f681e54948cd68775a31e4c93a53a13f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "theory/chemistry/cis.tex", "max_forks_repo_name": "murfreesboro/fenglai-note", "max_forks_repo_head_hexsha": "7bdf943f681e54948cd68775a31e4c93a53a13f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6806282723, "max_line_length": 94, "alphanum_fraction": 0.6437339423, "num_tokens": 7800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.30935208127124647}}
{"text": "\\documentclass[blue]{beamer}\n\\usepackage{etoolbox}\n\\mode<presentation>\n\n%\\usetheme{Warsaw}\n\n\\usepackage{paralist}\n  \\let\\itemize\\compactitem\n  \\let\\enditemize\\endcompactitem\n  \\let\\enumerate\\compactenum\n  \\let\\endenumerate\\endcompactenum\n  \\let\\description\\compactdesc\n  \\let\\enddescription\\endcompactdesc\n  \\pltopsep=\\medskipamount\n  \\plitemsep=1pt\n  \\plparsep=1pt\n\\usepackage[english]{babel}\n\n%/////////////////////////////////////////////////////////////////////////////\n% math pkgs\n\\usepackage{graphicx} % more modern\n\\usepackage{bbm, bm, amsmath, amssymb, amsthm, mathrsfs, booktabs,float}\n\\usepackage{color}\n\\usepackage{subfigure} \n% accent helper function\n\\usepackage{accents}\n\\DeclareMathSymbol{\\fixwidehatsym}{\\mathord}{largesymbols}{\"62}\n\\newcommand\\lowerwidehatsym{%\n  \\text{\\smash{\\raisebox{-1.3ex}{%\n    $\\fixwidehatsym$}}}}\n\\newcommand\\fixwidehat[1]{%\n  \\mathchoice\n    {\\accentset{\\displaystyle\\lowerwidehatsym}{#1}}\n    {\\accentset{\\textstyle\\lowerwidehatsym}{#1}}\n    {\\accentset{\\scriptstyle\\lowerwidehatsym}{#1}}\n    {\\accentset{\\scriptscriptstyle\\lowerwidehatsym}{#1}}\n}\n\n\n%/////////////////////////////////////////////////////////////////////////////\n% tikz\n\\usepackage{tikz}\n\\usetikzlibrary{arrows}\n\n\\newenvironment{figure*}%\n{\\begin{figure}}\n{\\end{figure}}\n\n\n%////////////////////////////////////////////////////////////////////\n%////////////////////////////////////////////////////////////////////\n\n\\title{Understanding Model Predictions via Influence Functions}\n\n\\subtitle{Statistical Machine Final Project}\n\n\\author{Ze Yang \\and Zhengyang Qi \\and Yundong Liu \\and Yuze Liu}\n\n\\institute[Carnegie Mellon University] % (optional, but mostly needed)\n{Carnegie Mellon University}\n% - Use the \\inst command only if there are several affiliations.\n% - Keep it simple, no one is interested in your street address.\n\n\\date{2018.05.05}\n\n% If you have a file called \"university-logo-filename.xxx\", where xxx\n% is a graphic format that can be processed by latex or pdflatex,\n% resp., then you can add a logo as follows:\n\n% \\pgfdeclareimage[height=0.5cm]{university-logo}{university-logo-filename}\n% \\logo{\\pgfuseimage{university-logo}}\n\n% Delete this, if you do not want the table of contents to pop up at\n% the beginning of each subsection:\n\\AtBeginSubsection[]\n{\n  \\begin{frame}<beamer>{Outline}\n    \\tableofcontents[currentsection,currentsubsection]\n  \\end{frame}\n}\n\n% Let's get started\n\\begin{document}\n\n\\begin{frame}\n  \\titlepage\n\\end{frame}\n\n\\begin{frame}{Outline}\n  \\tableofcontents\n  % You might wish to add the option [pausesections]\n\\end{frame}\n\n% Section and subsections will appear in the presentation overview\n% and table of contents.\n\\section{Backgrounds}\n\n\\subsection{Introduction}\n\n\\begin{frame}{Introduction}{}\n    \\begin{itemize}\n        \\item  In this project, we reproduced the \\emph{Best Paper} awardee of ICML 2017: \\textit{Understanding Black-box Predictions via Influence Functions}, by Koh \\& Liang.\n        \\item Our main topic is \\textbf{influence function}, a technique to trace a model’s prediction through the learning algorithm and back to its training data.\n        \\item  We carried out efficient implementations with \\texttt{Tensorflow}.\n        \\item We demonstrated its performance \\& applications on real-world datasets.\n        \n    \\end{itemize}\n\\end{frame}\n\n\\subsection{What is Influence Function?}\n\n\\begin{frame}{What is Influence Function: Some Definitions}{}\n  \\begin{itemize}\n  \\item \\textbf{Statistical Functional:} $T(F_Z)$, a functional maps from the space of population CDFs to a field (such as $\\mathbb{R}$). \n  \\item \\textbf{Risk Optimizer:} Idealy, minimizes EPE: A statistical functional.\n  $$\n  \\bm{\\theta}(\\fixwidehat{F}_Z)=\\underset{\\bm{\\theta} \\in \\Theta}{\\mathrm{argmin}}\\int\\mathcal{L}(\\bm{z},\\bm{\\theta})d\\fixwidehat{F}_Z\n  $$\n  \\item \\textbf{Empirical Risk Optimizer:} In reality, minimize empirical risk, a \\textit{plug-in} estimator to the risk optimizer.\n    $$\n  \\bm{\\theta}(\\fixwidehat{F}_Z)=\\underset{\\bm{\\theta} \\in \\Theta}{\\mathrm{argmin}}~\\frac{1}{n}\\sum_{i=1}^n\\mathcal{L}(\\bm{z}_i,\\bm{\\theta})\n  $$\n  \\end{itemize}\n\\end{frame}\n\n\\begin{frame}{What is Influence Function: G\\^ateaux Derivative}{}\n  \\textbf{G\\^ateaux Derivative} generalizes the idea of \\textbf{directional derivatives} - the inputs are CDFs!\n\\begin{align}\\label{gateaux}\n  \\mathcal{I}_{\\bm{\\theta}}(G) &:= \\nabla_{G} \\bm{\\theta}(F_Z)\\biggr\\rvert_{F_Z=F^*_Z} \\notag\\\\\n  &= \\underset{h \\to 0}{\\lim}\\frac{\\bm{\\theta}((1-h)F^*_Z + hG) - \\bm{\\theta}(F^*_Z)}{h}\n\\end{align}\nMeaning: the sensitivity of the statistical functional $\\bm{\\theta}(F_Z)$ with respect to ``mixing the CDF with a little bit $G$''.\n\\end{frame}\n\n\n\\begin{frame}{Empirical Influence Function}{}\nLet $\\hat{F}_Z$ be the empirical CDF; let the direction $G$ to be \"some probability mass\" at a training point $\\bm{z}_{tr}$.\n\\begin{align}\\label{empinfluence}\n  \\mathcal{I}_{\\fixwidehat{\\bm{\\theta}}}(\\bm{z}_{tr}) = \\underset{h \\to 0}{\\lim}\\frac{\\bm{\\theta}((1-h)\\fixwidehat{F}_Z+ h\\delta_{\\bm{z}_{tr}}) - \\bm{\\theta}(\\fixwidehat{F}_Z)}{h}\n\\end{align}\n\\begin{itemize}\n  \\item $\\delta_{\\bm{z}_{tr}}$ is the Heaviside step function centered at $\\bm{z}_{tr}$\n  \\item Meaning: the sensitivity of the statistical functional $\\bm{\\theta}(\\fixwidehat{F}_Z)$ with respect to ``adding a little bit probability mess at $\\bm{z}_{tr}$ into the empirical CDF''.\n\\end{itemize}\nSimilar to other statistical functionals, the prediction loss, for example:\n    \\begin{align}\\label{lossinfluence}\n  \\mathcal{I}_{\\mathcal{L}}(\\bm{z}_{tr}, \\bm{z}_{te}) = \\underset{h \\to 0}{\\lim}\\frac{\\mathcal{L}(\\bm{z}_{te}, \\bm{\\theta}((1-h)\\fixwidehat{F}_Z + h\\delta_{\\bm{z}_{tr}})) - \\mathcal{L}(\\bm{z}_{te}, \\bm{\\theta}(\\fixwidehat{F}_Z))}{h}\n    \\end{align}\n\\end{frame}\n\n\n\n\n\\subsection{How to Compute?}\n\n% You can reveal the parts of a slide one at a time\n% with the \\pause command: \n\\begin{frame}{Naive Approach: LOO Refitting, But...}\n Take $h=-\\frac{1}{n}\\to0$, the ``contaminated CDF'' is:\n $$\n (1+1/n)\\fixwidehat{F}_Z- \\delta_{\\bm{z}_{i}}/n = (1+1/n)\\fixwidehat{F}_{-i} + o(1/n)\\approx \\widehat{F}_{-i}\n $$\n It's the leave-$i$-out empirical CDF!\n\\begin{align}\\label{I_theta}\n\\mathcal{I}_{\\fixwidehat{\\bm{\\theta}}}(\\bm{z}_{i}) &= \\underset{n \\to \\infty}{\\lim}\\frac{\\bm{\\theta}(\\widehat{F}_{-i}) - \\bm{\\theta}(\\fixwidehat{F}_Z)}{-1/n} \\notag\\\\\n &= \\underset{n \\to \\infty}{\\lim}-n(\\fixwidehat{\\bm{\\theta}}_{-\\frac{1}{n}, \\bm{z}_i} - \\fixwidehat{\\bm{\\theta}}) \n\\end{align}\n\\begin{itemize}\n  \\item $\\fixwidehat{\\bm{\\theta}}_{-\\frac{1}{n}, \\bm{z}_i}$ is just the LOO estimate. \n  \\item Influence function is the asymptotic approximation of LOO difference in parameter estimate!\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}{But!}\n\\begin{itemize}\n  \\item If we want the influence from all training examples, we need to do LOO refit $n$-times!\n  \\item Super expensive. \\textbf{NO}!\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Let's Solve the Easier Version First}\nSuppose the loss is strictly convex, twice differentiable.\n\\begin{itemize}\n  \\item Use the FOC for the LOO empirical risk minimization problem $\\Rightarrow$ A closed-form solution for LOO estimator $\\fixwidehat{\\bm{\\theta}}_{-\\frac{1}{n}, \\bm{z}_i}$.\n  \\item Taylor approximation, drop high order infinitesimals...\n  \\item The LOO difference is approximately\n\\begin{align}\n(\\fixwidehat{\\bm{\\theta}}_{-\\frac{1}{n}, \\bm{z}_i} - \\fixwidehat{\\bm{\\theta}}) \\approx-\\frac{1}{n}\\nabla^2_{\\bm{\\theta}}R(\\fixwidehat{\\bm{\\theta}})^{-1} \\nabla_{\\bm{\\theta}} \\mathcal{L}(\\bm{z}_i, \\fixwidehat{\\bm{\\theta}})\n\\end{align}\n\\item Plug into the asymptotic formula:\n\\begin{align}\\label{I_theta}\n\\mathcal{I}_{\\fixwidehat{\\bm{\\theta}}}&= \\underset{n \\to \\infty}{\\lim}-n(\\fixwidehat{\\bm{\\theta}}_{-\\frac{1}{n}, \\bm{z}_i} - \\fixwidehat{\\bm{\\theta}}) \\\\\n&\\approx -\\nabla^2_{\\bm{\\theta}}R(\\fixwidehat{\\bm{\\theta}})^{-1} \\nabla_{\\bm{\\theta}} \\mathcal{L}(\\bm{z}_i, \\fixwidehat{\\bm{\\theta}})\n\\end{align}\nNo retraining, only hessian and gradients.\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Same for the Influence on Loss}\n\\begin{align}\n\\label{I_loss}\n\\mathcal{I}_{\\mathcal{L}}(\\bm{z}_{tr}, \\bm{z}_{te}) &= \\nabla_{\\delta_{\\bm{z}_{tr}}} \\mathcal{L}(\\bm{z}_{te}, \\bm{\\theta}(F_Z))\\biggr\\rvert_{F_Z=\\fixwidehat{F}_Z} \\\\[-2pt]\n&= \\nabla_{\\bm{\\theta}}\\mathcal{L}(\\bm{z}_{te}, \\fixwidehat{\\bm{\\theta}})^{\\top}\\underset{h \\to 0}{\\lim}\\frac{\\bm{\\theta}(\\fixwidehat{F}_{-\\bm{z}_{tr}}) - \\bm{\\theta}(\\fixwidehat{F}_Z)}{h}\\notag\\\\[0pt]\n&\\approx-\\nabla_{\\bm{\\theta}}\\mathcal{L}(\\textcolor{red}{\\bm{z}_{te}}, \\fixwidehat{\\bm{\\theta}})^{\\top}\\nabla^2_{\\bm{\\theta}}R(\\fixwidehat{\\bm{\\theta}})^{-1} \\nabla_{\\bm{\\theta}} \\mathcal{L}(\\textcolor{blue}{\\bm{z}_{tr}}, \\fixwidehat{\\bm{\\theta}})\\notag\\\\\n&~\\quad\\qquad(1\\times p)~~~~~(p\\times p)~~~~~~(p\\times 1)\\notag\n\\end{align}\n\\begin{itemize}\n  \\item Nothing but a fancy version of \\textit{chain rule}!\n  \\item Meaning: the validation loss of point $\\textcolor{red}{\\bm{z}_{te}}$'s sensitivity (w.r.t. to adding a little prob. mass at) training point $\\textcolor{blue}{\\bm{z}_{tr}}$.\n\\end{itemize}\n\\end{frame}\n\n\n\n\\section{Implementation}\n\n\\subsection{Exact Computation}\n\\begin{frame}{How to Compute $\\mathcal{I}_{\\mathcal{L}}(\\bm{z}_{i}, \\bm{z}_{te})$?}{}\nRecall $n = \\text{number of observations}$, $p=\\text{number of parameters}$.\n\\begin{align}\n\\label{I_loss}\n\\mathcal{I}_{\\mathcal{L}}(\\bm{z}_{i}, \\bm{z}_{te}) \\approx-\\underbrace{\\nabla_{\\bm{\\theta}}\\mathcal{L}(\\textcolor{red}{\\bm{z}_{te}}, \\fixwidehat{\\bm{\\theta}})^{\\top}\\nabla^2_{\\bm{\\theta}}R(\\fixwidehat{\\bm{\\theta}})^{-1}}_{\\text{Does not depend on $i$}} \\nabla_{\\bm{\\theta}} \\mathcal{L}(\\textcolor{blue}{\\bm{z}_{i}}, \\fixwidehat{\\bm{\\theta}})\n\\end{align}\n\\begin{itemize}\n  \\item We want this for all training points $\\bm{z}_1, \\bm{z}_2, ..., \\bm{z}_n$. \n  \\item Idea: evaluate the part that does not depend on $i$ only \\textbf{once}, then $n$ inner products. $O(np) + O(?)$.\n  \\item What is $O(?)$?\n\\end{itemize}\n\\end{frame}\n\n\n\\begin{frame}{How to Compute the part that does not depend on $i$?}{}\nLet $\\bm{s}_{te} := \\underbrace{\\nabla_{\\bm{\\theta}}\\mathcal{L}(\\textcolor{red}{\\bm{z}_{te}}, \\fixwidehat{\\bm{\\theta}})^{\\top}\\nabla^2_{\\bm{\\theta}}R(\\fixwidehat{\\bm{\\theta}})^{-1}}_{\\text{Does not depend on $i$}}$\n\\begin{itemize}\n  \\item $\\nabla_{\\bm{\\theta}}\\mathcal{L}(\\textcolor{red}{\\bm{z}_{te}}, \\fixwidehat{\\bm{\\theta}})^{\\top}$: just a 1 to $p$ gradient. $O(p)$.\n  \\item $\\nabla^2_{\\bm{\\theta}}R(\\fixwidehat{\\bm{\\theta}})^{-1}$: full hessian of the empirical risk. \n  \\begin{itemize}\n    \\item Empirical risk: \\texttt{reduce\\_sum}( $n$ things ). $\\times n$\n    \\item Hessian of 1 ``thing'': 1 to $p$, $O(p^2)$\n  \\end{itemize}\n  Forming the hessian: $O(np^2)$. Inverting the hessian $O(p^3)$.\n  \\item $O(np^2 + p^3)$ in total. \n\\end{itemize}\n\nToo expensive! On \\texttt{MNIST}, even multi-classes logistic regression has $p=(28^2+1)(10-1)=7065$.\n\\end{frame}\n\n\n\n\\subsection{Conjugate Gradients}\n\n\\begin{frame}{Conjugate Gradients}{}\n$\\bm{s}_{te} = \\nabla_{\\bm{\\theta}}\\mathcal{L}(\\bm{z}_{te}, \\fixwidehat{\\bm{\\theta}})^{\\top}\\nabla^2_{\\bm{\\theta}}R(\\fixwidehat{\\bm{\\theta}})^{-1}$\nis actually the solution to the linear system\n$$\n\\nabla^2_{\\bm{\\theta}}R(\\fixwidehat{\\bm{\\theta}}) \\bm{x} = \\nabla_{\\bm{\\theta}}\\mathcal{L}(\\bm{z}_{te}, \\fixwidehat{\\bm{\\theta}})^{\\top}\n$$\n\\begin{itemize}\n  \\item This is a positive definite linear system, which is good.\n  \\item Linear conjugate gradients method (CG) is an efficient iterative algorithm to solve PD linear system $\\bm{Ax} = \\bm{b}$.\n  \\item Only requires quantities like $\\bm{Av}$ for arbitrary vectors $\\bm{v}$.\n  \\item No need for $\\bm{A}$ itself!\n\\end{itemize}\nCan avoid explicitly forming and inverting hessian matrix. Only need to implement $\\bm{Hv}$ - \\textbf{hessain-vector products} (HVPs).\n\\end{frame}\n\n\\begin{frame}{Hessain-Vector Product}{}\n\\begin{itemize}\n  \\item Easy to implement in auto-gradients systems like \\texttt{Tensorflow}.\n  \\item Single HVP evaluation Cost is $O(np)$.\n  \\item If $m$ CG iterations, total cost is $O(nmp)$. (typically, $m=O(p)$)\n  \\item Should be a big improvement from $O(np^2 + p^3)$.\n\\end{itemize}\n\\end{frame}\n\n\\subsection{Stochastic Taylor Approximations}\n\n\\begin{frame}{Stochastic Taylor Approximations}{}\n\\begin{itemize}\n  \\item $\\widehat{\\bm{H}}$ be the full hessian matrix of empirical risk.\n  \\item If the Jordan normal form of $(\\bm{I}-\\fixwidehat{\\bm{H}})$ is $\\bm{J}$, then $\\exists$ an invertible matrix $\\bm{P}$ such that $(\\bm{I}-\\fixwidehat{\\bm{H}}) = \\bm{P}\\bm{J}\\bm{P}^{-1}$.\n  \\item $(\\bm{I}-\\fixwidehat{\\bm{H}})^m = \\bm{P}\\bm{J}^m\\bm{P}^{-1} \\to 0$ as $m\\to \\infty$, if and only if $|\\lambda| < 1$ for all the eigenvalues of $(\\bm{I}-\\fixwidehat{\\bm{H}})$.\n\\end{itemize}\nThe idea is to use power series (which converges in this case) to approximate hessian inverse. $(\\bm{I}-(\\bm{I}-\\fixwidehat{\\bm{H}}))^{-1}=\\fixwidehat{\\bm{H}}^{-1} = \\sum_{i=0}^{\\infty} (\\bm{I}-\\fixwidehat{\\bm{H}})^i$. The recursive form:\n\\begin{align}\\label{lissarule}\n\\fixwidehat{\\bm{H}}^{-1}_j \\bm{v} &= \\left[\\bm{I} + (\\bm{I} - \\fixwidehat{\\bm{H}})\\fixwidehat{\\bm{H}}^{-1}_{j-1}\\right]\\bm{v}\\notag\\\\\n\\bm{p}_j &= \\bm{v} + \\bm{p}_{j-1} - \\fixwidehat{\\bm{H}} \\bm{p}_{j-1}\n\\end{align}\n\\textit{LiSSA}: a stochastic (minibatch) version of the above. Look at only one training points in each iteration step. $O(np + dp)$.\n\\end{frame}\n\n\n\\section{Experiments}\n\\subsection{Ridge Regression Models}\n\n\\begin{frame}{Experiments}\n   \\begin{itemize}\n       \\item\n        {\n            Recall, $\\mathcal{I}_{\\fixwidehat{\\bm{\\theta}}}(\\bm{z}_{i}) = {\\lim}_{n \\to \\infty}-n(\\fixwidehat{\\bm{\\theta}}_{-\\frac{1}{n}, \\bm{z}_i} - \\fixwidehat{\\bm{\\theta}})$.\n        }\n        \\item Influence function = Asymptotic approximation of the LOO difference (of the influenced statistical functional)!\n        \\item Same argument holds for $\\mathcal{I}_{\\mathcal{L}}(\\bm{z}_{tr}, \\bm{z}_{te})$.\n        \\item We test our influence function by plotting it against the LOO retraining difference.\n   \\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Ridge Regression}\n   \\begin{itemize}\n       \\item Ridge regression empirical risk:\n        \\begin{align}\\label{ridge_R}\n        \\vspace{-0.15in}\n        R_{\\text{ridge}}(\\fixwidehat{\\bm{\\theta}}) = \\frac{1}{n}\\sum_{i=1}^n \\left( (y_i - \\bm{x}_i^{\\top} \\fixwidehat{\\bm{\\theta}} )^2 + \\frac{\\lambda}{n} \\left\\lVert\\fixwidehat{\\bm{\\theta}}  \\right\\rVert_2^2\\right)\n        \\vspace{-0.15in}\n        \\end{align}\n        \\item The influence has a closed-form:\n        \\begin{align}\\label{ridge_I_loss}\n        \\vspace{-0.15in}\n        \\mathcal{I}_{\\mathcal{L}_{\\text{ridge}}}(\\bm{z}_{tr}, \\bm{z}_{te}) &= \\frac{n}{2}\\left[ -2\\bm{x}_{tr}^{\\top}(y-\\bm{x}_{tr}^{\\top}\\fixwidehat{\\bm{\\theta}}) + \\frac{2 \\lambda}{n} \\fixwidehat{\\bm{\\theta}}\\right]^{\\top}\\left(\\bm{X}^{\\top} \\bm{X} + \\lambda \\bm{I}_p\\right)^{-1}\\cdot\\notag\\\\\n        &\\qquad \\left[ -2\\bm{x}_{te}^{\\top}(y-\\bm{x}_{te}^{\\top}\\fixwidehat{\\bm{\\theta}}) + \\frac{2 \\lambda}{n} \\fixwidehat{\\bm{\\theta}}\\right]\n        \\vspace{-0.15in}\n        \\end{align}\n   \\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Ridge Regression}\n   \\begin{itemize}\n       \\item Tested on the \\href{https://archive.ics.uci.edu/ml/datasets/forest+fires}{\\texttt{ForestFires}} dataset, a regression task with 517 instances and 13 features. \\item After training the model, compute the difference between the validation loss after doing actual LOO retaining and the original loss with $\\fixwidehat{\\bm{\\theta}}$, for all training points.\n        \\item Plot the actual LOO difference against the influence to assess the accuracy of our influence functions with all three methods that we discussed.\n   \\end{itemize}\n\n\\begin{figure*}\n\\vskip 0.0in\n\\begin{center}\n\\centerline{\\includegraphics[width=\\columnwidth]{fig-ridge}}\n\\vskip -0.1in\n\\label{ridge_examples}\n\\end{center}\n\\vskip -0.25in\n\\end{figure*} \n\\end{frame}\n\n\n\\subsection{Hyperplane Classification}\n\n\\begin{frame}{Logistic Regression}\n   \\begin{itemize}\n       \\item The logistic empirical risk is:\n        \\begin{align}\\label{logit_R}\n        \\vspace{-0.2in}\n        R_{\\text{logit}}(\\fixwidehat{\\bm{\\theta}}) = \\frac{1}{n}\\sum_{i=1}^n \\left(-y_i\\fixwidehat{\\bm{\\theta}}^{\\top}\\bm{x}_i + \\log(1+e^{\\fixwidehat{\\bm{\\theta}}^{\\top} \\bm{x}_i})\\right)\n        \\vspace{-0.2in}\n        \\end{align}\n        \\item\n        {\n        Let $\\sigma(t)=1/(1+e^{-t})$, label $y\\in \\{0,1\\}$. The influence also has a closed-form:\n        \\begin{align}\\label{logit_I_loss}\n        \\vspace{-0.15in}\n        \\mathcal{I}_{\\mathcal{L}_{logit}}(\\bm{z}_{tr}, \\bm{z}_{te}) &= -\\bm{x}_{tr}^{\\top}\\left(\\frac{1}{n}\\sum_{i=1}^n \\sigma(\\fixwidehat{\\bm{\\theta}}^{\\top}\\bm{x}_i)\\sigma(-\\fixwidehat{\\bm{\\theta}}^{\\top}\\bm{x}_i)\\bm{x}_i\\bm{x}_i^{\\top}\\right)^{-1} \\bm{x}_{te}\\cdot\\notag\\\\\n        &(\\sigma(\\fixwidehat{\\bm{\\theta}}^{\\top}\\bm{x}_{tr})-y_{tr})(\\sigma(\\fixwidehat{\\bm{\\theta}}^{\\top}\\bm{x}_{te})-y_{te})\n        \\vspace{-0.15in}\n        \\end{align}\n        }\n   \\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Logistic Regression}\n   \\begin{itemize}\n       \\item\n        {\n        We fit an $L_2$-regularized logistic regression on the \\href{http://yann.lecun.com/exdb/mnist/}{\\texttt{MNIST}} dataset. \n        \\item Binary case for simplicity: digits 1 and 7. Let the label $y=1$ stand for digit 1 and $y=0$ for digit 7.\n        }\n        \\item We plot the actual LOO difference against the influence function.\n   \\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Logistic Regression}\n\n\\begin{figure*}\n\\vskip 0.0in\n\\begin{center}\n\\centerline{\\includegraphics[width=3in]{fig-logit}\\includegraphics[width=1.05in]{fig-logit-img}}\n\\vskip -0.1in\n\\label{logit_examples}\n\\end{center}\n\\vskip -0.25in\n\\end{figure*} \n\n\\end{frame}\n\n\\begin{frame}{Support Vector Machine}\n\n\\begin{itemize}\n  \\item Many loss functions are non-differentiable.\n  \\item Idea: construct a smooth function that \\emph{converges} to the non-differentiable components.\n  \\item Linear SVC Empirical Risk (Non-differentiable):\n  \\begin{align}\\label{svc_R}\n\\vspace{-0.2in}\nR_{\\text{sv}}(\\fixwidehat{\\bm{\\theta}}) = \\frac{1}{n}\\sum_{i=1}^n \\left[h\\left(y_i(\\bm{x}_i^{\\top} \\fixwidehat{\\bm{\\beta}} + \\fixwidehat{\\beta_0})\\right) + \\frac{\\lambda}{2n} \\left\\lVert \\bm{\\beta}\\right\\rVert_2^2\\right]\n\\vspace{-0.2in}\n\\end{align}\n\\item ``Smooth Hinge'': replace $h(x) = \\max\\{0, 1-x\\}$ with $h_t(x) := t\\log(1+\\text{exp}(\\frac{1-x}{t}))$.\n\\end{itemize}\n\n\n\\begin{figure*}\n\\vskip 0.0in\n\\begin{center}\n\\centerline{\\includegraphics[width=1.0\\columnwidth]{fig-svm}}\n\\vskip -0.1in\n\\label{fig_svm}\n\\end{center}\n\\vskip -0.2in\n\\end{figure*} \n\n\\end{frame}\n\n\n\\section{Applications}\n\n\\subsection{Understanding the Components of Influence}\n\n\\begin{frame}{Understanding the Components of Influence}\n\\begin{align}\\label{logit_I_loss2}\n\\vspace{-0.15in}\n\\mathcal{I}'_{\\mathcal{L}_{logit}}(\\bm{z}_{tr}, \\bm{z}_{te}) &= -\\bm{x}_{tr}^{\\top}\\textcolor{red}{\\nabla_{\\bm{\\theta}}^2 R(\\fixwidehat{\\bm{\\theta}})^{-1}} \\bm{x}_{te}\\cdot\\\\\n&y_{tr}\\textcolor{blue}{\\sigma(-y_{tr}\\fixwidehat{\\bm{\\theta}}^{\\top}\\bm{x}_{tr})}\\cdot y_{te}\\textcolor{orange}{\\sigma(-y_{te}\\fixwidehat{\\bm{\\theta}}^{\\top}\\bm{x}_{te})}\\notag\n\\vspace{-0.15in}\n\\end{align}\n\n\\begin{align}\\label{logit_I_loss2}\n\\vspace{-0.15in}\n\\mathcal{I}'_{\\mathcal{L}_{logit}}(\\bm{z}_{tr}, \\bm{z}_{te}) &= -[\\textcolor{red}{\\text{Hessian Inv}} \\text{ scaled inner product}]\\cdot \\\\\n&(\\textcolor{blue}{\\text{training leverage}})(\\text{sgn}(y_{tr}y_{te}))(\\textcolor{orange}{\\text{constant}})\\notag\n\\vspace{-0.15in}\n\\end{align}\n   \n   \n\\begin{figure}[ht]\n\\vskip 0.0in\n\\begin{center}\n\\centerline{\\includegraphics[width=4.5in]{fig-components}}\n\\vskip -0.1in\n\\label{logit_components}\n\\end{center}\n\\vskip -0.25in\n\\end{figure}\n\\end{frame}\n\n\\subsection{Understanding Model Behavior}\n\\begin{frame}{Understanding Model Behavior}{}\n\\begin{itemize}\n  \\item The influence function can help us get a better understanding upon how black-box models rely on and extrapolate from the training data.\n  \\item Logistic regression V.S. linear SVC.\n\\end{itemize}\n\\begin{figure}[ht]\n\\vskip 0.0in\n\\begin{center}\n\\centerline{\\includegraphics[width=4.5in]{fig-app1}}\n\\vskip -0.1in\n\\label{logit_components}\n\\end{center}\n\\vskip -0.25in\n\\end{figure}\n\n\\end{frame}\n\n\\subsection{Software Package}\n\\begin{frame}{Software Package}{}\n\\begin{itemize}\n  \\item We built a generic empirical risk optimizing framework with \\texttt{Tensorflow} to compute influence functions for various models.\n  \\item With the help of auto-gradients system, the required gradients and hessian-vector products are automatically kept track of. \n  \\item The user only need to define the empirical risk funtion and its parametrization. \n  \\item All of our code, data, and reproducible experiments are available in our \\href{https://github.com/zedyang/46927-Project}{Github repository}: \\textcolor{blue}{https://github.com/zedyang/46927-Project}.\n  \\item Feel free to download and playaround!\n\\end{itemize}\n\\end{frame}\n\n\\frame\n{\n\n\\begin{center}\n\\LARGE\nThanks for your attention\n\\end{center}\n\n}\n\n\n\n\n\\end{document}\n", "meta": {"hexsha": "49d4f945fa9ceb41006c13a22c7bb75773341f85", "size": 20950, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/slides/slide.tex", "max_stars_repo_name": "zedyang/46927-Project", "max_stars_repo_head_hexsha": "366693a13d8ee1daad91364640792524f4664c04", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-01-24T23:44:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-25T10:23:23.000Z", "max_issues_repo_path": "tex/slides/slide.tex", "max_issues_repo_name": "zedyang/46927-Project", "max_issues_repo_head_hexsha": "366693a13d8ee1daad91364640792524f4664c04", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/slides/slide.tex", "max_forks_repo_name": "zedyang/46927-Project", "max_forks_repo_head_hexsha": "366693a13d8ee1daad91364640792524f4664c04", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-04-10T03:30:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-25T00:11:00.000Z", "avg_line_length": 42.4089068826, "max_line_length": 367, "alphanum_fraction": 0.6656801909, "num_tokens": 7226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.30935208127124647}}
{"text": "\\chapter{The State of the Art}\n\n\\section{Rogue Wave Research} \\label{sec:sota-rogue}\n\n\\sidefigure{AI art generated by VQGAN + CLIP \\citep{esser_taming_2021,radford_learning_2021}. Prompt: \\emph{\\enquote{offshore oil platform in a storm | rogue wave | Kodak}}.}[fig:vqgan-2]{\n    \\includegraphics[width=.9\\linewidth]{vqgan-images/vqgan-44}\n}\n%\nWhat people think of when they hear the term \\enquote{rogue wave} or \\enquote{freak wave} heavily depends on their personal context, even among experts.\n\nIn popular science, the term rogue wave is often used to describe any large ocean wave, and they are often credited to be responsible for the loss of ships and lives at sea \\citep{didenkulova_catalogue_2019}. This is contrary to the scientific definition, which is a relative criterion based on the observed wave height $H$ and the height of the surrounding waves, characterized by the significant wave height $H_s$:\n\n\\begin{align}\n    \\text{\\footnotesize\\spacedlowsmallcaps{Rogue wave criterion}} && \\frac{H}{H_s} > \\kappa && \\label{eq:rogue}\n\\end{align}\n\nUsually, the rogue threshold $\\kappa$ is taken to be $2.0$ or $2.2$ for crest-to-trough wave heights and $1.2$ for crest heights. The significant wave height $H_s$ is defined as 4 times the standard deviation of the surface elevation (see \\figref{fig:anatomy} for an illustration of these quantities). This is roughly equivalent to the mean of the highest third of waves, which aligns with the average wave height reported by a trained observer \\citep{holthuijsen_waves_2010}.\n\n\\begin{figure}\n    \\begin{sidecaption}{Anatomy of an Eulerian wave observation, in which the observer is fixed in space (like a seaward facing laser, or --- approximately --- a tightly moored wave buoy).}[fig:anatomy]\n\t\t\\antimpjustification\n\t\t\\includegraphics{sota/timeseries.pdf}\n\t\\end{sidecaption}\n\\end{figure}\n\nThe definition \\eqref{eq:rogue} immediately reveals the first fundamental issue in rogue wave research: most rogue waves are neither dangerous nor interesting. It is not noteworthy when a \\SI{50}{\\centi\\metre} wave occurs in a \\SI{20}{\\centi\\metre} sea state, but it is as much a rogue wave as a \\SI{20}{\\metre} wave in an \\SI{8}{\\metre} sea. For this definition to make sense, it implicitly encodes 2 fundamental assumptions:\n\n\\begin{enumerate}\n    \\item Small rogue waves are caused by the same generation mechanisms as big rogue waves.\n    \\item Waves above the rogue wave threshold are somehow fundamentally different from those below it.\n\\end{enumerate}\n\nBoth assumptions are non-trivial. In fact, the articles in \\chapref{chap:main} present evidence that the second assumption does not hold throughout most sea states in the real ocean, and \\chapref{chap:outro} discusses some of the implications.\n\nResearch interest in rogue waves was originally triggered by the indisputable measurement of a rogue wave at the Draupner oil rig in the North Sea in 1995, at a wave height of \\SI{25.6}{\\metre} and crest height of \\SI{18.5}{\\metre} during a storm with significant wave height of \\SI{12}{\\metre} \\citep{sunde1995kjempebolger,haver2004possible}. With a relative crest height of \\num{1.55}, this event would be extremely rare under the existing theory for linear, narrow-bandwidth waves \\citep{longuet1952statisticaldistribution}. This disconnect sent the research community searching for a theory that attaches a higher probability to this and similar events.\n\nThis ultimately resulted in a debate on the fundamental nature of these waves: are they themselves extremely rare, or the conditions under which they are generated? Or in the words of \\citeauthor{hayer2000freak}: \\citebook{hayer2000freak}\\sidenote[-4]{This is in fact an excellent question to address with machine learning. All we need to do is to see how well a model can reliably predict rogue waves given the sea state --- and hope that we have collected enough and the right kind of data.}. The following sections outline the ideas behind both hypotheses, and present the state of the art in rogue wave research.\n\n\\subsection{Linear Waves} \\label{sec:waves-linear}\n\nTo lowest order, the properties of a 1-dimensional wave measurement (like a time series observation at a fixed location) are fully described by its spectral density $\\mathcal{S}(f)$, often just called a \\enquote{wave spectrum} (see \\figref{fig:spectrum} for an example).\n\n\\begin{figure}\n    \\strictpagechecktrue\n    \\begin{sidecaption}{A typical bi-modal wave spectrum representing the overlap of swell and wind sea. Idealized Ochi-Hubble six-parameter wave spectrum with spectral peaks at periods \\SI{6}{\\second} and \\SI{14}{\\second} \\citep{ochi_michel_k_six-parameter_1976}.}[fig:spectrum]\n\t\t\\antimpjustification\n\t\t\\includegraphics{sota/spectrum.pdf}\n\t\\end{sidecaption}\n\\end{figure}\n\nTo see this, we adopt a simple model called the random phase-amplitude model \\citep[see \\eg][]{holthuijsen_waves_2010}: We view the wave train as a superposition of independent harmonics with frequency $f$, where each harmonic has an amplitude depending on the corresponding value of the wave spectrum $\\mathcal{S}(f)$ and an independent, uniformly random phase $\\phi \\in (0, 2\\pi)$. After all, many processes acting on waves in the real ocean are highly stochastic --- like wave generation from winds or scattering and refraction at a fractal coastline geometry --- so a random phase without a preferred value makes intuitive sense. In this case, the surface elevation $\\eta$ is just the sum of each harmonic:\n\n\\begin{equation}\n    \\eta(t) = \\sum_i \\sqrt{2 \\Delta f \\mathcal{S}(f_i)} \\sin(2\\pi f_i t + \\phi_i)\n\\end{equation}\n\n\\sidefigure{An ensemble of sea surface elevations drawn from the same wave spectrum (as shown in \\figref{fig:spectrum}).}[fig:ensemble]{\\includegraphics[width=\\linewidth]{sota/ensemble.pdf}}[-1]\n%\nwith time $t$, frequency $f$, frequency resolution $\\Delta f$, and random phase $\\phi$. In the case of a spectrum with many independent harmonics $f_i$ (as in the real ocean), this represents the sum of a large number of random variables with finite mean and variance. So per the central limit theorem, $\\eta$ is a Gaussian random variable with zero mean and a variance that is fully determined by the significant wave height. This inherent stochasticity of random phases also implies that even under an identical spectrum no two wave fields will look exactly the same (\\figref{fig:ensemble}).\n\nIn the limit of a narrow-band spectrum, the sea surface elevation only has one maximum / minimum per wave, and the wave heights and crest heights are Rayleigh distributed \\citep{longuet1952statisticaldistribution,holthuijsen_waves_2010}:\n\n\\sidedef{Rayleigh wave distribution}{}{\n\\begin{align}\n    \\text{\\footnotesize\\spacedlowsmallcaps{Wave heights}} & & P(H / H_s > \\kappa) &= \\exp( -2 \\kappa^2 ) \\label{eq:rayleigh} \\\\\n    \\text{\\footnotesize\\spacedlowsmallcaps{Crest heights}} & & P(h / H_s > \\kappa) &= \\exp( -8 \\kappa^2 )\n\\end{align}\n}\n\nThese probability distributions will serve as the baseline for all further comparisons. They also tells us that, under these assumptions\\sidenote[-1]{Assumptions behind Rayleigh-distributed wave heights:\n\\begin{renum}\n    \\item independent, non-interacting harmonics (linear waves);\n    \\item narrow spectral bandwidth.\n\\end{renum}\n}, we would expect about \\num{1} in \\num{10000} waves to be a rogue wave (with a threshold $\\kappa=2.0$ for waves and $1.2$ for crests) through mere random linear superposition.\n\nUnfortunately, the real ocean is not so simple. One commonly violated assumption is that of \\emph{narrow bandwidth}, which is used to derive the Rayleigh wave height distribution above. In fact, most seas do \\emph{not} have Rayleigh distributed wave heights, as we will see in \\chapref{chap:main} (not even seas that are approximately Gaussian). In particular, to create a rogue wave, both crest and trough have to be large, which makes them sensitive to the group structure of the wave train.\n\n\\sidefigure{Wave height probability density (top) and survival function for large wave heights (bottom). Curves are Tayfun distributions as in \\eqref{eq:tayfun} with different values of $r$. The case $r=1$ is identical to the Rayleigh distribution \\eqref{eq:rayleigh}.}[fig:wavedist]{\\includegraphics[width=\\linewidth]{sota/wavedist.pdf}}\n%\nWhen taking finite bandwidths into account, things are more difficult, and there are several competing wave height distributions in bandwidth-limited seas \\citep[\\eg the Boccotti, Naess, and Tayfun distributions:][]{naess_distribution_1985,boccotti_mechanics_1989,tayfun_m._aziz_distribution_1990}. As an example, the Tayfun distribution is based on a parameter $r$ (which we call \\emph{crest-trough correlation}) that is the value of the wave envelope at half the zero-crossing period (\\ie at the expected location of the trough following a crest). For large wave heights $\\gtrsim H_s$ it can be approximated as \\citep{tayfun_wave-height_2007}:\n\n\\begin{equation}\n    P(H / H_s > \\kappa) = \\sqrt{\\frac{1 + r}{2 r}} \\bigg( 1 + \\frac{1-r^2}{4r\\kappa^2} \\bigg) \\exp\\bigg( -\\frac{1}{4(1+r)} \\kappa^2 \\bigg) \\label{eq:tayfun}\n\\end{equation}\n\nwith $r \\in [0, 1]$. In the limit $r \\to 1$ this reduces to the Rayleigh distribution for wave heights (\\figref{fig:wavedist}).\n\n\\subsection{The Stokes Wave}\n\nSo far we have only considered waves and crests with independently random phases. This assumption is not fulfilled anymore as soon as waves are allowed to interact with each other, which couples the phases of different harmonics. Stokes theory extends this to weakly nonlinear waves with low characteristic steepness $\\varepsilon = k H$ (with wave number $k$).\n\nAs in virtually all problems in fluid dynamics, an appropriate starting point is with the incompressible Navier-Stokes equations and the continuity equation (encoding momentum balance and mass conservation, respectively):\n\n\\sidedef{Navier-Stokes equations}{}{\n\\begin{gather}\n\\frac{\\partial \\vec{u}}{\\partial t} + (\\vec{u} \\cdot \\nabla) \\vec{u} - \\nu \\nabla^2 \\vec{u} = -\\frac{1}{\\rho} \\nabla p - g \\cdot \\hat{k} \\\\\n\\nabla \\cdot \\vec{u} = 0\n\\end{gather}\n}\n\nwith velocity vector $\\vec{u}$, viscosity $\\nu$, pressure $p$, density $\\rho$, gravitational acceleration $g$, and unity vector in $z$ direction $\\hat{k}$.\n\nAssuming inviscid ($\\nu=0$) and irrotational ($\\nabla \\times \\vec{u} = 0$) fluid flow, we can introduce a velocity potential $\\phi$:\n\n\\sidedef{Velocity potential}{}{\n\\begin{equation}\n    \\nabla \\phi = \\vec{u}\n\\end{equation}\n}\n\nThis reduces the Navier-Stokes equations to the Bernoulli equation, and the continuity equation to a Laplace equation \\citep[see \\eg][]{holthuijsen_waves_2010}:\n\n\\sidedef{Bernoulli equation}{}{\n\\begin{gather}\n\\frac{\\partial \\phi}{\\partial t} + \\frac{1}{2} \\lvert \\nabla \\phi\n\\rvert^2 \\frac{p}{\\rho} + gz = 0  \\label{eq:bernoulli} \\\\\n\\nabla^2 \\phi = 0\n\\end{gather}\n}\n\nA central missing ingredient is a set of boundary conditions at the top and bottom of the sea that give rise to finite surface elevations --- waves --- and shallow water effects. At each boundary we impose a kinematic boundary condition that ensures that water particles only move parallel to the respective surface $\\eta(x, y, t)$:\n\n\\sidedef{Kinematic boundary condition}{}{\n\\begin{align}\n    & u_z = \\frac{\\partial \\eta}{\\partial t} + u_x \\frac{\\partial \\eta}{\\partial x} + u_y \\frac{\\partial \\eta}{\\partial y} & \\text{at $z=\\eta$}\\\\\n    \\Leftrightarrow\\quad & \\frac{\\partial\\phi}{\\partial z} = \\frac{\\partial \\eta}{\\partial t} + \\frac{\\partial \\phi}{\\partial x} \\frac{\\partial \\eta}{\\partial x} + \\frac{\\partial \\phi}{\\partial y} \\frac{\\partial \\eta}{\\partial y} & \\text{at $z=\\eta$} \\label{eq:bc-kin}\n\\end{align}\n}\n\nFor a flat bottom this just reduces to $\\partial \\phi / \\partial z = 0$ at the ocean floor, but at the surface all terms are generally non-zero. At the surface we also find a dynamic boundary condition for the pressure $p$ that we plug into the Bernoulli equation:\n\n\\sidedef{Dynamic boundary condition}{}{\n\\begin{equation}\n    p = 0 \\quad\\Rightarrow\\quad \\frac{\\partial \\phi}{\\partial t} + \\frac{1}{2} \\lvert \\nabla \\phi \\rvert^2 + g \\eta = 0 \\qquad \\text{at $z=\\eta$} \\label{eq:bc-dyn}\n\\end{equation}\n}\n\nThis assumes that the pressure at the water surface equals a constant atmospheric pressure.\n\nThe set of equations \\eqref{eq:bernoulli}--\\eqref{eq:bc-dyn} gives rise to a whole zoo of surface gravity waves in the ocean\\sidenote[-1]{Excluding planetary-scale waves like Rossby and Kelvin waves, and neglecting interactions with bottom topograpy and breaking waves.}. The equations are nonlinear (containing terms $\\propto \\lvert \\phi \\rvert^2$ and $\\nabla \\phi \\cdot \\eta$) and cannot be solved analytically without further assumptions. The linear wave solution with non-interacting harmonics (as in \\secref{sec:waves-linear}) is recovered by dropping all nonlinear terms and using the plane wave ansatz $\\eta(x, t) = a \\cos(\\omega t - k x)$ with amplitude $a$, frequency $\\omega$, and wave number $k$.\n\nIn the Stokes wave expansion, all nonlinear terms and unknown quantities (such as $\\eta$ and $\\omega$) are expanded in orders of the (assumed) small parameter $\\varepsilon=ak$, the characteristic wave steepness \\citep[see \\eg][]{dean_water_1991}. By keeping only terms up to a certain order $n$ in $\\varepsilon$, this leads to weakly nonlinear corrections of $n$-th order that generate wave trains with higher crests and flatter troughs than purely linear waves.\n\nWeakly nonlinear corrections also cause a modification of the wave height distribution and enhance rogue wave probabilities, especially for rogue crests \\citep{gemmrich_dynamical_2011,fedele_real_2016,fedele_large_2019}. This leads to conditions that have slightly elevated rogue wave probabilities, which supports the \\enquote{rare realizations of a typical population} theory of rogue waves.\n\n\\subsection{Cnoidal Waves}\n\nIn shallow water the Stokes expansion converges very slowly, which makes Stokes theory inapplicable in this case (see \\figref{fig:wave-regimes} for an overview). A characteristic parameter in this context is the Ursell number \\citep{ursell_long-wave_1953}:\n\n\\sidedef{Ursell Number}{}{\n\\begin{equation}\n    \\mathrm{Ur} = \\frac{\\lambda^2 H}{D^3}\n\\end{equation}\n}\n\nwith wavelength $\\lambda = 2\\pi/k$, wave height $H$, and water depth $D$. For high values of $\\mathrm{Ur}$, an expansion in the relative depth $\\widetilde{D}=kD$ is more fruitful than the Stokes expansion \\citep{dean_water_1991}, which leads to the Korteweg-de Vries (KdV) equation and cnoidal theory \\citep{korteweg1895xli}. Notably, cnoidal theory is the simplest theory that allows for solitary waves (solitons) --- waves that travel entirely above the water level and preserve their shape. Solitons have been studied intensely as a possible mechanism for rogue wave generation \\citep{clamond_interaction_2002,kharif_physical_2003,chabchoub_rogue_2011}.\n\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=.7\\textwidth]{sota/wave-regimes.png}\n    \\caption{The range of applicability for different weakly nonlinear theories. From \\citet{holthuijsen_waves_2010}, originally \\citet{mehaute_introduction_2013}. Here, $T$ is the wave period, $H$ wave height, $d$ water depth, $L$ wavelength.} \\label{fig:wave-regimes}\n\\end{figure}\n\n\\subsection{Highly Nonlinear Theory}\n\nA large body of rogue wave research does not consider linear and weakly nonlinear solutions, as it is implicitly assumed that these mechanisms cannot be responsible for observed extreme rogue waves like the Draupner wave. Instead, these studies focus on highly nonlinear phenomena\\sidenote[-3]{Highly nonlinear in the sense that these waves are not just small perturbations to the linear wave profile, but entirely new solutions with unique properties.} such as breathers, solitons, or the modulational instability as possible creation mechanisms \\citep[\\eg][]{kharif_physical_2003,onorato_extreme_2006,onorato_approximate_2012,toffoli_evolution_2010,shukla_instability_2006,kharif_focusing_2001,dematteis_experimental_2019}.\n\nA prototypical framework for these solutions is the nonlinear Schrödinger equation (NLS), which is also based on an expansion in orders of characteristic steepness $\\varepsilon$ and an expansion of the dispersion relation around a dominant wave number $k_0$ / frequency $\\omega_0$ \\citep[see \\eg][for a derivation]{johnson_modern_1997}. In contrast to the Stokes wave solution, the (now complex) wave amplitude $A(x, t)$ is allowed to evolve in time and space and satisfies the nonlinear Schrödinger equation \\citep{slunyaev_rogue_2011}:\n\n\\sidedef{Nonlinear Schrödinger equation}{}{\n\\begin{equation}\n    -2i \\bigg(\\frac{\\partial A}{\\partial t} + c_g \\frac{\\partial A}{\\partial x} \\bigg) + \\frac{\\omega_0}{8 k_0^2} \\frac{\\partial^2 A}{\\partial x^2} + \\frac{\\omega_0 k_0^2}{2} A \\lvert A \\rvert^2 = 0\n\\end{equation}\n}\n\nwith group speed $c_g$. This equation has solutions that grow exponentially due to energy transfer between the carrier wave and its sidebands, an effect called modulational instability or Benjamin-Feir instablity \\citep{benjamin_disintegration_1967}. These solutions are referred to as breathers, one of which is the Peregrine soliton \\citep[\\figref{fig:peregrine}]{peregrine_water_1983}. The strength of the modulational instability is governed by the Benjamin-Feir index \\citep{alber_effects_1978}:\n%\n\\sidefigure{The Peregrine solution. Shown is the evolution of the wave height envelope $A$ in space and time, with a clear localized maximum.}[fig:peregrine]{\n    \\includegraphics{sota/peregrine.pdf}\n}[3.3]\n\n\\sidedef{Benjamin-Feir index}{}{\n    \\begin{equation}\n        \\mathrm{BFI} = \\frac{k_0 A}{\\Delta\\omega / \\omega_0}\n    \\end{equation}\n}\n\nwith spectral bandwidth $\\Delta \\omega$. The original derivation of the nonlinear Schrödinger equation assumes deep water, unidirectional propagation, and narrow-banded spectra. Modifications that relax these assumptions exist \\citep{davey_three-dimensional_1974,dysthe_note_1979}, and modified versions of the BFI that take shallow water and directional spreading into account have been suggested \\citep{serio_computation_2005,fedele_kurtosis_2015}. There is good evidence demonstrating the modulational instability in wave tanks \\citep{onorato_extreme_2006}, but studies considering real ocean conditions have so far not confirmed an enhancement of extreme waves \\citep{gramstad_influence_2007,xiao_rogue_2013}.\n\nThe nonlinear Schrödinger equation is not the only nonlinear wave equation with unstable solutions. In general, waves transfer energy via nonlinear four-wave interactions \\citep{hasselmann_feynman_1966}. This is accounted for explicitly in the Zakharov equation \\citep{zakharov_stability_1968}, which can be studied to derive higher-order corrections to the wave height distribution \\citep[\\eg as in][]{janssen_nonlinear_2003}.\n\n\\subsection{Other Causes of Rogue Waves}\n\nThere are several other hypothesized causes for rogue waves that we have not considered so far \\citep[see][for reviews]{adcock_physics_2014,slunyaev_rogue_2011,dudley_rogue_2019}. While the Bernoulli equations \\eqref{eq:bernoulli} and associated boundary conditions are very general in terms of the permitted dynamics \\emph{within} the fluid, most of the real-world complexities \\emph{outside} the fluid are neglected. Examples for this include:\n\n\\begin{items}\n    \\item Interactions with non-uniform topography such as abrupt transitions in water depth or waves on top of a slope \\citep{trulsen_laboratory_2012};\n    \\item The non-stationarity of the sea state, \\ie its evolution in time \\citep{trulsen_rogue_2018};\n    \\item The interaction between waves and currents \\citep{mallory_abnormal_1974,didenkulova_rogue_2021,onorato_triggering_2011};\n    \\item Direct wind-wave interactions \\citep{adcock_energy_2011};\n    \\item Wave breaking, \\eg the influence of crossing seas on the onset and shape of breaking waves \\citep{mcallister_laboratory_2019}.\n\\end{items}\n\nAll of these effects impact the formation of large waves, but they are also inherently \\emph{local}, which causes them to be averaged out of bulk statistics (such as buoy measurements from many different locations).\n\n\\clearpage\n\n\\section{Physics and Machine Learning} \\label{sec:sota-ml}\n\n\\sidefigure{AI art generated by VQGAN + CLIP \\citep{esser_taming_2021,radford_learning_2021}. Prompt: \\emph{\\enquote{a cartoon robot surfing on a big wave}}.}{\n    \\includegraphics[width=.9\\linewidth]{vqgan-images/vqgan-24.png}\n}\n%\nThe are many examples of studies that apply machine learning to physical problems, most of which aim for improvements in computational efficiency or predictive performance of simulations \\citep[\\eg][]{pestourie_physics-enhanced_2021,bar-sinai_data-driven_2018,kochkov_machine_2021,li_kohn-sham_2020,cranmer_bayesian_2021,cranmer_lagrangian_2020}.\nThese efforts undoubtedly contribute tremendous value. Yet, better \\emph{predictions} are not the same as improved \\emph{understanding}, the foundation of all science. Ideally, machine learning would lead to advances on both fronts, but unfortunately, process understanding seems much harder to come by, in part also due to the immense complexity of real-world data and governing processes \\citep[\\figref{fig:ml-challenges};][]{reichstein_deep_2019}.\n\n\\begin{figure}\n    \\begin{sidecaption}{Challenges when applying machine learning to earth system data. Figure from \\citet{reichstein_deep_2019}.}[fig:ml-challenges]\n        \\antimpjustification\n        \\includegraphics[width=\\textwidth]{sota/ml-challenges.png}\n    \\end{sidecaption}\n\\end{figure}\n\nOne necessary ingredient for true understanding is the robust identification of causal connections over mere association. The emerging field of causality has formalized the identifiability of causal connections from data and provides tools for both causal inference and causal discovery \\citep[see \\eg][]{peters_elements_2017}. There are first promising applications of these methods \\citep[for example in climate:][]{hannart_causal_2016,kretschmer_using_2016,runge_inferring_2019}, but it is still a long way to go before we will be able to identify arbitrary causal connections in real-world spatiotemporal systems. Nevertheless, explicitly encoding or enforcing causal relationships in models is a promising way to make machine learning a more dependable tool for scientific discovery.\n\nCausal connections in physical systems are typically representable by simple mathematical relationships\\sidenote[-1]{An observation dubbed \\citebook{wigner_unreasonable_1960}.}. Machine learning can exploit this through symbolic regression, a method that aims to fit sparse mathematical expressions to data. While the idea itself is not new \\citep[traditionally based on genetic programming,][]{schmidt_distilling_2009}, it is now elevated through increasingly sophisticated machine learning algorithms, with some first successes \\citep{udrescu_ai_2020,zanna_data-driven_2020,lemos_rediscovering_2022,cranmer_discovering_2020}.\n\nAn in physics ubiquitous special case is systems of differential equations, which can be replaced or augmented with neural networks \\citep[neural ODEs / UDEs,][]{chen_neural_2019,rackauckas_universal_2021,kidger_neural_2022}. In combination with symbolic regression, this leads to methods for the automated discovery of differential equations (and thus system dynamics) from data, an approach that shows huge potential \\citep{brunton_discovering_2016,long_pde-net_2019,champion_data-driven_2019,bakarji_discovering_2022,reinbold_robust_2021} but is still very much a matter of active research, and still struggles with observational noise.\n%\n\\sidefigure{The increasing resolution of climate models over time leads to exponentially increasing data volumes. Horizontal resolution over Europe from IPCC (Intergovernmental Panel on Climate Change) reports FAR (1990), SAR (1996), TAR (2001a), and AR4 (2007). Figure from \\citet{change2007climate}.}[fig:climate-res]{\n    \\includegraphics[width=.9\\linewidth,trim=5 5 5 5,clip]{sota/climate-res.jpeg}\n}[-12]\n\nA methodologically much simpler approach is \\enquote{data-mining inspired induction} \\citep{voit_perspective_2019}, where interpretable machine learning \\citep{molnar_interpretable_nodate} and data mining guide the scientist towards the formation of hypotheses that can then be independently verified --- as opposed to setting out with a specific hypothesis to test.\n\nData-mining inspired induction addresses a common challenge in modern science: data volumes have increased exponentially in the last decades (\\figref{fig:climate-res}), while human resources are approximately fixed. The central idea is to combine the strengths of machine learning models (large-scale data analysis taking into account orders of magnitude more data than the human mind could) and humans (causal reasoning and interpretation) into a modern scientific workflow. The remainder of this thesis is a concrete application of this approach and serves as a case study on its feasibility, challenges, and opportunities on a real physical problem.\n", "meta": {"hexsha": "b2a172a60c7582db743e6ac481d1549ed1fa013a", "size": 25043, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "phd-thesis/src/chapters/sota.tex", "max_stars_repo_name": "dionhaefner/dionsthesis", "max_stars_repo_head_hexsha": "cc06f14d54f21692ae87a1a4858979841cf531c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2017-01-31T00:26:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-25T09:32:03.000Z", "max_issues_repo_path": "phd-thesis/src/chapters/sota.tex", "max_issues_repo_name": "dionhaefner/dionsthesis", "max_issues_repo_head_hexsha": "cc06f14d54f21692ae87a1a4858979841cf531c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phd-thesis/src/chapters/sota.tex", "max_forks_repo_name": "dionhaefner/dionsthesis", "max_forks_repo_head_hexsha": "cc06f14d54f21692ae87a1a4858979841cf531c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-09-29T18:31:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-29T16:00:45.000Z", "avg_line_length": 105.2226890756, "max_line_length": 788, "alphanum_fraction": 0.783731981, "num_tokens": 6473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.30935208127124647}}
{"text": "\\documentclass[preprint]{sigplanconf}\n\n\\usepackage{graphicx}\n%%\\usepackage{longtable}\n\\usepackage{comment}\n\\usepackage{amsmath}\n%%\\usepackage{mdwlist}\n%%\\usepackage{txfonts}\n\\usepackage{xspace}\n%%\\usepackage{amstext}\n\\usepackage{amssymb}\n\\usepackage{stmaryrd}\n\\usepackage{proof}\n\\usepackage{multicol}\n\\usepackage[nodayofweek]{datetime}\n\\usepackage{etex}\n\\usepackage[all, cmtip]{xy}\n\\usepackage{xcolor}\n\\usepackage{listings}\n\\usepackage{multicol}\n\\newcommand\\hmmax{0} % default \\newcommand\\bmmax{0} % default 4\n\\usepackage{bm}\n\\usepackage{cmll}\n\n\\newcommand{\\vecspace}[1]{\\mathbb{V}_{#1}}\n\\renewcommand{\\vec}[2]{\\begin{bmatrix} #1 \\\\ #2 \\end{bmatrix}}\n\\newcommand{\\Fpx}[1]{\\mathbb{F}_{#1}}\n\\newcommand{\\modulusp}[1]{\\left | #1 \\right |}\n\\newcommand{\\fname}[1]{\\ulcorner #1 \\urcorner}\n\\newcommand{\\fconame}[1]{\\llcorner #1 \\lrcorner}\n\n\\newcommand{\\xcomment}[2]{\\textbf{#1:~\\textsl{#2}}}\n\\newcommand{\\amr}[1]{\\xcomment{Amr}{#1}}\n\\newcommand{\\roshan}[1]{\\xcomment{Roshan}{#1}}\n\\newcommand{\\jacques}[1]{\\xcomment{Jacques}{#1}}\n\n\\newcommand{\\asterix}[0]{*}\n\n\\newcommand{\\ie}{\\textit{i.e.}\\xspace}\n\\newcommand{\\eg}{\\textit{e.g.}\\xspace}\n\n\\newcommand{\\lcal}{\\ensuremath{\\lambda}-calculus\\xspace}\n\\newcommand{\\G}{\\ensuremath{\\mathcal{G}}\\xspace}\n\n\\newcommand{\\code}[1]{\\lstinline[basicstyle=\\small]{#1}\\xspace}\n\\newcommand{\\name}[1]{\\code{#1}}\n\n\\def\\newblock{}\n\n\\newenvironment{floatrule}\n    {\\hrule width \\hsize height .33pt \\vspace{.5pc}}\n    {\\par\\addvspace{.5pc}}\n\n\\newtheorem{theorem}{Theorem}[section]\n\\newtheorem{lemma}[theorem]{Lemma}\n\\newtheorem{definition}[theorem]{Definition}\n\\newtheorem{proposition}[theorem]{Proposition}\n\\newenvironment{proof}[1][Proof.]{\\begin{trivlist}\\item[\\hskip \\labelsep {\\bfseries #1}]}{\\end{trivlist}}\n\n\\newcommand{\\arrow}[1]{\\mathtt{#1}}\n\n\\newcommand{\\dgm}[2][0.95]{\n\\begin{center}\n\\scalebox{#1}{\n\\includegraphics{diagrams/#2.pdf}\n}\n\\end{center}\n}\n\n%subcode-inline{bnf-inline} name langRev\n%! swap+ = \\mathit{swap}^+\n%! swap* = \\mathit{swap}^*\n%! dagger =  ^{\\dagger}\n%! assocl+ = \\mathit{assocl}^+\n%! assocr+ = \\mathit{assocr}^+\n%! assocl* = \\mathit{assocl}^*\n%! assocr* = \\mathit{assocr}^*\n%! identr* = \\mathit{uniti}\n%! identl* = \\mathit{unite}\n%! dist = \\mathit{distrib}\n%! factor = \\mathit{factor}\n%! eta = \\eta\n%! eps = \\epsilon\n%! eta+ = \\eta^+\n%! eps+ = \\epsilon^+\n%! eta* = \\eta^{\\times}\n%! eps* = \\epsilon^{\\times}\n%! trace+ = trace^+\n%! trace* = trace^{\\times}\n%! (o) = \\circ\n%! (;) = \\fatsemi\n%! (*) = \\times\n%! (+) = +\n%! LeftP = L^+\n%! RightP = R^+\n%! LeftT = L^{\\times}\n%! RightT = R^{\\times}\n%! alpha = \\alpha\n%! bool = \\textit{bool}\n%! color = \\textit{color}\n%! Gr = G\n\n%subcode-inline{bnf-inline} regex \\{\\{(((\\}[^\\}])|[^\\}])*)\\}\\} name main include langRev\n%! Gx = \\Gamma^{\\times}\n%! G = \\Gamma\n%! [] = \\Box\n%! |-->* = \\mapsto^{\\asterix}\n%! |-->> = \\mapsto_{\\ggg}\n%! |--> = \\mapsto\n%! <--| = \\mapsfrom\n%! |- = \\vdash\n%! <><> = \\approx\n%! ==> = \\Longrightarrow\n%! <== = \\Longleftarrow\n%! <=> = \\Longleftrightarrow\n%! <-> = \\leftrightarrow\n%! ~> = \\leadsto\n%! -o+ = \\multimap^{+}\n%! -o* = \\multimap^{\\times}\n%! -o = \\multimap\n%! ::= = &::=&\n%! /= = \\neq\n%! @@ = \\mu\n%! [^ = \\lceil\n%! ^] = \\rceil\n%! {| = \\{\n%! |} = \\}\n%! bot = \\bot\n%! bot1 = \\bot_1\n%! dots = \\ldots\n%! ^^^ = ^{\\dagger}\n%! elem = \\in\n%! forall = \\forall\n%! exists = \\exists\n%! empty = \\epsilon\n%! Pi = \\Pi\n%! Pi0 = \\Pi^{o}\n%! PiEE* = \\Pi^{\\eta\\epsilon}_{*}\n%! PiEE+ = \\Pi^{\\eta\\epsilon}_{+}\n%! PiEE = \\Pi^{\\eta\\epsilon}\n%! CatSet = \\textbf{Set}\n%! theseus = Theseus\n%! sqrt(x) = \\sqrt{#x}\n%! surd(p,x) = \\sqrt[#p]{#x}\n%! inv(x) = \\frac{1}{#x}\n%! frac(x,y) = \\frac{#x}{#y}\n%! * = \\times\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{document}\n\n\\conferenceinfo{ICFP'12}{}\n\\CopyrightYear{}\n\\copyrightdata{}\n\\titlebanner{}\n\\preprintfooter{}\n\n\\title{Computing in the Field of Rationals}\n\n\\authorinfo{Roshan P. James}\n           {Indiana University}\n           {rpjames@indiana.edu}\n\\authorinfo{Zachary Sparks} \n           {Indiana University}\n           {zasparks@indiana.edu}\n\\authorinfo{Jacques Carette} \n           {McMaster University}\n           {carette@mcmaster.ca}\n\\authorinfo{Amr Sabry}\n           {Indiana University}\n           {sabry@indiana.edu}\n\n\\maketitle\n\n\\begin{abstract}\n\n  Previous work on information effects introduced the computational\n  model {{Pi}} which lacked a natural notion of first-class functions.\n  This paper connects the line of work starting with\n  Filinski\\cite{Filinski:1989:DCI:648332.755574} on the duality of\n  computation \\cite{Curien:2000,DBLP:conf/rta/Wadler05} with work on\n  information preserving computation \\cite{infeffects,rc2011}.\n\n  %% Andrzej Filinski's Masters thesis\n  %% \\cite{Filinski:1989:DCI:648332.755574} suggested a remarkable\n  %% symmetry underlying computation in the \\lcal. Filinski showed that\n  %% values are dual to continuations and that functions are dual to\n  %% delimited continuations, thereby suggesting that\n  %% values-and-functions and continuations-and-delimited-continuations\n  %% are mirror images of the same phenomena.\n\n  %% Previous work on \\emph{information effects} established the notion\n  %% of information preserving computation \\cite{infeffects} and the core\n  %% calculus for computing with the isomorphisms of finite types,\n  %% {{Pi}}. Given the first-order nature of {{Pi}} however it was\n  %% unclear how one may express first-class functions and duality in the\n  %% sense of Filinski.\n\n  We present a computational model whose types are \\emph{the field of\n    rational numbers}. This computational model is derived\n  systematically from the {{Pi}} by considering a symmetric notion of\n  duality. Unlike the \\lcal which shows a classical De Morgan duality,\n  here we have two axis of dualization and hence two dualities -- an\n  additive duality, namely negative types and a multiplicative\n  duality, namely fractional types. Intuitively, values of negative\n  types are values that flow ``backwards'' to satisfy demands and\n  values of fractional types are values that impose constraints on\n  their context.\n\n\n  %% Every functional programmer knows about sum and product types, {{a+b}} and\n  %% {{a*b}} respectively. Negative and fractional types, {{a-b}} and {{a/b}}\n  %% respectively, are much less known and their computational interpretation is\n  %% unfamiliar and often complicated. We show that in a programming model in\n  %% which information is preserved (such as the model introduced in our recent\n  %% paper on \\emph{Information Effects}), these types have particularly natural\n  %% computational interpretations. Intuitively, values of negative types are\n  %% values that flow ``backwards'' to satisfy demands and values of fractional\n  %% types are values that impose constraints on their context.  The combination\n  %% of these negative and fractional types enables greater flexibility in\n  %% programming by breaking global invariants into local ones that can be\n  %% autonomously satisfied by a subcomputation. Theoretically, these types give\n  %% rise to \\emph{two} function spaces and to \\emph{two} notions of\n  %% continuations, suggesting that the previously observed duality of\n  %% computation conflated two orthogonal notions: an additive duality that\n  %% corresponds to backtracking and a multiplicative duality that corresponds\n  %% to constraint propagation.\n\n\\end{abstract}\n\n\\category{D.3.1}{Formal Definitions and Theory}{}\n\\category{F.3.2}{Semantics of Programming Languages}{}\n\\category{F.3.3}{Studies of Program Constructs}{Type structure}\n\n\\terms\nLanguages, Theory\n\n\\keywords continuations, information flow, linear logic, logic programming,\nquantum computing, reversible logic, symmetric monoidal categories, compact\nclosed categories.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Introduction}\n\nAndrzej Filinski's Masters thesis\n\\cite{Filinski:1989:DCI:648332.755574} suggested a remarkable symmetry\nunderlying computation in the \\lcal. Filinski inroduced a symmetric\nextension of the \\lcal in which he showed that values are dual to\ncontinuations, functions are dual to delimited continuations, pairs of\nvalues as dual to sums (choice) of continuations\n({{(a*b)^bot<->a^bot+b^bot}}), sums of values are dual to pairs of\ncontinuations ({{(a+b)^bot<->a^bot*b^bot}}) and that call-by-value is dual to call-by-name.\n\nThe symmetries exposed by Filinski suggested that values/continuations\nand functions/delimited continuations are different aspects of the same\ncomputational phenomenon and led to much work in this area.  Symmetry\nbetween the value fragment and the continuation fragment was refined\nby Curien and Herbelin \\cite{Curien:2000} who introduced the\nsequent-style $\\mu\\tilde{\\mu}$-calculus, that exhibits symmetries\nbetween values and continuations and between call-by-value and\ncall-by-name.  The duality between call-by-name and call-by-value was\nfurther investigated by Selinger using control\ncategories~\\cite{Selinger:2001:CCD:966910.966911} and by\nWadler~\\cite{Wadler:2003,DBLP:conf/rta/Wadler05}.\n\n\n\n\n%% The calculus includes the type $A-B$ which is the dual\n%% of implication, i.e., a value of type $A-B$ is a context expecting a\n%% function of type $A \\rightarrow B$. Alternatively a value of type\n%% $A-B$ is also explained as a \\emph{pair} consisting of a value of type\n%% $A$ and a continuation of type $B$. This is to be contrasted with our\n%% interpretation of a value of that type as \\emph{either} a value of $A$\n%% or a demand for a value of type $B$. \n\n%% The extension gives no interpretation to the subtraction connective\n%% and like the original symmetric calculus of Filinski, introduces a\n%% duality that relates sums to products and vice-versa.\n\n\nPrevious work on \\emph{information effects} established the logically\nreversible computational model {{Pi}} (and its extension {{Pi0}})\nwherein computation is information/entropy preserving. The\ncomputational model is derived from the isomorphisms of finite-types,\nis complete for combinational circuits and every computation admits an\nadjoint which is the ``inverse of the computation''. The term model of\n{{Pi}} corresponds to the categorification of a commutative semiring\nwith two commutative monoidal structures {{(0,+)}} and {{(*,1)}} with\n{{*}} distributing over {{+}} and is sometimes called a commutative\nbimonoidal category.  \n\nThe language {{Pi}} however lacks a natural representation for\nfirst-class functions due to the first-order nature of its values. The\nfirst approach to try is to re-use Filinski's duality (or one of its\nlater variants, such duality in the linear logic setting).  The De\nMorgan style duality in Filinski's symmetric \\lcal (and later works)\nis computationally interpreted as follows: if one has a pair of values\n{{(v1, v2)}}, then the context that consumes the value has a choice of\ncomsuming either {{v1}} or {{v2}}. Hence the dual of {{(v1,v2)}} maybe\nthought of as the continuation that does {{fst}} or {{snd}}. Such a De\nMorgan style computational interpretation is inherently based on the\ndeletion of values and completely collapses the logical reversibility\nand information preservation properties of {{Pi}}. Hence classical De\nMorgan duality and linear logic style De Morgan duality (which appears\nin later works on polarised focalized $\\mu\\tilde{\\mu}$) do not apply\ndirectly in the context of {{Pi}}.\n\nThe other obvious approach to try and build functions is to construct\na ``closed'' category. It is well know that the Int-construction of\nJoyal et al \\cite{joyal1996traced} and the $\\mathcal{G}$ construction\nof Abramsky allow the construction of compact closed category\n(sometimes also called monoidal closed) from a traced symmetric\nmonoidal category. The traced extension of {{Pi}}, called {{Pi0}} has\nbeen studied before and indeed the Int-construction gives us a compact\nclosed structure in this setting. However, the Int-construction does\nnot preserve the bimonoidal structure of {{Pi}}, i.e. if we use an\nadditive trace, we lose the {{(1, *)}} monoid and distributivity.\n\n%% In the light of the work of duality of computation it was felt that\n%% ``right model'' for expressing functions in {{Pi}} would also\n%% express symmetries similar to those in the calculi of Filinski,\n%% Curien and Herbelin and Wadler.\n\nThe technical goal of this paper is to present the compuational model\n{{PiEE}}, a Filinski-style symmetric dual extension of {{Pi}}.  The\nextended language has two distinct dualizing actions -- an additive\nduality characterized by negative types $-(\\_)$ and a multiplicative\nduality characterized by fractional types $1/(\\_)$. Each dualizing\noperation preserves the underlying connective {{-(a+b)<->(-a)+(-b)}}\nand {{1/(a*b)<->1/a*1/b}}.  The types of {{PiEE}} correspond to the\n\\emph{field of rational numbers}. Consequently algebraic manipulations\nof rationals can be given an operational interpretation and \\emph{have\n  computational content}.  \n\n%% Negative and fractional types have an\n%% intuitive semantics in the setting of {{Pi}}.\n\n\n\nThe term model of {{PiEE}} corresponds to the \\emph{categorification\n  of a field}. The category is compact closed over the additive\nmonoid. In the multiplicative monoid (since there is no division by\nzero) respects compact closed structure on non-zero objects.  Compact\nclosed categories preserve the monoidal tensor on dualizing. In other\nwords, negative and fractional dualities must not confused with\n$(\\-)^\\bot$ duality in the additive and multiplicative fragment of\nlinear logic.  Models of linear logic rely on *-autonomous categories\nwhich change the monoidal tensor when dualizing.\n\n\n\n%% Say more: fractionals, entanglements, backtracking, superposition,\n%% constraints, negative information. Negative types, backward information\n%% flows, sets with negative types, iteration.. etc.\n\n\nWe present {{Pi}} in the big-step style presented in the previous\nwork, develop the categorical semantics of its term model and present\na small-step semantics useful for modeling fractionals and\nnegatives. We proceed to present the fractional fragment of the\nlanguage {{PiEE*}}, work out its properties and categorical\nsemantics. We further use the multiplicative {{trace}} to express a\nSAT solver. We then present the negative fragment of the language\n{{PiEE+}} and finally present the unified language {{PiEE}}.\n\n\n%% Traditionally, dealing with fields in a categorical setting has proven\n%% hard and hence we hope that the term model of {{PiEE}} will prove\n%% useful. Further, it is as yet unclear why there are two different\n%% dualities in the setting of {{Pi}}.\n\n\n%% \\paragraph*{Declarative Continuations.} \n%% In his Masters thesis~\\cite{Filinski:1989:DCI:648332.755574}, Filinski\n%% proposes that continuations are a \\emph{declarative} concept. He,\n%% furthermore, introduces a symmetric extension of the $\\lambda$-calculus in\n%% which call-by-value is dual to call-by-name and values are dual to\n%% continuations. In more detail, the symmetric calculus contains a ``value''\n%% fragment and a ``continuation'' fragment which are mirror images. Pairs and\n%% sums are treated as duals in the sense that the ``value'' fragment includes\n%% pairs whose mirror image in the ``continuation'' fragment are sums. In\n%% contrast, our language includes pairs and sums in the value fragment and two\n%% symmetries: one that maps the pairs to fractions and another that maps the\n%% sums to subtractions.\n\n% \\begin{comment}\n\n%% In a recent paper~\\cite{infeffects}, we argued that, because they\n%% include irreversible physical primitives, conventional abstract\n%% models of computation have inadvertently included some\n%% \\emph{implicit} computational effects which we called\n%% \\emph{information effects}. We then developed a pure reversible\n%% model of computation that is obtained from the type isomorphisms\n%% and categorical structures that underlie models of linear logic and\n%% quantum computing and that treats information as a linear resource\n%% that can neither be erased nor duplicated. In this paper, we show\n%% that our pure reversible model unveils deeper and more elegant\n%% symmetries of computation than have previously been reported. In\n%% particular, we expose two notions of duality of computation: an\n%% additive duality and a multiplicative duality that give rise to\n%% negative types and fractional types respectively. Although these\n%% types have previously appeared in the literature (see\n%% Sec.~\\ref{sec:related}), they have typically appeared in the\n%% context of conventional languages with information effects, which\n%% limited their appeal and obscured their properties.\n\n\\paragraph*{Negative Types.} \nConsider the following algebraic manipulation relating a natural number {{a}}\nto itself (ignoring the dotted line for a moment):\n\\begin{center}\n\\scalebox{1.1}{\n\\includegraphics{diagrams/thesis/algebra-wire1.pdf}\n}\n\\end{center}\nAlthough seemingly pointless, this algebraic proof corresponds, in our model,\nto an isomorphism of type {{a <-> a}} with a non-trivial and interesting\ncomputational interpretation. The witness for this isomorphism is a\ncomputation that takes a value of type~{{a}}, say \\$20.00, and eventually\nproduces another \\$20.00 value as its output. As the semantics of\nSec.~\\ref{sec:rat} formalizes, this computation flows along the dotted line\nwith the following intermediate steps:\n\\begin{itemize}\n\\item We start at line (0) with \\$20.00; \n\\item We proceed to line (1) with the same \\$20.00 but tagged as being\n  in the left summand of the sum type {{a+0}}; we indicate this value\n  as {{left 20}};\n\\item We continue to line (2) with the same value {{left 20}};\n\\item At line (3), as a result of re-association the tag on the \\$20.00\n  changes to indicate that it is in the left-left summand, i.e., the value is\n  now {{left (left 20)}};\n\\item At line (4), we find ourselves needing to produce a value of type 0\n  which is impossible; this signals the beginning of a reverse execution\n  which sends us back to line (3) with a value {{left (right 20)}};\n\\item Execution continues in reverse to line (2) with the value \n  {{right (left 20)}};\n\\item At line (1) we find ourselves again facing an empty type so we reverse\n  execution again; we go to line (2) with a value {{right (right 20)}};\n\\item We proceed to line (3) and (4) with the value {{right 20}};\n\\item We finally reach line 5 with the value {{20}}.\n\\end{itemize}\nThe example illustrates that the empty type and negative types have a\ncomputational interpretation related to continuations: negative types denote\nvalues that backtrack to satisfy dependencies, or in other words act as debts\nthat are satisfied by the backward flow of information.\n\n\\paragraph*{Fractional Types.} \nConsider a similar algebraic manipulation involving fractional types.\n\\begin{center}\n\\scalebox{1.1}{\n\\includegraphics{diagrams/thesis/algebra-wire2.pdf}\n}\n\\end{center}\nIn the case of negatives, the dotted line indicated the flow of control\nwhereas for fractionals it indicates the flow of constraints. At the heart of\nlogic programming is the idea of variables that capture constraints. Hence it\nis useful to trace the computation corresponding to the algebraic proof\nabove, with the analogy to logic variables in mind.\n\nAs before, the execution begins at line~(0) with the value {{20}}. At\nline~(1) two values, {{20}} and {{()}}, flow forward. One can think of the\nvalue {{()}} (of type {{1}}) as ``having a credit card.'' The credit card\nisn't money, nor is it debt, but is the option to generate a credit-debt\nconstraint.  At line~(2) we exercise this option and hence have three values:\nthe initial value {{20}} flowing from line (1) and two entangled values,\n{{1/alpha}} and {{alpha}}. The {{alpha}} and {{1/alpha}} are unspecified\nvalues, i.e., we don't yet know how much money we need to borrow, but we do\nknow that what is borrowed must be what is returned. Hence~{{alpha}} denotes\nthe presence of an unknown quantity and dually {{1/alpha}} should be thought\nof as the absence of an unknown quantity. At line (3), the missing unknown\n{{1/alpha}} is brought together with a value {{20}} and at line (4) we use\nthe {{20}} to satisfy the constraint {{1/alpha}}. In other words, this branch\nof the computation succeeded in borrowing {{20}} which immediately\ncommunicates the {{20}} to the rightmost branch.\n\nUnlike with negative types, wherein only one value existed at a time and the\ncomputation backtracked, here we have three values that \\emph{exist at the\n  same time}. In other words, the computation with fractions is realized with\na schedule in which every value independently and concurrently proceeds\nthrough its subcomputation. The example illustrates that fractional types\nalso have a computational interpretation that have some flavor of\ncontinuations: the fractional types denote values ({{1/alpha}}) that\nrepresent missing information that must be supplied in much the same sense\nthat continuations denote evaluation contexts with holes that must be filled.\n\nThere are at least four fundamental points about the examples above that must\nbe emphasized:\n\n\\begin{itemize}\n\\item As the examples illustrate, both negative types and fractional types\n  corresponds to ``debts'' but in different ways: negatives are satisfied by\n  backtracking and fractionals are satisfied by constraint propagation.\n\n\\item It would clearly be disastrous if debts could be deleted or\n  duplicated. This simple observation explains why these types are much\n  simpler and much more appealing in a framework where information is\n  guaranteed to be preserved. In previous work that used negative types (see\n  Sec.~\\ref{sec:related}), complicated mechanisms are typically needed to\n  constrain the propagation and use of negative values because the\n  surrounding computational framework is, generally speaking, careless in its\n  treatment of information.\n\n\\item Each of the values {{-a + b}} and {{(1/a) * b}} can be viewed as a\n  function that asks for an {{a}} and then produces a {{b}}. When viewed as\n  functions, we write these types as {{a -o+ b}} and {{a -o* b}}\n  respectively. Alternatively we can view these values as first producing a\n  value of type {{b}} and then demanding an {{a}} and in that perspective\n  they correspond to delimited continuations. Evidently, as the discussion\n  above suggests, these two notions of functions are not the same at all and\n  should not be conflated. Sec.~\\ref{sub:hof} discusses this point in detail.\n\n\\item The main reason credit card transactions are convenient is because they\n  disentangle the propagation of the resources (money) from the propagation\n  of the services. Not every transaction needs both the resources and\n  services to be brought together: it is sufficient to have a promise that\n  the demand for resources will be somehow satisfied, as long as the\n  infrastructure can be trusted with such promises. This idea that\n  dependencies can be freely decoupled and propagated can be a powerful\n  programming tool and we leverage this in the construction of a novel\n  SAT-solver (see Sec.~\\ref{sec:sat-solver}).\n\\end{itemize}\n\n\\paragraph*{Contributions and Outline.} \nTo summarize, in a computational framework that guarantees that information\nis preserved, negative and fractional types provide fascinating mechanisms in\nwhich computations can be sliced and diced, decomposed and recomposed, run\nforwards and backwards, in arbitrary ways. The remainder of the paper\nformalizes these informal observations. Specifically our main contributions\nare:\n\\begin{itemize}\n\\item We extend {{Pi}} our reversible programming language of type\n  isomorphisms~\\cite{rc2011,infeffects} (reviewed in Sec.~\\ref{sec:pi}) with a notion\n  of negative types, that satisfies the isomorphism {{a + (-a) <-> 0}}. The\n  semantics of this extension is expressed by having a \\emph{dual} evaluator\n  that reverses the flow of execution for negative\n  values. (Sec.~\\ref{sec:neg})\n\\item We independently extend {{Pi}} with a notion of fractional types,\n  that satisfies the isomorphism {{a * (1/a) <-> 1}}. The semantics of this\n  extension is expressed by introducing logic variables and a unification\n  mechanism to model and resolve the constraints introduced by the fractional\n  types. (Sec.~\\ref{sec:frac})\n\\item We combine the above two extensions into a language, which we\n  call {{PiEE}}, whose type system allows any rational number to\n  be used as a type. Moreover the types satisfy the same familiar and\n  intuitive isomorphisms that are satisfied in the mathematical field\n  of rational numbers. (Sec.~\\ref{sec:rat})\n\\item We develop programming intuition and argue that negative and fractional\n  types ought to be part of the vocabulary of every\n  programmer. (Sec.~\\ref{sec:prog})\n\\item We relate our notions of negative and fractional types to previous work\n  on continuations. Briefly, we argue that conventional continuations\n  conflate negative and fractional components. This observation allows us to\n  relate two apparently unrelated lines of work: the first pioneered by\n  Filinski~\\cite{Filinski:1989:DCI:648332.755574} relating continuations to\n  negative types and the second~\\cite{Bernardi:2010:CSL:1749618.1749689}\n  relating continuations to the fractional types of the Lambek-Grishin\n  calculus. (Sec.~\\ref{sec:related})\n\\end{itemize}\n\n\\textbf{Note:} All the constructions, semantics, and examples in this paper\nhave been implemented and tested in Haskell. We will make the URL available\nonce the code is organized for better presentation.\n\n% \\end{comment}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{The Core Reversible Language: {{Pi}} }\n\\label{sec:pi}\n\n\\begin{verbatim}\n(parts of rewrite that are done are removed from here)\n\nIn plain Pi: \n------------\n\nSemantics of combinators:\n - iso-types b1 <-> b2 are interpreted as bijections \n   between the sets denoted by b1 and b2\n - a combinator c : b1 <-> b2 is interpeted as a \n   bijection from set b1 to set b2.\n - there is a natural adjoint to c : b1 <-> b2 \n   corresponding to the bijection c^* : b2 <-> b1\n\nEvaluation is function application, i.e., \n  eval c v applies the function (bijection) denoted by c to \n  the value denoted by v.\n\n[If we want to use categorical language, \nwe can express the above semantics using the category \nof finite sets and bijections.]\n\\end{verbatim} \n\nWe review our reversible language {{Pi}}: the presentation in this\nsection differs from the one in~\\cite{infeffects} in two technical\naspects. First, we add the empty type {{0}} which is necessary to express the\nadditive duality. Second, instead of explaining evaluation using a natural\nsemantics, we give a small-step operational semantics that is more\nappropriate for later parts of this paper.\n\nThere is also a notable shift in emphasis.  The terms of {{Pi}} are not\nclassical values and functions; rather, the terms are isomorphism \nwitnesses.  In other words, the terms of {{Pi}} are proofs that certain\n``shapes of values'' are isomorphic.  And, in classical Curry-Howard\nfashion, our operational semantics shows how these proofs can be\ndirectly interpreted as actions on ordinary values which effect this\nshape transformation.\n\nOf course, ``shapes of values'' are very familiar already: they are usually\ncalled \\emph{types}.  But usually one designs a type system as a method\nof classifying terms, with the eventual purpose to show that certain\nproperties of well-typed terms hold, such as safety.  Our eventual goal\nis different: we start from a type system, and are striving to discover\na term language which naturally inhabits these types, along with an\nappropriate operational semantics.\n\n%%%%%%%%%%%%%%%%%%%%\n\\subsection{Syntax and Types} \n\\label{sec:pi-syntax}\n\n\\paragraph*{Data.}\nWe view {{Pi}} as having two levels:  it has traditional values, given by\n%subcode{bnf} include main\n% values, v ::= () | left v | right v | (v, v)\nand these are classified by ordinary types\n%subcode{bnf} include main\n% value types, b ::= 0 | 1 | b + b | b * b \n\nTypes include the empty type {{0}}, the unit type {{1}}, sum types {{b1+b2}},\nand products types {{b1*b2}}.  Values includes {{()}} which is the only value\nof type {{1}}, {{left v}} and {{right v}} which inject {{v}} into a sum type,\nand {{(v1,v2)}} which builds a value of product type. There are no values of\ntype {{0}}.\n\nBut these should be regarded as largely ancilliary.  In particular we\ndo not treat the above values as first-class citizens.  They only occur\nwhen we want to observe the effect of an isomorphism.\n\nNevertheless, these have a precise denotation:  a type {{b}} is \ninterpreted as a set, and {{v : b}}  denotes that {{v}} is a member\nof the set denoted by {{b}}.  As our (traditional) values are first-order,\nand non-polymorphic, such a set interpretation is sound.\n\n\\paragraph*{Isomorphisms.} The terms of {{Pi}} are witnesses to type\nisomorphisms.  They have (iso) types {{v <-> v}}.  \nSpecifically, they are witnesses to the following type isomorphisms:\n%subcode{bnf} include main\n%! columnStyle = r@{\\hspace{-0.5pt}}c@{\\hspace{-0.5pt}}l\n%zeroe :&  0 + b <-> b &: zeroi\n%swap+ :&  b1 + b2 <-> b2 + b1 &: swap+\n%assocl+ :&  b1 + (b2 + b3) <-> (b1 + b2) + b3 &: assocr+\n%identl* :&  1 * b <-> b &: identr*\n%swap* :&  b1 * b2 <-> b2 * b1 &: swap*\n%assocl* :&  b1 * (b2 * b3) <-> (b1 * b2) * b3 &: assocr*\n%dist0 :& 0 * b <-> 0 &: factor0\n%dist :&~ (b1 + b2) * b3 <-> (b1 * b3) + (b2 * b3)~ &: factor\nEach line of the above table introduces a pair of dual constants%\n\\footnote{where {{swap*}} and {{swap+}} are self-dual} (and its typing)\nthat witness the type isomorphism in the middle.  Collectively the isomorphisms\nstate that the structure {{(b,+,0,*,1)}} is a \\emph{commutative semiring},\ni.e., that each of {{(b,+,0)}} and {{(b,*,1)}} is a commutative monoid and that\nmultiplication distributes over addition.  These are the base \n(non-reducible) terms of the second, principal level of {{Pi}}.\n\nNote how the above has two readings: first as a set of typing relations for\na set of constants, as well as giving names to the \\emph{axioms} of\ncommutative semirings.  However, if these axioms are seen as universally\nquantified, orientable statements, they also induce transformations of\nthe (traditional) values.  The (categorical) intuition here is that \nthese axioms have computational content because they witness isomorphisms\nrather than merely stating an extensional equality.\n\nFor example {{ swap* }} induces a function (akin to)\n%subcode{code}\n%! language = Haskell\n% swapProd (a,b) = (b,a)\n\nThe isomorphisms are extended to form a congruence relation by adding the\nfollowing constructors that witness equivalence and compatible closure:\n%subcode{proof} include main\n%@  ~\n%@@ id : b <-> b \n%\n%@ c : b1 <-> b2\n%@@ sym c : b2 <-> b1\n%\n%@ c1 : b1 <-> b2\n%@ c2 : b2 <-> b3\n%@@ c1(;)c2 : b1 <-> b3\n%---\n%@ c1 : b1 <-> b3\n%@ c2 : b2 <-> b4\n%@@ c1 (+) c2 : b1 + b2 <-> b3 + b4\n%\n%@ c1 : b1 <-> b3\n%@ c2 : b2 <-> b4\n%@@ c1 (*) c2 : b1 * b2 <-> b3 * b4\n\nThe syntax is overloaded: we use the same symbol at the value-type level\nand at the isomorphism-type level for denoting sums and products.  Hopefully\nthis will not cause undue confusion.\n\nIt is important to note that ``values'' and ``isomorphisms'' are \ncompletely separate syntactic categories which do not intermix.  The \nsemantics of the language come when these are made to interact at\nthe ``top level'', a new syntactic category:\n%subcode{bnf} include main\n% top-level term, l ::= c v\nWe refer to this as \\emph{application}.\n\n\\noindent\nTo summarize, the syntax of {{Pi}} is given as follows. \n\n\\begin{definition}{(Syntax of {{Pi}})}\n\\label{def:Pi}\nWe collect our types, values, and isomorphisms, to get the full language\ndefinition.\n%subcode{bnf} include main\n% value types, b ::= 0 | 1 | b+b | b*b \n% values, v ::= () | left v | right v | (v,v) \n%\n% iso.~types, t ::= b <-> b\n% base iso ::= zeroe | zeroi \n%     &|& swap+ | assocl+ | assocr+ \n%     &|& identl* | identr* \n%     &|& swap* | assocl* | assocr* \n%     &|& dist0 | factor0 | dist | factor \n% iso comb., c ::= iso | id | sym c | c (;) c | c (+) c | c (*) c \n% top-level term, l ::= c v\n\\end{definition}\n\n\\paragraph*{Adjoint.} \nAn important property of the language is that every term {{c}} has an\nadjoint {{c{dagger}}} that reverses the isomorphisms {{c}}.  This is evident by\nconstruction for the primitive isomorphisms. For the closure combinators, the\nadjoint is homomorphic except for the case of sequencing in which the order\nis reversed, i.e., {{(c1 (;) c2){dagger} = (c2{dagger}) (;) (c1{dagger}) }}.\n\n\\begin{definition}[Size of a type]\n\\label{def:size}\nThe size of a type {{b}}, denoted by {{[^ b ^]}}, is a numeric value\nand is defined to be:\n\\vspace{-20pt}\n\\begin{multicols}{2}\n%subcode{opsem} include main\n% [^ b1 + b2 ^] '= [^ b1 ^] + [^ b2 ^]\n% [^ b1 * b2 ^] '= [^ b1 ^] * [^ b2 ^]  \n\n%subcode{opsem} include main\n% [^ 0 ^] '= 0\n% [^ 1 ^] '= 1\n\\end{multicols}\nwhere {{+}} is numeric addition and {{*}} is numeric multiplication. \n  \n\\end{definition}\n\\noindent\nIn the setting of {{Pi}} the \\emph{size}, {{[^ b ^]}}, may be simply thought of\nas the number of inhabitants (an arity) of the type. This intuition will\nhowever become tenuous in the presence of negative and fractional\ntypes.\n\n%% \\begin{proposition}[Size 0 is uninhabited]. \n%% \\label{prop:no-zero-values}\n%% There are no values {{v:b}} when {{[^b^]=0}}.\n%% \\end{proposition}\n\n%%%%%%%%%%%%\n\\subsection{Semantics}\n\nThe operational semantics of top-level terms of {{Pi}} is summarized below\n(also see \\cite{infeffects}).  The semantics of applying the primitive\ncombinators to a value is given by the following single-step reductions below.\nSince there are no values of type {{0}}, there are no rules for the impossible\ncases:\n\\begin{scriptsize}\n%subcode{opsem} include main\n%! columnStyle = rlcl\n% zeroi & v & |-->& right v\n% zeroe & (right v) &|-->& v\n% swap+ & (left v) &|-->& right v\n% swap+ & (right v) &|-->& left v \n% assocl+ & (left v1) &|-->& left (left v1)\n% assocl+ & (right (left v2)) &|-->& left (right v2)\n% assocl+ & (right (right v3)) &|-->& right v3 \n% assocr+ & (left (left v1)) &|-->& left v1\n% assocr+ & (left (right v2)) &|-->& right (left v2)\n% assocr+ & (right v3) &|-->& right (right v3)\n% identl* & ((), v) &|-->& v \n% identr* & v &|-->& ((), v) \n% swap* & (v1, v2) &|-->& (v2, v1) \n% assocl* & (v1, (v2, v3)) &|-->& ((v1, v2), v3) \n% assocr* & ((v1, v2), v3) &|-->& (v1, (v2, v3)) \n% dist & (left v1, v3) &|-->& left (v1, v3)\n% dist & (right v2, v3) &|-->& right (v2, v3)\n% factor & (left (v1, v3)) &|-->& (left v1, v3) \n% factor & (right (v2, v3)) &|-->& (right v2, v3)   \n\\end{scriptsize}\nThe operational semantics of the closure conditions are presented in\nthe usual big-step style.\n\\begin{scriptsize}\n%subcode{proof} include main\n%@ ~\n%@@ id v |--> v \n%\n%@ c{dagger} v1 |--> v2\n%@@ (sym c) v1 |--> v2\n%\n%@ c1  v1 |--> v\n%@ c2  v |--> v2\n%@@ (c1(;)c2)  v1 |--> v2\n%---\n%@ c1  v1 |--> v2\n%@@ (c1 (+) c2)  (left v1) |--> left v2\n%\n%@ c2  v1 |--> v2\n%@@ (c1 (+) c2)  (right v1) |--> right v2\n%---\n%@ c1  v1 |--> v3\n%@ c2  v2 |--> v4\n%@@ (c1 (*) c2)  (v1, v2) |--> (v3, v4)\n\\end{scriptsize}\n\nThe type safety of {{Pi}} follows directly from the correspondence\nbetween inductive definitions of the types and the big-step\nsemantics. Previous work also established the following properties:\n\n\\begin{proposition}[Strongly Normalizing]\n\\label{prop:termination-pi} \n{{Pi}} computations always terminate.  \n{{forall. c:b1<->b2, v:b1, exists v':b2.}}  \n{{c v |--> v'}}\n\\end{proposition}\n\n\\begin{proposition}[Logical Reversibility]\n\\label{prop:logrev}\n{{c v |--> v'}} iff \n{{ c{dagger} v' |--> v}}\n\\end{proposition}\n\n\\begin{definition}[ {{c1  = c2}} ]\nWe say {{c1 = c2}} if {{c1:b1<->b2}} and {{c2:b1<->b2}} and for all\n{{v1:b}}, we have {{c1 v1 |--> v2}} iff {{c2 v1 |--> v2}} and {{v2:b2}}.\n\\end{definition}\n\n%%%%%%%%%%%%%%%\n\\subsection{Constructions}\n\\label{sec:pi-constructions}\n\nThe constructions in this section provide a brief overview to writing\nprograms in {{Pi}}. More details maybe found in previous work\n(Sec. 3.3 \\cite{infeffects} and the constructions in \\cite{rc2012}).\n\n\\paragraph*{Booleans, Conditionals and Cloning.} \nWe use the type {{1+1}} to denote {{bool}}, with {{left ()}} as\n{{true}} and {{right ()}} as {{false}}. The combinator\n{{not:bool<->bool}} can be expressed by {{swap+}} at the type\n{{bool}}. Further, given any two combinators {{c1:b1<->b2}} and\n{{c2:b1<->b2}}, we can write the conditional combinator\n{{if_{c1,c2}:bool*b1<->bool*b2}} as \n{{dist(;)((id(*)c1)(+)(id(*)c2))(;)factor}}.\n\n% \\dgm{if-c1-c2}\n\n\\noindent\nIf {{c1 v |--> v'}} and {{c2 v |--> v''}}, we can verify that the\nconditional maps {{if_{c1,c2} (true, v) |--> (true, v')}} and\n{{if_{c1,c2} (false, v) |--> (false, v'')}}.  Several useful\ncombinators follow from this basic construction:\n\n\\begin{enumerate}\n\\item The combinator {{cnot:bool*bool<->bool*bool}} that negates the\n  second input if the first input (called the control wire) is\n  {{true}} may be defined as {{if_{not,id} }}.\n\\item The universal reversible combinator, the Toffoli gate, may be\n  defined as\n  {{if_{cnot,id}:bool*(bool*bool)<->bool*(bool*bool)}}. This can be\n  extended to test {{n}} control wires and we call this combinator\n  {{cnot^n:bool^{n+1}<->bool^{n+1} }}.\n\\item The combinator {{if_{id,not}:bool*bool<->bool*bool}} has the\n  property that it maps {{(x, true)|-->(x, x)}} i.e. if the second bit\n  is fixed to {{true}} it clones the first bit. We can generalize this\n  to clone {{n}} bits and we write\n  {{clone^n:bool^n*bool^n<->bool^n*bool^n}}. The second argument\n  {{bool^n}} must be supplied {{true}} values to correctly simulate\n  cloning.\n\\end{enumerate}\n\n%% Given any combinator {{c : b <-> b}} we can construct a combinator called\n%% {{if_c : bool*b <->bool*b}} in terms of {{c}}, where {{if_c}} behaves like a\n%% one-armed $\\mathit{if}$-expression. If the supplied boolean is {{true}} then\n%% the combinator {{c}} is used to transform the value of type~{{b}}. If the\n%% boolean is {{false}}, then the value of type {{b}} remains unchanged. We can\n%% write down the combinator for {{if_c}} in terms of {{c}} as \n%% {{ dist (;) ((id (*) c) (+) id) (;) factor }}.\n\n%% \\noindent The diagram below shows the input value of type {{(1+1)*b}}\n%% processed by the distribute operator {{dist}}, which converts it into a value\n%% of type {{(1*b)+(1*b)}}. In the {{left}} branch, which corresponds to the\n%% case when the boolean is {{true}} (i.e. the value was {{left ()}}), the\n%% combinator~{{c}} is applied to the value of type~{{b}}. The right branch\n%% which corresponds to the boolean being {{false}} passes along the value of\n%% type {{b}} unchanged.\n\n%% \\begin{center}\n%% \\scalebox{1.0}{\n%% %%subcode-line{pdfimage}[diagrams/if_c.pdf]\n%% \\includegraphics{diagrams/thesis/cnot.pdf}\n%% }\n%% \\end{center}\n\n%% % We will be seeing many more such wiring diagrams in this paper and it is\n%% % useful to note some conventions about them. Wires indicate a\n%% % value that can exist in the program. Each wire, whenever possible, is\n%% % annotated with its type and sometimes additional information to help clarify\n%% % its role. When multiple wires run in parallel, it means that those values\n%% % exist in the system at the same time, indicating pair types. When there is a\n%% % disjunction, we put a {{+}} between the wires. \n%% % Combinators for distribution {{dist}} and factoring {{factor}}\n%% % are represented as triangles with their operator symbols in them. Other\n%% % triangles may be used and, in each case, types or labels will be used to\n%% % clarify their roles. Finally, we don't draw boxes for combinators such as\n%% % {{id}}, commutativity, and associativity, but instead just shuffle the wires\n%% % as appropriate.\n\n%% The combinator {{if_{not} }} has type {{bool*bool<->bool*bool}} and\n%% negates its second argument if the first argument is {{true}}. This\n%% gate {{if_{not} }} is often referred to as the {{cnot}} gate. An\n%% equivalent construction that is useful is {{else_{not} }} where we\n%% negate the second argument only if the first is {{false}}. \n\n%% Similarly, we can iterate the construction of {{if_c}} to check several\n%% bits. The gate {{if_{cnot} }}, which we may also write as {{if^2_{not} }},\n%% checks two booleans and negates the result wire only if they are both\n%% {{true}}. The gate {{if^2_{not} }} is well known as the Toffoli gate and is a\n%% universal reversible gate. We can generalize this construction to\n%% {{if^n_{not} }} which checks {{n}} bits and negates the result wire only if\n%% they are all {{true}}.\n\n%% %%\n%% \\paragraph*{Cloning.}\n%% Although cloning is generally not allowed in reversible languages, it is\n%% possible at the cost of having additional constant inputs. For example,\n%% consider the gate {{else_{not} }}. Generally, the gate maps\n%% {{(false,a)}} to {{(false,not a)}} and {{(true,a)}} to {{(true,a)}}. Focusing\n%% on the cases in which the second input is {{true}}, we get that the gate maps\n%% {{(false,true)}} to {{(false,false)}} and {{(true,true)}} to {{(true,true)}},\n%% i.e., the gate clones the first input. A circuit of {{n}} parallel\n%% {{else_{not} }} gates can hence clone {{n}} bits.  They also consume {{n}}\n%% {{true}} inputs in the process.  Let us call this construction\n%% {{clone^n_{bool} }}.\n\n%%%%%%%%%%%%\n\\subsection{Small Step Semantics}\n\nThe reductions for the primitive isomorphisms above are exactly the same as\nhave been presented before~\\cite{infeffects}. The reductions for the closure\ncombinators are however presented in a small-step operational style using the\nfollowing definitions of evaluation contexts and machine states:\n\n\\begin{scriptsize}\n%subcode{bnf} include main\n% Combinator Contexts, C = [] | Fst C c | Snd c C \n%                  &|& LeftT C c v | RightT c v C \n%                  &|& LeftP C c | RightP c C \n% Machine states = <c, v, C> | {[c, v, C]}\n% Start state = <c, v, []> \n% Stop State = {[c, v, []]}\n\\end{scriptsize}\nThe machine transitions below track the flow of particles through a\ncircuit. The start machine state, {{<c,v,[]>}}, denotes the\nparticle~{{v}} about to be evaluated by the circuit {{c}}. The end\nmachine state, {{[c, v, [] ]}}, denotes the situation where the particle\n{{v}} has exited the circuit {{c}}.\n\n\\begin{scriptsize}\n%subcode{opsem} include main\n%! columnStyle = rclr\n% <iso, v, C> &|-->& {[iso, v', C]} & (1)\n% & & where iso v |--> v' &\n% <c1(;)c2, v, C> &|-->& <c1, v, Fst C c2> & (2) \n% {[c1, v, Fst C c2]} &|-->& <c2, v, Snd c1 C> & (3) \n% {[c2, v, Snd c1 C]} &|-->& {[ c1(;)c2, v, C ]} & (4) \n% <c1(+)c2, left v, C> &|-->& <c1, v, LeftP C c2> & (5) \n% {[ c1, v, LeftP C c2 ]} &|-->& {[c1 (+) c2, left v, C ]} & (6)\n% <c1(+)c2, right v, C> &|-->& <c2, v, RightP c1 C> & (7)\n% {[ c2, v, RightP c1 C ]} &|-->& {[c1 (+) c2, right v, C ]} & (8)\n% <c1(*)c2, (v1, v2), C> &|-->& <c1, v1, LeftT C c2 v2> & (9)\n% {[ c1, v1, LeftT C c2 v2 ]} &|-->& <c2, v2, RightT c1 v1 C> & (10) \n% {[ c2, v2, RightT c1 v1 C ]} &|-->& {[ c1 (*) c2, (v1, v2), C ]} & (11)\n\\end{scriptsize}\nRule (1) describes evaluation by a primitive isomorphism. Rules (2), (3) and\n(4) deal with sequential evaluation. Rule (2) says that for the value {{v}}\nto flow through the sequence {{c1 (;) c2}}, it should first flow through\n{{c1}} with {{c2}} pending in the context ({{Fst C c2}}). Rule (3) says the\nvalue {{v}} that exits from {{c1}} should proceed to flow\nthrough~{{c2}}. Rule (4) says that when the value {{v}} exits {{c2}}, it also\nexits the sequential composition {{c1(;)c2}}. Rules (5) to (8) deal with \n{{c1 (+) c2}} in the same way. In the case of sums, the shape of the value,\ni.e., whether it is tagged with {{left}} or {{right}}, determines whether\npath {{c1}} or path {{c2}} is taken. Rules (9), (10) and (11) deal with \n{{c1 (*) c2}} similarly. In the case of products the value should have the\nform {{(v1, v2)}} where {{v1}} flows through {{c1}} and {{v2}} flows through\n{{c2}}. Both these paths are entirely independent of each other and we could\nevaluate either first, or evaluate both in parallel. In this presentation we\nhave chosen to follow {{c1}} first, but this choice is entirely arbitrary.\n\nThe interesting thing about the semantics is that it represents a reversible\nabstract machine. In other words, we can compute the start state from the\nstop state by changing the reductions {{|-->}} to run backwards\n{{<--|}}. When running backwards, we use the isomorphism represented by a\ncombinator {{c}} in the reverse direction, i.e., we use the adjoint\n{{c{dagger}}}.\n\n\\begin{proposition}[Correspondence]\n  Evaluation in the small-step evaluator corresponds to evaluation in\n  the natural semantics.\n\n  {{c v |--> v'}} iff {{<c, v, []> |-->* [c, v', [] ]}}\n\\end{proposition}\n\\begin{proof}\n  To prove the above, we first show that a more general lemma holds,\n  namely that: {{c v |--> v'}} iff {{<c, v, C> |-->* [c, v', C ]}}.\n\n  To show the left-to-right direction we proceed by induction on the\n  derivation of {{c v |--> v'}}. In the case of primitive isomorphisms\n  the condition holds trivially. In the case of composition, we work\n  out the case of {{c1+c2}} as an example. Given {{c1 +c2 v |--> v'}}\n  we have to show that there is a small step derivation sequence that\n  matches it. Here {{v:b1+b2}} can be of the form {{left v1}} or\n  {{right v2}}. Assuming {{left v1}}, we have: \n\n%subcode{proof} include main\n%@ c1 v1 |--> v1' ==> <c1, v1, C'> |-->* {[c1,v1',C']}\n%@@ c1+c2 (left v1) |--> left v1' ==> ? \n\nChoosing {{C' =LeftP c2 C}}, we have the required derivation sequence: \n{{ <c1+c2, left v1, C> |--> <c1,v1,LeftP c2 C> |-->* {[c1,v1', LeftP c2 C]} |--> {[c1+c2,left v1',C]} }}. The proof follows similarly for the {{right v2}} case.  \n\nTo show the right-to-left direction we proceed by induction of the\nsequence of {{|-->*}} derivations. Again the case for primitive\nisomorphisms follows trivially. Taking the case of {{c1+c2}} we are\nrequired to show that given a sequence \n{{<c1+c2,v,C> |-->* {[c1+c2, v', C]} }} there is a derivation tree for\n{{c1+c2 v |--> v'}}. In the case that {{v:v1+b2}} has the form\n{{left~v1}}, this follows by observing that the given sequence must have the form\n{{ <c1+c2, left v1, C> |--> <c1,v1,LeftP c2 C> |-->* {[c1,v1', LeftP c2 C]} |--> {[c1+c2,left v1',C]} }}. \nFor the strictly smaller inner subsequence by induction we have\n{{c1~v1 |--> v1'}} which lets us complete the derivation of\n{{c1+c2~(left v1) |--> left v1'}}. The {{right v2}} follows similarly. \n\n\\end{proof}\n\nConsequently the small step semantics is logically reversible and\nstrong normalizing. \n\n\\begin{proposition}[Type Safety]\n  \n\\end{proposition}\n\n% \\roshan{We really have to rethink this prop in the presence of\n%   negatives and fractionals. With negatives, the program can actually\n%   end at the beginning of the circuit -- i.e. the program {{c:b1<->b2}}\n%   can stop with a value of type {{b1}}. With fractionals, there can be\n%   several values of type {{b2}} produced for a value of type {{b1}}. }\n\n% \\begin{proposition}[Groupoid]\n% \\label{prop:groupoid}\n% {{Pi}} is a groupoid. \n% \\end{proposition}\n\n% \\begin{proposition}\n% \\label{prop:category}\n% {{Pi}} is a dagger symmetric monoidal category. \n% \\end{proposition}\n\n%%%%%%%%%%%%\n\\subsection{Graphical Language}\n\nThe syntactic notation above is often obscure and hard to read.\nFollowing the tradition established for monoidal\ncategories~\\cite{springerlink:10.1007/978-3-642-12821-94}, we present\na graphical language that conveys the intuitive semantics of the\nlanguage.\n\nThe general idea of the graphical notation is that combinators are modeled by\n``wiring diagrams'' or ``circuits'' and that values are modeled as\n``particles'' or ``waves'' that may appear on the wires. Evaluation therefore\nis modeled by the flow of waves and particles along the wires.\n\n%% In fact, when talking about {{Pi}} circuits, we will often use the\n%% words {{value}} and {{particle}} interchangeably.\n\n\\begin{itemize}\n\\item The simplest sort of diagram is the {{id : b <-> b}} combinator which\n  is simply represented as a wire labeled by its type {{b}}, as shown on the\n  left. In more complex diagrams, if the type of a wire is obvious from the\n  context, it may be omitted. When tracing a computation, one might imagine a\n  value {{v}} of type {{b}} on the wire, as shown on the right.\n\n  \\begin{multicols}{2}\n\\begin{center}\n\\scalebox{0.95}{\n%%subcode-line{pdfimage}[diagrams/thesis/b-wire.pdf]\n\\includegraphics{diagrams/thesis/b-wire.pdf}\n}\n\\end{center}\n\\begin{center}\n\\scalebox{0.95}{\n%%subcode-line{pdfimage}[diagrams/thesis/b-wire.pdf]\n\\includegraphics{diagrams/thesis/b-wire-value.pdf}\n}\n\\end{center}\n  \\end{multicols}\n\n\\item The product type {{b1*b2}} may be represented using either one wire\n  labeled {{b1*b2}} or two parallel wires labeled {{b1}} and {{b2}}. In the\n  case of products represented by a pair of wires, when tracing execution\n  using particles, one should think of one particle on each wire or\n  alternatively as in folklore in the literature on monoidal categories as a\n  ``wave.''\n\\begin{multicols}{2}\n\\begin{center}\n\\scalebox{0.95}{\n%%subcode-line{pdfimage}[diagrams/thesis/pair-one-wire.pdf]\n\\includegraphics{diagrams/thesis/product-one-wire.pdf}\n}\n\\end{center}\n\\begin{center}\n\\scalebox{0.95}{\n\\includegraphics{diagrams/thesis/product-one-wire-value.pdf}\n}\n\\end{center}\n\\end{multicols}\n\\begin{multicols}{2}\n\\begin{center}\n\\scalebox{0.95}{\n%%%subcode-line{pdfimage}[diagrams/thesis/pair-of-wires.pdf]\n\\includegraphics{diagrams/thesis/product-two-wires.pdf}\n}\n\\end{center}\n\\begin{center}\n\\scalebox{0.95}{\n\\includegraphics{diagrams/thesis/product-two-wires-value.pdf}\n}\n\\end{center}\n\\end{multicols}\n\n\\item Sum types may similarly be represented by one wire or using\n  parallel wires with a {{+}} operator between them. When tracing the\n  execution of two additive wires, a value can reside on only one of the two\n  wires.\n\\begin{multicols}{2}\n\\begin{center}\n\\scalebox{0.95}{\n%%subcode-line{pdfimage}[diagrams/thesis/sum-one-wire.pdf]\n\\includegraphics{diagrams/thesis/sum-one-wire.pdf}\n}\n\\end{center}\n\\begin{center}\n\\scalebox{0.95}{\n\\includegraphics{diagrams/thesis/sum-two-wires-left-value.pdf}\n}\n\\end{center}\n\\end{multicols}\n\\begin{multicols}{2}\n\\begin{center}\n\\scalebox{0.95}{\n%%subcode-line{pdfimage}[diagrams/thesis/sum-of-wires.pdf]\n\\includegraphics{diagrams/thesis/sum-two-wires.pdf}\n}\n\\end{center}\n\\begin{center}\n\\scalebox{0.95}{\n\\includegraphics{diagrams/thesis/sum-two-wires-right-value.pdf}\n}\n\\end{center}\n\\end{multicols}\n\n%% \\item\n%% When representing complex types like {{(b1*b2)+b3}} some visual\n%% grouping of the wires may be done to aid readability. The exact type\n%% however will always be clarified by the context of the diagram.\n\n%% \\begin{center}\n%% \\scalebox{0.95}{\n%% %subcode-line{pdfimage}[diagrams/thesis/complex-type-crop.pdf]\n%% }\n%% \\end{center}\n\n\\item Associativity is implicit in the graphical language. Three parallel\n  wires represent {{b1*(b2*b3)}} or {{(b1*b2)*b3}}, based on the context.\n\\begin{center}\n\\scalebox{0.95}{\n%%subcode-line{pdfimage}[diagrams/thesis/associate.pdf]\n\\includegraphics{diagrams/thesis/assoc.pdf}\n}\n\\end{center}\n\n\\item Commutativity is represented by crisscrossing wires.\n\\begin{multicols}{2}\n\\begin{center}\n\\scalebox{0.95}{\n%%subcode-line{pdfimage}[diagrams/thesis/swap-pair.pdf]\n\\includegraphics{diagrams/thesis/swap_times.pdf}\n}\n\\end{center}\n\\begin{center}\n\\scalebox{0.95}{\n%%subcode-line{pdfimage}[diagrams/thesis/swap-sum.pdf]\n\\includegraphics{diagrams/thesis/swap_plus.pdf}\n}\n\\end{center}\n\\end{multicols}\n\nBy visually tracking the flow of particles on the wires, one can\nverify that the expected types for commutativity are satisfied.\n\n\\begin{multicols}{2}\n\\begin{center}\n\\scalebox{0.95}{\n\\includegraphics{diagrams/thesis/swap_times_value.pdf}\n}\n\\end{center}\n\\begin{center}\n\\scalebox{0.95}{\n\\includegraphics{diagrams/thesis/swap_plus_value.pdf}\n}\n\\end{center}\n\\end{multicols}\n\n\\item The morphisms that witness that {{0}} and {{1}} are the additive and\n  multiplicative units are represented as shown below. Note that since there\n  is no value of type 0, there can be no particle on a wire of type {{0}}.\n  Also since the monoidal units can be freely introduced and eliminated, in\n  many diagrams they are omitted and dealt with explicitly only when they are\n  of special interest.\n\\begin{multicols}{2}\n\\begin{center}\n\\scalebox{0.95}{\n%%subcode-line{pdfimage}[diagrams/thesis/identr1.pdf]\n\\includegraphics{diagrams/thesis/uniti.pdf}\n}\n\\end{center}\n\\begin{center}\n\\scalebox{0.95}{\n%%subcode-line{pdfimage}[diagrams/thesis/identl1.pdf]\n\\includegraphics{diagrams/thesis/unite.pdf}\n}\n\\end{center}  \n\\end{multicols}\n\\begin{multicols}{2}\n\\begin{center}\n\\scalebox{0.95}{\n%%subcode-line{pdfimage}[diagrams/thesis/identr0.pdf]\n\\includegraphics{diagrams/thesis/zeroi.pdf}\n}\n\\end{center}\n\\columnbreak\n\\begin{center}\n\\scalebox{0.95}{\n%%subcode-line{pdfimage}[diagrams/thesis/identl0.pdf]\n\\includegraphics{diagrams/thesis/zeroe.pdf}\n}\n\\end{center}\n\\end{multicols}\n\n\\item Finally, distributivity and factoring are represented using the dual\n  boxes shown below:\n\\begin{multicols}{2}\n\\begin{center}\n  \\includegraphics{diagrams/thesis/dist.pdf}\n\\end{center}\n\\begin{center}\n  \\includegraphics{diagrams/thesis/factor.pdf}\n\\end{center}\n\\end{multicols}\n\nDistributivity and factoring are interesting because they represent\ninteractions between sum and pair types. Distributivity should\nessentially be thought of as a multiplexer that redirects the flow of\n{{v:b}} depending on what value inhabits the type {{b1+b2}}, as shown\nbelow. Factoring is the corresponding adjoint operation.\n\n\\begin{multicols}{2}\n\\begin{center}\n  \\includegraphics{diagrams/thesis/dist-wire-value1.pdf}\n\\end{center}\n\\begin{center}\n  \\includegraphics{diagrams/thesis/dist-wire-value2.pdf}\n\\end{center}\n\\end{multicols}\n\n\\item Combinators can be composed is series ({{c1 (;) c2}}) or\n  parallel. There are two forms of parallel composition -- combinators\n  can be combined additively {{c1(+)c2}} (shown on the left) or\n  multiplicatively {{c1(*)c2}} (shown on the right).\n\n  \\begin{multicols}{2}\n\\dgm{c1c2_par_sum}\n\\dgm{c1c2_par_times}\n  \\end{multicols}\n\\dgm{c1c2_seq}    \n\n\\end{itemize}\n\n%% \\noindent \n%% \\textit{Example.}  We use the type {{bool}} as a shorthand to denote\n%% the type {{1+1}} and use {{left ()}} to be {{true}} and {{right ()}}\n%% to be {{false}}. The following combinator is represented by the given\n%% diagram:\n\n%% {{c : b * bool <-> b + b}}\n\n%% {{c = swap* (;) dist (;) (identl* (+) identl*)}}\n\n%% \\begin{center}\n%% \\scalebox{0.95}{\n%% %%subcode-line{pdfimage}[diagrams/thesis/example1-crop.pdf]\n%% \\includegraphics{diagrams/thesis/example1.pdf}\n%% }\n%% \\end{center}\n\n%%%%%%%%%%%%%%%%\n\\subsection{Categorical Structure}\n\nWe present the categorical structure with minimum commentary. More\ndetails may be found in excellent references such as Barr and Wells\n[CITE] and Selinger \\cite{springerlink:10.1007/978-3-642-12821-94}.\nFor brevity, we don't re-state standard categorical definitions and\nsubsequently present their {{Pi}} equivalents. Instead, we directly\nstate categorical definitions in terms of {{Pi}} types and\ncombinators, and provide appropriate references to the former. For\nexample, associativity is denoted by the Greek letter $\\alpha$ (and\n$\\alpha^{-1}$) in standard definitions, whereas we use {{assocl*}}\n(and {{assocr*}}).\n\n\\begin{lemma}[{{Pi}} is a category]\n  The category {{Pi}} has the types {{b}} as objects and equivalence\n  classes of well-typed combinators {{b1<->b2}} as morphisms. One can\n  check:\n  \\begin{enumerate}\n  \\item Every object {{b}} has an identity morphism {{id : b <->b}}.\n  \\item Composition {{g (o) f}} of morphisms {{f:b1 <->b2}} and\n    {{g:b2<->b3}} is given by sequencing {{f (;) g}}. \n  \\item Associativity of composition follows from operational\n    equivalence of {{f(;)(g(;)h)}} and {{(f(;)g)(;)h}} (where\n    {{h:b3<->b4}}). \n\n    Assuming {{v1:b1}}, {{v2:b2}}, {{v3:b3}}, {{v4:b4}},\n    {{f~v1|-->v2}}, {{g v2 |--> v3}} and {{h~v3 |--> v4}}, one can\n    check:\n\n\\vspace{-20pt}\n    \\begin{multicols}{2}\n      \\begin{scriptsize}\n        \n%subcode{proof} include main\n%@@ f v1 |--> v2\n%@ g v2 |--> v3\n%@ h v3 |--> v4\n%@@ g (;) h  v2 |--> v4\n%@@@ f (;) (g (;) h) v1 |--> v4\n~\n%subcode{proof} include main\n%@ f v1 |--> v2\n%@ g v2 |--> v3\n%@@ f (;) g v1 |--> v3\n%@@ h v3 |--> v4\n%@@@ (f (;) g) (;) h v1 |--> v4\n\n      \\end{scriptsize}\n    \\end{multicols}\n\n  \\item Composition respects identity: {{id (;) f = f}} and {{g(;)id=g}}.\n  \\end{enumerate}\n\\end{lemma}\n\n\\begin{lemma}[Dagger]\n  {{Pi}} is a dagger category, where every morphism {{f : b1<->b2}}\n  has the adjoint {{f^{dagger}:b2 <->b1}}. The following properties\n  hold (where {{g : b2 <-> b3}}): \n  \\begin{enumerate}\n  \\item {{id^{dagger} = id : b <-> b}}.\n  \\item {{(f (;) g)^{dagger} = g^{dagger} (;) f^{dagger}: b3 <-> b1}}.\n  \\item {{f^{dagger dagger} = f : b1 <-> b2}}.\n  \\end{enumerate}\n\\end{lemma}\n\n\\begin{lemma}[Symmetric Monoidal (+, 0)]\n  {{Pi}} is a symmetric monoidal category with tensor {{+}} and\n  monoidal unit {{0}}. The monoidal operation on morphisms is the\n  additive composition of combinators {{c1 (+) c2}}.\n\n  \\begin{proof}\n    To establish that category is monoidal one must show isomorphisms\n    \\begin{enumerate}\n    \\item {{b1 + (b2 + b3) <-> (b1 +b2) + b3}} given by {{assocl+}}.\n    \\item {{0 + b <-> b}} given by {{zeroe}}.\n    \\item {{b + 0 <-> b}} given by {{swap+ (;) zeroe}}.\n    \\item We need to check that {{+}} is a bifunctor. \n      \\begin{enumerate}\n      \\item {{id_{b1<->b1}(+)id_{b2<->b2} = id_{b1+b2<->b1+b2} }}.\n      \\item {{(f(+)g)(;)(j(+)k) = (f (;) j) (+) (g (;) k)}}.\n      \\end{enumerate}\n    \\item We need to check the naturality of {{assocl+}}, {{zeroe}} and\n      {{swap+(;)zeroe}}.\n      \\begin{enumerate}\n      \\item {{assocl+ (;) ((f (+)g) (+) h) = (f (+)(g (+) h)) (;) assocl+}}.\n      \\item {{zeroe (;) f = (id (+) f) (;) zeroe}}.\n      \\item {{(swap+ (;) zeroe) (;) f = (f (+) id) (;) (swap+ (;) zeroe)}}.\n      \\end{enumerate}\n    \\item Satisfy certain coherence conditions which are usually\n      called the ``pentagon'' and ``triangle'' axioms (see Sec 3.1\n      \\cite{springerlink:10.1007/978-3-642-12821-94})\n    \\end{enumerate}\n\n    The last three points require checking equality of combinators by\n    writing out their derivation trees as we did in the case of\n    associativity of sequential composition. To show symmetry, we need\n    a braiding operation {{b1+b2 <-> b2+b1}} which is given by\n    {{swap+}} (see Sec. 3.3 and 3.5\n    \\cite{springerlink:10.1007/978-3-642-12821-94}).\n\n    \\begin{enumerate}\n    \\item The braiding must satisfy two ``hexagon'' axioms.\n    \\item The braiding is self inverse,\n      {{swap+_{b1+b2}=(swap+_{b2+b1})^{dagger} }}.\n    \\end{enumerate}\n\n\n  \\end{proof}\n\n\\end{lemma}\n\n\\begin{lemma}[Symmetric Monoidal {{(*, 1)}}]\n  {{Pi}} is a symmetric monoidal category over the tensor {{*}} and\n  unit {{1}}. The details mirror those of the {{(0, +)}} monoid.\n\\end{lemma}\n\n\\noindent\nSome technical and pedantic comments are due at this point. \n\n\\begin{itemize}\n\\item We have established the categorical structure of {{Pi}} as a\n  dagger symmetric monoidal category with two monoidal structures,\n  {{(0, +)}} and {{(*, 1)}}. In Sec. \\ref{sec:int} we will see that a\n  {{trace}} operator can be admitted in this category without any\n  change of expressiveness.\n\n\\item To be pedantic, what we have shown is that the ``term model'' of\n  {{Pi}} that follows from the extensional operational equality of\n  combinators has the requisite categorical structure. A consequence\n  is that the ``wiring diagrams'' of {{Pi}} correspond closely with ``string\n  diagrams'' developed for categories.\n\n  To establish the later rigorously, we will need to show when it is\n  valid to slide one wire over the other and that equivalent diagrams\n  for syntactically different combinators such as\n  {{(f(+)g)(;)(j(+)k)}} and {{(f(;)j)(+)(g(;)k)}} do respect\n  operational equivalence.  We don't formalize the graphical notation\n  in this work. Joyal et. al's work on ``planar isotopy'' and\n  Selinger's survey \\cite{springerlink:10.1007/978-3-642-12821-94}\n  show how this has been addressed before in the categorical\n  setting. In the absence of any prior knowledge of category theory\n  however, our wiring diagrams may be read as the ``flow of types'' in\n  a combinator-circuit.\n\n\\item By definition, in {{Pi}} every morphism is an isomorphism --\n  this makes {{Pi}} a groupoid.\n\n\\item The category {{Pi}} has no initial and terminal objects. The\n  objects {{0}} and {{1}} would be initial and terminal if we admitted\n  all functions (as in the category {{CatSet}}).\n\n\\item The category {{Pi}} has neither categorical products, nor\n  categorical co-products, i.e. {{*}} and {{+}} are merely monoidal\n  tensors. This follows from the fact that injection and projection\n  maps are not isomorphisms.\n\\end{itemize}\n\nWhile we don't do so in this work, if we extend {{Pi}} with products\nand co-products (say through the addition of information effects) it\nis conceivable that part of its structure collapses. This sort of\ncollapse, while catastrophic for algebraic structures (effectively\ntrivializing them), still retains some interest in computing, because\nin computing we are interested in the specific operational nature (the\ncomputational content, so to speak) of the morphisms. Anecdotal evidence\nfollows from the fact several real-world programming language have\ninconsistent type systems. blah blah blah...\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Fractional Types : {{PiEE*}} }\n\\label{sec:int}\n\n\nIn arithmetic the main identity satisfied by fractional numbers is that for\nnon-zero {{b}}, we have {{b * 1/b = 1}}. Accommodating this identity in the\nsetting of {{Pi}} requires us to find an isomorphism between the types {{1}}\nand {{b * 1/b}} (where {{b}} is not equivalent to {{0}}). Formally, we move\nfrom the setting of symmetric monoidal categories to that of compact closed\ncategories.\n\n%subcode{bnf} include main\n% Value Types, b = 0 | 1 | b + b | b * b  | 1/b\n% Values, v = () | left v | right v | (v, v) | 1/v\n%\n% Isomorphisms, iso &=& ... | eta* | eps*\n\n\n\\paragraph*{Traces and the Int-Construction.}\nFor a traced symmetric monoidal category, the Int-construction of\nJoyal, Street and Verity \\cite{joyal1996traced} gives us a way of\nconstructing a compact closed category. This is the obvious first\nthing to try for a duality in this setting.\n\n%subcode{proof} include main\n%@ c : b1 + b2 <-> b1 + b3\n%@@ trace c : b2 <-> b3  \n\n%% \\begin{center}\n%%   \\includegraphics{diagrams/thesis/trace_plus.pdf}\n%% \\end{center}\n\nShow that the int construction does not preserve the {{*}} tensor. We\nneed a duality that preserves both tensors.\n\n\\paragraph*{No division by zero.} \nThe important side-condition on the types not captured by the syntax\nabove is that there are no types of the form {{1/b}}, where\n{{[^b^]=0}} (see Def. \\ref{def:size} and \\ref{def:size-frac}\nbelow). This eliminates terms of the form {{1/0}}, {{1/(0+0)}},\n{{1/(0*b)}} etc, from being treated as valid {{b}} types. Intuitively,\nthis translates into the familiar restriction that there is no\ndivision by 0 in arithmetic, nor in algebraic fields.\n\n\\begin{multicols}{2}  \n%subcode{opsem} include main\n% eta* &: 1 <-> (1/b) * b :& eps*\n\n%subcode{proof} include main\n%@ |- v : b\n%@@ |- 1/v : 1/b\n\\end{multicols}\n\nFor the graphical language, we visually represent {{eta*}}, and\n{{eps*}} as U-shaped connectors. On the left below is {{eta*}} showing\nthe map and {{1}} to {{1/b * b}}.  On the right is {{eps*}} showing\nthe map from {{1/b * b}} to~1. Even though the diagrams below show the\n{{1}} wires for completeness, later diagrams will always drop them in\ncontexts where they can be implicitly introduced and eliminated.\n\\begin{multicols}{2}\n\\begin{center}\n  \\includegraphics{diagrams/eta_times.pdf}\n\\end{center}\n  \n\\begin{center}\n  \\includegraphics{diagrams/eps_times.pdf}\n\\end{center}\n\\end{multicols}\n\nThe usual interpretation of {{b1*b2}} we have both a value of type\n{{b1}} and a value of type {{b2}}. This interpretation is maintained\nin the presence of fractionals. Hence an {{eta* : 1 <-> (1/b) * b}} is\nto be viewed as a fission point for a value of type {{b}} and its\nmultiplicative inverse {{1/b}}. \n%% Operationally, this corresponds to the\n%% creation of two values {{alpha}} and {{1/alpha}} where {{alpha}} is a\n%% fresh logic variable. The operator {{eps*}} then becomes a unification\n%% site for these logic variables:\n\n\\begin{multicols}{2}\n\\begin{center}\n\\scalebox{1.5}{\n  \\includegraphics{diagrams/eta_times1.pdf}\n}\n\\end{center}\n\n\\begin{center}\n\\scalebox{1.5}{\n  \\includegraphics{diagrams/eps_times1.pdf}\n}\n\\end{center}  \n\\end{multicols}\n\nNegative Information and Measurements. \n\n\\begin{definition}[Size of a type.] \n\\label{def:size-frac}\nThe definition of size, {{[^ b ^]}}, is extended to include\nfractionals as {{[^1 / b ^] = 1/[^ b ^]}}.\n\\end{definition}\n\n%%%%%%%%%%%%\n\\subsection{Semantics}\n\nThe operational semantics for {{PiEE*}} involve the addition of the\nfollowing two rules to the small-step operational semantics of {{Pi}}.\n\n%subcode{opsem} include main\n%! columnStyle = rclr\n% <eta*, (), C> &|-->& forall v:b.{[eta*, (1/v, v), C]} & (eta*)\n% <eps*, (1/v,v), C> &|-->& {[eps*, (), C]} & (eps*) \n\nThe rule {{(eta*)}} is different from other rules encountered before\ndue to the {{forall v:b}} quantification. It is to be understood as\nfollows: when the machine encounters an {{eta*}} reduction it\nnon-deterministically replicates into several machine states (or\nworlds). Each world is seeded by a unique value {{v:b}}, where {{b}}\ncomes from {{eta*:1 <-> 1/b * b}}.  For example, at\n{{eta*:1<->1/bool*bool}}, we would have two possible machine\nstates:\n\n%subcode{opsem} include main\n%! columnStyle = rclr\n% <eta*, (), C> &|-->& {[eta*, (1/true, true), C]}\n% and  &|-->& {[eta*, (1/false, false), C]} \n\n\n\nThe rule {{(eps*)}} is straightforward : when given a tuple\n{{(1/v,v):1/b * b}} where {{eps*:1/b*b <-> 1}} the result is\n{{()}}. The machine is undefined for cases where where the input is\n{{(1/v',v):1/b*b}} and {{v' /= v}}.\n\n\\paragraph*{Annihilation.} \nA consequence of the semantics is that they admit computations that\nare undefined. For instance consider, where {{not : bool <-> bool}}. \n\n{{eta* (;) (id (*) not) (;) eps* : 1 <-> 1}}\n\n\\noindent\nTracing the execution of this circuit gives us: \n\n%subcode{opsem} include main\n%! columnStyle = rllr\n% & & <eta* (;) (id (*) not) (;) eps*, (), []>\n% & |-->* & <eta*, (), Fst [] (id (*) not) (;) eps*>\n% (1) & |--> & [eta*, (1/true, true), Fst [] (id (*) not) (;) eps*] \n% & |-->* & <not, true, RightT id 1/true (Fst (Snd~eta* []) ~eps*)> \n% & |-->* & [not, false, RightT id 1/true (Fst (Snd~eta* []) ~eps*)] \n% & |-->* & [eps*, (1/true, false), Snd (id (*) not) (Snd~eta* [])]\n% & |--> & undefined\n% (2) & |--> & [eta*, (1/false, false), Fst [] (id (*) not) (;) eps*] \n% & |-->* & <not, false, RightT id 1/false (Fst (Snd~eta* []) ~eps*)> \n% & |-->* & [not, true, RightT id 1/false (Fst (Snd~eta* []) ~eps*)] \n% & |-->* & [eps*, (1/false, true), Snd (id (*) not) (Snd~eta* [])]\n% & |--> & undefined\n\n%% \\roshan{Maybe replace the annihilation example with union and\n%%   difference.}\n\n\\begin{proposition}[Type Safety]\n  \n\\end{proposition}\n\n\\begin{proposition}[Strong Normalizing]\n  \n\\end{proposition}\n\n\\noindent\nWe use {{c v |-->* v'}} as a shorthand for the reduction sequence\n{{<c,v,[]>|-->*{[c,v',[] ]} }}.\n\n\\begin{definition}[eval(c,v)]\n\nGiven a combinator {{c:b1<->b2}} and a value {{v:b1}} we define\n{{eval(c, v)}} to be the set of values {{v':b}} such that there is\nsmall-step reduction sequence {{c v |-->* v'}}.\n\n$eval(c, v) = \\{v'~|~ c~ v\\mapsto^{\\asterix} v' \\} $\n\\end{definition}\n\nThe above definition implies that combinators {{c:b1<->b2}} denote\nrelations between the sets {{b1}} and {{b2}}, i.e.\n{{c:b1<->b2={|(v,v') | v:b2, v':b2 and c v |-->* v'|} }}.  The\ndefinition of combinator equality reflects the fact that combinators\ndenote relations.\n\n\\begin{definition}[{{c1 = c2}}]\nWe say that {{c1 = c2}}, for combinators {{c1:b1<->b2}} and\n{{c2:b1<->b2}} iff they denote the same relation. Equivalently,\n{{forall v:b1. eval(c1, v) = eval(c2, v)}}.\n\\end{definition}\n\n\\begin{proposition}[Logical Reversibility]\n\\label{prop:logrev2} ~\n\n{{c v |-->* v'}} iff {{ c{dagger} v' |-->* v}}\n\\end{proposition}\n\nIn other words, for any execution path from {{v}} to {{v'}} in {{c}},\n{{c{dagger} }} has an execution path from {{v'}} to {{v}}.\nIntuitively this maybe understood as follows: For every particular\nexecution sequence {{eta*}} transforms {{()}} into particular\n{{(1/v,v)}}. On reverse execution the adjoint {{eps*}} will transform\n{{(1/v,v)}} back to {{()}}.  Logical reversibility implies that\n{{c^^^}} denotes the inverse relation that {{c}} denotes, i.e.\n{{c^^^={|(v',v)~|~(v,v') elem c|} }}.\n\n% \\roshan{This probably needs rigorous proof.}\n\n\\paragraph*{Union.}\nThe union of the two relations {{c1:b1<->b2}} and {{c2:b1<->b2}} is\nexpressed by {{trace* if_{c1,c2} :b1<->b2}} (see Sec.\n\\ref{sec:pi-constructions} for {{if_{c1,c2} }} and\nSec. \\ref{sec:frac-constructions} for {{trace*}}). Intersection can be\nexpressed by ``controlled-annihilation'' detailed in\nSec. \\ref{sec:sat-solver}.\n\n%% \\roshan{Should we show completeness -- i.e. that every relation is\n%%   expressible? We can. But should we?}\n\n%%%%%%%%%%%\n\\subsection{Categorical Structure}\n\nLike {{Pi}}, {{PiEE*}} is a commutative bimonoidal category.\nSymmetric monoidal categories where every object had a dual object and\nwhere dualizing preserves the monoidal tensor are referred to as\ncompact closed categories. Since division is defined only for types of\nnon-zero size, not all objects have duals.  We show that {{PiEE*}}\nrespects compact closed structure for non-zero objects. We introduce\nthe term ``locally compact closed'' to refer to this notion.\n\nIt is important to note that in a compact closed category, the\ndualizing action, usually denoted $(-)^\\asterix$, is a contravariant\nfunctor. However {{PiEE*}} is not compact closed and {{1/(-)}} is not\na functor specifically because division is not defined on 0 sized\ntypes.\n\n\\roshan{This is an important question -- is {{PiEE*}} still\n  bimonoidal? i.e. do all the coherence conditions on isomorphisms\n  naturally extend to relations. I suspect yes.}\n\n\\begin{proposition}[Locally Compact Closed]\nFor every non-zero object {{b}} of {{PiEE*}}, there exists an inverse\nobject {{1/b}} in the {{(*, 1)}} symmetric monoid with the morphisms:\n\n\\begin{enumerate}\n\\item {{1 <-> 1/b * b}} given by {{eta*}}, called the `unit map'.\n\\item {{b * 1/b <-> 1}} given by {{swap* (;) eps*}}, called the `counit map'.\n\\end{enumerate}\n\n\\noindent\nsuch that the following coherence conditions hold (see 2.1 in\n\\cite{selinger2007dagger}):\n\n\n\\begin{enumerate}\n\\item {{uniti (;) swap* (;) (id (*) eta*) (;) assocl* (;) ((swap* (;) eps*) (*) id) (;) unite = id : b <-> b}}\n\\item {{uniti (;) (eta* (*) id) (;) assocr* (;) (id (*) (swap* (;) eps*)) (;) swap* (;) unite = id : 1/b <-> 1/b}}\n\n\n%% z_shape1Times :: a :<=> a\n%% z_shape1Times = UnitI\n%%                 :.: CommuteTimes\n%%                 :.: (Id :*: EtaTimes) \n%%                 :.: AssocTimesL\n%%                 :.: ((CommuteTimes :.: EpsTimes) :*: Id)\n%%                 :.: UnitE\n               \n%% z_shape2Times :: Inv a :<=> Inv a\n%% z_shape2Times = UnitI\n%%                 :.: (EtaTimes :*: Id)\n%%                 :.: AssocTimesR\n%%                 :.: (Id :*: (CommuteTimes :.: EpsTimes))\n%%                 :.: CommuteTimes\n%%                 :.: UnitE\n\n\\end{enumerate}\n\\end{proposition}\n\\begin{proof}\nFor convenience, we draw the combinator {{swap* (;) eps*}} (shown on\nthe left) as shown on the right.\n\n\\begin{multicols}{2}\n\\dgm[0.8]{swap_eps_times}\n\n\\dgm[0.8]{cat_eps_times}    \n\\end{multicols}\n\n\\noindent\nThe coherence conditions are intuitive when presented\ngraphically. They require that the combinators below be equal to\n{{id}}, at the appropriate type (see Sec. 4\n\\cite{springerlink:10.1007/978-3-642-12821-94}).\n\n\\begin{multicols}{2}\n\\dgm{z_times1}\n\n\\dgm{z_times2}\n\\end{multicols}\n\n\n  We briefly trace the execution of the first combinator (let us call\n  it {{c}}). To show that {{c=id}}, we must show for {{v:b}}, the\n  evaluation of {{<c,v,[]>}} always produces {{v:b}} as\n  output. Verification for the second combinator is similar.\n\n%subcode{opsem} include main\n%! columnStyle = rllr\n% & & <c, v:b, []>\n% & |-->* & <eta*, (), C1>\n% & |-->  & <eta*, (1/v',v'), C2> & some v':b\n% (1) & |-->* & <eps*, (1/v', v), C3> & when v' = v\n% & |-->~ & [eps*, (), C3]\n% & |-->* & [c, v, [] ]\n% (2) & |-->* & <eps*, (1/v', v), C3> & when v' /= v\n% & |-->~ & undefined\n\n\\end{proof}\n\n%% For a monoidal category to be compact closed the maps~{{eta}}\n%% and~{{eps}} must satisfy a coherence condition that is usually\n%% visualized as follows:\n%% \\begin{center}\n%%   \\includegraphics{diagrams/coherence.pdf}\n%% \\end{center}\n%% where $b^*$ represents the dual of {{b}}.  In the case of negatives,\n%% the condition amounts to checking that reversing direction twice is a\n%% no-op. In the case of fractionals, the condition amounts to checking\n%% that creating values {{alpha}} and {{1/alpha}} and immediately\n%% unifying them is also a no-op. Both checks are straightforward and are\n%% essentially the constructions in the introduction.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Zero Totalized Fields}\n\nWithout the important side condition on division by zero, we would\nhave {{1<->1/0*0}} which implies {{1 <-> 0}} consequently collapsing\nthe entire structure. \n\nWhile fields require the ``no division by zero'' constraint, alternate\nalgebraic structures such as meadows\n\\cite{Bergstra:2009:MES:1507774.1508000} have been studied which admit\ndivision and negative without this constraint. Such structures are\ncalled ``zero totalized fields'' and define multiplicative inverse of\n{{0}}. The axiomatic presentation of meadows involve removing the\ncombinators corresponding the axiom {{0*b<->0}} (i.e. {{dist0}} and\n{{factor0}}) and {{1<->1/b*b}} (i.e. {{eta*}} and {{eps*}}). Instead\nmeadows include axioms \\emph{reflexivity}, {{refl}} and {{refr}}, and\n\\emph{restricted inverse}, {{ril}} and {{rir}}, which are:\n%subcode{opsem} include main\n% refl :& 1/1/b <-> b :& refr\n% ril :& b*(b*1/b) <-> b :& rir\n\n\\noindent\nCombinators {{refl}} and {{refr}} are primitive and can be defined as:\n%subcode{opsem} include main\n% refl 1/(1/v) &|-->& v\n% refr v &|-->& 1/(1/v)\n\n\\noindent\nCombinators {{ril}} and {{rir}} are defined as machine transitions\nsimilar to {{eta*}}/{{eps*}}:\n%subcode{opsem} include main\n% <ril, (v,(v',1/v')), C> &|-->& {[ril, v, C]}\n% <rir, v, C> &|-->& forall v':b.{[rir, (v, (v',1/v')), C]}\n\nWhile not as commonly used as fields, zero totalization is useful not\njust because we are spared from continuously checking the division\nconstraint, but also because many other structures such as the\ncategory of vectors spaces do admit a dual to the 0 vector\nspace. However their categorization is not well developed and we\nhowever lose the nice correspondence that {{eta*}}/{{eps*}} have with\ncompact closed structures. \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{SAT Solver }\n\\label{sec:sat-solver}\n\n% Additive traces correspond to iteration and multiplicative traces\n% correspond to fixpoint of constraints. Addtive traces have been\n% studied in the past \\cite{infeffects} and here we focus on the\n% multiplicative trace.\n\n% The construction presented here is a novel SAT-solver that relies on\n% {{trace*}} for its solution. It varies from previous classical SAT solvers\n% \\amr{must cite ???} in that there is no explicit search operation on the\n% boolean space. It also varies from previous quantum SAT solvers \\amr{must\n%   cite ???} in that it does uses a {{trace}} operation to compute a fixpoint\n% which is the solution following which an isomorphic clone operation allows us\n% to examine the result.  Though we focus on SAT here, this construction can be\n% generalized to any constraint satisfaction problem whose search space can be\n% represented by a recursive type and for which an isomorphic clone operation\n% can be constructed. \n% can be constructed. Before we start, let us recall two constructions:\n\nAs we will see if Sec. \\ref{sec:neg-constructions}, every compact\nclosed category admits a {{trace}} operator. In the case of {{PiEE*}},\nthe operator {{trace*}} is defined only on the non-zero fragment.\nGiven {{f : a*c <-> b*c }}, we have {{trace* f : a <-> b}}:\n\n{{ trace* f = uniti (;) (id (*) eta*) (;) (f (*) id) (;) (id (*) eps*) (;) unite }}\n\n\\noindent This circuit uses {{eta*}} to generate all possible {{c}}-values\ntogether with an associated {{(1/c)}}-constraint. It then applies {{f}} to the\npair {{(a,c)}}. The function {{f}} must produce an output {{(b,c')}} for each\nsuch input. If the input {{c}} and the output {{c'}} are the same they can be\nannihilated by {{eps*}}; otherwise the execution gets stuck and this\nparticular choice of {{c}} is pruned. \n\n% Annihilation and non-termination describe undefined program\n% execution. While non-termination characterizes an iteration that fails\n% to terminate, annihilation characterizes a constraint that has no\n% fixpoint. The SAT-solver of Sec. \\ref{sec:sat-solver} works by\n% annihilating only the program states that do not match the boolean\n% satisfiability constraint.\n% \\emph{Annihilation.}  \n% With {{eta*}} and {{eps*}}, we can construct a {{trace*}} operation\n% which gives us the ability to find the fixpoint of a constraint.  If\n% the constraint has no satisfying values, there is no fixpoint possible\n% -- we use the term \\emph{annihilation} to describe the corresponding\n% undefined state of the program.\n\nA large class of constraint satisfaction problems can be expressed\nusing {{trace*}}. We illustrate the main ideas with the implementation\nof a SAT-solver.  \n\n%% We proceed in small steps, reviewing some of the\n%% necessary constructions presented in our earlier\n%% paper~\\cite{infeffects}.\n\n%%%%%%%\n\\subsection{Construction of the Solver}\n\nThe key insight underlying the construction comes from the fact that we can\nbuild \\emph{annihilation circuits} such as the one below:\n\n\\begin{center}\n\\scalebox{1.2}{\n  \\includegraphics{diagrams/not_trace.pdf}\n}\n\\end{center}\nThe circuit constructs a boolean {{b}} and its dual {{1/b}}, negates one of\nthem and attempts to satisfy the constraint that they are equal which\nevidently fails. \n\nWith a little work, we can modify this circuit to only annihilate values that\nfail to satisfy the constraints represented by a SAT-instance {{f}}. In more\ndetail, an instance of SAT is a function/circuit~{{f}} that given some\nboolean inputs returns {{true}} or {{false}} which we interpret as whether\nthe inputs satisfy the constraints imposed by the structure of {{f}}. Because\nwe are in a reversible world, our instance of SAT must be expressed as an\nisomorphism: this is easily achieved as shown in Sec.~\\ref{sub:f}\nbelow. Assuming that {{f}} is expressed as an isomorphism, we have enough\ninformation to reconstruct the input from the output. This can be done by\nusing the adjoint of {{f}}. At this point we have, the top half of the\nconstruction below:\n\n\\begin{center}\n\\scalebox{1.2}{\n  \\includegraphics{diagrams/sat1.pdf}\n}\n\\end{center}  \n\nTo summarize, the top half of the circuit is the identity function except\nthat we have also managed to produce a boolean wire labeled\n\\textsf{satisfied?} that tells us if the inputs satisfy the desired\nconstraints. We can take this boolean value and use it to decide whether to\nnegate the control wire or not. Thus, the circuit achieves the following\ngoal: if the inputs do not satisfy {{f}}, the control wire is negated.  We\ncan now use {{trace*}} to annihilate all these bad values because the control\nwire acts like the closed-loop {{not}} in the previous construction.\n\n%%%%%%%%\n\\subsection{Final Details}\n\\label{sub:f}\n\nAny boolean expression {{f : bool^n -> bool}} can be compiled into the\nisomorphism {{iso_f : bool^h*bool^n<->bool^g*bool}} where the extra\nbits {{bool^h}} and {{bool^g}} are considered as heap and\ngarbage. Constructing such an isomorphism has been detailed\nbefore~\\cite{Toffoli:1980,infeffects}. The important relation to note\nis that applying {{iso_f}} to some special heap values and an input\n\\textit{bs} produces some bits that can be ignored and the same output\nthat {{f}} would have produced on {{bs}}. We can ensure that the heap\nhas the appropriate initial values by checking the heap and negating a\nsecond control wire, if the values do not match using, i.e., the\ndotted part in the diagram below. This is achieved by first applying\n{{not}} to the control wire and then testing that all the heap values\nare true using {{cnot^n}}, undoing the {{not}} only if they are.\n\n\\begin{center}\n\\scalebox{1.2}{\n  \\includegraphics{diagrams/sat2.pdf}\n}\n\\end{center}  \n\n% \\roshan{Explain how the dotted part is implemented.}\n\nLet us call the above construction which maps inputs, heap, and\ncontrol wires to inputs, heap, and control wires as {{sat_f}}. The\nSAT-solver is is completed by tracing the {{sat_f}} and cloning the\ninputs using {{clone^n_{bool} }}.\n\n\\begin{center}\n\\scalebox{1.5}{\n  \\includegraphics{diagrams/sat3.pdf}\n}\n\\end{center}\n\nWhen the solver is fed inputs initialized to {{true}}, it clones only\nthose inputs to {{sat_f}} that satisfy {{f}} and the heap\nconstraints. In the case of unique-SAT the solver will produce exactly\n0 or 1 solutions. In the case of general SAT, the solver will produce\nall satisfying solution. \n\n\n\\begin{comment}\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Finite Dimensional Hilbert Spaces}\n\nHalmos \\cite{halmos1958finite}, Abramsky and Coecke\n\\cite{abramsky2004categorical}. Despite the fact that this fragment\nseem badly behaved (no logical reversibility) we have a close\nconnection with finite dimensional Hilbert spaces.\n\nThe technical goal of this section is to show that the categorical\nstructure of finite dimensional Hilbert spaces with unitary maps and\ninner product has the same categorical structure as {{PiEE*}}. Thus\nconstructions in {{PiEE*}} can be transported to FdHilb-unitary. If we\nallow all linear maps, then {{+}} becomes a biproduct.  This has\nconnections to the Quantum Picturisms of Abramsky and Coecke and hence\nto Quantum Physics.\n\n%subcode{bnf} include main\n% v = 0 | 1 | v + v | v * v| 1/v \n\nThere is much future work to be done in this line. The logical\nconsequence of this line of research is either (1) there is no way to\naccommodate probabilities etc in this setting and this is all\nmeaningless or (2) constructions in {{PiEE*}} correspond to physical\nphenomena.\n\nAlso show the what the irreversible constructions can be interpreted\nin Dirac style.\n\n\\end{comment}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Negative Types : {{PiEE+}} }\n\nCharles Pinter in his book on Abstract Algebra talks about how\nnegatives were used by \\emph{logisticians} of a 1000 years ago used\nnegative numbers as a ``useful fiction''.  The concept of negative\nnumbers were ``discovered''much later than fractionals. Like Joan Baez\nsays ``half an apple is easier to understand than a negative apple''.\n\nNegative types should correspond to sets with negative arity. But what\ndoes that mean? Various approaches have been proposed -- Loeb uses the\nnotion of multiplicity functions to express negative sized sets\n[CITE]. These notions have been extended to Euler characteristic and\nHomotopy cardinality of categories by Leinster, Joyal and Schanuel --\nnegative values are explained sometimes as equalities relating\notherwise independent objects -- Baez tells a story about ``island''\nand positive and ``bridges connecting islands'' as negatives (since\nthe effectively reduce the number of disconnected elements.)\n\nWe use the use the syntax {{-b}} for negative types and {{-v}} for\nnegative values and the axiom {{0 <-> (-b)+b}} as the basis for\nnegatives. In {{Pi}}/{{PiEE*}}, values flowed from left-to-right in\ncircuits. Negative types are negative in the sense that they flow in\nthe opposite direction. \n\n%subcode{bnf} include main\n% Value Types, b = 0 | 1 | b + b | b * b | -b\n% Values, v = () | left v | right v | (v, v) | -v \n%\n% Isomorphisms, iso &=& ... | eta+ | eps+\n\nFor convenience, we sometimes use the notations {{b1 - b2}} to\nindicate the types {{b1 + (-b2)}}.  The types of the new constructs\nare:\n\\vspace{-15pt}\n\\begin{multicols}{2}  \n%subcode{opsem} include main\n% eta+ &: 0 <-> (-b) + b :& eps+\n\n%subcode{proof} include main\n%@ |- v : b\n%@@ |- -v : -b\n\\end{multicols}\n\n\n\\begin{multicols}{2}\n\\begin{center}\n  \\includegraphics{diagrams/eta.pdf}\n\\end{center}\n  \n\\begin{center}\n \\includegraphics{diagrams/eps.pdf}\n\\end{center}\n\\end{multicols}\n\n\\begin{multicols}{2}\n\\begin{center}\n\\scalebox{1.5}{\n  \\includegraphics{diagrams/eps_plus1.pdf}\n}\n\\end{center}\n  \n\\begin{center}\n\\scalebox{1.5}{\n  \\includegraphics{diagrams/eps_plus2.pdf}\n}\n\\end{center}  \n\\end{multicols}\n\n\\begin{definition}[Size of a type]\nThe definition of size is extended to include negative types.\n{{[^-b^] = -[^b^]}}\n\\end{definition}\n\n%%%%%%%%%\n\\subsection{Semantics}\n\n\\begin{comment}\n  \n%subcode{opsem} include main\n%! columnStyle = rclr\n%! fwd = \\triangleright\n% <iso, v, C, s>_{fwd} &|-->& {[iso, v', C, s']}_{fwd}\n% & & where iso s v |--> (v', s')\n% <c1(;)c2, v, C, s>_{fwd} &|-->& <c1, v, Fst C c2, s>_{fwd}\n% {[c1, v, Fst C c2, s]}_{fwd} &|-->& <c2, v, Snd c1 C, s>_{fwd}\n% {[c2, v, Snd c1 C, s]}_{fwd} &|-->& {[ c1(;)c2, v, C,s ]}_{fwd}\n% <c1(+)c2, v', C, s>_{fwd} &|-->& <c1, v, LeftP C c2, s[v' <><> left v]>_{fwd}\n% {[ c1, v, LeftP C c2, s ]}_{fwd} &|-->& {[c1 (+) c2, left v, C,s ]}_{fwd}\n% <c1(+)c2, v', C, s>_{fwd} &|-->& <c2, v, RightP c1 C, s[v' <><> right v]>_{fwd}\n% {[ c2, v, RightP c1 C,s ]}_{fwd} &|-->& {[c1 (+) c2, right v, C,s ]}_{fwd}\n% <c1(*)c2, v', C, s>_{fwd} &|-->& <c1, v1, LeftT C c2 v2, s'>_{fwd}\n% & & where s' = s[v <><> (v1, v2)]\n% {[ c1, v1, LeftT C c2 v2,s ]}_{fwd} &|-->& <c2, v2, RightT c1 v1 C, s>_{fwd}\n% {[ c2, v2, RightT c1 v1 C,s ]}_{fwd} &|-->& {[ c1 (*) c2, (v1, v2), C,s ]}_{fwd}\n\n\\end{comment}\n\nGiven that our language is reversible (Prop.~\\ref{prop:logrev}), a backward\nevaluator is relatively straightforward to implement: using the backward\nevaluator to calculate {{c v}} is equivalent {{c^{dagger} v}} in the forward\nevaluator.\n\n%subcode{opsem} include main\n%! columnStyle = rclr\n% {[iso, v, C]}^^^ &|-->& <iso, v', C>^^^\n% & & where iso^{dagger} v |--> v'\n% <c1, v, Fst C c2>^^^ &|-->& <c1(;)c2, v, C>^^^\n% <c2, v, Snd c1 C>^^^ &|-->& {[c1, v, Fst C c2]}^^^\n% {[ c1(;)c2, v, C]}^^^ &|-->& {[c2, v, Snd c1 C]}^^^\n% <c1, v, LeftP C c2>^^^ &|-->& <c1(+)c2,left v, C>^^^\n% {[c1 (+) c2, left v, C]}^^^ &|-->& {[ c1, v, LeftP C c2 ]}^^^\n% <c2, v, RightP c1 C, s>^^^ &|-->& <c1(+)c2, right v, C>^^^\n% {[c1 (+) c2, right v, C ]}^^^ &|-->& {[ c2, v, RightP c1 C ]}^^^\n% <c1, v1, LeftT C c2 v2>^^^ &|-->& <c1(*)c2, (v1, v2), C>^^^\n% <c2, v2, RightT c1 v1 C >^^^ &|-->& {[ c1, v1, LeftT C c2 v2 ]}^^^\n% {[ c1 (*) c2, (v1, v2), C ]}^^^ &|-->& {[ c2, v2, RightT c1 v1 C ]}^^^\n\nTo add negative types we add the following rules to the\n  reductions above. The additions formalize our previous discussions\n  and should not be surprising at this point.\n\n  \\begin{enumerate}\n  \\item The rules for {{eps+}} essentially transfer control from the\n    forward evaluator (whose states are tagged by $\\triangleright$) to\n    the backward evaluator (whose states are tagged by\n    $\\triangleleft$). In other words, after an {{eps+}} the direction\n    of the world is reversed. The pattern matching done by the\n    unification ensures that a value on the {{right}} wire is tagged\n    to be negative and transferred to the {{left}} wire, and vice versa.\n\n%subcode{opsem} include main\n%! columnStyle = rclr\n%! fwd = \\triangleright\n%! bck = \\triangleleft\n% <eps+, right v, C, s> &|-->& <eps+, left (-v), C]>^^^\n% <eps+, left (-v), C, s> &|-->& <eps+, right v, C>^^^\n\n    Note that there is no evaluation rule for {{eta+}} in the forward\n    evaluator. This corresponds to the fact that there is no value of\n    type {{0}} and hence the forward evaluator can never execute an\n    {{eta+}}.\n\n    \\item The rules for {{eta+}} are added to the backward evaluator. A\n      program executing backwards starts executing forwards after the\n      execution of the {{eta+}}. Dual to the previous case, there is\n      no rule for {{eps+}} in the backward evaluator since the output\n      type of {{eps+}} is {{0}}.\n\n%subcode{opsem} include main\n%! columnStyle = rclr\n%! fwd = \\triangleright\n%! bck = \\triangleleft\n% {[eta+, right v, C, s]}^^^ &|-->& {[eta+, left (-v), C ]}\n% {[eta+, left (-v), C, s]}^^^ &|-->& {[eta+, right v, C ]}\n  \\end{enumerate}\n\nConsider the combinator {{c:(-1+1)+1<->1}} defined below. On providing\nthe value {{right ():(-1+1)+1}} we get the output {{():1}}. But on\nsupply input {{left (right ())}} evaluation stop on the reverse\ninterpreter with value {{left (left ()):(-1+1)+1}}.\n\nBy definition, since negative values flow in the opposite direction of\npositive values, this is not surprising. Combinators can terminate in\nthe forward interpreter (with result of type {{b2}}) or in the reverse\ninterpreter (with result of type {{b1}}). To define an {{eval}} in a\nconsistent manner without worrying about state of the evaluator, we\ntransform every combinator of the form {{c:b1<->b2}} to one of the\nform {{c:-b2+b1<->0}} by the construction {{action(c)=id(+)c(;)eps+}}. \n\n\\begin{definition}[{{eval(c, v)}}]\nGiven {{c:b1<->b2}} and {{v:b1}} we define {{eval(c, v)=v'}} such that\n\\begin{enumerate}\n\\item {{right v:-b2+b1}}, {{v':-b2+b1}} and\n\\item {{<action(c), right v, []> |-->* <action(c),v',[]>^^^}}\n\\end{enumerate}\n\\end{definition}\n\n\\begin{definition}[{{c1=c2}}]\n  For {{c1:b1<->b2}} and {{c2:b1<->b2}}, we define {{c1=c2}} if\n  {{~forall v:b1.eval(c1,v) = eval(c2,v)}}.\n\\end{definition}\n\n\\begin{proposition}[Logical Reversibility]\n  \n\\end{proposition}\n\n\\begin{proposition}[Strong Normalization]\n  \n\\end{proposition}\n\n\\begin{proposition}[Type Safety]\n  \n\\end{proposition}\n\n%%%%%%%%%\n\\subsection{Categorical Structure}\n% \\label{sec:neg-constructions}\n\nAs before, we can show that {{PiEE+}} is a bimonoidal\ncategory. Additionally it has a compact closed structure in the\n{{(0,+)}} monoid.\n\n\\begin{proposition}[Compact Closed {{(0,+,-)}}]\n  {{PiEE+}} is a compact closed category with over the symmetric\n  monoid {{(0,+)}} with the dual of objects {{b}} give by {{-b}} with\n  morphisms:\n\n\\begin{enumerate}\n\\item {{0 <-> -b + b}} given by {{eta+}}, called the `unit map'.\n\\item {{b + -b <-> 0}} given by {{swap+ (;) eps+}}, called the `counit map'.\n\\end{enumerate}\n\n\\noindent\nsuch that the following coherence conditions hold (see 2.1 in\n\\cite{selinger2007dagger}):\n\n\n\\begin{enumerate}\n\\item {{zeroi (;) swap+ (;) (id (+) eta+) (;) assocl+ (;) ((swap+ (;) eps+) (+) id) (;) zeroe = id : b <-> b}}\n\\item {{zeroi (;) (eta+ (+) id) (;) assocr+ (;) (id (+) (swap+ (;) eps+)) (;) swap+ (;) zeroe = id : -b <-> -b}}\n\\end{enumerate}\n\n\\end{proposition}\n\n\n%%%%%%%%%\n\\subsection{Categorical Constructions}\n\\label{sec:neg-constructions}\n\n\\\nAll the constructions below are standard: they are collected from Selinger's\nsurvey paper on monoidal\ncategories~\\cite{springerlink:10.1007/978-3-642-12821-94} and presented in\nthe context of our language. \n\nWe now review several interesting constructions related to looping,\ninvolution, and higher order functions. \n\n\\paragraph*{Trace.}\nEvery compact closed category admits a trace. For the additive case, we get\nthe following definition.  Given {{f : b1+b2 <-> b1+b3 }}, \ndefine {{trace+ f : b2 <-> b3}} as:\n\n{{ trace+ f = zeroi (;) (id (+) eta+) (;) (f (+) id) (;) (id (+) eps+) (;) zeroe }} \n\n\\begin{center}\n  \\includegraphics{diagrams/thesis/trace_plus.pdf}\n\\end{center}  \n\n\\noindent We have omitted some of the commutativity and associativity\nshuffling to communicate the main idea. We are given a value of type\n{{b2}} which we embed into {{0+b2}} and then {{(-b1+b1)+b2)}}. This\ncan be re-associated into {{-b1+(b1+b2)}}. The component {{b1+b2}},\nwhich until now is just an appropriately tagged value of type {{b2}},\nis transformed to a value of type {{b1+b3}} by {{f}}. \nIf the result is in the {{b3}}-summand, it is produced as\nthe answer; otherwise the result is in the {{b1}}-summand; {{eps+}} is\nused to make it flow backwards to be fed to the {{eta+}} located at\nthe beginning of the sequence. Iteration continues until a {{b3}} is\nproduced.\n\n\n%%%%%\n\\paragraph*{Involution (Principium Contradictiones)}\n\nIn a symmetric compact closed category, we can build isomorphisms that the\ndual operation is an involution. Specifically, we get the isomorphisms \n{{b <-> -(-b)}} and {{b <-> (1/(1/b))}}. For the additive case, the \nisomorphism is defined as follows:\n\n{{ (id (+) eta+) (;) (swap+ (+) id) (;) (id (+) eps+) }}\n\n\\noindent where we have omitted the 0 introduction and elimination. The idea\nis as follows: we start with a value of type {{b}}, embed it into {{b+0}} and\nuse {{eta}} to create something of type {{b + (-(-b) + (-b))}}. This is possible\nbecause {{eta}} has the polymorphic type {{-a + a}} which can be instantiated\nto {{-b}}. We then reshuffle the type to produce {{-(-b) + (-b + b)}} and cancel\nthe right hand side using {{eps+}}.  The construction for the multiplicative \ncase is identical and omitted.\n\n%% {{b <-> -(-b)}}\n%% \n%% this is the wrong diagram: see lemma 4.17 in selinger's paper\n%% \\begin{center}\n%%   \\includegraphics{diagrams/double_neg.pdf}\n%% \\end{center}\n\n\\paragraph*{Duality preserves the monoidal tensor. }\nAs with compact closed categories, the dual on the objects distributes\nover the tensor. In terms of {{PiEE}} we have that {{-(b1+b2)}}\ncan be mapped to {{(-b1)+(-b2)}} and that {{1/(b1*b2)}} can be mapped\nto {{(1/b1)*(1/b2)}}. The isomorphism {{-(b1 + b2) <-> (-b1) + (-b2)}}\ncan be realized as follows:\n\\begin{center}\n  \\includegraphics{diagrams/dist_neg_plus.pdf}\n\\end{center}\n\n\\noindent\nThe multiplicative construction is similar. \n\n%% This is a distinguishing difference from *-autonomous categories that\n%% are models for Linear Logic, where the dual does not preserve the\n%% tensor but maps to a dual tensor \\cite{curien2009interactive}.\n\n\\paragraph*{Duality is a functor.}\nDuality in {{PiEE}} can map objects to their duals and morphisms\nto act on dual objects. In other {{c : b1 <-> b2}} to\n{{neg~c:-b1<->-b2}} in the additive monoid and to\n{{inv~c:1/b1<->1/b2}} in the multiplicative monoid. \n%% Any operation on types can be applied to the negative versions of these\n%% types. \nThe idea is simply to reverse the flow of values and use the\nadjoint of the operation:\n\\begin{multicols}{2}\n\\begin{center}\n  \\includegraphics{diagrams/neg_lift.pdf}\n\\end{center}  \n\n%subcode{proof} include main\n%@ c : b1 <-> b2\n%@@ neg c : (-b1) <-> (-b2)\n\\end{multicols}\n\nThis construction relies on the fact that every {{PiEE}} morphism\nhas an adjoint.  The {{inv}} construction is similar.\n\n%% inverse morphism, whereas in compact closed categories with no\n%% underlying dagger structure we can only construct an op-functor.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Computing in the Field of Rationals : {{PiEE}} }\n\nNot logically reversible and we can express infinite loops.\n\n\\paragraph*{Observability.} \n\nThe reductions above allow us to apply a program {{c : b1 <-> b2}} to an\ninput {{v1 : b1}} to produce a result {{v2 : b2}} on termination. Execution\nis well defined only if {{b1}} and {{b2}} are entirely positive types. If\neither {{b1}} or {{b2}} is a negative or fractional type, the system has\n``dangling'' unsatisfied demands or constraints. For this reason, we\nconstrain entire programs to have positive non-fractional types. This is\nsimilar to the constraint that Zeilberger imposes to explain intuitionistic\npolarity and delimited control~\\cite{10.1109/LICS.2010.23}.\n\n%%%%%%%%%%%%\n\\subsection{Constructions with Negatives and Fractionals}\n\\label{sec:specific-constructions}\n\nThe additional constructions below (presented with minimal commentary)\nconfirm that conventional algebraic manipulations in the mathematical field\nof rationals do indeed correspond to realizable type isomorphisms in our\nsetting. The constructions involving both negative and fractional types are\nnovel.\n\n\\paragraph*{Lifting negation out of {{*}}.}\nThe isomorphisms below state that the direction is \\emph{relative}. If {{b1}}\nand {{b2}} are flowing opposite to each other then it doesn't matter which\ndirection is forwards and which is backwards. More interestingly as {{b1}} is\nmoving backwards, it can ``see the past'' of {{b2}} which is equivalent to\nboth particles moving backwards.\n\n{{(-b1) * b2 <-> -(b1 * b2) <-> b1 * (-b2)}}\n\nTo build these isomorphisms, we first build an intermediate\nconstruction which we call {{eps_{fst} : (-b1)*b2 + b1*b2 <-> 0}}. \n\\begin{center}\n\\scalebox{0.8}{\n  \\includegraphics{diagrams/eps_fst.pdf}\n}\n\\end{center}\n\nThe isomorphism {{(-b1) * b2 <-> -(b1 * b2)}} can be constructed in\nterms of {{eps_{fst} }} as shown below. \n\n\\begin{center}\n\\scalebox{0.9}{\n  \\includegraphics{diagrams/mult_neg.pdf}\n}\n\\end{center}  \n\nThe second isomorphism can be built in the same way by merely swapping\nthe arguments. \n\n\\paragraph*{Multiplying Negatives.}\n\n{{b1 * b2 <-> (-b1)*(-b2)}}\n\nThis isomorphism is a consequence of the fact that $-$ is an involution: it\ncorresponds to the algebraic manipulation:\n\n%% %subcode{opsem} include main\n%% %! columnStyle = rc\n%% %   & b1 * b2\n%% % = & -(-(b1*b2)) \n%% % = & -((-b1)*b2)\n%% % = & (-b1)*(-b2)\n\n{{b1 * b2 = -(-(b1*b2)) = -((-b1)*b2) = (-b1)*(-b2)}}\n\n\\paragraph*{Multiplying and Adding Fractions.}\nAn isomorphism witnessing:\n\n{{b1/b2 * b3/b4 <-> (b1*b3)/(b2*b4)}}\n\nis straightforward. More surprisingly, it is also possible to construct\nisomorphisms witnessing:\n\n{{b1/b + b2/b <-> (b1+b2)/b}}\n\n{{b1/b2 + b3/b4 <-> (b1*b4+b3*b2)/(b2*b4) }}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Two Dualities of Computation}\n\\label{sub:hof}\n\nInformation Effects, Filinski, De Morgan\n\n%%%%%%%%%%%%%\n\\subsection{Function Spaces}\n\nAlthough these constructions are also standard, they are less known and they\nare particularly important in our context: we devote a little more time to\nexplain them. Our discussion is mostly based on Abramsky and Coecke's article\non categorical quantum mechanics~\\cite{abramsky-2008}.\n\nIn a compact closed category, each morphism {{f : b1 <-> b2 }} can be given a\n\\emph{name} and a \\emph{coname}. For the additive fragment, the name\n$\\fname{f}$ has type {{0 <-> (-b1 + b2)}} and the coname $\\fconame{f}$ has type\n{{b1 + (-b2) <-> 0}}. For the multiplicative fragment, the name $\\fname{f}$ has\ntype {{1 <-> ((1/b1) * b2))}} and the coname $\\fconame{f}$ has type \n{{(b1 * (1/b2)) <-> 1}}. Intuitively, this means that for each morphism, \nit is possible to construct, from ``nothing,'' an object in the category that \ndenotes this morphism, and dually it is possible to eliminate this object.\nThe construction of the name and coname of {{c : b1 <-> b2}} in the additive case \ncan be visualized as follows:\n\n\\begin{multicols}{2}\n\\begin{center}\n  \\includegraphics{diagrams/function.pdf}\n\\end{center}\n\n\\begin{center}\n  \\includegraphics{diagrams/delimc.pdf}\n\\end{center}  \n\\end{multicols}\n\nIntuitively the name consists of viewing {{c}} as a function and the coname\nconsists of viewing {{c}} as a delimited continuation.\n\nIn addition to being able to represent morphisms, it is possible to express\nfunction composition. For the additive case, the composition is depicted\nbelow:\n\n\\begin{multicols}{2}\n\\scalebox{1.1}{\n    \\includegraphics{diagrams/compose1.pdf}\n}\n\n\\scalebox{0.8}{\n    \\includegraphics{diagrams/compose.pdf}\n}\n\\end{multicols}\nwhich is essentially equivalent to sequencing both the computation blocks as\nshown below:\n\n\\begin{center}\n  \\includegraphics{diagrams/compose2.pdf}\n\\end{center}\n\nApplying a function to an argument consists of making the argument flow\nbackwards to satisfy the demand of the function:\n\\begin{multicols}{2}\n\\begin{center}\n\\scalebox{1.0}{\n  \\includegraphics{diagrams/apply1.pdf}\n}\n\\end{center}\n\\begin{center}\n\\scalebox{0.8}{\n  \\includegraphics{diagrams/apply2.pdf}\n}\n\\end{center}\n\\end{multicols}\n\nHaving reviewed the representation of functions, we now discuss the\nsimilarities and differences between the two notions of functions and their\nrelation to conventional (linear) functions which mix additive and\nmultiplicative components. For that purpose, we use a small example.\nConsider a datatype {{color = R|Gr|B}}, and let us consider the following\nmanipulations:\n\\begin{itemize}\n\\item Using the fact that {{1}} is the multiplicative unit, generate\n  from the input {{()}} the value {{((),())}} of type {{1 * 1}};\n\\item Apply the isomorphism {{1 <-> (1/b) * b}} in parallel to each of\n  the components of the above tuple. The resulting value is\n  {{((1/alpha1,alpha1),(1/alpha2,alpha2))}} where {{alpha1}} and\n  {{alpha2}} are fresh logic variables;\n\\item Using the fact that {{*}} is associative and commutative, we can\n  rearrange the above tuple to produce the value:\n\n{{((1/alpha1,alpha2),(1/alpha2,alpha1))}}.\n\n\\end{itemize}\n\nAt this point we have constructed a strange mix of two {{b-o*b}} functions;\ninputs of one function manifest themselves as outputs of the other. If\n{{(1/alpha1,alpha2)}} is held by one subcomputation and {{(1/alpha2,alpha1)}}\nis held by another subcomputation, these remixed functions form a\ncommunication channel between the two concurrent subcomputations. Unifying\n{{1/alpha1}} with {{color}} {{R}} in one subcomputation, fixes {{alpha1}} to\nbe {{R}} in the other. The type {{b}} thus takes the role of the type of the\ncommunication channel, indicating how much information can be communicated\nbetween the two subcomputations.  Depending on the choice of the type {{b}},\nan arbitrary number of bits may be communicated.\n\nDually, the additive reading of the above manipulations correspond to\nfunctions of the form {{b-o+b}}, witnessing isomorphisms of the form\n{{0<->(-b)+b}}). The remixed additive functions express control flow transfer\nbetween two subcomputations, \\emph{only one of which exists} at any point,\ni.e., they capture the essence of coroutines. \n\nIt should be evident that in a universe in which information is not\nguaranteed to be preserved by the computational infrastructure, the above\nslicing and dicing of functions would make no sense. But linearity is not\nsufficient: one must also recognize that the additive and multiplicative\nspaces are different. \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Related Work} \n\\label{sec:related}\n\nThe idea of ``negative types'' has appeared many times in the literature and\nhas often been related to some form of continuations. Fractional types are\nless common but have also appeared in relation to parsing natural\nlanguages. Although each of these previous occurrences of negative and\nfractional types is somewhat related to our work, our results are\nsubstantially different. To clarify this point, we start by reviewing the\nsalient point of the major pieces of related work and conclude this section\nwith a summary contrasting our approach to previous work.\n\n\\paragraph*{Declarative Continuations.} \nIn his Masters thesis~\\cite{Filinski:1989:DCI:648332.755574}, Filinski\nproposes that continuations are a \\emph{declarative} concept. He,\nfurthermore, introduces a symmetric extension of the $\\lambda$-calculus in\nwhich call-by-value is dual to call-by-name and values are dual to\ncontinuations. In more detail, the symmetric calculus contains a ``value''\nfragment and a ``continuation'' fragment which are mirror images. Pairs and\nsums are treated as duals in the sense that the ``value'' fragment includes\npairs whose mirror image in the ``continuation'' fragment are sums. In\ncontrast, our language includes pairs and sums in the value fragment and two\nsymmetries: one that maps the pairs to fractions and another that maps the\nsums to subtractions.\n\n\\paragraph*{The Duality of Computation.}\nThe duality between call-by-name and call-by-value was further investigated\nby Selinger using control\ncategories~\\cite{Selinger:2001:CCD:966910.966911}. Curien and\nHerbelin~\\cite{Curien:2000} also introduce a calculus that exhibits\nsymmetries between values and continuations and between call-by-value and\ncall-by-name. The calculus includes the type $A-B$ which is the dual of\nimplication, i.e., a value of type $A-B$ is a context expecting a function of\ntype $A \\rightarrow B$. Alternatively a value of type $A-B$ is also explained\nas a \\emph{pair} consisting of a value of type $A$ and a continuation of type\n$B$. This is to be contrasted with our interpretation of a value of that type\nas \\emph{either} a value of $A$ or a demand for a value of type $B$. This\ncalculus was further analyzed and extended by\nWadler~\\cite{Wadler:2003,DBLP:conf/rta/Wadler05}. The extension gives no\ninterpretation to the subtraction connective and like the original symmetric\ncalculus of Filinski, introduces a duality that relates sums to products and\nvice-versa.\n\n\\paragraph*{Subtractive Logic.} \nRauszer~\\cite{springerlink:10.1007/BF02120864,rauszer,rauszer2} introduced a\nlogic which contains a dual to implication. Her work has been distilled in\nthe form of \\emph{subtractive logic}~\\cite{Crolard01} which has recently been\nrelated to coroutines~\\cite{Crolard01082004} and delimited\ncontinuations~\\cite{Ariola:2009:TFD:1743339.1743381}.  In more detail,\nCrolard explains the type $A-B$ as the type of \\emph{coroutines} with a local\nenvironment of type $A$ and a continuation of type $B$. The description is\ncomplicated by what is essentially the desire to enforce linearity\nconstraints so that coroutines cannot access the local environment of other\ncoroutines. \n\n\\paragraph*{Negation in Classical Linear Logic} \nFilinski~\\cite{Filinski92} uses the negative types of linear logic to model\ncontinuations. Reddy~\\cite{Reddy91} generalizes this idea by interpreting the\nnegative types of linear logic as \\emph{acceptors}, which are like\ncontinuations in the sense that they take an input and return no\noutput. Acceptors however are also similar in flavor to logic variables:\nthey can be created and instantiated later once their context of use is\ndetermined. Although a formal connection is lacking, it is clear that, at an\nintuitive level, acceptors are entities that combine elements of our negative\nand fractional types.\n\n\\paragraph*{The Lambek-Grishin Calculus.} The ``parsing-as-deduction'' style\nof linguistic analysis uses the Lambek-Grishin calculus with the following\ntypes: product, left division, right division, sum, right difference, and\nleft difference~\\cite{Bernardi:2010:CSL:1749618.1749689}. The division and\ndifference types are similar to our types but because the calculus lacks\ncommutativity and associativity and only has limited notions of\ndistributivity, each connective needs a left and right version. The\nLambek-Grishin exhibits two notions of symmetry but they are unrelated to our\nnotions. In particular, the first notion of symmetry expresses commutativity\nand the second relates products to sums and divisions to subtractions. In\ncontrast, our two symmetries relate sums to subtractions and products to\ndivisions.\n\n\\paragraph*{Our Approach.} The salient aspects of our approach are the\nfollowing:\n\\begin{itemize}\n\\item Negative and fractional types have an elementary and familiar\n  interpretation borrowed from the algebra of rational numbers. One can write\n  any algebraic identity that is valid for the rational numbers and interpret\n  it as an isomorphism with a clear computational interpretation: negative\n  values flow backwards and fractional values represent constraints on the\n  context. None of the systems above has such a natural interpretation of\n  negative and fractional types.\n\\item Because we are \\emph{not} in the context of the full\n  $\\lambda$-calculus, which allows arbitrary duplication and erasure of\n  information, values of negative and fractional types are first-class values\n  that can flow anywhere. The information-preserving computational\n  infrastructure guarantees that, in a complete program, every negative\n  demand will be satisfied exactly once, and every constraint imposed by a\n  fractional value will also be satisfied exactly once. This property is\n  shared with systems that are based on linear logic; other systems must\n  impose ad hoc constraints to ensure negative and fractional values are used\n  exactly once.\n\\item In contrast to all the work that takes continuations as primitive\n  entities of negative types, we view continuations as a derived notion that\n  combines a demand for a value with constraints on how this value will be\n  used to proceed with the evaluation (to the closest delimiter or to the end\n  of the program). In other words, we view a continuation as a non-elementary\n  notion that combines the negative types to demand a value and the\n  fractional types to explain how this value will be used to continue the\n  evaluation. As a consequence, the previously observed duality between\n  values and continuations can be teased into two dualities: a duality\n  between values flowing in one direction or the other and a duality between\n  aggregate values composing and decomposing into smaller values. Arguably\n  each of the dualities is more natural than a duality that maps regular\n  values to a conflated notion of negative and fractional types, and hence\n  requires notions like ``additive pairs'' and ``multiplicative sums.''\n\\end{itemize}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Conclusion and Future Work}\n\\label{sec:conc}\n\nWe have extended the language {{Pi}} that expressed computation\nin the commutative semiring of whole numbers to {{PiEE}} that\nexpresses computation in the field of rationals.  Every algebraic\nidentity that holds for the rational numbers corresponds to a type\nisomorphism with a computational interpretation in our model. We have\nexamined the two function spaces that arise in this model and\ndeveloped non-trivial constructions such as a SAT-solver that relies\non a multiplicative trace.\n\nIn another sense however, this paper is about the nature of duality in\ncomputation. \n% The concept of duality is deep and significant and in many cases ---\n% probably most famously in the divide between classical and intuitionistic\n% mathematics --- contain non-trivial assumptions about our worldview.  The\n% problem of duality in computation and logic, has many facets of which\n% `continuation' and `higher order functions' are only one.\nThe concept of duality is deep and significant: we have opened the\ndoor for us to consider, not one but two notions of\nduality. Surprisingly this makes things substantially simpler. In\nparticular, instead of conflating pairs as dual to sums, the tradition\nin mathematics has long been to consider fields with two notions of\nduality: one for sums and one for pairs. This double notion of duality\nhas a crisp semantics, clear computational interpretation, and an\ninformation theoretic basis.\n\nOur work has barely scratched the surface of an area of computing which has\nbeen explored in depth before but without the combined reversible\ninformation-preserving framework and the two notions of duality. The new\ninsights point to further new areas of investigation, of which we mention\nthe three most significant ones (in our opinion).\n\n%% \\paragraph*{Int Construction} How are we preserving two compact\n%% closed structures -- what does this imply about the Int\n%% construction.\n\n\\paragraph*{Geometry of Interaction (GoI).}\nGeometry of Interaction was developed by Girard~\\cite{girard1989geometry} as part of\nthe development of linear logic. It was given a computational interpretation\nby Abramsky and Jagadeesan~\\cite{Abramsky:1994:NFG:184662.184664}, and was\ndeveloped into a reversible model of computing by\nMackie~\\cite{Mackie2011,DBLP:conf/popl/Mackie95}. Preliminary investigations\nsuggest that many of the GoI machine constructions can be simulated in\n{{PiEE}} by treating Mackie's bi-directional wires as pairs of wires in\n{{PiEE}} and replacing the machine's global state with a typed value on\nthe wire that captures the appropriate state. This connection is exciting\nbecause when viewed through a Curry-Howard lens it suggests that the logical\ninterpretation of {{PiEE}} would be a linear-like logic with a notion of\nresource preservation and with a natural computational interpretation. \n\n\\paragraph*{Computing in the Field of Algebraic Numbers.}\n\\label{sec:algebraic-field}\nAlgebraically, the move from {{Pi}} to {{PiEE}} corresponds to a\nmove from a ring-like structure to a full field. Our language {{PiEE}}\ncaptures the structure of one particular field: that of the rational\nnumbers. As we have seen, computation in this field is quite expressive and\ninteresting and yet, it has two fundamental limitations. First it cannot\nexpress any recursive type, and second it cannot express any datatype\ndefinitions. We believe these to be two orthogonal extensions: recursive\ntypes were considered in our previous paper~\\cite{infeffects}; arbitrary\ndatatypes are however even more exciting that plain rationals as each\ndatatype definition can be viewed as a polynomial (see below) which\nessentially means that we start computing in the field of algebraic numbers,\nwhich includes square roots and imaginary numbers. As crazy as it might seem,\nthe type $\\sqrt{2}$ and even the type $(1/2)+i(\\sqrt{3}/2)$ ``make sense.''\nIn fact the latter type is the solution to the polynomial {{x^2-x+1=0}} which\nif re-arranged looks like {{x=1+x*x}} and perhaps more familiarly as the\ndatatype of binary trees {{@@x.(1+x*x)}}. These types happen to have been\nstudied extensively following a paper by Blass~\\cite{seventrees} which used\nthe above datatype of trees to infer an isomorphism between seven binary\ntrees and one!\n\nWe have confirmed that we can extended {{PiEE}} with the datatype\ndeclaration for binary trees and build a witness for this isomorphism\nthat works as expected. However not every isomorphism constructed from\nalgebraic manipulation is computationally meaningful. To understand the\nissue in more detail, consider the following algebraically valid proof\nof the isomorphism in question:\n\\[\\begin{array}{rclclclcl}\nx^3 &=& x^2 x &=& (x-1) x &=& x^2 - x &=& -1 \\\\\nx^6 &=& 1 \\\\\nx^7 &=& x^6 x &=& x\n\\end{array}\\]\nThe question is why such an algebraic manipulation makes sense type\ntheoretically, even though the intermediate step asking for an isomorphism\nbetween $x^6$ and $1$ has no computational context. In the setting of\n{{PiEE}}, this isomorphism can be constructed but it diverges on all\ninputs (in both ways). This suggests that, in the field of algebraic numbers,\nsome algebraic manipulations are somehow \n``more constructive'' than others.\n\nA related issue is that not all meaningful recursive types are\nmeaningful polynomials. For instance {{nat=@@x.(1+x)}} implies the\npolynomial {{x=1+x}} which has no algebraic solutions without appeal\nto more complex structures with limits etc. \n\n%% or dually that {{PiEE}} with recursive types\n%%somehow lacks the ability to express all computations that are otherwise\n%%algebraically meaningful.\n\n% \\begin{itemize}\n% \\item Maybe the problem is that there is cancellation in the second\n%   case and cancellation with recursive types is problematic. However\n%   not all cancellation is. So what gives?\n\n% \\item One idea is that irrationals correspond to an infinite amount of\n%   computational work. If what we are cancelling is not the same\n%   infinity, then things go wrong. \n\n% \\item Chaitin has already shown that reals have inifite amount of\n%   information which is paradoxical and problematic. This is a\n%   different issue from that of the rational being infinite\n%   computations.\n\n% \\item Finally, not all meaningful types are meaningful polynomials --\n%   ex. nat. So this is not the whole story. \n\n% \\end{itemize}\n\n\\paragraph*{Quantum Computing.} \nOne understanding of quantum computing is that it exploits the laws of physics\nto build faster machines (perhaps). Another more foundational understanding\nis that it provides a computational interpretation of physics, and in\nparticular directly addresses the question of interpretation of quantum\nmechanics. In a little known document, Rozas~\\cite{Rozas:1987:CMO:889539}\nuses continuations to implement the transactional interpretation of quantum\nmechanics~\\cite{transactional} which includes as its main ingredient a\nfixpoint calculation between waves or particles traveling forwards and\nbackwards in time. Our work sheds no light on whether this interpretation is\nthe ``right one'' but it is interesting that we can directly realize it using\nthe primitives of {{PiEE}}. \n\n% A \\emph{time\n%   traveling} intuition is also applicable here.  In a normal cicruit, as\n% computational steps are taken values flow from left to right,\n% i.e. computational time progresses from left to right.  The action of\n% {{eps+}} causes values, aka information particles, to flow from right to left\n% i.e. backwards in computational time.  The interesting thing about this\n% interpretation is that particles that travel backwards in time get to see and\n% interact with the history of particles that they coexist with. This gives us\n% an intuitive interpretation of the isomorphism {{(-b1)*b2<->-(b1*b2)}} (see\n% Sec. \\ref{sec:specific-constructions}) where it would otherwise seem that\n% {{-b1}} and {{b2}} move in opposite directions. The backward flow of the\n% {{-b1}} allows it to `see the past' of {{b2}} and is thus equivalent to both\n% particles moving backward in time.\n\nThe multiplicative structure of {{PiEE}} also has a direct\nconnection to entangled quantum particles, or perhaps entangled\nparticles and anti-particles.  The idea of entanglement, that an\naction on one particle is ``instantaneously'' communicated to the\nother, is analogous to how unifying one value affects its dual pair\nwhich is possibly in another part of the computation.  Again our model\nsheds no light on whether this is related to how nature computes but\nit is again interesting that we can directly realize the idea using\nthe primitives of {{PiEE}}.\n\n% natural An analogy\n% inspired by quantum mechanics is also applicable here.  The operator {{eta*}}\n% is a site of fission that creates \\emph{an entangled particle and\n%   anti-particle}. These particles can be thought to be in a\n% \\emph{superposition} of states determined by their type. Both flow in the\n% same direction in time.  In each possible world that the particle exists, it\n% takes on a specific value inhibiting its type and correspondingly its\n% entangled anti-particle takes the dual of the specific value. Since the\n% particles are entangled, actions on one (such as transformation by\n% application of an isomorphism) affects the other in much the same sense as\n% \\emph{action at a distance}. The `{{a-o*b}}' functions mentioned in the\n% introduction, are first-class values and they correspond to these entagled\n% pairs. Finally {{eps*}} operations are sites where corresponding particle and\n% anti-particles annihilate each other. While appealing as an analogy, this\n% description does not imply (or preclude) any formal connection with Physics.\n\n% Are constructions are very similar to those developed in the context\n% of QC. Is this how nature computes? Are the analogies to time\n% traveling particles and anti-particles more concrete in some way? \n\n\\begin{comment}\n  \n--- END -- \n\n\n%% \\begin{center}\n%%   \\includegraphics{diagrams/dispatch.pdf}\n%% \\end{center}\n\n% \\subsection{Other}\n\n%% To summarize negative, fractional, square root, and imaginary types all make\n%% sense. What they help you accomplish as a programmer is to disassociate\n%% global invariants into local ones that can be satisfied independently by\n%% subcomputations with no synchronization or communication. A computation\n%% producing something of type $a/b$ does not need to concern itself with who is\n%% going to supply the missing $b$: it just does its part. Conversely faced with\n%% a complicated task, a computation might decide to break it into pieces and\n%% demand these pieces using negative types. \n\n%% It is no surprise that these types are closely related to quantum mechanics\n%% and that they give us the feel that this is how nature computes. This is\n%% speculation however.\n\n%% In any case, in a framework where information can be copied and deleted, none\n%% of this makes much sense. It is critical that these constraints and demands\n%% can neither be duplicated nor erased.  This gives us the maximum\n%% ``parallelism'' possible.\n\n\n%% Say we have not considered recursion in this paper.\n\n%% The simplest way to connect the In a conventional computational model, one\n%% might realize this situation by simply writing the identity function: the\n%% buyer hands the money to the seller to finish the transaction. The above\n%% sequence of isomorphisms implements this identity function in a much more\n%% interesting way, however.  of the above series of\n\n%% On the producer side, the debt is paid for by the money computation with the\n%% identity function. the producer and consumer must somehow share an explicit\n%% dependency that allows the value. However in our model, the presence of\n%% negative types allows the produced value to satisfy the demand without the\n%% producer or consumer even knowing about each other. As is explained in detail\n%% in\n\n%% Furthermore, we illustrate their true appeal and expressiveness is brought\n%% forth by viewing them in the context of an information-preserving\n%% computational model.\n\n%% In addition, we show how these types enrich our computational model, they\n%% obey the same laws as the rational numbers. \n\n\n%% Specifically, isomorphisms enrich our computational model with have an\n%% interesting computational interpretation\n\nIn particular, linear logic~\\cite{Girard87tcs}, among other contributions,\nexposed an additive/multiplicative distinction in logical connectives and\nrules. In particular, linear logic includes additive disjunctions $\\oplus$\nand conjunctions $\\with$ as well as multiplicative disjunctions $\\parr$ and\nconjunctions $\\otimes$. Duality is also prominent in linear logic: it relates\nthe additive connectives to each other (the dual of $\\oplus$ is $\\with$ and\nvice-versa) and the multiplicative connectives to each other (the dual of\n$\\otimes$ is $\\parr$ and vice-versa).\n\n%% We furthermore demonstrate that, in our model,\n%% programming with these negative and fractional types, is a new ``revolution''\n%% breaking dependencies...\n\nSince Filinski, we've had the\nidea that values and continuations are like mirror images. In a conventional\nlanguage, the negative (continuation) side is implicit and we introduce\ninformation effects on the positive. Trying to recover the duality from this\ndistorted positive side has always been messy. Now it looks clean because we\nhave kept the positive side pure.\n\nContinuations made their introduction to the world of programming language\nsemantics as a mathematical device to model first-class labels and\njumps~\\cite{springerlink:10.1023/A:1010026413531}. In a remarkable\ndevelopment, Filinski~\\cite{Filinski:1989:DCI:648332.755574} observed that\n--- with the right perspective --- this highly imperative concept was\nactually the symmetric dual of values. The heart of the observation is that\nvalues represent entities that flow from producers to consumers while\ncontinuations represent \\emph{demands} for such entities, that flow from\nconsumers to producers. In more detail, Filinski describes continuations as\nrepresenting ``the \\emph{lack} or \\emph{absence} of a value, just as having a\nnegative amount of money represents a debt.'' He then proceeds to construct a\nlanguage where values and continuations are treated truly symmetrically. To\nthat end, he abandons the $\\lambda$-calculus amalgamation of functions and\nvalues and distinguishes between three different syntactic classes:\nfunctions, values, and continuations, with the property that any function can\nbe used either as a value transformer or as a continuation transformer.\n\nThis highly intuitive and appealing idea was further explored and refined by\nmany authors~\\cite{Griffin:1989:FNC:96709.96714, Curien:2000,\n  Wadler:2003, DBLP:conf/rta/Wadler05}. Yet, despite its appeal, the duality\nbetween values and continuations \n\n%% Computationally, symmetry exhibits itself as a duality between two concepts.\n\n%% Symmetry is pervasive in both natural and man-made environments. \n\nIn 1989, Filinski~\\cite{Filinski:1989:DCI:648332.755574} observed that values\nand continuations are dual notions. This observation was followed by numerous\n\n%% We introduced this thesis that computation should be based on isomorphisms\n%% that preserve information~\\cite{infeffects}. Since Filinski, we've had the\n%% idea that values and continuations are like mirror images. In a conventional\n%% language, the negative (continuation) side is implicit and we introduce\n%% information effects on the positive. Trying to recover the duality from this\n%% distorted positive side has always been messy. Now it looks clean because we\n%% have kept the positive side pure.\n\n%% In a technical sense, this paper extends the language of isomorphisms\n%% {{Pi}}, with duality. Unlike Linear logic \\cite{Girard87tcs} and\n%% other systems which have one notion of duality over additive and\n%% multiplicative components, {{PiEE}} has two notions of duality\n%% -- an additive duality over the monoid {{(0, +)}} and a multiplicative\n%% duality over the monoid {{(1, *)}}. Each axis of duality also give us\n%% a function space and hence {{PiEE}} has an additive function\n%% space corresponding to a notion of control or backtracking and a\n%% multiplicative function space corresponding to a notion of unification\n%% or constraint satisfaction.\n\nThe world of computation we are describing has:\n\\begin{itemize}\n\\item suppliers, \n\\item consumers, and\n\\item bi-directional transformations\n\\end{itemize}\nThis is the same world described by the papers on the duality of computation\nbut that work only scratched the surface! We have the following features:\n\\begin{itemize}\n\\item we can start from the supplier and push the values towards the\n  consumer (call-by-value in the duality of computation papers)\n\\item we can start from the consumer and pull the values from the suppliers\n  (call-by-name in the duality of computation papers)\n\\item we can combine the pushing and pulling and values using eta/epsilon for\n  sum types; these allow us to at any point in the middle of the computation\n  create out of nothing a value to send to the consumers and a demand to send\n  to the suppliers.\n\\item we can break a big data structure into fragments described by\n  fractional types; the suppliers and consumers can produce and consume the\n  pieces completely independently of each other. Eventually the pieces will\n  fit together at the consumer to produce the desired output.\n\\item we can break a bi-directional transformation into pieces using square\n  roots\n\\item we can take into account that values have phase (complex numbers),\n  i.e., it is not that they flow towards the consumer or just towards the\n  suppliers; they can be flowing in direction that ``30 degrees'' towards the\n  consumer for example.\n\\end{itemize}\n\n%% So it is all about breaking dependencies in some sense to allow for maximum\n%% autonomy (parallelism) of subcomputations. It is probably the case that to\n%% make full use of square root types and imaginary types, we have to move to a\n%% vector space. If that's the case, we should probably leave this stuff out and\n%% focus on negative and fractional types and only have a short discussion of\n%% the polynomials restricted to seven trees in one and similar issues.\n\n%% The conventional idea is to divide the world into a ``real'' one and a\n%% ``virtual'' one. In the ``real'' world, we can define datatypes like\n%% \\verb|t=t^2+1| but we don't have additive inverses so it makes no sense to\n%% talk of negative types and we can't rearrange the terms in the datatype\n%% definition. However the observation is that we can map these datatypes to a\n%% virtual world that has more structure (a ring that provides additive inverses\n%% or a field that also provides multiplicative inverses) and then perform\n%% computations in the ring/field. If we perform computations in the ring, then\n%% some of these will use additive inverses in ways that cannot be mapped back\n%% to the ``real'' world. Much of current research attempts to characterize\n%% which computations done in the ring are valid isomorphisms between datatypes\n%% in the ``real'' world. This is nice but is not what I am after. In fact I am\n%% not interested in the ring or the semiring at all. I am interested in the\n%% field and I want this field to be \\textbf{the real world.} This is partly\n%% motivated by the fact that Quantum Mechanics seems to demand an underlying\n%% field and more generally that the field provides the maximum generality in\n%% slicing and dicing computations. So assuming I live in a field and that the\n%% negative, fractional, square root, and imaginary types are all ``real,'' how\n%% do I compute in this field? Clearly there will be constraints on\n%% ``measurement'' in the sense that a full program cannot produce any of the\n%% crazy types but that's done outside the formalism in some sense just as in\n%% Quantum Computing. The main question I am after is how to compute in this\n%% field with first-class negative, fractional, etc. types. As I mentioned in my\n%% previous email, we can produce programs that have types \\verb|t^3 <-> -1| and\n%% they ``run'' (but only to give infinite loops). \n\n%% So when a programmer writes the datatype declaration \\verb|t = t^2+1|,\n%% if we allow negative etc. then this is effectively writing\n%% \\verb|t = cubicroot{-1}|. If we are in the field then computations\n%% that manipulate these trees can be sliced and diced even at interfaces\n%% that expose the cubic root and the imaginary types.\n\n%% Future work: develop a type system for a ``normal language'' that has\n%% negative, fractional, etc. types as first-class types. More long term,\n%% instead of adding one polynomial at a time, we can go to an algebraically\n%% closed field. The complex numbers is an obvious choice but I would rather go\n%% to something computable like the field of algebraic numbers. Is the adele\n%% ring or the p-adics relevant here?\n\n\nWe show a deep symmetry between functions and delimited continuations, values\nand continuations that arises in {{Pi}} in a manner that is reminiscent\nof Filinski's Symmetric \\lcal ~\\cite{Filinski:1989:DCI:648332.755574}. The\nsymmetry arises by extending {{Pi}} with a notion of additive duality\nover the monoid {{(+, 0)}} by including {{eta+}} and {{eps+}} operators of\nCompact Closed Categories. The resulting dual types, which we denote {{-b}},\nhave a time traveling ``backward information flow'' interpretation and allow\nfor the encoding of higher-order function and iteration via the construction\nof trace operators, thereby making the extended language {{PiEE}} a\nTuring-complete reversible programming language with higher-order functions\nand first-class delimited continuations.\n\n%% We introduced this thesis that computation should be based on isomorphisms\n%% that preserve information~\\cite{infeffects}. Since Filinski, we've had the\n%% idea that values and continuations are like mirror images. In a conventional\n%% language, the negative (continuation) side is implicit and we introduce\n%% information effects on the positive. Trying to recover the duality from this\n%% distorted positive side has always been messy. Now it looks clean because we\n%% have kept the positive side pure.\n\n%% The way to think about something of type $A$ is that it is a value we have\n%% produced. The way to think about something of type $-A$ is that is a value we\n%% have already consumed. \n\nOther interpretations of the types of think about. The first one is\narithmetic obviously. Another one is languages consisting of sets of\nstring. The type 0 is the empty set, the type 1 is the set containing the\nempty word, the $+$ constructor corresponds to union, and the $*$ constructor\ncorresponds to concatenation. The constructor $-$ would not correspond to set\ndifference however. It would correspond to marking the elements in the set as\n``consumed'' so that if we take the union and a ``consumed'' element appears\nin the other set, the two cancel. This makes it clear that concatenating a\nproduced $a$ and a consumed $b$ is not the same as concatenating a consumed\n$a$ and a produced $b$. They really need to be kept separate. Incidentally,\ndivision would be defined as follows:\n\\[\nL_1 / L_2 = \\{ x ~|~ xy \\in L_1 \\mbox{~for~some~} y \\in L_2 \\}\n\\]\n\nFilinski proposes that continuations are a \\emph{declarative} concept. He,\nfurthermore, introduces a symmetric extension of the $\\lambda$-calculus in\nwhich values and continuations are treated as opposites. This is essentially\nwhat we are proposing with one fundamental difference: our underlying\nlanguage is not the $\\lambda$-calculus but a language of pure isomorphisms in\nwhich information is preserved. This shift of perspective enables us to\ndistill and generalize the duality of values and continuations: in\nparticular, in the conventional $\\lambda$-calculus setting values and\ncontinuations can be erased and duplicated which makes it difficult to\nmaintain the correspondence between a value and its negative counterpart.\n\nThe idea of using negative types to model information flowing backwards,\ndemand for values, continuations, etc. goes back to at Filinski's thesis. We\nrecall these connections below but we first note that all these systems are\ncomplicated because in all these systems information can be ignored,\ndestroyed, or duplicated. Clearly the possibility of erasure of information\nwould mean that our credit card transaction is incorrect. In our work,\ninformation is maintained and hence we have a guarantee that, in a closed\nprogram, the debt must be accounted and paid for.\n\nMuch of previous work builds on the idea that there is one duality in\ncomputation between values and continuations which manifests itself as a\nduality between the call-by-value and call-by-name parameter-passing\nmechanisms. The former mechanism focuses on evaluating expressions to values\neven if these values are not demanded by the context; the latter focuses on\nevaluating expressions to continuations even if these continuations might be\naborted. The idea that a continuation is dual to a value is intuitive but\nthen one would expect that the sum of two values naturally corresponds to the\nsum of two continuations and that the product of two values naturally\ncorresponds to the product of two continuations.\n\ncheck and say that our work teases the continuations into a negative part\n(which simply demands a value) and a fractional part (which imposes\nconstraints on how this value will be used). So something like $-1/c$ is\nneeded to express a conventional continuation. Having two dualities makes the\nwhole calculus natural and symmetric.\n\nConsider a continuation that takes $x$ and $y$ and swaps them. It can't be\nexpressed using two conventional continuations because the demand and the way\nit is used are entangled together.\n\nIn accounts that are linear, the value and continuation that comprise the\nsubtractive type need to be constrained to ``stay together.'' This can be\nachieved by various restrictions. In this work we have no such constraints,\nthe negative value can flow anywhere. The entire system guarantees that any\nclosed program would have to account for it. We don't have to introduce\nspecial constraints to achieve that. Zeilberger in the paper on polarity and\nthe logic of delimited continuations uses polarized logic: he shows that if\npositive and negative values are completely symmetric except that answer\ntypes are positive, then the framework accommodates delimited\ncontinuations. But he interprets negative values are control operators, or as\nvalues defined by the shape of their continuations. We simply interpret\nvalues of negative type as values flowing in the ``other'' direction.\n\nThis is essentially what we are proposing with one fundamental difference:\nour underlying language is not the $\\lambda$-calculus but a language of pure\nisomorphisms in which information is preserved. This shift of perspective\nenables us to distill and generalize the duality of values and continuations:\nin particular, in the conventional $\\lambda$-calculus setting values and\ncontinuations can be erased and duplicated which makes it difficult to\nmaintain the correspondence between a value and its negative counterpart. In\ncontrast, in our setting, one can start from the empty type $0$, introduce a\npositive value and its negative counterpart, and let each of these flow in\narbitrary ways. The entire framework guarantees that neither the value nor\nits negative counterpart will be deleted or duplicated and hence that, in any\nclosed program, the ``debt'' corresponding to the negative value is paid off\nexactly once. The forward and backward executions in our framework correspond\nto call-by-value and call-by-name. This duality was observed by Filinski and\nothers following him but it is particularly clean in our framework.\n\n\\paragraph*{Logic Programming and Backtracking.} \nThis is a constrained form of backtracking and a constrained form of\nlogic programming.\n\n\\paragraph*{Linear Logic and GoI.} \nSay something. \n\n\\paragraph*{Int Construction.}\nFor a traced monoidal category {{C}} the Int construction produces a Compact\nClosed Category called Int {{C}} \\cite{joyal1996traced}.  Further we know\nthat the target of the Int construction is isomorphic to the target of \\G\nconstruction of Abramsky \\cite{Abramsky96:0} from Haghverdi. However, note\nthat the {{PiEE}} is not the same as the image of the Int construction\non {{Pi0}}, since the later lacks a multiplicative tensor that\ndistributes over the additive tensor in Int {{Pi0}}.\n\nonce we combine the two structures, we seem to retain the monoidal\nstructure. How!?\n\n\\end{comment}\n\n\\acks We thank Jacques Carette for stimulating discussion, and Michael Adams,\nWill Byrd, Lindsey Kuper, and Yin Wang for helpful comments and\nquestions. This project was partially funded by Indiana University's Office\nof the Vice President for Research and the Office of the Vice Provost for\nResearch through its Faculty Research Support Program.  We also acknowledge\nsupport from Indiana University's Institute for Advanced Study.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{small}\n\\bibliographystyle{abbrvnat}\n\\bibliography{cites}\n\\end{small}\n\n\n\\end{document}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n", "meta": {"hexsha": "061af368fb9c50746abe9ea3e18d54694f35541b", "size": 139096, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "rationals/fields.tex", "max_stars_repo_name": "JacquesCarette/pi-dual", "max_stars_repo_head_hexsha": "003835484facfde0b770bc2b3d781b42b76184c1", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2015-08-18T21:40:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T01:07:57.000Z", "max_issues_repo_path": "rationals/fields.tex", "max_issues_repo_name": "JacquesCarette/pi-dual", "max_issues_repo_head_hexsha": "003835484facfde0b770bc2b3d781b42b76184c1", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-06-07T16:27:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-29T20:41:23.000Z", "max_forks_repo_path": "rationals/fields.tex", "max_forks_repo_name": "JacquesCarette/pi-dual", "max_forks_repo_head_hexsha": "003835484facfde0b770bc2b3d781b42b76184c1", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-05-29T01:56:33.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-10T09:47:13.000Z", "avg_line_length": 43.3185923388, "max_line_length": 162, "alphanum_fraction": 0.7129320757, "num_tokens": 38120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.30920303568773516}}
{"text": "\\section{Declaration of Circuits}\n\nThe construction of RKQC is designed to be as similar as possible to C++ programs which contain a number of functions. To this end, circuits are specifiable through a main function, as well as through various submodules that are declared exactly as common C++ functions. Exactly one module must be named \"int main\", however this module, as well as any module, can call any other module at any time.\n\n\\section{Signal Types}\n\nThere is one major type of signal in RKQC, the \\textbf{qint}. This type forms the basis for the five other types of signals that are derived from this main class:\n\n\\begin{itemize}\n    \\item qbit\n    \\item zero\\_to\\_garbage ancilla\n    \\item zero\\_to\\_zero ancilla\n    \\item one\\_to\\_garbage ancilla\n    \\item one\\_to\\_one ancilla\n\\end{itemize}\n\nAll of the above signals can be declared and used in the specification of gates and circuit descriptions. The primary differences are that the \"\\_to\\_garbage\" ancilla are ancilla signals that are not guaranteed to maintain their original state during computation, while the two other ancilla types do make this guarantee.\n\nAs will be explained later on, all of these signals are of a base type \\textbf{qint}, which allows for circuit description flexibility when creating and passing parameters to submodules.\n\n\\section{Creating and Using Modules}\n\nAt the circuit level, both user defined modules as well as built in modules can be instantiated in the same fashion. \n\nIn the example circuit \"e008\\_swap.cpp\", the built in function \"cnot\" is called, creating CNOT gates on the qubits passed in as parameters:\n\n\\begin{lstlisting}\n    int main( int argc, char ** argv )\n    {\n        qbit a;\n        qbit b;\n\n        cnot(a, b);\n        cnot(b, a);\n        cnot(a, b);\n\n        return 0;\n    }\n\\end{lstlisting}\n\nIn exactly the same fashion, a circuit designer can create a submodule, and instantiate it within the main function, as in file \"e009\\_swap\\_triples.cpp\":\n\n\\begin{lstlisting}\n    void swap_bits( qint x, qint y){\n        cnot(x, y);\n        cnot(x, y);\n        cnot(x, y);\n    }\n\n    int main( int argc, char ** argv ){\n        qbit a0;\n        qbit a1;\n        qbit a2;\n\n        qbit b0;\n        qbit b1;\n        qbit b2;\n\n        swap_bits(a0, b0);\n        swap_bits(a1, b1);\n        swap_bits(a2, b2);\n\n        return 0;\n    }\n\\end{lstlisting}\n\n\\section{Arrays}\n\nRKQC also allows for multi-dimensional arrays of signals to be declared and used in circuits. To demonstrate this, file \"e010\\_swap\\_triples\\_2.cpp\" replicates the functionality of \"e009\\_swap\\_triples.cpp\" with arrays:\n\n\\begin{lstlisting}\n    void swap_bits( qint x, qint y){\n        cnot(x, y);\n        cnot(x, y);\n        cnot(x, y);\n    }\n\n    int main( int argc, char ** argv ){\n        qbit a(3);\n        qbit b(3);\n\n        swap_bits( a[0], b[0] );\n        swap_bits( a[1], b[1] );\n        swap_bits( a[2], b[2] );\n\n        return 0;\n    }\n\\end{lstlisting}\n\n\\section{Signals and Gates}\n\nGates are built in modules that can be instantiated in a variety of methods, with a variety of signal types. Specifically, \n\\begin{itemize}\n    \\item single qint signals,\n    \\item qint arrays,\n    \\item single qbit signals,\n    \\item qbit arrays,\n    \\item single ancilla signals, and\n    \\item ancilla arrays\n\\end{itemize}\nall are capable of being passed through as parameters to built in gates. For an example of this, file \"e002\\_signals\\_and\\_gates.cpp\" calls all of the intrinsic built in gates with all of the different signal types: \n\\begin{lstlisting}\n    int main( int argc, char ** argv )\n    {\n    \n        qbit a;\n        qbit b;\n        qbit c;\n        qbit d(10);\n    \tqbit e(10);\n    \tqbit f(10);\n    /*------------ Gates Called By Qubit --------------*/\n        NOT(a);\n        cnot(a,b);\n        toffoli(a, b, c);\t\n    /*------------ Gates Called By Register Index -----*/ \n        NOT(d[0]);\n        cnot(d[1], d[9]);\n        toffoli(d[0], e[0], c[0]);\n    /*------------ Gates Called By Mixed Register Index & Qbits -----*/ \n        cnot(a, d[0]);\n        cnot(e[0], b);\n    \ttoffoli(d[0], a, b);\n    \ttoffoli(a, d[0], b);\n    \ttoffoli(a, b, d[0]); \n    \ttoffoli(d[0], e[0], a);\n    \ttoffoli(d[0], a, e[0]);\n    \ttoffoli(a, d[0], e[0]);\n    /*------------ Gates Called By Full Qbit Reg ------*/ \n    \tNOT(d);\n    \tcnot(d, e);\n    \ttoffoli(d, e, f);\n    \n        return 0;\n    }\n\\end{lstlisting}\n\n\\section{Assign Value}\n\nA commonly used function of assigning value of one signal to another is built into RKQC in the form of a function:\n\\begin{lstlisting}\n    assign_value_of_b_to_a();\n\\end{lstlisting}\n\nThis function can be instantiated a number of different ways, with integer constants or with two \\textbf{qint} signals. These instantiation methods are detailed in file \"e004\\_assign\\_value.cpp\":\n\\begin{lstlisting}\n    int main( int argc, char ** argv )\n    {\n        qbit a;\n        assign_value_of_b_to_a(a, \"0\", 1);\n    \n        qbit b(8);\n        assign_value_of_b_to_a(b, \"1\", 8);\n    \n        qbit c(8);\n        assign_value_of_b_to_a(c, b, 8);\n    \n        return 0;\n    }\n\\end{lstlisting}\n\n\\section{Integer Arithmetic Modules}\n\nRKQC comes with implementations of quantum adders and multipliers developed in recent theoretical work. For instance, the quantum ripple-carry adder implemented in the function: \n\n\\begin{lstlisting}\n    a_eq_a_plus_b();\n\\end{lstlisting}\n\nis derived from work by Wang et. al \\cite{adder}, and an example of usage is contained in file \"e005\\_adder.cpp\": \n\n\\begin{lstlisting}\n    int main( int argc, char ** argv )\n    {\n        qbit a(32);\n        qbit b(32);\n    \n        a_eq_a_plus_b(a,b,32);\n    \n        return 0;\n    }\n\\end{lstlisting}\n\nAlternatively, an implementation of an ancilla-free addition circuit is also contained within RKQC, derived from earlier work by Cuccaro \\cite{Cuccaro}. \n", "meta": {"hexsha": "e0409ed489de4e3cdb1144059d3afbce8bf1a578", "size": 5825, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/ch-rkqc/examples.tex", "max_stars_repo_name": "clairechingching/ScaffCC", "max_stars_repo_head_hexsha": "737ae90f85d9fe79819d66219747d27efa4fa5b9", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 158, "max_stars_repo_stars_event_min_datetime": "2016-07-21T10:45:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T00:56:20.000Z", "max_issues_repo_path": "docs/ch-rkqc/examples.tex", "max_issues_repo_name": "clairechingching/ScaffCC", "max_issues_repo_head_hexsha": "737ae90f85d9fe79819d66219747d27efa4fa5b9", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 35, "max_issues_repo_issues_event_min_datetime": "2016-07-25T01:23:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T16:05:50.000Z", "max_forks_repo_path": "docs/ch-rkqc/examples.tex", "max_forks_repo_name": "clairechingching/ScaffCC", "max_forks_repo_head_hexsha": "737ae90f85d9fe79819d66219747d27efa4fa5b9", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 62, "max_forks_repo_forks_event_min_datetime": "2016-08-29T17:28:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T17:55:58.000Z", "avg_line_length": 31.4864864865, "max_line_length": 398, "alphanum_fraction": 0.6436051502, "num_tokens": 1573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.30920303568773516}}
{"text": "\\subsubsection{Benchmark Default Curve}\\label{ss:benchmark_default_curve}\n\nDefault curves can be set up as a difference curve of two yield curves as shown in listing\n\\ref{lst:defaultcurve_benchmark}. A typical use case is to back out a default curve from an all-in discounting curve\nfitted to a series of liquid bond prices (the ``source curve'') and a benchmark curve representing a benchmark funding\nlevel. The default curve can then be used in models consuming a benchmark curve and a default curve.\n\nIf $P_B(0,t)$ and $P_S(0,t)$ denote the discount factors of the given benchmark\nand source curve respectively the resulting default term structures has survival probabilities\n\n\\begin{equation}\nS(t) = \\left( P_S(0,t) / P_B(0,t) \\right) ^ { 1/(1-R) }\n\\end{equation}\n\non the given pillar times. Her, $R$ is the specified recovery rate. If the recovery rate is zero, which is the usual\ncase, the formula simplifies to\n\n\\begin{equation}\n  S(0,t) = P_S(0,t) / P_B(0,t)\n\\end{equation}\n\nThe interpolation is backward flat in the hazard rate. The meaning of each node is as follows:\n\n\\begin{itemize}\n\\item CurveId: The curve id.\n\\item CurveDescription: The curve description.\n\\item Currency: The currency of the curve.\n\\item Type: Must be set to Benchmark.\n\\item DayCounter: The day counter used to convert dates to times.\n\\item RecoveryRate [optional]: The recovery rate for the resulting default curve. Defaults to zero. The recovery rate\n  can be a market quote as usual or also a fixed numeric value for this curve type.\n\\item BenchmarkCurve: The benchmark yield curve, typically this is the standard Ibor curve in the currence\n  (e.g. EUR-EURIBOR-6M, USD-Libor-3M, ...)\n\\item SourceCurve: The all-in discounting curve.\n\\item Pillars: The pillars on which to match the source curve\n\\item SpotLag: The pillar dates are derived using the spot lag and the tenors as specified in the Pillars node using the\n  specified calendar.\n\\item Calendar: The calendar used to derive the pillar dates.\n\\item Extrapolation [Optional]: If set to true, the curve is extrapoalted beyond the last pillar. Defaults to true.\n\\item AllowNegativeRates [Optional]: If set to true, the check for non-negative instantaneous hazard rate in the result\n  curve is disabled, i.e. the relation $P_S(0,t) \\leq P_B(0,t)$ is not enforced. This flag should be enabled with care,\n  i.e.  a model consuming the resulting default curve must be able to handle negative hazard rates appropriately. On the\n  other hand in some situations it is natural that the source curve rates are below the benchmark rates. Defaults to\n  false.\n\\end{itemize}\n\n\\begin{longlisting}\n%\\hrule\\medskip\n\\begin{minted}[fontsize=\\footnotesize]{xml}\n    <DefaultCurve>\n      <CurveId>BOND_YIELD_EUR_OVER_OIS</CurveId>\n      <CurveDescription>Default curve derived as bond yield curve over Eonia</CurveDescription>\n      <Currency>EUR</Currency>\n      <Type>Benchmark</Type>\n      <DayCounter>A365</DayCounter>\n      <RecoveryRate>RECOVERY_RATE/RATE//SNR/USD</RecoveryRate>\n      <BenchmarkCurve>Yield/EUR/EUR6M</BenchmarkCurve>\n      <SourceCurve>Yield/EUR/BOND_YIELD_EUR</SourceCurve>\n      <Pillars>1Y,2Y,3Y,4Y,5Y,7Y,10Y</Pillars>\n      <SpotLag>0</SpotLag>\n      <Calendar>TARGET</Calendar>\n      <Extrapolation>true</Extrapolation>\n      <AllowNegativeRates>false</AllowNegativeRates>\n    </DefaultCurve>\n  </DefaultCurves>\n\\end{minted}\n\\caption{Benchmark default curve}\n\\label{lst:defaultcurve_benchmark}\n\\end{longlisting}\n\n\\subsubsection{Multi-Section Default Curve}\\label{ss:multisection_default_curve}\n\nDefault curves can be build by stitching together instantaneous hazard rates from multiple source curves for multiple\ndate ranges as shown in listing \\ref{lst:defaultcurve_multisection}.\n\nThe hazard rate of the resulting curve is taken from the $i$th input curve ($i=0,1,2,\\ldots$) for dates before the $i$th\nswitch date and (if $i>0$) on or after the $i-1$th switch date. The day counter of all input curves should be equal to\nthe day counter of the result curve. The interpolation is hardcoded as backward flat in the hazard rate.\n\nIf not given, the recovery rate $R$ is assumed to be zero. The result default curve's survival probabiltiies are\ncomputed as\n\n\\begin{equation}\n  S(t) = \\left[ \\left(\\frac{P_{S,n}(t)}{P_{S,n}(t_{n})}\\right)^{(1-R_n)} \\Pi_{i=0}^{n-1} \\left(\\frac{P_{S,i}(t_{i+1})}{P_{S,i}(t_{i})}\\right)^{(1-R_i)} \\right] ^ { \\frac{1}{1-R} }\n\\end{equation}\n\nwhere $P_{S,i}$ is the survival probability of the $i$th source curve, $R_i$ is the associated recovery rate for the\n$i$th source curve, $n$ is chosen such that $P_{S,n}$ is the relevant source curve for time $t$ according to the given\nswitch dates and curve $i$ is relevant for times in $[t_i,t_{i+1}]$.\n\nThe meaning of each node is as follows:\n\n\\begin{itemize}\n\\item CurveId: The curve id.\n\\item CurveDescription: The curve description.\n\\item Currency: The currency of the curve.\n\\item Type: Must be set to MutliSection.\n\\item SourceCurves: The list of input default curves.\n\\item SwitchDates: The list of dates where we switch from one input curve to the next. The number of switch dates must\n  be one less than the number of source curves.\n\\item DayCounter: The day counter used to convert dates to times.\n\\item RecoveryRate [optional]: The recovery rate for the resulting default curve. Defaults to zero. The recovery rate\n  can be a market quote as usual or also a fixed numeric value for this curve type.\n\\item Extrapolation [Optional]: If set to true, the curve is extrapoalted beyond the last pillar. Defaults to true.\n\\end{itemize}\n\n\n\\begin{longlisting}\n%\\hrule\\medskip\n\\begin{minted}[fontsize=\\small]{xml}\n<DefaultCurve>\n   <CurveId>MyMultiSectionDefaultCurve</CurveId>\n   <CurveDescription>Default curve with multiple sections</CurveDescription>\n   <Currency>USD</Currency>\n   <Type>MultiSection</Type>\n   <SourceCurves>\n     <SourceCurve>Default/USD/Generic_AA_Curve</SourceCurve>\n     <SourceCurve>Default/USD/Generic_B_Curve</SourceCurve>\n     <SourceCurve>Default/USD/Generic_C_Curve</SourceCurve>\n   </SourceCurves>\n   <SwitchDates>\n     <SwitchDate>2020-10-01</SwitchDate>\n     <SwitchDate>2021-12-01</SwitchDate>\n   <SwitchDates>\n   <Extrapolation>true</Extrapolation>\n   <DayCounter>A365</DayCounter>\n   <RecoveryRate>RECOVERY_RATE/RATE/NAME/SR/USD</RecoveryRate>\n</DefaultCurve>\n\\end{minted}\n\\caption{Multi-Section default curve}\n\\label{lst:defaultcurve_multisection}\n\\end{longlisting}\n", "meta": {"hexsha": "594cd303efe883c65ef69f88e9ba565d25bdb6fa", "size": 6425, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Docs/UserGuide/curve_configurations/default_curves_other.tex", "max_stars_repo_name": "mrslezak/Engine", "max_stars_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 335, "max_stars_repo_stars_event_min_datetime": "2016-10-07T16:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T07:12:03.000Z", "max_issues_repo_path": "Docs/UserGuide/curve_configurations/default_curves_other.tex", "max_issues_repo_name": "mrslezak/Engine", "max_issues_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 59, "max_issues_repo_issues_event_min_datetime": "2016-10-31T04:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T16:39:57.000Z", "max_forks_repo_path": "Docs/UserGuide/curve_configurations/default_curves_other.tex", "max_forks_repo_name": "mrslezak/Engine", "max_forks_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 180, "max_forks_repo_forks_event_min_datetime": "2016-10-08T14:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:43:05.000Z", "avg_line_length": 48.3082706767, "max_line_length": 179, "alphanum_fraction": 0.7559533074, "num_tokens": 1753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736783928749127, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.30920302783065506}}
{"text": "% !TeX spellcheck = en_GB\n\\documentclass[a4paper, 11pt]{article}\n\\usepackage[english]{babel}\n\\usepackage{newtxtext,newtxmath}\n\n\\usepackage{amsmath}\n\\usepackage{mathtools}\n\\usepackage{dramatist}\n\\usepackage{dirtytalk}\n\\usepackage{multicol}\n\\usepackage{soul}\n\\usepackage{xcolor}\n\n\\usepackage[round]{natbib}\n\n\\usepackage{geometry}\n\\geometry{\n\ta4paper,\n\ttotal={150mm,257mm},\n\ttop=20mm,\n}\n\\usepackage{adjustbox}\n\n\\usepackage{hyperref}\n\\hypersetup{\n\tcolorlinks=true,\n\tlinkcolor=blue,\n\tfilecolor=blue,      \n\turlcolor=blue,\n\tcitecolor=blue\n}\n\n\\setlength\\parindent{0pt}\n\n%opening\n\\title{\\textbf{Natural Language Processing}\\\\Portfolio II}\n\\author{\\textbf{Leon F.A. Wetzel}\\\\ Information Science \\\\ Faculty of Arts - University of Groningen\\\\ \\texttt{l.f.a.wetzel@student.rug.nl}}\n\n\\begin{document}\n\n\\maketitle\n\n\\begin{abstract}\n\t\n\tIn this document, you can find the results and explanations for the assignments of the second part of the portfolio for the course Natural Language Processing, taught at the University of Groningen. The corresponding Python code can be found at \\url{https://github.com/leonwetzel/natural-language-processing}\\footnote{All code will be published after the course has been completed}. Note that version control of Jupyter notebooks is done via \\texttt{jupytext}, so do not forget to convert the relevant Python scripts to notebooks yourself!\n\n\\end{abstract}\n\n\\section{Week 5 - Neural Language Models}\n\n\\subsection{Neurons}\n\n\\noindent\\fbox{%\n\t\\parbox{\\textwidth}{%\nConsider the basic neuron $y$ with a sigmoid activation $\\sigma$ ($g$ in the image).\n\n$$y = \\sigma(x*w+b) \\qquad \\sigma = s(z) = \\frac{1}{1 + e^{-z}} \\qquad y = \\sigma(x*w+b) = \\frac{1}{1 + e^{-(x*w+b)}}$$\n\nGiven the weight and bias values $x = [0.3, 0.9, 0.1]$, $w = [-0.2, 0.8, -0.6]$, $b = 0.4$ compute the value of $y$ and provide intermediate calculations. \n\t}%\n}\\\\\n\n\n\\begin{equation} \\label{eq1}\n\t\\begin{split}\n\t\ty & = \\frac{1}{1 + e^{-(w*x+b)}} = \\frac{1}{1+e^{-(0.3*-0.2 + 0.9*0.8 + 0.1*-0.6 + 0.4)}} \\\\\n\t\t& = \\frac{1}{1 + e^{-0.06 + 0.72 + -0.06 + 0.4}} = \\frac{1}{1 + e^{-1}} \\\\\n\t\t& = \\frac{1}{1 + 0.36787944117} = 0.73105857863\n\t\\end{split}\n\\end{equation}\n\n\\subsection{Relu}\n\n\\noindent\\fbox{%\n\t\\parbox{\\textwidth}{%\nAssume the same basic neuron as in 5.1, but now with ReLU activation, where\n\n$$\\sigma = \\text{relu}(z) = max(z,0)$$\n\nGive the updated formula for computing $y$, as well as the new value of $y$ (with intermediate calculations).\n\t}%\n}\\\\\n\n$$y = \\sigma(x*w+b) \\qquad \\sigma = \\text{relu}(z) = max(z,\\theta) \\qquad y = \\sigma(x*w+b) = max(x*w+b, 0)$$\n\n\\begin{equation} \\label{eq1}\n\t\\begin{split}\n\t\ty & = max(x*w+b, 0) = max(0.3*-0.2 + 0.9*0.8 + 0.1*-0.6 + 0.4, 0) \\\\\n\t\t& = max(-0.06 + 0.72 + -0.06 + 0.4, 0) \\\\\n\t\t& = max(1, 0) = 1\n\t\\end{split}\n\\end{equation}\n\n\\subsection{Model size}\n\n\\noindent\\fbox{%\n\t\\parbox{\\textwidth}{%\nThe feed-forward neural network below with a vocabulary of 50.000 words represented by one-hot vectors, a context window of 3 words, a projection layer with $d=100$, a hidden layer $d_h=500$, like the one below, has a total of $P = E + W + U$ trainable parameters. Which of the following has a bigger impact on the number of parameters:\n\n\\begin{enumerate}\n\t\\item increasing context-size from 3 to 4, or\n\t\\item increasing vocabulary from 50.000 to 51.000 words\n\\end{enumerate}\nGive the calculations of $P$ to motivate your answer.\n\t}%\n}\\\\\n\n\\begin{equation}\n\t\\left.\\begin{aligned}\n\t\tE &= d*|V| = 100 * 50.000 = 5.000.000\\\\\n\t\tW &= d_h * 3d = 500 * 3 * 100 = 150.000\\\\\n\t\tU &= |V| * d_h = 50.000 * 500 = 25.000.000\\\\\n\t\tP &= E + W + U = 5.000.000 + 150.000 + 25.000.000 = 30.150.000\n\t\\end{aligned}\n\t\\right\\}\n\t\\qquad \\text{CS = 3}\n\\end{equation}\n\n\\begin{equation}\n\t\\left.\\begin{aligned}\n\t\tE &= d*|V| = 100 * 50.000 = 5.000.000\\\\\n\t\tW &= d_h * 4d = 500 * 4 * 100 = 200.000\\\\\n\t\tU &= |V| * d_h = 50.000 * 500 = 25.000.000\\\\\n\t\tP &= E + W + U = 5.000.000 + 200.000 + 25.000.000 = 30.200.000\n\t\\end{aligned}\n\t\\right\\}\n\t\\qquad \\text{CS = 4}\n\\end{equation}\n\n\\begin{equation}\n\t\\left.\\begin{aligned}\n\t\tE &= d*|V| = 100 * 51.000 = 5.100.000\\\\\n\t\tW &= d_h * 3d = 500 * 3 * 100 = 150.000\\\\\n\t\tU &= |V| * d_h = 51.000 * 500 = 25.500.000\\\\\n\t\tP &= E + W + U = 5.100.000 + 150.000 + 25.500.000 = 30.750.000\n\t\\end{aligned}\n\t\\right\\}\n\t\\qquad \\text{V = 51.000}\n\\end{equation}\n\nIncreasing the vocabulary size leads to a higher amount of trainable parameters, contrary to increasing the context-size. The size of vocabulary affects both $E$ and $U$ (opposed to only $W$ when changing the context size), which leads to higher values in the summation.\n\\subsection{Architectures}\n\n\\noindent\\fbox{%\n\t\\parbox{\\textwidth}{%\nProvide at least one example of an NLP application for each of the following task formulations. Try to come up with examples that are different from those mentioned in class.\n\t}%\n}\\\\\n\n\\begin{table}[h]\n\t\\centering\n\t\\begin{tabular}{l|l}\n\t\\textbf{Task formulation}\t& \\textbf{Example(s)} \\\\ \\hline\n\tOne-to-many\t& Poem generation \\\\\n\tMany-to-one\t& Language detection \\\\\n\tMany-to-many (seq2seq)\t& Document summarization \\\\\n\tMany-to-many (sequence labelling) & Semantic tagging\n\t\\end{tabular}\n\t\\caption{Examples per task formulation for RNN's}\n\t\\label{tab:examples_rnn}\n\\end{table}\n\n\\subsection{Probing}\n\n\\noindent\\fbox{%\n\t\\parbox{\\textwidth}{%\nThink of a grammatical phenomenon in a language of your choice, and come up with at least 10 example sentences to probe whether the model makes the correct predictions. Think of cases where the context makes it clear that the mask has to be plural or singular, that a verb has to have a particular form (like plural or singular, or participle or infinitive), that a specific (personal, possessive, reflexive) pronoun has to be used, that an adjective or noun has to have a specific inflection (like in German and more generally in languages with a rich case and/or gender marking system). There is a host of literature on this, see for instance Marvin and Linzen (for English) and Sahin et al (for multilingual probes).\n\t}%\n}\\\\\n\n\\begin{enumerate}\n\t\\item De minister-president heeft [MASK] handtekening gezet onder de bepaling.\n\t\t\\begin{enumerate}\n\t\t\\item de;\n\t\t\\item een;\n\t\t\\item geen;\n\t\t\\item zijn;\n\t\t\\item deze;\n\t\\end{enumerate}\n\t\\item De ontwikkelaars onthouden [MASK] van commentaar op hun code.\n\t\\begin{enumerate}\n\t\t\\item software;\n\t\t\\item ook;\n\t\t\\item gebruik;\n\t\t\\item code;\n\t\t\\item niet;\n\t\\end{enumerate}\n\t\\item Het ijsje begon met [MASK] toen de zon doorbrak.\n\t\t\\begin{enumerate}\n\t\t\\item ij;\n\t\t\\item ,;\n\t\t\\item zon;\n\t\t\\item :;\n\t\t\\item water;\n\t\\end{enumerate}\n\t\\item De universiteit investeerde [MASK] in onderzoeken naar kunstmatige intelligentie.\n\t\\begin{enumerate}\n\t\t\\item ook;\n\t\t\\item verder;\n\t\t\\item \\#\\#n;\n\t\t\\item vooral;\n\t\t\\item zich;\n\t\\end{enumerate}\n\t\\item Het zwaard van Damocles hing boven [MASK] hoofd.\n\t\\begin{enumerate}\n\t\t\\item zijn;\n\t\t\\item het;\n\t\t\\item de;\n\t\t\\item haar;\n\t\t\\item hun;\n\t\\end{enumerate}\n\t\\item De kaas uit Duitsland was niet [MASK] dan de kaas uit Nederland.\n\t\\begin{enumerate}\n\t\t\\item groter;\n\t\t\\item meer;\n\t\t\\item kleiner;\n\t\t\\item anders;\n\t\t\\item beter;\n\t\\end{enumerate}\n\t\\item De diplomaten dronken uit [MASK] bekers terwijl het ongeval plaatsvond.\n\t\\begin{enumerate}\n\t\t\\item de;\n\t\t\\item in;\n\t\t\\item het;\n\t\t\\item uit;\n\t\t\\item en;\n\t\\end{enumerate}\n\t\\item Het weer was onstuimig, het [MASK] namelijk vrij hard.\n\t\t\\begin{enumerate}\n\t\t\\item was;\n\t\t\\item weer;\n\t\t\\item is;\n\t\t\\item kwam;\n\t\t\\item had;\n\t\\end{enumerate}\n\t\\item De scholen sloten hun deuren [MASK].\n\t\t\\begin{enumerate}\n\t\t\\item in;\n\t\t\\item aan;\n\t\t\\item op;\n\t\t\\item ';\n\t\t\\item .;\n\t\\end{enumerate}\n\t\\item Jan had gisteren [MASK] voet gestoten tegen de tafelpoot.\n\t\t\\begin{enumerate}\n\t\t\\item en;\n\t\t\\item met;\n\t\t\\item van;\n\t\t\\item aan;\n\t\t\\item de;\n\t\\end{enumerate}\n\\end{enumerate}\n\n\\noindent\\fbox{%\n\t\\parbox{\\textwidth}{%\nGive at least ten example sentences with a [MASK] and a list of targets that illustrate a specific grammatical phenomenon in a language of your choice. Describe what the grammatical phenomenon is you are investigating. Use the probe function for testing. Try to include both easy sentences (where the model should do well) as well as hard sentences (where there are words in the context that might lead to confusion, or where the clue words are far away from the mask). For languages other than Dutch or English, make sure to include enough explanation so that examples and tests are clear to a non-native speaker.\n\nDescribe how well the model did on your probe sentences. Where there any cases where the model made the wrong decision?\n\t}%\n}\\\\\n\nPlease see the notebook for the sentences that were tested. The model did quite well on the provided probe sentences. There is a noticeable bias present in the model when it comes to gender and pronoun usage; him/his often comes on tops when such cases are masked. Although the model performs well in most cases, it did make a slight error in the sentence \\texttt{The dog [MASK] hunting for food in the evenings.}, where \\textit{are} apparently has a higher score than \\textit{was}. \n\n\\section{Week 6 - Dependency Parsing}\n\n\\subsection{Evaluation}\n\nWe are given the following sentence: \\texttt{I hate to put a little pressure on you}\\\\\n\nOur total amount of nodes ($N$) is 8, so our formulas would look like...\n\n\t\\begin{equation}\n\t\tUAS = \\frac{\\text{\\# of nodes with correct parent}}{8}\n\t\\end{equation}\n\n\t\\begin{equation}\n\t\tLAS = \\frac{\\text{\\# of nodes with correct parent and edge label}}{8}\n\t\\end{equation}\n\nFor the example on the upper side, the scores are as follows:\n\n\\noindent\\begin{minipage}{.5\\linewidth}\n\t\\begin{equation}\n\t\tUAS = \\frac{8}{8} = 1\n\t\\end{equation}\n\\end{minipage}%\n\\begin{minipage}{.5\\linewidth}\n\t\\begin{equation}\n\t\tLAS = \\frac{8}{8} = 1\n\t\\end{equation}\n\\end{minipage}\\\\\n\nFor the example on the lower side, the scores are as follows:\n\n\\noindent\\begin{minipage}{.5\\linewidth}\n\t\\begin{equation} \n\t\tUAS = \\frac{6}{8} = 0.75\n\t\\end{equation}\n\\end{minipage}%\n\\begin{minipage}{.5\\linewidth}\n\t\\begin{equation}\n\t\tLAS = \\frac{3}{8} = 0.375\n\t\\end{equation}\n\\end{minipage}\n\n\\subsection{Transition-based Parsing}\n\n\\noindent\\fbox{%\n\t\\parbox{\\textwidth}{%\nDescribe the states and actions that a transition-based parser has to go through to produce the gold standard (top) analysis of the sentence\nin question 6.1. A state consists of a stack, input buffer, and set of dependency relations. An action is either SHIFT, RIGHTARC, or LEFTARC,\nwhere you can assume that the RIGHTARC and LEFTARC actions also produce the correctly labeled dependency relations.\n\t}%\n}\\\\\n\nWe are given the following sentence: \\texttt{I hate to put a little pressure on you}\\\\\n\nWe assume that the upper example from exercise 2.1 is the gold standard.\\\\\n\n\\adjustbox{max width=\\columnwidth}{\n%\\begin{table}[h]\n\t\\begin{tabular}{l|l|l|l|l}\n\tStep & Stack & Word List & Action & Relation Added \\\\ \\hline\n\t0\t& [root] & [I, hate, to, put, a, little, pressure, on, you] & SHIFT &  \\\\\n\t1\t& [root, I] & [hate, to, put, a, little, pressure, on, you] & SHIFT &  \\\\\n\t2\t& [root, I, hate] & [to, put, a, little, pressure, on, you] & LEFTARC & (I $\\leftarrow$ hate) \\\\\n\t3\t& [root, hate] & [to, put, a, little, pressure, on, you] & SHIFT &  \\\\\n\t4\t& [root, hate, to] & [put, a, little, pressure, on, you] & SHIFT &  \\\\\n\t5\t& [root, hate, to, put] & [a, little, pressure, on, you] & LEFTARC & (to $\\leftarrow$ put) \\\\\n\t6\t& [root, hate, put] & [a, little, pressure, on, you] & SHIFT &  \\\\\n\t7\t& [root, hate, put, a] & [little, pressure, on, you] & SHIFT &  \\\\\n\t8\t& [root, hate, put, a, little] & [pressure, on, you] & SHIFT &  \\\\\n\t9\t& [root, hate, put, a, little, pressure] & [on, you] & LEFTARC & (little $\\leftarrow$ pressure) \\\\\n\t10\t& [root, hate, put, a, pressure] & [on, you] & LEFTARC & (a $\\leftarrow$ pressure) \\\\\n\t11\t& [root, hate, put, pressure] & [on, you] & RIGHTARC & (put $\\rightarrow$ pressure) \\\\\n\t12\t& [root, hate, put] & [on, you] & SHIFT &  \\\\\n\t13\t& [root, hate, put, on] & [you] & SHIFT &  \\\\\n\t13\t& [root, hate, put, on, you] & [] & LEFTARC & (on $\\leftarrow$ you) \\\\\n\t14\t& [root, hate, put, you] & [] & RIGHTARC & (put $\\rightarrow$ you) \\\\\n\t15\t& [root, hate, put] & [] & RIGHTARC & (hate $\\rightarrow$ put) \\\\\n\t15\t& [root, hate] & [] & RIGHTARC & (root $\\rightarrow$ hate) \\\\\n\t16\t& [root] & [] & Done & \\\\ \\hline\n\t\\end{tabular}\n\\centering\n%\\caption{Transition-based parsing of the sentence \\textit{I hate to put a little pressure on you}.}\n%\\end{table}\n}\n\n\\subsection{Crossing arcs}\n\n\\noindent\\fbox{%\n\t\\parbox{\\textwidth}{%\nIt is not possible to produce the analysis for the sentence below using a transition-based parser. Give the state and input buffer for the point where the problem arises and explain why there is no sequence of actions that leads to a correct parse.\n\t}%\n}\\\\\n\nWe are given the following sentence: \\texttt{Who did Kim talk to}\\\\\n\n\t\\begin{table}[h]\n\t\\begin{tabular}{l|l|l|l|l}\n\t\tStep & Stack & Word List & Action & Relation Added \\\\ \\hline\n\t\t0\t& [root] & [Who, did, Kim, talk, to] & SHIFT &  \\\\\n\t\t1\t& [root, Who] & [did, Kim, talk, to] & SHIFT &  \\\\\n\t\t2\t& [root, Who, did] & [Kim, talk, to] & SHIFT &  \\\\\n\t\t3\t& [root, Who, did, Kim] & [talk, to] & SHIFT &  \\\\\n\t\t4\t& [root, Who, did, Kim, talk] & [to] & LEFTARC & (Kim $\\leftarrow$ talk) \\\\\n\t\t5\t& [root, Who, did, talk] & [to] & LEFTARC & (did $\\leftarrow$ talk) \\\\\n\t\t6\t& [root, Who, talk] & [to] & LEFTARC & (Who $\\leftarrow$ talk) \\\\\n\t\t\\textbf{7}\t& \\textbf{[root, talk]} &\\textbf{ [to]} & \\textbf{SHIFT (?)} &  \\\\\n\t\t? & [root] & [] & Done &\n\t\\end{tabular}\n\t\\centering\n\t%\\caption{Transition-based parsing of the sentence \\textit{I hate to put a little pressure on you}.}\n\t\\end{table}\n\nAs we can see in the table above, the problem arises near step 7. As a result of the previous LEFTARC action, we removed the word \\textbf{Who} which would be needed for a later RIGHTARC operation. The remaining word \\textbf{talk} cannot be coupled with \\textbf{to}, as there is no sensible relation between these words. We cannot couple \\textbf{root} and \\textbf{talk} at this moment, as \\textbf{to} is still part of either the stack or word list.\n\n\\subsection{Tiny-dependency parser}\n\n\\noindent\\fbox{%\n\t\\parbox{\\textwidth}{%\nImprove the oracle of the dependency parser in the notebook and train and evaluate it on the data. See notebook for details.\n\t}%\n}\\\\\n\n\\section{Week 7 - Word Sense Disambiguation}\n\nSee the attached notebook for the results of the various experiments.\n\n\\end{document}\n", "meta": {"hexsha": "d57bd151b4cd4802835e76db826b3e6aabc73162", "size": 14341, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "portfolio2/report/Wetzel portfolio 2.tex", "max_stars_repo_name": "leonwetzel/Natural-Language-Processing", "max_stars_repo_head_hexsha": "5223faf13cf696e9094e3ad939b7fa4ea813c004", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "portfolio2/report/Wetzel portfolio 2.tex", "max_issues_repo_name": "leonwetzel/Natural-Language-Processing", "max_issues_repo_head_hexsha": "5223faf13cf696e9094e3ad939b7fa4ea813c004", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "portfolio2/report/Wetzel portfolio 2.tex", "max_forks_repo_name": "leonwetzel/Natural-Language-Processing", "max_forks_repo_head_hexsha": "5223faf13cf696e9094e3ad939b7fa4ea813c004", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6777493606, "max_line_length": 719, "alphanum_fraction": 0.6814727006, "num_tokens": 4744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.3090419474270079}}
{"text": "\\documentclass[accentcolor=tud2c,usenames,dvipsnames,colorbacktitle,inverttitle,landscape,german,presentation,t]{tudbeamer}\n\\usepackage[english]{babel}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{slashed}\n\\usepackage{color}\n\\usepackage{physics}\n\\usepackage{graphicx}\n\\usepackage{braket}\n% \\usepackage[utf8]{inputenc}\n\n\\begin{document}\n\n  \\input{macros.tex}\n\n  \\setbeamerfont{footline}{size=\\fontsize{1}{1}\\selectfont}\n\n  \\title{Chiral Green's functions and Ward identities}\n  \\subtitle{\\small{Matthias Heinz}}\n  \\author{Matthias Heinz}\n  \\institute[Institut f\\\"ur Kernphysik, TU Darmstadt]{Institut f\\\"ur Kernphysik, TU Darmstadt}\n  \\date{January 30, 2020}\n\n  \\setbeamertemplate{section in toc}[ball unnumbered]\n  \\setbeamertemplate{subsection in toc}[ball unnumbered]\n\n  \\nocite{*}\n\n  \\begin{titleframe}\n    \\vskip3em\n    \\begin{columns}[c]\n      \\begin{column}{0.8\\textwidth}\n        Outline:\n          \\vskip2em\n        \\begin{enumerate}\n          \\item Ward identities in a $\\U{1}$ example\n          \\vskip2em\n          \\item Chiral Ward identities via the algebra of currents\n          \\vskip2em\n          \\item The chiral generating functional\n        \\end{enumerate}\n      \\end{column}\n    \\end{columns}\n      % \\includegraphics[width=0.75\\textwidth]{figures/05/critical_point_illustration}\n      % \\\\\\footnotesize{Stephanov 2009}\n  \\end{titleframe}\n\n  \\section{Ward identities in a $\\U{1}$ example}\n\n  \\begin{frame}\n    \\frametitle{Scalar $\\Phi^4$ theory with a global $\\U{1}$ symmetry}\n    \\begin{equation*}\n      \\mathcal{L}^0 = \\frac{1}{2}(\\dmulop{\\Phidag}\\dmuhip{\\Phi})\n      - \\frac{m^2}{2} \\Phidag \\Phi - \\frac{\\lambda}{4} (\\Phidag \\Phi)^2\n    \\end{equation*}\n\n    \\vskip3em\n\n    \\begin{columns}[c]\n      \\begin{column}{0.8\\textwidth}\n        Global $\\U{1}$ symmetry:\n\n        \\begin{equation*}\n        \\begin{array}{cc}\n          \\Phi \\rightarrow (1 + i \\epsilon) \\Phi, &\n          \\Phidag \\rightarrow (1 - i \\epsilon) \\Phidag, \\\\\n        \\end{array}\n        \\end{equation*}\n\n        \\vskip1em\n\n        Conserved Noether current:\n\n        \\begin{equation*}\n          \\Jmu = i (\\dmuhip{\\Phidag} \\Phi - \\Phidag \\dmuhip{\\Phi})\n        \\end{equation*}\n      \\end{column}\n    \\end{columns}\n  \\end{frame}\n\n  \\begin{frame}\n    \\frametitle{Scalar $\\Phi^4$ theory with a global $\\U{1}$ symmetry}\n\n    \\begin{columns}[c]\n      \\begin{column}{0.8\\textwidth}\n        Example Green's function:\n\n        \\begin{equation*}\n          \\Gmu(x,y,z) = \\mel*{0}{\\timeorder{\\Phi(x)\\Jmu(y)\\Phidag(z)}}{0},\n        \\end{equation*}\n\n        \\vskip1em\n\n        Symmetry constraint:\n\n        \\begin{equation*}\n          \\begin{array}{cc}\n            \\Jmu \\rightarrow \\Jmu, &\n            \\Gmu \\rightarrow \\Gmu, \\\\\n          \\end{array}\n        \\end{equation*}\n\n        \\vskip1em\n\n        Example Ward identity:\n\n        \\begin{align*}\n          \\dmulox{\\Gmu(x,y,z)}{y} = & (\\delta^4(y-x) - \\delta^4(y-z))\\mel*{0}{\\timeorder{\\Phi(x) \\Phidag(z)}}{0} \\\\\n                                    & + \\mel*{0}{\\timeorder{\\Phi(x) \\dmulopx{\\Jmu(y)}{y} \\Phidag(z)}}{0},\n        \\end{align*}\n      \\end{column}\n    \\end{columns}\n  \\end{frame}\n\n  % \\begin{frame}\n  %   \\frametitle{Recap of path integral formalism \\\\ Maybe just skip and explain on actual generating functional}\n  %   \\begin{columns}[c]\n  %     \\begin{column}{0.8\\textwidth}\n  %       Green's functions via path integral:\n  %\n  %       \\begin{equation*}\n  %         \\mel{0}{\\timeorder{\\Phidag(x) \\Phi(y)}}{0} =\n  %         \\int \\mathcal{D}\\Phistar \\mathcal{D}\\Phi \\Phistar(x) \\Phi(y) \\exp(i S[\\Phi, \\Phistar]),\n  %       \\end{equation*}\n  %\n  %       Generating functional:\n  %\n  %       \\begin{equation*}\n  %       W[j, j^{*}] = \\mel*{0}{\\timeorder{\\exp(i\\int d^4x[j(x) \\Phidag (x) + j^{*}(x) \\Phi(x)])}}{0},\n  %       \\end{equation*}\n  %\n  %       Green's functions via functional derivatives:\n  %\n  %       \\begin{equation*}\n  %         \\mel{0}{\\timeorder{\\Phidag(x) \\Phi(y)}}{0} = \\left.\\left(-i\\frac{\\delta}{\\delta j(x)} \\right) \\left(-i\\frac{\\delta}{\\delta j^{*}(y)} \\right) W[j, j^{*}] \\right\\rvert_{j=0,j^{*}=0},\n  %       \\end{equation*}\n  %     \\end{column}\n  %   \\end{columns}\n  % \\end{frame}\n\n  \\begin{frame}\n    \\frametitle{Generating functional for $\\Phi^4$}\n    \\begin{columns}[c]\n      \\begin{column}{0.8\\textwidth}\n        Generating functional:\n        \\begin{equation*}\n          W[j, j^{*}, j_{\\mu}] = \\mel*{0}{\\timeorder{\\exp{i\\int d^4x[j(x) \\Phidag (x) + j^{*}(x) \\Phi(x) + j_{\\mu}(x) \\Jmu(x)]}}}{0},\n        \\end{equation*}\n        Our example Green's function:\n        \\begin{equation*}\n          \\Gmu(x,y,z) = \\left.(-i)^3 \\frac{\\delta^3 W[j, j^{*}, j_{\\mu}]}{\\delta j^{*}(x) \\delta j_{\\mu}(y) \\delta j(z)}\\right\\rvert_{j=0,j^{*}=0,j_{\\mu}=0},\n        \\end{equation*}\n        As path integral:\n        \\vskip-1em\n    \\begin{equation*}\n      \\only<1>{W[j, j^{*}, j_{\\mu}] = \\int \\mathcal{D}\\Phistar \\mathcal{D}\\Phi \\exp(i \\int d^4x[\\mathcal{L}^{0}(x) + \\mathcal{L}_{\\textrm{ext}}(x)]),}\n      \\only<2>{W[j, j^{*}, j_{\\mu}] = \\int \\mathcal{D}\\Phistar \\mathcal{D}\\Phi \\exp(i S[\\Phi, \\Phistar, j, j^{*}, j_{\\mu}]),}\n    \\end{equation*}\n    \\only<1>{\n      \\begin{equation*}\n        \\mathcal{L}_{\\textrm{ext}}(x) = j(x) \\Phi^{*} (x) + j^{*}(x) \\Phi(x) + j_{\\mu}(x) \\Jmu(x),\n      \\end{equation*}\n    }\n    \\only<2>{Note: Only in the presence of external fields can we demand $\\mathcal{L}$ remain invariant under \\textit{local} transformations.}\n      \\end{column}\n    \\end{columns}\n\n  \\end{frame}\n\n  \\begin{frame}\n    \\frametitle{The master equation for $\\Phi^4$}\n    \\begin{columns}[c]\n      \\begin{column}{0.8\\textwidth}\n\n    Demanding $S[\\Phi, \\Phidag, j, j^{*}, j_{\\mu}] = S[\\Phi^{\\prime}, \\Phi^{\\prime \\dagger}, j^{\\prime}, j^{\\prime*}, j^{\\prime}_{\\mu}]$ gives:\n    \\begin{align*}\n    j(x) & \\rightarrow (1 + i \\epsilon(x))j(x), \\\\\n    j^{*}(x) & \\rightarrow (1 - i \\epsilon(x))j^{*}(x), \\\\\n    j_{\\mu}(x) & \\rightarrow j_{\\mu} - \\dmulop{\\epsilon(x)},\n    \\end{align*}\n    % \\begin{equation*}\n    %   \\begin{array}{ccc}\n    %     j(x) \\rightarrow (1 + i \\epsilon(x))j(x), &\n    %     j^{*}(x) \\rightarrow (1 - i \\epsilon(x))j^{*}(x), &\n    %     j_{\\mu}(x) \\rightarrow j_{\\mu} - \\dmulop{\\epsilon(x)}, \\\\\n    %   \\end{array}\n    % \\end{equation*}\n    We observe that this also means:\n    \\begin{equation*}\n      W[j, j^{*}, j_{\\mu}] = W[j^{\\prime}, j^{\\prime*}, j^{\\prime}_{\\mu}],\n    \\end{equation*}\n    Master equation:\n    \\begin{equation*}\n      \\only<1>{0 = \\int d^{4}x \\epsilon(x) \\left[ i j(x) \\frac{\\delta}{\\delta j(x)} - i j^{*}(x) \\frac{\\delta}{\\delta j^{*}(x)} + \\dmulox{\\frac{\\delta}{\\delta j_{\\mu}(x)}}{x} \\right] W[j, j^{*}, j_{\\mu}],}\n      \\only<2>{0 = \\left[ j(x) \\frac{\\delta}{\\delta j(x)} - j^{*}(x) \\frac{\\delta}{\\delta j^{*}(x)} - i \\dmulox{\\frac{\\delta}{\\delta j_{\\mu}(x)}}{x} \\right] W[j, j^{*}, j_{\\mu}],}\n    \\end{equation*}\n      \\end{column}\n    \\end{columns}\n  \\end{frame}\n\n  \\begin{frame}\n    \\frametitle{QCD in the chiral limit}\n    \\begin{columns}[c]\n      \\begin{column}{0.8\\textwidth}\n        \\begin{equation*}\n\\mathcal{L}_{\\textrm{QCD}}^{0} = \\sum_{l=u,d,s}(\\bar{q}_{R,l}i\\slashed{D}q_{R,l} + \\bar{q}_{L,l}i\\slashed{D}q_{L,l})\n- \\frac{1}{4} \\mathcal{G}_{a\\mu\\nu} \\mathcal{G}_{a}^{\\mu\\nu},\n        \\end{equation*}\n\n        Symmetry group:\n        \\begin{equation*}\n        \\U{3}_{L}\\times\\U{3}_{R} \\xrightarrow[]{\\textrm{Quantization}}\\suxsuxu\n        \\end{equation*}\n      \\end{column}\n    \\end{columns}\n\n    \\vskip3em\n    \\begin{columns}[t]\n      \\begin{column}{0.45\\textwidth}\n        Conserved currents:\n        \\begin{itemize}\n          \\item $\\vecoct = R_{a}^{\\mu} + L_{a}^{\\mu} = \\vecoctexpl$,\n          \\item $\\axvoct = R_{a}^{\\mu} - L_{a}^{\\mu} = \\axvoctexpl$,\n          \\item $\\vecsing = R^{\\mu} + L^{\\mu} = \\vecsingexpl$,\n        \\end{itemize}\n      \\end{column}\n      \\begin{column}{0.45\\textwidth}\n        Color-neutral quadratic forms:\n        \\begin{itemize}\n          \\item $\\scalardensityx{a}{x} = \\scalardensityexplx{a}{x}$,\n          \\item $\\pscalardensityx{a}{x} = \\pscalardensityexplx{a}{x}$,\n        \\end{itemize}\n        Note: $a=0,...,8$\n      \\end{column}\n    \\end{columns}\n  \\end{frame}\n\n  \\begin{frame}\n    \\frametitle{Chiral Green's functions and Ward identities \\\\ \\small{\\textit{An example}}}\n    \\begin{columns}[c]\n      \\begin{column}{0.8\\textwidth}\n      Green's function:\n\\begin{equation*}\n\\Gmu_{APab}(x, y) = \\mel*{0}{\\timeorder{\\axvoct(x)\\pscalardensityx{b}{y}}}{0},\n\\end{equation*}\n\n      Ward identity:\n      \\end{column}\n    \\end{columns}\n    \\vskip1em\n\n\\begin{equation*}\n\\dmulox{\\Gmu_{APab}(x,y)}{x} = \\delta(x_0 - y_0) \\mel*{0}{\\commutator{A_{a}^{0}(x)}{P_{b}(y)}}{0}\n+ \\mel*{0}{\\timeorder{\\dmulopx{\\axvoct(x)}{x}\\pscalardensityx{b}{y}}}{0},\n\\end{equation*}\n\n\\vskip1em\n\n    \\begin{columns}[c]\n      \\begin{column}{0.8\\textwidth}\n        Generalization to any $(n+1)$-point functions:\n        \\begin{align*}\n        % \\begin{equation*}\n        \\partial_{\\mu}^{x} &\\mel*{0}{\\timeorder{\\Jmu(x)A_1(x_1)\\ldots A_n(x_n)}}{0} = \\mel*{0}{\\timeorder{\\dmulopx{\\Jmu(x)}{x}A_1(x_1)\\ldots A_n(x_n)}}{0} \\\\\n                           & + \\delta(x^{0} - x_{1}^{0}) \\mel*{0}{\\timeorder{[J_{0}(x), A_{1}(x_{1})] A_{2}(x_2)\\ldots A_n(x_n)}}{0} \\\\\n                           & + \\ldots \\\\\n                           & + \\delta(x^{0} - x_{n}^{0}) \\mel*{0}{\\timeorder{A_{1}(x_1)A_2(x_2) \\ldots [J_{0}(x), A_{n}(x_{n})] }}{0},\n        % \\end{equation*}\n        \\end{align*}\n      \\end{column}\n    \\end{columns}\n  \\end{frame}\n\n  \\begin{frame}\n    \\frametitle{Algebra of currents}\n    \\begin{columns}[c]\n      \\begin{column}{0.8\\textwidth}\n        \\begin{itemize}\n          \\item We could now evaluate $[J_{0}(x), A_{n}(x_{n})]$ commutators\n          \\item \\textit{But we have to be careful}\n          \\item QED current example:\n          \\begin{itemize}\n            \\item $[J_0(t, \\vec{x}), J_{i}(t, \\vec{y})] = 0$\n            \\item from which one can show $\\mel*{0}{J_0(t, \\vec{x})}{n} = 0$\n          \\end{itemize}\n          \\item Fix: Schwinger term in original charge-current commutator\n          \\item In general, charge-current commutation relations only determined up to a derivative of a delta function\n          \\item Another problem: used naive time-ordered product rather than \\textit{covariant} time-ordered product\n          \\item Seagull terms from covariant time-ordering cancel with Schwinger terms (Feynman)\n        \\end{itemize}\n      \\end{column}\n    \\end{columns}\n  \\end{frame}\n\n  \\begin{frame}\n    \\frametitle{Chiral generating functional}\n    \\begin{columns}[c]\n      \\begin{column}{0.8\\textwidth}\n        Extend chiral Lagrangian to include external fields (sources):\n\\begin{equation*}\n\\mathcal{L} = \\mathcal{L}^{0}_{\\textrm{QCD}} + \\lext\n\\end{equation*}\n\nwith\n\n\\begin{equation*}\n  \\only<1>{\\lext = \\sum_{a = 1}^{8} v_a^{\\mu} \\vecoct + \\frac{1}{3} v_{(s)}^{\\mu} \\vecsing + \\sum_{a=1}^{8} a_a^{\\mu} \\axvoct\n  - \\sum_{a=0}^{8}s_{a} \\scalardensity{a} + \\sum_{a=0}^{8}p_{a} \\pscalardensity{a},}\n  \\only<2>{\\color{black}\\lext = \\bar{q} \\gamma_{\\mu} \\left( \\color{red}v^{\\mu} \\color{black}+ \\frac{1}{3} \\color{red}v_{(s)}^{\\mu} \\color{black}+ \\gamma_5 \\color{red}a^{\\mu} \\color{black}\\right) q\n  - \\bar{q} ( \\color{red}s \\color{black}- i \\gamma_5 \\color{red}p\\color{black}) q,}\n\\end{equation*}\n\n\\vskip1em\n\n\\pause\nusing definitions\n\n\\begin{equation*}\n\\begin{array}{cc}\n  v^{\\mu} = \\sum_{a=1}^{8} v_{a}^{\\mu} \\frac{\\lambda_a}{2}, &\na^{\\mu} = \\sum_{a=1}^{8} a_{a}^{\\mu} \\frac{\\lambda_a}{2}, \\\\\n\\end{array}\n\\end{equation*}\n\\begin{equation*}\n\\begin{array}{cc}\ns = \\sum_{a=0}^{8} s_{a} \\lambda_a, &\np = \\sum_{a=0}^{8} p_{a} \\lambda_a, \\\\\n\\end{array}\n\\end{equation*}\n\n\n      \\end{column}\n    \\end{columns}\n  \\end{frame}\n\n  \\begin{frame}\n    \\frametitle{Chiral generating functional \\\\ \\small{\\textit{Some examples}}}\n    \\begin{columns}[c]\n      \\begin{column}{0.8\\textwidth}\n        Generating functional:\n\n\\begin{equation*}\nW[v,a,s,p] = \\mel*{0}{\\timeorder{\\exp{i \\int d^4x \\lext(x)}}}{0}_{0},\n\\end{equation*}\n\n\\only<1>{Chiral limit example:}\n\\only<2>{Physical example:}\n\n\\begin{equation*}\n  \\only<1>{\\bar{u} u = \\frac{1}{2} \\bar{q} \\left(\\sqrt{\\frac{2}{3}} \\lambda_0 + \\lambda_3 + \\frac{1}{\\sqrt{3}} \\lambda_8 \\right) q,}\n\\end{equation*}\n      \\end{column}\n    \\end{columns}\n\\begin{equation*}\n  \\only<1>{\\mel*{0}{\\bar{u}(x) u(x)}{0}_{0} = \\frac{i}{2} \\left. \\left[ \\sqrt{\\frac{2}{3}} \\frac{\\delta}{\\delta s_0(x)} + \\frac{\\delta}{\\delta s_3(x)} + \\frac{1}{\\sqrt{3}} \\frac{\\delta}{\\delta s_8(x)} \\right] W[v,a,s,p]\\right\\rvert_{v=a=s=p=0},}\n  \\only<2>{\\mel*{0}{\\timeorder{\\axvoct(x)\\pscalardensityx{b}{y}}}{0} = (-i)^2 \\left. \\frac{\\delta^2}{\\delta a_{a\\mu}(x) \\delta p_{b}(y)} W[v,a,s,p] \\right\\rvert_{v=a=p=0,s=\\textrm{diag}(m_{u}, m_{d}, m_{s})},}\n\\end{equation*}\n\n  \\end{frame}\n\n  \\begin{frame}\n    \\frametitle{Constraining external fields}\n    \\begin{columns}[c]\n      \\begin{column}{0.8\\textwidth}\n        We demand of $\\mathcal{L}$ that it is:\n        \\begin{itemize}\n          \\item Hermitian Lorentz scalar\n          \\item Even under $P$ and $C$\n          \\item Invariant under local chiral transformations\n        \\end{itemize}\n\n        \\pause\n\n        Parity:\n\\begin{align*}\nv^{\\mu} &\\xrightarrow[]{P} v_{\\mu}, \\\\\nv^{\\mu}_{(s)} &\\xrightarrow[]{P} v^{(s)}_{\\mu}, \\\\\na^{\\mu} &\\xrightarrow[]{P} - a_{\\mu}, \\\\\ns &\\xrightarrow[]{P} s, \\\\\np &\\xrightarrow[]{P} -p,\n\\end{align*}\n\n      \\end{column}\n    \\end{columns}\n  \\end{frame}\n\n  \\begin{frame}\n    \\frametitle{Constraining external fields}\n    \\begin{columns}[c]\n      \\begin{column}{0.8\\textwidth}\n        We demand of $\\mathcal{L}$ that it is:\n        \\begin{itemize}\n          \\item Hermitian Lorentz scalar\n          \\item Even under $P$ and $C$\n          \\item Invariant under local chiral transformations\n        \\end{itemize}\n\n\n        Charge conjugation:\n\\begin{align*}\nv_{\\mu} &\\xrightarrow[]{C} -v^{T}_{\\mu}, \\\\\nv_{\\mu}^{(s)} &\\xrightarrow[]{C} -v^{(s)T}_{\\mu}, \\\\\na_{\\mu} &\\xrightarrow[]{C} a^{T}_{\\mu}, \\\\\ns &\\xrightarrow[]{C} s^{T}, \\\\\np &\\xrightarrow[]{C} p^{T},\n\\end{align*}\n\n      \\end{column}\n    \\end{columns}\n  \\end{frame}\n\n  \\begin{frame}\n    \\frametitle{Constraining external fields}\n    \\begin{columns}[c]\n      \\begin{column}{0.8\\textwidth}\n        Local chiral transformation:\n\n        \\begin{equation*}\n          \\begin{array}{cc}\n            q_{R} \\rightarrow \\exp{-i\\frac{\\Theta(x)}{3}} V_{R}(x) q_{R}, &\nq_{L} \\rightarrow \\exp{-i\\frac{\\Theta(x)}{3}} V_{L}(x) q_{L},\n          \\end{array}\n\\end{equation*}\n\n        After splitting our external fields into $r_{\\mu}=v_{\\mu}+a_{\\mu}$ and $l_{\\mu}=v_{\\mu}-a_{\\mu}$:\n\\begin{align*}\n  r_{\\mu} &\\rightarrow V_{R} r_{\\mu} V_{R}^{\\dagger} + i V_{R} \\dmulop{V_{R}^{\\dagger}}, \\\\\n  l_{\\mu} &\\rightarrow V_{L} l_{\\mu} V_{L}^{\\dagger} + i V_{L} \\dmulop{V_{L}^{\\dagger}}, \\\\\n  v_{\\mu}^{(s)} &\\rightarrow v_{\\mu}^{(s)} - \\dmulop{\\Theta}, \\\\\n  s + ip &\\rightarrow V_{R} (s + ip) V_{L}^{\\dagger}, \\\\\n  s - ip &\\rightarrow V_{L} (s - ip) V_{R}^{\\dagger},\n\\end{align*}\n      \\end{column}\n    \\end{columns}\n  \\end{frame}\n\n\n  \\begin{frame}\n    \\frametitle{Key takeaways}\n    \\begin{columns}[c]\n      \\begin{column}{0.8\\textwidth}\n        $\\U{1}$ example:\n        \\begin{itemize}\n          \\item Local invariance of generating functional contains all Ward identities of theory\n        \\end{itemize}\n\n        Chiral Ward identities from algebra of currents:\n        \\begin{itemize}\n          \\item Using the algebra of currents, one must tread with caution (Schwinger and seagull terms)\n        \\end{itemize}\n\n        Generating functional for chiral Green's functions:\n        \\begin{itemize}\n          \\item Allows one to compute Green's functions for chiral limit and ``real\" world\n          \\item Can constrain transformation behavior of external fields by invariance of generating functional under local transformations\n        \\end{itemize}\n      \\end{column}\n\n\n    \\end{columns}\n  \\end{frame}\n\n  %yank 7\n\n  % \\begin{frame}\n  %   \\frametitle{Frame template}\n  %   \\begin{columns}[c]\n  %     \\begin{column}{0.8\\textwidth}\n  %     \\end{column}\n  %   \\end{columns}\n  % \\end{frame}\n\n\n\n  \\begin{frame}[allowframebreaks]\n    \\frametitle{References}\n    \\bibliographystyle{apalike}\n    \\bibliography{bibfile}\n  \\end{frame}\n\n\\end{document}\n", "meta": {"hexsha": "4ac4be39b45d645886a9e7a4e6f1c5ad1e8cc0c4", "size": 16183, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "2020/01.30_Seminar_TheoreticalHadronPhysics/MHeinz_Chiral_Ward_Identities.tex", "max_stars_repo_name": "cheshyre/talks", "max_stars_repo_head_hexsha": "a209e153c6847342bda44a7326d338fdcd15d63c", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2020/01.30_Seminar_TheoreticalHadronPhysics/MHeinz_Chiral_Ward_Identities.tex", "max_issues_repo_name": "cheshyre/talks", "max_issues_repo_head_hexsha": "a209e153c6847342bda44a7326d338fdcd15d63c", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2020/01.30_Seminar_TheoreticalHadronPhysics/MHeinz_Chiral_Ward_Identities.tex", "max_forks_repo_name": "cheshyre/talks", "max_forks_repo_head_hexsha": "a209e153c6847342bda44a7326d338fdcd15d63c", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5746887967, "max_line_length": 245, "alphanum_fraction": 0.567385528, "num_tokens": 6011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984434543457, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.30901687101302683}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\marginpar{Tuesday\\\\ 2020-10-6, \\\\ compiled \\\\ \\today}\n\nAs we said earlier, massive stars go type-2 supernova: this corresponds to Core-Collapse. \n\nCompact objects are quite common in the galaxy. \n\n% Non si può preparare un matrimonio con i fichi secchi. \n\nA compact object is one for which the ratio of the gravitational radius \\(R_g = GM / c^2\\) is comparable to the radius of the true object.\nFor a white dwarf, the ratio is of the order of \\num{e3}.\n\nWe then need GR in order to deal with them. \nLet us quickly go over exact solutions of the Einstein Field Equations.\n\n\\section{The Schwarzschild external solution}\n\nThis lecture, we consider the vacuum Schwarzschild solution.\nThe most general line element which is spherically symmetric (invariant under spatial rotations) \nmust be made up of elements which are themselves invariant under spatial rotations. \nWe will use spherical coordinates: \\(r, \\theta , \\varphi , t\\). \n\nIn flat spacetime, the line element reads \n%\n\\begin{align}\n\\dd{s^2} = - c^2 \\dd{t^2} + \\dd{r^2} + r^2 \\qty( \\dd{\\theta^2} + \\sin^2 \\theta \\dd{\\varphi^2})\n\\,,\n\\end{align}\n%\nand our Schwarzschild solution will need to reduce to this in some limit.\n\nThe spatial line element is given by \n%\n\\begin{align}\n\\dd{\\vec{r}} \\cdot \\dd{\\vec{r}} =  \\dd{r^2} + r^2 \\qty( \\dd{\\theta^2} + \\sin^2 \\theta \\dd{\\varphi^2}) = g_{ij} \\dd{x^{i}} \\dd{x^{j}}\n\\,.\n\\end{align}\n\nThen, the most general spherically symmetric line element will read \n%\n\\begin{align}\n\\dd{s^2} =  F(r ,t) \\dd{t^2} + M(r, t) \\dd{r^2} + G(r, t) \\dd{r} \\dd{t} + C(r, t) r^2 \\qty( \\dd{\\theta^2} + \\sin^2 \\theta \\dd{\\varphi^2})\n\\,,\n\\end{align}\n%\nhowever, we can redefine the radial coordinate in order to remove the function multiplying the angular term, so we get \n%\n\\begin{align}\n\\dd{s^2} = F \\dd{t^2} + M \\dd{r^2}  + G \\dd{r} \\dd{t} \n+ r^2 \\qty(\\dd{\\theta^2} + \\sin^2\\theta \\dd{\\varphi^2}) \n\\,.\n\\end{align}\n\nWe can also introduce a new time variable: \n%\n\\begin{align}\n\\dd{t'} = \\dd{t} + \\psi (r, t) \\dd{r} \n\\,.\n\\end{align}\n\nIf \\(\\psi = G / 2F\\), then we remove the mixed term, and then we are left with the expression \n%\n\\begin{align}\n\\dd{s^2} = -B (r, t) \\dd{t^2} + A(r, t) \\dd{r^2} + r^2 \\dd{\\Omega^2}\n\\,.\n\\end{align}\n\nHowever, we have not yet determined the two functions, and we have not said anything about the Einstein Field Equations, which are \n%\n\\begin{align}\nR_{\\mu \\nu } - \\frac{1}{2} g_{\\mu \\nu } R = 8 \\pi G T_{\\mu \\nu }\n\\,.\n\\end{align}\n\nIn vacuo, the stress-energy tensor vanishes. \nThe curvature scalar must vanish (we can show this by contracting the EFE with the inverse metric), so the equations reduce to \\(R_{\\mu \\nu } = 0\\). \nWe restrict ourselves to the static case. \n\nThe linearly independent components of the Ricci tensor read \n%\n\\begin{align}\nR_{0}^{0} = \\frac{B''}{2AB} - \\frac{A' B'}{4 A'' B}\n- \\frac{B^{\\prime 2}}{4AB^2} + \\frac{B'}{rAB} &= 0 \\\\\nR_{1}^{1} = \\frac{B''}{2AB} - \\frac{A' B'}{4 A'' B}\n- \\frac{B^{\\prime 2}}{4AB^2} + \\frac{A'}{rA^2} &= 0 \\\\ \nR_{2}^{2} = \\frac{1}{4rA} \\qty(\\frac{B'}{B} - \\frac{A'}{A})\n+ \\frac{1}{r^2} \\qty( \\frac{1}{A} - 1)\n\\,.\n\\end{align}\n\nComputing \\(R^{0}_{0} - R^{1}_{1} = 0\\) we find \n%\n\\begin{align}\n\\frac{1}{rA} \\qty(\\frac{B'}{B} + \\frac{A'}{A} )&= 0  \\\\\n\\dv{\\log (AB)}{r} &= 0\n\\,,\n\\end{align}\n%\nso \\(AB\\) is constant.\nWithout losing generality we can take \\(A = 1/B\\), since if this is not the case we can just rescale the radial or temporal coordinate until it is.\n\nThen, we can compute \n%\n\\begin{align}\nR^{2}_{2} = \\frac{B}{2r} \\qty(\\frac{B'}{B} + \\frac{B'}{B}) + \\frac{1}{r^2} (B-1) &= 0  \\\\\nB' + \\frac{B}{r} - \\frac{1}{r} &= 0  \\\\\n\\dv{}{r} \\qty(rB) &= 1\n\\,,\n\\end{align}\n%\nso \\(r B(r) = r + C\\) for some constant \\(C\\), or equivalently \n%\n\\begin{align}\nB (r) = \\frac{C}{r} + 1\n\\,.\n\\end{align}\n\nAfter this, we can already substitute into the metric: \n%\n\\begin{align}\n\\dd{s^2} = - \\qty(1 + \\frac{C}{r}) \\dd{t^2} \n+ \\frac{1}{1 + C/r} \\dd{r^2} + r^2 \\dd{\\Omega^2}\n\\,.\n\\end{align}\n\nFor any value of \\(C\\), \\(B \\to 1\\) as \\(r \\to \\infty \\): the metric reduces to the flat one asymptotically. \nRight now \\(C\\) is an arbitrary constant, however in the weak field limit it is known that \n%\n\\begin{align}\ng_{00} = - \\qty(1 + 2 \\frac{\\phi }{c^2})\n\\,,\n\\end{align}\n%\nwhere \\(\\phi = - GM / r\\) is the Newtonian gravitational field.\nEquating this expression to the one for \\(g_{00} \\), we find \n%\n\\begin{align}\ng_{00} = - \\qty(1 - \\frac{2 GM}{rc^2})\n\\implies C = - \\frac{2GM}{c^2}\n\\,.\n\\end{align}\n\nThe constant \\(M\\) in the classical case is the mass of the source, however we are computing a vacuum solution. This is the mass we would compute if we were to measure the orbits of objects around the compact object.\n\n% \\todo[inline]{This is then surely a \\emph{gravitational} mass, is it also an \\emph{inertial} mass? Can we show this in GR?}\n\nThen, we can write the Schwarzschild metric: \n%\n\\begin{align}\n\\dd{s^2} = - \\qty(1 - \\frac{2GM}{c^2r}) \\dd{t^2}\n+ \\qty(1 - \\frac{2GM}{rc^2})^{-1} \\dd{r^2} + r^2 \\dd{\\Omega^2}\n\\,.\n\\end{align}\n\nThis is derived by assuming time-independence, however the result is the same even in the time-dependent case by the Jebsen-Birkhoff theorem (which we will prove in a moment). \nThe element \\(g_{rr} \\) diverges as \\(r \\to R_g = 2GM/c^2\\), however this does not represent any physical divergence: no component of the Riemann tensor \\(R_{\\mu \\nu \\rho \\sigma }\\) diverges there, while the Ricci tensor \\(R_{\\mu \\nu }\\) is identically zero by hypothesis.\nOn the other hand, the origin is a true singularity, since the scalar \\(R^{\\mu \\nu \\rho \\sigma } R_{\\mu \\nu \\rho \\sigma } \\propto r^{-6}\\) diverges there. \n\nThere are coordinates which do not diverge near the horizon: one classical choice employs the ``tortoise'' coordinates, which are the same for \\(r\\), \\(\\theta \\), \\(\\varphi \\) as the Schwarzschild ones, while the time becomes (setting \\(G = c =  1\\))\n%\n\\begin{align}\nt = t' - 2M \\log \\qty(1 - \\frac{r}{2M})\n\\,.\n\\end{align}\n\n\\begin{claim}\nSubstituting this into the metric yields (dropping the primes for clarity):\n%\n\\begin{align}\n\\dd{s^2} = - \\qty(1 - \\frac{2M}{r}) \\dd{t}^2\n+ \\frac{4M}{r} \\dd{r} \\dd{t} + \\qty(1 + \\frac{2M}{r}) \\dd{r^2}\n+ r^2 \\dd{\\Omega^2}\n\\,.\n\\end{align}\n\\end{claim}\n\n\\begin{proof}\nThe new time differential after the change of coordinates reads \n%\n\\begin{align}\n\\dd{t} &= \\pdv{t}{t'} \\dd{t'} + \\pdv{t}{r} \\dd{r}  \\\\\n&= \\dd{t'} - 2M \\frac{(-1/2M)}{1 - r/2M} \\dd{r} = \\dd{t}' + \\frac{ \\dd{r}}{1 - r / 2M}  \\\\\n\\dd{t}^2 &= \\dd{t}^{\\prime 2} \n+2 \\frac{ \\dd{r} \\dd{t'}}{1 - r/2M} \n+ \\frac{ \\dd{r^2}}{(1 - r / 2M)^2}\n\\,,\n\\end{align}\n%\ntherefore the new metric reads (omitting the angular part for brevity):\n%\n\\begin{align}\n\\dd{s}^2 \n&= - \\qty(1- \\frac{2M}{r}) \\dd{t}^2 + \\frac{ \\dd{r}^2}{1 - 2M / r}  \\\\\n&= - \\qty(1- \\frac{2M}{r}) \\qty(\\dd{t}^{\\prime 2} \n+2 \\frac{ \\dd{r} \\dd{t'}}{1 - r/2M} \n+ \\frac{ \\dd{r^2}}{(1 - r / 2M)^2}) + \\frac{ \\dd{r}^2}{1 - 2M / r}  \\\\\n&= - \\qty(1 - \\frac{2M}{r}) \\dd{t^{\\prime 2}} + \\frac{4M}{r} \\dd{r} \\dd{t'} + \\qty(1 + \\frac{2M}{r}) \\dd{r^2}\n\\,,\n\\end{align}\n%\nwhere we have used the following manipulations: setting \\(x = 2M / r\\), the coefficients of the \\(\\dd{r} \\dd{t}'\\) and \\(\\dd{r^2}\\) terms are respectively\n%\n\\begin{align}\n2\\frac{1 - x}{1 - x^{-1}} &= -2x  \\\\\n-\\frac{1 -x}{(1- x^{-1})^2} + \\frac{1}{1-x} &= \\frac{1}{1-x} \\qty(-\\qty(\\frac{1-x}{1- x^{-1}})^2 + 1) =  \\frac{1-x^2}{1-x} = 1+x\n\\,.\n\\end{align}\n\\end{proof}\n\nThere is no pathology at \\(r = 2M\\) anymore, so it was not a physical divergence. \nThe temporal coefficient \\(g_{00} \\) is the same: it can be shown that it is an invariant under coordinate transformations. \n\nIf we take two points which are very close along a particle trajectory, they must be separated by an interval \\(\\dd{s}^2 < 0\\). \n\nIf we consider a radial path (not necessarily geodesic) described by \\(r(t)\\), we can compute the corresponding line element by neglecting the angular part: \n%\n\\begin{align}\n\\dd{s^2} &= - \\qty(1 - \\frac{2M}{r}) \\dd{t}^2\n+ \\frac{4M}{r} \\dd{r} \\dd{t} + \\qty(1 + \\frac{2M}{r}) \\dd{r^2}  \\\\\n\\qty( \\dv{s}{t})^2 &= - \\qty(1- \\frac{2M}{r})\n+ \\frac{4M}{r} \\dv{r}{t} + \\qty(1 + \\frac{2M}{r} ) \\qty(\\dv{r}{t})^2\n\\,.\n\\end{align}\n\nNow, the question we ask is: is it possible for the particle trajectory to be timelike or lightlike (\\(\\dd{s}^2 \\leq 0\\)) and outgoing (\\(\\dv*{r}{t} > 0\\)) under these conditions? If this is the case, the signs of the three terms read \n%\n\\begin{align}\n\\underbrace{\\qty(\\dv{s}{t})^2}_{< 0 ?}\n= \n- \\qty(1- \\frac{2M}{r})\n\\underbrace{+ \\frac{4M}{r} \\dv{r}{t}}_{> 0 } \\underbrace{+ \\qty(1 + \\frac{2M}{r} ) \\qty(\\dv{r}{t})^2}_{> 0}\n\\,,\n\\end{align}\n%\nso we can see that the equality can be satisfied (a positive number cannot equal a negative one!) as long as the first term on the right-hand side is negative, which means \\(r > 2M\\). \nIf \\(r \\leq 2M\\), on the other hand, this cannot be the case: a radial trajectory below the horizon \\emph{cannot} be outward.\n\nThis is what ``horizon'' means: it is a \\emph{semi-permeable} membrane, particles can surpass it only in one direction. \n\n\\paragraph{Jebsen-Birkhoff}\n\nThis theorem states that the Schwarzschild solution also describes the spacetime around an object in the spherically-symmetric but time-\\emph{dependent} case. Let us give a sketch of its proof, omitting some tedious calculations. \nIf we write out the components of the Ricci tensor, we find something in the form \n%\n\\begin{align}\nR^{0}_{0} &= \\eval{R^{0}_{0}}_{\\text{static}} + \\dot{A} \\qty(\\dots)\\\\\nR^{1}_{1} &= \\eval{R^{1}_{1}}_{\\text{static}} + \\dot{A} \\qty(\\dots)\n\\,,\n\\end{align}\n%\nwhile \\(R^{2}_{2}\\) and \\(R^{3}_{3}\\) are the same. Also, the term \\(R^{1}_{0}\\) does not vanish unlike the static case, and is equal to \n%\n\\begin{align}\nR^{1}_{0} = - \\frac{\\dot{A}}{r A^2} = 0\n\\,,\n\\end{align}\n%\nso \\(\\dot{A} = 0\\): the equations then are the same as the static case ones!\nThis, however, is not the end, since now the equation \n%\n\\begin{align}\n\\frac{A'}{A} + \\frac{B'}{B} = 0\n\\,\n\\end{align}\n%\nis not necessarily solved by \\(\\log A = - \\log B\\), since a prime denotes a \\emph{partial} derivative with respect to \\(r\\), so in general we will have \\(\\log A + \\log B = f(t)\\), some generic function of time. \nThe metric will then read \n%\n\\begin{align}\n\\dd{s}^2 = - \\qty(1 - \\frac{2M}{r}) f(t)\\dd{t^2} + \\qty(1 - \\frac{2M}{r}) \\dd{r^2} + r^2 \\dd{\\Omega}^2\n\\,,\n\\end{align}\n%\nbut we can simply rescale the time coordinate to \\(t \\to \\sqrt{f} t\\) in order for this to reduce to the usual expression.\nThis theorem was originally discovered by the Norwegian physicist Jebsen, and only later popularized in a textbook by Birkoff \\cite{johansenDiscoveryBirkhoffTheorem2005}. \n\nThe source of the geometry can change in time while leaving the outside spacetime unperturbed, however this holds only as long as the variation remains spherically symmetric: collapse, expansion or pulsation. \nAny asymmetry can lead to the emission of gravitational radiation.  \n\n\\end{document}\n", "meta": {"hexsha": "7280055f01ad9c6dfdf88d0844dae3fe0a754e6a", "size": 10924, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ap_third_semester/compact_objects/oct06.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "ap_third_semester/compact_objects/oct06.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ap_third_semester/compact_objects/oct06.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 38.6007067138, "max_line_length": 272, "alphanum_fraction": 0.636854632, "num_tokens": 4040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.30901686245007914}}
{"text": "\\startreport{Network Influence Score}\n\\reportauthor{Ramesh Subramonian}\n\\section{Introduction}\n\nWe define the ``network influence score'' problem as follows. Let us assume that\nwe know 2 things for every user that we have (a) who referred that user (could\nbe zero or one user) (b) the revenue generated by that user. \n\nWe ``attribute''\nthe revenue of a user to every referrer along the chain of referrals ending at\nthat user. For example, if \\(a\\) referred \\(b\\) who referred \\(c\\) and \\(c\\)\ngenerated \\$210 of revenue, then \\$140 is attributed to \\(b\\) and 70 to \\(a\\).\nNote that the distribution of c's revenue depends on the length of the referral\nchain ending at \\(c\\). So, if \\(d\\) had referred \\(a\\) in this example, then\n\\$120 is attributed to \\(b\\), \\$60 to \\(a\\) and \\$30 to \\(d\\). \n\nSimply stated, the problem is to find the attributed revenue of each user.\n\n\\subsection{Selected Q operators}\nSee Table~\\ref{tbl_q_ops}.\n\n\\begin{table}[ht]\n\\centering\n\\begin{tabular}{|l|l|l|} \\hline \\hline\n{\\bf ID} & {\\bf operator} & {\\bf explanation} \\\\ \\hline \\hline\n1 & \\(y = \\mathrm{get\\_val\\_by\\_idx}(f, x)\\) & \\(y_i \\leftarrow x_{f_i}\\) \\\\ \\hline\n2 & \\(y = \\mathrm{set\\_sclr\\_val\\_by\\_idx}(x, y, s)\\) & \\(x_i = j \\Rightarrow y_j \\leftarrow s\\) \\\\ \\hline\n3 & \\(z = \\mathrm{add\\_vec\\_val\\_by\\_idx}(x, y, z)\\) & \\(x_i = j \\Rightarrow z_j \\leftarrow\nz_j + y_i\\) \\\\ \\hline\n4 & \\(z = \\mathrm{vvmul}(x, y)\\) & \\(z_i \\leftarrow x_i \\times y_i\\) \\\\ \\hline\n5 & \\(y = \\mathrm{vsleq}(x, s)\\) & {\\bf if} \\(x_i \\leq s\\) {\\bf then} \\(y_i \\leftarrow 1\\) {\\bf else} \\(y_i \\leftarrow 0\\)  \\\\ \\hline\n6 & \\(w = \\mathrm{ifxthenyelsez}(x, y,z)\\) & {\\bf if} \\(x_i\\) {\\bf then} \\(w_i \\leftarrow y_i\\) {\\bf else} \\(w_i \\leftarrow z_i\\)  \\\\ \\hline\n7 & \\(x = \\mathrm{const}(s)\\) & \\(x_i \\leftarrow s\\) \\\\ \\hline\n8 & \\(z = \\mathrm{where}(x, y)\\) & \\(z = \\{x_i\\}\\) where \\(y_i = 1\\) \\\\ \\hline\n\\hline\n\\end{tabular}\n\\caption{Selected Q operators}\n\\label{tbl_q_ops}\n\\end{table}\n\n\\section{Data Structures}\n\\subsection{T0}\n\n\\(T_0\\) has the following columns, where each row refers to a person.\n\\be\n\\item \\(x\\) --- a sequence \\(0, 1, \\ldots\\)\n\\item \\(y\\), person who did the referring. \n\\item id, original ID \n\\item \\(r\\), dollar amount spent \n\\item \\(s\\), dollar amount attributed, {\\em created by algorithm}\n\\item \\(d\\), max depth of referral chain ending in this person, {\\em created by algorithm}\n\\ee\nNotes:\n\\bi\n\\item \\(y[i] = j \\Rightarrow\\) \\(i\\) was referred by \\(j\\). \nWe also say that \\(y\\) is the 1-parent of \\(i\\)\n\\item \\(y[j] < 0 \\Rightarrow \\) nobody referred \\(j\\)\n\\item a person can be referred by at most one person \n\\ei\n\n\\subsection{T1}\n\n\\(T_1\\) is \\(T_0\\) restricted to persons who were refered. Specifically,\n\\bi\n\\item \\(v = \\mathbf{Q.vsgeq}(T_0.y, 0)\\)\n\\item \\(T_1.x = \\mathbf{Q.where}(T_0.x, v)\\)\n\\item \\(T_1.y = \\mathbf{Q.where}(T_0.y, v)\\)\n%% DELETE \\item \\(T_1.r = \\mathbf{Q.where}(T_0.r, v)\\)\n%% DELETE \\item \\(T_1.d = \\mathbf{Q.const}(1)\\) \n%% DELETE --- initial assumption on depth of chain ending in \\(x\\)\n\\ei\n\n\\subsection{Tk}\n\nTables \\(T_k\\) for \\(k =  2, \\ldots\\) have the following columns\n\\be\n\\item \\(x\\), person who was referred\n\\item \\(y\\), person who did the referring at a distance of \\(k\\)\n\\ee\n\nNote that if \\(a\\) referred \\(b\\) and \\(b\\) referred \\(c\\), then table \\(T_2\\)\nwould have a row of the form \\((c, a)\\)\n\n\\subsection{Sample Data}\nAn example is in Table~\\ref{example_extend}. \n\\begin{table}[hp]\n\\centering\n\\begin{tabular} {|l|l|l|l|l|} \\hline \\hline\n{\\bf k} & {\\bf x} & {\\bf y} & {\\bf z} & {\\bf w} \\\\ \\hline\n0 & 0 & 1  & --- & --- \\\\ \\hline\n0 & 1 & 2  & --- & --- \\\\ \\hline\n0 & 2 & 3  & --- & --- \\\\ \\hline\n0 & 3 & 4  & --- & --- \\\\ \\hline\n0 & 4 & -1 & --- & --- \\\\\\hline\n0 & 5 & 6  &  --- & --- \\\\\\hline\n0 & 6 & 7  &  --- & --- \\\\\\hline\n0 & 7 & -1 &  --- & --- \\\\\\hline\n0 & 8 & -1 &  --- & --- \\\\\\hline\n\\hline  \\hline\n1 & 0 & 1  & 2  & 1 \\\\ \\hline\n1 & 1 & 2  & 3  & 1 \\\\ \\hline\n1 & 2 & 3  & 4  & 1 \\\\ \\hline\n1 & 3 & 4  & -1 & 0 \\\\ \\hline\n1 & 5 & 6  & 2  & 1 \\\\ \\hline\n1 & 6 & 7  & -1 & 0 \\\\ \\hline\n\\hline  \\hline\n2 & 0 & 2 & 3 & 1 \\\\ \\hline\n2 & 1 & 3 & 4 & 1 \\\\ \\hline\n2 & 2 & 4 & -1 & 0 \\\\ \\hline\n2 & 5 & 7 & -1 & 0 \\\\ \\hline\n\\hline  \\hline\n3 & 0 & 3 & 4 & 1 \\\\ \\hline\n3 & 1 & 4 & -1 & 0 \\\\ \\hline\n\\hline  \\hline\n4 & 0 & 4 & -1 & 0 \\\\ \\hline\n\\end{tabular}\n\\caption{Sample data}\n\\label{example_extend}\n\\end{table}\n\n\n\\section{Algorithm}\n\nThe algorithm is presented in Figure~\\ref{algo}. Some useful routines in\nSection~\\ref{aux_algo}\n\\subsection{Sub-routines}\n\\label{aux_algo}\n\n\\bi\n\\item The function {\\bf Q.extend} is in Figure~\\ref{extend}\n\\item The way the attribution diminishes with distance is in Table~\\ref{attenuate}\n\\ei\n\n\\begin{figure}\n\\centering\n\\fbox{\n\\begin{minipage}{12 cm}\n\\centering\n\\begin{tabbing} \n\\hspace*{0.25in} \\= \\hspace*{0.25in} \\= \\hspace*{0.25in} \\= \\kill\nInputs: \\+ \\\\\n\\(T_k.x\\) \\\\\n\\(T_k.y\\) \\\\\n\\(T_0.y\\) \\- \\\\\n% Operation:  \\+ \\\\\n% Let \\(T_k.x[i] = x', T_k.y[i] = y'\\).  \\\\\n% Let \\(f' = T_0.y[y']\\).  \\\\\n% If \\(z' \\geq 0\\), add \\((x', z')\\) to output; else, do nothing \\- \\\\\nImplementation in Q:  \\+ \\\\\n\\(z = \\mathbf{Q.get\\_val\\_by\\_idx}(T_k.y, T_0.y)\\) \\\\\n\\(w = \\mathbf{Q.vsgeq}(z, 0)\\) \\\\\n\\(T_{k+1}.x = \\mathbf{Q.where}(T_k.x, w)\\) \\\\\n\\(T_{k+1}.y = \\mathbf{Q.where}(z, w)\\) \\- \\\\\n\\end{tabbing}\n\\caption{extend}\n\\label{extend}\n\\end{minipage}\n}\n\\end{figure}\n\n\n\\begin{table}[hp]\n\\centering\n\\begin{tabular}{|l|l|l|l|l|l|l|} \\hline \\hline\n\\(d_{max}\\) & \\(\\alpha_1\\)  & \\(\\alpha_2\\)  & \\(\\alpha_3\\)  & \\(\\alpha_4\\)\n\\\\ \\hline\n1 & 1 & --- & --- & --- \\\\ \\hline\n2 & 2/3 & 1/3 & --- & --- \\\\ \\hline\n3 & 4/7 & 2/7 & 1/7 & --- \\\\ \\hline\n4 & 8/15 & 4/15 & 2/15 & 1/15 \\\\ \\hline\n\\hline\n\\end{tabular}\n\\caption{Attenuation Factors for different \\(d, d_{max}\\)}\n\\label{attenuate}\n\\end{table}\n\n\n\\begin{figure}\n\\centering\n\\fbox{\n\\begin{minipage}{12 cm}\n\\centering\n\\begin{tabbing} \n\\hspace*{0.25in} \\= \\hspace*{0.25in} \\= \\hspace*{0.25in} \\= \\kill\n\n\\(T_0.d = \\mathbf{Q.const}(1)\\) --- initialize max depth to 1 \\\\\n\\(T_0.s = \\mathbf{Q.const}(0)\\) --- initialize attributed revenue to 0 \\\\\n\\(k = 1\\) \\\\\n{\\bf repeat } \\+ \\\\\n\\(T_{k+1} = \\mathbf{Q.extend}(T_k.x, T_k.y, T_0.y)\\) (Figure~\\ref{extend})\\\\\n{\\bf if} \\(T_{k+1} = \\bot\\) {\\bf then break else} \\(k = k+1\\) {\\bf end}\\\\\n--- Update max depth of referral chain \\\\\n\\(\\mathbf{Q.set\\_sclr\\_val\\_by\\_idx}(T_{k+1}.x, T_0.d, k+1)\\) \\- \\\\\n{\\bf until} --- not possible to extend any further \\\\\n\\(d_{max} = k\\) \\\\\nLoad \\(\\alpha\\) which contains attribution coefficients (Table~\\ref{attenuate})\\\\\n{\\bf for} \\(k = 1, \\ldots d_{max}\\) {\\bf do} \\+ \\\\\n% {\\bf for} \\(k = 1, \\ldots k\\) {\\bf do} \\+ \\\\\n  \\(T_k.d       = \\mathbf{Q.get\\_val\\_by\\_idx}(T_k.x, T_0.d)\\)  \\\\\n  \\(T_k.r       = \\mathbf{Q.get\\_val\\_by\\_idx}(T_k.x, T_0.r)\\)  \\\\\n  \\(T_k.\\alpha  = \\mathbf{Q.get\\_val\\_by\\_idx}(T_k.d, \\alpha[k])\\) \\\\\n  \\(s           = \\mathbf{Q.vvadd}(T[k].r, T[k].\\alpha)\\) \\\\\n  \\(\\mathbf{Q.add\\_vec\\_val\\_by\\_idx}(s, T_k.y, T_0.s)\\) \\- \\\\\n{\\bf endfor} \\\\\n\\end{tabbing}\n\\caption{Pseudo-code}\n\\label{algo}\n  \\end{minipage}\n}\n\\end{figure}\n\n\\newpage\n\n\\appendix\nSome bogus reference to make bibtex not complain \\cite{Hastie2009}.\n\\bibliographystyle{alpha}\n\\bibliography{../../../DOC/ref}\n", "meta": {"hexsha": "23a4f7f25231cd583bdc04b27cd0693779c04dc7", "size": 7126, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "GRAPH/ATTRIBUTION/doc/attribution.tex", "max_stars_repo_name": "subramon/qlu", "max_stars_repo_head_hexsha": "2fb8a2b3636dd11e2dfeae2a6477bd130316da47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GRAPH/ATTRIBUTION/doc/attribution.tex", "max_issues_repo_name": "subramon/qlu", "max_issues_repo_head_hexsha": "2fb8a2b3636dd11e2dfeae2a6477bd130316da47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-07-29T16:48:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-26T23:47:22.000Z", "max_forks_repo_path": "GRAPH/ATTRIBUTION/doc/attribution.tex", "max_forks_repo_name": "subramon/qlu", "max_forks_repo_head_hexsha": "2fb8a2b3636dd11e2dfeae2a6477bd130316da47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2015-05-14T22:34:13.000Z", "max_forks_repo_forks_event_max_datetime": "2015-05-14T22:34:13.000Z", "avg_line_length": 32.6880733945, "max_line_length": 140, "alphanum_fraction": 0.5822340724, "num_tokens": 2866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.309016862450079}}
{"text": "\\chapter{Anomaly Detection}\n\n\\section{Type of Anomaly}\n\\begin{enumerate}\n\\item Point Anomalies (Our Focus)\n\\item Contextual Anomalies\n\\item Collective Anomalies\n\\end{enumerate}\n\n\\section{Anomaly Detection Techniques}\n\\noindent General steps\n\\begin{table}[h!]\n\\begin{tabular}{r p{12cm}}\n\\hline\n    1: & Build profile of normal behavior \\\\\n    2: & Use the normal profile to detect anomalies \\\\\n\\hline\n\\end{tabular}\n\\end{table}\n\n\\begin{description}\n\\item[Graphical Approaches] Boxplot, Scatter plot, Spin plot\n\\item[Statistical Approaches] points are determined to be outliers depending on their relationship with this model\n\\item[Nearest Neighbor Based Approaches] Distance based methods or density based methods\n\\item[Classification Based Approaches] Supervised learning techniques\n\\end{description}\n\\textit{Evaluation of Anomaly Detection: Use F-measure and ROC curve}", "meta": {"hexsha": "0d13cf7a2a403be4936d8ab060325e53e11b2d4f", "size": 869, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapter9.tex", "max_stars_repo_name": "Andyccs/data-mining-summary", "max_stars_repo_head_hexsha": "27ffac528e9e225c8a15ff44fbf2ed3e1c6b9f7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapter9.tex", "max_issues_repo_name": "Andyccs/data-mining-summary", "max_issues_repo_head_hexsha": "27ffac528e9e225c8a15ff44fbf2ed3e1c6b9f7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter9.tex", "max_forks_repo_name": "Andyccs/data-mining-summary", "max_forks_repo_head_hexsha": "27ffac528e9e225c8a15ff44fbf2ed3e1c6b9f7a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1851851852, "max_line_length": 114, "alphanum_fraction": 0.7882623705, "num_tokens": 225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.30901685388713124}}
{"text": "\\chapter{Preliminaries and related work}\n\\label{preliminaries}\n\nIn this section we briefly introduce and explain the necessary theoretical background, upon which we build later on.\n\nWe first define the concepts of Machine learning (ML) and Deep neural networks (DNNs). We explain, how DNNs can learn patterns from data by using powerful gradient-based stochastic optimization algorithm called Stochastic gradient descent (SGD). Then we talk about a subset of DNNs that perform very well on image data called Convolutional neural networks (CNNs).\n\nFinally, we describe the systemic vulnerability of DNNs and define an adversarial attack. Then we explain related terms like adversarial defenses, adversarial examples, adversarial robustness and different adversarial attack threat models and present current state of the field.\n\n\n\\section{Deep learning basics}\n\n\\subsection{Machine learning}\nThe topic of machine learning has been introduced many times over in other books and papers. \\cite{10.5555/2380985}, \\cite{10.5555/1162264} and \\cite{Goodfellow-et-al-2016} all provide a comprehensive exposition to the field. Because of the abundance of many different kinds of resources, we don't feel the need to reinvent the wheel and come up with yet another machine learning introduction. \n\nTo put forward the most accepted definition of machine learning, the \\cite{10.5555/2380985} lay it as follows: \\\\\n\n“A computer program is said to learn from experience $E$ with respect to some class of tasks $T$ and performance measure $P$, if its performance at tasks in $T$, as measured by $P$, improves with experience $E$.”\n\n\\subsection{Deep neural networks}\nIn our case the \"computer program learning from experience\" will be in most cases a deep neural network (DNN). We will introduce neural networks only very briefly at a high level as more details can be easily found in \\cite{Goodfellow-et-al-2016}.\n\nDNN is in its essence a parametrized mapping $y = f(x;\\theta)$, where $x$ are the network inputs, $\\theta$ are the parameters and $y$ are the outputs of the network. The \"network\" in its name comes from the fact that the function computation is described as an evaluation of a computational directed acyclic graph (DAG), the structure of which depends on the exact network architecture.\n\nDuring evaluation, each node in the graph is asociated with a number called \"activation\", This activation value is computed from the values of other nodes and from the relevant parameters $\\theta$. It is then passed through a non-linear activation function $a(x)$. For a long time the $sigmoid(x)$ activation function was very popular. Nowdays $ReLU(x) = \\max(0, x)$ (Rectified Linear Unit) is used more often as it is better suited for deeper networks.\n\nThe nodes in the DAG are sometimes referred to as \"neurons\", as there is an analogy to the functioning of biological neurons.\n\nThe function $f(x;\\theta)$ can be often decomposed into several computational steps: $f(x;\\theta) = f_n(f_{n-1}(...f_2(f_1(x; \\theta_1);\\theta_2)...;\\theta_{n-1});\\theta_n)$. In this decomposition the individual functions $f_i(x_i; \\theta_i)$ are called \"layers\". When the number of layers is large, the network is said to be deep. The successive computations of $f_1(x_1, \\theta_1)$, $f_2(x_2, \\theta_2)$ up to $f_n(x_n, \\theta_n)$ is called a \"forward pass\".\n\n\\subsection{Network training}\nIf we have a dataset $D$ consisting of input datapoints $x_i$ and their corresponding $y_i$ values called \"labels\", we want the neural network function $f(x, \\theta)$ to express the relationship between $x_i$ and $y_i$. Depending on the complexity of the network, the parameters $\\theta$ can be often set accordingly, such that $f(x_i, \\theta) \\approx y_i$. This ability to approximate the data well with the right $\\theta$ is called \"network's capacity\". How good is the neural network's approximation is measured by a loss function $\\mathcal{L}(D, f(x, \\theta))$. Because the network models the relationship between $x_i$ and $y_i$, it is sometimes just called a \"model\".\n\nThe process of training a neural network tries to minimize the training loss by optimizing the parameters. Formally, we search for $\\theta$ = $\\argmin{\\theta}[ \\mathcal{L}(D, f(x, \\theta))]$.\n\nThis optimization is in practice done iteratively using an algorithm called stochastic gradient descent (SGD). It involves computing the gradient of the loss with respect to the parameters $\\theta$: $\\nabla_{\\theta} \\mathcal{L}(D, f(x, \\theta))$. It then updates the parameters in the opposite direction of the gradient to hopefully lower the loss.\n\nThe partial derivates $\\frac{\\partial \\mathcal{L}(D, f(x, \\theta))}{\\partial \\theta_i}$ can be efficiently computed by an algorithm called \"backpropagation\". It is very similar to a forward pass, but it starts from the loss and proceeds in the opposite direction of the DAG. Detailed explanation can be again found in \\cite{Goodfellow-et-al-2016}. It is also icredibly well explained in the \\href{https://www.youtube.com/playlist?list=PLZHQObOWTQDNU6R1_67000Dx_ZCJB-3pi}{YouTube video series about neural networks} by 3Blue1Brown (Grant Sanderson)\n\n\\subsection{Convolutional neural networks}\nConvolutional neural network (CNN) is a network using a special type of layers called \"convolutional layers\". CNNs were invented more than 20 years ago (\\cite{LeCun1998ConvolutionalNF}) and they are powerful feature extractors compressing highly dimensional spatial inputs to a smaller feature vector. They are used mainly when dealling with images, but in general, convolutions are useful for any type of spatial data with translational invarience property. When a network is asked to perform an image classification, it is often desireable for an object in the left part of the image to be detected in the same way as an object on the right side. Convolutional layer achives this by convolving each part of the input image with the same kernel, thus sharing weights and greatly reducing the parameter count. Each convolutional kernel is sometimes referred to as \"filter\", because the kernel convolution operation resembles a sobol operator used in classical computer vision and image processing. CNNs usually stack multiple convolutional layers on top of each other with each subsequent layer having more filters, but reducing the spatial dimension. The spatial dimension reduction is achived by an average or max pooling layers that follow periodically after each set of convolutional layers. The final convolution outputs are either pooled together to reduce the spatial dimension to 1x1, or they are passed through a one or two densely connected layers to produce the extracted features.\n\n\n\\section{Related Work}\n\\label{related_work}\n\n\\subsection{Definitions}\nAs it was outlined in chapter \\ref{introduction}, adversarial attacks are methods of producing adversarial examples. Given an original input $x$ and a classifier model $y = f(x), y \\in C$, an adversarial example $x_{adv} = x + \\delta$ is a slightly pertubed version of $x$, such that $f(x_{adv}) \\neq y$. By \"slightly\" we mean $\\lVert \\delta \\rVert < \\epsilon$. In this work we focus on image adversarial examples achieving misclasification on image classification models, albeit the concept of adversarial attacks is applicable across different types of neural networks and different types of input data.\n\nOne can be also interested in the minimal pertubation $\\delta_{min}$ needed to change the model classification:\n\n$$\\delta_{min} = \\argmin{\\delta} \\lVert \\delta \\rVert \\quad \\text{such that} \\quad f(x + \\delta) \\neq y$$\n\nThis brings us to the definition of robustness $r(x, f)$ given an input $x$:\n$$r(x, f) = \\lVert \\delta_{min} \\rVert$$\n\nMore informative can be the expected robustness across all of our data $D$, the global robustness of a model:\n\n$$\\rho (f) = \\underset{x \\sim \\mathcal D}{\\mathbb E} r(x, f)$$\n\nWhether we do or do not care about the nature of misclassification distinguishes the targeted and untargeted attacks:\n\n\\begin{itemize}\n    \\item targeted attacks require that $f(x_{adv}) = t, t \\in C$\n    \\item untargeted attacks only aim for unspecified misclasification - $f(x_{adv}) \\neq y$\n\\end{itemize}\n\n\nThe constraint on pertuation size $\\lVert \\delta \\rVert$ makes sure, that the adversarial example $x_{adv}$ looks almost the same as the original $x$. That said, there are many valid choices for the metric $\\lVert \\cdot \\rVert$ that are commonly used:\n\n\\begin{itemize}\n    \\item $l_{0}$ - the number of non-zero components of $\\delta$.\n    \\item $l_{1}$ - $\\lVert \\delta \\rVert = \\underset{i}{\\sum} \\lvert \\delta_{i} \\rvert$\n    \\item $l_{2}$ - $\\lVert \\delta \\rVert = \\sqrt{\\sum \\delta_{i}^2}$\n    \\item $l_{inf}$ - $\\lVert \\delta \\rVert = \\underset{i}{\\max \\delta_{i}}$\n\\end{itemize}\n\n\n\n\\subsection{Whitebox attacks}\nWhitebox adversarial attacks assume full knowledge of the target model, which allows for efficient computation of the the gradients with respect to the input. This is in contrast with blackbox attacks \\ref{blackbox_attack}, where the attacked model is available only as a blackbox and as such the gradients can be only estimated using sampling for example.\n\n\\cite{Biggio2013EvasionAA} was the first to point out the inherent vulnerability of machine learning models by attacking SVMs and multi-layer perceptrons.\n\n\nIn the same year \\cite{szegedy2014intriguing} used an L-BFGS optimization algorithm that leverages estimates of second order partial derivates information to find minimally distorted adversarial example $x$ by solving the following:\n$$\\min \\lVert x - x_{adv} \\rVert_2^2 \\quad \\text{s.t.} \\quad f(x_{adv}) = t \\quad \\text{and} \\quad x_{adv} \\in [0, 1]^m$$\n\n\nIn 2014 \\cite{goodfellow2015explaining} introduced the Fast gradient sign method (FGSM) which we use in \\ref{fgsm_exp}. It involves doing only one backpropagation, so it is very efficient and is often use for an adversarial training. Adversarial training is a method of dynamicaly extending the training dataset by adversarial examples generated on the fly. FGSM is well suited for this, because it's fast.\n\nIn 2015 Jacobian-based saliency map attack (JSMA) was proposed by \\cite{papernot2015limitations}.\n\nVarious methods trying to reduce the susceptibility of neural networks to adversarial examples are being proposed around this time. These methods are called \"adversarial defences\". One of those is the previously mentioned adversarial training. Few others include for example JPG compression, stochastic augmentations, feature distilation etc.\n\nAs an attempt to break a specific \"distilation defense\", \\cite{carlini2017evaluating} propose their C\\&W attack. FGSM and L-BFGS aren't strong-enough against the distilation defense, because the gradients are orders of magnitude smaller than in the case of an undefended target.\n\nThey reframe the optimization problem as:\n$$\\min \\lVert x - x_{adv} \\rVert^2_2 + c \\cdot f(x', t) \\quad \\text{s.t.} \\quad x' \\in [0, 1]^m \\quad \\text{where} \\quad f(x', t) = (max_{i \\neq t} Z(x')_i - Z(x')_t)^+$$\n\nTheir reframing allows for adaptive scaling of the objective being optimized and as such doesn't suffer as much from the small gradients. Furthemore, their objective is different from the objectives optimized previously, which also helps the C\\&W attack.\n\nFor a more comprehensive overview of whitebox attacks and adversarial attacks in general we will point the reader to the review paper \\cite{xu2019adversarial}.\n\n\\subsection{Transferability}\n\\label{transferability}\nIt was demonstrated \\cite{tramer2017space} that adversarial examples generated by whitebox attacks have high probability of decieving another neural network. This transferability of adeversarial examples is made more severe when the two models have similar architectures and when the datasets used to train them are the same.\n\n\n\\subsection{Blackbox attacks}\n\\label{blackbox_attack}\nIn the blackbox setting the access to the target model is limited and only the final output is available to the attacker.\n\nNevertheless, the transferability proprety \\ref{transferability} can be used to fool the target model without any further knowledge. \n\nA different approach of attacking a blackbox model can be to estimate the gradients by sampling to make up for the inability to backpropage through it. (\\cite{Chen2017ZOOZO}, \\cite{Ilyas2018BlackboxAA})\n\nThere is yet another class of blackbox attacks. These attacks don't rely on the gradient information at all, but instead they use random search to find the adversarial pertubation. SquareAttack \\cite{Andriushchenko2020SquareAA}, which we utilize in this work, is one example of such attacks.\n\nIn chapter \\ref{our_approach} we talk more about the different blackbox attacks and about possible ways of combining different approaches together.\n\n    % - maximizes classification for t and minimizes classification for all other classes\n    % - so called **\"margin loss\"**\n    % - there are many different ways to define valid loss function, but margin loss seems to work the best (probably)\n%   - only difference in formulation is that L-BFGS  uses **cross-entropy** instead of **margin loss**\n    % - this formulation has a nice property, that when $C(x') = t$, then $f(x', t) = 0$, and the algorithm switches to optimizing only the **distance part of the objective**\n    % - efficient for finding the minimally distorted adversarial example\n% - quite very strong attack, useful for benchmarking\n\n\n", "meta": {"hexsha": "bd5c3f8e2b589d3dbfde04f15e4f73f9006bddf5", "size": 13411, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis-text/en/02_preliminaries.tex", "max_stars_repo_name": "kubic71/bachelors-thesis", "max_stars_repo_head_hexsha": "f17a85e4e144972034f1d2174b51e63c68b39ff7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thesis-text/en/02_preliminaries.tex", "max_issues_repo_name": "kubic71/bachelors-thesis", "max_issues_repo_head_hexsha": "f17a85e4e144972034f1d2174b51e63c68b39ff7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis-text/en/02_preliminaries.tex", "max_forks_repo_name": "kubic71/bachelors-thesis", "max_forks_repo_head_hexsha": "f17a85e4e144972034f1d2174b51e63c68b39ff7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 102.3740458015, "max_line_length": 1492, "alphanum_fraction": 0.7770486914, "num_tokens": 3222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3087936582277344}}
{"text": "\\documentclass[10pt,noinfoline]{imsart}\n\n%\\usepackage[OT1]{fontenc}\n\\usepackage{palatino}\n\\usepackage{bm}\n\\usepackage{geometry}\n\\usepackage{graphics,epsfig,rotate,lscape,graphicx,amsmath,amsthm,amssymb,amsfonts,amsbsy,delarray,sectsty,amscd,pifont}\n\\usepackage[mathscr]{euscript}  % gives a different type of mathcal\n\\usepackage{multirow}\n\\usepackage{soul,float}\n\\usepackage{mathrsfs}\n\\usepackage{epsf}\n\\usepackage{psfrag}\n%\\usepackage{verbatim}\n\\usepackage{fancyvrb}\n\\usepackage{enumerate}\n\\usepackage{subfigure}\n\\usepackage[colorlinks,citecolor=blue,urlcolor=blue]{hyperref}\n\\usepackage[usenames,dvipsnames]{color}\n\n%----- for algorithms\n%\\usepackage{algorithmicx}\n%\\usepackage{algorithm}\n\n%----- for side captions\n%\\usepackage{sidecap}\n\n%---- for shading regions\n%\\usepackage{framed}\n%\\usepackage[usenames,dvipsnames]{color}\n%\\definecolor{shadecolor}{gray}{0.90}\n\n% ---- for bib\n\\usepackage[numbers]{natbib}\n\\bibliographystyle{plain}\n\n\n\n\\geometry{letterpaper,left=1.2in,right=1.2in,top=1.2in,bottom=1.2in}\n\n\n\n%\\startlocaldefs\n\\definecolor{shadecolor}{gray}{0.90}\n\\newtheorem{claim}{Claim}\n\\newtheorem{proposition}{Proposition}\n\\newtheorem{theorem}{Theorem}\n\\newtheorem{lemma}{Lemma}\n\\newtheorem{conjecture}{Conjecture}\n\\newtheorem{corollary}[theorem]{Corollary}\n\\newtheorem{definition}{Definition}\n\\newtheorem{assumption}{Assumption}\n\\renewcommand{\\labelenumi}{(\\roman{enumi})}\n\\newcommand{\\bs}{\\boldsymbol}\n%\\endlocaldefs\n\n\n\n\n\n\\begin{document}\n\n\\begin{frontmatter}\n\n\\title{A generalized quadratic estimate for random field nonstationarity\n\\thanksref{code}}\n\\runtitle{Generalized quadratic estimate}\n\n\\begin{aug}\n  \\author{\\fnms{Ethan}  \\snm{Anderes}\\thanksref{a, t1}\\ead[label=e1]{anderes@ucdavis.edu}}\n    \\and\n  \\author{\\fnms{Joe} \\snm{Guinness}\\thanksref{b}\\ead[label=e2]{jsguinne@ncsu.edu}}\n\n  \\runauthor{Anderes and Guinness}\n\n  \\address[a]{Department of Statistics, University of California, Davis CA 95616, USA. \\printead{e1}}\n\n  \\address[b]{Department of Statistics, North Carolina State University. \\printead{e2}}\n\n\n  \\thankstext{t1}{EA was partially supported by NSF CAREER grant DMS-1252795}\n  \\thankstext{code}{All the source code used for the simulations and graphics in this paper is publicly available through the on-line repository \\url{https://github.com/EthanAnderes/NonstationaryPhase.jl}}\n\n\n\\end{aug}\n\n\\begin{abstract}\nIn this paper, we attempt to shed light on a new class of nonstationary random fields which exhibit, what we call, {\\em local invariant nonstationarity}. We argue that the local invariant property has a special interaction with a new  generalized quadratic estimate---also derived here---which extends an estimate originally developed for gravitational lensing of the Cosmic Microwave Background in Cosmology \\cite{hu2001mapping, hu2002mass}. The nature of this interaction not only encourages low estimation bias but also enables accurate (and fast) quantification of Frequentist mean square error quantification of the estimated nonstationarity. These quadratic estimates are interesting, in their own right, as they detect and estimate nonstationarity by probing correlation among Fourier frequencies, the absence of which is the characterizing feature of weak stationarity (by Bochner's Theorem). Moreover, this generalized quadratic estimate can be computed with a Fourier characterization that runs in $\\mathcal O(n\\log n)$ time when observing the field on a uniform grid of size $n$ in $\\Bbb R^d $. Finally, the work presented here partially addresses two other problems associated with the statistical theory of nonstationarity: 1) estimating the phase of a spatially varying modulated stationary random field and 2) identifying a larger class of nonstationary random fields which admit an extension of the quadratic estimator of gravitational lensing that extends the same attractive statistical properties.\n\\end{abstract}\n% \\begin{keyword}\n% \t\\kwd{}\n% \t\\kwd{}\n% \\end{keyword}\n\\end{frontmatter}\n\n\n\n\n\n\n\\tableofcontents\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Introduction}\n\n\nMany data sets in time series and spatial statistics show clear signs of nonstationarity \\cite{sampson2010constructions,fuglstad2015does}. \nDespite the prevalence of nonstationary data, theory for understanding and estimating nonstationary random field models is still underdeveloped compared to what is known for stationary random fields. For example, there seems to be no consensus among statisticians as to the relative merits of various nonstationary models and their corresponding estimates found in the current literature (examples of such models can be found in \\cite{hsing2016local,sampson1992nonparametric,paciorek2006spatial,fuglstad2015exploring}). While powerful spectral techniques have been developed for deriving absolute continuity or orthogonality of stationary random fields \\cite{ibragimov2012gaussian} and for understanding the implications for spatial interpolation \\cite{stein2012interpolation}, we know quite little about such topics for nonstationary random fields.  A further complicating matter is that even if the parametric form for the nonstationary data generating mechanism is known, difficulties associated with the inevitable increase in the number of unknown parameters and computational complexity can outweigh the benefits of fitting the true nonstationary model. The situation is far worse for spatial statistics---as compared to time series---where irregularity of spatial observation locations and large boundary effects can make estimation and modeling of nonstationarity more difficult. \n\nIn this paper, we attempt to shed light on a new class of nonstationary random fields which exhibit, what we call, {\\em local invariant nonstationarity}. Formally defined in Section \\ref{section: local invariant}, a locally invariant nonstationary random field $\\{Z(\\bs x)\\colon \\bs x\\in \\Bbb R^d\\}$ has the feature that the covariance function can be written in the following form,\n\\begin{align*}\n\\text{cov}(Z(\\bs x), Z(\\bs y))=K(\\bs x-\\bs y, \\bs \\theta(\\bs x)-\\bs \\theta(\\bs y)),\n\\end{align*}\nwhere $K(\\cdot, \\cdot)\\colon \\Bbb R^d\\times \\Bbb R^d \\rightarrow \\Bbb R$ and $\\bs\\theta(\\cdot) \\colon \\Bbb R^d\\rightarrow \\Bbb R^d$ is a vector field which characterizes the nonstationarity in $Z(\\bs x)$. We argue that the locally invariant property has a special interaction with a new  generalized quadratic estimate (derived in Section \\ref{Section: the quad est}) which extends an estimate originally developed for gravitational lensing of the Cosmic Microwave Background in Cosmology \\cite{hu2001mapping, hu2002mass}. The nature of this interaction not only encourages low estimation bias but also enables accurate (and fast) Frequentist mean square error quantification of the nonstationarity characterized by $\\bs \\theta(\\bs x)$. These quadratic estimates are interesting in their own right, as they detect and estimate nonstationarity by probing correlation among Fourier frequencies, the absence of which is the characterizing feature of weak stationarity (by Bochner's Theorem). Moreover, this generalized quadratic estimate can be computed with a Fourier characterization that runs in $\\mathcal O(n\\log n)$ time and $\\mathcal O(n)$ storage when observing the field on a uniform grid of size $n$ in $\\Bbb R^d $. Finally, the work presented here partially addresses two unanswered questions that arise in two important bodies of work on nonstationarity: 1) estimating the spatially varying phase in the models analyzed by Dahlhaus \\cite{dahlhaus1997fitting,dahlhaus2000likelihood} and 2) how to extend the quadratic estimate of dark matter from the Cosmic Microwave Background to more general nonstationary random fields.\n\n\nThe seminal work of Dahlhaus in the time series literature \\cite{dahlhaus1997fitting,dahlhaus2000likelihood}  is  an example of a collection of results that hint at a more general statistical theory of nonstationarity.  Dahlhaus develops asymptotic theory for a particular class of nonstationary random fields modeled by a spatially (or temporally) varying spectral density. These random fields were originally developed for time series \\cite{priestley1965evolutionary,priestley1981spectral} and have the form \n\\begin{align}\n\\label{eq: intro nonstat phase model}\nZ(\\bs x)= \\int_{\\Bbb R^d} e^{i\\bs x\\cdot \\bs k} A(\\bs k, \\bs x)\\sqrt{C_{\\bs k}}\\frac{dW_{\\bs k}}{(2\\pi)^{d/2}}\n\\end{align} \nwhere  $C_{\\bs k}$ is a spectral density, $dW_{\\bs k}$ is an orthogonal increment random complex measure that satisfies $E|dW_{\\bs k}|^2 =  d{\\bs k}$ (see \\cite{Gikhman_Skorokhod_book_v1} for details on random measures) and $A({\\bs k},{\\bs x})$ represents a spatial (or temporal) modulation of $\\sqrt{C_{\\bs k}}$. \nDahlhaus proved consistency results for estimating the squared modulus $|A({\\bs k},{\\bs x})|^2$ when estimation is done  by maximizing a weighted sum of local likelihood functions. Left unanswered, however, is the question of estimating the phase of $A({\\bs k},{\\bs x})$. In Section \\ref{section: NPhase}, we partly resolve this question by showing that a generalized quadratic estimate can be used to estimate a pure phase modulation $A({\\bs k},{\\bs x})=\\exp({iB(\\bs k,\\bs x)})$ where $B(\\bs k,\\bs x)$ is a function taking values in $\\Bbb R$ and is a separable function of $\\bs x$ and $\\bs k$. Indeed, this nonstationary phase model has the local invariance property and, as such, can be accurately estimated (under certain conditions on $B(\\bs k,\\bs x)$) with the generalized quadratic estimate developed here.  \n\n\n\nAnother important development in the statistical theory of nonstationarity comes from recent gravitational lensing studies of the Cosmic Microwave Background (CMB) \\citep{das2011detection,van2012measurement, planck2013lensing, Polarbear2014, planck2015lensing}. In Cosmology, gravitational lensing describes the distortion of photon trajectories due to density fluctuations of intervening dark matter. These density fluctuations affect the CMB observations by introducing small nonstationarities in the original isotropic random field model of the CMB. The state-of-the-art estimator of lensing, the quadratic estimator developed by Hu and Okamoto \\cite{hu2001mapping, hu2002mass}, has become an incredibly successful tool for probing the nature of dark matter, understanding cosmic structure and constraining cosmological parameters. What is so surprising about this estimate is that is has small bias. This is due to a delicate cancellation of terms in an infinite Taylor expansion of the lensing effect. Unfortunately there has been no clear explanation as to why this cancellation occurs and whether or not it exists in other models of nonstationarity. In this paper, we argue that this cancellation is due to the fact that the lensing-induced nonstationarity is locally invariant. Moreover, the generalized quadratic estimator developed here extends the lensing estimator to more general settings. Indeed, many of techniques we use to derive the generalized quadratic estimator are inspired by---and closely follow---those used by Hu and Okamoto \\cite{hu2001mapping, hu2002mass}.  The point of this paper, in contrast to the work of Hu and Okamoto, is to identify the cause of the delicate Taylor series cancellation and extend the benefits of the lensing estimator to a larger class of nonstationary random fields available to general practitioners of spatial statistics.\n \n\nThe first part of this paper, given in Section~\\ref{section: local invariant}, defines the {\\it locally invariant} property and uses it to derive a corresponding generalized quadratic estimate, called the quadratic estimate hereafter,  which has particularly low bias. These new estimates are global rather than local in nature and thus avoid complicating theoretical and practical issues related to bandwidth selection. Moreover, they are unique in that they work in the spectral domain by estimating cross correlation of the Fourier coefficients.  In Section~\\ref{section: local invariant} we also derive analytic approximations for estimation variance and second order bias of the quadratic estimate. These approximations, and indeed the estimate itself, are often very accurate and have Fourier representations that yield fast computation.\n\n\nThe second part of this paper is given in Section~\\ref{section: NPhase}. Here we analyze random fields which are characterized by a spatially varying spectral phase modulation of a stationary field, called nonstationary spectral phase random fields for the remainder of this paper. These models effectively generalize warping models, are locally invariant and, as such, are amenable to quadratic estimates. In Subsection \\ref{section: Locally attainable spectral densities} we characterize how the local spectral density of the nonstationary spectral phase model varies as a function of spatial location. The theory of optimal transport and the $L_2$-Wasserstein metric play an important role in this characterization and leads to a natural heuristic for quantifying estimation bias in terms of the Wasserstein geodesic cut locus (see Claim \\ref{claim: cut locus}, Section \\ref{section: modeling xi, C and eta} and Figure \\ref{Figure 2 zx and var, extra bias}). We also present a set of simulations, based on nonstationary spectral phase random fields, which demonstrate the accuracy of both the quadratic estimate and our approximation to the mean squared sampling properties of the quadratic estimate. \n\n\n\n\n\n\\subsection{Notation}\n\nFor readability it will be advantageous to briefly summarize the notational conventions used throughout this paper, some of which are borrowed from Cosmology and are somewhat nonstandard in the statistics literature.\nVariables taking values in $\\Bbb R^d$ or $\\Bbb R^{d\\times d}$ will generally be written with bold font such as $\\bs x, \\bs y, \\bs k,\\bs \\ell\\in \\Bbb R^d$ or $\\bs A,\\bs M \\in \\Bbb R^{d\\times d}$. Indexing into vector or matrix coordinates are written with subscripts so that $\\bs x_i\\in\\Bbb R$ denotes the $i^{\\text{th}}$ coordinate of $\\bs x\\in\\Bbb R^d$, for example. When $\\bs z, \\bs w\\in\\Bbb C^d$ we let the (non-Hermitian) dot product  be denoted by $\\bs z \\cdot \\bs w = \\bs z_1 \\bs w_1 + \\ldots + \\bs z_d \\bs w_d$.\n\n\nVector fields  $\\bs \\theta(\\bs x):\\Bbb R^d\\rightarrow \\Bbb R^d$ are also written bold so that \\mbox{$\\bs \\theta(\\bs x)=(\\bs\\theta_{1}(\\bs x),\\ldots, \\bs\\theta_{d}(\\bs x))^T$} where $\\bs \\theta_i(\\bs x):\\Bbb R^d\\rightarrow \\Bbb R$. The Fourier transform of $\\bs \\theta(\\bs x)$, for example, is applied coordinate-wise and written $\\bs \\theta_{\\bs k}=(\\bs \\theta_{1,\\bs k},\\ldots, \\bs \\theta_{d,\\bs k})^T$ where $\\bs \\theta_{j,\\bs k}$ denotes the Fourier transform of $\\bs \\theta_j(\\bs x)$ and is defined as\n\\[\n \\bs\\theta_{j,\\bs k}= \\int e^{-i\\bs x\\cdot \\bs k} \\bs \\theta_{j}(\\bs x) \\frac{d\\bs x}{(2\\pi)^{d/2}}.\n \\]\nFor a mean-zero stationary random field $\\{Z(\\bs x): \\bs x\\in\\Bbb R^d\\}$ the autocorrelation function is denoted  $C^Z(\\bs x-\\bs y) := E(Z(\\bs x)Z(\\bs y)^*)$ and the spectral density is denoted $C_{\\bs\\ell}^{ZZ} = {(2\\pi)}^{d/2} C_{\\bs\\ell}^Z$ where, via our convention, $C_{\\bs\\ell}^Z$ denotes the Fourier transform of $C^Z(\\bs x)$.\nParenthetical superscripts are reserved for enumerating functions (and \\textit{not} higher order derivatives). For example $f^{(1)}_{\\bs k}, f^{(2)}_{\\bs k}, f^{(3)}_{\\bs k}, \\ldots$ denotes a sequence of functions taking arguments $\\bs k\\in \\Bbb R^d$ in the Fourier domain. This convention avoids indexing ambiguities and the subscript convention of the Fourier transform.\n\n\nIn the derivations that follow, one may assume all random fields have periodic boundary conditions on $(-L/2, L/2]{}^d$, for some large $L>0$. This alleviates subtleties associated with the Fourier transform of non-periodic random fields defined on $\\Bbb R^d$. However, extensions to non-periodic random fields can be made with an appropriate use of generalized random fields and generalized Fourier transforms. To incorporate the periodic case and the---possibly generalized---general case we use a single notation for the Fourier transform in both situations. For example when  $f(\\bs x)$ is periodic on $(-L/2, L/2]{}^d$ the notation $\\int e^{-i\\bs x\\cdot \\bs k} f(\\bs x)\\frac{d\\bs x}{(2\\pi)^{d/2}}$ and $\\int e^{i\\bs x\\cdot \\bs k} f_{\\bs k}\\frac{d\\bs k}{(2\\pi)^{d/2}}$ should be interpreted as notationally equivalent to $\\int_{-L/2}^{L/2}\\cdots\\int_{-L/2}^{L/2} e^{-i\\bs x\\cdot \\bs k} f(\\bs x)\\frac{d\\bs x}{(2\\pi)^{d/2}}$ and  $\\sum_{\\bs k \\in \\frac{2\\pi}{L}\\Bbb Z^d }   e^{i \\bs x\\cdot \\bs k}  f_{\\bs k} \\frac{(2\\pi/ L){}^{d}}{(2\\pi){}^{d/2}} $, respectively. A consequence of this convention is that, in the periodic case, one equates $d\\bs k$ with $(2\\pi / L)^d$ and, therefore,  the Dirac delta function $\\delta_{\\bs k}$ becomes a regular function taking the value $1/d\\bs k$ when $\\bs k=\\bs 0$ and zero otherwise. In particular, if $Z(\\bs x)$ is a mean zero stationary random field with with periodic boundary conditions on $(-L/2, L/2]^d$ then $E(Z_{\\bs k}^{\\phantom{*}} Z^{*}_{\\bs \\omega}) = \\delta_{\\bs k-\\bs \\omega}C_{\\bs k}^{ZZ}$\nand $E(|Z_{\\bs k}|^2) = \\delta_{\\bs 0}C_{\\bs k}^{ZZ}$.\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Locally invariant nonstationary random fields}\n\\label{section: local invariant}\n\nIn this section we define a property of nonstationary random fields called \\textit{local invariance}. This property,  along with a small set of generic model and observational assumptions, appears to be an important ingredient for quadratic estimates of nonstationarity to have low bias. Indeed, this is the main theme of the paper: {\\it that the structure of local invariance encourages bias cancellation}. A secondary theme of this paper is that local invariance provides a flexible restriction to the class of all random field covariance functions whereby making generalized quadratic estimation available to a wide class of nonstationary random field applications.\n\n\n\n\\begin{definition}\n\\label{Definition 1}\nLet $C^{\\bs \\theta}(\\bs x, \\bs y)$ be a positive definite covariance function defined on $\\bs x, \\bs y\\in\\Bbb R^d$ and parameterized by a vector field $\\bs \\theta(\\bs x)\\colon\\Bbb R^d\\rightarrow \\Bbb R^d$.\nThen $\\bs \\theta(\\bs x)$ is said to be a \\textbf{local invariant for $C^{\\bs \\theta}(\\bs x,\\bs y)$} if there exists a function \\mbox{$K:\\Bbb R^d\\times \\Bbb R^d \\rightarrow \\Bbb R$} such that\n\\begin{align}\\label{def eq: local invariant covariance function}\nC^{\\bs \\theta}(\\bs x,\\bs y) = K\\big(\\bs x-\\bs y,\\bs \\theta(\\bs x) -  \\bs \\theta(\\bs y)\\big).\n\\end{align}\nEquivalently, \\textbf{$Z(\\bs x)$ is  locally invariant with respect to $\\bs\\theta(\\bs x)$} if $Z(\\bs x)$ is a random field  with covariance function $C^{\\bs \\theta}$ that satisfies (\\ref{def eq: local invariant covariance function}).\n\\end{definition}\n\n\n\n\nThe name \\textit{local invariance} is intended to express the following fact: any region where $\\bs \\theta(\\bs x)$ is constant results in the same local stationary model. In particular, suppose $Z(\\bs x)$ is a nonstationary random field with covariance function $C^{\\bs \\theta}(\\bs x, \\bs y)$ satisfying (\\ref{def eq: local invariant covariance function}). If $\\bs \\theta(\\bs x)$ has no variation (i.e. is constant) over neighborhoods $\\Omega_1\\subset \\Bbb R^d$ and $\\Omega_2\\subset \\Bbb R^d$ then $Z(\\bs x)$ is locally stationary over $\\Omega_1$ and $\\Omega_2$ with the same local autocovariance function $K(\\bs x-\\bs y, \\bs 0)$.\n\n\nExamples of local invariant nonstationary random fields are easy to find. Indeed any warped random field of the form $Z(\\bs x + \\bs \\theta(\\bs x))$ is locally invariant with respect to $\\bs\\theta(\\bs x)$ when $Z$ is a stationary random field. Another example of a locally invariant model, discussed later in Section \\ref{section: NPhase}, is the spatially varying spectral phase model given in (\\ref{eq: intro nonstat phase model}) where $A(\\bs k,\\bs x)=\\exp(i\\bs\\theta(\\bs x) \\cdot \\bs\\eta_{\\bs k})$ and $\\bs \\eta_{\\bs k}$ is a known function mapping $\\Bbb R^d$ into $\\Bbb R^d$ that has odd symmetry about the origin. It is interesting to note that many of the asymptotic results for spatially (or temporally) varying spectral models study the estimation of $|A(\\bs k, \\bs x)|^2$ using a local periodogram \\cite{dahlhaus1997fitting} or a version or the preperiodogram \\cite{dahlhaus2000likelihood}. Since  $|A(\\bs k, \\bs x)|^2 = 1$ for the spectral phase model (\\ref{eq: intro nonstat phase model}), these local periodograms to not immediately apply to the estimation of $A(\\bs k, \\bs x)$ defined in (\\ref{eq: intro nonstat phase model}).\n\n\nIn what follows we derive a quadratic estimate of $\\bs\\theta(\\bs x)$ for locally invariant nonstationarity of the form given in Definition \\ref{Definition 1}. The estimates are derived under the following observational scenario: a single realization of the nonstationary random field observed on a dense grid with additive stationary noise. These assumptions hold throughout the paper. We list them here to be completely explicit.\n\n\n\\begin{assumption}\\label{Assumption 4}\nLet $Z(\\bs x)$ be a mean zero nonstationary Gaussian random field with local invariant nonstationary covariance function $C^{\\bs \\theta}(\\bs x, \\bs y)$ satisfying Definition \\ref{Definition 1}. The data field, denoted $Z^{obs}(\\bs x)$, is observed on a dense regular grid and has the form\n\\[\nZ^{obs}(\\bs x) = Z(\\bs x) + N(\\bs x)\n\\]\nwhere  $N(\\bs x)$ is a mean zero stationary Gaussian generalized random noise with spectral density $C_{\\bs k}^{N\\!N}$.\n\\end{assumption}\n\nOur second assumption is that the local invariant vector field $\\bs \\theta(\\bs x)$ can be additionally characterized by an unknown scalar potential function $\\phi(\\bs x):\\Bbb R^d \\rightarrow \\Bbb R$. This assumption simply  reduces the amount of complexity necessary for  developing a quadratic estimate of $\\bs \\theta(\\bs x)$ while still retaining enough modeling flexibility.\n\n\\begin{assumption}\\label{Assumption 2}\nSuppose the vector field $\\bs\\theta(\\bs x)\\colon \\Bbb R^d \\rightarrow \\Bbb R^d$ is characterized by an unknown scalar potential field $\\phi(\\bs x)\\colon \\Bbb R^d \\rightarrow \\Bbb R$ along with a known vector field  $\\bs \\xi_{\\bs k}$ which satisfies\n\\[\n\\bs\\theta_{\\bs k} := \\big(\\bs\\xi^{\\phantom{*}}_{1,\\bs k} \\hspace{.05cm}\\phi_{\\bs k}^{\\phantom{*}}\\hspace{.05cm}, \\,\\ldots, \\, \\bs \\xi_{d,\\bs k}^{\\phantom{*}}\\hspace{.05cm}\\phi_{\\bs k}^{\\phantom{*}}\\big)^T\\!\\!.\n\\]\nFor each $j\\in\\{1,\\ldots, d\\}$ the coordinate spectral multiplier $\\bs\\xi_{j,\\bs k}:\\Bbb R^d\\rightarrow \\Bbb C$ is assumed to be a Hermitian function of $\\bs k$ so that $\\bs\\xi_{j,-\\bs k}^{\\phantom{*}}= \\bs\\xi_{j,\\bs k}^*$.\n\\end{assumption}\n\nNotice that the above scalar potential model includes the case that $\\bs \\theta(\\bs x)=\\nabla \\phi(\\bs x)$,  by setting $\\bs \\xi_{\\bs k}=i\\bs k$, and the case that $\\bs \\theta(\\bs x) = (\\phi(\\bs x),\\ldots, \\phi(\\bs x))$, by setting $\\bs \\xi_{\\bs k}=(1,\\ldots, 1)$.\n\n\n\\begin{assumption}\\label{Assumption 3}\nThere exists a mean zero stationary Gaussian random field prior for the unknown scalar potential $\\phi(\\bs x)\\colon \\Bbb R^d \\rightarrow \\Bbb R$. Let $C^{\\phi}(\\bs x - \\bs y)= E(\\phi(\\bs x)\\phi(\\bs y))$ denote the autocovariance function for $\\phi(\\bs x)$ and $C^{\\phi\\phi}_{\\bs k}$ denote the corresponding spectral density for this prior.\n\\end{assumption}\n\nIt is important to note that the prior in Assumption \\ref{Assumption 3} is not used to generate a Bayesian posterior. A Bayesian posterior sampling methodology would be an exciting development but not the scope of the current paper. Instead, the prior is only used to approximate the marginal distribution of the data which, in turn, is used to optimize Fourier weights and to generate a variance approximation for the quadratic estimate of $\\phi_{\\bs k}$. Indeed the quadratic estimate, derived in Section \\ref{Section: the quad est}, is defined to be an unbiased estimate of $\\phi$ (up to first order) regardless of how $C_{\\bs k}^{\\phi\\phi}$ is specified. The only effect of mis-specification (or non-existence) of $C_{\\bs k}^{\\phi\\phi}$ will be to generate an estimate which gives too much weight to unruly frequencies and to report a less accurate mean squared error when using the approximations developed in Section \\ref{Section: var and bias}.\n\n\nAssumptions \\ref{Assumption 4}, \\ref{Assumption 2} and \\ref{Assumption 3} are generic and intended to isolate a small set of  assumptions for deriving an estimate with small bias. Bias is not universally guaranteed to be small but the generalized quadratic estimates, derived in the next section for  local invariance models, often have surprisingly small estimation bias due to the local invariant property.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{\nA generalized quadratic estimate of $\\phi(\\bs x)$\n}\\label{Section: the quad est}\n\nBased on assumptions \\ref{Assumption 4}, \\ref{Assumption 2} and \\ref{Assumption 3} given in the previous section, the first step for deriving a generalized quadratic estimate of $\\phi(\\bs x)$ is to linearly approximate  $C^{\\bs \\theta}(\\bs x,\\bs y)$, with a Taylor expansion in $\\bs \\theta(\\bs x) - \\bs \\theta(\\bs y)$ as follows \n\\begin{align}\n\\label{first order term, intro}\nC^{\\bs \\theta}(\\bs x,\\bs y) = C^{(0)}(\\bs x-\\bs y)\n        + \\bs C^{(1)}(\\bs x-\\bs y)\\cdot \\left({\\bs\\theta(\\bs x)-\\bs\\theta(\\bs y)}\\right)\n        + \\mathcal O({\\phi}^2)+ \\mathcal O(\\phi^3)+\\cdots.\n\\end{align}\nwhere $C^{(0)}\\colon \\Bbb R^d \\rightarrow \\Bbb R$ and $\\bs C^{(1)}\\colon \\Bbb R^d \\rightarrow \\Bbb R^d$ satisfies $\\bs C^{(1)}(-\\bs x) = -\\bs C^{(1)}(\\bs x)$.\nNow, truncating (\\ref{first order term, intro}) to first order and applying Claim \\ref{claim: first order expansion} of Appendix \\ref{section: Detailed Proofs} gives the following linear approximation of the cross frequency covariance in the Fourier transform of $Z(\\bs x)$\n\\begin{align}\n\\label{eq: first order cov intro}\nE\\big(Z_{\\bs k+\\bs \\ell}Z_{-\\bs k}\\big)  \\approx  \\phi_{\\bs\\ell}\\left({\\bs\\xi_{\\bs\\ell}\\!\\cdot\\! \\bs C^{(1)}_{\\bs k} - \\bs\\xi_{\\bs\\ell}\\!\\cdot\\! \\bs C_{\\bs k+\\bs \\ell}^{(1)}}\\right).\n\\end{align}\nRecall Bochner's Theorem (details can be found in \\cite{Gikhman_Skorokhod_book_v1}) which states that the random field $Z(\\bs x)$ is stationary if and only if  \\mbox{$E\\big(Z_{\\bs k+\\bs \\ell}Z_{-\\bs k}\\big) = 0$} for every $\\bs\\ell \\neq\\bs 0$. Therefore nontrivial covariance between $Z_{\\bs k+\\bs \\ell}$ and $Z_{-\\bs k}$ at some nonzero lag $\\bs\\ell$ provides a direct probe into the nonstationarity present in $Z(\\bs x)$. Equation (\\ref{eq: first order cov intro}) is, therefore, a translation of how local invariant nonstationarity relates to nonzero cross covariance in $Z_{\\bs k}$.\nUsing this translation, Claim \\ref{appendix, claim: quad est derivations} of Appendix \\ref{section: Detailed Proofs} derives the quadratic estimate of $\\phi_{\\bs \\ell}$. This estimate is effectively  an inverse-variance weighted autocovariance estimate in the Fourier domain and is given by\n\\begin{align}\n    \\label{explicit form of the qe in body of paper}\n    \\hat\\phi_{\\bs \\ell}\n    &=  A_{\\bs \\ell}\n        \\int\n        {\\Big(\\bs\\xi_{\\bs \\ell} \\!\\cdot\\!\\bs C^{{(1)}}_{\\bs k} - \\bs\\xi_{\\bs \\ell} \\!\\cdot\\!\\bs C^{{(1)}}_{\\bs k+\\bs \\ell}\\Big)}^{\\! *}\n        \\frac{Z^{obs}_{\\bs k+\\bs \\ell}Z^{obs}_{-\\bs k}}{C^{ZZobs}_{\\bs k+\\bs \\ell}C^{ZZobs}_{\\bs k}}\\frac{d\\bs k}{{(2\\pi)}^{d/2}}.\n\\end{align}\nIn the above formula, $A_{\\bs \\ell}$ is a normalizing constant (see Claim \\ref{appendix, claim: quad est derivations} for an exact expression),  $C^{ZZobs}_{\\bs k}$ is defined to be $C^{ZZm}_{\\bs k} + C^{N\\!N}_{\\bs k}$ where $C^{ZZm}_{\\bs k}$ is the spectral density of $Z(\\bs x)$ marginalized over the prior for $\\phi(\\bs x)$ given in Assumption \\ref{Assumption 3}. Notice that the prior only serves to optimize the weights in $\\hat\\phi_{\\bs \\ell}$. Indeed, one can easily avoid specifying $C_{\\bs k}^{\\phi\\phi}$ by instead defining $C^{ZZm}_{\\bs k}$ to be ${(2\\pi)}^{d/2}C^{(0)}_{\\bs k}$ where $C^{(0)}_{\\bs k}$ denotes the Fourier transform of $C^{(0)}(\\bs x)$ from (\\ref{first order term, intro}).\n\nThe normalizing constant $A_{\\bs \\ell}$ is completely determined by the weights used on the terms $Z^{obs}_{\\bs k+\\bs \\ell}Z^{obs}_{-\\bs k}$ through the requirement that $\\hat\\phi_{\\bs \\ell}$ be unbiased up to first order in $\\phi$, in particular, requiring that $E(\\hat\\phi_{\\bs \\ell}) = \\phi_{\\bs \\ell} + \\mathcal O(\\phi^2)+ \\mathcal O(\\phi^3)+\\cdots$ or equivalently that $\\frac{1}{\\phi_{\\bs \\ell}}E(\\hat\\phi_{\\bs \\ell}) = 1 + \\mathcal O(\\phi)+ \\mathcal O(\\phi^2)+\\cdots$. \nThis results in the following an analytic characterization for $A_{\\bs \\ell}$\n\\begin{equation}\n\\label{in text eq of the normalizing constant}\n A_{\\bs \\ell}\n        \\int\n        \\frac{\\big|{\\bs\\xi_{\\bs\\ell}\\!\\cdot\\! \\bs C^{(1)}_{\\bs k} - \\bs\\xi_{\\bs\\ell}\\!\\cdot\\! \\bs C_{\\bs k+\\bs \\ell}^{(1)}}\\big|^2}{C^{ZZobs}_{\\bs k+\\bs \\ell}C^{ZZobs}_{\\bs k}}\\frac{d\\bs k}{{(2\\pi)}^{d/2}} = 1 + \\mathcal O(\\phi) + \\mathcal O(\\phi^2) + \\cdots.\n\\end{equation}\nNotice also that one is free to manually change weights used on each term $Z^{obs}_{\\bs k+\\bs \\ell}Z^{obs}_{-\\bs k}$ in  (\\ref{explicit form of the qe in body of paper}). This may be advantageous for optimizing the sampling behavior of $\\hat\\phi_{\\bs \\ell}$ to specific applications. For example one may want to down-weight corrupted frequencies in a particular experimental setting. In this case, however, the form of the normalizing constant $A_{\\bs \\ell}$ given in (\\ref{in text eq of the normalizing constant}) will need to be adjusted accordingly.\n\n\n\nOne of the advantages of the estimator $\\hat\\phi_{\\bs \\ell}$, defined in (\\ref{explicit form of the qe in body of paper}), is that there exists a fast algorithm for computing $\\hat\\phi_{\\bs \\ell}$ at all frequencies $\\bs \\ell$ simultaneously by alternating pointwise operations in the Fourier domain and the pixel domain. Indeed by Claim \\ref{appendix, claim: quad est derivations} of Appendix \\ref{section: Detailed Proofs} the quadratic estimate given in (\\ref{explicit form of the qe in body of paper}) is equivalent to\n\\begin{align}\n    \\label{fast form of the qe in body of paper}\n    \\hat\\phi_{\\bs \\ell}\n    &=   A_{\\bs \\ell}\\sum_{p=1}^d \\bs\\xi^*_{p,\\bs \\ell} \\int \n        e^{-i\\bs x\\cdot\\bs \\ell} \\mathscr A(\\bs x)\\mathscr B_{p}(\\bs x)\\frac{d\\bs x}{{(2\\pi)}^{d/2}}\n\\end{align}\nwhere $\\mathscr A_{\\bs \\ell}:= Z^{obs}_{\\bs \\ell}/ C^{ZZobs}_{\\bs \\ell}$ and $\\mathscr B_{p,\\bs \\ell} := i 2  \\, \\textrm{imag}(\\bs C^{(1)}_{p,\\bs \\ell}) Z^{obs}_{\\bs\\ell} / C^{ZZobs}_{\\bs\\ell}$ which  can be computed in $\\mathcal O(n\\log(n))$ time (when observing $Z^{obs}$ on a grid of size $n$) by a sequence of fast Fourier transforms, inverse fast Fourier transforms and pointwise operations.\n\nThe derivation above only depends on the local invariance property insofar as it is used to optimize the weights  in (\\ref{explicit form of the qe in body of paper}) and the resulting normalizing constant given in (\\ref{fast form of the qe in body of paper}). Indeed, exactly similar arguments can be made for deriving quadratic estimates of nonstationary models which are not locally invariant, such as covariance functions of the form $C^{\\bs\\theta}(\\bs x,\\bs y)=K(\\bs x-\\bs y,\\bs\\theta(\\bs x)+\\bs\\theta(\\bs y))$ for example. The key difference is that the quadratic estimate $\\hat \\phi_{\\bs \\ell}$ for models which are {\\it not} locally invariant  tend to either have a large  $\\mathcal O(\\phi^2)+ \\mathcal O(\\phi^3)+\\cdots$ bias,  small signal to noise ratio, or have significant non-Gaussian estimation variability. Local invariant models, in contrast, encourage a significant amount of cancellation occurring within $\\mathcal O(\\phi^2)+ \\mathcal O(\\phi^3)+\\cdots$ so that bias is small even in the regime of moderately large signal to noise ratio. Moreover, small higher order terms provide a regime where mean square estimation variability is accurately approximated with easily computable formulas. This is explored in more detail in Section \\ref{Section: var and bias} and in the simulation examples presented later.\n\n\n\\subsection{The Hu and Okamoto lensing estimate as a special case of $\\hat\\phi_{\\bs \\ell}$}\n\\label{section: Hu and Okamoto lensing special case}\n\nIn this section we show that $\\hat \\phi_{\\bs \\ell}$, derived in the previous section, is an extension of the original quadratic estimate developed in \\cite{hu2001mapping, hu2002mass} for Cosmic Microwave Background gravitational lensing. Start by letting $Z(\\bs x) = T(\\bs x + \\nabla \\phi(\\bs x))$  denote the lensed Cosmic Microwave Background  and $\\phi(\\bs x)$ denote the projected gravitational potential in the $\\Bbb R^2$ flat sky approximation. In the original derivation \\cite{hu2001mapping, hu2002mass} a Taylor approximation is first applied to $T(\\bs x+ \\nabla \\phi(\\bs x))$ as follows\n\\begin{equation}\n\\label{HuOk approx 1}\nZ(\\bs x) \\approx T(\\bs x) +  \\nabla T(\\bs x)\\cdot\\nabla \\phi(\\bs x)\n\\end{equation}\nThe above linear model is then used to linearly approximate $Z(\\bs x)Z(\\bs y)$ by additionally discarding the term $\\big(\\nabla T(\\bs x)\\cdot\\nabla \\phi(\\bs x)\\big) \\big(\\nabla T(\\bs y)\\cdot\\nabla \\phi(\\bs y)\\big)$ which is quadratic in $\\phi$. Taking Fourier transforms, then an expected value, results in the following approximation\n\\begin{equation}\n\\label{HuOk approx 2}\nE(Z_{\\bs k+\\bs \\ell}Z_{-\\bs k}) \\approx \\frac{\\phi_{\\bs \\ell}}{2\\pi} \\Big(\\bs \\ell\\cdot(\\bs k+\\bs \\ell)C^{TT}_{\\bs k+\\bs \\ell} - \\bs \\ell\\cdot\\bs k C^{TT}_{\\bs k}\\Big).\n\\end{equation}\nNotice that (\\ref{HuOk approx 2}) is a special case of (\\ref{eq: first order cov intro}), and hence a special case of $\\hat\\phi_{\\bs \\ell}$ in (\\ref{explicit form of the qe in body of paper}), when setting $\\bs \\xi_{\\bs \\ell} = i\\bs \\ell$ and $\\bs C^{(1)}_{\\bs k} = \\frac{i\\bs k}{2\\pi}  C^{TT}_{\\bs k}$.\n\n\n\nIt is important to notice a particular subtlety when analyzing the accuracy of  (\\ref{HuOk approx 2}) in terms of the magnitude of the discarded terms in the Taylor approximation (\\ref{HuOk approx 1}). This subtlety can be illustrated by assuming the displacement $\\nabla \\phi(\\bs x)$ is extremely large and happens to be a \\textit{constant function of $\\bs x$}. In this case one clearly has $Z(\\bs x) \\not\\approx T(\\bs x)$, i.e. the zeroth order Taylor approximation completely breaks down. Yet, in a distributional sense, the zeroth order Taylor approximation is perfect since $Z(\\bs x)$ and $T(\\bs x)$ have the same finite dimensional distributions (by the fact that $T(\\bs x)$ is isotropic and $\\nabla \\phi(\\bs x)$ is assumed to be constant).\nTherefore one can not quantify the accuracy of (\\ref{HuOk approx 2}) by a map level analysis of the individual discarded terms in (\\ref{HuOk approx 1}).\nIn fact we propose that (\\ref{HuOk approx 2}) is accurate, not because the map level Taylor approximation (\\ref{HuOk approx 1}) is good (for which it is not), but rather because $\\nabla \\phi(\\bs x)$ is a locally invariant parameter and the corresponding nonstationary covariance\n\\[\nC^{\\bs \\theta}(\\bs x,\\bs y)=E(Z(\\bs x)Z(\\bs y)) = C^T(\\bs x - \\bs y + \\nabla\\phi(\\bs x) - \\nabla\\phi(\\bs y))\n\\]\nhas an accurate Taylor approximation in $\\nabla\\phi(\\bs x) - \\nabla\\phi(\\bs y)$, vis-\\`a-vis (\\ref{first order term, intro}).\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Variance and bias analytic approximation}\n\\label{Section: var and bias}\n\nIn Section \\ref{Section: the quad est} a fast formula was derived for computing the estimate $\\hat \\phi_{\\bs \\ell}$ when observing a single realization of $Z^{obs}(\\bs x)$. The speed at which $\\hat \\phi_{\\bs \\ell}$ can be computed on a dense observation grid makes it possible to perform large scale Monte Carlo analysis on $\\hat\\phi_{\\bs \\ell}$ in any experimental setting for which $Z^{obs}(\\bs x)$ can be easily simulated. In this section we complement a simulation-based method of uncertainty quantification by providing analytic approximations to variance and second order bias of $\\hat\\phi_{\\bs \\ell}$. These approximations are often very accurate and inherit a similar Fourier representation as (\\ref{fast form of the qe in body of paper}) for fast computation.\n\n\nBy inspection of (\\ref{explicit form of the qe in body of paper}) one can consider $\\hat\\phi_{\\bs \\ell}$ as a function of the quadratic form  $Z^{obs}_{\\bs k+\\bs \\ell}Z^{obs}_{-\\bs k}$, integrating over the variable $\\bs k$. In what follows we will consider the sampling behavior of $\\hat\\phi_{\\bs \\ell}$ when replacing $Z^{obs}_{\\bs k+\\bs \\ell}Z^{obs}_{-\\bs k}$ by some other function $X_{\\bs k, \\bs \\ell}$ of two variables $\\bs k,\\bs\\ell\\in \\Bbb R^d$. The following definition sets notation for this operation which is useful for denoting terms which are related to variance and bias of the estimator $\\hat\\phi_{\\bs \\ell}$ derived in subsections \\ref{SubSection: var} and \\ref{SubSection: bias}.\n\n\\begin{definition}\n\\label{def: quad est applied to X}\nFor any function $X_{\\bs k, \\bs \\ell}:\\Bbb R^d\\times \\Bbb R^d \\rightarrow \\Bbb C$ let\n$\\hat\\phi_{\\bs \\ell}\\{X_{\\bs k,\\bs \\ell}\\}$ denote the quadratic estimate $\\hat\\phi_{\\bs \\ell}$ defined in (\\ref{explicit form of the qe in body of paper}) but applied to the function $X_{\\bs k, \\bs \\ell}$ rather than $Z^{obs}_{\\bs k+\\bs \\ell}Z^{obs}_{-\\bs k}$. In particular $\\hat\\phi_{\\bs \\ell}\\{X_{\\bs k,\\bs \\ell}\\}$ is a function of $\\bs \\ell$  and satisfies\n\\[\n\\hat\\phi_{\\bs \\ell}\\{X_{\\bs k,\\bs \\ell}\\}\n:=A_{\\bs \\ell}\n        \\int\n        {\\Big(\\bs\\xi_{\\bs \\ell} \\!\\cdot\\!\\bs C^{{(1)}}_{\\bs k} - \\bs\\xi_{\\bs \\ell} \\!\\cdot\\!\\bs C^{{(1)}}_{\\bs k+\\bs \\ell}\\Big)}^{\\! *}\n        \\frac{X_{\\bs k,\\bs \\ell}}{C^{ZZobs}_{\\bs k+\\bs \\ell}C^{ZZobs}_{\\bs k}}\\frac{d\\bs k}{{(2\\pi)}^{d/2}}.\n\\]\nIf, on the other hand, $X_{\\bs k}$ and $Y_{\\bs k}$ are both functions of a single frequency argument $\\bs k\\in \\Bbb R^d$ then  we define\n\\[\n\\hat\\phi_{\\bs \\ell}\\{X,\\!Y\\}\n:=A_{\\bs \\ell}\n        \\int\n        {\\Big(\\bs\\xi_{\\bs \\ell} \\!\\cdot\\!\\bs C^{{(1)}}_{\\bs k} - \\bs\\xi_{\\bs \\ell} \\!\\cdot\\!\\bs C^{{(1)}}_{\\bs k+\\bs \\ell}\\Big)}^{\\! *}\n        \\frac{X_{\\bs k+\\bs \\ell}Y_{-\\bs k}}{C^{ZZobs}_{\\bs k+\\bs \\ell}C^{ZZobs}_{\\bs k}}\\frac{d\\bs k}{{(2\\pi)}^{d/2}}.\n\\]\n\\end{definition}\n\n\n\nIn the following two sections we derive approximations to the mean squared error and bias when using $\\hat\\phi_{\\bs \\ell}$ to estimate $\\phi_{\\bs \\ell}$. This comes in the form of two functions $C_{\\bs \\ell}^{\\text{var }\\hat\\phi}$ and $C_{\\bs \\ell}^{\\text{bias }\\hat\\phi}$ which represent approximations to the spectral density of variance and bias after marginalizing over the unknown $\\phi_{\\bs \\ell}$ using the Gaussian random field prior given in Assumption \\ref{Assumption 3}.\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Variance spectral density $C_{\\bs \\ell}^{\\text{var }\\hat\\phi}$}\n\\label{SubSection: var}\n\n\nThere are two main contributions to the variability in $\\hat\\phi_{\\bs\\ell}$. The first source of variability is due to the   additive observational noise $N(\\bs x)$. The second source, sometimes called \\textit{shape noise} in Cosmology, is due to the baseline stationary fluctuations in $Z(\\bs x)$ characterized by the autocovariance function $K(\\bs x - \\bs y, \\bs 0)$.  The spectral density of this shape noise can be approximated by ${(2\\pi)}^{d/2}C^{(0)}_{\\bs \\ell}$, which corresponds to the zero${}^\\text{th}$ order approximation in (\\ref{first order term, intro}), or by $C^{ZZm}_{\\bs \\ell}$ which denotes the  spectral density of $Z(\\bs x)$ marginalized over the prior from Assumption \\ref{Assumption 3}. Both these approximations can be used, within the formulas derived below, to give accurate approximations to the mean squared variability in $\\hat\\phi_{\\bs \\ell}$. However, in the cosmology literature on gravitational lensing, the marginal stationary model for $Z(\\bs x)$ is typically used, rather than ${(2\\pi)}^{d/2}C^{(0)}_{\\bs \\ell}$, for shape noise quantification.\n\n\nTo derive $C_{\\bs \\ell}^{\\text{var }\\hat\\phi}$ first let $X(\\bs x)$ denote the mean zero stationary Gaussian random field which models the sum of the observational noise $N(\\bs x)$ and the shape noise discussed in the previous paragraph. By propagating the random field $X$ through the quadratic estimate one obtains an estimate of variability of $\\hat\\phi_{\\bs \\ell}$ around its expected value. In particular\n\\begin{align}\nE\\big(\\big[\\hat\\phi_{\\bs \\ell}-E(\\hat\\phi_{\\bs \\ell})\\big]\\big[\\hat\\phi_{\\bs \\ell^\\prime}-E(\\hat\\phi_{\\bs \\ell^\\prime})\\big]^*\\big) &\\approx E\\big(\\hat\\phi_{\\bs \\ell}\\{X,\\!X\\} \\, \\hat\\phi_{\\bs \\ell^\\prime}\\{X,\\!X\\}^*\\big) =:  \\delta^{\\phantom{*}}_{\\bs \\ell-\\bs \\ell^\\prime} C^{\\text{var }\\hat\\phi}_{\\bs \\ell} \\label{var aprox wick form}\n\\end{align}\nwhere the existence of the spectral density $C^{\\text{var }\\hat\\phi}_{\\bs \\ell}$ is guaranteed by the fact that $X(\\bs x)$ is stationary so that $\\hat\\phi_{\\bs \\ell}\\{X,X\\}$ is stationary in the pixel domain (see Claim \\ref{thm: quantify the var fluctuations of hat phi}).\nDepending on which approximation one uses for the baseline stationary fluctuations in $Z(\\bs x)$, the spectral density of $X(\\bs x)$ can be defined in one of the following two ways\n\\begin{align}\\label{Cxx def}\nC^{X\\!X}_{\\bs \\ell}=\n\\begin{cases}\nC^{N\\!N}_{\\bs \\ell} + {(2\\pi)}^{d/2}C^{(0)}_{\\bs \\ell}, & \\text{option 1;}\\\\\nC^{N\\!N}_{\\bs \\ell} + C^{ZZm}_{\\bs \\ell}, & \\text{option 2.}\n\\end{cases}\n\\end{align}\nNow given $C^{X\\!X}_{\\bs \\ell}$, Claim \\ref{thm: quantify the var fluctuations of hat phi} establishes that\n\\begin{align}\n\t\\label{eq: spec den of hatphi on X}\n\tC^{\\text{var }\\hat\\phi}_{\\bs \\ell} &=\n        2 A_{\\bs\\ell}^2\n        \\int\n        {\\Big|\\bs\\xi_{\\bs \\ell} \\!\\cdot\\!\\bs C^{{(1)}}_{\\bs k} - \\bs\\xi_{\\bs \\ell} \\!\\cdot\\!\\bs C^{{(1)}}_{\\bs k+\\bs \\ell}\\Big|}^{2}\n        \\frac{C^{X\\!X}_{\\bs k+\\bs \\ell}}{{(C^{ZZobs}_{\\bs k+\\bs \\ell})}{}^2}\n        \\frac{C^{X\\!X}_{\\bs k}}{{(C^{ZZobs}_{\\bs k})}{}^2}\\frac{d\\bs k}{{(2\\pi)}^{d}}.\n    \\end{align}\n In certain situations the right hand side of (\\ref{eq: spec den of hatphi on X}) can be simplified. Recall that in the definition of $\\hat\\phi_{\\bs \\ell}$, one has two options for defining $C^{ZZobs}_{\\bs \\ell}$, either $C^{N\\!N}_{\\bs \\ell} + {(2\\pi)}^{d/2}C^{(0)}_{\\bs \\ell}$ or $C^{N\\!N}_{\\bs \\ell} + C^{ZZm}_{\\bs \\ell}$, depending on if one wants to use the prior spectral density $C^{\\phi\\phi}_{\\bs \\ell}$ for optimizing the quadratic estimate weights. If the choice of $C^{ZZobs}_{\\bs \\ell}$ matches the choice of  $C_{\\bs \\ell}^{X\\!X}$ then one obtains the following simplification of (\\ref{eq: spec den of hatphi on X})\n\\begin{align}\n\t\\label{eq: spec den of hatphi on CZZmobs}\nC^{\\text{var }\\hat\\phi}_{\\bs \\ell} = 2{(2\\pi)}^{-d/2} A_{\\bs \\ell}.\n \\end{align}\n\n\n\n\nIt should be noted that when marginalizing  over the prior given in Assumption \\ref{Assumption 3} the process $Z(\\bs x)$ becomes stationary but non-Gaussian. On the other hand, when conditioning on $\\phi$, the process $Z(\\bs x)$ is Gaussian but nonstationary. Therefore, when using option 2 in equation (\\ref{Cxx def}) to model $C^{\\text{var }\\hat\\phi}_{\\bs \\ell}$, the approximation in (\\ref{var aprox wick form}) includes a Gaussian approximation to $X(\\bs x)$. Finally, we mention that Claim \\ref{thm: quantify the var fluctuations of hat phi} also gives a Fourier based characterization  for fast computation of $C^{\\text{var }\\hat\\phi}_{\\bs \\ell}$. \n\n\n\n\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Bias spectral density $C_{\\bs \\ell}^{\\text{bias }\\hat\\phi}$}\n\\label{SubSection: bias}\n\nThe higher order terms $\\mathcal O(\\phi^n)$ in  (\\ref{first order term, intro}) are the exclusive source of bias in the quadratic estimate. The relation between $\\mathcal O(\\phi^n)$ and estimation bias can be written as follows\n\\[\nE(\\hat\\phi_{\\bs \\ell}|\\phi) -\\phi_{\\bs \\ell} =   \\hat\\phi_{\\bs\\ell}\\bigl \\{ {\\mathcal O(\\phi^2)}_{\\bs k +\\bs \\ell, -\\bs k} \\bigr \\} + \\hat\\phi_{\\bs\\ell}\\bigl \\{ {\\mathcal O(\\phi^3)}_{\\bs k +\\bs \\ell, -\\bs k} \\bigr \\} +\\cdots\n\\]\nwhere $\\mathcal O(\\phi^n)_{\\bs k+\\bs \\ell, -\\bs k}$ is defined to be Fourier transform of $\\mathcal O(\\phi^n)(\\bs x,\\bs y)$, defined in (\\ref{first order term, intro}), and evaluated at frequencies $\\bs k+\\bs \\ell$ and  $-\\bs k$, respectively. For the local invariant models we consider here, the second order bias term has the following form \n\\begin{equation}\\label{eq: 2nd order bias (x,y)}\n\\mathcal O(\\phi^2)(\\bs x,\\bs y) = (\\bs\\theta(\\bs x) - \\bs\\theta(\\bs y))^T \\bs C^{(2)}(\\bs x-\\bs y) (\\bs\\theta(\\bs x) - \\bs\\theta(\\bs y))\n\\end{equation}\nwhere $\\bs C^{(2)}\\colon \\Bbb R^d\\rightarrow \\Bbb R^{d\\times d}$ is a symmetric function about the origin.\nThis expression makes it clear how local invariant nonstationarity encourages low quadratic estimation bias. When the observational noise level is small, the high frequency fluctuations in the observations $Z^{obs}(\\bs x)$ are more influential to the quadratic estimate.\nAt these small scales the smoothness of $\\bs \\theta(\\bs x)$ and the function $\\bs C^{(2)}(\\bs x-\\bs y)$ will attenuate the influence of $\\mathcal O(\\phi^2)$  when propagated through $\\hat\\phi_{\\bs \\ell}$.\n\n\nFor remainder of this section we analyze how the second order term (\\ref{eq: 2nd order bias (x,y)}) propagates to second order bias in the quadratic estimate, denoted $\\hat\\phi_{\\bs \\ell}^{\\text{bias}}$. \nClaim \\ref{thm: bias in the appendix} in the Appendix gives the following expression for $\\hat\\phi_{\\bs \\ell}^{\\text{bias}}$\n\\begin{align}\n    \\label{2nd order bias in local invariant section II}\n    \\hat\\phi_{\\bs \\ell}^{\\text{bias}}&=\\hat\\phi_{\\bs \\ell}\\big\\{\\mathcal O(\\phi^2)_{\\bs k+\\bs \\ell, -\\bs k}\\big\\} =  2\\sum_{p,q=1}^d\\int  \\bs\\theta_{p,\\bs\\omega}\\bs\\theta_{q,\\bs \\ell - \\bs\\omega}\\, \\hat\\phi_{\\bs \\ell}\\big\\{{\\bs C^{(2)}_{p,q,\\bs k}}- {\\bs C^{(2)}_{p,q,\\bs k + \\bs\\omega}}\\big\\}\\frac{d\\bs\\omega}{(2\\pi)^{d/2}}.\n\\end{align}\nMoreover the marginal expected value of this bias term satisfies $E\\big( \\hat\\phi_{\\bs \\ell}^{\\text{bias}} \\big) = 0$\nwhen $\\bs \\ell \\neq 0$. Therefore, to quantify the marginal magnitude of the second order bias one must use the variance of (\\ref{2nd order bias in local invariant section II}). This is done in  Claim \\ref{thm: bias in the appendix} which establishes that when $\\bs\\theta(\\bs x)$ is a mean zero Gaussian random field with spectral density matrix $C_{\\bs \\ell}^{\\bs \\theta\\bs\\theta}$ the corresponding spectral density for $\\hat\\phi_{\\bs \\ell}^{\\text{bias}}$, denoted $C_{\\bs \\ell}^{\\text{bias }\\hat\\phi}$, satisfies\n\\begin{align}\n\tC_{\\bs \\ell}^{\\text{bias }\\hat\\phi}\n\t&= 4\\!\\! \\sum_{p,q,p^\\prime\\!,q^\\prime\\!=1}^d \\int \n\t\\Big(\n\tC^{\\bs \\theta\\bs \\theta}_{p,p^\\prime,\\bs \\omega}C^{\\bs \\theta\\bs \\theta}_{q,q^\\prime,\\bs \\ell - \\bs \\omega}\n\t+ C^{\\bs \\theta\\bs \\theta}_{p,q^\\prime,\\bs \\omega}C^{\\bs \\theta\\bs \\theta}_{q,p^\\prime,\\bs \\ell - \\bs \\omega}\n\t\\Big)\\nonumber\n\t\\\\\n\t&\\qquad\\qquad\\qquad\\qquad\\qquad\\times\n\t\\hat\\phi_{\\bs \\ell}\\big\\{{\\bs C^{(2)}_{p,q,\\bs k}}- {\\bs C^{(2)}_{p,q,\\bs k + \\bs\\omega}}\\big\\}\n\t\\hat\\phi_{\\bs \\ell}\\big\\{{\\bs C^{(2)}_{p^\\prime,q^\\prime,\\bs k}}- {\\bs C^{(2)}_{p^\\prime,q^\\prime,\\bs k + \\bs\\omega}}\\big\\}^*\\frac{d\\bs\\omega}{(2\\pi)^{d}}\n\t\\label{eq in intro on spec den of O(phi2)}\n\\end{align}\nwhen $\\bs \\ell \\neq \\bs 0$.\nNotice that $\\hat\\phi_{\\bs \\ell}^{\\text{bias}}$ equals the exact, map level, bias contribution from the second order term $\\mathcal O(\\phi^2)$. Therefore the statement that $C_{\\bs \\ell}^{\\text{bias }\\hat\\phi}$ is an approximation  to the second order bias only refers to the fact that it marginally quantifies the impact of the second order term $\\mathcal O(\\phi^2)$ rather than the all order bias $\\mathcal O(\\phi^2) + \\mathcal O(\\phi^3) + \\cdots$. \n\nIn contrast to  $C^{\\text{var\\,} \\hat\\phi}_{\\bs \\ell}$, which can be computed quickly using forward and inverse Fourier transformations, the calculation of $C^{\\text{bias\\,} \\hat\\phi}_{\\bs \\ell}$ appears to require explicit looping over $\\bs\\omega$ for each $\\bs \\ell$. This is problematic when $Z(\\bs x)$ is observed on a high dimensional dense grid. However, there is an approximation to $C^{\\text{bias\\,} \\hat\\phi}_{\\bs \\ell}$ which is both fast and yields excellent numerical accuracy for frequencies $\\bs \\ell$ with small to moderate magnitude. The approximation is derived with a second order Taylor approximation $\\bs C^{(2)}_{p,q,\\bs k + \\bs\\omega}\\approx \\bs C^{(2)}_{p,q,\\bs k} +  \\nabla\\bs C^{(2)}_{p,q,\\bs k}\\bs \\omega +  \\frac{1}{2}\\bs \\omega^T \\nabla^2\\bs C^{(2)}_{p,q,\\bs k} \\bs \\omega$ so that \n\\begin{align}\n \\hat\\phi_{\\bs \\ell}\\big\\{{\\bs C^{(2)}_{p,q,\\bs k}}- {\\bs C^{(2)}_{p,q,\\bs k + \\bs\\omega}}\\big\\}\n \\approx \n -  \\hat\\phi_{\\bs \\ell}\\big\\{ \\nabla\\bs C^{(2)}_{p,q,\\bs k} \\big\\} \\,\\bs \\omega\n - \\textstyle\\frac{1}{2}\\bs \\omega^T\\, \\hat\\phi_{\\bs \\ell}\\big\\{ \\nabla^2\\bs C^{(2)}_{p,q,\\bs k} \\big\\}\\,\\bs \\omega.\n \\label{eq: fast approximation to Cpbias}\n\\end{align}\nThe advantage being that $ \\hat\\phi_{\\bs \\ell}\\big\\{ \\nabla\\bs C^{(2)}_{p,q,\\bs k} \\big\\}$ and $\\hat\\phi_{\\bs \\ell}\\big\\{ \\nabla^2\\bs C^{(2)}_{p,q,\\bs k} \\big\\}$ only need to be computed once and can therefore be factored out of the integral (\\ref{eq in intro on spec den of O(phi2)}). The factored integral is then recognized as a convolution which can be quickly computed using forward and inverse Fourier transforms. \nThe quality of the approximation to  $C^{\\text{bias\\,} \\hat\\phi}_{\\bs \\ell}$ is illustrated in Section \\ref{section: nonstat example d=1} where simulations are done on a sufficiently coarse grid to allow a comparison of both $C^{\\text{bias\\,} \\hat\\phi}_{\\bs \\ell}$ and the fast approximation. In Section \\ref{section: nonstat example d=2}, however, simulations are done on a two dimensional grid which is dense enough to necessitate the fast approximation to $C^{\\text{bias\\,} \\hat\\phi}_{\\bs \\ell}$.\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n%  subsection\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{An illustration of the bias reduction due to local invariance}\n\\label{subsubsection: illustration of the bias reduction}\n\nIn this section we give an example of two stochastic processes with nearly the same values of $\\bs C_{\\bs k}^{(0)}, \\bs C_{\\bs k}^{(1)}$ and $\\bs C_{\\bs k}^{(2)}$, discussed above, but where one process is not locally invariant.  A quadratic estimate of nonstationarity is derived for both models and the resulting bias of each is compared. The main conclusion is that a small deviation from the locally invariant structure results in a bias that is orders of magnitude larger than what is found in the local invariant model.\n\nConsider the following two periodic nonstationary stochastic processes\\footnote{We follow our notational convention and use non-bold symbols in this section to indicate scalar quantities for $d=1$. Moreover, due to the periodic nature of $Z(t)$ and $\\tilde Z(t)$, our notation dictates \n$\\int \\equiv \\sum_{k\\in \\Bbb Z}$ in (\\ref{eq: def Z(t) and tildeZ(t)}).}\n on $[-\\pi,\\pi)$\n\\begin{align}\n\\label{eq: def Z(t) and tildeZ(t)}\nZ(t) &:= \\int  e^{i tk} e^{i\\phi(t)k }\\sqrt{C_k}\\frac{dB_{k}}{\\sqrt{2\\pi}},\\qquad    \\widetilde Z(t) := \\int    e^{i tk} e^{\\phi(t)|k| }\\sqrt{C_k}\\frac{dB_{k}}{\\sqrt{2\\pi}}\n\\end{align}\nwhere  $dB_{k}$ is complex Gaussian white noise, $C_k$ is the Mat\\'ern spectral density  with parameters $\\nu = 2, \\rho = 0.025, \\sigma = 1$ (using parameterization given in equation (33) of \\cite{stein2012interpolation}),  $C^{\\phi\\phi}_k$ is the Mat\\'ern spectral density with parameters $\\nu = 3 , \\rho = 2\\pi/10, \\sigma = 0.03$. Notice that $Z(t)$ has a local invariant nonstationarity, whereas $\\widetilde Z(t)$ does not. Indeed the analog to expansion (\\ref{first order term, intro}) for the two covariance structures is given by\n\\begin{align}\n\\text{cov}(Z(t),Z(s))= C^{(0)}(t\\!-\\!s) &+ \\big(\\phi(t)-\\phi(s)\\big)^{\\phantom{2}} C^{(1)}(t\\!-\\!s) \\nonumber\\\\\n\t\t\t\t\t\t\t\t\t &+ \\big(\\phi(t)-\\phi(s)\\big)^2 C^{(2)}(t\\!-\\!s) + \\mathcal O(\\phi^3)\\label{eq: cov expansion cov(Z(t),Z(s))}\\\\\n\\text{cov}(\\widetilde Z(t),\\widetilde Z(s)) = C^{(0)}(t\\!-\\!s) &+ \\big(\\phi(t)+\\phi(s)\\big)^{\\phantom{2}} \\widetilde C^{(1)}(t\\!-\\!s) \\nonumber\\\\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t&+ \\big(\\phi(t)+\\phi(s)\\big)^2 \\widetilde C^{(2)}(t\\!-\\!s) + \\mathcal O(\\phi^3)\\label{eq: cov expansion cov(widetilde Z(t),widetilde Z(s))}\n\\end{align}\nwhere $\\widetilde C^{(1)}_k$ and $\\widetilde C^{(2)}_k$ are related to the corresponding local invariant terms as follows\n\\begin{align}\n\\widetilde C^{(1)}_k &:= |C^{(1)}_k|, \\qquad\n\\widetilde C^{(2)}_k := -C^{(2)}_k.\n\\label{eq: comparison of invariant and non-invariant expansions}\n\\end{align}\n\n\nThe quadratic estimate $\\hat\\phi_{\\ell}$ based on the observed local invariant process $Z^{obs}(t)= Z(t)$, without observational noise (so that $C^{N\\!N}_{\\ell}\\equiv 0$), is defined by (\\ref{explicit form of the qe in body of paper}). To construct a quadratic estimate of $\\phi_\\ell$ based on observations $\\widetilde Z^{obs}(t) = \\widetilde Z(t)$ first notice that one can use the expansion (\\ref{eq: cov expansion cov(widetilde Z(t),widetilde Z(s))}) to derive the following approximation\n\\begin{align*}\nE\\big(\\widetilde Z_{k+\\ell}\\widetilde Z_{-k}\\big)  \\approx  \\phi_{\\ell}\\left( \\widetilde C^{(1)}_{k} + \\widetilde C_{k+\\ell}^{(1)}\\right).\n\\end{align*}\nThis is similar to\n(\\ref{eq: first order cov intro}) with the exception of one sign change necessary to accommodate the non local invariant structure in $\\widetilde Z$.\nThe above approximation can now be used to define the following quadratic estimate of $\\phi_\\ell$, denoted $\\widetilde \\phi_{\\bs \\ell}$, from observations $\\widetilde Z^{obs}(t)$\n\\begin{align*}\n    \\widetilde\\phi_{\\ell}\n    &:=  \\widetilde A_{\\ell}\n        \\int\n        {\\Big(\\widetilde C^{{(1)}}_{k} + \\widetilde C^{{(1)}}_{k+\\ell}\\Big)}^{\\! *}\n        \\frac{\\widetilde Z^{obs}_{k+\\ell}\\widetilde Z^{obs}_{-k}}{\\widetilde C^{ZZobs}_{k+\\ell}\\widetilde C^{ZZobs}_{k}}\\frac{dk}{\\sqrt{2\\pi}}\n\\end{align*}\nwhere $\\widetilde A_{\\ell}$ is defined just as in (\\ref{in text eq of the normalizing constant}) with the exception that the minus sign is switched to a plus sign. Moreover, the approximations given in Sections \\ref{SubSection: var} and \\ref{SubSection: bias} can be similarly modified---just changing the negative sign in (\\ref{2nd order bias in local invariant section II}) and in the definition of $C_{\\ell}^{\\text{var }\\hat \\phi}$---to produce analogous approximations for the variance and bias of $\\widetilde \\phi_{\\ell}$, denoted  $C_{\\ell}^{\\text{var }\\widetilde \\phi}$ and  $C_{\\ell}^{\\text{bias }\\widetilde \\phi}$ respectively.\n\nFigure \\ref{Figure 1} shows the second order bias and variance approximation for the local invariant estimate $\\hat\\phi_{\\ell}$ (\\textbf{shown at left}) compared to the non local invariant estimate $\\widetilde\\phi_{\\ell}$ (\\textbf{shown at right}).\nThe left plot shows  $\\ell^2 C_{\\ell}^{\\text{var }\\hat \\phi}$ and $\\ell^2 C_{\\ell}^{\\text{bias }\\hat \\phi}$ (\\textbf{solid-green} and \\textbf{dashed-red}, respectively) whereas the right plot shows  $\\ell^2 C_{\\ell}^{\\text{var }\\widetilde \\phi}$ and  $\\ell^2 C_{\\ell}^{\\text{bias }\\widetilde  \\phi}$ (\\textbf{solid-green} and \\textbf{dashed-red}, respectively).\nBoth plots use the same axis range and additionally show the signal spectral density $\\ell^2C^{\\phi\\phi}_\\ell$ (\\textbf{dotted line}) for comparison of the respective signal to noise ratios. Note that all spectral densities shown are multiplied by $\\ell^2$ to improve the visualization of the high frequency power.\n\n\n\\begin{figure}[H]\n\\includegraphics[height=6.2cm]{figure1.pdf}\n\\caption{\n These plots are intended to give an illustration  of the bias attenuation effect of the local invariant covariance structure (the specifics of the models are given in Section \\ref{subsubsection: illustration of the bias reduction}).  The plot \\textbf{at left} corresponds to the local invariant model and show estimation variance $\\ell^2 C_{\\ell}^{\\text{var }\\hat \\phi}$ (\\textbf{solid-green}), bias $\\ell^2 C_{\\ell}^{\\text{bias }\\hat \\phi}$ (\\textbf{dashed-red}) and the signal $\\ell^2 C_{\\ell}^{\\phi\\phi}$ (\\textbf{dotted-black}). In contrast the plot \\textbf{at right} shows their non local invariant counterparts.  Notice that the locally invariant second order bias is orders of magnitude smaller than the corresponding non local invariant bias, even though the functions $ C^{(1)}_k$ and $ C^{(2)}_k$ are similar to their non local invariant counterparts  $\\widetilde C^{(1)}_k$ and $\\widetilde C^{(2)}_k$. }\n\\label{Figure 1}\n\\end{figure}\n\nThe main conclusion from Figure \\ref{Figure 1} is that, even though the functions $\\widetilde C^{(1)}_k$ and $\\widetilde C^{(2)}_k$ are very similar to their locally invariant counterparts, the local invariant model results in quadratic estimation bias that is orders of magnitude smaller than the corresponding non local invariant estimation bias. Indeed at most small frequencies $\\ell$ one has\n\\begin{align*}\n C_{\\ell}^{\\text{bias }\\hat \\phi} &\\ll \\min(C_{\\ell}^{\\phi\\phi}, C_{\\ell}^{\\text{var }\\hat \\phi}) \\\\\n C_{\\ell}^{\\text{bias }\\widetilde \\phi} &\\gg \\max( C_{\\ell}^{\\phi\\phi}, C_{\\ell}^{\\text{var }\\widetilde \\phi}).\n\\end{align*}\nFigure \\ref{Figure 1} also shows that for small $\\ell$, the signal to noise ratio $C_{\\ell}^{\\phi\\phi}/C_{\\ell}^{\\text{var }\\hat \\phi}$ is large enough to suggest $\\hat\\phi(t)$ will be successful at tracking the large scale features of $\\phi(t)$. Moreover, even at large $\\ell$, where the signal to noise ratio for $\\hat\\phi_{\\ell}$ is small, the fact that the bias is sub-dominant to the signal implies that detection of $C_{\\ell}^{\\phi\\phi}$ is possible by averaging over a large number of frequencies to attenuate the impact of $C_{\\ell}^{\\text{var }\\hat \\phi}$.\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%w\n%\n% Section\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%w\n\\section{Nonstationary spectral phase model}\n\\label{section: NPhase}\n\n\nIn this section we specialize the results of the previous section to random fields which have a particular form: nonstationary spectral phase random fields. These models are locally invariant (c.f. Definition \\ref{Definition 1}) and can be viewed as generalized warping models which are amenable to quadratic estimates. The general formulas for $\\hat\\phi_{\\bs \\ell}$, $C_{\\bs \\ell}^{\\text{var }\\hat\\phi}$ and $C_{\\bs \\ell}^{\\text{bias }\\hat\\phi}$, given in the previous section, are derived for the nonstationary spectral phase model to yield exact formulas. In subsection \\ref{section: Locally attainable spectral densities} we present a characterization of the local spectral densities for nonstationary spectral phase models using the theory of optimal transport and the $L_2$-Wasserstein metric. In subsection \\ref{section: modeling xi, C and eta} we present informal guidance for specifying some of the modeling parameters of the nonstationary models presented here.\nFinally, in sections \\ref{section: nonstat example d=1} and \\ref{section: nonstat example d=2}, we \npresent a set of simulations which demonstrate the quadratic estimate and the accuracy of our approximation to the mean squared sampling properties. \n\n\n\n\\begin{definition}\\label{def: nonstate phase}\nA real random field $Z(\\bs x)$ on $\\Bbb R^d$ is said to be a \\textbf{nonstationary spectral phase random field} if there exists  functions $C_{\\bs k}:\\Bbb R^d \\rightarrow \\Bbb R^+$, $\\bs \\theta(\\bs x):\\Bbb R^d \\rightarrow \\Bbb R^d$ and  $\\bs\\eta_{\\bs k}:\\Bbb R^d \\rightarrow \\Bbb R^d$ such that $C_{\\bs k}$ has finite $L_1(\\Bbb R^d)$ norm, $C_{-\\bs k} = C_{\\bs k}$,  $\\bs \\eta_{-\\bs k} =-\\bs\\eta_{\\bs k}$ and \n\\begin{align}\n\\label{eq: nonstate phase}\nZ(\\bs x)= \\int \\exp\\big(i\\bs x\\cdot \\bs k\\big)\\exp\\big(i\\bs\\theta(\\bs x) \\cdot \\bs\\eta_{\\bs k}\\big) \\,\\sqrt{C_{\\bs k}} \\frac{dW_{\\bs k}}{(2\\pi)^{d/2}}\n\\end{align}\nwhere $dW_{\\bs k}$  denotes a complex Gaussian white noise random measure on $\\Bbb R^d$ which satisfies $E|dW_{\\bs k}|^2 = d\\bs k$.\n\\end{definition}\n\n  \nThe covariance function $C^{\\bs \\theta}(\\bs x,\\bs y):=\\text{cov}(Z(\\bs x), Z(\\bs y))$ for the random field defined by (\\ref{eq: nonstate phase}), conditioning on $\\bs \\eta_{\\bs k}$ and $\\bs \\theta(\\bs x)$, can be computed as follows\n\\begin{align}\n\\label{eq: NPhase cov model}\nC^{\\bs \\theta}(\\bs x,\\bs y)=\n\\int  \\exp\\big(i(\\bs x-\\bs y)\\cdot \\bs k\\big)\\exp\\big( i(\\bs\\theta(\\bs x)-\\bs\\theta(\\bs y)) \\cdot \\bs\\eta_{\\bs k}\\big)\\,C_{\\bs k}\\frac{d\\bs k}{(2\\pi)^d} .\n\\end{align}\nThe fact that $C^{\\bs \\theta}(\\bs x,\\bs y)$ can be written as a function of $\\bs x-\\bs y$ and $\\bs\\theta(\\bs x)-\\bs\\theta(\\bs y)$ implies that $Z(\\bs x)$ has the local invariant property (see Definition \\ref{Definition 1}) with respect to the nonstationarity characterized by $\\bs\\theta(\\bs x)$. By assuming $\\bs \\eta_{\\bs k}$ is known and $\\bs \\theta(\\bs x)$ is characterized by a scalar potential $\\phi(\\bs x):\\Bbb R^d \\rightarrow \\Bbb R$ (see Assumption \\ref{Assumption 2}) the results of Section \\ref{Section: the quad est} can be applied to generate a quadratic estimate $\\hat\\phi_{\\bs \\ell}$ based on a single realization of $Z(\\bs x)$ with additive stationary noise.  Indeed, by expanding $\\exp( i(\\bs\\theta(\\bs x)-\\bs\\theta(\\bs y)) \\cdot \\bs\\eta_{\\bs k})$ in (\\ref{eq: NPhase cov model}), to second order, one obtains the following expression for the terms in (\\ref{first order term, intro}) and (\\ref{eq: 2nd order bias (x,y)})\n\\begin{align}\nC_{\\bs k}^{(0)} =  \\frac{C_{\\bs k}}{(2\\pi)^{d/2}}, \\qquad \\bs C_{\\bs k}^{(1)} = \\frac{i  \\bs \\eta_{\\bs k} C_{\\bs k}}{(2\\pi)^{d/2}},\\qquad \\bs C_{\\bs k}^{(2)} = -\\frac{\\bs \\eta_{\\bs k}\\bs \\eta_{\\bs k}^T C_{\\bs k}}{2(2\\pi)^{d/2}}.\\label{eq: C(1), C(2) and C(3) for nonstationary phase}\n\\end{align}\nThe last ingredient needed for computing  $\\hat\\phi_{\\bs \\ell}$,\\, $C_{\\bs\\ell}^{\\text{var }\\hat \\phi}$ and $C_{\\bs \\ell}^{\\text{bias }\\hat \\phi}$ is an expression for the marginal spectral density of the observed field $Z^{obs}(\\bs x):=Z(\\bs x) + N(\\bs x)$, denoted $C^{ZZobs}_{\\bs k}$ in Section \\ref{Section: the quad est}. Notice that  Assumption \\ref{Assumption 3} guarantees that $\\bs \\theta(\\bs x)$ is a stationary mean zero Gaussian random field. Therefore\n\\begin{align*}\nE\\big(\\exp(i (\\bs \\theta(\\bs x) - \\bs\\theta(\\bs y))\\cdot \\bs \\eta_{\\bs k})\\big)\n& = \\exp\\!\\big(\\!-\\textstyle\\frac{1}{2}\\bs\\eta^T_{\\bs k} \\bs\\Sigma(\\bs x-\\bs y) \\bs \\eta_{\\bs k}\\big)\n\\end{align*}\nwhere $\\bs\\Sigma(\\bs x-\\bs y)$ is the covariance matrix of $\\bs\\theta(\\bs x) - \\bs\\theta(\\bs y)$.\nThis implies that the marginal spectral density of the observations has the form\n\\begin{align}\nC^{ZZobs}_{\\bs k} = {(2\\pi)}^{d/2}C^{Zm}_{\\bs k} + C^{NN}_{\\bs k} \\label{eq: CZZobs for nonstationary phase}\n\\end{align}\nwhere $C^{Zm}_{\\bs k}$ is the Fourier transform of the marginal auto covariance of $Z(\\bs x)$ and is given by\n\\begin{align*}\nC^{Zm}(\\bs x-\\bs y)= \n\\int  \\exp(i(\\bs x-\\bs y)\\cdot \\bs k)\\exp\\!\\big(\\!-{\\textstyle\\frac{1}{2}}\\bs\\eta^T_{\\bs k} \\bs\\Sigma(\\bs x-\\bs y) \\bs \\eta_{\\bs k}\\big)\\, C_{\\bs k}\\frac{d\\bs k}{(2\\pi)^d}.\n\\end{align*}\nNow the expressions for $C^{ZZobs}_{\\bs k}$, $\\bs C_{\\bs k}^{(1)}$ and $\\bs C_{\\bs k}^{(2)}$ given in (\\ref{eq: C(1), C(2) and C(3) for nonstationary phase})  and (\\ref{eq: CZZobs for nonstationary phase})\ncompletely define the quadratic estimate $\\hat\\phi_{\\bs \\ell}$, the second order bias spectral density $C_{\\bs\\ell}^{\\text{bias }\\hat \\phi}$ and the approximation to estimation variance characterized by $C_{\\bs\\ell}^{\\text{var }\\hat \\phi}$ derived in Section \\ref{Section: the quad est}.\n\n\n% In one dimension when $\\bs\\xi \\equiv 1$ then $\\Sigma(x-y) = 2(C^\\theta(0) - C^\\theta(x-y))$. In higher dimension notice that $E(\\bs \\theta_{p,k} \\bs \\theta_{q,\\ell}) = \\bs\\xi_{p,k}\\bs\\xi_{q,\\ell} E(\\theta_k\\theta_\\ell) = \\bs\\xi_{p,k}\\bs\\xi_{q,\\ell} \\delta_{k+\\ell} C^{\\theta\\theta}_\\ell$. Therefore taking the inverse Fourier transform with respect to $k$ and $\\ell$ one obtains\n% \\begin{align*}\n% E(\\bs \\theta_{p}(x) \\bs \\theta_{q}(y))\n% &=\\iint \\frac{dk\\,d\\ell}{(2\\pi)^d} e^{i\\langle x, k\\rangle+i\\langle y, \\ell\\rangle} E(\\bs \\theta_{p,k} \\bs \\theta_{q,\\ell}) \\\\\n% &=\\iint \\frac{dk\\,d\\ell}{(2\\pi)^d} e^{i\\langle x, k\\rangle+i\\langle y, \\ell\\rangle} \\bs\\xi_{p,k}\\bs\\xi_{q,\\ell} \\delta_{k+\\ell} C^{\\theta\\theta}_\\ell \\\\\n% &=\\int \\frac{dk}{(2\\pi)^d} e^{i\\langle x - y, k\\rangle} \\bs\\xi_{p,k}\\bs\\xi^*_{q,k} C^{\\theta\\theta}_k \\\\\n% &=\\int \\frac{dk}{(2\\pi)^d} e^{i\\langle x - y, k\\rangle} \\bs\\xi_{p,k}\\bs\\xi^*_{q,k} C^{\\theta\\theta}_k \\\\\n% \\end{align*}\n% Therefore letting $\\bs v^\\dagger := (\\bs v^T)^*$ one has that\n% \\begin{align*}\n% \\Sigma(x-y)\n% & = E\\bigl([\\bs \\theta(x) - \\bs\\theta(y)] [\\bs \\theta(x) - \\bs\\theta(y)]^T\\bigr) \\\\\n% & = 2\\int \\frac{dk}{(2\\pi)^d}  \\bigr(\\bs\\xi_{k}\\bs\\xi^\\dagger_{k}\\bigl) C^{\\theta\\theta}_k - 2  E\\bigl(\\bs\\theta(x) \\bs \\theta(y)^T \\bigr) \\\\\n% & = 2\\int \\frac{dk}{(2\\pi)^d}  \\bigl(\\bs\\xi_{k}\\bs\\xi^\\dagger_{k}\\bigl) C^{\\theta\\theta}_k - 2 \\int \\frac{dk}{(2\\pi)^d} e^{i\\langle x - y, k\\rangle} \\bigr(\\bs\\xi_{k}\\bs\\xi^\\dagger_{k}\\bigl) C^{\\theta\\theta}_k \\\\\n% & = 2\\int \\frac{dk}{(2\\pi)^d} \\bigl(1- e^{i\\langle x - y, k\\rangle} \\bigr) \\bigl(\\bs\\xi_{k}\\bs\\xi^\\dagger_{k}\\bigl) C^{\\theta\\theta}_k.\n% \\end{align*}\n\n\n\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Locally attainable spectral densities}\n\\label{section: Locally attainable spectral densities}\n\n\nIn this section we investigate the set of possible local spectral densities, for different values of the nonstationary function $\\bs \\theta(\\bs x)$, under the nonstationary spectral phase random field model of $Z(\\bs x)$. Since the nonstationarity in $Z(\\bs x)$ is exclusively due to local variation of a spectral phase, there is significant restriction on how local spectral densities can vary with $\\bs x$. For example, one can easily see that all the local spectral densities of $Z(\\bs x)$ must have the same integral (so that the pointwise variance of $Z(\\bs x)$ is a constant function of $\\bs x$). In what follows we characterize further restrictions and, in doing so, identify a second source of estimation bias due to the curved nature of the local spectral models. The theory of optimal transport and the $L_2$-Wasserstein metric play an important role in the characterization of local stationary models. We refer the reader to the excellent book \\cite{villani2003topics} for an overview of the subject. \n\n\n\nThe local invariance property of nonstationary spectral phase models implies that the local distribution of $Z(\\bs x)$ is invariant to changes in the magnitude of $\\bs \\theta(\\bs x)$. However, the local behavior of $Z(\\bs x)$ \\textit{is} sensitive to the gradient of $\\bs \\theta(\\bs x)$. In particular, suppose $\\bs\\theta(\\bs x)$ has the form $\\bs A \\bs x + \\bs b$  where $\\bs A\\in \\Bbb R^{d\\times d}$ and $\\bs b \\in \\Bbb R^d$. In this case the covariance function $C^{\\bs \\theta}(\\bs x,\\bs y)$ is still invariant to changes in $\\bs b \\in \\Bbb R^d$ but is sensitive to changes in $\\bs A\\in \\Bbb R^{d\\times d}$. Indeed assuming $\\bs\\theta(\\bs x)=\\bs A \\bs x + \\bs b$ one has\n\\begin{align}\nC^{\\bs \\theta}(\\bs x,\\bs y)\n&=\\int  \\exp\\!\\big(i(\\bs x-\\bs y)\\!\\cdot\\! (\\bs k + \\bs A^T\\bs\\eta_{\\bs k})\\big) \\, C_{\\bs k}\\frac{d\\bs k}{(2\\pi)^d}\n=\\int\\exp\\!\\big(i(\\bs x-\\bs y)\\!\\cdot\\! \\bs\\omega\\big)  \\frac{d\\lambda(\\bs \\omega)}{(2\\pi)^d} \\label{eq: local spectral density for nonstationary phase}\n\\end{align} \nwhere $\\lambda$ is the spectral measure obtained by a change of variables $\\bs\\omega = \\bs k + \\bs A^T\\bs\\eta_{\\bs k}$ (under appropriate measurability assumptions on $\\bs \\eta_{\\bs k}$) Therefore when $\\bs\\theta(\\bs x) = \\bs A \\bs x + \\bs b$ in a local neighborhood about $\\bs x$ the process $Z(\\bs x)$ becomes locally stationary with local spectral measure given by $\\lambda$. \n\n\nThe optimal transport literature uses the notation $\\bs v \\,\\sharp\\, \\lambda(B) := \\lambda(\\bs v^{-1}(B))$ to denote the push forward of a measure $\\lambda$ on $\\Bbb R^d$ under a measurable transformation $\\bs v_{\\bs k}:\\Bbb R^d\\rightarrow \\Bbb R^d$. For our needs it will be useful to extend this definition to spectral measures $\\lambda$ which have a spectral density $C_{\\bs k}$  with respect to Lebesgue measure on $\\Bbb R^d$.  In particular we let $\\bs v_{\\bs k}\\,\\sharp\\, C_{\\bs k}$ denote the push forward of the measure  $C_{\\bs k}d\\bs k$ under the transformation $\\bs v_{\\bs k}$. This notation allows one to easily express the spectral measure $\\lambda$  in (\\ref{eq: local spectral density for nonstationary phase}) as \n\\[\n\\lambda= (\\bs k+ \\bs A^T \\bs\\eta_{\\bs k})\\,\\sharp\\, C_{\\bs k}\n\\]\nand, in doing so, creates a succinct notation for the collection of locally attainable spectral measures defined  as follows.\n\n\n% --------------------------------------------------------\n%  definition\n%---------------------------------------------------------\n\\begin{definition}\nSuppose $Z(\\bs x)$ is a nonstationary spectral phase random field on $\\Bbb R^d$ satisfying Definition \\ref{def: nonstate phase}. \\textit{\\textbf{The family of locally attainable spectral measures for $Z(\\bs x)$}} is defined to be the collection of measures\n\\[\n\\mathscr C^{C,\\bs\\eta}:= \\big\\{ (\\bs k+ \\bs A^T \\bs\\eta_{\\bs k})\\,\\sharp\\, C_{\\bs k}: \\bs A \\in \\Bbb R^{d\\times d}\\big\\}\n\\] \nso that for each $\\lambda \\in \\mathscr C^{C,\\bs\\eta}$ there exists a matrix $\\bs A$ such that when $\\bs \\theta(\\bs x) = \\bs A\\bs x$ the random field $Z(\\bs x)$ becomes stationary with spectral measure $\\lambda$.\n\\end{definition}\n\n\nNotice that, depending on $\\bs \\xi$, there may a restriction on the possible matrices $\\bs A$ which can satisfy $\\bs \\theta(\\bs x) = \\bs A\\bs x$. This will further limit the set of attainable local spectral densities but is not included in the definition of $\\mathscr C^{C,\\bs \\eta}$. The role of $\\bs \\xi$, in terms of modeling $Z(\\bs x)$, is discussed in Section \\ref{section: modeling xi, C and eta} below.\n\n\nThe following claim shows that given any two spectral densities $C_{\\bs k}$ and $\\tilde C_{\\bs k}$ with finite second moments and the same $L_1(\\Bbb R^d)$ integral, there exists a nonstationary spectral phase random field $\nZ(\\bs x)$ which has both $C_{\\bs k}$ and $\\tilde C_{\\bs k}$ as locally attainable spectral densities (i.e. $C_{\\bs k},\\tilde C_{\\bs k}\\in\\mathscr C^{C,\\bs \\eta}$). Moreover, each measure contained in the $L_2$-Wasserstein geodesic connecting $C_{\\bs k}d\\bs k$ to $\\tilde C_{\\bs k}d\\bs k$ is also locally attainable by $Z(\\bs x)$.\n\n% --------------------------------------------------------\n%  claim\n%---------------------------------------------------------\n\\begin{claim}[\\textbf{Any pair of spectral densities with the same integral are attainable}]\n\\label{claim any two spec are attainable}\nLet $d\\geq 1$ be an integer, $t_0 > 0$ be a real number and $C_{\\bs k}$, $\\tilde C_{\\bs k}$ be two spectral densities on $\\Bbb R^d$ with finite second moments such that $\\sigma^2 = \\int_{\\Bbb R^d}  C_{\\bs k}d\\bs k = \\int_{\\Bbb R^d} \\tilde C_{\\bs k}d\\bs k$. Then there exists a vector field $\\bs \\eta_{\\bs k}\\colon \\Bbb R^d \\rightarrow \\Bbb R^d$ which is $L_2(\\Bbb R^d)$ integrable with respect to $C_{\\bs k}d\\bs k$ and  generates a one dimensional curve of spectral measures  $\\{\\lambda^{(t)}: t\\in [0,t_0]\\}$, defined by \n\\begin{align}\n\\lambda^{(t)} := (\\bs k + t\\bs \\eta_{\\bs k})\\,\\sharp\\, C_{\\bs k}\n\\end{align}\nwith endpoints $\\lambda^{(0)}=C_{\\bs k}d\\bs k$ and $\\lambda^{(t_0)}=\\tilde C_{\\bs k}d\\bs k$,\nsuch that  $\\{\\lambda^{(t)}:t\\in[0,t_0] \\}\\subset \\mathscr C^{C,\\bs\\eta}$. In particular there exists a nonstationary spectral phase random field model for which  $C_{\\bs k}$ and $\\tilde C_{\\bs k}$ are both locally attainable.\nMoreover,  $\\{\\lambda^{(t)}: t\\in [0,t_0]\\}$ is a $L_2$-Wasserstein geodesic path within the class of absolutely continuous spectral measures (with total mass $\\sigma^2$ and finite second moments) and each measure $\\lambda^{(t)}$ has a density $C^{(t)}_{\\bs k}$ with respect to Lebesgue measure on $\\Bbb R^d$ which (weakly) satisfies \n\\begin{align}\n\\label{div flow for geo}\n\\partial_t C^{(t)}_{\\bs k} +\\text{\\rm div}(\\bs \\eta^{(t)}_{\\bs k}C^{(t)}_{\\bs k}) = 0\n\\end{align}\nfor all $t\\in [0,t_0]$ where $\\bs \\eta^{(t)}_{\\bs k}:=\\bs \\eta_{T_t^{-1}(\\bs k)}$ and $T_t(\\bs k):= \\bs k + t\\bs \\eta_{\\bs k}$.\n\\end{claim}\n% --------------------------------------------------------\n%  proof\n%---------------------------------------------------------\n\\begin{proof}\nBy standard optimal transport theory (see \\cite{villani2003topics} for example) the assumptions on $C_{\\bs k}$ and $\\tilde C_{\\bs k}$ guarantee the existence of a convex function $\\psi_{\\bs k}:\\Bbb R^d \\rightarrow \\Bbb R$ such that $\\nabla \\psi_{\\bs k}$ is the optimal transport from $C_{\\bs k}d\\bs k$ to $\\tilde C_{\\bs k}d\\bs k$.  Let $\\bs \\eta_{\\bs k}:= \\frac{1}{t_0}(\\nabla \\psi_{\\bs k}-\\bs k)$ so that\n\\begin{align}\n\\label{geo eq number 1}\n\\lambda^{(t)}:=(\\bs k + t\\bs\\eta_{\\bs k})\\,\\sharp\\, C_{\\bs k} = \\big((1-\\textstyle\\frac{t}{t_0})\\bs k + \\textstyle\\frac{t}{t_0}\\nabla\\psi_{\\bs k}\\big)\\,\\sharp\\, C_{\\bs k}. \n\\end{align}\nThe particular form of the right hand side of (\\ref{geo eq number 1})  implies each measure $\\lambda^{(t)}$ has a density $C_{\\bs k}^{(t)}$ with respect to Lebesgue measure and the path of measures $\\{\\lambda^{(t)}\\colon t\\in[0,t_0] \\}$ forms an $L_2$-Wasserstein geodesic with endpoints $C_{\\bs k}d\\bs k$ and $\\tilde C_{\\bs k}d\\bs k$ at $t=0$ and $t=t_0$ respectively (see Proposition 5.9 in \\cite{villani2003topics}). Moreover, $C^{(t)}_{\\bs k}$ weakly satisfies (\\ref{div flow for geo}) by Theorem 5.34 of \\cite{villani2003topics} and the fact that $C^{(t)}_{\\bs k} = T_t\\,\\sharp\\, C^{(0)}_{\\bs k}$ where $\\partial_t T_t(\\bs k) = \\bs \\eta_{\\bs k}$.\nBy  setting $\\bs A=t\\bs I_d$ in (\\ref{eq: local spectral density for nonstationary phase}) one has\n\\[\n\\int  \\exp\\!\\big(i(\\bs x-\\bs y)\\!\\cdot\\! (\\bs k + t\\bs\\eta_{\\bs k})\\big)\\, C_{\\bs k}\\frac{d\\bs k}{(2\\pi)^d} \n=\\int \\exp\\!\\big(i(\\bs x-\\bs y)\\!\\cdot\\! \\bs\\omega\\big)\\,  C^{(t)}_{\\bs \\omega}\\frac{d\\bs \\omega}{(2\\pi)^d}\n\\]\nwhich implies that for each $t\\in[0,t_0]$ the measure $\\lambda^{(t)}$ is a locally attainable spectral measure.\n\\end{proof}\n\nIsotropic spectral densities are an important special case for many statistical applications. The following claim allows considerable simplification for the construction of the vector field $\\bs \\eta_{\\bs k}$ guaranteed by Claim \\ref{claim any two spec are attainable}.\n\n% --------------------------------------------------------\n%  claim\n%---------------------------------------------------------\n\\begin{claim}[\\textbf{Special case for isotropic spectral densities}]\n\\label{claim: isotropic spectral densities}\nLet $d\\geq 1$ be an integer, $t_0 > 0$ be a real number and $C_{|\\bs k|}$, $\\tilde C_{|\\bs k|}$ be two isotropic spectral densities on $\\Bbb R^d$ with finite second moments and total mass $\\sigma^2$. Define\n\\begin{align}\n\\bs \\eta_{\\bs k}:= \\frac{1}{t_0}\\Big(\\tilde F^{-1}\\circ F(|\\bs k|)\\frac{\\bs k}{|\\bs k|}-\\bs k\\Big)\n\\end{align} \n where $F(r) := \\frac{2\\pi^{d/2}}{\\sigma^2\\Gamma(d/2)}\\int_0^r \\xi^{d-1}C_\\xi d\\xi$ and $\\tilde F(r) := \\frac{2\\pi^{d/2}}{\\sigma^2\\Gamma(d/2)}\\int_0^r \\xi^{d-1}\\tilde C_\\xi d\\xi$. Then for all $t\\in[0,t_0]$, $\\bs \\eta_{\\bs k}$ generates the spectral measures $\\lambda^{(t)}:= (\\bs k + t\\bs \\eta_{\\bs k})\\,\\sharp\\, C_{|\\bs k|} $ defined in Claim \\ref{claim any two spec are attainable}. In particular, $\\{\\lambda^{(t)} \\colon t\\in[0,t_0]\\}$ forms a $L_2$-Wasserstein geodesic path of locally attainable spectral densities in $\\mathscr C^{C,\\bs \\eta}$, with endpoints $\\lambda^{(0)}=C_{|\\bs k|}d\\bs k$ and $\\lambda^{(t_0)}=\\tilde C_{|\\bs k|}d\\bs k$, where\n$\\bs k + t\\bs \\eta_{\\bs k}$ is the optimal transport from $\\lambda^{(0)}$ to $\\lambda^{(t)}$.\n\\end{claim}\n\n% --------------------------------------------------------\n%  proof\n%---------------------------------------------------------\n\\begin{proof}\nBy the proof of Claim \\ref{claim any two spec are attainable} it will be sufficient to show that $\\tilde F^{-1}\\circ F(|\\bs k|)\\frac{\\bs k}{|\\bs k|}$ is the optimal transport from $C_{|\\bs k|}$ to $\\tilde C_{|\\bs k|}$.\nLet $\\bs K$ and $\\tilde {\\bs K}$ be random vectors in $\\Bbb R^d$ with densities $C_{|\\bs k|}/\\sigma^2$ and $\\tilde C_{|\\bs k|}/\\sigma^2$, respectively. By the distributional rotational symmetry of $\\bs K$ there exists a convex $\\psi(r):\\Bbb R^+ \\rightarrow \\Bbb R$ such that $\\nabla (\\psi(|\\bs k|))=\\psi^\\prime(|\\bs k|)\\frac{\\bs k}{|\\bs k|}$ is the optimal transport from $\\mathscr L\\bs K$ to $\\mathscr L\\tilde{\\bs K}$ (where $\\mathscr L\\bs K$ and $\\mathscr L\\tilde{\\bs K}$ denotes the law, i.e. probability distribution, of $\\bs K$). Also notice that $\\psi^\\prime(r)$ is the optimal transport from $\\mathscr L |\\bs K|$ to  $\\mathscr L|\\tilde{\\bs K}|$ since $\\psi(r)$ is convex and\n\\begin{align*}\nP(\\psi^\\prime(|\\bs K|)\\leq r) = P\\big(\\big|\\psi^\\prime(|\\bs K|)\\textstyle\\frac{\\bs K}{|\\bs K|}\\big|\\leq r\\big) = P(|\\tilde{\\bs K}|\\leq r).\n\\end{align*}\nThe optimal transport between two univariate random variables (see \\cite{villani2003topics}) is given by the composition of the quantile function (of the target measure) and the cumulative distribution function (of the base measure). Therefore the optimal transport from $\\mathscr L|\\bs K|$ to $\\mathscr L|\\tilde{\\bs K}|$ is given by $\\tilde F^{-1}\\circ F(r)$ where $F(r)=\\frac{2\\pi^{d/2}}{\\sigma^2\\Gamma(d/2)}\\int_0^r \\xi^{d-1}C_\\xi d\\xi$ and $\\tilde F(r)=\\frac{2\\pi^{d/2}}{\\sigma^2\\Gamma(d/2)}\\int_0^r \\xi^{d-1}\\tilde C_\\xi d\\xi$ are the cumulative distribution functions of $|\\bs K|$ and $|\\tilde{\\bs K}|$, respectively. By the uniqueness of optimal transports one has $\\psi^\\prime(r)=\\tilde F^{-1}\\circ F(r)$ and therefore \n\\[\n\\nabla (\\psi(|\\bs k|))=\\psi^\\prime(|\\bs k|)\\frac{\\bs k}{|\\bs k|} = \\tilde F^{-1}\\circ F(|\\bs k|)\\frac{\\bs k}{|\\bs k|}\n\\]\nis the optimal transport from $\\mathscr L\\bs K$ to $\\mathscr L\\tilde{\\bs K}$,\nas was to be shown.\n\\end{proof}\n\nAs a corollary to the above theorem one can obtain partial closed form solutions for $\\bs \\eta_{\\bs k}$ when the spectral densities $C_{\\bs k}$ and $\\tilde C_{\\bs k}$ are both Mat\\'ern spectral densities with the same integral and with finite second moments. The form of $\\bs \\eta_{\\bs k}$, in this case, can be computed using the incomplete beta function and the quantiles of beta random variables (which is not technically given in closed form but for which simple Newton method characterizations are guaranteed to converge, see \\cite{giner2014monotonically}).\n\n% --------------------------------------------------------\n%  corollary\n%---------------------------------------------------------\n\\begin{corollary}[\\textbf{Optimal transports between Mat\\'ern spectral densities}]\n\\label{corollary: Optimal transports between Matern spectral densities}\nLet $d\\geq 1$ be an integer and $t_0,\\nu,\\tilde \\nu, \\rho, \\tilde \\rho,\\sigma^2 > 0$ be real numbers such that $\\nu,\\tilde \\nu >1$.\nIf \n\\begin{align}\nC_{|\\bs k|} &= \\sigma^22^{d}\\pi^{d/2}\\frac{\\Gamma(\\nu + d/2)}{\\Gamma(\\nu)}\\left(\\frac{4\\nu}{\\rho^2}\\right)^{\\nu}\\left(\\frac{4\\nu}{\\rho^2}+|\\bs k|^2\\right)^{-\\nu-d/2} \\label{eq: Ck matern}\\\\\n\\tilde C_{|\\bs k|} &= \\sigma^2 2^{d}\\pi^{d/2}\\frac{\\Gamma(\\tilde\\nu + d/2)}{\\Gamma(\\tilde\\nu)}\\left(\\frac{4\\tilde\\nu}{\\tilde\\rho^2}\\right)^{\\tilde\\nu}\\left(\\frac{4\\tilde\\nu}{\\tilde\\rho^2}+|\\bs k|^2\\right)^{-\\tilde\\nu-d/2}\\label{eq: tildeCk matern}\n\\end{align} \n then $F$ and $\\tilde F^{-1}$, defined in Claim \\ref{claim: isotropic spectral densities}, are given by\n\\begin{align}\n\\label{F0 for matern}\nF(r) &= I_{r^2/(4\\nu / \\rho^2 + r^2)}(d/2, \\nu) \\\\\n\\tilde F^{-1}(u) &= \\left(\\frac{4\\tilde\\nu}{\\tilde\\rho^2}\\right)^{1/2}\\left(\\frac{1}{Q_u(d/2,\\tilde\\nu)} -1 \\right)^{-1/2} \n\\label{Ft0inv for matern}\n\\end{align}\nwhere $I_x(p,q)$ is the incomplete beta function and $Q_u(p,q)$ is the quantile function for a univariate $\\text{Beta}(p,q)$ random variable evaluated at $u\\in (0,1)$.\n\\end{corollary}\n% --------------------------------------------------------\n%  proof\n%---------------------------------------------------------\n\\begin{proof}\nFirst notice that $ (2\\pi)^d\\sigma^2 =\\int_{\\Bbb R^d} C_{|\\bs k|}d\\bs k =  \\int_{\\Bbb R^d} \\tilde C_{|\\bs k|}d\\bs k$ and the constraints $\\nu, \\tilde \\nu>1$ are sufficient to ensure  $C_{|\\bs k|}$ and $\\tilde C_{|\\bs k|}$ have finite second moments. Therefore Claim \\ref{claim: isotropic spectral densities} applies. For any $\\nu,a>0$, the change of variables $x= y^2/(a+y^2)$ gives\n\\begin{align*}\n\\int_0^r \\frac{y^{d-1}}{(a+y^2)^{\\nu+d/2}} dy = \\frac{1}{2a^\\nu}\\int_0^{\\frac{r^2}{a+r^2}} (1-x)^{\\nu-1}x^{d/2-1}dx = \\frac{B(d/2,\\nu)}{2a^\\nu}I_{r^2/(a + r^2)}(d/2,\\nu).\n\\end{align*}\nTherefore $F(r) := \\frac{2\\pi^{d/2}}{\\sigma^2(2\\pi)^d\\Gamma(d/2)}\\int_0^r \\xi^{d-1}C_\\xi d\\xi = I_{r^2/(4\\nu / \\rho^2 + r^2)}(d/2,\\nu) $\nand similarly for $\\tilde F(r)$. \nThis immediately gives (\\ref{F0 for matern}) an (\\ref{Ft0inv for matern}).\n\\end{proof}\n\nThe Wasserstein structure of the locally attainable spectral models gives a convenient geometric picture for  potential difficulties when estimating local spectra in the nonstationary phase model.\nFor example, the space of probability distributions (with finite second moments) has positive curvature (in the sense of Aleksandrov's notion of metric curvature) under the $L_2$-Wasserstein metric \\cite{ambrosio2008gradient}. \nA less precise mathematical illustration of this is the fact is that the two locally attainable spectra, $(\\bs k+ \\bs A^T \\bs\\eta_{\\bs k})\\,\\sharp\\, C_{\\bs k}$ and $(\\bs k- \\bs A^T \\bs\\eta_{\\bs k})\\,\\sharp\\, C_{\\bs k}$, become asymptotically indistinguishable as the entries $\\bs A$ become arbitrarily large. Indeed, the probability distributions of $\\bs K + \\bs A^T\\bs\\eta_{\\bs K}$ and $\\bs K - \\bs A^T\\bs\\eta_{\\bs K}$ are similar when $\\bs K$ is a random vector with unnormalized density $C_{\\bs k}$ and the magnitude of the entries of $\\bs A$ are large (since $\\bs\\eta_{\\bs k}$ has odd symmetry and $C_{\\bs k}$ has even symmetric). One implication of this asymptotic non-identifiability is that estimates of the local spectra can break down when $\\bs \\theta(\\bs x)$ has large local linear fluctuations (i.e. when the entries of $\\bs A$ are large) so that the two local models $\\bs \\theta(\\bs x)=\\bs A\\bs x + \\bs b$ and $\\bs \\theta(\\bs x)=-\\bs A\\bs x + \\bs b$ are difficult to distinguish from the data.\n\n\n\nA possible numerical tool for probing this breakdown is to analyze the so called \\textbf{\\textit{cut locus}} associated with $L_2$-Wasserstein geodesics. Informally, the cut locus quantifies the maximal extent of geodesic paths emanating from some point. The cut locus of the geodesics emanating from $C_{\\bs k}d\\bs k$ can serve as a proxy for when curvature effects will corrupt local estimation of $\\bs\\theta(\\bs x)$ due to the similarity between the two local spectra characterized by the local linear models $\\bs \\theta(\\bs x)=\\bs A\\bs x + \\bs b$ and $\\bs \\theta(\\bs x)=-\\bs A\\bs x + \\bs b$.  If the cut locus starting at $C_{\\bs k}d\\bs k$ is far from $C_{\\bs k}d\\bs k$ this implies the geodesic paths are long and the entries of $\\bs A$ need to be much larger for curvature difficulties to arise.  In particular, fix $\\bs A$ and consider the  locally attainable models $(\\bs k+ c\\bs A^T \\bs\\eta_{\\bs k})\\,\\sharp\\, C_{\\bs k}$ indexed by $c\\in \\Bbb R$. If there exists a maximal $c_0>0$ such that $\\{(\\bs k+ c\\bs A^T \\bs\\eta_{\\bs k})\\,\\sharp\\, C_{\\bs k}\\colon c\\in[0,c_0]\\}$ and $\\{(\\bs k+ c\\bs A^T \\bs\\eta_{\\bs k})\\,\\sharp\\, C_{\\bs k}\\colon c\\in[-c_0,0]\\}$ are both $L_2$-Wasserstein geodesic, then nonstationary local linear models of the form $\\theta(\\bs x) = \\pm c\\bs A\\bs x + \\bs b$ are less exposed to curvature effects when $|c|\\ll c_0$. \nClaim \\ref{claim: cut locus}, below, allows one to numerically compute the maximal such cutoff $c_0$ which characterizes, what we call, the {\\it symmetric two sided cut locus}. \n\n\n\n% --------------------------------------------------------\n%  claim\n%---------------------------------------------------------\n\\begin{claim}\n\\label{claim: cut locus}\nLet $d\\geq 1$ be an integer, $c_0 > 0$ be a real number, $\\bs A\\in \\Bbb R^d$, $C_{\\bs k}$ is a spectral density on $\\Bbb R^d$ with finite second moments and $\\bs \\eta_{\\bs k}\\colon \\Bbb R^d \\rightarrow \\Bbb R^d$ which is $L_2(\\Bbb R^d)$ integrable with respect to $C_{\\bs k}d\\bs k$.\nSuppose both \n$\\bs k - c_0\\bs A^T\\bs \\eta_{\\bs k}$ and $\\bs k + c_0\\bs A^T\\bs \\eta_{\\bs k}$\nare $C^1$ diffeomorphisms which are gradients of convex functions. Then \n$\\{(\\bs k - c\\bs A^T\\bs \\eta_{\\bs k})\\,\\sharp\\,C_{\\bs k}\\colon c\\in[0,c_0]\\}$ and $\\{(\\bs k + c\\bs A^T\\bs \\eta_{\\bs k})\\,\\sharp\\,C_{\\bs k}\\colon c\\in[0,c_0]\\}$ are paths of absolutely continuous measures which are also $L_2$-Wasserstein geodesics. \n\\end{claim}\n% --------------------------------------------------------\n%  proof\n%---------------------------------------------------------\n\\begin{proof}\nLet $\\phi_{\\bs k}$ and $\\psi_{\\bs k}$ be convex functions defined on $\\Bbb R^d$ such that $\\nabla \\phi_{\\bs k}=\\bs k - c_0\\bs A^T\\bs \\eta_{\\bs k}$ and $\\nabla \\psi_{\\bs k}=\\bs k + c_0\\bs A^T\\bs \\eta_{\\bs k}$. By the diffeomorphic assumption on $\\bs k - c_0\\bs A^T\\bs \\eta_{\\bs k}$ and $\\bs k + c_0\\bs A^T\\bs \\eta_{\\bs k}$ there exists two spectral densities $C^{(-c_0)}_{\\bs k}$ and $C^{(c_0)}_{\\bs k}$ which satisfy \n\\begin{align*}\nC^{(-c_0)}_{\\bs k}d\\bs k = (\\bs k - c_0\\bs A^T\\bs \\eta_{\\bs k})\\,\\sharp\\, C_{\\bs k} \\\\\nC^{(c_0)}_{\\bs k}d\\bs k  = (\\bs k + c_0\\bs A^T\\bs \\eta_{\\bs k})\\,\\sharp\\, C_{\\bs k} .\n\\end{align*} \nNow for any $c\\in[0,c_0]$ one has\n\\begin{align}\n\\bs k - c\\bs A^T\\bs\\eta_{\\bs k} &= \\big(1-\\textstyle\\frac{c}{c_0}\\big)\\bs k + \\textstyle\\frac{c}{c_0}\\nabla\\phi_{\\bs k}\\label{cutlocus eq 1} \\\\\n\\bs k + c\\bs A^T\\bs\\eta_{\\bs k} &= \\big(1-\\textstyle\\frac{c}{c_0}\\big)\\bs k + \\textstyle\\frac{c}{c_0}\\nabla\\psi_{\\bs k}\\label{cutlocus eq 2}.\n\\end{align} \nThe explicit form of the right hand side of (\\ref{cutlocus eq 1}) and (\\ref{cutlocus eq 2}) imply $\\{ (\\bs k - c\\bs A^T\\bs \\eta_{\\bs k})\\,\\sharp\\, C_{\\bs k} :c\\in[0,c_0]\\}$  and  $\\{ (\\bs k + c\\bs A^T\\bs \\eta_{\\bs k})\\,\\sharp\\, C_{\\bs k} :c\\in[0,c_0]\\}$  are $L_2$-Wasserstein geodesics of absolutely continuous measures, connecting $C^{(-c_0)}_{\\bs k}d\\bs k$ to $C_{\\bs k}d\\bs k $ and  $C_{\\bs k}d\\bs k$ to $C^{(c_0)}_{\\bs k} d\\bs k$ respectively (by Proposition 5.9 in \\cite{villani2003topics}).\n\\end{proof}\n\n\n\n% --------------------------------------------------------\n%  subsection\n%---------------------------------------------------------\n\\subsection{Modeling $\\bs \\xi_{\\bs k}, C_{\\bs k}$ and $\\bs\\eta_{\\bs k}$}\n\\label{section: modeling xi, C and eta}\n\nIn this section we give some informal guidance for specifying $\\bs \\xi_{\\bs k}, C_{\\bs k}$ and $\\bs\\eta_{\\bs k}$ in the nonstationary spectral phase model (see Definition \\ref{def: nonstate phase}). Since the quadratic estimate is  adept at detecting small departures from stationarity---partly due to the accuracy of the variance calculations and the speed at which the quadratic estimate can be simulated under a null stationary model---we focus on the situation where the statistician wants to estimate or detect nonstationary extensions of a stationary model. Further details of this approach can be found in the simulation sections \\ref{section: nonstat example d=1} and \\ref{section: nonstat example d=2}. \n\n\n\\paragraph{Modeling $C_{\\bs k}$ and $\\bs\\eta_{\\bs k}$.} In sections \\ref{section: nonstat example d=1} and \\ref{section: nonstat example d=2}  we model $\\bs\\eta_{\\bs k}$ implicitly by specifying two spectral densities $C_{\\bs k}, \\tilde C_{\\bs k}$ and require that they both be locally attainable in the nonstationary random field model (note: $C_{\\bs k}$ and $\\tilde C_{\\bs k}$ must have the same $L_1(\\Bbb R^d)$ integral). In other words we construct a vector field $\\bs \\eta_{\\bs k}$ from $C_{\\bs k}$ and $\\tilde C_{\\bs k}$ by requiring  $\\tilde C_{\\bs k}\\in \\mathscr C^{C,\\bs \\eta}$. The results of Section \\ref{section: Locally attainable spectral densities} show this is possible by setting \n\\begin{align}\n\\label{eq: modeling eta}\n\\bs \\eta_{\\bs k}:=  \\frac{1}{t_0}(\\nabla \\psi_{\\bs k}-\\bs k)\n\\end{align}\n where  $\\nabla \\psi_{\\bs k}$ is the optimal transport from $C_{\\bs k}$ to $\\tilde C_{\\bs k}$ and $t_0>0$ is determined  by the  desired physical units of $\\bs \\theta(\\bs x)$ or is set to balance the bias and variance of the quadratic estimate (more on this in the next paragraph). Corollary \\ref{corollary: Optimal transports between Matern spectral densities} seems particularity useful for this approach in that $C_{\\bs k}$ can be determined by an overall Mat\\'ern fit and $\\tilde C_{\\bs k}$ can be defined by perturbing the Mat\\'ern  parameters in a direction of interest. For example, consider the case where one is interested in detecting nonstationarity arising from spatial variation in the Mat\\'ern smoothness parameter $\\nu$.  Using the notation given in Corollary \\ref{corollary: Optimal transports between Matern spectral densities} one could estimate $\\sigma^2$, $\\rho$ and  $\\nu$ (the parameters of $C_{\\bs k}$) by an overall stationary fit, then define  $\\tilde\\nu := \\nu + \\epsilon$ and $\\tilde \\rho := \\rho$ (the parameters of $\\tilde C_{\\bs k}$) for some $\\epsilon\\in\\Bbb R$.  \n\nGenerally larger values of $t_0$ or smaller values of $\\epsilon$ will increase estimation variance and decrease estimation bias. We do not yet have a coherent story for the precise nature the dependence of bias and variance as a function of $t_0$ and $\\epsilon$. However,  the cut locus of the $L_2$-Wasserstein geodesics emanating from $C_{\\bs k}$  (discussed at the end of Section \\ref{section: Locally attainable spectral densities}) can be a useful tool for probing this dependence. For example, given $t_0$ and $\\epsilon$ one can compute the maximal $c_0$ which satisfies the antecedent of Claim \\ref{claim: cut locus}. This maximal $c_0$ effectively characterizes the \\textit{symmetric two-sided cut locus} (c.f. Claim \\ref{claim: cut locus}) and heuristically serves to characterize an upper bound on the magnitude of the entries of $\\bs A$, beyond which bias is likely to dominate. \nThis will be explored in more detail in Section \\ref{section: nonstat example d=1} as a diagnostic tool for determining values of  $t_0$ and $\\epsilon$ that result in  large quadratic estimation bias. \n\n\n\n\n\\paragraph{Modeling $\\bs \\xi_{\\bs k}$.} In some cases the spectral multiplier $\\bs \\xi_{\\bs k}$ will be constrained by the physics of a particular application. An example of such a constraint is that $\\bs \\theta(\\bs x)$ be required to be curl free or divergence free. Indeed, a curl free constraint is enforced in the gravitational lensing problem  by setting $\\bs \\xi_{\\bs k}=i\\bs k$. In the absence of such constraints one can potentially use $\\bs \\xi_{\\bs k}$ to restrict the possible matrices $\\bs A$ which parameterize  the locally attainable spectral models  $\\mathscr C^{C,\\bs\\eta}= \\big\\{ (\\bs k+ \\bs A^T \\bs\\eta_{\\bs k})\\,\\sharp\\, C_{\\bs k}: \\bs A \\in \\Bbb R^{d\\times d}\\big\\}$.   If $\\xi_{\\bs k}:= i\\bs k$, for example, then $\\bs A$ must be of the form $(\\partial_{\\bs x_p}\\partial_{\\bs x_q}\\phi(\\bs x))_{p,q=1}^d = \\bs U\\bs \\Lambda \\bs U^T$ where $\\bs U$ is a rotation matrix and $\\bs \\Lambda$ is a diagonal matrix with real entries. \n\n\n% --------------------------------------------------------\n%  subsection\n%---------------------------------------------------------\n\\subsection{Nonstationary phase example $d=1$}\n\n\\label{section: nonstat example d=1}\n\n\n\n\n\n\nIn this section we present a simulation example to illustrate the quadratic estimate of $\\bs \\theta(\\bs x)$, or equivalently the potential $\\phi(\\bs x)$, when observing a single realization of a nonstationary spectral phase random field $Z(\\bs x)$ in dimension $d=1$ (c.f. Definition \\ref{def: nonstate phase}).  According to our notational conventions, vector quantities such as  $\\bs x, \\bs k, \\bs \\xi_{\\bs k},  \\bs\\eta_{\\bs k}, \\bs \\theta(\\bs x)$ are replaced with non-bold scalar notation $x, k, \\xi_{k},  \\eta_{k}, \\theta(x)$ to indicate scalar quantities for $d=1$. There are multiple points we hope to convey with this example. The first is that the quadratic estimate $\\hat\\phi_\\ell$, constructed to detect a spatially varying smoothness parameter, is fast and accurate. The second point is that $C^{\\text{var\\,}\\hat\\phi}_{\\ell}$ and $C^{\\text{bias\\,}\\hat\\phi}_{\\ell}$  accurately quantify the empirical variance and bias of $\\hat\\phi_\\ell$. A third point is that the fast approximation to $C^{\\text{bias\\,}\\hat\\phi}_{\\ell}$, discussed in the last paragraph of Section \\ref{SubSection: bias}, is accurate over a wide range of wave numbers. Finally we illustrate qualitative features of the estimation bias which results when $\\theta^\\prime(x)$ is large enough to exceed the symmetric two-sided cut locus discussed in Section \\ref{section: modeling xi, C and eta} (c.f. Claim \\ref{claim: cut locus}).\n\n\n\n\n\nFollowing the modeling approach outlined in Section \\ref{section: modeling xi, C and eta} we first define $C_k$ to be the  Mat\\'ern spectral density given in (\\ref{eq: Ck matern}) with parameters $(\\nu, \\rho, \\sigma^2):=(2, 0.05, 1)$. Now  $\\eta_k$ is defined implicitly by specifying a second spectral density $\\tilde C_k$ that is required to be locally attainable within the same nonstationary phase model for $Z(x)$. $\\tilde C_k$ is defined to be the  Mat\\'ern spectral density given in (\\ref{eq: tildeCk matern})  with parameters $(\\tilde \\nu, \\tilde\\rho, \\sigma^2):=(2.1, 0.05, 1)$. The variance parameter $\\sigma^2$ is the same for both $C_k$ and  $\\tilde C_k$ as per the necessary requirement for locally attainable spectral densities. Notice that the only difference between the two Mat\\'ern models is the fractional smoothness parameter which is set to model nonstationarity in the local smoothness in $Z(x)$.  The parameter $t_0$ used in (\\ref{eq: modeling eta}) to determine $\\eta_k$ is set to $1.5$ for Figure \\ref{Figure 2 zx and var} and $1.5/7$ for Figure \\ref{Figure 2 zx and var, extra bias}. \n\n\n\nA single ground truth potential $\\phi(x)$ is used throughout this section and was simulated from a mean zero stationary Gaussian process with Mat\\'ern parameters $(\\nu, \\rho, \\sigma^2):=(5, 1.5, 15^2 / (2\\pi)^4)$. The spectral multiplier $\\xi_k$ is set to $ik$ so that $\\theta(x) = \\phi^\\prime(x) $.  The derivative $\\theta^\\prime(x)$, in particular $\\phi^{\\prime\\prime}(x)$, is shown in blue in the middle plot of figures \\ref{Figure 2 zx and var} and \\ref{Figure 2 zx and var, extra bias}.  \nThe quantities $C^{(0)}_\\ell, C^{(1)}_\\ell, C^{(2)}_\\ell$ and $C^{ZZobs}_\\ell$ used to generate  $\\hat\\phi_\\ell$, $C^{\\text{var\\,}\\hat\\phi}_{\\ell}$ and $C^{\\text{bias\\,}\\hat\\phi}_{\\ell}$ are determined by (\\ref{eq: C(1), C(2) and C(3) for nonstationary phase}) and (\\ref{eq: CZZobs for nonstationary phase}). Finally, to avoid potential aliasing issues in the simulated data $Z^{obs}(x)$, the quadratic estimate is set to ignore $10\\%$ of Fourier coefficients which are nearest the Nyquist limit by truncating the weights corresponding to those frequency pairs.\n\n\n\n\n\n\n\\begin{figure}\n\\includegraphics[height=15cm]{figure2.pdf}%\n\\caption{ This figure shows a simulation of a nonstationary spectral phase random field $Z(x)$ (\\textbf{top}), the quadratic estimate of  $\\theta^\\prime(x)$ (\\textbf{middle}) and the spectral characterizations of estimation variance (\\textbf{bottom-left}) and estimation bias (\\textbf{bottom-right}). The details of the simulation are given in Section \\ref{section: nonstat example d=1}. In the \\textbf{middle plot} the \\textbf{blue line} shows the value of $\\theta^\\prime(x)=\\phi^{\\prime\\prime}(x)$ which characterizes the nonstationarity in $Z(x)$ through Definition \\ref{def: nonstate phase}, the  \\textbf{grey lines} show different quadratic estimates $\\hat\\theta^\\prime(x)$ each one applied to an independent realizations of $Z(x)$ with the same $\\theta(x)$ and the \\textbf{dashed line} shows the empirical average of $\\hat\\theta^\\prime(x)$ over 100 such realizations. In the \\textbf{bottom-left plot}\nThe main purpose of this simulation is intended to illustrate the accuracy of the quadratic estimate and the ability of $C^{\\text{var\\,}\\hat\\phi}_{\\bs \\ell}$ and $C^{\\text{bias\\,}\\hat\\phi}_{\\bs \\ell}$ to approximate the empirical variance and bias of the estimate. A secondary goal of this figure is to also show that the fast approximation to $C^{\\text{bias\\,}\\hat\\phi}_{\\bs \\ell}$ is very accurate over a wide range of small wave numbers.}\n\\label{Figure 2 zx and var}\n\\end{figure}\n\n\n\n\nThe process $Z(x)$ in this section is defined on $[-5,5)$ with periodic boundary conditions. \nThe observed process $Z^{obs}(x)$ is simulated without additive noise on $10^4$ evenly spaced observation locations in $[-5,5)$.  A simple discrete Riemann sum approximation, at each observed $x$, was used to approximate to the integral (\\ref{eq: nonstate phase}) to generate the simulation of $Z^{obs}(x)$. In general, this type of approximation will result in aliasing errors. Generating a distributionally exact simulation of $Z(x)$, without any approximation, appears to be an open problem.   It is not yet clear what impact the aliasing errors, present in our simulation, have on the quadratic estimate. However, we found little empirical difference in the performance of the quadratic estimate when reducing the aliasing errors by increasing the frequency upper limit used for the Riemann sum approximation. \n\n\n\n\n\nFigure \\ref{Figure 2 zx and var} shows the results of our simulation when $t_0$ is set to $1.5$. The \\textbf{top plot} shows a simulation of the nonstationary phase process $Z(x)$. The \\textbf{blue line} in the \\textbf{middle plot} shows $\\theta^\\prime(x)$ along with $5$ realizations of the quadratic estimate $\\hat\\theta^\\prime(x)$, shown in \\textbf{grey}, each one applied to an independent realization of $Z(x)$ with the same $\\phi(x)$ . The \\textbf{dashed line} in the \\textbf{middle plot} shows an empirical estimate to $E(\\hat\\theta^\\prime(x)|\\phi)$ based on averaging the quadratic estimate applied to $100$ independent realizations $Z(x)$ all simulated with the same nonstationary potential $\\phi(x)$. On average, computing these $100$ quadratic estimates (each based on $10^4$ observations) took $0.008$ seconds on a 2013 MacBook Pro with a 2.3 GHz Intel Core i7 CPU. This illustrates that the quadratic estimate can be computed extremely fast on a dense set of observations. Notice also the estimate is accurate with respect to both variance and bias. Indeed, by comparing signal spectral density $\\ell^2 C_\\ell^{\\phi\\phi}$ (\\textbf{dotted black line} in \\textbf{both bottom plots})  with  $\\ell^2 C^{\\text{var\\,}\\hat\\phi}_{\\ell}$ and $\\ell^2 C^{\\text{bias\\,}\\hat\\phi}_{\\ell}$  (\\textbf{green and red lines} respectively) one can see that the signal-to-noise ratio for estimation accuracy per-frequency is significantly greater than $1$ for a large range of wavenumbers. The \\textbf{bottom two plots} in Figure \\ref{Figure 2 zx and var} show the accuracy of the analytic approximations $\\ell^2 C^{\\text{var\\,}\\hat\\phi}_{\\ell}$ and  $\\ell^2 C^{\\text{bias\\,}\\hat\\phi}_{\\ell}$ for quantifying the empirical variance and bias (\\textbf{green and red dots} respectively) computed from the $100$ realizations of $\\hat\\theta^\\prime(x)$. The computation of $C^{\\text{var\\,}\\hat\\phi}_{\\ell}$ took $0.098$ seconds. The fast approximation to  $\\ell^2 C^{\\text{bias\\,}\\hat\\phi}_{\\ell}$ is plotted with the \\textbf{dashed blue line} in the \\textbf{bottom right plot}. This approximation can be seen to be very accurate, nearly indistinguishable from the \\textbf{red line}, and took only $0.308$ seconds to compute (compared to $99.44$ seconds for computing  $C^{\\text{bias\\,}\\hat\\phi}_{\\ell}$ directly).\n\n\nIn Figure \\ref{Figure 2 zx and var, extra bias} we show another simulation which is similar the one shown in Figure \\ref{Figure 2 zx and var} with the exception that $t_0$ is reduced from $1.5$ to $1.5/7$. This has the effect of shrinking the two-sided cut locus (discussed in Section \\ref{section: modeling xi, C and eta}). This is  equivalent to scaling $\\phi(x)$ by a factor of $7$ which has the effect of dramatically increasing the bias in the quadratic estimate. Indeed, the main point of Figure \\ref{Figure 2 zx and var, extra bias} is to illustrate the qualitative features of the quadratic estimate bias when $\\phi(x)$ is too large for the linear approximation in (\\ref{first order term, intro}) to hold. \nIndeed, when the magnitude of the true $\\theta^\\prime(x)$ exceeds the two-sided cut locus, the estimate $\\hat\\theta^\\prime(x)$ transitions from a low bias estimate to a bias dominated one as seen in the \\textbf{middle plot}. This is presumably due to the ability of the two-sided cut locus to identify when the geodesic path of local spectral densities begins to curl in on itself, creating an ill-posed inversion from observed local spectral density to estimate $\\phi(x)$.\n \n\n\n\\begin{figure}\n\\includegraphics[height=15cm]{figure3.pdf}%\n\\caption{ An illustration of the quadratic estimate bias which results when $\\theta^\\prime(x)$ is large enough to exceed the \\textbf{symmetric two-sided cut locus} discussed Section \\ref{section: modeling xi, C and eta} (c.f. Claim \\ref{claim: cut locus}). The \\textbf{shaded region} shown in the \\textbf{middle plot} corresponds to the interior of the symmetric two-sided cut locus. When the true  $\\theta^\\prime(x)$ (shown in \\textbf{blue}) exits the symmetric two-sided cut locus, the quadratic estimate suffers from large bias, attenuating for negative $\\theta^\\prime(x)$ and amplifying for positive $\\theta^\\prime(x)$. Note that the only difference between this figure and Figure \\ref{Figure 2 zx and var} is the parameter $t_0$ (c.f. Section \\ref{section: modeling xi, C and eta}) which was reduced by a factor of $1/7$. This has the effect of shrinking the symmetric two-sided cut locus. All other parameters, including the random seed, are the same.}\n\\label{Figure 2 zx and var, extra bias}\n\\end{figure}\n\n\n\n\n\n% --------------------------------------------------------\n%  subsection\n%---------------------------------------------------------\n\\subsection{Nonstationary phase example $d=2$}\n\\label{section: nonstat example d=2}\n\n\nIn this section we perform a simulation example to illustrate the quadratic estimate applied to a nonstationary spectral phase random field $Z(\\bs x)$ in dimension $d=2$. Besides the increase of dimension, there are two main differences in this simulation as compared to the simulation given in Section \\ref{section: nonstat example d=1}. The first difference is that the spectral multiplier $\\bs \\xi_{\\bs k}$ is set to $(i\\bs k_2, -i\\bs k_1)^T$ where $\\bs k = (\\bs k_1, \\bs k_2)$. Therefore $\\bs \\theta(\\bs x) = (\\partial_{\\bs x_2}\\phi(\\bs x), -\\partial_{\\bs x_1}\\phi(\\bs x))^T$ is a divergent free vector field. The second main difference is that the two spectral densities $C_{\\bs k}$ and $\\tilde C_{\\bs k}$, defined by (\\ref{eq: Ck matern}) and (\\ref{eq: tildeCk matern}), have different Mat\\'ern parameter values as those used in Section \\ref{section: nonstat example d=1}. The parameter values for $C_{\\bs k}$  are given by $(\\nu, \\rho, \\sigma^2):=(1.5, 0.015, 1)$ and the parameter values for $\\tilde C_{\\bs k}$ are given by $(\\tilde \\nu, \\tilde\\rho, \\sigma^2):=(1.7, 0.014, 1)$. Recall that $C_{\\bs k}$ and $\\tilde C_{\\bs k}$ are used to generate $\\bs \\eta_{\\bs k}$ (c.f. Section \\ref{section: modeling xi, C and eta}) by requiring both $C_{\\bs k}$ and $\\tilde C_{\\bs k}$ be locally attainable spectral models in $Z(\\bs x)$. Therefore the corresponding quadratic estimate is tuned to detect not only a variation in the smoothness of $Z(\\bs x)$ but also a corresponding scale change, where the correspondence is related inversely (an increase in smoothness corresponding to a reduction of spatial scale and vice versa).\n\nFor this simulation example, the process $Z(\\bs x)$  is defined on $[-\\pi,\\pi)^2$ with periodic boundary conditions and the observed process $Z^{obs}(\\bs x)$ is generated without additive noise on a evenly spaced grid of size $400 \\times 400$. Just as in Section \\ref{section: nonstat example d=1}, a simple discrete Riemann sum approximation, at each observed $\\bs x$, was used to approximate to the integral (\\ref{eq: nonstate phase}) for generating the simulation of $Z^{obs}(\\bs x)$. \nThe ground truth potential $\\phi(\\bs x)$, used to generate the nonstationarity in $Z(\\bs x)$, is simulated from a mean zero stationary Gaussian process with Mat\\'ern parameters $(\\nu, \\rho, \\sigma^2):=(5, 0.3 \\pi, 0.5^2)$. Just as in Section \\ref{section: nonstat example d=1} the quantities $C^{(0)}_{\\bs \\ell}, C^{(1)}_{\\bs \\ell}, C^{(2)}_{\\bs \\ell}$ and $C^{ZZobs}_{\\bs \\ell}$ used to generate  $\\hat\\phi_{\\bs\\ell}$, $C^{\\text{var\\,}\\hat\\phi}_{\\bs\\ell}$ and $C^{\\text{bias\\,}\\hat\\phi}_{\\bs \\ell}$ are determined by (\\ref{eq: C(1), C(2) and C(3) for nonstationary phase}) and (\\ref{eq: CZZobs for nonstationary phase}). Finally, the parameter $t_0$ used in (\\ref{eq: modeling eta}) to determine $\\bs \\eta_k$ is set to $1.5$.\n\n\n\n\n\nFigure \\ref{Figure 3} graphically summarizes the simulation results. The \\textbf{top left image} shows the quadratic estimate $\\hat\\phi(\\bs x)$ and the \\textbf{top right image} shows the ground truth $\\phi(\\bs x)$. These top images are intended to illustrate the high accuracy of the estimate. The \\textbf{bottom right image} shows the data $Z^{obs}(\\bs x)$ used in the estimate $\\hat\\phi(\\bs x)$. The \\textbf{bottom left plot} shows the radial profile of $|\\bs \\ell|^2C_{\\bs \\ell}^{\\text{var }\\hat\\phi}$ (\\textbf{solid green}), $|\\bs \\ell|^2C_{\\bs \\ell}^{\\phi\\phi}$ (\\textbf{dotted black}) along with the fast approximation to $|\\bs \\ell|^2C_{\\bs \\ell}^{\\text{bias }\\hat\\phi}$ (\\textbf{dashed blue}) and the corresponding radially averaged empirical mean squared error per wavenumber (\\textbf{dotted green}). The computation of $\\hat\\phi_{\\bs \\ell}$ and  $C_{\\bs \\ell}^{\\text{var }\\hat\\phi}$ took $0.25$ seconds and $0.23$ seconds to compute, respectively. The fast approximation to $C_{\\bs \\ell}^{\\text{bias }\\hat\\phi}$ took $77$ seconds (the exact value of $C_{\\bs \\ell}^{\\text{bias }\\hat\\phi}$ is not computed in this case since the imputation is intensive and takes on the order of hours in our implementation and is not shown).\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n%  Section\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Discusssion}\n\\label{section: Discussion}\n\nPart of the motivation for this paper is an attempt to construct an extended class of nonstationary random fields, and a corresponding generalized quadratic estimate, which share the same attractive statistical properties of an estimate originally developed for gravitational lensing studies of the Cosmic Microwave Background \\cite{hu2001mapping, hu2002mass}.  In doing so we have identified a particular form of nonstationarity, we call {\\it local invariance}, which encourages a delicate cancellation of estimation bias. This local invariant property---we believe---is the main source of what makes the gravitational lensing estimates so successful.  Indeed, the generalized quadratic estimate, derived in Section~\\ref{section: local invariant}, shares many of the same attractive statistical features as the original gravitational lensing estimate: it is particularly adept at detecting small departures from stationarity and allows fast, accurate quantification of mean square sampling properties.  In Section~\\ref{section: NPhase} we focus on a particular subclass of locally invariant nonstationary random fields which are given by a spatially varying spectral phase modulation of a stationary random field. In this work, the theory of optimal transport and the $L_2$-Wasserstein metric play a major role in characterizing the behavior of the set of possible local spectral densities under these models and leads to a natural heuristic for quantifying estimation bias in terms of the Wasserstein geodesic cut locus (see Claim \\ref{claim: cut locus}, Section \\ref{section: modeling xi, C and eta} and Figure \\ref{Figure 2 zx and var, extra bias}).\n\nOne of the byproducts of this paper is the understanding that a nonstationary spectral phase can be estimated by analyzing the correlation among the Fourier coefficients of the nonstationary random field $Z(\\bs x)$. This was illustrated in Section~\\ref{section: NPhase} using a quadratic estimate to reconstruct a spatially varying spectral phase modulation of a stationary random field. Left unanswered, however, is the question of how one simultaneously estimates both the phase and the magnitude of the spectral modulation $A(\\bs k, \\bs x)$ in model (\\ref{eq: intro nonstat phase model}). It appears this line of research has the potential to merge the seminal work of Dahlhaus \\cite{dahlhaus1997fitting,dahlhaus2000likelihood} with the generalized quadratic estimate, presented here, for nonstationary estimation within a broad class of nonstationary random fields. \n\n\nIt is also important to mention the fact that we have derived our results under the rather idealized assumption that the observations locations form a dense regular grid and $Z(\\bs x)$ has periodic boundary conditions. Extensions to more realistic experimental conditions are not in the scope of this paper but are clearly important for real life applications. The situation is not hopeless, however, since these same features are ubiquitous in measurements of the Cosmic Microwave Background. Despite this, Cosmologists have devised methods which turn the idealized quadratic estimate into a pragmatic statistical tool for probing gravitational lensing (see \\cite{namikawa2013bias,van2012measurement,planck2013lensing,planck2015lensing}, for example). This suggests there exist analogous methods which can make the generalized quadratic estimate available to more general observational scenarios.\n\n\nWe finish with a discussion of Assumption \\ref{Assumption 2} that stipulates $\\bs \\theta(\\bs x)$ be characterized by a scalar potential $\\phi(\\bs x)$.  It is yet unclear how one generalizes this assumption, especially in the case where $\\bs \\theta(\\bs x)$ maps into a higher dimensional space $\\Bbb R^m$ for $m>d$. Notice that by considering a general $\\bs \\theta(\\bs x)\\colon\\Bbb R^d \\rightarrow \\Bbb R^m$ one may redefine $\\bs\\theta(\\bs x)$ by absorbing (i.e. concatenating) the observation locations $\\bs x$ into extra coordinates of $\\bs \\theta(\\bs x)$. This generalization enables one to replace the local invariant condition $\\text{cov}(Z(\\bs x), Z(\\bs y))=K(\\bs x-\\bs y, \\bs\\theta(\\bs x) - \\bs \\theta(y))$ with the more general condition \n\\begin{align}\n\\label{eq: embedding}\n\\text{cov}(Z(\\bs x), Z(\\bs y))=K(\\bs\\theta(\\bs x) - \\bs \\theta(\\bs y)).\n\\end{align}\nRandom fields $Z(\\bs x)$, which have a covariance function of the form (\\ref{eq: embedding}), are simply traces of stationary random fields defined on the higher dimensional space $\\Bbb R^m$, restricted to the $d$-dimensional parameterized surface $\\{\\bs\\theta(\\bs x):\\bs x\\in\\Bbb R^d\\}$. Viewed from this perspective, it appears plausible that there exists a deeper, more geometric, picture of local invariance and quadratic estimation. It is not yet clear whether or not this viewpoint is useful, but it is tempting to imagine that the generalized quadratic estimate is simply a manifold embedding estimate in disguise. If such a development bears theoretical fruit, it would be a major step in the direction of a unified statistical theory of nonstationary random fields. \n\n\n\n\\begin{figure}\n\\includegraphics[height=15cm]{figure4.pdf}%\n\\caption{An illustration of the quadratic estimate in $d=2$ for a nonstationary spectral phase random field $Z(\\bs x)$. The model for $Z(\\bs x)$ is defined to have local variation in both the local smoothness of $Z(\\bs x)$ and a local range parameter, where an increase of local smoothness corresponds reduction of local range and vice versa. The \\textbf{top left image} shows the quadratic estimate $\\hat\\phi(\\bs x)$ with the  ground truth $\\phi(\\bs x)$ shown in the \\textbf{top right image} and the data shown in the \\textbf{bottom right image}.  The \\textbf{bottom left plot} shows the radial profile of  $|\\bs \\ell|^2C_{\\bs \\ell}^{\\text{var }\\hat\\phi}$ (\\textbf{solid green}), $|\\bs \\ell|^2C_{\\bs \\ell}^{\\phi\\phi}$ (\\textbf{dotted black}) along with the fast approximation to $|\\bs \\ell|^2C_{\\bs \\ell}^{\\text{bias }\\hat\\phi}$ (\\textbf{dashed blue}) and the corresponding radially averaged empirical mean squared error per wavenumber (\\textbf{dotted green}). See Section \\ref{section: nonstat example d=2} for further simulation details.\n }\n\\label{Figure 3}\n\\end{figure}\n\n\n\n%%%%%%%%%%%%%%%%%%%%\n%\n%  bib\n%\n%%%%%%%%%%%%%%%%%%%%%%\n\n\\bibliography{refs}\n\n\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%\n%\n%  appendix\n%\n%%%%%%%%%%%%%%%%%%%%%%\n\n\\appendix\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%\n%\n%  appendix: detailed proofs\n%\n%%%%%%%%%%%%%%%%%%%%%%\n\\section{Detailed derivations}\\label{section: Detailed Proofs}\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Claim: derive the cov structure of the Fourier coefficients\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\begin{claim}\n\\label{claim: first order expansion}\nLet $\\bs\\theta(\\bs x)\\colon \\Bbb R^d \\rightarrow \\Bbb R^d$ be a vector field and $Z(\\bs x)$ be a random field which satisfies\n$E\\big(Z(\\bs x)Z(\\bs y)|\\bs \\theta(\\cdot)\\big)= C^{(0)}(\\bs x-\n\\bs y) + \\bs C^{(1)}(\\bs x-\\bs y)\\cdot(\\bs\\theta(\\bs x)-\\bs\\theta(\\bs y)) +  \\mathcal O(\\bs\\theta^2)$. Then \n\\begin{align}\n\\label{eq in claim: first order expansion}\nE(Z_{\\bs k+\\bs \\ell}Z_{-\\bs k}|\\bs \\theta(\\cdot)) &= \\bs\\theta_{\\bs \\ell}\\cdot\\big(\\bs C^{(1)}_{\\bs k} - \\bs C_{\\bs k+\\bs \\ell}^{(1)}\\big) + \\mathcal O(\\bs\\theta^2)\n\\end{align}\nwhen $\\bs\\ell\\neq 0$.\n\\end{claim}\n\n\n\\begin{proof}\nThe Fourier transform $C^{(0)}(\\bs x-\\bs y)$, with respect to $\\bs x$ and $\\bs y$, gives  $\\delta_{\\bs \\ell_1 + \\bs \\ell_2} {(2\\pi)}^{d/2} C^{(0)}_{\\bs \\ell_1}$. \n%% --- extra details\n% \\begin{align*}\n% \\iint e^{-i\\bs x\\cdot \\bs \\ell_1} e^{-i\\bs y\\cdot \\bs \\ell_2}C^{(0)}(\\bs x-\\bs y)\\frac{d\\bs xd\\bs y}{(2\\pi)^{d}} &= \\iint e^{-i(\\bs z+\\bs y)\\cdot \\bs \\ell_1} e^{-i\\bs y\\cdot \\bs \\ell_2}C^{(0)}(\\bs z)\\frac{d\\bs zd\\bs y}{(2\\pi)^{d}} \\\\\n% & = \\iint e^{-i\\bs z\\cdot \\bs \\ell_1} e^{-i\\bs y\\cdot (\\bs \\ell_1 + \\bs \\ell_2)}C^{(0)}(\\bs z) \\frac{d\\bs zd\\bs y}{(2\\pi)^{d}}\\\\\n% & = \\delta_{\\bs \\ell_1 + \\bs \\ell_2}\\int  e^{-i\\bs z\\cdot \\bs \\ell_1} C^{(0)}(\\bs z) d\\bs z = \\delta_{\\bs \\ell_1 + \\bs \\ell_2} {(2\\pi)}^{d/2} C^{(0)}_{\\bs \\ell_1}.\n% \\end{align*}\nSimilarly, the Fourier transform of $\\bs\\theta(\\bs x)\\cdot \\bs C^{(1)}(\\bs x-\\bs y)$ and $- \\bs\\theta(\\bs y)\\cdot \\bs C^{(1)}(\\bs x-\\bs y)$, with respect to $\\bs x$ and $\\bs y$, gives $\\bs\\theta_{\\bs\\ell_1+\\bs\\ell_2}\\cdot  \\bs C^{(1)}_{-\\bs\\ell_2}$ and $-\\bs\\theta_{\\bs \\ell_1+\\bs \\ell_2} \\cdot  \\bs C^{(1)}_{\\bs\\ell_1}$ respectively.\n%% --- extra details\n% \\begin{align*}\n% \\iint& e^{-i\\bs x\\cdot \\bs\\ell_1} e^{-i\\bs y\\cdot \\bs\\ell_2} \\bs\\theta(\\bs x)\\cdot \\bs C^{(1)}(\\bs x-\\bs y)\\frac{d\\bs xd\\bs y}{(2\\pi)^{d}} \\\\\n% &= \\iint e^{-i\\bs x\\cdot \\bs\\ell_1} e^{-i(\\bs x-\\bs w)\\cdot \\bs\\ell_2} \\bs\\theta(\\bs x)\\cdot \\bs C^{(1)}(\\bs w)\\frac{d\\bs xd\\bs w}{(2\\pi)^{d}} \\\\\n% &= \\iint e^{-i\\bs x\\cdot (\\bs\\ell_1+\\bs\\ell_2)} e^{-i\\bs w\\cdot (-\\bs\\ell_2)} \\bs\\theta(\\bs x)\\cdot \\bs C^{(1)}(\\bs w)\\frac{d\\bs xd\\bs w}{(2\\pi)^{d}} \\\\\n% &= \\bs\\theta_{\\bs\\ell_1+\\bs\\ell_2}\\cdot\\int  e^{-i\\bs w\\cdot (-\\bs\\ell_2)} \\bs C^{(1)}(\\bs w)\\frac{d\\bs w}{{(2\\pi)}^{d/2}}\\\\\n% &= \\bs\\theta_{\\bs\\ell_1+\\bs\\ell_2}\\cdot  \\bs C^{(1)}_{-\\bs\\ell_2}\n% \\end{align*}\n%%%%\n%% --- extra details\n% \\begin{align*}\n% \\iint& e^{-i\\bs x\\cdot \\bs\\ell_1} e^{-i\\bs y\\cdot \\bs\\ell_2} (- \\bs\\theta(\\bs y))\\cdot \\bs C^{(1)}(\\bs x-\\bs y) \\frac{d\\bs xd\\bs y}{(2\\pi)^{d}}\\\\\n% &= \\iint e^{-i(\\bs z+\\bs y)\\cdot \\bs\\ell_1} e^{-i\\bs y\\cdot \\bs\\ell_2}( -\\bs\\theta(\\bs y))\\cdot \\bs C^{(1)}(\\bs z)\\frac{d\\bs zd\\bs y}{(2\\pi)^{d}}  \\\\\n% &= \\iint e^{-i\\bs z\\cdot \\bs\\ell_1} e^{-i\\bs y\\cdot (\\bs\\ell_1+\\bs\\ell_2)}( -\\bs\\theta(\\bs y))\\cdot \\bs C^{(1)}(\\bs z)\\frac{d\\bs zd\\bs y}{(2\\pi)^{d}} \\\\\n% &= -\\bs\\theta_{\\bs\\ell_1+\\bs\\ell_2} \\cdot \\int e^{-i\\bs z\\cdot \\bs\\ell_1} \\bs C^{(1)}(\\bs z)\\frac{d\\bs z}{{(2\\pi)}^{d/2}} \\\\\n% &= -\\bs\\theta_{\\bs\\ell_1+\\bs\\ell_2} \\cdot  \\bs C^{(1)}_{\\bs\\ell_1}.\n% \\end{align*}\nSumming these three terms gives\n\\begin{align*}\nE\\big(Z_{\\bs \\ell_1}Z_{\\bs \\ell_2}|\\bs \\theta(\\cdot)\\big) &= {(2\\pi)}^{d/2}C^{(0)}_{\\bs \\ell_1} \\delta_{\\bs \\ell_1+\\bs \\ell_2}\n+ \\bs\\theta_{\\bs \\ell_1+\\bs \\ell_2}\\cdot\\big(\\bs C^{(1)}_{-\\bs \\ell_2} -\\bs C_{\\bs \\ell_1}^{(1)}\\big) + \\mathcal O(\\bs\\theta^2).\n\\end{align*}\nReplacing $\\bs \\ell_1$ with  $\\bs k+\\bs \\ell$  and $\\bs \\ell_2$ with $-\\bs k$ finishes the derivation.\n\\end{proof}\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Claim: derive the quadratic estimate\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\begin{claim}\\label{appendix, claim: quad est derivations}\nSuppose assumptions \\ref{Assumption 4}, \\ref{Assumption 2} and \\ref{Assumption 3} hold. Then the first order unbiased quadratic estimate of $\\phi_{\\bs \\ell}$, which corresponds to an approximate inverse variance weighted averaging of $Z_{\\bs k+\\bs \\ell}^{obs}Z_{-\\bs k}^{obs}$, has the form\n    \\begin{align}\n        \\label{appendix-claim def of quad est}\n        \\hat\\phi_{\\bs \\ell} &=   A_{\\bs \\ell}\\sum_{p=1}^d \\bs\\xi^*_{p,\\bs\\ell} \\int\n        e^{-i\\bs x\\cdot\\bs\\ell}\n        \\mathscr A(\\bs x)\\mathscr B_{p}(\\bs x) \\frac{d\\bs x}{{(2\\pi)}^{d/2}}\n    \\end{align}\n    where $\\mathscr A_{\\bs \\ell}:= Z^{obs}_{\\bs \\ell}/ C^{ZZobs}_{\\bs \\ell}$,  $\\mathscr B_{p,\\bs\\ell} := i 2 \\textit{\\,imag}(\\bs C^{(1)}_{p,\\bs \\ell}) Z^{obs}_{\\bs\\ell} / C^{ZZobs}_{\\bs \\ell}$ and \n    the normalizing constant\n    $A_{\\bs\\ell}$ is given by\n    \\begin{align}\n        \\label{appendix-claim def of Aℓinv}\n        A_{\\bs\\ell}^{-1} &= \\sum_{p,q = 1}^d\\bs\\xi_{p,\\bs \\ell}\\bs\\xi^*_{q,\\bs \\ell}\\int  e^{-i\\bs x\\cdot\\bs\\ell} \\left[2\\mathscr A_{p,q}(\\bs x)\\mathscr B(\\bs x)  - \\mathscr C_{p}(\\bs x)\\mathscr C_{q}(\\bs x) -  \\mathscr D_{p}(\\bs x)\\mathscr D_{q}(\\bs x)\\right]  \\frac{d\\bs x}{{(2\\pi)}^{d/2}}\n    \\end{align}\n    where $\\mathscr A_{p,q, \\bs \\ell}:= \\bs C^{(1)}_{p,\\bs\\ell} \\bs C^{{(1)}^*}_{q,\\bs\\ell}  / C^{ZZobs}_{\\bs\\ell}$, $\\mathscr B_{\\bs\\ell}:= 1/C^{ZZobs}_{\\bs\\ell}$, $\\mathscr C_{p,\\bs\\ell}:= \\bs C^{(1)}_{p,\\bs\\ell}  / C^{ZZobs}_{\\bs\\ell}$ and $\\mathscr D_{p,\\bs\\ell}:= \\bs C^{{(1)}^*}_{p,\\bs\\ell}  / C^{ZZobs}_{\\bs\\ell}$.\n\\end{claim}\n\n\n\n\\begin{proof}\nBy Claim \\ref{claim: first order expansion} we have that\n\\begin{align}\n\\label{eq: first order appendix behavior of ZZ}\nE\\big(Z^{obs}_{\\bs k+\\bs \\ell}Z^{obs}_{-\\bs k}\\big)\n= \\phi_{\\bs \\ell}\\, (\\bs \\xi_{\\bs \\ell}\\cdot \\bs f_{\\bs k,\\bs\\ell})+ \\mathcal O(\\phi^2)\n\\end{align}\n when $\\bs \\ell\\neq 0$ where $\\bs f_{\\bs k,\\bs \\ell}:= \\bs C_{\\bs k}^{(1)} -  \\bs C_{\\bs k+\\bs \\ell}^{(1)}$.\n Therefore the quadratic estimate, as a weighted average of the first order unbiased terms $Z^{obs}_{\\bs k+\\bs \\ell}Z^{obs}_{-\\bs k}/(\\bs \\xi_{\\bs \\ell}\\cdot \\bs f_{\\bs k,\\bs\\ell})$, can be written in the form\n\\begin{align}\n    \\label{the basic form of the quadratic estimator in the proof}\n\\hat\\phi_{\\bs\\ell}\n& = \\int w_{\\bs k,\\bs \\ell}\\frac{Z^{obs}_{\\bs k+\\bs \\ell}Z^{obs}_{-\\bs k}}{\\bs \\xi_{\\bs \\ell}\\cdot \\bs f_{\\bs k,\\bs\\ell}} \\frac{d\\bs k}{{(2\\pi)}^{d/2}}\n\\end{align}\nwhere $w_{\\bs k,\\bs\\ell}\\geq 0$ are normalized so that $\\hat\\phi_{\\bs\\ell}$ has expected value $\\phi_{\\bs\\ell} + \\mathcal O(\\phi^2)$ using (\\ref{eq: first order appendix behavior of ZZ}). Assuming $\\bs\\ell\\neq 0$, the Gaussian part of the variance of $Z^{obs}_{\\bs k+\\bs \\ell}Z^{obs}_{-\\bs k}/(\\bs \\xi_{\\bs \\ell}\\cdot \\bs f_{\\bs k,\\bs\\ell})$ can be computed as follows\n\\begin{align*}\n\\text{var}\\left(\\frac{Z^{obs}_{\\bs k+\\bs \\ell}Z^{obs}_{-\\bs k}}{\\bs \\xi_{\\bs \\ell}\\cdot \\bs f_{\\bs k,\\bs\\ell}}\n\\right) \n& = \\frac{1}{|\\bs \\xi_{\\bs \\ell}\\cdot \\bs f_{\\bs k,\\bs\\ell}|^2}\\Big[E(Z^{obs}_{\\bs k+\\bs\\ell}Z^{obs}_{-\\bs k}Z^{obs}_{-\\bs k-\\bs\\ell}Z^{obs}_{\\bs k})  - E(Z^{obs}_{\\bs k+\\bs\\ell}Z^{obs}_{-\\bs k})E(Z^{obs}_{-\\bs k-\\bs\\ell}Z^{obs}_{\\bs k}) \\Big] \\\\\n&\\approx \\frac{1}{|\\bs \\xi_{\\bs \\ell}\\cdot \\bs f_{\\bs k,\\bs\\ell}|^2}\\underbrace{\\Bigl[E(Z^{obs}_{\\bs k+\\bs\\ell}Z^{obs}_{-\\bs k-\\bs\\ell})E(Z^{obs}_{\\bs k}Z^{obs}_{-\\bs k})  + E(Z^{obs}_{\\bs k+\\bs\\ell}Z^{obs}_{\\bs k})E(Z^{obs}_{-\\bs k}Z^{obs}_{-\\bs k-\\bs\\ell}) \\Bigr]}_{\\textit{only keeping the Gaussian part of the trispectrum}} \\\\\n& = \\frac{C^{ZZobs}_{\\bs k+\\bs\\ell} C^{ZZobs}_{\\bs k}}{|\\bs \\xi_{\\bs \\ell}\\cdot \\bs f_{\\bs k,\\bs\\ell}|^2}\\big[\\delta_{\\bs 0}^2   + \\delta_{2\\bs k+\\bs\\ell}^2 \\big].\n\\end{align*}\nwhere $C^{ZZobs}_{\\bs\\ell}$ denotes the spectral density of $Z^{obs}(\\bs x)$ marginalized over $\\phi(\\cdot)$.\nIf we ignore the term $\\delta_{2\\bs k+\\bs\\ell}^2$, which only activates at the point $\\bs k = -\\bs\\ell/2$, then by defining $w_{\\bs k,\\bs \\ell}$ in (\\ref{the basic form of the quadratic estimator in the proof}) to be proportional to the approximate inverse (Gaussian part of the) variance of $Z^{obs}_{\\bs k+\\bs \\ell}Z^{obs}_{-\\bs k}/(\\bs \\xi_{\\bs \\ell}\\cdot \\bs f_{\\bs k,\\bs\\ell})$ one has\n\\begin{align}\n\\hat\\phi_{\\bs\\ell}\n& = A_{\\bs\\ell}\\int \\frac{|\\bs \\xi_{\\bs \\ell}\\cdot \\bs f_{\\bs k,\\bs\\ell}|^2}{C^{ZZobs}_{\\bs k+\\bs \\ell} C^{ZZobs}_{\\bs k}}\\frac{Z^{obs}_{\\bs k+\\bs \\ell}Z^{obs}_{-\\bs k}}{\\bs \\xi_{\\bs \\ell}\\cdot \\bs f_{\\bs k,\\bs\\ell}} \\frac{d\\bs k}{{(2\\pi)}^{d/2}} \\nonumber\\\\\n%% ----- extra detail\n%& = A_{\\bs\\ell}\\int \\bs \\xi_{\\bs \\ell}^*\\cdot \\bs f_{\\bs k,\\bs\\ell}^* \\frac{Z^{obs}_{\\bs k+\\bs \\ell}Z^{obs}_{-\\bs k}}{C^{ZZobs}_{\\bs k+\\bs \\ell} C^{ZZobs}_{\\bs k}}\\frac{d\\bs k}{{(2\\pi)}^{d/2}} \\nonumber\\\\\n% & =  A_{\\bs\\ell}\\, \\bs\\xi^*_{\\bs\\ell}\\cdot\\int \\Bigl[\\bs C^{{(1)}^*}_{\\bs k} - \\bs C^{{(1)}^*}_{\\bs k+\\bs \\ell}\\Bigr] \\frac{Z^{obs}_{\\bs k+\\bs \\ell}Z^{obs}_{-\\bs k}}{C^{ZZobs}_{\\bs k+\\bs \\ell} C^{ZZobs}_{\\bs k}} \\frac{d\\bs k}{{(2\\pi)}^{d/2}} \\nonumber\\\\\n% & =  A_{\\bs\\ell}\\, \\bs\\xi^*_{\\bs\\ell}\\cdot\\int\n% \\Bigl[\n%   \\frac{Z^{obs}_{\\bs k+\\bs \\ell}}{C^{ZZobs}_{\\bs k+\\bs \\ell} }\\frac{\\bs C^{{(1)}^*}_{\\bs k}Z^{obs}_{-\\bs k}}{C^{ZZobs}_{\\bs k}}\n% - \\frac{\\bs C^{{(1)}^*}_{\\bs k+\\bs \\ell}Z^{obs}_{\\bs k+\\bs \\ell}}{C^{ZZobs}_{\\bs k+\\bs \\ell} } \\frac{Z^{obs}_{-\\bs k}}{C^{ZZobs}_{\\bs k}}\n% \\Bigr] \\frac{d\\bs k}{{(2\\pi)}^{d/2}}\\nonumber \\\\\n& =  A_{\\bs\\ell}\\sum_{p=1}^d \\bs\\xi^*_{p,\\bs \\ell}\\int\n\\Bigl[\n  \\frac{Z^{obs}_{\\bs k+\\bs \\ell}}{C^{ZZobs}_{\\bs k+\\bs \\ell} }\\frac{\\bs C^{(1)}_{p,-\\bs k} Z^{obs}_{-\\bs k}}{C^{ZZobs}_{-\\bs k}}\n- \\frac{\\bs C^{{(1)}^*}_{p, \\bs k+\\bs\\ell}Z^{obs}_{\\bs k+\\bs \\ell}}{C^{ZZobs}_{\\bs k+\\bs \\ell} } \\frac{Z^{obs}_{-\\bs k}}{C^{ZZobs}_{-\\bs k}}\n\\Bigr] \\frac{d\\bs k}{{(2\\pi)}^{d/2}} \\nonumber\\\\\n&= A_{\\bs\\ell}\\sum_{p=1}^d \\bs\\xi^*_{p,\\bs \\ell} \\int\n\\left[\n\\mathscr A_{{\\bs k+\\bs \\ell}}\\mathscr D_{p,-\\bs k}  -\n\\mathscr C_{p,\\bs k+\\bs \\ell}\\mathscr A_{-\\bs k}\n \\right]  \\frac{d\\bs k}{{(2\\pi)}^{d/2}} \\nonumber \\\\\n &= A_{\\bs\\ell}\\sum_{p=1}^d \\bs\\xi^*_{p,\\bs \\ell} \\int\n e^{-i\\bs x\\cdot \\bs\\ell}\n \\left[\n \\mathscr A(\\bs x)\\mathscr D_{p}(\\bs x)  -\n \\mathscr C_{p}(\\bs x)\\mathscr A(\\bs x)\n  \\right]  \\frac{d\\bs x}{{(2\\pi)}^{d/2}} \\label{first quad est form in proof}\n\\end{align}\nwhere $\\mathscr A_{\\bs\\ell}:= Z^{obs}_{\\bs\\ell}/ C^{ZZobs}_{\\bs\\ell}$, $\\mathscr D_{p,\\bs\\ell}:=\\bs C^{(1)}_{p,\\bs\\ell}Z^{obs}_{\\bs\\ell}/C^{ZZobs}_{\\bs\\ell}$ and $\\mathscr C_{p,\\bs\\ell}:=\\bs C^{{(1)}^*}_{p,\\bs\\ell}Z^{obs}_{\\bs\\ell}/C^{ZZobs}_{\\bs\\ell}$. Notice that the Fourier transform of $\\mathscr D_{p}(\\bs x)  - \\mathscr C_{p}(\\bs x)$ can be simplified as follows\n\\begin{align*}\n\\mathscr D_{p,\\bs \\ell}  - \\mathscr C_{p,\\bs \\ell}\n& = \\bigl[\\bs C^{(1)}_{p,\\bs \\ell} - \\bs C^{{(1)}^*}_{p,\\bs \\ell}\\bigr]\\frac{Z^{obs}_{\\bs\\ell}}{C^{ZZobs}_{\\bs\\ell}} \n = i 2 \\textit{\\,imag}(\\bs C^{(1)}_{p,\\bs\\ell})\\frac{Z^{obs}_{\\bs\\ell}}{C^{ZZobs}_{\\bs\\ell}}.\n\\end{align*}\nThis gives (\\ref{appendix-claim def of quad est}) as was to be shown.\n\nThe normalizing constant $A_{\\bs\\ell}$ is defined so that the right hand of (\\ref{first quad est form in proof}) is unbiased (up to first order). Utilizing (\\ref{eq: first order appendix behavior of ZZ}) this unbiased constraint is written as follows\n\\begin{align}\n 1 &= A_{\\bs\\ell}\\int \\frac{|\\bs \\xi_{\\bs \\ell}\\cdot \\bs f_{\\bs k,\\bs\\ell}|^2}{C^{ZZobs}_{\\bs k+\\bs \\ell} C^{ZZobs}_{\\bs k}} \\frac{d\\bs k}{{(2\\pi)}^{d/2}}  \\nonumber\\\\\n&= A_{\\bs\\ell}\\int \\frac{\\bigl|\\bs \\xi_{\\bs \\ell}\\cdot\\bs C^{(1)}_{\\bs k+\\bs \\ell}  - \\bs\\xi_{\\bs \\ell}\\cdot\\bs C^{(1)}_{\\bs k} \\bigr|^2}{C^{ZZobs}_{\\bs k+\\bs \\ell} C^{ZZobs}_{\\bs k}} \\frac{d\\bs k}{{(2\\pi)}^{d/2}} \n\\nonumber\\\\\n%% ----- extra detail\n% &= A_{\\bs\\ell}\\int \\frac{\\bigl|\\bs \\xi_{\\bs \\ell}\\cdot\\bs C^{(1)}_{\\bs k+\\bs \\ell}\\bigr|^2  + \\bigl|  \\bs\\xi_{\\bs \\ell}\\cdot\\bs C^{(1)}_{\\bs k}\\bigr|^2 -  \\big(\\bs\\xi^*_{\\bs\\ell}\\cdot\\bs C^{{(1)}^*}_{\n% \\bs k+\\bs\\ell}\\big)\\big(\\bs\\xi_{\\bs\\ell}\\cdot\\bs C^{(1)}_{\\bs k}\\big) -  \\big(\\bs \\xi_{\\bs \\ell}\\cdot\\bs C^{(1)}_{\\bs k+\\bs \\ell}\\big)\\big(\\bs\\xi^*_{\\bs\\ell} \\cdot \\bs C^{{(1)}^*}_{k}\\big)  }{C^{ZZobs}_{\\bs k+\\bs\\ell} C^{ZZobs}_{\\bs k}} \\frac{d\\bs k}{{(2\\pi)}^{d/2}}  \n%\\\\\n&= A_{\\bs\\ell}\\sum_{p,q = 1}^d\\bs\\xi_{p,\\bs\\ell}\\bs\\xi^*_{q,\\bs\\ell}\\int \\frac{\\bs C^{(1)}_{p,\\bs k+\\bs \\ell} \\bs C^{{(1)}^*}_{q,\\bs k+\\bs \\ell} + \\bs C^{(1)}_{p,\\bs k} \\bs C^{{(1)}^*}_{q,\\bs k}  -     \\bs C^{(1)}_{p,\\bs k+\\bs \\ell} \\bs C^{{(1)}^*}_{q,\\bs k} - \\bs C^{{(1)}^*}_{p,\\bs k+\\bs \\ell} \\bs C^{(1)}_{q,\\bs k} }{C^{ZZobs}_{\\bs k+\\bs\\ell} C^{ZZobs}_{\\bs k}} \\frac{d\\bs k}{{(2\\pi)}^{d/2}}  \\nonumber\\\\\n&= A_{\\bs\\ell}\\sum_{p,q = 1}^d\\bs\\xi_{p,\\bs\\ell}\\bs\\xi^*_{q,\\bs\\ell}\\int  e^{-i\\bs x\\cdot\\bs \\ell} \\left[2\\mathscr A_{p,q}(\\bs x)\\mathscr B(\\bs x)  - \\mathscr C_{p}(\\bs x)\\mathscr C_{q}(\\bs x) -  \\mathscr D_{p}(\\bs x)\\mathscr D_{q}(\\bs x)\\right]  \\frac{d\\bs x}{{(2\\pi)}^{d/2}}\\label{Aell derivation 11}\n\\end{align}\nwhere $\\mathscr A_{p,q, \\bs\\ell}:= \\bs C^{(1)}_{p,\\bs\\ell} \\bs C^{{(1)}^*}_{q,\\bs\\ell}  / C^{ZZobs}_{\\bs\\ell}$, $\\mathscr B_{\\bs\\ell}:= 1/C^{ZZobs}_{\\bs\\ell}$, $\\mathscr C_{p,\\bs\\ell}:= \\bs C^{(1)}_{p,\\bs\\ell}  / C^{ZZobs}_{\\bs\\ell}$ and $\\mathscr D_{p,\\bs\\ell}:= \\bs C^{{(1)}^*}_{p,\\bs\\ell}  / C^{ZZobs}_{\\bs\\ell}$.\n\n\\end{proof}\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Claim: derive Cvar\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\begin{claim}[{\\bf Estimation variance}]\\label{thm: quantify the var fluctuations of hat phi}\n    Suppose $X(\\bs x)$ is a mean-zero Gaussian random field with spectral density given by $C^{X\\!X}_{\\bs \\ell}$.\n    Then the spectral density of $\\hat\\phi_{\\bs \\ell}\\{X,\\!X\\}$ (c.f. Definition \\ref{def: quad est applied to X}), which satisfies $\\delta^{\\phantom{*}}_{\\bs \\ell-\\bs \\ell^\\prime}C^{\\text{\\rm var }\\hat\\phi}_{\\bs \\ell} = E\\big(\\hat\\phi_{\\bs \\ell}\\{X,\\!X\\} \\, \\hat\\phi_{\\bs \\ell^\\prime}\\{X,\\!X\\}^*\\big) $, is given as follows\n    \\begin{align}\n        C_{\\bs\\ell}^{\\text{\\rm var }\\hat{\\phi}}\n        &= 2 A_{\\bs\\ell}^2\n        \\int\n        \\Bigl|\\bs\\xi_{\\bs\\ell}\\!\\cdot\\!\\bs C^{{(1)}}_{\\bs k} - \\bs\\xi_{\\bs\\ell}\\!\\cdot\\! \\bs C^{{(1)}}_{\\bs k+\\bs \\ell}\\Bigr|^2\n        \\frac{C^{X\\!X}_{\\bs k+\\bs\\ell}}{(C^{ZZobs}_{\\bs k+\\bs\\ell})^2}\n        \\frac{C^{X\\!X}_{\\bs k}}{(C^{ZZobs}_{\\bs k})^2}\n         \\frac{d\\bs k}{{(2\\pi)}^{d}} \\label{appendix, claim raw var} \\\\\n        &= 2 A_{\\bs\\ell}^2  \\sum_{p,q = 1}^d\\bs\\xi_{p,\\bs\\ell}\\bs\\xi^*_{q,\\bs\\ell}\\int e^{-i\\bs x\\cdot\\bs \\ell} \\left[2\\mathscr A_{p,q}(\\bs x)\\mathscr B(\\bs x)  - \\mathscr C_{p}(\\bs x)\\mathscr C_{q}(\\bs x) -  \\mathscr D_{p}(\\bs x)\\mathscr D_{q}(\\bs x)\\right]  \\frac{d\\bs x}{{(2\\pi)}^{d}} \\label{appendix, claim fast var}\n    \\end{align}\n    for all $\\bs \\ell\\neq 0$\n    where $\\mathscr A_{p,q, \\bs \\ell}:= \\bs C^{(1)}_{p,\\bs \\ell} \\bs C^{{(1)}^*}_{q,\\bs \\ell} C^{X\\!X}_{\\bs\\ell} / (C^{ZZobs}_{\\bs \\ell})^2$, $\\mathscr B_\\ell:=  C^{X\\!X}_{\\bs\\ell} / (C^{ZZobs}_{\\bs\\ell})^2$, $\\mathscr C_{p,\\bs\\ell}:= \\bs C^{(1)}_{p,\\bs\\ell}  C^{X\\!X}_{\\bs\\ell} / (C^{ZZobs}_{\\bs\\ell})^2$ and $\\mathscr D_{p,\\bs\\ell}:= \\bs C^{{(1)}^*}_{p,\\bs\\ell}  C^{X\\!X}_{\\bs\\ell} / (C^{ZZobs}_{\\bs\\ell})^2$.\n    Moreover, if $C_{\\bs\\ell}^{X\\!X} = C^{ZZobs}_{\\bs\\ell}$  one obtains\n    \\begin{equation}\n    C_{\\bs\\ell}^{\\text{\\rm var }\\hat{\\phi}} =  2{(2\\pi)}^{-d/2} A_{\\bs\\ell}.\n    \\end{equation}\n\\end{claim}\n\n\\begin{proof}\n    Recall Definition \\ref{def: quad est applied to X} which states that $\\hat\\phi_{\\bs \\ell}\\{X,\\!X\\}$ denotes the quadratic estimate applied to data $X(\\bs x)$. Therefore \n    \\begin{align}\n        E\\big(\\hat\\phi_{\\bs \\ell}\\{X,\\!X\\} \\, \\hat\\phi_{\\bs \\ell^\\prime}\\{X,\\!X\\}^*\\big)\n        & = A_{\\bs \\ell}A_{\\bs \\ell^\\prime}\n        \\iint\n        {\\Big(\\bs\\xi_{\\bs \\ell} \\!\\cdot\\!\\bs C^{{(1)}}_{\\bs k} - \\bs\\xi_{\\bs \\ell} \\!\\cdot\\!\\bs C^{{(1)}}_{\\bs k+\\bs \\ell}\\Big)}^{\\! *}\n        {\\Big(\\bs\\xi_{\\bs \\ell^\\prime} \\!\\cdot\\!\\bs C^{{(1)}}_{\\bs k^\\prime} - \\bs\\xi_{\\bs \\ell^\\prime} \\!\\cdot\\!\\bs C^{{(1)}}_{\\bs k^\\prime+\\bs \\ell^\\prime}\\Big)}^{}\\nonumber\\\\\n        &\\qquad\\qquad\\qquad\n        \\times\n        \\frac{E\\bigl(X_{\\bs k+\\bs \\ell}X_{-\\bs k}X_{-\\bs k^\\prime-\\bs\\ell^\\prime}X_{\\bs k^\\prime}\\bigr)}{C^{ZZobs}_{\\bs k+\\bs \\ell}C^{ZZobs}_{\\bs k}C^{ZZobs}_{\\bs k^\\prime+\\bs \\ell^\\prime}C^{ZZobs}_{\\bs k^\\prime}}\n        \\frac{d\\bs kd\\bs k^\\prime}{{(2\\pi)}^{d}}.\\label{wicks term in Cvar}\n    \\end{align}\n    Now expanding the above fourth moment, using Wick's theorem (also called Isserlis's Theorem) \\cite{wick1950evaluation, isserlis1916certain} and the Gaussianity of $X(\\bs x)$, one obtains\n    \\begin{align*}\n        E\\bigl(X_{\\bs k+\\bs \\ell}X_{-\\bs k}X_{-\\bs k^\\prime-\\bs\\ell^\\prime}X_{\\bs k^\\prime}\\bigr)\n        &=C^{X\\!X}_{\\bs k+\\bs \\ell}C^{X\\!X}_{-\\bs k^\\prime}\\bigl( \\delta_{\\bs\\ell}\\delta_{\\bs\\ell^\\prime} +  \\delta_{\\bs k-\\bs k^\\prime + \\bs \\ell-\\bs\\ell^\\prime}\\delta_{\\bs k-\\bs k^\\prime} +  \\delta_{\\bs k + \\bs k^\\prime +\\bs\\ell}\\delta_{\\bs k + \\bs k^\\prime +\\bs\\ell^\\prime}   \\bigr) \\\\\n        &=C^{X\\!X}_{\\bs k+\\bs\\ell}C^{X\\!X}_{-\\bs k^\\prime}\\bigl( \\delta_{\\bs\\ell}\\delta_{\\bs\\ell^\\prime} +  \\delta_{ \n        \\bs\\ell-\\bs\\ell^\\prime}\\delta_{\\bs k-\\bs k^\\prime} +  \\delta_{\\bs\\ell-\\bs\\ell^\\prime}\\delta_{\\bs k+\\bs k^\\prime +\\bs\\ell^\\prime}   \\bigr).\n    \\end{align*}\n    The term $\\delta_{\\bs\\ell}\\delta_{\\bs\\ell^\\prime}$ is only nonzero  when $\\bs\\ell=\\bs\\ell^\\prime=0$. Furthermore, by a change of variables, one can see that effect of the terms $\\delta_{ \\bs\\ell-\\bs\\ell^\\prime}\\delta_{\\bs k-\\bs k^\\prime}$ and $ \\delta_{\\bs\\ell-\\bs\\ell^\\prime}\\delta_{\\bs k+\\bs k^\\prime +\\bs \\ell^\\prime}$ in (\\ref{wicks term in Cvar}) are identical. Therefore assuming $\\bs \\ell \\neq 0$ and replacing  $E\\bigl(X_{\\bs k+\\bs \\ell}X_{-\\bs k}X_{-\\bs k^\\prime-\\bs\\ell^\\prime}X_{\\bs k^\\prime}\\bigr)$ in (\\ref{wicks term in Cvar}) with $2C^{X\\!X}_{\\bs k+\\bs\\ell}C^{X\\!X}_{-\\bs k^\\prime}\\delta_{ \\bs\\ell-\\bs\\ell^\\prime}\\delta_{\\bs k-\\bs k^\\prime}$ gives (\\ref{appendix, claim raw var}). A similar approach to the derivation for (\\ref{Aell derivation 11}) can be used to establish (\\ref{appendix, claim fast var}). Finally, if one replaces $C^{X\\!X}_{\\bs k}$ in (\\ref{appendix, claim raw var}) with the marginal spectral density $C^{ZZobs}_{\\bs k}$ then using (\\ref{Aell derivation 11}) one obtains $C_{\\bs\\ell}^{\\text{\\rm var }\\hat{\\phi}} =  2{(2\\pi)}^{-d/2} A_{\\bs\\ell}$.\n\n\\end{proof}\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Claim: derive Cbias\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\begin{claim}[{\\bf Estimation bias}]\\label{thm: bias in the appendix}\n    Let $\\mathcal O(\\phi^2)(\\bs x,\\bs y) := {(\\bs\\theta(\\bs x)-\\bs\\theta(\\bs y))}^T \\bs C^{(2)}(\\bs x-\\bs y) (\\bs\\theta(\\bs x)-\\bs\\theta(\\bs y))$ where $\\bs C^{(2)}(\\bs x)\\colon\\Bbb R^d \\rightarrow \\Bbb R^{d\\times d}$ and $\\bs C^{(2)}(-\\bs x)=\\bs C^{(2)}(\\bs x)$. Then\n    \\begin{align}\n    \t\\label{eq: the form of Op2}\n        \\mathcal O(\\phi^2)_{\\bs k+\\bs\\ell, -\\bs k}\n        &=\\sum_{p,q = 1}^d\n        \\int \\bs\\theta_{p,\\bs\\omega}\\bs\\theta_{q,\\bs\\ell - \\bs\\omega}\n\t\t \\Bigl(\n         {\\bs C^{(2)}_{p,q,\\bs k}}\n        + {\\bs C^{(2)}_{p,q,\\bs k +\\bs \\ell}}\n        - {\\bs C^{(2)}_{p,q,\\bs k +\\bs \\ell - \\bs\\omega}}\n        - {\\bs C^{(2)}_{p,q,\\bs k + \\bs\\omega}}\n        \\Bigr)\\frac{d\\bs\\omega}{(2\\pi)^{d/2}}.\n    \\end{align}\n    Define $\\hat\\phi_{\\bs \\ell}^{\\text{bias}}:=\\hat\\phi_{\\bs \\ell}\\big\\{\\mathcal O(\\phi^2)_{\\bs k+\\bs \\ell, -\\bs k}\\big\\}$ (see Definition \\ref{def: quad est applied to X}), where the quadratic estimate $\\hat\\phi_{\\bs \\ell}$ satisfies all the assumptions given in Claim \\ref{appendix, claim: quad est derivations}. Then \n    \\begin{align}\n    \t\\label{eq: the form of hatphibias}\n        \\hat\\phi_{\\bs \\ell}^{\\text{bias}}&= 2\\sum_{p,q=1}^d\n    \t\\int \n    \t\\bs\\theta_{p,\\bs\\omega}\\bs\\theta_{q,\\bs \\ell - \\bs\\omega}\\, \\hat\\phi_{\\bs \\ell}\\Big\\{{\\bs C^{(2)}_{p,q,\\bs k}}- {\\bs C^{(2)}_{p,q,\\bs k + \\bs\\omega}}\\Big\\}\\frac{d\\bs\\omega}{(2\\pi)^{d/2}}\n   \t\\end{align}\n    and the spectral density of $\\hat\\phi_{\\bs \\ell}^{\\text{bias}}$, under a mean zero Gaussian random field model for $\\bs\\theta(\\bs x)$ with spectral density matrix $C_{\\bs \\ell}^{\\bs \\theta\\bs\\theta}$, satisfies\n\t\\begin{align}\n    \t\\label{eq: the form of the spectrum for hatphibias}\n\t\tE\\big(\\hat\\phi_{\\bs \\ell}^{\\text{bias}} \\hat\\phi_{\\bs \\ell^\\prime}^{\\text{bias}^*}\\big)\n        &=\n        4\\delta_{\\bs\\ell-\\bs \\ell^\\prime}\\!\\!\\! \\sum_{p,q,p^\\prime,q^\\prime=1}^d \\int \n        \\Big(\n        C^{\\bs \\theta\\bs \\theta}_{p,p^\\prime,\\bs \\omega}C^{\\bs \\theta\\bs \\theta}_{q,q^\\prime,\\bs \\ell - \\bs \\omega}\n        + C^{\\bs \\theta\\bs \\theta}_{p,q^\\prime,\\bs \\omega}C^{\\bs \\theta\\bs \\theta}_{q,p^\\prime,\\bs \\ell - \\bs \\omega}\n        \\Big)\\nonumber\n    \t\\\\\n        &\\qquad\\qquad\\qquad\\qquad\\qquad\\times\n        \\hat\\phi_{\\bs \\ell}\\Big\\{{\\bs C^{(2)}_{p,q,\\bs k}}- {\\bs C^{(2)}_{p,q,\\bs k + \\bs\\omega}}\\Big\\}\n        \\hat\\phi_{\\bs \\ell}\\Big\\{{\\bs C^{(2)}_{p^\\prime,q^\\prime,\\bs k}}- {\\bs C^{(2)}_{p^\\prime,q^\\prime,\\bs k + \\bs\\omega}}\\Big\\}^*\\frac{d\\bs\\omega}{(2\\pi)^{d}}\n        \\end{align}\n        when $\\bs \\ell \\neq 0$ or $\\bs \\ell^\\prime \\neq 0$.\n\\end{claim}\n\\begin{proof}\n    Notice that for any $p,q \\in \\{1,\\ldots, d\\}$ if one defines $B_{p,q}(\\bs x,\\bs y) := (\\bs\\theta_p(\\bs x)-\\bs\\theta_p(\\bs y))(\\bs\\theta_q(\\bs x)-\\bs\\theta_q(\\bs y))$ then the Fourier transform of $B_{p,q}(\\bs x,\\bs y)$ with respect to $(\\bs x,\\bs y)$, evaluated at frequency vector $(\\bs k,\\bs k^\\prime)$, is given by\n    \\begin{align*}\n       B_{p,q,\\bs k,\\bs k^\\prime} = \\int \\bs\\theta_{p,\\bs\\omega}\\Big(\n        \\bs\\theta_{q,\\bs k - \\bs \\omega}&\\delta_{-\\bs k^\\prime}\n        + \\bs\\theta_{q,\\bs k^\\prime - \\bs \\omega}\\delta_{-\\bs k}\\delta_{\\bs\\omega+\\bs\\omega^\\prime-\\bs k^\\prime} \\\\\n        &- \\bs\\theta_{q,\\bs k^\\prime}\\delta_{\\bs\\omega-\\bs k}\\delta_{\\bs\\omega^\\prime-\\bs k^\\prime}\n        - \\bs\\theta_{q,\\bs k}\\delta_{\\bs\\omega^\\prime-\\bs k}\\delta_{\\bs\\omega-\\bs k^\\prime}\n        \\Big)d\\bs\\omega. \n    \\end{align*}\n    % \\begin{align}\n    %     \\iint \\frac{d\\bs x\\,d\\bs y}{{(2\\pi)}^d} e^{-i\\bs x\\cdot \\bs k}e^{-i\\bs y\\cdot \\bs k^\\prime} \\bs C^{(2)}_{p,q}(\\bs x-\\bs y)\n    %     &= \\iint \\frac{d\\bs x^\\prime\\,d\\bs y}{{(2\\pi)}^d} e^{-i(\\bs x^\\prime+\\bs y)\\cdot \\bs k}e^{-i\\bs y\\cdot \\bs k^\\prime} \\bs C^{(2)}_{p,q}(\\bs x^\\prime) \\nonumber \\\\\n    %     &= \\iint \\frac{d\\bs x^\\prime\\,d\\bs y}{{(2\\pi)}^d} e^{-i\\bs x^\\prime\\cdot \\bs k}e^{-i\\bs y\\cdot (\\bs k+\\bs k^\\prime)} \\bs C^{(2)}_{p,q}(\\bs x^\\prime)\\nonumber\\\\\n    %      &= \\big(\\bs C^{(2)}_{\\bs k}\\big)_{p,q} \\delta_{\\bs k+\\bs k^\\prime} {(2\\pi)}^{d/2} \\label{eqn: in proof of bias, dirac A}.\n    % \\end{align}\n    % Recall the following general convolution formula applied to two variables\n    % \\[\n    % {\\bigl[ A(\\bs x,\\bs y)B(\\bs x,\\bs y) \\bigr]}_{\\bs k, \\bs k^\\prime} = \\iint \\frac{d\\bs z \\, d\\bs z^\\prime}{{(2\\pi)}^d} A_{\\bs z+\\bs k, \\bs z^\\prime + \\bs k^\\prime}B_{-\\bs z, -\\bs z^\\prime}\n    % \\]\n    Using the fact that  Fourier transform of $\\bs C^{(2)}_{p,q}(\\bs x-\\bs y)$ equals ${(2\\pi)}^{d/2}\\bs C^{(2)}_{p,q,\\bs k} \\delta_{\\bs k+\\bs k^\\prime}$ one obtains\n    \\begin{align}\n        \\mathcal O(\\phi^2)_{\\bs k, \\bs k^\\prime} &= \\sum_{p,q=1}^d\\Bigl[\n        \\,\n        \\underbrace{\\bs C^{(2)}_{p,q}(\\bs x-\\bs y)}_{A_{p,q}(\\bs x,\\bs y)}\n        \\underbrace{(\\bs\\theta_p(\\bs x)-\\bs\\theta_p(\\bs y))(\\bs\\theta_q(\\bs x)-\\bs\\theta_q(\\bs y))}_{B_{p,q}(\\bs x,\\bs y)}\n        \\,\n        \\Bigr]{\\vphantom{\\int}}_{\\bs k,\\bs k^\\prime} \\nonumber\\\\\n        &=\\sum_{p,q=1}^d\n        \\iint  A_{p,q,\\bs z+\\bs k, \\bs z^\\prime+\\bs k^\\prime}B_{p,q,-\\bs z, -\\bs z^\\prime}\\frac{d\\bs z \\, d\\bs z^\\prime}{{(2\\pi)}^d} \\nonumber\\\\\n        % &=\\sum_{p,q=1}^d \\iint \\frac{d\\bs z \\, d\\bs z^\\prime}{{(2\\pi)}^d} {\\bs C^{(2)}_{p,q,\\bs z+\\bs k}} \\delta_{\\bs k+\\bs k^\\prime +\\bs z+\\bs z^\\prime} {(2\\pi)}^{d/2} B_{-\\bs z, -\\bs z^\\prime} \\nonumber\\\\\n       %  &=\\sum_{p,q=1}^d\n       %  \\int \\frac{d\\bs z}{{(2\\pi)}^{d/2}}\n       % {\\bs C^{(2)}_{p,q,\\bs z+\\bs k}}\n       %  B_{-\\bs z, \\bs k+\\bs k^\\prime +\\bs z} \\nonumber\\\\\n       %  &=\\sum_{p,q=1}^d\n       %  \\iint \\frac{d\\bs\\omega d\\bs\\omega^\\prime}{(2\\pi)^d}\n       %  \\bs\\theta_{p,\\bs\\omega}\\bs\\theta_{q,\\bs\\omega^\\prime}\n       %  \\int \\frac{d\\bs z}{{(2\\pi)}^{d/2}}\n       % {\\bs C^{(2)}_{p,q,\\bs z+\\bs k}}\\nonumber\\\\\n       %  &\\qquad\\qquad\n       %  \\times (2\\pi)^d\\Bigl(\n       %  \\delta_{\\bs\\omega+\\bs\\omega^\\prime +\\bs z}\\delta_{\\bs k+\\bs k^\\prime +\\bs z}\n       %  + \\delta_{\\bs z}\\delta_{\\bs\\omega+\\bs\\omega^\\prime-\\bs k-\\bs k^\\prime -\\bs z}\n       %  - \\delta_{\\bs\\omega+\\bs z}\\delta_{\\bs\\omega^\\prime-\\bs k-\\bs k^\\prime -\\bs z}\n       %  - \\delta_{\\bs\\omega^\\prime+\\bs z}\\delta_{\\bs\\omega-\\bs k-\\bs k^\\prime -\\bs z}\n       %  \\Bigr)\\nonumber\\\\\n   %      &=\\sum_{p,q=1}^d\n   %      \\iint \\frac{d\\bs\\omega d\\bs\\omega^\\prime}{(2\\pi)^d}\n   %      \\bs\\theta_{p,\\bs\\omega}\\bs\\theta_{q,\\bs\\omega^\\prime}\n   %      \\frac{(2\\pi)^d}{{(2\\pi)}^{d/2}}\n\t\t % \\Bigl(\n   %       {\\bs C^{(2)}_{p,q,-\\bs k^\\prime}}\n   %      \\delta_{\\bs\\omega+\\bs\\omega^\\prime - \\bs k -\\bs k^\\prime}\n   %      + {\\bs C^{(2)}_{p,q,\\bs k}}\\delta_{\\bs\\omega+\\bs\\omega^\\prime-\\bs k-\\bs k^\\prime}\\nonumber\\\\\n   %      &\n   %      \\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\quad- {\\bs C^{(2)}_{p,q,\\bs\\omega^\\prime-\\bs k^\\prime}}\\delta_{\\bs\\omega+\\bs\\omega^\\prime-\\bs k-\\bs k^\\prime}\n   %      - {\\bs C^{(2)}_{p,q,\\bs\\omega-\\bs k^\\prime}}\\delta_{\\bs\\omega^\\prime+\\bs\\omega-\\bs k-\\bs k^\\prime}\n   %      \\Bigr)\\nonumber\\\\\n        &=\\sum_{p,q=1}^d\\int \n        \\bs\\theta_{p,\\bs\\omega}\\bs\\theta_{q,\\bs k+\\bs k^\\prime - \\bs\\omega}\n\t\t \\Bigl(\n         {\\bs C^{(2)}_{p,q,-\\bs k^\\prime}}\n        + {\\bs C^{(2)}_{p,q,\\bs k}}\n        - {\\bs C^{(2)}_{p,q,\\bs k - \\bs\\omega}}\n        - {\\bs C^{(2)}_{p,q,\\bs\\omega-\\bs k^\\prime}}\n        \\Bigr)\\frac{d\\bs\\omega}{(2\\pi)^{d/2}}.\n        \\label{2p349571 first order bias behavior}\n    \\end{align}\n    Making the substitution $\\bs k^\\prime \\rightarrow -\\bs k$ and $\\bs k\\rightarrow \\bs k+\\bs \\ell$ in (\\ref{2p349571 first order bias behavior}) proves (\\ref{eq: the form of Op2}). Equation (\\ref{eq: the form of hatphibias}) immediately follows from the fact that\n    \\begin{align*}\n\t\\hat\\phi_{\\bs \\ell}\\Big\\{{\\bs C^{(2)}_{p,q,\\bs k+\\bs \\ell}}- {\\bs C^{(2)}_{p,q,\\bs k+\\bs \\ell - \\bs\\omega}}\\Big\\}\n    &=\\hat\\phi_{\\bs \\ell}\\Big\\{{\\bs C^{(2)}_{p,q,\\bs k}}- {\\bs C^{(2)}_{p,q,\\bs k + \\bs\\omega}}\\Big\\}\n    \\end{align*}\n    which is established by utilizing the three properties $\\bs C^{(2)}_{-\\bs k} = \\bs C^{(2)}_{\\bs k}\\in\\Bbb R^{d\\times d}$, $\\bs C^{(1)^*}_{-\\bs k} = \\bs C^{(1)}_{\\bs k}$ and $\\bs C^{(1)}_{-\\bs k} = -\\bs C^{(1)}_{\\bs k}$ along with the change of variables $\\tilde {\\bs k} = - \\bs k - \\bs \\ell $. Finally, using Wick's theorem for Gaussian $\\bs \\theta(\\bs x)$ gives\n    \\begin{align}\n    \\label{eq: wicks expansion of theta}\n    E\\big(\\bs \\theta_{p,\\bs\\omega}\\bs \\theta_{q,\\bs \\ell - \\bs\\omega}\\bs \\theta_{p^\\prime,\\bs\\omega^\\prime}^* \\bs \\theta_{q^\\prime,\\bs\\ell^\\prime - \\bs\\omega^\\prime}^*\\big)\n    &= \\delta_{\\bs \\ell - \\bs \\ell^\\prime}\\big(C^{\\bs \\theta\\bs \\theta}_{p,p^\\prime,\\bs \\omega}C^{\\bs \\theta\\bs \\theta}_{q,q^\\prime,\\bs \\ell - \\bs \\omega}\\delta_{\\bs \\ell - \\bs\\omega^\\prime - \\bs \\omega}\n        + C^{\\bs \\theta\\bs \\theta}_{p,q^\\prime,\\bs \\omega}C^{\\bs \\theta\\bs \\theta}_{q,p^\\prime,\\bs \\ell - \\bs \\omega}\\delta_{ \\bs\\omega^\\prime + \\bs \\omega}  \\big)\n    \\end{align}\n    when $\\bs \\ell \\neq 0$ or $\\bs \\ell^\\prime \\neq 0$. Expanding the quadratic $E\\big(\\hat\\phi_{\\bs \\ell}^{\\text{bias}} \\hat\\phi_{\\bs \\ell^\\prime}^{\\text{bias}^*}\\big)$, applying Fubini and (\\ref{eq: wicks expansion of theta}) then gives (\\ref{eq: the form of the spectrum for hatphibias}) as was to be shown.\n\\end{proof}\n\n\n\n\\end{document}\n", "meta": {"hexsha": "65fa6a4a88f51d18ea9596a850eb3772d436a553", "size": 140025, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/paper.tex", "max_stars_repo_name": "EthanAnderes/NonstationaryPhase.jl", "max_stars_repo_head_hexsha": "4c9ffc1a71814507f4484251fc3ab11b2d5350ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2016-11-04T12:32:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-12T15:53:52.000Z", "max_issues_repo_path": "paper/paper.tex", "max_issues_repo_name": "EthanAnderes/NonstationaryPhase.jl", "max_issues_repo_head_hexsha": "4c9ffc1a71814507f4484251fc3ab11b2d5350ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/paper.tex", "max_forks_repo_name": "EthanAnderes/NonstationaryPhase.jl", "max_forks_repo_head_hexsha": "4c9ffc1a71814507f4484251fc3ab11b2d5350ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 107.4635456639, "max_line_length": 2300, "alphanum_fraction": 0.6695804321, "num_tokens": 45829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.30879365052139357}}
{"text": "\\documentclass[12pt]{article}\n\\usepackage{xspace,times,a4wide,command,environment}\n\\usepackage{skaff}\n\\usepackage{optionman}\n\\usepackage{comment}\n\n\\newcommand{\\Linsearch}[0]{{\\small \\textsf{linsearch}}\\xspace}\n\\newcommand{\\Binsearch}[0]{{\\small \\textsf{binsearch}}\\xspace}\n\\newcommand{\\Vmbucket}[0]{{\\small \\textsf{vmbucket}}\\xspace}\n\\newcommand{\\Vmctlook}[0]{{\\small \\textsf{vmctlook}}\\xspace}\n\\newcommand{\\Mkvtree}[0]{{\\small \\texttt{mkvtree}}\\xspace}\n\\newcommand{\\Showfile}[1]{{\\small \\texttt{#1}}}\n\\newcommand{\\Weight}[0]{w}\n\\newcommand{\\Sol}[1]{\\mathit{Sol}(\\Weight)}\n\\newcommand{\\Minmass}{600 \\cdot 10^{p}}\n\\newcommand{\\Maxmass}{4000 \\cdot 10^{p}}\n\\newcommand{\\Defaultrange}{\\lbrack\\Minmass,\\Maxmass\\rbrack}\n\\newcommand{\\WSMP}{weighted substring matching problem\\xspace}\n\n\\author{Stefan Kurtz\\thanks{\\SKaffiliation}}\n\\title{\\textbf{Implementing Algorithms for}\\\\\n       \\textbf{the Weighted String Matching Problem}}\n\n\\begin{document}\n\\maketitle\n\\section{Introduction}\nLet \\(\\Sigma\\) be a finite alphabet. Strings are indexed from \\(0\\), \ni.e.\\ any \\(w\\in\\Sigma^{l}\\) is written as \\(w=w_{0}\\ldots w_{l-1}\\).\nLet \\(\\sigma:\\Sigma\\to\\Reals_{+}\\) be a function.\nFor any \\(l\\in\\Reals_{+}\\) and any\nstring \\(w\\in\\Sigma^{l}\\) we define \\(\\sigma(w)=\\sum_{i=0}^{l-1}\\sigma(w_{i})\\).\nLet \\(S\\in\\Sigma^{n}\\). For any \\((j,l)\\in[0,n-1]\\times[1,n-j]\\)\nwe define \\(\\Weight_{j,l}=\\sigma(S_{j}\\ldots S_{j+l-1})\\), i.e.\\\n\\(\\Weight_{j,l}\\) is the weight of the substring of \\(S\\) of length \\(l\\) \nstarting at position \\(j\\). Let \\(\\alpha,\\beta\\in\\Reals_{+}\\), \n\\(\\alpha\\leq\\beta\\) and \\(\\Weight\\in[\\alpha,\\beta]\\). The \n\\emph{\\WSMP for} \\(\\Weight\\) is to enumerate the \nfollowing set:\n\\[\\Sol{\\Weight}=\\Set{(j,l)\\mid j\\in[0,n-1], l\\in[1,n-j],\\Weight_{j,l}=\\Weight}\\]\n\n\\section{Algorithms}\nCieliebak et.\\ al \\cite{CIE:ERL:LIP:STO:WEL:2001} describe several algorithms\nfor solving the \\WSMP. The simplest of these\nare the Algorithms \\Linsearch and \\Binsearch. This manuscript reports\non the implementation of these Algorithms or variations thereof.\n\n\\subsection{An $O(n)$ Time Algorithm}\nAlgorithm \\Linsearch performs a linear search over the input string \\(S\\).\nIt manipulates three integers \\(l\\), \\(r\\), and \\(z\\) such that \n\\(0\\leq l\\leq r\\leq n\\)  and \\(z=\\Weight_{l,r-l}\\). That is, \\(z\\) is the\nweight of the substring \\(S_{l}\\ldots S_{r-1}\\). In the initialization step\nwe set \\(l=r=z=0\\). The main loop of the algorithm iterates\nthe following case distinction, until \\(r=n\\):\n\n\\begin{itemize}\n\\item\nIf \\(z<\\Weight\\), then \\(z\\) is incremented\nby \\(\\sigma(S_{r})\\) and \\(r\\) is incremented by \\(1\\). \n\\item\nIf \\(z=\\Weight\\), then \\((l,r-l)\\in\\Sol{\\Weight}\\). Hence \\((l,r-l)\\) is output.\nMoreover, \\(z\\) is decremented by \\(\\sigma(S_{l})\\) and \\(l\\) is incremented \nby \\(1\\). \n\\item\nIf \\(z>\\Weight\\), then \\(z\\) is decremented by \\(\\sigma(S_{l})\\) and \\(l\\) is \nincremented by \\(1\\). \n\\end{itemize}\nThe correctness of the algorithm is easily established.\nIn each step either \\(l\\) or \\(r\\) is incremented. Thus the main loop has at\nmost \\(2(n+1)\\) iterations. Each loop iteration takes constant time. Thus \nthe running time of \\Linsearch is \\(O(n)\\).\n\n\\subsection{An $O(\\log n^{2})$ Time Algorithm}\nAlgorithm \\Binsearch, as suggested in \\cite{CIE:ERL:LIP:STO:WEL:2001},\nfirst preprocesses \\(S\\). It enumerates all \\(\\Weight_{j,l}\\),\n\\(j\\in[0,n-1]\\), \\(l\\in[1,n-j]\\), and stores all triples \n\\((\\Weight_{j,l},j,l)\\) in an array \\(wtab\\) which is sorted w.r.t.\\ the first \ncomponent, i.e.\\ the weight. Now \\(wtab\\) can be searched for a given weight\n\\(\\Weight\\), using two binary searches: One binary search\ndetermines the smallest \\(i\\), say \\(i_{l}\\), satisfying\n\\begin{equation}\nwtab(i)=(\\Weight,j,l)\\mbox{ for some }j\\mbox{ and some }l,\\label{Miexists}\n\\end{equation}\nif it exists. Similarly, the other binary search determines the \nlargest \\(i\\), say \\(i_{r}\\), satisfying (\\ref{Miexists}), if it exists.\nThe triples in \\(wtab\\) between the two boundaries \\(i_{l}\\) and \\(i_{r}\\)\ngive the solutions to the \\WSMP for \\(\\Weight\\). The size of \\(wtab\\) is\non the order of \\(O(n^{2})\\) in the worst case. Hence the running time\nof \\Binsearch is \\(O(\\log n^{2})\\).\n\n\\subsection{An $O(1)$ Time Algorithm for Integer Weights}\\label{OptimalAlgorithm}\nWe have developed a new method similar to Algorithm \\Binsearch.\nOur method makes the following assumptions:\n\\begin{itemize}\n\\item\nThe weights delivered by the weight function \\(\\sigma\\) are non-negative \nintegers.\n\\item\nThe weights to be searched are in the range \\(\\lbrack\\alpha,\\beta\\rbrack\\)\nfor some fixed constants \\(\\alpha\\) and \\(\\beta\\). These are known in advance.\n\\end{itemize}\nNote that \\Binsearch does not makes these assumptions.\n\nOur method naturally splits into two phases, a preprocessing phase and a \nlookup phase. Hence we describe the two algorithms\n\\Vmbucket and \\Vmctlook.\\footnote{Cieliebak et.\\ al \n\\cite{CIE:ERL:LIP:STO:WEL:2001} describe\nan algorithm \\emph{LOOKUP} which has nothing to do with \\Vmctlook}\nWe exploit the fact, that the upper and lower boundaries \\(\\alpha\\) and \n\nAlgorithm \\Vmbucket performs the preprocessing step by \ntraversing the suffix tree for \\(S\\)\nin a depth first strategy to efficiently collect all substring positions with \nweight between \\(\\alpha\\) and \n\\(\\beta\\). Whenever visiting a branching node \\(\\overline{v}\\),\n\\Vmbucket maintains a stack holding the weights for all non-empty prefixes\nof \\(v\\). The weight stack is used to determine the weight for all prefixes \nof \\(v\\) (including \\(v\\)) whose length is larger than the depth of the \nfather of \\(\\overline{v}\\). Call these prefixes the \\emph{edge prefixes}\nof \\(v\\). Leaves in the subtree below \\(\\overline{v}\\) tell the position where \nthe prefix of \\(v\\) starts. For all weights \\(\\Weight\\in[\\alpha,\\beta]\\) \nof the edge prefixes of \\(v\\), algorithm \\Vmbucket stores the rank of the \nleftmost leaf in the subtree below \\(\\overline{v}\\). The rank refers to an\nenumeration of all leaves in a depth first traversal of the suffix tree. That\nis, the leftmost leaf gets rank 0, the next leaf reached in the depth\nfirst traversal gets rank 1, etc. If \\(i\\) is the rank of the leftmost leaf,\nthen we say that \\(i\\) \\emph{goes into bucket} \\(B_{\\Weight}\\).\n\nWhenever Algorithm \\Vmbucket visits a leaf edge, say outgoing from \n\\(\\overline{v}\\), it takes the characters labeling the leaf edge and\nincrementally adds up corresponding weights, until the end of\nthe label is reached or the weight becomes larger than \\(\\beta\\). \nEach leaf represents a suffix of \\(S\\$\\) and hence for each weight \n\\(\\Weight\\in[\\alpha,\\beta]\\) obtained in this way, Algorithm \\Vmbucket stores \nthe start position, say \\(j\\), of this suffix in \\(S\\$\\). We say that \\(j\\)\n\\emph{goes into bucket} \\(B_{\\Weight}\\).\n\nTo efficiently obtain and retrieve the ranks and the start positions,\nthe suffix tree is traversed twice. In a first traversal Algorithm\n\\Vmbucket determines the size of each bucket \\(B_{\\Weight}\\), i.e.\\ the number \nof ranks and suffix positions that go into bucket \\(B_{\\Weight}\\). Then an array\n\\(B\\) is allocated large enough to store all ranks and suffix positions. \nFrom the size of the buckets, boundaries in \\(B\\) are determined where \nthe elements of each bucket are stored. For each \\(\\Weight\\in[\\alpha,\\beta]\\), \nthe elements of \\(B_{\\Weight}\\) are stored beginning at position \n\\(b_{\\Weight}=\\sum_{i=\\alpha}^{\\Weight-1}\\Size{B_{i}}\\) in \\(B\\). That is, all \nelements of \\(B_{\\Weight}\\) will be stored in consecutive positions of \\(B\\),\nand the buckets will be placed in consecutive order of their weights, where\n\\(\\Weight\\) is the weight of \\(B_{\\Weight}\\). Finally, Algorithm \\Vmbucket \nagain traverses the suffix tree and stores all elements into array \\(B\\) \nbetween the corresponding bucket boundaries. \nAlgorithm \\Vmbucket can be implemented such \nthat it runs in \\(O(\\beta-\\alpha+\\Size{B})\\) time.\n\nThe bucket boundaries \\(b_{\\alpha},b_{\\alpha+1},\\ldots,b_{\\beta-1},b_{\\beta}\\)\nand array \\(B\\) are stored on a file. This is mapped into main memory, so \nthat all necessary information is readily available when searching for a \nweight. Suppose we have to compute \\(\\Sol{\\Weight}\\) for \nsome \\(\\Weight\\in[\\alpha,\\beta]\\). Algorithm \\Vmctlook determines\nthe bucket boundaries \\(b_{\\Weight}\\) and \\(b_{\\Weight+1}\\).\nIf \\(\\Weight=\\beta\\), then \\(b_{\\Weight+1}=b_{\\Weight}+\\Size{B_{\\Weight}}\\).\nThen all \\(B[l]\\) for \\(l\\in[B_{\\Weight},B_{\\Weight+1}-1]\\) are processed. If \n\\(B[l]\\) stores a suffix position, say \\(j\\), then we know that a \nsubstring of \\(S\\) with weight \\(\\Weight\\) starts at position \\(j\\). \nTo determine the length of this substring we add up weights starting at \nposition \\(j\\) until we reach weight \\(\\Weight\\).\nIf \\(B[l]\\) is a rank, say \\(i\\), then we know that the \\(i\\)th\nleaf in the suffix tree represents a suffix which has a prefix with\nweight \\(\\Weight\\). This prefix, say \\(u\\), can easily be determined.\nSuppose \\(v\\) is the shortest prefix of that suffix such that \\(\\overline{v}\\)\nis a branching node and \\(v\\) is a prefix of \\(u\\). By construction, the\nleaf with rank \\(i\\) is the left most leaf in the subtree below \n\\(\\overline{v}\\). We only have to enumerate the other leaves in the subtree \nbelow \\(\\overline{v}\\) to obtain the positions where \\(v\\) occurs. This can be \ndone in time proportional to the number of these leaves. For each leaf \nobtained in this way we determine the start position of the corresponding \nsuffix. This gives us the start positions of \\(v\\) and \\(\\sigma(v)=\\Weight\\).\nThe length of \\(v\\) is determined once for the suffix corresponding to the \nleft most leaf. For all other start positions of \\(v\\), the length is the same.\n\nAlgorithm \\Vmctlook takes constant time to find the boundaries. Each of \nthe \\(b_{\\Weight+1}-b_{\\Weight}\\) integers (ranks or suffix positions)\nbetween the boundaries are processed one after the other.\nNote that any string with weight at most \\(\\beta\\) is at most of length \n\\(\\Rounddown{\\beta/\\sigma_{\\min}}\\)\nwhere \\(\\sigma_{\\min}=\\min\\Set{\\sigma(a)\\mid a\\in\\Sigma}\\). Hence\neach suffix position is processed in \\(O(\\Rounddown{\\beta/\\sigma_{\\min}})\\) \nsteps. This is independent of \\(n\\) and can thus be considered a constant. Each \ninteger representing a rank requires to find all, say \\(q\\), leaves in the\ncorresponding subtree. These can be found in \\(O(q)\\) time. Each leaf is \nprocessed in constant time. Altogether \\(\\Sol{\\Weight}\\) is\ndetermined in \\(O(\\Size{\\Sol{\\Weight}})\\) time. This is optimal.\nAn important disadvantage of algorithm \\Vmctlook is the fact that the size of \nthe precomputed bucket information is in \\(O(n^{2})\\). However, preliminary\nexperiments suggest that for the domain of protein identification the \nsize of the index grows linearly with \\(n\\). \n\\begin{comment}\nFor more details see\nSection \\ref{Experiments}.\n\\end{comment}\n\n\\section{Weights and Masses and their Representation}\nThe \\WSMP is motivated by applications in protein identification. In this\napplication \\(\\Sigma\\) is the alphabet of aminoacids and the weights are the\n\\emph{masses} of the aminoacids. Table \\ref{Masstab} shows these masses.\nMoreover, the assumption that only weights in some range \n\\([\\alpha,\\beta]\\) are sought holds true. We currently assume that\n\\(\\alpha=600\\) and \\(\\beta=4000\\). If you think this range is too\nrestricitve, please contact us.\n\n\\begin{table}\n\\begin{center}\n\\begin{small}\n\\begin{tabular}{llll}\n\\begin{tabular}{|l|r|}\\hline\n\\texttt{G} & 57.02146\\\\\\hline\n\\texttt{A} & 71.03711\\\\\\hline\n\\texttt{S} & 87.03203\\\\\\hline\n\\texttt{P} & 97.05276\\\\\\hline\n\\texttt{V} & 99.06841\\\\\\hline\n\\texttt{T} &101.04768\\\\\\hline\n\\end{tabular}&\n\\begin{tabular}{|l|r|}\\hline\n\\texttt{C} &103.00919\\\\\\hline\n\\texttt{L} &113.08406\\\\\\hline\n\\texttt{I} &113.08406\\\\\\hline\n\\texttt{X} &113.08406\\\\\\hline\n\\texttt{N} &114.04293\\\\\\hline\n\\texttt{O} &114.07931\\\\\\hline\n\\end{tabular}&\n\\begin{tabular}{|l|r|}\\hline\n\\texttt{B} &114.53494\\\\\\hline\n\\texttt{D} &115.02694\\\\\\hline\n\\texttt{Q} &128.05858\\\\\\hline\n\\texttt{K} &128.09496\\\\\\hline\n\\texttt{Z} &128.55059\\\\\\hline\n\\texttt{E} &129.04259\\\\\\hline\n\\end{tabular}&\n\\begin{tabular}{|l|r|}\\hline\n\\texttt{M} &131.04049\\\\\\hline\n\\texttt{H} &137.05891\\\\\\hline\n\\texttt{F} &147.06841\\\\\\hline\n\\texttt{R} &156.10111\\\\\\hline\n\\texttt{Y} &163.06333\\\\\\hline\n\\texttt{W} &186.07931\\\\\\hline\n\\end{tabular}\n\\end{tabular}\n\\label{Masstab}\n\\caption{The Masses of the Aminoacids}\n\\end{small}\n\\end{center}\n\\end{table}\nFor a given \\emph{precision value} \\(p\\in[0,5]\\), \nwe multiply the masses given in Table \\ref{Masstab} by \n\\(10^{p}\\) and round to the next integer. Then the maximal mass is\n$18607931\\leq 2^{25}$ and we represent it by a 32-bit integer. For \nefficiency reasons, \\(p\\) is determined at compile time. Several other \nconstants depend on the choice of \\(p\\). \n\\begin{comment}\nHence we have implemented a \nprogram \\Showfile{mkmasstab.x} which outputs appropriate C-definitions,\nsee Appendix \\ref{Mkmasout} for an example. \nBesides the table storing the rounded masses, \\Showfile{mkmasstab.x}\noutputs constant definitions for the maximal and minimal masses\n\\(600\\cdot 10^{p}\\) and \\(4000\\cdot 10^{p}\\). The output of \n\\Showfile{mkmasstab.x} is stored in a header file \n\\Showfile{masstab.h}, which is used by all programs described below.\n\\end{comment}\n\n%\\begin{comment}\n\n\\section{Programs}\nWe have implemented the algorithms described above. These and some\nother useful programs related to the \\WSMP are described in the following. \nThe distributions contains for all programs depending on \\(p\\),\nall versions of the program for \\(p\\in[0-5]\\). For example,\nthere are programs \n\\(\\texttt{findmass0.x}\\),\n\\(\\texttt{findmass1.x}\\),\n\\(\\texttt{findmass2.x}\\),\n\\(\\texttt{findmass3.x}\\),\n\\(\\texttt{findmass4.x}\\),\n\\(\\texttt{findmass5.x}\\). To always work with a consistent \ncollection of programs (for the same value of \\(p\\)), we recommend\nto call the shell-script \\texttt{Linkmassprogs.sh} with the appropriate\nvalue for \\(p\\) as first argument. This creates softlinks \nfor all programs, so that you can use them as described below.\nThe examples given below are for \\(p=2\\).\n\n\\subsection{The Program \\texttt{evalmass.x}}\nThis program takes a sequence of aminoacids and outputs the total mass\nof this sequence.  For example:\n\n\\begin{verbatim}\n$ evalmass.x GASPVTCLNOBDQKZEMHFRYW\n262018\n\\end{verbatim}\n\n\\subsection{The Program \\texttt{callmkvtree.sh}}\nTo solve the \\WSMP, we first perform\nan indexing step of the protein sequences to be searched. In \nparticular, we generate an enhanced suffix array of the protein sequences\n(see \\cite{ABO:KUR:OHL:2002}) using the program \\Mkvtree.\nWe use the shell script \\Showfile{callmkvtree.sh} to call \\Mkvtree with the\nproper arguments. The arguments to \\Showfile{callmkvtree.sh} specify the\nnames of the files to be indexed (following the option \\Showoption{db}). If \nmore than one file is to be indexed, then the additional \noption \\Showoption{indexname} followed by the name of the index must be \nspecified.\n\n\\paragraph{Example}\nAs a running example we suppose a file \\Showfile{swiss1MB} containing a \nsubsection of the Swissprot protein sequence database.\nThen we call the shell script \\Showfile{callmkvtree.sh} as follows:\n\n\\begin{footnotesize}\n\\begin{verbatim}\nreading file \"swiss1MB\"\ntotal length of sequences: 1000120 (including 2549 separators)\nalphabet of size 23: GASPVTCLNOBDQKZEMHFRYW*\ncreating file \"swiss1MB.ssp\"\ncreating file \"swiss1MB.tis\"\ncreating file \"swiss1MB.ois\"\ncreating file \"swiss1MB.des\"\ncreating file \"swiss1MB.sds\"\ncreating file \"swiss1MB.lcp\"\ninitializing data structures\nsorting suffixes according to prefix of length 4\nsorting all buckets\ncreating file \"swiss1MB.llv\"\ncreating file \"swiss1MB.suf\"\ncreating file \"swiss1MB.prj\"\ncreating file \"swiss1MB.al1\"\noverall space peak: main=6.11 MB (6.40 bytes/symbol), secondary=1.08 MB\n\\end{verbatim}\n\\end{footnotesize}\n\nNow we have the enhanced suffix array stored in different files\nwith the prefix \\Showfile{swiss1MB}.\n\n\\begin{small}\n\\begin{verbatim}\n$ ls -l swiss1MB.*\n-rw-r-----    1 kurtz    users         171 Mar  7 22:08 swiss1MB.al1\n-rw-r-----    1 kurtz    users      118867 Mar  7 22:08 swiss1MB.des\n-rw-r-----    1 kurtz    users     1000121 Mar  7 22:08 swiss1MB.lcp\n-rw-r-----    1 kurtz    users       85576 Mar  7 22:08 swiss1MB.llv\n-rw-r-----    1 kurtz    users     1000120 Mar  7 22:08 swiss1MB.ois\n-rw-r-----    1 kurtz    users         187 Mar  7 22:08 swiss1MB.prj\n-rw-r-----    1 kurtz    users       10204 Mar  7 22:08 swiss1MB.sds\n-rw-r-----    1 kurtz    users       10196 Mar  7 22:08 swiss1MB.ssp\n-rw-r-----    1 kurtz    users     4000484 Mar  7 22:08 swiss1MB.suf\n-rw-r-----    1 kurtz    users     1000120 Mar  7 22:08 swiss1MB.tis\n\\end{verbatim}\n\\end{small}\nSee \\cite{KUR:2002A} for more details on the information contained in the \ndifferent files comprising the index.\n\n\\subsection{The Program \\texttt{vmbucket.x}}\nThis program implements algorithm \\Vmbucket, as described above.\nHowever, while \\Vmbucket is based on suffix trees, \n\\Showfile{vmbucket.x} it is based on enhanced suffix arrays as constructed by\n\\Mkvtree. In \\cite{ABO:KUR:OHL:2002} it is shown how to simulate the depth\nfirst traversal of the suffix tree on an enhanced suffix array.\n\\Showfile{vmbucket.x} computes the bucket information for a given index.\n\n\\begin{Showprogramwithoptions}{\\Showfile{vmbucket.x}}{\n\\emph{indexname} is the name of the index produced by the\n\\Showfile{callmkvtree.sh}. Unless called with the option \\Showoption{size},\n\\Showfile{vmbucket.x} generates an additional mass-index file \n\\Showfile{indexname.mas} storing the bucket information.}\n\n\\Option{minmass}{$\\alpha$}{\nSpecify the minimal mass value $\\alpha$. This must be in the range\n$\\Defaultrange$. If this option is not specified, then the default value \nfor $\\alpha$ is $\\Minmass$.\n}\n\n\\Option{maxmass}{$\\beta$}{\nSpecify the maximal mass value $\\beta$. This must be in the range\n$\\Defaultrange$. If this option is not specified, then the default value \nfor $\\beta$ is $\\Maxmass$.\n}\n\n\\Option{size}{}{\nOnly report the size of the bucket information, but do not generate it.}\n\n\\Option{help}{}{\nShow a summary of all options and terminate.}\n\n\\end{Showprogramwithoptions}\n\n\\paragraph{Example (continued)}\nApplying \\Showfile{vmbucket.x} to the index \\Showfile{swiss1MB}, we obtain the \nfollowing:\n\n\\begin{small}\n\\begin{verbatim}\nnumber of bucket boundaries = 340002 (0.34 integers per input char)\nsuffix positions = 19054185 (19.05 integers per input char)\nranks = 2762138 (2.76 integers per input char)\ntotal size of buckets = 22156325 (22.15 integers per input char)\nsize of index: 84.52 megabytes\ncreate index file \"swiss1MB.mas\" of 84.52 megabytes\n# space peak in megabytes: 83.22\n# mmap space peak in megabytes: 5.81\n\\end{verbatim}\n\\end{small}\n\nNow we have the mass-index file \\Showfile{swiss1MB.mas} available.\n\n\\begin{small}\n\\begin{verbatim}\n$ ls -l swiss1MB.mas\n-rw-r-----    1 kurtz    users    107633732 Dec  4 01:10 swiss1MB.mas\n\\end{verbatim}\n\\end{small}\n\n\\subsection{The Program \\texttt{findmass.x}}\nThis program implements the different algorithms to solve the\n\\WSMP, namely algorithm \\Linsearch and\n\\Vmctlook. For each algorithm it provides different output formats.\n\n\\begin{Showprogramwithoptions}{\\Showfile{findmass.x}}{}\n\n\\Option{search}{$alg$}{\nspecify the search algorithm. \nIf $alg$ is \\texttt{lin}, then \\Linsearch is used.\nIf $alg$ is \\texttt{ctl}, then \\Vmctlook is used. If this option \nis not specified, then the default search algorithm is \\Vmctlook.\n}\n\n\\Option{trials}{$t$}{\nrun $t$ trials. In each trial, the \\WSMP is solved for a randomly chosen \nmass in the range $\\lbrack \\alpha,\\beta\\rbrack$.\nThis option is mainly used for testing purposes.\n}\n\n\\Option{massfile}{$\\emph{filename}$}{\nread the masses from the file named \\emph{filename}. This file\ncontains one mass per line and nothing else. For each mass value\nfound in the file, the \\WSMP is solved.\n}\n\n\\Option{output}{$outmode$}{\nspecify the form of the output. \n\\begin{itemize}\n\\item\nIf $outmode$ is \\texttt{no}, then no\noutput is shown, but the search is still performed. This output mode is \nmainly integrated to measure the running time of the program\nwithout disturbing it by the generation of the output. \n\\item\nIf $outmode$ is \\texttt{plain}, then all solutions to the \n\\WSMP are output, one per line.\n\\item\nIf $outmode$ is \\texttt{group}, then all matches are grouped according\nto the sequence in which they match. The groups are output ordered by their\nsize. For each group, its consecutive number, the corresponding sequence\nnumber and its size is reported, as well as all matches ordered by their \nrelative position in the sequence.\n\\end{itemize}\nIf $outmode$ is \\texttt{plain} or \\texttt{group}, then an additional\noptional argument \\texttt{seq} triggers the additional output of the \nmatching sequence.\n}\n\n\\Option{help}{}{\nShow a summary of all options and terminate.}\n\n\\end{Showprogramwithoptions}\n\nExactly one of the two options \\Showoption{trials} and \n\\Showoption{massfile} is mandatory.\n\n\\paragraph{Example (continued)}\nHere is the partial output for several calls of \\Showfile{findmass.x}. \nThe arguments of the program was called with are shown in the first line \nof the output.\n\n\\begin{footnotesize}\n\\begin{verbatim}\n# findmass.x -search ctl -output plain seq -trials 100 swiss1MB\n# indexfile \"swiss1MB.mas\" (88625308 bytes) read\n# each line reporting a match is in the following format:\n# mass sequence_header relative_position match_length matching_sequence\n# run 100 trials of masses in the range [60000,400000]\n314415 sp|AEGP_RAT|APICAL  27   30 HCRSPTEATCNFVCDCGDCSDEAQCGFHGA\n314415 sp|A2AB_DIDMA|ALPHA-2B 259   28 SVGPEDGSQKQEEEEEEEEEEEEECGPP\n314415 sp|ADH1_KLUMA|ALCOHOL  95   30 GSCMSCEECELSNEPNCPKADLSGYTHDGS\n383933 sp|41BB_MOUSE|4-1BB 182   34 SLQVLTLFLALTSALLLALIFITLLFSVLKWIRK\n 97434 sp|ACH4_HUMAN|NEURONAL 222    8 YECCAEIY\n 97434 sp|ACH4_RAT|NEURONAL 228    8 YECCAEIY\n...\n\\end{verbatim}\n\\end{footnotesize}\n\nIf we use a different search mode, then the results are reported in a \norder of the position of the matched in the indexed file.\n\n\\begin{footnotesize}\n\\begin{verbatim}\n# findmass.x -search lin -output plain seq -trials 100 swiss1MB\n# each line reporting a match is in the following format:\n# mass sequence_header relative_position match_length matching_sequence\n# run 100 trials of masses in the range [60000,400000]\n314415 sp|A2AB_DIDMA|ALPHA-2B 259   28 SVGPEDGSQKQEEEEEEEEEEEEECGPP\n314415 sp|ADH1_KLUMA|ALCOHOL  95   30 GSCMSCEECELSNEPNCPKADLSGYTHDGS\n314415 sp|AEGP_RAT|APICAL  27   30 HCRSPTEATCNFVCDCGDCSDEAQCGFHGA\n383933 sp|41BB_MOUSE|4-1BB 182   34 SLQVLTLFLALTSALLLALIFITLLFSVLKWIRK\n 97434 sp|A2HS_BOVIN|ALPHA-2-HS-GLYCOPROTEIN  30    9 ACDDPDTEQ\n 97434 sp|A2HS_BOVIN|ALPHA-2-HS-GLYCOPROTEIN  31    9 CDDPDTEQA\n...\n\\end{verbatim}\n\\end{footnotesize}\n\nIf we choose to group the output, then the output is independent of\nthe chosen search mode.\n\n\\begin{footnotesize}\n\\begin{verbatim}\n# findmass.x -search lin -output group -trials 100 swiss1MB\n# each line reporting a match is in the following format:\n# mass sequence_header relative_position match_length\n# run 100 trials of masses in the range [60000,400000]\n# output 2159 groups in order of their size\n# group 0 for sequence 1671 has 38 elements\n  288629 sp|ACVS_CEPAC|DELTA-(L-ALPHA-AMINOADIPYL)-L-CYSTEINYL 116   29\n  126958 sp|ACVS_CEPAC|DELTA-(L-ALPHA-AMINOADIPYL)-L-CYSTEINYL 133   13\n  124665 sp|ACVS_CEPAC|DELTA-(L-ALPHA-AMINOADIPYL)-L-CYSTEINYL 312   11\n...\n# group 1 for sequence 1673 has 36 elements\n  232817 sp|ACVS_NOCLA|DELTA-(L-ALPHA-AMINOADIPYL)-L-CYSTEINYL 130   20\n  124360 sp|ACVS_NOCLA|DELTA-(L-ALPHA-AMINOADIPYL)-L-CYSTEINYL 278   10\n  355276 sp|ACVS_NOCLA|DELTA-(L-ALPHA-AMINOADIPYL)-L-CYSTEINYL 380   34\n...\n# group 2 for sequence 1672 has 33 elements\n  149685 sp|ACVS_EMENI|DELTA-(L-ALPHA-AMINOADIPYL)-L-CYSTEINYL 268   14\n  213109 sp|ACVS_EMENI|DELTA-(L-ALPHA-AMINOADIPYL)-L-CYSTEINYL 476   20\n  213109 sp|ACVS_EMENI|DELTA-(L-ALPHA-AMINOADIPYL)-L-CYSTEINYL 477   20\n...\n\\end{verbatim}\n\\end{footnotesize}\n\n\\section{Release Notes}\n\\subsection{Changes made on March 7, 2003}\n\\begin{enumerate}\n\\item\nchange minimum mass from 800 to 600\n\\item\ncompile programs for different values of \\(p\\) and add \nhelpful script \\texttt{Linkmassprogs.sh}\n\\item\noutput original protein sequence instead of transformed sequence\n\\item\noutput sequence headers (up to the first blank) instead of \nsequence numbers\n\\item\nupdate manual accordingly\n\\end{enumerate}\n\n\\section{Preliminary Experimental Results}\\label{Experiments}\nIn our experiments we have applied the programs from above to six protein\nfiles: \\Showfile{swiss.$i$MB.fna}, for \\(i\\in[1,5]\\) and \\Showfile{sprot38}.\nThe latter is the complete swissprot database release 38. \nEach file \\Showfile{swiss.$i$MB.fna} is a collection of randomly selected\nprotein sequences from \\Showfile{sprot38} such that the total length of\nthe sequences is about \\(i\\) megabytes.\nTable \\ref{PPresults} shows the results when generating the index\nfor the different input files. In particular, \nfile sizes, number of suffix positions, number of ranks, and index sizes \nare shown.\nIn all cases, the number of bucket boundaries is \n\\(10^{p}(\\beta-\\alpha)+1+1=10^{2}(4000-600)+2=340002\\). Note that the \nindex size does not include the size of the \nfiles produced by \\Mkvtree. These are however small compared to the \nmass-index file. Similarly, the construction time for the suffix array is\nsmall compared to the construction of the mass index.\nTable \\ref{Findresults} shows the running time of the different searching\nalgorithms for the different indexes.\n\n\\begin{table}\n\\begin{center}\n\\begin{small}\n\\begin{tabular}{|*{6}{r|}}\\hline\n\\emph{file}&$n$&\\emph{suffix positions}$/n$&\\emph{ranks}$/n$&\\emph{size of index} (MB)&\\emph{time}\\\\\\hline\n\\Showfile{swiss1MB} & 1002835 & 26.17 & 0.35 & 102.65&10.18\\\\\\hline\n\\Showfile{swiss2MB} & 2006050 & 25.68 & 0.53 & 201.80&21.61\\\\\\hline\n\\Showfile{swiss3MB} & 3008338 & 25.36 & 0.66 & 299.93&33.43\\\\\\hline\n\\Showfile{swiss4MB} & 4011052 & 25.03 & 0.80 & 396.37&38.02\\\\\\hline\n\\Showfile{swiss5MB} & 5013972 & 24.64 & 0.93 & 490.36&54.73\\\\\\hline\n\\Showfile{sprot38}  &31791220 & 20.59 & 2.19 &2764.05&??\n\\\\\\hline\n\\end{tabular}\n\\end{small}\n\\end{center}\n\\caption{Results when computing the mass-index. The first column shows\nthe file, the second its size. The next columns show the number of\nstored suffix positions as well as the number of ranks, relative to the\nsize of the file. The last two column show the total size of the mass-index\nas well as the time to construct it. The reported time include the \noutput to a file. All time results are in seconds and refer to a computer\nwith a 1123~Mhz Pentium III processor and 614 MB RAM running Linux.}\n\\label{PPresults}\n\n\\begin{center}\n\\begin{small}\n\\begin{tabular}{|*{5}{c|}}\\hline\n           &\\multicolumn{2}{c|}{\\Linsearch}\n           &\\multicolumn{2}{|c|}{\\Vmctlook}\\\\\\hline\n\\emph{file}&\\emph{time}&\\emph{space}&\\emph{time}&\\emph{space}\\\\\\hline\n\\Showfile{swiss1MB}&182.44 &0.97 &0.52&108.40\\\\\\hline\n\\Showfile{swiss2MB}&374.83 &1.93 &1.11&213.30\\\\\\hline\n\\Showfile{swiss3MB}&556.20 &2.90 &1.29&317.18\\\\\\hline\n\\Showfile{swiss4MB}&746.24 &3.87 &2.10&419.39\\\\\\hline\n\\Showfile{swiss5MB}&935.78 &4.83 &2.18&519.13\\\\\\hline\n\\end{tabular}\n\\end{small}\n\\end{center}\n\\caption{Results when searching 10000 masses that are randomly sampled from\nthe interval $[60000,400000]$. The first column shows the file.\nThe second and third column show the running time (in seconds) and space \nrequirement (in MB) for the \\Linsearch algorithm.\nThe fourth and fifth column show the running time (in seconds) and space \nrequirement (in MB) for the \\Vmctlook algorithm.}\n\\label{Findresults}\n\\end{table}\n%\\end{comment}\n\n\\bibliographystyle{plain}\n\\bibliography{defines,strings,kurtz}\n\n\\begin{comment}\n\\newpage\n\\appendix\n\\section{The output of \\texttt{mkmasstab.x 2}}\\label{Mkmasout}\n\\begin{footnotesize}\n\\begin{verbatim}\n#ifndef MASSTAB_H\n#define MASSTAB_H\n\n        /* This file is generated by mkmas.x 2, do not edit */\n\n        /* the precision value */\n#define PRECISIONVALUE 2\n        /* number of aminoacids */\n#define NUMOFAMINOACIDS 22\n        /* minimal mass */\n#define MINMASS 60000\n        /* maximal mass */\n#define MAXMASS 400000\n        /* size of table countmasstab */\n#define SIZECOUNTMASSTAB (MAXMASS-MINMASS+1+1)\n        /* number of digits to output mass */\n#define DIGITSFORMAXMASS 6\n        /* aminoacids ordered by mass */\n#define AMINOCHARACTERS \"GASPVTCLNOBDQKZEMHFRYW\"\n\n#define MASSFORMAT \"%*u\"\n        /* type for masses */\ntypedef unsigned int Masstype;\n\n        /* defining this means to ignore masstab */\n#ifndef IGNOREMASSTAB\n\n        /* The masses of the amino acids */\nstatic Masstype masstab[] = \n{\n  5702,  /* G -> 0 */\n  7104,  /* A -> 1 */\n  8703,  /* S -> 2 */\n  9705,  /* P -> 3 */\n  9907,  /* V -> 4 */\n  10105,  /* T -> 5 */\n  10301,  /* C -> 6 */\n  11308,  /* L -> 7 */\n  11404,  /* N -> 8 */\n  11408,  /* O -> 9 */\n  11453,  /* B -> 10 */\n  11503,  /* D -> 11 */\n  12806,  /* Q -> 12 */\n  12809,  /* K -> 13 */\n  12855,  /* Z -> 14 */\n  12904,  /* E -> 15 */\n  13104,  /* M -> 16 */\n  13706,  /* H -> 17 */\n  14707,  /* F -> 18 */\n  15610,  /* R -> 19 */\n  16306,  /* Y -> 20 */\n  18608  /* W -> 21 */\n};\n\n#endif\n#endif\n\\end{verbatim}\n\\end{footnotesize}\n\\end{comment}\n\n\\end{document}\n\\newpage\n\n\\section{Ideas and Future Work}\n\\begin{enumerate}\n\\item\nDivide \\(S\\) into non-overlapping sections of length \\(n/2^{16}\\). Instead of\nstoring a suffix position only store the section in which the suffix position\nstarts. The section numbers can be stored in 16 bits. This would reduce the\nspace requirement for the suffix positions by 50\\%. Searching would require\nto search a complete section using \\Linsearch. However, applying\n\\Linsearch on a small section will not cost too much. Note that\nin each bucket a position can only be stored once.\n\\item\nCompute the smallest common multiple of all pairs of weights to determine\nif the partitions of the weights is unique.\nIf the scm of two weights is smaller, then the partition is is not unique.\n\\item\nThe index becomes so large due to the large number of suffix positions\nto be stored. The basic problem is for each mass to find the sets \nof leaf-weights it is contained in. Each set of leaf weights can be\nstores in constant space. But this does not allow fast retrieval.\n\\item\nIf there are two isomorphic subtrees below \\(\\overline{aw}\\) and\n\\(\\overline{w}\\), then the masses in the subtree are identical up to \nthe addition with \\(\\sigma(a)\\).\n\\item\nEncode the precision value in the index. Check if the programs\nfits to the index.\n\\end{enumerate}\n\n\nkurtz@mahagoni[57] time massbck -size sprot38.fas\ncountleaf = 654521611 (20.59 per input char)\ncountfirstbranch = 69737236 (2.19 per input char)\ntotal number of integers = 724258847 (22.78 integers per input char)\nsize of index: 2764.05 megabytes\n# space peak in megabytes: 0.00\n# mmap space peak in megabytes: 184.01\n160.79u 1.14s 2:41.96 99.9%\n", "meta": {"hexsha": "6f2377e6523c92487792a183606c9d6d8f685000", "size": 30900, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/doc/Massman.tex", "max_stars_repo_name": "gordon/vstree", "max_stars_repo_head_hexsha": "5f2835198eaa489432faf9fb47a802bc0f71b8ad", "max_stars_repo_licenses": ["ISC"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-02-11T21:38:26.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-11T23:47:46.000Z", "max_issues_repo_path": "src/doc/Massman.tex", "max_issues_repo_name": "gordon/vstree", "max_issues_repo_head_hexsha": "5f2835198eaa489432faf9fb47a802bc0f71b8ad", "max_issues_repo_licenses": ["ISC"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-01-11T19:05:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-03T07:02:24.000Z", "max_forks_repo_path": "src/doc/Massman.tex", "max_forks_repo_name": "gordon/vstree", "max_forks_repo_head_hexsha": "5f2835198eaa489432faf9fb47a802bc0f71b8ad", "max_forks_repo_licenses": ["ISC"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-03-09T13:32:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-03T21:58:32.000Z", "avg_line_length": 41.8699186992, "max_line_length": 106, "alphanum_fraction": 0.7268608414, "num_tokens": 9721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3087936505213935}}
{"text": "\\documentclass[../../../../main]{subfiles}\n\\graphicspath{{images/sfm/}}\n\n\\begin{document}\n\n\\paragraph{Structure from motion}\n\nStructure from motion problem is the case of finding a set of 3D points with projection matrices and translation vectors for corresponding views from the set of images. This process is a 3D reconstruction from a sequence of images.\n\nSequential methods are widely used, they are iterative thus reconstruction is done partially, step by step. The process starts with the first image, when the new image is registered algorithm processes new portion of data, performs triangulation and adds new 3D data to the reconstruction model. Initialization is usually achieved by finding fundamental matrix from the first two views and decomposing it \\cite{RichardSzeliski2010}.\n\nThese methods have some complications, first of all, they require huge amount of corresponding points per each image in a sequence. Usually seven or more correspondences must be present at three or more views. Large set of images require too much computational power in order to process these. Secondly, there is a number of structure and motion combinations that are not appropriate for the mentioned methods. These cases might be the camera rotation without any translation or planar scenes. It is impossible to avoid those cases without an expert planning on how to take pictures for the structure from motion sequence \\cite{sfm_theia}. However grouping of pictures by the feature similarities might be a partial answer to the raised problem.\n\nThe most common strategy for registering images is epipolar constraints. It is achieved by using the correspondence of the image from the current view to the image of the previous view. Essential matrix is typically used but intrinsic camera parameters must be known. Its decomposition gives relative camera orientation and translation vector. Figure \\ref{fig:incrementalSfm} illustrates iterative nature of incremental structure from motion.\n\n\\begin{figure} [ht]\n    \\begin{center}\n        \\includegraphics[width=200pt]{incremental_sfm}\n        \\caption{Demonstration of incremental structure from motion \\cite{sfm_theia}.}\n        \\label{fig:incrementalSfm}\n    \\end{center}\n\\end{figure}\n\nOn the other hand, factorization methods do the job simultaneously. These methods belong to the family of batch methods. \\ac{SVD} factorization based linear methods have been created for many affine camera models like orthographic, para-perspective or weak perspective and etc. These methods distribute reconstruction error among all measurements but, unfortunately, they are not applicable for the real world situations because camera lenses have too wide angle thus cannot be approximated as linear \\cite{factorization_sfm}.\n\nLastly, after receiving initial estimations for 3D points and projection matrices it is needed to minimize function cost with the non-linear iterative optimization. This optimization is called bundled adjustment. It, basically, refines camera and structure parameters initial estimations to get those parameters that predict the locations of features among all images in the most efficient way.\n\n\\begin{figure} [!ht]\n  \\centering    \n    \\begin{equation}\n        \\underset{a_j b_i}{min} = \\sum_{i=1}^{n} \\sum_{j=1}^{m} v_{i j} d(Q(a_j, b_i), x_{i j})^2\n        \\label{bundleAdjustmentFormula}\n    \\end{equation}\n  \\caption{Bundle adjustment minimization function.}\n\\end{figure}\n\nIn the equation \\ref{bundleAdjustmentFormula} $a$ is a vector that parametrizes camera and $b$ is a vector for 3D point so that $Q(a_j, b_i)$ is the prediction of $i$ point projection onto $j$ image. Euclidean distance is represented as $d(,)$ where its parameters are vectors.\n\n\\end{document}", "meta": {"hexsha": "a52182095846c361bb0f42c2e17aac8217aa6a5f", "size": 3731, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/Master Thesis/sections/related/computer-vision/theoretical/structure-from-motion.tex", "max_stars_repo_name": "Lewis945/RubiksCubeSolver", "max_stars_repo_head_hexsha": "30926412ef0fce764c9d737940a757ec4f55d3ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/Master Thesis/sections/related/computer-vision/theoretical/structure-from-motion.tex", "max_issues_repo_name": "Lewis945/RubiksCubeSolver", "max_issues_repo_head_hexsha": "30926412ef0fce764c9d737940a757ec4f55d3ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/Master Thesis/sections/related/computer-vision/theoretical/structure-from-motion.tex", "max_forks_repo_name": "Lewis945/RubiksCubeSolver", "max_forks_repo_head_hexsha": "30926412ef0fce764c9d737940a757ec4f55d3ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 95.6666666667, "max_line_length": 745, "alphanum_fraction": 0.7933529885, "num_tokens": 801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3087936505213935}}
{"text": "\\section{Shock wave simulation}\nWe studied the influence of fractions of heavy ions on the shock wave, in particular, the spectrum of particles and the shape of the shock wave. We present results of two simulations with different compositions of the plasma : pure protons and electrons in the first case and with the admixture of alpha particles in the second case. Initially the homogeneous flux is  moving from the right free boundary to the left. On the left side there is a reflecting super-conducting wall, which causes formation of shock wave. Simulations are one-dimensional and have following parameters: initial velocity $v = 0.2c$, number densities $n_e = 10^{-4} \\rm{cm}^{-3}$, $n_p = 10^{-4} \\rm{cm}^{-3}$ in the first simulation and $n_e = 10^{-4} \\rm{cm}^{-3}$, $n_p = 0.6\\cdot10^{-4} \\rm{cm}^{-3}$, $n_\\alpha = 0.2\\cdot10^{-4} \\rm{cm}^{-3}$ in the second, temperature $5\\cdot10^8 \\rm{K}$, magnetic field $B_\\parallel = 10^{-4} \\rm{G}, B_\\perp= 0.7\\cdot10^{-4} \\rm{G}$, the full size of the box $L = 1\\cdot10^{12} \\rm{cm}$, the number of cells $N=2\\cdot10^4$. Electron mass is reduced to $m_e = \\frac{m_p}{20}$. The full time of simulation is $T = 2000 {\\omega_p}^{-1}$.\n\\begin{figure}[h!]\n\t\\centering\n\t\\begin{minipage}{0.49\\textwidth}\n\t\t\\centering\n\t\t%\\includegraphics[width=0.98\\textwidth]{fig/protons.eps} \n\t\t\\caption{Distribution of protons in the simulation without alpha particles.}\n\t\t\\label{protons}\n\t\\end{minipage}\\hfill\n\t\\begin{minipage}{0.49\\textwidth}\n\t\t\\centering\n\t\t%\\includegraphics[width=0.98\\textwidth]{fig/protons_with_He.eps} \n\t\t\\caption{Distribution of protons in the simulation with alpha particles.}\n\t\t\\label{protons_with_alpha}\n\t\\end{minipage}\n\\end{figure}\n\\begin{figure}[h!]\n\t\\centering\n\t\\begin{minipage}{0.49\\textwidth}\n\t\t\\centering\n\t\t%\\includegraphics[width=0.98\\textwidth]{fig/electrons.eps} \n\t\t\\caption{Distribution of electrons in the simulation without alpha particles.}\n\t\t\\label{electrons}\n\t\\end{minipage}\\hfill\n\t\\begin{minipage}{0.49\\textwidth}\n\t\t\\centering\n\t\t%\\includegraphics[width=0.98\\textwidth]{fig/electrons_with_He.eps} \n\t\t\\caption{Distribution of electrons in the simulation with alpha particles.}\n\t\t\\label{electrons_with_alpha}\n\t\\end{minipage}\n\\end{figure}\n\nThe results presented in Figures \\ref{protons}-\\ref{electrons_with_alpha} show that the values of $F(p)p^4$ for high energies are much greater for protons, than for electrons in both simulations. Also electrons need much more time to be accelerated and to form spectrum $\\propto p^{-4}$. It means that protons are injected into the acceleration process more efficiently, and it is consistent with the work of Park et al. {\\cite{Park2015}}. Also we have shown that minority of heavy ions increases the spectrum of protons and do not have influence on the spectrum of electrons. It can be explained by the fact, that heavy ions form the large scale turbulence and protons can efficiently scatter on this turbulence. Otherwise for electrons turbulence produced by protons is already enough large-scale  and the influence of heavy ions is neglectable. \n", "meta": {"hexsha": "aeb87efc51359614d738f93b1b9d4a3a082d3108", "size": 3059, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "papers/Physica2016/shock.tex", "max_stars_repo_name": "eskyhome/PICpp", "max_stars_repo_head_hexsha": "3365e0e36ba46a87e7a406670ed2dbd9f60ef219", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-05-16T01:41:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-17T05:13:23.000Z", "max_issues_repo_path": "papers/Physica2016/shock.tex", "max_issues_repo_name": "eskyhome/PICpp", "max_issues_repo_head_hexsha": "3365e0e36ba46a87e7a406670ed2dbd9f60ef219", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "papers/Physica2016/shock.tex", "max_forks_repo_name": "eskyhome/PICpp", "max_forks_repo_head_hexsha": "3365e0e36ba46a87e7a406670ed2dbd9f60ef219", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-05-16T01:45:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-26T06:43:58.000Z", "avg_line_length": 87.4, "max_line_length": 1152, "alphanum_fraction": 0.7512258908, "num_tokens": 898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.30879364281505256}}
{"text": "\\documentclass{article}\n\n\\usepackage{graphicx}\n\\usepackage[utf8]{inputenc}\n\\usepackage[english]{babel}\n\\usepackage{authblk}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{amsthm}\n\\usepackage{titling}\n\\usepackage{float}\n\\usepackage{mathtools}\n\\usepackage{tabularx}\n\n\\DeclareMathOperator*{\\argmax}{arg\\,max}\n\\DeclareMathOperator*{\\argmin}{arg\\,min}\n\n\\newtheorem{theorem}{Theorem}[section]\n\\newtheorem{proposition}{Proposition}[section]\n\\newtheorem{corollary}{Corollary}[theorem]\n\\newtheorem{lemma}[theorem]{Lemma}\n\n\\theoremstyle{definition}\n\\newtheorem{definition}{Definition}[section]\n\n\\theoremstyle{definition}\n\\newtheorem{example}{Example}[section]\n\n\\newtheorem{xca}[theorem]{Exercise}\n\n\\newtheorem{remark}[theorem]{Remark}\n\n\\setlength{\\abovedisplayskip}{5pt}\n\\setlength{\\belowdisplayskip}{5pt}\n\\setlength{\\abovedisplayshortskip}{5pt}\n\\setlength{\\belowdisplayshortskip}{5pt}\n\n\\renewcommand*{\\Affilfont}{\\normalsize\\normalfont}\n\\renewcommand*{\\Authfont}{\\bfseries}\n\n\\newcounter{protocol}\n\\newenvironment{protocol}[1]\n  {\\par\\addvspace{\\topsep}\n   \\noindent\n   \\tabularx{\\linewidth}{@{} X @{}}\n    \\hline\n    \\refstepcounter{protocol}\\textbf{Protocol \\theprotocol} #1 \\\\\n    \\hline}\n  { \\\\\n    \\hline\n   \\endtabularx\n   \\par\\addvspace{\\topsep}}\n\n\\newcommand{\\sbline}{\\\\[.5\\normalbaselineskip]}% small blank line\n\n\\title{Algorithmic Governance Design for Cryptocurrency Protocols}\n\n\\author{Drew Stone}\n\n\\begin{document}\n\\maketitle\n\\begin{abstract}\nWe tryna do adaptive, autonomous governance yo.\n\\end{abstract}\n\\section{Introduction}\nGovernance is a topic that spans numerous fields like political science, economics, and, for our matter, computer science. In the world of blockchains, governance is the topic that embodies how cryptocurrencies evolve and grow. Participants act in a variety of ways according to ever-changing incentives according to a mechanism that defines the feasible set of actions. Oftentimes, blockchain governance garners dogmatic behavior from maximalists of different currencies, who flout the benefits of certain governance structures. In this paper, we discuss this and try to ascertain whether this behavior carries any weight when designing incentivized technology. We systematically build governance mechanisms using tools from algorithmic game theory, mechanism design, and computer science. Specifically, we formalize a number of governance objectives and solve them using distributed optimization techniques.\n\n\\section{Background}\nBlockchain governance in the context of this paper describes the set of interactive mechanisms that control a cryptocurrency protocol's evolution. For example, in existing blockchains, miners or validators selectively decide which transactions to process by selecting the highest-paying transactions (or none at all). In other protocols, miners and validators decide how large blocks should be within certain ranges. The mechanisms available to these agents largely define the dynamics of the underlying protocol.\n\nFor settings such as these, we, as the mechanism designers, want to build a governance mechanism for blockchain protocols that optimize certain properties. First and foremost is defining the mechanism designer's goal.\n\n\\begin{definition}\nA \\textit{blockchain governance mechanism designer} $\\mathcal{M}(\\mathcal{P})$ is primarily concerned with finding a feasible policy $\\pi^*\\in \\Pi_f$ over the system's state $s\\in \\mathcal{S}$ that maximizes the following quantities:\n\\begin{itemize}\n    \\item The throughput or transactions per second (\\text{\\fontfamily{lmss}\\selectfont tps}) of the protocol $\\mathcal{P}$.\n\n    \\item The decentralization (\\text{\\fontfamily{lmss}\\selectfont dec}) of the protocol $\\mathcal{P}$.\n\\end{itemize}\n\\end{definition}\n\\begin{proposition}\n$\\mathcal{M}(\\mathcal{P})$ is concerned with finding a policy $\\pi^*\\in \\Pi_f$ for any state $s\\in\\mathcal{S}$ that optimizes an objective function $\\varphi$ of the quantities above:\n\\begin{align*}\n    \\pi^*(s) \\in \\argmax_{\\pi \\in \\Pi_f}\n    \\varphi(\\text{\\fontfamily{lmss}\\selectfont tps($\\mathcal{P}(\\pi))$}, \\text{\\fontfamily{lmss}\\selectfont dec($\\mathcal{P}(\\pi))$})\n\\end{align*}\n\\end{proposition}\nPrevious work \\cite{previous work} has shown that increasing the throughput of many protocols leads to both a decrease in security and decentralization. This is due largely in the heterogeneity of participants in the protocol who will fail to keep up with higher throughput demand. As a result, less participants secure the information contained in the ledger and the network becomes more susceptible to malicious attacks such as 51\\% attacks.\n\nWhile much of the research in the blockchain space has focused on building protocols whose tradeoff between throughput and decentralization is less severe along any axis, none of the research has tried to optimize the governance policy utilized for balancing any such tradeoff. By casting the protocol designer's objective as a multi-objective optimization problem, any interested designer can select the tradeoff within the hyperparameters of the model. Therefore, finding an optimal policy for a given set of hyperparameters remains the main goal.\n\n\\section{A model for governance mechanisms}\n\\begin{definition}\nWe define a blockchain protocol $\\mathcal{P}$ over an abstract state space $B$ to be a tuple $\\langle \\mathcal{V}, \\mathcal{O}, P, \\pi, \\mathcal{R}\\rangle$ such that at any round $t$ there exists the following:\n\\begin{itemize}\n    \\item A set of $n$ active nodes $V\\subseteq \\mathcal{V}$.\n    \\item A leader election oracle $\\mathcal{O}(V)$ with distribution $\\mathcal{D}$.\n    \\item A payment rule $P:B^n\\longrightarrow \\mathbb{R}^n$.\n    \\item A governance rule $\\pi:B^n\\longrightarrow \\mathcal{A}$ where $\\mathcal{A}$ denotes the set of alternatives.\n    \\item A reward $\\mathcal{R}$ for the leader elected at each round.\n\\end{itemize}\n\\end{definition}\n\n\\begin{definition}\nA \\textit{miner, validator, node} or \\textit{agent} $i\\in V$ is a participant of a blockchain protocol with the following properties and responsibilities:\n\\begin{itemize}\n    \\item $i$ has some probability of being selected to mine a block $\\mathcal{O}(i)\\in [0,1]$ such that $\\sum_{i\\in V}\\mathcal{O}(i) = 1$.\n    \\item $i$ has private, local information $b_i\\in B$.\n    \\item $i$ has a valuation function over alternatives $v_i: \\mathcal{A}\\longrightarrow \\mathbb{R}$.\n    \\item $i$ has some utility $\\forall \\textbf{b}=(b_1,\\cdots,b_n)\\in B^n$ defined with respect to a given payment and governance rule.\n    \\begin{align*}\n        u_i(\\pi(\\textbf{b}),P(\\textbf{b})) = \\mathcal{R}\\cdot\\textbf{I}[\\mathcal{O}(V)=i] + v_i(\\pi(\\textbf{b})) - P(\\textbf{b})_i\n    \\end{align*}\n    \\textit{We use the subscript $i$ notation over vectors to denote the value at the $i$'th index of the vector.}\n\\end{itemize}\n\\end{definition}\n\n\\subsubsection{Ideal functionality}\n\\begin{definition}\nWe call $\\mathcal{P}$ \\textit{incentive-compatible} if $\\forall i\\in V$ with private state $\\textbf{b}\\in B^n,~\\forall b'\\in B$, the following holds:\n\\begin{align*}\n    \\mathbb{E}[u_i(\\pi(\\textbf{b}), P(\\textbf{b}))] \\geq \\mathbb{E}[u_i(\\pi(b',\\textbf{b}_{-i}), P(b', \\textbf{b}_{-i}))]\n\\end{align*}\n\\textit{i.e. for any reports of private states, a node always maximizes its expected utility by reporting its true private state when all other agents do so as well.}\n\\end{definition}\n\\begin{definition}\nWe call $\\mathcal{P}$ \\textit{individually-rational} if $\\forall i\\in V$ with private state $\\textbf{b}\\in B^n$, the following holds:\n\\begin{align}\n    \\mathbb{E}[u_i(\\pi(\\textbf{b}), P(\\textbf{b}))] \\geq 0\n\\end{align}\n\\end{definition}\n\nAs is typical with mechanism design, our ideal functionality is an incentive compatible and individually rational protocol $\\mathcal{P}$. We could also strive for budget-balanced or feasible mechanisms, defined as never running a deficit with respect to payments, but we have access to a monetary minting process that provides new functionality than traditionally available. We gloss over this concept primarily because a blockchain protocol allows us to mint a quantity $\\mathcal{R}$ of money each round. Therefore, it is not unreasonable to imagine the mechanism using inflationary processes to balance incentives with payment rules that incur deficits.\n\n\\subsubsection{A taxonomy of governance rules}\n\\begin{definition}\nWe call $\\pi$ a \\textit{constant} governance rule if at each round $t$ and $\\forall \\textbf{b}\\in B^n$, $\\pi$ always outputs the same alternative $a\\in \\mathcal{A}$:\n\\begin{align*}\n    \\pi(\\textbf{b}) = a\n\\end{align*}\n\\end{definition}\nThis describes the governance mechanism of Bitcoin since it requires a hard fork--through a new mechanism--to change the fixed alternative/block size chosen. There is no adaptability to different environments and as such presents both interesting and contentious discussion in different ecosystems.\n\\begin{definition}\nWe call $\\pi$ a \\textit{leader-based} governance rule if at each round $t$ and $\\forall \\textbf{b}\\in B^n$, $\\pi$ always outputs the alternative signalled by the chosen leader:\n\\begin{align*}\n    \\pi(\\textbf{b}) &= b_{i}\\text{ such that }i = \\mathcal{O}(V)\n\\end{align*}\n\\textit{i.e. the governance rule selects the information/alternative signalled by the elected leader $\\mathcal{O}(V)$. For simplicity, let $\\mathcal{A}=B$ so that leaders bid for their desired future alternatives. If leaders are rational or \"selfish\" then we get that:}\n\\begin{align*}\n\\pi(\\textbf{b}) = a^*\\text{ such that }a^* \\in \\argmax_{a\\in \\hat{\\mathcal{A}}} v_i(a)\n\\end{align*}\n\\textit{where $\\hat{\\mathcal{A}}$ denotes the feasible alternative set according to some globally known restriction.}\n\\end{definition}\nIn Ethereum for example, the miner $i$ that wins the proof of work process can set the next block gas limit within some bounded range with respect to the previous block's gas limit, usually 0.1\\% higher or lower. Therefore, this is analogous to a protocol $\\mathcal{P}$ receiving the vector $(\\_,\\dots,b_i,\\dots,\\_,)$ where the $i$'th entry corresponds to miner $i$ participating in the protocol. While we abuse notation since in proof of work blockchains we don't exactly know how many miners are participating, it is sufficient that we know there is some number $n$ of participants as described in the mechanism and only one is elected as a leader each round.\n\\begin{definition}\nWe call $\\pi$ a \\textit{social-welfare maximizing} governance rule if at each round $t$ and $\\forall \\textbf{b}\\in B^n$, $\\pi$ always outputs an alternative that maximizes (resp. minimizes) the valuations (resp. costs) of all participants:\n\\begin{align*}\n    \\pi(\\textbf{b}) &= a^*\\text{ such that } a^*\\in \\argmax_{a\\in \\hat{\\mathcal{A}}} \\sum_{i\\in V} v_i(a)\n\\end{align*}\n\\end{definition}\n\\section{Single Parameter Governance}\nWe begin our search for \\textit{incentive-compatible} blockchain protocols over single parameter governance rules where $\\mathcal{A}=\\mathbb{R}$ or $\\mathbb{Z}$. Single parameter governance rules are useful for determining parameters such as a block size or a block gas limit each round. Additionally, we are interested in mechanisms that incentivize truthfulness of reporting private state.\n\n\\subsubsection{Single peaked preferences}\nWe consider a model where agents have single peaked preferences over alternatives $a\\in \\mathcal{A}$ with the following structure:\n\\begin{align*}\nv_i(a) \\begin{cases} \n      a & a\\leq b_i \\\\\n      0 & otherwise\n   \\end{cases}\n\\end{align*}\n\\begin{definition}\nFor each agent $i\\in V$, the value $b_i$ as used above is known as the \\textit{bliss point}. We will often describe the agent's \\textit{bliss point} as their \\textit{tolerance} or \\textit{capacity}.\n\\end{definition}\n\nSince agents have single-peaked utilities at the bliss points $\\textbf{b} = (b_1,\\dots, b_{|V|})$, we can consider the agents in sorted order by their points: $b_1\\leq b_2\\leq \\dots\\leq b_{|V|}$. Oftentimes, we represent bold-faced variables such as \\textbf{b} and \\textbf{v} as sets (in most cases ordered), so that an agent $i$'s report $b_i\\in \\textbf{b}$ and valuation $v_i\\in\\textbf{v}$.\n\n\\subsection{Mechanisms without dropout}\nWe start by considering a model with the following premise: if the current parameter is $\\hat{b}$, any agent $i\\in V$ with bliss point $b_i< \\hat{b}$ does not drop out of the mechanism. They still provide their bids, albeit earning no positive utility.\n\\subsubsection{Median Mechanisms}\nGiven single-peaked preferences over alternatives, a natural thing to analyze is the median mechanism, which chooses the alternative denoted by the median bliss point over a set of agents or voters $V$. This immediately leads us to our first mechanism and the following proposition:\n\n\\begin{theorem}[\\textbf{Moulin 1980}]\nThe Median mechanism over single-peaked preferences \\textbf{v} that selects the median bliss point $b_{median}$ is truthful and Pareto-efficient.\n\\end{theorem}\n% \\begin{proof}\n% Using a plurality voting protocol, where agents vote for a single alternative, the median alternative chosen coincides with the median bliss point and bliss points are reported truthfully as follows.\n\n% Consider a voter $i$ whose bliss point $b_i<b_{median}$, i.e. voter $i$ falls on the left of voter $median$ according to the order of \\textbf{b}. The only way for $i$ to manipulate the vote is by reporting $\\hat{b}_i > b_{median}$ since anything different but still to the left of $b_{median}$ will result in the same median. However, if $i$ reports, untruthfully, a value greater than $b_{median}$ it will increase the median, leading to a weakly worse-off outcome since $v_i(a)=0,~\\forall a> b_i$. The same argument proves truthfulness in the reverse direction and so we have truthfulness. The median is also Pareto-efficient from this analysis, since any change in a vote that might make one voter better off, certainly makes another voter worse off.\n\n% Instead of a plurality voting protocol, we can also consider a majority voting protocol over the entire preference profiles of reporters. Given a feasible, ordered set of alternatives $\\textbf{a}=\\{a_1,\\cdots, a_k\\}\\subseteq \\mathcal{A}$ such that $\\textbf{b}\\subseteq \\textbf{a}$, for each agent $i\\in V$, we can represent their preferences as\n% $$\n% v_i(a_{i_1}) \\preceq v_i(a_{i_2}) \\preceq \\cdots \\preceq v_i(b_i)\n% $$\n% Then since \\textbf{b} is ordered, the median reporter's preference profile restricted to \\textbf{b} looks like the following. Let $m$ denote the index of the \\textit{median} reporter.\n% $$\n% v_{m}(b_{m+1}) \\preceq v_{m}(b_{m+2}) \\preceq \\cdots \\preceq v_{m}(b_{m})\n% $$\n% From single-peakedness, we know $v(b_{m+i})=0,~\\forall i>0$. We also know that each reporter of index $m+i,~\\forall i > 0$ prefers $b_m$ to any lower bliss point. Therefore, the median report $b_m$ has the majority of votes according to the preference profiles of all reporters; that is, the median receives at least half the votes, coinciding with exactly half the votes when all bliss points are distinct. \n% \\end{proof}\n\nContrary to median mechanisms in other domains \\cite{DBLP:journals/corr/BlumrosenD16}, the median mechanism may perform very poorly under certain distributions of bliss point vectors or player capacities. This occurs when the capacity of a single agent far outweighs the capacity of the rest of the agents. Therefore, while the median ensures the number of players with non-zero utility is at least half and that they report truthfully, it does not guarantee that any approximation to optimal social welfare under any distribution.\n\n\\begin{proposition}\nThere exist distributions $\\mathcal{D}$ over bliss points \\textbf{b} such that the Median mechanism is not a 2-approximation of optimal social welfare.\n\\end{proposition}\n\\begin{proof}\nGiven a bliss point vector \\textbf{b} = $\\{1,2,k\\},~\\forall k > 8$, the median mechanism does substantially worse than $\\frac{1}{2}$ the optimal social welfare as $k\\longrightarrow \\infty$. The median $\\forall k \n\\geq 2$ will be 2, leading to a social welfare of $4$. Therefore, for any value $k > 8$, the median mechanism achieves less than half the optimal welfare which is $k$.\n\\end{proof}\n\nA natural question to ask is under what assumptions do median mechanisms perform well with respect to the optimal social welfare. We now introduce some definitions that will allow us to design a modified median mechanism and argue for a 2-approximation to optimal social welfare.\n\\begin{definition}\nThe \\textit{Weighted Median} mechanism is defined over an ordered multi-set of weighted bliss points \\textbf{b} = $\\{(b_1, w_1),\\cdots,(b_n, w_n)\\}$ outputs the element $b_k$ that is incident where at most half the weight falls.\n$$\nb_k = \\sup\\{b_i~|~\\sum_{j=1}^i w_j \\leq \\frac{\\sum_{j=1}^n w_j}{2}\\}\n$$\n\\end{definition}\n\\begin{proposition}\nFor weight distributions $\\mathcal{D}$ proportional to a node's bliss point or capacity where no player has $\\geq 50\\%$ of weight, the Weighted Median mechanism achieves a 2-approximation to optimal social welfare.\n\\end{proposition}\n\\begin{proof}\nLet the weights \\textbf{w} be defined for each player as \n$$\n\\forall i\\in V,~w_i = \\frac{b_i}{\\sum_{j} b_j},~w_i\\leq \\frac{1}{2}\n$$. We want to show that if $b_k=\\pi(\\textbf{b})$ that $\\sum_{i\\in V}v_i(b_k)\\geq \\frac{1}{2} OPT$. If $\\exists w_j = \\frac{1}{2}$, notice that $b_k=b_{j-1}$. The social welfare is then \n$$\n\\sum_{i\\in V} v_i(\\pi(\\textbf{b})) \\geq 2\\cdot \\pi(\\textbf{b})\n$$\nSince $b_j \\leq 2\\cdot \\pi(\\textbf{b})$ by definition, we have that the welfare attained by $\\pi(\\textbf{b})$ is at least $\\frac{1}{2}OPT$.\n\nIf no bliss point has half the weight, then this implies that it is closer to $\\pi(\\textbf{b})$. Therefore, if $\\pi(\\textbf{b})$ is not the optimal bliss point, the bliss point yielding the optimal welfare yields the following:\n\\begin{align*}\nOPT &\\leq 2\\cdot \\sum_{i\\in V} v_i(\\pi(\\textbf{b})) \\\\\n\\frac{1}{2} OPT &\\leq \\sum_{i\\in V} v_i(\\pi(\\textbf{b}))\n\\end{align*}\n\\end{proof}\nThis claim tells us that we have a good approximation to the optimal social welfare when we have the assumptions set forth by blockchain protocols. We usually assume that no more than half of the computational power concentrates in the hands of a single individual. Therefore, as long as that holds over a Proof of Work based cryptocurrency, the median selection of parameters will give us a 2-approximation of the optimal social welfare.\n\n\\subsubsection{VCG Mechanisms}\nIn many settings, especially if there is a cost to reporting one's bliss point, we need to properly incentivize the reports while also preserving truthfulness. Here, we turn another realm of mechanism design that uses money to elicit reports from players such that the reports are truthful.\n\\begin{theorem}\nThe VCG mechanism over bids \\textbf{b} is truthful, individually rational, and social-welfare maximizing with $\\pi(\\textbf{b})\\in \\argmax_{b\\in \\textbf{b}} \\sum_{i\\in V} v_i(b)$. If $i^*$ is the index of $\\pi(\\textbf{b})\\in \\textbf{b}$, the mechanism charges the following payment to each agent $i$:\n\\begin{align*}\n    P(\\textbf{b})_i &= (\\max_{j\\neq i,~j\\in V} (n-j+1)\\cdot b_j - v_i(b_j)) - ((n-i^*)\\cdot b_{i^*} - v_i(b_{i^*}))\n\\end{align*}\n\\end{theorem}\n\\begin{proof}\nThe VCG mechanism charges as payment the externality that individual players impose on the social welfare of the entire group and is known to incentivize truthfulness. Starting from the VCG objective, we have that $\\pi(\\textbf{b}) = \\argmax_{b\\in \\textbf{b}}\\sum_{i\\in V} v_i(b)$, which by definition maximizes the social welfare. \n\nUsing similar notation as above, we let $\\pi_{-i}(\\textbf{b}_{-i})$ be the social-welfare maximizing alternative for the mechanism without agent $i\\in V$. We let $j^*$ be the index of $\\pi_{-i}(\\textbf{b}_{-i})\\in \\textbf{b}$. The VCG payment is computed as:\n\\begin{align*}\n    P(\\textbf{b})_i &= \\sum_{j\\neq i}v_j(\\pi_{-i}(\\textbf{b}_{-i})) - \\sum_{j\\neq i}v_j(\\pi(\\textbf{b})) \\\\\n    &= \\sum_{j\\neq i} v_j(\\pi_{-i}(\\textbf{b}_{-i})) - (n-i^* + 1)\\cdot b_{i^*} - v_i(b_{i^*}) \\\\\n    &= (n-j^* + 1)\\cdot b_{j^*} - v_i(b_{j^*}) - (n-i^* + 1)\\cdot b_{i^*} - v_i(b_{i^*}) \\\\ \n    &= (\\max_{j\\neq i,~j\\in V} (n-j+1)\\cdot b_j - v_i(b_{j})) - ((n-i^*+1)\\cdot b_{i^*} - v_i(b_{i^*}))\n\\end{align*}\nFor each agent $i$ with $b_i < \\pi(\\textbf{b})$, it follows that when $i$ has insufficient capacity to participate, $i$ has no affect whether he/she participates or not.. The welfare from $\\pi_{-i}(\\textbf{b}_{-i}) = \\pi(\\textbf{b})$ and consequently generate the same social welfare. Furthermore, agent $i$ is charged zero payment.\n\\end{proof}\n% \\subsection{Byzantine Agreement}\n% Consider a Byzantine Agreement protocol $\\mathcal{P}$ that builds a blockchain and manages a governance mechanism over its blocksize as described above. Further, let each miner also be identical in terms of computational power. As is common with these protocols, $|V|=3f+1$ where $f$ denotes the number of byzantine nodes.\n\n% \\begin{definition}\n% A miner $i$ is identical to a miner $j$ if $\\hat{b}_i=\\hat{b}_j$; that is, miners are identical if their true private states are equal.\n% \\end{definition}\n% \\begin{definition}\n% $\\forall i\\in V$ the private state $b_i\\in \\mathbb{R}$ is the true processing capacity of miner $i$'s hardware.\n% \\end{definition}\n% We now describe the protocol in detail. We assume the existence of digital signatures for each agent $i\\in V$, denoted by $\\sigma_i$. The protocol works by aggregating at least $n-f$ private state reports $\\textbf{b}_{n-f}$ and then computing the new alternative $a$. We inherit the logic of the Practical Byzantine Fault Tolerant protocol introduced by Castro and Liskov for building the underlying state machine. To that end, we modify the protocol to include new messages that enable the aggregation of state reports \\textbf{b} and to build a blockchain.\n% \\begin{protocol}{Byzantine Fault Tolerant Governance}\n% \\textit{Inputs.} At round $t$, $\\forall i\\in V$ with $b^t_i$, $H=\\{(a^0,\\emptyset),\\dots,(a^{t-2},\\textbf{b}^{t-1})\\}$.\n% \\sbline\n% \\textit{Goal.} $\\mathcal{O}(V)$ uses block size $a^t_{\\mathcal{O}(V)}=\\pi(\\textbf{b}, H\\cup\\{(a^{t-1}, \\textbf{b}^t\\})$ to build block $t$.\n% \\sbline\n% \\textit{The protocol:}\n% \\begin{enumerate}\n%   \\item \\textbf{Setup.}\n%   \\begin{enumerate}\n%     \\item $\\forall i\\in V,~i$ computes $b^t_i$ from $a^{t-1}$ and broadcasts $\\langle (a^{t-1}, b^t_i)\\rangle_{\\sigma_i}$\n%     \\item $\\forall i\\in V,~i$ collects $n-f$ reports $\\{\\langle(a^{t-1}, b^t_j)\\rangle_{\\sigma_j}\\}_{j\\in I\\subseteq V}$\n%     \\item $\\forall i\\in V,~i$ builds $\\langle (a^{t-1}, \\textbf{b}^t)_{\\sigma}\\rangle$ with at most $f$ empty slots in $\\textbf{b}^t$.\n%     \\item $\\forall i\\in V,~i$ computes $a^t_i = \\pi(\\textbf{b}^t, H\\cup\\{(a^{t-1}, \\textbf{b}^t)\\}$.\n%     \\item $\\forall i\\in V,~i$ broadcasts $\\langle a^t_i, H\\cup\\{(a^{t-1}, \\textbf{b}^t)_{\\sigma}\\}\\rangle$\n%   \\end{enumerate}\n% \\end{enumerate}\n\n% \\end{protocol}\n\\end{document}\n", "meta": {"hexsha": "9d81d5643eeb87e5d741a6dabb8e9944c677e991", "size": 22894, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "writeup/paper.tex", "max_stars_repo_name": "drewstone/dynamic-governanceq", "max_stars_repo_head_hexsha": "924317800db7bca6308ff912b16c7b834ab30e32", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "writeup/paper.tex", "max_issues_repo_name": "drewstone/dynamic-governanceq", "max_issues_repo_head_hexsha": "924317800db7bca6308ff912b16c7b834ab30e32", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "writeup/paper.tex", "max_forks_repo_name": "drewstone/dynamic-governanceq", "max_forks_repo_head_hexsha": "924317800db7bca6308ff912b16c7b834ab30e32", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 79.2179930796, "max_line_length": 909, "alphanum_fraction": 0.7406744125, "num_tokens": 6459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030761371502, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.30879364281505245}}
{"text": "\\section{\\uppercase{Best views estimation}}\\label{sec:best-views-estimation}\n\n\\noindent Estimation of the best views for a constellation of sensors requires both the ability to generate accurate sensor data for each type of sensor and also an efficient approach to compute the surface coverage that we are trying to maximize. The next sections explain how the sensor data is analyzed and also present the approaches used to estimate the best constellation of sensors for a given simulation world.\n\n\\subsection{Reference surface point cloud}\n\nThe first step in the processing pipeline includes the generation of the multi-object reference point cloud (described in \\cref{alg:reference-pointcloud}) that is built by transforming the point cloud associated with the target \\gls{cad} model into each target object within the simulation world (example shown in \\cref{fig:reference-cloud}). Later on, the reference point cloud in the world coordinate frame is filtered with a voxel grid algorithm in order to perform a regular space partition and extract the surface voxels centroids that contain points. This approach allows to generate a reference point cloud with a constant surface point density, which will be critical later on when computing the surface coverage percentage achieved with a given sensor constellation.\n\n\\begin{algorithm}\n\t\\caption{Generation of the reference point cloud}\n\t\\label{alg:reference-pointcloud}\n\t\\begin{algorithmic}[1]\n\t\t\\State \\textbf{Input:}\n\t\t\\State $P \\gets$ CAD model point cloud\n\t\t\\State $N \\gets$ target objects simulation names\n\t\t\\State $F \\gets$ cell size for the voxel grid filter\n\t\t\\Procedure{ReferencePointCloud}{$P,N,F$}\n\t\t\t\\State $r \\gets Empty$\\Comment{merged point cloud}\n\t\t\t\\ForAll{n names in N}\n\t\t\t\t\\State $w \\gets GetModelWorldPose(n)$\n\t\t\t\t\\State $p \\gets TransformPointCloud(P,w)$\n\t\t\t\t\\State $r \\gets Merge(r,p)$\n\t\t\t\\EndFor\n\t\t\t\\State $r \\gets FilterWithVoxelGrid(r,F)$\n\t\t\t\\State \\textbf{return} $(r)$\n\t\t\\EndProcedure\n\t\\end{algorithmic}\n\\end{algorithm}\n\n\\begin{figure}\n\t\\centering\n\t\\includegraphics[height=.14\\textheight]{sensor-data-processing/multimodel-environment}\\hspace{2em}\n\t\\includegraphics[height=.1\\textheight]{sensor-data-processing/cad-model-pointcloud}\n\t\\includegraphics[height=.14\\textheight]{sensor-data-processing/multimodel-pointclouds-with-cad}\\hspace{2em}\n\t\\includegraphics[height=.14\\textheight]{sensor-data-processing/multimodel-pointclouds}\n\t\\caption{The first image illustrates the color scene rendering in Gazebo with the target objects in green while the third and fourth images display the reference point cloud that was generated using the CAD point cloud shown on the second image.}\n\t\\label{fig:reference-cloud}\n\\end{figure}\n\n\n\\subsection{Sensors data analysis}\n\nAfter loading the simulation world 3D models, deploying the sensors populations on the environment and building the filtered reference point cloud, the proposed system generates a color and depth image for every sensor. Then, for each pixel in the color images that have the target objects unique color, the corresponding pixel in the depth image is retrieved and using the pinhole model equations shown in \\cref{eq:pointcloud}, the 3D point is computed from the 2D pixel coordinates and depth value. Later on, the 3D point is transformed from the sensor coordinate system into the world coordinate frame (having all sensor data in the same coordinate system allows fast merging of point clouds from several sensors). After processing all pixels of a given color image, the associated point cloud in the world coordinate frame is filtered with a voxel grid algorithm with a cell size tuned for the objects geometry we are trying to observe (given that too many points on a small area for a large object do not provide a significant advantage for 3D perception and require more processing time). This allows to perform a regular space partition for extracting the centroid of each voxel containing sensor points. This step is critical for allowing consistent evaluation of the object(s) observed surface area percentage, given that sensors with different resolution or at varying distances may generate point clouds with different point density even when observing the same surface area. Moreover, given that both the reference point cloud and the sensor data point cloud were filtered in the same coordinate frame and with the same voxel grid cell size, the surface coverage percentage can be computed very efficiently by simply dividing the number of surface points in the filtered sensor data point cloud by the number of surface points in the filtered reference point cloud.\n\nIn the end of the sensor analysis stage (presented in \\cref{alg:sensor-analysis}), each sensor is associated with a filtered point cloud in the world coordinate frame containing only points belonging to the target objects surface.\n\n\\begin{algorithm}\n\t\\caption{Sensor analysis}\n\t\\label{alg:sensor-analysis}\n\t\\begin{algorithmic}[1]\n\t\t\\State \\textbf{Input:}\n\t\t\\State $S \\gets$ deployed sensors\n\t\t\\State $C \\gets$ target objects unique color\n\t\t\\State $F \\gets$ cell size for the voxel grid filter\n\t\t\\Procedure{SensorAnalysis}{$S,C,F$}\n\t\t\t\\State $v \\gets Empty$\\Comment{sensors filtered point clouds}\n\t\t\t\\ForAll{s sensors in S}\n\t\t\t\t\\State $c \\gets RenderColorImage(s)$\n\t\t\t\t\\State $d \\gets RenderDepthImage(s)$\n\t\t\t\t\\State $w \\gets GetSensorWorldPose(s)$\n\t\t\t\t\\State $u \\gets Empty$\\Comment{target objects points}\n\t\t\t\t\\ForAll{y image rows in c}\n\t\t\t\t\t\\ForAll{x image columns in c}\n\t\t\t\t\t\t\\State $p \\gets GetPixel(c,x,y)$\n\t\t\t\t\t\t\\If{$p = C$}\n\t\t\t\t\t\t\t\\State $k \\gets GetDepth(d,x,y)$\n\t\t\t\t\t\t\t\\If{$InValidRange(k,s)$}\n\t\t\t\t\t\t\t\t\\State $j \\gets 3DPoint(k,x,y,s)$\n\t\t\t\t\t\t\t\t\\State $m \\gets TransformPt(j,w)$\n\t\t\t\t\t\t\t\t\\State $AppendPoint(u,m)$\n\t\t\t\t\t\t\t\\EndIf\n\t\t\t\t\t\t\\EndIf\n\t\t\t\t\t\\EndFor\n\t\t\t\t\\EndFor\n\t\t\t\t\\State $z \\gets FilterPointCloud(u,F)$\n\t\t\t\t\\State $AppendPointCloud(v,z)$\n\t\t\t\\EndFor\n\t\t\t\\State \\textbf{return} $(v)$\n\t\t\\EndProcedure\n\t\\end{algorithmic}\n\\end{algorithm}\n\n\\footnotesize\n\\begin{equation}\\label{eq:pointcloud}\n\t\\begin{split}\n\t\tX = \\frac{(PixelCol - XPrincipalPoint) \\times PixelDepth}{XFocalLenght}\\\\\n\t\tY = \\frac{(PixelRow - YPrincipalPoint) \\times PixelDepth}{YFocalLenght}\\\\\n\t\tZ = PixelDepth\n\t\\end{split}\n\\end{equation}\n\\normalsize\n\n\\begin{figure}\n\t\\centering\n\t\\includegraphics[height=.132\\textheight]{sensor-data-processing/sensors-best-view}\\\\\n\t\\vspace{0.5em}\n\t\\includegraphics[height=.132\\textheight]{sensor-data-processing/rviz-sensor-view}\\hspace{2em}\n\t\\includegraphics[height=.132\\textheight]{sensor-data-processing/rviz-sensor-view-without-cad-with-model}\n\t\\caption{Color image rendered with the Gazebo simulator (top image containing the scene and sensor) along with the generated point cloud for the target object taking into consideration the environment occlusions (bottom images, in which the green spheres are the observed points and the blue spheres are from the filtered point cloud of the associated CAD model).}\n\t\\label{fig:sensor-data-processing}\n\\end{figure}\n\n\n\\subsection{Estimation of the best sensors views}\n\nWhen only one sensor is needed for the task at hand (for example when we are trying to perform 3D perception of the environment in which the sensor is attached to a robotic arm), the estimation of the best sensor can be performed by simply selecting the one that achieved the best surface coverage percentage. On the other hand, if several sensors are available or we want a single sensor to observe the target objects from a set of N best views, then it is used a \\gls{ransac} approach to estimate the constellation of sensors that can achieve the best surface coverage. This approach allows to mitigate and bound the combinatorial explosion that happens when we need to estimate a high number of best views from a large population of sensors. As can be seen in \\cref{alg:best-n-views}, this approach runs at most a fixed number of iterations. In each iteration, a set of N sensors are chosen randomly, their sensor data is merged and filtered, and if the surface coverage percentage achieved by this set of views is higher than a given threshold, then the search is stopped. In the end, it is returned the best sensor constellation found along with its associated point could (with the merged sensor data) and the best surface coverage percentage that was achieved.\n\n\\begin{algorithm}\n\t\\caption{Estimation of the best N sensors views}\n\t\\label{alg:best-n-views}\n\t\\begin{algorithmic}[1]\n\t\t\\State \\textbf{Input:}\n\t\t\\State $N \\gets$ number of desired sensors\n\t\t\\State $P \\gets$ point clouds from each deployed sensor\n\t\t\\State $F \\gets$ cell size for the voxel grid filter\n\t\t\\State $C \\gets$ minimum surface coverage percentage\n\t\t\\State $I \\gets$ maximum number of iterations\n\t\t\\Procedure{BestSensorsViews}{$N,P,F,C,I$}\n\t\t\t\\State $s \\gets Empty$\\Comment{best coverage sensors}\n\t\t\t\\State $p \\gets Empty$\\Comment{best merged point cloud}\n\t\t\t\\State $c \\gets 0$\\Comment{best coverage percentage}\n\t\t\t\\State $i \\gets 0$\\Comment{current iteration}\n\t\t\t\\While{$i < I$ and $c < C$}\n\t\t\t\t\\State $x \\gets SelectSensorsRandomly(P,N)$\n\t\t\t\t\\State $m \\gets MergePointClouds(P,x)$\n\t\t\t\t\\State $f \\gets FilterPointCloud(m,F)$\n\t\t\t\t\\State $k \\gets ComputeSurfaceCoverage(f)$\n\t\t\t\t\\State $i \\gets i + 1$\n\t\t\t\t\\If{$k > c$}\n\t\t\t\t\t\\State $s \\gets x$\n\t\t\t\t\t\\State $p \\gets f$\n\t\t\t\t\t\\State $c \\gets k$\n\t\t\t\t\\EndIf\n\t\t\t\\EndWhile\n\t\t\t\\State \\textbf{return} $(s,p,c)$\n\t\t\\EndProcedure\n\t\\end{algorithmic}\n\\end{algorithm}\n", "meta": {"hexsha": "f3da36345f72d9dc6b461d4317fe333220cfc338", "size": 9413, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/sections/best-views-estimation.tex", "max_stars_repo_name": "carlosmccosta/active_perception_article", "max_stars_repo_head_hexsha": "44838a7bb96da2b807bfb3bfec29d8564b9f4c7f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tex/sections/best-views-estimation.tex", "max_issues_repo_name": "carlosmccosta/active_perception_article", "max_issues_repo_head_hexsha": "44838a7bb96da2b807bfb3bfec29d8564b9f4c7f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/sections/best-views-estimation.tex", "max_forks_repo_name": "carlosmccosta/active_perception_article", "max_forks_repo_head_hexsha": "44838a7bb96da2b807bfb3bfec29d8564b9f4c7f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 67.7194244604, "max_line_length": 1877, "alphanum_fraction": 0.7645808988, "num_tokens": 2360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982043529716, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.3087274421902151}}
{"text": "\\chapter{Results}\n\\label{ch:results}\n\n\\section{Neutron Stars}\nUsing \\chromos, power colours can be obtained for a large number of observations. Applying \\chromos to the population of neutron stars given in Tab.~\\ref{tab:objects} reveals that most objects follow similar tracks in the \\ac{PCC}~diagram. This can be seen in Fig.~\\ref{fig:pc_all_ns}, where a distinct elliptical shape emerges after overplotting these tracks. In this plot $PC1$ is defined as the variance in (0.25-2.0~Hz)/(0.0039-0.031~Hz) and $PC2$ as the variance in (0.031-0.25~Hz)/(2.0-16.0~Hz). Only objects with more than three data points were included, and two objects were excluded due to their peculiar behaviours. A full discussion on the nature of those objects can be found in section~\\ref{sec:dis_ns}. For sake of clarity, only points where the variance is $>\\!3 \\sigma$ in all four frequency bands are plotted, and error bars are omitted. Typical error bars are on the order of 17\\% of the power colour values. Individual tracks can be seen more clearly in appendix~\\ref{ch:pccds}, where each object has been plotted with the neutron star \\ac{PCC} tracks in reference. \\\\\n\nWhile using power colours is useful in comparing evolutionary tracks of systems, power colours require two dimensions ($PC1$ and $PC2$) to classify the state of a system. Reducing this down to a single parameter can be helpful in comparing the state of a system against other parameters. To this end, the `hue'~parameter \\marginpar{In colour theory, hue is defined as the attribute by virtue of which a colour is red, green, etc \\citep{oed}, and is often determined using a colour wheel. This makes hue an excellent analogy to the angle within a \\ac{PCC}~diagram.} can be introduced \\citep{heil2015power}. Defined as the angle of a point in the \\ac{PCC}~diagram with respect to a central point, hue runs in a clockwise direction from a line in the Northwest direction from $0^\\circ$ to $360^\\circ$. Following the original classification of the hue centre given in \\citet{heil2015power}, a central point with the coordinates (4.51920, 0.453724) is chosen as reference point. An example of this classification can be seen in Fig.~\\ref{fig:pc_hue_bins}, where the neutron star \\ac{PCC}~diagram has been divided into hue bins of $20^\\circ$. \\\\\n\nThese hue bins allow an overview of power spectra to be created per hue bin, showing typical power spectra for a variety of objects. Comprising of various types of neutron star systems, these power spectra can be found in appendix~\\ref{ch:psds}. Intrinsic scatter in the power, especially at the high frequencies, is reduced by binning data points linear in log-frequency and errors reduced accordingly. \\\\\n\n\\begin{landscape}\n\\begin{figure}\n\t\\myfloatalign\n\t{\\vspace*{-3cm}\\includegraphics[width=0.8\\linewidth]{pc/all_ns}}\n\t\\caption[Neutron stars in a \\acs{PCC}~diagram]{A \\ac{PCC}~diagram showing tracks for neutron stars. While providing an excellent overview of the general trend, tracks of individual objects can perhaps be best pursued in appendix~\\ref{ch:pccds}, where \\ac{PCC}~diagrams can be found for each system.}\\label{fig:pc_all_ns}\n\\end{figure}\n\\end{landscape}\n\n\\begin{figure}[p]\n\t\\myfloatalign\n\t{\\includegraphics[width=0.8\\linewidth]{pc/hue_bins}}\n\t\\caption[Defining the hue in a \\acs{PCC}~diagram]{A \\ac{PCC}~diagram showing the division of $20^\\circ$ hue bins for neutron star \\acp{PCC}. The starting angle is defined as the angle at $45^\\circ$ in a counter-clockwise direction from the axes. Based on Fig.~2b from \\citet{heil2015power}.}\\label{fig:pc_hue_bins}\n\\end{figure}\n\nAn interesting parameter to compare hue with, is the energy spectral hardness. Linking timing information back to spectral information can provide valuable insights into properties of systems such as the relative spectral evolution and therefore changes in inner region structure. A \\ac{HH}~diagram for neutron stars can be seen in Fig.~\\ref{fig:hh_all_ns}, with the hardness defined as the ratio of the total count rate in 9.7-16.0~keV over the total count rate in 6.4-9.7~keV. Next to the selection methods for \\ac{PCC}~points described in the first paragraph of this section, only points with a hue-error $<\\!30^\\circ$ are included in this graph, where errors are propagated through from the \\ac{PCC}-errors. In a similar fashion to the \\ac{PCC}~diagrams in appendix~\\ref{ch:pccds}, individual \\ac{HH}~diagrams can be found in appendix~\\ref{ch:hhds}, allowing the evolution of an object within a \\ac{HH}~diagram to be traced against other neutron stars.\\\\\n\n\\begin{figure}[p]\n\t\\myfloatalign\n\t{\\includegraphics[width=\\linewidth]{hh/all_ns}}\n\t\\caption[Neutron stars in a \\acs{HH}~diagram]{A \\ac{HH}~diagram showing the evolution of \\ac{PCC}-tracks for neutron stars through use of the hue. Supplementary \\ac{HH}~diagrams can be found in appendix~\\ref{ch:hhds}, showing the tracks of individual objects with neutron star \\ac{HH} tracks as reference.}\\label{fig:hh_all_ns}\n\\end{figure}\n\nAn often-used method in X-ray astronomy to trace the overall secular evolution of \\acp{LMXB} is the \\ac{HI}~diagram (e.g. \\citet{done2003observing}, \\citet{klein2008identification} or \\citet{fridriksson2015common}). In a \\ac{HI}~diagram the energy spectral hardness is plotted against the relative intensity of an object. Appendix~\\ref{ch:hids} shows \\ac{HI}~diagrams for the full population of systems given in Tab.~\\ref{tab:objects}, allowing a broad range of tracks to be compared. A number of objects show unusual tracks, a point discussed in more detail in section~\\ref{sec:dis_ns}.\\\\\n\nIn order to fully encapsulate the evolution of neutron star \\acp{LMXB}, \\ac{ECC}~diagrams are preferred over \\ac{HI}~diagrams. The tracks in the \\ac{ECC}~diagram are commonly divided into various states --- the \\ac{EIS}, the \\ac{IS} and the banana branch, with the \\ac{LLB}, the \\ac{LB} and the \\ac{UB}. Linking the states of atoll source Aql~X-1 with the \\ac{PCC}~diagram reveals an interesting link as shown in Fig.~\\ref{fig:cc}. Here the softness is defined as the ratio of the total count rate in 3.5-6.0~keV over the total count rate in 2.0-3.5~keV, with the hardness retaining the same definition as earlier. For clarity, error bars on the energy colours have been left off the \\ac{ECC}~diagram, typically being small in comparison to the \\ac{ECC}~values. A clear distinction can be made in the \\ac{PCC}~diagram between sources in the \\ac{EIS}, and sources in the banana states. While the \\ac{IS} does not show up in the \\ac{PCC}~diagram, other objects showed this state to be located left of the lower apex, a region with relatively few \\ac{PCC} due to the rapid state transitions.\n\n\\begin{figure}[p]\n\\myfloatalign%\n\\makebox[\\textwidth][r]{%\n\\subfloat{\\includegraphics[width=.5\\largefigure,valign=t]{cc/ns_states_aquila_X1}}%\n\\quad%\n\\subfloat{\\includegraphics[width=.51\\largefigure,valign=t]{pc/ns_states_aquila_X1}}%\n}%\n\\caption[Comparing energy and power colours]{\\spacedlowsmallcaps{left} A \\ac{ECC}~diagram for Aql~X-1, showing the commonly-adopted division into various states: the \\acf{EIS}, the \\acf{IS} and the banana branch, with the \\acf{LLB}, the \\acf{LB} and the \\acf{UB} \\spacedlowsmallcaps{right} A \\ac{PCC}~diagram showing observations linked to the various states defined using the \\ac{ECC}~diagram.}\\label{fig:cc}\n\\end{figure}\n\n\\section{Neutron Stars \\& Black Holes}\nIn order to conduct a model-independent comparison of accreting black hole and neutron star variability, \\ac{PCC}~diagrams can be constructed to show the evolution of both black hole and neutron star systems. In the left panel of Fig.~\\ref{fig:ns_bh}, three representative transient black holes have been plotted for comparison with neutron stars, with additional information on these systems in Tab.~\\ref{tab:objects}. Both types of system show similar paths, yet a clear distinction is found on the right-hand side of the diagram where the black holes systematically follow a higher path with respect to the neutron stars. In the right panel of Fig.~\\ref{fig:ns_bh}, a \\ac{HH}~diagram is shown for the same systems, where the hardness is classified as the same ratio of (9.7-16.0~keV)/(6.4-9.7~keV). With the hue washing out any radial differences in \\acp{PCC}, in the \\ac{HH}~diagram the black holes closely follow the neutron stars albeit with a broader coverage of angles. \\\\\n\n\\begin{figure}[p]\n\\myfloatalign%\n\\makebox[\\textwidth][r]{%\n\\subfloat{\\includegraphics[width=.51\\largefigure,valign=t]{pc/ns_bh}}%\n\\quad%\n\\subfloat{\\includegraphics[width=.49\\largefigure,valign=t]{hh/ns_bh}}%\n}%\n\\caption[Comparison of neutron stars and black holes]{\\spacedlowsmallcaps{left} A \\ac{PCC}~diagram showing black hole systems, with in grey the neutron star \\acp{PCC} in Fig.~\\ref{fig:pc_all_ns} as reference. \\spacedlowsmallcaps{right} The same systems plotted in a \\ac{HH}~diagram.}\\label{fig:ns_bh}\n\\end{figure}\n\nWhile black hole and neutron star \\acp{LMXB} have similar broad-band spectral shapes, the frequency at which power spectral features occur can be a factor five higher for black holes than for neutron stars \\citep{kleinwolt}. Thus comparing \\ac{PCC}~values of black holes with neutron stars could perhaps best be done by shifting the frequency ranges for neutron star power colours up by a factor of five in the power spectrum. This causes the original frequency band boundaries to shift up to 0.0195, 0.155, 1.25, 10 and 64~Hz, where the final frequency is limited by the resolution in which light curves were extracted. Fig.~\\ref{fig:shiftedpc} shows the result of shifting the frequency bands for neutron stars. In the left panel, the original \\ac{PCC}~values for neutron stars can be seen in red against the black hole \\ac{PCC}~values in grey. In the right panel are respectively the shifted \\ac{PCC}~values, shown against the unaffected black hole \\ac{PCC}~values. While the shifted \\ac{PCC}~values show a greater overlap between neutron star and black hole \\acp{PCC}, both tracks can still be distinguished.\\\\\n\n\\begin{figure}[p]\n\t\\myfloatalign\n\t{\\includegraphics[width=\\largefigure]{pc/shiftedpc}}\n\t\\caption[Effect of shifting power colour frequency bands]{\\spacedlowsmallcaps{left} A \\ac{PCC}~diagram showing neutron stars in red against black hole systems in grey. \\spacedlowsmallcaps{right} \\acp{PCC} for neutron stars where the frequency bands have been shifted up by a factor of five. The black hole systems in grey have retained the original frequency bands for their \\ac{PCC} values.}\\label{fig:shiftedpc}\n\\end{figure}\n\n\\section{Effects of Neutron Star Properties}\n\n\\enlargethispage{2\\baselineskip}\n\\subsection{Inclination}\nPower colours present the unique ability to compare various parameters of multiple systems throughout different energy spectral states. Using power colours in such a fashion, \\citet{heil2015inclination} found black holes systems followed an inclination-dependent track in the \\ac{HH}~diagram. Applying the same technique to neutron stars results in Fig.~\\ref{fig:inclination}, where sources have been split into either a low ($i\\!\\leq\\!60^\\circ$)  or high ($i\\!>\\!60^\\circ$) binary orbit inclination group using Tab.~\\ref{tab:objects}, following the division adopted in \\citet{heil2015inclination}. Errorbars have been omitted for clarity and sources with an undefined inclination plotted in grey. While no particular trend can be discerned from the \\ac{PCC}~diagram, the resulting \\ac{HH}~diagram shows signs of an offset dependent on inclination, with low inclination sources showing higher hardness per hue than high inclination sources. Implications of this trend are discussed in section~\\ref{sec:dis_incl}, including suggestions on possible origins.\\\\\n\n\\begin{figure}[p]\n\\myfloatalign%\n\\makebox[\\textwidth][l]{%\n\\subfloat{\\includegraphics[width=.51\\largefigure,valign=t]{pc/inclination}}%\n\\quad%\n\\subfloat{\\includegraphics[width=.49\\largefigure,valign=t]{hh/inclination}}%\n}%\n\\caption[Inclination effects]{\\spacedlowsmallcaps{left} A \\ac{PCC}~diagram with neutron star systems split into high and low inclination groups. Sources with an undefined inclination have been plotted in grey. Details on the inclination of individual sources can be found in Tab.~\\ref{tab:objects}. \\spacedlowsmallcaps{right} A \\ac{HH}~diagram with neutron star systems divided in the same manner.}\\label{fig:inclination}\n\\end{figure}\n\n\\subsection{Atoll \\& Z Sources}\nBased on the path \\acp{LMXB} trace out in a \\ac{ECC}~diagram, neutron star systems can be classified into two subclasses: atoll and Z sources \\citep{hasinger1989two}. In Tab.~\\ref{tab:objects}, systems classified as either an atoll or a Z source have been denoted with respectively an $A$ or a $Z$. A comparison of these systems in the \\ac{PCC} and \\ac{HH}~space can be seen in Fig.~\\ref{fig:atoll_z}. Plotted together with unclassified neutron stars, the Z sources in the \\ac{PCC}~diagram rarely cross into the upper-right half of diagram. This is reflected in the \\ac{HH}~diagram, where almost all Z source values remain above a hue of $180^\\circ$. No particular difference can be discerned between atoll and as of yet unclassified sources, with atoll sources tracing a similar path to the latter.\\\\\n\n\\begin{figure}[p]\n\\myfloatalign%\n\\makebox[\\textwidth][l]{%\n\\subfloat{\\includegraphics[width=0.51\\largefigure,valign=t]{pc/atoll_z}}%\n\\quad%\n\\subfloat{\\includegraphics[width=0.49\\largefigure,valign=t]{hh/atoll_z}}%\n}%\n\\caption[Comparing Atoll and Z sources]{\\spacedlowsmallcaps{left} \\ac{PCC}~diagram with systems classified as atoll sources in red, Z sources in blue and unclassified sources in grey. An overview showing the type of each individual system can be found in Tab.~\\ref{tab:objects}. \\spacedlowsmallcaps{right} Replotting the same systems in a \\ac{HH}~diagram.}\\label{fig:atoll_z} % \\TODO Check Z-source outlier\n\\end{figure}\n\nA further division can be made in Z sources on the basis of spectral and timing behaviour, allowing sources to be split into Cyg- and Sco-like sources \\citep{kuulkers1997gx}. Nonetheless, there are only a few sources which have been classified as Cyg- or Sco-like sources, as seen in Tab.~\\ref{tab:objects}. These can be plotted in a \\ac{PCC}~diagram, as seen in Fig.~\\ref{fig:pc_sco_cyg}. With Z sources rarely straying beyond the lower left corner, a large degree of scatter is expected, and is found in the \\ac{PCC}~values. It is interesting that there is seemingly a lower degree of scatter for the Cyg-like sources in comparison to the Sco-like sources.\\\\\n\n\\begin{figure}[p]\n\t\\myfloatalign\n\t{\\includegraphics[width=0.8\\linewidth]{pc/sco_cyg}}\n\t\\caption[\\acs{PCC}~diagram with Sco- and Cyg-like sources]{\\ac{PCC}~diagram with Z sources. Sco-like sources are plotted in red and with Cyg-like sources in blue. Note the large contributions of Sco X-1 and Cyg X-2 to each respective group.}\\label{fig:pc_sco_cyg}\n\\end{figure}\n\n\\subsection{Pulsations \\& Spin}\nSince the discovery of the first \\ac{AMSP} by \\citet{wijnands1998millisecond}, systematic searches have revealed fourteen other systems of this nature \\citep[see][for a review]{patruno2012accreting}. One such source, HETE J1900.1-2455, was the first to show `quasi-persistent' activity \\citep{galloway2006intermittent}. Believed to be due to a build-up and subsequent suppression of magnetic field through channeling of the accreting flow \\citep[e.g.][]{cumming2001magnetic}, it provides an effective test for a possible correlation between magnetic fields and \\acp{PCC}. Fig.~\\ref{fig:hete_pulsations} shows a selection of observations split into time intervals of standard luminosity levels and time intervals with pulsations. Selections were made on basis of the fractional pulse amplitudes between MJD~53520--53690 as given in \\citet{galloway2006intermittent}. Though the \\ac{PCC}~diagram hints at higher PC2 values during pulsation periods, no conclusive correlation can be determined, with relatively few observations available to distinguish any trends.\\\\\n\n\\begin{figure}[p]\n\t\\myfloatalign\n\t{\\includegraphics[width=0.8\\linewidth]{pc/hete_pulsations}}\n\t\\caption[\\acsp{PCC} during intermittent pulsations]{A \\ac{PCC}~diagram with observations of HETE~J1900.1-2455 split into pulsation time intervals and periods of standard flux-levels. The division between these time intervals was made on basis of information in \\citet{galloway2006intermittent}.}\\label{fig:hete_pulsations}\n\\end{figure}\n\\newpage\nPulsations in neutron star \\acp{LMXB} are commonly used in an attempt to establish the spin frequency of the neutron star, resulting in groups of objects referred to as respectively bursters and pulsars. It is generally accepted that the rapid increase in flux observed in bursters is linked to unstable nuclear burning on the neutron-star surface \\citep[e.g.][]{klis2000millisecond}, providing a means to determine the spin frequency of the neutron star through hotspots on the neutron star surface \\citep[see][]{chakrabarty2003nuclear,strohmayer2003new}. In contrast, pulsars show regular pulsations, resulting in extremely precise spin frequencies. While spin frequencies typically fall far from the frequency bands that power colours probe, some effect of the higher spin frequencies could perhaps be expected to be seen in the lower power colour frequencies. The spin could for instance affect the accretion flow via the pulsar magnetosphere. Coupling spin frequencies with \\acp{PCC} results in Fig.~\\ref{fig:spin}, with objects colour-coded according to their spin frequency. Objects with less than four points have been removed from the sample, to ensure clarity. Bursters show no distinct effects on \\acp{PCC}, however a tentative link could perhaps be found in pulsar systems where a shift in \\acp{PCC} according to spin frequency can be observed. An in-depth discussion on this relation can be found in section~\\ref{sec:dis_ps}, as well as an hypothesis on the origin of this tentative relationship.\\\\\n\n\\begin{figure}[p]\n\t\\myfloatalign\n\t\\makebox[\\textwidth][l]{%\n\t{\\includegraphics[width=\\largefigure]{pc/bursters_pulsars}}\n\t}%\t\n\t\\caption[The effect of spin frequency on \\acsp{PCC}]{\\spacedlowsmallcaps{left} Bursters plotted in order of frequency, with neutron star \\acp{LMXB} without a defined spin frequency in comparison. \\spacedlowsmallcaps{right} \\ac{PCC}~diagram showing pulsars per spin frequency together with the \\ac{PCC} values of the other neutron stars.}\\label{fig:spin}\n\\end{figure}", "meta": {"hexsha": "2efbbeac66d4a0e91779cdc6106b63ffb281ed92", "size": 18355, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/results.tex", "max_stars_repo_name": "davidgardenier/master_thesis", "max_stars_repo_head_hexsha": "d2156dcd79e21c47115dd1bc9ac972a8325b14db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/results.tex", "max_issues_repo_name": "davidgardenier/master_thesis", "max_issues_repo_head_hexsha": "d2156dcd79e21c47115dd1bc9ac972a8325b14db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/results.tex", "max_forks_repo_name": "davidgardenier/master_thesis", "max_forks_repo_head_hexsha": "d2156dcd79e21c47115dd1bc9ac972a8325b14db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 150.4508196721, "max_line_length": 1511, "alphanum_fraction": 0.782348134, "num_tokens": 4938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982043529715, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.30872744219021503}}
{"text": "\n\n\n\\documentclass[10pt, handout]{beamer}\n\\setbeamertemplate{navigation symbols}{}\n\\usefonttheme{serif} \n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{graphicx}\n\\usepackage{cite}\n\\usepackage{color} \n\\usepackage{setspace}\n\\usepackage{hyperref}\n\n\\newcommand{\\xx}{{\\bf{x}}}\n\n\\begin{document}\n\\title{Machine Learning I Lecture III:\\\\ Gaussian models}   \n\\author{Jakob H Macke\\\\ Max Planck Institute for Biological Cybernetics\\\\ Bernstein Center for Computational Neuroscience} \n\\date{XY.XY.2012} \n\n\\frame{\\titlepage} \n\n%\\frame{\\frametitle{Today: Back to basics of probability theory}} \n\n\n\\frame{\\frametitle{Plan for today}\\tableofcontents} \n\n\\section{Wrap up: Continuous random variables}\n\n\\frame{\\frametitle{Mean, variance, and conditioning on events are the same as the discrete case, just with sums replaced by integrals.}\n\\begin{itemize}\n\\item Mean: $E(X)= \\int_x x  \\cdot p(x) dx$\\\\\n\\item Variance: $\\mbox{Var}(X)= E(X^2)- E(X)^2$\n\\item Example: Uniform, Exponential [on board]\n\\item \\pause If $X$ has pdf $p(x)$, then $X | (X \\in A)$ has pdf \n\\begin{align}\np_{X|A}(x)=\\frac{p(x)}{P(A)}=\\frac{p(x)}{\\int_{x \\in A} p(x) dx}\n\\end{align}\n\\item \\pause Only makes sense if $P(A)>0$~!\n\\item Examples: Uniform, Exponential [on board]\n\\end{itemize}\n}\n\n\n\n\\frame{\\frametitle{Bivariate continuous distributions: Marginalization, Conditioning and Independence}\n\\begin{itemize}\n\\item $p_{X,Y}(x,y)$, joint probablity density function of $X$ and $Y$\n\\item $\\int_x \\int_y p(x,y)dx dy=1$\n\\item \\pause \\alert{Marginal distribution:} $p(x)= \\int_{-\\infty}^\\infty p(x,y) dy$\n\\item \\pause \\alert{Conditional distribution:} $p(x|y)= \\frac{p(x,y)}{p(y)}$ \n\\item Note: $P(Y=y)=0$! Formally, conditional probability in the continuous case can be derived using infinitesimal events.\n\\item \\pause \\alert{Independence:} $X$ and $Y$ are independent if $p_{X,Y}(x,y)=p_X(x)p_Y(y)$\n\\end{itemize}\n}\n\n\\section{Gaussians}\n\\frame{\\frametitle{The univariate Gaussian}\n\\begin{align}\nt &\\sim \\mathcal{N}(\\mu,\\sigma^2)\\\\\np(t|\\mu, \\sigma^2)&=\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp\\left( -\\frac{1}{2}\\left(\\frac{t-\\mu}{\\sigma} \\right)^2\\right)\n\\end{align}\n\\begin{itemize}\n\\item \nThe Gaussian has \\alert{mean} $\\mu$ and \\alert{variance} $\\sigma^2$ and \\alert{precision} $\\beta=1/\\sigma^2$\n\\item \\pause Q: What are the \\alert{mode} and the \\alert{median} of the Gaussian?\n\\item \\pause Maximum Likelihood estimation of $\\mu$ and $\\beta$: [on board]\n\\item \\pause Q: How would you find the conjugate prior for the Gaussian?\n\n\\end{itemize}\n}\n\n\n\\frame{\\frametitle{A (very important) aside: Products of Gaussian pdfs are (unnormalized) Gaussians pdfs}\n\\begin{itemize}\n\\item Suppose $p_1(x)=\\mathcal{N}(x,\\mu_1, 1/\\beta_1)$ and $ p_2(x)=\\mathcal{N}(x,\\mu_2, 1/1\\beta_2)$, then  \n\\pause \\begin{align}\np_1(x) p_2(x) &\\propto \\mathcal{N}(x, \\mu, 1/\\beta)\\\\\n\\beta&=\\beta_1+\\beta_2\\\\\n\\mu&=\\frac{1}{\\beta}(\\beta_1 \\mu_1 +  \\beta_2 \\mu_2)\n\\end{align}\n\n\\pause \nIn general:\n\\begin{align}\np_1(x) p_2(x) ... p_n(x) &\\propto \\mathcal{N}(x, \\mu, 1/\\beta)\\\\\n\\beta&=\\sum_n \\beta_n\\\\\n\\mu&=\\frac{1}{\\beta} \\sum_n \\mu_n \\beta_n\n\\end{align}\n\n\\pause \nThis is also true for multivariate Gaussians!\n\n\\end{itemize}\n}\n\n\n\\section{Bayesian inference for Gaussians}\n\n\\frame{\\frametitle{Bayesian Inference for the Gaussian}\n\\begin{itemize}\n\\item Suppose we are given data $D=\\{x_1, \\ldots, x_N\\}$. \n\\item We assume that the data is Gaussian-distribution with known variance $\\sigma^2$ and unknown mean $\\mu$.\n\\item Our prior for $\\mu$ is Gaussian: $\\mu \\sim \\mathcal{N}(\\mu_o, \\sigma^2_o)$\n\\item Posterior distribution over $\\mu$ given the data: [on board] \n\\end{itemize}\n~\n\\pause\n{\\centering\n\\includegraphics[width=.58\\textwidth]{Figure212.pdf}\n\\\\\\vspace{-.5cm}}\n{\\tiny[Bishop PRML Figure 2.12]}\n\n\\pause Behaviour for large $N$: [on board]\n}\n\n\\frame[shrink=0]{\\frametitle{What if the variance is not given?}\n\\begin{itemize}\n\\item For simplicity, assume mean to be known.\n\\item More convenient to work with precision $\\lambda=1/\\sigma^2$.\n\\item Conjugate prior: Gamma distribution $\\mbox{Gam}(\\lambda|a,b)$\n\\begin{align}\np(\\lambda|a, b)=\\frac{1}{\\Gamma(a)}b^a \\lambda^{a-1} exp(-b\\lambda)\n\\end{align}\n\\item Posterior is $\\mbox{Gam}(\\lambda|a_N,b_B)$\n\\begin{align}\na_N &= a + \\frac{N}{2}\\\\\nb_N &= b + \\frac{1}{2} \\sum_{n=1}^N (x_n -\\mu)^2\n\\end{align}\n\\pause\n\\includegraphics[width=.38\\textwidth]{Figure213b.pdf}\n\\includegraphics[width=.38\\textwidth]{Figure213c.pdf} \\\\\\tiny[Bishop PRML Page 100]\n\n\\end{itemize}\n}\n\n\\frame[shrink=0]{\\frametitle{What if both the mean and the variance are unknown?}\n\\begin{itemize}\n\\item Conjugate prior: Gaussian-Gamma distribution\n\\begin{align}\np(\\mu,\\lambda) & = \\mathcal{N}\\left(\\mu |\\mu_o (\\beta\\lambda)^{-1}\\right) \\mbox{Gam}(\\lambda|a,b)\n\\end{align}s\n\\includegraphics[width=.68\\textwidth]{Figure214.pdf} \\\\\\tiny[Bishop PRML Page 102]\n\\end{itemize}\n}\n\n\n\n\n \n\\end{document}\n\n\n\n", "meta": {"hexsha": "b1c8c80db245964ee21e8970b83405f0a4df13c5", "size": 4836, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "slides/lecture3_gaussians/lecture3.tex", "max_stars_repo_name": "mackelab/machine-learning-I", "max_stars_repo_head_hexsha": "fedd9ea0b9b257af5cd59036a3b49876aed5c77c", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2015-07-31T15:08:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T17:07:23.000Z", "max_issues_repo_path": "slides/lecture3_gaussians/lecture3.tex", "max_issues_repo_name": "cne-tum/msne_statsandprob_ss2018", "max_issues_repo_head_hexsha": "fedd9ea0b9b257af5cd59036a3b49876aed5c77c", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slides/lecture3_gaussians/lecture3.tex", "max_forks_repo_name": "cne-tum/msne_statsandprob_ss2018", "max_forks_repo_head_hexsha": "fedd9ea0b9b257af5cd59036a3b49876aed5c77c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2018-03-16T07:42:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-01T14:02:27.000Z", "avg_line_length": 31.0, "max_line_length": 135, "alphanum_fraction": 0.6985111663, "num_tokens": 1696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118791767282, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.30857857617932805}}
{"text": "% Chapter 2\r\n%\r\n\\chapter{Technology and Basic Principles} % Main chapter title\r\n\\label{Chapter2} % For referencing the chapter elsewhere, use \\ref{Chapter2} \r\n%\r\n%2. Technology and basic principles\r\n    %\r\n    %Public Key Cryptography\r\n        \r\n        %Key management\r\n\r\n        %Certificates\r\n        %\\label{sec:cert} %Discussion of what data certificates usually contain\r\n\r\n        %\\label{sec:pgp_enc} %Demmonstration/Example of PGP encryption\r\n\r\n    %Web of Trust\r\n        %Overview\r\n\r\n        %Ceritifcates\r\n\r\n        %Certificate sharing\r\n\r\n        %Sylbil attack\r\n        %\\label{sec:trust_syl} %Sylbil attack theory\r\n\r\n    %WebRTC\r\n    %\\label{sec:webrtc}\r\n        \r\n        %Connection setuo\r\n            %ICE, STUN \\& TURN\r\n            %\\label{sec:webrtc_icetri} % WebRTC ICE trickling\r\n            %SDP and DTLS-SCTP\r\n            %Offer and Answer\r\n            %\\label{sec:webrtc_off} \r\n\r\n        %Signaling server\r\n\r\n    %WS\r\n    %\\label{sec:ws}\r\n    \r\n%\r\n% THIS SHOULD GO THROUGH THE TECHNOLOGY OBJECTIVELY AND HOW IT WORKS!\r\n%\r\nThis chapter will go over the technologies proposed and used in SendIt and give an introduction to their functionality, as well as the reasons for choosing said technology. It will give a basic understanding of the technology, which the rest of the thesis is built upon.\r\n%\r\n\\section{Cryptography}\r\n\\label{sec:pkc}\r\n%\r\n    %\r\n    %Key pairs\r\n    The encryption and authentication scheme used in SendIt is based on public-key cryptography and symmetric cryptography. Public-key cryptography is a technology that creates a public and a private key pair, where the public key is used for encryption. The encrypted data can \\emph{only be decrypted by the corresponding private key}. The inverse is also true. Anything encrypted with the private key, can be decrypted by the public key. The common usage is to spread the public key around, hence the name public. The private key (also called secret key) is kept safe, and only the identity that is the owner of the key pair should have access to it \\cite{trcekManagingInformationSystems2006}.\r\n\r\n    In contrast, symmetric cryptography utilizes the same key for encryption and decryption. The advantage of symmetric cryptography is that it can encrypt larger amounts of data. The disadvantage is that anyone with the key, can read any message. Symmetric keys usually also needs a value called IV (Initialization Vector), that is used to randomize the encrypted values. It allows for two identical messages to have different ciphers. There are two forms of IV schemes. One is using completely random number(s) each time, called a randomized scheme. The other scheme requires each IV to be unique, and is called a stateful scheme \\cite{bellareIntroductionModernCryptography2005}.\r\n\r\n    SendIt uses public-key cryptography to exchange encrypted messages that only the person having the correct key can decrypt. This is the same principles as used in Public Key Infrastructure. The difference lies in that PKI relies on a central authority for signing and verifying the keys used, in the form of certificates. SendIt tries to avoid any central form of governance, and as such, implements the web of trust model instead, in order to avoid this central management. This is discussed more in \\Cref{sec:trustmodel}.\r\n\r\n    \\subsection{Key management}\r\n    This means that the keys have to be the same every time, which requires each user to store their keys for later. This should be done with some consideration, since a stolen private key means anyone can now take your identity and successfully authenticate as you. As such the need for secure storage arises. This can be solved by encrypting the keys with a password, then storing them on the local machine. Only when a key is in use, will it be read and decrypted. This decreases the chance of the key being stolen, since it minimizes the attack surface by only having the key available when it is in use.\r\n\r\n    When storing keys it is necessary to keep more information than just the key. For example, it is also necessary to know who it belongs to. For the proposed system, information relevant to the trust-level of each key also needs to be stored. The easiest way to do this is to store the certificate of each key with the key. That means the trust in a key will have to be re-calculated every time it is loaded. This is costly when it comes to computational resources, but allows the system to re-calculate the trust  in a key before each use. This gives a flexible and up-to-date environment where trust is evaluated, similar to in the real world.\r\n\r\n    \\subsection{Certificates}\r\n    \\label{sec:cert}\r\n    %\r\n    SendIt also proposes to use digital certificates like the ones used in the web of trust model \\cite{ar_pgp}. Certificates traditionally contain various information. The certificate is then signed by any number of “introducers”, by encrypting it using their private key. An introducer is an identity who trusts another identity and vouches for the legitimacy of that identity \\cite{ar_pgp}.\r\n    \r\n    Certificates used in PKI are required to contain enough information to provide a third party with the subject's public key. Usually certificates used in PKI contain more data than required. The minimum required data can be summed up in four points \\cite{vaccaPublicKeyInfrastructure2004}:\\\\\r\n    \\begin{itemize}\r\n        \\item CA identification information\r\n        \\item Subject identification information\r\n        \\item Subject public key\r\n        \\item Validity (time)\r\n    \\end{itemize}\r\n    More information on introducers and certificates can be found in \\Cref{sec:trustmodel}.\r\n\r\n    \\subsection{Authentication}\r\n    \\label{sec:pgp_enc}\r\n    The last part of the puzzle is \\emph{how can a user be authenticated based on this information?} There are many different schemes, but SendIt focuses on the one suggested by PGP for securely exchanging messages \\cite{b_pgp}. The system is based on public key encryption. It also uses a session key, which is a random, one time generated symmetric key. The system guarantees the authenticity, confidentiality, and integrity of the data. Encryption and decryption using the PGP system is shown in \\Cref{fig:enc} and \\Cref{fig:decr}.\r\n\r\n    The way PGP works is by first generating a symmetric key and encrypting the data to be transferred with this symmetric key. This results in a cipher. Let us call this \\emph{Cipher 1}. Then the symmetric key is encrypted with the recipients public key. This also results in a cipher (\\emph{Cipher 2}). The data transferred to the recipient is \\emph{Cipher 1} and \\emph{Cipher 2}.\r\n\r\n    The recipient then retrieves the symmetric key, by decrypting \\emph{Cipher 2}, using their private key. Then, using the retrieved symmetric key, \\emph{Cipher 1} is decrypted and the original data is available.\r\n\r\n    This solution is made with a one-directional exchange of data in mind. This system will be used to authenticate both endpoints, which means it will have bi-directional communication. The way to solve this issue, is by taking advantage of the way symmetric keys encrypt data. The initial exchange from Sender to Receiver gives proof to the Sender that the recipient is as intended. This is not the case if the same IV is re-used for the reply. As such, it should be changed.\r\n\r\n    Usually the IV is shared in cleartext, since knowledge of the key is also required to decrypt it, therefore it is not sensitive data. In SendIt, the IV used in the reply is encrypted with the Sender's public key. That means that in order to be able to access the data, the private key is needed, and as such, the Sender is also authenticated. This solves the issues of mutual, bi-directional authentication.\r\n\r\n%\r\n\\section{Web of trust}\r\n\\label{sec:trustmodel}\r\n%\r\n    This section is a suggestion and evaluation of the system only. This has not been implemented in SendIt due to time constraints, but is considered a part of the design.\r\n\r\n    \\subsection{Overview}\r\n    The model suggested is based on the web of trust. The web of trust model says that trust should be split into two groups: \\textbf{Trustworthiness of public-key certificate} - \\emph{How willing are you to trust this key pair when it is being used to communicate?} and \\textbf{Trustworthiness of an introducer} - \\emph{How willing are you to trust this key pair when it is being used to introduce another key?}.\r\n\r\n    It also suggests that the trust level given to a key should be based on points given to a certificate, based on the sum of introducers and their respective trust level. There is no concrete policy or algorithm suggested for evaluating which level of trust is assigned. The model does define levels of trust, but they are different for the two groups previously mentioned. \r\n\r\n    There is also no recommendation of which trust level should be considered safe or unsafe \\cite{ar_pgp}. This is left up to each individual user, since there exist many ways to rate and evaluate trust. For this system, a simple point-based system is likely to be the best fit. The web of trust model has also been recommended by other researchers, albeit for a more traditional WebRTC authentication system \\cite{ar_whois}. For a look into more options, J\\o sang et al. (2007) \\cite{a_trustserv} gives a good overview over possible alternatives.\r\n\r\n    \\subsection{Certificates}\r\n    %\r\n    The way one infers, evaluates, and determines trust is by using certificates. The trust is evaluated based on interactions with others and the interactions between trusted introducers and others. This means that information from identities one does not trust will be disregarded (their introductions mean nothing), while still valuing and receiving updated information from identities one does trust. In other words, many untrusted identities introducing someone does not hold any value, while introductions from a few trusted identities has a significant impact on the trust level assigned to a certificate.\r\n\r\n    \\subsection{Certificate sharing}\r\n    The exchange of keys and the trust each identity assigns these keys are central to the web of trust model, as described previously (\\Cref{sec:trustmodel}). Since the connection used for communication is already secure, and each party authenticated, this data can be transferred without additional encryption. This section will describe how this is intended to be implemented in SendIt. This is included as part of this chapter since it has not been implemented in the prototype.\r\n    %\r\n        \\subsubsection*{Request certificates:}\r\n        SendIt will have an automated, bi-directional sharing of certificates, that happens on every exchange. This sharing will be part of the file transfer protocol and will happen after the file transfer has completed (before terminating the connection). This automatic sharing will abstract the system away from the user, to make the system easy to use and understand, while still updating the trust-level for different identities according to recent changes in the system. The choice to make this part mandatory also allows for the system to avoid being biased by only receiving updates from certain identities.\r\n        %\r\n        \\subsubsection*{Evaluate certificates:}\r\n        While exchanging certificates with all communication-partners is important to avoid bias, it is also important to let the user influence and differentiate the level of trust given to each partner. This is where settings and evaluation comes into play. Each user can change the level of trust in each partner manually, based on his own preferences.\r\n\r\n        As an extension of the trust given to each partner, the information they share is also evaluated based on how trusted the partner is. The trust evaluation of each key, and by extension each identity, will vary depending on user settings and preferences. It will however always follow the scheme as described above. The effect of this evaluation will result in a corresponding trust-level associated with the identity. Identities that have too low a trust level to be used can either raise an \\emph{untrusted user warning} before communication occurs, or a \\emph{connection terminated message}, depending on the user's settings. These keys will still be stored in the user's key-chain and stay available for future evaluation, even if their current level of trust is low.\r\n\r\n    \\subsection{Sybil attack}\r\n    \\label{sec:trust_syb}\r\n    A common attack in decentralized reputation systems is the Sybil attack. It is an attack that takes advantage of the fact that the system can be manipulated by having a large number of identities share the same, false information, to innocent identities. In SendIt's case, that a certain key pair belongs to a certain identity, while in fact it does not. Through sheer numbers, the attack manipulates identities in the system to believe that the attacker should be the trusted identity, not the original identity. This misleads users to connect to the wrong identity, which makes them vulnerable to attacks. It can also lead to being unable to connect to the legitimate identity, since all traffic for that identity is instead routed to the attacker \\cite{lncs_sybil}.\r\n\r\n%\r\n\\section{WebRTC}\r\n\\label{sec:webrtc}\r\n%\r\n    WebRTC is a fairly new technology developed for real-time communication between web entities. It focuses on allowing video, audio, and data transfers over P2P, through an easy to use API. It does this without the need to install plugins or having to download native applications, since it is already implemented in most of today's popular browsers. \r\n\r\n    %Connection setup\r\n    \\subsection{Connection setup}\r\n    \\label{sec:conn_setup}\r\n    %\r\n    To set up a connection using WebRTC, there are different variables one has to take into account. First, \\emph{what are the network conditions for each endpoint?} To be able to create a connection, a way to address each endpoint directly is needed. To do this WebRTC utilizes STUN \\cite{ar_stun}, and/or TURN \\cite{ar_turn}, and ICE \\cite{ar_ice}. \r\n    %\r\n    \\subsubsection*{ICE, STUN, and TURN}\r\n    \\label{sec:webrtc_icetri}\r\n    %\r\n    \\begin{figure}[th]\r\n      \\centering\r\n      \\includegraphics[width=\\textwidth]{Figures/ICE_trickling}\r\n      \\decoRule\r\n      \\caption[ICE trickling]{This illustration displays how ICE trickling works. Do note that for ICE trickling, process number 3 in the illustration can happen at any time, and any number of times.}\r\n      \\label{fig:ice_trick}\r\n    \\end{figure}\r\n    %\r\n    The ICE protocol works by trying to connect directly to the endpoint. If an endpoint is behind symmetrical NAT, however, a TURN server is required. A TURN server acts as a relay-server that both endpoints connect to, and there is no longer a direct P2P connection. Instead each endpoint is connected to a server by a P2P connection, and the server forwards information to the other end. It is the ICE protocol that detects and manages this information, and tries to find the best possible connection \\cite{ar_webrtc_sign}.\r\n\r\n    ICE is a protocol for NAT traversal used in Offer/Answer protocols. In regular WebRTC-applications, something called ICE trickling is used. This is because generating the Offer and the Answer is quick, but gathering ICE candidates takes time. When using ICE trickling, the Offer/Answer is generated and shared independently of the ICE candidates. Once the Offer/Answer is generated, ICE candidate gathering begins. Once an ICE candidate is found, it is immediately shared. This allows the connection setup to happen first, then ICE candidates to be shared afterwards \\cite{ar_ice_trickle}.  This is illustrated in \\Cref{fig:ice_trick}. In SendIt, this functionality is utilized in the ACS mode.\r\n\r\n    In Serverless mode, all the information is gathered, then attached to the Offer/Answer, and then shared. ICE is used in order to be able to address and reach computers behind NAT \\cite{ar_ice}. The easiest way to describe the whole process is to imagine ICE as the decision maker, utilizing STUN and TURN to find information about the endpoint. Once all the information from STUN and TURN is gathered, ICE prioritizes the information, and shares it as separate possible ways to connect to the endpoint. These connection alternatives are called ICE candidates.\r\n    %\r\n    \\subsubsection*{SDP and DTLS-SCTP}\r\n    %\r\n    Session Description Protocol (SDP) is a format for session descriptions. This is a protocol for formatting data, for example discovered through the ICE protocol, to be shared with the other endpoint \\cite{ar_sdp}. For the Serverless mode, it is up to the users how they share the Offer and Answer, and as such it does not use a transfer-protocol. In the ACS mode, secure WebSockets are used for sharing the information.\r\n\r\n    The WebRTC DataChannel used for direct communication uses DTLS-SCTP as it's transport-protocol \\cite{ar_webrtc_dc}.\r\n    %\r\n    \\begin{quotation}\r\n        \\enquote{DTLS itself is modelled upon the stream-orientated TLS, a protocol which offers full encryption with asymmetric cryptography methods, data authentication, and message authentication \\cite{StudyWebRTCSecurity}.}\r\n    \\end{quotation}\r\n    %\r\n    In other words, the communication is securely transported between the endpoints, once the connection setup is done.\r\n\r\n    %WRITE XEXPLICITLY! TODO\r\n    Encapsulation of SCTP over DTLS, as well as the ICE and SDP protocols are complex. As such, an in-depth explanation is available in Holmberg, H.-C. (2015)\\cite{url_webrtc_data}, for those unfamiliar with this technology. In summary: each endpoint gathers the necessary connection data and then formats it according to the SDP protocol, for session-negotiation and initiation. Then the DataChannel is created and the connection is made.\r\n    %\r\n    \\subsubsection*{Offer and Answer}\r\n    \\label{sec:webrtc_off}\r\n    %\r\n    Following, is how the relevant RFC describes how endpoint guarantee is done:\r\n    %\r\n    \\begin{quotation}\r\n        \\enquote{A certificate fingerprint is a secure one-way hash of the DER (distinguished encoding rules) form of the certificate. If the X.509 certificate presented for the TLS connection matches the fingerprint presented in the SDP, the endpoint can be confident that the author of the SDP is indeed the initiator of the connection \\cite{ar_tls_sdp}.}\r\n    \\end{quotation}\r\n    %\r\n    This explanation can be a little hard to understand, so let us break it down. Both the Offer and the Answer generated by the WebRTC API has a fingerprint of a certificate attached. The endpoint generates a X.509 certificate and a corresponding private key. By matching the fingerprint received during signaling with the certificate used during the setup of the DTLS-SCTP connection, one can be certain that the endpoint is the same. This is illustrated in \\Cref{fig:DTLS_setup}.\r\n    %\r\n    \\begin{figure}[t]\r\n      \\centering\r\n      \\includegraphics[width=\\textwidth]{Figures/DTLS_Exchange}\r\n      \\decoRule\r\n      \\caption[DTLS setup]{This illustration shows and describes how DTLS is setup between two endpoints. The final channel in the illustration is of the type SRTP, but the same procedure is true for SCTP \\cite{WebRTCManMiddle2015}}\r\n      \\label{fig:DTLS_setup}\r\n    \\end{figure}\r\n    %\r\n    \\subsection{Signaling server}\r\n    \\label{sec:sign_serv}\r\n    %\r\n    In the usual use case of WebRTC, a signaling server is used to share SDP Offers and Answers, as well as continuously sharing ICE candidates. This separate channel allows for re-negotiation of communication, if the connection breaks down. An Offer is the exchange of SDP information from the sender, to the receiver. An Answer is the exchange of SDP information from the receiver to the sender.\r\n\r\n    There are several reasons for the usage of a signaling server. One is the ability to reconnect in the event of a failure in the established connection. Another is that it delays the Offer and Answer from being created until both endpoints are online, after which it is immediately created and shared. This is the case when using ACS. When using Serverless mode, however, this is not the case. This means it is affected by the fact that network conditions can change rapidly and, as such, ICE candidates may no longer be viable, leaving endpoints with no way to connect or renegotiate the connection. For more information on the lifetime of the exchange, see \\Cref{Chapter5}.\r\n\r\n    Another use of the signaling server is that it allows for encrypted communication between the parties, via the server. As long as you trust the signaling server, your communication is confidential. This is important in regards to the exchange of the Offer and Answer, as they contain information that allows a secure connection to be set up, as described in the previous section.\r\n\r\n    Serverless mode does not have a secure channel over which the Offer and Answer is exchanged. That means it would be vulnerable to a MITM-attack. To combat this, the Offer and Answer will be encrypted by each endpoints public key for all connections after the first (See \\Cref{fig:enc} for illustration). With this protection in place, an attacker can not get a hold of the Offer and/or Answer without stealing the private key that can decrypt the cipher.\r\n\r\n%\r\n\\section{WebSockets}\r\n\\label{sec:ws}\r\n%\r\nTo understand why WebSockets are necessary, let us first examine how normal communication between clients and a server is done. The client sends a request and the server sends a response. If the data contained in the response is time critical, it will, in many cases, already be outdated by the time it is rendered by the client. A manual way to combat this is to refresh the page. A more elegant way is the use of polling. Polling is a regularly timed, synchronous call the client makes to the server, to look for new information. This works well if you can predict when new data will be available. The problem is that this is often not the case. There are other alternatives as well, for example, long polling or streaming. However, they all come with certain issues regarding real-time, two-way communication. Especially latency and overhead are problematic.\r\n\r\nThis is where WebSockets come into play. WebSockets offers real-time, duplex, bi-directional connections. It makes communication between a client and a server easier and faster. It also supports real-time communication, which is an added bonus. WebSockets are commonly used in a lot of real-time applications in today's online environment. From transferring game data to simple chat applications. It is also commonly used for signaling in WebRTC applications. This is also how it is used in SendIt, specifically in the ACS mode.\r\n\r\nAnother great thing about WebSockets, is that they support the traditional use of TLS. This means that the WebSocket protocol can use the same security mechanisms as traditional HTTPS traffic. This makes it easy to protect the confidentiality, integrity, and availability of network communications. Finally, all modern browsers have native support for the WebSocket protocol and as such it is incredibly easy to deploy \\cite{wangDefinitiveGuideHTML52013}. For these reasons, the WebSocket protocol was chosen to take care of the communication between endpoints and the server, required by the ACS mode.\r\n\r\n", "meta": {"hexsha": "32b96b1a0348d55940e428f8ff63cde54c8a1293", "size": 23360, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Latex/Chapters/Chapter2.tex", "max_stars_repo_name": "Robiq/Thesis", "max_stars_repo_head_hexsha": "9f764a067ffef6984533dfe17c1f5366a7ec0a16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Latex/Chapters/Chapter2.tex", "max_issues_repo_name": "Robiq/Thesis", "max_issues_repo_head_hexsha": "9f764a067ffef6984533dfe17c1f5366a7ec0a16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Latex/Chapters/Chapter2.tex", "max_forks_repo_name": "Robiq/Thesis", "max_forks_repo_head_hexsha": "9f764a067ffef6984533dfe17c1f5366a7ec0a16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 113.9512195122, "max_line_length": 862, "alphanum_fraction": 0.7719178082, "num_tokens": 5004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.30857856712665155}}
{"text": "\\documentclass{article}\n\n\\usepackage[final]{style}\n\\usepackage[utf8]{inputenc} % allow utf-8 input\n\\usepackage[T1]{fontenc}    % use 8-bit T1 fonts\n\\usepackage{hyperref}       % hyperlinks\n\\usepackage{url}            % simple URL typesetting\n\\usepackage{booktabs}       % professional-quality tables\n\\usepackage{amsfonts}       % blackboard math symbols\n\\usepackage{nicefrac}       % compact symbols for 1/2, etc.\n\\usepackage{microtype}      % microtypography\n\\usepackage{verbatim}\n\\usepackage{graphicx}       % for figures\n\\usepackage[]{algorithm2e}\n\n\n\\title{Lecture \\#20: Convolutional Neural Networks}\n\n\\author{\nKendall Beache, Sammy Mohammed, Hannah Zhang \\\\\n  Department of Computer Science\\\\\n  Stanford University\\\\\n  Stanford, CA 94305 \\\\\n  \\texttt{\\{kbeache, sammym, hzhang16\\}@stanford.edu} \\\\\n}\n\n\\begin{document}\n\n\\maketitle\n\n\\section{Introduction}\nThroughout this class, we have explored several different computer vision techniques, including edge detection, clustering methods, classifiers, and feature detectors/descriptors. These techniques still have one main drawback, in that they require humans to hand-design features. In this lecture, we will go over backpropagation in neural networks, a method to recursively find the ideal weights for the neural network, and convolutional neural networks, a new method designed to solve any image processing problem the network is trained for. \n\nA convolutional neural network is an algorithm that performs \\textit{end-to-end learning}, directly mapping raw inputs (images) to a desired output, such as labels or predictions. The history of convolutional neural networks spans decades, but the biggest breakthroughs were in 2010 and 2012, with the publication of Mohamed et al's  Acoustic Modeling\nusing Deep Belief Networks, and Dahel et al's Context-Dependent\nPre-trained Deep Neural\nNetworks for Large Vocabulary\nSpeech Recognition. Now, convolutional neural networks and deep learning have led to rapid progress in computer vision, which we will explore. Deep learning approaches usually involve combining a small set of simple tools to build a network and then training that network on data for the specific problem you're trying to solve; they can often be adapted to different problems by simply swapping out the training data.\n\n\\section{Backpropagation in Neural Networks}\n\n\n\\subsection{Fundamentals of Backpropagation}\n\n\\textit{Backpropagation} is an algorithm used to build arbitrarily large neural networks, and gradients only require local information to calculate gradients, via recursive implementation of the chain rule. It allows any gradient in the network to be computed by solving the gradients in later layers. Backprop is necessary, as calculating the gradients for intermediate variables manually is difficult even with just a few layers, and does not scale well to neural networks with many layers. \n\\\\\n\\begin{figure}[h]\n\\includegraphics[width=6cm]{Capture.png}\n\\centering\n\\caption{1D example (CS 131 lecture slide 20-10)}\n\\end{figure}\n \\\\\nIn order to demonstrate backprop, we will use a 1-d neural network as an example. In this case, $a = wx$, and $\\hat{y} =$ max($0,a$). Our goal is to calculate $dL/dW$. Using the chain rule, we can see that $dL/dw_1 = dL/da * da/dw_1$, and $dL/da = dL/d\\hat{y} * d\\hat{y}/da$. We can then apply the chain rule to solve.\n\n\\subsection{Rules for Calculating Gradients}\n\nThere are some general rules that can help when calculating gradients of input features. If the operation is addition, then the gradients of the input features are distributed in that $\\frac{dL}{dx_i} = \\frac{dL}{dy}$ for all input features $x_i$. If the operation is multiplication, then each gradient will be proportional to the values of the other input features. For example, if there are two input features $w$ and $x$, then $\\frac{dL}{dw} = x\\frac{dL}{dy}$ and $\\frac{dL}{dx} = w\\frac{dL}{dy}$. If the operation is a maximum function, like $y = $ max$(x, w)$, then $\\frac{dL}{dw} = \\frac{dL}{dy}$ if $w \\geq x$ and 0 otherwise; $\\frac{dL}{dx} = \\frac{dL}{dy}$ if $x \\geq w$ and 0 otherwise. If the function is $y = e^x$, then $\\frac{dL}{dx} = y \\frac{dL}{dy}$, since $\\frac{dy}{dx} = e^x$.\n\n\n\n\\section{Convolutional Neural Networks}\n\nConvolutional neural networks are a type of deep learning models that are often used for object recognition and classification. At a high level, CNNs start with an original image, and convolve it with multiple filters. The parameters for convolution are also chosen via backpropagation, ensuring that we do not have to hand-choose features.\n\nConvolutional neural networks can be broken down into 3 steps\n1) Convolution, 2) Non Linearity,\n3) Pooling\n\n\\subsection{Convolution:} We use convolution in this step as a means to extract features from the original input image. A CNN learns the values of the filters or kernels during the training process. Typically we use 1 2D convolution layer on black and white images; however, if you wanted to extract features from a color image you can use 3 2D convolution layers (one for each channel).\n\nThe size of the convolved feature is controlled by three parameters: depth, stride, and zero-padding that we need to decide before the convolution step is performed. Depth corresponds to the number of filters we use for the convolution operation. Stride is the number of pixels by which we slide our filter matrix over the input matrix. We use zero-padding to apply the filter to bordering elements of our input image matrix. Zero padding also allows us to control the size of the feature maps. \n\nIntroduce Non-Linearity (ReLu Function):\nAfter every convolution, the ReLu function is applied to introduce non-linearity in our model (because most real-world data we would want our ConvNet to learn would be non-linear.) ReLU stands for Rectified Linear Unit and its output is given by the following:\n\\begin{figure}[h]\n\\includegraphics[width=6cm]{relu.png}\n\\centering\n\\caption{The ReLU function. (Kanchan Sarkar, Medium))}\n\\end{figure}\n\nOther non-linear functions that can be applied to the convolved images include the sigmoid and tanh function; however, the ReLu function tends to give the best results.\n\n\\subsection{Pooling}\nModern convolutional neural networks incorporate pooling layers -- layers in the neural network that downsize the dimensionality but retain the most important information. This works by defining a spatial neighborhood, such as a 2x2 window, and then taking different data from the neighborhood depending upon the pooling algorithm. One example of this sort of pooling is MaxPool, where the max value in the window is the value that is retained. There are other pooling algorithms, such as AveragePool and SumPool, where the average is taken and the sum of the window is taken.\n\n\\begin{figure}[h]\n\\includegraphics[width=6cm]{maxpooling.png}\n\\centering\n\\caption{Max pooling reduces dimensionality by a factor of 2. (CS 131 lecture slide 20-38)}\n\\end{figure}\n \n\\subsection{Architecture}\nThese different layers can be stacked, feeding the input of one layer into the other in order to help improve output quality. These layers extract relevant information, and then classify.\n\n\\begin{figure}[h]\n\\includegraphics[width=6cm]{structure.png}\n\\centering\n\\caption{CNN Architecture (CS 131 lecture slide 20-41)}\n\\end{figure}\n\nThis basic structure can be expanded -- consider GoogLeNet, a CNN with an Inception layer, a hand-designed network within a network. \n\n\\begin{figure}[h]\n\\includegraphics[width=6cm]{Inception.png}\n\\centering\n\\caption{GoogLeNet architecture and Inception module. (CS 131 lecture slide 19-101)}\n\\end{figure}\n\nHowever, this layering process comes with a drawback. Convolutional neural networks are not shift-invariant, due to the pooling layer -- minor shifts in the image can result in dramatically different classification outputs. (Best demonstrated here: https://richzhang.github.io/antialiased-cnns/). One potential solution would be the BlurPool algorithm, where the window is blurred and shifted before MaxPool is ran, resulting in better outcomes. However, this does not solve the shift-invariance problem, so results may still be unpredictable.\n \n\\section{Conclusion}\nWhile CNNs meet the basic architecture described above, there are still many variations between different networks. CNNs can differ by the amount of layers or values of the hyperparameters used. If you are interested in learning more about different CNNs, read more on  GoogLeNet, VGGNet, or ZF Net.\n\n% References\n\\small\n\\bibliographystyle{plain}\n\\bibliography{bibliography}\n\\end{document}\n", "meta": {"hexsha": "bc077e5208d8a96f7abd16c1c42ea3c7b795268e", "size": 8570, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "cs131_notes/lecture20/main.tex", "max_stars_repo_name": "suryadheeshjith/CS_131", "max_stars_repo_head_hexsha": "98fd6511b684cd14f99d3a8d280385d36732e568", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cs131_notes/lecture20/main.tex", "max_issues_repo_name": "suryadheeshjith/CS_131", "max_issues_repo_head_hexsha": "98fd6511b684cd14f99d3a8d280385d36732e568", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cs131_notes/lecture20/main.tex", "max_forks_repo_name": "suryadheeshjith/CS_131", "max_forks_repo_head_hexsha": "98fd6511b684cd14f99d3a8d280385d36732e568", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 72.0168067227, "max_line_length": 795, "alphanum_fraction": 0.7817969662, "num_tokens": 2049, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.3085785671266515}}
{"text": "\\documentclass[a4paper,10pt]{article}\n%\\documentclass[a4paper,10pt]{scrartcl}\n\n\\usepackage[utf8]{inputenc}\n\\usepackage{dsfont}\n\n\\title{Coupled Probabilistic Latent Semantic Analysis}\n\\author{John McCrae}\n\n\\pdfinfo{%\n  /Title    (Coupled Probabilistic Latent Semantic Analysis)\n  /Author   (John McCrae)\n  /Creator  ()\n  /Producer ()\n  /Subject  ()\n  /Keywords ()\n}\n\n\\begin{document}\n\\maketitle\n\n\\section{Preliminaries}\n\nAssume the observed variables are\n\n\\[\n X = ( w^l_{jn} ) ; w^l_{jn} \\in \\{ 1,\\ldots V \\}\n\\]\n\nWhere there are $J$ documents each of length $N^l_j$ and $l \\in \\{1,2\\}$. The\nlatent variables are\n\n\\[\n Y = ( z^l_{jn} ) ; z^l_{jn} \\in \\{ 1,\\ldots K \\}\n\\]\n\n\\section{Model definition}\n\nAssume we have the following model variables\n\n\\[\n \\Theta = ( \\phi^l_{wk}, \\theta^l_{kj} )\n\\]\n\nAnd that the model is given as \n\\[\n p_\\Theta(X,Y) = \\prod_j^J\\prod_l^2\\prod_n^{N^l_j}\n\\phi^l_{w^l_{jn}z^l_{jn}}\\theta^l_{z^l_{jn}j}\n\\]\n\nAnd we have the marginal distribution as follows:\n\\[\n p_\\Theta(X) = \\prod_j^J\\prod_l^2\\prod_n^{N^l_j}\\prod_k^K\n\\phi^l_{w^l_{jn}k}\\theta^l_{kj}\n\\]\n\nFollowing \\cite{platt} we define the posterior condition as \n\n\\[\n \\pi_{jk}(w_j,z_j) = \\frac{\\sum_n^{N^2_j} \\mathds{1}(z^1_{jn} = k)}{N^1_j} - \n  \\frac{\\sum_n^{N_j^2} \\mathds{1}(z^2_{jn} = k)}{N^2_j}\n\\]\n\\[\n  = \\frac{N^1_{jk}}{N^1_j} - \\frac{N^2_{jk}}{N^2_j}\n\\]\n\nAnd that\n\n\\[\n \\pi(X,Y) = \\sum_j^J\\sum_k^K \\pi_{jk}(w_j,z_j)\n\\]\n\nHence, the problem is to find $\\Theta^*$ for some $\\epsilon$ such that\n\n\\[\n \\Theta^* = \\arg\\max_\\Theta p_\\Theta(Y|X)\n\\]\n\nSuch that\n\n\\[\n E_\\Theta[\\pi(X,Y)] \\leq \\epsilon\n\\]\n\n\\section{Solution}\n\nBy \\cite{ganchev}, this can be solved by an E-M procedure where\n\n\\[\n \\textrm{\\bf{E}:}~~~~ q^{t+1} = \\arg\\min_q KL(q(Y) || p_{\\Theta^t} (Y | X))\n\\]\n\\[\n \\textrm{\\bf{M}:}~~~~ \\Theta^{t+1} = \\arg\\max_\\Theta\nE_{q^{t+1}}[log_\\Theta(p(X,Y))]\n\\]\n\nWhere KL is as usual:\n\\[\n KL(p(X)||q(X)) = \\sum_X p(x) \\log\\left(\\frac{p(x)}{q(x)}\\right)\n\\]\n\nAnd $q(Y)$ is constrained by\n\\[\n q(Y) : E_q[\\pi(X,Y)] \\leq \\epsilon\n\\]\n\nBy Lagrangian duality, the problem of solving\n\\[\n \\arg\\min_q KL(q(Y) || p_{\\Theta} (Y | X))\n\\]\nSubject to\n\\[\n E_q[\\pi(X,Y)] \\leq \\xi ; ||\\xi|| < \\epsilon\n\\]\n\nIs equivalent to finding\n\\[\n q^*(z_j) = \\frac{p_\\Theta(z_j|X) \\exp(-\\lambda^*\n\\theta(X,Y))}{\\zeta(\\lambda^*)}\n\\]\nWhere\n\\[\n \\lambda^* = \\arg\\max_{\\lambda \\geq 0} - log(\\zeta(\\lambda)) - \\epsilon\\lambda\n\\]\nAnd\n\\[\n \\zeta(\\lambda) = \\sum_Y p_\\Theta(Y|X) \\exp(-\\lambda \\pi(X,Y))\n \\]\n \\[\n = \\sum_j^J\\sum_l^2 p_\\Theta(z^l_j|X) e^{-\n\\lambda \\pi_j(X,z_j)}\n\\]\nIt follows by differentiation\n\\[\n -\\frac{\\zeta'(\\lambda^*)}{\\zeta(\\lambda^*)} - \\epsilon = 0\n\\]\nAnd the solution to this can be found by Newtonian gradient descent\n\nGiven we have $\\lambda^*$ then we can apply\n\n\\[\n q^*(z_j) \\propto p_\\Theta(z_j|X) exp(-\\lambda^*\\pi(X,Y))\n\\]\n\nAnd hence we can use a Gibbs-like sampling\n\n\\[\n p_\\Theta(z^{tl}_{jn} = k|X) \\propto\n\\phi^{tl}_{x_{jn}k}\\theta^{tl}_{kj}exp(-\\lambda^*\\pi_{jk}(w_j,z_j))\n\\]\n\nFinally the maximization step is trivial\n\n\\[\n \\phi^l_{wk} = \\frac{N^l_{wk}}{N^l_k}\n\\]\n\n\\[\n \\theta^l_{kj} = \\frac{N^l_{kj}}{N^l_j}\n\\]\n\n\\section{Dirichlet assumption}\n\nThe Dirichlet assumption is that \n\n\\[\n \\theta^l_j \\sim Dir(\\alpha)\n\\]\n\\[\n \\phi^l_k \\sim Dir(\\beta)\n\\]\n\nThe result of which is that the maximization step is generalized\nto~\\cite{porteous}\n\n\\[\n \\theta^l_{kj} = \\frac{N^l_{kj} + \\alpha}{N^l_k + K\\alpha}\n\\]\n\\[\n \\phi^l_{wk} = \\frac{N^l_{wk} + \\beta}{N^l_k + V \\beta}\n\\]\n\n\n\\section{Initialization}\n\n\\begin{enumerate}\n \\item Sort words by frequency $\\{w'_1,\\ldots w'_V\\}$\n \\item Find $K-1$ values, $\\kappa_i$, such that $\\kappa_i < \\kappa_{i+1}$ and\n   $\\sum_{j = \\kappa_i}^{\\kappa_{i+1}} w'_j \\leq \\frac{N}{K}$\n \\item Initialize $z^l_{jn} = k$ where $w^l_{jn} = w'_i$ and $\\kappa_k \\leq i <\n\\kappa_{i+1}$\n \\item Calculate initial $\\Theta$\n \n\\section{Notes}\n\n\\cite{platt} used 500 iterations at $\\alpha=1.1$, $\\beta=1.01$.\n \n\\end{enumerate}\n\n\n\n\n\n\n\\begin{thebibliography}{9}\n\n\\bibitem{platt}\nJohn C. Platt and Kristina Toutanova and Wen-tau Yih (2010).\nTranslingual Document Representations from Discriminative Projections.\n\n\\bibitem{ganchev}\nKuzman Ganchev and João Graça and Jennifer Gillenwater and Ben Taskar (2010).\nPosterior Regularization for Structured Latent Variable Models.\n\n\\bibitem{porteous}\nIan Porteous and David Newman and Alexander Ihler and Arthur Asuncion\nand Padhraic Smyth and Max Welling (2008).\nFast Collapsed Gibbs Sampling For Latent Dirichlet Allocation.\n\n\\end{thebibliography}\n\n\\end{document}\n", "meta": {"hexsha": "26028b2885980739ad97ff779aea4d04eb6a07b9", "size": 4464, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "lda/docs/cplsa.tex", "max_stars_repo_name": "monnetproject/bliss", "max_stars_repo_head_hexsha": "cc0ad7bc2fda400d05e6431b86f223c23c6cd45d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-04-20T19:17:10.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-20T19:17:10.000Z", "max_issues_repo_path": "lda/docs/cplsa.tex", "max_issues_repo_name": "monnetproject/bliss", "max_issues_repo_head_hexsha": "cc0ad7bc2fda400d05e6431b86f223c23c6cd45d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lda/docs/cplsa.tex", "max_forks_repo_name": "monnetproject/bliss", "max_forks_repo_head_hexsha": "cc0ad7bc2fda400d05e6431b86f223c23c6cd45d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0179372197, "max_line_length": 79, "alphanum_fraction": 0.6375448029, "num_tokens": 1736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.30856502991744233}}
{"text": "%%!TEX TS-program = latex\n\\documentclass[]{beamer}\n%\\usepackage{helvet}\n%\\usepackage{pstricks,pst-node,pst-tree}\n\\usepackage{graphicx}\n\\hypersetup{pdfpagemode=FullScreen}\n\\usetheme{Singapore}\n%\\usetheme{copenhagen}\n%\\usetheme{Boadilla}\n%\\usetheme{Warsaw} \n\\usecolortheme{seagull} \n\\setbeamercovered{transparent}\n\\beamertemplatenavigationsymbolsempty \n\\setbeamertemplate{footline}[frame number]\n\n\\usepackage{hyperref}\n\\usepackage{amsmath}\n\\usepackage{amsfonts}\n\\usepackage{amssymb}\n\\usepackage{booktabs}\n\\usepackage{dsfont}\n\\usepackage{multicol}\n\\usepackage{multirow}\n\n\\newcommand{\\R}{\\ensuremath{\\mathds{R}}}\n\\newcommand{\\C}{\\ensuremath{\\mathds{C}}}\n\\newcommand{\\Q}{\\ensuremath{\\mathds{Q}}}\n\\newcommand{\\N}{\\ensuremath{\\mathcal{N}}}\n\\newcommand{\\Z}{\\ensuremath{\\mathds{Z}}}\n\n\\setbeamerfont{bib}{size*={4.00}{4.00}}\n\\usepackage[square, sort, numbers, authoryear]{natbib}\n\\renewcommand{\\bibsection}{\\subsubsection*{\\bibname } }\n\n\n\\DeclareMathOperator*{\\argmax}{argmax}\n\\DeclareMathOperator*{\\argmin}{argmin}\n\\DeclareMathOperator*{\\Corr}{Corr}\n\\DeclareMathOperator*{\\E}{E}\n\\DeclareMathOperator*{\\sign}{sign}\n\\renewcommand{\\vec}[1]{\\mathbf{#1}}\n\\usepackage{hyperref}\n\n\\usepackage{multicol}\n\\usepackage{multirow}\n\\usepackage{pbox}\n\n\n\\institute[]{}\n%\\logo{\\pgfimage[width=.8cm,height=.8cm]{../KU_logo}}\n\\title[Active Manifesto]{\n{\nSpeeding up the Manifesto Project: \\\\ Active learning strategies for \\\\efficient automated political annotations\n}}\n\\author{\nFelix Biessmann\\thanks{felix.biessmann@gmail.com},~ \nPhilipp Schmidt\\thanks{schmidtiphil@gmail.com}\n}\n\\date{}\n\\begin{document}\n\n\\begin{frame} \n\\titlepage \n\\end{frame}\t\n\n%\n\\section{Intro}\n\\subsection{}\n\n\\begin{frame}\\frametitle{Disclaimers}\n\\small\n\\begin{itemize}\n\\item (For us) This open source project is a hobby\n\\item It has nothing to do with our job\n\\item Apologies if we missed to cite somebody in this room\n\\item We'd be excited to hear about more related work\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}\\frametitle{Motivation}\n\\begin{itemize}[<+->]\n\\item Automated political analysis required for \n\\begin{itemize}\n\\item Political scientists\n\\item Journalists\n\\item Average media consumer\n\\end{itemize}\n\\item ML models need in-domain training data \\footnote{\\cite{Biessmann16}}\n\\item But annotation budget is often limited:\n\\begin{itemize}\n\\item Temporal constraints (before elections) \\footnote{\\cite{merz2017}, \\cite{bronline}}\n\\item Online news media (too much content) \n\\end{itemize}\n\\item[$\\rightarrow$] If you cannot annotate all texts:\\\\\n\\centering How to choose which texts to annotate (first)?\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}\\frametitle{Active Learning}\n\\begin{itemize}[<+->]\n\\item Given limited annotation budget, find the best model\n\\item How? \\\\\n\\begin{itemize}\n\\item Annotate difficult ones\\footnote{For which model is most uncertain.} first\n\\end{itemize}\n\\item Why?\n\\begin{itemize}\n\\item Intuition: \\\\\n\\textit{ Model learns most from difficult examples}\\\\\n\\item Math:\\\\\n\\textit{ Gradient of loss function is larger for difficult examples }\\\\\n\\end{itemize}\n\\end{itemize}\n\\end{frame}\n\n\\section{Methods}\n\\subsection{}\n\n\\begin{frame}\\frametitle{Data}\n\n\\begin{itemize}\n\\item All annotated German texts from:\\\\ \n\\url{https://manifestoproject.wzb.eu/} \n\\item Custom python tooling for manifesto API:\\\\\n{\\footnotesize \\url{https://github.com/felixbiessmann/active-manifesto} }\\\\\n\\item Only texts with more than 1000 observed labels\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}\\frametitle{Model}\n\\begin{itemize}\n\\item Preprocessing\n\\begin{itemize}\n\\item Unigram Bag-of-Words features\n\\item Hashing Vectorizer\n\\end{itemize}\n\\item Classification Model: Multinomial Logistic Regression\n\\begin{eqnarray}\\label{eq:logreg_multiclass}\np(y=k|\\vec{x}) = \\frac{e^{z_k}}{\\sum_{j=1}^K e^{z_j}}  \\textrm{ with }  z_k=\\vec{w}_k^{\\top}\\vec{x}.\n\\end{eqnarray}\nWith\n\\begin{itemize}\n\\item Labels $y\\in\\{1,2,\\dots,K\\}$ (manifesto code)\\\\ \n\\item $\\vec{w}_1,\\dots,\\vec{w}_K\\in\\R^{d}$ weight vectors of $k$th manifesto code\\\\ \n%\\item $L_2$ norm regularization of weights\n\\end{itemize}\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}\\frametitle{Offline Experiments}\n\n\\begin{itemize}\n\\item Train model on 1\\%, 10\\%, 20\\%, \\dots, 100\\% of training data\n\\item Vary sampling strategies to select from unlabelled texts\n\\item Compute accuracy on hold-out data\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}\\frametitle{Active Learning Strategies}\n\n\\begin{itemize}\n\\item Random Baseline: Uniform random sampling\n\\item Uncertainty Sampling: Only top-prediction counts\n\\begin{align}\\label{eq:uncertainty_sampling}\n\\vec{x}_i = \\argmax_{i,k} \\left(1- p(y=k|\\vec{x}_i,\\vec{W})\\right)\n\\end{align}\n\\item Entropy Sampling: All predictions count\n\\begin{align}\\label{eq:entropy_sampling}\n\\vec{x}_i = \\argmax_{i} \\sum_k p(y=k|\\vec{x}_i,\\vec{W}) \\log(p(y=k|\\vec{x}_i,\\vec{W}))\n\\end{align}\n\\item Margin Sampling: Top 2 predictions count\n\\begin{align}\\label{eq:entropy_sampling}\n\\vec{x}_i = \\argmin_{i} \\left(p(y=k_1|\\vec{x}_i,\\vec{W}) - p(y=k_2|\\vec{x}_i,\\vec{W}) \\right)\n\\end{align}\n\\end{itemize}\n\\end{frame}\n\n\n\n\n\\section{Results}\n\\subsection{}\n\n\n\\begin{frame}\\frametitle{Results: 'Perfect' Reference Model}\n\\footnotesize\n\\begin{table}\n\\centering\n\\begin{tabular}{cccccc}\n\\toprule\n&  manifesto code & precision  &  recall&  f1-score &  support\\\\\n\\midrule\n&   107&  0.60& 0.48& 0.53&  774\\\\\n&   201&  0.51& 0.55& 0.53& 1194\\\\\n&   202&  0.63& 0.57& 0.60&  983\\\\\n&   305&  0.46& 0.59& 0.52&  783\\\\\n&   403&  0.52& 0.48& 0.50& 1281\\\\\n&   411&  0.39& 0.60& 0.47& 1535\\\\\n&   501&  0.61& 0.55& 0.58& 1380\\\\\n&   502&  0.65& 0.41& 0.50&  587\\\\\n&   503&  0.46& 0.52& 0.49& 2083\\\\\n&   506&  0.63& 0.48& 0.54& 1026\\\\\n&   605&  0.56& 0.44& 0.49&  576\\\\\n&   701&  0.59& 0.39& 0.47& 1123\\\\\n\\bottomrule\n& avg / total&  0.50& 0.48& 0.48&17559\\\\\n\\end{tabular}\n\\caption{Precision, recall, F1 score and number of instances per class. }\n\\label{tab:baseline_model_report} \n\\end{table}\n\n\\end{frame}\n\n\\begin{frame}\\frametitle{Active Learning Results}\n\\begin{center}\n\\includegraphics[width=\\textwidth]{images/active_learning_manifesto.pdf} \\\\\nMedian accuracy and the 5th/95th percentile across 100 repetitions \\\\\n\\end{center}\n\n\\end{frame}\n\n\\section{Conclusion}\n\\subsection{}\n\n\n\\begin{frame}\\frametitle{Conclusion}\n\\begin{itemize}\n\\item Automated political analysis requires annotations\n\\item \\textbf{Limited budged} for annotations of political texts \n\\item Active Learning\n\\begin{itemize}\n\\item Helps to select which texts to annotate\n\\item Perfect model with 80\\% of data\n\\item Almost perfect (over 90\\%) with 50\\% of data\n\\end{itemize}\n\\item[$\\rightarrow$] Active learning can speed up political annotations. \n\\item Code:\\\\\n\\footnotesize\n \\url{https://github.com/felixbiessmann/active-manifesto} \n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}\\frametitle{Limitations}\n\\begin{itemize}\n\\item We used a simple model\n\\item Random sampling is an unrealistic baseline\n\\item We only performed offline experiments\n\\item[$\\rightarrow$] More convincing: online experiments\n\\end{itemize}\n\\end{frame}\n\n\n\\section{Demo}\n\\subsection{}\n\n\n\\begin{frame}\\frametitle{Demo \\url{http://rightornot.info}}\n\\begin{itemize}\n\\item Goal: Collect Annotations with Active Learning\n\\begin{enumerate}\n\\item For political analysis of non-manifesto texts\n\\item For comparing manifesto annotations with laymen judgements\n\\end{enumerate}\n\\item Incentive for users: \n\\begin{enumerate}\n\\item Estimate your political bias\n\\item Escape your political filter bubble\n\\end{enumerate}\n\\end{itemize}\n\\centering\n\\end{frame}\n\n\n\\begin{frame}\\frametitle{Demo \\url{http://rightornot.info}}\n\\centering \n\\includegraphics[width=.9\\textwidth]{images/active_learning_manifesto-left-neutral-right}\\\\\nLabels: Left, Neutral, Right\n\\end{frame}\n\n\\begin{frame}\\frametitle{Demo \\url{http://rightornot.info}}\n\\centering \n\\includegraphics[width=.6\\textwidth]{images/web-demo}\\\\\n\\end{frame}\n\n\\begin{frame}\\frametitle{References}\n\\usebeamerfont{bib}\n\n\\bibliographystyle{abbrvnat}\n\\def\\newblock{}\n\\vspace{2em}\n\\bibliography{active-manifesto} \n\\end{frame}\n\n\\end{document} \n", "meta": {"hexsha": "2ec53a8d2de07148fab88130da3655f3bac6d3df", "size": 7983, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "manuscript/manifesto-conference-presentation.tex", "max_stars_repo_name": "felixbiessmann/active-manifesto", "max_stars_repo_head_hexsha": "0802200450dbf7fce6a75068f1dfe4d92fcb23e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-12-22T09:13:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-04T20:52:51.000Z", "max_issues_repo_path": "manuscript/manifesto-conference-presentation.tex", "max_issues_repo_name": "felixbiessmann/active-manifesto", "max_issues_repo_head_hexsha": "0802200450dbf7fce6a75068f1dfe4d92fcb23e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2017-11-02T22:34:42.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-23T20:33:25.000Z", "max_forks_repo_path": "manuscript/manifesto-conference-presentation.tex", "max_forks_repo_name": "felixbiessmann/active-manifesto", "max_forks_repo_head_hexsha": "0802200450dbf7fce6a75068f1dfe4d92fcb23e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-05-03T22:35:58.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-03T22:35:58.000Z", "avg_line_length": 27.0610169492, "max_line_length": 112, "alphanum_fraction": 0.7366904672, "num_tokens": 2661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.30856502991744233}}
{"text": "%% LyX 2.2.2 created this file.  For more info, see http://www.lyx.org/.\n%% Do not edit unless you really know what you are doing.\n\\documentclass[english]{beamer}\n\\usepackage{mathptmx}\n\\usepackage{eulervm}\n\\usepackage[T1]{fontenc}\n\\usepackage[latin9]{inputenc}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{graphicx}\n\n\\makeatletter\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LyX specific LaTeX commands.\n%% A simple dot to overcome graphicx limitations\n\\newcommand{\\lyxdot}{.}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Textclass specific LaTeX commands.\n % this default might be overridden by plain title style\n \\newcommand\\makebeamertitle{\\frame{\\maketitle}}%\n % (ERT) argument for the TOC\n \\AtBeginDocument{%\n   \\let\\origtableofcontents=\\tableofcontents\n   \\def\\tableofcontents{\\@ifnextchar[{\\origtableofcontents}{\\gobbletableofcontents}}\n   \\def\\gobbletableofcontents#1{\\origtableofcontents}\n }\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% User specified LaTeX commands.\n\\usetheme{CambridgeUS} \n\\beamertemplatenavigationsymbolsempty\n\n\\AtBeginSection[]{\n  \\begin{frame}\n  \\vfill\n  \\centering\n  \\begin{beamercolorbox}[sep=8pt,center,shadow=true,rounded=true]{title}\n    \\usebeamerfont{title}\\insertsectionhead\\par%\n  \\end{beamercolorbox}\n  \\vfill\n  \\end{frame}\n}\n\n\\makeatother\n\n\\usepackage{babel}\n\\begin{document}\n\n\\global\\long\\def\\reals{\\mathbf{R}}\n\\global\\long\\def\\RR{\\mathbf{R}}\n \\global\\long\\def\\integers{\\mathbf{Z}}\n \\global\\long\\def\\naturals{\\mathbf{N}}\n \\global\\long\\def\\rationals{\\mathbf{Q}}\n \\global\\long\\def\\ca{\\mathcal{A}}\n \\global\\long\\def\\cb{\\mathcal{B}}\n \\global\\long\\def\\cc{\\mathcal{C}}\n \\global\\long\\def\\cd{\\mathcal{D}}\n \\global\\long\\def\\ce{\\mathcal{E}}\n \\global\\long\\def\\cf{\\mathcal{F}}\n \\global\\long\\def\\cg{\\mathcal{G}}\n \\global\\long\\def\\ch{\\mathcal{H}}\n \\global\\long\\def\\ci{\\mathcal{I}}\n \\global\\long\\def\\cj{\\mathcal{J}}\n \\global\\long\\def\\ck{\\mathcal{K}}\n \\global\\long\\def\\cl{\\mathcal{L}}\n \\global\\long\\def\\cm{\\mathcal{M}}\n \\global\\long\\def\\cn{\\mathcal{N}}\n \\global\\long\\def\\co{\\mathcal{O}}\n \\global\\long\\def\\cp{\\mathcal{P}}\n \\global\\long\\def\\cq{\\mathcal{Q}}\n \\global\\long\\def\\calr{\\mathcal{R}}\n \\global\\long\\def\\cs{\\mathcal{S}}\n \\global\\long\\def\\ct{\\mathcal{T}}\n \\global\\long\\def\\cu{\\mathcal{U}}\n \\global\\long\\def\\cv{\\mathcal{V}}\n \\global\\long\\def\\cw{\\mathcal{W}}\n \\global\\long\\def\\cx{\\mathcal{X}}\n \\global\\long\\def\\cy{\\mathcal{Y}}\n \\global\\long\\def\\cz{\\mathcal{Z}}\n \\global\\long\\def\\ind#1{1(#1)}\n %\\newcommand{\\pr}{P}\n\\global\\long\\def\\pr{\\mathbb{P}}\n \\global\\long\\def\\predsp{\\cy}\n %{\\hat{\\cy}}\n\\global\\long\\def\\outsp{\\cy}\n\n\\global\\long\\def\\prxy{P_{\\cx\\times\\cy}}\n \\global\\long\\def\\prx{P_{\\cx}}\n \\global\\long\\def\\prygivenx{P_{\\cy\\mid\\cx}}\n %\\newcommand{\\ex}{E}\n\\global\\long\\def\\ex{\\mathbb{E}}\n \\global\\long\\def\\var{\\textrm{Var}}\n \\global\\long\\def\\Ind{\\mathbf{1}}\n \\global\\long\\def\\cov{\\textrm{Cov}}\n \\global\\long\\def\\sgn{\\textrm{sgn}}\n \\global\\long\\def\\sign{\\textrm{sign}}\n \\global\\long\\def\\kl{\\textrm{KL}}\n \\global\\long\\def\\law{\\mathcal{L}}\n \\global\\long\\def\\eps{\\varepsilon}\n \\global\\long\\def\\as{\\textrm{ a.s.}}\n \\global\\long\\def\\io{\\textrm{ i.o.}}\n \\global\\long\\def\\ev{\\textrm{ ev.}}\n \\global\\long\\def\\convd{\\stackrel{d}{\\to}}\n \\global\\long\\def\\eqd{\\stackrel{d}{=}}\n \\global\\long\\def\\del{\\nabla}\n \\global\\long\\def\\loss{\\ell}\n \\global\\long\\def\\risk{R}\n \\global\\long\\def\\emprisk{\\hat{R}}\n \\global\\long\\def\\lossfnl{L}\n \\global\\long\\def\\emplossfnl{\\hat{L}}\n \\global\\long\\def\\empminimizer#1{\\hat{#1}^{*}}\n \\global\\long\\def\\minimizer#1{#1^{*}}\n\\global\\long\\def\\optimizer#1{#1^{*}}\n \\global\\long\\def\\etal{\\textrm{et. al.}}\n \\global\\long\\def\\tr{\\operatorname{tr}}\n\n\\global\\long\\def\\trace{\\operatorname{trace}}\n \\global\\long\\def\\diag{\\text{diag}}\n \\global\\long\\def\\rank{\\text{rank}}\n \\global\\long\\def\\linspan{\\text{span}}\n \\global\\long\\def\\spn{\\text{span}}\n \\global\\long\\def\\proj{\\text{Proj}}\n \\global\\long\\def\\argmax{\\operatornamewithlimits{arg\\, max}}\n \\global\\long\\def\\argmin{\\operatornamewithlimits{arg\\, min}}\n\n\\global\\long\\def\\bfx{\\mathbf{x}}\n \\global\\long\\def\\bfy{\\mathbf{y}}\n \\global\\long\\def\\bfl{\\mathbf{\\lambda}}\n \\global\\long\\def\\bfm{\\mathbf{\\mu}}\n \\global\\long\\def\\calL{\\mathcal{L}}\n\n\\global\\long\\def\\vw{\\boldsymbol{w}}\n \\global\\long\\def\\vx{\\boldsymbol{x}}\n \\global\\long\\def\\vxi{\\boldsymbol{\\xi}}\n \\global\\long\\def\\valpha{\\boldsymbol{\\alpha}}\n \\global\\long\\def\\vbeta{\\boldsymbol{\\beta}}\n \\global\\long\\def\\vsigma{\\boldsymbol{\\sigma}}\n\\global\\long\\def\\vtheta{\\boldsymbol{\\theta}}\n \\global\\long\\def\\vd{\\boldsymbol{d}}\n \\global\\long\\def\\vs{\\boldsymbol{s}}\n \\global\\long\\def\\vt{\\boldsymbol{t}}\n \\global\\long\\def\\vh{\\boldsymbol{h}}\n \\global\\long\\def\\ve{\\boldsymbol{e}}\n \\global\\long\\def\\vf{\\boldsymbol{f}}\n \\global\\long\\def\\vg{\\boldsymbol{g}}\n \\global\\long\\def\\vz{\\boldsymbol{z}}\n \\global\\long\\def\\vk{\\boldsymbol{k}}\n \\global\\long\\def\\va{\\boldsymbol{a}}\n \\global\\long\\def\\vb{\\boldsymbol{b}}\n \\global\\long\\def\\vv{\\boldsymbol{v}}\n \\global\\long\\def\\vy{\\boldsymbol{y}}\n\n\\global\\long\\def\\hil{\\ch}\n \\global\\long\\def\\rkhs{\\hil}\n \\global\\long\\def\\ber{\\text{Ber}}\n\n\n\\title[DS-GA 1003 ]{Gaussian Mixture Models}\n\n\\author{David Rosenberg, Brett Bernstein}\n\n\\date{\\today}\n\n\\institute{New York University}\n\n\\makebeamertitle\n\n\\section{Intro Question}\n\\begin{frame}{Intro Question}\n  Suppose we begin with a dataset $\\cd = \\{x_1,\\ldots,x_n\\}\\subseteq\\RR^2$\n  and we run $k$-means (or $k$-means$++$) to obtain $k$ cluster\n  centers.  Below we have drawn the cluster centers.  If we are given\n  a new $x\\in\\RR^2$, we can assign it a label based on which cluster\n  center is closest.  What regions of the plane below correspond to\n  each possible labeling?\n  \\begin{center}\n    %trim={<left> <lower> <right> <upper>}\n    \\includegraphics[height=.7\\textheight,trim={0 6cm 0 8cm}]{Figures/clustering/vorpoints.pdf}\n  \\end{center}\n\\end{frame}\n\\begin{frame}{Intro Solution}\n  \\begin{itemize}\n  \\item Note that each cell is disjoint (except for the boarders), and\n    convex.\n  \\item This can be thought of as a limitation of $k$-means: neither\n    will be true for GMMs.\n  \\end{itemize}\n  \\begin{center}\n    \\includegraphics[height=.9\\textheight,trim={0 5cm 0 8cm}]{Figures/clustering/voronoi.pdf}\n  \\end{center}\n\\end{frame}\n\\section{Gaussian Mixture Models}\n\\begin{frame}{Yesterday's Intro Question}\n  Consider the following probability model for generating data.\n  \\begin{enumerate}\n  \\item Roll a weighted $k$-sided die to choose a label\n    $z\\in\\{1,\\ldots,k\\}$.  Let $\\pi$ denote the PMF for the die.\n  \\item Draw $x\\in\\reals^d$ randomly from the multivariate normal\n    distribution $\\cn(\\mu_z,\\Sigma_z)$.\n  \\end{enumerate}\n  Solve the following questions.\n  \\begin{enumerate}\n  \\item What is the joint distribution of $x,z$ given $\\pi$ and the\n    $\\mu_z,\\Sigma_z$ values?\n  \\item Suppose you were given the dataset\n    $\\cd=\\{(x_1,z_1),\\ldots,(x_n,z_n)\\}$.  How would you estimate the\n    die weightings, and the $\\mu_z,\\Sigma_z$ values?\n  \\item How would you determine the label for a new datapoint $x$?\n  \\end{enumerate}\n\\end{frame}\n\\begin{frame}{Yesterday's Intro Solution}\n  \\begin{enumerate}\n  \\item The joint PDF/PMF is given by\n    $$p(x,z) = \\pi(z)f(x;\\mu_z,\\Sigma_z)$$\n    where\n    $$f(x;\\mu_z,\\Sigma_z) =\n    \\frac{1}{\\sqrt{|2\\pi\\Sigma_z|}}\\exp\\left(-\\frac{1}{2}(x-\\mu)^T\\Sigma^{-1}(x-\\mu)\\right).$$\n  \\item We could use maximum likelihood estimation.  Our estimates are\n    $$\\begin{array}{rcl}\n    n_z  & = & \\sum_{i=1}^n \\Ind(z_i=z) \\\\\n    \\hat{\\pi}(z) & = & \\frac{n_z}{n}\\\\\n    \\hat{\\mu}_z & = & \\frac{1}{n_z}\\sum_{i:z_i=z} x_i\\\\\n    \\hat{\\Sigma}_z & = & \\frac{1}{n_z}\\sum_{i:z_i=z} (x_i-\\hat{\\mu}_z)(x_i-\\hat{\\mu}_z)^T.\n    \\end{array}$$\n  \\item $\\argmax_z p(x,z)$\n  \\end{enumerate}\n\\end{frame}\n\\begin{frame}{Probabilistic Model for Clustering}\n\n\\begin{itemize}\n\\item Let's consider a \\textbf{generative model} for the data.\n\\item Suppose \n\n\\begin{enumerate}\n\\item There are $k$ clusters.\n\\item We have a probability density for each cluster.\n\\end{enumerate}\n\\item Generate a point as follows\n\n\\begin{enumerate}\n\\item Choose a random cluster $z\\in\\left\\{ 1,2,\\ldots,k\\right\\} $. \n\\item Choose a point from the distribution for cluster $Z$. \n\\end{enumerate}\n\\item The clustering algorithm is then:\n  \\begin{enumerate}\n  \\item Use training data to fit the parameters of the generative\n    model.\n  \\item For each point, choose the cluster with the highest likelihood \n    based on model.\n  \\end{enumerate}\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Gaussian Mixture Model ($k=3$)}\n\n\\begin{enumerate}\n\\item Choose $z\\in\\left\\{ 1,2,3\\right\\}$\n\\item Choose $x\\mid z\\sim\\cn\\left(X\\mid\\mu_{z},\\Sigma_{z}\\right)$.\n\\end{enumerate}\n\\begin{center}\n\\includegraphics[width=0.7\\textwidth]{../Figures/clustering/mixture-3-gaussians}\n\\par\\end{center}\n\n\\end{frame}\n\n\\begin{frame}{Gaussian Mixture Model Parameters ($k$ Components)}\n\n\\begin{center}\n\\begin{eqnarray*}\n\\text{Cluster probabilities}: &  & \\pi=\\left(\\pi_{1},\\ldots,\\pi_{k}\\right)\\\\\n\\text{Cluster means}: &  & \\mu=\\left(\\mu_{1},\\ldots,\\mu_{k}\\right)\\\\\n\\text{Cluster covariance matrices:} &  & \\Sigma=\\left(\\Sigma_{1},\\ldots\\Sigma_{k}\\right)\n\\end{eqnarray*}\n\\begin{itemize}\n\\item What if one cluster had many more points than another cluster?\n\\end{itemize}\n\\end{center}\n\\end{frame}\n\n\\begin{frame}{Gaussian Mixture Model: Joint Distribution }\n\n\\begin{itemize}\n\\item Factorize the joint distribution:\n\\begin{eqnarray*}\np(x,z) & = & p(z)p(x\\mid z)\\\\\n& = & \\pi_{z}\\cn\\left(x\\mid\\mu_{z},\\Sigma_{z}\\right)\n\\end{eqnarray*}\n\n\n\\begin{itemize}\n\\item $\\pi_{z}$ is probability of choosing cluster $z$.\n\n\n\\item $x\\mid z$ has distribution $\\cn(\\mu_{z},\\Sigma_{z})$.\n\n\n\\item $z$ corresponding to $x$ is the true cluster assignment. \n\\end{itemize}\n\\end{itemize}\n\n\\begin{itemize}\n\\item Suppose we know all the parameters of the model.\n\\item Then we can easily compute the joint $p(x,z)$, and the\n  conditional $p(z\\mid x)$.\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Latent Variable Model }\n\n\\begin{itemize}\n\\item We observe $x$.\n\\item In the intro problem we had labeled data, but here we don't observe\n  $z$, the cluster assignment.\n\n\n\n\\item Cluster assignment $z$ is called a \\textbf{hidden} \\textbf{variable}\nor \\textbf{latent variable}.\n\n\n\n\n\\end{itemize}\n\\begin{definition}\nA\\textbf{ latent variable model }is a probability model for which\ncertain variables are never observed.\n\n\n\n\n\\end{definition}\n\ne.g. The Gaussian mixture model is a latent variable model.\n\\end{frame}\n\n\\begin{frame}{The GMM ``Inference'' Problem}\n\n\\begin{itemize}\n\\item We observe $x$. We want to know $z$.\n\n\n\n\\item The conditional distribution of the cluster $z$ given $x$ is\n\\[\np(z\\mid x)=p(x,z)/p(x)\n\\]\n\n\n\n\\item The conditional distribution is a\\textbf{ soft assignment }to clusters.\n\n\n\n\\item A \\textbf{hard assignment }is\n\\[\nz^{*}=\\argmax_{z\\in\\left\\{ 1,\\ldots,k\\right\\} }p(z\\mid x).\n\\]\n\n\n\n\\item So if we have the model, clustering is trivial.\n\\end{itemize}\n\\end{frame}\n\n\n\\section{Mixture Models}\n\\begin{frame}{Gaussian Mixture Model: Marginal Distribution}\n\n\\begin{itemize}\n\\item The \\textbf{marginal distribution} for a single observation $x$ is\\textbf{\n\\begin{eqnarray*}\np(x) & = & \\sum_{z=1}^{k}p(x,z)\\\\\n & = & \\sum_{z=1}^{k}\\pi_{z}\\cn\\left(x\\mid\\mu_{z},\\Sigma_{z}\\right)\n\\end{eqnarray*}\n}\n\n\n\n\\item Note that $p(x)$ is a convex combination of probability densities.\n\n\n\n\\item This is a common form for a probability model...\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Mixture Distributions (or Mixture Models)}\n\n\\begin{definition}\nA probability density $p(x)$ represents a \\textbf{mixture distribution\n}or \\textbf{mixture model, }if we can write it as a \\textbf{convex\ncombination} of probability densities. That is, \n\\[\np(x)=\\sum_{i=1}^{k}w_{i}p_{i}(x),\n\\]\nwhere $w_{i}\\ge0$, $\\sum_{i=1}^{k}w_{i}=1$, and each $p_{i}$ is\na probability density.\n\n\n\n\\end{definition}\n\n\\begin{itemize}\n\\item In our Gaussian mixture model, $x$ has a \\textbf{mixture distribution}.\n\n\n\n\\item More constructively, let $S$ be a set of probability distributions:\n\n\\begin{enumerate}\n\\item Choose a distribution randomly from $S$.\n\\item Sample $x$ from the chosen distribution.\n\\end{enumerate}\n\\item Then $x$ has a mixture distribution.\n\\end{itemize}\n\\end{frame}\n\n\n\\section{Learning in Gaussian Mixture Models}\n\n\\begin{frame}{The GMM ``Learning'' Problem}\n\n\\begin{itemize}\n\\item Given data $x_{1},\\ldots,x_{n}$ drawn from a GMM,\n\\item Estimate the parameters: \n\\begin{eqnarray*}\n\\text{Cluster probabilities}: &  & \\pi=\\left(\\pi_{1},\\ldots,\\pi_{k}\\right)\\\\\n\\text{Cluster means}: &  & \\mu=\\left(\\mu_{1},\\ldots,\\mu_{k}\\right)\\\\\n\\text{Cluster covariance matrices:} &  & \\Sigma=\\left(\\Sigma_{1},\\ldots\\Sigma_{k}\\right)\n\\end{eqnarray*}\n\n\n\n\\item Once we have the parameters, we're done. \n\n\n\n\\item Just do ``inference'' to get cluster assignments.\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Estimating/Learning the Gaussian Mixture Model}\n\n\\begin{itemize}\n\\item One approach to learning is \\textbf{maximum likelihood}\n\n\\begin{itemize}\n\\item find parameter values that give \\textbf{observed data }the\\textbf{\nhighest likelihood}.\n\\end{itemize}\n\\item The model likelihood for $\\cd=\\left\\{ x_{1},\\ldots,x_{n}\\right\\} $\nis\n\\begin{eqnarray*}\nL(\\pi,\\mu,\\Sigma) & = & \\prod_{i=1}^{n}p(x_{i})\\\\\n & = & \\prod_{i=1}^{n}\\sum_{z=1}^{k}\\pi_{z}\\cn\\left(x_{i}\\mid\\mu_{z},\\Sigma_{z}\\right).\n\\end{eqnarray*}\n\n\n\n\\item As usual, we'll take our objective function to be the log of this:\n\\begin{eqnarray*}\nJ(\\pi,\\mu,\\Sigma) & = & \\sum_{i=1}^{n}\\log\\left\\{ \\sum_{z=1}^{k}\\pi_{z}\\cn\\left(x_{i}\\mid\\mu_{z},\\Sigma_{z}\\right)\\right\\} \n\\end{eqnarray*}\n \n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Properties of the GMM Log-Likelihood}\n\n\\begin{itemize}\n\\item GMM log-likelihood:\n\\begin{eqnarray*}\nJ(\\pi,\\mu,\\Sigma) & = & \\sum_{i=1}^{n}\\log\\left\\{ \\sum_{z=1}^{k}\\pi_{z}\\cn\\left(x_{i}\\mid\\mu_{z},\\Sigma_{z}\\right)\\right\\} \n\\end{eqnarray*}\n\n\n\n\\item Let's compare to the log-likelihood for a single Gaussian:\n\\begin{eqnarray*}\n &  & \\sum_{i=1}^{n}\\log\\cn\\left(x_{i}\\mid\\mu,\\Sigma\\right)\\\\\n & = & -\\frac{nd}{2}\\log\\left(2\\pi\\right)-\\frac{n}{2}\\log\\left|\\Sigma\\right|-\\frac{1}{2}\\sum_{i=1}^{n}(x_{i}-\\mu)'\\Sigma^{-1}(x_{i}-\\mu)\n\\end{eqnarray*}\n\n\n\n\\item For a single Gaussian, the $\\log$ cancels the $\\exp$ in the Gaussian\ndensity.\n\n\\begin{itemize}\n\\item $\\implies$ Things simplify a lot.\n\\end{itemize}\n\n\n\\item For the GMM, the sum inside the $\\log$ prevents this cancellation.\n\n\\begin{itemize}\n\\item $\\implies$ Expression more complicated. No closed form expression\nfor MLE.\n\\end{itemize}\n\\end{itemize}\n\\end{frame}\n\n\n\\section{Issues with MLE for GMM}\n\\begin{frame}{Identifiability Issues for GMM}\n\n\\begin{itemize}\n\\item Suppose we have found parameters \n\\begin{eqnarray*}\n\\text{Cluster probabilities}: &  & \\pi=\\left(\\pi_{1},\\ldots,\\pi_{k}\\right)\\\\\n\\text{Cluster means}: &  & \\mu=\\left(\\mu_{1},\\ldots,\\mu_{k}\\right)\\\\\n\\text{Cluster covariance matrices:} &  & \\Sigma=\\left(\\Sigma_{1},\\ldots\\Sigma_{k}\\right)\n\\end{eqnarray*}\n that are at a local minimum.\n\\end{itemize}\n\n\n\\begin{itemize}\n\\item What happens if we shuffle the clusters? e.g. Switch the labels for\nclusters 1 and 2.\n\\end{itemize}\n\n\n\\begin{itemize}\n\\item We'll get the same likelihood. How many such equivalent settings are\nthere?\n\\end{itemize}\n\n\n\\begin{itemize}\n\\item Assuming all clusters are distinct, there are $k!$ equivalent solutions.\n\\end{itemize}\n\n\n\\begin{itemize}\n\\item Not a problem per se, but something to be aware of.\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Singularities for GMM}\n\n\\begin{itemize}\n\\item Consider the following GMM for 7 data points:\n\\end{itemize}\n\\begin{center}\n\\includegraphics[height=0.4\\textheight]{../Figures/clustering/gmm-singularity}\n\\par\\end{center}\n\n\n\\begin{itemize}\n\\item Let $\\sigma^{2}$ be the variance of the skinny component.\n\\item What happens to the likelihood as $\\sigma^{2}\\to0$?\n\n\n\n\\item In practice, we end up in local minima that do not have this problem.\n\n\\begin{itemize}\n\\item Or keep restarting optimization until we do.\n\\end{itemize}\n\n\n\\item Bayesian approach or regularization will also solve the problem.\n\\end{itemize}\n\\let\\thefootnote\\relax\\footnotetext{\\tiny{From Bishop's \\emph{Pattern recognition and machine learning}, Figure 9.7.}}\n\\end{frame}\n\n\\begin{frame}{Gradient Descent / SGD for GMM}\n\n\\begin{itemize}\n\\item What about running gradient descent or SGD on\n\\begin{eqnarray*}\nJ(\\pi,\\mu,\\Sigma) & = & -\\sum_{i=1}^{n}\\log\\left\\{ \\sum_{z=1}^{k}\\pi_{z}\\cn\\left(x_{i}\\mid\\mu_{z},\\Sigma_{z}\\right)\\right\\} ?\n\\end{eqnarray*}\n\n\n\n\\item Can be done \\textendash{} but need to be clever about it.\n\n\n\\item Each matrix $\\Sigma_{1},\\ldots,\\Sigma_{k}$ has to be positive semidefinite.\n\n\n\\item How to maintain that constraint?\n\n\n\\begin{itemize}\n\\item Rewrite $\\Sigma_{i}=M_{i}M_{i}^{T}$, where $M_{i}$ is an unconstrained\nmatrix. \n\n\n\\item Then $\\Sigma_{i}$ is positive semidefinite. \n\n\\end{itemize}\n\\end{itemize}\n\\end{frame}\n\n\\section{The EM Algorithm for GMM}\n\\begin{frame}{MLE for GMM}\n\n\\begin{itemize}\n\\item From yesterday's intro questions, we know that we can solve the MLE\n  problem if the cluster assignments $z_i$ are known\n  \\begin{eqnarray*}\n    n_z  & = & \\sum_{i=1}^n \\Ind(z_i=z)\\\\\n    \\hat{\\pi}(z) & = & \\frac{n_z}{n}\\\\\n    \\hat{\\mu}_z & = & \\frac{1}{n_z}\\sum_{i:z_i=z} x_i\\\\\n    \\hat{\\Sigma}_z & = & \\frac{1}{n_z}\\sum_{i:z_i=z} (x_i-\\hat{\\mu}_z)(x_i-\\hat{\\mu}_z)^T.\n  \\end{eqnarray*}\n\\item In the EM algorithm we will modify the equations to handle\n  our evolving \\textbf{soft assignments}, which we will call \\textbf{responsibilities}.\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Cluster Responsibilities: Some New Notation}\n\n\\begin{itemize}\n\\item Denote the probability that observed value $x_{i}$ comes from cluster\n$j$ by\n\\[\n\\gamma_{i}^{j}=\\pr\\left(Z=j\\mid X=x_{i}\\right).\n\\]\n\n\n\n\\item The \\textbf{responsibility }that cluster $j$ takes for observation\n$x_{i}$.\n\n\n\n\\item Computationally, \n\\begin{eqnarray*}\n\\gamma_{i}^{j} & = & \\pr\\left(Z=j\\mid X=x_{i}\\right).\\\\\n & = & p\\left(Z=j,X=x_{i}\\right)/p(x)\\\\\n & = & \\frac{\\pi_{j}\\cn\\left(x_{i}\\mid\\mu_{j},\\Sigma_{j}\\right)}{\\sum_{c=1}^{k}\\pi_{c}\\cn\\left(x_{i}\\mid\\mu_{c},\\Sigma_{c}\\right)}\n\\end{eqnarray*}\n\n\n\n\\item The vector $\\left(\\gamma_{i}^{1},\\ldots,\\gamma_{i}^{k}\\right)$ is\nexactly the \\textbf{soft assignment} for $x_{i}$.\n\n\n\n\\item Let $n_{c}=\\sum_{i=1}^{n}\\gamma_{i}^{c}$ be the ``number'' of points\n\\textbf{soft assigned} to cluster $c$.\n\\end{itemize}\n\\end{frame}\n\\begin{frame}{EM Algorithm for GMM: Overview}\n\\begin{itemize}\n  \\item If we know $\\pi$ and $\\mu_j,\\Sigma_j$ for all $j$ then we can\n    easily find $\\gamma_i^j=\\pr(Z=j\\mid X=x_i)$.\n  \\item If we know the (soft) assignments, we can easily find\n    estimates for $\\pi$, $\\mu_j,\\Sigma_j$ for all $j$.\n  \\item Repeatedly alternate the previous 2 steps.\n\\end{itemize}\n\\end{frame}\n\\begin{frame}{EM Algorithm for GMM: Overview}\n\n\\begin{enumerate}\n\\item Initialize parameters $\\mu,\\Sigma,\\pi$.\n\n\n\n\\item ``E step''. Evaluate the responsibilities using current parameters:\n\\[\n\\gamma_{i}^{j}=\\frac{\\pi_{j}\\cn\\left(x_{i}\\mid\\mu_{j},\\Sigma_{j}\\right)}{\\sum_{c=1}^{k}\\pi_{c}\\cn\\left(x_{i}\\mid\\mu_{c},\\Sigma_{c}\\right)},\\quad \\text{for $i=1,\\ldots,n$ and $j=1,\\ldots,k$.}\n\\]\n\n\n\n\n\\item ``M step''. Re-estimate the parameters using responsibilities.\n  [Compare with intro question.]\n\\begin{eqnarray*}\n\\mu_{c}^{\\text{new}} & = & \\frac{1}{n_{c}}\\sum_{i=1}^{n}\\gamma_{i}^{c}x_{i}\\\\\n\\Sigma_{c}^{\\text{new}} & = & \\frac{1}{n_{c}}\\sum_{i=1}^{n}\\gamma_{i}^{c}\\left(x_{i}-\\mu_c^{\\text{new}}\\right)\\left(x_{i}-\\mu_c^{\\text{new}}\\right)^{T}\\\\\n\\pi_{c}^{\\text{new}} & = & \\frac{n_{c}}{n},\n\\end{eqnarray*}\n\\item Repeat from Step 2, until log-likelihood converges. \n\\end{enumerate}\n\\end{frame}\n\n\\begin{frame}{EM for GMM}\n\n\\begin{itemize}\n\\item Initialization\n\\end{itemize}\n\\begin{center}\n\\includegraphics[height=0.55\\textheight]{../Figures/clustering/9\\lyxdot 8a}\n\\par\\end{center}\n\n\\let\\thefootnote\\relax\\footnotetext{\\tiny{From Bishop's \\emph{Pattern recognition and machine learning}, Figure 9.8.}}\n\n\\end{frame}\n\n\\begin{frame}{EM for GMM}\n\n\\begin{itemize}\n\\item First soft assignment:\n\\end{itemize}\n\\begin{center}\n\\includegraphics[height=0.55\\textheight]{../Figures/clustering/9\\lyxdot 8b}\n\\par\\end{center}\n\n\\let\\thefootnote\\relax\\footnotetext{\\tiny{From Bishop's \\emph{Pattern recognition and machine learning}, Figure 9.8.}}\n\n\\end{frame}\n\n\\begin{frame}{EM for GMM}\n\n\\begin{itemize}\n\\item First soft assignment:\n\\end{itemize}\n\\begin{center}\n\\includegraphics[height=0.55\\textheight]{../Figures/clustering/9\\lyxdot 8c}\n\\par\\end{center}\n\n\\let\\thefootnote\\relax\\footnotetext{\\tiny{From Bishop's \\emph{Pattern recognition and machine learning}, Figure 9.8.}}\n\n\\end{frame}\n\n\\begin{frame}{EM for GMM}\n\n\\begin{itemize}\n\\item After 5 rounds of EM:\n\\end{itemize}\n\\begin{center}\n\\includegraphics[height=0.55\\textheight]{../Figures/clustering/9\\lyxdot 8e}\n\\par\\end{center}\n\n\\let\\thefootnote\\relax\\footnotetext{\\tiny{From Bishop's \\emph{Pattern recognition and machine learning}, Figure 9.8.}}\n\n\\end{frame}\n\n\\begin{frame}{EM for GMM}\n\n\\begin{itemize}\n\\item After 20 rounds of EM:\n\\end{itemize}\n\\begin{center}\n\\includegraphics[height=0.55\\textheight]{../Figures/clustering/9\\lyxdot 8f}\n\\par\\end{center}\n\n\\let\\thefootnote\\relax\\footnotetext{\\tiny{From Bishop's \\emph{Pattern recognition and machine learning}, Figure 9.8.}}\n\n\\end{frame}\n\n\\begin{frame}{Relation to $K$-Means}\n\n\\begin{itemize}\n\\item EM for GMM seems a little like $k$-means.\n\n\n\n\\item In fact, there is a precise correspondence.\n\n\n\n\\item First, fix each cluster covariance matrix to be $\\sigma^{2}I$. \n\\item Then the density for each Gausian only depends on distance to\n  the mean.\n\n\n\\item As we take $\\sigma^{2}\\to0$, the update equations converge to doing\n$k$-means.\n\n\n\n\\item If you do a quick experiment yourself, you'll find\n\n\\begin{itemize}\n\\item Soft assignments converge to hard assignments.\n\\item Has to do with the tail behavior (exponential decay) of\n  Gaussian.\n\\end{itemize}\n\\item Can use $k$-means$++$ to initialize parameters of EM algorithm.\n\\end{itemize}\n\\end{frame}\n\\section{Math Prerequisites for General EM Algorithm}\n\\begin{frame}{Jensen's Inequality}\n  \\begin{itemize}\n  \\item Which is larger: $\\ex[X^2]$ or $\\ex[X]^2$?\n    \\pause\n  \\item Must be $\\ex[X^2]$ since $\\var[X] = \\ex[X^2]-\\ex[X]^2\\geq0$.\n  \\item More general result is true:\n  \\end{itemize}\n  \\begin{theorem}{Jensen's Inequality}\n    If $f:\\RR\\to\\RR$ is convex and $X$ is a random variable then $\\ex[f(X)] \\geq\n    f(\\ex[X])$. If $f$ is strictly convex then we have equality iff\n    $X=\\ex[X]$ with probability 1 (i.e., $X$ is constant).\n  \\end{theorem}  \n\\end{frame}\n\\begin{frame}{Proof of Jensen}\n  \\begin{block}{Exercise}\n    Suppose $X$ can take exactly two value: $x_1$ with probability\n    $\\pi_1$ and $x_2$ with probability $\\pi_2$.  Then prove Jensen's inequality.\n  \\end{block}\n  \\pause\n  \\begin{itemize}\n  \\item Let's compute $\\ex[f(X)]$:\n    $$\\ex[f(X)] = \\pi_1f(x_1) + \\pi_2f(x_2) \\leq f(\\pi_1x_1+\\pi_2x_2)\n    = f(\\ex[X]).$$\n  \\item For the general proof, what do we know is true about all\n    convex functions $f:\\RR\\to\\RR$?\n  \\end{itemize}\n\\end{frame}\n\\begin{frame}{Proof of Jensen}\n  \\begin{enumerate}\n  \\item Let $e = \\ex[X]$. (Remember $e$ is just a number.)\n  \\item Since $f$ has a subgradient at $e$, there is an\n    underestimating line $g(x)=ax+b$ that passes through the point\n    $(e,f(e))$.\n  \\item Then we have\n    \\begin{eqnarray*}\n      \\ex[f(X)]  & \\geq & \\ex[g(X)] \\\\\n      & = & \\ex[aX+b]\\\\\n      & = & a\\ex[X]+b\\\\\n      & = & ae+b\\\\\n      & = & f(e)\\\\\n      & = & f(\\ex[X]).\n    \\end{eqnarray*}\n  \\item If $f$ is strictly convex then $f=g$ at exactly 1 point, so\n    equality iff $X$ is constant.\n  \\end{enumerate}\n\\end{frame}\n\\begin{frame}{KL-Divergence}\n\\begin{itemize}\n\\item Let $p(x)$ and $q(x)$ be probability mass functions (PMFs) on\n  $\\cx$.\n\\item We want to measure how different they are.\n\\item The \\textbf{Kullback-Leibler} or \\textbf{``KL'' Divergence} is\n  define by\n  $$\\kl(p\\|q) = \\sum_{x\\in\\cx} p(x)\\log\\frac{p(x)}{q(x)}.$$\n  (Assumes \\textit{absolute continuity}: $q(x)=0$ implies $p(x)=0$.)\n\\item Can also write\n  $$\\kl(p\\|q) = \\ex_{x\\sim p}\\log\\frac{p(x)}{q(x)}.$$\n\\item Note, the KL-divergence is not symmetric and doesn't satisfy the\n  triangle inequality.\n\\end{itemize}\n\\end{frame}\n\\begin{frame}{Gibbs' Inequality}\n  \\begin{theorem}{Gibbs' Inequality}\n    Let $p(x)$ and $q(x)$ be PMFs on $\\cx$.  Then\n    $$\\kl(p\\|q)\\geq 0,$$\n    with equality iff $p(x)=q(x)$ for all $x\\in\\cx$.\n  \\end{theorem}\n  \\begin{itemize}\n  \\item Since \n    $$\\kl(p\\|q)=\\ex_p\\left[-\\log\\left(\\frac{q(x)}{p(x)}\\right)\\right],$$\n    this is screaming for Jensen's inequality.\n  \\end{itemize}\n\\end{frame}\n\\begin{frame}{Gibbs' Inequality: Proof}\n  \\begin{eqnarray*}\n    \\kl(p\\|q)\n    & = & \\ex_p\\left[-\\log\\left(\\frac{q(x)}{p(x)}\\right)\\right]\\\\\n    & \\geq & -\\log\\left(\\ex_p\\left[\\frac{q(x)}{p(x)}\\right]\\right)\\\\\n    & = & -\\log\\left(\\sum_{x:p(x)>0}p(x)\\frac{q(x)}{p(x)}\\right)\\\\\n    & = & -\\log\\left(\\sum_x q(x)\\right)\\\\\n    & = & -\\log1=0.\n  \\end{eqnarray*}\n  \\begin{itemize}\n  \\item Since $-\\log$ is strictly convex, we have equality iff $q/p$\n    is constant, i.e., $q=p$.\n  \\end{itemize}\n\\end{frame}\n\\end{document}\n", "meta": {"hexsha": "5870359d6688b641ef6a301560fd6d12b529cd94", "size": 24918, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Archive/2017/Lectures/source/brett-stuff/13.lab.mixture-models.tex", "max_stars_repo_name": "LBJ-Wade/mlcourse", "max_stars_repo_head_hexsha": "f5af0db001bf5e2fb153d381c10b35d34a491ebf", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 484, "max_stars_repo_stars_event_min_datetime": "2016-01-29T18:44:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T21:31:34.000Z", "max_issues_repo_path": "Archive/2017/Lectures/source/brett-stuff/13.lab.mixture-models.tex", "max_issues_repo_name": "LBJ-Wade/mlcourse", "max_issues_repo_head_hexsha": "f5af0db001bf5e2fb153d381c10b35d34a491ebf", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 76, "max_issues_repo_issues_event_min_datetime": "2016-12-25T19:14:21.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-20T19:52:59.000Z", "max_forks_repo_path": "Archive/2017/Lectures/source/brett-stuff/13.lab.mixture-models.tex", "max_forks_repo_name": "LBJ-Wade/mlcourse", "max_forks_repo_head_hexsha": "f5af0db001bf5e2fb153d381c10b35d34a491ebf", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 248, "max_forks_repo_forks_event_min_datetime": "2016-01-31T04:11:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T00:45:41.000Z", "avg_line_length": 28.6743383199, "max_line_length": 190, "alphanum_fraction": 0.6823581347, "num_tokens": 8739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3085335064598199}}
{"text": "\\chapter{Implementation}\n\\label{chp:implementation}\n\n\\nomad is a \\verb|C++| implementation of reverse mode automatic\ndifferentiation that uses an \\textit{operator overloading} strategy.\nMore precisely, we introduce a dual number type and then overload\ncommon functions to accept this type.\n\nA key difference of \\nomad to other implementations is the generalization\nto higher-orders.  Most higher-order automatic differentiation\nimplementations leverage the recursive nature of higher-order dual\nnumbers directly, automatically differentiating through a first-order\nimplementation to compute higher-order partial derivatives and\nthe subsequent linear differential operators.  This approach allows for\narbitrary-order automatic differentiation, but only at the cost of inefficient and \nsometimes numerically unstable results.  \\nomad,\non the other hand, explicitly implements second and third-order operators\nwith a focus on performance and numerical stability.\n\nIn this chapter we introduce the architecture behind the \\nomad automatic \ndifferentiation implementation.  We first review the internal representation \nof the expression graph and how it interfaces with function overloads before\ndiscussing the user interface itself.\n\n\\section{Internal Representation of the Expression Graph}\n\\label{sec:exp_graph_rep}\n\nWhile the expression graph represents the entire composite function, each\nnode in the expression graph represents just a single component function.  \nConsequently each node must be responsible for both implementing the \nlocal pushforward and pullback of the corresponding function and storing \nthe dual numbers, input nodes, and any auxiliary storage convenient for \nthe operator implementations, such as partial derivatives.\n \nLike many other automatic differentiation implementations, \\nomad\ntopologically sorts the expression graph into a linear stack of nodes, \nsometimes known as a tape (Figure \\ref{fig:topologicalSort}).  This ordering \npreserves the structure of the expression graph, ensuring that a sweep \nthrough the stack executes a valid forward or reverse sweep through the \nexpression graph.\n\n\\begin{figure}\n\\setlength{\\unitlength}{0.1in} \n\\centering\n\\begin{picture}(50, 20)\n%\n%\\put(0, 0) { \\framebox(50, 20){} }\n%\\put(25, 0) { \\framebox(25, 30){} }\n%\\put(25, 0) { \\framebox(6.25, 30){} }\n%\\put(25, 0) { \\framebox(12.5, 30){} }\n%\\put(25, 0) { \\framebox(18.75, 30){} }\n%\n%\\put(25, 0) { \\framebox(3.125, 30){} }\n%\\put(25, 0) { \\framebox(9.375, 30){} }\n%\\put(25, 0) { \\framebox(15.625, 30){} }\n%\n% Expression Graph\n%\n\\put(6.25, 2.5) { \\circle{4} }\n\\put(6.25, 2.5) { \\makebox(0, 0) {$ x_{1} $} }\n%\n\\put(12.5, 2.5) { \\circle{4} }\n\\put(12.5, 2.5) { \\makebox(0, 0) { $ x_{2} $ } }\n%\n\\put(18.75, 2.5) { \\circle{4} }\n\\put(18.75, 2.5) { \\makebox(0, 0) { $ x_{3} $ } }\n%\n\\put(6.25, 4.5) { \\vector(3, 4){2.75} }\n\\put(12.5, 4.5) { \\vector(-3, 4){2.75} }\n\\put(12.5, 4.5) { \\vector(3, 4){2.75} }\n\\put(18.75, 4.5) { \\vector(-3, 4){2.75} }\n%\n\\put(10, 10) {\\circle{4} } % Tweaked to the right\n\\put(9.375, 10) { \\makebox(0, 0) { $f_{1}$ } }\n%\n\\put(16.25, 10) {\\circle{4} } % Tweaked to the right\n\\put(15.625, 10) { \\makebox(0, 0) { $f_{2}$ } }\n%\n\\put(9.375, 12) { \\vector(3, 4){2.75} }\n\\put(15.625, 12) { \\vector(-3, 4){2.75} }\n%\n\\put(13, 17.5) {\\circle{4} } % Tweaked to the right\n\\put(12.5, 17.5) { \\makebox(0, 0) { $ g $ } }\n%\n% Middle Arrow\n%\n\\put(21.875, 10) { \\thicklines \\vector(1, 0){6.25} }\n%\n% Stack\n%\n\\put(33.5, 4) { \\framebox(8, 2){ $x_{1}$} }\n\\put(33.5, 6) { \\framebox(8, 2){ $x_{2}$ } }\n\\put(33.5, 8) { \\framebox(8, 2){ $x_{3}$ } }\n\\put(33.5, 10) { \\framebox(8, 2){ $f_{1}$ } }\n\\put(33.5, 12) { \\framebox(8, 2){ $f_{2}$ } }\n\\put(33.5, 14) { \\framebox(8, 2){ $g$ } }\n%\n\\end{picture} \n\\caption{\nA topological sort of the expression graph yields a linear stack of nodes, \nsometimes known as a \\textit{tape}, ordered such that a pass through the \nstack yields a valid forward or reverse sweep of the expression graph.\n}\n\\label{fig:topologicalSort} \n\\end{figure}\n\nNodes are implemented with the \\verb|var_node| class which defines\ndefault pushforward and pullback methods that can be specialized\nfor functions with structured Jacobians.  Because the amount of storage for \neach node can vary widely depending on the corresponding function and the \norder of the desired linear differential operator, storage is decoupled from \neach node.  Instead the necessary data are stored in three global stacks, the \ninputs stack, dual numbers stack, and partials stack, with \\verb|var_node| \ncontaining only an address to the relevant data in each \n(Figure \\ref{fig:architecture}), as well as accessor and mutator methods that \nabstract the indirect storage.\n\nStorage for each stack is pre-allocated and expanded only as necessary with \nan arena-based allocation pattern.\n\n\\begin{figure}\n\\setlength{\\unitlength}{0.1in} \n\\centering\n\\begin{picture}(50, 30)\n%\n%\\put(0, 0) { \\framebox(50, 30){} }\n%\n%\\put(0, 0) { \\framebox(12.5, 30){} }\n%\\put(0, 0) { \\framebox(25, 30){} }\n%\\put(0, 0) { \\framebox(37.5, 30){} }\n%\n%\\put(0, 0) { \\framebox(50, 7.5){} }\n%\\put(0, 0) { \\framebox(50, 15){} }\n%\\put(0, 0) { \\framebox(50, 22.5){} }\n%\n% Var Body\n%\n\\put(8.5, 2) { \\makebox(8, 2){Var Node} }\n\\put(8.5, 6) { \\framebox(8, 2){} }\n\\put(8.5, 8) { \\framebox(8, 2){} }\n\\put(8.5, 10) { \\framebox(8, 2){} }\n\\put(8.5, 12) { \\framebox(8, 2){} }\n\\put(8.5, 14) { \\framebox(8, 2){} }\n\\put(8.5, 16) { \\framebox(8, 2){} }\n\\put(8.5, 18) { \\framebox(8, 2){} }\n\\put(8.5, 20) { \\framebox(8, 2){} }\n\\put(8.5, 22) { \\framebox(8, 2){} }\n\\put(8.5, 24) { \\framebox(8, 2){} }\n%\n% Inputs\n%\n\\put(39, 24) { \\makebox(8, 2){Inputs} }\n\\put(25, 22) { \\framebox(2, 6){} }\n\\put(27, 22) { \\framebox(2, 6){} }\n\\put(29, 22) { \\framebox(2, 6){} }\n\\put(31, 22) { \\framebox(2, 6){} }\n\\put(33, 22) { \\framebox(2, 6){} }\n\\put(35, 22) { \\framebox(2, 6){} }\n\\put(37, 22) { \\framebox(2, 6){} }\n%\n% Dual Numbers\n%\n\\put(39, 15) { \\makebox(8, 2){Dual} }\n\\put(39, 13) { \\makebox(8, 2){Numbers} }\n\\put(25, 12) { \\framebox(2, 6){} }\n\\put(27, 12) { \\framebox(2, 6){} }\n\\put(29, 12) { \\framebox(2, 6){} }\n\\put(31, 12) { \\framebox(2, 6){} }\n\\put(33, 12) { \\framebox(2, 6){} }\n\\put(35, 12) { \\framebox(2, 6){} }\n\\put(37, 12) { \\framebox(2, 6){} }\n%\n% Partials\n%\n\\put(39, 4) { \\makebox(8, 2){Partials} }\n\\put(25, 2) { \\framebox(2, 6){} }\n\\put(27, 2) { \\framebox(2, 6){} }\n\\put(29, 2) { \\framebox(2, 6){} }\n\\put(31, 2) { \\framebox(2, 6){} }\n\\put(33, 2) { \\framebox(2, 6){} }\n\\put(35, 2) { \\framebox(2, 6){} }\n\\put(37, 2) { \\framebox(2, 6){} }\n%\n% Arrows\n%\n\\thicklines\n\\put(32, 22) { \\vector(-1, -1){4} }\n\\put(34, 22) { \\vector(0, -1){4} }\n%\n\\put(16.5, 15) { \\vector(4, 3){15.5} }\n\\put(16.5, 15) { \\vector(1, 0){19.5} }\n\\put(16.5, 15) { \\vector(2, -1){17.5} }\n%\n\\end{picture} \n\\caption{ \nUpon a topological sort (Figure \\ref{fig:topologicalSort}), the expression graph \nis represented by a stack of \\texttt{var\\_node} objects.  The input nodes, \ndual numbers, and partial derivatives are stored in external stacks, with each \n\\texttt{var\\_node} storing only addresses to each.  Note that the inputs stack \naddress not the \\texttt{var\\_node} objects directly, but rather only the dual numbers \nof those nodes needed for implementing the pushforward and pullback operators.\n}\n\\label{fig:architecture} \n\\end{figure}\n\n\\subsubsection{The Inputs Stack}\n\nThe inputs stack represents the edges in the expression graph\nneeded for directing the forward and reverse sweeps.  Because\nthe pushforward and pullback operators need to read and write only \nthe dual numbers at each node, edges index the dual numbers of any\ndependencies directly (Figure \\ref{fig:architecture}) and avoid the overhead\nthat would be acquired for indirect access through the \\verb|var_node|\nobjects.\n\n\\subsubsection{Dual Number Stack}\n\nThe dual number stack stores the $2^{k}$ components of the $k$th-order\ndual numbers at each node.  For example, a first-order expression graph\nwill need only two elements for each node while a third-order expression \ngraph will need eight (Figure \\ref{fig:dualNumberStorage}).\n\n\\begin{figure}\n\\setlength{\\unitlength}{0.1in} \n\\centering\n\\begin{picture}(50, 20)\n%\n%\\put(0, 0) { \\framebox(50, 20){} }\n%\n% First-Order\n%\n\\put(0, 15) { \\makebox(8, 2){First-} }\n\\put(0, 13) { \\makebox(8, 2){Order} }\n\\put(9, 17) { \\makebox(2, 2){ $\\ldots$ } }\n\\put(9, 11) { \\makebox(2, 2){ $\\ldots$ } }\n\\put(11, 12) { \\framebox(4, 6){ $x $ } }\n\\put(15, 12) { \\framebox(4, 6){ $ \\delta x $ } }\n\\put(19, 17) { \\makebox(2, 2){ $\\ldots$ } }\n\\put(19, 11) { \\makebox(2, 2){ $\\ldots$ } }\n%\n{ \\thicklines \\put(13, 20) { \\vector(0, -1){2} } }\n%\n% Second-Order\n%\n\\put(0, 5) { \\makebox(8, 2){Third-} }\n\\put(0, 3) { \\makebox(8, 2){Order} }\n\\put(9, 7) { \\makebox(2, 2){ $\\ldots$ } }\n\\put(9, 1) { \\makebox(2, 2){ $\\ldots$ } }\n\\put(11, 2) { \\framebox(4, 6){ $s$ } }\n\\put(15, 2) { \\framebox(4, 6){ $\\delta s$ } }\n\\put(19, 2) { \\framebox(4, 6){ $\\delta t$ } }\n\\put(23, 2) { \\framebox(4, 6){ $\\delta^{2} t$ } }\n\\put(27, 2) { \\framebox(4, 6){ $\\delta u$ } }\n\\put(31, 2) { \\framebox(4, 6){ $\\delta^{2} u$ } }\n\\put(35, 2) { \\framebox(4, 6){ $\\delta^{2} v$ } }\n\\put(39, 2) { \\framebox(4, 6){ $\\delta^{3} v$ } }\n\\put(43, 7) { \\makebox(2, 2){ $\\ldots$ } }\n\\put(43, 1) { \\makebox(2, 2){ $\\ldots$ } }\n%\n{ \\thicklines \\put(13, 10) { \\vector(0, -1){2} } }\n%\n\\end{picture} \n\\caption{\nThe dual number stack is able to accommodate storage of dual numbers \nof any order without reallocating memory.  For example, first-order dual \nnumbers require only two elements while third-order dual numbers require\neight elements.\n}\n\\label{fig:dualNumberStorage} \n\\end{figure}\n\n\\subsubsection{Partials Stack}\n\nA common approach in many automatic differentiation implementations\nis to compute partial derivatives online as necessary and avoid storing them\nin the expression graph.  This strategy is sound for first-order reverse\nmode calculations where the partials are used only once, but higher-order\ncalculations require multiple sweeps that reuse the partials.  Recomputing\nthe partials for each sweep then becomes a significant computational burden.\n\nWith a focus on implementing efficient higher-order methods, \\nomad \nexplicitly stores partial derivatives in a dedicated partials stack.  When \nconstructing an $k$th-order expression graph only the $k$th-order partial \nderivatives and lower are stored, and only if the partial derivatives are \nnon-zero.  For example, a second-order expression graph will calculate \nand store only the first and second-order partial derivatives.\n\nTo avoid redundant calculations and storage, \\nomad stores only the \nunique higher-order values.  In a second-order calculation a node \nrepresenting the component function \n$f: \\mathbb{R}^{N} \\rightarrow \\mathbb{R}$ will store\n%\n\\begin{equation*}\n\\frac{ \\partial^{2} f }{ \\partial x_{i} \\partial x_{j} }, \\, i \\in 1, \\ldots, N, j \\in 1, \\ldots i,\n\\end{equation*}\n%\nwhile a third-order calculation will store\n%\n\\begin{equation*}\n\\frac{ \\partial^{3} f }{ \\partial x_{i} \\partial x_{j} \\partial x_{k} }, \\, \ni \\in 1, \\ldots, N, j \\in 1, \\ldots i, k \\in 1, \\ldots, j.\n\\end{equation*}\n%\nFor example, when executing a third-order calculation the node representing\na binary function, $f : \\mathbb{R}^{2} \\rightarrow \\mathbb{R}$, utilizes the\ncompact storage demonstrated in Figure \\ref{fig:partialsStorage}.\n\n\\begin{figure}\n\\setlength{\\unitlength}{0.1in} \n\\centering\n\\begin{picture}(50, 10)\n%\n%\\put(0, 0) { \\framebox(50, 10){} }\n%\n% Second-Order\n%\n\\put(5, 7) { \\makebox(2, 2){ $\\ldots$ } }\n\\put(5, 1) { \\makebox(2, 2){ $\\ldots$ } }\n\\put(7, 2) { \\framebox(4, 6){ $ \\frac{ \\partial f }{ \\partial x} $ } }\n\\put(11, 2) { \\framebox(4, 6){ $ \\frac{ \\partial f }{ \\partial y} $ } }\n\\put(15, 2) { \\framebox(4, 6){ $ \\frac{ \\partial^{2} f }{ \\partial x^{2}} $ } }\n\\put(19, 2) { \\framebox(4, 6){ $ \\frac{ \\partial^{2} f }{ \\partial x \\partial y} $ } }\n\\put(23, 2) { \\framebox(4, 6){ $ \\frac{ \\partial^{2} f }{ \\partial y^{2}} $ } }\n\\put(27, 2) { \\framebox(4, 6){ $ \\frac{ \\partial^{3} f }{ \\partial x^{3}} $ } }\n\\put(31, 2) { \\framebox(4, 6){ $ \\frac{ \\partial^{3} f }{ \\partial x^{2} \\partial y} $ } }\n\\put(35, 2) { \\framebox(4, 6){ $ \\frac{ \\partial^{3} f }{ \\partial x \\partial y^{3}} $ } }\n\\put(39, 2) { \\framebox(4, 6){ $ \\frac{ \\partial^{3} f }{ \\partial y^{3}} $ } }\n\\put(43, 7) { \\makebox(2, 2){ $\\ldots$ } }\n\\put(43, 1) { \\makebox(2, 2){ $\\ldots$ } }\n%\n{ \\thicklines \\put(9, 10) { \\vector(0, -1){2} } }\n%\n\\end{picture} \n\\caption{\nOnly unique partial derivatives are stored in the partials stack,\nas demonstrated here for node representing a binary function,\n$f: \\mathbb{R}^{2} \\rightarrow \\mathbb{R}$, in a third-order \nexpression graph that requires first, second, and third-order\npartial derivatives.\n}\n\\label{fig:partialsStorage} \n\\end{figure}\n\nIn general a function with $N$ inputs and non-vanishing derivatives at\nall orders will require $\\binom{N + M}{M}$ elements to store the unique\n$M$th-order partial derivatives.\n\n\\section{Extending Functions to Accept Dual Numbers}\n\nIn order to implement automatic differentiation calculations, each dual-number \nvalued-function is responsible for not only computing the function\nvalue but also expanding the expression graph with the addition of\na node with the desired pushforward and pullback methods and\naddresses to the top of the inputs, dual numbers, and partials stacks.\nThe evaluation of a composite dual number-valued function will then\nbuild the complete expression graph primed for the application of\nlinear differential operators.\n\nDual numbers in \\nomad are exposed to the user by the \\verb|var|\nclass with \\verb|var|-valued functions responsible for the management\nof the expression graph.  In this section we present the details of\nthe \\verb|var| class and the implementation of \\verb|var|-valued functions.\n\n\\subsection{The var Class}\n\nThe \\verb|var| class itself is only a lightweight wrapper for an underlying \n\\verb|var_node| in the expression graph, storing an address to the \ncorresponding node with a variety of member functions that expose the \nnode's data.  Most importantly, \\verb|var| is templated to allow for the \ncompile-time configuration of the expression graph,\n%\n\\begin{verbatim}\ntemplate <short AutodiffOrder, bool StrictSmoothness, bool ValidateIO>\nclass var { ...\n\\end{verbatim}\n%\n\\nomad also defines a variety of type definitions for the most commonly\nused template configurations (Table \\ref{tab:typedefs}).\n\n\\begin{table*}[t!]\n\t\\centering\n\t\\renewcommand{\\arraystretch}{2}\n\t\\begin{tabular}{cccc}\n\t\\rowcolor[gray]{0.9} Type Definition & \\verb|AutodiffOrder|\n\t& \\verb|StrictSmoothness| & \\verb|ValidateIO| \\\\\n\t\\verb|var1| & \\verb|1| & \\verb|true| & \\verb|false| \\\\\n\t\\rowcolor[gray]{0.9} \\verb|var2| & \\verb|2| & \\verb|true| & \\verb|false| \\\\\n\t\\verb|var3| & \\verb|3| & \\verb|true| & \\verb|false| \\\\\n\t\\rowcolor[gray]{0.9} \\verb|var1_debug| & \\verb|1| & \\verb|true| & \\verb|true| \\\\\n\t\\verb|var2_debug| & \\verb|2| & \\verb|true| & \\verb|true| \\\\\n\t\\rowcolor[gray]{0.9} \\verb|var3_debug| & \\verb|3| & \\verb|true| & \\verb|true| \\\\\n\t\\verb|var1_wild| & \\verb|1| & \\verb|false| & \\verb|false| \\\\\n\t\\rowcolor[gray]{0.9} \\verb|var2_wild| & \\verb|2| & \\verb|false| & \\verb|false| \\\\\n\t\\verb|var3_wild| & \\verb|3| & \\verb|false| & \\verb|false| \\\\\n\t\\end{tabular}\n\t\\caption{The \\texttt{nomad} namespace includes helpful type definitions for \n\tthe most common \\texttt{var} configurations.}\n\t\\label{tab:typedefs}\n\\end{table*}\n\n\\subsubsection{AutodiffOrder}\n\nThe template parameter \\verb|AutodiffOrder| defines the maximum order\nlinear differential operator that the corresponding expression graph will\nadmit.  Attempting to apply a second-order linear differential operator\nto a graph built from \\verb|var|s with \\verb|AutodiffOrder = 1|, for example,\nwill induce a compile-time error.\n\nNote that lower-order graphs require the computation and storage of\nfewer dual numbers and partial derivatives, not to mention faster pushforward\nand pullback implementations.  Consequently, although a higher-order\ngraph will admit lower-order operators, it is much more efficient to match\nthe order of the expression graph, via the choice of \\verb|AutodiffOrder|,\nto the linear differential operators of interest.\n\n\\subsubsection{StrictSmoothness}\n\n\\verb|StrictSmoothness| defines the smoothness requirements of \ncomponent functions.\n\nFormally, automatic differentiation requires only that each component\nfunction have well-behaved derivatives defined in some neighborhood\ncontaining the point at which the function is being evaluated.  For\nexample, a linear differential operator applied to the absolute value\nfunction is well defined everywhere except at the origin.  Many\nalgorithms that use these operators, however, actually require that\nthe derivatives be well-defined \\textit{everywhere} because even \nfunctions with only point discontinuities in their derivatives will\nmanifest undesired pathologies.\n\nWith these algorithms in mind, when \\verb|StrictSmoothness = true| \n\\nomad will disable functions and operators that are not everywhere \nsmooth, as well as those that admit comparisons that may introduce cusps.\n\n\\subsubsection{ValidateIO}\n\n\\verb|ValidateIO| enables strict validation of the inputs and outputs\nto each component function.\n\nIdentifying the source of potential floating-point pathologies like\nunderflow, overflow and \\verb|NaN| in a large, composite function\nis often a challenging debugging task.  When \\verb|ValidateIO = true|,\n\\nomad assists users by checking all input values, output values,\nand output partial derivatives for \\verb|NaN| and throws an\nexception identifying the responsible component function if any\nare found.  Domain validation will also be done if implemented in\nthe function.  These checks, however, are a nontrivial computational\nburden and should be disabled for high-performance applications.\n\n\\subsection{var-valued Functions}\n\nExtending a function to take \\verb|var| arguments requires not just propagating the\nvalue of the function but also creating a new node in the expression\ngraph.  In this section we review the steps necessary for implementing\na \\verb|var|-valued function and present some specific examples.\n\n\\subsubsection{Input Validation}\n\nFirstly, a \\verb|var|-valued function has to validate its inputs if\n\\verb|ValidateIO| is \\verb|true|.  \\nomad provides helper functions\nthat validate double values and throws \\nomad-specific exceptions\nif \\verb|NaN|s are encountered,\n%\n\\begin{verbatim}\ninline void validate_input(double val, std::string f_name)\n\\end{verbatim}\n%\nHere \\verb|f_name| is the name of the function being implemented\nand is used to trace the exception to the origin of the violation.\nDomain constraints may also be validated here with helper functions\nsuch as\n%\n\\begin{verbatim}\ninline void validate_lower_bound(double val, double lower, std::string f_name)\n\\end{verbatim}\n\n\\subsubsection{Expression Graph Node Creation}\n\nWith the inputs validated we can now append a new node to the\nexpression graph with the \\verb|create_node| function.  This function\nis templated to accept the type of node being used by the function\nand will require the number of inputs to the function unless the\nspecific \\verb|var_node| implementation does not require it.\n\nFor example, if the function is utilizing the default \\verb|var_node|\nimplementation then the call would be\n%\n\\begin{verbatim}\ncreate_node<var_node<AutodiffOrder, PartialsOrder>>(n_inputs);\n\\end{verbatim}\n%\nOn the other hand, a function utilizing a \\verb|var_node| specialization\nwith a predefined number of inputs would not need to specify an\nargument,\n%\n\\begin{verbatim}\ncreate_node<binary_var_node<AutodiffOrder, PartialsOrder>>();\n\\end{verbatim}\n\n\\subsubsection{Pushing Inputs}\n\nOnce the node representing the component function has been created\nwe can now being to push the necessary data onto the external stacks.\nFirst are the addresses of the inputs to the function,\n%\n\\begin{verbatim}\ninline void push_inputs(nomad_idx_t input)\n\\end{verbatim}\n%\nwhich are readily accessed from the input \\verb|var| arguments.\n\n\\subsubsection{Pushing Dual Numbers}\n\nNext are the dual numbers.  The function\n%\n\\begin{verbatim}\ntemplate<short AutodiffOrder, bool ValidateIO>\ninline void push_dual_numbers(double val)\n\\end{verbatim}\n%\npushes $2^{\\mathrm{AutodiffOrder}}$ components onto the stack, with\nthe first component set to the value of the function, \\verb|val|, and the\nrest set to zero.\n\nWhen \\verb|ValidateIO = true| the function \\verb|push_dual_numbers|\nwill also check the output \\verb|val| for a \\verb|NaN| and throw an\nexception if necessary.  Consequently the call to \\verb|push_dual_numbers|\nmust be wrapped in a \\verb|try/catch| block, preferable one that throws\na new exception identifying the current function, for example\n%\n\\begin{verbatim}\ntry {\n  push_dual_numbers<AutodiffOrder, ValidateIO>(binary_function(x, y));\n} catch(nomad_error) {\n  throw nomad_output_value_error(\"binary_function\");\n}\n\\end{verbatim}\n\n\\subsubsection{Pushing Partials}\n\nFinally we can compute the partial derivatives and push them onto the\npartials stack with\n%\n\\begin{verbatim}\ntemplate<bool ValidateIO>\ninline void push_partials(double partial)\n\\end{verbatim}\n%\nAs with \\verb|push_dual_numbers|, \\verb|push_partials| will optionally\nvalidate the values of the partial derivatives and must be wrapped in\na \\verb|try/catch| block,\n%\n\\begin{verbatim}\ntry {\n  if (AutodiffOrder >= 1) {\n    push_partials<ValidateIO>(df_dx);\n    push_partials<ValidateIO>(df_dy);\n  }\n  ...Push higher-order partial derivatives...\n} catch(nomad_error) {\n  throw nomad_output_partial_error(\"binary_function\");\n}\n\\end{verbatim}\n\nBecause partial derivatives only up to \\verb|AutodiffOrder| need to be\ncomputed and stored, efficient implementations of a \\verb|var|-valued\nfunction should evaluate partial derivatives only conditionally on\n\\verb|AutodiffOrder|.\n\n\\subsubsection{Returning a New Var}\n\nFinally we return a new \\verb|var| that wraps the freshly-created node.\n%\n\\begin{verbatim}\nreturn var<AutodiffOrder, StrictSmoothness, ValidateIO>(next_node_idx_ - 1);\n\\end{verbatim}\n%\n\\verb|next_node_idx_| addresses the top of the \\verb|var_node| stack, hence\n\\verb|next_node_idx_ - 1| addresses the last node pushed to the stack.\n\n\\subsubsection{Example Implemention of a Smooth Function}\n\nThe logic of a \\verb|var|-valued function implementation is more clear\nwhen each step is presented together.  Here is an example implementation\nof a smooth, binary function using the default \\verb|var_node| implementation.\n\n\\begin{verbatim}\ntemplate <short AutodiffOrder, bool StrictSmoothness, bool ValidateIO>\ninline var<AutodiffOrder, StrictSmoothness, ValidateIO>\n  binary_function(const var<AutodiffOrder, StrictSmoothness, ValidateIO>& v1,\n                  const var<AutodiffOrder, StrictSmoothness, ValidateIO>& v2) {\n    \n  // Validate input values if ValidateIO is true\n  if (ValidateIO) {\n    validate_input(v1.first_val(), \"binary_function\");\n    validate_input(v2.first_val(), \"binary_function\");\n  }\n      \n  // Create a var_node on the top of the stack\n  const short partials_order = 3;\n  const unsigned int n_inputs = 2;\n    \n  create_node<var_node<AutodiffOrder, partials_order>>(n_inputs);\n\n  // Push dependencies to top of the inputs stack\n  push_inputs(v1.dual_numbers());\n  push_inputs(v2.dual_numbers());\n\n  // Push dual numbers to the the top of the dual numbers stack\n  double x = v1.first_val();\n  double y = v2.first_val();\n    \n  try {\n    push_dual_numbers<AutodiffOrder, ValidateIO>(binary_function(x, y));\n  } catch(nomad_error) {\n    throw nomad_output_value_error(\"binary_function\");\n  }\n    \n  // Push partial derivatives to the top of the partials stack\n  try {\n    if (AutodiffOrder >= 1) {\n      ...Compute df_dx and df_dy...\n      push_partials<ValidateIO>(df_dx);\n      push_partials<ValidateIO>(df_dy);\n    }\n    if (AutodiffOrder >= 2) {\n      ...Compute df2_dx2, df2_dxy, and df2_dy2...\n      push_partials<ValidateIO>(df2_dx2);\n      push_partials<ValidateIO>(df2_dxdy);\n      push_partials<ValidateIO>(df2_dy2);\n    }\n    if (AutodiffOrder >= 3) {\n      ...Compute df3_dx3, df3_dx2dy, df3_dxdy2, and df3_dy3...\n      push_partials<ValidateIO>(df3_dx3);\n      push_partials<ValidateIO>(df3_dx2dy);\n      push_partials<ValidateIO>(df3_dxdy2);\n      push_partials<ValidateIO>(df3_dy3);\n    }\n  } catch(nomad_error) {\n    throw nomad_output_partial_error(\"binary_function\");\n  }\n\n  // Return a new var that wraps the newly created node\n  return var<AutodiffOrder, StrictSmoothness, ValidateIO>(next_node_idx_ - 1);\n    \n}\n\\end{verbatim}\n%\nNote that expensive calculations, such as when validating inputs and computing\nand storing partial derivatives, are conditioned on template parameters wherever \npossible to avoid unnecessary computation.  Because these template parameters \nare known at compile-time these checks incur no run-time penalties.\n\nWhen the partial derivatives of a function are structured then we can achieve\nmuch higher performance by specializing the underlying \\verb|var_node|.\nFor example, the only non-zero partial derivatives of the addition operator\nare at first-order, and they are all equal to $1$.  Consequently we can speed\nup the automatic differentiation computations by specializing \\verb|var_node|\nto avoid unnecessary multiplications by $1$.\n\nThis is done in the \\verb|binary_sum_var_node| and the implementation of\nthe addition operator then becomes\n%\n\\begin{verbatim}\ntemplate <short AutodiffOrder, bool StrictSmoothness, bool ValidateIO>\ninline var<AutodiffOrder, StrictSmoothness, ValidateIO>\n  operator+(const var<AutodiffOrder, StrictSmoothness, ValidateIO>& v1,\n            const var<AutodiffOrder, StrictSmoothness, ValidateIO>& v2) {\n\n  if (ValidateIO) {\n    validate_input(v1.first_val(), \"operator+\");\n    validate_input(v2.first_val(), \"operator+\");\n  }\n      \n  // Create a specialized var_node on the stack\n  create_node<binary_sum_var_node<AutodiffOrder>>();\n    \n  push_inputs(v1.dual_numbers());\n  push_inputs(v2.dual_numbers());\n    \n  try {\n    push_dual_numbers<AutodiffOrder, ValidateIO>(v1.first_val() + v2.first_val());\n  } catch(nomad_error) {\n    throw nomad_output_value_error(\"operator+\");\n  }\n    \n  // The binary_sum_var_node pushforward and pullback implementations\n  // use hardcoded partial derivatives and don't require partial derivatives to \n  // be pushed onto the partials stack\n    \n  return var<AutodiffOrder, StrictSmoothness, ValidateIO>(next_node_idx_ - 1);\n    \n}\n\\end{verbatim}\n\n\\subsubsection{Example Implemention of a Non-Smooth Function}\n\nNon-smooth functions are implemented almost exactly the same as smooth functions.\nThe only difference is in the function signature which uses the \\verb|enable_if|\ntemplate metaprogram to disable the function unless \\verb|StrictSmoothness = 1|.\n\nFor example, the absolute value function is implemented as\n%\n\\begin{verbatim}\ntemplate <short AutodiffOrder, bool StrictSmoothness, bool ValidateIO>\ninline typename \n  std::enable_if<!StrictSmoothness, \n                 var<AutodiffOrder, StrictSmoothness, ValidateIO> >::type\n  fabs(const var<AutodiffOrder, StrictSmoothness, ValidateIO>& input) {\n    \n  if (ValidateIO) validate_input(input.first_val(), \"fabs\");\n      \n  const short partials_order = 1;\n  const unsigned int n_inputs = 1;\n    \n  create_node<unary_var_node<AutodiffOrder, partials_order>>(n_inputs);\n\n  double x = input.first_val();\n    \n  try {\n    push_dual_numbers<AutodiffOrder, ValidateIO>(fabs(x));\n  } catch(nomad_error) {\n    throw nomad_output_value_error(\"fabs\");\n  }\n      \n  push_inputs(input.dual_numbers());\n    \n  try {\n    if (AutodiffOrder >= 1) {\n      if (x < 0)\n        push_partials<ValidateIO>(-1);\n      else\n        push_partials<ValidateIO>(1);\n    }\n  } catch(nomad_error) {\n    throw nomad_output_partial_error(\"fabs\");\n  }\n\n  return var<AutodiffOrder, StrictSmoothness, ValidateIO>(next_node_idx_ - 1);\n    \n}\n\\end{verbatim}\n\n\\section{The \\nomad User Interface}\n\\label{sec:user_interface}\n\nIn \\nomad, linear differential operators are implemented as functionals acting\non \\verb|var|-valued functors.\n\nSpecifically, functors are classes deriving from \\verb|base_functor|\n%\n\\begin{verbatim}\ntemplate<class T>\nclass base_functor {\npublic:\n  virtual T operator()(const Eigen::VectorXd& x) const;\n  typedef T var_type;\n};\n\\end{verbatim}\n%\nthat implement a \\verb|var|-valued \\verb|operator()| taking an\n\\verb|Eigen::VectorXd&| of input values.  For example, at\nfirst-order the composite function\n%\n\\begin{equation*}\nf \\! \\left( x, y, z \\right) = \\cos \\! \\left( e^{x} + e^{y} \\right) / z\n\\end{equation*}\n%\nwould be defined as\n%\n\\begin{verbatim}\nclass example_functor: public base_functor<var1> {\n  var1 operator()(const Eigen::VectorXd& x) const {\n    var1 v1 = x[0];\n    var1 v2 = x[1];\n    var1 v3 = x[2];\n    return cos( exp(v1) + exp(v2) ) / v3;  \n  }\n};\n\\end{verbatim}\n\nThe functionals implementing linear differential operators then\ntake a functor instance as an argument, first calling \\verb|operator()|\nto build the expression graph and then the various sweeps\nnecessary to compute the differential operator itself.  For example,\nthe gradient is defined with the signature\n%\n\\begin{verbatim}\ntemplate <typename F>\nvoid gradient(const F& f,\n              const Eigen::VectorXd& x,\n              Eigen::VectorXd& g)\n\\end{verbatim}\n%\nConsequently computing a gradient is straightforward,\n%\n\\begin{verbatim}\nint n = 100;\nEigen::VectorXd x = Eigen::VectorXd::Ones(n);\n  \ndouble f;\nEigen::VectorXd grad(x.size());\n  \nexample_functor example;\ngradient(example, x, f, grad);\n\nstd::cout << grad.transpose() << std::endl;\n\\end{verbatim}\n\nFor the complete list of \\verb|var|-valued functions and linear differential\noperators implemented in \\nomad please consult Chapter \\ref{chap:reference_guide}.\n", "meta": {"hexsha": "111dbf986a02ff87daec0e217c3d497e3d65e21f", "size": 29662, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "manual/2-implementation.tex", "max_stars_repo_name": "stan-dev/nomad", "max_stars_repo_head_hexsha": "a21149ef9f4d53a198e6fdb06cfd0363d3df69e7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2015-12-11T20:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T18:59:58.000Z", "max_issues_repo_path": "manual/2-implementation.tex", "max_issues_repo_name": "stan-dev/nomad", "max_issues_repo_head_hexsha": "a21149ef9f4d53a198e6fdb06cfd0363d3df69e7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2015-12-15T08:12:01.000Z", "max_issues_repo_issues_event_max_datetime": "2016-07-17T01:36:56.000Z", "max_forks_repo_path": "manual/2-implementation.tex", "max_forks_repo_name": "stan-dev/nomad", "max_forks_repo_head_hexsha": "a21149ef9f4d53a198e6fdb06cfd0363d3df69e7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-10-13T17:40:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-08T19:17:51.000Z", "avg_line_length": 36.5295566502, "max_line_length": 99, "alphanum_fraction": 0.7162699751, "num_tokens": 8961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.30853350645981986}}
{"text": "\\section{Type inference}\n\nWe now formulate type inference for the \\lang language. Type inference is\nbased on the HM(X) framework~\\citep{DBLP:journals/tapos/OderskySW99} which\npresents how to implement Hindley-Milner type inference in a language\nwith qualified types. We first present various preliminaries definitions,\nwe then show our extension of HM(X) that support a kind system and affine\ntypes.\n\n\\subsection{Preliminaries}\n\n\\subsubsection{Usage maps}\n\nIn order to determine if a variable is used in an affine manner, we must track\nits uses and the associated kinds. For instance, in the expression\n$(x,x)$, $x$ is used twice. If $x$ is of type $\\tau$, which is of kind $k$,\nwe must add the constraint $\\Cleq{k}{\\kun}$. In order to record uses and kinds,\nour type inference relation will return a ``usage map'', noted $\\Sv$,\nwhich associates each variable to a list of kinds corresponding to each use site\nof the variable.\nWe note $\\Sone{x}{k_1,\\dots,k_n}$ the singleton usage map.\nCommon operations on usage maps are defined in \\cref{op:usgmap}. We define\nregular set operations such as union\n($\\Sv\\cup\\Sv'$) and intersection ($\\Sv\\cap\\Sv'$), along\nwith constraint creation $\\Cleq{\\Sv}{k_0}$ which indicates that all the kinds\npresents in the usage map $\\Sv$ are constrained by the kind $k_0$.\nThese operations corresponds roughly to the various parts of the join\noperator on sets $\\esplit{}{}$.\n\n\\begin{figure}[tp]\\centering\n\\begin{mathpar}\n  % \\Sv\\cap\\Sv'\n  % &= \\left\\{ x \\to l,l'\n  %   \\mid \\Sone{x}{l}\\in\\Sv \\text{ and } \\Sone{x}{l'}\\in\\Sv' \\right\\} \\\\\n  % \\infer\n  % { \\forall x \\in \\Dom{\\Sv_1}\\cup\\Dom{\\Sv_2}.\\quad\n  %   \\bsplit{C_x}{\\Sv(x)}{\\Sv_1(x)}{\\Sv_2(x)}\n  % } \n  % { \\bsplit{(\\bigwedge C_x)}{\\Sv}{\\Sv_1}{\\Sv_2} }\n  % &= \\Sv\\cap\\Sv' \\sqcup\n  %   (\\Sv\\Sdel{x' \\mid x'\\in\\Sv'}) \\sqcup\n  %   (\\Sv'\\Sdel{x \\mid x\\in\\Sv})\n  %   &\\text{where $\\sqcup$ is the disjoint union}\\\\\n  % \\and\n  \\inferrule{}\n  { \\Cleq{\\Sv}{k}\n    = \\bigwedge_{\\Sone{x}{\\schm}\\in\\Sv} \\Cleq{\\schm}{k}\n  }\n  \\and\n  % \\inferrule\n  % { \\forall \\bshadow{x} \\in \\Sv, b'\\in\\Sv'.\\quad\n  %   \\tregion{C_x}{y}{\\bshadow{x}}{b'} }\n  % { \\bregion{(\\bigwedge C_x)}{y}{\\Sv}{\\Sv'} }\n  % \\and\n  % \\inferrule\n  % { \\text{if } \\operatorname{lenght}(\\Sv(x))  = \\Cempty{} \\wedge  }\n  { \\Weaken_{(x,k)}(\\Sv) =\n    \\begin{dcases}\n      \\Ctrue& \\operatorname{length}(\\Sv(x)) = 1\\\\\n      {k}\\lk\\kaff_\\infty& \\text{ otherwise}\\\\\n    \\end{dcases}\n\n  }\n\\end{mathpar}\n\\caption{Operation on usage maps $\\Sv$}\n\\label{op:usgmap}\n\\end{figure}\n\n\\subsection{Kind inference}\n\nWe note $\\inferK{(C,\\unif)}{\\bf{\\E}}{\\bf{\\tau}}{k}$ when type $\\tau$ has kind $k$\nin environment $\\E$ under constraints $C$ and unifier $\\unif$. From an\nalgorithmic point of view, $\\E$ and $\\tau$ are the input parameters of\nour inference procedure.\nWe present the kind inference algorithm as a set of syntax-directed rules in\n\\cref{rules:kinding}.\nSince higher-kinded types are not supported, the type application\nrule and the type constructor rule are merged in {\\sc KApp}.\nAdditionally, type variables must be of a simple kind in rule {\\sc KVar}.\nNote that in the case of a type constructor with no argument, the {\\sc KApp}\nrule degenerates to a simpler form which is similar to the {\\sc KVar} rule.\nKind schemes are instantiated in the {\\sc KApp} and {\\sc KVar} rules by creating\nfresh kind variables and the associated substitution.\n\n\\begin{figure}[ht]\n  \\centering\n  \\input{infer/kinds}\n  \\caption{Kind inference algorithm -- $\\inferK{(C,\\unif)}{\\E}{\\tau}{(\\Multi{k}) k}$}\n  \\label{rules:kinding}\n\\end{figure}\n\n\n\n\\subsection{Type inference}\n\nWe reformulate the HM(X) type inference in the context of our affine type\nsystem. The main difference compared to HM(X) are noted in \\addlin{blue}.\nWe note $\\inferW{\\addlin{\\Sigma}}{(C,\\unif)}{\\bf{\\E}}{\\bf{e}}{\\tau}$ when\n$e$\\ as type $\\tau$ in $\\E$ under the constraints $C$ and unifier $\\unif$.\n$\\Sigma$ is a map which associates free variables in $e$ to\ntheir kinds.\nAs before, $\\E$ and $e$ are the input parameters of the inference\nalgorithm. The syntax-directed rules are shown in \\cref{rules:typing}.\n\n\\begin{figure*}[htp]\n  \\input{infer/typing}\n  \\caption{Type inference algorithm -- $\\inferW{\\Sigma}{(C,\\psi)}{\\bf{\\E}}{\\bf{e}}{\\tau}$ }\n  \\label{rules:typing}\n\\end{figure*}\n\n\\subsection{Normal forms and generalization}\n\\label{sec:normalize}\n\n\nWe now place ourselves in a more general context where kinds are either variables\nor constants belonging to a total bounded lattice $(\\mathcal L, \\lk_\\Lat)$ ie.,\na lattice which admits a total order and upper and lower bounds ($l^\\top$ and $l^\\bot$).\nWe note lattice elements $l$ and $\\glb_i l_i$ (resp. $\\lub_i l_i$)\nthe greatest lower bound (resp. least upper bound) in $\\mathcal L$.\n%\nLet $\\CL$ the set of constraints in this lattice. We consider the\nfollowing base entailment rules in this system:\n\\begin{center}\n  \\begin{mathpar}\n    \\inferrule{l \\lk_\\Lat l'}{\\entail{}{\\Cleq{l}{l'}}}\n    \\and\n    \\inferrule{}{\\entail{}{\\Cleq{k}{l^\\top}}}\n    \\and\n    \\inferrule{}{\\entail{}{\\Cleq{l^\\bot}{k}}}\n  \\end{mathpar}\n\\end{center}\n\n\n\nThe normalization procedure is noted $\\normalize{C_0}{\\unif_0}$ where\n$C_0\\in \\CL$ is a set of constraints and $\\unif_0$ is a substitution.\nIt returns a constraint $C \\in \\mathcal S$ in\nsolved form and a unifier $\\unif$.\nThe main idea of the algorithm is to first remove all the type equalities\nby using regular Herbrand unification. After that, we only have\na set of inequalities among kinds, which we can consider as a relation.\nWe can then saturate the relation,\nunify all kinds that in the same equivalence classes to obtain\na most general unifier on kind variables,\nremove all existentially quantified variables and\nthen minimize back the relation.\n\nMore precisely, we apply the following steps:\n\\begin{enumerate}\n\\item Solve all type equality constraints through Herband unification and\n  gather all existential quantifications at the front of the constraint.\n  We obtain a constraint $C^k = \\exists \\kvar_i,\\ \\Cleq{k_j}{k'_j}_j$ and\n  a substitution $\\unif_\\tau$.\n  \n  We note $\\mathcal R$ the relation $\\Cleq{k_j}{k'_j}_j$,\n  $\\mathcal G$ the underlying directed graph and $V$ its vertices.\n\n\\item Saturate the lattice equalities in $\\mathcal R$.\n  \n  More precisely, for each kind variable $\\kvar \\in V$,\n  for each constant $l_i$ (resp. $l_j$) such that\n  there is a path from $l_i$ to $\\kvar$ (resp. from $\\kvar$ to $l_j$) in $\\mathcal G$,\n  add an edge from $\\lub l_i$ to $\\kvar$\n  (resp. from $\\kvar$ to $\\glb l_j$).\n  This step is well defined since $\\mathcal L$ is a bounded lattice\n  and $\\lub\\emptyset$ and $\\glb\\emptyset$ are well defined.\n\n  We also complement $\\mathcal R$ with $(\\leq)$ by adding an edge\n  between related constants.\n\\item\n  At this point, we can easily check for satisfiability: A constraint\n  is satisfiable (in the given environment) if and only if,\n  for any constants $l_1$ and $l_2$ such that\n  there is a path from $l_1$ to $l_2$ in $\\mathcal G$, then $l_1\\lk_\\Lat l_2$.\n  If this is not the case, we return \\textbf{fail}.\n  \n\\item For each strongly connected component in $\\mathcal G$, unify all its vertices and replace it by a representative.\n  We note $\\unif_k$ the substitution that replaces a kind variable by\n  its representative.\n  The representative of a strongly connected component $g$ can be determined as follows:\n  \\begin{itemize}\n  \\item If $g$ does not contain any constant, then the representative\n    is a fresh kind variable.\n  \\item If $g$ contains exactly one constant, it is the representative.\n  \\item Otherwise, the initial constraint $C_0$ is not satisfiable.\n  \\end{itemize}\n  Note that this step will also detect all unsatisfiable constraints.\n\\item Take the transitive closure of $\\mathcal R$.\n\\item Remove all the vertices corresponding to the kind variables $\\kvar_i$\n  that are existentially quantified in $C^k$.\n\\item Take the transitive reduction of $\\mathcal R$.\n\\item Remove the extremums of $\\mathcal L$ and the edges of $(\\leq)$\n  from $\\mathcal R$.\n\\item Return $C = \\left\\{ k \\leq k' \\mid k \\operatorname{\\mathcal R}k' \\right\\}$\n  and $\\unif =  \\unif_\\tau \\meet \\unif_k$.\n\\end{enumerate}\n\n\\TODO{Add an example}\n\n\\subsubsection{Soundness and Principality}\n\n\\begin{lemma}[Normal form]\n  \\label{lemma:normalform}\n  Given a constraint $D\\in\\CL$, a substitution $\\phi$ and\n  $(C,\\unif) = \\normalize{D}{\\phi}$,\n  then $\\phi\\leq\\unif$,\n  $C \\equivC \\unif D$ and\n  $\\unif C = C$.\n\\end{lemma}\n\\begin{proof}\n  % For simplicity, we assume that any substitution has been already applied\n  % to $D$ and that $\\phi = id$.\n  Let us partition $\\phi$ into a part which affects type variables,\n  $\\phi_\\tau$, and a part which affects kind variables, $\\phi_k$.\n  \n  We note $(C^k,\\unif_\\tau)$ the result of\n  the modified Herbrand unification on $(D,\\phi)$ in step (1).\n  Herbrand unification computes the most general\n  unifier. Our modified Herbrand unification only output additional\n  kind constraints for kind on the arrows and does not change\n  the result of the unification. Thus, we have\n  $\\phi_\\tau\\leq\\unif_\\tau$,\n  $C^k \\equivC \\unif_\\tau D$ and\n  $\\unif_\\tau C^k = C^k$.\n  \n  Let $C^{k+}$ be the result after step (2), we trivially have that\n  $\\fv{C^{k+}} = \\fv{C^k}$ and that $C^{k+} \\equivC C^k$.\n\n  Let $C^{A}$ and $\\unif_k$ be the results after step (4).\n  By definition, we have $\\unif_k C^{k+} \\equivC C^{A}$ and\n  $\\unif_k C^{A} = C^{A}$. Since $\\phi_k$ has already be applied to $C$ before\n  unifying the strongly connected components,\n  we have that $\\phi_k\\leq\\unif_k$.\n\n  Let $\\unif = \\unif_\\tau \\meet \\unif_k$. Since $\\unif_\\tau$ and $\\unif_k$\n  have disjoint supports,\n  we have $C^{A} = \\unif_\\tau C^{A} \\equivC \\unif C^{k+} \\equivC \\unif D$\n  and $\\unif C^{A} = C^{A}$.\n  Furthermore, $\\phi_\\tau \\meet \\phi_k \\leq \\unif_\\tau \\meet \\unif_k$.\n  \n  Steps (5) to (9) all preserve the free variables and the equivalence\n  of constraints, which concludes.\n\\end{proof}\n\n\\begin{lemma}[Uniqueness]\n  Given $(C_1,\\unif_1)$ and $(C_2,\\unif_2)$ such that\n  $\\unif_1 C_1 \\equivC \\unif_2 C_2$, then\n  $\\normalize{C_1}{\\unif_1}$ and $\\normalize{C_2}{\\unif_2}$\n  are identical up to $\\alpha$-renaming.\n\\end{lemma}\n\\begin{proof}\n  In \\cref{lemma:normalform}, we have showed that all the steps of the\n  normalization procedure preserve equivalence.\n  Since $\\unif_1 C_1 \\equivC \\unif_2 C_2$, equivalence between\n  the two results of the normalization procedures is preserved for all steps.\n\n  We note $P(C_a)$ if for all $C = (k, k)'$\n  such that $\\entail{C_a}{C}$ and $\\nvdash_eC$,\n  we have $C \\in {\\mathcal R}_a$. \n\n  Let us note $C_1'$ and $C_2'$ the constraints after step (4). $P(C_1')$ and\n  $P(C_2')$ hold. Indeed, since $C_1'$ and $C_2'$ are only composed\n  of existential quantifications and kind inequalities, the only rules\n  that applies are transitivity and lattice inequalities.\n  After step (2) and (5), the associated relations are fully saturated for these\n  two rules, hence all inequalities that can be deduced from $C_a'$ are already\n  present in the relation.\n\n  The property $P$ is preserved by step (6) since we only remove\n  inequalities that involve existentially quantified variables. Such\n  inequalities could not be picked in $P$.\n  % In (6) we only remove\n  % trivial lattice inequalities.\n\n  Let us note $C''_a$ for $a\\in\\{1,2\\}$ the constraints after step (5).\n  Since there are no more existential variables,\n  we have $C''_a=(k_i,k'_i)_i=\\mathcal R''_a$.\n  For any $C=(k,k')$ such that $\\entail{}{C}$ and $\\entail{C''_a}{C}$,\n  then $C \\in (\\leq) \\subset {\\mathcal R}''_a$.\n  Indeed, the only trivial inequalities in our system are equalities of the form\n  $(\\kvar, \\kvar)$, which were removed in step (4) and the lattice inequalities.\n\n  Let us consider $C = (k,k') \\in \\mathcal R''_1$.\n  Since $C''_1\\equivC C''_2$, we have $\\entail{C''_2}{C}$.\n  If $\\nvdash_e{C}$, by $P(C''_2)$ we have that\n  $C\\in R''_2$.\n  If $\\entail{}{C}$, then $C\\in (\\leq) \\subset R''_2$.\n  We conclude that $R''_1 \\subset R''_2$.\n  By symmetry, $R''_1 = R''_2$ and $C''_1 = C''_2$.\n\n  This equality is preserved by step (7) and (8)\n  since the transitive reduction of a directed acyclic graph is unique,\n  which concludes.\n\\end{proof}\n\n\n\\begin{theorem}\n  $\\CL$ has the principal constraint property and\n  $\\operatorname{normalize}$ computes principal normal forms for $\\CL$.\n\\end{theorem}\n\n\\begin{lemma}\n  For all $C\\in\\mathcal S$, $\\entail{C}{x = x}$ implies\n  $\\entail{}{x = x}$.\n\\end{lemma}\n\\begin{proof}\n  By definition of $\\operatorname{normalize}$, We have $C = \\Cleq{k}{k'}_i$\n  such that the underlying relation has no cycles.\n  Thus, we can not deduce neither kind nor type equalities from $C$.\n\\end{proof}\n\n\\begin{lemma}\n  $\\CL$ is regular, ie, for $x, x'$ two types or kinds,\n  $\\entail{}{\\Ceq{x}{x'}}$ implies\n  $\\fv{x} = \\fv{x'}$\n\\end{lemma}\n\\begin{proof}\n  The only equalities possibles are between variables (via symmetry) or\n  between constants.\n\\end{proof}\n\n\\begin{theorem}\n  Type inference in $HM(\\CL)$ is sound, principal and complete.\n\\end{theorem}\n\n\n\\subsection{Principality}\n\n\\TODO{}\n\n\\begin{itemize}\n\\item Properly ensure that it respects HM(X) (cylindric, \\dots)\n\\item Show principal type inference:\n  \\begin{itemize}\n  \\item Principal constraint system\n  \\item Regular constraint system: $\\Ceq{\\tau}{\\tau'} \\implies \\fv{\\tau} = \\fv{\\tau'}$.\n  \\item Solved forms are in simplified form.\n    $C\\in S, \\entail{C}{\\Ceq{\\tau}{\\tau'}} \\implies \\entail{}{\\Ceq{\\tau}{\\tau'}}$.\n  \\end{itemize}\n\\item Show equivalence with the logic-based system.\n\n\\end{itemize}\n\n\n% \\begin{lemma}\n%   Without loss of generality, we can consider that\n%   kind inequalities in satisfiable constraints\n%   are only done on kind variables. \n\n%   \\begin{proof}\n%     Consider the constraint $\\Cleq{k}{k'}\\Cand C$.\n%     \\begin{itemize}\n%     \\item If $k$ and $k'$ are both constants, it can be removed.\n%     \\item If the constraint is $\\Cleq{\\kvar}{\\kaff}$ or $\\Cleq{\\kun}{\\kvar}$, it can be removed.\n%     \\item If the constraint is $\\Cleq{\\kvar}{\\kun}$ or $\\Cleq{\\kaff}{\\kvar}$, we\n%       can substitute $\\kvar$ by its value in $C$.\n%     \\end{itemize}\n%   \\end{proof}\n% \\end{lemma}\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: \"../main\"\n%%% End:\n", "meta": {"hexsha": "82d780a21d4226698ef8f3afd83c38e0eb171900", "size": 14197, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "kindly/infer/infer.tex", "max_stars_repo_name": "m0rphism/uniqueness", "max_stars_repo_head_hexsha": "0fb8834e5739fdfe1fe78b056e233e6afbbc9921", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kindly/infer/infer.tex", "max_issues_repo_name": "m0rphism/uniqueness", "max_issues_repo_head_hexsha": "0fb8834e5739fdfe1fe78b056e233e6afbbc9921", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kindly/infer/infer.tex", "max_forks_repo_name": "m0rphism/uniqueness", "max_forks_repo_head_hexsha": "0fb8834e5739fdfe1fe78b056e233e6afbbc9921", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.895890411, "max_line_length": 119, "alphanum_fraction": 0.6878918081, "num_tokens": 4541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.5273165233795672, "lm_q1q2_score": 0.3085334988298176}}
{"text": "\\subsection{ZINDO-based transfer integrals using MOO }\n\\label{sec:izindo}\n\n\\newcommand{\\moo}{MOO\\xspace}\n\\index{electronic coupling!ZINDO}\n\nAn approximate method based on Zerner's Intermediate Neglect of Differential Overlap (ZINDO) has been described in Ref.~\\cite{kirkpatrick_approximate_2008}. This semiempirical method is substantially faster than first-principles approaches, since it avoids the self-consistent calculations on each individual monomer and dimer. This allows to construct the matrix elements of the ZINDO Hamiltonian of the dimer from the weighted overlap of molecular orbitals of the two monomers. Together with the introduction of rigid segments, only a single self-consistent calculation on one isolated conjugated segment is required. All relevant molecular overlaps can then be constructed from the obtained molecular orbitals.\n\nThe main advantage of the molecular orbital overlap (\\moo) library is {\\em fast} evaluation of electronic coupling elements. Note that \\moo is based on the ZINDO Hamiltonian which has limited applicability. The general advice is to first compare the accuracy of the \\moo method to the DFT-based calculations. \n\n\\moo can be used both in a \\slink{prog:moo_overlap}{standalone mode} and as an \\calc{izindo} \\calculator of \\votcactp. \n\nSince \\moo constructs the Fock operator of a dimer from the  molecular orbitals of monomers by translating and rotating the orbitals of \\slink{sec:segments}{rigid fragments}, the optimized geometry of all \\slink{sec:segments}{conjugated segments} and the coefficients of the molecular orbitals are required as its input in addition to the state file (\\sqlstate) with the \\slink{sec:neighborlist}{neighbor list}. Coordinates are stored in \\xyz files with four columns, first being the atom type and the next three atom coordinates. This is a standard \\texttt{xyz} format without a header. Note that the atom order in the \\xyz files can be different from that of the mapping files. The correspondence between the two is established in the \\xmlcsg file. \n\n\\attention{Izindo requires the specification of orbitals for hole and electron transport in \\xmlcsg. They are the HOMO and LUMO respectively and can be retrieved from the \\texttt{log} file from which the \\orb file is generated. The number of \\texttt{alpha electrons} is the HOMO, the LUMO is HOMO+1 } \n\nThe calculated transfer integrals are immediately saved to the \\sqlstate file.\n\\votcacommand{Transfer integrals from \\calc{izindo}}{\\ctprun \\opt \\xmloptions \\sql \\sqlstate \\exe \\calc{izindo} }\n\n\n", "meta": {"hexsha": "1043c207209d1cd00bb7e26f60a9c9d2470dcc6c", "size": 2538, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "manual/theory/moo.tex", "max_stars_repo_name": "mbarbry/ctp", "max_stars_repo_head_hexsha": "8461ba9d012c7e171a05e0b114b59d0523fc9a56", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "manual/theory/moo.tex", "max_issues_repo_name": "mbarbry/ctp", "max_issues_repo_head_hexsha": "8461ba9d012c7e171a05e0b114b59d0523fc9a56", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "manual/theory/moo.tex", "max_forks_repo_name": "mbarbry/ctp", "max_forks_repo_head_hexsha": "8461ba9d012c7e171a05e0b114b59d0523fc9a56", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 120.8571428571, "max_line_length": 751, "alphanum_fraction": 0.804570528, "num_tokens": 605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6688802471698041, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.30836501729584886}}
{"text": "% !TEX root = ../../../proposal.tex\nIn the following, $a||b$ denotes concatenation of strings $a$ and $b$.\n$a{[i]}$ references the $i$-th byte in $a$. $(N,e)$ denotes an RSA public\nkey, where $N$ has byte-length $\\ell_m$ ($|N|=\\ell_m$) and $e$ is the public\nexponent. The corresponding secret exponent is $d = 1/e \\bmod \\phi(N)$.\n\n\\subsection{\\PKCS encryption padding}\n\\label{sec:PKCSdescr}\n\nOur attacks rely on the structure of RSA \\PKCS padding. Although RSA PKCS\\#1\nv2.0 implements OAEP, SSL/TLS still uses \\PKCS. The \\PKCS encryption padding\nscheme~\\cite{rfc2313} randomizes encryptions by prepending a random padding\nstring $PS$ to a message $k$ (here, a symmetric session key) before RSA\nencryption:\n\n\\begin{enumerate} \n\t\\item The plaintext message is $k$, $\\ell_k = |k|$. The encrypter generates a random byte\n\tstring $PS$, where $|PS| \\geq 8$, $|PS|=\\ell_m-3-\\ell_k$, and $\\hex{00} \\not \\in \\{PS{[1]}, \\ldots,PS{[|PS|]}\\}$. \n\t\\item The encryption block is $m = 00||02||PS||00||k$. \n\t\\item The ciphertext is computed as $c = m^e \\bmod N$. \n\\end{enumerate} \n\nTo decrypt such a ciphertext, the decrypter first computes $m = c^d\n\\bmod N$.  Then it checks whether the decrypted message $m$ is\ncorrectly formatted as a \\PKCS-encoded message. We say that the\nciphertext $c$ and the decrypted message bytes $m{[1]} || m{[2]} || ... ||\nm{[\\ell_m]}$ are \\PKCSconform if:\n\\begin{equation*} \n\t\\begin{split} \n\t\tm{[1]}||m{[2]} \\text{ } = &\\text{ } \\hex{00} || \\hex{02}\\\\\n\t\t\\hex{00} \\text{ } \\not \\in &\\text{ } \\{m{[3]}, \\ldots,m{[10]}\\}\\\\ \n\t\\end{split}\n\\end{equation*} \nIf this condition holds, the decrypter searches for the first value\n$i>10$ such that $m{[i]}=0x00$. Then, it extracts $k =\nm{[i+1]}||\\ldots||m{[\\ell_m]}$. Otherwise, the ciphertext is rejected.\n\nIn SSLv3 and TLS, RSA \\PKCS is used to encapsulate the \\pms exchanged during\nthe handshake~\\cite{rfc5246}. Thus, $k$ is interpreted as the \\pms. In SSLv2,\nRSA \\PKCS is used for encapsulation of an equivalent key denoted the\n\\texttt{master\\_key}.\n\n\n\\subsection{SSL and TLS}\nThe first incarnation of the TLS protocol was the SSL (Secure Socket Layer)\nprotocol, which was designed by Netscape in the 90s. The first two versions\nof SSL were immediately found to be vulnerable to trivial\nattacks~\\cite{rfc6176,ssl-v3-1996} which were fixed in SSLv3~\\cite{rfc6101}.\nLater versions of the standard were renamed TLS, and share a similar\nstructure to SSLv3. The current version of the protocol is TLS 1.2; TLS 1.3\nis currently under development.\n\nAn SSL/TLS protocol flow consists of two phases: handshake and\napplication data exchange. In the first phase, the communicating\nparties agree on cryptographic algorithms and establish shared\nkeys. In the second phase, these keys are used to protect the\nconfidentiality and authenticity of the transmitted application data.\n\nThe handshake protocol was fundamentally redesigned in the \\sslthree\nversion. This new handshake protocol was then used in later TLS\nversions up to TLS 1.2. In the following, we describe the RSA-based\nhandshake protocols used in TLS and \\ssltwo, and highlight their\ndifferences.\n\n\\paragraph{The \\ssltwo handshake protocol.}\n\\label{sec:ssl2}\n\nThe \\ssltwo protocol description~\\cite{sslv2} is less formally specified than\nmodern RFCs. Figure~\\ref{fig:ssl-handshake} depicts an \\ssltwo handshake.\n\n\\begin{figure}\n\t\\includegraphics[width=\\linewidth]{\\DrownFigures/ssl-handshake} \n\t\\caption{\\textbf{\\ssltwo handshake}\\,---\\,%\n\tThe server responds with a \\texttt{ServerVerify} message directly after\n    receiving an RSA-\\PKCS ciphertext contained in \\texttt{ClientMasterKey}.\n\tThis protocol feature enables the attack.\n\t}\n\t\\label{fig:ssl-handshake}\n\\end{figure}\n\nA client initiates an \\ssltwo handshake by sending a\n\\texttt{ClientHello} message, which includes a list of cipher\nsuites $cs_c$ supported by the client and a client nonce $r_c$,\ntermed \\texttt{challenge}.\nThe server responds with a \\texttt{ServerHello} message, which\ncontains a list of cipher suites $cs_s$ supported by the server,\nthe server certificate, and a server nonce $r_s$, termed\n$\\texttt{connection\\_ID}$.\n\nThe client responds with a \\texttt{ClientMasterKey} message, which\nspecifies a cipher suite supported by both peers and key data\nused for constructing a \\texttt{master\\_key}. In order to support\n\\textit{export} cipher suites with 40-bit security (e.g.,\n\\texttt{SSL\\_RC2\\_128\\_CBC\\_EXPORT40\\_WITH\\_MD5}), the key data is\ndivided into two parts:\n\\begin{itemize}\n\t\\item $mk_{clear}$: A portion of the \\texttt{master\\_key} sent in the \\texttt{ClientMasterKey} message as plaintext (termed \\texttt{clear\\_key\\_data} in the \\ssltwo standard).\n\t\\item $mk_{secret}$: A secret portion of the\n          \\texttt{master\\_key}, encrypted with RSA \\PKCS (termed \\texttt{secret\\_key\\_data}). \n\\end{itemize}\nThe resulting \\texttt{master\\_key} $mk$ is constructed by\nconcatenating these two keys: $mk = mk_{clear} || mk_{secret}$. For\n40-bit export cipher suites, $mk_{secret}$ is five bytes in length.\nFor non-export cipher suites, the whole \\texttt{master\\_key} is\nencrypted, and the length of $mk_{clear}$ is zero.\n\nThe client and server can then compute session keys from the reconstructed \\texttt{master\\_key} $mk$:\n\n\\vspace{-6pt}\n\\begin{center}\n\\begin{math}\n\t\\texttt{server\\_write\\_key} = MD5(mk || ``0\" || r_c || r_s) \\linebreak\t\n\t\\texttt{client\\_write\\_key} = MD5(mk || ``1\" || r_c || r_s)\n\\end{math}\n\\end{center}\n\\vspace{-6pt}\n\nThe server responds with a \\texttt{ServerVerify} message\nconsisting of the \\texttt{challenge} $r_c$ encrypted with the\n\\texttt{server\\_write\\_key}.  Both peers then exchange\n\\texttt{Finished} messages in order to authenticate to each other.\n\nOur attack exploits the fact that the server always decrypts an RSA-\\PKCS\nciphertext, computes the \\texttt{server\\_write\\_key}, and \\textit{immediately}\nresponds with a \\texttt{ServerVerify} message.  The \\ssltwo standard\nimplies this message ordering, but does not make it explicit.\nHowever, we observed this behavior in every implementation we\nexamined.  Our attack also takes advantage of the fact that the\nencrypted $mk_{secret}$ portion of the \\texttt{master\\_key} can vary\nin length, and is only five bytes for export ciphers.\n\n\\ifsubmit\\relax\\else\n\\begin{figure}\n\t\\includegraphics[width=\\linewidth]{\\DrownFigures/tls-handshake} \n\t\\caption{\\textbf{TLS-RSA handshake}\\,---\\,%\n    After receiving an encrypted \\pms, the server waits for an authenticated\n\t\\texttt{ClientFinished} message.\n\t}\n\t\\label{fig:tls-handshake}\n\\end{figure}\n\\fi\n\n\\paragraph{The TLS handshake protocol.}\nIn TLS~\\cite{rfc5246} or \\sslthree, the client initiates the handshake with a \\texttt{ClientHello}, which contains a client random $r_c$ and a list of supported cipher suites. The server chooses one of the cipher suites and responds with three messages, \\texttt{ServerHello}, \\texttt{Certificate}, and \\texttt{ServerHelloDone}. These messages include the server's choice of cipher suite, server nonce $r_s$, and a server certificate with an RSA public key. The client then uses the public key to encrypt a newly generated 48-byte \\pms $pms$ and sends it to the server in a \\texttt{ClientKeyExchange} message. The client and server then derive encryption and MAC keys from the \\pms and the client and server random nonces. The details of this derivation are not important to our attack.  The client then sends \\texttt{ChangeCipherSpec} and \\texttt{Finished} messages. The \\texttt{Finished} message authenticates all previous handshake messages using the derived keys. The server responds with its own \\texttt{ChangeCipherSpec} and \\texttt{Finished} messages.\n\nThe two main details relevant to our attacks are:\n\\begin{itemize}\n\t\\item The \\pms is always 48 bytes long, independent of the chosen cipher suite.  This is also true for export cipher suites.\n\t\\item After receiving the \\texttt{ClientKeyExchange} message, the server waits for the \\texttt{ClientFinished} message, in order to authenticate the client.\n\\end{itemize}\n\n\n\\subsubsection{Real-world protocol support}\nTLSv1.0 is the most commonly supported protocol version, according to several\nsurveys. The SSL Labs SSL Pulse survey~\\cite{ssl-pulse} reports that 98.6\\%\nof about 140,000 popular TLS/SSL-enabled web sites supported TLSv1.0 in\nJanuary 2016. 72.0\\% supported TLSv1.2. Support for \\ssltwo was at 9.3\\%, and\n\\sslthree was at 29\\%. Mayer et al.~\\cite{mail-tls-mayer-2015} performed\nInternet-wide surveys of SMTP, IMAP, and POP3 between April and August 2015,\nand found that support for \\ssltwo support was as high as 41.7\\% of servers\nfor SMTP on port 25 and as low as 3.7\\% of IMAP servers on port 143. Support\nfor TLSv1.0 was nearly universal on these ports, varying from 91.6\\% on port\n25 to 98.9\\% on port 143.\n\nBowen~\\cite{cab-forum-sslv2} collected 213 million SSL/TLS client hellos and\nuser agent strings from connections to popular sites, of which 183,000\n(0.09\\%) client hellos supported \\ssltwo. All of these client hellos also\nsupported at least TLSv1.0.\n\nHolz et al.~\\cite{mail-tls-holz-2016} performed passive monitoring to collect\ninformation about 16 million SSL/TLS connections during one week in\nJuly-August 2015. They did not report any numbers for \\ssltwo, and stated in\npersonal communication that they did not observe any \\ssltwo connections in\ntheir dataset.\n\n%In response to our disclosure, OpenSSL has disabled \\ssltwo by default in the 1.0.1r and 1.0.2f releases~\\cite{opensslchangelog}.  \n\n%This bug was also fixed in the aforementioned openssl releases.\n\n\\subsection{Bleichenbacher's attack}\n\\label{sec:bleichenbacher}\nBleichenbacher's attack is a padding oracle attack---it exploits the fact\nthat RSA ciphertexts should decrypt to \\PKCS-compliant plaintexts. If an\nimplementation receives an RSA ciphertext that decrypts to an invalid \\PKCS\nplaintext, it might naturally leak this information via an error message, by\nclosing the connection, or by taking longer to process the error condition.\nThis behavior can leak information about the plaintext that can be modeled as\na cryptographic \\textit{oracle} for the decryption process.\nBleichenbacher~\\cite{bleichenbacher-1998} demonstrated how such an oracle\ncould be exploited to decrypt RSA ciphertexts.\n\n%For example, the decrypting code may require different processing times for valid vs.\\ invalid plaintexts - this is termed a \"timing side-channel vulnerability\". As another example, the decrypting code may send messages derived in some way from the plaintexts - this is termed a \"direct message side channel vulnerability\".\n%The seminal work in this area \\cite{Bleichenbacher} identified the general potential for such vulnerabilities, specifically using a direct message side channel vulnerability present in TLS implementations at the time, and demonstrated how such information could be gradually combined to eventually decrypt the RSA ciphertext in full.\n\n\\paragraph{Algorithm.}\nIn the simplest attack scenario, the attacker has a valid \\PKCS\nciphertext $c_{0}$ that they wish to decrypt to discover the message\n$m_{0}$.  They have no access to the private RSA key, but instead have\naccess to an oracle $\\Oracle$ that will decrypt a ciphertext $c$ and\ninform the attacker whether the most significant two bytes match\nthe required value for a correct \\PKCS padding:\n\\begin{equation*} \n\\Oracle(c) =  \n\\begin{cases} \n1 & \\text{ if } m=c^d \\bmod N \\text{ starts with \\hexb{00}{02}} \\\\ \n0 & \\text{ otherwise.} \n\\end{cases} \n\\end{equation*} \n\nIf the oracle answers with \\texttt{1}, the attacker knows that $2B\n\\leq m \\leq 3B-1$, where $B = 2^{8(\\ell_m-2)}$.  The attacker can\ntake advantage of RSA malleability to generate new candidate ciphertexts\nfor any $s$:\n\\[\nc = (c_{0} \\cdot s^e) \\bmod N = (m_{0} \\cdot s)^e \\bmod N \n\\]\nThe attacker queries the oracle with $c$. If the oracle responds with\n$0$, the attacker increments $s$ and repeats the previous\nstep. Otherwise, the attacker learns that for some~$r$, $2B \\leq m_{0}s - rN  < 3B$. This allows the attacker to reduce the range of possible solutions to:  \n\\[ \n\\frac{2B+rN}{s} \\leq m_{0} < \\frac{3B+rN}{s}  \n\\] \nThe attacker proceeds by refining guesses for $s$ and $r$ values and\nsuccessively decreasing the size of the interval containing $m_{0}$.  At\nsome point the interval will contain a single valid value, $m_{0}$.\nBleichenbacher's original paper describes this process in further\ndetail~\\cite{bleichenbacher-1998}.\n\n\\paragraph{Countermeasures.}\nIn order to protect against this attack, the decrypter must not leak\ninformation about the \\PKCS validity of the ciphertext.  The\nciphertext does not decrypt to a valid message, so the\ndecrypter generates a fake plaintext and continues the\nprotocol with this decoy.  The attacker should not be able to\ndistinguish the resulting computation from a correctly decrypted\nciphertext.\n\nIn the case of SSL/TLS, the server generates a random \\pms to continue\nthe handshake if the decrypted ciphertext is\ninvalid.  The client will not possess the session key to send a valid\n\\texttt{ClientFinished} message and the connection will terminate.\n\n", "meta": {"hexsha": "4a60f5cb996bfebc4ad2aa956e72e8ea8e9c7a44", "size": 13028, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "papers/drown/paper/background.tex", "max_stars_repo_name": "dadrian/dissertation", "max_stars_repo_head_hexsha": "5607114fb4340c5b6e944c73ed6019006d3ebec9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "papers/drown/paper/background.tex", "max_issues_repo_name": "dadrian/dissertation", "max_issues_repo_head_hexsha": "5607114fb4340c5b6e944c73ed6019006d3ebec9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "papers/drown/paper/background.tex", "max_forks_repo_name": "dadrian/dissertation", "max_forks_repo_head_hexsha": "5607114fb4340c5b6e944c73ed6019006d3ebec9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.6131687243, "max_line_length": 1057, "alphanum_fraction": 0.7612833896, "num_tokens": 3617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.4493926344647596, "lm_q1q2_score": 0.30826063269579773}}
{"text": "\\documentclass[twoside]{article}\n\n\\usepackage{amsmath,amsthm}\n\\usepackage{xspace}\n\\usepackage{fancyhdr}\n\\usepackage{hyperref}\n\\usepackage[a4paper,left=2cm,right=2cm,top=2cm,bottom=2cm]{geometry}\n\\newtheorem{definition}{Definition}\n%%% Logik\n\n\n\\input{./definitions}\n\\input{./version}\n\n\\title{\\DiMo -- A Tool for Discrete Modelling Using Propositional Logic \\\\ Version \\DiMoVersion}\n\n\\author{Martin Lange \\\\ University of Kassel, Germany}\n\n\n\\fancyhead[L]{M.~Lange}\n\\fancyhead[R]{The \\DiMo Tool}\n\\fancyfoot[RO, LE]{\\thepage}\n\\fancyfoot[C]{}\n\\renewcommand{\\headrulewidth}{0.4pt}\n\\renewcommand{\\footrulewidth}{0.4pt}\n\\pagestyle{fancy}\n\n\n\\allowdisplaybreaks\n\n\\begin{document}\n\n\\maketitle\n\n\\tableofcontents\n\n\\section{Discrete Modelling Problems}\n\nThe \\DiMo language can be used to model various discrete decision or computation problems as logical problems in quantifier-free logic.\nThe four logical problems that are supported are\n\\begin{itemize}\n\\item the \\emph{satisfiability problem} for finding \\emph{some} model of a given formula;\n\\item the \\emph{validity problem} for checking whether \\emph{all} interpretations satisfy a given formula, respectively for finding\n      a countermodel;\n\\item the \\emph{model class} problem for finding \\emph{all} models of a given formula;\n\\item the \\emph{equivalence} problem for checking whether two given formulas are semantically equivalent on a given set of propositions, \n      respectively finding a model (in those propositions) that separates the two.\n\\end{itemize}\nThe \\DiMo language can be used to specify formulas \\emph{parametrised} by natural numbers. The logical problems above are then applied\nto \\emph{all} instances of such formula schemes. \n\n\n\\section{Basic Design Principles of the Language}\n\n\\paragraph*{Specifying problems.} \nA \\DiMo input starts with the specification of the problem, defined by the keywords \\texttt{SATISFIABLE}, \\texttt{VALID}, \n\\texttt{EQUIVALENT} or \\texttt{MODELS}, followed by the formula scheme to be tested. \n\nIn case of the equivalence problem this is followed by the keyword \\texttt{TO} and a second formula scheme. Note that this is a generalisation\nof the standard equivalence problem which checks equality between the model classes of two formulas. Here the input is given by two formulas\n$\\varphi$ and $\\psi$ and a set of propositional variables $L$, and the question is to decide whether the model classes of $\\varphi$ and $\\psi$\ncoincide when restricted to $L$. In other words: for every propositional variable assignment $\\vartheta$ s.t.\\ $\\vartheta \\models \\varphi$, is\nthere a variable assignment $\\vartheta'$ s.t.\\ $\\vartheta' \\models \\psi$ and $\\vartheta(X) = \\vartheta'(X)$ for all $X \\in L$. Moreover, does\nthe same hold vice-versa between $\\psi$ and $\\varphi$? Note that this generalises semantic equivalence in the sense that each pair of\nsemantically equivalent formulas is also equivalent when restricted to any $L$ but not vice-versa.\n \n\n\\paragraph*{Specifying interesting predicates.}\nOne can then optionally specifiy the (names) of the predicate symbols which should be considered in the output. This can be used\nto suppress the reporting of unnecessarily long models or countermodels, for instance when the formula schemes use certain predicate\nsymbols as auxiliary only. This is indicated by the keyword \\texttt{PROPOSITIONS}, followed by a list of those predicate names. Note\nthat all predicate symbols not listed here are suppressed. Hence, without the \\texttt{PROPOSITIONS} section in the input, no models / \ncountermodels are generated.\n\nFurthermore, when the chosen problem is the equivalence problem then it is taken to be restricted to those propositions that are given \nin this section. Consequently, when no propositions are given here, the equivalence problem boils down to a simple equi-satisfiability check.\n\n\\paragraph*{Specifying parameters.}\nThis section is followed by a section specifying the parameters to the formula scheme, started with the keyword \\texttt{PARAMETERS}.\nParameters are variables for natural numbers and can be denoted with an arbitrary alphanumeric string starting with a lowercase letter.\nParameters to the scheme are specified as a comma-separated list of name-domain pairs, for instance \n\\begin{quote}\n\\texttt{n : NAT}   \n\\end{quote}\ndefines a parameter \\texttt{n} that stands for any number in $\\{0,1,\\ldots\\}$. Other means to specify a domain are, for instance\n\\begin{center}\n\\begin{tabular}{ll}\n\\texttt{\\{3,..\\}} & for the set $\\{3,4,5,\\ldots\\}$, \\\\\n\\texttt{\\{3,7,..\\}} & for the set $\\{3,7,11,15,\\ldots\\}$, \\\\\n\\texttt{\\{3,7,..,20\\}} & for the set $\\{3,7,11,15,19\\}$, \\\\\n\\texttt{\\{3,7,20,4,16\\}} & for the set $\\{3,4,7,16,20\\}$.\n\\end{tabular}\n\\end{center} \nIt is possible to impose certain simple conditions on parameter combinations by appending the keyword \\texttt{WITH}, followed by\na comma-separated non-empty list of basic comparisons like \\texttt{n < m}. Allowed comparisons are \\emph{equals}, \\emph{greater-than}, \n\\emph{less-than}, \\emph{greater-or-equals}, \\emph{less-or-equals}, and \\emph{unequals}.\n\n\\paragraph*{Specifying formula abbreviations.} \nThere is no distinction between a predicate, like \\texttt{P(n,m)} and an auxiliary formula. It is thus possible to abbreviate certain\nformula parts and give the definition of these predicates in a final section started with the keyword \\texttt{WHERE}, followed by\na list of definitions of the form \n\\begin{quote}\n\\emph{pattern} \\texttt{=} \\emph{formula}\n\\end{quote}\nNote that there is no comma separation between these definitions. A pattern in this context is a predicate symbol, possibly followed\nby a comma-separated list of variables or numbers, enclosed in parentheses, i.e.\\ \\texttt{P} or \\texttt{P(n)} or \\texttt{P(0,n)}.\nNote that \\DiMo does not type-check predicates w.r.t.\\ their arity. A symbol should only be used with the same arity throughout the\nentire specification.\n\n\\paragraph*{Specifying terms and finite sets.} \nTerms are made up from integers and variables which are either specified in the \\texttt{PARAMETERS} section or introduced by the junctors \n\\texttt{FORALL} and \\texttt{FORSOME}, using the arithmetical operations of addition, subtraction and multiplication. Terms can be used\nas arguments to predicate symbols, for instance as in \\texttt{X(n,n+2)}.\n\nA finite set is an enumeration of terms like \\texttt{\\{1,n,n+3,m-2,n*m+i,10\\}}. It is possible to define linear sets by specifying the\nleast, possibly the second-to-least, and the last element. This follows the same convention as used in the specification of domains\nabove. For instance, \\texttt{\\{1,..,n\\}}, \\texttt{\\{0,2,..,n-1\\}} and \\texttt{\\{n,2*n,..,m*n\\}} are valid specifications of such sets\nprovided that the variables have been defined either as parameters or via generalised junctors, see below.\n\nThere are also the operators \\texttt{MIN} and \\texttt{MAX} which turn sets into terms. For instance, \\texttt{MIN \\{n+1,9,k,m-n\\}} is a term.\n\n\n\\paragraph*{Specifying formulas.}\nThe \\DiMo language supports propositional logic with the standard Boolean unary or binary operators $\\wedge,\\vee,\\neg,\\to,\\leftrightarrow$, \nas well as conjunctions and disjunctions over finite sets of indices (e.g.\\ $\\bigwedge_{i=1}^n \\ldots$). For instance, formula (scheme)\n$\\bigwedge_{i=0}^{n-1} X_i \\leftrightarrow X_{i+1}$, parametrised by a natural number $n$ would be specified as\n\\begin{quote} \\tt\n  FORALL i: \\{0,..,n-1\\} . X(i) <-> X(i+1)\n\\end{quote}\nIn general, such a junctor defines a new variable \\texttt{i} which can be used in the formula following the dot. A disjunction $\\bigvee$ \nis denoted using the keyword \\texttt{FORSOME}.\n\n\n \n\n\n\\section{Examples}\n\n\\subsection{The $n$-Queens Problem}\n\nA standard discrete modelling problem is the following: given a chess board of size $n \\times n$ with $n \\ge 1$, place $n$ queens on this board such that\nnone of them threatens another. A queen in chess can move an arbitrary distance along a row, column or diagonale. Clearly, the problem\namounts to placing one queen in each column for example. Moreover, to exclude possible threats between queens, by symmetry it suffices to\nconsider one direction per row/column/diagonale only, for example no queen should ``see'' another queen in the directions east, north, \nnorth-east and south-east. \n\nThe question of finding a solution to the $n$-queens problem boils down to finding a model of the following propositional formula (scheme) $\\varphi_n$ for\ngiven $n$. We use propositional variables $D_{i,j}$ with $1 \\le i,j, \\le n$ to intuitively denote that the square in column $i$ and row $j$ is occupied by a queen.\n\\begin{align*}\n\\varphi_n := & \\bigwedge\\limits_{i=1}^n \\bigvee\\limits_{j=1}^n D_{i,j} & \\text{``\\emph{in each column place a queen in some row}''} \\\\\n\\wedge & \\bigwedge\\limits_{i=1}^n \\bigwedge\\limits_{j=1}^{n-1} D_{i,j} \\to \\bigwedge\\limits_{k=j+1}^n \\neg D_{i,k} & \\text{``\\emph{no two queens per row}''} \\\\ \n\\wedge & \\bigwedge\\limits_{i=1}^{n-1} \\bigwedge\\limits_{j=1}^n D_{i,j} \\to \\bigwedge\\limits_{k=i+1}^n \\neg D_{k,j} & \\text{``\\emph{no two queens per column}''} \\\\ \n\\wedge & \\bigwedge\\limits_{i=1}^{n-1} \\bigwedge\\limits_{j=1}^{n-1} D_{i,j} \\to \\hspace*{-1cm} \n  \\bigwedge\\limits_{k = 1 \\atop \\text{s.t. } i+k \\le n \\text{ and } j+k \\le n}^\\infty \\hspace*{-1cm}\\neg D_{i+k,j+k} \n  & \\text{``\\emph{no two queens per diagonale up}''} \\\\ \n\\wedge & \\bigwedge\\limits_{i=1}^{n-1} \\bigwedge\\limits_{j=2}^{n} D_{i,j} \\to \\hspace*{-1cm} \n  \\bigwedge\\limits_{k = 1 \\atop \\text{s.t. } i+k \\le n \\text{ and } j-k \\ge 1}^\\infty \\hspace*{-1cm}\\neg D_{i+k,j-k} \n  & \\text{``\\emph{no two queens per diagonale down}''} \\\\ \n\\end{align*}\nThe problem of finding a model for each instance of $\\varphi_n$ can be specified as a \\DiMo program as follows.\n\\begin{verbatim}\nSATISFIABLE NQueens(n)\nPROPOSITIONS D\nPARAMETERS n: {1,..}\nFORMULAS \n  NQueens(n) = AtLeastOneInEachRow(n)\n             & AtMostOneInEachRow(n)\n             & AtMostOneInEachColumn(n)\n             & AtMostOneInEachDiagUp(n)\n             & AtMostOneInEachDiagDown(n)\n\t         \n  AtLeastOneInEachRow(n)     = \n    FORALL i: {1,..,n}. FORSOME j: {1,..,n}. D(i,j)\n    \n  AtMostOneInEachRow(n)      = \n    FORALL i: {1,..,n}. FORALL j: {1,..,n-1}. \n      D(i,j) -> FORALL k: {j+1,..,n}. -D(i,k)\n    \n  AtMostOneInEachColumn(n)   = \n    FORALL i: {1,..,n-1}. FORALL j: {1,..,n}. \n      D(i,j) -> FORALL k: {i+1,..,n}. -D(k,j)\n    \n  AtMostOneInEachDiagUp(n)   = \n    FORALL i: {1,..,n-1}. FORALL j: {1,..,n-1}. \n      D(i,j) -> FORALL k: {1,..,MIN {n-i,n-j}}. -D(i+k,j+k)\n    \n  AtMostOneInEachDiagDown(n) = \n    FORALL i: {1,..,n-1}. FORALL j: {2,..,n}. \n      D(i,j) -> FORALL k: {1,..,MIN {n-i,j-1}}. -D(i+k,j-k)\n\\end{verbatim}\nTesting this problem with the \\DiMo tool reveals solutions in terms of propositional variable assignments from which the placement of queens on the \nchess boards of respective sizes can immediately be derived.\n\\begin{verbatim}\n[~] dimo.native examples/nQueens.dm\nInstance n=1 ................................... satisfiable.\n  Satisfying assignment: D(1,1)\nInstance n=2 ................................... unsatisfiable.\nInstance n=3 ................................... unsatisfiable.\nInstance n=4 ................................... satisfiable.\n  Satisfying assignment: -D(1,1), -D(1,2), D(1,3), -D(1,4), D(2,1), -D(2,2), -D(2,3), \n  -D(2,4), -D(3,1), -D(3,2), -D(3,3), D(3,4), -D(4,1), D(4,2), -D(4,3), -D(4,4)\n...\n\\end{verbatim} \nThe output shows that the \\DiMo tool has chosen the standard enumeration $n = 1,2,\\ldots$ for the parameter \\texttt{n}, instantiated the formulas scheme for\neach instance of this enumeration and checked each of them for satisfiability subsequently. For $n = 2$ and $n = 3$ there is no solution to the $n$-queens\nproblem as one can easily check. Consequently, these instances are reported as being unsatisfiable. On the other hand, the instances $n=1,4,5,\\ldots$ are\nsatisfiable, and a propositional model is found. It is easy to read off a solution to the $n$-queens problem from the assignment satisfying the $n$-th formula,\ngiven the interpretation of the propositions $D_{i,j}$ mentioned above.\n\n \n\\subsection{A Simple Combinatorial Problem}\n\nAs a second example we consider the simple combinatorial problem of choosing exactly $m$ out of $n$ items. This can equally be modelled as the problem\nof finding some or all models of a propositional formula $\\varphi_{n,m}$ with $n \\ge 1$ and $0 \\le m \\le n$. We use propositions $A_i$ to denote that\nthe $i$-th element is chosen. The straight-forward scheme\n\\begin{displaymath}\n\\bigvee\\limits_{I \\subseteq \\{1,\\ldots,n\\} \\atop |C| = m} (\\bigwedge\\limits_{i \\in I} A_i) \\wedge \\hspace*{-5mm} \\bigwedge\\limits_{i \\in \\{1,\\ldots,n\\} \\setminus I} \\hspace*{-5mm} \\neg A_i) \n\\end{displaymath}\ncannot be written down as such in the \\DiMo language because variables for sets of natural numbers are not supported (yet). However, note that this \nis a formula of size $\\mathcal{O}(n \\cdot \\binom{n}{m}) = \\mathcal{O}(n^{m+1})$, and there is a much shorter way of specifying this which uses formulas\nof size $\\mathcal{O}(n^2)$ only. The trick is to use auxiliary propositions $B_{i,j}$ to abbreviate the fact that at least $j$ out of the first $i$\nelements have chosen, or equivalently, at least $j$ of the $A_1,\\ldots,A_i$ need to be set to true. Consider\n\\begin{align*}\n\\varphi_{n,m} := &B_{n,m}  & \\text{``\\emph{at least m out of (the first) n are chosen''}} \\\\ \n\\wedge &\\bigwedge\\limits_{i=1}^n \\bigwedge\\limits_{j=1}^m B_{i,j} \\to & \\text{``\\emph{if j of i are chosen then}} \\\\\n&\\hspace*{2.4cm} A_i \\wedge B_{i-1,j-1} & \\text{\\emph{the i-th is chosen and j-1 of i-1 are chosen}} \\\\\n&\\hspace*{2cm}\\vee B_{i-1,j} &\\text{\\emph{or j of i-1 are chosen}''} \\\\\n\\wedge &\\bigwedge\\limits_{j=1}^m \\neg B_{0,j} & \\text{``\\emph{it is impossible to choose j from 0 elements}''}\n\\end{align*}\nUsing the same principle one can also demand that at the same time \\emph{at most} $m$ out of $n$ are chosen. Note that this is the case if and only if\n\\emph{at least} $n-m$ are \\emph{not chosen}. Based on this, the following \\DiMo program specifies the problem of choosing exactly $m$ out $n$ elements\nrepresented by propositions $A_i$. The auxiliary propositions $B_{i,j}$ are hidden away from output by not listing them in the \\texttt{PROPOSITIONS}\nsection.\n\\begin{verbatim}\nMODELS       ExactlyMofN(n,m)\nPROPOSITIONS A\nPARAMETERS   n : {1,..}, m : NAT WITH m <= n\nFORMULAS\n\n  ExactlyMofN(n,m) = AtLeastMChosen(n,m) & AtMostMChosen(n,m)\n\n  AtLeastMChosen(n,m) = B(n,m) & BsWellBehaved(n,m) & BsEndOk(m)\n  BsWellBehaved(n,m)  = FORALL i : {1,..,n}. FORALL j: {1,..,m}. \n                          B(i,j) -> A(i) & B(i-1,j-1) | B(i-1,j) \n  BsEndOk(m)          = FORALL j : {1,..,m}. -B(0,j)\n\n  AtMostMChosen(n,m) = AtLeastNminusMNotChosen(n,n-m)\n  AtLeastNminusMNotChosen(n,m) = N(n,m) & NsWellBehaved(n,m) & NsEndOk(m)\n  NsWellBehaved(n,m) = FORALL i : {1,..,n}. FORALL j: {1,..,m}. \n                          N(i,j) -> -A(i) & N(i-1,j-1) | N(i-1,j)\n  NsEndOk(m)         = FORALL j : {1,..,m}. -N(0,j)\n\\end{verbatim}\nNote that formulas constraining the propositions \\texttt{N(i,j)} are copied verbatim from those for the \\texttt{B(i,j)}. It is not (yet) possible to\nre-use such code because only integer variables can be used as parameters, not propositions themselves. \n\nRunning the \\DiMo tool on this program results in finding all possibilities to choose $m$ out of $n$ elements, represented by propositional variable\nassignments, for some enumeration of the parameters $n$ and $m$.\n\\begin{verbatim}\n[~] dimo.native examples/exactlyMofN.dm\nInstance m=0, n=1 .............................. \n  Found model -A(1)\n1 model found.\nInstance m=0, n=2 .............................. \n  Found model -A(1), -A(2)\n1 model found.\nInstance m=1, n=1 .............................. \n  Found model A(1)\n1 model found.\nInstance m=0, n=3 .............................. \n  Found model -A(1), -A(2), -A(3)\n1 model found.\nInstance m=1, n=2 .............................. \n  Found model A(1), -A(2)\n  Found model -A(1), A(2)\n2 models found.\nInstance m=0, n=4 .............................. \n  Found model -A(1), -A(2), -A(3), -A(4)\n1 model found.\nInstance m=1, n=3 .............................. \n  Found model A(1), -A(2), -A(3)\n  Found model -A(1), A(2), -A(3)\n  Found model -A(1), -A(2), A(3)\n3 models found.\nInstance m=2, n=2 .............................. \n  Found model A(1), A(2)\n1 model found.\nInstance m=0, n=5 .............................. \n  Found model -A(1), -A(2), -A(3), -A(4), -A(5)\n1 model found.\n...\n\\end{verbatim}\nThe chosen enumeration of all pairs of parameters $n,m$ such that $n \\ge 1$, and $0 \\le m \\le n$ is the standard ``diagonale'' $(1,0),(2,0),(1,1),(3,0),(2,1),(4,0),\\ldots$.\nHere, for each such instance \\DiMo finds all possibilities to choose $m$ out of $n$ elements, represented by a propositional variable assignment in the variables $A_i$. \n\n\n\\appendix\n\n\\section{The \\DiMo Tool}\n\n\\subsection{License}\nAs of version 0.2.1, \\DiMo is available via GitHub under the BSD-3-Clauses licence.\n\n\n\\subsection{Installation}\n\nThe \\DiMo testing tool is written in OCaml using version 4.07.0. Lower version may work as well. The simplest way to use the tool is to install the OCaml package manager \n\\texttt{Opam}\\footnote{\\url{https://opam.ocaml.org/}}. Make sure you use version 2 of \\texttt{Opam}. For correct functionality, version 0.4 of the Opam package \n\\texttt{ocaml-sat-solvers} is needed which is not installed with previous versions of Opam.\n\nOpam then gives a simple way to install the OCaml compiler and runtime environment. To use the precompiled byte code version this should suffice. To compile a native \nversion of the \\DiMo tool one needs additional components that can be installed via \\texttt{Opam}. See the file \\texttt{README} for details.\n\n\\section{Syntax of the \\DiMo Language}\n\nThe syntax of the \\DiMo input language is given by the following grammar.\n\\begin{align*}\n\\nonterm{Main} ::=\\ & \\nonterm{Problem} \\optional{\\term{PROPOSITIONS} \\nonterm{Props}}\\ \n                                         \\optional{\\term{PARAMETERS} \\nonterm{Params}}\\ \n                                         \\optional{\\term{FORMULAS} \\nonterm{Defs}} \\\\\n\\nonterm{Problem}\\ ::=\\ & \\term{SATISFIABLE} \\nonterm{Formula} \\\\\n                 \\altn & \\term{VALID} \\nonterm{Formula} \\\\\n                 \\altn & \\term{EQUIVALENT} \\nonterm{Formula} \\term{TO} \\nonterm{Formula} \\\\\n                 \\altn & \\term{MODELS} \\nonterm{Formula} \\\\\n\\nonterm{Props} ::=\\ & \\epsilon \\altn \\nonterm{Ident} \\Big(\\term{,} \\nonterm{Ident}\\Big)^* \\\\\n\\nonterm{Ident} ::=\\ & \\enumset{\\texttt{A},\\ldots,\\texttt{Z}}\\enumset{\\texttt{A},\\ldots,\\texttt{Z},\\texttt{a}\\ldots,\\texttt{z},\\texttt{0},\\ldots,\\texttt{9},\\term{\\_}}^*\\enumset{\\term{'}}^* \\\\\n\\nonterm{Params} ::=\\ & \\nonterm{Var} \\term{:} \\nonterm{Domain} \\Big( \\term{,} \\nonterm{Var} \\term{:} \\nonterm{Domain} \\Big)^* \n                           \\optional{\\term{WITH} \\nonterm{Constr}} \\\\\n\\nonterm{Var} ::=\\ & \\enumset{\\texttt{a},\\ldots,\\texttt{z}}\\enumset{\\texttt{A},\\ldots,\\texttt{Z},\\texttt{a}\\ldots,\\texttt{z},\\texttt{0},\\ldots,\\texttt{9},\\term{\\_}}^*\\enumset{\\term{'}}^* \\\\ \n\\nonterm{Domain} ::=\\ & \\term{Nat} \\\\\n                \\altn & \\term{\\{} \\nonterm{Number} \\term{,} \\optional{\\nonterm{Number} \\term{,}} \\term{..} \n                                         \\optional{\\term{,} \\nonterm{Number}} \\term{\\}} \\\\\n                \\altn & \\term{\\{} \\nonterm{Number} \\group{\\term{,} \\nonterm{Number}}^* \\term{\\}} \\\\\n\\nonterm{Number} ::=\\ & \\enumset{\\texttt{1},\\ldots,\\texttt{9}}\\enumset{\\texttt{0},\\ldots,\\texttt{9}}^* \\\\ \n\\nonterm{Constr} ::=\\ & \\nonterm{Var} \\nonterm{Cmp} \\nonterm{Var} \\group{\\term{,} \\nonterm{Var} \\nonterm{Cmp} \\nonterm{Var}}^* \\\\\n\\nonterm{Cmp} ::=\\ & \\term{=} \\altn \\term{<=} \\altn \\term{>=} \\altn \\term{<} \\altn \\term{>} \\altn \\term{<>} \\\\ \n\\nonterm{Defs} ::=\\ & \\epsilon \\altn \\nonterm{Pattern} \\term{=} \\nonterm{Formula} \\group{\\term{,} \\nonterm{Pattern} \\term{=} \\nonterm{Formula}}^* \\\\\n\\nonterm{Pattern} ::=\\ &\\nonterm{Ident} \\optional{\\term{(} \\nonterm{Atom} \\group{\\term{,} \\nonterm{Atom}}^* \\term{)}} \\\\\n\\nonterm{Atom} ::=\\ &\\nonterm{Var} \\altn \\nonterm{Number} \\\\\n\\nonterm{Formula} ::=\\ & \\term{True} \\altn \\term{False} \\altn \\nonterm{Pred} \\\\\n                 \\altn & \\term{(} \\nonterm{Formula} \\term{)} \\\\\n                 \\altn & \\term{-} \\nonterm{Formula} \\altn \\nonterm{Formula} \\nonterm{Junct} \\nonterm{Formula} \\\\\n                 \\altn & \\nonterm{GenJunct} \\nonterm{Var} \\term{:} \\nonterm{FinSet} \\term{.} \\nonterm{Formula} \\\\\n\\nonterm{Junct} ::=\\ & \\term{\\&} \\altn \\term{|} \\altn \\term{->} \\altn \\term{<->} \\\\\n\\nonterm{GenJunct} ::=\\ & \\term{FORALL} \\altn \\term{FORSOME} \\\\\n\\nonterm{Pred} ::=\\ & \\nonterm{Ident} \\optional{\\term{(} \\nonterm{Term} \\group{\\term{,} \\nonterm{Term}}^* \\term{)}} \\\\\n\\nonterm{Term} ::=\\ & \\nonterm{Atom} \\altn \\term{(} \\nonterm{Term} \\term{)} \\altn \\nonterm{UnOp} \\nonterm{Term} \\altn \\nonterm{Term} \\nonterm{BinOp} \\nonterm{Term} \\altn \\nonterm{AccOp} \\nonterm{FinSet} \\\\\n\\nonterm{UnOp} ::=\\ & \\term{LOG} \\altn \\term{FLOG} \\\\\n\\nonterm{BinOp} ::=\\ &\\term{+} \\altn \\term{-} \\altn \\term{*} \\altn \\term{\\textasciicircum} \\altn \\term{MOD} \\\\\n\\nonterm{AccOp} ::=\\ &\\term{MIN} \\altn \\term{MAX} \\\\\n\\nonterm{FinSet} ::=\\ & \\term{\\{} \\nonterm{Term} \\term{,} \\optional{\\nonterm{Term} \\term{,}} \\term{..} \\term{,} \\nonterm{Term} \\term{\\}} \\\\\n                \\altn & \\term{\\{} \\nonterm{Term} \\group{\\term{,} \\nonterm{Term}}^* \\term{\\}} \\\\\n                \\altn & \\nonterm{FinSet} \\nonterm{SetOp} \\nonterm{FinSet} \\\\\n\\nonterm{SetOp} ::=\\ & \\term{\\&} \\altn \\term{|} \\altn{-} \n\\end{align*}\nA note regarding precedences: the \\DiMo tool implements the standard precedence rules for Boolean operators, i.e.\\ \\texttt{A \\& B | C} is parsed in the same way as\n\\texttt{(A \\& B) | C}. \n\nThe precedence and associativity rules for the arithmetic operators are as follows: Addition, subtraction, multiplication and division are left-associative; exponentiation is \nright-associative. This enumeration also reflects the increasing order of precedence amongst these operations.\n\n\n\\section{Version History}\n\n%Bug fixes:\n%\\begin{itemize}\n%\\item \n%\\end{itemize}\n\n\\subsubsection*{Version 0.2.3 (21/06/2021)}\n\nBug fixes:\n\\begin{itemize}\n\\item Fixed throwing of \\texttt{exception Invalid_argument(\"Bytes.create\")} on instances with long (or many) parameter names.\n\\end{itemize}\n\n\\subsubsection*{Version 0.2.2 (01/07/2020)}\n\nFeature changes:\n\\begin{itemize}\n\\item Output of Boolean constants has been changed to match input, now \\texttt{True} and \\texttt{False}\n\\item The format of variables and formulas has been extended to allow quote symbols in the end as in \\texttt{x'} etc.\n\\end{itemize}\n\n\\subsubsection*{Version 0.2.1 (29/10/2019)}\n\nFeature changes:\n\\begin{itemize}\n\\item \\DiMo has moved to GitHub under the BSD-3-Clauses license.\n\\end{itemize}\n\n\n\\subsubsection*{Version 0.2.0 (10/09/2019)}\n\nBug fixes:\n\\begin{itemize}\n\\item The tokenizer did not recognise line breaks properly so that failure because of lexing errors resulted in error messages reporting the line and column number wrongly. Fixed.\n\\item Applying the LOG function to argument 0 does not result in a stack overflow anymore. Instead the program terminates with failure. \n\\end{itemize}\nFeature changes:\n\\begin{itemize}\n\\item The \\DiMo language has been extended with a function FLOG on terms that computes the rounded-off logarithm to base 2.\n\\item The standard precedence and associativity rules for the arithmetic operators have been implemented. The \\DiMo language has been extended with a function FLOG on terms that computes the rounded-off logarithm to base 2.\n\\end{itemize}\n\n\n\\subsubsection*{Version 0.1.5 (03/07/2019)}\n\nBug fixes:\n\\begin{itemize}\n\\item Operator MAX was interpreted as MIN: fixed.\n\\end{itemize}\n\n\n\\subsubsection*{Version 0.1.4 (01/07/2019)}\n\nBug fixes:\n\\begin{itemize}\n\\item Command line parameters \\texttt{--onlypos} and \\texttt{--onlyneg} no longer ignored in checking validity problems.\n\\item Problem with non-atomic terms like \\texttt{i+1} in set definitions, leading to program crashes with error ``\\texttt{compare: invalid argument}'', fixed.\n\\item Problem with instantiation of formula schemes into negation normal form fixed.\n\\end{itemize}\nFeature changes:\n\\begin{itemize}\n\\item Model enumeration problems now report the number of models that were found.\n\\end{itemize}\n\n\\subsubsection*{Version 0.1.2 (27/11/2018)}\nBug fixes:\n\\begin{itemize}\n\\item Faulty instantiation of formulas containing negation, generalised junctions (\\texttt{FORALL}, \\texttt{FORSOME}) and propositional constants (\\texttt{True}, \\texttt{False}) fixed.\n\\item Crash through array-out-of-bounds exception when specifying finite domains by enumeration of alle elements (e.g.\\ \\texttt{n:~\\{1,2\\}}) fixed.\n\\end{itemize}\nFeature changes:\n\\begin{itemize}\n\\item Output in debug mode streamlined.\n\\item Added command-line parameters to suppress the printing of negative, resp.\\ positive literals in models.\n\\end{itemize}\n\n\\subsubsection*{Version 0.1.1 (26/11/2018)}\n\nBug fixes:\n\\begin{itemize}\n\\item Problem with producing output for validity problems trying to show refuting assignments for valid rather than invalid formulas fixed. \n\\item Program crashes due to an error in function ``toCNF.negate'' caused by non-literal arguments fixed. \n\\end{itemize}\n\n \n\\bibliographystyle{plain}\n\\bibliography{../literature} \n\\end{document}\n\n", "meta": {"hexsha": "c4ceef592b7dcac162fb70abe0d55b2a3f6d6d7e", "size": 25388, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/dimo.tex", "max_stars_repo_name": "muldvarp/DiMo", "max_stars_repo_head_hexsha": "c233debe69b75ae09c57efc4ced0e233d27e1f9f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-06-30T13:47:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T13:43:27.000Z", "max_issues_repo_path": "doc/dimo.tex", "max_issues_repo_name": "muldvarp/DiMo", "max_issues_repo_head_hexsha": "c233debe69b75ae09c57efc4ced0e233d27e1f9f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/dimo.tex", "max_forks_repo_name": "muldvarp/DiMo", "max_forks_repo_head_hexsha": "c233debe69b75ae09c57efc4ced0e233d27e1f9f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.1681415929, "max_line_length": 223, "alphanum_fraction": 0.6880809831, "num_tokens": 7913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3082365543113072}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\marginpar{Wednesday\\\\ 2020-10-7, \\\\ compiled \\\\ \\today}\n\nWe come back to the horizon problem. \n[Plot of the comoving Hubble radius \\(r_H\\) as a function of time]\n\nThe problem is solved if there is an early epoch in which \\(r_H\\) decreases in time, due to accelerated expansion.\n\nAfter the end of this inflation, the regular FLRW universe's history starts, with the radiation, then matter, then cosmological constant dominated phases. \nAn accelerated expansion, however, is not enough to solve the horizon problem: what we need is for \\emph{every} observable scale, up to the largest ones, was causally connected in the early universe.\nIn other words, the inflation phase must last \\emph{long enough}.\n\nMore specifically, our constraint on inflation is that it must start when the Hubble radius was at least as large as it is today.\nThis can be expressed in terms of the \\emph{number of \\(e\\)-folds}: \n%\n\\begin{align}\nN = \\log \\qty( \\frac{a_f}{a _{\\text{in}}})\n= \\int_{t _{\\text{in}}}^{t_f} H(t) \\dd{t}\n\\marginnote{Since \\(H = \\dot{a} / a = \\dv{(\\log a)}{t}\\).}\n\\,,\n\\end{align}\n%\nthe ratio of the scale factor at the beginning and at the end of inflation.\n% This is a natural measure of time \nThe number of elapsed \\(e\\)-folds is a natural measure of time in the epoch of inflation. \n\nWe can give the bound \\(N \\gtrsim 60 \\divisionsymbol 70\\) in order to solve the horizon problem. \nThis is a \\emph{huge} expansion! Typical atomic scales of \\SI{e-15}{m} get stretched to the typical scales of the Solar System, \\SI{e11}{m}. \n\nThe condition is \\(r_H (t _{\\text{in}}) \\gtrsim r_H (t_0 )\\). \nWe can express this as \n%\n\\begin{align}\n\\frac{1}{a _{\\text{in}} H _{\\text{in}}} &\\gtrsim \\frac{1}{a_0 H_0 }  \\\\\n\\frac{a_f}{ a _{\\text{in}}} = e^{N} &\\gtrsim \\frac{H _{\\text{in}}}{H_0 } \\frac{a_f}{a_0}\n\\,.\n\\end{align}\n%\n\\todo[inline]{See on Moodle: paper with the exact computation.}\n\nWe want to bring on the left all the quantities in the inflationary epoch. \nRecall that \\(H^2 \\propto \\rho \\propto a^{-3 (1+ w_i)}\\), which we will apply to the inflationary epoch with an equation of state \\(w_i < - 1/3\\). This means that \n%\n\\begin{align}\n\\frac{H_i}{H_f} H_f = \\qty(\\frac{a_i}{a_f})^{-3(1+ w_i) / 2} H_f\n\\,,\n\\end{align}\n%\nso \n%\n\\begin{align}\n\\frac{a_f}{a_i} \\qty(\\frac{a_f}{a_i})^{- 3 (1+ w_i) / 2} &\\gtrsim  \n\\frac{H_f}{H_0} \\frac{a_f}{a_0 } \\\\\n\\qty(\\frac{a_f}{a_i})^{\\frac{-(1 + 3 w_i)}{2}}\n&\\gtrsim \\frac{T_0 }{H_0 } \\frac{H_f}{T_f}\n\\,,\n\\end{align}\n%\nwhere we applied Tolman's law, \\(T \\sim 1/a\\), neglecting the matter dominated phase --- this is a reasonable approximation, we find a similar result to the complete calculation. This yields \n%\n\\begin{align}\nN \\gtrsim - \\frac{2}{1 + 3 w _i} \\qty[ \\log \\frac{T_0 }{H_0 } + \\log \\frac{H_f}{T_f}]\n\\,,\n\\end{align}\n%\nwhere \\(T_0 = \\SI{2.7}{K} \\approx \\SI{e-13}{GeV}\\), while \\(H_0 \\sim \\SI{e-42}{GeV}\\) in natural units. Therefore, the first logarithm is of the order \\(\\sim 67\\). \nWe also need the \\emph{pre-heating} temperature and Hubble parameter: \\(H_f\\) and \\(T_f\\). \nThis is model-dependent: it is what gives the theoretical uncertainty. \nThe dependence, however, is weak: only logarithmic. \n\nWith current measurements, we are starting to be able to measure this term as well. \nLet us give an estimate for it: \n%\n\\begin{align}\nH_f^2 \\approx \\frac{8 \\pi G}{3} \\rho _{\\text{rad}}\n\\,,\n\\end{align}\n%\nwhere \\(\\rho _{\\text{rad}} = \\frac{\\pi^2}{30} g_* T^{4}\\). This then yields \n%\n\\begin{align}\nH^2_f = \\frac{8 \\pi G}{3} \\frac{\\pi^2}{30} g_* T^{4} \\sim \\frac{T_f^4}{M_P^2}\n\\,.\n\\end{align}\n\nThere is model dependence here, in \\(g_*\\)! If we go BDSM (beyond de standard model) it could change. \nWe are giving a very rough estimate with the Planck mass. This then means \\(H_f \\sim T_f^2 / M_p\\). So, \n%\n\\begin{align}\n\\log \\qty( \\frac{H_f}{T_f}) \\approx \\log \\frac{T_f}{M_p}\n\\,.\n\\end{align}\n\nTypically, models predict \n%\n\\begin{align}\n\\num{e-5} < \\frac{T_f}{M_p} < 1\n\\,,\n\\end{align}\n%\nbut this is not set in stone, we could have different predictions as well. \n\nNow, let us assume that \\(w_i \\sim -1\\), something like a cosmological constant. Then, the prefactor is of the order \\(1\\), so the bound is \\(N \\gtrsim 60 \\divisionsymbol 70\\) as was mentioned before. \n\nWe now discuss the causal structure of the FLRW metric: \n%\n\\begin{align}\n\\dd{s^2} = - \\dd{t^2} + a^2(t) \\qty[ \\frac{ \\dd{r^2}}{1 - kr^2} + r^2 \\dd{\\Omega^2}]\n\\,.\n\\end{align}\n\nLet us express this in different coordinates: we introduce \\(\\chi \\), so that \n%\n\\begin{align}\nr = S_k (\\chi ) = \\begin{cases}\n    \\sinh \\chi & k = -1  \\\\\n    \\chi & k = 0 \\\\\n    \\sin \\chi & k = +1\n\\end{cases}\n\\,.\n\\end{align}\n\nThis allows the term \\(\\dd{r^2} / (1 - kr^2)\\) to become simply \\(\\dd{\\chi^2}\\). \n\nAlso, we introduce conformal time: \\(\\dd{\\eta } = \\dd{t} / a(t)\\), so that the metric becomes \n%\n\\begin{align}\n\\dd{s^2} = a^2(\\eta ) \\qty[- \\dd{ \\eta^2} + \\dd{\\chi^2} + S_k^2 (\\chi ) \\dd{\\Omega^2}]\n\\,.\n\\end{align}\n\nThe meaning of \\(\\chi \\) is still a comoving distance. \nHowever, the interesting thing is that this metric is conformally related to (``is a time-dependent rescaling of'') the Minkowski metric (if we consider radial motion, at least), we say that it is \\emph{conformally flat}.\n\nIn these coordinates, light propagates at \\SI{45}{\\degree} in the (\\(\\eta \\), \\(\\chi \\)) plane. \n\nThen, we can draw a diagram for the horizon problem in these coordinates: the Big Bang singularity looks like a straight line at constant \\(\\eta \\). \nThe last-scattering surface is also a straight line at constant \\(\\eta \\).\nWe can then draw a past light-cone from a point in the last-scattering surface. Inflation pushes the BB surface back in conformal time, so that light has more time to propagate and light cones will intersect. \n\n\\begin{claim}\nThe conformal time at the end of inflation looks like \\(\\eta \\propto 2 / (1 + 3 w) a^{2 / (1 + 3w)} H_*^{-1}\\), where \\(H_*\\) is the Hubble parameter at some reference time. \n\\end{claim}\n\n\\begin{proof}\nLet us again make use of the fact that \n%\n\\begin{align}\n\\dd{\\eta } = - \\frac{ \\dd{z}}{a_0 H(z)}\n\\,.\n\\end{align}\n\nHere \\(a_0 \\) is usually taken to mean ``now'', however the analysis which follows does not really depend on that fact. Then, the conformal time reads\n%\n\\begin{align}\n\\eta &= \\int_0^{\\eta} \\dd{\\widetilde{\\eta}} \n= \\int_{z}^{\\infty } \\frac{ \\dd{\\widetilde{z}}}{a_0 H(\\widetilde{z})} \n\\marginnote{Switched the integration margins: \\([0, \\eta ]\\) corresponds to \\((\\infty, z]\\).}\n \\\\\n&= \\frac{1}{a_0 H_0 } \\int_{z}^{\\infty } \\frac{ \\dd{\\widetilde{z}}}{E(\\widetilde{z})}\n\\,.\n\\end{align}\n\nIf we need to account for different fluids the integral cannot be done analytically, so we only account for one: the expression for the \\(E\\) function simplifies as \n%\n\\begin{align}\nE(z) = \\sqrt{\\sum _{i} \\Omega_{0, i} (1 + z)^{3 + 3 w_i}} = \\sqrt{(1 + z)^{3 + 3w}}\n\\,\n\\end{align}\n%\nfor a single component, with \\(\\Omega_0 = 1\\) and equation of state \\(w\\). Then, the integral reads \n%\n\\begin{align}\n\\eta &= \\frac{1}{a_0 H_0 } \\int_{z}^{\\infty } (1 + \\widetilde{z})^{-(3 + 3w) / 2} \\dd{\\widetilde{z}}  \\\\\n&= \\frac{1}{a_0 H_0 } \\qty(- \\frac{1 + 3w}{2})^{-1} \\qty[(1 + \\widetilde{z})^{-(1+3w) /2}]_{\\widetilde{z} = z}^{\\widetilde{z} = \\infty }  \\\\\n&= \\frac{1}{a_0 H_0 } \\frac{2}{(1 + 3w)} (1 + z)^{-(1+ 3w) / 2}  \\\\\n&= \\frac{2}{(1 + 3w)H_0 } a^{- (1+3w) / 2} a_0^{-1 - (1+ 3w) /2}  \\\\\n&\\propto \\frac{2}{(1 + 3w)H_0 } a^{- (1+3w) / 2}\n\\,.\n\\end{align}\n\nThis manipulation only works as long as \\(w > - 1/3\\): otherwise, the integral diverges. \n\\end{proof}\n% So, if \\(w < - 1/3\\), we are good. \n\n% \\todo[inline]{We can only detect correlations in the CMB up to the quadrupole, since the dipole is correlated with the Earth's motion\\dots Roughly, this means that we can only see correlations on the scale of \\(\\sim r_H\\), corresponding to \\SI{90}{\\degree} separation, instead of being able to see them on the scale of \\SI{180}{\\degree}. }\n\n\\subsection{Flatness problem}\n\nNow, we move to the flatness problem. \nThe HBB model is not intrinsically flawed, however the shortcomings we are discussing tell us that the initial conditions which would be required in order to yield the current universe would be very specific.\n\nWe should set initial conditions which are homogeneous and isotropic, with very specific small fluctuations. Inflation provides a dynamical solution to these problems, which is an attractor towards these initial conditions.\\footnote{See \\textcite[]{hossenfelderScreamsExplanationFinetuning2019} for a critical discussion of this fine-tuning problem.}\n\nThe first Friedmann equation reads \n%\n\\begin{align}\nH^2=  \\frac{8 \\pi G}{3} \\rho - \\frac{k}{a^2}\n\\,,\n\\end{align}\n%\nwhich we can express through \\(\\Omega = \\rho / \\rho _c\\), where \\(\\rho _c = 3 H^2 / (8 \\pi G) \\): \n%\n\\begin{align}\n\\Omega - 1 = \\frac{k}{a^2 H^2} = k r_H^2 (t)\n\\,,\n\\end{align}\n%\nso if \\(\\Omega \\) differs from unity even by a small amount, this difference increases with time. \n\nAt \\SI{95}{\\percent} CL, we know that \\(\\abs{\\Omega - 1} = \\abs{\\Omega _k} < \\SI{.4}{\\percent}\\), so the universe we observe is consistent with flatness. \n\nSpecifically, in the Planck epoch we will have \n%\n\\begin{align}\n\\Omega (t _{\\text{Pl}}) - 1 \\approx  (\\Omega_0 - 1) \\times \\num{e-60}\n\\,,\n\\end{align}\n%\nso \\(\\abs{\\Omega (t _{\\text{Pl}}) - 1} < \\num{e-62}\\).\n\n\\begin{claim}\nIt can be shown that \n%\n\\begin{align}\n\\qty(\\Omega^{-1} - 1) \\rho a^2 = \\const = -\\frac{3k}{8 \\pi G}\n\\,.\n\\end{align}\n\\end{claim}\n\\begin{proof}\nThe calculation is as follows: \n%\n\\begin{align}\nH^2 &= \\frac{8 \\pi G}{3} \\rho - \\frac{k}{a^2}  \\\\\n\\rho _c &= \\rho - \\underbrace{\\frac{3 k}{8 \\pi G}}_{\\const} \\frac{1}{a^2}  \\\\\n\\rho \\bigg( \\underbrace{\\frac{\\rho _c}{\\rho }}_{\\Omega^{-1}} - 1\\bigg) a^2 &= \\const\n\\,.\n\\end{align}\n\n\\end{proof}\n\nFor times before the matter-radiation equivalence \\(\\rho \\propto a^{-4}\\), so (neglecting the matter component) \\(\\rho (t) = \\rho _{\\text{eq}} (a _{\\text{eq}} / a)^{4}\\). Also, during matter domination up to now (neglecting the cosmological constant)\n%\n\\begin{align}\n\\rho_0 = \\rho _{\\text{eq}} \\qty(\\frac{a _{\\text{eq}}}{a_0 })^3\n\\,,\n\\end{align}\n%\ntherefore \n%\n\\begin{align}\n(\\Omega^{-1} -1) \\qty(\\frac{a _{\\text{eq}}}{a})^{4} a^2 \\rho _{\\text{eq}} \\qty(\\frac{a_0 }{a _{\\text{eq}}})^{3} \\frac{1}{\\rho _{\\text{eq}} a_0^2} &= (\\Omega_0^{-1} - 1)\n\\\\\n\\Omega^{-1} - 1 &= (\\Omega_0^{-1} -1) \\frac{a^2}{a _{\\text{eq}} a_0 } \\\\\n\\Omega^{-1} - 1 &= (\\Omega_0^{-1} -1) (1 + z _{\\text{eq}}) \\frac{a^2}{a_0^2}\n\\,,\n\\end{align}\n%\nsince \\(1 + z _{\\text{eq}} = a_0 / a _{\\text{eq}}\\). Also, we can approximate \\(a/a_0 \\sim T_0 / T _{\\text{Pl}}\\) by extending Tolman's law. \nThen, \n%\n\\begin{align}\n\\Omega^{-1} - 1 &= (\\Omega_0^{-1} -1) \\underbrace{(1 + z _{\\text{eq}})}_{\\sim \\num{e4}} \\underbrace{\\frac{T_0 ^2}{T _{\\text{Pl}}^2}}_{\\sim \\num{e-64}}\n\\,.\n\\end{align}\n\nThis proves the relation we wrote earlier. It is an extreme extrapolation to go back to the Planck time, but even if we only went back to Big Bang nucleosynthesis (\\(\\sim \\SI{1}{MeV}\\)) we would get \n%\n\\begin{align}\n\\abs{\\Omega (t _{\\text{BBN}}) - 1 } < \\num{e-18}\n\\,.\n\\end{align}\n\nHow does inflation solve the problem?\nRecall that \\(\\Omega -1  = k r_H^2\\), and inflation is by definition a time in which \\(r_H\\) decreases. \nAt the end of inflation, \\(\\Omega - 1\\) is very close to 0, meaning that \\(r_H\\) is small, but at the start of inflation it could have been relatively far from 1. \n\nNext week we will discuss the proper mechanism of this process.\nDuring an inflationary phase, \\(a (t) \\approx \\exp(Ht)\\). So, as long as \\(H\\) is approximately constant, we have\n%\n\\begin{align}\nr_H^2 = \\frac{1}{a^2 H^2} \\propto \\frac{1}{a^2}\n\\,.\n\\end{align}\n\nThen, we have \n%\n\\begin{align}\n\\frac{\\abs{\\Omega -1}_{t_f}}{\\abs{\\Omega - 1}_{t_i}} \\sim \\qty(\\frac{a_i}{a_f})^{2} \\sim \\exp(- 2N)\n\\,.\n\\end{align}\n\nThis means that, with very broad possible initial conditions, we find \\(\\Omega -1\\) very close to zero at the end of inflation. \n\nA De-Sitter phase is a reference example of a possible inflationary stage. \nIt would correspond to \\(\\rho = \\const\\), \\(w = -1\\): in general, since the ``curvature energy density'' scales like \\(a^{-2}\\), curvature becomes negligible. \n\nNote, however, that this is an unrealistic example: it does not include any method for the inflation to end. \n\n\\end{document}\n", "meta": {"hexsha": "01102d83e2e705cf222443cc2315c69faae8d39c", "size": 12287, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ap_third_semester/early_universe/oct07.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "ap_third_semester/early_universe/oct07.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ap_third_semester/early_universe/oct07.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 40.5511551155, "max_line_length": 350, "alphanum_fraction": 0.6556523155, "num_tokens": 4310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.30823655431130714}}
{"text": "\\documentclass[a4paper,10pt]{article}\n\\title{Wilcoxon Signed Ranks test.}\n\\date{\\today}\n\\author{KEEL non-parametric statistical module}\n\\begin{document}\n\n\\pagestyle{empty}\n\\maketitle\n\\thispagestyle{empty}\n\n\n\n\\section{Detailed results for no-features}\n\n\n\\subsection{Results}\n\n\\begin{table}[!htp]\n\\centering\\small\n\\begin{tabular}{\n|c|c|c|c|c|}\n\\hline\n VS & $R^{+}$ & $R^{-}$ & Exact P-value & Asymptotic P-value \\\\ \\hline \nfeatures & 194.0 & 271.0 & $\\geq$ 0.2 & 1\\\\ \\hline \nvoting & 152.0 & 313.0 & $\\geq$ 0.2 & 1\\\\ \\hline \nbagging & 233.0 & 263.0 & $\\geq$ 0.2 & 1\\\\ \\hline \nsvm-lin & 280.0 & 216.0 & $\\geq$ 0.2 & 0.524198\\\\ \\hline \nsvm-rbf & 159.0 & 306.0 & $\\geq$ 0.2 & 1\\\\ \\hline \nknn3 & 159.0 & 306.0 & $\\geq$ 0.2 & 1\\\\ \\hline \nknn5 & 389.0 & 107.0 & 0.004752 & 0.005556\\\\ \\hline \nmlp & 360.0 & 105.0 & 0.007612 & 0.00847\\\\ \\hline \n\n\\end{tabular}\n\\caption{Results obtained by the Wilcoxon test for algorithm no-features}\n\\end{table}\n\n\\subsection{Confidence intervals for Median of diferences}\n\n\\begin{table}[!htp]\n\\centering\\small\n\\begin{tabular}{\n|c|c|c|}\n\\hline\n $\\alpha$=0.90 & Confidence interval & Exact confidence \\\\ \\hline \nfeatures & [-0.003427 , 0.001041] & 0.90182\\\\ \\hline \nvoting & [-0.018906 , 0] & 0.90182\\\\ \\hline \nbagging & [-0.01 , 0.007856] & 0.90182\\\\ \\hline \nsvm-lin & [-0.01249 , 0.03584] & 0.90182\\\\ \\hline \nsvm-rbf & [-0.025688 , 0.001238] & 0.90182\\\\ \\hline \nknn3 & [-0.025688 , 0.001238] & 0.90182\\\\ \\hline \nknn5 & [0.008587 , 0.036948] & 0.90182\\\\ \\hline \nmlp & [0.007629 , 0.035931] & 0.90182\\\\ \\hline \n\n\\end{tabular}\n\\caption{Confidence intervals for algorithm no-features ($\\alpha$=0.90)}\n\\end{table}\n\\begin{table}[!htp]\n\\centering\\small\n\\begin{tabular}{\n|c|c|c|}\n\\hline\n $\\alpha$=0.95 & Confidence interval & Exact confidence \\\\ \\hline \nfeatures & [-0.003845 , 0.001525] & 0.9521\\\\ \\hline \nvoting & [-0.021229 , 0.002776] & 0.9521\\\\ \\hline \nbagging & [-0.011777 , 0.009389] & 0.9521\\\\ \\hline \nsvm-lin & [-0.015173 , 0.044271] & 0.9521\\\\ \\hline \nsvm-rbf & [-0.027805 , 0.004204] & 0.9521\\\\ \\hline \nknn3 & [-0.027805 , 0.004204] & 0.9521\\\\ \\hline \nknn5 & [0.006451 , 0.039682] & 0.9521\\\\ \\hline \nmlp & [0.004637 , 0.039409] & 0.9521\\\\ \\hline \n\n\\end{tabular}\n\\caption{Confidence intervals for algorithm no-features ($\\alpha$=0.95)}\n\\end{table}\n\n \\clearpage \n\n\n\\section{Detailed results for features}\n\n\n\\subsection{Results}\n\n\\begin{table}[!htp]\n\\centering\\small\n\\begin{tabular}{\n|c|c|c|c|c|}\n\\hline\n VS & $R^{+}$ & $R^{-}$ & Exact P-value & Asymptotic P-value \\\\ \\hline \nno-features & 271.0 & 194.0 & $\\geq$ 0.2 & 0.422457\\\\ \\hline \nvoting & 162.0 & 303.0 & $\\geq$ 0.2 & 1\\\\ \\hline \nbagging & 219.0 & 246.0 & $\\geq$ 0.2 & 1\\\\ \\hline \nsvm-lin & 280.0 & 216.0 & $\\geq$ 0.2 & 0.524198\\\\ \\hline \nsvm-rbf & 171.0 & 294.0 & $\\geq$ 0.2 & 1\\\\ \\hline \nknn3 & 171.0 & 294.0 & $\\geq$ 0.2 & 1\\\\ \\hline \nknn5 & 393.0 & 103.0 & 0.003598 & 0.004354\\\\ \\hline \nmlp & 374.0 & 122.0 & 0.012432 & 0.013176\\\\ \\hline \n\n\\end{tabular}\n\\caption{Results obtained by the Wilcoxon test for algorithm features}\n\\end{table}\n\n\\subsection{Confidence intervals for Median of diferences}\n\n\\begin{table}[!htp]\n\\centering\\small\n\\begin{tabular}{\n|c|c|c|}\n\\hline\n $\\alpha$=0.90 & Confidence interval & Exact confidence \\\\ \\hline \nno-features & [-0.001041 , 0.003427] & 0.90182\\\\ \\hline \nvoting & [-0.019587 , 0.002341] & 0.90182\\\\ \\hline \nbagging & [-0.009995 , 0.007197] & 0.90182\\\\ \\hline \nsvm-lin & [-0.012311 , 0.038649] & 0.90182\\\\ \\hline \nsvm-rbf & [-0.025331 , 0.003499] & 0.90182\\\\ \\hline \nknn3 & [-0.025331 , 0.003499] & 0.90182\\\\ \\hline \nknn5 & [0.009214 , 0.037489] & 0.90182\\\\ \\hline \nmlp & [0.008169 , 0.037251] & 0.90182\\\\ \\hline \n\n\\end{tabular}\n\\caption{Confidence intervals for algorithm features ($\\alpha$=0.90)}\n\\end{table}\n\\begin{table}[!htp]\n\\centering\\small\n\\begin{tabular}{\n|c|c|c|}\n\\hline\n $\\alpha$=0.95 & Confidence interval & Exact confidence \\\\ \\hline \nno-features & [-0.001525 , 0.003845] & 0.9521\\\\ \\hline \nvoting & [-0.021 , 0.003998] & 0.9521\\\\ \\hline \nbagging & [-0.011579 , 0.009372] & 0.9521\\\\ \\hline \nsvm-lin & [-0.015417 , 0.045676] & 0.9521\\\\ \\hline \nsvm-rbf & [-0.027915 , 0.005656] & 0.9521\\\\ \\hline \nknn3 & [-0.027915 , 0.005656] & 0.9521\\\\ \\hline \nknn5 & [0.006989 , 0.041708] & 0.9521\\\\ \\hline \nmlp & [0.004317 , 0.040127] & 0.9521\\\\ \\hline \n\n\\end{tabular}\n\\caption{Confidence intervals for algorithm features ($\\alpha$=0.95)}\n\\end{table}\n\n \\clearpage \n\n\n\\section{Detailed results for voting}\n\n\n\\subsection{Results}\n\n\\begin{table}[!htp]\n\\centering\\small\n\\begin{tabular}{\n|c|c|c|c|c|}\n\\hline\n VS & $R^{+}$ & $R^{-}$ & Exact P-value & Asymptotic P-value \\\\ \\hline \nno-features & 313.0 & 152.0 & 0.1004 & 0.095706\\\\ \\hline \nfeatures & 303.0 & 162.0 & 0.15188 & 0.144193\\\\ \\hline \nbagging & 348.0 & 148.0 & 0.05024 & 0.048901\\\\ \\hline \nsvm-lin & 379.0 & 117.0 & 0.009148 & 0.009968\\\\ \\hline \nsvm-rbf & 195.0 & 270.0 & $\\geq$ 0.2 & 1\\\\ \\hline \nknn3 & 195.0 & 270.0 & $\\geq$ 0.2 & 1\\\\ \\hline \nknn5 & 482.0 & 14.0 & 1.0244E-7 & 0.000004\\\\ \\hline \nmlp & 490.0 & 6.0 & 1.3038E-8 & 0.000002\\\\ \\hline \n\n\\end{tabular}\n\\caption{Results obtained by the Wilcoxon test for algorithm voting}\n\\end{table}\n\n\\subsection{Confidence intervals for Median of diferences}\n\n\\begin{table}[!htp]\n\\centering\\small\n\\begin{tabular}{\n|c|c|c|}\n\\hline\n $\\alpha$=0.90 & Confidence interval & Exact confidence \\\\ \\hline \nno-features & [0 , 0.018906] & 0.90182\\\\ \\hline \nfeatures & [-0.002341 , 0.019587] & 0.90182\\\\ \\hline \nbagging & [0.001961 , 0.023434] & 0.90182\\\\ \\hline \nsvm-lin & [0.003494 , 0.038727] & 0.90182\\\\ \\hline \nsvm-rbf & [-0.007311 , 0.002286] & 0.90182\\\\ \\hline \nknn3 & [-0.007311 , 0.002286] & 0.90182\\\\ \\hline \nknn5 & [0.022858 , 0.041694] & 0.90182\\\\ \\hline \nmlp & [0.022108 , 0.037243] & 0.90182\\\\ \\hline \n\n\\end{tabular}\n\\caption{Confidence intervals for algorithm voting ($\\alpha$=0.90)}\n\\end{table}\n\\begin{table}[!htp]\n\\centering\\small\n\\begin{tabular}{\n|c|c|c|}\n\\hline\n $\\alpha$=0.95 & Confidence interval & Exact confidence \\\\ \\hline \nno-features & [-0.002776 , 0.021229] & 0.9521\\\\ \\hline \nfeatures & [-0.003998 , 0.021] & 0.9521\\\\ \\hline \nbagging & [-0.000258 , 0.026104] & 0.9521\\\\ \\hline \nsvm-lin & [0.002014 , 0.049373] & 0.9521\\\\ \\hline \nsvm-rbf & [-0.008866 , 0.003289] & 0.9521\\\\ \\hline \nknn3 & [-0.008866 , 0.003289] & 0.9521\\\\ \\hline \nknn5 & [0.021008 , 0.044465] & 0.9521\\\\ \\hline \nmlp & [0.020545 , 0.039383] & 0.9521\\\\ \\hline \n\n\\end{tabular}\n\\caption{Confidence intervals for algorithm voting ($\\alpha$=0.95)}\n\\end{table}\n\n \\clearpage \n\n\n\\section{Detailed results for bagging}\n\n\n\\subsection{Results}\n\n\\begin{table}[!htp]\n\\centering\\small\n\\begin{tabular}{\n|c|c|c|c|c|}\n\\hline\n VS & $R^{+}$ & $R^{-}$ & Exact P-value & Asymptotic P-value \\\\ \\hline \nno-features & 263.0 & 233.0 & $\\geq$ 0.2 & 0.761321\\\\ \\hline \nfeatures & 246.0 & 219.0 & $\\geq$ 0.2 & 0.77338\\\\ \\hline \nvoting & 148.0 & 348.0 & $\\geq$ 0.2 & 1\\\\ \\hline \nsvm-lin & 248.0 & 248.0 & $\\geq$ 0.2 & 0.992182\\\\ \\hline \nsvm-rbf & 139.0 & 357.0 & $\\geq$ 0.2 & 1\\\\ \\hline \nknn3 & 139.0 & 357.0 & $\\geq$ 0.2 & 1\\\\ \\hline \nknn5 & 383.0 & 113.0 & 0.007088 & 0.007923\\\\ \\hline \nmlp & 355.0 & 141.0 & 0.03558 & 0.03515\\\\ \\hline \n\n\\end{tabular}\n\\caption{Results obtained by the Wilcoxon test for algorithm bagging}\n\\end{table}\n\n\\subsection{Confidence intervals for Median of diferences}\n\n\\begin{table}[!htp]\n\\centering\\small\n\\begin{tabular}{\n|c|c|c|}\n\\hline\n $\\alpha$=0.90 & Confidence interval & Exact confidence \\\\ \\hline \nno-features & [-0.007856 , 0.01] & 0.90182\\\\ \\hline \nfeatures & [-0.007197 , 0.009995] & 0.90182\\\\ \\hline \nvoting & [-0.023434 , -0.001961] & 0.90182\\\\ \\hline \nsvm-lin & [-0.016785 , 0.029622] & 0.90182\\\\ \\hline \nsvm-rbf & [-0.027765 , -0.005666] & 0.90182\\\\ \\hline \nknn3 & [-0.027765 , -0.005666] & 0.90182\\\\ \\hline \nknn5 & [0.008017 , 0.036183] & 0.90182\\\\ \\hline \nmlp & [0.003571 , 0.032056] & 0.90182\\\\ \\hline \n\n\\end{tabular}\n\\caption{Confidence intervals for algorithm bagging ($\\alpha$=0.90)}\n\\end{table}\n\\begin{table}[!htp]\n\\centering\\small\n\\begin{tabular}{\n|c|c|c|}\n\\hline\n $\\alpha$=0.95 & Confidence interval & Exact confidence \\\\ \\hline \nno-features & [-0.009389 , 0.011777] & 0.9521\\\\ \\hline \nfeatures & [-0.009372 , 0.011579] & 0.9521\\\\ \\hline \nvoting & [-0.026104 , 0.000258] & 0.9521\\\\ \\hline \nsvm-lin & [-0.019752 , 0.035137] & 0.9521\\\\ \\hline \nsvm-rbf & [-0.03042 , -0.002545] & 0.9521\\\\ \\hline \nknn3 & [-0.03042 , -0.002545] & 0.9521\\\\ \\hline \nknn5 & [0.006602 , 0.038597] & 0.9521\\\\ \\hline \nmlp & [0.001184 , 0.03602] & 0.9521\\\\ \\hline \n\n\\end{tabular}\n\\caption{Confidence intervals for algorithm bagging ($\\alpha$=0.95)}\n\\end{table}\n\n \\clearpage \n\n\n\\section{Detailed results for svm-lin}\n\n\n\\subsection{Results}\n\n\\begin{table}[!htp]\n\\centering\\small\n\\begin{tabular}{\n|c|c|c|c|c|}\n\\hline\n VS & $R^{+}$ & $R^{-}$ & Exact P-value & Asymptotic P-value \\\\ \\hline \nno-features & 216.0 & 280.0 & $\\geq$ 0.2 & 1\\\\ \\hline \nfeatures & 216.0 & 280.0 & $\\geq$ 0.2 & 1\\\\ \\hline \nvoting & 117.0 & 379.0 & $\\geq$ 0.2 & 1\\\\ \\hline \nbagging & 248.0 & 248.0 & $\\geq$ 0.2 & 0.992182\\\\ \\hline \nsvm-rbf & 88.5 & 376.5 & $\\geq$ 0.2 & 1\\\\ \\hline \nknn3 & 88.5 & 376.5 & $\\geq$ 0.2 & 1\\\\ \\hline \nknn5 & 316.0 & 180.0 & 0.18866 & 0.179478\\\\ \\hline \nmlp & 309.0 & 187.0 & $\\geq$ 0.2 & 0.228131\\\\ \\hline \n\n\\end{tabular}\n\\caption{Results obtained by the Wilcoxon test for algorithm svm-lin}\n\\end{table}\n\n\\subsection{Confidence intervals for Median of diferences}\n\n\\begin{table}[!htp]\n\\centering\\small\n\\begin{tabular}{\n|c|c|c|}\n\\hline\n $\\alpha$=0.90 & Confidence interval & Exact confidence \\\\ \\hline \nno-features & [-0.03584 , 0.01249] & 0.90182\\\\ \\hline \nfeatures & [-0.038649 , 0.012311] & 0.90182\\\\ \\hline \nvoting & [-0.038727 , -0.003494] & 0.90182\\\\ \\hline \nbagging & [-0.029622 , 0.016785] & 0.90182\\\\ \\hline \nsvm-rbf & [-0.045601 , -0.006963] & 0.90182\\\\ \\hline \nknn3 & [-0.045601 , -0.006963] & 0.90182\\\\ \\hline \nknn5 & [-0.012359 , 0.029786] & 0.90182\\\\ \\hline \nmlp & [-0.008037 , 0.02484] & 0.90182\\\\ \\hline \n\n\\end{tabular}\n\\caption{Confidence intervals for algorithm svm-lin ($\\alpha$=0.90)}\n\\end{table}\n\\begin{table}[!htp]\n\\centering\\small\n\\begin{tabular}{\n|c|c|c|}\n\\hline\n $\\alpha$=0.95 & Confidence interval & Exact confidence \\\\ \\hline \nno-features & [-0.044271 , 0.015173] & 0.9521\\\\ \\hline \nfeatures & [-0.045676 , 0.015417] & 0.9521\\\\ \\hline \nvoting & [-0.049373 , -0.002014] & 0.9521\\\\ \\hline \nbagging & [-0.035137 , 0.019752] & 0.9521\\\\ \\hline \nsvm-rbf & [-0.048474 , -0.005111] & 0.9521\\\\ \\hline \nknn3 & [-0.048474 , -0.005111] & 0.9521\\\\ \\hline \nknn5 & [-0.029511 , 0.032364] & 0.9521\\\\ \\hline \nmlp & [-0.014593 , 0.026545] & 0.9521\\\\ \\hline \n\n\\end{tabular}\n\\caption{Confidence intervals for algorithm svm-lin ($\\alpha$=0.95)}\n\\end{table}\n\n \\clearpage \n\n\n\\section{Detailed results for svm-rbf}\n\n\n\\subsection{Results}\n\n\\begin{table}[!htp]\n\\centering\\small\n\\begin{tabular}{\n|c|c|c|c|c|}\n\\hline\n VS & $R^{+}$ & $R^{-}$ & Exact P-value & Asymptotic P-value \\\\ \\hline \nno-features & 306.0 & 159.0 & 0.13474 & 0.127995\\\\ \\hline \nfeatures & 294.0 & 171.0 & $\\geq$ 0.2 & 0.202225\\\\ \\hline \nvoting & 270.0 & 195.0 & $\\geq$ 0.2 & 0.434452\\\\ \\hline \nbagging & 357.0 & 139.0 & 0.03212 & 0.031887\\\\ \\hline \nsvm-lin & 376.5 & 88.5 & 0.0022779999999999996 & 0.002957\\\\ \\hline \nknn3 & 232.5 & 232.5 & $\\geq$ 0.2 & 0.991795\\\\ \\hline \nknn5 & 457.0 & 39.0 & 7.006E-6 & 0.00004\\\\ \\hline \nmlp & 472.0 & 24.0 & 7.096E-7 & 0.000011\\\\ \\hline \n\n\\end{tabular}\n\\caption{Results obtained by the Wilcoxon test for algorithm svm-rbf}\n\\end{table}\n\n\\subsection{Confidence intervals for Median of diferences}\n\n\\begin{table}[!htp]\n\\centering\\small\n\\begin{tabular}{\n|c|c|c|}\n\\hline\n $\\alpha$=0.90 & Confidence interval & Exact confidence \\\\ \\hline \nno-features & [-0.001238 , 0.025688] & 0.90182\\\\ \\hline \nfeatures & [-0.003499 , 0.025331] & 0.90182\\\\ \\hline \nvoting & [-0.002286 , 0.007311] & 0.90182\\\\ \\hline \nbagging & [0.005666 , 0.027765] & 0.90182\\\\ \\hline \nsvm-lin & [0.006963 , 0.045601] & 0.90182\\\\ \\hline \nknn3 & [0 , 0] & 0.90182\\\\ \\hline \nknn5 & [0.02428 , 0.049381] & 0.90182\\\\ \\hline \nmlp & [0.024474 , 0.04485] & 0.90182\\\\ \\hline \n\n\\end{tabular}\n\\caption{Confidence intervals for algorithm svm-rbf ($\\alpha$=0.90)}\n\\end{table}\n\\begin{table}[!htp]\n\\centering\\small\n\\begin{tabular}{\n|c|c|c|}\n\\hline\n $\\alpha$=0.95 & Confidence interval & Exact confidence \\\\ \\hline \nno-features & [-0.004204 , 0.027805] & 0.9521\\\\ \\hline \nfeatures & [-0.005656 , 0.027915] & 0.9521\\\\ \\hline \nvoting & [-0.003289 , 0.008866] & 0.9521\\\\ \\hline \nbagging & [0.002545 , 0.03042] & 0.9521\\\\ \\hline \nsvm-lin & [0.005111 , 0.048474] & 0.9521\\\\ \\hline \nknn3 & [0 , 0] & 0.9521\\\\ \\hline \nknn5 & [0.021493 , 0.0517] & 0.9521\\\\ \\hline \nmlp & [0.021698 , 0.046523] & 0.9521\\\\ \\hline \n\n\\end{tabular}\n\\caption{Confidence intervals for algorithm svm-rbf ($\\alpha$=0.95)}\n\\end{table}\n\n \\clearpage \n\n\n\\section{Detailed results for knn3}\n\n\n\\subsection{Results}\n\n\\begin{table}[!htp]\n\\centering\\small\n\\begin{tabular}{\n|c|c|c|c|c|}\n\\hline\n VS & $R^{+}$ & $R^{-}$ & Exact P-value & Asymptotic P-value \\\\ \\hline \nno-features & 306.0 & 159.0 & 0.13474 & 0.127995\\\\ \\hline \nfeatures & 294.0 & 171.0 & $\\geq$ 0.2 & 0.202225\\\\ \\hline \nvoting & 270.0 & 195.0 & $\\geq$ 0.2 & 0.434452\\\\ \\hline \nbagging & 357.0 & 139.0 & 0.03212 & 0.031887\\\\ \\hline \nsvm-lin & 376.5 & 88.5 & 0.0022779999999999996 & 0.002957\\\\ \\hline \nsvm-rbf & 232.5 & 232.5 & $\\geq$ 0.2 & 0.991795\\\\ \\hline \nknn5 & 457.0 & 39.0 & 7.006E-6 & 0.00004\\\\ \\hline \nmlp & 472.0 & 24.0 & 7.096E-7 & 0.000011\\\\ \\hline \n\n\\end{tabular}\n\\caption{Results obtained by the Wilcoxon test for algorithm knn3}\n\\end{table}\n\n\\subsection{Confidence intervals for Median of diferences}\n\n\\begin{table}[!htp]\n\\centering\\small\n\\begin{tabular}{\n|c|c|c|}\n\\hline\n $\\alpha$=0.90 & Confidence interval & Exact confidence \\\\ \\hline \nno-features & [-0.001238 , 0.025688] & 0.90182\\\\ \\hline \nfeatures & [-0.003499 , 0.025331] & 0.90182\\\\ \\hline \nvoting & [-0.002286 , 0.007311] & 0.90182\\\\ \\hline \nbagging & [0.005666 , 0.027765] & 0.90182\\\\ \\hline \nsvm-lin & [0.006963 , 0.045601] & 0.90182\\\\ \\hline \nsvm-rbf & [0 , 0] & 0.90182\\\\ \\hline \nknn5 & [0.02428 , 0.049381] & 0.90182\\\\ \\hline \nmlp & [0.024474 , 0.04485] & 0.90182\\\\ \\hline \n\n\\end{tabular}\n\\caption{Confidence intervals for algorithm knn3 ($\\alpha$=0.90)}\n\\end{table}\n\\begin{table}[!htp]\n\\centering\\small\n\\begin{tabular}{\n|c|c|c|}\n\\hline\n $\\alpha$=0.95 & Confidence interval & Exact confidence \\\\ \\hline \nno-features & [-0.004204 , 0.027805] & 0.9521\\\\ \\hline \nfeatures & [-0.005656 , 0.027915] & 0.9521\\\\ \\hline \nvoting & [-0.003289 , 0.008866] & 0.9521\\\\ \\hline \nbagging & [0.002545 , 0.03042] & 0.9521\\\\ \\hline \nsvm-lin & [0.005111 , 0.048474] & 0.9521\\\\ \\hline \nsvm-rbf & [0 , 0] & 0.9521\\\\ \\hline \nknn5 & [0.021493 , 0.0517] & 0.9521\\\\ \\hline \nmlp & [0.021698 , 0.046523] & 0.9521\\\\ \\hline \n\n\\end{tabular}\n\\caption{Confidence intervals for algorithm knn3 ($\\alpha$=0.95)}\n\\end{table}\n\n \\clearpage \n\n\n\\section{Detailed results for knn5}\n\n\n\\subsection{Results}\n\n\\begin{table}[!htp]\n\\centering\\small\n\\begin{tabular}{\n|c|c|c|c|c|}\n\\hline\n VS & $R^{+}$ & $R^{-}$ & Exact P-value & Asymptotic P-value \\\\ \\hline \nno-features & 107.0 & 389.0 & $\\geq$ 0.2 & 1\\\\ \\hline \nfeatures & 103.0 & 393.0 & $\\geq$ 0.2 & 1\\\\ \\hline \nvoting & 14.0 & 482.0 & $\\geq$ 0.2 & 1\\\\ \\hline \nbagging & 113.0 & 383.0 & $\\geq$ 0.2 & 1\\\\ \\hline \nsvm-lin & 180.0 & 316.0 & $\\geq$ 0.2 & 1\\\\ \\hline \nsvm-rbf & 39.0 & 457.0 & $\\geq$ 0.2 & 1\\\\ \\hline \nknn3 & 39.0 & 457.0 & $\\geq$ 0.2 & 1\\\\ \\hline \nmlp & 167.0 & 298.0 & $\\geq$ 0.2 & 1\\\\ \\hline \n\n\\end{tabular}\n\\caption{Results obtained by the Wilcoxon test for algorithm knn5}\n\\end{table}\n\n\\subsection{Confidence intervals for Median of diferences}\n\n\\begin{table}[!htp]\n\\centering\\small\n\\begin{tabular}{\n|c|c|c|}\n\\hline\n $\\alpha$=0.90 & Confidence interval & Exact confidence \\\\ \\hline \nno-features & [-0.036948 , -0.008587] & 0.90182\\\\ \\hline \nfeatures & [-0.037489 , -0.009214] & 0.90182\\\\ \\hline \nvoting & [-0.041694 , -0.022858] & 0.90182\\\\ \\hline \nbagging & [-0.036183 , -0.008017] & 0.90182\\\\ \\hline \nsvm-lin & [-0.029786 , 0.012359] & 0.90182\\\\ \\hline \nsvm-rbf & [-0.049381 , -0.02428] & 0.90182\\\\ \\hline \nknn3 & [-0.049381 , -0.02428] & 0.90182\\\\ \\hline \nmlp & [-0.01 , 0.000999] & 0.90182\\\\ \\hline \n\n\\end{tabular}\n\\caption{Confidence intervals for algorithm knn5 ($\\alpha$=0.90)}\n\\end{table}\n\\begin{table}[!htp]\n\\centering\\small\n\\begin{tabular}{\n|c|c|c|}\n\\hline\n $\\alpha$=0.95 & Confidence interval & Exact confidence \\\\ \\hline \nno-features & [-0.039682 , -0.006451] & 0.9521\\\\ \\hline \nfeatures & [-0.041708 , -0.006989] & 0.9521\\\\ \\hline \nvoting & [-0.044465 , -0.021008] & 0.9521\\\\ \\hline \nbagging & [-0.038597 , -0.006602] & 0.9521\\\\ \\hline \nsvm-lin & [-0.032364 , 0.029511] & 0.9521\\\\ \\hline \nsvm-rbf & [-0.0517 , -0.021493] & 0.9521\\\\ \\hline \nknn3 & [-0.0517 , -0.021493] & 0.9521\\\\ \\hline \nmlp & [-0.011054 , 0.002555] & 0.9521\\\\ \\hline \n\n\\end{tabular}\n\\caption{Confidence intervals for algorithm knn5 ($\\alpha$=0.95)}\n\\end{table}\n\n \\clearpage \n\n\n\\section{Detailed results for mlp}\n\n\n\\subsection{Results}\n\n\\begin{table}[!htp]\n\\centering\\small\n\\begin{tabular}{\n|c|c|c|c|c|}\n\\hline\n VS & $R^{+}$ & $R^{-}$ & Exact P-value & Asymptotic P-value \\\\ \\hline \nno-features & 105.0 & 360.0 & $\\geq$ 0.2 & 1\\\\ \\hline \nfeatures & 122.0 & 374.0 & $\\geq$ 0.2 & 1\\\\ \\hline \nvoting & 6.0 & 490.0 & $\\geq$ 0.2 & 1\\\\ \\hline \nbagging & 141.0 & 355.0 & $\\geq$ 0.2 & 1\\\\ \\hline \nsvm-lin & 187.0 & 309.0 & $\\geq$ 0.2 & 1\\\\ \\hline \nsvm-rbf & 24.0 & 472.0 & $\\geq$ 0.2 & 1\\\\ \\hline \nknn3 & 24.0 & 472.0 & $\\geq$ 0.2 & 1\\\\ \\hline \nknn5 & 298.0 & 167.0 & 0.18396 & 0.174619\\\\ \\hline \n\n\\end{tabular}\n\\caption{Results obtained by the Wilcoxon test for algorithm mlp}\n\\end{table}\n\n\\subsection{Confidence intervals for Median of diferences}\n\n\\begin{table}[!htp]\n\\centering\\small\n\\begin{tabular}{\n|c|c|c|}\n\\hline\n $\\alpha$=0.90 & Confidence interval & Exact confidence \\\\ \\hline \nno-features & [-0.035931 , -0.007629] & 0.90182\\\\ \\hline \nfeatures & [-0.037251 , -0.008169] & 0.90182\\\\ \\hline \nvoting & [-0.037243 , -0.022108] & 0.90182\\\\ \\hline \nbagging & [-0.032056 , -0.003571] & 0.90182\\\\ \\hline \nsvm-lin & [-0.02484 , 0.008037] & 0.90182\\\\ \\hline \nsvm-rbf & [-0.04485 , -0.024474] & 0.90182\\\\ \\hline \nknn3 & [-0.04485 , -0.024474] & 0.90182\\\\ \\hline \nknn5 & [-0.000999 , 0.01] & 0.90182\\\\ \\hline \n\n\\end{tabular}\n\\caption{Confidence intervals for algorithm mlp ($\\alpha$=0.90)}\n\\end{table}\n\\begin{table}[!htp]\n\\centering\\small\n\\begin{tabular}{\n|c|c|c|}\n\\hline\n $\\alpha$=0.95 & Confidence interval & Exact confidence \\\\ \\hline \nno-features & [-0.039409 , -0.004637] & 0.9521\\\\ \\hline \nfeatures & [-0.040127 , -0.004317] & 0.9521\\\\ \\hline \nvoting & [-0.039383 , -0.020545] & 0.9521\\\\ \\hline \nbagging & [-0.03602 , -0.001184] & 0.9521\\\\ \\hline \nsvm-lin & [-0.026545 , 0.014593] & 0.9521\\\\ \\hline \nsvm-rbf & [-0.046523 , -0.021698] & 0.9521\\\\ \\hline \nknn3 & [-0.046523 , -0.021698] & 0.9521\\\\ \\hline \nknn5 & [-0.002555 , 0.011054] & 0.9521\\\\ \\hline \n\n\\end{tabular}\n\\caption{Confidence intervals for algorithm mlp ($\\alpha$=0.95)}\n\\end{table}\n\n \\clearpage \n\n\n\\end{document}", "meta": {"hexsha": "7dd043f1ffa7583e92e6245aca88515ca8f4034c", "size": 19014, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "wilcoxnew.tex", "max_stars_repo_name": "olafkrawczyk/praca-magisterska", "max_stars_repo_head_hexsha": "ae0ba39cde1f9b8ec15d693ca9954d5e5aa033ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "wilcoxnew.tex", "max_issues_repo_name": "olafkrawczyk/praca-magisterska", "max_issues_repo_head_hexsha": "ae0ba39cde1f9b8ec15d693ca9954d5e5aa033ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wilcoxnew.tex", "max_forks_repo_name": "olafkrawczyk/praca-magisterska", "max_forks_repo_head_hexsha": "ae0ba39cde1f9b8ec15d693ca9954d5e5aa033ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3245469522, "max_line_length": 73, "alphanum_fraction": 0.6235405491, "num_tokens": 8567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.30817089151971566}}
{"text": "\n\\subsection{Omitted variable bias}\n\nIf the producer sees customer characteristics we do not, then there will be a bias in our estimate.\n\nProducers will set prices correlated with those characteristics.\n\n", "meta": {"hexsha": "79a16756583db50b56f840617fe956cf0f08ddfe", "size": 204, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/pug/theory/economics/econometricsDiscrete/01-03-discreteEstimationOmitted.tex", "max_stars_repo_name": "adamdboult/nodeHomePage", "max_stars_repo_head_hexsha": "266bfc6865bb8f6b1530499dde3aa6206bb09b93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pug/theory/economics/econometricsDiscrete/01-03-discreteEstimationOmitted.tex", "max_issues_repo_name": "adamdboult/nodeHomePage", "max_issues_repo_head_hexsha": "266bfc6865bb8f6b1530499dde3aa6206bb09b93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-03-03T12:36:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-01T22:16:09.000Z", "max_forks_repo_path": "src/pug/theory/economics/econometricsDiscrete/01-03-discreteEstimationOmitted.tex", "max_forks_repo_name": "adamdboult/nodeHomePage", "max_forks_repo_head_hexsha": "266bfc6865bb8f6b1530499dde3aa6206bb09b93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5, "max_line_length": 99, "alphanum_fraction": 0.8088235294, "num_tokens": 39, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.30817088465220877}}
{"text": "\\chapter{Bytevectors}\n\\label{bytevectorschapter}\n\nMany applications deal with blocks of binary data by accessing\nthem in various ways---extracting signed or unsigned numbers of\nvarious sizes.  Therefore, the \\defrsixlibrary{bytevectors} library\nprovides a single type for\nblocks of binary data with multiple ways to access that data. It deals\nwith integers and floating-point representations \nin various sizes with specified endianness.\n\nBytevectors\\mainindex{bytevector} are objects of a disjoint\ntype. Conceptually, a bytevector represents a sequence of 8-bit\nbytes.  The description of bytevectors uses the term \\defining{byte}\nfor an exact integer object in the interval $\\{-128, \\ldots, 127\\}$ and the\nterm \\defining{octet} for an exact integer object in the interval $\\{0,\n\\ldots, 255\\}$.  A byte corresponds to its two's complement\nrepresentation as an octet.\n\nThe length of a bytevector is the number of bytes it contains. This\nnumber is fixed. A valid index into a bytevector is an exact,\nnon-negative integer object less than the length of the bytevector.\nThe first byte of a bytevector has index 0;\nthe last byte has an index one less than the length of the bytevector.\n\nGenerally, the access procedures come in different flavors according\nto the size of the represented integer and the endianness of the\nrepresentation.  The procedures also distinguish signed and unsigned\nrepresentations.\nThe signed representations all use two's complement.\n\nLike string literals, literals representing bytevectors do not need to\nbe quoted:\n%\n\\begin{scheme}\n\\#vu8(12 23 123) \\ev \\#vu8(12 23 123)%\n\\end{scheme}\n\n\\section{Endianness}\n\nMany operations described in this chapter accept an\n\\defining{endianness} argument.  Endianness describes the encoding of\nexact integer objects as several contiguous bytes in a bytevector~\\cite{IEN137}. \nFor this purpose, the binary representation of the integer object is split into\nconsecutive bytes.  \\mainindex{little-endian}The little-endian\nencoding places the least significant byte of an integer first, with\nthe other bytes following in increasing order of significance.\n\\mainindex{big-endian}The big-endian encoding places the most\nsignificant byte of an integer first, with the other bytes following\nin decreasing order of significance. \n\nThis terminology also applies to IEEE-754 numbers: IEEE~754 describes\nhow to represent a floating-point number as an exact integer object, and\nendianness describes how the bytes of such an integer are laid out in\na bytevector.\n\n\\begin{note}\n  Little- and big-endianness are only the most common kinds of\n  endianness.  Some architectures distinguish between the endianness\n  at different levels of a binary representation.\n\\end{note}\n\n\\section{General operations}\n\n\\begin{entry}{%\n\\proto{endianness}{ \\hyper{endianness symbol}}{\\exprtype}}\n\n\\domain{The name of \\hyper{endianness symbol} must be a symbol describing an\n  endianness.  An implementation must support at least the symbols\n  {\\cf big} and {\\cf little}, but may support other endianness\n  symbols.}  {\\cf (endianness \\hyper{endianness symbol})} evaluates to\nthe symbol named \\hyper{endianness symbol}.  Whenever one of the\nprocedures operating on bytevectors accepts an endianness as an\nargument, that argument must be one of these symbols.  It is a syntax\nviolation for \\hyper{endianness symbol} to be anything other than an\nendianness symbol supported by the implementation.\n\n\\begin{note}\n  Implementors should use widely accepted designations\n  for endianness symbols other than {\\cf big} and {\\cf little}.\n\\end{note}\n\n\\begin{note}\n  Only the name of \\hyper{endianness symbol} is significant.\n\\end{note}\n\\end{entry}\n\n\\begin{entry}{%\n\\proto{native-endianness}{}{procedure}}\n\nReturns the endianness symbol associated implementation's preferred\nendianness (usually that of the underlying machine architecture).\nThis may be any \\hyper{endianness symbol}, including a symbol other\nthan {\\cf big} and {\\cf little}.\n\\end{entry}   \n\n\\begin{entry}{%\n\\proto{bytevector?}{ obj}{procedure}}\n   \nReturns \\schtrue{} if \\var{obj} is a bytevector,\notherwise returns \\schfalse{}.\n\\end{entry}\n\n\\begin{entry}{%\n\\proto{make-bytevector}{ k}{procedure}\n\\rproto{make-bytevector}{ k fill}{procedure}}\n   \nReturns a newly allocated bytevector of \\var{k} bytes.\n   \nIf the \\var{fill} argument is missing, the initial contents of the\nreturned bytevector are unspecified.\n   \nIf the \\var{fill} argument is present, it must be an exact integer\nobject in\nthe interval $\\{-128, \\ldots 255\\}$ that specifies the initial value\nfor the bytes of the bytevector: If \\var{fill} is positive, it is\ninterpreted as an octet; if it is negative, it is interpreted as a byte.\n\\end{entry}   \n\n\\begin{entry}{%\n\\proto{bytevector-length}{ bytevector}{procedure}}\n   \nReturns, as an exact integer object, the number of bytes in \\var{bytevector}.\n\\end{entry}\n\n\\begin{entry}{%\n\\proto{bytevector=?}{ \\vari{bytevector} \\varii{bytevector}}{procedure}}\n   \nReturns \\schtrue{} if \\vari{bytevector} and \\varii{bytevector} are equal---that\nis, if they have the same length and equal bytes at all valid indices.\nIt returns \\schfalse{} otherwise.\n\\end{entry}\n\n\\begin{entry}{%\n\\proto{bytevector-fill!}{ bytevector fill}{procedure}}\n\n\\domain{The \\var{fill} argument is as in the description of the {\\cf\n    make-bytevector} procedure.}\nThe {\\cf bytevector-fill!} procedure stores \\var{fill} in every element of \\var{bytevector}\nand returns \\unspecifiedreturn.  Analogous to {\\cf vector-fill!}.\n\\end{entry}\n\n\\begin{entry}{%\n\\pproto{(bytevector-copy! \\var{source} \\var{source-start}}{procedure}}\n\\mainschindex{bytevector-copy!}{\\tt\\obeyspaces\\\\\n     \\var{target} \\var{target-start} \\var{k})}\n\n\\domain{\\var{Source} and \\var{target} must be bytevectors.\n  \\var{Source-start}, \\var{target-start},\n  and \\var{k} must be non-negative exact integer objects that satisfy\n  \n  \\begin{displaymath}\n    \\begin{array}{rcccccl}\n      0 & \\leq & \\var{source-start} & \\leq & \\var{source-start} + \\var{k} & \\leq & l_{\\var{source}}\n      \\\\\n      0 & \\leq & \\var{target-start} & \\leq & \\var{target-start} + \\var{k} & \\leq & l_{\\var{target}}\n    \\end{array}\n  \\end{displaymath}\n  %\n  where $l_{\\var{source}}$ is the length of \\var{source} and\n  $l_{\\var{target}}$ is the length of \\var{target}.}\n   \n   \n  The {\\cf bytevector-copy!} procedure copies the bytes from \\var{source} at indices \n  \\begin{displaymath}\n     \\var{source-start}, \\ldots, \\var{source-start} + \\var{k} - 1\n  \\end{displaymath}\n  to consecutive indices in \\var{target} starting at \\var{target-index}.\n   \n  This must work even if the memory regions for the source and the target\n  overlap, i.e., the bytes at the target location after the copy must be\n  equal to the bytes at the source location before the copy.\n   \n  This returns \\unspecifiedreturn.\n\\begin{scheme}\n(let ((b (u8-list->bytevector '(1 2 3 4 5 6 7 8))))\n  (bytevector-copy! b 0 b 3 4)\n  (bytevector->u8-list b)) \\ev (1 2 3 1 2 3 4 8)%\n\\end{scheme}\n\\end{entry}\n\n\\begin{entry}{%\n\\proto{bytevector-copy}{ bytevector}{procedure}}\n   \nReturns a newly allocated copy of \\var{bytevector}.\n\\end{entry}\n\n\\section{Operations on bytes and octets}\n\n\\begin{entry}{%\n\\proto{bytevector-u8-ref}{ bytevector k}{procedure}\n\\proto{bytevector-s8-ref}{ bytevector k}{procedure}}\n   \n\\domain{\\var{K} must be a valid index of \\var{bytevector}.}\n   \nThe {\\cf bytevector-u8-ref} procedure returns the byte at index \\var{k} of \\var{bytevector},\nas an octet.\n   \nThe {\\cf bytevector-s8-ref} procedure returns the byte at index \\var{k} of \\var{bytevector},\nas a (signed) byte.\n\n\\begin{scheme}\n(let ((b1 (make-bytevector 16 -127))\n      (b2 (make-bytevector 16 255)))\n  (list\n    (bytevector-s8-ref b1 0)\n    (bytevector-u8-ref b1 0)\n    (bytevector-s8-ref b2 0)\n    (bytevector-u8-ref b2 0))) \\lev (-127 129 -1 255)%\n\\end{scheme}\n\\end{entry}   \n\n\\begin{entry}{%\n\\proto{bytevector-u8-set!}{ bytevector k octet}{procedure}\n\\proto{bytevector-s8-set!}{ bytevector k byte}{procedure}}\n   \n\\domain{\\var{K} must be a valid index of \\var{bytevector}.}\n   \nThe {\\cf bytevector-u8-set!} procedure stores \\var{octet} in element \\var{k} of\n\\var{bytevector}.\n   \nThe {\\cf bytevector-s8-set!} procedure stores the two's-complement representation of\n\\var{byte} in element \\var{k} of \\var{bytevector}.\n   \nBoth procedures return \\unspecifiedreturn.\n\n\\begin{scheme}\n(let ((b (make-bytevector 16 -127)))\n\n  (bytevector-s8-set! b 0 -126)\n  (bytevector-u8-set! b 1 246)\n\n  (list\n    (bytevector-s8-ref b 0)\n    (bytevector-u8-ref b 0)\n    (bytevector-s8-ref b 1)\n    (bytevector-u8-ref b 1))) \\lev (-126 130 -10 246)%\n\\end{scheme}\n\\end{entry}\n\n\\begin{entry}{%\n\\proto{bytevector->u8-list}{ bytevector}{procedure}\n\\proto{u8-list->bytevector}{ list}{procedure}}\n   \n\\domain{\\var{List} must be a list of octets.}\n\nThe {\\cf bytevector->u8-list} procedure returns a newly allocated list of the octets of\n\\var{bytevector} in the same order.\n\nThe {\\cf u8-list->bytevector} procedure returns a newly allocated bytevector whose\nelements are the elements of list \\var{list}, in\nthe same order.  It is analogous to {\\cf list->vector}.\n\\end{entry}\n\n\\section{Operations on integers of arbitrary size}\n\n\\begin{entry}{%\n\\proto{bytevector-uint-ref}{ bytevector k endianness size}{procedure}\n\\proto{bytevector-sint-ref}{ bytevector k endianness size}{procedure}\n\\proto{bytevector-uint-set!}{ bytevector k n endianness size}{procedure}\n\\proto{bytevector-sint-set!}{ bytevector k n endianness size}{procedure}}\n   \n\\domain{\\var{Size} must be a positive exact integer object. $\\var{K}, \\ldots,\n  \\var{k} + \\var{size} - 1$ must be valid indices of \\var{bytevector}.}\n   \nThe {\\cf bytevector-uint-ref} procedure retrieves the exact integer object corresponding to the\nunsigned representation of size \\var{size} and specified by \\var{endianness}\nat indices $\\var{k}, \\ldots, \\var{k} + \\var{size} - 1$.\n   \nThe {\\cf bytevector-sint-ref} procedure retrieves the exact integer object corresponding to the two's-complement representation of size \\var{size} and specified by \\var{endianness} at\nindices $\\var{k}, \\ldots, \\var{k} + \\var{size} - 1$.\n   \n\\domain{For {\\cf bytevector-uint-set!}, \\var{n} must be an exact\n  integer object in the interval $\\{0, \\ldots, 256^{\\mathit{size}}-1\\}$.}\n\nThe {\\cf bytevector-uint-set!} procedure stores the unsigned representation of size \\var{size}\nand specified by \\var{endianness} into \\var{bytevector} at indices\n$\\var{k}, \\ldots, \\var{k} + \\var{size} - 1$.\n   \n\\domain{For {\\cf bytevector-sint-set!}, \\var{n} must be an exact\n  integer object in\n  the interval $\\{-256^{\\mathit{size}}/2, \\ldots,\n  256^{\\mathit{size}}/2-1\\}$.}\n{\\cf bytevector-sint-set!} stores the two's-complement\nrepresentation of size \\var{size} and specified by \\var{endianness}\ninto \\var{bytevector} at indices $\\var{k}, \\ldots, \\var{k} + \\var{size} - 1$.\n   \nThe \\ldots{\\cf -set!} procedures return \\unspecifiedreturn.\n\n\\begin{scheme}\n(define b (make-bytevector 16 -127))\n\n(bytevector-uint-set! b 0 (- (expt 2 128) 3)\n                     (endianness little) 16)\n\n(bytevector-uint-ref b 0 (endianness little) 16)\\lev\n    \\#xfffffffffffffffffffffffffffffffd\n\n(bytevector-sint-ref b 0 (endianness little) 16)\\lev -3\n\n(bytevector->u8-list b)\\lev (253 255 255 255 255 255 255 255\n               255 255 255 255 255 255 255 255)\n\n(bytevector-uint-set! b 0 (- (expt 2 128) 3)\n                 (endianness big) 16)\n(bytevector-uint-ref b 0 (endianness big) 16) \\lev\n    \\#xfffffffffffffffffffffffffffffffd\n\n(bytevector-sint-ref b 0 (endianness big) 16) \\lev -3\n\n(bytevector->u8-list b) \\lev (255 255 255 255 255 255 255 255\n               255 255 255 255 255 255 255 253))%\n\\end{scheme}\n\\end{entry}\n\n\\begin{entry}{%\n\\proto{bytevector->uint-list}{ bytevector endianness size}{procedure}\n\\proto{bytevector->sint-list}{ bytevector endianness size}{procedure}\n\\proto{uint-list->bytevector}{ list endianness size}{procedure}\n\\proto{sint-list->bytevector}{ list endianness size}{procedure}}\n   \n\\domain{\\var{Size} must be a positive exact integer object.  For {\\cf\n    uint-list->bytevector}, \\var{list} must be a list of exact\n  integer objects in the interval $\\{0, \\ldots, 256^{\\mathit{size}}-1\\}$.  For\n  {\\cf sint-list->bytevector}, \\var{list} must be a list of exact\n  integer objects in the interval $\\{-256^{\\mathit{size}}/2, \\ldots,\n  256^{\\mathit{size}}/2-1\\}$.  The length of \\var{bytevector} \n  must be divisible by \\var{size}.}\n   \nThese procedures convert between lists of integer objects and their consecutive\nrepresentations according to \\var{size} and \\var{endianness} in the\n\\var{bytevector} objects in the same way as {\\cf bytevector->u8-list} and {\\cf\n  u8-list->bytevector} do for one-byte representations.\n\n\\begin{scheme}\n(let ((b (u8-list->bytevector '(1 2 3 255 1 2 1 2))))\n  (bytevector->sint-list b (endianness little) 2)) \\lev (513 -253 513 513)\n\n(let ((b (u8-list->bytevector '(1 2 3 255 1 2 1 2))))\n  (bytevector->uint-list b (endianness little) 2)) \\lev (513 65283 513 513)%\n\\end{scheme}\n\\end{entry}\n\n\\section{Operations on 16-bit integers}\n\n\\begin{entry}{%\n\\proto{bytevector-u16-ref}{ bytevector k endianness}{procedure}\n\\proto{bytevector-s16-ref}{ bytevector k endianness}{procedure}\n\\proto{bytevector-u16-native-ref}{ bytevector k}{procedure}\n\\proto{bytevector-s16-native-ref}{ bytevector k}{procedure}\n\\proto{bytevector-u16-set!}{ bytevector k n endianness}{procedure}\n\\proto{bytevector-s16-set!}{ bytevector k n endianness}{procedure}\n\\proto{bytevector-u16-native-set!}{ bytevector k n}{procedure}\n\\proto{bytevector-s16-native-set!}{ bytevector k n}{procedure}}\n   \n\\domain{\\var{K} must be a valid index of \\var{bytevector}; so must\n  $\\var{k} + 1$. For {\\cf bytevector-u16-set!} and {\\cf\n    bytevector-\\hp{}u16-native-\\hp{}set!}, \\var{n} must be an exact integer object in\n  the interval $\\{0, \\ldots, 2^{16}-1\\}$.  For {\\cf bytevector-s16-set!}\n  and {\\cf bytevector-s16-native-set!}, \\var{n} must be an exact\n  integer object in the interval $\\{-2^{15}, \\ldots, 2^{15}-1\\}$.}\n   \nThese retrieve and set two-byte representations of numbers at indices\n\\var{k} and $\\var{k}+1$, according to the endianness specified by\n\\var{endianness}. The procedures with {\\cf u16} in their names deal with the\nunsigned representation; those with {\\cf s16} in their names deal\nwith the two's-complement representation.\n\nThe procedures with {\\cf native} in their names employ the native\nendianness, and work only at aligned indices:\n\\var{k} must be a multiple of 2.\n   \nThe \\ldots{\\cf -set!} procedures return \\unspecifiedreturn.\n\n\\begin{scheme}\n(define b\n  (u8-list->bytevector\n    '(255 255 255 255 255 255 255 255\n      255 255 255 255 255 255 255 253)))\n\n(bytevector-u16-ref b 14 (endianness little)) \\lev 65023\n(bytevector-s16-ref b 14 (endianness little)) \\lev -513\n(bytevector-u16-ref b 14 (endianness big)) \\lev 65533\n(bytevector-s16-ref b 14 (endianness big)) \\lev -3\n\n(bytevector-u16-set! b 0 12345 (endianness little))\n(bytevector-u16-ref b 0 (endianness little)) \\lev 12345\n\n(bytevector-u16-native-set! b 0 12345)\n(bytevector-u16-native-ref b 0) \\ev 12345\n\n(bytevector-u16-ref b 0 (endianness little)) \\lev \\unspecified%\n\\end{scheme}\n\\end{entry}\n\n\\section{Operations on 32-bit integers}\n\n\\begin{entry}{%\n\\proto{bytevector-u32-ref}{ bytevector k endianness}{procedure}\n\\proto{bytevector-s32-ref}{ bytevector k endianness}{procedure}\n\\proto{bytevector-u32-native-ref}{ bytevector k}{procedure}\n\\proto{bytevector-s32-native-ref}{ bytevector k}{procedure}\n\\proto{bytevector-u32-set!}{ bytevector k n endianness}{procedure}\n\\proto{bytevector-s32-set!}{ bytevector k n endianness}{procedure}\n\\proto{bytevector-u32-native-set!}{ bytevector k n}{procedure}\n\\proto{bytevector-s32-native-set!}{ bytevector k n}{procedure}}\n   \n\\domain{$\\var{K}, \\ldots, \\var{k}+ 3$ must be valid indices of\n  \\var{bytevector}.\n  For {\\cf bytevector-u32-set!} and {\\cf\n    bytevector-\\hp{}u32-\\hp{}native-\\hp{}set!}, \\var{n} must be an exact integer\n  object in\n  the interval $\\{0, \\ldots, 2^{32}-1\\}$.  For {\\cf bytevector-s32-set!}\n  and {\\cf bytevector-s32-native-set!}, \\var{n} must be an exact\n  integer object in the interval $\\{-2^{31}, \\ldots, 2^{31}-1\\}$.}\n   \nThese retrieve and set four-byte representations of numbers at indices $\\var{k},\n\\ldots, \\var{k}+ 3$, according to the endianness specified by \\var{endianness}. The\nprocedures with {\\cf u32} in their names deal with the unsigned representation;\nthose with {\\cf s32} with the two's-complement representation.\n   \nThe procedures with {\\cf native} in their names employ the native endianness, and\nwork only at aligned indices: \\var{k} must be a multiple of 4.\n   \nThe \\ldots{\\cf{}-set!} procedures return \\unspecifiedreturn.\n\n\\begin{scheme}\n(define b\n  (u8-list->bytevector\n    '(255 255 255 255 255 255 255 255\n      255 255 255 255 255 255 255 253)))\n\n(bytevector-u32-ref b 12 (endianness little)) \\lev 4261412863\n(bytevector-s32-ref b 12 (endianness little)) \\lev -33554433\n(bytevector-u32-ref b 12 (endianness big)) \\lev 4294967293\n(bytevector-s32-ref b 12 (endianness big)) \\lev -3%\n\\end{scheme}\n\\end{entry}\n\n\\section{Operations on 64-bit integers}\n\n\\begin{entry}{%\n\\proto{bytevector-u64-ref}{ bytevector k endianness}{procedure}\n\\proto{bytevector-s64-ref}{ bytevector k endianness}{procedure}\n\\proto{bytevector-u64-native-ref}{ bytevector k}{procedure}\n\\proto{bytevector-s64-native-ref}{ bytevector k}{procedure}\n\\proto{bytevector-u64-set!}{ bytevector k n endianness}{procedure}\n\\proto{bytevector-s64-set!}{ bytevector k n endianness}{procedure}\n\\proto{bytevector-u64-native-set!}{ bytevector k n}{procedure}\n\\proto{bytevector-s64-native-set!}{ bytevector k n}{procedure}}\n \n\\domain{$\\var{K}, \\ldots, \\var{k}+ 7$ must be valid indices of\n  \\var{bytevector}.\n  For {\\cf bytevector-u64-set!} and {\\cf\n    bytevector-\\hp{}u64-\\hp{}native-\\hp{}set!}, \\var{n} must be an exact integer\n  object in\n  the interval $\\{0, \\ldots, 2^{64}-1\\}$.  For {\\cf bytevector-s64-set!}\n  and {\\cf bytevector-s64-native-set!}, \\var{n} must be an exact\n  integer object in the interval $\\{-2^{63}, \\ldots, 2^{63}-1\\}$.}\n   \nThese retrieve and set eight-byte representations of numbers at\nindices $\\var{k}, \\ldots, \\var{k}+ 7$, according to the endianness\nspecified by \\var{endianness}. The procedures with {\\cf u64} in their names deal\nwith the unsigned representation; those with {\\cf s64} with the\ntwo's-complement representation.\n   \nThe procedures with {\\cf native} in their names employ the native endianness, and\nwork only at aligned indices: \\var{k} must be a multiple of 8.\n   \nThe \\ldots{\\cf{}-set!} procedures return \\unspecifiedreturn.\n\n\\begin{scheme}\n(define b\n  (u8-list->bytevector\n    '(255 255 255 255 255 255 255 255\n      255 255 255 255 255 255 255 253)))\n\n(bytevector-u64-ref b 8 (endianness little)) \\lev 18302628885633695743\n(bytevector-s64-ref b 8 (endianness little)) \\lev -144115188075855873\n(bytevector-u64-ref b 8 (endianness big)) \\lev 18446744073709551613\n(bytevector-s64-ref b 8 (endianness big)) \\lev -3%\n\\end{scheme}\n\\end{entry}\n\n\\section{Operations on IEEE-754 representations}\n\n\\begin{entry}{%\n\\proto{bytevector-ieee-single-native-ref}{ bytevector k}{procedure}\n\\proto{bytevector-ieee-single-ref}{ bytevector k endianness}{procedure}}\n\n\\domain{$\\var{K}, \\ldots, \\var{k}+3$ must be valid indices of\n  \\var{bytevector}.  For {\\cf bytevector-ieee-single-native-ref}, \\var{k} must\n  be a multiple of $4$.}\n\nThese procedures return the inexact real number object that best\nrepresents the IEEE-754 single-precision number represented by the\nfour bytes beginning at index\n\\var{k}.\n\\end{entry}\n\n\\begin{entry}{%\n\\proto{bytevector-ieee-double-native-ref}{ bytevector k}{procedure}\n\\proto{bytevector-ieee-double-ref}{ bytevector k endianness}{procedure}}\n\n\\domain{$\\var{K}, \\ldots, \\var{k}+7$ must be valid indices of\n  \\var{bytevector}.  For {\\cf bytevector-ieee-double-native-ref}, \\var{k} must\n  be a multiple of $8$.}\n\nThese procedures return the inexact real number object that best\nrepresents the IEEE-754 double-precision number represented by the\neight bytes beginning at index \\var{k}.\n\\end{entry}\n\n\\begin{entry}{%\n\\proto{bytevector-ieee-single-native-set!}{ bytevector k x}{procedure}\n\\pproto{(bytevector-ieee-single-set! \\var{bytevector}}{procedure}}\n{\\tt\\obeyspaces\\\\\n     \\var{k} \\var{x} \\var{endianness})}\n\n\\domain{$\\var{K}, \\ldots, \\var{k}+3$ must be valid indices of\n  \\var{bytevector}.  For {\\cf bytevector-ieee-single-native-set!}, \\var{k} must\n  be a multiple of $4$.}\n\nThese procedures store an IEEE-754 single-precision representation of \\var{x} into\nelements \\var{k} through $\\var{k}+3$ of \\var{bytevector}, and return\n\\unspecifiedreturn.\n\\end{entry}\n\n\\begin{entry}{%\n\\proto{bytevector-ieee-double-native-set!}{ bytevector k x}{procedure}\n\\pproto{(bytevector-ieee-double-set! \\var{bytevector}}{procedure}}\n{\\tt\\obeyspaces\\\\\n     \\var{k} \\var{x} \\var{endianness})}\n\n\\domain{$\\var{K}, \\ldots, \\var{k}+7$ must be valid indices of\n  \\var{bytevector}.  For {\\cf bytevector-ieee-double-native-set!}, \\var{k} must\n  be a multiple of $8$.}\n\nThese procedures store an IEEE-754 double-precision representation of \\var{x} into\nelements \\var{k} through $\\var{k}+7$ of \\var{bytevector}, and return\n\\unspecifiedreturn.\n\\end{entry}\n\n\\section{Operations on strings}\n\nThis section describes procedures that convert between strings and\nbytevectors containing Unicode encodings of those strings.  When\ndecoding bytevectors, encoding errors are handled as with the {\\cf\n  replace} semantics of textual I/O (see\nsection~\\ref{transcoderssection}): If an invalid or incomplete\ncharacter encoding is encountered, then the replacement character\nU+FFFD is appended to the string being generated, an appropriate\nnumber of bytes are ignored, and decoding continues with the following\nbytes.\n\n\\begin{entry}{%\n\\proto{string->utf8}{ string}{procedure}}\n\nReturns a newly allocated (unless empty) bytevector that\ncontains the UTF-8 encoding of the given string.\n\\end{entry}\n\n\\begin{entry}{%\n\\proto{string->utf16}{ string}{procedure}\n\\rproto{string->utf16}{ string endianness}{procedure}}\n\n\\domain{If \\var{endianness} is specified, it must be the symbol {\\cf\n    big} or the symbol {\\cf little}.}  The {\\cf string->utf16}\n  procedure returns a newly allocated (unless empty) bytevector that\ncontains the UTF-16BE or UTF-16LE encoding of the given string (with\nno byte-order mark).  If endianness is not specified or is {\\cf big},\nthen UTF-16BE is used.  If endianness is {\\cf little}, then UTF-16LE\nis used.\n\\end{entry}\n\n\\begin{entry}{%\n\\proto{string->utf32}{ string}{procedure}\n\\rproto{string->utf32}{ string endianness}{procedure}}\n\n\\domain{If \\var{endianness} is specified, it must be the symbol {\\cf\n    big} or the symbol {\\cf little}.}  The {\\cf string->utf32}\nprocedure returns\na newly allocated (unless empty) bytevector that contains the UTF-32BE\nor UTF-32LE encoding of the given string (with no byte mark).  If\nendianness is not specified or is {\\cf big}, then UTF-32BE is used.\nIf endianness is {\\cf little}, then UTF-32LE is used.\n\\end{entry}\n\n\\begin{entry}{%\n\\proto{utf8->string}{ bytevector}{procedure}}\n\nReturns a newly allocated (unless empty) string whose character\nsequence is encoded by the given bytevector.\n\\end{entry}\n\n\\begin{entry}{%\n\\proto{utf16->string}{ bytevector endianness}{procedure}\n\\pproto{(utf16->string \\var{bytevector}}{procedure}}\n{\\tt\\obeyspaces\\\\\n    \\var{endianness} \\var{endianness-mandatory?})}\n\n\\domain{\\var{Endianness} must be the symbol {\\cf big} or\n  the symbol {\\cf little}.} The {\\cf utf16->string} procedure returns\na newly allocated (unless empty) string whose character sequence is\nencoded by the given bytevector.  \\var{Bytevector} is decoded according\nto UTF-16, UTF-16BE, UTF-16LE, or a fourth encoding scheme that differs from\nall three of those as follows: If \\var{endianness-mandatory?} is\nabsent or \\schfalse, {\\cf utf16->string} determines the endianness\naccording to a UTF-16 BOM at the beginning of \\var{bytevector} if a\nBOM is present; in this case, the BOM is not decoded as a character.\nAlso in this case, if no UTF-16 BOM is present, \\var{endianness}\nspecifies the endianness of the encoding.  If\n\\var{endianness-mandatory?} is a true value, \\var{endianness}\nspecifies the endianness of the encoding, and any UTF-16 BOM in the\nencoding is decoded as a regular character.\n\n\\begin{note}\n  A UTF-16 BOM is either a sequence of bytes \\sharpsign{}xFE,\n  \\sharpsign{}xFF specifying {\\cf big} and UTF-16BE, or \\sharpsign{}xFF,\n  \\sharpsign{}xFE specifying {\\cf little} and UTF-16LE.\n\\end{note}\n\\end{entry}\n\n\\begin{entry}{%\n\\proto{utf32->string}{ bytevector endianness}{procedure}\n\\pproto{(utf32->string \\var{bytevector}}{procedure}}\n{\\tt\\obeyspaces\\\\\n    \\var{endianness} \\var{endianness-mandatory?})}\n\n\\domain{\\var{Endianness} must be the symbol {\\cf big} or\n  the symbol {\\cf little}.} The {\\cf utf32->string} procedure returns\na newly allocated (unless empty) string whose character sequence is\nencoded by the given bytevector.  \\var{Bytevector} is decoded according\nto UTF-32, UTF-32BE, UTF-32LE, or a fourth encoding scheme that differs from\nall three of those as follows: If \\var{endianness-mandatory?} is\nabsent or \\schfalse, {\\cf utf32->string} determines the endianness\naccording to a UTF-32 BOM at the beginning of \\var{bytevector} if a\nBOM is present; in this case, the BOM is not decoded as a character.\nAlso in this case, if no UTF-32 BOM is present, \\var{endianness}\nspecifies the endianness of the encoding.  If\n\\var{endianness-mandatory?} is a true value, \\var{endianness}\nspecifies the endianness of the encoding, and any UTF-32 BOM in the\nencoding is decoded as a regular character.\n\n\\begin{note}\n  A UTF-32 BOM is either a sequence of bytes \\sharpsign{}x00,\n  \\sharpsign{}x00, \\sharpsign{}xFE, \\sharpsign{}xFF specifying {\\cf\n    big} and UTF-32BE, or \\sharpsign{}xFF, \\sharpsign{}xFE,\n  \\sharpsign{}x00, \\sharpsign{}x00, specifying {\\cf little} and\n  UTF-32LE.\n\\end{note}\n\\end{entry}\n\n%%% Local Variables: \n%%% mode: latex\n%%% TeX-master: \"r6rs-lib\"\n%%% End: \n", "meta": {"hexsha": "55e1b3e63a877bcdf3443464dbfce67f08988958", "size": 25928, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "r6rs/bytevector.tex", "max_stars_repo_name": "schemedoc/rnrs-metadata", "max_stars_repo_head_hexsha": "2f998d354177dc41a8d3147fd15c056a14ffabda", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-04T17:38:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-04T17:38:19.000Z", "max_issues_repo_path": "r6rs/bytevector.tex", "max_issues_repo_name": "schemedoc/scheme-rnrs-metadata", "max_issues_repo_head_hexsha": "2f998d354177dc41a8d3147fd15c056a14ffabda", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-03-27T22:24:05.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-26T17:56:02.000Z", "max_forks_repo_path": "r6rs/bytevector.tex", "max_forks_repo_name": "schemedoc/scheme-rnrs-metadata", "max_forks_repo_head_hexsha": "2f998d354177dc41a8d3147fd15c056a14ffabda", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4042553191, "max_line_length": 183, "alphanum_fraction": 0.7289031163, "num_tokens": 7689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.30790294296055437}}
{"text": "%!TEX root = thesis.tex\n\\chapter{\\code{FASMA} and machine learning}\n\\label{cha:fasmaML}\n\nWith the increasing amount of astrophysical data, it is important to perform a rapid and trustworthy\nanalysis. This is one of the strengths for \\code{FASMA} when dealing with high quality spectroscopic\ndata for determination of stellar atmospheric parameters. Here a classic method to analyse these\nlarge amount of data has been modernised with a new minimisation technique that utilise the physical\nknowledge about the system. However smart it may sound like, it can be improved. The time consuming\npart in \\code{FASMA} are the calls to \\code{MOOG}. In the end a couple of minutes are spent on the\nminimisation on a modern computer.\n\nThis lead to a side-project: explorer the use of machine learning to determine stellar atmospheric\nparameters. Machine learning (ML) is not a new topic in computer science, but it is a tool that is\nsteadily becoming more and more popular in today's science. The effort of using ML here is meant as\na proof of concept, and something that can be improved upon in the future.\n\nThe idea was to remove the expensive calls to \\code{MOOG} completely. Two things are required in\norder to do so in the approach presented here:\n\\begin{enumerate}\n  \\item Stellar atmospheric parameters of a large sample of stars with a big span in the parameter\n        space\n  \\item The EW measurements of as many absorption lines as possible (in this case \\ion{Fe}{I} and\n        \\ion{Fe}{II})\n\\end{enumerate}\nAdditionally it is here required that the above two points are obtained in a homogeneous way.\nLuckily such a sample was already analysed during this thesis as a test of \\code{FASMA} (see\n\\sref{sec:fasma_test}) where a sample of 582 stars were analysed; all of which meet the above\nrequired criteria.\n\nThis data set of measurements of EWs and the parameters were organised and prepared in a big table\nas follows:\n\\begin{itemize}\n  \\item Each row contains both the measurements of the EWs (first N columns) and the parameters\n        (last four columns). The parameters are $T_\\mathrm{eff}$, $\\log g$, $[\\ion{Fe}/\\ion{H}]$,\n        and $\\xi_\\mathrm{micro}$\n  \\item The columns excluding the last four are labelled with the wavelength of the absorption line\n  \\item All wavelength columns which contained at least one missing measurement of the EW for any\n        of the 582 stars were removed\n\\end{itemize}\nThere are 58 wavelength columns after removing wavelength columns with missing measurements. Before\nthe removal there were 299 columns with wavelength. In this case the \\code{scikit-learn}\npackage\\footnote{\\url{http://scikit-learn.org/}} from the Python ecosystem was used to train the\ndata set. This also package also include a tool to split the data into a training part and testing\npart. This is particular useful when trying to evaluate the accuracy of the model used. Here the\ntraining consist of 2/3 of the data, and the rest is for testing. This splitting is done randomly,\ngiving slight different results each time the script is executed.\n\nThe training itself is quite fast (less than \\SI{10}{s}). However, the real power comes when the\ntrained model is saved to the disk, which can later be loaded again. In this way the training will\nonly be done once. Using the model to obtain the parameters is much less than \\SI{1}{s}, which makes\nis many orders of magnitudes faster\\footnote{Improvements in the order of millions have been\nobtained here.} than a more traditional approach as with \\code{FASMA}.\n\nWhen testing the model trained, the 1/3 data set is used to derive parameters. Those derived\nparameters are then compared to the actual parameters with a mean absolute error. This gives an idea\nof the accuracy. In \\fref{fig:ml} the script was run 1000 times (the splitting was done randomly in\neach run), and the error for each parameter is shown as a histogram. The mean errors for each\nparameters are roughly $T_\\mathrm{eff}:\\SI{47}{K}$, $\\log g:\\SI{0.10}{dex}$,\n$[\\ion{Fe}/\\ion{H}]:\\SI{0.038}{dex}$, and $\\xi_\\mathrm{micro}:\\SI{0.12}{km/s}$.\n\n\\begin{figure}[htpb!]\n    \\centering\n    \\includegraphics[width=1.0\\linewidth]{figures/ML.pdf}\n    \\caption{Mean absolute error on each parameter after 1000 runs.}\n    \\label{fig:ml}\n\\end{figure}\n\nThere exists many different algorithms within \\code{scikit-learn} to train the final model. In the\ntest here a simple \\code{LinearRegression} was used. Other algorithms were tested as well, such as\n\\code{Ridge} and \\code{Lasso}, however with very similar results. The main difference between the\ndifferent algorithms are found in the details on how the minimisation is done. This is described in\ngreat detail in the online documentation.\n", "meta": {"hexsha": "2d6953e463737217112d02c32d6cd5a45fc1552a", "size": 4705, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "fasmaML.tex", "max_stars_repo_name": "DanielAndreasen/Thesis", "max_stars_repo_head_hexsha": "da18d41e48de5d34c8281ffd9e850dfd4fe37824", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-04-25T08:31:52.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-09T13:46:52.000Z", "max_issues_repo_path": "fasmaML.tex", "max_issues_repo_name": "DanielAndreasen/Thesis", "max_issues_repo_head_hexsha": "da18d41e48de5d34c8281ffd9e850dfd4fe37824", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fasmaML.tex", "max_forks_repo_name": "DanielAndreasen/Thesis", "max_forks_repo_head_hexsha": "da18d41e48de5d34c8281ffd9e850dfd4fe37824", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 63.5810810811, "max_line_length": 100, "alphanum_fraction": 0.7719447396, "num_tokens": 1145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3079029354849906}}
{"text": "% !TEX root = manual.tex\n\n\\chapter{Uncertainty Quantification Methods and Tools}\n\\label{chapter:uq}\n\n\\section{Overview}\n\\label{sec:uqoverview}\nThe SST/macro UQ workflow generally occurs in two steps:\n\\begin{itemize}\n\\item Generating and running parameter sweep\n\\item Running calibration and sensitivity analysis\n\\end{itemize}\n\nFor uncertainty quantification (UQ) and validation studies the UQ Toolkit (UQTk) library is used.\nUQTk (\\url{www.sandia.gov/UQToolkit}) is a lightweight C++ library, developed in Sandia National Laboratories, California, \nthat primarily offers tools for surrogate model construction and uncertainty propagation with \npolynomial chaos expansions (PCE), as well as model calibration and validation.\n\nUQTk Version 2.0 is released under the GNU Lesser General Public License (LGPL). \nA tar-ball with the source code, tutorials, examples and documentation can be \ndownloaded from \\url{www.sandia.gov/UQToolkit/uqtk\\_download.html}\nUQTk uses a standard CMake build system. \nFortran (and libgfortran) is required.\nThe two basic UQ tasks, enabled by UQTk, are \\emph{forward UQ} and \\emph{inverse UQ} as outlined in the next subsections.\n\n\\section{Parameter Sweep and Data Collection}\n\nPerforming uncertainty quantification and sensitivity analysis requires sampling across a multi-dimensional parameter space.\nHere the multi-dimensional input parameters covers all the latency, bandwidth, and size parameters for a given machine configuration.\nIn practical usage, a large parameter sweep must be performed to build a surrogate model.\nThe surrogate model must cover all observables - outputs or statistics of interest from the simulation.\nThat surrogate model is then used in a Markov Chain Monte-Carlo (MCMC) workflow to derive properties such as:\n\n\\begin{itemize}\n\\item Output sensitvity to input parameters\n\\item Maximum likelihood values of input parameters\n\\item Posterior distribution showing for each parameter showing uncertainties\n\\end{itemize}\n\n\\subsection{Surrogate Construction}\n\\label{subsec:surrogateConstruction}\nSST/macro provides helper scripts in the folder \\inlineshell{bin/uq} to generate and collect the data for surrogate construction.\nThe following steps must be performed:\n\n\\begin{itemize}\n\\item Create a template file (see \\inlineshell{exampleTemplate.ini} for example). Variables such as \\$link\\_bw are marked to be replaced.\n\\item Create a parameter definition file (see \\inlineshell{exampleParams} example file). Each variable to explore should match the \\$name in the template file. Each parameter must define the range of values to explore. These define the ``prior distribution'' of realistic values for each parameter with min and max for the range given.\n\\item Run \\inlineshell{generate_quad} installed by UQTk. This will create a file \\inlineshell{qdpts.dat} defining the parameter sweep to perform.\n\\item Run \\inlineshell{genSweep} using \\inlineshell{qdpts.dat} to generate all the input \\inlineshell{params_N.ini} files for each point in the sweep.\n\\item Run \\inlineshell{genRunScript} to create a script \\inlineshell{runAll} for running all the jobs in parallel on a given machine.\n\\item Make sure the \\inlineshell{runSubSweep} script is in the same folder as \\inlineshell{runAll}. Run the \\inlineshell{runAll} script. Wait until a \\inlineshell{testN.out} file matching all the .ini files is generated.\n\\item Gather the results. This must be re-written for each study. An example file \\inlineshell{gatherResults} shows the basic idea. A final file, e.g. \\inlineshell{results.out}, must be \ncreated with one line for each .ini file.  Each line must contain all the output observables corresponding to the run.\n\\end{itemize}\n\nThe files \\inlineshell{qdpts.dat} and \\inlineshell{results.out} are enough to build the surrogate.\n\n\\subsection{Surrogate Validation}\nThe surrogate is a polynomial fit to the actual observed values.\nTo test how well the surrogate is able to reproduce the actual simulation, a random set of parameter points should be run through the simulator and compared to the surrogate estimates.\nSST/macro provides a helper script \\inlineshell{genRandom} to create a \\inlineshell{samples.dat} file.\nThe \\inlineshell{samples.dat} file is equivalent to \\inlineshell{qdpts.dat} in the surrogate construction phase.\nOnce \\inlineshell{samples.dat} is generated, all the same steps should be followed as in Section \\ref{subsec:surrogateConstruction}.\n\n\\subsection{Experimental Comparison}\nThe simulator is trying to reproduce experimental values collected from an actual machine.\nThese experimental values are the ``nominally correct'' values.\nThe parameter calibration and sensitivity analysis, \nmust compare to the nominally correct values.\nUsually these will come from a test bed or existing system, \nbut may come from, e.g. higher-accuracy simulations.\nA file \\inlineshell{experiments.out} should be generated that matches the format of \\inlineshell{results.out} (one line per experimental trial, all output observables on a given line).\nWhile only a single line of data is minimally required,\nhaving multiple trials will improve the UQ workflow by including experimental noise into the uncertainty quantification.\n\nOnce you have all three output files (simulation results, random simulation samples, and experimental results),\nsurrogate construction and analysis can take place using UQTk.\n\n\\subsection{Initial Sanity Checks}\nTo sanity check the match between the simulation parameter sweep and the experimental values, \nSST/macro provides a helper script \\inlineshell{validatePoints} that creates a PDF plot of all the data.\nThis is illustrated in Figure \\ref{fig:uqSanityCheck} for an MPI ping-pong benchmark.\nHere the entire range of the parameter sweep is shown in red lines for the simulator values.\nThe range of experimental values for each output is also shown.\nIn this case, the parameter sweep covers all the experimental outputs suggesting that we can reproduce the experiments.\n\n\\begin{figure}\n\\includegraphics{figures/uqSanity.pdf}\n\\caption{Sanity check plot showing the parameter sweep data (red lines) against the experimental outputs (blue dots) for an MPI ping-pong benchmark}\n\\label{fig:uqSanityCheck}\n\\end{figure}\n\n\\section{Advanced Usage: Running Surrogate Construction and Sensitivity Analysis By Yourself}\nRunning the UQ analysis is involved. Help is available by contacting us at \\url{sst-macro-help@sandia.gov}.\nDocumentation pending...\n\n\n%\\section{Applications/Capabilities}\n%\\label{sec:uqapp}\n%\n%\\subsection{Forward UQ: uncertainty propagation and global sensitivity analysis}\n%\\label{subsec:fuq}\n%\n%The main technique we employ for forward UQ is the spectral Polynomial Chaos expansions (PCEs). \n%A PCE for a given model allows for a) efficient uncertainty propagation, b) very fast global sensitivity analysis, and \n%c) cheap surrogate model construction that can replace the original model in sampling-intensive studies such as calibration, \n%optimization, or, generally, inverse UQ.\n%\n%\\subsubsection{Generic workflow:}\n%\n%A set of scripts that illustrate the essential forward UQ tasks is located in  \\texttt{examples\\_cpp/uq\\_surr}.\n%To enable running all scripts one should set an environment variable \\texttt{UQTK\\_SRC} that points to the location of UQTk.\n%\n%\\begin{ShellCmd}\n%setenv UQTK_SRC location/of/uqtk/in/your/computer\n%\\end{ShellCmd}\n%\n%\n%A generic workflow consists of 4 steps:\n%\\begin{enumerate}\n%\\item Generate parameter samples to run the forward model at, for PC construction and validation, \\texttt{gen\\_sam.x}\n%\\begin{ShellCmd}\n%gen_sam.x <domain_file> <sampling_type(Q/U)> <N_samples> <N_val>\n%\\end{ShellCmd}\n%The list of arguments:\n%\\subitem \\emph{domain\\_file}: A file with \\bgmth d \\endmth rows and 2 columns. \\bgmth d \\endmth is the total number of parameters being explored.\n%           The two columns are the lower and upper bound of the corresponding parameter.\n%\\subitem \\emph{sampling\\_type}: Q (Quadrature) or U (uniformly random). Note that currently in this script set, only Q is supported for further PCE generation.\n%\\subitem \\emph{N\\_samples}: Number of samples used for training, i.e. for building PCE.\n%\\subitem \\emph{N\\_val}:  Number of random samples generated for PCE validation. This can be set to 0 to skip validation.\n%\n%\\item Run the black-box model, \\texttt{model.x}\n%\\begin{ShellCmd}\n%model.x\n%\\end{ShellCmd}\n%This is a black-box model that takes no arguments. However, it expects two input files mparam.dat and minput.dat, and returns the function evaluations in the output file moutput.dat.\n%\\subitem \\emph{mparam.dat}: a single column $d\\times$1 of the parameters of interest, where d is the number of parameters \n%\\subitem \\emph{minput.dat}: controllable input in a matrix form, $N$$\\times$$k$, where $k$ is the number of controllable parameters and $N$ is the number of values or model observables.\n%\\subitem \\emph{moutput.dat}: the model output in a column format $N$$\\times$1.\n%\n%This is the file that needs to be modified/provided by the user according to the model under study. Currently, a simple function $y=Ae^{Bx}+2Bx$ is implemented, where $A$ and $B$ are the parameters (mparam.dat) and $x$ is the single controllable input parameter (minput.dat). A user-created \\texttt{model.x} should accept input files minput.dat and mparam.dat as described above, and it should produce an output file moutput.dat with the formats described above, \n%\n%\\item Obtain PCE for the model, \\texttt{uq\\_surr.x}\n%\\begin{ShellCmd}\n%uq_surr.x <domain_file> <sampling_type(Q/U)> <N_samples> <N_val> \\\n%\t\t<P_order> <moutput_surr_filename> <moutput_val_filename>\n%\\end{ShellCmd}\n%\n%The first four arguments coincide with those from \\texttt{gen\\_sam.x}, the rest of the arguments are:\n%\\subitem \\emph{P\\_order}: the PCE surrogate order. Polynomial series is truncated according to the total order.\n%\\subitem \\emph{moutput\\_surr\\_filename}: model output file resulting from running \\texttt{model.x} on training samples.\n%\\subitem \\emph{moutput\\_val\\_filename}: model output file resulting from running \\texttt{model.x} on validation samples.\n%\n%\\item Postprocess, e.g. global sensitivity analysis, \\texttt{pp\\_sens.x} \n%\\begin{ShellCmd}\n%pp_sens.x\n%\\end{ShellCmd}\n%\n%The current implementation of the post processing script \\texttt{pp\\_sens.x} takes no arguments. It expects the presence of a PCE information file pccf\\_all.dat, which is one of the outcomes of \\texttt{uq\\_surr.x}. The final global sensitivity results are saved in the \\inlineshell{allsens.dat} file of dimensions $N$$\\times$$d$, where each row corresponds to a single value for the controllable input (number of controllable inputs = N), and each column corresponds to the sensitivity index of a parameter (number of parameters = d).\\\\\n%\n%\\medskip\n%\n%Note that one can run the model \\texttt{model.x} in an \\emph{online} regime by using the keyword \"M\" instead of filenames in\n%\\begin{ShellCmd}\n%uq_surr.x <domain_file> <sampling_type(Q/U)> <N_samples> <N_val> <P_order> M M\n%\\end{ShellCmd}\n%that effectively incorporates the steps 1-3 above.\n%\n%\\subsubsection{Simple Example:}\n%\n%The script \\texttt{example.x} incorporates the full workflow above for a test function $y=Ae^{Bx}+2Bx$. Try\n%\\begin{ShellCmd}\n%example.x online\n%\\end{ShellCmd}\n%which produces, in a newly created folder \\texttt{test}, the sensitivity file \\inlineshell{allsens.dat} with sensitivity indices with respect to $A$ and $B$ for all values of controllable input $x$.\n%\n%\n%\n%\\end{enumerate}\n%\n%\n%\\subsubsection{How Forward UQ applies to \\sstmacro}\n%\n%In the workflow described above, \\sstmacro would replace the black-box simple model given by the equation, and \\sstmacro parameters of interest would replace $A$ and $B$.   Note that while\n%we could explore the entire \\sstmacro parameter space using this workflow, the higher the dimensionality of the space the more time process takes, so we would also want to narrow it down to the most important parameters, usually by reasoning, inspection, or simple experimentation.  \n%Also note that running an \\sstmacro simulation can be considerably more expensive than evaluating an\n%analytical model, which is why we typically construct a \\textit{surrogate}, or an arbitrarily-complex polynomial that can approximate performance given by \\sstmacro. \n%\n%While the above workflow must currently be manually applied to \\sstmacro data, we are working on automating this process and coming up with tutorials explaining how it is done.\n%\n%\\subsection{Inverse UQ: parameter calibration and model validation}\n%\\label{subsec:iuq}\n%\n%UQTk relies on Bayesian inference methods for model parameter calibration. Model validation is a direct result of calibration \n%postprocessing. Indeed, a model is considered validated if the calibrated model parameters and the associated uncertainties can explain/predict available data well. \n%The library \\texttt{uqtkmcmc} allows implementation of Bayesian calibration using Markov chain Monte Carlo (MCMC) methods. The MCMC technique essentially \n%searches the parameter space and compares model results with available data. Note that each parameter sample invokes a model evaluation, and often MCMC requires \n%many samples for properly estimating the uncertainties. In such cases, the full model, as a black-box, will be replaced by its surrogate, again as a black-box model, that is constructed by the forward UQ techniques described in Subsection~\\ref{subsec:fuq}.\n", "meta": {"hexsha": "77824a0846a0019dc9fb4e610e4824cdeef47aec", "size": 13411, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/manual/UQ.tex", "max_stars_repo_name": "calewis/sst-macro", "max_stars_repo_head_hexsha": "067a2cb9f1606b652396b5dda6093096e5bcf2d7", "max_stars_repo_licenses": ["BSD-Source-Code"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2017-01-26T09:28:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T11:31:55.000Z", "max_issues_repo_path": "docs/manual/UQ.tex", "max_issues_repo_name": "calewis/sst-macro", "max_issues_repo_head_hexsha": "067a2cb9f1606b652396b5dda6093096e5bcf2d7", "max_issues_repo_licenses": ["BSD-Source-Code"], "max_issues_count": 542, "max_issues_repo_issues_event_min_datetime": "2016-03-29T22:50:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T20:14:08.000Z", "max_forks_repo_path": "docs/manual/UQ.tex", "max_forks_repo_name": "calewis/sst-macro", "max_forks_repo_head_hexsha": "067a2cb9f1606b652396b5dda6093096e5bcf2d7", "max_forks_repo_licenses": ["BSD-Source-Code"], "max_forks_count": 36, "max_forks_repo_forks_event_min_datetime": "2016-03-10T21:33:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T07:44:12.000Z", "avg_line_length": 67.391959799, "max_line_length": 537, "alphanum_fraction": 0.7914398628, "num_tokens": 3213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3079029354849906}}
{"text": "\\documentclass[a4paper,11pt]{article}\n\\usepackage{a4wide}\n\\usepackage[utf8]{inputenc}\n\\usepackage{amssymb}\n\\usepackage{amsmath}\n\\usepackage{amsfonts}\n\\usepackage{enumerate}\n\\usepackage{fancyhdr}\n\\usepackage{array}\n%\\usepackage{./include/matrices}\n\\usepackage{graphicx}\n%\\usepackage{pictex}\n\\pagestyle{fancy}\n\\begin{document}\n\\renewcommand{\\vec}[1]{\\ensuremath{\\underline{\\mathbf{#1}}}}\n% Equal sign with hat on top:\t\t\t\n\\newcommand{\\corresponds}{\\ensuremath{\\widehat{=}}}\n\n\\section{fig 1 - handwritten page 2}\n\\[\\substack{\t\\text{estimate of the density} \\\\\n\t\t\\text{at a given point } \\vec{x}}\n\\]\nobservations\n\n\\section{fig 2 - handwritten page 2}\nGaussian kernel \\\\\\\\\nhistogram kernel\\\\\\\\\n$H$\\\\\\\\\n$u$\n\n\\section{fig 3 - handwritten page 4}\ntrue density \\\\\\\\\n$P$\\\\\\\\\n$\\widehat{P}$\n\\[ \\substack{ \t\\text{estimated density} \\\\\n\t\t\\text{(optimal w.r.t } E^T \\text{)} }\n\\]\n\n\\section{fig 4 - handwritten page 5}\ntest data \\\\\\\\\nmodel density I \\\\\\\\\nmodel density II\n\n\\section{fig 5 - handwritten page 8}\nGauss\\\\\\\\\n$\\vec{w}^*$ \\\\\\\\\n$\\widehat{\\vec{w}}$\\\\\\\\\n\\[ \\substack{ \t\\text{width}^2 \\text{ (variance) given} \\\\\n\t\t\\text{by Fisher information matrix} \\\\\n\t\t\\text{(} \\leadsto \\text{error measure for } \n\t\t\t\\widehat{\\vec{w}} \\text{)}}\n\\]\n\t\n\\end{document}\n", "meta": {"hexsha": "9521ab1bfe1607f818e504401cfd8f1ca87a111b", "size": 1241, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "figures/section1_to_png.tex", "max_stars_repo_name": "nigroup/mi2script", "max_stars_repo_head_hexsha": "d2810dda5a1e4fdff8082dbdd54244322b7c9f79", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-11T10:14:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-11T10:14:13.000Z", "max_issues_repo_path": "figures/section1_to_png.tex", "max_issues_repo_name": "nigroup/mi2script", "max_issues_repo_head_hexsha": "d2810dda5a1e4fdff8082dbdd54244322b7c9f79", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "figures/section1_to_png.tex", "max_forks_repo_name": "nigroup/mi2script", "max_forks_repo_head_hexsha": "d2810dda5a1e4fdff8082dbdd54244322b7c9f79", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5636363636, "max_line_length": 60, "alphanum_fraction": 0.6720386785, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.30790293548499054}}
{"text": "\\section{}\nThe chiral central charge tells you the heat current.\nIf you had a single chiral Majorana mode it's half.\n\n\\begin{table}\n    \\centering\n    \\begin{tabular}{ccccc}\n        (1+1)D & $\\mathbb{Z}_2$ invariant &\n        $\\mathcal{I}=P_0 P_\\pi$ &\n        $G_f = \\mathbb{Z}_2^f$ &\n        $\\psi\\to e^{i\\theta}\\psi$ Class D\\\\\n        (2+1)D & $\\mathbb{Z}$ invariant Chern number &\n        C &\n        $G=U(1)$ &\n        [$G_f=U(1)^f$] Class A\\\\\n        & $\\mathbb{Z}$ invariant &\n        $\\nu=2C_{-}$ (sp. Chern # for free fermions) &\n        $G_f=\\mathbb{Z}_2^f$\n    \\end{tabular}\n    \\caption{Free fermion models}\n    \\label{tab:freefermions}\n\\end{table}\n\n\\begin{question}\n    What is a full Majorana measurement?\n\\end{question}\nMeasurement of $\\gamma_1 \\gamma_j \\gamma_k \\gamma_l$.\nJoint fermion parity.\n\n\nConsider $U(1)_\\uparrow$ with Chern number $C_\\uparrow$\nand $U(1)_\\downarrow$ with Chern number $C_\\downarrow$\nwith\n$C_{\\uparrow} = -C_{\\downarrow} = C$.\nThere is also time-reversal symmetry.\n\nChern number breaks time-reversal and reflection symmetry.\nIt breaks time rerseal because the direction of the current on the edge would\nhave to switch sign.\n\nBut if they have opposite Chern number on both sides with two components then\nyou can.\n\nA two-component system with $C_\\uparrow = -C_\\downarrow$ can be time-invariant.\n\nLet's study the edge theory in a particular case here.\n\n\\subsection{Edge theory for $C_\\uparrow=C_\\downarrow=1$}\nThe Hamiltonian would be like\n\\begin{align}\n    H &=\n    \\sum_k \\left[ \n    |V_\\uparrow| k \\psi_{\\uparrow,k}^\\dagger \\psi_{\\uparrow,k}\n    |V_\\downarrow| k \\psi_{\\downarrow,k}^\\dagger \\psi_{\\downarrow,k}\n    \\right]\n\\end{align}\nNon-trivial topological phases have something interesitng at the edges.\nSo consider a backscatttering term or a mass term for htis fermion\n\\begin{align}\n    m \\psi_\\uparrow^\\dagger \\psi_\\downarrow + h.c.\n\\end{align}\nThis breans spin consdervation,\nwhich is the relative $U(1)$.\nThis breaks the $S_z$ spin conservation.\nBut that's not so surprising because you have an up fermion and that gets\nbackscattered by a down fermion,\nand it's not so surprising that breaks spin conservation.\nMore interesting,\nthis term also breaks time-reversal symmetyr.\n\nLet's deine time reversal to hae the following actiona\n\\begin{align}\n    T: \\psi_\\uparrow &\\to \\psi_\\downarrow\\\\\n    \\psi_\\downarrow &\\to -\\psi_\\uparrow\n\\end{align}\nwhich means on a single fermion $T^2=-1$,\nand so\n\\begin{align}\n    T^2 &= {(-1)}^F\n\\end{align}\nSo you could say this is a $\\mathbb{Z}_4^{T,f}$ symmetry.\nBut there's also a $U(1)^f$ symmetry.\nBut if you apply one and apply another,\nthe order matters,\nand there's a complex conjugation when you reverse the order.\nAnd you need to mod out to consider equivalence.\nSo the symmetry of the system is this\n\\begin{align}\n    G_f &=\n    \\frac{U(1)^f \\rtimes Z_4^{T,f}}{\\mathbb{Z}_2}.\n\\end{align}\nThis is called the class AII symmetry group in the Cartan classification.\n\nFermionic symmetry group $G_f$.\nConsider whath appens when you act the symmetry only on bosonic operators,\nthen you can ask what symmetry acts on them,\nand that allows you to define a bosoinc symmetry gorup\n\\begin{align}\n    G_b &= G_f/\\mathbb{Z}_2^f\n\\end{align}\n\nIf you look at the bosoinc symmetry group,\nthen\n\\begin{align}\n    G_b &=\n    U(1) \\rtimes \\mathbb{Z}_2^T\n\\end{align}\nUnder time-reversal symmetry,\n\\begin{align}\n    T (M \\psi_\\uparrow^\\dagger \\psi_\\downarrow) T^\\dagger &=\n    - m^* \\psi_\\downarrow^\\dagger \\psi_\\uparrow\n\\end{align}\nYou'd think there's a single total Chern number.\nSurprisingly,\nthere's still something non-trivial left over.\nThis suggests there's still some non-trivial topological phase still left over\nin the system.\nYou can then consider two copies.\n\\begin{align}\n    C_\\uparrow = - C_\\downarro = 2\n\\end{align}\nthen you can write the same thing,\nbut there's an extra flavour $s$.\n\\begin{align}\n    H &=\n    \\sum_{k,s} \\left[ \n    |V_{\\uparrow,s}| k \\psi_{\\uparrow,k,s}^\\dagger \\psi_{\\uparrow,k,s}\n    |V_{\\downarrow,s}| k \\psi_{\\downarrow,k,s}^\\dagger \\psi_{\\downarrow,k,s}\n    \\right]\n\\end{align}\nUnder time-reversal,\n\\begin{align}\n    T: \\psi_{\\uparrow, s} & \\to \\psi_{\\downarrow,s}\\\\\n    \\psi_{\\downarrow,s} &\\to -\\psi_{\\uparrow,s}\n\\end{align}\nAnd now you can consdier what terms you can add,\nand it turns out you can add a backscaettering term.\n\\begin{align}\n    \\delta H_{\\textrm{backscattering}} &=\n    m\\left(\n    \\psi_{\\uparrow,1}^\\dagger \\psi_{\\downarrow, 2}\n    - \\psi_{\\downarrow,1}^\\dagger \\psi_{\\uparrow, 2}\n    + \\mathrm{h.c.}\n    \\right)\n\\end{align}\nand now you can open an energy gap.\nThis suggests the bulk topological phase should have\n$\\mathbb{Z}_2$ invariant.\n\nThis is the bulk-edge correspondence.\nYou can deduce the bulk properties by looking at he stability of the boundary\nmodes under action of the symmetry group.\n\nNow we can consider whath appens when this time-reversal symmetry does not have\nthis minus sign.\nSuppose that instead\n\\begin{align}\n    T: \\psi_\\uparrow &\\to \\psi_\\downarrow\\\\\n    \\psi_\\downarrow & \\to \\psi_\\uparrow\n\\end{align}\nand so $T^2=+1$.\nThen the symmetry groups are\n\\begin{align}\n    G_f &= U(1)^f \\rtimes \\mathbb{Z}_2^T\\\\\n    G_b &= U(1) \\rtimes \\mathbb{Z}_2^T\n\\end{align}\nand then $C_\\uparrow = C_\\downarrow = -1$\nand it does not have protected edge modes.\nThe fact that $G_f$ is different has consequences on what ind of backscattering\nterms you can add.\n\nFermions can ermge in a variety of situations in solid state systems.\nI don't have a good example,\nbut you can have fermions show up in solid state systems.\nOf ten this kind of time reversal can be thoguht of as a effectie time reversal\nwhere you combien it wiht some kind of rotation.\nThis may be the true time reversal plus some rotation,\nbut we still call it time reversal because it's anti hermitian.\n\nThe $\\pi$ rotation in $G_f$ becomes the $1$ operation in $G_b$.\nThis becomes implicit in\n\\begin{align}\n    G_b &= G_f / \\mathbb{Z}_2^f\n\\end{align}\nThis becomes a trivial operation as far as a boson is concerned.\n\n\\begin{question}\n    Why do we ultimately have to define $G_b$?\n    The first symmetry gourp is $G_f$.\n    Why do we not just work with $G_f$?\n\\end{question}\nI didn't use $G_b$ anywhere,\nI just noted $G_b$.\nAnd depending on how sophisticated the theroy is,\nit could be useful,\nbut not in this particular scenario.\n\nLet me remind you of the important Kramers theorem.\n\nIf $T^2=-1$,\nit measn the minimal representation is 2-dimensional,\nwhichm eans if you have a state on which $T^2$ acts as $-1$,\nit has to be a doublet.\nThe proof is two lines.\nSuppose you act $T$ on a state and you don't change it\n\\begin{align}\n    T\\ket{\\psi} &= \\lambda\\ket{\\psi}\\\\\n    -\\ket{\\psi} = T^2 = \\lambda^* \\lambda \\ket{\\psi}\n\\end{align}\nSo therefore,\n$T$ msut bring it to another state\n\\begin{align}\n    T\\ket{\\uparrow} &= \\lambda \\ket{\\downarrow}\\\\\n    T\\ket{\\downarrow} &= \\lambda^' \\ket{\\uparrow}\n\\end{align}\nand $\\lambda\\lambda' = -1$.\nwhich is a contradiction.\nSo that's Kramers theorem.\n\nconsider a cylinder with a momentum around a circle $k_y$ and let $x$ e the axis\nof the cylinder.\n\nConsider the spectrum of $E$ vs $k_y$.\nthere are bulk states in tethe valence conduction bands.\nYou can see that $T: k \\to -k$,\nbecause intiuitively time reversal changes the sign of momentum.\nThen the possible time-reversal momenta are\n\\begin{align}\n    \\vec{k} &=\n    \\begin{cases}\n        (0, 0)\\\\\n        (0, \\pi)\\\\\n        (\\pi 0)\\\\\n        (0, 0)\n    \\end{cases}\n\\end{align}\nThere's two topological distrinct scenarios that can happen.\nEither these states connect up in a non-trivial way.\nThis merges into the bulk and then this comes out.\n\nThisis topological.\nNo matter where I put my chemical otential,\nI'mg going to hit exactly 1.\nThe trivial situation is when Karmers pairs connect up in a non-trial wahuoWe\nhave these states and I can have ooThe Kramrs degenerate states in time-reversal\nomentua connect up.\n\nYou can geta band invariant bby mulitplying hte hern nmber through the Brilluoin\nzone.\n\n\\section{\\mathbb{$Z_2$}c  band invariant}\nDefine\n\\begin{align}\n    W_{mn}(k) &=\n    \\bra{U_m(k)} T \\ket{U_n(-k)}\n\\end{align}\nwhere $w$ is unitary.\n\n\\begin{align}\n    w^T(k) = -w(-k)\n\\end{align}\n$\\Lambda_a$ = $ trim,\n$a+1,\\dpts.a$4$\n\\begin{align}\n    \\lambda_n = \\mathrm{TRIM}\\qquad a=1,\\ldots, 4\\\\\n    w^T(\\Lambda_a) &= -w(`A_a)\n\\end{align}\nand\n\\begin{align}\n    \\delta_a &= \\frac{\\Pf(w(\\Lambda_a))}{\\sqrt\\det(w(\\lambda_a))}}\n    = \\pm 1\n\\end{align}\nHere\n\\begin{align}\n    \\pm 1 &= (-1)^{\\nu}\n    = \\prod_{a=1}^{N}\n\\end{align}\nNeed $\\sqrt{deg{w(k)}}$ continuous everywhere in BZ.\nCan do this if Bloch wave functions we defined continuously everywhere.\nPossible boundary condition that total Chern number = 0 by $T$.\n\n\n\\subsection{Time-reversal polarization in 1D}\nFu-Kane arXiv 0606336.\nCan split up Bloch states of occupied bands in the two classes.\n\\begin{align}\n    \\ket{U_m^I(k)}, \\ket{U_m^{II}(k)}\\\\\n    T\\ket{U_m^I(k)} &= e^{i\\chi_m(k)}\\ket{u_m^{II}(-k)}.\n\\end{align}\nDefine polarization $P_I$ and $P_{II}$ fore each class.\nTotal polarization\n\\begin{align}\n    P &= P_I + P_{II}\n\\end{align}\nand time-reversal polarization\n\\begin{align}\n    P_T &= P_I - P_{II}\n\\end{align}\n\\begin{align}\n    \\pm 1 &= (-1)^{P_T} = \\delta_1 \\delta_2\n\\end{align}\nfor $\\Lambda_1=0$ $\\Lambda_2=\\pi$ where\n\\begin{align}\n    \\delta_{a} &=\n    \\frac{\\Pf(w(\\Lambda_a))}{\\sqrt{\\det(w(\\Lambda_a))}}\n\\end{align}\n\nThe physical meaning is this.\n$(-1)^{P_T}=-1$ means boundary has a Kramers degeneracy in each end.\n\n\\subsection{Back to 2D}\nCan think of 2D system as parameterized 1D\n\\begin{align}\n    H_{2d} &=\n    \\sum_{k_y} H_{1d}\\left( k_y \\right)\n\\end{align}\nConsider change in $P_T$ from $k_y=0$ to $\\pi$.\n\\begin{align}\n    {(-1)}^{P_T(k_y=\\pi) - P_T(k_y=0)} &=\n    \\delta\\left( (0, 0) \\right)\n    \\delta\\left( (\\pi ,0) \\right)\n    \\delta\\left( (0, \\pi) \\right)\n    \\delta\\left( (\\pi, \\pi) \\right)\\\\\n    &=\n    {(-1)}^{\\nu}\n\\end{align}\nYou can think of this as localized Wannier states.\n\nJust like there is a story for insulators as superconductors,\nthis story also has an analogue for topological superconductors.\nInstead of Chern number $\\pm 1$,\nwe can also consider $p+ip$ or $p-ip$.\n\nConsider a different symmetry group\n\\begin{align}\n    G_f = \\mathbb{Z}_4^{T,f}\n\\end{align}\nand there's no $U(1)$.\nThis is called class DIII.\nThis would be for topological superconductors.\nConsider 2 layers.\nThere is an invariant $\\nu$ for the $p+ip$ layer and\n$-\\nu$ for the $p-ip$ layer.\n\nAll this stuff about topological pumps.\nThe story on why states are protected.\nWe get the $\\mathbb{Z}_$ classification of topological phases.\nFrom a high level it's very similar.\n\nIf you're okay,\nwe can go to (3+1)D.\nOnce we've done that,\nwe'll just leave the world of free fermion topological phases\nand go on to describe some other kinds of things.\n\nSo we wrote down this band invariant $\\nu$.\nIf you go up one dimension you can consider a similar invariant.\n\nFor (3+1)D Classs AII,\n\\begin{align}\n    G_f &= \\frac{U(1)^f\\rtimes \\mathbb{Z}^{T,f}}{\\mathbb{Z}_2}\n\\end{align}\nand\n\\begin{align}\n    (-1)^\\nu &= \\prod_{a=1}^8 \\delta_a\n\\end{align}\n8 TRIM:\n\\begin{align}\n    \\Lambda_a &= \\left( \\pi s_1, \\pi s_2, \\pi s_3 \\right)\n\\end{align}\n\n\n\\section{(3+1)D massive Dirac fermion}\nIt is useful to start in (4+1)D.\n\\begin{align}\n    H &=\n    \\sum_{a=0}^{4}\n    \\sum_{k} \\psi_k^\\dagger d_a(k)\\cdot \\Gamma^a \\psi_k\n\\end{align}\nwhere $\\Gamma^\\mu$ are $4\\times 4$ Dirac matrices wiht $\\mu=0,\\ldots,4$.\nThen the anticommutation is\n\\begin{align}\n    \\left\\{ \\Gamma^{\\mu}, \\Gamma^{\\nu} \\right\\} = 2\\delta_{\\mu\\nu} II\n\\end{align}\nThis can be  parameterized family of 3 + 1 dimensional models,\nparameetrized by a parameter $k_w$.\n\\begin{align}\n    d_a(k) &=\\left( \n    m +c \\sum_{i=1}^{4}\\cos(k),\n    \\sin k_x,\n    \\sin k_y,\n    \\sin k_z,\n    \\sin k_w\n    \\right)\n\\end{align}\nso\n\\begin{align}\n    H &= \\sum_{k_w} H_{3+1Dj}(k_1,k_2,k_3,k_w).\n\\end{align}\nThen we couple this to a background $U(1)$ gauge field.\n\nView $k_w + A_w = \\theta$ as a parameter.\nI view this fourth dimension as a parameter.\nThe 4 + 1 D effective action if we integrate out the fermions is basically a\nChern Simons term.\nSo it's going to give\n\\begin{align}\n    S_{\\mathrm{eff}} &=\n    \\frac{C_2}{24\\pi^2}\n    \\int d^4x\\, dt\\,\n    \\epsilon^{\\mu\\nu\\lambda\\sigma}\n    A_{\\mu} \\partial_{\\nu} A_{\\lambda} \\partial_{\\rho} A_{\\sigma}\n\\end{align}\nwhere $C_2$ is the second Chern number of Bloch states\n\\begin{align}\n    C_2 &=\n    \\int \\mathcal{F}_{\\mu\\nu} \\mathcal{F}_{\\lambda\\sigma}\n    \\epsilon^{\\mu\\nu\\lambda\\sigma}\n\\end{align}\nwhere $\\mathcal{F}_{\\mu\\nu}$ is the Berry curvature of the Bloch wave functions.\n", "meta": {"hexsha": "425642879b06d0ee49d85302254808f0e11982c3", "size": 12609, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "phys733/lecture15.tex", "max_stars_repo_name": "ehua7365/umdphysnotes", "max_stars_repo_head_hexsha": "00e4e2b6aba3d03baaec5caa36903e5135b014de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-11T12:53:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T12:53:46.000Z", "max_issues_repo_path": "phys733/lecture15.tex", "max_issues_repo_name": "ehua7365/umdphysnotes", "max_issues_repo_head_hexsha": "00e4e2b6aba3d03baaec5caa36903e5135b014de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phys733/lecture15.tex", "max_forks_repo_name": "ehua7365/umdphysnotes", "max_forks_repo_head_hexsha": "00e4e2b6aba3d03baaec5caa36903e5135b014de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9501187648, "max_line_length": 80, "alphanum_fraction": 0.6855420731, "num_tokens": 4159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665855647394, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.30790292800942665}}
{"text": "\\section{Systematic uncertainties}\n\\label{sec:hmhzz_sys}\n\nThis section describes the sources and values of theoretical and experimental systematic uncertainties considered in this analysis.\n\n%% =========================================================================================================================\n\\subsection{Theoretical systematics}\n\nThe theoretical modelling uncertainties include the PDF variations, missing QCD higher-order corrections via the variations of factorisation and renormalization scales,\nand the parton showering uncertainties.\n\n\\subsubsection{Theoretical uncertainties for signal}\n\\label{sec:hmhzz_theo_signal}\n\nThe PDF, QCD scale and parton showering uncertainties affecting the acceptance difference originating from analysis selection for signal are taken into account in different categories.\nThe acceptance uncertainties are calculated on the acceptance factor which extrapolates from the fiducial space to the full phase space by a simple ratio:\n\\begin{equation}\n        A = \\frac{N_{fiducial}}{N_{total}}\n\\end{equation}\n\nFor PDF uncertainties, the standard derivations of 100 PDF replicas of NNPDF3.0 NNLO, as well as comparison to two external PDF sets: MMHT2014 NNLO, CT14 NNLO are considered.\nFor missing QCD higher-order corrections, the effects are studied with truth events by comparing weights corresponding to\nvariations of the renormalization and factorization scale factors, up and down by a factor of two, and the envelop of different variations is used.\nThe parton showering uncertainties are estimated by comparing events with different setting via \\textsc{Pythia8}.\n\nSystematic uncertainties are studied for both cut- and MVA- based event categorizations, \nfor cut-based analysis in two different categories: the inclusive ggF-CBA-enriched and VBF-CBA-enriched category,\nand for MVA-based one in three different categories: inclusive ggF-MVA-high, ggF-MVA-low and VBF-MVA-enriched category.\nThis section shows the MVA-based results as an example.\n\nTable~\\ref{tab:acc-ggF-dnn} and ~\\ref{tab:acc-VBF-dnn} show the theoretical uncertainties mentioned above for ggF and VBF signal respectively in MVA-based categorization.\n\n\\begin{table}[htbp]\n  \\centering\n  \\caption{Summary of acceptance uncertainties of PDF, QCD scale and parton shower variations for ggF production. The MVA-based categorization is used.}\n  \\label{tab:acc-ggF-dnn}\n  \\begin{spacing}{0.75}\n  \\begin{tabular}{cccc}\n    \\toprule\n    Categories  & PDF    & QCD Scale  & Parton Shower \\\\\n    \\midrule\n    ggF-MVA-high  & 0.40\\% & 0.06\\% & 2.03\\% \\\\\n    ggF-MVA-low   & 0.56\\% & 0.07\\% & 4.86\\% \\\\\n    VBF-MVA-enriched  & 0.53\\% & 0.09\\% & 3.43\\% \\\\\n    \\bottomrule\n  \\end{tabular}\n  \\end{spacing}\n\\end{table}\n\n\\begin{table}[htbp]\n  \\centering\n  \\caption{Summary of acceptance uncertainties of PDF, QCD scale and parton shower variations for VBF production. The MVA-based categorization is used.}\n  \\label{tab:acc-VBF-dnn}\n  \\begin{spacing}{0.75}\n  \\begin{tabular}{cccc}\n    \\toprule\n    Categories  & PDF    & QCD Scale  & Parton Shower \\\\\n    \\midrule\n    ggF-MVA-high  & 0.18\\% & 1.20\\% & 0.41\\% \\\\\n    ggF-MVA-low   & 0.43\\% & 0.26\\% & 0.36\\% \\\\\n    VBF-MVA-enriched  & 0.23\\% & 3.19\\% & 0.85\\% \\\\\n    \\bottomrule\n  \\end{tabular}\n  \\end{spacing}\n\\end{table}\n\n%\\textbf{Cut-based analysis} \\\\\n%\n%Table~\\ref{tab:acc-ggF-cut} and ~\\ref{tab:acc-VBF-cut} show the theoretical uncertainties for ggF and VBF signals respectively in cut-based categorization.\n%The uncertainties are computed in two different categories: the inclusive ggF and VBF category.\n%\\begin{table}[htbp]\n%  \\centering\n%  \\caption{Summary of acceptance uncertainties of PDF, QCD scale and parton shower variations for ggF production. The cut-based categorization is used.}\n%  \\label{tab:acc-ggF-cut}\n%  \\begin{tabular}{cccc}\n%    \\toprule\n%    Categories  & PDF    & QCD Scale  & Parton Shower \\\\\n%    \\midrule\n%    ggF  & 0.44\\% & 0.07\\% & 0.22\\% \\\\\n%    VBF  & 0.61\\% & 0.12\\% & 3.33\\% \\\\\n%    \\bottomrule\n%  \\end{tabular}\n%\\end{table}\n%\n%\\begin{table}[htbp]\n%  \\centering\n%  \\caption{Summary of acceptance uncertainties of PDF, QCD scale and parton shower variations for VBF production. The cut-based categorization is used.}\n%  \\label{tab:acc-VBF-cut}\n%  \\begin{tabular}{cccc}\n%    \\toprule\n%    Categories  & PDF    & QCD Scale  & Parton Shower \\\\\n%    \\midrule\n%    ggF  & 0.18\\% & 2.87\\% & 0.52\\% \\\\\n%    VBF  & 0.08\\% & 4.52\\% & 0.72\\% \\\\\n%    \\bottomrule\n%  \\end{tabular}\n%\\end{table}\n\n\n\\subsubsection{Theoretical uncertainties for SM background processes}\n\nThe theoretical uncertainties of irreducible $ZZ$ backgrounds are considered in terms of both the variations of shape of \\mfl distributions\nand the acceptance originating from the event selection.\n\nThe PDF and QCD scale uncertainties are considered by using the same method as described for signal.\nThe parton showering uncertainties for those \\textsc{Sherpa} samples are evaluated by varying the resummation scale by a factor of 2, \nchanging the CKKW setting and using different showering option, following the PMG recommendation in Ref.~\\cite{twiki_pmgsyst},\nand the quadratic sum between the uncertainties in different kinds of showering option is taken as final result of uncertainties.\nMoreover, the shape uncertainty associated with electroweak higher-order correction for \\qqZZ process is also taken into account.\n\nSame as for signals, these theoretical uncertainties for irreducible backgrounds are studied for both cut- and MVA- based event categorizations.\nThe value of shape uncertainties vary from less than 1\\% at low mass region to 50\\% at high mass tail due to large statistic fluctuation.\nAs for the acceptance uncertainties, the values vary from about 1\\% for PDF variations to 40\\% for parton showering variations.\nThe VBF category has relative larger uncertainties.\n\nTable~\\ref{tab:acc-all-qqZZ_MVA} summarizes the acceptance uncertainties of PDF, QCD scale, and parton showering variations for the dominant background: \\qqZZ.\n\n\\begin{table}[htbp]\n  \\centering\n  \\caption{Summary of acceptance uncertainties of PDF, scale, and parton showering variations for QCD \\qqZZ background. The MVA-based categorization is used.}\n  \\label{tab:acc-all-qqZZ_MVA}\n  \\begin{spacing}{0.75}\n  \\begin{tabular}{cccc}\n    \\toprule\n    Categories  & PDF    & QCD Scale   & Parton showering \\\\\n    \\midrule\n    ggF-MVA-high  & 1.15\\% & 10.16 \\% & 3.71\\% \\\\\n    ggF-MVA-low   & 1.04\\% & 3.26  \\% & 3.80\\% \\\\\n    VBF-MVA-enriched  & 2.91\\% & 27.90 \\% & 23.82\\% \\\\\n    \\bottomrule\n  \\end{tabular}\n  \\end{spacing}\n\\end{table}\n\n%% =========================================================================================================================\n\\subsection{Experimental systematics}\n\nThe signal and background predictions used in this analysis are also affected by various sources of experimental systematic uncertainties.\nSimilar as described in section~\\ref{sec:vbszz_exp_uncer}, the dominant experimental uncertainties in this analysis also come from the energy/momentum scales \nand reconstruction and identification efficiencies of the leptons and jets, as well as the luminosity uncertainty.\nThe systematic uncertainties are calculated using the recommendations from the Combined Performance (CP) groups of ATLAS experiment.\nIn addition, as mentioned in previous sections, the uncertainties of irreducible background modelling, reducible background shape smoothing procedure and signal yield difference between simulation and parameterization are all taken into account.\n%Table~\\ref{tab:np_list} summarizes the experimental systematics considered in this analysis that affect either the normalization of total event yield or the shape of \\mfl distribution.\nThe impact of a few largest systematics and their value from statistical fit are studied in section~\\ref{sec:hmhzz_result_4l}.\n\n\\iffalse\n\\begin{table}\n  \\centering\n  \\caption{\n  A list of the experimental systematics considered in this analysis. The NPs have been separated by whether they only\n  affect the normalisation (left column) or if they affect the shape (right column) of the \\mfl distribution. They are\n  further subdivided into the primary objects that they affect.\n  }\n  \\begin{spacing}{0.65}\n  \\small\n  \\begin{tabular}{l|l}\n    \\toprule\n    \\multicolumn{1}{c}{Normalisation NPs} & \\multicolumn{1}{c}{Shape NPs} \\\\\n    \\midrule\n    \\multicolumn{2}{c}{\\textbf{Electrons}} \\\\\n    \\midrule\n    \\texttt{EL\\_EFF\\_ID\\_CorrUncertaintyNP[0-15]}               & \\texttt{EG\\_RESOLUTION\\_ALL} \\\\\n    \\texttt{EL\\_EFF\\_ID\\_SIMPLIFIED\\_UncorrUncertaintyNP[0-17]} & \\texttt{EG\\_SCALE\\_ALLCORR} \\\\\n    \\texttt{EL\\_EFF\\_Iso\\_TOTAL\\_1NPCOR\\_PLUS\\_UNCOR}           & \\texttt{EG\\_SCALE\\_E4SCINTILLATOR} \\\\\n    \\texttt{EL\\_EFF\\_Reco\\_TOTAL\\_1NPCOR\\_PLUS\\_UNCOR}          & \\texttt{EG\\_SCALE\\_LARCALIB\\_EXTRA2015PRE} \\\\\n    ~                                                           & \\texttt{EG\\_SCALE\\_LARTEMPERATURE\\_EXTRA2015PRE} \\\\\n    ~                                                           & \\texttt{EG\\_SCALE\\_LARTEMPERATURE\\_EXTRA2016PRE} \\\\\n    \\midrule\n    \\multicolumn{2}{c}{\\textbf{Muons}} \\\\\n    \\midrule\n    \\texttt{MUON\\_EFF\\_ISO\\_STAT}         & \\texttt{MUON\\_ID} \\\\\n    \\texttt{MUON\\_EFF\\_ISO\\_SYS}          & \\texttt{MUON\\_MS} \\\\\n    \\texttt{MUON\\_EFF\\_RECO\\_STAT}        & \\texttt{MUON\\_SAGITTA\\_RESBIAS} \\\\\n    \\texttt{MUON\\_EFF\\_RECO\\_STAT\\_LOWPT} & \\texttt{MUON\\_SAGITTA\\_RHO} \\\\\n    \\texttt{MUON\\_EFF\\_RECO\\_SYS}         & \\texttt{MUON\\_SCALE} \\\\\n    \\texttt{MUON\\_EFF\\_RECO\\_SYS\\_LOWPT}  & ~ \\\\\n    \\texttt{MUON\\_EFF\\_TTVA\\_STAT}        & ~ \\\\\n    \\texttt{MUON\\_EFF\\_TTVA\\_SYS}         & ~ \\\\\n    \\midrule\n    \\multicolumn{2}{c}{\\textbf{Jets}} \\\\\n    \\midrule\n    ~                            & \\texttt{JET\\_BJES\\_Response} \\\\\n    ~                            & \\texttt{JET\\_EffectiveNP\\_[1-7]} \\\\\n    ~                            & \\texttt{JET\\_EffectiveNP\\_8restTerm} \\\\\n    ~                            & \\texttt{JET\\_EtaIntercalibration\\_Modelling} \\\\\n    ~                            & \\texttt{JET\\_EtaIntercalibration\\_NonClosure\\_highE} \\\\\n    ~                            & \\texttt{JET\\_EtaIntercalibration\\_NonClosure\\_negEta} \\\\\n    ~                            & \\texttt{JET\\_EtaIntercalibration\\_NonClosure\\_posEta} \\\\\n    ~                            & \\texttt{JET\\_EtaIntercalibration\\_TotalStat} \\\\\n    ~                            & \\texttt{JET\\_Flavor\\_Composition} \\\\\n    ~                            & \\texttt{JET\\_Flavor\\_Response} \\\\\n    ~                            & \\texttt{JET\\_JER\\_DataVsMC} \\\\\n    ~                            & \\texttt{JET\\_JER\\_EffectiveNP\\_[1-6]} \\\\\n    ~                            & \\texttt{JET\\_JER\\_EffectiveNP\\_7restTerm} \\\\\n    ~                            & \\texttt{JET\\_Pileup\\_OffsetMu} \\\\\n    ~                            & \\texttt{JET\\_Pileup\\_OffsetNPV} \\\\\n    ~                            & \\texttt{JET\\_Pileup\\_PtTerm} \\\\\n    ~                            & \\texttt{JET\\_Pileup\\_RhoTopology} \\\\\n    ~                            & \\texttt{JET\\_PunchThrough\\_MC16} \\\\\n    ~                            & \\texttt{JET\\_SingleParticle\\_HighPt} \\\\\n    \\midrule\n    \\multicolumn{2}{c}{\\textbf{Other}} \\\\\n    \\midrule\n    \\texttt{HOEW\\_QCD\\_syst}    & ~ \\\\\n    \\texttt{HOEW\\_syst}         & ~ \\\\\n    \\texttt{HOQCD\\_scale\\_syst} & ~ \\\\\n    \\texttt{PRW\\_DATASF}        & ~ \\\\\n    \\bottomrule\n  \\end{tabular}\n  \\end{spacing}\n  \\label{tab:np_list}\n\\end{table}\n\\fi\n", "meta": {"hexsha": "d0b5dd4c9b020ee75b58472e8263c6019e17f645", "size": 11447, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/HMHZZ/syst.tex", "max_stars_repo_name": "zhuhel/PhDthesis", "max_stars_repo_head_hexsha": "55ec32affb5c105143798989d78043467c88da8e", "max_stars_repo_licenses": ["LPPL-1.3c"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/HMHZZ/syst.tex", "max_issues_repo_name": "zhuhel/PhDthesis", "max_issues_repo_head_hexsha": "55ec32affb5c105143798989d78043467c88da8e", "max_issues_repo_licenses": ["LPPL-1.3c"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/HMHZZ/syst.tex", "max_forks_repo_name": "zhuhel/PhDthesis", "max_forks_repo_head_hexsha": "55ec32affb5c105143798989d78043467c88da8e", "max_forks_repo_licenses": ["LPPL-1.3c"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.4906542056, "max_line_length": 245, "alphanum_fraction": 0.6642788504, "num_tokens": 3212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6791787121629465, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.30784579820768715}}
{"text": "\\section{UTxO}\n\\label{sec:utxo}\n\n\n\\subsection{UTxO Transitions}\n\\label{sec:utxo-trans}\n\nWe have added the following helper functions, which are used in defining the\nUTxO transition system, see Figure~\\ref{fig:functions:insouts}. These include:\n\n\\begin{itemize}\n  \\item the function $\\fun{getOut}$ builds a UTxO-type output out of a\n  transaction output\n  \\item the function $\\fun{outs}$ builds the MC UTxO entries from the outputs\n  of a transaction\n\\end{itemize}\n\n\\begin{figure}[htb]\n  \\begin{align*}\n    & \\fun{getOut} \\in \\TxOut \\to \\UTxOOut \\\\\n    & \\text{tx outputs transformed to UTxO outputs} \\\\\n    & \\fun{getOut} ~{txout}~= (\\fun{getAddr}~\\var{txout}, \\fun{getValue}~\\var{txout})\n    \\nextdef\n    & \\fun{outs} \\in \\TxBody \\to \\UTxO \\\\\n    & \\text{tx outputs as UTxO} \\\\\n    & \\fun{outs} ~\\var{txb} =\n        \\left\\{\n          (\\fun{txid} ~ \\var{txb}, \\var{ix}) \\mapsto \\fun{getOut}~\\var{txout} ~\n          \\middle|~\n          \\var{ix} \\mapsto \\var{txout} \\in \\txouts{txb}\n        \\right\\} \\\\\n  \\end{align*}\n  \\caption{Functions on Tx Inputs and Outputs}\n  \\label{fig:functions:insouts}\n\\end{figure}\n\n\\textbf{Value Operations and Partial Order.}\nSome of the UTxO update and precondition functions now operate on the $\\Value$\ntype instead of $\\Coin$ (sometimes on a combination of $\\Value$ and $\\Coin$).\nTo make this precise, we must define basic operations on $\\Value$, which\ninclude, most notably, addition and $\\leq$ comparison.\n\nThe type $\\Value$ has a partial order defined on it in (see~\\cite{plutus_eutxo}).\nThe idea of this partial order, as well as operations like addition and subtraction\nof terms of the $\\Value$ type, is that a term $v \\in \\Value$ can be treated\nas a total map that maps to the trivial element $\\epsilon \\in \\Token \\to \\Quantity$\nalmost everywhere except for a several currency IDs that appear in $\\dom~v$.\n\nThis way, when adding two terms of type value, $\\{ cid1 \\mapsto tkns1\\}$ and\n$\\{ cid2 \\mapsto tkns2\\}$, the result is\n\\[ \\{ cid1 \\mapsto (tkns1 + \\epsilon), cid2 \\mapsto (\\epsilon + tkns2)\\} \\]\n\nwhich simplifies to\n\n\\[ \\{ cid1 \\mapsto tkns1, cid2 \\mapsto tkns2\\} \\]\n\nThis definition of addition is also defined in Section~\\ref{sec:notation-shelley}.\nSimilarly, if we compare these two tokens, we compare them as follows\n(element-wise, with $\\epsilon$ as the value associated to any currency ID\nnot present in on of the values),\n\n\\[ (\\{ cid1 \\mapsto tkns1\\}~\\leq~\\{ cid2 \\mapsto tkns2\\}) \\Leftrightarrow \\\\\n   (tkns1 \\leq \\epsilon~\\wedge~ \\epsilon \\leq tkns2) \\]\n\n\\textbf{UTxO Helper Functions.}\n\nFigure~\\ref{fig:functions:utxo} defines additional calculations needed for the\nUTxO transition system with MC:\n\n\\begin{itemize}\n\n  \\item $\\fun{getCoin}$ adds up all the Ada in a given output and returns it as a\n  $\\Coin$ value\n\n  \\item $\\fun{utxoAda}$ returns the set of all the outputs in a UTxO with only Ada\n  tokens (the other tokens are ignored). This is used in the stake distribution\n  calculation at the epoch boundary\n\n  \\item\n    The $\\fun{ubalance}$ function calculates the (aggregated by currency ID and\n    Token) sum total of all the value in a given UTxO.\n\n  \\item The $\\fun{consumed}$ calculation is still the sum of the reward address\n   value consumed, the values of the UTxO entries consumed,\n   and the value consumed from the deposit pot due\n   to the transaction collecting deposit refunds. There is an additional\n   summand in this calculation, the value forged by a transaction.\n   This calculation now returns a $\\Value$.\n\n  \\item The $\\fun{produced}$ calculation sums up the same things\n  as the corresponding $\\fun{produced}$ calculation in Shelley.\n  This calculation also returns a $\\Value$.\n\\end{itemize}\n\n\\textbf{Produced and Consumed Calculations and Preservation of Value.}\nNote that\nthe $\\fun{consumed}$ and $\\fun{produced}$ calculations both produce a $\\Value$.\nThe reason for this is that the outputs of a transaction, as well as UTxO outputs,\nare of the $\\Value$ type. The administrative amounts (of the $\\Coin$ type)\nare converted into MC values for these summations.\n\nWhile the preservation of value is a single\nequality, it is really a comparison of token quantities aggregated by\n$\\Token$ and by $\\CurrencyID$. In particular, ensuring that the produced\namount equals the consumed amount also implies that the total quantity of\nAda tokens is preserved.\n\n\\textbf{Forging and the Preservation of Value.}\nWhat does it mean to preserve the value of non-Ada tokens, since they\nare put in and taken out of circulation by the users themselves?\nThis is expressed by including the $\\fun{forge}$ value of the transaction\nin the preservation of value equation.\n\nThe \\textit{produced} side of the equation adds up, among other things, the\nvalues in the\noutputs that will be added to the ledger UTxO by the transaction. These outputs are\nwhere the\nforged value is \"put into of circulation\", i.e. how it ends up in the UTxO.\nSuppose a transaction $tx$ contains a single output $(a, cid \\mapsto tkns)$. Suppose\nalso that it does not\nhave any inputs spending any UTxO outputs with currency ID $cid$.\n\nA valid transaction $tx$ satisfies the preservation of value\ncondition by adding the value $cid \\mapsto tkns$ to the \\textit{consumed} side as well.\nTo do this, the $tx$ declares that it is forging the tokens $cid \\mapsto tkns$\nvia the $\\fun{forge}$ field, i.e. $tx$ must have\n\n\\[cid \\mapsto tkns\\in\\fun{forge}~tx\\]\n\nThe forge field value is then added to the consumed side. This approach\nto balancing the POV equation extends\nto cases where the transaction might also be consuming some existing $cid$ tokens,\nor taking the out of circulation with negative quantities in the forge field.\n\nThe forge field value represents the change in total existing tokens of each given currency\nas a result of processing the transaction. It is always added to the\n\\textit{consumed} side of the POV equation because of this side, the signs of the\nquantities in the forge field match the signs of the change. That is,\nwhen tokens are added into the UTxO, their quantities are positive, and when they are\ntaken out of circulation via the forge field, the signs are negative.\n\nNote also that the UTXO rule only checks that the transaction is forging the\namount it has declared using the forge field (and that no Ada is forged).\nThe forging scripts themselves are not evaluated in this transition rule.\nThat step is part of witnessing, i.e. the UTXOW rule, see below.\n\n\\begin{figure}[htb]\n  \\emph{Helper Functions}\n  \\begin{align*}\n    & \\fun{getCoin} \\in \\UTxOOut \\to \\Coin \\\\\n    & \\fun{getCoin}~{\\var{out}} ~=~\\sum_{\\mathsf{adaID} \\mapsto tkns \\in \\fun{getValue}~out}\n       (\\sum_{q \\in \\range~{tkns}} \\fun{co}~q) \\\\\n    & \\text{sum total of amount of Ada in an output}\n    \\nextdef\n    & \\fun{utxoAda} \\in \\UTxO \\to \\powerset{(\\Addr \\times \\Coin)} \\\\\n    & \\fun{utxoAda}~{\\var{utxo}} ~=~\\{~(\\fun{getAddr}~\\var{out},~\\fun{getCoin}~{out})\n    ~\\vert~ \\var{out} \\in \\range~\\var{utxo} ~\\} \\\\\n    & \\text{returns the outputs in the UTxO with only the Ada coins} \\\\\n    \\nextdef\n    & \\fun{ubalance} \\in \\UTxO \\to \\Value \\\\\n    & \\fun{ubalance} ~ utxo = \\sum_{\\wcard\\mapsto\\var{u}\\in~\\var{utxo}}\n    \\fun{getValue}~\\var{u} \\\\\n    & \\text{UTxO balance} \\\\\n  \\end{align*}\n  %\n  \\emph{Produced and Consumed Calculations}\n  \\begin{align*}\n    & \\fun{consumed} \\in \\PParams \\to \\UTxO \\to \\StakeCreds \\to \\Wdrl \\to \\TxBody \\to \\Value \\\\\n    & \\consumed{pp}{utxo}{stkCreds}{rewards}~{txb} = \\\\\n    & ~~\\ubalance{(\\txins{txb} \\restrictdom \\var{utxo})} + \\\\\n    &~~  \\fun{coinToValue}(\\fun{wbalance}~(\\fun{txwdrls}~{txb})~\\\\\n        &~~+~ \\keyRefunds{pp}{stkCreds}{txb}) +\n        ~\\fun{forge}~\\var{txb} \\\\\n    & \\text{value consumed} \\\\\n    \\nextdef\n    & \\fun{produced} \\to \\PParams \\to \\StakePools \\to \\TxBody \\to \\Value \\\\\n    & \\fun{produced}~\\var{pp}~\\var{stpools}~\\var{txb} = \\\\\n    &~~\\ubalance{(\\fun{outs}~{txb})}  + \\fun{coinToValue}(\\txfee{txb} \\\\\n    &~~+ \\deposits{pp}{stpools}~{(\\txcerts{txb})})\\\\\n    & \\text{value produced} \\\\\n  \\end{align*}\n  \\caption{UTxO Calculations}\n  \\label{fig:functions:utxo}\n\\end{figure}\n\n\\clearpage\n\n\\textbf{The UTXO Transition Rule.}\nIn Figure \\ref{fig:rules:utxo-shelley}, we give the UTXO transition rule,\nupdated for MC support. There are the following changes to the preconditions\nof this rule as compared to the original Shelley UTXO rule:\n\n\\begin{itemize}\n  \\item The transaction is not forging any Ada\n\n  \\item All outputs of the transaction contain only non-negative quantities\n  (this is the $\\Value$-type version to the corresponding rule about non-negative\n  $\\Coin$ amounts in the Shelley ledger rules)\n\n  \\item In the preservation of value calculation (which looks the same as in\n  Shelly), the value in the $\\fun{forge}$ field is taken into account\n\\end{itemize}\n\nNote that updating the $\\UTxO$ with the inputs and the outputs of the transaction\nlooks the same as in the Shelley rule, however, there is a type-level difference.\nRecall that the outputs of a transaction contain a $\\Value$ term, rather than\n$\\Coin$. Moreover, the $\\fun{outs}$ map converts $\\TxOut$ terms into $\\UTxOOut$.\n\n\n\\begin{figure}[htb]\n  \\begin{equation}\\label{eq:utxo-inductive-shelley}\n    \\inference[UTxO-inductive]\n    { \\var{txb}\\leteq\\txbody{tx}\n      & \\txttl txb \\geq \\var{slot}\n      \\\\ \\txins{txb} \\neq \\emptyset\n      & \\minfee{pp}{tx} \\leq \\txfee{txb}\n      & \\txins{txb} \\subseteq \\dom \\var{utxo}\n      \\\\\n      \\consumed{pp}{utxo}{stkCreds}{rewards}~{txb} = \\produced{pp}{stpools}~{txb}\n      \\\\\n      ~\n      \\\\\n      {\n        \\begin{array}{r}\n          \\var{slot} \\\\\n          \\var{pp} \\\\\n          \\var{genDelegs} \\\\\n        \\end{array}\n      }\n      \\vdash \\var{ups} \\trans{\\hyperref[fig:rules:update]{up}}{\\fun{txup}~\\var{tx}} \\var{ups'}\n      \\\\\n      ~\n      \\\\\n      \\mathsf{adaID}~\\notin \\dom~{\\fun{forge}~tx} \\\\\n      \\forall txout \\in \\txouts{txb}, ~ \\fun{getValue}~txout  ~\\geq ~ \\epsilon \\\\~\n      \\\\\n      \\fun{txsize}~{tx}\\leq\\fun{maxTxSize}~\\var{pp}\n      \\\\\n      ~\n      \\\\\n      \\var{refunded} \\leteq \\keyRefunds{pp}{stkCreds}~{txb}\n      \\\\\n      \\var{decayed} \\leteq \\decayedTx{pp}{stkCreds}~{txb}\n      \\\\\n      \\var{depositChange} \\leteq\n        \\fun{totalDeposits}~{pp}{stpools}{(\\txcerts{txb})} - (\\var{refunded} + \\var{decayed})\n    }\n    {\n      \\begin{array}{r}\n        \\var{slot}\\\\\n        \\var{pp}\\\\\n        \\var{stkCreds}\\\\\n        \\var{stpools}\\\\\n        \\var{genDelegs}\\\\\n      \\end{array}\n      \\vdash\n      \\left(\n      \\begin{array}{r}\n        \\var{utxo} \\\\\n        \\var{deposits} \\\\\n        \\var{fees} \\\\\n        \\var{ups}\\\\\n      \\end{array}\n      \\right)\n      \\trans{utxo}{tx}\n      \\left(\n      \\begin{array}{r}\n        \\varUpdate{(\\txins{txb} \\subtractdom \\var{utxo}) \\cup \\fun{outs}{txb}}  \\\\\n        \\varUpdate{\\var{deposits} + \\var{depositChange}} \\\\\n        \\varUpdate{\\var{fees} + \\txfee{txb} + \\var{decayed}} \\\\\n        \\varUpdate{ups'}\\\\\n      \\end{array}\n      \\right)\n    }\n  \\end{equation}\n  \\caption{UTxO inference rules}\n  \\label{fig:rules:utxo-shelley}\n\\end{figure}\n\n\n\\clearpage\n\n\\textbf{Witnessing.}\n\nWe have changed the definition of the function\n$\\fun{scriptsNeeded}$, see Figure~\\ref{fig:functions-witnesses}. There is\nnow an additional category of scripts that are needed for transaction validation,\nthe forging scripts.\n\nNote that there are no restrictions on the use of forging scripts. Their hashes may\nbe used as credentials in UTxO entries, certificates, and withdrawals.\nNon-MPS type scripts can also be used for forging, e.g. MSig scripts.\n\nNote also that UTxO entries containing MC tokens, just like Shelley UTxO entries,\ncan be locked by a script. This script will add an additional set of\nrestrictions to the use of MC tokens (additional to the forging script\nrequirements, but enforced at spending time). This output-locking script can itself\nalso be a forging script.\n\n\\begin{figure}[htb]\n  \\begin{align*}\n    & \\hspace{-1cm}\\fun{scriptsNeeded} \\in \\UTxO \\to \\Tx \\to\n      \\powerset{\\ScriptHash}\n    & \\text{required script hashes} \\\\\n    &  \\hspace{-1cm}\\fun{scriptsNeeded}~\\var{utxo}~\\var{tx} = \\\\\n    & ~~\\{ \\fun{validatorHash}~a \\mid i \\mapsto (a, \\wcard) \\in \\var{utxo},\\\\\n    & ~~~~~i\\in\\fun{txinsScript}~{(\\fun{txins~\\var{txb}})}~{utxo}\\} \\\\\n    \\cup & ~~\\{ \\fun{stakeCred_{r}}~\\var{a} \\mid a \\in \\dom (\\AddrRWDScr\n           \\restrictdom \\fun{txwdrls}~\\var{txb}) \\} \\\\\n      \\cup & ~~(\\AddrScr \\cap \\fun{certWitsNeeded}~{txb}) \\\\\n      \\cup & ~~\\dom~(\\fun{forge}~{txb}) \\\\\n      & \\where \\\\\n      & ~~~~~~~ \\var{txb}~=~\\txbody{tx} \\\\\n  \\end{align*}\n  \\caption{Scripts Needed}\n  \\label{fig:functions-witnesses}\n\\end{figure}\n\n\n\n\\clearpage\n", "meta": {"hexsha": "cc46f3173f2387c98610934667dac1039ce07903", "size": 12599, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "shelley-mc/formal-spec/utxo.tex", "max_stars_repo_name": "kderme/cardano-ledger-specs", "max_stars_repo_head_hexsha": "29491f563344dba30db866cbf91efee3d1988430", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "shelley-mc/formal-spec/utxo.tex", "max_issues_repo_name": "kderme/cardano-ledger-specs", "max_issues_repo_head_hexsha": "29491f563344dba30db866cbf91efee3d1988430", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "shelley-mc/formal-spec/utxo.tex", "max_forks_repo_name": "kderme/cardano-ledger-specs", "max_forks_repo_head_hexsha": "29491f563344dba30db866cbf91efee3d1988430", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.1273291925, "max_line_length": 95, "alphanum_fraction": 0.6752123184, "num_tokens": 3912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.307845786434162}}
{"text": "\\vssub\n\\subsection{~Source terms}\n\\vsssub\n\\subsubsection{~General concepts}\n\\vsssub\n\nIn deep water, the net source term $S$ is generally considered to consist of\nthree parts, an atmosphere-wave interaction term $S_{\\mathrm{in}}$, which \nis usually a positive energy input but can also be negative in the case of swell, a nonlinear wave-wave\ninteractions term $S_{\\mathrm{nl}}$ and a wave-ocean interaction term that is generally dominated by wave breaking\n$S_{\\mathrm{ds}}$. The input term $S_{\\mathrm{in}}$ is dominated by the\nexponential wind-wave growth term, and this source term generally describes this\ndominant process only. For model initialization, and to provide more realistic\ninitial wave growth, a linear input term $S_{\\mathrm{ln}}$ can also be added in\n\\ws.\n\nIn shallow water additional processes have to be considered, most notably\nwave-bottom interactions $S_{\\mathrm{bot}}$ \\cite[e.g.,][]{pro:Sea78}. In extremely\nshallow water, an additional  breaking term ($S_{\\mathrm{db}}$) should be considered,  \nif not well represented in  $S_{\\mathrm{ds}}$ \\citep[see][]{Filipot&Ardhuin2012}.\nTriad wave-wave\ninteractions ($S_{\\mathrm{tr}}$) may also be considered, but present parameterizations have limited accuracy. \nAlso available in \\ws\\ are source\nterms for scattering of waves by bottom features ($S_{\\mathrm{sc}}$), wave-ice\ninteractions ($S_{\\mathrm{ice}}$), reflection off shorelines or floating objects such\nas icebergs which can include sources of infragravity wave energy ($S_{\\mathrm{ref}}$),  and a general purpose slot for additional, user\ndefined source terms ($S_{\\mathrm{user}}$).\n\nThis defines the general source terms used in \\ws\\ as\n\n%---------------------------------%\n% General source term composition %\n%---------------------------------%\n% eq:general_st\n\n\\begin{equation}\nS = S_{\\mathrm{ln}} + S_{\\mathrm{in}} + S_{\\mathrm{nl}} + S_{\\mathrm{ds}} + S_{\\mathrm{bot}} + S_{\\mathrm{db}} \n    + S_{\\mathrm{tr}} +\n    S_{\\mathrm{sc}} + S_{\\mathrm{ice}} + S_{\\mathrm{ref}} + S_{\\mathrm{user}}\\: .\n\\label{eq:general_st}\n\\end{equation}\n\n\\noindent\nOther source terms could be easily added. Those source terms are defined for the\n{\\em energy} spectra. In the model, however, most source terms are directly\ncalculated for the action spectrum. The latter source terms are denoted as\n$\\cS \\equiv S/\\sigma$.\n\nThe explicit treatment of the nonlinear interactions defines third-generation wave\nmodels. Therefore, the options for the calculation of $S_{\\mathrm  nl}$ will be\ndiscussed first, starting in section \\ref{sec:NL1}. $S_{\\mathrm  in}$ and $S_{\\mathrm ds}$\nrepresent separate processes, but are often interrelated,\nbecause the balance of these two source terms governs the integral growth\ncharacteristics of the wave energy. Several combinations of these basic source\nterms are available, and are described in section~\\ref{sec:ST1} and following.\nThe description of linear input starts in section~\\ref{sec:LN1}, and\nsection~\\ref{sec:BT1} and following describe available additional processes, mostly\nrelated to shallow water and sea ice. \n\n%\\vspace{\\baselineskip} \\noindent\n\nA third-generation wave model effectively integrates the spectrum only up to a\ncut-off frequency $f_{hf}$ (or wavenumber $k_{hf}$), that is ideally equal to the \nhighest discretization frequency. In practice the source terms parameterization or the time step used may not allow a proper \nbalance to be obtained, and thus $f_{hf}$  may be taken within the model frequency range. Above the cut-off frequency a\nparametric tail is applied \\citep[e.g.,][]{art:WAM88}\n\n%--------------------------------------%\n% General tail parameterization E(f,t) %\n%--------------------------------------%\n% eq:tail_E_f\n\n\\begin{equation}\nF(f_r,\\theta) = F(f_{r,hf},\\theta) \\left ( \\frac{f_r}{f_{r,hf}}\n\\right ) ^{-m} \\label{eq:tail_E_f} ,\n\\end{equation}\n\n\\noindent\nwhich is easily transformed to any other spectrum using the Jacobian\ntransformations as discussed above. For instance, for the present action\nspectrum, the parametric tail can be expressed as (assuming deep water for the\nwave components in the tail)\n\n%--------------------------------------%\n% General tail parameterization N(k,t) %\n%--------------------------------------%\n% eq:tail_N_k\n\n\\begin{equation}\nN(k,\\theta) = N(k_{hf},\\theta) \\left ( \\frac{f_r}{f_{r,hf}}\n\\right ) ^{-m-2} \\label{eq:tail_N_k} ,\n\\end{equation}\n\n\\noindent\nthe actual values of $m$ and the expressions for $f_{r,hf}$ depend on the\nsource term parameterization used, and will be given below.\n\n%\\vspace{\\baselineskip} \\noindent\nBefore actual source term parameterizations are described, the definition of\nthe wind requires some attention. In cases with currents, one can either\nconsider the wind to be defined in a fixed frame of reference, or in a frame\nof reference moving with the current. Both definitions are available in \\ws,\nand can be selected during compilation. The output of the program, however,\nwill always be the wind speed which is not in any way corrected for the\ncurrent.\n\n%\\vspace{\\baselineskip} \\noindent\nThe treatment of partial ice coverage (ice concentration) in the source terms\nfollows the concept of a limited air-sea interface. This means that the momentum\ntransferred from the atmosphere to the waves is limited. Therefore, input and\ndissipation terms are scaled by the fraction of ice concentration. The\nnonlinear wave-wave interaction term can be used in areas of open water\nand ice \\citep{art:PL07}. The scaling is implemented so that it is independent\nof the source term selected.\n\n", "meta": {"hexsha": "dfaac8ea66335529f698352d263178ec334e5298", "size": 5531, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "WW3/manual/eqs/source.tex", "max_stars_repo_name": "minsukji/ci-debug", "max_stars_repo_head_hexsha": "3e8bbbe6652b702b61d2896612f6aa8e4aa6c803", "max_stars_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WW3/manual/eqs/source.tex", "max_issues_repo_name": "minsukji/ci-debug", "max_issues_repo_head_hexsha": "3e8bbbe6652b702b61d2896612f6aa8e4aa6c803", "max_issues_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-05-31T15:49:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-04T14:17:45.000Z", "max_forks_repo_path": "WW3/manual/eqs/source.tex", "max_forks_repo_name": "minsukji/ci-debug", "max_forks_repo_head_hexsha": "3e8bbbe6652b702b61d2896612f6aa8e4aa6c803", "max_forks_repo_licenses": ["Apache-2.0", "CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-01T09:29:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T09:29:46.000Z", "avg_line_length": 47.6810344828, "max_line_length": 136, "alphanum_fraction": 0.7295244983, "num_tokens": 1415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.3078118686435651}}
{"text": "\\section{Second-order correlation analysis}\n\nIn this section, we analyse the effectiveness of the implemented countermeasures against second-order side-channel analysis based on the linear correlation coefficient (CPA). For this study, we will target the Sbox output value and consider a Hamming weight ($HW$) univariate leakage model.\n\nIn the remainder of this section, we will use:\n\\begin{itemize}\n\n\\item the centered product combination function $\\mathcal{C}(x,y) = (x-\\bar{x})(y-\\bar{y})$ to preprocess the traces, where $\\bar{x}$ (resp. $\\bar{y}$) stands for the mean value of $x$ (resp. $y$), computed on all traces in our campaign; \n\n\\item the corresponding function $f_{HW}(z) = \\sum_m (HW(z \\oplus m) - \\overline{HW(z\\oplus m)})\\\\(HW(m)-\\overline{HW(m)})$ to compute the predictions, where $\\overline{HW(m)}$ (resp $\\overline{HW(z \\oplus m)}$) stands for the mean value of $HW(m)$ (resp. $HW(z\\oplus m)$) computed on all possible values of $m$\\footnote{Note that all possible values for $m$ are in $[0,255]$.}.\n\\end{itemize}\n\nAs in our first-order correlation analysis, we will split this study in two parts. The first part will consider priviledged knowledge on the mask values. The second part will not take this knowledge into account.\n\n\\subsection{Priviledged knowledge}\nWe first study the setting where the attacker knows the random masks used to compute the permutation. \nIn order to characterize the effectiveness of a CPA against this implementation, we use the random masks to recompute the permutation $Sh(i)$ for each byte index $i$.\n\nFor each byte index $i$, we use the characterization phase to isolate a window $w_{z\\oplus m}$ of $11$ points of interest corresponding to the manipulation of the Sbox output $\\rmult \\times S[P[Sh(i)\\oplus K[Sh(i)]] \\oplus \\rout$, and a window $w_m$ of $11$ points of interest corresponding to the manipulation of the mask value $\\rout$. For each couple $(i,j)$ of points in $w_{z\\oplus m} \\times w_m$, we apply the combination function $\\mathcal{C}(i,j)$.\n\n\\noindent We then perform an attack targeting the value $Z_{\\hat{k}}[i]=S[P[Sh(i)] \\oplus K[Sh(i)] \\oplus \\hat{k}]$, where $\\hat{k}$ is an hypothesis on a value of one byte.\n\n\n\\subsubsection{Multiplicatively masked Sbox output}\nWe suppose the knowledge of the multiplicative mask $\\rmult$. This knowledge allows for the prediction of the value $\\rmult \\times Z_{\\hat{k}}[i]$ for any hypothesis $\\hat{k}$.\nThe attack succeeds with around $8.000$ traces to $20.000$ traces.\nFigure~\\ref{fig:CPA2O_trickedaZ1} illustrates the results using $20.000$ traces.\n\n\\begin{figure}[H]\n\t\\centering \n\t\\includegraphics[scale=0.35]{figures/CPA2O_trickedaZ1.png}\n\t\\caption{Correlation coefficients obtained when targeting $\\rmult \\times S[P[i]\\oplus \\hat{k}] $, for every value of $\\hat{k}$. Correct hypothesis plotted in red. X-axis represents all 121 points combinations.}\n\t\\label{fig:CPA2O_trickedaZ1}\n\\end{figure}\n\n\n\\subsubsection{Raw Sbox output}\nWe target the value $Z_{\\hat{k}}[i]$ for any hypothesis $k$.\nThe attack does not succeed using the $100.000$ traces.\nFigure~\\ref{fig:CPA2O_trickedZ1} illustrates the results using $100.000$ traces.\n\n\\begin{figure}[H]\n\t\\centering \n\t\\includegraphics[scale=0.35]{figures/CPA2O_trickedZ1.png}\n\t\\caption{Correlation coefficients obtained when targeting $S[P[i]\\oplus \\hat{k}] $, for every value of $\\hat{k}$. Correct hypothesis plotted in red. X-axis represents all 121 points combinations.}\n\t\\label{fig:CPA2O_trickedZ1}\n\\end{figure}\n\n\n\\subsection{Unknown permutation, processed traces}\nWe now study the setting where the attacker does not know the random masks used to compute the permutation.\nWe preprocess the traces in order to average the leakage over the different byte indices manipulation:\n\\begin{itemize}\n\t\\item for each index $i$ in $[0,15]$, we define a small window $w_i$ of $\\ell$ points around the SNR peak corresponding to the manipulation of $\\rmult \\times S[P[Sh(i)] \\oplus K[Sh(i)]]\\oplus \\rout$ in the characterization phase. In our experiments, the size of the window was arbitrarily fixed to $\\ell=11$.\n\t\\item for each trace in our acquisition campaign, we compute the average window $m$ such that for each time sample $j$, $m[j]=\\frac{1}{16}\\sum_{i=0}^{15} w_i[j]$. We then consider $m$ as our reduced averaged trace of size $\\ell$.\n\t\\item we concatenate to this trace a small window of $\\ell$ points around the SNR peak corresponding to the manipulation of $\\rout$.\n\\end{itemize}\n\n\\subsubsection{Multiplicatively masked Sbox output}\nWe suppose the knowledge of the multiplicative mask $\\rmult$. This knowledge allows for the prediction of the value $\\rmult \\times Z_{\\hat{k}}[i]$ for any hypothesis $\\hat{k}$.\nThe attack is unsuccessful using $100.000$ traces.\n\nFigure~\\ref{fig:CPA2O_averagedaZ1} illustrates the results using $100.000$ traces.\n\\begin{figure}[H]\n\t\\centering \n\t\\includegraphics[scale=0.35]{figures/CPA2O_averagedaZ1.png}\n\t\\caption{Correlation coefficients obtained when targeting $\\rmult \\times S[P[i]\\oplus \\hat{k}] $, for every value of $\\hat{k}$. Correct hypothesis plotted in red. X-axis represents all 121 points combinations.}\n\t\\label{fig:CPA2O_averagedaZ1}\n\\end{figure}\n\nHowever, we observe that, for certain combinations of points (around abscissa 135), the correct hypothesis is indeed the most likely. Furthermore, the rank convergence of the key, plotted on Figure~\\ref{fig:convergence}, might indicate that the attack could be successful when using more traces.\n\n\\begin{figure}[H]\n\t\\centering \n\t\\includegraphics[scale=0.35]{figures/convergence.png}\n\t\\caption{Rank of the ten best-ranked keys, by steps of 10000 measurements, from $10.000$ to $100.000$. Correct key plotted in red.}\n\t\\label{fig:convergence}\n\\end{figure}\n\n\\subsubsection{Raw Sbox output}\nWe target the value $Z_{\\hat{k}}[i]$ for any hypothesis $\\hat{k}$.\nThe attack does not succeed using the $100.000$ traces.\nFigure~\\ref{fig:CPA2O_averagedZ1} illustrates the results using $100.000$ traces.\n\\begin{figure}[H]\n\t\\centering \n\t\\includegraphics[scale=0.35]{figures/CPA2O_averagedZ1.png}\n\t\\caption{Correlation coefficients obtained when targeting $S[P[i]\\oplus \\hat{k}] $, for every value of $\\hat{k}$. Correct hypothesis plotted in red. X-axis represents all 121 points combinations.}\n\t\\label{fig:CPA2O_averagedZ1}\n\\end{figure}\n\n\n\\subsection{Unknown permutation, non-processed traces}\nFor the sake of completeness, we also perform these experiments on raw unprocessed traces. No success is obtained when targeting $Z_{\\hat{k}}[i]$ or $\\rmult \\times Z_{\\hat{k}}[i]$.\n\nNo attack is successful using $100.000$ traces.\n\n\\subsection{Summary}\nThis section evidences the effectiveness of the implemented countermeasures. \nThe shuffling countermeasures increases the number of needed measurements by a factor of at least $\\frac{100.000}{8.000} = 12,5$. It is however likely that this countermeasure does not suffice when increasing slightly the number of measurements.\nThe effectiveness of the affine countermeasure is evidenced by the fact that a 2OCPA is achievable targeting the value $\\rmult \\times S[P[i] \\oplus \\hat{k}]$\nbut no attack is found targeting the value $S[P[i] \\oplus \\hat{k}]$ using $100.000$ traces.\n\n\\begin{figure}[h!]\n\\centering\n\\begin{tabular}{|c|c|c|c|c|}\n  \\hline\n   & \\multicolumn{2}{c|}{Known permutation}&\\multicolumn{2}{c|}{Unknown permutation}\\\\\n  \\hline\n  Known & $\\rmult $ &  None  & $\\rmult $  &  None \\\\\n  \\hline\n  \\# Traces& $\\approx 8.000$ & $ > 100.000$ & $ > 100.000$ & $> 100.000$\\\\\n  \\hline\n\\end{tabular}\n\\caption{Number of traces needed for a successful second-order attack, in the different settings.}\n\\end{figure}\n\n\n", "meta": {"hexsha": "1c539f815a33a2d061a86431f08ce80c3cd00e4b", "size": 7605, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/technical-report/second_order.tex", "max_stars_repo_name": "CroixDrinkers/SecAESSTM32", "max_stars_repo_head_hexsha": "71d356a1141624994cf613bd2d2583892e8e6d5a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 51, "max_stars_repo_stars_event_min_datetime": "2019-05-09T16:49:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T19:31:22.000Z", "max_issues_repo_path": "doc/technical-report/second_order.tex", "max_issues_repo_name": "CroixDrinkers/SecAESSTM32", "max_issues_repo_head_hexsha": "71d356a1141624994cf613bd2d2583892e8e6d5a", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-05-21T09:50:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-30T10:48:52.000Z", "max_forks_repo_path": "doc/technical-report/second_order.tex", "max_forks_repo_name": "CroixDrinkers/SecAESSTM32", "max_forks_repo_head_hexsha": "71d356a1141624994cf613bd2d2583892e8e6d5a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2019-05-10T00:53:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-21T05:11:45.000Z", "avg_line_length": 64.4491525424, "max_line_length": 456, "alphanum_fraction": 0.7475345168, "num_tokens": 2137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.3078118620503049}}
{"text": "\n\\chapter{Reference Manual --- VertEgg Version 0.9}\n\n\\section{Overview of the Toolbox}\n\nThe VertEgg toolbox  presently contain  the following tools,\ngrouped here according to functionality.\n\n\\begin{itemize}\n  \\item Initialise VertEgg\n    \\begin{itemize}\n      \\item \\edb{ve\\_init}\n      \\item \\edb{ve\\_grid(Hcol, dz)}\n    \\end{itemize}  \n  \\item Make initial egg distribution\n    \\begin{itemize}\n      \\item \\edb{spawn(M, Z)}\n      \\item \\edb{ve\\_rand(M)}\n    \\end{itemize}  \n  \\item Compute the stationary solution\n    \\begin{itemize}\n      \\item \\edb{eggsact(M, K, W, Z)}\n      \\item \\edb{srcsact(K, W, P, alpha)}\n      \\item \\edb{sstate(M, K, W)}\n    \\end{itemize}  \n  \\item Solve the transient problem numerically\n    \\begin{itemize}\n      \\item \\edb{fluxlim(A0, K, W, nstep, dt, P, alpha)}\n      \\item \\edb{ftcs(A0, K, W, nstep, dt, P, alpha)}\n      \\item \\edb{lwendrof(A0, K, W, nstep, dt, P, alpha)}\n      \\item \\edb{upstream(A0, K, W, nstep, dt, P, alpha)}\n    \\end{itemize} \n  \\item Compute terminal egg velocity\n    \\begin{itemize}\n      \\item \\edb{dens0(S, T)}\n      \\item \\edb{eggvel(drho, d, mu)}\n      \\item \\edb{eggvelst(S, T, d, Se)}\n      \\item \\edb{molvisc(S, T)}\n    \\end{itemize} \n  \\item Analyse distributions\n    \\begin{itemize}\n      \\item \\edb{eggmom(A, p)}\n      \\item \\edb{ve\\_drint(A, z1, z2)}\n      \\item \\edb{ve\\_int(A)}\n      \\item \\edb{ve\\_mean(A)}\n      \\item \\edb{ve\\_std(A)}\n      \\item \\edb{ve\\_rmsd(A, B)}\n    \\end{itemize} \n\\end{itemize}\n\n\n\\section{Description of the Tools}\n\n\n{\\parindent=0pt\n\n\n\\thead{dens0}{Sigma-T of sea water at zero pressure}\n\n\\begin{tdesc}\n\\item[Usage] \\edb{sigma = dens0(S, T)}\n\\item[Input]\n  \\begin{vartab}\n    \\edb{S}  \\> : \\> Salinity     \\>   [psu]   \\\\\n    \\edb{T}  \\> : \\> Temperature  \\>   [\\degC] \n  \\end{vartab}\n  \\edb{S} and \\edb{T} may be arrays of the same shape.\n\\item[Output]\n  \\begin{vartab}\n    \\edb{sigma} \\> : \\> Sigma-T value \\>  [\\kgpcum] \n  \\end{vartab}\n  \\edb{sigma} is an array of the same shape as \\edb{S} and \\edb{T}.\n\\item[Description] \\mbox{}\\\\\n  \\edb{dens0} computes the $\\sigma_T$ value (density - 1000)\n  of sea water at zero pressure.\n  The density is computed by the international equation\n  of state for sea water, UNESCO, 1980.\n\\end{tdesc}\n\n\n\\thead{eggmom}{Moment of egg distribution}\n\n\\begin{tdesc}\n\\item[Usage] \\edb{M = eggmom(A, p)}\n\\item[Input]\n  \\begin{vartab}\n  \\edb{A}   \\> : \\> Egg distribution \\>  [eggs/m$^3$] \\\\\n  \\edb{p}   \\> : \\> Order of moment  \n  \\end{vartab}\n  \\edb{A} must be a matrix where the columns live on egg-points,\n  but a row-vector at egg-points is also accepted,\n  \\edb{size(A) = (Ncell x n)} or \\edb{(1 x Ncell)}\n\\item[Output]\n  \\begin{vartab}\n  \\edb{M}  \\>  : \\> The \\edb{p}-th moment of \\edb{A} \\> [eggs m$^{p-2}$]\n  \\end{vartab}\n  If \\edb{A} is a matrix of size \\edb{(Ncell x n)}, \\edb{M} becomes a \n  row-vector of length n containing the moments of\n  the columns of \\edb{A}. \\edb{p} must not be negative.\n\\item[Description]\\mbox{}\\\\\n  Computes the \\edb{p}-th moment of the egg-distribution \\edb{A},\n  \\begin{displaymath}\n      M = \\int^0_{-H} z^p a(z) dz\n  \\end{displaymath}\n   where $a(z)$ is the piecewise constant function \n   $a(z) = \\edb{A(i)}$ for $\\edb{ZF(i+1)} < z < \\edb{ZF(i)}$.\n   If \\edb{A} is a matrix, the moments of the columns are\n   calculated.\n\\end{tdesc}\n\n\n\\thead{eggsact}{Exact stationary solution, const. coeff.}\n\n\\begin{tdesc}\n\\item[Usage] \\edb{A = eggsact(M, K, W, Z)}\n\\item[Input]\n  \\begin{vartab}\n  \\edb{M}   \\> : \\> Vertical integrated concentration \\>  [eggs/m$^2$] \\\\\n  \\edb{K}   \\> : \\> Eddy diffusivity     \\> [\\sqmps] \\\\\n  \\edb{W}   \\> : \\> Terminal velocity   \\>  [\\mps] \\\\\n  \\edb{Z} (opt) \\> : \\> Vertical coordinate  \\> [\\m] \n  \\end{vartab}\n  \\edb{M}, \\edb{K}, \\edb{W} are scalars. \\edb{Z} can be arbitrary array.\n  IF \\edb{Z} is omitted, \\edb{ZE} is used as vertical coordinates.\n\\item[Output]\n  \\begin{vartab}\n  \\edb{A}     \\>  : \\> Concentration at depth \\edb{Z} \\> [eggs/m$^3$]\n  \\end{vartab}\n  If \\edb{Z} is present, \\edb{size(A) = size(Z)},\n  otherwise, \\edb{size(A) = size(ZE)}.\n\\item[Description]\n   Computes the exact stationary solution of the\n   convection diffusion equation with constant\n   eddy diffusivity \\edb{K} and velocity \\edb{W}.\n   If \\edb{Z} is present, returns array of pointwise values.\n   If \\edb{Z} is not present, returns exact cell averages.\n\\end{tdesc}\n\n\\thead{eggvel}{Terminal egg velocity}\n\n\\begin{tdesc}\n\\item[Usage] \\edb{[W, Re] = eggvel(drho, d, mu)}\n\\item[Input]\n   \\begin{vartab}\n   \\edb{drho}  \\> : \\> Buoyancy of egg  \\> [\\kgpcum] \\\\\n   \\edb{d}     \\> : \\> Diameter of egg  \\> [\\m] \\\\\n   \\edb{mu} (opt) \\> : \n         \\> Dynamic molecular viscosity \\>   [kgm$^{-1}$s$^{-1}$] \n   \\end{vartab}\n   \\edb{drho}, \\edb{d} and \\edb{mu} can be matrices (of the same shape).\n   \\edb{mu} can be also be a scalar or omitted.\n   The sign of \\edb{drho} is positive if the egg is ascending,\n   \\edb{drho} = Density of water - density of egg. With only two arguments,\n   a default value 0.0016 is used for \\edb{mu}. \n\\item[Output]\n  \\begin{vartab}\n  \\edb{W}   \\> : \\> Terminal velocity  \\> [\\mps] \\\\\n  \\edb{Re} (opt) \\> : \\> Reynolds number\n  \\end{vartab}\n\\item[Description]\n  Computes the terminal velocity of a small sphere in sea water\n  by the formulas in Stokes' or Dallavalles formula.\n\\end{tdesc}\n\n\n\\thead{eggvelst}{Egg velocity from salinity and temperature}\n\n\\begin{tdesc}\n\\item[Usage] \\edb{[W, Re] = eggvelst(S, T, d, Se)}\n\\item[Input]\n  \\begin{vartab}\n  \\edb{S}  \\>  : \\> Salinity of the environment \\> [psu]   \\\\\n  \\edb{T}  \\>  : \\> Temperature                 \\> [\\degC] \\\\\n  \\edb{d}  \\>  : \\> Egg diameter                \\> [m]     \\\\\n  \\edb{Se} \\>  : \\> Egg salinity                \\> [psu]\n  \\end{vartab}\n  All arguments can be arrays of the same shape.\n  Alternatively \\edb{d} and/or \\edb{Se} may be scalars.\n\\item[Output]\n  \\begin{vartab}\n  \\edb{W}    \\> : \\> Terminal velocity  \\> [\\mps] \\\\\n  \\edb{Re} (opt) \\> : \\> Reynolds number\n  \\end{vartab}\n\\item[Description]\\mbox{}\\\\\n  Computes the terminal egg velocity given the hydrography\n  of the environment and the salinity \\edb{Se} where the egg is\n  neutral buoyant.\n\\end{tdesc}\n\n\\thead{fluxlim}{Numerical integration of transport equation}\n\n\\begin{tdesc}\n\\item[Usage] \\edb{A = fluxlim(A0, K, W, nstep, dt, P, alpha)}\n\\item[Input]\n  \\begin{vartab}\n  \\edb{A0}  \\> : \\> Start concentration \\>  [eggs/m$^3$] \\\\\n  \\edb{K}   \\> : \\> Eddy diffusivity    \\>  [\\sqmps]  \\\\\n  \\edb{W}   \\> : \\> Terminal velocity   \\>  [\\mps]  \\\\\n  \\edb{nstep}  \\> : \\> Number of integration steps \\\\\n  \\edb{dt}     \\> : \\> Time step           \\>  [s] \\\\\n  \\edb{P}     (opt) \\> : \\> Spawning term       \\>  [eggs/m$^3$/s] \\\\\n  \\edb{alpha} (opt) \\> : \\> Loss coefficient \\> [1/s] \n  \\end{vartab}\n  \\edb{A0} lives at the egg-points, \\edb{size(A0) = (Ncell x 1)}.\n  \\edb{K} and \\edb{W} live at the flux-points, \\edb{size = (Ncell+1 x1)}.\n  If \\edb{P} and \\edb{alpha} are present, they also live at the egg-points.\n  If \\edb{P} and \\edb{alpha} are missing, the source term is ignored. \n\\item[Output]\n  \\begin{vartab}\n  \\edb{A} \\>  : \\> Result concentration \\> [eggs/m$^3$]\n  \\end{vartab}\n  \\edb{A} lives at egg-points in the same way as \\edb{A0}\n\\item[Description]\\mbox{}\\\\\n  Integrates the convection-diffusion equation by the \n  flux-limited method. Starting with the concentration \n  in \\edb{A0} nstep integration steps  are performed. \n  The result is saved in \\edb{A}.\n\\end{tdesc}\n\n\n\\thead{ftcs}{Numerical integration of transport equation}\n\n\\begin{tdesc}\n\\item[Usage] \\edb{A = ftcs(A0, K, W, nstep, dt, P, alpha)}\n\\item[Input]\n  \\begin{vartab}\n  \\edb{A0}  \\> : \\> Start concentration \\>  [eggs/m$^3$] \\\\\n  \\edb{K}   \\> : \\> Eddy diffusivity    \\>  [\\sqmps]  \\\\\n  \\edb{W}   \\> : \\> Terminal velocity   \\>  [\\mps]  \\\\\n  \\edb{nstep}  \\> : \\> Number of integration steps \\\\\n  \\edb{dt}     \\> : \\> Time step           \\>  [s] \\\\\n  \\edb{P}     (opt) \\> : \\> Spawning term       \\>  [eggs/m$^3$/s] \\\\\n  \\edb{alpha} (opt) \\> : \\> Loss coefficient \\> [1/s] \n  \\end{vartab}\n  \\edb{A0} lives at the egg-points, \\edb{size(A0) = (Ncell x 1)}.\n  \\edb{K} and \\edb{W} live at the flux-points, \\edb{size = (Ncell+1 x1)}.\n  If \\edb{P} and \\edb{alpha} are present, they also live at the egg-points.\n  If \\edb{P} and \\edb{alpha} are missing, the source term is ignored. \n\\item[Output]\n  \\begin{vartab}\n  \\edb{A} \\>  : \\> Result concentration \\> [eggs/m$^3$]\n  \\end{vartab}\n  \\edb{A} lives at egg-points in the same way as \\edb{A0}\n\\item[Description]\\mbox{}\\\\\n  Integrates the convection-diffusion equation by the \n  forward time central space (FTCS)  method. Starting \n  with the concentration in \\edb{A0} nstep integration steps \n  are performed. The result is saved in \\edb{A}.\n\\end{tdesc}\n\n\n\n\n\\thead{lwendrof}{Numerical integration of transport equation}\n\n\\begin{tdesc}\n\\item[Usage] \\edb{A = lwendrof(A0, K, W, nstep, dt, P, alpha)}\n\\item[Input]\n  \\begin{vartab}\n  \\edb{A0}  \\> : \\> Start concentration \\>  [eggs/m$^3$] \\\\\n  \\edb{K}   \\> : \\> Eddy diffusivity    \\>  [\\sqmps]  \\\\\n  \\edb{W}   \\> : \\> Terminal velocity   \\>  [\\mps]  \\\\\n  \\edb{nstep}  \\> : \\> Number of integration steps \\\\\n  \\edb{dt}     \\> : \\> Time step           \\>  [s] \\\\\n  \\edb{P}     (opt) \\> : \\> Spawning term       \\>  [eggs/m$^3$/s] \\\\\n  \\edb{alpha} (opt) \\> : \\> Loss coefficient \\> [1/s] \n  \\end{vartab}\n  \\edb{A0} lives at the egg-points, \\edb{size(A0) = (Ncell x 1)}.\n  \\edb{K} and \\edb{W} live at the flux-points, \\edb{size = (Ncell+1 x1)}.\n  If \\edb{P} and \\edb{alpha} are present, they also live at the egg-points.\n  If \\edb{P} and \\edb{alpha} are missing, the source term is ignored. \n\\item[Output]\n  \\begin{vartab}\n  \\edb{A} \\>  : \\> Result concentration \\> [eggs/m$^3$]\n  \\end{vartab}\n  \\edb{A} lives at egg-points in the same way as \\edb{A0}\n\\item[Description]\\mbox{}\\\\\n  Integrates the convection-diffusion equation by the \n  Lax-Wendroff method. Starting with the concentration\n  in \\edb{A0} nstep integration steps are performed. The \n  result is saved in \\edb{A}.\n\\end{tdesc}\n\n\\thead{molvisc}{Dynamical molecular viscosity of sea water}\n\n\\begin{tdesc}\n\\item[Usage] \\edb{mu = molvisc(S, T)}\n\\item[Input]\n  \\begin{vartab}\n    \\edb{S}     \\> : \\> Salinity     \\>   [psu]   \\\\\n    \\edb{T}     \\> : \\> Temperature  \\>   [\\degC] \n  \\end{vartab}\n  \\edb{S} and \\edb{T} may be arrays of the same shape.\n\\item[Output]\n  \\begin{vartab}\n    \\edb{mu} \\> : \\> Dynamic molecular viscosity \\>  [kgm$^{-1}$s$^{-1}$] \n  \\end{vartab}\n  \\edb{mu} is an array of the same shape as \\edb{S} and \\edb{T}.\n\\item[Description] \\mbox{}\\\\\n  Computes the dynamic molecular viscosity by formula~\\eqref{eq:molvisc}.\n\\end{tdesc}\n\n\n\\thead{spawn}{Make concentrated egg distribution}\n\n\\begin{tdesc}\n\\item[Usage] \\edb{A = spawn(M, Z)}\n\\item[Input]\n  \\begin{vartab}\n  \\edb{M} \\> : \\> Vertical integrated concentration \\>  [eggs/m$^2$] \\\\\n  \\edb{Z} \\> : \\> Spawning depth              \\>       [m]\n  \\end{vartab}\n  \\edb{M} and \\edb{Z} are scalars.\n\\item[Output]\n  \\begin{vartab}\n  \\edb{A}  \\> : \\> Egg distribution     \\>        [eggs/m$^3$]\n  \\end{vartab}\n  \\edb{A} is a column vector, living at the egg points.\n\\item[Description]\\mbox{}\\\\\n  Returns a vertical egg distribution \\edb{A} with vertical\n  integral \\edb{M}, concentrated as much as possible around \n  depth = \\edb{Z}.\n  If $\\edb{ZE(Ncell)} < \\edb{Z} < \\edb{ZE(1)}$, then \\edb{Z = ve\\_mean(A)}.\n\\end{tdesc}\n\n\n\\thead{srcsact}{Stationary solution, const. coeff., source term}\n\n\\begin{tdesc}\n\\item[Usage] \\edb{A = srcsact(K, W, P, alpha, Z)}\n\\item[Input]\n  \\begin{vartab}\n    \\edb{K} \\> : \\> Eddy diffusivity  \\>  [\\sqmps] \\\\\n    \\edb{W} \\> : \\> Terminal velocity \\>  [\\mps] \\\\\n    \\edb{P} \\> : \\> Egg production    \\>  [eggs/m$^3$/s] \\\\\n    \\edb{alpha} \\> : \\> Egg loss rate  \\>       [1/s] \\\\\n    \\edb{Z} (opt) \\> : \\> Vertical coordinate \\>  [m]\n  \\end{vartab}\n  \\edb{K}, \\edb{W}, \\edb{P} and \\edb{alpha} are scalars. \\edb{Z} can \n  be an arbitrary array.\n  If \\edb{Z} is ommitted, \\edb{ZE} is used as vertical coordinate.\n\\item[Output]\n  \\begin{vartab}\n    \\edb{A} \\> : \\>  Concentration at depth \\edb{Z}.  \\>   [eggs/m$^3$]\n  \\end{vartab}\n  If \\edb{Z} is present, \\edb{size(Y) = size(Z)},\n  otherwise, \\edb{size(Y) = size(ZE)}.\n\\item[Description]\\mbox{}\\\\\n   Computes the exact stationary solution of the\n   convection diffusion equation with constant\n   eddy diffusivity \\edb{K}, velocity \\edb{W}, egg production \\edb{P}\n   and loss rate \\edb{alpha}.\n   If \\edb{Z} is present, returns array of pointwise values.\n   If \\edb{Z} is not present, returns exact cell averages.\n\\end{tdesc}\n\n\n\\thead{sstate}{Steady state solution}\n\n\\begin{tdesc}\n\\item[Usage] \\edb{A = sstate(M, K, W)}\n\\item[Input]\n  \\begin{vartab}\n  \\edb{M} \\>  : \\> Vertical integrated concentration \\> [eggs/m$^2$] \\\\\n  \\edb{K} \\>  : \\> Eddy diffusivity \\> [\\sqmps] \\\\\n  \\edb{W} \\>  : \\> Egg velocity   \\>  [\\mps]\n  \\end{vartab}\n  \\edb{M} is scalar, \\edb{K} and \\edb{W} are column vectors of\n  length \\edb{Ncell+1}, \\edb{K} and \\edb{W} live at the flux-points.\n\\item[Output]\n  \\begin{vartab}\n  \\edb{A}    \\>  : \\> Stationary solution \\> [eggs/m$^3$]\n  \\end{vartab}\n  \\edb{A} lives at the egg points, \\edb{size = (Ncell x 1)}.\n\\item[Description]\\mbox{}\\\\\n  Computes the steady state solution of the convection-\n  diffusion equation without source term, with eddy diffusivity \n  \\edb{K} and egg\n  velocity \\edb{W} variable in the water column. \n  The solution is computed by viewing \\edb{K} and \\edb{W}\n  as piecewise constant on the grid cells.\n\\end{tdesc}\n\n\n\\thead{upstream}{Numerical integration of transport equation}\n\n\\begin{tdesc}\n\\item[Usage] \\edb{A = upstream(A0, K, W, nstep, dt, P, alpha)}\n\\item[Input]\n  \\begin{vartab}\n  \\edb{A0}  \\> : \\> Start concentration \\>  [eggs/m$^3$] \\\\\n  \\edb{K}   \\> : \\> Eddy diffusivity    \\>  [\\sqmps]  \\\\\n  \\edb{W}   \\> : \\> Terminal velocity   \\>  [\\mps]  \\\\\n  \\edb{nstep}  \\> : \\> Number of integration steps \\\\\n  \\edb{dt}     \\> : \\> Time step           \\>  [s] \\\\\n  \\edb{P}     (opt) \\> : \\> Spawning term       \\>  [eggs/m$^3$/s] \\\\\n  \\edb{alpha} (opt) \\> : \\> Loss coefficient \\> [1/s] \n  \\end{vartab}\n  \\edb{A0} lives at the egg-points, \\edb{size(A0) = (Ncell x 1)}.\n  \\edb{K} and \\edb{W} live at the flux-points, \\edb{size = (Ncell+1 x1)}.\n  If \\edb{P} and \\edb{alpha} are present, they also live at the egg-points.\n  If \\edb{P} and \\edb{alpha} are missing, the source term is ignored. \n\\item[Output]\n  \\begin{vartab}\n  \\edb{A} \\>  : \\> Result concentration \\> [eggs/m$^3$]\n  \\end{vartab}\n  \\edb{A} lives at egg-points in the same way as \\edb{A0}\n\\item[Description]\\mbox{}\\\\\n  Integrates the convection-diffusion equation by the \n  upstream method. Starting with the concentration \\edb{A0},\n  nstep integration steps are performed. The result is \n  saved in \\edb{A}.\n\\end{tdesc}\n\n\\thead{ve\\_drint}{Integrate over a depth range}\n\n\\begin{tdesc}\n\\item[Usage]  \\edb{int = ve\\_drint(A, z1, z2)}\n\\item[Input]\n   \\begin{vartab}    \n   \\edb{A}  \\> : \\>  Egg distribution \\> [eggs/m$^3$] \\\\\n   \\edb{z1} \\> : \\>  First integration limit \\>  [\\m] \\\\\n   \\edb{z2} \\> : \\> Second integration limit \\> [\\m]\n   \\end{vartab}\n   \\edb{A} must be a matrix where the columns are\n   egg distributions. But a row-vector can also \n   be accepted, \\edb{size(A) = (Ncell x n)} or \\edb{(1 x Ncell)}.\n\\item[Output]\n   \\begin{vartab}\n   \\edb{int} \\> : \\> Integral of A over depth range \\> [eggs/m$^2$]\n   \\end{vartab}\n   If \\edb{A} is a matrix of size \\edb{(Ncell x m)}, \\edb{int} becomes\n   a row-vector of length \\edb{m} containing the integrals\n   of the columns of A.\n\\item[Description]\\mbox{}\\\\\n    Computes the vertical integral\n    \\begin{displaymath}\n      \\edb{int} = \\int_\\edb{z1}^\\edb{z2} a(z) dz\n    \\end{displaymath}\n    where $a(z)$ is the piecewice constant function \n    $a(z) = \\edb{A(i)}$ for $\\edb{ZF(i+1)} < z < \\edb{ZF(i)}$.\n    If \\edb{A} is a matrix, the integral is computed for each column\n\\end{tdesc}\n\n\\thead{ve\\_grid}{Set up vertical grid}\n\n\\begin{tdesc}\n\\item[Usage]  \\edb{ve\\_grid(H, dz0)}\n\\item[Input]\n  \\begin{vartab} \n  \\edb{H}        \\>  : \\> Depth of water column  \\> [m] \\\\\n  \\edb{dz0}      \\>  : \\> Grid size              \\> [m]\n  \\end{vartab}\n\\item[Output]\n  None\n\\item[Description]\\mbox{}\\\\\n  Sets up the vertical grid used in VertEgg, given the depth\n  \\edb{H} of the water column and the grid size \\edb{dz0}.\n  (Re)defines all global variables.\n  The global variables are declared by \\edb{ve\\_init}.\n\\end{tdesc}\n\n\n\\thead{ve\\_init}{Initialize VertEgg}\n\n\\begin{tdesc}\n\\item[Usage] \\edb{ve\\_init}\n\\item[Input] none\n\\item[Output] none\n\\item[Description]\\mbox{}\\\\\n  Script for initializing VertEgg.\n  Declares the global variables, so they become\n  available in the workspace.\n  The actual values are set by \\edb{ve\\_grid}.\n\\end{tdesc}\n\n\\thead{ve\\_int}{Vertical integral of egg distribution}\n\n\\begin{tdesc}\n\\item[Usage] \\edb{M = ve\\_int(A)}\n\\item[Input]\n  \\begin{vartab}\n  \\edb{A} \\>  : \\> Egg distribution  \\>  [eggs/m$^3$]\n  \\end{vartab}\n  \\edb{A} must be a matrix where the columns live on egg-points,\n  but a row-vector at egg-points is also accepted,\n  \\edb{size(A) = (Ncell x n)} or \\edb{(1 x Ncell)}\n\\item[Output]\n  \\begin{vartab}\n  \\edb{M}    \\>  : \\> The vertical integral \\>  [eggs/m$^2$]\n  \\end{vartab}\n  If \\edb{A} is a matrix of size \\edb{(Ncell x n)}, \\edb{M} is a\n  row-vector of length \\edb{n}.\n\\item[Description]\\mbox{}\\\\\n  Computes the vertical integral of an egg distribution.\n  \\edb{ve\\_int} is a vector function.\n\\end{tdesc}\n\n\n\\thead{ve\\_mean}{Mean depth of an egg distribution}\n\n\\begin{tdesc}\n\\item[Usage] \\edb{mu = ve\\_mean(A)}\n\\item[Input]\n  \\begin{vartab}\n  \\edb{A}  \\> :\\>  Egg distribution   \\>  [eggs/m$^3$]\n  \\end{vartab}\n  \\edb{A} must be a matrix where the columns live on egg-points,\n  but a row-vector at egg-points is also accepted,\n  \\edb{size(A) = (Ncell x n)} or \\edb{(1 x Ncell)}\n\\item[Output]\n  \\begin{vartab}\n  \\edb{mu}   \\> : \\> The center of gravity \\>  [m] \n  \\end{vartab}\n  If \\edb{A} is a matrix of size \\edb{(Ncell x n)}, \\edb{mu} is a\n  row-vector of length \\edb{n}.\n\\item[Description]\\mbox{}\\\\\n  Computes the mean (or center of gravity) of the egg\n  egg distribution \\edb{A},\n  \\edb{ve\\_mean} is a vector function.\n\\end{tdesc}\n\n\n\\thead{ve\\_rand}{Make random egg distribution}\n\n\\begin{tdesc}\n\\item[Usage] \\edb{Y = ve\\_rand(M)}\n\\item[Input]\n  \\begin{vartab}\n  \\edb{M}    \\>  : \\> Vertical integrated concentration \\> [eggs/m$^2$]\n  \\end{vartab}\n  \\edb{M} is a scalar\n\\item[Output]\n  \\begin{vartab}\n  \\edb{Y}    \\>  : \\>  Random egg distribution \\> [eggs/m$^3$]\n  \\end{vartab}\n  \\edb{Y} is vector of size \\edb{[Ncell 1]}\n \n\\item[Description]\\mbox{}\\\\\n  A uniform distribution is used to generate random \n  values between 0 and 1. The values are scaled\n  to make \\edb{ve\\_int(Y) = M}.\n\\end{tdesc}\n\n\n\\thead{ve\\_rmsd}{Root mean square deviation}\n\n\\begin{tdesc}\n\\item[Usage] \\edb{R = ve\\_rmsd(X, Y)}\n\\item[Input]\n  \\begin{vartab}\n  \\edb{X} \\> : \\> Egg concentration  \\>  [eggs/m$^3$] \\\\\n  \\edb{Y} \\> : \\> Egg concentration  \\>  [eggs/m$^3$]\n  \\end{vartab}\n  \\edb{X} and \\edb{Y} may be matrixes of the same size\n  with \\edb{Ncell} rows. \\edb{X} and/or \\edb{Y} may also be\n  vectors of length \\edb{Ncell}.\n\\item[Output]\n  \\begin{vartab}\n  \\edb{R} \\>  : \\> Root mean square deviation \\> [eggs/m$^3$]\n  \\end{vartab}\n  \\edb{R} is a row vector with length =\n  \\edb{max(columns(X), columns(Y))}.\n\\item[Description]\\mbox{}\\\\\n  Computes the root mean square deviation \\edb{R}\n  between the columns of \\edb{X} and \\edb{Y}. If one\n  argument is a vector, it is compared to\n  all columns of the other argument.\n  If \\edb{X} and \\edb{Y} are matrices\n  \\begin{displaymath}\n    \\edb{R(j)} =\n    \\sqrt{\\frac{1}{\\edb{Ncell}} \\sum_\\edb{i} (\\edb{X(i,j)}-\\edb{Y(i,j)})^2} .\n  \\end{displaymath}\n  If \\edb{Y} is a vector\n  \\begin{displaymath}\n    \\edb{R(j)} = \n    \\sqrt{\\frac{1}{\\edb{Ncell}} \\sum_\\edb{i} (\\edb{X(i,j)}-\\edb{Y(i)})^2} .\n  \\end{displaymath}\n\\end{tdesc}\n\n\n\\thead{ve\\_std}{Standard deviation of egg distribution}\n\n\\begin{tdesc}\n\\item[Usage] \\edb{s = ve\\_std(A)}\n\\item[Input]\n  \\begin{vartab}\n  \\edb{A}    \\> : \\> Egg distribution  \\>  [eggs/m$^3$]\n  \\end{vartab}\n  \\edb{A} must be a matrix where the columns live on egg-points,\n  but a row-vector at egg-points is also accepted,\n  size(A) = (Ncell x n) or (1 x Ncell)\n\\item[Output]\n  \\begin{vartab}\n  \\edb{s}   \\>  : \\> The standard deviation  \\> [m]\n  \\end{vartab}\n  If \\edb{A} is a matrix of size (Ncell x n), s is a\n  row-vector of length n.\n\\item[Description]\\mbox{}\\\\\n  Computes the standard deviation of an egg \n  distribution \\edb{A},\n  \\edb{ve\\_std} is a vector function.\n\\end{tdesc}\n\n\n} % \\parindent=0pt\n\n", "meta": {"hexsha": "3fe7163f9ec78e85dfa035461ef1366deb7c0859", "size": 20543, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Rapport/manual.tex", "max_stars_repo_name": "bjornaa/Vertegg", "max_stars_repo_head_hexsha": "836ed0857b2f6bc1a7399a20b28b3e4320810b15", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Rapport/manual.tex", "max_issues_repo_name": "bjornaa/Vertegg", "max_issues_repo_head_hexsha": "836ed0857b2f6bc1a7399a20b28b3e4320810b15", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Rapport/manual.tex", "max_forks_repo_name": "bjornaa/Vertegg", "max_forks_repo_head_hexsha": "836ed0857b2f6bc1a7399a20b28b3e4320810b15", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7878289474, "max_line_length": 77, "alphanum_fraction": 0.6146132503, "num_tokens": 7599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.3077289913116912}}
{"text": "\\documentclass[aps,showpacs,12pt,onecolumn,prd,superscriptaddress,nofootinbib]{revtex4}\n\n\\usepackage{amsmath}\n\\usepackage{amsfonts}\n\\usepackage{amssymb}\n\\usepackage{latexsym}\n\\usepackage{graphicx}\n\\usepackage{bm}\n\\usepackage{color}\n\\usepackage{enumerate}\n\\usepackage{ulem}\n\n\\newcommand{\\be}{\\begin{equation}}\n\\newcommand{\\ee}{\\end{equation}}\n\\newcommand\\ud{{\\mathrm{d}}}\n\\newcommand\\uD{{\\mathrm{D}}}\n\\newcommand\\calO{{\\mathcal{O}}}\n\\newcommand\\bfx{\\mathbf{x}}\n\\newcommand{\\ov}[1]{\\overline{#1}}\n\\newcommand{\\ph}[1]{\\phantom{#1}}\n\\newcommand{\\cte}{\\mathrm{cte}}\n\\newcommand{\\nn}{\\nonumber}\n\\newcommand{\\hatk}{\\hat{k}}\n\\newcommand{\\Hz}{\\,\\mathrm{Hz}}\n\\newcommand{\\sinc}{\\,\\mathrm{sinc}}\n\\newcommand{\\Msol}{M_{\\odot}}\n\\newcommand{\\bsub}{\\begin{subequations}}\n\\newcommand{\\esub}{\\end{subequations}}\n\\newcommand\\betaL{{\\beta_{L}}}\n\\newcommand\\lambdaL{{\\lambda_{L}}}\n\\newcommand\\varphiL{{\\varphi_{L}}}\n\\newcommand\\psiL{{\\psi_{L}}}\n\\newcommand\\C{{\\cos(4\\psi)}}\n\\newcommand\\mc{{\\mathcal{M}}}\n\n\\newcommand{\\jgb}[1]{{\\color{DarkGreen} #1}}\n\n\\begin{document}\n\n\\title{Astrometry Inference Note}\n\n\\author{John G. Baker}\n\\affiliation{Gravitational Astrophysics Laboratory, NASA Goddard Space Flight Center, 8800 Greenbelt Rd., Greenbelt, MD 20771, USA}\n\n\n\\date{\\today}\n\n\\begin{abstract}\n\nThis is back of the envelope note on estimating incited GW direction by temporally extended GW observation from a moving platform.\n\n\\end{abstract}\n\n\\pacs{\n04.80.Nn, % Gravitational wave detectors and experiments\n95.30.Sf, % relativity and gravitation\n95.55.Ym, % Gravitational radiation detectors\n}\n\n\\maketitle\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Introduction}\n\nThe basic idea is that we want to treat a 'synthetic aperature', but with measurements separated by space \\emph{and time}. We need to compare the phases at two different spatial observation points to estimate a wavefront incidence angle. Befor doing so, however we need to first realize a time-transfer of the signals to a common time.  The time-transfer depends on the model of the signal and our measured knowledge of it at each time-separated observation.\n\nFor now we consider just two epochs of observation non-overlapping in time, but spatially separated because of the motion of the observatory. For this analysis we neglect any direct information about position from within each observation epoch (eg because of the attenna pattern, or finite instrument size) to focus only on the information gained by the instrument's motion.\n\n\\section{Minimally evolving source}\n\nFor an nearly monochromatic GW source, the signal model is nearly trivial, we will assume that the signal is monochromatic.\n(An uncertain frequency drift would seem to break this analysis, as degenerate with the linearly computed phase difference\nhere, but observing over multiple orbits would break that degeneracy.)\n\nFor each epoch $\\alpha$ of observation we assume some definition for an epoch-specific reference position $x^i_\\alpha$ e.g.\nthe mean location of the observatory during that epoch and a similar epoch observation time $t_\\alpha$.  Through the\nobservation we can estimate the incident wavefront phase $\\varphi\\alpha(t_\\alpha)$\nat that epoch's spacetime reference point.\nWe can compare the wavefront phases, by projecting them to some common reference time $t_0$ which we are free to select.\nFor a nearly monochromatic wavefront we estimate reference time phase from observation:\n$$\n\\varphi_\\alpha(t_0)\\approx\\varphi_\\alpha(t_\\alpha)+\\omega_\\alpha(t_\\alpha)(t_0-t_\\alpha) + \\mathcal{O}\\left(\\frac{t_0-t_\\alpha}{T_c}\\right)\n$$\nwhere $\\omega_\\alpha$ is the signal frequency and $T_c$ is the intrinsic coherence time of the signal.\nWe won't have perfect knowledge of the epoch's phase and frequency. These will depend on how precisely these can be\ninferred during the observation epoch, which in turn will also depend on the epoch SNR $\\rho_\\alpha$.\n\nWe estimate the error in the phase at reference time as\n$$\n\\left(\\delta\\varphi_\\alpha(t_0)\\right)^2\\approx\\left(\\delta\\varphi_\\alpha(t_\\alpha)\\right)^2+\\left(\\delta\\omega_\\alpha(t_0-t_\\alpha)\\right)^2. \n$$\nWe approximate that the GW phase information content is uniformly distributed according to SNR within the signal so that we can approximate $\\delta\\varphi_\\alpha(t_\\alpha)\\approx\\bar{\\delta\\varphi}/(\\rho_\\alpha)$.  (For a chirping signal it might also be appropriate to make this proportional to $1/\\omega_\\alpha$.)\n\nThe estimate for error in the GW frequency estimate builds on that from the phase.  Suppose we split each epoch into two halves, then estimate\n$$\n\\omega_\\alpha(t_\\alpha)\\approx\\frac{\\varphi_{\\alpha R}-\\varphi_{\\alpha L}}{T_\\alpha/2}\n$$\nwhere $T_\\alpha$ is the duration of the epoch. Again, if there is significant chirp during the epoch, more consideration is needed.  Then, again assuming equal distribution of phase info with $\\rho$, and uniform accumulation of $\\rho^2$ with time we estimate\n$$\n\\left(\\delta\\omega_\\alpha(t_\\alpha)\\right)^2\\approx\\frac{\\left(\\bar{\\delta\\varphi}\\right)^2}{T_\\alpha/2}\\left(\\frac{1}{\\rho^2_{\\alpha R}}+\\frac{1}{\\rho^2_{\\alpha L}}\\right).\n$$\nFor the non-chirping example, the RHS is optimized when left and right SNRs are each equal to $\\rho_\\alpha/\\sqrt2$.\n$$\n\\delta\\omega_\\alpha(t_\\alpha)\\approx\\sqrt{\\frac{8}{\\rho^2_\\alpha T_\\alpha}}\\bar{\\delta\\varphi}\n$$\n\nNow can complete the estimate for the error in the phase at reference time as estimated by the epoch of observation\n$$\n\\left(\\delta\\varphi_\\alpha(t_0)\\right)^2\\approx\\left(\\frac{\\delta\\varphi}{\\rho_\\alpha}\\right)^2\\left(1 + 8\\frac{\\left(t_0-t_\\alpha\\right)^2 }{T_\\alpha}\\right).\n$$\n\nNow let us construct the angle estimate by comparing the reference phase measurments at epochs $a$ and $b$ between which the constellation has moved by $D=x_b-x_a$. We estimate the triangulation error by\n$$\n\\left(\\delta\\theta\\right)^2 \\approx \\frac{\\lambda^2\\left(\\varphi_b(t_0)\\right)^2+\\left(\\varphi_b(t_0)\\right)^2}{D^2}\n$$\nwhere $\\lambda$ is the GW wavelength.\nNote that we have somewhat conservatively added all error terms in quadrature here. It is likely, though, there may be a common-mode phase errors particularly in the first (explicit phase error) term for each epoch.  Degneracy with intrinsic parameters, for instance, could be common mode.  The analysis assumes such error are not included here.  This likely reduces sensitivity to degeneracy.  In the end, we find that the frequency error terms dominate, where we only more subtle common-mode errors would enter.\nIf we assume that each epoch's squared SNR is propotional to its duration, then $\\rho^2_\\alpha=\\rho^2(T_\\alpha/T)$ where $\\rho$ and $T$ are the SNR and duration of the full observation. We thus have\n$$\n\\delta\\theta\\approx\\frac{\\lambda\\bar{\\delta\\varphi}}{D}\\left(\\frac{T}{T_a}+\\frac{T}{T-T_a} + 8\\frac{\\left(t_0-T_a/2\\right)^2}{T^2_a} +8\\frac{\\left(t_0-(T+T_a)/2\\right)^2}{(T-T_a)^2}\\right)\n$$\nwhere we have assumed the epochs are consecutive with epoch $a$ beginning at $t=0$ so $b$ begins at $t=T_a$ and ends at $t=T$. Optimizing, we find minimum error at $T_a=t_0=T/2$, meaning that the minumum error construction is where there are equal durations (and equal SNR) for the two epochs and the phase is compared at the temporal midpoint.  Then,\n$$\n\\bar{\\delta\\theta}\\approx20\\frac{\\lambda\\bar{\\delta\\varphi}}{D}.\n$$\nAt this optimum, $4/5$ of the estimated comes from the frequency term.\n\nLastly, a good rough estimate for a good-quality observation is $\\bar{\\delta\\varphi}\\approx 1/\\rho$, so\n$$\n\\bar{\\delta\\theta}\\approx20\\frac{\\lambda}{\\rho D}.\n$$\nThe factor or 20 is not something we had before.\n\n\\end{document}\n", "meta": {"hexsha": "05da495e09a66785a51d0ef37bc8dfdc34de711b", "size": 7577, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/astrometric_inference_note.tex", "max_stars_repo_name": "slutskyj/GWI-metrics", "max_stars_repo_head_hexsha": "f60616b11e6e60ca34eb21f02d06fba7a9ec213d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/astrometric_inference_note.tex", "max_issues_repo_name": "slutskyj/GWI-metrics", "max_issues_repo_head_hexsha": "f60616b11e6e60ca34eb21f02d06fba7a9ec213d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-05-07T18:18:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-07T18:18:01.000Z", "max_forks_repo_path": "doc/astrometric_inference_note.tex", "max_forks_repo_name": "slutskyj/GWI-metrics", "max_forks_repo_head_hexsha": "f60616b11e6e60ca34eb21f02d06fba7a9ec213d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-06T15:53:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-11T17:19:41.000Z", "avg_line_length": 55.7132352941, "max_line_length": 513, "alphanum_fraction": 0.7550481721, "num_tokens": 2121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754371026368, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.3075729962067486}}
{"text": "\\section{Equation of State}\nCASTRO is written in a modular fashion so that the EOS and network\nburning routines can be supplied by the user.   However, for the\nexamples presented later we use several EOS and network routines\nthat come with the CASTRO distribution.  \n\nEOS routines that come with CASTRO are (listed by directory name):\n\\begin{itemize}\n\\item {\\bf GammaLawEOS} directory represents a gamma law gas.\n\\item {\\bf HelmEOS} directory contains a general, publicly available\nstellar equation of state based on the Helmholtz free energy,\nwith contributions from ions, radiation, and electron degeneracy, as\ndescribed in (Timmes and Arnett 1999, Times and Swesty 2000, and Fryxell et al. 2000).\n\\item {\\bf LattimerSwestyEOS} directory contains a modified version of the\nLS EOS available at http://www.astro.sunysb.edu/dswesty.  Full\ndocumentation is available through that web site.  We use this EOS\nin the 1D core collapse supernova example in a later section.\n\\end{itemize}\n\nEach EOS directory contains two subroutines by which it interfaces to\nthe rest of the CASTRO code.  The first, \n\\[\n{\\bf \\rm EosGivenRTX}(e^\\outp, p^\\outp, \\rho^\\inp, T^\\inp, X^\\inp, n_{\\rm spec}, Y^\\inp, n_{\\rm aux})\n\\]\nis a direct interface to the EOS, in which density, species and auxiliary variables,\nand temperature are specified, and the necessary thermodynamical variables such as \ninternal energy, pressure, gamma, and sound speed are returned.\n\nThe second routine, \n\\[\n{\\bf \\rm EosGivenReX}(\\Gamma^\\outp, p^\\outp, c^\\outp, T^\\outp, \\rho^\\inp, e^\\inp, X^\\inp, n_{\\rm spec}, Y^\\inp, n_{\\rm aux})\n\\]\nuses a Newton iteration to find the temperature given\nthe internal energy, density, and species and auxiliary variables.  \n\\section{Burning Network}\nBurning network routines that come with CASTRO are (listed by directory name):\n\\begin{itemize}\n\\item {\\bf networks/null} directory describes a non-reacting white dwarf,\nwith only hydrogen, helium and carbon12.   There are\nno auxiliary variables, and no reactions are allowed.\n\\item {\\bf networks/collapse} directory describes a pre-supernova neutron\nstar with hydrogen, helium, oxygen and iron, There is one auxiliary\nvariable, Ye, the electron fraction.  Again no reactions are\nallowed.\n\\item {\\bf networks/ignition} directory contains a single-step\n$^{12}\\mathrm{C}(^{12}\\mathrm{C},\\gamma)^{24}\\mathrm{Mg}$ reaction.\nThe carbon mass fraction equation appears as\n\\begin{equation}\n\\frac{D X(^{12}\\mathrm{C})}{Dt} = - \\frac{1}{12} \\rho X(^{12}\\mathrm{C})^2\n    f_\\mathrm{Coul} \\left [N_A \\left <\\sigma v \\right > \\right]\\enskip,\n\\end{equation}\nwhere $N_A \\left <\\sigma v\\right>$ is evaluated using the reaction\nrate from (Caughlan and Fowler 1988).  The Coulomb screening factor,\n$f_\\mathrm{Coul}$, is evaluated using the general routine from the\nKepler stellar evolution code (Weaver 1978), which implements\nthe work of (Graboske 1973) for weak screening and the work of\n(Alastuey 1978 and Itoh 1979) for strong screening.\n\\end{itemize}\n\nThere are two primary files within each network directory. The first,\n{\\tt castro\\_burner.f90}, contains the burner routine, \nwhich takes $\\rho^\\inp, e^\\inp, X_k^\\inp$, and $\\Delta t$ as inputs.\nIt is possible for the internal energy, $e$, which is computed from $\\Ub$, to be\nnegative due to roundoff error.  CASTRO has an option to protect against using a \nnegative value of $e$ by recomputing $e = e(\\rho,T_{\\rm small},X_k)$ using the \nequation of state, where $T_{\\rm small}$ is a user-defined temperature floor.  In the \nevent that $e$ is still negative, we abort the program.  CASTRO also has an option to\nskip the reactions if the density is below a user-defined density floor.\n\nNext, the burner computes $T = T(\\rho^\\inp,e^\\inp,X_k^\\inp)$ using the equation of state.\nThe burner returns $X_k^\\outp$ and $e^\\outp$ by solving over a time interval of $\\Delta t/2$,\n\\begin{eqnarray}\n\\frac{\\partial X_k}{\\partial t} &=& \\omegadot_k.\\\\\n\\end{eqnarray}\nIn particular, to evolve the species, we solve the system:\n\\begin{eqnarray}\n\\frac{dX_k}{dt} &=& \\omegadot_k(\\rho,X_k,T)\\enskip, \\label{eq:VODE1C} \\\\\n\\frac{dT}{dt} &=&\\frac{1}{c_p} \\left ( -\\sum_k \\xi_k  \\omegadot_k  \\right )\\enskip. \\label{eq:tempreactC}\n\\end{eqnarray}\n\\MarginPar{Need to include temperature evolution equation somewhere}\nusing the stiff ordinary differential equation integration methods provided by \nthe VODE package.  The absolute error tolerances are set to \n$10^{-12}$ for the species, and a relative tolerance of $10^{-5}$ is used for \nthe temperature.  The integration yields the new values of the mass fractions, \n$X_k^\\outp$.  Equation (\\ref{eq:tempreactC}) is derived from equation (???) by \nassuming that the pressure is constant during the burn state.  In evolving these \nequations, we need to evaluate $c_p$ and $\\xi_k$.  In theory, this means \nevaluating the equation of state for each right-hand side evaluation that \nVODE requires.  In practice, we freeze $c_p$ and $\\xi_k$ at the start of \nthe integration time step and compute them using $\\rho^\\inp, X_k^\\inp,$ and $T^\\inp$ \nas inputs to the equation of state.  Note that the density remains unchanged during \nthe burning.  At the end of the routine, we compute \n$T^\\outp = T(\\rho^\\outp,e^{\\outp},X_k^\\outp)$.\n\nThe second file, ``{\\tt network.f90}'', supply the\nnumber of species and auxiliary variables, names of each species and \nauxiliary variable, as well as other initializing data, such as\naion, zion and the binding energy.\n\nIt is straightforward to implement additional EOS and network routines; all that is required\nis to create an appropriate interface to the CASTRO calls, which is easily done given\nthe prototypes supplied with the CASTRO distribution.\n", "meta": {"hexsha": "17b8335a4ec84868d2ca7dcfded08a3ad5c78655", "size": 5677, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "UsersGuide/EOSNetwork/EOSNetwork.tex", "max_stars_repo_name": "Gosenca/axionyx_1.0", "max_stars_repo_head_hexsha": "7e2a723e00e6287717d6d81b23db32bcf6c3521a", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-02-18T09:13:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T21:27:46.000Z", "max_issues_repo_path": "UsersGuide/EOSNetwork/EOSNetwork.tex", "max_issues_repo_name": "Gosenca/axionyx_1.0", "max_issues_repo_head_hexsha": "7e2a723e00e6287717d6d81b23db32bcf6c3521a", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-12T08:54:31.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-12T08:54:31.000Z", "max_forks_repo_path": "UsersGuide/EOSNetwork/EOSNetwork.tex", "max_forks_repo_name": "Gosenca/axionyx_1.0", "max_forks_repo_head_hexsha": "7e2a723e00e6287717d6d81b23db32bcf6c3521a", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-09-04T10:26:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T23:51:51.000Z", "avg_line_length": 55.1165048544, "max_line_length": 124, "alphanum_fraction": 0.7509247842, "num_tokens": 1573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160664, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3075439277580332}}
{"text": "\\documentclass[10pt,journal]{IEEEtran}\n\\usepackage{caption}\n\\usepackage{amsmath}\n\\usepackage{graphicx}\n\\usepackage{subfigure}\n\\usepackage[square, comma, sort&compress, numbers]{natbib}\n\n\n\\begin{document}\n\\bibliographystyle{IEEEtran}\n\n\n\\title{ {Joint Synchronization and Channel Estimation of ACO-OFDM Systems with Simplified Transceiver}\n%\\thanks{Manuscript received November 24, 2016.}\n\\thanks{\nManuscript received October 11, 2017; revised December 27, 2017; accepted January 7, 2018. Date of publication January XX, 2018; date of current version May 19, 2016. This work was supported by Central South University under Post-graduation Innovation Fund project (2016zzts228) and Mittal Innovation Fund project. It is also supported by Research Foundation of Education Bureau of Hunan Province [Project No. 17B238].\n}\n\\thanks{\nXuewen Qian is with Laboratoire des Signaux et Syst��mes (L2S), CentraleSup\\'elec-CNRS-Universit\\'e Paris-Sud, Universit\\'e Paris-Saclay, 3, rue Joliot Curie, 91192, Gif-sur-Yvette, France (e-mail: xuew.qian@gmail.com).\nHonggui~Deng is with the Department of Physics and Electronics, Central South University (e-mail: denghonggui@163.com).\nHailang He is with Department of Information Engineering, Shaoyang University, Shaoyang, Hunan, China (e-mail:7887302@qq.com).\n}\n\\thanks{\nColor versions of one or more of the figures in this letter are available online at http://ieeexplore.ieee.org.\n}\n\\thanks{\nDigital Object Identifier XX.\n}\n}\n\n\\author{Xuewen Qian,\n        %Marco Di Renzo,~\\IEEEmembership{Senior Member,~IEEE}\n        Honggui Deng, ~\\IEEEmembership{Member,~IEEE}\n        and~ Hailang He }\n%\\author{Xuewen~Qian,\n\n %       }\n\n\n\\maketitle\n\\begin{abstract}\nTo facilitate the development of asymmetrically clipped optical OFDM (ACO-OFDM) systems, a joint synchronization and channel estimation scheme is proposed. The preamble used in the scheme is based on zero correlation code pair (ZCC pair) and has impulse-like correlation relationship. This property can let the results of synchronization process be the coarsely estimated channel time response, thus simplifies channel frequency response generation. Also, a transceiver with low complexity is proposed. The proposed transceiver needs only half the amount of multiplications compared to conventional transceiver. Simulation results reveal that the proposed scheme achieves better performance both in synchronization and channel estimation than existing schemes.\n\\end{abstract}\n\n\\begin{IEEEkeywords}\nSynchronization, channel estimation, ACO-OFDM, low complexity transceiver.\n\\end{IEEEkeywords}\n\n\n\n\\section{Introduction}\nVisual light communication (VLC) technology\\cite{Chi2015,Qian2016Synchronisation} is a promising technique providing light and ensuring data transmission at the same time. Besides, the light emitting diode (LED) \\cite{tsonev20143,ferreira2016high} as one of the most popular light sources can promote the widespread utilization of VLC systems. However, multi-path distortion caused by the glass reflections can heavily reduce the communication qualities. Thus, orthogonal frequency division multiplexing (OFDM) technique is introduced to combat the multi-path effect.\n\nDue to intensity modulation and direct detection in most VLC systems, many OFDM-based VLC systems resort to the direct current bias optical OFDM (DCO-OFDM) modulation, asymmetrically clipped optical OFDM (ACO-OFDM) and other schemes to generate positive signals. However, as revealed in \\cite{Dissanayake2013Comparison}, it is better to choose ACO-OFDM scheme when constellations like quadrature amplitude modulation (QAM) and 16QAM are exploited since ACO-OFDM scheme has higher optical power efficiency especially for some scenarios such as Internet of Things (IoT) systems.\n\nIn IoT systems, low complexity is essential to the ACO-OFDM system implementation. For lower power consumption and higher data rates, ACO-OFDM schemes are integrated to develop other modulation techniques, such as asymmetrically clipped DC-biased optical OFDM (ADO-OFDM), hybrid ACO-OFDM (HACO-OFDM) and layered ACO-OFDM (LACO-OFDM)\\cite{yang2016novel,Wang2017Optical}. Therefore, ACO-OFDM scheme with low complexity is important and must be researched.\n\nIt is well known that OFDM systems are sensitive to synchronization errors and are heavily affected by the complex channels. Many researches focus on making use of the preamble symbols to synchronize signals and estimate channel frequency response at the same time. Like systems in radio communication systems, the channel state information (CSI) is estimated via preamble symbols in time domain and the channel frequency response can be calculated using CSI.\n\nIn \\cite{Tian2008}, Tian et. al. proposed a synchronization scheme based on the symmetric symbols. However, this scheme has low estimation precision and the high side-lobes. Ranjha et. al \\cite{Ranjha2015} proposed a new timing metric with synchronization performance enhancement but the scheme still has high side-lobes. Thus, the results of synchronization process of Tian's and Ranjha's schemes cannot be exploited for channel estimation. For channel estimation, a common scheme is least square (LS) estimation scheme \\cite{wu2016channel}.\nThe synchronization and channel estimation scheme cannot be combined as a whole for the mentioned schemes.\nAspired by \\cite{Qian2017}, modified zero correlation code (ZCC) pair symbols designed based on Physical layer for dynamic spectrum access and cognitive radio (PHYDYAS) \\cite{Bellanger2010} filter have impulse-like aperiodic correlation results and are used to estimate CSI to perform channel estimation in DCO-OFDM systems. %This kind of technique can also be applied to ACO-OFDM channel estimation and synchronization.\n\nIn this letter, the ACO-OFDM system is firstly investigated and a new transceiver is proposed to reduce the calculation complexity. After that a joint synchronization and channel estimation scheme based on ZCC pair is proposed for ACO-OFDM system.\nThe rest is organized as follows. In Section II, the system model is presented, including the channel model, ACO-OFDM-based VLC system and the new transceiver. Then, the joint synchronization and channel estimation scheme is proposed in Section III. In Section IV, performance and simulation results are analysed. In the end, the conclusion is drawn in Section V.\n\n\\section{System Model}\n\n\t\\subsection{VLC Channel Model}\n\t\tA realistic VLC channel is determined by many factors. As simulated in \\cite{Uysal2015Lifi}, in manufacturing cell environment, the maximum path delay may exceed 80ns which is bigger than that of home environment.\n%the maximum path delay in home environment is about 60ns and there is often one line of sight (LOS) response while the not line of sight (NLOS) responses are extremely small. However in manufacturing cell environment, the maximum path delay may exceed 80ns.\nThere are more strong responses as many light traces.\n\n\t\tThe VLC channel can be modeled as\n        \\begin{equation}\\label{channel_model}\n          h(\\tau)=\\sum_{l=0}^{L-1}g(l)\\delta(\\tau-\\tau_l),\n        \\end{equation}\n        where $g(l)$ and $\\tau_l$ denote the gain and delay of the l-th transmission path, $\\delta(\\tau)$ denotes the Dirac function and $L$ represents the number of path.\n        The $h(\\tau)$ can be made discrete at a sampling speed.\n        For simplicity, we assume that $\\tau_l$ is an integer.\n        Since VLC systems can only transfer intensity signals, $g(l)\\geq0$.\n\n    \\subsection{ACO-OFDM-based VLC system}\n\t\tConsidering an ACO-OFDM system with N sub-carriers, the signal after IFFT is\n\t\t\\begin{equation}\\label{equ:ACO_OFDM_base}\n          x(n)=\\frac{1}{\\sqrt{N}}\\sum_{i=0}^{N-1}X_{i}e^{j2\\pi\\frac{ni}{N}},-N_{CP}\\leq n \\leq N-1,\n        \\end{equation}\n        where $n$ denotes the index of signal in time domain and $X_{i}$ denotes the modulated data on the k-th sub-carrier. The $N_{CP}$ represents CP length.\n        To make $x(n)$ be real, $X_{i}$ must follow the Hermite symmetry property which is\n\t\t\\begin{equation}\\label{equ:Hermite_symmetry}\n          X=[X_0,X_1,\\ldots,X_{N/2-1},X(N/2),X_{N/2-1}^{*},\\ldots,X_{1}^{*}].\n        \\end{equation}\n\t\tIn ACO-OFDM systems, only the odd sub-carriers are used and the even sub-carriers are set to zero so that $ x(n)=-x(n+N/2) $ when $\n0\\leq n\\leq N/2-1 $. In this way, $ x(n) $ can be clipped at zero to be $ x_c(n) $ without information loss. Then, the cyclic prefix (CP) is introduced to overcome the multipath channel.\n\n\t\tThe effect of multipath channel is\n        \\begin{equation}\\label{equ:multipath_effect}\n          y(n)=\\sum_{l=0}^{L-1}h(l)x_c(n-\\tau_l)+w(n),\n        \\end{equation}\n        where $h(l)$ represents the VLC channel time domain response and $w(n)$ denotes the total noise which is modeled as white Gaussian noise\\cite{Narmanlioglu2015}.\n\n        In frequency domain, (\\ref{equ:multipath_effect}) can be expressed as\n        \\begin{equation}\\label{equ:multipath_effect_frequency}\n          Y(m)=H(m)X_c(m)+\\eta(m),\n        \\end{equation}\n        where $Y(m)$, $H(m)$, $X_c(m)$ and $\\eta(m)$ denote the FFT transform results of $y(n)$, $h(\\tau)$, $x_c(n)$ and $w(n)$, respectively. Normally, $X_c(2m+1) = X(2m+1)/2 $ when $0\\leq m\\leq N-1$ \\cite{Wang2017Optical}.\n        If the $X_c(2m+1)$ is known in advance, $H(2m+1)$ can be acquired via LS method\n        \\begin{equation}\\label{equ:LS}\n          \\widehat{H}(2m+1) = Y(2m+1) / X_c(2m+1), 0\\leq m\\leq N-1.\n        \\end{equation}\n        %since only the used sub-channels are useful.\n\n\t\\subsection{Simplified Transmitter and Receiver}\n\t\tSince the original signals are clipped at zero, the direct FFT results of $ x_c(n) $ are not the same as that of $ x(n) $, but the odd sub-carriers are not distorted. %Only the odd sub-carriers are necessary.\n\n\t\tIf we denote $ C $ as the first half of $ x(n) $, then $ x=[C;-C] $. If we denote $ A $ and $ B $ as the first half and second half of $ x_c(n) $, then $ C = A - B $. Thus, when $ C $ is generated via IFFT of $ N/2 $ length, $ x(n) $ can be obtained without using IFFT of $ N $ length which reduces the calculation complexity.\n\n\t\tFor $ 0\\leq n \\leq N/2-1 $, $ C $ can be generated via\n\t\t\\begin{eqnarray}\\label{equ:sim_transmitter}\n\t\t\tx(n) &=& \\sum_{i=0}^{N/2-1} X_{2i+1}e^{j\\frac{2\\pi}{N}n(2i+1)} \\nonumber\\\\\n\t\t\t\t &=& \\sum_{k=0}^{N/2-1} X_{k} e^{j\\frac{2\\pi}{N/2}nk}e^{j\\frac{2\\pi}{N}n} \\nonumber\\\\\n\t\t\t\t &=& IFFT(X)_{N/2}e^{j\\frac{2\\pi}{N}n},\n\t\t\\end{eqnarray}\n\t\twhere $ IFFT(\\cdot)_{N/2} $\trepresents the IFFT process of $ N/2 $ length.\tThere are $ N/2 log_2(N/2) + N/2 = N/2 log_2(N) $ multiplications used in generation of $ C $ which is just  half the calculations of conventional method $( N log_2(N) )$.\n\n\t\tFor the receiver, the results of the FFT process must be multiplied with 2 due to the signal clipping \\cite{Wang2017Optical}. Since only the odd sub-carriers are necessary, thus the received data on the $ 2i+1 $ sub-carrier can be obtained as\n        %\\begin{small}\n\t\t\\begin{eqnarray}\\label{equ:sim_receiver}\n            %\\begin{split}\n\t\t\t %&X_{2i+1}& \\nonumber\\\\\n            X_{2i+1}&=& \\frac{2}{N}\\sum_{n=0}^{N-1} y(n) e^{-j\\frac{2\\pi}{N}n(2i+1)}\\nonumber\\\\\n\t\t\t&=& \\frac{2}{N}\\sum_{n=0}^{N/2-1} y(n) e^{-j\\frac{2\\pi}{N}n(2i+1)}  \\nonumber\\\\\n\t\t\t&&+ \\frac{2}{N}\\sum_{n=0}^{N/2-1} y(n+N/2) e^{-j\\frac{2\\pi}{N}(n+N/2)(2i+1)} \\nonumber\\\\\n\t\t\t&=& \\frac{2}{N}\\sum_{n=0}^{N/2-1} y(n) e^{-j\\frac{2\\pi}{N}n(2i+1)}  \\nonumber\\\\\n\t\t\t&&- \\frac{2}{N}\\sum_{n=0}^{N/2-1} y(n+N/2) e^{-j\\frac{2\\pi}{N}n(2i+1)} \\nonumber\\\\\n\t\t\t&=& \\frac{2}{N}\\sum_{n=0}^{N/2-1} ( y(n)-y(n+N/2) ) e^{-j\\frac{2\\pi}{N}n(2i+1)}  \\nonumber\\\\\n\t\t\t\t\t %&=& \\sum_{n=0}^{N/2-1} ( y(n)-y(n+N/2) ) e^{-j\\frac{2\\pi}{N}n} e^{-j\\frac{2\\pi}{N/2}ni} \\nonumber\\\\\n\t\t\t&=& FFT( ( y(n)-y(n+N/2) ) e^{-j\\frac{2\\pi}{N}n} )_{N/2},\n            %\\end{split}\n\t\t\\end{eqnarray}\n        %\\end{small}\n\t\twhere $ FFT(\\cdot)_{N/2} $\trepresents the FFT process of $ N/2 $ length. Just as the proposed transmitter, the computational complexity of proposed receiver is half that of conventional receiver.\n\n\t\t%\\begin{figure}[htb]\n\t\t%\t\\centering \\includegraphics[width=8cm]{asymmetric_property_ACO_OFDM.eps}\n\t\t%\t\\caption{The symmetric property of symbols after the multipath channels} \\label{fig:symmetric_property_illustration}\n\t\t%\\end{figure}\n\n\\section{Synchronization and Channel Estimation Scheme with Low Complexity Transceiver}\n\tIn \\cite{Qian2016Synchronisation}, zero-correlation-code (ZCC) pair is proposed to synchronize signal in DCO-OFDM-based VLC systems. In \\cite{Qian2017}, modified ZCC pair generated via PHYDYAS filters can be used to obtain the gains and delays of the multi-path channels.\n%There is no frequency offset in VLC systems due to the intensity modulation and demodulation property. This makes synchronization and channel estimation process easier than systems in radio communications.\nUnlike DCO-OFDM systems, the transmitted signals of ACO-OFDM systems from the data generated after IFFT process are clipped at zero. It is hard to exploit ZCC pair sequences in ACO-OFDM systems directly. To reserve the impulse-like correlation property of ZCC pair sequences, the received signals must be investigated.\n\n\tThe following is to show that $ y(n)-y(n+N/2) $ contains $ C $.\n\t%If $C$ is generated to be ZCC pair sequence,\n\tWe denote the $A^{'}$ and $A^{''}$ as the parts of the delayed $A$ and denote  $B^{'}$ and $B^{''}$ as the parts of the delayed $B$ and delayed CP.\n\tBy investigating the effect of multi-path channels,\n\t\\begin{figure}[htb]\n        \\captionsetup{belowskip=-5pt}\n\t\t\\centering \\includegraphics[width=5cm]{effect_of_channel_ACO_OFDM.eps}\n\t\t\\caption{The illustration for the effect of multipath channels on symbols} \\label{fig:effect_of_channel_ACO_OFDM}\n\t\\end{figure}\n\tSince $C^{'}=A^{'}-B^{'}$ and $C^{''}=A^{''}-B^{''}$, the results of $y(n)-y(n+N/2)$ are shown in Fig.\\ref{fig:effect_of_channel_ACO_OFDM}.\n\n\tIf $C$ and $D$ are set to be the ZCC pair sequence and the pair sequence, the aperiodic correlation between $C$ and $D$ is impulse-like.\n\t%Since there is no frequency offset in VLC systems,\n\t%As shown in \\cite{Qian2017}, the\n\tBecause $ \\sum_{n=0}^{N/2-1}C(n+k)D^*(n)=N/2 \\delta(k) $, the CSI can be estimated via\n\t%\\begin{small}\n\t\\begin{align}\\label{equ:gain_acquire}\n        %\\begin{split}\n          %\\bar{h}(k)&\\nonumber\\\\\n          \\bar{h}(k)=&\\frac{2}{N}\\sum_{n=0}^{N/2-1}(y(n+k)-y(n+k+N/2))D^*(n)\\nonumber\\\\\n          =&\\frac{2}{N}\\sum_{n=0}^{N/2-1}\\sum_{l=0}^{L-1}(h(l)(x(n+k-l)-x(n+k-l+N/2))\\nonumber\\\\\n          &+w(n+k-l)-w(n+k-l+N/2))D^*(n)\\nonumber\\\\\n          =&\\frac{2}{N}\\sum_{l=0}^{L-1}h(l)\\sum_{n=0}^{N/2-1}C(n+k-l)D^*(n)+\\tilde{w}(k)\\nonumber\\\\\n          =&\\sum_{l=0}^{L-1}h(l)\\delta(k-l)+\\tilde{w}(k).\n        %\\end{split}\n    \\end{align}\n\t%\\end{small}\n    %where $\\tilde{w}(k)$ denotes the noise.\n\n    The next step is to design the required preamble sequence for synchronization and channel estimation. %According to (\\ref{equ:sim_transmitter}), all the sub-carriers are needed to generate $ C $. to some extent.\n\n\tThe detailed steps to generate $ C $ are listed as:\n\n    Step1: Define $S$ as a vector of $N/16+1$ length consisting of $1$ and $-1$:\n        $S=[1, \\cdots 1, \\cdots -1, \\ldots -1]^T$.\n\n    Step2: $S$ is multiplied by a matrix $diag([1,j,-1,j^3,\\ldots j^{N/16-1},j^{N/16}])$ to be $S_{a}$. This is also called offset quadrature amplitude modulation process.\n\n    Step3: Define $S_b$ as a vector with Hermite property via\n\n        $S_b=[S_{a}(0),S_{a}(1),\\cdots S_{a}(N/16),S_{a}^*(N/16-1),\\cdots S_{a}^*(1)]^T$.\n\n\tStep4: Inverse Fourier transform the $S_b$ to be $S_c$.\n\n    Step5: Finally, we get the required sequence $C$ via $C=[ S_c; S_c; S_c; S_c]\\cdot g$. The $g$ is given in \\cite{Bellanger2010}.\n\n    According to the relationship of ZCC pair sequences, $D$ is the same as $C$ generated based on PHYDYAS filter. Thus, the preamble in the proposed scheme is designed according to $C$ and the timing offset estimation metric is expressed as\n    \\begin{eqnarray}\\label{equ:synchronization}\n          M(k)=\\frac{2}{N}\\sum_{n=0}^{N/2-1}(y(n+k)-y(n+N/2+k))C^*(n).\n    \\end{eqnarray}\n    Then the timing instant is calculated as\n    \\begin{equation}\\label{equ:d}\n            \\hat k=\\arg\\max\\limits_{k}(\\|M(k)\\|),\n    \\end{equation}\n    where $\\arg\\max\\limits_{k}(\\|M(k)\\|)$ means returning the timing instant $\\hat k$ when the absolute value of $M(k)$ is the biggest. It performs an one-dimensional search to find $\\hat k$.\n\n    Since the $ h $ is positive, the negative values in $ \\bar{h} $ (obtained from (\\ref{equ:synchronization}) ) are set to zero to be $ h^{'} $. After the CSI is acquired, the channel frequency response can be calculated via\n    \\begin{equation}\\label{equ:Channel_Fre}\n          H(k)=\\sum_{l=0}^{L-1}h^{'}e^{-j2\\pi\\frac{\\tau_l k}{N}},0\\leq k \\leq N-1.\n    \\end{equation}\n    Also, only the odd sub-carriers are transmitting data. Therefore the simplified channel frequency response is expressed as\n    \\begin{equation}\\label{equ:Channel_Fre_sim}\n          H(2k+1)=\\sum_{l=0}^{L-1}(h^{'}e^{-j2\\pi\\frac{\\tau_l}{N}})e^{-j2\\pi\\frac{\\tau_l k}{N/2}},0\\leq k\\leq N/2-1.\n    \\end{equation}\n    The calculation complexity of (\\ref{equ:Channel_Fre_sim}) is just half of (\\ref{equ:Channel_Fre}).\n\n    The received data in frequency domain can be equalized as\n    \\begin{equation}\\label{equ:equalizer}\n       X^{'}(2k+1)=\\dfrac{2Y(2k+1)}{H(2k+1)},0\\leq k\\leq N/2-1.\n    \\end{equation}\n\n    The whole simplified ACO-OFDM system is depict in Fig.\\ref{fig:sim_ACO_OFDM_system}.\n    \\begin{figure}[!htb]\n        \\captionsetup{belowskip=-5pt}\n    \t\\centering \\includegraphics[width=9cm,height=3cm]{ACO_OFDM_system.eps}\n\t\t\\caption{The illustration for the simplified ACO-OFDM system} \\label{fig:sim_ACO_OFDM_system}\n    \\end{figure}\n    The IFFT and FFT process in the system are of $ N/2 $ length. After the generation of $ C $, the positive and negative of $ C $ are used to compose ACO-OFDM symbols and the CP is added before transmitted by optical transmitters. The received signals are firstly subtracted. Then results are used to calculate the right timing point via (\\ref{equ:synchronization}). When the right timing point is obtained, the needed channel frequency response is calculated via (\\ref{equ:Channel_Fre_sim}) after the negative part of synchronization results are set to zero. In the end, data are equalized according to (\\ref{equ:equalizer}).\n\n\n\n\\section{Simulation and Analysis}\n\tThe simulation channel is the indoor manufacturing cell channel given by \\cite{Uysal2015Lifi}. Some other simulation parameters are listed in the Table. \\ref{Tab:paramters}.\n\n    \\begin{table} [htb]\n        \\caption{The parameters of simulation}\n        \\captionsetup{belowskip=-10pt}\n         \\centering\\begin{tabular}{|l|c|}\n                    \\hline\n                    Parameters & Value\\\\\n                    \\hline\n                    Number of subcarriers & 512 \\\\\n                    \\hline\n                    CP length & 64\\\\\n                    \\hline\n                    Frame length & 16 OFDM symbols\\\\\n                    \\hline\n                    Bandwidth & 500MHz \\\\\n                    \\hline\n                    Constellation order & 16QAM \\\\\n                    %Maximum time delay $\\tau_{max}$ & 50  \\\\\n                    %Number of paths L & [$0.1\\tau_{max}$,$0.9\\tau_{max}$] \\\\\n                    %Pilot distribution & Scattered \\\\\n                    \\hline\n                    Simulation trial number & 100000 \\\\\n                    \\hline\n                    Room area W$\\times$H$\\times$L & 2$\\times$4$\\times$3$m^3$\\\\\n                    \\hline\n                    Receiving node(PD)area & 1$cm^2$ \\\\\n                    \\hline\n                    Conversion efficient of photoelectricity & $0.5A/W$ \\\\\n                    \\hline\n                    Receiver field of view(FOV) & $60^{\\circ}$ \\\\\n                    \\hline\n                    \\end{tabular}\n         \\label{Tab:paramters}\n    \\end{table}\n\n\n\t\\begin{figure}[!htb]\n        %\\setlength{\\abovecaptionskip}{-0.1cm}\n        \\captionsetup{belowskip=-10pt}\n    \t\\centering \\includegraphics[width=6cm]{synchronization_mse.eps}\n\t\t\\caption{The MSE performance comparison of synchronization schemes} \\label{fig:synchronization_mse}\n    \\end{figure}\n    Fig.\\ref{fig:synchronization_mse} shows the normalized MSE value of timing offset estimation with respect to the IFFT length. The MSE values of the three schemes decrease with enlarging the SNR value. The Tian's scheme achieves the worst performance compared with the Ranjha's and proposed schemes. When SNR value is large, the estimation error is just one third of that of Ranjha's scheme. If the SNR is below 16 dB, the Ranjha's scheme has better performance but the performance difference is small.\n    %As to the calculation complexity, the Tian's scheme needs $ N/2-2 $ multiplications at each discrete sample time, while Bilal's \\cite{Ranjha2015} and proposed schemes both need\n    In \\cite{chow2013adaptive}, the OFDM-based VLC systems using common LEDs are tested and the suggested SNR values are over 18dB.\n    Thus, the proposed scheme is good enough.\n\n    \\begin{figure}[!htb]\n        %\\setlength{\\abovecaptionskip}{-0.1cm}\n        \\setlength{\\abovecaptionskip}{10pt}\n        \\captionsetup{belowskip=-10pt}\n    \t\\centering \\includegraphics[width=6cm]{channel_estimation_HMSE.eps}\n\t\t\\caption{The channel frequency estimation performance comparison of LS and proposed scheme}\n        \\label{fig:channel_estimation_HMSE}\n    \\end{figure}\n    Fig.\\ref{fig:channel_estimation_HMSE} presents a comparison of channel frequency response estimation performance. The channel frequency estimation MSE value of LS scheme decreases with enlarging SNR with steady slope, while the MSE value of proposed scheme drops gradually to a level but is much lower than that of LS scheme. The proposed scheme has better channel estimation performance than LS scheme.\n\n    %In terms of the calculation complexity, for the proposed algorithm, most calculation can be done via the system FFT module. Only $ N/2 $ multiplications are needed for the simplified channel frequency response.\n    %The proposed algorithm is easier than conventional\n\n    \\begin{figure}[!htb]\n        \\setlength{\\abovecaptionskip}{10pt}\n        \\captionsetup{belowskip=-10pt}\n    \t\\centering \\includegraphics[width=6cm]{channel_estimation_BER.eps}\n\t\t\\caption{The BER performance comparison of LS and proposed scheme} \\label{fig:channel_estimation_BER}\n    \\end{figure}\n\n\tFig.\\ref{fig:channel_estimation_BER} shows BER performances of the LS scheme, proposed scheme and the ideal performance with prior knowledge of CSI. The proposed scheme has BER performance similar to the ideal performance and is better than LS scheme.\n\n\t%Overall, the proposed joint synchronization and channel estimation scheme has better performance than other schemes.\n\n\\section{Conclusion}\nIn this letter, a joint synchronization and channel estimation scheme is proposed for ACO-OFDM systems. A simplified transceiver is proposed which only needs half the calculations compared with conventional transceiver. Simulations have revealed that the proposed scheme has better timing MSE performance than Tian's and Ranjha's schemes in synchronization task and has better channel frequency response MSE performance and BER performance than LS channel estimation scheme.\n\n\n\\scriptsize{\\bibliography{mybibtex}}\n\\end{document}\n", "meta": {"hexsha": "1bdc6e2c9a637dff2e1c90dec346de0aee9449da", "size": 23410, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "FINAL VERSION.tex", "max_stars_repo_name": "qianxuewen/ACO_OFDM_CE_Syn_paper", "max_stars_repo_head_hexsha": "3a25472f46cecb640622a5fa73db84970429021a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FINAL VERSION.tex", "max_issues_repo_name": "qianxuewen/ACO_OFDM_CE_Syn_paper", "max_issues_repo_head_hexsha": "3a25472f46cecb640622a5fa73db84970429021a", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FINAL VERSION.tex", "max_forks_repo_name": "qianxuewen/ACO_OFDM_CE_Syn_paper", "max_forks_repo_head_hexsha": "3a25472f46cecb640622a5fa73db84970429021a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-07-27T08:39:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-21T03:19:57.000Z", "avg_line_length": 74.5541401274, "max_line_length": 760, "alphanum_fraction": 0.7074327211, "num_tokens": 6686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3075328086113792}}
{"text": "\\documentclass{scrartcl}\n\\usepackage{threeparttable}\n\n\\usepackage{relsize}\n\\usepackage{xspace}\n\n\\usepackage{listings}\n\\lstset{language=MATLAB,numbers=left,frame=lines}\n\\lstnewenvironment{snippet}{\\lstset{numbers=none,frame=none}}{}\n\n\\usepackage{amsmath}\n\\usepackage{amsfonts}\n\n\\usepackage{graphicx}\n\n\\usepackage{tikz}\n\\usetikzlibrary{shapes,arrows}\n\\tikzstyle{decision} = [diamond, draw, fill=blue!20, \n    text width=4.5em, text badly centered, node distance=3cm, inner sep=0pt]\n\\tikzstyle{block} = [rectangle, draw, fill=blue!20, \n    text width=7em, text centered, rounded corners, minimum height=4em]\n\\tikzstyle{line} = [draw, -latex']\n\\tikzstyle{cloud} = [draw, ellipse,fill=red!20, node distance=3cm,\n    minimum height=2em]\n\n\n\\newcommand{\\RR}{\\mathbb{R}}\n\\newcommand{\\trace}{\\textrm{tr}}\n\\renewcommand{\\SS}{\\mathbb{S}}\n\n\\newcommand{\\find}{\\textrm{find}}\n\\newcommand{\\minimize}{\\textrm{minimize}}\n\\newcommand{\\maximize}{\\textrm{maximize}}\n\\newcommand{\\subjto}{\\textrm{subj. to}}\n\n\\newcommand{\\li}[1]{\\lstinline{#1}}\n\\newcommand{\\spotless}{SPOT{\\relsize{-2}LESS}\\xspace}\n\\newcommand{\\msspoly}{\\lstinline{ msspoly}\\xspace}\n\\newcommand{\\spotprog}{\\lstinline{spotprog}\\xspace}\n\\newcommand{\\spotsdpsol}{\\lstinline{spotsdpsol}\\xspace}\n\\newcommand{\\spotsosprog}{\\lstinline{spotsosprog}\\xspace}\n\n\n\n\n%\\newcommand{\\matlab}{MATLAB$^\\textregistered$}\n\\title{\\spotless \\\\ Polynomial and Conic Optimization}\n\\author{ Mark M. Tobenkin, Frank Permenter, Alexandre Megretski}\n\\begin{document}\n\\maketitle\n\\tableofcontents\n\\section{Introduction}\n\\spotless is a software toolbox for MATLAB for posting conic \\cite{cone} and sum-of-squares (SOS) optimization problems \\cite{sos}.\nThe basic functionality provided:\n\\begin{enumerate}\n\\item A simple, reasonably fast approximate symbolic algebra package.\n\\item A modeling tool for posing and pre-/post-processing conic optimization problems.\n\\item A modeling tool for posing SOS problems.\n\\end{enumerate}\nSeveral alternative tools exist for addressing these problems, notably  CVX \\cite{cvx} and Yalmip \\cite{yalmip}.  We recommend these packages as more user-friendly modeling environments -- the emphasis of \\spotless is on providing an {\\it extensible} tool for {\\it  building other libraries}.\n\n\n\n\n\n\\section{Quick Start}\nThis section provides an explanation of the basic capabilities of \\spotless, and provides simple examples of solving conic and SOS programs and inspecting the solutions.\n\n\\subsection{Basic \\spotless Work-Flow}\nThe basic work-flow in \\spotless is as described by Figure~\\ref{fig:basic}.\n\n\\begin{figure}\n  \\centering\n\\begin{tikzpicture}[node distance = 2.222222cm, auto]\n    % Place nodes\n    \\node [block] (prog) {Create \\\\Program};\n    \\node [block,below of=prog] (new) {Create \\\\ Variables\\\\(\\lstinline{prog.new...})};\n    \\node [block,below of=new] (with) {Add \\\\Constraints\\\\ (\\lstinline{prog.with...})};\n    \\node [block,below of=with] (solve) {Solve \\\\ (\\lstinline{prog.minimize})};\n    \\node [block,below of=solve] (feas) {Check Feasibility and Accuracy};\n    \\node [block,below of=feas] (solution) {Extract Solution};\n\n    \\path[line] (prog) -- (new);\n    \\path[line] (new) -- (with);\n    \\path[line] (solve) -- (feas);\n    \\draw[->] (feas) -- node[pos=0.5]{If Feasible}(solution);\n    \\draw [->]  (with.east)  -- ++(10mm,0) |- node [black, near end, yshift=0.75em] {} (new.east);    \n    \\path[line] (with) -- (solve);\n  \\end{tikzpicture}\n\\caption{Basic \\spotless workflow.\\label{fig:basic}}\n\\end{figure}\n\nLet's walk through the following example to provide some more detail.\nThe input to the program is a pair of positive integers $(n,m)$ a matrix $A \\in \\RR^{n \\times m}$ and a vector $b \\in \\RR^{n}$. The program is defined by:\n\\begin{flalign*}\n  \\mathop{\\minimize}_{x\\in\\RR^m} \\quad & \\sum_{i=1}^m |x_i|\\\\\n  \\subjto \\quad & Ax = b.\n\\end{flalign*}\n\\begin{lstlisting}\nprog = spotprog;\n[prog,x] = prog.newFree(m);\nprog = prog.withEqs(A*x - b);\n\n[prog,a] = prog.newPos(m);\nprog = prog.withPos(a - x);\nprog = prog.withPos(a - (-x));\n\nobj = sum(a);\n\nsol = prog.minimize(obj);\n\nif sol.solutionQuality < 0\n    error('Solution is of very low quality.');\nelseif sol.solutionQuality < 1\n    warning('Low solution quality.');\nend\nif sol.primalInfeasible || sol.dualInfeasible\n    error('Infeasibility detected.');\nend\n\nxopt = double(sol.eval(x));\n\\end{lstlisting}\n\n\\subsubsection{Create a program} First, one constructs a program object as in\n\\begin{lstlisting}[firstnumber=1,frame=none]\n  prog = spotprog;\n\\end{lstlisting}\nfor conic programming. For SOS programming one instead uses\n\\begin{lstlisting}[numbers=none,frame=none]\n  prog = spotsosprog;\n\\end{lstlisting}\n\\subsubsection{Create Variables}\n  Next, one constructs new decision variables, e.g.\n\\begin{lstlisting}[frame=none,firstnumber=2]\n[prog,x] = prog.newFree(m);\n\\end{lstlisting}\nupdates \\lstinline{prog} to have \\li{m} new free (unconstrained) variables, stored in the vector \\li{x}.\nA similar syntax modifies the program to have \\li{m} non-negative variables:\nas in\n\\begin{lstlisting}[frame=none,firstnumber=5]\n[prog,a] = prog.newPos(m);\n\\end{lstlisting}\nstored in the vector \\li{a}.  The types supported by \\spotprog are  listed in Table~\\ref{tab:spotprog_types}.  \n\\subsubsection{Add Constraints}\n  Equality constraints are defined by expressions which must be equal to zero, i.e.\n\\begin{lstlisting}[frame=none,firstnumber=3]\nprog = prog.withEqs(A*x - b);\n\\end{lstlisting}\nensures $Ax = b$.  Additional ``conic'' constraints can be added, e.g.\n\\begin{lstlisting}[frame=none,firstnumber=6]\nprog = prog.withPos(a - x);\n\\end{lstlisting}\n  requires \\lstinline{a(i)} $\\geq$ \\lstinline{x(i)} for $i \\in \\{1,\\ldots,m\\}$.\n  Similar function calls, (i.e. \\lstinline{prog.withType()}) are used to impose other kinds of constraints.\n\\subsubsection{Solve The Program}\nThe next step is to identify an objective, and solve the program:\n\\begin{lstlisting}[frame=none,firstnumber=11]\nsol = prog.minimize(obj);\n\\end{lstlisting}\nhere \\li{obj} is an affine expression in decision parameters and \\li{sol} is a solution object.\nCalling \\li{prog.minimize} without a first argument, or with zero as the first argument solves a feasibility problem.  See Section~\\ref{sec:sol} for more details about specifying a solver and adding pre-/post-processing options.\n\\subsubsection{Examine Feasibility and Accuracy}\nIdeally, a ``solution'' to a conic programming problem should consist of one of:\n\\begin{enumerate}\n  \\item[(i)] A pair of primal and dual feasible points which are optimal.\n  \\item[(ii)] A primal improving direction (proving dual infeasibility).\n  \\item[(iii)] A dual improving direction (proving primal infeasibility).\n\\end{enumerate}\nSolution {\\it quality} in \\spotless refers to a numerical measure of confidence that the solver has obtained such a solution.\nBoth poorly posed problems and numerical errors can lead to a low quality solution.\nSection~\\ref{sec:bad} contains some examples of programs for which no solution in the above sense exists.\n\nOnce a solver has been called, one must examine the quality of the returned solution. Note that {\\bf the interpretation of solution quality is application dependent!}  Please see Section~\\ref{sec:sol} for information about customizing solution quality reporting for your application.  \nNegative solution quality is supposed to indicate a useless solution, as tested by\n\\begin{lstlisting}[frame=none,firstnumber=13]\nif sol.solutionQuality < 0\n\\end{lstlisting}\nwhereas solution quality less than \\li{1} is supposed to be circumspect.\n\nIf the soluton quality is high, one can still have an {\\it infeasible} program, as test by\n\\begin{lstlisting}[frame=none,firstnumber=18]\nif sol.primalInfeasible || sol.dualInfeasible\n\\end{lstlisting}\nPrimal infeasibility generally implies that no choice of decision variables satisfies the given constraints.  Dual infeasibility often means that the optimal cost is unbounded below.  A more thorough account is given in Section~\\ref{sec:feas}.\n\\subsubsection{Extract Solution}\nTo extract a solution, one first uses \\li{sol.eval} to substitute optimal decision parameters into any algebraic expression, e.g.\n\\begin{lstlisting}[frame=none,firstnumber=18]\nxopt = double(sol.eval(x));\n\\end{lstlisting}\nHere, \\li{double} is then used to transform the resulting expression from \\spotless's internal symbolic algebra library into a numerical vector.\n\\subsection{Basic Types}\n\n\n\\begin{table}\n  \\centering\n  \\begin{threeparttable}[b]\n  \\caption{Constraint Types for \\spotprog\\label{tab:spotprog_types}}\n  \\begin{tabular}{|l|lll|}\n    \\hline\n    Type& Abbrev. & Vector Space & Constraint\\\\\n    \\hline\n    Free & \\lstinline!Free! & $ x \\in \\RR^n$ & \\\\\n    Positive & \\lstinline!Pos! & $x\\in\\RR^n$ & $x_i \\geq 0$\\\\\n    Lorentz & \\lstinline!Lor! & $x \\in\\RR^{n\\times m}$ & $x_{1j}^2 \\geq \\sum_{i=2}^n |x_{ij}|^2$, \\quad $\\forall j$\\\\\n    Rotated Lorentz & \\lstinline!RLor! & $x\\in\\RR^{n\\times m}$ & $x_{1j} \\geq 0, \\quad x_{1j}x_{2j} \\geq \\sum_{i=3}^n |x_{ij}|^2$\\quad $\\forall j$\\\\\n    Positive Semidefinite & \\lstinline!PSD! & See below.\\tnote{1}\n&\\\\\n\\hline\n\\end{tabular}\n\\begin{tablenotes}\n\\item [1]  The positive semidefinite cone refers to matrices $X \\in \\RR^{n\\times n}$ such that $v^T X v \\geq 0$\n      for all $v \\in \\RR^n$.  Two representations are used in \\spotless:  a single PSD variable can be represented by an $n\\times n$ \\msspoly and  a set of $N$ PSD variables can be represented as ${n+1 \\choose 2}\\times N$ \\msspoly.  When $N=1$ this transformation from one representation to the other is given by \\lstinline{mss_v2s} (read: vector-to-symmetric) and \\lstinline{mss_s2v} (read: symmetric-to-vector):\n  \\[\n  \\lstinline{mss_s2v(X)} = \\begin{bmatrix} X_{11} \\\\ X_{12} \\\\ X_{22} \\\\ X_{13} \\\\ \\vdots\\end{bmatrix}\n\\qquad   \\lstinline{mss_v2s(x)} = \\begin{bmatrix}\n    x_1 & x_2 & x_4 & \\ldots \\\\\n    x_2 & x_3 & x_5 & \\ldots \\\\\n    x_5 & x_3 & x_6 & \\ldots \\\\\n    \\vdots & \\vdots & \\vdots & \\ddots\n  \\end{bmatrix},\n  \\]\n  where $X \\in \\RR^{n\\times n}$ and $x \\in \\RR^{n+1 \\choose 2}$.\n  {\\bf N.B.}: Generally:\n  \\[\n \\trace(\\lstinline[mathescape]!X*S!) \\not \\equiv \\lstinline{mss_s2v}(X)'*\\lstinline{mss_s2v}(S).\n \\]\n\\end{tablenotes}\n\\end{threeparttable}\n\\end{table}\n\n% \\end{tabular}\n\n\n\n\\subsection{Conic Programming Examples}\n\\subsubsection{$\\ell_\\infty$ Fitting Example}\nGiven an positive integers $N$ and $d$ find $x \\in \\RR^{n}$ to solve:\n\\begin{flalign*}\n  \\minimize \\quad & \\max_{i \\in \\{-N,\\ldots,N\\}} \\left \\{\\left |\\sum_{i=0}^d x_{i+1} \\left(\\frac{i}{N}\\right)^d - \\left |\\frac{i}{N}\\right|\\right| \\right \\}, \\\\\n  \\subjto \\quad & x \\in \\RR^{d+1}.\n\\end{flalign*}\n\\lstinputlisting[title=examples/linf\\_fitting.m]{examples/linf_fitting.m}\nThis program fits a degree 5 polynomial in $t$ to the function $|t|$ over $[-1,1]$.  Line 9 constructs a new program.  Lines 11 and 12 introduce the indeterminate t and constructs the vector \\lstinline{basis = [ 1 ; t ; ... ; t^d]}.  A vector of $d+1$ coefficients are created on Line 13, and on Line 14 used to construct a function \\lstinline{f = coeff(1) + coeff(2)t + ...}.  The function \\lstinline{msubs} is used on line 16 to evaluate \\lstinline{f} at each \\lstinline{t = tt(i)} (returning a row).  Finally Lines 19 and 20 require the free variable \\lstinline{obj} to satisfy \\lstinline{obj} $\\geq$ \\lstinline{err(i)} and \\lstinline{-err(i)}  respectively for each $i$.  The program is solved (Line 22), and the optimal coefficients are substituted into \\lstinline{f} and stored in \\lstinline{fopt} on Line 24.\n\n\\subsubsection{SDP Projection Example}\nGiven $A = A' \\in \\RR^{n\\times n}$, solve:\n\\begin{flalign*}\n  \\minimize \\quad & \\|A-X\\|_F \\\\\n  \\subjto \\quad & X \\in \\SS_{n,+}.\n\\end{flalign*}\n\\lstinputlisting[title=examples/sdp\\_projection.m]{examples/sdp_projection.m}\n\nThe optimization problem begins at line 6 by constructing a new program.  Line 7 constructs a new $n\\times n$ PSD decision variable,\\lstinline{P}, and line 8 a 1-by-1 free variable, \\lstinline{obj}.  Line 10 constraints \\lstinline{obj} to be greater than the $2$-norm of $P-A$ when regarded of as a vector using a Lorentz cone constraint (see Section \\ref{sec:cones}).  A solution is then generated to the problem of minimizing \\lstinline{obj} with the default solver on Line 12.  Finally, Line 14 substitutes the optimizing variables into the expression for \\lstinline{P}, and then transforms that expression in a MATLAB double array stored in \\lstinline{Popt}.\n\n\n\\subsubsection{SDP Control Design Example}\nGiven a matrix pair $(A,B) \\in \\RR^{n\\times n} \\times \\RR^{n \\times m}$ representing a stabilizable discrete time LTI system\n\\[\nx[t+1] = A x[t] + B u[t],\n\\]\nfind matrix $K \\in \\RR^{m \\times n}$ such that $A+BK$ is exponentially stable.\nFor $\\rho \\in (0,1)$ solve\n\\begin{flalign*}\n  \\find \\quad & (S,L) \\in \\SS_{n,+} \\times \\RR^{m\\times n} \\\\\n  \\subjto \\quad & \n\\begin{bmatrix} (1-\\rho)S   & AS+BL\\\\\n  SA'+L'B' &   S\n  \\end{bmatrix} \\in \\SS_{2n,+}.\n\\end{flalign*}\nand take $K = LS^{-1}$.\n\\lstinputlisting[title=examples/sdp\\_lti\\_control.m]{examples/sdp_lti_control.m}\n\n\n\n\\subsection{SOS Programming Examples}\n\\subsubsection{Upper Bound Polynomial On Sphere}\n\\begin{lstlisting}\n% Construct a random polynomial.\nn = 2;\nd = 4;\nx = msspoly('x',n);\nbasis = monomials(x,0:d);\np = randn(length(basis))'*basis;\n\ng = 1 - x'*x;\n\nprog = spotsosprog;\nprog = prog.withIndeterminate(x);\n[prog,r] = prog.newFree(1);\n\n[prog,f] = prog.newFreePoly(x,monomials(x,0:d-2));\nprog = prog.withSOS(r-p-f*g);\n\nsol = prog.minimize(r);\n\nsol.eval(r);\n\\end{lstlisting}\n\\subsubsection{Van der Pol ROA}\n\\subsubsection{Simple Pendulum ROA}\n\n\n\n\n\\section{Basic Classes}\n\\subsection{\\msspoly: Simple Approximate Symbolic Algebra}\n\\subsection{\\spotprog: Representation of Optimization Problems}\n\\subsection{\\spotsdpsol: Representation of Optimization Solutions}\n\\subsection{\\spotsosprog: Representation of SOS Problems}\n\\section{Function Guide}\n\\end{document}", "meta": {"hexsha": "b65e53aaa23ec0c4c4c3f1fa26904ac929498132", "size": 13846, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "externals/spotless/spotless/doc/manual.tex", "max_stars_repo_name": "ericmanzi/double_pendulum_lqr", "max_stars_repo_head_hexsha": "76bba3091295abb7d412c4a3156258918f280c96", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "externals/spotless/spotless/doc/manual.tex", "max_issues_repo_name": "ericmanzi/double_pendulum_lqr", "max_issues_repo_head_hexsha": "76bba3091295abb7d412c4a3156258918f280c96", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "externals/spotless/spotless/doc/manual.tex", "max_forks_repo_name": "ericmanzi/double_pendulum_lqr", "max_forks_repo_head_hexsha": "76bba3091295abb7d412c4a3156258918f280c96", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.664516129, "max_line_length": 815, "alphanum_fraction": 0.7199191102, "num_tokens": 4263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.3075328086113792}}
{"text": "\\chapter{Numerical modelling of fluid–grain interactions}\n\n\\ifpdf\n    \\graphicspath{{Chapter5/figs/raster/}{Chapter5/figs/pdf/}{Chapter5/figs/}}\n\\else\n    \\graphicspath{{Chapter5/figs/vector/}{Chapter5/figs/}}\n\\fi\n\n\n\\section{Fluid simulation using the lattice Boltzmann method}\n\nGrain--fluid systems can be found in many scientific and engineering \napplications, such as suspensions, fluidised beds, sediment transport, and \ngeo-mechanical problems. In general, the fundamental physical phenomena in \nthese systems are not well understood mainly due to the intricate complexity of \ngrain--fluid interactions and the lack of powerful analysis \ntools~\\citep{Han2007b}. In addition to the interactions amongst soil grains, \nthe motion of soil grains is mainly driven by gravity and the hydrodynamic \nforce exerted by the fluid. The fluid flow pattern can be significantly \naffected by the presence of soil grains and this often results in a turbulent \nflow. Hence, the development of an effective numerical framework for modelling \nboth the fluid flow patterns and the grain--fluid interactions is very \nchallenging.\n\nDevelopment of a numerical framework depends crucially on the size of the soil \ngrains relative to the domain/mesh size~\\citep{Feng2007}. Traditionally, the \nNavier-Stokes equation is solved by a grid-based Computational Fluid Dynamics \n(CFD) method~\\citep{Tsuji2007}, such as the Finite Volume Method, \nFVM,~\\citep{Capecelatro2013} or a mesh-free technique such as Smooth Particle \nHydrodynamics (SPH)~\\citep{Sun2013}. The grid size in FVM or the smooth length \nin SPH for discretisation of the Navier-Stokes equation is at least an order of \nmagnitude larger than the grain diameter~\\citep{Xiong2014}, thus ignoring the \nmicro-scale interactions. \n\nIn situations where the average domain concentration phase is far from dilute, \nthe computational effort is mostly devoted to the grain dynamics. The \nhydrodynamic forces on the soil grains are applied based on an empirical \nrelation using the domain-averaged local porosity of the soil grains in the \ngrid. As a result, developing a fast fluid hydrodynamics solver is unimportant \nfor dense flows. However, most geo-mechanical problems involve complex \ninteractions between the solid and the fluid phase. This requires accurate \nmodelling of the fluid flow pattern. Additionally, geophysical problems, such \nas submarine landslides and debris flow have a relatively large simulation \ndomain, which requires parallel computation. Implementation of traditional \ngrid-based CFD methods faces great challenges on multi-processor \nsystems~\\citep{Xiong2014}. Although mesh-free approaches are free from the \nproblem of parallel scalability, their modelling accuracy and speed are \nrelatively low when compared to grid-based CFD methods. Therefore, an accurate, \nfast and a highly scalable scheme is required to model fluid - grain systems in \ngeo-mechanics. \n \nThe Navier-Stokes equation describes the motion of a non-turbulent Newtonian \nfluid. The equation is obtained by applying Newton's second law to the fluid \nmotion, together with an assumption that the fluid stress is the sum of the \nviscous term, proportional to the gradient of the velocity, and the pressure \nterm. Conventional CFD methods compute pertinent flow fields, such as velocity \n\\textit{u} and pressure \\textit{p}, by numerically solving the Navier-Stokes \nequation in space \\textit{x} and time \\textit{t}. Alternatively, the transport \nequation or the Boltzmann equation, which deals with a single particle \ndistribution function $f(x,\\xi,t)$ in phase space $(x,\\xi)$ and time \n\\textit{t}, can be used to solve various problems in fluid dynamics. \n\nThe Lattice Boltzmann Method\n(LBM)~\\citep{He1997a,He1997b,Chen1998a,Mei2000,Han2007a,Zhou2012}\nis an alternative approach to the classical Navier-Stokes solvers for fluid \nflows. LBM works on an equidistant grid of cells, called lattice cells, which \ninteract only with their direct neighbours. In LBM, the discretisation of \ncontinuum equations is based on microscopic models and mesoscopic continuum \ntheories. LBM is a special discretising scheme of the Boltzmann equation where \nthe particle distribution functions (mass fractions) collide and propagate on a \nregular grid. The important aspect, however, is the \\textit{discretisation of \nthe velocity}, which means that the particle velocities are restricted to a \npredefined set of orientations.\n\nThe theoretical premises of the LB equation are that (1) hydrodynamics is \ninsensitive to the details of microscopic physics, and (2) hydrodynamics can be \npreserved so long as the conservation laws and associated symmetries are \nrespected in the microscopic and mesoscopic level. Therefore, the computational \nadvantages of LBM are achieved by drastically reducing the particle velocity \nspace $\\xi$ to only a very few discrete points without seriously degrading the\nhydrodynamics~\\citep{Mei2000}. This is possible because LBM rigorously \npreserves the hydrodynamic moments of the distribution function, such as mass \ndensity and momentum fluxes, and the necessary \nsymmetries~\\citep{He1997a,He1997b}.\n% The process of averaging the density and the momentum over some regions of \n%the space, i.e. coarse graining, produces some useful fluid simulation. \nLBM has evolved as a comprehensive fluid solver and its theoretical aspects \nlink well with the conventional central finite difference \nscheme~\\citep{Cook2004}.\n\n\\subsection{Formulation}\n\nLBM is a `micro-particle' based numerical time-stepping procedure for the \nsolution of incompressible fluid flows. Consider a 2D incompressible fluid flow \nwith density $\\rho$ and kinematic viscosity \\textit{v}, in a rectangular domain \n\\textit{\\textbf{D}}. The fluid domain is divided into rectangular grids or \nlattices, with the same grid length \\textit{`h'} in both \\textit{x-} and \n\\textit{y-}directions (see~\\cref{fig:D2Q9}). \n\\begin{figure}[htpb]\n\t\\centering\n\t\\includegraphics[width=0.95\\textwidth]{D2Q9}\n\t\\caption[The lattice Boltzmann discretisation and the \\textit{D2Q9} \n\tscheme.]{The Lattice Boltzmann discretisation and the \\textit{D2Q9} \n\tscheme: (a) a standard LB \n\tlattice and \n\thistogram views of the discrete single particle distribution \n\tfunction/direction-specific densities $f_i$; (b) \\textit{D2Q9} model.}\n\t\\label{fig:D2Q9}\n\\end{figure}\n\nThese lattices are usually classified in the literature using the \n$\\mathit{D}\\alpha\\mathit{Q}\\beta$-notation, where $\\alpha$ denotes the space \ndimensionality and $\\beta$ is the number of discrete velocities (but also \nincluding the possibility of having particles at rest) within the momentum \ndiscretisation. The most common lattices are the $\\mathit{D2Q9}$ and the \n$\\mathit{D3Q19}$-models, see~\\citet{He1997}. The present study focuses on \ntwo-dimensional problems, hence the $\\mathit{D2Q9}$ momentum discretisation is \nadopted.\n\nLBM discretises the Boltzmann equation in space to a finite number of possible \nparticle spatial positions, microscopic momenta, and time. Particle positions \nare confined to the lattice nodes. The fluid particles at each node are \nallowed to move to their eight intermediate neighbours with eight different \nvelocities $\\mathit{e_i} (\\mathit{i}=1\\,,\\dots\\,,8)$. A particle can remain at \nits own node, which is equivalent to moving with zero velocity $\\mathit{e_o}$. \nThe particle mass is uniform, hence these microscopic velocities and momentum \nare always effectively equivalent~\\citep{Han2007a}. Referring to the numbering \nsystem shown in~\\cref{fig:D2Q9}, the nine discrete velocity vectors are \ndefined as\n%\n\\begin{align} \n\t\\begin{cases}\n\t\\mathit{e_0}=(0,0);\\\\\n\t\\mathit{e_1}=\\mathit{c}(1,0); \\mathit{e_2}=\\mathit{c}(0,1); \n\t\\mathit{e_3}=\\mathit{c}(-1,0); \\mathit{e_4}=\\mathit{c}(0,-1); \\\\\n\t\\mathit{e_5}=\\mathit{c}(1,1); \\mathit{e_6}=\\mathit{c}(-1,1);  \n\t\\mathit{e_7}=\\mathit{c}(-1,-1); \\mathit{e_8}=\\mathit{c}(1,-1)\\,, \n\t\\end{cases}\n\\end{align}\n%\n\\noindent where \\textit{C} is the lattice speed that is defined as \n$\\mathit{c}=\\mathit{h}/\\Delta t \\,,$ and $\\Delta \\mathit{t}$ is the discrete \ntime step. The primary variables in LB formulation are called the \\textit{fluid \ndensity distribution functions}, $\\mathit{f_i}$, each representing the probable \namount of fluid particles moving with the velocity $\\mathit{e_i}$ along the \ndirection $\\mathit{i}$ at each node. The macroscopic variables are defined \nas functions of the particle distribution function (see \\cref{fig:D2Q9})\n%\n\\begin{align} \n\t\\label{eq:lbm_macroscopic}\t\n\t\\begin{cases}\n\t\\rho = \\sum\\limits_{\\mathit{i}=0}^{\\beta - 1}{\\mathit{f_i}} \\qquad \n\t\\mbox{(macroscopic fluid density)} \\\\ \n\t\\mbox{and}\\\\\n\t\\overrightarrow{\\mathit{u}} = \\frac{1}{\\rho} \n\t\\sum\\limits_{\\mathit{i}=0}^{\\beta \n\t-1}{\\mathit{f_i}\\overrightarrow{\\mathit{e_i}}} \\quad \\mbox{(macroscopic \n\tvelocity)}\\,,\n\t\\end{cases}\t\n\\end{align} \n%\n\\noindent where $\\mathit{i} \\in [0, \\beta -1]$ is an index spanning the \ndiscretised momentum space. There are nine fluid density distribution \nfunctions, $\\mathit{f_i}(\\mathit{i}=0,\\dots,8)$, associated with each node \nin the \\textit{D2Q9} model. The evolution of the density distribution function \nat each time step for every lattice point is governed by\n%\n\\nomenclature[a-f]{\\textit{f}}{Fluid density distribution function in LBM}\n\\nomenclature[a-Ma]{$M_a$}{Mach number -  a dimensionless quantity representing \nthe ratio of speed of an object moving through a fluid and the local speed of \nsound}\n\\nomenclature[a-Pr]{$P_r$}{Prandtl number - a dimensionless number defined as \nthe ratio of momentum diffusivity to thermal diffusivity}\n\\nomenclature[a-St]{$S_t$}{Strouhal number - a dimensionless number describing \noscillating unsteady flow dynamics}\n\\nomenclature[a-S]{\\textit{S}}{Collision matrix in LBM}\n\\nomenclature[a-M]{\\textit{M}}{Transformation matrix mapping a vector} \n\\nomenclature[a-Q]{\\textit{Q}}{Vector of conserved variables in CFD}\n\\begin{equation} \n\t\\label{eq:stream}\n\t\\mathit{f_i}(\\mathbf{x}+\\mathbf{e}_{\\mathit{i}} \\Delta t, t + \\Delta t) = \n\t\\mathit{f_i}(\\mathbf{x},t) - \\frac{1}{\\tau} [\\mathit{f_i}(\\mathbf{x},t) \n\t-\\mathit{f_i}^{\\mathit{eq}}(\\mathbf{x},t)] \\quad (\\mathit{i}=0,\\dots,8) \\,,\n\\end{equation}\n%\n\\noindent where for any grid node $\\mathbf{x},$ $\\mathbf{x}+\\mathbf{e_i} \\Delta \nt$ is its nearest node along the direction $\\mathit{i}$. $\\tau$ is a \nnon-dimensional relaxation time parameter, which is related to the fluid \nviscosity; and $\\mathit{f_i}^{\\mathit{eq}}$ is termed as the equilibrium \ndistribution function that is defined as\n%\n\\begin{align}\n\t\\begin{cases}\n\t\\mathit{f}_{\\mathit{0}}^{\\mathit{eq}} = \\mathit{w}_{\\mathit{0}} \\rho (1 - \n\t\\frac{3}{2\\mathit{c}^{\\mathit{2}}}\\mathbf{v}.\\mathbf{v}) \\\\ \n\t\\mbox{and}\\\\\n\t\\mathit{f_i}^{\\mathit{eq}} = \\mathit{w_i} \\rho (1 + \n\t\\frac{3}{\\mathit{c}^{\\mathit{2}}}\\mathbf{e}_{\\mathit{i}}.\\mathbf{v} \n\t\\frac{9}{2\\mathit{c}^{\\mathit{2}}} \n\t(\\mathbf{e}_{\\mathit{i}}.\\mathbf{v})^{\\mathit{2}}-\\frac{3}{2 \n\t\\mathit{c}^{\\mathit{2}}}\\mathbf{v}.\\mathbf{v}) \\quad \n\t(\\mathit{i}=0,\\dots,8)\\,,\n\t\\end{cases}\n\\end{align}\n%\n\\noindent in which, $\\mathit{w_i}$ represents the fixed weighting values:\n%\n\\begin{equation}\n\t\\mathit{w}_{\\mathit{0}} = \\frac{4}{9}\\,, \\quad \n\t\\mathit{w}_{\\mathit{1,2,3,4}}= \n\t\\frac{1}{9}\\,, \\quad \\mbox{and} \\quad \\mathit{w}_{\\mathit{5,6,7,8}}= \n\t\\frac{1}{36}\\,.\n\\end{equation}\n\nThe right-hand side of~\\cref{eq:stream} is often denoted as \n$\\mathit{f_i}(\\mathbf{x}, \\mathit{t}_{+})$ and termed the post collision \ndistribution. LBM ensures conservation of total mass and total momentum of the \nfluid particles at each lattice node (see~\\cref{eq:stream}). The lattice \nBoltzmann model consists of two phases: \\textit{collision} and \n\\textit{streaming}. The \ncollision phase computed in the right-hand side of~\\cref{eq:stream} involves \nonly those variables that are associated with each node \\textbf{x}, and \ntherefore is a local operation. The streaming phase then explicitly propagates \nthe updated distribution functions at each node to its neighbours \n$\\mathbf{x}+\\mathbf{\\mathit{e}_i} \\Delta t$, where no computations are required \nand only data exchange between neighbouring nodes are necessary. These \nfeatures, together with the explicit time-stepping nature and the use of a \nregular grid, make LB computationally efficient, simple to implement and \neasy to parallelise~\\citep{Han2007a}. \n\nThe streaming step involves the translation of the distribution functions to \ntheir neighbouring sites according to the respective discrete velocity \ndirections, as illustrated in~\\cref{fig:stream} in the \\textit{D2Q9} model. The \ncollision step, (see~\\cref{fig:collision}) consists of re-distribution the \nlocal discretised Maxwellian equilibrium functions in such a way that \nlocal mass and momentum are invariant. In incompressible flows, energy \nconservation is equivalent to momentum conservation~\\citep{He1997}.\n\n\\begin{figure}[htbp]\n\t\\centering\n\t\\includegraphics[width=0.95\\textwidth]{stream}\n\t\\caption[Illustration of the streaming process on a \\textit{D2Q9} \n\tlattice.]{Illustration of the streaming process on a \\textit{D2Q9} lattice. \n\tThe magnitude of the distribution functions remains unchanged, but they \n\tmove to a neighbouring node according to their direction.}\n\t\\label{fig:stream}\n\\end{figure}\n\n\\begin{figure}[htbp]\n\t\\centering\n\t\\includegraphics[width=0.95\\textwidth]{collision}\n\t\\caption[Illustration of the collision process on a \\textit{D2Q9} \n\tlattice.]{Illustration of the collision process on a \\textit{D2Q9} lattice. \n\tThe local density $\\rho$ and velocity $\\mathbf{v}$ are conserved, but the \n\tdistribution functions change according to the relaxation to local \n\tMaxwellian rule.}\n\t\\label{fig:collision}\n\\end{figure} \n\nThe standard macroscopic fluid variables, such as density $\\rho$ and velocity \n$\\mathbf{\\mathit{ v}}$, can be recovered from the distribution functions as\n%\n\\begin{equation}\n\t\\rho = \\sum\\limits_{\\mathit{i}=0}^{8}{\\mathit{f_i}}\\,, \\quad \\mbox{and} \n\t\\quad \\rho \\mathbf{v} \n\t= \\sum\\limits_{\\mathit{i}=0}^{8}{\\mathit{f_i}}\\mathbf{\\mathit{e_i}}\\,.\n\\end{equation}\n\nThe fluid pressure field `\\textit{p}' is determined by the \nequation of state\n%\n\\begin{equation}\n\t\\mathit{p}=\\mathit{c_s}^{2} \\rho,\n\\end{equation}\n%\n\\noindent where $\\mathit{c_s}$ is termed the fluid speed of sound and is \nrelated to the lattice speed \\textit{c} as\n%\n\\begin{equation}\n\t\\mathit{c_s}=\\mathit{c}/\\sqrt{3}\\,.\n\\end{equation}\n\nThe kinematic viscosity of the fluid \\textbf{\\textit{v}} is implicitly \ndetermined by the model parameters \\textit{h}, $\\Delta \\mathit{t}$ and $\\tau$ \nas\n%\n\\begin{equation}\n\t\\mathit{v}=\\frac{1}{3}(\\tau - \\frac{1}{2})\\frac{\\mathit{h}^{2}}{\\Delta \n\t\\mathit{t}} = \\frac{1}{3}(\\tau - \\frac{1}{2})\\mathit{Ch},\n\\end{equation}\n%\n\\noindent which indicates that these three parameters are related to each other \nand have to be appropriately selected to represent the correct fluid viscosity. \nAn additional constraint to the parameter selection is the lattice speed \n\\textit{c}, which must be sufficiently large in comparison to the maximum \nfluid velocity $\\mathit{v}_{\\mathit{max}}$, to ensure \naccuracy of the solution. The `computational' Mach number, \n$\\mathit{M}_{\\mathit{a}}$, defined as\n%\n\\begin{equation}\n\t\\mathit{M}_{\\mathit{a}}=\\frac{\\mathit{v}_{\\mathit{max}}}{\\mathit{c}}\\,.\n\\end{equation}\n%\nTheoretically, for an accurate solution, the Mach number is required to be $<< \n1$. In practice, $\\mathit{M}_{\\mathit{a}}$ should be at least smaller than \n0.1~\\citep{He1997}. \nFrom a computational point of view, it is more convenient to choose \\textit{h} \nand $\\tau$ as two independent parameters and $\\Delta \\mathit{t}$ as the derived \nparameter\n%\n\\begin{equation}\n\t\\Delta \\mathit{t} = (\\tau - \\frac{1}{2}) \\frac{h^{2}}{3\\mathit{v}}\\,.\n\\end{equation}\n%\nIt can be observed that $\\tau$ has to be greater than 0.5 \\citep{He1997}. \nSince there is no a \\emph{priori} estimation available to determine appropriate \nvalues \nof \\textit{h} and $\\tau$, for a given fluid flow problem and a know fluid \nviscosity $\\mathit{v}$, a \\textit{trial and error} approach is employed to \nensure a smaller \\textit{Mach Number}. This is similar to choosing an \nappropriate Finite Element mesh size, without using automatic adaptive mesh \ntechniques. \n\n%*******************************************************************************\n\\subsection{Lattice Boltzmann - Multi-Relaxation Time (LBM-MRT)}\n\nThe Lattice Boltzmann Bhatnagar-Gross-Krook (LGBK) method is capable of \nsimulating various hydrodynamics, such as multiphase flows and \nsuspensions in fluid~\\citep{Succi1989,Succi2001}. However, LBM suffers from \nnumerical instability when the dimensionless relaxation time $\\tau$ is close to \n0.5. The Lattice Boltzmann Method -- Multi-Relaxation Time (LBM-MRT) overcomes \nthe deficiencies of linearlised single relaxation LBM-BGK approach, such as the \nfixed Prandtl number (Pr=$\\nu/\\kappa$), where the thermal conductivity \n`$\\kappa$' is unity~\\citep{Liu2003a}. LBM-MRT offers better numerical stability \nand has more degrees of freedom. In LBM-MRT the advection is mapped onto the \nmomentum space by a linear transformation and the flux is finished within the \nvelocity space~\\citep{Du2006}.\n\nThe lattice Boltzmann equation with multiple relaxation time approximation is \nwritten as\n%\n\\begin{equation}\nf_{\\alpha}(\\mathbf{x}+\\mathbf{e}_i\\Delta_t, t+ \n\\Delta_t)-f_{\\alpha}(\\mathbf{x},t)=-\\mathbf{S}_{\\alpha \n\ti}(f_i(\\mathbf{x},t)-f_i^{eq}(\\mathbf{x},t)\\,,\n\\end{equation}\n%\n\\noindent where \\textbf{S} is the collision matrix. The nine eigen values of \n\\textbf{S} are all between 0 and 2 so as to maintain linear stability and \nseparation of scales. This ensures that the relaxation times of non-conserved \nquantities are much faster than the hydrodynamic time scales. The LGBK model is \na special case in which the nine relaxation times are all equal and the \ncollision matrix $\\mathbf{S}=\\frac{1}{\\tau}\\mathbf{I}$, where \\textbf{I} is the \nidentity matrix. The evolutionary progress involves two steps, advection and \nflux:\n%\n\\begin{align}\nf_{\\alpha}^+(\\mathbf{x},t)-f_{\\alpha}(\\mathbf{x},t) & = -\\mathbf{S}_{\\alpha \ni}(f_i(\\mathbf{x},t)-f_i^{eq}(\\mathbf{x},t) \\label{eq:advection}\\\\\nf_{\\alpha}(\\mathbf{x}+e_{\\alpha}\\Delta_t, t+\\Delta_t) & = \nf_{\\alpha}^+(\\mathbf{x},t)\\,.\n\\end{align}\n%\nThe advection (\\cref{eq:advection}) can be mapped to the \nmomentum space by multiplying with a transformation matrix \\textbf{M}. The \nevolutionary equation of LBM--MRT is written as\n%\n\\begin{equation}\n\\mathbf{f}(\\mathbf{x}+\\mathbf{e}_i\\Delta_t, t+ \n\\Delta_t)-\\mathbf{f}(\\mathbf{x},t)=-M^{-1}\\hat{\\mathbf{S}}(\\hat{\\mathbf{f}}\n(\\mathbf{x},t)-\\hat{\\mathbf{f}}^{eq}(\\mathbf{x},t))\\,,\n\\end{equation}\n%\n\\noindent where \\textbf{M} is the transformation matrix mapping a vector \n\\textbf{f} in the discrete velocity space $\\mathds{V}=\\mathds{R}^b$ to a vector \n$\\hat{\\mathbf{f}}$ in the moment space $\\mathds{V}=\\mathds{R}^b$. \n%\n\\begin{gather}\n\\hat{\\mathbf{f}}= \\mathbf{M}\\mathbf{f}\\,, \\\\ \n\\mathbf{f}(\\mathbf{x},t) =\\left[f_0(\\mathbf{x},t),f_1(\\mathbf{x},t),\\dots \nf_8(\\mathbf{x},t)\\right]^T\\,.\n\\end{gather}\n%\nThe collision matrix $\\hat{\\mathbf{S}} = MSM^{-1}$ in moment space is \na diagonal matrix:\n\\begin{equation*}\n\\hat{\\mathbf{S}} =\\mbox{diag} \\left[ s_1, s_2, s_3, \\dots s_9  \\right]\\,.\n\\end{equation*} \n%\nThe transformation matrix \\textbf{M} can be constructed via Gram-Schmidt \northogonalisation procedure. The general form of the transformation matrix \n\\textbf{M} can be written as\n%\n\\begin{equation}\n\\mathbf{M} =  \n\\left[|p\\rangle,|e\\rangle,|e^2\\rangle,|u_x\\rangle,|q_x\\rangle,|u_y\\rangle,\n|q_y\\rangle,|p_{xx}\\rangle,|p_{xy}\\rangle\\right]^T \\,, \\\\\n\\end{equation}\n% \n\\noindent whose elements are, \n%\n\\begin{subequations}\n\\begin{align}\n|p\\rangle & =  |\\mathit{e}_{\\alpha}|^0\\\\\n|e\\rangle_{\\alpha} & = \\mathit{Q}e_{\\alpha}^2-b_2\\\\\n|e^2\\rangle_{\\alpha} & =  \t\na_1(\\mathit{Q}e_{\\alpha}^4-b_6)+a_2(\\mathit{Q}e_{\\alpha}^4-b_6)\\\\\n|u_x\\rangle_{\\alpha} & = e_{\\alpha,x} \\\\\n|q_x\\rangle_{\\alpha} & = (\\mathit{b}_1e_{\\alpha}^2-b_3)e_{\\alpha,x}\\\\\n|u_y\\rangle_{\\alpha} & = e_{\\alpha,y}\\\\\n|q_y\\rangle_{\\alpha} & = (\\mathit{b}_1e_{\\alpha}^2-b_3)e_{\\alpha,y}\\\\\n|p_{xx}\\rangle_{\\alpha} & = \\mathit{d}e_{\\alpha,x}^2-e_{\\alpha}^2\\\\\n|p_{xy}\\rangle_{\\alpha}  & = e_{\\alpha,x}e_{\\alpha,y} \\,,\n\\end{align}\n\\end{subequations}\n\n\\noindent where $d = 2$ and $Q = 9$, $b_1=\\sum_{\\alpha=1}^{Q}e_{\\alpha,x}^2$, \n$b_2=\\sum_{\\alpha=1}^{Q}e_{\\alpha}^2$, \n$b_3=\\sum_{\\alpha=1}^{Q}e_{\\alpha}^2e_{\\alpha,x}^4$, $a_1=||e^2||^2,$ and \n$a_2=\\sum_{\\alpha=0}^{Q-1}(Qc_{\\alpha}^2-b_2)\\times(Qc_{\\alpha}^4-b_6)$. \n\nExplicitly, the transformation matrix can be written as\n%\n\\begin{align}\n\\mathbf{M}= \\begin{bmatrix}\n1 &  1 &  1 &  1 &  1 &  1 &  1 &  1 &  1 \\\\\n-4 & -1 & -1 & -1 & -1 &  2 &  2 &  2 &  2 \\\\ \n4 & -2 & -2 & -2 & -2 &  1 &  1 &  1 &  1 \\\\\n0 &  1 &  0 & -1 &  0 &  1 & -1 & -1 &  1 \\\\\n0 & -2 &  0 &  2 &  0 &  1 & -1 & -1 &  1 \\\\\n0 &  0 &  1 &  0 & -1 &  1 &  1 & -1 & -1 \\\\\n0 &  0 & -2 &  0 &  2 &  1 &  1 & -1 & -1 \\\\\n0 &  1 & -1 &  1 & -1 &  0 &  0 &  0 &  0 \\\\\n0 &  0 &  0 &  0 &  0 &  1 &  1 &  1 &  1 \\\\\n\\end{bmatrix}\\,.\n\\end{align}\n%\nThe corresponding equilibrium distribution functions in moment space \n$\\widehat{\\mathbf{f}^{eq}}$ is given as\n%\n\\begin{equation}\n\\widehat{\\mathbf{f}^{eq}}=\\left[\\rho_0,e^{eq}, \ne^{2eq},u_x,q_x^{eq},q_y^{eq},p_{xx}^{eq},p_{xy}^{eq}\\right]^T\\,,\n\\end{equation}\n%\n\\noindent where\n%\n\\begin{subequations}\n\\begin{align}\ne^{eq} & = \\frac{1}{4}\\alpha_2p+\\frac{1}{6}\\gamma_2(u_x^2+y_y^2)\\\\\ne^{2eq} & = \\frac{1}{4}\\alpha_3p+\\frac{1}{6}\\gamma_4(u_x^2+y_y^2)\\\\\nq_x^{eq} & = \\frac{1}{2}c_1u_x\\\\\nq_y^{eq} & = \\frac{1}{2}c_2u_y \\\\\np_{xx}^{eq} & = \\frac{3}{2}\\gamma_1(u_x^2 - u_y^2)\\\\\np_{xy}^{eq} & = \\frac{3}{2}\\gamma_3(u_xu_y) \\,.\n\\end{align}\n\\end{subequations}\n%\nTo get the correct hydrodynamic equation, the values of the coefficients are \nchosen as $\\alpha_2=24$,  $\\alpha_3=-36$, $c_1=c_2=-2$, \n$\\gamma_1=\\gamma_3=2/3$, $\\gamma_2=18$ and $\\gamma_4=-18$. The values of the \nelements in the collision matrix are: $s_8 = s_9 = \\tau$ \nand $s_1=s_4=s_6=1.0$ and the others vary between 1.0 and 2.0 for linear \nstability. Through the Chapman-Enskog expansion~\\citep{Du2006}, the \nincompressible Navier-Stokes equation can be recovered and the viscosity is \ngiven as\n%\n\\begin{equation}\n\\nu=c_s^2\\Delta t(\\tau-0.5)\\,.\n\\end{equation}\n\n%*******************************************************************************\n\n\\subsection{Boundary conditions}\n\\label{sec:lbm_bc}\nBoundary conditions (BC) form an important part of any numerical technique. In \nmany cases, the boundary conditions can strongly influence the accuracy of the \nalgorithm. Velocity and pressure are not the primary variables in LBM, \nhence the standard pressure, velocity, and mixed boundary conditions cannot be \nimposed directly. Alternative conditions in terms of the distribution \nfunctions are adopted to describe the boundary conditions.\n\n\\subsubsection*{Periodic boundary condition}\n\nThe simplest type of boundary condition is the periodic boundary. In this case, \nthe domain is folded along the direction of the periodic boundary pair. For \nboundary nodes, the neighbouring nodes are on the opposite boundary, using the \nnormal referencing of neighbours (see~\\cref{fig:D2Q9}a). From the perspective \nof submarine landslide modelling, the periodic boundary conditions are useful \nfor preliminary analysis, as they imply a higher degree of symmetry of the \nfluid domain. Further information on the periodic boundary condition can be \nfound in~\\citet{Aidun1998}.\n\n\\subsubsection*{No-slip boundary condition} \\label{bounce}\n\nThe most commonly adopted BC for fluid-solid interface in the lattice Boltzmann \napproach is the no-slip BC, especially the simple bounce-back rule, which is \nquite elegant and surprisingly accurate. The basic idea is that the incoming \ndistribution functions at a wall node are reflected back to the original fluid \nnodes, but with the direction rotated by $\\pi$ radians. The bounce-back \nboundary condition is one of the benefits of LBM, as it is trivial to implement \nand it allows one to effortlessly introduce obstacles into the fluid domain. \nHowever, the boundary conditions have been proven to be only first-order \naccurate in time and space~\\citep{Pan2006}. A straightforward improvement is to \nconsider the wall-fluid interface to be situated halfway between the wall and \nthe fluid lattice nodes~\\citep{Ziegler1993}. It involves defining the \n\\textit{solid} nodes as those lying within the stationary wall regions, and the \n\\textit{fluid} nodes otherwise. Then, if \\textit{i} is the direction between a \nfluid node $\\mathit{n}_{1}$ and a solid node $\\mathit{n_2}$, the bounce-back \nrule requires that the incoming fluid particle from $\\mathit{n}_{1}$ to \n$\\mathit{n}_{2}$ be reflected back along the direction it came from, i.e.,\n%\n\\begin{equation}\n\t\\mathit{f}_{-\\mathit{i}}(\\mathbf{x}, \\mathit{t}+\\Delta \\mathit{t}) = \n\t\\mathit{f_i}(\\mathbf{x}, \\mathit{t}_{+})\\,,\n\\end{equation}\n%\n\\noindent where $-\\mathit{i}$ denotes the opposite direction of \n\\textit{i}. The bounce back rule is illustrated \nin~\\cref{fig:bounce}. This simple rule ensures that no \ntangential velocity exists along the fluid-wall interface, \nthereby a non-slip condition is imposed, and can be extended to \nany shapes or objects in a fluid flow~\\citep{Han2007b,Zou1997}. \nThe slip boundary conditions have similar treatment to the \nnon-slip condition, except that the distribution functions are \nreflected in the boundary instead of \nbounce-back~\\citep{Succi2001}.\n\n\\begin{figure}[htbp]\n\t\\centering\n\t\\includegraphics[width=0.5\\textwidth]{bounce}\n\t\\caption[Half-way bounce back algorithm for the \\textit{D2Q9} \n\tmodel.]{Half-way \n\tbounce back algorithm for the \\textit{D2Q9} model adopted after \n\t\\citet{Sukop2006}.}\n\t\\label{fig:bounce}\n\\end{figure}\n\n\\subsubsection*{Pressure and velocity boundary condition}\n\nThe pressure (Dirichlet) boundary condition can be imposed in \nlattice Boltzmann by specifying a fluid density at the pressure \nboundary~\\citep{Zou1997}. To impose a pressure boundary along \nthe y-direction (for example, consider the left hand side inlet boundary \nin~\\cref{fig:LBMcontour}), a \ndensity $\\rho = \\rho_{in}$ is specified from which the velocity is computed. \nThe vertical component of the velocity on the boundary is set as zero, $u_y=0$. \nAfter streaming, $f_2, f_3, f_4, f_6,$ and $f_7$ are known, $u_x$ and $f_1, \nf_5, f_8$ are to be determined from~\\cref{eq:lbm_macroscopic} as\n%\n\\begin{align}\n f_1+f_5+f_8 & =  \\rho_{in} - (f_0+f_2+f_3+f_4+f_6+f_7) \n \\label{eq:pressure1}\\\\\n f_1+f_5+f_8 & =  \\rho_{in}u_x + (f_3+f_6+f_7) \n \\label{eq:pressure2} \\\\\n f_5 - f_8  & =  f_2 - f_4 +f_6 -f_7\\,,\n\\end{align}\n%\n\\noindent Consistency of~\\cref{eq:pressure1,eq:pressure2} gives\n%\n\\begin{equation}\nu_x  = 1 - \\frac{[f_0+f_2+f_4+2*(f_3+f_6+f_7)]}{\\rho_{in}}\\,.\n\\end{equation}\n\nThe bounce-back rule for the non-equilibrium part of the \nparticle distribution normal to the inlet is used to find $f_1 \n-f_1^{eq} = f_3 -f_3^{eq}$. The values of $f_5$ and $f_8$ can \nbe obtained from $f_1$:\n%\n\\begin{align}\nf_1 & = f_3 + \\frac{2}{3} \\rho_{in}u_x \\nonumber \\\\ \nf_5 & = f_7 - \\frac{1}{2}(f_2 - f_4) + \\frac{1}{6}\\rho_{in}u_x\\nonumber \\\\ \nf_8 & = f_6 + \\frac{1}{2}(f_2 - f_4) + \\frac{1}{6}\\rho_{in}u_x\\,.\n\\end{align}\n\nThe corner node at inlet needs some special treatment. \nConsidering the bottom node at inlet as an example, after \nstreaming, $f_3, f_4, f_7$ are known; $\\rho$ is \ndefined, and $u_x = u_y = 0$. The particle distribution \nfunctions $f_1, f_2, f_5, f_6, $ and  $f_8$ are to be determined. The \nbounce-back rule for the non-equilibrium part of the particle \ndistribution normal to the inlet and the boundary is used to \nfind\n%\n\\begin{align}\nf_1 & = f_3 + (f_1^{eq}-f_3^{eq}) = f_3 \\\\\nf_2 & = f_4 + (f_1^{eq}-f_3^{eq}) = f_4 \\,.\n\\end{align}\n%\n\\noindent Using these we can compute\n%\n\\begin{gather}\nf_5 = f_7 \\\\\nf_6 = f_8 = \\frac{1}{2}[\\rho_{in} - (f_1 + f_2 + f_3 + f_4 + f_5 + f_6 + f_7 + \nf_8)]\\,.\n\\end{gather}\n\nSimilar procedure can be applied to the top inlet node and the outlet \nnodes. Von Neumann boundary conditions constrain the flux at the boundaries. A \nvelocity vector $u=\\left[ u_0\\mbox{ }v_0 \\right]^T$ is specified, from which \nthe density and pressure are computed based on the domain. The velocity \nboundary condition can be specified in a similar way~\\citep{Zou1997}. The \npressure and velocity boundary conditions contribute additional equation(s) \nto determine the unknown distribution functions. In the case of velocity \nboundary, the boundary condition equation is sufficient to determine the \nunknown distribution functions in the \\textit{D2Q9} model, however the pressure \nboundary conditions \nrequire additional constitutive laws to determine the unknown distribution \nfunctions. \n\n%*******************************************************************************\n\\section{Validation of the lattice Boltzmann method}\n\nTo verify the incompressible LBM model implemented in the above section, \nnumerical simulation of a transient development of steady state \nPoiseuille flow in a straight channel is performed. At $t=0$, the LBM water \nparticles ($\\rho=1000 kg/m^{3}$) are simulated to flow through a channel of \nwidth `H' (= 0.4 \\si{\\meter}) and simulation length `L' (2.5H) under constant \nbody force. Periodic boundary conditions are applied at either end of the \nchannel and the pressure gradient is set to zero, which simulates the condition \nof a continuous flow of fluid in a closed circular pipe. The length `L' has no \neffect on the simulation as no stream-wise variation is detected in the \nsolution. The parameters adopted in LBM simulation are presented \nin~\\cref{table:lbm}. Sufficient time is allowed for the flow to travel beyond \nthe required development length so that the flow is laminar~\\citep{Durst2005}. \nThe development length  $\\mathrm{X}_{\\mathrm{D}}$ required for a flow to be \nfully laminar is\n%\n\\begin{equation}\nX_{D}/H=[(0.619)^{1.6}+(0.0567 R_{e})^{1.6}]^{1/1.6} \\,,\n\\end{equation}\n%\n\\noindent where $R_{e}$ is the Reynolds number. The velocity profile at steady \nstate is presented in~\\cref{fig:LBMcontour}. A maximum \nhorizontal velocity of 0.037863~\\si{\\meter\\per\\second} is observed along the \ncentre-line of the channel. The maximum horizontal velocity is compared with \nthe closed-form based on the Haygen-Poiseuille flow equation for no-slip \nboundary condition~\\citep{Willis2008}\n%\n\\begin{equation}\n\t\\mathit{U}_{\\mathit{x}}=\\frac{\\Delta P}{2 \\mu L} [\\frac{H^{2}}{4}-y^{2}]\\,,\n\\end{equation}\n%\n\\noindent where $v_{x}$ is the horizontal velocity (m/s); $\\Delta P$ is the \npressure gradient, $\\mu$ dynamic viscosity of the fluid. LBM predicts the \nmaximum horizontal velocity within an error of 0.009~\\%.\n\n\\begin{table}[tb]\n\\caption{LBM parameters used in simulating laminar flow through \na circular pipe.}\n\\label{table:lbm}\n\\centering\n\\begin{tabular}{ll}\n\\toprule\n\\textbf{Parameter} & \\textbf{Value} \\\\ \\midrule\nDensity $\\rho$ & 1000~\\si{\\kilogram\\per\\metre\\cubed}\\\\ \nRelaxation parameter $\\tau$ & 0.51\\\\ \nKinematic viscosity  & $1 \\times 10^{-6}$~\\si{\\metre\\squared\\per\\second} \\\\\nGrid resolution `h' & $1 \\time 10^{-2} $~\\si{\\meter} \\\\\nNumber of steps & 50,000 \\\\\n\\midrule\nError in predicting horizontal velocity & 0.009 \\% \\\\ \\bottomrule\n\\end{tabular}\n\\end{table}\n\nIn order to further validate the accuracy of the lattice Boltzmann code, the \ntransient development of the Poiseuille's flow is compared with the CFD \nsimulation performed using ANSYS Fluent. The Finite Volume Method is a \ncommon CFD technique, which involves solving the governing partial differential \nequation (Navier-Stokes) over the discretised control volume. This guarantees \nthe conservation of fluxes over a particular control volume. The finite volume \nequations yield governing equations of the form\n%\n\\begin{align}\n\\frac{\\partial}{\\partial t} \\int\\int\\int  Q d\\mathbf{V} + \n\\int\\int \\mathit{F} d\\mathbf{A} = 0\\,,\n\\end{align}\n%\nwhere \\textit{Q} is the vector of conserved variables, \\textit{F} is the vector \nof fluxes in the Navier-Stokes equation, \\textit{V} is the volume of control \nvolume element, and \\textit{A} is the surface area of the control volume \nelement.\n\nA 2D rectangular plane of length 1~\\si{\\meter} and height 0.04~\\si{\\meter} \nis discretised into 400 cells of size $1 \\time 10^{-2} $~\\si{\\meter} \n(see~\\cref{fig:CFDmesh}). A constant velocity is applied at the \ninlet. Water ($\\rho = 998.2\\mbox{ }kg/m^{3},\\mbox{ } \nviscosity`\\eta'=1 \\times 10^{-3}\\mbox{ } Ns/m^{2} $) is allowed to flow through \nthe channel and it develops into a fully laminar flow. The least squares \napproach was adopted to solve the gradient, and a maximum of 100 \niteration steps were carried out until the solution converged. \n\n\\begin{figure}[htbp]\n\t\\centering\n\t\\includegraphics[width=0.85\\textwidth]{LBM_Poiseuille}\n\t\\caption{Velocity profile obtained from a LBM Simulation of a laminar flow \n\tthrough a \n\t\tchannel.}\n\t\\label{fig:LBMcontour}\n\\end{figure}\n%\n\\begin{figure}[htbp]\n\t\\centering\n\t\\includegraphics[width=0.85\\textwidth]{CFD_Mesh}\n\t\\caption{Finite Volume mesh used in the CFD analysis of laminar flow \n\tthrough a \n\t\tchannel.}\n\t\\label{fig:CFDmesh}\n\\end{figure}\n%\n\\begin{figure}[htbp]\n\t\\centering\n\t\\includegraphics[width=0.85\\textwidth]{CFD_Poiseuille}\n\t\\caption{Velocity profile obtained from a CFD analysis of laminar flow \n\tthrough a \n\tchannel.}\n\t\\label{fig:CFDcontour}\n\\end{figure}\n\nThe velocity profile obtained from the CFD simulation at cross-section `L/4' is \nshown in~\\cref{fig:CFDcontour}.~\\Cref{fig:Pois} compares the development of \ncomputed velocity profiles with the analytical solution. At normalised time $t \n= 1$, the flow approaches steady state. It can be observed that LBM has \nexcellent agreement with CFD and the analytical solution at various stages of \nflow evolution.\n\n\\begin{figure}[tbhp]\n\t\\centering\n\t\\includegraphics[width=0.95\\textwidth]{Poiseuille}\n\t\\caption[Comparison between LBM and CFD on the development of the \n\tPoiseuille velocity profile in time.]{Development of the Poiseuille \n\tvelocity \n\tprofile in time: comparison between LBM simulation, CFD simulation and the \n\tanalytical solution. Time is made dimensionless by $H/U_0$.}\n\t\\label{fig:Pois}\n\\end{figure}\n\nIn order to study the capability of the lattice Boltzmann technique to simulate \nfluid--solid interaction, LB simulation of a fluid flow around a rectangular \nobstacle is compared with the CFD technique. A solid wall of height `H/2' is \nplaced at length `L/4' in the channel. Bounce-back algorithm is employed to \nmodel the fluid-wall interaction in LBM. In the CFD model, the control volume \nis discretised into 10,000 cells. A constant velocity is applied in the inlet \nand the horizontal velocity profile is recorded. Both, CFD and LBM simulations \nwere performed to study the influence of a solid wall on the fluid flow \nbehaviour.\n\nThe horizontal velocity profile obtained after 50,000 LBM iterations is \npresented in~\\cref{fig:LBMobstacle}. LBM is able to capture the velocity \nshedding around the edges of the wall. The velocity profile obtained from the \nCFD analysis is presented in~\\cref{fig:CFDobstacle}. The horizontal velocity \nprofile at `L/4' at $t=1$ is shown in~\\cref{fig:Obstacle}. The maximum \nhorizontal velocity from the CFD analysis is 0.3\\% \nhigher in comparison with the LBM simulation. The discrepancy in the horizontal \nvelocity profile (\\cref{fig:Obstacle}) can be attributed to the relaxation \nparameter used in the LBM, which is obtained by a trial and error procedure. \nThe velocity profile obtained from the LBM simulation compares qualitatively \nwith the FE analysis performed by~\\citet{Zhong1991}. Thus, it can be concluded \nthat the lattice Boltzmann method is a suitable form of numerical \nrepresentation of the Navier-Stokes equation to model fluid -- solid \ninteractions. \n\n\\begin{figure}[!t]\n\\centering\n\\hspace{-13mm}\\includegraphics[width=0.95\\textwidth]{LBM_Obstacle}\n\\caption{LBM simulation of velocity profile for a laminar flow through a pipe \nwith an obstacle at L/4.}\n\\label{fig:LBMobstacle}\n\\end{figure}\n\n\\begin{figure}[!ht]\n\\centering\n\\includegraphics[width=0.7\\textwidth]{CFD_Obstacle}\n\\caption{CFD simulation of velocity contour for a laminar flow through a pipe \nwith an obstacle at L/4.}\n\\label{fig:CFDobstacle}\n\\end{figure}\n\n\\begin{figure}[htbp]\n\\centering\n\\includegraphics[width=0.95\\textwidth]{Obstacle}\n\\caption{LBM and CFD simulation of the velocity contour at L/2 for a flow \naround an obstacle at L/4.}\n\\label{fig:Obstacle}\n\\end{figure}\n\n\n%**************************************************************************\n\n\\section{Turbulence in lattice Boltzmann method}\n\nThe above formulation of lattice Boltzmann has been successfully \napplied to many fluid flow problems, however it is restricted to flows with low \nReynolds number. Modelling fluids with low viscosity like water and air \nremains a challenge, necessitating very small values of \\textit{h}, and/or \n$\\tau$ very close to 0.5~\\citep{He1997}. The standard lattice Boltzmann can \ndeal with laminar flows, while practical problems with small kinematic \nviscosity are often associated with flows having large Reynolds numbers, i.e. \nflows which are unsteady or turbulent in nature. Turbulent flows are \ncharacterised by the occurrence of eddies with multiple scales in space, time \nand energy.\n\nThe Large Eddy Simulation (LES) is the most widely adopted approach to \nsolve turbulent flow problems. It directly solves the large scale eddies, which \ncarry the predominant portion of the energy, and the smaller eddies are \nmodelled using a sub-grid approach. The separation of scales is achieved by \nfiltering of the Navier-Stokes equations, from which the resolved scales are \ndirectly obtained. The unresolved scales are modelled by a one-parameter \nSmagorinski sub-grid methodology, which assumes that the Reynolds stress \ntensor is dependent only on the local strain rate~\\citep{Smagorinsky1963}. It \ninvolves parametrising the turbulent energy dissipation in the flows, where the \nlarger eddies extract energy from the mean flow and ultimately transfer some of \nit to the smaller eddies which, in turn, pass the energy to even smaller \neddies, and so on up to the smallest scales. At the smallest scale, the eddies \nconvert the kinetic energy into the internal energy of the fluid. At this \nscale, the viscous friction dominates the flow~\\citep{Frisch1995}.\n\nIn the Smargonisky model, the turbulent viscosity $\\nu$ is related to the \nstrain rate $\\dot{\\epsilon}_{ij}$ and a filtered length scale `h' as follows\n%\n\\begin{align}\n\\dot{\\epsilon}_{ij} & = \\frac{1}{2}(\\partial_i u_j + \\partial_j u_i) \\\\\n\\mathit{v}_{\\mathit{t}} & = (\\mathit{S}_{c}\\mathit{h})^{2}\\overline{\\epsilon} \n\\\\\n\\overline{\\epsilon} & =  \n\\sqrt{\\sum\\limits_{\\mathit{i,j}}{\\tilde{\\epsilon}_{\\mathit{i,j}}\\tilde{\\epsilon}_{\\mathit{i,j}}}}\\,,\n\\end{align}\n%%\n\\nomenclature[a-D]{\\textit{D}}{Diameter of a pipe}\n\\nomenclature[a-Sc]{$S_c$}{Smargonisky constant}\n\\nomenclature[a-Re]{\\textit{Re}}{Reynolds number -  a dimensionless quantity \nthat is used to help predict similar flow patterns in different fluid flow \nsituations}\n\\nomenclature[r-dot]{$\\cdot$}{Rate of change of a variable}\n\\nomenclature[g-taustar]{$\\tau_{*}$}{Total relaxation time}\n\\nomenclature[g-thetadotdot]{$\\ddot{\\theta}$}{Angular acceleration}\n\\nomenclature[a-ns]{$n_s$}{Number of DEM subcycles in a LBM time step}\n%\n\\noindent where $\\mathit{S}_{c}$ is the Smargonisky constant, which is close \nto 0.03~\\citep{yu2005}. \n%\nThe effect of the unresolved scale motion is taken into account by introducing \nan effective collision relaxation time scale $\\tau_{t}$, so that the total \nrelaxation time $\\tau_{*}$ is written as\n%\n\\begin{equation}\n\\tau_{*}=\\tau + \\tau_{t}\\,,\n\\end{equation} \n%\n\\noindent where $\\tau$ and $\\tau_{t}$ are respectively the standard relaxation \ntimes \ncorresponding to the true fluid viscosity $\\nu$ and the turbulence \nviscosity $\\nu_{\\mathit{t}}$, defined by a sub-grid turbulence model. \nThe new viscosity $\\nu_{*}$ corresponding to $\\tau_{*}$ is defined as\n\n\\begin{align}\n\\nu_{*} & \n=\\nu+\\nu_{\\mathit{t}} \\nonumber \\\\\n\t& =\\frac{1}{3}(\\tau_{*}-\\frac{1}{2})\n\\mathit{c}^{2} \\Delta \\mathit{t} \n=\\frac{1}{3}(\\tau+\\tau_{t}-\\frac{1}{2})\\mathit{c}^{2} \\Delta \\mathit{t}  \\\\\n\\nu_{\\mathit{t}} & =\\frac{1}{3}\\tau_{\\mathit{t}}\\mathit{c}^{2} \\Delta \n\\textit{t} \\,.\n\\end{align} \n\nThe Smargonisky model is easy to implement and the lattice Boltzmann \nformulation remains unchanged, except for the use of a new turbulence-related \nviscosity $\\tau_{*}$. The component $s_1$ of the collision matrix becomes $s_1 \n= \\frac{1}{\\tau+\\tau_t}$.\n\nThe effectiveness of LBM-LES model in simulating unsteady flows is verified by \nmodelling the K\\'{a}rm\\'{a}n vortex street. In fluid dynamics, a K\\'{a}rm\\'{a}n \nvortex street is a repeating pattern of vortices caused by unsteady separation \nof fluid flow around circular obstacles. A vortex street will only be observed \nabove a limiting value of Reynolds number of 90. The Reynolds number \nis computed based on the cylinder diameter `D' and the mean flow velocity $U$ \nof the parabolic inflow profile:\n%\n\\begin{equation}\n\\label{eq:reynolds}\nRe=\\frac{UD}{\\nu}\\,.\n\\end{equation}\n\nLBM particles are simulated to flow through a 2D rectangular channel with an \naspect ratio `L/H' of 2.5. A cylinder of diameter `d' $=0.27H$ is placed at \nH/2. The pressure gradient at the inlet and the outlet is varied to create \nflows with different mean velocities. Numerical simulations of vortex \nshedding behind a circular obstacle are carried out for three different fluid \nflow regimes (Reynolds number of 55, 75, and 112). The fully developed fluid \nflows for different Reynolds numbers are shown in~\\cref{fig:karman}. It can be \nobserved from~\\cref{fig:karman} that the Von K\\'{a}rm\\'{a}n vortex street can \nonly be observed at high a Reynolds number of 112 (Re > 90), which shows the \nability of the LBM turbulence model to capture instabilities in fluid flow.\n%\n\\begin{figure}[htbp]\n\t\\centering\n\t\\includegraphics[width=0.95\\textwidth]{karman}\n\t\\caption{Development of K\\'{a}rm\\'{a}n vortex street around a circular \n\tobstacle, for different Reynolds number.}\n\t\\label{fig:karman}\n\\end{figure}\n\nOne important quantity taken into account in the present analysis is the \nStrouhal number St, a dimensionless number describing oscillating unsteady \nflow dynamics. The Strouhal number is computed from the cylinder diameter D, \nthe measured frequency of the vortex shedding f, and the maximum velocity \n$U_{max}$ at the inflow plane:\n%\n\\begin{equation}\nSt=\\frac{fD}{U_{max}}\\,.\n\\end{equation}\n\n\\noindent The characteristic frequency $f$ is determined by a spectral \nanalysis (Fast Fourier Transform - FFT) of time series of the fluid pressure. \n\\Cref{table:strouhal} shows that the Strouhal numbers computed from LBM \nsimulations have a very good agreement with FVM results obtained \nby~\\citet{Breuer2000}. This shows the ability of LBM-LES in capturing unsteady \nflow dynamics.\n\n\n\\begin{table}[tbhp]\n\t\\caption{Computed Strouhal number for fluid flows with different Reynolds \n\tnumber.}\n\t\\label{table:strouhal}\n\t\\centering\n\t\\begin{tabular}{l c c}\n\t\t\\toprule\n\t\tReynolds number & \\multicolumn{2}{c}{Strouhal number} \\\\\n\t\t\\cmidrule{2-3}\n\t\t& LBM & FVM \\\\\n\t\t\\midrule\n\t\t55\t\t& 0.117\t &\t0.117 \\\\\n\t\t75\t\t& 0.128\t &\t0.129 \\\\\n\t\t112\t\t& 0.141  &\t0.141 \\\\\n\t\t\\bottomrule\n\t\t\\multicolumn{3}{l}{\\footnotesize{\\textsuperscript{*}~FVM results are \n\t\tfrom~\\citet{Breuer2000}}}\n\t\\end{tabular}\n\\end{table}\n\n\n\n%************************************************************************* %\n\n\\section{Coupled LBM and DEM for fluid-grain interactions}\n\\label{sec:coupled_lbm_dem}\nModelling fluid--grain interactions in submarine landslides requires the \nability to simulate the interactions at the dynamic fluid -- solid boundaries. \nIn principle, the conventional FE and FVM based approaches for solving the \nNavier-Stokes equations with moving boundaries and/or structural \ninteraction~\\citep{Bathe2004} can be applied to particle fluid interaction \nproblems. The common feature of these approaches is to model the interaction \nbetween the fluid and the solid to a high degree of accuracy. However, the main \ncomputational challenge is the need to continuously generate new geometrically \nadapted meshes to circumvent severe mesh distortion, which is computationally \nvery intensive~\\citep{Han2007a}. \n\nThe lattice Boltzmann approach has the advantage of accommodating large \nparticle sizes and the interaction between the fluid and the moving grains \ncan be modelled through relatively simple fluid - grain interface treatments. \nFurther, employing DEM to account for the grain/grain interaction naturally \nleads to a combined LB -- DEM solution procedure. The Eulerian nature \nof the lattice Boltzmann formulation, together with the common explicit time \nstep scheme of both LBM and DEM makes this coupling strategy an efficient \nnumerical procedure for the simulation of fluid -- grain systems. \n\nLBM -- DEM technique is a powerful predictive tool for gaining insights into \nmany fundamental physical phenomena in fluid-solid systems. \nSuch a coupled methodology was first proposed by~\\citep{Cook2004} for \nsimulating fluid-grain systems dominated by fluid-grain and grain-grain \ninteractions. To capture the actual physical behaviour of the fluid-grain \nsystem, it is essential to model the boundary condition between the fluid and \nthe grain as a non-slip boundary condition, i.e. the fluid velocity near the \ngrain should be similar to the velocity of the grain boundary. The soil grains \nin the fluid domain are represented by lattice nodes. The discrete nature of \nthe lattice will result in stepwise representations of the surfaces, which are \notherwise circular, this is  neither accurate nor smooth, unless sufficiently \nsmall lattice spacing is adopted. \n\n%*******************************************************************************%\n\n\\subsubsection*{Modified bounce back rule}\n\nTo accommodate the movement of solid particles in the commonly adopted \nbounce-back rule (see \\cref{bounce}),~\\citet{Ladd1994} modified the `no-slip' \nrule for a given boundary link \\textit{i} to be\n%\n\\begin{equation}\n\\mathit{f_i}(\\mathbf{x}, t + \\Delta t)=\\mathit{f_i}(\\mathbf{x}, t_{+}) - \n\\alpha_{\\mathit{i}}\\mathbf{\\mathit{e}_i}.\\mathbf{\\mathit{v}}_{b} \\qquad \n(\\alpha_{i}=6\\mathit{w_i}\\rho/\\gamma_{\\mathit{s}}^{2})\\,,\n\\end{equation}\n%\n\\noindent where $\\mathit{f_i}(\\mathbf{x}, t_{+})$ is the post collision \ndistribution at the fluid or solid boundary node \\textbf{x}, and \n$\\mathit{v}_{b}$ is the velocity at the nominal boundary point at the middle of \nthe boundary link \\textit{i}\n%\n\\begin{equation}\n\\mathbf{v}_{b}=\\mathbf{v}_{c}+\\omega \\times \n(\\mathbf{x}+\\mathbf{\\mathit{e}_i}\\Delta t /2 - \\mathbf{x}_{c})\\,,\n\\end{equation}\n%\n\\noindent in which $\\mathbf{\\mathit{v}}_{c}$ and $\\omega$ are the translational \nand angular velocities at the mass centre of the solid particle, respectively. \n$\\mathbf{x}_{c}$ and $\\mathbf{x}+\\mathbf{\\mathit{e}_i}\\Delta t /2$ are the \ncoordinates of the centre and the nominal boundary point,  respectively. The \nimpact force on the soil grain from the link is defined as\n%\n\\begin{equation}\n\\mathbf{F_i}=2[\\mathit{f_i} (\\mathbf{x}, t_{+}) \n-\\alpha_{\\mathit{i}}\\mathbf{\\mathit{e}_i}.\\mathbf{v}_{b}]/ \\Delta t \\,.\n\\end{equation} \n%\nThe corresponding torque $\\mathbf{T}_{\\mathit{i}}$, produced by the force with \nrespect to the centre of the particle is computed as\n%\n\\begin{equation}\n\\mathbf{T}_{\\mathit{i}}=\\mathbf{r}_{c} \\times \\mathit{F_i} \n(\\mathbf{r}_{c}=\\mathbf{x}+\\mathbf{e}_{\\mathit{i}} \\Delta t /2 - \\mathbf{x}_{c})\n\\,.\n\\end{equation}\n%\nThen the total hydrodynamic force and torque exerted on the particle can be \ncalculated by summing up the forces and torques from all the related boundary \nlinks:\n%\n\\begin{equation}\n\\begin{aligned}\n\\mathbf{F} &= \\sum\\limits_{\\mathit{i}}{\\mathbf{F}_{\\mathit{i}}} \\\\\n\\mathbf{T} &= \\sum\\limits_{\\mathit{i}}{\\mathbf{T}_{\\mathit{i}}} \\,.\n\\end{aligned}\n\\end{equation}\n\n\\citet{Ladd2001} described a methodology that minimises the oscillations \nresulting from soil grains crossing lattices at a very high speed. The \nmethodology involves combining several extensions for the fluid simulation like \nthe treatment of moving curved boundaries with the scheme of~\\citet{Yu2003} and \na fluid/grain force interaction method with the momentum exchange method  \nof~\\citet{Ladd2001}. The simulation of the moving curved grain surfaces results \nin the intersection of links between two nodes at arbitrary \ndistances~\\citep{Iglberger2008}. These distance values are referred to as delta \nvalues:\n%\n\\begin{equation}\n\\delta = \\frac{\\mbox{Distance between fluid node and soil\nsurface}}{\\mbox{Distance between fluid node and soil node}} \\in [0,1] \\,.\n\\end{equation} \n%\nFor each pair of a fluid and grain node, a delta value has to be \ncalculated. Delta values of zero are not possible as the nodes on the surface \nare considered as solid nodes. The algorithm for computation of the $\\delta$ \nvalue is presented in~\\citet{Iglberger2008}.~\\Cref{fig:bouncemod} shows the \nthree possible situations for delta values between 0 and 1. The \nfluid particles in LBM are always considered to be moving at the rate of one \nlattice per time step $(\\delta \\mathbf{x}/ \\delta \\mathbf{t})$, for delta \nvalues smaller than 0.5. For $\\delta$ values larger than 0.5, the fluid \nparticles would come to rest at an intermediate node $\\mathbf{x}_{\\mathit{i}}$. \nIn order to calculate the reflected distribution function in node \n$\\mathbf{x}_{\\mathit{f}}$, an interpolation scheme has to be applied. The \nlinear interpolation scheme of~\\citet{Yu2003} is used in the present study, \nwhich uses a single equation, irrespective of the value of $\\delta$ being \nsmaller or larger than 0.5, to the reflected distribution function that is \ncomputed as\n%\n\\begin{align}\n \\nonumber\n\\mathit{\\mathit{f}}_{\\overline{\\alpha}}(\\mathbf{x}_{\\mathit{f}},t + \\delta t) = \n& \\frac{1}{1 + \\delta} \\cdot [(1-\\delta)\\cdot \n\\mathit{\\mathit{f}}_{\\alpha}(\\mathbf{x}_{\\mathit{f}},t + \\delta t) + \\delta \n\\cdot \\mathit{\\mathit{f}}_{\\alpha}(\\mathbf{x}_{\\mathit{b}},t + \\delta t)  \\\\\n& + \\delta \\cdot \n\\mathit{\\mathit{f}}_{\\overline{\\alpha}}(\\mathbf{x}_{\\mathit{f2}},t + \\delta t) \n-2\\mathit{w}_{\\mathit{a}}\\rho_{\\mathit{w}}\\frac{3}{\\gamma^{2}}\n\t\\mathbf{\\mathit{e}}_{\\mathit{a}}\\cdot\n \\mathbf{u}_{\\mathit{w}}]\\,,\n\\end{align}\n%\nwhere $\\mathit{w}_{\\alpha}$ is the weighting factor, $\\rho_{\\mathit{w}}$ is the \nfluid density in node $\\mathbf{x}_{\\mathit{f}}$, and $ \\mathbf{u}_{\\mathit{w}}  \n$ is the velocity at the bounce-back wall. In order to couple the \nfluid-grain interaction, the LBM approach is extended by adopting a force \nintegration scheme, to calculate the fluid force acting on the grain surface, \nand the momentum exchanged method described earlier. The physical force acting \non grain agglomerates is calculated as the sum over all fluid/grain node \npairs, resulting in\n%\n\\begin{equation}\n\\mathit{F} = \n\\sum\\limits_{\\mathbf{x}_{b}}\\sum\\limits_{\\alpha=1}^{19}{\\mathbf{e}_{\\alpha}\n\t[\\mathit{f}_{\\alpha}(\\mathbf{x}_{b},t)\n\t\t+\\mathit{f}_{\\overline{\\alpha}}(\\mathbf{x}_{f},t)]\n \t\t\t\t\\delta \\mathbf{x} / \\delta t}\\,.\n\\end{equation}\n%\nAfter the force calculations, the coupled rigid body physics can be simulated \nin order to move the grains / grain-agglomerates according to the applied \nforces. The total hydrodynamic forces and torque exerted on a grain can be \ncomputed as ~\\citep{Cook2004, Noble1998}\n%\n\\begin{align}\n\\mathbf{F}_{f} & = \\mathit{Ch}[\\sum\\limits_{\\mathit{n}}{(\\beta_{\\mathit{n}} \n\\sum\\limits_{\\mathit{i}}{\\mathit{f_i}^{\\mathit{ m}}\\mathbf{\\mathit{e}_i}}})] \\\\ \n\\mathbf{T}_{f} & = \n\\mathit{Ch}[\\sum\\limits_{\\mathit{n}}{(\\mathbf{x}_{\\mathit{n}}-\\mathbf{x}_{\\gamma})\n \\times (\\beta_{\\mathit{n}} \\sum\\limits_{\\mathit{i}}{\\mathit{f_i}^{\\mathit{ \nm}}\\mathbf{\\mathit{e}_i}})}]\\,.\n\\end{align}\n%\nThe summation is over all lattice nodes covered by the soil grain, and \n$\\mathbf{x}_{\\mathit{n}}$ represents the coordinate of the lattice node \n\\textit{n}.\n%\n\\begin{figure}[htbp]\n\\centering\n\\includegraphics[height=0.9\\textheight]{bouncemod}\n\\caption{LBM bounce back boundaries for different values of $\\delta$.}\n\\label{fig:bouncemod}\n\\end{figure}\n\nWhen grains are not in direct contact among themselves, but are driven by \nthe fluid flow and body force, i.e. gravity, their motion can be determined by \nNewton's equation of motion\n%\n\\begin{align}\n\\mathit{m}\\mathbf{ a} & = \\mathbf{F}_{f} + \\mathit{m }\\mathbf{g} \\\\\n\\mathit{J } \\ddot{\\theta} & = \\mathbf{T}_{f} \\,,\n\\end{align}\n%\n\\noindent where \\textit{m} and \\textit{J} are respectively the mass and the \nmoment of inertia of a grain, $\\ddot{\\theta}$ is the \nangular acceleration, \\textbf{g} is the gravitational acceleration,\n$\\mathbf{F}_{f}$ and $\\mathbf{T}_{f}$ are respectively the hydrodynamic forces \nand torque. The equation can be solved numerically by an explicit numerical \nintegration, such as the central difference scheme. \n\nThe interaction between the soil grains, and the soil grains with the walls are \nmodelled using the DEM technique. To solve the coupled DEM--LBM formulation, \nthe hydrodynamic force exerted on soil grains and the static buoyancy force are \nconsidered by reducing the gravitational acceleration to $(1- \n\\rho/rho_{s})\\mathbf{g}$, where $\\rho_{s}$ is the density of the grains. When \ntaking into account all forces acting on an element, the dynamic equations of \nDEM can be expressed as\n%\n\\begin{equation}\n\\label{eq:mde}\n\\mathit{m}\\mathbf{a} +\\gamma\\mathbf{v} = \\mathbf{F}_{c} + \\mathbf{F}_{f} \n+\\mathit{m}\\mathbf{g} \\,,\n\\end{equation} \n%\n\\noindent where $\\mathbf{F}_{c}$ denotes the total contact forces from other \nelements and/or the walls, and $\\gamma$ is a damping coefficient. The term \n\\textit{c\\textbf{v}} represents a viscous force that accounts for the effect of \nall possible dissipation forces in the system including energy lost during the \ncollision between grains. Considering a linear contact model\n%\n\\begin{equation}\n\\mathbf{F}_{c}=\\mathit{k}_{\\mathit{n}} \\delta \\,,\n\\end{equation}\n%\n\\noindent where $\\mathit{k}_{\\mathit{n}}$ is the normal stiffness and $\\delta$ \nis the overlap, the critical time step associated with the explicit integration \nis determined as~\\citep{He1997}\n%\n\\begin{equation}\n\\Delta t_{\\mathit{cr}}= 2(\\sqrt{1 + \\xi^{2}}-\\xi) / \\omega \\,,\n\\end{equation}\n%\n\\noindent where $\\omega = \\sqrt{\\mathit{k}_{\\mathit{n}}/\\mathit{m}}$ is the \nlocal contact natural frequency and $\\xi = \\gamma/2\\mathit{m}\\omega$ is the \ncritical damping ratio. The actual time step used for the integration of the \nDiscrete Element equations is\n%\n\\begin{equation}\n\\Delta \\mathit{t}_{D}=\\lambda \\Delta \\mathit{t}_{cr} \\,.\n\\end{equation}\n%\nThe time step factor $\\lambda$ is chosen to be around 0.1 to ensure both \nstability and accuracy~\\citep{He1997}.\n\nWhen combining the Discrete Element modelling of the grain interactions with \nthe LB formulation, an issue arises. There are now two time steps: $\\Delta t$ \nfor the fluid flow and $\\Delta t_{D}$ for the particles. Since $\\Delta t_{D}$ \nis normally smaller than $\\Delta t$, $\\Delta t_{D}$ is slightly reduced to a \nnew value $\\Delta t_{s}$ so that $\\Delta t$ and $\\Delta t_{s}$ have an integer \nratio $\\mathit{n}_{\\mathit{s}}$\n%\n\\begin{align}\n\\Delta t_{s}=\\frac{\\Delta t}{\\mathit{n}_{s}} \\qquad(\\mathit{n}_{s}=[\\Delta t/ \n\\Delta t_{D}]+1) \\,.\n\\end{align} \n%\nThis results in a sub-cycling time integration for the Discrete \nElement part. At every step of the fluid computation, $\\mathit{n}_{s}$ \nsub-steps of integration are performed for the Discrete Element \nMethod~\\eqref{eq:mde} using the time step $\\Delta t_{s}$. The hydrodynamic \nforce $\\mathbf{F}_{f}$ is unchanged during the sub-cycling. \n\n\\subsection{Draft, kiss and tumbling: Sedimentation of two grains}\n\nIn multiphase flows, the fundamental mechanisms of fluid -- grain and grain – \ngrain interactions are very important for accurately predicting the flow \nbehaviours. The sedimentation of two circular grains in a viscous fluid serves \nas the simplest problem to study these two types of interactions, and many \nexperimental and numerical studies have been carried out to investigate this \nbehaviour~\\citep{Wang2014,Komiwes2005}.~\\citet{Fortes1987} observed \nexperimentally that in the sedimentation of two grains under gravity in a \nNewtonian fluid, the two grains would undergo the draft, kiss and tumbling \n(DKT) phenomenon.\n\nThe \\emph{draft}: grain 2 is first placed within the hydrodynamic drag above \ngrain 1. As the hydrodynamic drag of grain 1 is a depression zone, \ngrain 2 is attracted inside. The \\emph{kiss}: grain 2 increases its \nvertical velocity until it touches grain 1. The horizontal velocity of \ngrain 1 increases and its vertical velocity decreases below that of \ngrain 2. \\emph{Tumbling}: grain 2 having the same horizontal velocity and \nhigher vertical velocity than grain 1, overtakes grain 1.\n%\n\nLBM-DEM simulation of two grains under gravity in a viscous Newtonian fluid \nreproduces the draft, kiss and tumble effect (see~\\cref{fig:kissing}). They \nare in agreement with the experimental description of the DKT effect. For \nbetter understanding of the DKT effect, the time history of three distances \nbetween the grains (normalised to the diameter of the grain D) are tracked \ni.e., the difference in the transverse coordinates $\\delta_x/D$ and \nlongitudinal coordinates $\\delta_y/D$ of the two grain centres, and the gap \nbetween the two surfaces $\\delta = \\sqrt{{\\delta_x}^2+{\\delta_y}^2} - 1 $ \n(see~\\cref{fig:kissdelta}). \n\nAs shown in~\\cref{fig:kissing}, grain 1 trails grain 2. As grain 2 approaches \nthe depression zone, corresponding to negative fluid pressure behind grain 1, \nthe velocity of the trailing grain increases as the grains approach closer, \nthis is in agreement with the experimental description of the draft. Grain 2 \nincreases its vertical velocity more than grain 1 until it touches grain 1. The \nkiss happens at a normalised time ($t/\\sqrt{(D/g)}$)  = 25. At this stage, the \ngap $\\delta$ between the grains is zero, but the actual gap is about one \nlattice spacing for the LBM collision model. After this time, the vertical \nvelocity of grain 1 decreases and its horizontal velocity increases as the \ngrains tumble. At this stage, the grains still remain in contact, i.e., the gap \nremains unchanged $\\delta=0$. Subsequently, the two grains separate and move \naway from each other.~\\Cref{fig:kissvelocity} shows that the terminal \nvelocities of the two grains are in good agreement with the terminal velocity \nof a single grain found by an independent simulation and calculated using the \nempirical Schiller and Nauman formula~\\citep{Komiwes2005}.\n\n\\begin{figure}[tbhp]\n\\centering\n\\includegraphics[height=0.9\\textheight]{kissing}\n\\caption{Time series of draft, kiss and tumble of two grains \nduring \nsedimentation in a viscous fluid.}\n\\label{fig:kissing}\n\\end{figure}\n\n\\begin{figure}[tbhp]\n\t\\centering\n\t\\begin{subfigure}[b]{0.475\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{Kissing_xy}\n\t\t\\caption{transverse and longitudinal position}\n\t\t\\label{fig:kissxy}\n\t\\end{subfigure}\n\t\\begin{subfigure}[b]{0.475\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{Kissing_velocity}\n\t\t\\caption{normalised velocity}\n\t\t\\label{fig:kissvelocity}\n\t\\end{subfigure}\\\\\n\t\\begin{subfigure}[b]{0.475\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{Kissing_delta}\n\t\t\\caption{distance between grains}\n\t\t\\label{fig:kissdelta}\n\t\\end{subfigure}\n\t\\caption{Time history of sedimentation of two circular grains.}\n\t\\label{fig:kiss}\n\\end{figure}\n\n\\section{GP-GPU Implementation}\n\nThe Graphics Processing Unit (GPU) is a massively multi-threaded architecture \nthat is widely used for graphical and now non-graphical computations. Today's \nGPUs are general purpose processors with support for an accessible programming \ninterface. The main advantage of GPUs is their ability to perform significantly \nmore floating point operations (FLOPs) per unit time than a CPU. General \nPurpose computations on GPUs (GPGPUs) often achieve speed-ups of orders of \nmagnitude in comparison with optimised CPU implementations. \n\nA GPU consists of several \\emph{Streaming Multiprocessors} (SMs). Each SM \ncontains 32 CUDA processors. Each CUDA processor has a fully pipelined integer \narithmetic logic unit (ALU) and a floating point unit (FPU). The FPU complies \nwith the IEEE 754-2008 industry standard for floating-point arithmetic, capable \nof double precision computations. The SM schedules work in groups of 32 threads \ncalled warps. Each SM features two warp schedulers and two instruction dispatch \nunits, allowing two warps to be issued and executed concurrently. Each thread \nhas access to both L1 and L2 caches, which improves the performance for \nprograms with random memory access.\n\nThe occupancy rate of the SPs, i.e. the ratio between the \nnumber of threads run and the maximum number of executable threads, is an \nimportant aspect to take into consideration for the optimisation of a CUDA \nkernel. Even though a block may only be run on a single SM, it is possible to \nexecute several blocks concurrently on the same SM. Hence, tuning the execution \ngrid layout allows one to increase the occupancy rate. Nevertheless, reaching \nthe maximum occupancy is usually not possible, as the threads executed in \nparallel on one SM have to share the available registers~\\citep{Obrecht2011}.\n\nMany-core processors are promising platforms for intrinsically parallel \nalgorithms such as the lattice Boltzmann method. Since the global memory \nfor GPU devices shows high latency and LBM is data intensive, the\nmemory access pattern is an important issue for achieving good performances. \nWhenever possible, global memory loads and stores should be coalescent and \naligned, but the propagation phase in LBM can lead to frequent misaligned \nmemory accesses. Also, the data transfer between the host and the device is \nvery expensive. In the present study, the LBM implementation follows carefully \nchosen data transfer schemes in global memory.\n\nThere are three ways to accelerate GPGPU applications: (a) Using `drop-in' \nlibraries, (b) using directives by exposing parallelism, and (c) using \ndedicated GPGPU programming languages. OpenACC (Open Accelerators) is an open \nGPU directives programming standard for parallel computing on heterogeneous \nCPU/GPU systems. Unlike conventional GPU programming languages, such as CUDA, \nOpenACC uses directives to specify parallel regions in the code and performance \ntuning works on exposing parallelism. OpenACC targets a host-directed execution \nmodel where the sequential code runs on a conventional processor and \ncomputationally intensive parallel pieces of code (kernels) run on an \naccelerator such as a GPU (see~\\cref{fig:GPUConcept}). \n\nInitially, the GPGPU LBM -- DEM code was implemented in C using OpenACC API \nv1.0, which was released in November 2011. The current implementation in C++ \nuses OpenACC API v2.0a~\\citep{OpenACCmembers2013} and has two compute \nconstructs, the kernels construct and the parallel construct. LBM -- DEM \nimplementation predominantly uses the OpenACC gang and vector parallelism. The \nLBM -- DEM code runs sequential and computationally less intensive \nfunctions on the CPU, OpenMP multi-threading is used when possible. \nComputationally intensive functions are converted to a target accelerator \nspecific GPU parallel code. Schematics of a heterogeneous CPU/GPU system is \nshown in~\\cref{fig:GPUConcept}.\n\n\\begin{figure}[tbhp]\n\t\\centering\n\t\\includegraphics[width=0.92\\textwidth]{GPU_Concept}\n\t\\caption{Schematics of a heterogeneous CPU/GPU system.}\n\t\\label{fig:GPUConcept}\n\\end{figure}\n\nOpenACC offers kernel and parallel constructs to parallelise algorithms on CUDA \nkernels. The loop nests in a kernel construct are converted by the compiler \ninto parallel kernels that run efficiently on a GPU. There are three steps to \nthis process. The first is to identify the loops that can be executed \nin parallel. The second is to map that abstract loop parallelism onto a \nconcrete hardware parallelism. In OpenACC terms, gang parallelism maps to \ngrid-level parallelism (equivalent to a CUDA blockIdx), and vector parallelism \nmaps to thread-level parallelism (equivalent to a CUDA threadIdx). The compiler \nnormally maps a single loop across multiple levels of parallelism using \nstrip-mining. Finally, in step three the compiler generates and optimises the \nactual code to implement the selected parallelism mapping.\n\nAn OpenACC parallel construct creates a number of parallel threads that \nimmediately begin executing the body of the parallel construct redundantly. \nWhen a thread reaches a work-sharing loop, that thread will execute some subset \nof the loop iterations, depending on the scheduling policy as specified by the \nprogram or at the runtime. The code generation and optimization for a parallel \nconstruct is essentially the same as for the kernel construct. A key \ndifference is that unlike a kernel construct, the entire parallel construct \nbecomes a single target parallel operation, aka a single CUDA kernel. Both \nconstructs allow for automatic vectorization within the loops~\\citep{Wolfe2012}.\n\nAn excerpt from the LBM-DEM code showing the OpenACC GPU implementation of the \nhydrodynamic force computation is presented in Listing~\\ref{lst:GPU}. The \nkernels loop construct tells the compiler to map the body of the following loop \ninto an accelerator kernel. The GPU implementation uses a two-dimensional grid \nsplitting the iterations across both the vector and gang modes. The kernel is \nmapped to a vector mode mapped (aligned with CUDA threadidx\\%x) with a vector \nlength (thread block size) of 128. The kernel is also mapped to gang \nparallelism, aligned to CUDA blockidx\\%x, to avoid partition camping by mapping \nthe stride-1 loop to the x dimension. The compiler strip-mines the loop into \nchunks of 256 iterations, mapping the 256 iterations of a chunk in vector mode \nacross the threads of a CUDA thread block, and maps the n/256 chunks in gang \nmode across the thread blocks of the CUDA grid. The consecutive iterations (i \nand i+1), which refer to contiguous array elements (fhf[i] and fhf[i+1]), are \nmapped to adjacent CUDA threads in the same thread block, to optimise for \ncoalesced memory accesses. \n\nMemory transaction optimisation is more important than computation\noptimisation. Registers do not give rise to any specific problem apart from \ntheir limited amount. Global memory, being the only one accessible by both the \nCPU and the GPU, is the critical path as it suffers from high latency. However, \nthis latency is mostly hidden by the scheduler which stalls inactive warps \nuntil data are available. For data intensive LBM, this aspect is generally the \nlimiting factor~\\citep{Obrecht2011}. To optimise the global memory \ntransactions, the memory access is coalesced and aligned, as explained above. \nThe memory transactions between the host and the target through a PCI bus are \nkept to a minimum.\n\n\\clearpage\n\n\\begin{lstlisting}[label=lst:GPU,caption= OpenACC GPU implementation of the \nhydrodynamic force computation.,style=customcpp]\n//OpenACC Kernels copy data between the host and the device\n#pragma acc kernels \ncopyout(fhf1[0:nbgrains], fhf2[0:nbgrains], fhf3[0:nbgrains]) \ncopyin(obst[0:][0:], g[0:nbgrains], ey[0:], f[0:][0:][0:], ex[0:])\n//Create individual threads for each DEM grain\n#pragma acc parallel for\nfor (i=0; i<nbgrains;i++) {\n  // Reset hydrodynamic forces to zero at the start of time step\n  fhf1[i]=fhf2[i]=fhf3[i]=0.;\n  // Iterate through all lattice nodes\n  for (y=0; y<ly;y++) {\n    for (x=0; x<lx;x++) {\n      if(obst[x][y]==i) {\n        // generate code to execute the iterations in parallel with\n        // no synchronization\n        #pragma acc for independent\n        for (iLB=1; iLB<Q; iLB++) {\n          next_x=x+ex[iLB];\n          next_y=y+ey[iLB];\n          if(iLB<=half) halfq=half;\n          else halfq= $-$half;\n          if(obst[next_x][next_y]!=i) {\n            fnx=(f[x][y][iLB+halfq]+f[next_x][next_y][iLB])*ex[iLB+halfq];\n            fny=(f[x][y][iLB+halfq]+f[next_x][next_y][iLB])*ey[iLB+halfq];\n            fhf1[i]=fhf1[i]+fnx;\n            fhf2[i]=fhf2[i]+fny;\n            fhf3[i]=fhf3[i]$-$fnx*(y$-$(g[i].x2$-$wall_bottom_y)/dx) \n                    +fny*(x$-$(g[i].x1$-$wall_left_x)/dx);\n          }\t\t\t\n        }\n      }\n    }\n  }\n}\n\\end{lstlisting}\n\nA two-dimensional fluid -- grain system, which consists of 7.2 million LBM \nnodes and 2500 DEM grains is used to demonstrate the ability of the GPGPU LBM \n-- DEM code. The wall time required to compute 100 iterations of the given LBM \n-- DEM  problem is compared for executions running on a single CPU thread, \nmulti-threaded CPU (using OpenMP) and the GPGPU implementations \n(see~\\cref{table:GPU}). The speed-up of parallel implementations are measured \nagainst the single CPU thread execution time. OpenMP parallelised \nmulti-threaded CPU execution running on 12 cores achieved a speed-up of 13.5x \nin comparison to a serial implementation. GPGPU implementation using OpenACC \ndelivered an impressive 126x speed-up in comparison to a single thread CPU \nexecution and about 10 times quicker than a CPU parallel code. In other words, \na simulation that would have ordinarily taken 126 days to compute, could now be \nfinished in a day using a GPU.\n\n\n\n\n\n\n\\begin{table}[tbhp]\n\t\\caption{GPU vs. CPU parallelisation.}\n\t\\label{table:GPU}\n\t\\centering\n\t\\begin{tabular}{l l l}\n\t\t\\toprule\n\t\tExecution & Computational Time (s) &  Speedup \\\\\n\t\t\\midrule\n\t\tCPU 1 OpenMP thread\t\t& 2016\t & -- \\\\\n\t\tCPU 2 OpenMP threads\t& 1035\t & 1.5 x \\\\\n\t\tCPU 4 OpenMP threads\t& 660 \t & 3.0 x \\\\\n\t\tCPU 12 OpenMP threads\t& 150\t & 13.5 x\\\\\n\t\tGPU OpenACC\t\t\t\t& 16\t & 126.0 x \\\\\n\t\t\\bottomrule\n\t\t\\multicolumn{3}{l}{\\footnotesize{\\textsuperscript{\\#}}~Wall time \n\t\tfor 100 iteration for 7.2 Million LBM nodes and 2500 DEM grains.} \\\\\n\t\t\\multicolumn{3}{l}{\\footnotesize{\\textsuperscript{*}~CPU OpenMP threads \n\t\t- 6 core Intel Xeon $\\mathrm{@}$ 3.3GHz}} \\\\\n\t\t\\multicolumn{3}{l}{\\footnotesize{\\textsuperscript{\\dag}~GPU threads - \n\t\tGeForce GTX 580 - 512 CUDA cores}}\n\t\\end{tabular}\n\\end{table}\n\nScalability is an important criterion when developing high-performance \ncomputing codes. Scalability in GPUs is measured in terms of SM utilisation. It \nis important to distribute sufficient work to all SMs such that on every cycle \nthe warp scheduler has at least one warp eligible to issue instructions. In \ngeneral, sufficient warps on each SM should be available to hide instruction \nand memory latency and to provide a variety of instruction types to \nfill the execution pipeline.~\\Cref{fig:GPUSpeed} shows the scalability of \nGPGPU implementation as the LBM domain size is increased from 500,000 to 9 \nmillion nodes. With increase in LBM nodes the computation time increases \nlinearly with a slope of about 2, which shows that the LBM--DEM implementation \nalgorithm scales with the domain size.\n\n\\begin{figure}[tbhp]\n\t\\centering\n\t\\includegraphics[width=0.87\\textwidth]{GPU_Speedup}\n\t\\caption{Test of scalability of the GPU parallelised code with increase in \n\tthe number of LBM nodes.}\n\t\\label{fig:GPUSpeed}\n\\end{figure}\n\nA two-dimensional coupled LBM--DEM technique is developed to understand the \nlocal rheology of granular flows in fluid. The coupled LBM--DEM technique \noffers the possibility to capture the intricate micro-scale effects such as the \nhydrodynamic instabilities. The Smargonisky turbulence model is implement in \nLBM to capture the unsteady flow dynamics in underwater granular avalanches. \nThe GPGPU implementation of the coupled LBM -- DEM technique offers the \ncapability to model large scale fluid -- grain systems, which are otherwise \nimpossible to model using conventional computation techniques. Efficient data \ntransfer mechanisms that achieve coalesced global memory ensure that the \nGPGPU implementation scales linearly with the domain size.\n", "meta": {"hexsha": "52942c7bfc00561abfee1552a5f84334cc9d1afa", "size": 71900, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapter5/chapter5.tex", "max_stars_repo_name": "kks32/phd-thesis", "max_stars_repo_head_hexsha": "18cab9acd8bed4970dea72d8b5c6cc0617c14f3a", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-08-31T01:39:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-21T22:01:16.000Z", "max_issues_repo_path": "Chapter5/chapter5.tex", "max_issues_repo_name": "kks32/phd-thesis", "max_issues_repo_head_hexsha": "18cab9acd8bed4970dea72d8b5c6cc0617c14f3a", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter5/chapter5.tex", "max_forks_repo_name": "kks32/phd-thesis", "max_forks_repo_head_hexsha": "18cab9acd8bed4970dea72d8b5c6cc0617c14f3a", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2016-09-17T20:14:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-04T08:16:32.000Z", "avg_line_length": 47.7740863787, "max_line_length": 100, "alphanum_fraction": 0.7416272601, "num_tokens": 20798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.307508490360365}}
{"text": "% Introduction\n\n\\chapter{Introduction}\n\nSpecialized hardware for running deep learning algorithms seems to be a natural step in the evolution of\nArtificial Intelligence.  Google, for example, developed its own \\gls{asic} named \\gls{tpu}\nto accelerate tensor computations. The formidable cost of such endeavors limits \\gls{asic} development to\nthe big players in the industry. For tech startups and hobbyists, the \\gls{fpga} comes to rescue by filling\nthe gap between high-cost customized ICs and the need to make specialized hardware for certain\napplications. The programmable logic blocks contained in the \\gls{fpga} can be reconfigured, making it\nideal for situations where ``in the field'' functionality update is required. It is also a valuable tool\nfor fast prototyping and verification of \\gls{asic} design with low cost.\n\nIn machine learning, a discriminative model takes data that can be observed from a phenomenon and outputs\ndata that can only be inferred. For instance, let the phenomenon be a group of people speaking different\nlanguages, a discriminative model can take the speech data and infer the language being spoken. In other\nwords, the model classifies the speeches into different language types or labels. This can be done, e.g.,\nby analyzing the linguistic models of each speech and observing the differences. By contrast, a generative\nmodel outputs both data that can be directly observed as well as data that can only be inferred. Therefore,\nin the previous example, a generative model would have to actually learn each language and be able to generate\nspeeches of them. Probabilistically speaking, a discriminative model learns the conditional probability\ndistribution $P(Y \\vert X)$ (the probability of language $Y$ given speech $X$), while a generative model\nlearns the joint probability distribution $P(X,Y) = P(X \\vert Y)P(Y)$, which explicitly models the speech\ngeneration process of each language class.\n\nGenerative models are interesting since they are capable of creating new data that resembles the real world\ndata. These models enable the machine to paint new paintings, compose new music, or write new poetries.\nMany types of generative model exist \\cite{Goodfellow-et-al-2016},\nincluding deep belief networks, variational autoencoder,\nBoltzmann machine, \\glspl{gan}, etc. A \\gls{gan} model consists of two different neural networks trained to\ncompete against each other in order to learn about the probability distribution of a particular dataset.\nThe training process pits the two players in a minimax game so that the performance of both networks improves\nover time. Introduced in 2014 by Ian Goodfellow \\textit{et al.} \\cite{goodfellow:gan}, it soon gained\npopularity in the machine learning community, kindled a wave of research on improving the training properties\nand generation quality.\n\nThe marriage of \\gls{fpga} and \\gls{gan} seems to be an interesting topic in its own right. This project\nexplores such possibilities by implementing a pre-trained generator model of \\gls{dcgan} proposed by\nAlec Radford \\textit{et al.} \\cite{radford:conv_gan} on \\gls{fpga} to generate realistic pictures.\nFigure \\ref{fig:bedroom} shows a group of generated images of bedrooms trained from the LSUN dataset\n\\cite{yu15lsun}.\n\n\\begin{figure}[h]\n  \\centering\n  \\includegraphics[scale=0.5]{bedroom}\n  \\caption{Images of bedrooms generated by \\gls{dcgan} \\cite{radford:conv_gan}}\n  \\label{fig:bedroom}\n\\end{figure}\n\nNowadays, \\gls{hls} is a popular option for implementing algorithms on \\gls{fpga}. \\gls{hls} takes a\nbehavioral description written in a high-level programming language such as C and translates the description\ninto \\gls{rtl} \\gls{hdl} such as Verilog or VHDL. This approach is particularly favored by engineers with\na software background who wish to quickly convert an algorithmic description into hardware implementation.\nIn this project, however, low-level \\gls{hdl} was chosen to implement the generator model in order to gain\nfiner control of the implementation details. The architecture was designed with simplicity in mind and\nabstained from premature optimizations. This paper serves as a rather detailed documentation of the design and\nimplementation process. The source code of this project is published on GitHub \\cite{github:dcgan_fpga} under\nApache License 2.0.\n\n\\clearpage %force the next chapter to start on a new page. Keep that as the last line of your chapter!\n", "meta": {"hexsha": "bbd6d0cab093755bb5776e16a535532328dd3e64", "size": 4420, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/introduction.tex", "max_stars_repo_name": "lambdalainen/metropolia-thesis-latex", "max_stars_repo_head_hexsha": "d7e705ad24f1f8065b2e7f026db5fdc90a7c8b3a", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/introduction.tex", "max_issues_repo_name": "lambdalainen/metropolia-thesis-latex", "max_issues_repo_head_hexsha": "d7e705ad24f1f8065b2e7f026db5fdc90a7c8b3a", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/introduction.tex", "max_forks_repo_name": "lambdalainen/metropolia-thesis-latex", "max_forks_repo_head_hexsha": "d7e705ad24f1f8065b2e7f026db5fdc90a7c8b3a", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 72.4590163934, "max_line_length": 110, "alphanum_fraction": 0.8036199095, "num_tokens": 1021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.30750848357452826}}
{"text": "\\section{SI Units}\n  \\subsection{Base Units}\n  \\begin{itemize}\n    \\item Length - meter - m\n    \\item Mass - kilogram - kg\n    \\item Time - second - s\n    \\item Electric Current - ampere - A\n    \\item Thermodynamic Temperature - kelvin - K\n    \\item Amount of substance - mole - mol\n    \\item Luminous intensity - candela - cd\n  \\end{itemize}\n  \\subsection{Derived Units}\n  \\begin{itemize}\n    \\item Frequency - hertz - Hz - $s^{-1}$\n    \\item Force - newton - N - $m*kg*s^{-2}$\n    \\item Pressure - pascal - Pa - $\\frac{N}{m^2}$\n    \\item Energy - joule - J - $N*m$\n    \\item Power - watt - W - $\\frac{J}{s}$\n    \\item Electric charge - coulomb - C - $s*A$\n    \\item Electric potential - volt - V - $\\frac{W}{A}$\n    \\item Electric resistance - ohm - $\\Omega$ - $\\frac{V}{A}$\n    \\item Celsius temperature - degree Celsius - $\\si{\\degree}C$ - $K-272.15 $\n  \\end{itemize}\n\\newpage", "meta": {"hexsha": "ecc3952fa8c2395bfc6b2e6cc7cfa9c0d4496017", "size": 880, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "physics204/Sections/1SIUnits.tex", "max_stars_repo_name": "CameronSWilliamson/GU-MATH", "max_stars_repo_head_hexsha": "a501bcb919b60bc35fa43b99eb6ed2a2630cb100", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-18T00:49:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-18T00:49:14.000Z", "max_issues_repo_path": "physics204/Sections/1SIUnits.tex", "max_issues_repo_name": "therealkeyisme/Math-Notes", "max_issues_repo_head_hexsha": "a501bcb919b60bc35fa43b99eb6ed2a2630cb100", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "physics204/Sections/1SIUnits.tex", "max_forks_repo_name": "therealkeyisme/Math-Notes", "max_forks_repo_head_hexsha": "a501bcb919b60bc35fa43b99eb6ed2a2630cb100", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6666666667, "max_line_length": 78, "alphanum_fraction": 0.6, "num_tokens": 291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3074375046776287}}
{"text": "\\section*{Abstract - English}%\n\\label{sec:abstract}\n\nThe purpose of this study is to create a framework that is able to\nautomatically detect unusual behaviour in non-linear, dynamical systems.  We\nassume no prior information about the physics that govern these dynamics, so\nthere is no knowledge about the kind of anomaly that we are looking for.  This\nis motivated by the large amounts of output that state of the art,\neddy-resolving ocean models produce.  These large datasets might contain\nunknown physical behaviour, such as the recently discovered Kuroshio anomaly\n(Sec.~\\ref{sec:kuroshio}).  It is impossible for humans to evaluate all the\navailable climate model data within an acceptable time frame. An automated\nanomaly detection is a first step towards harnessing the full potential of such\nexpensive simulations and could contribute to a deeper understanding of the\nocean circulation.\\\\\n\nThe detection problem is approached by trying to define what is normal, so that\neverything that looks significantly different from this norm can be treated as\nanomalous. This norm is found by predicting the future evolution of a system\nthat has been observed for a certain amount of time.  This is not a trivial\ntask, because non-linear systems can exhibit chaotic behaviour which makes\ntheir prediction notoriously hard. However, recent research indicates that it\ncan be solved by employing a special kind of recurrent neural network. Once the\nprediction is extracted from the network, it can be compared to the true values\nof the dataset and where they deviate significantly, a potential anomaly is\nfound.\n\nThe type of recurrent network that is used is called \\emph{echo state network}\nand belongs to the class of \\emph{reservoir computing} methods.  They feature a\ncomparatively low computational cost and have been shown to be able to predict\nchaotic systems with surprising accuracy [\\cite{pathak2018model}].\\\\\n\nConcepts of machine learning and artificial intelligence are, despite their\nproven effectiveness in other fields, still very sparsely utilized in climate\nresearch.  Therefore this work also serves as a showcase of what can be done by\nexpanding the set of standard analysis tools towards these methods.  The final\nresult is the successful detection of the Kuroshio anomaly in the turbulent\nocean dataset.\\\\\n\nThe Python package that implements the anomaly detection is published in a GitHub\nrepository (\\url{https://github.com/nmheim/torsk}).\n", "meta": {"hexsha": "14090467829b801f9f500d87124a4ca35df3ed3e", "size": 2457, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "frontmatter/abstract_en.tex", "max_stars_repo_name": "nmheim/thesis", "max_stars_repo_head_hexsha": "feafb9f5c7bcf6b6473d3fca844a33dc25dcff0f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-09-22T12:17:23.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-22T12:17:23.000Z", "max_issues_repo_path": "frontmatter/abstract_en.tex", "max_issues_repo_name": "nmheim/thesis", "max_issues_repo_head_hexsha": "feafb9f5c7bcf6b6473d3fca844a33dc25dcff0f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "frontmatter/abstract_en.tex", "max_forks_repo_name": "nmheim/thesis", "max_forks_repo_head_hexsha": "feafb9f5c7bcf6b6473d3fca844a33dc25dcff0f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 58.5, "max_line_length": 81, "alphanum_fraction": 0.8131868132, "num_tokens": 521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3074375046776287}}
{"text": "\\documentclass[12pt, answers]{exam}\n%\\documentclass[12pt]{exam}\n\\usepackage[top=1in, bottom=1in, left=1in, right=1in]{geometry}\n\\usepackage{setspace}\n\\PassOptionsToPackage{hyphens}{url}\n\\usepackage{tabu}\n\\onehalfspacing\n\\setlength{\\parindent}{0mm} \\setlength{\\parskip}{1em}\n\n% packages\n\\RequirePackage{amssymb, amsfonts, amsmath, latexsym, verbatim, xspace, setspace}\n\\RequirePackage{tikz}\n% The float package HAS to load before hyperref\n\\usepackage{float} % for psuedocode formatting\n\\usepackage{amsthm}\n\\usepackage{epsfig}\n\\usepackage{times}\n\\renewcommand{\\ttdefault}{cmtt}\n\\usepackage{amsmath}\n\\usepackage{graphicx} % for graphics files\n\n% for creating indented blocks\n\\usepackage{scrextend}\n\\usepackage{paralist, tabularx}\n\n% from Denovo Methods Manual\n\\usepackage{mathrsfs}\n\\usepackage[mathcal]{euscript}\n\\usepackage{color}\n\\usepackage{array}\n\n\\usepackage[pdftex]{hyperref}\n\\usepackage[parfill]{parskip}\n\\usepackage{cancel}\n\n\\newcommand{\\nth}{n\\ensuremath{^{\\text{th}}} }\n\\newcommand{\\ve}[1]{\\ensuremath{\\mathbf{#1}}}\n\\newcommand{\\Macro}{\\ensuremath{\\Sigma}}\n\\newcommand{\\vOmega}{\\ensuremath{\\hat{\\Omega}}}\n\\newcommand{\\cc}[1]{\\ensuremath{\\overline{#1}}}\n\\newcommand{\\ccm}[1]{\\ensuremath{\\overline{\\mathbf{#1}}}}\n\n\n\n%--------------------------------------------------------------------\n%--------------------------------------------------------------------\n\\begin{document}\n\\begin{center}\n{\\bf NE 155, Topic 14, S21 \\\\\nFinite Difference and Volume Methods for the Eigenvalue form of the DE \\\\ April 1, 2021}\n\\end{center}\n\n\\setlength{\\unitlength}{1in}\n\\begin{picture}(6,.1) \n\\put(0,0) {\\line(1,0){6.25}}         \n\\end{picture}\n\n%------------------------------------------\n\\subsection*{Helmholtz Form}\nWhen we derived the Diffusion Equation, we skipped over the Helmholtz form. I am bringing it up now b/c it can be a convenient way to solve the DE. This approach can also be useful if you need to generate an analytical solution.\n\nIn steady state, we can write the diffusion equation this way:\n%\n\\begin{align*}\n-\\nabla \\cdot D(\\vec{r})\\nabla \\phi(\\vec{r}) + \n\\Sigma_a \\phi(\\vec{r}) &= Q(\\vec{r})\\:, \\\\\n%\n\\text{where }\\qquad Q(\\vec{r}) &=\n\\nu \\Sigma_f \\phi(\\vec{r}) +\nS(\\vec{r})\\:,\n\\end{align*}\n%\nwhich can be written as the Helmholtz equation of applied mathematics:\n%http://en.wikipedia.org/wiki/Helmholtz_equation\n%\n\\ifprintanswers \n\\begin{align*}\n\\nabla^2 \\phi(\\vec{r}) - \\frac{1}{L^2}\\phi(\\vec{r}) &= \\frac{-Q(\\vec{r})}{D}\\:, \\\\\n\\text{where }\\qquad L &\\equiv \\sqrt{\\frac{D}{\\Sigma_a}}\\:.\n\\end{align*}\n\\else\n\\\\ \\vspace*{4em}\\\\\n\\fi\n%\n$L$ is called the neutron diffusion length. This is ``how far a neutron diffuses from a source prior to absorption\". \n\nIn the Helmholtz formulation, $\\phi$ is amplitude and $\\frac{1}{L}$ is wave number. \n\nThis formulation is useful because we know how to solve it. We write\n\\[\\phi(\\vec{r}) = \\phi_H(\\vec{r}) + \\phi_P(\\vec{r}) \\:,\\]\n\nFor example, we often have:\n\\[\\phi_H(\\vec{r}) = A\\exp\\bigl(-\\frac{|\\vec{r}|}{L}\\bigr) + B\\exp\\bigl(\\frac{|\\vec{r}|}{L}\\bigr) \\:.\\]\n\nGoing through how to solve this analytically in a variety of circumstances, geometries, etc.\\ is another class (NE 150/250). \n\n%------------------------------------------\n\\subsection*{Criticality Calculations}\n\\textbf{Recall:}\n\nWe also want to think about the details of how to configure a reactor to get it to work the way we want it to. \nWe can write our DE in steady state for a nuclear reactor core:\n%\n\\begin{align*}\n-\\nabla \\cdot D\\nabla \\phi(\\vec{r}) + \n\\Sigma_a \\phi(\\vec{r}) &= \\nu \\Sigma_f \\phi(\\vec{r})\\:, \\\\\n\\text{with} \\qquad \\phi(\\tilde{x}_s) &= 0\\:.\n\\end{align*}\n%\nUnless we have the proper combination of core composition ($\\Sigma_a$, $\\Sigma_f$, $D$) and geometry ($\\vec{r}$ ,$\\vec{r}_s$) details, there is \\underline{no} general solution. \n\nTo deal with this, we introduce a parameter $k$ into the equation:\n%\n\\begin{equation}\n-\\nabla \\cdot D\\nabla \\phi(\\vec{r}) + \n\\Sigma_a \\phi(\\vec{r}) = \\frac{1}{k}\\nu \\Sigma_f \\phi(\\vec{r})\\:. \\nonumber\n\\end{equation}\n%\nThen, for any value of $k$ we assert that there is always a solution. We use an iterative process to find the condition when $k=1$, called ``critical''.\n\n%A reactor is called \\textbf{``critical''} if the chain reaction is self-sustaining and time-independent. Another way to think of the addition of $k$ is to assume $\\nu$ can be adjusted to obtain a time-independent solution by replacing it with $\\frac{\\nu}{k}$, where $k$ is the parameter expressing the deviation from critical. \n%\n%This substitution changes the transport equation into an \\textbf{eigenvalue problem.} A spectrum of eigenvalues can be found, but at \\textbf{long times only the non-negative solution corresponding to the largest real eigenvalue will dominate}, and that's $k$. \n%\n%$k$ can also be thought of as the asymptotic ratio of the number of neutrons in one generation to the number in the next.\n\n%--------------------------------------------------------------------\n\\section*{Finite Difference Method, Eigenvalue Problem}\n\nWe can extend all of the finite difference and finite volume methods we just learned to the eigenvalue problem case, which is another layer of complication. \n\nNow instead of a fixed source, we have an eigenvalue problem\n\\[-\\frac{d}{dx}D(x)\\frac{d \\phi(x)}{dx} + \\Sigma_a(x) \\phi(x) = \\frac{1}{k}\\nu \\Sigma_f(x) \\phi(x) \\]\n%\n\\begin{figure}[h!]\n\\begin{center}\n\\includegraphics[height=1in]{FVM-fig}\n\\end{center}\n\\end{figure}\n%\nLet's again have a reflecting condition at the centerline ($x_0 = 0$) and vacuum on the right ($x_n = a$):\n\\begin{align}\n\\frac{d}{dx}\\phi(x) \\big|_{x=0} &= 0 \\qquad \\text{zero net current,} \\nonumber\\\\\n\\phi(\\tilde{a}) &= 0 \\qquad \\tilde{a} = a + 2D\\:. \\nonumber\n\\end{align}\n%\nWe again have a spatial mesh:\n%\n\\begin{center}\n\\begin{tikzpicture}\n\\draw (-.25,0)--(1.25,0);\n\\draw[dotted] (1.25,0)--(2.75,0);\n\\draw (2.75,0)--(5.25,0);\n\\draw[dotted] (5.25,0)--(6.75,0);\n\\draw (6.75,0)--(8.25,0);\n%\\draw (4,0)--(5.25,0);\n\\draw (0,-.25)--(0,.25);\n\\draw (1,-.25)--(1,.25);\n%\\draw (2,-.25)--(2,.25);\n\\draw (3,-.25)--(3,.25);\n\\draw (4,-.25)--(4,.25);\n\\draw (5,-.25)--(5,.25);\n\\draw (7,-.25)--(7,.25);\n\\draw (8,-.25)--(8,.25);\n\\node[below] at (0,-.25) {$x_0$};\n\\node[below] at (1,-.25) {$x_1$};\n\\node[below] at (3,-.25) {$x_{i-1}$};\n\\node[below] at (4,-.25) {$x_i$};\n\\node[below] at (5,-.25) {$x_{i+1}$};\n\\node[below] at (7,-.25) {$x_{n-1}$};\n\\node[below] at (8,-.25) {$x_n$};\n\\node[above] at (0.5, 0.5) {$h_1$};\n\\node[above] at (3.5, 0.5) {$h_i$};\n\\end{tikzpicture}\n\\end{center}\n%\nand in this configuration $x_0 = 0$, $x_n = a$, and $h_i$ is the mesh spacing. There are $n+1$ points and $n$ mesh cells.\n\nMaterial discontinuities will coincide with the cell \\textit{edges}, $x_i$. Thus, we can assume that the cross sections and the diffusion coefficient are constant in each cell.\n%\n%\\begin{align}\n%D(x) &= D_i \\qquad \\text{for } x_{i-1} \\leq x \\leq x_i \\:,\\nonumber \\\\\n%\\Sigma_{a}(x) &= \\Sigma_{a,i} \\qquad \\text{for } x_{i-1} \\leq x \\leq x_i \\:, \\nonumber \\\\\n%\\nu\\Sigma_f(x) &= \\nu\\Sigma_{f,i}\\;, \\quad \\text{for } x_{i-1} \\leq x \\leq x_i\\:, \\nonumber \\\\\n%h_i &\\equiv x_i - x_{i-1} \\:.\\nonumber \n%\\end{align}\n%\nThe unknown values are again defined at the mesh or cell \\textit{edges}, e.g.\\ $\\phi(x_i) = \\phi_i$.\n\nWe derive the equations just like we did in the fixed source case, but now instead of $S_i$ we have $\\nu \\Sigma_{f,i}$ on the rhs and a $1/k$ in multiplying the rhs vector.\n\n\\ifprintanswers\n\\begin{align}\n\\frac{\\phi_{i+1} - 2\\phi_i + \\phi_{i-1}}{h_i^2} - \\frac{1}{L_i^2}\\phi_i = -\\frac{1}{k}\\frac{\\nu\\Sigma_{f,i}}{D_i}\\phi_i \\qquad i &= 1, 2, \\dots, n-1 \\:,\\nonumber \\\\\n%\n-\\phi_{i-1} + \\bigl(2 + \\frac{h_i^2}{L_i^2}\\bigr)\\phi_i - \\phi_{i+1} = \\frac{1}{k} h_i^2 \\frac{\\nu\\Sigma_{f,i}}{D_i}\\phi_i \\qquad i &= 1, 2, \\dots, n-1\\: \\text{ or,} \\nonumber\\\\\n%\n\\nonumber \\\\\n\\frac{-D_i}{h_i^2}\\phi_{i-1} + \\biggl(\\frac{2D_i}{h_i^2} + \\Sigma_{a,i} \\biggr)\\phi_i - \\frac{D_i}{h_i^2}\\phi_{i+1} = \\frac{1}{k} \\nu\\Sigma_{f,i}\\phi_i \\qquad i &= 1, \\dots, n-1 \\:.\\nonumber \n\\end{align}\n\\else\n\\vspace*{10em}\n\\fi\n\nWith this formulation we still have the problem that our unknown is defined the cell edges and if the properties in neighboring cells differ we will have discontinuities. To be able to handle \\textit{material discontinuities} we're going to do our volume integration again.\n\n\n%-----------------------------------------------------\n%-----------------------------------------------------\n\\section*{Finite Volume Method}\n\nLike last time, we will integrate the flux and source values across neighboring half-cells.\n%\n\\begin{figure}[h!]\n\\includegraphics[height=2.5in]{FVM-eig-fig}\n\\end{figure}\n\nWe again assume the cross section and diffusion coefficient are constant in each cell; for $i=1, \\dots, n$: \n\\begin{align}\nD(x) &= D_i\\;, \\qquad x_{i-1} \\leq x \\leq x_i \\nonumber \\\\\n\\Sigma_a(x) &= \\Sigma_{a,i}\\;, \\qquad x_{i-1} \\leq x \\leq x_i \\nonumber \\\\\n\\nu\\Sigma_f(x) &= \\nu\\Sigma_{f,i}\\;, \\quad x_{i-1} \\leq x \\leq x_i \\nonumber \\\\\nh_i &\\equiv x_{i} - x_{i-1} \\:.\\nonumber \n\\end{align}\n%\nWe also still assume that the fluxes are constant over the interval centered around $x_i$; for $i=0, \\dots, n$:\n%\n\\begin{align}\n\\phi(x) &= \\phi_i \\qquad \\text{for } \\bigl(x_i - \\frac{h_i}{2}\\bigr) \\leq x \\leq \\bigl(x_i + \\frac{h_{i+1}}{2}\\bigr)\\:. \\nonumber %\\\\\n%S(x) &= S_i \\qquad \\text{for } \\bigl(x_i - \\frac{h_i}{2}\\bigr) \\leq x \\leq \\bigl(x_i + \\frac{h_{i+1}}{2}\\bigr) \\nonumber \n\\end{align}\n\nNow, we integrate the differential equation over each cell, $\\bigl(x_i - \\frac{h_i}{2}\\bigr) \\leq x \\leq \\bigl(x_i + \\frac{h_{i+1}}{2}\\bigr)$:\n%\n\\[\\int_{(x_i - \\frac{h_i}{2})}^{(x_i + \\frac{h_{i+1}}{2})} \\biggl(  -\\frac{d}{dx}D(x)\\frac{d \\phi(x)}{dx}\\biggr) dx \n+ \\int_{(x_i - \\frac{h_i}{2})}^{(x_i + \\frac{h_{i+1}}{2})} \\Sigma_a(x) \\phi(x) dx \n= \\int_{(x_i - \\frac{h_i}{2})}^{(x_i + \\frac{h_{i+1}}{2})} \\frac{1}{k}\\nu \\Sigma_f(x) \\phi(x) dx\\]\n%\nWe'll only add the term we didn't do before:\n%\n\\ifprintanswers\n\\begin{align}\n\\int_{(x_i - \\frac{h_i}{2})}^{(x_i + \\frac{h_{i+1}}{2})} \\frac{1}{k}\\nu \\Sigma_f(x)\\phi(x) dx &= \n%\n\\int_{(x_i - \\frac{h_i}{2})}^{(x_i)} \\frac{1}{k}\\nu \\Sigma_f(x) \\phi(x) dx + \\int_{(x_i)}^{(x_i + \\frac{h_{i+1}}{2})} \\frac{1}{k}\\nu \\Sigma_f(x) \\phi(x) dx \\nonumber\\\\\n%\n&\\nonumber \\\\\n&= \\frac{1}{k} \\biggl(\\frac{\\nu\\Sigma_{f,i}h_i + \\nu\\Sigma_{f,i+1}h_{i+1}}{2} \\biggr)\\phi_i \\:.\\nonumber \n\\end{align}\n\\else\n\\\\ \\vspace*{4em}\n\\fi\n\nCollecting all of the terms:\n%\n\\begin{equation}\n-D_{i+1}\\biggl(\\frac{\\phi_{i+1} - \\phi_i}{h_{i+1}}\\biggr) + D_{i}\\biggl(\\frac{\\phi_{i} - \\phi_{i-1}}{h_{i}}\\biggr) + \\biggl(\\frac{\\Sigma_{a,i}h_i + \\Sigma_{a,i+1}h_{i+1}}{2} \\biggr)\\phi_i =   \\frac{1}{k} \\biggl(\\frac{\\nu\\Sigma_{f,i}h_i + \\nu\\Sigma_{f,i+1}h_{i+1}}{2} \\biggr)\\phi_i \\:.\\nonumber\n\\end{equation}\n\nTo express this in matrix form we'll use the same abbreviations as last time, and add one for the fission term (where we've divided through by $h_{ii}$ to get the x-sec terms):\n\\begin{align}\n%h_{ii} &= \\frac{h_i + h_{i+1}}{2} \\nonumber \\\\\n%%\n%\\Sigma_{a,ii} &= \\frac{\\Sigma_{a,i}h_i + \\Sigma_{a,i+1}h_{i+1}}{h_i + h_{i+1}} \\nonumber \\\\\n\\nu\\Sigma_{f,ii} &= \\frac{\\nu\\Sigma_{f,i}h_i + \\nu\\Sigma_{f,i+1}h_{i+1}}{h_i + h_{i+1}} \\:.\\nonumber\n\\end{align}\n%\nThen\n%\n\\[a_{i,i-1} \\phi_{i-1} + a_{i,i}\\phi_i + a_{i, i+1} \\phi_{i+1} = \\frac{1}{k}\\nu\\Sigma_{f,ii} \\phi_i \\qquad \\text{for } i = 1, 2, \\dots, n-1\\:,\\]\n%\nwhere the $a$s have the same value as last time. (Only the rhs is new.)\n%\n%\\begin{align}\n%a_{i,i-1} &= \\frac{-D_i}{h_i h_{ii}}\\:, \\nonumber \\\\\n%a_{i,i} &= \\frac{D_i}{h_i h_{ii}} + \\frac{D_{i+1}}{h_{i+1} h_{ii}} +\\Sigma_{a,ii}\\:, \\nonumber \\\\\n%a_{i,i+1} &= \\frac{-D_{i+1}}{h_{i+1} h_{ii}}:.\\nonumber\n%\\end{align}\n\nWe again have a set of $n-1$ linear algebraic equations with $n+1$ unknowns. We will use the boundary conditions to get the rest of the information that we need.\n\n\n%-------------------------------------------------------\n\\subsection*{Boundary Conditions}\n\nAgain assume $x_n = \\tilde{a}$, then the \\textbf{vacuum condition} becomes\n\\[\\phi_n = 0\\]\nand the last equation for $i=n-1$ becomes\n\\ifprintanswers\n\\[a_{n-1,n-2} \\phi_{n-2} + a_{n-1,n-1}\\phi_{n-1} + 0 = \\frac{1}{k}\\nu\\Sigma_{f,(n-1,n-1)} \\phi_{n-1}\\]\n\\else\n\\\\ \\vspace*{2em}\n\\fi\n\nTo include the \\textbf{reflecting} or zero current condition we integrate over $[0, h_{1}/2]$.\n%\n\\begin{figure}[h!]\n\\includegraphics[height=2in]{ReflectingBC-eig}\n\\end{figure}\n%\n\\begin{align}\n\\int_{0}^{\\frac{h_{1}}{2}} \\biggl(-\\frac{d}{dx}D(x)\\frac{d \\phi(x)}{dx}\\biggr) dx &+ \\int_{0}^{\\frac{h_{1}}{2}} \\Sigma_a(x) \\phi(x) dx = \\int_{0}^{\\frac{h_{1}}{2}} \\frac{1}{k}\\nu \\Sigma_f(x) \\phi(x) dx \\:. \\nonumber %\\\\\n%\n%-D(x)\\frac{d \\phi(x)}{dx}\\big|_{\\frac{h_{1}}{2}} &+ D(x)\\frac{d \\phi(x)}{dx}\\big|_{0} + \\Sigma_{a,1}\\phi_0 \\frac{h_1}{2} = \\frac{1}{k}\\nu\\Sigma_{f,1} \\phi_0 \\frac{h_1}{2} \\nonumber \n\\end{align}\n%\nWe perform the integration and can apply the boundary condition $\\frac{d \\phi(x)}{dx}\\big|_{0} = 0$ just like last time, \n%\\[-D(x)\\frac{d \\phi(x)}{dx}\\big|_{\\frac{h_{1}}{2}} + \\Sigma_{a,1}\\phi_0 \\frac{h_1}{2} = \\frac{1}{k}\\nu\\Sigma_{f,1} \\phi_0 \\frac{h_1}{2}\\]\n%%\n%Recall that\n%\\[-D(x)\\frac{d \\phi(x)}{dx}\\big|_{\\frac{h_{1}}{2}} \\cong -D_{1}\\biggl(\\frac{\\phi_{1} - \\phi_0}{h_{1}}\\biggr) \\]\n%\nand the first equation ($i=0$) becomes\n\\[a_{00}^*\\phi_0 + a_{01}^* \\phi_1 = \\frac{1}{k}\\nu\\Sigma_{f,1} \\phi_0 \\:,\\]\n%\nwhere we redefine the $a^*$s to be the same as last time as well.%to be (I've added the * to indicate that these have different definitions than the rest of the terms.)\n%\n%\\begin{align}\n%a_{00}^* &= \\frac{2D_1}{h_1^2} + \\Sigma_{a,1} \\nonumber \\\\\n%a_{01}^* &= -\\frac{2D_1}{h_1^2} \\nonumber \n%\\end{align}\n\nWe now have $n$ equations and $n$ unknowns, but we formulate it a bit differently: \n\\[\\ve{A}\\vec{\\phi} = \\frac{1}{k}\\ve{F}\\vec{\\phi}\\:,\\]\nwhere:\n\\begin{align}\n%\\ve{A} &= \\begin{pmatrix}\n%a_{00}^* & a_{01}^* & 0      & 0 & \\cdots & 0 \\\\\n%a_{10}   & a_{11}   & a_{12} & 0 & \\cdots & 0 \\\\\n%0        & a_{21}   & a_{22}   & a_{21} &  & \\vdots \\\\\n%\\vdots        &    & \\ddots  & \\ddots & \\ddots & \\vdots \\\\\n%0 & \\cdots & 0 & a_{n-3,n-3}   & a_{n-2,n-2} & a_{n-2,n-1} \\\\\n%0        & \\cdots   & 0   & 0 & a_{n-1,n-2} & a_{n-1,n-1} \n%\\end{pmatrix} \\nonumber \\\\\n%%\n%\\vec{\\phi} &= \\begin{pmatrix}\\phi_0 \\\\ \\phi_1 \\\\ \\phi_2 \\\\ \\vdots \\\\ \\phi_{n-2} \\\\ \\phi_{n-1} \\end{pmatrix} \\:, \\qquad\n%\n\\ve{F} = \\begin{pmatrix}\n\\nu\\Sigma_{f,1} & 0 & 0 & 0 & \\cdots & 0 \\\\\n0   & \\nu\\Sigma_{f,11} & 0  & 0 & \\cdots & 0 \\\\\n0   & 0 & \\nu\\Sigma_{f,22}  & 0 & \\cdots & 0 \\\\\n\\vdots  &     & \\ddots  & \\ddots & \\ddots  & \\vdots \\\\\n0 & \\cdots & 0 & 0 & \\nu\\Sigma_{f,n-2,n-2} & 0 \\\\\n0        & \\cdots & 0 & 0   & 0 & \\nu\\Sigma_{f,n-1,n-1} \n\\end{pmatrix} \\:.\\nonumber\n\\end{align}\n\n\n%----------------------------------------------------------------\n%----------------------------------------------------------------\n\\section*{Solution Methods}\n\nWe are only going to talk about iterative solution methods for eigenvalue problems since no one uses direct methods in practice (dealing with directly solving an eigenvalue matrix problem rapidly becomes intractable). We will formulate the problem this way, where $m$ is the eigenvalue or ``outer\" iteration index:\n%\n\\ifprintanswers\n\\[ \\ve{A} \\vec{\\phi}^{(m+1)} = \\frac{1}{k^{(m)}}\\ve{F}\\vec{\\phi^{(m)}}\\]\n\\else\n\\\\ \\vspace*{3em}\n\\fi\n\nThere are a variety of ways you can choose to determine convergence. We will consider these convergence criteria:\n\\begin{align}\n\\bigg|\\frac{k^{(m)} - k^{(m-1)}}{k^{(m)}}\\bigg| &< \\epsilon_1 \\:, \\nonumber \\\\\n\\bigg|\\frac{\\phi_i^{(m)} - \\phi_i^{(m-1)}}{\\phi_i^{(m)}}\\bigg| &< \\epsilon_2 \\qquad \\forall i\\:. \\nonumber\n\\end{align}\n%\nWhere $\\epsilon_1$ is the eigenvalue convergence criterion (often $1 \\times 10^{-4}$ or smaller), and $\\epsilon_2$ is the flux error criterion (often $1 \\times 10^{-3}$ or smaller).\n\n\\subsection*{Finding $k$}\n\nBut wait, that iterative method was only telling us how to update $\\vec{\\phi}$. How do we get new iterates for $k$? To sort that out, we're going to think about the physical interpretation of $k$.\n\nThe multiplication factor, $k$, can be defined as\n\\[k = \\frac{\\text{total production rate}}{\\text{total loss rate}}\\]\n%\nWe can define two \\textbf{operators} (\\emph{not matrices}; to get the thing that we solve, we apply our specific discretization methods to turn the operators into matrices) to help us compute this:\n%\n\\begin{align}\nA &= -\\frac{d}{dx}D(x)\\frac{d}{dx} + \\Sigma_a(x) \\quad \\text{is the loss operator,} \\nonumber \\\\\nF &= \\nu\\Sigma_f(x) \\qquad \\qquad \\text{is the production operator.}\\nonumber\n\\end{align}\n\n%Fortunately, the discretized versions of these operators are the matrices that we have $\\ve{A}$ and $\\ve{F}$, respectively. \nThis allows us to write an equation for $k$ as\n\\ifprintanswers\n\\[k^{(m+1)} = \\frac{\\int_0^{\\tilde{a}} F \\vec{\\phi}^{(m+1)}(x)dx}{\\int_0^{\\tilde{a}} A \\vec{\\phi}^{(m+1)}(x)dx}\\:. \\]\n\\else\n\\\\ \\vspace*{3em}\n\\fi\n\nWe can express our iterative method with our operators,\n\\[ A \\vec{\\phi}^{(m+1)} = \\frac{1}{k^{(m)}}F\\vec{\\phi^{(m)}}\\]\n%\nand substitute this into our $k$ equation to get\n\\[k^{(m+1)} = \\frac{\\int_0^{\\tilde{a}} F \\vec{\\phi}^{(m+1)}(x)dx}{\\frac{1}{k^{(m)}}\\int_0^{\\tilde{a}} F \\vec{\\phi}^{(m)}(x)dx\\:.} \\]\n%\nThis idea applies to any discretization strategy. To use the finite difference formulation we've developed, we discretize the operators and this can be expressed as:\n\\ifprintanswers\n\\[k^{(m+1)} = k^{(m)}\\Biggl(\\frac{\\nu\\Sigma_{f,1} \\phi_0^{(m+1)} \\frac{h_1}{2} + \\sum_{i=1}^{n-1} \\nu\\Sigma_{f,ii} \\phi_i^{(m+1)} \\frac{h_{ii}}{2}}\n{\\nu\\Sigma_{f,1} \\phi_0^{(m)} \\frac{h_1}{2} + \\sum_{i=1}^{n-1} \\nu\\Sigma_{f,ii} \\phi_i^{(m)} \\frac{h_{ii}}{2}}\\Biggr)\\:.\\]\n\\else\n\\\\ \\vspace*{3em}\n\\fi\n\n\n\\subsection*{Power Method}\n\nPower Iteration (PI) is an old and straightforward algorithm for finding an eigenvalue/vector pair. \n\nThe basic idea is that any non-zero vector can be written as a linear combination of the eigenvectors of $\\ve{B}$ because the eigenvectors are linearly independent, namely $\\vec{v}_0 = \\gamma_1 \\vec{x}_1 + \\gamma_2 \\vec{x}_2 + \\cdots + \\gamma_n \\vec{x}_n$, where $\\vec{x}_{j}$ is the $j$th eigenvector and $\\gamma_{j}$ is some constant. This specific expression assumes a non-defective $\\ve{B}$, though this assumption is not necessary for the method to work. \n\nAnother fact that is used to understand power iteration is that $\\ve{B}^m \\vec{x}_i = \\lambda_i^m \\vec{x}_i$. Thus\n%\n\\begin{equation}\n  \\ve{B}^m \\vec{v}_{0} = \\gamma_1 \\lambda_1^m \\vec{x}_1 + \\gamma_2 \\lambda_2^m \\vec{x}_2 + \\cdots + \\gamma_n \\lambda_n^m \\vec{x}_n \\:.\\nonumber\n  \\label{eq:Ak}\n\\end{equation}\n%\nSince $|\\lambda_1| > |\\lambda_i|, i \\ne 1$, the first term in the expansion will dominate as $m \\to \\infty$ and $\\ve{B}^m \\vec{v}_{0}$ therefore becomes an increasingly accurate approximation to $\\vec{x}_1$. \n\nIn practice, it is desirable to avoid exponentiating a matrix, so we will use an algorithm that does something else. It is also helpful to normalize $\\vec{v}_0$ to avoid possible over or underflow.\n\nWe are also quite interested in the \\textit{convergence behavior} of PI. After $m$ steps, the iteration vector $\\vec{v}$ will be: \n%\n\\ifprintanswers\n\\begin{equation}\n  \\vec{v}_{m} = \\bigl( \\frac{\\lambda_{1}^{m}}{\\vec{e}_{1}^{T}\\ve{B}^{m}\\vec{v}_{0}} \\bigr) \\bigl(\\frac{1}{\\lambda_{1}^{m}}\\ve{B}^{m}\\vec{v}_{0} \\bigr) \\:' \\nonumber\n\\end{equation}\n\\else\n\\\\ \\vspace*{2em}\n\\fi\n\n% \nwhere $\\vec{e}_{1}^{T}$ is a vector with 1 in the first entry and zeros elsewhere; it selects the first row of $\\ve{B}$ in the multiplication. If $\\ve{B}$ has eigenpairs $\\{(\\vec{x}_{j}, \\lambda_{j}), 1 \\le j \\le n \\}$ and $\\vec{v}_{0}$ has the expansion $\\vec{v}_{0} = \\sum_{j=1}^{n} \\vec{x}_{j}\\gamma_{j}$ then\n%\n\\begin{equation}\n  \\frac{1}{\\lambda_{1}^{m}}\\ve{B}^{m}\\vec{v}_{0} =  \\frac{1}{\\lambda_{1}^{m}} \\sum_{j=1}^{n} \\ve{B}^{m}\\vec{x}_{j}\\gamma_{j} = \\sum_{j=1}^{n} \\bigl(\\frac{\\lambda_{j}}{\\lambda_{1}} \\bigr)^m \\vec{x}_{j} \\gamma_{j} \\:.\n  \\label{eq:PIexpand}\n\\end{equation}\n%\n\\ifprintanswers\nFrom equation \\eqref{eq:PIexpand} it can be determined that the error is reduced in each iteration by a factor of $|\\frac{\\lambda_{2}}{\\lambda_{1}}|$, which is called the dominance ratio. If $\\lambda_2$ is close to $\\lambda_1$, then this ratio will be close to unity and the method will converge very slowly. \n\nIf $\\lambda_2$ is far from $\\lambda_1$, then convergence will happen much more quickly. Put simply, PI is better suited for problems where $\\ve{B}$ has eigenvalues that are well separated.  \n\\else\n\\vspace*{8em}\n\\fi\n\n\nPower iteration is very attractive because it only requires matrix-vector products and two vectors of storage space. Because of its simplicity and low storage cost, PI has been widely used in the transport community for criticality problems for quite some time.\n\nDespite these beneficial characteristics, many current codes use an acceleration method with PI or have moved away from it altogether because of the slow convergence for many problems of interest. Nevertheless, it is still used in some codes, has historical relevance, and is used in many studies as a base comparison case.\n\n\n\\subsubsection*{Algorithm}\n\nThe power method applies in our formulation when $\\ve{B} \\equiv \\ve{A}^{-1}\\ve{F}$, $\\lambda \\equiv k$ and $\\vec{x} \\equiv \\vec{\\phi}$. \n%\nWhen we write it this way it is technically \\textbf{inverse power iteration} because we're using the inverse of $\\ve{A}$ rather than $\\ve{A}$ (the theory is the same). Be careful when setting up these solvers about whether you are solving for $k$ or $1/k$ to ensure you get the correct eigenvectors.\n\nHere is an algorithm to implement the power method (note: this is not the most efficient way to do this, but it is likely the clearest).\n%\n\\begin{enumerate}\n\\item get initial values for $k^{(0)}$ and $\\phi^{(0)}$ for $i = 0, \\dots, n-1$; normalize $\\phi_0 = \\phi_0 / ||\\phi_0||$\n\n\\item compute the elements of $\\ve{A}$\n\n\\item compute the initial fission source\n\\[\\vec{Q}_{f}^{(0)} = \\begin{pmatrix}\nQ_{f,0}^{(0)} \\\\ Q_{f,1}^{(0)} \\\\ \\vdots \\\\ Q_{f,n-1}^{(0)} \\\\\n\\end{pmatrix}\\]\n%\nwhere $Q_{f,i}^{(0)} = \\nu\\Sigma_{f,ii}\\phi_i^{(0)} \\: \\text{for } i = 1, \\dots, n-1$ and $Q_{f,0}^{(0)} = \\nu\\Sigma_{f,1}\\phi_0^{(0)}$\n\n\\item for $m = 1, ...,$ convergence:\n\\begin{enumerate}\n\\item solve (using a method like Jacobi or GS)\n\\[\\ve{A} \\vec{\\phi}^{(m)} = \\frac{1}{k^{(m-1)}}\\vec{Q}_{f}^{(m-1)}\\]\n\n\\item compute the next fission source $\\:Q_{f,i}^{(m)} = \\nu\\Sigma_{f,ii}\\phi_i^{(m)} \\: \\text{ for } i = 1, \\dots, n-1$ and\\\\ $Q_{f,0}^{(m)} = \\nu\\Sigma_{f,1}\\phi_0^{(m)}$\n\n\\item compute the next eigenvalue:\n\\[k^{(m)} = k^{(m-1)}\\Biggl(\\frac{Q_{f,0}^{(m)} \\frac{h_1}{2} + \\sum_{i=1}^{n-1} Q_{f,i}^{(m)} \\frac{h_{ii}}{2}}\n{Q_{f,0}^{(m-1)} \\frac{h_1}{2} + \\sum_{i=1}^{n-1} Q_{f,i}^{(m-1)} \\frac{h_{ii}}{2}}\\Biggr)\\]\n\n\\item check for convergence\n\\begin{align}\n\\bigg|\\frac{k^{(m)} - k^{(m-1)}}{k^{(m)}}\\bigg| &< \\epsilon_1 \\nonumber \\\\\n\\bigg|\\frac{\\phi_i^{(m)} - \\phi_i^{(m-1)}}{\\phi_i^{(m)}}\\bigg| &< \\epsilon_2 \\nonumber\n\\end{align}\n\n\\end{enumerate}\n\\end{enumerate}\n\n%--------------------------------------------------------------------\n%--------------------------------------------------------------------\n%\\bibliographystyle{plain}\n%\\bibliography{LinearSolns} \n\n\\end{document}", "meta": {"hexsha": "06a0bfeda65a47807bde8072ea8f7ea80a00d91f", "size": 23134, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "13-1d-fd-fvm/14-1d-eig-fd-fvm.tex", "max_stars_repo_name": "rachelslaybaugh/NE155", "max_stars_repo_head_hexsha": "5a08229eb11eebdd60e5ec1b4c0d41a541e7d82f", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2015-08-22T05:28:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T02:00:39.000Z", "max_issues_repo_path": "13-1d-fd-fvm/14-1d-eig-fd-fvm.tex", "max_issues_repo_name": "rachelslaybaugh/NE155", "max_issues_repo_head_hexsha": "5a08229eb11eebdd60e5ec1b4c0d41a541e7d82f", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2015-04-01T00:18:04.000Z", "max_issues_repo_issues_event_max_datetime": "2016-10-31T20:14:58.000Z", "max_forks_repo_path": "13-1d-fd-fvm/14-1d-eig-fd-fvm.tex", "max_forks_repo_name": "rachelslaybaugh/NE155", "max_forks_repo_head_hexsha": "5a08229eb11eebdd60e5ec1b4c0d41a541e7d82f", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-01-21T20:12:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-20T08:01:10.000Z", "avg_line_length": 46.268, "max_line_length": 460, "alphanum_fraction": 0.6274747125, "num_tokens": 8551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.30743749651343244}}
{"text": "\\documentclass[12pt]{article}\n\\usepackage{epsfig}\n\\usepackage{amssymb}\n\\textwidth=17cm\n\\textheight=22.5cm\n\n\\topmargin -1.5 cm\n\\oddsidemargin -0.3cm\n\n\\parskip 0.3cm\n \\begin{document}\n\n\\vspace*{20mm}\n\\begin{flushright}\nCERN-TH/2000.015\n\\end{flushright}\n\\vspace*{1cm}\n\\begin{center}\n{\\bf CONTINUATION OF DIRECT PRODUCTS OF DISTRIBUTIONS}\n\\vspace*{1cm}\n\n{\\bf A. Peterman }\\\\\n\\vspace{0.3cm}\nTheoretical Physics Division,\nCERN \\\\\nCH -- 1211 Geneva 23\\\\\n\\vspace*{2cm}\n \\end{center}\n\n\\setcounter{page}{1}\n\\pagestyle{plain}\n\n\n\\begin{center}{\\bf Preamble}\\end{center}\nIf, in some problems, one has to deal with the ``product'' of\ndistributions\n$\\rm f_i$ (also called\ngeneralized functions) $\\rm\\overline T = \\Pi^m_{i=1} f_i$, this product\nhas\na priori no definite meaning\nas a functional $(\\rm \\overline T, \\varphi) $ for $\\rm\\varphi \\in S$. But\nif $\\rm x^{\\kappa +1}\n\\Pi^m_{i=1} f_i$ exists, whatever the associativity is  between some\npowers\n$\\rm r_i$ of $\\rm x$ ($\\rm\nr_i\n\\in \\Bbb N, \\sum_i r_i\\leq \\kappa  +1, r_i \\geq 0$) and the various $\\rm\nf_i$, then a continuation\nof the  linear functional $\\rm \\overline T$ from $\\rm M$  onto $\\rm\nS^{(N)}$  for some $\\rm N$\nis shown to exist\\footnote{$\\rm M$ is a closed subspace of $\\rm S^N$ for\nsome $\\rm N$. It is a Banach\nspace with norm\n$\\rm \\|\n\\|_N $.} in such a way that $\\rm x^{\\kappa +1} \\overline T$ is defined\nunambiguously, and $\\rm (\\overline\nT,\n\\varphi), \\varphi \\in S$, significant, though not unique.\n\\vspace*{4cm}\n\\begin{flushleft}\nCERN-TH/2000-015\\\\\nJanuary 2000\n\\end{flushleft}\n\\vfill\\eject\n\n\\section{Existence}\n\nIn the sense of convergence in the space $\\rm S^*$ (distributions),\n$$\\rm f_\\kappa = \\lim_{y \\rightarrow 0,\\; y \\in C^+} F^y_\\kappa (x)\n\\;;\\;\\;\n\\kappa = 1,2, \\cdots ,\nm\\;,$$\n with $\\rm F^y_\\kappa (x) = f^+_\\kappa (x +iy) - f^-_\\kappa (x - i y)$,\n$\\bigg(\\rm f^\\pm_\\kappa (x)$ are\nholomorphic in tabular domains $\\rm T^{C^\\pm_R}$ and satisfy\n\\begin{equation}\n|f (x + i y) | \\leq C (R^\\prime, C^\\prime) |y|^{-\\alpha} (1+|x|)^\\beta\n\\end{equation}\nand\n$$\nz \\in R^n + i (C^\\prime\n\\cap U (0, R^\\prime))\n$$\n$\\rm \\alpha , \\beta \\geq 0$, independent of $\\rm R^\\prime$ and $\\rm\nC^\\prime$. From this, it follows that\nthere exists in $\\rm S^*$ a unique boundary value\n$$\\left.{\\rm f(x) = \\lim_{y \\rightarrow 0 , \\; y \\rightarrow c} f(x + iy)\n \\in S^{(m) *}; \\; m= \\alpha +\\beta +\nn +3\\;.}\\right)$$\n\nLet us suppose that for arbitrary  $\\rm \\varphi \\in S$ there exists a\nfinite limit\n\\begin{equation}\n\\lim_{y \\rightarrow 0, \\;y\\in C^+} \\int  F_1^y (x) \\cdots F^y_m (x) \\cdot\n\\varphi (x) dx\n\\end{equation}\nindependent of the sequence $\\rm y \\rightarrow 0 , \\; y \\in C^+$. Then,\nsince the space $\\rm S^*$ is\ndense, this limit defines a distribution in $\\rm S^*$ which we call the\nproduct $\\rm f_1 . f_2 .\\cdots\n.f_m$ of the distributions $\\rm f_1, f_2,\\cdots , f_m$. Thus\n\\begin{equation}\nf_1. f_2. \\cdots . f_m = \\lim_{y\\rightarrow 0 , \\; y \\in C^+} F^y_1 \\cdots\nF^y_m\\;\\;({\\rm in}\\; S^*)\n\\end{equation}\nif the limit of the RHS exists and is independent of the sequence $\\rm y\n\\rightarrow 0 , y \\in C^+$.\nThis product is obviously commutative and associative. So  the set of\nboundary values that are\nholomorphic in $\\rm T^{C^+_R}$ and satisfy (1) constitute a commutative\nring with unity, without zero\ndivisors with respect to the multiplication defined above.\n\nWe note that the existence of the lim in (2) for $\\rm \\varphi \\in S$\nimplies the existence of the\nlimit in (3) with respect to the norm of the functional in $\\rm S^{(N)*}$\nfor some $\\rm N$, which depends\non\n$\\rm f_1 \\dots f_m$ (notice that weak convergence in $\\rm S^*$ implies\nstrong convergence).\n\n\\section{General case}\n\nSuppose now that (2) does not exist for all $\\rm \\varphi \\in S$, but that\nit exists for all $\\rm \\varphi$\nin a closed subspace  $\\rm M$ of $\\rm S^{(N)}$ for some $\\rm N$. (Since\n$\\rm M$ is closed in $\\rm\nS^{(N)}$ it is a Banach space with norm $\\rm \\|\\;\\|_N$). From the\nBanach-Steinhaus theorem, (2) defines a\ncontinuous linear functional $\\rm \\overline T$ on $\\rm M$. We use now the\nterm `product' $\\rm f_1.\n\\cdots . f_m$ of the distributions $\\rm f_1, f_2, \\cdots , f_m$ for\n\\underline{any} continuous linear\nfunctional in the space $\\rm S^{(N)*}\\subset S^*$ that is a\n\\underline{continuation} of $\\rm \\overline T$\nfrom\n$\\rm M$ to\n$\\rm S^{(N)}$. According to the Hahn-Banach theorem, such an extension\nalways exists but is not\n\\underline{unique} in general.\n\nWe shall concentrate now on the case of those $\\varphi$ in $\\rm S^{(N)}$\nthat vanish together with\nall derivatives of order $\\rm p\\leq N$ inclusively, at $\\rm x=0$. In this\ncase, \\underline{all}\ncontinuations\n  $\\rm f_1. f_2. \\cdots . f_m$ of $\\rm \\overline T$ from $\\rm M$ onto $\\rm\nS^{(N)}$ are given by\n\\begin{equation}\n(f_1. f_2 . \\cdots . f_m, \\varphi ) = (\\overline{T}, \\overline{\\varphi}) +\n\\sum_{\\kappa \\leq p}\nc_\\kappa (\\delta^{(\\kappa)}, \\varphi)\n\\end{equation}\nwhere\n$$\\rm \\overline{\\varphi} (x) = \\varphi (x) - \\sum_{\\kappa \\leq p}\n\\varphi^{(\\kappa )} (o) \\omega (x)\n\\frac{x^\\kappa}{\\kappa^!}$$\nand $\\rm \\omega (x)$ is an arbitrary function, $\\rm \\omega \\in S$,\nidentically equal to 1 in a\nneighbourhood of the point $\\rm x =0$; the $\\rm c_\\kappa$ are arbitrary\nconstants. (Notice that the\nextension (4) is actually independent of $\\rm \\omega (x)$).\n\nIn conclusion, the formula (4) represents the desired result, given at the\nend of the preamble\nwith $\\rm \\sum_{\\kappa \\leq p} c_\\kappa \\delta^{(\\kappa)}$ the general\nsolution of $\\rm (f_1. \\cdots .\nf_m, \\varphi) =0$ and $\\rm ( {T}, \\overline{\\varphi} ) = (\\overline{T},\nx^{\\kappa +1} \\psi) =\n(x^{\\kappa +1} \\overline{T}, \\psi ), \\psi \\in S$, a particular solution of\n$\\rm (f_1.\\cdots . f_m,\n\\varphi )$.\n\nIt is therefore shown that the solution (4) is not unique, the $\\rm\nc_\\kappa$ being arbitrary\nconstants.\n\\end{document}\n", "meta": {"hexsha": "ae9c33a30f1a0e7cc782e345dfe4dbb53dc8b995", "size": 5785, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "benchmark/src/test-data/0001/math-ph0001025/math-ph0001025.tex", "max_stars_repo_name": "e-sim/pdf-text-extraction-benchmark", "max_stars_repo_head_hexsha": "42eede9867e5795a6fc040b0a7ce92da3ddd3120", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-08-23T19:07:01.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-23T19:07:01.000Z", "max_issues_repo_path": "benchmark/src/test-data/0001/math-ph0001025/math-ph0001025.tex", "max_issues_repo_name": "e-sim/pdf-text-extraction-benchmark", "max_issues_repo_head_hexsha": "42eede9867e5795a6fc040b0a7ce92da3ddd3120", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmark/src/test-data/0001/math-ph0001025/math-ph0001025.tex", "max_forks_repo_name": "e-sim/pdf-text-extraction-benchmark", "max_forks_repo_head_hexsha": "42eede9867e5795a6fc040b0a7ce92da3ddd3120", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5, "max_line_length": 74, "alphanum_fraction": 0.665514261, "num_tokens": 2119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.3074189554582096}}
{"text": "\\documentclass[12pt]{article}\n\\usepackage{verbatim}\n\\usepackage{charter}\n\n\\title{Summary of the {\\tt res\\_quan} library}\n\\author{W. Wong}\n\\date{15 April 1993}\n\n\\input{summacs}\n\n\\begin{document}\n\\maketitle\n\nThe {\\tt res\\_quan} library privides some basic facilities for\nmanipulate restricted quantifications. It consists of a single theory,\n{\\tt res\\_quan}, which  contains a number of theorems about the\nproperties of some restricted quantifiers, and a set of ML functions\nfor dealing with them. This summary lists all theorem stored in the\n{\\tt res\\_quan} theory and ML functions available in the library.\n\n\\section{The theory {\\tt res\\_quan}}\n\nThis theory caontains the following theorems.\n{\\small\n% =====================================================================\n% Commands for typesetting theorems\n% =====================================================================\n\n\\makeatletter\n\n% ---------------------------------------------------------------------\n% define \\@xboxverb<thing>\\ENDTHEOREM to mean <thing>\\ENDTHEOREM\n% ---------------------------------------------------------------------\n\n\\begingroup \\catcode `|=0 \\catcode `[= 1\n\\catcode`]=2 \\catcode `\\{=12 \\catcode `\\}=12\n\\catcode`\\\\=12 |gdef|@xboxverb#1\\ENDTHEOREM[#1|ENDTHEOREM]\n|endgroup\n\n% ---------------------------------------------------------------------\n% \\bboxverb<thing> = <thing> in a verbatim box 5mm from left margin\n% ---------------------------------------------------------------------\n\n\\def\\@boxverb{\\bgroup\\leftskip=5mm\\parindent\\z@\n\\parfillskip=\\@flushglue\\parskip\\z@\n\\obeylines\\tt \\catcode``=13 \\@noligs \\let\\do\\@makeother \\dospecials}\n\n\\def\\boxverb{\\@boxverb \\frenchspacing\\@vobeyspaces \\@xboxverb}\n\n% ---------------------------------------------------------------------\n% \\ENDTHEOREM just finishes off the group (and kick page if necessary)\n% ---------------------------------------------------------------------\n\n\\def\\ENDTHEOREM{\\egroup\\filbreak}\n\n% ---------------------------------------------------------------------\n% \\THEOREM <name> <thy> ... \\ENDTHEOREM = typeset a theorem\n% ---------------------------------------------------------------------\n\\def\\autoindex#1{}\n\\def\\THEOREM #1 #2 {\n \\autoindex{#1@{\\tt #1}}\n   \\vspace{4mm plus2mm minus1mm}\n   \\noindent {\\tt #1}\\quad ({\\tt #2}) \\par \\boxverb\n}\n\n\\makeatother\n\n\\THEOREM DISJ\\_RESQ\\_EXISTS\\_DIST res\\_quan\n|- !P Q R.\n   (?i :: \\i. P i \\/ Q i. R i) = (?i :: P. R i) \\/ (?i :: Q. R i)\n\\ENDTHEOREM\n\\THEOREM RESQ\\_EXISTS\\_DISJ\\_DIST res\\_quan\n|- !P Q R. (?i :: P. Q i \\/ R i) = (?i :: P. Q i) \\/ (?i :: P. R i)\n\\ENDTHEOREM\n\\THEOREM RESQ\\_EXISTS\\_REORDER res\\_quan\n|- !P Q R. (?i :: P. ?j :: Q. R i j) = (?j :: Q. ?i :: P. R i j)\n\\ENDTHEOREM\n\\THEOREM RESQ\\_EXISTS\\_UNIQUE res\\_quan\n|- !P j. (?i :: $= j. P i) = P j\n\\ENDTHEOREM\n\\THEOREM RESQ\\_FORALL\\_CONJ\\_DIST res\\_quan\n|- !P Q R. (!i :: P. Q i /\\ R i) = (!i :: P. Q i) /\\ (!i :: P. R i)\n\\ENDTHEOREM\n\\THEOREM RESQ\\_FORALL\\_DISJ\\_DIST res\\_quan\n|- !P Q R.\n   (!i :: \\i. P i \\/ Q i. R i) = (!i :: P. R i) /\\ (!i :: Q. R i)\n\\ENDTHEOREM\n\\THEOREM RESQ\\_FORALL\\_FORALL res\\_quan\n|- !P R x. (!x. !i :: P. R i x) = (!i :: P. !x. R i x)\n\\ENDTHEOREM\n\\THEOREM RESQ\\_FORALL\\_REORDER res\\_quan\n|- !P Q R. (!i :: P. !j :: Q. R i j) = (!j :: Q. !i :: P. R i j)\n\\ENDTHEOREM\n\\THEOREM RESQ\\_FORALL\\_UNIQUE res\\_quan\n|- !P j. (!i :: $= j. P i) = P j\n\\ENDTHEOREM\n}\n\n\\section{ML functions in the library}\n\n\\subsection*{Conditional rewriting tools}\n\n\\begin{itemize}\n\\item \\mlname{COND_REWRITE1_CONV} \\verb|: (thm list -> thm -> conv)|\\newline\nA simple conditional rewriting conversion.\n\n\\item \\mlname{COND_REWRITE1_TAC} \\verb|: thm_tactic|\\newline\nA simple conditional rewriting tactic.\n\n\\item \\mlname{COND_REWR_CANON} \\verb|: thm -> thm|\\newline\nTransform a theorem into a form accepted by \\mlname{COND_REWR_TAC}.\n\n\\item \\mlname{COND_REWR_CONV} \\linebreak\n\\verb|: ((term -> term ->| \\verb|((term # term) list # (type # type) list) list)|\n\\verb| -> thm -> conv)|\\newline\nA lower level conversion implementing simple conditional rewriting.\n\n\\item \\mlname{COND_REWR_TAC}\\linebreak\n\\verb|: ((term -> term ->| \\verb|((term # term) list # (type # type) list) list)|\n\\verb|-> thm_tactic)|\\newline\nA lower level tactic used to implement simple conditional rewriting tactic.\n\\end{itemize}\n\n\\subsection*{Syntax functions}\n\n\\begin{itemize}\n\\item \\mlname{mk_resq_abstract} \\verb|: ((term # term # term) -> term)|\\newline\nTerm constructor for restricted abstraction.\n\n\\item \\mlname{mk_resq_exists} \\verb|: ((term # term # term) -> term)|\\newline\nTerm constructor for restricted existential quantification.\n\n\\item \\mlname{mk_resq_forall} \\verb|: ((term # term # term) -> term)|\\newline\nTerm constructor for restricted universal quantification.\n\n\\item \\mlname{mk_resq_select} \\verb|: ((term # term # term) -> term)|\\newline\nTerm constructor for restricted choice quantification.\n\n\\item \\mlname{list_mk_resq_exists} \\verb|: ((term # term) list # term) -> term)|\\newline\nIteratively constructs a restricted existential quantification.\n\n\\item \\mlname{list_mk_resq_forall} \\verb|: ((term # term) list # term) -> term)|\\newline\nIteratively constructs a restricted universal quantification.\n\n\\item \\mlname{dest_resq_abstract} \\verb|: (term -> (term # term # term))|\\newline\nBreaks apart a restricted abstract term into\nquantified variable, predicate and body.\n\n\\item \\mlname{dest_resq_exists} \\verb|: (term -> (term # term # term))|\\newline\nBreaks apart a restricted existentially quantified term into\nquantified variable, predicate and body.\n\n\\item \\mlname{dest_resq_forall} \\verb|: (term -> (term # term # term))|\\newline\nBreaks apart a restricted universally quantified term into\nquantified variable, predicate and body.\n\n\\item \\mlname{dest_resq_select} \\verb|: (term -> (term # term # term))|\\newline\nBreaks apart a restricted choice quantified term into\nquantified variable, predicate and body.\n\n\\item \\mlname{strip_resq_exists} \\verb|: (term -> ((term # term) list # term))|\\newline\nIteratively breaks apart a restricted existenially quantified term.\n\n\\item \\mlname{strip_resq_forall} \\verb|: (term -> ((term # term) list # term))|\\newline\nIteratively breaks apart a restricted universally quantified term.\n\n\\item \\mlname{is_resq_abstract} \\verb|: (term -> bool)|\\newline\nTests a term to see if it is a restricted abstraction.\n\n\\item \\mlname{is_resq_exists} \\verb|: (term -> bool)|\\newline\nTests a term to see if it is a restricted existential quantification.\n\n\\item \\mlname{is_resq_forall} \\verb|: (term -> bool)|\\newline\nTests a term to see if it is a restricted universal quantification.\n\n\\item \\mlname{is_resq_select} \\verb|: (term -> bool)|\\newline\nTests a term to see if it is a restricted choice quantification.\n\\end{itemize}\n\n\\subsection*{Derived rules}\n\n\\begin{itemize}\n\\item \\mlname{RESQ_GEN} \\verb|: ((term # term) -> thm -> thm)|\\newline\nGeneralizes the conclusion of a theorem to a restricted universal quantification.\n\n\\item \\mlname{RESQ_GENL} \\verb|: ((term # term) list -> thm -> thm)|\\newline\nGeneralizes zero or more variables to restricted universal quantification\nin the conclusion of a theorem.\n\n\\item \\mlname{RESQ_GEN_ALL} \\verb|: (thm -> thm)|\\newline\nGeneralizes the conclusion of a theorem over its own assumptions.\n\n\\item \\mlname{RESQ_HALF_EXISTS} \\verb|: (thm -> thm)|\\newline\nStrip a restricted existential quantification in the conclusion of a theorem.\n\n\\item \\mlname{RESQ_HALF_SPEC} \\verb|: (thm -> thm)|\\newline\nStrip a restricted universal quantification in the conclusion of a theorem.\n\n\\item \\mlname{RESQ_MATCH_MP} \\verb|: (thm -> thm -> thm)|\\newline\nEliminating a restricted universal quatification with automatic matching.\n\n\\item \\mlname{RESQ_REWR_CANON} \\verb|: thm -> thm|\\newline\nTransform a theorem into a form accepted for rewriting\n\n\\item \\mlname{RESQ_SPEC} \\verb|: (term -> thm -> thm)|\\newline\nSpecializes the conclusion of a restricted universally quantified theorem.\n\n\\item \\mlname{RESQ_SPECL} \\verb|: (term list -> thm -> thm)|\\newline\nSpecializes zero or more variables in the conclusion of a restricted\nuniversally quantified theorem.\n\n\\item \\mlname{RESQ_SPEC_ALL} \\verb|: (thm -> thm)|\\newline\nSpecializes the conclusion of a theorem with its own quantified variables.\n\\end{itemize}\n\n\\subsection*{Conversions}\n\n\\begin{itemize}\n\\item \\mlname{AND_RESQ_FORALL_CONV} \\verb|: conv|\\newline\nMoves a restricted universal quantification out a conjunction.\n\n\\item \\mlname{IMP_RESQ_FORALL_CONV} \\verb|: conv|\\newline\nConverts an implication to a restricted universal quantification.\n\n\\item \\mlname{LIST_RESQ_FORALL_CONV} \\verb|: conv|\\newline\nConverts restricted universal quantifications iteratively to implications.\n\n\\item \\mlname{RESQ_EXISTS_CONV} \\verb|: conv|\\newline\nConverts a restricted existential quantification to a conjunction.\n\n\\item \\mlname{RESQ_FORALL_AND_CONV} \\verb|: conv|\\newline\nSplits a restricted universal quantification across a conjunction.\n\n\\item \\mlname{RESQ_FORALL_CONV} \\verb|: conv|\\newline\nConverts a restricted universal quantification to an implication.\n\n\\item \\mlname{RESQ_FORALL_SWAP_CONV} \\verb|: conv|\\newline\nChanges the order of two restricted universal quantifications.\n\n\\item \\mlname{RESQ_REWRITE1_CONV} \\verb|: thm list -> thm -> conv|\\newline\nRewriting conversion with restricted universally quantified theorem.\n\\end{itemize}\n\n\\subsection*{Tactics}\n\n\\begin{itemize}\n\\item \\mlname{RESQ_GEN_TAC} \\verb|: tactic|\\newline\nStrips the outermost restricted universal quantifier from\nthe conclusion of a goal.\n\n\\item \\mlname{RESQ_HALF_GEN_TAC} \\verb|: tactic|\\newline\nStrips the outermost restricted universal quantifier from\nthe conclusion of a goal.\n\n\\item \\mlname{RESQ_EXISTS_TAC} \\verb|: term -> tactic|\\newline\nStrips the outermost restricted extistential quantifier from\nthe conclusion of a goal.\n\n\\item \\mlname{RESQ_IMP_RES_TAC} \\verb|: thm_tactic|\\newline\nREpeatedly resolves a restricted univerally quantified theorem with\nthe assumptions of a goal.\n\n\\item \\mlname{RESQ_IMP_RES_THEN} \\verb|: thm_tactical|\\newline\nResolves a restricted univerally quantified theorem with\nthe assumptions of a goal.\n\n\\item \\mlname{RESQ_RES_TAC} \\verb|: tactic|\\newline\nEnriches assumptions by repeatedly resolving restricted universal\nquantifications in them against the others.\n\n\\item \\mlname{RESQ_RES_THEN} \\verb|: thm_tactic -> tactic|\\newline\nResolves all restricted univerally quantified assumptions against\nother assumptions of a goal.\n\n\\item \\mlname{RESQ_REWRITE1_TAC} \\verb|: thm_tactic|\\newline\nRewriting with restricted universally quantified theorem.\n\\end{itemize}\n\n\\subsection*{Constant definition}\n\n\\begin{itemize}\n\\item \\mlname{new_binder_resq_definition} \\verb|: ((string # term) -> thm)|\\newline\nDeclare a new binder and install a definitional axiom in the current theory.\n\n\\item \\mlname{new_infix_resq_definition} \\verb|: ((string # term) -> thm)|\\newline\nDeclare a new infix constant and install a definitional axiom in the current theory.\n\n\\item \\mlname{new_resq_definition} \\verb|: ((string # term) -> thm)|\\newline\nDeclare a new constant and install a definitional axiom in the current theory.\n\\end{itemize}\n\n\n\\end{document}\n", "meta": {"hexsha": "e29489459b157da95a3743ea6a3b0f380a18c648", "size": 11076, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/res_quan/Manual/summary.tex", "max_stars_repo_name": "dwRchyngqxs/HOL", "max_stars_repo_head_hexsha": "3b1931c130fcab243da332adb2c1413c42c59cf9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 492, "max_stars_repo_stars_event_min_datetime": "2015-01-07T16:36:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T22:18:48.000Z", "max_issues_repo_path": "src/res_quan/Manual/summary.tex", "max_issues_repo_name": "dwRchyngqxs/HOL", "max_issues_repo_head_hexsha": "3b1931c130fcab243da332adb2c1413c42c59cf9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 759, "max_issues_repo_issues_event_min_datetime": "2015-01-01T00:40:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T17:33:39.000Z", "max_forks_repo_path": "src/res_quan/Manual/summary.tex", "max_forks_repo_name": "dwRchyngqxs/HOL", "max_forks_repo_head_hexsha": "3b1931c130fcab243da332adb2c1413c42c59cf9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 126, "max_forks_repo_forks_event_min_datetime": "2015-02-17T03:20:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T00:42:55.000Z", "avg_line_length": 37.6734693878, "max_line_length": 88, "alphanum_fraction": 0.6905922716, "num_tokens": 3176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5506073655352403, "lm_q1q2_score": 0.3074189554582096}}
{"text": "% !TEX root = zeth_relay\n\n\\chapter{Network structure}\\label{chap:unicast-vs-broadcast}\n\n\\section{Binding requests to relays}\n\n\\subsection{Background}\n\nThe protocols presented in this document require users to create relay requests that can only be successfully processed by a specific relay. This serves as a mechanism to prevent other network participants from ``stealing'' the relay requests or front-running relay transactions. The alternative to this would be to support ``free'' relay requests, not bound to specific relays, which could therefore be processed by any participant. If these ``free'' requests are made available (or ``broadcast'') to multiple relays, those relays must then ``race'' to process the request and broadcast a corresponding relay transaction. When the first relay transaction is accepted by the blockchain, the ``winning'' relay will receive the relay fee and later transactions from other relays will be rendered invalid (as a consequence of the nullifiers declared in the $\\zeth$ relay request being marked as used).\n\nWhile such an approach is entirely feasible, it increases the risk for relays, making it much harder for them to hedge against lost fees and wasted compute resources. As a consequence, it becomes much more difficult for relays to assess the risk associated with a given request, which in turn is likely to result in an increase in relay fees. All resources used by ``losers'' of the race are wasted.  In contrast, in the case where requests are bound to specific relays, these resources can be used to process multiple requests in parallel, increasing the efficiency of the system.\n\n\\subsection{Emulating ``free'' relay requests}\\label{unicast-vs-broadcast:requests:emulate-free-requests}\n\nDespite the mechanisms to prevent front-running, the protocols presented in this document could be leveraged by some user (say $\\userP$) to force relays to ``compete'' for relay requests.\nSpecifically, in order to call the \\zeth~mixer \\mixer~with parameters $\\mixparams$, $\\userP$ can run multiple instances of a protocol in parallel, generating $N$ relay requests for $\\mixparams$, each targeting a different relay. If the user then sends each of these $N$ requests to the targeted relay, the desired state transition will be carried out by the first relay transaction to be accepted into the blockchain, rendering the remaining $N-1$ requests invalid (by the nullifier mechanism cited previously).\n\nAs in the case of ``free'' requests, relays are exposed to extra risk for the reasons given above. However, this ``emulating'' approach does provide partial mitigation of this risk, due to the extra cost that the user $\\userP$ must incur. Under the protocols given in this document, in order to create $N$ requests targeting different relays, the user must generate $N$ zk-SNARKs, which is computationally demanding and therefore represents a cost to the user. Therefore, request generation may act as a user-side proof-of-work, preventing malicious messages from flooding the network (as originally designed for by Dwork et al.~\\cite{DBLP:conf/crypto/DworkN92,Jakobsson1999ProofsOW}). This naturally leads to the following process by which relays can partially protect against some DoS vectors, by performing the following checks on relay requests:\n\\begin{enumerate}\n    \\item Verify that none of the nullifiers in the request has been seen in previously received requests (inspect the mempool and the blockchain state). If one or more nullifiers is a duplicate then reject the request, else proceed.\n    \\item Verify the zk-SNARK proof in the request. If the proof is invalid, reject the request. Otherwise the request can be considered for processing.\n\\end{enumerate}\n\nIn this way, the cost of generating $N$ proofs imposes some upper bound on the message output rate of a potential attacker.\n\n\\section{Unicast vs broadcast networks}\\label{unicast-vs-broadcast:unicast-vs-broadcast}\n\nThe discussions in this document assume only that some transport mechanism exists for users to send relay requests to specific relays. As noted in \\cref{preliminaries:introduction}, users can achieve further anonymity if this transport mechanism does not require the user to reveal any identifying information at the network level. We now discuss some specific implementations of the transport layer (namely ``unicast'' vs ``broadcast'' networks), and their respective properties.\n\nBy design, relay requests are bound to specific relays, which intuitively implies a ``unicast'' style transport mechanism. That is, relays publish a network address of some form, and users send requests to this address. Observers of the physical network may determine that a message has been sent from the user to the relay, but the content of the message (i.e.~the details of the relay request) is not visible to other participants. This is a natural choice given that relay request data cannot be used by parties other than the targeted relay. While not a requirement of any of these protocols, unicast channels (in particular point-to-point communication channels, which we assume to be encrypted by default) only reveal the relay request content to the relay itself. Adversaries able to gain control a physical network node along the route between user and relay (in general a limited set of nodes, which varies depending on user and relay) may learn that a message was sent from the user to the relay, but they will not learn anything about the message content. Such communication channels also allow for interaction between relay and user (for example, the relay could dynamically select an \\ethereum~or \\zeth~address to receive payment, or privately negotiate fees with the user).\n\nClearly it would be entirely possible to implement these protocols using a ``broadcast'' system, such as those employed by blockchains to propagate transactions and blocks. Requests could be broadcast unencrypted without impacting the reliability of the system, as long as messages were eventually seen by the target relay. Broadcast networks provide some inherent receiver anonymity, in the sense that it is more difficult to identify which \\emph{network node} is the recipient of a given message, however in this setting, all participants in the system would be able to see the content of relay requests and potentially determine the number of requests received by each relay identity (and, in turn, infer information about their profit). Despite relay requests being visible to other participants, the protocol would still prevent other relays from profiting from these requests, since they are bound to the target relay. Further, the content of requests could be hidden by encryption so that only the intended relay may read them. Instead of publishing a network ``address'' of some form, relays could publish an encryption key, with which users must encrypt requests before broadcasting them (although care must be taken to use a key-private encryption scheme to avoid leaking information about the recipient).\n\nWhile broadcast networks could theoretically be used in these relay protocols, unicast networks are more bandwidth efficient (i.e.~a given message needs only to find a path through the network in order to flow from the sender to the recipient). In contrast, broadcast networks may provide a level of sender anonymity in the face of network observers, although even in broadcast networks methods exist to infer the message originator (e.g.~nodes with high degree\\footnote{In the graph theoretical sense.} -- also referred to as ``supernodes'' -- can be used to infer the sender of a message on a broadcast channel by using timing information~\\cite{DBLP:conf/fc/KoshyKM14}). Broadcast communication channels are also of great interest to achieve ``recipient anonymity''(see~\\cite{DBLP:journals/compsec/PfitzmannW87} for more details on ``anonymity'').\n\nAt first sight, the use of a unicast transport may appear to increase the centralization of the system. However, this is demonstrably not the case for the protocols discussed here, which can (as described above) be implemented using a transparent broadcast network and do not inherently rely on any centralization.\n\nFinally, we note that, although broadcast networks could theoretically be used, we suggest that unicast networks are likely to be more suitable, given their lower bandwidth and complexity.\n\n\\section{Network anonymity}\\label{unicast-vs-broadcast:network-anonymity}\n\nRelay protocol designers may choose to transmit requests via the method that best fits their needs, taking into consideration the tradeoffs mentioned in \\cref{unicast-vs-broadcast:unicast-vs-broadcast} above. As well as overhead, network topology also has a strong influence on anonymity~\\cite{DBLP:conf/pet/DiazMT10}). However, in order to achieve strong privacy guarantees, anonymisation techniques (e.g.~cover traffic, message padding etc.) must be used, to minimize communication leakages.\n\nWhile protocols like Dandelion~\\cite{DBLP:journals/pomacs/Venkatakrishnan17,DBLP:journals/pomacs/FantiVBDBMV18} were initially introduced to improve \\emph{diffusion} mechanisms and improve network anonymity on Bitcoin, they could also be of interest in the context of relay request broadcasts (as alluded to in~\\cref{unicast-vs-broadcast:unicast-vs-broadcast}).\nHowever, other techniques (providing different properties) may also be of interest for relay network. Some of these are given below:\n\\begin{itemize}\n    \\item DC-nets~\\cite{DBLP:journals/joc/Chaum88} provide strong guarantees with respect to the sender anonymity (but generally incur a big overhead and require large amounts of randomness).\n    \\item Crowds~\\cite{DBLP:journals/tissec/ReiterR98} follow a ``blending into a crowd'' approach (i.e.~hiding one's actions among the actions of many others), in which a user's request is randomly circulated in a ``crowd'' (set of users) before being submitted -- by a random member of the crowd -- and sent to the destination\\footnote{Crowd members \\emph{cannot} identify the initiator of the request. The initiator is indistinguishable from a member that forwards a request from another user.}. Note that such approaches generally do not provide strong guarantees with respect to recipient anonymity\\footnote{While relay anonymity is not our principal focus, it is worth keeping in mind the impact of side channel leakages which can be used to infer information about the sender. For instance, a powerful adversary -- monitoring a big part of the Internet -- may notice a client access the relay's public information (such as the relay's website) followed by a message to the relay from a crowd to which the client belongs. The adversary may then infer that the client was the relay user. Hence, additional care needs to be allocated to the relay discovery mechanism itself, and the right trade-offs must be made depending on the application and associated threat model.}.\n    \\item Mix networks (or \\emph{mixnets})~\\cite{DBLP:series/ais/Chaum03}, in which nodes (``mix nodes'') are routers that perform cryptographic operations (providing bit-wise unlinkability), and modify the order in which output messages are emitted. This hides any correspondence between input and output messages.\n    \\item Onion routing~\\cite{DBLP:journals/cacm/GoldschlagRS99} (which also underlies ``garlic routing''~\\cite{garlic-nets}) consists of multiple layers of encryption (one per ``hop'' on the network). Requests are sent through a chosen set of routers (forming a ``circuit'') in order to obfuscate the link between sender and recipient, as seen by non-global adversaries (i.e.~those that do not control all nodes on the circuit\\footnote{In some cases, controlling the ``entry'' and ``exit'' nodes (i.e.~first and last nodes of the chain/circuit) is sufficient to carry out so-called ``correlation attacks''. See~\\url{https://github.com/Attacks-on-Tor/Attacks-on-Tor} for a list of attacks on Tor~\\cite{DBLP:conf/uss/DingledineMS04}}). This generally achieves low-latency relative to other approaches.\n\\end{itemize}\n\nImportantly, modern protocols building on these techniques use additional mechanisms for enhanced robustness (e.g.~``cover traffic'' to prevent timing attacks etc.).\n\n\\begin{remark}\n    We note that accountable anonymous communication networks~\\cite{DBLP:books/sp/07/DiazP07} are also of great interest in the context of transaction relay protocols as a way to further prevent DoS attacks.\n\\end{remark}\n", "meta": {"hexsha": "bdbe951d1c1274f6d63cdbae6a07fdaaa8a27382", "size": 12459, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "relay/appendices/unicast_vs_broadcast.tex", "max_stars_repo_name": "clearmatics/zeth-specifications", "max_stars_repo_head_hexsha": "ba29c67587395f5c7b26b52ee7ab9cba12f1cc6b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-29T18:22:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-29T18:22:00.000Z", "max_issues_repo_path": "relay/appendices/unicast_vs_broadcast.tex", "max_issues_repo_name": "clearmatics/zeth-specifications", "max_issues_repo_head_hexsha": "ba29c67587395f5c7b26b52ee7ab9cba12f1cc6b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2020-10-27T10:41:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-16T10:57:05.000Z", "max_forks_repo_path": "relay/appendices/unicast_vs_broadcast.tex", "max_forks_repo_name": "clearmatics/zeth-specifications", "max_forks_repo_head_hexsha": "ba29c67587395f5c7b26b52ee7ab9cba12f1cc6b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-26T04:51:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-26T04:51:29.000Z", "avg_line_length": 214.8103448276, "max_line_length": 1315, "alphanum_fraction": 0.8016694759, "num_tokens": 2649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.5506073655352403, "lm_q1q2_score": 0.30741894736517106}}
{"text": "\\section{Introduction}\n\n\\begin{frame}{Introduction}\n  \\textbf{Edit distance:}\n  \\begin{itemize}\n    \\item<2->\n      Measurement for similarity of two words / strings\n    \\item<3->\n      Algorithm for efficient calculation\n    \\item<4->\n      General principle: dynamic programming\n  \\end{itemize}\n\\end{frame}\n\n%-------------------------------------------------------------------------------\n\n\\begin{frame}{Introduction}{Motivation: Error tolerant string comparison}\n  \\begin{adjustbox}{width=\\linewidth}\n    \\includegraphics[width=\\linewidth]%\n      {Images/Introduction/Search_Volcano.pdf}\n  \\end{adjustbox}\n\\end{frame}\n\n%-------------------------------------------------------------------------------\n\n\\begin{frame}{Introduction}{Motivation}\n  \\textbf{A lot of applications where similar string are searched:}\n  \\begin{itemize}\n    \\item<2->\n      Duplicates in databases:\\\\[0.5em]\n      \\begin{tabular}{ll}\n        \\texttt{Hein Bl\\\"od} & \\texttt{27568 Bremerhaven}\\\\\n        \\texttt{Hein Bloed} & \\texttt{27568 Bremerhafen}\\\\\n        \\texttt{Hein Doof} & \\texttt{27478 Cuxhaven}\n      \\end{tabular}\n    \\item<3->\n      Product search:\\\\[0.5em]\n      \\texttt{memory stik}\n    \\item<4->\n      Websearch:\\\\[0.5em]\n      \\texttt{eyjaf\\\"ollajak\\\"ull}\\\\\n      \\texttt{uniwersit\\\"at verien 2017}\n    \\item<5->\n      Bioinformatics: Similarity of DNA-sequences\n  \\end{itemize}\n\\end{frame}\n\n%-------------------------------------------------------------------------------\n\n\\begin{frame}{Introduction}{Example: Bioinformtics DNA-matching}\n  \\textbf{Search of similar proteins:}\n  \\begin{itemize}\n    \\item<2->\n      \\texttt{BLAST} (\\textbf{B}asic \\textbf{L}ocal \\textbf{A}lignment\n        \\textbf{S}earch \\textbf{T}ool)\n    \\item<3->\n      Alignment $\\hat{=}$ Edit distance\n    \\item<4->\n      Changed life-science completely\n    \\item<5->\n      Cited 63437 times on Google Scholar (Sep. 2017)\n\n  \\end{itemize}\n\n\\end{frame}\n", "meta": {"hexsha": "618113fd418370d7b8e4f64f92087f47acdd8816", "size": 1917, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Lecture-14/Chapter/eng/010_Introduction.tex", "max_stars_repo_name": "TobiOnline/AlgoDat", "max_stars_repo_head_hexsha": "565a9f03a9ed7ef354cb4f143959df77df89b726", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2016-12-16T17:42:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-26T11:07:16.000Z", "max_issues_repo_path": "Lecture-14/Chapter/eng/010_Introduction.tex", "max_issues_repo_name": "TobiOnline/AlgoDat", "max_issues_repo_head_hexsha": "565a9f03a9ed7ef354cb4f143959df77df89b726", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2016-10-08T09:27:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-20T15:40:10.000Z", "max_forks_repo_path": "Lecture-14/Chapter/eng/010_Introduction.tex", "max_forks_repo_name": "TobiOnline/AlgoDat", "max_forks_repo_head_hexsha": "565a9f03a9ed7ef354cb4f143959df77df89b726", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2016-10-07T11:55:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-05T08:36:38.000Z", "avg_line_length": 29.0454545455, "max_line_length": 80, "alphanum_fraction": 0.5722483046, "num_tokens": 535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.5506073655352403, "lm_q1q2_score": 0.30741894736517106}}
{"text": "%% SECTION HEADER /////////////////////////////////////////////////////////////////////////////////////\n\\section{Model-assisted severity damage assessment }\n\\label{sec:madif}\n\n%% SECTION CONTENT ////////////////////////////////////////////////////////////////////////////////////\n\n%% SUBSECTION HEADER //////////////////////////////////////////////////////////////////////////////////\nThe process of determining the damage size is shown in the flowchart in Fig. \\ref{fig:Flowchart}.\nBefore inspecting a given \\ac{hsc} panel, a numerical analysis is performed to determine a function that describes the effect of damage on wave propagation.\nThen the model is subjected to experimental validation.\nIf the simulation results do not agree with the measured results, the material parameters of the components should be adjusted.\nIn the dissertation, the volume fraction fibre of the \\ac{cfrp} is adjusted to determine a wave velocity \\cite{kudela2007modelling} and a damping coefficient of the skin to set the magnitude of the registered signals \\cite{wandowski2017guided}.\n\\begin{figure}[H]\n\t\t\\begin{center}\n\t\\includegraphics[width=1\\linewidth]{Chapter_3/flowchart}\n\t\t\\end{center}\n\t\\caption{A flowchart representing the process for damage size estimation.}\n\t\\label{fig:Flowchart}\n\\end{figure}\n\nWhen the structure model is developed, several computer simulations for various damage sizes must be conducted to determine the \\ac{madif}, a cornerstone of the dissertation. This function determines the severity of the \\ac{hsc} damage based on the signal received by the sensor.\nSeveral excitation signals and damage indices will be considered to select the best \\ac{madif}.\nThe selection criterion will be the monotonicity and the function slope over the considered range of the damage size. Then, the damage magnitude is obtained from the \\ac{madif} for the measured signal and normalised to the reference one.\n\n\n", "meta": {"hexsha": "d7c0bb3d8ef095e161ead77d2c8989b63964435c", "size": 1906, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/proposal/Dissertation/Chapters/Chapter3/sec:madif.tex", "max_stars_repo_name": "pfiborek/model-hc", "max_stars_repo_head_hexsha": "9e49fe23117fd320be14214e5ff6bafd2b1fc1a3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/proposal/Dissertation/Chapters/Chapter3/sec:madif.tex", "max_issues_repo_name": "pfiborek/model-hc", "max_issues_repo_head_hexsha": "9e49fe23117fd320be14214e5ff6bafd2b1fc1a3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/proposal/Dissertation/Chapters/Chapter3/sec:madif.tex", "max_forks_repo_name": "pfiborek/model-hc", "max_forks_repo_head_hexsha": "9e49fe23117fd320be14214e5ff6bafd2b1fc1a3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 73.3076923077, "max_line_length": 279, "alphanum_fraction": 0.6956977964, "num_tokens": 374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3073633411834779}}
{"text": "% !TeX program = lualatex\n\\documentclass[]{article}\n\n\\usepackage{caption,subcaption,graphicx,float,url,amsmath,amssymb,amsthm,tocloft,cancel,thmtools,gensymb,braket,tikz-cd,tikz-feynman,mathtools}\n\\usepackage[toc,nonumberlist]{glossaries}\n\\usepackage{glossaries-extra}\n\\newcommand\\numberthis{\\addtocounter{equation}{1}\\tag{\\theequation}}\n\n\\newtheorem{thm}{Theorem}\n\\newtheorem{defn}[thm]{Definition}\n\\newtheorem{cor}[thm]{Corollary}\n\\newtheorem{lemma}[thm]{Lemma}\n\\graphicspath{{figs/}}\n\\widowpenalty10000\n\\clubpenalty10000\n\\setcounter{tocdepth}{2}\n\\tikzfeynmanset{compat=1.0.0}\n%opening\n\\title{Theoretical Minimum\\\\Advanced Quantum Mechanics}\n\\author{Simon Crase (compiler)\\\\simon@greenweaves.nz}\n\n\\begin{document}\n\n\\maketitle\n\n\\begin{abstract}\nThese are my notes from the Advanced Quantum Mechanics lectures\\cite{susskind2013advanced}  from Leonard Susskind's Theoretical Minimum series\\cite{susskind2007theoretical}. Feynman diagrams were prepared using \\emph{TikZ-Feynman} \\cite{ellis2016tikz}.\n\nDisclaimer: I have created these notes as an aide-m\\'emoire for my own use; if you find them useful, you are welcome, but I'd appreciate hearing from you. They are not intended \nas a substitute for listening to the lectures. The intellectual property for all material derived from the lectures belongs, of course, to Professor Susskind; any mistakes, however, are my own.\n\nThe notes were created using TexStudio\\cite{TexStudio}, which I recommend for compiling them to a PDF; the bibliography was created using JabRef\\cite{Jabref}.\n\n\\end{abstract}\n\n\\tableofcontents\n\\listoffigures\n\\listoftables\n\\listoftheorems\n\n\n\\section{Review and Introduction to Symmetry}\n\nWe start with a review of quantum mechanics, and then move on to the applications--not the technology but the basic physics problems for which quantum mechanics was invented: atoms; electrons, which stand for a whole class of particles, muons, quarks, neutrinos; and photons. One theme will be symmetry--how symmetries are realized in quantum mechanics, how they are represented, and what they tell us about the quantum mechanical system\n\n\\subsection{Review of Quantum Mechanics}\n This is a review of material from \\cite{susskind2012quantum,susskind2014quantum}.\n\\begin{itemize}\n\t\\item We start by asking how to represent the state of a system: in classical mechanics states are represented as points in phase space, in quantum mechanics they are represented by state vectors, in a vector space--$\\ket{\\psi}$ and $\\bra{\\psi}$. Complex numbers are ubiquitous in quantum mechanics, and our vector space is also complex; $\\bra{\\psi}$ is analogous to the complex conjugate of $\\ket{\\psi}$.\n\t\\item Observables. We have observables in classical mechanics, such as position and momentum, but we assume we know what we mean when we say \"observable\". In quantum mechanics we have to be very precise. An observable is represented by a Hermitian matrix. Hermitian operators are analogous to real numbers: $A=A^{\\dag}$.\n\t\\item Eigenvalues represent values that can be measured: $A\\ket{\\alpha} = \\alpha\\ket{\\alpha}$. The set of eigenvalues is the set of possible values of a measurement; the eigenvectors are the state vectors of the system such that, if you make a measurement in one of these states, the value is definite, not statistical, and the value is $\\alpha$.\n\t\\item Inner product $\\braket{\\phi|\\psi}$-- a complex number defined for any bra/ket pair.\n\t\\item Orthogonal $\\braket{\\phi|\\psi}=0$--for any pair of states that can be distinguished by some possible measurement.\n\t\\item A particle is something that has a definite position in space. The position, $x$ say, should be thought of as an observable. If we measure a particle's position and definitely find it at $x_0$, we have state vector $\\ket{x_0}$.\n\t\\begin{itemize}\n\t\t\\item Independent values $\\braket{x|x^{\\prime}}=0$ if $x$ and $x^{\\prime}$ are distinguishable.\n\t\t\\item For any state $\\ket{\\psi}$, $\\braket{x|\\psi} = \\psi(x)$ is called the \\emph{wave function}. \n\t\t\\item The meaning of $\\psi$ is closely related to probability: probability of finding particle at $x$ is $P(x)=\\psi^*(x)\\psi(x)$\n\t\t\\item Position is an observable $X$. In 3 dimensions $\\braket{xyz|x^{\\prime}y^{\\prime}z^{\\prime}}=0$ if there is any mismatch $x^{\\prime}\\ne x \\lor y^{\\prime} \\ne y \\lor z^{\\prime} \\ne z$. We will generally suppress $y$ and $z$; remember they are still there.\n\t\t\\item Another important observable is Momentum, which has one component for each dimension of space: $P\\psi(x)=- i \\hslash \\frac{\\partial \\Psi}{\\partial x}$.\n\t\t\\item The eigenvector of $X$ corresponding to $x_0$ is $\\delta(x-x_0)$.\n\t\t\\item The eigenvector of $P$ corresponding to $p_0$ is $e^{\\frac{i p_0 x}{\\hslash}}$. Using $P(x)=\\psi^*(x)\\psi(x)$, $P(x)=1$--particles is smeared along entire line--Uncertainty Principle.\n\t\\end{itemize}\n\\end{itemize}\n\n\\begin{itemize}\n\t\\item Evolution operator $U(t)$:\n\t\\begin{itemize}\n\t\t\\item $U(t)\\ket{\\psi(0)} = \\ket{\\psi(t)}$\n\t\t\\item $U(t)\\ket{\\psi(t_0)} = \\ket{\\psi(t_0 + y)}$\n\t\\end{itemize}\n\t\\item Following the \"minus 1-th law\"\\footnote{Information is conserved}, we postulate that two states that are observably different will not evolve into two other states that are \\emph{not} observably different, so inner products must be preserved: $\\braket{\\phi|\\psi}=\\braket{\\phi|U^{\\dagger}U|\\psi}$ i.e. $U^{\\dagger}U=I$. U is \\emph{Unitary}\n\t\\item Let $U(\\epsilon)= I + \\epsilon G$, so $U^\\dagger(\\epsilon)= I - \\epsilon G^\\dagger$ and $G=-G^{\\dagger}$. We can satisfy this be defining $G=- i H$ for some Hermitian $H$--the \\emph{Hamiltonian}.\n\t\\item For general $t$, $U(t)=e^{- i H t}$\n\\end{itemize}\n\\begin{align*}\n\t\\psi(t+\\epsilon) =& e^{-i \\hslash \\epsilon} \\ket{\\psi(t)}\\\\\n\t=& (1- i \\hslash \\epsilon)\\ket{\\psi(t)}\\\\\n\t\\frac{\\ket{\\psi(t+\\epsilon)} -\\ket{\\psi(t)} }{\\epsilon}=& -i \\hslash \\ket{\\psi(t)}\\\\\n\t\\frac{\\partial \\ket{\\psi}}{\\partial t} =& -i H \\ket{\\psi(t)} \\text{, Time dependent Schr\\\"odinger Equation}\\\\\n\tH \\ket{\\psi} =& E \\ket{\\psi}\\text{, Time independent Schr\\\"odinger Equation}\n\\end{align*} \n\nHow does eigenvector change with time? It just gets multiplied by a \\emph{phase}, which has no effect on probability.\n\n\\subsection{Introduction to Symmetry}\n\nEvolution is one example of a transformation on a system which preserve inner products. One important example is the rotational symmetry of the hydrogen atom. Translational symmetry is another example.\n\n\\begin{defn}[Symmetry]\\label{defn:symmetry}\n\tA symmetry is a transformation that doesn't change equations. \n\\end{defn}\n\nIf $V$ is a symmetry we expect it to be unitary, as it should preserve differences.\n\n\\begin{thm}[A symmetry is a unitary operator that commutes with the Hamiltonian]\n\t\\begin{align*}\n\tV \\ket{\\psi} =& \\ket{\\psi^{\\prime}} \\text{is a symmetry}\\numberthis \\label{eq:symmetry}\\\\\n\t\\iff&\\\\\n\tV H =& H V\\numberthis \\label{eq:symmetry:commute}\n\t\\end{align*}\n\\end{thm}\n\n\\begin{proof}\n\tSuppose $\\psi_1$ evolves to $\\psi_2=U(t)\\psi_1$, as shown in Figure \\ref{fig:commutator}.\n\t\\begin{figure}[H]\n\t\t\\begin{center}\n\t\t\t\\caption{Commutative diagram: $\\ket{\\psi_1}$ evolves to $\\ket{\\psi_2}$}\\label{fig:commutator}\n\t\t\t\\begin{tikzcd}\n\t\t\t\t\\ket{\\psi_1} \\arrow[r, \"U\"] \\arrow[d,\"V\"]\n\t\t\t\t& \\ket{\\psi_2} \\arrow[d, \"V\" ] \\\\\n\t\t\t\t\\ket{\\psi_1^\\prime} \\arrow[r,  \"U\" ]\n\t\t\t\t&  \\ket{\\psi_2^\\prime}\n\t\t\t\\end{tikzcd}\n\t\t\\end{center}\n\t\\end{figure}\n\t\\begin{align*}\n\t\t\\ket{\\psi_1} \\xrightarrow{U}& \\ket{\\psi_2} \\text {or, equivalently}\\\\\n\t\t\\psi_2 =& U \\psi_1 \\text{. Now, if $V$ really is a symmetry:} \\numberthis \\label{eq:psi_1}\\\\\n\t\t\\ket{\\psi_1^{\\prime}} \\xrightarrow{U}& \\ket{\\psi_2^{\\prime}} \\text {,  or}\\\\\n\t\t\\psi_2^{\\prime} =& U \\psi_1^{\\prime} \\text{, so from (\\ref{eq:symmetry}) and Definition \\ref{defn:symmetry}:} \\\\\n\t\tV\\ket{\\psi_2} =& U V \\ket{\\psi_1} \\text{, or, using (\\ref{eq:psi_1})}\\\\\n\t\tV U\\ket {\\psi_1} =& U V \\ket{\\psi_1} \\text{. But $\\ket{\\psi_1}$ is an arbitrary state, so} \\\\\n\t\tV U =& U V \\text{. Hence for small time $\\epsilon$}\\\\\n\t\tV (I - i \\epsilon H) =& (I - i \\epsilon H) V \\text{, whence}\\\\\n\t\tV H =& H V \\text{, which is (\\ref{eq:symmetry:commute})}\n\t\\end{align*}\n\tMoreover the symmetry $V$ should transform mutually exclusive states into mutually exclusive states, whence it should preserve orthogonality; $V$ should be unitary. \n\\end{proof}\n\nSymmetries can be discrete or continuous.\n\n\\begin{itemize}\n\t\\item Discrete\n\t\\begin{itemize}\n\t\t\\item Reflection\n\t\t\\item interchange particles\n\t\\end{itemize}\n\t\\item Continuous\n\t\\begin{itemize}\n\t\t\\item rotation\n\t\t\\item translation\n\t\\end{itemize}\n\\end{itemize}\n\nAll continuous symmetries can be generated by $I-i \\epsilon G$, for some Hermitean $G$ such that $[H,G]=0$.\n\nE.g.\n\\begin{align*}\nV \\psi(x) = & \\psi(x-\\epsilon)\\text{, shift right}\\\\\n=& \\psi(x) - \\epsilon \\frac{\\partial \\psi}{\\partial x}\\\\\nV =& I -  \\epsilon \\frac{\\partial }{\\partial x}\\\\\n=& I - \\frac{i \\epsilon}{\\hslash}P\\\\\nG =& \\frac{P_x}{\\hslash}\\text{, Generator of $x$ translation}\n\\end{align*}\n\n\n\\section{Symmetry groups and degeneracy}\\label{seq:symmetry:degeneracy}\n\n\\subsection{Symmetry groups and degeneracy}\n\nSymmetries are operations that you can do on a system which don't change:\n\\begin{itemize}\n\t\\item the description;\n\t\\item the phenomena;\n\t\\item then energy levels, and value of the energy.\n\\end{itemize}\n\nExamples of symmetry:\n\\begin{itemize}\n\t\\item translation--doesn't change energy levels, Hamiltonian, or the Schro\\\"edinger equation;\n\t\\item rotation;\n\t\\item interchanging identical particles;\n\t\\item crystal symmetry: translate one lattice spacing (not exact if crystal not infinite).\n\\end{itemize}\nSome symmetries are more abstract than others; the more obvious symmetries come from the properties of space; homogeneity and isotropy.\n\n\\begin{defn}[Degeneracy of energy levels]\n\tIf there is more than one state with given energy level, that energy level is called degenerate. We will see that it only happens when there is a symmetry: symmetries sometimes imply degeneracy, but not always.\n\\end{defn}\n\nDegeneracy isn't a coincidence: symmetry sometimes implies degeneracy.\n\nOne application of symmetry is to analyze the energy of a system and see if it has energy levels that exactly match.\n\n\nWe will start with Rotation symmetry and think about a very simple system, a particle moving in a circle. If it can't leave the circle we can describe its position using an angle $\\theta$. It has a wave function $\\psi(\\theta)$, such that $\\psi^*(\\theta)\\psi(\\theta)$ gives the probability of finding the particle at a particular point.\n\nFor a small counter-clockwise rotation:\n\\begin{align*}\n\\psi(\\theta) \\rightarrow & \\psi(\\theta - \\epsilon)\\\\\n\\delta\\psi =& - \\epsilon \\frac{\\partial \\psi}{\\partial \\theta} \\text{, c.f. linear momentum}\\\\\n=& -i \\epsilon \\big(-i \\frac{\\partial \\psi}{\\partial \\theta}\\big)\n\\end{align*}\nNow defining the Angular Momentum operator $L$:\n\\begin{align}\n- i \\frac{\\partial}{\\partial \\theta} \\triangleq&\\hslash L \\text{, Hermitean--c.f. $P=-i\\hslash \\frac{\\partial}{\\partial x}$}\\\\\n\\delta\\psi =& - \\frac{i \\epsilon}{\\hslash} L \\psi \\text{, generator of rotation}\n\\end{align}\nWhat are the Eigenvalues and Eigenvectors of Rotation?\n\n\\begin{align*}\nL\\ket{\\psi} =& m \\ket{\\psi}\\\\\n-i \\hslash \\frac{\\partial \\psi}{\\partial \\theta} =& m \\psi\\\\\n\\psi(\\theta) =& e^{\\frac{i m \\theta}{\\hslash}}\\text{. Now, we want $\\psi$ single valued (symmetry!), i.e.}\\\\\n\\psi(\\theta + 2\\pi) =& \\psi(\\theta) \\text{, so}\\\\\n\\frac{m}{\\hslash}=&k\\text{, some integer. But, by convention, redefine $m$}\\\\\nL=& m \\hslash \\numberthis \\label{eq:magnetic:quantum:number}\n\\end{align*}\nThis is the quantization of angular momentum.\n\n\\begin{defn}[Magnetic quantum number]\n\tThe eigenvalue of $L$, $m$ in (\\ref{eq:magnetic:quantum:number}) is known as the Magnetic quantum number.\n\\end{defn}\n\nWe expect that the energy will depend on the angular momentum. Now $m\\ne 0 \\implies E(m)=E(-m)$, so we have degeneracy. A magnetic field breaks this; rotational symmetry isn't enough for degeneracy, but adding reflection symmetry is sufficient (but need two non-commuting symmetries).\n\nWe will use $M$ to denote reflection symmetry. If we have reflection symmetry, $E(m)=E(-m)$, because the reflection of a system with specified angular momentum is a system with opposite angular momentum (Avoid calling reflection symmetry \"mirror symmetry\", as is this is used in string theory with a precise meaning).\n\nThe reflection of a magnetic field is not the same field, as it is an axial vector. Imagine a current generating a magnetic field going into the plane. If we reflect, the current goes in the opposite direction, as does the magnetic field.\n\n\\begin{thm}[Two symmetries that don't commute imply degeneracy]\n\tSuppose we have two symmetries, whose generators are $A$ and $B$.\n\t\\begin{align*}\n\t\t[A,H]=&0 \\text{, because it's a symmetry}\\\\\n\t\t[B,H]=& 0\\\\\n\t\t[A,B]\\ne 0\n\t\\end{align*}\n\tthen...\n\\end{thm}\n\\begin{proof}\n\t\\begin{align*}\n\t\t[A,B]=& i C  \\text{. Need $i$ for $C$ to be Hermitean}\n\t\\end{align*}\n\t\\begin{lemma}[C commutes with H]\n\t\t$[C,H]=0$\n\t\\end{lemma}\n\t\\begin{proof}\n\t\tThere are two cases: $C$ is a linear combination of $A$ and $B$, or $A$, $B$, and $C$ are independent. Since the lemma is trivial in the former case, we shall suppose the latter.\n\t\t\\begin{align*}\n\t\ti[C,H] =& (AB)H - H(AB)\\\\\n\t\t=& AHB -HAB\\\\\n\t\t=& [A,H]B\\\\\n\t\t=&0\n\t\t\\end{align*}\n\t\\end{proof}\n\t\n\tTBP\n\\end{proof}\n\n\\begin{thm}[Reflection and rotation don't commute]\n\tIf $M\\psi(\\theta) = \\psi(-\\theta)$, $ML \\ne LM$\n\\end{thm}\n\\begin{proof}\n\t\\begin{align*}\n\tMLe^{i m \\theta} =& M m e^{i m \\theta}\\\\\n\t=&m e^{- i m \\theta}\\\\\n\tLMe^{i m \\theta} =& L e^{- i m \\theta}\\\\\n\t=& -m e^{- i m \\theta}\\\\\n\t[M,L]e^{im\\theta}=&2m e^{- i m \\theta}\n\t\\end{align*}\n\\end{proof}\n\n\n\n\n\n\\begin{defn}[Commutator algebra]\n\tClosure of $\\{A,B,C,...\\}$ under commutation.\n\\end{defn}\n\nCollection of generators is an algebra.\n\n\\begin{defn}[abelian]\n\tA group of symmetries that all commute.\n\\end{defn}\n\n\\begin{defn}[non-abelian]\n\tA group of symmetries that isn't abelian.\n\\end{defn}\n\n\\subsection{An example: Angular Momentum}\n\nConsider a classical orbit with energy $E$, Figure \\ref{eq:aqm-2-1}. \tIs it degenerate? All we have to do is rotate it to see a new orbit with energy $E$: rotation about the y-axis has added a z-component. This is a classical suggestion that the quantum mechanical operators of angular momentum don't commute (rotation about 2nd axis converts rotation about 1st into something with a component along 3rd).\n\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\caption{Degeneracy of Angular Momentum(classical)}\\label{eq:aqm-2-1}\n\t\t\\includegraphics[width=0.5\\textwidth]{aqm-2-1}\n\t\\end{center}\n\\end{figure}\n\nLet's look at the angular momentum generators. Figure \\ref{fig:aqm-2-2} shows a  rotation about the z-axis by a small angle $\\epsilon$.\n\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\caption{Rotation in 2D by a small angle $\\epsilon$}\\label{fig:aqm-2-2}\n\t\t\\includegraphics[width=0.5\\textwidth]{aqm-2-2}\n\t\\end{center}\n\\end{figure}\n\n\\begin{align*}\n\t\\delta x =& - y \\epsilon\\\\\n\t\\delta y =& x \\epsilon \\text{. Now for a wave function $\\psi(x,y)$}\\\\\n\t\\delta \\psi =& \\frac{\\partial \\psi}{\\partial x} \\delta x + \\frac{\\partial \\psi}{\\partial y} \\delta y\\\\\n\t=&\\big( - y \\frac{\\partial \\psi}{\\partial x} + x \\frac{\\partial \\psi}{\\partial y}\\big) \\epsilon\\\\\n\t\\triangleq& i \\epsilon L_z \\psi\\\\\n\t=& \\big(- y P_x + x P_y x\\big) i \\epsilon \\text{, whence}\\\\\n\tL_z =& x P_y - y P_x \\text{, similarly}\\\\\n\tL_x =& y P_z - z P_y \\text{, and}\\\\\n\tL_y =& x P_x - x P_z \\text{, c.f. the classical formula}\\\\\n\t\\vec{L} =& \\vec{r} \\times \\vec{P}\n\\end{align*}\nThese are symmetries if the system is rotationally invariant.\n\nDo they commute with each other? In \\cite{susskind2014quantum} we saw\n\\begin{align*}\n\t[L,H_i]=& 0 \\numberthis \\label{eq:LH}\\\\\n\t[L_x,L_y] =& i L_z \\numberthis \\label{eq:lx_ly}\\\\\n\t[L_y,L_z] =& i L_x\\numberthis \\label{eq:ly_lz}\\\\\n\t[L_z,L_x] =& i L_y\\numberthis \\label{eq:lz_lx}\n\\end{align*}\n\n\\begin{defn}[Algebra]\n\tIn mathematics, an \\emph{algebra over a field } (often simply called an algebra) is a vector space equipped with a bilinear product. \n\\end{defn}\n\n\\begin{defn}[Lie algebra]\n\tA Lie algebra is an algebra where multiplication is commutation. LS uses the definition that is is a collection of generators that is closed under commutation.\n\\end{defn}\n\nSo $L_x$, $L_y$, $L_z$ generate a Lie algebra: if we continue commuting we don't find anything new.\n\nWe want to find eigenvalues of angular momentum. It us useful to introduce creation and annihilation operators for $L_z$.\n\\begin{align*}\n\tL_{\\pm} \\triangleq& L_x \\pm i L_y \\numberthis \\label{eq:comm:Lpm}\\\\\n\t[L_{\\pm},L_Z] =& \\mp L_{\\pm} \\numberthis \\label{eq:comm:LpmLz}\n\\end{align*}\n\n\\begin{thm}[If $\\ket{m}$ is an eigenvector of $L_z$, so are $L_+ \\ket{m}$ and $L_- \\ket{m}$]\n\tIf \n\t\\begin{align*}\n\t\tL_z \\ket{m} =& m \\ket{m} \\text{, then }\\\\\n\t\tL_z (L^+ \\ket{m}) =& (m+1) (L^+\\ket{m}) \\text{, and}\\\\\n\t\tL_z (L^- \\ket{m}) =& (m-1) (L^-\\ket{m})\n\t\\end{align*}\n\\end{thm}\n\\begin{proof}\n\tSuppose we have found one eigenvector of $L_z$:\n\t\\begin{align*}\n\t\tL_z \\ket{m} =& m \\ket{m} \\text{, magnetic quantum number}\\numberthis \\label{eq:ev:Lz}\\\\\n\t\t[L_+,L_z] \\ket{m} =& \\big(L_+L_z - L_zL_+\\big) \\ket{m}\\\\\n\t\t=&- L_+ \\ket{m} \\text{, from (\\ref{eq:comm:LpmLz}). Rearranging  and using (\\ref{eq:ev:Lz})}\\\\\n\t\tm L_+\\ket{m} + L_+\\ket{m} =& L_z L_+ \\ket{m} \\text{, whence}\\\\\n\t\t\\big(m + 1 \\big)L_+\\ket{m}  =& L_z L_+ \\ket{m} \\text{; $L_+ \\ket{m}$ is an eigenvector, eigenvalue $m+1$}\\numberthis \\label{eq:create_m}\n\t\\end{align*}\n\tSimilarly, $L_- \\ket{m}$ is an eigenvector, eigenvalue $m-1$. The sequence of eigenvectors terminates if  $L_{\\pm} \\ket{m}=0$.\n\\end{proof}\n\nSo, using the algebra of commutators, we have generated a spectrum of values of $L_z$, separated by integers--see Figure \\ref{fig:aqm-2-3}. Imagine that we rotate by $180\\degree$: this takes $L_z\\rightarrow - L_z$, so rotational symmetry requires that the termination points be reversed: they must be symmetrical. There are two possibilities--Figures \\ref{fig:aqm-2-3a} and \\ref{fig:aqm-2-3b}. We can show that the only values that are allowed for orbital angular momentum are integral (single values wave function), but half integral is also possible for spin. \n\n\\begin{figure}[H]\n\t\\caption{Spectrum of $L_z$.}\\label{fig:spectrum_Lz}\n\t\\begin{subfigure}[t]{0.3\\textwidth}\n\t\t\\caption{Terminators in red}\\label{fig:aqm-2-3}\n\t\t\\includegraphics[width=0.8\\textwidth]{aqm-2-3}\n\t\\end{subfigure}\n\t\\begin{subfigure}[t]{0.3\\textwidth}\n\t\t\\caption{Integral values in red}\\label{fig:aqm-2-3a}\n\t\t\\includegraphics[width=0.8\\textwidth]{aqm-2-3a}\n\t\\end{subfigure}\n\t\\begin{subfigure}[t]{0.3\\textwidth}\n\t\t\\caption{Half integral values}\\label{fig:aqm-2-3b}\n\t\t\\includegraphics[width=0.8\\textwidth]{aqm-2-3b}\n\t\\end{subfigure}\n\\end{figure}\n\n We now show that the multiplet of states in Figure \\ref{fig:aqm-2-3a} all have the same energy. \n\n\\begin{thm}[Eigenvectors of $L_z$ are degenerate eigenvectors of $H$]\n\t\\begin{align*}\n\tL_z \\ket{m} = m \\ket{m} \\land& H \\ket{m} = E \\ket{m}\\\\\n\t \\implies&\\\\\n\t  H \\ket{m \\pm 1} =& E \\ket{m \\pm 1}\n\t\\end{align*}\n\\end{thm} \n\\begin{proof}\n\t\\begin{align*}\n\tH \\ket{m} =& E \\ket{m} \\numberthis \\label{eq:assume_ev}\\\\\n\tH L_+ \\ket{m} =& L_+ H \\ket{m}\\\\\n\t=& L_+ E \\ket{m} \\text{, from (\\ref{eq:assume_ev})}\\\\\n\t=& E L_+  \\ket{m}\\\\\n\tH \\ket{m+1} =& E \\ket{m+1} \\text{, from (\\ref{eq:create_m})}\n\t\\end{align*}\n\tSince symmetries commute, we have degeneracy.\n\\end{proof}\n\n\\section{Atomic orbits and harmonic oscillators}\n\n\\subsection{Atomic orbits and Angular Momentum}\n\nWe will talk more about what angular momentum is about.\n\nIf a particle moves in a central force field, angular momentum and, hence, the orbital plane are preserved. The state is $\\psi(r,\\theta,\\phi)= \\psi(r,\\theta)$; if system were 2 dimensional, the angular momentum would be:\n\n\\begin{align*}\n\tL =& -i \\frac{\\partial}{\\partial \\theta} \\text{, and the eigenvalues and eigenvectors would satisfy}\\\\\n\t-i \\frac{\\partial \\psi(r,\\theta)}{\\partial \\theta} =& l \\psi(r,\\theta) \\text{, which has solution}\\\\\n\t\\psi(r,\\theta) =& e^{i l \\theta} \\chi(r) \\text{, for some $\\chi$}\n\\end{align*}\n\nIn 3 dimensions, $\\psi(r,\\theta,\\phi)= Y(\\theta,\\phi) \\chi(r)$, where $Y(\\theta,\\phi)$ encapsulates the angular dependence of the wave function.\n\nIn Section \\ref{seq:symmetry:degeneracy} we derived the commutators, (\\ref{eq:lx_ly}), (\\ref{eq:ly_lz}), and (\\ref{eq:lz_lx}). We selected one component, $L_z$, and worked with its eigenvectors, $L_z \\ket{m} = m \\ket{m}$. We defined $L_\\pm$, (\\ref{eq:comm:Lpm}), and found that they had useful properties, (\\ref{eq:comm:LpmLz}). $L_\\pm$ were raising and lowering operators, which take use up and down the spectrum.\n\nWe asked whether the raising and lowering could go on forever. The only way to come to an end is if $\\exists l$ such that $L_+\\ket{k}=0$ (and similarly for $L_-$). Spectrum has to be symmetric (rotational invariance). We found spectrum had to go up in integers, and that it started at either an integer or half integer. We found that the spectrum was a multiplet of $2l+1$ states. The multiplet is characterized by the magnitude of angular momentum.\n\n\nFrom (\\ref{eq:create_m}) we have a spectrum of angular momenta, integral or half integral, say $\\set{-l,...,l:L_+\\ket{l}=0}$. There are $2l+1$ states with constant $L^2 = L_x^2 + L_y^2 + L_x^2$. Classically $L^2 = L_z^2 +(L_x-iL_y)(L_x+iL_y)$, but this fails in quantum mechanics as they operators don't commute.\n\nThe quantum version is:\n\\begin{align*}\n\tL^2 =& L_z^2 +(L_x-iL_y)(L_x+iL_y) -i [L_x,L_y]\\\\\n\t=& L_z^2 + L_z + L^-L^+\\\\\n\tL^2\\ket{l}=& L_z^2\\ket{l} + L_z\\ket{l} + L^-L^+\\ket{l}\\\\\n\t=& l^2\\ket{l} + l\\ket{l} + 0\\text{, because eigenvectors.}\\\\\n\tL^2\\ket{l}=&l (l+1) \\ket{l} \\numberthis \\label{eq:max:L}\n\\end{align*}\n\n\\begin{thm}[Degeneracy of $L^2$]\\label{thm:degeneracy:L2}\n\t\\begin{enumerate}\n\t\t\\item $[L^2, L_i] =0$\\label{thm:degeneracy:1}\n\t\t\\item All eigenvectors of $L_z$ are eigenvectors of $L^2$, eigenvalue $l(l+1)$\\label{thm:degeneracy:2}\n\t\\end{enumerate}\n\\end{thm}\n\\begin{proof}\n\tPart \\ref{thm:degeneracy:1}\n\t\\begin{align*}\n\t\t[L^2, L_x] =& [L_x^2+L_y^2+L_2^2,L_x]\\\\\n\t\t=& \\cancel{[L_x^2,L_x]} + [L_y^2,L_x] + [L_z^2,L_x] \\numberthis \\label{eq:L2}\\\\\n\t\t[L_y^2,L_x]=&L_yL_yL_x -L_y L_x L_y + L_y L_x L_y -L_xL_yL_y\\\\\n\t\t=&-L_y[L_x,L_y]-[L_x,L_y]L_y\\\\\n\t\t=&-iL_yL_z-iL_zL_y \\text{, using (\\ref{eq:lx_ly})} \\numberthis \\label{eq:ly2x}\\\\\n\t\t[L_z^2,L_x]=&L_zL_zL_x -L_z L_x L_z + L_z L_x L_z -L_xL_zL_z\\\\\n\t\t=&L_z[L_z,L_x]+[L_z,L_x]L_z\\\\\n\t\t=&iL_zL_y+iL_yL_z \\text{, using (\\ref{eq:lz_lx})} \\numberthis \\label{eq:lz2x}\\\\\n\t\t[L^2, L_x] =&0 \\text{, on substituing (\\ref{eq:ly2x}) and (\\ref{eq:lz2x}) in (\\ref{eq:L2})}\n\t\\end{align*}\n\tPart \\ref{thm:degeneracy:2}. We know from (\\ref{eq:max:L}) that the eigenvector of $L_z$ with the maximum eigenvalue satisfies the  theorem. The theorem follows by induction once we have the following Lemma.\n\t\\begin{lemma}[Induction step for Theorem \\ref{thm:degeneracy:L2}]\n\t\tIf $\\ket{m}$ is an eigenvector of $L_z$, and it is also an eigenvector of $L^2$, with eigenvalue $l(l+1)$, and $L_-\\ket{m}$ is not zero, then  $L_-\\ket{m}$ is an eigenvector of $L^2$, with eigenvalue $l(l+1)$.\n\t\\end{lemma}\n\t\\begin{proof}\n\t\t\\begin{align*}\n\t\tL^2\\ket{m}=&l (l+1) \\ket{m} \\text{, by hypothesis. Now}\\\\\n\t\t[L_-,L^2] =& 0 \\text{, from (\\ref{eq:comm:Lpm}) and Part \\ref{thm:degeneracy:1}, hence}\\\\\n\t\tL^2(L_- \\ket{m})=&(L^2 L_-) \\ket{m}\\\\\n\t\t=& (L_- L^2) \\ket{m}\\\\\n\t\t=& L_- (L^2 \\ket{m})\\\\\n\t\t=& L_- [l (l+1) \\ket{m}]\\\\\n\t\t=& l (l+1) (L_- \\ket{m})\n\t\t\\end{align*}\n\t\\end{proof}\n\t\n\\end{proof}\n\nWhen we find a multiplet such as Figure \\ref{fig:aqm-2-3}, we not only have eigenvectors of $L_z$, but also of $L^2$. For each $l $, there are $2l+1$ states with the same $L^2$, and the same Energy\\footnote{Because $[L_i,H]=0$--(\\ref{eq:LH})}. Classically they are just tilts--Figure \\ref{eq:aqm-2-1}.\n\nWe have a collection of functions of the angles, characterized by $m$ and $l$, $Y_{ml}(\\theta,\\phi)$. They are known as ''spherical harmonics'', and they are the analogues on the unit sphere of $e^{\\pm i l \\theta}$\n\n\\subsection{The Central Force Problem}\n\nWe will use classical mechanics to guess a solution.\n\n\nClassically:\n\\begin{align*}\n\tH =& \\frac{\\vec{P}^2}{2m} + V(r) \\text{, conserved} \\numberthis \\label{eq:classical:Hamiltonian}\\\\\n\t\\vec{L} =& \\vec{r}\\times \\vec{P}  \\text{, angular momentum is conserved, so use $xy$ plane}\\\\\n\tH =& \\frac{P_r^2+P_{\\theta}^2}{2m} +V(r) \\text{, resolving as shown in Figure \\ref{fig:aqm-3-1-momentum}} \\numberthis \\label{eq:resolve}\\\\\n\t=& \\frac{P_r^2}{2m} + \\frac{L^2}{2m r^2} + V(r) \\text{, since $\\left|L\\right| = \\left|r\\right| \\left|P\\right|$}\n\\end{align*}\n\nSo we have an equation for a one dimensional problem. Figure \\ref{fig:aqm-3-central} depicts the potential, and Figure \\ref{fig:aqm-3-central-osc} shows a solution, oscillations about the $r$ that yields the minimum potential. \n\n\\begin{figure}[H]\n\t\\caption{Central Force as  a one dimensional problem}\n\t\\begin{subfigure}[t]{0.3\\textwidth}\n\t\t\\caption{Resolving momentum into radial and angular components}\\label{fig:aqm-3-1-momentum}\n\t\t\\includegraphics[width=\\textwidth]{aqm-3-1-momentum}\n\t\\end{subfigure}\n\t\\begin{subfigure}[t]{0.3\\textwidth}\n\t\t\\caption{Potential assuming the Coulomb force}\\label{fig:aqm-3-central}\n\t\t\\includegraphics[width=\\textwidth]{aqm-3-central}\n\t\\end{subfigure}\n\t\\begin{subfigure}[t]{0.3\\textwidth}\n\t\t\\caption{Small oscillations about minimum}\\label{fig:aqm-3-central-osc}\n\t\t\\includegraphics[width=\\textwidth]{aqm-3-central-osc}\n\t\\end{subfigure}\n\\end{figure}\n\nThat is the classical physics. What about the quantum physics? For the quantum physics we have a wave function which satisfies the Schr\\\"odinger Equation(\\ref{eq:schroedinger:central}). The angular part is totally taken care of by our existing study of angular momentum\\footnote{Strictly step (\\ref{eq:resolve}) requires a quantum mechanical justification}.\n\\begin{align*}\n\t-\\frac{\\hslash^2}{2m}\\frac{\\partial^2 \\psi(r)}{\\partial r^2} + \\hslash^2 \\frac{l(l+1)\\hslash^2}{r^2}\\psi(r)+V(r)\\psi(r) =& E\\psi(r)\\numberthis \\label{eq:schroedinger:central}\n\\end{align*}\n\nFigure \\ref{fig:aqm-3-central-potential} depicts the potential for the Coulomb force. The energy levels of (\\ref{eq:schroedinger:central}) are characterized by the number of nodes--Definition \\ref{defn:node} and Figures \\ref{fig:aqm-3-central-0node}, \\ref{fig:aqm-3-central-1node}, and \\ref{fig:aqm-3-central-2nodes} (The more nodes, the faster the wiggle, hence higher momentum).\n\n\\begin{figure}[H]\n\t\\caption{Solving Central Potential Schro\\\"dinger Equation (\\ref{eq:schroedinger:central})}\n\t\\begin{subfigure}[t]{0.45\\textwidth}\n\t\t\\caption{Potential}\\label{fig:aqm-3-central-potential}\n\t\t\\includegraphics[width=\\textwidth]{aqm-3-central-potential}\n\t\\end{subfigure}\n\t\\begin{subfigure}[t]{0.45\\textwidth}\n\t\t\\caption{No nodes}\\label{fig:aqm-3-central-0node}\n\t\t\\includegraphics[width=\\textwidth]{aqm-3-central-0node}\n\t\\end{subfigure}\n\t\\begin{subfigure}[t]{0.45\\textwidth}\n\t\t\\caption{One node}\\label{fig:aqm-3-central-1node}\n\t\t\\includegraphics[width=\\textwidth]{aqm-3-central-1node}\n\t\\end{subfigure}\n\t\\begin{subfigure}[t]{0.45\\textwidth}\n\t\t\\caption{Two nodes}\\label{fig:aqm-3-central-2nodes}\n\t\t\\includegraphics[width=\\textwidth]{aqm-3-central-2node2}\n\t\\end{subfigure}\n\\end{figure}\n\n\\begin{defn}[Node]\\label{defn:node}\n\tA node is a point where the wave function is zero.\n\\end{defn}\n\n\\begin{thm}[Nodes and energy levels]\n\tThe ground state has 0 nodes, the first excited one node, etc.\n\\end{thm}\n\nWhat can we say about energy levels in general? Figure \\ref{fig:degeneracy:hydrogen} plots the number of energy levels against $l$, and plots number of nodes vertically. It exhibits degeneracy. If the energy is too high the electron escapes. The Coulomb potential has a very special feature. It is almost an accident: it is violated by the finite size of the nucleus, by relativistic corrections, by spin. \\emph{The zero node energy for $l=1$ is equal to the 1 node energy for $l=0$, etc}--Figure \\ref{fig:aqm-3-central-coulomb}.\n\n\n\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\caption[Degeneracy of Energy Levels in Hydrogen Atom]{Degeneracy of Energy Levels in Hydrogen Atom. Each $l$ has its own Schro\\\"edinger equation (\\ref{eq:schroedinger:central}), so each $l$ may have its own set of bound solutions. The ground state for $l=0$ has no nodes,  the next state has one node, etc. For $l=1$ the energy of the ground state lies somewhere above the corresponding state for $l=1$. Moreover there are 3 states for each node: the energy levels are degenerate. Similarly for $l=2$ there are 5 states for each node, and the energy levels are higher.}\\label{fig:degeneracy:hydrogen}\n\t\t\\includegraphics[width=0.9\\textwidth]{aqm-3-hydrogen-degeneracy}\n\t\\end{center}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\caption[Energy Levels for the Coulomb Force]{For the Coulomb force \\emph{only}, the energy levels for $l+1$ match those for $l$, shifted up by one. This is an extra degeneracy from a bizarre symmetry. The number of states at each level is  $\\{1,4,9,16,...\\}$}\\label{fig:aqm-3-central-coulomb}\n\t\t\\includegraphics[width=0.8\\textwidth]{aqm-3-central-coulomb}\n\t\\end{center}\n\\end{figure}\n\nReal atoms behave a bit differently.\n\\begin{itemize}\n\t\\item the nucleus has finite size, so at short distances the Coulomb law isn't quite accurate;\n\t\\item Instead of  $\\{1,4,9,16,...\\}$ states at each energy level there are  $\\{2,8,18,32,...\\}$--we have ignored \\emph{spin}.\n\\end{itemize}\n\nAre there always raising an lowering operators? No: only when you are very lucky; physics has been lucky twice. The harmonic oscillator piece of luck is very pervasive, as many things in nature can be well approximated by a harmonic oscillator. For example, go to a higher momentum state of the central force problem, Figure \\ref{fig:aqm-3-central-osc}, and the simplest solution is to treat them as a harmonic oscillator.\n\n\\subsection{Harmonic oscillators}\\label{sect:harmonic:oscillators}\n\n\nEverything in physics that has an equilibrium, if you disturb equilibrium by a small amount, the behaviour can be approximated by a  harmonic oscillator. The model is just a suspended mass $(m=1)$, spring constant $(k=\\omega^2)$\n\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\caption[Model: suspended mass.]{Suspended mass $(m=1)$, spring constant $(k=\\omega^2)$.  $X$ is deviation from equillibrium.}\\label{fig:aqm-3-shm-suspended-mass}\n\t\t\\includegraphics[width=0.8\\textwidth]{aqm-3-shm-suspended-mass}\n\t\\end{center}\n\\end{figure}\n\nClassically:\n\\begin{align*}\n\tH =& \\frac{P^2}{2m} + \\frac{\\omega^2 x^2}{2} \\text{. We'll check with Hamilton's equations}\\\\\n\t \\dot{p}=&\\frac{\\partial H}{\\partial x} \\\\\n\t=& \\dot{x} \\\\\n\t\\dot{x} =& -\\frac{\\partial H}{\\partial p} \\\\\n\t=& - \\omega^2 p \\\\\n\t\\dddot{x} + \\omega^2 x =&0 \\text{, as expected}\n\\end{align*}\n\nQuantum mechanically:\n\\begin{align*}\n\tH =& \\frac{P^2}{2m} + \\frac{\\omega^2 x^2}{2}\\\\\n\t=& \\frac{\\omega}{2 \\omega}\\big(P + i \\omega x \\big)\\big(P - i \\omega x \\big) - \\frac{i \\omega}{2} [x,P] \\text{, since x and p don't commute}\\\\\n\t=& \\frac{\\omega}{2 \\omega}\\big(P + i \\omega x \\big)\\big(P - i \\omega x \\big) + \\underbrace{\\frac{\\hslash \\omega}{2}}_\\text{zero point energy}\\\\\n\t=&\\omega \\frac{\\big(P + i \\omega x \\big)}{\\sqrt{2 \\omega}}\\frac{\\big(P - i \\omega x \\big)}{\\sqrt{2 \\omega}}\n\\end{align*}\n\nClassically both $p=0$ and $x=0$ in the ground state; since the Heisenberg uncertainty principle precludes  $p=0$ and $x=0$, the zero point energy is the minimum possible. We'll drop the ground state energy (zero point energy) for the time being, since it is just an additive constant\\footnote{At the end of lecture \\ref{section:fermions:dirac}, LS mentioned that the zero point energy is involved only in gravitational interactions; elsewhere only the energy \\emph{difference} matters}.\n\nWe'll introduce raising and lowering operators:\n\n\\begin{align*}\n\ta^+ \\triangleq & \\frac{P + i \\omega x } {\\sqrt{2 \\omega}} \\numberthis \\label{eq:creation:operator}\\\\\n\ta^- \\triangleq & \\frac{P - i \\omega x } {\\sqrt{2 \\omega}}\\text{, Hermitean conjugate--$a^-=(a^+)^\\dagger$} \\numberthis \\label{eq:annihilation:operator}\\\\\n\tH =& \\omega a^+ a^-\\text{. We'll take the commutator:}\\numberthis \\label{eq:shM}\\\\\n\t[a^-,a^+] =& \\frac{1}{2\\omega}\\big[P - i \\omega x,P + i \\omega x\\big]\\\\\n\t=& 1\\text{. We also define} \\numberthis \\label{eq:a:comm}\\\\\n\tN \\triangleq& a^+a^-\\text{, so (\\ref{eq:shM}) becomes} \\numberthis \\label{eq:number:operator}\\\\\n\tH =& \\omega N\n\\end{align*}\n$N$ is Hermitian, so it has a complete set of eigenvalues and eigenvectors.\n\n\\begin{align*}\n\tN\\ket{n} =& n\\ket{n} \\text{, we aren't \\emph{assuming} that $n$ is an integer}\\\\\n\ta^+a^-\\ket{n} =& n\\ket{n}\\\\\n\ta^+(a^-a^+ - a^+a^-)\\ket{n} =& a^+\\ket{n}\\text{, using (\\ref{eq:a:comm})}\\\\\n\ta^+a^-a^+ \\ket{n} - a^+\\underbrace{a^+a^- \\ket{n}}_\\text{$ n\\ket{n}$} =& a^+\\ket{n}\\\\\n\t\\underbrace{a^+a^-}_\\text{$N$}a^+ \\ket{n} =& n a^+\\ket{n} + a^+\\ket{n}\\\\\n\tN a^+ \\ket{n} =& (n+1) a^+ \\ket{n}\n\\end{align*}\n\nSo $a^+$ acts as raising operator, and we can show $a^-$ is lowering.  Since the Hamiltonian is positive we can't ever get negative energy, so there must be a lowest energy state, $0$--Figure \\ref{fig:aqm-3-spectrum}. In QM there is a theorem that all the eigenvalues of $MM^\\dagger$ are positive or zero, for any operator $M$. \n\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\caption[Energy Spectrum for Harmonic Oscillator]{Energy Spectrum for Harmonic Oscillator. $a^+$ takes energy up one level, and $a^-$ down, except for $a^-\\ket{0}$=0.}\\label{fig:aqm-3-spectrum}\n\t\t\\includegraphics[width=0.8\\textwidth]{aqm-3-spectrum}\n\t\\end{center}\n\\end{figure}\nWe will see (Theorem \\ref{thm:norm:harmonic}) the appropriate normalization gives:\n\\begin{align*}\n\ta^+\\ket{n} =& \\sqrt{n+1}\\ket{n+1}\\\\\n\ta^-\\ket{n} =& \\sqrt{n}\\ket{n-1}\n\\end{align*}\n \n\\section{Spin}\n\n\\subsection{Harmonic oscillators(continued)}\n\nHarmonic oscillators are ubiquitous. Any time a system has an equilibrium, there can be oscillations about equilibrium. An oscillator can oscillate at different frequencies simultaneously (harmonics)--e.g. a violin string. We will be particularly interested in oscillations in an electromagnetic field.  For example, if you have radiation in a cavity, there will be a variety of oscillations. What is the equilibrium? No electromagnetic field, i.e. vacuum is the equilibrium for electromagnetic field. Give it a knock, e.g. microwaves, and there will be oscillations.\n\nIn a crystal, the oscillations of one atom affect its neighbours, so we have a field. The quanta are called phonons.\n\nIn Section \\ref{sect:harmonic:oscillators} we found:\n\\begin{align*}\n\tH =& \\frac{P^2}{2m} + \\frac{\\omega^2 x^2}{2} \\text{, and we defined}\\\\\n\ta^\\pm=& \\frac{q \\pm i \\omega x}{\\sqrt{2 \\omega}} \\text{, raising and lowering operators}\\\\\n\t[a^-,a^+]=& 1\\\\\n\tN =& a^+a^- \\text{, whence}\\\\\n\tH =& \\omega(N+\\frac{1}{2})\n\\end{align*}\n\nWe will find ground state by solving the Schr\\\"odinger equation.\n\\begin{align*}\n\t\\ket{\\psi} \\rightarrow& \\psi_0(x) \\text{, in thr ground state}\\\\\n\tX \\rightarrow& x. \\text{, multiplication}\\\\\n\tP \\rightarrow& -i \\frac{d}{dx}\n\\end{align*}\n\n\nWe know that there has to be a ground state. We can't use $a^-$ indefinitely; since $H$ is positive, there can be no negative eigenvalues. So $\\exists \\ket{0}$ such that: \n\\begin{align*}\n\ta^-\\ket{0}=&0\\\\\n\tN\\ket{0}=&a^+a^- \\ket{0 }\\\\\n\t=& a^+0\\\\\n\t=&0\n\\end{align*}\n\nNB $\\ket{0} \\ne 0$. $\\ket{0}$ is a vector which can be normalized; $0$ is a vector of length 0.\nApplying the transformations given above, we get the time independent Schr\\\"odinger equation.\n\\begin{align*}\n\t-\\frac{1}{2}\\frac{d^2 \\psi(x)}{dx^2} + \\omega^2 x^2 \\psi(x)=& E\\psi(x)\n\\end{align*}\n\n There are solutions for all $E$, but the solutions are not normalizable unless E is in the spectrum, Figure \\ref{fig:aqm-3-spectrum}. So we impose the condition $\\braket{\\psi|\\psi}=1$, or:\n\\begin{align*}\n\t\\int_{-\\infty}^{\\infty} dx \\psi^*(x) \\psi(x) =& 1 \\text{. We know that}\\\\\n\ta^-\\ket{0}=& 0 \\text{, whence}\\\\\n\t\\big(-i \\frac{d}{dx} - i \\omega x \\big)\\psi_0(x) =& 0 \\text{. Write}\\\\\n\t\\psi(x)=&e^{f(x)} \\text{, then}\\\\\n\t\\psi^\\prime(x) =&f^\\prime e^{f(x)}\\\\\n\ti \\big[f^\\prime  + \\omega x\\big]e^{f(x)} =&0\\\\\n\tf(x) =& -\\frac{\\omega x^2}{2}+C\\\\\n\t\\psi_0(x) =& e^{-\\frac{\\omega x^2}{2}} \\text{, not normalized.}\n\\end{align*}\n\nWe can then use $a^+$  to generate excited states.\n\\begin{align*}\n\t\\ket{1}=& a^+ \\ket{0} \\text{, or, in the Schro\\\"edinger representation:}\\\\\n\t\\psi_1(x) =& \\big(-i \\frac{d}{dx} + i \\omega x \\big) e^{-\\frac{\\omega x^2}{2}}\\\\\n\t=& 2 i \\omega e^{-\\frac{\\omega x^2}{2}}\n\\end{align*}\n\nThis is an odd function (antisymmetric)--Figure \\ref{fig:wave:harmonic}. It has one node.\n\nFigure \\ref{fig:wave:harmonic} shows how higher levels have more wiggles (momentum) and are away from origin (the particle is more likely to be far away) most of time.\n\n\\begin{figure}[H]\n\t\\caption{Wave functions for harmonic oscillator}\\label{fig:wave:harmonic}\n\t\\includegraphics[width=0.9\\textwidth]{harmonic_wavefunction}\n\\end{figure}\n\nTo see classical behaviour, superpose states to create wave packets. Time dependent looks like classical oscillator, especially at high energy (energy larger that ground state).\n\n\n\n\\subsection{Spin}\n\nSome particles have half-integral spin, e.g. electron or proton. At rest they have no orbital rotation, no $\\vec{r}\\times\\vec{p}$, only spin. Spin is a kind of angular momentum that is attached to a particle. You can think of it as an abstract quantity or as a tiny thing that is literally spinning. It transforms under rotation as angular momentum does. Spin has two states, up or down, left or right, in or out. The thing that characterizes angular momentum is having three components, which can be represented by matrices satisfying (\\ref{eq:lx_ly}), (\\ref{eq:ly_lz}), and (\\ref{eq:lz_lx}). These are closely related to the commutation relations of the Pauli matrices (we will work in the representation of the $z$ component of the spin):\n\n\\begin{align*}\n\t\\sigma_z =& \\begin{pmatrix}\n\t\t1 & 0 \\\\\n\t\t0 & -1\\\\\n\t\\end{pmatrix} \\\\\n\t\\sigma_x =& \\begin{pmatrix}\n\t\t0 & 1 \\\\\n\t\t1 & 0\\\\\n\t\\end{pmatrix}\\\\\n\t\\sigma_y =& \\begin{pmatrix}\n\t\t0 & -i \\\\\n\t\ti & 0\\\\\n\t\\end{pmatrix}\n\\end{align*}\n\nThe Pauli matrices are Hermitian. We define:\n\n\\begin{align*}\n\t\\vec{s} =& \\frac{\\vec{\\sigma}}{2} \n\\end{align*}\n\nWe can show the $s_i$ satisfy (\\ref{eq:lx_ly}), (\\ref{eq:ly_lz}), and (\\ref{eq:lz_lx}).\n\n\\begin{align*}\n\t[s_x,s_y] =& i s_z \\\\\n\t[s_y,s_z] =& i s_x\\\\\n\t[s_z,s_x] =& i s_y\n\\end{align*}\nSo the Pauli matrices, operating on 2D vectors, represent a simple angular momentum system, which is attached to the particles. Now we can ask about eigenvalues and eigenvectors. The Eigenvalues of $s_z$ are $\\pm \\frac{1}{2}$. \n\nIn Figures \\ref{fig:aqm-2-3a} and \\ref{fig:aqm-2-3b} we saw there were two possibilities for the spectrum of angular momentum, integral and half integral spins. We could have \\emph{guessed} the Pauli matrices by noticing the spin ${-\\frac{1}{2},\\frac{1}{2}}$ case. Note: there are spin $0$ particles, such as the Higgs, and the deuteron. We will largely focus on spin $\\frac{1}{2}$ particles.\n\nWe define $J$, the total angular momentum:\n\\begin{align*}\n\tJ=&L+s \\text{, where $L$ denotes the orbital angular momentum $\\vec{r}\\times\\vec{P}$}\n\\end{align*}\n\nThere are QM rules for adding angular momenta, which we won't cover in this lecture.\n\n\nThe first experimental background came from spectroscopy and the periodic table. The goal of this lecture is to see how periodic table emerges from spin. Pauli realized spin was needed.\n\n$L^2=l(l+1)$. We look at the energy levels of hydrogen --see Figure \\ref{fig:degeneracy:hydrogen}. There is a bunch of states for $l=0$, for zero nodes($n=0$), 1 node, etc. For $l=1$ there are $2l+1=3$ states for each node, and ground state for $l=1$ has more energy than ground state for $l=0$, because it has angular momentum.\n\nFigure \\ref{fig:aqm-3-central-coulomb} shows the coincidence that the  energy for  for one value of $l$ matches that $l-1$, except that energies are shifted in $n$: $E(n,l)$ satisfies $E(n,l+1)=E(n+1,l)$. So the number of states for each n is 1, 4, 9, 16, ...\n\nThe Helium nucleus has twice the charge of the hydrogen nucleus, so electrons are pulled in tighter, but the structure of Figure \\ref{fig:aqm-3-central-coulomb}  is preserved for a Helium ion (negative). Put another electron in: we can put 2 electrons into ground state; if we try to create an ion with 3 electrons, one goes into first excited state! \n\n\\subsection{Pauli exclusion principle}\n\nPauli exclusion principle: no two electrons can ever get into the same state. But we can put 2 electrons into ground state. Pauli said there was a new property with two values, up and down.\n\nLithium has 3 electrons, 2 in ground state, 3rd in 1st excited state. There is room for 8 states in first excited level, if we allow for spin. This explains 2nd row of periodic table. The fact that spin was angular momentum was checked with magnetic field (split energy levels).\n\nPauli's Exclusion Principle is a \\emph{postulate} of non-relativistic QM, but a \\emph{consequence} of relativistic QM. There are two kinds of particles: ones that satisfy Pauli's Exclusion Principle (Fermions), and those that don't (Bosons).\n\nIn statistical mechanics, how do we handle identical particles? Imagine that we are putting particles into boxes (real or phase space). In Figure \\ref{fig:aqm-4-particles-boxen} we can imagine each particle having a name painted in \"classical paint\", so they are distinct. Or we can treat them as absolutely identical, so we usually count as if they were identical. In quantum mechanics, however, identical  particles are indistinguishable.\n\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\caption[Configurations Particles in Boxes]{Configurations Particles in Boxes: if we exchange labels, do we count as separate configurations?}\\label{fig:aqm-4-particles-boxen}\n\t\t\\includegraphics[width=0.6\\textwidth]{aqm-4-particles-boxen}\n\t\\end{center}\n\\end{figure}\n\nConsider two particles, forgetting spin.\n\\begin{align*}\n\t\\psi(x) =& \\braket{x|\\psi}\\\\\n\t\\psi(x_1,x_2) =& \\braket{x_1x_2|\\psi}\\text{, two particles}\\\\\n\t\\psi(x_1,x_2) \\rightarrow & \\psi(x_2,x_1)\\text{, swap using operator $S$}\\\\\n\tS\\ket{x1,x2} =& \\ket{x2,x1}\\\\\n\tS^2 =& 1\n\\end{align*}\n\n$S$ is unitary, so eigenvalues are $\\pm1$.\n\n\\section{Fermions: a tale of two minus signs}\n\n\nWe'll review the chemistry that went into the discovery of spin, and the Fermionic character of electrons. The Fermionic character implies two things that are related:\n\\begin{itemize}\n\t\\item spin of electron is half spin $\\pm \\frac{1}{2}$\n\t\\item the electron satisfies the Pauli Exclusion Principle.\n\\end{itemize} \n\nWe can put 2 electrons into the ground state only because of spin. NB, the 2 electrons in Helium are \\textit{entangled}.\n\nPhotons don't have an exclusion principle; in fact they have a tendency to congregate.\n \nCan we have spin $\\frac{1}{2}$ particles that don't obey Pauli exclusion principle, or a spin integer that does obey Pauli exclusion principle? No. Can show this from quantum field theory.\n\nThis lecture is a tale of two minus signs, one from exchange--Section \\ref{section:swap},  the other from spin--Section \\ref{section:spin}.\n\n\\subsection{Swapping particles}\\label{section:swap}\n\nThe Pauli Exclusion Principle is deeper than simply saying that you cannot put two particles into the same state. It is actually a statement about multi particle wave functions. Let's forget about spin for the moment.\n\nConsider wave function of positions for multiple particles, e.g. $\\ket{x_1,x_2,x_3}$. Then $\\braket{x_1,...x_n|\\psi}=\\psi(x_1,...x_n)$, and $\\psi^*(x_1,...x_n)\\psi(x_1,...x_n)$ is the probability that the system is in state $\\ket{x_1,...x_n}$. We ask whether $\\psi(x_1,x_2,...x_n)$ is the same as $\\psi(x_2,x_1,...x_n)$, or, equivalently, whether the upper configuration in Figure \\ref{fig:aqm-4-states} is the same as the lower one. All experiments and theory agree that they are the same state: $\\ket{x1,x2}=\\ket{x2,x1}$ .\n\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\caption{Is the upper configuration the same as the lower one?}\\label{fig:aqm-4-states}\n\t\t\\includegraphics[width=0.8\\textwidth]{aqm-4-states}\n\t\\end{center}\n\\end{figure}\n\nOn the other hand, the physical properties of a state do not depend on the overall phase. We can't say that $\\ket{x_1, x_2}=\\ket{x_2, x_1}$, as there may be a phase $e^{i\\phi}$.\n\\begin{align*}\n\t\\ket{x_1, x_2}=&\\ket{x_2, x_1}e^{i\\phi}\\text{, interchange twice--there are two possibilities}\\\\\n\t\\ket{x_1, x_2}=&+\\ket{x_2, x_1}\\text{ Bosons}\\\\\n\t\\ket{x_1, x_2}=&-\\ket{x_2, x_1}\\text{ Fermions}\n\\end{align*}\n\nNB: sign is not observable.\n\n\\begin{table}[H]\n\t\\begin{center}\n\t\t\\caption{Wave functions for Fermions and Bosons}\n\t\t\t\\begin{tabular}{|l| c| c|} \\hline \n\t\t\t\tWave function&Fermions&Bosons \\\\ \\hline \n\t\t\t\t$\\psi(x_1,x_2)=-\\psi(x_2,x_1)$&OK&not OK\\\\ \\hline\n\t\t\t\t$\\psi(x_1,x_2)=\\psi(x_2,x_1)$&not OK& OK\\\\ \\hline\n\t\t\t\t$\\psi_0(x_1)\\psi_0(x_2)$&not OK& OK\\\\ \\hline\n\t\t\t\t$\\psi_0(x_1)\\psi_1(x_2)$&not OK& not OK\\\\ \\hline\n\t\t\t\t$\\psi_0(x_1)\\psi_1(x_2)+\\psi_0(x_2)\\psi_1(x_1)$&not OK& OK\\\\ \\hline\n\t\t\t\t$\\psi_0(x_1)\\psi_1(x_2)-\\psi_0(x_2)\\psi_1(x_1)$&OK&not OK \\\\ \\hline\n\t\t\\end{tabular}\n\t\\end{center}\n\\end{table}\n\nWhen there is spin we can think of the wave function as a function of position and spin--$\\psi(x,\\sigma_z)$ and $\\psi(x1,\\sigma_1,x2,\\sigma_2,...)$. You cannot put two Fermions into the same state.\n\n\\subsection{Spin}\\label{section:spin}\n\nRotation by $2\\pi$ is a mathematical process that you might expect to do nothing. Let's consider a wave function for one particle $\\psi(x,\\sigma)$ and rotate the coordinate system or the particle. What happens when you rotate a system with a given angular momentum by an angle about any axis--$R(\\theta)2\\pi$? What about $R(2\\pi)2\\pi$? Surely this leaves the system unchanged? But the system is analogous to swapping particles--Section \\ref{section:swap}. If all we want is for the probabilities and expectation to be preserved, perhaps the rotations introduce a phase--$\\pm1$.\n\nConsider the generator of rotations:\n\\begin{align*}\n\tJ_z\\ket{\\psi} =& -i \\frac{\\partial \\ket{\\psi}}{\\partial \\theta}\n\\end{align*}\nImagine that angular momentum about $z$ has a definite value, so $\\ket{\\psi}$ is an eigenvector.\n\\begin{align*}\n\tJ_z\\ket{\\psi}=& m\\ket{\\psi} \\text{, which is easily solved.}\\\\\n\t\\ket{\\psi(\\theta)} =& e^{im\\theta}\\ket{\\psi(0)}\n\\end{align*}\n\nBut, from the commutation relations\\footnote{See discussion preceding Figure \\ref{fig:spectrum_Lz}} we know that  $m$ integral or half integral (in 3D, not 2D).\nWhat if $m$ half integral and we rotate by $2\\pi$? We have phase of $-1$, so $\\psi$ changes sign. Fermions follow $-1$, Bosons $+1$. Of course rotation by  $4\\pi$ does give the identity.\n\nLeonard Susskind demonstrated that $2\\pi\\ne0$:\n\\begin{itemize}\n\t\\item Gerard 't Hooft Coffee Cup--Figure \\ref{fig:thooft:coffee_cup} \n\t\\item Dirac sphere in a box\n\\end{itemize}\nIn each case we are following a path in rotation space.\n\n\\begin{figure}[H]\n\t\\caption{The Gerard 't Hooft Coffee Cup trick}\\label{fig:thooft:coffee_cup}\n\t\\begin{subfigure}{0.45\\textwidth}\n\t\t\\caption{Starting the first rotation}\n\t\t\\includegraphics[width=\\textwidth]{aqm-5-coffee-cup1}\n\t\\end{subfigure}\n\t\\begin{subfigure}{0.45\\textwidth}\n\t\t\\caption{$2\\pi$: That is not the identity: let me tell you I'm quite certain that is not the identity!}\n\t\t\\includegraphics[width=\\textwidth]{aqm-5-coffee-cup2}\n\t\\end{subfigure}\n\t\\begin{subfigure}{0.45\\textwidth}\n\t\t\\caption{Staring the 2nd rotation}\n\t\t\\includegraphics[width=\\textwidth]{aqm-5-coffee-cup3}\n\t\\end{subfigure}\n\t\\begin{subfigure}{0.45\\textwidth}\n\t\t\\caption{$4\\pi$: that is the identity}\n\t\t\\includegraphics[width=\\textwidth]{aqm-5-coffee-cup4}\n\t\\end{subfigure}\n\\end{figure}\n\n\\begin{itemize}\n\t\\item The wave function for two fermions changes sign when we swap them;\n\t\\item The wave function for a single fermion changes sign when we rotate by $2\\pi$.\n\\end{itemize}\n\n\\subsection{The connection between interchange and rotation}\n\nIs there a connection between interchange and rotation? Yes: it was discovered by David Finkelstein. \n\n\\begin{figure}[H]\n\t\\caption[The David Finkelstein Belt Trick]{The David Finkelstein Belt Trick: A rotation by $2\\pi$, plus an exchange, gives an untwisted belt}\n\t\\begin{subfigure}[t]{0.5\\textwidth}\n\t\t\\caption{Exchange of the two loops}\n\t\t\\includegraphics[width=\\textwidth]{aqm-5-belt-exchange}\n\t\\end{subfigure}\n\t\\begin{subfigure}[t]{0.5\\textwidth}\n\t\t\\caption{Turn around and we see 2 rotations instead}\n\t\t\\includegraphics[width=\\textwidth]{aqm-5-belt-rotation}\n\t\\end{subfigure}\n\t\\begin{subfigure}[t]{0.24\\textwidth}\n\t\t\\caption{Not a possible configuration from twisting a belt}\n\t\t\\includegraphics[width=\\textwidth]{aqm-5-belt-illegal}\n\t\\end{subfigure}\n\t\\begin{subfigure}[t]{0.24\\textwidth}\n\t\t\\caption{The twist makes it legal: you can pull it apart to get the topologically trivial configuration.}\n\t\t\\includegraphics[width=\\textwidth]{aqm-5-belt-legal}\n\t\\end{subfigure}\n\t\\begin{subfigure}[t]{0.24\\textwidth}\n\t\t\\caption{Add time, and create two pairs of particles at bottom}\\label{fig:aqm-5-belt-legal-time}\n\t\t\\includegraphics[width=\\textwidth]{aqm-5-belt-legal-time}\n\t\\end{subfigure}\n\t\\begin{subfigure}[t]{0.24\\textwidth}\n\t\t\\caption{Rotate one particle, and switch two of them. The switch and rotate give the same configuration}\\label{fig:belt_switch:rotate}\n\t\t\\includegraphics[width=\\textwidth]{aqm-5-belt-switch-rotate}\n\t\\end{subfigure}\n\\end{figure}\n\n\nThis shows the deep topological connection between rotation and interchange.\n\nImagine that I have two particles. I take one at rotate it by $2\\pi$, then I switch two of them. Then, regardless of whether they are Fermions or Bosons, doing nothing is equivalent to doing a rotation and an exchange--Figure \\ref{fig:belt_switch:rotate} (this isn't the way Pauli did it).\n\nThis would not make sense if particles were eternal. Quantum Field Theory allows particles to be created. We start with no particles, then create particle-antiparticle pairs--Figure \\ref{fig:aqm-5-belt-legal-time}. Do whatever it takes to create particles out of nothing. As time goes on, at the same time we rotate one particle and exchange the two negative ones. Topologically this is equivalent to just creating the two particles and not doing anything.\n\nThe spin statistics theorem is more general than the version Pauli proved. It is also true for solitons. A soliton is (solitary wave) is a lump of field (Finkelstein, Rubinstein). Its true for lumps of stuff in condensed matter physics, for manifolds, for all kinds of things where Pauli's argument doesn't apply.\n\n\nAssume field is mostly zero, but there are lumps. The spin statistics theorem says that there are two kinds of lumps: those whose wave function changes sign when rotated, and those where it doesn't change--Figure \\ref{fig:lump:antilump}--Fermions and Bosons.\n\n\\begin{figure}[H]\n\t\\caption{Annihilation of lumps and anti-lumps}\\label{fig:lump:antilump}\n\t\\begin{subfigure}{0.3\\textwidth}\n\t\t\\caption{Blue and black lumps}\n\t\t\\includegraphics[width=\\textwidth]{aqm-5-lumps}\n\t\\end{subfigure}\n\t\\begin{subfigure}{0.3\\textwidth}\n\t\t\\caption{Mirror image}\n\t\t\\includegraphics[width=\\textwidth]{aqm-5-anti-lumps}\n\t\\end{subfigure}\n\t\\begin{subfigure}{0.3\\textwidth}\n\t\t\\caption{Bring together - black lumps annihilated}\n\t\t\\includegraphics[width=\\textwidth]{aqm-5-partially-annihilated}\n\t\\end{subfigure}\n\\end{figure}\n\nIs there a way to observe the change in phase of a Fermion?\n\nLet's start with a experiment where you wouldn't see anything. Put electron in a cavity with a magnetic field, \\emph{slowly} rotate box, release, and generate interference pattern--Figure \\ref{fig:aqm-5-expt1}. Compare with another experiment where we don't rotate: the interference pattern won't show any differences--Figure \\ref{fig:aqm-5-expt-beam-splitter}. Now use a beam splitter, and we see interference from the $2\\pi$ rotation (we don't know which box contains electron: don't look!).\n\nRepeat with a beam splitter\n\\begin{figure}[H]\n\t\\caption {An experiment to observe the change in phase of a Fermion}\n\t\\begin{subfigure}[t]{0.3\\textwidth}\n\t\t\\caption{Two experiments, with an without \\emph{slow} rotation}\\label{fig:aqm-5-expt1}\n\t\t\\includegraphics[width=\\textwidth]{aqm-5-expt1}\n\t\\end{subfigure}\n\t\\begin{subfigure}[t]{0.3\\textwidth}\n\t\t\\caption{Experiment with beam splitter: one electron, but waves are split. One box \\emph{only} rotates. $\\psi_1(x)-\\psi_2(x)\\ne\\psi_1(x)+\\psi_2(x)$}\\label{fig:aqm-5-expt-beam-splitter}\n\t\t\\includegraphics[width=\\textwidth]{aqm-5-expt-beam-splitter}\n\t\\end{subfigure}\n\t\\begin{subfigure}[t]{0.3\\textwidth}\n\t\t\\caption{Detail of actual experiment. Magnetic field used to rotate spin, tuned so rotation is $2\\pi$}\n\t\t\\includegraphics[width=\\textwidth]{aqm-5-expt-actual}\n\t\\end{subfigure}\n\\end{figure}\n\n\n\n\\section{Quantum Field Theory}\n\nWe are entering today into the world of Quantum Field Theory. Quantum Field Theory is the description of nature as we know it, with the exception of gravity. In principle we believe that we could explain everything, except gravity, if we only had enough computational power. Of course problems tend to be too complicated. We can understand hydrogen, but boron is already too complicated, and human beings are much too complicated. Nevertheless, apart from gravity, Quantum Field Theory seems to be all there is. Today we will study second qunatization.\n\n\\subsection{Review and Generalization of Harmonic Oscillator}\nThe Harmonic Oscillator is the central mathematical object that goes into Quantum Field Theory. We need to understand it well.\nWe are interested in the algebra of the operators $a^+$, $a^-$ and $N$.\n\nImagine many (possibly infinite number) harmonic oscillators. Think of each oscillator  as an independent system of degrees of freedom, each with its own frequency.\n\nFrom (\\ref{eq:creation:operator}) and (\\ref{eq:annihilation:operator}):\n\\begin{align*}\n\ta^+_i \\triangleq & \\frac{P + i \\omega x } {\\sqrt{2 \\omega}} \\text{, raising or creation operator} \\numberthis \\label{eq:creation:operator:i}\\\\\n\ta^-_i \\triangleq & \\frac{P - i \\omega x } {\\sqrt{2 \\omega}}\\text{, lowering or annihilation operator} \\numberthis \\label{eq:annihilation:operator_i}\\\\\n\ta^-\\ket{0} =& \\vec{0}\\\\\n\tN_i\\triangleq& a^+_i a^-_i \\text{, number operator--this is what goes into Hamiltonian} \n\\end{align*}\n\n We can compute the commutators from  (\\ref{eq:a:comm}) and (\\ref{eq:number:operator}), and use the fact that oscillators $i$ and $j$ are independent (if two measurements don't commute, they can not be measured simultaneously - i.e. they are not independent). \n\n\\begin{align*}\n\t[a^+_i,a^+_j] =& 0 \\numberthis \\label{eq:a:comm_i_plus}\\\\\n\t[a^-_i,a^-_j] =& 0 \\numberthis \\label{eq:a:comm_i_minus}\\\\\n\t[a^-_i,a^+_i] =& \\delta_{i,j} \\numberthis \\label{eq:a:comm_i}\\\\\n\tH =& \\hslash \\sum_{i}  \\omega_i N_i\\text{: the $N_i$ are known as \\emph{occupation numbers}.}\n\\end{align*}\nWe're ignoring ground state energy, as it is just an additive constant, and plays no role.\n\nHow do we label states? For one oscillator we have the occupation number. One way to specify a basis of states is to write the occupation number for each oscillator--$\\ket{n_1,n_2,n_3,...}$. One example where we need an infinite number of oscillators is an idealized violin string.\n\n\\begin{thm}[Normalization of harmonic oscillator state--creation]\\label{thm:norm:harmonic}\n\t\\begin{align*}\n\t\t\\braket{m|n}=&\\delta_{m,n} \\numberthis \\label{eq:norm}\\\\\n\t\t\\implies&\\\\\n\t\ta^+\\ket{n}=&\\sqrt{n+1}\\ket{n+1}\n\t\\end{align*}\n\\end{thm} \n\n\\begin{proof}\n\t\\begin{align*}\n\t\ta^+\\ket{n}=&c_n\\ket{n+1} \\text{, for the eigenvector $\\ket{n}$ and some $c_n$}\\\\\n\t\t\\bra{n}a^-=&c_n\\bra{n+1}\\text{, wlog assume $c_n$ real}\\\\\n\t\t\\braket{n|a^-a^+|n}=&c_n^2\\text{, from (ref{eq:norm})}\\\\\n\t\t=& \\braket{n|a^+a^-+1|n}\\text{, using (\\ref{eq:a:comm_i})}\\\\\n\t\t=& \\braket{n|N+1|n} \\text{, from (\\ref{eq:number:operator})}\\\\\n\t\t=&n+1 \\text{, whence}\\\\\n\t\tc_n=&\\sqrt{n+1}\n\t\\end{align*}\n\\end{proof}\n\n\\begin{thm}[Normalization of harmonic oscillator state--annihilation]\\label{thm:norm:a-}\n\t\\begin{align*}\n\t\ta^-\\ket{n}=\\sqrt{n}\\ket{n-1}\n\t\\end{align*}\n\\end{thm}\n\n\\begin{proof}\n\t\\begin{align*}\n\t\ta^-\\ket{n}=&c^\\prime_n\\ket{n-1} \\text{, for the eigenvector $\\ket{n}$ and some $c_n$}\\\\\n\t\t\\bra{n}a^+=&c^\\prime_n\\bra{n-1} \\text{, wlog assume $c_n$ real}\\\\\n\t\t\\bra{n}a^+a^-\\ket{n}=&(c^\\prime_n)^2\\bra{n-1}\\ket{n-1}\\\\\n\t\t\\bra{n}N\\ket{n}=&(c^\\prime_n)^2 \\text{, from (\\ref{eq:number:operator})}\\\\\n\t\tn=&(c^\\prime_n)^2\n\t\\end{align*}\n\\end{proof}\n\n\\begin{cor}[Annihilation of ground state]\n\t\\begin{align*}\n\t\ta^-\\ket{0} =& \\vec{0}\n\t\\end{align*}\n\\end{cor}\n\n\\begin{proof}\n\tIn the proof of Theorem \\ref{thm:norm:a-}, $c^\\prime_n=0$.\n\\end{proof}\n\n\\begin{cor}[Creation operator acting on vector]\n\t\\begin{align*}\n\t\ta_i^+\\ket{n_1,n_2,...n_i,..}=&\\sqrt{n_i+1}\\ket{n_1,n_2,...n_i+1,...}\n\t\\end{align*}\n\\end{cor}\n\n\\subsection{Non-relativistic Quantum Field Theory of Bosons}\n\nParticles are described by wave functions, which are functions of position, and sort od look like fields. Fields are degrees of freedom that depend on position and time, but we'll focus on position and freeze time for a while. The wave function of a particle, $\\psi(x)$, the state vector in the position representation, is a function of position, but it isn't \"the field\". For one thing $\\psi(x)$ is not Hermitian, hence it is not an observable; we observe position, momentum, angular momentum, etc, but not $\\psi$.\n\\begin{enumerate}\n\t\\item $\\psi$ is not an observable;\n\t\\item for multiple particles, $\\psi$ is a function of all positions--$\\psi(x_1,x_2)$\n\t\\item $\\psi(x_1,x_2,...x_n)$ describes the state of a \\emph{fixed number of particles}.\n\\end{enumerate}\n\n That is not the idea of a quantum field. We want a quantity $\\Psi$ such that:\n\n\\begin{enumerate}\n\t\\item $\\Psi$ is an observable, e.g. magnetic field, so it is an operator, not a state;\n\t\\item $\\Psi$ function of one position;\n\t\\item $\\Psi$ describes a system of any number of particles (even if number of particles changes).\n\\end{enumerate}\n\nEach field $\\Psi$ corresponds to a particular type of particle: for this lecture we mean bosons.\n\nA question was asked about using $i$ to label states. Let's go back to single particle quantum mechanics. For simplicity consider one particle in a box, whose potential energy stops it getting out of the box. Since there's only one particles we don't need to worry about bosons versus fermions. Let's think about energy eigenstates. They are wave functions, and the lowest eigenstate $\\psi_1(x)$ will be sine (lowest energy level)--Figure \\ref{fig:aqm-6-sine}. Next $\\psi_2(x)$ has one node, with higher energy, $\\psi_3(x)$ two nodes,...\n\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\caption[Wave function of 1-particle system in a box]{Wave function of 1-particle system in a box: $\\psi_1(x)$, $\\psi_2(x)$,..., using non standard notation where $i$ stands for the number of nodes plus 1. NB: this is not the same $i$ as used in (\\ref{eq:creation:operator:i}).}\\label{fig:aqm-6-sine}\n\t\t\\includegraphics[width=0.6\\textwidth]{aqm-6-sine}\n\t\\end{center}\n\\end{figure}\n\nNow imagine that we have many particles (bosons), some in state 1 (first energy level), some in second,..., which we will write: $\\ket{n1,n2,n3,...}$. This is identical to the way we labelled states in a multi-oscillator system (We couldn't do this for Fermions!).  Because this is a complete parallel, we can \\emph{invent} operators as in (\\ref{eq:a:comm_i_plus}) - (\\ref{eq:a:comm_i}) to \\emph{literally} create and remove particles. NB $\\set{1,2,3,...}$ are states, $\\set{n_i}$ occupation numbers.\n\n\\begin{align*}\n\ta_1^+\\ket{n_1,n_2,...} =& \\sqrt{n_1+1} \\ket{n_1+1,n_2,...}\n\\end{align*}\nWe had a question about the physical significance of the square root. We know that\n\\begin{align*}\n\ta^+a^-\\ket{n} = n \\ket{n} \\numberthis \\label{eq:creator:annihil}\n\\end{align*}\nso it is reasonable to expect a square root to be associated with each operator. However, we can do better. Suppose that we don't know (\\ref{eq:creator:annihil}), but we did know about commutator and square root.\n\n\\begin{align*}\n\t(a^+a^-)\\ket{n}=&(a^-a^+-1)\\ket{n}\\\\\n\t=&\\sqrt{n+1}a^-\\ket{n+1}-\\ket{n}\\\\\n\t=&(\\sqrt{n+1})^2\\ket{n}-\\ket{n}\\\\\n\t=&(n+1)\\ket{n}-\\ket{n}\\\\\n\t=&n\\ket{n} \\text{, which is  (\\ref{eq:creator:annihil})}\n\\end{align*}\n\nNB: we are \\emph{defining} creation and annihilation operators. Don't ask \\emph{why} for a definition, \\emph{ask why it is useful}. E.g. our definition of creation is useful because we want to explore systems where the number of particles may change. It lets us create a photon, and annihilation lets us absorb particles.\n\n\\begin{defn}[Vacuum]\n\tVacuum is the state that is annihilated by all annihilation operators: $a^-$ -- $\\ket{0,0,0,....}$.\n\\end{defn}\n\nDenote energy by $\\omega_i$ for state $i$. \n\n\\begin{align*}\n\tE =& \\sum_{i} n_i \\omega_i\\\\\n\t=& \\sum_{i} \\omega_i \\underbrace{ a^+_i a^-_i}_\\text{$N_i$} \n\\end{align*}\nYou can think of this two ways:\n\\begin{itemize}\n\t\\item oscillator energies;\n\t\\item sum of all particles.\n\\end{itemize}\n\nWe are inventing something that is a bunch of oscillators.\n\\begin{itemize}\n\t\\item a violin string is a bunch of oscillators;\n\t\\item radiation in a cavity is a bunch of oscillators.\n\\end{itemize}\nWe are building up an idea of collections of particles as harmonic oscillators; soon enough we'll see the connection with fields.\n\nWe'll consider free particles--no interactions.\n\nWhy can we ignore ground-state energy? Because constants commute with everything. \n\nQuantum field theory is a book-keeping device for keeping track of many particles that come and go.\n\n\\subsubsection{Digression on History of  Quantum Field Theory }\n\\begin{itemize}\n\t\\item Faraday invented Field Theory.\n\t\\item Maxwell invented modern Field Equations (there had been wave eqiations before him).\n\t\\item Planck introduced $\\hslash$ (realized classical field theory not enough). He quantized the oscillators in cavity of black body: he didn't realize that field had to be quantized.\n\t\\item Einstein realized field had to be quantized.\n\t\\item Heisenberg, Pauli, Dirac put it all together around 1928.\n\t\\item particle creation via harmonic oscillator? Maybe Dirac.\n\\end{itemize}\n\nQuanta are the things that occupy the Occupation Numbers: if the field is the electromagnetic field we call the quanta photons.\n\n\\subsubsection{Quantum Field Theory resumed}\n$\\Psi(x)$ -- an operator that is a function of position--one operator for each position. It acts on a space of states $\\{\\ket{n_1,n_2,...n_i,...}\\}$, known as \\emph{Fock Space}--\\cite{wiki:fock}.\n\n\\begin{align*}\n\t\\Psi(x)\\triangleq&\\sum_{i}a^-_i\\psi_i(x)\\text{, not Hermitean, so conjugate is}\\\\\n\t\\Psi^\\dagger(x)=&\\sum_{i}a^+_i\\psi_i^*(x)\\\\\n\t\\Psi(x)+\\Psi^\\dagger \\text{ is}&\\text{ Hermitean}\n\\end{align*}\n\nIf the $\\psi$ were in the momentum representation, the coefficients would resemble Fourier coefficients. They are the quantum version of Fourier coefficients. \n\nWhat if we apply $\\Psi^\\dagger$ to vacuum? $\\Psi(x)$ annihilates it--what about $\\Psi(x)^\\dagger$.\n\n\\begin{align*}\n\t\\sum_{i} \\ket{i} \\bra{i} =& I \\text{, sum over one particle states with $\\psi_i$}\\\\\n\\sum_{i} \\ket{i} \\braket{i|X} =& \\ket{X} \\text{, state where particles known to be at $X$. But}\\\\\n\t\\braket{i|X}=&\\psi^*(X) \\text{, so we can write:}\\\\\n\t\\psi^*_i(x)\\ket{i} =& \\ket{x}\\text{ one particle in state $i$ at $x$. But}\\\\\n\t\\ket{i} =& a^+_i\\ket{0} \\text{, using $a^+_i$ to create the particle. Whence}\\\\\n\t\\psi^*_i(x) a^+_i\\ket{0}=&\\ket{x}\\\\\n\t\\Psi^\\dagger(x) \\ket{0} =& \\ket{x}\\text{ so $\\Psi^\\dagger(x)$ creates a particle at $x$.}\n\\end{align*}\n\n\\begin{itemize}\n\t\\item $a^+_i$ creates a particle in state $i$.\n\t\\item $\\Psi^\\dagger(x)$  creates a particle at position $x$.\n\t\\item $a^-_i$ annihilates a particle in state $i$, or gives zero.\n\t\\item $\\Psi(x)$  annihilates a particle at position $x$, or gives zero.\n\\end{itemize}\n\nThere is a separate field for each Boson.\n\nAdd vacuum to a state, we get probability of 0.5 of vacuum, 0.5 of original state. It is not the same as zero. Vacuum has length of 1!\n\nLet's make a two particle state, at $x$ and $y$. \n \n\\begin{align*}\n\t\\Psi^\\dagger(y)\\Psi^\\dagger(y)\\ket{0} =& \\ket{y,x}\\\\\n\t\\Psi^\\dagger(x)\\Psi^\\dagger(y)\\ket{0} =& \\ket{x,y} \\text{, but from (\\ref {eq:a:comm_i_plus})}\\\\\n\t\\Psi^\\dagger(y)\\Psi^\\dagger(x) =& \\Psi^\\dagger(x)\\Psi^\\dagger(y) \\text{, so}\\\\\n\t\\ket{x,y} =& \\ket{y,x} \\text{, which is the defining property of Bosons.} \n\\end{align*}\n\nA given quantum field describes one type of Boson. There are two types of field for photons, as there are two polarizations. There is a separate field for each type of particle.\n\nWe can handle situation where number of particles is a random variable: a laser wave is a superposition of different number of photons.\n\n\\section{Quantum Field Theory II}\n\n\\subsection{Review construction of a simple quantum field}\n\nThe trick of introducing fields from particles can be done in two ways. We can start with particles and reconstruct why they can be described by fields, or start with wave fields and work out why they have quanta. Starting with particles we can describe 1 particle, 2 particles, etc, then move on to a variable number of particles. We'll start with one single type of particle. Number of photons in room changes constantly. A neuron can decay into a proton, an electron, and a neutrino. We can't rely on quantum mechanics of a single particle: we need to invent fields.\n\nWe will start with single particle quantum mechanics, a state vector $\\ket{\\psi}$. We can construct the inner product $\\bra{x}\\ket{\\psi}=\\psi(x)$ and the probability density $\\psi^*(x) \\psi(x)$.  Normalization: $\\int \\psi^*(x) \\psi(x) dx=1$ gives \\textit{number of particles}: this isn't very interesting since we had only one particle to begin with.\n\nWe next introduced some a particle states that form an orthonormal basis. There are many ways to do this. For instance the x-states form an orthonormal basis. The eigenvectors of any Hermitian operator will form a basis. In particular the energy eigenstates of the particles in a box--Figure \\ref{fig:aqm-6-sine} form an orthonormal basis. \n\\begin{align*}\n\t\t\\int d(x) \\psi^*_i(x) \\psi_j(x) =& \\delta_{i,j} \\numberthis \\label{eq:orthog:psi}\n\\end{align*}\nNow we have another useful little manipulation. \n\n\\begin{thm}[Construction of delta function from orthonormal basis]\\label{thm:orthonormal}\n\tFor any orthonormal basis, $\\psi_i$, and any $x$ and $y$:\n\t\\begin{align*}\n\t\t\\delta(x-y)=& \\sum_{i} \\psi_i(y) \\psi^*_i(x)\n\t\\end{align*}\n\\end{thm}\n\n\\begin{proof}\n\t\\begin{align*}\n\t\t\\sum_{i} \\ket{i} \\bra{i} =& I \\text{. For any $x$ and $y$}\\\\\n\t\t\\braket{y|x}=& \\sum_{i} \\braket{y|i} \\braket{i|x}\\\\\n\t\t=& \\sum_{i} \\psi_i(y) \\psi^*_i(x) \\text{, but}\\\\\n\t\t\\braket{y|x}=&\\delta(x-y) \\text{, whence}\\\\\n\t\t\\delta(x-y)=& \\sum_{i} \\psi_i(y) \\psi^*_i(x)\n\t\\end{align*}\n\\end{proof}\n\nThis is true for any set of eigenvectors of any Hermitian operator.\n\nNow we move on to problem of studying many particles at the same time. How are we going to characterize a state? One set of states that is particularly useful is to say how many there are for each energy level. Characterize by the occupation numbers,  $\\ket{n_1, n_2,...n_i,...}$. These don't belong in the same vector space s the single particle wave functions. Do not confuse the single particle states with these more general structures. We use the same notation merely because nobody has invented anything that works better than Dirac's bras and kets.\n\nWe want to change the numbers of particles, i.e. increase and decrease occupation numbers. We introduce an oscillator for each $i$: this has nothing to do with oscillation, it is just a bookkeeping trick. We introduce creation and annihilation operators, $a^+_i$ and $a^-_i$, and make them behave the same as the oscillator creation and annihilation operators. They are often written slightly differently.\n\n\\begin{itemize}\n\t\\item $a^+_i=a^\\dagger_i$\n\t\\item $a^-_i=a_i$\n\\end{itemize} \n\nWe will find it convenient to introduce the field operator, which operates on Fock space.\n\\begin{align*}\n\t\\Psi(x) \\triangleq & \\sum_{i} a_i \\psi_i(x)\\\\\n\t\\Psi^\\dagger(x) \\triangleq& \\sum_{i} a^\\dagger_i \\psi^*_i(x)\n\\end{align*}\n\n\\begin{itemize}\n\t\\item These would be Fourier transforms if sine/cosine waves, except they are operator values, not numeric.\n\t\\item $\\Psi(x)$ and $\\Psi^\\dagger(x)$ are not Hermitian.\n\\end{itemize}\n\nThe following are Hermitian, and, hence, observable:\n\\begin{align*}\n\t\\Psi(x) + \\Psi^\\dagger(x) \\\\\n\t\\frac{\\Psi(x) - \\Psi^\\dagger(x)}{i}\n\\end{align*}\nBut right now we aren't observing them, just using them as bookkeeping devices.\n\nWe will now look at a different interpretation of $\\Psi(x)$. What does it do when it operates on the vacuum, the Fock space state where all the occupation numbers are zero: $\\ket{0} = \\ket{0,0,0,.....}$? We'll write down the following formula.\n\n\\begin{align*}\n\t\\ket{x}=&\\sum_{i}\\ket{i}\\braket{i|x}\\text{ \"resolution of the identity\". Now}\\\\\n\t\\ket{i}=&a^\\dagger_i\\ket{0} \\text{, i.e. a state with one particle in $i^{th}$ energy level, and}\\\\\n\t\\braket{i|x}=&\\psi_i(x) \\text{, so}\\\\\n\t\\ket{x}=& \\sum_i \\psi^*_i(x)a^\\dagger_i\\ket{0}\\\\\n\t=& \\Psi^\\dagger(x) \\ket{0}\n\\end{align*} \n\nSo $\\Psi^\\dagger(x)$ is the operator that creates, out of the vacuum, a particle with position $x$.\n\n\\begin{itemize}\n\t\\item $a^\\dagger_i$ creates particles with definite energy;\n\t\\item $\\Psi^\\dagger$ creates particles at definite locations.\n\\end{itemize}\n\nDirac introduced the following terminology:\n\\begin{itemize}\n\t\\item c-number (an ordinary number) commutes with everything;\n\t\\item q-number (quantum operator \"number\") does not always commute.\n\\end{itemize}\n\n\\subsection{Some illustrative calculations}\nWe will now see what we can do with the  $\\Psi$ and  $\\Psi^\\dagger$ operators.\n\n\\subsubsection{Density of particles}\n\nThe operator $\\int dx \\Psi^\\dagger(x) \\Psi(x)$ is interesting: it is not the same as $\\int dx \\psi^\\dagger(x) \\psi(x)$ (operator vs wave function). What does it do?\n\\begin{align*}\n\t\\int dx \\Psi^\\dagger(x) \\Psi(x)=&\\int dx \\sum_{i,j}a^+_i\\psi_i^*(x) a_j\\psi_j(x) \\text{, expanding using definition of $\\Psi$ and $\\Psi^\\dagger$}\\\\\n\t=&\\sum_{i,j} a^+_i a_j \\int dx \\psi_i^*(x) \\psi_j(x)\\\\\n\t=&\\sum_{i,j} a^+_i a_j \\delta_{i,j} \\text{, from (\\ref{eq:orthog:psi})}\\\\\n\t=&\\sum_i a^+_i a_i \\text{. Now we use (\\ref{eq:number:operator})}\\\\\n\t=&\\sum_i N_i \\text{, total number of particles.}\n\\end{align*}\nSo $\\int dx \\Psi^\\dagger(x) \\Psi(x)$ is the operator representing total number of particles. Will it be finite, since there are infinitely many $i$s? Unless the total energy is insanely high, the $N_i$ must fall off quickly. To make energy finite, total number of particles must be finite. $\\Psi^\\dagger(x) \\Psi(x)$ represents particle density\\footnote{The measured value is not necessarily the probability; usually will be within $\\sqrt{n}$ of probability.}, since its integral is the total number.\n\nNow  $\\Psi^\\dagger(x) \\Psi(x)$ is an observable, so we can measure it.  To measure we integrate over a small volume, and ask how many particles are there. Like any observable it has states: you can measure and get a variety of answers.\n\n$\\{\\ket{n_1,n_2,...n_i,...}\\}$ is not the most general state: it is a basis. We can superpose to get the most general state.\n\n\n\\subsubsection{Total Energy}\nWe now determine the operator that gives the total energy. We'll assume that particles don't interact. This works for dilute particles. Even photons will interact if they are dense enough (we can't get this density in the laboratory.)\n\n\\begin{align*}\n\tE =& \\sum_{i} N_i \\omega_i \\text{ sum over all modes, i.e. single particle states}\\\\\n\t=& \\sum_{i} a^\\dagger_i a_i \\omega_i\n\\end{align*}\n\nWe determine $\\omega_i$ from eigenvalues of the time independent Schr\\\"odinger equation (ignoring interactions). Particles may interact with $V$, but not with each other.\n\\begin{align*}\n\tH \\psi_i =& \\omega_i \\psi_i\\\\\n\t\\big[\\frac{p^2}{2m} + V(x)\\big]\\psi_i(x)=& \\omega_i \\psi_i(x)\\\\\n\t\\big[-\\frac{\\nabla^2}{2m} + V(x)\\big]\\psi_i(x)=& \\omega_i \\psi_i(x) \\numberthis \\label{eq:schroedinger:psi}\n\\end{align*}\n\nWe will guess the solution. Start with the observation that the expectation of the energy for one particle is given by:\n\\begin{align*}\n\t\\braket{\\psi | H | \\psi} =& \\big[-\\frac{\\nabla^2}{2m} + V(x)\\big]\\psi_i(x)\n\\end{align*}\n\nThis suggests:\n\\begin{thm}[Energy of multi-particle system]\n\t\\begin{align*}\n\t\tE=&\\int dx \\Psi^\\dagger(x) \\big[-\\frac{\\nabla^2}{2m} + V(x)\\big] \\Psi(x)\n\t\\end{align*}\n\\end{thm}\n\n\\begin{proof}\n\t\\begin{align*}\n\t\t&\\int dx \\underbrace{\\Psi^\\dagger(x) \\big[-\\frac{\\nabla^2}{2m} + V(x)\\big] \\Psi(x)}_\\text{energy density} \\\\\n\t\t=& \\int dx \\sum_{i,j}a^+_i\\psi_i^*(x)\\big[-\\frac{\\nabla^2}{2m} + V(x)\\big]\\psi_j(x)a^-_j\\\\\n\t\t=& \\int dx \\sum_{i,j} a^+_i a^-_j \\psi_i^*(x) \\omega_j \\psi_j(x) \\text{, from (\\ref{eq:schroedinger:psi})}\\\\\n\t\t=& \\sum_{i,j} a^+_i a^-_j \\delta_{i,j} \\omega_j \\text{, since $\\{\\psi_i\\}$ form an orthonormal basis} \\\\\n\t\t=& \\sum_{i} a^+_i a^-_i  \\omega_i\\\\\n\t\t=& \\sum_i N_i \\omega_i\n\t\\end{align*}\n\\end{proof}\n\nNotes:\n\\begin{itemize}\n\t\\item We can recover single particle QM from QFT: just go to states where total number of particles is one.\n\t\\item Behaves like classical theory if the number of particles in same state is very large. E.g. expectations follow  laws of classical particles.\n\t\\item If we don't split too many hairs,square of electromagnetic field is qualitatively related to density of photons.\n\\end{itemize}\n\nYou can imagine how confused everybody was before Dirac put it all together. People were confused by $psi$, which they thought was a field, like the electromagnetic field. Some thought it was just an auxiliary device for computing probabilities. If that was what is was, how was it connected with electromagnetic field? What was connection between particles and fields. The Scr\\\"odinger equation looked a but like Maxwell's equations. But Maxwell's equations were not anything to do with probability amplitudes: they concerned measurable value of the field. But there was a connection, as the photons were quanta of the field. QFT is the resolution of that confusion.  \n\nFor electromagnetic field:\n\\begin{align*}\n\t\\vec{\\Psi} =& \\vec{E} + i \\vec{B}\\\\\n\t\\vec{\\Psi^*} =& \\vec{E} - i \\vec{B}\\\\\n\t\\vec{\\Psi} \\vec{\\Psi^*} =&\\text{ energy density of photons: $E^2+B^2$}\n\\end{align*}\nDensity of photons isn't a good concept, but energy density is.\n\n\\section {Second Quantization}\n\n\\subsection{Digression on neutrinos}\n\nIf neutrinos have mass, and they mix, do they have the same mass? No. So how to mix and conserve energy?\n\nMass is energy. The eigenstates of energy are linear superpositions of eigenstates of something else, \\emph{the type of neutrino}. The eigenstates of energy don't mix with each other, but they are mixtures themselves.\n\n\\subsubsection{A simple example}\n\nHere is simple example. Imagine a particle trapped in the potential of Figure \\ref{fig:aqm-7-potential}, and let's suppose for the sake of argument that the middle barrier very high, so, to a good approximation, particle is trapped on one side or t'other (ignore tunnelling). So we can treat particle as being on the left, say. In Figure \\ref{fig:particle_mixed_left} we treat the barrier as a brick wall and ask what is the ground state. We might say that Figure \\ref{fig:particle_mixed_left} shows the ground state: it has no nodes, is as smooth as possible, and has an energy, $E$. But there must be a second ground state, from symmetry--Figure \\ref{fig:double:well}, with the same energy. These are two states that have apparently the same energy--except they don't. The two wave functions in Figure  \\ref{fig:double:well} are not exactly eigenstates of the energy.\n\n\\begin{figure}[H]\n\t\\caption{Double well potential with very high barrier}\n\t\\begin{subfigure}{0.3\\textwidth}\n\t\t\\caption{Double well potential}\\label{fig:aqm-7-potential}\n\t\t\\includegraphics[width=0.8\\textwidth]{aqm-7-potential}\n\t\\end{subfigure}\n\t\\begin{subfigure}{0.3\\textwidth}\n\t\t\\caption{One \"ground state\"}\\label{fig:particle_mixed_left}\n\t\t\\includegraphics[width=0.8\\textwidth]{particle_mixed_left}\n\t\\end{subfigure}\n\t\\begin{subfigure}{0.3\\textwidth}\n\t\t\\caption{Two \"ground states\"}\\label{fig:double:well}\n\t\t\\includegraphics[width=0.8\\textwidth]{particle_mixed}\n\t\\end{subfigure}\n\\end{figure}\n\nWe know that for a potential like Figure \\ref{fig:aqm-7-potential} the eigenstates are either symmetric or antisymmetric functions.\n\n\\begin{thm}[If $V$ is an even function, $\\psi$ is either even or odd.]\n\tIf  $\\psi$  is a continuously differentiable solution to the time independent Schr\\\"odinger equation\n\t\\begin{align*}\n\t-\\frac{\\hslash^2}{2m}\\frac{d^2 \\psi(x)}{d x^2} + V(x)\\psi(x) =& E\\psi(x) \\text{ and}\\numberthis \\label{eq:ti:schroedinger}\\\\\n\t\\forall x V(-x) =& V(x) \\numberthis \\label{eq:even_V}\\\\\n\t\\text{then}&\\text{ either}\\\\\n\t\\psi(x) =& \\psi(x)\\text{, or}\\\\\n\t\\psi(x) =& \\psi(-x)\n\t\\end{align*}\n\\end{thm}\n\n\\begin{proof}\n\tDefine an operator $R$ (reflection in time) such that:\n\t\\begin{align*}\n\t\tR \\ket{\\psi} =& \\ket{\\psi^{\\prime}} \\text{, where} \\numberthis \\label{eq:reflection}\\\\\n\t\t\\psi^{\\prime}(x) =& \\psi(-x)\n\t\\end{align*}\n\t\n\t(\\ref{eq:even_V}) $\\implies RV=V$, and $\\psi^{\\prime}$ satisfies (\\ref{eq:ti:schroedinger}), whence:\n\t\n\t\\begin{align*}\n\t\\psi^{\\prime}(x) =& \\rho \\psi(x) \\text{, for some constant $\\rho$.} \\numberthis \\label{eq:R:rho}\n\t\\end{align*}\n\tWLOG we can assume that $\\psi$ and $\\psi^{\\prime}$ are both normalized, whence:\n\t\\begin{align*}\n\t\t\\lvert \\rho \\rvert = 1& \\text{, so (\\ref{eq:reflection}) and (\\ref{eq:R:rho}) give:}\\\\\n\t\tR \\ket{\\psi} =& \\rho \\ket{\\psi} \\text{. But (\\ref{eq:reflection}) implies}\\\\\n\t\tR^2    =& I \\text{, whence}\\\\\n\t\t\\rho^2 =& 1 \\text{, i.e.}\\\\\n\t\t\\rho \\pm& 1 \\text{, so, in any interval where $\\psi(x)\\ne 0$ \\emph{either}}\\\\\n\t\t\\psi(x) =& \\psi(-x) \\text{\\emph{or}}\\\\\n\t\t\\psi(x) =& -\\psi(-x)\n\t\\end{align*}\n\tWe still need to rule out the possibility that $\\rho$ changes sign at a zero. Let $x_0$ be a point such that $\\psi(x_0)=0$, and, WLOG, assume that $\\psi(x)=\\psi^{\\prime}(x)$ in some interval up to $x_0-$ and $\\psi(x)=-\\psi^{\\prime}(x)$ in some interval starting $x_0+$. Since $\\psi$ is continuously differentiable: then $\\frac{\\psi^{\\prime}(x_0-)}{dx}=\\frac{\\psi^(x_0-)}{dx}$. Now define $\\psi^{\\prime\\prime} \\triangleq \\big(\\psi^{\\prime}-\\psi\\big)$: $\\psi^{\\prime\\prime}$ satisfies (\\ref{eq:ti:schroedinger}), $\\psi^{\\prime\\prime}(x_0)=0$, and $\\frac{\\psi^{\\prime\\prime}(x_0-)}{dx}=0$, whence $\\psi^{\\prime\\prime}=0 \\forall x$. \n\\end{proof}\n\nBut neither LHS or RHS wave function of Figure \\ref{fig:double:well} symmetric or antisymmetric. Can make symmetric or antisymmetric combinations. Figure \\ref{fig:double:well:symmetrized} has slightly lower energy than Figure \\ref{fig:double:well}: it is the true ground state\\footnote{Remember that sign of wave function doesn't matter}. Figure \\ref{fig:double:well:1st} shows first excited state: it's energy is ever so slightly larger that a wave function constrained to be on one side.\n\n\\begin{figure}[H]\n\t\\caption{Wave functions for Figure \\ref{fig:double:well}}\n\t\\begin{subfigure}{0.45\\textwidth}\n\t\t\t\\caption{Wave function symmetrized(minimum in middle is slightly greater than zero-allow tunnelling)}\\label{fig:double:well:symmetrized}\n\t\t\t\\includegraphics[width=0.8\\textwidth]{particle_mixed_symmetrized}\n\t\\end{subfigure}\n\t\\begin{subfigure}{0.45\\textwidth}\n\t\t\\caption{First excited state}\\label{fig:double:well:1st}\n\t\t\\includegraphics[width=0.8\\textwidth]{particle_mixed_1st_excited}\n\t\\end{subfigure}\n\\end{figure}\n\n\nSo we mix the pure states from Figures \\ref{fig:double:well:symmetrized} and \\ref{fig:double:well:1st}. Let's start with electron on left, and evolve.\n\\begin{align*}\n\t\\frac{\\psi_L+\\psi_R}{\\sqrt{2}}& \\text{--symmetric, with energy }& E_1-\\epsilon\\\\\n\t\\frac{\\psi_L-\\psi_R}{\\sqrt{2}}& \\text{--antisymmetric, with energy }& E_1+\\epsilon\n\\end{align*}\nWhat if we put a particle on the left? How does it evolve? Each is an eigenvector, so they evolve as follows:\n\\begin{align*}\n\t\\frac{\\psi_L+\\psi_R}{\\sqrt{2}} e^{(E_1-\\epsilon)t}=&\\psi^+ \\text{, say}\\\\\n\t\\frac{\\psi_L-\\psi_R}{\\sqrt{2}}e^{(E_1+\\epsilon)t}=&\\psi^-\n\\end{align*}\n\nNow what if we start with pure $\\psi_L$?\n\\begin{align*}\n\t\\psi_L =& \\frac{\\psi^+ + \\psi^-}{\\sqrt{2}}\\text{, then the denominator evolves as}\\\\\n\t\\psi_L^\\prime =&\\psi^+ e^{(E_1-\\epsilon)t} + \\psi^- e^{(E_1+\\epsilon)t}\\\\\n\t=&e^{E_1 t}\\big[\\psi^+ e^{-\\epsilon t} + \\psi^- e^{+\\epsilon t}\\big]\n\\end{align*}\nSigns change with time, so eventually they will be opposite.\n\\begin{align*}\n\te^{-\\epsilon t} =& - e^{\\epsilon t}\\\\\n\te^{2 \\epsilon t}=&-1\\\\\n\t2 \\epsilon t = \\pi\n\\end{align*}\nSo $\\psi_L$ becomes $\\psi_R$!\n\n\\subsubsection{Neutrinos}\n\nThe phenomenon of mixing goes with the phenomenon of oscillation. Neutrinos behave  like that: \n\\begin{itemize}\n\t\\item the analog of the left wave function is the neutrino that is made when a particle decays to an electron plus a neutrino;\n\t\\item the analog of the right wave function is the neutrino that is made when a particle decays to a muon plus a neutrino.\n\\end{itemize}\nThe real eigenstate of the energy is a linear combination of the muon and electron neutrino. When a neutrino is made, it is either in a state of an electron neutrino or a muon neutrino. If you wait a while it will change to the other state.\n--electron neutrino changes to muon neutrino.\nNow the neutrino can be scattered, and produce an electron (from electron neutrino) or a muon. But wait a while and see what is produced: electron neutrino becomes muon neutrino, and can produce muons. This type of neutrino will oscillate! If you have a very long baseline you'll see the oscillations\n\nWhat controls size of $\\epsilon$? All sorts of details, mass of particle, height of barrier, width of barrier. It is extremely sensitive. \n\nThe neutrino masses are the energy levels. They start small, but mixing splits the energy a bit. There is no barrier; there is a coupling in the Hamiltonian which, for whatever reason takes an electron neutrino to a muon neutrino and vice versa. In Figure \\ref{fig:double:well} the coupling is due to tunnelling.\n\nAmmonia has a tetrahedral shape--Figure \\ref{fig:aqm-8-nh3}. The Nitrogen likes to sit a certain distance of the base of the triangle (energy lowest). But there is another state which is symmetric, with Nitrogen below: $N$ tunnels through $H_3$ plane. \n\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\caption{Ammonia has a tetrahedral shape}\\label{fig:aqm-8-nh3}\n\t\t\\includegraphics[width=0.5\\textwidth]{aqm-8-nh3}\n\t\\end{center}\n\\end{figure}\n\nWe've also seen this with spins. Without any magnetic field up and down have the same energy. Now apply a weak magnetic field--Figure \\ref{fig:aqm-8-spins-lr}. What are the eigenstates? Left, and right. But these are just linear combinations of up and down.\n\\begin{align*}\n\t\\ket{l} = \\frac{1}{\\sqrt{2}}\\big[\\ket{u} + \\ket{v}\\big]\\\\\n\t\\ket{r} = \\frac{1}{\\sqrt{2}}\\big[\\ket{u} - \\ket{v}\\big]\n\\end{align*}\nThe eigenstates have slightly different energy because of the magnetic field: we have the same situation with slightly different energy levels. What happens if we start the electron up? It precesses, moving between down and up. There is no tunnelling, just a term in the Hamiltonian. \n\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\caption{Spins in a weak magnetic field}\\label{fig:aqm-8-spins-lr}\n\t\t\\includegraphics[width=0.5\\textwidth]{aqm-8-spins-lr}\n\t\\end{center}\n\\end{figure}\n\nIf there is something that an up electron can do, and down can't, and vice version, we can create the electron as an up, and later do an experiment to see whether it is behaving like a down.\n\nThe strength of field only controls speed of precession. The analogue of the magnetic field is the mixing of the neutrinos: this is a very small parameter, and we don't know where it came from. It doesn't fit into the Standard Model.\n\nNeutrino oscillation: the energy is also affected by spin.\n\nThis is believed to be the explanation of the deficit of solar neutrinos: by the time they get here, some have transformed.\n\n\\subsubsection{Scientific American Article on whether electron is a sphere}\n\nWhat would it mean for the electron to be a sphere?\n\nWhat was measured was the electric dipole moment, the charge times the distance between them, and it represents an off centred distribution. The centre of the dumbbell is the centre. For a charge distribution not to have a dipole does not mean that it is a sphere. A charge distribution can have many multipole moments. What kind of shape corresponds to a dipole? One with an imbalance of charge. We could have a distribution shaped like an oblate spheroid, or any kind of ellipsoid. This would not have a dipole moment, because it is uniformly distributed about any plane passing through centre. It might have a quadrapole moment, or an octopole moment.\n\nIn quantum mechanics there is something odd about  the notion of spherical symmetry. Figure \\ref{fig:aqm-8-qm-dumbbell} depicts a quantum dumbbell.\n\\begin{figure}[H]\n\t\\caption{Quantum Dumbbells and electric dipoles}\n\t\\begin{subfigure}[t]{0.3\\textwidth}\n\t\t\\caption{Quantum Dumbbell - e.g. a molecule}\\label{fig:aqm-8-qm-dumbbell}\n\t\t\\includegraphics[width=\\textwidth]{aqm-8-qm-dumbbell}\n\t\\end{subfigure}\n\t\\begin{subfigure}[t]{0.3\\textwidth}\n\t\t\\caption{Quantum Dumbbell - e.g. a molecule}\\label{fig:aqm-8-qm-dumbbell-superposition}\n\t\t\\includegraphics[width=\\textwidth]{aqm-8-qm-dumbbell-superposition}\n\t\\end{subfigure}\n\t\\begin{subfigure}[t]{0.3\\textwidth}\n\t\t\\caption{Spinning electron, showing hypothetical imbalance of charge.}\\label{fig:aqm-8-electron-spin}\n\t\t\\includegraphics[width=\\textwidth]{aqm-8-electron-spin}\n\t\\end{subfigure}\n\\end{figure}\nLet's take the ground state of the molecule, which is described by its angular momentum about the centre (ignore vibrations). If molecule is a boson, the ground state will have angular momentum $0$: wave function is completely symmetric for all rotations. So, independent of shape of molecule, the ground state is rotationally symmetric. Maybe it is a superposition of states, such as Figure \\ref{fig:aqm-8-qm-dumbbell-superposition}, so wave function is symmetrized. Does Figure \\ref{fig:aqm-8-qm-dumbbell-superposition} have a dipole moment? Answer is ambiguous, depending on the experiment.\n\\begin{itemize}\n\t\\item Take a sudden quick snapshot; we'd discover it was lopsided with dipole moment. How fast does camera have to be? What resolution do we need? Snapshot measures angle; system would be in a state of definite orientation, so can't measure angular momentum (Heisenberg).\n\t\\item What is energy of first excited state? What if it is enormous? More than we have in our photons. Then apparatus cannot resolve angle. We measure average: a sphere. Mesons are also (smaller) dumbbells. Kicking it into first excited state is huge compared to ordinary photons. All we can mesaud=sure shows it is a sphere on average.\n\\end{itemize}\n\nQuestion of whether it a sphere or not is confusing.\n\nBosons can have spin zero, but electrons can't. They have an axis--Figure \\ref{fig:aqm-8-electron-spin}. Given that direction, is there a charge imbalance?\n\nWhat did they measure? Once you know that electron has an axis, we can ask whether there is an imbalance (small compared to overall negative charge--e.g. move charge from centre). Is there an imbalance as shown in Figure \\ref{fig:aqm-8-electron-spin}? Is there a correlation between electrical charge displacement and the magnetic direction? This is what would be called the electric dipole moment of the electron.\n\nSome symmetries forbid electric dipole moment, e.g. reflection symmetry. If the mirror image of an electron is another electron. Figure \\ref{fig:aqm-8-mirror-image} shows that reflection doesn't preserve relationship between dipole and field direction. So, \\emph{if the laws of physics don't distinguish between left hand and right hand}, there is no dipole moment.\n\n\\begin{figure}[H]\n\t\\caption{Symmetries and dipoles}\n\t\\begin{subfigure}[t]{0.45\\textwidth}\n\t\t\\caption[Mirror image of an electron]{Mirror image of an electron. Magnetic field has same directions, since it comes from spinning charge, but charge imbalance is reversed.}\\label{fig:aqm-8-mirror-image}\n\t\t\\includegraphics[width=0.8\\textwidth]{aqm-8-mirror-image}\n\t\\end{subfigure}\n\t\\begin{subfigure}[t]{0.45\\textwidth}\n\t\t\\caption[Mirror image of an electron]{Mirror image of an electron. Magnetic field has same directions, since it comes from spinning charge, but charge imbalance is reversed.}\\label{fig:aqm-8-time-reversal}\n\t\t\\includegraphics[width=0.8\\textwidth]{aqm-8-time-reversal}\n\t\\end{subfigure}\n\\end{figure}\n\nBut the laws of physics do distinguish between left hand and right hand (e.g. neutrinos). But there another more accurate symmetry, time reversal.  Figure \\ref{aqm-8-time-reversal} shows the direction of spin being reversed, hence the magnetic filed reversed, but the charge distribution is unchanged. So time reversal would preclude a dipole, if it is a good symmetry of nature.\n\nBut time reversal is not a good symmetry of nature, either.\n\nStandard Model predicts a very small dipole moment that is too small to detect. Experiment has failed to detect dipole moment.\n\n\\url{https://youtu.be/7G4C7scQX3A?t=4380}\n\n\\subsection{Second Quantization of Bosons}\n How are fields connected with Fourier transforms? In ordinary QM we have wave functions; in the position representation, and the squares define probabilities of the particle being at a particular point. We can Fourier transform the wave functions, and the transform is the representation in momentum space.\n\n\n\\begin{align*}\n\t\\psi(x) \\rightarrow& \\psi^*(x)\\psi(x)=&P(x) \\text{ in position representation}\\\\\n\t\\widetilde{\\psi}(p) \\rightarrow& \\widetilde{\\psi}^*(p) \\widetilde{\\psi}(p) =&P(p) \\text{ in momentum representation, where}\\\\\n\t\\widetilde{\\psi}(p) =& \\int \\frac{dx}{\\sqrt{2\\pi}} \\psi(x) e^{-i p x}\\\\\n\t\\psi(x) =& \\int \\frac{dp}{\\sqrt{2\\pi}} \\widetilde{\\psi}(p) e^{+i p x}\n\\end{align*}\n\nNow let's go to field theory, with creation and annihilation operators.\n\n\\begin{align*}\n\t\\Psi(x) =& \\sum_{i} a^-_i \\psi_i(x)\\\\\n\t\\psi_i(x) =& e^{ipx} \\text{ for a free particle (different $i$!), so} \\\\\n\t\\Psi(x)=& \\int \\frac{dp}{\\underbrace{\\sqrt{2\\pi}}_\\text{by convention}} a^-(p) e^{ipx} \\text{, where annihilation operator}\n\\end{align*}\nThe momentum states are now represented by a continuous parameter, $p$, not a discrete $i$. Moreover $a^-(p)$  removes 1 particle with momentum $p$: it plays same role as $\\widetilde{\\psi}(p)$. If there is no particle to remove, $a^-(p)$ annihilates the state.\n\\begin{align*}\n\t\\Psi^\\dagger(x)=& \\int \\frac{dp}{\\sqrt{2\\pi}} a^+(p) e^{ipx} \\text{ creates particle at position $x$}\n\\end{align*}\nThere is a similarity between wave functions in position and momentum space and creation and annihilation operators for particles and given position or momentum. And we can invert the equations.\n\\begin{align*}\n\ta^-(p) = \\int \\frac{dx}{\\sqrt{2\\pi}} \\Psi(x) e^{-ipx}\\\\\n\ta^+(p) = \\int \\frac{dx}{\\sqrt{2\\pi}} \\Psi^\\dagger(x) e^{ipx}\n\\end{align*}\n\nRemember there is a field operator for each kind of particle.\n\nIf we recall the commutators:\n\\begin{align*}\n\t[a^+_i,a^-_j] =& \\delta_{i,j}\\\\\n\t[a^+_i,a^+_j] =& 0\\\\\n\t[a^-_i,a^-_j] =& \n\\end{align*}\nWe can prove the following.\n \n\\begin{align*}\n\t[\\Psi^+(x),\\Psi^-(y)] =& \\delta(x-y) \\text{, introduces Heisenberg uncertainty!}\\\\\n\t[\\Psi^+(x),\\Psi^+(y)] =&0 \\\\\n\t[\\Psi^-(x),\\Psi^-(y)] =&0\\\\\n\t[\\Psi^+_R(x),\\Psi^-_I(y)] =& \\delta(x-y) \\text{, can not measure simultaneously at same point!}\n\\end{align*}\n\nMakes sense in relativity: if measuring field at one point kicked value at a distant point, it would violate causality/locality. If there is a spacelike separation between measurements one cannot affect another!\n\nFermions don't work like this! One measurement can kick another arbitrarily far away. This sounds crazy--or there is no way to measure a Fermion Field.\n\n\\section{Quantum Field Hamiltonian}\n\n\n\n\\subsection{Particle Field Interactions}\n\nIn the previous lectures we talked about Quantum Fields, the quanta of those fields, the creation and annihilation operators, and examined the Hamiltonian for a very simple field--non-interacting particles satisfying Schr\\\"odinger's equation. The second term counts particles, giving each energy $V(x)$.\\footnote{We are not restricted to 3D: x may be a vector.}\n\\begin{align*}\n\tH =& \\int dx \\big[ \\Psi^\\dagger(x) \\big[\\frac{- \\nabla^2}{2m} \\Psi(x) \\big]+ V(x) \\Psi^\\dagger(x) \\Psi(x) \\big] \n\\end{align*}\n$\\Psi^\\dagger(x) \\Psi(x)$ represents the density of particles at $x$, so $\\Psi^\\dagger(x) \\Psi(x) V(x)$ counts particles at $x$, and gives each one energy $V(x)$.\n\nWe restrict to the special case of constant potential energy\n\\begin{align*}\nH=&\\int dx \\big[\\Psi^\\dagger(x) \\big(\\frac{- \\nabla^2}{2m} \\Psi(x)\\big) + mc^2 \\Psi^\\dagger(x) \\Psi(x)\\big]  \\numberthis\\label{eq:psi_mc2}\n\\end{align*}\n\nEach particle has energy $mc^2$.\n\nHow do we see from (\\ref{eq:psi_mc2}) that momentum is conserved?\n\nThe Hamiltonian updates state, $\\phi$, say.\n\n\\begin{align*}\n\t\\ket{\\phi(t+\\epsilon)} =& (1-i \\epsilon H) \\ket{\\phi(t)} \\text{State}\\\\\n\t=& \\ket{\\phi(t)} -i \\epsilon H \\ket{\\phi(t)} \\numberthis \\label{eq:update:state}\n\\end{align*}\n\nWhat would it mean to say momentum is conserved? It means Hamiltonian, when it acts on a state with definite momentum, doesn't change momentum. Whatever the Hamiltonian does, if it acts on a state with given momentum, it must give back the same momentum, \\emph{if momentum is conserved.}  Let's see how this works with (\\ref{eq:psi_mc2}). Rewrite 2nd term  using momentum variables (Fourier transform).\n\n\\begin{align*}\n\t\\Psi(x) =& \\int \\frac{dp}{\\sqrt{2\\pi}} \\underbrace{ \\widetilde{\\Psi}(p)}_\\text{annihilation operator} e^{ipx}\\\\\n\t\\Psi^\\dagger (x) =& \\int \\frac{dp}{\\sqrt{2\\pi}} \\underbrace{ \\widetilde{\\Psi}(p)}_\\text{creation operator} e^{-ipx} \\numberthis \\label{eq:psi:dagger}\n\\end{align*}\n The factor is actually $\\big(\\frac{1}{\\sqrt{2\\pi}}\\big)^n$ where $n$ is number of dimensions.\n\\begin{align*}\n\t\\int dx \\big(mc^2\\big) \\Psi^\\dagger(x) \\Psi(x) =& \\frac{mc^2}{2 \\pi} \\int \\widetilde{\\Psi^\\dagger}(p_2) \\widetilde{\\Psi}(p_1) e^{i(p_1-p_2)x} dx dp_2 dp_1\\\\\n\t=& \\frac{mc^2}{2 \\pi} \\int \\widetilde{\\Psi^\\dagger}(p_2) \\widetilde{\\Psi}(p_1) \\delta(p_1-p_2) dp_2 dp_1\\\\\n\t=& \\frac{mc^2}{2 \\pi} \\int \\widetilde{\\Psi^\\dagger}(p) \\widetilde{\\Psi}(p) dp\n\\end{align*}\n\nThis just removes a particle with momentum $p$ and puts it back with same momentum; momentum isn't changed. The key thing was the integration over $x$, which introduced $\\delta$ for momentum. Before we repeat with the 1st term of (\\ref{eq:psi_mc2}) we will see that this can be more general. Let's suppose we had a term in the Hamiltonian for a whole bunch of fields: $\\Psi^\\dagger(x) \\Psi(x)\\rightarrow \\Psi^\\dagger_A(x) \\Psi_A(x) + \\Psi^\\dagger_B(x) \\Psi_B(x)+...$. We would end up with an integral:\n\\begin{align*}\n\t&\\int dp_1A dp_1B...dp_2A dp 2B \\Pi \\Psi(p_1) \\Pi \\Psi(p_2) e^{i(\\sum p_1-\\sum p_2)x} dx\\\\\n\t=&\\int dp_1A dp_1B...dp_2A dp 2B \\Pi \\Psi(p_1) \\Pi \\Psi(p_2) \\delta(\\sum p_1-\\sum p_2) \n\\end{align*}\nThe first sum is the momentum we put in, the 2nd the momentum that we take out. Total that we take out = total that we put in. Whenever we see a Hamiltonian of this form we have sum of outgoing momentum = sum incoming.\n\nLet's look at derivatives. If we calculate $\\nabla^2 \\Psi^\\dagger (x)$,  only one part of (\\ref{eq:psi:dagger}) is affected, $e^{-ipx}$, since the remainder is doesn't involve $x$. \n\\begin{align*}\n\t- \\nabla^2 \\Psi^\\dagger (x) =& \\int \\frac{dp}{\\sqrt{2\\pi}} p^2 \\widetilde{\\Psi^\\dagger}(p) e^{-ipx}\\text{, so}\\\\\n\t\\int dx \\Psi^\\dagger(x) \\frac{- \\nabla^2}{2m} \\Psi(x)=& \\int \\frac{ p^2}{2m} \\widetilde{\\Psi^\\dagger}(p) \\widetilde{\\Psi}(p) dp \\numberthis \\label{eq:minus:nabla}\n\\end{align*}\nThis adds the kinetic energy of all the particles.\n\nNote: the left hand side of (\\ref{eq:minus:nabla}) looks negative, but it is meant to be kinetic energy, which is positive. Integrating by parts we get:\n\n\\begin{align*}\n\t\\int dx \\Psi^\\dagger(x) \\frac{- \\nabla^2}{2m} \\Psi(x)=& \\frac{1}{2m} \\int dx \\frac{\\partial }{\\partial x} \\Psi^\\dagger(x)  \\frac{\\partial }{\\partial x} \\Psi(x)\n\\end{align*}\nThis looks like any other Hamiltonian, where you see squares of derivatives of the fields. \n\nImagine two species of particles: fake electrons and protons that happen to be bosons.\\footnote{We aren't quite ready for Fermions.}\n\n\\begin{align*}\n\tH =& \\int dx  \\Psi^\\dagger_e(x) \\frac{- \\nabla^2}{2m_e} \\Psi_e(x) + \\int dx \\Psi^\\dagger_p(x) \\frac{- \\nabla^2}{2m_p} \\Psi_p(x)  + g \\int dx \\underbrace{\\Psi^\\dagger_e(x) \\Psi^\\dagger_p(x) \\Psi_e(x) \\Psi_p(x)}_\\text{Figure \\ref{fig:scatter:e:p}} \n\\end{align*}\nwhere $g$ is a coupling constant--proportional to probability of interaction. \n\nThe integrand in last term annihilates a proton and an electron if it finds them at point $x$, then creates an electron and a proton.\n\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\caption[$\\Psi^\\dagger_e(x) \\Psi^\\dagger_e(x) \\Psi_e(x) \\Psi_p(x)$--scattering]{$\\Psi^\\dagger_e(x) \\Psi^\\dagger_e(x) \\Psi_e(x) \\Psi_p(x)$: annihilate and create an electron and proton if they are at the same place, then create again --i.e. scatter}\\label{fig:scatter:e:p}\n\t\t\\feynmandiagram[vertical=o1 to i1]{\n\t\t\ti1[particle=$e^-$]--[fermion]a--[fermion]o1[particle=$e^-$],\n\t\t\ti2[particle=$p^+$]--[fermion]a--[fermion]o2[particle=$p^+$]\n\t\t};\n\t\\end{center}\n\\end{figure}\n\n\\begin{itemize}\n\t\\item Total momentum is conserved, not that of individual particles.\n\t\\item Coulomb potential has been ignored.\n\t\\item If experiment shows that particles interact, then there must be a term in the Hamiltonian.\n\t\\item This is the sort of term for a short range interaction.\n\\end{itemize}\n\nImagine we find particle decay in an experiment, as shown in Figure \\ref{fig:particle:decay}. We might try a term: $\\Psi^\\dagger_b(x) \\Psi^\\dagger_c(x) \\Psi_a(x)$. Since space it isotropic, the interaction can happen anywhere: $g \\int \\Psi^\\dagger_b(x) \\Psi^\\dagger_c(x) \\Psi_a(x) dx$. We can show that momentum is conserved.\n\n\\begin{figure}[H]\n\t\\caption{$\\Psi^\\dagger_b(x) \\Psi^\\dagger_c(x) \\Psi_a(x) dx +  \\Psi^\\dagger_a(x) \\Psi_c(x) \\Psi_b(x)$}\\label{fig:particle:decay:and:reverse}\n\t\\begin{subfigure}{0.45\\textwidth}\n\t\t\\caption{Particle Decay: $\\Psi^\\dagger_b(x) \\Psi^\\dagger_c(x) \\Psi_a(x)$}\\label{fig:particle:decay}\n\t\t\\feynmandiagram[horizontal' = b to c]{\n\t\t\ta[particle=a]--[charged scalar]cc--[charged scalar]b[particle=b],\n\t\t\tcc--[charged scalar]c[particle=c]\n\t\t};\n\t\\end{subfigure}\n\t\\begin{subfigure}{0.45\\textwidth}\n\t\t\\caption{Reverse: $\\Psi^\\dagger_a(x) \\Psi_c(x) \\Psi_b(x)$}\\label{fig:particle:decay:reverse}\n\t\t\\feynmandiagram[horizontal' = b to c]{\n\t\t\tb[particle=b]--[charged scalar]cc--[charged scalar]a[particle=a],\n\t\t\tc[particle=c]--[charged scalar]cc\n\t\t};\n\t\\end{subfigure}\n\\end{figure}\n\nNow what goes in the Hamiltonian must be Hermitian, so we need:\n\\begin{align*}\n\tg \\int \\Psi^\\dagger_b(x) \\Psi^\\dagger_c(x) \\Psi_a(x) dx + g \\int \\Psi^\\dagger_a(x) \\Psi_c(x) \\Psi_b(x)\n\\end{align*}\nwhich reverses the process of  Figure \\ref{fig:particle:decay}: $b+c\\rightarrow a$--Figure \\ref{fig:particle:decay:reverse}.\n\nWe now have a the basic rules of a simple version of quantum field theory:\n\\begin{itemize}\n\t\\item Creation and annihilation operators;\n\t\\item Fields made out of creation and annihilation operators;\n\t\\item Fields are functions of position;\n\t\\item The Fields can be thought of as creation and annihilation operators at a definite position;\n\t\\item Each type of particle has its own field;\n\t\\item We write down Hamiltonian with kinetic energies of particles and other concoctions. \n\\end{itemize}\n\nIn the first round of QFT the concoctions largely came from experiment. A classic example it beta decay: a neutron decaying into a proton, an electron, and a neutrino--$g \\int \\Psi^\\dagger_{\\nu}(x) \\Psi^\\dagger_e(x) \\Psi^\\dagger_p(x) \\Psi_n(x) dx$ (need to make Hermitian).\n\nLet's go one step further. Imagine that we made $\\epsilon$ a little larger in (\\ref{eq:update:state}):\n\n\\begin{align*}\n\t\\ket{\\phi(t+\\epsilon)} =& \\ket{\\phi(t)} -i \\epsilon H \\ket{\\phi(t)} - \\frac{\\epsilon^2}{2} H^2 \\ket{\\phi(t)}\n\\end{align*}\n\nWhat is the effect of $H^2$? We can multiply it out, but the easy way is to use the pictures. E.g., Figure \\ref{fig:particle:decay} becomes a scatter: $b+c \\rightarrow a \\rightarrow b + c$. Or Figure \\ref{fig:scatter:annihilate} shows a more complex situation. You can have a forest of interactions that are mediated by a single term in the Hamiltonian. \n\n\\begin{figure}[H]\n\t\\caption{$\\Psi^\\dagger_c\\Psi^\\dagger_b\\Psi_a\\Psi^\\dagger_a\\Psi_b\\Psi_c$}\n\t\\begin{subfigure}[t]{0.45\\textwidth}\n\t\t\\caption{b and c scattering}\\label{fig:scatter:annihilate}\n\t\t\\feynmandiagram[horizontal' = b to c]{\n\t\t\tb[particle=b]--[charged scalar]cc--[charged scalar]a[particle=a],\n\t\t\tc[particle=c]--[charged scalar]cc,\n\t\t\ta--[charged scalar]ccc--[charged scalar]bb[particle=b],\n\t\t\tccc--[charged scalar]cccc[particle=c]\n\t\t};\n\t\\end{subfigure}\n\t\\begin{subfigure}[t]{0.45\\textwidth}\n\t\t\\caption{Additional particle}\\label{fig:additional:particle}\n\t\t\\feynmandiagram[vertical = cc to c]{\n\t\t\ta[particle=a]--[charged scalar]cc--[charged scalar]b[particle=b],\n\t\t\tcc--[charged scalar]c[particle=c],\n\t\t\tbb[particle=b]--[charged scalar]c,\n\t\t\tc--[charged scalar]aa[particle=a]\n\t\t};\n\t\\end{subfigure}\n\\end{figure}\n\\url{https://youtu.be/7a1hon7NJ1M?t=2917}\n\n\nFigures \\ref{fig:scatter:annihilate} and \\ref{fig:additional:particle} have a coupling constant $g^2$.\n\nWhat about $a\\rightarrow (b+c)\\rightarrow a$? This is a self energy diagram for $a$. A real $a$ has a probability of being a $b+c$, and it behave like a $b+c$ close together some times. Figure \\ref{fig:self:energy:electron} shows a self energy diagram for the electron.\n\n\\begin{figure}[H]\n\t\\caption[Scatter electron and emit photon]{Scatter electron and emit photon(field $A$):$A\\Psi^+_e\\Psi^-_e$. Sometimes what you thought was an electron behaves like an electron + photon. Don't take it too literally: this happens, then  this, then that. The pictures just come out of iterating the Hamiltonian twice. Low probability: think of as correction to structure of an electron, not a new process. If we look, we will screw up electron! Sometime you will see that what you thought was an electron is an electron + photon. Superposition.}\\label{fig:self:energy:electron}\n\t\\begin{subfigure}[t]{0.45\\textwidth}\n\t\t\\begin{center}\n\t\t\t\\caption{Electron comes in and emits photon--$A\\Psi^+_e\\Psi^-_e$}\n\t\t\t\\feynmandiagram[vertical=e2 to e1]{\n\t\t\t\te1[particle=$e^-$]--[fermion]e2[particle=$e^-$]\n\t\t\t\t--[fermion]e3[particle=$e^-$],\n\t\t\t\te2--[photon]x\n\t};\n\t\\end{center}\n\t\\end{subfigure}\n\t\\begin{subfigure}[t]{0.45\\textwidth}\n\t\t\\begin{center}\n\t\t\t\\caption{One other thing that can happen: emit photon and reabsorb. The photon is the electric field of the electron. If electron is moving at the speed of light it behaves like a suerposition of an electron and an electron+photon.}\n\t\t\t\\feynmandiagram[vertical=e4 to e1]{\n\t\t\t\te1[particle=$e^-$]--[fermion]e2--[fermion]e3\n\t\t\t\t--[fermion]e4[particle=$e^-$],\n\t\t\t\te2--[photon,looseness=3.0,half left]e3\n\t\t\t};\n\t\t\\end{center}\n\t\\end{subfigure}\n\\end{figure}\n\nEnergy isn't just the sum of the particles: it includes these interactions.\n\nWe have just seen the basic physics: the rest is technology and tricks.\n\n\n\n\\subsection{The Dirac Equation}\n\nWe will study the relativistic electron. We will start with an electron that moves in 1 direction along a line. Why did Dirac want to handle the relativistic case? Electrons in at atom move at a significant proportion of the speed of light. \n\n\\begin{align*}\n\tE =& \\frac{p^2}{2m} \\text {, classical}\\\\\n\tP =& -i \\frac{\\partial}{\\partial x} \\text{, quantum}\\\\\n\tH = & i \\frac{\\partial}{\\partial t}\\\\\n\tE^2 =& p^2 + m^2 \\text{, relativistic($c^2=1$). It becomes:}\\\\\n\t-\\frac{\\partial^2}{\\partial t^2} \\phi(x) =& -\\frac{\\partial^2}{\\partial x^2}\\phi(x) + m^2 \\phi(x) \n\\end{align*}\n\nThis was already known; it is the Klein-Gordon equation. But Dirac wanted this:\n\\begin{align*}\n\ti \\frac{\\partial \\psi}{\\partial t} =& H\\psi\\\\\n\t=& \\big(\\sqrt{- \\frac{\\partial^2}{\\partial x^2} + m^2}\\big) \\psi  \n\\end{align*}\nWhat could this possibly mean? What is the operator on the right hand side? Dirac decided to start again. Imagine a particle moving along the x axis with the speed of light (massless).\n\n\\begin{align*}\n\tc P =& E \\text{, moving to right. ($c=1$)}\\\\\n\ti \\frac{\\partial \\psi}{\\partial t} =& -i \\frac{\\partial \\psi}{\\partial x} \\numberthis\\label{eq:dirac1:R}\\\\\n\t\\implies&\\\\\n\t\\frac{\\partial \\psi}{\\partial t} + \\frac{\\partial \\psi}{\\partial x}=&0\n\\end{align*}\n\nAny function of x-t will satisfy this  equation. It describes a wave, moving to the right.\n\nThree things are wrong with this equation:\n\\begin{enumerate}\n\t\\item it allows particles with negative momentum, which have negative energy;\\label{item:negative:energy}\n\t\\item it only has particles that move to the right;\\label{item:right:only}\n\t\\item the electron has no mass, so it moves with the speed of light.\\label{item:speed:light}\n\\end{enumerate}\n\nDirac solved second problem by imagining two species of electrons, one moving to the right, t'other to the left, labelled $\\psi_1$ and $\\psi_2$. Or a particle can be one or t'other, or a superposition.\n\n\\begin{align*}\n\t\\frac{\\partial \\psi_1}{\\partial t} + \\frac{\\partial \\psi_1}{\\partial x}=&0 \\text{, moving to right}\\\\\n\t\\frac{\\partial \\psi_2}{\\partial t} - \\frac{\\partial \\psi_2}{\\partial x}=&0 \\text{, moving to left}\n\\end{align*}\n\nImagine particle with two degrees of freedom, $x$ and $1/2$. Make second degree into matrix index. Introduce an observable, $\\alpha$, to tell us whether particle is 1 or 2 (a bit like a spin). We thinks of the $\\psi$s as a column vector, and introduce a matrix whose eigenvectors are $\\psi_1$ or $\\psi_2$. Here is such a matrix (observable).\n\n\\begin{align*}\n\t\\underbrace{\n\t\t\\begin{pmatrix}\n\t\t\t1 & 0\\\\\n\t\t\t0 & -1\n\t\t\\end{pmatrix}\n\t}_\\text{Dirac's $\\alpha$}\n\t\\begin{pmatrix}\n\t\t\\psi_1\\\\\n\t\t\\psi_2\n\t\\end{pmatrix}\\\\\n\tH =& \\alpha P \\numberthis \\label{eq:dirac:1d:hp}\\\\\n\ti\\frac{\\partial \\psi}{\\partial t} =& -i \\alpha \\frac{\\partial \\psi}{\\partial x} \\text{, matrix equation!}\n\\end{align*}\n\nWe have fixed problem \\ref{item:right:only}, particles moving to the right only. To fix problem \\ref{item:speed:light}, absence of mass, Dirac added a term to give the electron mass. \n\n\\begin{align*}\n\tH =& \\alpha P + \\beta m \\text{, where $\\beta$ is some matrix. Now} \\numberthis \\label{eq:dirac:1D:m}\\\\\n\tE^2 =& P^2 + m^2 \\text{, so}\\\\\n\tE^2 =& \\big(\\alpha P + \\beta m \\big) \\big(\\alpha P + \\beta m \\big)\\\\\n\t=& \\underbrace{\\alpha^2 P^2}_\\text{(=1)} + \\underbrace{\\beta^2 m^2}_\\text{set  $=1$} + (\\alpha \\beta + \\beta \\alpha) P m\\\\\n\t=&  P^2 + m^2 + (\\alpha \\beta + \\beta \\alpha) P m \\text{, so we want:}\\\\\n\t\\alpha \\beta + \\beta \\alpha=&0 \n\\end{align*}\n\nNow $\\alpha$ is a Pauli matrix, $\\sigma_3$, so we can use any other Pauli matrix for $\\beta$. We will use\n$\n\t\\begin{pmatrix}\n\t\t0&1\\\\\n\t\t1&0\n\t\\end {pmatrix}\n$.\n\nWe have the 1-dimensional version of Dirac's equation.\n\\begin{align*}\n\ti \\frac{\\partial \\psi}{\\partial t}=& a p \\psi + \\beta m \\psi \\text{, where $\\psi$ is a two component spinor.}\\\\\n\ti \\frac{\\partial}{\\partial t}\\begin{pmatrix}\n\t\\psi_1\\\\\n\t\\psi_2\n\t\\end{pmatrix}=&-i \\begin{pmatrix}\n\t1&0\\\\\n\t0&-1\n\t\\end{pmatrix} \\frac{\\partial}{\\partial x}\\begin{pmatrix}\n\t\\psi_1\\\\\n\t\\psi_2\n\t\\end{pmatrix} + \\begin{pmatrix}\n\t0&m\\\\\n\tm&0\n\t\\end{pmatrix}\\begin{pmatrix}\n\t\\psi_1\\\\\n\t\\psi_2\n\t\\end{pmatrix}\n\\end{align*}\n\nSo\n\\begin{align*}\n\ti\\frac{\\partial \\psi_1}{\\partial t} + i\\frac{\\partial \\psi_1}{\\partial x}=&m \\psi_2\\\\\n\ti\\frac{\\partial \\psi_2}{\\partial t} - i\\frac{\\partial \\psi_2}{\\partial x}=&m \\psi_1\n\\end{align*}\n\nSo the mass term couples the two equations, and makes particle move slower then light. Dirac knew that mass is coupled to ability to move left or right.\n\n\\section{Fermions and the Dirac equation}\\label{section:fermions:dirac}\n\n\\subsection{Second Quantization of Fermions}\n\nIf you have two bosons, can put them into same state, and creation and annihilation operators commute. There is nothing strange about commuting, but anticommuting is odd. Suppose we have two particles, and we want to say that when we interchange them the wave function or state vector changes sign.  whose wave function changes sign when we interchange. Let $\\ket{x,y}$ represent particles at x and y (two 3 dimensional positions). $\\Psi^\\dagger(x)\\Psi^\\dagger(y)\\ket{0}$ will create.\n\nFor bosons, operators commute and:\n\\begin{align*}\n\t\\ket{x,y}=&\\ket{y,x} \\text{, because}\\\\\n\t\\Psi^\\dagger(x)\\Psi^\\dagger(y)=&\\Psi^\\dagger(y)\\Psi^\\dagger(x) \\text{, because}\\\\\n\t[\\Psi^\\dagger(x),\\Psi^\\dagger(y)]=&0\n\\end{align*}\n\nFor Fermions:\n\\begin{align*}\n\t\\ket{x,y}=&-\\ket{y,x} \\text{, so we need}\\\\\n\t\\Psi^\\dagger(x)\\Psi^\\dagger(y)=& -\\Psi^\\dagger(y)\\Psi^\\dagger(x) \\text{, or}\\\\\n\t\\Psi^\\dagger(x)\\Psi^\\dagger(y)+\\Psi^\\dagger(y)\\Psi^\\dagger(x)=&0 \\text{. This is usually written:}\\\\\n\t\\{\\Psi^\\dagger(x), \\Psi^\\dagger(y)\\}=&0 \\text{, where}\\\\\n\t\\{A,B\\}\\triangleq& AB + BA \\text{, the anticommutator.}\n\\end{align*}\n\nIn general we can go from Bosons to Fermions by replacing the commutator with the anticommutator.\n\nNB  $\\Psi^\\dagger(x)\\Psi^\\dagger(x)=\\frac{1}{2}\\{\\Psi^\\dagger(x)\\Psi^\\dagger(x)\\}=0$,  so we can't have two identical particles at same position.\n\n\\begin{itemize}\n\t\\item For Bosons there is a clear distinction between creation and annihilation operators, since $[a,a^\\dagger]=1$ (\\ref{eq:a:comm_i}), and $[a^\\dagger,a]=-1$. We can't confuse them because the spectrum of energies from $0$ to $\\infty$ can't be turned upside down. Creation operators never give 0!.\n\t\\item For Fermions $\\{a^\\dagger,a\\}= \\{a,a^\\dagger\\}=+1$: from the algebra there is no difference between creation and annihilation operators. They do different things, so they are different, but we can't see this from the algebra alone.\n\\end{itemize}\n\nConsider occupation numbers of Fermion with only one state: creation operator takes $0$ to $1$; if we create again the operator  annihilates, leaving $0$. Complete symmetry between empty and filled, creation and annihilation (mathematically!--it doesn't mean they are the same).\n\\begin{align*}\n\ta^2=&0\\\\\n\t(a^\\dagger)^2=&0\n\\end{align*}\n\n\n\\subsection{The Dirac Equation in 3 dimensions}\n\n\\subsubsection{Review of 1D Dirac Electron}\n\nReturning to the 1D Dirac equation for zero mass, (\\ref{eq:dirac1:R}):\n\\begin{align*}\n\ti \\frac{\\partial \\psi}{\\partial t}=& -i \\frac{\\partial \\psi}{\\partial x} \\\\\n\tH \\Psi =& i \\Psi\n\\end{align*}\nThis was a failure as a theory of 1D electrons. We want a 2nd species that propagates to the left.\n\\begin{align*}\n\ti \\frac{\\partial \\psi_1}{\\partial t}=& -i \\frac{\\partial \\psi_1}{\\partial x} \\\\\n\tH \\Psi_1 =& i \\Psi_1\\\\\n\ti \\frac{\\partial \\psi_2}{\\partial t}=& i \\frac{\\partial \\psi_2}{\\partial x} \\\\\n\tH \\Psi_2 =& -i \\Psi_2\n\\end{align*}\nWe combined into a vector, adding handedness, $\\begin{pmatrix} \\psi_1\\\\ \\psi_2 \\end{pmatrix}$, and defined the matrix $\\alpha = \\begin{pmatrix}\n1&0\\\\\n0&-1\n\\end{pmatrix}$\n\nSo we had (\\ref{eq:dirac:1d:hp})\n\\begin{align*}\n\tH \\psi =& \\alpha P \\psi\n\\end{align*}\n\nThat didn't get us a mass, but it got stuff moving in both directions. We then invented another matrix $\\beta=\\begin{pmatrix}\n0&1\\\\\n1&0\n\\end{pmatrix}$ and in (\\ref{eq:dirac:1D:m}) wrote $H = \\alpha P + \\beta m$. Note $\\alpha^2=\\beta^2=1$, and $\\alpha\\beta + \\beta\\alpha=1$, whence $H^2=P^2+m^2$. We combined left moving and right moving, then added coupling to give mass. It is in this sense that a mass term switches you from left moving to right moving.\n\n\\subsubsection{The Dirac Equation in 3 dimensions}\n\n How do we do this in 3D? Let's  drop $m$ temporarily, make $\\alpha$ a vector, $\\vec{\\alpha}$, so we can dot product with $\\vec{P}$.\n\\begin{align*}\n\tH =& \\vec{\\alpha} \\boldsymbol{\\cdot} \\vec{P}\\\\\n\t=& \\alpha_x P_x + \\alpha_y P_y + \\alpha_z P_z \\text{. We want}\\\\\n\tH^2 =& P_x^2 + P_y^2 + P_z^2\n\\end{align*}\nSo we need\n\\begin{align*}\n\t\\alpha_x^2 =&1\\\\\n\t\\alpha_y^2 =&1\\\\\n\t\\alpha_z^2 =&1\n\\end{align*}\nand\n\\begin{align*}\n\t\\alpha_y\\alpha_x + \\alpha_x\\alpha_y=&0\\\\\n\t\\alpha_z\\alpha_x + \\alpha_x\\alpha_z=&0\\\\\n\t\\alpha_x\\alpha_y + \\alpha_y\\alpha_z=&0\n\\end{align*}\nwhich can be written:\n\\begin{align*}\n\t\\{\\alpha_y,\\alpha_x\\} =&0\\\\\n\t\\{\\alpha_z,\\alpha_x\\} =&0\\\\\n\t\\{\\alpha_x,\\alpha_y\\} =&0\n\\end{align*}\n\nDirac needed three matrices that satisfy these equations; the three Pauli matrices do exactly that:\n\\begin{align*}\n\t\\vec{\\alpha}=&\\vec{\\sigma} \\text{, so}\\\\\n\tH =& \\vec{\\sigma} \\cdot \\vec{P}\n\\end{align*}\n\nSpin is always $\\pm 1$, so it looks as if we have two cases, where spin is either in the same direction as momentum, or the opposite; again we have a massless particle with positive and negative energy, and whose spin is locked so its axis is along the momentum vector.\n\nDirac's logic, which was not necessarily unimpeachable, was that he wanted to write an equation for H in terms or P without having an insane square root. He wrote $\tH = \\vec{\\alpha} \\cdot \\vec{P}$ because he wanted it to be linear in the momentum. He wondered what $\\alpha$ was, because it couldn't just be a bunch of numbers. By requiring $H^2=P^2$ he found the Pauli matrices. He thought that he had discovered the origin of spin. He was not correct it that it is not the case that every particles has to have spin, but he was right for Fermions.\n\nWe still have $H^2=P^2$, and we don't have a mass. So we try $H= H = \\vec{\\alpha} \\cdot \\vec{P}+\\beta m$ for some $\\beta$ such that $\\beta^2=1$.\n\n\\begin{align*}\n\tH^2 = P^2 +& m^2 \\\\\n\t+& P_x m (\\sigma_x \\beta + \\beta \\sigma_x) \\\\\n\t+& P_y m (\\sigma_y \\beta + \\beta \\sigma_y) \\\\\n\t+& P_z m (\\sigma_z \\beta + \\beta \\sigma_z)\n\\end{align*}\n\nSo $\\beta$ anticommutes with all the Pauli matrices: unfortunately there is not matrix that anticommutes with all the Pauli matrices.\n\n\\begin{thm}[There is no $2 \\times 2$ matrix that anticommutes with the Pauli matrices]\n\tWe can find 3 $2 \\times 2$ matrices that anticommute, but not 4.\n\\end{thm}\n\\begin{proof}\n\tTBP\n\\end{proof}\nWe have two choices: we can give up, or introduce another 2 valued degree of freedom, so we would use $4 \\times 4$. It turns out that this will work: $4 \\times 4$ \\emph{has nothing to do with space being 4 dimensional; it is just a mathematical fact about anti-commuting matrices.} \n\nThere are many different and equivalent representation of the Dirac matrices, which must satisfy:\n\\begin{align*}\n\t\\alpha_x^2=&1  \\\\\n\t\\alpha_y^2=&1  \\\\\n\t\\alpha_z^2=&1  \\\\\n\t\\beta^2=&1\n\\end{align*}\nand\n\\begin{align*}\n\t[\\alpha_y,\\alpha_z] =&0 \\\\\n\t[\\alpha_z,\\alpha_x] =&0 \\\\\n\t[\\alpha_x,\\alpha_y ]=&0 \\\\\n\t[\\alpha_x,\\beta]=&0 \\\\\n\t[\\alpha_y,\\beta]=&0 \\\\\n\t[\\alpha_z,\\beta]=&0 \n\\end{align*}\nHere is one solution, the Pauli representation of the Dirac matrices. This is not the representation that Dirac used.\n\\begin{align*}\n\t\\vec{\\alpha} =& \\begin{pmatrix}\n\t\t\\vec{\\sigma}&0 \\\\\n\t\t0&-\\vec{\\sigma}\n\t\\end{pmatrix} \\\\ \n\t\\alpha_x =& \\begin{pmatrix}\n\t\t\\sigma_x&0\\\\\n\t\t0&-\\sigma_x\n\t\\end{pmatrix}=&\\begin{pmatrix}\n\t\t0&1&0&0\\\\\n\t\t1&0&0&0\\\\\n\t\t0&0&0&-1\\\\\n\t\t0&0&-1&0\n\t\\end{pmatrix}\\\\\n\t\\alpha_y =& \\begin{pmatrix}\n\t\\sigma_y&0\\\\\n\t0&-\\sigma_y\n\t\\end{pmatrix}=&\\begin{pmatrix}\n\t\t0&i&0&0\\\\\n\t\t-i&0&0&0\\\\\n\t\t0&0&0&-i\\\\\n\t\t0&0&i&0\n\t\\end{pmatrix}\\\\\n\t\\alpha_z =& \\begin{pmatrix}\n\t\\sigma_z&0\\\\\n\t0&-\\sigma_z\n\t\\end{pmatrix}=&\\begin{pmatrix}\n\t\t1&0&0&0\\\\\n\t\t0&-1&0&0\\\\\n\t\t0&0&-1&0\\\\\n\t\t0&0&0&1\n\t\\end{pmatrix}\\\\\n\t\\beta =& \\begin{pmatrix}\n\t\t0&1\\\\\n\t\t1&0\n\t\\end{pmatrix} =& \\begin{pmatrix}\n\t\t0&0&1&0\\\\\n\t\t0&0&0&1\\\\\n\t\t1&0&0&0\\\\\n\t\t0&1&0&0\n\t\\end{pmatrix}\n\\end{align*}\n\nWhen we tried $H= H = \\vec{\\alpha} \\cdot \\vec{P}+\\beta m$, we found that for positive energy, $\\sigma$ has to be aligned with momentum. We introduced another species which has its spin reversed: this is said to be the opposite \\emph{chirality}.\n\n\\begin{defn}[Helicity]\n\t Physically, the helicity operator can be thought of as a projection operator of spin along the direction of motion $h=\\frac{\\vec{S}\\cdot\\vec{P}}{\\lvert P \\rvert}$.\n\\end{defn}\n\\begin{defn}[Chirality]\n\tChirality is the relationship between the directions of spin and momentum. If the directions are the same, the chirality is right handed, otherwise left handed.\\cite{meredith2018helicity}\n\\end{defn}\n\nWe coupled the left and right handed particles using the off diagonal entries in $\\beta$, and the mass. So mass is a coupling between left and right. For massless particles, chirality is conserved.[Sort out helicity]\n\nWhat is $\\alpha$? Each component of $\\alpha$ is a matrix, with two eigenvalues $+1$ and two $-1$. What physical quantity does it represent? They don't commute, so we can't measure them simultaneously. What is physical meaning of a component? It is the velocity, so the expectation value in any state is the velocity of the particle.\n\nFor any operator $L$:\n\\begin{align*}\n\t\\dot L =& i [H,L] \\text{, for any operator L. We'll consider}\\\\\n\t\\dot X =& i[\\alpha P + \\beta m,X]\\\\\n\t=& i \\alpha [P,X]\\\\\n\t=&\\alpha_x\n\\end{align*}\n\nSo it is the velocity of particle! Velocity is not the same as momentum for electron.\n\n\\begin{align*}\n\t\\frac{d}{dt} \\alpha_x=&[H,\\alpha_x]\\\\\n\t \\ne& 0 \\text{ because H contains $\\alpha_y$ and $\\alpha_z$}\n\\end{align*}\nso $\\alpha_x$ is not conserved.\n\nIt does a spiral movement called Zitterbewegung.\n\nDirac discovered a multiplicity of different states of the electron, one had to do with chirality, the other to do with actual spin.\n\n\\subsubsection{Dirac Electron  and negative energy}\nDirac equation can have negative energy, even in 1 D case. We don't need 3D even for interesting effects.\n\n\\begin{align*}\n\tH=P \\text{, right moving electron, What if $P<0$?}\n\\end{align*} \n\nGround state has lowest energy (not fewest particles). With negative energy can lower indefinitely! What does -ve energy mean? They are very dangerous, because ground state is lowest energy: if we have negative energies could lower energy past vacuum! Or we could lower energy indefinitely. \n\nDirac \\emph{defined} vacuum to have lowest energy. Dirac filled with negative energies (Fermions!) --only one in each state. Since they are Fermions, if state filled we can't keep going. Vacuum must have every negative state occupied; then thee is no room to lower energy further. Can add positive energy electron, or move a negative energy electron to positive--Figure \\ref{fig:dirac:sea}. (This was an intuitive way to describe some mathematics).\n\nIn Figure \\ref{fig:ds} we have filled all negative energy levels, whch stabilizes vacuum. We can put in a positive energy electron, Figure \\ref{fig:aqm-10-dirac-sea}, or take out a negative energy electron and leave a hole, Figure \\ref{fig:dirac:sea}\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\caption{The Dirac Sea}\\label{fig:ds}\n\t\t\\begin{subfigure}[t]{0.3\\textwidth}\n\t\t\t\\begin{center}\n\t\t\t\t\\caption{Positive energy electron added}\\label{fig:aqm-10-dirac-sea}\n\t\t\t\t\\includegraphics[width=0.5\\textwidth]{aqm-10-dirac-sea}\n\t\t\t\\end{center}\n\t\t\\end{subfigure}\n\t\t\\begin{subfigure}[t]{0.3\\textwidth}\n\t\t\t\\begin{center}\n\t\t\t\t\\caption{Pluck out negative energy electron and get +ve charge and +ve energy hole (positron)}\\label{fig:dirac:sea}\n\t\t\t\t\\includegraphics[width=0.5\\textwidth]{DiracSea}\n\t\t\t\\end{center}\n\t\t\\end{subfigure}\n\t\t\\begin{subfigure}[t]{0.3\\textwidth}\n\t\t\t\\begin{center}\n\t\t\t\t\\caption{Photon displaces negative energy electron and produces +ve charge and +ve energy hole (positron)}\\label{fig:dirac:sea:photon}\n\t\t\t\t\\includegraphics[width=\\textwidth]{aqm-10-dirac-sea-photon}\n\t\t\t\\end{center}\n\t\\end{subfigure}\n\t\\end{center}\n\\end{figure}\n\nImagine photon coming along and hitting -ve energy electron in vacuum: we get an electron and a hole--Figures \\ref{fig:dirac:sea:photon} and \\ref{photon:dirac}.\n\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\caption[Photon$\\rightarrow$ electrons + hole]{Photon$\\rightarrow$ electons + hole. By convention positron points down. Can slice in time: upwards electron, down positrons.}\\label{photon:dirac}\n\t\t\\feynmandiagram[vertical=n1 to i1]{\n\t\t\ti1--[photon,edge label=$\\gamma$]n1--[anti fermion]o1[particle=$e^+$],\n\t\t\tn1--[fermion]o2[particle=$e^-$]\n\t\t};\n\t\\end{center}\n\\end{figure}\n\nThe wave function needs fermion operators, which anticommute.\n\\begin{align*}\n\t\\Psi =& \\int_{-\\infty}^{\\infty} dp a^-(p) e^{-ipx}\\\\\n\t=& \\underbrace{\\int_{-\\infty}^0 dp a^-(p) e^{-ipx}}_\\text{negative energies}+ \\underbrace{\\int_0^{\\infty} dp a^-(p) e^{-ipx}}_\\text{positive energies}\n\\end{align*}\n\nBut the mathematics doesn't distinguish between Fermion creation and annihilation operators. Introducing $b^+(p)$, the creation operator for positirons:\n\\begin{align*}\n\t\\Psi =&  \\int_0^{\\infty} dp  b^+(p) e^{ipx}+ \\int_0^{\\infty} dp a^-(p) e^{-ipx}\n\\end{align*}\n\nConsider the interaction of Figure \\ref{fig:electron_scattering_dirac}.\n\\begin{align*}\n\ta^+a^-A& \\text{, which comes from a term in the Hamiltonian:}\\\\\n\t\\Psi^\\dagger(x)\\Psi(x)A&\\text{, }\n\\end{align*}\n\nBut this also describes the interactions of  Figures \\ref{fig:electron_scattering_dirac}, \\ref{fig:positron annihilating_dirac}, and \\ref{fig:all3-created}.\n\\begin{figure}[H]\n\t\\caption{Possible outcomes of $\\Psi^\\dagger(x)\\Psi(x)A$: Feynman diagrams.}\n\t\\begin{subfigure}{0.3\\textwidth}\n\t\t\\caption{Electron scattering}\\label{fig:electron_scattering_dirac}\n\t\t\\feynmandiagram[vertical'=a to i1]{\n\t\t\ti1[particle=$e^-$]--[fermion]a--[fermion]o1[particle=$e^-$],\n\t\t\ta--[photon]o2\n\t\t};\n\t\\end{subfigure}\n\t\\begin{subfigure}{0.3\\textwidth}\n\t\t\\caption{Positron annihilation}\\label{fig:positron annihilating_dirac}\n\t\t\\feynmandiagram[vertical'=i2 to a]{\n\t\t\ta -- [boson]b,\n\t\t\tc[particle=$e^-$]--[fermion]b,\n\t\t\td[particle=$e^+$]--[anti fermion]b\n\t\t};\n\t\\end{subfigure}\n\t\\begin{subfigure}{0.3\\textwidth}\n\t\t\\caption{Electron, photon, positron created}\\label{fig:all3-created}\n\t\t\\feynmandiagram[vertical=o2 to i1]{\n\t\t\ta--[opacity=0.0]b,\n\t\t\ta--[fermion]c[particle=$e^-$],\n\t\t\ta--[anti fermion]d[particle=$e^+$],\n\t\t\ta--[boson]e,\n\t\t\ta--[opacity=0.0]f,\n\t\t\ta--[opacity=0.0]g\n\t\t};\n\t\\end{subfigure}\n\\end{figure}\n\nThis was pretty much the start of Feynman diagrams (back in Dirac's day)! But Feynman figured out how to evaluate them.\n\nHow do modern physicists think of the Dirac Sea? They just forget the Dirac sea and replace creation operators for negative energy with annihilators for positive.\n\nSame pattern in solid state physics. If you have crystal with lots of electrons, put all electrons into lowest available states--ground state. We have the Fermi sea. Can take an energy out of sea and kick into higher state, leaving a hole which behaves like a particle. But Dirac did this first!\n\nQuestion about Cosmological constant. Can think of it as energy in Dirac Sea, or zero point oscillation of field. Photons aren't thought of as part of Dirac sea, but they contribute $\\frac{1}{2}\\hslash\\omega$ for every oscillating mode. For photons background energy is positive, for Fermions it is negative. You could think of them cancelling, but Fermions have mass, photons don't, so they don't cancel. You are always left with some huge amount of energy left over. \n\nKeep in mind that the only time zero point energy comes into anything is when that energy is gravitating. For all other purposes we can ignore it because only differences matter.\n\n\\bibliographystyle{unsrt}\n\\addcontentsline{toc}{section}{Bibliography}\n\\raggedright\n\\bibliography{tm}\n\n\\end{document}", "meta": {"hexsha": "8aa9b32bccf1990411c9c22bb61fd9550eff5c54", "size": 122828, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "aqm.tex", "max_stars_repo_name": "weka511/tm", "max_stars_repo_head_hexsha": "091aa09764b70d860cca7926658937363a9e1e83", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aqm.tex", "max_issues_repo_name": "weka511/tm", "max_issues_repo_head_hexsha": "091aa09764b70d860cca7926658937363a9e1e83", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2021-07-15T19:53:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-03T22:54:10.000Z", "max_forks_repo_path": "aqm.tex", "max_forks_repo_name": "weka511/tm", "max_forks_repo_head_hexsha": "091aa09764b70d860cca7926658937363a9e1e83", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.0304659498, "max_line_length": 869, "alphanum_fraction": 0.7122073143, "num_tokens": 39146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.30736334118347786}}
{"text": "    \\section{Low-Voltage Induced Random Bit Errors in Quantized DNN Weights}\n\\label{sec:supp-main}\n\nWe provide a more detailed discussion of the considered error model: random bit errors, induced through low-voltage operation of memories commonly used on DNN accelerators \\cite{KimDATE2018,KoppulaMICRO2019}. Work such as \\cite{ChandramoorthyHPCA2019,KoppulaMICRO2019} model the effect of low-voltage induced bit errors using two parameters: the probability $\\pfault$ of bit cells in accelerator memory being faulty at a given low voltage and the probability $\\perror$ that a faulty bit cell results in a bit error on access.\nFollowing measurements in works such as \\cite{GanapathyHPCA2019,KimDATE2018}, we assume that these errors are \\emph{not} transient errors by setting $\\perror = 100\\%$ such that the overall probability of bit errors is $p := \\pfault \\cdot \\perror = \\pfault$. In doing so, we consider the worst-case where faulty bit cells \\emph{always} induce bit errors. However, the noise model from the main paper remains valid for any arbitrary but fixed $\\perror \\neq 100\\%$. For the reminder of this document, we assume the probability of bit error $p = \\pfault$, with $\\perror = 100\\%$, as in the main paper. In the following section, we describe the two parameters, $\\pfault$ and $\\perror$, in more details.\n\n\\begin{table}[t]\n\t\\centering\n\t\\caption{\\textbf{Quantization-Aware Training Accuracies.} Clean \\TE for $m = 8$ bits or lower using our robust fixed-point quantization. We obtain competitive performance for $m = 8$ and $m = 4$ bits. On \\CifarH, a Wide ResNet (WRN) clearly outperforms our standard SimpleNet model. Batch normalization (BN), improving \\TE slightly on \\CifarT, is significantly less robust than group normalization (GN), \\cf \\tabref{tab:supp-bn}. * For $m \\leq 4$, we report results with weight clipping, \\Clipping[$0.1$].}\n\t\\label{tab:supp-accuracy}\n\t\\vspace*{-0.25cm}\n\t\\hspace*{-0.25cm}\n\t\\begin{subfigure}[t]{0.19\\textwidth}\n\t\t\\vspace*{0px}\n\t\t\\small\n\t\t\\begin{tabular}{|@{\\hskip 4px}l@{\\hskip 4px}|@{\\hskip 4px}c@{\\hskip 4px}|}\n\t\t\t\\multicolumn{2}{c}{\\bfseries \\CifarT}\\\\\n\t\t\t\\multicolumn{2}{c}{\\bfseries SimpleNet+GN}\\\\\n\t\t\t\\hline\n\t\t\tQuant. $m$ & \\TE in \\%\\\\\n\t\t\t\\hline\n\t\t\t-- & 4.34\\\\\n\t\t\t8 & \\bfseries 4.32\\\\\n\t\t\t4* & 5.29\\\\\n\t\t\t3* & 5.71\\\\\n\t\t\t\\hline\n\t\t\\end{tabular}\n\t\\end{subfigure}\n\t\\begin{subfigure}[t]{0.28\\textwidth}\n\t\t\\vspace*{0px}\n\t\t\\small\n\t\t\\begin{tabular}{|@{\\hskip 4px}l@{\\hskip 4px}|@{\\hskip 4px}c@{\\hskip 4px}|@{\\hskip 4px}c@{\\hskip 4px}|}\n\t\t\t\\multicolumn{3}{c}{\\bfseries \\CifarT}\\\\\n\t\t\t\\multicolumn{3}{c}{\\bfseries Arch. Comparison}\\\\\n\t\t\t\\hline\n\t\t\tModel & no Quant. & $m = 8$\\\\\n\t\t\t\\hline\n\t\t\tSimpleNet+GN & 4.34 & 4.32\\\\\n\t\t\tSimpleBet+BN & 4.04 & 3.83\\\\\n\t\t\tResNet-50+GN & 5.88 & 6.81\\\\\n\t\t\tResNet-50+BN & \\bfseries 3.91 & \\bfseries 3.67\\\\\n\t\t\t\\hline\n\t\t\\end{tabular}\n\t\\end{subfigure}\\\\[4px]\n\t\n\t\\hspace*{-0.5cm} \n\t\\begin{subfigure}[t]{0.19\\textwidth}\n\t\t\\vspace*{0px}\n\t\t\\small\n\t\t\\begin{tabular}{| l | c |}\n\t\t\t\\multicolumn{2}{c}{\\bfseries \\MNIST}\\\\\n\t\t\t\\hline\n\t\t\tQuant. $m$ & \\TE in \\%\\\\\n\t\t\t\\hline\n\t\t\t4 & 0.4\\\\\n\t\t\t2* & 0.47\\\\\n\t\t\t\\hline\n\t\t\\end{tabular}\n\t\\end{subfigure}\n\t\\begin{subfigure}[t]{0.2\\textwidth}\n\t\t\\vspace*{0px}\n\t\t\\small\n\t\t\\begin{tabular}{| l | c |}\n\t\t\t\\multicolumn{2}{c}{\\bfseries \\CifarH}\\\\\n\t\t\t\\hline\n\t\t\tQuant. $m$, Model & \\TE in \\%\\\\\n\t\t\t\\hline\n\t\t\t8, SimpleNet & 23.68\\\\\n\t\t\t8, WRN & 18.53\\\\\n\t\t\t\\hline\n\t\t\\end{tabular}\n\t\\end{subfigure}\n\t\\vspace*{-0.1cm}\n\\end{table}\n\n\\textbf{Faulty Bit Cells.} Due to variations in the fabrication process, SRAM bit cells become more or less vulnerable to low-voltage operation. For a specific voltage, the resulting bit cell failures can be assumed to be random and independent of each other. We assume a bit to be faulty with probability $\\pfault$ increasing exponentially with decreased voltage \\cite{GanapathyDAC2017,GanapathyHPCA2019,KimDATE2018,ChandramoorthyHPCA2019}. Furthermore, the faulty bits for $\\pfault' \\leq \\pfault$ can be assumed to be a subset of those for $\\pfault$. For a fixed chip, consisting of multiple memory arrays, the pattern (spatial distribution) of faulty cells is fixed for a specific supply voltage. Across chips/memory arrays, however, faulty cells are assumed to be random and independent of each other.\n\n\\textbf{Bit Errors in Faulty Bit Cells:} Faulty cells may cause bit errors with probability $\\perror$ upon read/write access.\nWe note that bit errors read from memory affect \\emph{all} computations performed on the read weight value. \nWe assume that a bit error flips the currently stored bit, where flips $0$-to-$1$ and $1$-to-$0$ are assumed equally likely.\n\n\\subsection{Profiled Bit Errors}\n\\label{subsec:supp-errors-profiled}\n\n\\begin{figure}[t]\n\t\\centering\n\t\\includegraphics[width=0.4\\textwidth]{c10_clipping_linf.pdf}\n\t\\vspace*{-8px}\n\t\\caption{\\textbf{Weight Clipping Improves $L_\\infty$ Robustness.} On \\CifarT, we plot \\RTE for \\emph{relative} $L_\\infty$ perturbations on weights: Random noise with $L_\\infty$-norm smaller than or equal to $x\\%$ of the weight range is applied. \\Clipping clearly improves robustness. Again, the relative magnitude of noise is not affected by weight clipping. Note that $L_\\infty$ noise usually affects all weights, while random bit errors affect only a portion of the weights.}\n\t\\label{fig:supp-clipping-inf}\n\t\\vspace*{-0.2cm}\n\\end{figure}\n\n\\figref{fig:supp-errors} splits the bit error distributions of \\figref{fig:errors} into a $0$-to-$1$ flip and a $1$-to-$0$ bit flip map. The obtained maps, $p_{\\text{1t0}}$ and $p_{\\text{0t1}}$, contain per-bit flip probabilities for $1$-to-$0$ and $0$-to-$1$ bit flips at a given low voltage. In this particular profiled chip, \\figref{fig:supp-errors} (bottom), $0$-to-$1$ flips are more likely. Similarly, \\figref{fig:supp-errors} (right) shows that most  $0$-to-$1$ flips are actually persistent across time at that voltage \\ie, not random transient errors. \nThe following table summarizing the key statistics of the profiled chips: the overall bit error rate $p$, the rate of $1$-to-$0$ and $0$-to-$1$ flips $p_{\\text{1t0}}$ and $p_{\\text{0t1}}$, and the rate of persistent errors $p_{\\text{sa}}$, all in \\% at a specific supply voltage:\n\n\\begin{center}\\small\n\\begin{tabular}{| l | c | c | c | c |}\n\t\\hline\n\tChip & $p$ & $p_{\\text{0t1}}$ & $p_{\\text{1t0}}$ & $p_{\\text{sa}}$ \\\\\n\t\\hline\n\t\\multirow{2}{*}{1} & 2.744 & 1.27 & 1.47 & 1.223\\\\\n\t& 0.866 & 0.38 & 0.49 & 0.393\\\\\n\t\\hline\n\t\\multirow{3}{*}{2} & 4.707 &  3.443 & 1.091 & 0.627\\\\\n\t& 1.01 &  0.82 & 0.19 & 0.105\\\\\n\t& 0.136 & 0.115 & 0.021 & 0.01 \\\\\n\t\\hline\n\t\\multirow{2}{*}{3} & 2.297 & 1.81 & 0.48 & 0.204 \\\\\n\t& 0.597 & 0.496 & 0.0995 & 0.206 \\\\\n\t\\hline\n\\end{tabular}\n\\end{center}\n\n\\begin{table*}[t]\n\t\\centering\n\t\\small\n\t\\caption{\\textbf{Impact of Quantization Scheme on Robustness.} Complementary to \\tabref{tab:quantization-robustness}, we report \\TE and \\RTE for various bit error rates $p$ for the quantization scheme in \\eqnref{eq:quantization} with global, per-layer and asymmetric quantization, $m = 8$ bits. Instead of quantizing into signed integer, using unsigned integers works better for asymmetric quantization. Furthermore, proper rounding instead of integer conversion also improves robustness. Note that influence on clean \\TE is neglegible, \\ie, the DNN can ``learn around'' these difference in quantization-aware training. Especially for $m = 4$ bit, the latter makes a significant difference in terms of robustness.}\n\t\\label{tab:supp-quantization}\n\t\\vspace*{-0.25cm}\n\t\\begin{tabular}{| c | l | c | c | c | c | c | c | c |}\n\t\t\\hline\n\t\t\\multicolumn{9}{|c|}{\\bfseries \\CifarT: quantization robustness}\\\\\n\t\t\\hline\n\t\t& Model & \\multirow{2}{*}{\\begin{tabular}{c}\\TE\\\\in \\%\\end{tabular}} & \\multicolumn{6}{c|}{\\RTE in \\%, $p$ in \\% p=0.01}\\\\\n\t\t\\cline{4-9}\n\t\t& (see text) && $0.01$ & $0.05$ & $0.1$ & $0.5$ & $1$ & $1.5$\\\\\n\t\t\\hline\n\t\t\\hline\n\t\t\\multirow{5}{*}{\\rotatebox{90}{$m = 8$ bit}} & \\eqnref{eq:quantization}, global & 4.63 & 10.70 {\\color{gray}\\scriptsize ${\\pm}$1.37} & 86.01 {\\color{gray}\\scriptsize ${\\pm}$3.65} & 90.36 {\\color{gray}\\scriptsize ${\\pm}$0.66} & 90.71 {\\color{gray}\\scriptsize ${\\pm}$0.49} & 90.57 {\\color{gray}\\scriptsize ${\\pm}$0.43} & --\\\\\n\t\t& \\eqnref{eq:quantization}, per-layer (= \\Normal) & 4.36 & 4.82 {\\color{gray}\\scriptsize ${\\pm}$0.07} & 5.51 {\\color{gray}\\scriptsize ${\\pm}$0.19} & 6.37 {\\color{gray}\\scriptsize ${\\pm}$0.32} & 24.76 {\\color{gray}\\scriptsize ${\\pm}$4.71} & 72.65 {\\color{gray}\\scriptsize ${\\pm}$6.35} & 87.40 {\\color{gray}\\scriptsize ${\\pm}$2.47}\\\\\n\t\t& +asymmetric & 4.36 & 5.76 {\\color{gray}\\scriptsize ${\\pm}$0.09} & 6.47 {\\color{gray}\\scriptsize ${\\pm}$0.22} & 7.85 {\\color{gray}\\scriptsize ${\\pm}$0.46} & 40.78 {\\color{gray}\\scriptsize ${\\pm}$7.56} & 76.72 {\\color{gray}\\scriptsize ${\\pm}$7.01} & 85.83 {\\color{gray}\\scriptsize ${\\pm}$2.58}\\\\\n\t\t& +unsigned & 4.42 & 6.58 {\\color{gray}\\scriptsize ${\\pm}$0.13} & 6.97 {\\color{gray}\\scriptsize ${\\pm}$0.28} & 7.49 {\\color{gray}\\scriptsize ${\\pm}$0.41} & 17.00 {\\color{gray}\\scriptsize ${\\pm}$2.77} & 54.57 {\\color{gray}\\scriptsize ${\\pm}$8.58} & 83.18 {\\color{gray}\\scriptsize ${\\pm}$3.94}\\\\\n\t\t& +rounded (= \\Quant) & 4.32 & 4.60 {\\color{gray}\\scriptsize ${\\pm}$0.08} & 5.10 {\\color{gray}\\scriptsize ${\\pm}$0.13} & 5.54 {\\color{gray}\\scriptsize ${\\pm}$0.2} & 11.28 {\\color{gray}\\scriptsize ${\\pm}$1.47} & 32.05 {\\color{gray}\\scriptsize ${\\pm}$6} & 68.65 {\\color{gray}\\scriptsize ${\\pm}$9.23}\\\\\n\t\t\\hline\n\t\t\\hline\n\t\t\\multirow{2}{*}{\\rotatebox{90}{$4$ bit}} & integer conversion & 5.81 & 90.46 {\\color{gray}\\scriptsize ${\\pm}$0.2} & 90.40 {\\color{gray}\\scriptsize ${\\pm}$0.21} & 90.39 {\\color{gray}\\scriptsize ${\\pm}$0.22} & 90.36 {\\color{gray}\\scriptsize ${\\pm}$0.2} & 90.36 {\\color{gray}\\scriptsize ${\\pm}$0.22} & 90.39 {\\color{gray}\\scriptsize ${\\pm}$0.22}\\\\\n\t\t& proper rounding & 5.29 & 5.49 {\\color{gray}\\scriptsize ${\\pm}$0.04} & 5.75 {\\color{gray}\\scriptsize ${\\pm}$0.06} & 5.99 {\\color{gray}\\scriptsize ${\\pm}$0.09} & 7.71 {\\color{gray}\\scriptsize ${\\pm}$0.36} & 10.62 {\\color{gray}\\scriptsize ${\\pm}$1.08} & 15.79 {\\color{gray}\\scriptsize ${\\pm}$2.54}\\\\\n\t\t\\hline\n\t\\end{tabular}\n\t\\vspace*{-0.1cm} \n\\end{table*}\n\nFor evaluation, we assume that the DNN weights are mapped linearly onto the memory of these chips. The bit error maps are of size $8192 \\times 128$ bits for chips 2 and 3 and $2048 \\times 128$ bits for chip 1. Furthermore, to simulate various different mappings, we repeat this procedure with various offsets and compute average \\RTE across all mappings. For results, we refer to \\appref{subsec:supp-randbet-baselines}.\n\n\\subsection{Bounding Generalization to Random Bit Errors}\n\\label{subsec:supp-bound}\n\nLet $w$ denote the final weights of a trained DNN $f$. We test $f$ using $n$ i.i.d. test examples, \\ie, $(x_i,y_i)_{i=1}^n$. We denote by $w'$ the weights where each bit of $w$ is flipped with probability $p$ uniformly at random, corresponding to the error model from \\secref{sec:errors}.\nThe expected \\emph{clean} error  of $f$ is given by\n\\begin{align*}\n\t\\Exp[\\Id_{f(x;w)\\neq y}] = \\Pr(f(x;w)\\neq y).\n\\end{align*}\nThe expected \\emph{robust} error (regarding i.i.d. test examples drawn from the data distribution) with random bit errors in the (quantized) weights is\n\\begin{align*}\n\t\\Exp[ \\Id_{f(x;w')\\neq y}] = \\Pr( f(x;w')\\neq y).\n\\end{align*}\nHere, the weights of the neural network are themselves random variables. Therefore, with $x, y, w$, and $w'$ we denote the random variables corresponding to test example, test label, weights and weights bit random bit errors. With $x_j, y_j, w_i$ and $w'_i$ we denote actual examples. Then, the following proposition derives a simple, probabilistic bound on the deviation of expected robust error from the empirically measured one (\\ie, \\RTE in our experiments):\n\n\\begin{table*}[t]\n\t\\centering\n\t\\small\n\t\\caption{\\textbf{Weight Clipping Improves Robustness.} We report \\TE and \\RTE for various experiments on the robustness of weight clipping with $\\wmax$, \\ie, \\Clipping[$\\wmax$]. First, we show that the robustness benefit of \\Clipping is independent of quantization-aware training, robustness also improves when applying post-training quantization. Then, we show results for both symmetric and asymmetric quantization. For the latter we demonstrate that label smoothing \\cite{SzegedyCVPR2016} reduces the obtained robustness. This supports our hypothesis that weight clipping, driven by minimizing cross-entropy loss during training, improves robustness through redundancy.}\n\t\\label{tab:supp-clipping}\n\t\\vspace*{-0.25cm}\n\t\\begin{tabular}{| c | l | c | c | c | c | c | c | c |}\n\t\t\\hline\n\t\t\\multicolumn{9}{|c|}{\\bfseries \\CifarT ($\\mathbf{m = 8}$ bit): clipping robustness for post- and during-training quantization}\\\\\n\t\t\\hline\n\t\t&Model & \\multirow{2}{*}{\\begin{tabular}{c}\\TE\\\\in \\%\\end{tabular}} & \\multicolumn{6}{c|}{\\RTE in \\%, $p$ in \\% p=0.01}\\\\\n\t\t\\cline{4-9}\n\t\t&&& $0.01$ & $0.05$ & $0.1$ & $0.5$ & $1$ & $1.5$\\\\\n\t\t\\hline\n\t\t\\hline\n\t\t\\multirow{6}{*}{\\rotatebox{90}{\\begin{tabular}{@{}c@{}}Post-Training\\\\Asymmetric\\end{tabular}}} & \\Normal & 4.37 & 4.95 {\\color{gray}\\scriptsize ${\\pm}$0.11} & 5.47 {\\color{gray}\\scriptsize ${\\pm}$0.17} & 6.03 {\\color{gray}\\scriptsize ${\\pm}$0.22} & 15.42 {\\color{gray}\\scriptsize ${\\pm}$3.4} & 51.83 {\\color{gray}\\scriptsize ${\\pm}$9.92} & 81.74 {\\color{gray}\\scriptsize ${\\pm}$5.14}\\\\\n\t\t& \\Quant & 4.27 & 4.59 {\\color{gray}\\scriptsize ${\\pm}$0.08} & 5.10 {\\color{gray}\\scriptsize ${\\pm}$0.13} & 5.54 {\\color{gray}\\scriptsize ${\\pm}$0.15} & 10.59 {\\color{gray}\\scriptsize ${\\pm}$1.11} & 30.58 {\\color{gray}\\scriptsize ${\\pm}$6.05} & 63.72 {\\color{gray}\\scriptsize ${\\pm}$6.89}\\\\\n\t\t& \\Clipping[$0.25$] & 4.96 & 5.24 {\\color{gray}\\scriptsize ${\\pm}$0.07} & 5.73 {\\color{gray}\\scriptsize ${\\pm}$0.14} & 6.16 {\\color{gray}\\scriptsize ${\\pm}$0.21} & 10.51 {\\color{gray}\\scriptsize ${\\pm}$0.91} & 26.27 {\\color{gray}\\scriptsize ${\\pm}$5.65} & 61.49 {\\color{gray}\\scriptsize ${\\pm}$9.03}\\\\\n\t\t& \\Clipping[$0.2$] & 5.24 & 5.48 {\\color{gray}\\scriptsize ${\\pm}$0.05} & 5.87 {\\color{gray}\\scriptsize ${\\pm}$0.09} & 6.23 {\\color{gray}\\scriptsize ${\\pm}$0.13} & 9.47 {\\color{gray}\\scriptsize ${\\pm}$0.7} & 19.78 {\\color{gray}\\scriptsize ${\\pm}$3.58} & 43.64 {\\color{gray}\\scriptsize ${\\pm}$8.2}\\\\\n\t\t& \\Clipping[$0.15$] & 5.38 & 5.63 {\\color{gray}\\scriptsize ${\\pm}$0.05} & 6.03 {\\color{gray}\\scriptsize ${\\pm}$0.09} & 6.38 {\\color{gray}\\scriptsize ${\\pm}$0.13} & 8.80 {\\color{gray}\\scriptsize ${\\pm}$0.41} & 15.74 {\\color{gray}\\scriptsize ${\\pm}$2.24} & 36.29 {\\color{gray}\\scriptsize ${\\pm}$7.34}\\\\\n\t\t& \\Clipping[$0.1$] & 5.32 & 5.52 {\\color{gray}\\scriptsize ${\\pm}$0.04} & 5.82 {\\color{gray}\\scriptsize ${\\pm}$0.06} & 6.05 {\\color{gray}\\scriptsize ${\\pm}$0.07} & 7.45 {\\color{gray}\\scriptsize ${\\pm}$0.26} & 9.80 {\\color{gray}\\scriptsize ${\\pm}$0.62} & 17.56 {\\color{gray}\\scriptsize ${\\pm}$3.08}\\\\\n\t\t\\hline\n\t\t\\hline\n\t\t\\multirow{7}{*}{\\rotatebox{90}{\\begin{tabular}{@{}c@{}}Symmetric\\\\(during training)\\end{tabular}}} & \\Normal & 4.36 & 4.82 {\\color{gray}\\scriptsize ${\\pm}$0.07} & 5.51 {\\color{gray}\\scriptsize ${\\pm}$0.19} & 6.37 {\\color{gray}\\scriptsize ${\\pm}$0.32} & 24.76 {\\color{gray}\\scriptsize ${\\pm}$4.71} & 72.65 {\\color{gray}\\scriptsize ${\\pm}$6.35} & 87.40 {\\color{gray}\\scriptsize ${\\pm}$2.47}\\\\\n\t\t& \\Quant & 4.39 & 4.77 {\\color{gray}\\scriptsize ${\\pm}$0.08} & 5.43 {\\color{gray}\\scriptsize ${\\pm}$0.21} & 6.10 {\\color{gray}\\scriptsize ${\\pm}$0.32} & 17.11 {\\color{gray}\\scriptsize ${\\pm}$3.07} & 55.35 {\\color{gray}\\scriptsize ${\\pm}$9.4} & 82.84 {\\color{gray}\\scriptsize ${\\pm}$4.52}\\\\\n\t\t& \\Clipping[$0.25$] & 4.63 & 4.99 {\\color{gray}\\scriptsize ${\\pm}$0.07} & 5.53 {\\color{gray}\\scriptsize ${\\pm}$0.1} & 6.06 {\\color{gray}\\scriptsize ${\\pm}$0.16} & 13.55 {\\color{gray}\\scriptsize ${\\pm}$1.42} & 41.64 {\\color{gray}\\scriptsize ${\\pm}$7.35} & 73.39 {\\color{gray}\\scriptsize ${\\pm}$7.15}\\\\\n\t\t& \\Clipping[$0.2$] & 4.50 & 4.79 {\\color{gray}\\scriptsize ${\\pm}$0.06} & 5.25 {\\color{gray}\\scriptsize ${\\pm}$0.09} & 5.65 {\\color{gray}\\scriptsize ${\\pm}$0.16} & 9.64 {\\color{gray}\\scriptsize ${\\pm}$0.99} & 21.37 {\\color{gray}\\scriptsize ${\\pm}$4.23} & 45.68 {\\color{gray}\\scriptsize ${\\pm}$7.9}\\\\\n\t\t& \\Clipping[$0.15$] & 5.18 & 5.42 {\\color{gray}\\scriptsize ${\\pm}$0.05} & 5.76 {\\color{gray}\\scriptsize ${\\pm}$0.08} & 6.07 {\\color{gray}\\scriptsize ${\\pm}$0.09} & 8.36 {\\color{gray}\\scriptsize ${\\pm}$0.43} & 13.80 {\\color{gray}\\scriptsize ${\\pm}$1.45} & 24.70 {\\color{gray}\\scriptsize ${\\pm}$3.77}\\\\\n\t\t& \\Clipping[$0.1$] & 4.86 & 5.07 {\\color{gray}\\scriptsize ${\\pm}$0.04} & 5.34 {\\color{gray}\\scriptsize ${\\pm}$0.06} & 5.59 {\\color{gray}\\scriptsize ${\\pm}$0.1} & 7.12 {\\color{gray}\\scriptsize ${\\pm}$0.3} & 9.44 {\\color{gray}\\scriptsize ${\\pm}$0.7} & 13.14 {\\color{gray}\\scriptsize ${\\pm}$1.79}\\\\\n\t\t& \\Clipping[$0.05$] & 5.56 & 5.70 {\\color{gray}\\scriptsize ${\\pm}$0.03} & 5.89 {\\color{gray}\\scriptsize ${\\pm}$0.06} & 6.03 {\\color{gray}\\scriptsize ${\\pm}$0.08} & 6.68 {\\color{gray}\\scriptsize ${\\pm}$0.14} & 7.31 {\\color{gray}\\scriptsize ${\\pm}$0.2} & 8.06 {\\color{gray}\\scriptsize ${\\pm}$0.36}\\\\\n\t\t\\hline\n\t\t\\hline\n\t\t\\multirow{11}{*}{\\rotatebox{90}{\\begin{tabular}{@{}c@{}}{\\color{red}\\textbf{A}}symmetric (default) quant.\\\\(during training)\\end{tabular}}} & \\Normal & 4.36 & 4.82 {\\color{gray}\\scriptsize ${\\pm}$0.07} & 5.51 {\\color{gray}\\scriptsize ${\\pm}$0.19} & 6.37 {\\color{gray}\\scriptsize ${\\pm}$0.32} & 24.76 {\\color{gray}\\scriptsize ${\\pm}$4.71} & 72.65 {\\color{gray}\\scriptsize ${\\pm}$6.35} & 87.40 {\\color{gray}\\scriptsize ${\\pm}$2.47}\\\\\n\t\t& \\Quant & 4.32 & 4.60 {\\color{gray}\\scriptsize ${\\pm}$0.08} & 5.10 {\\color{gray}\\scriptsize ${\\pm}$0.13} & 5.54 {\\color{gray}\\scriptsize ${\\pm}$0.2} & 11.28 {\\color{gray}\\scriptsize ${\\pm}$1.47} & 32.05 {\\color{gray}\\scriptsize ${\\pm}$6} & 68.65 {\\color{gray}\\scriptsize ${\\pm}$9.23}\\\\\n\t\t& \\Clipping[$0.25$] & 4.58 & 4.84 {\\color{gray}\\scriptsize ${\\pm}$0.05} & 5.29 {\\color{gray}\\scriptsize ${\\pm}$0.12} & 5.71 {\\color{gray}\\scriptsize ${\\pm}$0.16} & 10.52 {\\color{gray}\\scriptsize ${\\pm}$1.14} & 27.95 {\\color{gray}\\scriptsize ${\\pm}$4.16} & 62.46 {\\color{gray}\\scriptsize ${\\pm}$8.89}\\\\\n\t\t& \\Clipping[$0.2$] & 4.63 & 4.91 {\\color{gray}\\scriptsize ${\\pm}$0.05} & 5.28 {\\color{gray}\\scriptsize ${\\pm}$0.08} & 5.62 {\\color{gray}\\scriptsize ${\\pm}$0.11} & 8.27 {\\color{gray}\\scriptsize ${\\pm}$0.35} & 18.00 {\\color{gray}\\scriptsize ${\\pm}$2.84} & 53.74 {\\color{gray}\\scriptsize ${\\pm}$8.89}\\\\\n\t\t& \\Clipping[$0.15$] & 4.42 & 4.66 {\\color{gray}\\scriptsize ${\\pm}$0.05} & 5.01 {\\color{gray}\\scriptsize ${\\pm}$0.09} & 5.31 {\\color{gray}\\scriptsize ${\\pm}$0.12} & 7.81 {\\color{gray}\\scriptsize ${\\pm}$0.6} & 13.08 {\\color{gray}\\scriptsize ${\\pm}$2.21} & 23.85 {\\color{gray}\\scriptsize ${\\pm}$5.07}\\\\\n\t\t& \\Clipping[$0.1$] & 4.82 & 5.04 {\\color{gray}\\scriptsize ${\\pm}$0.04} & 5.33 {\\color{gray}\\scriptsize ${\\pm}$0.07} & 5.58 {\\color{gray}\\scriptsize ${\\pm}$0.1} & 6.95 {\\color{gray}\\scriptsize ${\\pm}$0.24} & 8.93 {\\color{gray}\\scriptsize ${\\pm}$0.46} & 12.22 {\\color{gray}\\scriptsize ${\\pm}$1.29}\\\\\n\t\t& \\Clipping[$0.05$] & 5.44 & 5.59 {\\color{gray}\\scriptsize ${\\pm}$0.04} & 5.76 {\\color{gray}\\scriptsize ${\\pm}$0.07} & 5.90 {\\color{gray}\\scriptsize ${\\pm}$0.07} & 6.53 {\\color{gray}\\scriptsize ${\\pm}$0.13} & 7.18 {\\color{gray}\\scriptsize ${\\pm}$0.16} & 7.92 {\\color{gray}\\scriptsize ${\\pm}$0.25}\\\\\n\t\t\\cline{2-9} \n\t\t& \\Clipping[$0.2$]+LS & 4.48 & 4.77 {\\color{gray}\\scriptsize ${\\pm}$0.05} & 5.19 {\\color{gray}\\scriptsize ${\\pm}$0.1} & 5.55 {\\color{gray}\\scriptsize ${\\pm}$0.12} & 9.46 {\\color{gray}\\scriptsize ${\\pm}$0.82} & 32.49 {\\color{gray}\\scriptsize ${\\pm}$5.07} & 68.60 {\\color{gray}\\scriptsize ${\\pm}$7.33}\\\\\n\t\t& \\Clipping[$0.15$]+LS & 4.67 & 4.86 {\\color{gray}\\scriptsize ${\\pm}$0.05} & 5.23 {\\color{gray}\\scriptsize ${\\pm}$0.08} & 5.83 {\\color{gray}\\scriptsize ${\\pm}$0.12} & 7.99 {\\color{gray}\\scriptsize ${\\pm}$0.43} & 29.40 {\\color{gray}\\scriptsize ${\\pm}$6.99} & 68.99 {\\color{gray}\\scriptsize ${\\pm}$8.48}\\\\\n\t\t& \\Clipping[$0.1$]+LS & 4.82 & 5.05 {\\color{gray}\\scriptsize ${\\pm}$0.04} & 5.37 {\\color{gray}\\scriptsize ${\\pm}$0.08} & 6.10 {\\color{gray}\\scriptsize ${\\pm}$0.11} & 7.36 {\\color{gray}\\scriptsize ${\\pm}$0.4} & 10.59 {\\color{gray}\\scriptsize ${\\pm}$1.01} & 18.31 {\\color{gray}\\scriptsize ${\\pm}$2.84}\\\\\n\t\t& \\Clipping[$0.05$]+LS & 5.30 & 5.43 {\\color{gray}\\scriptsize ${\\pm}$0.03} & 5.63 {\\color{gray}\\scriptsize ${\\pm}$0.06} & 6.43 {\\color{gray}\\scriptsize ${\\pm}$0.07} & 6.51 {\\color{gray}\\scriptsize ${\\pm}$0.15} & 7.30 {\\color{gray}\\scriptsize ${\\pm}$0.23} & 8.06 {\\color{gray}\\scriptsize ${\\pm}$0.38}\\\\\n\t\t\\hline\n\t\\end{tabular}\n\t\\vspace*{-0.1cm}\n\\end{table*}\n\n\\begin{proposition}\n\t\\label{prop:bound}\n\tLet $w'_i$, $i = 1,\\ldots,l$ be $l$ examples of weights bit random bit errors (each bit flipped with probability $p$). Then it holds\n\t\\begin{align*}\n\t\t\\Pr\\Big( \\frac{1}{nl}&\\sum_{j=1}^n \\sum_{i=1}^l \\Id_{f(x_j;w'_i)\\neq y_j} - \\Pr(f(x;w')\\neq y)\\geq \\epsilon\\Big)\\\\\n\t\t&\\quad\\leq (n+1) e^{-n\\epsilon^2 \\frac{l}{(\\sqrt{l}+\\sqrt{n})^2}}.\n\t\\end{align*}\n\tAs alternative formulation, with probability $1-\\delta$ it holds\n\t\\begin{align*}\n\t\t\\Pr( f(x; w'_i)\\neq y) < & \\frac{1}{nl}\\sum_{j=1}^n \\sum_{i=1}^l \\Id_{f(x_j; w'_i)\\neq y_j}\\\\ &+ \\quad \\leq\\sqrt{\\frac{\\log\\Big(\\frac{n+1}{\\delta}\\Big)}{n}} \\frac{\\sqrt{l}+\\sqrt{n}}{\\sqrt{l}}.\n\t\\end{align*} \n\\end{proposition}\n{\\small\n\\begin{proof}\nLet $0<\\alpha<1$. Using the Hoeffding inequality and union bound, we have:\n\\begin{align*}\n\t&\\Pr\\Big(\\maxop_{j=1,\\ldots,n} \\frac{1}{l}\\sum_{i=1}^l \\Id_{f(x_j; w'_i)\\neq y_j} - \\Exp_{w'}[\\Id_{f(x_j; w')\\neq y_j}] > \\alpha\\epsilon\\Big) \\\\\n\t=& \\Pr\\Big(\\bigcup_{j=1,\\ldots,n}\\big\\{ \\frac{1}{l}\\sum_{i=1}^l \\Id_{f(x_j; w'_i)\\neq y_j} - \\Exp_{w'}[\\Id_{f(x_j; w')\\neq y_j}] > \\alpha\\epsilon\\big\\}\\Big)\\\\\n\t&\\leq \\; n\\, e^{-l\\alpha^2 \\epsilon^2}.\n\\end{align*}\nThen, again by Hoeffding's inequality, it holds:\n\\begin{align*}\n\t&\\Pr\\Big( \\frac{1}{n}\\sum_{j=1}^n \\Exp_{w'}[\\Id_{f(x_j; w')\\neq y_j}]\n\t- \\Exp_{x,y}[\\Exp_{w'}[\\Id_{f(x; w')\\neq y}]] > (1-\\alpha) \\epsilon \\Big)\\\\\n\t&\\leq \\; e^{-n\\epsilon^2 (1-\\alpha)^2}.\n\\end{align*}\nThus, using\n\\begin{align*}\n\ta + b>\\epsilon \\Longrightarrow \\{a > \\alpha \\epsilon\\} \\cup \\{b > (1-\\alpha)\\epsilon\\}\n\\end{align*}\ngives us:\n\\begin{align*}\n\t&\\Pr\\Big( \\frac{1}{nl}\\sum_{j=1}^n \\sum_{i=1}^l \\Id_{f(x_j; w'_i)\\neq y_j} - \\Pr( f(x; w')\\neq y)\\geq \\epsilon\\Big)\\\\\n\t=& \\Pr\\Big( \\frac{1}{n}\\sum_{j=1}^n \\big(\\frac{1}{l}\\sum_{i=1}^l \\Id_{f_{w'_i}(x_j)\\neq y_j} - \\Exp_{w'}[\\Id_{f(x_j; w'_i)\\neq y_j}]\\big)\\\\\n\t +& \\frac{1}{n}\\sum_{j=1}^n \\Exp_{w'}[\\Id_{f(x_j; w'_i)\\neq y_j}] - \\Pr( f(x; w')\\neq y)\\geq \\epsilon\\Big)\\\\\n\t\\leq & \\Pr\\Big( \\frac{1}{n}\\sum_{j=1}^n \\big(\\frac{1}{l}\\sum_{i=1}^l \\Id_{f(x_j; w'_i)\\neq y_j} - \\Exp_{w'}[\\Id_{f(x_j; w')\\neq y_j}]\\big)>\\alpha \\epsilon\\Big)\\\\\n\t+& \\Pr\\Big( \\frac{1}{n}\\sum_{j=1}^n \\Exp_{w'}[\\Id_{f(x_j; w')\\neq y_j}] - \\Pr( f(x; w')\\neq y)\\geq (1-\\alpha)\\epsilon\\Big)\\\\\n\t\\leq &  n\\, e^{-l\\alpha^2 \\epsilon^2} + e^{-n\\epsilon^2 (1-\\alpha)^2} \n\\end{align*}\nHaving both exponential terms have the same exponent yields $\\alpha=\\frac{\\sqrt{n}}{\\sqrt{l}+\\sqrt{n}}$ and we get the upper bound of the proposition.\n\\end{proof}\n}\n\n\\textbf{Remarks:}\nThe samples of bit error injected weights $\\{w'_i\\}_{i=1}^l$ can actually be different for any test example $(x_j, y_j)$, even though this is not the case in our evaluation. Thus, the above bound involves a stronger result: for any test example, the empirical test error with random bit errors (\\ie, robust test error \\RTE) and the expected one have to be similar with the same margin. Note also that this bound holds for any fixed bit error distribution as the only requirement is that the bit error patterns we draw are i.i.d. but not the bit errors on the pattern.\nIn \\appref{subsec:experiments-stress}, we consider results with $l = 10^6$, \\ie, $l \\gg n$ with $n = 10^4$ on \\CifarT such that $\\nicefrac{l}{(\\sqrt{l}+\\sqrt{n})^2}$ tends towards one. With $\\delta=0.99$ the excess term $\\sqrt{\\frac{\\log\\Big(\\frac{n+1}{\\delta}\\Big)}{n}} \\frac{\\sqrt{l}+\\sqrt{n}}{\\sqrt{l}}$ in the Proposition is equal to $4.1\\%$. Thus larger test sets would be required to get stronger guarantees e.g. for $n=10^5$ one would get $1.7\\%$.\n\n\\section{Quantization and Bit Manipulation in PyTorch}\n\\label{sec:supp-implementation}\n\nOur fixed-point quantization $Q$ in \\eqnref{eq:quantization} quantizes weights $w_i \\in [-\\qmax, \\qmax] \\subset \\mathbb{R}$ into signed integers $\\{-2^{m-1}-1,\\ldots,2^{m-1}-1\\}$. Here, the quantization range $[-\\qmax,\\qmax]$ is symmetric around zero. Note that zero is represented exactly. To implement asymmetric quantization, as outlined in \\secref{subsec:robustness-quantization}, the same scheme can be used to quantize weights $w_i \\in [\\qmin, \\qmax]$ within any arbitrary, potentially asymmetric, interval. To this end, \\eqnref{eq:quantization} with $\\qmax = 1$ is used and the weights in $[\\qmin,\\qmax]$ are mapped linearly to $[-1, 1]$ using the transformation $N$:\n\\begin{align}\n\tN(w_i) = \\left(\\frac{w_i - \\qmin}{\\qmax - \\qmin}\\right)\\cdot 2 - 1.\\label{eq:asymmetric-quantization}\n\\end{align}\nGenerally, $\\qmin$ and $\\qmax$ are chosen to reflect minimum and maximum weight value -- either from all weights (global quantization) or per-layer.\nFurthermore, we argue that asymmetric quantization becomes more robust when using \\emph{unsigned} integers as representation. In this case, \\eqnref{eq:quantization} can be adapted using a simple additive term:\n\\begin{align}\n\t\\begin{split}\n\t\tQ(w_i) &= \\left\\lceil \\frac{w_i}{\\Delta}\\right\\rfloor + (2^{m - 1} - 1)\\\\\n\t\tQ^{-1}(v_i) &= \\Delta (v_i - (2^{m - 1} - 1))\n\t\\end{split}\\label{eq:unsigned-quantization}\n\\end{align}\nWe use asymmetric quantization using $N$ in \\eqnref{eq:asymmetric-quantization} with \\eqnref{eq:unsigned-quantization} as our \\emph{robust} fixed-point quantization.\n\n\\begin{table}[t]\n\t\\centering\n\t\\small\n\t\\caption{\\textbf{Batch Normalization not Robust.} \\RTE with group normalization (GN) or batch normalization (BN). \\RTE increases when using BN even though clean \\TE improves slightly compared GN. However, using batch statistics at test time (\\ie, ``training mode'' in PyTorch) improves \\RTE significantly indicating that the statistics accumulated throughout training do not account for random bit errors. We use \\textbf{group normalization as default.}}\n\t\\label{tab:supp-bn}\n\t\\vspace*{-0.25cm}\n\t\\hspace*{-0.25cm}\n\t\\begin{tabular}{| c | l | c | c | c |}\n\t\t\\hline\n\t\t\\multicolumn{5}{|c|}{\\bfseries \\CifarT ($\\mathbf{m = 8}$ bit): robustness of BN}\\\\\n\t\t\\hline\n\t\t&& \\multirow{2}{*}{\\begin{tabular}{@{}c@{}}\\TE\\\\in \\%\\end{tabular}} & \\multicolumn{2}{c|}{\\RTE in \\%}\\\\\n\t\t\\hline\n\t\t&& & $p{=}0.1$ & $p{=}0.5$\\\\\n\t\t\\hline\n\t\t\\hline\n\t\t\\multirow{2}{*}{GN} & \\Normal & 4.32 & 5.54 & 11.28\\\\\n\t\t& \\Clipping[$0.1$] & 4.82 & 5.58 & 6.95\\\\\n\t\t\\hline\n\t\t\\hline\n\t\t\\multicolumn{5}{|c|}{\\textbf{BN w/ \\emph{Accumulated} Statistics}}\\\\\n\t\t\\hline\n\t\t\\multirow{2}{*}{BN} & \\Normal & 3.83 & 6.36 & 52.52\\\\\n\t\t& \\Clipping[$0.1$] & 4.46 & 5.32 & 8.25\\\\\n\t\t\\hline\n\t\t\\hline\n\t\t\\multicolumn{5}{|c|}{\\textbf{BN w/ Batch Statistics at Test Time}}\\\\\n\t\t\\hline\n\t\t\\multirow{2}{*}{BN} & \\Normal & 3.83 & 6.65 & 9.63\\\\\n\t\t& \\Clipping[$0.1$] & 4.46 & 6.57 & 7.29\\\\\n\t\t\\hline\n\t\\end{tabular}\n\t\\vspace*{-0.1cm}\n\\end{table}\n\nFollowing \\secref{subsec:robustness-quantization}, we implement ``fake'' fixed-point quantization for quantization-aware training and bit error injection directly in PyTorch \\cite{PaszkeNIPSWORK2017}. Here, fake quantization means that computation is performed in floating point, but before doing a forward pass, the DNN is quantized and dequantized, \\ie, $w_q = Q^{-1}(Q(w))$ in \\algref{alg:training}. Note that we quantize into \\emph{unsigned} $8$ bit integers, irrespective of the target precision $m \\leq 8$. To later induce random bit errors, the $8 - m$ most significant bits (MSBs) are masked for $m < 8$. Bit manipulation of unsigned $8$ bit integers is then implemented in C/CUDA and interfaced to Python using CuPy \\cite{cupy} or CFFI \\cite{cffi}. These functions can directly operate on PyTorch tensors, allowing bit manipulation on the CPU as well as the GPU. We will make our code publicly available to faciliate research into DNN robustness against random bit errors.\n\n\\section{Weight Clipping with Group/Batch Normalization}\n\\label{sec:supp-clipping}\n\nWhile weight clipping, \\ie, globally constraining weights to $[-\\wmax, \\wmax]$ during training, is easy to implement, we make a simple adjustment to group and batch normalization layers: we reparameterize the scale parameter $\\alpha$ of batch/group normalization, which usually defaults to $\\alpha = 1$ and may cause problems when clipped, \\eg, to $[-0.1, 0.1]$. In particular with aggressive weight clipping, $\\alpha \\leq \\wmax < 1$, the normalization layers loose their ability to represent the identity function, considered important for batch normalization in \\cite{IoffeICML2015}. Our reparameterization introduces a learnable, auxiliary parameter $\\alpha'$ such that $\\alpha$ as $\\alpha = 1 + \\alpha'$ to solve this problem.", "meta": {"hexsha": "5b7e9632f6fc2d1433909ead24d520da3622e816", "size": 28897, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/supp_main.tex", "max_stars_repo_name": "davidstutz/mlsys2021-bit-error-robustness", "max_stars_repo_head_hexsha": "3d9c4d6c3bab61c75201f758a40937768ea18b99", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paper/supp_main.tex", "max_issues_repo_name": "davidstutz/mlsys2021-bit-error-robustness", "max_issues_repo_head_hexsha": "3d9c4d6c3bab61c75201f758a40937768ea18b99", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/supp_main.tex", "max_forks_repo_name": "davidstutz/mlsys2021-bit-error-robustness", "max_forks_repo_head_hexsha": "3d9c4d6c3bab61c75201f758a40937768ea18b99", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 92.3226837061, "max_line_length": 981, "alphanum_fraction": 0.6585804755, "num_tokens": 11143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.30736334118347786}}
{"text": "\\chapter{Background}\\label{chap:background}\n\nImagine the following task between two players, Anne and Bill. Between Anne and Bill is a lever in the middle position and has five positions in total. Anne thinks the lever should be pulled two positions to her side and Bill thinks the lever should be pulled two positions to his side.\nAnne does not know Bill has a goal on his side, and Bill does not know Anne has a goal on her side.\nThis can be seen in figure \\ref{leverexample}.\\\\\n\\input{figures/pictures/Hebelbild} \\\\\n\nWith the asynchronous execution order this task could be easily finished if Anne or Bill just pulled the lever two times in their direction. But just as easily this task could go on a really long time if Anne and Bill pulled the lever alternating, once to the right and then to the left, then to the right again and so on. This could go on infinitely. With no set execution order, how can we prevent the task from going on infinitely? To answer this question we first need to introduce the formal framework.\n\n\\section{Dynamic Epistemic Logic}\nIn the following we will define and explain the core concepts of the Dynamic Epistemic Logic (DEL). DEL is a specific mathematical language used as the framework of this thesis.\n\nThe definitions are taken from the work of Bolander et al. \\cite{bolander2018better} and \\cite{bolander2017gentle} and the book ``Dynamic epistemic logic'' from Ditmarsch \\cite{Ditmarsch2007}.\n\nLet $\\mathcal{A}$ be a finite set of agents, from the example above this would be $\\mathcal{A} =\\{$Anne, Bill$\\}$. Let $\\mathcal{P}$ be a finite set of atomic propositions. Atomic propositions, like $p$ or $q$, describe some affairs that can be true or false.\nThe epistemic language $\\mathcal{L}_{\\text{KC}}$ is: \\\\\n$$\n\\varphi ::= \\top \\ | \\ \\bot \\ | \\ p \\ | \\ \\neg \\varphi \\ | \\ \\varphi \\wedge \\varphi \\ | \\ K_i \\varphi \\ | \\ C\\varphi\n$$\n\nwith $p \\in \\mathcal{P}$ and $i \\in \\mathcal{A}$.\n$\\top$ describes $\\varphi$ as being true, $\\bot$ as false.\n$K_i \\varphi$ reads as ``Agent $i$ knows $\\varphi$''. $C \\varphi$ reads as ``it is common knowledge that $\\varphi$ ''.\\\\\nFrom the example before, the two agents, $a$ (Anne) and $b$ (Bill) have two goal positions, goal $p$ (lever to the left) and $q$ (lever to the right). Anne knows that one goal position is the left, but does not know the other: $K_a p \\wedge \\neg K_a q$ . Bill knows that one goal position is the right, but does not know the other position: $\\neg K_b  p \\wedge K_b q$.\n\n\nFormulas are evaluated in epistemic models %\\todo{not defined}\n$$\n\\mathcal{M}=(W, (\\sim_i)_{i \\in \\mathcal{A}}, V)\n$$\nwith the domain $W$ being a nonempty finite set of worlds,\n$\\sim_i$ being an equivalence relation called the indistinguishably relation for agent $i \\in \\mathcal{A}$ and $V : \\mathcal{P} \\rightarrow \\mathcal{P}(W)$ assigning a valuation to each atomic proposition.\n\n\nUsing Anne and Bill as an example, Anne only knows $p$ is true. She does not know if $p \\land q$ or $p \\land \\neg q$, so she sees two worlds. Those two worlds are indistinguishable for Anne. Bill only knows $q$ is true, he does not know if $p \\land q$ or $\\neg p \\land q$. One world where just the lever to the left is a goal, a world where another goal is the lever to the right and a world where just the lever to the right is a goal. Let $w_1$ be the world where just the lever to the left is a goal, $w_2$ be the world where the goal is the lever to the left or to the right and $w_3$ be the world where the goal is the lever to the right. Then $w_1 \\sim_\\text{Anne} w_2$ and $w_2 \\sim_\\text{Bill} w_3$. A graphic representation of this would be the global state $s = (\\mathcal{M}, w_2)$ with the nodes representing the worlds and the edges representing the indistinguishably relation. The circle around a node represent designated worlds. In all graphic representations in this thesis we usually omit reflexive edges and edges that can be implied by transivity for better readability.\n\\[\ns=\n\\begin{tikzpicture}\n  \\draw (-2,0) node[world, label=below:{$w_1: p, \\neg q$}] (w1) {};\n  \\draw (0,0) node [desig] {}; % designation\n  \\draw (0,0) node[world, label=below:{$w_2: p,q$}] (w2) {};\n  \\draw (2,0) node[world, label=below:{$w_3: \\neg p, q$}] (w3) {};\n  \\draw (w1) -- node[above] {Anne} (w2);\n  \\draw (w2) -- node[above] {Bill} (w3);\n\\end{tikzpicture}\n\\]\n\n\nFor $W_d \\subseteq W$, the pair $(\\mathcal{M}, W_d)$ is called an epistemic state (or simply a state) and the worlds of $W_d$ are called designated worlds. A state is called global if $W_d=\\{w\\}$ for some world $w$ (called the actual world). We then often write $(\\mathcal{M},w)$ instead of $(\\mathcal{M},\\{w\\} )$. We use $S^{gl}(P,\\mathcal{A})$ to denote the set of global states (or simply $S^{gl}$ if $P$ and $\\mathcal{A}$ are clear from context). For any state $ s=(\\mathcal{M}, W_d) $ we let $Globals(s)= \\{ (\\mathcal{M},w) | w \\in W_d \\} $.\nA state $(\\mathcal{M}, W_d)$ is called a local state for agent $i$ if $W_d$ is closed under $\\sim _i$ (that is, if $w \\in W_d$ and $w \\sim _i v $, then $v \\in W_d$).\nGiven a state $s=(\\mathcal{M}, W_d)$ the associated local state of agent $i$, denoted $s^i$, is $(\\mathcal{M},\\{v|v\\sim _i w \\text{ and } w \\in W_d\\})$. Going from $s$ to $s^i$ amounts to a \\textit{perspective shift} to the local perspective of agent $i$.\n\n\nIn the example above, Anne has the local state $s^{\\text{Anne}}=(\\mathcal{M},\\{w_1,w_2\\})$ and Bill has the local state $s^{\\text{Bill}}=(\\mathcal{M},\\{w_2,w_3\\})$.\n\n\nLet $(\\mathcal{M}, W_d)$ be a state on $P,\\mathcal{A}$ with $\\mathcal{M}=(W, (\\sim_i)_{i \\in \\mathcal{A}}, V)$. For $i \\in \\mathcal{A}$, $p \\in P$ and $\\varphi, \\psi \\in \\mathcal{L}_{\\text{KC}}(P,\\mathcal{A})$, we define truth as follows:\n\\begin{align*}\n  &(\\mathcal{M}, W_d) \\models \\varphi\n    & &\\text{ iff } \\qquad\n    (\\mathcal{M},w)\\models \\varphi \\text{ for all } w \\in W_d \\\\\n  &(\\mathcal{M}, w) \\models p\n    & &\\text{ iff } \\qquad\n    w \\in V(p) \\\\\n  &(\\mathcal{M}, w) \\models \\neg \\varphi\n    & &\\text{ iff } \\qquad\n    (\\mathcal{M},w) \\not\\models \\varphi \\\\\n  &(\\mathcal{M}, w) \\models \\varphi \\wedge \\psi\n    & &\\text{ iff } \\qquad\n    (\\mathcal{M},w) \\models \\varphi \\text{ and } (\\mathcal{M},w) \\models \\psi \\\\\n  &(\\mathcal{M}, w) \\models K_i \\varphi\n    & &\\text{ iff } \\qquad\n    (\\mathcal{M},v) \\models \\varphi \\text{ for all } v \\sim_i w \\\\\n  &(\\mathcal{M}, w) \\models C \\varphi\n    & &\\text{ iff } \\qquad\n    (\\mathcal{M},v) \\models \\varphi \\text{ for all } v \\sim^* w \\\\\n  &(\\mathcal{M}, w) \\models \\top\n    & &\\text{        } \\qquad\n    \\text{always} \\\\\n  &(\\mathcal{M}, w) \\models \\bot\n    & &\\text{        } \\qquad\n    \\text{never}\n\\end{align*}\nwhere $\\sim^*$ is the transitive closure of $\\bigcup_{i \\in \\mathcal{A}}\\sim_i$.\n\n\nFrom the example above, in $(\\mathcal{M},w_2)$, $w_2$ is the designated world. In this designated world, Anne still does not know if $q$ is true or not. $(\\mathcal{M},w_2) \\models \\neg K_aq \\wedge \\neg K_a \\neg q$.\nPerforming a perspective sift on $s=(\\mathcal{M},w_2)$ for Anne is $(\\mathcal{M},w_2)^{\\text{Anne}} =(\\mathcal{M},\\{w_1,w_2\\})$. This perspective shift gives us $(\\mathcal{M},\\{w_1,w_2\\})\\not\\models q$ and $(\\mathcal{M},\\{w_1,w_2\\})\\not\\models \\neg q$. This way, we can verify the knowledge from the global world for an agent by performing a perspective shift for that agent.\n\n\n\\subsection{Epistemic Actions and Product Updates}\n\nAn event model is a 4-tuple $\\mathcal{E} = \\langle E, (\\sim_i)_{i\\in \\mathcal{A}}, pre, \\textit{eff}  \\rangle$ where the domain $E$ is a non-empty finite set of events; $\\sim_i \\subseteq E \\times E$ is an equivalence relation called the indistinguishably relation for agent $i$;\n$pre:E \\rightarrow \\mathcal{L}_{KC}$ assigns a precondition to each event;\nand $\\textit{eff}:E \\rightarrow \\mathcal{L}_{KC}$ assigns a post condition, or effect to each event.\nFor all $e\\in E$, $\\textit{eff}(e)$ is a conjunction of literals, that means atomic propositions and their negations, including $\\top$ and $\\bot$.\\\\\nFor $E_d \\subseteq E$, the pair $(\\mathcal{E}, E_d)$ is called an epistemic action, or simply action and the events in $E_d$ are called a local action for agent $i$ when $E_d$ is closed under $\\sim_i$. \\\\\nEach event of an action represents a different possible outcome.\nBy using multiple events $e, e' \\in E$ that are indistinguishable ($e \\sim e' )$, it is possible to model only partially observable actions.\\\\\nIf the event model has $E=\\{e\\}$, we will write $\\mathcal{E}=\\langle pre(e), \\textit{eff}(e)\\rangle$.\n\nThe product update is used to specify the next state resulting from performing an action in a state.\nLet a state $s = (\\mathcal{M},W_d)$ and an action $a=(\\mathcal{E},E_d)$ be given with $\\mathcal{M}=\\langle W,(\\sim_i)_{i \\in \\mathcal{A}}, V\\rangle $ and $\\mathcal{E}=\\langle E, (\\sim_i)_{i \\in \\mathcal{A}},pre, \\textit{eff} \\rangle$\nthen the product update of $s$ with $a$ is defined as $s \\otimes a = ((W',(\\sim_i')_{i \\in \\mathcal{A}}, W_d'))$ where :\n\n \\begin{itemize}\n   \\item each world is paired up with all applicable events \\\\\n   $W'=\\{(w,e)\\in W \\times E ~|~ \\mathcal{M}, w \\models pre(e)\\};$\n   \\item new worlds are indistinguishable if the old worlds and the events are indistinguishable \\\\\n   $\\sim_i'=\\{((w,e),(w',e')) \\in W'\\times W' ~|~ w \\sim_i w' \\text{ and } e \\sim_i e'\\};$\n   \\item propositions become true if the proposition occurred as a positive literal in the effect of the event or the proposition was satisfied in the world before and did not appear negative in the effect \\\\\n   $V'(p) = \\{ (w,e) \\in W' ~|~ \\textit{eff}(e) \\models p \\text{ or } (\\mathcal{M},w \\models p \\text{ and } \\textit{eff}(e)\\not \\models \\neg p)\\};$\n   \\item worlds are designated if both predecessor world and event are designated. \\\\\n   $W_d' = \\{ (w,e) \\in W' ~|~ w \\in W_d \\text{ and } e \\in E_d\\}$.\n \\end{itemize}\n\n$a=(\\mathcal{E}, E_d)$ is applicable in $s=(\\mathcal{M},W_d)$ if for all $w \\in W_d$ there is an event $e \\in E_d$ such that $(\\mathcal{M},w) \\models pre(e)$.\n\nLet us imagine a planning task between Lea and Max. Lea puts two cards face down in front of Max. The goal is that Max picks up the queen. The problem here is that Max does not know where the queen is. \\\\\nLea has put the queen to the right, so $qR$.\n\n\\[\ns=\n\\begin{tikzpicture}\n  \\draw (-2,0) node[world, label=below:{$w_1: \\neg qR$}] (w1) {};\n  \\draw (0,0) node [desig] {}; % designation\n  \\draw (0,0) node[world, label=below:{$w_2: qR$}] (w2) {};\n  \\draw (w1) -- node[above] {Max} (w2);\n\\end{tikzpicture}\n\\]\n\nThere are two types of actions that could be performed to solve this problem:\n\\begin{enumerate}\n  \\item Announcement actions \\\\\n    Lea could tell Max where she put the queen. $\\omega(a_{\\text{announcement}})=\\text{Lea}$\n\n    \\[\n    \\begin{tikzpicture}\n      \\draw (-2,0) node[world, label=below:{$w_1: \\neg qR$}] (w1) {};\n      \\draw (0,0) node [desig] {}; % designation\n      \\draw (0,0) node[world, label=below:{$w_2: qR$}] (w2) {};\n      \\draw (w1) -- node[above] {Max} (w2);\n    \\end{tikzpicture}\n    %\n    ~\\otimes~\n    %\n    \\begin{tikzpicture}\n      \\draw (0,0) node [desig] {}; % designation\n      \\draw (0,0) node[world, label=below:{$e_1: \\langle qR, \\top \\rangle $}] (w1) {};\n    \\end{tikzpicture}\n    %\n    ~=~\n    %\n    \\begin{tikzpicture}\n      \\draw (0,0) node [desig] {};\n      \\draw (0,0) node[world, label=below:{$(w_2, e_1): qR$}] (w1e1) {};\n    \\end{tikzpicture}\n    \\]\n\n\n\n  \\item Sensing actions \\\\\n    Max could look at the left card, then he knows where the queen is.\n    $\\omega(a_{\\text{sense}})=\\text{Max}$\n\n    \\[\n    \\begin{tikzpicture}\n      \\draw (-2,0) node[world, label=below:{$w_1: \\neg qR$}] (w1) {};\n      \\draw (0,0) node [desig] {}; % designation\n      \\draw (0,0) node[world, label=below:{$w_2: qR$}] (w2) {};\n      \\draw (w1) -- node[above] {Max} (w2);\n    \\end{tikzpicture}\n    %\n    ~\\otimes~\n    %\n    \\begin{tikzpicture}\n      \\draw (-2,0) node[world, label=below:{$e_1: \\langle qR, \\top \\rangle $}] (e1) {};\n      \\draw (0,0) node [desig] {}; % designation\n      \\draw (0,0) node[world, label=below:{$e_2: \\langle \\neg qR, \\top \\rangle $}] (e2) {};\n    \\end{tikzpicture}\n    %\n    ~=~\n    %\n    \\begin{tikzpicture}\n      \\draw (-2,0) node[world, label=below:{$w_1: \\neg qR$}] (w1) {};\n      \\draw (0,0) node [desig] {}; % designation\n      \\draw (0,0) node[world, label=below:{$w_2: qR$}] (w2) {};\n    \\end{tikzpicture}\n    \\]\n\n\\end{enumerate}\n\n\n\n\\subsection{Planning tasks}\n\n\nA planning task $\\Pi = \\langle s_0, A, \\omega, \\gamma \\rangle$ consists of a global state $s_0$ called the \\textit{initial state}; a finite set of actions A; an owner function $\\omega: A \\rightarrow \\mathcal{A}$; and a \\textit{goal formula} $\\gamma \\in \\mathcal{L}_{KC}$.\n\nConsider a version of the lever problem from before. For simplicity, in this example there is only one player and the lever can only be pulled once. The planning task $\\langle s_0, \\{ a_1 \\} , \\omega, p \\rangle$ consists of the initial state $s_0 = $\n\\begin{tikzpicture}\n  \\draw (0,0) node [desig] {}; % designation\n  \\draw (0,0) node[world, label=below:{$\\neg p$}] (w1) {};\n\\end{tikzpicture}\nwith the lever being in the upright position. The action $a_1$ =\n\\begin{tikzpicture}\n  \\draw (0,0) node [desig] {}; % designation\n  \\draw (0,0) node[world, label=below:{$e_1: \\langle \\top, p \\rangle $}] (w1) {};\n\\end{tikzpicture}\nhas the owner $\\omega(a_1) = 1$ (player 1). Everything is fully observable for the agent. The intuitive  solution should prescribe the action $a_1$ to agent 1, pulling the lever to the right.\n\n\\[\n\\begin{tikzpicture}\n  \\draw (0,0) node [desig] {}; % designation\n  \\draw (0,0) node[world, label=below:{$w_1: \\neg p$}] (w1) {};\n\\end{tikzpicture}\n%\n~\\otimes~\n%\n\\begin{tikzpicture}\n  \\draw (0,0) node [desig] {}; % designation\n  \\draw (0,0) node[world, label=below:{$e_1: \\langle \\top, p \\rangle $}] (w1) {};\n\\end{tikzpicture}\n%\n~=~\n%\n\\begin{tikzpicture}\n  \\draw (0,0) node [desig] {};\n  \\draw (0,0) node[world, label=below:{$(w_1, e_1): p$}] (w1e1) {};\n\\end{tikzpicture}\n\\]\n\n\nA policy $\\pi$ for $\\Pi = \\langle s_0, A, \\omega, \\gamma \\rangle$ is a partial mapping $\\pi: S^{gl} \\hookrightarrow \\mathcal{P}(A)$ such that:\n\\begin{enumerate}\n  \\item Applicability\\\\\n    We require actions to be applicable in all states they are assigned to: \\\\\n    for all $a \\in S^{gl}, a \\in \\pi(s): a$ is applicable in $s$.\n  \\item Uniformity \\\\\n    If the policy $\\pi$ prescribes some action $a$ to agent $i$ in state $s$ and agent $i$ cannot distinguish $s$ from some other state $t$, then $\\pi$ has to prescribe the same action $a$ for $i$ in $t$ as well: \\\\\n    for all $s,t \\in S^{gl} $ such that $ s^{\\omega(a)} = t^{\\omega(a)}, a \\in \\pi(s): a \\in \\pi(t)$\n\n    A planning task with the agents Lea and Max,\n    initial state Lea puts two cards face down on the table, one of them is a queen, the other a king. Max does not know if the queen is on the left or the right side. The goal is that Max turns over the queen. Max has two actions, he can either turn over the left card or the right card. The policy in which Max turns over the left card is a valid policy because even though he does not know if that card is the queen, the action is prescribed in both cases.\n\n\n  \\item Determinism \\\\\n    We require $\\pi$ to be unambiguous for all agents in the sense that in each state $s$ where an agent $i$ is supposed to act according to $\\pi$, $\\pi$ will always prescribe the same action for agent $i$.\n\\end{enumerate}\n\nThe properties uniformity and applicability together imply knowledge of preconditions, the property that in each state, an agent who is supposed to perform a particular action must also know that the action is applicable in that state.\n\nWe also must allow policies to sometimes prescribe multiple actions of different owners to the same state. This is because the set of indistinguishable states can differ between the agents. To characterize the different outcomes of agents acting according to a common policy, we define the notion of policy executions.\n\nAn execution of a policy $\\pi$ from a global state $s_0$ is a maximal (finite or infinite) sequence of alternating global states and actions $(s_0, a_1, s_1, a_2, s_2,...)$, such that for all $ m \\leq 0$\n\\begin{enumerate}\n  \\item $a_{m+1} \\in \\pi(s_m)$ and\n  \\item $s_{m+1} \\in Globals(s_m \\otimes a_{m+1})$\n\\end{enumerate}\nAn execution is called successful for a planning task $\\Pi = \\langle s_0, A, \\omega, \\gamma \\rangle$, if it is a finite execution $(s_0, a_1, s_1,...,a_n, s_n)$ such that $s_n \\models \\gamma$.\n\n%\\extend{Example: Anna lets Bill pull the lever to the right. Globally this makes sense, since that is Bills goal. But individually, this makes no sense at all because Anne doesent know Bills goal.}\n\nIn the lever example, a policy could be that, starting in the position with the lever being in the middle, Bill pulls the lever to the right and then to the right again. This is a policy that satisfies all properties and where the last state satisfies the goal formula. The execution of the policy is finite and successful. \\\\\nFor Bill, this is a reasonable policy. It satisfies the goal formula he knows to be true, with the lever being at the far right position. But for Anne, it is not a reasonable policy because she can not see that the execution of this policy will satisfy the goal formula.\n\n%\\todo{Geht das hier etwas schöner?}\nWe now want to restrict our focus to policies that are guaranteed to achieve the goal after a finite number of steps. More formally, all of their executions must be successful. As in nondeterministic planning, such policies are called strong (Cimatti et al. \\cite{cimattietal}).\nFor a planning task $\\Pi = \\langle s_0, A, \\omega, \\gamma \\rangle$, a policy $\\pi$ is called strong if $s_0 \\in \\text{Dom}(\\pi) \\cup \\{s \\in S^{gl} ~|~ s \\models \\gamma\\}$ and for each $s \\in \\text{Dom}(\\pi)$, any execution of $\\pi$ from $s$ is successful for $\\Pi$. A planning task is called solvable if a strong policy for $\\Pi$ exists.\nFor $ i \\in \\mathcal{A} $ , we call a policy $i$-strong if it is strong and  $Globals(s_0^i ) \\subseteq \\text{Dom}(\\pi) \\cup\\{ s \\in S^{gl} ~|~ s \\models \\gamma \\}$.\n\nWhen a policy is i-strong it means that the policy is strong and defined on all the global states that agent $i$ cannot distinguish inbetween. It follows directly from the definition that any execution of an $i$-strong policy from any of those initially indistinguishable states will be successful. So if agent $i$ comes up with an $i$-strong policy, agent $i$ knows the policy to be successful.\n\nThe policy from above, with Bill pulling the lever to the right twice is Bill-strong but not Anne-strong.\n\nSometimes the agents cannot coordinate their plans but rather have to come up with plans individually. These plans can differ a lot, the agents often have different knowledge about the states, the actions and therefore the action outcomes. For this reason we will define a policy profile for a planning task $\\Pi$ to be a family $(\\pi_i)_{i \\in \\mathcal{A}}$ where each $\\pi_i$ is a policy for $\\Pi$. We assume actions to be instantaneous and executed asynchronously. This leads to the following generalization:\n\nAn execution of a policy profile $(\\pi_i)_{i \\in \\mathcal{A}}$ is a maximal (finite or infinite) sequence of alternating global states and actions $(s_0, a_1, s_1,...)$, such that for all $m \\leq 0$,\n\\begin{enumerate}\n  \\item $a_{m+1} \\in \\pi_i(s_m)$ where $i=\\omega(a_{m+1})$ \\\\\n    Note here the source of nondeterminism as a result from the possibility of multiple policies prescribing actions for their respective agents.\n  \\item $s_{m+1} \\in Globals(s_m \\otimes a_{m+1}) $ \\\\\n    Here the source of nondeterminism is from the possibility of nondeterministic action outcomes.\n\\end{enumerate}\n\n\nIf all agents have one strong policy in common which all of them follow, then at execution time, the goal is guaranteed to be eventually reached. If, however, each agent acts on its individual strong policy, then the incompatibility of the individual policies may prevent the agents from reaching the goal, even though each individual policy is strong.\n\n\n\nThe cost of a a policy can be defined as its worst-case execution length, the number of actions in its longest possible execution. An optimal policy is one with minimal costs. Due to partial observability and different knowledge, the agents might assign different costs to the same policy and therefore the costs are subjective. \\\\\nLet $\\pi$ be a strong policy for a planning task $\\Pi$. The perspective-sensitive cost (or simply cost) of $\\pi$ from a state $s\\in Dom(\\pi)$, denoted $\\kappa_{\\pi}(s)$ is defined as:\n$$\\kappa_{\\pi}(s) =\n\\begin{cases}\n0 \\qquad & \\text{if there exists no } a \\in \\pi(s)\\\\\n1+ \\max_{a\\in \\pi(s), s'\\in Globals(s^{\\omega(a)} \\otimes a)} \\kappa_{\\pi}(s') \\qquad & \\text{else.}\n\\end{cases}$$\n", "meta": {"hexsha": "aab7d827540e4b39ccdbdf07017b40e9ad0771ac", "size": 20774, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/3-background.tex", "max_stars_repo_name": "ritterchen123/bachelor_thesis", "max_stars_repo_head_hexsha": "cd912e78403641032c4d84b32c460dd252d17959", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/3-background.tex", "max_issues_repo_name": "ritterchen123/bachelor_thesis", "max_issues_repo_head_hexsha": "cd912e78403641032c4d84b32c460dd252d17959", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/3-background.tex", "max_forks_repo_name": "ritterchen123/bachelor_thesis", "max_forks_repo_head_hexsha": "cd912e78403641032c4d84b32c460dd252d17959", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 69.711409396, "max_line_length": 1089, "alphanum_fraction": 0.6831616444, "num_tokens": 6493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.30736333287959267}}
{"text": "\n\\documentclass{easychair}\n\n\\usepackage{doc}\n\\usepackage{scalerel}\n\\usepackage{amsfonts}\n\n\\newcommand{\\easychair}{\\textsf{easychair}}\n\\newcommand{\\miktex}{MiK{\\TeX}}\n\\newcommand{\\texniccenter}{{\\TeX}nicCenter}\n\\newcommand{\\makefile}{\\texttt{Makefile}}\n\\newcommand{\\latexeditor}{LEd}\n\\newcommand{\\emptycon}{\\scaleobj{.75}\\bullet}\n\\newcommand{\\ext}{\\triangleright}\n\\newcommand{\\arri}{\\Rightarrow}\n\n\\newcommand{\\ms}[1]{\\mathsf{#1}}\n\\newcommand{\\ToS}{\\mathsf{ToS}}\n\\newcommand{\\U}{\\mathsf{U}}\n\\newcommand{\\Code}{\\mathsf{Code}}\n\\newcommand{\\Ty}{\\mathsf{Ty}}\n\\newcommand{\\V}{\\mathsf{V}}\n\\newcommand{\\C}{\\mathsf{C}}\n\\newcommand{\\Bool}{\\ms{Bool}}\n\n\\title{Staged Compilation and Generativity%\n  \\thanks{The author was supported by the European Union, co-financed\n    by the European Social Fund (EFOP-3.6.3-VEKOP-16-2017-00002).}}\n\n\\author{\nAndr\\'as Kov\\'acs\n}\n\n% Institutes for affiliations are also joined by \\and,\n\\institute{\n  E\\\"otv\\\"os Lor\\'and University,\n  Budapest, Hungary \\\\\n  \\email{kovacsandras@inf.elte.hu}\n}\n\n\\authorrunning{Kov\\'acs}\n\\titlerunning{Staged Compilation and Generativity}\n\\pagenumbering{gobble}\n\\begin{document}\n\n\\maketitle\n\nThe purpose of staged compilation is to write code-generating programs in a safe\nand ergonomic way. Although it is always possible to write metaprograms by\nsimply manipulating strings or deeply embedded syntax trees, this is often\nerror-prone and tedious. Staging is a way to have more guarantees about the\nsafety and well-typing of metaprograms, and also a way to integrate object-level\nand meta-level syntaxes more organically.\n\nTwo-level type theory (2LTT) \\cite{twolevel} was originally developed for the\npurpose of doing synthetic homotopy theory, by adding a metaprogramming layer on\ntop of homotopy type theory \\cite{hottbook}. However, it turns out that 2LTT is\nalso a great framework for metaprogramming and staging in general; it is\napplicable to a wide range of object theories.\n\nThere is a natural semantics to 2LTT which justifies the metaprogramming view:\nthis is the \\emph{presheaf model} of 2LTT. Here, meta-level types are presheaves\nover the underlying category of the object theory. Hence, every meta-level\nconstruction must be stable under the object-level morphisms.\n\n\\paragraph{Generativity}Generativity means that we can only generate code, but not look inside\nobject-level syntax and make decisions based on that. Generativity simplifies\nstaging, and it is often enforced in practical implementations\n\\cite{kiselyov14metaocaml}. However, non-generative staging provides additional\npower and flexibility. A simple example for a non-generative feature is\nconversion checking. Assume that given an object-level type $A$, $\\Code\\,A$ is\nthe type of meta-level programs which compute $A$-expressions. Conversion\nchecking may be postulated as $\\ms{conversion}_A : (t\\,u : \\Code\\,A) \\to (t = u)\n+ (t \\neq u)$. We aim to investigate generativity in the presheaf model. We\nobserve that it depend on the choice of morphisms in the object theory.\n\nIf base morphisms are \\emph{substitutions}, then $\\ms{conversion}$ does not hold\nin the model, because definitional inequality is not stable under substitution. For\nexample, inequal variables may become equal after substitution.\n\nIf base morphisms are \\emph{weakenings}, then $\\ms{conversion}$\nholds. However, in this case the object theory can only support features which\ncan be specified with weakenings. For instance, this allows simple types at at\nthe object level, without any $\\beta$-rules, but it does not allow polymorphism\nor dependent types. This is still sufficient for many staging applications.\n\n\\paragraph{Yoneda lemma} It is worth to note that we get generativity statements\nin the presheaf model from the Yoneda lemma. For example, the natural\ntransformation $\\ms{y}\\,\\Bool_0 \\Rightarrow \\Bool_1$ must be a constant map in the\nmodel. How is it possible then to have non-generativity? The answer is that\nthe Yoneda lemma can only meaningfully apply to \\emph{types} (as opposed to\ncontexts) in the presheaf model, if context extension is preserved by Yoneda\nembedding. If base morphisms are weakenings, the base category does not have all\nbinary products, and context extension is not preserved by $\\ms{y}$. Hence, the\nsingleton context $\\emptycon,\\ms{y}\\,\\Bool_0$ is not representable, and the\nYoneda lemma does not say anything about dependency on $\\ms{y}\\,\\Bool_0$.\n\n\n\\bibliographystyle{plain}\n\\bibliography{references}\n\n\\end{document}\n", "meta": {"hexsha": "99bf740462f4ce7b2ef5d20a7307ba8233f42658", "size": 4457, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "efop_abstract/abstract.tex", "max_stars_repo_name": "AndrasKovacs/staged", "max_stars_repo_head_hexsha": "8876a92136e5d37f67e7a8cf52c88253ddf77d9f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 78, "max_stars_repo_stars_event_min_datetime": "2021-04-22T12:51:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T20:12:54.000Z", "max_issues_repo_path": "efop_abstract/abstract.tex", "max_issues_repo_name": "AndrasKovacs/staged", "max_issues_repo_head_hexsha": "8876a92136e5d37f67e7a8cf52c88253ddf77d9f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-07-16T04:06:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-05T10:17:38.000Z", "max_forks_repo_path": "efop_abstract/abstract.tex", "max_forks_repo_name": "AndrasKovacs/staged", "max_forks_repo_head_hexsha": "8876a92136e5d37f67e7a8cf52c88253ddf77d9f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.2718446602, "max_line_length": 94, "alphanum_fraction": 0.7796724254, "num_tokens": 1208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.3073475055818697}}
{"text": "\\section{Low-Voltage Induced Random Bit Errors in Quantized DNN Weights}\n\\label{sec:errors}\n\nWe assume the quantized DNN weights to be stored  on multiple memory banks, \\eg, SRAM in the case of on-chip scratchpads or DRAM for off-chip memory. As shown in \\cite{GanapathyDAC2017,KimDATE2018,ChandramoorthyHPCA2019}, the probability of memory bit cell failures increases exponentially as operating voltage is scaled below $\\Vmin$, \\ie, the minimal voltage required for reliable operation, see \\figref{fig:introduction}. This is done intentionally to reduce energy consumption, \\eg, \\cite{ChandramoorthyHPCA2019,KimDATE2018,KoppulaMICRO2019}, or adversarially by an attacker, \\eg, \\cite{TangUSENIX2017}. Process variation during fabrication causes a variation in the vulnerability of individual bit cells. As shown in \\figref{fig:errors} (left), for a specific memory array, bit cell failures are typically approximately random and independent of each other \\cite{GanapathyDAC2017}. We also consider chips showing other error patterns as in \\figref{fig:errors} (right). Nevertheless, there is generally an ``inherited'' distribution of bit cell failures across voltages \\cite{GanapathyHPCA2019}, if a bit error occurred at a given voltage, it is likely to occur at lower voltages, as made explicit in \\figref{fig:errors}. However, across different SRAM arrays in a chip or different chips, the patterns or spatial distribution of bit errors is usually different and can be assumed random \\cite{ChandramoorthyHPCA2019}. Throughout the paper, we use the following bit error model:\n\n\\textbf{Random Bit Error Model:}\n\\textit{The probability of a bit error is $p$ (in \\%) for all weight values and bits. For a fixed memory array, bit errors are persistent across supply voltages, \\ie, bit errors at probability $p'{\\leq}p$ also occur at probability $p$. A bit error flips the currently stored bit. We denote random bit error injection by $\\biterror_p$.}\n\n\\begin{figure*}\n    \\vspace*{-0.15cm}\n    \\centering\n    \\includegraphics[width=0.85\\textwidth]{main_training_flow4.pdf}\n    \\vspace*{-6px}\n    \\caption{\\textbf{Random Bit Error Training (\\Random).} We illustrate the data-flow for \\Random as in \\algref{alg:training}. Here, $\\biterror_p$ injects random bit errors in the \\red{quantized weights} $\\red{v^{(t)}} = Q(\\magenta{w^{(t)}})$, resulting in $\\red{\\tilde{v}^{(t)}}$, while the forward pass is performed on the \\blue{de-quantized perturbed weights} $\\blue{\\tilde{w}_q^{(t)}} = Q^{-1}(\\red{\\tilde{v}^{(t)}})$, \\ie, fixed-point arithmetic is not emulated. The weight update during training is not affected by bit errors and computed in \\magenta{floating point}.}\n    \\label{fig:flowchart}\n    \\vspace*{-0.2cm}\n\\end{figure*}\n\nThis error model realistically captures the nature of low-voltage induced bit errors, from both SRAM and DRAM as confirmed in \\cite{ChandramoorthyHPCA2019,KimDATE2018,KoppulaMICRO2019}. However, our approach in \\secref{sec:robustness} is model-agnostic: the error model can be refined if extensive memory characterization results are available for individual chips. For example, faulty bit cells with $1$-to-$0$ or $0$-to-$1$ flips might not be equally likely. Similarly, as in \\cite{KoppulaMICRO2019}, bit errors might be biased towards alignment along rows or columns of the memory array. The latter case is illustrated in \\figref{fig:errors} (right). However, estimating these specifics requires testing infrastructure and detailed characterization of individual chips. \nMore importantly, it introduces the risk of overfitting to few specific memories/chips. \nFurthermore, we demonstrate that the robustness obtained using our uniform error model generalizes to bit error distributions with strong spatial biases as in \\figref{fig:errors} (right).\n\nWe assume the quantized weights to be mapped linearly to the memory. This is the most direct approach and, in contrast to \\cite{KoppulaMICRO2019}, does not require knowledge of the exact spatial distribution of bit errors. This also means that we do not map particularly vulnerable weights to more reliable memory cells, and therefore no changes to the hardware or the application are required. Thus, in practice, for $W$ weights and $m$ bits per weight value, we sample uniformly $u \\sim U(0, 1)^{W \\times m}$. Then, the $j$-th bit in the quantized weight $v_i = Q(w_i)$ is flipped iff $u_{ij} \\leq p$.\nOur model assumes that the flipped bits at lower probability $p' \\leq p$ are a subset of the flipped bits at probability $p$ and that bit flips to $1$ and $0$ are equally likely. The noise pattern of random bit errors is illustrated in \\figref{fig:quantization}: \nfor example a single bit flip in the most-significant bit (MSB) of the signed integer $v_i$ can result in a change of roughly half of the quantized range (also \\cf \\secref{subsec:robustness-quantization}).\n\n\\section{Towards Robustness Against Random Bit Errors}\n\\label{sec:robustness}\n\nWe address robustness against random bit errors in three steps: First, we analyze the impact of fixed-point quantization schemes on bit error robustness. This has been neglected both in prior work on low-voltage DNN accelerators \\cite{KimDATE2018,KoppulaMICRO2019} and in work on quantization robustness \\cite{MurthyARXIV2019,MerollaARXIV2016,SungARXIV2015}. This yields our \\textbf{robust quantization} (\\secref{subsec:robustness-quantization}). On top, we propose aggressive \\textbf{weight clipping} as regularization during training (\\secref{subsec:robustness-clipping}). \nWeight clipping enforces a more uniformly distributed, \\ie, redundant, weight distribution, improving robustness. We show that this is due to minimizing the cross-entropy loss, enforcing large logit differences.\nFinally, in addition to robust quantization and weight clipping, we perform \\textbf{random bit error training (\\Random)} (\\secref{subsec:robustness-training}): in contrast to the fixed bit error patterns in \\cite{KimDATE2018,KoppulaMICRO2019}, we train on completely \\emph{random} bit errors and, thus, generalize across chips and voltages.\nGeneralization is measured using \\emph{average robust test error (\\RTE)}, the test error after injecting bit errors, \\wrt to our error model from \\secref{sec:errors} as well as real, profiled bit error patterns. % but also the corresponding standard deviation. \nRobustness against bit error rate $p$ has to induce robustness for $p' \\leq p$ (\\ie, higher voltage), as well.\n\n\\subsection{Robust Fixed-Point Quantization}\n\\label{subsec:robustness-quantization}\n\nWe consider quantization-aware training \\cite{JacobCVPR2018,KrishnamoorthiARXIV2018} using a generic, deterministic fixed-point quantization scheme commonly used in DNN accelerators \\cite{ChandramoorthyHPCA2019}. However, we focus on the impact of quantization schemes on robustness against random bit errors, mostly neglected so far \\cite{MurthyARXIV2019,MerollaARXIV2016,SungARXIV2015}. We find that quantization affects robustness significantly, even if accuracy is largely unaffected.\n\n\\textbf{Fixed-Point Quantization:} Let $f(x; w)$ be a DNN taking an example $x \\in [0, 1]^D$, \\eg, an image, and weights $w \\in \\mathbb{R}^W$ as input. Quantization determines how weights are represented in memory, \\eg, on SRAM. In a \\emph{fixed-point quantization} scheme, $m$ bits allow to represent $2^m$ distinct values. \nA weight $w_i \\in [-\\qmax, \\qmax]$ \nis represented by a signed $m$-bit integer $v_i = Q(w_i)$ corresponding to the underlying bits. Here, $[-\\qmax, \\qmax]$ is the \\emph{symmetric} quantization range and signed integers use two's complement representation. Then, $Q: [-\\qmax, \\qmax] \\mapsto \\{-2^{m - 1} - 1, \\ldots, 2^{m - 1} - 1\\}$ is defined as \n\\begin{align}\n    Q(w_i) = \\left\\lfloor \\frac{w_i}{\\Delta}\\right\\rfloor,\\text{  }\n    Q^{-1}(v_i) = \\Delta v_i,\\text{  }\n    \\Delta = \\frac{\\qmax}{2^{m - 1} - 1}\n    \\label{eq:quantization}\n\\end{align}\nFlipping the most significant bit (MSB, \\ie, sign bit) leads to an absolute error of half the quantization range, \\ie, $\\qmax$ ({\\color{yellow!75!black!}yellow} in \\figref{fig:quantization}).\nFlipping the least significant bit (LSB) incurs an error of $\\Delta$, \\cf \\eqnref{eq:quantization}. Thus, the impact of bit errors ``scales with'' $\\qmax$.\n\n\\textbf{Global and Per-Layer Quantization:} $\\qmax$ can be chosen to accommodate all weights, \\ie, $\\qmax = \\max_i |w_i|$. This is called \\emph{global} quantization. However, it has become standard to apply quantization \\textit{per-layer} allowing to adapt $\\qmax$ to each layer. As in PyTorch \\cite{PaszkeNIPSWORK2017}, we consider weights and biases of each layer separately. By reducing the quantization range for each layer individually, the errors incurred by bit flips are automatically minimized, \\cf \\figref{fig:quantization}. The\n\\textbf{per-layer, symmetric quantization is our default reference}, referred to as \\Normal. However, it turns out that it is further beneficial to consider arbitrary quantization ranges $[\\qmin, \\qmax]$ (allowing $\\qmin > 0$). In practice, we\nfirst map $[\\qmin, \\qmax]$ to $[-1,1]$ and then quantize $[-1,1]$ using \\eqnref{eq:quantization}.\nOverall, per-layer asymmetric quantization has the finest granularity, \\ie, lowest $\\Delta$ and approximation error. Nevertheless it is not the most robust\nquantization.\n\n\\begin{figure}[t]\n\t\\centering\n\t\\vspace*{-0.1cm}\n\t\\hspace*{-0.3cm}\n\t\\begin{subfigure}{0.24\\textwidth}\n\t\t\\vspace*{3px}\n\t\t\n\t\t\\includegraphics[height=1.35cm]{c10_q81auunfp_nt_original_logits.pdf}\n\t\\end{subfigure}\n\t\\begin{subfigure}{0.12\\textwidth}\n\t\t\\vspace*{0px}\n\t\t\n\t\t\\includegraphics[height=1.425cm]{c10_q81auunfp_nt_original_confidences.pdf}\n\t\\end{subfigure}\n\t\\begin{subfigure}{0.12\\textwidth}\n\t\t\\vspace*{0px}\n\t\t\n\t\t\\includegraphics[height=1.425cm]{c10_q81auunfp_nt_original_weights.pdf}\n\t\\end{subfigure}\n\t\n\t\\hspace*{-0.4cm}\n\t\\begin{subfigure}{0.24\\textwidth}\n\t\t\\vspace*{3px}\n\t\t\n\t\t\\includegraphics[height=1.35cm]{c10_q801auunfp_nt_original_logits.pdf}\n\t\\end{subfigure}\n\t\\begin{subfigure}{0.12\\textwidth}\n\t\t\\vspace*{0px}\n\t\t\n\t\t\\includegraphics[height=1.425cm]{c10_q801auunfp_nt_original_confidences.pdf}\n\t\\end{subfigure}\n\t\\begin{subfigure}{0.12\\textwidth}\n\t\t\\vspace*{3px}\n\t\t\n\t\t\\includegraphics[height=1.425cm]{c10_q801auunfp_nt_original_weights.pdf}\n\t\\end{subfigure}\n\t\n\t\\hspace*{-0.3cm}\n\t{\\color{black!25!white}\\rule{0.5\\textwidth}{0.5px}}\n\t\n\t\\hspace*{-0.4cm}\n\t\\begin{subfigure}{0.24\\textwidth}\n\t\t\\vspace*{0px}\n\t\t\n\t\t\\includegraphics[height=1.825cm]{c10_q81auunrfp_sawt_bit_random_g001_pop1_logits.pdf}\n\t\\end{subfigure}\n\t\\begin{subfigure}{0.12\\textwidth}\n\t\t\\vspace*{0px}\n\t\t\n\t\t\\includegraphics[height=1.7cm]{c10_q81auunrfp_sawt_bit_random_g001_pop1_confidences.pdf}\n\t\\end{subfigure}\n\t\\begin{subfigure}{0.12\\textwidth}\n\t\t\\vspace*{3px}\n\t\t\n\t\t\\includegraphics[height=1.7cm]{c10_q81auunrfp_sawt_bit_random_g001_pop1_weights.pdf}\n\t\\end{subfigure}\n\t\n\t\\vspace*{-8px}\n\t\\caption{\\textbf{Effect of Weight Clipping.} On \\CifarT, weight clipping constraints the weights (right), thereby implicitly limiting the possible range for logits (left, {\\color{colorbrewer2}blue}).\n\tHowever, even for $\\wmax = 0.1$ the DNN is able to produce high confidences (middle, {\\color{colorbrewer2}blue}), suggesting that more weights are used to obtain these logits. Furthermore, the impact of random bit errors, $p = 1\\%$, on the logits/confidences ({\\color{colorbrewer1}red}) is reduced significantly. \\Random (trained with $p = 1\\%$, w/o weight clipping), increases the range of weights and is less effective at preserving logit/confidence distribution. %Logit/confidence histograms normalized over $10\\cdot 128$ examples.\n\t}\n\t\\label{fig:clipping}\n\t\\vspace*{-0.2cm}\n\\end{figure}\n\n\\textbf{Robust Quantization:} Quantization as in \\eqnref{eq:quantization} does \\emph{not} provide optimal robustness against bit errors. First, the floor operation $\\lfloor \\nicefrac{w_i}{\\Delta}\\rfloor$ is commonly implemented as float-to-integer conversion. Using proper rounding $\\lceil\\nicefrac{w_i}{\\Delta}\\rfloor$ instead has negligible impact on accuracy, even though approximation error improves slightly. In stark contrast, bit error robustness is improved considerably. During training, DNNs can compensate the differences in approximation errors, even for small precision $m < 8$. However, at test time,\nrounding decreases the impact of bit errors considerably. Second, \\eqnref{eq:quantization} uses signed integers for symmetric quantization. For asymmetric quantization, with arbitrary $[\\qmin, \\qmax]$, we found quantization into \\emph{unsigned} integers to improve robustness, \\ie, $Q : [\\qmin, \\qmax] \\mapsto \\{{\\color{red}0}, \\ldots, {\\color{red}2^m - 1}\\}$. This is implemented using an additive term of $2^{m-1}-1$ in \\eqnref{eq:quantization}. While accuracy is not affected, the effect of bit errors in the sign bit changes: in symmetric quantization, the sign bit mirrors the sign of the weight value. For asymmetric quantization, an unsigned integer representation is more meaningful. Overall, our \\textbf{robust fixed-point quantization (\\Quant)}  uses per-layer, asymmetric quantization into unsigned integers with rounding.\nThese seemingly \\emph{small differences} have little to no impact on accuracy, while having tremendous impact on robustness against bit errors, see \\secref{subsec:experiments-quantization} and \\appref{sec:supp-implementation}. \n\\revision{They are simple to implement, do not add training complexity or hyper-parameters and demonstrate the importance of robustness in developing DNN quantization schemes.}\n\n\\begin{algorithm}[t]\n\\caption{\\textbf{Random Bit Error Training (\\Random).} The forward passes are performed using \\blue{de-quantized weights (blue)}. Perturbed weights are obtained by injecting bit errors in the \\red{quantized weights (in red)}. The update, averaging gradients from both forward passes, is performed in \\magenta{floating-point (magenta)}. Also see \\figref{fig:flowchart}.}\n\\label{alg:training}\n\\begin{algorithmic}[1]\n\\small\n\\Procedure{RandBET}{$p$}\n    \\State initialize \\magenta{$w^{(0)}$}\n\t\\For{$t = 0, \\ldots, T - 1$}\n    \t\\State sample batch $\\{(x_b, y_b)\\}_{b = 1}^B$\n    \t\\State \\{element-wise clipping:\\}\n    \t\\State $\\magenta{w^{(t)}} = \\min(\\wmax, \\max(-\\wmax, \\magenta{w^{(t)}}))$\n    \t\\State \\{quantization:\\}\n    \t\\State $\\red{v^{(t)}} = Q(\\magenta{w^{(t)}})$\n        \\State $\\blue{w_q^{(t)}} = Q^{-1}(\\red{v^{(t)}})$\n        \\State \\{clean forward and backward pass:\\}\n        \\State $\\Delta^{(t)} = \\nabla_w \\sum_{b = 1}^B \\mathcal{L}(f(x_b; \\blue{w_q^{(t)}}), y_b)$\n        \\State \\{\\emph{perturbed} forward and backward pass:\\}\n        \\State $\\blue{\\tilde{w}_q^{(t)}}{\\hskip 1px=\\hskip 1px}Q^{-1}(\\biterror_p(\\red{v^{(t)}}))$\\label{line:attack} \\{inject random bit errors\\}\n        \\State $\\tilde{\\Delta}^{(t)} = \\nabla_w \\sum_{b = 1}^B \\mathcal{L}(f(x_b; \\blue{\\tilde{w}_q^{(t)}}), y_b)$\n        \\State \\{average gradients and weight update:\\}\n        \\State $\\magenta{w^{(t + 1)}} = \\magenta{w^{(t)}} - \\gamma(\\Delta^{(t)} + \\tilde{\\Delta}^{(t)})$\n    \\EndFor\n    \\State \\textbf{return} $\\blue{w_q^{(T)}} = Q^{-1}(Q(\\magenta{w^{(T)}}))$\n\\EndProcedure\n\\end{algorithmic}\n\\end{algorithm}\n\n\\subsection{Training with Weight Clipping as Regularization}\n\\label{subsec:robustness-clipping}\n\n\\textbf{Weight clipping} refers to constraining the weights to $[-\\wmax, \\wmax]$ \\emph{during training}, where $\\wmax$ is a hyper-parameter. Generally, $\\wmax$ is independent of the quantization range(s) which always adapt(s) to the weight range(s) at hand. However, weight clipping limits the maximum possible quantization range (\\cf \\secref{subsec:robustness-quantization}), \\ie, $\\qmax \\leq \\wmax$.\nIt might seem that weight clipping with small $\\wmax$ automatically improves robustness against bit errors as the absolute errors are reduced. However, the \\emph{relative} errors are not influenced by rescaling. As the DNN's decision is usually invariant to rescaling, reducing the scale of the weights does not impact robustness. In fact, the mean relative error of the weights in \\figref{fig:quantization} (right) increased with clipping at $\\wmax = 0.1$. Thus, weight clipping does \\emph{not} ``trivially'' improve robustness by reducing the scale of weights. Nevertheless, we found that weight clipping actually improves robustness considerably on top of our robust quantization.\n\nThe interplay of weight clipping and minimizing the the cross-entropy loss during training is the key. High confidences can only be achieved by large differences in the logits. Because the weights are limited to $[-\\wmax, \\wmax]$, large logits can only be achieved using more weights in each layer to produce larger outputs. This is illustrated in \\figref{fig:clipping} (right): using $\\wmax = 0.1$, the weights are (depending on the layer) up to $5$ times smaller. Considering deep NNs, the ``effective'' scale factor for the logits is significantly larger, scaling exponentially with the number of layers. Thus, using $\\wmax = 0.1$ is a significant constraint on the DNNs ability to produce large logits. As result, weight clipping produces a much more uniform weight distribution.\n\\figref{fig:clipping} (left and middle) shows that a DNN constrained at $\\wmax = 0.1$ can produce similar logit and confidence distributions (in {\\color{colorbrewer2}blue}) as the unclipped DNN. At the same time, random bit errors, have a significantly smaller impact on the logits and confidences (in {\\color{colorbrewer1}red}). \\figref{fig:clipping} (right column) also shows the induced redundancy in the weight distribution. Weight clipping leads to more weights being utilized, \\ie, less weights are zero (note log-scale, marked in {\\color{colorbrewer1}red}, on the y-axis). Also, more weights reach large values, relative to the maximum absolute weight. Overall, we found weight clipping to be an easy-to-use but effective measure to improve weight robustness. We use \\Clipping[$\\wmax{=}0.1$] to refer to, \\eg, weight clipping with $\\wmax = 0.1$. For more evidence supporting our argumentation, see \\tabref{tab:clipping-robustness}. For example, we show that DNNs loose robustness when using label smoothing, \\ie, not enforcing high confidences/logits during training.\n\\revision{Finally, weight clipping is straight-forward to implement (\\cf \\algref{alg:training}, line 6) and adds negligible training cost. The additional hyper-parameter, \\ie, $\\wmax$, can easily be tuned based on constraints on clean (or robust) performance, \\cf \\secref{subsec:experiments-clipping}.}\n\n\\subsection{Random Bit Error Training (\\Random)}\n\\label{subsec:robustness-training}\n\nIn \\emph{addition to} weight clipping and robust quantization, we inject random bit errors with probability $p$ during training to further improve robustness. This results in the following learning problem, which we optimize as illustrated in \\figref{fig:flowchart}:\n\\begin{align}\n\t\\begin{split}\n    \t&\\min_w \\mathbb{E}[\\mathcal{L}(f(x; \\tilde{w}), y) + \\mathcal{L}(f(x; w), y)]\\\\\n    \t\\text{s.t.}&\\quad v = Q(w),\\, \\tilde{v} = \\biterror_p(v),\\, \\tilde{w} = Q^{-1}(\\tilde{v}).\n   \t\\end{split}\\label{eq:random-training-average}\n\\end{align}\nwhere $(x, y)$ are labeled examples, $\\mathcal{L}$ is the cross-entropy loss and $v = Q(w)$ denotes the (element-wise) quantized weights $w$ which are to be learned. $\\biterror_p(v)$ injects random bit errors with rate $p$ in $v$. Note that we consider both the loss on clean weights and weights with bit errors. This is desirable to avoid an increase in (clean) test error and stabilizes training compared to training only on bit errors in the weights. Note that bit error rate $p$ implies, in expectation, $pmW$ bit errors. Following \\algref{alg:training}, we use stochastic gradient descent to optimize \\eqnref{eq:random-training-average}, by performing the gradient computation using the perturbed weights $\\tilde{w} = Q^{-1}(\\tilde{v})$ with $\\tilde{v} = \\biterror_p(v)$, while applying the gradient update on the (floating-point) clean weights $w$. In spirit, this is similar to data augmentation, however, the perturbation is applied on the weights instead of the inputs. As we found that introducing bit errors right from the start may prevent the DNN from converging, we apply bit errors as soon as the (clean) cross-entropy loss is below $1.75$. Interestingly, weight clipping and \\Random have somewhat orthogonal effects, which allows to combine them easily in practice: While weight clipping encourages redundancy in weights by constraining them to $[-\\wmax,\\wmax]$, % and activations, \n\\Random (w/o weight clipping) causes the DNN to have larger tails in the weight distribution, as shown in \\figref{fig:clipping} (bottom). However, considering logits and confidences, especially with random bit errors (in {\\color{colorbrewer1}red}), \\Random alone performs slightly worse than \\Clipping[$0.1$]. Thus, \\Random becomes particularly effective when combined with weight clipping, as we make explicit using the notation \\Random[$\\wmax$] in \\algref{alg:training}.\n\\revision{While \\Random increases training complexity (\\cf \\algref{alg:training}), inference is \\emph{not} affected. This is in stark contrast to hardware- or redundancy-based bit error mitigation strategies which usually impact inference time and energy consumption. We also note that the additional hyper-parameter, \\ie, $p$, is easily chosen according to the target bit error rate.}", "meta": {"hexsha": "965472888a645c426d58939c19bbce8107cb28b6", "size": 21339, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/sec_main.tex", "max_stars_repo_name": "davidstutz/mlsys2021-bit-error-robustness", "max_stars_repo_head_hexsha": "3d9c4d6c3bab61c75201f758a40937768ea18b99", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paper/sec_main.tex", "max_issues_repo_name": "davidstutz/mlsys2021-bit-error-robustness", "max_issues_repo_head_hexsha": "3d9c4d6c3bab61c75201f758a40937768ea18b99", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/sec_main.tex", "max_forks_repo_name": "davidstutz/mlsys2021-bit-error-robustness", "max_forks_repo_head_hexsha": "3d9c4d6c3bab61c75201f758a40937768ea18b99", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 119.8820224719, "max_line_length": 1482, "alphanum_fraction": 0.7584235437, "num_tokens": 5932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.30714101737661853}}
{"text": "%!TEX TS-program = xelatex\n%!TEX encoding = UTF-8 Unicode\n\n\\documentclass[12pt,letterpaper]{article}\n\\usepackage{fontspec}\n\\usepackage{geometry}\n\\geometry{letterpaper, textwidth=6.5in, textheight=9.5in, marginparsep=20pt, marginparwidth=2in}\n\\setlength\\parindent{0in}\n\\usepackage[usenames,dvipsnames]{color}\n\n% math packages\n\\usepackage{amsmath}\n\\usepackage{arevmath}\n\\usepackage{enumerate}\n\n% for sans serif math\n%\\usepackage{cmbright}\n\n\\usepackage{cancel}\n% alp's math bold command: Use it like \\mb{\\lambda} or \\mb{X}.\n\\DeclareRobustCommand{\\mb}[1]{\\ensuremath{\\boldsymbol{\\mathbf{#1}}}}\n\n% cond. independence\n\\newcommand\\independent{\\protect\\mathpalette{\\protect\\independenT}{\\perp}}\n\\def\\independenT#1#2{\\mathrel{\\rlap{$#1#2$}\\mkern2mu{#1#2}}}\n\n\n\n\\usepackage{xunicode}\n\\usepackage{xltxtra}\n\\defaultfontfeatures{Mapping=tex-text,Ligatures=Common, Scale=1}\n%\\setromanfont [Ligatures={Common}, Numbers={OldStyle}, Variant=01]{Hoefler Text Roman}\n%\\setromanfont{Whitney HTF Light}\n%\\setmainfont{Whitney HTF}\n\\setmainfont[\n BoldFont={Whitney HTF Medium},\n ItalicFont={Whitney HTF Light Italic},\n BoldItalicFont={Whitney HTF Medium Italic}\n ]{Whitney HTF}\n\\usepackage[]{hyperref}\n\\usepackage[\n    style=numeric-comp,\n    sorting=none,\n    doi=false,\n    isbn=false,\n    url=true,\n    eprint=false,\n    natbib=true,\n    maxnames=99\n]{biblatex}\n\\addbibresource{Untitled.bib}\n\n\\usepackage{dsfont}\n\n\n\n%% Commands\n\\newcommand{\\be}{\\begin{equation*}}\n\\newcommand{\\ee}{\\end{equation*}}\n\\newcommand{\\ba}{\\begin{align*}}\n\\newcommand{\\ea}{\\end{align*}}\n\\newcommand{\\indicator}{\\mathds{1}}\n\n\\title{User-artist-song Model (draft)}\n\\author{Jaan Altosaar, Laurent Charlin, David Blei}\n\n\\begin{document}\n\n\\makeatletter\n\n\\def\\maketitle{%\n\\begin{centering}\n\\textbf{\\large\\@title}\\\\%\n\\@author\\\\%\n{\\today}\\\\\n\\end{centering}\n\\par}\n\n\\makeatother\n\\maketitle\n\\vspace{10mm}\n\n\\section{Motivation}\n\nListening to music is different than reading articles. The artist of a song is of higher importance than the author of a scientific paper for a given user perusing their library.\n\n\nWe aim to capture this intuition using latent variables representing artist-level topics $\\beta_a$, song-level topics $\\beta_s$, and user preferences $x_u$ as shown in Figure \\ref{fig:uasmodel}.  This model can be extended, for example by connecting the artist-level $\\beta_a$ node to the song-level $\\beta_s$ node, or the artist-level rating $r_{ua}$ to the song-level rating $r_{uai}$.\n\n\\input{./src/uasmodelfig}\n\\clearpage\n\\section{Generative Process}\n\nThe generative process for the observed ratings is partially inspired by content-based Poisson factorization \\parencite{Gopalana}:\n\n\\begin{enumerate}\n\\item Draw user preferences $x_u \\sim \\textrm{\\bf Gamma}(b,c)$\n\\item Draw artist-level topics $\\beta_a \\sim \\textrm{\\bf Gamma}(d,e)$\n\\item Draw song-level topics $\\beta_i \\sim \\textrm{\\bf Gamma}(f,g)$\n\\item Draw user-artist rating $r_{ua} \\sim \\textrm{\\bf Poisson}(x_u^T \\beta_a)$\n\\item Draw user-song rating $r_{uai} \\sim \\textrm{\\bf Poisson}(x_u^T(\\beta_a + \\beta_i))$\n\\end{enumerate}\n\n\\section{Inference}\n\nStructured Stochastic Variational Inference (SSVI) was recently introduced \\parencite{Hoffman2014} as a method to add some dependencies between global and local parameters (as opposed to mean-field inference where there are no such dependencies). Here we derive SSVI first for Poisson factorization \\citep{Gopalan2013}, and then for the user-artist-song model (Figure \\ref{fig:uasmodel}).\n\n\\section{Experiments}\n\nSSVI was used to fit Poisson factorization to the million song data set \\citep{Liang2014}. The precision was 8.5\\% (compared to 5.2\\% for content-based Poisson factorization from last semester).\n\n\\printbibliography\n\n\\end{document}\n\n%%% Local Variables:\n%%% mode: tex-pdf\n%%% TeX-master: t\n%%% End:\n", "meta": {"hexsha": "cf5bd9005e8297592b5718b52ab7e3e2a8880985", "size": 3778, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/old/user-artist-song model.tex", "max_stars_repo_name": "altosaar/user-artist-song-poisson-factorization", "max_stars_repo_head_hexsha": "e569cea56ae42c0332b2c5312fb0cf696e6bb2a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-11-22T13:03:24.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-22T13:03:24.000Z", "max_issues_repo_path": "doc/old/user-artist-song model.tex", "max_issues_repo_name": "altosaar/user-artist-song-poisson-factorization", "max_issues_repo_head_hexsha": "e569cea56ae42c0332b2c5312fb0cf696e6bb2a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/old/user-artist-song model.tex", "max_forks_repo_name": "altosaar/user-artist-song-poisson-factorization", "max_forks_repo_head_hexsha": "e569cea56ae42c0332b2c5312fb0cf696e6bb2a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-07-05T21:22:22.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-05T21:22:22.000Z", "avg_line_length": 31.4833333333, "max_line_length": 388, "alphanum_fraction": 0.7503970355, "num_tokens": 1141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3071410095018976}}
{"text": "%! Author = tstreule\n\n\\section{Amperometric Sensors}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Electrochemistry}\n%\n\\formbox{Overpotential}{\\eta \\equiv \\Delta\\phi\\ped{appl} {-} \\Delta\\phi^0 \\equiv \\phi_s {-} \\phi_m \\equiv E {-} E^0}\n{\\hfill\\scriptsize $E^0$: Nernst}%\n\\formula{~}{\\eta = 0}\n\\quad (\\textbf{equilibrium} i.e. no net current)\n\n\\formula{\\textbf{Faraday's law}}{\n    \\textcolor{gray}{\n        \\textit{1st: } n\\propto Q \\textit{,\\quad 2nd: } \\textrm{(equiv. weigth) } W\\ped{eq} = M/z\n    }\n}\n\\formbox{\\textbf{of electrolysis}}{m = \\frac{Q}{z\\;F}\\;M = \\frac{I\\;t}{z\\;F}\\;M = n\\cdot M}\n\\enskip \\textcolor{gray}{\\scriptsize $[m] {=} \\unit{g}$, $[n] {=} \\unit{mol}$}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Butler-Volmer equation \\textnormal{Effect of $\\eta$ on barrier heigth $G$}}\n\\label{sec:butler-volmer}\n%\n\\begin{tabular}{r@{:\\quad}l}\n    Let\n    $\\phi_s$\t& potential of ions in solution\\\\\n    $\\phi_m$\t& potential of $e^-$ in (metallic) electrode\\\\\n    $z$\t\t\t& valency of oxidized species\\\\\n    $n$\t\t\t& \\#of transferred $e^-$\\\\\n    $z-n$\t\t& valency of reduced species\n\\end{tabular}\n\\formula{\\textbf{transfer coeff. $\\alpha$}}{nF\\eta = n(1-\\alpha)F\\eta+n\\alpha F\\eta}\n%\t\t\\formula{@equilibrium ($\\eta=0$)}{k_0 \\equiv k\\ped{red}=k\\ped{ox}}\n\\scalebox{.9}{%\n    \\formbox{\\fbox{$f{\\equiv}\\frac{F}{RT} {\\overset{@\\unit[298]{K}}{=}} \\frac{1}{\\SI{25.69}{\\milli\\volt}}$}}{%\n        k\\ped{red} {=} k_0\\;\\eu^{-n\\alpha f\\eta}, \\enskip\n        k\\ped{ox}  {=} k_0\\;\\eu^{n(1-\\alpha)f\\eta}\n    }\t\\shortstack[l]{\n        @equi. ($\\eta=0$)\\\\\n        $k_0 {\\equiv} k\\ped{red} {=} k\\ped{ox}$\n    }\n}\n\nThe Butler-Vomer eq. relates what we measure (the \\textbf{current}) with what we would like to determine (the \\textbf{concentration} of an analyte):\n\\scalebox{.9}{%\n    \\formbox{\\textbf{Butler-Volmer}}{j = \\underbrace{nFAk_0\\vspace{-1mm}}_{\\vspace{-2mm}j_0} \\big( C\\ped{ox}(0,t)\\;\\eu^{-\\alpha nf\\eta} - C\\ped{red}(0,t)\\;\\eu^{(1-\\alpha)nf\\eta} \\big)}}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Cyclic Voltammetry}\n%\n\\begin{minipage}{.4\\columnwidth}\n    \\includegraphics[width=.9\\columnwidth]{Electrochemistry_Cyclic_Voltammetry}\n\\end{minipage}%\n\\begin{minipage}{.6\\columnwidth}\n    Offers information on the mechanism of the ec reactions occuring at an electrode.\n    \\begin{itemize}\n        \\item May be irreversible\\\\\n        $\\to$ \\#upper peaks $\\neq$ \\#lower peaks\\\\\n        $\\to$ irreversible reaction fast\n        \\item Sweep rate\\\\\n        $\\to$ irreversible reaction slow\n    \\end{itemize}\n\\end{minipage}\n\\formtex{\\textbf{Water electrolysis}}{High potentials/volt's}\n%$\\to$ affects $I$ %(disturbance, bad)\n\\formtex{~}{$\\to$ affects $I$ (disturbance, bad)}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Amperometric Sensors}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Clark \\textnormal{(Oxygen)} Electrode \\hfill\\textnormal{$\\to$ Measure \\ce{O2}}}\n%\n\\begin{itemize}\n    \\item test solution \\ce{->[O2 passes][membrane]} \\ce{Pt} cathode \\ce{->[reduction]} current\n    \\item \\ce{Ag} anode is in \\ce{KCl} solution ($\\to$ ``enough'' \\ce{Cl-} for oxidation)\n\\end{itemize}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{1st and 2nd Generation}\n%\n$\t\\textrm{analyte of interest}\n\\;\\ldots\\;\n\\underbrace{\\textrm{redox enzyme}\\vspace{-1.5mm}}_{\\vspace{-2.5mm}\\textrm{catalize}}\n\\;\\underbrace{\\ldots\\vspace{-.5mm}}_{\\vspace{-2.5mm}\\textrm{P1}}\\;\n\\underbrace{\\textrm{mediator}\\vspace{-1mm}}_{\\vspace{-2.5mm}\\textrm{P2}}\n\\;\\ldots\\;\n\\textrm{Clark Electrode}\n$\n\\formtex{problem P1 (1st)}{\\ce{O2} may be consumed, when not measured}\n\\formtex{problem P2 (2nd)}{need to have ``enough'' of them}\n\\formtex{Mediator has to be}{$\\bullet$ reversible \\quad $\\bullet$ not toxic \\quad $\\bullet$ no side reactions}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{3rd Generation}\n%\n\\textit{Immobilization}/fixation of a redox enzyme on electrode surface\n\n$\\to$ free-diffusing redox mediators are not necessary\\\\\n$\\to$ in vivo measurments allowed since immobilized\n\n\\formtex{problem P3}{Efficient electron transfer (Marcus theory)}\\vspace{-1mm}\n\\formtex{~}{$\\to$ may be overcome by mediators}\\vspace{-1mm}\n\\formtex{~}{$\\to$ minimize ET distance}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Three Electrode Cell}\n%\n\\begin{minipage}{.5\\columnwidth}\n    \\includegraphics[width=\\columnwidth]{Electrochemistry_Three_Electrode_Cell}\n\\end{minipage}%\n\\hspace{1cm}\n\\begin{minipage}{.5\\columnwidth-1cm}\n    $\\frac{U\\ped{REF}}{R_2} = - \\frac{U\\ped{in}}{R_1}$\n    \\par\n    $I = \\frac{U\\ped{out}}{R_3}$\n\\end{minipage}\n", "meta": {"hexsha": "1b289ddf20b582fc3a83c485161c2394f324e327", "size": 4722, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/BE18/sections/10_amperometric_sensors.tex", "max_stars_repo_name": "tstreule/eth-cheat-sheets", "max_stars_repo_head_hexsha": "c61f9fd3b13edf405f790581b4d5eacb50b4f1c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-26T23:11:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T23:11:57.000Z", "max_issues_repo_path": "src/BE18/sections/10_amperometric_sensors.tex", "max_issues_repo_name": "tstreule/eth-cheat-sheets", "max_issues_repo_head_hexsha": "c61f9fd3b13edf405f790581b4d5eacb50b4f1c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BE18/sections/10_amperometric_sensors.tex", "max_forks_repo_name": "tstreule/eth-cheat-sheets", "max_forks_repo_head_hexsha": "c61f9fd3b13edf405f790581b4d5eacb50b4f1c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.1607142857, "max_line_length": 185, "alphanum_fraction": 0.5919102075, "num_tokens": 1617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3071263493835959}}
{"text": "\\documentclass{article}\n\n\\usepackage{times}\n\\usepackage{graphicx} % more modern\n\\usepackage{natbib}\n\\usepackage{algorithm, algorithmic}\n\\usepackage{hyperref}\n\\usepackage{amssymb, mathtools}\n\\usepackage{xcolor,colortbl}\n\\newcommand{\\theHalgorithm}{\\arabic{algorithm}}\n\\usepackage{subcaption} % for \"subfigure\" environment\n\\usepackage{geometry} \n\n\n\n\n\n\n\\usepackage[accepted]{icml2017} \n\n\n\n% The \\icmltitle you define below is probably too long as a header.\n% Therefore, a short form for the running title is supplied here:\n\\icmltitlerunning{Globally Induced Forest}\n\n% ============================== CONFIG =================================== %\n\\graphicspath{{./images/}}\n\\captionsetup[figure]{size=footnotesize}\n% ============================== COLORS =================================== %\n\\definecolor{orange}{HTML}{FFA500}\n\\definecolor{dodgerblue}{HTML}{1E90FF}\n\\definecolor{deepgreen}{HTML}{0AF191}\n\\definecolor{purplish}{HTML}{E21173}\n\n% ============================== COMMANDS =================================== %\n\\DeclareMathOperator*{\\argmin}{arg\\,min}\n\\DeclareMathOperator*{\\argmax}{arg\\,max}\n\n\n\\newcommand{\\best}{\\cellcolor{lightgray}}\n\\newcommand{\\bestA}{\\cellcolor{orange}}\n\\newcommand{\\bestB}{\\cellcolor{dodgerblue}}\n\n\n\\begin{document} \n\\twocolumn[\n\\icmltitle{Globally Induced Forest: A Prepruning Compression \nScheme\\\\Supplementary material}\n\n% It is OKAY to include author information, even for blind\n% submissions: the style file will automatically remove it for you\n% unless you've provided the [accepted] option to the icml2017\n% package.\n\n% list of affiliations. the first argument should be a (short)\n% identifier you will use later to specify author affiliations\n% Academic affiliations should list Department, University, City, Region, \n%Country\n% Industry affiliations should list Company, City, Region, Country\n\n% you can specify symbols, otherwise they are numbered in order\n% ideally, you should not use this facility. affiliations will be numbered\n% in order of appearance and this is the preferred way.\n\\icmlsetsymbol{equal}{*}\n\n\\begin{icmlauthorlist}\n\\icmlauthor{Jean-Michel Begon}{ulg}\n\\icmlauthor{Arnaud Joly}{ulg}\n\\icmlauthor{Pierre Geurts}{ulg}\n\\end{icmlauthorlist}\n\n\\icmlaffiliation{ulg}{Department of Electrical Engineering and Computer Science\nUniversity of Li\\`ege, Li\\`ege, Belgium}\n\n\\icmlcorrespondingauthor{Jean-Michel Begon}{jm.begon@ulg.ac.be}\n%\\icmlcorrespondingauthor{Arnaud Joly}{a.joly@ulg.ac.be}\n\\icmlcorrespondingauthor{Pierre Geurts}{p.geurts@ulg.ac.be}\n\n% You may provide any keywords that you \n% find helpful for describing your paper; these are used to populate \n% the \"keywords\" metadata in the PDF but will not be shown in the document\n\n\\icmlkeywords{Decision tree, Random forest, Extremely randomized trees, \npruning, node budget, memory constraint, compression, growing algorithm, greedy \nselection}\n\n\\vskip 0.3in\n]\n\n\\printAffiliationsAndNotice{}\n\n\n\n\n\\section{GIF algorithm}\nFigure \\ref{fig:gif-algo} illustrates visually the inner loop of the GIF \nbuilding algorithm: a subset of the candidates nodes is chosen uniformely at \nrandom. The contribution of each node is evaluated and the one which reduces \nthe error the most is added to the model. Its children are then built and added \nto the candidate list.\n\n\\begin{figure*}[ht]    \n  \\begin{subfigure}[b]{0.5\\linewidth}\n    \\centering\n    \\includegraphics[height=0.25\\textheight]{gif_algo1} \n    \\caption{Current forest at time $t$} \n    \\label{fig:gif-algo1} \n  \\end{subfigure} \n  \\hspace{\\fill}  %% maximize space between adjacent subfigures\n  \\begin{subfigure}[b]{0.5\\linewidth}\n    \\centering\n    \\includegraphics[height=0.25\\textheight]{gif_algo2} \n    \\caption{A subset of candidates $C_t$  is drawn uniformely at random from \n    the set of candidates $C$ (step 8)} \n    \\label{fig:gif-algo2} \n  \\end{subfigure} \n\n  \\vspace{4ex}  %% extra vertical space\n  \\begin{subfigure}[b]{0.5\\linewidth}\n    \\centering\n    \\includegraphics[height=0.25\\textheight]{gif_algo3} \n    \\caption{The error reduction is computed for all candidates of $C_t$ (step \n    9)} \n    \\label{fig:gif-algo3} \n  \\end{subfigure} \n  \\hspace{\\fill}\n  \\begin{subfigure}[b]{0.5\\linewidth}\n    \\centering\n    \\includegraphics[height=0.25\\textheight]{gif_algo4} \n    \\caption{The best node (highest error reduction) is selected (step 9)} \n    \\label{fig:gif-algo4} \n  \\end{subfigure} \n\n    \\vspace{4ex}\n  \\begin{subfigure}[b]{0.5\\linewidth}\n    \\centering\n    \\includegraphics[height=0.25\\textheight]{gif_algo5} \n    \\caption{The chosen node is introduced in the model (step 10)} \n    \\label{fig:gif-algo5} \n  \\end{subfigure}\n  \\hspace{\\fill}\n  \\begin{subfigure}[b]{0.5\\linewidth}\n    \\centering\n    \\includegraphics[height=0.25\\textheight]{gif_algo6} \n    \\caption{The children of the chosen node are computed (step 11) and added \n    to the candidate list (step 12)} \n    \\label{fig:gif-algo6} \n  \\end{subfigure} \n\n\\caption{Illustration of the GIF regression building algorithm ($T=3$, $CW=3$)}\n\\label{fig:gif-algo} \n\\end{figure*}\n\n\n\n\\section{Optimization problem}\n\nWe are building an additive model by inserting progressively nodes in the \nforest.\nAt time $t$, we are trying to find the best node $j^{(t)}$ from the candidate \nlist $C_t$ and its associated optimal weight $w_j^{(t)}$:\n\\begin{align}\nj^{(t)},w_j^{(t)} =\\argmin_{j\\in C_t, w\\in \\mathbb{R}^K} \\sum_{i=1}^{N} L \n\\left(y_i, \n\\hat{y}^{(t-1)}(x_i) + w z_j(x_i) \\right)\n\\end{align}\nwhere $(x_i, y_i)_{i=1}^N$ is the learning sample, $\\hat{y}^{(t-1)}()$ is the \nmodel at time $t-1$, $z_j()$ is the node indicator functions, meaning that it \nis $1$ if its argument reaches node $j$ and $0$ otherwise.\n\nThis problem is solved in two steps. First a node $j$ is selected from $C_t$ \nand the corresponding optimal weight, alongside the error reduction, are \ncomputed. This is repeated for all nodes and the one achieving the best \nimprovement is selected.\n\n\\paragraph{Regression}\nFor regression, we used the L2-norm:\n\\begin{align}\nw_j^{(t)} = \\argmin_{w\\in \\mathbb{R}} \\sum_{i=1}^{N} L \\left(y_i, \n\\hat{y}^{(t-1)}(x_i) + w z_j(x_i) \\right)^2\n\\end{align}\nand the solution is given by\n\\begin{align}\\label{eq:L2Solution}\nw_j^{(t)} = \\frac{1}{|Z_j|} \\sum_{i \\in Z_j} r_i^{(t-1)}\n\\end{align}\nwhere $r_i^{(t-1)} = y_i - \\hat{y}^{(t-1)}(x_i)$ is the residual at time $t-1$ \nfor the $i$th training instance and $Z_j = \\{1 \\leq i \\leq N | z_j(x_i)=1\\}$ is \nthe subset of instances reaching node $j$.\n\n\\paragraph{Classification}\nFor classification we used the multi-exponential loss \n\\cite{zhu2009multiadaboost}. First, we need to encode the labels so that\n\\begin{align}\\label{eq:MEencode}\ny_i^{(k)} = \\begin{cases}\n1, &\\text{ if the class of } y_i \\text{ is } k \\\\\n-\\frac{1}{K-1}, &\\text{otherwise}\n\\end{cases}\n\\end{align}\nwhere $K$ is the number of classes. Notice that $\\sum_{k=1}^{K} y_i^{(k)} = 0$.\nThe optimization then becomes\n\\begin{align}\\label{eq:MEmin}\nw_j^{(t)} &=  \\argmin_{w \\in \\mathbb{R}^K} \\sum_{i=1}^N \\exp \n\\left(\\frac{-1}{K} y_i^T \\left(\\hat{y}^{(t-1)}(x_i) + w z_j(x_i) \\right)\\right) \n\\\\\n&= \\argmin_{w \\in \\mathbb{R}^K} F_j^{(t-1)}(w)\n\\end{align}\nSolving for $\\nabla F_j^{(t-1)}(w) = 0$ yields\n\\begin{align}\\label{eq:MErawSol}\n\\alpha_j^{(t-1, k)}\\phi^{(k)}(w) = \\frac{1}{K} \\sum_{l=1}^{K} \\alpha_j^{(t-1, \nl)}\\phi^{(l)}(w)\n\\end{align}\nfor $1 \\leq k\\leq K$, where\n\\begin{align}\n\\alpha_j^{(t-1, k)} &\\triangleq \\sum_{i \\in Z_j^{(k)}} \\exp \\left( - \n\\mu_i^{(t-1)} \\right) \\\\\n\\mu_i^{(t-1)} &\\triangleq \\frac{1}{K} \\sum_{k=1}^{K} y_i \\hat{y}^{(t-1, \nk)}(x_i) \\\\\n\\phi^{(k)}(w) &\\triangleq \\exp \\left( - \\frac{1}{K} \\psi^{(k)}(w) \\right) \\\\\n\\psi^{(k)}(w) &\\triangleq -w^{(k)} + \\frac{1}{K-1} \\sum_{l=1, l\\neq k}^{K}  \nw^{(l)}\n\\end{align}\nwhere $Z_j^{(k)} = \\{1 \\leq i \\leq N | z_{i,j} = 1 \\wedge y_i^{(k)} = 1 \\}$ is \nthe subset of learning instances of class $k$ reaching node $j$. In words, \n$\\mu_i^{(t-1)}$ is the hyper-margin of instance $i$ at time $t-1$ and \n$\\alpha_j^{(t-1, k)}$ is the class error of label $k$ for node $j$ at time \n$t-1$.\n\n\nEquation \\ref{eq:MErawSol} is equivalent to\n\\begin{align}\\label{eq:MEequation}\n\\alpha_j^{(t-1, k)}\\phi^{(k)}(w) &= \\alpha_j^{(t-1, l)}\\phi^{(l)}(w) \\quad 1 \n\\leq k,l \\leq K\n\\end{align}\n\n\nIn keeping with the output representation (Equation \\ref{eq:MEencode}), we can \nimpose a zero-sum constraint on the prediction to get a unique solution for the \n$k$th component of $w_j^{(t)}$. If it is imposed at each stage, it means that\n\\begin{align}\\label{eq:MEzeroSum}\n\\sum_{k=1}^{K} \\hat{y}^{(t-1, k)} = \\sum_{k=1}^{K} \n\\hat{y}^{(t, k)} = 0 = \\sum_{k=1}^{K} w^{(k)}\n\\end{align}\nand this is not impacted by the learning rate. \n\nThe corresponding solution is\n\\begin{align}\n\\phi^{(k)}(w) &= \\exp \\left(-\\frac{1}{K-1} w^{(k)}\\right)\\\\ \n\\label{eq:MEClsErrZS}\n\\alpha_j^{(t-1, k)} &= \\sum_{i \\in Z_j^{(k)}} \\exp \\left( -\\frac{1}{K-1} \n\\hat{y}^{(t-1, k)}(x_i) \\right) \\\\ \\label{eq:MEsolution}\nw_j^{(t,k)} &= \\frac{K-1}{K}  \\sum_{l=1}^{K} \\log \\frac{\\alpha_j^{(t-1, \nk)}}{\\alpha_j^{(t-1, l)}} \n\\end{align}\n\n\n\n\n\n\n\n\n\n\\section{Equivalence of GIF and the underlying tree}\\label{app:Equiv}\nIn the case of a single tree ($T=1$) and a unit learning rate ($\\lambda=1$), \nboth the square loss in regression and the multiexponential loss in \nclassification produce the same predictions as the underlying tree. \nThis is due to the fact that, when examining the weight to give to node $j$ at \ntime $t$, the prediction of time $t-1$ relates to the parent node $\\pi_j$ of \n$j$. It is thus independent of $t$ and is also the same for all instances \nreaching that node. \n\nConsequently, we will adopt the following slight change in notation:\n\\begin{align}\n\\hat{y}_j = \\hat{y}_{(\\pi_j)} + w_j\n\\end{align}\nmeaning that the prediction associated to any object reaching node $j$ is the \nweight of $j$ plus the prediction associated to its parent $\\pi_j$. With  \n$\\hat{y}_{(\\pi_1)} = 0$, the prediction of the root's pseudo-parent.\n\n\\subsection{Regression}\nIn regression, the tree prediction $Tr_j$ of any leaf $j$ is the average of the \nlearning set's outputs reaching that node: $Tr_j = \\frac{1}{|Z_j|}\\sum_{i \\in \nZ_j} y_i$. We need to show that the GIF prediction is:\n\\begin{align}\\label{eq:EquivL2Cond}\n\\hat{y}_{j} = \\frac{1}{|Z_j|}\\sum_{i \\in Z_j} y_i\n\\end{align}\n\n\n\nThe prediction of node $j$ is\n\\begin{align}\\label{eq:EquivL2Solution}\n\\hat{y}_j &= \\hat{y}_{\\pi_j} + w_j \\\\\n&= \\hat{y}_{\\pi_j} +  \\frac{1}{|Z_j|} \\sum_{i \\in Z_j} \\left(y_i - \n\\hat{y}_{\\pi_j}\\right) \\\\\n&= \\hat{y}_{\\pi_j} + \\frac{1}{|Z_j|} \\sum_{i \\in Z_j} \\left( y_i \\right) - \n\\hat{y}_{\\pi_j} \\\\\n&= \\frac{1}{|Z_j|} \\sum_{i \\in Z_j}  y_i \n\\end{align}\n\n\nThe first step is how the additive model is built. The second is the optimal \nweight value of node $j$ derived in Equation \\ref{eq:L2Solution}, the third \nstep is due to the fact that the prediction at $\\pi_j$ is constant since there \nis only one tree.\n\n\\subsection{Classification}\nIn order to have the same prediction as the underlying tree, we must \ndemonstrate that the probability of being in class $l$ associated to node $j$ \nwill be $\\frac{|Z_j^{(l)}|}{|Z_j|}$.\n\nUnder the zero-sum constraint, we have\n\\begin{align} \n\\exp \\left(  \\frac{1}{K-1} w_j^{(l)}\\right) &= \\frac{1}{c_j} \n\\alpha_{\\pi_j}^{(l)} \\\\\n&=  \\frac{1}{c_j} \\sum_{i \\in Z_j^{(l)}} \\exp \\left(-\\frac{1}{K-1} \n\\hat{y}_{\\pi_j}^{(l)}\\right)\\\\\n&= \\frac{1}{c_j} |Z_j^{(l)}| \\exp \\left(-\\frac{1}{K-1} \n\\hat{y}_{\\pi_j}^{(l)}\\right) \\\\\n\\exp \\left(\\frac{1}{K-1} \\hat{y}_j^{(l)} \\right) &= \\exp \\left(\\frac{1}{K-1} \n\\hat{y}_{\\pi_j}^{(l)} \\right) \\exp \\left(\\frac{1}{K-1} w_j^{(l)}\\right) \\\\\n&= \\frac{1}{c_j} |Z_j^{(l)}| \\\\\nP_j(l) &= \\frac{\\exp \\left(\\frac{1}{K-1} \\hat{y}_j^{(l)}\n\\right)}{\\sum_{k=1}^K\\exp \\left(\\frac{1}{K-1} \\hat{y}_j^{(k)} \\right)} = \n\\frac{|Z_j^{(l)}|}{|Z_j|}\n\\end{align}\t\nwhere $c_j = \\left(\\prod_{k=1}^K \\alpha_j^{(k)}\\right)^{\\frac{1}{K}}$ is a \nconstant. The first equality is a consequence of the value of $w_j^{(l)}$ \n(Equation \\ref{eq:MEsolution}). The second is a due to the definition of \n$\\alpha_j^{(l)}$ (Equation \\ref{eq:MEClsErrZS}). The third is a consequence of \nhaving a single tree: the prediction of the parent is the same for all \ninstances.\n\n\nNotice that, in both regression and classification, the equivalence also holds \nfor an internal node: the prediction is the one the tree would have yielded if \nthat node had been a leaf.\n\n\n\\section{Datasets}\n\nTable \\ref{tab:datasets} sums up the main characteristics of the datasets we \nused. Abalone, CT slice, California data housig (Cadata), Musk2, Vowel and \nLetter come from the UCI Machine Learning Repository \\cite{uci}. Ringnorm, \nTwonorm and Waveform are described in \\cite{breiman1998arcing}. Hwang F5 comes \nfrom the DELVE repository \\footnote{http://www.cs.utoronto.ca/∼delve}.\nThe noise parameter of the Friedman1 dataset \\cite{friedman11991} has \nbeen set to $1$. Hastie is described in \\cite{hastie2009}. Out of the 500 \nfeatures of Madelon \\cite{guyon2004madelon}, 20 are informative and 50 are \nredundant; the others are noise.\nMnist8vs9 is the Mnist dataset \\cite{lecun1998mnist} of which only the $8$ and \n$9$ digits have been kept. Binary versions of the Mnist, Letter and Vowel \ndatasets have been created as well by grouping the first half and second half \nclasses together.\n\n\\begin{table}[th]\n\\caption{Characteristics of the datasets. $N$ is the learning sample size, TS \nstands for testing set, and $p$ is the number of features.}\n\\label{tab:datasets}\n\\begin{center}\n\\begin{footnotesize}\n\\begin{sc}\n\\begin{tabular}{l|cccc}\n\\hline\nDataset & $N$ & $|TS|$ & $p$ & \\# classes\\\\\n\\hline\nFriedman1 & 300 & 2000 & 10 & - \\\\\nAbalone & 2506 & 1671 & 10 & - \\\\\nCT slice & 2000 & 51500 & 385 & - \\\\\nHwang F5 & 2000 & 11600 & 2 & - \\\\\nCadata & 12384 & 8256 & 8 & - \\\\\nRingnorm & 300 & 7100 & 20 & 2 \\\\\nTwonorm & 300 & 7100 & 10 & 2 \\\\\nHastie & 2000 & 10000 & 10 & 2 \\\\\nMusk2 & 2000 & 4598 & 166 & 2 \\\\\nMadelon & 2200 & 2200 & 500 & 2 \\\\\nMnist8vs9 & 11800 & 1983 & 784 & 2 \\\\\nWaveform & 3500 & 1500 & 40 & 3 \\\\\nVowel & 495 & 495 & 10 & 11 \\\\\nMnist & 50000 & 10000 & 784 & 10 \\\\\nLetter & 16000 & 4000 & 8 & 26 \\\\\n\\hline\n\\end{tabular}\n\\end{sc}\n\\end{footnotesize}\n\\end{center}\n\\vskip -0.2in\n\\end{table}\n\n\\section{Comparison with local baseline algorithms}\nWe have tested three deepening algorithm for decision forest relying on \nnon-global metrics, meaning that the choice of the best candidate is not made \naccording to how well the forest, as a whole, performs. These algorithms share \nthat the final model is exactly a sub-forest of the un-pruned forest: contrary \nto GIF, no internal weights are fitted and the predictions of at the leaves are \nthe usual tree predictions.\n\n\\paragraph{Breadth first deepening}\nThis variant consist in adding the nodes level after level, from left to right, \nproducing a heaped forest. As a consequence, all trees have the same (order of) \nheight, implying that the forest can be quite wide but usually shallow.\n\n\\paragraph{Random deepening}\nThis variant consist in first choosing a tree and then choosing one of its \nleaves to transform to a decision nodes. Both choices are made uniformly at \nrandom so that the trees are expected to have approximately the same number of \nnodes. The depth, however, might vary significantly.\n\n\\paragraph{Best first deepening}\nThis variant consist in choosing, among all leaves which could be turned into a \ninternal node, the one which reduces its local impurity the most. \nLet $N_c$, $N_l$ and $N_r$ be the number of instances \nreaching the candidate node, candidate left child and candidate right child \nrespectively.\nLet also $I_c$, $I_l$ and $I_r$ be the impurity (gini index in classification, \nvariance in regression) of the instances reaching the candidate node, candidate \nleft child and candidate right child respectively. \nThen, for $N$ learning instances, the local impurity reduction is \ndefined as:\n\n\\begin{align}\n\\Delta I_c \\triangleq \\frac{N_c}{N} \\left[ I_c - \\left( \\frac{N_l}{N_c} I_l + \n\\frac{N_r}{N_c} I_r \\right)\\right]\n\\end{align}\n\nSince the fraction of learning instances reaching the candidate is accounted \nfor in the reduction of impurity, this approach will naturally favor higher \nnodes in the trees.\n\n\n\\begin{table*}[t]\n\\caption{Average mean square error for local baselines at $1\\%$ and $10\\%$ \nbudgets  ($T=1000$, $m=p$).}\n\\vskip -0em\n\\label{tab:baseline-reg}\n\\begin{center}\n\\begin{footnotesize}\n\\begin{sc}\n\\begin{tabular}{l|ccc|ccc}\n\\hline\nDataset & Breadth First$_{10\\%}$ & Random$_{10\\%}$ & Best First$_{10\\%}$ & \nBreadth First$_{1\\%}$ & Random$_{1\\%}$ & Best First$_{1\\%}$ \\\\\n\\hline\nFriedman1 & 6.02 $\\pm$ 0.28 & 6.80 $\\pm$ 0.34 & 15.00 $\\pm$ 0.39 & 11.73 $\\pm$ \n0.46 & 12.52 $\\pm$ 0.47 & 15.29 $\\pm$ 0.42  \\\\\nAbalone & \\best 4.72 $\\pm$ 0.23 & 4.77 $\\pm$ 0.23 & 6.82 $\\pm$ 0.33 & 5.42 \n$\\pm$ 0.27 & 5.55 $\\pm$ 0.27 & 6.82 $\\pm$ 0.33 \\\\\nCT slice &  30.39 $\\pm$ 1.90 & 36.19 $\\pm$ 1.84 & 310.87 $\\pm$ 4.79 & 82.19 \n$\\pm$ 2.41 & 97.24 $\\pm$ 1.90 & 313.84 $\\pm$ 4.64  \\\\\nHwang F5 \\hfill {\\tiny $\\times 10^{-2}$} & \\best 6.73 $\\pm$ 0.07 & 6.83 $\\pm$ \n0.06 & 56.57 $\\pm$ 6.03 & 8.52 $\\pm$ 0.24 & 13.17 $\\pm$ 0.44 & 56.60 $\\pm$ 6.07 \n\\\\\nCadata \\hfill {\\tiny $\\times 10^{-2}$} & 29.24 $\\pm$ 0.73 & 31.08 $\\pm$ 0.74 & \n75.23 $\\pm$ 0.95  & 43.40 $\\pm$ 1.18 & 47.47 $\\pm$ 1.02 & 75.48 $\\pm$ 0.95 \\\\\n\\hline\n\\end{tabular}\n\\end{sc}\n\\end{footnotesize}\n\\end{center}\n\\vskip -0.2in\n\\end{table*}\n\n\n\\begin{table*}[t]\n\\caption{Error rate ($\\%$) for local baselines at $1\\%$ and $10\\%$ budgets \n($T=1000$, $m=\\sqrt{p}$). The six first datasets are binary classification. The \nlast three are multiclass. The three in the middle are their binary versions.}\n\\vskip -1em\n\\label{tab:baseline-cls}\n\\begin{center}\n\\begin{footnotesize}\n\\begin{sc}\n\\begin{tabular}{l|ccc|ccc}\n\\hline\nDataset & Breadth First$_{10\\%}$ & Random$_{10\\%}$ & Best First$_{10\\%}$ & \nBreadth First$_{1\\%}$ & Random$_{1\\%}$ & Best First$_{1\\%}$ \\\\\n\\hline \nRingnorm & 4.25 $\\pm$ 1.24 & 4.08 $\\pm$ 1.12 & 8.38 $\\pm$ 6.94 &  8.94 $\\pm$ \n7.45 & 8.53 $\\pm$ 7.04 & 8.94 $\\pm$ 7.41 \\\\\nTwonorm & 3.51 $\\pm$ 0.26 & 3.53 $\\pm$ 0.30 & 5.59 $\\pm$ 1.85  & 5.91 $\\pm$ \n3.03 & 6.52 $\\pm$ 4.28 & 7.28 $\\pm$ 4.34 \\\\\nHastie & 11.30 $\\pm$ 1.20 & 11.18 $\\pm$ 1.16 & 21.24 $\\pm$ 7.11  & 13.92 $\\pm$ \n2.93 & 14.29 $\\pm$ 3.20 & 21.24 $\\pm$ 7.12 \\\\\nMusk2 & 7.01 $\\pm$ 0.40 & 7.63 $\\pm$ 0.43 & 15.42 $\\pm$ 0.23 & 15.42 $\\pm$ 0.23 \n& 15.42 $\\pm$ 0.23 & 15.42 $\\pm$ 0.23 \\\\\nMadelon & 11.68 $\\pm$ 0.67 & 11.92 $\\pm$ 0.65 & 19.12 $\\pm$ 1.94 & 16.26 $\\pm$ \n0.97 & 16.70 $\\pm$ 1.07 & 20.14 $\\pm$ 2.41 \\\\\nMnist8vs9 & 2.20 $\\pm$ 0.38 & 2.37 $\\pm$ 0.39 & 6.17 $\\pm$ 0.73  & 4.53 $\\pm$ \n0.48 & 4.84 $\\pm$ 0.51 & 6.67 $\\pm$ 0.69 \\\\\n\\hline\nBin. Vowel &8.99 \n$\\pm$ 1.96 & 8.85 $\\pm$ 2.03 & 16.57 $\\pm$ 3.02  & 18.73 $\\pm$ 3.08 & 19.90 \n$\\pm$ 3.71 & 21.80 $\\pm$ 4.38 \\\\\nBin. Mnist & 4.46 $\\pm$ 0.25 & 4.91 $\\pm$ 0.27 & 21.71 $\\pm$ 0.30  & 10.09 \n$\\pm$ 0.25 & 11.78 $\\pm$ 0.32 & 22.50 $\\pm$ 0.35\\\\\nBin. Letter & 5.91 $\\pm$ 0.43 & 5.71 $\\pm$ 0.40 & 26.16 $\\pm$ 0.86  & 17.91 \n$\\pm$ 0.77 & 18.05 $\\pm$ 0.78 & 26.19 $\\pm$ 0.88 \\\\\n\\hline\nWaveform & 14.74 $\\pm$ 0.63 & 14.83 $\\pm$ 0.76 & 20.25 $\\pm$ 2.22 & 16.75 $\\pm$ \n1.26 & 17.13 $\\pm$ 1.25 & 20.45 $\\pm$ 2.21 \\\\\nVowel & 14.26 $\\pm$ 2.41 & 13.21 $\\pm$ 2.33 & 41.49 $\\pm$ 5.45 & 42.40 $\\pm$ \n4.33 & 40.28 $\\pm$ 4.62 & 50.44 $\\pm$ 5.81 \\\\\nMnist & 4.63 $\\pm$ 0.27 & 4.96 $\\pm$ 0.26 & 28.54 $\\pm$ 0.59 & 8.60 $\\pm$ 0.35 \n& 9.76 $\\pm$ 0.31 & 29.72 $\\pm$ 0.61 \\\\\nLetter & 7.06 $\\pm$ 0.29 & 6.39 $\\pm$ 0.20 & 36.92 $\\pm$ 1.80 & 22.11 $\\pm$ \n0.59 & 20.90 $\\pm$ 0.55 & 37.27 $\\pm$ 1.78 \\\\\n\\hline\n\\end{tabular}\n\\end{sc}\n\\end{footnotesize}\n\\end{center}\n\\vskip -0.2in\n\\end{table*}\n\n\\paragraph{Experiment}\nWe conducted the same experiment as for GIF: the three algorithms were tested \non ten folds with different learning sample/testing sample splits and were \nsubjected to the $1\\%$ and $10\\%$ node constraints. We started with a pool of \n$T=1000$ roots and no restriction was imposed regarding the depth. All of the \n$m=p$ the features were examined in regression and $m=\\sqrt{p}$ in \nclassification, as suggested in \\cite{extratrees}. Table \\ref{tab:baseline-reg} \nholds the average mean square error for the five regression problems and Table \n\\ref{tab:baseline-cls} holds the average misclassification rate for the \nclassification problems.\n\n\\paragraph{Regression}\nThe trend is quite clear: both at $1\\%$ and $10\\%$, the breadth first algorithm \nis the best and the best first is (largely) the worst. \nThere are two instances where the local baselines are able to beat GIF: on \nAbalone and Hwang F5 at $10\\%$. Interestingly, these are the same cases on \nwhich GIF was beaten by a small forest of Extremely randomized trees. The \n$10\\%$ Hwang F5 case aside, the local baselines always underperform the smaller \nfully-developed forest. Overall, such variants do not seem adequate for \nregression.\n\n\\paragraph{Classification}\nIn classification, the breadth first and random baselines tend to perform \nsimilarly, one beating the other on some problems. Once again, the best first \napproach seems to be lagging behind on some datasets. At $10\\%$, the local \nbaselines cannot rival with the other methods. Only on Waveform are they able \nto reach the other performances---a setting where all methods seems to produce \nclose results. At $1\\%$, the breadth first and/or the random methods surpass \nthe ET$_{10\\%}$ on Twonorm, Hastie, Madelon and Waveform. Those datasets \ncorrespond to cases where ET was under-performing significantly compared to GIF. \nAll in all, the local baselines are never able to beat GIF, even in the \nmulticlass setting, which is particularly defavorable for GIF. Once again, the \nconclusion is against the purely local baselines.\n\n\nWe believed the poor performances of the baselines are due to the building \nmechanism of traditional ensemble methods. Although the trees are built \nindependently and with randomization, there remains an important redundancy \nbetween them, which is especially defavorable to pruning. A global approach is \nbetter able to avoid redundancy and can thus better exploit the node budget. \nThis would also explain why the best first variant performs worst in both \nregression and classification: it is prone at picking redundant nodes, which \nwill usually offer the same kind of impurity reduction.\n\n\n\n\n\n\\bibliography{gif}\n\\bibliographystyle{icml2017}\n\n\\end{document} \n\n", "meta": {"hexsha": "addd0049d6961ac616ed528d93a6642d9759ece6", "size": 22285, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/supplementary.tex", "max_stars_repo_name": "jm-begon/globally-induced-forest", "max_stars_repo_head_hexsha": "bf41640a5f0d9db637877dfa077b1d529539dbc6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2018-01-05T11:56:27.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-13T13:14:05.000Z", "max_issues_repo_path": "paper/supplementary.tex", "max_issues_repo_name": "jm-begon/globally-induced-forest", "max_issues_repo_head_hexsha": "bf41640a5f0d9db637877dfa077b1d529539dbc6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-01-05T12:04:37.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-05T13:56:20.000Z", "max_forks_repo_path": "paper/supplementary.tex", "max_forks_repo_name": "jm-begon/globally-induced-forest", "max_forks_repo_head_hexsha": "bf41640a5f0d9db637877dfa077b1d529539dbc6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2341549296, "max_line_length": 81, "alphanum_fraction": 0.675835764, "num_tokens": 7882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.3071263493835959}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% From a template maintained at https://github.com/jamesrobertlloyd/cbl-tikz-poster\n%\n% Code near the top should be fairly standard and not need to be changed\n%  - except for the document class\n% Code lower down is more likely to be customised\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\documentclass[landscape,a0b,final,a4resizeable]{include/a0poster}\n\n\\usepackage{multicol}\n\\usepackage{color}\n\\usepackage{morefloats}\n\\usepackage[pdftex]{graphicx}\n\\usepackage{rotating}\n\\usepackage{amsmath, amsthm, amssymb, bm}\n\\usepackage{array}\n\\usepackage{booktabs}\n\\usepackage{multirow}\n\\usepackage{hyperref}\n\n\n\\usepackage{include/picins}\n\\usepackage{tikz}\n\\usetikzlibrary{shapes.geometric,arrows,chains,matrix,positioning,scopes,calc}\n\\tikzstyle{mybox} = [draw=white, rectangle]\n\\definecolor{darkblue}{rgb}{0,0.08,0.45}\n\\definecolor{blue}{rgb}{0,0,1}\n\n\\usepackage{dsfont}\n\n\\input{include/jlposter.tex}\n\n\\input{include/preamble.sty}\n\\newcommand{\\vv}{\\mathbf{v}}\n\n\\begin{document}\n\\begin{poster} \n\n% Potentially add some space at the top of the poster\n\\vspace{0\\baselineskip}\n\n\n%%% Header\n\\begin{center}\n\\begin{pcolumn}{0.99}\n\n\\newcommand{\\logowidth}{0.11\\textwidth}\n\n\\pbox{0.99\\textwidth}{}{linewidth=2mm,framearc=0.3,linecolor=camdarkblue,fillstyle=gradient,gradangle=0,gradbegin=white,gradend=white,gradmidpoint=1.0,framesep=1em}{\n%\n%%% Cambridge Logo\n\\begin{minipage}[c]{\\logowidth}\n  \\begin{center}\n    \\includegraphics[width=20cm]{badges/hips-logo.png}\n  \\end{center}\n\\end{minipage}\n%\n%%% Title\n\\begin{minipage}[c][9cm][c]{0.76\\textwidth}\n  \\begin{center}\n    {\\sffamily \\VeryHuge \\textbf{Convolutional Networks on Graphs\\\\[4mm] for Learning Molecular Fingerprints}}\\\\[10mm]\n    {\\huge\\sffamily \\Huge David Duvenaud*, Dougal Maclaurin*, Jorge Aguilera-Iparraguirre \\\\ Rafael G\\'omez-Bombarelli, Timothy Hirzel, Al\\'an Aspuru-Guzik, Ryan P. Adams\\\\[7.5mm]\n    %\\texttt{\\{ti242, dkd23, zoubin\\}@cam.ac.uk}\n    }\n  \\end{center}\n\\end{minipage}\n%\n%\n% Harvard logo\n\\begin{minipage}[c]{\\logowidth}\n  \\begin{flushright}\n    \\includegraphics[width=9cm,trim=2em 0em 2em 2em, clip]{badges/harvard}\n  \\end{flushright}\n\\end{minipage}\n%\n}\n\\end{pcolumn}\n\\end{center}\n\n\\vspace*{3cm}\n\n\\Large\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Beginning of Document\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\begin{multicols}{3}\n\n\\mysection{How to do regression on graphs?}\n\n%\\vspace{-0.5in}\n\n\\begin{tabular}{cc}\n\\begin{minipage}[c]{0.45\\columnwidth}\n\\begin{itemize}\n  \\item Input can be any size or shape\n  \\item Hard to turn into fixed-length vector\n  \\item In our case, graphs represent molecules\n  \\item Applications to photovoltaics, organic LEDS, flow batteries and pharmaceuticals\n\\end{itemize}\n\\end{minipage} & \n\\begin{minipage}[c]{0.55\\columnwidth}\n%\\includegraphics[width=\\columnwidth]{../talks/talkfigs/learning_curves_3.pdf}\n\\centerline{\\includegraphics[width=1.0\\columnwidth, clip, trim=4mm 0mm 4mm 4mm]{figures/how-fingerprints.png}}\n\\end{minipage}\n\\end{tabular}\n\n%\\vspace{-0.5in}\n\n\\vspace{1.5in}\n\n\\mysection{Circular fingerprints}\n\n%Also called Morgan fingerprints, or ECFP\n\n\\vspace{0.5in}\n\n\\begin{tabular}{cc}\n\\begin{minipage}[c]{0.5\\columnwidth}\n\\begin{itemize}\n  \\item Maps variable-sized molecular graph to fixed-length binary vector\n  %\\item Does this by hashing self with neighbors iteratively\n  \\item Binary features indicate presence of substructures\n\\end{itemize}\n\n\\vspace{0.5in}\n\nCan be efficiently computed using local operations:\n\n\\begin{itemize}\n  \\item At each layer, hash the features of each atom and its neighbors/bonds\n  \\item More layers correspond to increasing radius of substructures\n  \\item Interpret each hash as integer and set that entry to one\n\\end{itemize}\n\\end{minipage} & \n\\begin{minipage}[c]{0.5\\columnwidth}\n%\\includegraphics[width=\\columnwidth]{../talks/talkfigs/learning_curves_3.pdf}\n\\centerline{\\includegraphics[width=0.9\\columnwidth, clip, trim=4mm 12mm 4mm 4mm]{figures/fig_1}}\n\\end{minipage}\n\\end{tabular}\n\n\\vspace{0.5in}\n\nWas state-of-the-art for large-scale regression and classification.\n\n\n\n\\newpage %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\mysection{Convolutional neural nets on graphs}\n\n\\vspace{0.5in}\n\n\\begin{tabular}{ccc}\n\\begin{minipage}[c]{0.45\\columnwidth}\n\nHow to make circular fingerprints differentiable?\nReplacing ops:\n\\vspace{0.5in}\n\n\\begin{center}\n\\begin{tabular}{rcl}\nHash  & $\\rightarrow$ & Neural net \\\\\nIndex & $\\rightarrow$ & Softmax \\\\\nWrite & $\\rightarrow$ & Add\n\\end{tabular}\n\\end{center}\n\n\\vspace{0.5in}\n\nGives end-to-end differentiable convolutional network.\n\n\\vspace{0.5in}\n\nCan be trained to adapt to particular tasks.\n\n\\end{minipage}\n& \\qquad &\n\\begin{minipage}[c]{0.45\\columnwidth}\n\\begin{center}\nInformation flow graph:\n\\centerline{\\includegraphics[width=\\columnwidth, clip, trim=0mm 0mm 4mm 4mm]{figures/3d-nets/net1.png}}\n\\end{center}\n\nMessage passing between neighbors, then final pooling step\n\n\\end{minipage}\n\\end{tabular}\n\n\\vspace{1.5in}\n\n\\mysection{Neural fingerprints are interpretable}\n\n\\newcommand{\\mywidtha}{8cm}\n\\newcommand{\\mywidthb}{10.3cm}\n\nWhen fed into linear layer, can see how fragments affect prediction:\n\n\\vspace{-0.5in}\n\\begin{center}\n\\begin{tabular}{>{\\centering}m{\\mywidthb} >{\\centering}m{\\mywidtha} >{\\centering}m{\\mywidtha} >{\\centering\\arraybackslash}m{\\mywidtha}}\nFragments predictive of solubility & \n%\\molfeature{15}{0}{3.3cm} & \\molfeature{15}{3}{3.3cm} & \\molfeature{15}{2}{2.5cm}\\\\\n\\includegraphics[width=\\mywidtha, clip, trim = 2mm 3mm 2mm 6mm]{figures/fig_5.pdf} &\n\\includegraphics[width=\\mywidtha, clip, trim = 2mm 3mm 2mm 6mm]{figures/fig_6.pdf} &\n\\includegraphics[width=6cm, clip, trim = 2mm 3mm 2mm 6mm]{figures/fig_7.pdf} \\\\\n\\midrule\nFragments predictive of insolubility & \n%\\molfeature{18}{4}{3.3cm} & \\molfeature{18}{1}{3.3cm} & \\molfeature{18}{2}{3.3cm}\n\\includegraphics[width=\\mywidtha, clip, trim = 2mm 3mm 2mm 6mm]{figures/fig_8.pdf} &\n\\includegraphics[width=\\mywidtha, clip, trim = 2mm 3mm 2mm 6mm]{figures/fig_9.pdf} &\n\\includegraphics[width=\\mywidtha, clip, trim = 2mm 3mm 2mm 6mm]{figures/fig_10.pdf} \\\\\n%\\end{tabular}\n%\\end{center}\n\\midrule\n%\\subsection{Toxicity features}\n%We trained the same model architecture to predict toxicity in two different datasets.\n%Shows fragments which maximally activate the feature most predictive of toxicity, in two separate datasets.\n%\\newcommand{\\molfeaturetox}[2]{\\includegraphics[width=3.4cm, clip, trim = 1mm 3mm 1mm 3mm]{fig_11.pdf}}%\n%\\begin{figure}[h]\n%\\begin{center}\n%\\begin{tabular}{>{\\centering}m{\\mywidthb} >{\\centering}m{\\mywidtha} >{\\centering}m{\\mywidtha} >{\\centering\\arraybackslash}m{\\mywidtha}}\n%\\vspace{0.5}\n\\vspace{0.5in}Fragments predictive of toxicity on SR-MMP dataset\\vspace{0.5in}\n& \\includegraphics[width=7cm]{figures/jorge-figures/7.png} \n& \\includegraphics[width=\\mywidtha]{figures/jorge-figures/8.png}\n& \\includegraphics[width=\\mywidtha]{figures/jorge-figures/9.png}\\\\\n\\midrule\n\\vspace{0.5in}\nFragments predictive of toxicity on NR-AHR dataset\n\\vspace{0.5in}\n%& \\molfeaturetox{7}{14} & \\molfeaturetox{7}{6} & \\molfeaturetox{7}{5}\n& \\includegraphics[width=6.5cm]{figures/jorge-figures/10.png} \n& \\includegraphics[width=\\mywidtha]{figures/jorge-figures/11.png}\n& \\includegraphics[width=7cm]{figures/jorge-figures/12.png}\\\\\n\\end{tabular}\n%\\caption{\n\\end{center}\n\n%Visualizing fingerprints optimized for predicting toxicity.\n%Shown here are representative samples of molecular fragments (highlighted in red) which most activate the feature most predictive of toxicity.\n\n%\\emph{Top row:} the most predictive feature identifies groups containing a sulphur atom attached to an aromatic ring.\n%\\emph{Bottom row:} the most predictive feature identifies fused aromatic rings, also known as polycyclic aromatic hydrocarbons, a well-known carcinogen.\n\n\n\n\n\\newpage %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\mysection{Neural graph fingerprints\\\\generalize circular fingerprints}\n\nLarge random weights give similar behavior to circular fingeprints:\n\\vspace{0.5em}\n\n\\begin{tabular}{cc}\n\\begin{minipage}[c]{0.48\\columnwidth}\n\\includegraphics[width=\\columnwidth]{figures/fig_2.pdf}\n\\end{minipage} & \n\\begin{minipage}[c]{0.48\\columnwidth}\n\\begin{center}\n\\vspace{0.5cm}\\includegraphics[width=\\columnwidth]{figures/fig_3.pdf}\n\\end{center}\n\\end{minipage}\n\\end{tabular}\n\n\\vspace{0.5em}\n\nSmall random weights already much better than circular fingerprints!\n\nCan do even better by optimizing for given task.\n\n\\vspace{1in}\n\n\\mysection{Predictive accuracy}\n\nNeural graph fingerprints fed to neural net generalizes state of the art:%, we can't not win:\n\n\\vspace{0.5em}\n\n\\begin{center}\n\\begin{tabular}{r|lll}\nDataset                      &   Solubility  & Drug efficacy & Photovoltaic \\\\\n & & & efficiency \\\\\n\\midrule\nUnits                        &   log Mol/L                            & EC$_{50}$ in nM                        & percent \\\\\n\\midrule\nPredict mean                 & 2.07 $\\pm$ 0.10        & 1.21 $\\pm$ 0.03         & 2.53 $\\pm$ 0.02 \\\\\nCircular FPs + linear layer  & 1.31 $\\pm$ 0.05        & \\bf{1.06} $\\pm$ 0.01    & 1.62 $\\pm$ 0.03 \\\\\nCircular FPs + neural net    & 1.18 $\\pm$ 0.05        & 1.16 $\\pm$ 0.04         & 1.41 $\\pm$ 0.03 \\\\ \nNeural FPs + linear layer    & 0.87 $\\pm$ 0.06        & \\bf{1.07} $\\pm$ 0.01    & 1.61 $\\pm$ 0.06 \\\\  \nNeural FPs + neural net      & \\bf{0.72} $\\pm$ 0.05   & \\bf{1.08} $\\pm$ 0.01    & \\bf{1.20} $\\pm$ 0.04\n\\end{tabular}\n\n\\vspace{0.5em}\n\n\n%RMSE Mean predictive accuracy of neural fingerprints compared to standard circular fingerprints.\n\\end{center}\n\n\\vspace{0.5em}\n\n\\mysection{Conclusion}\n\n\\begin{itemize}\n\\item Can learn graph features end-to-end!\n\\item Works on other types of graphs too \n\\item Code at \\url{github.com/HIPS/neural-fingerprint}\n\\item Autodiff package that works on standard Numpy code:\\\\ \\url{github.com/HIPS/autograd}\n\\end{itemize}\n\n\n\n\\end{multicols}\n\\end{poster}\n\n\\end{document}\n\n", "meta": {"hexsha": "99a1bfc77fe7f2bc4b09cf4f39128ea46b309e63", "size": 10025, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "poster/neural-fingerprints-poster.tex", "max_stars_repo_name": "wilderlopes/neural-fingerprint", "max_stars_repo_head_hexsha": "29bd4973dc8b8ef0b4aeb0263b5116e215c5d9d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 454, "max_stars_repo_stars_event_min_datetime": "2015-09-30T18:17:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T11:39:54.000Z", "max_issues_repo_path": "poster/neural-fingerprints-poster.tex", "max_issues_repo_name": "wilderlopes/neural-fingerprint", "max_issues_repo_head_hexsha": "29bd4973dc8b8ef0b4aeb0263b5116e215c5d9d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2015-11-12T10:25:50.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-18T15:21:12.000Z", "max_forks_repo_path": "poster/neural-fingerprints-poster.tex", "max_forks_repo_name": "wilderlopes/neural-fingerprint", "max_forks_repo_head_hexsha": "29bd4973dc8b8ef0b4aeb0263b5116e215c5d9d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 168, "max_forks_repo_forks_event_min_datetime": "2015-10-15T03:22:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T20:09:36.000Z", "avg_line_length": 30.5640243902, "max_line_length": 179, "alphanum_fraction": 0.6963591022, "num_tokens": 3174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.3071263493835959}}
{"text": "\\subsection{Preliminary experiments: encoding hierarchical rules}\nBefore diving into the FET task, KENN has been tested in a hierarchical classification scenario. Since the goal of this preliminary phase is to familiarize with KENN rather than achieve the best performance, we do not dwell on the architecture, training setup, and results. We focus, instead, on how hierarchical relations can be encoded with KENN. Different heuristics to represent a hierarchy through logical rules are proposed within these preliminary studies.\n\n\\subsubsection{Dataset}\n% The baseline model implemented for these experiments has a simple architecture. It uses DistilBERT as encoder, followed by a dense fully connected layer and a final classification layer that applies the sigmoid activation function. The choice of this activation function is due to the fact that in a multilabel task we want as output the probability of each label. Starting from this architecture, KENN is placed between the fully connected layer and the classification layer. Clause weights are set as learnable parameters with an initial value of 0.5.\n\nThe dataset used for this experiment is called DBpedia Classes\\footnote{https://www.kaggle.com/danofer/dbpedia-classes}. It is composed of approximately 240k labeled Wikipedia articles, where the only feature is the span of text. The types are organized as a forest of 9 trees, each of them representing a 3-level hierarchy. The type set counts 298 types: 9 at top-level, 70 at middle-level, and 219 at low-level. Each example is labeled with exactly 3 classes from the full path of a tree (i.e., one class per level). For example, if we consider the \\textit{Species} tree shown in Figure~\\ref{fig:dbpedia_classes}, an instance of the dataset could present $ label_{1} = Species $, $ label{_2} = Animal $, and $ label_{3} = Bird $.\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=.7\\linewidth]{dbpedia_classes.png}\n    \\caption{Example of a tree of DBpedia Classes}\n    \\label{fig:dbpedia_classes}\n\\end{figure}\n\n\\subsubsection{Knowledge definition} \\label{knowledge_generation}\nThe first step to integrate KENN is to create the logical KB. We can start from the tree in Figure~\\ref{fig:dbpedia_classes} and then generalize different strategies for defining logical rules. The most intuitive and straightforward way consists in following the \\textit{is-a} relations, which are implicitly encoded in the tree structure. Considering the picture, it is possible to state that if an instance is a \\texttt{Fish}, then it is an \\texttt{Animal}. In the same way, we can then proceed with the next level of the hierarchy and state that if an instance is an \\texttt{Animal}, then it is a \\texttt{Species}. This mechanism can be extended to all the other subtrees to create a logical clause per edge. The resulting KB will be a set of logical implications between subtypes and supertypes. Even if it seems a natural way to describe the hierarchy, it doesn't necessarily mean it is the most effective solution. For this reason, we should take a step back and analyze the alternatives offered by the hierarchy. Figure~\\ref{fig:hierarchy_example} shows a generic hierarchy and highlights two groups of constraints we can distinguish:\n\\begin{enumerate}\n    \\item \\textbf{Vertical constraints:} based on the paths of a tree, they can be used to represent specialization relations\n    \\item \\textbf{Horizontal constraints:} based on pairs of nodes from different branches, they can be used to represent disjointness relations\n\\end{enumerate}\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=.7\\linewidth]{hierarchy_example.png}\n    \\caption{Examples of a generic hierarchy. In green the vertical constraints, in red the horizontal constraints.}\n    \\label{fig:hierarchy_example}\n\\end{figure}\nFor each group of constraints, it is possible to implement different strategies to define the KB. In the rest of the thesis, these strategies will be referred to as \\textit{KB modes}. Note that in the definitions below we will use unary predicates to represent the belonging of an instance $X$ to a type.\n\n\\paragraphn{Vertical Constraints}\nUsing the unary predicates $Subtype$ and $Supertype$ such that the type $Subtype$ is a specialization of the type $Supertype$, we can define three main strategies to build vertical constraints:\n\\begin{itemize}\n    \\item \\textbf{Bottom Up:}\n        \\begin{itemize}\n            \\item FOL: $ \\forall X, Subtype(X) \\to Supertype(X) $\n            \\item KENN: $ \\neg Subtype \\vee Supertype $\n            \\item Defined by following every path of the tree from the leaves to the root. It represents the logic dependency between types, following the most widely used semantics in the definition of subclass.\n            \\item Open World Assumption: a clause is satisfied even when an instance is assigned only to supertypes\n        \\end{itemize}\n    \\item \\textbf{Top Down:}\n        \\begin{itemize}\n            \\item FOL: $ \\forall X, Supertype(X) \\to (Subtype_{1}(X) \\vee ... \\vee Subtype_{n}(X)) $\n            \\item KENN: $ \\neg Supertype \\vee Subtype_{1} \\vee ... \\vee Subtype_{n}  $\n            \\item Defined by following every path of the tree from the root to the leaves\n            \\item Closed World Assumption: a clause is not satisfied when an instance is assigned to a supertype without any of its subtypes\n        \\end{itemize}  \n    \\item \\textbf{Hybrid:} \n    \\begin{itemize}\n        \\item Composed of a mix of \\textit{Bottom Up} and \\textit{Top Down} clauses\n    \\end{itemize}\n\\end{itemize}\nNote that if a model that uses this kind of knowledge is confident about a given type, a \\textit{Bottom Up} clause propagates this certainty towards the root of the hierarchy. Conversely, a \\textit{Top Down} clause only guarantees that one of the subtypes is appropriate, but provides no information as to which one. The reason, of course, is the tree-like hierarchy, where each type has only one parent, but potentially many descendants.\n\nThe presented KB modes can be considered as the starting point to create new strategies by adding some variations. In Table~\\ref{tab:kb_modes} we can find a summary that comprehends every KB mode, each of them accompanied by examples of clauses from the hierarchy in Figure~\\ref{fig:dbpedia_classes}. Before proceeding with the explanation of the variants, we have to make clear why they have been introduced: the conflicts. If we look at the table, we can see that in the examples of the pure \\textit{Bottom Up} and \\textit{Top Down} modes there are conflicts: a middle-level label appears both as positive and negative literal. This fact derives from the translation of the logical implication into a disjunction since an intermediate node is at the same time antecedent and consequent of different logical implications. This behavior still hold for the \\textit{Hybrid} mode.\n\nNow that the possible problems of the starting strategies are known, it is possible to introduce their conflict-free variants. These variants avoid conflict situations in different ways. The ``Skip\" ones rely on the transitivity of a relation by linking top-level and low-level nodes by skipping those middle-level nodes that would create a conflict (i.e., a middle-level node cannot be the antecedent of an implication rule). These solutions provide a more shallow representation of the knowledge, especially for the \\textit{Top Down Skip}. In this case, a logical rule that represents the relation between top-level and low-level lose effectiveness because the implication may have too many consequents. The \\textit{Hybrid In} and \\textit{Hybrid Out} modes, instead, avoid conflicts by fixing the middle-level types as consequent or antecedent of an implication rule, respectively. In this way, the deltas produced by each CE for the same literal will always have the same sign.\n\nNote that the proposed variants are valid for this dataset, but some of them do not apply to every context since they require a hierarchy with at least 3 levels.\n\n\\begin{table}\n\\centering\n\\caption{Strategies for defining logical clauses based on the hierarchy in Figure~\\ref{fig:dbpedia_classes}}\n\\label{tab:kb_modes}\n\\begin{tabular}{c|l|}\n\\cline{2-2}\n                                              & \\multicolumn{1}{c|}{\\textbf{Clauses}}                                                                                                                                                                                             \\\\ \\hline\n\\multicolumn{1}{|c|}{\\textbf{Bottom Up}}      & \\begin{tabular}[c]{@{}l@{}}$ c_{1}: \\neg Fish \\vee Animal $\\\\ $ c_{2}: \\neg Bird \\vee Animal $\\\\ $ c_{3}: \\neg Animal \\vee Species $\\\\ ...\\end{tabular}                                                                           \\\\ \\hline\n\\multicolumn{1}{|c|}{\\textbf{Top Down}}       & \\begin{tabular}[c]{@{}l@{}}$ c_{1}: \\neg Species \\vee Animal \\vee ... \\vee Plant $\\\\ $ c_{2}: \\neg Animal \\vee Fish \\vee ... \\vee Bird $\\\\ $ c_{3}: \\neg Plant \\vee Fem \\vee ... \\vee Cycad $\\\\ ...\\end{tabular}                  \\\\ \\hline\n\\multicolumn{1}{|c|}{\\textbf{Hybrid}}         & \\begin{tabular}[c]{@{}l@{}}$ c_{1}: \\neg Species \\vee Animal \\vee ... \\vee Plant $\\\\ $ c_{2}: \\neg Animal \\vee Species $\\\\ $ c_{3}: \\neg Plant \\vee Species $\\\\ ...\\end{tabular}                                                  \\\\ \\hline\n\\multicolumn{1}{|c|}{\\textbf{Bottom Up Skip}} & \\begin{tabular}[c]{@{}l@{}}$ c_{1}: \\neg Fish \\vee Animal $\\\\ $ c_{2}: \\neg Fish \\vee Species $\\\\ $ c_{3}: \\neg Bird \\vee Animal $\\\\ $ c_{4}: \\neg Bird \\vee Species $\\\\ ...\\end{tabular}                                         \\\\ \\hline\n\\multicolumn{1}{|c|}{\\textbf{Top Down Skip}}  & \\begin{tabular}[c]{@{}l@{}}$ c_{1}: \\neg Species \\vee Animal \\vee ... \\vee Plant $\\\\ $ c_{2}: \\neg Species \\vee Fish \\vee ... \\vee Bird \\vee Fem \\vee Cycad $\\\\ ...\\end{tabular}                                                  \\\\ \\hline\n\\multicolumn{1}{|c|}{\\textbf{Hybrid In}}      & \\begin{tabular}[c]{@{}l@{}}$ c_{1}: \\neg Species \\vee Animal \\vee ... \\vee Plant $\\\\ $ c_{2}: \\neg Fish \\vee Animal $\\\\ $ c_{3}: \\neg Bird \\vee Animal $\\\\ $ c_{4}: \\neg Fem \\vee Plant $\\\\ ...\\end{tabular}                      \\\\ \\hline\n\\multicolumn{1}{|c|}{\\textbf{Hybrid Out}}     & \\begin{tabular}[c]{@{}l@{}}$ c_{1}: \\neg Animal \\vee Species $\\\\ $ c_{2}: \\neg Animal \\vee Fish \\vee ... \\vee Bird $\\\\ $ c_{3}: \\neg Plant \\vee Species $\\\\ $ c_{4}: \\neg Plant \\vee Fem \\vee ... \\vee Cycad $\\\\ ...\\end{tabular} \\\\ \\hline\n\\end{tabular}\n\\end{table}\n\n\\paragraphn{Horizontal Constraints}\nThese constraints aim to avoid the co-occurrence of types whose instances form disjoint sets (e.g., if an example is labeled as \\texttt{Person} it cannot be labeled as \\texttt{Location} and vice versa). Using $T_i$ to indicate an arbitrary type, the logical rule that best represents this constraint is:\n\\begin{gather*}\n    \\forall X, T_{1}(X) \\to (\\neg T_{2}(X) \\wedge ... \\wedge \\neg T_{n}(X))\n\\end{gather*}\nWith the following steps, we can derive an equivalent formula without implication and conjunctions:\n\\begin{align*}\n    & T_{1} \\to (\\neg T_{2} \\wedge ... \\wedge \\neg T_{n}) = \\\\\n    & = \\neg T_{1} \\vee (\\neg T_{2} \\wedge ... \\wedge \\neg T_{n}) = \\\\\n    & = \\neg T_{1} \\vee \\neg (T_{2} \\vee ... \\vee T_{n})\n\\end{align*}\nUnfortunately, the derived formula cannot be furthermore decomposed due to the presence of parentheses. We can opt for two alternative solutions to bypass the problem:\n\\begin{enumerate}\n    \\item \\textbf{Approximate the rule with a softer constraint:} if an instance does not belong to \\texttt{T$_1$}, then it should belong to another type. \\\\\n    The logical formula for this statement is:\n    \\begin{gather*}\n            \\forall X, \\neg T_{1}(X) \\to (T_{2}(X) \\vee ... \\vee T_{n}(X))\n    \\end{gather*}\n    that can be translated into KENN's language with the following steps:\n    \\begin{align*}\n        & \\neg T_{1} \\to (T_{2} \\vee ... \\vee T_{n}) = \\\\\n        & = T_{1} \\vee (T_{2} \\vee ... \\vee T_{n}) = \\\\\n        & = T_{1} \\vee T_{2} \\vee ... \\vee T_{n}\n    \\end{align*}\n    From a logical point of view, the resulting formula does not seem very helpful because it simply states that an instance belongs at least to one class. Indeed, if we repeat the previous steps using any other type as the antecedent of the implication, the derived clause will be identical. Furthermore, the action of KENN on such clauses would not lead to mutual exclusivity because every literal is positive and none of the involved predictions will receive a negative boost.\n    \n    \\item \\textbf{Split the rule into multiple clauses:} define a clause for each pair of disjoint types.\n    Given two disjoint types, the logical formula to express the mutual exclusivity is:\n    \\begin{gather*}\n        \\forall X, T_{1}(X) \\to \\neg T_{2}(X)\n    \\end{gather*}\n    If we consider $n$ disjoint pairs in which appears $T_{1}$, the resulting KB in KENN's language will be the following:\n    \\begin{align*}\n        & c_{1}: \\neg T_{1} \\vee \\neg T_{2}\\\\\n        & ...\\\\\n        & c_{n}: \\neg T_{1} \\vee \\neg T_{n}\n    \\end{align*}\n    Unlike strategy 1, this one preserves the soundness of the starting formula. However, there are still some issues to take into account. The first concerns the number of clauses necessary to cover the possible combinations of pairs: having $ n $ mutual independent types will result in $ \\frac{n!}{2!(n-2)!} $ logical clauses. The second issue regards the action of KENN: while in strategy 1 there were only positive literals, in this strategy there are only negative literals, thus meaning that none of the predictions will ever receive a positive boost.\n\\end{enumerate}\n\n\\paragraphn{Horizontal constraints - Alternative usage}\nAnother use of horizontal constraints that is not related to this dataset, but could be useful in other contexts, is to encourage the co-occurrence between different types. Here the purpose is exactly the opposite with respect to the previous rules. Even if this goal can be reached by applying a simple inference on the final predictions without the use of KENN, in some tasks (e.g., domain adaptation) it may be useful to leave the decision to the network. If we want the model to learn a mapping between two types \\texttt{A} and \\texttt{B}, we can define the logical rule\n\\begin{gather*}\n    (A \\to B) \\wedge (B \\to A)\n\\end{gather*}\nthat can be expressed in KENN using the following clauses:\n\\begin{align*}\n    & c1: \\neg A \\vee B \\\\\n    & c2: \\neg B \\vee A\n\\end{align*}\nThe first thing we can notice is the presence of conflicts, but they will not have a negative impact on the final predictions. The preactivation of the literals belonging to the two clauses are the same with opposite signs, so a  literal cannot be dominant in both clauses. In other words, the final predictions always benefit from the knowledge enhancement since the effect of KENN will be one of the following:\n\\begin{itemize}\n    \\item \\textbf{positive preactivations:} a positive aggregated delta is produced for each literal\n    \\item \\textbf{negative preactivations:} a negative aggregated delta is produced for each literal\n    \\item \\textbf{discord preactivations:} an aggregated delta with the sign of the highest\\footnote{in absolute value} preactivation is produced for each literal\n\\end{itemize}\n\n\n\\subsubsection{Results}\nAs anticipated, the results are not the focus of this study since we are not dealing with the target problem of this thesis. To see KENN in action, the KB modes of Bottom Up, Top Down, Hybrid In, and Hybrid Out have been evaluated. \nThe baseline model implemented for these experiments has a simple architecture. It uses DistilBERT as encoder, followed by a dense fully connected layer and a final classification layer that applies the sigmoid activation function. The choice of this activation function is due to the fact that in a multilabel task we want as output the probability of each label. Starting from this architecture, KENN is placed between the fully connected layer and the classification layer. Clause weights are set as learnable parameters with an initial value of 0.5.\n\nIn Table \\ref{tab:performance_dbpedia} are reported the results obtained by the baseline and KENN-based models. Hybrid Out is the configuration that brought more benefits to the baseline model with a $+0.0157$ on the F1 score, thanks to its highest recall. Even Top Down brought improvements with an increase of $+0.0097$. This did not happen with the other configurations.\n\nAn interesting fact that emerged regards the clause weights. By inspecting the final weights learned by the models, it was found out that the models that performed the best are the ones that finished the train with higher clause weights. In particular, some clauses have increased their starting weight by 10 times. On the contrary, the worst models are the ones whose final weights are smaller. This fact means that KENN helped the baseline model the most when it gained more influence on the final predictions. From these results, we can say that the higher the weight, the better the performance. This result may lead to think that it could be reasonable to set higher initial clause weights to anticipate the learning process. However, we have to take this conclusion with a grain of salt because it could be strictly related to this dataset.\n\n\\begin{table}[H]\n\\centering\n\\caption{Comparison between the baseline and KENN-based models on DBpedia Classes in terms of \\textit{macro f1 classes}}\n\\label{tab:performance_dbpedia}\n\\begin{tabular}{|c|ccc|}\n\\hline\n\\textbf{KB mode} & \\multicolumn{1}{c|}{\\textbf{P}} & \\multicolumn{1}{c|}{\\textbf{R}} & \\textbf{F1}     \\\\ \\hline\n- (baseline)       & 0.9265                          & 0.8644                          & 0.8897          \\\\ \\hline\nBottom Up      & 0.924                           & 0.8685                          & 0.8901          \\\\ \\hline\nTop Down       & \\textbf{0.93}                   & 0.8788                          & 0.8994          \\\\ \\hline\nHybrid In      & 0.9186                          & 0.87                            & 0.8884          \\\\ \\hline\nHybrid Out     & 0.927                           & \\textbf{0.8913}                 & \\textbf{0.9054} \\\\ \\hline\n\\end{tabular}\n\\end{table}", "meta": {"hexsha": "ca777f5581703d2b86e24570c8b9f5fff4f61529", "size": 18231, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "project/kenn/kenn_preliminary_experiments.tex", "max_stars_repo_name": "christianbernasconi96/MasterThesis", "max_stars_repo_head_hexsha": "6211ff86af247aace530912c4eca9019365d606e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "project/kenn/kenn_preliminary_experiments.tex", "max_issues_repo_name": "christianbernasconi96/MasterThesis", "max_issues_repo_head_hexsha": "6211ff86af247aace530912c4eca9019365d606e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project/kenn/kenn_preliminary_experiments.tex", "max_forks_repo_name": "christianbernasconi96/MasterThesis", "max_forks_repo_head_hexsha": "6211ff86af247aace530912c4eca9019365d606e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 116.8653846154, "max_line_length": 1141, "alphanum_fraction": 0.705666173, "num_tokens": 4585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.30712634938359584}}
{"text": "\\section{\\texorpdfstring{Random number generators}{Random number generators}}\n\\vspace{5mm}\n\\large\n\n\\begin{definition}\n\tSecure RNG - even knowing complete past output, next bit is unpredictable $\\Rightarrow$ statistically uniform.\n\\end{definition}\n\nWe have 2 type of random number generators:\\\\\na) PRNG: e.g. block cipher in CTR mode. Key should be changed on regular basis.\\\\\nb) physical randomness (we have no proof such thing exists).\nExamples:\n\n\\begin{itemize}\n\t\\item Thermal noise or resister/diode\n\t\\item Radioactive decay (count \\# of particles)\n\t\\item Radio noise\n\t\\item Lava lamp (chaotic movement)\n\t\\item Ring oscillator (attacker can observer)\n\t\\item Precise timings of keystrokes, mouse movements or network packages (attacker can record or flood packages)\n\\end{itemize}\n\n\\begin{note}\n\tEntropy in physical processes is not as high as we can expect.\n\tTherefore, a combination of PRNG and physical randomness is the best choice.\n\\end{note}\n\nProblem with PRGN + rekey: if a key or state of the PRNG is compromised, adding 1 bit or physical entropy does not help. Attacher can try both options (guess) and track the state. Therefore entropy should be mixed in large batches.\n\n\\subsection{Fortuna RNG}\n\\begin{definition}\n\tFortuna RGN has a \\emph{Generator} and \\emph{Accumulator}.\n\n\tGenerator is based on block cipher (AES) which encrypts a 128-bit counter (never overflows). After $2^{16}$ block we rekey and using the next 2 blocks as key.\n\n\tTrick: do not reset the counter to avoid short cycles.\n\n\tAccumulator: gets entropy from other sources and resets Generator periodically.\n\tHas $p_0, ..., p_{31}$ pods of entropy. External RNG is mixed to the pods in Round-Robin order: assign RNG to $p_i$, move to the next.\n\tSuch process distributes RNG among the pods.\n\n\tAfter 100ms we mix pods into Generator. In the $j$-th mixing only selected pods are used, e.g. with index $2^j/i$.\n\\end{definition}\n\nAssume that $\\rho = $ rate of input entropy, measured in bits per 100ms.\nIf $\\rho \\geq 128 * 32 \\Rightarrow p_0$ is enough for recovery. As at least 128 bit of entropy were put in $p_0$.\nIf $ \\rho \\geq 128 * 32/2^i \\Rightarrow p_i$ is enough to recover.\n\nTo conclude, for any given rate of entropy Fortuna can recover after some time. Speed of recovery depends on entropy rate.\n\n\\subsection{Secure channel}\nWe use symmetric encryption to establish secure channel. Assume Alice and Bob share unique random key $k$.\nAlice sends $\\{ m_i \\}_0^n$ sequence of messages, Bob receives a subsequence and he is still able to know which one he got.\nOn the other hand, attacker have no such info, except for length of the sequence.\n\nWe use\n\\begin{itemize}\n\t\\item Random IV for every message (public).\n\t\\item AES in CTR mode for encryption (alternatively ChaCha20).\n\t\\item MAC after encrypt.\n\t\\item Sequence numbers (inside MAC).\n\t\\item Key derivation function which generates encryption and MAC keys for both directions.\n\t\t\\[ h(k | id) \\]\n\\end{itemize}\n", "meta": {"hexsha": "c8f55034bd9cd6e53eafc670561258df2265d2cc", "size": 2945, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/prednasky/08_prednaska.tex", "max_stars_repo_name": "karlov/NDMI100", "max_stars_repo_head_hexsha": "8a2c78790212b79c55083663ef0aaf27ef54d596", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/prednasky/08_prednaska.tex", "max_issues_repo_name": "karlov/NDMI100", "max_issues_repo_head_hexsha": "8a2c78790212b79c55083663ef0aaf27ef54d596", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/prednasky/08_prednaska.tex", "max_forks_repo_name": "karlov/NDMI100", "max_forks_repo_head_hexsha": "8a2c78790212b79c55083663ef0aaf27ef54d596", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.3076923077, "max_line_length": 231, "alphanum_fraction": 0.7589134126, "num_tokens": 760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.30712634206458117}}
{"text": "\\section{Preliminary Results}\\label{section:results}\n\nAs a criteria of the project is to compare the performance of different frameworks against the performance of ROOT based \\texttt{HistFactory} benchmarking of the different backends was carried out.\nAs a preliminary benchmark of the frameworks a one point $\\text{CL}_{s}$ test\\footnote{$\\text{CL}_{s}$ is defined as the ratio of the signal + background hypothesis $p$-value to $1$ minus the background only hypothesis $p$-value: $\\text{CL}_{s} = p_{s+b}/\\left(1-p_{b}\\right)$.~\\cite{Cowan:2010js}} was performed, in which the $p$-values of test statistics from the data and the ``Asimov'' data set are compared given the parameter of interest.~\\cite{Cowan:2010js}\nThe model used is a simple one in which every bin has the same content to ensure that the fit will complete.\nIn lieu of model complexity large numbers of bins are given to simulate difficult conditions for the fit as each bin is uncorrelated and so represents an additional nuisance parameter.\nThe results are shown against each other in Figure~\\ref{fig:benchmark_backends}.\nAs a pure MXNet optimizer has not been fully implemented in pyhf at this time it has not yet been benchmarked, and so only backends that do have language specific optimizers have been compared to ROOT based \\texttt{HistFactory}.\\\\\n\nThe preliminary results show that the computational backends that support automatic differentiation and built in parallelism show promising scaling behavior as the nature of the statistical fits becomes more computational difficult, as seen in Figure~\\ref{fig:relative_time}.\nThe optimizer for the NumPy pyhf backend is based on optimizers in SciPy, and while the NumPy backend optimizer does not currently have automatic differentiation support it does show very good timing for lower computational difficulty problems.\nGiven that pyhf allows for fluidity in the choice of backend, this demonstrates a possible use case for automatically switching from the low overhead NumPy backend to a graph based backend as computational difficulty rises.\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=0.9\\linewidth]{benchmark_times.pdf}\n \\caption{Comparison of the mean time needed to complete a one point $\\text{CL}_{s}$ test for ROOT \\texttt{HistFactory} and the NumPy, TensorFlow, and PyTorch pyhf backends vs. the number of bins in the associated fit.\n  The binning choices (number of nuisance parameters) used are $n_{\\text{bins}} \\in \\left\\{1, 10, 50, 100, 200, 500, 800, 1000\\right\\}$.\n  For each binning choice the fit is repeated 5 times.\n  For ROOT \\texttt{HistFactory} only binning choices up to 200 are used as runtime became too long afterwards.\n  The minimum and maximum run times time for each binning choice are shown as open shapes corresponding to the shapes of the markers for each backend, and an uncertainty bar corresponding to 1 standard deviation is drawn (though it may be obscured by the markers).\n }\\label{fig:benchmark_backends}\n\\end{figure}\n\n\\begin{figure}[htbp]\n \\centering\n \\subfigure[ROOT \\texttt{HistFactory}]{%\n  \\includegraphics[width=0.5\\textwidth]{relative_times_root_log.eps}\\label{fig:relative_time_root_HF}%\n }\\hfil\n \\subfigure[NumPy backend]{%\n  \\includegraphics[width=0.5\\textwidth]{relative_times_numpy_log.eps}\\label{fig:relative_time_numpy}%\n }\n \\subfigure[TensorFlow backend]{%\n  \\includegraphics[width=0.5\\textwidth]{relative_times_tensorflow_log.eps}\\label{fig:relative_time_tensorflow}%\n }\\hfil\n \\subfigure[PyTorch backend]{%\n  \\includegraphics[width=0.5\\textwidth]{relative_times_pytorch_log.eps}\\label{fig:relative_time_pytorch}%\n }\n \\caption{Comparison of the mean time needed to complete a one point $\\text{CL}_{s}$ test for ROOT \\texttt{HistFactory} and the pyhf backends for a number of bins in the associated fit relative to the time for a single bin.\n  The binning choices (number of nuisance parameters) used are $n_{\\text{bins}} \\in \\left\\{1, 10, 50, 100, 200, 500, 800, 1000\\right\\}$.\n  For ROOT \\texttt{HistFactory} only binning choices up to 200 are used as runtime became too long afterwards.\n }\\label{fig:relative_time}\n\\end{figure}\n", "meta": {"hexsha": "4c5ef4a0d9b08cef1510913c6db8466ae7ea5778", "size": 4117, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "summary_report/src/results.tex", "max_stars_repo_name": "matthewfeickert/DIANA-Proposal-Feickert", "max_stars_repo_head_hexsha": "dac5181e7e87e747fbdb3c5a6d0201f723fa4670", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "summary_report/src/results.tex", "max_issues_repo_name": "matthewfeickert/DIANA-Proposal-Feickert", "max_issues_repo_head_hexsha": "dac5181e7e87e747fbdb3c5a6d0201f723fa4670", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-04-10T20:42:05.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-11T14:33:40.000Z", "max_forks_repo_path": "summary_report/src/results.tex", "max_forks_repo_name": "matthewfeickert/DIANA-Proposal-Feickert", "max_forks_repo_head_hexsha": "dac5181e7e87e747fbdb3c5a6d0201f723fa4670", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 93.5681818182, "max_line_length": 464, "alphanum_fraction": 0.7886810785, "num_tokens": 1023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.30697442216530413}}
{"text": "% From Robert_Harper@terrier.fox.cs.cmu.edu  Wed Jun 19 00:07:29 1996\n%Return-Path: Robert_Harper@terrier.fox.cs.cmu.edu\n%To: tofte@diku.dk\n%Subject: revised appendix 5 (tex source, no references)\n%Date: Tue, 18 Jun 1996 18:07:12 -0400\n%From: Robert Harper <Robert_Harper@terrier.fox.cs.cmu.edu>\n%\n\\section{Appendix: The Development of ML}\n\\label{story-app}\n\nThis Appendix records the main stages in the development of ML, and the people\nprincipally involved.  The main emphasis is upon the design of the language;\nthere is also a section devoted to implementation. On the other hand, no\nattempt is made to record work on applications of the language.\n\\note{\\thenewpreface}{This appendix has been revised and extended in \nseveral ways. A detailed list of changes is not available.} \n\\subsection*{Origins}\n\nML and its semantic description have evolved over a period of about\ntwenty years.  It is a fusion of many ideas from many people;  in this\nappendix we try to record and to acknowledge the important precursors\nof its ideas, the important influences upon it, and the important\ncontributions to its design, implementation and semantic description.\n\nML, which stands for {\\em meta language}, was conceived as a medium for\nfinding and performing proofs in a formal logical system.  This application\nwas the focus of the initial design effort, by Robin Milner in collaboration\nfirst with Malcolm Newey and Lockwood Morris, then with Michael Gordon and\nChristopher Wadsworth~\\cite{GMMNW}. The intended application to proof affected\nthe design considerably.  Higher order functions in full generality seemed\nnecessary for programming proof tactics and strategies, and also a robust type\nsystem (see below).  At the same time, imperative features were important for\npractical reasons; no-one had experience of large useful programs written in a\npure functional style. In particular, an exception-raising mechanism was\nhighly desirable for the natural presentation of tactics.\n\nThe full definition of this first version of ML was included in a\nbook~\\cite{GMW} which describes LCF, the proof system which ML was designed to\nsupport.  The details of how the proof application exerted an influence on\ndesign is reported by Milner~\\cite{Mil2}.  Other early influences were the\napplicative languages already in use in Artificial Intelligence, principally\nLISP~\\cite{McC}, ISWIM~\\cite{Lan} and POP2~\\cite{BP}.\n\n\\subsection*{Polymorphic types}\n\nThe polymorphic type discipline and the associated type-assignment algorithm\nwere\\linebreak\n prompted by the need for security;  it is vital to know that when\na program produces an object which it claims to be a theorem, then it\nis indeed a theorem.  A type discipline provides the security, but a\npolymorphic discipline also permits considerable flexibility.\n\nThe key ideas of the type discipline were evolved in combinatory logic by\nHaskell Curry and Roger Hindley, who arrived at different but equivalent\nalgorithms for computing principal type schemes.  Curry's~\\cite{Cur} algorithm\nwas by equation-solving; Hindley~\\cite{Hin} used the unification algorithm of\nAlan Robinson~\\cite{Rob} and also presented the precursor of our type\ninference system.  James Morris~\\cite{Mor} independently gave an\nequation-solving algorithm very similar to Curry's.  The idea of an algorithm\nfor finding principal type schemes is very natural and may well have been\nknown earlier. Roger Hindley has pointed out that Carew\nMeredith's inference rule for propositional logic called Condensed Detachment,\ndefined in the early 1950s, clearly suggests that he knew such an algorithm\n\\cite{Mer}.\n\nMilner~\\cite{Mil1}, during the design of ML, rediscovered principal types and\ntheir calculation by unification, for a language (slightly richer than\ncombinatory logic) containing local declarations.  He and Damas~\\cite{DM}\npresented the ML type inference systems following Hindley's style.  Damas\n\\cite{Dam}, using ideas from Michael Gordon, also devised the first\nmathematical treatment of polymorphism in the presence of references and\nassignment.  Tofte~\\cite{Tof-a} produced a different scheme employing\nso-called {\\em imperative types}, which was adopted in the original version of\nthe language.  This approach has been superseded in the present language by a\nsimpler scheme, suggested by Tofte~\\cite{Tof-a}, Andrew Wright~\\cite{wright95}, and\nXavier Leroy~\\cite{Ler1}, according to which polymorphic bindings are\nrestricted to non-expansive expressions.\n\n\\subsection*{Refinement of the Core Language}\n\nTwo movements led to the re-design of ML.  One was the work of Rod\nBurstall and his group on specifications, crystallised in the specification\nlanguage CLEAR~\\cite{BG} and in the functional programming language HOPE\n\\cite{BMS};  the latter was for expressing executable specifications.  The\noutcome of this work which is relevant here was twofold.  First, there were\nelegant programming features in HOPE, particularly pattern matching and\nclausal function definitions; second, there were ideas on modular construction\nof specifications, using signatures in the interfaces.  A smaller but\nsignificant movement was by Luca Cardelli, who extended the data-type\nrepertoire in ML by adding named records and variant types.\n\nIn 1983, Milner (prompted by Bernard Sufrin) wrote the first draft of a\nstandard form of ML attempting to unite these ideas; over the next three years\nit evolved into the Standard ML core language.  Notable here was the harmony\nfound among polymorphism, HOPE patterns and Cardelli records, and the nice\ngeneralisations of ML exceptions due to ideas from Alan Mycroft, Brian Monahan\nand Don Sannella.  A simple stream-based I/O mechanism was developed from\nideas of Cardelli by Milner and Harper.  The Standard ML core language is\ndescribed in detail in a composite report~\\cite{HMM} which also contains a\ndescription of the I/O mechanism and MacQueen's proposal for program modules\n(see later for discussion of this). Since then only few changes to the core\nlanguage have occurred.  Milner proposed equality types, and these were added,\ntogether with a few minor adjustments~\\cite{Mil3}.  The \nlast development before the 1990 Definition was in the exception mechanism, by MacQueen using an idea\nfrom Burstall~\\cite{AMMT}; it harmonized the ideas of exception and data type\nconstruction.\n\n\\subsection*{Modules}\n\nBesides contributory ideas to the core language, HOPE~\\cite{BMS} contained a\nsimple notion of program module.  The most important and original feature of\nML modules, however, stems from the work on parameterised specifications in\nCLEAR~\\cite{BG}.  MacQueen, who was a member of Burstall's group at the time,\ndesigned~\\cite{Mac} a new parametric module feature for HOPE inspired by the\nCLEAR work.  He later extended the parameterisation ideas by a novel method of\nspecifying sharing of components among the structure parameters of a functor,\nand produced a draft design which accommodated features already present in ML\n-- in particular the polymorphic type system.  This design was discussed in\ndetail at Edinburgh, leading to MacQueen's first report on modules~\\cite{HMM}.\n\nThereafter, the design came under close scrutiny through a draft operational\nstatic semantics and prototype implementation of it by Harper, through Kevin\nMitchell's implementation of the evaluation, through a denotational semantics\nwritten by Don Sannella, and then through further work on operational\nsemantics by Harper, Milner, and Tofte.  (More is said about this in the later\nsection on Semantics.)  In all of this work the central ideas withstood\nscrutiny, while it also became clear that there were gaps in the design and\nambiguities in interpretation.  (An example of a gap was the inability to\nspecify sharing between a functor argument structure and its result structure;\nan example of an ambiguity was the question of whether sharing exists in a\nstructure over and above what is specified in the signature expression which\naccompanies its declaration.)\n\nMuch discussion ensued; it was possible for a wider group to comment on\nmodules through using Harper's prototype implementation, while Harper, Milner\nand Tofte gained understanding during development of this semantics.  In\nparallel, Sannella and Tarlecki explored the implications of modules for the\nmethodology of program development~\\cite{ST}.  Tofte, in his thesis\n\\cite{tofte88}, proved several technical properties of modules in a skeletal\nlanguage, which generated considerable confidence in this design. A key point\nin this development was the proof of the existence of principal signatures,\nand, in the careful distinction between the notion of {\\it enrichment} of\nstructures, which allows more polymorphism and more components, and {\\it\nrealisation} which allows more sharing.\n\nAt a meeting in Edinburgh in 1987 a choice of two designs was presented,\nhinging upon whether or not a functor application should coerce its actual\nargument to its argument signature.  The meeting chose coercion, and\nthereafter the production of Section~\\ref{statmod-sec} of this report -- the\nstatic semantics of modules -- was a matter of detailed care.  That section is\nundoubtedly the most original and demanding part of this semantics, just as\nthe ideas of MacQueen upon which it is based are the most far-reaching\nextension to the original design of ML.\n\nConsiderable experience was gained in implementing, programming with, and\nteaching the language during the nearly ten years since the definition was\nfirst published.  Based on this experience a number of design decisions were\nrevisited at a meeting of the authors in Cambridge at the end of 1995.  At\nthis meeting it was decided to make several modest, but significant, changes\nto the language in order to simplify the semantics and to correct some\nshortcomings that had come to light.  The most important of these changes was\nthe replacement of the imperative type discipline by the so-called value\nrestriction (discussed above), the elimination of structure sharing as a\nseparate concept from type sharing, and the introduction of the closely\nconnected mechanisms of opaque signature matching and type abbreviations in\nsignatures.  An important impetus for these changes to the modules language\nwas the work of Leroy~\\cite{leroy94}, and Harper and\nLillibridge~\\cite{HL} on the type-theoretic interpretation of\nmodules (described below).\n\n\\subsection*{Implementation}\n\nThe first implementation of ML was by Malcolm Newey, Lockwood Morris and Robin\nMilner in 1974, for the DEC10.  Later Mike Gordon and Chris Wadsworth joined;\ntheir work was mainly in specialising ML towards machine-assisted reasoning.\nAround 1980 Luca Cardelli implemented a version on VAX; his work was later\nextended by Alan Mycroft, Kevin Mitchell and John Scott.  This version\ncontained one or two new data-type features, and was based upon the {\\em\nFunctional Abstract Machine (FAM)}, a virtual machine which has been a\nconsiderable stimulus to later implementation.  By providing a reasonably\nefficient implementation, this work enabled the language to be taught to\nstudents; this, in turn, prompted the idea that it could become a useful\ngeneral purpose language.\n\nIn Gothenburg, an implementation was developed by Lennart Augustsson and\nThomas Johnsson in 1982, using lazy evaluation rather than call-by-value; the\nresult was called {\\em Lazy ML} and is described in~\\cite{Aug}.  This work is\npart of continuing research in many places on implementation of lazy\nevaluation in pure functional languages.  But for ML, which includes\nexceptions and assignment, the emphasis has been mainly upon strict evaluation\n(call-by-value).\n\nIn Cambridge, in the early 1980s, Larry Paulson made considerable improvements\nto the Edinburgh ML compiler, as part of his wider programme of improving {\\em\nEdinburgh LCF} to become {\\em Cambridge LCF}~\\cite{Pau}.  This system has\nsupported larger proofs than the Edinburgh system, and with greater\nconvenience; in particular, the compiled ML code ran four to five times\nfaster.\n\nAround the same time G\\'{e}rard Huet at INRIA (Versailles) adapted ML to\nMaclisp on Multics, again for use in machine-assisted proof.  There was close\ncollaboration between INRIA and Cambridge in this period.  ML has undergone a\nseparate development in the group at INRIA on the {\\em CAML}\nlanguage~\\cite{CCM}.  Work on {\\em CAML} included the development of several\nextensions to the core language, notably updatable fields in record types,\nvalues with dynamic types, support for lazy evaluation, and handling of\nembedded languages with user-defined syntax.  It did not, however, include\nmodules.\n\nThe first implementation of the Standard ML core language was by Mitchell,\nMycroft and Scott at Edinburgh, around 1984.  The prototype implementation of\nmodules, before that part of the language settled down, was done in 1985-6;\nMitchell dealt with evaluation, while Harper tackled the elaboration (or\n`signature checking') which raised problems of a kind not previously\nencountered.  Harper's implementation employed a form of unification that was\nlater adopted in the static semantics of modules.\n\nAt around the same time the {\\em Poly/ML} implementation began with a\nsuggestion from Mike Gordon that an interesting application of Matthews' Poly\nlanguage would be to implement Standard ML.  Important experience was gained\nthrough Matthews' early implementation of the core language, followed by\nseveral versions of the modules language as they were devised.  {\\em Poly/ML}\nfeatures arbitrary precision arithmetic, a process package, and a windowing\nsystem.  Considerable experience has been gained with the compiler, notably by\nLarry Paulson at Cambridge and by Abstract Hardware Limited (AHL).\n\n  The {\\em Standard ML of New Jersey (SML/NJ)} system has been in active development\n  since 1986~\\cite{am87,am91}.\n  Initially started by David MacQueen at Bell Laboratories and Andrew Appel at Princeton University, \n  the project has also benefited from significant contributions\n  by Matthias Blume, Emden Gansner, Lal George, John Reppy and Zhong Shao.\n  {\\em SML/NJ} is a robust and complete environment for Standard ML that supports\n  the implementation of large software systems and generates efficient code for a\n  number of different hardware and software platforms.  {\\em SML/NJ} also serves as\n  a laboratory for compiler research: in implementations of module systems for ML;\n  code optimization based on continuation-passing style; efficient pattern matching;\n  and very fast heap allocation and garbage collection.  Dozens of researchers\n  have contributed to the development of the compiler, in such areas as\n  efficient closure representations, first-class continuations, type-directed\n  compilation, concurrent programming, portable code generators, separate\n  compilation, and register allocation.  \n  {\\em SML/NJ} has also been widely used to explore extending SML with\n  concurrency features.\n\n%In 1986 Andrew Appel and David MacQueen began work on the {\\em Standard ML of\n%New Jersey (SML/NJ)} compiler~\\cite{am87}.  {\\em SML/NJ} is a robust and\n%complete environment for Standard ML that supports the implementation of large\n%software systems and generates efficient code for a number of different\n%hardware and software platforms.  {\\em SML/NJ} also serves as a laboratory for\n%compiler research: in implementations of module systems for ML; code\n%optimization based on continuation-passing style; efficient pattern matching;\n%and very fast heap allocation and garbage collection.  Dozens of researchers\n%have contributed to the development of the compiler, in such areas as\n%efficient closure representations, first-class continuations, type-directed\n%compilation, concurrent programming, portable code generators, separate\n%compilation, and register allocation.  \n\n\nIn 1989, Mads Tofte, Nick Rothwell and David N. Turner started work on the\n{\\em ML Kit Compiler} in Edinburgh. The {\\em ML Kit} is a direct translation\nof the 1990 Definition into a collection of Standard ML modules, emphasis being\non clarity rather than efficiency. During 1992 and 1993, Version~1 of the {\\em\nML Kit} was completed, mostly through the work of Nick Rothwell at Edinburgh\nand Lars Birkedal at DIKU\\cite{BRTT}. In 1994, region inference was added to\nthe {\\em ML Kit}, by Mads Tofte. Lars Birkedal wrote a region-based C-code\ngenerator and a runtime system in C.  In 1995, Martin Elsman and Niels\nHallenberg extended this work to generate native code for the HP PA-RISC\narchitecture.\n\nHarlequin Ltd. began the implementation of a commercial compiler in 1990.  The\n{\\em MLWorks} system is a fully-featured graphical programming environment,\nincluding an interactive debugger, inspector, browser, extensive profiling\nfacilities, separate compilation and delivery, a foreign-language interface,\nand libraries for threads and windowing systems.  \n%Harlequin was a major\n%partner in the effort to standardize the revised Standard ML basis library.\n\n{\\em Caml Light}, a lightweight reimplementation of {\\em CAML} released in\n1991, added a simple module system in the style of Modula-2, targeted towards\nseparate compilation of modules: structures and signatures are identified with\nfiles, functors and multiple views of a structure are not supported.  These\nwere added in the {\\em Caml Special Light} implementation in 1995, while\npreserving the support for separate compilation. {\\em Caml Special Light} and\nthe present version of Standard ML share several important simplifications,\nsuch as the value restriction on polymorphism, type definitions in signatures,\nand the lack of support for structure sharing.  The static semantics for {\\em\nCaml Special Light} is based on the type-theoretic properties of dependent\nfunction types (functor signatures) and manifest types (type definitions in\nsignatures)~\\cite{leroy94}.\n\n{\\em Moscow ML} is an implementation of core Standard ML, created in 1994 by\nSergei Romanenko in Moscow and Peter Sestoft in Copenhagen.  The {\\em Caml\nLight} system was used to implement the dynamic semantics, and the ML Kit\nguided the implementation of the static semantics.  The result is a compact\nand robust implementation, suitable for teaching.\n\nThe {\\em TIL (Typed Intermediate Languages)} compiler developed at Carnegie\nMellon\nUniversity by Greg Morrisett, David Tarditi, Perry Cheng, Chris Stone,\nRobert Harper,\nand Peter Lee demonstrates the use of\ntypes in compilation.  All but the last few stages of {\\em TIL} are expressed\nas type-directed and type-preserving transforms.  Types are used at run time\nto support unboxed, untagged data representations and natural calling\nconventions in the presence of variable types and garbage collection.  {\\em\nTIL} employs a wide variety of conventional functional language optimizations\nfound in other SML compilers, as well as a set of loop-oriented optimizations.\nA description of the compiler and an analysis of its performance appears\nin~\\cite{Tar}.\n\nOther currently active implementations are by Michael Hedlund at the\nRutherford-Appleton Laboratory, by Robert Duncan, Simon Nichols and Aaron\nSloman at the University of Sussex ({\\em POPLOG}) and by Malcolm Newey and his\ngroup at the Australian National University.\n \n\\subsection*{Semantics}\n\nThe description of the first version of ML~\\cite{GMW} was informal, and in an\noperational style; around the same time a denotational semantics was written,\nbut never published, by Mike Gordon and Robin Milner.  Meanwhile structured\noperational semantics, presented as an inference system, was gaining credence\nas a tractable medium.  This originates with the reduction rules of\n$\\lambda$-calculus, but was developed more widely through the work of Plotkin\n\\cite{Plo}, and also by Milner.  This was at first only used for dynamic\nsemantics, but later the benefit of using inference systems for both static\nand dynamic semantics became apparent.  This advantage was realised when\nGilles Kahn and his group at INRIA were able to execute early versions of both\nforms of semantics for the ML core language using their Typol system\n\\cite{Des}.  The static and dynamic semantics of the core language reached a\nfinal form mostly through work by Tofte and Milner.\n\nThe modules of ML presented little difficulty as far as dynamic semantics is\nconcerned, but the static semantics of modules was a concerted effort by\nseveral people.  MacQueen's original informal description~\\cite{HMM} was the\nstarting point; Sannella wrote a denotational semantics for several versions,\nwhich showed that several issues had not been settled by the informal\ndescription.  Robert Harper, while writing the first implementation of\nmodules, made the first draft of the static semantics.  Harper's version made\nclear the importance of structure names; work by Milner and Tofte introduced\nfurther ideas including realisation; thereafter a concerted effort by all\nthree led to several suggestions for modification of the language, and a small\nrange of alternative interpretations; these were assessed in discussion with\nMacQueen, and more widely with the principal users of the language, and an\nagreed form was reached.\n\nConcurrently with the formulation of the Definition of Standard ML, Harper and\nMitchell took up the challenge adumbrated by MacQueen~\\cite{Mac2} to find\na type-theoretic interpretation of Standard ML~\\cite{HM}.  This work led to\nthe formulation of the XML language, an explicitly-typed $\\lambda$-calculus\nthat captured many aspects of Standard ML.  Although incomplete, their\napproach formed the basis for a number of subsequent studies, including the\nwork of Harper and Lillibridge~\\cite{HL} and Leroy~\\cite{leroy94} on the\ntype-theoretic interpretation of modules.  This work influenced the decision\nto revise the language, and culminated in a type-theoretic interpretation of\nthe present language by Harper and Stone~\\cite{SH}.  The TIL/ML compiler\n(described above) is based directly on this interpretation.\n\nThere is no doubt that the interaction between design and semantic description\nof modules has been one of the most striking phases in the entire language\ndevelopment, leading (in the opinion of those involved) to a high degree of\nconfidence both in the language and in the semantics.\n\n\n\\subsection*{Program Libraries}\n%During 1989-1991, Dave Berry produced the first program library for\n%Standard ML\\cite{mllib91,berry93}. Subsequently, a partnership between\n%the originators of {\\em SML/NJ}, {\\em MLWorks} and \n%{\\em Moscow ML} was formed, with the goal of creating an industrial strength\n%initial basis for Standard ML. The resulting SML Basis \n%Library\\cite{mllib96} is a much improved and extended \n%replacement of the initial basis defined in the 1990 Definition of \n%Standard ML.\n During 1989-1991, Dave Berry produced the first program library for\n Standard ML\\cite{mllib91,berry93}.\n The {\\em SML/NJ} system is distributed with a rich library organised by\n Emden Gansner and John Reppy; this library was the starting point for\n the SML Basis Library~.\n The {\\em SML Basis Library\\/}\\cite{mllib96} has been developed \n over the past three years in a\n partnership between the SML/NJ effort, {\\em MLWorks}, and {\\em Moscow ML}.\n The resulting library is a much improved and extended \n replacement of the initial basis defined in the 1990 Definition of \n Standard ML.\n", "meta": {"hexsha": "d31f4e6f632b06babccbd9ef132f8318fef2570c", "size": 23317, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/definition/app5.tex", "max_stars_repo_name": "baguette/emblem-sandbox", "max_stars_repo_head_hexsha": "8aaa3f3c23be43210be064cd0c0bf4c56c6c50cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-01-11T20:01:15.000Z", "max_stars_repo_stars_event_max_datetime": "2016-01-11T20:01:15.000Z", "max_issues_repo_path": "doc/definition/app5.tex", "max_issues_repo_name": "baguette/emblem-sandbox", "max_issues_repo_head_hexsha": "8aaa3f3c23be43210be064cd0c0bf4c56c6c50cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/definition/app5.tex", "max_forks_repo_name": "baguette/emblem-sandbox", "max_forks_repo_head_hexsha": "8aaa3f3c23be43210be064cd0c0bf4c56c6c50cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 60.7213541667, "max_line_length": 101, "alphanum_fraction": 0.8057640348, "num_tokens": 5278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.3069731619528473}}
{"text": "\\chapter{Conclusion \\& Perspectives}         % ne pas numéroter\r\n%\\phantomsection\\addcontentsline{toc}{chapter}{Conclusion \\& Perspectives} % dans TdM\r\n\r\n\\section{General conclusions}\r\nThe objectives of the present thesis were, first, to deploy the infrared thermography technique in the procedure of maintaining the ``cold food chain'', especially in insulated vehicles of ATP standards. The application of infrared thermography aims to identify thermal insulation anomalies, which the standard ATP test cannot localize. \r\n\r\nThe preliminary work focused on mapping the heat flux on the external surface of an insulated roll-container using the Infrared thermography technique. The ATP standard measurement was performed to obtain the experimental results, meanwhile IR images of the roll-container were obtained when the steady condition was reached, in order to analyze and compute the corresponding heat flux on the entire surface. A simple thermal resistance model was applied to conduct the computation. Final temperature figures showed a good uniform distribution, and several defects in the structure such as thermal bridges or air leakages were identified. A reference zone of the external wall was measured by a thermal flux meter, then with that reference the entire surface heat flux map was determined. In addition, for a better view of the heat flux map, the homography, one of the computer vision techniques, was performed in the raw images by applying a bilinear interpolation with the projective transformation matrix. The final corrected heat flux map was demonstrated for each surface, in which the right surface showed a smaller value than the others.  Due to the air streaming, temperatures in the lateral surfaces were a little smaller than other surfaces, thus this lead to the smaller heat flux values.\r\n\r\nWhen implemented into the internal surface of the insulated vehicle, a panoramic view was needed, since the field of view (FOV) of the infrared camera could not capture the entire surface of insulated vehicle. With the help of an infrared camera mounted on a pan-tilt head and automatically driven by a suitable software, a series of thermal images of the inner walls of the vehicle under steady condition have been captured. Proper computer vision techniques such as inverse spherical projection and stitching images by translation helped to generate the final panorama. The same thermal resistance model was utilized to compute the corresponding heat flux map. Results demonstrated a good performance of the algorithm, though the manual creation of the panoramic view required more time for completion. Compared with the standard ATP test, the final K-value obtained by infrared thermography showed a good accuracy (0.87\\% of error).\r\n\r\nThen based on the previous favorable results, the second aspect of this project was to explore cold approaches (such as compressed air, liquid nitrogen, etc.) in infrared thermography for Non-Destructive Testing \\& Evaluation. The first interesting idea of detection of insulation flaws and thermal bridges in insulated truck box panels then emerged. As it is not convenient to heat the entire vehicle panels for the detection, cooling them by compressed air therefore can be a better solution. The study then focused on the cooling approach for the truck box panels inspection by infrared thermography. Both heating and cooling methods were applied by lamp and compressed air respectively. Numerical simulations under COMSOL Multiphysics{\\textregistered} platform were conducted as well. For a comprehensive analysis, passive thermography detection in computational models has been presented at the same time. Results demonstrate that the compressed air spray is more rapid than the traditional heating method in providing successful detection.\r\n\r\nA consideration of replacing compressed air by liquid nitrogen was then explored in more detail. Thus a study was performed, in which a steel specimen was used to test three different stimulations for thermal images and also Receiver Operating Characteristic (ROC) analysis comparison. Results showed that all techniques highlighted part of the flaws in the sample, whereas the liquid nitrogen technique represented the defects only at the beginning; this may be due to the high conductivity of steel. In thermal results, the PCT post-processing method displayed better results for all procedures. More defects were exhibited in Flash stimulation with PCT processing. ROC curve analysis has elucidated a straightforward classification comparison, in which the best curve was obtained using the Flash technique with PCT processing. \r\n\r\n\r\n\r\n\\section{Future perspectives}\r\nGenerally, the infrared thermography technique has been applied with promising results in ATP standard insulated vehicle tests, for the goal of maintaining the ``cold food chain\". The results have demonstrated that the benefits of time-saving and the accuracy in the determination of the K-value could be applied for assessment at a commercial level.  For the panoramic view of the insulated vehicle internal surface, due to the repeated structure on the internal surface of vehicle, algorithms of automatic creation which have better feature detection and comparison remain to be explored.  A suitable software package may be created to simplify the post-processing of thermal images. This will facilitate the computation of the K-value.\r\n\r\nOn the other hand, the exploration of cold approaches in infrared thermography for Non-Destructive Testing and Evaluation has also shown several advantages. Compressed air cooling can be a good replacement of heating in the detection of insulation flaws for truck box panels. The strategy of heating one side and cooling another side can be deployed in practice, since ideal cases in simulation show favorable results.\r\n\r\nThe use of ROC curves to compare the different methods in infrared thermography is an interesting approach. This technique would benefit from more complete application and discussion, which would favor a more harmonious implementation in traditional techniques of NDT.\r\n\r\n\r\n\r\n", "meta": {"hexsha": "0c7e6f5583986fc7eeb6af182a68d71d7a6bb559", "size": 6127, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "main/conclusion.tex", "max_stars_repo_name": "Crescent-Saturn/PhD_grind", "max_stars_repo_head_hexsha": "aaa976e6c1c9bf932cd7cb44147a6a25a0537e39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main/conclusion.tex", "max_issues_repo_name": "Crescent-Saturn/PhD_grind", "max_issues_repo_head_hexsha": "aaa976e6c1c9bf932cd7cb44147a6a25a0537e39", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main/conclusion.tex", "max_forks_repo_name": "Crescent-Saturn/PhD_grind", "max_forks_repo_head_hexsha": "aaa976e6c1c9bf932cd7cb44147a6a25a0537e39", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 235.6538461538, "max_line_length": 1300, "alphanum_fraction": 0.8212828464, "num_tokens": 1092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.30697315497766314}}
{"text": "\\documentclass[../../main]{subfiles}\n\\graphicspath{{images/rubiks-exp/}}\n\n\\begin{document}\n\nThis project is a continuation of the previous experiment described in Section \\ref{subsec:sudoku_experiment}. Ideas developed for Sudoku were extrapolated on a Rubik's cube face detection problem as they are assumed to be similar in some sense \\cite{rubiks_cube_zakharov}.\n\n\\subsubsection{Contour and corner detection}\n\nContour detection was covered in the previous step but in this case there were some issues to be solved. From the beginning, it was an issue that edges of the cube are not very clear thus face extraction with the biggest contour is not an option. On the contrary, small contours of face pieces were detected with higher success rate. Therefore, they were used for face detection. So as the next step, the closed contours with proper approximation of 4 corners were picked. These contours were supposed to be diffused square pieces of cube's face. The mentioned operations still were not able to filter all duplicates. They occur from time to time if \\ac{OpenCV} detects a couple of different contours for the same object. To reject unnecessary contours, all of those with almost the same center of mass were removed but one. In order to find a face it is not enough to find contours. Diagonal of these small contours were computed and if 9 diagonals exist and located at the same angle to horizon their contours assumed to be face's pieces. The following action is to find the extremums or top-left, top-right, bottom-left, bottom-right points. The found extremums are expected to be the face's corners.\n\n\\subsubsection{Extraction}\n\nThe corner detection is covered in the previous subsection thus at this point 4 detected corners should to be passed to the next stage to apply linear transformation. As a result, plane image of the face will be stored.\nThis approach has the limitation for an input. It is not possible to detect the face corners if an image or a video quality is poor or contours are broken. These circumstances will fail face extraction. However, if the source quality is sufficient then this algorithm performs well because of its simplicity and performance.\n\n\\subsubsection{Transforming Image}\n\nAt this stage the same approach as in the Sudoku experiment was used. The same set of equations was used to transform the image. The system of equations from figure \\ref{eq:persptransform} makes mapping of points from distorted image to a flat square image possible. To achieve this \\ac{OpenCV}'s $GetPerspectiveTransform$ and $WarpPerspective$ methods were used for applying perspective transformation to the source.\n\n\\subsubsection{Identifying unique faces}\n\nThere are many possible options to check images for similarities like feature matching, color histograms, cross correlation, euclidean distance. Looking at a cube it is clear that there are no specific features on it, only colored pieces. The other case is the observation problem, the cube can be shown in different orientations. From the observations made, color histograms was chosen as a best choice to distinguish faces.\nAll uniquely detected faces were stored in the list and compared with every newly detected face. In order to achieve this images were converted to \\ac{HSV} to calculate the histogram and normalize the results. To compare images correlation was used and performed well. For example, if the correlation is more than 0.6 it is assumed that faces are too similar thus the new one has to be rejected as already found.\nThis algorithm is a simple one however the empirical research showed that it works as expected.\n\n\\subsubsection{Color detection}\n\nColor detection is nearly the easiest part of the program. In order to detect \\ac{RGB} color representation for each piece of a cube face it should be segmented into $n$ equal squares, since the 3 by 3 Rubik's cube was used. The segmentation operation produces nine pieces and this approach cannot handle larger cubes.\nAfter the piece of the face is cut out, the center pixel \\ac{RGB} data and intensity are taken. The extracted data is collected into specific data structure and this is the end of the process. Extracted \\ac{RGB} colors are mapped to the new data structure in order to convert it to the Rubik's cube 3D model for solving and rendering purposes. \n\n\\subsubsection{Conclusion}\n\nThis project was a continuation of the Sudoku ideas projected onto the Rubik's cube. At this stage single faces were extracted correctly but some faces extraction might fail due to illumination conditions. In fact, cube's surface may be different and it means that when the light falls on the surface it may be reprojected and create color distortions thus it brakes edge detection. Under the good illumination conditions corners of faces and pieces colors are extracted correctly.  From the figure \\ref{fig:rubiks_cube_face_detected} it is clearly seen that this approach is applicable for the given problem.\n\n\\begin{figure} [ht]\n    \\begin{center}\n        \\includegraphics[width=150pt]{detected_face}\n        \\includegraphics[width=150pt]{extracted_face}\n        \\caption{Detected and extracted face sample with distorted colors.}\n        \\label{fig:rubiks_cube_face_detected}\n    \\end{center}\n\\end{figure}\n\n\\end{document}", "meta": {"hexsha": "8b41cfc65f92e0787415e6f6f5e85a27aff6d4dc", "size": 5275, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/Master Thesis/sections/experiments/rubiks-cube-lines-experiment.tex", "max_stars_repo_name": "Lewis945/RubiksCubeSolver", "max_stars_repo_head_hexsha": "30926412ef0fce764c9d737940a757ec4f55d3ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/Master Thesis/sections/experiments/rubiks-cube-lines-experiment.tex", "max_issues_repo_name": "Lewis945/RubiksCubeSolver", "max_issues_repo_head_hexsha": "30926412ef0fce764c9d737940a757ec4f55d3ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/Master Thesis/sections/experiments/rubiks-cube-lines-experiment.tex", "max_forks_repo_name": "Lewis945/RubiksCubeSolver", "max_forks_repo_head_hexsha": "30926412ef0fce764c9d737940a757ec4f55d3ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 117.2222222222, "max_line_length": 1203, "alphanum_fraction": 0.8018957346, "num_tokens": 1097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.3068113236061447}}
{"text": "\\documentclass[twocolumn,12pt]{scrartcl}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Text formatting %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\setkomafont{disposition}{\\normalfont\\bfseries}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Includes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\usepackage{amsmath, amsfonts, amsbsy, amssymb}\n\\usepackage{lipsum}\n\\usepackage{paralist}\n\\input{Qcircuit.tex}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Title %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\title{An Introduction to Quantum Circuits and Shor's Algorithm}\n\\subtitle{A literature survey}\n\\author{Ben Hamlin}\n\\date{}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Macros %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\newcommand{\\mat}[2][ccccccccccccccccccccccccccccccccccc]{\\left[\n  \\begin{array}{#1}\n  #2\\\\\n  \\end{array}\n\\right]}\n\n\\newcommand{\\rot}{\\frac{1}{\\sqrt{2}}}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Document %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\begin{document}\n\n\\maketitle\n\n\\section{Introduction}\n\\label{sec:intro}\n\nQuantum computing systems are nothing more than a collection of\nTuring-equivalent programming systems. They differ from classical programming\nsystems, however, in that they rely on the features of quantum mechanics to\nperform computations. It's an open question whether this gives them a\nfundamental advantage in complexity over classical methods (a more than\npolynomial speedup over ``physically realizable'' classical machines), but\nthere's enough evidence to make studying them worthwhile.\n\nIn order to take take advantage of --- or, put another way, to model --- quantum\nmechanics, a system must have some way to represent all of the following\n\\cite{pit00}: \\begin{compactenum}\n\\item {\\it probabilistic states:} A closed quantum system is characterized by\n      the probability that it will be in each of a set of observable states when\n      it is measured;\n\\item {\\it change in state:} The probabilities that characterize a state can be\n      manipulated to change over time, making computation possible. This is\n      frequently called {\\it time evolution} in the literature;\n\\item {\\it measurement:} When a quantum system is measured, its state resolves\n      into a particular observable outcome. This effect is distinct from time\n      evolution;\n\\item {\\it interference:} The probabilities associated with each component of\n      a closed quantum system can affect or ``interfere'' with the probabilities\n      associated with other components. This results in the two components\n      having non-independent distributions.\n\\end{compactenum} A variety of systems with these properties have been proposed.\nBernstein and Vazirani have suggested a quantum analog of the classical Turing\nmachine \\cite{ber97}, and quantum cellular automata, proposed by Richard\nFeynmann, have been formalized more recently by Delgado and others \\cite{del07}.\nQuantum circuits remain the most popular system for representing quantum\nalgorithms, however, and those are what this paper will cover.\n\nThe goal of this paper is to introduce the reader to quantum circuits from the\nperspective of computational theory. In the process, I'll survey some of the\nliterature on this topic and walk through some examples of how quantum circuits\ncan be applied. In sections \\ref{sec:qubits} and \\ref{sec:ensembles}, I'll\nintroduce the basic abstractions in the quantum circuit model: qubits and qubit\nensembles. I'll also introduce the concept of ``mixed'' or ``entangled'' states,\nwhich is one of the principle ways in which quantum computation differs from\nclassical computation. Next, in section \\ref{sec:operations} I'll talk about the\noperations that can be applied to qubits and ensembles, and with these\npreliminaries out of the way, I'll describe the system of quantum circuits and\nhow they differ from classical boolean circuits. In sections \\ref{sec:simon} and\n\\ref{sec:shor}, I'll describe some algorithms that can be expressed using\nquantum circuits, including --- to the limited degree to which I understand it\n--- Shor's famous integer factorization algorithm.\n\nI began writing this paper in the hopes of answering the question of whether\nquantum algorithms allow a fundamental speedup over classical algorithms, in\ncontradiction of the strong form of the Church-Turing thesis, and if so, what\nthis speedup entails. In section \\ref{sec:conclusion}, I'll briefly sum up my\nanswer to this question, to the extent that I've succeded in finding one.\n\n\\section{Qubits}\n\\label{sec:qubits}\n\nQubits are the basic unit of quantum information, whether you're working with\nQTMs, quantum circuits, or even the bloch sphere representation used in quantum\nphysics. That is to say, they're not specific to quantum circuits. Nonetheless,\nqubits and their canonical representation as column or ``ket'' vectors are\ncentral to understanding quantum circuits.\n\nA qubit represents a single bit of classical information. When measured, it will\nbe observed to be a zero or a one. However between measurements, a qubit exists\nin a ``superposition'' of classical states. That is, when measured, it will be\na zero with probability $P(0)$ and a one with probability $P(1)$. Obviously,\n$P(0) + P(1) = 1$ in a single qubit system.\n\nRather than express the state of our system using $P(0)$ and $P(1)$ themselves,\nit's useful to think of the one-state and the zero-state as having signed\n{\\it amplitudes} whose squares represent their respective probabilities. I.e.,\n\\[P(0) = a_0^2\\] \\[P(1) = a_1^2\\] This means that \\[\\mat{a_0\\\\a_1}\\]\nis a unit vector. As it turns out, letting $a_0,a_1 \\in \\mathbb{C}$ allows\nus to accurately model the kinds of time evolution we can perform on quantum\nsystems. For complex-valued amplitudes, \\[P(0) = |a_0|^2 = |x_0 + iy_0|^2 =\nx_0^2 + y_0^2\\] and similarly for $P(1)$.\n\nThe standard notation for a qubit in the classical state zero is \\[\\ket{0}\\] The\nimplication here is that, even though the qubit happens to be in a classical\nstate, it still has amplitudes: \\[\\ket{0} = 1\\ket{0} + 0\\ket{1}\\] More\ngenerally, a qubit is always in the state \\[a_0\\ket{0} + a_1\\ket{1}\\] where\n$a_0$ and $a_1$ are amplitudes, as before. This is called Dirac notation, and\nthe symbol $\\ket{n}$ is called a {\\it ket}\\footnote{There's also a ``bra'',\nhence together they're ``bra-ket'' notation. A bra, written $\\bra{n}$, is\njust a row vector, the complex transpose of a ket.}.\n\nThis notation avoids some messy typesetting, but at first glance, it hides an\nimportant fact: A ket is nothing more than a column vector. That is, \\[\\ket{0} =\n\\mat{1\\\\0}\\] \\[\\ket{1} = \\mat{0\\\\1}\\]. More generally, you'll see when we\ntalk about ensembles of qubits that $\\ket{b}$, where $b \\in \\{0, 1\\}^n$ is the\nbinary representation of the number $B$, is the n-dimensional column vector in\nwhich the $B$th element is a one, and the rest are zeroes. Thus \\[a_0\\ket{0} +\na_1\\ket{1} = a_0\\mat{1\\\\0} + a_1\\mat{0\\\\1}\\] \\[= \\mat{a_0\\\\0} + \\mat{0\\\\a_1} =\n\\mat{a_0\\\\a_1}\\] which is identical to our unit vector representation above.\n\nThe ket vectors $\\ket{0}$ and $\\ket{1}$ are called {\\it bases} --- in linear\nalgebra terms, orthonormal basis vectors. It's worth noting that they're not\nunique. These particular bases --- called the computational bases in the\nliterature --- are useful because their amplitudes correspond to the\nprobabilities of observing the classical states when measured. Nonetheless, we\ncould as easily express the state of our system using any set of orthonormal\nbases. For example, \\[\\ket{+} = \\mat{1\\\\1}\\] \\[\\ket{-} = \\mat{1\\\\-1}\\] are\ncalled the Bell bases.\n\nWe can derive a Bell representation of a qubit using the following\nidentities: \\[\\ket{0} = \\frac{\\ket{+} + \\ket{-}}{\\sqrt{2}}\\] \\[\\ket{1} =\n\\frac{\\ket{+} - \\ket{-}}{\\sqrt{2}}\\] As we'll see in section\n\\ref{sec:operations}, viewing a quantum system in terms of the Bell bases can\nmake the effects of some quantum operations seem less mystifying\\footnote{\nIn fact from a physical perspective, we could even {\\it measure} the qubit with\nrespect to these bases. That is, we could measure the qubit $\\ket{\\phi} =\na_+\\ket{+} + a_-\\ket{-}$ in such a way that we would see a $\\ket{+}$ with\nprobability $|a_+|^2$ and a $\\ket{-}$ with probability $|a_-|^2$. This would\ntell us nothing about whether the qubit was a $\\ket{0}$ or a $\\ket{1}$\n\\cite{nie00}. For the purposes of quantum computation, all measurement happens\nwith respect to the computational bases.}.\n\n\\section{Ensembles of Qubits}\n\\label{sec:ensembles}\n\nOne of the principle notions in quantum computation --- called interference ---\nis that the amplitudes of one qubit can affect the amplitudes of another qubit\nin the same closed system before they are measured. This results in qubits whose\nprobability distributions are intertwined. Put in the terminology of quantum\nmechanics, they are {\\it entangled,} or in a {\\it mixed} as opposed to a\n{\\it pure} state. The upshot of this is that being able to represent qubits in\nisolation isn't enough. We need to be able to represent groups or\n{\\it ensembles} of qubits.\n\nThe computational bases for qubit ensembles are analogous to the ones used for\nindividual qubits. That is, \\[\\ket{...000} = \\mat{1\\\\0\\\\0\\\\.\\\\.\\\\.} ,\n\\ket{...001} = \\mat{0\\\\1\\\\0\\\\.\\\\.\\\\.} , ...\\] More precisely, the states of an\nensemble's component qubits are combined using the tensor product ($\\otimes$),\ndefined as \\[\\mat{a_0\\\\a_1\\\\.\\\\.\\\\.} \\otimes \\mat{b_0\\\\b_1\\\\.\\\\.\\\\.} =\n\\mat{a_0 \\times b_0\\\\a_0 \\times b_1\\\\a_1 \\times b_0\\\\.\\\\.\\\\.}\\] Note that tensor\ndistributes over addition, so that \\[a \\otimes (b + c) = a \\otimes b + a\n\\otimes c\\]\n\nIf we have two qubits $\\ket{\\phi_a} = a_0\\ket{0} + a_1\\ket{1}$ and $\\ket{\\phi_b}\n= b_0\\ket{0} + b_1\\ket{1}$, the ensemble $\\ket{\\phi_0} \\otimes \\ket{\\phi_1}$,\noften expressed as $\\ket{\\phi_0}\\ket{\\phi_1}$, or even $\\ket{\\phi_0\\phi_1}$, is\n\\[a_0b_0\\ket{00} + a_0b_1\\ket{01} + a_1b_0\\ket{10} + a_1b_1\\ket{11}\\] \\[=\n\\mat{a_0b_0\\\\a_0b_1\\\\a_1b_0\\\\a_1b_1}\\] Thus an ensemble with $n$ qubits will\nbe represented using $2^n$ basis vectors and amplitudes. Again, the square of\nthe amplitude of each state corresponds to the probability of observing that\nstate when the system is measured. That is $P(00) = |a_0b_0|^2$, etc.\n\nIt's also possible to measure just one qubit of an ensemble \\cite{nie00}. Given\nthe ensemble \\[a_{00}\\ket{00} + a_{01}\\ket{01} + a_{10}\\ket{10} +\na_{11}\\ket{11}\\] measuring just the first qubit gives us \\[P(0) = |a_{00} +\na_{01}|^2 \\] \\[P(1) = |a_{10}|^2 + |a_{11}|^2\\] and assuming the outcome of our\nmeasurement was $X$, the new state of the ensemble is \\[\\frac{a_{X0}\\ket{X0} +\na_{X1}\\ket{X1}}{\\sqrt{P(X)}}\\]\n\nA simple example of an entangled state is $\\frac{\\ket{00} +\n\\ket{11}}{\\sqrt{2}}$, sometimes called the Bell state. Say we measure the first\nqubit in an ensemble in the Bell state and, with probability $\\frac{1}{2}$, we\nobserve a $\\ket{0}$. The new state of the ensemble is\n\\[\\frac{\\rot\\ket{00}}{\\rot} = \\ket{00}\\] so the second qubit must be a\n$\\ket{0}$. On the other hand, if we observe the first qubit to be a $\\ket{1}$,\nthe second qubit must also be a $\\ket{1}$. Measuring the first qubit changes the\nprobabilities associated with the second. There is no way to represent this\nwith single-qubit ket vectors.\n\nIt's important to note that increasing the number of qubits in the ensemble by\none multiplies the number of amplitudes by two. This makes quantum circuits ---\nand quantum mechanics in general --- difficult to simulate with a classical\ncomputer. It also hints at the power of quantum computing: An ensemble of $n$\nqubits seems to contain $2^n$ complex-valued amplitudes --- significantly more\nthan $n$ bits of information. This information isn't immediately useful, since\nmeasuring the qubit resolves the ensemble into a classical state, and $n$ bits\nof information are lost. Quantum algorithm design is an exercise in trying to\nuse interference to perform calculations using this extra information before\nthe system is measured.\n\n\\section{Operations and Gates}\n\\label{sec:operations}\n\nEnsembles of qubits allow us to represent the probabilistic state of a quantum\ncomputational system at a single moment in time. In addition, we need to be able\nto represent the way the system changes over time --- its so-called ``time\nevolution.'' In fact, in order to perform computations, we need to be able to\nexecute these changes. Since we're representing qubits and ensembles with\n$2^n$-dimensional unit vectors, it's natural to represent operations as\ndimension-preserving linear transformations, that is, by left-multiplying our\nstate vectors by $2^n\\times2^n$ matrices.\n\nThe laws of probability and physics place some limits on the kinds of operations\nwe can perform. The laws of thermodynamics demand that we only perform\nreversible transformations. That is, we can only multiply our state vectors by\ninvertible matrices. Fortunately, any classical computation can be made\nreversible with only a constant increase in time complexity \\cite{sim97}. In\naddition, it would make no sense if the probabilities associated with the\nobservable outcomes of our system didn't add up to one. Thus we are limited to\noperations that can be described by unitary matrices. Since state vectors have\nelements in $\\mathbb{C}$, our operations must be unitary in the complex-valued\nsense that $P^{-1} = P^\\dagger$, where $P^\\dagger$ is the adjoint\\footnote{\n``Adjoint'' is just a quantum mechanical term for conjugate transpose.} of $P$.\nIn quantum circuits, operations are often refered to as ``gates''. From here on,\nI'll use the terms interchangably.\n\nAny $2^n\\times2^n$ unitary matrix over $\\mathbb{C}$ is a valid transformation on\nan $n$-bit ensemble. This provides us with an infinite number of possible\noperations --- an undesirable state if we ever hope to implement a quantum\ncomputer. A wide variety of sets of ``universal'' operations have been proposed\nto deal with this problem --- ``universal'' in the sense that in combination,\nthey can approximate any quantum operation to an arbitrary degree of accuracy.\nThe most influential approach seems to be the one taken by Barenco, et al.\n\\cite{bar95}, who show that the set of one qubit ``rotations'', which they\nsimulate using five one-qubit operations, along with a single two-qubit\noperation, form a universal set.\n\nThe choice of operations is important because although any universal set of\nquantum operations can be combined to approximate any other quantum operation,\nthey may not be able to do so efficiently. In fact, it is conjectured that\n``almost all'' operations require a number of applications of the universal\ngates that is exponential in the number of input qubits. The choice of a\nuniversal set thus determines which operations can be efficiently approximated.\nIn practice, it seems to be possible to implement useful circuits using a\nrelatively small --- efficiently approximable --- set of operations. This is\ndiscussed more fully in \\cite{bar95} and \\cite{nie00}.\n\nOnly one one-qubit gate has an obvious analog in classical computation:\nthe ``not'' or $X$ gate. This has the effect of swapping the amplitudes of\nthe computational bases. The corresponding matrix representation is \\[X =\n\\mat{0&1\\\\1&0}\\] The effect this has on the classical states is \\[X\\ket{0} =\n\\ket{1}\\] \\[X\\ket{1} = \\ket{0}\\] Note that the interpretation of $X$ as ``not''\nonly makes sense as long as we intend to measure in the computational bases,\nsince \\[X\\ket{+} = \\frac{\\ket{0} + \\ket{1}}{\\sqrt{2}} = \\ket{+}\\] \\[X\\ket{-} =\nX\\frac{\\ket{0} - \\ket{1}}{\\sqrt{2}} = \\frac{\\ket{1} - \\ket{0}}{\\sqrt{2}} =\n-1\\ket{-}\\] So $X\\ket{+} \\not= \\ket{-}$, and vice versa.\n\nThe other one-qubit gates used in the circuits described below are the Hadamard\nor $H$ gate and the $T$ gate. The $H$ gate takes a qubit in one of the\ncomputational base states and places it reversibly into a ``uniform'' state ---\na state that has equal probability of resolving to a $\\ket{0}$ or a $\\ket{1}$ on\nmeasurement. The matrix for $H$ is \\[\\rot\\mat{1&1\\\\1&-1}\\] and its effect is\n\\[H\\ket{0} = \\frac{\\ket{0} + \\ket{1}}{\\sqrt{2}}\\] \\[H\\ket{1} = \\frac{\\ket{0} -\n\\ket{1}}{\\sqrt{2}}\\] It is its own inverse, so its effects can be reversed\nsimply by applying it a second time. It's interesting to note that \\[H\\ket{0} =\n\\ket{+}\\] \\[H\\ket{1} = \\ket{-}\\] \\[H\\ket{+} = \\ket{0}\\] \\[H\\ket{-} = \\ket{1}\\]\nSo another way to characterize the Hadamard gate is that it converts between\nthe computational and Bell bases.\n\nThe effects of the $T$ gate are harder to describe in an intuitive way. If the\ncomplex-valued amplitudes of a qubit are taken to represent angles of the form\n\\[a = cos(\\theta) + i sin(\\theta)\\] then the $T$ gate rotates $\\theta$ in the\n$\\ket{1}$ amplitude of the qubit $45^\\circ$ counterclockwise\\footnote{This\nrelates to a representation of qubits called the Bloch sphere, which can be\nuseful, but which I won't talk about further here.}. Its only application in the\nalgorithms discussed in this paper is to perform the quantum Fourier transform\nas part of Shor's algorithm.\n\nIn order to model interference --- the property of quantum mechanical systems\nthat the amplitudes of one qubit can affect the amplitudes of another before\nmeasurement occurs --- we need multi-qubit gates. As discussed by \\cite{bar95}\nand others, it suffices to talk about two qubit gates, since they can be used to\nconstruct gates over an arbitrary number of qubits.\n\nIn particular, we can construct arbitrary n-qubit gates using single-qubit gates\nand the two-qubit gate ``controlled-not,'' or $CNOT$. $CNOT$ has a control qubit\nand a target qubit, and its effect is to perform $X$ on the target qubit if the\ncontrol qubit is a $\\ket{1}$, and do nothing otherwise. Assuming the first qubit\nin a two-qubit ensemble is the control and the second is the target, its matrix\nrepresentation is \\[CNOT = \\mat{1&0&0&0\\\\0&1&0&0\\\\0&0&0&1\\\\0&0&1&0}\\]\n\nNow that we have introduced all of the components of a quantum circuit, we can\nstart talking about the circuits themselves. Quantum circuits, also called\nquantum gate arrays, were introduced by D. Deutsch in \\cite{deu85}. They are\nanalogous to classical boolean circuits, and analogously, they can be used to\njudge the time complexity of an algorithm. The time complexity of a quantum\ncircuit is the number of gates it contains as a function of its input size. In\naddition, we require that a family of circuits describing the algorithm for\narbitrary input sizes be constructible by a Turing machine. This allows us to\nrule out circuit families that solve uncomputable problems.\n\nGraphically, a quantum circuit looks much like a classical boolean circuit. In\nthe circuit \\[\\Qcircuit @R=.8em {\n  & \\gate{H} & \\ctrl{1} & \\gate{T} & \\qw \\\\\n  & \\gate{H} &\\targ     &\\qw       & \\qw\n}\\]\nthe gates applied are $H$, $CNOT$ with the upper qubit as control and the lower\nas target, and $T$, in that order. Time proceeds left to right along the x-axis.\nSometimes, like the Hadamards in the above diagram, gates will be applied to\nmultiple wires at the same ``time''. This is strictly for convenience of\nrepresentation. They both count toward the complexity of the overall circuit.\nAlso, many operations require extra scratch, or ``ancilla'' qubits that are not\npart of the input and that start in a known state. These to not count toward the\ninput size. A comprehensive coverage of quantum circuit complexity is provided\nin \\cite{deu85}.\n\nQuantum circuits are lacking some features of classical circuits. In particular\nfanout is impossible. The number of wires is constant throughout the circuit.\nEven using scratch qubits, it's impossible to copy the value of a qubit.\nConsider a circuit of the form \\[\\Qcircuit @R=.8em {\n  \\lstick{\\ket{x}} & \\multigate{1}{CLONE} & \\rstick{\\ket{x}} \\qw \\\\\n  \\lstick{\\ket{y}} & \\ghost{CLONE}        & \\rstick{\\ket{x}} \\qw\n}\\] The value of $y$ is lost, so this gate is not invertible. On the other hand,\nthis circuit is realizable \\[\\Qcircuit @R=.8em {\n  \\lstick{\\ket{x}} & \\multigate{1}{CLONE} & \\rstick{\\ket{x}} \\qw \\\\\n  \\lstick{\\ket{y}} & \\ghost{CLONE}        & \\rstick{\\ket{y \\oplus x}} \\qw\n}\\] and as long as we make sure that $y$ is $\\ket{0}$ to start out with, this\nhas the same effect.\n\nSimilarly, there is no way to implement an exact analog of classical $and$. On\nthe other hand, we can do this \\[\\Qcircuit @R=.8em {\n  \\lstick{\\ket{x}} & \\multigate{2}{AND} & \\rstick{\\ket{x}} \\qw \\\\\n  \\lstick{\\ket{y}} & \\ghost{AND}        & \\rstick{\\ket{y}} \\qw \\\\\n  \\lstick{\\ket{0}} & \\ghost{AND}        & \\rstick{\\ket{x \\land y}} \\qw \\\\\n}\\] This is called a Toffoli gate, and it can be implemented using $CNOT$s as\nfollows: \\[\\Qcircuit @R=.8em {\n  & \\ctrl{1} & \\targ     & \\ctrl{1} & \\ctrl{2} & \\qw \\\\\n  & \\targ    & \\ctrl{-1} & \\targ    & \\qw      & \\qw \\\\\n  & \\qw      & \\qw       & \\qw      & \\targ    & \\qw\n}\\] An $or$ gate can be constructed similarly, and along with $X$ ($not$) and\n$CNOT$ ($xor$), these can be used to construct any classical circuit. On the\nother hand, every $and$ in a classical circuit requires a scratch qubit in a\nquantum circuit. This could result in an unbounded increase in the number of\nqubits required for a computation, so quantum algorithms have to be carefully\ndesigned to reset their scratch qubits to $\\ket{0}$ between calculations so they\ncan be reused. This is frequently accomplished by performing the computation and\nthen performing its inverse, as in \\cite{sho97}.\n\nFinally, it's worthwhile to note a possibly counterintuitive property of $CNOT$:\n\\[\\Qcircuit @R=.8em {\n  & \\gate{H} & \\ctrl{1} & \\gate{H} & \\qw \\\\\n  & \\gate{H} & \\targ    & \\gate{H} & \\qw\n} \\equiv \\Qcircuit @R=.8em {\n  & \\targ     & \\qw \\\\\n  & \\ctrl{-1} & \\qw \\\\\n}\\] This is unexpected, because our description of $CNOT$ entails that it leaves\nthe control qubit unchanged. This characterization applies to ensembles in\nclassical states, however ($\\ket{00}$, $\\ket{01}$, ...). Remember that the\neffect of Hadamard is to make a qubit undetermined with respect to the\ncomputational bases but determined with respect to the Bell bases. The effect of\n$CNOT$ on an ensemble represented with respect to the Bell bases is\n\\[CNOT\\ket{++} = \\ket{++}\\] \\[CNOT\\ket{+-} = \\ket{--}\\] \\[CNOT\\ket{-+} =\n\\ket{-+}\\] \\[CNOT\\ket{--} = \\ket{+-}\\] In other words, its effect is to change\nthe first qubit when the second qubit is a $\\ket{-}$ and do nothing otherwise,\nthe exact opposite of what it does when the qubit is determined with respect to\nthe computational bases.\n\n\\section{An Example: Simon's Problem}\n\\label{sec:simon}\n\nSimon's problem is a relatively simple example of the power of quantum\ncomputing. In fact, it was published with the express interest of demonstrating\nthe potential of quantum algorithms \\cite{sim97}. The problem it solves is of\nless practical interest than integer factorization or discrete logarithm.\nNonetheless, it is thought not to be in $BPP$, whereas the quantum-computational\nsolution runs in expected polynomial time.\n\nThe problem is the following: Let \\[f:\\{0,1\\}^n \\rightarrow \\{0,1\\}^m\\] such\nthat for some constant $c$ \\[\\forall x \\not= y, f(x) = f(y) \\text{ iff } x = c\n\\oplus y\\] We wish to find $c$. Note that $f$ is an injection in the case that\n$c = 0$. Otherwise, each output of $f$ corresponds to exactly two inputs, $x$\nand $x \\oplus c$.\n\nThe corresponding decision problem --- whether the $c$ value for $f$ is within a\nspecified range --- is clearly in $NP$. The $c$ value acts as the certificate,\nand because we are guaranteed that $c$ exists, the verifier can simply\n\\begin{compactenum}\n\\item Select some $x$,\n\\item Calculate $a = f(x)$ and $b = f(x \\otimes c)$,\n\\item Return true iff $a = b$.\n\\end{compactenum} which runs in polynomial time assuming $f$ runs in polynomial\ntime.\n\nOn the other hand, there is no known decider for the problem in $P$. The naive\nalgorithm would be \\begin{compactitem}\n\\vspace{10pt}\n  \\item[] for $x$ from $0$ to $2^n$ \\begin{compactitem}\n    \\item[] for $y$ from $0$ to $2^n$ \\begin{compactitem}\n      \\item[] if $x \\not= y$ \\begin{compactitem}\n        \\item[] $a \\leftarrow f(x)$\n        \\item[] $b \\leftarrow f(y)$\n        \\item[] if $a = b$ return $x \\oplus y$\n      \\end{compactitem}\n    \\end{compactitem}\n  \\end{compactitem}\n  \\item[] return $0$\n\\vspace{10pt}\n\\end{compactitem}\n\nAssuming $c$ is non-zero, the likelyhood that $a = b$ at each\ncomparison is \\[\\frac{1}{2^{2n} - 2^n - ((x + 1)(y + 1))}\\] and it can can be\nshown that no classical probabilistic Turing machine that runs $f$ fewer than\n$2^\\frac{1}{4}$ times can correctly guess even whether $c$ is zero or non-zero \nith greater than $\\frac{1}{2} + 2^{-\\frac{n}{2}}$ probability \\cite{sim97}.\n\nThe quantum circuit for Simon's problem looks as follows, where $U_f$ finds\n$a_0,a_1,...,a_m = f(x)$ on the first $n$ qubits of the ensemble and sets\neach $b_i$ of the last $m$ qubits to $b_i = b_i \\oplus a_i$:\n\\[\\Qcircuit @R=.8em @C=.7em {\n  \\lstick{\\ket{0}_{1}}   & \\gate{H} & \\qw & \\multigate{7}{U_f} & \\qw & \\gate{H} & \\qw \\\\\n  \\lstick{\\ket{0}_{2}}   & \\gate{H} & \\qw & \\ghost{U_f}        & \\qw & \\gate{H} & \\qw \\\\\n  \\dots                  &          &     &                    &     &          & \\\\\n  \\lstick{\\ket{0}_{n}}   & \\gate{H} & \\qw & \\ghost{U_f}        & \\qw & \\gate{H} & \\qw \\\\\n  \\lstick{\\ket{0}_{n+1}} & \\qw      & \\qw & \\ghost{U_f}        & \\qw & \\qw      & \\qw \\\\\n  \\lstick{\\ket{0}_{n+1}} & \\qw      & \\qw & \\ghost{U_f}        & \\qw & \\qw      & \\qw \\\\\n  \\dots                  &          &     &                    &     &          & \\\\\n  \\lstick{\\ket{0}_{n+m}} & \\qw      & \\qw & \\ghost{U_f}        & \\qw & \\qw      & \\qw \\\\\n}\\] Only the upper $n$ qubits are measured. I provide examples below, but the\ngist is that after the second Hadamard, assuming $c \\not= 0$, the upper $n$\nqubits will contain, with equal likelyhood, exactly one of the two inputs\ncorresponding to each output\\footnote{E.g., if $f(00) = f(01) = 00$ and $f(10) =\nf(11) = 11$, the upper $n$ bits will contain a superposition of $\\ket{00}$ and\n$\\ket{10}$}. On the other hand if $c = 0$, the upper $n$ bits will be uniformly\ndistributed over $2^n$. Sampling $k$ times and solving the resulting set of\nlinear equations will give us $c$. A detailed statistical analysis of this,\nincluding a proof that the number of samples required is polynomial, can be\nfound in \\cite{sim97}.\n\nIn broad strokes, the technique here is a common approach in quantum algorithms:\n\\begin{compactenum}\n\\item Put a set of qubits into a uniform superposition.\n\\item Run some function on them and store the output, generating a uniform\n      superposition of pairs of the form $(x,f(x))$ for all possible input\n      values, $x$.\n\\end{compactenum} This is sometimes called ``quantum parallelism''. Note that\nthis does let us obtain all possible $(x,f(x))$ pairs using a single run of $f$.\nIf we measure our ensemble at this point, we'll see a single such pair, which we\ncould have obtained by simply running $f$ classically. The tricky part is using\nthis uniform superposition to give us some information about the function.\n\nTo take a minimal one-bit example, say \\[f(0) = 1\\] \\[f(1) = 0\\] In this case,\n$c = 0$. The circuit implementing Simon's algorithm for this problem description\nis simply \\[\\Qcircuit @R=.8em {\n  \\lstick{\\ket{0}} & \\gate{H} & \\ctrl{1} & \\gate{H} & \\qw \\\\\n  \\lstick{\\ket{0}} & \\qw      & \\targ    & \\qw      & \\qw \\\\\n}\\] After the first Hadamard gate, we have \\[\\frac{\\ket{00} + \\ket{10}}{\\sqrt{2}}\\]\nThe $CNOT$ takes this to \\[\\frac{\\ket{00} + \\ket{11}}{\\sqrt{2}}\\] And the final\nHadamard gives us \\[\\frac{\\ket{00} + \\ket{10} + \\ket{01} - \\ket{11}}{2}\\] Since\neach input to $f$ maps to a different output, nothing cancels, and measuring the\nfirst qubit gives us $\\ket{0}$ or $\\ket{1}$ with equal probability.\n\nOn the other hand, say $c = 1$, for example, our function might be\n\\[f(0) = f(1) = 1\\] The circuit to implement Simon's algorithm would be\n\\[\\Qcircuit @R=.8em {\n  \\lstick{\\ket{0}} & \\gate{H} & \\qw      & \\gate{H} & \\qw \\\\\n  \\lstick{\\ket{0}} & \\qw      & \\gate{X} & \\qw      & \\qw \\\\\n}\\] After the final Hadamard, our ensemble is in the state \\[\\frac{\\ket{01} +\n\\ket{11} + \\ket{01} - \\ket{11}}{2} = \\ket{01}\\] Because an output value was\nrepeated, one of our input values canceled out, and the only possible value for\nthe first qubit is $\\ket{0}$. This can be used to find $c$.\n\nIn this simple case, the outcome may seem trivial. After all, $H$ is its own\nidentity, so of course $HH\\ket{0} = \\ket{0}$. Nonetheless, this generalizes to\nfunctions with inputs of arbitrary size. Moreover, it illustrates a feature that\n\\cite{sim97} uses to characterize why quantum machines seem to be more powerful\n--- in a complexity sense --- than classical probabilistic machines:\n\nThe computation of a classical probabilistic machine can be characterized by a\ntree in which each node is a configuration. The probability of it being in\nconfiguration $a$ at step $n + 1$ is determined by its configuration at step $n$\nand the input it sees. Configurations can be duplicated at the $n + 1$st\nlevel of the tree if they are reachable from more than one configuration at step\n$n$. For each leaf, the probability of ending at that leaf is the product of the\nprobabilities along the path to that leaf, and if a configuration is duplicated\nin more than one leaf, the probability of ending in that configuration is the\nsum of those leaves' probabilities. All of the probabilities are, of course,\npositive.\n\nA quantum computation can be described by a similar tree of configurations. The\ndifference is that, until measurement is taken, each node is assigned\namplitudes, not probabilities, and these amplitudes can be negative. If a\nconfiguration is duplicated, the probability of arriving at that leaf is the\n{\\it square of the sums} of their amplitudes. This means that if one of leaf\nrepresenting configuration $c$ has amplitude $\\rot$ and another has amplitude\n$^-\\rot$, they cancel out, and the configuration is unreachable. In other words,\nthe amplitudes interfere with each other before they resolve to probabilities.\nIt's interesting to note that, if one were to measure the system after each\nstep, collapsing the amplitudes to probabilities, the result would have no more\npower than a classical probabilistic machine.\n\n\\section{Shor's Algorithm}\n\\label{sec:shor}\n\nShor's algorithm is the most famous quantum algorithm. It factors integers, a\nproblem that is not only believed not to be in $P$, but whose hardness is the\nbasis for RSA. Nonetheless, integer factorization is not $NP$ complete, and from\nthe perspective of computational complexity, its solution is no more surprising\nthan the solution to Simon's problem. I'll cover Shor's algorithm in\nsignificantly less depth than I did Simon's problem, without circuit diagrams or\nexamples. This is in part because the circuits involved in Shor's algorithm are\nquite complex, but also because the final step in Shor's algorithm involves an\nelement of Fourier analysis that I have yet to fully understand. Nonetheless,\nthe general thrust of Shor's algorithm isn't hard to grasp, and is in fact\nquite similar to the algorithm for Simon's problem.\n\nIn \\cite{sho97}, Shor presents a solution not just to integer factorization, but\nalso to the discrete logarithm problem, which is the hard problem behind the\nDiffie-Hellman cryptographic key exchange algorithm. In fact, the problem Shor\nsolves is neither of these, directly, but order-finding: determining the\nsmallest $r$ such that $x^r \\equiv 1 (\\text{mod }n)$. Such an $r$ for a\nuniformly chosen $x$ can be used to find a prime factor of $n$ with probability\ngreater than $\\frac{1}{3}$, and since the number of factors of $n$ is polynomial\nin $log(n)$, a polynomial time algorithm for order-finding equates to a\npolynomial time algorithm for integer factorization: All we need to do is choose\nvalues for $x$ and find their order until the prime factors derived can be\nmultiplied together to get $n$. A complete coverage of the number-theoretic\nfoundations of this can be found in \\cite{sho97}, but an order-finding approach\nis not unique to Shor's algorithm. It is the basis for classical factoring\nalgorithms as well.\n\nShor's algorithm can be broken up into two basic parts, one of which could\neasily be performed by a classical computer. The other two require quantum\ncomputation. The first of these is merely a quantum version of fast\nexponentiation. The algorithm is fully described in \\cite{sho97}, but it is\nidentical in most respects to the classical algorithm for performing the same\ntask. We calculate $x^y (\\text{mod }n)$, where $y$ is treated as input, and $x$\nis hard-wired into the circuit\\footnote{Thus for each new value of $x$ whose\norder we wish to find, we must create a new circuit.}.\n\nOnce we have a circuit that calculates $f(y) = x^y (\\text{mod }n)$ on $log(n)$\nqubits and sets the next $log(n)$ qubits to their original value $xor$ the\nresult, we do the following: \\begin{compactenum}\n\\item Prepare an ensemble of $2log(n)$ qubits plus scratch qubits to $\\ket{0}$\n\\item Use Hadamard gates to bring the first $log(n)$ qubits into the uniform\n      state\n\\item Apply $f$ with the first $log(n)$ qubits as control and the next $log(n)$\n      qubits as target\n\\end{compactenum} Our ensemble is now in the state\n\\[\\sum_{i = 0}^n\\frac{\\ket{i}\\ket{x^i (\\text{mod }n)}}{n^{\\frac{1}{2}}}\\] This\nvery similar to the approach taken in the algorithm for Simon's problem. Every\npair of the form $(y,f(y))$ is now stored in our ensemble with equal amplitude.\nIf we attempt to measure it at this stage, however, the amplitudes collapse to\ngive us just one of these pairs --- no more than we could have gotten with\nclassical fast exponentiation. We need some way to tease out only those values\nfor which $f(y) = 1$.\n\nThe solution to this --- and the part of the algorithm I have yet to understand\n--- involves performing quantum Fourier transform (QFT). The classical Fourier\ntransform takes as input a list of numbers representing outputs to a function\n$f$ and produces a list of coefficients to $sine$ and $cosine$ functions whose\nsum approximates $f$. This can then be used to find the periodicity of $f$. QFT\ndoes exactly the same thing, but the list taken as input and used as output is\nthe list of amplitudes to a qubit ensemble. That is, each amplitude of the\nresulting ensemble is a coefficient to a $sine$ or $cosine$ function, which\ntogether approximate the function described by the original coefficients. The\nfinal part of the algorithm, which can be performed by a classical computer, is\nto perform statistical analysis on a polynomial number of runs of the quantum\nalgorithm. The results of this are used to find the order of $x$ mod $n$ with\nprobability greater than $\\frac{2}{3}$. More detail on this process can be found\nin \\cite{sho97}.\n\n\\section{Conclusion}\n\\label{sec:conclusion}\n\nI'm a little disappointed that I failed to fully understand fully Shor's\nalgorithm. I feel like I learned a lot in the attempt, though. In general, I\nthink the answer to my original question, ``To what extent does quantum\ncomputation allow a more-than-polynomial speedup over classical algorithms, and\nwhat does that speedup entail,'' can be summed up as follows:\n\\begin{compactitem}\n\\item There is evidence, albeit inconclusive, that quantum algorithms provide\n      a fundamental algorithmic speedup in some cases.\n\\item To the extent that such a speedup exists, it can be explained by \n      interference phenomena and so-called ``quantum parallelism''. In other\n      words, it stems from the fact that at a quantum mechanical level, it seems\n      to be possible to execute a function on an exponential\\footnote{That is,\n      exponential in the number of qubits.} number of inputs at once and then\n      cause the outputs of those executions to affect the amplitudes of qubits\n      in a limited way.\n\\end{compactitem}\n\n\\begin{thebibliography}{10}\n\\label{sec:ref}\n\n\\bibitem{bar95}\nA. Barenco, C. Bennett, R. Cleve, D. DiVincenzo, N. Margolus, P. Shor, T.\n  Sleater, J. Smolin, and H. Weinfurter.\n\"Elementary Gates for Quantum Computing.\"\nIn {\\it Physical Review A.}\nMarch, 1995.\n\n\\bibitem{ber97}\nE. Bernstein and U. Vazirani.\n``Quantum complexity theory.''\nIn {\\it Siam Journal on Computing} 26(5).\n1997.\n\n\\bibitem{del07}\nC. Delgado and D. Cheung.\n``Local unitary quantum cellular automata.''\nIn {\\it Physical Review A} 76(3A).\n2007.\n\n\\bibitem{deu85}\nD. Deutsch.\n``Quantum theory, the Church-Turing principle and the universal quantum\n  computer''\nIn {\\it Proceedings of the Royal Society of London A} 400, pages 97--117.\n1985.\n\n\\bibitem{nie00}\nM. Nielsen and I. Chuang.\n{\\it Quantum Computation and Quantum Information.}\nCambridge, UK, 2000.\n\n\\bibitem{pit00}\nA. Pittenger.\n{\\it An Introduction to Quantum Computing Algrithms.}\nBirkhauser, Boston, MA, 2000.\n\n\\bibitem{sho97}\nP. Shor.\n``Polynomial time algorithms for prime factorization and discrete logarithm on a\n  quantum computer.''\nIn {\\it SIAM Journal of Computing 26.}\n1997.\n\n\\bibitem{sim97}\nD. Simon.\n``On the power of quantum computation.''\nIn {\\it SIAM Journal on Computing} 26(5).\n1997.\n\n\\end{thebibliography}\n\n\\end{document}\n\n%%% End %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n", "meta": {"hexsha": "852d368dffd06fff951b87b726acd2dd078942b0", "size": 37563, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/intro_to_quantum_circuits.tex", "max_stars_repo_name": "protoben/qsim", "max_stars_repo_head_hexsha": "9fb191c5f047f8d492b3c7ca642f5eec200990c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paper/intro_to_quantum_circuits.tex", "max_issues_repo_name": "protoben/qsim", "max_issues_repo_head_hexsha": "9fb191c5f047f8d492b3c7ca642f5eec200990c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/intro_to_quantum_circuits.tex", "max_forks_repo_name": "protoben/qsim", "max_forks_repo_head_hexsha": "9fb191c5f047f8d492b3c7ca642f5eec200990c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.2320359281, "max_line_length": 88, "alphanum_fraction": 0.7088890664, "num_tokens": 10306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3068113101982134}}
{"text": "\\section{Introduction}\nThe fact that \\gls{FRE} is uncorrelated with \\gls{TRE} is well established \n\\cite{fitzpatrick2009}. In spite of this, many students and users of clinical guidance systems struggle to \ncorrectly interpret \\gls{FRE} and residual errors in general. \n\\fred (Fiducial Registration Educational Demonstrator)\n \\cite{stephen_thompson_2021_4462897} was developed using the \n\\sksurgery \\cite{PMID:32436132} libraries to probe the causes of misconceptions \nabout \\gls{FRE} and \\gls{TRE}. \\fred supports online learning and provides tools to enable \nresearch into user interface design for image guidance systems. \n\nFaced with the need to deliver teaching and research remotely during 2020's {SARS-CoV-2}\\cite{PMID:32123347}\ntravel restrictions, we \ndeveloped a new online tutorial\\footnote{\\href{https://mphy0026.readthedocs.io/en/latest/summerschool/registration_demo.html}{https://mphy0026.readthedocs.io/en/latest/summerschool/registration{\\textunderscore}demo.html}}\non fiducial based registration. The tutorial utilises \\fred which is now implemented as a browser based web-app. \n\\fred can be accessed on-line\\footnote{\\href{https://scikit-surgeryfred.ew.r.appspot.com/}{https://scikit-surgeryfred.ew.r.appspot.com/}} or deployed locally.\nRather than simply telling the students that \\gls{FRE} is uncorrelated with \\gls{TRE} \nwe decided it would be more effective to use divergent questioning strategies\\cite{Tofade155} within the application, analysis, synthesis and \nevaluation levels of Bloom's taxonomy \\cite{blooms_tax}: hence the question posed within the title of this paper. \n\nWe also took the opportunity to develop a serious game based on \\fredns. \nSerious games are games designed to be engaging to play, whilst setting out to achieve an objective\nbeyond pure entertainment. In the case of \\fredns, the objective is to gather data on how clinical \ndecision making might be influenced by the communication of registration errors. \nSerious games have significant potential \nas a training tool for clinicians \\cite{PMID:28133947, serious-needle}. Serious games have also been shown to be \nuseful in assessing the usability of human computer interfaces \\cite{hci_games}, which is of particular\nrelevance to computer aided surgery. The results of the game indicate that the choice of error statistic shown can affect clinical decision making.  \n\nIn this paper we introduce the \\fred application and show how it can\nbe used as an educational tool and to perform studies to measure registration and \nablation performance. By default \\fred\nimplements \\gls{FLE} as an isotropic, normally distributed, independent variable. \nIn this paper we show how \\fred can be modified to implement anisotropic and \nsystematic errors, and present the results of these modifications. \nIt is our plan to build on \nthe software to perform larger studies; to investigate more realistic models of \\gls{FLE};\nto investigate other registration approaches; and other ways of communicating registration error. \n\\fred is entirely open \nsource software and we encourage researchers and educators to use and contribute to it. \n\n", "meta": {"hexsha": "c37ab46eb24c181cff82a32dbf85577a22094494", "size": 3121, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "introduction.tex", "max_stars_repo_name": "SciKit-Surgery/scikit-surgeryfred-paper", "max_stars_repo_head_hexsha": "bc72551650facf1adf0e5954810f6ac2aec81080", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "introduction.tex", "max_issues_repo_name": "SciKit-Surgery/scikit-surgeryfred-paper", "max_issues_repo_head_hexsha": "bc72551650facf1adf0e5954810f6ac2aec81080", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "introduction.tex", "max_forks_repo_name": "SciKit-Surgery/scikit-surgeryfred-paper", "max_forks_repo_head_hexsha": "bc72551650facf1adf0e5954810f6ac2aec81080", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 76.1219512195, "max_line_length": 221, "alphanum_fraction": 0.807753925, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.30677095106660357}}
{"text": "\\section{Results for SWR detection}\n\\label{sec:RNN-results}\n\nThe first GRU network that we analyzed used all 16 input LFP channels, had 2 layers of 40 hidden units each, and was trained on a target function $y_t$ that is $1$ during the entire duration of each reference SWR segment, and $0$ elsewhere. \\Cref{fig:validloss} shows the evolution of the validation loss while training this RNN. \\Cref{fig:RNN-envelopes} shows example output envelopes $n_t$.\n\n\\begin{figure}\n\\img[0.6]{575_4--576_0}\n\\img[0.6]{589_8--590_4}\n\\captionn{RNN output envelopes}{Output of a trained GRU-RNN that uses all input channels and that has two hidden layers of 40 hidden units each. See \\cref{fig:BPF-outputs} for legend.}\n\\label{fig:RNN-envelopes}\n\\end{figure}\n\nWe notice that the RNN output matches the target block-shaped function $y_t$ relatively well. Together with the validation loss curve, it seems that the target function was relatively well learnable.\n\nSecondly, the RNN clearly uses more information than the ripple oscillation only to generate its output. In the right panel of \\cref{fig:RNN-envelopes}, the RNN outputs a positive with high confidence. The low frequency LFP over all channels indeed has the profile of an SWR; but the ripple is almost non-existent, as can be seen in the band-pass and GEVec filter outputs. This detection of the RNN is thus classified as a false positive. Additional examples of this phenomenon are shown in \\cref{fig:RNN-profile}.\n\n% The fact that the trained RNN seemingly uses the low frequency spatiotemporal pattern of SWR's leads to a correct and early detection in the left panel of \\cref{fig:RNN-envelopes}, but a correct and relatively late detection in the right panel; this might be because the negative sharp wave only starts after the ripple oscillation has already begun.\n\nThis phenomenon, where the RNN seemingly uses the low frequency spatiotemporal pattern of SWR's but does not require clear ripples, leads to a low precision for the RNN detector, under our evaluation scheme. \\Cref{fig:RNN-PR} compares the precision-recall curve of this RNN detector with those of previous online SWR detectors, as well as comparing their detection latencies.\n\n\\begin{figure}\n\\img[0.9]{PR_full_fullrect}\\\\[2.5em]\n\\img[0.9]{PR_fullrect}\n\\captionn{Online SWR detection performance of an RNN}{See \\cref{fig:BPF-performance} for legend. \\Top: Full PR-curve. \\Bottom: zoom-in on high-recall/high-precision region. Same net as \\cref{fig:RNN-envelopes}.}\n\\label{fig:RNN-PR}\n\\end{figure}\n\nThe detection thresholds in \\cref{fig:RNN-envelopes} are chosen at the maximal $F_1$ point for each output envelope. Because of the relatively low precision (high false-positive rate) of the RNN, this threshold is set high for the RNN envelope. This leads often to relatively late detections; see e.g. the rightmost detection in \\cref{fig:RNN-envelopes}.\n\nTo investigate the influence of input channels, we trained a GRU-RNN that only used a single input channel (namely the pyramidal cell layer channel that is also used as input for the band-pass filters). The resulting RNN behaves very much like the band-pass filter (\\cref{fig:RNN-pyr-envelopes}). It does not show the non-ripple false positive detections of the all-channel RNN. Its detection performance approaches, but is not as good as the baseline online band-pass filter (\\cref{fig:RNN-PR-pyr}).\n\nA second net was trained on this single channel input, this time with only one hidden layer, of 25 hidden units. Its performance was slightly worse than the two-layer, 40 hidden units per layer RNN (\\cref{fig:RNN-PR-pyr}).\n\nFinally, we experimented with a different target function; Namely a $y_t$ that is $1$ only around the start of reference SWR segments. This did not result in good performance for all-channel, two-layer, 40 hidden unit RNN's (\\cref{fig:RNN-PR-startblocks}).\n", "meta": {"hexsha": "b72356f7d05659c49ce5e8ed68f8ef2d3c7020e3", "size": 3850, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "modules/RNN/Results.tex", "max_stars_repo_name": "tfiers/master-thesis", "max_stars_repo_head_hexsha": "3e97128eeb18827b03da90817fe6f6985c84ad80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-23T01:39:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-23T01:39:24.000Z", "max_issues_repo_path": "modules/RNN/Results.tex", "max_issues_repo_name": "tfiers/master-thesis", "max_issues_repo_head_hexsha": "3e97128eeb18827b03da90817fe6f6985c84ad80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46, "max_issues_repo_issues_event_min_datetime": "2018-09-18T16:38:12.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-10T22:37:35.000Z", "max_forks_repo_path": "modules/RNN/Results.tex", "max_forks_repo_name": "tfiers/master-thesis", "max_forks_repo_head_hexsha": "3e97128eeb18827b03da90817fe6f6985c84ad80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 110.0, "max_line_length": 514, "alphanum_fraction": 0.785974026, "num_tokens": 993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.3067709510666035}}
{"text": "\\documentclass[]{article}\n\n\\usepackage{graphicx}\n%times,palatino,bookman, palatino, newcent\n\n\\usepackage{geometry}\n \\geometry{ a4paper, total={210mm,297mm},\n left=25mm,\n right=25mm,\n top=20mm,\n bottom=20mm,\n }\n\n\n\\begin{document}\n\n\\title{Synple User's Guide}\n\n\\date{\\today}\n\\author{C. Allende Prieto, I. Hubeny, T. Lanz, Y. M. Osorio}\n\n\\maketitle\n\n{\\tt Synple} is a Python interface to the spectral synthesis code Synspec\nand a set of related utilities. Synple can compute emerging spectra from LTE Kurucz, \nMARCS, Phoenix or Tlusty model atmospheres, as well as NLTE Tlusty models. Appropriate \ndefault choices for the continuum and line opacities are provided, while the chemical \nabundances and micro-turbulence velocity are taken from the input model atmospheres, but\ncan be changed as needed.\n\n\\tableofcontents\n\n\\newpage\n\n\\section{Introduction}\n\\label{intro}\n\nThe computation of detailed stellar stellar spectra is a basic but important step required for the analysis of star light,  spectra of integrated stellar populations, or transiting planets. The calculations involve solving the equation of radiative transfer\n\\begin{equation}\n\\cos \\theta \\frac{d I_{\\nu} (\\theta)}{dz} = \\eta_{\\nu} - \\kappa_{\\nu}  I_{\\nu} (\\theta) + \\int_0^{\\pi} I_{\\nu} (\\theta') \\phi (\\theta') \\sin \\theta' d\\theta',\n\\end{equation}\n\\noindent where $I_{\\nu}$ is the specific intensity, and describes the radiation field (radiative energy per unit of frequency propagating at an angle $\\theta$ from the vertical traversing a unit area per unit time), $\\kappa$ is the opacity (fraction of energy absorbed per unit length), $\\eta$ the emissivity (energy emited, same units as the intensity) and $\\phi$ represents the scattering function (photons scattered from the direction $\\theta$' into the direction $\\theta$. \n\nOnce $I_{\\nu}$ ($\\theta$) is known, it can be integrated to derive the stellar flux\n\\begin{equation}\nH_{\\nu} = \\int_0^{\\pi} I_{\\nu} (\\theta) \\cos \\theta \\sin \\theta d\\theta\n\\label{flux}\n\\end{equation}\n\\noindent which can be finally convolved with various kernels that describe large-scale atmospheric turbulence, rotation, or the instrumental profile.\n\nPrior to solving the equation of radiative transfer, one requires a physical model of the stellar atmosphere in order to compute $\\eta$, $\\kappa$ and $\\phi$. This is the running of the thermodynamical quantities (e.g temperature and density) with height, as well as the chemical composition. This input {\\it model atmosphere} is the sole required input to Synple.  Of course, computing a detailed spectrum requires fundamental physical data on the interaction of matter and radiation (photoionization cross-sections, atomic and molecular transition probabilities and damping constants, etc), but a generic collection of such data is included in Synspec, in a standard format that allows easy modifications when  needed.\n\nMultiple codes for radiative transfer exist and are publicly available. However, most require deep knowledge of the related physics and are cumbersome to use. Synple provides an easy-to-use Python interface for the fast computation of model stellar spectra with accuracy and flexibility.\n\nSynple is simply a wrapper to the FORTRAN code synspec (Hubeny \\& Lanz), and inherits all the physical approximations adopted by synspec: a plane parallel geometry and hydrostatic equilibrium. The input model atmospheres can be in LTE (Kurucz, MARCS, Tlusty or Phoenix models) or in NLTE (Tlusty). The generic physical data included with Synple will be appropriate for most stars, but not all. Users must be aware that such data are also required to compute the  input model atmospheres, and in general those used for that task will be inconsistent with those adopted in Synple.  By default the chemical composition and micro-turbulence adopted for the construction of the input model atmospheres will also be adopted by synple, but those can be changed by the user, at the risk of incurring in larger (and significant) inconsistencies.\n\n\\section{Installing}\n\nSynple is hosted in github at https://github.com/callendeprieto/synple\nand can be obtained using {\\tt git} \n\\\\ {\\tt git clone https://github.com/callendeprieto/synple synple} \\\\\n\\noindent or by downloading a zip file from the website.\n\nYour Python (3.x) installation  will require the packages {\\tt subprocess}, {\\tt numpy}, and {\\tt scipy}, usually obtained with {\\tt pip} (e.g. {\\tt pip3 install numpy}). You probably want to install ipython and matplotlib as well, since we will be using that in the examples below. \n\nThe installation requires a FORTRAN compiler, and the GNU compiler is used by default\n\\\\ {\\tt cd synple/synspec ; make ; cd ../..}.\n\nThe atomic and molecular line lists are sizable and need to be downloaded separately\n\\\\ {\\tt cd synple/linelists ; make ; cd ../..} \\\\\n\\noindent where the automated download requires that {\\tt wget} is available in your system, otherwise download the line lists manually from \\\\ {\\tt ftp://carlos:allende@ftp.ll.iac.es/linelists} and copy them to the synple/linelists directory.\n\nYou need to make synple visible to Python by including the synple directory in your PYTHONPATH variable. Say you've placed the synple parent directory in your home, then you can add it in the linux shell by typing (or including in your .bashrc or .cshrc files)\n\\begin{table}[h]\n\\begin{tabular}{ll}\nbash: & export PYTHONPATH=\"\\$PYTHONPATH:\\$HOME/synple\"  \\\\\ncsh:  & setenv PYTHONPATH = \"\\$PYTHONPATH:\\$HOME/synple\" .\n\\end{tabular}\n\\end{table}\n\nThe set of atomic and molecular line lists provided with synple v1.1 and above is sizeable, requiring at least 12 GB. For that reason some users may prefer to install synple in a location other than their home directory, and the PYTHONPATH must be set accordingly.\n\nFor many purposes it suffices to use the smaller line lists provided with v1.0, which will take less than 1 GB. To do so users should replace the {\\tt make} command run in the linelists folder by {\\tt make old}. \n\n\\section{Examples}\n\nOnce synple is installed, all you need is a model atmosphere to being using it. In this section we'll include a set of simple practical examples, mainly based on the three model atmospheres included in the synple/models directory: one is a solar Kurucz model ('ksun.mod'), one is a solar MARCS model ('msun.mod'), and the third is a Phoenix model for Vega-like A-type star ('lte09600-4.00-0.0.PHOENIX-ACES-AGSS-COND-2011.ATMOS.fits') from Huser et al. (20xx).\n\n\n\\subsection{Computing your first solar spectrum}\n\\label{6162}\n\n\n\\begin{figure}[t!]\n\\centering\n\\includegraphics[width=14cm]{Figure_1.ps}\n\\caption{Here's your first spectrum with synple. You have modeled the solar spectrum in the vicinity of the Ca I $\\lambda$6162 line. The Ca I line is the strong line at the center, visibly damped by collisions with hydrogen atoms.\n\\label{first}\n}\n\\end{figure}\n\n\nFor this exercise we'll use the Kurucz solar model included with synple. We're going to compute a piece of the spectrum around the Ca I $\\lambda$6162 line. We start ipython and import the standard synthesis routine {\\tt syn} from synple\n\\\\\n\\\\\n\\noindent {\\tt \n\\$ ipython \\\\\nPython 3.6.8 (default, Jan 14 2019, 11:02:34) \\\\\nType 'copyright', 'credits' or 'license' for more information \\\\\nIPython 7.4.0 -- An enhanced Interactive Python. Type '?' for help. \\\\\n\\\\\nIn [1]: from synple import syn                                            \\\\      \n}\n\n\\noindent then request the computation of the spectrum from the model atmosphere in the file {\\it ksun.mod} between 6160 and 6164 \\AA\\\n\\\\\n\\\\\n\\noindent {\\tt \nIn [2]: wave, flux, cont = syn('ksun.mod', (6160,6164) )                     \\\\    \nteff,logg,vmicro= 5777.0 4.437 2.0 \\\\\nsyn ellapsed time  48.8003294467926 seconds \\\\\n}\n\n\\noindent We've got it! The routine {\\tt syn} returns three numpy arrays with the wavelengths (wave), the fluxes (flux; $H_{\\lambda}$), and the continuum flux (cont). If we wish to visualize the continuum-normalized spectrum, we can use matplotlib\n\\\\\n\\\\\n\\noindent {\\tt \nIn [3]: \\%pylab                                               \\\\                   \nUsing matplotlib backend: TkAgg \\\\\nPopulating the interactive namespace from numpy and matplotlib \\\\\n\\\\\nIn [4]: plot(wave,flux/cont)                                     \\\\   \n}\n\n\\noindent and that's it! You should be looking at your first computed spectrum and it should look like the one in Fig. \\ref{first}. In addition to the run with height of the thermodyanical quantities, the model atmosphere contains a detailed description of the chemical abundances and the micro-turbulence velocity (see below). These parameters are simply adopted from the model atmosphere, but can be changed if needed, as described in the next section.\n\n\\subsection{Altering micro-turbulence and chemical composition}\n\\label{abundances}\n\n\\begin{figure}[t!]\n\\centering\n\\includegraphics[width=7cm]{Figure_2a.ps}\n\\includegraphics[width=7cm]{Figure_2b.ps}\n\\caption{Repeating the calculation in Fig \\ref{6162} (blue) but adding a second curve (orange) on the left panel reducing the micro-turbulence from 2 to 1 km s$^{-1}$, and on the right-hand panel increasen the Ca abundance by 0.2 dex.\n\\label{micro-abu}\n}\n\\end{figure}\n\n\nThe model atmospheres we deal with are in hydrostatic equilibrium, and therefore pressure and gravity are in balance, so everything is at rest. This is unrealistic. Real stellar atmospheres have turbulence, shocks, convection, meridional circulation, etc. Thus, the computed line profiles are narrower than observed. One of the patches to address this problem is the so-called micro-turbulence velocity, which accounts for small-scale velocities of the absorbing particles. This includes small scale turbulence, and needs to be included in the computation of the linel absorption profile at the microscopic level, before solving the radiative transfer equation.\n\nSynple includes micro-turbulence in the spectrum calculations automatically, if that's indicated in the model atmosphere file, but that value can be overridden by explicitly indicating it when calling the synthesis routine {\\tt syn} using the parameter {\\it vmicro}.\n\nLet's repeat the example in \\S \\ref{6162} changing the micro-turbulence from the value used to construct the solar Kurucz model we used, 2 km s$^{-1}$, to a more reasonable value for a solar-like star of 1 km s$^{-1}$\n\\\\\n\\\\\n\\noindent {\\tt \nIn [5]: wave2, flux2, cont2 = syn('ksun.mod', (6160,6164), vmicro = 1. )   \\\\    \nteff,logg,vmicro= 5777.0 4.437 1.0 \\\\\n}\n\n\\noindent which can be easily compared with the previous calculation \n\\\\\n\\\\\n\\noindent {\\tt \nIn [6]: plot(wave2,flux2/cont2)                          \\\\                       \n}\n\n\\noindent as illustrated in the left-hand panel of Fig. \\ref{micro-abu}. The weak, unsaturated, lines, and the core of the strong Ca I $\\lambda$6162 line, are less broadened (brown curve) after reducing the micro-turbulence, while the damping wings of strong lines are insensitive to this parameter.\n\nSimilarly to the micro-turbulence, the chemical abundances can be changed from those used in the construction of the model atmosphere when computing the detailed spectrum. Since the most direct effect of the change of the abundance of an element (other than hydrogen) in the atmosphere is on the strength of its spectral lines, this is usually a good approximation for most elements and for reasonably small changes in abundances. But many elements, especially the most abundant ones, affect the thermodynamics of the atmosphere, and therefore for those elements this is a risky approximation to make. On the other hand, the approximation is very good for trace elements.\n\nTo supersede the abundances in the model atmosphere we can call {\\tt syn} with the keyword {\\it abu}. The abundances are expressed as the number density of nucleii of the elements relative to that of hydrogen\n\\begin{equation}\n\\epsilon (X) = \\frac{N(X)}{N(H)}.\n\\end{equation}\n\nLet's read the ones in the model atmosphere and then increase the calcium abundance by 50\\% (0.2 dex) \n\\\\\n\\\\\n\\noindent {\\tt \nIn [7]: from synple import read\\_model \\\\\nIn [8]: atmostype, teff, logg, vmicro, abu, nd, atmos = read\\_model('ksun.mod') \\\\\nIn [9]: abu[19] = abu[19] * 1.5 \\\\\nIn [10]: wave3, flux3, cont3 = syn('ksun.mod', (6160,6164), vmicro = 1. , abu=abu )   \\\\    \nteff,logg,vmicro= 5777.0 4.437 1.0. \\\\ \nIn [11]: clf() \\\\\nIn [12]: plot(wave2,flux2/cont2, wave3, flux3/cont3).\n}\n\\\\\n\\\\\nThis calculation is shown in the right-hand panel of Fig. \\ref{micro-abu}, and it reveals that there are three Ca I lines in the computed spectral segment. \n\n\n\\subsection{Additional line broadening}\n\\label{fwhm}\n\n\\begin{figure}[t!]\n\\centering\n\\includegraphics[width=14cm]{Figure_3.ps}\n\\caption{Repeating the calculation in Fig \\ref{6162} (blue) but adding the result of a convolution with a rotational profile for $v \\sin i = 5$ km s$^{-1}$ (orange), a Gaussian kernel with a FWHM of 0.2 \\AA\\ (green), and both (brown).\n\\label{convolution}\n}\n\\end{figure}\n\nThe spectral lines in a computed spectrum are naturally broadened due to the uncertainty principle, micro-turbulence (see Section \\ref{abundances}), the thermal velocities of the absorbing atoms and molecules, and the collisions they suffer with surrounding free electrons and hydrogen atoms.  All these broadening factors are included in the calculations done as described in the previous exercise, but there are additional sources of uncertainty that may be significant for your particular application.\n\n\\begin{itemize}\n\\item \\underline{macro-turbulence}: while the {\\it micro} takes care of small-scale velocity fields by introducing broadening at the microscopic level, broadening the line profiles at each atmospheric layer, there are velocities on scales much larger than the photon mean free-path that need to be taken into account by convolution of the computed spectrum. This is usually taken into account by convolving with a Gaussian velocity kernel, or with a radian-tangencial profile (see Gray xxxx). Synple implements convolution with a Gaussian velocity field in the routine {\\tt vgconv}.\n\\item \\underline{rotation}: stellar rotation broadens the spectral profiles. To be exact this has to be taken into account numerically, by Doppler-shifting the intensity contributions from different angles ($\\theta$) in Eq. \\ref{flux}. Nevertheless the effect or rotation can be well approximated by a covolution of the flux computed for no rotation with a particular kernel (see Gray xxxx). This is implemented in Synple in the routine {\\tt rotconv}.\n\\item \\underline{instrumental profile}: Instruments distort the stellar spectrum by convolving it with the instrumental profile. If the resolving power is constant, this can be usually approximated as a macro-turbulence, with a Gaussian kernel with a constant width in velocity space. Sometimes is the resolution, the FWHM in wavelength of the response of the instrument to a monochromatic source, what is constant, and the instrumental profile can be handle in Synple with the routine {\\tt lgconv}.\n\\end{itemize}\n\n\\begin{figure}[t!]\n\\centering\n\\includegraphics[width=14cm]{Figure_4.ps}\n\\caption{In addition to the original calculation in Fig. \\ref{6162} (blue line), we show the result of the convolution with a rotational profile for $v \\sin i = 5$ km s$^{-1}$ and a Gaussian kernel with a FWHM of 0.2 \\AA\\ using {\\tt rotconv}{\\tt lgconv} (green) and rotin (orange).\n\\label{rotin}\n}\n\\end{figure}\n\n\nThe following example demonstrates how to convolve with a rotational profile ($vsini = 5. $ km s$^{-1}$), a Gaussian profile with a constant resolution FWHM = 0.2 \\AA\\, and both, the original calculation in \\S \\ref{6162}\n\\\\\n\\\\\n\\noindent {\\tt \nIn [13]: from synple import rotconv, lgconv \\\\\nIn [14]: wave2, flux2 = rotconv(wave, flux/cont,  5.) \\\\\nIn [15]: wave3, flux3 = lgconv(wave, flux/cont, 0.2) \\\\\nIn [16]: wave4, flux4 = lgconv(wave2, flux2,  0.2) \\\\\nIn [17]: clf() \\\\\nIn [18]: plot(wave, flux/cont, wave2,flux2, wave3, flux3, wave4, flux4).\n}\n\\\\\n\\\\\n\n\\noindent Note that the spectral range of the output spectrum is truncated in wavelength, since it is computed only for the frequencies with information in the original calculation. \n\n\nThese routines for convolution are directly implemented in Python. Synspec has a companion FORTRAN program that handles the convolution with the instrumental or rotational profiles: rotin. One can use this program by including the {\\it fwhm} and {\\it vrot} parameters when calling {\\tt syn} as in the following example\n\n\\noindent {\\tt\nIn [19]: wave2, flux2, cont2 = syn('ksun.mod', (6160,6164) , vrot = 5.0, fwhm = 0.2 ) \\\\\nIn [20]: clf() \\\\\nIn [21]: plot(wave, flux/cont, wave2, flux2/cont2, wave4, flux4)\n}\n\\\\\n\\noindent Note the different behaviour for rotin (orange curve in Fig. \\ref{rotin}), which does not trim the edges of the computed spectrum, and {\\tt lgconv}/{\\tt rotconv} (green). Rotin does not include convolution with a Gaussian kernel with a constant width in velocity, implemented in {\\tt vgconv}. \n\n\\subsection{Multiple models}\n\nOne often fases the need to compute the spectra for multiple models. Since the sampling of frequencies is internally control within synspec, it become desirable to force the output fluxes to be on the same wavelength grid, and this can be controlled with the parameter {\\it dw} in the routine {\\tt syn}.\n\nWhen using synple, by default value for the variable {\\tt modeldir} points to the folder {\\tt models} inside you {\\tt synple} parent directory. If the model atmospheres are in your working directory, or as in the first examples below, the models are in the {\\tt models} folder, that's ok, but if you want to use models elsewhere you will need to change {\\tt modeldir} to point to the right path (changing the source code in synple.py) or simply passing the complete filenames, including an absolute path.\n\n\n\\begin{figure}[t!]\n\\centering\n\\includegraphics[width=14cm]{Figure_5.ps}\n\\caption{We now use all the models in the 'modeldir' directory in one command, with multiple values of the micro, using {\\tt multisyn}.\n\\label{rotin}\n}\n\\end{figure}\n\n\nIf you have a bunch of models you want to compute spectra for, or multiple values of vrot, fwhm, or vmicro, you can wrap around the routine syn, or you can use the macro {\\tt multisyn}, after setting the file names in a list like  in this example\n\n\n\\noindent {\\tt\nIn [22]: from synple import multisyn \\\\\nIn [23]: import glob \\\\\nIn [24]: import os.path \\\\\nIn [25]: modeldir = \"/home/callende/synple/models\" \\\\\nIn [26]: models = glob.glob(os.path.join(modeldir,\"*mod\"))  \\#get the models in a list \\\\\nIn [27]: wave5, flux5, cont5 = multisyn(models, (6160,6164), vmicro = [1.,2.,4.] ) \\\\\nIn [28]: clf() \\\\\nIn [29]: for i in range(len(models)): plot(wave5, flux5[i,:]/cont5[i,:])\\\\\n\\\\\n}\n\\\\\n\n\\noindent and the wavelength array will now be common to all spectra, and the flux and cont arrays returned will be two-dimensional, with the first dimention running along the models in the input list.\n\n\\section{References}\n\n\\begin{itemize}\n\\item Allende Prieto, C., Fern{\\'a}ndez-Alvar, E., Schlesinger, K.~J., et al.\\ 2014, A\\&A, 568, A7 \n\\end{itemize}\n\n\\end{document}\n\n", "meta": {"hexsha": "18a68d9be51c6c59307abe5bd8ce453ca5b20f8c", "size": 19117, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/synple.tex", "max_stars_repo_name": "callendeprieto/synple", "max_stars_repo_head_hexsha": "4e3611db5568633da3053be87cfc5213a86b2a26", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-07-09T16:47:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T20:37:15.000Z", "max_issues_repo_path": "docs/synple.tex", "max_issues_repo_name": "callendeprieto/synple", "max_issues_repo_head_hexsha": "4e3611db5568633da3053be87cfc5213a86b2a26", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/synple.tex", "max_forks_repo_name": "callendeprieto/synple", "max_forks_repo_head_hexsha": "4e3611db5568633da3053be87cfc5213a86b2a26", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-03-13T10:44:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-08T09:53:10.000Z", "avg_line_length": 65.4691780822, "max_line_length": 836, "alphanum_fraction": 0.7491238165, "num_tokens": 4868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.3067436087240035}}
{"text": "% !TeX root = ../thesis.tex\n% !TeX spellcheck = en_GB\n% !TeX encoding = UTF-8\n\n\nMathematics and finance have been intricately linked since the inception of human civilisations. In the span of the last two millennia, many mathematicians -- from Thales of Greece to Fibonacci, Pascal, Fermat and Bernoulli -- have tried to apply their knowledge to the domain of finance\\footnote{Significant portions in this introductory section have been taken verbatim from the paper \\cite{Akyildirim2014}}. However, Louis Bachelier's thesis “Théorie de la Spéculation” (Theory of Speculation) in 1900 arguably marked the birth of modern mathematical finance. Bachelier is credited with being the first person to derive the mathematics of Brownian motion and to apply its trajectories for modelling stock price dynamics and calculating option prices.\n\nOne of the most exciting innovations in the modern history of mathematical finance is rooted in the discovery of the Brownian motion by Scottish botanist Robert Brown. In 1827, he observed rapid oscillatory motion of microscopic particles in a fluid resulting from their collision with atoms or molecules in the fluid. However, Bachelier was the first to define Brownian motion mathematically, and used the one dimensional version $ t \\mapsto B_t, t \\ge 0 $ to model stock price dynamics. Norbert Wiener laid down the rigorous mathematical foundation of Browian motion, hence the parallel name of Wiener process is also used for Brownian motion. He proved the existence of Brownian motion, and constructed the Wiener measure which describes its probability distribution.\n\nIn 1933, in the seminal book “Foundations of the Theory of Probability”, Kolmogorov laid the foundation of modern Probability theory from fundamental axioms. His work relied heavily on Lebesgue's Measure Theory, and united the previously disparate areas of probability -- discrete and continuous -- into a unified theory that could be applied to both. It is in this book that he introduced the ideas of conditional expectation and equivalent measures.\n\nAnother breakthrough in Probability theory came in 1941, when in his attempts to model Markov processes, Kiyosi Itô (in his famous 1942 paper “On stochastic processes”) constructed stochastic differential equations of the form $ \\dif X_t = \\mu(X_t) \\dif t + \\sigma(X_t) \\dif B_t $, where $ B_t $ is a standard Brownian motion. He introduced the theory of integration over a Brownian motion, and in 1951 gave a formula for constructing new stochastic differntial equations from existing ones (Itô's lemma), giving birth to Itô calculus. Itô's lemma is one of the most widely used mathematical formula by financial engineers today.\n\nAt this crucial juncture, when the probability theory was ripe enough, in 1973, Fischer Black and Myron Scholes published the paper “The Pricing of Options and Corporate Liabilities”, and Robert Merton published the paper “On the pricing of corporate debt: the risk structure of interest rates”. These papers together introduced a new methodology for the valuation of financial instruments and in particular developed the Black–Scholes model for pricing European call and put options. At the same time, another breakthrough on the industry side was the foundation of the Chicago Board Options Exchange to become the first marketplace for trading listed options. Even beyond the imagination of the celebrated authors above, the market was so quick to adapt these models. By 1975, almost all traders were valuing and hedging option portfolios by using the Black–Scholes model built in their hand calculators.\n\nBut there were problems with the Black and Scholes model. A primary disadvantage was that the esoteric theory was not understandable by most practitioners in the field of finance. Moreover, it could not be used to price all kinds of options. In 1979, Cox, Ross and Rubinstein introduced a discrete model, which is much more approachable, and yet has the flexibility to price almost all kinds of derivatives. Yet, the exponential nature of the complexity forbids scaling up the number of levels of the tree to any significant value, reducing its utility.\n\nIn this chapter, we briefly discuss some fundamental ideas in finance. We shall follow this up with a discussion on the two models mentioned.\n\n\n\\section{Financial instruments}\n\\label{sec:intro-assets}\n\nA \\emph{financial instrument} or a \\emph{financial asset} is an intangible asset whose value is derived from a contractual claim, such as bank deposits, bonds, stocks and derivatives. Financial assets are usually more \\emph{liquid} than other tangible assets, such as commodities or real estate, and may be traded on financial markets. Every financial asset is characterised by its return. When the return is deterministic, we call it a \\emph{risk-free} or \\emph{riskless} asset. When the return is contingent on the market and external conditions, it is called \\emph{risky}. It must be kept in mind that no instrument is fundamentally risk-free, it has only negligible risk compared to its risky counterparts.\n\n\n\n\\subsection{Return on an asset}\n\\label{subsec:intro-assets-return}\n\n\\subparagraph{Notation} We will use a zero in the superscript to denote the riskless asset. For example, $ S_t^0 $ denotes the price of the riskless asset at a time $ t $. On the other hand, the absence of a zero (or presence of another index) in the subscript means that we are referring to a risky asset.\n\n\\paragraph{Return on a riskless asset -- Compounding}\nCompounding is the first idea that we must be familiar with. Essentially, a riskless asset will increase in monetary value in a deterministic manner if we keep it in the market. The increase depends on the compounding frequency and the duration of investment. The term compounding is used because the interest earned in each period also contributes to the principal in the successive periods.\n\nLet the compounding frequency is $ n $ times per year, the total time is $ t $, and the annual rate of interest is $ r $. Then\n\\begin{equation}\n\t\\label{eq:intro-compounding-discrete}\n\tS_t^0 = S_0^0 \\left(1 + \\frac{r}{n} \\right)^{\\floor{nt}},\n\\end{equation}\nwhere $ S_0^0 $ is the starting value of the asset, and $ S_t^0 $ is the value of the asset at time $ t $, and $ \\floor{\\cdot} $ represents the floor function.\n\nIf the compounding is continuous, we let $ n \\to \\infty $ to obtain\n\\begin{equation}\n\t\\label{eq:intro-compounding-continous}\n\tS_t^0 = S_0^0 e^{rt}.\n\\end{equation}\n\n\n\\paragraph{Return on a risky asset}\nAt any point of time in the future, the value of a risky asset is not known with certainty, so it is a random variable taking values in $ [0, \\infty) $. Since the values change with time, we denote the \\emph{spot price} of a risky asset by the stochastic process\\footnote{\\url{https://en.wikipedia.org/wiki/Stochastic_process}} $ (S_t)_t $, where $ t \\in [0, T] $ denotes the time, $ T $ being the maturity. Since the future value of the asset is adventitious, we use the following metrics to measure the return of the risky asset in the given time interval.\n\n\\begin{dfn}[absolute and relative returns]\n\tThe absolute return on an asset for the time interval $ [0, t], \\  t \\in [0, T] $ is given by\n\t\\begin{equation*}\n\t\t\\tilde{R}_t = S_t - S_0 ,\n\t\\end{equation*}\n\twhile the relative return on the asset is given by\n\t\\begin{equation*}\n\t\tR_t = \\frac{S_t - S_0}{S_0} .\n\t\\end{equation*}\t\n\\end{dfn}\n\nIt must be noted that relative return is usually a better indicator of the return on an asset as compared to its absolute equivalent. This may be illustrated better by the following example.\n\\begin{eg}[relative vs absolute return]\n\tLet A and B be two assets. Let their values at $ t = 0 $ be $ S_0^A = 5 $ and $ S_0^B = 10 $, respectively. At time $ t = 1 $ one observes that the prices have become $ S_1^A = 10 $ and $ S_1^B = 15 $.\n\t\n\tThe absolute return on both assets are equal to $ 5 $ here. On the other hand, the relative returns are:\n\t\\begin{align*}\n\t\tR_1^A  &=  \\frac{S_1^A - S_0^A}{S_0^A} = \\frac{5}{5} = 1  \\\\\n\t\tR_1^B  &=  \\frac{S_1^B - S_0^B}{S_0^B} = \\frac{5}{10} = \\frac{1}{2}\n\t\\end{align*}\n\t\n\tThus, the asset A is more interesting to an investor, as it gives more return on investment. If an investor were to invest an amount of $ 10 $ at $ t = 0 $, it is more profitable for him to buy two units of asset A as compared to one unit of asset B.\n\\end{eg}\n\n\n\\subsection{Common asset types}\n\n\\paragraph{Bonds}\nA \\emph{bond} is an instrument of indebtedness of the \\emph{issuer} to the \\emph{holder}. It is a \\emph{debt security}, under which the issuer owes the holders a debt and, depending on the terms of the bond, is obliged to pay them interest (the coupon) and/or to repay the principal at a later date, termed the maturity date. Bonds can also be thought of as a \\emph{loan} given to the issuer by the holder. A bond primarily has two kinds of risks, \\emph{credit default risk} and \\emph{interest rate risk}. A bond issued by a reliable institution like the United States government is a good illustration of a risk-free asset. This is because the probability of such an organisation defaulting is close to zero, or in other words, the bond has \\emph{negligible} \\emph{credit default risk}. Such bonds are only subject to fluctuations of the current interest rate, called \\emph{interest rate risk}. The interest rate risk may also be nullified if the bond is held till maturity. If we assume that the interest rate is deterministic (the fluctuations are not random), the value of the bond is computable at any given future date, making it riskless. Such an assumption is quite reasonable in short periods of time and for institutions with a low default risk rating.\n\n\n\\paragraph{Stocks}\nA \\emph{stock} of a corporation is an ownership certificate, and constitutes the equity stake of its owners. It represents the residual assets of the company that would be due to stockholders after discharge of all senior claims such as secured and unsecured debt. A \\emph{share} of a stock is a unit of ownership of the organisation. Stocks are inherently risky, since the value of the organisation may change from time to time due to various internal and external factors. This is why the value of a stock in time is represented by a stochastic process $ (S_t)_t $.\n\n\n\\paragraph{Derivatives}\nA \\emph{derivative} is a contract between two parties that specify conditions (starting and termination dates, resulting values and definitions of the underlying variables, the parties' contractual obligations, and the notional amount) under which transactions are to be made between the parties. The most common underlying assets include commodities, stocks, bonds, interest rates and currencies, but they can also be other derivatives, which adds another layer of complexity to proper valuation. Essentially, the value of a derivative is a function of the value of the \\emph{underlying} asset(s). Derivatives are traded in their own right, and a \\emph{fair price} must be found for a derivative at each time of its existence. This problem is known as the \\emph{pricing problem}. One of the primary motivations for creation of derivatives was to hedge one's position from fluctuations in the market. A \\emph{hedge} is an investment strategy intended to offset potential losses or gains that may be incurred by a companion investment. Finding a hedging strategy is called the \\emph{hedging problem}. These are the two problems that must be looked at when defining a market model. In this thesis, our main focus shall be the pricing problem of a particular class of derivatives, called \\emph{exotic options}.\n\n\n\\subsection{Classification of derivatives}\n\\label{subsec:intro-derivative-classification}\n\nDerivatives may be classified on the basis of various factors. One important factor is whether the risk is symmetric (shared equally), or asymmetric (taken up by only one party). Another factor is the nature of the function (of the underlying) that the derivative depends on. This function may either be dependent only on the final value of the underlying (\\emph{path-independent}), or on the path that it took to reach this final value (\\emph{path-dependent}). The function may be discrete (\\emph{digital} or \\emph{binary}), or continuous In this section, we briefly look at some of the more important types of derivatives. \\footnote{\n\tA more interested reader should consult the following extensive Wikipedia articles.\n\t\\begin{itemize}\n\t\t\\item \\url{https://en.wikipedia.org/wiki/Option_(finance)\\#Types}\n\t\t\\item \\url{https://en.wikipedia.org/wiki/Option_style}\n\t\\end{itemize}\n}\n\n\n\\paragraph{Futures and forwards}\n\n\\begin{dfn}[Futures and forwards]\n\tFutures and forwards are contracts between two parties, the seller and the buyer, to exchange a certain asset at a predetermined future time at a agreed upon price. Futures are \\emph{exchange-traded derivatives} (ETDs), whereas forwards are traded \\emph{over-the-counter} (OTC).\n\\end{dfn}\n\nSuch derivatives obligate the contractual parties to the terms over the life of the contract. Futures are in some sense `safer' compared to forwards, since the involved parties must go through standard protocols of the exchange.\nThe contract contains the following details.\n\\begin{description}\n\t\\item[$ T $] The maturity, or the duration of the contract\n\t\\item[$ F_0 $] The delivery price, or the price prefixed (at the initial time) at which trades must take place at maturity\n\t\\item[$ r $] The rate of interest\n\t\\item[underlying] The asset(s) of trade at maturity\n\t\\item[$ S_0 $] The initial value of the underlying asset(s)\n\\end{description}\nThere are, of course, other possibilities, for instance a variable interest rate, dividends yielded by the underlying, but these may be viewed as generalisations of this simple case.\n\nLet us assume that the compounding is continuous. We may show that under the condition of a \\emph{viable market}\\footnote{see Section \\ref{sec:intro-market} for definitions of the term}, the fair delivery price of a future with underlying prices $ ( S_t )_{t \\in [0, T] } $ at any time $ t \\in [0, T] $ is given by the following equation.\n\\begin{equation}\n\t\\label{eq:intro-future-pr}\n\tF_t = S_t e^{ r (T - t) }\n\\end{equation}\n\n\n\\paragraph{Options}\n\n\\begin{dfn}[option]\n\tAn \\emph{option} or a \\emph{contingent claim} is a derivative which provides the buyer \\emph{the right, but not the obligation} to enter the contract under the specified terms.\n\\end{dfn}\n\nThus, the owner of the option may choose whether to exercise his right or not. Thus, on the one hand, the owner of the option bears no risk, since all the choice is his. On the other hand, the seller of the option is \\emph{obligated} to honour the terms of the contract -- whether it benefits him or not -- essentially making him bear all the risks. This asymmetry is primarily what sets options apart from the futures and forwards discussed earlier.\nThe contract contains the following details.\n\\begin{description}\n\t\\item[$ T $] The maturity, or the duration of the contract\n\t\\item[$ K $] The strike price, or the prefixed price at which trades may take place at maturity\n\t\\item[$ r $] The rate of interest\n\t\\item[underlying] The asset(s) which may be traded at maturity\n\t\\item[$ S_0 $] The initial value of the underlying asset at the initial time\n\t\\item[right] The exact right that the owner of the options has (see below)\n\t\\item[exercise time] European or American (see below)\n\\end{description}\n\nOptions may be categorised by the right of the owner and the exercise time.\n\n\\subparagraph{According to the right of the owner}  Options may be of two main types.\n\\begin{description}\n\t\\item[call] The owner has the right to buy. In this case, the price of the option at maturity is given by $ c_T = (S_T - K)_+ $, where $ (x)_+ \\coloneqq \\max \\{ 0, x \\} $.\n\t\\item[put] The owner has the right to sell. In this case, the price of the option at maturity is given by $ p_T = (K - S_T)_+ $.\n\\end{description}\nOf course, other complicated ownership rights may be constructed, but we shall restrict ourselves to calls and puts.\n\n\\subparagraph{According to the time at which the option may be exercised}  Again, option may be of two main types.\n\\begin{description}\n\t\\item[European] The owner may exercise the option only at maturity\n\t\\item[American] The owner may exercise the option at any time up to the maturity\n\\end{description}\nAgain, more complicated options exist, which allow exercising rights only at certain time points, but we exclude them from out discussion.\n\nSince American options allow for more flexibility for the owner, and thus more risk for the seller, they are more expensive as compared to their European counterparts. Let $ c_t, p_t $ denote the prices of an European call and put, and $ C_t, P_t $ denote the prices of an American call and put, respectively. Then, we must have $ C_t \\ge c_t $ and $ P_t \\ge p_t $.\n\n\n\\subparagraph{Call-put parity}  Call and put prices are connected to each other. We need the following proposition to explore the relationship.\n\n\\begin{prp}[Equality of portfolios]\n\t\\label{thm:intro-portfolio-eq}\n\tIn a \\emph{viable} and \\emph{frictionless market}\\footnote{see Section \\ref{sec:intro-market} for definitions of the terms}, if the values of two portfolios coincide at a time $ T $, they have to coincide at $ 0 $ ( or any other intermediate time $ t $).\n\\end{prp}\n\n\\begin{proof}\n\tLet us denote by $ \\mathcal{P}_1 $ and $ \\mathcal{P}_2 $ the two portfolios and by $ v_t(\\mathcal{P}) $ the value of a portfolio $ \\mathcal{P} $ at time $ t $. By assumption $ v_T (\\mathcal{P}_1) = v_T (\\mathcal{P}_2) $, so we assume by contradiction that $ v_0 (\\mathcal{P}_1) > v_0 (\\mathcal{P}_2) $.\n\t\n\tUnder this hypothesis it is possible to construct the following arbitrage strategy. At time 0, one can borrow the portfolio $ \\mathcal{P}_1 $ and sell it right away to buy portfolio $ \\mathcal{P}_2 $. One can pocket the difference $ v_0 (\\mathcal{P}_1) - v_0 (\\mathcal{P}_2) > 0 $. At $ t = T $ the values of the two portfolios coincide, so selling $ \\mathcal{P}_2 $ one gets the exact money to buy $ \\mathcal{P}_1 $ to be returned to the original lender. An profit is achieved, without investing any money, implying an arbitrage and violating the viable market hypothesis.\n\t\n\tSimilarly, we can show that $ v_0 (\\mathcal{P}_1) < v_0 (\\mathcal{P}_2) $ would also enable an arbitrage opportunity. Generalising the argument to all intermediate times $ t \\in [0, T] $, we get the result.\n\\end{proof}\n\nWe now look at the relationship. $ S_T - K = (S_T - K)_+ + (S_T - K)_- = (S_T - K)_+ - (K - S_T)_+ = c_T - p_T $. For any general time $ t $, using Proposition \\ref{thm:intro-portfolio-eq}, it holds that $ c_t - p_t = S_t - K e^{- r (T-t) } $. This is known as the \\emph{call-put parity}.\n\n\n\\paragraph{Exotic options}\nEuropean options are path-independent and the simplest type of options available. Hence, they are popularly known as \\emph{vanilla options}. The American options are path-dependent. Typically, other options which are more complex in nature are collectively called \\emph{exotic options}. These are usually path-dependent, and may be either European, American or have more complex exercise times. A few such options are described in brief.\n\\begin{description}\n\t\\item[Asian] The payoff depends on the average of the underlying's prices.\n\t\\item[lookback] The payoff depends on one of the extrema of the underlying's prices.\n\t\\item[cliquet or ratchet] A series of globally or locally, capped or floored, at-the-money options, but where the total premium is determined in advance.\n\t\\item[barrier] The price of the underlying reaching the pre-set barrier level either springs the option into existence (\\emph{knock-in}) or extinguishes an already existing option (\\emph{knock-out}).\n\\end{description}\n\n\n\n\\section{Financial Markets}\n\\label{sec:intro-market}\n\nThe idea of financial markets is intricately linked to that of financial transactions. Analogous to the ordinary markets, a financial market is a human construct to allow transaction between investors. The assets in the financial market are typically financial instruments such as bonds, stocks and derivatives discussed in the previous section. In this section we will primarily concern ourselves with the nature of financial markets and the assumptions we make while modelling them. Some of the jargon used in the previous section will become clear after this section.\n\nPricing of financial assets is one of the pressing aims of the subject of Financial Mathematics. In order to do so, we need to understand and characterise the fundamental mechanisms of the market that shape the pricing of assets. In doing so, we must note which dynamics of the market are more fundamental and must be incorporated in every model, and which are more debatable may be excluded from simpler models.\n\n\\paragraph{Viable market}\nThe term viability here refers to the fairness of a market. To interpret viability, we need to familiarise ourselves with some definitions.\n\nIn what follows, we assume the following.\n\\begin{itemize}\n\t\\item There is a probability space $ (\\Omega, \\mathcal{F}, (\\mathcal{F}_t)_t, P) $, endowed with the filtration $ (\\mathcal{F}_t)_t $.\n\t\\item $ \\forall t \\in [0, T], T \\in [0, \\infty) $, there is one riskless asset worth $ S_t^0 = e^{rt} $ (Take $ S_0^0 = 1 $).\n\t\\item $ \\forall t \\in [0, T], T \\in [0, \\infty) $, there are $ d $ risky assets each worth $ S_t^i $, where $ i \\in \\{ 1, 2, \\dots, d \\} $ is the index of the risky asset. These may be represented as a $ d $-dimensional (vector) stochastic process $ ( S_t^1, S_t^2, \\dots, S_t^d ) $.\n\\end{itemize}\n\nAlso, any quantity with a `$ \\sim $' on top denotes the discounted value of that quantity.\n\n\n\\begin{dfn}[investment strategy]\n\tA $ d + 1 $ dimensional (vector) stochastic process $ \\Phi = (\\bm{\\phi_t})_t = (\\phi_t^0, \\phi_t^1, \\dots, \\phi_t^d)_t $ is called an \\emph{investment strategy} or \\emph{trading strategy} if $ \\phi_t^i $ is $ \\mathcal{F}_t $-measurable $ \\forall i \\in [d] $.\n\\end{dfn}\nThis means that there is a procedure to allocate resources within the portfolio at all times. We shall write strategy to mean investment strategy in the rest of the document.\n\nThe following definition gives the value of a strategy at a point in time.\n\\begin{dfn}[value of a strategy]\n\tThe value of a strategy $ \\Phi $ at a time $ t $ is given by $ V_t( \\Phi ) = \\bm{\\phi_t} \\cdot S_t $.\n\\end{dfn}\n\n\\begin{dfn}[self-financing strategy]\n\tA portfolio is self-financing if its changes in value are only due to changes in prices of the assets. This can be represented as follows.\n\t\\begin{subequations}\n\t\t\\begin{align}\n\t\t\t\\dif V_t &= \\bm{\\phi_t} \\cdot \\dif S_t \\qquad \\forall t \\in [0, T]  \\\\\n\t\t\t\\implies  \\qquad  \\dif \\tilde{V}_t &= \\bm{\\phi_t} \\cdot \\dif \\tilde{S}_t \\qquad \\forall t \\in [0, T]\n\t\t\\end{align}\n\t\\end{subequations}\n\\end{dfn}\nThis implies that we do not put in any fresh money in the strategy at any point of time, apart from what is generated due to the change is values of the underlying assets.\n\n\\begin{dfn}[admissible strategy]\n\tA self-financing strategy $ \\Phi $ is said to be admissible if $ V_t( \\Phi ) \\ge 0 \\  \\forall t \\in [0, T] $.\n\\end{dfn}\nThis implies that we do not run out of money at any point of time.\n\n\\begin{dfn}[arbitrage strategy]\n\tAn admissible strategy $ \\Phi $ is said to be an arbitrage strategy if $ V_0( \\Phi ) = 0 $ and $ P( V_T( \\Phi ) > 0 ) > 0 $.\n\\end{dfn}\nA arbitrage strategy basically means that it generates value at time $ T $ without any initial investment. For the sake of fairness, we do not want a market in which there exist arbitrage opportunities. The next definition addresses this issue.\n\n\\begin{dfn}[viable market, no free lunch]\n\tA market is called \\emph{viable}, or there is \\emph{no free lunch}, if there does not exist any arbitrage strategies.\n\\end{dfn}\n\nWe will see in Theorem \\ref{thm:discrete-ftoap1} of Chapter \\ref{cha:models} how the financial concept of viability translates mathematically to the existence of equivalent martingale measures.\n\n\n\\paragraph{Complete market}\n\n\\begin{dfn}[hedgeable, attainable]\n\tA derivative is called hedgeable or attainable if it can be represented as a linear combination of the \\emph{basic assets} at all times. Basic assets include stocks, bonds and commodities whose prices are \\emph{not} directly linked to other assets in the market.\n\\end{dfn}\n\n\\begin{dfn}[complete market]\n\tA market is said to be complete if all derivatives are hedgeable.\n\\end{dfn}\n\nA market is complete if the traded basic assets represent all the random factors that influence the course of prices. If we are in complete market model, this means that, whatever be the contract, one can always set a hedging strategy that equals the final value of the derivative. This hedging strategy employs, by definition, only the basic assets (riskless and risky) traded on the market. In a sense those derivatives are redundant, they do not introduce any additional risk factor; any randomness source is represented by the basic assets prices and it is tradeable.\n\nThis implies that the marginal probability distributions of the derivative price are uniquely determined by the marginal distributions of the prices of the basic assets. Namely, each derivative is replicable, so its price at all times may be written as the value of a portfolio employing basic assets only, that is to say it is a linear combination of the prices of the basic assets. On the other hand, in a viable market the discounted value of a portfolio is a martingale under the risk-neutral probability, so if a contingent claim is attainable, then its price, by the martingale property, belongs to the linear span of the basic assets' prices under this probability. Vice versa, if the market is incomplete, then there must be sources of randomness that cannot be totally represented as linear combinations of the prices of the basic tradeable assets, which means that the basic titles are not sufficient to construct all the necessary hedging strategies.\n\nWe will see in Theorem \\ref{thm:discrete-ftoap2} of Chapter \\ref{cha:models} how the financial concept of market completeness translates mathematically to the existence of a unique equivalent martingale measure.\n\n\n\\paragraph{Frictionless market}\nFor any transaction (sale or purchase) in the market, one usually pays some \\emph{commission}. The commission is a very small fraction of the current value of the traded assets, and it seems reasonable to assume that it is not a factor that affects the dynamics of the prices in a direct fashion. Furthermore, the computational difficulty of including such transactional costs in the market is quite high. Thus, we choose to ignore such costs in the simple market models that we shall deal with, and call the market as \\emph{frictionless}.\n\n\\begin{dfn}[frictionless market]\n\tA market is called frictionless if there are no transaction costs.\n\\end{dfn}\n\n\n\\paragraph{Infinitely divisible assets}\nIn a market, usually only discrete units of assets may be bought or sold. This would pose an additional constraint in the modelling of the market. But it is quite evident that this constraint does in no way affect prices of individual assets. Furthermore, markets are usually so varied that one might think to combine stocks and bonds to a value that is roughly equivalent to a fraction of a different asset. Thus, we ignore this constraint in our market models, and say that we may have \\emph{infinitely divisible assets} in our market.\n\n\n\\paragraph{Small investor hypothesis}\nAn investor who has virtually unlimited funds might decide to buy massive quantities of an asset to make its price rise in order to sell it later at a higher price. We shall ignore such cases, and assume that all agents are trifling with respect to the market dimension, meaning that they cannot influence prices uniquely by means of their investing strategies, hence prices are determined only by the combined actions of all agents. This assumption is called the \\emph{small investor hypothesis} and it is totally realistic in bigger stock markets like for those in the United States, even though it is less so for much smaller markets.\n\n\n\\paragraph{Borrowing}\nLastly, we assume that an investor may borrow assets, whether they are financial instruments such as money, bonds and stocks, or otherwise.\n\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: t\n%%% End:\n", "meta": {"hexsha": "5919b42fe7fc4696047a2fbd6599213b1afd0c29", "size": 28385, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "MathMods/Thesis/docs/tex/prologue.tex", "max_stars_repo_name": "homdx/edu", "max_stars_repo_head_hexsha": "a32c9f1777f80a54c3d4a3fc8389748fe27739c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MathMods/Thesis/docs/tex/prologue.tex", "max_issues_repo_name": "homdx/edu", "max_issues_repo_head_hexsha": "a32c9f1777f80a54c3d4a3fc8389748fe27739c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MathMods/Thesis/docs/tex/prologue.tex", "max_forks_repo_name": "homdx/edu", "max_forks_repo_head_hexsha": "a32c9f1777f80a54c3d4a3fc8389748fe27739c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-09-15T21:30:43.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-15T21:30:43.000Z", "avg_line_length": 96.8771331058, "max_line_length": 1307, "alphanum_fraction": 0.7683988022, "num_tokens": 6941, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.30668375038193746}}
{"text": "% Copyright 2015-2017 Dan Foreman-Mackey and the co-authors listed below.\n\n\\documentclass[modern, letterpaper]{aastex61}\n\n\\pdfoutput=1\n\n\\include{vc}\n\n\\usepackage{microtype}\n\\usepackage{url}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{natbib}\n\\usepackage{multirow}\n\\bibliographystyle{aasjournal}\n\n% Matrix fix:\n% http://tex.stackexchange.com/questions/317824/letter-c-appearing-inside-pmatrix-environment-with-aastex\n%\\makeatletter\n%\\def\\env@matrix{\\hskip -\\arraycolsep\\let\\@ifnextchar\\new@ifnextchar\\array{*{\\c@MaxMatrixCols}c}}\n%\\makeatother\n\n% Column spacing in matrix\n% http://tex.stackexchange.com/questions/275725/adjusting-separation-between-matrix-entries\n\\setlength\\arraycolsep{25pt}\n\n% Projects:\n\\newcommand{\\project}[1]{\\textsf{#1}}\n\n\\newcommand{\\foreign}[1]{\\emph{#1}}\n\\newcommand{\\etal}{\\foreign{et\\,al.}}\n\\newcommand{\\etc}{\\foreign{etc.}}\n\\newcommand{\\ie}{\\foreign{i.e.}}\n\n\\newcommand{\\figureref}[1]{\\ref{fig:#1}}\n\\newcommand{\\Figure}[1]{Figure~\\figureref{#1}}\n\\newcommand{\\figurelabel}[1]{\\label{fig:#1}}\n\n\\newcommand{\\Table}[1]{Table~\\ref{tab:#1}}\n\\newcommand{\\tablelabel}[1]{\\label{tab:#1}}\n\n\\renewcommand{\\eqref}[1]{\\ref{eq:#1}}\n\\newcommand{\\Eq}[1]{Equation~(\\eqref{#1})}\n\\newcommand{\\eq}[1]{\\Eq{#1}}\n\\newcommand{\\eqalt}[1]{Equation~\\eqref{#1}}\n\\newcommand{\\eqlabel}[1]{\\label{eq:#1}}\n\n\\newcommand{\\sectionname}{Section}\n\\newcommand{\\sectref}[1]{\\ref{sect:#1}}\n\\newcommand{\\Sect}[1]{\\sectionname~\\sectref{#1}}\n\\newcommand{\\sect}[1]{\\Sect{#1}}\n\\newcommand{\\sectalt}[1]{\\sectref{#1}}\n\\newcommand{\\App}[1]{Appendix~\\sectref{#1}}\n\\newcommand{\\app}[1]{\\App{#1}}\n\\newcommand{\\sectlabel}[1]{\\label{sect:#1}}\n\n\\newcommand{\\T}{\\ensuremath{\\mathrm{T}}}\n\\newcommand{\\dd}{\\ensuremath{\\,\\mathrm{d}}}\n\\newcommand{\\unit}[1]{{\\ensuremath{\\,\\mathrm{#1}}}}\n\\newcommand{\\bvec}[1]{{\\ensuremath{\\boldsymbol{#1}}}}\n\\DeclareMathOperator*{\\argmax}{argmax}\n\n% TO DOS\n\\newcommand{\\todo}[3]{{\\color{#2}\\emph{#1}: #3}}\n\\newcommand{\\dfmtodo}[1]{\\todo{DFM}{red}{#1}}\n\n\\newcommand{\\response}[1]{{\\color{blue}#1}}\n\n\\begin{document}\n\\sloppy\\sloppypar\\raggedbottom\\frenchspacing\n\n\\title{Gaussian processes in astronomy}\n\n\\correspondingauthor{Daniel Foreman-Mackey}\n\\email{foreman.mackey@gmail.com}\n\n\\author[0000-0002-9328-5652]{Daniel Foreman-Mackey}\n\\affiliation{Center for Computational Astrophysics, Flatiron Institute, New York, NY}\n\\affiliation{NASA Sagan Fellow; Astronomy Department, University of Washington, Seattle, WA}\n\n\\begin{abstract}\\noindent\n\nGaussian Processes are a class of statistical models that are broadly applied\nin the astronomical literature.\nThis paper provides a pedagogical introduction to the mathematical foundation\nfor these models and motivates the use in astrophysics.\nWe also provide some examples, a discussion of the limitations of GP models,\nand present some methods for scaling GPs to large datasets.\n\n\\end{abstract}\n\n\\keywords{%\n %methods: data analysis\n %---\n %methods: statistical\n %---\n %asteroseismology\n %---\n %stars: rotation\n %---\n %planetary systems\n}\n\n\\section{Introduction}\n\nOutline:\n\n\\begin{enumerate}\n\n\\item Intro: history, motivation, some examples, etc.\n\n\\item Example: fitting a line to data, the effects of correlated noise\n\n\\item Formalism: prior over function space, prediction, etc.\n\n\\item Examples: list some examples from the literature (linear models, noise,\n    model, etc.)\n\n\\item Issues: outliers, computational cost\n\n\\item Scaling: approximate and exact methods\n\n\\end{enumerate}\n\nGaussian Processes (GPs) are a class of stochastic models that have been used\nin the astronomical literature for more than a century\\footnote{The Dutch\nastronomer T.~N.~Thiele has been credited as one of the earliest users of\nGPs in 1880 \\citep{Lauritzen:1981}.}, but as probabilistic methods for data\nanalysis become more popular, these methods have seen a resurgence over the\npast decade.\nOutside of the astronomy, there is a rich literature in statistics, computer\nscience, and other fields discussing the implementation and use of GPs as a\ncomputational tool.\nThe quintessential reference is the textbook \\emph{Gaussian Processes for\nMachine Learning} \\citep{Rasmussen:2006} and much of the discussion in this\npaper draws from this reference, but a clear pedagogical introduction---with\nastronomers in mind---is lacking in the literature.\nThe goal of this paper is to fill this gap and enable more astronomers to\nconfidently use GPs in their work, or confidently justify not using them.\nWe also summarize some of the important developments from other fields and\ndiscuss their implications for GPs in astronomy.\n\nA useful way of thinking about GP models is that they are an extension of more\ntraditional regression methods where we fit for the parameters of a\ndeterministic function by minimizing the (scaled) residuals between the model\npredictions and the observations.\nWhen using GPs, we model both the \\emph{mean function} (as before) and the\n\\emph{covariance function}.\nThis intuitive generalization allows us to take into account stochastic\neffects like correlated noise or model misspecification.\nIf this isn't clear, don't worry because we will return to more specific\nexamples in the following pages.\n\n\\section{Motivating example: Fitting a line to data}\n\nTo motivate our discussion, let's start with the classic data analysis\nproblem: fitting a line to data.\\footnote{A detailed discussion of this\nproblem can be found elsewhere \\citep{Hogg:2010}.}\nIn this example, we have simulated a dataset using a linear model, but we have\nalso introduced some correlated noise (more on this shortly).\nThe data are shown in SOMEFIGURE with the ``true'' linear model superimposed.\nIn this case, we are interested in placing constraints on the parameters of\nthis linear model (slope $m$ and intercept $b$) conditioned on the observed\nset of $N$ data points ${\\{x_n,\\,y_n,\\,\\sigma_n\\}}_{n=1}^N$.\nA typical way of doing this inference would be to compute the weighted linear\nleast squares solution \\citep[see][for example]{Hogg:2010,Ivezic:2014}.\nThis solution is plotted as the SOMECOLOR contour in SOMEFIGURE.\\footnote{It\nis worth noting that for this example, we have assumed improper uniform priors\non $m$ and $b$, and the contours are the ``one-sigma'' credible intervals on\nthe resulting posterior.}\n\n\n\\section{Notation}\n\n\\section{Probabilistic inference}\n\nTo start, let's consider the general problem of fitting a model to data.\nWhether you are a frequentist or a Bayesian, the key quantity of interest in\nany fitting procedure is the likelihood function\n\\begin{eqnarray}\n\\mathcal{L}(\\bvec{\\theta}) &=& p(D\\,|\\,\\bvec{\\theta})\n\\end{eqnarray}\nwhere $D$ represents the data and $\\bvec{\\theta}$ are the parameters of the\nmodel.\nThe right-hand side of this equation can be read as ``the probability of a\ndataset $D$ given a specific set of model parameters $\\bvec{\\theta}$.''\nMore formally, this is the probability density function (pdf) for $D$\n\\emph{conditioned} on $\\bvec{\\theta}$.\nIt is important to remember that this is a pdf \\emph{over datasets}.\nThis means that\n\\begin{eqnarray}\n\\int p(D\\,|\\,\\bvec{\\theta}) \\dd D &=& 1\n\\end{eqnarray}\nbut\n\\begin{eqnarray}\n    \\int p(D\\,|\\,\\bvec{\\theta}) \\dd \\bvec{\\theta} &\\ne& 1 \\quad.\n\\end{eqnarray}\n\nIt is our job as scientists to specify the model~--~and, hence, the likelihood\nfunction~--~that we want to fit.\nOnce we have specified this pdf, there are two main ways to make inferences\nabout the model parameters $\\bvec{\\theta}$ based on a given dataset.\nThe first method is to maximize the likelihood to find a point estimate of the\n``best-fit'' parameters.\nThis can be written as\n\\begin{eqnarray}\n\\bvec{\\theta}^* = \\argmax_{\\bvec{\\theta}} \\mathcal{L}(\\bvec{\\theta})\n\\end{eqnarray}\nwhere $\\bvec{\\theta}^*$ are the ``maximum likelihood'' parameters and the\n$\\argmax$ operator indicates that we are finding the value of $\\bvec{\\theta}$\nthat maximizes $\\mathcal{L}(\\bvec{\\theta})$.\nIn practice, this maximization must usually be performed numerically using a\nnon-linear optimization routine.\n\nTo quantify the uncertainties on our constraints on the model parameters or\nmarginalize over our uncertainty in some nuisance parameters, we can quantify\nthe posterior pdf for $\\bvec{\\theta}$\n\\begin{eqnarray}\np(\\bvec{\\theta}\\,|\\,D) &=&\n    \\frac{p(\\bvec{\\theta})\\,p(D\\,|\\,\\bvec{\\theta})}{p(D)} \\quad.\n\\end{eqnarray}\nAs above, we can read the left-hand side of this equation as ``the probability\nof the parameters conditioned on the data.''\nIn practice, this pdf is usually obtained by drawing samples from\n$p(\\bvec{\\theta}\\,|\\,D)$ using a numerical method like Markov chain Monte\nCarlo (MCMC).\nIn this case, we must specify the likelihood function and, additionally, the\nprior pdf $p(\\bvec{\\theta})$.\n\nThe point here is that the likelihood function is the key ingredient in any\nmodel fitting context.\nIn fact, some people (including this author) would argue that the likelihood\nfunction is as much part of the model as your code that computes the physics\nof your system.\nThe following sections present some of the commonly made assumptions about the\nlikelihood function for astronomical data analysis, and then derive the\nGaussian process (GP) likelihood as a generalization of the standard\nequations.\nIn \\sect{corr-noise}, we derive the likelihood function for a GP model\n(\\eqalt{gp-loglike}) and the key point is that this function is probably a\n\\emph{drop-in replacement} for the likelihood that you're currently using.\n\n\\section{The Gaussian likelihood}\n\nIn this section, we derive the likelihood function that is most commonly used\nfor astronomical data analysis and discuss this choice in the context of\nprobabilistic data analysis.\nIt is not uncommon for astronomers to compute and minimize something that we\nrefer to as ``chi-squared'' $\\chi^2$, the sum of normalized squared residuals.\nThis section demonstrates that this is equivalent to maximizing a likelihood\nfunction derived under a restrictive set of assumptions.\nThis will then allow us, in the next section, to generalize this procedure.\n\nIt is commonly assumed that a set of data points with error bars represent\nindependent measurements with Gaussian uncertainties of known variance.\nUnder this assumption, for a model $f(\\bvec{x};\\,\\bvec{\\theta})$, the\nlikelihood for a single data point $y_n$ measured at coordinates $\\bvec{x}_n$\nwith error bar $\\sigma_n$ is\n\\begin{eqnarray}\np(y_n\\,|\\,\\bvec{x}_n,\\,\\sigma_n,\\,\\bvec{\\theta}) &=&\n    \\frac{1}{\\sqrt{2\\,\\pi\\,{\\sigma_n}^2}}\\,\\exp\\left(\n    -\\frac{1}{2}\\,\\frac{{[y_n-f(\\bvec{x};\\,\\bvec{\\theta})]}^2}{{\\sigma_n}^2}\n    \\right) \\quad.\n\\end{eqnarray}\nTherefore, the joint likelihood for a set of $N$ data points ${\\{\\bvec{x}_n,\\,\ny_n,\\, \\sigma_n\\}}_{n=1}^N$ is\n\\begin{eqnarray}\\eqlabel{ind-like}\np(\\{y_n\\}\\,|\\,\\{\\bvec{x}_n,\\,\\sigma_n\\},\\,\\bvec{\\theta}) &=&\n    \\prod_{n=1}^N\\frac{1}{\\sqrt{2\\,\\pi\\,{\\sigma_n}^2}}\\,\\exp\\left(\n    -\\frac{1}{2}\\,\\frac{{[y_n-f(\\bvec{x};\\,\\bvec{\\theta})]}^2}{{\\sigma_n}^2}\n    \\right) \\quad.\n\\end{eqnarray}\nIt is common practice to work with the natural logarithm of this quantity\ninstead of the likelihood directly.\nTaking the logarithm of \\eq{ind-like}, we find\n\\begin{eqnarray}\\eqlabel{ind-loglike}\n\\log p(\\{y_n\\}\\,|\\,\\{\\bvec{x}_n,\\,\\sigma_n\\},\\,\\bvec{\\theta}) &=&\n    -\\frac{1}{2}\\,\\sum_{n=1}^N\\left[\n    \\frac{{[y_n-f(\\bvec{x};\\,\\bvec{\\theta})]}^2}{{\\sigma_n}^2}\n    +\\log {(2\\,\\pi\\,{\\sigma_n}^2)}\n    \\right]\\quad.\n\\end{eqnarray}\nIt is worth qualitatively considering the roles of the two terms in\n\\eq{ind-loglike} because this discussion will come up repeatedly throughout\nthis paper.\nThe first term within the square brackets is what is commonly referred to as\n``$\\chi^2$'' in the astronomy literature and it quantifies the\n``goodness-of-fit'' of the model.\nThe second term quantifies the specificity of the model and penalizes overly\ngeneral models.\nFor fixed uncertainties $\\{\\sigma_n\\}$, this second term is a constant with\nrespect to the parameters $\\bvec{\\theta}$ and maximizing the log-likelihood in\n\\eq{ind-loglike} is equivalent to minimizing $\\chi^2$.\nIn other words, calculating $\\chi^2$ requires assuming that the uncertainties\nare independent Gaussians with known variance.\n\nThis more general formulation of the Gaussian likelihood function will come in\nhandy for our derivation of GP modeling shortly, but let's start with a\nconcrete example where minimizing $\\chi^2$ is not sufficient.\nIt is not uncommon for uncertainties on astronomical quantities to be\nunderestimated or unknown.\nIn this case, we must fit for a parametric representation of the uncertainties\nsimultaneously with the model $f(\\bvec{x};\\,\\bvec{\\theta})$.\nTo do this, we might include another parameter, we'll call it $s$, to quantify\nthe amount by which the uncertainties are underestimated.\nIn this case, the likelihood becomes\n\\begin{eqnarray}\\eqlabel{jitter-loglike}\n\\log p(\\{y_n\\}\\,|\\,\\{\\bvec{x}_n,\\,\\sigma_n\\},\\,\\bvec{\\theta},\\,s) &=&\n    -\\frac{1}{2}\\,\\sum_{n=1}^N\\left[\n    \\frac{{[y_n-f(\\bvec{x};\\,\\bvec{\\theta})]}^2}{{\\sigma_n}^2 + s^2}\n    +\\log {(2\\,\\pi\\,[{\\sigma_n}^2+s^2])}\n    \\right]\n\\end{eqnarray}\nand we can now use this to fit for both $\\bvec{\\theta}$ and $s$.\n\n\\section{A Gaussian process as a model of correlated noise}\n\\sectlabel{corr-noise}\n\nOne way to motivate the definition of a GP is to think of it as a model of\ncorrelated noise.\nThe derive this, we start by re-writing \\eq{ind-loglike} as a matrix equation\n\\begin{eqnarray}\\eqlabel{ind-loglike-matrix}\n\\log p(\\{y_n\\}\\,|\\,\\{\\bvec{x}_n,\\,\\sigma_n\\},\\,\\bvec{\\theta}) &=&\n    -\\frac{1}{2}\\,{\\bvec{r}_\\bvec{\\theta}}^\\T\\,K^{-1}\\,{\\bvec{r}_\\bvec{\\theta}}\n    -\\frac{1}{2}\\,\\log\\det K\n    -\\frac{N}{2}\\,\\log(2\\,\\pi)\n\\end{eqnarray}\nwhere $\\bvec{r}_\\bvec{\\theta}$ is the residual vector\n\\begin{eqnarray}\n{\\bvec{r}_\\bvec{\\theta}}^\\T = \\left(\\begin{array}{ccc}\n    y_1 - f(\\bvec{x}_1;\\,\\bvec{\\theta}) & \\cdots &\n    y_N - f(\\bvec{x}_N;\\,\\bvec{\\theta})\n\\end{array}\\right)\n\\end{eqnarray}\nand $K$ is the ``covariance matrix'' that is, in this case, diagonal\n\\begin{eqnarray}\\eqlabel{diag-cov}\nK = \\left(\\begin{array}{ccc}\n    {\\sigma_1}^2 & 0 & 0 \\\\\n    0 & \\ddots & 0 \\\\\n    0 & 0 & {\\sigma_N}^2\n\\end{array}\\right) \\quad.\n\\end{eqnarray}\nNoting that, for a diagonal matrix like this $K$, the inverse is\n\\begin{eqnarray}\nK^{-1} = \\left(\\begin{array}{ccc}\n    1/{\\sigma_1}^2 & 0 & 0 \\\\\n    0 & \\ddots & 0 \\\\\n    0 & 0 & 1/{\\sigma_N}^2\n\\end{array}\\right) \\quad.\n\\end{eqnarray}\nand the log-determinant is\n\\begin{eqnarray}\n    \\log\\det K &=& \\log \\prod_{n=1}^N {\\sigma_n}^2 \\\\\n    &=& \\sum_{n=1}^N \\log{\\sigma_n}^2 \\quad,\n\\end{eqnarray}\nwe can see that \\eq{ind-loglike} and \\eq{ind-loglike-matrix} are equivalent.\n\nYou might remember that, in the previous section, we assumed that the data\npoints are independent.\nThis assumption is expressed by the fact that the covariance matrix in\n\\eq{diag-cov} is diagonal~--~all the off-diagonal elements are zero.\nIn order to take correlated noise into account, we introduce non-zero\noff-diagonal elements in the covariance $K$.\nThe $n,\\,m$-th entry in the $N \\times N$ matrix $K$ quantifies the covariance\nbetween data points $n$ and $m$.\nIf we have some method of \\emph{estimating} this covariance \\foreign{a\npriori}~--~much like how we often assume that we can estimate the diagonal\nelements of this matrix~--~we can fill in this matrix $K$ and evaluate\n\\eq{ind-loglike-matrix} with this new, dense $K$.\nHowever, it is often hard to estimate these covariances reliably and we will,\ninstead, fit for them.\nIn practice, we probably don't want to add the $N\\,(N-3)/2 \\sim N^2$\nparameters that would be needed to fit for each entry in this matrix directly.\nInstead, we parameterize this covariance using a functional form where the\n$n,\\,m$-th element of the matrix is given by\n\\begin{eqnarray}\\eqlabel{kernel}\nK_{n,\\,m} &=& {\\sigma_n}^2\\,\\delta_{n,\\,m} +\n    k(\\bvec{x}_n,\\,\\bvec{x}_m;\\,\\bvec{\\alpha})\n\\end{eqnarray}\nwhere $\\delta_{n,\\,m}$ is the Kronecker delta, and $k(\\bvec{x}_n,\\,\\bvec{x}_m;\n\\,\\bvec{\\alpha})$ is a function~--~parameterized by $\\bvec{\\alpha}$~--~that\ncaptures the covariance between the data points $\\bvec{x}_n$ and $\\bvec{x}_m$.\nThis function $k(\\bvec{x}_n,\\,\\bvec{x}_m;\\,\\bvec{\\alpha})$ goes by a few names\nin the literature, the most common of which are ``covariance function'' or\n``kernel function''.\nThroughout this paper, we will refer to this function as the covariance\nfunction.\nTo indicate that the covariance matrix is now parameterized by\n$\\bvec{\\alpha}$, we will typeset it as $K_\\bvec{\\alpha}$ and the\nlog-likelihood function becomes\n\\begin{eqnarray}\\eqlabel{gp-loglike}\n\\log p(\\{y_n\\}\\,|\\,\\{\\bvec{x}_n,\\,\\sigma_n\\},\\,\\bvec{\\theta},\\,\\bvec{\\alpha})\n    &=&\n    -\\frac{1}{2}\\,{\\bvec{r}_\\bvec{\\theta}}^\\T\\,{K_\\bvec{\\alpha}}^{-1}\\,\n        {\\bvec{r}_\\bvec{\\theta}}\n    -\\frac{1}{2}\\,\\log\\det K_\\bvec{\\alpha}\n    -\\frac{N}{2}\\,\\log(2\\,\\pi) \\quad.\n\\end{eqnarray}\n\nIt is worth noting that the case of independent data points\n(\\eqalt{ind-loglike-matrix}) is a special (restrictive) case of\n\\eq{gp-loglike} where\n\\begin{eqnarray}\nk(\\bvec{x}_n,\\,\\bvec{x}_m;\\,\\bvec{\\alpha}) &=& 0 \\quad.\n\\end{eqnarray}\nIn the case of GPs, we relax this assumption and choose a more flexible\ncovariance function that approximates the real covariance structure in the\ndata generation process.\nIf we fit this GP model to a dataset where the data are actually independent\nand the diagonal variances ${\\sigma_n}^2$ are correctly estimated, the second\nterm in \\eq{gp-loglike} will drive the covariance function to zero and\ncorrectly capture the fact that the data are independent.\n\nOne of the touchiest subjects in GP modeling is the choice of covariance\nfunction and we will return to a detailed discussion of this in \\dfmtodo{SOME\nSECTION}, but first, let's consider a concrete example.\n\n\\section{Kernel functions}\n\nAny kernel function used for GP modeling must be positive semi-definite.\nIf this is not satisfied, the covariance matrix will not be invertible and the\ndeterminant will be zero or negative, giving a likelihood of zero.\nThis requirement can also be written informally as\n\\begin{eqnarray}\n    \\int k(\\bvec{x},\\,\\bvec{x}^\\prime)\\,f(\\bvec{x})\\,f(\\bvec{x}^\\prime)\\,\n    p(\\bvec{x})\\dd \\bvec{x} \\, p(\\bvec{x}^\\prime)\\dd \\bvec{x}^\\prime\n    \\ge 0\n\\end{eqnarray}\nfor all finite functions $f(\\bvec{x})$.\nThis property is generally hard to prove for a new kernel function so the\nstandard practice is to use sums and products of common functions that have\nbeen proved to be valid.\nMost common functions are discussed in Chapter~4 of \\citet{Rasmussen:2006}.\nJust like any model selection problem, there are few different methods of\nchoosing the kernel and some of these might be better than others depending on\nthe goals of the user.\nSometimes, the choice can be motivated using physics and the parameters of the\nmodel can then be interpreted in this same framework.\nIn other cases, the GP model might just be acting as an effective model.\nFor these situations, it is generally useful to demonstrate quantitatively\nthat the results of your inference are not sensitive to your choice of kernel.\nIt is also possible to compare different kernel functions using standard model\ncomparison techniques like Bayes factors, cross validation, or information\ncriteria.\n\n\n\n\n\n\n- an example: linear fit\n- prediction: interpolation and extrapolation\n- kernel choice\n- outliers\n- examples: exoplanet transit fitting, radial velocity fitting, emulation,\n- practical considerations: scaling,\n\n\n\\subsection{Code availability}\n\nAlongside this paper, we have released a well-tested and documented open\nsource software package that implements the method and all of the examples\ndiscussed in these pages.\nThis software is available on GitHub\n\\url{https://github.com/dfm/george}\\footnote{This version of the paper was\ngenerated with git commit \\texttt{\\githash} (\\gitdate).} and Zenodo\n\\dfmtodo{ADD ZENODO}, and it is made available under the MIT license.\n\n\\acknowledgments\nIt is a pleasure to thank\nfor helpful discussions informing the ideas and code presented here.\n\nThis work was performed in part under contract with the Jet Propulsion\nLaboratory (JPL) funded by NASA through the Sagan Fellowship Program executed\nby the NASA Exoplanet Science Institute.\n\n%This research made use of the NASA \\project{Astrophysics Data System} and the\n%NASA Exoplanet Archive.\n%The Exoplanet Archive is operated by the California Institute of Technology,\n%under contract with NASA under the Exoplanet Exploration Program.\n\n%This paper includes data collected by the \\kepler\\ Mission. Funding for the\n%\\kepler\\ Mission is provided by the NASA Science Mission directorate.\n%We are grateful to the entire \\kepler\\ team, past and present.\n%These data were obtained from the Mikulski Archive for Space Telescopes\n%(MAST).\n%STScI is operated by the Association of Universities for Research in\n%Astronomy, Inc., under NASA contract NAS5-26555.\n%Support for MAST is provided by the NASA Office of Space Science via grant\n%NNX13AC07G and by other grants and contracts.\n\n%This research made use of Astropy, a community-developed core Python package\n%for Astronomy \\citep{Astropy-Collaboration:2013}.\n\n\\facility{Kepler}\n\\software{%\n     %\\project{AstroPy} \\citep{Astropy-Collaboration:2013},\n     %\\project{corner.py} \\citep{Foreman-Mackey:2016},\n     %\\project{Eigen} \\citep{Guennebaud:2010},\n     %\\project{emcee} \\citep{Foreman-Mackey:2013},\n     %\\project{george} \\citep{Ambikasaran:2016},\n     %\\project{Julia} \\citep{Bezanzon:2012},\n     %\\project{LAPACK} \\citep{Anderson:1999},\n     %\\project{matplotlib} \\citep{Hunter:2007},\n     %\\project{numpy} \\citep{Van-Der-Walt:2011},\n     %\\project{transit} \\citep{Foreman-Mackey:2016a},\n     %\\project{scipy} \\citep{Jones:2001}.\n}\n\n%\\vspace{5ex}\n%\\appendix\n\n\\bibliography{george}\n\n\\end{document}\n", "meta": {"hexsha": "80012af76210a114e31ae17905cb3a450375c168", "size": 21709, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/ms.tex", "max_stars_repo_name": "rychallener/george", "max_stars_repo_head_hexsha": "98eae39ae453c31afac530c49f178f66c0013c5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 379, "max_stars_repo_stars_event_min_datetime": "2015-01-08T15:35:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:01:03.000Z", "max_issues_repo_path": "paper/ms.tex", "max_issues_repo_name": "rychallener/george", "max_issues_repo_head_hexsha": "98eae39ae453c31afac530c49f178f66c0013c5f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 136, "max_issues_repo_issues_event_min_datetime": "2015-01-06T17:36:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-08T20:12:17.000Z", "max_forks_repo_path": "paper/ms.tex", "max_forks_repo_name": "rychallener/george", "max_forks_repo_head_hexsha": "98eae39ae453c31afac530c49f178f66c0013c5f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 119, "max_forks_repo_forks_event_min_datetime": "2015-01-06T09:27:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T17:54:48.000Z", "avg_line_length": 42.0717054264, "max_line_length": 105, "alphanum_fraction": 0.7394168317, "num_tokens": 6275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792046, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.30668375038193746}}
{"text": "\\documentclass[a4paper]{article}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{braket}%量子力学符号\n\\usepackage{geometry}\n\\usepackage{natbib}\n\\usepackage{float}%稳定图片位置\n\\usepackage{graphicx,subfig}%画图\n\\usepackage{caption}\n\\usepackage[english]{babel}\n\\usepackage{indentfirst}%缩进\n\\usepackage{enumerate}%加序号\n\\usepackage{multirow}%合并行\n\\usepackage{hyperref}\n\\usepackage{verbatim}\n\\title{\\Large \\textbf{VP390 Problem Set 7}\\\\\n\\author{\\textbf{Pan, Chongdan ID:516370910121}\\\\\n}\n}\n\\begin{document}\n\\maketitle\n\\section{Problem 1}\n\\noindent\n\\\\$\\hat{L_y}=\\hat{z}\\hat{p_x}-\\hat{x}\\hat{p_z},\\hat{L_z}=\\hat{x}\\hat{p_y}-\\hat{y}\\hat{p_x},\\hat{L_x}=\\hat{y}\\hat{p_z}-\\hat{z}\\hat{p_y}$\n\\\\$[\\hat{L_y},\\hat{L_z}]=\\hat{L_y}\\hat{L_z}-\\hat{L_z}\\hat{L_y}=(\\hat{z}\\hat{p_x}-\\hat{x}\\hat{p_z})(\\hat{x}\\hat{p_y}-\\hat{y}\\hat{p_x})-(\\hat{x}\\hat{p_y}-\\hat{y}\\hat{p_x})(\\hat{z}\\hat{p_x}-\\hat{x}\\hat{p_z})$\n\\\\$\\hat{L_y}\\hat{L_z}=\\hat{z}\\hat{p_x}\\hat{x}\\hat{p_y}+\\hat{x}\\hat{p_z}\\hat{y}\\hat{p_x}-\\hat{x}\\hat{p_z}\\hat{x}\\hat{p_y}-\\hat{z}\\hat{p_x}\\hat{y}\\hat{p_x}=\\hat{z}\\hat{p_y}\\hat{p_x}\\hat{x}+\\hat{p_z}\\hat{y}\\hat{x}\\hat{p_x}-\\hat{p_z}\\hat{p_y}\\hat{x}\\hat{x}-\\hat{y}\\hat{z}\\hat{p_x}\\hat{p_x}$\n\\\\$-\\hat{L_z}\\hat{L_y}=\\hat{y}\\hat{p_x}\\hat{z}\\hat{p_x}+\\hat{x}\\hat{p_y}\\hat{x}\\hat{p_z}-\\hat{x}\\hat{p_y}\\hat{z}\\hat{p_x}-\\hat{y}\\hat{p_x}\\hat{x}\\hat{p_z}=\\hat{y}\\hat{z}\\hat{p_x}\\hat{p_x}+\\hat{p_y}\\hat{p_z}\\hat{x}\\hat{x}-\\hat{p_y}\\hat{z}\\hat{x}\\hat{p_x}-\\hat{y}\\hat{p_z}\\hat{p_x}\\hat{x}$\n\\\\$[\\hat{L_y},\\hat{L_z}]=\\hat{y}\\hat{p_z}(\\hat{x}\\hat{p_x}-\\hat{p_x}\\hat{x})-\\hat{z}\\hat{p_y}(\\hat{x}\\hat{p_x}-\\hat{p_x}\\hat{x})=\\hat{y}\\hat{p_z}[\\hat{x},\\hat{p_x}]-\\hat{z}\\hat{p_y}[\\hat{x},\\hat{p_x}]$\n\\\\$[\\hat{L_y},\\hat{L_z}]=\\hat{y}\\hat{p_z}-\\hat{z}\\hat{p_y}[\\hat{x},\\hat{p_x}]=i\\hbar\\hat{L_z}$\n\\section{Problem 2}\n\\noindent $\\cos\\theta=\\frac{L_z}{L}=\\frac{m}{\\sqrt{3(3+1)}}=\\frac{\\sqrt{3}}{2}\\rightarrow\\theta=\\frac{\\pi}{6}$\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[scale=0.5]{P1.png}\n    \\caption{Projection of $L$ on the z-axis}\n\\end{figure}\n\\section{Problem 3}\n    \\noindent(a)$\\mu=\\frac{m^2}{2m}=\\frac{m}{2}$\n    \\\\$I=\\mu(2a)^2=2ma^2$\n    \\\\$\\hat{H}\\psi=\\frac{\\hat{L}^2}{2I}\\psi=E\\psi\\rightarrow\\hat{L}^2\\psi=4Ema^2\\psi$\n    \\\\Since $L=\\hbar\\sqrt{l(l+1)}$\n    \\\\$E_l=\\frac{\\hbar^2l(l+1)}{4ma^2}$\n    \\\\$[-\\frac{\\hbar^2}{2\\mu}\\frac{\\partial}{\\partial r}(r^2\\frac{\\partial}{\\partial r})+\\frac{\\hat{L}}{2\\mu r^2}+V(r)]\\psi=E\\psi$\n    \\\\$[-\\frac{\\hbar^2}{2\\mu}\\frac{\\partial}{\\partial r}(r^2\\frac{\\partial}{\\partial r})+\\frac{\\hbar^2l(l+1)}{2\\mu r^2}+V(r)]R(r)=ER(r)$\n    \\\\Then $E=-\\frac{E_1}{n^2}$ where $E_1=\\frac{\\mu e^4}{32\\pi^2\\hbar^2\\epsilon_0}=\\frac{me^4}{64\\pi^2\\hbar^2\\epsilon_0}$ and $R_{nl}=Ae^{-\\frac{r}{a_0n}r^lL_{nl}(\\frac{r}{a_0})}$\n    \\\\(b)\\begin{figure}[H]\n        \\centering\n        \\includegraphics[scale=0.25]{P2.png}\n        \\caption{Energy level diagram}\n    \\end{figure}\n    \\noindent For transition energy $E_1=\\frac{\\hbar^2(l+1)}{2I}=\\frac{\\hbar^2(1+1)}{2I}=\\frac{\\hbar^2}{I}$\n    \\\\$\\bigtriangleup E=E_{l+1}-E_l=\\frac{\\hbar^2(l+2)(l+1)}{2I}-\\frac{\\hbar^2l(l+1)}{2I}=\\frac{2\\hbar^2(l+1)}{2I}=(l+1)\\frac{\\hbar^2}{I}$\n    \\\\Hence $E_n=nE_1$ where $n=1,2,3\\cdots$\n    \\\\(c) $I=2ma^2=2\\cdot1.67\\cdot10^{-27}\\cdot(3.7\\cdot10^{-11})^2=4.57\\cdot10^{-48}$\n    \\\\$E_1=\\frac{\\hbar^2}{2ma^2}=\\frac{\\hbar^2}{I}=2.41\\times10^{-21}$J\n    \\\\(d) $\\bigtriangleup E_{l\\rightarrow l+1}=\\frac{2\\hbar^2(l+1)}{4ma^2}$\n    \\\\Hence when $l=0$ we have the lowest transition energy $\\bigtriangleup E_{l\\rightarrow l+1}=\\frac{\\hbar^2}{2ma^2}=0.015$eV\n    \\\\$\\bigtriangleup E=\\frac{hc}{\\lambda}\\rightarrow\\lambda=\\frac{hc}{\\bigtriangleup E}=\\frac{6.63\\cdot10^{-34}3\\cdot10^8}{2.41\\times10^{-21}}=8.25\\cdot10^{-5}m$\n    \\\\It's in the visible light region close to Paschen region.\n\\section{Problem 4}\n\\noindent (a)$L=r\\times p$, since $r$ and $p$ are perpendicular to each other in the xy-plane, then $L$ is along the z-axis, hence it has two zero components\n\\\\According to classic mechanic, for the total energy, since $V(x)=0,E=K=\\frac{1}{2}I\\omega^2=\\frac{L^2}{2I}$\n\\\\(b) $\\hat{H}=\\frac{\\hat{L_z}^2}{2I}+V=-\\frac{\\hbar^2}{2I}\\frac{\\partial^2}{\\partial\\varphi^2}+V$\n\\\\Since $V=0,-\\frac{\\hbar^2}{2I}\\frac{\\partial^2\\psi}{\\partial\\varphi^2}=E\\psi\\rightarrow-\\frac{\\hbar^2}{2I}\\frac{\\partial^2\\phi(\\varphi)}{\\partial\\varphi^2}=E\\phi(\\varphi)\\rightarrow \\phi=Ce^{\\pm\\sqrt{-\\frac{2IE}{\\hbar^2}}\\varphi}, E$ can be any real number\n\\\\Hence $\\psi=Ce^{\\pm\\sqrt{-\\frac{2IE}{\\hbar^2}}\\varphi}$\n\\\\ (c) $\\psi(\\varphi+2\\pi)=\\psi(\\varphi)\\rightarrow\\int_0^{2\\pi}C^2\\cos^4(\\varphi)d\\varphi=1\\rightarrow C^2\\frac{3\\pi}{4}=1\\rightarrow C=\\pm\\frac{2}{\\sqrt{3\\pi}}$\n\\section{Problem 5}\n\\noindent (a) $n=6,l=3$\n\\\\ (b) $E_6=-\\frac{E}{n^2}=-\\frac{13.6}{36}=0.38$eV\n\\\\ (c) $|L|=\\sqrt{L^2}=\\sqrt{3(3+1)\\hbar^2}=2.3\\times10^{-33}$\n\\\\ (d) $L_z=m\\hbar=\\pm1.989\\times10^{-33},\\pm1.326\\times10^{-33},\\pm6.63\\times10^{-34},0$\n\\section{Problem 6}\n\\noindent (a)$\\psi_{210}=\\frac{1}{4\\sqrt{2\\pi}}(\\frac{Z}{a_0})^{3/2}\\frac{Zr}{a_0}e^{-Zr/2a_0}\\cos\\theta$\n\\\\Since it's hydrogen atom, $Z=1,\\psi_{210}=\\frac{1}{4\\sqrt{2\\pi}}(\\frac{1}{a_0})^{3/2}\\frac{r}{a_0}e^{-r/2a_0}\\cos\\theta$\n\\\\$P(r)=\\psi_{210}^*\\psi_{210}4\\pi r^2=\\frac{r^4}{8a_0^5}e^{-r/a_0}\\cos^2\\theta,$ hence $P(r)\\propto r^4e^{-r/a_0}$\n\\\\(b) $\\frac{\\mathrm{d}P(r)}{\\mathrm{r}}=\\frac{r^3}{2a_0^5}e^{-r/a_0}\\cos^2\\theta-\\frac{1}{a0}\\frac{r^4}{8a_0^5}e^{-r/a_0}\\cos^2\\theta=0$\n\\\\ $r=4a_0\\text{ or }r=0$\n\\section{Problem 7}\n\\noindent $\\psi_{000}=\\frac{1}{\\sqrt{\\pi}}(\\frac{Z}{a_0})^{3/2}e^{-Zr/a_0}$\n\\\\Since $Z=1$, then $P(r)=4r^2\\frac{1}{a_0^3}e^{-2r/a_0}$\n\\\\Since $a_0=5.29\\cdot10^{-11}>>R_0=10^{-15},e^{-2r/a_0}\\approx0$\n\\\\$\\int_0^{R_0}P(r)\\mathrm{d}r=\\int_0^{10^{-15}}4r^2\\frac{1}{a_0^3}\\mathrm{d}r=9\\cdot10^{-15}$\n\\section{Problem 8}\n\\noindent $I=\\frac{2}{5}mR^2=\\frac{2}{5}9.1\\cdot10^{-31}(10^{-15})^2\\approx3.64\\cdot10^{-60}$\n\\\\$\\omega=\\frac{|L|}{I}=\\frac{|S|}{I}=\\frac{\\hbar\\sqrt{\\frac{3}{4}}}{3.64\\cdot10^{-60}}\\approx2.5\\cdot10^{25}$rad/s\n\\\\$v=\\omega R=2.5\\cdot10^{25}10^{-15}=2.5\\cdot10^{10}$m/s\n\\\\The speed is larger than the speed of light, hence the result from classic mechanic is incorrect.\n\\section{Problem 9}\n\\noindent (a) We should expect to see 4 lines with $j=\\pm\\frac{3}{2}$ because $l=0,s=\\frac{3}{2}$\n\\\\Hence the lines corresponds $m_s=\\pm\\frac{3}{2},\\pm\\frac{1}{2}$\n\\\\ (b) We should expect to see 3 lines with $m=\\pm1,0$ \n\\section{Problem 10}\n\\noindent $\\textbf{L}=\\hbar\\sqrt{l(l+1)}=1.05\\cdot10^{-34}\\sqrt{2\\cdot3}\\approx2.58\\cdot10^{-34}\\text{N}\\cdot\\text{m}\\cdot\\text{s}$\n\\\\$j=l\\pm\\frac{1}{2}=\\frac{5}{2}\\text{ or }\\frac{3}{2}$\n\\\\The corresponding $\\textbf{J}\\approx3.11\\cdot10^{-34}\\text{ or }2.03\\cdot10^{-34}\\text{N}\\cdot\\text{m}\\cdot\\text{s}$   \n\\end{document}", "meta": {"hexsha": "5e33f8ad38076d991a5567e692964971eae5a697", "size": 6676, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "VP390ModernPhysics/HW/Assigments/HW7/HW7.tex", "max_stars_repo_name": "PANDApcd/Physics", "max_stars_repo_head_hexsha": "ed8171e5872ecef1d3e3e81935d71bc65063fc95", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "VP390ModernPhysics/HW/Assigments/HW7/HW7.tex", "max_issues_repo_name": "PANDApcd/Physics", "max_issues_repo_head_hexsha": "ed8171e5872ecef1d3e3e81935d71bc65063fc95", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "VP390ModernPhysics/HW/Assigments/HW7/HW7.tex", "max_forks_repo_name": "PANDApcd/Physics", "max_forks_repo_head_hexsha": "ed8171e5872ecef1d3e3e81935d71bc65063fc95", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 69.5416666667, "max_line_length": 287, "alphanum_fraction": 0.6208807669, "num_tokens": 3209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.30653073342459336}}
{"text": "\\documentclass{brownthesis}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{graphicx}\n\\usepackage{tikz}\n\\usepackage{bbm}\n\\usepackage{verbatim}\n\\usepackage[percent]{overpic}\n\n\\DeclareMathOperator{\\Tr}{tr}\n\\DeclareMathOperator{\\tr}{tr}\n\\DeclareMathOperator*{\\diag}{diag}\n\\DeclareMathOperator{\\arctanh}{arctanh}\n\\DeclareMathOperator{\\arcsinh}{arcsinh}\n\\DeclareMathOperator{\\sech}{sech}\n\\DeclareMathOperator{\\var}{var}\n\n\\def\\dd{{\\rm d}}\n\\def\\LL{{\\rm L}}\n\\def\\RR{{\\rm R}}\n\n\\begin{document}\n\n\\title{\\say{A Tale of 2-Spheres}: How Conformal Symmetry, Chaos, and\\\\\n  Some Elementary Algebra Led to Insights in\\\\\n  Black Holes and Quantum Cosmology}\n\\author{Chang Liu}\n\\degrees{B.~Sc., University of Science and Technology of China, 2013\\\\\n  M.~Eng., University of Auckland, 2015\\\\\n  M.~Sc., University of Auckland, 2017\\\\\n  M.~Sc, Brown University, 2019}\n\\principaladvisor{David Anthony Lowe}\n\\reader{David Anthony Lowe}\n\\reader{Antal Jevicki}\n\\reader{Stephon Haigh-Solomon Alexander}\n\\dean{Andrew G.~Campbell}\n\\submitdate{May 2022}\n\\abstract{The unification of quantum mechanics and general relativity is the holy grail of fundamental theoretical physics. This thesis represents a small part of that effort, where we consider a number of problems that might be of interest to the theoretical studies of black holes and quantum cosmology. Why study black holes and quantum cosmology, one might ask? The answer lies in the fact that they are the only two systems where it is necessary to apply quantum mechanics and general relativity simultaneously. In particular, they both have event horizons, which are global structures of the spacetime that prevent events from making causal contact. They therefore have become the primary arenas where logical incompatibilities of quantum mechanics and general relativity can be made most transparent. One of the most dramatic incompatibilities is the black hole information paradox, which concerns the unitarity of processes that involve the formation and the evaporation of black holes. This thesis will first discuss a proposed resolution to the information paradox called black hole complementarity, and a closely linked issue known as quantum scrambling, in particular in the context of a 2D conformal field theory. We will then present a microscopic quantum model of the de-Sitter universe that incorporates the required quantum scrambling on the cosmological horizon. This quantum model of cosmology is a so-called ``holographic'' map between the stretched horizon of the de-Sitter spacetime and the static patch (colloquially known as the ``bulk''). Continuing in a similar vein, the rest of the thesis will be concerned with building holographic theories between flat spacetime and its boundary, and we present two holographic theories of the flat spacetime, first for massive scalar particles and then extending the results to gravitons. As these all have something to do with mappings between boundary 2-spheres and their bulk, this is therefore a story of building holography on 2-spheres. Hence the title of this thesis.}\n\\abstractpage\n\\abstractpage\n\\beforepreface\n\n\\prefacesection{Vita}\n   \\begin{flushright}\n{\\large\\bf Chang Liu}\\\\\\vskip6pt\n182 Hope Street\\\\\nPROVIDENCE RI 02912 USA\\\\\\vskip2pt\n{\\tt chang\\_liu3@brown.edu}\\\\\n{\\tt github.com/cl91}\n\\end{flushright}\n\n\\section*{Education}\n\\begin{description}\n\\item[2017--2022] PhD, Physics. Brown University.\\\\\n  Advisor: David A. Lowe\n\\item[2016--2017] MSc 1st Class Honours, Physics. University of Auckland.\\\\\n  Advisor: Richard Easther\\\\\n  Faculty of Science Master's Award Scholarship\n\\item[2014--2015] MEng 1st Class Honours, Software Engineering. University of Auckland.\n\\item[2009--2013] BSc, Physics. University of Science and Technology of China.\n\\end{description}\n\n\\section*{Publications}\n{\\bf Conformal Wavefunctions for Graviton Amplitudes}\n\\medbreak\n\\noindent Authors: Chang Liu (Brown U.), David A. Lowe (Brown U.)\\\\\nDate: Aug 31, 2021\\\\\nPublished in: {\\sl JHEP} 01 (2022) 148\\\\\ne-Print: {\\tt 2109.00037 [hep-th]}\\\\\nDOI: {\\tt 10.1007/JHEP01(2022)148}\n\\medbreak\n\\noindent Abstract:\\quad The extended-BMS algebra of asymptotically flat spacetime contains an SO(3,1) subgroup that acts by conformal transformations on the celestial sphere. It is of interest to study the representations of this subgroup associated with gravitons. To reduce the equation of motion to a Schr\\\"odinger-like equation it is necessary to impose a non-covariant gauge condition. Using these solutions, leading-order gauge invariant Weyl scalars are then computed and decomposed into families of unitary principal series representations. An invertible holographic mapping is constructed between these unitary principal series operators and massless spin-2 perturbations of flat spacetime.\n\\bigbreak\n\n\\noindent{\\bf Conformal Wave Expansions for Flat Space Amplitudes}\n\\medbreak\n\\noindent Authors: Chang Liu (Brown U.), David A. Lowe (Brown U.)\\\\\nDate: May 3, 2021\\\\\nPublished in: {\\sl JHEP} 07 (2021) 102\\\\\ne-Print: {\\tt 2105.01026 [hep-th]}\\\\\nDOI: {\\tt 10.1007/JHEP07(2021)102}\n\\medbreak\n\\noindent Abstract:\\quad The extended BMS algebra contains a conformal subgroup that acts on the celestial sphere as SO(3,1). It is of interest to perform mode expansions of free fields in Minkowski spacetime that realize this symmetry in a simple way. In the present work we perform such a mode expansion for massive scalar fields using the unitary principal series representations of SO(3,1) with a view to developing a holographic approach to gravity in asymptotically flat spacetime. These mode expansions are also of use in studying holography in three-dimensional de Sitter spacetime.\n\\bigbreak\n\n\\noindent{\\bf Holographic Map for Cosmological Horizons}\n\\medbreak\n\\noindent Authors: Chang Liu (Brown U.), David A. Lowe (Brown U.)\\\\\nDate: Dec 10, 2019\\\\\nPublished in: {\\sl Int.J.Mod.Phys.A} 35 (2020) 26, 2050158\\\\\ne-Print: {\\tt 1912.04864 [hep-th]}\\\\\nDOI: {\\tt 10.1142/S0217751X20501584}\n\\medbreak\n\\noindent Abstract:\\quad We propose a holographic map between Einstein gravity coupled to matter in a de Sitter background and large $N$ quantum mechanics of a system of spins. Holography maps a spin model with a finite dimensional Hilbert space defined on a version of the stretched horizon into bulk gravitational dynamics. The full Hamiltonian of the spin model contains a non-local piece which generates chaotic dynamics, widely conjectured to be a necessary part of quantum gravity, and a local piece which recovers the perturbative spectrum in the bulk.\n\\bigbreak\n\n\\noindent{\\bf Notes on Scrambling in Conformal Field Theory}\n\\medbreak\n\\noindent Authors: Chang Liu (Brown U.), David A. Lowe (Brown U.)\\\\\nDate: Aug 29, 2018\\\\\nPublished in: {\\sl Phys.Rev.D 98} (2018) 12, 126013\\\\\ne-Print: {\\tt 1808.09886 [hep-th]}\\\\\nDOI: {\\tt 10.1103/PhysRevD.98.126013}\n\\medbreak\n\\noindent Abstract:\\quad The onset of quantum chaos in quantum field theory may be studied using out-of-time-order correlators at finite temperature. Recent work argued that a timescale logarithmic in the central charge emerged in the context of two-dimensional conformal field theories, provided the intermediate channel was dominated by the Virasoro identity block. This suggests a wide class of conformal field theories exhibit a version of fast scrambling. In the present work we study this idea in more detail. We begin by clarifying to what extent correlators of wavepackets built out of superpositions of primary operators may be used to quantify quantum scrambling. Subject to certain caveats, these results concur with previous work. We then go on to study the contribution of intermediate states beyond the Virasoro identity block. We find that at late times, time-ordered correlators exhibit a familiar decoupling theorem, suppressing the contribution of higher dimension operators. However this is no longer true of the out-of-time-order correlators relevant for the discussion of quantum chaos. We compute the contributions of these conformal blocks to the relevant correlators, and find they are able to dominate in many interesting limits. Interpreting these results in the context of holographic models of quantum gravity, sheds new light on the black hole information problem by exhibiting a class of correlators where bulk effective field theory does not predict its own demise.\n\n\\bigbreak\n\\noindent{\\bf Two-Scale Oscillons}\n\\medbreak\n\\noindent Authors: Chang Liu, Richard Easther (U of Auckland).\\\\\nDate: Dec 21, 2016\\\\\ne-Print: {\\tt 1612.07228 [hep-th]}\n\\medbreak\n\\noindent Abstract:\\quad Oscillons are spatially stationary, quasi-periodic solutions of nonlinear field theories seen in settings ranging from granular systems, low temperature condensates and early universe cosmology. We describe a new class of oscillon in which the spatial envelope can have ``off centre'' maxima and pulsate on timescales much longer than the fundamental frequency. These are exact solutions of the 1-D sine-Gordon equation and we demonstrate numerically that similar solutions exist in up to three dimensions for a range of potentials. The dynamics of these solutions match key properties of oscillons that may form after cosmological inflation in string-motivated monodromy scenarios.\n\n\\section*{Employment History}\n\\begin{description}\n\\item[2015] Software Engineer at Pharos Systems International.\\\\\n  {Skills:} .NET/C\\#, iOS, Microsoft SQL Server, REST API.\\\\\n  {Job description:} Development and maintainance. Products include\n  \\begin{enumerate}\n  \\item Blueprint, an enterprise printing management system.\n  \\item PharosAPI, a RESTful API for printing and accounting.\n  \\item MobilePrint, an iOS APP for printing management.\n  \\end{enumerate}\n\\end{description}\n\n\\prefacesection{Preface}\nThe unification of quantum mechanics and general relativity is the holy grail of fundamental theoretical physics. This thesis represents a small part of that effort, where we consider a number of problems that might be of interest to the theoretical studies of black holes and quantum cosmology. A natural question to ask is: how does the study of black holes and quantum cosmology help us unify quantum mechanics and general relativity? The answer lies in the simple observation that black holes and our universe both share a number of key features that practically demand the simultaneous application of quantum mechanics and general relativity: they both have a singularity, where matter and energy are infinitely dense, and known laws of physics do not apply, as well as a horizon, which prevents spacetime events from making causal contact no matter how much they want to. They are also intrinsically gravitational systems, meaning that their classical (ie.~non-quantum) description involves only the spacetime geometry\\footnote{One might argue that for a charged black hole the full description contains both the Maxwell field and the metric. This is certainly true, but the most important feature, ie.~the singularity and the event horizon structure, involve only the metric.}. They therefore have become the primary objects to study if one wants to build a unified theory of quantum gravity, because it is in these two systems that the logical incompatibilities of quantum mechanics and general relativity become most apparent.\n\nOne of the most fundamental reason that makes quantum mechanics incompatible with general relativity is the existence of entangled states in quantum mechanics. You can form arbitrary superpositions of quantum states, and these quantum superpositions are still valid quantum states. However, in general relativity arbitrary superpositions of spacetime geometries do not make any sense (especially when they have different topologies). This has motivated the opinion that general relativity should be viewed an emergent theory as part of a complete quantum theory of spacetime, and the idea of defining a ``holographic'' theory between a quantum mechanical model and a semi-classical gravity in a spacetime with one additional spatial dimension. In other words, objects on the classical spacetime (called the bulk) are mapped into objects in the quantum mechanical model defined on its boundary, and objects in the boundary quantum mechanical models are mapped into objects in the semi-classical local field theory in the bulk. This thesis will discuss three separate, but closely linked issues that all have something to do with building holographic theories between the bulk and the boundary. As these boundaries are all two-dimensional spheres, this is therefore a story of building holography on 2-spheres. Hence the title of this thesis.\n\n\\prefacesection{Acknowledgements}\nFirst of all I would like to thank my advisor, Prof.~David Anthony Lowe, for guidance and advisory. I would also like to thank other faculty members in the high energy theory group, in particular my defense committee members and letter writers, Prof.~Antal Jevicki, Prof.~Marcus Spradlin, and Prof.~Stephon H.~Alexander, for their support. Finally, I would like to thank my friend Yiming Xing from the condensed matter experiment group for many enlightening discussions.\n\nI would also like to use this opportunity to thank my weightlifting coaches, Jeremy and Tommy from PBC strength and conditioning, and Dave, Jarred, and James from the Providence Barbell Club for their help in athletic development, in particular for helping me win the men's 89kg weightclass Gold Medal in the USAW meet down at Westerly in December 2021. I also just realized that I am morally obliged to thank Steve, not just because of the shirt but also because of the very threatening look that he gave me when I mentioned that his name wasn't here. This gratitude (although in considerably less strength than the one for Steve) is also extended to the other team members of the Providence Barbell Club (at least the ones I like!).\n\nFinally, a special thanks is awarded to Bioware Montreal for ruining the Mass Effect series forever, especially with that nonsense known as Andromeda. I have finally been able to spend less time in video games and focus on finishing my PhD.\n\\afterpreface\n\n\\chapter{Introduction}\nThis thesis is based on the materials published in the following four papers:\n\\begin{enumerate}\n  \\item{Notes on Scrambling in Conformal Field Theory, {\\sl Phys.Rev.D 98} (2018) 12, 126013}\n  \\item{Holographic Map for Cosmological Horizons, {\\sl Int.J.Mod.Phys.A} 35 (2020) 26, 2050158}\n  \\item{Conformal Wave Expansions for Flat Space Amplitudes, {\\sl JHEP} 07 (2021) 102}\n  \\item{Conformal Wavefunctions for Graviton Amplitudes, {\\sl JHEP} 01 (2022) 148}\n\\end{enumerate}\nAs we have explained in the Preface, the results in these papers will hopefully contribute to\nthe overall goal of building a consistent theory that unifies quantum mechanics and general\nrelativity. There are several closely related ideas in play here, so in this Introduction\nwe will review the relevant literature and explain how the work in the rest of the thesis\nis motivated by these ideas.\n\nThe fundamental reason why it is so difficult to build a consistent quantum theory of\ngravity, is that the theory of general relativity and the theory of quantum mechanics\nare logically incompatible in their core assumptions. The core assumption of general relativity\nis the equivalence principle, the mathematical formulation of which is that spacetime\nis a Riemann manifold. On the other hand, in quantum mechanics states are described\nas vectors in a Hilbert space evolving via unitary operators. The incompatibilities of these\nassumptions are best shown in what is known as the black hole information paradox, which we will\nnow explain.\n\nThe black hole information paradox follows from a famous result from Hawking \\cite{PhysRevD.14.2460},\nnow known as the Hawking radiation, which says that black holes of a given mass $M$ radiate with\na temperature $T_{\\rm H}$ that is proportional to its surface gravity on the horizon. For\nSchwarzschild black holes this is inversely proportional to its mass:\n\\[\nT_{\\rm H} = \\frac{1}{8\\pi M}\n\\]\nin Planck units ($c=\\hbar = G = k_{\\rm B} = 1$). This radiation has a thermal (black body)\nspectrum, and it takes energy away from the black hole, which implies that black holes\nevaporate and will eventually disappear\\footnote{We assume that after evaporation, there is nothing left for the black hole\nand spacetime is back to normal, ie.~locally Minkowski spacetime without any singularity.\nA different resolution to the information paradox instead proposes that a Planck-scale\nremnant is left over as a result of black hole evaporation, which carries the information that has\nbeen captured by the event horizon. Although an interesting, if not somewhat problematic idea\n(see, for instance, Ref.~\\cite{Chen:2014jwq} for a review), in this thesis we assume the\nabsence of any Planck-scale remnant.}. This may not seem problematic by itself, and it is a reasonably robust result\nthat follows directly from semi-classical physics near the horizon, without invoking any\nPlanck-scale assumptions. However, the fact that the radiation has a thermal spectrum\nviolates quantum mechanics in the most profound way: imagine a collection of particles\nin a pure quantum state that forms a black hole, which then evaporates into a collection\nof thermal particles. This is therefore a scattering process which turns\na pure state into a thermal density matrix, so it cannot be unitary in general. As unitarity\nis equivalent to information conservation, we therefore have a paradox where any process\nthat involves black holes as intermediate states has information loss.\n\nThe core geometric property of black holes that led to the information paradox,\nis that classically, once information has crossed the event horizon, it will never be\nable to get out. An idea known as black hole complementarity \\cite{PhysRevD.48.3743}\nis therefore to propose that in the full quantum theory of gravity,\nthe Hawking radiation from the horizon is not completely thermal,\nbut instead carries subtle deviations that encode the incoming state. In other words, the\nevent horizon, or more correctly the ``stretched horizon'' that is one Planck length outside\nthe event horizon, scrambles the incoming information and ``reflects'' them via subtle\ncorrelations in the outgoing Hawking radiation. However, on closer inspection this leads\nto a new paradox: if a particle carrying some information crosses the event horizon,\nthe equivalence principle implies that the free-falling observer sees nothing special\nabout the event horizon, certainly nothing so dramatic that destroys the information.\nAt the same time though, the information is being reflected by the stretched horizon,\nso one would be able to see two copies of the same quantum state by first collecting\nthe Hawking radiation and then jump into the event horizon to catch the original\ncarrier of the information. This is a direct violation\nof the quantum no-cloning theorem \\cite{nielsen2001quantum}, which itself follows from\nlinearity and unitarity of quantum mechanics.\n\nThere is a clever way out of this, and it draws from the lesson we\nhave learned from both relativity and quantum mechanics, which is that descriptions\nof physics should depend on the observer. It is indeed true that information seems to\nappear in two different places, but no single observer can observe them simultaneously.\nFor an observer to observe the information reflected by the stretched horizon, he\nmust first wait long enough to collect enough Hawking radiation to reconstruct the original\ninformation. If the stretched horizon takes too long to reflect information, the observer\nwould not have enough time once he jumps into the event horizon, because the original\ncarrier would have died at the singularity.\n\nThis is explained in detail in Ref.~\\cite{Sekino:2008he}, but the upshot is that\nthe stretched horizon must be able to hide information longer than the so-called\nscrambling time-scale $t_\\star$, otherwise the quantum no-cloning theorem is violated.\nFor a Schwarzschild black hole of mass $M$, this is\n\\[\nt_\\star = \\beta \\log S\n\\]\nHere $\\beta$ is the inverse Hawking temperature $\\beta = 1/T_{\\rm H} = 8\\pi M$, and\n$S$ is the Bekenstein-Hawking entropy. We are therefore led to the task of finding\nquantum systems that exhibit this scrambling time-scale, and for several types of\nquantum systems, from Brownian quantum circuits \\cite{Lashkari:2011yi} to a sparse\nrandom graphs \\cite{Lashkari:2011yi, Bentsen:2018uph}, we do observe at least in a\ncertain sense a scrambling time that is logarithmic in their system size. This has\nsubsequently led Ref.~\\cite{PhysRevLett.115.131603} to study quantum scrambling in\nthe generic setting of a 2D conformal field theory at finite temperature, and\nconclude that if the intermediate channel were dominated by the Virasoro identity\nblock, then the out-of-time-order correlators would exhibit a time-scale $t_\\star$\nthat is logarithmic in the central charge $c$:\n\\[\nt_\\star = \\frac{\\beta}{2\\pi}\\log\\frac{c}{h_{w}}\n\\]\nHere $\\beta$ is the inverse temperature and $h_w$ is the conformal weight of\nan operator $W$.\n\nChapter \\ref{chap:chaos} of this thesis is therefore dedicated to a more careful\nstudy of this scrambling time-scale in 2D conformal field theories. We will find that\nsubject to certain caveats, our results concur with Ref.~\\cite{PhysRevLett.115.131603},\nbut only if the intermediate channels are dominated by the Virasoro identity block.\nHowever, for many conformal field theories this is not true. We find that\neven a sparse spectrum of intermediate states can dominate the out-or-time-order\ncorrelators, and therefore spoil or at least dramatically modify the onset of\nquantum chaos. This has important implications which we will discuss in detail in\nChapter \\ref{chap:chaos}, but one of the biggest impacts is that the decoupling\ntheorem is no longer true for the gravity dual of the boundary CFT, and one can\nno longer use effective field theory to describe bulk physics.\n\nArmed with the insights about quantum scrambling on the black hole horizon, it is interesting to see if we can apply the same understanding to cosmological horizons, since they share the same mathematical formulation classically. In particular, it would be interesting to build a microscopic theory of the cosmological horizon that enables the thermodynamic interpretation of the de-Sitter entropy as the logarithm of the number of quantum microstates encoded by the stretched horizon. We would expect the stretched horizon of the de-Sitter spacetime to share the same feature of the stretched horizon of black holes, in the sense that for an observer in the static patch the stretched horizon scrambles information and reflects them via Hawking radiation with the de-Sitter temperature. In Chapter \\ref{chap:map} we will attempt to build such a theory, where we model the de-Sitter horizon as a large-$N$ quantum spin model with a Hamiltonian consisting of a ``local'' piece, which reproduces the semi-classical local bulk physics, and a ``non-local'' piece which generates the scrambling dynamics. This is a holographic theory in the sense that we have constructed a map between semi-classical gravity in a bulk spacetime (in our case the static patch of the de-Sitter spacetime) and a unitary quantum mechanical model its boundary (the stretched horizon).\n\nA key piece in our holographic map on the cosmological horizon is the ability to write bulk modes as spin waves living on the boundary spin model. This requires that we solve for the wavefunctions of scalar fields living on the bulk. In a similar vein, in Chapter \\ref{chap:flatspace} we will discuss how one can construct wavefunctions of massive scalar fields that transform as a unitary principal series representation of the $\\rm SO(3,1)$ group. This is motivated by recent work in constructing holographic theories between flat 4D Minkowski spacetime and its 2D boundary, known as the celestial sphere \\cite{deBoer:2003vf,Kapec:2014opa,Kapec:2016jld,Cheung:2016iub}. As an application, we will discuss how these unitary principal series wavefunctions can be used to construct a holographic map between gravitons living in 4D Minkowski spacetime and conformal operators living on the celestial sphere. The details will be discussed in Chapter \\ref{chap:gravitons}, but the basic idea is to decompose the Weyl scalars built from the graviton modes into the scalar modes in Chapter \\ref{chap:flatspace}, and map these into the celestial sphere. Both the scalar holographic map and the graviton holographic map are invertible, in the sense that one can recover the original bulk modes via inverse transforms on the celestial operators. We will discuss both the successes and the shortcomings of our procedure. These include, in particular, the fact that this simple holographic map that we have proposed amounts to a kinematic reorganization of the bulk modes, and that it remains unclear whether the addition of dynamical interactions will have any useful description in terms of conformal operators on the celestial sphere.\n\n\n\\chapter{Notes on Scrambling in Conformal Field Theory}\\label{chap:chaos}\nThe onset of quantum chaos in quantum field theory may be studied\nusing out-of-time-order correlators at finite temperature. Recent\nwork argued that a timescale logarithmic in the central charge emerged\nin the context of two-dimensional conformal field theories, provided\nthe intermediate channel was dominated by the Virasoro identity block.\nThis suggests a wide class of conformal field theories exhibit a version\nof fast scrambling. In the present work we study this idea in more\ndetail. We begin by clarifying to what extent correlators of wavepackets\nbuilt out of superpositions of primary operators may be used to quantify\nquantum scrambling. Subject to certain caveats, these results concur\nwith previous work. We then go on to study the contribution of intermediate\nstates beyond the Virasoro identity block. We find that at late times,\ntime-ordered correlators exhibit a familiar decoupling theorem, suppressing\nthe contribution of higher dimension operators. However this is no\nlonger true of the out-of-time-order correlators relevant for the\ndiscussion of quantum chaos. We compute the contributions of these\nconformal blocks to the relevant correlators, and find they are able\nto dominate in many interesting limits. Interpreting these results\nin the context of holographic models of quantum gravity, sheds new\nlight on the black hole information problem by exhibiting a class\nof correlators where bulk effective field theory does not predict\nits own demise.\n\n\\section{Introduction}\n\nIt has been suggested that quantum theories of gravity exhibit a property\nknown as fast scrambling, where a generic quantum state exhibits global\nthermalization in a timescale that is logarithmic in the system size\n\\cite{Sekino:2008he}. It is interesting to explore this idea in\nthe context of holographic theories of gravity dual to conformal field\ntheories, where one may try to extract constraints on the class of\nconformal field theories with gravity duals.\n\nOne simple way to to quantify this notion of scrambling is to consider\nthe norm (or equivalently the square) of the commutator of a pair\nof Hermitian operators $V$ and $W$ at different times. For the purposes\nof the present chapter, we will also consider the system at finite temperature,\nwith inverse temperature $\\beta$. This leads to a relation with out-of-time-order\ncorrelators\n\n\\begin{align}\n-\\langle[V(0),W(t)]^{2}\\rangle_{\\beta} & =\\langle V(0)W(t)W(t)V(0)\\rangle_{\\beta}+\\langle W(t)V(0)V(0)W(t)\\rangle_{\\beta}\\nonumber \\\\\n & \\quad-\\langle W(t)V(0)W(t)V(0)\\rangle_{\\beta}-\\langle V(0)W(t)V(0)W(t)\\rangle_{\\beta}\\,.\\label{eq:commutator}\n\\end{align}\nFor sufficiently late times, the first two terms are simply the time-independent\ndisconnected diagram $\\langle WW\\rangle_{\\beta}\\langle VV\\rangle_{\\beta}$,\nwhile the last two terms are genuine out-of-time-order correlators.\nFor the 2d conformal field theories of interest here, these correlators\nmay be computed by continuing the Euclidean four-point function through\nthe second Riemann sheet \\cite{PhysRevLett.115.131603}, as we describe\nin detail later. These terms vary as a function of $t$, unlike the\ndisconnected terms, and from them a scrambling timescale may be extracted.\nIn the following section we describe in more detail the dependence\nof this timescale on the chosen operators. Briefly, one wishes to\nchoose operators that exhibit the longest scrambling timescale, so\none may use this commutator computation as a proxy for asking that\nthe longest timescale a generic state scrambles. There may of course\nexist special choices of operators with much shorter scrambling times,\nand likewise special choices with much longer times, such as those\nthat commute with the Hamiltonian.\n\nIn order to study these out-of-time-order correlators at finite temperature\nin conformal field theory we will begin with the Euclidean theory\non $S^{1}\\times\\mathbb{R}$. The correlators in this theory may be\nobtained by a conformal mapping from the complex plane. The circle\ndirection is to be periodically identified with period $\\beta$ and\ncorresponds to the imaginary time direction. The spatial direction\nis then necessarily of infinite extent. For the purposes of the present\nchapter we will study four-point correlators of primary operators, as\nwell as correlators of wavepackets of such operators. Four-point functions\nof primaries are expressed in the so-called conformal blocks of the\ntheory. In general, these conformal blocks are not known beyond infinite\nseries expansions. However there has been much progress in the literature\non obtaining asymptotic expansions of these conformal blocks in a\nvariety of limits, and we will make extensive use of these results\nin the following \\cite{Fitzpatrick:2014vua}.\n\nIn holographic theories, the graviton mode is dual to the stress energy\ntensor of the CFT, which in turn is a Virasoro descendant of the identity\noperator. Long distance bulk physics should be dominated by the propagation\nof this mode, so the limit where the identity block dominates the\nconformal block is of particular interest. Assuming this intermediate\nVerma module dominates the conformal block of the four-point function\n\\cite{PhysRevLett.115.131603} (as well as assuming large central\ncharge and large external conformal weight $h_{w}$) obtained a scrambling\ntime logarithmic in the central charge $c$ of the CFT\n\\begin{equation}\nt_{*}=\\frac{\\beta}{2\\pi}\\log\\frac{c}{h_{w}}\\label{eq:rstime}\n\\end{equation}\nsuggesting (at least if the result can be continued to values $h_{w}$\nof order 1) that conformal field theories exhibit a version of fast\nscrambling.\n\nIn this chapter we will study this problem in more detail. One immediate\nissue is that primary operators on their own do not exhibit the timescale\n\\eqref{eq:rstime}, but rather a thermalization timescale of order\n$\\beta$ or less. However the class of states obtained by acting on\nthe thermal state with a primary is not necessarily a good representative\nof a generic state, so this is not an immediate contradiction. To\nproceed we fold the primary operators into wavepackets, and consider\noptimizing the shape of the wavepacket to obtain the longest thermalization\ntime. When this is done, we find a timescale resembling \\eqref{eq:rstime}\ndoes indeed emerge. Next we examine the contribution of Verma modules\nwith higher conformal weights to the four-point function. While we\nfind the time-ordered four-point functions respect the familiar late-time\ndecoupling theorems, and can be ignored with respect to the identity\nblock, this is no longer true of the out-of-time-order correlators\nneeded to compute \\eqref{eq:commutator}. We compute the contributions\nof these higher intermediate states, and find these can indeed dominate\nthe commutator even when all the time-ordered correlators have a sensible\nholographic description in terms of bulk low energy effective field\ntheory. This implies that many of the bulk observables, defined over\nfinite ranges of time, that one might use to probe the black hole\ninformation problem, are not accessible using low energy effective\nfield theory. In this sense effective field theory does not predict\nits own demise.\n\n\\section{Scrambling and CFT Correlators}\n\nWe consider a thermal system described by a conformal field theory\nliving on a spatial real line $x$ with imaginary time $-it$ periodically\nidentified with period $\\beta$. We can map this spatially infinite\nthermal system to a CFT defined on the complex plane $z$ via the\nexponential map\n\\[\nz=\\exp\\left(\\frac{2\\pi}{\\beta}(x+t)\\right)\\,.\n\\]\nWe are interested in computing the 4-point functions that appear in\n\\eqref{eq:commutator} so to this end we consider four pair-wise local\noperators, inserted at distinct spatial positions as in fig.~\\ref{fig:localops}.\nWe therefore have, after conformal mapping\n\\[\n\\begin{aligned}z_{1} & =e^{\\frac{2\\pi}{\\beta}x_{1}}\\\\\nz_{2} & =e^{\\frac{2\\pi}{\\beta}x_{2}}\\\\\nz_{3} & =e^{\\frac{2\\pi}{\\beta}(x_{3}+t)}\\\\\nz_{4} & =e^{\\frac{2\\pi}{\\beta}(x_{4}+t)}\n\\end{aligned}\n\\]\nwhere we are interested in the limit $x_{1}\\to x_{2},\\,x_{3}\\to x_{4}$\nto reproduce the desired commutator.\n\\begin{figure}\n\\centering\\includegraphics[width=0.41\\textwidth]{localops} \\caption{\\label{fig:localops}The configuration of four pair-wise identical\nlocal operators, themselves separated by large $t$.}\n\\end{figure}\n\nThe spacetime dependence of the conformal blocks appearing in the\n4-point function will only depend on the cross-ratio $z=z_{12}z_{34}/z_{13}z_{24}$\n(and $\\bar{z}$) which is easily shown to be\n\\[\nz=\\frac{\\sinh\\left(\\frac{\\pi}{\\beta}(x_{1}-x_{2})\\right)\\sinh\\left(\\frac{\\pi}{\\beta}(x_{3}-x_{4})\\right)}{\\sinh\\left(\\frac{\\pi}{\\beta}(t-x_{1}+x_{3})\\right)\\sinh\\left(\\frac{\\pi}{\\beta}(t-x_{2}+x_{4})\\right)}\\,.\n\\]\nAs discussed in appendix \\ref{sec:Correlators-and-Conformal} we rescale\nthe 4-point function by the coincident 2-point functions, to scale\nout the operator norm. The rescaled correlators then depend only on\nthe cross-ratios as in \\eqref{eq:normcorr}.\n\nAs an example, let us consider the identity conformal block in a large\n$c$ limit, where the $V$ and $W$ operators have conformal weights\n$h_{v}$ and $h_{w}$ respectively. The large $c$ limit is to be\ntaken with $h_{w}/c$ fixed, and $h_{v}\\ll c$ fixed. The conformal\nblock $\\mathcal{F}(z)$ in this limit is computed in \\cite{Fitzpatrick:2014vua,Fitzpatrick:2015zha}\n\\begin{equation}\nz^{2h_{v}}\\mathcal{F}(z)\\approx\\left[\\frac{z\\alpha_{w}(1-z)^{(\\alpha_{w}-1)/2}}{1-(1-z)^{\\alpha_{w}}}\\right]^{2h_{v}}\\,,\\label{eq:prinblock}\n\\end{equation}\nwith $\\alpha_{w}=\\sqrt{1-24h_{w}/c}$. The real-time out-of-time-order\ncorrelator is obtained by continuing this block to the second Riemann\nsheet as described in \\cite{PhysRevLett.115.131603} and the leading\ncontribution to the rescaled commutator is\n\\begin{equation}\nz^{2h_{v}}\\mathcal{F}(z)\\approx\\left[\\frac{e^{-\\pi i(\\alpha_{w}-1)}z\\alpha_{w}(1-z)^{(\\alpha_{w}-1)/2}}{1-e^{-2\\pi i\\alpha_{w}}(1-z)^{\\alpha_{w}}}\\right]^{2h_{v}}\\sim\\left(\\frac{1}{1-\\frac{24\\pi ih_{w}}{cz}}\\right)^{2h_{v}}\\,.\\label{eq:identityblock}\n\\end{equation}\nLet us take a limit where $\\epsilon_{12}=x_{1}-x_{2}$ and $\\epsilon_{34}=x_{3}-x_{4}$\nare much smaller than $\\beta$, and without loss of generality set\n$x_{1}=0$. The cross-ratio is then approximately\n\\[\nz\\approx\\frac{\\pi^{2}}{\\beta^{2}}\\frac{\\epsilon_{12}\\epsilon_{34}}{\\sinh^{2}\\left(\\frac{\\pi}{\\beta}\\left(t+x_{3}\\right)\\right)}\n\\]\nprovided we stay away from light-like separations where $x_{3}\\to-t$.\nAs we see the conformal block on the second sheet has a simple limit\nas $\\epsilon_{12}$ and $\\epsilon_{34}\\to0$, when $z\\to0$, corresponding\nto the actual computation of the commutator\n\\begin{equation}\nz^{2h_{v}}\\mathcal{F}(z)\\approx\\left(\\frac{cz}{24\\pi ih_{w}}\\right)^{2h_{v}}\\,.\\label{eq:latetimeblock}\n\\end{equation}\nThe exponential decay of this quantity indicates the commutator between\n$V$ and $W$ becomes large after a time of order\n\\begin{equation}\nt=\\frac{\\beta}{4\\pi h_{v}}\\label{eq:primarytime}\n\\end{equation}\nshowing rapid thermalization of primary operators on a timescale much\nshorter than \\eqref{eq:rstime}.\n\nHowever the interesting physical question is whether generic states\nexhibit some notion of quantum scrambling on a longer timescale. To\nexplore this question in the current context of CFT 4-point functions,\nwe can then try to build more generic deformations of the thermal\ndensity matrix by acting with primary operators folded into wavepackets\nwith some characteristic spatial size $L$. Computing the 4-point\nfunction of these wavepackets, one can attempt to vary $L$ to maximize\nthe convoluted amplitude, then ask what thermalization timescale emerges.\n\nConcretely, we convolute the function \\eqref{eq:identityblock} with\nspatial Gaussian wavepackets with width $L$. We will choose $t,L$\nand the $x_{i}$ such that light-like singularities in $z$ are avoided.\nIn this regime, the resulting integral will be dominated by a saddle\npoint value of $z$, and the convoluted (rescaled) conformal block\nmay then be well approximated by simply substituting this value into\n\\eqref{eq:identityblock}. Given the simple form of \\eqref{eq:identityblock},\nwith a cusp at $z=1$, the optimal value for $L$ will be the one\nthat makes $z$ approach $1$.\n\nFor simplicity let us set $x_{1}+x_{2}=x_{3}+x_{4}=0$, and we will\nbuild Gaussian wavepackets in the variables $x_{1}-x_{2}=\\ell_{v}$\nand $x_{3}-x_{4}=\\ell_{w}$. To fix $L$ in terms of $z$, one is\ntherefore interested in the convolution\n\\begin{equation}\nz(t,L)=\\frac{4}{\\pi L^{2}}\\int_{0}^{\\infty}dl_{v}dl_{w}e^{-(l_{v}^{2}+l_{w}^{2})/L^{2}}\\frac{\\sinh\\left(\\frac{\\pi}{\\beta}l_{v}\\right)\\sinh\\left(\\frac{\\pi}{\\beta}l_{w}\\right)}{\\sinh\\left(\\frac{\\pi}{\\beta}\\left(t-\\frac{l_{v}}{2}+\\frac{l_{w}}{2}\\right)\\right)\\sinh\\left(\\frac{\\pi}{\\beta}\\left(t+\\frac{l_{v}}{2}-\\frac{l_{w}}{2}\\right)\\right)}\\,.\\label{eq:crossratiosmear}\n\\end{equation}\nThis formula is justified because the exponential variation of $z$\nwith $l_{v},l_{w}$ is much more rapid than power law variation of\nthe conformal block with $z$, so analyzing the convolution of $z$\nalone is sufficient to determine $l_{v}$ and $l_{w}$ and subsequently\n$L$. The integrand has light-like poles, however for suitable values\nof $t$ and $L$ these contributions to the smeared conformal block\ncan be made negligible. In this limit, the integrand can be well-approximated\nby simply\n\\[\nz(t,L)\\approx\\frac{4}{\\pi L^{2}}\\int_{0}^{\\infty}dl_{v}dl_{w}e^{-(l_{v}^{2}+l_{w}^{2})/L^{2}}\\frac{2\\sinh\\left(\\frac{\\pi}{\\beta}l_{v}\\right)\\sinh\\left(\\frac{\\pi}{\\beta}l_{w}\\right)}{\\cosh\\left(\\frac{2\\pi}{\\beta}t\\right)}\\,.\n\\]\nThis has saddle points when\n\\[\nl_{v}\\tanh\\left(\\frac{l_{v}\\pi}{\\beta}\\right)=\\frac{\\pi L^{2}}{2\\beta}\n\\]\nand likewise for $l_{w}$. The positive solutions are to be taken\ncorresponding to the limits of integration in \\eqref{eq:crossratiosmear}.\nIf we then ask that the resulting amplitude \\eqref{eq:identityblock}\nis maximized in magnitude, we find that we must choose $L\\sim\\beta$\nnear $t=0$. We choose not to change the shape of the wavepackets\nat time increases, and impose this condition for all values of $t$.\nAt the end we find the optimal value of $z$ is\n\\begin{equation}\nz_{sad}=\\mathrm{sech}\\left(\\frac{2\\pi}{\\beta}t\\right)\\label{eq:zsad}\n\\end{equation}\nup to constant factors of order $1$.\n\nLet us now return to the example of the identity conformal block continued\nto the second Riemann sheet as considered in \\cite{PhysRevLett.115.131603}.\nIn this case, the saddle point approximation to the (rescaled) convoluted\nblock function is for sufficiently late times\n\\begin{equation}\nz^{2h_{v}}\\mathcal{F}(z)\\approx\\left(\\frac{1}{1-\\frac{12\\pi ih_{w}}{c}e^{\\frac{2\\pi}{\\beta}(t-x)}}\\right)^{2h_{v}}\\label{eq:rscorrel}\n\\end{equation}\nwhere we have restored dependence on the spatial separation $x$ of\nthe centers of the wavepackets, and inserted the saddle point approximation\nvalue for $z$ \\eqref{eq:zsad} for $t\\gg\\beta$. It is helpful to\nplot this for sample parameters as in fig. \\ref{fig:scrambling-plot}.\nAs $t-x$ increases from $0$ to\n\\begin{equation}\nt_{*}=\\frac{\\beta}{2\\pi}\\log\\frac{c\\sqrt{\\log2}}{12\\pi h_{v}^{1/2}h_{w}}\\label{eq:scrambletime}\n\\end{equation}\nthe conformal block decreases in magnitude by a factor of about $1/2$.\nThis thermalization time may be viewed as a proxy for the true scrambling\ntime of the system, and shows the distinctive appearance of the logarithm\nof the system size. The formula is valid for $0<h_{v}\\ll c$, but\nideally one would want to argue this formula continues to hold as\n$h_{w}$ becomes of order $1$. Unfortunately it is not yet possible\nto prove this. We note fig. \\ref{fig:scrambling-plot} also shows\nin the late-time limit the asymptotic form \\eqref{eq:latetimeblock}\nis applicable and the timescale for variation is the much shorter\ntime \\eqref{eq:primarytime}.\n\nThe correlator of the wavepackets is given by \\eqref{eq:rscorrel}\nprovided one steers clear of the light-cone singularities in \\eqref{eq:crossratiosmear}\nwhich render the approximation \\eqref{eq:zsad} invalid. This is a\nsignature that even the wavepackets of primaries are not ideal representatives\nof a generic state, and retain regions of spacetime where thermalization\nhas not yet occurred, outside the light-cone of the wavepacket. Nevertheless\nfor the present purposes, the reduced state inside the light-cone\nappears to be well-thermalized according to the correlators, so this\nprocedure should yield a good measure of the global scrambling time.\nAgain it remains to be seen whether \\eqref{eq:scrambletime} holds\nin the case of most physical interest where $h_{w}$ is of order 1.\n\n\\begin{figure}\n\\includegraphics[width=0.45\\textwidth]{Fz-t-plot}\\qquad{}\\includegraphics[width=0.45\\textwidth]{scrambling-plot-real}\n\\caption{\\label{fig:scrambling-plot}Plot of function $|z^{2h_{v}}\\mathcal{F}(z)|=|F(z(t))|=1/\\left|1-12\\pi ih_{w}\\exp\\left(2\\pi/\\beta\\left(t-\\log c-x\\right)\\right)\\right|^{2h_{v}}$\nwhere $c=10^{7}$, $h_{v}=100$, $h_{w}=10$, $\\beta=2\\pi$ and $x=0$.\nHere $t_{*}=7.7$ according to \\eqref{eq:scrambletime}. In the right\npanel, a plot of $\\mathrm{Re}\\,F(z(t))$ is shown.}\n\\end{figure}\n\n\\section{Higher Weight Intermediate States}\n\nWe now turn our attention to the contribution of higher weight intermediate\nstates to the out-of-time order correlators, and will find the surprising\nresult that these may dominate over the identity block in the late-time\nlimit. Again we will assume we are taking $c\\gg1$ with $h_{w}/c$\nfixed and $h_{v}\\ll c$ fixed. In addition we will generalize from\nthe identity block to an intermediate channel with conformal weight\n$h_{p}$ fixed as $c\\to\\infty$.\n\nOur starting point is the formula for the conformal block at next-to-leading\norder in this large $c$ expansion of \\cite{Fitzpatrick:2015zha}\n\n\\[\n\\mathcal{F}(z)=\\mathcal{F}_{0}(z)\\left(\\frac{1-(1-z)^{\\alpha_{w}}}{\\alpha_{w}}\\right)^{h_{p}}{}_{2}F_{1}\\left(h_{p},h_{p},2h_{p},1-(1-z)^{\\alpha_{w}}\\right)\n\\]\nwhere $_{2}F_{1}(\\alpha,\\beta;\\gamma;z)$ is the Gauss hypergeometric\nfunction. To continue this expression to the second sheet we use the\nhypergeometric function identity \\cite{hypergeomexp}\n\\[\n\\frac{\\Gamma(h)^{2}}{\\Gamma(2h)}{}_{2}F_{1}(h,h;2h;w)=\\left(\\sum_{k=0}^{\\infty}\\frac{2\\left(h\\right)_{k}^{2}\\left(\\psi(k+1)-\\psi(h+k)\\right)}{k!^{2}}\\ensuremath{(1-w)^{k}}\\right)-\\log(1-w)\\,_{2}F_{1}(h,h,1;1-w)\n\\]\n valid for $|1-w|<1$, where $\\left(h\\right)_{k}$ is the Pochhammer\nsymbol, and $\\psi(a)$ is the digamma function. Continuing to the\nsecond sheet we then obtain\n\\begin{align}\n\\mathcal{F}_{II}(z) & =\\mathcal{F}_{0,II}(z)\\left(\\frac{1-e^{-i2\\pi\\alpha_{w}}(1-z)^{\\alpha_{w}}}{\\alpha_{w}}\\right)^{h_{p}}\\left(_{2}F_{1}\\left(h_{p},h_{p},2h_{p},1-e^{-i2\\pi\\alpha_{w}}(1-z)^{\\alpha_{w}}\\right)\\right.\\nonumber \\\\\n+ & \\left.2\\pi i\\alpha_{w}\\frac{\\Gamma(2h_{p})}{\\Gamma(h_{p})^{2}}\\,_{2}F_{1}(h_{p},h_{p},1;e^{-i2\\pi\\alpha_{w}}\\left(1-z\\right)^{\\alpha_{w}})\\right)\\,.\\label{eq:blocktwo}\n\\end{align}\nExpanding for small $h_{w}/c$ and $z\\ll1$ leads to\n\\[\n\\mathcal{F}_{II}(z)\\sim\\mathcal{F}_{0,II}(z)\\left(\\frac{z-\\frac{\\pi ih_{w}}{6c}}{\\alpha_{w}}\\right)^{h_{p}}\\left(1+i\\tan\\left(\\pi h_{p}\\right)-2\\pi^{2}iz^{1-2h_{p}}\\frac{\\Gamma(2h_{p})}{\\Gamma(2-2h_{p})\\Gamma(h_{p})^{4}\\sin\\left(2\\pi h_{p}\\right)}\\right)\\,.\n\\]\nThis ends up being dominated by the last term in the third factor,\nand in fact grows at late times. Even at early times ($z$ near 1)\nthe last term in \\eqref{eq:blocktwo} dominates over the other term\nin the third factor for $h_{p}>1$. The second factor in \\eqref{eq:blocktwo}\nrapidly approaches a constant much smaller than 1.\n\nThe upshot is the identity block dominates for a finite period of\ntime, however after\n\\[\nt_{*}\\approx\\frac{\\beta}{4\\pi}\\log\\left(\\frac{c}{h_{w}}\\right)\n\\]\nthe higher weight intermediate states take over. This late time sum\nover intermediate states apparently diverges when considered term\nby term. This would lead one to conclude the commutator grows initially\nwhile dominated by the identity block, but then may again decrease\nat later times, indicating a lack of true scrambling in the conformal\nfield theory.\n\nOne possible way to avoid this conclusion is to demand an infinite\ntower of higher weight intermediate primaries, such that the apparently\ndivergent sum might be resummed to a finite answer. However in the\nfollowing section we find contributions for $h_{p}\\gg c$ are actually\nsuppressed. We conclude that even a sparse spectrum of intermediate\nprimaries with weights $1<h_{p}\\ll c$ are sufficient to destroy or\ndrastically modify the onset of quantum chaos. In light of our previous\ndiscussion, this may simply mean such smeared primaries are still\nnot good representatives of generic states, and instead one would\nneed to consider commutators of much more general operators to see\nthe correct timescale for global thermalization, or quantum scrambling.\nAlternatively, it may happen that only operators dual to black hole\nstates efficiently scramble, and these must be reflected in a choice\nof external operators that do not couple at all (or only very weakly)\nto higher weight primaries, such that the identity block may dominate\nthe out-of-time order correlators.\n\nFor conformal field theories with holographic anti-de Sitter gravity\nduals, the implication of the higher intermediate channels is that\nthe bulk effective field theory breaks down when it is used to compute\nout-of-time-ordered correlators at finite time. On the other hand,\nthere is no indication of such a breakdown when time-ordered CFT correlators\nare computed (see also \\cite{Fitzpatrick:2016ive,Fitzpatrick:2016mjq}),\nwhich correspond to the boundary $S$-matrix of the bulk theory. To\nsee this we simply note that as higher dimensional operators in CFT$_{2}$\ncorrespond to interactions of increasing mass scale in AdS$_{3}$,\ndomination of all intermediate channels with dimension $h_{p}\\geq1$\nmeans that there would be a dual set of an infinite sequence of interactions\nin the gravitation theory in AdS$_{3}$. If these high scale interactions\naffect the infrared physics of the theory, then the standard decoupling\ntheorems of effective field theory such \\cite{PhysRevD.11.2856}\nbreak down.\n\nNow the usual measurements we perform can be well-approximated by\ntransition amplitudes, built out of time-ordered correlators which\nmay be computed as within effective field theory. It is only the particular\nset of observables corresponding to out-of-time-order correlators,\nor norms of commutators that exhibit this peculiar behavior. For the\nblack hole information problem this would seem to imply that contrary\nto expectations, commutators that measure limits on the causal propagation\nof information are indeed observables sensitive to the ultra-violet\nstructure of the theory, as long hinted at in perturbative string\ntheory computations \\cite{Lowe:1995pu,Lowe:1995ac}.\n\n\\section{Intermediate Channels with $h_{p}\\gg c$}\n\nSo far we have only considered intermediate channels with fixed $h_{p}\\ll c$.\nIt is also instructive to perform the same analysis for intermediate\nchannels with $h_{p}\\gg c$ where the limit is $h_{p}\\to\\infty$ with\n$c/h_{p}$, $h_{v}/h_{p}$ and $h_{w}/h_{p}$ fixed and small. For\nthis we consider equation (16) in \\cite{Zam87},\n\\begin{equation}\n\\mathcal{F}(z)=\\left(16q\\right)^{h_{p}-\\frac{c}{24}}z^{\\frac{c}{24}-2h_{v}}(1-z)^{\\frac{c}{24}-(h_{v}+h_{w})}\\theta_{3}(q)^{\\frac{c}{2}-8(h_{v}+h_{w})}H(c,h_{p},h_{i},q)\\label{eq:eq16zem87}\n\\end{equation}\nwhere the nome $q=e^{i\\pi\\tau}$ is related to the cross-ratio $z$\nby\n\\[\n\\tau=i\\frac{K'(z)}{K(z)}=i\\frac{K(1-z)}{K(z)}\n\\]\nwhere $K(z)$ is the complete elliptic integral with parameter\\footnote{We clarify that in most mathematical literature, the complete elliptic\nintegral $K$ is defined with the modulus $k$ as the argument. Our\n$z$ is related to $k$ through $z=k^{2}$. It is also common for\nmany mathematicians to use the symbol $m$ for our $z$.} $z$. Here $H$ is a function that is $1+O(1/h_{p})$ and\n\\begin{equation}\n\\theta_{3}(q)=\\sum_{n=-\\infty}^{\\infty}q^{n^{2}}\\,.\\label{eq:thetathree}\n\\end{equation}\n\nEq.~(\\ref{eq:eq16zem87}) has a branch cut at $z=1$ from the $1-z$\nfactor which will lead to the same analytic behavior for the intermediate\ncase $h_{p}\\ll c$, which we have previously considered. To see this\nwe expand the nome $q$ around $z=0$ to obtain\n\\[\nq=e^{i\\pi\\tau}=\\frac{z}{16}+\\frac{z^{2}}{32}+\\cdots\\,.\n\\]\nAs $\\theta_{3}(q)$ is regular near $q=0$, we see that on the principal\nsheet $\\mathcal{F}(z)$ goes to zero as $z\\to0$. Therefore the heavy\nintermediate channels are perfectly suppressed on the first Riemann\nsheet. Crossing the branch cut $z=1$ from above, the complete elliptic\nfunction $K(z)$ picks up an additional imaginary part \\cite{Bogner:2017vim}:\n\\[\n\\lim_{\\epsilon\\to0^{+}}K(z+i\\epsilon)=K(z)+2iK(1-z)\\,.\n\\]\nAnalyticity implies that on the second Riemann sheet the nome is now\n\\[\nq=\\exp\\left[-\\frac{\\pi K(1-z)}{K(z)+2iK(1-z)}\\right]=\\exp\\left[-\\frac{\\pi}{\\frac{K(z)}{K(1-z)}+2i}\\right]\\,.\n\\]\nTo expand this expression near $z=0$, we use\n\\[\n\\frac{K(z)}{K(1-z)}\\approx\\frac{\\pi}{4\\log2-\\log z}+\\mathcal{O}\\left(\\frac{z}{\\log^{2}z}\\right)\n\\]\nso that\n\\begin{equation}\nq\\approx e^{\\frac{i\\pi}{2}+\\frac{\\pi^{2}}{4\\log z}}\\,.\\label{eq:nomeexpan}\n\\end{equation}\nWe then need to expand \\eqref{eq:thetathree} near $q=i$. The expansion\nnear $q=1$ is\n\\[\n\\left|\\theta_{3}(q)\\right|\\approx\\left|\\frac{\\sqrt{\\pi}}{\\sqrt{1-q}}\\right|\n\\]\nbut we can obtain the expansion near $q=i$ by using the relation\n\\[\n\\left|\\theta_{3}(q)\\right|=\\left|\\frac{\\sqrt{\\pi}}{\\sqrt{\\log q}}\\theta_{3}\\left(e^{\\frac{\\pi^{2}}{\\log q}}\\right)\\right|\n\\]\nand substituting in \\eqref{eq:nomeexpan} to give $\\theta_{3}(q)$\nnear $q=i$ as\n\\begin{equation}\n\\left|\\theta_{3}(q)\\right|\\approx\\left|\\frac{\\sqrt{-2\\log z}}{\\sqrt{\\pi}}\\right|\\,.\\label{eq:nomeneari}\n\\end{equation}\nAssembling the various factors, we find again a dramatic enhancement\nof the higher weight channel on the second Riemann sheet arising from\nthe behavior \\eqref{eq:nomeneari}, compared to the behavior on the\nprincipal sheet. However when we compare to the $h_{p}=0$ expression\nof the previous section, the $z^{c/24}$ factor of \\eqref{eq:eq16zem87}\ndominates for small $z$ so we conclude they do not dominate versus\nthe identity channel (again modulo restrictions on the operator couplings\n$C_{p}$ of \\eqref{eq:blockdef}).\n\n\\section{Conclusions}\n\nIn this chapter we discussed the issue of smearing local operators in\na thermal CFT and its connection with quantum scrambling. We pointed\nout that the correct scrambling time should be identified with operators\nthat maximize the timescale of variation of the out-of-time ordered\ncorrelator, which may occur well before the asymptotic late-time limit.\nWe then examined a somewhat independent issue, that the higher intermediate\nstates with $0<h_{p}\\ll c$ can have large out-of-time ordered correlators.\nWe discussed the implications of this statement, which is that in\nthe AdS$_{3}$ gravity dual the UV dynamics and IR dynamics are no\nlonger decoupled when these observables are computed. This lack of\ndecoupling appears even when the usual time-ordered correlators, or\ntransition amplitudes satisfy the standard decoupling lore. When applied\nto scattering in $AdS_{3}$ black hole backgrounds this implies that\nthe commutators that lead one to conclude information is lost semiclassically,\nare in fact not computable without a full specification of the ultraviolet\nphysics of the theory. The ordinary bulk effective field theory does\nnot predict its own demise when computing these observables.\n\nAs for the appearance of a scrambling time of the form \\eqref{eq:rstime}\nwe have found a variant of this expression \\eqref{eq:scrambletime},\nvalid when the identity block dominates. The expression involves a\nterm of the form $\\beta/2\\pi\\log c$, but other significant terms\nare also present. If other intermediate primaries appear, with conformal\nweights fixed in a large $c$ limit, they will dominate the late-time\nbehavior and may completely spoil thermalization. It will be very\ninteresting to extend the range of validity of these expressions to\ndetermine whether there exist a class of 2d conformal field theories\nthat may be viewed as fast scramblers at finite temperature.\n\n\n\\chapter{Holographic Map for Cosmological Horizons}\\label{chap:map}\nWe propose a holographic map between Einstein gravity coupled to matter\nin a de Sitter background and large $N$ quantum mechanics of a system\nof spins. Holography maps a spin model with a finite dimensional Hilbert\nspace defined on a version of the stretched horizon into bulk gravitational\ndynamics. The full Hamiltonian of the spin model contains a non-local\npiece which generates chaotic dynamics, widely conjectured to be a\nnecessary part of quantum gravity, and a local piece which recovers\nthe perturbative spectrum in the bulk.\n\n\\section{Introduction}\n\nPrevious work has argued for a unitary, holographic description of\nblack hole dynamics via certain spin models \\cite{Lowe:2016mhi,Lowe:2017ehz}\ndefined on the stretched horizon \\cite{thorne1986black} of the black\nhole. These spin models have the common feature that non-local interactions\ngenerate chaotic dynamics, widely conjectured to be an integral part\nof a full quantum mechanical description of gravity \\cite{Sekino:2008he}.\nIn this chapter we argue that a similar approach works for the cosmological\nhorizon in de Sitter spacetime, given that the static patch metric\nhas a similar form to the metric in Schwarzschild coordinates. To\nthis end we will give an explicit prescription to map perturbative\nbulk fields to a quantum mechanical operator defined in the holographic\nspin model. This map will then allow us to construct a local Hamiltonian\nthat reproduces the classical energy of a perturbation around de Sitter\nspacetime. We argue that this local Hamiltonian, together with the\nnon-local long-range interaction necessary to generate chaotic dynamics,\ncan potentially be a viable description of de Sitter quantum gravity.\n\nBefore we begin, we will review relevant facts of the de Sitter space-time\nto establish our convention of notations. We mostly follow the conventions\nin Ref.~\\cite{Spradlin:2001pw}. Throughout the chapter we will restrict\nour discussion to $(1+3)$-dimensional space-time entirely, although\nthe methodology presented can in principle be applied to higher (or\nlower) dimensions. Our metric signatures are always mostly positive,\ni.e.~$(-++\\cdots)$.\n\nStatic coordinates cover only one triangular region in the Penrose\ndiagram (see Fig.~\\ref{penrose})\n\\begin{equation}\n\\dd s^{2}=-(1-\\frac{r^{2}}{\\ell^{2}})\\,\\dd t^{2}+\\frac{\\dd r^{2}}{1-\\frac{r^{2}}{\\ell^{2}}}+r^{2}\\,\\dd\\Omega^{2}\\label{eq:static}\n\\end{equation}\nwhere $\\dd\\Omega^{2}=\\dd\\theta^{2}+\\sin^{2}\\theta\\,\\dd\\varphi^{2}$\nis the line element on the unit 2-sphere $S^{2}$ and $\\ell$ is the\nradius of curvature of the de Sitter spacetime.\n\n\\begin{figure}\\centering\n\\begin{tikzpicture}[scale=1]\n    \\draw (-2,2) -- (2,2);\n    \\draw (-2,2) -- (-2,-2);\n    \\draw (-2,-2) -- (2,-2);\n    \\draw (2,-2) -- (2,2);\n    \\draw[->,dashed] (-2,-2) -- (2,2);\n    \\draw[->,dashed] (2,-2) -- (-2,2);\n    \\shade (0,0) -- (2,2) -- (2,-2) -- (0,0);\n    \\pgfmathsetmacro{\\e}{1.5}   % eccentricity\n    \\pgfmathsetmacro{\\a}{0.7}\n    \\pgfmathsetmacro{\\b}{(\\a*sqrt((\\e)^2-1)}\n    \\draw plot[domain=-1.66:1.66] ({\\a*cosh(\\x)+0.09},{\\b*sinh(\\x)});\n  \\end{tikzpicture} \\caption{Penrose diagram for de-Sitter spacetime, where shaded region is covered\nby the static coordinates. The stretched horizon (solid curve inside\nthe static patch) is defined as a hypersurface at fixed $r$.}\n\\label{penrose}\n\\end{figure}\n\n\n\\section{Mode Functions in de-Sitter}\n\n\\subsection{Static Patch}\n\nOur goal is to construct a spin model which reproduces the bulk spectrum\nin a de Sitter background. To proceed we first review some standard\nresults concerning mode functions in static de Sitter. For simplicity,\nwe will treat the massless minimally coupled scalar, and follow the\npoint of view of \\cite{Danielsson:2002qh} that with a cutoff to\nexclude the zero mode, the system can be quantized around the Bunch-Davies\n(or Euclidean) vacuum state. Had we been interested in the system\nincluding the zero-mode, this quantization preserving de Sitter isometries\nwould be inadmissible \\cite{Allen:1987tz}. This quantization of\nthe massless minimally coupled scalar around the Bunch-Davies vacuum\nis closely related to that of perturbative gravitons, as explained\nin \\cite{Bernar:2016zgq,Bernar:2018nww}. The results may then be\nstraightforwardly applied to other bulk modes once this case is understood.\n\nWe begin by considering modes in the static patch \\eqref{eq:static}.\nThe equation of motion for the free scalar field $\\Phi(t,r,\\theta,\\phi)$\nis\n\\[\n\\frac{\\partial_{t}^{2}\\Phi}{1-r^{2}/\\ell^{2}}-\\frac{\\partial_{r}[r^{2}(1-r^{2}/\\ell^{2})\\partial_{r}\\Phi]}{r^{2}}-\\frac{\\partial_{\\theta}(\\sin\\theta\\partial_{\\theta}\\Phi)}{r^{2}\\sin\\theta}-\\frac{\\partial_{\\varphi}^{2}\\Phi}{r^{2}\\sin^{2}\\theta}=0\\,.\n\\]\nSeparating variables, we have\n\\[\n\\Phi_{\\omega lm}(t,r,\\theta,\\varphi)=A_{\\omega l}e^{-i\\omega t}f_{\\omega l}(r)Y_{lm}(\\theta,\\varphi)\\,,\n\\]\nwhere $f_{\\omega l}(r)$ satisfies\n\\[\n(1-r^{2}/\\ell^{2})f''_{\\omega l}(r)+\\frac{2(1-2r^{2}/\\ell^{2})}{r}f'_{\\omega l}(r)+\\left(\\frac{\\omega^{2}}{1-r^{2}/\\ell^{2}}-\\frac{l(l+1)}{r^{2}}\\right)f_{\\omega l}(r)=0\\,.\n\\]\nWe pick the set of solutions that are regular at $r=0$ and find\n\\[\nf_{\\omega l}(r)=\\frac{(r/\\ell)^{l}}{\\ell}(1-r^{2}/\\ell^{2})^{i\\omega\\ell/2}{}_{2}{\\rm F}_{1}\\left(\\frac{l+i\\omega\\ell}{2},\\frac{l+i\\omega\\ell+3}{2};l+\\frac{3}{2};\\frac{r^{2}}{\\ell^{2}}\\right)\\,.\n\\]\nWe fix the normalization constant $A_{\\omega l}$ by computing the\nKlein-Gordon norm. This is defined on a spacelike surface $\\Sigma$\nby\n\\begin{align*}\n\\left\\langle f,g\\right\\rangle  & =-i\\int_{\\Sigma}\\dd\\Sigma\\,n^{\\lambda}\\,(f\\partial_{\\lambda}g^{*}-g^{*}\\partial_{\\lambda}f)\n\\end{align*}\nwhere $n^{\\lambda}$ is a timelike unit vector normal to $\\Sigma$.\nEvaluating this on a constant $t$ slice gives\n\\begin{equation}\n\\left\\langle f,g\\right\\rangle =-i\\int(f\\partial_{t}g^{\\star}-g^{\\star}\\partial_{t}f)\\frac{r^{2}\\,\\dd r\\,\\sin\\theta\\,\\dd\\theta\\,\\dd\\varphi}{1-r^{2}/\\ell^{2}}\\,.\\label{eq:innerprod}\n\\end{equation}\nComputing the mode normalization then gives\n\\[\n\\left\\langle \\Phi_{\\omega lm},\\Phi_{\\omega'l'm'}\\right\\rangle =A_{\\omega l}A_{\\omega'l}^{\\star}(\\omega+\\omega')\\delta_{ll'}\\delta_{mm'}\\int_{0}^{\\ell}\\frac{f_{\\omega l}(r)f_{\\omega'l}^{\\star}(r)\\,r^{2}\\,\\dd r}{1-r^{2}/\\ell^{2}}\\,.\n\\]\nUsing the equation of motion for $f_{\\omega l}(r)$ we have\n\\[\n[r^{2}(1-r^{2}/\\ell^{2})f'_{\\omega l}(r)]'\\,f_{\\omega'l}^{\\star}(r)+\\left(\\frac{\\omega^{2}r^{2}}{1-r^{2}/\\ell^{2}}-l(l+1)\\right)f_{\\omega l}(r)f_{\\omega'l}^{\\star}(r)=0\n\\]\nand likewise\n\\[\n[r^{2}(1-r^{2}/\\ell^{2})f_{\\omega'l}^{\\star\\prime}(r)]'\\,f_{\\omega l}(r)+\\left(\\frac{\\omega'^{2}r^{2}}{1-r^{2}/\\ell^{2}}-l(l+1)\\right)f_{\\omega'l}^{\\star}(r)f_{\\omega l}(r)=0\\,.\n\\]\nSubtracting we have\n\\[\n\\frac{(\\omega^{2}-\\omega'^{2})r^{2}}{1-r^{2}/\\ell^{2}}f_{\\omega l}(r)f_{\\omega'l}^{\\star}(r)=[r^{2}(1-r^{2}/\\ell^{2})f_{\\omega'l}^{\\star\\prime}(r)]'\\,f_{\\omega l}(r)-[r^{2}(1-r^{2}/\\ell^{2})f'_{\\omega l}(r)]'\\,f_{\\omega'l}^{\\star}(r)\\,,\n\\]\nand integrating by parts, we have\n\\[\n\\int_{0}^{\\ell}\\frac{(\\omega^{2}-\\omega'^{2})r^{2}}{1-r^{2}/\\ell^{2}}f_{\\omega l}(r)f_{\\omega'l}^{\\star}(r)=r^{2}(1-r^{2}/\\ell^{2})f_{\\omega'l}^{\\star\\prime}(r)\\,f_{\\omega l}(r)-r^{2}(1-r^{2}/\\ell^{2})f'_{\\omega l}(r)\\,f_{\\omega'l}^{\\star}(r)\\Big|_{0}^{\\ell}\\,.\n\\]\nThis gives\n\\[\n\\int_{0}^{\\ell}\\frac{r^{2}\\,\\dd r}{1-r^{2}/\\ell^{2}}f_{\\omega l}(r)f_{\\omega'l}^{\\star}(r)=\\frac{\\ell^{2}}{\\omega^{2}-\\omega'^{2}}\\lim_{r\\to\\ell}\\,(1-r^{2}/\\ell^{2})\\left[f_{\\omega'l}^{\\star\\prime}(r)\\,f_{\\omega l}(r)-f'_{\\omega l}(r)\\,f_{\\omega'l}^{\\star}(r)\\right]\\,.\n\\]\nUsing the hypergeometric identity near $z=1$\n\\[\n_{2}{\\rm F}_{1}(a,b,c,z)=\\frac{\\Gamma(c)\\Gamma(c-a-b)}{\\Gamma(c-a)\\Gamma(c-b)}+\\frac{\\Gamma(c)\\Gamma(a+b-c)}{\\Gamma(a)\\Gamma(b)}(1-z)^{c-a-b}\n\\]\nwe can expand $f_{\\omega l}(r)$ near $r=\\ell$ to give\n\\[\n\\ell f_{\\omega l}(r)\\approx\\frac{\\Gamma(l+\\frac{3}{2})\\Gamma(-i\\ell\\omega)}{\\Gamma\\left(\\frac{l-i\\omega\\ell}{2}\\right)\\Gamma\\left(\\frac{l-i\\omega l+3}{2}\\right)}(1-r^{2}/\\ell^{2})^{\\frac{i\\ell\\omega}{2}}+\\frac{\\Gamma(l+\\frac{3}{2})\\Gamma(i\\ell\\omega)}{\\Gamma\\left(\\frac{l+i\\omega\\ell}{2}\\right)\\Gamma\\left(\\frac{l+i\\omega l+3}{2}\\right)}(1-r^{2}/\\ell^{2})^{-\\frac{i\\ell\\omega}{2}}\\,.\n\\]\nLetting\n\\[\nB_{\\omega l}=\\frac{\\Gamma(l+\\frac{3}{2})\\Gamma(i\\ell\\omega)}{\\Gamma\\left(\\frac{l+i\\omega\\ell}{2}\\right)\\Gamma\\left(\\frac{l+i\\omega l+3}{2}\\right)}\n\\]\nwe see that we have\n\\[\n\\ell f_{\\omega l}(r)\\approx B_{\\omega l}^{\\star}(1-r^{2}/\\ell^{2})^{\\frac{i\\ell\\omega}{2}}+B_{\\omega l}(1-r^{2}/\\ell^{2})^{-\\frac{i\\ell\\omega}{2}}\n\\]\nand\n\\[\nf'_{\\omega l}(r)\\approx\\frac{-i\\omega}{1-r^{2}/\\ell^{2}}\\left[B_{\\omega l}^{\\star}(1-r^{2}/\\ell^{2})^{\\frac{i\\ell\\omega}{2}}-B_{\\omega l}(1-r^{2}/\\ell^{2})^{-\\frac{i\\ell\\omega}{2}}\\right]\\,.\n\\]\nMultiplying $f_{\\omega l}(r)$ and $f'_{\\omega l}(r)$ and dropping\nterms that are rapidly oscillating as $|\\omega-\\omega'|>0$ and $r\\to\\ell$,\nwe find that\n\\begin{equation}\n\\int_{0}^{\\ell}\\frac{r^{2}\\,\\dd r}{1-r^{2}/\\ell^{2}}f_{\\omega l}(r)f_{\\omega'l}^{\\star}(r)=\\lim_{r\\to\\ell}\\frac{2|B_{\\omega l}|^{2}}{\\omega-\\omega'}\\sin\\left[\\frac{\\left(\\omega-\\omega'\\right)\\ell}{2}\\log\\left(\\frac{1}{1-r^{2}/\\ell^{2}}\\right)\\right]\\label{eq:radialint}\n\\end{equation}\nUsing\n\\[\n\\lim_{C\\to\\infty}\\frac{\\sin Cx}{x}=\\pi\\delta(x)\n\\]\nwe have\n\\[\n\\int_{0}^{\\ell}\\frac{r^{2}\\,\\dd r}{1-r^{2}/\\ell^{2}}f_{\\omega l}(r)f_{\\omega'l}^{\\star}(r)=2\\pi|B_{\\omega l}|^{2}\\delta(\\omega-\\omega')\n\\]\nor\n\\begin{equation}\n\\left\\langle \\Phi_{\\omega lm},\\Phi_{\\omega'l'm'}\\right\\rangle =4\\pi|A_{\\omega l}|^{2}|B_{\\omega l}|^{2}\\delta_{ll'}\\delta_{mm'}\\omega\\delta(\\omega-\\omega')\\,.\\label{eq:staticnorm}\n\\end{equation}\nIf we normalize according to\n\\[\n\\left\\langle \\Phi_{\\omega lm},\\Phi_{\\omega'l'm'}\\right\\rangle =\\delta_{ll'}\\delta_{mm'}\\omega\\delta(\\omega-\\omega')\\,,\n\\]\nwe need to pick $A_{\\omega l}$ such that\n\\[\n|A_{\\omega l}|^{2}=\\frac{1}{4\\pi|B_{\\omega l}|^{2}}\\,.\n\\]\n\n\n\\subsection{Flat Slicing}\n\nNow let us consider the analogous problem for modes in the flat slicing.\nThe metric takes the form\n\\[\n\\dd s^{2}=-\\dd\\tau^{2}+e^{2\\tau/\\ell}\\dd\\vec{x}^{2}=-\\dd\\tau^{2}+e^{2\\tau/\\ell}(\\dd\\rho^{2}+\\rho^{2}\\dd\\theta^{2}+\\rho^{2}\\sin^{2}\\theta\\dd\\varphi^{2})\n\\]\nwhere $\\tau\\in(-\\infty,+\\infty)$ and $\\rho\\in(0,+\\infty)$. The wave\nequation for the massless minimally coupled scalar is given by\n\\[\n\\partial_{\\tau}^{2}\\phi+\\frac{3}{\\ell}\\partial_{\\tau}\\phi-e^{-2\\tau/\\ell}\\Delta\\phi=0\n\\]\nwhere $\\Delta\\phi$ is the usual spatial Laplacian operator\n\\[\n\\Delta\\phi=\\partial_{\\rho}^{2}\\phi+\\frac{2}{\\rho}\\partial_{\\rho}\\phi+\\frac{\\partial_{\\theta}^{2}\\phi}{\\rho^{2}}+\\frac{\\partial_{\\theta}\\phi}{\\rho^{2}\\tan\\theta}+\\frac{\\partial_{\\varphi}^{2}\\phi}{\\rho^{2}\\sin^{2}\\theta}\\,.\n\\]\nSeparating variables, we use the ansatz\n\\[\n\\phi_{klm}(\\tau,\\rho,\\theta,\\varphi)=T_{k}(\\tau)R_{kl}(\\rho)Y_{lm}(\\theta,\\varphi)\n\\]\nwhere $T_{k}(\\tau)$ satisfies\n\\[\nT''(\\tau)+\\frac{3}{\\ell}T'(\\tau)+k^{2}e^{-2\\tau/\\ell}T(\\tau)=0\n\\]\nand $R_{kl}(\\rho)$ satisfies\n\\[\nR''(\\rho)+\\frac{2}{\\rho}R'(\\rho)+\\left(k^{2}-\\frac{l(l+1)}{\\rho^{2}}\\right)R(\\rho)=0\\,.\n\\]\nAssuming regularity at $\\rho=0$ we can solve for $R(\\rho)$\n\\[\nR_{kl}(\\rho)=C_{kl}\\,j_{l}(k\\rho)\n\\]\nwhere $j_{l}(x)$ is the spherical Bessel function of first kind $j_{l}(x)=\\sqrt{\\frac{\\pi}{2x}}J_{l+\\frac{1}{2}}(x)$.\nWe will determine the normalization constant $C_{kl}$ later.\n\nThe equation for $T(\\tau)$ can be solved to give\n\\[\nT_{k}(\\tau)=c_{1}e^{ik\\ell e^{-\\tau/\\ell}}\\left(1-ik\\ell e^{-\\tau/\\ell}\\right)+c_{2}e^{-ik\\ell e^{-\\tau/\\ell}}\\left(1+ik\\ell e^{-\\tau/\\ell}\\right)\n\\]\nor, in terms of the conformal time $\\eta=-\\ell e^{-\\tau/\\ell}$\n\\[\nT_{k}(\\tau)=c_{1}e^{-ik\\eta}\\left(1+ik\\eta\\right)+c_{2}e^{ik\\eta}\\left(1-ik\\eta\\right)\\,.\n\\]\nWe assume Bunch-Davies vacuum and therefore pick the special solution\n\\[\nT_{k}(\\eta)=e^{-ik\\eta}\\left(1+ik\\eta\\right)\n\\]\nand absorb the normalization constant into $C_{kl}$, which we will\nfix now. The mode functions are normalized according to the Klein-Gordon\nnorm\n\\[\n\\left\\langle f,g\\right\\rangle =-i\\int_{\\Sigma}(f\\partial_{\\mu}g^{\\star}-g^{\\star}\\partial_{\\mu}f)\\,n^{\\mu}\\sqrt{\\gamma}\\,\\dd^{3}x\\,.\n\\]\nHere $\\Sigma$ is a spacelike hypersurface with unit norm $n^{\\mu}$\nand $\\sqrt{\\gamma}$ is the spatial volume element. We pick the $\\tau=0$\ntimeslice in the flat slicing since the metric at $\\tau=0$ is conveniently\nthe Minkowski metric. In addition, we have $\\partial_{\\tau}=\\partial_{\\eta}$\non the $\\tau=0$ timeslice. We therefore have\n\\[\n\\left\\langle f,g\\right\\rangle =-i\\int(f\\partial_{\\tau}g^{\\star}-g^{\\star}\\partial_{\\tau}f)\\,\\rho^{2}\\,\\dd\\rho\\,\\sin\\theta\\,\\dd\\theta\\,\\dd\\varphi\\,.\n\\]\nWe use this to fix the normalization factor $C_{kl}$. We have, for\nthe $\\phi_{klm}$ modes on $\\tau=0$\n\\[\n\\partial_{\\tau}\\phi_{klm}=-C_{kl}\\,k^{2}\\ell\\,e^{ik\\ell}j_{l}(k\\rho)\\,Y_{lm}(\\theta,\\varphi)\\,.\n\\]\nTherefore\n\\[\n\\left\\langle \\phi_{klm},\\phi_{k'l'm'}\\right\\rangle =i\\ell C_{kl}C_{k'l'}^{\\star}\\,\\delta_{ll'}\\delta_{mm'}e^{i(k-k')\\ell}\\int[(1-ik\\ell)k'^{2}-(1+ik'\\ell)k^{2}]j_{l}(k\\rho)j_{l}(k'\\rho)\\rho^{2}\\,\\dd\\rho\\,.\n\\]\nUsing the orthogonality of spherical Bessel functions\n\\[\n\\int_{0}^{\\infty}\\rho^{2}j_{l}(u\\rho)j_{l}(v\\rho)\\,\\dd\\rho=\\frac{\\pi}{2u^{2}}\\delta(u-v)\n\\]\nwe have\n\\[\n\\left\\langle \\phi_{klm},\\phi_{k'l'm'}\\right\\rangle =\\ell^{3}\\,\\pi k\\,|C_{kl}|^{2}\\,\\delta_{ll'}\\delta_{mm'}\\delta(k\\ell-k'\\ell)\\,.\n\\]\nWe therefore find\n\\[\nC_{kl}=\\frac{1}{\\sqrt{\\pi k\\ell}}\\frac{1}{\\ell}\\,,\n\\]\nand the full solution is therefore\n\\[\n\\phi_{klm}(\\tau,\\rho,\\theta,\\varphi)=\\frac{1}{\\ell\\sqrt{\\pi k\\ell}}\\,e^{-ik\\eta}(1+ik\\eta)\\,j_{l}(k\\rho)\\,Y_{lm}(\\theta,\\varphi)\\,.\n\\]\n\n\n\\subsection{Matching Modes Across the Cosmological Horizon}\n\n\\begin{figure}\n\\centering\n\\includegraphics{penrose}\\caption{\\label{fig:Penrose-diagram-for}Penrose diagram for the de-Sitter spacetime. Flat\nslicing modes cover the right upper half of the diagram and are matched\nto static patch modes on the line $u=0$. Positive frequency modes\nin the Bunch-Davies vacuum are then analytic in the lower-half-complex\n$v-$plane.}\n\n\\end{figure}\n\nFollowing \\cite{PhysRevD.14.870}, modes in the flat slicing may be viewed\nas modes entangled across the left and right static patches. In Kruskal\ncoordinates in the right static patch $u=e^{x^{-}/\\ell}$ and $v=-e^{-x^{+}/\\ell}$\n(other choices of sign generate the other patches in static coordinates)\nwhere $x^{\\pm}=t\\pm r^{\\star}$ and\n\\[\nr^{\\star}=\\frac{\\ell}{2}\\log\\frac{1+r/\\ell}{1-r/\\ell}\\approx\\frac{\\ell}{2}\\log\\frac{2}{1-r/\\ell}\n\\]\nwe have\n\\[\n\\Phi_{\\omega lm}\\approx A_{\\omega l}(B_{\\omega l}^{\\star}2^{i\\omega\\ell}|v|^{i\\omega\\ell}+B_{\\omega l}2^{-i\\omega\\ell}|u|^{-i\\omega\\ell})Y_{lm}(\\theta,\\varphi)\n\\]\n near the cosmological horizon.\n\nWe now define a mode function $\\Phi_{\\omega lm}^{+}$ which is non-zero\non the right quadrant, and a $\\Phi_{\\omega lm}^{-}$ which is non-zero\non the left quadrant. We require that the linear combination\n\\[\n\\bar{\\Phi}_{\\omega lm}=c\\,\\Phi_{\\omega lm}^{+}+d\\,\\Phi_{\\omega lm}^{-}\n\\]\nbe analytic in the lower half $v-$plane on the past horizon on the\nright (and the past horizon on the left), i.e. the surface $u=0$.\nOn the right quadrant we can rewrite the function $(-v)^{i\\omega\\ell}=(e^{i\\pi}v)^{i\\omega\\ell}=e^{-\\pi\\omega\\ell}v^{i\\omega\\ell}$.\nTherefore, the linear combination $\\Phi_{\\omega lm}^{+}+e^{-\\pi\\omega\\ell}\\Phi_{\\omega lm}^{-}$\nis analytic in the lower-half-complex $v-$plane at $u=0$ (see fig.\n\\ref{fig:Penrose-diagram-for}) corresponding to a combination of\npositive frequency flat-slicing modes. The properly normalized mode\nis\n\\begin{equation}\n\\bar{\\Phi}_{\\omega lm}=\\frac{1}{\\sqrt{2\\sinh(\\pi\\omega\\ell)}}\\left(e^{\\pi\\omega\\ell/2}\\Phi_{\\omega lm}^{+}+e^{-\\pi\\omega\\ell/2}\\Phi_{\\omega lm}^{-}\\right)\\,.\\label{eq:entmode}\n\\end{equation}\nThis mode is analytic in the lower-half $v$-plane for either choice\nof sign for $\\omega$, so should be identified with a linear combination\nof positive $k$ flat-slicing modes.\n\nWe can now expand a quantum field operator $\\hat{\\Phi}$ in terms\nof normal modes\n\\begin{align*}\n\\hat{\\Phi} & =\\int_{0}^{\\infty}dk\\sum_{lm}\\phi_{klm}a_{klm}+{\\rm h.c.\\,(flat\\,slicing)}\\\\\n & =\\int_{0}^{\\infty}d\\omega\\sum_{lm}\\Phi_{\\omega lm}^{+}b_{\\omega lm}^{+}+\\Phi_{\\omega lm}^{{\\rm -}}b_{\\omega lm}^{{\\rm -}\\dagger}+{\\rm h.c.\\,(static\\,patches)}\\\\\n & =\\int_{-\\infty}^{\\infty}d\\omega\\sum_{lm}\\bar{\\Phi}_{\\omega lm}c_{\\omega lm}+{\\rm h.c.\\,(entangled\\,static\\,patches)}\\,.\n\\end{align*}\nWe define the Bunch-Davies vacuum $|0\\rangle$ to be annihilated by\nall $a_{klm}$ with $k>0$\n\\[\na_{klm}|0\\rangle=0\n\\]\nwhich coincides with\n\\[\nc_{\\omega lm}\\left|0\\right\\rangle =0\n\\]\nfor $-\\infty<\\omega<\\infty$. We similarly define the static patch\nvacuum $|\\Omega\\rangle$ to be annihilated by all $b_{\\omega lm}^{\\pm}$\nwith $\\omega>0$\n\\[\nb_{\\omega lm}^{\\pm}|\\Omega\\rangle=0\\,.\n\\]\nFrom the relation we obtained between $\\Phi^{\\pm}$ and $\\bar{\\Phi}$\nwe obtain the relations between $b_{\\omega lm}^{\\pm}$ and $c_{\\omega lm}$\n\\begin{align*}\nc_{\\omega lm} & =\\begin{cases}\n\\frac{1}{\\sqrt{2\\sinh{\\pi\\omega\\ell}}}\\left(e^{\\pi\\omega\\ell/2}b_{\\omega lm}^{+}+e^{-\\pi\\omega\\ell/2}b_{\\omega lm}^{-\\dagger}\\right) & \\omega>0\\\\\n\\frac{1}{\\sqrt{2\\sinh{\\pi\\omega\\ell}}}\\left(e^{\\pi\\omega\\ell/2}b_{\\omega lm}^{+\\dagger}+e^{-\\pi\\omega\\ell/2}b_{\\omega lm}^{-}\\right) & \\omega<0\\,.\n\\end{cases}\n\\end{align*}\nAs usual, the vacuum state $\\left|0\\right\\rangle $ becomes a thermal\ndensity matrix in the right static patch when the modes $b_{\\omega lm}^{-}$\nare traced over.\n\nWe now need to compute the overlap of modes $\\Phi_{\\omega lm}$ with\n$\\phi_{\\omega lm}$ to construct the Bogoliubov transformation. In\norder to perform the integrals, we need the coordinate transformation\nbetween $(t,r)$ and $(\\eta,\\rho)$. We define null coordinates in\nthe flat slicing\n\\[\nU=\\frac{\\eta-\\rho}{2}\\qquad V=\\frac{\\eta+\\rho}{2}\n\\]\nleading to the metric. In the flat slicing using the $(\\eta,\\rho)$\ncoordinates the metric is\n\\[\n\\dd s^{2}=\\frac{\\ell^{2}}{\\eta^{2}}(-\\dd\\eta^{2}+\\dd\\rho^{2}+\\rho^{2}\\dd\\Omega^{2})\n\\]\nwhich in terms of $(U,V)$ coordinates becomes\n\\[\n\\dd s^{2}=\\frac{\\ell^{2}}{(U+V)^{2}}(-4\\dd U\\dd V+(V-U)^{2}\\dd\\Omega^{2})\\,.\n\\]\nIn the static patch, we define null coordinates $(u,v)$\n\\[\nu=e^{x^{-}/\\ell}\\,,v=-e^{-x^{+}/\\ell}\n\\]\nand one verifies that the metric is\n\\[\n\\dd s^{2}=\\frac{\\ell^{2}}{(1-uv)^{2}}(-4\\dd u\\dd v+(1+uv)^{2}\\dd\\Omega^{2})\\,.\n\\]\nWe see that the relation between $(u,v)$ and $(U,V)$ is simply\n\\[\nU=-\\frac{\\ell}{u}\\qquad V=\\ell v\n\\]\nwhich gives\n\\[\n\\eta=-\\frac{\\ell}{u}+\\ell v\\qquad\\rho=\\frac{\\ell}{u}+\\ell v\\,.\n\\]\nThe flat slicing mode function therefore becomes\n\\[\n\\phi_{klm}=\\frac{1}{\\ell}\\frac{1}{\\sqrt{\\pi k\\ell}}\\,e^{ik\\ell(\\frac{1}{u}-v)}\\left[1-ik\\ell\\left(\\frac{1}{u}-v\\right)\\right]\\,\\frac{\\sin(k\\ell(v+1/u)-l\\pi/2)}{k\\ell(v+1/u)}\\,Y_{lm}(\\theta,\\varphi)\n\\]\nwhere we have used the behavior of spherical Bessel function at infinity\n\\[\n\\lim_{\\rho\\to\\infty}j_{l}(k\\rho)=\\frac{\\sin(k\\rho-l\\pi/2)}{k\\rho}\\,.\n\\]\nNear the past horizon on the left patch, $u\\to0$ with $v$ fixed,\nthe flat slice mode becomes\n\\[\n\\phi_{klm}=\\frac{1}{\\ell}\\frac{-i}{\\sqrt{\\pi k\\ell}}\\,e^{ik\\ell(\\frac{1}{u}-v)}\\sin(k\\ell(v+1/u)-l\\pi/2)\\,Y_{lm}(\\theta,\\varphi)\\,.\n\\]\nUsing the identity $\\sin z=(e^{iz}-e^{-iz})/2i$ we can rewrite the\nflat slice mode function as\n\\begin{align*}\n\\phi_{klm} & =\\frac{1}{\\ell}\\frac{-1}{2\\sqrt{\\pi k\\ell}}\\,e^{ik\\ell(\\frac{1}{u}-v)}(i^{-l}e^{ik\\ell(v+1/u)}-i^{l}e^{-ik\\ell(v+1/u)})Y_{lm}(\\theta,\\varphi)\\\\\n & =\\frac{1}{\\ell}\\frac{1}{2\\sqrt{\\pi k\\ell}}(i^{l}e^{-2ik\\ell v}-i^{-l}e^{2ik\\ell/u})Y_{lm}(\\theta,\\varphi)\\sim\\frac{1}{\\ell}\\frac{i^{l}}{2\\sqrt{\\pi k\\ell}}e^{-2ik\\ell v}Y_{lm}(\\theta,\\varphi)\\,.\n\\end{align*}\nWe have shown above that near the past horizon the static patch mode\nis\n\\[\n\\Phi_{\\omega lm}=A_{\\omega l}B_{\\omega l}^{\\star}(-v)^{i\\omega\\ell}2^{i\\omega\\ell}Y_{lm}(\\theta,\\varphi)\\,.\n\\]\nOn the past horizon the Klein-Gordon norm is\n\\[\n\\left\\langle f,g\\right\\rangle =-i\\ell^{2}\\int\\dd\\Omega\\dd v\\,(f\\partial_{v}g^{\\star}-g^{\\star}\\partial_{v}f)=i\\ell^{2}\\int_{-\\infty}^{0}\\dd\\Omega\\left(2\\int g^{\\star}\\partial_{v}f\\,\\dd v-g^{\\star}f\\Big|_{0}^{-\\infty}\\right)\\,.\n\\]\nSince we have\n\\[\n\\partial_{v}\\Phi_{\\omega lm}=i\\omega\\ell v^{-1}\\Phi_{\\omega lm}\n\\]\nadding a small imaginary part to $\\omega$ and $k$ to dampen the\noscillation of $(-v)^{i\\omega\\ell}$ and $e^{-ikv}$ we have, since\nthe boundary term vanishes,\n\\[\n\\left\\langle \\Phi_{\\omega lm},\\phi_{klm}\\right\\rangle =\\frac{(-i)^{l}}{\\sqrt{\\pi k\\ell}}A_{\\omega l}B_{\\omega l}^{\\star}2^{i\\omega\\ell}\\int_{0}^{+\\infty}e^{-2ik\\ell v}v^{i\\omega\\ell-1}\\,\\dd v\n\\]\nwhere we replaced $v\\to-v$. This can be evaluated to give\n\\[\n\\left\\langle \\Phi_{\\omega lm},\\phi_{klm}\\right\\rangle =\\frac{(-i)^{l}}{\\sqrt{\\pi k\\ell}}A_{\\omega l}B_{\\omega l}^{\\star}(ik\\ell)^{-i\\omega\\ell}\\Gamma(i\\omega\\ell)\\,.\n\\]\nBy choosing the phase of $A_{\\omega l}$ appropriately such that\n\\[\nA_{\\omega l}B_{\\omega l}^{\\star}=\\frac{1}{\\sqrt{4\\pi}}\n\\]\nwe finally have\n\\[\n\\left\\langle \\Phi_{\\omega lm},\\phi_{klm}\\right\\rangle =\\frac{(-i)^{l}}{\\sqrt{k\\ell}}\\frac{(ik\\ell)^{-i\\omega\\ell}\\Gamma(i\\omega\\ell)}{2\\pi}\\,.\n\\]\nWith the Bogoliubov transformation at hand, we can now map modes in\nthe flat slicing to entangled modes in the left and right static patch.\nThese in turn define modes in the upper quadrant of the static slicing\nby continuation.\n\n\\section{Holographic Map}\n\nOur goal is to build a holographic version of the bulk theory that\nmight be viewed as living on the so-called ``stretched horizon''\n\\cite{thorne1986black}. The essence of the black hole membrane paradigm\nis that to an external observer outside the horizon, the black hole\nhorizon behaves more or less like a hydrodynamic membrane with properties\nsuch as resistance and viscosity. Quantum mechanically, the stretched\nhorizon acts as a mirror \\cite{Hayden:2007cs} which scrambles and\nreflects information sent into it. Our viewpoint in this chapter is\nthat since the static patch of de-Sitter has essentially the same\nmathematical form as the Schwarzschild metric, one ought to be able\nto construct a similar stretched horizon theory for static de-Sitter.\nWe further assume that the horizon entropy of de Sitter is to be matched\nwith the logarithm of the Hilbert space dimension. Thus, the stretched\nhorizon theory will be a finite dimensional quantum mechanical system.\n\nUsually the stretched horizon is defined as the constant $r$ surface\nsuch that the local temperature measured by a fiducial observer (constant\n$r$) is the Planck temperature. When redshifted down to $r=0$, this\nwill match the Hawking temperature. In other words, one usually defines\n$r_{\\star}$ such that\n\\begin{equation}\n\\frac{1}{2\\pi\\ell_{p}}\\sqrt{1-r_{\\star}^{2}/\\ell^{2}}=T_{{\\rm H}}=\\frac{1}{2\\pi\\ell}\\,,\\label{eq:usualrs}\n\\end{equation}\nwhere $\\ell_{p}$ is the Planck length.\n\nAs it stands, the bulk Hilbert space is infinite dimensional, labeled\nby the oscillators $c_{\\omega lm}$ where $\\omega\\in\\mathbb{R}$,\nand the angular momentum ranges up to infinity. Each oscillator mode\ncreates a mode entangled across both static patches, with a stress-energy\ntensor non-singular on the future cosmological horizon on the right\npatch.\n\nAs a first step, we can discretize the sphere in coordinate space.\nThere are many possibilities for such a discretization, and the details\nwill not be too important for us, except to note that such a discretization\nwill produce an effective cutoff $l_{max}$ on the angular momentum.\n\nLikewise, it is necessary to discretize the frequency $\\omega$ which\ncan in turn be viewed as a radial quantum number. This discretization\nmay then be viewed as a kind of regulator for the radial coordinate.\nIn order to produce a useful effective field theory with such a cutoff\nwe choose a finite set of frequencies in the range\n\\begin{equation}\n\\frac{1}{\\ell_{p}n_{UV}}>|\\omega|\\geq\\frac{\\pi}{\\ell\\log\\left(\\ell/\\ell_{p}\\right)}\\,.\\label{eq:iruv}\n\\end{equation}\nFor simplicity we can take the $\\omega's$ to be evenly spaced in\nthis range, with spacing $\\pi/\\ell\\log\\left(\\ell/\\ell_{p}\\right)$.\nThis corresponds to $n_{rad}=2\\ell\\log(\\ell/\\ell_{p})/\\pi\\ell_{p}n_{UV}$\nradial points in the static patch. In particular, this number is conserved\nwith time. Here $n_{UV}>1$ is a factor introduced to parameterize\nthe ultraviolet cutoff. We will see momentarily why the $\\log$ factor\nappears.\n\nAn issue we immediately face is regulating the continuum mode normalization\n\\eqref{eq:staticnorm} to the discrete case. To do this we replace\nthe upper limit on the radial integral in \\eqref{eq:innerprod} by\n$\\ell\\to\\ell-\\epsilon.$ Then the result of the integral \\eqref{eq:radialint}\nmay be replaced by\n\\begin{align*}\n\\int_{0}^{\\ell-\\epsilon}\\frac{r^{2}\\,\\dd r}{1-r^{2}/\\ell^{2}}f_{\\omega l}(r)f_{\\omega'l}^{\\star}(r) & =\\frac{2|B_{\\omega l}|^{2}}{\\omega-\\omega'}\\left.\\sin\\left[\\frac{\\left(\\omega-\\omega'\\right)\\ell}{2}\\log\\left(\\frac{1}{1-r^{2}/\\ell^{2}}\\right)\\right]\\right|_{r=\\ell-\\epsilon}\\,.\n\\end{align*}\nKeeping in mind $\\omega-\\omega'=\\pi n/\\ell\\log\\left(\\ell/\\ell_{p}\\right)$\nfor some integer $n$ we choose\n\\begin{equation}\n\\left.\\log\\left(\\frac{1}{1-r^{2}/\\ell^{2}}\\right)\\right|_{r=\\ell-\\epsilon}=2\\log\\left(\\ell/\\ell_{p}\\right)\\label{eq:horpos}\n\\end{equation}\nwhich fixes $r_{*}$ according to \\eqref{eq:usualrs},\n\\[\n\\int_{0}^{\\ell-\\epsilon}\\frac{r^{2}\\,\\dd r}{1-r^{2}/\\ell^{2}}f_{\\omega l}(r)f_{\\omega'l}^{\\star}(r)=2\\ell\\log\\left(\\frac{\\ell}{\\ell_{p}}\\right)|B_{\\omega l}|^{2}\\delta_{\\omega,\\omega'}\n\\]\nup to rapidly oscillating terms. This unusual relation between a short\ndistance cutoff and an infrared cutoff is typical in holographic models.\n\nFinally, each harmonic oscillator mode $c_{\\omega lm}$ produces an\ninfinite dimensional Hilbert space. To regulate these Hilbert subspaces,\nwe use the Holstein-Primakoff map \\cite{PhysRev.58.1098} to replace $c_{\\omega lm}$\nby spin operators, introducing the parameter $s_{max}\\gg1$\n\\[\ns_{+}^{\\omega lm}=\\sqrt{2s_{max}}\\sqrt{1-\\frac{c_{\\omega lm}^{\\dagger}c_{\\omega lm}}{2s_{max}}}c_{\\omega lm},\\,s_{-}^{\\omega lm}=\\sqrt{2s_{max}}c_{\\omega lm}^{\\dagger}\\sqrt{1-\\frac{c_{\\omega lm}^{\\dagger}c_{\\omega lm}}{2s_{max}}},\\,s_{z}^{\\omega lm}=s-c_{\\omega lm}^{\\dagger}c_{\\omega lm}\\,.\n\\]\n For states near the ground state, we can approximate $\\sqrt{1-\\frac{c_{\\omega lm}^{\\dagger}c_{\\omega lm}}{2s_{max}}}$\nby $1$.\n\nThis regularization of the Hilbert space then allows us to write the\nenergy in the scalar field at quadratic order as a spin model\n\\[\nH_{0}=\\sum_{\\left\\{ \\omega\\right\\} }\\sum_{l=0}^{l_{max}}\\sum_{m=-l}^{l}\\omega\\left(c_{\\omega lm}^{\\dagger}c_{\\omega lm}+c_{\\omega lm}c_{\\omega lm}^{\\dagger}\\right)\\,.\n\\]\nThe dimension of the Hilbert space, for large $l_{max}$ is $(2s_{max}+1)^{l_{max}^{2}n_{rad}}=e^{S_{BH}}$,\nidentified with the Bekenstein-Hawking entropy of the cosmological\nhorizon $S_{BH}=\\pi\\ell^{2}/\\ell_{p}^{2}\\equiv N$. If we follow the\narguments of \\cite{Cohen:1998zx}, we identify\n\\[\nl_{max}^{2}n_{rad}\\log s_{max}\\sim N\n\\]\nand a natural choice would be to scale $n_{rad}\\sim l_{max}\\sim N^{1/3}$,\ndropping subleading $\\log$ factors for simplicity in a large $N$\nlimit. This leads to a short distance cutoff length of order $\\ell_{p}N^{1/6}$\nin all directions (and a choice $n_{UV}\\sim N^{1/6}$). We note if\nour present universe was replaced by a pure de Sitter region with\nthe same Hubble parameter, we would find $N\\approx10^{120}$ and $\\ell_{p}N^{1/6}$\nwould correspond to a $GeV$ UV cutoff.\n\n\\begin{comment}\nIf we wish, we can pass from angular momentum modes to modes local\non the discretized sphere by doing $c_{\\omega lm}=\\int d\\Omega Y_{lm}^{*}c_{\\omega}(\\theta,\\phi)$\nand using $\\sum_{l,m}Y_{lm}(\\theta,\\phi)Y_{lm}^{*}(\\theta',\\phi')=\\frac{1}{\\sin\\theta}\\delta(\\theta-\\theta')\\delta(\\phi-\\phi')$\nbut will generate some nontrivial kernel.\n\\end{comment}\n\nSo far, we have simply regulated the scalar field theory at the level\nof free field theory and found a holographic dual that reproduces\nthat. The holographic dual can be viewed as living on an $S^{2}$\nwith the discrete parameter $\\omega$ labelling different variables\nat each point on the sphere. This construction is guaranteed to reproduce\nthe bulk correlators of free scalar field theory with this particular\nregulator.\n\nThe ground state of the Hamiltonian corresponds to the Bunch-Davies\nvacuum state, and the Hamiltonian is diagonal in modes that are entangled\nbetween the left and right ``patches''. Tracing over one set leads\nto an approximately thermal density matrix in the other, subject to\nthe regulator on mode number imposed by finite $s_{max}$. The excitations\nof this model will lead to stress-energy tensors regular on the cosmological\nhorizon, avoiding the firewall conundrum.\n\nIn general, we also expect to have to add perturbative interactions\nto this model, which will typically be suppressed by powers of $N$\nrelative to the quadratic term. One might hope to follow a construction\nparalleling HKLL \\cite{Hamilton:2005ju,Hamilton:2006az} to reproduce\nperturbative field theory in the bulk.\n\nSuch a theory might be satisfactory for de Sitter spacetime. Once\nthe initial state corresponding to Bunch-Davies is specified on the\npast horizon of the right static patch (and its continuation onto\nthe left static patch) it evolves according to the standard rules\nof quantum mechanics. The future cosmological horizon would essentially\nbehave like a remnant, becoming entangled with the degrees of freedom\nin the left patch. A priori this poses no issues for the information\nproblem, because the cosmological horizon in de Sitter is eternal.\n\nMotivated by the physics of black hole horizons, it is interesting\nto explore what happens when this model is supplemented by an additional\nnonlocal term as studied in \\cite{Lowe:2016mhi,Lowe:2017ehz,Lowe:2019scv}\nwhich is thought to generate chaotic dynamics over sufficiently long\ntimescales. In the black hole case, the timescale associated with\nquantum scrambling is linked to the timescale the horizon can retain\nquantum information, before emitting it to the region outside the\nblack hole. In the de Sitter case, we view the static patch as analogous\nto the black hole interior and are mostly interested in developing\nthe holographic map on timescales shorter than this scrambling time.\nWe may then study the decoherence of local observables built using\nthe holographic map described above, when supplemented by chaotic\ninteractions.\n\nThe full Hamiltonian includes a non-local piece and a local piece,\nwhere the non-local piece is given by\n\\begin{equation}\nH_{\\textrm{nl}}=\\sum_{ijkl}J_{ijkl}s_{i}s_{j}s_{k}s_{l}\\label{eq:nonlocalham}\n\\end{equation}\nHere the coupling $J_{ijkl}$ is drawn randomly from a Gaussian distribution\nwith zero mean (tensor indices are suppressed). We do not have in\nmind averaging over this coupling, but rather work with a fixed set\nof $J_{ijkl}$ as needed to generate chaotic dynamics. We impose the\ncondition that the variance of the non-local Hamiltonian $\\var(H_{{\\rm nl}})=1$.\nThis forces the width of the Gaussians to scale like $1/N^{2}$, due\nto the following analysis\n\\begin{equation}\n1=\\langle H_{nl}^{2}\\rangle\\sim J^{2}\\left\\langle \\sum_{i_{1}\\cdots i_{8}}s_{i_{1}}\\cdots s_{i_{8}}\\right\\rangle \\sim J^{2}N^{4}\\label{eq:scaling}\n\\end{equation}\nwhere in the last step we have used the fact that on average $\\langle s_{i}s_{j}\\rangle=\\delta_{ij}$.\nWe note this unusual scaling with $N$ is designed to reproduce the\nBekenstein-Hawking entropy via microstate counting for fixed $N$\nas opposed to the more conventional large $N$ limit where $\\left\\langle H_{nl}^{2}\\right\\rangle \\sim N$,\nwhich would widen the spectrum to much larger energies.\n\nOur proposal for the full Hamiltonian is then\n\\begin{equation}\nH=H_{0}+T_{H}H_{nl}\\label{eq:hamiltonian}\n\\end{equation}\nand the chaotic term may then be treated as a small perturbation for\nshort enough time intervals, where it will shift energies at leading\norder by terms of order $T_{H}$.\n\nOne may then study how local perturbations of the thermal state decohere\nwhen this term is included. Following the analysis of \\cite{Lowe:2019scv}\nwe expect the timescale of such decoherence to be\n\\begin{equation}\nt_{dec}=\\beta\\log N\\label{eq:deco}\n\\end{equation}\nThis resembles the scrambling time, however the interpretation here\nis somewhat different. With the scaling \\eqref{eq:scaling} the global\nscrambling time is expected to be\n\\[\nt_{scr}=\\beta N^{1/2}\\log N\\gg t_{dec}\n\\]\nif the bounds derived in \\cite{Bentsen:2018uph} happen to be saturated.\nHowever, the local decoherence time is the quantity of most relevance\nin deciding when the holographic map derived above breaks down. A\nsimilar breakdown of the bulk description via effective field theory\nin a black hole interior was noted in \\cite{Lowe:2015eba,Lowe:2016mhi,Lowe:2017ehz}.\n\nGiven that a local operator will evolve to a highly non-local operator\nin the time \\eqref{eq:deco}, rather than simply undergoing the free\npropagation governed by the term $H_{0}$, our holographic map based\non the mode functions \\eqref{eq:entmode} will break down after this\ntimescale. In the case of applying this to a pure de Sitter region\nwith $\\ell$ matched to our present cosmological horizon, this would\nimply a breakdown in the local laws of physics after a timescale of\norder 4000 billion years due to quantum gravity effects. It would\nbe very interesting to devise experiments sensitive to this local\ndecoherence. While the shifts in energy levels are tiny, of order\n$10^{-33}eV$ the nonlocal character of the decoherence opens the\ndoor to more sensitive experiments.\n\nOne might wonder whether such a holographic description is ruled out\nfor primordial inflation. In that case, one can try to embed ``small''\nde Sitter models into a much larger Hilbert space, which is needed\nto describe the late-time phase of cosmology. Holographic bounds with\nthese considerations in mind were considered in \\cite{Banks:2003pt,Lowe:2004zs}.\nThe decoherence times in this case can be made much longer than the\ntimescale associated with primordial inflation.\n\nIt should also be noted that once a local basis of operators has decohered,\nfor example in Heisenberg picture\n\\[\nc_{\\omega lm}(t)=e^{iHt}c_{\\omega lm}(0)e^{-iHt}\n\\]\nwith $t>t_{dec}$ one may simply do a change of basis by the unitary\ntransformation $e^{iHt_{dec}}$ to return to another local basis\n\\[\n\\tilde{c}_{\\omega lm}(t)=e^{-iHt_{dec}}c_{\\omega lm}(t)e^{iHt_{dec}}\n\\]\ntherefore, in some basis, one always retains an approximately local\ndescription of spacetime physics. This realizes the proposal of \\cite{Lowe:2015eba}\nin a concrete model, when adapted to de Sitter spacetime.\n\n\\section{Conclusions}\n\nNow that we have a detailed proposal for the stretched horizon theory\nof the de Sitter cosmological horizon, we can try to adapt the method\nto black holes. A key step in the development of the holographic map\nwas the assumption of regularity of the modes on the pole of the static\npatch. This eliminated the non-normalizable modes and allowed us to\nmake a one-one map from frequency/radial quantum number space to mode\nfunctions \\eqref{eq:entmode}. For black holes in asymptotically flat\nspace, one would need to perform a similar restriction, which might\nbe accomplished by placing a mirror around the black hole to prevent\nevaporation. In practice, as we have learned over the years, the best\nsubstitute for this procedure is simply to introduce a negative cosmological\nconstant which has the same effect and can be handled much more precisely.\nThus, we expect the present considerations will apply largely unchanged\nto a large black hole in anti-de Sitter spacetime which does not evaporate.\nIn this way, we can use the present construction to derive a holographic\nmap for the interior of such a black hole. One might then hope to\nderive the spin model directly from the conformal field theory description\navailable in that case. Note here we have in mind realizing the black\nhole in a single conformal field theory representing, perhaps, a large\nblack hole formed by collapse, rather than the tensor product conformal\nfield theories describing wormholes.\n\nTurning this argument around, we then expect the much more interesting\ncase of the evaporating black hole in asymptotically flat space, or\na small black hole in asymptotically anti de Sitter space will involve\nimportant extra ingredients. The coupling between this stretched horizon\ntheory and some larger holographic theory describing the asymptotic\nregion will need to be specified. Nevertheless, for timescales shorter\nthan $t_{dec}$ we expect to be able to apply the considerations of\nthe present chapter, which is sufficient to extend the holographic map\nto black hole interiors.\n\nIn the case of anti-de Sitter/conformal field theory duality, it is\noften suggested one has control of the holographic map all the way\nto the stretched horizon. In that case one has a fixed local basis\nextending from asymptotic infinity down to the stretched horizon.\nThe present picture implies the coupling between the exterior and\nthe stretched horizon eventually become highly nonlocal, contaminating\nthe exterior physics with non-local effects. Indeed, nonlocal interactions\nakin to \\eqref{eq:nonlocalham} must emerge from the correspondence\nin a smooth way as one approaches the stretched horizon. This has\nthe profound consequence that nonlocal scrambling effects might be\ndetected outside large black holes, if sufficiently long timescales\ncan be probed to overcome the $T_{H}$ suppression factor in \\eqref{eq:hamiltonian}.\nIndeed, such effects are probed in current gravitational wave experiments\n\\cite{LIGOScientific:2018mvr}. For example, for black hole mergers\nwith masses of order a solar mass, one must probe around $100$ light\ncrossing times to access the timescale \\eqref{eq:deco}. As these\nexperiments become more precise it will be very interesting to look\nfor signs of violations of the equivalence principle. For example,\none might look for anomalies in the late time ringing profile following\nblack hole merger.\n\nFinally, we end with a comment on an interesting numerological coincidence\nof this holographic model. We noted above, that if we replace our\npresent cosmology with a de Sitter horizon with size around $14$\nbillion light years, an unacceptably small ultraviolet cutoff emerges\non bulk effectively field theory of about $1$ GeV. This may simply\nbe a signal that a more precise holographic model would produce a\nbulk cutoff in a much more subtle way. However, for now, let us instead\nexplore the possibility that the current observable entropy $S\\approx10^{88}$\nwhich arises largely from cosmic microwave background photons, might\nbe equated with a late-time de Sitter entropy. Interestingly, this\npredicts the cosmic acceleration must increase versus the previous\npossibility, a feature also noted in the Hubble tension experiments,\nand the ultraviolet cutoff that emerges is the more experimentally\ninteresting value of $100$ TeV. This raises the possibility that\nholographic physics might appear in collider experiments at experimentally\naccessible scales. Unfortunately, the model also predicts the horizon\nsize must shrink to of order $10^{4}$ m to reach the late time de\nSitter phase, so we are presently far off from the phase, and it is\nnot clear how much to trust the ultraviolet cutoff result. Nevertheless,\nthe model was designed so a freely falling observer will use a cutoff\nwith fixed proper spatial resolution, so there is reason to be optimistic.\n\n\n\\chapter{Conformal Wave Expansions for Flat Space Amplitudes}\\label{chap:flatspace}\nThe extended BMS algebra contains a conformal subgroup that acts on\nthe celestial sphere as $SO(3,1)$. It is of interest to perform mode\nexpansions of free fields in Minkowski spacetime that realize this\nsymmetry in a simple way. In the present work we perform such a mode\nexpansion for massive scalar fields using the unitary principal series\nrepresentations of $SO(3,1)$ with a view to developing a holographic\napproach to gravity in asymptotically flat spacetime. These mode expansions\nare also of use in studying holography in three-dimensional de Sitter\nspacetime.\n\n\\section{Introduction}\n\nThere has been considerable interest recently in constructing holographic\ntheories between flat 4D Minkowski spacetime and a 2D boundary celestial\nsphere conformal field theory \\cite{deBoer:2003vf,Kapec:2014opa,Kapec:2016jld,Cheung:2016iub}.\nCentral to this mission is the construction of conformally covariant\nwavefunctions that form unitary representations of the ${\\rm SO}(d,1)$\ngroup. These wavefunctions are defined on a $d$-dimensional de Sitter\nspacetime ${\\rm dS}_{d}$, on which ${\\rm SO}(d,1)$ acts naturally\nthrough an embedding of ${\\rm dS}_{d}$ as a submanifold of a $(d+1)$-dimensional\nMinkowski spacetime.\n\nAs part of the program to realize the dS/CFT correspondence \\cite{Strominger:2001pn},\nnumerous papers have previously constructed unitary principal series\nrepresentations of the ${\\rm SO(2,1)}$ group on two-dimensional de\nSitter spacetimes \\cite{Guijosa:2003ze,Guijosa:2005qi}, as well\nas $q$-deformed versions of the principal series on the three-dimensional\nde Sitter spacetime \\cite{Lowe:2004nw}. In this chapter we construct\nthe unitary principal series representation of the ${\\rm SO(3,1)}$\ngroup on the three-dimensional de Sitter spacetime. We also compute\nthe uplifted version of these wavefunctions on the ambient four-dimensional\nMinkowski spacetime. Finally, we comment on relevant previous work\n\\cite{Pasterski:2016qvg,Pasterski:2017kqt,Pasterski:2017ylz} and\ndiscuss how our results fit within the program to develop holographic\napproaches to gravity in de Sitter and asymptotically Minkowski spacetime.\n\nThe sections are organized as follows: we first establish our coordinate\nsystems and fix our notations in section \\ref{sec:coord}. We then\nconstruct massive scalar mode functions on both the three-dimensional\nde Sitter spacetime ${\\rm dS_{3}}$ and the four-dimensional Minkowski\nspacetime ${\\rm M_{4}}$, in section \\ref{sec:dsmodes} and \\ref{sec:minkmodes},\nrespectively. We then show in section \\ref{sec:ups} that these mode\nfunctions form a unitary principal series representation of the ${\\rm SO(3,1)}$\ngroup. We note that previous work \\cite{Pasterski:2016qvg,Pasterski:2017kqt,Pasterski:2017ylz}\nuses modes that form non-unitary highest weight representations of\n$SO(3,1)$. Finally we comment in section \\ref{sec:further} on how\nour mode functions can serve as a conformal basis to develop holographic\nformulations of gravity in asymptotically de Sitter and Minkowski\nspacetimes.\n\n\\section{Conformal Coordinates}\n\n\\label{sec:coord}\n\n\\begin{figure}\n\\centering \\begin{overpic}[width=0.7\\textwidth]{plot.pdf} \\put\n(25,49) {$x^{1}$} \\put (69,52) {$\\,x^{2},x^{3}$} \\put (48,89)\n{$x^{0}$} \\put (63,59) {$\\leftarrow\\rho=1$ hypersurface} \\put\n(17,76) {$\\nearrow$} \\put (9,73) {$\\rho=0$} \\put (4,69) {hypersurface}\n\\end{overpic}\n\n\\begin{tikzpicture}[scale=1.5]\n  \\shade (0,0) -- (1,1) -- (2,0) -- (1,-1) -- (0,0);\n  \\draw (0,2) node[above] {$i^+$};\n  \\draw (0,-2) node[below] {$i^-$};\n  \\draw (2,0) node[right] {$i^0$};\n  \\draw (1.2,1) node[above] {$\\mathcal{I}^+$};\n  \\draw (1.2,-1) node[below] {$\\mathcal{I}^-$};\n  \\draw (0.7,0) node[right] {$\\leftarrow \\rho=1$};\n  \\draw (0,2) -- (0,-2);\n  \\draw (0,2) -- (2,0);\n  \\draw (0,-2) -- (2,0);\n  \\pgfmathsetmacro{\\e}{1.5}   % eccentricity\n  \\pgfmathsetmacro{\\a}{0.7}\n  \\pgfmathsetmacro{\\b}{(\\a*sqrt((\\e)^2-1)}\n  \\draw plot[domain=-1:1] ({\\a*cosh(\\x)},{\\b*sinh(\\x)});\n\\end{tikzpicture} \\caption{Minkowski spacetime may be divided up into radial ($\\rho$) slices\nisometric to 3D de Sitter spacetime as shown in the top panel. The\nbottom panel shows the Penrose diagram of Minkowski spacetime. The\nshaded region is the region bounded by $\\rho=0$ and $\\rho=\\infty$.\nIn particular, $i^{\\pm}$ are excluded from this region.}\n\\label{fig:coord}\n\\end{figure}\n\nBefore we begin our discussion of the representation theory of ${\\rm SO(3,1)}$\nin de Sitter and Minkowski spacetimes, we would like to present the\ncoordinate systems we employ and fix notation. A schematic plot of\nthe relevant hypersurfaces can be found in Fig.~\\ref{fig:coord}.\n\nWe start with the 4d flat Minkowski spacetime labeled by coordinates\n$(x^{0},x^{1},x^{2},x^{3})$ with the following metric\n\\[\n\\dd s^{2}=-(\\dd x^{0})^{2}+(\\dd x^{1})^{2}+(\\dd x^{2})^{2}+(\\dd x^{3})^{2}\\,.\n\\]\nWe embed our 3D de Sitter spacetime as a hypersurface within the 4d\nMinkowski spacetime. To do so we first switch to hyperbolic coordinates\n$(t,\\rho,\\theta,\\varphi)$ with $-\\infty<t<\\infty$, $\\rho>0$, $0\\le\\theta<\\pi$\nand $0\\le\\varphi<2\\pi$, defined by\n\\begin{align}\nx^{0} & =\\rho\\sinh(t/\\rho)\\nonumber \\\\\nx^{1} & =\\rho\\cos\\theta\\cosh(t/\\rho)\\nonumber \\\\\nx^{2} & =\\rho\\sin\\theta\\cos\\varphi\\cosh(t/\\rho)\\nonumber \\\\\nx^{3} & =\\rho\\sin\\theta\\sin\\varphi\\cosh(t/\\rho)\\,.\\label{eq:embedding}\n\\end{align}\nNote that these coordinates only cover the region of the Minkowski\nspacetime defined by points $x^{\\mu}$ where $x\\cdot x>0$. The metric\nthen becomes\n\\[\n\\dd s^{2}=-\\dd t^{2}+\\frac{2t\\,\\dd\\rho\\,\\dd t}{\\rho}+\\left(1-\\frac{t^{2}}{\\rho^{2}}\\right)\\dd\\rho^{2}+\\rho^{2}\\cosh^{2}\\left(\\frac{t}{\\rho}\\right)\\left(\\dd\\theta^{2}+\\sin^{2}\\theta\\,\\dd\\varphi^{2}\\right)\\,.\n\\]\nThe d'Alembertian in this coordinate system looks rather complicated.\nWe therefore perform the following change of variables\n\\[\n\\eta=\\frac{t}{\\rho}\n\\]\nand the metric takes the following simpler form\n\\[\n\\dd s^{2}=-\\rho^{2}\\dd\\eta^{2}+\\dd\\rho^{2}+\\rho^{2}\\cosh^{2}\\eta\\left(\\dd\\theta^{2}+\\sin^{2}\\theta\\,\\dd\\varphi^{2}\\right)\\,.\n\\]\n\nA 3D de Sitter spacetime can then be embedded into this 4d Minkowski\nspacetime as a hypersurface of constant $\\rho=\\ell$, where $\\ell$\nis the de Sitter length scale which we will set to unity in what follows.\nOn the 3D de Sitter spacetime the induced metric is simply\n\\[\n\\dd s^{2}=-\\dd t^{2}+\\cosh^{2}t\\left(\\dd\\theta^{2}+\\sin^{2}\\theta\\,\\dd\\varphi^{2}\\right)\\,.\n\\]\nThrough a stereographic projection we can parameterize the 2-sphere\ncovered by coordinates $(\\theta,\\varphi)$ with a complex variable\n$z$, and obtain the Fubini-Study metric on the 2-sphere:\n\\[\n\\dd\\theta^{2}+\\sin^{2}\\theta\\,\\dd\\varphi^{2}=\\frac{4\\,\\dd z\\,\\dd\\bar{z}}{(1+|z|^{2})^{2}}\\,.\n\\]\nThis allows us to rewrite the 3D de Sitter metric as\n\\begin{equation}\n\\dd s^{2}=-\\dd t^{2}+\\cosh^{2}t\\,\\frac{4\\,\\dd z\\,\\dd\\bar{z}}{(1+|z|^{2})^{2}}\\label{eq:3dds}\n\\end{equation}\nand the 4d Minkowski metric in hyperbolic coordinates as\n\\[\n\\dd s^{2}=-\\rho^{2}\\dd\\eta^{2}+\\dd\\rho^{2}+\\rho^{2}\\cosh^{2}\\eta\\,\\frac{4\\,\\dd z\\,\\dd\\bar{z}}{(1+|z|^{2})^{2}}\\,.\n\\]\n\n\n\\section{3D de-Sitter Mode Functions}\n\n\\label{sec:dsmodes}\n\nWe start from the metric on the 3D de Sitter spacetime \\eqref{eq:3dds}.\nThe isometry group of the 3D de Sitter spacetime is ${\\rm SO(3,1)}$\nwhich has 6 generators with real coefficients. The first step in building\na unitary representation of ${\\rm SO(3,1)}$ on 3D de Sitter is to\nsolve the scalar field equation with mass $\\mu$\n\\[\n(\\Delta-\\mu^{2})\\phi(t,z,\\bar{z})=0\n\\]\nwhere the d'Alembertian is defined in general as\n\\[\n\\Delta\\phi=\\frac{1}{\\sqrt{|g|}}\\partial_{i}(g^{ij}\\sqrt{|g|}\\partial_{j}\\phi)\\,.\n\\]\nHere and in what follows we use Latin indices when we are referring\nto the 3D de Sitter submanifold and use Greek indices when we are\ndealing with the ambient 4d Minkowski spacetime. The d'Alembertian\nis computed to be\n\\[\n\\Delta\\phi=\\left[-\\partial_{t}^{2}-2(\\tanh t)\\partial_{t}+(\\sech^{2}t)(1+|z|^{2})^{2}\\partial_{z}\\partial_{\\bar{z}}\\right]\\phi\\,.\n\\]\nThe massive scalar field equation therefore is\n\\[\n\\left(-\\frac{\\partial^{2}}{\\partial t^{2}}-2\\tanh t\\frac{\\partial}{\\partial t}+\\mathrm{sech}^{2}t\\,(1+|z|^{2})^{2}\\frac{\\partial^{2}}{\\partial z\\partial\\bar{z}}-\\mu^{2}\\right)\\phi(t,z,\\bar{z})=0\\,.\n\\]\nWe can perform separation of variables as usual and write a mode function\nas\n\\[\n\\phi_{lm}(t,z,\\bar{z})=\\phi_{l}(t)\\,Y_{m}^{l}(z,\\bar{z})\n\\]\nwhere $m$ is a $j_{3}$ eigenvalue. The $Y_{m}^{l}$ are the standard\nspherical harmonics \\cite{kelvin1867treatise} in $(z,\\bar{z})$\ncoordinates. They satisfy the eigenvalue equation\n\\[\n(1+|z|^{2})^{2}\\frac{\\partial^{2}}{\\partial z\\partial\\bar{z}}Y_{m}^{l}=-l(l+1)Y_{m}^{l}\\,.\n\\]\nExplicitly, we have\n\\[\nY_{m}^{l}(\\theta,\\varphi)=\\sqrt{\\frac{(2l+1)(l-m)!}{4\\pi(l+m)!}}P_{l}^{m}(\\cos\\theta)e^{im\\varphi}\n\\]\nwhere\n\\[\nP_{l}^{m}(x)=\\frac{(1+x)^{m/2}}{(1-x)^{m/2}}\\sum_{k=0}^{l}\\frac{\\left(\\frac{1-x}{2}\\right)^{k}(-l)_{k}(l+1)_{k}}{k!\\,\\Gamma(k-m+1)}\\,.\n\\]\nThe coordinate transformation linking $(\\theta,\\varphi)$ and $(z,\\bar{z})$\nis\n\\[\n(\\sin\\theta\\,e^{i\\varphi},\\cos\\theta)=\\left(\\frac{2z}{1+|z|^{2}},\\frac{1-|z|^{2}}{1+|z|^{2}}\\right)\\,.\n\\]\nIt is easy to see that the spherical harmonics $Y_{l}^{m}(z,\\bar{z})$\ncan be built out of homogeneous polynomials of the following three\nvariables\n\\[\nF_{z}=\\frac{2z}{1+|z|^{2}}\\qquad F_{\\bar{z}}=\\frac{2\\bar{z}}{1+|z|^{2}}\\qquad F_{t}=\\frac{1-|z|^{2}}{1+|z|^{2}}\\,.\n\\]\nWe will later see that these three variables will appear in (\\ref{eq:cartesian}).\nOne is then left to solve\n\\[\n\\left(\\frac{\\partial^{2}}{\\partial t^{2}}+2\\tanh t\\frac{\\partial}{\\partial t}+l(l+1)\\mathrm{sech}^{2}t+\\mu^{2}\\right)\\phi_{l}(t)=0\\,.\n\\]\nThis has the following two linearly independent solutions\n\\begin{equation}\n\\phi_{l,1}(t)=\\mathrm{sech}t\\,P_{l}^{\\sqrt{1-\\mu^{2}}}\\left(\\tanh t\\right),\\quad\\phi_{l,2}(t)=\\mathrm{sech}t\\,Q_{l}^{\\sqrt{1-\\mu^{2}}}\\left(\\tanh t\\right)\\label{eq:basis}\n\\end{equation}\nwhere $P$ and $Q$ are the associated Legendre functions of first\nand second kind, respectively. We expect to get a unitary representation\ncorresponding to a general complex linear combination, one of which\nwill be the Euclidean vacuum (see Section \\ref{sec:norm} and Appendix\n\\ref{app:euclidean}). Other combinations will generate modes around an\n$\\alpha$-vacuum \\cite{PhysRevD.32.3136,GOLDSTEIN2003325,PhysRevD.69.023507}.\n\n\\section{Uplifting onto 4D Minkowski}\n\n\\label{sec:minkmodes}\n\nTo uplift the 3D de Sitter mode functions onto the 4d Minkowski spacetime\nwe consider the scalar field equation in 4d with mass $M$\n\\[\n(\\Box-M^{2})\\Phi(\\eta,\\rho,z,\\bar{z})=0\\,.\n\\]\nThe d'Alembertian is computed to be\n\\[\n\\Box=-\\frac{1}{\\rho^{2}}(\\partial_{\\eta}^{2}+2\\tanh\\eta\\,\\partial_{\\eta})+3\\frac{\\partial_{\\rho}}{\\rho}+\\partial_{\\rho}^{2}+\\frac{\\sech^{2}\\eta\\,(1+|z|^{2})^{2}\\,\\partial_{z}\\partial_{\\bar{z}}}{\\rho^{2}}\\,.\n\\]\nSeparating variables, the mode functions can be written as\n\\[\n\\Phi_{plm}(\\eta,\\rho,z,\\bar{z})=\\phi_{pl}(\\eta)\\,\\psi_{p}(\\rho)\\,Y_{m}^{l}(z,\\bar{z})\n\\]\nwhere $l=0,1,\\cdots$, $m=-l,\\cdots,l$ and the range of the real\nparameter $p$ will be discussed later. We find the differential equation\nfor $\\phi_{pl}$ to be identical to the 3D de Sitter modes, except\nthat we replace $\\mu$ with a real parameter $p$,\n\\[\n\\left(\\partial_{\\eta}^{2}+2(\\tanh\\eta)\\partial_{\\eta}+l(l+1)\\sech^{2}\\eta+p^{2}\\right)\\phi_{pl}(\\eta)=0\n\\]\nwhich has solutions \\eqref{eq:basis} with the replacement $t\\to\\eta$\nand $\\mu\\to p$.\n\nThe differential equation for $\\psi_{p}$ therefore becomes\n\\[\n\\left(\\partial_{\\rho}^{2}+\\frac{3}{\\rho}\\partial_{\\rho}+\\frac{p^{2}}{\\rho^{2}}-M^{2}\\right)\\psi_{p}(\\rho)=0\\,.\n\\]\nThis has two independent solutions\n\\begin{equation}\n\\psi_{p,1}=\\frac{I_{\\sqrt{1-p^{2}}}(M\\rho)}{\\rho}\\,,\\qquad\\psi_{p,2}=\\frac{K_{\\sqrt{1-p^{2}}}(M\\rho)}{\\rho}\\label{eq:radialsol}\n\\end{equation}\nwhere $I_{\\alpha}$ and $K_{\\alpha}$ are modified Bessel functions\nof first and second kind, respectively.\n\n\\section{Klein-Gordon Norm and Orthonormality Conditions}\n\n\\label{sec:norm}\n\nBefore presenting the explicit form of our unitary principal series\nrepresentation we would like to first establish the orthonormalizability\nof the 4d Minkowski mode functions. The mode functions are normalized\nwith respect to the Klein-Gordon norm, the most general form of which\nis \\cite{birrell1984quantum}\n\\begin{equation}\n\\langle f,g\\rangle=-i\\int_{\\Sigma}\\dd\\Sigma\\,n^{\\lambda}(f\\partial_{\\lambda}g^{\\star}-g^{\\star}\\partial_{\\lambda}f)\\,.\\label{eq:kgnorm}\n\\end{equation}\nHere $\\Sigma$ is a spacelike surface, $n^{\\lambda}$ is a timelike\nunit vector field normal to $\\Sigma$ and $d\\Sigma$ is the volume\nelement in $\\Sigma$. This norm is time-independent, and in principle\ncan be evaluated on any Cauchy slice. Here, for convenience we choose\nthe $\\eta=\\eta_{0}$ slice, where $\\eta_{0}$ is an arbitrary constant.\nOn the 4d Minkowski spacetime with coordinate system $(\\eta,\\rho,\\theta,\\varphi)$\nthis then becomes\n\\[\n\\langle f,g\\rangle=-i\\int_{\\rho}\\int_{S^{2}}(f\\partial_{\\eta}g^{\\star}-g^{\\star}\\partial_{\\eta}f)|_{\\eta=\\eta_{0}}\\,(\\cosh^{2}\\eta_{0})\\,\\rho\\,\\dd\\rho\\,\\dd\\Omega\n\\]\nwhere $\\dd\\Omega$ is the area element of the unit 2-sphere $S^{2}$.\nGiven that our mode functions are separable $\\Phi_{plm}(\\eta,\\rho,z,\\bar{z})=\\phi_{pl}(\\eta)\\psi_{p}(\\rho)Y_{m}^{l}(z,\\bar{z})$\nwe can further evaluate this norm to obtain\n\\begin{align*}\n\\langle\\Phi_{plm},\\Phi_{p'l'm'}\\rangle= & -i\\,\\left(\\phi_{pl}(\\eta_{0})\\dot{\\phi}_{p'l'}^{\\star}(\\eta_{0})-\\phi_{p'l'}^{\\star}(\\eta_{0})\\dot{\\phi}{}_{pl}(\\eta_{0})\\right)\\,\\left(\\cosh^{2}\\eta_{0}\\right)\\\\\n & \\qquad\\times\\int_{0}^{\\infty}\\psi_{p}(\\rho)\\psi_{p'}^{\\star}(\\rho)\\,\\rho\\,\\dd\\rho\\int_{S^{2}}Y_{m}^{l}(z,\\bar{z})Y_{m'}^{\\star l'}(z,\\bar{z})\\,\\dd\\Omega\n\\end{align*}\nwhere $\\dot{\\phi}(\\eta)=\\partial_{\\eta}\\phi$. The orthonormality\nof the spherical harmonics allows us to conclude that\n\\[\n\\int_{S^{2}}Y_{m}^{l}(z,\\bar{z})Y_{m'}^{\\star l'}(z,\\bar{z})\\,\\dd\\Omega=\\delta_{ll'}\\delta_{mm'}\\,.\n\\]\nFor the $\\rho$ integral, note that multiplying the differential equation\nsatisfied by $\\psi_{p}$ with $\\psi_{p'}^{\\star}$ gives\n\\[\n\\psi''_{p}\\psi_{p'}^{\\star}+\\frac{3}{\\rho}\\psi'_{p}\\psi_{p'}^{\\star}+\\left(\\frac{p^{2}}{\\rho^{2}}-M^{2}\\right)\\psi_{p}\\psi_{p'}^{\\star}=0\n\\]\nwhere $\\psi'=\\partial_{\\rho}\\psi$. Likewise swapping $\\psi_{p}\\leftrightarrow\\psi_{p'}^{*}$\nand subtracting we have\n\\[\n-\\frac{p^{2}-p'^{2}}{\\rho^{2}}\\psi_{p}\\psi_{p'}^{\\star}=\\psi''_{p}\\psi_{p'}^{\\star}-\\psi_{p'}^{\\star''}\\psi_{p}+\\frac{3}{\\rho}\\psi'_{p}\\psi_{p'}^{\\star}-\\frac{3}{\\rho}\\psi_{p'}^{\\star'}\\psi_{p}\\,.\n\\]\nIntegrating, we have\n\\[\n-(p^{2}-p'^{2})\\int_{0}^{\\infty}\\psi_{p}\\psi_{p'}^{\\star}\\,\\rho\\,\\dd\\rho=\\int_{0}^{\\infty}\\dd\\rho\\,[\\rho^{3}(\\psi''_{p}\\psi_{p'}^{\\star}-\\psi_{p'}^{\\star''}\\psi_{p})+3\\rho^{2}(\\psi'_{p}\\psi_{p'}^{\\star}-\\psi_{p'}^{\\star'}\\psi_{p})]\\,.\n\\]\nThe integral on the right hand side can be integrated by parts to\nyield\n\\begin{equation}\n-(p^{2}-p'^{2})\\int_{0}^{\\infty}\\psi_{p}\\psi_{p'}^{\\star}\\,\\rho\\,\\dd\\rho=[\\rho^{3}(\\psi'_{p}\\psi_{p'}^{\\star}-\\psi_{p'}^{\\star'}\\psi_{p})]\\Big|_{0}^{\\infty}\\,.\\label{eq:norm-int}\n\\end{equation}\n\nThe modified Bessel functions have the following mirror symmetry\n\\[\nI_{\\alpha}^{\\star}(z)=I_{\\alpha^{\\star}}(z^{\\star})\\qquad K_{\\alpha}^{\\star}(z)=K_{\\alpha^{\\star}}(z^{\\star})\\,.\n\\]\nAt $z=+\\infty$, $I_{\\alpha}(z)\\sim e^{z}$ which increases exponentially\nwhile $K_{\\alpha}(z)\\sim e^{-z}$ which decreases exponentially. We\ntherefore discard the $\\psi_{p,1}$ set of solutions as these modes\nare not normalizable and study the \\eqref{eq:radialsol} solutions\n$\\psi_{p,2}$. We begin by considering the case $p^{2}>1$ and take\nthe branch $\\sqrt{1-p^{2}}=i\\sqrt{p^{2}-1}$. Let us define $\\alpha=\\sqrt{p^{2}-1}$\nand henceforth we will drop the 2 subscript on $\\psi_{p,2}$. Near\n$z=0$, the expansion\n\\[\nK_{\\nu}(z)=2^{\\nu-1}\\Gamma(\\nu)z^{-\\nu}+2^{-\\nu-1}\\Gamma(-\\nu)z^{\\nu}+\\cdots\n\\]\nallows us to evaluate the surface term to give\n\\begin{align}\n & \\lim_{\\rho\\to0}\\rho^{3}\\left(\\psi'_{p}\\psi_{p'}^{*}-\\psi_{p'}^{*'}\\psi_{p}\\right)=\\nonumber \\\\\n & \\quad\\lim_{\\rho\\to0}i(\\alpha+\\alpha')2^{-2}\\left(\\Gamma(i\\alpha')\\Gamma(-i\\alpha)(M\\rho/2)^{i(\\alpha-\\alpha')}-\\Gamma(i\\alpha)\\Gamma(-i\\alpha')(M\\rho/2)^{-i(\\alpha-\\alpha')}\\right)\\label{eq:surfaceterm}\n\\end{align}\ntreating the rapidly oscillating terms in $\\alpha$ as vanishing in\nthe sense of a distribution. For $\\rho\\to0$, this is proportional\nto a sinc representation of the Dirac delta function\n\\[\n\\lim_{\\rho\\to0}\\rho^{3}\\left(\\psi'_{p}\\psi_{p'}^{*}-\\psi_{p'}^{*'}\\psi_{p}\\right)=-\\frac{\\alpha\\Gamma(i\\alpha)\\Gamma(-i\\alpha)}{2}\\sin\\left[(\\alpha-\\alpha')\\log(M\\rho/2)\\right]\n\\]\nwhich gives\n\\[\n\\int_{0}^{\\infty}\\psi_{p}\\psi_{p'}^{\\star}\\,\\rho\\,\\dd\\rho=\\frac{\\Gamma(i\\alpha)\\Gamma(-i\\alpha)}{4}\\lim_{C\\to\\infty}\\frac{\\sin[C(\\alpha-\\alpha')]}{\\alpha-\\alpha'}\n\\]\nwhere we have set $C=\\log(M\\rho/2)$. Using the following identity\n\\[\n\\lim_{C\\to\\infty}\\frac{\\sin(Cx)}{x}=\\pi\\delta(x)\n\\]\nwe then have\n\\begin{equation}\n\\int_{0}^{\\infty}\\psi_{p}\\psi_{p'}^{\\star}\\,\\rho\\,\\dd\\rho=\\frac{\\pi\\Gamma(i\\alpha)\\Gamma(-i\\alpha)}{4}\\delta(\\alpha-\\alpha')=\\frac{\\pi^{2}}{4p\\sinh\\left(\\pi\\sqrt{p^{2}-1}\\right)}\\delta\\left(p-p'\\right)\\,.\\label{eq:radialnorm}\n\\end{equation}\n For $0\\le p^{2}<1$, instead of oscillating terms in eq.~\\ref{eq:surfaceterm}\nwe have power-law divergences, and the mode functions $\\psi_{p}$\nin this case again are not normalizable.\n\nTo conclude, the normalizable radial mode functions arise from $\\psi_{p,2}$\nin \\eqref{eq:radialsol} with $p^{2}>1$. The $p$-dependent prefactor\nin \\eqref{eq:radialnorm} may then be absorbed into the normalization\nof these functions. We assume this has been done, and in the interest\nof notational clarity we will from now use $\\psi_{p}$ to denote the\nnormalized radial mode functions. The normalized radial mode functions\nin this case will satisfy the following\n\\begin{equation}\n\\int_{0}^{\\infty}\\psi_{p}\\psi_{p'}^{\\star}\\,\\rho\\,\\dd\\rho=\\delta(p-p')\\,.\\label{eq:radialinnerprod}\n\\end{equation}\n\nFor the $\\eta$ dependence, we form the following linear combination\nof $\\phi_{pl,1}$ and $\\phi_{pl,2}$ to obtain\n\\[\n\\phi_{pl}=\\frac{i\\pi}{2}\\phi_{pl,1}+\\phi_{pl,2}\n\\]\nwhich, as we will show in Appendix \\ref{app:euclidean}, are the (unnormalized)\nmodes corresponding to the 4d Minkowski vacuum. Using\n\\[\n\\frac{\\partial P_{\\nu}^{\\mu}}{\\partial z}=\\frac{\\nu zP_{\\nu}^{\\mu}(z)-(\\mu+\\nu)P_{\\nu-1}^{\\mu}(z)}{z^{2}-1}\\qquad\\frac{\\partial Q_{\\nu}^{\\mu}}{\\partial z}=\\frac{\\nu zQ_{\\nu}^{\\mu}(z)-(\\mu+\\nu)Q_{\\nu-1}^{\\mu}(z)}{z^{2}-1}\n\\]\nand\n\\[\nP_{\\nu}^{\\mu}(0)=\\frac{\\pi^{1/2}2^{\\mu}}{\\Gamma\\left(\\frac{1-\\mu-\\nu}{2}\\right)\\Gamma\\left(\\frac{\\nu-\\mu}{2}+1\\right)}\\qquad Q_{\\nu}^{\\mu}(0)=-\\frac{\\pi^{3/2}2^{\\mu-1}\\tan\\frac{\\pi(\\mu+\\nu)}{2}}{\\Gamma\\left(\\frac{1-\\mu-\\nu}{2}\\right)\\Gamma\\left(\\frac{\\nu-\\mu}{2}+1\\right)}\n\\]\nwe can evaluate the $\\eta$-dependent part of the Klein-Gordon norm\nto obtain\n\\[\n-i[\\phi_{pl}(\\eta_{0})\\phi_{pl}^{\\star'}(\\eta_{0})-\\phi_{pl}^{\\star}(\\eta_{0})\\phi'_{pl}(\\eta_{0})](\\cosh^{2}\\eta_{0})=\\pi e^{-\\pi\\sqrt{p^{2}-1}}\n\\]\nwhich does not depend on $\\eta_{0}$ due to conservation of the Klein-Gordon\nnorm. We can therefore normalize the modes $\\phi_{pl}$ by replacing\n\\[\n\\phi_{pl}\\to\\frac{e^{\\frac{\\pi}{2}\\sqrt{p^{2}-1}}}{\\pi^{1/2}}\\phi_{pl}\\,.\n\\]\nIn what follows we will assume that this has been done and in the\ninterest of notational simplicity we will use $\\phi_{pl}$ to denote\nthe normalized modes.\n\nTo summarize, for $p^{2}>1$ we have constructed mode functions of\nthe 4d Klein-Gordon equation corresponding to the Minkowski vacuum,\nwhich when restricted to the de Sitter slice $\\rho=1$ correspond\nto the Euclidean vacuum of the 3D de Sitter spacetime. These modes\n$\\Phi_{plm}(\\eta,\\rho,z,\\bar{z})=\\phi_{pl}(\\eta)\\psi_{p}(\\rho)Y_{m}^{l}(z,\\bar{z})$\nare normalized with respect to to the Klein-Gordon norm (\\ref{eq:kgnorm})\nwith the following orthonormality condition\n\\[\n\\langle\\Phi_{plm},\\Phi_{p'l'm'}\\rangle=\\delta(p-p')\\delta_{ll'}\\delta_{mm'}\\,.\n\\]\nFor $0\\le p^{2}<1$, the radial mode functions are not normalizable.\n\n\\section{Unitary Principal Series Representation}\n\n\\label{sec:ups} We are now in a position to build the unitary principal\nseries representation of ${\\rm SO(3,1)}$ which acts on the ${\\rm dS_{3}}$/${\\rm M_{4}}$\nmode functions. Since the action of ${\\rm SO(3,1)}$ on ${\\rm M_{4}}$\nleaves the radial coordinate $\\rho$ invariant, the action is identical\non both ${\\rm dS_{3}}$ mode functions and on ${\\rm M_{4}}$ mode\nfunctions. For simplicity of presentation we will focus on ${\\rm dS_{3}}$\nmodes, but all equations in this section carry over to the ${\\rm M_{4}}$\nmodes trivially.\n\nOn the past and future null infinities $\\mathcal{I^{\\pm}}$ of the\n3D de Sitter spacetime, the Killing vectors can be written as conformal\nKilling vectors of the spatial 2-sphere\n\\[\nL_{n}=-z^{n+1}\\frac{\\partial}{\\partial z},\\,\\bar{L}_{n}=-\\bar{z}^{n+1}\\frac{\\partial}{\\partial\\bar{z}}\n\\]\nwhere $n=0,\\pm1$. However one should use caution in applying this\nformula. It is correct when acting on the metric, or massless scalars,\nbut as we will see there will be additional terms that must be added\ndepending on the class of functions or fields considered. General\ncomplex combinations of these vectors will not preserve the desired\nreality conditions, so we will need to be careful to construct the\ncorrect 6 independent generators that will appear with real coefficients.\n\nTo extend these into the bulk of de Sitter it is helpful to arrange\nthem into an ${\\rm SO(3)}$ corresponding to the isometries of the\nspatial slices. With the convention $g=\\exp(i\\theta J)$ we find the\ngenerators:\n\\begin{align*}\nJ_{1} & =\\frac{i}{2}\\left(L_{-1}+L_{1}+\\bar{L}_{-1}+\\bar{L}_{1}\\right)\\\\\nJ_{2} & =\\frac{1}{2}\\left(L_{-1}-L_{1}-\\bar{L}_{-1}+\\bar{L}_{1}\\right)\\\\\nJ_{3} & =L_{0}-\\bar{L}_{0}\\,.\n\\end{align*}\nThese immediately extend into the bulk without time dependent contributions.\nThis also allows us to read off the conjugation condition to be imposed\non the generators. Since the $J_{k}$ are Hermitian we require\n\\[\nL_{n}^{\\dagger}=-\\bar{L}_{n},\\qquad\\bar{L}_{n}^{\\dagger}=-L_{n}\\,.\n\\]\n\nThe time-dependent Killing vectors take the form\n\\[\nK=F\\frac{\\partial}{\\partial t}+\\frac{1}{2}\\left(1+z\\bar{z}\\right)^{2}\\tanh t\\,\\left(\\partial_{\\bar{z}}F\\right)\\frac{\\partial}{\\partial z}+\\frac{1}{2}\\left(1+z\\bar{z}\\right)^{2}\\tanh t\\,\\left(\\partial_{z}F\\right)\\frac{\\partial}{\\partial\\bar{z}}\n\\]\nwhere $F$ is one of the three solutions\n\\begin{equation}\nF_{z}=\\frac{2z}{1+|z|^{2}}\\qquad F_{\\bar{z}}=\\frac{2\\bar{z}}{1+|z|^{2}}\\qquad F_{t}=\\frac{1-|z|^{2}}{1+|z|^{2}}\\,.\\label{eq:cartesian}\n\\end{equation}\nAt $\\mathcal{I}^{+}$ these reduce to\n\\begin{align*}\n\\tilde{K}_{1} & =L_{1}-\\bar{L}_{-1}\\\\\n\\tilde{K}_{2} & =\\bar{L}_{1}-L_{-1}\\\\\n\\tilde{K}_{3} & =L_{0}+\\bar{L}_{0}\n\\end{align*}\nwhen acting on the metric. It is convenient to assemble these into\nHermitian linear combinations:\n\\begin{align*}\nK_{1} & =\\frac{1}{2}\\left(L_{1}-\\bar{L}_{-1}-\\bar{L}_{1}+L_{-1}\\right)\\\\\nK_{2} & =\\frac{i}{2}\\left(\\bar{L}_{1}-L_{-1}+L_{1}-\\bar{L}_{-1}\\right)\\\\\nK_{3} & =-i\\left(L_{0}+\\bar{L}_{0}\\right)\n\\end{align*}\nwhich at a general spacetime point become\n\\begin{align}\nK_{1} & =\\frac{1}{2}\\left(\\frac{2(z-\\bar{z})}{1+|z|^{2}}\\frac{\\partial}{\\partial t}-\\tanh t\\left(\\left(z^{2}+1\\right)\\frac{\\partial}{\\partial z}-\\left(\\bar{z}^{2}+1\\right)\\frac{\\partial}{\\partial\\bar{z}}\\right)\\right)\\nonumber \\\\\nK_{2} & =\\frac{i}{2}\\left(\\frac{2(z+\\bar{z})}{1+|z|^{2}}\\frac{\\partial}{\\partial t}-\\tanh t\\left(\\left(z^{2}-1\\right)\\frac{\\partial}{\\partial z}+\\left(\\bar{z}^{2}-1\\right)\\frac{\\partial}{\\partial\\bar{z}}\\right)\\right)\\nonumber \\\\\nK_{3} & =-i\\left(\\frac{1-|z|^{2}}{1+|z|^{2}}\\frac{\\partial}{\\partial t}-\\tanh t\\left(z\\frac{\\partial}{\\partial z}+\\bar{z}\\frac{\\partial}{\\partial\\bar{z}}\\right)\\right)\\,.\\label{eq:bulkgen}\n\\end{align}\nNote the generators satisfy the canonical Lorentz algebra\n\\begin{align*}\n[J_{i},J_{j}] & =i\\epsilon_{ijk}J_{k}\\\\{}\n[J_{i},K_{j}] & =i\\epsilon_{ijk}K_{k}\\\\{}\n[K_{i},K_{j}] & =-i\\epsilon_{ijk}J_{k}\\,.\n\\end{align*}\n\nOn the three-dimensional de Sitter mode functions (\\ref{eq:basis})\nthe generators (\\ref{eq:bulkgen}) take the simplified form\n\\begin{align}\nK_{1} & =\\frac{1}{2}\\left(\\frac{2(z-\\bar{z})}{1+|z|^{2}}\\left(2h_{+}-2\\right)-\\left(\\left(z^{2}+1\\right)\\frac{\\partial}{\\partial z}-\\left(\\bar{z}^{2}+1\\right)\\frac{\\partial}{\\partial\\bar{z}}\\right)\\right)\\nonumber \\\\\nK_{2} & =\\frac{i}{2}\\left(\\frac{2(z+\\bar{z})}{1+|z|^{2}}\\left(2h_{+}-2\\right)-\\left(\\left(z^{2}-1\\right)\\frac{\\partial}{\\partial z}+\\left(\\bar{z}^{2}-1\\right)\\frac{\\partial}{\\partial\\bar{z}}\\right)\\right)\\nonumber \\\\\nK_{3} & =-i\\left(\\frac{1-|z|^{2}}{1+|z|^{2}}\\left(2h_{+}-2\\right)-\\left(z\\frac{\\partial}{\\partial z}+\\bar{z}\\frac{\\partial}{\\partial\\bar{z}}\\right)\\right)\\label{eq:bulkgenprin}\n\\end{align}\nwhere we define\n\\[\n2h_{\\pm}=\\frac{d-1}{2}\\pm\\sqrt{\\left(\\frac{d-1}{2}\\right)^{2}-\\mu^{2}}=1\\pm\\sqrt{1-\\mu^{2}}\\,.\n\\]\nTo check this we note that the group of rotations ${\\rm SO(3)}$ acts\nstraightforwardly in the basis \\eqref{eq:basis}. The rotation generators\nalso rotate the $K_{i}$ amongst themselves, so we can focus on the\naction of say $K_{3}$ on the mode functions \\eqref{eq:basis}. It\nis then straightforward to check that\n\\[\n\\frac{\\partial}{\\partial t}\\phi_{l=0}=2(h_{+}-1)\\phi_{l=1}\n\\]\nwhich holds for the solutions $\\phi_{l,1}$ and $\\phi_{l,2}$ of \\eqref{eq:basis}\nindependently and determines the prefactors that appear in \\eqref{eq:bulkgenprin}.\nLikewise, when acting on the four-dimensional Minkowski modes the\ngenerators take the exact same expression with $\\mu$ replaced by\n$p$.\n\nTo confirm the generators match the principal series we will use the\nrepresentation of ${\\rm SO(3,1)}$ on functions $L^{2}(S^{2})$. Note\nthis differs from the more common representation on functions $L^{2}(\\mathbb{C})$,\nwhich would be applicable to the flat slicing of de Sitter. Likewise\nthere is a representation on $L^{2}(H^{2})$, though we won't need\nthat here. The upshot of these different realizations of the principal\nseries is that the extra terms in \\eqref{eq:bulkgenprin} take completely\ndifferent forms.\n\nTo realize the representation we consider the cone $C_{+}^{3}$ embedded\nin 4d Minkowski spacetime, where\n\\[\nx_{1}^{2}+x_{2}^{2}+x_{3}^{2}-x_{0}^{2}=0\\,.\n\\]\nWe then consider the slice through the cone where $x_{0}=1$. This\nslice is an $S^{2}$ which may be parameterized by coordinates $z$\nabove using the Fubini-Study metric. The cone maps into itself under\n${\\rm SO(3,1)}$. The principal series may be defined as functions\non the slice that behave as \\cite{vilenkin1992representation}\n\\begin{equation}\n(T^{\\sigma}(g)f)(z)=\\alpha(z,g)^{\\sigma}f\\left(\\frac{g^{-1}\\cdot z}{\\alpha(z,g)}\\right)\\label{eq:prindef}\n\\end{equation}\nwhere $g$ is a ${\\rm SO(3,1)}$ group element, and $\\alpha(z,g)$\nis defined to be the rescaling factor needed to return $g^{-1}\\cdot x^{\\mu}$\nto the slice $x_{0}=1$. The action of ${\\rm SO(3,1)}$ on $z$ is\nthe usual fraction linear transformation, but the factor $\\alpha$\ndepends on which realization of the principal series we are considering.\nTo write the action of ${\\rm SL}(2,\\mathbb{C})$ on the Minkowski\ncoordinates it is helpful to use the familiar representation\n\\[\nx^{\\mu}=\\frac{1}{2}\\mathrm{Tr}\\left(M\\sigma^{\\mu}\\right),\\qquad M=\\left(\\begin{array}{cc}\nx^{0}+x^{3} & x^{1}-ix^{2}\\\\\nx^{1}+ix^{2} & x^{0}-x^{3}\n\\end{array}\\right),\\qquad\\sigma^{\\mu}=\\left(\\mathbbm{1},\\sigma^{i}\\right)\n\\]\nwhere $\\sigma^{i}$ are the Pauli matrices. Then an ${\\rm SL}(2,\\mathbb{C})$\ntransformation acts as\n\\[\nM'=SMS^{\\dagger}\\,.\n\\]\nTo rescale back to the slice $x^{0}=1$ we rescale to\n\\[\n\\tilde{M}'=\\frac{M'}{\\frac{1}{2}\\mathrm{Tr}\\left(M'\\right)}\\,.\n\\]\nFinally, the coordinates on the 2-sphere $x^{0}=1$ are matched with\nthe Fubini-Study coordinates via\n\\begin{align*}\nx^{1}+ix^{2} & =\\frac{2z}{1+|z|^{2}}\\\\\nx^{1}-ix^{2} & =\\frac{2\\bar{z}}{1+|z|^{2}}\\\\\nx^{3} & =\\frac{1-|z|^{2}}{1+|z|^{2}}\\,.\n\\end{align*}\nFrom these equations we can read off the factor $\\alpha$ and determine\nthe action of the $z$ coordinate. For\n\\[\nS=\\left(\\begin{array}{cc}\na & b\\\\\nc & d\n\\end{array}\\right)\\,,\n\\]\nthe fractional linear transformation is\n\\[\nz'=\\frac{dz+c}{bz+a}\\,.\n\\]\n\nSince we know the group of rotations acts in a straightforward way\non the spherical harmonics, it suffices to consider one of the boost\ngenerators to check the matching of the generators. To do this we\nTaylor expand \\eqref{eq:prindef} for a group element of the form\n$g=\\exp(ik_{3}\\epsilon)$. Plugging in the above relations gives\n\\[\nK_{3}=-i\\left(\\frac{1-|z|^{2}}{1+|z|^{2}}\\sigma-\\left(z\\frac{\\partial}{\\partial z}+\\bar{z}\\frac{\\partial}{\\partial\\bar{z}}\\right)\\right)\\,.\n\\]\nWe therefore identify the scalar field representation with a principal\nseries representation where $\\sigma=-2h_{-}$. We have $\\sigma=-1+i\\sqrt{\\mu^{2}-1}$\nin the notation of \\cite{vilenkin1992representation}. We note the\nequivalence of the representations under the replacement $h_{+}\\to h_{-}$\nand $2h_{+}-2=-2h_{-}$. For the principal series, the inner product\nis simply the usual integral over the 2-sphere in Fubini-Study coordinates\nwhich matches the Klein-Gordon norm up to a constant factor. For $0<\\mu^{2}<1$\nwe have the complementary series representations and the above results\nextend straightforwardly to that case.\n\n\\section{Relation to Previous Work}\n\n\\label{sec:psrep}\n\nHere we show the mode functions computed in Ref.~\\cite{Pasterski:2017kqt}\nform a non-unitary highest-weight representation, and therefore do\nnot produce a unitary principal series representation of $SO(3,1)$.\nTo do so we first show that the generators of the special conformal\ntransformations annihilate a mode function corresponding to the highest\nweight of the representation. The mode functions (eq.~2.19 of \\cite{Pasterski:2017kqt})\nare parameterized by the tuple $(\\Delta,\\vec{w})$ where $\\Delta$\nis in general a complex number and $\\vec{w}=(w_{x},w_{y})\\in\\mathbb{R}^{2}$.\nThese mode functions are\n\\begin{equation}\n\\phi_{\\Delta}^{\\pm}(X^{\\mu};\\vec{w})=\\frac{4\\pi}{(im)}\\frac{(\\sqrt{-X^{2}})^{\\Delta-1}}{(-q(\\vec{w})\\cdot X\\mp i\\epsilon)^{\\Delta}}K_{\\Delta-1}(m\\sqrt{X^{2}})\\,.\\label{eq:psmode}\n\\end{equation}\nHere $X^{\\mu}$ are the usual flat coordinates of the 4d Minkowski\nspacetime ${\\rm M_{4}}$. The $q^{\\mu}(\\vec{w})$ is the following\n4-vector\n\\[\nq^{\\mu}(\\vec{w})=(1+|\\vec{w}|^{2},2\\vec{w},1-|\\vec{w}|^{2})\\,.\n\\]\nThe conformal group ${\\rm SO(3,1)}$ acts on the space of scalar functions\ndefined on ${\\rm M_{4}\\times\\mathbb{R}^{2}}$ by acting on ${\\rm M_{4}}$\nwith the usual Lorentz transformation and on $\\mathbb{R}^{2}$ with\nthe 2D conformal transformations (2D translations, 2D rotations, dilatations\nand special conformal transformations):\n\\[\n\\phi_{\\Delta}(X^{\\mu};\\vec{w})\\to\\phi_{\\Delta}(\\Lambda^{\\mu}{}_{\\nu}X^{\\nu};\\vec{w}'(\\vec{w}))\\,.\n\\]\nHere $\\Lambda^{\\mu}{}_{\\nu}$ is the Lorentz transformation corresponding\nto the ${\\rm SO(3,1)}$ group element, and the $\\vec{w}'(\\vec{w})$\nis the conformal transformation corresponding to the ${\\rm SO(3,1)}$\nelement. For special conformal transformation, it is\n\\[\n\\vec{w}'=\\frac{\\vec{w}+|\\vec{w}|^{2}\\vec{b}}{1+2\\vec{b}\\cdot\\vec{w}+|\\vec{b}|^{2}|\\vec{w}|^{2}}\\,.\n\\]\nThese are labeled by a vector $\\vec{b}\\in\\mathbb{R}^{2}$.\n\nConsider an infinitesimal group element near the identity\n\\[\n\\Lambda^{\\mu}{}_{\\nu}=\\delta_{\\nu}^{\\mu}+(\\delta\\Lambda)^{\\mu}{}_{\\nu}\n\\]\nthis has the corresponding infinitesimal transformation on $\\mathbb{R}^{2}$\n\\[\n\\vec{w}'=\\vec{w}+\\delta\\vec{w}\\,.\n\\]\nIn particular, for the special conformal transformation parameterized\nby an infinitesimal $\\vec{b}$ we have the infinitesimal transformation\n\\[\n\\vec{w}'=\\vec{w}-2(\\vec{w}\\cdot\\vec{b})\\vec{w}+|\\vec{w}|^{2}\\vec{b}\\,.\n\\]\nFollowing the conventions of \\cite{Pasterski:2017kqt} this corresponds\nto the infinitesimal Lorentz transformation where\n\\[\n(\\delta\\omega)^{0}{}_{i}=(\\delta\\omega)^{i}{}_{0}=(\\delta\\omega)^{3}{}_{i}=-(\\delta\\omega)^{i}{}_{3}=b_{i}\n\\]\nwith all other components being zero. Here $i=x,y$ labels the indices\nof $\\mathbb{R}^{2}$. In other words we have\n\\[\n\\begin{bmatrix}X'^{0}\\\\\nX'^{i}\\\\\nX'^{3}\n\\end{bmatrix}=\\begin{bmatrix}X^{0}\\\\\nX^{i}\\\\\nX^{3}\n\\end{bmatrix}+\\begin{bmatrix}b_{i}X^{i}\\\\\nb^{i}(X^{0}-X^{3})\\\\\nb_{i}X^{i}\n\\end{bmatrix}\\,.\n\\]\nTaylor-expanding $\\phi_{\\Delta}(\\Lambda^{\\mu}{}_{\\nu}X^{\\nu};\\vec{w}'(\\vec{w}))$\nand substituting the expressions for $\\delta\\omega$ and $\\delta\\vec{w}$\nabove, we have\n\\begin{align*}\n\\phi_{\\Delta}(\\Lambda^{\\mu}{}_{\\nu}X^{\\nu};\\vec{w}'(\\vec{w})) & =\\phi_{\\Delta}(X^{\\mu}+\\left(\\delta\\omega\\right)_{\\enskip\\nu}^{\\mu}X^{\\nu};\\vec{w}+\\delta\\vec{w})\\\\\n & =\\phi_{\\Delta}(X^{\\nu};\\vec{w})+\\left(\\delta\\omega\\right)_{\\enskip\\nu}^{\\mu}X^{\\nu}\\left(\\frac{\\partial}{\\partial X^{\\mu}}\\phi_{\\Delta}\\right)+\\delta\\vec{w}\\cdot\\left(\\frac{\\partial}{\\partial\\vec{w}}\\phi_{\\Delta}\\right)\\\\\n & =\\phi_{\\Delta}(X^{\\nu};\\vec{w})+b_{i}X^{i}\\left(\\frac{\\partial}{\\partial X^{0}}+\\frac{\\partial}{\\partial X^{3}}\\right)\\phi_{\\Delta}+b^{i}(X^{0}-X^{3})\\left(\\frac{\\partial}{\\partial X^{i}}\\phi_{\\Delta}\\right)\\\\\n & \\qquad+\\left(-2(\\vec{w}\\cdot\\vec{b})\\vec{w}+|\\vec{w}|^{2}\\vec{b}\\right)\\cdot\\left(\\frac{\\partial}{\\partial\\vec{w}}\\phi_{\\Delta}\\right)\\,.\n\\end{align*}\nFor infinitesimal $\\vec{b}$ this evaluates to\n\\begin{equation}\n\\delta\\phi_{\\Delta}=\\frac{8\\pi\\Delta}{im}\\vec{b}\\cdot\\vec{w}\\frac{\\left(\\sqrt{-X^{2}}\\right){}^{\\Delta-1}}{(-q(\\vec{w})\\cdot X\\mp i\\epsilon)^{\\Delta}}K_{\\Delta-1}\\left(m\\sqrt{X^{2}}\\right)\\,.\\label{eq:lxpsmode}\n\\end{equation}\nIn particular, the special conformal transformations annihilate the\nmode functions when the weight $\\vec{w}=(0,0)$. This implies \\cite{doi:10.1142/9789813149441_0001}\nthat the mode functions (\\ref{eq:psmode}) form a highest-weight representation\nof $SO(3,1)$, and since $SO(3,1)$ has only non-unitary highest-weight\nrepresentations, these mode functions cannot form a unitary principal\nseries.\n\n\\section{Discussion}\n\n\\label{sec:further} The results of the previous sections lead to\na proposal for a holographic mapping between the 3D de Sitter modes\nand conformal operators on a two-sphere. Likewise, the construction\nmay be lifted to 4D Minkowski spacetime.\n\n\\begin{comment}\nIn the context of celestial sphere amplitudes \\cite{deBoer:2003vf,Kapec:2014opa,Kapec:2016jld,Cheung:2016iub}\nit is tempting to use our 4D Minkowski spacetime mode functions as\na conformal basis of wavefunctions against which all conformally invariant\namplitudes can be decomposed.\n\\end{comment}\n\n\n\\subsection{Holographic Mapping Between 3D de-Sitter and a Euclidean 2-Sphere}\n\nFor the case of a flat slicing, it was possible to define a bulk-to-boundary\nmap and its inverse map \\cite{Chatterjee:2015pha} via a construction\nreminiscent of the LSZ reduction formula in asymptotically flat spacetime\n\\cite{Lehmann:1954rq}. That construction does not extend immediately\nto the case of the sphere slicing, but we will see the Klein-Gordon\ninner product defined above can still be used to extract a natural\nset of operators living on the 2-sphere.\n\nWe work with a scalar bulk field of mass $\\mu$\n\\begin{equation}\n\\phi(t,z,\\bar{z})=\\sum_{l=0}^{\\infty}\\sum_{m=-l}^{l}a_{lm}\\phi_{lm}(t,z,\\bar{z})+a_{lm}^{\\dagger}\\phi_{lm}^{\\dagger}(t,z,\\bar{z})\\label{eq:modeexpan}\n\\end{equation}\nwhere $\\phi_{lm}$ is defined using the Euclidean vacuum modes \\eqref{eq:evacmode}\nand $a_{lm}$ and $a_{lm}^{\\dagger}$ are standard creation/annihilation\noperators. Let us consider a late-time sphere at $t=T$ and build\nthe following inner product using the Klein-Gordon inner product in\n3D de Sitter spacetime\n\\[\n\\mathcal{O}_{lm}=\\left\\langle \\phi_{lm}(t),\\phi(t,z,\\bar{z})\\right\\rangle _{t=T}\n\\]\nwhich identifies $\\mathcal{O}_{lm}=a_{lm}$. Likewise one can define\n$\\mathcal{O}_{lm}^{\\dagger}=a_{lm}^{\\dagger}$. One may view this\nmapping as a holographic map, with $l,m$ being dual variables to\nthe coordinates on the 2-sphere $z,\\bar{z}$. The formula \\eqref{eq:modeexpan}\ncan then be viewed as the inverse mapping reconstructing the bulk\nfield in terms of boundary operators. The boundary operators will\nobey their usual commutation relations, and at the same time will\ntransform as a representation of the unitary principal series as described\nabove. All the above is established at the level of free field theory.\nOnce interactions are included it seems difficult to view the resulting\nboundary theory as any kind of conventional field theory \\cite{PhysRevD.96.066031}.\n\n\\subsection{Holographic Mapping Between Celestial Sphere and 4D Minkowski}\n\nThis procedure can be extended to the 4D Minkowski case. However we\nwill now have a continuous spectrum of allowed conformal weights $\\Delta$\ncorresponding to the continuous spectrum of radial quantum numbers\n$p$. For a scalar field we can use the orthogonality of the radial\nmode functions \\eqref{eq:radialinnerprod} to project onto a particular\n$p$ eigenvalue and then follow the procedure of the previous subsection\nto build a boundary operator. The mode expansion of the bulk field\nis now\n\\[\n\\Phi(\\eta,\\rho,z,\\bar{z})=\\sum_{l=0}^{\\infty}\\sum_{m=-l}^{l}\\int_{1}^{\\infty}dp\\left(a_{plm}\\Phi_{plm}(\\eta,\\rho,z,\\bar{z})+a_{plm}^{\\dagger}\\Phi_{plm}^{\\dagger}(\\eta,\\rho,z,\\bar{z})\\right)\n\\]\nwhere $a_{plm}$ and $a_{plm}^{\\dagger}$ are annihilation and creation\noperators. Again we can define an operator on the celestial 2-sphere\nby constructing\n\\[\n\\mathcal{O}_{\\Delta_{p},lm}=\\left\\langle \\Phi_{plm}(\\eta,\\rho,z,\\bar{z}),\\Phi(\\eta,\\rho,z,\\bar{z})\\right\\rangle =a_{plm}\n\\]\nwhere the operator transforms as a unitary principal series representation\nparameterized by $\\Delta_{p}$. Likewise one may define a conjugate\noperator $\\mathcal{O}_{\\Delta_{p},lm}^{\\dagger}=a_{plm}^{\\dagger}$.\nWe can therefore interpret this as a holographic map between the bulk\n4D Minkowski spacetime and the boundary 2D celestial sphere. One ends\nup with a continuous family of boundary operators labelled by the\nradial quantum number $p$. As above, it is not clear how the construction\nextends to interacting theories.\n\n\\chapter{Conformal Wavefunctions for Graviton Amplitudes}\\label{chap:gravitons}\nBuilding on the results of the previous chapter, it is of interest to study the\nrepresentations of the $\\rm SO(3,1)$ group associated with gravitons. To reduce the equation of\nmotion to a Schr\\\"odinger-like equation it is necessary to impose a\nnon-covariant gauge condition. Using these solutions, leading-order\ngauge invariant Weyl scalars are then computed and decomposed into\nfamilies of unitary principal series representations. An invertible\nholographic mapping is constructed between these unitary principal\nseries operators and massless spin-2 perturbations of flat spacetime.\n\n\\section{Introduction}\n\nIn the previous chapter, massive scalar fields in 4D\nMinkowski spacetime were decomposed into modes on 3D de-Sitter spacetime\nslices where they form unitary principal series representations of\n${\\rm SO(3,1)}$. This study was motivated by the program of \\cite{Pasterski:2016qvg}\nwhere the goal is to formulate gravity in asymptotically flat spacetime\nas a theory on the celestial sphere with conformal symmetry. In this\nchapter we extend this construction to massless spin-2 particles, or\ngravitons, in 4D Minkowski spacetime. To this end, we consider linearized\ngravitational waves living in flat 4D background spacetime with the\nstandard spherical coordinates. The background metric is simply\n\\[\ng_{\\mu\\nu}=\\diag(-1,1,r^{2},r^{2}\\sin^{2}\\theta)\n\\]\nFollowing the notations in \\cite{Bernar:2014lna}, from now on indices\n$a,b,c,\\ldots$ refer to the ``orbit'' spacetime labeled by the\ncoordinates $(t,r)$, and $i,j,k,\\ldots$ refer to the 2-sphere labeled\nby $(\\theta,\\varphi)$. In other words, we write the background metric\nas\n\\[\ng_{\\mu\\nu}\\,\\dd x^{\\mu}\\dd x^{\\nu}=g_{ab}\\,\\dd y^{a}\\dd y^{b}+r^{2}\\,\\dd\\sigma^{2}\n\\]\nwhere $g_{ab}=\\diag(-1,1)$ and $\\dd\\sigma^{2}=\\gamma_{ij}\\,\\dd z^{i}\\dd z^{j}=\\dd\\theta^{2}+\\sin^{2}\\theta\\,\\dd\\varphi^{2}$.\n\nFor Minkowski spacetime in four dimensions, the gravitational perturbations\ncan be expanded in terms of both the scalar and the vector spherical\nharmonics defined on the 2-sphere. These are also known as the ``even''\nand ``odd'' waves in \\cite{PhysRev.108.1063}, and will automatically\nhave the desired transformation properties under the rotation group\n${\\rm SO(3)}$. However, as we shall see, the specific gauge conditions\nthat we will choose in what follows are not Lorentz covariant, and\ntherefore these metric perturbations do not transform as tensors under\nthe full ${\\rm SO(3,1)}$ group. To remedy this, we consider the Newman-Penrose\nformalism \\cite{doi:10.1063/1.1724257} of general relativity and\nconstruct leading-order gauge-invariant scalars known as the Weyl\nscalars. These scalars can then be mapped onto the celestial sphere\nthrough a generalization of the method described in the previous work\n\\cite{Liu:2021tif}. This generalization involves performing a spectral\ndecomposition into radial eigenvalues using the Meijer K-transform\n\\cite{meijer1940a,meijer1940b}. We therefore obtain an invertible\nholographic map between graviton fields on the flat Minkowski background\nspacetime and conformal operators on the celestial sphere. We stress\nthat this procedure is defined for tree-level amplitudes and it remains\nto be seen whether an interacting holographic theory can be defined\nindependently of the four-dimensional gravitational description.\n\n\\section{Graviton Wavefunctions}\n\n\\subsection{Scalar Perturbations}\n\nRefs.~\\cite{Kodama:2003jz,doi:10.1142/S0218271816410169} present\na general formalism which expresses the metric perturbation $h_{\\mu\\nu}$\nin terms of a master function $\\phi$. For the scalar perturbation,\na gauge choice allows us to express the metric perturbation $h_{\\mu\\nu}$,\nexpanded in terms of the spherical harmonics $Y_{lm}$, as\n\\begin{equation}\nh_{ab}=f_{ab}Y_{lm},\\quad h_{ai}=0,\\quad h_{ij}=f\\,\\gamma_{ij}Y_{lm}\\label{eq:ansatz}\n\\end{equation}\nwhere $f_{ab}$ and $f$ are functions that are related to a master\nfunction $\\phi(t,r)$\n\\begin{align}\nf & =\\frac{l(l+1)r\\phi}{2}+r^{2}\\partial_{r}\\phi\\nonumber \\\\\nf_{ab} & =\\partial_{a}\\partial_{b}(r\\phi)-\\frac{g_{ab}}{2}\\Box(r\\phi)\\nonumber \\\\\n & =r\\partial_{a}\\partial_{b}\\phi+\\partial_{a}r\\,\\partial_{b}\\phi+\\partial_{b}r\\,\\partial_{a}\\phi-\\frac{g_{ab}}{2}(r\\Box\\phi+2\\partial_{r}\\phi)\\,.\\label{eq:fab}\n\\end{align}\nHere $\\partial_{a}r\\partial_{b}\\phi$ stands for $(\\partial_{a}r)(\\partial_{b}\\phi)$\nand $\\Box$ is the d'Alembertian on the orbit spacetime. The components\nof $f_{ab}$ are\n\\begin{align*}\nf_{tt} & =f_{rr}=r\\partial_{t}^{2}\\phi+\\partial_{r}\\phi+\\frac{l(l+1)}{2r}\\phi\\\\\nf_{tr} & =r\\partial_{t}\\partial_{r}\\phi+\\partial_{t}\\phi\\,.\n\\end{align*}\nThe master function $\\phi(t,r)$ satisfies the following master equation\n\\[\n\\Box\\phi-\\frac{l(l+1)}{r^{2}}\\phi=0\n\\]\nwhich can be solved to yield a basis of mode functions\n\\[\n\\phi_{\\omega l}(t,r)=e^{-i\\omega t}\\sqrt{r}(c_{1}J_{l+\\frac{1}{2}}(\\omega r)+c_{2}Y_{l+\\frac{1}{2}}(\\omega r))\n\\]\nfor $\\omega\\neq0$. Here $J_{n}$ is the Bessel function of first\nkind and $Y_{n}$ is the Bessel function of second kind. We demand\nthat the mode functions be regular at the origin, and therefore discard\nthe second set of solutions. We therefore find the (unnormalized)\nmodes for the master function\n\\[\n\\phi_{\\omega l}(t,r)=e^{-i\\omega t}\\sqrt{r}J_{l+\\frac{1}{2}}(\\omega r)\\,.\n\\]\nFor $\\omega\\neq0$ this agrees with the master equation found in Ref.~\\cite{PhysRevLett.24.737}.\n\nFor $\\omega=0$ we have the special time-independent solution of the\nmaster equation\n\\[\n\\phi_{0l}(t,r)=c_{1}r^{l+1}+c_{2}r^{-l}\\,.\n\\]\nDiscarding solutions that are divergent at $r\\to\\infty$ we find the\nbasis of functions for the $\\omega=0$ modes\n\\[\n\\phi_{0l}(t,r)=r^{-l}\\,.\n\\]\nPhysically this represents a time-independent spacetime perturbation\nthat is rotating at a constant angular momentum (for $l\\neq0$. For\n$l=0$ the metric perturbation is zero), similar to the eternal Kerr\nblack hole which appears to a distant observer as having a total angular\nmomentum. Substituting the master function into eq.~\\ref{eq:ansatz}\nwe find the scalar metric perturbation for $\\omega=0$\n\\[\nh_{\\mu\\nu}=Y_{lm}\\begin{bmatrix}\\frac{l(l-1)}{2}r^{-l-1} & 0 & 0 & 0\\\\\n0 & \\frac{l(l-1)}{2}r^{-l-1} & 0 & 0\\\\\n0 & 0 & \\frac{l(l-1)}{2}r^{1-l} & 0\\\\\n0 & 0 & 0 & \\frac{l(l-1)}{2}r^{1-l}\\sin^{2}\\theta\n\\end{bmatrix}\\,.\n\\]\n\n\n\\subsection{Vector Perturbations}\n\nWe define the vector spherical harmonics as a vector field $Y_{i}^{(lm)}$\non the unit 2-sphere satisfying\n\\[\n[\\Delta_{2}+(l(l+1)-1)]Y_{i}^{(lm)}=0\n\\]\nwith $D^{i}Y^{(lm)}{}_{i}=0$. Here $\\Delta_{2}$ and $D_{i}$ are\nthe Laplace operator and the covariant derivative on the unit 2-sphere,\nrespectively. In terms of the scalar spherical harmonics $Y_{lm}$\nwe find\n\\[\nY_{i}^{(lm)}(\\theta,\\varphi)=\\frac{\\epsilon_{ij}}{\\sqrt{l(l+1)}}\\partial^{j}Y_{lm}(\\theta,\\varphi)\n\\]\nHere indices are raised and lowered using the metric $\\gamma_{ij}$\non the unit 2-sphere, and $\\epsilon^{ij}$ is the Levi-Civita tensor\non the 2-sphere defined by $\\epsilon_{\\theta\\varphi}=\\sqrt{|\\det\\gamma_{ij}|}=\\sin\\theta$.\nGiven suitable gauge choice \\cite{PhysRev.108.1063}, the metric perturbation\ncan then be expanded in terms of $Y_{i}^{(lm)}$ as follows\n\\begin{equation}\nh_{ab}=0,\\quad h_{ai}=f_{a}Y_{i}^{(lm)},\\quad h_{ij}=0\\label{eq:vectoransatz}\n\\end{equation}\nwhere $f^{a}$ is related to the master function $\\phi(t,r)$ above\nvia\n\\[\nf^{a}=\\epsilon^{ab}\\partial_{b}(r\\phi)\\,.\n\\]\nHere $\\epsilon_{ab}$ is the Levi-Civita tensor on the two-dimensional\norbit spacetime defined by $\\epsilon^{tr}=+1$. For $\\omega\\neq0$\nthis agrees with the so-called odd waves in Ref.~\\cite{PhysRev.108.1063}.\nFor $\\omega=0$ substituting the master function $\\phi=r^{-l}$ into\neq.~\\ref{eq:vectoransatz} we find the metric perturbation\n\\[\nh_{\\mu\\nu}=\\sqrt{\\frac{l}{l+1}}r^{-l-1}\\begin{bmatrix}0 & 0 & \\frac{1}{\\sin\\theta}\\partial_{\\varphi}Y_{lm} & -\\sin\\theta\\,\\partial_{\\theta}Y_{lm}\\\\\n0 & 0 & 0 & 0\\\\\n\\frac{1}{\\sin\\theta}\\partial_{\\varphi}Y_{lm} & 0 & 0 & 0\\\\\n-\\sin\\theta\\,\\partial_{\\theta}Y_{lm} & 0 & 0 & 0\n\\end{bmatrix}\\,.\n\\]\n\n\n\\section{Klein-Gordon Inner Product}\n\nThe metric perturbation expressions constructed above are yet to be\nnormalized. Following \\cite{doi:10.1142/S0218271816410169} we define\nthe inner product between two metric perturbations $h_{\\mu\\nu}$ and\n$h'_{\\mu\\nu}$ as\n\\[\n\\langle h,h'\\rangle=-i\\int_{\\Sigma}\\dd\\Sigma\\,n_{\\lambda}(h_{\\mu\\nu}^{\\star}p'{}^{\\lambda\\mu\\nu}-h'_{\\mu\\nu}p^{\\star\\lambda\\mu\\nu})\n\\]\nwhere $\\Sigma$ is a Cauchy surface and $n^{\\lambda}$ is the future-directed\nunit vector field normal to $\\Sigma$. Here $p^{\\lambda\\mu\\nu}$ is\nthe conjugate momentum current\n\\[\np^{\\lambda\\mu\\nu}=g^{\\lambda\\nu}\\nabla_{\\kappa}h^{\\kappa\\nu}+g^{\\lambda\\nu}\\nabla_{\\kappa}h^{\\kappa\\mu}-\\nabla^{\\lambda}h^{\\mu\\nu}+g^{\\mu\\nu}(\\nabla^{\\lambda}h-\\nabla^{\\kappa}h^{\\lambda}{}_{\\kappa})-\\frac{g^{\\lambda\\nu}\\nabla^{\\mu}h+g^{\\lambda\\mu}\\nabla^{\\nu}h}{2}\n\\]\nHere all indices are raised and lowered with respect the the background\nmetric $g_{\\mu\\nu}$ and $\\nabla$ is the covariant derivative of\nthe background metric.\n\n\\subsection{Scalar Perturbations}\n\nFor the scalar perturbation Ref.~\\cite{doi:10.1142/S0218271816410169}\neq.~88 has shown that for $h_{\\mu\\nu}^{\\omega lm}$ and $h_{\\mu\\nu}^{\\omega'l'm'}$,\nderived from the master function $\\phi_{\\omega l}$ and $\\phi_{\\omega'l'}$\nvia eq.~\\ref{eq:ansatz} respectively, the conserved inner product\nis\n\\[\n\\langle h^{\\omega lm},h^{\\omega'l'm'}\\rangle=-i\\int_{0}^{+\\infty}\\dd r\\,\\delta_{ll'}\\delta_{mm'}\\,J^{0}\n\\]\nwhere the orbit spacetime current $J^{a}$ is given by\n\\[\nJ^{a}=\\frac{4}{r}\\partial^{c}r(f^{\\star ab}f'_{bc}-f^{ab}f'{}_{bc}^{\\star})-(f^{\\star bc}\\partial^{a}f'_{bc}-f'{}^{bc}\\partial^{a}f_{bc}^{\\star})\\,\n\\]\nHere $f_{ab}$ is related to the master function $\\phi_{\\omega l}$\nand $f'_{ab}$ is related to the master function $\\phi_{\\omega'l'}$\nvia eq.~\\ref{eq:fab}. Substituting eq.~\\ref{eq:fab} and following\nthe derivations in eqs.~90--100 and Appendix B of Ref.~\\cite{doi:10.1142/S0218271816410169}\nwe find\n\\[\nJ^{0}=-\\frac{l(l-1)(l+1)(l+2)}{2}(\\phi_{\\omega l}^{\\star}\\partial_{t}\\phi_{\\omega'l'}-\\phi_{\\omega'l'}\\partial_{t}\\phi_{\\omega l}^{\\star})\\,.\n\\]\nFor $\\phi_{\\omega l}=e^{-i\\omega t}\\sqrt{r}J_{l+\\frac{1}{2}}(\\omega r)$\nwe have\n\\[\ni\\,(\\phi_{\\omega l}^{\\star}\\partial_{t}\\phi_{\\omega'l}-\\phi_{\\omega'l}\\partial_{t}\\phi_{\\omega l}^{\\star})|_{t=0}=(\\omega+\\omega')rJ_{l+\\frac{1}{2}}(r\\omega)J_{l+\\frac{1}{2}}(r\\omega')\\,.\n\\]\nUsing\n\\[\n\\int_{0}^{\\infty}rJ_{\\alpha}(\\omega r)J_{\\alpha}(\\omega'r)\\,\\dd r=\\frac{\\delta(w-w')}{\\omega}\n\\]\nwe find\n\\[\n\\langle h^{\\omega lm},h^{\\omega'l'm'}\\rangle=l(l-1)(l+1)(l+2)\\delta(\\omega-\\omega')\\delta_{ll'}\\delta_{mm'}\\,.\n\\]\nWe see that in order to normalize the metric perturbations to have\n\\[\n\\langle h^{\\omega lm},h^{\\omega'l'm'}\\rangle=\\delta(\\omega-\\omega')\\delta_{ll'}\\delta_{mm'}\n\\]\nwe will perform a change of variable $h_{\\mu\\nu}\\to[l(l-1)(l+1)(l+2)]^{-1/2}h_{\\mu\\nu}$.\nIn the interest of notational clarity we will assume this has been\ndone and will continue to use $h_{\\mu\\nu}$ to denote the normalized\nscalar metric perturbation.\n\n\\subsection{Vector Perturbations}\n\nFor the vector perturbations Ref.~\\cite{doi:10.1142/S0218271816410169}\neq.~A10 has shown that for $h_{\\mu\\nu}^{V}$ and $\\left.h'\\right._{\\mu\\nu}^{V}$\ngiven by master functions $\\phi_{\\omega lm}$ and $\\phi_{\\omega'l'm'}$\n(via eq.~\\ref{eq:vectoransatz}) we have\n\\[\n\\langle h^{V},h'{}^{V}\\rangle=-i\\,\\delta_{ll'}\\delta_{mm'}(l-1)(l+2)\\int_{0}^{+\\infty}\\dd r\\,(\\phi_{\\omega l}^{\\star}\\partial_{t}\\phi_{\\omega'l'}-\\phi_{\\omega'l'}\\partial_{t}\\phi_{\\omega l}^{\\star})\\,.\n\\]\nFollowing the calculations of the previous section we find\n\\[\n\\langle h^{V},\\tilde{h}^{V}\\rangle=2(l-1)(l+2)\\delta(\\omega-\\omega')\\delta_{ll'}\\delta_{mm'}\\,.\n\\]\nWe see that a change of variable $h_{\\mu\\nu}^{V}\\to[2(l-1)(l+2)]^{-1/2}h_{\\mu\\nu}$\nwill allow us to normalize the vector metric perturbations to have\n\\[\n\\langle(h^{V})^{\\omega lm},(h^{V})^{\\omega'l'm'}\\rangle=\\delta(\\omega-\\omega')\\delta_{ll'}\\delta_{mm'}\\,.\n\\]\n\n\n\\section{Gauge Invariant Observables}\n\nThe solutions we have described above depend on the choice of gauge\n\\eqref{eq:ansatz}. Since our graviton modes are expanded in terms\nof scalar or vector spherical harmonics, we expect that they transform\nunder the rotation group ${\\rm SO(3)}$ in the usual way. Indeed,\ndenoting $(h^{S})_{\\mu\\nu}^{\\omega lm}$ by $|\\omega lm\\rangle$,\nwe find that\n\\[\nL_{3}\\,|\\omega lm\\rangle=m\\,|\\omega lm\\rangle\n\\]\nand\n\\[\n(L_{1}\\pm iL_{2})\\,|\\omega lm\\rangle=\\sqrt{(l\\mp m)(l\\pm m+1)}\\,|\\omega l,m\\pm1\\rangle\n\\]\nwhere the rotation operators $L_{i}$ act on the graviton modes as\n\\[\nL_{i}h_{\\mu\\nu}=-i\\,[\\epsilon_{ijk}x^{j}\\partial^{k}h_{\\mu\\nu}+(\\omega_{ij})_{\\mu}{}^{\\lambda}h_{\\lambda\\nu}+(\\omega_{ij})_{\\nu}{}^{\\lambda}h_{\\mu\\lambda}]\n\\]\nwith\n\\[\n(\\omega_{\\mu\\nu})_{\\alpha}{}^{\\beta}=\\eta_{\\mu\\alpha}\\delta_{\\nu}^{\\beta}-\\eta_{\\nu\\alpha}\\delta_{\\mu}^{\\beta}\\,.\n\\]\nHowever, since the gauge conditions (eqs.~\\ref{eq:ansatz},\\ref{eq:vectoransatz})\nfor either the scalar and vector perturbations are not Lorentz covariant,\nwe do not expect that these graviton modes transform as representations\nof the full Lorentz group ${\\rm SO(3,1)}$. Indeed, acting with the\nboost operators\n\\[\nK_{i}h_{\\mu\\nu}=-i\\,[(x^{0}\\partial^{i}-x^{i}\\partial^{0})h_{\\mu\\nu}+(\\omega_{0i})_{\\mu}{}^{\\lambda}h_{\\lambda\\nu}+(\\omega_{0i})_{\\nu}{}^{\\lambda}h_{\\mu\\lambda}]\n\\]\ndoes not produce the correct Lorentz algebra. In order to restore\nthe correct Lorentz algebra, one needs to perform additional gauge\ntransformations after a boost to restore the gauge conditions (eqs.~\\ref{eq:ansatz},\\ref{eq:vectoransatz}).\nThe exact gauge transformations required are non-trivial and do not\nhave a closed expression as far as we know.\n\nAlternatively, one could consider the transverse-traceless gauge that\nis indeed Lorentz covariant and rewrite our graviton modes in this\ngauge, and attempt to quantize such a theory with a procedure similar\nto the Gupta-Bleuler formalism of electromagnetism. However this procedure\ndoes not provide a complete gauge fixing, and one is still left with\na Hilbert space containing zero-norm states. Neither of these approaches\nwill be completely satisfactory in producing a conformal description\nof the graviton modes as gauge invariant operators on the celestial\nsphere.\n\nIn the context of AdS/CFT the usual procedure would be to adopt Fefferman-Graham\ncoordinates where one can simply identify components of the metric\nexpansion around spatial infinity with a boundary stress-energy tensor.\nThe boundary stress-energy tensor then provides a complete description\nof the boundary data for gravitational waves.\n\nFinding an analogous set of variables in the case of asymptotically\nflat spacetime is a somewhat more thorny problem. One approach is\nsimply to choose a Bondi metric near null infinity \\cite{doi:10.1098/rspa.1962.0161,doi:10.1098/rspa.1962.0206}\nand describe the gravitational waves using the asymptotic variables\nthat appear there. Another approach, used in the numerical study of\ngravitational waves from time-dependent collapsing/colliding objects,\nis to instead pick a distinguished tetrad and compute the so-called\nWeyl scalars (see for example \\cite{PhysRevD.73.064005,Nerozzi:2016kky}.\nAn infinitesimal gauge transformation of the Riemann tensor is\n\\[\n\\delta R_{\\mu\\nu\\beta}^{\\alpha}=\\mathcal{L}_{\\xi}R_{\\mu\\nu\\beta}^{\\alpha}\n\\]\nwhere $\\xi$ parameterizes the diffeomorphism and $\\mathcal{L}_{\\xi}$\nis the Lie derivative. Since the Lie derivative is linear in $R_{\\mu\\nu\\beta}^{\\alpha}$\nand linear in $\\xi$ this will vanish at leading order in $\\xi$ if\nthe Riemann tensor is computed at linear order in the perturbation\naround flat spacetime. So the Weyl scalars, which amount to picking\nparticular components of the Riemann tensor in this context, will\nbe a set of gauge invariant observables at leading order.\n\nWe are therefore led to the consideration of the so-called spin-coefficient\nformalism \\cite{deFelice:1990hu} of general relativity, a special\nexample of which is known as the Newman-Penrose formalism \\cite{doi:10.1063/1.1724257}.\nHere one picks a null tetrad satisfying\n\\[\nl_{\\mu}l^{\\mu}=n_{\\mu}n^{\\mu}=m_{\\mu}m^{\\mu}=\\bar{m}_{\\mu}\\bar{m}^{\\mu}=0\n\\]\nnormalized so that\n\\[\nl_{\\mu}n^{\\mu}=-1,\\qquad m_{\\mu}\\bar{m}^{\\mu}=1\n\\]\nwith other cross contractions between two vectors vanishing. For our\nspecific purpose we will pick the limit of the Kinnersley tetrad \\cite{kinnersley}\n\\begin{align}\nl^{\\mu} & =\\left(1,1,0,0\\right)\\,,\\qquad n^{\\mu}=\\left(\\frac{1}{2},-\\frac{1}{2},0,0\\right)\\,,\\nonumber \\\\\nm^{\\mu} & =\\frac{1}{\\sqrt{2}r}\\left(0,0,1,\\frac{i}{\\sin\\theta}\\right)\\,,\\qquad\\bar{m}^{\\mu}=\\frac{1}{\\sqrt{2}r}\\left(0,0,1,-\\frac{i}{\\sin\\theta}\\right)\\,.\\label{eq:kinner}\n\\end{align}\nThe five Weyl scalars $\\Psi_{i}$ for $i=0,\\ldots,4$ are built out\nof the Weyl tensor $C_{\\alpha\\beta\\gamma\\delta}$ of the full spacetime\nas\n\\begin{align}\n\\Psi_{0} & =C_{\\alpha\\beta\\gamma\\delta}\\,l^{\\alpha}m^{\\beta}l^{\\gamma}m^{\\delta}\\label{eq:weylscalarstart}\\\\\n\\Psi_{1} & =C_{\\alpha\\beta\\gamma\\delta}\\,l^{\\alpha}n^{\\beta}l^{\\gamma}m^{\\delta}\\\\\n\\Psi_{2} & =C_{\\alpha\\beta\\gamma\\delta}\\,l^{\\alpha}m^{\\beta}\\bar{m}^{\\gamma}n^{\\delta}\\\\\n\\Psi_{3} & =C_{\\alpha\\beta\\gamma\\delta}\\,l^{\\alpha}n^{\\beta}\\bar{m}^{\\gamma}n^{\\delta}\\\\\n\\Psi_{4} & =C_{\\alpha\\beta\\gamma\\delta}\\,n^{\\alpha}\\bar{m}^{\\beta}n^{\\gamma}m^{\\delta}\\,.\\label{eq:weylscalarend}\n\\end{align}\nHere we expand $C_{\\alpha\\beta\\gamma\\delta}$ to first order in $h_{\\mu\\nu}$.\nSince the full spacetime satisfies the vacuum Einstein equation, we\nfind that the Weyl tensor $C_{\\alpha\\beta\\gamma\\delta}$ is equal\nto the Riemann tensor $R_{\\alpha\\beta\\gamma\\delta}$. The Weyl scalars,\ngauge invariant under infinitesimal gauge transformations, may then\nbe expressed in terms of the graviton wavefunctions of the previous\nsection. Our strategy will then be to decompose these gauge invariant\nscalars into representations of the conformal group.\n\nNote that for a particular value of $l,m$ it would be possible to\nfind modification of the tetrad, at leading order in the perturbation,\nsuch as picking $l$ along a principal null direction, that would\nmake some of the Weyl scalars vanish. However if make pick the tetrad\nindependently of the perturbation, all the Weyl scalars will typically\nbe non-vanishing, and will provide a basis for gauge invariant observables\n(at leading order).\n\nA straightforward calculation leads to the expressions for the Weyl\nscalars evaluated on the scalar and vector perturbations in appendices\nA and B respectively. These expressions involve radial derivations\nof the master function $\\phi(t,r)$ and angular derivatives of the\nspherical harmonics. For us, the main point is that the Weyl scalars\ndo not satisfy a simple wave equation in 4D spacetime. In order to\nuse the methods of \\cite{Liu:2021tif} we next must perform a spectral\ndecomposition in the radial direction to allow us to use that basis\nfunctions as a complete basis for the Weyl scalars.\n\n\\section{Holographic Mapping to the Celestial Sphere}\n\nThe Weyl scalars encode all the information of the gravitational perturbations.\nOur strategy will be to proceed in two steps: first consider a fixed\nradius 3D de Sitter slice of flat spacetime, and use the Plancherel\n(or completeness) theorem for the unitary principal series representations\nto decompose a general function on such a slice into irreducible representations;\nnext we allow for a general radial variation of such functions, effectively\ndecomposing a general solution into solutions of the 4D massive scalar\nwave equations with a continuous spectrum of masses.\n\nThe starting point is the unitary principal series mode functions\nthat we have computed in \\cite{Liu:2021tif}\n\\[\n\\Phi_{pMlm}(\\eta,\\rho,z,\\bar{z})=\\phi_{pl}(\\eta)\\,\\psi_{pM}(\\rho)\\,Y_{m}^{l}(z,\\bar{z})\n\\]\nwhere\n\\[\n\\phi_{pl}(\\eta)=\\sech\\eta\\left[\\frac{i\\pi}{2}P_{l}^{i\\sqrt{p^{2}-1}}\\left(\\tanh\\eta\\right)+Q_{l}^{i\\sqrt{p^{2}-1}}\\left(\\tanh\\eta\\right)\\right]\n\\]\nand\n\\[\n\\psi_{pM}(\\rho)=\\frac{K_{i\\sqrt{p^{2}-1}}(M\\rho)}{\\rho}\\,.\n\\]\nHere $M$ is the 4D scalar mass, $l,m$ are the usual angular momentum\nquantum numbers, and $p$ labels the unitary principal series representation\nand also behaves as a radial quantum number. $K_{\\nu}(x)$ is the\nmodified Bessel function of second kind, and $(\\eta,\\rho,z,\\bar{z})$\nare the hyperbolic coordinates on Minkowski spacetime with metric\n\\[\n\\dd s^{2}=-\\rho^{2}\\dd\\eta^{2}+\\dd\\rho^{2}+\\rho^{2}\\cosh^{2}\\eta\\,\\frac{4\\,\\dd z\\,\\dd\\bar{z}}{(1+|z|^{2})^{2}}\\,.\n\\]\nWe will apply the main result of Ref.~\\cite{Liu:2021tif}, which\nstates that these modes $\\Phi_{pMlm}$ form a unitary principal series\nrepresentation of ${\\rm SO(3,1)}$. This allows us to apply the Plancherel\ntheorem \\cite{knapp2001representation} and map the Weyl scalars into\nsets of conformal operators defined on the celestial sphere. We now\ndiscuss this procedure in detail.\n\nTo motivate the full 4D map, let us first consider the simpler case\nwhere one is to construct a holographic map on the 3D de-Sitter slice\n(which we take to be the $\\rho=1$ hypersurface) of 4D Minkowski.\nOn the 3D de-Sitter slice, the mode functions $\\Phi_{pMlm}$ above\nreduce to the mode functions $\\phi_{plm}(\\eta,z,\\bar{z})=\\phi_{pl}(\\eta)Y_{lm}(z,\\bar{z})$.\nWe can then use these modes as basis for the analogue of Fourier transform,\nand maps a scalar function $f(\\eta,z,\\bar{z})$ into ``Fourier''\ncoefficients labeled by $\\hat{f}(p,l,m)$\n\\[\n\\hat{f}(p,l,m)=\\int_{-\\infty}^{+\\infty}\\cosh^{2}\\eta\\,\\dd\\eta\\int_{\\mathbb{C}}\\frac{4\\dd z\\dd\\bar{z}}{(1+|z|^{2})^{2}}\\,\\bar{\\phi}_{pl}(\\eta)\\,\\bar{Y}_{lm}(z,\\bar{z})\\,f(\\eta,z,\\bar{z})\\,.\n\\]\nThe Plancherel theorem \\cite{knapp2001representation} guarantees\nthat this map is unitary. Using eq.~10.40 of Ref.~\\cite{knapp2001representation},\nwe find the inverse map\n\\[\nf(\\eta,z,\\bar{z})=\\int_{1}^{\\infty}2p\\tanh\\left(\\frac{\\pi}{2}\\sqrt{p^{2}-1}\\right)\\dd p\\sum_{lm}\\phi_{pl}(\\eta)\\,Y_{lm}(z,\\bar{z})\\,\\hat{f}(p,l,m)\\,.\n\\]\nIn particular, the integral measure of the inverse map follows from\nsetting $v=\\sqrt{p^{2}-1}$ in the expression $v\\tanh(\\pi v/2)\\,\\dd v$ of eq.~10.40 in\nRef.~\\cite{knapp2001representation}, and multiplying it by two, since\nboth $p\\in(1,+\\infty)$ and $p\\in(-\\infty,-1)$ map to $v\\in(0,+\\infty)$.\n\nIn order to include the radial variation of the scalars, we note the\nfact that the following Meijer $K$-transform of order $\\nu$, defined\nfor a function $f(x)$ as\n\\[\n\\hat{f}(y)=\\int_{0}^{\\infty}f(x)K_{\\nu}(xy)\\,(xy)^{1/2}\\,\\dd x\n\\]\nhas the following inverse transform\n\\[\nf(x)=\\frac{1}{\\pi i}\\int_{c-i\\infty}^{c+i\\infty}\\hat{f}(y)I_{\\nu}(xy)\\,(xy)^{1/2}\\,\\dd y\n\\]\nwhere $c$ is an arbitrary real number and $I_{\\nu}(x)$ is the modified\nBessel function of the first kind. This is developed in a series of\npapers \\cite{meijer1940a,meijer1940b,Boas1942a,Boas1942b} and summarized\nin Chapter X of Ref.~\\cite{bateman1954tables}, which we simply quote\nwithout going into further details of the proof. This gives us a unitary\ntransformation for the radial component, from which we obtain the\nfull 4D forward and inverse map: given a scalar function $\\Psi(\\eta,\\rho,z,\\bar{z})$,\nwe define the following analogue of the Fourier transform on four-dimensional\nMinkowski spacetime\n\\begin{equation}\n\\hat{\\Psi}(p,M,l,m)=\\int_{-\\infty}^{+\\infty}d\\eta\\,\\bar{\\phi}_{pl}(\\eta)\\cosh^{2}\\eta\\,\\int_{0}^{\\infty}d\\rho K_{i\\sqrt{p^{2}-1}}(M\\rho)(M\\rho)^{1/2}\\,\\int_{\\mathbb{C}}\\frac{4\\dd z\\dd\\bar{z}}{(1+|z|^{2})^{2}}\\bar{Y}_{lm}(z,\\bar{z})\\,\\Psi(\\eta,\\rho,z,\\bar{z})\\label{eq:forwardmap}\n\\end{equation}\nthat maps any scalar function $\\Psi(\\eta,\\rho,z,\\bar{z})$ to ``Fourier''\ncoefficients $\\hat{\\Psi}$ labeled by $(p,M,l,m)$, where $p>1$,\n$M>0$, $l\\ge0$, and $-l\\le m\\le l$. We note this $\\rho$ integral\nis indeed convergent. This transformation is invertible, with the\ninverse map given by\n\\begin{align}\n\\Psi(\\eta,\\rho,z,\\bar{z})={}\\frac{1}{\\pi i} & \\int_{1}^{+\\infty}2p\\tanh\\left(\\frac{\\pi}{2}\\sqrt{p^{2}-1}\\right)\\,\\dd p\\int_{-i\\infty}^{+i\\infty}I_{i\\sqrt{p^{2}-1}}(M\\rho)(M\\rho)^{1/2}\\,\\dd M\\nonumber \\\\\n & \\sum_{l=0}^{\\infty}\\sum_{m=-l}^{l}\\,\\phi_{pl}(\\eta)\\,Y_{lm}(z,\\bar{z})\\hat{\\Psi}(p,M,l,m)\\label{eq:inversemap}\n\\end{align}\nHere $I_{\\nu}(x)$ is the modified Bessel function of the first kind.\n\nWe are now in a position to apply the forward and inverse map described\nabove to each of the Weyl scalars of the gravitational modes computed\nearlier. This allows us to identify two families of celestial sphere\noperators that encode the 5 complex Weyl scalars for each variety\nof perturbation (scalar and vector) which we can label as $\\hat{\\Psi}_{pMlm}^{S,\\alpha}$\nand $\\hat{\\Psi}_{pMlm}^{V,\\alpha}$. Here $S,V$ refer to scalar and\nvector, and $\\alpha=0,\\cdots,4$ labels the 5 Weyl scalars. The $l,m$\nangular momentum space is conjugate to the 2-sphere coordinate space\n$z,\\bar{z}$ so in this sense we obtain a holographic mapping of the\ngravitational modes to the celestial sphere.\n\nThese celestial sphere operators will automatically have the desired\nconformal transformation properties as shown in \\cite{Liu:2021tif}.\nWe therefore find that the procedure described above allows us to\nbuild a celestial sphere description of the gravitational modes living\nin the Minkowski bulk spacetime at leading order. To further illustrate\nthis point we summarize the flat spacetime holographic map that we\nhave constructed above in the following section.\n\n\\section{Discussion}\n\nWhat we have constructed above is a holographic map between gravitons\nin 4D Minkowski background and conformal operators in the 2D boundary\nof 4D Minkowski known as the celestial sphere. The forward map, going\nfrom a metric perturbation $g_{\\mu\\nu}=\\eta_{\\mu\\nu}+h_{\\mu\\nu}$\nin 4D to conformal operators $\\{\\hat{\\Psi}_{pMlm}^{\\alpha}\\}$ in\n2D celestial sphere, is the following\n\\begin{enumerate}\n\\item Compute the Riemann tensor $R_{\\alpha\\beta\\gamma\\delta}$ to first\norder in $h_{\\mu\\nu}$. Since the full spacetime satisfies the vacuum\nEinstein equation, the Weyl tensor $C_{\\alpha\\beta\\gamma\\delta}$\nis equal to the Riemann tensor $R_{\\alpha\\beta\\gamma\\delta}$\n\\item From the Weyl tensor, compute the five Weyl scalars $\\{\\Psi^{\\alpha}\\}$\nusing eq.~\\ref{eq:kinner} and eqs.~\\ref{eq:weylscalarstart}--\\ref{eq:weylscalarend}.\nHere $\\alpha=0,\\ldots,4$.\n\\item Apply the forward map (eq.~\\ref{eq:forwardmap}) to the five Weyl\nscalars, and obtain five conformal operators $\\{\\hat{\\Psi}_{pMlm}^{\\alpha}\\}$\non the celestial sphere, labeled by four quantum numbers $p$, $M$,\n$l$, and $m$.\n\\end{enumerate}\nLikewise, the inverse map, starting from the complete set of conformal\noperators $\\{\\hat{\\Psi}_{pMlm}^{\\alpha}\\}$, is to apply eq.~\\ref{eq:inversemap}\nto obtain the five (complex) Weyl scalars $\\{\\Psi^{\\alpha}(\\eta,\\rho,z,\\bar{z})\\}$.\nThese five complex Weyl scalars encode the ten independent components\nof the Weyl tensor, which fully specify the metric perturbation $h_{\\mu\\nu}$,\nup to coordinate (gauge) choices. In particular, one can apply the\nholographic map above to the case of individual gravitational wave\nmodes (there are two types, scalar and vector perturbations, see eqs.~\\ref{eq:ansatz}--\\ref{eq:fab}\nand eq.~\\ref{eq:vectoransatz}) and obtain 2D conformal operators\nthat describe 4D gravitons in flat spacetime. The significance of\nall these formalisms developed in this chapter is precisely to allow\nus to write down a simple procedure that holographically maps gravitons\nliving in flat 4D spacetime, to 2D conformal operators living on the\ncelestial sphere.\n\nWe stress that this simple procedure amounts to using kinematic information\nto organize the modes in a convenient way. With interactions included,\none can still use this procedure to map bulk dynamics to the celestial\nsphere. The important question then is whether the dynamics has any\nuseful description incorporating the conformal symmetry of the celestial\nsphere as in the program advocated in \\cite{Pasterski:2016qvg}. In\nthe case of AdS/CFT the analogous answer was the holographic theory\nwas simpler than the gravity theory, being a quantum field theory\nwith conformal symmetry. In the case of asymptotically flat spacetime\nit remains unclear whether the celestial sphere theory is a quantum\nfield theory. It remains a logical possibility that the 4D gravitational\ndescription will be the simplest way to describe dynamics of the theory.\n\n\\appendix\n\n\\chapter{Supplementary Materials for Chapter \\ref{chap:chaos}}\n\n\\section{\\label{sec:Correlators-and-Conformal}Correlators and Conformal Blocks}\n\nConformal blocks are usually written in terms of 4-point functions\nafter a global $SL(2,C)$ conformal transformation has sent generic\npoints in the complex plane to the values $0,z,1,\\infty$. Here we\nbriefly unpack the relation between these conformal blocks and 4-point\nfunctions for general $z_{i}$.\n\nA canonical form for the 4-point function at general $z_{i}$ in the\ncomplex plane is \\cite{Ginsparg:1988ui}\n\\begin{equation}\n\\left\\langle \\prod_{i=1}^{4}\\mathcal{O}_{i}(z_{i})\\right\\rangle =f(z,\\bar{z})\\prod_{i<j}z_{ij}^{-(h_{i}+h_{j})+h/3}\\prod_{i<j}\\bar{z}^{-(\\bar{h}_{i}+\\bar{h}_{j})+\\bar{h}/3}\\label{eq:canfour}\n\\end{equation}\nwhere $z_{ij}=z_{i}-z_{j}$, the cross-ratio $z=z_{12}z_{34}/z_{13}z_{24}$\nand $h=\\sum_{i}h_{i}$. The conformal block on the other hand is usually\ndefined \\cite{Belavin:1984vu} for the special choice $z_{i}=0,z,1,\\infty$.\nTo define the correlator as the point $z_{4}$ moves to infinity we\nmust rescale by a factor of $z_{4}^{2h_{w}}$\n\\begin{equation}\n\\lim_{z_{4}\\to\\infty}z_{4}^{2h_{w}}\\bar{z}_{4}^{2\\bar{h_{v}}}\\left\\langle \\prod_{i=1}^{4}\\mathcal{O}_{i}(z_{i})\\right\\rangle =\\sum_{p}C_{12p}C_{34p}\\mathcal{F}(p,z)\\bar{\\mathcal{F}}(p,\\bar{z})\\,.\\label{eq:blockdef}\n\\end{equation}\nComparing the two formulae yields\n\\begin{align}\n\\lim_{z_{4}\\to\\infty}z_{4}^{2h_{w}}\\bar{z}_{4}^{2\\bar{h_{v}}}\\left\\langle \\prod_{i=1}^{4}\\mathcal{O}_{i}(z_{i})\\right\\rangle \\bigg|_{z_{1}=0,z_{3}=1,z_{2}=z} & =f(z,\\bar{z})\\left(1-z\\right)^{h/3-h_{2}-h_{3}}z^{h/3-h_{1}-h_{2}}\\nonumber \\\\\n & \\times\\left(1-\\bar{z}\\right)^{\\bar{h}/3-\\bar{h}_{2}-\\bar{h}_{3}}\\bar{z}^{\\bar{h}/3-\\bar{h}_{1}-\\bar{h}_{2}}\\nonumber \\\\\n & =\\sum_{p}C_{12p}C_{34p}\\mathcal{F}(p,z)\\bar{\\mathcal{F}}(p,\\bar{z})\\label{eq:blockcan}\n\\end{align}\nand we see the canonical form of the 4-point function involves a nontrivial\nrescaling of the conformal block by a function of the cross-ratio.\n\nLater when we study the commutator of two operators, $V$ and $W$\nas a function of time, it will be convenient to factor out the norm\nof the operators. To accomplish this we compute\n\\begin{equation}\n\\frac{\\left\\langle V(z_{1})V(z_{2})W(z_{3})W(z_{4})\\right\\rangle }{\\left\\langle V(z_{1})V(z_{2})\\right\\rangle \\left\\langle W(z_{3})W(z_{4})\\right\\rangle }=z^{2h_{v}}\\bar{z}^{2\\bar{h}_{v}}\\sum_{p}C_{12p}C_{34p}\\mathcal{F}(p,z)\\bar{\\mathcal{F}}(p,\\bar{z})\\label{eq:normcorr}\n\\end{equation}\nusing \\eqref{eq:canfour} and \\eqref{eq:blockcan}. Now the expression\nfor general $z_{i}$  is a function only of the cross-ratios. Finally\nwe note that in performing a coordinate transformation to a different\ncoordinate system, each correlator of primaries transforms by\n\\[\n\\left\\langle \\prod_{i}\\mathcal{O}(x_{i})\\right\\rangle =\\prod_{i}\\left(\\frac{\\partial z}{\\partial x}\\right)_{z=z_{i}}^{h_{i}}\\left(\\frac{\\partial\\bar{z}}{\\partial\\bar{x}}\\right)_{\\bar{z}=\\bar{z}_{i}}^{\\bar{h}_{i}}\\left\\langle \\prod_{i}\\mathcal{O}(z_{i})\\right\\rangle\n\\]\nand these factors cancel in the expression \\eqref{eq:normcorr}.\n\n\\chapter{Supplementary Materials for Chapter \\ref{chap:flatspace}}\\label{app:euclidean}\n\\section{Euclidean Vacuum}\n\nThe closed form expression of the positive-frequency\nEuclidean modes has been computed in Ref.~\\cite{Bousso:2001mw},\neq.~3.37, which we reproduce below in the interest of being self-contained.\nTranslating the notations of Ref.~\\cite{Bousso:2001mw} to our notations,\nthe time-dependent component of the (unnormalized) Euclidean modes\nof the 3D de Sitter spacetime is\n\\begin{equation}\n\\phi_{l}^{E}(t)=(\\cosh^{l}t)\\,e^{(l+1+i\\sqrt{\\mu^{2}-1})t}\\,{}_{2}{\\rm F}_{1}(l+1,l+1+i\\sqrt{\\mu^{2}-1};2l+2;1+e^{2t})\\,.\\label{eq:evacmode}\n\\end{equation}\n The identities \\cite{pident} and \\cite{qident} may be used provided\nwe continue $t$ to the complex plane. It is then straightforward\nto verify that the linear combination of modes in \\eqref{eq:basis}\n\n\\[\n\\phi_{l}^{E}(t)\\propto\\frac{i\\pi}{2}\\phi_{l,1}(t)+\\phi_{l,2}(t)\n\\]\nare the (unnormalized) positive-frequency modes corresponding to the\nEuclidean vacuum of the 3D de Sitter spacetime upon continuing $t$\nto real values. These when uplifted to the 4d Minkowski spacetime\nwill correspond to the Minkowski vacuum, since both are distinguished\nby the fact that their Wightman function has a Hadamard singularity\n\\cite{cmp/1103904566}. The normalization factor is determined in\nSection \\ref{sec:norm}.\n\n\\chapter{Supplementary Materials for Chapter \\ref{chap:gravitons}}\n\\section{Weyl Scalars for Scalar Perturbation}\n\nThe Weyl scalars are evaluated at linear order for the scalar perturbation\nmode $h_{\\mu\\nu}^{\\omega lm}$ defined above. Here we use $\\phi'=\\frac{\\partial}{\\partial r}\\phi$.\n\n\\begin{align*}\n\\Psi_0= & -\\frac{[l^2+l-2r\\omega(r\\omega+i)]\\phi+2r(1-ir\\omega)\\phi'}{4r^3}\\Bigg[\\sqrt{(l-m)(l+m+1)(l+m+2)}e^{-i2\\varphi}Y_{l}^{m+2}\\\\\n  & +(m-1)m\\tan^{2}\\left(\\frac{\\theta}{2}\\right)Y_{l}^{m} -2me^{-i\\varphi}\\tan\\left(\\frac{\\theta}{2}\\right)\\sqrt{(l-m)(l+m+1)}Y_{l}^{m+1}\\Bigg]\\\\\n\\Psi_{1}= & \\frac{e^{-i\\varphi}}{4\\sqrt{2}r^{3}}\\left\\{\\left(l^{2}+l-2\\right)r\\phi'+2r^2(1-ir\\omega)\\phi''+i\\left[\\left(l^{2}+l+2\\right)r\\omega+2il(l+1)-2r^{3}\\omega^{3}-2ir^{2}\\omega^{2}\\right]\\phi\\right\\}\\\\\n & \\left[\\sqrt{(l-m)(l+m+1)}Y_{l}^{m+1}-me^{i\\varphi}\\tan\\left(\\frac{\\theta}{2}\\right)Y_{l}^{m}\\right]\\\\\n\\Psi_{2}= & -\\frac{1}{8r^{3}}\\left[2r^3\\phi'''+l(l+1)r^2\\phi''-2r\\left(l^{2}+l-r^{2}\\omega^{2}\\right)\\phi'+l(l+1)\\left(r^{2}\\omega^{2}+2\\right)\\phi\\right]Y_{l}^{m}\\\\\n \\Psi_{3}= & \\frac{e^{-i\\varphi}}{8\\sqrt{2}r^{3}}\\left\\{\\left[i\\left(l^{2}+l+2\\right)r\\omega+2l(l+1)-2ir^{3}\\omega^{3}-2r^{2}\\omega^{2}\\right]\\phi-\\left(l^{2}+l-2\\right)r\\phi'-2r^2(1+ir\\omega)\\phi''\\right\\}\\\\\n  & \\left[\\sqrt{(l-m)(l+m+1)}Y_{l}^{m+1}+me^{i\\varphi}\\cot\\left(\\frac{\\theta}{2}\\right)Y_{l}^{m}\\right]\\\\\n \\Psi_{4}= & -\\frac{e^{-i2\\varphi}}{16r^{3}}\\left\\{\\left[l^{2}+l-2r\\omega(r\\omega-i)\\right]\\phi+2r(1+ir\\omega)\\phi'\\right\\} \\Bigg[\\sqrt{(l-m)(l+m+1)(l+m+2)}Y_{l}^{m+2}\\\\\n   &+2me^{i\\varphi}\\cot\\left(\\frac{\\theta}{2}\\right)\\sqrt{(l-m)(l+m+1)}Y_{l}^{m+1}+(m-1)me^{2i\\varphi}\\cot^2\\left(\\frac{\\theta}{2}\\right)Y_{l}^{m}\\Bigg]\\,.\n\\end{align*}\n\n\\section{Weyl Scalars for Vector Perturbation}\n\nThe Weyl scalars are evaluated at linear order for the vector perturbation\nmode $h_{\\mu\\nu}^{\\omega lm}$ defined above. Here we use $\\phi'=\\frac{\\partial}{\\partial r}\\phi$.\nFor brevity of presentation we follow \\cite{PhysRev.108.1063} and\npresent the $m=0$ modes. The $m\\neq0$ modes can always be obtained\nby acting with an $\\rm SO(3)$ generator.\n\n\\begin{align*}\n\\Psi_{0}= & \\frac{\\sqrt{(l-1)(l+2)}e^{-i2\\varphi}}{2r^{2}}\\left[ir\\phi''+2(r\\omega+i)\\phi'+\\omega\\phi(2-ir\\omega)\\right]Y_{l}^{2}\\\\\n\\Psi_{1}= & -\\frac{e^{-i\\varphi}}{2\\sqrt{2}r^{2}}\\left\\{i\\left[\\left(r^{2}\\omega^{2}-2\\right)\\phi'+r^2\\phi'''+(2-ir\\omega)r\\phi''\\right]+\\omega\\phi(r\\omega-1+i)(r\\omega+1+i)\\right\\}Y_{l}^{1}\\\\\n\\Psi_{2}= & -\\frac{ie^{-i2\\varphi}\\left[r^{2}\\phi''+\\phi\\left(r^{2}\\omega^{2}-2\\right)\\right]}{4r^{3}}\\left[\\sqrt{(l-1)(l+2)}Y_{l}^{2}+2e^{i\\varphi}\\cot(\\theta)Y_{l}^{1}\\right]\\\\\n\\Psi_{3}= & \\frac{e^{-i\\varphi}}{4\\sqrt{2}r^{2}}\\left\\{i\\left[\\left(r^{2}\\omega^{2}-2\\right)\\phi'+r^2\\phi'''+(2+ir\\omega)r\\phi''\\right]+\\omega\\phi[2+r\\omega(-r\\omega+2i)]\\right\\}Y_{l}^{1}\\\\\n\\Psi_{4}= & \\frac{\\sqrt{(l-1)(l+2)}e^{-i2\\varphi}}{8r^{2}}\\left[ir\\phi''+(-2r\\omega+2i)\\phi'-\\omega\\phi(2+ir\\omega)\\right]Y_{l}^{2}\\,.\n\\end{align*}\n\n\\bibliographystyle{utphys}\n\\bibliography{ref}\n\n\\end{document}\n", "meta": {"hexsha": "513eed58c1dc845190936d46293c0d466b4a6fee", "size": 166336, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis.tex", "max_stars_repo_name": "cl91/PhD-Thesis", "max_stars_repo_head_hexsha": "cc1639f69908a7e0e86596b362b693cbff40ac7e", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thesis.tex", "max_issues_repo_name": "cl91/PhD-Thesis", "max_issues_repo_head_hexsha": "cc1639f69908a7e0e86596b362b693cbff40ac7e", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis.tex", "max_forks_repo_name": "cl91/PhD-Thesis", "max_forks_repo_head_hexsha": "cc1639f69908a7e0e86596b362b693cbff40ac7e", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 57.0620926244, "max_line_length": 2040, "alphanum_fraction": 0.7276296172, "num_tokens": 52786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.30653073243822343}}
{"text": "\\documentclass[11pt]{article}\n\\usepackage{geometry} % see geometry.pdf on how to lay out the page. There's lots.\n\\usepackage{hyperref}\n\\usepackage{graphicx}\n\\usepackage{gensymb}\n\\usepackage[affil-it]{authblk}\n\\usepackage[toc,page]{appendix}\n\\usepackage{pifont}\n\\usepackage{amsmath}\n\\usepackage{draftwatermark}\n\n\\SetWatermarkText{DRAFT}\n\\SetWatermarkScale{6}\n\\SetWatermarkLightness{0.95}\n\n% \\geometry{letter} % or letter or a5paper or ... etc\n% \\geometry{landscape} % rotated page geometry\n\n% See the ``Article customise'' template for come common customisations\n\n\\title{Cheating Tsiolkovsky's Equation with Highly Unrealizable Physical Approaches}\n\\author{Robert L. Read\n  \\thanks{read.robert@gmail.com}\n}\n\\affil{Founder, Public Invention, an educational non-profit.}\n\n\n\\date{\\today}\n\n%%% BEGIN DOCUMENT\n\\begin{document}\n\n\\maketitle\n\n%% \\tableofcontents\n\n\\section{Introduction}\n\nSquirting a bunch of hot gases out of a rocket seems wasteful.\nTsiolkovsky's equation:\n\n\\[\n\\tag{The Rocket Equation} \\Delta v = v_e \\ln \\frac{m_0}{m_f} \n\\]\n\nis so dreary in its demand that most of a rocket be devoted to fuel\nthat even its creator cheated it by inventing the multi-stage rocket.\n\nIf a rocket starts in free space, \nis it possible to build a rocket which is more efficient in power or\nconservative of propellant reaction mass by designing the form\nof the remaining propellant?\n\n\\section{Conservation of Linear Momentum}\n\nAlthough it is promising to consider powering a rocket with a beam\nfrom a base station, we may be able to learn something interesting from\nconsidering a rocket starting in free space. After all, the base station\nitself or the planet it rests upon is simply a large object in free space.\n\nA chemical rocket in free space without gravity is a system that can't\nchange its center of mass. As the rocket fires, the system spreads out\nin space, with the part be call the propellant moving in one direction\nand the rocket moving in the other.\n\n\nSince we are primarily interested in going in one direction fast, we\ncan think of this as a one-dimensional problem. The fact that a cloud\nof gas spreads a little from our single axis is an unfortunate inefficiency.\n\nWe choose coordinates so that the directions we wish to go is the positive $x$ axis.\nThe origin is at the center of mass of our starting machine, which includes the rocket\nand its propellant.\nConservation of linear moment applies to whatever form the propellant takes.\nIf $\\dot{P_x}$ is the velocity of the center of mass of the propellant (which will\nlikely be negative), and $\\dot{R_x}$ is the velocity of the rocket:\n\n\\[\n\\label{conslinmom} \\tag{CLM} \\dot{R_x}\\cdot M_R = - \\dot{P_x} \\cdot M_P\n\\]\n\nWhat would happen if instead of throwing gas molecules behind ourselves\nwe threw solid objects? In other words, what if we used a ``mass driver'',\nwithout specifying how it is powered, to throw a solid propellant?\nCould we change Tsiolkovsky's equation in some favorable way?\n\n\\section{Extruded Forms}\n\nSuppose that our rocket could extrude an object extremely quickly.\nIf we extruded an object in the opposite direction we wish to travel,\nby the conservation of linear momentum our rocket will move forward.\n\n\\[\n\\tag{Linear Extrusion} R_x - P_x  = \\frac{s t}{2}\n\\]\n\n\nAfter doing a lot of math, we determine that the speed of the rocket\nat time $t$, assume an extrusion rate of $s$ in $m /s$ and density\nof extrusion of $k$ in $kg / $ linear meter, \n\n\\[\n\\dot{R_x} = \\frac{k s^2 t}{2 m_0}\n\\]\n\nwhere $m_0$ is the total inital mass of the rocket and the propellant:\n\n\\[\nm_0 = m_R + m_P\n\\]\n\nor, in terms or Tsiolkovsky's symols, $m_0 = T_m$ and $m_f = m_R$.\n\nBy solving for the time it takes to use up all of the propellant and\nthen substituting back into the form of the Tsiolkovsky equation:\n\n\\[\nv_r = \\frac{s (m_0-m_f)}{2 m_0}\n\\]\n\nIf we graph this against the Tsiolkovsky equation:\n\nINSERT GRAPH HERE\n\nwe find that extruding a cylinder very quickly is not quite as\ngood as squirting gases at the same velocity behind us.\nMy interpretation of this is that being attached to the extruded\nrod during until the momenet of separation holds the rocket back,\nwhere as the acceleartion provided by each molecule of gas\nallows the rocket to move forward without being attached.\n\n\\subsection{Develop Mathematics of Instantaneous Ejection and Relate}\n\n\\section{Constant Acceleration of Cylinder}\n\nSuppose that we could extrude the rod not at a constant speed, but\nat a constant acceleration? This is physically hard to engineer,\nbecause as the mass of the rod behind us increases, the force required\nto sustain a constant acceleration $A$ increases. Nonetheless if we\nwork out the math, we obtain:\n\n\\[\n\\tag{Constant Acceleration} R_x - P_x  = \\frac{A t^2}{2}\n\\]\n\n\\label{Constant Acceleration} can be differentiated:\n\n\\[\n\\tag{Velocities under C.A.} \\dot{R_x} - \\dot{P_x}  = A \\cdot t\n\\]\n\nand the mass of the propellant will be:\n\n\\[\n M_P = (R_x - P_x)\\cdot K \\cdot 2\n\\]\n\nor\n\n\\[\n M_P = A t^2 \\cdot K \n\\]\n\n\nRearranging and using \\eqref{conslinmom}, we obtain:\n\n\\[\n\\dot{R_x}(1 + \\frac{M_R}{M_P} ) = A \\cdot t\n\\]\n\\[\n=\n\\]\n\\[\n\\dot{R_x}(\\frac{M_P + M_R}{M_P} ) = A \\cdot t\n\\]\n\\[\n=\n\\]\n\\[\n\\dot{R_x} = A \\cdot t \\cdot (\\frac{M_P}{M_P + M_R} )\n\\]\n\\[\n=\n\\]\n\\[\n\\dot{R_x} = A \\cdot t \\cdot (\\frac{M_P}{m_0} )\n\\]\n\\[\n=\n\\]\n\\[\n\\dot{R_x} = A \\cdot t \\cdot (\\frac{A t^2 \\cdot K }{m_0} )\n\\]\n\\[\n=\n\\]\n\\[\n\\dot{R_x} = \\frac{A^2 t^3 K}{m_0}\n\\]\n\n...where A is the acceleration we support. If we again solve for the\nexpulsion of all of the propellant, we obtain:\n\n\\[\nv_r = \\frac{(m_0 - m_f)^\\frac{3}{2}\\sqrt{\\frac{A}{K}}}{m_0}\n\\]\n\nThis goes up as $A$ goes up, and goes up as we dedicated more mass to the propellant as we would expect.\nNote that it also goes up as $K$ the denisty of our extrusion goes down, which is perhaps interesting:\nthe thinnner a rod we can extrude the more efficient our system is.\n\nNEED TO compare to Tsiolkovsky.\n\nBut of course this is unrealistic in that we cannot have infinite power in our rocket.\nMy friend Mr. John Gibbons has criticized this equation as simply obscuring an unrelistic\nway to obtain a higher exhaust velocity.\n\n\\section{Relate to A Plume of Bouncing Machines}\n\nAn alternative to producing a solid plume as a single unit is to eject discrete objects.\nThese objects can interact by bouncing off each other or potentially accelerating objects\nin one direction or the other.  The conservation of linear momentum remains ironclad,\nbut we may now think of our rocket/propellant complex as a complicated machine which\nis working to spread itself out in space. Hopefully we are working to send as much\nmass behind us as quickly as possible.\n\nPossibly our propellant could even be complete machines with their own power supply.\nThuse our rocket becomes a line of mass drivers spread out in space that may drive\nobjects with mass towards or away from the rocket.\n\nThe fact that it might be a little tricky to survice collision with or the ``catching'' and\n``rethrowing'' of these objects we will ignore for the time being.\n\nWe assert that just as the Tsiolkovsky equation can be cheated by using a multi-stage\nrocket, it can also be cheated by bouncing objects around in a line, reusing reaction mass.\nThis can potentially result in final propellant shape more efficient than a plume of\ngas flying through and slowly spreading through space.\n\nEven better, if one line of the mass drivers is anchored on a planet, we can\nimagine a system in which the rocket is powered from the planet, where presumably power\nis cheap, via the transfer or momentum to the rocket via objects driven to and fro from\nthe rocket to the planet.\n\n\\section{The Simulation Showing That Bouncing Leads to Higher Speed}\n\n\n\n\\section{TODO}\n\nFill out the math in a reasonable way.  Fill in graphs. Do dimensional analysis.\n\n\n\n\n\\end{document}\n", "meta": {"hexsha": "e9b216d831d906743cda2fa8f752cffd48ef5dee", "size": 7778, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "cheatingTsiolkovsky.tex", "max_stars_repo_name": "PubInv/projpop", "max_stars_repo_head_hexsha": "b2b57005c9d4c329d8f74524534960164a11bc79", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cheatingTsiolkovsky.tex", "max_issues_repo_name": "PubInv/projpop", "max_issues_repo_head_hexsha": "b2b57005c9d4c329d8f74524534960164a11bc79", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cheatingTsiolkovsky.tex", "max_forks_repo_name": "PubInv/projpop", "max_forks_repo_head_hexsha": "b2b57005c9d4c329d8f74524534960164a11bc79", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3828125, "max_line_length": 104, "alphanum_fraction": 0.752121368, "num_tokens": 2085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.30653072478835675}}
{"text": "\\chapter{Searching for PBH Candidates in \\Fermi-LAT 3FGL Catalog}\\label{chapter:pbh_analysis}\n\n\n\\Fermi-LAT surveys the entire sky approximately every three hours, and has relatively uniform exposure over long time scales; in our dataset of 4 years, the exposure above 1 GeV varies by approximately 40\\% over the entire sky. Combined with a large effective area (approximately 1 m$^2$ between 1 GeV and 1 TeV), this makes it an ideal instrument for detecting a large number of gamma-ray point sources. \nThe most complete catalog of point sources is currently the third \\Fermi point source catalog \\citep[3FGL, ][]{2015ApJS..218...23A} (see Section \\ref{sec:analysisTools} for a brief description of the methodology that the \\Fermi-LAT collaboration uses to build catalogs). \nThe 3FGL contains sources that are significantly detected above 100 MeV and spans the first 4 years of the \\Fermi mission. \n%A complete description of the 3FGL can be found in \\citep{2015ApJS..218...23A}. .\nIn this chapter, I use the 3FGL catalog to search for PBH candidates and to constrain the local PBH evaporation rate.\n\n\\section{Search Strategy}\n\\label{sec:search}\nThe first step in selecting PBH candidates in the 3FGL catalog was excluding from further consideration point sources associated with known astrophysical sources (such as blazars). Of 3033 sources in the 3FGL catalog, 1010 are unassociated sources. Also excluded were a further 468 unassociated sources that lie within $10^\\circ$ of the Galactic plane. The analysis was restricted to high-latitude sources for three reasons: (a) detectable PBHs are expected be distributed isotropically given the detectability distances estimated in Section \\ref{sec:sens}, while astrophysical sources are concentrated along the Galactic plane, (b) association of extragalactic sources such as blazars is easier at high latitude \n\\citep[see, e.g.][]{2015ApJ...810...14A}, and (c) the reduced Galactic diffuse emission at high latitude makes proper motion identification easier.\n\nThe spectra of the remaining unassociated 3FGL sources were next compared with the time-integrated PBH gamma-ray spectrum.\nSpectra of the candidate sources are reported in the 3FGL as fluxes in 5 energy bands (0.1 -- 0.3, 0.3 -- 1, 1 -- 3, 3 -- 10, and 10 -- 100 GeV).\nThe time-integrated PBH spectrum depends on two parameters: initial mass (or temperature), and the distance to the Earth (equivalent to an overall normalization).\nThese two parameters were varied to obtain the best fit to the candidate source spectra in the five energy bands.\nThe quality of the fit to the 3FGL spectrum was determined by calculating the value of the $\\chi ^2$ over the five energy bands:\n\n\\noindent\n\\begin{equation}\n\\chi^2 = \\sum_{i = 1}^{5} \\frac{(\\Phi_i-\\Psi_i )^2}{\\sigma_i^2}, \n\\end{equation}\nwhere $\\Phi_i$ is the PBH spectrum integrated over the width of bin $i$ and $\\Psi_i$ is the flux in bin $i$ reported in the 3FGL. Here $\\sigma_i$ represents the uncertainty on the flux in bin $i$.\nIn the 3FGL, flux uncertainty is represented by a 68\\% confidence interval; the value of the uncertainty can then be written as the difference between the best-fit flux and either the upper or lower bound.\nWe set $\\sigma_i$ to be the larger of the two in order to be conservative.\nWe require the value of the best-fit $\\chi^2$ to be below the critical value of 11.3, which corresponds to 99\\% exclusion for 5 degrees of freedom and 2 parameters. In other words, sources with a $\\chi ^2$ value greater than 11.3 have only a 1\\% chance of being spectrally consistent with a PBH. After the spectral consistency was computed, 318 sources out of the 542 unassociated candidates remained as plausible PBH candidates.\nThe candidate sources next underwent a check for proper motion. \n\n\\subsection{Proper Motion}\\label{sec:propmotion}\nSeveral algorithms were examined for the ability to discriminate between moving and stationary sources.\nInspired by the track reconstruction algorithms used in the \\Fermi-LAT tracker, the first algorithm studied was a Kalman filter, implemented with a model of a moving source (with Gaussian uncertainty at each data point). \nThe Kalman filter was successful was successful in Monte Carlo simulations of reconstructing the velocity of a moving point source, but is not easily adapted to cases where the signal is subdominant to background.\n\nNext studied was an algorithm which computed the moment of inertia tensor of the source photon locations.\nSubsequent diagonalization of the moment of inertia tensor gave the spatial eigenvectors and eigenvalues associated with the source; any motion was assumed to take place along the larger of the two eigenvectors.\nThe photons were divided into two groups according to which side of the center of mass (along the eigenvector) they fell, and the mean arrival times of the two groups of photons were compared.\nHowever, the moment of inertia depends on the square of the distance of each photon from the center of mass.\nTherefore the algorithm was found to be too sensitive to the diffuse background, which is distributed isotropically across the region of interest, and nearby non-candidate point sources.\n\nAfter further testing, an algorithm was built which uses the method of maximum likelihood estimation to (a) weight background photons given a model of the ROI, and (b) reconstruct the proper motion of the candidate source.\nThe algorithm works as follows:\n\\begin{enumerate}\n\\item\nAll source-class photons above 1 GeV within $5^\\circ$ of the source's reported 3FGL location were collected.\nThe time range (August 2008 to July 2012) and data reconstruction (\\texttt{P7REP\\char`_SOURCE\\char`_V15}) were consistent with that of the data used to construct the 3FGL.\nSince the angular resolution of the \\Fermi LAT decreases quickly below 1 GeV, including photons below 1 GeV did not have a significant impact on the final results.\n\\item \nData covering a longer time range (August 2008 to July 2017) and a more recent event reconstruction (\\texttt{P8R2\\char`_SOURCE\\char`_V6}) were held in reserve for validation, and was used to test the PBH hypothesis for any sources that passed the proper motion cut.\n\n\\item\nThe expected number of photons $N$ from the source of interest was calculated by multiplying the flux in each energy bin by \nthe \\Fermi-LAT exposure at the bin's midpoint energy, and summing over the three relevant bins (1 -- 3 GeV, 3 -- 10 GeV, 10 -- 100 GeV). \n\\item \n\\label{step:prop_motion_likelihood}\nIn order to estimate the velocity of a PS, the maxima of the likelihood function $\\mathcal{L}(\\vec{x_i},t_i,\\vec{x_0},\\vec{v_0})$ are compared in two cases: \nfixed $\\vec{v_0}=0$ and free $\\vec{v_0}$. \nThe point spread function of \\Fermi-LAT was approximated as a Gaussian for simplicity.\nThe likelihood function is given by multiplying over $N$ photons around the initial position of the source:\n\n\\noindent\n\\begin{equation}\n\\label{eq:vlike}\n\\mathcal{L} = \\prod_{i=1}^{N}w_i\\times \\textup{exp} \\big\\{\\frac{{-(\\vec{x_i}-\\vec{x_0}-\\vec{v_0}t_i)^2}}{{\\sigma_i^2}}\\big\\}\n\\end{equation}\nwhere $\\vec{x_i}$ is the coordinates of the photon, $\\vec{v_0}$ is the proper motion of the source, $t_i$ is the photon arrival time, $\\vec{x_0}$ is the source location at the beginning of the observation time, and $\\sigma_i$ is the 68\\% angular containment radius for a photon at energy $E_i$, which is $\\sim 0.7^\\circ$ at 1 GeV \\citep{2013arXiv1304.5456B}.\nHere $w_i$ is a weight assigned to each photon, the calculation of which is defined in Section \\ref{sec:likelihood}. \n\nIn practice, the natural logarithm of the likelihood is used:\n\\begin{equation}\n\\label{eq:vloglike}\n\\log \\mathcal{L} = \\sum_{i=1}^{N}\\log w_i-\\frac{{(\\vec{x_i}-\\vec{x_0}-\\vec{v_0}t_i)^2}}{{\\sigma_i^2}}\n\\end{equation}\n\nThe main difficulty is separating the $N$ photons attributed to the source from background photons.\nThe algorithm chooses a 4-dimensional grid of points around an initial value of $\\vec{x_0}$ and $\\vec{v_0} = 0$, and for each grid point finds the $N$ photons\ninside the $5^\\circ$ ROI that have the highest contribution to $\\log \\mathcal{L}$, i.e. the photons which most likely belong to the source given a particular position and velocity.\nTherefore the weights $w_i$ do not appear as a prefactor in Eqs \\ref{eq:vlike} and \\ref{eq:vloglike} because the $N$ best-fit photons change given different assumptions of $\\vec{x_0}$ and $\\vec{v_0}$.\nThe best-fit $\\vec{x_0}$ and $\\vec{v_0}$ are found by maximizing $\\Delta \\log \\mathcal{L} = \\log \\mathcal{L} - \\log \\mathcal{L}(\\vec{v_0}=0)$ on the grid.\nWith the additional degrees of freedom from allowing $\\vec{v_0}$ to float, the value of $\\Delta \\log \\mathcal{L}$ is always nonnegative. \n\nMC simulations (described in Section \\ref{sec:MClimit}) demonstrate that this algorithm tends to underestimate the input velocity by $\\approx 25\\%$;\nthe best-fit velocity should therefore be considered a lower bound on the true velocity and sufficient for our purpose of separation of moving and stationary sources.\nThe underestimation occurs because source photons that are far away from the average source position have lower weights and so are less often included in the likelihood calculation.\nIn their place are background photons, whose distribution in time is random, and therefore cause the algorithm to favor a slower overall velocity.\n%The $N$ photons used in the calculation will generally change over the course of the maximization procedure, because it is not possible to discriminate between individual source and nearby background photons. However, the algorithm converges if the source is sufficiently brighter than the background. \n\\item \nThe significance of $\\Delta \\log \\mathcal{L}$ for each source was found by assigning random times $t_i$ drawn from a flat distribution to each photon but fixing the positions $\\vec{x_i}$ of all the photons, and reoptimizing $\\Delta \\log \\mathcal{L}$. \nThis process was repeated 50 times for each source, and the original value of $\\Delta \\log \\mathcal{L}$ was compared with the distribution of $\\Delta \\log \\mathcal{L}$ for the data sets scrambled in time to find a local significance $\\sigma$:\n\n\\noindent\n\\begin{equation}\n\\sigma = \\frac{\\Delta \\log \\mathcal{L}_0 - \\overline{\\Delta \\log \\mathcal{L}_s}}{\\textup{std}(\\Delta \\log \\mathcal{L}_s)},\n\\end{equation}\nwhere $\\Delta \\log \\mathcal{L}_0$ is the original value of the improvement in likelihood, $\\overline{\\Delta \\log \\mathcal{L}_s}$ is the mean of the scrambled likelihood improvements, and $\\textup{std}(\\Delta \\log \\mathcal{L}_s)$ is the standard deviation of the scrambled likelihood improvements.\n\\item\nA cut on the local significance for each source was made at $3.6 \\sigma$ which corresponds to a global significance of $2 \\sigma$ for 318 sources. \n\\end{enumerate}\n\nThe key step in this process is the maximization of likelihood in Step \\ref{step:prop_motion_likelihood}. \nBecause the algorithm only considers the $N$ best photons at each grid point, it is highly resistant to background photons in cases where the source is undergoing proper motion; background photons are generally distributed evenly across time which means they are unlikely to fit well to the reconstructed path of the source at the grid point under consideration.\nMonte Carlo simulations of PBHs show that the algorithm is highly successful (See Figure X) at reconstructing the true velocity in cases where the PBH has a lifetime at least as long as the time considered.\nIn cases where the PBH evaporates before the end of the time period, the velocity reconstruction is not accurate, but the discrimination between moving and stationary sources is still sufficient.\nLong-lived PBHs far outnumber short-lived ones due to the nonlinear nature of the evaporation process- see Equation \\ref{eq:Tdistr}- so the algorithm was designed to maximize sensitivity to long-lived PBHs.\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=0.9\\columnwidth]{figures/reconstructedVelocity.pdf}\n\\caption{\n\\label{fig:reconstruction}\nReconstructed velocities from MC simulations (described in Section \\ref{sec:MClimit}). The reconstruction is not perfect due to the presence of background photons and statistical fluctuations, and works best for slow-moving sources. At high velocities, the reconstructed velocity is generally below the true velocity because of the photon weighting scheme (Section \\ref{sec:likelihood}) which favors slow-moving sources. The coloring indicates distance, showing that distant sources must be moving relatively slowly to pass the selection criteria.\n}\n\\end{center}\n\\end{figure}\n\nA single source (3FGL J2310.1$-$0557, see Section \\ref{sec:j2310} for a discussion of this source) exceeded this cut on local significance, and the standard deviation of the local significances of the entire set of candidates was 1.03, which is consistent with statistical fluctuations.\nAfter examining the data held in reserve for J2310.1$-$0557 (described in Section \\ref{sec:j2310}), it was concluded that no likely PBH candidates exist in the 3FGL catalog.\n\n\\subsection{Photon Weights}\n\\label{sec:likelihood}\n\nThe photon weights $w_i$ in equations \\ref{eq:vlike} and \\ref{eq:vloglike} are defined as the probability that a given photon originated from the candidate PS, and are calculated by performing a standard likelihood optimization with the \\Fermi Science Tool {\\tt gtlike}\\footnote{Science Tools version v10r0p5, available at \\url{http://fermi.gsfc.nasa.gov/ssc/data/analysis/software}}.\nThe model used includes all 3FGL PS within 5$^\\circ$ of the candidate source, as well as the standard Pass 7 models for Galactic and isotropic diffuse emission.\nThe candidate source is modeled as an extended source with a radial Gaussian profile with $\\sigma=0.25^\\circ$ instead of a PS, in order to account for the possibility of small amounts of proper motion.\nThe data were binned into three logarithmically spaced energy bands between 1 GeV and 100 GeV and in $0.1^\\circ \\times 0.1^\\circ$ spatial pixels.\nAfter the model was optimized by {\\tt gtlike}, weights were assigned to each photon (described its coordinates $x$, $y$, and energy $E$) by calculating the fraction of the flux belonging to the candidate source in each pixel:\n\n\\begin{equation}\nw_{x,y,E} = \\frac{\\Phi'(x,y,E)}{\\sum_i \\Phi_i(x,y,E)}\n\\end{equation}\nwhere $\\Phi'(x,y,E)$ is the predicted flux from the candidate source in the pixel and $\\Phi_i(x,y,E)$ are the fluxes from all the sources in the model.\n\nIn addition, the 3FGL PS were masked by assigning a weight of zero to all the photons which fell in a pixel more than 1$^\\circ$ from the candidate source position where the summed contribution of the non-candidate PS fluxes exceeded 10\\% of the total flux in that pixel.\nThis meant that all the photons in the calculation had a high probability of originating only from either the candidate source or the diffuse background.\n\nThe weighting has little impact on the reconstruction of proper motion because individual photon weights do not change as the likelihood maximization from step \\ref{step:prop_motion_likelihood} optimizes $\\vec{x_0}$ and $\\vec{v_0}$.\nHowever, weighting the photons in this way prevents the algorithm from interpreting photons from nearby sources as originating from the candidate source.\nWithout weighting, nearby flaring sources could mimic a moving source and therefore lead to false positives.\n\nThe radial Gaussian weighting of the candidate PS does reduce the accuracy of reconstructing the proper motion of fast-moving sources- see Figre X.\nBecause the main purpose of the algorithm is simply to discriminate between moving and non-moving sources, this was deemed an acceptable tradeoff for the improvement in background rejection that comes from the weighting.\n\n\\subsection{J2310.1$-$0557}\n\\label{sec:j2310}\nThe source J2310.1$-$0557 passed the proper motion cut with a significance of 4.2$\\sigma$, and was therefore investigated further.\nApproximately 9 years (August 2008 to July 2017) of Pass 8 (\\texttt{P8\\char`_SOURCE\\char`_V6}) data above 1 GeV in an ROI of 5$^\\circ$ around the source location were collected.\nThe increased statistics and improved angular resolution of the Pass 8 data set clearly indicated that J2310.1$-$0557 lies approximately 1$^\\circ$ away from a separate, highly variable source of gamma rays which is not in the 3FGL catalog.\nThis source flared brightly (approximately 150 photons above 1 GeV) on 7 March 2011 (near the end of the 3FGL time period) but was quiet for the remainder of the period.\nWe found that the position of the source was consistent with the Sun, which flared brightly on the same date \\citep{2011ATel.3214....1A}.\n$\\gamma$-ray emission from the Sun and Moon was not included in the models of the ROI.\n\nThe effect of the solar flare near a candidate PBH was to mimic a moving source, which explains why the proper motion algorithm returned a positive result. \nBecause the sources in the Monte Carlo simulation described in Section \\ref{sec:MClimit} are placed at random points on the sky, similar false positives are expected to occur in the simulations.\nTherefore,the upper limit on PBH evaporation rate is reported as if one source passed our criteria, even though J2310.1$-$0557 is not a good PBH candidate.\nIncidentally after the publication of the 3FGL source list, J2310.1$-$0557 was found to be a millisecond pulsar\\footnote{See https://confluence.slac.stanford.edu/display/SCIGRPS/LAT+Pulsations+from+PSR+J2310-0555}.\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=0.45\\columnwidth]{figures/3fgl_overlay.pdf}\n\\includegraphics[width=0.45\\columnwidth]{figures/4fgl_overlay.pdf}\n\\caption{\n\\label{fig:j2310}\n{\\it Left Panel:} 5$^\\circ$ ROI around 3FGL J2310.1$-$0557, using the 4 years of data from the 3FGL analysis. The source at the center of the image appears to be extended due to the 7 March 2011 solar flare just to the upper-left of the candidate source.\n{\\it Right Panel:} The same ROI using 9 years of data and using the more recent Pass 8 reconstruction algorithms. The formerly extended source is clearly resolved as two separate sources.\n}\n\\end{center}\n\\end{figure}\n\\section{Limits on PBH\\MakeLowercase{s}}\n\\label{sec:MClimit}\n\nAn analytic derivation of the upper limit on the local PBH evaporation rate is difficult due to the complex nature of the variables in question.\nFor a PBH to pass all the cuts in Section \\ref{sec:search}, it must have three main characteristics: (a) be listed as a PS in the 3FGL, (b) have a reconstructed spectrum which is consistent with a PBH, and (c) yield a significant proper motion when analyzed with the algorithm described in Section \\ref{sec:propmotion}.\nEach step in this process depends intimately on models of the background, as well as the temperature, distance, and velocity of the PBH.\nTherefore, the efficiency for detecting PBHs was derived from Monte Carlo (MC) simulations.\nUpper limits on the local PBH evaporation rate were then placed using the derived efficiency.\n\nA sample of PBHs was generated within 0.08 pc of the Earth with uniform spatial density.\nThe PBH velocites were randomly sampled from a Gaussian distribution that had an average value of $250\\rm\\,km\\, s^{-1}$, which is close to an upper bound on orbital velocity of the Sun around the Galactic center \\citep{1999MNRAS.310..645W, 2008ApJ...684.1143X, 2009PASJ...61..227S, 2010ApJ...720L.108G, 2010MNRAS.402..934M, 2011MNRAS.414.2446M},\nand dispersion equal to the local velocity dispersion of dark matter, $270\\rm\\,km\\, s^{-1}$ \\citep{2010JCAP...02..030K}.\nAt the end of this section, different assumptions about the PBH distribution (such as the relative velocity and velocity dispersion) are used to calculate an upper limit for the evaporation rate, providing an estimate of the systematic uncertainty.\n\nThe PBH population is assumed to have a constant rate of PBH evaporations, $\\dot{\\rho}_{\\rm PBH} = const$ which is reasonable given the short time period of the search (4 years) compared with the age of the Universe.\nA constant rate of evaporation implies that the derivative of the PBH density is related to the PBH temperature as:\n\n\\noindent\n\\begin{equation}\n\\label{eq:Tdistr}\n\\frac{d \\rho_{\\rm PBH}}{d T} \\propto T^{-4}.\n\\end{equation}\n\nThis relation can be derived as follows: Let $\\rho_{\\rm PBH}(T)$ be the density of PBHs with temperature larger than $T$. If $\\tau(T)$ is the lifetime of a PBH with temperature $T$, then all PBHs with $T' > T$ will evaporate during time $\\tau$. Consequently,\n\n\\noindent\n\\begin{equation}\n\\label{eq:rho0}\n\\rho_{\\rm PBH}(T) = \\int_0^{\\tau(T)} \\dot{\\rho}_{\\rm PBH} dt = \\dot{\\rho}_{\\rm PBH}\\; \\tau(T).\n\\end{equation}\nNow taking into account that $\\tau \\propto T^{-3}$ and differentiating with respect to $T$ to get\nEquation (\\ref{eq:Tdistr}).\n\nThe following steps were performed in the derivation of the PBH evaporation rate limit:\n\\vspace{-2mm}\n\\begin{enumerate}\n\\item\n\\label{item:make_pbhs}\nA sample of PBHs $(T_i, \\vec{x}_i, \\vec{v}_i)$ was simulated with temperatures $T_i>5\\: {\\rm GeV}$ and $T_i<60\\: {\\rm GeV}$ distributed according to Equation (\\ref{eq:Tdistr}), and distances $R_i$ within $R < 0.08$ pc around the Earth. \nThe velocities $v_i$ of the sample PBHs were distributed with mean equal to the orbital velocity of the Sun, \n$v_{\\rm rot} = 250\\; {\\rm km\\: s^{-1}}$,\nand dispersion $v_{\\rm disp} = 270\\; {\\rm km\\: s^{-1}}$.\n\\item\nThe photons emitted by each PBH were simulated over the 4 year 3FGL time period, consistent with the parent PBH evolution.\nA time step of $\\Delta t = 1$ day was used in modeling the evolution of the PBH position and temperature since \\Fermi LAT has relatively uniform exposure on time periods longer than 1 day; because the analysis takes place over 4 years the uneven exposure on timescales shorter than 1 day are negligible.\n The number of photons detected by the \\Fermi LAT each day was given by a Poisson random value with a mean of \n\n\\noindent\n\\begin{equation}\n\\overline{N(t)} = \\frac{ \\Delta t}{4\\pi R^2}\\int_{\\textup{E=100 MeV}}^{\\textup{E=500 GeV}} {\\Phi(E,t)} A(E) dE,\n\\end{equation}\nwhere $A$ is defined as the average \\Fermi-LAT exposure per unit time at the position of the simulated PBH, and $R$ is the distance from the Earth.\nThe energy of each photon was found by random sampling of $\\Phi(E,t)\\times A(E)$. \nPBH emission spectra $\\Phi(E,t)$ are discussed in Appendix \\ref{chapter:pbh_spectrum}. \nThe positions of the photons were randomized according to the \\Fermi-LAT point-spread function (modeled as a Gaussian distribution) at the photon energy.\n\n\\item\n\\label{item:detection}\nThe list of simulated PBH photons was concatenated to the real photons present within $5^\\circ$ of the final location of the PBH, with the same data selection as the 3FGL. A likelihood fit using the \\Fermi Science Tool {\\tt gtlike} was performed in a $7^{\\circ}\\times7^{\\circ}$ ROI centered at the same location, using a model of the sky which included all 3FGL sources within $5^\\circ$ of the ROI center, as well as models of the isotropic diffuse and Galactic diffuse emission\\footnote{The models used were the standard Pass 7 (for consistency with the 3FGL) diffuse emission models available from \\url{https://fermi.gsfc.nasa.gov/ssc/data/access/lat/BackgroundModels.html}}. The PBH was modeled as a source with a LogParabola spectrum, with fitting parameters restricted to the ranges $1.2<\\alpha<3.0$ and $0.0<\\beta<1.0$. Once the likelihood maximization was complete, the PBH was considered detected if its TS value was greater than 25, which is consistent with the 3FGL cutoff.\n\\item\n\\label{item:spectrum}\nIf the PBH source was detected, the results from the likelihood fit were used to find the source flux in the five energy bins reported in the 3FGL catalog. The spectral consistency with a PBH spectrum was then calculated in the same way as described in Section \\ref{sec:search}.\n\\item \n\\label{item:motion}\nIf the source was found to be spectrally consistent with a PBH, the significance of any proper motion was evaluated by the algorithm described in Section \\ref{sec:search}. The combined efficiency of steps \\ref{item:detection}$-$\\ref{item:motion} is displayed in Figure \\ref{fig:det_map}. We smoothed the results by convolving the detectability map with a 3$\\times$3 matrix of ones, which had a minor ($\\approx$ 8\\%) impact on the resulting limit. The impact of fluctuations was quantified by observing the change in the limit as the number of simulations increased; we found that an increase of the number of simulations by 100\\% had less than a 20\\% change in the resulting limit.\n\\item \n\n\\label{step:eff}\nTo derive an upper limit on the number of PBH evaporations in our search region, we begin with the number of expected detections:\n\n\\noindent\n\\begin{equation}\n\\label{eq:N_det}\nN = \\rho \\epsilon V,\n\\end{equation}\nwhere $\\rho$ is the true density of PBHs and $V$ is the volume searched.\n$\\epsilon$ is the average PBH detection efficiency in time $t = 4$ yr and within the search volume $V$ (a sphere with radius 0.08 pc, with the wedge corresponding to $|b|<10^\\circ$ removed); \nit is calculated by taking the mean over the pixels in Figure \\ref{fig:det_map} with the weight $R^2 T^{-4}$:\n\n\n\\noindent\n\\begin{equation}\n\\epsilon = \\frac{\\iint \\epsilon (R, T) \\frac{R^2}{T^4} \\,dR\\,dT }{\\iint \\frac{R^2}{T^4}\\,dR\\,dT },\n\\end{equation}\nwhere the integrals run over the space of parameters described in step \\ref{item:make_pbhs}. \nEquation \\ref{eq:N_det} can be inverted to find the PBH density $\\rho$ as a function of the number of detections $N$, or the upper limit on $\\rho$ given an upper limit on $N$. Given that one PBH candidate passed the selection criteria described in Section \\ref{sec:search}, we set an upper limit $N < 6.64$, \nwhich is the 99\\% confidence upper limit on the mean of a Poisson distribution with 1 observed event.\n\n\\item\n\\label{item:limit}\nWe convert the upper limit on $\\rho$ to an upper limit on $\\dot{\\rho}$ by finding the fraction $f$ of PBHs that would have evaporated during the search time \n$t$. \nGiven a time of observation of 4 years, we find that all PBHs with initial temperature above 16.4 GeV would evaporate. Therefore,\n\n\\noindent\n\\begin{equation}\nf = \\frac{\\int_{\\textup{16.4 GeV}}^{\\textup{60 GeV}} T^{-4} \\,dT}{\\int_{\\textup{5 GeV}}^{\\textup{60 GeV}} T^{-4} \\,dT}.\n\\end{equation}\nWe calculate the 99\\% upper limit on $\\dot{\\rho}_{\\rm PBH}$ to be:\n\n\\noindent\n\\begin{equation}\n\\dot{\\rho}_{\\rm PBH} < f\\frac{6.64}{\\epsilon V t} = 7.2 \\times 10^3 \\textup{ pc}^{-3} \\textup{ year}^{-1}.\n\\end{equation}\n\n\\item\nWe estimated the systematic uncertainties arising from the uncertaintes in the PBH spectrum by varying the overall normalization of the PBH spectrum (see Appendix \\ref{app:PBH_spectrum}) and varying the velocity distributions of the Milky Way disk and DM halo. We consider two scenarios (``aggressive\" and ``conservative\") which give the best and worst sensitivity, respectively. Steps \\ref{item:make_pbhs}$-$\\ref{item:limit} are then repeated to find the resulting limit. The parameters of the aggressive and conservative models, as well as the resulting limits, are listed in Table \\ref{table:systematics}.\n\\begin{table}[h]\n\\begin{center}\n\\begin{tabular}{|c c c c c|}\n\\hline\nModel & Spectrum Normalization & Orbital Velocity (${\\rm km\\: s^{-1}}$) & DM Halo Velocity (${\\rm km\\: s^{-1}}$) & Limit\\\\\n\\hline\nAggressive & $\\frac{0.45}{0.35}$ & 100 & 150 & $4.8\\times 10^3  \\textup{ pc}^{-3}  \\textup{yr}^{-1}$ \\\\\nConservative & $\\frac{0.25}{0.35}$ & 300 & 350 & $15.3\\times10^3 \\textup{ pc}^{-3} \\textup{ yr}^{-1}$ \\\\\n\\hline\n\\end{tabular}\n\\caption{Parameters used in estimation of systematic uncertainty. \nTo be more conservative in the estimates of the systematic uncertainties,\nwe have tested the ranges of orbital velocities and the DM dispersion velocities which are larger than most of the values reported\nin the literature\n\\citep{1999MNRAS.310..645W, 2008ApJ...684.1143X, 2009PASJ...61..227S, 2010ApJ...720L.108G, 2010JCAP...02..030K,\n2010MNRAS.402..934M, 2011MNRAS.414.2446M}.}\n%e.g., $\\sim 200 - 280\\: {\\rm km / s}$ in \\cite{2010MNRAS.402..934M}.}\n%The range of uncertainty in the orbital velocity is somewhat more conservative than the range given in \\citep{2010MNRAS.402..934M}}\n\\label{table:systematics}\n\\end{center}\n\\end{table}\n\n\nThe limit including the systematic uncertainties is\n\n\\noindent\n\\begin{equation}\n\\label{eq:ev_rate}\n%\\dot{\\rho}_{\\rm PBH} < (19.2\\pm 1.5 \\textup{[stat]} ^{+14.8}_{-9.6} \\textup{[syst]}) \\times 10^3 \\textup{ pc}^{-3} \\textup{ yr}^{-1}.\n\\dot{\\rho}_{\\rm PBH} < (7.2^{+8.1}_{-2.4} ) \\times 10^3 \\textup{ pc}^{-3} \\textup{ yr}^{-1}.\n\\end{equation}\n\\end{enumerate}\n\n%For comparison, if we assume no candidate source had passed our selection criteria, the limit would be $\\dot{\\rho}_{\\rm PBH} < (5.0^{+5.6}_{-1.6} ) \\times 10^3 \\textup{ pc}^{-3} \\textup{ yr}^{-1}$.\n\\begin{figure}[htbp]\n\\begin{center}\n\\epsfig{figure = figures/detectability_map.pdf, scale=\\onepic}\n\\noindent\n\\end{center}\n\\caption{\\small \n\\label{fig:det_map}\nFraction of simulated PBHs which are detected as a point source with a spectrum compatible with a PBH evaporation spectrum and with significant proper motion. The detectability peaks for PBHs with initial temperatures above 16.4 GeV because the lifetime of a 16.4 GeV PBH is 4 years, which is the same as the observation period of the 3FGL. Few PBHs are detected past a distance of 0.05 pc or below 10 GeV.}\n\n\\end{figure}\n\n\n\n\n\n\n", "meta": {"hexsha": "68c18f62da6be734175fd6cff126cbd200f9592d", "size": 29399, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapter4.tex", "max_stars_repo_name": "christian-johnson/phd-thesis", "max_stars_repo_head_hexsha": "269a0a554963753ca7c81144428f80f3f97239cf", "max_stars_repo_licenses": ["LPPL-1.3c"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapter4.tex", "max_issues_repo_name": "christian-johnson/phd-thesis", "max_issues_repo_head_hexsha": "269a0a554963753ca7c81144428f80f3f97239cf", "max_issues_repo_licenses": ["LPPL-1.3c"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter4.tex", "max_forks_repo_name": "christian-johnson/phd-thesis", "max_forks_repo_head_hexsha": "269a0a554963753ca7c81144428f80f3f97239cf", "max_forks_repo_licenses": ["LPPL-1.3c"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 90.1809815951, "max_line_length": 983, "alphanum_fraction": 0.7685635566, "num_tokens": 7778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3065307247883567}}
{"text": "\\chapter{Performing Optimizations}\n\\label{chap:chapter8}\n\nThis chapter explains how to use the Herbrand Equivalence analysis\ninformation to perform actual program optimizations.\n\n\\section{Available Variables}\n\\label{AvailableVariables}\nA variable is said to be \\textbf{available} at a basic block if \nit is defined at some point along all the execution paths from the \nstart of the program that reaches the beginnning of that basic block.\nIt is forward data analysis problem and can be determined via fixed \npoint computation.\n\nThe universe $\\mathcal U$ would be the set of all program variables.\nAlso, let $\\mathcal B$ be the set of all basic blocks in the program.\nDenote by $DEF[B]$ the set of variables defined in the basic block\n$B \\in \\mathcal B$, and $IN[B]$ be corresponding set of available \nvariables. Initialise $OUT[B] = \\mathcal U, \\forall B \\in \\mathcal B$ \nand perform updates as follows till a fixed point is reached.\n$$IN[B] = \\cap_{B' \\in Predecessors(B)} OUT[B']$$\n$$OUT[B] = IN[B] \\cup DEF[B]$$\n\nNote that the definition of \\textbf{available variables} is different\nfrom that of \\textbf{reaching definitions} and \\textbf{available \nexpressions}. If a variable is available at the beginning of a given\nbasic block, then that variable can be used in the basic block without\ndefining it because by \\textit{definition of avilable variables} it \nwould already be defined along every path from the start of the \nprogram to that basic block.\n\nThe definition of available variables can be extended to that of any\ninstruction. Variables available at an instruction $I$ is the union \nof variables available at the beginning of its basic block and any \nvariables defined by the instructions preceding it in that block.\n\n\\section{Performing Optimizations}\n\\label{PerformingOptimizations}\nThe results of Herbrand Equivalence and available variables analysis \ncan be used to perform optimizations involving redundant expression \nelimination and some dead code elimination.\n\nSuppose, there is an instruction $I : z \\gets e$, where $e$ is an \nexpression (as already mentioned expression means either a constant, \nor a variable or a length two expression). First find the Herbrand \nequivalence class of $z$ at that program point. If the class represents\na constant valued expression ($partitions[I][z].isConst == true$), then\nthis instruction can be deleted and all uses of $z$ replaced by \n$partitions[I][z].constVal$, till $z$ is redefined. Else if it is not \na constant valued expression, \n$\\mathcal S = (getClass(partitions[I], z) \\cap IN[I])$\nwill be the set of variables, such that $z$ can be replaced by \n$s \\in \\mathcal S$ (before $z$ and $s$ are redefined), without changing\nthe meaning of the program. \\\\ \nPseudocode \\ref{Optimize} is the precise formulation of the mentioned facts.\n\n\\begin{algorithm}\n\\caption{Performing Optimizations}\\label{Optimize}\n\\begin{algorithmic}[1]\n\\Procedure{Optimize}{}\n    \\For{$B \\in \\mathcal B$}\n        \\State $Insts \\gets$ \\textbf{Instructions}$(B)$\n        \\State $AvailVars \\gets IN[B]$\n        \\State\n        \\For{$I \\in Insts$}\n            \\State $Insts.remove(I)$\n            \\State $z \\gets$ \\textbf{LValue}$(I)$\n\\algstore{Optimize}\n\\end{algorithmic}\n\\end{algorithm}\n                    \n\n\\begin{algorithm}\n\\begin{algorithmic}[1]\n\\algrestore{Optimize}\n            \\If{\\textbf{Defined}$(z)$}\n                \\State \\textbf{IDstruct*} $ptr \\gets partitions[I][z]$\n                \\State\n                \\If{$ptr.isConst$}\n                    \\State \\textbf{Bool} $reachedEnd \\gets true$\n                    \\For{$I' \\in Insts$}\n                        \\If{\\textbf{LValue}$(I') == z$}\n                            \\State $reachedEnd \\gets false$\n                            \\State \\textbf{break}\n                        \\EndIf\n                        \\State \\textbf{Replace}$(I',\\ z,\\ ptr.constVal)$\n                    \\EndFor\n                    \\If{$reachedEnd$}\n                        \\State $B.insert(z \\gets ptr.constVal)$\n                    \\EndIf\n                    \\State\n                    \\State \\textbf{DeleteInstruction}$(I)$\n                \\Else\n                    \\State \\textbf{set}$<$\\textbf{Expressions}$> curPart \\gets$ \\textbf{GetClass}$(partitions[I],\\ z)$\n                    \\State $curPart \\gets (curPart \\cap AvailVars)$\n                    \\State\n                    \\If{not $curPart.empty()$}\n                        \\State \\textbf{Bool} $reachedEnd \\gets true$\n                        \\State $replacement \\gets curPart.first()$\n                        \\State\n                        \\For{$I' \\in Insts$}\n                            \\If{\\textbf{LValue}$(I') == z$}\n                                \\State $reachedEnd \\gets false$           \n                                \\State \\textbf{break}\n                            \\EndIf\n                            \\State $curPart = curPart \\setminus \\{$\\textbf{LValue}$(I')\\}$\n                            \\If{not $curPart.empty()$}\n                                \\State $replacement \\gets curPart.first()$\n                                \\State \\textbf{Replace}$(I',\\ z,\\ replacement)$\n                            \\Else\n                                \\State $B.insert(I', z \\gets replacement)$\n                                \\State $AvailVars \\gets AvailVars \\cup \\{z\\}$\n                                \\State $reachedEnd \\gets false$\n                                \\State \\textbf{break}\n                            \\EndIf\n                        \\EndFor\n                        \\State\n                        \\If{$reachedEnd$}\n                            \\State $B.insert(z \\gets replacement)$\n                        \\EndIf\n                        \\State \\textbf{DeleteInstruction}$(I)$\n                        \\State\n                    \\Else\n                        \\State $AvailVars \\gets AvarilVars \\cup \\{z\\}$\n                    \\EndIf\n                \\EndIf\n            \\EndIf\n        \\EndFor\n    \\EndFor\n\\EndProcedure\n\\end{algorithmic}\n\\end{algorithm}\n    \nAlso note the following functions whose details has not been provided.\\\\\n\\textbf{Instructions}$(B)$ :- Returns a list of instructions in the basic block $B$.\\\\\n\\textbf{Replace}$(I', z, replacement)$ :- Replaces variable $z$ in the instruction $I'$ with $replacement$ which can be a constant or another variable.\\\\\n\\textbf{B.insert}$(I)$ :- Inserts instruction $I$, at the end of basic block $B$.\\\\\n\\textbf{B.insert}$(I, I')$ :- Insert instruction $I'$ before instruction $I$ in basic block $B$.\\\\\n\\textbf{DeleteInstruction}$(I)$ :- Deletes instruction $I$ from the program.\\\\\n\\textbf{set.empty}$()$ :- Returns $true$ if $set$ is empty, else $false$.\\\\\n\\textbf{set.first}$()$ :- Returns first element from $set$.\\\\\n\n\\section{LLVM Implementation}\n\\label{LLVMImplementation}\nThe LLVM specific implementation of the pseudocodes mentioned can be found in \n\\href{https://github.com/himanshu520/HerbrandEquivalence}{this github repository}.", "meta": {"hexsha": "7e92be27c5930111405802afb16963ae8c58028a", "size": 6929, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "reports/Rep_Mid_8/chapter8.tex", "max_stars_repo_name": "himanshu520/HerbrandEquivalence", "max_stars_repo_head_hexsha": "bfe056d9d370d9e5fe2782381b872bf102a960ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "reports/Rep_Mid_8/chapter8.tex", "max_issues_repo_name": "himanshu520/HerbrandEquivalence", "max_issues_repo_head_hexsha": "bfe056d9d370d9e5fe2782381b872bf102a960ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "reports/Rep_Mid_8/chapter8.tex", "max_forks_repo_name": "himanshu520/HerbrandEquivalence", "max_forks_repo_head_hexsha": "bfe056d9d370d9e5fe2782381b872bf102a960ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.4589041096, "max_line_length": 153, "alphanum_fraction": 0.5954683215, "num_tokens": 1693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3065307247883567}}
{"text": "\\documentclass[12pt]{article}\n\n\\usepackage[top=1in, bottom=1in, left=1in, right=1in]{geometry} \n\\usepackage{graphicx}\n\\usepackage{titling}\n\\usepackage{float}\n\\usepackage{bm}\n%\\usepackage[fleqn]{amsmath}\n\\usepackage{amssymb,amsmath}\n\\usepackage{listings}\n\\usepackage{color}\n\\usepackage{multirow}\n\\usepackage{enumitem}\n\\usepackage{fancyvrb}\n\\usepackage{hyperref}\n\\usepackage{setspace}\n\\usepackage{tabularx}\n\\usepackage{diagbox}\n\\geometry{letterpaper}\n\\linespread{1.1}% \\geometry{landscape} % rotated page geometry\n\n\\definecolor{codegreen}{rgb}{0,0.6,0}\n\\definecolor{codegray}{rgb}{0.5,0.5,0.5}\n\\definecolor{codepurple}{rgb}{0.58,0,0.82}\n\\definecolor{backcolour}{rgb}{0.95,0.95,0.92}\n\\definecolor{outcolor}{rgb}{0.545, 0.0, 0.0}\n\n\\lstdefinestyle{mystyle}{\n\tbackgroundcolor=\\color{backcolour},   \n\tcommentstyle=\\color{codegreen},\n\tkeywordstyle=\\color{magenta},\n\tnumberstyle=\\tiny\\color{codegray},\n\tstringstyle=\\color{codepurple},\n\tbasicstyle=\\footnotesize,\n\tbreakatwhitespace=false,         \n\tbreaklines=true,                 \n\tcaptionpos=b,                    \n\tkeepspaces=true,                 \n\tnumbers=left,                    \n\tnumbersep=5pt,                  \n\tshowspaces=false,                \n\tshowstringspaces=false,\n\tshowtabs=false,                  \n\ttabsize=2\n}\n\n\\lstset{style=mystyle}\n\n\\setlength{\\droptitle}{-5em}\n\\title{CE 295 Project Proposal}\n\\date{9 Feb. 2018} \n\\author{Team 17}\n\n\\begin{document}\n\t\n\t\\maketitle\n\t\\renewcommand\\theequation{\\arabic{equation}}\n\t\\renewcommand{\\figurename}{Fig.}\n\t\\renewcommand\\thesection{\\Roman{section}}\n\t\\renewcommand\\thesubsection{(\\alph{subsection})}\n\t%\\onehalfspacing\n\t\n\\section{Title \\& Team Member Names}\n\\textbf{Title:} States Estimation of Li-ion Batteries with Electro-Thermal-Aging Dynamics\\\\\n\\textbf{Team Member:} Xin Peng, Junzhe Shi, Franklin Zhao, and Ruitong Zhu\n\\section{Abstract}\nBatteries are ubiquitous in all forms of electronics and transportation, and also are a key to the store of clean and secure energy. In different kinds of batteries,  Li-ion battery is the most prominent one due to their superior gravimetric and volumetric energy density.  For the safe operation of Li-ion battery, the state of charge (SOC) and state of health (SOH) estimation is of great significance. Hence, the goal of the project is to design a robust observer which can estimate the SOC and SOH of Li-ion batteries. In the project, the equivalent-circuit model will be used for the battery modeling with current and ambient temperature as inputs and voltage as the measured output. The equivalent-circuit model will include three parts which are an electrical model, a thermal model, and an aging model. To ensure the accuracy of states estimation, both of Luenberger observer and Kalman filter will be used and examined in the project. The battery system will be built and simulated by MATLAB and/or Python. The robustness of designed observer will be tested by real Li-ion battery testing data.\n\\section{Introduction}\n\\subsection{Motivation \\& Background}\nThe identification of battery operation and aging in real life has been a long-desired yet challenging goal, which includes multiple complex processes in complicated operating conditions and environments. An accurate method to observe SOC and SOH of Li-ion battery is in need. Meanwhile, batteries invariably work at varying thermal and aging conditions. Thus, it’s necessary for us to build a battery observation system to monitor operation and aging of battery. The potential challenges also exist. We need to express a multi-control problem via mathematical equations and combine electrical model, thermal model and aging model. Besides, since all team members are major in Civil System, a lack of background knowledge in Electrical Engineering can be a big challenge. However, our previous course CE 291F, Control and Optimization of Distributed Parameters Systems can be helpful for the project. It gave us a background knowledge of partial differential equations, conservation laws, linear stability, Kaman filter and so on. We all have experiences of building, controlling and optimizing systems, including quench process,  heat diffusion and Lighthill Whitham Richards model.\n\\subsection{Focus of this study}\nIn this project, we will focus on the SOC and SOH of LI-ion batteries. Based on equivalent-circuit, the electrical, thermal and aging models will be developed for the observing system. Since battery monitoring and management can be the key to allowing innovation in future designs because of their limit properties, our system may play an important role in such an area, and significantly contribute to the energy saving and efficiency. \n\\newpage\n\\section{Statement of Work}\nThe statement of work is shown in Table 1.\n\\begin{center}\nTable 1: Statement of Work\n\\end{center}\n\\vspace{-23pt}\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics[width=\\linewidth]{tmp.jpg}      \n\\end{figure}\n\\newpage\n\\section{Summary}\nThis project will basically develop an obeserving system with high efficiency and robustness. Eletrical, thermal, and aging models will be built based on the equivalent-circuit model. The accuracy will be tested using Luenberger observer and Kalman filter.\n\\section*{Relevant Literature}\n\\begin{itemize}[noitemsep, topsep=0pt]\n\t\\item[{[1]}] Perez, Hector, et al. ``Optimal Charging of Li-Ion Batteries with Coupled Electro-Thermal-Aging Dynamics.\" \\textit{IEEE Transactions on Vehicular Technology}, vol. 66, no. 9, pp. 99, 2017.\n\t\\item[{[2]}] G. L. Plett, ``Extended Kalman filtering for battery management systems of LiPB-based HEV battery packs: Part 1. Background,\" \\textit{Journal of Power Sources}, vol. 134, no. 2, pp. 252 – 61, 2004.\n\t\\item[{[3]}] G. L. Plett, ``Extended Kalman filtering for battery management systems of LiPB-based HEV battery packs: Part 2. Modeling and identification,\" \\textit{Journal of Power Sources}, vol. 134, no. 2, pp. 262 – 76, 2004.\n\t\\item[{[4]}] G. L. Plett, ``Extended Kalman filtering for battery management systems of LiPB-based HEV battery packs: Part 3. State and parameter estimation,\" \\textit{Journal of Power Sources}, vol. 134, no. 2, pp. 262 – 76, 2004.\n\t\\item[{[5]}] Lin, Xinfan, et al. ``A lumped-parameter electro-thermal model for cylindrical batteries.\" \\textit{Journal of Power Sources}, vol. 257, no. 0, pp. 1 – 11, 2014.\n\\end{itemize}\n\\end{document}", "meta": {"hexsha": "91a901620bf034e188dc269e9339455c0d3839ae", "size": 6338, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/proposal/CE295ProjectProposalTeam17.tex", "max_stars_repo_name": "QinganZhao/Cycle-life-model-for-graphite-LiFePO4-cells", "max_stars_repo_head_hexsha": "be457810276c08c073007828e8ed1a79db2349ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2018-12-28T13:06:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T02:42:30.000Z", "max_issues_repo_path": "doc/proposal/CE295ProjectProposalTeam17.tex", "max_issues_repo_name": "Monowar51-tech/Cycle-life-model-for-graphite-LiFePO4-cells", "max_issues_repo_head_hexsha": "be457810276c08c073007828e8ed1a79db2349ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/proposal/CE295ProjectProposalTeam17.tex", "max_forks_repo_name": "Monowar51-tech/Cycle-life-model-for-graphite-LiFePO4-cells", "max_forks_repo_head_hexsha": "be457810276c08c073007828e8ed1a79db2349ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2018-12-28T15:12:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T09:26:51.000Z", "avg_line_length": 66.7157894737, "max_line_length": 1183, "alphanum_fraction": 0.7650678447, "num_tokens": 1637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3065307247883567}}
{"text": "\\subsubsection{\\texorpdfstring{The 3\\textsuperscript{rd} Law of Thermodynamics}{The 3rd Law of Thermodynamics}}\nThe third law of thermodynamics is that fix. It states that\n\\begin{center}\n    \\textbf{As the temperature of a system tends towards absolute zero, the entropy of the system tends towards a finite value.}\n\\end{center}\nGreat! That means that using zero as our reference point, we can calculate the entropy of the system at any other state.\n\nBut here's the thing (thing might be the 956\\textsuperscript{th} time I've said this). We've figured our \\textit{how} entropy behaves, and can use it to predict the future behaviour of the system. But we seem no closer to figuring out \\textit{what} entropy is or \\textit{why} it behaves the way it does. Luckily, someone else has already figured that out quite a while ago!", "meta": {"hexsha": "ed80fef5bc7c4c2f71ee282f1a301a1ce363399c", "size": 824, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Entropy/thirdlaw.tex", "max_stars_repo_name": "RioWeil/SCIE001-thermo-notes", "max_stars_repo_head_hexsha": "8578248f8f79f5704319dc6cd4ec679ce12b949c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Entropy/thirdlaw.tex", "max_issues_repo_name": "RioWeil/SCIE001-thermo-notes", "max_issues_repo_head_hexsha": "8578248f8f79f5704319dc6cd4ec679ce12b949c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Entropy/thirdlaw.tex", "max_forks_repo_name": "RioWeil/SCIE001-thermo-notes", "max_forks_repo_head_hexsha": "8578248f8f79f5704319dc6cd4ec679ce12b949c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-30T05:36:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-30T05:36:50.000Z", "avg_line_length": 103.0, "max_line_length": 373, "alphanum_fraction": 0.7827669903, "num_tokens": 207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.527316523379567, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3065307247883566}}
{"text": "%========================================================================\n%Beginning of Chapter 2\n%========================================================================\n\n\\section{THE SOFTWARE COMPONENTS}\\label{ch:overview}\n\n\\subsection{Introduction}\\label{sec:chp2intro}\n\nThere are many issues to be addressed when using multiple libraries together.  The scope of the different components presented is quite vast and their dependencies and usage vary extensively.  Understanding the importance and the work involved in tying these together requires a thorough overview of each piece of software.  Some theory will be covered as well to explain what the libraries do or why they're necessary.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Finite Difference Vs. Finite Element}\\label{sec:chp2grid}\n\nCurrently many glacial models, including the one used, that run large scale simulations use finite difference methods in order to solve the partial differential equations involved in the numerical approximations.  Finite difference methods are used primarily due to the ease of implementation with fluid dynamics, especially over large areas, and the computations are also less intensive than with finite element methods.\n\nFinite element analysis provides a much more efficient way of calculating the solution with an area that is not of a fixed sized.  The difference can be summed up by a quote from Gershenfeld about finite elements: ``Instead of discretizing the space in which the problem is posed, this (finite element analysis) discretizes the form of the function used to represent the solution.\" \\citep{Gershenfeld:1999}  \n\nAs discussed later in chapter \\ref{ch:verification} using finite difference methods, both for data and for the calculations, can introduce artifacts and erroneous results if not careful since the domain in ice-sheet modeling can change drastically, but the points at which the approximations are being made do not.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{GLIMMER-CISM}\\label{sec:chp2cism}\n\nGLIMMER-CISM is a three-dimensional thermo-mechanical ice-sheet model that is open source and is developed to better understand ice dynamics within glaciers and sea-rise consequences.  GLIMMER (GENIE Land Ice Model with Multiply-Enabled Regions) was originally developed as part of the GENIE (Grid-ENabled Integrated Earth system model) project in order to be the glacial modeling component of the larger model.\\citep{glimmerdoc}\n\nBeginning in 2002 GLIMMER was used as the basis for advancing current research of ice-sheet dynamics.  The current model, GLIMMER-CISM (Community Ice Sheet Model) has incorporated many new elements beyond the standard SIA (Shallow Ice Approximation) that the original model used. \n\\citep{cismwiki:website}\n\nGLIMMER-CISM now has a higher-order model for mass-balance based on recent ideas by Pattyn \\citep{Pattyn:2003}, some verification tools and test suites, more standardization, intermodel comparisons, and a lot of developers building an infrastructure to share data within the community.\n\nGLIMMER-CISM is written primarily in Fortran and uses NetCDF (Network Common Data Form) files as the input and output to the model as well as configuration files for options, model size, simulation lengths, and many other parameters that can be set.  This makes the model very capable and adaptable for both small and large scale simulations. \n\n\n%GLIMMER-CISM is based on a staggered grid.  blah\n\n%should i talk about the sia or first order model mathematics?????????\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{PHAML}\\label{sec:ch2phaml}\n\nPHAML stands for ``Parallel Hierarchical Adaptive MultiLevel method\", and it uses several hp-adaptive methods using triangle meshes to solve elliptical partial differential equations.  PHAML incorporates a lot more than just the solving methods though.  The software contains parallel libraries to run parts of the simulation over multiple processors, it has OpenGL bindings allowing the user to receive 3D representations of the solutions, and it is very extendible allowing other solvers to be used.\n\nPHAML is designed to solve linear elliptical partial differential equations of the form:\n\n\\begin{equation}\n    - \\frac{\\partial}{\\partial x} \\left (c_{xx}\\frac{\\partial u}{\\partial x} \\right ) - \\frac{\\partial}{\\partial x} \\left (c_{xy}\\frac{\\partial u}{\\partial y} \\right ) - \\frac{\\partial}{\\partial y} \\left (c_{yy}\\frac{\\partial u}{\\partial y} \\right ) + c_x \\frac{\\partial u}{\\partial x} + c_y \\frac{\\partial u}{\\partial y} + c_{u}u = f \\; in \\; \\Omega\n\\label{eq:phamlmain}\n\\end{equation}\n\nwhere $c_{xx},c_{yy},c_x,c_y$ and $f$ are functions of $x$ and $y$, and the domain $\\Omega$ is a bounded, connected, region in $R^2$.\\citep{phamldoc}  The boundary conditions can be Dirchlet, natural, or mixed.  Dirichlet boundary conditions are of the form:\n\n\\begin{equation}\nu=g \\; on \\; \\partial \\Omega_D\n\\label{eq:dirbound}    \n\\end{equation}\n\notherwise the boundary is defined by:\n\\begin{equation}\n    \\left ( c_{xx} \\frac{\\partial u}{\\partial x} + c_{xy}\\frac{\\partial u}{\\partial y} \\right ) \\frac{\\partial y}{\\partial s} - c_{yy} \\frac{\\partial u}{\\partial y} \\frac{\\partial x}{\\partial s} + c_{bc}u = g \\; on \\; \\partial \\Omega_N\n\\label{eq:phamlbound}\n\\end{equation}\n\nwhere $g$ and $c_{bc}$ are also functions of $x$ and $y$ and everything else is as defined for the equation \\eqref{eq:phamlmain}.  Here $s$ is some parameter going through some finite range to define the boundary as a function $(x(s),y(s))$.  These equations are explained thoroughly in the PHAML documentation as well as all of the different consequences of a chosen boundary condition. \\citep{phamldoc}\n\n\n%I should talk about lin. elliptical pdes in general.\n\nPHAML works by allowing a custom PSLG (Planar Straight Line Graph) or mesh to be passed to the main program, and then it retrieves any information it needs about the solution (or the problem) by means of subroutine callbacks. These are listed in the appendix \\ref{sec:libphamlcall}.  These callbacks allow you to specify any of the coefficients as well as functions of the elliptical PDE.  This makes the solver very flexible since different types of solutions can be found merely be changing one of the callback.  For instance, solving Poisson would have the source subroutine returning the functional value at a given point, but by changing the callback to return zero for all points changes the solution to the Laplacian.\n\nThe callbacks also allow for several interesting PDE characteristics to be achieved if desired such as non-homogeneous coefficients, using true solutions, derivative and second derivative based functions, etc.\n\nThe mesh geometry can also be generated once the program starts if a functional boundary exists.  There are callbacks that allow the program to define what the boundary is while PHAML is executing.  This is very beneficial when solving for solutions based on a dataset or a function.\n\nOne of the most beneficial aspects of PHAML are that it uses hp-adaptive finite element analysis methods.  This allows it to solve PDEs by using piece-wise polynomial approximations that employ elements of variable size (h) and polynomial degree (p). As demonstrated by W. Mitchell this allows hp-FEM methods to not only be more accurate than standard FEM, but that they can also achieve ``a convergence rate that is exponential in the number of degrees of freedom.\" \\citep{mitchell:hp}\n\nHaving this amount of flexibility also means that PHAML has a lot of functionality that can be tweaked.  There are many options for nearly every facet of the solving process.  This can be very useful for solutions where a particular type of result is desired.  The options themselves will not be covered since they are listed and described in detail within the PHAML documentation.\\citep{phamldoc}\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Triangle}\\label{sec:chp2triangle}\n\nTriangle is summed up as ``a two-dimensional quality mesh generator and Delaunay triangulator\".\\citep{shewchuk96b}  The software is able to read in files describing a two-dimensional graph and build the data structure while adding useful functionality.  The software is also capable of dynamically refining the mesh, adding to the mesh, and providing instant feedback.  Triangle can generate ``exact Delaunay triangulations, constrained Delaunay triangulations, conforming Delaunay triangulations, Voronoi diagrams, and high-quality triangular meshes\". \\citep{Triangle:website} Most of the algorithms that Triangle depends upon are recent advanced triangulation methods as well as sorting and location algorithms.  Some algorithms stemming from this research, such as the robust geometric predicates, are also now used in many other areas of study. \\citep{shewchuk97a}\n\nTriangle is not used directly by the interface, but is used as the mesh component of PHAML.  The GLIMMER-CISM code uses the Triangle program simply to generate the mesh files needed by PHAML.  Since it is needed but not directly used, Triangle is not discussed as thoroughly.\n\n\\subsubsection{Showme}\n\nTriangle also comes with a small mesh viewer called `showme' which is very useful for looking at the mesh files directly.  This program opens the .poly files and allows easy access to the properties of the mesh.  This is useful in testing the different generation algorithms by being able to view the output file.  The only drawback of the application is that it doesn't show the bmarks associated with each node. \n\n\n%========================================================================\n%End of Chapter 2\n%========================================================================\n", "meta": {"hexsha": "37adafb6b7ab4ec5a9c6e18d3564f8c04ba8ac42", "size": 9854, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "models/glc/cism/glimmer-cism/doc/ext/libphaml/chapter2.tex", "max_stars_repo_name": "fmyuan/clm-microbe", "max_stars_repo_head_hexsha": "9faee9ed7d6c092c4a9e4a207f32cbffab78b85c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-03-12T01:58:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-16T03:08:25.000Z", "max_issues_repo_path": "models/glc/cism/glimmer-cism/doc/ext/libphaml/chapter2.tex", "max_issues_repo_name": "fmyuan/clm-microbe", "max_issues_repo_head_hexsha": "9faee9ed7d6c092c4a9e4a207f32cbffab78b85c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-21T01:51:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-21T01:51:13.000Z", "max_forks_repo_path": "models/glc/cism/glimmer-cism/doc/ext/libphaml/chapter2.tex", "max_forks_repo_name": "email-clm/CLM-Microbe", "max_forks_repo_head_hexsha": "711c87faec2c1bfe2cea1a7ebd07e4373e82a184", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2016-03-08T21:04:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-16T03:29:35.000Z", "avg_line_length": 104.829787234, "max_line_length": 868, "alphanum_fraction": 0.7435559164, "num_tokens": 2136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3065307171384899}}
{"text": "\\documentclass[letterpaper,12pt]{article}\n\n\\usepackage{threeparttable}\n\\usepackage{geometry}\n\\geometry{letterpaper,tmargin=1in,bmargin=1in,lmargin=1.25in,rmargin=1.25in}\n\\usepackage[format=hang,font=normalsize,labelfont=bf]{caption}\n\\usepackage{amsmath}\n\\usepackage{multirow}\n\\usepackage{array}\n\\usepackage{delarray}\n\\usepackage{amssymb}\n\\usepackage{amsthm}\n\\usepackage{lscape}\n\\usepackage{natbib}\n\\usepackage{setspace}\n\\usepackage{float,color}\n\\usepackage[pdftex]{graphicx}\n\\usepackage{pdfsync}\n\\usepackage{verbatim}\n\\usepackage{placeins}\n\\usepackage{geometry}\n\\usepackage{pdflscape}\n\\synctex=1\n\\usepackage{hyperref}\n\\hypersetup{colorlinks,linkcolor=red,urlcolor=blue,citecolor=red}\n\\usepackage{bm}\n\n\n\\theoremstyle{definition}\n\\newtheorem{theorem}{Theorem}\n\\newtheorem{acknowledgement}[theorem]{Acknowledgement}\n\\newtheorem{algorithm}[theorem]{Algorithm}\n\\newtheorem{axiom}[theorem]{Axiom}\n\\newtheorem{case}[theorem]{Case}\n\\newtheorem{claim}[theorem]{Claim}\n\\newtheorem{conclusion}[theorem]{Conclusion}\n\\newtheorem{condition}[theorem]{Condition}\n\\newtheorem{conjecture}[theorem]{Conjecture}\n\\newtheorem{corollary}[theorem]{Corollary}\n\\newtheorem{criterion}[theorem]{Criterion}\n\\newtheorem{definition}{Definition} % Number definitions on their own\n\\newtheorem{derivation}{Derivation} % Number derivations on their own\n\\newtheorem{example}[theorem]{Example}\n\\newtheorem{exercise}[theorem]{Exercise}\n\\newtheorem{lemma}[theorem]{Lemma}\n\\newtheorem{notation}[theorem]{Notation}\n\\newtheorem{problem}[theorem]{Problem}\n\\newtheorem{proposition}{Proposition} % Number propositions on their own\n\\newtheorem{remark}[theorem]{Remark}\n\\newtheorem{solution}[theorem]{Solution}\n\\newtheorem{summary}[theorem]{Summary}\n\\bibliographystyle{aer}\n\\newcommand\\ve{\\varepsilon}\n\\renewcommand\\theenumi{\\roman{enumi}}\n\\newcommand\\norm[1]{\\left\\lVert#1\\right\\rVert}\n\n\\begin{document}\n\nThis document outlines how we can us the first order conditions of the household to estimate the utility weights on the disutility of work and the warm glow bequest.  \n\n\\section{Estimating the utility weight on the disutility of work, $\\chi^{n}_{s}$}.\n\nThe household first order condition for the choice of hours worked yields:\n\n        \\begin{equation}\\label{EqEulerLabGen}\n      \\begin{split}\n        &(c_{j,s,t})^{-\\sigma}\\Biggl(w_t e_{j,s} - \\frac{\\partial T_{j,s,t}}{\\partial n_{j,s,t}}\\Biggr) = e^{g_y t(1-\\sigma)}\\chi^n_{s}\\biggl(\\frac{b}{\\tilde{l}}\\biggr)\\biggl(\\frac{n_{j,s,t}}{\\tilde{l}}\\biggr)^{v-1}\\Biggl[1 - \\biggl(\\frac{n_{j,s,t}}{\\tilde{l}}\\biggr)\\Biggr]^{\\frac{1-v}{v}} \\\\\n        &\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\forall j,t, \\quad\\text{and}\\quad E+1\\leq s\\leq E+S \\\\\n        &\\qquad\\text{where}\\quad c_{j,s,t} = \\left(1 + r_t\\right) b_{j,s,t} + w_t e_{j,s}n_{j,s,t} + \\frac{BQ_{j,t}}{\\lambda_j\\tilde{N}_t} - b_{j,s+1,t+1} - T_{j,s,t} \\\\\n        &\\qquad\\text{and}\\quad \\frac{\\partial T_{j,s,t}}{\\partial n_{j,s,t}} = w_t e_{j,s}\\biggl[\\tau^I\\bigl(F\\hat{a}_{j,s,t}\\bigr) + \\frac{F\\hat{a}_{j,s,t}CD\\bigl[2A(F\\hat{a}_{j,s,t})+B\\bigr]}{\\bigl[A(F\\hat{a}_{j,s,t})^2+B(F \\hat{a}_{j,s,t})+C\\bigr]^2} + \\tau^P\\Biggr] \n      \\end{split}\n    \\end{equation}\n    \n    To simplify notation a bit, let $w_{t}e_{j,s}=\\tilde{w}_{j,s,t}$, which is defined as the hourly earnings of household of ability type $j$, age $s$, at time $t$.  Further, we can write derivative of the tax function, $ \\frac{\\partial T_{j,s,t}}{\\partial n_{j,s,t}}$ as $\\tau^{l}(y_{j,s,t})\\tilde{w}_{j,s,t}$, where $\\tau^{l}(y_{j,s,t})$ is the marginal tax rate on labor income for an individual with taxable income $y_{j,s,t}$.  Now we can write the FOC as:\n    \n            \\begin{equation}\\label{EqEulerLabGen}\n      \\begin{split}\n        &(c_{j,s,t})^{-\\sigma}\\Biggl(\\tilde{w}_{j,s,t}(1-\\tau^{l}(y_{j,s,t})\\Biggr) = e^{g_y t(1-\\sigma)}\\chi^n_{s}\\biggl(\\frac{b}{\\tilde{l}}\\biggr)\\biggl(\\frac{n_{j,s,t}}{\\tilde{l}}\\biggr)^{v-1}\\Biggl[1 - \\biggl(\\frac{n_{j,s,t}}{\\tilde{l}}\\biggr)\\Biggr]^{\\frac{1-v}{v}} \n        \\end{split}\n        \\end{equation}\n        \n        This problem is deterministic, but we can assume that their is some noise in the data, thus the data analog to the model FOC is: \n\n  \\begin{equation}\\label{EqEulerLabGen}\n      \\begin{split}\n        &(c_{j,s,t})^{-\\sigma}\\Biggl(\\tilde{w}_{j,s,t}(1-\\tau^{l}(y_{j,s,t})\\Biggr) - e^{g_y t(1-\\sigma)}\\chi^n_{s}\\biggl(\\frac{b}{\\tilde{l}}\\biggr)\\biggl(\\frac{n_{j,s,t}}{\\tilde{l}}\\biggr)^{v-1}\\Biggl[1 - \\biggl(\\frac{n_{j,s,t}}{\\tilde{l}}\\biggr)\\Biggr]^{\\frac{1-v}{v}} = \\varepsilon_{j,s,t}  \n        \\end{split}\n        \\end{equation}\n\nAnd the moment condition for a GMM estimator for each $\\chi^{n}_{s}$ would be:\n\n  \\begin{equation}\\label{EqEulerLabGen}\n      \\begin{split}\n        &\\sum_{J}\\sum_{T}\\left[(c_{j,s,t})^{-\\sigma}\\Biggl(\\tilde{w}_{j,s,t}(1-\\tau^{l}(y_{j,s,t})\\Biggr) - e^{g_y t(1-\\sigma)}\\chi^n_{s}\\biggl(\\frac{b}{\\tilde{l}}\\biggr)\\biggl(\\frac{n_{j,s,t}}{\\tilde{l}}\\biggr)^{v-1}\\Biggl[1 - \\biggl(\\frac{n_{j,s,t}}{\\tilde{l}}\\biggr)\\Biggr]^{\\frac{1-v}{v}}\\right] =\\\\\n        &  \\quad  \\quad  \\quad  \\quad  \\quad  \\quad \\sum_{J}\\sum_{T}\\varepsilon_{j,s,t}  = 0\n        \\end{split}\n        \\end{equation}\n        \n        Note that the above equation for each $s$ - and we can have more moment conditions if we wish to have an over-identified model.  We may also think about estimating the parameters of the ellipse via this method.\n        \n        To estimate, we need data on consumption, $c$, and labor supply, $n$, by lifetime income group, age, and year.  We can get this from the PSID - see \\\\\n        \\href{http://www.federalreserve.gov/pubs/feds/2007/200716/200716pap.pdf}{http://www.federalreserve.gov/pubs/feds/2007/200716/200716pap.pdf} for a document outlining the measurement of consumption from the PSID.  We can find $\\tau^{l}(y_{j,s,t})$ by running the PSID observation through a tax calculator (e.g. the OSPC calculator).  The remaining parameters are calibrated elsewhere.\n        \n        \n        \n\\section{Estimating the utility weight on the warm glow bequest motive, $\\chi^{b}_{j}$}.\n\nThe household first order condition for the choice of savings yields:\n\n    \\begin{equation}\\label{EqEulerSavGen}\n      \\begin{split}\n        &(c_{j,s,t})^{-\\sigma} = \\rho_s\\chi^b_j\\bigl(b_{j,s+1,t+1}\\bigr)^{-\\sigma} + \\beta(1-\\rho_s)(c_{j,s+1,t+1})^{-\\sigma}\\Biggl[(1 + r_{t+1}) - \\frac{\\partial T_{j,s+1,t+1}}{\\partial b_{j,s+1,t+1}}\\Biggr] \\\\\n        &\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\forall j,t,\\quad\\text{and}\\quad E+1\\leq s \\leq E+S-1 \\\\\n        &\\qquad\\text{where}\\quad \\frac{\\partial T_{j,s+1,t+1}}{\\partial b_{j,s+1,t+1}} = ...\\\\\n        &\\qquad\\qquad r_{t+1}\\Biggl(\\tau^I(F\\hat{a}_{j,s+1,t+1}) + \\frac{F\\hat{a}_{j,s+1,t+1}CD\\left[2A(F\\hat{a}_{j,s+1,t+1}) + B\\right]}{\\left[A(F\\hat{a}_{j,s+1,t+1})^2 + B(F\\hat{a}_{j,s+1,t+1}) + C\\right]^2}\\Biggr) ... \\\\\n        &\\qquad\\qquad \\tau^W(\\hat{b}_{j,s+1,t+1}) + \\frac{\\hat{b}_{j,s+1,t+1}PHM}{\\left(H\\hat{b}_{j,s+1,t+1} + M\\right)^2}\n      \\end{split}\n    \\end{equation}\n    \n    We can write derivative of the tax function, $ \\frac{\\partial T_{j,s,t}}{\\partial b_{j,s,t}}$ as $\\tau^{b}(y_{j,s,t})r_{t+1}$, where $\\tau^{b}(y_{j,s,t})$ is the marginal tax rate on capital income for an individual with taxable income $y_{j,s,t}$.  Now we can write the FOC as:\n    \n            \\begin{equation}\\label{EqEulerLabGen}\n        (c_{j,s,t})^{-\\sigma} = \\rho_s\\chi^b_j\\bigl(b_{j,s+1,t+1}\\bigr)^{-\\sigma} + \\beta(1-\\rho_s)(c_{j,s+1,t+1})^{-\\sigma}\\Biggl[(1 + (1-\\tau^{b}_{j,s+1,t+1})r_{t+1}) \\Biggr]\n        \\end{equation}\n        \n        This problem is deterministic, but we can assume that their is some noise in the data, thus the data analog to the model FOC is: \n\n  \\begin{equation}\\label{EqEulerLabGen}\n      \\begin{split}\n         (c_{j,s,t})^{-\\sigma} - \\rho_s\\chi^b_j\\bigl(b_{j,s+1,t+1}\\bigr)^{-\\sigma} + \\beta(1-\\rho_s)(c_{j,s+1,t+1})^{-\\sigma}\\Biggl[(1 + (1-\\tau^{b}_{j,s+1,t+1})r_{t+1}) \\Biggr] = \\varepsilon_{j,s,t}  \n        \\end{split}\n        \\end{equation}\n\nAnd the moment condition for a GMM estimator for each $\\chi^{b}_{j}$ would be:\n\n  \\begin{equation}\\label{EqEulerLabGen}\n      \\begin{split}\n        &\\sum_{S}\\sum_{T}\\left[( (c_{j,s,t})^{-\\sigma} - \\rho_s\\chi^b_j\\bigl(b_{j,s+1,t+1}\\bigr)^{-\\sigma} + \\beta(1-\\rho_s)(c_{j,s+1,t+1})^{-\\sigma}\\Biggl[(1 + (1-\\tau^{b}_{j,s+1,t+1}r_{t+1}) \\Biggr]\\right] = \\\\\n        &    \\quad\\quad\\quad\\quad \\quad \\quad \\sum_{S}\\sum_{T}\\varepsilon_{j,s,t}  = 0\n        \\end{split}\n        \\end{equation}\n        \n        Note that the above equation for each $j$ - and we can have more moment conditions if we wish to have an over-identified model. \n        \n        To estimate, we need data on consumption, $c$, and wealth, $b$, by lifetime income group, age, and year.  We can get consumption from the PSID, as noted above.  We can also get wealth from the PSID, at least for the years 1984-2005 - see \\href{http://www.brookings.edu/~/media/research/files/papers/2009/2/saving-wealth-bosworth/02\\_saving\\_wealth\\_bosworth.pdf}{http://www.brookings.edu/~/media/research/files/papers/2009/2/saving-wealth-bosworth/02\\_saving\\_wealth\\_bosworth.pdf} for a document outlining the measurement of wealth from the PSID.  We can find $\\tau^{b}(y_{j,s,t})$ by running the PSID observation through a tax calculator (e.g. the OSPC calculator).  The remaining parameters are calibrated elsewhere.\n        \n\n\n   \n    \n\n\n\\end{document}", "meta": {"hexsha": "cf00e50d73d55192e2ca6a991547c46bc0bb19c2", "size": 9370, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Data/Calibration/UtilityWeights/chi_b_chi_n_calib_gmm.tex", "max_stars_repo_name": "lnsongxf/OG-USA", "max_stars_repo_head_hexsha": "9e92129e67f4aea5f3a6b8da4110bf67b99ce88a", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-05-23T13:57:53.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-23T13:57:53.000Z", "max_issues_repo_path": "Data/Calibration/UtilityWeights/chi_b_chi_n_calib_gmm.tex", "max_issues_repo_name": "lnsongxf/OG-USA", "max_issues_repo_head_hexsha": "9e92129e67f4aea5f3a6b8da4110bf67b99ce88a", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data/Calibration/UtilityWeights/chi_b_chi_n_calib_gmm.tex", "max_forks_repo_name": "lnsongxf/OG-USA", "max_forks_repo_head_hexsha": "9e92129e67f4aea5f3a6b8da4110bf67b99ce88a", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-03T19:06:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-03T19:06:24.000Z", "avg_line_length": 61.2418300654, "max_line_length": 727, "alphanum_fraction": 0.6574172892, "num_tokens": 3357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593171945416, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3063670908920208}}
{"text": "\\section{Kinetic model algorithm.}\n\n The kinetic algorithm can be considered as a step by step\nupdating of a particle vector:\n\\begin{enumerate}\n\\item Create a vector of particles: assign initial\nparticle types, their coordinates and momenta etc. Assign initial value\nfor time evolution parameter;\n\\item  For choosen time evolution parameter step find pairs of particles\n(according to a collision criterion), which are assumed to collide and\nparticles (according to their life times), which are assumed to decay; \n\\item  Perform particle collisions and particle decays. Collisions and\ndecays convert incoming particles  into outgoing particles. During this\nstep one should update also particle coordinates and momenta (particle \npropagation); \n\\item Starting from (2) perform the next step.\n\\end{enumerate}\n\nAt any evolution parameter step one needs a possibility to interupt\n\"updating\" process.\nThus at\n each evolution time step  for the system consisting\nfrom $n$ particles we are looking for the particles, which will decay\naccording to their lifetimes and the pairs $(i,j)$, where $i\\neq j$ and\n$i,j = 1,2,...,n$, of particles, which will collide according to the\nchoosen collision criterion. The collision pairs are ordered\nchronologically using their collision times.  This algorithm is very\nsimple and general enough but it is CPU time consuming if $n$ is large, \ne. g. during\nnucleus-nucleus collision at high energy, because at each time step we\nneed to perform $n(n-1)/2 \\sim n^2$ computations. \n \nIf we neglect by field interaction and keep only particle collisions and \ndecays (the cascade option), when\nparticles move along straight trajectories, after each collision we\nonly have to look for the collisions between new produced particles and\nthe existing particles. We also do not need to use fixed time step. We \nneed to \"shift\" system on time between events of collisions or decays.\n Then the number of computations at given time \nwill be $n_{new}n$, where $n_{new}$ is the number of produced particles\nduring the former time step. It should be noted that in this case we \nhave to maintain\n the list of\npotential particle collision or decay events.\nUsing \"cascade\" algorithm describing evolution of system we have the criterion \nto stop calculation process: the list of potential particle collision or \ndecay events is empty.\n", "meta": {"hexsha": "b3955611e55f4b14d556c63f0731f763e47326e2", "size": 2341, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "geant4/hadronic/theory_driven/HadronKinetic/KineticModelAlgorithm.tex", "max_stars_repo_name": "berghaus/cernlib-docs", "max_stars_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-24T12:30:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-24T12:30:01.000Z", "max_issues_repo_path": "geant4/hadronic/theory_driven/HadronKinetic/KineticModelAlgorithm.tex", "max_issues_repo_name": "berghaus/cernlib-docs", "max_issues_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geant4/hadronic/theory_driven/HadronKinetic/KineticModelAlgorithm.tex", "max_forks_repo_name": "berghaus/cernlib-docs", "max_forks_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.7708333333, "max_line_length": 79, "alphanum_fraction": 0.7928235797, "num_tokens": 517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593171945416, "lm_q2_score": 0.4921881357207955, "lm_q1q2_score": 0.30636709089202074}}
{"text": "\\section{Introduction}\n\\label{sec:intro}\n\n%We observe that the \\UTXO\\ ledger rules do not fundamentally depend on the fact that an output locks only a single integral value. Instead, all they require is that locked values follow the algebraic structure of a monoid. We exploit that insight by generalising the notion of locked values to cryptocurrency \\emph{bundles.} Furthermore, we extend transactions by a \\emph{forge} field, where user-defined tokens can be forged (or minted) and destroyed. That process is controlled by smart contract scripts called \\emph{monetary policies.}\n\n\nDistributed ledgers began by tracking just a single asset --- money.\nThe goal was to compete with existing currencies, and so they naturally started by focusing on their own currencies --- Bitcoin and its eponymous currency, Ethereum and Ether, and so on.\nThis focus was so clear that the systems tended to be identified with their primary currency.\n\nMore recently, it has become clear that it is possible and very useful to track other kinds of asset on distributed ledger systems.\nEthereum has led the innovation in this space, with ERC-20~\\cite{erc20} implementing new currencies and ERC-721~\\cite{erc721} implementing unique non-fungible tokens.\n\nThese have been wildly popular --- variants of ERC-20 are the most used smart contracts on Ethereum by some margin.\nHowever, they have major shortcomings.\nNotably, custom tokens on Ethereum are not native. This means that tokens do not live in a user's account, and in order to send another user ERC-20 tokens, the sender must interact with the governing smart contract for the currency.\nThat is, despite the fact that Ethereum's main purpose is to track ownership of assets and perform transactions, users have been forced to build their own \\emph{internal ledger} inside a smart contract.\n\nOther systems have learned from this and have made custom tokens native, such as Stellar, Waves,\nZilliqa, and more.\nHowever, these typically rely on some kind of global state, such as a global currency registry, or special global accounts that must be created.\nThis is slow, and restricts creative use of custom tokens because of the high overhead in terms of time and money.\nThere have also been efforts to introduce native multi-assets into UTXO ledgers~\\cite{mcledgers}, a precursor to our work.\n\nWe can do better than this through a combination of two ideas.\nFirstly, we generalise the value type that the ledger works with to include \\emph{token bundles} that freely and uniformly mix tokens from different custom assets, both fungible and non-fungible.\nSecondly, we avoid any global state by ``eternally'' linking a currency to a governing forging policy via a hash.\nBetween them this creates a multi-asset ledger system (which we call \\UTXOma) with native, lightweight custom tokens.\n\nSpecifically, this paper makes the following contributions:\n%\n\\begin{itemize}\n\\item We introduce token bundles, represented as finitely-supported functions, as a uniform mechanism to generalise the existing \\UTXO\\ accounting rules to custom assets including fungible, non-fungible, and mixed tokens.\n\\item We avoid the need for global state in the form of a currency registry by linking custom forging policy scripts by way of their script hash to the name of asset groups.\n\\item We support a wide range of standard applications for custom assets without the need for general-purpose smart contracts by defining a simple domain-specific language for forging policy scripts.\n\\item We provide a formal definition of the \\UTXOma\\ ledger rules as a basis to formally reason about the resulting system, along with a mechanised version in Agda.\\footnote{\\url{\\agdaRepo}}\n\n\\end{itemize}\n%\nCreating and transferring new assets in the resulting system is lightweight and cheap. It is lightweight as we avoid special setup transactions or registration procedures, and it is cheap as only standard transaction fees are required --- this is unlike the Ethereum gas model, where a script must\nbe run each time a custom asset is transferred, which incurs gas costs.\n\nThe proposed multi-asset system is not merely a pen and paper exercise. It forms the basis of the multi-asset support for the Bcc blockchain.\nIn a related work~\\cite{eutxo-ma}, we further modify the native multi-asset ledger\npresented in this paper to an extended UTxO ledger model, which additionally supports\nthe use of Zerepoch (Turing complete smart contract language) to define forging policies.\nThis ledger model extension allows the use of stateful smart contracts to define\nstate machines for output locking.\n", "meta": {"hexsha": "c53f910ac066129ceb4bb3bd5303ff8a1b2f16da", "size": 4589, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "papers/utxoma/intro.tex", "max_stars_repo_name": "Quantum-One-DLT/zerepoch", "max_stars_repo_head_hexsha": "c8cf4619e6e496930c9092cf6d64493eff300177", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "papers/utxoma/intro.tex", "max_issues_repo_name": "Quantum-One-DLT/zerepoch", "max_issues_repo_head_hexsha": "c8cf4619e6e496930c9092cf6d64493eff300177", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "papers/utxoma/intro.tex", "max_forks_repo_name": "Quantum-One-DLT/zerepoch", "max_forks_repo_head_hexsha": "c8cf4619e6e496930c9092cf6d64493eff300177", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-11-13T21:25:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T16:38:59.000Z", "avg_line_length": 93.6530612245, "max_line_length": 539, "alphanum_fraction": 0.8047504903, "num_tokens": 970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.30629831780077504}}
{"text": "\\chapter{3D source reconstruction: Imaging approach}\n\\label{ch:eeg_imaging}\n\nHere is a brief help to the 3D reconstruction based on the Imaging approach. In the near future, this will be improved by including more theoretical details upon the different procedures as well as a practical tutorial that will guide the user through the SPM interface via the analysis of a sample dataset.\n\n\\section{Introduction}\n\\label{sec:imaginv_intro}\nThis chapter focuses on the imaging (or distributed) method for doing EEG/MEG source reconstruction in SPM.\nSuch an approach to spatial projection onto (3D) brain space consists in considering a large amount of dipolar sources all over the cortical sheet, with fixed locations and orientations. This renders the observation model linear, the unknown variables being the source amplitudes or power.\\\\\nGiven epoched and preprocessed data (see chapter ...), the evoked and/or induced activity for each dipolar source can be estimated, for a single time-sample or a wider peristimulus time window.\\\\\nThe obtained reconstructed activity is in 3D voxel space and enables mass-univariate analysis in SPM (see chapter...).\n\nContrary to PET/fMRI data reconstruction, EEG/MEG source reconstruction is a non trivial operation. Often compared to estimating a body shape from its shadow, inferring brain activity from scalp data is mathematically ill-posed and requires prior information such as anatomical, functional or mathematical constraints to isolate a unique and most probable solution~\\cite{Baillet01}.\n\nDistributed linear models have been around for more than a decade now~\\cite{Dale93} and the proposed pipeline in SPM for 'Imaging' solution is classical and very similar to common approaches in the field. However, at least two aspects are quite original and should be emphasized here:\n\\begin{itemize}\n\\item Based on an empirical Bayesian formalism, the inversion is meant to be generic in the sense it can incorporate and estimate the relevance of multiple constraints of various nature; data-driven relevance estimation being made possible through Bayesian model comparison~\\cite{peb1,Phillips05,Mattout06,karl_induced}.\n\\item The subject's specific anatomy is incorporated in the generative model of the data, in a fashion that eschews individual cortical surface extraction. The individual cortical mesh is obtained automatically from a canonical mesh in MNI space, providing a simple and efficient way of reporting results in stereotactic coordinates.\n\\end{itemize}\n\nThe EEG/MEG imaging pipeline is divided into four consecutive steps which characterize any inverse procedure. In this chapter, we go through each of those steps that all need to be completed when proceeding with a full inverse analysis:\n\\begin{enumerate}\n\t\\item Source space modeling,\n\t\\item Data co-registration,\n\t\\item Forward computation,\n\t\\item Inverse reconstruction.\n\\end{enumerate}\n\nWhereas the three first steps are part of the whole generative model, the last step consists in the Bayesian inversion and is the only one involving the actual EEG/MEG data.\\\\\n\nEverything which is described hereafter is a new feature in SPM and is accessible from SPM5 user-interface by choosing the 'EEG/MEG' application, '3D source reconstruction' and 'Imaging'.\n\n\\section{Data structure}\n\\label{sec:datastruct}\nThe Matlab structure describing a given EEG/MEG dataset in SPM is denoted as \\textit{D}. Within that structure, each new inverse analysis will be described by a new cell of sub-structure field \\textit{D.inv} and will be made of the following fields:\n\n\\begin{itemize}\n\t\\item \\textit{method}: character string indicating the method, either 'ECD' or 'Imaging' in present case;\n\t\\item \\textit{mesh}: sub-structure with relevant variables and filenames for source space and head modeling;\n\t\\item \\textit{datareg}: sub-structure with relevant variables and filenames for EEG/MEG data registration into MRI space;\n\t\\item \\textit{forward}: sub-structure with relevant variables and filenames for forward computation;\n\t\\item \\textit{inverse}: sub-structure with relevant variable, filenames as well as results files;\n\t\\item \\textit{comment}: character string provided by the user to characterize the present analysis;\n\t\\item \\textit{date}: date of the last modification made to this analysis.\n\\end{itemize}\n\n\n\\section{Source space modeling (\\textit{mesh})}\nThe individual cortical mesh is obtained from a template mesh. Four Mesh sizes are available (3004, 4004, 5004 and 7204 vertices). If not yet obtained, the spatial normalization of the subject's T1 MRI into MNI space is performed (see \\textit{spm\\_preproc.m} based on tissue probability maps). The inverse of that transformation is computed and applied to the template mesh to furnish the individual cortical mesh.\\\\\n\nIndividual meshes for the inner-skull and scalp surfaces are also computed from the individual T1 MRI. They are obtained by performing a binary mask of the the volumes delimited by the inner-skull and scalp surface respectively. Then, using an initial spherical mesh, a realistic-shaped mesh is obtained for each of the two tissues and further regularized via an erosion and growing procedure.\n\nThe meshing module includes the following functions:\n\\begin{itemize}\n\t\\item \\textit{spm\\_eeg\\_inv\\_mesh\\_ui.m}: run the user interface for this module,\n\t\\item \\textit{spm\\_eeg\\_inv\\_spatnorm.m}: normalize the T1 image if needed,\n\t\\item \\textit{spm\\_eeg\\_inv\\_meshing.m}: main function to produce Cortex, Inner-skull and Scalp meshes,\n\t\\item \\textit{spm\\_eeg\\_inv\\_getmasks.m}: produce masks of Inner-skull and Scalp,\n\t\\item \\textit{spm\\_eeg\\_inv\\_ErodeGrow.m}: erosion and growing procedure,\n\t\\item \\textit{spm\\_eeg\\_inv\\_getmeshes.m}: obtains the inner-skull and scalp meshes from correpsonding binary masks,\n\t\\item \\textit{spm\\_eeg\\_inv\\_CtrBin.m}\n\t\\item \\textit{spm\\_eeg\\_inv\\_TesBin.m}\n\t\\item \\textit{spm\\_eeg\\_inv\\_ElastM.m}\n\t\\item \\textit{spm\\_eeg\\_inv\\_checkmeshes.m}: displays the computed three meshes in the SPM main figure\n\\end{itemize}\n\n\n\\section{Data Registration (\\textit{datareg})}\n\\label{sec:datareg}\nThere are two possible ways of coregistrating the EEG/MEG data into the structural MRI space.\n\n\\begin{enumerate}\n\t\\item A Landmark based coregistration (using fiducials only).\\\\\n\tThe rigid transformation matrices (Rotation and Translation) are computed such that they match each fiducial in the EEG/MEG space into the corresponding one in sMRI space. The same \t\t\t\t\ttransformation is then applied to the sensor positions.\n\t\\item Surface matching (between some headshape in MEG/EEG space and some sMRI derived scalp tesselation).\nFor EEG, the sensor locations can be used instead of the headshape. For MEG, the headshape is first coregistrated into sMRI space; the same transformation is then applied to the sensors.\\\\\nSurface matching is performed using an Iterative Closest Point algorithm (ICP). The ICP algorithm~\\cite{Besl_McKay} is an iterative alignment algorithm that works in three phases:\n\\begin{itemize}\n\t\\item Establish correspondence between pairs of features in the two structures that are to be aligned based on proximity;\n\t\\item Estimate the rigid transformation that best maps the first member of the pair onto the second;\n\t\\item Apply that transformation to all features in the first structure. These three steps are then reapplied until convergence is concluded.\nAlthough simple, the algorithm works quite effectively when given a good initial estimate.\n\\end{itemize}\n\\end{enumerate}\n\nThe data-registration module includes the following functions:\n\\begin{itemize}\n\t\\item \\textit{spm\\_eeg\\_inv\\_datareg\\_ui.m}: run the user interface for this module,\n\t\\item \\textit{spm\\_eeg\\_inv\\_datareg.m}:\tmain co-registration function,\n\t\\item \\textit{spm\\_eeg\\_inv\\_checkdatareg.m}: display meshes, sensor locations and fiducials in native MRI space to enable one checking the co-registration by eye.\n\\end{itemize}\n\n\n\\section{Forward computation (\\textit{forward})}\nSeveral methods are proposed, depending on the modality (EEG or MEG). All these approaches/functions are identical to the one initialy developed and provided by the BrainSTorm package (Matlab open-source and free software: http://neuroimage.usc.edu/brainstorm/).\n\nFor EEG~\\cite{Ermer2001}:\n\\begin{enumerate}\n\t\\item single sphere (scalp surface),\n\t\\item three spheres (inner, outer skull and scalp surfaces),\n\t\\item three spheres (+ Berg correction),\n\t\\item overlapping spheres (one fitted sphere per sensor).\n\\end{enumerate}\n\nFor MEG~\\cite{Huang1999}:\n\\begin{enumerate}\n\t\\item single sphere,\n\t\\item overlapping spheres\n\\end{enumerate}\n\n\nThe forward module includes the following functions:\n\\begin{enumerate}\n\t\\item \\textit{spm\\_eeg\\_inv\\_forward\\_ui.m}: run the user interface for this module,\n\t\\item \\textit{spm\\_eeg\\_inv\\_BSTcreatefiles.m}:\tcreate the structure and required files and parameters to interface SPM and BrainSTorm,\n\t\\item \\textit{spm\\_eeg\\_inv\\_BSTfwdsol.m}:\tcompute the BrainSTorm forward solution, calling function \\textit{bst\\_headmodeler.m},\n\t\\item \\textit{spm\\_eeg\\_inv\\_PCAgain}: compute the svd of the gain matrix.\n\\end{enumerate}\n\n\n\\section{Inverse reconstruction (\\textit{inverse})}\nThe reconstruction is based on an empirical Bayesian approach to localize either the evoked response, the evoked power or the induced power, as measured by EEG or MEG.\n\nThe inverse module includes the following functions:\n\\begin{itemize}\n\t\\item \\textit{spm\\_eeg\\_inv\\_inverse\\_ui.m}: run the user interface for this module,\n\t\\item \\textit{spm\\_eeg\\_inv\\_inverse.m}: main function,\n\t\\item \\textit{spm\\_eeg\\_inv\\_evoked.m}:\tcompute the evoked response,\n\t\\item \\textit{spm\\_eeg\\_inv\\_induced.m}:\tcompute the evoked and/or induced power,\n\t\\item \\textit{spm\\_eeg\\_inv\\_msp.m}: Multivariate Source Prelocalisation~\\cite{Mattout2005a}.\n\\end{itemize}\n\t\n", "meta": {"hexsha": "e80aad80ee4ca8b132b20c79bf98e359cbda9721", "size": 9811, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "lib/spm5/man/meeg/eeg_imaging.tex", "max_stars_repo_name": "awangga/braindecoding", "max_stars_repo_head_hexsha": "97128a8346263c81c9ccd606cfa54b35dacd6ca1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/spm5/man/meeg/eeg_imaging.tex", "max_issues_repo_name": "awangga/braindecoding", "max_issues_repo_head_hexsha": "97128a8346263c81c9ccd606cfa54b35dacd6ca1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-10-13T13:34:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-13T14:23:51.000Z", "max_forks_repo_path": "lib/BDTB-1.2.2/open/spm5/man/meeg/eeg_imaging.tex", "max_forks_repo_name": "awangga/braindecoding", "max_forks_repo_head_hexsha": "97128a8346263c81c9ccd606cfa54b35dacd6ca1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 73.7669172932, "max_line_length": 416, "alphanum_fraction": 0.7971664458, "num_tokens": 2357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.30626105634612694}}
{"text": "\\chapter{Equation Input} \\label{chap:equation}\n\nThe expressions to be evaluated are entered by the user as equations.\nThe syntax is very similar to \\caps{FORTRAN} equation syntax. The first\nitem is the variable to be assigned, followed by an ``\\cmd{=}'', then\nthe expression to be evaluated. The expression consists of constants,\nvariables, arithmetic operators, and functions.\n\nThe equations must adhere to the following syntax rules.\n\\setlength{\\itemsep}{\\medskipamount} \\begin{itemize}\n\\item\nBlanks are treated as delimiters, but are otherwise ignored.\n\\item\nEither lowercase or uppercase letters are acceptable, but lowercase\nletters are converted to uppercase.\n\\item\nA ``\\verb|'|'' character in any equation starts a comment. The\n``\\verb|'|'' and any characters following it on the line are ignored.\n\\item\nAn equation may be continued over several lines with a ``\\verb|>|''\ncharacter. The ``\\verb|>|'' and any characters following it on the\ncurrent line are ignored and the next line is appended to the current\nline.\n\\end{itemize}\n\n\\section{The Assigned Variable} \\label{assvar}\n\nThe assigned variable name must start with a letter and can be up to\neight alphanumeric characters (A--Z, 0--9) long. A name that is longer\nthan eight characters is truncated with a warning. Blanks cannot be\nembedded in a variable name.\n\nAll assigned variables (except temporary variables specified by a\n\\cmd{DELETE} command) will be written to the output database. The input\ndatabase variables are not written to the output database unless they\nare assigned in an equation (such as \\cmd{X~=~X}) or transferred with a\n\\cmd{SAVE} command.\n\nThe type of the assigned variable depends on the expression. There are\nthree types of ``quantities'' in an expression that are related to the\nvariable types:\n\\setlength{\\itemsep}{\\medskipamount} \\begin{itemize}\n\\item\nGlobal quantities include global variables and nodal or element\nvariables for specific nodes or elements.\n\\item\nNodal quantities include nodal variables and nodal coordinates, unless\nthe value is limited to a specific node.\n\\item\nElement quantities include element variables, unless the value is\nlimited to a specific element.\n\\end{itemize}\nGlobal quantities are referred to as ``single-value''\nquantities. Nodal and element quantities are referred to as ``arrays''.\n\nEach part of an expression yields a result of a particular type. The\ntypes of constants and variables are defined above. The type of an\narithmetic operation is dependent on the types of its operands. If both\noperands are global quantities, the operation yields a global\nquantity. If either operand is an array, the operation type is\nthe array type. Thus a nodal quantity and an element quantity cannot\nappear in the same operation. For array operations, the operator is\napplied to each array element. The type of a function is dependent on\nthe types of its parameters. The rules for operand types also apply to\nall function parameters. One special type of function yields a global\nquantity regardless of the parameter type.\n\nThe assigned variable can be reassigned, but it must be assigned to the\nsame variable type (global, nodal or element).\n\nThe equations are evaluated in order. The assigned variables are grouped\nby variable type, but are otherwise output in the order they are first\nassigned by the equations.\n\nIf there are no timesteps on the input database, a timestep will be\nadded to the output database. The equation defining new variable(s)\ncan access constants and coordinates.\n\n\\section{Restricting the Nodes and/or Elements}\n\nNodes and/or elements may be deleted from the input database with the\n\\cmd{ZOOM}, \\cmd{VISIBLE}, \\cmd{FILTER}, or \\cmd{REMOVE} commands. An\ninput variable is defined for all input nodes and/or elements. An\noutput variable is only defined for the nodes and/or elements to be\noutput.\n\nElement variables may be undefined for certain element blocks. This may\nbe further restricted with the \\cmd{BLOCKS} command. If two or more\nelement variables are combined with an operator or are function\nparameters, the resulting variable is only defined for an element block\nif all the variables involved are defined for that block.\n\nWhen an operation or function is performed on an array variable, it is\nonly performed for the defined nodes/elements. This is done to prevent\nproblems with numerical errors such as divide by zero for undefined\nvalues.\n\n\\section{Constants}\n\nConstants can be entered in any legal \\caps{FORTRAN} numeric format\n(e.g., 5, 5.4 or 5.4E3). All integers are converted to real numbers. If\nthe constant is signed, parenthesis should surround the sign and\nconstant.\n\n\\section{Variables}\n\nThe variables that may be found in the expression to be evaluated are:\n\\setlength{\\itemsep}{\\smallskipamount} \\begin{itemize}\n\\item any input database global, nodal or element variable,\n\\item the values for any coordinate,\n\\item a reference to a specific nodal or element quantity,\n\\item the time associated with each time step, and\n\\item any previously assigned variable.\n\\end{itemize}\n\nIf an embedded blank is included in an input database variable or\ncoordinate name, the blank must be deleted in references to the\nvariable. For example, variable ``\\cmd{SIG X}'' must be entered as\n``\\cmd{SIGX}''.\n\nThe coordinates may be referenced in the expression by name. They are\ntreated as an input database nodal variable whose value remains constant\nin all ``whole'' time steps.\n\nIf the value for a specific node or element is desired, a ``\\cmd{\\$}''\nand the node or element number is appended to the variable name. For\nexample, \\cmd{SIGR\\$40} refers to the value for the \\nth{40}{th} element\nof variable \\cmd{SIGR}. A specifier may be appended to the name of any\nnodal or element quantity in an expression, including coordinates and\npreviously assigned variables. References to specific nodes and/or\nelements can only be made if the variable is defined at that node and/or\nelement.\n\nThe value of a variable in the previous time step is referenced by\nappending a ``\\cmd{:}'' to the variable name. The value in the first\ntime step is referenced by appending a ``\\cmd{:1}'' to the variable\nname. If time steps are selected, the previous and first time steps\nrefer to the selected time steps, not the input time steps.\n\nThe name ``\\cmd{TIME}'' is reserved for the time associated with each\ntime step. The output database times are copied from the input database\nunless a value is assigned to the variable \\cmd{TIME}. \\cmd{TIME} may also\nappear in the expression, referring to the input or assigned database\ntime.\n\nThe equations are evaluated in order. References to a variable name in\nthe expression refer to the last assigned value, or to the input\nvariable if the name has not been assigned. For example, if input global\nvariable \\cmd{CONST} has a value of 4 and the following equations are\nexecuted,\n\\cenlinesbegin\n\\cmd{X = CONST} \\\\\n\\cmd{CONST = 2$*$CONST} \\\\\n\\cmd{Y = CONST}\n\\cenlinesend\nthe result is \\cmd{X} equals 4, \\cmd{CONST} equals 8, and \\cmd{Y} equals\n8.\n\n\\section{Operators}\n\nThe legal operations are addition ($+$), subtraction ($-$),\nmultiplication ($*$), division ($/$), and exponentiation ($**$). The\noperands may be either single-value or array quantities as explained in\nSection~\\ref{assvar}.\n\n\\caps{FORTRAN} operator precedence rules apply (e.g., multiplication is\nperformed before addition). Parenthesis may be used to change the order\nof evaluation.\n\nTwo operators cannot be placed in succession. To precede a value with a\nsign, enclose the sign and value in parenthesis. For example,\n\\cenlinesbegin\n\\cmd{A = $-$5 $*$ $-$SIN(0.5)}\n\\cenlinesend\nshould be written as\n\\cenlinesbegin\n\\cmd{A = ($-$5) $*$ ($-$SIN(0.5))}\n\\cenlinesend\nwhere the parenthesis around the \\cmd{$-$5} are optional.\n\n\\section{Functions}\n\nMany of the standard \\caps{FORTRAN} functions and several special\nfunctions are implemented in \\caps{\\PROGRAM}. \nThese functions are summarized in Appendix~\\ref{appx:function}.\nThe parameters for any\nfunction may be expressions and all parameters must be supplied. The\nparameters may be either single-value or array quantities as explained\nin Section~\\ref{assvar}.\n\nA function in an equation is distinguished from a variable name by the\n``\\cmd{(}'' which follows the function name. This allows the user to\nassign variable names which are the same as the function names and to\nreference input database variables with the same names as the functions.\n\n\\subsection*{\\caps{FORTRAN} Functions}\n\nThe standard \\caps{FORTRAN} functions implemented are: \\cmd{AINT},\n\\cmd{ANINT}, \\cmd{ABS}, \\cmd{MOD}, \\cmd{SIGN}, \\cmd{DIM}, \\cmd{MAX},\n\\cmd{MIN}, \\cmd{SQRT}, \\cmd{EXP}, \\cmd{LOG}, \\cmd{LOG10}, \\cmd{SIN},\n\\cmd{COS}, \\cmd{TAN}, \\cmd{ASIN}, \\cmd{ACOS}, \\cmd{ATAN}, \\cmd{ATAN2},\n\\cmd{SINH}, \\cmd{COSH}, and \\cmd{TANH}. The use and result of these\nfunctions is the same as in \\caps{FORTRAN}, and the same restrictions\napply.\n\n\\subsection*{Tensor Principal Values and Magnitude Functions}\n\nFunctions \\cmd{PMAX} and \\cmd{PMIN} calculate the maximum and minimum\nprincipal values of a symmetric tensor. For example, to obtain the\nmaximum principal values for a tensor $T$,\n\\cenlinesbegin\n\\cmd{SMAX = PMAX ($T_{11}$, $T_{22}$, $T_{33}$, $T_{12}$, $T_{23}$,\n$T_{31}$)}.\n\\cenlinesend\nFor a two-dimensional tensor or a tensor using cylindrical coordinates\nfor an axisymmetric solution, \\cmd{PMAX2} and \\cmd{PMIN2} may be used:\n\\cenlinesbegin\n\\cmd{SMAX = PMAX2 ($T_{11}$, $T_{22}$, $T_{12}$)}.\n\\cenlinesend\n\nThe function \\cmd{TMAG} calculates the magnitude of the deviatoric part\nof a symmetric tensor. To calculate the magnitude of tensor $T$,\n\\cenlinesbegin\n\\cmd{SMAG = TMAG ($T_{11}$, $T_{22}$, $T_{33}$, $T_{12}$, $T_{23}$,\n$T_{31}$)}\n\\cenlinesend\nwhere the following calculation is made:\n\\cenlinesbegin\n\\cmd{SMAG = }$\\sqrt{(T_{11} - T_{22})^{2} + (T_{22} - T_{33})^{2} +\n(T_{33} - T_{11})^{2} + 6 * (T_{12}^{2} + T_{23}^{2} + T_{31}^{2})}$.\n\\cenlinesend\n\nTo obtain the von Mises stress, the value supplied by function\n\\cmd{TMAG} is multiplied by the constant $1/\\sqrt{2}$. To calculate\neffective strain, multiply by the constant $\\sqrt{2.0}/3.0$.\n\n\\subsection*{IF Functions}\n\nThe functions \\cmd{IFLZ}, \\cmd{IFEZ}, and \\cmd{IFGZ} provide a simple\n\\mbox{if-then-else} capability. Each function expects three parameters:\na condition, a true result, and a false result. Function \\cmd{IFLZ}\nreturns the true result if the condition evaluates to less than zero;\notherwise the function returns the false result. Function \\cmd{IFEZ}\nchecks for equal to zero and \\cmd{IFGZ} checks for greater than zero.\nFor example, the equation\n\\cenlinesbegin\n\\cmd{\\param{x} = IFLZ (\\param{cond}, \\param{rtrue}, \\param{rfalse})}\n\\cenlinesend\nwith global parameters \\param{cond}, \\param{rtrue}, and \\param{rfalse}\ncould be implemented in \\caps{FORTRAN} by\n\\cenlinesbegin\n\\cmd{IF (\\param{cond} .LT. 0.0) THEN} \\\\\n\\hspace*{\\myindent} \\cmd{\\param{x} = \\param{rtrue}} \\\\\n\\cmd{ELSE} \\\\\n\\hspace*{\\myindent} \\cmd{\\param{x} = \\param{rfalse}} \\\\\n\\cmd{END IF}\n\\cenlinesend\nAll the parameters are evaluated before the function, so both the true\nresult and the false result are evaluated even though only one is\nneeded.\n\n\\subsection*{Array $\\Rightarrow$ Global Variable Functions}\n\nThe functions \\cmd{SUM}, \\cmd{SMAX}, and \\cmd{SMIN} perform a\ncalculation on a nodal or element array parameter which produces a\nglobal result. \\cmd{SUM} sums all the array values. \\cmd{SMAX} and\n\\cmd{SMIN} return the maximum and minimum of all the array values.\n\nValues for specific nodes and/or elements are only included in the\nfunction calculation if the variable is defined at that node and/or\nelement.\n\n\\subsection*{Envelope Functions}\n\nAn ``envelope'' function performs a calculation that is cumulative for\nall previous time steps. The function \\cmd{ENVMAX} results in an array\n(assuming the parameter is an array) that is the maximum of each array\nvalue for all previous selected time steps and the current time step. On\nthe last time step, \\cmd{ENVMAX} contains the maximum of each array\nvalue for all selected time steps. \\cmd{ENVMIN} is the corresponding\nminimum function.\n", "meta": {"hexsha": "b9bb894242518d79ced68aa46b365832f458ad4f", "size": 12080, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "packages/seacas/doc-source/algebra/algeqn.tex", "max_stars_repo_name": "jschueller/seacas", "max_stars_repo_head_hexsha": "14c34ae08b757cba43a3a03ec0f129c8a168a9d3", "max_stars_repo_licenses": ["Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "NetCDF", "BSL-1.0", "X11", "BSD-3-Clause"], "max_stars_count": 82, "max_stars_repo_stars_event_min_datetime": "2016-02-04T18:38:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T03:01:49.000Z", "max_issues_repo_path": "packages/seacas/doc-source/algebra/algeqn.tex", "max_issues_repo_name": "jschueller/seacas", "max_issues_repo_head_hexsha": "14c34ae08b757cba43a3a03ec0f129c8a168a9d3", "max_issues_repo_licenses": ["Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "NetCDF", "BSL-1.0", "X11", "BSD-3-Clause"], "max_issues_count": 206, "max_issues_repo_issues_event_min_datetime": "2015-11-20T01:57:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:12:04.000Z", "max_forks_repo_path": "packages/seacas/doc-source/algebra/algeqn.tex", "max_forks_repo_name": "jschueller/seacas", "max_forks_repo_head_hexsha": "14c34ae08b757cba43a3a03ec0f129c8a168a9d3", "max_forks_repo_licenses": ["Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "NetCDF", "BSL-1.0", "X11", "BSD-3-Clause"], "max_forks_count": 68, "max_forks_repo_forks_event_min_datetime": "2016-01-13T22:46:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T06:25:05.000Z", "avg_line_length": 42.8368794326, "max_line_length": 74, "alphanum_fraction": 0.7638245033, "num_tokens": 3097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3062538502961012}}
{"text": "\\chapter{Introduction}\nIn this paper the nonhomogenous Poisson process is used to generate data and conditional samples from sufficient statistics. The nonhomogenous Poisson process is a combination of the power law case and log-linear case. To generate the samples a Monte Carlo approach is used. The approach is a Gibbs sampler with a Metropolis-Hastings step. \n\\\\\n\\\\\nThe hypothesis test theory is used to check if the samples comes from the right distribution. This is the null hypothesis. To check the null hypothesis several condtional tests are used. The conditional tests are generated by simulation of conditional samples. These samples are conditional on minimum sufficent statistics.\n\\\\\n\\\\\nThe motivation for this study comes from the papers \\cite{lindqvist2011monte} and \\cite{lockhart2007use}. In the first paper two types of NHPP were studied. The first one was a case of log-linear rate function, and the second case was the log-linear case. The paper proposed to look at a NHPP where these cases were combined. The second paper is about conditional sampling from a gamma distribution\\cite{stacy1962generalization}. In this paper the same sufficient statistics were used.\n\\\\\n\\\\\nFirst the paper is going to introduce the nonhomogenous Poisson process. Further necessary theory and the sampling algorithm is introduced. At the end the results and analysis of the simulations are presented.", "meta": {"hexsha": "9301205c5742b05f19081a7d641a3cd4d26c0beb", "size": 1401, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Thesis/chapters/introduction.tex", "max_stars_repo_name": "mariufa/ProsjektOppgave", "max_stars_repo_head_hexsha": "3ef2fda314c55322de20f19ca861e4268a5e2d08", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Thesis/chapters/introduction.tex", "max_issues_repo_name": "mariufa/ProsjektOppgave", "max_issues_repo_head_hexsha": "3ef2fda314c55322de20f19ca861e4268a5e2d08", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Thesis/chapters/introduction.tex", "max_forks_repo_name": "mariufa/ProsjektOppgave", "max_forks_repo_head_hexsha": "3ef2fda314c55322de20f19ca861e4268a5e2d08", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 127.3636363636, "max_line_length": 485, "alphanum_fraction": 0.8137044968, "num_tokens": 292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3062538502961012}}
{"text": "\\title{Overlapping Group Lasso Via ADMM in Python}\n\\author{Daniel Kessler}\n\n\\documentclass{article}\n\n% \\usepackage{parskip}\n\\usepackage{geometry}\n\\usepackage{amsmath,amssymb,physics,framed,mathtools}\n\\usepackage{algorithm,algpseudocode}\n\\usepackage{graphicx}\n\\usepackage[utf8]{inputenc}\n\\usepackage[style=numeric,citestyle=numeric]{biblatex}\n\\addbibresource{refs.bib}\n\n\\AtEveryBibitem{\n    \\clearfield{urlyear}\n    \\clearfield{urlmonth}\n}\n\n\\usepackage{hyperref}\n\\begin{document}\n\n\\maketitle\n\n\\begin{abstract}\n  In this report, we present a brief summary of the overlapping group lasso, showing how it can be motivated as an extension first of the regular lasso to a group setting, and then as a further generalization thereof.\n  We then provide some background on the Alternating Direction Method of Multipliers (ADMM) algorithm, and show why it is a reasonable choice for solving overlapping group lasso problems.\n  Next, we derive the ADMM algorithm for overlapping group lasso, and present a software implementation in python that implements this algorithm.\n  Finally, we show some experimental results on synthetic data across a variety of parameter settings.\n\\end{abstract}\n\n\\section{Notation}\n\\label{sec:notation}\n\nFirst, we fix notation.\nSince much of our derivations are based on \\cite{boyd_distributed_2011}, we will use different notation than is typically deployed in more statistics-oriented treatments of the lasso.\nLet $A \\in \\mathbb{R}^{m \\times n}$ be a (fixed) design matrix, with $m$ observations and $n$ covariates, and $b \\in \\mathbb{R}^m$ a vector of observations.\nWe assume that our $b$ follows $b = A x^{\\star} + \\epsilon$, where $x^{\\star} \\in \\mathbb{R}^p$ is an unknown weight vector, and $\\epsilon$ are independent and identically distributed errors (for a simple case, we can take them to follow $\\mathcal{N}(0,\\sigma^2)$ for some fixed, but unknown, $\\sigma^2$).\nWhen norms are not otherwise specified, they are taken to be the 2-norm, i.e., $\\lVert \\cdot \\rVert \\overset{\\Delta}{=} \\lVert \\cdot \\rVert_2$.\nWe will generally be interested in minimizing the least squares loss, i.e., finding $\\hat{x} \\in \\operatorname{argmin}_x \\left\\| Ax - b \\right\\|$.\nNote: A great deal of the treatment below, including that of the lasso, group lasso, overlapping group lasso, and ADMM is taken from \\cite{boyd_distributed_2011}.\nWe explicitly cite this text at key points, but we do not cite \\emph{every} claim which is based on \\cite{boyd_distributed_2011} to avoid cluttering the text.\n\n\\section{Background: Overlapping Group Lasso}\n\\label{sec:backgr-group-lasso}\nIn order to introduce the overlapping group lasso, we will first discuss the regular lasso and then show how it can be extended to the (non-overlapping) group lasso setting.\nThe lasso is a highly popular method that is especially useful in high dimensional settings, i.e., where $n \\gg m$.\nIn this setting (presuming $A$ is of full rank), the OLS estimate is no longer uniquely determined, as there exist infinitely many candidate $\\hat{x}$ that yield zero loss.\nInstead, one can instead minimize a \\emph{regularized problem} in order to obtain a \\emph{sparse solution}.\nWhile various (essentially equivalent) formulations of the lasso objective exist, for our purposes we will define the primal lasso problem as\n\\begin{equation}\n  \\label{eq:1}\n  \\operatorname*{min}_x \\frac{1}{2} \\lVert Ax - b \\rVert_2^2 + \\lambda \\lVert x \\rVert_1,\n\\end{equation}\nwhere $\\lambda > 0$ determines the amount of regularization.\nAs $\\lambda \\to 0$, we see that \\eqref{eq:1} becomes the OLS problem, and as $\\lambda \\to \\infty$, $x \\to 0$.\nOne advantage of the lasso is that it will typically recover a sparse solution, i.e., a solution where the minimizing $\\hat{x}$ has many entries that are identically 0.\n\nIn the setting where covariates can be organized into groups, as may be natural in many applied settings (e.g., where the covariates are gene expression levels, and genes can be organized based on chromosome or location), we may wish not to simply select useful covariates, but instead to select useful \\emph{groups} of covariates.\nThis motivates the use of \\emph{group lasso} \\cite{yuan_model_2006}, where we replace the objective in \\eqref{eq:1} with\n\\begin{equation}\n  \\label{eq:2}\n  \\operatorname*{min}_x \\frac{1}{2} \\lVert Ax - b \\rVert_2^2 + \\lambda \\sum_{i=1}^N \\lVert x_i \\rVert_2,\n\\end{equation}\nwhere $x_i$ is a sub-vector of $x$ containing only the coefficients corresponding to the $i$'th group, with $i \\in [N]$.\nNote that when extending to the group lasso, the penalty term no longer involves the 1-norm but instead has the 2-norm.\nAlthough this may seem surprising, the 1-norm is separable, i.e., $\\left\\| \\begin{pmatrix} a_1 \\\\ a_2 \\end{pmatrix} \\right\\|_1 = \\lVert a_1 \\rVert_1 + \\lVert a_2 \\rVert_1$, and this would devolve back to the original lasso.\nCritically, the 2-norm in the regularizer is not squared, which yields an analogous geometry to the lasso, with singularities corresponding to solutions that are group-sparse (see \\cite{yuan_model_2006}, Fig 1 for a helpful illustration of this phenomena).\nNote that for a singleton vector, $\\lVert a \\rVert_1 = \\lVert a \\rVert_2$, so when $N = n$, i.e., each feature is alone in its own atomic group, we can rewrite \\eqref{eq:2} as\n\\begin{align*}\n  \\operatorname*{min}_x \\frac{1}{2} \\lVert Ax - b \\rVert_2^2 + \\lambda \\sum_{i=1}^N \\lVert x_i \\rVert_2 \n  &= \\operatorname*{min}_x \\frac{1}{2}  \\lVert Ax - b \\rVert_2^2 + \\lambda \\sum_{i=1}^N \\lVert x_i \\rVert_1 \\\\\n  &= \\operatorname*{min}_x \\frac{1}{2} \\lVert Ax - b \\rVert_2^2 + \\lambda  \\lVert x \\rVert_1    ,\n\\end{align*}\nand we can recover the original lasso formulation in \\eqref{eq:1} as a special case of the group lasso.\n\nFinally, the \\emph{group lasso} can be further extended to accommodate \\emph{overlapping groups} in the ``overlapping group lasso'' \\cite{zhao_composite_2009,mairal_network_2010}.\nIn this setting, rather than partitioning $x$ into disjoint sub-vectors, we let $G_i, i = [N]$ be an index set holding the indices of coefficients corresponding to the $i$'th group, i.e., $x_{G_i}$ is a vector of coefficients for group $i$, $x_{G_j}$ is a vector of coefficients for group $j$, and it may be the case that $G_i \\cap G_j \\neq \\emptyset$.\nAs a toy example, suppose $n=3$, and in this simple setting we have two groups, with $G_1 = \\left\\{ 1, 2 \\right\\}, G_2 = \\left\\{ 2, 3 \\right\\}$, such that $x_2$ is common to both $x_{G_1}$ and $x_{G_2}$, i.e., $G_1 \\cap G_2 = \\left\\{ 2 \\right\\}$.\nIn this setting, the overlapping group lasso objective is given by\n\\begin{equation}\n  \\label{eq:3}\n  \\operatorname*{min}_x \\frac{1}{2} \\lVert Ax - b \\rVert_2^2 + \\lambda \\sum_{i=1}^N \\lVert x_{G_i} \\rVert_2.\n\\end{equation}\nOf course, the (non-overlapping) group lasso discussed above is a special case of the overlapping group lasso, and by transitivity, since lasso is a special case of the group lasso, it is also a special case of the overlapping group lasso.\n\nThe geometry of this problem is rather complicated, and there is some work (e.g., \\cite{jacob_group_2009}) that proposes addressing the overlapping group lasso through latent variables, in essence, performing variable duplication to render the problem non-overlapping, and then using the standard group lasso formulation in \\eqref{eq:2} to solve the problem.\nHowever, in the present work we will focus on directly optimizing the objective given in \\eqref{eq:3}, although as we shall see in Section \\ref{sec:group-lasso-via}, our algorithmic approach will involve a sort of variable duplication, but with an update step that pulls our duplicated variables back toward one another.\n\n\\section{Background: ADMM}\n\\label{sec:background:-admm}\nThe Alternating Direction Method of Multipliers (ADMM) is an algorithmic approach to optimization well suited to solving problems that can be decomposed as the sum of two problems in distinct variables, subject to linear constraints.\nThe background we provide here will closely follow \\cite{boyd_distributed_2011}, as this was our primary resource when endeavoring to learn the material.\nOur development here will be terse and limited, and we refer the reader to \\cite{boyd_distributed_2011}, as the exposition given below chiefly consists of key highlights from this very useful text.\n\nADMM is formulated to solve problems structured as\n\\begin{equation}\n  \\begin{aligned}\n    \\label{eq:4}\n    \\operatorname*{min}_{x,z} \\qquad &f(x) + g(z) \\\\\n    \\text{subject to} \\qquad&Ax + Bz = c\n  \\end{aligned}.\n\\end{equation}\nIt is closely related to the method of multipliers (a brief background is given in \\cite{boyd_distributed_2011}) and proceeds by first constructing an augmented Lagrangian\n\\begin{equation}\n  \\label{eq:5}\n  L_{\\rho}(x,z,y) = f(x) + g(z) + y^T (Ax + Bz - c) + \\frac{\\rho}{2} \\lVert Ax + Bz - c \\rVert_2^2,\n\\end{equation}\nwhere $y$ is a dual variable, and the last term is the ``augmenting'' piece.\nAlthough augmenting may seem unnatural at first, we note that when the linear constraints are satisfied, this last term is identically 0 and thus inconsequential for the objective function at the optimum, and its inclusion makes the use of the \\texttt{prox} operator natural during the optimization.\nADMM is an iterative procedure, which given some initial values for $x,z,y$, proceeds as\n\\begin{align}\n  \\label{eq:6}\n  x^{k+1} &\\leftarrow \\operatorname*{argmin}_x L_{\\rho}(x,z^k,y^k) \\\\\n  \\label{eq:7}\n  z^{k+1} &\\leftarrow \\operatorname*{argmin}_x L_{\\rho}(x^{k+1},z,y^k) \\\\\n  \\label{eq:8}\n  y^{k+1} &\\leftarrow y^k + \\rho(Ax^{k+1} + Bz^{k+1} -c).\n\\end{align}\nOf course, the rub lies in actually solving the sub-problems given in \\eqref{eq:6}\\eqref{eq:7}, but using the augmented Lagrangian $L_{\\rho}$ makes this tractable for certain problems.\n\n\\section{Overlapping Group LASSO Via ADMM}\n\\label{sec:group-lasso-via}\nThere is treatment of lasso, group lasso, and (very brief) mention of overlapping group lasso in \\S 6.4 of \\cite{boyd_distributed_2011}.\nWe noted in Section \\ref{sec:backgr-group-lasso} that the group lasso, and in turn lasso, can be recovered as special cases of the overlapping group lasso.\nHowever, \\cite{boyd_distributed_2011} attempts to make (both overlapping and non-overlapping) group lasso notationally consistent with their later section on consensus learning, which actually yields an algorithm that does not permit recovery of these simpler forms as special cases, since the roles of $x$ and $z$ are reversed.\nIn our treatment here, we have eschewed this notational change and describe an approach that connects more naturally to lasso.\n\n\n\nOur goal is to rewrite \\eqref{eq:3} in a form amenable to application of ADMM but that is still equivalent to the original optimization problem.\nIn a similar spirit to the ``latent'' approach to overlapping group lasso \\cite{jacob_group_2009,obozinski_group_2011}, we will create many \\emph{new} variables which in a strict sense do not overlap, but then use linear equality constraints to impose the requirement that their relevant components coincide via a common ``anchoring'' global variable, which will indirectly enforce equality in the shared components.\nIn particular, we rewrite \\eqref{eq:3} as,\n\\begin{equation}\n  \\begin{aligned}\n  \\label{eq:9}\n  \\operatorname*{min}_{x,z_i, i \\in [N]} \\quad &\\frac{1}{2} \\lVert A x - b \\rVert_2^2 + \\lambda \\sum_{i=1}^N \\lVert z_i \\rVert_2 \\\\\n  \\text{such that} \\quad & \\tilde{x}_i - z_i = 0, \\quad \\forall i \\in [N]\n  \\end{aligned},\n\\end{equation}\nwhere $\\tilde{x}_i \\overset{\\Delta}{=} x_{G_i}$, i.e., the components of $x$ corresponding to group $i$ for $i \\in [N]$, and the constraint ensures that the solution satisfies $z_i = x_{G_i}, z_i \\in \\mathbb{R}^{\\left| G_i \\right|}$\nThis is now in a form compatible with ADMM, where the second term is analogous to $g(z)$, where $z$ is the concatenation of all the $z_i$'s, and $g$ very naturally decomposes across the $z_i$, which permits the update of the $z_i$ to be done in parallel.\n\nNow, our task is to give explicit forms for steps \\eqref{eq:6}\\eqref{eq:7}.\nOur update can be performed as\n\\begin{align}\n  \\label{eq:11}\n  x^{k+1} &\\leftarrow (A^TA + \\rho I)^{-1}(A^T b + \\rho(\\bar{z}^{k+1} - \\bar{u}^k)) \\\\\n  \\label{eq:10}\n  z_i^{k+1} &\\leftarrow \\operatorname*{argmin}_{z_i} (\\lambda \\lVert z_i \\rVert_2 + \\left( u_i^k \\right)^T(z_i - \\tilde{x}_i^k) + \\frac{\\rho}{2} \\lVert z_i - \\tilde{x}_i^k \\rVert_2^2) \\\\\n  \\label{eq:12}\n  u_i^{k+1} &\\leftarrow u_i^k +  \\tilde{x}_i^{k+1} - z_i^{k+1},\n\\end{align}\nwhere $\\bar{z}, \\bar{u}$ are obtained by averaging over $z_i, u_i$ at the relevant components.\nThe operation at \\eqref{eq:10} is precisely the proximal operator, which for group lasso is the vector soft thresholding operation, as given in \\S 6.4.2 of \\cite{boyd_distributed_2011}, i.e.,\n\\begin{equation}\n  \\label{eq:13}\n  z_i^{k+1} = (1 - \\frac{\\lambda}{\\rho} \\lVert \\tilde{x}_i^{k+1} + u^k \\rVert_2^{-1})_+ (\\tilde{x}_i^{k+1} + u^k)\n\\end{equation}\n\nWe summarize the approach in Algorithm \\ref{alg:grp-lasso-admm}.\n\\begin{algorithm}\n    \\caption{Overlapping Group LASSO Via ADMM}\n    \\label{alg:grp-lasso-admm}\n    \\begin{algorithmic}[1]\n      \\Require{$A, b, x^0 \\in \\mathbb{R}^n, \\rho, \\lambda, G$}\n      \\State $Q \\gets (A^TA + \\rho I)^{-1}$\n      \\For{$i \\in [N]$}\n      \\State $z_i \\gets x^0_{G_i}$\n      \\State $u_i \\gets \\left\\{ 0 \\right\\}^{\\lvert G_i \\rvert}$\n      \\EndFor\n      \\State $k \\gets 0$ \n      \\While{not converged}\n      \\State $x^{k+1} \\gets Q \\left( A^Tb + \\rho(\\bar{z}^{k+1} - \\bar{u} \\right)$\n      \\For{$i \\in [N]$}\n      \\State $z_i^{k+1} \\gets S_{\\lambda/\\rho}(\\tilde{x}_i^{k+1} + u_i)$\n      \\EndFor\n      \\For{$i \\in [N]$}\n      \\State $u_i^{k+1} \\gets u_i^k + \\tilde{x}_i^{k+1} - z_i^{k+1} $\n      \\EndFor      \n      \\State $k \\gets k+1$\n      \\EndWhile\n  \\end{algorithmic}\n\\end{algorithm}\n\n\\section{Software Implementation}\n\\label{sec:implementation}\nWe implemented the procedure of Algorithm \\ref{alg:grp-lasso-admm} in python 3.7.\nThe implementation, along with this report, is available on github at \\url{http://github.com/dankessler/608a-project}.\nThe dependency environment can be reconstructed using \\href{https://pipenv.readthedocs.io/en/latest/}{\\texttt{pipenv}} using the \\texttt{Pipfile} and \\texttt{Pipfile.lock} found at the root of the repository.\n\n\\section{Experimental Results}\n\\label{sec:experimental-results}\nWe conducted numerical experiments in simulated data.\nA script named \\texttt{simulations.py} reproducing these results is available on github in the root directory of our repository \\url{http://github.com/dankessler/608a-project}.\nWe generate synthetic data as $y = A x^{\\star} + \\epsilon$, where $\\epsilon \\sim \\mathcal{N}_m(0,I_m), A \\in \\mathbb{R}^{m \\times n}$ is a random matrix with iid standard normal entries, and for all simulations we fix $m = 50, n = 100$.\nOur three experiments below are under different settings for $x^{\\star}$.\nIn each case, we run our implementation of Algorithm \\ref{alg:grp-lasso-admm} on the synthetic data with $\\rho = 1$ and vary $\\lambda$ over a logarithmic grid.\nEach evaluation yields a regularized estimate $\\hat{x}$, and with this we evaluate\n\\begin{enumerate}\n\\item The prediction error: $\n  \\left\\|\n    A x^{\\star} - A \\hat{x}\n  \\right\\|_2$\n\\item The accuracy of the estimated $x$: $\n  \\left\\|\n    x^{\\star} - \\hat{x}\n  \\right\\|_2$\n\\item The precision of the recovery of the support: $\\frac{\n    \\left|\n      \\left\\{\n        i: \\hat{x}_i \\neq 0\n      \\right\\}\n      \\cap\n      \\left\\{\n        j: x^{\\star}_j \\neq 0\n      \\right\\}\n    \\right|}{\n    \\left\\|\n      \\hat{x}\n    \\right\\|_0}$\n\\item The recall of the recovery of the support: $\\frac{\n    \\left|\n      \\left\\{\n        i: \\hat{x}_i \\neq 0\n      \\right\\}\n      \\cap\n      \\left\\{\n        j: x^{\\star}_j \\neq 0\n      \\right\\}\n    \\right|}{\n    \\left\\|\n      x^{\\star}\n    \\right\\|_0}$\n\\end{enumerate}\nBecause the $x$ iterates in our algorithm never become \\emph{truly} sparse, as a heuristic after returning $\\hat{x}$ for a fixed number of iterations (here one thousand) we set to 0 any entries of $\\hat{x}$ with magnitude smaller than $\\epsilon = .01$.\nThis enables more meaningful interpretation for the latter two metrics (since otherwise the set of components of $\\hat{x}$ that are nonzero will be all $n$.\nThese results are depicted graphically as a function of $\\lambda$ in Figures \\ref{fig:lasso}, \\ref{fig:glasso}, and \\ref{fig:oglasso}.\n\n\n\\subsection{Lasso as a Special Case}\n\\label{sec:lasso-as-special}\nAs discussed earlier, if we place each covariate into its own atomic group, our problem devolves to the classic lasso.\nWe set $x_i^{\\star} = 10$ for $i \\in [25]$, and $x_i^{\\star} = 0$ for $i \\in [50] \\setminus [25]$.\nWe conduct the simulation approach as described above, and display our results in Figure \\ref{fig:lasso}.\n\n\n\\begin{figure}[h]\n  \\centering\n  \\includegraphics[width=\\textwidth]{../lasso}\n  \\caption{Performance metrics for simulations under lasso. Larger values of $\\lambda$ generally encourage a sparser solution, which seems to yield worse prediction error, estimation error, and recall in recovery of support. Precision initially improves, but this is likely due to a shrinking denominator.}\n  \\label{fig:lasso}\n\\end{figure}\n\n\n\n\n\\subsection{Non-overlapping Group Lasso as a Special Case}\n\\label{sec:non-overl-group}\nOur set up for (non-overlapping) group lasso is reasonably straightforward.\nWe construct two disjoint groups as $G_1 = [25], G_2 = [50] \\setminus G_1$.\nWe set $x^{\\star}_i = 10$ for $i \\in G_1$, and $x^{\\star}_i = 0$ for $i \\in G_2$.\nNote that this is the same $x^{\\star}$ as in lasso above, but the penalization is different.\nThe results are presented in Figure \\ref{fig:glasso}.\n\n\\begin{figure}[h]\n  \\centering\n  \\includegraphics[width=\\textwidth]{../glasso}\n  \\caption{Performance metrics for simulations under (non-overlapping) group lasso. These plots are reasonably similar to those in Figure \\ref{fig:lasso}, which is unsurprising since the problem set up is very similar.}\n  \\label{fig:glasso}\n\\end{figure}\n\n\\subsection{Overlapping Group Lasso}\n\\label{sec:overl-group-lasso}\nFor overlapping group lasso, we construct 9 groups of equal size that overlap by the same amount.\nIn particular, $G_i = \\{5(i-1) + j : j \\in [10]\\}, i \\in [9]$.\nFor example, $G_1 = \n\\left\\{\n  1, 2, 3, 4, 5, 6, 7, 8, 9, 10\n\\right\\}$, $G_2 = \n\\left\\{\n  6, 7, 8, 9, 10, 11, 12, 13, 14, 15\n\\right\\}$, so $G_1 \\cup G_2 = \n\\left\\{\n  6, 7, 8, 9, 10\n\\right\\}$.\nAs was discussed briefly earlier, our formulation of the overlapping group lasso, unlike that in \\cite{jacob_group_2009,obozinski_group_2011}, has singularities corresponding to the complement of unions of groups.\nFor this reason, we set $x^{\\star}_i = 10$ for $i \\in \n\\left\\{\n  1, 2, 3, 4, 5, 16, 17, 18, 19, 20\n\\right\\}$ and 0 otherwise.\nThis corresponds to the complement of the union of groups $G_2, G_3, G_5, G_6, G_7, G_8$,  and $G_9$.\nResults are presented in Figure \\ref{fig:oglasso}.\n\n\\begin{figure}[h]\n  \\centering\n  \\includegraphics[width=\\textwidth]{../oglasso}\n  \\caption{Performance metrics for simulations under overlapping group lasso.\nAs with all our results, increasing $\\lambda$ hurts prediction error. Also, we can infer that we require high values of $\\lambda$  before we obtain solutions that are at all sparse, and this is why recall is initially so high. In terms of estimation error, extreme values of $\\lambda$ (too big or too small) give poor performance, but things are quite good in the middle.}\n  \\label{fig:oglasso}\n\\end{figure}\n\n\\section{Conclusion and Future Directions}\n\\label{sec:concl-future-direct}\nIn this report, we provided a brief introduction to overlapping group lasso, reviewed requisite background materials on ADMM, and then showed how ADMM could be applied to the overlapping group lasso problem.\nWe then conducted numerical experiments on simulated data under three different settings: lasso as a special case of overlapping group lasso, (non-overlapping) group lasso as a special case of overlapping group lasso, and finally a non-trivial overlapping group lasso problem.\nOne important note is that our approach is in contrast to one favored by some statisticians \\cite{obozinski_group_2011,jacob_group_2009}.\nThe reason for this is that the explicit formulation of the overlapping group lasso, as we have implemented, \nis well positioned for recovery in settings where the true support is the complement of a union of groups.\nConceptually, this corresponds to ``deactivating'' a set of groups, and zeroing out all of their corresponding features, which in the case of overlaps, will result in some ``active'' groups only being active in components that are not shared with a deactivated group.\nIn some applied settings this may be a reasonably accurate regime, but in settings where it is more natural to countenance the support being the union of \\emph{active} groups, an alternative formulation, described in \\cite{obozinski_group_2011,jacob_group_2009}, proposes that variables be duplicated to render the problem non-overlapping, but does \\emph{not} involve the introduction of linear constraints that require that corresponding entries perfectly match.\nThis effectively renders the problem non-overlapping.\nFor some of the applied settings in neuroscience where we propose to use our newly developed overlapping group lasso package in python, this latter formulation is more natural.\nHowever, the good news is that since we have demonstrated that our approach can solve \\emph{both} of these problems, as the latter is a special case of the former, the software that we have developed in this project can be used directly (with some wrapper functionality to handle the bookkeeping involved in variable duplication).\n\nAs a next step, we plan to validate the performance of our implementation against a reference implementation.\nWhile there exist many implementations of lasso and a few implementations of non-overlapping group lasso, we have yet to find a overlapping group lasso implementation that seems to give sensible results.\nNonetheless, if we can validate our implementation against the simpler cases, we may be able to use our package as a benchmark against this other implementations to better understand their shortcomings.\n\n\\clearpage\n\\printbibliography\n\n\\end{document}\n\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: t\n%%% End:\n\n%  LocalWords:  ADMM covariates argmin OLS eq th regularizer Bz prox\n%  LocalWords:  notationally notational thresholding github pipenv py\n%  LocalWords:  Pipfile iid covariate neuroscience\n", "meta": {"hexsha": "85cc2a6bf2d83d76437d00d5717fbf8319f64dd6", "size": 22525, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/kesslerd-stats608a-project-report.tex", "max_stars_repo_name": "dankessler/608a-project", "max_stars_repo_head_hexsha": "6586cfd820485fcb7ba87d60c669650f67da96d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "report/kesslerd-stats608a-project-report.tex", "max_issues_repo_name": "dankessler/608a-project", "max_issues_repo_head_hexsha": "6586cfd820485fcb7ba87d60c669650f67da96d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/kesslerd-stats608a-project-report.tex", "max_forks_repo_name": "dankessler/608a-project", "max_forks_repo_head_hexsha": "6586cfd820485fcb7ba87d60c669650f67da96d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 67.4401197605, "max_line_length": 463, "alphanum_fraction": 0.7350499445, "num_tokens": 6596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.30625385029610114}}
{"text": "\\documentclass[a4paper]{siamart190516}\n\n\\usepackage{damacros}\n\n% PACKAGES added by TB\n% PACKAGES FOR ALGORITHMS (PSEUDO-CODE)\n\\usepackage{algorithm}\n\\usepackage{algorithmic}\n\n% Sets running headers as well as PDF title and authors\n\\headers{Coupling intra-cellular and multi-cellular dynamics in spatially-extended models of root-hair initiation}{D. Avitabile, S. Perotto, N. Ferro, T. Babini}\n\n% Title. If the supplement option is on, then \"Supplementary Material\"\n% is automatically inserted before the title.\n\\title{Coupling intra-cellular and multi-cellular dynamics in spatially-extended models of root-hair initiation}\n\n% Authors: full names plus addresses.\n\\author{%\n  Daniele Avitabile%\n  \\thanks{%\n    Vrije Universiteit Amsterdam,\n    Department of Mathematics,\n    Faculteit der Exacte Wetenschappen,\n    De Boelelaan 1081a,\n    1081 HV Amsterdam, The Netherlands.\n  \\protect\\\\\n    Inria Sophia Antipolis M\\'editerran\\'ee Research Centre,\n    MathNeuro Team,\n    2004 route des Lucioles-Boîte Postale 93 06902,\n    Sophia Antipolis, Cedex, France.\n  \\protect\\\\\n    (\\email{d.avitabile@vu.nl}, \\url{writemywebpage}).\n  }\n %  .... mancano altri\n  % \\and\n%   Paul T. Frank \\thanks{Department of Applied Mathematics, Fictional University, Boise, ID\n% (\\email{ptfrank@fictional.edu}, \\email{jesmith@fictional.edu}).}\n% \\and Jane E. Smith\\footnotemark[3]\n}\n\n\\begin{document}\n\n\\maketitle\n\n\\begin{abstract}\nThis thesis deals with novel models and numerical approximations of spatially-extended multi-cellular models of Rho Of Plants (ROPs), that is, a family of proteins responsible for root-hair initiation in the plant cell Arabidopsis thaliana. The study of this dynamical system is of great relevance in the so-called agriculture 4.0, since it is instrumental to optimise plant uptake. In particular, ascertaining how intra-cellular protein distributions and extra-cellular coupling influence root-hair initiation is a challenging but pressing problem.\n\nCurrent studies have focussed on two separate model types: on the one hand, ROPs dynamics is studied in single-cell models, which resolve patterns at sub cellular level; on the other, multi- cellular models with realistic geometries neglect intra-cellular patterning. In this thesis we make progress on coupling these two\nmodel descriptions.\n\nWe initially focus on a well-established single-cell, nonlinear reaction-diffusion model, here approximated for the first time with a finite-element scheme. In addition, we present a new model which couples multiple cells through ROP flux at the interface. We present numerical evidence that such coupling has a bearing on the patterns supported by the model. It is shown that, under variations of auxin gradients, the model robustly forms ROP hotspots from ROP stripes, and that spots are later advected downstream.\n\nFinally, we consider a novel model in which the auxin dynamics are not prescribed, but derive from the interaction between this hormone and other membranals proteins (PIN). We show that self-sustained auxin oscillations influence ROP intracellular patterning.\n\\end{abstract}\n\n\\section{Introduction (Daniele+Teresa+Simona)}\n\nmettere il modello Capitolo 4 (solo equazioni) +  posizionamento in\nletteratura + novelty paper\n\n% from chapter 4 physical model sec.\n\nthe dynamics of auxin and carriers proteins PIN in each cell $\\Omega_i$ with $i \\in \\{ 1, ..., N \\}$ can be written as the following system of coupled ordinary differential equations:\n\\begin{equation}\\begin{aligned}\n\\begin{cases}\n  {\\displaystyle d a_i\\over\\displaystyle d t} & = {\\displaystyle 1 \\over \\displaystyle V_i} \\sum_{j=1}^{N} A_{ij} \\Phi_{ij} +k - \\delta a_i \\\\[8pt]\n  {\\displaystyle d \\Tilde{P}_{ij}\\over\\displaystyle d t} & = h\\left(\\Phi_{ij}\\right) + \\rho_0 - \\mu \\Tilde{P}_{ij},\n\\end{cases}\n\\end{aligned} \\end{equation}\n\n% ...\n\nThe original system of equations can be rescaled and simplified. In particular, under the assumptions of cells having same volume $V =V_i$ and exchange surface areas $A = A_{ij}$, rescaling properly the diffusion coefficient $D_a$ and variables $P_{ij}$, a new system is obtained. Thus, the final system of equations we work on is:\n\\begin{equation}\\label{eq:Sys_auxPIN}\\begin{aligned}\n\\begin{cases}\n  {\\displaystyle d a_i\\over\\displaystyle d t} & = \\sum_{j \\in \\mathcal{N}_i} \\displaystyle \\Phi_{ji} +k - \\delta a_i \\\\[8pt]\n  {\\displaystyle d P_{ij}\\over\\displaystyle d t} & = h\\left(\\Phi_{ij}\\right) - \\mu P_{ij},\n\\end{cases}\n\\end{aligned} \\end{equation}\n\n% ... from chapter 2 sec physical model\nThe dimentional reaction-diffusion model summarizing binding process, autocatalytic activation and catalysis of ROPs proteins described in Section \\ref{sec:intromodel} is formulated as follows:\n% As mentioned before, the dimentional reaction-diffusion model is:\n\\begin{equation} \\label{eq:FM}\\begin{aligned}\n\\left\\lbrace\n\\begin{matrix}\n\\partial_t u = & D_1 \\Delta_s u + k_{20} \\alpha(x,y)u^2 v - \\left(c+r\\right) u + k_1 v  & \\ \\text{in} \\ \\Omega\\\\\n    \\partial_t v = & D_2 \\Delta_s v - k_{20} \\alpha(x,y) u^2 v - k_1 v + c \\ u + b   & \\ \\text{in} \\ \\Omega.\n\\end{matrix}\n\\right.\n\\end{aligned}\\end{equation}\n\n% ...\nThe RD system is rewritten to explicit its mathematical formulation and methods in order to solve it in the most general way, including both the case of the RD system with the original parameters and the RD system with the rescaled ones.\n\nAs a consequence, we define a unified system of equations comprehensive of both \\eqref{eq:FM} and \\eqref{eq:adim} systems:\n\\begin{equation} \\label{eq:final}\n\\left\\lbrace\n\\begin{matrix}\n\\partial_t u = & \\Tilde{D_1} \\Delta_s u + \\Tilde{a_1} u + \\Tilde{b_1} v + \\Tilde{c_1} u^2 v \\ \\ \\text{in} \\ \\Omega\\\\\n\\partial_t v = & \\Tilde{D_2} \\Delta_s v + \\Tilde{a_2} v + \\Tilde{b_2} u + \\Tilde{c_2} u^2 v + f_2 \\ \\ \\text{in} \\ \\Omega,\n\\end{matrix}\n\\right.\n\\end{equation}\nwith tilde parameters defined differently in the two cases under study\n\n\\section{A starting modeling  (Teresa+Daniele)}\n\nModello di Capitolo 3\n\n\\textbf{Physical model - Sec.3.1}\nWe consider the root-hair cell projection onto a 2D rectangular domain, neglecting axial dimension.\n% as in Chapter \\ref{cap:2}\nA system of four cells is schematically presented in Figure \\ref{fig:2cell}. We can see that each cell has longitudinal and transverse boundaries in common with close cells.\nWe recall the single cellular model, namely:\n\\begin{equation} \\label{eq:singModel}\n\\left\\lbrace\n\\begin{matrix}\n  \\begin{aligned}\n    & \\partial_t u = \\Tilde{D_1} \\Delta_s u + \\Tilde{a_1} u + \\Tilde{b_1} v + \\Tilde{c_1} u^2 v & \\ \\text{in} \\ \\Omega\\\\\n    & \\partial_t v = \\Tilde{D_2} \\Delta_s v + \\Tilde{a_2} v + \\Tilde{b_2} u + \\Tilde{c_2} u^2 v + f_2 & \\ \\text{in} \\ \\Omega \\\\\n    & \\Tilde{D_1} \\nabla_s u \\cdot \\mathbf{n} = 0 & \\ \\text{on} \\ \\partial \\Omega \\\\\n    & \\Tilde{D_2} \\nabla_s v \\cdot \\mathbf{n} = 0 & \\ \\text{on} \\ \\partial \\Omega.\n  \\end{aligned}\n\\end{matrix}\n\\right.\n\\end{equation}\nNo-flux on $\\partial \\Omega$, namely Neumann homogeneous boundary conditions, characterizes the system behaviour along the cell boundary.\n% prima spieghiamo il significato fisico, poi come rappresentarlo matematicamente\nIn the multi-cellular model, communication between cells is represented by allowed flux of ROPs, active and inactive, through localized channels along boundaries between neighboring cells.\n\nWe define as neighbor of cell $\\Omega_i$ the set of cells with index in $\\mathcal{N}_i = \\{ j : \\partial \\Omega_j  \\cap \\partial \\Omega_i \\neq \\emptyset \\}$. The flux of concentration of active and inactive ROPs $(u_i, v_i)$ is proportional to the difference of concentration $(u_j, v_j)$ in neighbouring cells for $j \\ \\in \\ \\mathcal{N}_i$.\n\nWe formulate the new model still focusing on one single cell domain $\\Omega_i$, taking into account the new flux generated from the discrepancy of concentrations with the neighboring cells. The new flux results in adding a non-homogeneous Neumann boundary condition on the common interfaces, as follows:\n\\begin{equation} \\label{eq:pluriModel}\n\\left\\lbrace\n\\begin{matrix}\n  \\begin{aligned}\n    & \\partial_t u_i = \\Tilde{D_1} \\Delta_s u_i + \\Tilde{a_1} u_i + \\Tilde{b_1} v_i + \\Tilde{c_1} (u_i)^2 v_i & \\ \\text{in} \\ \\Omega_i\\\\[6pt]\n    & \\partial_t v_i = \\Tilde{D_2} \\Delta_s v_i + \\Tilde{a_2} v_i + \\Tilde{b_2} u_i + \\Tilde{c_2} (u_i)^2 v_i + f_2 & \\ \\text{in} \\ \\Omega_i \\\\[6pt]\n    & \\Tilde{D_1} \\nabla_s u_i \\cdot \\mathbf{n} = 0 & \\ on \\ \\partial \\Omega_i \\backslash \\cup_{j \\in \\mathcal{N}_i} \\Gamma_{j,i} \\\\[6pt]\n    & \\Tilde{D_2} \\nabla_s v_i \\cdot \\mathbf{n} = 0 & \\ on \\ \\partial \\Omega_i \\backslash \\cup_{j \\in \\mathcal{N}_i} \\Gamma_{j,i} \\\\[6pt]\n    & \\Tilde{D_1} \\nabla_s u_i \\cdot \\mathbf{n} = \\beta_{uRR} \\ \\alpha_{uRR} \\left(u_j - u_i \\right) & \\ on \\ \\Gamma_{j,i} \\ \\forall j \\in  \\mathcal{N}_i \\\\[6pt]\n    & \\Tilde{D_2} \\nabla_s v_i \\cdot \\mathbf{n} = \\beta_{vRR} \\ \\alpha_{vRR} \\left(v_j - v_i \\right) & \\ on \\ \\Gamma_{j,i}\\ \\forall j \\in  \\mathcal{N}_i ,\n  \\end{aligned}\n\\end{matrix}\n\\right.\n\\end{equation}\nwhere we define as $(u_i, v_i)$ the concentrations of active and inactive ROPs restricted to cell $\\Omega_i$: $(u_i, v_i): \\Omega_i \\times \\left(0, T_{max} \\right) \\longrightarrow \\RSet^2$ and $\\Gamma_{j,i}$ represents the common side between cell $\\Omega_i$ and cell $\\Omega_j \\ \\in \\mathcal{N}_i $, therefore defined as: $\\Gamma_{j,i} = \\partial \\Omega_i \\cap \\partial \\Omega_j$.\n\nEach of the neighboring cells follows the same model for hair formation, meaning that system in \\eqref{eq:pluriModel} holds $\\forall \\ i$ cells composing the pluricellular system. As a consequence, the newly defined boundary conditions is coupled with the solutions $(u_j, v_j)$ with $j \\ \\in \\mathcal{N}_i$. Therefore, the pluricellular system requires a proper iterative method for setting correctly boundary conditions depending on solutions in the neighboring cells.\n\nNot communicating with other RH cells boundaries have as before no-flux. The new boundary conditions are characterized by a function and a coefficient for both active active ROPs $u$ and inactive ROPs $v$, having the same meaning:\n\\begin{itemize}\n  \\item $\\beta_{u/v RR} \\ [\\frac{1}{\\mu m^2}]$ are indicator functions defined on boundaries of cells, equal to $1$ where the communicating channels are open and $0$ where  no-flux is assumed;\n  \\item $\\alpha_{u/v RR} \\ [\\frac{1}{\\mu m}]$ are transport efficiency coefficients, representing a sort of flux quantity allowed through channels.\n  \\end{itemize}\nThese channel parameters aim at representing the average active transport along the sides of confining cells, set equal to the flux of proteins from one cell to the neighbouring ones.\n\nWe have no physical insight on previously cited functions modeling open channels for ROPs. A whole set of simulations for the proper tuning of parameters is required, in order to find a sufficiently plausible setting of the system.\n\n\\section{A new dd-wise coupling approach (Simona+Daniele+Nicola+Teresa)}\n\nDD sul modello del Capitolo 3 + parte discreta\n\n\\textbf{Numerical treatment - Sec.3.2}\n% brutto mettere gli stessi titoli?\n% -> prima questione: trattarlo con uno schema iterativo simile robin robin algorithm of domain decomposition, in modo da accoppiare le soluzioni; quindi descrivere bene lo schema (dalla strong formulation); già partendo dalo schema semi implicit nel tempo\nThe communication between cells requires a proper iterative algorithm in order to deal with the mutual interplay between confining cells.\n\nEvery subdomain $\\Omega_i$ of the pluricellular system $\\Omega$ represents the single cell and the original system of equations in \\eqref{eq:final} is solved in $\\Omega_i$ for all $i = 1, ..., N$. We solve such systems by means of the semi-implicit method described in Section \\ref{sec:SI method}. Let us consider the weak formulation restricted to $\\Omega_i$, defining the functional space $V_i = \\{ w_i \\in \\ H^1\\left(\\Omega_i\\right)\\}$, the finite element subspace $V_{i,h} \\subset V_i $ and the time interval discretization used in Section \\ref{sec:SI method}. In particular, we divide the time interval $\\left[0, T_{max}\\right]$ in $N_{max}$ time steps such that $t^n = n \\Delta t$ with $\\Delta t = T_{max} / N_{max}  $. We rewrite the full discretized formulation, identifying $u_{i,h}$ with $u_h|_{\\Omega_i}$, as:\n\ngiven the initial state $(u_{i,h}^0, v_{i,h}^0) $, find $(u_{i,h}^{n+1}, v_{i,h}^{n+1}) \\ \\in V_{i,h} \\times V_{i,h}$ such that\n\\begin{equation} \\label{eq:fullGalerkin}\n\\left\\lbrace\n\\begin{matrix}\n\\begin{aligned}\n  a_{i,u}(u_{i,h}^{n+1}, w_{i,h}) + b_{i,u}(v_{i,h}^{n+1}, w_{i,h}) + c_{i,u}(v_{i,h}^{n+1}, w_{i,h}) = f_{i,u}(w_{i,h}) \\ \\forall \\ w_{i,h} \\ \\in V_{i,h} \\\\[6pt]\n a_{i,v}(v_{i,h}^{n+1}, w_{i,h}) + b_{i,v}(u_{i,h}^{n+1}, w_{i,h}) + c_{i,v}(v_{i,h}^{n+1}, w_{i,h}) = f_{i,v}(w_{i,h}) \\ \\forall \\ w_{i,h} \\ \\in V_{i,h},\n\\end{aligned}\n\\end{matrix}\n\\right.\n\\end{equation}\n$\\forall n = 0, ... N_{max}$, where\n\\begin{subequations} \\label{eq:Gvarfmono}\n\\begin{align}\n    a_{i,u}(u_{i,h}^{n+1}, w_{i,h}) = & \\int_{\\Omega_i} \\left( \\frac{1}{\\Delta t} u_{i,h}^{n+1} w_{i,h} + \\Tilde{D}_1 \\nabla_s u_{i,h}^{n+1} \\cdot w_{i,h} - \\Tilde{a}_1 u_i^{n+1} w_{i,h} \\right) \\label{Gmono:au}\\\\ - & \\int_{\\partial \\Omega_i}\\left(\\Tilde{D}_1 \\nabla_s u_{i,h}^{n+1} \\cdot \\mathbf{n} w_{i,h}\\right)  \\nonumber\\\\\n    b_{i,u}(v_{i,h}^{n+1}, w_{i,h}) = & \\int_{\\Omega_i} \\left(- \\Tilde{b}_1 v_{i,h} w_{i,h} \\right)  \\label{Gmono:bu} \\\\\n    c_{i,u}(v_{i,h}^{n+1}, w_{i,h}) = & \\int_{\\Omega_i} \\left(- \\Tilde{c}_1 (u_{i,h}^{n})^2  v_{i,h}^{n+1} w_{i,h} \\right) \\label{Gmono:cu} \\\\[6pt]\n    a_{i,v}(v_{i,h}^{n+1}, w_{i,h}) = & \\int_{\\Omega_i} \\left(\\frac{1}{\\Delta t} v_{i,h}^{n+1} w_{i,h} + \\Tilde{D}_2 \\nabla_s v_{i,h}^{n+1} \\cdot w_{i,h} - \\Tilde{a}_2 v_i^{n+1} w_{i,h} \\right) \\label{Gmono:av} \\\\ - &  \\int_{\\partial \\Omega_i} \\left( \\Tilde{D}_1 \\nabla_s u_{i,h}^{n+1} \\cdot \\mathbf{n} w_{i,h} \\right) \\nonumber\\\\\n    b_{i,v}(v_{i,h}^{n+1}, w_{i,h}) = &\\int_{\\Omega_i} \\left( - \\Tilde{b}_2 u_{i,h} w_{i,h} \\right) \\label{Gmono:bv}\\\\\n    c_{i,v}(v_{i,h}^{n+1}, w_{i,h}) =& \\int_{\\Omega_i} \\left( - \\Tilde{c}_2 (u_{i,h}^{n})^2  v_{i,h}^{n+1} w_{i,h} \\right) \\label{Gmono:cv}\\\\[6pt]\n    f_{i,u}(w_{i,h}) = & \\int_{\\Omega_i} \\left( \\frac{1}{\\Delta t} u_{i,h}^n \\ w_{i,h} \\right) \\label{Gmono:fu}\\\\\n    f_{i,v}(w_{i,h}) = & \\int_{\\Omega} \\left( \\frac{1}{\\Delta t} v_{i,h}^n \\ w_{i,h} + f_2 w_{i,h} \\right). \\label{Gmono:fv}\n\\end{align}\n\\end{subequations}\n\nThe introduction of different boundary conditions will require to modify the bilinear forms \\eqref{Gmono:au} and \\eqref{Gmono:av} and to add contributions in the right hand sides \\eqref{Gmono:fu} and \\eqref{Gmono:fv}.\n\nTo this aim, we synthetically rewrite the model problem \\eqref{eq:fullGalerkin}, assuming generic boundary conditions, through a linear operator $\\mathcal{L}$ in the following way:\n\nGiven the initial state $(u_i^0, v_i^0)$, find $(u_i^{n+1}, v_i^{n+1}) \\ \\in \\Omega_i$ such that:\n\\begin{equation}\\label{eq:modelpb}\n% \\begin{cases}\n\\mathcal{L}^n (u_i^{n+1}, v_i^{n+1}) = \\mathbf{f}^n \\ \\text{in} \\ \\Omega_i\n% \\Tilde{D_1} \\nabla_s u_i^{n+1} \\cdot \\mathbf{n} = 0 \\ \\text{on} \\ \\partial \\Omega_i \\\\\n% \\Tilde{D_2} \\nabla_s v_i^{n+1} \\cdot \\mathbf{n} = 0 \\ \\text{on} \\ \\partial \\Omega_i\n% \\end{cases}\n\\end{equation}\n$\\forall n = 0, ... N_{max}$.\n\n\\textbf{A new iterative modeling algorithm - Sec 3.2.3 }\nThe model that we propose to make cells communicate can be regarded as a simplification of the classical domain decomposition scheme with Robin boundary conditions. We start for simplicity from a two cells problem and rewrite the common interface boundary conditions in \\eqref{eq:RR} to recover the modelled open channels in \\eqref{eq:pluriModel}. In the spirit of a block-Gauss-Seidel algorithm, we solve in sequence:\n\\begin{equation} \\label{eq:RR_final}\n\\begin{aligned}\n& \\begin{cases}\n\\mathcal{L}^n (u_1^{k+1}, v_1^{k+1}) = \\mathbf{f}^n \\ \\text{in} \\ \\Omega_1 \\\\\n\\Tilde{D_1} \\nabla_s u_1^{k+1} \\cdot \\mathbf{n} = 0 \\ \\text{on} \\ \\partial \\Omega_1 \\setminus \\Gamma \\\\\n\\Tilde{D_1} \\displaystyle{\\partial u_1^{k+1}\\over\\partial \\mathbf{n}} = \\alpha_{uRR} u_2^{k} - \\alpha_{uRR} u_1^{k+1} \\ \\text{on} \\ \\Gamma \\\\\n\\Tilde{D_2} \\nabla_s v_1^{k+1} \\cdot \\mathbf{n} = 0 \\ \\text{on} \\ \\partial \\Omega_1 \\setminus \\Gamma \\\\\n\\Tilde{D_2} \\displaystyle{\\partial v_1^{k+1}\\over\\partial \\mathbf{n}} = \\alpha_{vRR} v_2^{k} -\\alpha_{vRR} v_1^{k+1} \\ \\text{on} \\ \\Gamma\n\\end{cases}\n\\\\[6pt]\n& \\begin{cases}\n\\mathcal{L}^n (u_2^{k+1}, v_2^{k+1}) = \\mathbf{f}^n \\ \\text{in} \\ \\Omega_2 \\\\\n\\Tilde{D_1} \\nabla_s u_2^{k+1} \\cdot \\mathbf{n} = 0 \\ \\text{on} \\ \\partial \\Omega_2 \\setminus \\Gamma \\\\\n\\Tilde{D_1} \\displaystyle{\\partial u_2^{k+1}\\over\\partial \\mathbf{n}} = \\alpha_{uRR} u_1^{k+1} - \\alpha_{uRR} u_2^{k+1} \\ \\text{on} \\ \\Gamma \\\\\n\\Tilde{D_2} \\nabla_s v_2^{k+1} \\cdot \\mathbf{n} = 0 \\ \\text{on} \\ \\partial \\Omega_2 \\setminus \\Gamma\\\\\n\\Tilde{D_2} \\displaystyle{\\partial v_2^{k+1}\\over\\partial \\mathbf{n}} = \\alpha_{vRR} v_1^{k+1} -\\alpha_{vRR} v_2^{k+1} \\ \\text{on} \\ \\Gamma.\n\\end{cases}\n\\end{aligned}\\end{equation}\nThe flux imposed depends on the difference of the neighbouring solutions. As a consequence, we are imposing a not necessarily null Neumann boundary condition. Equation \\eqref{eq:RR_final} defines a RR iterative method applied to two cells using proper parameters $\\beta_{u/vRR}$ and $\\alpha_{u/v RR}$ from the model formulated in Section \\ref{sec:PluriMod}:\n\nstarting from $(u_2^{k = 0}, v_2^{k = 0}) = (u_2^n, v_2^n)$, find $(u_1^{k+1}, v_1^{k+1}) \\ \\in V_{1}$ and $(u_2^{k+1}, v_2^{k+1}) \\ \\in V_{2}$:\n\\begin{equation}\\label{eq::RRmod}\n\\begin{aligned}\n& \\begin{cases}\n\\mathcal{L}^n (u_1^{k+1}, v_1^{k+1}) = \\mathbf{f}^n \\ \\text{in} \\ \\Omega_1 \\\\\n\\Tilde{D_1} \\nabla_s u_1^{k+1} \\cdot \\mathbf{n} = 0 \\ \\text{on} \\ \\partial \\Omega_1 \\setminus \\Gamma \\\\\n\\Tilde{D_1} \\displaystyle{\\partial u_1^{k+1}\\over\\partial \\mathbf{n}} = \\beta_{uRR} \\alpha_{uRR} \\left( u_2^{k} - u_1^{k+1} \\right) \\ \\text{on} \\ \\Gamma \\\\\n\\Tilde{D_2} \\nabla_s v_1^{k+1} \\cdot \\mathbf{n} = 0 \\ \\text{on} \\ \\partial \\Omega_1 \\setminus \\Gamma \\\\\n\\Tilde{D_2} \\displaystyle{\\partial v_1^{k+1}\\over\\partial \\mathbf{n}} = \\beta_{vRR} \\alpha_{vRR} \\left( v_2^{k} - v_1^{k+1} \\right) \\ \\text{on} \\ \\Gamma\n\\end{cases}\n\\\\[6pt]\n& \\begin{cases}\n\\mathcal{L}^n (u_2^{k+1}, v_2^{k+1}) = \\mathbf{f}^n \\ \\text{in} \\ \\Omega_2 \\\\\n\\Tilde{D_1} \\nabla_s u_2^{k+1} \\cdot \\mathbf{n} = 0 \\ \\text{on} \\ \\partial \\Omega_2 \\\\\n\\Tilde{D_1} \\displaystyle{\\partial u_2^{k+1}\\over\\partial \\mathbf{n}} = \\beta_{uRR} \\alpha_{uRR} \\left( u_1^{k+1} - u_2^{k+1} \\right) \\ \\text{on} \\ \\Gamma \\\\\n\\Tilde{D_2} \\nabla_s v_2^{k+1} \\cdot \\mathbf{n} = 0 \\ \\text{on} \\ \\partial \\Omega_2 \\setminus \\Gamma\\\\\n\\Tilde{D_2} \\displaystyle{\\partial v_2^{k+1}\\over\\partial \\mathbf{n}} = \\beta_{vRR} \\alpha_{vRR} \\left( v_1^{k+1} - v_2^{k+1} \\right) \\ \\text{on} \\ \\Gamma.\n\\end{cases}\n\\end{aligned}\\end{equation}\nfor $k \\geq 0$ up to convergence.\n\nWe remark that in \\eqref{eq::RRmod} the coefficients $\\beta_{u/vRR}$ and $\\alpha_{u/v RR}$ have physical meaning since they come from the model \\eqref{eq:pluriModel}. This is in contrast with the model and method presented in Section \\ref{sec:RRclassic}, where the Robin coefficients are arbitrary.\n\nLet $V_{i,h}$ denote the finite dimensional subspace of $H^1\\left(\\Omega_i\\right)$, wih $\\Omega_i$ being the sub-domain of the pluricellular system $\\Omega$ corresponding to cell. We find solutions $\\left(u_{h}^{n+1}, v_{h}^{n+1}\\right)|_{\\Omega_i}$ identified with $\\left(u_{i,h}, v_{i,h}\\right) \\ \\in V_{i,h}$ for each time step $t^{n+1}$, solving up to convergence the iteration step, whose Galerkin formulation is:\n\\begin{equation}\\begin{aligned}\n    a_{i,u}^{RR}(u_{i,h}^{k+1}, w_{i,h}) + b_{i,u}(v_{i,h}^{k+1}, w_{i,h}) + c_{i,u}^n(v_{i,h}^{k+1}, w_{i,h}) = f_{i,u}^{RR}(w_{i,h}) \\ \\forall w_{i,h} \\in V_{i,h} \\\\\n    a_{i,v}^{RR}(v_{i,h}^{k+1}, w_{i,h}) + b_{i,v}(u_{i,h}^{k+1}, w_{i,h}) + c_{i,v}^n(v_{i,h}^{k+1}, w_{i,h}) = f_{i,v}^{RR}(w_{i,h}) \\ \\forall w_{i,h} \\in V_{i,h}.\n\\end{aligned}\\end{equation}\n\nThe bilinear forms used are equal to \\eqref{eq:Gvarfmono} - \\eqref{eq:au&avRR} for classic Robin-Robin algorithm. The only difference is in the right hand side \\eqref{eq:fu&fvRR} in which has been neglected the weak normal derivative of the neighbour solutions, as follows:\n\\begin{align}\n f_{i,u}^{RR}(w_{i,h}) & = f_{i,u}(w_{i,h}) + \\int_{\\Gamma} \\left(\\beta_{uRR} \\alpha_{uRR} \\mathcal{I}_{i,j} u_{j,h}^{k} \\mathcal{I}_{i,j}w_{j,h} \\right), \\\\\nf_{i,v}^{RR}(w_{i,h}) & = f_{i,v}(w_{i,h}) + \\int_{\\Gamma} \\left(\\beta_{vRR} \\alpha_{vRR} \\mathcal{I}_{i,j} v_{j,h}^{k} \\mathcal{I}_{i,j} w_{j,h} \\right).\n\\end{align}\n\nConsequently, the algebraic formulation of the new iterative method used is formulated similarly as in \\eqref{eq:LinSysRR}, with time-dependent block matrix that need to be reassembled at each time-step. The right-hand sides depend on the previous solution found for the neighbouring cells and their contributions need to be interpolated by means of a interpolation matrix as in Robin-Robin classic method. We here explicit the whole iterative method for a two cells composed system.\n\nStarting from initial guess given by the previous time-step solution  $\\begin{bmatrix} \\mathbf{U}_2^{0} \\\\ \\mathbf{V}_2^{0} \\end{bmatrix} = \\begin{bmatrix} \\mathbf{U}_2^{n} \\\\ \\mathbf{V}_2^{n} \\end{bmatrix}$, solve problem for $i = 1$ to find $\\begin{bmatrix} \\mathbf{U}_1^{k+1} \\\\ \\mathbf{V}_1^{k+1} \\end{bmatrix}$:\n\\begin{equation*}\n\\begin{aligned}\n \\begin{bmatrix}\n    A_u^1 & B_u^1 + C_u^1\\left(  \\mathbf{U}_1^n\\right) \\\\\n    B_v^1 & A_v^1 + C_v^1\\left(  \\mathbf{U}_1^n\\right)\n    \\end{bmatrix} \\begin{bmatrix}\n    \\mathbf{U}_1^{k+1} \\\\ \\mathbf{V}_1^{k+1} \\end{bmatrix} = \\begin{bmatrix} F^1_u \\left(\\mathbf{U}_2^k\\right) \\\\ F^1_v \\left(\\mathbf{V}_2^k\\right)\n    \\end{bmatrix}\n        \\end{aligned}\n\\end{equation*}\nand then solve problem for $ i = 2$ to find $\\begin{bmatrix} \\mathbf{U}_2^{k+1} \\\\ \\mathbf{V}_2^{k+1} \\end{bmatrix}$:\n\\begin{equation*}\n    \\begin{aligned}\n\\begin{bmatrix}\n    A_u^2 & B_u^2 + C_u^2\\left(  \\mathbf{U}_2^n\\right) \\\\\n    B_v^2 & A_v^2 + C_v^2\\left(  \\mathbf{U}_2^n\\right)\n    \\end{bmatrix} \\begin{bmatrix}\n    \\mathbf{U}_2^{k+1} \\\\ \\mathbf{V}_2^{k+1} \\end{bmatrix} = \\begin{bmatrix} F^2_u \\left(\\mathbf{U}_1^k\\right) \\\\ F^2_v \\left(\\mathbf{V}_2^k\\right)\n    \\end{bmatrix}\n\\end{aligned}\\end{equation*}\nfor $k \\geq 0$ up to convergence.\n\nIterations end when the normalized residual of consecutive computed solutions is smaller than a proper tolerance or when a maximum number of iterations is performed and we update the new solution as:\n $$\\begin{bmatrix} \\mathbf{U}_1^{n+1} \\\\ \\mathbf{V}_1^{n+1} \\end{bmatrix} = \\begin{bmatrix} \\mathbf{U}_1^{k+1} \\\\ \\mathbf{V}_1^{k+1} \\end{bmatrix}, \\ \\ \\ \\begin{bmatrix} \\mathbf{U}_2^{n+1} \\\\ \\mathbf{V}_2^{n+1} \\end{bmatrix} = \\begin{bmatrix} \\mathbf{U}_2^{k+1} \\\\ \\mathbf{V}_2^{k+1} \\end{bmatrix}$$\n\nMatrices and vectors used are defined in the following way:\n\\begin{equation}\n    \\begin{aligned}\n    & \\left[ A_u^i\\right]_{j,l} & = a_{i,u}^{RR}(\\phi_l, \\phi_j), \\ \\ \\ \\left[ A_v^i\\right]_{j,l} & = a_{i,v}^{RR}(\\phi_l, \\phi_j) \\\\\n    & \\left[ B_u^i\\right]_{j,l} & = b_{i,u}(\\phi_l, \\phi_j), \\ \\ \\ \\left[ B_v^i\\right]_{j,l} & = b_{i,v}(\\phi_l, \\phi_j)\\\\\n    & \\left[ C_u^i\\right]_{j,l} & = c_{i,u}(\\phi_l, \\phi_j),\\ \\ \\ \\left[ C_v^i\\right]_{j,l} & = c_{i,v}(\\phi_l, \\phi_j)\\\\\n    & \\left[F_u^i\\right]_{j} & = f_{i,u}^{RR}(\\phi_j), \\ \\ \\\n    \\left[F_v^i\\right]_{j} & = f_{i,v}^{RR}(\\phi_j),\n    \\end{aligned}\n\\end{equation}\nbeing $\\{\\phi_l\\}_{l = 1}^{N_h}$ the functional basis of $V_{i,h}$ finite dimensional space defined on each cell $\\Omega_i$ with $i =1,2$.\n\nA sketch of the procedure to be adopted to deal with a generic N cells pluricellular system using Robin-Robin modifed algorithm is schematically given in Algorithm \\ref{alg:RRmod}; $r_i$ are different coefficients characterizing initial state of concentrations, necessary for having flux between communicating cells. For physical reasons, we choose same initial guesses in the direction of the auxin gradient.\n\nWe have implemented a solver for a system of four cells.\n\nAs expressed in \\eqref{eq::RRmod}, the iterative procedure is formulated such that the pluricellular domain is solved sequentially, in the sense that the boundary conditions characterizing sub-domain $i$, depending on sub-domain solutions of $j \\in \\mathcal{N}_i$, are computed using the newly updated solutions. In view of a parallel implementation, the method can be reformulated such that the new boundary conditions are a function of the previous iteration solution.\n\n\\begin{algorithm}[t]\n    \\caption{Pluricellular system solver procedure: RR}\n    \\label{alg:RRmod}\n    Given $N \\geq 1$ cells, $r_i$\n    \\begin{algorithmic}[1]\n    \\STATE Initialization: $\\forall i = 1, ..., N$\n    \\STATE \\verb|[U0i, V0i]| $\\gets [r_i u_0, r_i v_0]$\n    \\STATE \\verb|[Uiprec, Viprec]| $\\gets$  \\verb|[U0i, V0i]|\n    \\WHILE{$t < T_{max}$}\n    \\STATE{\\verb|assemble| matrix for $\\forall i = 1,..., N$}\n    \\FOR{$iter < Niter$}\n    \\STATE{$\\forall i =1, ..., N$}\n    \\STATE{compute BC contribute from $j \\in \\mathcal{N}_i$}\n    \\STATE{\\verb|interpolate| on $i$}\n    \\STATE{update \\verb|rhs|}\n    \\STATE{\\verb|solve| $\\Omega_i$ problem \\eqref{eq:pluriModel}}\n    \\STATE{update residual, check tolerance, update $iter$}\n    \\STATE \\verb|[Uiprec, Viprec]| $\\gets$  \\verb|[Ui, Vi]|\n    \\ENDFOR\n    \\STATE \\verb|[U0i, V0i]| $\\gets$  \\verb|[Ui, Vi]|\n    \\ENDWHILE\n    \\end{algorithmic}\n\\end{algorithm}\n\n\\subsection{Convergence check (Simona+Nicola+Teresa+Daniele)}\n\\subsection{Reliability (Simona+Nicola+Teresa+Daniele)}\n\\subsection{Eventuali sensitivity (Simona+Nicola+Teresa+Daniele)}\n\n\\section{DD per il modello completo (Simona+Nicola+Teresa+Daniele)}\n\n\\tb{si intende solo i risultati o anche la discretizzazione?}\n\n\\section{Conclusions and future developments (Simona+Daniele)}\n\n\\textbf{Conclusions and future developments}%\nIn this thesis we developed a multi-cellular model accounting for a spatially-extended intra-cellular system for ROPs pattern formation. In the proposed framework, we solved ROPs pattern formation in a system composed by multiple cells, together with a transport model for hormone auxin. The RD model explains the auxin-mediated action of ROPs in an Arabidopsis root hair cell leading to formation of the localized patches of activated ROPs.\n\nOur simulations support conclusions reached in other works regarding ROPs dynamics under a-priori defined auxin distribution \\cite{phdthesis:victor, intra1_R, intra2}. We have analyzed various scenarios such that a stripe-like patch forms where auxin concentration is higher. Then, instability of stripe into spot-like states occurs and multiple spots align with auxin gradient or travel towards auxin minimum. Several results confirm that, for a transversally independent gradient, lateral stripes become unstable states.\n\nSuccessively as a new contribution, we extended the intra-cellular dynamics for root-hair initiation model to a multi-cellular system, developing a new model taking into account communication between cells. In order to do so, we have defined a boundary value problem which assumes new boundary conditions between neighboring cells. Subsequently, we develop an iterative procedure to solve it. We take as reference scheme a Robin-Robin domain decomposition method. We impose fluxes of ROPs betweeen neighboring cells, depending on the difference of the ROPs concentrations, through localised open channels. Such connections are tuned in order to visualize considerably different results with respect to a configuration characterized by stagnant cells. In addition,we aim at preserving all previous analyses over important parameters characterizing the system. We numerically assessed the robustness of the proposed model in cooperating with auxin distribution in influencing ROPs pattern formation.\n\nHaving defined a reliable multi-cellular model, we have taken into account also auxin concentration dynamics. Hormone auxin is regulated by carriers PIN following a non-linear ODEs system. We implement a semi-implicit method to solve such as a system on a two cells setting. The simulations we carried out show oscillating values of auxin concentration for specific sets of parameters, as expected from previous studies. A further confirmation of the robustness of pattern formation according to the proposed new multi-cellular model, when considering channel communication between cells, is given in Chapter \\ref{cap:4}. It is shown that even if the system is under steady homogeneous auxin concentrations, the model robustly forms hotspots when considering open channels under a sufficiently high overall auxin level.\n\nThe results show two ways spots of active ROPs can be generated. The first factor is the auxin gradient, which still guarantees and influence stripe to spot evolution. The second factor is the structural coupling between cells. Even if not characterized by variation in space but with a sufficiently high value of the auxin concentrations, the multi-cellular model leads the system to multiple spots.\n\nIn conclusion, this thesis provides a first attempt in modeling communication between root-hair cells in pattern formation. Future developments include to study the structural model or to deeply analyze channels characterization. Moreover, the iterative procedure implemented could be applied to a multi-cellular system composed by more than four cells and eventually try to increase the computational performance through parallel computing. Another possible road to follow is to approach the problem through homogenization techniques. The cited method may increase the efficiency in solving the model, particularly when the number of cells involved becomes large. Finally, one could assume other auxin transport models, less simplified or accounting for spatial dependence inside the cells.\n\n\n\n\n\n\\bibliographystyle{siamplain}\n\\bibliography{references}\n\\end{document}\n", "meta": {"hexsha": "66bc7d0f057c1e9819f7fae12159752a884b94cc", "size": 29975, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Manuscript/articolo_root.tex", "max_stars_repo_name": "danieleavitabile/root-simulator", "max_stars_repo_head_hexsha": "b530efef392f3cabbc251ee5f0d7d50dea2271d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Manuscript/articolo_root.tex", "max_issues_repo_name": "danieleavitabile/root-simulator", "max_issues_repo_head_hexsha": "b530efef392f3cabbc251ee5f0d7d50dea2271d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Manuscript/articolo_root.tex", "max_forks_repo_name": "danieleavitabile/root-simulator", "max_forks_repo_head_hexsha": "b530efef392f3cabbc251ee5f0d7d50dea2271d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 81.2330623306, "max_line_length": 997, "alphanum_fraction": 0.7106255213, "num_tokens": 9835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.3062052208820547}}
{"text": "\\subsection{Gravitational Body Force Examples}\n\\label{sec:example:3dhex8:gravity}\n\nPyLith features discussed in this example:\n\\begin{itemize}\n\\item Gravitational body forces\n\\item Initial stresses\n\\item Finite strain\n\\item Generalized Maxwell linear viscoelastic material\n\\end{itemize}\n\n\\subsubsection{Overview}\n\nThis set of examples describes a set of problems for PyLith involving\ngravitational body forces. All of the examples are quasi-static and\nrun for a time period of 200 years. These examples also demonstrate\nthe use of a generalized Maxwell viscoelastic material, which is used\nfor the lower crust in all examples. The final example (step17)\ndemonstrates the usage of a finite strain formulation, which\nautomatically invokes the nonlinear solver. All of the examples are\ncontained in the directory \\filename{examples/3d/hex8}, and the\ncorresponding \\filename{cfg} files are \\filename{step15.cfg},\n\\filename{step16.cfg}, and \\filename{step17.cfg}.  Run the examples as follows:\n\\begin{shell}\n# Step15\n$ pylith step15.cfg\n\n# Step16\n$ pylith step16.cfg\n\n# Step17\n$ pylith step17.cfg\n\\end{shell}\nThis will cause PyLith to read the default parameters in\n\\filename{pylithapp.cfg}, and then override or augment them with the\nadditional parameters in the \\filename{stepXX.cfg} file. Each\n\\filename{cfg} file is extensively documented, to provide detailed\ninformation on the various parameters.\n\n\n\\subsubsection{Step15 - Gravitational Body Forces}\n\nThe \\filename{step15.cfg} file defines a problem with extremely simple\nDirichlet boundary conditions. On the positive and negative x-faces,\nthe positive and negative y-faces, and the negative z-face, the\ndisplacements normal to the face are set to zero. Because all of the\nmaterials in the example have the same density, the elastic solution\nfor loading via gravitational body forces is\n\\begin{equation}\n\\sigma_{zz}=\\rho gh;\\:\\sigma_{xx}=\\sigma_{yy}=\\frac{\\nu\\rho gh}{1-\\nu}\\:.\\label{eq:1-1}\n\\end{equation}\n\nWe set the gravity field, which by default has values of 9.80655\n$\\unitfrac{m}{s^{2}}$ for acceleration and $\\left[0,0,-1\\right]$\nfor direction and time stepping implementation:\n\\begin{cfg}[Excerpt from \\filename{Step15.cfg}]\n<h>[pylithapp.timedependent]</h>\n<f>gravity_field</f> = spatialdata.spatialdb.GravityField ; Set gravity field\n\n<h>[pylithapp.timedependent.implicit]</h>\n# Change time stepping algorithm from uniform time step, to adaptive\n# time stepping.\n<f>time_step</f> = pylith.problems.TimeStepAdapt\n\n# Change the total simulation time to 200 years, and set the maximum time\n# step size to 10 years.\n<h>[pylithapp.timedependent.implicit.time_step]</h>\n<p>total_time</p> = 200.0*year\n<p>max_dt</p> = 10.0*year\n<p>stability_factor</p> = 1.0 ; use time step equal to stable value from materials\n\\end{cfg}\n\nWe use a generalized Maxwell model for the lower crust (see Section\n\\vref{sec:materials:formulation:generalized:Maxwell}), and use a \\object{SimpleDB} to\nprovide the properties. We also request the relevant properties and\nstate variables for output:\n\\begin{cfg}[Excerpt from \\filename{Step15.cfg}]\n# Change material type of lower crust to generalized Maxwell viscoelastic.\n<h>[pylithapp.timedependent]</h>\n<f>materials.lower_crust</f> = pylith.materials.GenMaxwellIsotropic3D\n# Provide a spatial database from which to obtain property values.\n# Since there are additional properties and state variables for the\n# generalized Maxwell model, we explicitly request that they be output.\n# Properties are named in cell\\_info\\_fields and state variables are named in\n# cell\\_data\\_fields.\n<h>[pylithapp.timedependent.materials.lower_crust]</h>\n<p>db_properties.iohandler.filename</p> = spatialdb/mat\\_genmaxwell.spatialdb\n<p>output.cell_info_fields</p> = [density, mu, lambda, shear_ratio, maxwell_time]\n<p>output.cell_data_fields</p> = [total_strain, stress, viscous_strain_1, viscous_strain_2, \\\\\n  viscous_strain_3]\n\\end{cfg}\nThe boundary conditions for this example are trivial, so we are able\nto use the default \\object{ZeroDispDB} for all faces. When we have\nrun the simulation, the output VTK files will be contained in \\filename{examples/3d/hex8/output}\n(all with a prefix of \\filename{step15}). Results using ParaView are\nshown in Figure \\vref{fig:example:3dhex8:step15:displacement}.\n\n\\begin{figure}\n  \\includegraphics[width=10cm]{examples/figs/3dhex8_step15-displ-t200}\n  \\caption{Displacement field for example step15 at t = 200 years visualized\n    using ParaView. The z-component of the displacement field is shown\n    with the color contours, and the vectors show the computed displacements.}\n  \\label{fig:example:3dhex8:step15:displacement}\n\\end{figure}\n\n\n\\subsubsection{Step16 - Gravitational Body Forces with Initial Stresses}\n\nThe \\filename{step16.cfg} file defines a problem that is identical to\nexample step15, except that initial stresses are used to prevent the\ninitial large displacements due to 'turning on' gravity. Since all\nnormal stress components are given an initial stress of $\\rho gh$,\nthe initial stress state is lithostatic, which is an appropriate condition\nfor many tectonic problems in the absence of tectonic stresses (e.g.,\nMcGarr \\cite{McGarr:1988}). When compared to example step15, this\nexample should maintain a lithostatic state of stress for the entire\nsimulation, and displacements should remain essentially zero.\n\nWe set the gravity field, as in example step15, and we again use adaptive\ntime stepping with a generalized Maxwell rheology for the lower crust.\nWe provide values for the initial stress for both the upper and lower\ncrust. Since the materials have the same density, we are able to use\nthe same \\object{SimpleDB} with a linear variation for both (see file\n\\filename{examples/3d/hex8/spatialdb/initial\\_stress.spatialdb}):\n\\begin{cfg}[Excerpt from \\filename{Step16.cfg}]\n# We must specify initial stresses for each material.\n# We provide a filename for the spatial database that gives the stresses,\n# and we change the query_type from the default 'nearest' to 'linear'.\n<h>[pylithapp.timedependent.materials.upper_crust]</h>\n<f>db_initial_stress</f> = spatialdata.spatialdb.SimpleDB\n<p>db_initial_stress.iohandler.filename</p> = spatialdb/initial_stress.spatialdb\n<p>db_initial_stress.query_type</p> = linear\n\n<h>[pylithapp.timedependent.materials.lower_crust]</h>\n<f>db_initial_stress</f> = spatialdata.spatialdb.SimpleDB\n<p>db_initial_stress.iohandler.filename</p> = spatialdb/initial_stress.spatialdb\n<p>db_initial_stress.query_type</p> = linear\n\\end{cfg}\nNote that we use a \\texttt{linear} \\property{query\\_type} rather than\nthe default type of \\texttt{nearest}, so that a linear interpolation\nis performed along the z-direction. When we have run the simulation,\nthe output VTK files will be contained in \\filename{examples/3d/hex8/output}\n(all with a prefix of \\filename{step16}). Results using ParaView are\nshown in Figure \\vref{fig:example:3dhex8:step16:stress}.\n\n\\begin{figure}\n  \\includegraphics[width=10cm]{examples/figs/3dhex8_step16-stress_xx-t200}\n  \\caption{Stress field (xx-component) for example step16 at t = 200 years visualized\n    using ParaView. Note that for this example, Stress\\_xx = Stress\\_yy\n    = Stress\\_zz, and there is no vertical displacement throughout the\n    simulation. Also note that the stresses appear as four layers since\n    we have used \\object{CellFilterAvg} for material output.}\n  \\label{fig:example:3dhex8:step16:stress}\n\\end{figure}\n\n\n\\subsubsection{Step17 - Gravitational Body Forces with Small Strain}\n\nThe \\filename{step17.cfg} file defines a problem that is identical to\nexample step15, except that we now use a small strain formulation\n(see Section \\vref{sec:small:strain:formulation}). All of the problems\nup to this point have assumed infinitesimal strain, meaning that the\nchange in shape of the domain during deformation is not taken into\naccount. In many problems it is important to consider the change in\nshape of the domain. This is particularly important in many problems\ninvolving gravitational body forces, since a change in shape of the\ndomain results in a different stress field. By examining the stress\nand deformation fields for this example in comparison with those of\nexample step15, we can see what effect the infinitesimal strain approximation\nhas on our solution.\n\nWe set the gravity field, as in example step15 and again use adaptive\ntime stepping withs a generalized Maxwell rheology for the lower crust.\nThe only change is that we change the problem formulation from the\ndefault \\object{Implicit} to \\object{ImplicitLgDeform}. Since the\nlarge deformation formulation is nonlinear, PyLith automatically switches\nthe solver from the default \\object{SolverLinear} to \\object{SolverNonlinear}.\nIt is thus only necessary to change the formulation:\n\\begin{cfg}[Excerpt from \\filename{Step17.cfg}]\n<h>[pylithapp.timedependent]</h>\n# Set the formulation for finite strain. The default solver will\n# automatically be switched to the nonlinear solver.\n<f>formulation</f> = pylith.problems.ImplicitLgDeform\n\\end{cfg}\nWhen we have run the simulation, the output VTK files will be contained\nin \\filename{examples/3d/hex8/output} (all with a prefix of \\filename{step17}).\nResults using ParaView are shown in Figure \\vref{fig:example:3dhex8:step17:displacement}.\n\n\\begin{figure}\n  \\includegraphics[width=10cm]{examples/figs/3dhex8_step17-displ-t200}\n  \\caption{Displacement field for example step17 at t = 200 years visualized\n    using ParaView. The z-component of the displacement field is shown\n    with the color contours, and the vectors show the computed displacements.\n    Note the larger displacements compared with example step15.}\n  \\label{fig:example:3dhex8:step17:displacement}\n\\end{figure}\n\n", "meta": {"hexsha": "5797cac8904d506facfb62584a5b9e7556fd0d66", "size": 9693, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/userguide/examples/3dhex8_gravity.tex", "max_stars_repo_name": "joegeisz/pylith", "max_stars_repo_head_hexsha": "f74060b7b19d7e90abf8597bbe9250c96593c0ad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-20T17:18:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-20T17:18:28.000Z", "max_issues_repo_path": "doc/userguide/examples/3dhex8_gravity.tex", "max_issues_repo_name": "joegeisz/pylith", "max_issues_repo_head_hexsha": "f74060b7b19d7e90abf8597bbe9250c96593c0ad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/userguide/examples/3dhex8_gravity.tex", "max_forks_repo_name": "joegeisz/pylith", "max_forks_repo_head_hexsha": "f74060b7b19d7e90abf8597bbe9250c96593c0ad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.9545454545, "max_line_length": 96, "alphanum_fraction": 0.7921180233, "num_tokens": 2503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.3062052208820547}}
{"text": "\\documentclass[notheorems]{beamer}\n\n\\usepackage[english]{babel}\n\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\n% Typesetting evaluation rules (http://cristal.inria.fr/~remy/latex/)\n\\usepackage{mathpartir}\n\n\\usepackage[T1]{fontenc}\n\\usepackage{ae,aecompl}\n\n\\usepackage{listings}\n\n\\usepackage{beamerthemesplit}\n\n\\setbeamertemplate{background canvas}[vertical shading][bottom=red!10,top=blue!10]\n\\setbeamertemplate{navigation symbols}{}\n\\setbeamertemplate{headline}{}\n\\usetheme{Warsaw}\n\\useinnertheme{rectangles}\n\n\\colorlet{darkred}{red!80!black}\n\\colorlet{darkblue}{blue!80!black}\n\\colorlet{darkgreen}{green!80!black}\n\n\\lstdefinelanguage{Coq}{\n  mathescape=true,\n  texcl=false,\n  keywords={Require, Declare},\n  morekeywords={forall, exists, with, match, let, in, if, then, else},\n  morekeywords={\n    destruct, change, Variable, Inductive, CoInductive, Fixpoint, CoFixpoint, Definition,\n    Lemma, Theorem, Proof, Axiom, Local, Save, Grammar, Syntax, Intro, Trivial,\n    Qed, Intros, Symmetry, Simpl, Rewrite, Apply, Elim, Assumption, Left,\n    Cut, Case, Auto, Unfold, Exact, Right},\n  morekeywords={Section, Module, End},\n  %emph={[1]Type, Set, nat, bool}, emphstyle={[1]\\textit},\n  comment=[s]{(*}{*)},\n  showstringspaces=false,\n}%[keywords,comments,strings]%\n\n\\lstset{\n  numbers=none,\n  basicstyle=\\footnotesize\\ttfamily,\n  frame=tb,\n  language=Coq,\n  captionpos=b,\n  xleftmargin=0em,\n  xrightmargin=0em,\n  aboveskip=1em,\n  belowskip=1em\n}\n\n\n\\title{Names and Numbers in Binding}\n\n\\author{Martijn Vermaat}\n\\institute{mvermaat@cs.vu.nl\\\\\nhttp://www.cs.vu.nl/\\~{}mvermaat/}\n\\date{Literature Study\\\\\nMarch 13, 2009}\n\n\n\\begin{document}\n\n\n\\frame{\\titlepage}\n\n\n\\frame{\n\n  \\frametitle{Names and Numbers in Binding}\n\n  \\tableofcontents\n\n}\n\n\n\\section{Mechanical Reasoning about Languages}\n\n\n\\frame{\n\n  \\frametitle{Mechanical Reasoning}\n\n  Shift from on-paper reasoning to mechanical reasoning:\n\n  \\begin{itemize}\n    \\item History of on-paper proofs and ideas\n    \\item Informal mechanical implementations of ideas\n    \\item Add a scale increase and we have a gap\n  \\end{itemize}\n\n  \\uncover<2->{\n    \\begin{block}{Goal}\n      Let's make rigorous mechanical reasoning possible.\n    \\end{block}\n  }\n\n}\n\n\n\\frame{\n\n  \\frametitle{Reasoning about Languages}\n\n  \\begin{block}{Reasoning about languages}\n    Often not intrinsically hard, but cumbersome in a mechanical setting.\n  \\end{block}\n\n  Why?\n  \\uncover<2->{\n    \\begin{itemize}\n    \\item Most languages have a notion of binding\n    \\item Bindings and bound variables are easy on paper, hard on a computer\n    \\end{itemize}\n  }\n\n}\n\n\n\\frame{\n\n  \\frametitle{Mechanical Reasoning about Languages}\n\n  So we want to\n  \\begin{quote}\n    Reason about terms with bindings in tools like Coq, in a way that is close\n    to the on-paper way.\n  \\end{quote}\n\n  \\uncover<2->{\n    We need a representation for binders and variables.\n  }\n\n}\n\n\n\\section{Representing Bindings}\n\n\n\\frame{\n\n  \\frametitle{Names and Numbers in Binding}\n\n  \\tableofcontents[currentsection]\n\n}\n\n\n\\frame{\n\n  \\frametitle{Representing Bindings}\n\n  Classical problems related to binders and variables:\n\n  \\begin{itemize}\n    \\item $\\alpha$-equivalence\n    \\item $\\alpha$-conversion (e.g. in substitution)\n  \\end{itemize}\n\n  \\uncover<2->{\n    Let's look at some representations.\n    \\begin{block}{Running example}\n      Substitution in untyped $\\lambda$-calculus\n    \\end{block}\n  }\n\n}\n\n\n\\subsection{Named Variables}\n\n\n\\frame{\n\n  \\frametitle{Names and Numbers in Binding}\n\n  \\tableofcontents[currentsubsection]\n\n}\n\n\n\\frame{\n\n  \\frametitle{Traditional Representation 1/2}\n\n  Traditional representation with named variables:\n  \\begin{align*}\n    M ::=             &\\; x\n    && \\text{variable} \\\\\n    \\llap{\\textbar\\:} &\\; \\lambda x.M\n    && \\text{abstraction} \\\\\n    \\llap{\\textbar\\:} &\\; M \\; M\n    && \\text{application} \\\\\n  \\end{align*}\n  Abstractions introduce names.\n\n}\n\n\n\\frame{\n\n  \\frametitle{Traditional Representation 2/2}\n\n  \\begin{itemize}\n\n    \\item $\\alpha$-equivalent terms are routinely identified\n\n    \\item Substitution $M[N/x]$:\n      \\begin{align*}\n        x[N/x]              &= N\\\\\n        y[N/x]              &= y                  && \\text{$x \\neq y$} \\\\\n        (\\lambda y.M')[N/x] &= \\lambda y.M'[N/x]  && \\text{$x \\neq y$ and $y$ not free in $N$} \\\\ % TODO: fix layout\n        (M_1 \\; M_2)[N/x]   &= M_1[N/x] \\; M_2[N/x]\n      \\end{align*}\n\n    \\item Now implement this\n      % alpha-quivalence is very hard\n      % side-conditions are declarative\n      % (\\x.M)[N/x] not even defined\n      % use variable convention, or a more general substitution (next slide)\n\n  \\end{itemize}\n\n}\n\n\n\\frame{\n\n  \\frametitle{Simple Substitution}\n\n  Use $\\alpha$-conversion to rename bound variables and define\n  substituting $N$ for $x$ in $M$ inductively$^*$ on M:\n\n  \\begin{align*}\n    x[N/x]              &= \\text{$N$ if $x = y$, $y$ otherwise}\\\\\n    (\\lambda y.M')[N/x] &= \\lambda z.M'[z/y][N/x]  && \\text{$z$ not free in $N, M'$} \\\\ % TODO: fix layout\n    (M_1 \\; M_2)[N/x]   &= M_1[N/x] \\; M_2[N/x]\n  \\end{align*}\n\n  % Note that M'[z/y] is not a subterm of M\n\n  \\uncover<2->{\n    Already difficult enough to read, but just what we would intuitively do.\n    So on paper, we can get by with some handwaving.\n  }\n\n}\n\n\n\\begin{frame}[fragile]\n\n  \\frametitle{Named Variables in Coq}\n\n  Term datatype:\n  \\begin{lstlisting}\nInductive term : Set :=\n  | Var : name -> term\n  | Abs : name -> term -> term\n  | App : term -> term -> term.\n  \\end{lstlisting}\n\n\\end{frame}\n\n\n\\begin{frame}[fragile]\n\n  \\frametitle{Substitution in Coq}\n\n  Simple substitution:\n  \\begin{lstlisting}\nFixpoint subst (t:term) (n:name) (t':term)\n  {struct t'} : term :=\n  match t' with\n  | Var x =>\n      if eq_name x n then t else t'\n  | Abs x b =>\n      let z := fresh_name\n                 (n :: (free_vars t) ++ (free_vars b))\n      in\n      Abs z (subst t n (rename x z b))\n  | App f a =>\n      App (subst t n f) (subst t n a)\nend.\n  \\end{lstlisting}\n  \\uncover<2->{\n    \\emph{But this is ill-defined.}\n  }\n\n\\end{frame}\n\n\n\\begin{frame}[fragile]\n\n  \\frametitle{Recursion on Term Size in Coq 1/3}\n\n  Using term size as a measure:\n  \\begin{lstlisting}\nFixpoint size (t:term) : nat :=\n  match t with\n  | Var _   => 0\n  | Abs x b => S (size b)\n  | App f a => 1 + (size f) + (size a)\nend.\n\nLemma size_rename : forall (n n':name) (t:term),\n  size (rename n n' t) = size t.\nProof.\nunfold size.\nunfold rename.\ninduction t;\n  [ case (eq_name n0 n); intro; trivial  (* Var *)\n  | congruence                           (* Abs *)\n  | congruence ].                        (* App *)\nQed.\n  \\end{lstlisting}\n\n\\end{frame}\n\n\n\\begin{frame}[fragile]\n\n  \\frametitle{Recursion on Term Size in Coq 2/3}\n\n  Substitution with term size as a recursion measure:\n  \\begin{lstlisting}\nFunction subst (t:term) (n:name) (t':term)\n  {measure size t'} : term :=\n  match t' with\n  | Var x =>\n      if eq_name x n then t else t'\n  | Abs x b =>\n      let z := fresh_name\n                 (n :: (free_vars t) ++ (free_vars b))\n      in\n      Abs z (subst t n (rename x z b))\n  | App f a =>\n      App (subst t n f) (subst t n a)\nend.\n(* Leaves us with 3 obligations. *)\n  \\end{lstlisting}\n\n\\end{frame}\n\n\n\\begin{frame}[fragile]\n\n  \\frametitle{Recursion on Term Size in Coq 3/3}\n\n  Proving termination of \\texttt{subst}:\n  \\begin{lstlisting}\nProof.\nintros.\nrewrite size_rename.\nauto.\n\nintros.\nunfold size.\ninversion f; omega.\n\nintros.\nunfold size.\ninversion a; omega.\nDefined.\n  \\end{lstlisting}\n  \\uncover<2->{\n    We really prefer structural recursion.\n  }\n\n\\end{frame}\n\n\n\\frame{\n\n  \\frametitle{Simultaneous Substitution}\n\n  Stoughton suggests the structurally recursive simultaneous substitution $M \\sigma$:\n  \\begin{align*}\n    x \\sigma              &= \\sigma x\\\\\n    (\\lambda x.M') \\sigma &= \\lambda y.(M' \\; \\sigma[y/x])  && \\text{$y$ not free in $M', \\sigma$}\\\\\n    (M_1 \\; M_2) \\sigma   &= M_1 \\sigma \\; M_2 \\sigma\n  \\end{align*}\n  where\n  \\begin{equation*}\n    \\sigma[N/y] \\; x =\n    \\begin{cases}\n      N        & \\text{if $x = y$,}\\\\\n      \\sigma x & \\text{otherwise}\n    \\end{cases}\n  \\end{equation*}\n\n  \\uncover<2->{\n    Substituting $N$ for $x$ in $M$ is now $M \\; \\iota [N/x]$ with $\\iota$ the identity substitution.\n  }\n\n}\n\n\n\\begin{frame}[fragile]\n\n  \\frametitle{Simultaneous Substitution in Coq}\n\n  \\begin{lstlisting}\nFixpoint sim_subst (l:list (term*name)) (t:term)\n  {struct t} : term :=\n  match t with\n  | Var x =>\n      apply_subst l x\n  | Abs x b =>\n      let z := fresh_name\n                  ((free_vars_sub l) ++ (free_vars b))\n      in\n      Abs z (sim_subst ((Var z, x)::l) b)\n  | App f a =>\n      App (sim_subst l f) (sim_subst l a)\nend.\n\nDefinition subst' (t:term) (n:name) (t':term)\n  : term := sim_subst ((t, n) :: nil) t'.\n  \\end{lstlisting}\n\n\\end{frame}\n\n\n\\subsection{de Bruijn Indices}\n\n\n\\frame{\n\n  \\frametitle{Names and Numbers in Binding}\n\n  \\tableofcontents[currentsubsection]\n\n}\n\n\n\\frame{\n\n  \\frametitle{de Bruijn Indices 1/2}\n\n  Represent variable occurrences by number of binders between itself and abstraction:\n  \\begin{align*}\n    M ::=             &\\; n\n    && \\text{variable} \\\\\n    \\llap{\\textbar\\:} &\\; \\lambda .M\n    && \\text{abstraction} \\\\\n    \\llap{\\textbar\\:} &\\; M \\; M\n    && \\text{application} \\\\\n  \\end{align*}\n\n  \\uncover<2->{\n    \\begin{itemize}\n      \\item Harder to read\n      \\item $\\alpha$-equivalence is term equivalence\n      \\item Substitution is structurally recursive\n      \\item No renaming (but lifting)\n      \\item Mechanically less tedious\n    \\end{itemize}\n  }\n\n}\n\n\n\\begin{frame}\n\n  \\frametitle{de Bruijn Indices 2/2}\n\n  Substitution can be defined as:\n  \\begin{align*}\n    n[N/n]             &= N\\\\\n    m[N/n]             &= m                    && \\text{$m \\neq n$} \\\\\n    (\\lambda .M')[N/n] &= \\lambda .M'[\\uparrow \\! N / n\\!+\\!1]\\\\\n    (M_1 \\; M_2)[N/n]  &= M_1[N/n] \\; M_2[N/n]\n  \\end{align*}\n  where $\\uparrow \\! M$ is $M$ with all free variables incremented.\n\n\\end{frame}\n\n\n\\begin{frame}[fragile]\n\n  \\frametitle{de Bruijn Indices in Coq}\n\n  Term datatype:\n  \\begin{lstlisting}\nInductive term : Set :=\n  | Var : nat -> term\n  | Abs : term -> term\n  | App : term -> term -> term.\n  \\end{lstlisting}\n\n\\end{frame}\n\n\n\\begin{frame}[fragile]\n\n  \\frametitle{Substitution in Coq}\n\n  Substitution:\n  \\begin{lstlisting}\nFixpoint lift (l:nat) (t:term) {struct t} : term :=\n  match t with\n  | Var n   => Var (if le_lt_dec l n then (S n)\n                    else n)\n  | Abs u   => Abs (lift (S l) u)\n  | App u v => App (lift l u) (lift l v)\nend.\n\nFixpoint subst (t:term) (n:nat) (t':term)\n  {struct t'} : term :=\n  match t' with\n  | Var m   => if eq_nat_dec n m then t else t'\n  | Abs u   => Abs (subst (lift 0 t) (S n) u)\n  | App u v => App (subst t n u) (subst t n v)\nend.\n  \\end{lstlisting}\n\n\\end{frame}\n\n\n\\subsection{Locally Nameless}\n\n\n\\frame{\n\n  \\frametitle{Names and Numbers in Binding}\n\n  \\tableofcontents[currentsubsection]\n\n}\n\n\n\\begin{frame}\n\n  \\frametitle{Locally Nameless Representation 1/2}\n\n  Combine names and numbers -- names for free variables, de Bruijn indices for bound variables:\n  \\begin{align*}\n    M ::=             &\\; x\n    && \\text{free variable} \\\\\n    \\llap{\\textbar\\:} &\\; n\n    && \\text{bound variable} \\\\\n    \\llap{\\textbar\\:} &\\; \\lambda .M\n    && \\text{abstraction} \\\\\n    \\llap{\\textbar\\:} &\\; M \\; M\n    && \\text{application} \\\\\n  \\end{align*}\n\n  \\uncover<2->{\n    \\begin{itemize}\n      \\item $\\alpha$-equivalence is term equivalence\n      \\item No renaming, no lifting (but freshening)\n      \\item Substitution is structurally recursive\n    \\end{itemize}\n  }\n\n\\end{frame}\n\n\n\\begin{frame}\n\n  \\frametitle{Locally Nameless Representation 2/2}\n\n  Two substitution operations:\n  \\begin{itemize}\n  \\item Substitute a term for a named variable\n  \\item Substitute a term for a de Bruijn index\\\\[2em]\n  \\end{itemize}\n\n  \\only<2>{\n  Named variable substitution:\n  \\begin{align*}\n    x[N/x]             &= N\\\\\n    y[N/x]             &= y                 && \\text{$x \\neq y$} \\\\\n    n[N/x]             &= n\\\\\n    (\\lambda .M')[N/x] &= \\lambda .M'[N/x]\\\\\n    (M_1 \\; M_2)[N/x]  &= M_1[N/x] \\; M_2[N/x]\n  \\end{align*}\n  No renaming.\n  }\n\n  \\only<3->{\n  de Bruijn substitution:\n  \\begin{align*}\n    x[N/n]             &= x\\\\\n    n[N/n]             &= N\\\\\n    m[N/n]             &= m                    && \\text{$m \\neq n$} \\\\\n    (\\lambda .M')[N/n] &= \\lambda .M'[N / n\\!+\\!1]\\\\\n    (M_1 \\; M_2)[N/n]  &= M_1[N/n] \\; M_2[N/n]\n  \\end{align*}\n  No lifting.\n  }\n\n\\end{frame}\n\n\n\\begin{frame}[fragile]\n\n  \\frametitle{Locally Nameless Representation in Coq}\n\n  Term datatype:\n  \\begin{lstlisting}\nInductive term : Set :=\n  | FreeVar  : name -> term\n  | BoundVar : nat -> term\n  | Abs      : term -> term\n  | App      : term -> term -> term.\n  \\end{lstlisting}\n\n\\end{frame}\n\n\n\\begin{frame}[fragile]\n\n  \\frametitle{Named Variable Substitution in Coq}\n\n  Substitute a term for a named variable:\n  \\begin{lstlisting}\nFixpoint subst (t:term) (x:name) (t':term)\n  {struct t'} : term :=\n  match t' with\n  | FreeVar y  => if eq_name x y then t else t'\n  | BoundVar n => t'\n  | Abs b      => Abs (subst t x b)\n  | App f a    => App (subst t x f) (subst t x a)\nend.\n  \\end{lstlisting}\n\n\\end{frame}\n\n\n\\begin{frame}[fragile]\n\n  \\frametitle{de Bruijn Substitution in Coq}\n\n  Substitute a term for a de Bruijn index:\n  \\begin{lstlisting}\nFixpoint subst (t:term) (n:nat) (t':term)\n  {struct t'} : term :=\n  match t' with\n  | FreeVar x  => t'\n  | BoundVar m => if eq_nat_dec m n then t else t'\n  | Abs b      => Abs (subst t (S n) b)\n  | App f a    => App (subst t n f) (subst t n a)\nend.\n  \\end{lstlisting}\n\n\\end{frame}\n\n\n\\section{Implementations}\n\n\n\\subsection{The POPLmark Challenge}\n\n\n\\frame{\n\n  \\frametitle{Names and Numbers in Binding}\n\n  \\tableofcontents[currentsubsection]\n\n}\n\n\n\\begin{frame}\n\n  \\frametitle{The POPLmark Challenge}\n\n  Mechanized metatheory for the masses:\n  \\begin{quote}\n    Your average POPL paper should include machine-checked proofs\n  \\end{quote}\n\n  Set of benchmarks for measuring progress:\n  \\begin{itemize}\n    \\item Based on metatheory of System F$_\\texttt{<\\!:}$\n    \\item Binding issues are a central aspect\n    \\item 15 (partial) solutions\n    \\item Part 1a: transitivity of subtyping\n  \\end{itemize}\n\n\\end{frame}\n\n\n\\begin{frame}\n\n  \\frametitle{Syntax of System F$_\\texttt{<\\!:}$}\n\n  Part 1a considers just the type language of F$_\\texttt{<\\!:}$.\n\n  \\begin{align*}\n    T ::=             &\\; X\n    && \\text{type variable} \\\\\n    \\llap{\\textbar\\:} &\\; \\texttt{Top}\n    && \\text{maximum type} \\\\\n    \\llap{\\textbar\\:} &\\; T \\rightarrow T\n    && \\text{type of functions} \\\\\n    \\llap{\\textbar\\:} &\\; \\forall X\\texttt{\\small<\\!:}T.T\n    && \\text{universal type} \\\\[2em]\n    \\Gamma ::=        &\\; \\emptyset\n    && \\text{empty type environment} \\\\\n    \\llap{\\textbar\\:} &\\; \\Gamma, X \\texttt{\\small<\\!:}T\n    && \\text{type variable binding} \\\\\n  \\end{align*}\n\n\\end{frame}\n\n\n\\begin{frame}\n\n  \\frametitle{Subtyping Rules of System F$_\\texttt{<\\!:}$}\n\n  \\begin{mathpar}\n    \\infer*[right=SA-Top]\n           {\\:}\n           {\\Gamma \\vdash S \\texttt{\\large<\\!:} \\texttt{Top}}\n    \\and\n    \\infer*[right=SA-Refl-TVar]\n           {\\:}\n           {\\Gamma \\vdash X \\texttt{\\large<\\!:} X}\n    \\\\\n    \\infer*[right=SA-Trans-TVar]\n           {X \\texttt{\\small<\\!:} U \\in \\Gamma\n             \\\\ \\Gamma \\vdash U \\texttt{\\large<\\!:} T}\n           {\\Gamma \\vdash X \\texttt{\\large<\\!:} T}\n    \\\\\n    \\infer*[right=SA-Arrow]\n           {\\Gamma \\vdash T_1 \\texttt{\\large<\\!:} S_1\n             \\\\ \\Gamma \\vdash S_2 \\texttt{\\large<\\!:} T_2}\n           {\\Gamma \\vdash S_1 \\rightarrow S_2 \\; \\texttt{\\large<\\!:} \\; T_1 \\rightarrow T_2}\n    \\\\\n    \\infer*[right=SA-All]\n           {\\Gamma \\vdash T_1 \\texttt{\\large<\\!:} S_1\n             \\\\ \\Gamma, X \\texttt{\\small<\\!:} T_1 \\vdash S_2 \\texttt{\\large<\\!:} T_2}\n           {\\Gamma \\vdash \\forall X \\texttt{\\small<\\!:} S_1.S_2 \\; \\texttt{\\large<\\!:} \\; \\forall X \\texttt{\\small<\\!:} T_1.T_2}\n  \\end{mathpar}\n\n  POPLmark 1a: transitivity of $\\texttt{<\\!:}$\n\n\\end{frame}\n\n\n\\begin{frame}\n\n  \\frametitle{Solutions in Coq}\n\n  Named variables:\n  \\begin{itemize}\n    \\item \\only<1>{Stump} \\uncover<2->{{\\bf Stump} (7641)}\n  \\end{itemize}\n\n  de Bruijn indices:\n  \\begin{itemize}\n    \\item \\only<1>{Vouillon} \\uncover<2->{{\\bf Vouillon} (5443)}\n    \\item Sallinens \\uncover<2->{(unavailable)}\n    \\item Charg\\'eraud \\uncover<2->{(3727)}\n  \\end{itemize}\n\n  Locally nameless:\n  \\begin{itemize}\n    \\item \\only<1>{Leroy} \\uncover<2->{{\\bf Leroy} (1081+5414=6495)}\n    \\item Chlipala \\uncover<2->{(2650+2400=5050)}\n    \\item Chargu\\'eraud \\uncover<2->{(803+3533=4336)}\n  \\end{itemize}\n\n  Nested datatypes:\n  \\begin{itemize}\n    \\item Hirschowitz and Maggesi \\uncover<2->{(2757)}\n  \\end{itemize}\n\n\\end{frame}\n\n\n\\begin{frame}\n\n  \\frametitle{Stump -- Named Variables}\n\n  Two main techniques to avoid difficulties with named variables:\n  \\begin{enumerate}\n    \\item Free and bound variables are disjoint\n      \\begin{itemize}\n        \\item Substitution is just grafting\n      \\end{itemize}\n    \\item \\uncover<2->{Use common bound variable in the bodies of the SA-All rule\n      \\begin{itemize}\n        \\item Avoid $\\alpha$-equivalence issues\n        \\item Original rule:\n          \\begin{mathpar}\n            \\infer*[right=SA-All]\n                   {\\Gamma \\vdash T_1 \\texttt{\\large<\\!:} S_1\n                     \\\\ \\Gamma, X \\texttt{\\small<\\!:} T_1 \\vdash S_2 \\texttt{\\large<\\!:} T_2}\n                   {\\Gamma \\vdash \\forall X \\texttt{\\small<\\!:} S_1.S_2 \\; \\texttt{\\large<\\!:} \\; \\forall X \\texttt{\\small<\\!:} T_1.T_2}\n          \\end{mathpar}\n        \\item \\uncover<3->{Adapted rule:\n          \\begin{mathpar}\n            \\infer*[right=SA-All]\n                   {\\Gamma \\vdash T_1 \\texttt{\\large<\\!:} S_1\n                     \\\\ \\Gamma, X \\texttt{\\small<\\!:} T_1 \\vdash S_2[X/X_1] \\; \\texttt{\\large<\\!:} \\; T_2[X/X_2]}\n                   {\\Gamma \\vdash \\forall X_1 \\texttt{\\small<\\!:} S_1.S_2 \\; \\texttt{\\large<\\!:} \\; \\forall X_2 \\texttt{\\small<\\!:} T_1.T_2}\n          \\end{mathpar}}}\n      \\end{itemize}\n  \\end{enumerate}\n\n\\end{frame}\n\n\n\\begin{frame}\n\n  \\frametitle{Vouillon -- de Bruijn Indices}\n\n  \\begin{itemize}\n    \\item Very clear implementation, even suggested as baseline by POPLmark team\n    \\item A lot of code deals with shifting (but straightforward)\n    \\item Proofs not by structural induction, but by induction on the size of types\n    \\item Narrowing and transitivity are proved separately\n    \\item Unfortunately no accompanying paper\n  \\end{itemize}\n\n\\end{frame}\n\n\n\\begin{frame}\n\n  \\frametitle{Leroy -- Locally Nameless Representation}\n\n  \\begin{itemize}\n   \\item Two substitution operations, no renaming or lifting\n   \\item Considering abstraction bodies, freshening is needed\n   \\item Proofs not by structural induction, but by induction on the size of types\n   \\item A lot of code deals with swaps (used for equivariance proofs)\n   \\item Room for improvements, some implemented by Chargu\\'eraud\n     \\begin{itemize}\n       \\item Useless case in de Bruijn substitution\n       \\item Treat well-formed typing environments as sets\n       \\item Cofinite quantification of free variable in SA-All\n       \\item Proofs by induction on well-formdness derivation instead of size\n     \\end{itemize}\n  \\end{itemize}\n\n\\end{frame}\n\n\n\\subsection{Engineering Formal Metatheory}\n\n\n\\frame{\n\n  \\frametitle{Names and Numbers in Binding}\n\n  \\tableofcontents[currentsubsection]\n\n}\n\n\n\\begin{frame}\n\n  \\frametitle{Engineering Formal Metatheory}\n\n  Aydemir et al, POPL'08: {\\em Engineering Formal Metatheory}\\\\[2em]\n\n  Complete style for formalizing language metatheory:\n  \\begin{itemize}\n    \\item Building on experience from POPLmark solutions\n    \\item Locally nameless representation\n    \\item Cofinite quantification of free variables in inductive definitions of relations on terms\\\\[2em]\n  \\end{itemize}\n\n  Implemented in this style:\n  \\begin{itemize}\n    \\item Parts of POPLmark challenge\n    \\item Type soundness for core ML\n    \\item Subject reduction for Calculus of Constructions\n    \\item Several small developments\n  \\end{itemize}\n\n\\end{frame}\n\n\n\\begin{frame}\n\n  \\frametitle{LNgen}\n\n  Aydemir and Weirich, this Wednesday:\n  \\begin{quote}\n    LNgen: Tool Support for Locally Nameless Representations\\\\[2em]\n  \\end{quote}\n\n  Building on {\\em Engineering Formal Metatheory}:\n  \\begin{itemize}\n    \\item Takes Ott-like specifications\n    \\item Generates locally nameless infrastructure for Coq\n  \\end{itemize}\n\n\\end{frame}\n\n\n\\section{Conclusions}\n\n\n\\frame{\n\n  \\frametitle{Names and Numbers in Binding}\n\n  \\tableofcontents[currentsection]\n\n}\n\n\n\\begin{frame}\n\n  \\frametitle{Related Work}\n\n  Other Representations\n\n  \\begin{block}{Nominal Representation}\n    \\begin{itemize}\n    \\item Based on nominal logic (Pitts, Gabbay)\n    \\item Names for variables\n    \\item Swapping as primitive\n    \\item Urban in Isabelle/HOL\n    \\end{itemize}\n  \\end{block}\n\n  \\begin{block}{Higher Order Abstract Syntax}\n    \\begin{itemize}\n    \\item Meta-variables for variables\n    \\item Meta-functions for functions\n    \\item $\\alpha$-equivalence for free\n    \\item No renaming needed\n    \\item Leads to quite unusual formulations\n    \\end{itemize}\n  \\end{block}\n\n\\end{frame}\n\n\n\\frame{\n\n  \\frametitle{Conclusion 1/2}\n\n  Named variables:\n  \\begin{itemize}\n    \\item Closest to paper, but too much trouble mechanically\\\\[1em]\n  \\end{itemize}\n\n  \\uncover<2->{\n    de Bruijn indices:\n    \\begin{itemize}\n    \\item Good candidate for mechanical developments\n    \\item Involves a lot of `easy' work\n    \\item Not so easy to read\\\\[1em]\n    \\end{itemize}\n  }\n\n  \\uncover<3->{\n    Locally nameless representation:\n    \\begin{itemize}\n    \\item Improves on de Bruijn\n    \\item Still quite some boilerplate code\n    \\item Tools like LNgen might make it feasible\\\\[1em]\n    \\end{itemize}\n  }\n\n  \\uncover<4->{\n    Nominal approaches are promissing\n  }\n\n}\n\n\n\\begin{frame}\n\n  \\frametitle{Conclusion 2/2}\n\n  Of course, it also depends on your goal:\n  \\begin{itemize}\n    \\item A language implementation might not need to be close to its concrete syntax\n    \\item Metatheory for many users on the other hand probably does\\\\[1em]\n  \\end{itemize}\n\n  \\ldots and on your environment:\n  \\begin{itemize}\n    \\item We focussed on Coq\n    \\item There are other tools\n  \\end{itemize}\n\n\\end{frame}\n\n\n\\begin{frame}\n\n  \\frametitle{Questions and Further Reading}\n\n  Questions?\\\\[4em]\n\n  \\begin{block}{Literature}\n    \\begin{itemize}\n      \\item de Bruijn, 1972: {\\em $\\lambda$-calculus with nameless dummies}\n      \\item Stoughton, 1988: {\\em Substitution revisited}\n      \\item McBride and McKinna, 2004: {\\em I am not a number -- I am a free variable}\n      \\item Aydemir et al, 2005: {\\em The POPLmark challenge}\n      \\item Pollack, 2006: {\\em Reasoning about languages with binding}\n      \\item Aydemir et al, 2008: {\\em Engineering formal metatheory}\n    \\end{itemize}\n  \\end{block}\n\n\\end{frame}\n\n\n\\end{document}\n", "meta": {"hexsha": "87584a18e090196e2809a4e3517a94762e0a064b", "size": 22807, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "vu/literature-study/binding-slides.tex", "max_stars_repo_name": "martijnvermaat/documents", "max_stars_repo_head_hexsha": "42483b7c4bf94ed708e2893c3ea961d025a10b5e", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-28T14:38:06.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-28T14:38:06.000Z", "max_issues_repo_path": "vu/literature-study/binding-slides.tex", "max_issues_repo_name": "martijnvermaat/documents", "max_issues_repo_head_hexsha": "42483b7c4bf94ed708e2893c3ea961d025a10b5e", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vu/literature-study/binding-slides.tex", "max_forks_repo_name": "martijnvermaat/documents", "max_forks_repo_head_hexsha": "42483b7c4bf94ed708e2893c3ea961d025a10b5e", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4699507389, "max_line_length": 140, "alphanum_fraction": 0.6235804797, "num_tokens": 7286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.30620522088205465}}
{"text": "\\section{Discussion} \\label{sec:discuss}\n\\subsection{Forward Model} \\label{sec:forward-model}\nIn the previous section, we demonstrated the accuracy of \\sedflow~posteriors. \nNevertheless, a primary determining factor for the fidelity of \\sedflow, or any\nML model, is the quality of the training data set and, thus, the forward model\nused to construct it. \nBelow, we discuss the caveats and limitations of our forward model, which has\ntwo components: the PROVABGS SPS model and noise model \n(Section~\\ref{sec:training}).\n\nFirst, for our noise model, we assign uncertainties to noiseless photometric\nfluxes based on an empirical estimate of $p(\\sigma_X\\given f_X)$ for each band\nindependently. \nThis is a simplicistic prescription and, as the bottom right panels of\nFigure~\\ref{fig:data} ($g - \\sigma_r$ and $r - \\sigma_r$) reveal, there are\ndiscrepancies between the magnitude - uncertainty distributions of the training\ndata and observations. \nDespite these discrepancies, \\sedflow~provides excellent estimates of the true\nposterior.  \nThis is because we design our ANPE to include $\\sigma_X$ as a conditional\nvariable (Section~\\ref{sec:anpe_train}).\nThe $f_X-\\sigma_X$ distribution of our training data does not impact the\naccuracy of the posteriors as long as there are sufficient training data near\n$\\bfi{x}$ to train the NDE in that region.\n\nA more accurate noise model will, in theory, improve the performance of\n\\sedflow~because the $\\bfi{x}$-space of the training data will more efficiently \nspan the observations. \nFewer training data would be expended in regions of $\\bfi{x}$-space that are\ndevoid of observations.  \nHowever, for our application, we do not find significantly  \nimproved performance when we alter the noise model.\nThis suggests that even with our simplistic noise model, the $\\bfi{x}$-space of\nobservations is covered sufficiently well by the training data. \nWe note that when we decrease $N_{\\rm train}$ to below 500,000,\n\\sedflow~posteriors are significantly less accurate. \nA more realistic forward model may reduce this $N_{\\rm train}$ threshold for\naccurate posteriors. \nHowever, generating $N_{\\rm train}{\\sim}1,000,000$ training SEDs has a\nnegligible computational cost compared to MCMC SED modeling, so we do not\nconsider it necessary to explore this further. \n\nNext, we consider limitations in the PROVABGS SPS model used in our forward\nmodel. \nOur SPS model uses a compact and flexible prescription for SFH and ZH that can\ndescribe a broad range of SFHs and ZHs.\nHowever, the prescription is derived from simulated Illustris galaxies, whose\nSFHs and ZHs may be not reflect the full range of SFHs and ZHs of real\ngalaxies.\nIf certain subpopulations of observed galaxies have SFHs and ZHs that cannot be\nwell described by the PROVABGS prescription, they cannot be accurately modeled.\nEven if the PROVABGS SFH and ZH prescriptions are sufficient, there are\nlimitations in our understanding of stellar evolution. \n\nThere is currently no consensus in the stellar evolution, stellar spectral\nlibraries, or IMF of galaxies~\\citep[\\emph{e.g.}][]{treu2010, vandokkum2010,\nrosani2018, ge2019, sonnenfeld2019}.\nThe PROVABGS model uses MIST isochrones, \\cite{chabrier2003} IMF, and the MILES\n+ BaSeL spectral libraries. \nThese choices limit the range of SEDs that can be produced by the training\ndata. \nFor instance, if galaxies have significant variations in their IMF, assuming a\nfixed IMF would falsely limit the range of our training data.  \nA more flexible SED model that includes uncertainties in SPS would broaden the\nrange of galaxy SEDs that can be modeled.\nData-driven approaches may also enable SED models to be more\ndescriptive~\\citep[\\emph{e.g.}][]{hogg2016, portillo2020}. \nImproving  SED models, however, is beyond the scope of this work. \nOur focus is on improving the Bayesian inference framework.\nIn that regard, the limitations of the SED model equally impacts conventional\napproaches with MCMC. \n\nWe encounter the caveats above when we apply \\sedflow~to the NSA catalog. \nFor a small fraction of NSA galaxies (588 out of 33,884), \\sedflow~generates\nposteriors that are outside of the prior volume. \nThis is because the photometry or uncertainties of these galaxies lie outside\nof the support of the training data and where \\sedflow~is well trained. \nThey either have higher photometric uncertainties, for a given magnitude, or\nbluer photometric colors than the training data. \nSome of these may be observational artifacts or problematic photometry.\nNevertheless, \\sedflow~fails because we cannot construct training data near\nthem with our limited noise and SPS models. \nSince this only affects a small fraction of the NSA galaxies, we flag them in\nour catalog and, for completeness, infer their galaxy properties by applying\nPROVABGS with MCMC sampling.\nFor more details, we refer readers to Appendix~\\ref{sec:fail}.\n\nTo test for limitations of the forward model, we can construct additional tests\nof posteriors derived from ANPE. \nFor instance, the $\\chi^2$ of the best-fit parameter value from the \nestimated posterior can be used to assess whether the best-fit model \naccurately reproduces observations.\nThis would only require one additional model evaluation per galaxy. \nOne can also construct an Amortized Neural Likelihood Estimator (ANLE) using\nthe same training data.\nUnlike the ANPE, which estimates $p(\\btheta\\given f_X, \\sigma_X, z)$, the ANLE\nwould estimate $p(f_X \\given \\btheta, \\sigma_X, z)$.\nWe can then further validate the posteriors by assessing whether the observed\nphotometry lies within the ANLE distribution. \nBased on the overall high level of accuracy of \\sedflow~posteriors, we do not\nexplore these additional tests; however, they can be used to further validate\nany ANPE posteriors. \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Advantages of \\sedflow} \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nThe primary advantage of \\sedflow~is its computational speed. \nThis becomes even more pertinent if we want to add additional parameters to\naddress concerns about the choices in current SPS models, described above.\nTo relax these assumptions, SPS models would need to introduce additional\nparameters that flexibly model these uncertainties~\\citep{conroy2009,\nconroy2010c}. \nWhile the dimensionality of current SPS models already makes MCMC methods\ncomputational infeasible, ANPE has been applied to higher dimensional\napplications.\nFor instance, \\cite{dax2021} constructed an accurate ANPE for a\n15-dimensional model parameter and 128-dimensional conditional variable\nspaces.\nNDE is an actively developing field in ML and new methods are constantly\nemerging~\\citep[\\eg][]{wu2020, dhariwal2021}. \nSince ANPE can handle higher dimensionality, we can in the future include\nadditional parameters that model uncertainties in SPS. \nThis will not only improve our SED modeling, but also improve our understanding\nof stellar evolution and the IMF.\n\nIn addition to enabling scalable SED modeling for the next generation galaxy\nsurveys, \\sedflow~will also enable us to tackle other key challenges in SED\nmodeling. \nFor example, recent works have demonstrated that priors of SED models can\nsignificantly impact the inferred galaxy properties~\\citep{carnall2018,\nleja2019, hahn2022}. \nEven ``uniformative'' uniform priors on SED model parameters can impose\nundesirable priors on derived galaxy properties such as $M_*$, SFR, SFH, or\nZH.\nTo avoid significant biases, galaxy studies must carefully select priors and\nvalidate their results using multiple different choices. \nWith an MCMC approach, selecting a different prior means reevaluating every\nposterior and repeating all the SED model evaluations in the MCMC sampling.  \nFor an ANPE approach, the prior is set by the distribution of parameters in the\ntraining data. \nFor a new prior, instead of reconstructing the training data, we can resample\nit in such a way that the parameters follow the new prior.\nThen, the ANPE model can be re-trained, re-validated on the test data, and\nre-deployed on observations.\nEach of these steps require substantially less computational resources than\ngenerating a new set of training data or using MCMC methods. \nHence, the ANPE approach provides a way to efficiently vary the prior without\nmultiplying computational costs.\n", "meta": {"hexsha": "43d45b0dd3dfc9748f634b0d410fcbc0c91356a4", "size": 8343, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/paper/discuss.tex", "max_stars_repo_name": "changhoonhahn/SEDflow", "max_stars_repo_head_hexsha": "4561ecfe3a38cc4c25df263d971a87e8a83f88ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2022-03-16T03:11:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T16:01:42.000Z", "max_issues_repo_path": "docs/paper/discuss.tex", "max_issues_repo_name": "changhoonhahn/SEDflow", "max_issues_repo_head_hexsha": "4561ecfe3a38cc4c25df263d971a87e8a83f88ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/paper/discuss.tex", "max_forks_repo_name": "changhoonhahn/SEDflow", "max_forks_repo_head_hexsha": "4561ecfe3a38cc4c25df263d971a87e8a83f88ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.9932885906, "max_line_length": 80, "alphanum_fraction": 0.7883255424, "num_tokens": 1969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631556226291, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3062052137214157}}
{"text": "% !TEX root = template.tex\n\n\\begin{table*}[t]\n\t\\centering\n\t\t\\begin{tabular}{ p{7cm}p{2cm}p{2cm}p{2cm}p{2cm} }\n\t\t\t\\hline\n\t\t\tMethod & Accuracy & Precision & Recall & F1-Score \\\\\n\t\t\t\\hline\n\t\t\tCNN + No centering & 77.0 & 78.0 & 75.8 & 76.8 \\\\\n\t\t\tCNN + No centering + Manual F. & 75.6 & 76.8 & 73.9 & 75.3 \\\\\n\t\t\tCNN + Centering + Manual F. & 86.2 & 86.9 & 70.2 & 77.6 \\\\\n\t\t\t\\textbf{CNN + Centering + Encoder F.} & \\textbf{89.2} & \\textbf{88.9} &  \\textbf{86.1} & \\textbf{86.1} \\\\\n\t\t\t\\hline\n\t\t\\end{tabular}\n\t\t\\caption{\\label{tab:model-performance} HD\n                  classification results with different features CNN\n                  augmentation and data preprocessing. The tests are\n                  made with our proposed architecture, linear\n                  interpolation and data centering, 196 (1x16)\n                  filters, max-pool (1x4), 64 fully connected neurons,\n                  a dropout rate of $0.05$, l2-regularization of\n                  $5e^{-5}$ and Adam learning rate of $2e^{-5}$. Here\n                  we don't use OIT since we are testing our result\n                  onto HD dataset, including \\textit{sit} and\n                  \\textit{stand} labels. The test set is composed by\n                  users \\textit{a-b} and the reaming users form the\n                  training set.}\n\\end{table*}\n\n\\section{Results}\n\\label{sec:results}\n\n\\subsection{Heterogeneity Dataset (HD)}\n\\label{subsec:heterogeneity-dataset}\n\nIn this section we evaluate performances between previous works and\ndifferent model architectures, and the influences of the preprocessing\ntechniques applied here. Similar to what was done in\n\\cite{ignatov2018real}, we carried out from the HD dataset some\nrepresentative users to test the model and then use the remaining ones\nto train the model. In this case we selected users \\textit{a} and\n\\textit{b} since we found that they are very representative among all\nothers. In fact the proposed models tend to be less precise with user\n\\textit{a} and more accurate with user \\textit{b}. This mainly depends\non the user's style in walking, doing stairs and so on. In this way also, we\nare able to compare results with other works that usually tend to\nevaluate performances on unseen user.\n\nIn this training and test set settings, we evaluate the best\nhyper-parameters amd results for the models, excluding OIT\npreprocessing block, since this dataset was collected with a fixed orientation. \\textit{sit} and \\textit{stand} activities are included. The rest\nof preprocessing blocks are enabled, unless otherwise specified.\n\n\\textbf{Autoencoder.} In order to search for best autoencoder model\nhyper-parameters we performed a grid search. Results are reported in\nTab. \\ref{tab:ae-hyperparams} where values that performs well on the\nvalidation dataset are reported in bold. The best hyper-parameters\nmodel used to be the one with a relatively small code size: from 24 to\n36 features which is also a good thing as we do not want the\nautoencoder to learn the identity, but only to keep useful\ninformation. In this settings we get an MSE of $0.87$.\n\n\\begin{table}[t]\n  \\centering\n  \\begin{tabular}{lp{4cm}}\n    \\hline\n    Hyper-parameter & Values \\\\\n    \\hline\n    code size & \\{2, 3, 4, 5, 6, 12, 18, 24, 30, \\textbf{36}, 42, 48, 54, 60, 72\\} \\\\\n    batch size & \\{32, \\textbf{128}\\} \\\\\n    epochs & \\{\\textbf{150}, 200\\} \\\\\n    \\hline\n  \\end{tabular}\n  \\caption{Grid-search for best hyper-parameters on autoencoder}\n  \\label{tab:ae-hyperparams}\n\\end{table}\n\n\\begin{table}[b]\n\t\\centering\n\t\\begin{tabular}{p{2.4cm}p{4.5cm}}\n\t\t\\hline\n\t\tHyper-parameter & Values \\\\\n\t\t\\hline\n\t\tDistance measure & \\{\\textbf{euclidean}, manhattan, chebyshev, minkowski, standardized euclidean, mahalanobis\\} \\\\\n\t\tNumber of neighbors & \\{3, 4, \\textbf{5}, 6, 7, 8\\} \\\\\n\t\t\\hline\n\t\\end{tabular}\n\t\\caption{Grid-search for KNN classifier}\n\t\\label{tab:knn-grid-search}\n\\end{table}\n\nEven if the primary goal for this autoencoder is to automatically\nextract features from signal for the main CNN model, we implement also\ntwo simple classifiers in order to directly use autoencoder's feature\nand check their effectiveness.\n\nThe first is a K-Nearest Neighbors (KNN) clustering algorithm, and we\nperform clustering on encoder's code. The idea here is that\nautoencoder should extract relevant features which may be similar\nclass by class. We performed fine-tuning of KNN parameters with a grid\nsearch, looking for best values of distance measure and number of\nneighbors. The Tab. \\ref{tab:knn-grid-search} show the values.  We\nselect the euclidean distance measure and $5$ as number of neighbors.\nIn this case we obtained an accuracy of $76.2$\\%.  From the\ngrid-search on KNN we surprisingly noticed that performances do not\nvary significantly among different hyper-parameters: most results are\nless than $5$\\% far from the best. This may be an indication of the\nmaximum capability of this autoencoder model, so to obtain better\nperformances we have to add complexity to the model.\n\n\\begin{table}[b]\n\t\\centering\n\t\\begin{tabular}{ p{1.8cm}p{1.9cm}p{1.7cm}p{1.7cm} }\n\t\t\\hline\n\t\tCNN Filters & FC2 Neurons & Accuracy & F1-Score \\\\\n\t\t\\hline\n\t\t196 & 1024 & 84.6 & 75.3 \\\\\n\t\t196 & 512 & 86.1 & 75.7 \\\\\n\t\t\\textbf{196} & \\textbf{64} & \\textbf{86.2} & \\textbf{77.6} \\\\\n\t\t96 & 1024 & 82.8 & 69.9 \\\\\n\t\t96 & 512 & 84.4 & 73.7 \\\\\n\t\t96 & 64 & 89.0 & 73.0 \\\\\n\t\t48 & 1024 & 80.0 & 79.4 \\\\\n\t\t48 & 512 & 83.7 & 74.9 \\\\\n\t\t48 & 64 & 84.0 & 72.3 \\\\\n\t\t\\hline\n\t\\end{tabular}\n\t\\caption{Hyper-parameters selection using HD results with data centering and manual features augmented CNN}\n\t\\label{tab:model-selection}\n\\end{table}\n\nThe second classifier instead is based on a Feed Forward Neural\nNetwork (FFNN). The architecture is very simple and consists on two\ndense layers of $100$ neurons each with $0.1$ dropout and\n\\textit{ReLU} activation function, while the last is a dense layer\nwith a number of neurons equal to the number of classes and soft-max\nactivation function. The network is trained with Adam optimizer to\nminimize the categorical cross-entropy loss function. In this case we\nobtained an accuracy of $81.8\\%$.\n\n\\textbf{CNN Network.} We fist test how number of convolutional filters and dense neurons in CL1 and FL2 will influence classification performances with data centering and manual extracted features. The results obtained are presented in Tab. \\ref{tab:model-selection}. We decided to choose 196 convolutional filters and 64 dense neurons thanks to its balance between accuracy and F1-Score performances, obtaining $86.2\\%$ and $77.6\\%$ respectively. \n\nTo better appreciate how our preprocessing blocks affects model overall performances, we also try to disable or enable some of them. In Tab. \\ref{tab:model-performance} we reported our obtained results experiments. We see that augmenting the CNN with manual extracted feature when data are not centered, lead to no significant change in performances, instead when also enabling data centering preprocessing with manual features augmented CNN the model obtain nearly $10\\%$ more in accuracy and precision metrics. This prove the benefits of data centering stated previously. However we were not able to reach the same performances presented in \\cite{ignatov2018real}, where the authors obtained in the same exact settings an accuracy of $97.6\\%$. These empirically confirm that performances of state-of-the-art models trained with one type of sensors are worse when dealing with smartphone sensors heterogeneity. Moving on, augmenting the CNN with encoder feature increments the model performances, meaning that encoder features are more robust that manual features, as explained previously. To compare our best results in this setting with the ones presented in \\cite{stisen2015smart}, we decided to perform their \\textit{Leave-one-user-out cross validation} evaluation, consisting of test the model with data from one user, and train with data from all the others in a cross validation fashion and then averaging the obtained results. In this evaluation setting we obtained an average F1-score of $85.8\\%$, beating their best model result of nearly $10\\%$ more in F1-Score metric. This prove also that using users a and b to do our evaluation is a good compromise of the real \\textit{Leave-one-user-out cross validation} evaluation performances, since we obtain nearly the same results ($90.2\\%$ instead of $89.2\\%$ in accuracy and $85.8\\%$ instead of $86.1\\%$). A confusion matrix in this latter setting is reported in Fig. \\ref{fig:cnn-confusion-matrix} where we could see that the model performs nicely overall in all the considered activities, with some difficulties in distinguishing between \\textit{stand} and \\textit{sit} and \\textit{walk} with \\textit{stairs} activities.\n\n\\vspace{-0.2cm}\n\\begin{figure}[h]\n\t\\centering\n\t\\includegraphics[width=0.5\\textwidth]{images/confusion_matrix.png}\n\t\\caption{CNN confusion matrix}\n\t\\label{fig:cnn-confusion-matrix}\n\\end{figure}\n\n\\vspace{-0.3cm}\n\n\\subsection{Oriented Dataset (OD)}\n\nWith this new collected dataset we want to test our models' performance\nin a real use case scenario, where smartphone could be placed in\ndifferent positions and orientations. In this case we trained the\nmodels with the entire HD as training set, and then use the OD as a\ntest set. It is important to remember that in this case we apply OIT\nand so we condensed the \\textit{sit} and \\textit{stand} activities of\nHD into a one class \\textit{no activity} category.\n\n\\textbf{Autoencoder.}  An interesting result, as\nTab.~\\ref{tab:ae-loss} confirms, is that OIT is a necessary operation\nwhen dealing with different orientations. For example, without OIT we can see\nthat the autoencoder trained and tested on same data goes from $0.75$\nto $10.42$ MSE: more than ten times worse. Furthermore, data from\n\\textit{hand} or \\textit{pocket-up/down} do not inflate the loss too much. This is good\nbecause it indicates that autoencoder is producing robust features.\n\n\\begin{table}[t]\n  \\centering\n  \\begin{tabular}{lr}\n    \\hline\n    Scenario & Loss (MSE) \\\\\n    \\hline\n    HD + OIT + OD validation & 0.75 \\\\\n    HD + OIT + OD validation (allpos) & 0.82 \\\\\n    HD + OD validation & 10.42 \\\\\n    \\hline\n  \\end{tabular}\n  \\caption{Autoencoder loss on different scenarios}\n  \\label{tab:ae-loss}\n\\end{table}\n\nTab. \\ref{tab:knn-metrics} and \\ref{tab:ffnn-metrics} show\nrespectively KNN and FFNN evaluation for the best autoencoder with\n$36$ features and the two classifier with hyper-parameters selected in\nSec. \\ref{subsec:heterogeneity-dataset}. From this results, we can\nobserve that KNN is more stable and not influenced by sensor's\nposition/orientation w.r.t. FFNN. Also, the two models preserve\nevaluation order: on \\textit{pouch} position gets best results on both\nmodels, while the worse positions is \\textit{hand+pocket}, as we\nexpect.\n\n\\begin{table}[h]\n  \\centering\n  \\begin{tabular}{lrrrr}\n    \\hline\n    Positions & Accuracy & Precision & Recall & F1-score \\\\\n    \\hline\n    Pouch & 80.1 & 86.4 & 80.7 & 79.0 \\\\\n    Hand+Pocket & 79.5 & 83.7 & 79.5 & 79.6 \\\\\n    All & 80.0 & 83.8 & 79.1 & 78.2 \\\\\n    \\hline\n  \\end{tabular}\n  \\caption{KNN evaluation onto OD between smartphone positions (pouch\n    left/right/top/back, hand and pocket-up/down, all positions)}\n  \\label{tab:knn-metrics}\n\\end{table}\n\n\\vspace{-0.25cm}\n\n\\begin{table}[h]\n  \\centering\n  \\begin{tabular}{lrrrr}\n    \\hline\n    Positions & Accuracy & Precision & Recall & F1-score \\\\\n    \\hline\n    Pouch & 74.4 & 84.7 & 74.4 & 74.8 \\\\\n    Hand+Pocket & 67.8 & 78.0 & 67.8 & 70.0 \\\\\n    All & 69.9 & 81.3 & 69.9 & 72.4 \\\\\n    \\hline\n  \\end{tabular}\n  \\caption{FFNN evaluation onto OD between smartphone positions (pouch\n    left/right/top/back, hand and pocket-up/down, all positions)}\n  \\label{tab:ffnn-metrics}\n\\end{table}\n\n\\textbf{CNN Network.} Combining autoencoder features into the CNN, we were able to reach better performances w.r.t the simpler KNN and FFNN previous presented classifiers. For the \\textit{hand+pocket} new positions, we noticed a performance drop of nearly $15\\%$, but given the complexity of this new unseen context we are pretty satisfied with the obtained results. As\nTab. \\ref{tab:model-oit-performance} confirms, the final proposed learning strategy with a smart data preprocessing lead to good results even with new problem\nsettings that nearly match real use case scenarios.\n\n\\begin{table}[b]\n  \t\\centering\n\t\\begin{tabular}{p{1.8cm}rrrr}\n\t  \\hline\n\t  Positions & Accuracy & Precision & Recall & F1-score \\\\\n\t  \\hline\n\t  Pouch & 85.3 & 92.0 & 73.8 & 81.9 \\\\\n\t  Hand+Pocket & 70.5 & 79.5 & 63.0 & 70.2 \\\\\n\t  All & 78.0 & 84.0 & 69.0 & 75.7 \\\\\n\t  \\hline\n\t\\end{tabular}\n\t\\caption{CNN classification comparisons onto \\textit{OD} between\n\t  smartphone positions (pouch left/right/top/back, hand and\n\t  pocket-up/down and all positions).}\n\t\\label{tab:model-oit-performance}\n\t\\end{table}\n\nWe also try to disable OIT in the CNN model, obtaining a drop in performances of nearly $45$\\% for all metrics considered. This demonstrate that OIT is an extremely useful preprocessing technique both for autoencoder and CNN models.\n", "meta": {"hexsha": "8f3d1db866380be66f5a069ba4f81f76396186a3", "size": 13075, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/results.tex", "max_stars_repo_name": "lparolari/har", "max_stars_repo_head_hexsha": "4cab66e686f7d1a337636d40dcbf8036731bde9b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-30T01:57:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-30T01:57:34.000Z", "max_issues_repo_path": "paper/results.tex", "max_issues_repo_name": "lparolari/har", "max_issues_repo_head_hexsha": "4cab66e686f7d1a337636d40dcbf8036731bde9b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/results.tex", "max_forks_repo_name": "lparolari/har", "max_forks_repo_head_hexsha": "4cab66e686f7d1a337636d40dcbf8036731bde9b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.4763779528, "max_line_length": 2180, "alphanum_fraction": 0.7291013384, "num_tokens": 3683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631556226291, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3062052137214157}}
{"text": "% !TEX root = ../00_thesis.tex\n\n\\section{Appendix B}\n% \\subsection*{Additional constraints for the multi-mode schedule synthesis problem}\n\\label{appendix:multi_mode}\n\nIn this appendix, we present how are practically implemented the constraints ensuring that\n\\begin{itemize}\n\n\t\\item Schedules in the multi-mode case are compatible, \\ie the inheritance constraints formulated in Theorem~\\ref{thm:minVirtLegacy} (\\cref{sec:multi_mode}) are respected\n\n\t\\item Running applications can seamlessly switch between modes, \\ie there is no risk of missed deadline due to a mode change, as described in \\cref{sec:modeChanges}.\n\n\\end{itemize}\nFinally, we conclude with a short comment on how to implement context-specific requirements in the schedule synthesis problem.\n\n\\vspace{10pt}\n\\fakepar{Compatible schedules}\nLet us consider the schedule synthesis of mode \\mode{j} where applications \\app and \\appB have been scheduled in higher-priority mode \\mode{i}, such that\n\\begin{itemize}\n\n\t\\item $\\exists \\; \\app \\in \\legApp{j}$\n\n\t\\item $\\exists \\; \\appX \\in \\freeApp{j} \\, , \\; \\appB \\in \\minvirtlegApp{j}{\\appX}$\n\n\\end{itemize}\nWe denote with a superscript $^k$ a schedule value computed in mode \\mode{k}, \\eg $m^j.o$ is the offset of message $m$ computed in mode \\mode{j}.\n\n%legacy app: fix everything.\n\\app is a legacy application for mode \\mode{j}. Its schedule must be reserved, which is realized simply as follows\n\\begin{flalign}\n&\\forall \\; (\\tau, m) \\in \\app.c,\n&\t\\tau^{j}.o \\; &= \\; \\tau^i.o\n&&\\\\\n&\n&\tm^i.o \\; &= \\; m^j.o\n&&\\\\\n&\n&\tm^i.d \\; &= \\; m^j.d\n&&\n\\end{flalign}\n\n%virtual legacy app: use\n\\appB is a virtual legacy application for application \\appX. As a result, the scheduling ``space'' of the tasks of \\appB must be reserved, to guarantee that the tasks of \\appX will not overlap with \\appB. This is achieved by adding constraints similar to those enforcing (C3), guaranteeing the validity of the task mappings (see the previous Appendix)\n%\n\\begin{align}\n\\intertext{%\n$\t\\forall\\,\n\t\t\\tau_\\appB \\in \\appB.c\t, \\,\n\t\t\\tau_\\appX \\in \\appX.c  , \\;\n\t\t\\; E_\\appB == E_\\appX, \\;\n\t\\forall\\, k_\\appB \\in [1..LCM/\\tau_\\appB.p], \\; \\forall\\, k_\\appX \\in [1..LCM/\\tau_\\appX.p]$}\n\t\\tau_\\appB.o + \\tau_\\appB.e + \\tau_\\appB.p*k_\\appB\n\t&\\; \\leq \\; \\tau_\\appX.o + \\tau_\\appX.p*k_\\appX \\\\\n\\texttt{or} \\quad\n\t\\tau_\\appX.o + \\tau_\\appX.e + \\tau_\\appX.p*k_\\appX\n\t&\\; \\leq \\; \\tau_\\appB.o + \\tau_\\appB.p*k_\\appB\n\\end{align}\n%\nSimilarly, the \\; \\texttt{or} \\; condition is realized using a ``big'' time constant $M$ and boolean variables.\n%\n\\begin{align}\n\\tau_\\appB.o + \\tau_\\appB.e + \\tau_\\appB.p*k_\\appB\n\t&\\; \\leq \\; \\tau_\\appX.o + \\tau_\\appX.p*k_\\appX\n\t\t+ M * (1 - \\lambda_{\\appB,\\appX}^{k_\\appB,k_\\appX})\\\\\n\\tau_\\appX.o + \\tau_\\appX.e + \\tau_\\appX.p*k_\\appX\n\t&\\; \\leq \\; \\tau_\\appB.o + \\tau_\\appB.p*k_\\appB\n\t\t+ M * \\lambda_{\\appB,\\appX}^{k_\\appB,k_\\appX}\n\\end{align}\n\n\n\\vspace{10pt}\n\\fakepar{Seamless mode switch}\n%message served and released in the same hyperperiod\nIn order to prevent the risk of missed deadline due to a mode change, we described in \\cref{sec:modeChanges} a simple procedure to execute mode change requests.\n\\begin{enumerate}\n\n\t\\item All messages must be released and served within the same hyperperiod.\n\t\\label{rule1}\n\n\t\\item The starting time \\tjstart of mode \\modej is set to the end of the first hyperperiod of \\modei after which the execution of all applications $\\app \\in \\Sij$ has been completed.\n\n\\end{enumerate}\n%\nThe second rule depends on the embedded software, it is independent of the schedule synthesis.\nTo enforce the first rule however, additional constraints must be formulated. As discussed at the end of \\cref{sec:single_mode} and illustrated in \\cref{fig:openboxoptions}, the rounds schedule may be such that some messages are released in one of the mode's hyperperiod, but served only in the next hyperperiod, see~\\cref{subfig:case2}.\n\\TODO{Now the only case presented in df(0) = -1, adapt the text}\n\nFor applications scheduled in only one mode, this is no problem. Indeed, for every mode changed, they are either starting, terminating, or not involved, which cannot lead to a deadline miss.\nFor the other applications, \\ie scheduled in more than one mode, we enforce rule (\\ref{rule1}) by setting the parameters $r_o.B_i$ in the definition of the service function $sf_i$~(see \\eqref{eq:sf_def}).\nFor any application \\app scheduled in more than one mode,\n%\n\\begin{flalign}\n&\n\\forall \\, m_i \\in \\app.c,\n&&r_o.B_i \\; = \\; 0\n&&\n\\end{flalign}\n%\n\n\n\n\\vspace{5pt}\n\\fakepar{Context-specific requirements}\nThe scheduling framework proposed in this work is very flexible thanks to the use of an ILP formulation to synthesize the schedules.\nWe described in the Appendices a set of constraints for this ILP formulation that solves our initial problem, as stated in \\cref{sec:model}.\nThen, additional constraints can be added to the formulation, to capture context-specific requirements. We give thereafter some examples of practically-relevant constraints.\n\n\\vspace{5pt}\n\\begin{description}\n\n\t\\item[Tasks $\\tau_1$ and $\\tau_2$ must start simultaneously]\n\t\\begin{equation}\n\t\\tau_1.o \\; = \\;  \\tau_2.o\n\t\\end{equation}\n\n\t\\item[The time difference between $\\tau_1$ finishing and $\\tau_2$ starting is bounded by $D$]\n\t\\begin{equation}\n\t\\tau_2.o - ( \\, \\tau_1.o + \\tau_1.e \\, ) \\; \\leq \\; D\n\t\\end{equation}\n\n\t\\item[Messages $m_1$ and $m_2$ must be allocated to the same rounds]\n\t\\begin{flalign}\n\t&\\forall\\, j\\in [1..R],\n\t&&r_j.B_1 \\; = \\; r_j.B_2 \\qquad\n\t&&\n\t\\end{flalign}\n\n\\end{description}\n", "meta": {"hexsha": "84cf711ff1b3b013d9e5d907f46494fa352eed44", "size": 5496, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "50_TTW/appendix_multi_mode.tex", "max_stars_repo_name": "romain-jacob/doctoral-theis", "max_stars_repo_head_hexsha": "fd21e9f0cddeda91821eb061c9ab12df9f610da9", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "50_TTW/appendix_multi_mode.tex", "max_issues_repo_name": "romain-jacob/doctoral-theis", "max_issues_repo_head_hexsha": "fd21e9f0cddeda91821eb061c9ab12df9f610da9", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "50_TTW/appendix_multi_mode.tex", "max_forks_repo_name": "romain-jacob/doctoral-theis", "max_forks_repo_head_hexsha": "fd21e9f0cddeda91821eb061c9ab12df9f610da9", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.2769230769, "max_line_length": 351, "alphanum_fraction": 0.7181586608, "num_tokens": 1708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982315512489, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.3062035202382125}}
{"text": "\\section{Tensat: Optimizing Deep Learning Computation Graphs}\n\\label{sec:tensat}\n\n\\newcommand{\\ourname}{Tensat\\xspace}\n\\newcommand{\\tensat}{Tensat\\xspace}\n\nDeep learning frameworks and compilers\n (e.g., Tensorflow~\\cite{TensorFlow}, PyTorch~\\cite{NEURIPS2019_9015},\n  XLA~\\cite{xla}, TensorRT~\\cite{TensorRT}, TVM~\\cite{tvm},\n  MLIR~\\cite{mlir})\n have enabled diverse kinds of machine learning models to run\n efficiently on numerous compute platforms.\nNeural network models in\n these frameworks are typically represented as tensor computation\n graphs.\nTo improve the runtime performance of a tensor graph, these\n frameworks perform various optimizations.\n\nOne of the most important optimizations is graph rewriting,\n which takes in a tensor graph $g$ and a set of semantics-preserving graph rewrites $R$,\n and by applying rewrites to $g$ seeks to find an semantically equivalent $g'$ with lower cost according to some cost model.\n% which transforms a tensor graph by iteratively applying rewrite rules that substitute subgraphs with semantically equivalent ones.\n%The graph rewriting optimization problem can be factored into two sub-problems: (1) discovering a comprehensive set of rewrite rules and (2) an algorithm that determines the order in which to apply the rewrite rules to optimize a given graph.\nThe current industry-standard approach adopted by most frameworks is to use a manually curated set of rewrite rules and rely on a heuristic strategy to determine the order in which to apply the rewrite rules.\n%that often applies rewrite rules greedily.\nHowever, this approach often leads to sub-optimal results both due to the non-comprehensive set of rewrite rules, as well as the sub-optimal graph substitution heuristic \\cite{taso,metaflow}. % that considers only a small fraction of all possible graphs reachable with a given set of rewrites \\cite{taso, metaflow, Fang:sampling}.\n\nThis case study aims to address the sub-optimality problem of graph rewrite strategies, while leveraging the existing rewrite rules generation technique~\\cite{taso}.\nPrior research has shown that searching for sequences of substitutions\n\\cite{taso,metaflow,Fang:sampling} outperforms heuristic approaches.\nHowever, both heuristic and search-based solutions rely on sequential application of substitutions.\nSince rewrites often depend on or enable one another,\noptimization depends heavily on the order in which rewrites are applied;\nthe ``phase ordering'' problem strikes again.\n% this classically tricky problem is known in the compilers community as the ``phase-ordering'' or ``rewrite-ordering'' problem.\n\n\n\\begin{table}[]\n    \\centering\n    \\begin{tabular}{ccc|cc}\n    \\hline\n    & \\multicolumn{2}{c|}{\\bf Search time (s)} & \\multicolumn{2}{c}{\\bf Runtime speedup (\\%)} \\\\\n    & TASO & \\ourname{} & TASO & \\ourname{} \\\\\n    \\hline\n    BERT & 13.6 & \\textbf{1.4} & 8.5 & \\textbf{9.2} \\\\\n    ResNeXt-50 & 25.3 & \\textbf{0.7} & 5.5 & \\textbf{8.8} \\\\\n    NasNet-A & 1226 & \\textbf{10.6} & 1.9 & \\textbf{7.3} \\\\\n    NasRNN & 177.3 & \\textbf{0.5} & 45.4 & \\textbf{68.9} \\\\\n    Inception-v3 & 68.6 & \\textbf{5.1} & 6.3 & \\textbf{10.0} \\\\\n    SqueezeNet & 16.4 & \\textbf{0.3} & 6.7 & \\textbf{24.5} \\\\\n    VGG-19 & 8.9 & \\textbf{0.4} & \\textbf{8.9} & \\textbf{8.9} \\\\\n    \\hline\n    \\end{tabular}\n    \\caption{Comparison of optimization time and runtime speedup of the optimized computation graphs over the original graphs, TASO~\\cite{taso} v.s. \\ourname{}.}\n    \\label{table:ngraph}\n\\end{table}\n\n\nThis case study presents \\ourname{}, a tensor graph superoptimization framework that employs equality saturation \\cite{eqsat, eqsat-llvm, egg},\nto apply all possible rewrites at once.  %comprehensively and scalably explore the search space of all equivalent graphs a given a set of rewrite rules.\n\\tensat splits program optimization into two phases: {\\em exploration} and {\\em extraction}.\nThe exploration phase is equality saturation using \\egg as usual.\n\\tensat's extraction phase is totally custom;\n simple cost functions simply do not suffice for extracting efficient deep learning compute graphs.\nInstead, \\tensat employs an Integer Linear Programming (ILP) extraction solution,\n which requires\n a novel method to filter out invalid subgraphs from an e-graph.\n% The extraction phase selects from the e-graph the equivalent program with the lowest cost according to a given cost model. The compact representation of the exponentially large search space using e-graphs enables extraction algorithms that can find the globally optimal equivalent program quickly.\n%\\ourname{} uses equality saturation to replace the heuristic- or sequential-search-based rewriting approaches from prior work.\n\n% Applying equality saturation to tensor graph rewriting requires non-trivial extensions in both the exploration and extraction phases.\n% We extend the exploration phase to support complex, non-local rewrite rules that are necessary to produce highly efficient tensor graphs.\n% Additionally, we introduce a novel method to filter out invalid subgraphs from an e-graph,\n% which enables our extraction procedure based on Integer Linear Programming (ILP) to quickly find the optimal solution.\n\nWe evaluated \\ourname{} on a number of well-known machine learning models executing on a GPU.\nAs highlighted in \\autoref{table:ngraph}, \\ourname{} can synthesize optimized graphs that are up to 23\\% faster in runtime than state-of-the-art \\cite{taso}, while reducing the optimization time by up to 300x.\nBy having the e-graph compactly representing an exponential number of equivalent graphs, \\ourname{} is able to cover a larger search space more efficiently than the sequential search methods.\nAs a result, our search approach is both extremely effective and fast enough to be used as part of a normal complation flow.\n%Our approach discovers better optimized graphs than the state-of-the-art, at the same time running much faster such that it can be used as part of a normal compilation flow.\n%We believe that our approach is the first tensor graph superoptimization that is both \\ATTN{provably optimal} and fast enough to be used as part of a normal complation flow.\n\n%However, doing so requires non-trivial extensions in both the saturation as well as the extraction phase: (a) extending equality saturation to support complex rewrite rules (b) formulating the extraction problem as a integer linear programming(ILP), and (c) designing pruning strategies to trade-off coverage (in terms of the number of graphs explored) for shorter time to solve the ILP problem.\n\n\n%We evaluated \\ourname{} on a number of well-known machine learning models (including BERT, ResNeXt-50, NasNet-A, NasRNN, and Inception-v3), comparing against TASO \\cite{taso}, state-of-the-art tensor graph rewriting approach.\n%up to xxx faster performing graphs in up to xxx smaller search time while exploring an exponentially larger search space.\n%In addition, we have also performed a number of ablation studies to highlight the importance of the specific optimizations and extensions proposed in this paper.\n\n\\subsection{Representation}\n\nThis section describes how \\ourname{} represents tensor computation graphs and rewrite rules.\n\n\\paragraph{Representing Tensor Computation Graphs}\n\\label{sec:language}\n\nWe use a representation based on the one in TASO~\\cite{taso},\n with modifications to make it suitable for equality saturation.\n\\autoref{table:ops} shows the set of operators we consider.\nEach operator $o_i$ corresponds to a node $n_i$ in the graph; the node represents the output tensor of the operator.\nThe nodes corresponding to the inputs of $o_i$ are the children nodes of $n_i$.\n% Unlike TASO, we include both the input tensors and the operator parameters as the children nodes of the operator node.\n% This way, all the relevant information of the tensor computation graph is represented syntactically by the nodes and the edges, without the need of additional annotations on the nodes.\nEach tensor computation graph is a DAG under this representation.\n\nThe formulations in equality saturation become simpler if a graph is\nsingle-rooted. Therefore, we combine all the final output nodes of a\ngraph with \\emph{no-op}s to make the graph single-rooted. The no-op\nnodes do not have any actual operators associated with them, and they\nwill not be altered during the exploration phase, so there are no side\neffects.\n\n\n\\begin{table}[t]\n    \\centering\n    \\newcommand\\act{\\textsf{activation}}\n    \\newcommand\\width{\\textsf{w}}\n    \\newcommand\\height{\\textsf{h}}\n    {\\textbf{Types}\n      \\\\[1mm]\n      \\small\n    \\begin{tabular}{cl|cl|cl|cl}\n      $T$ & Tensor\n      & $TT$ & Tensor tuple\n      & $W$ & Weights tensor\n      & $s_\\height, s_\\width$ & stride (height, width) \\\\\n      $n$ & natural number\n      & $p$  & padding\n      & $a$ & activation\n      & $k_\\height, k_\\width$ & kernel (height, width) \\\\\n    \\end{tabular}}\n    \\\\[2em]\n    \\begin{tabular}{lll}\n        {\\bf Operator}  & {\\bf Description}                    & {\\bf Type signature} \\\\\n    \\hline\n        \\sf ewadd           & Element-wise addition                & $(T, T) \\rightarrow T$ \\\\\n        \\sf ewmul           & Element-wise multiplication          & $(T, T) \\rightarrow T$ \\\\\n        \\sf matmul          & Matrix multiplication                & $(a, T, T) \\rightarrow T$ \\\\\n        \\sf conv $^a$       & Grouped convolution                  & $(s_\\height, s_\\width, p, a, T, W) \\rightarrow T$ \\\\\n        \\sf relu            & Relu activation                      & $T \\rightarrow T$ \\\\\n        \\sf tanh            & Tanh activation                      & $T \\rightarrow T$ \\\\\n        \\sf sigmoid         & Sigmoid activation                   & $T \\rightarrow T$ \\\\\n        \\sf poolmax         & Max pooling                          & $(T, k_\\height, k_\\width, s_\\height, s_\\width, p, a) \\rightarrow T$ \\\\\n        \\sf poolavg         & Average pooling                      & $(T, k_\\height, k_\\width, s_\\height, s_\\width, p, a) \\rightarrow T$ \\\\\n        \\sf transpose $^b$  & Transpose                            & $(T, {\\sf permutation}) \\rightarrow T$ \\\\\n        \\sf enlarge $^c$    & Pad a convolution kernel with zeros  & $(T, T_{\\sf ref}) \\rightarrow T$ \\\\\n        \\sf concat$_n$ & Concatenate along the given axis     & $(n, T, \\dots, T) \\rightarrow T$ \\\\\n        \\sf split $^d$      & Split a tensor into two along the axis & $(n, T) \\rightarrow TT$ \\\\\n        \\sf split$_0$       & Get the first output from split      & $TT \\rightarrow T$ \\\\\n        \\sf split$_1$       & Get the second output from split     & $TT \\rightarrow T$ \\\\\n        \\sf merge $^e$      & Update weight to merge grouped conv  & $(W, n) \\rightarrow W$ \\\\\n        \\sf reshape         & Reshape tensor                       & $(T, {\\sf shape}) \\rightarrow T$ \\\\\n        \\sf input           & Input tensor                         & ${\\sf identifier} \\rightarrow T$ \\\\\n        \\sf weight          & Weight tensor                        & ${\\sf identifier} \\rightarrow T$ \\\\\n        \\sf no-op            & Combine the outputs of the graph     & $(T, T) \\rightarrow T$ \\\\\n    \\end{tabular}\n    \\\\[1em]\n    \\caption{\n        Operators supported by \\ourname.\n        There are four types for the nodes in our representation:\n        tensor type (T), string type (S), integer type (N), and tensor tuple type (TT).\n        The integer type is used to represent parameters of the\n         operators, such as stride, axis, and also padding and activation modes\n         (by representing different modes using different integers).\n         The more complex, variable-length parameters\n          (e.g. shape, axes permutation) are represented using the\n          string type according to the specified formats.\n          \\\\[1em]\n          \\footnotesize{\n            $^a$ Same representation as TASO \\cite{taso}.\n                 Normal and depth-wise convolutions are special cases\n                 of grouped convolutions. \\\\\n            $^b$ Axis permutation for transpose is specified\n                 using a string with format: axis$_1$\\_axis$_2$\\_\\dots .\\\\\n            $^c$ Pad a convolution kernel (input) with\n                 zeros to make it the same size as input $T_{\\sf ref}$ \\\\\n            $^d$ Split the tensor in the given axis. The position of the split is at the place of the most recent concat. \\\\\n            $^e$ Merge every \\textit{count} number of groups in the grouped convolution. See TASO \\cite{taso} for more details. \\\\\n          }\n    }\\label{table:ops}\n\\end{table}\n\n\n\\paragraph{Representing Rewrite Rules}\n\\label{sec:rewrite}\n\nA rewrite rule for tensor computation graph specifies that some local subgraph pattern (\\textit{source pattern}) is equivalent to another subgraph pattern (\\textit{target pattern}).\nThe input tensors to the source and target patterns are \\textit{variable nodes}, which can be substituted with any concrete nodes (or e-class in equality saturation) in the current graph.\nEach output tensor in the source pattern corresponds to an output tensor in the target pattern.\nThe two corresponding output nodes are called a pair of \\textit{matched outputs}.\nA rewrite rule states the equivalence between each pair of matched outputs.\n\nWe represent each source (and target) pattern using symbolic expressions (S-exprs) with variables.\nPatterns with a single output is represented with an S-expr rooted on the output.\nRewrite rules with such patterns are called \\textit{single-pattern rewrite rules}.\nPatterns with multiple outputs are represented as a list of S-exprs rooted on each output.\nRewrite rules with multiple matched outputs are called \\textit{multi-pattern rewrite rules}.\n% \\autoref{fig:rewrite} shows an example rewrite rule and its representation.\n\n% \\begin{figure}[t]\n%     \\centering\n%     \\includegraphics[width=\\linewidth, draft=true]{figures/rewrite-example.pdf}\n%     \\begin{scriptsize}\n%     Source: (matmul ?input$_1$ ?input$_2$), (matmul ?input$_1$ ?input$_3$) \\\\\n%     Target: (split$_0$ (split 1 (matmul ?input$_1$ (concat$_2$ 1 ?input$_2$ ?input$_3$)))), \\\\\n%     (split$_1$ (split 1 (matmul ?input$_1$ (concat$_2$ 1 ?input$_2$ ?input$_3$))))\n%     \\end{scriptsize}\n%     \\caption{\n%     Example rewrite rule and its representation in S-expressions.\n%     Identifiers starting with \"?\" denote variable nodes.\n%     For clarity, we omit the activation mode inputs to \\texttt{matmul}.\n%     Arrows point from parent nodes to children nodes.\n%     1 is the axis for \\texttt{split} and \\texttt{concat} operators.\n%     % The first argument to \\texttt{matmul} indicates which activation function to use.\n%     }\n%     \\label{fig:rewrite}\n% \\end{figure}\n\n\\subsection{Exploration Phase}\n\\label{sec:saturation}\n\nWe initialize the e-graph with the original tensor computation graph.\nIn each iteration of the exploration phase, we search for matches of all rewrite rules in the current e-graph, and add the target patterns and equivalence relations to the e-graph.\nThis process continues until either the e-graph saturates or a user-specified limit (in terms of time, e-graph size, or number of iterations) is reached.\nBefore applying a rewrite at a found match, we perform a \\textit{shape checking} to verify if the tensor shapes in the target pattern are compatible.\nThis is necessary since some rewrite rules requires input tensor shapes to satisfy specific preconditions, in addition to the syntactic match.\nWe perform shape checking in the same way as TASO \\cite{taso}.\n\n\n% \\paragraph{Multi-Pattern Rewrite Rules}\n\n% Multi-pattern rewrite rules are an important type of rules for tensor graph superoptimization \\cite{taso}.\n% However, most equality saturation toolkits only support efficient search methods to find matches for single-pattern rewrite rules \\cite{egg, ematching}.\n% We introduce an algorithm for applying multi-pattern rewrites, as shown in \\autoref{alg:multi}. Our algorithm leverages the existing efficient search routine for single-pattern rewrites as a subroutine.\n% %For clarity, we omit the handling of single-pattern rules and cycles here (those are described in \\autoref{alg:cycle}).\n\n% At the beginning of the exploration phase, we collect the set of unique S-exprs present in the source patterns of the rewrite rules after canonicalization.\n% Here, if one S-expr can be transformed into another S-expr by variable renaming only, they will be mapped to the same canonicalized S-expr.\n% In each iteration of the exploration phase, we use the single-pattern search subroutine to search for matches of the canonical S-exprs.\n% Then for each multi-pattern rule, we take the Cartesian product of the matches found, decanonicalize the variable-to-e-class map into the original variables (using the variable renaming map stored during canonicalization), and check if the matches are compatible at the shared variables between the S-exprs (i.e., if the shared variables refer to the same e-class after the mapping).\n% We apply the matches that are compatible.\n\n% \\begin{algorithm}[t]\n% \\small\n% \\caption{Applying multi-pattern rewrite rules}\n% \\label{alg:multi}\n% \\begin{algorithmic}[1]\n% \\Require starting e-graph $\\mathcal{G}$, set of multi-pattern rewrite rules $\\mathcal{R}_m$.\n% \\Ensure updated e-graph $\\mathcal{G}$.\n% \\State canonicalized S-expr $e_c$ = Set(\\{\\})\n% \\For{rule $r \\in \\mathcal{R}_m$ }\n% \\For{$i = 0, \\dots, |r|-1$ } \\Comment{{\\scriptsize $|r|$: \\#S-exprs in source pattern}}\n%     \\State ($e$, rename\\_map) = \\Call{Canonical}{$r$.source[$i$]}\n%     \\State $e_c$.insert($e$)\n%     \\State $r$.map[i] = rename\\_map\n% \\EndFor\n% \\EndFor\n\n%   \\For{iter = 0, \\dots, MAX\\_ITER}\n%     \\State $M$ = \\Call{Search}{$\\mathcal{G}, e_c$} \\Comment{all matches for all patterns}\n%     \\For{rule $r \\in \\mathcal{R}_m$ }\n%         \\For{$i = 0, \\dots, |r|-1$ }\n%         \\State canonical matches mc$_i$ = $M$[$r$.source[i]]\n%         \\State matches m$_i$ = \\Call{Decanonical}{mc$_i$, $r$.map[$i$]}\n%         \\EndFor\n%         \\For{$(\\sigma_0, \\dots, \\sigma_{|r|-1}) \\in$ m$_0 \\times \\dots \\times$ m$_{|r|-1}$}\n%             \\If{\\Call{Compatible}{$(\\sigma_0, \\dots, \\sigma_{|r|-1})$}}\n%             \\State \\Call{Apply}{$\\mathcal{G}, r, \\sigma_0, \\dots, \\sigma_{|r|-1}$}\n%             \\EndIf\n%         \\EndFor\n%     \\EndFor\n%   \\EndFor\n% \\State \\Return $\\mathcal{G}$\n% \\end{algorithmic}\n% \\end{algorithm}\n\n% In our experience, one feature of multi-pattern rules for tensor graph is that they can grow the e-graph extremely rapidly.\n% Let's consider again the example rewrite rule in \\autoref{fig:rewrite}.\n% This rule can be matched with any two \\texttt{matmul} nodes with a shared input (input$_1$).\n% By applying this rule once on some match, a new \\texttt{matmul} node will be created and added to the e-graph (the one on the RHS of \\autoref{fig:rewrite}), which also has input$_1$ as its input.\n% If the e-graph contains $N$ \\texttt{matmul} nodes that has some input$_1$ at the beginning, then after iteration 1, $\\mathcal{O}(N^2)$ new \\texttt{matmul} nodes sharing input$_1$ will be created.\n% In iteration 2, each pair in these $\\mathcal{O}(N^2)$ nodes will be a match, which will create $\\mathcal{O}(N^4)$ new nodes.\n% Such double exponential growth can quickly explode the e-graph.\n\n% Based on this feature, we set a separate limit $k_{\\textrm{multi}}$ on the number of iterations to apply the multi-pattern rules.\n% After $k_{\\textrm{multi}}$ iterations, we only apply the single-pattern rules until saturation or some user-specified limit.\n\n\n\\subsection{Extraction Phase}\n\nDuring extraction, the goal is to pick one e-node from each e-class in the e-graph to obtain an optimized graph.\nThe optimized graph should minimize the total cost with respect to a given cost model.\nIn tensor graph superoptimization, the cost model reflects the inference time taken by the graph.\n\n\\paragraph{Cost model}\nWe use the same cost model as TASO \\cite{taso}.\nEach operator has a separate and independent cost, which is the measured runtime of that operator (with the specific input sizes and parameters) on hardware.\nThe total cost of a graph is the sum of costs of each of its nodes.\nThis cost model is suitable for GPUs, since GPUs typically run one operator at a time when executing a graph.\nNote that an operator can be a fused operator, consisting of multiple primitive operators, such as a fused convolution and ReLU.\n\n\\label{sec:extraction}\n\n\\paragraph{Greedy extraction}\n\nWe first experiment with a greedy extraction strategy that has been shown to be effective for certain domains~\\cite{herbie, spores, egg}.\n%The first extraction method we experiment with is greedy extraction.\n%It has been shown to be a simple but effective method in multiple domains \\cite{herbie, spores, egg}.\nFor each e-class, the greedy strategy computes the total cost of the subtrees rooted on each of the e-nodes, and picks the e-node with the smallest subtree cost.\n\nGreedy extraction is not guaranteed to extract the graph with the minimum cost, even under our independent cost model.\nFor example, if two children of an e-node share a subgraph, greedy extraction would ignore the sharing and overestimate the cost.\n\n\\paragraph{ILP extraction}\nThe second approach we experiment with is formulating the extraction problem as an Integer Linear Program (ILP).\n\nLet $i = 0, ..., N-1$ be the set of e-nodes in the e-graph.\nLet $m = 0, ..., M-1$ be the set of e-classes in the e-graph.\nLet $e_m$ denote the set of e-nodes within e-class $m$: $\\{i | i\\in e_m \\}$.\nLet $h_i$ denote the set of children e-classes for e-node $i$.\nLet $g(i)$ denote the e-class of e-node $i$, i.e. $i\\in e_{g(i)}$.\nLet $m=0$ be the root e-class.\nEach e-node is associated with a cost $c_i$.\n\nWe then formulate our problem as follows:\n\\begin{align*}\n    &\\textrm{Minimize: } f(x) = \\sum_{i} c_i x_i\n\\end{align*}\nSubject to:\n\\begin{align}\n    &x_i \\in \\{0, 1\\}, \\\\\n    &\\sum_{i\\in e_0} x_i = 1, \\\\\n    &\\forall i, \\forall m \\in h_i, x_i \\leq \\sum_{j\\in e_m} x_j , \\\\\n    & \\forall i, \\forall m \\in h_i, t_{g(i)} - t_m - \\epsilon + A (1 - x_i) \\geq 0, \\\\\n    &\\forall m, 0 \\leq t_m \\leq 1,\n\\end{align}\n\nHere we introduce a binary integer variable $x_i$ for each e-node $i$; node $i$ is selected if $x_i=1$, and not selected otherwise.\nConstraint (2) ensures that one node is picked in the root e-class.\nConstraint (3) ensures that if a node is picked, then at least one node in each of its children e-classes needs to be picked.\nWe rely on the fact that at the optimal solution, each e-class can have at most one picked node (otherwise we can remove more picked nodes in this e-class to reduce the objective while still satisfying all the constraints).\nConstraints (1)--(3) and the objective encode the main extraction logic.\n\nA more subtle requirement on the extraction phase is that the extracted graph cannot contain cycles.\nWhile the e-graph can (and likely will) contain cycles, the extracted graph is meant to map directly to an executable tensor DAG.\nThe extraction procedure must therefore take care to respect the acyclic invariant of DAGs.\n\n% \\autoref{fig:cycle} shows an example to illustrate how valid rewrites can produce cycles in the e-graph.\nTo ensure the extracted graph does not contain cycles, we introduce a real variable $t_m$ for each e-class $m$ in the ILP.\nConstraint (4) ensures that the order defined by $t_m$'s is a valid topological order for the extracted graph.\nHere $\\epsilon < 1/M$ is a small constant for effectively encoding strict inequalities in ILP.\n$A$ is a large enough constant such that $A > 1 + \\epsilon$.\nConstraint (5) is to limit the range for the topological order variables $t_m$'s.\n\nWe also experiment with using integer variables for $t_m$'s. In this case, $t_m$'s are constrained to take integer values between 0 to $M-1$.\nConstraint (4) changes accordingly to: $\\forall i, \\forall m \\in h_i, t_{g(i)} - t_m + A (1 - x_i) \\geq 1$, where $A \\geq M$.\n\nUnlike greedy extraction, the optimal solution to the ILP is guaranteed to give a valid graph (no cycles) with the lowest cost.\n\n% \\begin{figure}\n%     \\centering\n%     \\includegraphics[width=\\linewidth, draft=true]{figures/cycle.pdf}\n%     \\caption{Example on how a valid rewrite can introduce cycles into the e-graph. RHS is the resulting e-graph after applying the rewrite rule from \\autoref{fig:rewrite} to the LHS. Dotted lines circles the e-classes. We omit the e-classes with a single node for clarity. If the node split$_1$ is picked in the right e-class, then the resulting graph will have a cycle (indicated by the red edges).}\n%     \\label{fig:cycle}\n% \\end{figure}\n\n\\paragraph{Cycle Filtering}\n\\label{sec:cycle}\n\nSimilar to previous work that uses ILP extraction \\cite{eqsat, spores},\nwe find that as the size of the e-graph grows bigger, the ILP solver takes a long time and becomes the main bottleneck.\nThis is mainly due to the cycle constraint (4): ILP solver struggles to find a feasible solution with these constraints.\nTherefore, we explore an alternative approach by filtering cycles during the exploration phase to make sure that the e-graph does not contain any cycles at the end of the exploration phase.\nThis way, we can get rid of the cycle constraints in the ILP.\n\n\\paragraph{Vanilla cycle filtering}\nThe first method is to check if applying a substitution introduces cycles to the e-graph, and discard such a substitution.\nThis check is run every time before applying a substitution.\nEach check requires a pass over the entire e-graph.\nFor one iteration during the exploration phase, if we denote $N$ as the current size of the e-graph and $n_m$ as the total number of matches of the rewrite rules on the e-graph, then this vanilla cycle filtering has complexity $\\mathcal{O}(n_m N)$.\n\n\\paragraph{Efficient cycle filtering}\n\nAs the number of matches $n_m$ is typically large and scales with $N$, vanilla cycle filtering can be slow.\nWe therefore design a novel and more efficient cycle filtering algorithm, consisting of a \\textit{pre-filtering} step and a \\textit{post-processing} step.\n%Intuitively, in the pre-filtering step, we run one pass over the e-graph and use the information to check a large number of substitutions.\n%Then we filter the remaining cycles in a post-processing steps.\n\\autoref{alg:cycle} shows the pseudocode for the exploration phase with efficient cycle filtering.\n\nAt the start of each iteration, we do one pass over the e-graph to record the set of descendent e-classes for each e-node (stored in a descendants map).\nDuring the iteration, for each match of the rewrite rules, we use the pre-stored descendants map to check if  applying a rewrite introduces cycles to the e-graph; if so, we skip this match.\nLine 3--9 implements the pre-filtering step.\nNotice that this check is sound but not complete: a match that passes this check can still introduce cycles to the e-graph.\nThis is because new descendants relations introduced by the previous rewrite in this iteration are not included in the pre-stored descendants map.\n\n\\begin{algorithm}[t]\n\\small\n\\caption{Exploration phase with efficient cycle filtering}\n\\label{alg:cycle}\n\\begin{algorithmic}[1]\n\\Require starting e-graph $\\mathcal{G}$, set of rewrite rules $\\mathcal{R}$.\n\\Ensure updated e-graph $\\mathcal{G}$, filter list $l$\n  \\State $l = $ $\\{\\}$\n  \\For{iter = 0, \\dots, MAX\\_ITER}\n    \\State descendants map $d$ = \\Call{GetDescendants}{$\\mathcal{G}, l$}\n    \\State matches = \\Call{Search}{$\\mathcal{G}, \\mathcal{R}, l$}\n    \\For{match $\\in$ matches}\n      \\If{\\Not \\Call{WillCreateCycle}{match, $d$}}\n        \\State \\Call{Apply}{$\\mathcal{G}$, match}\n      \\EndIf\n    \\EndFor\n    \\While{true}\n      \\State cycles = \\Call{DfsGetCycles}{$\\mathcal{G}, l$}\n      \\If{len(cycles) == 0}\n        \\State \\textbf{break}\n      \\EndIf\n      \\For{cycle $\\in$ cycles}\n        \\State \\Call{ResolveCycle}{$\\mathcal{G}, l$, cycle}\n      \\EndFor\n    \\EndWhile\n  \\EndFor\n  \\State \\Return $\\mathcal{G}, l$\n\\end{algorithmic}\n\\end{algorithm}\n\nTo resolve the cycles we missed in the pre-filtering step, we add a post-processing step at the end of each iteration (line 10-18).\nWe make a pass over the e-graph in DFS order and collect a set of cycles in the e-graph.\nFor each cycle, we choose the last node that is added to the e-graph, and add that node to a filter list.\nThe nodes in the filter list are considered as removed from the e-graph.\nWe make sure those nodes are not picked during extraction by explicitly adding constraints $\\forall i \\in l, x_i = 0$ to the ILP.\n\nBy constructing a descendants map once before each iteration, each of the checking in the pre-filtering step takes constant time.\nThe worst case complexity of the post-processing step is $\\mathcal{O}(n_c N)$, where $n_c$ is the number of cycles in the e-graph.\nSince $n_c$ is typically much smaller than $n_m$, this algorithm is much faster than the vanilla cycle filtering.\nIn practice, each DFS pass over the e-graph can find many cycles, which makes $\\mathcal{O}(n_c N)$ a very conservative upper bound.\n\n\\subsection{Evaluation}\n\nWe implemented \\ourname{} in Rust~\\cite{rust} using \\texttt{egg}~\\cite{egg}.\nFor the extraction phase, we use SCIP \\cite{scip} as the ILP solver, wrapped by Google OR-tools \\cite{ortools}.\n\nWe utilize egg's \\textit{e-class analysis} feature for the shape checking discussed.\nAn e-class analysis associates data with each e-class to support rewrites that are not purely syntactic.\nWe store all the relevant information of the tensors (shape, layout, split locations) in the analysis data and use these information for shape checking.\n\n\\paragraph{Experimental Setup}\n\nWe compareed \\ourname{} with TASO \\cite{taso} to evaluate our equality saturation based search.\nWe used the same set of rewrite rules as TASO for our experiments.\nWe evaluated on the inference graphs of 7 models:\n\\textbf{BERT} \\cite{bert}, \\textbf{ResNeXt-50} \\cite{resnext50}, \\textbf{NasNet-A} \\cite{nasneta}, \\textbf{NasRNN} \\cite{nasrnn}, \\textbf{Inception-v3} \\cite{inceptionv3},\n\\textbf{VGG-19} \\cite{vgg}, and \\textbf{SqueezeNet} \\cite{squeezenet}.\nThis benchmark set covers a wide range of commonly used state-of-the-art models, including both models for computer vision tasks and models for NLP tasks, both human-designed models and automatically-discovered models by neural architecture search.\nWe performed all experiments on a Google Cloud instance with one NVIDIA Tesla T4 GPU, a 16-core CPU, and 60 GB of memory.\n% We also experimented with ResNet-50 \\cite{resnet}, but find that on T4 GPU, the rewrite rules from TASO cannot provide any speedup to the graph.\n\nFor \\ourname{}, our full approach uses the efficient cycle filtering algorithm (\\autoref{sec:cycle}) during the exploration phase and the ILP method without the cycle constraints (\\autoref{sec:extraction}) for extraction.\nWe set a limit on the number of nodes in the e-graph $N_{\\textrm{max}}=50000$ and the number of iterations for exploration $k_{\\textrm{max}}=15$.\nWe terminate the exploration phase when any of the limit is reached, or the e-graph is saturated.\nWe set a separate limit $k_{\\textrm{multi}}$ on the number of iterations to apply the multi-pattern rules.\nWe use a default of $k_{\\textrm{multi}}=1$ for the main results in \\autoref{sec:speedup} and \\autoref{sec:time}.\n % and study the effect of varying $k_{\\textrm{multi}}$ in \\autoref{sec:multi-vary}.\nWe set a timeout of 1 hour for the ILP solver.\n\nFor TASO's backtracking search, we use their default settings from their artifact evaluation code on the number of iterations\\footnote{The number of iterations of the outer loop, see Algorithm 2 in \\cite{taso} for more details} $n=100$ and the hyperparameter $\\alpha=1.0$ for each benchmark.\nWe also test $\\alpha=1.05$ as mentioned in their paper, and find that the difference is tiny (difference in speedup percentage is less than 0.1\\% on average over the benchmarks).\nIncreasing to $n=1000$ leads to less than 1\\% speedup gain with the cost of over 11x longer in optimization time on average.\n\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[height=8cm]{tensat/all_speedup.pdf}\n  \\caption{\n    Speedup percentage of the optimized graph with respect to the original graph, TASO v.s. \\ourname{}.\n    Each setting (optimizer $\\times$ benchmark) is run for five times, and we plot the mean and standard error for the measurements.\n  }\\label{fig:speedup}\n  \\vspace{2em}\n\n  \\includegraphics[height=8cm]{tensat/all_optim_time.pdf}\n  \\caption{\n    Comparison of the optimization time (log scale) between TASO and \\ourname{}.\n    ``TASO total'' is the total time of TASO search.\n    ``TASO best'' indicates when TASO found its best result;\n    achieving this time would require an oracle telling it when to stop.\n  }\\label{fig:overhead}\n\\end{figure}\n\n\\paragraph{Program Speedup}\n\\label{sec:speedup}\n\nWe compare the speedup percentage of the optimized graph with respect to the original graph between \\ourname{} and TASO.\nWe use TASO's cuDNN backend to measure the runtime of the full computation graphs.\n\\autoref{fig:speedup} shows the results.\nWe can see that \\ourname{} discovers better optimized graphs compared with TASO's backtracking search in most benchmarks.\n\\ourname{}'s optimized graphs are on average 6.6\\% faster than TASO's. We see the biggest speedup of 23\\% over TASO on NasRNN.\nNote that for Inception-v3, \\ourname{} with $k_{\\textrm{multi}}=1$ gives a smaller speedup than TASO,\nbut increasing $k_{\\textrm{multi}}$ to 2 achieves a better speedup than TASO\nwhile still being 13.4$\\times$ faster than TASO's search (see \\autoref{fig:overhead}).\n\nThis improvement comes from the fact that equality saturation covers a much larger space of equivalent graphs than sequential backtracking search.\nBy using e-graph as a compact representation of an exponential number of equivalent graphs, \\ourname{} is able to cover orders of magnitude more equivalent graphs than TASO.\n\n\\paragraph{Optimization Time}\n\\label{sec:time}\n\nAnother important metric is the time taken by the optimizer itself.\nFor \\ourname{}, this is the sum of time taken by the exploration phase and the extraction phase.\nFor TASO, we record two times for a single backtracking search.\nThe first is the total time of the backtracking search with the default number of iterations ($T_{\\textrm{total}}$).\nThe second one is the time taken to first reach the best graph found during its search ($T_{\\textrm{best}}$).\n$T_{\\textrm{best}}$ is the best possible time for TASO's sequential backtracking search.\nIn practice, it is difficult (if not impossible) to achieve $T_{\\textrm{best}}$ since the sequential search algorithm would have no way to know that it can stop at that point.\n\n\\autoref{fig:overhead} shows the time taken by the optimizers across benchmarks.\nWe can see that \\ourname{} runs 9.5x to 379x faster than TASO's $T_{\\textrm{total}}$, and 1.8x to 260x times faster than $T_{\\textrm{best}}$.\nThis shows that \\ourname{} can not only cover a much larger search space, but also achieve this in drastically less time.\nFurthermore, \\ourname{}'s optimization time is small enough that we believe our approach can be integrated into a default compilation flow instead of running the search as an additional offline autotuning process.\n\n\n% \\paragraph{Varying Number of Iterations for Multi-Pattern Rewrites}\n% \\label{sec:multi-vary}\n\n% As we discuss in \\autoref{sec:saturation}, multi-pattern rewrite rules can grow the e-graph in a extremely rapid manner.\n% Here we study the effect of varying the number of iterations for multi-pattern rewrites $k_{\\textrm{multi}}$.\n% \\autoref{fig:trend} shows the results.\n% We can see the explosion of the number of nodes in the e-graph as $k_{\\textrm{multi}}$ increases (due to the double exponential growth).\n% For NasRNN, Inception-v3, BERT, NasNet-A, and ResNeXt-50, by increasing $k_{\\textrm{multi}}$, \\ourname{} discovers better graphs with larger speedups.\n% But for SqueezeNet, speedup decreases with $k_{\\textrm{multi}}$.\n% This is due to the discrepancy between the cost model and the real graph runtime.\n% As $k_{\\textrm{multi}}$ increases for SqueezeNet, the cost model suggests that certain new rewrites can reduce the cost, while they in fact increase full graph runtime.\n% Despite this special case where the discrepancy has an effect, \\ourname{} on SqueezeNet with $k_{\\textrm{multi}}=3$ still achieves a better speedup than TASO.\n% By increasing $k_{\\textrm{multi}}$, \\ourname{} can explore a larger search space and find better optimized graphs for most benchmarks, at the cost of longer time taken by the optimizer.\n\n% \\begin{figure}\n%     \\centering\n%     \\includegraphics[width=0.29\\hsize]{figures/speedup_trend.pdf}\n%     \\includegraphics[width=0.29\\hsize]{figures/optim_trend.pdf}\n%     \\includegraphics[width=0.29\\hsize]{figures/nodes_trend.pdf}\n%     \\includegraphics[width=0.09\\hsize]{figures/legend_trend.pdf}\n%     \\caption{Effect of varying the number of iterations of multi-pattern rewrites $k_{\\textrm{multi}}$.\n%     For BERT, NasNet-A, NasRNN, Inception-v3, the ILP solver times out at one hour for $k_{\\textrm{multi}}=3$.\n%     Left: speedup of the optimized graphs (the $y$-axis is split for clarity).\n%     Middle: time taken by the \\ourname{}.\n%     Right: final e-graph size (number of e-nodes).\n%     The middle and right figures are in log scale.\n%     }\n%     \\label{fig:trend}\n% \\end{figure}\n\n\n\n% \\paragraph{Ablation Study}\n% \\label{sec:ablation}\n\n% In this section, we study the effect of the important design choices in our approach.\n\n% \\paragraph{Greedy v.s. ILP extraction}\n\n% The first important design choice is the extraction method.\n% \\autoref{table:extraction} shows the comparison between greedy extraction and ILP extraction.\n% Although greedy extraction works fine on some benchmarks (e.g. NasRNN), it fails to extract an optimized graph on others (e.g. BERT and NasNet-A).\n% This is due to the nature of greedy extraction: it makes the choices on which node to pick separately and greedily, without considering the inter-dependencies between the choices.\n% Consider the rewrite in \\autoref{fig:rewrite} (merging two \\texttt{matmul}s by \\texttt{concat} and \\texttt{split}) as an illustrative example.\n% After applying this rewrite to the e-graph, there will be two e-classes that have multiple e-nodes: one e-class per each output.\n% This rewrite can reduce the cost only if both e-classes choose the split node, since the RHS subgraph can be reused by the two outputs.\n% However, greedy extraction will never pick the split nodes, since it does not know the RHS subgraph is shared between the two split nodes.\n\n% \\begin{table}[]\n%     \\centering\n%     \\begin{tabular}{cccc}\n%     \\hline\n%         {\\bf Graph Runtime (ms)} & {\\bf Original} & {\\bf Greedy} & {\\bf ILP} \\\\\n%     \\hline\n%         BERT & 1.88 & 1.88 & \\textbf{1.73} \\\\\n%         NasRNN & 1.85 & 1.15 & \\textbf{1.10} \\\\\n%         NasNet-A & 17.8 & 22.5 & \\textbf{16.6} \\\\\n%     \\hline\n%     \\end{tabular}\n%     \\caption{Comparison between greedy extraction and ILP extraction, on BERT, NasRNN, and NasNet-A.\n%     This table shows the runtime of the original graphs and the optimized graphs by greedy extraction and ILP extraction.\n%     The exploration phase is run with $k_{\\textrm{multi}} = 1$. }\n%     \\label{table:extraction}\n% \\end{table}\n\n% \\paragraph{ILP with or without cycle constraints}\n\n% Here we study the effect of whether or not to include the cycle constraints in ILP.\n% \\autoref{table:cycle} presents the effect on extraction time as $k_{\\textrm{multi}}$ (thus e-graph size) varies.\n% With the cycle constraints, ILP solver time quickly increases with the e-graph size, and reaches timeout when $k_{\\textrm{multi}}=2$.\n% In our experiments, the ILP solver has not yet found a feasible solution at timeout.\n% Removing the cycle constraints leads to approximately 10x--1000x speedup on ILP solving time on larger e-graphs.\n% These results show that the main difficulty for the ILP solver is to satisfy the cycle constraints.\n% Thus, removing the cycle constraints makes it possible for our approach to scale to larger e-graphs.\n\n% \\begin{table}[]\n%     \\centering\n%     \\begin{tabular}{ccccc}\n%     \\hline\n%         {\\bf Extraction} & \\multirow{2}{*}{\\bf $k_{\\textrm{multi}}$} & \\multicolumn{2}{c}{\\bf With cycle} & {\\bf Without} \\\\\n%         {\\bf time (s)} & & real & int & {\\bf cycle} \\\\\n%     \\hline\n%        \\multirow{2}{*}{BERT} & 1 & 0.96 & 0.98 & \\textbf{0.16} \\\\\n%        & 2 & $>$3600 & $>$3600 & \\textbf{510.3} \\\\\n%        \\hline\n%        \\multirow{2}{*}{NasRNN} & 1 & 1116 & 1137 & \\textbf{0.32}  \\\\\n%        & 2 & $>$3600 & $>$3600 & \\textbf{356.7}  \\\\\n%        \\hline\n%        \\multirow{2}{*}{NasNet-A} & 1 & 424 & 438 & \\textbf{1.81}  \\\\\n%        & 2 & $>$3600 & $>$3600 & \\textbf{75.1}  \\\\\n%     \\hline\n%     \\end{tabular}\n%     \\caption{Effect of whether or not to include cycle constraints in ILP on extraction time (in seconds), on BERT, NasRNN, and NasNet-A.\n%     For the cycle constraints, we compare both using real variables and using integer variables for the topological order variables $t_m$. }\n%     \\label{table:cycle}\n% \\end{table}\n\n% \\paragraph{Efficient cycle filtering}\n\n% To remove the cycle constraints from ILP, we need to perform cycle filtering during the exploration phase.\n% Here we compare the two cycle filtering techniques introduced in \\autoref{sec:cycle}.\n% \\autoref{table:efficient} shows the effect on the exploration phase time, as $k_{\\textrm{multi}}$ varies.\n% We can see that the efficient cycle filtering algorithm achieves up to 2000x speedup compared with the vanilla algorithm, making it possible to explore a larger e-graph.\n\n% \\begin{table}[]\n%     \\centering\n%     \\begin{tabular}{ccccccc}\n%     \\hline\n%         \\multirow{2}{*}{$k_{\\textrm{multi}}$} & \\multicolumn{2}{c}{BERT} & \\multicolumn{2}{c}{NasRNN} & \\multicolumn{2}{c}{NasNet-A} \\\\\n%         & Van. & Eff. & Van. & Eff. & Van. & Eff. \\\\\n%     \\hline\n%         1 & 0.18 & \\textbf{0.17} & 1.30 & \\textbf{0.08} & 3.76 & \\textbf{1.27} \\\\\n%         2 & 32.9 & \\textbf{0.89} & 2932 & \\textbf{1.47} & $>$3600 & \\textbf{8.62} \\\\\n%     \\hline\n%     \\end{tabular}\n%     \\caption{Comparison between vanilla cycle filtering and efficient cycle filtering, on the exploration phase time (in seconds) for BERT, NasRNN, and NasNet-A.}\n%     \\label{table:efficient}\n% \\end{table}\n\n\n%%% Local Variables:\n%%% TeX-master: \"../thesis\"\n%%% End:", "meta": {"hexsha": "608424ce1c0bf842eadb3a4827cb91abda650a18", "size": 42267, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/case-tensat.tex", "max_stars_repo_name": "mwillsey/thesis", "max_stars_repo_head_hexsha": "1706ea16107f60d8c43caff13ecdb57950896872", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-17T01:00:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-17T01:00:20.000Z", "max_issues_repo_path": "chapters/case-tensat.tex", "max_issues_repo_name": "mwillsey/thesis", "max_issues_repo_head_hexsha": "1706ea16107f60d8c43caff13ecdb57950896872", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/case-tensat.tex", "max_forks_repo_name": "mwillsey/thesis", "max_forks_repo_head_hexsha": "1706ea16107f60d8c43caff13ecdb57950896872", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 65.8364485981, "max_line_length": 402, "alphanum_fraction": 0.7225495067, "num_tokens": 10994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.3062035138101244}}
{"text": "% $Id: phystat2011_adye.tex 289 2011-05-05 19:21:23Z T.J.Adye $\n\\documentclass{cernrep}\n\\newcommand{\\babar}{\\mbox{\\slshape B\\kern-0.1em{\\small A}\\kern-0.1em B\\kern-0.1em{\\small A\\kern-0.2em R}}}\n\\newcommand{\\E}{\\mathrm{E}}\n\\newcommand{\\C}{\\mathrm{C}}\n\\newcommand{\\dd}[2]{\\frac{\\partial{#1}}{\\partial{#2}}}\n\n\\title{Unfolding algorithms and tests using RooUnfold}\n\\author{Tim Adye}\n\\institute{Particle Physics Department, Rutherford Appleton Laboratory, Didcot, United Kingdom.}\n\\begin{document}\n\\maketitle\n\n%========================================================================\n\\begin{abstract}\nThe RooUnfold package provides a common framework to evaluate and use\ndifferent unfolding algorithms, side-by-side. It currently provides\nimplementations or interfaces for the Iterative Bayes, Singular Value Decomposition, and\nTUnfold methods, as well as bin-by-bin and matrix inversion reference\nmethods. Common tools provide covariance matrix evaluation and\nmulti-dimensional unfolding. A test suite allows comparisons of the\nperformance of the algorithms under different truth and measurement models.\nHere I outline the package, the unfolding methods, and some experience of their use.\n\\end{abstract}\n%========================================================================\n\n\\section{RooUnfold package aims and features}\n\nThe RooUnfold package~\\cite{RooUnfold-web} was designed to provide a framework for different unfolding algorithms.\nThis approach simplifies the comparison between algorithms and has allowed\ncommon utilities to be written.\nCurrently RooUnfold implements or interfaces to the Iterative Bayes~\\cite{D'Agostini:1994zf,Bierwagen:PHYSTAT2011},\nSingular Value Decomposition (SVD)~\\cite{Hocker:1995kb,Kartvelishvili:PHYSTAT2011,Tackmann:PHYSTAT2011},\nTUnfold~\\cite{Schmitt-web}, bin-by-bin correction factors, and unregularized matrix inversion methods.\n\nThe package is designed around a simple object-oriented approach, implemented in\nC++, and using existing ROOT~\\cite{Brun:1997pa} classes. RooUnfold defines classes for the different\nunfolding algorithms, which inherit from a common base class, and a class for\nthe response matrix. The response matrix object is independent of the unfolding,\nso can be filled in a separate `training' program.\n\nRooUnfold can be linked into a stand-alone program, run from a ROOT/CINT script, or\nexecuted interactively from the ROOT prompt.\nThe response matrix can be initialized using existing histograms or matrices, or\nfilled with built-in methods (these can take care of the normalization when inefficiencies are to be considered).\nThe results can be returned as a histogram with errors, or a vector with full covariance matrix.\nThe framework also takes care of handling multi-dimensional distributions\n(with ROOT support for 1--, 2--, and 3--dimensional (1D,2D,3D) histograms),\ndifferent binning for measured and truth distributions,\nvariable binning, and the option to include or exclude under- and over-flows.\nIt also supports different methods for calculating the errors that can\nbe selected with a simple switch: bin-by-bin errors with no correlations,\nthe full covariance matrix from the propagation of measurement errors in the unfolding, or\nthe covariance matrix calculated using Monte Carlo (MC) toys.\n\nAll these details are handled by the framework, so do not have to be\nimplemented for each algorithm. However different bin layouts may not produce good results for\nalgorithms that rely on the global shape of the distribution (SVD).\n\nA toy MC test framework is provided, allowing\nselection of different MC probability density functions (PDF) and parameters,\ncomparing different binning, and performing the unfolding with the different\nalgorithms and varying the unfolding regularization parameters.\nTests can be performed with 1D, 2D, and 3D distributions.\nThe results of a few such tests are presented in section~\\ref{sec:adye:examples}.\n\n\n\n\\section{C++ classes}\n\nFigure~\\ref{Fig:adye:classes} summarizes how the ROOT and RooUnfold classes are used\ntogether. The RooUnfoldResponse object can be constructed using a 2D response histogram (TH2D)\nand 1D truth and measured projections (these are required to determine the effect of inefficiencies).\nAlternatively, RooUnfoldResponse can be filled directly with the\n\\texttt{Fill($x_{\\rm measured}$, $x_{\\rm true}$)}\nand\n\\texttt{Miss($x_{\\rm true}$)}\nmethods, where the \\texttt{Miss} method is used to count an event that was not measured\nand should be counted towards the inefficiency.%\n\\begin{figure}\n\\centerline{\\includegraphics[width=0.8\\textwidth]{phystat2011_adye_classes.eps}}\n\\caption\n[The RooUnfold classes.]%\n{The RooUnfold classes. The training truth, training measured, measured data, and unfolded distributions\ncan also be given as TH2D or TH3D histograms.}%\n\\label{Fig:adye:classes}%\n\\end{figure}\n\nThe RooUnfoldResponse object can be saved to disk using the usual ROOT input/output\nstreamers. This allows the easy separation in separate programs\nof MC training from the unfolding step.\n\nA RooUnfold object is constructed using a RooUnfoldResponse object and the measured\ndata. It can be constructed as a RooUnfoldBayes, RooUnfoldSvd, RooUnfoldTUnfold, (etc)\nobject, depending on the algorithm required.\n\nThe results of the unfolding can be obtained as ROOT histograms (TH1D, TH2D, or TH3D)\nor as a ROOT vector (TVectorD) and covariance matrix (TMatrixD). The histogram will\ninclude just the diagonal elements of the error matrix. This should be used with care,\ngiven the significant correlations that can occur if there is much bin-to-bin migration.\n\n\\section{Unfolding algorithms}\n\n\\subsection{Iterative Bayes' theorem}\n\nThe RooUnfoldBayes algorithm uses the method described by D'Agostini in~\\cite{D'Agostini:1994zf}.\nRepeated application of Bayes' theorem is used to invert the response matrix.\nRegularization is achieved by stopping iterations before reaching the `true'\n(but wildly fluctuating) inverse.\nThe regularization parameter is just the number of iterations.\nIn principle, this has to be tuned according to the sample statistics and binning.\nIn practice, the results are fairly insensitive to the precise setting used\nand four iterations are usually sufficient.\n\nRooUnfoldBayes takes the training truth as its initial prior, rather than a flat distribution,\nas described by D'Agostini.\nThis should not bias result once we have iterated, but could reach an optimum after fewer iterations.\n\nThis implementation takes account of errors on the data sample but not,\nby default, uncertainties in the response matrix due to finite MC statistics.\nThat calculation can be very slow, and usually the training sample is much larger\nthan the data sample.\n\nRooUnfoldBayes does not normally do smoothing, since this has not been found to be necessary\nand can, in principle, bias the distribution. Smoothing can be enabled with an option.\n\n\\subsection{Singular Value Decomposition}\n\nRooUnfoldSvd provides an interface to the\nTSVDUnfold class implemented in ROOT by Tackmann~\\cite{Tackmann:PHYSTAT2011}, which\nuses the method of H\\\"ocker and Kartvelishvili~\\cite{Hocker:1995kb}.\nThe response matrix is inverted using singular value decomposition,\nwhich allows for a linear implementation of the unfolding algorithm.\nThe normalization to the number of events is retained in order to minimize\nuncertainties due to the size of the training sample.\nRegularization is performed using a smooth cut-off on small singular value contributions\n($s_i^2 \\rightarrow s_i^2 / (s_i^2 + s_k^2)$, where the $k$th singular value defines the cut-off),\nwhich correspond to high-frequency fluctuations.\n\nThe regularization needs to be tuned according to the distribution, binning, and sample statistics\nin order minimize the bias due to the choice of the training sample (which dominates at small $k$)\nwhile retaining small statistical fluctuations in the unfolding result (which grow at large $k$).\n\nThe unfolded error matrix includes the contribution of uncertainties on the\nresponse matrix due to finite MC training statistics.\n\n\\subsection{TUnfold}\n\nRooUnfoldTUnfold provides an interface to the TUnfold method implemented in ROOT by Schmitt~\\cite{Schmitt-web}.\nTUnfold performs a matrix inversion with 0-, 1-, or 2-order polynomial regularization of neighbouring bins.\nRooUnfold automatically takes care of packing 2D and 3D distributions\nand creating the appropriate regularization matrix required by TUnfold.\n\nTUnfold can automatically determine an optimal regularization parameter ($\\tau$) by scanning the\n`L-curve' of $\\log_{10} \\chi^2$ vs $\\log_{10} \\tau$.\n\n\\subsection{Unregularized algorithms}\n\nTwo simple algorithms,\nRooUnfoldBinByBin, which applies MC correction factors with no inter-bin migration,\nand RooUnfoldInvert, which performs unregularized matrix inversion with singular value removal (TDecompSVD)\nare included for reference.\nThese methods are not generally recommended: the former risks biases from the MC model,\nwhile the latter can give large bin-bin correlations and magnify statistical fluctuations.\n\n\\section{Examples\\label{sec:adye:examples}}\n\nExamples of toy MC tests generated by RooUnfoldTest\nare shown in Figs.~\\ref{Fig:adye:bayes-example}--\\ref{Fig:adye:tunfold-example}.\nThese provide a challenging test of the procedure.\nCompletely different training and test MC models are used:\na single wide Gaussian PDF for training and a\ndouble Breit-Wigner for testing. In both cases\nthese are smeared, shifted, and a variable inefficiency\napplied to produce the `measured' distributions.%\n\\begin{figure}\n\\makebox[\\textwidth]{\\includegraphics[angle=-90,width=.640\\textwidth,clip]{phystat2011_adye_bayes1.eps}\\hfill\n                     \\includegraphics[angle=-90,width=.338\\textwidth,clip]{phystat2011_adye_bayes2.eps}}%\n\\caption\n[Unfolding with the Bayes algorithm.]%\n{Unfolding with the Bayes algorithm.\nOn the left, a double Breit-Wigner PDF on a flat background (green curve) is used to generate\na test `truth' sample (upper histogram in blue).\nThis is then smeared, shifted, and a variable inefficiency applied to produce\nthe `measured' distribution (lower histogram in red).\nApplying the Bayes algorithm with 4~iterations on this latter gave the unfolded result\n(black points), shown with errors from the diagonal elements of the error matrix.\nThe bin-to-bin correlations from the error matrix are shown on the right.}%\n\\label{Fig:adye:bayes-example}%\n\\end{figure}%\n\\begin{figure}\n\\makebox[\\textwidth]{\\includegraphics[angle=-90,width=.640\\textwidth,clip]{phystat2011_adye_svd1.eps}\\hfill\n                     \\includegraphics[angle=-90,width=.338\\textwidth,clip]{phystat2011_adye_svd2.eps}}%\n\\caption\n[Unfolding with the SVD algorithm]%\n{Unfolding with the SVD algorithm ($k=30$) on the same training and test\nsamples as described in Fig.~\\ref{Fig:adye:bayes-example}.}%\n\\label{Fig:adye:svd-example}%\n\\end{figure}%\n\\begin{figure}\n\\makebox[\\textwidth]{\\includegraphics[angle=-90,width=.640\\textwidth,clip]{phystat2011_adye_tunfold1.eps}\\hfill\n                     \\includegraphics[angle=-90,width=.338\\textwidth,clip]{phystat2011_adye_tunfold2.eps}}%\n\\caption\n[Unfolding with the TUnfold algorithm]%\n{Unfolding with the TUnfold algorithm ($\\tau=0.004$) on the same training and test\nsamples as described in Fig.~\\ref{Fig:adye:bayes-example}.\nHere we use two measurement bins for each truth bin.}%\n\\label{Fig:adye:tunfold-example}\n\\end{figure}\n\n\\section{Unfolding errors}\n\nRegularization introduces inevitable correlations between bins in the unfolded distribution.\nTo calculate a correct $\\chi^2$, one has to invert the covariance matrix:\n\\begin{equation}\n\\chi^2 = (\\mathbf{x}_{\\mathrm{measured}} - \\mathbf{x}_{\\mathrm{true}})^{\\mathrm{T}} \\mathbf{V}^{-1}\n         (\\mathbf{x}_{\\mathrm{measured}} - \\mathbf{x}_{\\mathrm{true}})\n\\end{equation}\n\nHowever, in many cases, the covariance matrix is poorly conditioned,\nwhich makes calculating the inverse problematic.\nInverting a poorly conditioned matrix involves subtracting large, but\nvery similar numbers, leading to significant effects due to the\nmachine precision.\n\n\\subsection{Unfolding errors with the Bayes method}\n\nAs shown on the left-hand side of Fig.~\\ref{fig:bayes_errors},\nthe uncertainties calculated by propagation of errors in the Bayes method\nwere found to be significantly underestimated compared to those given by the toy MC.\nThis was found to be due to an omission in the original method\noutlined by D'Agostini (\\cite{D'Agostini:1994zf}~section~4).%\n\\begin{figure}\n\\makebox[\\textwidth]{\\includegraphics[width=.47\\textwidth,clip]{phystat2011_adye_bayes_errors_old.eps}\\hfill\n                     \\includegraphics[width=.47\\textwidth,clip]{phystat2011_adye_bayes_errors_new.eps}}%\n\\caption\n[Bayesian unfolding errors compared to toy MC]%\n{Bayesian unfolding errors (lines) compared to toy MC RMS (points) for 1, 2, 3, and 9 iterations\non the Fig.~\\ref{Fig:adye:bayes-example} test.\nThe left-hand plot shows the errors using D'Agostini's original method,\nignoring any dependence on previous iterations (only the $M_{ij}$ term in Eq.~(\\ref{eq:dnCidnEj})).\nThe right-hand plot shows the full error propagation.}%\n\\label{fig:bayes_errors}%\n\\end{figure}\n\nThe Bayes method gives the unfolded distribution (`estimated causes'), $\\hat{n}(\\C_i)$,\nas the result of applying the unfolding matrix, $M_{ij}$, to the measurements (`effects'), $n(\\E_j)$:\n\\begin{equation}\n\\hat{n}(\\C_i) = \\sum_{j=1}^{n_{\\E}} M_{ij} n(\\E_j)\n\\quad\\mathrm{where}\\quad\nM_{ij} = \\frac{P(\\E_j|\\C_i) n_0(\\C_i)}{\\epsilon_i \\sum_{l=1}^{n_{\\C}} P(\\E_j|\\C_l) n_0(C_l)}\n\\label{eq:nCi}\n\\end{equation}\n\\noindent $P(\\E_j|\\C_i)$ is the $n_{\\E} \\times n_{\\C}$ response matrix,\n$\\epsilon_i \\equiv \\sum_{j=1}^{n_{\\E}} P(\\E_j|\\C_i)$ are efficiencies, and\n$n_0(C_l)$ is the prior distribution --- initially arbitrary (eg. flat or MC model), but updated on\nsubsequent iterations.\n\nThe covariance matrix, which here we call $V(\\hat{n}(\\C_k),\\hat{n}(\\C_l))$,\nis calculated by error propagation from $n(\\E_j)$,\nbut $M_{ij}$ is assumed to be itself independent of $n(\\E_j)$. That is only true for the first iteration.\nFor subsequent iterations, $n_0(\\C_i)$ is replaced by $\\hat{n}(\\C_i)$ from the\nprevious iteration, and $\\hat{n}(\\C_i)$ depends on $n(\\E_j)$ (Eq.~(\\ref{eq:nCi})).\n\nTo take this into account, we compute the error propagation matrix\n\\begin{equation}\n\\dd{\\hat{n}(\\C_i)}{n(\\E_j)} = M_{ij} + \\sum_{k=1}^{n_{\\E}} M_{ik} n(\\E_k)\n\\left( \\frac{1}{n_0(\\C_i)} \\dd{n_0(\\C_i)}{n(\\E_j)} - \\sum_{l=1}^{n_{\\C}} \\frac{\\epsilon_l}{n_0(\\C_l)} \\dd{n_0(\\C_l)}{n(\\E_j)} M_{lk} \\right)\n\\label{eq:dnCidnEj}\n\\end{equation}\nThis depends upon the matrix $\\dd{n_0(\\C_i)}{n(\\E_j)}$, which is $\\dd{\\hat{n}(\\C_i)}{n(\\E_j)}$ from the previous iteration.\nIn the first iteration, the second term vanishes ($\\dd{n_0(\\C_i)}{n(\\E_j)}=0$) and we get $\\dd{\\hat{n}(\\C_i)}{n(\\E_j)} = M_{ij}$.\n\nThe error propagation matrix can be used to obtain the covariance matrix on the unfolded distribution\n\\begin{equation}\nV(\\hat{n}(\\C_k),\\hat{n}(\\C_l)) = \\sum_{i,j=1}^{n_{\\E}} \\dd{\\hat{n}(\\C_k)}{n(\\E_i)} V(n(\\E_i),n(\\E_j)) \\dd{\\hat{n}(\\C_l)}{n(\\E_j)}\n\\label{eq:Vij}\n\\end{equation}\n\\noindent from the covariance matrix of the measurements, $V(n(\\E_i),n(\\E_j))$.\n\nWithout the new second term in Eq.~(\\ref{eq:dnCidnEj}),\nthe error is underestimated if more than one iteration\nis used, but agrees well with toy MC tests if the full error propagation is used,\nas shown in Fig.~\\ref{fig:bayes_errors}.%\n\n\\section{Status and plans}\n\nRooUnfold was first developed in the \\babar\\ software environment and\nreleased stand-alone in 2007.\nSince then, it has been used by physicists from many\ndifferent particle physics, particle-astrophysics, and nuclear physics groups.\nQuestions, suggestions, and bug reports from users\nhave prompted new versions with fixes and improvements.\n\nLast year I started working with a small group hosted by the\nHelmholtz Alliance, the Unfolding Framework Project\\cite{unfolding-project}.\nThe project is developing unfolding experience, software, algorithms, and performance tests.\nIt has adopted RooUnfold as a framework for development.\n\nDevelopment and improvement of RooUnfold is continuing.\nIn particular, determination of the systematic errors due to uncertainties on\nthe response matrix, and due to correlated measurement bins will be added.\nThe RooUnfold package will be incorporated into the ROOT distribution,\nalongside the existing TUnfold and TSVDUnfold classes.\n\n%========================================================================\n\n\\begin{thebibliography}{99}\n\n\\bibitem{RooUnfold-web}\n  The RooUnfold package and documentation are available from\\\\\n  \\verb=http://hepunx.rl.ac.uk/~adye/software/unfold/RooUnfold.html=\n\n\\bibitem{D'Agostini:1994zf}\n  G.~D'Agostini,\n  ``A Multidimensional unfolding method based on Bayes' theorem'',\n  Nucl.\\ Instrum.\\ Meth.\\  A {\\bf 362} (1995) 487.\n  %%CITATION = NUIMA,A362,487;%%\n\n\\bibitem{Bierwagen:PHYSTAT2011}\n  K.~Bierwagen,\n  ``Bayesian Unfolding'',\n% these proceedings.\n  presented at PHYSTAT 2011 (CERN, Geneva, January 2011), to be published in a CERN Yellow Report.\n\n\\bibitem{Hocker:1995kb}\n  A.~Hocker and V.~Kartvelishvili,\n  ``SVD Approach to Data Unfolding'',\n  Nucl.\\ Instrum.\\ Meth.\\  A {\\bf 372} (1996) 469.\n  % [arXiv:hep-ph/9509307].\n  %%CITATION = NUIMA,A372,469;%%\n\n\\bibitem{Kartvelishvili:PHYSTAT2011}\n  V.~Kartvelishvili,\n  ``Unfolding with SVD'',\n% these proceedings.\n  presented at PHYSTAT 2011 (CERN, Geneva, January 2011), to be published in a CERN Yellow Report.\n\n\\bibitem{Tackmann:PHYSTAT2011}\n  K.~Tackmann,\n  ``SVD-based unfolding: implementation and experience'',\n% these proceedings.\n  presented at PHYSTAT 2011 (CERN, Geneva, January 2011), to be published in a CERN Yellow Report.\n\n\\bibitem{Schmitt-web}\n  The TUnfold package is available in ROOT~\\cite{Brun:1997pa} and documented in\\\\\n  \\verb=http://www.desy.de/~sschmitt/tunfold.html=\n\n\\bibitem{Brun:1997pa}\n  R.~Brun and F.~Rademakers,\n  ``ROOT: An object oriented data analysis framework'',\n  Nucl.\\ Instrum.\\ Meth.\\  A {\\bf 389} (1997) 81.\n  %%CITATION = NUIMA,A389,81;%%\n  See also \\verb=http://root.cern.ch/=.\n\n\\bibitem{unfolding-project}\n  For details of the Unfolding Framework Project, see\\\\\n  \\verb=https://www.wiki.terascale.de/index.php/Unfolding_Framework_Project=\n\n\\end{thebibliography}\n\n\\end{document}\n", "meta": {"hexsha": "8bcc5b107b3afb39c96077122cbb22248899818d", "size": 18277, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/phystat2011/phystat2011_adye.tex", "max_stars_repo_name": "RhiannonSJ/SBND_Analysis_Tool", "max_stars_repo_head_hexsha": "e31378c59da54295e2fe58ab73dfee5d6cf7f7fd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/phystat2011/phystat2011_adye.tex", "max_issues_repo_name": "RhiannonSJ/SBND_Analysis_Tool", "max_issues_repo_head_hexsha": "e31378c59da54295e2fe58ab73dfee5d6cf7f7fd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/phystat2011/phystat2011_adye.tex", "max_forks_repo_name": "RhiannonSJ/SBND_Analysis_Tool", "max_forks_repo_head_hexsha": "e31378c59da54295e2fe58ab73dfee5d6cf7f7fd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.349862259, "max_line_length": 140, "alphanum_fraction": 0.7638014992, "num_tokens": 4909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521102, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.30620351381012434}}
{"text": "\\chapter{Electronic many-body problem}\\label{chap:electrons}\n\n{\\sffamily This chapter briefly reviews those basic building blocks of the electronic structure theory that are necessary for the presentation of the actual new work done for this thesis.\nThis comprises mostly the density functional theory, the adiabatic-connection fluctuation--dissipation framework, and the theory of the nonlocal dipole polarizability.\n}\n\n\\section{Schrödinger equation}\n\nThe role of the second Newton law ($\\mathrm d^2\\mathbf r/\\mathrm dt^2=\\mathbf F/m$) in nonrelativistic quantum mechanics is played by the Schrödinger equation, which therefore underlies all material discussed in this thesis.\nIn quantum mechanics, the state of a fixed number, $N$, of electrons in a molecule or a crystal is fully specified by a vector, $|\\Psi\\rangle$, from the $N$-electron Hilbert space.\nMeasurable properties of the state, such as energy, are expressed as Hermitian operators, whose eigenvalues are the possibly measured values of the property, the eigenvectors form a complete orthogonal basis of the Hilbert space, and the probability of measuring an eigenvalue corresponding to a given eigenvector is given by the square of the inner product of that eigenvector and the given state.\nThe operator for energy, called Hamiltonian, $\\hat H$, has a central role in quantum mechanics because it determines time evolution of the state via the Schrödinger equation,\n\\begin{equation}\n  \\frac{\\partial|\\Psi\\rangle}{\\partial t}=-\\mathrm i\\hat H|\\Psi\\rangle\n  \\makebox[0pt]{\\hspace{0.4\\linewidth}(in a.\\,u.)}\n  \\label{eq:schrodinger-time}\n\\end{equation}\nThis equation dictates that the phases of components of a state corresponding to different energy eigenstates oscillate at different rates, and eventually appear to be random for a system in equilibrium with its environment, so that one can regard the system as an ensemble of eigenstates of the Hamiltonian.\nBecause the probability of the $n$-th eigenstate ($n=0,1,\\ldots$) with energy $E_n$ at temperature $T$ is proportional to $\\exp(-E_n/T)$, and because the energy differences between electronic energy eigenstates typically count in at least thousands of kelvins ($1\\,\\mathrm{eV}\\doteq12\\,000\\,\\mathrm{K}$ in atomic units), most matter on Earth is found in the electronic ground state.\n\nThe nonrelativistic Hamiltonian for $N$ electrons ($i=1,\\ldots,N$) in electric potential $v_\\text{ext}(\\mathbf r)$ consists of three terms that correspond to the kinetic energy, potential energy, and interelectronic Coulomb repulsion,\n\\begin{equation}\n  \\hat H=\\sum_i\\frac{\\mathbf{\\hat p}_i^2}2-\\sum_i v_\\text{ext}(\\mathbf{\\hat r}_i)+\\sum_{i<j}\\frac1{|\\mathbf{\\hat r}_i-\\mathbf{\\hat r}_j|}\\equiv\\hat T+\\hat V_\\text{ext}+\\hat V_{ee}\n  \\label{eq:el-hamiltonian}\n\\end{equation}\nBecause electrons are fermions (particles with half-integer spin), the corresponding Hilbert space is antisymmetric, meaning that when any two electrons are exchanged, the resulting state vector must be equal to the negative of the original state vector.\nIn a free molecule or crystal, the nuclei at positions $\\mathbf R_A$ with charges $q_A$ generate the external potential for the electrons,\n\\begin{equation}\n  v_\\text{ext}(\\mathbf r)=\\sum_A\\frac{q_A}{|\\mathbf r-\\mathbf R_A|}\n\\end{equation}\nIn the basis of eigenstates of the position operators, $\\mathbf{\\hat r}_i$, and spin operators, $\\hat s_i$, one can define a wave function, $\\Psi(\\{\\mathbf r_i s_i\\})=\\langle\\mathbf r_i s_i|\\cdots\\langle\\mathbf r_N s_N|\\Psi\\rangle$, and the search for eigenvectors is then turned into a differential equation,\n\\begin{equation}\n  \\left(-\\sum_i\\frac{\\boldsymbol\\nabla_i^2}2-\\sum_i\\sum_A\\frac{q_A}{|\\mathbf r_i-\\mathbf R_A|}+\\sum_{i<j}\\frac1{|\\mathbf r_i-\\mathbf r_j|}-E\\right)\\Psi(\\mathbf r_1 s_1,\\ldots,\\mathbf r_N s_N)=0\n\\end{equation}\nThe wave function must be antisymmetric, and the solution of the equation gives possible values of the electronic energy, $E$, which are the eigenvalues of the Hamiltonian.\nThis equation cannot be solved analytically already for the simplest of systems, and formulating approximate, efficient, yet accurate methods for its solution is historically the biggest problem in quantum chemistry.\n\nThe spin variables are discrete ($s_i\\in\\{-\\frac12,\\frac12\\}$), and because we operate in nonrelativistic quantum mechanics, they do not enter the Hamiltonian, but only influence the form of the spatial dependence of the wave function via the requirement of the antisymmetry~\\cite{Pauncz79}.\nThe spin part of the wave function can be always written in terms of the one-electron spin functions, $\\uparrow\\!(s)$ and $\\downarrow\\!(s)$, whose values are either zero or one,\n\\begin{equation}\n\\begin{aligned}\n  \\uparrow\\!(\\tfrac12)&=1 & \\downarrow\\!(\\tfrac12)&=0 \\\\\n  \\uparrow\\!(-\\tfrac12)&=0 & \\downarrow\\!(-\\tfrac12)&=1\n\\end{aligned}\n\\end{equation}\nBecause of the antisymmetry, the probability of finding two electrons of the same spin at the same position is zero, $\\Psi(\\mathbf rs,\\mathbf rs,\\ldots)=0$, which is also called the Pauli exclusion principle.\n\n\\section{Variational method and energy functionals}\n\nOne of the oldest approaches to finding the ground state, but also a foundation of many modern methods, is based on the fact that the eigenstates of the Hamiltonian, $|\\psi_n\\rangle$, form a complete basis,\n\\begin{equation}\n\\begin{aligned}\n  \\langle\\Psi|\\hat H|\\Psi\\rangle\n  &=\\langle\\Psi|\\hat H\\sum_n|\\psi_n\\rangle\\langle\\psi_n|\\Psi\\rangle\n  =\\sum_n E_n\\langle\\Psi|\\psi_n\\rangle\\langle\\psi_n|\\Psi\\rangle \\\\\n  &\\geq E_0\\sum_n\\langle\\Psi|\\psi_n\\rangle\\langle\\psi_n|\\Psi\\rangle=E_0\\langle\\Psi|\\Psi\\rangle=E_0\n\\end{aligned}\n\\end{equation}\nAs a result, the expectation value of the Hamiltonian is never smaller than the ground-state energy, and if the energy is understood as a functional of a wave function, $E[\\Psi]$, the ground state can be found at its minimum,\n\\begin{equation}\n  |\\psi_0\\rangle=\\operatorname*{arg\\,min}_{|\\Psi\\rangle}E[\\Psi]\n  \\label{eq:minimization}\n\\end{equation}\n(In fact all eigenstates can be gradually found in this fashion, by requiring that they are orthogonal to all the lower-energy eigenstates.)\n\nBecause all terms in the Hamiltonian are either one- or two-electron, do not depend on spin, and the wave function is antisymmetric, the expression for the energy functional can be simplified by partial integrations over $\\Psi$~\\cite{Parr89},\n\\begin{equation}\n  E[\\Psi]=\\int\\mathrm d\\mathbf r\\,\\big(-\\tfrac12\\boldsymbol\\nabla_{\\mathbf r'}^2 \\gamma(\\mathbf r,\\mathbf r')\\!\\big)\\big|_{\\mathbf r'=\\mathbf r}+\\int\\mathrm d\\mathbf r\\,v_\\text{ext}(\\mathbf r)n(\\mathbf r)+\\frac12\\iint\\mathrm d\\mathbf r_1\\mathrm d\\mathbf r_2\\frac{n_2(\\mathbf r_1,\\mathbf r_2)}{|\\mathbf r_1-\\mathbf r_2|}\n  \\label{eq:master-energy-functional}\n\\end{equation}\nThe energy is then expressed in terms of the first-order density matrix, $\\gamma(\\mathbf r,\\mathbf r')$, the electron-pair density, $n_2(\\mathbf r_1,\\mathbf r_2)$, and the electron density, $n(\\mathbf r)=\\gamma(\\mathbf r,\\mathbf r)$.\nIn principle, the ground-state energy can be found just as well by minimizing this energy functional over all $n$, $\\gamma$, and $n_2$ that originate from the same wave function.\nBut this latter search constraint, called the $N$-representability problem, is what makes this approach unfeasible, because the sufficient conditions for $n_2$ to be $N$-representable are unknown.\\footnote{\nMore precisely, the energy functional is a functional of the second-order density matrix, $\\gamma_2(\\mathbf r_1\\mathbf r_2,\\mathbf r'_1\\mathbf r'_2)$, from which $n_2(\\mathbf r_1,\\mathbf r_2)=2\\gamma_2(\\mathbf r_1\\mathbf r_2,\\mathbf r_1\\mathbf r_2)$ and $\\gamma_1(\\mathbf r,\\mathbf r')=2\\int\\mathrm d\\mathbf r_2\\gamma_2(\\mathbf r\\mathbf r_2,\\mathbf r'\\mathbf r_2)/(N-1)$, and it is $\\gamma_2$ for which the sufficient $N$-representability conditions are not known.\n}\nThe electron-pair density can be written in terms of the electron density and a pair correlation (distribution) function, $g(\\mathbf r_1,\\mathbf r_2)$,\n\\begin{equation}\n  n_2(\\mathbf r_1,\\mathbf r_2)=n(\\mathbf r_1)n(\\mathbf r_2)g(\\mathbf r_1,\\mathbf r_2)\n\\end{equation}\nIf the motions of the electrons were uncorrelated, the pair correlation function would be equal to 1, but in reality the wave-function antisymmetry and the interelectronic Coulomb term cause it to deviate from 1.\nBy using $g=1-(1-g)$, the interelectronic energy term can be naturally split into a classical part (also called the Hartree energy), which is simply the electrostatic energy, $J[n]$, of the electron charge density, and a nonclassical correction,\n\\begin{equation}\n  \\langle\\Psi|\\hat V_{ee}|\\Psi\\rangle=J[n]-\n  \\frac12\\iint\\mathrm d\\mathbf r_1\\mathrm d\\mathbf r_2\\frac{n(\\mathbf r_1)n(\\mathbf r_2)}{|\\mathbf r_1-\\mathbf r_2|}\\big(1-g(\\mathbf r_1,\\mathbf r_2)\\!\\big)\n\\end{equation}\nThe total electronic energy can then be written as a sum of four terms,\n\\begin{equation}\n  E[\\Psi]=T[\\gamma]+V_\\text{ext}[n]+J[n]+\\text{nonclassical term}\n  \\label{eq:energy-nonclassical}\n\\end{equation}\n\n\\section{Mean-field models}\n\nUnlike the spin part of the wave function, the spatial part cannot be in general expressed in terms of one-electron functions because of the Coulomb force between electrons.\nFor instance, the ground state of harmonium, a two-electron system described by the Hamiltonian in~\\eqref{eq:el-hamiltonian} with $v_\\text{ext}(\\mathbf r)=r^2/8$, has the form\n\\begin{equation}\n  \\psi_0(\\mathbf r_1s_1,\\mathbf r_2s_2)\\sim\\big(1+\\tfrac12|\\mathbf r_1-\\mathbf r_2|\\big)\\exp\\big(-\\tfrac14(r_1^2+r_2^2)\\big)(\\uparrow\\downarrow-\\downarrow\\uparrow)\n\\end{equation}\nThe simple prefactor $(1+\\frac12 r_{12})$ is caused by the Coulomb term, and makes the two electrons more likely to be found far apart than close to each other.\nIn contrast to the Pauli principle though, the Coulomb term is not strong enough to make the electrons completely avoid each other, and $\\psi_0(\\mathbf r,\\mathbf r)\\neq0$.\nUnfortunately, harmonium is the only many-electron system with a known exact wave function in a closed form, and realistic calculations of common systems require approximate models.\n\n\\begin{figure}\n\\includegraphics[center]{media/exchange.pdf}\n\\caption{\\textbf{Antisymmetrization.}\nContour plots of the square of a wave function, $|\\Psi(x_1,x_2)|^2$, of two particles in one dimension formed from two one-particle functions, $\\phi_1(x)=\\exp(-x^2)$ and $\\phi_2(x)=\\exp(-x^2/2)$.\nOn the left, $\\Psi$ is a simple product.\nOn the right, $\\Psi$ is an antisymmetrized product, $\\phi_1(x_1)\\phi_2(x_2)-\\phi_1(x_2)\\phi_2(x_1)$.\nThe contour levels in both plots are equal.\n}\\label{fig:exchange}\n\\end{figure}\n\nAlthough true many-electron wave functions cannot be built from one-electron functions (also called orbitals), such constructs form the basis of almost all approximate electron models.\nAn antisymmetrized product of spin-orbitals, $\\phi_j(\\mathbf r_i s_i)$, is called a Slater determinant, $\\mathcal D(\\{\\phi_j\\})$, and the approximate many-electron wave function thus formed is characterized by a simple expression for the one-electron density matrix, $\\gamma(\\mathbf r,\\mathbf r')=\\sum_{s}\\sum_j f_j\\phi_j^*(\\mathbf rs)\\phi_j(\\mathbf r's)$, in which $f_j\\in\\{0,1\\}$ are the occupation numbers of the orbitals.\n(Generalizing from here, any $N$-representable density matrix can be expressed in this form by allowing any $0\\leq f_j\\leq1$.)\nMinimizing $E[\\Psi]$ with respect to this Slater-type wave function is called the Hartree--Fock (HF) approximation.\nThe antisymmetrization of same-spin electrons works on the spatial part of the wave function (Fig.~\\ref{fig:exchange}), and of opposite-spin electrons on the spin part.\nAs a result of this, the pair correlation function for opposite-spin electrons in a Slater determinant is equal to 1, whereas that of the same-spin electrons is modified ($n^\\uparrow=n^\\downarrow=n/2$ for simplicity),\n\\begin{equation}\n  g^{\\uparrow\\uparrow}(\\mathbf r_1,\\mathbf r_2)=g^{\\downarrow\\downarrow}(\\mathbf r_1,\\mathbf r_2)=1-\\frac{|\\gamma(\\mathbf r_1,\\mathbf r_2)|^2}{n(\\mathbf r_1)n(\\mathbf r_2)}\\qquad\n  g^{\\uparrow\\downarrow}(\\mathbf r_1,\\mathbf r_2)=1\n\\end{equation}\nIn line with the Pauli principle, the pair correlation function of same-spin electrons in the HF model starts at zero when $\\mathbf r_1$ equals $\\mathbf r_2$, but then goes quickly to 1, around which it slowly oscillates with decreasing amplitude as $r_{12}$ increases.\n(In sodium, for instance, $g$ reaches 0.99 already at $|\\mathbf r_1-\\mathbf r_2|\\approx 0.25$\\,\\AA.)\n\nThe modification of $g$ from 1 due to the antisymmetry reduces the short-range repulsion between same-spin electrons, and this part of the nonclassical term in~\\eqref{eq:energy-nonclassical} is called the exchange energy,\n\\begin{equation}\n  K[\\gamma]=-\\frac14\\iint\\mathrm d\\mathbf r_1\\mathrm d\\mathbf r_2\\frac{|\\gamma(\\mathbf r_1,\\mathbf r_2)|^2}{|\\mathbf r_1-\\mathbf r_2|}\n\\end{equation}\nWhen incorporated into the exact energy functional, the remaining part of the electronic energy is called the correlation energy (despite the fact that the exchange energy also originates from a nontrivial pair correlation function),\n\\begin{equation}\n  E[\\Psi]=T[\\gamma]+V_\\text{ext}[n]+J[n]+K[\\gamma]+\\text{correlation}\n  \\label{eq:energy-with-exchange}\n\\end{equation}\nOmitting the correlation part and minimizing this functional with respect to all $N$-representable density matrices ($f_j\\in\\{0,1\\}$ is obtained as a result) leads to the HF one-electron equations, which describe the motion of an electron in the mean field generated by all the other electrons (hence then name ``mean-field'' methods).\nIn most molecules and nonconducting solids, the basic structure of the ground-state wave function is dominated by the kinetic energy, and the HF approximation works quite well in such cases, failing only quantitatively to account for the opposite-spin correlation and the small Coulomb correction to the same-spin correlation.\nStill, two fundamental problems exist:\nFirst, the Coulomb interaction becomes as important as the kinetic energy for the wave-function structure\\footnote{\nMore precisely, the functional derivatives of the Coulomb energy and the kinetic energy with respect to the wave function become equally important.}\nin metals, certain special materials (such as Mott insulators), and spin-unpaired (open-shell) systems, and the missing opposite-spin correlation leads to qualitatively wrong wave functions in such cases.\nFor instance, it leads to spurious preference to ``cluster'' same-spin electrons together, leading to the formation of unphysical spin waves in metals in the HF approximation~\\cite{OverhauserPR62}.\nSecond, the long-range finer structure of the wave function is dominated by the Coulomb interaction, not by the antisymmetry, leading to complete neglect of vdW interactions in the HF approximation.\n\nApproximating the correlation energy as a functional of the one-electron density matrix and minimizing that functional with respect to $\\gamma$ leads to the density-matrix functional theory (of which the HF method is a special case).\nGoing further, the post-HF methods of quantum chemistry construct more complex wave functions on top of the Slater determinant, and approximate the correlation energy either by reapplying the variational technique or using the perturbation theory with the correlation term in the functional being the perturbation.\nUsing linear combinations of Slater determinants instead of a single one leads to the class of multi-configurational methods.\n\n\\section{Diffusion quantum Monte Carlo}\\label{sec:dqmc}\n\nThe diffusion quantum Monte Carlo (DQMC) is a practical numerical method to calculate the exact electronic ground-state energy that uses the mean-field wave functions of the previous section only indirectly~\\cite{FoulkesRMP01}.\nCalculations performed for this thesis use it indirectly via the parametrization of effective electron models introduced below, as well as directly to calculate reference binding energies in Chapter~\\ref{chap:pi-pi}.\n\nDQMC is based on the fact that the imaginary-time evolution operator of~\\eqref{eq:schrodinger-time} projects out the true ground state in the limit of the infinite time because the excited states have a higher energy and decay faster,\n\\begin{equation}\n  \\exp(-\\tau\\hat H)|\\Psi\\rangle=\\sum_n\\exp(-\\tau E_n)|\\psi_n\\rangle\\xrightarrow{\\tau\\rightarrow\\infty}\\exp(-\\tau E_0)|\\psi_0\\rangle\n  \\label{eq:dqmc}\n\\end{equation}\nThis fact becomes numerically useful by reinterpreting the corresponding wave function as a distribution of particles and the evolution operator as describing a stochastic diffusion-and-branching process of these particles.\n(In fact, this process can also be interpreted as a stochastic gradient-descent minimization of the Hamiltonian expectation value, directly connecting DQMC to the standard variational techniques~\\cite{SchwarzPRL17}.)\nThe ground-state wave function and energy can then be obtained by stochastically evolving the particles with $\\exp(-\\tau(\\hat H-E))$, while adjusting $E$ such that the number of the particles is kept constant, so that $E$ eventually converges to $E_0$.\nEnding the evolution process before infinite time gives the wave function and energy with some limited, but statistically known and arbitrarily good accuracy.\nThe correspondence between the wave function and the particle distribution is only valid when the wave function is positive everywhere.\nThis is true for the ground state of distinguishable or bosonic particles, but not for the ground state of fermions (electrons), which must be antisymmetric (for more than one particle).\nThis makes direct application of DQMC to electrons impractical without further approximations.\n\nThe $(3N-1)$-dimensional plane of points at which the wave function of $N$ electrons is zero is called the nodal surface.\nIn general, it is no less complicated than the full wave function, and the $(3N-3)$-dimensional coincidence plane at which $\\mathbf r_i=\\mathbf r_j$ and $\\Psi=0$ by antisymmetry forms only its lower-dimensional scaffold~\\cite{CeperleyJSP91}.\nIf the nodal surface of the ground-state wave function was known, the full wave function could be recovered by running a DQMC simulation independently in each nodal pocket, in which the wave function does not change sign.\nThe fixed-node approximation then uses the nodal surface of some approximate wave function to determine these independent DQMC simulations.\nBecause this effectively restricts the wave function to a certain form, the obtained approximate ground-state energy is variationally guaranteed to be higher than the true energy.\n\nModified Slater-type wave functions obtained from mean-field methods (either HF or KS-DFT, described below) are usually used to determine the nodal surface in the fixed-node approximation.\nThe missing correlation (in the sense of a pair correlation function) in the Slater determinant, $\\mathcal D$, due to the Coulomb interaction is added in an ad-hoc way via the so-called Jastrow factor, $\\mathcal J$,\n\\begin{equation}\n\\begin{gathered}\n  \\Psi(\\{\\mathbf r_i s_i\\})=\\exp\\big(\\mathcal J(\\{\\mathbf r_i s_i\\})\\!\\big)\\mathcal D(\\{\\mathbf r_i s_i\\}) \\\\\n  J(\\{\\mathbf r_i s_i\\})=\\sum_i u_1(\\mathbf r_i s_i)+\\sum_{i<j} u_2(\\mathbf r_i s_i,\\mathbf r_j s_j)\n\\end{gathered}\n\\end{equation}\nThe two-electron Jastrow functions, $u_2$, decrease the probability of two electrons coming close to each other (different for same- and opposite-spin electron pair), while the one-electron functions, $u_1$, restore the electron density of $\\mathcal D$ that would be otherwise somewhat diffused by the two-electron Jastrow functions.\nThe particular forms of $u_1$ and $u_2$ are mostly a result of experimentations and can be found for instance in~\\cite{FoulkesRMP01}.\n\n\\section{Density-functional theory}\n\nThe theoretical framework presented in this section has led to the most widely used methods for calculating the electronic structure of molecules and materials, and it is the lack of vdW interactions in its most popular approximations that renewed the theoretical interest in vdW interactions.\nIt provides the context, motivation, as well as essential tools for most of the work in this thesis.\n\nOne can try to go one step further from the density-matrix functional theory, and express the electronic energy in terms of the electron density only, resulting in the density-functional theory (DFT).\nThat this is in principle possible was shown by \\citet{HohenbergPR64} and later more rigorously by \\citet{LevyPNAS79}, who divided the minimization in~\\eqref{eq:minimization} over all antisymmetric wave functions in two steps, one over wave functions with a given density, the other over all densities, thus establishing the Hohenberg--Kohn functional, $F_\\text{HK}$,\n\\begin{equation}\n\\begin{aligned}\n  E_0&=\\min_\\Psi E[\\Psi]=\\min_n\\min_{\\Psi\\rightarrow n}E[\\Psi]=\\min_n\\big(\\min_{\\Psi\\rightarrow n}(T[\\Psi]+V_{ee}[\\Psi])+V_\\text{ext}[n]\\big) \\\\\n  &\\equiv\\min_n(F_\\text{HK}[n]+V_\\text{ext}[n])\\equiv\\min_n(E[n])\n\\end{aligned}\n\\end{equation}\nIf a given input density of the Hohenberg--Kohn functional, $F_\\text{HK}$, is $v$-representable, meaning that there is some external potential (other than $V_\\text{ext}$) of which ground state has that density, then the minimizing wave function, $\\Psi_\\text{HK}$, is the ground state for the corresponding external potential.\nFor densities that are not $v$-representable, the HK functional is still well-defined.\nIn either case, one can define the kinetic-energy functional, $T[n]\\equiv T[\\Psi_\\text{HK}]$, and $V_{ee}[n]\\equiv V_{ee}[\\Psi_\\text{HK}]$.\nThe task of DFT is then to devise sufficiently accurate approximations to $T[n]$ and $V_{ee}[n]$.\n(The theory can be equivalently formulated using the electron spin densities, $n_\\uparrow(\\mathbf r)$ and $n_\\downarrow(\\mathbf r)$, which gives a more useful framework for approximations in the case of spin-polarized systems.)\n\nHistorically, the development of DFT was hampered by unsuccessful attempts at the kinetic-energy functional, whose various approximate formulations explicitly in terms of the electron density fail to reproduce any electronic shell structure in atoms.\nThis problem was largely solved by \\citet{KohnPR65}, KS, who approximated the true kinetic energy with that of an auxiliary system of noninteracting electrons ($V_{ee}=0$) having the same density as the actual system,\n\\begin{equation}\n\\begin{aligned}\n  T[n]&=T[\\Psi_\\text{HK}]=T\\big[\\operatorname*{arg\\,min}_{\\Psi\\rightarrow n}(T[\\Psi]+V_{ee}[\\Psi])\\big] \\\\\n  &\\approx T\\big[\\operatorname*{arg\\,min}_{\\Psi\\rightarrow n}T[\\Psi]\\big]=\\min_{\\Psi\\rightarrow n}T[\\Psi]\\equiv T_\\text{s}[n]\n\\end{aligned}\n\\label{eq:ks-kinetic}\n\\end{equation}\nThe wave function minimizing $T_\\text{s}$, $\\Psi_\\text{s}$, is always of the Slater type, and would in fact be a ground state of the noninteracting system if it was put in a particular external potential, called the KS potential,\\footnote{\nMore precisely, it would be a ground state only if the given density is noninteracting $v$-representable, otherwise it would be an excited state.\n}\n\\begin{equation}\n  v_\\text{s}(\\mathbf r)=-\\frac{\\delta T_\\text{s}[n]}{\\delta n(\\mathbf r)}\n\\end{equation}\nAfter the KS approximation, the remaining unknown terms are collected in the so-called exchange--correlation (XC) functional (so named despite the contained kinetic-energy correction),\n\\begin{equation}\n\\begin{aligned}\n  E[n]&=T_\\text{s}[n]+V_\\text{ext}[n]+J[n]+(T[n]-T_\\text{s}[n]+V_{ee}[n]-J[n]) \\\\\n  &\\equiv T_\\text{s}[n]+V_\\text{ext}[n]+J[n]+E_\\text{xc}[n]\n  \\label{eq:ks-dft-energy}\n\\end{aligned}\n\\end{equation}\nThe aim of KS-DFT is then to search for approximate formulations of $E_\\text{xc}$ expressed explicitly in terms of the electron density.\n\nMinimization of this functional with respect to $N$-representable densities leads to the KS one-electron equations (another mean-field model, but unlike the HF model, exact in principle), whose structure differs from the HF equations mathematically only in that their effective mean-field potential is local rather than nonlocal,\n\\begin{equation}\n\\begin{aligned}\n  v_\\text{xc}(\\mathbf r)&=v_\\text{ext}(\\mathbf r)+\\frac{\\delta(J[n]+E_\\text{xc}[n])}{\\delta n(\\mathbf r)} \\\\\n  v_\\text{HF}(\\mathbf r,\\mathbf r')&=\\left(v_\\text{ext}(\\mathbf r)+\\frac{\\delta J[n]}{\\delta n(\\mathbf r)}\\right)\\delta(\\mathbf r-\\mathbf r')+\\frac{\\delta K[\\gamma]}{\\delta\\gamma(\\mathbf r,\\mathbf r')}\n\\end{aligned}\n\\end{equation}\nThis difference makes the KS equations somewhat less complex, and more efficient to solve numerically, which is one of the reasons for the popularity of KS-DFT over the HF method.\nAt the minimum of $E[n]$, the effective-mean field potential of the KS equations, $v_\\text{xc}(\\mathbf r)$, is equal to the KS potential of the auxiliary noninteracting system, $v_\\text{s}(\\mathbf r)$.\n\n\\section{Adiabatic-connection fluctuation--dissipation theorem}\n\nThis section introduces the starting point for the classification of vdW methods presented in Chapter~\\ref{chap:vdw-methods}.\nThe auxiliary KS system of noninteracting electrons can be adiabatically connected to the real system by slowly turning on the interelectronic Coulomb interaction, $\\lambda\\hat V_{ee}$, from $\\lambda=0$ to $\\lambda=1$, while keeping the electron density constant by adjusting the Kohn--Sham potential.\n\\begin{equation}\n\\begin{gathered}\n  F_\\text{HK}(\\lambda)[n]=\\min_{\\Psi\\rightarrow n}(T[\\Psi]+\\lambda V_{ee}[\\Psi])\\qquad\n  v_\\text{s}(\\mathbf r;\\lambda)=-\\frac{\\delta F_\\text{HK}(\\lambda)[n]}{\\delta n(\\mathbf r)} \\\\\n  E(\\lambda)[n]=F_\\text{HK}(\\lambda)[n]+V_\\text{s}(\\lambda)[n]\n\\end{gathered}\n\\end{equation}\nThe standard HK functional and KS potential are recovered for $\\lambda=1$ and $\\lambda=0$, respectively, whereas the Kohn--Sham potential for the true system reduces to the external potential, $V_\\text{s}(1)[n]=V_\\text{ext}[n]$.\nThe true electronic energy ($\\lambda=1$) can be obtained from the noninteracting energy ($T_\\text{s}[n]+V_\\text{s}[n]$) by integrating over $\\mathrm dE/\\mathrm d\\lambda$,\n\\begin{equation}\n  E(1)[n]=E(0)[n]+\\int_0^1\\mathrm d\\lambda\\frac{\\mathrm d E(\\lambda)[n]}{\\mathrm d\\lambda}\n  \\label{eq:adiabatic-connection}\n\\end{equation}\nBecause the process is adiabatic, the system is in the ground state at any point, so the HK functional is stationary with respect to the wave function of the system ($\\delta F_\\text{HK}/\\delta\\Psi=0$), and the expression for $\\mathrm dE/\\mathrm d\\lambda$ reduces to a simple formula (this is also called the Hellmann--Feynman theorem),\n\\begin{equation}\n\\begin{aligned}\n  \\frac{\\mathrm d E(\\lambda)[n]}{\\mathrm d\\lambda}&=\\frac{\\partial F_\\text{HK}(\\lambda)}{\\partial\\lambda}[\\Psi_\\text{HK}(\\lambda)]+\\frac{\\delta F_\\text{HK}(\\lambda)[\\Psi]}{\\delta\\Psi}\\Bigg|_{\\Psi=\\Psi_\\text{HK}(\\lambda)}\\frac{\\partial\\Psi_\\text{HK}(\\lambda)}{\\partial\\lambda}+\\frac{\\mathrm dV_s(\\lambda)[n]}{\\mathrm d\\lambda} \\\\\n  &=V_{ee}[\\Psi_\\text{HK}(\\lambda)]+\\frac{\\mathrm dV_s(\\lambda)[n]}{\\mathrm d\\lambda}\n\\end{aligned}\n\\end{equation}\nInserting the derivative into~\\eqref{eq:adiabatic-connection}, one gets an alternative expression for the electronic energy that provides, by comparison to~\\eqref{eq:ks-dft-energy}, an explicit formula for the XC energy (the last term),\n\\begin{equation}\n\\begin{aligned}\n  E(1)[n]&=T_\\text{s}[n]+V_\\text{s}(0)[n]+\\int_0^1\\mathrm d\\lambda V_{ee}[\\Psi_\\text{HK}(\\lambda)]+V_\\text{s}(1)[n]-V_\\text{s}(0)[n] \\\\\n  &=T_\\text{s}[n]+V_\\text{ext}[n]+J[n]-\\int_0^1\\mathrm d\\lambda\\,\\frac12\\iint\\mathrm d\\mathbf r_1\\mathrm d\\mathbf r_2\\frac{n(\\mathbf r_1)n(\\mathbf r_2)-n_2(\\mathbf r_1,\\mathbf r_2;\\lambda)}{|\\mathbf r_1-\\mathbf r_2|}\n  \\label{eq:energy-adiabatic}\n\\end{aligned}\n\\end{equation}\n\nThe fluctuation--dissipation theorem is a deep result of (quantum) statistical physics that relates correlations in fluctuations of any physical quantity describing a system in equilibrium with the dissipative part of the nonequilibrium response of that quantity to an external perturbation of the system~\\cite{CallenPR51}.\nThe linear density response function, $\\chi$, of an electronic system describes the change in the electron density at time $t$ generated by a change in the external potential at time $t'<t$,\n\\begin{equation}\n  \\frac{\\delta n(\\mathbf r,t)}{\\delta v_\\text{ext}(\\mathbf r',t')}=\\chi(\\mathbf r,\\mathbf r',t-t')\n\\end{equation}\nIt is often more convenient to Fourier-transform the time to frequency, $u$,\n\\begin{equation}\n  \\frac{\\delta n(\\mathbf r,u)}{\\delta v_\\text{ext}(\\mathbf r',u)}=\\chi(\\mathbf r,\\mathbf r',u)\n\\end{equation}\n\nA particular version of the fluctuation--dissipation theorem for the fluctuations of the electron density then enables one to express the electron-pair density, $n_2$, in terms of the density response.\nThis version of the theorem, at zero temperature, is expressed in terms of the density operator, $\\hat n(\\mathbf r)=\\sum_i\\delta(\\mathbf r-\\mathbf r_i)$, (see \\citealp[eq.~4.8]{CallenPR51}, \\citealp[eq.~124.10]{Landau80}, \\citealp[eq.~8.6.2]{Parr89}, and \\citealp[eq.~8]{KohnPRL98}),\n\\begin{equation}\n  \\langle\\Psi|(\\hat n(\\mathbf r_1)-n(\\mathbf r_1)\\!)(\\hat n(\\mathbf r_2)-n(\\mathbf r_2)\\!)|\\Psi\\rangle=-\\frac1\\pi\\int_0^\\infty\\mathrm du\\operatorname{Im}\\chi(\\mathbf r_1,\\mathbf r_2,u)\n\\end{equation}\nThe electron-pair density can be likewise expressed in terms of the density operators,\n\\begin{equation}\n  n_2(\\mathbf r_1,\\mathbf r_2)=\\langle\\Psi|\\hat n(\\mathbf r_1)\\hat n(\\mathbf r_2)-\\hat n(\\mathbf r_1)\\delta(\\mathbf r_1-\\mathbf r_2)|\\Psi\\rangle\n\\end{equation}\nWith the help of following identity,\n\\begin{equation}\n  \\langle\\Psi|(\\hat n(\\mathbf r_1)-n(\\mathbf r_1)\\!)(\\hat n(\\mathbf r_2)-n(\\mathbf r_2)\\!)|\\Psi\\rangle \\\\\n  =\\langle\\Psi|\\hat n(\\mathbf r_1)\\hat n(\\mathbf r_2)|\\Psi\\rangle-n(\\mathbf r_1)n(\\mathbf r_2)\n\\end{equation}\none can finally relate $n_2$ and $\\chi$,\n\\begin{equation}\n  n(\\mathbf r_1)n(\\mathbf r_2)-n_2(\\mathbf r_1,\\mathbf r_2)=\\frac1\\pi\\int_0^\\infty\\mathrm du\\operatorname{Im}\\chi(\\mathbf r_1,\\mathbf r_2,u)+n(\\mathbf r_1)\\delta(\\mathbf r_1-\\mathbf r_2)\n  \\label{eq:fluctuation-dissipation}\n\\end{equation}\nIn this equation, the left-hand side is finite for $\\mathbf r_1=\\mathbf r_2$, and the divergent second term on the right-hand side is formally canceled by the divergence of the response function at $\\mathbf r_1=\\mathbf r_2$.\nPlugging this equation into~\\eqref{eq:energy-adiabatic}, the XC energy is expressed in terms of the density response function,\n\\begin{equation}\n  E_\\text{xc}[\\chi]=-\\int_0^1\\mathrm d\\lambda\\,\\frac12\\iint\\mathrm d\\mathbf r_1\\mathrm d\\mathbf r_2\\frac{\\frac1\\pi\\int_0^\\infty\\mathrm du\\operatorname{Im}\\chi(\\mathbf r_1,\\mathbf r_2,u;\\lambda)+n(\\mathbf r_1)\\delta(\\mathbf r_1-\\mathbf r_2)}{|\\mathbf r_1-\\mathbf r_2|}\n\\end{equation}\nA standard form of the adiabatic-connection fluctuation--dissipation (ACFD) formula is reached by introducing the Coulomb operator, $v(R)\\equiv1/R$, and using the Wick rotation, $\\int_0^\\infty\\mathrm du\\operatorname{Im}\\chi(u)=\\int_0^\\infty\\mathrm du\\chi(\\mathrm iu)$, \\citep[see][eq.~123.20]{Landau80},\n\\begin{equation}\n  E_\\text{xc}[\\chi]=-\\frac1{2\\pi}\\int_0^\\infty\\mathrm du\\iint\\mathrm d\\mathbf r_1\\mathrm d\\mathbf r_2\\int_0^1\\mathrm d\\lambda\\,\\chi(\\mathbf r_1,\\mathbf r_2,\\mathrm iu;\\lambda)v(|\\mathbf r_1-\\mathbf r_2|)+Nv(0)\n  \\label{eq:acfd-xc}\n\\end{equation}\nHere, the density response outside the real axis is defined via analytic continuation, and is guaranteed to be real on the imaginary axis, and decrease monotonically to zero with growing $\\mathrm iu$.\nThe divergent second term, $Nv(0)$, is formally canceled by the corresponding divergence in the first term.\nEvaluation of the ACFD expression for the KS response function, $\\chi(\\lambda=0)$, reduces to the HF-like expression for exchange, which can be subtracted from the total XC energy to yield the remaining correlation part,\n\\begin{equation}\n  E_\\text{c}[\\chi]=-\\frac1{2\\pi}\\int_0^\\infty\\mathrm du\\iint\\mathrm d\\mathbf r_1\\mathrm d\\mathbf r_2\\int_0^1\\mathrm d\\lambda\\big(\\chi(\\mathbf r_1,\\mathbf r_2,\\mathrm iu;\\lambda)-\\chi(\\mathbf r_1,\\mathbf r_2,\\mathrm iu;0)\\!\\big)v(|\\mathbf r_1-\\mathbf r_2|)\n  \\label{eq:acfd-c}\n\\end{equation}\n\n\\section{Exchange--correlation functionals}\\label{sec:xc-func}\n\nThe search for accurate approximations of the exact XC functional, $E_\\text{xc}$, has been the major goal in DFT to this date, but the first and oldest approximation, which still serves as a basis of all modern and more accurate approximations, was published in the same manuscript as the KS-DFT framework itself.\nThe uniform electron gas (UEG) is an idealized system of electrons on an infinite uniform background of positive charge, which is fully specified by the value of the (constant) electron density, $n(\\mathbf r)\\equiv n$.\nThe exchange-energy density (exchange energy per electron), $\\varepsilon_\\text{x}$, as defined by the HF approximation, was first calculated for the UEG by \\citet{DiracMPCPS30},\n\\begin{equation}\n  \\varepsilon_\\text{x}^\\text{UEG}(n)=-\\frac34\\left(\\frac3\\pi\\right)^\\frac13 n^\\frac13\n\\end{equation}\nThe corresponding correlation-energy density, $\\varepsilon_\\text{c}\\equiv\\varepsilon_\\text{xc}-\\varepsilon_\\text{x}$, is known to a very good degree in a closed form from many-body perturbation theory~\\cite{ChachiyoJCP16},\n\\begin{equation}\n  \\varepsilon_\\text{c}^\\text{UEG}(n)\\approx\\frac{\\ln(2)-1}{2\\pi^2}\\ln\\left(1+20.4563\\bigg(\\!\\Big(\\frac{4\\pi}3\\Big)^\\frac13n^\\frac13+\\Big(\\frac{4\\pi }3\\Big)^\\frac23n^\\frac23\\bigg)\\!\\right)\n\\end{equation}\nAlternatively, it can be calculated nearly exactly using DQMC~\\cite{CeperleyPRL80}, for which fitted analytical forms exist~\\cite{PerdewPRB92}.\nThe local-density approximation (LDA) then assumes that the XC energy density of the UEG can be applied locally at each point of a nonuniform system,\n\\begin{equation}\n  E_\\text{xc}^\\text{LDA}[n]=\\int\\mathrm d\\mathbf r n(\\mathbf r)\\varepsilon_\\text{xc}^\\text{UEG}\\big(n(\\mathbf r)\\!\\big)\n\\end{equation}\n\nThe XC functionals can be also viewed as resulting from particular approximations to the so-called XC hole, $n_\\text{xc}$,\n\\begin{equation}\n  n_\\text{xc}(\\mathbf r_1,\\mathbf r_2)=n(\\mathbf r_1)\\big(1-g(\\mathbf r_1,\\mathbf r_2)\\!\\big)\n\\end{equation}\nFor a fixed electron at point $\\mathbf r_2$, the XC hole represents the instantaneous missing density of a single electron around $\\mathbf r_2$, hence its name.\nThe XC energy can be expressed as the Coulomb interaction of the electron density and the $\\lambda$-averaged XC hole,\n\\begin{equation}\nE_\\text{xc}=-\\frac12\\iint\\mathrm d\\mathbf r_1\\mathrm d\\mathbf r_2\\frac{n(\\mathbf r_1)\\int_0^1\\mathrm d\\lambda\\,n_\\text{xc}(\\mathbf r_1,\\mathbf r_2;\\lambda)}{|\\mathbf r_1-\\mathbf r_2|}=\\int\\mathrm d\\mathbf r\\,n(\\mathbf r)\\int\\mathrm d\\mathbf r'\\frac{-\\int_0^1\\mathrm d\\lambda\\,n_\\text{xc}(\\mathbf r,\\mathbf r';\\lambda)}{2|\\mathbf r-\\mathbf r'|}\n\\end{equation}\nThe LDA can then be understood as approximating the true XC hole of a system with that of the UEG of the corresponding density at each point.\n\nThe electronic motion in the UEG with the density in the range of average densities in molecules and solids consists of two major processes: the collective organized electronic fluctuations, called plasmons, and the individual motion of largely independent quasi-electrons (abstractions of electrons that behave in many regards as electrons).\nThe true electronic motion cannot be separated exactly in this way, but it is done so under the so-called random-phase approximation (RPA) that neglects explicit interactions between the collective and single-particle motions~\\cite{BohmPR51,PinesPR52,BohmPR53}.\nThis separation of motion also corresponds to a range separation of the Coulomb interaction, as in~\\eqref{eq:range-separation}.\nWhereas the interactions of the individual quasi-electrons are constrained to the short-range part of the potential, the plasmons interact via the long-range part.\nBecause LDA is exact for the UEG by construction, it captures both the short-range and long-range part of the XC energy in uniform systems (that is, metals, in which the uniform regions of the electron density are formed by the conducting electrons).\nBut these two types of electronic motion are not equally transferable to nonuniform systems.\nWhereas the character of short-range interactions between quasi-electrons is relatively similar in most electronic systems, the collective motion is completely determined by the particular arrangement of the atoms.\nFor this reason, the LDA captures in general relatively well the short-range part of the XC energy in most systems, but completely misses the long-range part in nonuniform systems, which comprise all real molecules and materials except metals.\n\nThe LDA estimates the local XC energy density only from the local value of the electron density, and better approximations can be constructed using more detailed semilocal information about the electronic system.\nIn the generalized gradient approximation (GGA), the XC energy functionals are constructed using also the magnitude of the gradient of the density, $|\\boldsymbol\\nabla n(\\mathbf r)|$.\nThe KS kinetic energy, $T_\\text{s}[n]$, can be formally expressed as an integral over the local kinetic-energy density, $\\tau_\\text{s}$,\n\\begin{equation}\n  T_\\text{s}[n]\\equiv\\int\\mathrm d\\mathbf r\\,\\tau_\\text{s}(\\mathbf r)\n\\end{equation}\nThis constraint does not uniquely define $\\tau_\\text{s}$.\nTwo common definitions, one directly from the kinetic-energy operator, the other expressed using only orbital gradients, are related via the Laplacian of the density, $\\nabla^2n(\\mathbf r)$,\n\\begin{equation}\n\\begin{gathered}\n  \\tau_\\text{s}^\\text{I}(\\mathbf r)=-\\frac12\\sum_j\\phi_j^*(\\mathbf r)\\nabla^2\\phi_j(\\mathbf r)\\qquad\n  \\tau_\\text{s}^\\text{II}(\\mathbf r)=\\frac12\\sum_j|\\boldsymbol\\nabla\\phi_j(\\mathbf r)|^2 \\\\\n  \\tau_\\text{s}^\\text{I}=\\tau_\\text{s}^\\text{II}-\\tfrac14\\nabla^2n(\\mathbf r)\n\\end{gathered}\\label{eq:kinetic}\n\\end{equation}\n\\citet{vonWeizsackerZFP35} formulated an approximate kinetic-energy density, $\\tau_\\text W$, as a correction to the kinetic energy of the UEG for nonuniform electron densities, which is by construction exact (on its own) for one-electron and spin-paired two-electron densities,\n\\begin{equation}\n  \\tau_\\text{W}(\\mathbf r)=\\frac18\\frac{|\\boldsymbol\\nabla n(\\mathbf r)|^2}{n(\\mathbf r)}\n  \\label{eq:von-w}\n\\end{equation}\n\nThe spherically averaged electron-pair density, $\\langle n_2\\rangle_\\Omega(\\mathbf r_1,r_{12})=\\int\\mathrm d\\Omega_{12}n_2(\\mathbf r,r_{12}\\Omega_{12})$, of the HF approximation can be to leading order in the electron--electron distance, $r_{12}$, expressed in terms of kinetic-energy densities~\\cite{BeckeJCP90},\n\\begin{equation}\n  \\langle n_2\\rangle_\\Omega(\\mathbf r,r_{12})=\\tfrac13\\big(\\tau_\\text{s}^\\text{II}(\\mathbf r)-\\tau_\\text{W}(\\mathbf r)\\!\\big)n(\\mathbf r)r_{12}^2+O(\\mathbf r_{12}^3)\n  \\label{eq:pair-correlation-expansion}\n\\end{equation}\nBecause the electron-pair density is a fundamental quantity for the calculation of the XC energy, this motivates the use of kinetic-energy densities and the related Laplacian in formulations of approximate XC energy functionals, which leads to the so-called meta-GGA functionals.\nThe smaller the electron-pair density is for small $r_{12}$, the more localized the electrons are, which motivates the definition of a function, $\\alpha(\\mathbf r)$, expressing the relative localization of electrons with respect to the UEG,\n\\begin{equation}\n  \\alpha(\\mathbf r)=\\frac{\\tau_\\text{s}^\\text{II}(\\mathbf r)-\\tau_\\text{W}(\\mathbf r)}{\\tau_\\text{s}^\\text{UEG}(n(\\mathbf r)\\!)}\n  \\label{eq:scan-alpha}\n\\end{equation}\nThis electron-localization function is always positive, and tends to be small (large localization) in the intra-shell regions of atoms and in the density tails (dominated by the highest occupied orbital) and large in inter-shell and bonding regions~\\cite{SunPRL13}.\nThe kinetic-energy densities enter many meta-GGA functionals in the form of $\\alpha(\\mathbf r)$.\n\nA generalized KS approximation can be formulated by relaxing the constraint that the KS potential must be local.\nSuch generalization then allows one to use the exchange functional of the HF method as part of an XC functional, evaluated on the one-electron orbitals of the noninteracting KS system, which are implicit functionals of the electron density (via the KS kinetic functional).\nThese so-called hybrid functionals proved useful and in general more accurate than pure KS functionals with local KS potentials.\n\n\\section{Time-dependent density-functional theory}\n\nThe ACFD formula yields the exact XC energy given the exact response function of the system, and time-dependent DFT provides a formally exact prescription how to calculate the latter.\n\\citet{RungePRL84} generalized the ground-state DFT for $v$-representable densities to time-dependent external potentials by proving that the map from the potentials to the densities is injective and hence invertible, establishing the time-dependent density as a fundamental quantity of the theory.\nWithin time-dependent KS-DFT, the primary role is played not by the XC functional, which cannot be well defined, but by the time-dependent XC potential, defined such that it yields the same time-dependent density for a noninteracting system as the true external potential yields for the interacting system.\nThe linear response of this XC potential to the changes in the density around the ground-state density is called the XC kernel, $f_\\text{xc}$,\n\\begin{equation}\n  f_\\text{xc}(\\mathbf r,\\mathbf r',u)=\\frac{\\delta v_\\text{xc}[n](\\mathbf r,u)}{\\delta n(\\mathbf r',u)}\n\\end{equation}\nThe time-independent XC potential is recovered as a restriction of the time-dependent one to static densities, which makes time-dependent KS-DFT a harder theory to approximate than ground-state DFT\\@.\n\nThe utility of the XC kernel comes from the expression for the density response function of the $\\lambda$-scaled interacting system in terms of the KS density response function of the noninteracting auxiliary system of electrons \\citep{GrossPRL85},\n\\begin{equation}\n  \\chi^{-1}(\\mathbf r,\\mathbf r',u;\\lambda)=\\chi^{-1}(\\mathbf r,\\mathbf r',u;0)-\\lambda v(|\\mathbf r-\\mathbf r'|)-f_\\text{xc}(\\mathbf r,\\mathbf r',u;\\lambda)\n  \\label{eq:dyson-td-dft}\n\\end{equation}\nThe KS density response is known explicitly in terms of the KS one-electron wave functions and their respective energies, $\\varepsilon_i$, \\citep{AdlerPR62,WiserPR63},\n\\begin{equation}\n  \\chi(\\mathbf r,\\mathbf r',u;0)=\\sum_{ij}{(f_i-f_j)\\frac{\\phi_i^*(\\mathbf r)\\phi_i(\\mathbf r')\\phi_j^*(\\mathbf r)\\phi_j(\\mathbf r')}{\\epsilon_i-\\epsilon_j+\\mathrm iu}}\n\t\\label{eq:adler-wiser}\n\\end{equation}\n\n\\section{Nonlocal dipole polarizability}\n\nThe presentation above revolved around the density response function.\nThis section presents a quantity that can serve as an equivalent alternative specification of the response properties of a system, but provides a better starting point for formulating approximate models of the response, as discussed in Chapter~\\ref{chap:vdw-methods}.\n\nThe polarization of electronic matter under the influence of an additional external electric field, $\\mathbf E_\\Delta=-\\boldsymbol\\nabla v_\\Delta$, (on top of that from the nuclei and electrons) can be expressed by the change, in the electron density, $\\Delta n$, from the unpolarized state ($\\mathbf E_\\Delta=0$).\nIn the linear regime, this change is related to the corresponding potential, $v_\\Delta$, via the density response function,\n\\begin{align}\n  \\Delta n(\\mathbf r,t)&=\\int\\mathrm d\\mathbf r'\\int_{-\\infty}^t\\mathrm dt'\\chi(\\mathbf r,\\mathbf r',t-t')v_\\Delta(\\mathbf r',t') \\\\\n  \\Delta n(\\mathbf r,u)&=\\int\\mathrm d\\mathbf r'\\chi(\\mathbf r,\\mathbf r',u)v_\\Delta(\\mathbf r',u)\n  \\label{eq:polarization}\n\\end{align}\n(A time-dependent electric field implies a nonzero magnetic field, but this is neglected in the nonrelativistic treatment discussed here.)\nAlternatively, the polarization state can be described by the polarization density, $\\mathbf P$, which can be interpreted as a dipole density, and which gives the polarized charge density via divergence,\n\\begin{equation}\n  -\\Delta n(\\mathbf r,u)=-\\boldsymbol\\nabla\\cdot\\mathbf P(\\mathbf r,u)\n\\end{equation}\nEach vector field, such as $\\mathbf P$, can be decomposed into its longitudinal and transversal component whose rotation and divergence are zero, respectively.\nUnlike $\\Delta n$ (but like the vector potential in classical electrodynamics), the polarization density is not observable, and is not unique, because any other polarization density that differs only by a rotation of some vector field will yield the same $\\Delta n$.\nHowever, its longitudinal component is unique, and equal to $-\\mathbf E_{\\Delta\\Delta}/4\\pi$, the electric field generated by the polarization density, $\\Delta n$.\n\nThe polarization density is related to the electric field via the (nonlocal) dipole polarizability, $\\boldsymbol\\alpha$, \\citep{HuntJCP83},\\footnote{\nThe following common notation is used for vectors from any vector space.\nThe application of a linear map (tensor), $M$, to a vector, $v$, omits parentheses, $M(v)\\equiv Mv$, and composition of tensors likewise, $M(O(v))\\equiv(MO)v\\equiv MOv$.\nSpecifically for the Euclidean space, vectors and tensors are typeset in bold, and the inner and tensor (outer) products are denoted with ``$\\cdot$'' and ``$\\otimes$'', respectively, $(\\mathbf u\\otimes\\mathbf v)\\mathbf w\\equiv(\\mathbf v\\cdot\\mathbf w)\\mathbf u$.\n}\n\\begin{equation}\n  \\mathbf P(\\mathbf r,u)=-\\int\\mathrm d\\mathbf r'\\boldsymbol\\alpha(\\mathbf r,\\mathbf r',u)\\mathbf E_\\Delta(\\mathbf r',u)\n  \\label{eq:nonlocal-polarizability}\n\\end{equation}\nIn general, the response of the electron density is anisotropic, $\\mathbf E_\\Delta$ and $\\mathbf P$ are not aligned, and the polarizability must be a tensor.\nLike $\\mathbf P$, the nonlocal dipole polarizability is not uniquely defined, but its longitudinal component is.\nThe relation between the density response function and dipole polarizability is obtained by taking the divergence of~\\eqref{eq:nonlocal-polarizability}, using integration by parts,\\footnote{\nFor a scalar field, $\\phi(\\mathbf r)$, and a vector field, $\\mathbf A(\\mathbf r)$,\n\\[ \\int_V\\mathrm d\\mathbf r\\,\\mathbf A(\\mathbf r)\\cdot\\boldsymbol\\nabla\\phi(\\mathbf r)=\\oint_{\\partial V}\\mathrm d\\mathbf r\\,\\boldsymbol\\nabla\\cdot\\big(\\mathbf A(\\mathbf r)\\phi(\\mathbf r)\\!\\big)-\\int_V\\mathrm d\\mathbf r\\big(\\boldsymbol\\nabla\\cdot\\mathbf A(\\mathbf r)\\!\\big)\\phi(\\mathbf r) \\]\nWhen $V$ is the whole space, and $A(\\mathbf r)\\phi(\\mathbf r)$ goes to zero when $\\mathbf r$ goes to infinity,\n\\[ \\int\\mathrm d\\mathbf r\\,\\mathbf A(\\mathbf r)\\cdot\\boldsymbol\\nabla\\phi(\\mathbf r)=-\\int\\mathrm d\\mathbf r\\big(\\boldsymbol\\nabla\\cdot\\mathbf A(\\mathbf r)\\!\\big)\\phi(\\mathbf r) \\]\n}\nthe definitions of $\\mathbf E_\\Delta$ and $\\mathbf P$, and comparing to~\\eqref{eq:polarization},\n\\begin{equation}\n\\begin{aligned}\n  \\chi(\\mathbf r,\\mathbf r',u)&=-\\boldsymbol\\nabla\\cdot\\boldsymbol\\nabla'\\cdot\\boldsymbol\\alpha(\\mathbf r,\\mathbf r',u)\n  \\label{eq:alpha-chi} \\\\\n  &=-\\sum_{\\iota\\zeta}\\frac{\\partial^2}{\\partial r_\\iota\\partial r'_\\zeta}\\alpha_{\\iota\\zeta}(\\mathbf r,\\mathbf r',u)\n  \\makebox[0pt]{\\hspace{0.25\\linewidth}$(\\iota,\\zeta=x,y,z)$}\n\\end{aligned}\n\\end{equation}\nThe observable density response function depends only on the (unique) longitudinal component of the dipole polarizability, and one can always fix the gauge of the polarizability to be such that its transversal component is zero.\n\nWhereas the electron density and the density response functions are coupled via the Coulomb operator, the polarization density and dipole polarizability are coupled via the dipole operator,\n\\begin{equation}\n  \\mathbf T(\\mathbf R)=\\boldsymbol\\nabla\\otimes\\boldsymbol\\nabla'v(|\\mathbf r-\\mathbf r'|)\\Big|_{\\substack{\\mathbf r=\\mathbf R\\\\\\mathbf r'=\\mathbf 0}}=\\frac{-3\\mathbf R\\otimes\\mathbf R+R^2\\mathbf I}{R^5}\n  \\label{eq:dipole-op}\n\\end{equation}\nFor instance, the electrostatic Coulomb self-interaction of $\\Delta n$, which has the corresponding $\\mathbf P$, can be expressed in two equivalent ways,\n\\begin{equation}\n\\begin{aligned}\n  J[\\Delta n]&=\\frac12\\iint\\mathrm d\\mathbf r_1\\mathrm d\\mathbf r\\,\\Delta n(\\mathbf r_1)v(|\\mathbf r_1-\\mathbf r_2|)\\Delta n(\\mathbf r_2) \\\\\n  &=\\frac12\\iint\\mathrm d\\mathbf r_1\\mathrm d\\mathbf r_2\\,\\mathbf P(\\mathbf r_1)\\cdot\\mathbf T(\\mathbf r_1-\\mathbf r_2)\\mathbf P(\\mathbf r_2)\n\\end{aligned}\n\\label{eq:elstat-energy}\n\\end{equation}\n\nThe total polarizability of a system, $\\boldsymbol\\alpha_\\text{tot}$, that relates its total induced dipole moment to a perturbing uniform field, $\\mathbf E(u)$, is recovered by integrating over both arguments of the nonlocal polarizability,\n\\begin{equation}\n\\begin{aligned}\n  \\textstyle\\int\\mathrm d\\mathbf r\\,\\mathbf P(\\mathbf r,u)&=\\Big(\\textstyle\\iint\\mathrm d\\mathbf r\\mathrm d\\mathrm r'\\,\\boldsymbol\\alpha(\\mathbf r,\\mathbf r',u)\\!\\Big)\\mathbf E(u) \\\\\n  &=\\boldsymbol\\alpha_\\text{tot}\\mathbf E(u)\n\\end{aligned}\n\\end{equation}\n\n\\section{Periodic potentials and reciprocal space}\n\nThe relevant physical information in quantum mechanics is encoded in operators on the appropriate Hilbert space (Fock space if change in number of particles is considered), which can be expressed in whichever basis is the most convenient for a particular calculation.\nThis section presents a class of bases that are best suited for systems where the external potential has a full or discrete translational symmetry.\nSuch systems correspond to perfect crystals, but are also good models or starting point for subsequent improved treatments of imperfect crystals or nonperiodic systems after applying artificial periodic boundary condition.\n\nAs can be the time domain of response functions Fourier-transformed into the frequency domain, so can be the real space Fourier-transformed into the reciprocal space,\n\\begin{equation}\n  f(\\mathbf k)=\\int\\mathrm d\\mathbf r\\,f(\\mathbf r)\\mathrm e^{-\\mathrm i\\mathbf k\\cdot\\mathbf r}\n\\end{equation}\nWhile the frequency domain directly exposes the time-translational symmetry of stationary states, the reciprocal space exposes the space-translational symmetry (periodicity) in crystals.\nThe Fourier transformation of any Bravais lattice, $\\{\\mathbf R\\}$, is the corresponding reciprocal lattice, $\\{\\mathbf G\\}$.\nThe spectrum of a crystal-periodic function, $f$, such as the electron density, is discrete, and is conventionally defined by normalizing to the unit-cell (UC) volume, $\\Omega_\\text{UC}$,\n\\begin{equation}\n\\begin{aligned}\n  f(\\mathbf k)&=(2\\pi)^3\\Omega_\\text{UC}\\sum_\\mathbf G\\delta(\\mathbf k-\\mathbf G)\\frac1{\\Omega_\\text{UC}}\\int_\\text{UC}\\mathrm d\\mathbf r\\,n(\\mathbf r)\\mathrm e^{-\\mathrm i\\mathbf G\\cdot\\mathbf r} \\\\\n  &\\equiv(2\\pi)^3\\Omega_\\text{UC}\\sum_\\mathbf G\\delta(\\mathbf k-\\mathbf G)f_\\mathbf G\n\\end{aligned}\n\\end{equation}\nFor a two-point function, $A$, such as the response function, the sign in the exponential of the Fourier transformation is conventionally inverted for the second argument.\nBecause a two-point function related to a crystal is periodic only in both of its arguments at the same time, its spectrum is partially discrete, partially continuous, and any two wave vectors, $\\mathbf k$, $\\mathbf k'$, for which its spectrum is nonzero, can be written in terms of two reciprocal unit-cell vectors, $\\mathbf G$, $\\mathbf G'$, and a single wave vector from the first Brillouin zone, $\\mathbf q$,\n\\begin{equation}\n  A_{\\mathbf G\\mathbf G'}(\\mathbf q)=\\frac1{\\Omega_\\text{UC}}\\int_\\text{UC}\\mathrm d\\mathbf r\\int\\mathrm d\\mathbf r'A(\\mathbf r,\\mathbf r')\\mathrm e^{-\\mathrm i\\mathbf G\\cdot\\mathbf r}\\mathrm e^{\\mathrm i\\mathbf G'\\cdot\\mathbf r'}\\mathrm e^{-\\mathrm i\\mathbf q\\cdot(\\mathbf r-\\mathbf r')}\n\\end{equation}\nThe Fourier transformation reduces inner-product real-space integrals into reciprocal-space infinite sums,\n\\begin{equation}\n  A(\\mathbf r,\\mathbf r')=\\int\\mathrm d\\mathbf r''B(\\mathbf r,\\mathbf r'')C(\\mathbf r'',\\mathbf r) \\quad\\Leftrightarrow\\quad\n  A_{\\mathbf G\\mathbf G'}(\\mathbf q)=\\sum_{\\mathbf G''}B_{\\mathbf G\\mathbf G''}(\\mathbf q)C_{\\mathbf G''\\mathbf G'}(\\mathbf q)\n\\end{equation}\nBecause larger $\\mathbf G$ correspond to ever more rapid changes in real space, a reasonable approximation can be made by neglecting $\\mathbf G$ above some threshold, and making the $\\mathbf q$-dependent matrices finite.\nSuch a truncation of the Fourier transformation corresponds to perhaps the simplest finite one-electron basis for periodic external potentials that can be reasonably efficient when actually used to numerically solve HF or KS equations.\nSince the functions corresponding to a given $\\mathbf G$ are plane waves, $\\mathrm e^{-\\mathrm i\\mathbf G\\cdot\\mathbf r}$, the computer programs that calculate the electronic structure of crystals in this way are usually referred to as plane-wave codes.\n\nThere is no reasonable cutoff when the functions being transformed are discrete, say, over atoms positions, $\\mathbf R_i$, $A(\\mathbf r,\\mathbf r')=\\sum_{\\mathbf R\\mathbf R'}\\sum_{ij}\\delta(\\mathbf r-\\mathbf R-\\mathbf R_i)\\delta(\\mathbf r'-\\mathbf R'-\\mathbf R_j)A_{\\mathbf R+\\mathbf R_i,\\mathbf R'+\\mathbf R_j}$.\n($\\mathbf R$, $\\mathbf R'$ are lattice vectors.)\nIn such case, it is convenient to define the Fourier transformation of the individual discrete points,\n\\begin{equation}\n\\begin{aligned}\n  A_{\\mathbf G\\mathbf G'}(\\mathbf q)&=\\frac1{\\Omega_\\text{UC}}\\sum_i\\sum_{\\mathbf Rj}A_{\\mathbf R_i,\\mathbf R+\\mathbf R_j}\\mathrm e^{-\\mathrm i\\mathbf G\\cdot\\mathbf R_i}\\mathrm e^{\\mathrm i\\mathbf G'\\cdot\\mathbf R_j}\\mathrm e^{-\\mathrm i\\mathbf q\\cdot(\\mathbf R_i-\\mathbf R-\\mathbf R_j)} \\\\\n  &=\\frac1{\\Omega_\\text{UC}}\\sum_{ij}\\Big(\\sum_\\mathbf RA_{\\mathbf R_i,\\mathbf R+\\mathbf R_j}\\mathrm e^{-\\mathrm i\\mathbf q\\cdot(\\mathbf R_i-\\mathbf R-\\mathbf R_j)}\\Big)\\mathrm e^{-\\mathrm i\\mathbf G\\cdot\\mathbf R_i}\\mathrm e^{\\mathrm i\\mathbf G'\\cdot\\mathbf R_j} \\\\\n  &\\equiv\\frac1{\\Omega_\\text{UC}}\\sum_{ij}A_{ij}(\\mathbf q)\\mathrm e^{-\\mathrm i\\mathbf G\\cdot\\mathbf R_i}\\mathrm e^{\\mathrm i\\mathbf G'\\cdot\\mathbf R_j}\n\\end{aligned}\n\\end{equation}\nThis naturally reduces reciprocal-space infinite sums into real-space finite sums,\n\\begin{equation}\n  A_{\\mathbf G\\mathbf G'}(\\mathbf q)=\\sum_{\\mathbf G''}B_{\\mathbf G\\mathbf G''}(\\mathbf q)C_{\\mathbf G''\\mathbf G'}(\\mathbf q) \\quad\\Leftrightarrow\\quad\n  A_{ij}(\\mathbf q)=\\sum_k B_{ik}(\\mathbf q)C_{kj}(\\mathbf q)\n  \\label{eq:fourier-discrete}\n\\end{equation}\n\n\\subsection{Dielectric function from dipole polarizability}\\label{sec:dielectric}\n\nThe previous sections introduced two ways to specify the response properties of a material---the density response function and the nonlocal dipole polarizability.\nBoth of them are useful theoretical constructs, but none of them is directly measurable in solids in a practical way.\nIn molecules, the total polarizability can be measured and compared to theoretical predictions, but this quantity is extensive and hence not very useful for describing macroscopic material samples.\nThis disadvantage is resolved by yet another response, the (scalar) microscopic dielectric function, $\\epsilon$, which has a directly measurable macroscopic limit.\n\nThe dielectric function relates the change in the total electric potential (including the field from the electrons), $\\Delta v_\\text{tot}$, to that in the external potential,\n\\begin{equation}\n  \\Delta v_\\text{tot}(\\mathbf r,u)=\\int\\mathrm d\\mathbf r'\\epsilon^{-1}(\\mathbf r,\\mathbf r',u)v_\\Delta(\\mathbf r',u)\n\\end{equation}\nIt can be expressed in terms of the density response function,\n\\begin{equation}\n\\begin{aligned}\n  \\epsilon^{-1}(\\mathbf r,\\mathbf r',u)&=\\delta(|\\mathbf r-\\mathbf r'|)+\\int\\mathrm d\\mathbf r''v(|\\mathbf r-\\mathbf r''|)\\chi(\\mathbf r'',\\mathbf r',u) \\\\\n  &\\hspace{5em}\\Updownarrow \\\\\n  \\epsilon^{-1}_{\\mathbf G\\mathbf G'}(\\mathbf q,u)&=\\delta_{\\mathbf G\\mathbf G'}+\\sum_{\\mathbf G''}v_{\\mathbf G\\mathbf G''}(\\mathbf q)\\chi_{\\mathbf G''\\mathbf G'}(\\mathbf q,u) \\\\\n  &=\\delta_{\\mathbf G\\mathbf G'}+v(|\\mathbf G+\\mathbf q|)\\chi_{\\mathbf G\\mathbf G'}(\\mathbf q,u)\n\\end{aligned}\n\\end{equation}\nThe (tensor) macroscopic dielectric function, $\\boldsymbol\\epsilon_\\text{M}$, relates the macroscopic total electric field to the macroscopic external electric field,\n\\begin{equation}\n  \\mathbf E(u)=\\boldsymbol\\epsilon^{-1}_\\text M(u)\\mathbf E_\\text{ext}(u)\n\\end{equation}\nThe macroscopic dielectric function can be obtained from the microscopic one by taking the latter's long-wavelength limit,\n\\begin{equation}\n  \\hat{\\mathbf q}\\cdot\\boldsymbol\\epsilon_\\text M(u)\\hat{\\mathbf q}=\\lim_{\\mathbf q\\rightarrow0}\\frac1{\\epsilon^{-1}_{\\mathbf 0\\mathbf 0}(\\mathbf q,u)}\n\\end{equation}\nThis limit depends on the direction from which zero is approached, which is the mechanism by which a microscopic scalar quantity becomes a macroscopic tensor quantity.\n\n\\subsection{Ewald summation of dipole interaction}\n\nThis section presents a reciprocal-space numerical technique that will be used in Chapter~\\ref{chap:mbd} to speed up calculations of vdW energies.\nThe Fourier transformations of the discrete samples of the Coulomb and dipole operators, $v$ and $\\mathbf T$, are infinite real-space sums that converge slowly, hindering numerical evaluation,\n\\begin{equation}\n  \\mathbf T_{ij}(\\mathbf q)=\\sum_\\mathbf R\\mathbf T_{\\mathbf R_i,\\mathbf R+\\mathbf R_j}\\mathrm e^{-\\mathrm i\\mathbf q\\cdot(\\mathbf R_i-\\mathbf R-\\mathbf R_j)}=\\sum_\\mathbf R\\mathbf T(\\mathbf R_i-\\mathbf R-\\mathbf R_j)\\mathrm e^{-\\mathrm i\\mathbf q\\cdot(\\mathbf R_i-\\mathbf R-\\mathbf R_j)}\n\\end{equation}\n\\citet{EwaldAP21} summation is a technique that splits such a sum in two parts, one of which converges quickly in the real space, and the other in the reciprocal space.\nThe split is governed by a single parameter, $\\alpha>0$, which balances the rate of convergence of the two components.\nIn the case of the dipole operator for general $\\mathbf q$ \\citep{BowdenJPCSSP81}, the resulting expression consists of three terms,\n\\begin{multline}\n  \\mathbf T_{ij}(\\mathbf q)=\\sum_\\mathbf R\\mathbf T_\\text{Ew,sr}(\\mathbf R_i-\\mathbf R-\\mathbf R_j;\\alpha)\\mathrm e^{-\\mathrm i\\mathbf q\\cdot(\\mathbf R_i-\\mathbf R-\\mathbf R_j)} \\\\\n  +\\frac1{\\Omega_\\text{UC}}\\sum_{\\mathbf G}\\mathbf T_\\text{Ew,lr}(\\mathbf G+\\mathbf q;\\alpha)\\mathrm e^{-\\mathrm i\\mathbf G\\cdot(\\mathbf R_i-\\mathbf R_j)}\n  -\\delta_{ij}\\frac{4\\alpha^3}{3\\sqrt{\\pi}}\\mathbf I\n  \\label{eq:ewald}\n\\end{multline}\nwhere\n\\begin{gather}\n  \\mathbf T_\\text{Ew,sr}(\\mathbf d;\\alpha)=\\frac{-3\\mathbf d\\otimes\\mathbf dB_1(\\alpha d)+d^2\\mathbf IB_2(\\alpha d)}{d^5} \\qquad\n  \\mathbf T_\\text{Ew,lr}(\\mathbf k;\\alpha)=4\\pi\\frac{\\mathbf k\\otimes\\mathbf k}{k^2}\\exp\\bigg(-\\frac{k^2}{4\\alpha^2}\\bigg) \\\\\n  B_1(x)=\\operatorname{erfc}(x)+\\tfrac2\\pi x\\big(1+\\tfrac23x^2\\exp(-x^2)\\!\\big)\\qquad\n  B_2(x)=\\operatorname{erfc}(x)+\\tfrac2\\pi x\\exp(-x^2)\n\\end{gather}\nThe first term is a real-space sum of the short-ranged part, while the other two combined are a reciprocal-space sum of the long-ranged part.\n\nThe long-ranged part is not defined for $\\mathbf k=\\mathbf G+\\mathbf q=0$, and neither has an analytical limit there.\nThis corresponds to the fact that the dipole sum is not absolutely convergent for $\\mathbf q=0$, which in turn corresponds to the physical fact that the electrostatic energy of a macroscopic sample of a dipole crystal, described by a polarization density (eq.~\\ref{eq:elstat-energy}), depends on the shape of the crystal sample.\nThis ambiguity disappears when one studies only differences between to states of such a crystal, because the shape-dependent terms cancel out.\nA particular choice for the limit of $\\mathbf T_\\text{Ew,lr}(\\mathbf k)$ when $\\mathbf k$ goes to zero corresponds to a particular choice of the shape, and a common choice is a sphere,\n\\begin{equation}\n  \\lim_{\\mathbf k\\rightarrow0}\\mathbf T_\\text{Ew,lr}(\\mathbf k;\\alpha)=\\frac{4\\pi}3\\mathbf I\n\\end{equation}\n", "meta": {"hexsha": "f72ce2b328f012e39f02befadaa33307c08ae331", "size": 59870, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/electronic-many-body-problem.tex", "max_stars_repo_name": "azag0/dissertation", "max_stars_repo_head_hexsha": "7b56b7fba557c58f624cb3ef88b1c91d5f72a765", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/electronic-many-body-problem.tex", "max_issues_repo_name": "azag0/dissertation", "max_issues_repo_head_hexsha": "7b56b7fba557c58f624cb3ef88b1c91d5f72a765", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/electronic-many-body-problem.tex", "max_forks_repo_name": "azag0/dissertation", "max_forks_repo_head_hexsha": "7b56b7fba557c58f624cb3ef88b1c91d5f72a765", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 99.9499165275, "max_line_length": 464, "alphanum_fraction": 0.7633372307, "num_tokens": 17138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982043529716, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.3062035073820362}}
{"text": "\\documentclass[11pt]{article}\n\n\\usepackage{fullpage,graphicx, verbatim, subcaption, amsmath, amssymb}\n\n\\title{CSCI 599 Project : Learning the protein coding signature}\n\n\\author{Saket Choudhary\\\\ Team Launchpad \\\\ skchoudh@usc.edu}\n\n\\begin{document}\n\\maketitle \n\\section*{Abstract} \nThe central dogma of biology describes how genetic information flows within a system where the RNA is synthesizes from DNA which in turn gets synthesized to proteins. Any gene can be roughly partitioned into three regions: 5' Untranslated Region (UTR), Coding Domain Sequence (CDS) and 3'UTR. While 5'UTR region regulates translation process, the 3'UTR region is involved in post-transcriptional regulation. CDS is the region that codes for protein and is mostly the longest of the three regions. These annotations are available for a lot of organisms, but  not for all organisms even if there genome sequence is completely known. Inferring the protein coding boundaries requires learning the sequence dependencies in the different partitions. Formally, the problem is stated as follows:\n\n\\textbf{Input}: A vector $\\mathbf{x} \\in \\mathcal{V}^l$ where $l$ is sequence length  and $\\mathcal{V} = \\{N, A, C, T, G \\}$. where N represents no base and $A,C,T,G$ are the four chemical bases Adenine, Cytosine, Thymine and Guanine.\n\n\\textbf{Output}: Labels $\\mathbf{y} = \\{ \\text{5'UTR}, \\text{CDS}, \\text{3'UTR} \\}^l$\n\nIn other words, the aim is to be able to first be able to do a base level prediction for one of the three classes and then using a cutoff-length $k$ )to be empirically determined) determine the exact boundaries of these regions.\n\n\\section*{Model}\nWe propose an LSTM based approach to learn these dependencies. The training process would involve training on annotated boundaries of over ~ 25000 genes using the human dataset. \n\n\\section*{Goals}\nThe project will have two goals, with Goal 2 dependent on Goal 1's success:\n\n\\subsection*{Goal 1}\nCan the RNN capture the non-random signal in genome? Given a sequence of bases $\\{A, C, T, G\\}$ can the RNN predict the next base with an accuracy better than a \\textit{random} genome? This random genome can consist of a pre-defined length of random permutation of $\\{A, C, T, G\\}$.\n\n\\subsection*{Goal 2}\nIf Goal 1 is successful, the next goal would be to use this model for a classification problem. Where we predict a label  $\\{ \\text{5'UTR}, \\text{CDS}, \\text{3'UTR} \\}$ for each base. This will have two parts:\n\\begin{itemize}\n\\item Training on human dataset using 15000 genes and testing on remaining ~10000 genes\n\\item Training on entire human dataset of ~25000 genes and testing on an entirely different organism\n\\end{itemize}\n\n\n\\begin{figure}[h]\n\\includegraphics[width=\\textwidth]{cds}\n\\caption{Different regions in a gene.}\n\\end{figure}\n\\end{document}\n", "meta": {"hexsha": "263b82e6b50040da9b3eb70ec33f0359eb245cca", "size": 2797, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/proposal_presentation/main.tex", "max_stars_repo_name": "saketkc/predicting-cds-rnn", "max_stars_repo_head_hexsha": "fb673a794540a1c823ca11268fe5c182b64c764e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-11T22:41:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-11T22:41:51.000Z", "max_issues_repo_path": "docs/proposal_report/main.tex", "max_issues_repo_name": "saketkc/predicting-cds-rnn", "max_issues_repo_head_hexsha": "fb673a794540a1c823ca11268fe5c182b64c764e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/proposal_report/main.tex", "max_forks_repo_name": "saketkc/predicting-cds-rnn", "max_forks_repo_head_hexsha": "fb673a794540a1c823ca11268fe5c182b64c764e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 66.5952380952, "max_line_length": 787, "alphanum_fraction": 0.7647479442, "num_tokens": 739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.3060993368630181}}
{"text": "% \\input{/Users/jovo/Research/latex/latex_paper.tex}\r\n\r\n\\documentclass[10pt,journal,cspaper,compsoc]{IEEEtran}\r\n%\r\n% If IEEEtran.cls has not been installed into the LaTeX system files,\r\n% manually specify the path to it like:\r\n% \\documentclass[12pt,journal,compsoc]{../sty/IEEEtran}\r\n\r\n\\usepackage{fixltx2e}\r\n% \\usepackage{stfloats}\r\n\\usepackage{amsmath}\r\n\\usepackage{graphicx}\r\n\\usepackage{amsfonts}\r\n\\usepackage{amssymb}\r\n\\usepackage{amsthm}\r\n\\usepackage{cite}\r\n\\usepackage{algorithm}\r\n\\usepackage{algorithmic}\r\n\\usepackage{url}\r\n\\usepackage{enumerate}\r\n% \\usepackage{hyperref}\r\n\\usepackage{color}\r\n\r\n\\input{/Users/jovo/Research/other/latex/latex_commands.tex}\r\n\r\n% \\newcommand{\\texttt{PATH}}{\\texttt{PATH}}\r\n\r\n\r\n\r\n\\hyphenation{op-tical net-works semi-conduc-tor}\r\n% \\newcommand{\\Qqap}{\\Qqap}\r\n\\usepackage{caption}\r\n\\captionsetup{justification=raggedright}\r\n\\newcommand{\\PmcP}{P \\in \\mc{P}}\r\n\r\n\r\n\\begin{document}\r\n\r\n\\title{(Brain) Graph Matching via \\\\ Fast Approximate Quadratic Programming}\r\n\r\n% \\huge{A Fast Approximate Quadratic Assignment Problem Algorithm for Brain Graph Matching}} % \\\\ with Applications in Statistical Connectomics}\r\n% \\title{A Quadratic Assignment Problem Approach to Graph Matching: Applications in Statistical Connectomics}\r\n\r\n\\author{Joshua T.~Vogelstein, John M.~Conroy, Louis J.~Podrazik, Steven G.~Kratzer, Eric T.~Harley,\r\n        Donniell E.~Fishkind, \r\n\t\tR.~Jacob~Vogelstein,\r\n        and~Carey~E.~Priebe% <-this % stops a space\r\n\\IEEEcompsocitemizethanks{\\IEEEcompsocthanksitem J.T. Vogelstein, E.T. Harley, D.E. Fishkind, and C.E. Priebe are with the Department\r\nof Applied Mathematics and Statistics, Johns Hopkins University, Baltimore, MD 21218. \r\n%\\protect\\\\\r\n% note need leading \\protect in front of \\\\ to get a newline within \\thanks as\r\n% \\\\ is fragile and will error, could use \\hfil\\break instead.\r\nE-mail: \\{joshuav,eric.harley,def,cep\\}@jhu.edu, \\{conroyjohnm,ljpodra,sgkratz\\}@gmail.com, jacob.vogelstein@jhuapl.edu\r\n\\IEEEcompsocthanksitem J.M. Conroy, L.J. Podrazik and S.G. Kratzer are with Institute for Defense Analyses, Center for Computing Sciences, Bowie, MD 20708.\r\n\\IEEEcompsocthanksitem R.J. Vogelstein is with the Johns Hopkins University Applied Physics Laboratory, Laurel, MD, 20723.}% <-this % stops a space\r\n\\thanks{This work was partially supported by the Research Program in Applied Neuroscience.}}\r\n \r\n% The paper headers\r\n\\markboth{SUBMITTED}\r\n{Fast Inexact Graph Matching}\r\n\r\n\\IEEEcompsoctitleabstractindextext{%\r\n\\begin{abstract}\r\n\t\r\nGraph matching (GM)---the process of finding an optimal permutation of the vertices of one graph to minimize adjacency disagreements with the vertices of another---is rapidly becoming an increasingly important computational problem, arising in fields ranging from machine vision to chemical engineering to neuroscience. Because GM is NP-hard, exact algorithms are unsuitable for today's massive graphs; yet, scalable GM algorithms have received short shrift.  GM can be formulated as a quadratic program with linear and binary constraints.  We develop a fast approximate quadratic (\\FAQ) assignment algorithm to approximately solve a relaxed quadratic program with only linear constraints.  \\FAQ scales cubicly with the number of vertices, and demonstrates marked improvements over previous state-of-the-art on nearly all benchmarks. Moreover, our non-convex formulation facilitates multiple restarts; $2-3$ wisely chosen initial conditions yield the best objective function on \\emph{all} benchmarks. We find qualitatively similar results for our motivating application: brain-graph matching.  Unfortunately, the computational complexity of \\FAQ scales too poorly to use it for mammalian brain-graphs, with millions or billions of vertices.  To inspire further development of approximate solutions to these problems, this work is available from on the first author's website, \\url{http://jovo.me}.\r\n\r\n\r\n% The quadratic assignment problem (QAP) arises in numerous disparate applications, ranging from traveling salesman problems to various machine vision problems.  We are particularly interested in a special case of QAP often called the (weighted) graph matching problem---the process of determining which permutation assigns vertices of one graph to those of another. \r\n% Our work is motivated by a particular graph matching problem: \r\n% Unfortunately, FAQ does not scale up to graphs with millions or billions of vertices, the size of mammalian brain-graphs.  \r\n% A brain-graph (or connectome), is a graph in which vertices correspond to (collections of) neurons, and edges are either functional or structural connections between them.  \r\n% % that is matching one connectome (brain-graph) to another. We are further interested in a specific application of graph matching applied to ``connectomes'' (networks comprising whole brains), which we call \\emph{brain-graph matching}.  \r\n% Brain-graphs have between $n \\dot{\\approx} 10^2$ and $\\dot{\\approx} 10^{11}$ vertices, making exact graph matching algorithms computationally infeasible, even for the smallest brains.  We cast our brain-graph matching problem as a nonlinearly constrained quadratic program.  Relaxing the constraints yields a simpler quadratic problem with linear constraints.  Our Fast Approximate Quadratic Assignment Problem algorithm, \\texttt{FAQ}, finds a local minimum of this problem in $\\mc{O}(n^3)$ time, outperforming the current state-of-the-art inexact (heuristic) algorithms on a number of QAP benchmarks.  Moreover, we prove that our relaxed optimization function has the same solution as the original problem in certain scenarios. Applying \\texttt{FAQ} to a synthetic \\emph{Caenorhabditis elegans} connectome problem demonstrates that brain-graph matching is much more difficult than many standard QAP benchmarks.  Utilizing multiple random restarts, however, often yields optimal performance on this task with $\\dot{\\approx} 300$ vertices.  \r\n% .  To that end, \r\n% , and share our code \r\n% The formalism and algorithm we utilize here are designed for extending performance on larger and more complicated QAPs. \r\n\r\n\r\n % This work presents an inexact strategy for GM.  Specifically, we frame GM as a quadratic assignment problem, and then relax the feasible region to its convex hull.  We prove that our relaxed optimization function has the same solution as the original problem, yet it is continuously differentiable. Because the objective function is not necessarily convex, we consider multiple principled initializations.  Performance exceeds the previous state-of-the-art in \\emph{all} of 16 benchmark tests.  Moreover, this approach is fast, scaling cubically with the number of vertices, requiring only about a minute on a laptop for graphs with a few hundred vertices.  We illustrate this approach via a brain-graph application (the Caenorhabditis elegans ``connectome'').  We find that we can find the optimal solution for nearly every random permutation of the connectome that we sample.  Although this strategy already natively operates on weighted graphs, either directed or undirected, we propose a number of possible extensions, and make all code available.\r\n\\end{abstract}\r\n\r\n% Note that keywords are not normally used for peer review papers.\r\n\\begin{keywords}\r\ngraph theory, network theory, statistical inference, structural pattern recognition, connectome.\r\n\\end{keywords}}\r\n\r\n\r\n% make the title area\r\n\\maketitle\r\n\\IEEEdisplaynotcompsoctitleabstractindextext\r\n\\IEEEpeerreviewmaketitle\r\n\r\n\r\n\r\n\\section{Introduction}\r\n\r\n\\IEEEPARstart{G}{raph} matching---the process of finding an optimal permutation of the vertices of one graph to minimize adjacency disagreements with the vertices of another---is a famously computationally daunting problem (see, for example, ``Thirty Years of Graph Matching in Pattern Recognition''  \\cite{Conte2004}). Specifically, graph matching is an $\\mc{NP}$-hard problem, in particular, we do not know whether a polynomial time algorithm can solve it \\cite{Papadimitriou1998}.  Perhaps the most prominent special case of graph matching is the traveling salesman problem \\cite{Burkard2009}. As such, performance of graph matching algorithms are usually evaluated on graphs with $\\dot{\\approx} 10$ vertices, or at maximum $\\dot{\\approx} 100$ (see \\cite{Burkard1997} for a description of the standard set of benchmarks).  Yet, it is increasingly popular to represent large data sets by a graph, and thus increasingly desirable to consider matching large graphs.  \r\n\r\nThe motivating application for this work is \\emph{brain-graph matching}.  A brain-graph (aka, a connectome) is a graph for which vertices represent (collections of) neurons and edges represent connections between them \\cite{SpornsKotter05, Hagmann05}. Via  Magnetic resonance (MR) imaging, one can image the whole brain and estimate connectivity across voxels, yielding a voxelwise connectome with up to $\\dot{\\approx} 10^6$ vertices and $\\dot{\\approx} 10^9$ edges \\cite{Zuo2011}.  Comparing brains is an important step for many neurobiological inference tasks.  For example, it is becoming increasingly popular to diagnose neurological diseases via comparing brain images \\cite{Csernansky2004}.  To date, however, these comparisons have largely rested on anatomical (e.g., shape) comparisons, not graph comparisons.  This is despite the widely held doctrine that many\r\n% Yet almost immediately after the ``neuron doctrine'' was conjectured (the idea that networks of neurons comprise brains), Wernicke and others began postulating that \r\npsychiatric disorders are fundamentally ``connectopathies'', that is, disorders of the connections of the brain \\cite{Kubicki2007,Calhoun2011,Fornito2012,Fornito2012a}. Currently available tests for connectopic explanation of psychiatric disorders  hedge upon first choosing some number of graph invariants to compare across populations. The graph invariant approach to classifying is both theoretically and practically inferior to comparing whole graphs via matching \\cite{VP11_unlabeled}.  \r\n\r\nMore generally, state-of-the-art inference procedures for essentially any decision-theoretic or inference task follow from constructing interpoint dissimilarity matrices \\cite{Duin2011}.  Thus, we believe that graph matching of large graphs will become a fundamental subroutine of many statistical inference pipelines operating on graphs. Because the number of vertices of these graphs is so large, exact matching is intractable.   Instead, we require inexact matching algorithms (also called ``heuristics'') that will scale polynomially or even linear \\cite{Conte2004}.  We develop an approach to graph matching based on a relaxation of the quadratic programming problem (QAP).  Our approach is only cubic in the number of vertices, and outperforms previously proposed approximate graph matching heuristics on a wide range of benchmark datasets as well as our motivating application.  \r\n\r\n\r\n\r\n\r\n\\section{Graph Matching} % (fold)\r\n\\label{sec:graph_matching}\r\n\r\n\r\nA labeled graph $G=(\\mc{V},\\mc{E})$ consists of a vertex set $\\mc{V}$, where $|\\mc{V}|=n$ is number of vertices, and an edge set $\\mc{E}$. %, where $|\\mc{E}| \\leq n^2$. \r\nNote that we are not restricting our formulation to be directed or exclude self-loops. Given a pair of graphs, $G_A=(\\mc{V}_A,\\mc{E}_A)$ and $G_B=(\\mc{V}_B,\\mc{E}_B)$, where $|\\mc{V}_A|=|\\mc{V}_B|=n$, \r\nlet $\\Pi$ be the set of permutation functions (bijections), $\\Pi=\\{\\pi \\from \\mc{V}_A \\to \\mc{V}_B\\}$.\r\n% $\\pi: \\mc{V}_1 \\to \\mc{V}_2$ be a permutation function (bijection), and let $\\Pi$ be the set of all such permutation functions.  \r\nNow consider the following two closely related problems:\r\n% A pair of graphs, $G_1$ and $G_2$, are isomorphic if and only if the following \\emph{isomorphism criterion} holds: there exists a $\\pi \\in \\Pi$ such that . \r\n% Let $A$ be the adjacency matrix representation of graph such that $A_{ij}=1$ if there is an edge from $u$ to $v$, and $A_{ij}=0$ otherwise. \r\n% Note that the below follows for directed/undirected and loopy/non-loopy graphs.\r\n% $u \\sim v \\in \\mc{E}$ and $A_{ij}=0$ otherwise.  \r\n% Let  $\\Pi$ be the set of permutation functions, where a permutation function (bijection) $\\pi: \\mc{V} \\to \\mc{V}$ (re-)orders the elements of the set $\\mc{V}$.  Given a pair of $n \\times n$ adjacency matrices, $A=(a_{ij})$ and $B=(b_{ij})$, consider the following two problems:\r\n\\begin{itemize}\r\n\t\\item \\textbf{Graph Isomorphism (GI):}  Does there exist a $\\pi \\in \\Pi$ such that $(u,v) \\in \\mc{E}_A$ if and only if $(\\pi(u),\\pi(v)) \\in \\mc{E}_B$. \r\n\t\t\\item \\textbf{Graph Matching (GM):}\r\n\t\t% Which $\\pi \\in \\Pi$ minimizes the number of pairs of vertices $u,v \\in \\mc{V}_A$ such that $(u,v) \\in \\mc{E}_A$ and $(\\pi (u) ,\\pi (v)) \\not \\in \\mc{E}_B$ or $(u,v) \\not \\in \\mc{E}_A$ and  $(\\pi (u) ,\\pi (v)) \\in \\mc{E}_B$\r\n\t\t Which $\\pi \\in \\Pi$ minimizes adjacency disagreements between $\\mc{E}_A$ and the permuted $\\mc{E}_B$?\r\n\\end{itemize}\r\n\r\n\r\nBoth GI and GM are computationally difficult. GM is at least as hard as GI, since solving GM also solves GI, but not vice versa. It is not known whether GI is in complexity class $\\mc{P}$ \\cite{Fortin1996}.  In fact, GI is one of the few problems for which, if $\\mc{P} \\neq \\mc{NP}$, then GI might reside in an intermediate complexity class called $\\mc{GI}$-complete.  GM, however, is known to be $\\mc{NP}$-hard.    \r\n % There exist no known algorithms for which worst case behavior is polynomial \\cite{Fortin1996}.  While GM is known to be $\\mc{NP}$-hard, it remains unclear whether GI is in $\\mc{P}$, $\\mc{NP}$, or its own intermediate complexity class, $\\mc{NP}$-isomorphism (or isomorphism-complete).  \r\nYet, for large classes of GI and GM problems, linear or polynomial time algorithms are available \\cite{Babai1980}.  Moreover, at worst, it is clear that GI is only ``moderately exponential,'' for example, $\\mc{O}(\\exp\\{n^{1/2 + o(1)}\\})$ \\cite{Babai1981}.  Unfortunately, even when linear or polynomial time GI or GM algorithms are available for special cases of graphs, the constants are typically unbearably large.  For example, if all vertices have degree less than $k$, there is a linear time algorithm for GI.  However, the hidden constant in this algorithm is $512k^3!$ (yes, that is a factorial!) \\cite{Chen1994}.  \r\n\r\nBecause we are interested in solving GM for graphs with $\\dot{\\approx} 10^6$ or more vertices, exact GM solutions will be computationally intractable. As such, we develop a fast approximate graph matching algorithm.   Our approach is based on formulating GM as a quadratic assignment problem (QAP).  %Below, we introduce assignment problems, and reiterate their close relationship to GI and GM \\cite{Burkard2009}.\r\n\r\n% section graph_matching (end)\r\n\r\n\r\n\\section{Graph  Matching as a QAP} % (fold)\r\n\\label{sub:preliminaries}\r\n\r\n% Our interests here lie in a particular instantiation of QAPs, the weighted graph matching problem \\cite{Umeyama1988}.  A \\emph{graph} is the mathematical abstraction of a network, consisting of a collection of vertices (or nodes)  and edges (or links, arcs) between them  \\cite{Bollobas1998}.  A \\emph{weighted graph},  is a kind of \\emph{attributed graph}, where each edge has associated with it a weight.  The (weighted) graph matching problem (WGMP) is the problem of ``aligning'' the vertices of a pair of (weighted) graphs such that each vertex in one graph can be assigned to its corresponding vertex in the other graph.\r\n% \r\n% Formally, let $G=(V,E)$ be a graph, where $V$ is the set of $|V|=n$ vertices and $E$ is the set of edges between them.  Let $i\\sim j$ indicate the presence of an edge from $i$ to $j$.  The \\emph{adjacency matrix} representations of a graph is a matrix, $A \\in \\Real^{n \\times n}$, where $a_{ij}=0$ if and only if $i\\sim j$.  In a weighted graph, $G=(V,E,A)$, each edge's weight can be non-binary, that is, $a_{ij} \\in \\Real$.\r\n\r\nGraph matching can be formulated as a quadratic assignment problem (QAP).  Let $A=(a_{uv}) \\in \\{0,1\\}^{n \\times n}$ and $B=(b_{uv}) \\in \\{0,1\\}^{n \\times n}$ correspond to the adjacency matrix representations of two graphs that we desire to match. That is, let $a_{uv}=1$ if and only if $(u,v) \\in \\mc{E}_A$, and similarly for $b_{uv}$.  Moreover, let $\\mc{P}$ be the set of  $n \\times n$ \\emph{permutation matrices}  $\\mc{P}=\\{P : P\\T \\mb{1} = P \\mb{1} = \\mb{1}, P \\in \\{0,1\\}^{n \\times n}\\}$, where $\\mb{1}$ is an $n$-dimensional column vector.\r\n% \r\n% % Let , and assume that $|V(A)|=|V(B)|=n$.  \r\nWe therefore have the following problem:  \r\n\\begin{subequations} \\label{eq:GM}\r\n\\begin{align}\r\n\\text{(QAP)} \\quad \t&\\argmin_{\\pi \\in \\Pi} \\sum_{i,j \\in [n]} (a_{ij} - b_{\\pi(i) \\pi(j)})^2= \\\\\r\n\t&\\argmin_{\\PmcP} \\norm{A - PBP\\T}_F = \\\\\r\n\t% &\\argmin_{\\PmcP} \\norm{PAP\\T - B}_F =\r\n\t% \\\\&\r\n\t% \\argmin_{\\PmcP} \\norm{PA - BP\\T} =\\\\\r\n\t% &\\argmin_{\\PmcP} (PAP\\T-B)\\T (PAP\\T-B) \\\\ \r\n\t&\\argmin_{\\PmcP} tr(A - PBP\\T)\\T (A - PBP\\T) = \\label{eq:trQAP2} \\\\\r\n\t% &\\argmin_{\\PmcP}  tr(P\\T A\\T P\\T P A P\\T) - 2tr(PAP\\T B) + tr(B\\T B)  = \\\\ %- tr(B\\T PAP\\T)\r\n\t&\\argmin_{\\PmcP} - tr(B P\\T AP), \\label{eq:trQAP} %\\\\ % - tr(PAP\\T B),\t\t\t\r\n\t% &\\argmin_{\\PmcP} tr (A\\T P\\T PA) - tr(2PA) + tr(B\\T B)=\\\\ \r\n\t% &\\argmin_{\\PmcP}  - tr(B\\T PAP\\T)=\\\\\r\n\t% &\\argmin_{\\PmcP}  -\\sum_{u \\in \\mc{V}} p_{ij} a_{ij} b_{ij} p_{ji} \r\n\t% = \\\\ &\\argmin_{\\PmcP}  -\\langle PAP\\T, B \\rangle.\r\n\t% \r\n\t% &\\argmin_{\\PmcP}  -\\langle B,PAP\\T \\rangle.\r\n\t % =\\\\\r\n\\end{align}\r\n\\end{subequations}\r\nwhere the last equality follows from dropping terms that cancel because $P$ is a permutation matrix. Note that the above algebraic formulation of GM facilitates generalizing the original problem statement. In particular, one can now search for the permutation that minimizes a particular objective function, $f(P)=- tr(B P\\T AP)$.  Moreover, it is natural to consider ``weighted graph matching''  problems, in which each edge is associated with a weight, $a_{uv} \\in \\Real$.  \r\n\r\n\r\n\r\n\r\n% Note that Eq. \\eqref{eq:trQAP} demonstrates that WGMP is indeed a QAP, although the $C$ matrix has been dropped. \r\nOur approach follows from relaxing the above binary constraints\r\n % of Eq. \\eqref{eq:trQAP} \r\nto be non-negative constraints, yielding a quadratic program with \\emph{linear} constraints.  %Specifically, we relax the binary constraint to a non-negative constraint.  \r\nThus, the feasible region expands to the convex hull of the permutation matrices: the doubly stochastic matrices, $\\mc{D}=\\{P : P\\T \\mb{1} =  P \\mb{1} = \\mb{1}, P \\succeq 0\\}$, where $\\succeq$ indicates an element-wise inequality:\r\n% the feasible space becomes the doubly stochastic matrices; that is, all matrices whose rows and columns both sum to unity, and whose elements are all non-negative, $\\mc{D}=\\{P : P\\T \\mb{1} =  P \\mb{1} = \\mb{1}, P \\succeq 0\\}$, where $\\succeq$ indicates an element-wise inequality. Because the equalities in Eq. \\eqref{eq:GM} follow from $P$ being a permutation matrix, relaxing the constraints for different formulations yields different optimization problems.  We relax the binary constraints in the trace formulation, yielding:\r\n\\begin{subequations} \\label{eq:FAQ}\r\n\\begin{align}\r\n\t\t\\text{(rQAP) } \\quad &\\underset{P}{\\text{minimize}}  && - tr(B P\\T AP) \\label{eq:FAQ1}  \\\\\r\n\t\t&\\text{subject to } && P \\in \\mc{D}.\r\n\\end{align}\r\n\\end{subequations}\r\n% FAQ---the above Fast Approximate Quadratic problem---is therefore a quadratic program with linear constraints, meaning that relatively standard solvers may be employed to search for approximately optimal solutions to an $\\mc{NP}$-hard problem.\r\n% \r\n% Importantly, the convex hull of permutation matrices is the set of doubly stochastic matrices, implying that this is a ``natural'' relaxation in a very meaningful sense.    Moreover, a\r\nrQAP---the above relaxed Quadratic Assignment Problem---is quadratic but not necessarily convex, \r\n% Although the objective function  $f(P)= - tr(B\\T PAP\\T)$ of  FAQ is ,\r\nbecause the Hessian of its objective function is not necessarily positive definite:\r\n\\begin{align}\r\n\t\\nabla^2 f(P)  =  - B \\otimes A - B\\T \\otimes A\\T,\r\n\\end{align}\r\nwhere $\\otimes$ indicates the Kronecker product. This means that the solution space will potentially be multimodal, making initialization important.  With this in mind, below, we describe an algorithm to find a local optimum of rQAP.\r\n\r\n\r\n\r\n% subsection preliminaries (end)\r\n\r\n\r\n% We therefore determined the average complexity of our algorithm \\emph{and} the leading constants.  Figure \\ref{fig:scaling} suggests that our algorithm is not just cubic in time, but also has very small leading constants ($\\dot{\\approx} 10^{-9}$ seconds), making using this algorithm feasible for even reasonably large graphs.\r\n\r\n\r\n\r\n\\section{Fast Approximate Quadratic Assignment Problem Algorithm} % (fold)\r\n\\label{sec:faq}\r\n\r\n\r\nOur algorithm, called \\texttt{FAQ}, has three components:\r\n\\begin{enumerate}[A.]\r\n\t\\item Choose a suitable initial position. % $P^{(0)} \\in \\mc{D}$.\r\n\t\\item Find a local solution to rQAP. %, $\\mh{D} \\in \\mc{D}$.\r\n\t\\item Project onto the set of permutation matrices. %, yielding $\\mh{P} \\in \\mc{P}$.\r\n\\end{enumerate}\r\n% We refer to one run of the above three steps as \\texttt{FAQ}.  For any integer $m$, upon using $m$ restarts, we report only the best solution, and we refer to the whole procedure as \\texttt{FAQ}$_m$.  \r\nBelow, we provide details for each component.\r\n\r\n\\textbf{A: Find a suitable initial position.}  While any doubly stochastic matrix would be a feasible initial point, we choose the \r\n% two choices seem natural: (i) the \r\n``flat doubly  stochastic matrix,'' $J=\\ve{1} \\cdot \\ve{1}\\T/n$, which is the barycenter of the feasible region.\r\n% , and (ii) the identity matrix, which is a permutation matrix.  We elect to use the barycenter as our default initial starting point.\r\n% Therefore, if we run \\FAQ  once, we always start with one of those two.  If we use multiple restarts, each initial point is ``near'' the flat matrix.  Specifically, we sample $K$, a random doubly stochastic matrix using 10 iterations of Sinkhorn balancing \\cite{Sinkhorn1964}, and let $P^{(0)}=(J+K)/2$. %Given this initial estimate, we iterate the following five steps until convergence.\r\n\r\n\r\n\\textbf{B: Find a local solution to rQAP.} As mentioned above, rQAP is a quadratic problem with linear constraints.  A number of off-the-shelf algorithms are readily available for finding local optima in such problems.  We utilize the Frank-Wolfe algorithm (\\texttt{FW}), a successive linear programing problem originally devised to solve quadratic problems with linear constraints \\cite{Frank1956, Bradley1977}.\r\n\r\n\r\nAlthough \\texttt{FW} is a relatively standard solver, especially as a subroutine for QAP algorithms \\cite{Anstreicher03}, below we provide a detailed view of applying \\texttt{FW} to rQAP.\r\n% , where our objective function is %. Let our objective function be that of Eq. \\eqref{eq:FAQ1}, \r\n% $f(P)=tr(B\\T PAP\\T)$. \r\nGiven an initial position, $P^{(0)}$, iterate the following four steps.\r\n\r\n\\emph{Step 1: Compute the gradient $\\nabla f(P^{(i)})$:}  The gradient $f$ with respect to $P$ is given by\r\n% \\emph{Step 1: Compute the gradient} The gradient of $f$ with respect to $P$ is given by\r\n\\begin{align} \\label{eq:grad}\r\n\t\\nabla f (P^{(i)}) = \r\n\t% \\partial f / \\partial P^{(i)} =\r\n\t  - A P^{(i)} B\\T - A\\T P^{(i)} B.\r\n\\end{align}\r\n\r\n\r\n\\emph{Step 2: Compute a new putative point $\\mt{P}^{(i+1)}$:} The new putative point is given by the argument that minimizes a first-order Taylor series approximation to $f(P)$ around the current estimate, $P^{(i)}$. The first-order Taylor series approximation to $f(P)$ is given by\r\n\\begin{align}\r\n\t\\mt{f}^{(i)}(P) \\defn f(P^{(i)}) + \\nabla f(P^{(i)})\\T(P - P^{(i)}).\r\n\\end{align}\r\nThus, Step 2 of \\texttt{FW} is\r\n% \\begin{align}\r\n% \t\t\\text{(FW1) } \\quad &\\underset{P}{\\text{minimize}}  && \\mt{f}(P)  \\\\\r\n% \t\t&\\text{subject to } && P \\in \\mc{D},\r\n% \\end{align}\r\n% which is equivalent to\r\n\\begin{subequations} \\label{eq:FW1}\r\n\\begin{align}\r\n\t\\mt{P}^{(i+1)} &= \\argmin_{P \\in \\mc{D}} f(P^{(i)}) + \\nabla f(P^{(i)})\\T(P - P^{(i)}) \r\n\t\\\\ &=\\argmin_{P \\in \\mc{D}} \\nabla f(P^{(i)})\\T P. \\label{eq:dotFW1}\r\n\t % \\\\ &=\\argmin_{P \\in \\mc{D}}  \\langle \\nabla f(P^{(i)}), P \\rangle, \r\n\\end{align}\r\n\\end{subequations}\r\nAs it turns out, Eq. \\eqref{eq:dotFW1} can be solved as a \\emph{Linear Assignment Problem} (LAP).  The details of LAPs are well known \\cite{Burkard2009}, so we relegate them to the appendix.  Suffice it to say here, LAPs can be solved via  the ``Hungarian Algorithm'', named after three Hungarian mathematicians \\cite{Kuhn1955, Konig1931, Egevary1931}.  Modern variants of the Hungarian algorithm are cubic in $n$, that is, $\\mc{O}(n^3)$, or even faster in the case of sparse or otherwise structured graphs \\cite{Jonker1987, Burkard2009}.  The $\\mc{O}(n^3)$ computational complexity of \\texttt{FW} was the primary motivating factor for utilizing \\texttt{FW}; generic linear programs can require up to $\\mc{O}(n^7)$.\r\n\r\n% Thus, we can solve the first step of FW upon computing \r\n\r\n\\emph{Step 3: Compute the step size $\\alpha^{(i)}$} Given $\\mt{P}^{(i+1)}$, the new point is given maximizing the \\emph{original} optimization problem, rQAP, along the line segment from $P^{(i)}$ to $\\mt{P}^{(i+1)}$ in $\\mc{D}$.    \r\n% \r\n% \\begin{align}\r\n% \td^{(i)}=L^{(i)}-P^{(i)}.\r\n% \\end{align}\r\n% \r\n% % paragraph step_3_updating_the_direction (end)\r\n% \r\n% \\emph{Step 4: Line search} Given this direction, one can then perform a line search to find the doubly stochastic matrix that minimizes the objective function along that direction:\r\n\\begin{align}\\label{eq:step}\r\n\t\\alpha^{(i)} = \\argmin_{\\alpha \\in [0,1]} f(P^{(i)} + \\alpha^{(i)} \\mt{P}^{(i)}).\r\n\\end{align}\r\nThis can be performed exactly, because $f$ is a quadratic function.  \r\n\r\n% paragraph step_4_line_search (end)\r\n\r\n\\emph{Step 4: Update $P^{(i)}$} Finally, the new estimated doubly stochastic matrix is given by\r\n\\begin{align}\\label{eq:update}\r\n\tP^{(i+1)} = P^{(i)} + \\alpha^{(i)} \\mt{P}^{(i+1)}.\r\n\\end{align}\r\n\r\n% paragraph step_5_update_q_ (end)\r\n\r\n\\emph{Stopping criteria} Steps 1--4 are iterated until some stopping criterion is met (computational budget limits, $P^{(i)}$ stops changing much, or $\\nabla f(P^{(i)})$ is close to zero).  These four steps collectively comprise the Frank-Wolfe algorithm for solving rQAP.  %Note that while $P^{(i)}$ will generally not be a permutation matrix, we do not project $P^{(i)}$ back onto the set of permutation matrices between each iteration, as that projection requires $\\mc{O}(n^3)$ time.\r\n\r\n\r\n\\textbf{C: Project onto the set of permutation matrices.}   Let $\\wh{D}$ be the doubly stochastic matrix resulting from the final iteration of \\texttt{FW}.  We project $\\wh{D}$ onto the set of permutation matrices, yielding\r\n\\begin{align} \\label{eq:proj}\r\n\t\\wh{P} = \\argmin_{\\PmcP} -\\langle \\wh{D}, P \\rangle,\r\n\\end{align}\r\nwhere $\\langle \\cdot,\\cdot \\rangle$ %the equality on the second to last line defines \r\nis the usual Euclidean inner product, i.e., $\\langle X,Y\\rangle \\defn tr(X\\T Y)= \\sum_{ij} x_{ij} y_{ij}$.  Note that Eq. \\eqref{eq:proj} is a LAP (again, see appendix for details).\r\n\r\n\r\n\r\n\\section{Results} % (fold)\r\n\\label{sec:theoretical_results}\r\n\r\n\r\n\r\n\r\n\r\n\\subsection{Algorithm Complexity and leading constants} % (fold)\r\n\\label{sub:algorithm_complexity_and_leading_constants}\r\n\r\n% Both GM and its closely related counterpart, graph isomorphism (GI), are computationally difficult.  There exist no known algorithms for which worst case behavior is polynomial \\cite{Fortin1996}.  While GM is known to be $\\mc{NP}$-hard, it remains unclear whether GI is in $\\mc{P}$, $\\mc{NP}$, or its own intermediate complexity class, $\\mc{NP}$-isomorphism (or isomorphism-complete).  Yet, for large classes of GI and GM problems, linear or polynomial time algorithms are available \\cite{Babai1980}.  Moreover, at worst, it is clear that GI is only ``moderately exponential,'' for example, $\\mc{O}(\\exp\\{n^{1/2 + o(1)}\\})$ \\cite{Babai1981}.  Unfortunately, even when linear or polynomial time GM or GI algorithms are available for special cases of graphs, the constants are typically unbearably large.  For example, if all graphs have degree less than $k$, there is a linear time algorithm for GI.  However, the hidden constant in this algorithm is $512k^3!$ \\cite{Chen1994}.  \r\nAs mentioned above, GM is computationally difficult; even those special cases for which polynomial time algorithms are available, the leading constants are intractably large for all but the simplest cases. We therefore determined the average complexity of our algorithm and the leading constants.  Figure \\ref{fig:scaling} suggests that our algorithm is not just cubic in time, but also has very small leading constants ($\\dot{\\approx} 10^{-9}$ seconds), making using this algorithm feasible for even reasonably large graphs.\r\n\r\n\r\n\r\n\\begin{figure}[htbp]\r\n\t\\centering\t\t\t\r\n\t\\includegraphics[width=1.0\\linewidth]{../figs/ErdosRenyi_results.pdf}\r\n\t\\caption{Running time of \\FAQ as function of number of vertices. Data was sampled from an Erd\\\"os-R\\'enyi model with $p=log(n)/n$.  Each dot represents a single simulation, with 100 simulations per $n$.  The solid line is the best fit cubic function.  Note the leading constant is $\\dot{\\approx} 10^{-9}$ seconds. \\FAQ finds the optimal objective function value in every simulation.}\r\n\t\\label{fig:scaling}\r\n\\end{figure}\r\n\r\n% subsection algorithm_complexity_and_leading_constants (end)\r\n\r\n\r\n\\subsection{QAP Undirected Benchmarks}\r\n\\label{sub:undirected}\r\n\r\nWe next assess the computational properties of \\FAQ in comparison with other the previous state-of-the-art algorithms.  We therefore compare \\FAQ to other approaches using a selection of the QAP benchmark library, QAPLIB \\cite{Burkard1997}.  Specifically, \\cite{Zaslavskiy2009} created a path following algorithm (\\texttt{PATH}) based on a convex and concave relaxation of QAP.  In that manuscript, the authors considered 16 datasets from the QAPLIB benchmark, the same 16 datasets as were used in \\cite{Schellewald2001}, which are known to be ``particularly difficult''.  \\texttt{PATH} was shown to outperform other state-of-the-art algorithms on 14 of 16 tests.  Specifically, \\texttt{PATH} was compared to the Quadratic Programming Bound approach (\\texttt{QGP}) of \\cite{Anstreicher2001}, the graduated assignment algorithm (\\texttt{GRAD}) of \\cite{Gold1996}, and Umeyama's algorithm (\\texttt{U}) \\cite{Umeyama1988}.  Because either \\texttt{PATH} or \\texttt{QBP} outperformed \\texttt{GRAD} and \\texttt{U} on every dataset, Table \\ref{tab:1} shows the performance of \\FAQ versus \\texttt{PATH} and \\texttt{QBP}.  \\FAQ outperforms both of the previous state-of-the-art cubic algorithms on 13 out of 16 benchmarks.  Figure \\ref{fig:path16} presents the same data graphically. The top panel compares both \\FAQ and \\texttt{PSOA}---which is the minimum of the previous state-of-the-art (either \\texttt{PATH} or \\texttt{QBP} here)---to the absolute minimum; \\FAQ get closer than \\texttt{PSOA} to the minimum on 13 of 16. The bottom panel shows the ratio of \\FAQ to \\texttt{PSOA}. \r\n\r\n\r\n\\begin{table}[h!]\r\n\\caption{Comparison of \\FAQ with the optimal objective function value and previous state-of-the-art on a set of 16 standard benchmarks from QAPLIB.  The best (lowest) value is in \\textbf{bold}. The number of vertices for each problem is the number in its name (second column).}\r\n\\begin{center}\r\n\\begin{tabular}{|r|r|r||l|l|l|l|l|}\r\n\\hline\r\n\\# & Problem  &   Optimal   & \\FAQ & \\texttt{PATH} & \\texttt{QBP} \\\\\r\n\\hline\r\n1&    chr12c &   11156 &    \\textbf{13072} &   18048 \t& 20306\\\\\r\n2&    chr15a &    9896 &    27584 &   \\textbf{19086} \t& 26132\\\\\r\n3&    chr15c &    9504 &    \\textbf{11936}  &   16206 \t& 29862\\\\\r\n4&   chr20b &    2298 & \\textbf{3068} &    5560 \t\t& 6674\\\\\r\n5&    chr22b &    6194 &    \\textbf{8482} &    8500 \t\t& 9942\\\\\r\n6&    esc16b & 292 &    320 & 300 \t\t& \\textbf{296}\\\\\r\n7& rou12 &  235528 &    \\textbf{253684} &  256320 \t& 278834\\\\\r\n8& rou15 &  354210 &    \\textbf{371458} &  391270 \t& 381016\\\\\r\n9& rou20 &  725522 &    \\textbf{743884} &  778284 \t& 804676\\\\\r\n10&    tai10a &  135028 &   157954 &  \\textbf{152534} \t& 165364\\\\\r\n11&    tai15a &  388214 &   \\textbf{397376} &  419224 \t& 455778\\\\\r\n12&    tai17a &  491812 &   \\textbf{529134} &  530978 \t& 550862\\\\\r\n13&    tai20a &  703482 &   \\textbf{734276} &  753712 \t& 799790\\\\\r\n14&    tai30a & 1818146 &  \t\\textbf{1894640} & 1903872 \t& 1996442\\\\\r\n15&    tai35a & 2422002 & \t\\textbf{2460940} & 2555110 \t& 2720986\\\\\r\n16&    tai40a & 3139370 &  \t\\textbf{3227612} & 3281830 \t& 3529402\\\\\r\n    \\hline\r\n\\end{tabular}\r\n\\end{center}\r\n\\label{tab:1}\r\n\\end{table}%\r\n\r\n\r\n\\begin{figure}[htbp]\r\n\t\\centering\r\n\t\t\\includegraphics[width=1.0\\linewidth]{../figs/path16.pdf}\r\n\t\\caption{Performance of \\FAQ relative to the previous state-of-the-art (\\texttt{PSOA}) algorithms on the undirected QABLIB benchmarks.  Top: The optimal error ratio is defined: $(\\mh{f} - f^*)/f^*$, for $\\mh{f}$ being the minimum function value found by each algorithm, and $f^*$ is the optimal (minimum) value.  Bottom: Ratio of \\FAQ minimum to \\texttt{PSOA} minimum.  Note that both panels indicate that \\FAQ gets closer to the minimum on 13 of 16 benchmarks.}\r\n\t\\label{fig:path16}\r\n\\end{figure}\r\n\r\n\r\n\\subsection{QAP Directed Benchmarks}\r\n\\label{sub:directed}\r\n\r\nNothing in the development of our algorithm depends on the graphs being simple; indeed, \\FAQ applies equally well to directed graphs.  To assess the performance of \\FAQ on directed graphs, we compare the performance of our algorithm to the previous state-of-the-art. Liu et al.  recently developed an extended path following algorithm for directed graphs \\cite{Liu2012}. They compare the performance of their algorithm (\\texttt{EPATH}) with several other algorithms on a set of 16 benchmarks from QAPLIB.  In particular, they consider \\texttt{U} and \\texttt{GRAD}, as well as an algorithm called \\texttt{QCV}, which solves a convex relaxation similar to our approach.  The \\texttt{EPATH} algorithm achieves at least as low objective value as the other algorithms on 15 of 16 benchmarks.  Our algorithm, \\texttt{FAQ}, always gets the best of the five algorithms.  Table \\ref{tab:directed} shows the numerical results comparing \\FAQ to \\texttt{EPATH} and \\texttt{GRAD}, which sometimes did better than \\texttt{EPATH}.  Note that some of the algorithms achieve the absolute minimum on some benchmarks.  Figure \\ref{fig:lipa16} compares \\FAQ to whichever other algorithm did best, clearly indicating that \\FAQ is the best on these benchmarks.\r\n\r\n\r\n\\begin{table}[h!]\r\n\\caption{Comparison of \\FAQ with optimal objective function value and previous state-of-the-art for undirected graphs.  The best (lowest) value is in \\textbf{bold}. Asterisks indicate achievement of the global minimum.  The number of vertices for each problem is the number in its name (second column).}\r\n\\begin{center}\r\n\\begin{tabular}{|r|r|r||l|l|l|l|l|}\r\n\t\\hline \r\n\t          \\# &  Problem &      Optimal & \\texttt{FAQ} & \\texttt{EPATH} & \\texttt{GRAD} \\\\\r\n\t\\hline \r\n\t           1 &  lipa20a &     3683 & \\textbf{3791} &     3885 &     3909 \\\\ \r\n\t           2 &  lipa20b &    27076 & \\textbf{27076}$^*$ &    32081 &    \\textbf{27076}$^*$ \\\\ \r\n\t           3 &  lipa30a &    13178 & \\textbf{13571} \t&    13577 &    13668 \\\\ \r\n\t           4 &  lipa30b &   151426 & \\textbf{151426}$^*$ & \\textbf{151426}$^*$ &   \\textbf{151426}$^*$ \\\\ \r\n\t           5 &  lipa40a &    31538 & \\textbf{32109} \t&    32247 &    32590 \\\\ \r\n\t           6 &  lipa40b &   476581 & \\textbf{476581}$^*$ &   \\textbf{476581}$^*$ &   \\textbf{476581}$^*$ \\\\ \r\n\t           7 &  lipa50a &    62093 & \\textbf{62962} &    63339 &    63730 \\\\ \r\n\t           8 &  lipa50b &  1210244 & \\textbf{1210244}$^*$ &  \\textbf{1210244}$^*$ &  \\textbf{1210244}$^*$ \\\\ \r\n\t           9 &  lipa60a &   107218 & \\textbf{108488} &   109168 &   109809 \\\\ \r\n\t          10 &  lipa60b &  2520135 & \\textbf{2520135}$^*$ &  \\textbf{2520135}$^*$ &  \\textbf{2520135}$^*$ \\\\ \r\n\t          11 &  lipa70a &   169755 & \\textbf{171820} &   172200 &   173172 \\\\ \r\n\t          12 &  lipa70b &  4603200 & \\textbf{4603200}$^*$ &  \\textbf{4603200}$^*$ &  \\textbf{4603200}$^*$ \\\\ \r\n\t          13 &  lipa80a &   253195 & \\textbf{256073} &   256601 &   258218 \\\\ \r\n\t          14 &  lipa80b &  7763962 & \\textbf{7763962}$^*$ &  \\textbf{7763962}$^*$ &  \\textbf{7763962}$^*$ \\\\ \r\n\t          15 &  lipa90a &   360630 & \\textbf{363937} &   365233 &   366743 \\\\ \r\n\t          16 &  lipa90b & 12490441 & \\textbf{12490441}$^*$ & \\textbf{12490441}$^*$ & \\textbf{12490441}$^*$ \\\\ \r\n\t\\hline\r\n\t\\end{tabular}\r\n\\end{center}\r\n\\label{tab:directed}\r\n\\end{table}%\r\n\r\n\r\n\\begin{figure}[htbp]\r\n\t\\centering\r\n\t\t\\includegraphics[width=1.0\\linewidth]{../figs/lipa16.pdf}\r\n\t\\caption{Performance of \\FAQ relative to the previous state-of-the-art (\\texttt{PSOA}) algorithms on the undirected QABLIB benchmarks. Top and Bottom panels as in Figure \\ref{fig:path16}.  Note that \\FAQ gets closer to the minimum on all 8 benchmarks for which the \\FAQ and \\texttt{PSOA} answer differ.}\r\n\t\\label{fig:lipa16}\r\n\\end{figure}\r\n\r\n\r\n\r\n\\subsection{rQAP solves QAP in certain special cases} % (fold)\r\n\\label{sub:rqap_solves_qap_}\r\n\r\nThe above numerical results can be strengthened by the below theoretical results.  \r\nNote that rQAP relaxes the constraints of Eq. \\eqref{eq:trQAP}, which suggests that in certain important special cases, the minimum of rQAP will be identical to the minimum of QAP. On the other hand, the equality between Eq. \\eqref{eq:trQAP2} and Eq. \\eqref{eq:trQAP} follows from dropping cross-terms that fall out of the optimization because $P$ is constrained to be a permutation matrix.  If we had relaxed the constraints prior to canceling those terms, this equality would not follow.  This leads us to wonder in which circumstances are the objective functions of QAP and rQAP equal.  The following lemma clarifies:\r\n % This insight leads to the following theorem:\r\n% Although, rLAP and LAP are always equivalent, in general, it is not the case that FAQ and QAP are equivalent.  However, in a certain important special case, FAQ and QAP are equivalent.\r\n\\begin{lem}\r\n\tIf $A$ and $B$ are the adjacency matrices of simple graphs (symmetric, hollow, and binary) that are isomorphic to one another, then the minimum of rQAP is equal to the minimum of QAP.\r\n\\end{lem}\r\n\\begin{proof}\r\nBecause any feasible solution to QAP is also a feasible solution to rQAP, we must only show that the optimal objective function value to rQAP can be no better than the optimal objective function value of QAP.  Let $A=PBP\\T$, so that $\\langle A, PBP\\T\\rangle=2m$, where $m$ is the number of edges in $A$.  If rQAP could achieve a lower objective value, then it must be that there exists a $D \\in \\mc{D}$ such that $\\langle A, DBD\\T\\rangle > \\langle A, PBP\\T\\rangle = 2m$ (remember that we are minimizing the negative Euclidean inner product). For that to be the case, it must be that $(DBD\\T)_{ij} \\geq 1$ for some $(u,v)$.  That this is not so may be seen by the submultiplicativity of the norm induced by the $\\ell_{\\infty}$ norm:\r\n$\\norm{Dx}_\\infty \\leq \\norm{D}_{\\infty,\\infty} \\norm{x}_\\infty$.  Applying this twice (once for each doubly stochastic matrix multiplication) yields our result.\r\n% Consider $d_i=\\langle D, \\text{col}_i(BD\\T) \\rangle$, where $\\text{col}_i(\\cdot)$ indicates the $i^{th}$ column of the matrix.  $d_i \\leq 1$ for all $i \\in [n]$, therefore, our result holds.\r\n\\end{proof}\r\n% subsection rqap_solves_qap_ (end)\r\n\r\n\r\n% section theoretical_results (end)\r\n\r\n% \\section{Numerical Results} % (fold)\r\n% \\label{sub:numerical_results}\r\n\r\n\r\n% subsection numerical_results (end)\r\n\r\n\r\n\\subsection{Multiple Restarts} % (fold)\r\n\\label{sub:multiple_restarts}\r\n\r\nAlthough \\FAQ outperformed \\texttt{PSOA} on 13 of 16 undirected benchmarks, and always did the best amongst 16 of 16 directed benchmarks, it was annoying to us that we did not do best on all 32 benchmarks.  \r\n% Note that the computational bottleneck of both \\FAQ and \\texttt{PATH} is the Hungarian algorithm which solves a LAP. \r\n% \\FAQ strives to solve a non-convex problem.\r\n% In \\texttt{PATH}, the algorithm finds the minimum of a convex path between two extremes, $F_0$ and $F_1$.  Similarly, \\texttt{QBP} finds the minimum of a convex program.  Our approach, on the other hand, does not construct a convex problem to solve, rather, it chooses an initial starting point and then finds a local optimum (note that the initial position of the \\texttt{PATH} algorithm could also be variable, because $F_0$ is not convex as they assert, so their starting point depends on their initialization). \r\n% \r\nWe utilize the non-convexity of rQAP is as a feature, although it can equally well be regarded as a bug  (because rQAP is non-convex so the solution found by \\FAQ depends on the initial condition).  It is a feature, however, if (i) we have some reason to believe that better solutions exist (many algorithms efficiently compute relatively tight lower bounds \\cite{Anstreicher2009}), and (ii) we can efficiently search the space of initial conditions.  Although we  lack any supporting theory of optimality, we do know how to sample feasible starting points.  Specifically, we desire that our starting points are ``near'' the flat matrix, and satisfy the conditions.  Therefore, we  sample $K \\in \\mc{D}$, a random doubly stochastic matrix using 10 iterations of Sinkhorn balancing \\cite{Sinkhorn1964}, and let our initial guess be $P^{(0)}=(J+K)/2$, where $J$ is the doubly flat matrix.  We can therefore use any number of restarts with this approach.  \r\n\r\nTable \\ref{tab:2} shows the performance of running \\FAQ 3 and 100 times, reporting only the best result (indicated by \\texttt{FAQ}$_3$ and \\texttt{FAQ}$_{100}$, respectively), and comparing it to the best performing result from Table \\ref{tab:1}.  It only required three restarts to outperform all other cubic algorithms on all 16 of 16 benchmarks.  Moreover, after 100 restarts, \\FAQ finds the absolute minimum on 3 of the 16 benchmarks. Figure \\ref{fig:restarts} graphically demonstrates these results. \r\n Note that restarting \\FAQ a fixed number of multiple times is still cubic.  Future work could investigate performance as a function of the number of restarts. %, although with an arbitrary number of random restarts, stating that it is cubic is somewhat meaningless.  \r\n\r\n\r\n\r\n\\begin{table}[h!]\r\n\\caption{Comparison of \\FAQ with optimal objective function value and the best result from Table \\ref{tab:1} on undirected benchmarks.  Note that \\FAQ restarted 100 times finds the optimal objective function value in 3 of 16 benchmarks, and that \\FAQ restarted 3 times finds a minimum better than the PSOA on all 16 benchmarks.}\r\n\\begin{center}\r\n\\begin{tabular}{|r|r|r||l|l|l|l|l|}\r\n\\hline\r\n\\# & Problem  &   Optimal    & \\texttt{FAQ}$_{100}$ & \\texttt{FAQ}$_{3}$ & min(\\FAQ,\\texttt{PSOA}) \\\\\r\n\\hline\r\n1&    chr12c &   11156 &    \\textbf{12176} &   13072 & 13072 \\\\\r\n2&    chr15a &    9896 &    \\textbf{9896}$^*$ &   17272 &  19086 \\\\\r\n3&    chr15c &    9504 &    \\textbf{10960} &   14274 &  16206 \\\\\r\n4&   chr20b &    2298 &     \\textbf{2786} &    3068 &    3068 \\\\\r\n5&    chr22b &    6194 &    \\textbf{7218} &    7876 &   8482 \\\\\r\n6&    esc16b & \t292 & \t\t\\textbf{292}$^*$ & 294 &    296 \\\\\r\n7& \t   rou12 &  235528 &  \\textbf{235528}$^*$ &  238134 &    253684 \\\\\r\n8& \t   rou15 &  354210 &  \\textbf{356654} &  371458 &    371458 \\\\\r\n9&      rou20 &  725522 &  \\textbf{730614} &  743884 &    743884 \\\\\r\n10&    tai10a &  135028 &  \\textbf{135828} &  148970 &    152534 \\\\\r\n11&    tai15a &  388214 &  \\textbf{391522} &  397376 &    397376 \\\\\r\n12&    tai17a &  491812 &  \\textbf{496598} &  511574 &    529134 \\\\\r\n13&    tai20a &  703482 &  \\textbf{711840} &  721540 &    734276 \\\\\r\n14&    tai30a & 1818146 & \\textbf{1844636} & 1890738 &  1894640 \\\\\r\n15&    tai35a & 2422002 & \\textbf{2454292} & 2460940 &  2460940 \\\\\r\n16&    tai40a & 3139370 & \\textbf{3187738} & 3194826 &  3227612 \\\\\r\n    \\hline\r\n\\end{tabular}\r\n\\end{center}\r\n\\label{tab:2}\r\n\\end{table}%\r\n\r\n\\begin{figure}[htbp]\r\n\t\\centering\r\n\t\t\\includegraphics[width=1.0\\linewidth]{../figs/path16_restarts.pdf}\r\n\t\\caption{Performance of \\FAQ with multiple restarts on the undirected benchmarks. \\texttt{FAQ}$_3$ yields a lower objective function value than the best result from Figure \\ref{fig:path16}, and \\texttt{FAQ}$_{100}$ finds the absolute optimal permutation on 3 of the 16 benchmarks.  Note that no other algorithm compared ever found the optimal for any of the benchmarks.}\r\n\t\\label{fig:restarts}\r\n\\end{figure}\r\n\r\n\r\n% subsection multiple_restarts (end)\r\n\r\n% \r\n% \\begin{figure}[htbp]\r\n% \t\\centering\t\t\t\r\n% \t\\includegraphics[width=1.0\\linewidth]{../figs/benchmarks.pdf}\r\n% \t\\caption{\\texttt{FAQ}$_3$ outperforms the previous state-of-the-art (PSOA) on all 16 benchmark graph matching problems.  Moreover, \\FAQa outperforms PSOA on 12 of 16 tests.  For 3 of 16 tests, \\FAQb achieves the minimum (none of the other algorithms ever find the absolute minimum), as indicated by a black dot.  Let $f_*$ be the minimum and $\\mh{f}_x$ be the minimum achieved by algorithm $x$.  Error is $\\mh{f}_x/f_*-1$.  }\r\n% \t\\label{fig:fwpath}\r\n% \\end{figure}\r\n\r\n\r\n\r\n\\subsection{Brain-Graph Matching} % (fold)\r\n\\label{sub:connectome_classification}\r\n\r\nA ``connectome'' is a brain-graph in which vertices correspond to (collections of) neurons, and edges correspond to connections between them. The \\emph{Caenorhabditis elegans} (\\emph{C. elegans}) is a small worm (nematode) with $302$ labeled vertices.  We consider the subgraph with $279$ somatic neurons that form edges with other neurons \\cite{WhiteBrenner86, Varshney2011}.  Two distinct kinds of edges exist between vertices: chemical and electrical ``synapses'' (edges). Any pair of vertices may have several edges of each type. Moreover, some of the synapses are hyper-edges amongst more than two vertices.   Thus, the connectome of a \\emph{C. elegans} may be thought of as a weighted multi-hypergraph, where the weights are the number of edges of each type.  \\FAQ natively operates on weighted or unweighted graphs.  We therefore conducted the following synthetic experiments.  \r\n\r\nLet $A_{ij;z} \\in \\{0,1,2,\\ldots\\}$ be the number of synapses from neuron $i$ to neuron $j$ of type $z$ (either chemical $c$ or electrical $e$), and let $A_z=\\{A_{ij;z}\\}_{i,j \\in [279]}$ for $z \\in \\{e,c\\}$ correspond to the electrical or chemical connectome.  To generate synthetic data, we let $B_z^{(k)}=Q_z^{(k)} A_z {Q_z^{(k)}}\\T$, for some $Q_z^{(k)}$ chosen uniformly at random from $\\mc{P}$, effectively shuffling the vertex labels of the connectome.  Then, we try to graph match $A_z$ to $B_z^{(k)}$, for $z \\in \\{e,c\\}$ and for $k =1,2,\\ldots, 1000$, that is, we repeat the experiment $1000$ times.  We define accuracy as the fraction of vertices correctly assigned. We always start with the doubly flat matrix.\r\n% by the value of our objective function, $f(P_z^{(k)})$.  \r\n% To evaluate the impact of multiple restarts, for both connectomes, we restarted \\FAQ up to 30 times.   Specifically, our stopping criteria on the number of restarts was either (i) perfect assignment or (ii) 30 restarts.\r\n\r\n% Table \\ref{tab:1} shows the mean (standard deviation) of accuracy and solution time for both connectomes.  For the chemical connectome, \\FAQ always found the optimal solution, but not so for the electrical connectome.  \r\n\r\n\r\n\\begin{figure}[htbp]\r\n\t\\centering\r\n\t\t\\includegraphics[width=1.1\\linewidth]{../figs/connectomes.pdf}\r\n\t\\caption{Performance of \\texttt{U}, \\texttt{QCV}, \\texttt{PATH}, and \\FAQ on synthetic C.~elegans connectome data, that is, graph matching the true connectomes with permuted versions of themselves.  Error is the fraction of vertices correctly matched.  Circle indicates the median, thick black bars indicate the quartiles, thin black lines indicate extreme but non-outlier points, and plus signs are outliers. The top panels indicate error (fraction of misassigned vertices), and the bottom panels indicate wall time on a 2.2 GHz Apple MacBook.  The left panels show the chemical connectome results, and the right panels show the electrical connectome results. For the chemical connectome, \\FAQ always obtained the optimal solution, whereas none of the other algorithms ever found the optimal.  On the other hand, for the electrical connectome, none of the algorithms ever found the optimal.  \\FAQ also ran very quickly, nearly as quickly as \\texttt{U} and \\texttt{QCV}, and much faster than \\texttt{PATH}, even though our \\FAQ implementation is in Matlab, and the others are in C.}\r\n\t\\label{fig:connectomes}\r\n\\end{figure}\r\n\r\n\r\nFigure \\ref{fig:connectomes} displays the results of \\FAQ along with three previous state-of-the-art algorithms on the two connectomes: (i) Umeyama's algorithm\\texttt{U}, (ii) a quadratic convex relaxation \\texttt{QCV} (which follows from relaxing the permutation matrix constraint to the doubly stochastic constraint in Eq. \\eqref{eq:trQAP2}), and (iii) \\texttt{PATH}.  The top left panel indicates that \\FAQ \\emph{always} found the optimal solution for the chemical connectome, whereas none of the other algorithms \\emph{ever} found the optimal solution.  On the other hand, the top right panel shows that for the electrical connectome, none of the four algorithms ever found the optimal. One hundred restarts of \\FAQ failed to significantly improve the results. \r\n\r\nThe bottom panels compare the wall time of the various algorithms, running on an 2.2 GHz Apple MacBook. Note that we have only a Matlab implementation of \\texttt{FAQ}, whereas the other algorithms are implemented in C.  Nonetheless, \\FAQ runs nearly as quickly as both \\texttt{U} and \\texttt{QCV}, and significantly faster than \\texttt{PATH}, for both connectomes.  %This suggests that lower level language implementation of \\FAQ might be \r\n\r\n % \\FAQ ran very quickly, finding the optimal solution for the chemical connectome and converging for the electrical connectome, in only a few seconds.  Although computer times are not directly comparable, as our \\FAQ implementation is in Matlab, and the other algorithms are coded in C, consider \\FAQ versus \\texttt{PATH}.  The bottleneck in both is \\texttt{FW}.  In \\texttt{PATH}, the number of \\texttt{FW}s depends on a parameter, $d\\lambda$, which sets the step size along the path. The \\texttt{PATH} paper, \\cite{Zaslavskiy2009}, describes an adaptive scheme for updating $d\\lambda$, with a lower bound of $10^{-5}$, clearly indicating that sometimes, \\texttt{FW} is run many times.  On the other hand, in \\texttt{FAQ}, \\texttt{FW} is always run only once.  \r\n\r\nThe properties of these connectomes are analyzed in \\cite{Varshney2011}; a cursory evaluation of the properties of these graphs does not suggest to us why the chemical connectome was so much easier to graph match than the electrical one. \r\n\r\n\r\nTo investigate the performance of \\FAQ on undirected graphs, we ran \\FAQ on binarized symmeterized versions of the graphs ($A_{ij;z}=1$ if and only if $A_{ij;z}\\geq 1$ or $A_{ji;z} \\geq 1$).  The resulting errors are nearly identical to those presented in Figure \\ref{fig:connectomes}, although speed increased by greater than a factor of two. Note that the number of vertices in this brain-graph matching problem---279---is several times larger than the largest of the 32 benchmarks used above. \r\n\r\n\r\n\r\n\r\n\\section{Discussion}\r\n\\label{sec:discussion}\r\n\r\nThis work presents a fast approximate quadratic assignment problem algorithm called \\FAQ for approximately solving large graph matching problems, motivated by brain-graphs.  Our key insight was to relax the binary constraint of QAP to its continuous and non-negative counterpart---the doubly stochastic matrix---which is the convex hull of the original feasible region.  \r\nNumerically, we demonstrated that not only is \\FAQ cubic in time, but also its leading constants are quite small---$10^{-9}$---suggesting that it can be used for graphs with hundreds or thousands of vertices.  Moreover, it achieves better performance than previous state-of-the-art cubic-time algorithms on 29 of the 32 standard QAP benchmarks, including both directed and undirected graph matching problems.  Because rQAP is non-convex, we also consider multiple restarts, and achieve improved performance for the remaining three benchmarks using only two or three restarts.  We then demonstrate that the solution to our relaxed optimization problem, rQAP, is identical to that for QAP whenever the two graphs are simple and isomorphic to one another.  Finally, we used it to match C.~elegans connectomes to permuted versions of themselves. For the chemical connectome, of the four state-of-the-art algorithms considered, \\FAQ achieved perfect performance $100\\%$ of the time, whereas none of the other three algorithms ever achieved perfect performance. On the other hand, all the algorithms struggled with the electrical connectome.   Moreover, \\FAQ ran about as fast as two of them, and significantly faster than \\texttt{PATH}, even though \\FAQ is implemented in Matlab, and the others are implemented in C.  Note that these connectomes have 302 vertices, several-fold more than even the largest benchmarks. \r\n\r\n% our motivating application: brain-graph matching.  \\FAQ solved a brain-graph matching problem, which has an order of magnitude more vertices than any of the 16 QAP benchmarks.\r\n\r\n% These insights led to an approximate QAP solver with a few distinct features. %While others have incorporated the FW algorithm as a subroutine of a graph matching strategy \\cite{Zaslavskiy2009}, we modified the FW algorithm for GM in a few ways.  \r\n\r\n% First, after finding a local solution to the relaxed problem, we project the resulting doubly stochastic matrix onto the set of permutation matrices.  Second, we initialize the algorithm using either the identity matrix or the doubly flat matrix (the matrix where all elements are $1/n$).  These choices seem to us to be the most obvious places to start if one must choose.  Third, if one of those choices does not work, we restart FW with other ``nearby'' initial points.  These modifications facilitate improved performance on \\emph{all} the benchmarks we considered.  Moreover, although the algorithm scales cubically with the number of vertices, the leading constants are very small ($\\mc{O}(10^{-9})$ seconds), so the algorithm runs quite fast on reasonably sized networks (e.g., $n \\dot{\\approx} 100$).  Indeed, on a biologically inspired GM problem, \\emph{C. elegans} connectome mapping, this approach was both fast and effective.  \r\n\r\nFortunately, our work is not done. Even with very small leading constants for this algorithm, as $n$ increases, the computational burden gets quite high.  For example, extrapolating the curve of Figure \\ref{fig:scaling}, this algorithm would take about 20 years to finish (on a standard laptop from 2011) when $n=100,000$.  We hope to be able to approximately solve rQAP on graphs much larger than that, given that the number of neurons even in a fly brain, for example, is $\\approx 250,000$.  More efficient algorithms and/or implementations are required for such massive graph matching. \r\n\r\n% more efficient algorithms and/or implementations are essential.\r\n\r\n% Although \\FAQm consistently found the optimal solution for the \\emph{C. elegans} chemical connectome, connectomes for different organisms even within a species are unlikely to be identical. Even if all connectomes of a particular species were identical, measurement error will likely persist \\cite{Helmstaedter2011}. Therefore, \\texttt{FAQ}$_m$'s scientific utility will largely rest on its performance under noisy conditions, which we aim to explore in future work.  \r\n\r\nAdditional future work might generalize \\FAQ in a number of ways.  First, many (brain-) graphs of interest will be errorfully observed \\cite{Priebe2011}, that is, vertices might be missing and putative edges might exhibit both false positives and false negatives.  Explicitly dealing with this error source is both theoretically and practically of interest \\cite{VP11_unlabeled}.  \r\n% that QAP and LAP are so similar suggests that perhaps one could simply implement a single iteration of QAP starting from the identity.  While not changing the order of complexity, it could reduce computational time by at least an order of magnitude, without drastically changing performance properties (because convergence typically requires around $5-15$ iterations for the graphs we tested).  The relative performance/computational cost trade-off merits further theoretical investigations.  \r\nSecond, for many brain-graph matching problems, the number of vertices will not be the same across the brains.  Recent work from \\cite{Zaslavskiy2009, Zaslavskiy2010} and \\cite{Escolano2011} suggest that extensions in this direction would be both relatively straightforward and effective. Third, the most ``costly'' subroutine is LAP.  Fortunately, LAP is a quadratic optimization problem with linear constraints.  A number of parallelized optimization strategies could therefore potentially be brought to bear on this problem \\cite{Boyd2011}.  Fourth, our matrices have certain special properties, namely sparsity, which makes more efficient algorithms (such as ``active set'' algorithms) readily available for further speed increases.  Fourth, for brain-graphs, we have some prior information that could easily be incorporated in the form of vertex attributes.  For example, position in the brain, cell type, etc., could be used to measure ``dissimilarity'' between vertices.  %The WGMP could easily incorporate these dissimilarities, in fact, the original QAP formulation already encodes them via the matrix $C$; that matrix was simply dropped when WGMP was originally proposed.  \r\n% The objective function could then be modified to give\r\n% \\begin{align} \\label{eq:Jqap}\r\n% \t\\mt{Q}_{AB}= \\argmin_{Q \\in \\mc{D}} \\norm{Q A Q\\T - B}^2_F + \\lambda J(Q),\r\n% \\end{align}\r\n% where $J(Q)$ is a dissimilarity based penalty and $\\lambda$ is a hyper-parameter.  \r\nFinally, although this approach natively operates on both unweighted and weighted graphs, multi-graphs are a possible extension.\r\n\r\nIn conclusion, this manuscript has presented an algorithm for approximately solving the quadratic assignment problem that is fast, effective, and easily generalizable.  Yet, the $\\mc{O}(n^3)$ complexity remains too slow to solve many problems of interest.  To facilitate further development and applications, all the code and data used in this manuscript is available from the first author's website, \\url{http://jovo.me}.\r\n\r\n% \\subsection{Related Problems} % (fold)\r\n% \\label{sub:related_problems}\r\n% \r\n% In addition to brain-graph matching, large approximate graph matching could be fruitful for a number of other domains.  For example, consider social networks.  In both the Twitter and Facebook graph, each vertex represents an individual.  For many users of each social networking application, it is not clear whether they have an account on another social network, and if so, what is the label of that account.  Thus, graph matching in this domain could suggest assignments of Facebook user names to twitter accounts.  Alternately, consider a language graph, where each vertex represent a word in some language, and an edge represent the existence of an adjacency between a pair of words in a text corpus of that language.  If one could match a pair of graphs corresponding to two different languages, one might obtain a highly effective machine translation tool. This might be especially true when no additional information is known about one or both languages.\r\n% \r\n% Consider the scale of these problems.  Twitter and Facebook have $\\mc{O}(10^8)$ users and languages often have $\\mc{O}(10^5)$ words.  Exact graph matching algorithms require exponential time in the worst case.  So, even considering the smallest problem above, brain-graph matching, the fastest exact graph matching algorithms would require more time than there are nanoseconds since the big bang.\\footnote{Assuming the big bang occurred 15 billion years ago means about $10^{17}$ seconds ago.  Assuming computational time is $1.004^n$ nanoseconds, even when $n=10^4$, the problem will already exceed the number of seconds since the big bang} This motivates us to consider developing \\emph{approximate} (or \\emph{heuristic}) algorithms, with polynomial time complexity.  Indeed, we present here an algorithm the requires approximately one week on a standard desktop computer (running non-optimized code) to match graphs with $\\mc{O}(10^4)$ vertices.\r\n% \r\n% \r\n% % subsection related_problems (end)\r\n\r\n\r\n\\appendix\r\n\r\n% \\textbf{APPENDIX}\r\n\\section{Linear Assignment Problems} % (fold)\r\n% \\label{ssub:linear_assignment_problems}\r\n\r\n% subsubsection linear_assignment_problems (end)\r\n\r\nThe standard way of writing a Linear Assignment Problem (LAP) is\r\n\\begin{subequations} \\label{eq:LAP}\r\n\\begin{align}\r\n\t \\text{(LAP) }\\quad  &\\underset{\\pi}{\\text{minimize}} \\sum_{u,v \\in [n]} a_{u \\pi(v)} b_{ij} \\\\\r\n\t&\\text{subject to } \\pi \\in \\Pi,\r\n\\end{align}\r\n\\end{subequations}\r\nwhich can be written equivalently in a number of ways using the notion of permutation matrix introduced in the main text:\r\n\\begin{subequations} \\label{eq:LAP2}\r\n\\begin{align}\r\n\t&\\argmin_{\\PmcP} \\norm{PA - B}_F =\\\\\r\n\t&\\argmin_{\\PmcP} \\, tr(PA-B)\\T (PA-B)=\\\\ \r\n\t% &\\argmin_{\\PmcP} tr (A\\T P\\T PA) - tr(2PAB\\T) + tr(B\\T B)=\\\\ \r\n\t&\\argmin_{\\PmcP}  -tr (P AB\\T) = \\argmin_{\\PmcP}  -\\langle P\\T, AB\\T \\rangle = \\label{eq:2c} \\\\\r\n\t% &\\argmin_{\\PmcP}  -\\sum_{u,v \\in [n]} p_{ij} a_{ij} b_{ji}\r\n\t% =\\\\% &\\argmin_{\\PmcP}  - \\text{vec}(P)\\T \\text{vec}(AB\\T).=\\\\\r\n\t&\\argmin_{\\PmcP}  -\\langle P, AB\\T \\rangle, \\label{eq:dotLAP}\r\n\\end{align}\r\n\\end{subequations}\r\nwhere $\\langle \\cdot,\\cdot \\rangle$ %the equality on the second to last line defines \r\nis the usual Euclidean inner product, i.e., $\\langle X,Y\\rangle \\defn tr(X\\T Y)= \\sum_{ij} x_{ij} y_{ij}$.\r\nWhile the objective function and the first two constraints of LAP are linear, the binary constraints make solving even this problem computationally tricky.  Nonetheless, in the last several decades, there has been much progress in accelerating algorithms for solving LAPs, starting with exponential time, all the way down to $\\mc{O}(n^3)$ for general LAPs, and even faster for certain special cases (e.g., sparse matrices) \\cite{Jonker1987, Burkard2009}.\r\n\r\nThat Eq. \\eqref{eq:dotFW1} is a LAP is evident by considering Eq. \\eqref{eq:dotLAP}.  If $A=\\nabla_P^{(i)}$ and $B=I$ (the $n\\times n$ identity matrix), then Eq. \\eqref{eq:dotFW1} is identical to Eq. \\eqref{eq:dotLAP}.\r\n\r\n\r\n% The last form indicates that LAP is a linear programming problem (hence the name).  Yet, the constraints, $\\mc{P}$, make it a bit trickier.  The feasible region $\\mc{P}$ can be written as a set of three constraints: two linear equality constraint sets and a binary constraint.  The LAP objection function with constraints can explicitly be written:\r\n% \\begin{align}\r\n% \t\t&\\text{minimize}_P  &&\\sum_{u \\in \\mc{V}} -p_{ij} a_{ij} b_{ji} \\nonumber \\\\\r\n% \t\t&\\text{subject to } && \\sum_{u \\in \\mc{V}} p_{ij} = 1 \\, \\forall u \\in \\mc{V} \\nonumber \\\\\r\n% \t\t& && \\sum_{v \\in \\mc{V}} p_{ij} = 1 \\, \\forall v \\in \\mc{V}, \\nonumber \\\\\r\n% \t\t& &&p_{ij} \\in \\{0,1\\} \\, \\forall u,v. \\label{eq:rLAP}\t\r\n% \\end{align}\r\n% Perhaps because LAP comes up in a wide variety of contexts, a large number of algorithms have been developed to solve LAP \\cite{Burkard2009}.  These algorithms have become increasing efficient.  \r\n% One of the most popular algorithms, the so-called ``Hungarian algorithm'' has time complexity $\\mc{O}(n^3)$ \\cite{Jonker1987}.  Under certain conditions (for example, when $AB\\T$ is sparse), faster implementations are also available.  As will be seen below, LAP is a key subroutine to our inexact QAP solution.  \r\n\r\nTo solve a LAP, consider a continuous relaxation of LAP, specifically, relaxing the permutation matrix constraint to a doubly stochastic matrix constraint:\r\n% A matrix $P$ is doubly stochastic precisely when $P$ satisfies the following three conditions: \r\n% \\begin{enumerate}\r\n% \\item\t$P\\mb{1} = \\mb{1}$,\r\n% \\item\t$P\\T \\mb{1}=\\mb{1}$, %\\\\\r\n% \\item \t$P \\in  \\Real_+^{n \\times n}$,\r\n% \\end{enumerate}\r\n% where the third constraint relaxes the binary constraints of the permutation matrices with a non-negativity constraint.  \r\n% Let $\\mc{D}$ be the set of doubly stochastic matrices.\r\n% With this, we now state a relaxed LAP problem:\r\n\\begin{subequations} \\label{eq:rLAP}\r\n\\begin{align}\r\n\t\t\\text{(rLAP) } \\quad &\\underset{P}{\\text{minimize}}  &&-\\langle P, AB\\T \\rangle \\\\\r\n\t\t&\\text{subject to } && P \\in \\mc{D}.\r\n\t\t% && \\sum_{u \\in \\mc{V}} p_{ij} = 1 \\, \\forall u \\in \\mc{V} \\nonumber \\\\\r\n\t\t% \t\t& && \\sum_{v \\in \\mc{V}} p_{ij} = 1 \\, \\forall v \\in \\mc{V}, \\nonumber \\\\\r\n\t\t% \t\t& &&p_{ij} \\geq 0 \\, \\forall u,v, \\label{eq:ALAP}\t\r\n\\end{align}\r\n\\end{subequations}\r\nAs it turns out, solving rLAP is equivalent to solving LAP.\r\n\\begin{prop}\r\n\tLAP and rLAP are equivalent, meaning that they have the same optimal objective function value.\r\n\\end{prop}\r\n\\begin{proof}\r\n\tAlthough this proposition is typically proven by invoking total unimodularity, we present a simpler proof here.\tLet $P'$ be a solution to LAP and let $P = \\sum_{i\\in[k]} \\alpha_i P^{(i)}$ be a solution to rLAP for some positive integer $k$, permutation matrices $\\{P^{(i)}\\}_{i \\in [k]}$, and positive real numbers $\\{\\alpha_i\\}_{i \\in[k]}$ such that $\\sum_{i \\in [k]} \\alpha_i=1$.  Note that \r\n\t\\begin{align*}\r\n\t\\langle P,AB\\T \\rangle &= \\langle  \\sum_{i\\in[k]} \\alpha_i P^{(i)}, AB\\T \\rangle=  \\sum_{i\\in[k]} \\alpha_i \\langle  P^{(i)}, AB\\T \\rangle\t \\\\\r\n\t&\\leq \\sum_{i\\in[k]} \\alpha_i \\langle P', AB\\T  \\rangle = \\langle P', AB\\T \\rangle \\leq \\langle P, AB\\T \\rangle,\r\n\t\\end{align*}\r\n\t% then we have a contradiction, \r\n\tbecause $P'$ is feasible in rLAP.\r\n\t\\end{proof}\r\nThis relaxation motivates our approach to approximating QAP.\r\n\r\n\t\r\n\r\n\r\n\r\n% use section* for acknowledgement\r\n\\ifCLASSOPTIONcompsoc\r\n  % The Computer Society usually uses the plural form\r\n  \\section*{Acknowledgments}\r\n\\else\r\n  % regular IEEE prefers the singular form\r\n  \\section*{Acknowledgment}\r\n\\fi\r\n\r\nThe authors would like to acknowledge two helpful reviewers as well as Lav Varshney for providing the data.\r\n% This work was partially supported by the Research Program in Applied Neuroscience. \r\n\r\n% Can use something like this to put references on a page\r\n% by themselves when using endfloat and the captionsoff option.\r\n\\ifCLASSOPTIONcaptionsoff\r\n  \\newpage\r\n\\fi\r\n\r\n\\bibliography{/Users/jovo/Research/other/latex/library}\r\n\\bibliographystyle{IEEEtran}\r\n\r\n% \\begin{IEEEbiographynophoto}{Joshua T. Vogelstein}\r\n% % Joshua T. Vogelstein is a spritely young man, engulfed in a novel post-buddhist metaphor.\r\n% \r\n% \\end{IEEEbiographynophoto}\r\n% \r\n% \r\n% % insert where needed to balance the two columns on the last page with\r\n% % biographies\r\n% %\\newpage\r\n% \r\n% \\begin{IEEEbiographynophoto}{John C.~Conroy}\r\n% % John C.~Conroy seems to basically always be right. He also publishes sometimes.\r\n% \r\n% \\end{IEEEbiographynophoto}\r\n% \r\n% % \\begin{IEEEbiographynophoto}{Doniell E.~Fishkind}\r\n% % % John C.~Conroy seems to basically always be right. He also publishes sometimes.\r\n% % \r\n% % \\end{IEEEbiographynophoto}\r\n% \r\n% \\begin{IEEEbiographynophoto}{Lou Podrazik}\r\n% \r\n% \\end{IEEEbiographynophoto}\r\n% \r\n% \\begin{IEEEbiographynophoto}{Steve Kratzer}\r\n% \r\n% \\end{IEEEbiographynophoto}\r\n% \r\n% \r\n% \r\n% \\begin{IEEEbiographynophoto}{R. Jacob Vogelstein}\r\n% % R. Jacob Vogelstein received the Sc.B. degree in neuroengineering from Brown University, Providence, RI, and the Ph.D. degree in biomedical engineering from the Johns Hopkins University School of Medicine, Baltimore, MD.  He currently oversees the Applied Neuroscience programs at the Johns Hopkins University (JHU) Applied Physics Laboratory as an Assistant Program Manager, and has an appointment as an Assistant Research Professor at the JHU Whiting School of Engineering’s Department of Electrical and Computer Engineering. He has worked on neuroscience technology for over a decade, focusing primarily on neuromorphic systems and closed-loop brain–machine interfaces. His research has been featured in a number of prominent scientific and engineering journals including the IEEE Transactions on Neural Systems and Rehabilitation Engineering, the IEEE Transactions on Biomedical Circuits and Systems, and the IEEE Transactions on Neural Networks.  \r\n% \\end{IEEEbiographynophoto}\r\n% \r\n% \\begin{IEEEbiographynophoto}{Carey E. Priebe}\r\n% % Buddha in training.\r\n% \\end{IEEEbiographynophoto}\r\n% \r\n% % Can be used to pull up biographies so that the bottom of the last one\r\n% % is flush with the other column.\r\n% % \\enlargethispage{-5in}\r\n\r\n\\input{../PAMI/QAP-response.tex}\r\n\r\n\r\n\\end{document}\r\n\r\n\r\n\r\n", "meta": {"hexsha": "c8a1ca88f2b1fee93b70e813568c055a62dad288", "size": 68793, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Drafts/PAMI2/QAP.tex", "max_stars_repo_name": "rwolst/FastApproximateQAP", "max_stars_repo_head_hexsha": "08854a8edfe8881003b11fe4433dec8f0c8217ed", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2015-08-27T14:10:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-08T21:38:55.000Z", "max_issues_repo_path": "Drafts/PAMI2/QAP.tex", "max_issues_repo_name": "rwolst/FastApproximateQAP", "max_issues_repo_head_hexsha": "08854a8edfe8881003b11fe4433dec8f0c8217ed", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2015-02-20T01:53:58.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-24T11:14:00.000Z", "max_forks_repo_path": "Drafts/PAMI2/QAP.tex", "max_forks_repo_name": "rwolst/FastApproximateQAP", "max_forks_repo_head_hexsha": "08854a8edfe8881003b11fe4433dec8f0c8217ed", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2016-08-23T11:44:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T01:41:25.000Z", "avg_line_length": 93.9795081967, "max_line_length": 1576, "alphanum_fraction": 0.7304522262, "num_tokens": 19197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213368305399, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3059404684614787}}
{"text": "\\documentclass[landscape, letterpaper, 10pt]{article}\n\n\\usepackage[margin=.25in]{geometry}\n\\usepackage{fontspec}\n\\usepackage{mathtools}\n\\usepackage{multicol}\n\\usepackage{unicode-math}\n\\usepackage{enumitem}\n\n\\setmainfont{Calibri}\n\n\\begin{document}\n\\begin{multicols}{3}\n    \\section*{Financial Statements}\n    \\begin{tabular}{|l|l|}\n        \\hline\n        Statement Type    & Uses               \\\\ \\hline\n        Balance Sheet     & Money at the end   \\\\ \\hline\n        Cash Flow         & How much cash made \\\\ \\hline\n        Income            & Fiscal profit      \\\\ \\hline\n        Retained Earnings & How money is spent \\\\ \\hline\n    \\end{tabular}\n\n    \\subsection*{Balance Sheet}\n    \\begin{itemize}[noitemsep,nolistsep]\n        \\item Current Assets\n              \\begin{itemize}[noitemsep,nolistsep]\n                  \\item Cash, Receivables, Inventory, Bills\n              \\end{itemize}\n        \\item Long Term Assets\n              \\begin{itemize}[noitemsep,nolistsep]\n                  \\item Fixed assets: Land, Buildings, Machines, Equipment, Vehicles\n                  \\item Investments\n                  \\item Intangibles: Licenses, Patents, Copyrights, Goodwill/PR\n              \\end{itemize}\n        \\item Current Liabilities\n              \\begin{itemize}[noitemsep,nolistsep]\n                  \\item Short term credit, Payables, Expenses, Taxes, Current portion of long term debt/loan\n              \\end{itemize}\n        \\item Long Term Liabilities\n              \\begin{itemize}[noitemsep,nolistsep]\n                  \\item Long term portion of debt, Bonds, Mortgages, Grants\n              \\end{itemize}\n        \\item Shareholder's equity\n              \\begin{itemize}[noitemsep,nolistsep]\n                  \\item Common Stock: Pays dividends depending on company's income\n                  \\item Preferred Stock: Pays fixed dividends\n                  \\item Treasury Stock: Bought back stock\n                  \\item Paid-in capital: More expensive stock\n                  \\item Retained earnings: Cumulative net income since beginning\n              \\end{itemize}\n    \\end{itemize}\n    \\subsection*{Cash Flow}\n    \\begin{itemize}[noitemsep,nolistsep]\n        \\item Operating: Production and sale of goods, Depreciation\n        \\item Investing: New assets, Selling equipment, investments\n        \\item Financing: Borrowing, Selling stock, Paying debt\n    \\end{itemize}\n    \\section*{Ratio Analysis}\n\n    \\textbf{Contribution Margin}: the amount of profit each unit makes.\n\n    \\textbf{Capital}: obtained from debt and equity.\n\n    \\textbf{Debt}: money from bank.\n\n    \\textbf{Equity}: money from owners.\n\n    \\subsection*{Ratios}\n    \\small\\begin{align*}\n        DebtRatio      & = & \\frac{TotalDebt}{TotalAssets}                     \\\\\n        TIE            & = & \\frac{TaxableIncome}{Interest}                    \\\\\n        Current        & = & \\frac{Assets}{Liabilities}                        \\\\\n        Quick          & = & \\frac{AssetsInventory}{Liabilities}               \\\\\n        IT             & = & \\frac{Sales}{AverageInventory}                    \\\\\n        DSO            & = & \\frac{Receivables}{AvgSales/day}                  \\\\\n        TAT            & = & \\frac{Sales}{TotalAssets}                         \\\\\n        PMoS           & = & \\frac{NetIncome}{Revenue}                         \\\\\n        RoA            & = & \\frac{NetIncome + i(1-Tax)}{AvgTotalAssets}       \\\\\n        RoE            & = & \\frac{NetIncome}{AvgTotalEquity}                  \\\\\n        Price-Earnings & = & \\frac{PricePerShare}{EarningsPerShare}            \\\\\n        BVPS           & = & \\frac{TotalEquity - PrefStock}{SharesOutstanding} \\\\\n    \\end{align*}\n    \\normalsize\n    \\section*{Interest Rates}\n    \\textbf{Effective Interest Rate per Payment Period}\n    \\begin{align*}\n        i_a & = & \\left(1+\\frac{r}{M}\\right)^M -1 \\\\\n        i   & = & \\left(1+\\frac{r}{M}\\right)^C -1 \\\\\n        M   & = & CK                              \\\\\n    \\end{align*}\n    \\textbf{Continuous Compounding}\n    \\begin{align*}\n        i_a & = e^r - 1           \\\\\n        i   & = e^\\frac{r}{k} - 1 \\\\\n    \\end{align*}\n    \\begin{align*}\n        i & : & \\text{Effective interest rate per payment period} \\\\\n        M & : & \\text{Compounding periods per year}               \\\\\n        C & : & \\text{Compounding periods per payment period}     \\\\\n        K & : & \\text{Payment periods per year}                   \\\\\n        r & : & \\text{Nominal interest rate}                      \\\\\n    \\end{align*}\n    \\section*{Loans}\n    \\begin{align*}\n        A    & : & \\text{Annual payments}                       \\\\\n        B_N  & : & \\text{Remaining balance at period } N        \\\\\n        B_0  & = & P                                            \\\\\n        B_N  & = & A(P/A, i, N-n)                               \\\\\n        I_N  & : & \\text{Interest part of payment at period } N \\\\\n        I_N  & = & B_{N-1} i                                    \\\\\n        PP_N & : & \\text{Principal Payment at period } N        \\\\\n        A    & = & PP_N + I_N                                   \\\\\n    \\end{align*}\n    \\section*{Bonds}\n    \\begin{tabular}{|l|l|}\n        \\hline\n        Market value  & Sum of all present values  \\\\\\hline\n        Par value     & Face value                 \\\\\\hline\n        Maturity date & When does the par get paid \\\\\\hline\n        Coupon rate   & Interest rate              \\\\\\hline\n        Cheap Bond    & Discount                   \\\\\\hline\n        Expensive     & Premium                    \\\\\\hline\n    \\end{tabular}\n    \\begin{align*}\n        \\text{Yield to maturity} & : & \\text{Return if kept to maturity}        \\\\\n                                 & = & A(P/A, i, N) + Par(P/F, i, N)            \\\\\n        \\text{Current yield}     & : & \\text{Interest payment per market price} \\\\\n                                 & = & \\frac{A}{Purchase}                       \\\\\n    \\end{align*}\n    \\section*{Project Analysis}\n    \\textbf{Never} compare two projects by measuring IRR. Always use MARR and find present worth or do incremental analysis if no MARR provided.\n\n    \\textbf{When project lifespans differ}: If the analysis period is shorter than both projects, us PW analysis. If analysis period is longer, find replacement to pad.\n\n    If analysis period is equal to the highest length, find NPW, do not repeat projects.\n\n    If no analysis period specified, get LCM of project periods, and find NPW, repeating to fill out period.\n\n    Choose the project with bigger NPW or higher incremental IRR.\n\n    \\section*{Depreciation}\n    \\subsection*{Book}\n    \\begin{align*}\n        \\textbf{Straight Line}                                            \\\\\n        D           & = \\frac{P-S}{N}                                     \\\\\n        BV_n        & = P-nD                                              \\\\\n        \\textbf {Declining Balance}                                       \\\\\n        d           & = \\frac{\\text{Multiplier}}{N}                       \\\\\n        D_n         & = dP(1-d)^{n-1}                                     \\\\\n        BV_n        & = P(1-d)^n                                          \\\\\n        \\textbf {Sum of Years Digits}                                     \\\\\n        \\text{SOYD} & = \\frac{N(N+1)}{2}                                  \\\\\n        D_n         & = \\frac{N-n+1}{\\text{SOYD}}(P-S)                    \\\\\n        \\textbf{Units of Production}                                      \\\\\n        D_n         & = \\frac{\\text{Units/year}}{\\text{Total Units}}(P-S) \\\\\n    \\end{align*}\n    \\subsection*{Tax}\n    \\textbf{Overhaul of equipment} is considered a \\textbf{separate} asset, that gets its own line of depreciation.\n    \\section*{Taxation}\n    \\subsection*{Disposal Tax Effects}\n    \\begin{align*}\n        \\text{Cost > Salvage > UCC}: G & = t(UCC_N - S) \\\\\n        \\text{Cost > UCC > Salvage}: G & = t(UCC_N - S) \\\\\n        \\text{Salvage > Cost > UCC}: G & = t(UCC_N - P) \\\\\n                                       & - 0.5t(S-P)    \\\\\n        NS                             & = S + G        \\\\\n    \\end{align*}\n    \\begin{align*}\n        NS & : \\text{Net Salvage Value}   \\\\\n        G  & : \\text{Disposal Tax Effect} \\\\\n        S  & : \\text{Salvage Value}       \\\\\n        P  & : \\text{Principal}           \\\\\n    \\end{align*}\n    \\subsection*{After Tax Cashflows}\n\n    \\textbf{For debt}, interest is taxable, but principal is not. Interest goes to Income Statement; Principal goes to Cash Flow Statement.\n\n    \\begin{align*}\n        \\textbf{Taxable Income} & = \\text{Revenue} - \\text{Expenses}                   \\\\\n        \\textbf{Expenses}       & =  \\text{Operating} + \\text{CCA} + \\text{Interest}   \\\\\n        \\textbf{Income Tax}     & = \\text{Income} \\times \\text{Tax Rate}               \\\\\n        \\textbf{Net Cash Flow}  & = \\text{Net Income} + \\text{CCA} +\\text{Investments} \\\\\n                                & +\\text{Salvage} +\\text{Disposal Tax Effect}          \\\\\n    \\end{align*}\n\n    \\section*{Sensitivity Analysis}\n    Separate the cashflows that you are sure will come, and those that are variable such as revenue, salvage value, fixed costs, etc.\n    %WARN: Need more here. Didn't seem too important in class?\n    \\section*{Replacement Analysis}\n    \\subsection*{Same Period}\n    \\textbf{Notation:} $(j_0, n_0), (j_1, n_1), (j_2, n_3), \\ldots, (j_i, n_i)$.\n\n    First pair is defender. All following pairs are challengers. Example: $(j_0, 2), (j_1, 5), (j_2, 3)$ means defender stays for 2 years, replaced by challenger 1 for 5 years then challenger 2 for 3 years.\n\n    \\textbf{Opportunity Cost Approach} is to find Annual Equivalent Cost of both the defender and challenger and keep the one with lower costs. Recommended for an infinite planning horizon.\n\n    \\textbf{Present Worth Approach} is to find the present worths of both projects and choosing one with higher worth. Recommended for a finite planning horizon.\n\n    \\textbf{Optimal time to replace} is determined to be when you have the lowest AEC/highest NPW. Trial and error is the only way to find. Easiest method is as follows: Check if immediate replacement fulfils above criteria. If yes, replace immediately. If not, list down all possible AEC/NPWs for both defender and challenger. Find N where AEC/NPW fits criteria.\n\n\\end{multicols}\n\\end{document}", "meta": {"hexsha": "81a41258b9ca9294239c76eced60a73b2780c1cd", "size": 10271, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Notes/ENGM401.tex", "max_stars_repo_name": "n30phyte/SchoolDocuments", "max_stars_repo_head_hexsha": "79652ec7e3345d67e67f0cffe3bea468708622bd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Notes/ENGM401.tex", "max_issues_repo_name": "n30phyte/SchoolDocuments", "max_issues_repo_head_hexsha": "79652ec7e3345d67e67f0cffe3bea468708622bd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Notes/ENGM401.tex", "max_forks_repo_name": "n30phyte/SchoolDocuments", "max_forks_repo_head_hexsha": "79652ec7e3345d67e67f0cffe3bea468708622bd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.5960591133, "max_line_length": 363, "alphanum_fraction": 0.5228312725, "num_tokens": 2630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.30594045969972306}}
{"text": "\\documentclass[./\\jobname.tex]{subfiles}\n\\begin{document}\n\n\\chapter{Experimental Design}\nThis chapter gives an overview on how the subsequent experiments are conducted. An integral part of solver comparison is to define a testbed that holds example problems with a known analytical solution. Further, a quality measurement must be defined that compares the numerical to the analytical solution. Since the memory consumption and the solving time is of interest, a robust method to measure these characteristics is needed. The baseline for all experiments is the \\gls{fem} solver NGSolve (\\cite{schoberl_ngsolvengsolve_2020}). \n\n\\section{Testbed}\n\\label{chap:testbed_description}\nThe testbed is a collection of multiple two-dimensional scalar \\gls{pde}s that are analytically solved such that $u_{ext}(\\mathbf{x}): \\mathbb{R}^2 \\rightarrow \\mathbb{R}$ is a solution to the underlying PDE. These can be used to demonstrate the correct implementation of a solver. The testbed can also be used to compare the performance of the classical \\gls{fem} solver (NGSolve) with the \\gls{ci} solver. The equations and graphs are displayed in the appendix \\ref{chap:testbed}. The equations used here are a mixture of different testbeds. Specifically, the equations \\gls{pde} 2 and \\gls{pde} 3 are picked from the testbed in \\cite{chaquet_using_2019}. These problems were also used by \\cite{tsoulos_solving_2006} and \\cite{panagant_solving_2014}. Preliminary tests have shown that the equations used in these papers are rather simple to approximate. Thus, more complicate equations are added to test the solvability over a wider variety of functions. The more complex equations are taken from the National Institute of Standards and Technology (NIST) website (\\cite{mitchell_nist_2018}) that provides benchmarking problems for \\gls{fem} solvers with adaptive mesh refinement methods. The other equations 0A, 0B and 8 are specially created to show different properties of the solver. \n\n\\textbf{PDE 0A: Gauss Kernel} \\\\\n\\underline{Equation Reference:} \\eqref{eq:pde0a} \\\\\n\\underline{Characteristics:} sum of 5 \\gls{gak}, thus can be approximated arbitrarily close; is designed to show convergence towards analytical solution; \\\\\n\\underline{Difficulty:} not especially difficult; \\\\\n\\underline{Boundary:} function value of solution; \\\\\n\n\\textbf{PDE 0B: Gauss Sine Kernel} \\\\\n\\underline{Equation Reference:} \\eqref{eq:pde0b} \\\\\n\\underline{Characteristics:} can be approximated arbitrarily close by 3 \\gls{gsk}; 3 kernels are used to keep the minimal necessary dimension of the representation similar to \\gls{pde} 0A;\\\\\n\\underline{Difficulty:} the contrast between a dominant wave with a steep gradient in the middle and small waves with little influence on the boundary; simple approximations lay the focus on the middle, while good approximations also match the small waves; \\\\\n\\underline{Boundary:} function value of solution; \\\\\n\n\\textbf{PDE 1: Polynomial 2D} \\\\\n\\underline{Equation Reference:} \\eqref{eq:pde1} \\\\\n\\underline{Characteristics:} polynomial of order 20 \\\\\n\\underline{Difficulty:} global structure similar to a \\gls{gak}; thus, it is simple to approximate; \\\\\n\\underline{Boundary:} homogeneous boundary condition; \\\\\n\\underline{Reference:} \\cite{mitchell_nist_2018}; \\\\\n\n\\textbf{PDE 2: Chaquet PDE 1} \\\\\n\\underline{Equation Reference:} \\eqref{eq:pde2} \\\\\n\\underline{Characteristics:} compare the performance to other solvers; \\\\\n\\underline{Difficulty:} rather simple; slight curvature and no steep gradient; \\\\\n\\underline{Boundary:} function value on boundary; \\\\\n\\underline{Reference:} \\cite{chaquet_using_2019}, \\cite{chaquet_solving_2012}, \\cite{tsoulos_solving_2006}, \\cite{sobester_genetic_2008}, \\cite{panagant_solving_2014};\\\\\n\n\\textbf{PDE 3: Chaquet PDE 3} \\\\\n\\underline{Equation Reference:} \\eqref{eq:pde3} \\\\\n\\underline{Characteristics:} compare the performance to other solvers; polynomial of order 2; \\\\\n\\underline{Difficulty:} well behaved, no steep gradient; \\\\\n\\underline{Boundary:} function value on boundary; \\\\\n\\underline{Reference:} \\cite{chaquet_using_2019}, \\cite{chaquet_solving_2012}, \\cite{tsoulos_solving_2006}, \\cite{panagant_solving_2014}; \\\\\n\n\\textbf{PDE 4: Sine Bump 2D} \\\\\n\\underline{Equation Reference:} \\eqref{eq:pde4} \\\\\n\\underline{Characteristics:} this \\gls{pde} is used in both, the work of \\cite{chaquet_using_2019} and  \\cite{mitchell_nist_2018} with slightly different boundary condition; preliminary tests have shown that the \\cite{chaquet_using_2019} \\gls{pde} is easier to solve, thus this formulation is disregarded;\\\\\n\\underline{Difficulty:} sharp boundary condition on the corners of $\\Omega$; \\\\\n\\underline{Boundary:} homogeneous boundary condition; \\\\\n\\underline{Reference:} \\cite{mitchell_nist_2018};\\\\\n\n\\textbf{PDE 5: Arctan Circular Wave Front} \\\\\n\\underline{Equation Reference:} \\eqref{eq:pde5} \\\\\n\\underline{Characteristics:} quarter section of slightly shifted arctan; \\\\\n\\underline{Difficulty:} transition from the flat plateaus to the steep gradient of the circular wave front; preliminary tests have shown that this problem is especially hard; \\\\\n\\underline{Boundary:} function value on boundary; \\\\\n\\underline{Reference:} \\cite{mitchell_nist_2018}; \\\\\n\n\\textbf{PDE 6: Peak 2D} \\\\\n\\underline{Equation Reference:} \\eqref{eq:pde6} \\\\\n\\underline{Characteristics:} solution is a single but sharp Gaussian ``peak'' at $(0.5, 0.5)$; \\\\\n\\underline{Difficulty:} large negative exponent in e-function results in a steep gradient and small region of interest; \\\\\n\\underline{Boundary:} function value on boundary; \\\\\n\\underline{Reference:} \\cite{mitchell_nist_2018}; \\\\\n\n\\textbf{PDE 7: Boundary Line Singularity} \\\\\n\\underline{Equation Reference:} \\eqref{eq:pde7} \\\\\n\\underline{Characteristics:} the solution to this problem is a root function that is only defined on $x \\in \\mathbb{R}^{+}$; \\\\\n\\underline{Difficulty:} line singularity on boundary with increasing gradient; \\\\\n\\underline{Boundary:} function value with singularity on boundary $x_0 = 0$; \\\\\n\\underline{Reference:} \\cite{mitchell_nist_2018}; \\\\\n\n\\textbf{PDE 8: Interior Point Singularity} \\\\\n\\underline{Equation Reference:} \\eqref{eq:pde8} \\\\\n\\underline{Characteristics:} root function; a singularity within the domain; \\\\\n\\underline{Difficulty:} not defined at $(0.5, 0.5)$ which results in numerical inaccuracies; \\\\\n\\underline{Boundary:} function value on boundary; \\\\\n\n\\textbf{PDE 9: Arctan Wave Front Homogeneous Boundary Conditions 2D} \\\\\n\\underline{Equation Reference:} \\eqref{eq:pde9} \\\\\n\\underline{Characteristics:} arctan oscillation diagonal to the domain;  \\\\\n\\underline{Difficulty:} steep gradient on the transition between wave peak and trough; sharp corners on the boundary; \\\\\n\\underline{Boundary:} homogeneous boundary condition; \\\\\n\\underline{Reference:} \\cite{mitchell_nist_2018}; \\\\\n\n\n\\section{Software Architecture}\n\\label{chap:software_architecutre}\n\nTo simplify the preparation, execution and evaluation of the experiments, a comprehensive software architecture is defined. The \\gls{uml} class diagram can be seen in the appendix \\ref{chap:appendix_software_architecture}. The limited class diagram, without any methods and attributes is shown in the figure \\ref{fig:uml_class_small} below. The architecture is organised in four main segments. \n\n\\large \\underline{\\textbf{Optimisation Algorithm}} \\\\\nThe \\inlinecode{IOptAlgoBase} interface must be implemented by every \\inlinecode{OptAlgo} class to ensure the compatibility with \\inlinecode{CiPdeBase} class of the testbed. A nice side-effect is that it reduces the number of user-defined parameters. An optimisation algorithm of this class must only take an initial guess (e.g. the starting population) as well as two stopping criteria: the maximum number of function evaluation or a minimum error to reach. Also a fitness function (i.e. the function to be optimised) must be provided. Four lists of the same length are returned: the optimum-guess, the function value, the crossover probability and the scale factor per each generation. The actual implementation of the algorithm is not predefined. \n\n\\large \\underline{\\textbf{Kernels}} \\\\\nAs described in chapter \\ref{chap:candidate_rep}, a candidate solution is defined as a sum of \\gls{rbf}. In order to test different candidate representations, different classes must be implemented. Again, to ensure compatibility with the \\inlinecode{CiPdeBase} class, all representations must implement the \\inlinecode{IKernelBase} interface. This assures that all classes have a method that can calculate the solution as well as the first and the second order derivatives. Here, only two kernels are implemented. A typical Gauss kernel as described in chapter \\ref{chap:gauss_kernel} and a so called Gauss Sine kernel shown in chapter \\ref{chap:gsin_kernel}. \n\n\\large \\underline{\\textbf{Testbed}} \\\\\nThe testbed holds the 11 differential equations used in all experiments. The testbed is abstracted in such a way that an experiment is as simple as creating an \\gls{pde} object and calling its solve method. All testbed classes must implement the \\inlinecode{ITestbenchBase} interface. This ensures the minimal functionality of every subsequent class. Currently two classes implement this interface, the \\inlinecode{FemPdeBase} and the \\inlinecode{CiPdeBase}. These are the base classes that provide the specific attributes and methods needed for the \\gls{fem} solver and the \\gls{ci} solver. The actual \\gls{pde} problems are implemented in the classes \\inlinecode{FemPdeN} or \\inlinecode{CiPdeN} which inherit from the \\inlinecode{FemPdeBase} and the \\inlinecode{CiPdeBase}, respectively. The number \\textit{N} in their name is representative for all different testbench problems and every \\gls{pde} has its own class. Since all \\gls{pde} classes have the same methods/attributes and only differ in their implementation and name, they do not have to be displayed separately. Therefore, they are symbolised together by a ``stacked notation'' used in the class diagram. Some methods in these classes must be overridden and adapted to the current \\gls{pde} problem, which is indicated by the $\\land$ character.\n\n\\large \\underline{\\textbf{Post Processing}} \\\\\nAlthough the post processing block is not actually a class, it is still represented in this diagram. This module provides functions that take \\inlinecode{FemPdeN} or \\inlinecode{CiPdeN} objects and perform actions with them. The methods are used in the experiments chapters to interpret the results. A detailed description of the implementation is given in the appendix \\ref{chap:apendix_post_proc}.\n\n\\begin{figure}[H]\n\t\\centering\n\t\\noindent\\adjustbox{max width=\\linewidth}{\\includegraphics[width=1\\textwidth]{../../code/uml_diag/testbench_uml_class_small.pdf}\n\t}\n\t\\unterschrift{This reduced \\gls{uml} class diagram gives an overview of the testbed design and its interfaces and classes.}{}{}\n\t\\label{fig:uml_class_small}\n\\end{figure}\n\n\\section{Performance Metric} \n\\label{chap:metric}\nIn order to scientifically compare the results produced by the different solvers, some metrics are necessary. Three important solver-properties are measured: the execution time, the memory usage and the quality of the numerical solution. The following chapters describe the measurement process in greater detail. \n\n\\subsection{Solving Time}\n\\label{chap:metric_time}\nThe solving time is measured within the \\inlinecode{solve()} method of either class. The time module of the \\cite{python_standard_library_time_2020} is used to interact with the system clock. The resolution, that the time module can access, depends on the system it is running on. Specifically, on the machine used in all further experiments, \\inlinecode{time.time()} returns a 24 byte float that represents the time passed since 1st of January 1970. Usually, consecutive calls of this function return increasing values - changing the system time could interfere with the correctness of this value.\\\\ \n\nAs the execution time of a program depends on many other factors, such as the current system load, the CPU temperature and the process scheduler, it is necessary to view it as a random variable. Thus, multiple replications have to be done before trying to interpret the results. To make for a fair comparison, the same machine with a similar work-load must be used.  The replications are not done within the \\inlinecode{solve()} function and must be applied during the experiment. To reduce the random effects and prevent possible outlier, the Python garbage collector is switched off during the time measurement. For a step-by-step description, the pseudocode is shown in the appendix \\ref{chap:solve_function}. \n\n\n\n\\subsection{Memory Usage}\n\\label{chap:metric_mem}\nSimilar to the solving time measurement, the memory usage is determined within the \\inlinecode{solve()} method. The \\textit{psutil} module (\\cite{rodola_psutil_2020}) provides the functionality to read the amount of memory attached to a process at a given time. The function call \\inlinecode{process.memory_info()} returns an object with multiple attributes about the current state of the process. Of special interest is the \\gls{vms} field. This includes the \\gls{rss}, the memory that is currently held within the main memory, and the memory that is currently swapped out to the hard drive.\n\nWithout assuming anything about the inner workings of the process, the memory usage is also a random variable. Thus, similar to the time measurement, replications have to be performed. The same pseudocode as for the time measurement (appendix \\ref{chap:solve_function}) also applies here. To remove outliers, it is helpful to create and solve one testbed object before recording the experiment. This sets up the necessary references to libraries and modules. Thus they are not mingled into the actual experiments. This should be done for both, the \\gls{fem} and the \\gls{ci} solver.  \n\n\\subsection{Quality Measurement}\n\\label{chap:metric_quality}\nAlthough the fitness function is the criterion that is optimised, it is not applicable as an objective quality measure. As \\cite{chaquet_using_2019} describe, it depends on multiple factors:\n\\begin{itemize}\n\t\\item user-defined parameters $\\xi$ and $\\phi$ \n\t\\item the formulation of the \\gls{pde} \n\t\\item number of collocation points used \n\t\\item number of kernels used\n\\end{itemize}\nThus, \\cite{chaquet_using_2019} define a new quality measurement based on the \\gls{rmse} over the collocation points as seen in equation \\eqref{eq:rmse_chaquet}. \n\\begin{equation}\n\\label{eq:rmse_chaquet}\nRMSE^2 = \\frac{\\sum_{i=1, \\mathbf{x}_i \\in C}^{n_C} \\left|\\left| u(\\mathbf{x}_i) - u_{ext}(\\mathbf{x}_i) \\right|\\right|^2 + \\sum_{j=1, \\mathbf{x}_j \\in B}^{n_B} \\left|\\left| u(\\mathbf{x}_j) - u_{ext}(\\mathbf{x}_j) \\right|\\right|^2}{(n_C + n_B)}\n\\end{equation}\nThis quality criterion has three inherent issues. At first, it firmly depends on the number of collocation points used. In an algorithm that uses self-adaptive collocation points, where the distribution of the points depends on random variables, subsequent measures of similar solutions could result in different quality values. Especially in solutions with high condition numbers, the \\gls{rmse} measurement would be rendered useless since a small deviation of the point results in a large difference of the function value. \n\nFurther with the \\gls{rmse}, the quality is only measured on the collocation points and not in between. However, a good solution fits not only these discrete points, but the whole domain. This is called an aliasing error. An approximation can fit the points, without correctly representing the space between them. This is shown in the following figure \\ref{fig:aliasing error}.\n\n\\begin{figure}[H]\n\t\\centering\n\t\\noindent\\adjustbox{max width=0.8\\linewidth}{\n\t\t\\includegraphics[width=\\textwidth]{../img/pdf/aliasing_error.pdf}\n\t}\n\t\\unterschrift{Aliasing Error: sharp inaccuracies in between collocation points}{}{}\n\t\\label{fig:aliasing error}\n\\end{figure}\n\nFinally, the \\gls{fem} method doesn't use collocation points, so this quality measurement could not be calculated. A good quality measurement tool only uses the numerical and analytical solution, independently of the solving method. \n\nThis leads to the quality measurement formulation used in this thesis: the L2 norm defined for functions as denoted in equation \\eqref{eq:quality_measurement}. This actually measures the distance between the analytical solution and the numerical approximation.  \n\\begin{equation}\n\\label{eq:quality_measurement}\n\\left|\\left|u_{ext} - u_{apx}\\right|\\right| = \\sqrt{\\int_{\\Omega} (u_{ext}(\\mathbf{x}) - u_{apx}(\\mathbf{x}))^2 dx}\n\\end{equation}\nAlthough this integral is numerically evaluated, the discretisation is much finer than the resolution of the collocation points used in the fitness function - thus also taking the areas between these points into account.\n\n\n\n\\section{Baseline: NGSolve}\n\\label{chap:fem_baseline_results}\nAs mentioned above, the NGSolve framework (\\cite{schoberl_ngsolvengsolve_2020}) is used as the baseline for all experiments. NGSolve is a state of the art \\gls{fem} solver that is in part developed and maintained by numerous well-known institutes such as the Vienna University of Technology, the University of Göttingen and the Portland State University. This chapter describes the results obtained by running NGSolve on the testbed. The metrics from chapter \\ref{chap:metric} are applied. \n\n\\subsection{Setup}\nAt first the \\gls{pde}s must be transformed into their corresponding weak form. As all testbed problems are Poisson equations and only differ in their algebraic sign and inhomogeneous part, the weak form is similar for all problems. Referring to equation \\eqref{eq: weak form}, the terms $\\vec{b} = 0$ and $c = 0$, thus these parts vanish. The matrix $A$ is either $\\begin{bsmallmatrix} 1 & 0 \\\\ 0 & 1 \\end{bsmallmatrix}$ or with a negative sign $\\begin{bsmallmatrix} -1 & 0 \\\\ 0 & -1 \\end{bsmallmatrix}$ as only the non-mixed second order derivatives occur in the equations. This results in the weak form as presented in equation \\eqref{eq: weak form testbed}, where f is the inhomogeneous part of the \\gls{pde}.\n\\begin{equation}\n\\label{eq: weak form testbed}\n\\int_{\\Omega} \\nabla u^T \\nabla v dV = \\int_{\\Omega} f v dV\n\\end{equation}\n\nTo enhance the performance of NGSolve, static condensation is turned on. Further, a multigrid preconditioner is used. All problems are approximated by second order polynomials. The automatic mesh refinement is performed until a maximum of $5 \\cdot 10^4$ \\gls{dof} is reached. To properly interpret the results, 20 replications for each problem are performed. This is only needed for time and memory usage, the solution itself is not a random variable. To further reduce memory usage, the GUI of NGSolve is switched off. \n\n\\subsection{Result}\nWith the parameters described above, the following results are produced. The solving time as well as the memory usage are displayed in the boxplots \\ref{fig:_fem_time_boxplot} and \\ref{fig:_fem_mem_boxplot}, respectively. These datasets provide a reference point for the performance of the \\gls{ci} solver. In general, the solving time ranges from 2.5 to 5.0 seconds at about 50 to 80 Mbyte of memory. Only problem 3 stands out as a notable exception. To keep the diagram within a readable scale, this \\gls{pde} is omitted and plotted in a separate figure. \n\nTable \\ref{tab:fem_sol_quality} presents the achieved distances between the exact and the approximated solutions. On \\gls{pde} 3 the best numerical quality is achieved.\n\nThe problem \\gls{pde} 7 only needs around 2.5 seconds to be solved. A reason could be that the solution only depends on one variable and the derivative with respect to y evaluate to zero $\\frac{\\partial u}{\\partial y} = 0$ and thus vanishes. This does not effect the memory usage, since all $5 \\cdot 10^4$ \\gls{dof} must be created to terminate. \n\n\\begin{table}[h]\n\t\\centering\n\t\\noindent\\adjustbox{max width=\\linewidth}{\n\t\t\\begin{tabular}{|c|c|}\n\t\t\t\n\t\t\t\\hline\n\t\t\t\\rowcolor[HTML]{\\farbeTabA}\n\t\t\t\n\t\t\tProblem PDE & L2 Norm \\\\ \\hline\n\t\t\t\n\t\t\t0A & $2.967 \\cdot 10^{-5}$ \\\\ \\hline\n\t\t\t0B & $1.071 \\cdot 10^{-5}$ \\\\ \\hline\n\t\t\t1  & $8.004 \\cdot 10^{-7}$ \\\\ \\hline\n\t\t\t2  & $3.501 \\cdot 10^{-8}$ \\\\ \\hline\n\t\t\t3  & $1.680 \\cdot 10^{-9}$ \\\\ \\hline\n\t\t\t4  & $4.764 \\cdot 10^{-7}$ \\\\ \\hline\n\t\t\t5  & $6.057 \\cdot 10^{-6}$ \\\\ \\hline\n\t\t\t6  & $1.908 \\cdot 10^{-7}$ \\\\ \\hline\n\t\t\t7  & $5.203 \\cdot 10^{-5}$ \\\\ \\hline\n\t\t\t8  & $3.237 \\cdot 10^{-7}$ \\\\ \\hline\n\t\t\t9  & $2.366 \\cdot 10^{-7}$ \\\\ \\hline\n\t\t\t\n\t\t\\end{tabular}\n\t}\n\t\\unterschrift{These are the results obtained by the \\gls{fem} solver in terms of distance to the analytical solution. The solver achieves the smallest deviation in PDE 3.}{}{}\n\t\\label{tab:fem_sol_quality}\n\\end{table}\n\n\n\\begin{figure}[H]\n\t\\centering\n\t\\noindent\\adjustbox{max width=0.66\\linewidth}{\n\t\t\\includegraphics[width=\\textwidth]{../../code/experiments/_experiment_fem_base/time_boxplot_pde_0a_0b_1_2_4_5_6_7_8_9.pdf}\n\t}\n\t\\unterschrift{Boxplot: time (in seconds) needed to solve the testbed \\gls{pde} (without \\gls{pde}3)}{}{}\n\t\\label{fig:_fem_time_boxplot}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\noindent\\adjustbox{max width=0.66\\linewidth}{\n\t\t\\includegraphics[width=\\textwidth]{../../code/experiments/_experiment_fem_base/mem_boxplot_pde_0a_0b_1_2_4_5_6_7_8_9.pdf}\n\t}\n\t\\unterschrift{Boxplot: memory (in Mbyte) needed to solve the testbed \\gls{pde} (without \\gls{pde}3)}{}{}\n\t\\label{fig:_fem_mem_boxplot}\n\\end{figure}\n\nThe following figures \\ref{fig:_fem_time_boxplot_pde3} and \\ref{fig:_fem_mem_boxplot_pde3} show the boxplot of the time and memory consumption for the testbed \\gls{pde} 3 with $5 \\cdot 10^4$ \\gls{dof}. Compared to the other equations, this problem takes longer to solve while also needing more memory: somewhere around 65.2 seconds at about 130 Mbyte. One possible explanation for that is the fundamental structure of the \\gls{pde}. As described in equation \\eqref{eq:sol3}, the exact solution to this problem is a polynomial of second order. This can be approximated perfectly by the \\gls{fem} solver, since it also uses second order polynomials as basis functions. The mesh-refinement step takes more iterations to produce the $5 \\cdot 10^4$ \\gls{dof} as compared to the other testbed problems. In fact, since the numerical errors per finite element accumulate, more \\gls{dof} should result in a larger approximation error. Figure \\ref{fig:_dof_sweep_pde3} shows the performance metrics at different \\gls{dof} budgets. The plot supports this hypothesis that less \\gls{dof} take less time and memory to solve the \\gls{pde} and still end up with a better quality. \n\n\\begin{figure}[H]\n\t\\centering\n\t\\noindent\\adjustbox{max width=0.7\\linewidth}{\n\t\t\\includegraphics[width=\\textwidth]{../../code/experiments/_experiment_fem_base/pde3_ndof.pdf}\n\t}\n\t\\unterschrift{\\gls{pde} 3 performance metrics at different \\gls{dof} budgets.}{}{}\n\t\\label{fig:_dof_sweep_pde3}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\begin{subfigure}[b]{0.5\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width=1\\textwidth]{../../code/experiments/_experiment_fem_base/time_boxplot_pde_3.pdf}\n\t\t\\caption{Boxplot: time to solve testbed \\gls{pde}3 at $5\\cdot 10^4$ \\gls{dof}.}\n\t\t\\label{fig:_fem_time_boxplot_pde3}\n\t\\end{subfigure}% \n\t%\n\t\\begin{subfigure}[b]{0.5\\linewidth}\n\t\t\\centering\n\t\t\\includegraphics[width=1\\textwidth]{../../code/experiments/_experiment_fem_base/mem_boxplot_pde_3.pdf}\n\t\t\\caption{Boxplot: memory to solve testbed \\gls{pde}3 at $5\\cdot 10^4$ \\gls{dof}.}\n\t\t\\label{fig:_fem_mem_boxplot_pde3}\n\t\\end{subfigure}%\n\t\\unterschrift{Comparison of time and memory effort on \\gls{pde} 3 at $5 \\cdot 10^4$ \\gls{dof}.}{}{}%\n\t\\label{}\n\\end{figure}\n\n\\section{Default CI Parameter}\n\\label{chap:default_ci_param}\nTypically, the performance of heuristic optimisation algorithms can be adjusted to specific testbed problems by tuning its parameters. For all further experiments the JADE algorithm, as described with pseudocode \\ref{algo: jade}, is used. Similarly, the reported \\gls{ci} solver has many parameters that could be adapted. However, adjusting every parameter in order to find the best combination is not an option, since that would take an extensive amount of computation time. Some parameters that might not have a great effect on the performance can be predefined. These values are determined by preliminary tests. If not stated otherwise, the following parameters from table \\ref{tab:ci_parameter} are used in the subsequent experiments. \n\n\\begin{table}[h]\n\t\\centering\n\t\\noindent\\adjustbox{max width=\\linewidth}{\n\t\t\\begin{tabular}{|c|c|c|}\n\t\t\t\n\t\t\t\\hline\n\t\t\t\\rowcolor[HTML]{\\farbeTabA}\n\t\t\t\n\t\t\tParameter & JADE & \\multilinecell{\\gls{cma_es} \\\\ (\\cite{chaquet_using_2019})} \\\\ \\hline\n\t\t\t\n\t\t\t$\\varphi$ & 100 & 300 \\\\ \\hline\n\t\t\t$\\kappa$  & 1   & 3   \\\\ \\hline\n\t\t\tpopulation size & $2 \\cdot dim$ & $\\frac{3}{2}(4 + \\lfloor 3 \\cdot ln(dim) \\rfloor)$ \\\\ \\hline\n\t\t\tmin error & 0   & - \\\\ \\hline\n\t\t\tp & 0.3 & - \\\\ \\hline\n\t\t\tc & 0.5 & - \\\\ \\hline\n\t\t\treplication & 20 & 50 \\\\ \\hline\n\t\t\t\\multilinecell{nb \\\\ nc \\\\~\\\\ } & \\multilinecell{40 \\\\ 81 \\\\ \\hline 121 = 11x11}  & \\multilinecell{100 equally spaced \\\\ points over the domain} \\\\ \\hline\n\t\t\tinitialisation & $\\vec{u_{apx}} \\in \\mathcal{N}(0,1)$ & \\multilinecell{$\\omega_i \\in \\mathcal{U}[-0.01, 0.01]$ \\\\ $\\gamma_i \\in \\mathcal{U}(0,1]$ \\\\ $c_{ik} \\in \\mathcal{U}[2\\Omega]$}  \\\\ \\hline\n\t\t\t\n\t\t\\end{tabular}\n\t}\n\t\\unterschrift{These predefined parameters are used for the following numerical experiments. }{}{}\n\t\\label{tab:ci_parameter}\n\\end{table}\n\nThe parameters $\\varphi$ and $\\kappa$ are used in the fitness function (equation \\eqref{eq:fit_func}) for changing the relative importance of the boundary and the interior. \\cite{chaquet_using_2019} take similar values. However, preliminary tests have shown, that the current values perform slightly better on the present testbed. Figure \\ref{fig:collocation_weight} shows the values of $\\xi$ and $\\varphi$. It further describes how the weighting factor emphasises the areas closer to the boundary. \n\n\\begin{figure}[h]\n\t\\centering\n\t\\noindent\\adjustbox{max width=0.8\\linewidth}{\n\t\t\\includegraphics[width=\\textwidth]{../img/pdf/collocation_weight.pdf}\n\t}\n\t\\unterschrift{Weighting factor $\\varphi$ and $\\xi$ on every collocation point}{}{}\n\t\\label{fig:collocation_weight}\n\\end{figure}\n\nThe population size used by \\cite{chaquet_using_2019} is based on the original formulation of the \\gls{cma_es}. However, they observed a better convergence when scaling the recommended population size by three. Typically, \\gls{de} uses larger population sizes. \\cite{mallipeddi_empirical_2008} describe an empirical study on choosing this parameter. They discuss the trade-off between premature convergence and computational effort. The results suggest that population sizes of $2\\cdot dim$ are more likely to stagnate, but also converge faster. Since time is a critical resource for the \\gls{ci}-solver, this population size is chosen. \n\nThe termination condition for \\gls{de} is either a maximum number of function evaluation, or a minimal function value to reach. Since the fitness function (equation \\eqref{eq:fit_func}) has its optimum at 0, this value is used as the termination condition. A helpful side-effect is that it ensures the same amount of function evaluation in every run, without early termination. This prevents outliers in the time and memory measurement. \n\nThe parameters p and c are specific to JADE (algorithm \\ref{algo: jade}). The mutation operator \\inlinecode{mutationCurrentToPBest1} uses p to select the best individuals and c weights the parameter adaption mechanism. For all experiments these values are set at $p=0.3$ and $c=0.5$. \n\nTo account for the statistical influence, every setup is reevaluated by 20 replications where each replication starts with independent initial guesses. \n\nThe \\gls{fem} solver terminates after it surpasses $5 \\cdot 10^4$ \\gls{dof}. The whole number of collocation points ($n_B + n_C$) is the equivalent for the \\gls{ci} solver. Typically, fewer collocation points are used, since the evaluation time of the fitness function scales poorly with more points. \\cite{chaquet_using_2019} use 100 equally spaced collocation points over the domain to solve the \\gls{pde}. Here, 121 points are created, as seen in figure \\ref{fig:collocation_points}. \n\n\n\\begin{figure}[h]\n\t\\centering\n\t\\noindent\\adjustbox{max width=0.6\\linewidth}{\n\t\t\\includegraphics[width=\\textwidth]{../img/pdf/testbed_small_domain.pdf}\n\t}\n\t\\unterschrift{Collocation points used in the testbed. For the \\gls{pde}s 0A and 0B with the larger domain, the lower limits $x_0$L and $x_1$L are replaced with -2 and the upper limits $x_0$U and $x_1$U are replaced with 2. The points are still equally spaced.}{}{}\n\t\\label{fig:collocation_points}\n\\end{figure}\n\nThe initialisation is done by a standard normal distribution. This means that every value in the $\\mathbf{p_{apx}}$ vector is drawn from a normal distribution. On the contrary, \\cite{chaquet_using_2019} initialise the values specifically tailored to each parameter of the kernel. This process assumes a priori information about the solution. In the typical application, this knowledge is not available and thus it should not be used. \n\n\n\\section{Hardware Infrastructure}\n\\label{chap:hardware_setup}\n\nTo increase the experimental throughput, two machines are used: a personal computer (machine 1) and a server in the cloud (machine 2). It is important that any time or memory usage comparisons must be performed between experiments on the same machine. In the experiments chapter it is separately denoted which comparisons are allowed. The following table \\ref{tab:machines} shows the properties of both machines. It is important to note that these information are only a reference point. This is probably not enough to actually recreate the exact time or memory data presented in this work. \n\n\\begin{table}[h]\n\t\\centering\n\t\\noindent\\adjustbox{max width=\\linewidth}{\n\t\t\\begin{tabular}{|c|c|c|}\n\t\t\t\n\t\t\t\\hline\n\t\t\t\\rowcolor[HTML]{\\farbeTabA}\n\t\t\t\n\t\t\tProperty & Machine 1 & Machine 2 \\\\ \\hline\n\t\t\t\n\t\t\tOperating System & Windows 10 Home 1909 18363.900 & CentOS Linux release 7.3.1611 \\\\ \\hline\n\t\t\tPython & Anaconda version 2019.03 & Anaconda version 2020.02 \\\\ \\hline\n\t\t\tProcessor & Intel Core i7-4790K CPU @ 4.00GHz & Intel Xeon CPU E5-2630 v3 @ 2.40GHz \\\\ \\hline\n\t\t\tCores & 4 Cores + 4 logical & 32 Cores \\\\ \\hline\n\t\t\t\n\t\t\\end{tabular}\n\t}\n\t\\unterschrift{Comparison of the machines used for the experiments.}{}{}\n\t\\label{tab:machines}\n\\end{table}\n\nDue to the Python incompatibilities, NGSolve can only be installed on machine 1. Thus, any time or memory usage comparisons between the \\gls{ci} solver and the \\gls{fem} solver must be conducted on machine 1. \n\n\\end{document}", "meta": {"hexsha": "9c377b4590e1e4894cf4db257098d237b273a974", "size": 30767, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "master_thesis_doc/tex/Experimental_Design.tex", "max_stars_repo_name": "nicolai-schwartze/Masterthesis", "max_stars_repo_head_hexsha": "7857af20c6b233901ab3cedc325bd64704111e16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-13T10:02:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-13T10:02:02.000Z", "max_issues_repo_path": "master_thesis_doc/tex/Experimental_Design.tex", "max_issues_repo_name": "nicolai-schwartze/Masterthesis", "max_issues_repo_head_hexsha": "7857af20c6b233901ab3cedc325bd64704111e16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "master_thesis_doc/tex/Experimental_Design.tex", "max_forks_repo_name": "nicolai-schwartze/Masterthesis", "max_forks_repo_head_hexsha": "7857af20c6b233901ab3cedc325bd64704111e16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 86.4241573034, "max_line_length": 1308, "alphanum_fraction": 0.7703708519, "num_tokens": 8346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.30594045969972306}}
{"text": "\\subsubsection{\\stid{6.02} LLNL ATDM: MFEM}\r\n\r\n\\paragraph{Overview}\r\n\r\nThe MFEM library\r\n\\cite{MFEM} is focused on providing high-performance mathematical algorithms\r\nand finite element discretizations to next-gen high-order ECP/ATDM\r\napplications. A main component of these efforts is the development of\r\nATDM-specific physics enhancements in the finite element algorithms in\r\nMFEM and the MFEM-based BLAST Arbitrary Lagrangian-Eulerian (ALE)\r\ncode \\cite{BLAST}, in order to provide efficient discretization\r\ncomponents for LLNL's ATDM efforts, including the MARBL application\r\n(ECP's LLNLApp).\r\n\r\nA second main task in the project is the development of unique unstructured\r\nadaptive mesh refinement (AMR) algorithms in MFEM, that focus on generality,\r\nparallel scalability, and ease of integration in unstructured mesh\r\napplications. The new AMR capabilities can benefit a variety of ECP apps that\r\nuse unstructured meshes, as well as many other applications in industry and the\r\nSciDAC program.\r\n\r\nAnother aspect of the work is the preparation of the MFEM finite element library\r\nand related codes for exascale platforms by using mathematical algorithms and\r\nsoftware implementations that exploit increasing on-node concurrency targeting\r\nmultiple complex architectures (e.g. GPUs). This part of the project is\r\nsynergistic with and leverages efforts from the ECP CEED co-design center.\r\n\r\nMFEM is an open-source finite element library with ~3000 downloads/year from 70+\r\ncountries. It is freely available at \\url{mfem.org}, on GitHub\r\nat \\url{github.com/mfem}, where the MFEM community includes more than 165\r\nmembers), as well as via Spack and OpenHPC. The application outreach and the\r\nintegration in the ECP ecosystem is further facilitated by MFEM's participation\r\nin ECP's xSDK project.\r\n\r\n\\paragraph{Key Challenges}\r\n\r\nThe key challenges addressed by the LLNL ATDM Mathematical Libraries project are:\r\n\r\n\\noindent\r\n{\\bf \\em Robust high-order finite element methods for ALE compressible flow.}\r\nWhile high-order methods offer significant advantages in terms of HPC performance,\r\ntheir application to complicated ALE problems requires careful considerations to\r\ncontrol oscillations and ensure accuracy.\r\n\r\n\\begin{figure}[htb]\r\n\\centering\r\n\\includegraphics[width=\\textwidth]{projects/2.3.6-NNSA/2.3.6.02-LLNL-ATDM/mfem-amr}\r\n\\caption{\\label{fig:mfem-amr}AMR implementation in MFEM allows many applications to benefit from non-conforming adaptivity, without significant changes in their codes.}\r\n\\end{figure}\r\n\r\n\\noindent\r\n{\\bf \\em Scalable algorithms for unstructured adaptive mesh refinement.}\r\nAdaptive mesh refinement is a common way to increasing application efficiency\r\nin problems with localized features. While block-structured AMR has been\r\nwell-studied, applying AMR in unstructured settings is challenging, especially\r\nin terms of derefinement, anisotropic refinement, parallel rebalance and\r\nscalability.\r\n\r\n\\noindent\r\n{\\bf \\em GPU porting of finite element codes.}\r\nDue to the relatively high complexity of the finite element machinery, MFEM,\r\nBLAST and related codes use object-oriented C++ design that allows generality\r\nand flexibility, but poses challenges in terms of porting to GPU architectures.\r\nFinding the right balance between generality and performance in the GPU context\r\nis an important challenge for many finite element-based codes that remains\r\noutstanding in the current software and programming model environment.\r\n\r\n\\paragraph{Solution Strategy}\r\n\r\nThe MFEM team has performed and documented a lot of research in\r\nhigh-performance mathematical algorithms and finite element discretizations\r\nof interest to ATDM applications\r\n\\cite{BLAST18,BLASTFCT18,BLASTFCT17,BLAST16,BLAST14,BLAST13,BLAST12,BLAST11}.\r\nOur work has demonstrated that the high-order finite element approach can\r\nsuccessfully handle coupled multi-material ALE, radiation-diffusion and MHD.\r\nWe have also shown how high-order methods can be adapted for monotonicity\r\n(positivity preservation), handling of artificial viscosity (shock capturing),\r\nsub-zonal physics via closure models, etc.\r\n\r\nTo enable many applications to take advantage of unstructured mesh adaptivity,\r\nthe MFEM team is developing AMR algorithms at library level, targeting both\r\n{\\em conforming} local refinement on simplex meshes and {\\em non-conforming}\r\nrefinement for quad/hex meshes. Our approach is fairly general, allowing for\r\nany high-order finite element space, H1, H(curl), H(div), on any high-order\r\ncurved mesh in 2D and 3D, arbitrary order hanging nodes, anisotropic refinement,\r\nderifenement and parallel load balancing.\r\nAn important feature of our library approach is that it is independent of\r\nthe physics, and thus easy to incorporate in apps, see Figure \\ref{fig:mfem-amr}.\r\n\r\nAs part of the efforts in the ECP co-design Center for Efficient Exascale\r\nDiscretizations (CEED), the MFEM team is also developing mathematical algorithms\r\nand software implementations for finite element methods that exploit increasingq\r\non-node concurrency targeting multiple complex architectures (e.g. GPUs). This\r\nwork includes the libCEED low-level API library, the Laghos miniapp, and several\r\nother efforts available through CEED.\r\n\r\nTo reach its many customers and partners in NNSA, DOE Office of Science,\r\nacademia and industry, the MFEM team delivers regular releases on GitHub\r\n(e.g. mfem-3.3 in 2017, mfem-3.4 in 2018, mfem-4.0 in 2019) that include\r\ndetailed documentation and many example codes.  Code quality is ensured\r\nby smoke tests with Travis CI on Linux, Mac, Windows and nightly\r\nregression testing at LLNL.\r\n\r\n\\paragraph{Recent Progress}\r\n\r\n\\begin{figure}[tb]\r\n\\centering\r\n\\includegraphics[width=.4\\textwidth]{projects/2.3.6-NNSA/2.3.6.02-LLNL-ATDM/HO-LO}\r\n\\includegraphics[width=.4\\textwidth]{projects/2.3.6-NNSA/2.3.6.02-LLNL-ATDM/mfem-gpu}\r\n\\caption{The MFEM team has developed High-Order $\\protect\\leftrightarrow$ Low-Order Transformations and GPU support for many linear algebra and finite element operations}\r\n\\end{figure}\r\n\r\nSelected recent highlights:\r\n\\begin{itemize}\r\n\\item\r\nDeveloped ALE discretization methods that support {\\it completely lossless}\r\nhigh order to low order transformations, and vice versa.\r\n\\item\r\nDelivered MFEM 4.0 release, with initial GPU support for many linear\r\nalgebra and finite elementn operations.\r\n\\item\r\nDeveloped a new formulation for discretizing problems with 1D spherical symmetry\r\nin BLAST. Extended BLAST to the 3T-model (separate equations for the electron\r\nand ion internal energies). Added support for changing masses during the\r\nLagrangian phase.\r\n\\item\r\nCompleted the delivery of discretization support for the FY18 MARBL ATDM L2\r\nmilestone, including new 3T radiation-diffusion algorithms, and a simulation\r\ncapability for problems with spherical and cylindrical symmetry via weight\r\nadjustments.\r\n%With this and other support from the MFEM team, the MARBL team\r\n%successfully defended its ATDM L2 milestone.\r\n\\item\r\nWorked on high-order ALE algorithms in BLAST: developed remap step for density\r\ncomponent masses, various code improvements and bugs fixes related to L2\r\nmilestone.\r\n%% \\item\r\n%% MFEM version 3.4 was released with many new features including: significantly\r\n%% improved non-conforming unstructured AMR scalability; integration with PUMI;\r\n%% block nonlinear operators and variable order NURBS; Conduit mesh blueprint\r\n%% support; general high-order-to-low-order refined field transfer; new specialized\r\n%% time integrators and 12 new examples and miniapps.\r\n%% \\item\r\n%% Implemented an initial draft of MFEM’s ``engine'' interface extension to support\r\n%% GPUs and other accelerators. Performed tests with the new ``engine'' extension\r\n%% on Sierra. Explored its use in the Laghos miniapp and BLAST.\r\n%% \\item\r\n%% Improvements in AMR interpolation matrix for better construction of\r\n%% communication groups and performance monitoring in the Laghos miniapp.\r\n%% \\item\r\n%% Several AMR improvements, including better local conforming tetrahedral\r\n%% refinement (collaborating with a GitHub user), fix for boundary coefficient\r\n%% projection, and general communication groups on for non-conforming AMR\r\n%% supporting the AMR integration in BLAST.\r\n%% \\item\r\n%% With summer student made progress on matrix-free algorithms for high-order field\r\n%% monotonicity, targeting performance improvements in the remap phase of\r\n%% MARBL/BLAST.\r\n%% \\item\r\n%% GLVis version 3.4 was released with several new features including: 10 new color\r\n%% palettes, better multi-screen window manager support, capability to show element\r\n%% and vertex numbering in 2D, use of X.509 certificates in secure sockets, and a\r\n%% new CMake build system.\r\n%% \\item\r\n%% Developed a new version of the hogtess high order experimental visualization\r\n%% tool based on modern OpenGL 4.3 compute shaders that does correct cutting of\r\n%% high order meshes in 3D.\r\n\\end{itemize}\r\n\r\n\\paragraph{Next Steps}\r\n\r\nThe MFEM team will next demonstrate the use of our HO/LO mappings on\r\ngeneral unstructured meshes in ATDM application at scale.  This includes\r\nnew discretization enhancements and new algorithms for ALE multi-physics\r\napplications, in particular in support of the MARBL appliaction's L2\r\nmilestone, especially with respect to the transition to exascale\r\nhardware.  We will have MFEM running on early access machines as soon as\r\nthey become available, and will support production runs on exascale platforms.\r\n", "meta": {"hexsha": "d54c273c06a411782eda0ce3b3a43c761734105c", "size": 9440, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "projects/2.3.6-NNSA/2.3.6.02-LLNL-ATDM/2.3.6.02-LLNL-ATDM-MFEM.tex", "max_stars_repo_name": "curfman/ECP-ST-CAR-PUBLIC", "max_stars_repo_head_hexsha": "002b50d166516c0b55b566fcb576dda251b05a6a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "projects/2.3.6-NNSA/2.3.6.02-LLNL-ATDM/2.3.6.02-LLNL-ATDM-MFEM.tex", "max_issues_repo_name": "curfman/ECP-ST-CAR-PUBLIC", "max_issues_repo_head_hexsha": "002b50d166516c0b55b566fcb576dda251b05a6a", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "projects/2.3.6-NNSA/2.3.6.02-LLNL-ATDM/2.3.6.02-LLNL-ATDM-MFEM.tex", "max_forks_repo_name": "curfman/ECP-ST-CAR-PUBLIC", "max_forks_repo_head_hexsha": "002b50d166516c0b55b566fcb576dda251b05a6a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.7374301676, "max_line_length": 171, "alphanum_fraction": 0.7951271186, "num_tokens": 2133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.3057697322114779}}
{"text": "This appendix presents the complete type system of Typed Lua.\n\n\\section{Subtyping rules}\n\n\\noindent\n\n\\mylabel{S-LITERAL}\n\\[\n\\senv \\vdash L \\subtype L\n\\]\n\n\\mylabel{S-FALSE}\n\\[\n\\senv \\vdash \\False \\subtype \\Boolean\n\\]\n\n\\mylabel{S-TRUE}\n\\[\n\\senv \\vdash \\True \\subtype \\Boolean\n\\]\n\n\\mylabel{S-STRING}\n\\[\n\\senv \\vdash {\\it string} \\subtype \\String\n\\]\n\n\\mylabel{S-INT1}\n\\[\n\\senv \\vdash {\\it int} \\subtype \\Integer\n\\]\n\n\\mylabel{S-INT2}\n\\[\n\\senv \\vdash {\\it int} \\subtype \\Number\n\\]\n\n\\mylabel{S-FLOAT}\n\\[\n\\senv \\vdash {\\it float} \\subtype \\Number\n\\]\n\n\\mylabel{S-BASE}\n\\[\n\\senv \\vdash B \\subtype B\n\\]\n\n\\mylabel{S-INTEGER}\n\\[\n\\senv \\vdash \\Integer \\subtype \\Number\n\\]\n\n\\mylabel{S-NIL}\n\\[\n\\senv \\vdash \\Nil \\subtype \\Nil\n\\]\n\n\\mylabel{S-VALUE}\n\\[\n\\senv \\vdash F \\subtype \\Value\n\\]\n\n\\mylabel{S-ANY}\n\\[\n\\senv \\vdash \\Any \\subtype \\Any\n\\]\n\n\\mylabel{S-SELF}\n\\[\n\\senv \\vdash \\Self \\subtype \\Self\n\\]\n\n\\mylabel{S-UNION1}\n\\[\n\\dfrac{\\senv \\vdash F_{1} \\subtype F \\;\\;\\;\n       \\senv \\vdash F_{2} \\subtype F}\n      {\\senv \\vdash F_{1} \\cup F_{2} \\subtype F}\n\\]\n\n\\mylabel{S-UNION2}\n\\[\n\\dfrac{\\senv \\vdash F \\subtype F_{1}}\n      {\\senv \\vdash F \\subtype F_{1} \\cup F_{2}}\n\\]\n\n\\mylabel{S-UNION3}\n\\[\n\\dfrac{\\senv \\vdash F \\subtype F_{2}}\n      {\\senv \\vdash F \\subtype F_{1} \\cup F_{2}}\n\\]\n\n\\mylabel{S-FUNCTION}\n\\[\n\\dfrac{\\senv \\vdash S_{3} \\subtype S_{1} \\;\\;\\;\n       \\senv \\vdash S_{2} \\subtype S_{4}}\n      {\\senv \\vdash S_{1} \\rightarrow S_{2} \\subtype S_{3} \\rightarrow S_{4}}\n\\]\n\n\\mylabel{S-PAIR}\n\\[\n\\dfrac{\\senv \\vdash F_{1} \\subtype F_{2} \\;\\;\\;\n       \\senv \\vdash P_{1} \\subtype P_{2}}\n      {\\senv \\vdash F_{1} \\times P_{1} \\subtype F_{2} \\times P_{2}}\n\\]\n\n\\mylabel{S-VARARG1}\n\\[\n\\dfrac{\\senv \\vdash F_{1} \\cup \\Nil \\subtype F_{2} \\cup \\Nil}\n      {\\senv \\vdash F_{1}{*} \\subtype F_{2}{*}}\n\\]\n\n\\mylabel{S-VARARG2}\n\\[\n\\dfrac{\\senv \\vdash F_{1} \\cup \\Nil \\subtype F_{2} \\;\\;\\;\n       \\senv \\vdash F_{1}{*} \\subtype P_{2}}\n      {\\senv \\vdash F_{1}{*} \\subtype F_{2} \\times P_{2}}\n\\]\n\n\\mylabel{S-VARARG3}\n\\[\n\\dfrac{\\senv \\vdash F_{1} \\subtype F_{2} \\cup \\Nil \\;\\;\\;\n       \\senv \\vdash P_{1} \\subtype F_{2}{*}}\n      {\\senv \\vdash F_{1} \\times P_{1} \\subtype F_{2}{*}}\n\\]\n\n\\mylabel{S-UNION4}\n\\[\n\\dfrac{\\senv \\vdash S_{1} \\subtype S \\;\\;\\;\n       \\senv \\vdash S_{2} \\subtype S}\n      {\\senv \\vdash S_{1} \\sqcup S_{2} \\subtype S}\n\\]\n\n\\mylabel{S-UNION5}\n\\[\n\\dfrac{\\senv \\vdash S \\subtype S_{1}}\n      {\\senv \\vdash S \\subtype S_{1} \\sqcup S_{2}}\n\\]\n\n\\mylabel{S-UNION6}\n\\[\n\\dfrac{\\senv \\vdash S \\subtype S_{2}}\n      {\\senv \\vdash S \\subtype S_{1} \\sqcup S_{2}}\n\\]\n\n\\mylabel{S-TABLE1}\n\\[\n\\dfrac{\\forall i \\; \\exists j \\;\\;\\;\n       \\senv \\vdash F_{j} \\subtype F_{i}' \\;\\;\\;\n       \\senv \\vdash F_{i}' \\subtype F_{j} \\;\\;\\;\n       \\senv \\vdash V_{j} \\subtype_{c} V_{i}'}\n      {\\senv \\vdash \\{\\overline{F{:}V}\\}_{fixed|closed} \\subtype\n                    \\{\\overline{F'{:}V'}\\}_{closed}}\n\\]\n\n\\mylabel{S-TABLE2}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\forall i \\; \\forall j \\;\\;\\;\n       \\senv \\vdash F_{i} \\subtype F_{j}' \\to \\senv \\vdash V_{i} \\subtype_{u} V_{j}'\\\\\n       \\forall j \\; \\nexists i \\;\\;\\;\n       \\senv \\vdash F_{i} \\subtype F_{j}' \\to \\senv \\vdash \\Nil \\subtype_{o} V_{j}'\n       \\end{array}}\n      {\\senv \\vdash \\{\\overline{F{:}V}\\}_{unique} \\subtype\n                    \\{\\overline{F'{:}V'}\\}_{closed}}\n\\]\n\n\\mylabel{S-TABLE3}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\forall i \\; \\exists j \\;\\;\\;\n       \\senv \\vdash F_{i} \\subtype F_{j}' \\land \\senv \\vdash V_{i} \\subtype_{u} V_{j}' \\\\\n       \\forall j \\; \\nexists i \\;\\;\\;\n       \\senv \\vdash F_{i} \\subtype F_{j}' \\to \\senv \\vdash \\Nil \\subtype_{o} V_{j}'\n       \\end{array}}\n      {\\senv \\vdash \\{\\overline{F{:}V}\\}_{unique} \\subtype\n                    \\{\\overline{F'{:}V'}\\}_{unique|open|fixed}}\n\\]\n\n\\mylabel{S-TABLE4}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\forall i \\; \\forall j \\;\\;\\;\n       \\senv \\vdash F_{i} \\subtype F_{j}' \\to \\senv \\vdash V_{i} \\subtype_{c} V_{j}' \\\\\n       \\forall j \\; \\nexists i \\;\\;\\;\n       \\senv \\vdash F_{i} \\subtype F_{j}' \\to \\senv \\vdash \\Nil \\subtype_{o} V_{j}'\n       \\end{array}}\n      {\\senv \\vdash \\{\\overline{F{:}V}\\}_{open} \\subtype\n                    \\{\\overline{F'{:}V'}\\}_{closed}}\n\\]\n\n\\mylabel{S-TABLE5}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\forall i \\; \\exists j \\;\\;\\;\n       \\senv \\vdash F_{i} \\subtype F_{j}' \\land \\senv \\vdash V_{i} \\subtype_{c} V_{j}' \\\\\n       \\forall j \\; \\nexists i \\;\\;\\;\n       \\senv \\vdash F_{i} \\subtype F_{j}' \\to \\senv \\vdash \\Nil \\subtype_{o} V_{j}'\n       \\end{array}}\n      {\\senv \\vdash \\{\\overline{F{:}V}\\}_{open} \\subtype\n                    \\{\\overline{F'{:}V'}\\}_{open|fixed}}\n\\]\n\n\\mylabel{S-TABLE6}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\forall i \\; \\exists j \\;\\;\\;\n       \\senv \\vdash F_{i} \\subtype F_{j}' \\;\\;\\;\n       \\senv \\vdash F_{j}' \\subtype F_{i} \\;\\;\\;\n       \\senv \\vdash V_{i} \\subtype_{c} V_{j}' \\\\\n       \\forall j \\; \\exists i \\;\\;\\;\n       \\senv \\vdash F_{i} \\subtype F_{j}' \\;\\;\\;\n       \\senv \\vdash F_{j}' \\subtype F_{i} \\;\\;\\;\n       \\senv \\vdash V_{i} \\subtype_{c} V_{j}' \\\\\n       \\end{array}}\n      {\\senv \\vdash \\{\\overline{F{:}V}\\}_{fixed} \\subtype\n                    \\{\\overline{F'{:}V'}\\}_{fixed}}\n\\]\n\n\\mylabel{S-FIELD1}\n\\[\n\\dfrac{\\senv \\vdash F_{1} \\subtype F_{2} \\;\\;\\;\n       \\senv \\vdash F_{2} \\subtype F_{1}}\n      {\\senv \\vdash F_{1} \\subtype_{c} F_{2}}\n\\]\n\n\\mylabel{S-FIELD2}\n\\[\n\\dfrac{\\senv \\vdash F_{1} \\subtype F_{2}}\n      {\\senv \\vdash \\Const \\; F_{1} \\subtype_{c} \\Const \\; F_{2}}\n\\]\n\n\\mylabel{S-FIELD3}\n\\[\n\\dfrac{\\senv \\vdash F_{1} \\subtype F_{2}}\n      {\\senv \\vdash F_{1} \\subtype_{c} \\Const \\; F_{2}}\n\\]\n\n\\mylabel{S-FIELD4}\n\\[\n\\dfrac{\\senv \\vdash F_{1} \\subtype F_{2}}\n      {\\senv \\vdash F_{1} \\subtype_{u} F_{2}}\n\\]\n\n\\mylabel{S-FIELD5}\n\\[\n\\dfrac{\\senv \\vdash F_{1} \\subtype F_{2}}\n      {\\senv \\vdash \\Const \\; F_{1} \\subtype_{u} \\Const \\; F_{2}}\n\\]\n\n\\mylabel{S-FIELD6}\n\\[\n\\dfrac{\\senv \\vdash F_{1} \\subtype F_{2}}\n      {\\senv \\vdash \\Const \\; F_{1} \\subtype_{u} F_{2}}\n\\]\n\n\\mylabel{S-FIELD7}\n\\[\n\\dfrac{\\senv \\vdash F_{1} \\subtype F_{2}}\n      {\\senv \\vdash F_{1} \\subtype_{u} \\Const \\; F_{2}}\n\\]\n\n\\mylabel{S-FIELD8}\n\\[\n\\dfrac{\\senv \\vdash \\Nil \\subtype F}\n      {\\senv \\vdash \\Nil \\subtype_{o} F}\n\\]\n\n\\mylabel{S-FIELD9}\n\\[\n\\dfrac{\\senv \\vdash \\Nil \\subtype F}\n      {\\senv \\vdash \\Nil \\subtype_{o} \\Const \\; F}\n\\]\n\n\\mylabel{S-AMBER}\n\\[\n\\dfrac{\\senv[x_{1} \\subtype x_{2}] \\vdash F_{1} \\subtype F_{2}}\n      {\\senv \\vdash \\mu x_{1}.F_{1} \\subtype \\mu x_{2}.F_{2}}\n\\]\n\n\\mylabel{S-ASSUMPTION}\n\\[\n\\dfrac{x_{1} \\subtype x_{2} \\in \\senv}\n      {\\senv \\vdash x_{1} \\subtype x_{2}}\n\\]\n\n\\mylabel{S-UNFOLDR}\n\\[\n\\dfrac{\\senv \\vdash F_{1} \\subtype [x \\mapsto \\mu x.F_{2}]F_{2}}\n      {\\senv \\vdash F_{1} \\subtype \\mu x.F_{2}}\n\\]\n\n\\mylabel{S-UNFOLDL}\n\\[\n\\dfrac{\\senv \\vdash [x \\mapsto \\mu x.F_{1}]F_{1} \\subtype F_{2}}\n      {\\senv \\vdash \\mu x.F_{1} \\subtype F_{2}}\n\\]\n\n\\mylabel{S-EXPRESSION}\n\\[\n\\senv \\vdash T \\subtype T\n\\]\n\n\\mylabel{S-PAIR2}\n\\[\n\\dfrac{\\senv \\vdash T_{1} \\subtype T_{2} \\;\\;\\;\n       \\senv \\vdash E_{1} \\subtype E_{2}}\n      {\\senv \\vdash T_{1} \\times E_{1} \\subtype T_{2} \\times E_{2}}\n\\]\n\n\\mylabel{S-VARARG4}\n\\[\n\\dfrac{\\senv \\vdash T_{1} \\cup \\Nil \\subtype T_{2} \\cup \\Nil}\n      {\\senv \\vdash T_{1}{*} \\subtype T_{2}{*}}\n\\]\n\n\\mylabel{S-VARARG5}\n\\[\n\\dfrac{\\senv \\vdash T_{1} \\cup \\Nil \\subtype T_{2} \\;\\;\\;\n       \\senv \\vdash T_{1}{*} \\subtype E_{2}}\n      {\\senv \\vdash T_{1}{*} \\subtype T_{2} \\times E_{2}}\n\\]\n\n\\mylabel{S-VARARG6}\n\\[\n\\dfrac{\\senv \\vdash T_{1} \\subtype T_{2} \\cup \\Nil \\;\\;\\;\n       \\senv \\vdash E_{1} \\subtype T_{2}{*}}\n      {\\senv \\vdash T_{1} \\times E_{1} \\subtype T_{2}{*}}\n\\]\n\n\\mylabel{C-ANY1}\n\\[\n\\senv \\vdash F \\lesssim \\Any\n\\]\n\n\\mylabel{C-ANY2}\n\\[\n\\senv \\vdash \\Any \\lesssim F\n\\]\n\n\\section{Typing rules}\n\n\\noindent\n\n\\mylabel{T-SKIP}\n\\[\n\\env_{1}, \\penv \\vdash \\mathbf{skip}, \\env_{1}\n\\]\n\n\\mylabel{T-SEQ}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash s_{1}, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash s_{2}, \\env_{3}}\n      {\\env_{1}, \\penv \\vdash s_{1} \\; ; \\; s_{2}, \\env_{3}}\n\\]\n\n\\mylabel{T-ASSIGNMENT}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash el:S_{1}, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash \\overline{l}:S_{2}, \\env_{3} \\;\\;\\;\n       S_{1} \\lesssim S_{2}}\n      {\\env_{1}, \\penv \\vdash \\overline{l} = el,\\env_{3}}\n\\]\n\n\\mylabel{T-METHOD1}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}(id_{1}) = F_{s} \\;\\;\\;\n       F_{s} = \\{\\overline{F{:}V}\\}_{unique} \\\\\n       \\env_{1}, \\penv \\vdash id_{2} : L, \\env_{2} \\;\\;\\;\n       \\nexists i \\in 1..n \\; L \\lesssim F_{i} \\;\\;\\;\n       n = |\\overline{F{:}V}| \\\\\n       closeall(\\env_{1})[self \\mapsto \\Self, \\overline{id \\mapsto F}, \\self \\mapsto F_{s}],\n       \\penv[\\ret \\mapsto S] \\vdash s, \\env_{3}\\\\\n       F_{o} = \\{\\overline{F{:}V}, L{:}\\Const \\; \\Self \\times F_{1} \\times ... \\times F_{n} \\times \\Nil{*} \\rightarrow S\\}_{unique}\\\\\n       \\env_{4} = openset(\\env_{1}[id_{1} \\mapsto F_{o}], frv(\\mathbf{fun} \\; (\\overline{id{:}T}){:}S \\; s)) \\\\\n       \\env_{5} = closeset(\\env_{4}, fav(\\mathbf{fun} \\; (\\overline{id{:}T}){:}S \\; s))\n       \\end{array}}\n      {\\begin{array}{c}\n       \\env_{1}, \\penv \\vdash \\mathbf{fun} \\; id_{1}{:}id_{2} \\; (\\overline{id{:}F}){:}S \\; s, \\env_{5}\\\\\n       \\end{array}}\n\\]\n\n\\mylabel{T-METHOD2}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}(id_{1}) = F_{s} \\;\\;\\;\n       F_{s} = \\{\\overline{F{:}V}\\}_{open} \\\\\n       \\env_{1}, \\penv \\vdash id_{2} : L, \\env_{2} \\;\\;\\;\n       \\nexists i \\in 1..n \\; L \\lesssim F_{i} \\;\\;\\;\n       n = |\\overline{F{:}V}| \\\\\n       closeall(\\env_{1})[self \\mapsto \\Self, \\overline{id \\mapsto F}, \\self \\mapsto F_{s}],\n       \\penv[\\ret \\mapsto S] \\vdash s, \\env_{3}\\\\\n       F_{o} = \\{\\overline{F{:}V}, L{:}\\Const \\; \\Self \\times F_{1} \\times ... \\times F_{n} \\times \\Nil{*} \\rightarrow S\\}_{open}\\\\\n       \\env_{4} = openset(\\env_{1}[id_{1} \\mapsto F_{o}], frv(\\mathbf{fun} \\; (\\overline{id{:}T}){:}S \\; s)) \\\\\n       \\env_{5} = closeset(\\env_{4}, fav(\\mathbf{fun} \\; (\\overline{id{:}T}){:}S \\; s))\n       \\end{array}}\n      {\\begin{array}{c}\n       \\env_{1}, \\penv \\vdash \\mathbf{fun} \\; id_{1}{:}id_{2} \\; (\\overline{id{:}F}){:}S \\; s, \\env_{5}\\\\\n       \\end{array}}\n\\]\n\n\\mylabel{T-METHOD3}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}(id_{1}) = F_{s} \\;\\;\\;\n       F_{s} = \\{\\overline{F{:}V}\\}_{unique} \\\\\n       \\env_{1}, \\penv \\vdash id_{2} : L, \\env_{2} \\;\\;\\;\n       \\nexists i \\in 1..n \\; L \\lesssim F_{i} \\;\\;\\;\n       n = |\\overline{F{:}V}| \\\\\n       closeall(\\env_{1})[self \\mapsto \\Self, \\overline{id \\mapsto F}, {...} \\mapsto F, \\self \\mapsto F_{s}],\n       \\penv[\\ret \\mapsto S] \\vdash s, \\env_{3}\\\\\n       F_{o} = \\{\\overline{F{:}V}, L{:}\\Const \\; \\Self \\times F_{1} \\times ... \\times F_{n} \\times F{*} \\rightarrow S\\}_{unique}\\\\\n       \\env_{4} = openset(\\env_{1}[id_{1} \\mapsto F_{o}], frv(\\mathbf{fun} \\; (\\overline{id{:}T}){:}S \\; s)) \\\\\n       \\env_{5} = closeset(\\env_{4}, fav(\\mathbf{fun} \\; (\\overline{id{:}T}){:}S \\; s))\n       \\end{array}}\n      {\\begin{array}{c}\n       \\env_{1}, \\penv \\vdash \\mathbf{fun} \\; id_{1}{:}id_{2} \\; (\\overline{id{:}F},{...}{:}F){:}S \\; s, \\env_{5}\\\\\n       \\end{array}}\n\\]\n\n\\mylabel{T-METHOD4}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}(id_{1}) = F_{s} \\;\\;\\;\n       F_{s} = \\{\\overline{F{:}V}\\}_{open} \\\\\n       \\env_{1}, \\penv \\vdash id_{2} : L, \\env_{2} \\;\\;\\;\n       \\nexists i \\in 1..n \\; L \\lesssim F_{i} \\;\\;\\;\n       n = |\\overline{F{:}V}| \\\\\n       closeall(\\env_{1})[self \\mapsto \\Self, \\overline{id \\mapsto F}, {...} \\mapsto F, \\self \\mapsto F_{s}],\n       \\penv[\\ret \\mapsto S] \\vdash s, \\env_{3}\\\\\n       F_{o} = \\{\\overline{F{:}V}, L{:}\\Const \\; \\Self \\times F_{1} \\times ... \\times F_{n} \\times F{*} \\rightarrow S\\}_{open}\\\\\n       \\env_{4} = openset(\\env_{1}[id_{1} \\mapsto F_{o}], frv(\\mathbf{fun} \\; (\\overline{id{:}T}){:}S \\; s)) \\\\\n       \\env_{5} = closeset(\\env_{4}, fav(\\mathbf{fun} \\; (\\overline{id{:}T}){:}S \\; s))\n       \\end{array}}\n      {\\begin{array}{c}\n       \\env_{1}, \\penv \\vdash \\mathbf{fun} \\; id_{1}{:}id_{2} \\; (\\overline{id{:}F},{...}{:}F){:}S \\; s, \\env_{5}\\\\\n       \\end{array}}\n\\]\n\n\\mylabel{T-METHOD5}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}(id_{1}) = F_{s} \\;\\;\\;\n       F_{s} = \\{\\overline{F{:}V}\\}_{unique} \\;\\;\\;\n       \\env_{1}, \\penv \\vdash id_{2} : L, \\env_{2} \\;\\;\\;\n       n = |\\overline{F{:}V}| \\\\\n       \\exists i \\in 1..n \\; L \\subtype F_{i} \\wedge F_{i} \\subtype L \\wedge\n       \\Const \\; \\Self \\times F_{1} \\times ... \\times F_{n} \\times \\Nil{*} \\rightarrow S \\subtype V_{i} \\\\\n       closeall(\\env_{1})[self \\mapsto \\Self, \\overline{id \\mapsto F}, \\self \\mapsto F_{s}],\n       \\penv[\\ret \\mapsto S] \\vdash s, \\env_{3}\\\\\n       V_{i} \\mapsto \\Const \\; \\Self \\times F_{1} \\times ... \\times F_{n} \\times \\Nil{*} \\rightarrow S\\\\\n       \\env_{4} = openset(\\env_{1}[id_{1} \\mapsto F_{s}], frv(\\mathbf{fun} \\; (\\overline{id{:}T}){:}S \\; s)) \\\\\n       \\env_{5} = closeset(\\env_{4}, fav(\\mathbf{fun} \\; (\\overline{id{:}T}){:}S \\; s))\n       \\end{array}}\n      {\\begin{array}{c}\n       \\env_{1}, \\penv \\vdash \\mathbf{fun} \\; id_{1}{:}id_{2} \\; (\\overline{id{:}F}){:}S \\; s, \\env_{5}\\\\\n       \\end{array}}\n\\]\n\n\\mylabel{T-METHOD6}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}(id_{1}) = F_{s} \\;\\;\\;\n       F_{s} = \\{\\overline{F{:}V}\\}_{open} \\;\\;\\;\n       \\env_{1}, \\penv \\vdash id_{2} : L, \\env_{2} \\;\\;\\;\n       n = |\\overline{F{:}V}| \\\\\n       \\exists i \\in 1..n \\; L \\subtype F_{i} \\wedge F_{i} \\subtype L \\wedge\n       \\Const \\; \\Self \\times F_{1} \\times ... \\times F_{n} \\times \\Nil{*} \\rightarrow S \\subtype V_{i} \\\\\n       closeall(\\env_{1})[self \\mapsto \\Self, \\overline{id \\mapsto F}, \\self \\mapsto F_{s}],\n       \\penv[\\ret \\mapsto S] \\vdash s, \\env_{3}\\\\\n       V_{i} \\mapsto \\Const \\; \\Self \\times F_{1} \\times ... \\times F_{n} \\times \\Nil{*} \\rightarrow S\\\\\n       \\env_{4} = openset(\\env_{1}[id_{1} \\mapsto F_{s}], frv(\\mathbf{fun} \\; (\\overline{id{:}T}){:}S \\; s)) \\\\\n       \\env_{5} = closeset(\\env_{4}, fav(\\mathbf{fun} \\; (\\overline{id{:}T}){:}S \\; s))\n       \\end{array}}\n      {\\begin{array}{c}\n       \\env_{1}, \\penv \\vdash \\mathbf{fun} \\; id_{1}{:}id_{2} \\; (\\overline{id{:}F}){:}S \\; s, \\env_{5}\\\\\n       \\end{array}}\n\\]\n\n\\mylabel{T-METHOD7}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}(id_{1}) = F_{s} \\;\\;\\;\n       F_{s} = \\{\\overline{F{:}V}\\}_{unique} \\;\\;\\;\n       \\env_{1}, \\penv \\vdash id_{2} : L, \\env_{2} \\;\\;\\;\n       n = |\\overline{F{:}V}| \\\\\n       \\exists i \\in 1..n \\; L \\subtype F_{i} \\wedge F_{i} \\subtype L \\wedge\n       \\Const \\; \\Self \\times F_{1} \\times ... \\times F_{n} \\times F{*} \\rightarrow S \\subtype V_{i} \\\\\n       closeall(\\env_{1})[self \\mapsto \\Self, \\overline{id \\mapsto F}, {...} \\mapsto F, \\self \\mapsto F_{s}],\n       \\penv[\\ret \\mapsto S] \\vdash s, \\env_{3}\\\\\n       V_{i} \\mapsto \\Const \\; \\Self \\times F_{1} \\times ... \\times F_{n} \\times F{*} \\rightarrow S\\\\\n       \\env_{4} = openset(\\env_{1}[id_{1} \\mapsto F_{s}], frv(\\mathbf{fun} \\; (\\overline{id{:}T}){:}S \\; s)) \\\\\n       \\env_{5} = closeset(\\env_{4}, fav(\\mathbf{fun} \\; (\\overline{id{:}T}){:}S \\; s))\n       \\end{array}}\n      {\\begin{array}{c}\n       \\env_{1}, \\penv \\vdash \\mathbf{fun} \\; id_{1}{:}id_{2} \\; (\\overline{id{:}F},{...}{:}F){:}S \\; s, \\env_{5}\\\\\n       \\end{array}}\n\\]\n\n\\mylabel{T-METHOD8}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}(id_{1}) = F_{s} \\;\\;\\;\n       F_{s} = \\{\\overline{F{:}V}\\}_{open} \\;\\;\\;\n       \\env_{1}, \\penv \\vdash id_{2} : L, \\env_{2} \\;\\;\\;\n       n = |\\overline{F{:}V}| \\\\\n       \\exists i \\in 1..n \\; L \\subtype F_{i} \\wedge F_{i} \\subtype L \\wedge\n       \\Const \\; \\Self \\times F_{1} \\times ... \\times F_{n} \\times F{*} \\rightarrow S \\subtype V_{i} \\\\\n       closeall(\\env_{1})[self \\mapsto \\Self, \\overline{id \\mapsto F}, {...} \\mapsto F, \\self \\mapsto F_{s}],\n       \\penv[\\ret \\mapsto S] \\vdash s, \\env_{3}\\\\\n       V_{i} \\mapsto \\Const \\; \\Self \\times F_{1} \\times ... \\times F_{n} \\times F{*} \\rightarrow S\\\\\n       \\env_{4} = openset(\\env_{1}[id_{1} \\mapsto F_{s}], frv(\\mathbf{fun} \\; (\\overline{id{:}T}){:}S \\; s)) \\\\\n       \\env_{5} = closeset(\\env_{4}, fav(\\mathbf{fun} \\; (\\overline{id{:}T}){:}S \\; s))\n       \\end{array}}\n      {\\begin{array}{c}\n       \\env_{1}, \\penv \\vdash \\mathbf{fun} \\; id_{1}{:}id_{2} \\; (\\overline{id{:}F},{...}{:}F){:}S \\; s, \\env_{5}\\\\\n       \\end{array}}\n\\]\n\n\\mylabel{T-WHILE1}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}, \\penv \\vdash e:F, \\env_{2} \\;\\;\\;\n       closeall(\\env_{2}), \\penv \\vdash s, \\env_{3}\\\\\n       \\env_{4} = closeset(\\env_{2}, fav(s)) \\\\\n       \\env_{5} = openset(\\env_{4},frv(s))\n       \\end{array}}\n      {\\env_{1}, \\penv \\vdash \\mathbf{while} \\; e \\; \\mathbf{do} \\; s,\\env_{5}}\n\\]\n\n\\mylabel{T-WHILE2}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}(id) = F\\\\\n       closeall(\\env_{1}[id \\mapsto \\phi(F, filter(F, \\Nil))]), \\penv \\vdash s, \\env_{2}\\\\\n       \\env_{3} = openset(\\env_{1}[id \\mapsto F], frv(s))\\\\\n       \\env_{4} = closeset(\\env_{3}, fav(s))\n       \\end{array}}\n      {\\env_{1}, \\penv \\vdash \\mathbf{while} \\; id \\; \\mathbf{do} \\; s,\\env_{4}}\n\\]\n\n\\mylabel{T-IF1}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}, \\penv \\vdash e:T, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash s_{1}:\\env_{3} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash s_{2}:\\env_{4} \\;\\;\\;\n       \\env_{5} = join(\\env_{3}, \\env_{4})\n       \\end{array}}\n      {\\env_{1} \\vdash \\mathbf{if} \\; e \\; \\mathbf{then} \\; s_{1} \\; \\mathbf{else} \\; s_{2}, \\env_{5}}\n\\]\n\n\\mylabel{T-IF2}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}(id) = F \\;\\;\\;\n       F_{t} = fot(F, \\Nil) \\;\\;\\;\n       F_{e} = fit(F, \\Nil) \\\\\n       \\env_{1}[id \\mapsto \\phi(F,F_{t})], \\penv \\vdash s_{1}, \\env_{2}\\\\\n       \\env_{1}[id \\mapsto \\phi(F,F_{e})], \\penv \\vdash s_{2}, \\env_{3}\\\\\n       \\env_{4} = join(\\env_{2}, \\env_{3})\n      \\end{array}}\n      {\\env_{1}, \\penv \\vdash \\mathbf{if} \\; id \\; \\mathbf{then} \\; s_{1} \\; \\mathbf{else} \\; s_{2}, \\env_{4}[id \\mapsto F]}\n\\]\n\n\\mylabel{T-IF3}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}(id) = F \\;\\;\\;\n       F_{t} = fot(F, \\Nil) \\;\\;\\;\n       F_{e} = fit(F, \\Nil) \\\\\n       F_{e} = \\Void \\;\\;\\;\n       \\env_{1}[id \\mapsto \\phi(F,F_{t})], \\penv \\vdash s_{1}, \\env_{2}\n      \\end{array}}\n      {\\env_{1}, \\penv \\vdash \\mathbf{if} \\; id \\; \\mathbf{then} \\; s_{1} \\; \\mathbf{else} \\; s_{2}, \\env_{2}[id \\mapsto F]}\n\\]\n\n\\mylabel{T-IF4}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}(id) = F \\;\\;\\;\n       F_{t} = fot(F, \\Nil) \\;\\;\\;\n       F_{e} = fit(F, \\Nil) \\\\\n       F_{t} = \\Void \\;\\;\\;\n       \\env_{1}[id \\mapsto \\phi(F,F_{e})], \\penv \\vdash s_{2}, \\env_{2}\n      \\end{array}}\n      {\\env_{1}, \\penv \\vdash \\mathbf{if} \\; id \\; \\mathbf{then} \\; s_{1} \\; \\mathbf{else} \\; s_{2}, \\env_{2}[id \\mapsto F]}\n\\]\n\n\\mylabel{T-IF5}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}(id) = \\pi_{i}^{x} \\\\\n       S_{t} = fopt(\\penv(x), \\Nil, i) \\;\\;\\;\n       S_{e} = fipt(\\penv(x), \\Nil, i) \\\\\n       \\env_{1}, \\penv[x \\mapsto S_{t}] \\vdash s_{1}, \\env_{2}\\\\\n       \\env_{1}, \\penv[x \\mapsto S_{e}] \\vdash s_{2}, \\env_{3}\\\\\n       \\env_{4} = join(\\env_{2}, \\env_{3})\n      \\end{array}}\n      {\\env_{1}, \\penv \\vdash \\mathbf{if} \\; id \\; \\mathbf{then} \\; s_{1} \\; \\mathbf{else} \\; s_{2}, \\env_{4}}\n\\]\n\n\\mylabel{T-IF6}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}(id) = \\pi_{i}^{x} \\\\\n       S_{t} = fopt(\\penv(x), \\Nil, i) \\\\\n       fit(proj(\\penv(x), i), \\Nil) = \\Void \\\\\n       \\env_{1}, \\penv[x \\mapsto S_{t}] \\vdash s_{1}, \\env_{2}\n      \\end{array}}\n      {\\env_{1}, \\penv \\vdash \\mathbf{if} \\; id \\; \\mathbf{then} \\; s_{1} \\; \\mathbf{else} \\; s_{2}, \\env_{2}}\n\\]\n\n\\mylabel{T-IF7}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}(id) = \\pi_{i}^{x} \\\\\n       S_{e} = fipt(\\penv(x), \\Nil, i) \\\\\n       fot(proj(\\penv(x), i), \\Nil) = \\Void \\\\\n       \\env_{1}, \\penv[x \\mapsto S_{e}] \\vdash s_{2}, \\env_{2}\n      \\end{array}}\n      {\\env_{1}, \\penv \\vdash \\mathbf{if} \\; id \\; \\mathbf{then} \\; s_{1} \\; \\mathbf{else} \\; s_{2}, \\env_{2}}\n\\]\n\n\\mylabel{T-IF8}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}(id) = \\phi(F_{1},F_{2}) \\;\\;\\;\n       F_{t} = fit(F_{2}, \\String) \\;\\;\\;\n       F_{e} = fot(F_{2}, \\String) \\\\\n       \\env_{1}[id \\mapsto \\phi(F_{1},F_{t})], \\penv \\vdash s_{1}, \\env_{2}\\\\\n       \\env_{1}[id \\mapsto \\phi(F_{1},F_{e})], \\penv \\vdash s_{2}, \\env_{3}\\\\\n       \\env_{4} = join(\\env_{2}, \\env_{3})\n      \\end{array}}\n      {\\env_{1}, \\penv \\vdash \\mathbf{if} \\; type(id) == ``string\" \\; \\mathbf{then} \\; s_{1} \\; \\mathbf{else} \\; s_{2}, \\env_{4}[id \\mapsto F_{1}]}\n\\]\n\n\\mylabel{T-IF9}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}(id) = \\phi(F_{1},F_{2}) \\;\\;\\;\n       F_{t} = fit(F_{2}, \\String) \\;\\;\\;\n       F_{e} = fot(F_{2}, \\String) \\\\\n       F_{t} = \\Void \\;\\;\\;\n       \\env_{1}[id \\mapsto \\phi(F_{1},F_{e})], \\penv \\vdash s_{2}, \\env_{2}\n      \\end{array}}\n      {\\env_{1}, \\penv \\vdash \\mathbf{if} \\; type(id) == ``string\" \\; \\mathbf{then} \\; s_{1} \\; \\mathbf{else} \\; s_{2}, \\env_{2}[id \\mapsto F_{1}]}\n\\]\n\n\\mylabel{T-IF10}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}(id) = \\phi(F_{1},F_{2}) \\;\\;\\;\n       F_{t} = fit(F_{2}, \\String) \\;\\;\\;\n       F_{e} = fot(F_{2}, \\String) \\\\\n       F_{e} = \\Void \\;\\;\\;\n       \\env_{1}[id \\mapsto \\phi(F_{1},F_{t})], \\penv \\vdash s_{1}, \\env_{2}\n      \\end{array}}\n      {\\env_{1}, \\penv \\vdash \\mathbf{if} \\; type(id) == ``string\" \\; \\mathbf{then} \\; s_{1} \\; \\mathbf{else} \\; s_{2}, \\env_{2}[id \\mapsto F_{1}]}\n\\]\n\n\\mylabel{T-LOCAL1}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}, \\penv \\vdash el:S, \\env_{2} \\\\\n       S \\lesssim F_{1} \\times ... \\times F_{n} \\times \\Value{*} \\;\\;\\;\n       n = |\\;\\overline{id{:}F}\\;| \\\\\n       \\env_{2}[\\overline{id \\mapsto F}], \\penv \\vdash s, \\env_{3}\n       \\end{array}}\n      {\\env_{1}, \\penv \\vdash \\mathbf{local} \\; \\overline{id{:}F} = el \\; \\mathbf{in} \\; s, (\\env_{3} - \\{\\overline{id}\\})[\\overline{id \\mapsto \\env_{2}(id)]}}\n\\]\n\n\\mylabel{T-LOCAL2}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}, \\penv \\vdash el:E, \\env_{2}, (x,S) \\\\\n       \\env_{3} = \\env_{2}[id_{1} \\mapsto infer(E,1), ..., id_{n} \\mapsto infer(E,n)] \\\\\n       \\env_{3}, \\penv[x \\mapsto S] \\vdash s, \\env_{4} \\;\\;\\;\n       n = |\\;\\overline{id}\\;|\n       \\end{array}}\n      {\\env_{1}, \\penv \\vdash \\mathbf{local} \\; \\overline{id} = el \\; \\mathbf{in} \\; s, (\\env_{4} - \\{\\overline{id}\\})[\\overline{id \\mapsto \\env_{2}(id)]}}\n\\]\n\n\\mylabel{T-LOCALREC}\n\\[\n\\dfrac{\\env_{1}[id \\mapsto F], \\penv \\vdash e:F_{1}, \\env_{2} \\;\\;\\;\n       F_{1} \\lesssim F \\;\\;\\;\n       \\env_{2}, \\penv \\vdash s, \\env_{3}}\n      {\\env_{1}, \\penv \\vdash \\mathbf{rec} \\; id{:}F = e \\; \\mathbf{in} \\; s, (\\env_{3} - \\{id\\})[\\overline{id \\mapsto \\env_{2}(id)]}}\n\\]\n\n\\mylabel{T-RETURN}\n\\[\n\\dfrac{\\env_{1} \\vdash el:S_{1}, \\env_{2} \\;\\;\\;\n       \\penv(\\ret) = S_{2} \\;\\;\\;\n       S_{1} \\lesssim S_{2}}\n      {\\env_{1} \\vdash \\mathbf{return} \\; el, \\env_{2}}\n\\]\n\n\\mylabel{T-STMAPPLY1}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e(el):S, \\env_{2}}\n      {\\env_{1}, \\penv \\vdash \\lfloor e(el) \\rfloor_{0},\\env_{2}}\n\\]\n\n\\mylabel{T-STMINVOKE1}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e{:}n(el):S, \\env_{2}}\n      {\\env_{1}, \\penv \\vdash \\lfloor e{:}n(el) \\rfloor_{0}, \\env_{2}}\n\\]\n\n\\mylabel{T-NIL}\n\\[\n\\env_{1}, \\penv \\vdash \\mathbf{nil}:\\Nil, \\env_{1}\n\\]\n\n\\mylabel{T-FALSE}\n\\[\n\\env_{1}, \\penv \\vdash \\mathbf{false}:\\False, \\env_{1}\n\\]\n\n\\mylabel{T-TRUE}\n\\[\n\\env_{1}, \\penv \\vdash \\mathbf{true}:\\True, \\env_{1}\n\\]\n\n\\mylabel{T-INT}\n\\[\n\\env_{1}, \\penv \\vdash {\\it int}:{\\it int}, \\env_{1}\n\\]\n\n\\mylabel{T-FLOAT}\n\\[\n\\env_{1}, \\penv \\vdash {\\it float}:{\\it float}, \\env_{1}\n\\]\n\n\\mylabel{T-STR}\n\\[\n\\env_{1}, \\penv \\vdash {\\it string}:{\\it string}, \\env_{1}\n\\]\n\n\\mylabel{T-IDREAD1}\n\\[\n\\dfrac{\\env_{1}(id) = F}\n      {\\env_{1}, \\penv \\vdash id:close(F), \\env_{1}[id \\mapsto open(F)]}\n\\]\n\n\\mylabel{T-IDREAD2}\n\\[\n\\dfrac{\\env_{1}(id) = F}\n      {\\env_{1}, \\penv \\vdash id:fix(F), \\env_{1}[id \\mapsto fix(F)]}\n\\]\n\n\\mylabel{T-IDREAD3}\n\\[\n\\dfrac{\\env_{1}(id) = \\phi(F_{1},F_{2})}\n      {\\env_{1}, \\penv \\vdash id:F_{2}, \\env_{1}}\n\\]\n\n\\mylabel{T-IDREAD4}\n\\[\n\\dfrac{\\env_{1}(id) = \\pi_{i}^{x}}\n      {\\env_{1}, \\penv \\vdash id:proj(\\penv(x), i), \\env_{1}}\n\\]\n\n\\mylabel{T-INDEXREAD1}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}(id) = \\{\\overline{F{:}V}\\} \\;\\;\\;\n       \\env_{1}, \\penv \\vdash e_{2}:F, \\env_{2} \\;\\;\\;\n       \\exists i \\in 1{..}n \\; F \\lesssim F_{i} \\;\\;\\;\n       n = |\\overline{F{:}V}|\n       \\end{array}}\n      {\\env_{1}, \\penv \\vdash id[e_{2}]:rconst(V_{i}), \\env_{2}}\n\\]\n\n\\mylabel{T-INDEXREAD2}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}, \\penv \\vdash e_{1}:\\{\\overline{F{:}V}\\}, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash e_{2}:F, \\env_{3} \\;\\;\\;\n       \\exists i \\in 1{..}n \\; F \\lesssim F_{i} \\;\\;\\;\n       n = |\\overline{F{:}V}|\n       \\end{array}}\n      {\\env_{1}, \\penv \\vdash e_{1}[e_{2}]:rconst(V_{i}), \\env_{3}}\n\\]\n\n\\mylabel{T-INDEXREAD3}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{1}:\\Any, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash e_{2}:F, \\env_{3}}\n      {\\env_{1}, \\penv \\vdash e_{1}[e_{2}]:\\Any, \\env_{3}}\n\\]\n\n\\mylabel{T-COERCE1}\n\\[\n\\dfrac{\\env_{1}(id) \\subtype F \\;\\;\\; tag(F,closed)}\n      {\\env_{1}, \\penv \\vdash {<}F{>} \\; id:F, \\env_{1}[id \\mapsto reopen(F)]}\n\\]\n\n\\mylabel{T-COERCE2}\n\\[\n\\dfrac{\\env_{1}(id) \\subtype F \\;\\;\\; tag(F,fixed)}\n      {\\env_{1}, \\penv \\vdash {<}F{>} \\; id:F, \\env_{1}[id \\mapsto F]}\n\\]\n\n\\mylabel{T-FUNCTION1}\n\\[\n\\dfrac{\\begin{array}{c}\n       closeall(\\env_{1})[\\overline{id \\mapsto F}], \\penv[\\ret \\mapsto S] \\vdash s, \\env_{2} \\\\\n       \\env_{3} = openset(\\env_{1}, frv(\\mathbf{fun} \\; (\\overline{id{:}F}){:}S \\; s)) \\\\\n       \\env_{4} = closeset(\\env_{3}, fav(\\mathbf{fun} \\; (\\overline{id{:}F}){:}S \\; s))\n       \\end{array}}\n      {\\env_{1}, \\penv \\vdash \\mathbf{fun} \\; (\\overline{id{:}F}){:}S \\; s:F_{1} \\times ... \\times F_{n} \\times \\Nil{*} \\rightarrow S, \\env_{4}}\n\\]\n\n\\mylabel{T-FUNCTION2}\n\\[\n\\dfrac{\\begin{array}{c}\n       closeall(\\env_{1})[\\overline{id \\mapsto F}, {...} \\mapsto F], \\penv[\\ret \\mapsto S] \\vdash s, \\env_{2} \\\\\n       \\env_{3} = openset(\\env_{1}, frv(\\mathbf{fun} \\; (\\overline{id{:}F}){:}S \\; s)) \\\\\n       \\env_{4} = closeset(\\env_{3}, fav(\\mathbf{fun} \\; (\\overline{id{:}F}){:}S \\; s))\n       \\end{array}}\n      {\\env_{1}, \\penv \\vdash \\mathbf{fun} \\; (\\overline{id{:}F},{...}{:}F){:}S \\; s:F_{1} \\times ... \\times F_{n} \\times F{*} \\rightarrow S, \\env_{4}}\n\\]\n\n\\mylabel{T-CONSTRUCTOR1}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}, \\penv \\vdash ([e_{1}] = e_{2})_{i}:(F_{i},V_{i}), \\env_{i+1} \\;\\;\\;\n       T = \\{F_{1}{:}V_{1}, ..., F_{n}{:}V_{n}\\}_{unique} \\\\\n       wf(T) \\;\\;\\;\n       n = |\\;\\overline{[e_{1}] = e_{2}}\\;| \\;\\;\\;\n       \\env_{f} = merge(\\env_{1}, ..., \\env_{n+1})\n       \\end{array}}\n      {\\env_{1}, \\penv \\vdash \\{\\;\\overline{[e_{1}] = e_{2}}\\;\\}:T, \\env_{f}}\n\\]\n\n\\mylabel{T-CONSTRUCTOR2}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}, \\penv \\vdash ([e_{1}] = e_{2})_{i}:(F_{i},V_{i}), \\env_{i+1} \\\\\n       \\env_{1}, \\penv \\vdash me : F_{n+1} \\times ... \\times F_{n+m} \\times F_{n+m+1}{*}, \\env_{n+2}\\\\\n       T = \\{F_{1}{:}V_{1}, ..., F_{n}{:}V_{n}, 1{:}F_{n+1}, ..., m{:}F_{n+m}, \\Integer{:}F_{n+m+1} \\cup \\Nil\\}_{unique}\\\\\n       wf(T) \\;\\;\\;\n       n = |\\;\\overline{[e_{1}] = e_{2}}\\;| \\;\\;\\;\n       \\env_{f} = merge(\\env_{1}, ..., \\env_{n+2})\n       \\end{array}}\n      {\\env_{1}, \\penv \\vdash \\{\\;\\overline{[e_{1}] = e_{2}}\\;\\}:T, \\env_{f}}\n\\]\n\n\\mylabel{T-FIELD}\\\\\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{2}:V, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash e_{1}:F, \\env_{3}}\n      {\\env_{1}, \\penv \\vdash [e_{1}] = e_{2}: (F,vt(F,V)), \\env_{3}}\n\\]\n\n\\mylabel{T-ARITH1}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{1}:F_{1}, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash e_{2}:F_{2}, \\env_{3} \\;\\;\\;\n       F_{1} \\subtype \\Integer \\;\\;\\;\n       F_{2} \\subtype \\Integer}\n      {\\env_{1}, \\penv \\vdash e_{1} + e_{2}:\\Integer, \\env_{3}}\n\\]\n\n\\mylabel{T-ARITH2}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{1}:F_{1}, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash e_{2}:F_{2}, \\env_{3} \\;\\;\\;\n       F_{1} \\subtype \\Integer \\;\\;\\;\n       F_{2} \\subtype \\Number}\n      {\\env_{1}, \\penv \\vdash e_{1} + e_{2}:\\Number, \\env_{3}}\n\\]\n\n\\mylabel{T-ARITH3}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{1}:F_{1}, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash e_{2}:F_{2}, \\env_{3} \\;\\;\\;\n       F_{1} \\subtype \\Number \\;\\;\\;\n       F_{2} \\subtype \\Integer}\n      {\\env_{1}, \\penv \\vdash e_{1} + e_{2}:\\Number, \\env_{3}}\n\\]\n\n\\mylabel{T-ARITH4}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{1}:F_{1}, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash e_{2}:F_{2}, \\env_{3} \\;\\;\\;\n       F_{1} \\subtype \\Number \\;\\;\\;\n       F_{2} \\subtype \\Number}\n      {\\env_{1}, \\penv \\vdash e_{1} + e_{2}:\\Number, \\env_{3}}\n\\]\n\n\\mylabel{T-ARITH5}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{1}:\\Any, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash e_{2}:F, \\env_{3}}\n      {\\env_{1}, \\penv \\vdash e_{1} + e_{2}:\\Any, \\env_{3}}\n\\]\n\n\\mylabel{T-ARITH6}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{1}:F, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash e_{2}:\\Any, \\env_{3}}\n      {\\env_{1}, \\penv \\vdash e_{1} + e_{2}:\\Any, \\env_{3}}\n\\]\n\n\\mylabel{T-CONCAT1}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{1}:F_{1}, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash e_{2}:F_{2}, \\env_{3} \\;\\;\\;\n       F_{1} \\subtype \\String \\;\\;\\;\n       F_{2} \\subtype \\String}\n      {\\env_{1}, \\penv \\vdash e_{1} \\; {..} \\; e_{2}:\\String, \\env_{3}}\n\\]\n\n\\mylabel{T-CONCAT2}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{1}:\\Any, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash e_{2}:F, \\env_{3}}\n      {\\env_{1}, \\penv \\vdash e_{1} \\; {..} \\; e_{2}:\\Any, \\env_{3}}\n\\]\n\n\\mylabel{T-CONCAT3}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{1}:F, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash e_{2}:\\Any, \\env_{3}}\n      {\\env_{1}, \\penv \\vdash e_{1} \\; {..} \\; e_{2}:\\Any, \\env_{3}}\n\\]\n\n\\mylabel{T-EQUAL}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{1}:F_{1}, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash e_{2}:F_{2}, \\env_{3}}\n      {\\env_{1}, \\penv \\vdash e_{1} == e_{2}:\\Boolean, \\env_{3}}\n\\]\n\n\\mylabel{T-ORDER1}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{1}:F_{1}, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash e_{2}:F_{2}, \\env_{3} \\;\\;\\;\n       F_{1} \\subtype \\Number \\;\\;\\;\n       F_{2} \\subtype \\Number}\n      {\\env, \\penv \\vdash e_{1} < e_{2}:\\Boolean, \\env_{3}}\n\\]\n\n\\mylabel{T-ORDER2}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{1}:F_{1}, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash e_{2}:F_{2}, \\env_{3} \\;\\;\\;\n       F_{1} \\subtype \\String \\;\\;\\;\n       F_{2} \\subtype \\String}\n      {\\env_{1}, \\penv \\vdash e_{1} < e_{2}:\\Boolean}\n\\]\n\n\\mylabel{T-ORDER3}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{1}:\\Any, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash e_{2}:F, \\env_{3}}\n      {\\env_{1}, \\penv \\vdash e_{1} < e_{2}:\\Any, \\env_{3}}\n\\]\n\n\\mylabel{T-ORDER4}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{1}:F, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash e_{2}:\\Any, \\env_{3}}\n      {\\env_{1}, \\penv \\vdash e_{1} < e_{2}:\\Any, \\env_{3}}\n\\]\n\n\\mylabel{T-BITWISE1}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{1}:F_{1}, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash e_{2}:F_{2}, \\env_{3} \\;\\;\\;\n       F_{1} \\subtype \\Integer \\;\\;\\;\n       F_{2} \\subtype \\Integer}\n      {\\env_{1}, \\penv \\vdash e_{1} \\;\\&\\; e_{2}:\\Integer, \\env_{3}}\n\\]\n\n\\mylabel{T-BITWISE2}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{1}:\\Any, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash e_{2}:F, \\env_{3}}\n      {\\env_{1}, \\penv \\vdash e_{1} \\;\\&\\; e_{2}:\\Any, \\env_{3}}\n\\]\n\n\\mylabel{T-BITWISE3}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{1}:F, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash e_{2}:\\Any, \\env_{3}}\n      {\\env_{1}, \\penv \\vdash e_{1} \\;\\&\\; e_{2}:\\Any, \\env_{3}}\n\\]\n\n\\mylabel{T-AND1}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{1}:\\Nil, \\env_{2}}\n      {\\env_{1}, \\penv \\vdash e_{1} \\; \\mathbf{and} \\; e_{2}:\\Nil, \\env_{2}}\n\\]\n\n\\mylabel{T-AND2}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{1}:\\False, \\env_{2}}\n      {\\env_{1}, \\penv \\vdash e_{1} \\; \\mathbf{and} \\; e_{2}:\\False, \\env_{2}}\n\\]\n\n\\mylabel{T-AND3}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{1}:\\Nil \\cup \\False, \\env_{2}}\n      {\\env_{1}, \\penv \\vdash e_{1} \\; \\mathbf{and} \\; e_{2}:\\Nil \\cup \\False, \\env_{2}}\n\\]\n\n\\mylabel{T-AND4}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{1}:F_{1}, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash e_{2}:F_{2}, \\env_{3} \\;\\;\\;\n       \\Nil \\not\\lesssim F_{1} \\;\\;\\;\n       \\False \\not\\lesssim F_{1}}\n      {\\env_{1}, \\penv \\vdash e_{1} \\; \\mathbf{and} \\; e_{2}:F_{2}, \\env_{3}}\n\\]\n\n\\mylabel{T-AND5}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{1}:F_{1}, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash e_{2}:F_{2}, \\env_{3}}\n      {\\env_{1}, \\penv \\vdash e_{1} \\; \\mathbf{and} \\; e_{2}:F_{1} \\cup F_{2}, \\env_{3}}\n\\]\n\n\\mylabel{T-OR1}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{1}:F, \\env_{2} \\;\\;\\;\n       \\Nil \\not\\lesssim F \\;\\;\\;\n       \\False \\not\\lesssim F}\n      {\\env_{1}, \\penv \\vdash e_{1} \\; \\mathbf{or} \\; e_{2}:F, \\env_{2}}\n\\]\n\n\\mylabel{T-OR2}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{1}:\\Nil, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash e_{2}:F, \\env_{3}}\n      {\\env_{1}, \\penv \\vdash e_{1} \\; \\mathbf{or} \\; e_{2}:F, \\env_{3}}\n\\]\n\n\\mylabel{T-OR3}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{1}:\\False, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash e_{2}:F, \\env_{3}}\n      {\\env_{1}, \\penv \\vdash e_{1} \\; \\mathbf{or} \\; e_{2}:F, \\env_{3}}\n\\]\n\n\\mylabel{T-OR4}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{1}:\\Nil \\cup \\False, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash e_{2}:F, \\env_{3}}\n      {\\env_{1}, \\penv \\vdash e_{1} \\; \\mathbf{or} \\; e_{2}:F, \\env_{3}}\n\\]\n\n\\mylabel{T-OR5}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{1}:F_{1}, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash e_{2}:F_{2}, \\env_{3}}\n      {\\env_{1}, \\penv \\vdash e_{1} \\; \\mathbf{or} \\; e_{2}:filter(filter(F_{1}, \\Nil), \\False) \\cup F_{2}, \\env_{3}}\n\\]\n\n\\mylabel{T-NOT1}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e:\\Nil, \\env_{2}}\n      {\\env_{1}, \\penv \\vdash \\mathbf{not} \\; e:\\True, \\env_{2}}\n\\]\n\n\\mylabel{T-NOT2}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e:\\False, \\env_{2}}\n      {\\env_{1}, \\penv \\vdash \\mathbf{not} \\; e:\\True, \\env_{2}}\n\\]\n\n\\mylabel{T-NOT3}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e:\\Nil \\cup \\False, \\env_{2}}\n      {\\env_{1}, \\penv \\vdash \\mathbf{not} \\; e:\\True, \\env_{2}}\n\\]\n\n\\mylabel{T-NOT4}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e:F \\;\\;\\;\n       \\Nil \\not\\lesssim F \\;\\;\\;\n       \\False \\not\\lesssim F}\n      {\\env_{1}, \\penv \\vdash \\mathbf{not} \\; e:\\False, \\env_{2}}\n\\]\n\n\\mylabel{T-NOT5}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e:F, \\env_{2}}\n      {\\env_{1}, \\penv \\vdash \\mathbf{not} \\; e:\\Boolean, \\env_{2}}\n\\]\n\n\\mylabel{T-LEN1}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e:F, \\env_{2} \\;\\;\\;\n       F \\subtype \\String}\n      {\\env_{1}, \\penv \\vdash \\# \\; e:\\Integer, \\env_{2}}\n\\]\n\n\\mylabel{T-LEN2}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e:F, \\env_{2} \\;\\;\\;\n       F \\subtype \\{\\}_{closed}}\n      {\\env_{1}, \\penv \\vdash \\# \\; e:\\Integer, \\env_{2}}\n\\]\n\n\\mylabel{T-LEN3}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e:\\Any, \\env_{2}}\n      {\\env_{1}, \\penv \\vdash \\# \\; e:\\Any, \\env_{2}}\n\\]\n\n\\mylabel{T-EXPAPPLY1}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e(el):S, \\env_{2}}\n      {\\env_{1}, \\penv \\vdash \\lfloor e(el) \\rfloor_{1}:proj(S,1), \\env_{2}}\n\\]\n\n\\mylabel{T-EXPINVOKE1}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e{:}n(el):S, \\env_{2}}\n      {\\env_{1}, \\penv \\vdash \\lfloor e{:}n(el) \\rfloor_{1}:proj(S,1), \\env_{2}}\n\\]\n\n\\mylabel{T-EXPDOTS}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash {...}:F{*}, \\env_{2}}\n      {\\env_{1}, \\penv \\vdash \\lfloor {...} \\rfloor_{1}:F \\cup \\Nil, \\env_{2}}\n\\]\n\n\\mylabel{T-IDWRITE1}\n\\[\n\\dfrac{\\env_{1}(id) = F}\n      {\\env_{1}, \\penv \\vdash id_{l}:F, \\env_{1}}\n\\]\n\n\\mylabel{T-IDWRITE2}\n\\[\n\\dfrac{\\env_{1}(id) = \\phi(F_{1},F_{2})}\n      {\\env_{1}, \\penv \\vdash id_{l}:F_{1}, \\env_{1}[id \\mapsto F_{1}]}\n\\]\n\n\\mylabel{T-INDEXWRITE1}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}, \\penv \\vdash e_{1}:\\{\\overline{F{:}V}\\}, \\env_{2} \\\\\n       \\env_{2}, \\penv \\vdash e_{2}:F, \\env_{3} \\;\\;\\;\n       \\exists i \\in 1{..}n \\; F \\lesssim F_{i} \\wedge \\neg const(V_{i}) \\;\\;\\;\n       n = |\\overline{F{:}V}|\n       \\end{array}}\n      {\\env_{1}, \\penv \\vdash e_{1}[e_{2}]_{l}:V_{i}, \\env_{3}}\n\\]\n\n\\mylabel{T-INDEXWRITE2}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{1}:\\Any, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash e_{2}:F, \\env_{3}}\n      {\\env_{1}, \\penv \\vdash e_{1}[e_{2}]_{l}:\\Any, \\env_{3}}\n\\]\n\n\\mylabel{T-REFINE1}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}(id) = \\{\\overline{F{:}V}\\}_{unique}\\\\\n       \\env_{1}, \\penv \\vdash e:F_{new}, \\env_{2} \\;\\;\\;\n       \\nexists i \\in 1..n \\; F_{new} \\lesssim F_{i} \\;\\;\\;\n       V_{new} = vt(F_{new},V) \\;\\;\\; n = |\\overline{F{:}V}|\n       \\end{array}}\n      {\\env_{1}, \\penv \\vdash id[e] {<}V{>}:V_{new}, \\env_{2}[id \\mapsto \\{\\overline{F{:}V}, F_{new}{:}V_{new}\\}_{unique}]}\n\\]\n\n\\mylabel{T-REFINE2}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}(id) = \\{\\overline{F{:}V}\\}_{open}\\\\\n       \\env_{1}, \\penv \\vdash e:F_{new}, \\env_{2} \\;\\;\\;\n       \\nexists i \\in 1..n \\; F_{new} \\lesssim F_{i} \\;\\;\\;\n       V_{new} = vt(F_{new},V) \\;\\;\\; n = |\\overline{F{:}V}|\n       \\end{array}}\n      {\\env_{1}, \\penv \\vdash id[e] {<}V{>}:V_{new}, \\env_{2}[id \\mapsto \\{\\overline{F{:}V}, F_{new}{:}V_{new}\\}_{open}]}\n\\]\n\n\\mylabel{T-LHSLIST}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash l_{i}:F_{i}, \\env_{i+1} \\;\\;\\;\n       \\env_{f} = merge(\\env_{1}, ..., \\env_{n+1}) \\;\\;\\;\n       n = |\\;\\overline{l}\\;|}\n      {\\env_{1}, \\penv \\vdash \\overline{l}:F_{1} \\times ... \\times F_{n} \\times \\Value{*}, \\env_{f}}\n\\]\n\n\\mylabel{T-EXPLIST1}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{i}:F_{i}, \\env_{i+1} \\;\\;\\;\n       \\env_{f} = merge(\\env_{1}, ..., \\env_{n+1}) \\;\\;\\;\n       n = |\\;\\overline{e}\\;|}\n      {\\env_{1}, \\penv \\vdash \\overline{e}:F_{1} \\times ... \\times F_{n} \\times \\Nil{*}, \\env_{f}}\n\\]\n\n\\mylabel{T-EXPLIST2}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}, \\penv \\vdash e_{i}:F_{i}, \\env_{i+1} \\;\\;\\;\n       \\env_{1}, \\penv \\vdash me:F_{n+1} \\times ... \\times F_{n+m} \\times F_{n+m+1}{*}, \\env_{n+2}\\\\\n       \\env_{f} = merge(\\env_{1}, ..., \\env_{n+2}) \\;\\;\\;\n       n = |\\;\\overline{e}\\;|\n       \\end{array}}\n      {\\env_{1}, \\penv \\vdash \\overline{e},me:F_{1} \\times ... \\times F_{n+m} \\times F_{n+m+1}{*}, \\env_{f}}\n\\]\n\n\\mylabel{T-EXPLIST3}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}, \\penv \\vdash e_{i}:F_{i}, \\env_{i+1} \\;\\;\\;\n       \\env_{1}, \\penv \\vdash me:S, \\env_{n+2}\\\\\n       S = F_{n+1} \\times ... \\times F_{n+m} \\times \\Nil{*} \\sqcup F_{n+1}' \\times ... \\times F_{n+m}' \\times \\Nil{*} \\\\\n       \\env_{f} = merge(\\env_{1}, ..., \\env_{n+2}) \\;\\;\\;\n       n = |\\;\\overline{e}\\;|\n       \\end{array}}\n      {\\env_{1}, \\penv \\vdash \\overline{e},me:F_{1} \\times ... \\times F_{n} \\times \\pi_{1}^{x} \\times ... \\times \\pi_{m}^{x} \\times \\Nil{*}, \\env_{f}, (x,S)}\n\\]\n\n\\mylabel{T-APPLY1}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e:S_{1} \\rightarrow S_{2}, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash el:S_{3}, \\env_{3} \\;\\;\\;\n       S_{3} \\lesssim S_{1}}\n      {\\env_{1}, \\penv \\vdash e(el):S_{2}, \\env_{3}}\n\\]\n\n\\mylabel{T-APPLY2}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e:\\Any, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash el:S, \\env_{3}}\n      {\\env_{1}, \\penv \\vdash e_{1}(el):\\Any{*}, \\env_{3}}\n\\]\n\n\\mylabel{T-INVOKE1}\n\\[\n\\dfrac{\\begin{array}{c}\n       \\env_{1}, \\penv \\vdash e:F, \\env_{2}\\\\\n       \\env_{2}[\\sigma \\mapsto F], \\penv \\vdash e[id]:\\Const \\; S_{1} \\rightarrow S_{2}, \\env_{3}\\\\\n       \\env_{3}[\\sigma \\mapsto F], \\penv \\vdash el:S_{3}, \\env_{4} \\;\\;\\;\n       F \\times S_{3} \\lesssim [\\Self \\mapsto F]S_{1}\n       \\end{array}}\n      {\\env_{1}, \\penv \\vdash e{:}id(el):[\\Self \\mapsto F]S_{2}, \\env_{4}}\n\\]\n\n\\mylabel{T-INVOKE2}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e:\\Any, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash el:S, \\env_{3}}\n      {\\env_{1}, \\penv \\vdash e{:}id(el):\\Any{*}, \\env_{3}}\n\\]\n\n\\mylabel{T-DOTS}\n\\[\n\\dfrac{\\env_{1}({...}) = F}\n      {\\env_{1}, \\penv \\vdash {...}:F{*}, \\env_{1}}\n\\]\n\n\\mylabel{T-SELF}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e:\\Self, \\env_{2} \\;\\;\\;\n       \\env_{2}(\\self) = F}\n      {\\env_{1}, \\penv \\vdash e:F, \\env_{2}}\n\\]\n\n\\mylabel{T-SETMETATABLE1}\n\\[\n\\dfrac{\\env_{1}(id) = \\Self}\n      {\\env_{1}, \\penv \\vdash setmetatable(\\{\\}, \\{[``\\string_\\string_index\"] = id\\}):\\Self, \\env_{1}}\n\\]\n\n\\mylabel{T-SETMETATABLE2}\n\\[\n\\dfrac{\\env_{1}(id) = \\{F_{1}{:}V_{1}, ..., F_{n}{:}V_{n}\\}_{fixed}}\n      {\\env_{1}, \\penv \\vdash setmetatable(\\{\\}, \\{[``\\string_\\string_index\"] = id\\}):\\{F_{1}{:}V_{1}, ..., F_{n}{:}V_{n}\\}_{open}, \\env_{1}}\n\\]\n\n\\mylabel{T-SETMETATABLE3}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e : T, \\env_{2} \\;\\;\\;\n       T = \\{F_{1}{:}V_{1}, ..., F_{n}{:}V_{n}\\}_{closed} \\;\\;\\;\n       \\env_{1}(id) = \\Self \\;\\;\\; \\env_{1}(\\sigma) \\subtype T}\n      {\\env_{1}, \\penv \\vdash setmetatable(e, \\{[``\\string_\\string_index\"] = id\\}):\\Self, \\env_{2}[\\sigma \\mapsto T]}\n\\]\n\n\\mylabel{T-UNFOLD}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e:\\mu x.F, \\env_{2}}\n      {\\env_{1}, \\penv \\vdash e:[x \\mapsto \\mu x.F]F, \\env_{2}}\n\\]\n\n\\mylabel{T-FOLD}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e:[x \\mapsto \\mu x.F]F, \\env_{2}}\n      {\\env_{1}, \\penv \\vdash e:\\mu x.F, \\env_{2}}\n\\]\n\n\\mylabel{T-TERNARY}\n\\[\n\\dfrac{\\env_{1}, \\penv \\vdash e_{1}:F_{1}, \\env_{2} \\;\\;\\;\n       \\env_{2}, \\penv \\vdash e_{2}:F_{2}, \\env_{3} \\;\\;\\;\n       \\env_{3}, \\penv \\vdash e_{3}:F_{2}, \\env_{4}}\n      {\\env_{1}, \\penv \\vdash e_{1} \\; \\mathbf{and} \\; e_{2} \\; \\mathbf{or} \\; e_{3}:F_{2}, \\env_{4}}\n\\]\n\n\\section{Auxiliary functions}\n\n\\noindent\n\n\\begin{align*}\nwf(\\{\\overline{F:V}\\}_{unique|open|fixed|closed}) & = \\forall i \\; ((\\nexists j \\; i \\not= j \\,\\wedge\\, F_{i} \\lesssim F_{j}) \\,\\wedge\\, wf(V_{i}) \\,\\wedge\\\\\n& \\;\\;\\;\\; \\lnot tag(V_{i},unique) \\,\\wedge\\, \\lnot tag(V_{i},open))\\\\\nwf({\\bf const}\\; F) & = wf(F) \\\\\nwf(F_1 \\cup F_2) & = wf(F_1) \\,\\wedge\\, wf(F_2) \\\\\nwf(\\mu x.F) & = wf(F) \\\\\nwf(S_1 \\rightarrow S_2) & = wf(S_1) \\,\\wedge\\, wf(S_2) \\\\\nwf(S_1 \\sqcup S_2) & = wf(S_1) \\,\\wedge\\, wf(S_2)\\\\\nwf(F{*}) & = wf(F) \\\\\nwf(F \\times P) & = wf(F) \\,\\wedge\\,wf(P)\\\\\nwf(F) & = \\top \\;\\;\\;\\mathrm{for\\; all\\; other\\; cases}\n\\end{align*}\n\n\\begin{align*}\ntag(F_1 \\cup F_2, t) & = tag(F_1, t) \\,\\vee\\, tag(F_2,t) \\\\\ntag(\\{\\overline{F{:}V}\\}_{t}, t) & = \\top\\\\\ntag(\\{\\overline{F{:}V}\\}_{t_{1}}, t_{2}) & = \\bot\\\\\ntag(F, t) & = \\bot\n\\end{align*}\n\n\\begin{align*}\nvt(L, V) & = fix(V) \\\\\nvt(F_1, F_2) & = nil(fix(F_2))\\\\\nvt(F_1, {\\bf const}\\;F_2) & = {\\bf const}\\;nil(fix(F_2))\n\\end{align*}\n\n\\begin{align*}\nnil(T) & = \\left\\{\n\\begin{array}{ll}\nT & \\text{if $\\Nil \\lesssim T$} \\\\\nT \\cup \\Nil & \\text{otherwise}\n\\end{array} \\right.\n\\end{align*}\n\n\\begin{align*}\nfix(F_{1} \\cup F_{2}) & = fix(F_{1}) \\cup fix(F_{2})\\\\\nfix(\\{\\overline{F{:}V}\\}_{unique|open}) & = \\{\\overline{F{:}V}\\}_{fixed} \\\\\nfix(F) & = F\n\\end{align*}\n\n\\begin{align*}\nclose(F_{1} \\cup F_{2}) & = close(F_{1}) \\cup close(F_{2})\\\\\nclose(\\{\\overline{F{:}V}\\}_{unique|open}) & = \\{\\overline{F{:}V}\\}_{closed} \\\\\nclose(F) & = F\n\\end{align*}\n\n\\begin{align*}\nopen(F_{1} \\cup F_{2}) & = open(F_{1}) \\cup open(F_{2})\\\\\nopen(\\{\\overline{F{:}V}\\}_{unique}) & = \\{\\overline{F{:}V}\\}_{open} \\\\\nopen(F) & = F\n\\end{align*}\n\n\\begin{align*}\nreopen(\\{\\overline{F:V}\\}_{closed}) & = \\{\\overline{F:V}\\}_{open}\\\\\nreopen(F) & = F\n\\end{align*}\n\n\\begin{align*}\nrconst({\\bf const}\\;F) & = F\\\\\nrconst(F) & = F\n\\end{align*}\n\n\\begin{align*}\nconst({\\bf const}\\;F) & = \\top\\\\\nconst(F) & = \\bot\n\\end{align*}\n\n\\begin{align*}\nproj(S_1 \\sqcup S_2, i) & = proj(S_1, i) \\cup proj(S_2, i) \\\\\nproj(F{*}, i) & = nil(F) \\\\\nproj(F \\times P, 1) & = F \\\\\nproj(F \\times P, i) & = proj(P, i-1)\\\\\nproj(E{*}, i) & = nil(E) \\\\\nproj(T \\times E, 1) & = T \\\\\nproj(T \\times E, i) & = proj(E, i-1)\n\\end{align*}\n\n\\begin{align*}\ninfer(T_{1} \\times ... \\times T_{n}{*}, i) & = \\left\\{\n\\begin{array}{ll}\ngeneral(T_{i}) & \\text{if $i < n$}\\\\\ngeneral(nil(T_{n})) & \\text{if $i >= n$}\n\\end{array} \\right.\n\\end{align*}\n\n\\begin{align*}\ngeneral(\\False) & = \\Boolean\\\\\ngeneral(\\True) & = \\Boolean\\\\\ngeneral({\\it int}) & = \\Integer\\\\\ngeneral({\\it float}) & = \\Number\\\\\ngeneral({\\it string}) & = \\String\\\\\ngeneral(F_{1} \\cup F_{2}) & = general(F_{1}) \\cup general(F_{2})\\\\\ngeneral(S_{1} \\rightarrow S_{2}) & = general2(S_{1}) \\rightarrow general2(S_{2})\\\\\ngeneral(\\{F_{1}{:}V_{1}, ..., F_{n}{:}V_{n}\\}_{tag}) & = \\{F_{1}{:}general(V_{1}), ..., F_{n}{:}general(V_{n})\\}_{tag}\\\\\ngeneral(\\mu x.F) & = \\mu x.general(F)\\\\\ngeneral(T) & = T\n\\end{align*}\n\n\\begin{align*}\ngeneral2(F{*}) & = general(F){*}\\\\\ngeneral2(F \\times P) & = general(F) \\times general2(P)\\\\\ngeneral2(S_{1} \\sqcup S_{2}) & = general2(S_{1}) \\sqcup general2(S_{2})\n\\end{align*}\n\n\\begin{align*}\ncloseall(\\env[id_{1} \\mapsto T_{1}, ..., id_{n} \\mapsto T_{n}]) & = \\env[id_{1} \\mapsto close(T_{1}), ..., id_{n} \\mapsto close(T_{n})]\n\\end{align*}\n\n\\begin{align*}\ncloseset(\\env, \\{id_{1}, ..., id_{n}\\}) & = \\env[id_{1} \\mapsto close(\\env(id_{1})), ..., id_{n} \\mapsto close(\\env(id_{n}))]\n\\end{align*}\n\n\\begin{align*}\nopenset(\\env, \\{id_{1}, ..., id_{n}\\}) & = \\env[id_{1} \\mapsto open(\\env(id_{1})), ..., id_{n} \\mapsto open(\\env(id_{n}))]\n\\end{align*}\n\n\\begin{align*}\nmerge(\\overline{\\env}) & = reduce(\\overline{\\env}, merge2)\\\\\nmerge2(\\env_1,\\env_2) & = \\{\\overline{(id,merget(\\env_1(id),\\env_2(id))}\\}\\\\\nmerget(T_1, T_2) & = T_1 \\;\\;\\; \\mathrm{if\\;} T_2 \\lesssim T_1\\\\\nmerget(T_1, T_2) & = T_2 \\;\\;\\; \\mathrm{if\\;} T_1 \\lesssim T_2\\\\\n& \\;\\;\\;\\;\\; \\mathrm{the\\;next\\;case\\;applies\\;if} \\\\\n& \\;\\;\\;\\;\\; \\overline{V^l \\lesssim_u V_r \\,\\vee\\, V^r \\lesssim_u V_l}\\\\\n& \\;\\;\\;\\;\\; \\mathrm{and\\;the\\;right\\; side\\; is\\;}wf\\\\\nmerget(\\{\\overline{F:V^l},\\overline{F^{\\prime}:V^\\prime}\\}_{unique},\\\\\n\\{\\overline{F:V^r},\\overline{F^{\\prime\\prime}:V^{\\prime\\prime}}\\}_{unique}) & =\n\\{\\overline{F:sup_u(V^l,V^r)},\\\\\n& \\;\\;\\;\\;\\;\\; \\overline{F^\\prime:V^\\prime},\\\\\n& \\;\\;\\;\\;\\;\\; \\overline{F^{\\prime\\prime}:V^{\\prime\\prime}}\\}_{unique}\\\\\n& \\;\\;\\;\\;\\; \\mathrm{the\\;next\\;case\\;applies\\;if} \\\\\n& \\;\\;\\;\\;\\; \\overline{V^l \\lesssim_c V_r \\,\\vee\\, V^r \\lesssim_c V_l}\\\\\n& \\;\\;\\;\\;\\; \\mathrm{and\\;the\\;right\\; side\\; is\\;}wf\\\\\nmerget(\\{\\overline{F:V^l},\\overline{F^{\\prime}:V^{\\prime}}\\}_{unique|open},\\\\\n\\{\\overline{F:V^r},\\overline{F^{\\prime\\prime}:V^{\\prime\\prime}}\\}_{unique|open}) & =\n\\{\\overline{F:sup_c(V^l,V^r)},\\\\\n& \\;\\;\\;\\;\\;\\; \\overline{F^\\prime:V^\\prime},\\\\\n& \\;\\;\\;\\;\\;\\; \\overline{F^{\\prime\\prime}:V^{\\prime\\prime}}\\}_{open}\\\\\nmerget(T_1, T_2) & = \\bot \\;\\;\\; \\mathrm{otherwise}\n\\end{align*}\n\n\\begin{align*}\nsup_u(V_1, V_2) & = V_2 \\;\\;\\; \\mathrm{if}\\; V_1 \\lesssim_u V_2\\\\\nsup_u(V_1, V_2) & = V_1 \\;\\;\\; \\mathrm{if}\\; V_2 \\lesssim_u V_1\n\\end{align*}\n\n\\begin{align*}\nsup_c(V_1, V_2) & = V_2 \\;\\;\\; \\mathrm{if}\\; V_1 \\lesssim_c V_2\\\\\nsup_c(V_1, V_2) & = V_1 \\;\\;\\; \\mathrm{if}\\; V_2 \\lesssim_c V_1\n\\end{align*}\n\n\\begin{align*}\njoin(\\env_1,\\env_2) & = \\{\\overline{(id,joint(\\env_1(id),\\env_2(id))}\\}\\\\\njoint(T_1, T_2) & = T_1 \\;\\;\\; \\mathrm{if\\;} T_2 \\lesssim T_1\\\\\njoint(T_1, T_2) & = T_2 \\;\\;\\; \\mathrm{if\\;} T_1 \\lesssim T_2\\\\\n& \\;\\;\\;\\;\\; \\mathrm{the\\;next\\;case\\;applies\\;if}\\; \\\\\n& \\;\\;\\;\\;\\; \\overline{V^l \\lesssim_u V_r \\,\\vee\\, V^r \\lesssim_u V_l}\\\\\n& \\;\\;\\;\\;\\; \\mathrm{and\\;the\\;right\\; side\\; is\\;}wf\\\\\njoint(\\{\\overline{F:V^l},\\overline{F^{\\prime}:V^{\\prime}}\\}_{unique},\n\\{\\overline{F:V^r},\\overline{F^{\\prime\\prime}:V^{\\prime\\prime}}\\}_{unique}) & =\n\\{\\overline{F:sup_u(V^l,V^r)},\\\\\n& \\;\\;\\;\\;\\;\\; \\overline{F^\\prime:nil(V^\\prime)},\\\\\n& \\;\\;\\;\\;\\;\\; \\overline{F^{\\prime\\prime}:nil(V^{\\prime\\prime})}\\}_{unique}\\\\\njoint(T_1, T_2) & = \\bot \\;\\;\\; \\mathrm{otherwise}\n\\end{align*}\n\n\\begin{align*}\nfilter(F_{1} \\cup F_{2}, F_{1}) & = filter(F_{2}, F_{1})\\\\\nfilter(F_{1} \\cup F_{2}, F_{2}) & = filter(F_{1}, F_{2})\\\\\nfilter(F_{1} \\cup F_{2}, F_{3}) & = filter(F_{1}, F_{3}) \\cup filter(F_{2}, F_{3})\\\\\nfilter(F_{1}, F_{2}) & = F_{1}\n\\end{align*}\n\n\\begin{align*}\nfopt(P_1 \\sqcup P_2, F, i) & = P_2 & \\mathrm{if} \\; fot(proj(P_1, i),F) = {\\bf void} \\\\\nfopt(P_1 \\sqcup P_2, F, i) & = P_1 & \\mathrm{if} \\; fot(proj(P_2, i),F) = {\\bf void} \\\\\nfopt(P_1 \\sqcup P_2, F, i) & = P_1 \\sqcup P_2 & \\mathrm{otherwise}\\\\\nfopt(P \\sqcup S, F, i) & = fopt(S,F,i) & \\mathrm{if} \\; fot(proj(P, i),F) = {\\bf void} \\\\\nfopt(P \\sqcup S, F, i) & = P \\sqcup fopt(S,F,i) & \\mathrm{otherwise}\\\\\nfopt(S \\sqcup P_2, F, i) & = fopt(S,F,i) & \\mathrm{if} \\; fot(proj(P, i),F) = {\\bf void} \\\\\nfopt(S \\sqcup P, F, i) & = fopt(S,F,i) \\sqcup P & \\mathrm{otherwise}\\\\\nfopt(S_1 \\sqcup S_2, F, i) & = fopt(S_1,F,i) \\sqcup fopt(S_2,F,i)\n\\end{align*}\n\n\\begin{align*}\nfot(F_1 \\cup F_2,F_3) & = fot(F_1,F_3) & \\mathrm{if}\\;fot(F_2,F_3) = {\\bf void}\\\\\nfot(F_1 \\cup F_2,F_3) & = fot(F_2,F_3) & \\mathrm{if}\\;fot(F_1,F_3) = {\\bf void}\\\\\nfot(F_1 \\cup F_2,F_3) & = fot(F_1,F_3) \\cup fot(F_2,F_3) & \\mathrm{otherwise}\\\\\nfot(F_1,F_2) & = {\\bf void} & \\mathrm{if} \\; F_1 \\subtype F_2 \\; \\mathrm{and} \\; F_2 \\subtype F_1\\\\\nfot(F_1,F_2) & = F_1 & \\mathrm{otherwise}\n\\end{align*}\n\n\\begin{align*}\nfipt(P_1 \\sqcup P_2, F, i) & = P_2 & \\mathrm{if} \\; fit(proj(P_1, i),F) = {\\bf void} \\\\\nfipt(P_1 \\sqcup P_2, F, i) & = P_1 & \\mathrm{if} \\; fit(proj(P_2, i),F) = {\\bf void} \\\\\nfipt(P_1 \\sqcup P_2, F, i) & = P_1 \\sqcup P_2 & \\mathrm{otherwise}\\\\\nfipt(P \\sqcup S, F, i) & = fipt(S,F,i) & \\mathrm{if} \\; fit(proj(P, i),F) = {\\bf void} \\\\\nfipt(P \\sqcup S, F, i) & = P \\sqcup fipt(S,F,i) & \\mathrm{otherwise}\\\\\nfipt(S \\sqcup P_2, F, i) & = fipt(S,F,i) & \\mathrm{if} \\; fit(proj(P, i),F) = {\\bf void} \\\\\nfipt(S \\sqcup P, F, i) & = fipt(S,F,i) \\sqcup P & \\mathrm{otherwise}\\\\\nfipt(S_1 \\sqcup S_2, F, i) & = fipt(S_1,F,i) \\sqcup fipt(S_2,F,i)\n\\end{align*}\n\n\\begin{align*}\nfit(F_1 \\cup F_2,F_3) & = fit(F_1,F_3) & \\mathrm{if}\\;fit(F_2,F_3) = {\\bf void}\\\\\nfit(F_1 \\cup F_2,F_3) & = fit(F_2,F_3) & \\mathrm{if}\\;fit(F_1,F_3) = {\\bf void}\\\\\nfit(F_1 \\cup F_2,F_3) & = fit(F_1,F_3) \\cup fit(F_2,F_3) & \\mathrm{otherwise}\\\\\nfit(F_1,F_2) & = F_1 & \\mathrm{if} \\; F_1 \\subtype F_2 \\; \\mathrm{and} \\; F_2 \\subtype F_1\\\\\nfit(F_1,F_2) & = {\\bf void} & \\mathrm{otherwise}\n\\end{align*}\n\n\n", "meta": {"hexsha": "27f425ef2691f727995996922656997cbf0122ef", "size": 49254, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/thesis/rules.tex", "max_stars_repo_name": "andremm/typedlua", "max_stars_repo_head_hexsha": "2ff68c56668da62b0fa8e7256f70f3ca1475586a", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": 486, "max_stars_repo_stars_event_min_datetime": "2015-01-17T00:51:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:31:14.000Z", "max_issues_repo_path": "doc/thesis/rules.tex", "max_issues_repo_name": "drinkwithwater/typedlua", "max_issues_repo_head_hexsha": "b0cb071644c1a23b7963564a9cb77b3d5ee4daa7", "max_issues_repo_licenses": ["MIT", "Unlicense"], "max_issues_count": 93, "max_issues_repo_issues_event_min_datetime": "2015-01-02T02:30:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-07T12:49:53.000Z", "max_forks_repo_path": "doc/thesis/rules.tex", "max_forks_repo_name": "drinkwithwater/typedlua", "max_forks_repo_head_hexsha": "b0cb071644c1a23b7963564a9cb77b3d5ee4daa7", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": 60, "max_forks_repo_forks_event_min_datetime": "2015-01-20T06:08:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T07:36:49.000Z", "avg_line_length": 32.297704918, "max_line_length": 159, "alphanum_fraction": 0.5060705729, "num_tokens": 21995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.3057260459468708}}
{"text": "\\section{Methods for monocular reconstruction of articulated subjects}\n\n    Having discussed methods for modelling articulated subjects, this section will discuss approaches for reconstructing the 3D shape and pose of a subject from a monocular image or video. It is important to note that this task is challenging and fundamentally ill-posed. In common with other challenging 3D reconstruction tasks, input images will typically exhibit variation in camera view, lighting and environmental occlusion. However, 3D reconstruction pipelines for articulated subjects must also deal with variation due to body shape, body pose, clothing and self-occlusion (body parts obscuring other parts). In addition, the challenge of reconstructing 3D models from 2D images is also inherently ambiguous. As explained by Toshev and Szegedy~\\cite{toshev2014deeppose}, even if 2D structure can be determined (for example, using 2D keypoint prediction), the subsequent `lifting' step to recover 3D remains ill-posed, as the space of consistent 3D poses for given 2D landmark locations is infinite. It is for this reason that the history of monocular 3D reconstruction makes extensive use of 3D morphable models (or other geometric, temporal, structural priors), as they provide necessary optimization contraints.\n\n    The theme of this section is therefore to discuss how 3D morphable models (3DMMs) can be incoporated into 3D reconstruction pipelines. In general, algorithms take as input an image or video and predict a set of 3D model parameters $\\alpha$ (often factored into shape $\\shape$ and pose $\\pose$). Once determined, the output parameters are then supplied to the morphable model's generator function $g: \\alpha \\mapsto \\R{3}$ (e.g. $\\SMPL: (\\shape, \\pose) \\mapsto \\R{3}$ or $\\SMAL: (\\shape, \\pose) \\mapsto \\R{3}$) to produce vertex positions $V \\subseteq \\R{3}$ for the model $M = (V, T)$ with fixed triangulation $T$. For completeness and comparison, this section will make some mention of the small class of 3D reconstruction methods for articulated subjets which operate without an explicit 3D morphable model. Although currently a developing area, current work in this category typically requires either paired 3D training data, employ alternative (and arguably more restrictive) shape priors (e.g. symmetry constraints) or produce results of significantly lower fidelity.\n\n    Methods which align a parametric 3D model to monocular input date back as far as 1963, in a seminal paper by Roberts~\\cite{xxx}. Roberts presents a method which optimizes parameters for viewpoint and cuboidal shape primitives to reconstruct a 2D line image. Model-based methods have also been applied to understand object structure, starting with fitting of geometric primitives~\\cite{xxx} and later with Active Shape Models~\\cite{xxx} which learn deformation priors from a provided training set. Perhaps due to the numerous commercial applications, the majority of recent work in 3D shape and pose recovery focuses particuarly on \\emph{humans} as a special case. The first example of such an approach is the seminal work of Blanz and Vetter~\\cite{blanz-vetter} who built the first 3D morphable face model by aligning 3D scans and optimized the parameters to provide a fit to a single image. Since then, the research community has collected a multitude of open source human datasets which provide strong supervisory signals for training deep neural networks. These include include accurate 3D deformable template models~\\cite{loper15smpl} generated from real human scans, 3D motion capture datasets~\\cite{ionescu2013human3,vonmarcard2018recovering} and large 2D datasets~\\cite{lin2014microsoft,johnson2010clustered,andriluka14cvpr} which provide keypoint and silhouette annotations. The combination of these publically available datasets and their incoporation into deep learning pipelines have led to impressive reconstruction results when tested on in-the-wild human images and videos. Unfortunately, the diversity among animal subjects and the practical challenges associated with data capture have resulted in few datasets being made available. Despite appearing superficially similar to human tracking, these factors result in specific challenges to animal tracking which must be carefully handled. Perhaps for this reason, the body of related literature for animal tracking is considerably sparser. The remainder of this section will focus on methods for 3D pose estimation, followed by 3D shape and pose reconstruction of human and animal bodies. Further discussion on techniques for body part (e.g. face, hands) reconstruction are deferred to the following survey papers~\\cite{xxx, xxx}.\n\n\\subsection{3D Pose Estimation}\n\n% The reconstruction of an arbitrary configuration of 3D points from a single monocular RGB image has three characteristics that affect its performance: (i) it is a severely ill-posed problem because similar image projections can be derived from different 3D poses; (ii) it is an ill-conditioned problem since minor errors in the loca- tions of the 2D body joints can have large consequences in the 3D space; and (iii) it suffers from high dimensionality ( Agarwal and Triggs, 2006 ).\n\n    Techniques for 3D pose estimation output a set of 3D keypoint locations which can be combined to form a skeletal outline. Apart from basic limb measurements, no other shape detail (e.g. surface definition, object density etc.) is obtained. However, it should be noted that this output form is often perfectly satisfactory depending on the intended application. In particular, this family of techniques have found numerous applications in controllerless gaming (e.g. Microsoft Kinect~\\cite{kinectpaper}), motion capture (e.g. for digital character generation~\\cite{xxx}), gait analysis (e.g. identifying lameness in cattle~\\cite{xxx}) and many more. \n    \n    The general approach is to recover a 3D skeleton such that the 3D joints project to known or estimated 2D joints subject to anatomical priors. Early approaches in this category fit human stick figures with various constraints, including assumptions of fixed limb lengths~\\cite{xxx}, length ratios~\\cite{xxx} or that limb lengths are isometric across individuals and vary only in global scaling~\\cite{xxx}. More advanced techniques built statistical models of shape variation using anthropometric tables or learnt them from motion capture data~\\cite{barron2001estimating}.\n\n    A broad category of appraoches for this are methods for \\emph{non-rigid structure from motion}~\\cite{xxx}. The general formulation is to express a 3D skeleton $S \\in \\RR{3}{P}$ on $P$ points as a linear combination of basis shapes $S_{1}, \\dots, S_{k}$ where $S_{i} \\in \\RR{3}{P}$. Precisely:\n    \n    \\begin{equation}\n        S = \\sum_{i=1}^K l_{i} \\cdot S_{i} \\quad S, S_{i} \\in \\RR{3}{P} \\quad l_{i} \\in \\R{}\n    \\end{equation}\n    \n    Assuming scaled orthographic projection, the following expression represents the projection of $P$ points of $S$ into 2D image coordinates $(u_{i}, v_{i})$:\n    \n    \\begin{equation}\n        \\begin{bmatrix}\n            u_{1} & u_{2} & \\dots & u_{P} \\\\\n            v_{1} & v_{2} & \\dots & v_{P} \\\\\n        \\end{bmatrix}\n        = R \\cdot ( \\sum_{i=1}^{K} l_{i} \\cdot S_{i} ) + T\n    \\end{equation}\n\n    or equivalently:\n\n    \\begin{equation}\n        \\begin{bmatrix}\n            u_{1} & u_{2} & \\dots & u_{P} \\\\\n            v_{1} & v_{2} & \\dots & v_{P} \\\\\n        \\end{bmatrix}\n        = \n        \\begin{bmatrix}\n            l_{1}R & \\dots & l_{K}R\n        \\end{bmatrix}\n        \\cdot\n        \\begin{bmatrix}\n            S_{1} \\\\\n            S_{2} \\\\\n            \\dots \\\\\n            S_{K} \\\\\n        \\end{bmatrix}\n    \\end{equation}\n\n    \\def\\PT#1#2#3{#1_{#2}^{(#3)}}\n    \\def\\T#1#2{#1^{(#2)}}\n\n    This can then be extended to handle multiple views of the subject taken over a monocular video sequence. Let $(\\PT{u}{i}{t}, \\PT{v}{i}{t})$ denote the tracked 2D point at timestep $t$. This gives rise to the following system, taken over $N$ timesteps:\n\n    \\begin{equation}\n        \\underbrace{\n        \\begin{bmatrix}\n            \\PT{u}{i}{1} & \\dots & \\PT{u}{P}{1} \\\\\n            \\PT{v}{i}{1} & \\dots & \\PT{v}{P}{1} \\\\\n            \\PT{u}{i}{2} & \\dots & \\PT{u}{P}{2} \\\\\n            \\PT{v}{i}{2} & \\dots & \\PT{v}{P}{2} \\\\\n            & \\dots & \\\\\n            \\PT{u}{i}{N} & \\dots & \\PT{u}{P}{N} \\\\\n            \\PT{v}{i}{N} & \\dots & \\PT{v}{P}{N} \\\\\n        \\end{bmatrix}\n        }_{W}\n        = \n        \\underbrace{\n        \\begin{bmatrix}\n            \\PT{l}{1}{1}\\T{R}{1} & \\dots & \\PT{l}{K}{1}\\T{R}{1} \\\\\n            \\PT{l}{1}{2}\\T{R}{2} & \\dots & \\PT{l}{K}{2}\\T{R}{2} \\\\\n            & \\dots & \\\\\n            \\PT{l}{1}{N}\\T{R}{N} & \\dots & \\PT{l}{K}{2}\\T{R}{N} \\\\\n        \\end{bmatrix}\n        }_{Q}\n        \\cdot\n        \\underbrace{\n        \\begin{bmatrix}\n            S_{1} \\\\\n            S_{2} \\\\\n            \\dots \\\\\n            S_{K}\n        \\end{bmatrix}\n        }_{B}\n    \\end{equation}\n\n    % https://arxiv.org/pdf/1705.03098.pdf\n\n    This shows the tracking matrix $W$ can be factored into 2 matrices: $Q$ which contains the camera pose $\\T{R}{t}$ and configuration weights $\\PT{l}{1}{t}, \\dots, \\PT{l}{K}{t}$ per frame ${t}$. $B$ encodes the $K$ basis shapes $S_{i}$. This system can be factored with singular value decomposition to yield the shape basis $S_{i}$, per-frame camera rotations $R$ and per-frame configuration weights $l$. A number of techniques follow this formulation~\\cite{xxx, xxx, xxx}, but start with a shape basis learnt from available motion capture datasets (e.g. CMU~\\cite{xxx}).\n\n    More recent approaches were designed to be fully automatic. Shotton et al.~\\cite{kinectpaper} designed a commerically-available system for 3D human skeletal tracking which required a depth sensor. A generative 3D body model was used to synthesize a large training dataset of depth images with corresponding body part labels. Density estimators for each body part are then used in combination to localize body joints with a calculated confidence value. Taylor et al.~\\cite{taylor2012vitruvian} predict dense correpsondences between image pixels (again, with depth so in $\\R{3}$) and a representative 3D human body model, again by training on synthetic depth images. \\Cref{chap:cgas} of this thesis demonstrates a technique for predicting keypoints by training on synthetic \\emph{silhouette} data, rendered from an animal deformable body model, which overcomes the need for depth imagery at test time.\n\n    Automatic monocular approaches often take advantage of 2D keypoint or body part detectors when reasoning about 3D skeletons. Simo-Serra et al.~\\cite{xxx, xxx} form a probabilistic model that models both 3D pose and 2D keypoints jointly, overcoming noise among 2D body parts. Other approaches~\\cite{xxx, xxx} employ a two-stage pipeline; they begin by localizing 2D joint positions on an input image before running a subsequent optimization step that `lifts` these to a 3D pose. Tangential work~\\cite{xxx} takes uses detected 2D joints to perform a nearest neighbour search in a 3D mocap dataset. The most recent two-stage pipelines rely on deep convolutional networks to predict keypoints. Examples of such systems include DeepPose~\\cite{toshev2014deeppose}, an approach which employs a CNN to reason jointly about 2D landmark detection and 3D pose estimation from single RGB images. Pishchulin et al.~\\cite{pishchulin2016deepcut} later introduced DeepCut which extends DeepPose to the multi-person case.\n\n    State-of-the-art techniques now operate as a direct regression to a 3D pose. Most often, paired 3D training data (such as is available from datasets such as Human3.6M~\\cite{xxx}) is required which is generally expensive to obtain, particularly for animal categories. One branch of approaches~\\cite{tekin2016direct} predicts body configuration in terms of angles. Other approaches include Pavlakos et al.~\\cite{xxx}, who use a 2D joint predictor~\\cite{xxx} followed by a deep architecture to regress 3D heatmaps. Moreno-Noguer~\\cite{xxx} learn a pairwise distance matrix from 2D-to-3D space in order to allow unlikely 3D predictions to be ruled out with a suitable prior. These techniques were designed under the assumption that neural networks would struggle to learn a `lifting' function from 2D to 3D pose. This assumption was corrected by Martinez et al.~\\cite{xxx} who demonstrate the effectiveness of a simple architecture at regressing accurate 3D keypoints from 2D predictions. This technique was later interpreted probabilistically by The technique was interpreted probabilistically by Li et al.~\\cite{xxx}, who handled ambiguity in the 2D-to-3D lifting problem with a mixture density network. Related work that predicts a depth segmentation (so not strictly 3D keypoints) is SURREAL~\\cite{xxx} who train their network with data generated synthetically with a 3D human body model.\n\n\n% \\subsection{Toolkit}\n\n\n\\subsection{Model-based human shape and pose}\n\n    % only discuss dense methods -- discuss methods that do/do not explicitly model shape\n\n    This section will discuss methods for reconstructing a full 3D \\emph{dense} human from a monocular image or video sequence. Early work in this category fit shape primitives combined into a kinematic tree to silhouettes extracted from the input~\\cite{xxx, xxx, xxx}. The introduction of the 3D deformable human body model known as SCAPE~\\cite{xxx} enabled various fitting approaches. Sigal et al~\\cite{xxx} compute shape features from manually extracted silhouettes and use a mixture of experts formulation for predicting SCAPE model parameters. Later, Guan et al.~\\cite{xxx} fit the SCAPE model to provided keypoints, extracted silhouettes, edges and shading cues. They also define an interpenetration term that penalizes self-intersecting body parts, although this does not lead to easy optimization. Hasler et al.~\\cite{xxx}, Zhou et al.~\\cite{xxx} and Chen et al.~\\cite{xxx} present a similar approach, although show optimization only to input keypoints and manually or semi-manually (e.g. GraphCut~\\cite{xxx}) extracted silhouettes.\n\n    A significant advance was made by the introduction of SMPLify~\\cite{xxx}, the first fully-automatic method for monocular 3D human pose and shape reconstruction. Many of the concepts presented by SMPLify are used throughout this thesis, making it worthy of study. \n\n    %     \\begin{equation}\n    %         E_{\\text{data}}(\\theta,U) =\\sum_{i=1}^{n}s_{i} \\cdot d(x_{i}, M(u_{i}; \\theta))\n    %     \\end{equation}\n    %     where $M(u_{i}, \\theta)$ is the position of vertex $u_{i}$ on the vitruvian manifold mesh after having been displaced by an LBS deformation with respect to the pose~$\\theta$. \n\n    %     The sheer quantity of correspondences greatly constrain their optimizer which works well, even on challenging input images. Much of this report focuses on how this paper can be extended to work for animal subjects, incorporating deep learning correspondence prediction and working from monocular RGB input data.\n\n\n    \\subsubsection{Fitting a 3D model to 2D keypoints}\n\n    \\def\\J#1{J_\\mathrm{#1}}\n\n    SMPLify works by fitting the SMPL~\\cite{loper15smpl} model to a set of 2D image locations predicted by DeepCut~\\cite{xxx}, a deep convolutional neural network. For an input image $I$, DeepCut predicts a set of image keypoint locations $\\J{est} \\in \\RR{23}{2}$ which correspond to locations on the 3D SMPL mesh $\\J{\\SMPL}$. Precisely $\\J{\\SMPL} = R_{\\pose}(J(\\shape))$ where $J(\\shape)$ computes 3D skeleton positions from SMPL shape parameters $\\shape$, and $R_{\\pose}$ is the global rigid transformation effected by SMPL pose parameters $\\pose$. A model fitting approach is then used to align the SMPL model to the predicted keypoint positions. This is achieved through optimizing the SMPL parameters $(\\shape, \\pose)$, global translation $\\trans$ and camera parameters $K$, subject to priors over pose, shape and limb interpenetration priors. \n\n    The key energy term used in the optimization (and indeed throughout this thesis) is given by $\\E{J}(\\shape, \\pose; K, \\J{est})$ and measures the weighted 2D distance between estimated keypoints $\\J{est}$ and the corresponding SMPL joints $J_{\\SMPL}$.\n\n    % E_{J}(\\shape, \\pose, \\trans; K, \\J{est}) = \\sum_{joint, i} w_{i} \\rho(\\Pi_{K}(\\J{\\SMPL, i} - \\J{est, i}))\n\n\n    \\begin{equation}\n        E_{J}(\\shape, \\pose, \\trans; K, \\J{est}) = \\sum_{\\mathrm{joint}, i} w_{i} \\rho(\\Pi_{K}(\\J{\\SMPL, i} - \\J{est, i}))\n    \\end{equation}\n\n    The weighted 2D distance is implemented using the Geman-McClure~\\cite{xxx} penalty function $\\rho$ which helps deal with noisy DeepCut estimates. SMPLify implements $\\Pi_{K}$ perspective camera model with known (or roughly initialized) focal length although others opt for orthographic projection. The following definition provides a quick primer for this:\n\n    \\begin{definition}[Primer on camera geometry]\n\n        Perspective projection is a function which maps a 3D structure to blah blah.\n\n        \\begin{equation}\n            2X = Y\n        \\end{equation}\n\n        Orthographic projection is the following:\n\n        \\begin{equation}\n            3X = Z\n        \\end{equation}\n\n    \\end{definition}\n\n    The full energy formulation is then given as:\n\n    \\begin{equation}\n        E(\\shape, \\pose) = E_{J}(\\shape, \\pose; K, J_{\\text{est}}) + \\lambda_{\\pose}E_{\\pose}(\\pose) + \\lambda_{\\alpha}E_{\\alpha}(\\pose) + \\lambda_{\\text{sp}}E_{\\text{sp}}(\\pose; \\shape) + \\lambda_{\\shape}E_{\\shape}(\\shape)\n    \\end{equation}\n\n    where the following energy terms are employed, balanced according to the $\\lambda$ scalar weights:\n\n    \\begin{itemize}\n        \\item $E_{\\pose}(\\pose)$ is referred to as a \\textit{pose prior} which favours more likely poses by assigning large punishment to those that deviate from known poses collected from a large dataset.\n        \\item $E_{\\shape}(\\shape)$ is referred to as a \\textit{shape prior} which favours more likely pose-invariant shape configurations by assigning large punishment to those that deviate from known shapes collected from a large dataset. \n        \\item $E_{\\alpha}(\\pose)$ is a \\textit{joint limit} prior which ensures particular joints remain within acceptable angle limits. For example, a knee joint in a human model should be prohibited from bending more than 5 degrees upwards.\n        \\item $E_{sp}(\\pose; \\shape)$ is an \\textit{interpenetration} term, which can only be defined in such shape modelling approaches. Using both shape and pose from the model, it is possible to determine if any limbs are self-intersecting, or intersect other parts of the body and assign appropriate penalty.\n    \\end{itemize}\n\n    % TODO: Variations on SMPLify\n    SMPLify has recently undergone subsequent variations, including Huang et al.~\\lazycite{https://arxiv.org/abs/1707.07548}{Huang Multiview} who fit SMPL to multi-view images and Pavlakos et al.~\\lazycite{https://arxiv.org/abs/1904.05866}{SMPL-X fitting} who extend SMPL with hand and facial expression parameters and follow a similar fitting procedure. \\Cref{chap:cgas} of this thesis will introduce a \\emph{self-supervised} version of SMPLify that uses synthetic data for training, thereby overcoming the need for a large 2D dataset with manually-labelled keypoints.\n\n    An example result can be seen in Figure \\ref{fig:smplify}:\n\n    \\begin{figure}[H] % Example image\n        \\center{\\includegraphics[width=0.95\\linewidth]{fitting_smpl}}\n        \\caption{SMPLify: Fitting the SMPL model to the Leeds Sports Dataset.}\n        \\label{fig:smplify}\n    \\end{figure}\n        \n    \\subsubsection{Direct regression}\n    The most recent, and state-of-the-art approaches employ deep learning techniques to solve the entire optimization problem by directly regressing shape and pose parameters of the template model. An early approach by Tan et al.~\\cite{tan17indirect} used deep neural networks to learn an encoding $f: \\RR{H}{W} \\mapsto (\\pose, \\shape, \\trans, K)$ of input images to SMPL pose and shape, translation and camera parameters. Their method makes use of a \\emph{silhouette renderer} $R : (V, T) \\mapsto \\{0,1\\}^{H \\times W}$ (learnt using synthetic data) capable of producing a binary silhouette from a predicted SMPL mesh. In this way, $R$ allows the network's SMPL predictions to be supervised to ensure generated silhouettes match ground-truth annotations. \n    Improvements were realised by incoporating an abudance of available human data into the training pipeline. Apart from 3D morphable models (e.g. SMPL~\\cite{loper15smpl}), methods use paired 3D motion capture data (e.g. Human3.6M~\\cite{ionescu2013human3,IonescuSminchisescu11}, 3DPW~\\cite{vonmarcard2018recovering}) to help relate 2D appearance and the underlying 3D structure, unpaired 3D motion capture data (e.g. CMU~\\lazycite{CMU}{CMU}) for learning detailed priors over the distribution of human shapes and poses, and large 2D keypoint datasets (e.g. MSCOCO~\\lazycite{COCO}{COCO}, LSP~\\lazycite{LSP}{LSP}, MPI~\\lazycite{MPI}{MPI}) which help promote generalization to `in-the-wild' scenarios. A notable work in this category is Human Mesh Recovery (HMR) of Kanazawa et al.~\\cite{kanazawa18end-to-end}, although multiple concurrent works exist\\lazycite{https://proceedings.neurips.cc/paper/2017/file/ab452534c5ce28c4fbb0e102d4a4fb2e-Paper.pdf}{Hsiao-Yu Fish Tung}, \\lazycite{https://www.seas.upenn.edu/~pavlakos/projects/humanshape/}{pavlakos}, \\lazycite{http://virtualhumans.mpi-inf.mpg.de/papers/omran2018NBF/omran2018NBF.pdf}{neural body fitting} and \\lazycite{DenseRaC}{DenseRaC}. \\Cref{chap:3dmulti} of this thesis will explore a method for modelling uncertainty in 3D reconstruction, by exploring extensions to the aforementioned architectures.\n\n    % Show the basic structure of these networks in a picture\n    \n    BodyNet \\lazycite{https://www.di.ens.fr/willow/research/bodynet/}{bodynet} follow a similar pipeline with the inclusion of a texture prediction module supervised by 2D body part segementations \\lazycite{body part dataset}{dataset}. Silhouette data has also been shown to assist in accurate reconstruction of clothes, hair and other appearance detail~\\cite{alldieck2019learning} \\lazycite{https://arxiv.org/pdf/1901.00049.pdf}{SiCloPe} \\lazycite{https://arxiv.org/abs/2004.04572}{ARCH}. Methods typically represent 3D clothes as `freeform' vertex deformations; in other words, deformations beyond the standard SMPL blend shapes which represent unclothed bodies. This presents significantly more degrees of freedom in the optimization, which must be controlled; either by large training datasets with limited variation or mesh-based deformation priors such as ARAP. \n\n    While the dominant paradigm in human reconstruction is now end-to-end deep learning methods, SPIN~\\cite{kolotouros19learning} show impressive improvement by incorporating an energy minimization process within their training loop to further minimize a 2D reprojection loss subject to fixed pose \\& shape priors. This idea inspired the work presented in \\Cref{chap:wldo} of this thesis, in which a 3D dog shape prior is learnt during the training loop via expectation maximization.\n\n    % https://openaccess.thecvf.com/content_ICCV_2019/papers/Xu_DenseRaC_Joint_3D_Pose_and_Shape_Estimation_by_Dense_Render-and-Compare_ICCV_2019_paper.pdf\n\n    \\subsubsection{Implicit representations}\\label{ss:implicit}\n    \n    There have also been a few recent works that reconstruct 3D humans without an explicit template prior. The general idea is to interpret a neural network as an implicit representation of the 3D surface. In particular, the network $f$ is trained to map sampled 3D locations $(x,y,z) \\in \\R{3}$ to an occupancy value $\\{0,1\\}$ (and optionally a texture value $(r,g,b) \\in \\R{3}$). This results in a memory efficient representation of the 3D surface as the space used to embed the surface does not need to be explicitly stored. Saito et al.~\\cite{pifuSHNMKL19,saito2020pifuhd} present an example of such an architecture. Their network maps 3D locations with ResNet~\\lazycite{Resnet}{Resnet} features sampled at coordinates projected with a known weak-perpective camera to occupancy and texture values. Li et al.\\lazycite{https://project-splinter.github.io/monoport/}{MonoPort} later sped up reconstruction and rendering to allow real-time inference. Neural Radiance Fields (NeRF) capture high resolution details of static scenes by mapping 3D coordinates $(x,y,z)$ and viewing directions $(\\theta, \\phi)$ to volume density and view-dependent emitted radiances. The work was adapted to articulated structures~\\lazycite{ANerf}{ANerf} by learning new skin for the SMPL model, using SPIN~\\cite{kolotouros19learning} as a basic 3D skeleton predictor. A current downside of these techniques is the need to train a separate model per scene/subject and the slow inference time. However, these works do demonstrate high quality results and are a worthy direction for future research.\n\n    % TODO - add these!    \n\n    % https://zju3dv.github.io/animatable_nerf/\n\n    % https://pablopalafox.github.io/npms/palafox2021npms.pdf - decent related work about implicit representations for 3D shapes & deformable shapes. This paper learns different MLPs, one for shape and one for pose from existing datasets e.g. AMASS [30], DeformingThings4D [26], CAPE [30], MANO [45]\n\n    % Multi-view Neural Human Rendering - https://openaccess.thecvf.com/content_CVPR_2020/papers/Wu_Multi-View_Neural_Human_Rendering_CVPR_2020_paper.pdf\n    % https://arxiv.org/pdf/2104.03953.pdf - SNARF: Differentiable Forward Skinning for Animating Non-Rigid Neural Implicit Shapes \n    % https://arxiv.org/abs/2102.06199 A-NERF\n    % https://arxiv.org/abs/2011.14143 i3DMM - human heads\n    % https://arxiv.org/abs/2007.11432 Combining Implicit Function Learning and Parametric Models for 3D Human Reconstruction\n    % https://www.sciencedirect.com/science/article/abs/pii/S0097849321000777: DIMNet: Dense implicit function network for 3D human body reconstruction\n    % https://pablopalafox.github.io/npms/?fbclid=IwAR0EPN8SuJ1j8LZyiccF4EgNA67nvrmmk7_kOf6P7Gk_fN1zgX32Z2txZmg - NPMs: \n\n    % TODO: talk about how they are slow, but methods have been developed to speed them up.\n\n    % Show the basic structure of these networks in a picture\n\n\\subsection{Model-based animals}\n\n    Having discussed reconstruction methods for other articulated subjects, this section will move on work related to the main topic of this thesis: 3D reconstruction of animal subjects. As summarized above, there are multiple challenges associated with animals which are not present with humans. Firstly, the general class of animal subjects is significantly more diverse in appearance and structure than the human category. This holds (although to a lesser extent) with various important animal subcategorizations, such as the class of medium-to-large quadrupeds, dog breeds, or birds. This diversity leads to challenges when designing 3D morphable models, since extreme deformations must allowed while penalizing even subtle adapations deemed unnatural. Also of concern are the significant variations in animal motion patterns (causing complex self-occlusion), body textures including fur (which vary even within breeds) and difficult environmental conditions. An interesting advantageous aspect to reconstructing animals is that they are less frequently clothed; a common nusiance factor for human reconstruction. These factors combined with practical challenges associated with capturing and annotating images has also led to a lack of open-source datasets which depict animal subjects. Of particular concern to this thesis is the lack of 3D training data captured from real animal subjects (typically using motion capture or static scans). Equivalent resources made available for humans have been used as a basis for building 3D morphable models (e.g. SMPL~\\cite{loper15smpl}, FAUST~\\lazycite{FAUST}{FAUST}), for learning priors over human shape and pose~\\lazycite{learning priors}{learning priors}, and to provide per-image 3D supervisation when training deep neural networks~\\cite{kanazawa18end-to-end}. Thankfully, online animal imagery which could serve as the basis for future datasets is plentiful, as are datasets with 2D silhouette data~\\cite{lin2014microsoft,everingham2010pascal,DAVIS2017-2nd}. A formal comparison is given in \\Cref{tab:animal-dsets}.  While animals are often featured in computer vision literature, there are still relatively few works that focus on accurate 3D animal reconstruction. However, the creative approaches used in these methods makes a formal review worthwhile. A summary of recent approaches is tabulated in \\Cref{tab:literature}.\n    \n    \\input{Chapter3/Tables/animal-dsets-tbl.tex}\n\n    \\input{Chapter3/Tables/lit-review-tbl.tex}\n\n    % Table~\\ref{tab:literature} summarizes previous work on animal reconstruction.\n    % It is interesting to note that while several papers demonstrate reconstruction across species, which {\\em prima facie} is a richer class than just dogs, the test-time requirements (e.g. manually-clicked keypoints/silhouette segmentations, input image quality etc.) are considerably higher for those systems.\n    % Thus we claim that the achievement of reconstructing a full range of dog breeds, \n    % with variable fur length, varying shape and pose of ears, and with considerable occlusion, is a significant contribution.\n\n    % \\subsubsection{Animals intro}\n\n    % Cashman and Fitzgibbon~\\cite{cashman2013shape} obtained one of the first 3D morphable animal models, but their work was limited to small classes of objects (e.g. dolphins, pigeons), and did not incorporate a skeleton.  Their work also showed the use of the 2D silhouette for fitting, which is key to our method. \n    % Reinert {\\em et al.} \\cite{reinert2016animated} meanwhile construct 3D meshes by fitting generalized cylinders to hand-drawn skeletons.\n    % Combined skeletal and morphable models were used by Khamis {\\em et al.}~\\cite{hand-shape} for modelling the human hand, and Loper {\\em et al.}~\\cite{loper15smpl} in the SMPL model which has been extensively used for human tracking. \n\n    % The SMPL model was extended to animals by Zuffi {\\em et al.}~\\cite{zuffi2017menagerie}, where the lack of motion capture data for animal subjects is cleverly overcome by building the model from $41$ 3D scans of toy figurines from five quadruped families in arbitrary poses. Their paper demonstrates single-frame fits of their model to real-world animal data, showing that despite the model being built from ``artists' impressions'' it remains an accurate model of real animals. This is borne out further by our work.  Their paper did however depend on per-frame human annotated keypoint labels, which would be costly and challenging to obtain for large video sequences. This work was recently extended~\\cite{zuffi_lions} with a refinement step that optimizes over model vertex positions. This can be considered independent to the initial SMAL model fit and would be trivial to add to our method.\n\n    \\subsubsection{Learning animal shape from 2D image collections}\n    % Early work in reconstructing animals includes Chen et al.~\\lazycite{chensharks}{chensharks} who learn a simple shape space by registering 11 3D shark models. \n    \n    Early work in animals focuses on learning 3D animal shape spaces by registering an input 3D model to image collections. Examples include Chen et al.\\lazycite{chensharks}{chensharks} who learn a shark model and Cashman et al.~\\cite{cashman2013shape} who recover a parameterized, morphable 3D model from unrelated 2D images depicting examples of the target class. Their method requires user-supplied 2D object outlines and point constraints for each image, and a single rigid mesh for the entire object class. The authors demonstrate recovering an 8-parameter morphable dolphin model from 32 images sourced from the Internet. To reduce required user activity, it is reasonable to assume that given sufficient labelled training data, it would be simple to manipulate a convolutional network architecture able to perform foreground / background segmentation and identify key points (say, joints) for the desired object class. The system achieves impressive results when optimizing over both pose and shape parameters across a range of object classes, but suffers from an overly smooth shape representation which causes trouble for strongly articulated classes such as polar bears. Related is the work of Ntouskos et al.\\lazycite{ntouskos}{ntouskos} who use an optimization scheme to combine geometric primitives fit to segmented animal parts.\n\n    \\begin{figure}[t] % Example image\n        \\center{\\includegraphics[width=0.7\\linewidth]{dolphins}}\n        \\caption{8-parameter dolphin model with annotated contour (left) and contour generators (middle and right).}\n        \\label{fig:cashman_fitzgibbon}\n    \\end{figure}\n\n    \n    \\subsubsection{Reconstructing animals with unknown skeleton}\n\n    The approach was later extended to articulated classes in work by Stebbing et al.~\\cite{arap_stebbing}, who optimize a 3D template model to animal video sequences. In this work, rather than defining an internal skeleton, the template model is rigged with virtual markers, which assign each mesh vertex $v_i$ to one of $M$ groups that share a set of basis rotations $B_{m}$. User interaction is again reuqired to segement the animal from the background and to provide mesh-to-image keypoint correspondences.\n\n    \\begin{figure}[t]\n        \\centering\n        \\begin{subfigure}{0.5\\textwidth}\n        \\centering\n            \\includegraphics[height=0.5\\linewidth]{arapsfm/arap_annotated_template}\n            \\caption{Template mesh with joint movement constraints.}\n        \\end{subfigure}%\n        \\begin{subfigure}{0.5\\textwidth}\n        \\centering\n            \\includegraphics[height=0.5\\linewidth]{arapsfm/arap_point_tracks}\n            \\caption{Example of user supplied point tracks.}\n        \\end{subfigure}%\n        \\caption{User input required for the deformable mesh animation algorithm, reprinted from~\\cite{arap_stebbing}.}\n        \\label{fig:arap_user}\n    \\end{figure} \n\n    Through reasonably accurate pose fitting and by allowing some pose-invariant shape deformation, this work produces smooth meshes which match the input video. Moreover, experimentation demonstrates that ARAP is a useful prior for reconstructing articulated, non-rigid motion in instances that an internal skeleton is a priori unknown. However, the shape attributes for the reconstructed model are not particularly accurate, which results in frequent errors appearing at internal occluding contours. In addition, the large non-convex optimization algorithm is an expensive operation, taking around 1 minute per video frame on a standard Linux workstation. Results are shown on 11 sequences.\n\n    Results showing this work fitting a crude dog template mesh to a sample video obtained from YouTube are shown previously in Figure \\ref{fig:intro_arap_output}. Figure \\ref{fig:arap_output} shows another example, which operates on a template impala mesh. Similar is the technique of Favreau et al.~\\lazycite{favreau}{favreau}, who fitting geometric primitives to a 2D video sequence with manually sketched body part labels. % TODO\n\n    \\begin{figure}[t]\n        \\center{\\includegraphics[width=0.95\\linewidth]{arapsfm/arapsfm_output.png}}\n        \\caption{Example of an dog template being fit to input video sequence, reprinted from~\\cite{arap_stebbing}}\n        \\label{fig:arap_output}\n    \\end{figure}\n\n    \\subsubsection{Fitting a morphable animal mesh to images}\n    % Draw out the silhouette term as important here\n    % Talk about subsequent SMALR + SMALST in the same section\n    Unfortunately, none of the techniques above are suitable for reconstructing an animal category with significant shape diversity. Zuffi et al.~\\cite{zuffi2017menagerie} made a significant contribution by releasing SMAL, a deformable 3D quadruped model (analagous to SMPL~\\cite{loper15smpl} for human reconstruction) build from $41$ scans of artist-designed toy figurines. The authors also released shape and pose priors generated from artist data. The authors also discuss a small modification to the SMPLify~\\lazycite{smplify}{smplify} approach in order to fit the SMAL model to RGB animal input images. However, an example result showing the result of the optimizer fitting the SMAL mesh to an RGB image of a fox can be seen in Figure \\ref{fig:smalify}. The whole optimization process takes around 1 minute per frame. \n\n    \\begin{figure}[t] % Example image\n        \\center{\\includegraphics[width=0.95\\linewidth]{fitting_smal}}\n        \\caption{Fitting SMAL to a hand segmented animal, reprinted from~\\cite{zuffi2017menagerie}.}\n        \\label{fig:smalify}\n    \\end{figure}\n\n    The terms of the optimization largely mirror the work of SMALify, although the interpenetration term is ommited and joints are provided manually rather than by a CNN. Importantly, the optimization incoporates an additional \\emph{silhouette} term which aligns the 3D model shape to a binary silhouette image extracted by a user. \\Cref{chap:cgas} of this thesis shows silhouette terms are of particular importance when reconstructing accurate animal shape. The following definition describes the process for differentiably rendering a 3D model to form a silhouette image which can then be compared to the provided 2D silhouette:\n\n    \\begin{definition}[Differentiable Rendering]\n        The process of generating a 2D image from a 3D polygon mesh is known as rendering and can be achieved through a process known as raytracing. Raytracing is a rendering technique able to generate photorealistic 2D images from the scene. It can be considered the opposite process by which the human eye perceives the world, as this method involves lines being cast outwards, beginning at a point known as the \\emph{camera origin}. Figure \\ref{fig:raycasting} shows a typical set up, in which rays are cast from the camera origin through each pixel on the image plane. The colour for the pixel is obtained by following the ray through the scene until a light source or non-reflective surface is reached, taking into account any reflections or non-opaque scene items. Due to the considerable comptuation required, the operation is often parallelized and assigned to the GPU. However, the technique is typically considered unsuitable for real-time rendering of complex scenes (due to complex ray paths) or when high resolution images (many rays required) are needed. However, for this work, scenes are typically made up of a single non-reflective, solid mesh surface and contain no complex elements (e.g.\\ shadows, non-constant lighting.\n\n        \\begin{figure}[H] % Example image\n            \\center{\\includegraphics[width=0.5\\linewidth]{ray_trace}}\n            \\caption{Diagram showing raycast rendering.~\\cite{rendering}.}\n            \\label{fig:raycasting}\n        \\end{figure}\n\n        It is also worth noting that the standard method for raycasting is not differentiable, causing problems for differentiable optimizers (including neural networks). However, alternative rendering methods~\\cite{loper2014opendr} are available for these purposes.\n    \\end{definition}\n\n    The SMAL authors~\\cite{zuffi2017menagerie} demonstrate their system by fitting their deformable 3D model to quadruped species. Subsequent work includes SMALR~\\cite{zuffi_lions}, who fit to multiple images of an animal and incoporate similar freeform deformation term used to model clothing in 3D human pipelines. They show their technique, which takes advantage of multi-view constraints afforded by fitting to video sequences, allows high-quality reconstructions of more exotic animal categories with details not covered in the original SMAL 3D model training set. \n    \n    A common property of techniques discussed so far is the reliance on manual annotations (commonly 2D silhouettes and keypoint correspondences) at test time. 3D-Safari~\\cite{Zuffi19Safari} overcome this by training a deep network on synthetic data (generated by applying SMALR~\\cite{zuffi_lions} on a large input dataset) to recover detailed zebra shapes in the wild. \\Cref{chap:cgas} of this thesis demonstrates a technique which overcomes the need for a large input dataset of joint annotations by training on synthetic data generated from the graphics model alone. \n    \n    A further drawback of the approaches is their reliance on a test-time energy-based optimization procedure, which is susceptible to failure with poor quality keypoint/silhouette predictions and increases the computational burden. \\Cref{chap:wldo} of this method presents an automatic reconstruction method that overcomes the need for additional energy-based refinement, and is trained purely from single in-the-wild images. \n    \n    Tangential to these approaches is the work of Kulkarni et al.\\lazycite{Canonical Surface Mapping}{Canonical Surface Mapping} who reconstruct pose (although not shape) parameters for an rigged mesh using a deep network, learning from geometry cycle consistency terms rather than annotated keypoints. However, the shape is fixed to the input mesh and pose is also often confused, particularly determining the difference between the legs. The results appear of significantly poorer quality than the results in \\Cref{chap:cgas} and \\Cref{chap:wldo} of this thesis. Also of consideration is the end-to-end network of Kanazawa et al.~\\cite{kanazawa2018birds} and subsequent paper which overcomes the need for keypoints by capturing uncertainty in camera viewpoints. In addition, their network does not require an input 3D morphable model, although they do initialize a sphere model to a mean bird. In addition, the bird category exhibits more limited articulation than our dog category. \n    \n\n    % TODO: LASR: Learning Articulated Shape Reconstruction from a Monocular Video: https://arxiv.org/pdf/2105.02976.pdf, https://lasr-google.github.io/ mesh based\n    \n    % TODO:\n    %Finally, there are techniques which do not produce a mesh~\\cite{Agudo_2018_CVPR,novotny19c3dpo} or rely heavily on input 2D keypoints or video at test-time~\\cite{vicente_3dv,Probst2018_ECCVa}.\n    % Unsupervised Learning of Probably Symmetric Deformable 3D Objects from Images in the Wild\n    % Canonical Surface Mapping via Geometric Cycle Consistency https://arxiv.org/abs/1907.10043\n\n\n\n% \\subsubsection{Literature review tables}\n\n% The closest work in terms of scale is the category-specific mesh reconstruction of Kanazawa et al.~\\cite{kanazawa2018birds}, where 2850 images of birds were reconstructed.  However doing so for the complex pose and shape variations of dogs required the advances described in this paper.\n\n\n\n% Caves near Tubingham - first identified 3D models created by people.\n% Then cave paintings\n\n% Birth of photography, trying to understand animal behaviour\n% Muybridge, 1878 in photography\n% Marey 1882 in France\n\n% Marr and Nisihara, 1978 -- modelling animals with cylinders\n% Weizmann horse dataset, ECCV 2002 \n% MSRC dataset, ICCV 2005 - labelling animal parts, included cows\n% ImageNet 2009 - animals lumped in\n%  Caltech-UCSD Bird dataset - fine grained classification. Realised that animals were a special class of entity in the world, and have interesting features\n% Crall et al. HotSpotter 2013 - identifying individual zebra by their patterns\n% Cashman & Fitzgibbon 2013 - foundation of 3D animals, for are dolphins. Also giraffes apparently?\n% SMAL model - zuffi et al\n% Mathis - deeplabcut keypoint detection. avenues for scientific exploration\n% Gravin et al. DeepPoseKit. Looking at collective behaviour of large swarms of animals.\n\n\n% 3D cheetahs in the wild (7500 frames + 2D pose, 20K 3D frames)\n% Horse keypoint detection. does imagenet performance correlate to pose estimation robustness. Horse10, Horse-C? -- mathis, biasi et al WACV 2021.\n% AnimalPose dataset.\n% iRodents dataset (on iNaturalist?)\n% SuperAnimal pretraining? Ye et al. CV4Animals.\n% MacaquePose\n\n% end-to-end bottom-up multi-agent pose estimation", "meta": {"hexsha": "b31c05cc7dbb118700604ae7aac7cfa1baa023e8", "size": 44101, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapter3/3_model-based-reco.tex", "max_stars_repo_name": "benjiebob/phd-thesis-template", "max_stars_repo_head_hexsha": "2fd86bb807b830c06944d9c59962939d9a95ca7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter3/3_model-based-reco.tex", "max_issues_repo_name": "benjiebob/phd-thesis-template", "max_issues_repo_head_hexsha": "2fd86bb807b830c06944d9c59962939d9a95ca7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter3/3_model-based-reco.tex", "max_forks_repo_name": "benjiebob/phd-thesis-template", "max_forks_repo_head_hexsha": "2fd86bb807b830c06944d9c59962939d9a95ca7a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 125.6438746439, "max_line_length": 2377, "alphanum_fraction": 0.765696923, "num_tokens": 10897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.3057260459468708}}
{"text": "\\documentclass{llncs}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{comment}\n\\usepackage{hyperref}\n\\usepackage{longtable}\n\\usepackage{stmaryrd}\n\\newcommand{\\interp}[1]{\\llbracket #1 \\rrbracket}\n\\newcommand{\\maps}{\\colon}\n\\newcommand{\\FinSet}{\\mathrm{FinSet}}\n\\newcommand{\\Set}{\\mathrm{Set}}\n\\newcommand{\\Cat}{\\mathrm{Cat}}\n\\newcommand{\\Calc}{\\mathrm{Calc}}\n\\newcommand{\\Mon}{\\mathrm{Mon}}\n\\newcommand{\\BoolAlg}{\\mathrm{BoolAlg}}\n\\renewcommand{\\Form}{\\mathrm{Form}}\n\\newcommand{\\leftu}{\\mathrm{left}}\n\\newcommand{\\rightu}{\\mathrm{right}}\n\\newcommand{\\send}{\\mathrm{send}}\n\\newcommand{\\recv}{\\mathrm{recv}}\n\\newcommand{\\comm}{\\mathrm{comm}}\n\\renewcommand{\\quote}[1]{``#1\"}\n\\newcommand{\\deref}[1]{\\mathrm{eval}(#1)}\n\\newcommand{\\op}{\\mathrm{op}}\n\\newcommand{\\NN}{\\mathbb{N}}\n\\newcommand{\\lpquote}{\\ulcorner}\n\\newcommand{\\rpquote}{\\urcorner}\n\\newcommand{\\quotep}[1]{\\lpquote #1 \\rpquote}\n\\makeatletter\n\\gdef\\tshortstack{\\@ifnextchar[\\@tshortstack{\\@tshortstack[c]}}\n\\gdef\\@tshortstack[#1]{%\n  \\leavevmode\n  \\vtop\\bgroup\n    \\baselineskip-\\p@\\lineskip 3\\p@\n    \\let\\mb@l\\hss\\let\\mb@r\\hss\n    \\expandafter\\let\\csname mb@#1\\endcsname\\relax\n    \\let\\\\\\@stackcr\n    \\@ishortstack}\n\\makeatother\n\n\\title{Modal Logics via a distributive law}\n\\author{\nMichael Stay\\inst{1}\\\\\n\\and\nL.G. Meredith\\inst{2}\\\\\n}\n\\institute{\n  {Pyrofex Corp.}\\\\\n  \\email{\\fontsize{8}{8}\\selectfont stay@pyrofex.net}\\\\\n  \\and\n  {Synereo, Ltd}\\\\\n  \\email{\\fontsize{8}{8}\\selectfont greg@synereo.com}\n}\n\\begin{document}\n\\maketitle\n\\begin{abstract}\n\\noindent\n\n\\end{abstract}\n\\section{Introduction}\n\n\\subsection{The reflective higher-order $\\pi$-calculus}\n\nLawvere theories are limited in that they only talk about products of sorts.  A lambda theory is a generalization of a Lawvere theory that has the ability to talk about function sorts like $A \\Rightarrow B$ and sums like $A+B$ or $1 + A + A^2 + \\cdots,$ more commonly denoted with the Kleene star $A^*.$  One can think of lambda theories as having access to a ``library'' that takes care of the details of bound variables and substitution for us so we do not have to implement all that machinery.  Much of the work on nominal logics has been about exactly this factorization \\cite{GabbayMJ:picfm}.  A lambda theory Th(Calc) is a bicartesian closed 2-category equipped with an identity-on-objects functor from $(\\FinSet/\\Sigma)^{\\op}$ to Th(Calc).  Models of Th(Calc) are functors to Cat that preserve all the structure.\n\nThe $\\pi$-calculus was invented in the early 1990s by Robin Milner as a model of networks of processes with a dynamically changing topology; two processes initially unaware of each other can be introduced by a third process.  The reflective higher order $\\pi$-calculus uses quoted processes as names; the term constructors for quote and eval replace the more traditional nu and replicate constructors.  We also add a ``comm'' term to restrict the contexts in which reduction can occur \\cite{DBLP:journals/corr/StayM15}.\n\nHere is a presentation of the multisorted lambda theory Th(RHOpi) for the reflective higher-order $\\pi$-calculus:\n\\begin{center}\n  \\begin{longtable}{|p{0.3\\linewidth}|p{0.7\\linewidth}|}\n    \\hline\n    Sorts:\n    \\begin{itemize}\n      \\item $N$ for names\n      \\item $P$ for processes\n    \\end{itemize}\\bigskip\n    Term constructors:\n    \\begin{itemize}\n      \\item $\\mathsf{!}\\maps N \\times P^* \\to P$\n      \\item \\raggedright $\\forall k \\in \\NN \\; \\mathsf{for}\\maps N^{k} \\times ((N^*)^k \\Rightarrow P) \\to P$\n      \\item $|\\maps P^2 \\to P$\n      \\item $0\\maps 1 \\to P$\n      \\item $\\comm\\maps 1 \\to P$\n      \\item $\\quotep{-}\\maps P \\to N$\n      \\item $\\deref{-}\\maps N \\to P$\n    \\end{itemize}\n    &\n    Rewrites:\n    \\begin{itemize}\n      \\item $\\alpha\\maps (p_1 | p_2) | p_3 \\Rightarrow p_1 | (p_2 | p_3)$\n      \\item $\\beta\\maps p_1 | p_2 \\Rightarrow p_2 | p_1$\n      \\item $\\iota\\maps 0 | p \\Rightarrow p$\n      \\item \\raggedright $\\chi\\maps \\mathsf{for}( x^1; \\ldots; x^k, q) \\;|\\; \\Pi_{i=1}^{k} x^1\\mathsf{!}(p^i_1, \\ldots, p^i_{n^i})\\;|\\; \\comm \\Rightarrow q([\\quotep{p^1_1}, \\ldots, \\quotep{p^1_{n^1}}], \\ldots, [\\quotep{p^k_1}, \\ldots, \\quotep{p^k_{n^k}}]) \\;|\\; \\comm$\n      \\item $\\epsilon\\maps \\deref{\\quotep{p}} \\Rightarrow p$\n    \\end{itemize}\n    Equations:\n    \\begin{itemize}\n      \\item \\tshortstack[l]{$\\alpha = P^3, \\beta = P^2, \\iota = P$ ($|$ and 0 form a \\\\ commutative monoid)}\n      \\item \\tshortstack[l]{$\\epsilon = P$ (evaluating a quoted process is the \\\\ same as the process itself)}\n    \\end{itemize}\\\\\n    \\hline\n  \\end{longtable}\n\\end{center}\n\nFor readability and consistency with common practice (see Scala\nfor-notation) we introduce syntactic sugar for the input guarded\nprocess forms, writing it as\n\n\\[\\interp{\\mathsf{for}( \\vec{y^1} \\leftarrow x^1;\\ldots ; \\vec{y^k} \\leftarrow x^k)\\{ p \\}} = \\mathsf{for}( x^1, \\ldots, x^k, \\lambda \\vec{y^1} \\ldots \\vec{y^k}.p)\\]\n\nThe simplest RHOpi processes are 0, the ``do nothing'' process; and comm, a ``catalyst'' process that enables communication on a channel.  The only rewrite that is not an identity is $\\chi,$ the communication event.  The $\\chi$ rewrite is neither confluent nor deterministic.  For example, we can model contention for resources with the term\n\\[ \\recv(x, P)\\;|\\;\\recv(x, Q)\\;|\\;\\send(x,R)\\;|\\;\\comm \\]\nwhich has two rewrites out of it, one where the continuation $P$ is invoked on the name $\\quotep{R}$ and the other where the continuation $Q$ is invoked on it.  We can model message arrival order nondeterminism with the term\n\\[ \\send(x, P)\\;|\\;\\send(x, Q)\\;|\\;\\recv(x,R)\\;|\\;\\comm \\]\nwhich has two similar rewrites out of it, one where the continuation $P$ is invoked on the name $\\quote{R}$ and one where $P$ is invoked on the name $\\quote{Q}$.\n\nIn the theory above, comm is preserved by the rewrites; one can think of each comm instance as representing a processor.  An alternative would be to consume comm in the $\\chi$ rewrite; then comm would track clock ticks; an application of a consumable comm is the formal verification of billing code for tracking compute resources.\n\nReplication of processes, and therefore general recursion, can be encoded \\cite{DBLP:journals/entcs/MeredithR05} via\n\\[D(x) = \\recv(x, y\\mapsto \\send(x, \\deref{y}) | \\deref{y})\\]\n\\[!P = \\send(x, D(x) | P) | D(x).\\]\n\n%% P    ::= { [P [| P]]}\n%%       | for( Ptrn <- X [; Ptrn <- X] )P\n%%       | X!( P )\n%%       | *X\n%%       | V\n%% V    ::= Arry | Grnd\n%% Grnd ::= Bool | Num | Str | ...\n%% Ptrn ::= X | _ | ...\n%% X    ::= @P | [Char]+\n\n%% for( y1 <- x1 ){ for( y2 <- x2 )P }\n%% for( \n\n%% \\begin{mathpar}\n%%   \\inferrule* [lab=process] {} {P \\bc \\{ [P [| P]] \\}}\n%%   \\and\n%%   \\inferrule* [lab=summation] {} {{M,N} \\bm \\mathsf{for}( Ptrn\n%%     \\leftarrow X [] }\n%%   \\and\n%%   \\inferrule* [lab=agent] {} {{A} \\bc (\\vec{x})P \\;| \\; \\clift{\\vec{P}}}\n%%   \\and\n%%   \\inferrule* [lab=name] {} {{x,y} \\bc \\quotep{P}}\n%% \\end{mathpar} \n\n\\[ \\interp{u \\langle C\\rangle v} = \\{ t \\;|\\; \\exists \\rho\\maps C[t, u] \\Rightarrow v \\}; \\]\n\nCaires' \\cite{Caires} operator $\\triangleright$ for rely-guarantee properties, the adjunct to $|,$ is an instance of our generic modal operator, where $u \\triangleright v = u \\langle - | - \\rangle v:$\n\\[ \\interp{u \\triangleright v} = \\{ t \\;|\\; \\exists \\rho\\maps (t\\;|\\;u) \\Rightarrow v\\} \\]\n\n\\[\\interp{ \\langle \\quotep{\\phi} \\rangle \\psi } = \\{ t | \\exists x\\in\\interp{\\quotep{\\phi}} \\rho : x!(\\top) | t \\Rightarrow \\psi \\}\\]\n\nThen we have that $\\langle x \\rangle \\psi$ is merely restricting $\\quotep{\\phi}$ to the singleton namespace consisting of $x$.\n\n\\[ \\langle \\rangle \\psi = \\interp{ 0 \\langle -|- \\rangle \\psi } \\]\n\n\\subsection{Three useful kinds of formulae}\n\\subsubsection{Responsiveness}\nAlways responsive to outside, but may contain internal deadlocks:\n\\[ \\mbox{resp}(\\quotep{\\phi}) = \\exists x \\in \\quotep{\\phi} . \\langle x\\rangle(\\top).\\mbox{resp}(\\quotep{\\phi}) \\]\n\n\nAttempt to say ``no deadlocks anywhere'':\n\n\\[\\begin{array}{rl}\n  \\mbox{Responsive}( \\quotep{\\phi} ) = & \\\\\n  & \\langle \\quotep{\\phi} \\rangle \\mbox{Responsive}(\\quotep{\\phi}) \\\\\n  & \\lor\\; \\mbox{outputOnly}\\; | \\;\\mbox{Responsive}(\\quotep{\\phi}) \\\\\n  & \\lor\\; \\exists x. x?\\top.\\top \\;|\\; x!\\top \\;|\\; \\top \\implies \\langle\\rangle \\mbox{Responsive}(\\quotep{\\phi})\\\\\n  & \\lor\\; \\mbox{Responsive}(\\quotep{\\phi}) \\; | \\;\\mbox{Responsive}(\\quotep{\\phi}) \\\\  \n\\end{array}\\]\nwhere\n\\[ \\mbox{outputOnly} = 0 \\lor ( \\quotep{\\top} ! \\top \\;|\\; \\mbox{outputOnly} ) \\]\n\nNote that there can be infinite prefixes and liveness is undecidable.  E.g. for every exchange in the last line check some finitely refutable conjecture like Riemann's hypothesis or Goldbach conjecture and return to the first line only if a counterexample is found.\n\nIt is easy to see that a process that satisfies $\\mbox{Responsive}$ will have a shape that\nlooks like\n\n\\[\\Pi\\mathsf{for}( v \\leftarrow u )P \\;|\\; \\Pi x!(Q) \\;|\\; \\Pi I\\]\n\nwhere $u, x \\in \\quotep{\\phi}$, but $\\neg u \\bot x$, $P \\models \\mbox{Responsive}(\\quotep{\\phi})$ and $\\Pi I$ is communicates internally before becoming\n$\\mbox{Responsive}$. Building on this observation we can adapt the\nformula to be parametric in a formula $\\psi$, and in this way enforce\na property on the components that eventually communicate with the environment.\n\n\\[\\begin{array}{rl}\n\\mbox{ResponsiveP}( \\quotep{\\phi}, \\psi ) = \\psi \\land \\mbox{RecResponsiveP}( \\quotep{\\phi}, \\psi ) \\\\\n\\end{array}\\]\n\n\\[\\begin{array}{rl}\n\\mbox{RecResponsiveP}( \\quotep{\\phi}, \\psi ) = & \\\\\n  & \\langle \\quotep{\\phi} \\rangle \\mbox{ResponsiveP}( \\quotep{\\phi}, \\psi ) \\\\\n  & \\lor\\; \\mbox{outputOnly}\\; | \\;\\mbox{ResponsiveP}( \\quotep{\\phi}, \\psi ) \\\\\n  & \\lor\\; \\exists x. x?\\top.\\top \\;|\\; x!\\top \\;|\\; \\top \\implies \\langle\\rangle \\mbox{ResponsiveP}( \\quotep{\\phi}, \\psi )\\\\\n  & \\lor\\; \\mbox{ResponsiveP}( \\quotep{\\phi}, \\psi ) \\; | \\;\\mbox{ResponsiveP}( \\quotep{\\phi}, \\psi ) \\\\\n\\end{array}\\]\n\n\\subsubsection{Containment}\n\\[ \\mu X. \\langle \\quotep{\\phi} \\rangle ((X \\lor 0)\\;|\\;\\neg\\langle\\quotep{\\neg \\phi}\\rangle\\top)\\;|\\;\\neg\\langle\\quotep{\\neg \\phi}\\rangle\\top \\]\n\\subsubsection{Fuel}\nRevisit liveness: prove there's enough fuel to get back to first line.\n\nComputational complexity.\n\n\\bibliographystyle{amsplain}\n\\bibliography{ladl}\n\\end{document}\n", "meta": {"hexsha": "a65f2c001395d1736e1164b48ebcda14b4963558", "size": 10199, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ladl modal lics/modalics.tex", "max_stars_repo_name": "leithaus/pi4u", "max_stars_repo_head_hexsha": "c87163938857589153eb5225d0e4ac17597fd189", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2015-10-12T20:35:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T00:37:17.000Z", "max_issues_repo_path": "ladl modal lics/modalics.tex", "max_issues_repo_name": "leithaus/pi4u", "max_issues_repo_head_hexsha": "c87163938857589153eb5225d0e4ac17597fd189", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2018-07-06T19:01:06.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-19T22:39:58.000Z", "max_forks_repo_path": "ladl modal lics/modalics.tex", "max_forks_repo_name": "leithaus/pi4u", "max_forks_repo_head_hexsha": "c87163938857589153eb5225d0e4ac17597fd189", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2016-10-03T06:03:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-16T00:37:25.000Z", "avg_line_length": 48.5666666667, "max_line_length": 819, "alphanum_fraction": 0.6621237376, "num_tokens": 3403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.3057260391338469}}
{"text": "\\section{Smol Zooid}\n\n\\subsection{Processes}\n\n\\begin{frame}\n    \\frametitle{Goals}\n    \\begin{sticky}%\n    \\vspace{-.7cm}\n    \\begin{enumerate}\n    \\item Certifying \\textbf{individual} processes of a \\textbf{distributed system}\n    \\item Extracting runnable code\n    \\item Avoiding complex formalisations of binders, whenever possible\n    \\end{enumerate}\n    \\end{sticky}\n\\end{frame}\n\n\\pgfdeclarelayer{background}\n\\pgfsetlayers{background,main}\n\\begin{frame}\n    \\frametitle{Overview}\n\n  \\centering\n  \\begin{tikzpicture}[commutative diagrams/every diagram]\n    \\begin{pgfonlayer}{background}\n      \\fill[rounded corners, yellow!20!white] (-0.8,0.5) rectangle (7.5,-3.5);\n    \\end{pgfonlayer}\n    \n    \\node(G0)at (0,0) {$\\G$};\n    \\node(G1)at (3,0) {$\\coG$};\n    \\node(G2)at (6,0) {\\small{global trace}};\n    \\node(L0)at (0,-1.5) {$\\lT$};\n    \\node(L1)at (3,-1.5) {$\\colT$};\n    \\node(L2)at (6,-1.5) {\\small{local trace}};\n    \\node(P0)at (0,-3) {$\\proc$};\n    \\node(P2)at (6,-3) {\\small{process trace}};\n    \\node(OC)at (0,-5) {\\small{OCaml code}};\n    \\node(ZZ)at (3.5,-5) {\\bf \\dslName};\n     \n     \\path[commutative diagrams/.cd,every arrow,font=\\scriptsize]\n     (G0) edge node[above] {$\\Re$} (G1)\n     (G1) edge node[above] {LTS} (G2)\n     (L0) edge node[above] {$\\Re$} (L1)\n     (L1) edge node[above] {LTS} (L2)\n     (G0) edge node[right] {$\\upharpoonright$} (L0)\n     (G1) edge node[right] {$\\upharpoonright^{\\textsf{c}}$} (L1)\n     (G2) edge[<->] node[right] {$=$} (L2)\n     (L0) edge node[right] {$\\ofLt$} (P0)\n     (P0) edge node[above, xshift=-.5cm] {LTS} (P2)\n     (P2) edge node[right] {erase} (L2)\n     (P0) edge node[left] {extraction} (OC)\n     (P0) edge[<->] node[right,xshift=.1cm] {DSL layer} (ZZ)\n     ;\n%      \\path[dashed, red, commutative diagrams/.cd, font=\\scriptsize]\n%      (L0) edge[bend left=40] node[below left,yshift=.4cm, xshift=-.2cm]\n%        {Well typed!} (ZZ)\n%      (P2) edge[] node[below right] {Certified semantics!} (ZZ)\n%      (OC) edge[] node[above] {Extractable!} (ZZ)\n%      ;\n  \\end{tikzpicture}\n\n\\end{frame}\n\n\\begin{frame}\n    \\frametitle{Smol Zooid}\n    \\begin{greenbox}{}\n    \\begin{itemize}\n    \\item We combine \\textbf{shallow/deep embeddings} of binders\n    \\begin{itemize}\n    \\item We use DeBruijn indices for the deeply embedded binders\n    \\end{itemize}\n    \\item SZooid constructs are \\textbf{well-typed by construction}\n    \\item We leverage \\textbf{Coq code extraction} mechanism\n    \\item For simplicity, SZooid does not cover \\emph{choices}\n    \\end{itemize}\n    \\end{greenbox}\n\\end{frame}\n\n\\begin{frame}[fragile]\n    \\frametitle{Core Processes}\n    In: \\url{http://github.com/emtst/gentleAdventure}\n\\vspace{.5cm}\n    \\begin{minted}{coq}\nInductive proc :=\n| Inact | Rec (e : proc) | Jump (X : nat)\n| Send (p : participant) {T : type}\n     (x : interp_type T) (k : proc)\n| Recv (p : participant) {T : type}\n    (k : interp_type T -> proc)\n\n| ReadIO {T : type} (k : interp_type T -> proc)\n| WriteIO {T : type} (x : interp_type T) (k : proc).\n    \\end{minted}    \n\\end{frame}\n\n\\begin{frame}[fragile]\n    \\frametitle{Payload Types}\n    We need to define a type for payload types:\n    \\begin{itemize}\n    \\item We need a decidable equality on payload types\n    \\item We need a decidable equality on payload values\n    \\end{itemize}\n\\vspace{1cm}\n    \\begin{minted}{coq}\nInductive type := Nat | Bool | ...\nDefinition interp_type : type -> Type := ...\n    \\end{minted}\n\\end{frame}\n\n\\subsection{Traces}\n\n\n\\begin{frame}[fragile]\n    \\frametitle{Semantics: events}\n    The semantics is an LTS: \n    \\begin{itemize}\n    \\item the labels are the \\textbf{communication events}\n    \\item it is parameterised by a \\textbf{payload interpretation function}\n    \\item traces are obtained as the greatest fixpoint of the LTS step\n    \\end{itemize}\n\\vspace{.5cm}\n    \\begin{minted}{coq}\nInductive action := a_send | a_recv.\nRecord event interp_payload :=\n  { action_type  : action;\n    subj         : participant;\n    party        : participant;\n    payload_type : type;\n    payload      : interp_payload payload_type\n  }.\n    \\end{minted}\n\\end{frame}\n\n\\begin{frame}[fragile]\n    \\frametitle{Semantics: Recursion Variables and I/O}\n    \\verb|p_unroll : proc -> proc| \n\\vspace{.2cm}\n\n\\verb|p_unroll| exposes the first communication action in a process:\n\\begin{itemize}\n\\item ``runs'' any I/O action\n\\item unfolds recursion\n\\end{itemize}\n\\vspace{1cm}\n    \\begin{minted}{coq}\nDefinition p_unroll : proc -> proc := ...\n    \\end{minted}\n\\end{frame}\n\n\\begin{frame}[fragile]\n    \\frametitle{Semantics: step}\nThe step of the LTS is defined as a \\textbf{function}:\n\\vspace{.5cm}\n    \\begin{minted}{coq}\nDefinition step' e E :=\n  match e with\n  | Send p T x k =>\n    if (action_type E == a_send) && (party E == p) &&\n       (eq_payload (payload E) x)\n    then Some k else None\n  | Recv p T k => ...  | _ => None\n  end.\nDefinition step e := step' (p_unroll e).\n    \\end{minted}\n\\end{frame}\n\n\\subsection{Local Types}\n\n\\begin{frame}[fragile]\n    \\frametitle{Local Types}\n    We introduce a typing discipline that associates processes with \\textbf{local types}, that \ncharacterise their communication behaviour:\n\n    \\begin{minted}{coq}\nInductive lty :=\n  | l_end\n  | l_jump (X : nat)\n  | l_rec (k : lty)\n  | l_send (p : participant) (T : type) (l : lty)\n  | l_recv (p : participant) (T : type) (l : lty).\n    \\end{minted}\n\\end{frame}\n\n\\begin{frame}[fragile]\n    \\frametitle{Type System}\n    \\begin{minted}{coq}\nInductive of_lty : proc -> lty -> Prop :=\n| lt_Send    p T k L x :\n    of_lty k L -> of_lty (@Send p T x k) (l_send p T L)\n| lt_ReadIO  T k L :\n    (forall x, of_lty (k x) L) -> of_lty (@ReadIO T k) L\n| ...\n.\n    \\end{minted}\n\\end{frame}\n\n\\begin{frame}[fragile]\n    \\frametitle{Smol Zooid: Smart Constructors (I)}\n    \\begin{sticky}\n\\vspace{-.5cm}\n    \\begin{itemize}\n        \\item It would be tedious to type up both a local type and a process\n        \\item Users would need to provide a proof that processes are well-typed\n    \\end{itemize}\n    \\end{sticky}\n    \\begin{greenbox}{}\n        We define \\textbf{SZooid} (Smol Zooid), to write\nwell-typed processes by construction, avoiding repetition.\n    \\end{greenbox}\n\\end{frame}\n\n\\begin{frame}[fragile]\n    \\frametitle{Smol Zooid: Smart Constructors (and II)}\n\\begin{minted}{coq}\nDefinition SZooid L := { p | of_lty p L}.\n\nDefinition z_Send  p T x L (k : SZooid L)\n  : SZooid (l_send p T L)\n  := exist _ _ (lt_Send p x (proj2_sig k)).\n...\n\\end{minted}\n\\end{frame}\n\n\\begin{frame}[fragile]\n    \\frametitle{Inferring Local Types}\n    SZooid constructs fully determine their types from their inputs, so we can ask Coq to \\emph{infer} local types\nassociated with SZooid terms:\n\\vspace{1cm}\n\\begin{minted}{coq}\nDefinition AZooid := { L & SZooid L }.\n\\end{minted}\n\\end{frame}\n\n\\subsection{Subject Reduction}\n\n\\begin{frame}[fragile]\n\\frametitle{Subject Reduction}\n\\begin{minted}{coq}\nTheorem preservation (e : proc) (L : lty) \n    (H : of_lty e L) (E : rt_event) :\n  forall e',\n    step e E = Some e' ->\n      exists L', lstep L (ev_erase E) = Some L' /\\\n                 of_lty e' L'.\n\\end{minted}\n\\end{frame}\n\n\\subsection{Extraction}\n\n\\begin{frame}[fragile]\n\\frametitle{Extraction}\n\\begin{itemize}\n\\item We convert \\verb|proc| to function calls in an \\textbf{ambient monad}\n\\item We extract the monadic code to OCaml\n\\item The ambient monad needs to be implemented in OCaml\n\\item Processes are extracted using Higher-Order modules, so it is straightforward to change the underlying\ntransport\n\\vspace{.2cm}\n\\item \\textbf{Remark:} SZooid does not provide an implementation of the ambient monad, but Zooid does, using TCP/IP sockets: \n\\url{https://github.com/emtst/zooid-cmpst}\n\\end{itemize}\n\\end{frame}\n\n\\begin{frame}[fragile]\n\\frametitle{Extraction Module}\n\\begin{minted}{coq}\nModule ProcExtraction (MP : ProcessMonad).\n  Fixpoint extract_proc (d : nat) (p : proc) : MP.t unit \n    := match p with\n       | Send p T x k\n         => MP.bind (MP.send T p x)\n                    (fun=> extract_proc d k)\n       ...\nEnd ProcExtraction.\n\\end{minted}\n\\end{frame}\n\n\\begin{frame}[fragile]\n\\frametitle{Example Extraction}\n\\begin{minted}{coq}\nModule  ALICE (MP : ProcessMonad) : PROCESS(MP).\n  Module PE := ProcExtraction(MP).\n  Definition proc :=\n    Eval compute in PE.extract_proc 0 alice.\nEnd ALICE.\n\nExtraction ALICE.\n\\end{minted}\n\\end{frame}\n\n\\begin{frame}[fragile]\n\\frametitle{Summary}\n\\begin{sticky}\n\\begin{itemize}\n\\item We have seen how to encode a small calculus of Multiparty Processes, with a basic type system\n\\item \\textbf{Next: how do we relate traces of individual processes to a larger system?}\n\\end{itemize}\n\\end{sticky}\n\\end{frame}\n", "meta": {"hexsha": "5fe56ae6dc3aaa365483f2dcfd831c231d5767ef", "size": 8624, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "act2/slides/parts/smolzooid.tex", "max_stars_repo_name": "emtst/GentleAdventure", "max_stars_repo_head_hexsha": "33d557ae6b1b7ec8f75f6e408a9b2d07e0e38e44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "act2/slides/parts/smolzooid.tex", "max_issues_repo_name": "emtst/GentleAdventure", "max_issues_repo_head_hexsha": "33d557ae6b1b7ec8f75f6e408a9b2d07e0e38e44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "act2/slides/parts/smolzooid.tex", "max_forks_repo_name": "emtst/GentleAdventure", "max_forks_repo_head_hexsha": "33d557ae6b1b7ec8f75f6e408a9b2d07e0e38e44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8428093645, "max_line_length": 125, "alphanum_fraction": 0.6525974026, "num_tokens": 2836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.5, "lm_q1q2_score": 0.30569098664707556}}
{"text": "\\section{Related Work} \\label{sec:related-work}\nWe summarize three closely related papers and point out similarities and differences with our\nwork.\nThe first paper describes another distribute \\textsc{WCOJ} on Timely Dataflow.\nThe second, compares multiple worst-case optimal join algorithm parallelization\napproaches to determine the best given a specific use-case.\nThird we describe a general graph pattern mining system build on Spark which also\nemploys work-stealing.\n\n\\subsection{\\textsc{WCOJ} on Timely Data Flow}\\label{subsec:wcoj-timely-data-flow}\n\nMc Sherry et al. published a distributed worst-case optimal join based on Timely Data Flow in 2018~\\cite{ammar2018distributed,naiad}.\nIn their paper they introduce three algorithms: \\textit{BigJoin}, \\textit{Delta-BigJoin} and \\textit{BigJoin-S}.\nThey implement only the first two algorithms.\n\n\\textit{BigJoin-S} is only described not implemented but comes with stronger theoretical guarantees.\nNamely, it is worst-case optimal in computation and communication with respect to the output size of the query\ngiven by the AGM bound.\n\\textit{BigJoin-S} can guarantee work balance.\nMoreover, it achieves optimality and work-balance while using low amounts of memory on all workers;\nthe memory usage per worker is in $\\mathcal{O} (\\frac{IN}{w})$ with $IN$ size of the input relationships and $w$ the number of workers.\n\nThe other two join algorithm are only worst-case optimal in computation and communication costs but\ndo not guarantee work-balance nor do they give the same low memory guarantees.\nAlthough, in praxis, they achieve both on many real-world datasets.\n\n\\textit{Delta-BigJoin} is an incremental algorithm which computes the new instances of the subgraph given a batch of new edges.\nHence, it operates in a different setting than our work.\nWe assume static graphs while they operate on graphs with the ability to find new instances caused by insertions.\n\n\\textit{BigJoin} is closest to our work.\nIt has been implemented and is a worst-case optimal join for static graphs.\n\nIn the following paragraphs, we describe \\textit{BigJoin}, analyse why it is not likely to be a good fit for Spark,\ndiscuss and compare the index structures used in their work to represent the input relationships and compare the\nguarantees are given by them and us.\n\n\\subsubsection{The \\textit{BigJoin} algorithm}\n\\textit{BigJoin} encodes a \\textit{Generic Join} (see~\\cref{subsec:worst-case-optimal-join-algorithm}) into multiple\ntimely dataflow operators.\n\nIn short, Timely Dataflow operators are distributed over multiple workers and each of them takes a stream of input data, operates\non it and sends it to the next operator which can be processed on a different worker.\nExamples for operators are \\textit{map} functions, \\textit{filters} \\textit{count} or \\textit{min}.\nIt is important to note that sending the output to an operator on a different worker is a fast, streaming operation, as opposed to,\nSpark's shuffles which are synchronous and slow because they involve disk writes and reads.\n\nFor the \\textit{BigJoin} the authors require each worker to hold an index for each input relationship which maps prefixes\nof the global variable order to the possible bindings for the next variable.\nIn use-case of graph pattern matching, this means that each worker holds an index into the forward and backward adjacency lists.\n\nTheir algorithm runs in multiple rounds;\none per variable in the join query.\nIn each round, they bind one variable.\nSo each round takes the prefixes as input and fixes one more binding.\n\nA single round starts with all prefixes from the former round distributed among all workers arbitrarily.\nThen they find join relations that offers the smallest set of extensions for each prefix.\nThis is done in steps with one step per relationship.\nIn each step, the prefix is sent to a worker by the hash of the attributes bound in the relationship of that step.\nWhen the relationship offers less possible values for the new binding then the current minimum, i.e. the size of its matching adjacency\nthe list is smaller, we remember it as the new minimum for the given prefix.\n\nNext, they hash the values of the prefix which are defined in the relationship with the least extensions and use these hashes to\ndistribute the tuples over all workers.\nThen, each worker produces all possible extensions for each prefix.\n\nFinally, each round ends with filtering out all extensions that are not in the intersection of extensions offered by each relationship.\nThis again takes one filtering step per relationship in the join.\n\nThis is a simple instance of the \\textit{Generic Join} implemented in data flow operators.\n\nThe algorithm described so far can build a high amount of possible extensions in each round.\nThis keeps it from keeping worst-case optimal guarantees for memory usage.\nThe authors fix this problem by batching the prefixes:\nthey allow only a certain number of prefixes in the system at all times.\nThey defer building new prefixes until the current batch of prefixes has been completed.\nThis is natively supported by Timely Dataflow.\n\n\\subsubsection{Applicability to Spark and comparison to GraphWCOJ}\n\\textit{BigJoin} is not suitable for Spark.\nThis has multiple reasons.\n\nMost importantly, it uses too many shuffle rounds.\nEach round and each step in a round requires communication and therefore a shuffle.\nIn total, the algorithm uses $2R \\times V$ rounds for a query with $R$ relations and $V$ variables.\nAs pointed out before this is no big problem in Timely Dataflow because shuffles are fast and asynchronous.\nHowever, in Spark, this is not the case.\n\nWe would like to point out that binary join plans can solve the same queries in $R - 1$ shuffle rounds and\nthat our solution does not require any communication rounds.\n\nSecond, Spark does not support batching queries naturally as Timely Dataflow.\nBuilding support for batching into Spark would be an engineering effort.\nAdditionally, it would be hard to define a good user interface over a batched query in Spark.\n\n\\textsc{GraphWCOJ} does not require batching because it only processes at most as many prefixes as workers in the system in parallel.\nTherefore, we do not have the problem of memory pressure to remember prefixes.\nThis is because the \\textsc{LFTJ} algorithm is a non-materialized representation of the join.\nWhen the Leapfrog Triejoin is executed, it changes its state such that the state always represents the non-materialized\npart of the join;\nthe state is encoded in the positions of the \\textit{TrieIterators}.\nIn other words, the \\textsc{LFTJ} performs a depth-first search of all possible bindings while the \\textit{BigJoin}\nperforms a batched breadth-first search.\n\n\\subsubsection{Indices used by \\textit{BigJoin} and GraphWCOJ}\nThe index structures used in their and our solutions are the same; one forward and one backward index over the whole graph on each\nworker.\nIt is possible to distribute the index of \\textit{BigJoin} such that each worker holds only a part\nof the index.\nThis is because each worker needs to hold only the possible extensions for the prefixes that map to it for each relationship.\nWe analyse this in the next paragraph.\n\nThe prefixes are mapped to workers by the hash of the attributes already bound.\nFor graph pattern matching this is one or zero attributes;\nthe edge relationship has two attributes and one is a new, yet unbound variable in the prefix.\n\nWe can reach a distribution of the indices such that each worker holds $\\frac{I}{w}$ with $I$ the size of the indices.\nFor that, we choose the same hash function for each variable such that always the same values match to the same worker.\nHowever, this solution is likely to lead to high skew and work imbalance because if a value is a heavy hitter the\nworker needs to process it for each binding over and over.\n\nIt is better to use different hash functions per variable.\nIn this case, we can estimate the percentage of the whole index hold by each worker by the binomial distribution.\nThis distribution models the probability that out of $N$ independent trials $k$ succeed with the likelihood of $p$ for a single trial\nto succeed.\nWe model the event of a key from the index being assigned to a worker as trial.\nThe likelihood is $\\frac{1}{w}$.\nWe have as many trials as variables in the join: $N = V$.\nWe are interested in the case that the tuple is not assigned by any of the variables, so $k = 0$.\nThen we have the likelihood that a tuple is not assigned given by $\\mathcal{B} (V, 0, \\frac{1}{w})$;\nso the fraction of the indices assigned to each worker is $1 - \\mathcal{B} (V, 0, \\frac{1}{w})$.\n\nWe plot this function for different numbers of workers and variables in~\\cref{fig:big-join-indices}.\nThe split of the indices held by each worker decreases drastically with the numbers of workers in\nthe system.\nHence, this partitioning scheme scales relatively well.\n\n\\begin{figure}\n    \\centering\n    \\includesvg[width=0.5\\textwidth]{svg/big-join-indices}\n    \\caption{Expected split of the indexes hold on each worker for different numbers of workers used\n    and variables in the query.\n    }\n    \\label{fig:big-join-indices}\n\\end{figure}\n\n\\subsubsection{Theoretical guarantees}\n\\textit{BigJoin} guarantees computational and communication worst-case optimality.\nHowever, the communication optimality does not take into account how the indices are generated on each worker.\nIf they are sent to each worker, this would be not worst-case optimal.\nThe extensions of \\textit{BigJoin-S} additionally give work-balance and low memory usage in $\\mathcal{O} (\\frac{IN}{w})$.\n\nGraphWCOJ guarantees computational worst-case optimality which it inherits from \\textsc{LFTJ}.\nWorst-case optimal communication is given by the fact that we do not communicate.\nThis is if we do not take the distribution of the indices into account which is in line with the analysis of the discussed paper.\n\nIf we take the distribution of indices into account, our algorithm is not worst-case optimal.\nDuring our setup, we broadcast the indices used.\nThis is not optimal for a single query;\nShares would be optimal.\nHowever, it amortizes quickly over multiple queries, while Shares converges to broadcasting for big queries.\n\nWe can not guarantee work-balance.\nHowever, we get close to it by using work-stealing.\nWith work-stealing, we are optimal within the size of a single task.\n\nGraphWCOJ's memory footprint does not depend on the size of the input nor of the output of the join.\nIts memory usage is given by the size of the Java objects used which depend on the query.\nHowever, this size should be neglectful small for all but embedded use-cases.\n\n\\subsubsection{Conclusion}\nWe conclude that our approach is the better fit for Spark because it requires less shuffling and no batching.\nGraphWCOJ gives nearly the same theoretical guarantees as \\textit{BigJoin}.\nWhile they can distribute their indices we cannot;\nwe rely on the fact that each worker holds the complete index.\n\nFinally, we would like to point out that~\\cite{ammar2018distributed} does not publish any number on the amount\nof network traffic caused by their algorithm.\nGiven that it sends many prefixes via the network this could be a bottleneck in many deployments, i.e. in cheaper instances\nin the Amazon cloud.\nAn analysis of the network traffic would be beneficial for a better understanding of the advantages and disadvantages\nof their approach.\n\n% General comparision?\n% rather not\n% but if so, state tracked, number of prefixes in the system at any time,\n% our system is monolith, theirs is built of simple operators\n\n% Experiments\n% Scaling of BigJoin not given, cannot be compared\n% Single threaded on twitter graph (big one) (need to double check which) and LJ, LJ needs 6.5s\n% BigJoin 8 workers 16 cores each, takes 3.4 s to find all triangles in LJ\n% BigJoin 10 machines 16 cores each 4-clique, house, 5-clique. they do not report dataset, maybe i can find the dataset int\n% seed paper\n% no experiment regarding communication costs\n\n% Implemenation: https://github.com/frankmcsherry/dataflow-join\n\n\\subsection{Survey and experimental analysis of distributed subgraph matching}\nOn the 28th July 2019, L. Lai et al. published a survey with experiments for multiple\ndistributed graph pattern matching algoritms~\\cite{longbin}\\footnote{The survey was published on arXiv 5 months after we started our\nthesis in\nFebruary.}.\nHere, we focus on four of the strategies they tested: \\textit{BigJoin} (see \\cref{subsec:wcoj-timely-data-flow}),\nShares, fully replicated graph and binary joins.\nAll of their algorithms are implemented in Timely Dataflow;\nso far they are not open-source.\nThey ran the all algorithms on 9 different queries over 8 datasets mostly on a cluster of 10 machines\nand 3 workers per machine.\nBelow we first summarize the most important design decisions for each algorithm, then\nhighlight their most interesting findings and finally compare their results with ours.\n\n\\textit{BigJoin} is implemented as described above but uses a \\textsc{CSR} data structure,\ntriangle indexing and a specific form of compression as optimization.\n\nThe Shares algorithm is configured as described in~\\cref{subsubsec:shares} and uses\n\\textit{DualSim} as the local algorithm.\n\\textit{DualSim} is a specialized subgraph matching algorithm.\nThe authors show that it beats the worst-case optimal join used in \\textit{EmptyHeaded}~\\cite{emptyheaded}\nwhich is a form of the \\textit{Generic Join} (see \\cref{subsec:worst-case-optimal-join-algorithm}).\n\nThe survey also covers our strategy of fully replicating the graph on all machines.\nThey choose \\textit{DualSim} as a local algorithm and a round-robin partitioning on the\nsecond join variable.\n\nFinally, they implement the binary joins with hash joins and use a sophisticated query optimizer\nto devise the best join order.\n\nThe most important finding of this work is that fully replicating the graph on all machines\nis the best option if the graph fits into memory even in Timely Dataflow with its deeply\noptimized and asynchronous communication routines.\nThey establish that fully replicating the graph is nearly always the fastest strategy,\nhas the lowest memory footprint\\footnote{Shares replicates too much data,\n\\textit{BigJoin} needs to hold many prefixes in memory and binary joins incur intermediary results.}, no\nfurther\ncommunication costs and scales better\nthan\nall other strategies up to 60 workers.\n\nIn line with our argument against Shares, they find that this strategy is nearly always\nbeaten by most other strategies.\nThey establish that it takes longer than the other strategies on nearly all queries and datasets.\nFurthermore, it shows the weakest ability to scale.\n\nThey report that \\textit{BigJoin} or binary joins are the best option if fully\nreplicating the graph is out of the question.\nBinary joins can be used for star and clique joins if it is possible to index all triangles in\nthe graph and keep this index in memory.\nOtherwise, \\textit{BigJoin} is preferable in most cases.\n\nFinally, they study the communication costs of the binary joins, Shares and \\textit{BigJoin}.\nThey find that graph pattern matching is computation bound problem when 10 GB switches are used\nfor networking but communication costs dominate in 1 GB switched networks.\nThey draw their conclusions from experiments run with 10 GB network infrastructure.\n\nInterestingly, Shares incurs fewer communication costs than \\textit{BigJoin}.\n\nTheir paper differs from our thesis in multiple ways.\n\nWe implement our system in Spark which has wide-spread usage in industry and a surrounding eco-system\nof graph pattern matching systems (see \\cref{subsec:graphs-on-spark}).\n\nWe give a comparison between a column store, binary search based Leapfrog Triejoin and\nour \\textsc{CSR} based GraphWCOJ.\nThey do not report on the benefits of \\textsc{CSR} in the context of \\textsc{WCOJ}.\n\nTheir implementation of the fully replicated strategy differs from ours in two important factors.\n\nFirst, they use a different local algorithm called Dual Sim~\\cite{dualsim}.\n\nSecond, they use a different partitioning scheme.\nTheir scheme replicates work of finding bindings for the first and second variable in a query and does not actively counter skew.\nThe skew-resilience of their scheme is based on the fact that it partitions the work on the second\nbinding.\nHence, it distributes skew of the first binding equally.\nHowever, as we see with our work-stealing approach this does not guarantee skew freeness for\nbigger queries (see \\cref{subsec:scaling-graphWCOJ}).\n\nTheir scheme could be applied to our system.\nIt is simpler than work-stealing but less resilient to skew.\n\nHowever, they come to the same conclusions, namely that fully replicating is the preferred strategy\nwhen the graph fits into main memory and that Shares is not a good strategy for graph pattern matching.\n\n\\subsection{Fractal: a graph pattern mining system on Spark} \\label{subsec:fractal}\nFractal is a general-purpose graph pattern mining system built on top of Spark published at SIGMOD'19~\\cite{fractal}.\nWe first describe the relevant aspects of their system.\nThen we compare it to our approach.\n\nGraph pattern mining includes the problem of graph pattern matching (as defined in~\\cref{subsec:graph-pattern-matching}).\nAdditionally, it includes problems such as frequent subgraph mining or keyword-based subgraph search.\n\nTo support all these problems in a single system, the authors describe their own programming interface made\noff initialization operators, workflow operators and output operators.\nEach workflow is described as a sequence of these operators.\nAll workflows are based around extending a subgraph starting from a single edge, vertex or a user-described\npattern.\nThis makes for three initialization operators one to start from a vertex, edge or pattern each.\n\nThe workflow operators process the subgraphs induced by the initialization operators.\nThey can expand the subgraph, e.g. if the subgraph is vertex induced, one expand step adds all neighbouring\nvertices to the subgraph.\n\nAnother workflow operator is to filter the subgraph instances.\nThen it is possible to aggregate subgraphs by computing a key, a value and possibly a reduction.\nFinally, these workflow steps can be looped to be repeated multiple times.\n\nTo execute the workflow the user can use one out of two output operators: \\textit{subgraphs} and\n\\textit{aggregation} to list all matching subgraphs or aggregate all matching subgraphs respectively.\n\nFor example, the workflow $vertexInduced().filter(sg => fully connected).subgraphs()$ enumerates\nall cliques in a graph.\n\nFractal maps these workflows to Spark by splitting them into \\textit{fractal steps} on\nsynchronization points, e.g. an aggregation which results is required in the next step.\nEach step maps to a Spark job which is scheduled by the Spark scheduler.\nFractal schedules the \\textit{fractal steps} in the correct order and waits for them to complete\nbefore starting the next one.\n\nA typical problem of graph pattern mining is the high amount of memory needed to keep partial matches;\nthe state of the algorithm.\nFractal counters this problem by enlisting subgraphs with a depth-first strategy.\nFurthermore, it starts computing all subgraphs from scratch for each step, instead of keeping them in\nmemory in between the steps.\nThey only keep the results of the aggregations to be used by the next step.\n\nAnother problem in graph pattern mining is work-balance because some parts of the graph are\nmore work-intensive than others.\nFractal tackles this problem with work-stealing.\nThey use a hierarchical work-stealing approach.\nFirst, each thread tries to steal work from another thread within the same Spark executor.\nOnly if this is not possible, they request work from another machine.\n\nThe local work-stealing is implemented by sharing the same subgraph enumerators;\nan iterator-like data structure that saves the state of the subgraph matching algorithm in a prefix\nmatch.\nThe subgraph enumerator offers a thread-safe method to generate the next prefix.\nHence, a thread can steal work simply by using the enumerator of another thread.\n\nThe second hierarchy of work-stealing is between multiple Spark workers.\nThe authors support that by using Akka to implement a simple message passing interface between\nall Spark workers.\n\nTheir experiments show near-linear scaling for the described work-stealing strategy up to 280\nexecution threads over 10 machines.\n\nFractal is similar to our system in some aspects.\nThey also solve graph pattern matching on Spark, inspired our approach to work-stealing and\nchoose a depth-first subgraph enumeration approach.\nWe discuss these similarities below and outline the differences.\n\nLike us, Fractal solves the problem of graph pattern matching.\nHowever, they offer the ability to solve multiple other common subgraph related problems as well.\nThe biggest difference is that they directly support aggregation over subgraphs, which, for example,\nallows them to solve frequent subgraph mining.\n\nThey build an independent system on top of Spark's infrastructure which comes with their own\nimperative query language.\nWe integrate a single algorithm deeply into Spark's query optimizer.\nTherefore, our contribution can be easily integrated into other graph systems building on Spark, e.g.\nG-Core~\\cite{gcore} or CAPS~\\cite{caps}.\nThese systems would offer a declarative interface to our worst-case optimal joins.\n\nThe work-stealing approach of Fractal inspired our solution.\nWe also use a shared object to steal work within a single Spark executor.\nAnyhow, our approach is simpler and less fine-grained.\nThey allow stealing work at every level of the depth-first enumeration of all subgraphs.\nWe only share work on the first level.\nThis makes their solution strictly more fine-grained and likely to perform better on big\nqueries.\nWe discuss this issue in our future work section~\\ref{subsubsec:finer-grained-work-stealing}.\n\nFractal is built for Spark in cluster mode.\nHence, they allow processes to steal work from different workers.\nGraphWCOJ is currently limited to a single worker.\nHowever, their message-passing based solution is directly applicable to our system if\nwe extend to multiple workers.\nAgain, we talk about this in more depth in future work (\\ref{subsubsec:cluster-mode}).\nIn short, we could use the same message-passing implementation but instead of stealing\nfrom a subgraph enumerator, the work would be taken from the queue on each worker.\n\nBoth systems enlist the subgraphs in a depth-first like fashion.\nIn both systems, this is highly beneficial to memory usage;\nthe problem of breadth-first algorithms has been discussed for \\textit{BigJoin} before (\\cref{subsec:wcoj-timely-data-flow}).\n\nTo conclude, Fractal is a complete system with its own query interface.\nThis makes it more powerful than our system but also less integrated into Spark.\nHence, it forces the user to adapt to their imperative language and hinders\nintegration with declarative graph query languages.\nWe used a similar work-stealing algorithm in our work.\nBoth systems recognize and demonstrate the advantages of a depth-first approach.\n\n%\\subsection{Adaptive Query Exectution}\n\n% Code generation\n%A novel development in Spark is the ability to generate code to execute queries on the fly, called WholeStage code-generation, based on a technique used in the Hyper database~\\cite{hyper,jira-whole-stage,1m-rows-laptop}.\n%Compiled queries have been shown to be multiple magnitudes faster than interpreted queries traditionally used in most database systems.\n%Interpreted queries are most commonly implemented using the Volcano model~\\cite{volcano}.\n%This model provides a simple and composable interface for algebraic operators; basically, every operator would provide an iterator interface.\n%This interface would be used by a query by calling next on the root operator, who in turn calls next on each of its children and so on until the next calls reach the scanning operators at the bottom of the query execution tree.\n%These would provide a single tuple which would then be \"pulled\" upwards through the query tree and processed by all operators.\n%When it reaches the root operator, the result is delivered to the user.\n%This happens for every tuple; hence, the approach can be described as tuple-at-a-time.\n%Although, this interface is simple yet powerful due to its composability, it is also quite computation intensive mainly due to the high number of calls to the next function, which is often a virtual function call.\n%This high number of virtual function call is not only CPU intensive but also makes bad use of CPU registers (they are spilled on every function call) and hinders compiler optimizations.\n%Compiled queries avoid these costs by generating code specific to each query consisting mainly out of multiple, tight for-loops following each other.\n%This speeds up processing by keeping data in the CPU registers as long as possible and avoiding materilization and function calls.\n%Furthermore, it allows compiler optimizations, such as loop unrolling or ~\\cite{hyper}\n%We are not aware of any published efforts to speed up worst-case optimal joins via code generation.\n\n%We aim to combine the research on worst-case optimal join algorithm and Spark's extensible optimizer Catalyst to speed up graph processing for all Spark users.\n%In particular, this work will be based on either of the two distributed versions of worst-case optimal join algorithms mentioned above.\n%We hope to further their work by evaluating which approach (shuffle + local join or timely data flow) works best on a MapReduce based processing engine as well as proving that worst-case optimal join algorithms\n%can improve performance on a complex, optimized, existing platform that has not been built with them in mind originally, albeit their high additional cost (e.g. for sorting and need for special data structures).\n", "meta": {"hexsha": "89146ea51e499b5f985649b19c2b542ba91566e7", "size": 25934, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "related-work.tex", "max_stars_repo_name": "PerFuchs/master-thesis", "max_stars_repo_head_hexsha": "85386c266fecf72348114bcbafeeb896a9e74601", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-02T20:23:03.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-02T20:23:03.000Z", "max_issues_repo_path": "related-work.tex", "max_issues_repo_name": "PerFuchs/master-thesis", "max_issues_repo_head_hexsha": "85386c266fecf72348114bcbafeeb896a9e74601", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "related-work.tex", "max_forks_repo_name": "PerFuchs/master-thesis", "max_forks_repo_head_hexsha": "85386c266fecf72348114bcbafeeb896a9e74601", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 62.3413461538, "max_line_length": 228, "alphanum_fraction": 0.8044651808, "num_tokens": 5580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3056909866470755}}
{"text": "\\section{Feature extraction}\n\\label{feature-extraction}\n\nThis Sections presents the original dataset structure and the \nsteps followed to create training and test sets from it.\n\nNote that the models mentioned in this section, for the first and \nextended datasets are\nthree layers \\emph{multilayer perceptrons}, \na feed forward neural network where each layer \nis densely connected  to the following, \nwith a reasonable number of neurons, trained \nfor 100 epochs with default parameters for the \\emph{stochastic gradient \ndescent optimizer}.~\\cite{mlp}\\cite{sgd}\\\\\nA \\emph{convolutional neural network}, a network with \na series of convolutional and pooling layers, followed by \nsome densely connected ones, is applied to the image dataset, trained for 15 epochs\nwith default parameters for the Adam optimizer.~\\cite{cnn} \\\\\nFor all datasets, the accuracy mentioned is computed with a \\emph{cross-validation} \napproach.~\\cite{cross}\\\\\n\nA deeper discussion about the models structure as well as the validation\ntechniques used in the project can be found at Section \\vref{model-definition}.\n\n\\subsection{Dataset structure}\n\\label{dataset-structure}\n\nThe UrbanSound8k dataset contains ten folds of audio samples, each one about \nfour seconds long. The samples are divided in ten classes.\\\\\nFrom the total of ten folds, the number one, two, three, four and six \nare taken as a training set, the others are each one a test set.\nFor this reason the following count about class numerosity considers\nonly the five training folds.\n\n\\begin{center}\n    \\begin{tabular}{ |l|c| } \n        \\hline\n        Class name & Number of samples \\\\\n        \\hline\n        air conditioner & 500 \\\\\n        car horn & 208 \\\\\n        children playing & 500 \\\\\n        dog bark & 500 \\\\\n        drilling & 500 \\\\\n        engine idling & 517 \\\\\n        gun shot & 190 \\\\\n        jackhammer & 548 \\\\\n        siren & 536 \\\\\n        street music & 500 \\\\\n        \\hline\n    \\end{tabular}\n\\end{center}\n\nThe table shows a clear class imbalance. In particular, the classes \n\\emph{car horn} and \\emph{gun shot} are not as numerous as the others. \nThis can lead to poor performances on the these two categories, it is\ntherefore taken \ninto consideration with training. \n\nThe following table shows the number of samples in the training set and \nthe various test sets.\n\n\\begin{center}\n    \\begin{tabular}{ |l|c| } \n        \\hline\n        Dataset & Number of samples \\\\\n        \\hline\n        Training set & 4499 \\\\\n        Test set 5 & 936 \\\\\n        Test set 7 & 838 \\\\\n        Test set 8 & 806 \\\\\n        Test set 9 & 816 \\\\\n        Test set 10 & 837 \\\\\n        \\hline\n    \\end{tabular}\n\\end{center}\nAll the operations on the datasets are performed with \\emph{Pandas} library.~\\cite{pandas}\n\n\\subsection{First dataset}\n\\label{first}\nExtracting features from audio files is not straightforward, nonetheless there \nare a collection of audio characteristics that are commonly used in audio machine learning \napplications.~\\cite{features}\n\nTo extract information from audio files \\emph{Librosa} is used.~\\cite{librosa}\nThe library provides many methods to choose from,\nto keep it simple, for the first try with this dataset, the extracted features \nare these three ones: \n\\begin{enumerate}\n    \\item \\emph{Mel-frequency cepstral coefficients}: the first 20 coefficients \n    are extracted;\n    \\item \\emph{Chromagram}: the first 12 chromas are considered;\n    \\item \\emph{Root-mean-square}.\n\\end{enumerate}\nMethod parameters that are not specified in the above list, are left on their default values.\nEach feature consists of an array of arrays containing measurements. \nA series of functions are applied to each sub-array and results \nare concatenated in a final feature vector. \nThe functions applied are \\emph{minimum}, \\emph{maximum}, \\emph{mean} \nand \\emph{median} from the \\emph{Numpy} library.~\\cite{numpy}\n\nThis approach results in 132 components feature vectors.\n\n\\paragraph{Parallelizing feature extraction}\nExtracting the three features listed above is really intensive \nbut the task is easily parallelizable, in fact, each file is independent \nfrom one another.\n\nFor this purpose \\emph{Dask} is used to speed up the computation and \nextract features from audio files in a multi-processing fashion.~\\cite{dask}\nThe main idea is to build an execution plan, where each audio file \nis managed in parallel by a collection of workers. \nImprovement is great as the time to process a single fold \nis cutted into a third.\n\n\\paragraph{Feature scaling}\nAfter testing some neural networks on the first dataset results \nare not promising. One of the reasons is the big difference in \nranges among feature vector components, for instance, \nsome audio characteristics are in the order of thousands while others \nrange between zero and one.\n\nTo mitigate this effect a \\emph{StandardScaler} with default parameters from \\emph{scikit learn} is applied.~\\cite{scaler}\nThe result is a dataset where each feature has more or less a distribution \ncentered in zero with unit variance.\nThis leads to an improvement on the results using the same\nmodel as before. \n\n\n\\subsection{Extended dataset}\n\\label{extended-dataset}\n\nResults using the three features named in the previous Subsection \nare promising but not enough, thus, to improve accuracy on the training set, \nnew audio characteristics are extracted, namely:\n\\begin{enumerate}\n    \\item \\emph{Zero-crossing rate};\n    \\item \\emph{Roll-off frequency};\n    \\item \\emph{Spectral flux onset strength}.\n\\end{enumerate}\nAs before methods parameters are left on default, but \nthis time \\emph{standard deviation} is added to\nthe previous functions \\emph{minimum}, \\emph{maximum}, \\emph{mean} \nand \\emph{median}. Each one is applied to the feature sub-vectors and \nresults are concatenated, leading to a total of 180 features for each audio file.\nScaling yields to promising results on the first dataset, \nso the same approach is applied to the extended one.\n\nAfter testing a network on the new training set \nwe can see a better accuracy.\n\n\\paragraph{Feature selection}\nAdding new features can lead to better results \nin the end but they all need to be useful to the model.\nFor this reason the extended dataset is subject of some experiments \nwith feature selection, in particular \\emph{PCA} algorithm from scikit\nlearn is applied.~\\cite{pca}\n\nThe main idea is to select a reduced number of features from the total, \nloosing as little information as possible. This approach often leads to better results, \nas useless features are discarded.\n\nThe method used to select features offers the possibility to specify how much \nvariance to preserve in the reduced dataset, this means that the number of \ncomponents is not given explicitly, indeed we try to preserve 99 percent of the original variance.\n\nThis technique resulted in 102 features, unfortunately, a model applied to this new dataset \nfailed to reach the performances obtained by the previous one, nonetheless, performances\nimproved with respect to the scaled dataset.\n\n\\subsection{Image dataset}\nA completely different approach is followed this time to represent audio files \nas images, to later apply a convolutional neural network.\n\n\\paragraph{Audio as an image}\nRepresenting an audio as an image is not straightforward but can be done after \nsome preprocessing.\nThe main idea is to use audio features and consider them in a two dimensional \nspace, where the value of a single cell can be viewed as a pixel.\nNote that some features are well suited for this kind of representation, for instance, \nsome of the previously extracted ones are given in output as a two dimensional vector.\n\nUsually, an image has three channels, red, green and blue, but \nimage classification on grayscale images, with one single channel \nis also relevant. This means that one can extract multiple features and view them \nas different channels, or choose only one to have the equivalent of a grayscale image.\n\n\\paragraph{Short time Furier Transform}\nFor this try with image classification the Short-time Furier transform \nis extracted from the audio files, and then used as a single channel image. \nIn particular, we extract 128 intervals with the \\emph{stft} function from Librosa, and, to accomodate \nthe different lenghts of audio in the dataset, pad the result to 256 wide vectors.\nThe result is an $128 \\times 256$ image for each sample. Figure \\ref{img}\nshows an example of an image obtained for each class.\n\n\\begin{figure}\n    \\includegraphics[width=\\textwidth]{images/class_images.png}  \n    \\caption{Short time Furier transform on samples coming from each class.\n    The scale on the Y axis is logarithmic, the X axis represent time and \n    the black portion on the edges is due to the applied padding.}  \n    \\label{img}\n\\end{figure}\n\nWe can see some difference between the classes, for instance, the \\emph{dog barking}\nshows short repeated sounds while \\emph{air conditioner}\nis constant. The hope is that those subtle differences are enough lo learn and classify.\n\n\\paragraph{Scaling pixel values}\nScaling techniques  are usually applied even to images to prevent high disparities \namong pixel value ranges, for this reason a Standard scaler with default parameters is \nonce again applied to the training set to mitigate this effect.\nWe can not apply it directly to the images, as they are two dimensional, but we can \nflatten the pixel arrays, apply scaling and reshape them in the original $128 \\times 256$ format.\n\nTesting a convolutional network \non the image dataset gives results that are comparable to the ones obtained on the initial scaled training \nset, discussed at Subsection \\vref{first}.\n\\newpage", "meta": {"hexsha": "95d3c6f3e1d700d32d54b2a5e3414eb41f89db98", "size": 9650, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/chapters/feature_extraction.tex", "max_stars_repo_name": "tomfran/urban-sound-classification", "max_stars_repo_head_hexsha": "9516e9a4f6ed3af2c5847c13321f8c0624ff827d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-08T22:33:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T22:33:40.000Z", "max_issues_repo_path": "report/chapters/feature_extraction.tex", "max_issues_repo_name": "tomfran/urban-sound-classification", "max_issues_repo_head_hexsha": "9516e9a4f6ed3af2c5847c13321f8c0624ff827d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-11-17T10:16:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-17T10:16:19.000Z", "max_forks_repo_path": "report/chapters/feature_extraction.tex", "max_forks_repo_name": "tomfran/urban-sound-classification", "max_forks_repo_head_hexsha": "9516e9a4f6ed3af2c5847c13321f8c0624ff827d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-08T22:16:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T22:16:39.000Z", "avg_line_length": 44.2660550459, "max_line_length": 122, "alphanum_fraction": 0.7650777202, "num_tokens": 2197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926666143434, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.3055907097395889}}
{"text": "\n\\chapter{Introduction} \\label{ch-1}\n\nThis research proposal is a significant extension of objectives and projects begun during my master's degree. Drinfeld modules have been a tool of theoretical interest in Number Theory since the 1970s when they were introduced by Valdimir Drinf'eld in his proof of the Langlands conjecture for the general linear group over a global function field of positive characteristic. Since then, there has been considerable interest in extending known results concerning Elliptic curves to the Drinfeld setting. This was partly the motivation of Gekeler in \\cite{frobdist} who aimed to study the distribution of coefficients of the characteristic polynomials of Drinfeld modules to determine if an analog of the Sato-Tate conjecture might hold. Recent research has continued to scrutinize computational questions connected Drinfeld modules, which includes work that makes use of rank-two Drinfeld modules for factoring polynomials \\cite{eschost2017arXiv171200669D}, as well as isogeny structures \\cite{DBLP:books/ams/20/CaranayGS20} and endomorphism rings \\cite{GaPa18}. Cryptographic primitives based on elliptic curves have been known for several decades and see use in real-world crypto-systems, however several attempts to extend these constructions to Drinfeld modules have proven insecure \\cite{Scanlon2001PublicKC}, \\cite{cryptoeprint:2019:1329}. \n\nTo that end, the main goal of \\cite{Musleh} was to develop an analog of Schoof's algorithm for counting points on an elliptic curve to the Drinfeld setting; while a direct parallel was not quite achieved, an algorithm in the spirit of Schoof's approach was developed, in addition to other algorithms that could leverage randomization for better practical performance. \n\nOne of the main goals of our research has been to extend algorithms previously developed for the rank-two case to Drinfeld modules of arbitrary rank. One particular challenge in the higher rank case has been finding suitable classical methods on which to base our algorithms. While the relationship with elliptic curves is well established for the rank-two case, higher rank Drinfeld modules are less clearly analogized by classical algebro-geometric objects. \n\nAnother major motivator for studying skew polynomials has been their use in coding theory, and in particular Gabidulin codes \\cite{PUCHINGER2017b} \\cite{bartz2021fast}. \n\n\n\n\n", "meta": {"hexsha": "7fa0990cba3f5193a2f639914db8ab593fe3e048", "size": 2392, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "MainText/chapter1.tex", "max_stars_repo_name": "DocTrivial/Research-Proposal", "max_stars_repo_head_hexsha": "cf988f64aa400d4c398fe4cb6738a4b90264359d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MainText/chapter1.tex", "max_issues_repo_name": "DocTrivial/Research-Proposal", "max_issues_repo_head_hexsha": "cf988f64aa400d4c398fe4cb6738a4b90264359d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MainText/chapter1.tex", "max_forks_repo_name": "DocTrivial/Research-Proposal", "max_forks_repo_head_hexsha": "cf988f64aa400d4c398fe4cb6738a4b90264359d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 159.4666666667, "max_line_length": 1346, "alphanum_fraction": 0.8260869565, "num_tokens": 510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.30559070232016367}}
{"text": "\\section{Dealing with variation}\n\\label{imaging:variation}\n\n\nExperimental error is always present in our\nmeasurements. Additionally, any given feature\nmay show extensive biological variability even within\napparently homogeneous populations. The biological\nvariation can be informative, as it gives us\ninsight into the limits to accuracy of cellular\nprocessing and can reveal phenotypically distinct\nsubpopulations (see \\ar{insulation:introduction}).\nHowever, if experimental error is mis-interpreted\nas biological variability, we lose statistical resolution\nor may assign unwarranted meaning to non-biological\nvariation. It is then important to be able to separate\nexperimental from biological variation.\n\n\nExperimental variation in fluorescence imaging\ncomes from many sources.\nThe imaging plane itself may cause\nvariation by intersecting cells at different\nrelative heights. This focal plane effect\ncan cause cell-to-cell differences in the\ndegree of focus and in how much off-plane\nfluorescence is captured. As discussed\nin \\ar{imaging:distortion}, image shading and\nbackground can also contribute to artificial variation\ndue to microscopy.\n\n\nAside from microscopy artifacts, the process\nof preparing cells for imaging may also\ngenerate distortions of true biological variability.\nFor example, variation in cellular surface\narea or volume may lead to differences\nin how well an antibody or non-permeable dye\ncan access an intracellular target.\nSuch differences in cell morphology may be\nenhanced or dampened by fixatives, which can cause cells to shrink\nin the $z$-axis \\cite{Pawly2006}.\n\n\n  \\begin{figure}[!bt]\n  \\centering\n  \\includegraphics[width=4in]{FIGS/imaging/cycleFit.pdf}\n  {\\singlespacing \n  \\caption[ Fitting total DNA to a simple cell cycle model.]\n            {An asynchronous cell population can be\n            fit to a simple model of the cell cycle\n            with reasonable accuracy. Left,\n            the theoretical\n            asynchronous cell-cycle distribution consists\n            of delta functions for G1 and G2 cells (i.e.\n            all cells in these populations have identical\n            DNA content) and a uniform distribution for\n            S-phase cells that are moving from the G1 to G2\n            states at a constant rate. Middle, the\n            total DNA feature of G1 and G2 nuclei shows log-normal variation\n            that can thus be fit to normal distributions after log-transformation.\n            Right, the cell subpopulation models \n            add up to a reasonably accurate estimate\n            of the cell cycle distribution. Gray, filled\n            histograms are of $\\log_2$(total DNA), with \n            DNA in arbitrary units, of $\\sim2\\times10^4$ Hoechst-stained\n            human colonic epithelial cells. Dashed lines are\n            the actual fits to this data using the method described\n            in the text.}\n  \\label{fig:imaging:cycleFit}}\n  \\end{figure}\n\n\nFinally, non-biological variation can be introduced\nduring segmentation. This can be due to outright errors\n(e.g. a cell being split into two objects) or to\nthe more subtle fact that the accuracy of a set of\nsegmentation parameters will vary from cell to cell.\nFor example, a chosen threshold that perfectly separates\nbackground from foreground for one cell may end up\ndiscarding the outer edges of a dimmer cell.\n\n\n\\subsection{Using DNA features for quality control}\n\\label{imaging:variation:dnaQC}\n\nDue to the error sources discussed above (among others)\nthere may be many outlier cells to discard. Manual or pseudo-manual\napproaches are often used for this task. \nVisual inspection of a random\nsubset of segmented cells is a common approach,\nthough automated solutions are needed for large datasets.\nAn example is the identification of out-of-focus images using\nimage-level features from tools like PhenoRipper\n\\cite{Rajaram2012}.\nI use an automated statistical approach that takes\nadvantage of ``ground truth'' aspects of total DNA\ncontent in cells. \nThis approach uses population-level statistics\nof DNA features to determine which cells\nare likely to be properly\nsegmented and in focus. In effect, I make the assumption that\ncells with biologically-unlikely DNA feature values will have\nnon-biological values in other features as well.\n\n\n\n\n  \\begin{figure}[!bt]\n  \\centering\n  \\includegraphics[width=6in]{FIGS/imaging/qualityControl.pdf}\n  {\\singlespacing \n  \\caption[ Using DNA features for quality control.]\n            {DNA features can be used for single-cell quality\n            control. Bottom left, the Total DNA feature\n            is fit to a cell cycle plot (fit not shown)\n            and the G1 population is gated as all cells\n            within $\\mu_{G1}\\pm2\\sigma_{G1}$ (blue). The population is\n            also statistically gated using the nuclear area (bottom,\n            middle) and the intra-nuclear intensity $cv$ (bottom, right).\n            The gating is $\\pm3\\times\\text{MAD}$ from the median of each\n            feature, where $\\text{MAD}$ is the median absolute deviation\n            ($\\text{median}(|X-\\text{median}(X)|)$. \n            ($3\\times\\text{MAD}\\approx2\\sigma$ for normal distributions.)\n            The gated points are considered to be in-focus G1 cells\n            that are likely segmented properly. In the top plot,\n            these quality-controlled\n            cells are found as red points within the blue box. Data from\n            >4000 Hoechst-stained human colonic epithelial cells.}\n  \\label{fig:imaging:qualityControl}}\n  \\end{figure}\n\n\n\nThe first step in my quality control pipeline is to identify cell cycle\nsubpopulations by fitting a cell cycle model\nto the total DNA histograms. This allows for later isolation\nof these subpopulations and removal of outliers. Note that\nin tissue culture microscopy\nmitotic (M-phase) cells are often lost during sample washes\nand so are already excluded from analysis.\n\n\nAn asynchronous cell population can be accurately\nfit to a simple model of the cell cycle. The\ntheoretical, variation-free model of this cell cycle\nconsists of of delta functions for the G1 and G2 peaks\nwith a uniform S-phase distribution in between\n(\\ar{fig:imaging:cycleFit}, left). In other words, all\ncells within G1 or G2 have the exact same DNA content,\nand cells moving through S-phase increase their DNA content\nat a constant rate. In reality,\nthe cell cycle distribution arising from measured\ntotal DNA consists of $\\log$-normally distributed G1\nand G2 peaks, with a variable-shaped S-phase distribution\nin between. I note that, on a $\\log$-scale, the G1 and\nG2 distributions have near-identical standard deviations\n($\\sigma_{G1}\\approx\\sigma_{G2}$).\n\n\n\nI implemented a simple variant of the\nDean-Jett-Fox cell cycle model \\cite{Dean1974,Fox1980}\nthat is sufficient to accurately identify G1 and G2 cells\nfrom microscopy data.\nThe formulae that comprise this model are in\nEquations~\\ref{eq:imaging:g1}\\nobreakdash-\\ref{eq:imaging:g2},\nwhere: $T_c$ is the $\\log_2$-transformed\ntotal DNA of a single cell; $\\mu_{G1}$ is the average of this\nvalue across all G1-phase cells; $\\sigma$ is the standard\ndeviation of the G1 and G2 distributions; $v$ is the height of the S-phase\nuniform distribution, $f(T_c)$ is the fraction of\ncells with the same $T_c$ DNA content (in practice, it is the fraction of cells\nfalling into the same histogram bin), and $w$ values are weights. \\ar{fig:imaging:cycleFit} shows\nthis model graphically, fit to experimental data.\n    %\n    \\begin{align}\n    f_{G1}(T_c) &= \\frac{w_1}{\\sigma \\sqrt{2\\pi}}\n    e^{-\\frac{(T_c-\\mu_{G1})^2}{2\\sigma^2}} \\label{eq:imaging:g1}\\\\\n    f_{S} (T_c) &= \\left\\{\n        \\begin{array}{lr}\n        0 & : T_c \\notin [ \\mu_{G1}, \\mu_{G2} ] \\\\\n        v & : T_c \\in    [ \\mu_{G1}, \\mu_{G2} ]\n        \\end{array}\n        \\right.\n    \\label{eq:imaging:s}\\\\\n    f_{G2}(T_c) &= \\frac{w_2}{\\sigma \\sqrt{2\\pi}}\n    e^{-\\frac{(T_c-\\mu_{G2})^2}{2\\sigma^2}} \\label{eq:imaging:g2}\n    \\end{align}\n\n\nWhile fitting to a cell cycle distribution model may\nbe sufficient to identify biological outlier cells, I use two\nadditional DNA features to further exclude low-quality\nimages of nuclei. These features\nare the nuclear area and the coefficient of variation ($cv$)\nof intra-nuclear DNA intensity.\nThe $cv$ is a rough proxy for the DNA texture,\nand so can be used to identify out-of-focus cells\n(lower $cv$) or those with chromatin condensation or\npunctate artifacts (higher $cv$). I therefore statistically\ngate the population by rejecting those cells that are too\nfar from the median of either of these features\n(see \\ar{fig:imaging:qualityControl}).\n\n\nFinally, I restrict my analyses to cells in the G1 phase\n\\arp{fig:imaging:qualityControl}.\nThe rationale for this is that I do not expect G1\nand G2 cells to have different qualitative behaviors\nfor the signaling pathways that I study in \\ar{insulation:introduction},\nthough I do expect them to have somewhat different quantitative\nbehaviors. The effect of combining these subpopulations\nwould then be a meaningless increase in apparent signaling variability.\nI therefore chose the G1 population as it is\ntypically more populated and is less prone to\ndouble-segmentation errors.\n\n\n\\subsection{Using DNA features to correct measurement error}\n\n\nBy using DNA features for quality control, we can thus collect\nall cells within the G1 and/or G2 populations that are high-quality\n(from an imaging standpoint) and accurately segmented.\nThe quality control described above may be a sufficient level of\ndata clean-up for some experimental goals, but\nit does not deal with the problem\nidentified at the top of this section: \nthat is, the separation of true biological variation from\nmeasurement error. In other words, quality control only discards\ncells that are too far from the ``typical'' cell, it does nothing\nto determine or correct the measurement error in those cells that are kept.\n\n\nTo identify biological variability, then,\nI again take advantage of the cell cycle ``ground truth.''\nAs shown in \\ar{fig:imaging:cycleFit}, the theoretical\ncell cycle distribution has no variation in the G1 or G2\npopulations, as all cells have exactly the same diploid\nor tetraploid DNA content. The observed variation\naround the theoretical values then do not carry any biological\nmeaning. (Note that this approximation becomes less accurate\nwith chromosomally-unstable cell populations.)\n\n\n\\subsubsection{Single-cell measurement error correction}\n\\label{imaging:singleCellCorrection}\n\nIf the variation in total DNA carries no biological\ninformation, then it should not be predictive of\nof other feature values: any feature dependence on\nthe DNA content must then be due to a global source\nof error. In principle, then, we can then reduce this error by \nremoving the meaningless correlations of other features to total DNA content. \n\n\n  \\begin{figure}[!bt]\n  \\centering\n  \\includegraphics[width=6in]{FIGS/imaging/singleCellNorm.pdf}\n  {\\singlespacing \n  \\caption[ Single-cell correction using DNA features.]\n            {The variation in total DNA content (within a single cell cycle peak)\n            is non-biological and therefore should not be predictive of\n            intensity values for other probes.\n            \\b{a}, Total Smad as a function of\n            total DNA. The raw data show a low\n            Pearson correlation coefficient (inset $r$ value)\n            and linear regression slope (black line),\n            which is over-corrected by\n            multiplicative normalization (middle) and\n            corrected by regression-based normalization\n            (right). \\b{b}, Comparison of single-cell values\n            before (x-axis) and after (y-axis) regresson-based\n            correction. This dataset has low correlation to\n            total DNA, and so the change is small. \n            $n=689$ human colonic epithelial cells (G1 only,\n            quality-controlled) immunostained\n            with anti-Smad2/3 (Smad) and Hoechst (DNA).\n            All $y$-axes on the same scale.}\n  \\label{fig:imaging:singleCellNorm}}\n  \\end{figure}\n\nI take two single-cell level approaches to correcting\ntotal intensity feature errors\n\\arp{fig:imaging:singleCellNorm}. The intuitive method\nis to estimate a normalization factor for e.g. all G1 cells\nusing total DNA ($T_{\\text{DNA},c}$), and then use this\nfactor to normalize the total intensity of other\nfluorescent probes ($T_{\\text{probe},c}$)\nin those same cells (\\ar{eq:imaging:dnaNorm}). Indeed,\nI have seen this approach used in the literature even\nwithout first restricting analysis to one cell cycle\nsubpopulation. This\nmethod assumes a simple multiplicative relationship\nbetween the DNA and other channels such that, for example, a 10\\%\nincrease in total DNA content would predict a 10\\%\nincrease in different total probe intensity. Note\nthat this assumption may not hold true, such that this\nmethod can cause over- or under-correction (as in\n\\ref{fig:imaging:singleCellNorm}a, middle).\n    %\n    \\begin{equation} \\label{eq:imaging:dnaNorm}\n    f_{\\text{norm}}(T_{\\text{probe},c})=\n    \\frac{\\text{median}_c(T_{\\text{DNA},c})}{T_{\\text{DNA},c}}T_{\\text{probe},c}\n    \\end{equation}\n\n    \nMy preferred method is regression-based, as it\nguarantees removal of\ncorrelation between total Hoechst and the total intensity of\nanother probe (\\ar{fig:imaging:singleCellNorm}a, right).\nFor this method, linear regression is performed to get the\nfunction in \\ar{eq:imaging:reg} with slope $m$ and intercept $b$.\nThis results in a residual value ($\\text{r}_{\\text{probe},c}$)\nfor every cell.\nThe value of each $T_{\\text{probe},c}$ can then be corrected\nby setting it equal to the median across all values plus the residual\nvalue for the same cell (\\ar{eq:imaging:regNorm}).\n    %\n    \\begin{gather}\n    T_{\\text{probe},c}=f_\\text{regression}(T_{\\text{DNA},c})=mT_{\\text{DNA},c}+\\text{r}_{\\text{probe},c}+b\n        \\label{eq:imaging:reg}\\\\\n    f_\\text{norm}(T_{\\text{probe},c}) =\n        \\text{median}_c(T_{\\text{probe},c})+\\text{r}_{\\text{probe},c}\n        \\label{eq:imaging:regNorm}\n    \\end{gather}\n\n    \nFor the sample data in \\ar{fig:imaging:singleCellNorm} it is\nclear that there is low basal correlation between total DNA\nand total Smad, though I have observed much\nhigher correlations in some datasets. I further note that this same rationale\ncould be extended to non-DNA references and other features\nfor cases in which cross-probe\ncorrelations are expected to be meaningless.\nFor all datasets in this dissertation I\napply the total DNA regression-based correction when accurate\nsingle-cell values are needed (such as for the calculation of mutual\ninformation between single-cell distributions).\n\n\n\\subsubsection{Population-level error correction}\n\n\nWhile the single-cell correction above can be used to remove\nthose measurement errors that are directly shared by each probe,\nit is reasonable to expect that much\nof measurement error is more random and so affects probes independently. Though it is\nnot possible to correct single-cell values for such\nunpredictable error, we can apply correction at the\npopulation level.\n\n\n  \\begin{figure}[!bt]\n  \\centering\n  \\includegraphics[width=4in]{FIGS/imaging/convolution.pdf}\n  {\\singlespacing \n  \\caption[ Estimating measurement error of the total intensity feature.]\n            {An observed total intensity distribution $f_\\text{observed}$\n            is the result of convolution of the true distribution\n            $f_\\text{true}$ and the measurement error $f_\\text{error}$.\n            The error function for total nuclear intensity features\n            can be estimated as having $\\sigma_\\text{error}\\approx\n            \\sigma_\\text{DNA}$.\n            Cartoon, using distributions from \\ar{fig:imaging:cycleFit}.}\n  \\label{fig:imaging:convolution}}\n  \\end{figure}\n\n\nAn observed feature distribution can be modeled as the convolution\nof a true biological distribution with a measurement error\ndistribution centered on zero, $f_{true}*f_{error}$. In the case of $\\log$-total DNA\nin G1 cells, $f_{true}$\nis a delta distribution, $\\delta_{true}$, positioned at $\\mu_{G1}$.\nI can then take advantage of\nthe property that $\\delta_{true}*f_{error}=f_{error}+\\mu_{G1}$.\nIn other words, the G1 and G2 distributions are themselves\nestimates of the measurement error distribution, if their\nmeans are set to 0\n\\arp{fig:imaging:convolution}.\n\n\nFor distributions that are log-normal, as are the total\nintensity features for all probes used in this dissertation,\nI can also use the property that two convolved normal distributions\nyield a third normal distribution with mean\n$\\mu_3=\\mu_1+\\mu_2$ and variance\n$\\sigma_3^2=\\sigma_1^2+\\sigma_2^2$.\nThus, I can estimate the ``true'' cell-to-cell\ntotal nuclear intensity variation\nfor any probe by \\ar{eq:imaging:decon}. There of course may\nbe other sources of error not compensated for in this way, and\nsuch an approach is only defensible for the total intensity feature.\n    %\n    \\begin{equation} \\label{eq:imaging:decon}\n    \\sigma_\\text{probe,true} = \\sqrt{ \\sigma_\\text{probe,observed}^2-\\sigma_\\text{DNA,error}^2 }\n    \\end{equation}\n\n    \nWhat utility does this deconvolution have? Published\nmeasurements of cell-to-cell\nvariability range from 15-30\\% \\cite{Sigal2006a},\nand my own raw data show values within\nthis same range. However, these values include measurement error\nthat is not being compensated for. Thus,\ncell-to-cell variability, as measured by microscopy, is\nnecessarily overestimated. The above reasoning shows that\nthis overestimation is simple to measure, as all that is\nneeded are the log-scale standard deviations of the G1/2\ntotal DNA distributions and the standard deviations of\nthe total-probe values in question.\n\n\nI have not performed a comprehensive\nstudy of the size of this effect, though I have measured it\nin several independent datasets for various markers. I find\nthat deconvolved total intensity distributions yield\n$\\sim10\\%$ lower standard deviations and $\\sim10\\%$ higher\ninformation content (measured by mutual information \\cite{Cheong2011}).\nThese inaccuracies are small enough that I feel comfortable\nstating that measurement errors in high-quality microscopy datasets\nare much smaller\nthan true biological variation.\n\n\nIt is important to note\nthat this DNA-based deconvolution makes the assumption\nthat the sources of error are the same between Hoechst and other probes. It is\npossible that nuclear antibody-based stains have a partially non-overlapping\nset of error sources with small molecules like Hoechst.\nOne possibility to address this, then, would be to use a\nnon-specific secondary antibody in a free channel.\nThat non-specific antibody should\nnot be correlated with the specific antibody staining in other\nchannels, and so any measured correlations could be removed using the\nsame rationale as for DNA content-based correction. Unfortunately,\nI have had limited success with this\napproach, though non-specific secondary antibodies\ndo indeed show high single-cell correlation. The problem has been that they also\nshow unexpected properties, like differences in intracellular\nlocalization, for which adequate controls are not clear.\n\n", "meta": {"hexsha": "ba5b248573c3247cbbb3f89a816c1891af73028b", "size": 19127, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "TEXT/imaging/variation.tex", "max_stars_repo_name": "adam-coster/dissertation", "max_stars_repo_head_hexsha": "4ddf35426f6ce2d83d7193dd94bd36f21b68c27d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TEXT/imaging/variation.tex", "max_issues_repo_name": "adam-coster/dissertation", "max_issues_repo_head_hexsha": "4ddf35426f6ce2d83d7193dd94bd36f21b68c27d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TEXT/imaging/variation.tex", "max_forks_repo_name": "adam-coster/dissertation", "max_forks_repo_head_hexsha": "4ddf35426f6ce2d83d7193dd94bd36f21b68c27d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.0788288288, "max_line_length": 106, "alphanum_fraction": 0.7512939823, "num_tokens": 4587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3055907023201636}}
{"text": "\\documentclass[11pt]{article}\n\n\\usepackage{framed}\n\\usepackage{float}\n\\usepackage{listings}\n\\usepackage{graphicx}\n\n\\begin{document}\n\t\\title{\\texttt{markov\\_populator.py} Documentation}\n\t\\date{\\today}\n\t\\maketitle\n\t\n\t\\section{Introduction}\n\tThis document serves to explain the algorithm behind how the script\n\t\\texttt{markov\\_populator.py} functions and how a user may use it to produce\n\tscenarios.  This script lives within the \\texttt{GOSM} library and the\n\tproper installation of the most recent version of \\texttt{GOSM} will \t\n\tcorrectly install this script. Note it may be necessary to run\n\t\\texttt{python setup.py install} again if you do not have the most recent\n\tversion installed.\n\t\n\t\\section{Algorithm}\n\tThis section will serve as a brief description how the script actually\n\tproduces scenarios. It functions by first classifying given historic data on\n\tforecasts, actuals, and errors, each historic date-time into a specific\n\tstate $S_i$. The state will generally just be an interval that a certain \n\tfield is in. For example if we have that the error at a given time is 125, \n\tthen the corresponding state might be $[100, 150]$. It might also be\n\tpreferred to specify the state by quantiles in which case the state might be\n\t$[0.2,0.4]$. In the simplest case, the state will just be an error interval,\n\tbut in separate tests, it may be useful to include the forecast interval or\n\tthe forecast derivative interval in the state.\n\tThen given this mapping of date-times to states produces a \n\ttransition matrix $A$ where $A_{ij}$ is the frequency with which state \n\t$S_j$ follows state $S_i$. Empirically we take this as the probability with\n\twhich one state will proceed another. \n\t\n\tFor each scenario on a specific day, we choose a start state for the Markov \n\tChain. To do this, we categorize the first hour of that day based on the \n\tforecast into a certain state and pick a random sample from the historically\n\tobserved states which fall into the same forecast category. Then using this\n\tstart state, we transition from state to state based on the probabilities in\n\tthe transition matrix until we have a state for all 24 hours of the day.\n\t\n\tUsing this sequence of states, we then can convert this into an 24-error \n\tvector by sampling from an empirical distribution on the error interval of\n\tthe state. This error is then added to the daily forecast which then is\n\ttruncated at 0 and the capacity of the source to complete the scenario.\n\t\n\t\\section{Input Files}\n\tThis script only requires two input files, a data file and an options file.\n\tThe data file is structured the same as is used for \\texttt{prescient} and\n\tis described here for good measure.\n\tThese files are described in turn.\n\t\n\tOnce you have both of these, with an appropriately structured options file,\n\tthe script can be executed with the command:\n\t\\begin{verbatim}\n\t\trunner.py <options_file>\n\t\\end{verbatim}\n\twhere \\texttt{<options\\_file>} is replaced by the name of the file.\n\t\n\t\\input{data.tex}\n\t\t\n\t\\subsection{Options File}\n\tThe options file specifies how you may configure behavior of the script to\n\tgenerate scenarios differently. Any option's description can be found using \n\tthe command \\texttt{python markov\\_populator.py -h}. We discuss the most\n\tcommon options here. We begin by presenting the most basic\n\texample of an options file in Figure \\ref{example1}.\n\t\n\t\\begin{figure}[H]\n\t\\begin{framed}\n\t\t\\lstinputlisting{markov_example1.txt}\n\t\\end{framed}\n\t\\label{example1}\n\t\\caption{A basic example of an options file}\n\t\\end{figure}\n\t\n\tThe first thing we note is that all options file used for executing this\n\tscript must begin with the following line verbatim:\n\t\\begin{verbatim}\n\t\tcommand/exec markov_populator.py\n\t\\end{verbatim}\n\tThis specifies to the script \\texttt{runner.py} which program to actually\n\trun.\n\t\n\tAlso contained in this script are required options for every run of \n\t\\texttt{markov\\_populator.py}. Namely, these are \\texttt{--power-source}\n\twhich specifies the data file which contains forecasts and actuals, \n\t\\texttt{--start-date} and \\texttt{--end-date} which specify the date range\n\tfor which you would like to produce scenarios, and \n\t\\texttt{--output-directory} which specifies where to store all the output\n\tfiles.\n\t\n\tIn addition, this specifies the number of scenarios to generate with the \n\t\\texttt{--number-of-scenarios} option. All other options are left to\n\tdefaults. This means that the exact specification for what a state is\n\twill simply be which interval the recorded error is in. Put more precisely,\n\tthe separate error states will be intervals of length 100 and the entire\n\tset is given by $\\{[0, 100], [100, 200], \\ldots\\}$. This specific length\n\tcan be adjusted with the \\texttt{--error-bin-size} argument. Note that the\n\tlimits of the intervals will always be multiples of this size option.\n\t\n\tAn example where the user expresses more control over the what a state\n\tactually is can be seen in Figure \\ref{example2}. Note that here, the user\n\tspecifies that they would like to use quantile intervals instead of raw\n\tenergy intervals with the \\texttt{--use-error-quantiles} option. The user\n\talso specifies the exact width of the intervals with the \n\t\\texttt{--error-quantile-size} option. This means the states will \n\tbe quantile intervals $\\{[0,0.1],[0.1,0.2],\\ldots,[0.9,1]\\}$. If the user\n\twants more control over the exact quantiles that determine the state, then\n\the may use the \\texttt{explicit-error-quantiles} option with a string\n\tspecifying the quantiles in the form \\texttt{0,0.1,0.9,1}.\n\t\n\t\\begin{figure}[H]\n\t\\begin{framed}\n\t\t\\lstinputlisting{markov_example2.txt}\n\t\\end{framed}\n\t\\caption{A more involved example of an options file}\n\t\\label{example2}\n\t\\end{figure}\n\t\n\tNote that the user also includes forecasts in the state description with\n\tthe option \\texttt{--consider-forecasts}. This just includes the interval\n\tthe forecast is in (each of size 100) in the state information. After\n\tgenerating the state walk, this will not use the forecast state though\n\tto compute the scenario, only the error state. The forecast state is just\n\tused for computing the random walk itself. There are options\n\t\\texttt{--forecast-bin-size}, \\texttt{--use-forecast-quantiles},\n\t\\texttt{--forecast-quantile-size}, \\texttt{--explicit-forecast-quantiles}\n\tand similar options for derivatives (replace 'forecast' with 'derivative' in the option) for more control over what a state is.\n\t\n\tThis options file also specifies the name of the source with \\texttt{--source-name}. This has no effect on the computation and only affects names on\n\tthe plots and data files generated.\n\t\n\tThe option \\texttt{--allow-multiprocessing} enables parallelism over the\n\tdays of scenario generation.\n\t\n\tA final example of an options file is shown in Figure \\ref{example3}. The\n\tonly new option used here is the \\texttt{--capacity} option which specifies\n\tan upper bound at which the scenarios will be truncated.\n\t\n\t\\begin{figure}[H]\n\t\\begin{framed}\n\t\t\\lstinputlisting{markov_example3.txt}\n\t\\end{framed}\n\t\\caption{A third options file}\n\t\\label{example3}\n\t\\end{figure}\n\t\n\t\\section{Output Files}\n\tFor each day of scenario generation, inside the output directory a \n\tdirectory will be created which will\n\tcontain two files. The first of which is a csv file with all produced\n\tscenarios and the second a plot of scenarios.\n\t\n\tExamples of each follow:\n\t\n\t\\begin{figure}\n\t\t\\begin{framed}\n\t\t\t\\lstinputlisting{scenarios.csv}\n\t\t\\end{framed}\n\t\\end{figure}\t\t\n\t\n\t\\begin{figure}\n\t\\includegraphics{wind.png}\n\t\\end{figure}\t\n\t\n\\end{document}", "meta": {"hexsha": "faed94a3e4501d4dcc6c9125b733c0a3a1a577a6", "size": 7517, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/markov.tex", "max_stars_repo_name": "iSoron/Prescient", "max_stars_repo_head_hexsha": "a3c1d7c5840893ff43dca48c40dc90f083292d26", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2020-06-03T13:54:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T18:20:35.000Z", "max_issues_repo_path": "doc/markov.tex", "max_issues_repo_name": "iSoron/Prescient", "max_issues_repo_head_hexsha": "a3c1d7c5840893ff43dca48c40dc90f083292d26", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 79, "max_issues_repo_issues_event_min_datetime": "2020-07-30T17:29:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T00:06:39.000Z", "max_forks_repo_path": "doc/markov.tex", "max_forks_repo_name": "bknueven/Prescient", "max_forks_repo_head_hexsha": "6289c06a5ea06c137cf1321603a15e0c96ddfb85", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2020-07-14T17:05:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T17:51:13.000Z", "avg_line_length": 44.2176470588, "max_line_length": 149, "alphanum_fraction": 0.7673273912, "num_tokens": 1927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.3055906949007384}}
{"text": "%\n% Appendix A\n%\n\n\\chapter{SVFit Mass}\n\\label{SVFit}\n\nA study has been performed to improve the next iteration of the search for LFV decays of the Higgs boson. In this study, we have observed that using the ``Classic'' SVFit (Sensitivity Volume Fit) algorithm can help improve the signal resolution compared to the collinear mass resolution~\\cite{Bianchini:2016yrt}. The ``Classic'' SVFit algorithm has been developed to reconstruct the mass of a Higgs boson decaying into two tau leptons \\mtt and is an improved version of the SVFit algorithm. The SVfit algorithm~\\cite{Bianchini:2014vza} has been used to reconstruct the Higgs boson mass in the SM \\Htt analysis and searches for further Higgs bosons predicted by models beyond the SM performed by the CMS collaboration during LHC Run 1. Compared to alternative mass variables, the SVfit algorithm's usage has improved the SM \\Htt analysis's sensitivity for measuring the signal rate by $\\approx 40\\%$~\\cite{Chatrchyan:2014nva}. The improvement in sensitivity corresponds to a gain by about a factor of two in the integrated luminosity of the analyzed dataset.\n\nThe ``Classic'' SVFit algorithm uses a likelihood function of arbitrary normalization. The algorithm allows for the reconstruction of not only the mass \\mtt of the tau lepton pair but any kinematic function of the two tau leptons, including the \\pt, $\\eta$, and $\\phi$ and transverse mass of the tau lepton pair. A further improvement concerns the algorithm's extension to account for the experimental resolution on the reconstruction of hadrons produced in the tau decays. The ``Classic'' SVFit algorithm was modified to reconstruct the mass of the Higgs boson decaying into LFV decay modes \\mlt. A brief description of the algorithm is given in the following paragraphs.\n\n\\section{``Classic'' SVfit algorithm}\nAs only one of the lepton from an LFV Higgs decay is a tau, it was modified so that the matrix element of the probability density function defined can reconstruct the Higgs mass \\mlt. The phase space of the tau decay products along with the angles $\\theta_{inv}$ and $\\phi_{inv}$ are illustrated in Figure~\\ref{fig:sv}. The $\\bp_{inv}$ vector is located on the surface of a cone, the axis of which is given by the $\\bp_{vis}$ vector. The variable $\\phi_{inv}$ represents the angle of rotation, in a counter-clockwise direction, around the cone's axis. The value $\\phi_{inv} = 0$ is chosen to correspond to the case that the $\\bp_{inv}$ vector is within the plane spanned by the $\\bp_{vis}$ vector and the beam direction.\n\n\\begin{equation}\n  \\begin{aligned}\n    \\mathcal{L}\\left(\\bp^{\\text{vis}} ; p_{\\text{x}}^{\\text{rec}}, p_{\\text{y}}^{\\text{rec}} \\mid \\mh \\right)=\\frac{32 \\pi^{4}}{s} \\int \\text{d} \\mh \\text{d} \\Phi_{n} \\left|\\text{BW}_{\\Pgt}\\right|^{2} \\left|\\mathcal{M}_{\\Pgt \\rightarrow \\ldots}(\\tilde{\\bp})\\right|^{2} \\\\\n    W\\left(\\bp^{\\text{vis}} \\mid \\hat{\\bp}^{\\text{vis}}\\right) W_{\\text{rec}}\\left(p_{\\text{x}}^{\\text{rec}}, p_{\\text{y}}^{\\text{rec}} \\mid \\hat{p}_{\\text{x}}^{\\text{rec}}, \\hat{p}_{\\text{y}}^{\\text{rec}} \\right) \\mathcal{F}(\\bp)\n  \\end{aligned}\n\\end{equation}\n\n\\begin{figure*}[!htpb]\n  \\centering\n  \\includegraphics[width=0.9\\textwidth]{plots/appendix/SV.png}\n  \\caption{Illustration of the variables $\\theta_{inv}$ and $\\phi_{inv}$ that specify the orientation of the $\\bp_{inv}$ vector relative to the momentum vector $\\bp_{vis}$ of the visible tau decay products.}\n  \\label{fig:sv}\n\\end{figure*}\n\nThe function $\\mathcal{F}(\\bp)$ in the integrand may be an arbitrary function of the momenta of the prompt and tau leptons. The integral is evaluated numerically, using a custom implementation of the Markov chain MC integration method with the Metropolis-Hastings algorithm~\\cite{Hastings:1970aa}. The actual value $\\mathcal{L}(y)$ of the integral is irrelevant. The reconstruction of the mass \\mlt of the prompt and tau lepton pair is based on choosing:\n%\n$\\mathcal{F}(\\bp) \\equiv \\left(\\hat{E}_{\\ell} + \\hat{E}_{\\Pgt}\\right)^{2} - \\left(\\left(\\hat{p}_{\\text{x}}^{\\ell}+\\hat{p}_{\\text{x}}^{\\Pgt}\\right)^{2}+\\left(\\hat{p}_{\\text{y}}^{\\ell}+\\hat{p}_{\\text{y}}^{\\Pgt}\\right)^{2}+\\left(\\hat{p}_{\\text{z}}^{\\ell}+\\hat{p}_{\\text{z}}^{\\Pgt}\\right)^{2}\\right)$,\n%\nrecording the values of $\\mathcal{F}(\\bp)$ for each evaluation of the integrand by the Markov chain and taking the median of the series of $\\mathcal{F}(\\bp)$ values as the best estimate \\mlt for the mass of the prompt and tau lepton pair in a given event. The total number of evaluations of the integrand referred to as Markov chain ``states'', amounts to 100000 per event. The first 10000 evaluations of the integrand are used as a ``burn-in'' period and are excluded from the median's computation.\n\nFigure~\\ref{fig:svfit} shows the collinear mass and SVFit mass distributions. The distributions are fit with a double Gaussian, and the goodness of fit as tested from $\\chi^2/\\text{ndof}$ is close to one, suggesting that it is a good fit. The full width at half maximum is used for inferring the signal resolution, and it has a value of 38.88~\\GeV for collinear mass, while for SVFit mass, the value is 30.90~\\GeV. This corresponds to a 20\\% improvement in signal resolution. The collinear mass and SVFit mass are peaking close to the Higgs mass of 125~\\GeV. The collinear mass has a higher mean of $\\sim 129 \\GeV$ due to its larger tail, while SVFit mass has a mean of $\\sim 117 \\GeV$ due to it's smaller tail distribution.\n\n\\begin{figure*}[!htpb]\n  \\centering\n  \\includegraphics[width=0.45\\textwidth]{plots/appendix/CollMass.png}\n  \\includegraphics[width=0.45\\textwidth]{plots/appendix/SVFit.png}\n  \\caption{Collinear mass vs SVFit mass.}\n  \\label{fig:svfit}\n\\end{figure*}\n\nThis study has shown that mass resolution is significantly improved by using the SVFit mass instead of the collinear mass, and it can give much more sensitive results for the \\Hmt and \\Het searches. A future search using the full Run 3 data can benefit from this improved sensitivity, and the SVFit can easily be extended to be used for heavy Higgs boson searches. The only disadvantage that was noted during the study was from the computing point of view. It takes an order of magnitude longer time to compute the SVFit mass than the collinear mass, which has to be investigated and improved in any future analysis.\n", "meta": {"hexsha": "67cd25dd95e35c7d47962687e9bfc1610d1ed0d3", "size": 6307, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/appendixA.tex", "max_stars_repo_name": "psiddire/nddiss", "max_stars_repo_head_hexsha": "9a7a4ae447331fb76b458374b9a3511298df309d", "max_stars_repo_licenses": ["LPPL-1.3c"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thesis/appendixA.tex", "max_issues_repo_name": "psiddire/nddiss", "max_issues_repo_head_hexsha": "9a7a4ae447331fb76b458374b9a3511298df309d", "max_issues_repo_licenses": ["LPPL-1.3c"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis/appendixA.tex", "max_forks_repo_name": "psiddire/nddiss", "max_forks_repo_head_hexsha": "9a7a4ae447331fb76b458374b9a3511298df309d", "max_forks_repo_licenses": ["LPPL-1.3c"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 137.1086956522, "max_line_length": 1057, "alphanum_fraction": 0.7490090376, "num_tokens": 1743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.30531400561872174}}
{"text": "% rubber: set program xelatex\n\n% The theme used for this presentation is matze's mtheme, which can be\n% found at https://github.com/matze/mtheme\n\n\\newif\\ifhandout\n\\newif\\ifextended\n\n\\handoutfalse\n%\\handouttrue\n\n\\extendedfalse\n%\\extendedtrue\n\n\\ifhandout\n    \\documentclass[12 pt, compress, handout, intlimits]{beamer}\n\n    \\setbeamertemplate{note page}[plain]\n\n    \\setbeameroption{show notes}% on second screen=bottom}\n\\else\n\n    \\documentclass[12 pt, compress, intlimits]{beamer}\n\n\\fi\n\n\\usetheme{metropolis}\n\n\\usepackage{mymacros}\n\\usepackage[retainorgcmds]{IEEEtrantools}\n\\setlength{\\IEEEnormaljot}{9pt}\n\n\\renewcommand{\\d}{\\operatorname{d}\\!}\n\\renewcommand{\\L}{\\mathcal{L}}\n\\renewcommand{\\B}{\\mathcal{B}}\n\\newcommand{\\inprod}[2]{\\left\\langle {#1}, {#2} \\right\\rangle}\n\\newcommand{\\conj}[1]{\\overline{#1}}\n\n\\usepackage{graphicx}\n\\usepackage{booktabs}\n\\usepackage[scale=2]{ccicons}\n\\usepackage{array}\n\\usepackage{tabularx}\n\n\\usepackage{xcolor}\n\\usepackage{mathtools}\n\\usepackage{empheq}\n\n\\renewcommand{\\tabularxcolumn}[1]{>{\\normalsize}m{#1}}\n\n\\newcommand{\\highlight}[1]{\\colorbox{mLightBrown!65}{$\\displaystyle{#1}$}}\n\\newcommand{\\mygreenbox}[1]{\\colorbox{mLightBrown!65}{\\hspace{1em}#1\\hspace{1em}}}\n\\newcommand*\\widefbox[1]{\\fbox{\\hspace{1em}#1\\hspace{1em}}}\n\n\n%\\usepgfplotslibrary{dateplot}\n\n%\\usefonttheme[onlymath]{serif}\n%\\usepackage{eulervm}\n%\\usepackage{arevmath}\n%\\renewcommand{\\vect}[1]{\\vec{#1}}\n\\renewcommand{\\L}{\\mathcal{L}}\n\\newcommand{\\ft}[1]{\\tilde{#1}}\n\\newcommand{\\rinprod}[2]{\\left\\langle {#1}, {#2} \\right\\rangle_r}\n\\newcommand{\\pinprod}[2]{\\left\\langle {#1}, {#2} \\right\\rangle_p}\n\n\\useinnertheme{circles}\n\n\\setbeamercovered{transparent}\n\n\\title{Green's functions}\n\\subtitle{A short introduction}\n\\date{\\today}\n\\author{Chris Deimert}\n\\institute{Department of Electrical and Computer Engineering, University of Calgary}\n\n\\begin{document}\n\n\\maketitle\n\n\\note{\n    \\begin{itemize}\n    \\item\n        This is intended as a short introduction to Green's functions for electrical engineers.\n    \\item\n        Basic idea of Green's functions is simple, but there is a huge amount of theory for actually calculating and using them.\n    \\item\n        We won't be able to cover much here, but we'll try to focus on building a solid foundation and understanding of Green's functions.\n    \\item\n        Suggested further reading is provided at the end.\n    \\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Outline}\n    \\tableofcontents\n\\end{frame}\n\n\\note{\n\\begin{enumerate}\n\\item\n    Basic idea of Green's functions.\n\\item\n    Simplest method for solving the Green's function equation.\n\\item\n    How to use the Green's function to solve a problem with boundary conditions. (Biggest section!)\n\\item\n    Useful properties of Green's functions for special types of problems.\n\\item\n    Summary and suggested further reading.\n\\end{enumerate}\n\n}\n\n\\section{Basic idea}\n\\label{sec:basic_idea}\n\n\\note{\n\\begin{itemize}\n\\item\n    The basic idea of Green's functions is really simple.\n    You've actually used them before!\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{What is a Green's function?}\n    \n    Linear equation to solve:\n    \\begin{align*}\n        \\L u(x) &= f(x)\n    \\end{align*}\n    \n    \\pause\n\n    Green's function is the \\textbf{impulse response}:\n    \\begin{align*}\n        \\L G(x,x') &= \\delta(x - x')\n    \\end{align*}\n\n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Most electromagnetics problems are described by linear (differential) equations with some source/driving function $ f(x) $.\n\\item\n    The Green's function is the solution when the source $ f(x) $ is set equal to an impulse (delta function) located at $ x' $.\n\\item\n    Can think of it as a generalization of the familiar impulse response from signal processing.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Why is it useful?}\n    \n    \\begin{align*}\n        \\delta(x - x') &\\xrightarrow{\\quad \\L^{-1} \\quad} G(x,x')\n    \\end{align*}\n \n    \\pause\n\n    \\begin{align*}\n        f(x) = \\int \\delta(x - x') f(x') \\d x \\xrightarrow{\\quad \\L^{-1} \\quad} \\int G(x,x') f(x') \\d x\n    \\end{align*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Once we know the Green's function for a problem, we can find the solution for any source $ f(x) $.\n\\item\n    Impulses $ \\delta(x - x') $ produce a response $ G(x,x') $.\n\\item\n    We can split the source $ f(x) $ up into a sum (integral) of impulses $ \\delta(x - x') $.\n\\item\n    Then the response to $ f(x) $ is just a weighted sum (integral) of impulse responses.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Why is it useful?}\n\n    \\begin{align*}\n        \\L u(x) &= f(x)\n    \\end{align*}\n    \\begin{align*}\n        \\L G(x,x') &= \\delta(x - x')\n    \\end{align*}\n    \\begin{empheq}[box=\\widefbox]{align*}\n        u(x) = \\int G(x,x') f(x') \\d x\n    \\end{empheq}\n    \\begin{flushright}\\scriptsize{(Some conditions apply.)}\\end{flushright}\n\n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Once we know the Green's function, we have an explicit formula for the solution $ u(x) $ for any source function $ f(x) $.\n\\item\n    Beware the fine print! \n    This formula actually only works under certain assumptions about the boundary conditions.\n\\item\n    We'll deal with the more general approach later.\n    For now, we'll use this simple version to get the key idea across.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Familiar Green's functions}\n\n    Impulse response of a linear time-invariant system:\n    \\begin{align*}\n        y(t) &= \\int_{-\\infty}^{\\infty} x(t') \\alert{h(t - t')} \\d t'\n    \\end{align*}\n\n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    In electrical engineering, we've seen Green's functions before.\n\\item\n    Impulse response $ h(t - t') $ from linear system theory is an example of a Green's function.\n    \\begin{align*}\n        G(t,t')  = h(t - t')\n    \\end{align*}\n\\item\n    Output $ y(t) $ is given by convolution of the impulse $ h(t) $ with the input $ x(t) $.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Familiar Green's functions}\n\n    Poisson's equation:\n    \\begin{align*}\n        \\nabla^2 V(\\vect{r}) &= - \\frac{\\rho(\\vect{r})}{\\epsilon_0}\n    \\end{align*}\n    \\begin{align*}\n        V(\\vect{r}) &= \\iiint \\alert{\\frac{1}{4 \\pi \\epsilon_0 \\left| \\vect{r} - \\vect{r}' \\right|}} \\rho(\\vect{r}') \\d^3 \\vect{r}'\n    \\end{align*}\n\\end{frame}\n\n\\note{\n    \\begin{itemize}\n    \\item\n        Green's function for Poisson's equation is\n        \\begin{align*}\n            G(\\vect{r}, \\vect{r}') &= \\frac{1}{4 \\pi \\epsilon_0 \\left| \\vect{r} - \\vect{r}' \\right|}\n        \\end{align*}\n    \\item\n        The Green's function is the potential created by a point (impulse) charge.\n    \\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Familiar Green's functions}\n    \n    Helmholtz equation:\n    \\begin{align*}\n        \\left( \\nabla^2 + k^2 \\right) A_z(\\vect{r}) &= -J_z(\\vect{r})\n    \\end{align*}\n    \\begin{align*}\n        A_z(\\vect{r}) &= \\iiint \\alert{\\frac{e^{-jk \\left| \\vect{r} - \\vect{r}' \\right|}}{4 \\pi \\left| \\vect{r} - \\vect{r}' \\right|}} J_z\\left( \\vect{r}' \\right) \\d^3 \\vect{r}'\n    \\end{align*}\n\\end{frame}\n\n\\note{\n    \\begin{itemize}\n    \\item\n        Green's function for the Helmholtz equation is\n        \\begin{align*}\n            G(\\vect{r}, \\vect{r}') &= \\frac{e^{-jk \\left| \\vect{r} - \\vect{r}' \\right|}}{4 \\pi \\left| \\vect{r} - \\vect{r}' \\right|}\n        \\end{align*}\n    \\item\n        The Green's function is the potential created by a point (impulse) current.\n    \\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Familiar Green's functions}\n    \n    Green's functions let us:\n    \\begin{itemize}\n    \\item\n        Derive and understand these expressions.\n    \\item\n        Generalize to other problems and boundary conditions.\n    \\end{itemize}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    With Green's function theory, we learn how to derive the above expressions and understand them a little more rigorously. (Though we won't have time to derive the 3D ones here.)\n\\item\n    In addition, Green's function theory allows us to deal with different boundary conditions.\n    The solutions to the Poisson and Helmholtz equations above assume free space (boundaries at infinity).\n    Green's functions would allow us to, e.g., find the response to a current source inside a specific waveguide.\n\\end{itemize}\n}\n\n\\section{Finding the Green's function}\n\\label{sec:finding_the_green_s_function}\n\\note{\n\\begin{itemize}\n\\item\n    In this section, we'll look at one of the simplest methods for actually solving the Green's function problem.\n\\item\n    Often called the \\emph{direct method}.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{A simple example}\n\n    Original problem:\n    \\begin{align*}\n        \\frac{\\d^2 u(x)}{\\d x^2} - k^2 u(x) &= f(x)\n    \\end{align*}\n    \n    Green's function problem:\n    \\begin{align*}\n        \\frac{\\d^2 G(x, x')}{\\d x^2} - k^2 G(x,x') &= \\delta(x - x')\n    \\end{align*}\n    \n\n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Let's start off by looking at a simple example.\n\\item\n    This problem is similar to a simple harmonic oscillator, but the negative sign means we expect lossy behaviour rather than oscillation.\n\\item\n    We won't worry much about boundary conditions yet, we'll just look for solutions that don't blow up at $ x = \\pm \\infty $.\n\\item\n    If we can find the Green's function, then we can find the solution to the original problem for any $ f(x) $.\n\\item\n    But the Green's function problem looks hard! \n    The point of this example is to demonstrate that we can actually solve it.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{A simple example}\n\n    For $ x \\neq x' $\n    \\begin{align*}\n        \\frac{\\d^2 G(x, x')}{\\d x^2} - k^2 G(x,x') &= 0\n    \\end{align*}\n    \n    \\pause\n    So we have\n    \\begin{align*}\n        G(x,x') &= \n        \\begin{cases} \n            A e^{+k (x - x')} & \\text{for } x < x'\n            \\\\\n            B e^{-k (x - x')} & \\text{for } x > x'\n        \\end{cases}\n    \\end{align*}\n    \n    \n\\end{frame}\n\n\\note{\n    \\begin{itemize}\n    \\item\n        Key thing to notice is that the source is concentrated at $ x = x' $.\n    \\item\n        So for $ x > x' $ and $ x < x' $, we expect the solutions to look like those of the source-free equation.\n    \\item\n        To keep the solutions finite, we expect exponential growth before $ x = x' $ and exponential decay afterward.\n    \\item\n        Now, how do we find the constants $ A $ and $ B $?\n    \\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{A simple example}\n\n    \\begin{align*}\n        \\frac{\\d^2 G(x,x')}{\\d x^2} - k^2 G(x,x') &= \\delta(x - x')\n    \\end{align*}\n\n    \\pause\n    Continuity of the Green's function:\n    \\begin{align*}\n        \\lim_{\\epsilon \\to 0} \\left[ G(x'+\\epsilon, x') - G(x' - \\epsilon, x') \\right] = 0\n    \\end{align*}\n\n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    How continuous do we expect our Green's function to be?\n\\item\n    If $ G(x,x') $ is discontinuous (like a step function), then $ \\d G / \\d x $ will behave like a delta function and $ \\d^2 G / \\d x^2 $ will behave like a delta function derivative. No good!\n\\item\n    So we expect $ G(x,x') $ to be continuous.\n\\item\n    That gives us one condition we can use to find $ A $ and $ B $. (In fact, it tells us that $ A = B $.)\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{A simple example}\n \n    \\begin{align*}\n        \\alt<2->{\\int_{x'-\\epsilon}^{x'+\\epsilon} \\left[ \\frac{\\d^2 G(x, x')}{\\d x^2} - k^2 G(x,x') \\right] \\d x &= \\int_{x'-\\epsilon}^{x'+\\epsilon} \\delta(x - x') \\d x}{\\frac{\\d^2 G(x, x')}{\\d x^2} - k^2 G(x,x') = \\delta(x - x')}\n    \\end{align*}\n\n    \\pause\n    \\pause\n    Discontinuity condition:\n    \\begin{align*}\n        \\lim_{\\epsilon \\to 0} \\left[ \\left. \\frac{\\d G}{\\d x}\\right|_{x = x' + \\epsilon} - \\left. \\frac{\\d G}{\\d x} \\right|_{x = x' - \\epsilon} \\right] &= 1\n    \\end{align*}\n    \n\n\\end{frame}\n\n\\note{\n    \\begin{itemize}\n    \\item\n        But what if the derivative $ \\d G / \\d x $ is discontinuous?\n    \\item\n        Then $ \\d^2 G / \\d x^2 $ is like a delta function.\n        But that's fine, because we have a delta function on the right hand side too.\n    \\item\n        We can find exactly how discontinuous the derivative is by integrating over a small interval around $ x' $.\n    \\item\n        In the limit of $ \\epsilon \\to 0 $, the second integral vanishes because $ G(x,x') $ is continuous.\n    \\item\n        The first integral is an integral of a derivative, so we can use the fundamental theorem of calculus.\n        The result is a \\emph{discontinuity condition for the derivative.}\n    \\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{A simple example}\n\n    \\begin{align*}\n        G(x,x') &= \n        \\begin{cases} \n            A e^{+k (x - x')} & \\text{for } x < x'\n            \\\\\n            B e^{-k (x - x')} & \\text{for } x > x'\n        \\end{cases}\n    \\end{align*}\n    \n    Continuity of $ G(x,x') $:\n    \\begin{align*}\n        A &= B\n    \\end{align*}\n\n    Discontinuity of $ \\dfrac{\\d G(x,x')}{\\d x} $:\n    \\begin{align*}\n        k A + k B = 1\n    \\end{align*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Applying our two conditions, we can solve for $ A $ and $ B $.\n    We find\n    \\begin{align*}\n        A = B = \\frac{1}{2 k}\n    \\end{align*}\n    \n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{A simple example}\n    Solving, our Green's function is\n    \\begin{align*}\n        G(x,x') &= \\frac{1}{2k} \n        \\begin{dcases} \n            e^{+k (x - x')} & \\text{for } x < x'\n            \\\\\n            e^{-k (x - x')} & \\text{for } x > x'\n        \\end{dcases}\n    \\end{align*}\n    Or, more compactly:\n    \\begin{empheq}[box=\\widefbox]{align*}\n        G(x, x') = \\frac{e^{k |x - x'|}}{2 k}\n    \\end{empheq}\n    \n\n\\end{frame}\n\n\\note{\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{A simple example}\n\n    Original problem:\n    \\begin{align*}\n        \\frac{\\d^2 u(x)}{\\d x^2} - k^2 u(x) &= f(x)\n    \\end{align*}\n\n    Solution:\n    \\begin{align*}\n        u(x) &= \\int_{-\\infty}^{\\infty} f(x') \\frac{e^{k|x - x'|}}{2k} \\d x'\n    \\end{align*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Now that we have the Green's function, we can construct the solution to our original problem for any forcing function $ f(x) $.\n\\item\n    Caution: remember the fine print from before. \n    This solution only works with certain assumptions about boundary conditions.\n    (More on this to come!)\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{General approach}\n\n    Direct solution:\n    \\begin{itemize}\n    \\item\n        $ G(x,x') $ obeys source-free equation for $ x \\neq x' $.\n    \\item\n        $ G(x,x') $ and its derivatives are continuous or discontinuous at $ x = x' $.\n    \\end{itemize}\n    \n\\end{frame}\n\n\\note{\n    \\begin{itemize}\n    \\item\n        Write down the source-free solution for $ x \\neq x' $: usually has a few unknown coefficients.\n    \\item\n        Examine the equation to find continuity/discontinuity requirements for $ G(x,x') $ and its derivatives.\n        (Most books on Green's functions provide these requirements for general Sturm-Liouville problems.)\n    \\item\n        This approach is great if it works.\n        Unfortunately, it doesn't always work (especially in 3D problems).\n    \\item\n        We'll briefly look at an alternative solution method later using eigenvalues and eigenfunctions, but this still just scratches the surface. \n        See the references provided at the end.\n    \\end{itemize}\n}\n\n\\section{Constructing the solution}\n\\label{sec:constructing_the_solution}\n\n\\note{}\n\n\\begin{frame}[fragile]\n    \\frametitle{Constructing the solution}\n\n    \\begin{align*}\n        u(x) &= \\int G(x,x') f(x') \\d x'\n    \\end{align*}\n    \n    \\begin{center}Can we prove/generalize this?\\end{center}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    In the introduction, we showed non-rigorously how to construct a solution from the Green's function.\n    To keep things simpler, we ignored boundary conditions.\n\\item\n    Here, we'll look at how to properly construct a solution from the Green's function when boundary conditions are involved.\n\\item\n    Our approach is quite challenging compared to a lot of books on the subject. \n    The advantage is that we'll deal with some subtleties that can otherwise lead to confusion.\n\\item\n    For approaches similar to the one in this section, see Dudley, Morse and Feshbach, or Gerlach.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Adjoint operators}\n\n    Inner product:\n    \\begin{align*}\n        \\inprod{u}{v} &= \\int_a^b u(x) \\conj{v}(x) \\d x\n    \\end{align*}\n    \n    Adjoint operator $ \\L^* $:\n    \\begin{align*}\n        \\inprod{\\L u}{v} &= \\inprod{u}{\\L^* v}\n    \\end{align*}\n   \n\n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Underpinning our approach is the idea of an adjoint operator.\n\\item\n    Start with an inner product (for 1D problems, usually the one shown).\n    Note that $ \\conj{v} $ is the complex conjugate of $ v $.\n\\item\n    If $ \\L $ is a linear operator, then its adjoint $ \\L^* $ is defined as the operator which satisfies\n    \\begin{align*}\n        \\inprod{\\L u}{v} &= \\inprod{u}{\\L^* v}\n        \\\\\n        \\Longrightarrow \\quad \\int_a^b (\\L u) v^* \\d x &= \\int_a^b u \\conj{(\\L^* v)} \\d x\n    \\end{align*}\n\\item\n    Roughly, $ \\L^* $ is what appears if we try to move $ \\L $ into the other slot of the inner product. \n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Adjoint boundary conditions}\n    \n    \\begin{align*}\n        \\inprod{\\L u}{v} &= \\inprod{u}{\\L^* v} \\longrightarrow \\text{Only for certain $ u, v $ !}\n    \\end{align*}\n\n    Adjoint boundary conditions:\n    \\begin{align*}\n        \\B_i[u] &= 0; \\qquad \\B_i^*[v] = 0\n    \\end{align*}\n    \n    Otherwise\n    \\begin{align*}\n        \\inprod{\\L u}{v} &= \\inprod{u}{\\L^* v} + \\underbrace{J(u,\\conj{v})}_{\\text{Conjunct}} \\Big|_a^b\n    \\end{align*}\n    \n\n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    The adjoint is only truly the adjoint (i.e., $ \\inprod{\\L u}{v} = \\inprod{u}{\\L^* v} $) for certain functions $ u $ and $ v $.\n    (Mathematically, when $ \\L $ and $ \\L^* $ are unbounded operators, they do not necessarily share the same \\emph{domain}, and we need to consider that.)\n\\item\n    This is where boundary conditions come in. \n    Specifically, if $ u $ obeys some boundary conditions $ \\B_i[u] = 0 $, then $ v $ has to obey some adjoint boundary conditions $ \\B_i^*[v] = 0 $.\n\\item\n    Note on notation: $ \\B_i[u] = 0 $ means that some linear combination of $ u $ and its derivatives are set equal to zero at the boundaries.\n\\item\n    If $ \\B_i[u] = 0 $ and $ \\B_i^*[v] = 0 $ are not satisfied, then the adjoint equation almost holds, but we get an extra term $ J(u,v^*) $ called the \\emph{conjunct}. It's only evaluated at the boundaries.\n\\end{itemize}\n\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Adjoint operators: example}\n    \\begin{align*}\n        \\L u(x) &= \\left[ \\frac{\\d^2}{\\d x^2} + k^2 \\right] u(x)\n    \\end{align*}\n\n    Want $ \\L^* $ so that\n    \\begin{align*}\n        \\inprod{\\L u}{v} &= \\inprod{u}{\\L^* v} + J(u, \\conj{v})\\Big|_a^b\n    \\end{align*}\n\n\\end{frame}\n\n\\note{\n    \\begin{itemize}\n    \\item\n        Let's look at an example: the 1D simple harmonic oscillator.\n    \\item\n        Let's try to find $ \\L^* $ without worrying about boundary conditions for now.\n        (So we expect the conjunct to appear.)\n    \\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Adjoint operators: example}\n    \n    \\begin{align*}\n        \\inprod{\\L u}{v} &= \\int_a^b \\left[ u'' + k^2 u \\right] \\conj{v} \\d x\n        \\\\\n        \\inprod{\\L u}{v} &= \\int_a^b \\left[ -u' \\conj{v}' + k^2 u \\conj{v} \\right] \\d x + \\left[ u' \\conj{v} \\right]_a^b\n        \\\\\n        \\inprod{\\L u}{v} &= \\int_a^b u \\left[ \\conj{v}^{\\prime\\prime} + k^2 \\conj{v} \\right] \\d x + \\left[ u' \\conj{v}  - u \\conj{v}' \\right]_{a}^{b}\n    \\end{align*}\n    \n\n\\end{frame}\n\n\\note{\n    \\begin{itemize}\n    \\item\n        To find the adjoint, let's expand $ \\inprod{\\L u}{v} $.\n    \\item\n        Use integration by parts twice.\n    \\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Adjoint operators: example}\n\n    \\begin{align*}\n        \\inprod{\\L u}{v} &= \\int_a^b u \\left[ \\conj{v}^{\\prime\\prime} + k^2 \\conj{v} \\right] \\d x + \\left[ u' \\conj{v}  - u \\conj{v}' \\right]_{a}^{b}\n    \\end{align*}\n    \n    Looks like\n    \\begin{align*}\n        \\inprod{\\L u}{v} &= \\inprod{u}{\\L^* v} + J(u, \\conj{v})\\Big|_a^b\n    \\end{align*}\n    with\n    \\begin{align*}\n        \\L^* &= \\frac{\\d^2}{\\d x^2} + \\conj{k^2}\n        \\\\[4pt]\n        J(u,\\conj{v}) &= u' \\conj{v}  - u \\conj{v}'\n    \\end{align*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    After integration by parts, we can read off the adjoint operator and the conjunct.\n\\item\n    So in this case, the adjoint operator is the almost the same as the original operator, but there's an extra complex conjugate.\n    If $ k $ is real, then $ \\L = \\L^* $.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Adjoint operators: example}\n\n    For\n    \\begin{align*}\n        \\inprod{\\L u}{v} &= \\inprod{u}{\\L^* v}\n    \\end{align*}\n    must have\n    \\begin{align*}\n        J(u,\\conj{v})\\Big|_a^b &= 0\n        \\\\\n        \\left[u' \\conj{v}  - u \\conj{v}'\\right]_a^b &= 0\n    \\end{align*}\n    \\begin{align*}\n        u'(b) \\conj{v}(b) - u(b) \\conj{v}'(b) - u'(a) \\conj{v}(a) + u(a) \\conj{v}'(a) = 0\n    \\end{align*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Now let's look at adjoint boundary conditions.\n\\item\n    For $ \\L^* $ to be a true adjoint, we need the conjunct to be zero.\n\\item\n    Let's expand the conjunct for this particular example.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Adjoint operators: example}\n\n    \\begin{align*}\n        u'(b) \\conj{v}(b) - u(b) \\conj{v}'(b) - u'(a) \\conj{v}(a) + u(a) \\conj{v}'(a) = 0\n    \\end{align*}\n\n    Boundary conditions:\n    \\begin{align*}\n        \\begin{array}{c}\n        \\B_1[u] = u(a) = 0\n        \\\\\n        \\B_2[u] = u(b) = 0\n        \\end{array}\n        \\Longrightarrow\n        \\begin{array}{c}\n        \\B^*_1[v] = v(a) = 0\n        \\\\\n        \\B^*_2[v] = v(b) = 0\n        \\end{array}\n    \\end{align*}\n\n    \\begin{align*}\n        \\B_i &= \\B_i^*\n    \\end{align*}\n    \n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Suppose we have the simple boundary conditions $ u(a) = u(b) = 0 $.\n\\item\n    Then, to make the conjunct zero, we need $ \\conj{v}(a) = \\conj{v}(b) = 0 $ or $ v(a) = v(b) = 0 $.\n\\item\n    So in this case, the adjoint boundary conditions on $ v $ are the same as the boundary conditions on $ u $.\n\\item\n    Remember what these boundary conditions mean.\n    $ \\L^* $ is the true adjoint when $ \\L $ operates on functions $ u(x) $ which are zero at $ x = a,b $ and $ \\L^* $ operates on functions $ v(x) $ which are zero at $ x = a,b $.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Adjoint operators: example}\n\n    \\begin{align*}\n        u'(b) \\conj{v}(b) - u(b) \\conj{v}'(b) - u'(a) \\conj{v}(a) + u(a) \\conj{v}'(a) = 0\n    \\end{align*}\n\n    Initial conditions:\n    \\begin{align*}\n        \\begin{array}{c}\n        \\B_1[u] = u(a) = 0\n        \\\\\n        \\B_2[u] = u'(a) = 0\n        \\end{array}\n        \\Longrightarrow\n        \\begin{array}{c}\n        \\B^*_1[v] = v(b) = 0\n        \\\\\n        \\B^*_2[v] = v'(b) = 0\n        \\end{array}\n    \\end{align*}\n\n    \\begin{align*}\n        \\B_i &\\neq \\B_i^*\n    \\end{align*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    What if we have initial conditions instead? $ u(a) = u'(a) = 0 $.\n\\item\n    Then, to make the conjunct zero, we need $ v(b) = v'(b) = 0 $.\n\\item\n    So, for initial conditions, the adjoint boundary conditions are \\emph{final} conditions.\n    $ \\B_i \\neq \\B_i^* $.\n\\end{itemize}\n}\n\n\n\\begin{frame}[fragile]\n    \\frametitle{Adjoint operators: summary}\n\n    Adjoint operator:\n    \\begin{align*}\n        \\inprod{\\L u}{v} &= \\inprod{u}{\\L^* v}\n    \\end{align*}\n    Adjoint boundary conditions:\n    \\begin{align*}\n        \\begin{array}{c} \\B_i[u] = 0 \\\\ \\B^*_i[v] = 0 \\end{array} \\Longrightarrow J(u,\\conj{v})\\Big|_a^b = 0\n    \\end{align*}\n    Otherwise:\n    \\begin{align*}\n        \\inprod{\\L u}{v} &= \\inprod{u}{\\L^* v} + J(u,\\conj{v}) \\Big|_a^b\n    \\end{align*}\n    \n    \n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    The adjoint operator satisfies $ \\inprod{\\L u}{v} = \\inprod{u}{\\L^* v} $.\n\\item\n    This only works for certain $ u,v $, though.\n    Specifically, it works when $ u $ obeys boundary conditions and $ v $ obeys adjoint boundary conditions.\n\\item\n    If $ u,v $ do not satisfy these boundary conditions, then $ \\L^* $ is not truly the adjoint anymore.\n    However, it still nearly obeys the adjoint equation; there's just a leftover conjunct term which depends on the boundary values of $ u, v $ and their derivatives.\n\\item\n    For a lot of things (e.g., using eigenfunction bases) we need this conjunct to be zero.\n    But for Green's functions, it will end up being indispensible.\n\\end{itemize}\n\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{The adjoint Green's function}\n \n    Original problem:\n    \\begin{IEEEeqnarray*}{rClCrCl}\n        \\L u(x) &=& f(x); &\\qquad& \\B_i [u(x)] &=& \\alpha_i\n    \\end{IEEEeqnarray*}\n    Green's problem:\n    \\begin{IEEEeqnarray*}{rClCrCl}\n        \\L G(x,x') &=& \\delta(x - x'); &\\qquad& \\B_i [G(x,x')] &=& 0\n    \\end{IEEEeqnarray*}\n    Adjoint Green's problem:\n    \\begin{IEEEeqnarray*}{rClCrCl}\n        \\L^* H(x,x') &=& \\delta(x - x'); &\\qquad& \\B_i^* [H(x,x')] &=& 0\n    \\end{IEEEeqnarray*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Now we'll be able to deal with boundary conditions properly.\n\\item\n    We define $ G(x,x') $ to obey the same equation as $ u(x) $, but with $ f(x) \\to \\delta(x - x') $ and $ \\alpha_i \\to 0 $.\n    As before, $ G(x,x') $ is the impulse response.\n\\item\n    In addition, we define a new function $ H(x,x') $ which is called the adjoint Green's function.\n    It obeys the adjoint version of the $ G(x,x') $ equation.\n\\item\n    Warning! A lot of textbooks don't distinguish between $ H(x,x') $ and $ G(x,x') $.\n    Sometimes the ``Green's function'' in an expression is really the adjoint Green's function.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Constructing solutions: derivation}\n\n    \\begin{align*}\n        \\inprod{\\L u(x)}{H(x,x')} &= \\inprod{u(x)}{\\L^* H(x,x')} + J\\big(u(x), \\conj{H}(x,x')\\big) \\Big|_a^b\n        \\\\\n        \\inprod{f(x)}{H(x,x')} &= \\inprod{u(x)}{\\delta(x - x')} + J\\big(u(x), \\conj{H}(x,x')\\big) \\Big|_a^b\n        \\\\\n        \\int_a^b f(x) H^*(x,x') \\d x &= \\int_a^b u(x) \\delta(x - x') \\d x + J\\big(u(x), \\conj{H}(x,x')\\big) \\Big|_a^b\n    \\end{align*}\n    \\begin{empheq}[box=\\widefbox]{align*}\n        u(x') &= \\int_a^b f(x) \\conj{H}(x,x') \\d x - J\\big(u(x), \\conj{H}(x,x')\\big) \\Big|_a^b\n    \\end{empheq}\n    \n\\end{frame}\n\n\\note{\n    \\begin{itemize}\n    \\item\n        To construct the solution $ u(x) $, we take an inner product of $ \\L u(x) $ with $ H(x,x') $, and apply our knowledge of adjoints and conjuncts.\n    \\item\n        Then, we use the fact that $ \\L u(x) = f(x) $ and $ \\L H(x,x') = \\delta(x - x') $.\n    \\item\n        After evaluating the inner product terms, we arrive at a fairly general formula which looks somewhat like what we had in the introduction.\n        The difference is that it involves the \\emph{adjoint} Green's function $ H(x,x') $, and it has an extra conjunct term.\n    \\item\n        We'll deal with the conjunct later.\n        For now, let's try to get rid of $ H(x,x') $ and express $ u(x) $ in terms of $ G(x,x') $.\n        To do that, we need a relationship between $ H(x,x') $ and $ G(x,x') $.\n    \\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Constructing solutions: derivation}\n\n    How are $ G(x,x') $ and $ H(x,x') $ related?\n    \\begin{align*}\n        \\inprod{\\L G(x,x')}{H(x,x'')} &= \\inprod{G(x,x')}{\\L^* H(x,x'')}\n        \\\\\n        \\inprod{\\delta(x - x')}{H(x,x'')} &= \\inprod{G(x,x')}{\\delta(x - x'')}\n        \\\\\n        \\int_a^b \\delta(x - x') \\conj{H}(x,x'') \\d x &= \\int_a^b G(x,x') \\delta(x - x'') \\d x\n        \\\\\n        \\conj{H}(x',x'') &= G(x'',x')\n    \\end{align*}\n    \\begin{empheq}[box=\\widefbox]{align*}\n        G(x,x') = \\conj{H}(x',x)\n    \\end{empheq}\n    \n\\end{frame}\n\n\\note{\n    \\begin{itemize}\n    \\item\n        Using the definition of the adjoint problem, we find that there is a simple relationship between $ G(x,x') $ and $ H(x,x') $.\n    \\item\n        Note, in the last example, we had to include the conjunct because $ \\B[u] \\neq 0 $.\n        The boundary conditions and adjoint boundary conditions have to be set to zero to eliminate the conjunct.\n        In this case, $ \\B[G] = 0 $ and $ \\B[H] = 0 $, so the conjunct is eliminated.\n    \\item\n        Also note a surprising result of this: if $ G(x,x') $ obeys the boundary conditions with respect to $ x $, then it automatically obeys the \\emph{adjoint} boundary conditions with respect to $ x' $. \n        We'll come back to this idea later.\n    \\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Constructing solutions: derivation}\n\n    \\begin{align*}\n        u(x') &= \\int_a^b f(x) \\conj{H}(x,x') \\d x - J\\big(u(x), \\conj{H}(x,x')\\big) \\Big|_a^b\n    \\end{align*}\n    \\begin{center}and\\end{center}\n    \\begin{align*}\n        G(x,x') = \\conj{H}(x',x)\n    \\end{align*}\n    \\begin{center}so\\end{center}\n    \\begin{empheq}[box=\\widefbox]{align*}\n        u(x) &= \\int_{a}^{b} f(x') G(x,x') \\d x' - J\\big( u(x'), G(x,x') \\big) \\Big|_{x'=a}^b\n    \\end{empheq}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Let's go back to our expression for $ u(x') $ in terms of $ H(x,x') $.\n\\item\n    Using our new relationship $ G(x,x') = \\conj{H}(x,x') $, we can rewrite this as an expression for $ u(x) $ in terms of $ G(x,x') $.\n    (Note: we switched $ x $ and $ x' $ to make it look a little nicer.)\n\\item\n    So this is the more correct version of what we saw in the introduction.\n    If the conjunct happens to be zero, then we get what we had before.\n    If not, we have an extra term that depends only on the boundaries.\n\\item\n    In general, the conjunct term deals with the boundary conditions of $ u(x) $.\n    It turns out that the boundary conditions act, in some way, like additional sources.\n    We'll look more closely at this now through an example.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Example: 1D Poisson equation}\n\n    Original problem:\n    \\begin{align*}\n        \\frac{\\d^2 V(x)}{\\d x^2} &= - \\frac{\\rho(x)}{\\epsilon_0}; \\quad \\begin{array}{c} V(a) = V_a \\\\ V(b) = V_b \\end{array}\n    \\end{align*}\n    \n    Green's problem:\n    \\begin{align*}\n        \\frac{\\d^2 G(x,x')}{\\d x^2} &= \\delta(x - x'); \\quad \\begin{array}{c} G(a,x') = 0 \\\\ G(b,x') = 0 \\end{array}\n    \\end{align*}\n\n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Let's look at a simple 1D voltage problem.\n\\item\n    We have both a charge density $ \\rho $ inside the region $ a < x < b $, and we have an applied voltage at the boundaries.\n    Intuitively, both of these will affect the voltage in the region.\n\\item\n    In the Green's function problem, we turn the charge density into an impulse function, and we set the applied voltage to zero.\n\\end{itemize}\n}\n\n\n\\begin{frame}[fragile]\n    \\frametitle{Example: 1D Poisson equation}\n\n    Solution:\n    \\begin{align*}\n        V(x) &= \\int_{a}^{b} - \\frac{\\rho(x')}{\\epsilon_0} G(x,x') \\d x' - J\\big( V(x'), G(x,x') \\big) \\Big|_{x'=a}^b\n    \\end{align*}\n\n    Take $ \\rho(x) = 0 $ for now.\n    \\begin{align*}\n        V(x) &= - J\\big( V(x'), G(x,x') \\big) \\Big|_{x'=a}^b\n    \\end{align*}\n\n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    From our recent results, we can write down the solution for $ V(x) $ in terms of the Green's function.\n\\item\n    Take $ \\rho = 0 $ so that we can focus on the boundary conditions for now.\n\\end{itemize}\n\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Example: 1D Poisson equation}\n\n    Can show\n    \\begin{align*}\n        \\inprod{\\L u}{v} &= \\int_a^b u'' \\conj{v} \\d x = \\int_a^b u \\conj{v}'' \\d x + \\left[ u' \\conj{v} - u \\conj{v}' \\right]_a^b\n    \\end{align*}\n    \n    Comparing with\n    \\begin{align*}\n        \\inprod{\\L u}{v} &= \\inprod{u}{\\L^* v} + J(u,\\conj{v}) \\big|_a^b\n    \\end{align*}\n    we see\n    \\begin{align*}\n        \\L^* &= \\frac{\\d^2}{\\d x^2} = \\L\n        \\\\[4pt]\n        J(u,\\conj{v}) &= u' \\conj{v} - u \\conj{v}'\n    \\end{align*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    To write the solution more explicitly, we need to find the conjunct of the operator $ \\L = \\d^2 / \\d x^2 $.\n\\item\n    As before, use integration by parts and compare with the expected formula.\n\\end{itemize}\n\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Example: 1D Poisson equation}\n\n    \\begin{IEEEeqnarray*}{rCl}\n        V(x) &=& - J\\big( V(x'), G(x,x') \\big) \\Big|_{x'=a}^b\n        \\\\[8pt]\n        V(x) &=& \\left[ V(x') \\frac{\\d G(x,x')}{\\d x'} - \\frac{\\d V(x')}{\\d x'} G(x,x') \\right]_{x'=a}^b\n        \\\\[8pt]\n        V(x) &=& V_b \\frac{\\d G(x,b)}{\\d x'} - \\frac{\\d V(b)}{\\d x'} G(x,b) -\n        \\\\[4pt] && - V_a \\frac{\\d G(x,a)}{\\d x'} + \\frac{\\d V(a)}{\\d x'} G(x,a)\n    \\end{IEEEeqnarray*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Now that we know the conjunct, we can write the solution for $ V(x) $ more explicitly.\n\\item\n    Problem: we don't know $ \\d V / \\d x $ at the boundaries.\n\\item\n    The adjoint problem saves us, because we can show that $ G(x,b) = G(x,a) = 0 $.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Example: 1D Poisson equation}\n\n    Green's problem:\n    \\begin{align*}\n        \\frac{\\d^2 G(x,x')}{\\d x^2} &= \\delta(x - x'); \\quad \\begin{array}{c} G(a,x') = 0 \\\\ G(b,x') = 0 \\end{array}\n    \\end{align*}\n    \n    \n    Adjoint Green's problem:\n    \\begin{align*}\n        \\frac{\\d^2 H(x,x')}{\\d x^2} &= \\delta(x - x'); \\quad \\begin{array}{c} H(a,x') = 0 \\\\ H(b,x') = 0 \\end{array}\n    \\end{align*}\n\n    But $ G(x,x') = \\conj{H}(x',x) $ so\n    \\begin{align*}\n        \\frac{\\d^2 \\conj{G}(x,x')}{\\d x^{\\prime 2}} &= \\delta(x - x'); \\quad \\begin{array}{c} G(x,a) = 0 \\\\ G(x,b) = 0 \\end{array}\n    \\end{align*}\n\n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Back to the adjoint Green's equation.\n\\item\n    Because of the relationship between $ G(x,x') $ and $ H(x,x') $ we see that $ G^*(x,x') $ obeys the adjoint equation with respect to $ x' $.\n\\item\n    More importantly, we see that $ \\conj{G}(x,x') $ (and thus $ G(x,x') $) obeys the adjoint boundary conditions with respect to $ x' $.\n\\item\n    So not only do we have $ G(a,x') = G(b,x') = 0 $, we also have $ G(x,a) = G(x,b) = 0 $.\n    This is not a trivial or obvious result (at least to me).\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Example: 1D Poisson equation}\n    \n    \\begin{IEEEeqnarray*}{rCl}\n        V(x) &=& V_b \\frac{\\d G(x,b)}{\\d x'} - \\frac{\\d V(b)}{\\d x'} G(x,b) -\n        \\\\[4pt] && - V_a \\frac{\\d G(x,a)}{\\d x'} + \\frac{\\d V(a)}{\\d x'} G(x,a)\n    \\end{IEEEeqnarray*}\n    With $ G(x,a) = G(x,b) = 0 $, we have\n    \\begin{empheq}[box=\\widefbox]{align*}\n        V(x) &= V_b \\frac{\\d G(x,b)}{\\d x'} - V_a \\frac{\\d G(x,a)}{\\d x'} \n    \\end{empheq}\n    \n\n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Using the fact that $ G(x,x') $ obeys the adjoint boundary conditions with respect to $ x' $, we can eliminate the unknown values and simplify our result.\n\\item\n    Now we have an explicit solution for $ V(x) $ given any boundary conditions $ V(a) = V_a $ and $ V(b) = V_b $.\n\\item\n    Further, we see that the solution only depends on the Green's function.\n    It's as if the non-zero boundary conditions $ V_a, V_b $ act like additional sources whose response is given by the Green's function.\n\\end{itemize}\n\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Example: 1D Poisson equation}\n    \n    Full solution with $ \\rho(x) $:\n    \\begin{align*}\n        \\Aboxed{V(x) = \\int_a^b - \\frac{\\rho(x')}{\\epsilon_0} G(x,x') \\d x' + V_b \\frac{\\d G(x,b)}{\\d x'} - V_a \\frac{\\d G(x,a)}{\\d x'}}\n    \\end{align*}\n\n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Putting back our charge distribution $ \\rho(x) $, we get a full solution for any charge distribution and boundary conditions.\n\\item\n    The first part gives the voltage produced by the charge distribution $ \\rho(x) $.\n    The last two parts give the voltage produced by the boundary conditions $ V_a, V_b $.\n\\item\n    The response to \\emph{both} of these sources of voltage is given by the Green's function!\n\\item\n    For those familiar with the derivative of the delta function, this can be written in an even more suggestive form:\n    \\begin{align*}\n        V(x) &= \\int_a^b \\left[ - \\frac{\\rho(x)}{\\epsilon_0} - V_b \\delta'(x' - b) + V_a \\delta'(x' - a) \\right] G(x,x') \\d x'\n    \\end{align*}\n    \n\\end{itemize}\n\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Solving problems with Green's functions}\n    \\begin{align*}\n        \\text{Given:} \\quad \\L u(x) = f(x); \\quad \\B_i[u(x)] = \\alpha_i\n    \\end{align*}\n    \\vspace{-12pt}\n    \\begin{enumerate}\n    \\item\n        Solve Green's problem\n        \\begin{align*}\n            \\L G(x,x') = \\delta(x - x'); \\quad \\B_i[G(x,x')] = 0\n        \\end{align*}\n    \\item\n        Find $ \\L^* $, $ \\B_i^* $, and $ J(u,\\conj{v}) $ from $ \\inprod{\\L u}{v} $.\n    \\item\n        Solution is\n        \\begin{align*}\n            u(x) &= \\int_{a}^{b} f(x') G(x,x') \\d x' - J\\big( u(x'), G(x,x') \\big) \\Big|_{x'=a}^b\n        \\end{align*}\n    \\item\n        Simplify using $ \\B^*[G(x,x')] = 0 $ (with respect to $ x' $).\n    \\end{enumerate}\n    \n\\end{frame}\n\n\\note{\nNow let's look at the general process for solving a boundary value problem with a source.\n\\begin{enumerate}\n\\item\n    Set up the Green's function equation by setting the source to $ \\delta(x - x') $ and the boundary conditions to zero.\n    Solve this to find the Green's function.\n\\item\n    Find $ \\L^* $, $ \\B_i^* $, and $ J(u,\\conj{v}) $ by expanding the inner product $ \\inprod{\\L u}{v} $ (usually using integration by parts).\n\\item\n    Write down the solution.\n\\item\n    Unknown boundary values of $ u(x) $ will appear in the conjunct term.\n    Eliminate them using the fact that $ G(x,x') $ obeys the adjoint boundary conditions with respect to $ x' $.\n\\end{enumerate}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Solving 3D problems with Green's functions}\n \n    \\begin{align*}\n        \\text{Given:} \\quad \\L u(\\vect{r}) = f(\\vect{r}); \\quad \\B_i[u(\\vect{r})] = \\alpha_i\n    \\end{align*}\n    \\vspace{-12pt}\n    \\begin{enumerate}\n    \\item\n        Solve Green's problem\n        \\begin{align*}\n            \\L G(\\vect{r},\\vect{r}') = \\delta(\\vect{r} - \\vect{r}'); \\quad \\B_i[G(\\vect{r},\\vect{r}')] = 0\n        \\end{align*}\n    \\item\n        Find $ \\L^* $, $ \\B^* $, and $ J(u,\\conj{v}) $ from $ \\inprod{\\L u}{v} $.\n    \\item\n        Solution is\n        \\begin{align*}\n            u(\\vect{r}) &= \\int_{V} f(\\vect{r}') G(\\vect{r},\\vect{r}') \\d^3 \\vect{r}' - \\oint_{\\partial V} \\vect{J}\\big( u(\\vect{r}'), G(\\vect{r},\\vect{r}') \\big) \\cdot \\d \\vect{s}\n        \\end{align*}\n    \\item\n        Simplify using $ \\B^*[G(\\vect{r},\\vect{r}')] = 0 $ (with respect to $ \\vect{r}' $).\n    \\end{enumerate}\n       \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Great thing about our approach is that it's easily extended to 3D. \n\\item\n    Inner product is now a volume integral over the region of interest ($ V $).\n    Have to use 3D versions of integration by parts (e.g., Green's identities) to find $ \\L^* $, $ J(u,\\conj{v}) $ and $ \\B_i^* $.\n\\item\n    The conjunct is now vector-valued, and it must be integrated over the surface of $ V $ (denoted $ \\partial V $).\n\\item\n    Still have the same interpretation though.\n    The first (volume) integral is the contribution from the source $ f(\\vect{r}) $.\n    The second (surface) integral is the contribution from the non-zero boundary conditions.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Constructing the solution}\n    Comments:\n    \\begin{itemize}\n    \\item\n        Calculating Green's functions is not trivial.\n    \\item\n        Adjoint approach is difficult, but offers clarity.\n    \\end{itemize}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Step 1 of our approach (calculate the Green's function) can be difficult: especially in 3D.\n    Learning these techniques is time-consuming, but we now have a solid foundation with which to understand them.\n\\item\n    Our approach was not the easiest, but note the critical role played by the adjoint, both in the derivation and the final solution method.\n\\item\n    Though some authors don't talk about adjoints, they still use these ideas.\n    E.g., often the ``Green's function'' used in 3D problems is actually the \\emph{adjoint} Green's function. (Can be confusing!)\n\\end{itemize}\n}\n\n\\section{Special properties}\n\\label{sec:special_properties}\n\n\\note{\n\\begin{itemize}\n\\item\n    The behaviour of the Green's function is shaped by the type of problem we're trying to solve.\n\\item\n    In this section, we'll see how a lot of properties of problems are tied to properties of the Green's function.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Self-adjointness}\n\n    If $ \\L = \\L^* $ and $ \\B_i = \\B_i^* $, then\n    \\begin{align*}\n        G(x,x') &= \\conj{G}(x',x)\n    \\end{align*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Self-adjointness is equivalent to conjugate symmetry of the Green's function.\n\\item\n    If a problem is self-adjoint, then the adjoint Green's function $ H(x,x') $ is the same as the Green's function $ G(x,x') $.\n    Then, using a result from before, we find that $ G(x,x') = \\conj{G}(x,x') $.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Reciprocity}\n    \n    Reciprocity in the frequency-domain:\n    \\begin{align*}\n        G(\\vect{r}, \\vect{r}') &= G(\\vect{r}', \\vect{r})\n    \\end{align*}\n\n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    The notion of reciprocity in electromagnetism can be tied to this property of the Green's function.\n\\item\n    In the frequency-domain, the Green's function is symmetric under interchange of $ \\vect{r}, \\vect{r}' $ (no complex conjugate!).\n    It can be shown that this is equivalent to reciprocity.\n    (See Collin for a more thorough discussion using dyadic Green's functions.)\n\\item\n    Mathematically, frequency-domain reciprocity is related to the pseudo-inner product\n    \\begin{align*}\n        \\pinprod{u}{v} &= \\iiint u(\\vect{r}) v(\\vect{r}) \\d^3 \\vect{r}\n    \\end{align*}\n    and operators which are ``self-adjoint'' under it:\n    \\begin{align*}\n        \\pinprod{\\L u}{v} &= \\pinprod{u}{\\L v}\n    \\end{align*}\n    \n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Reciprocity}\n\n    \\vspace{14pt}\n    Reciprocity in the time-domain:\n    \\begin{align*}\n        G(\\vect{r}, t; \\vect{r}', -t') &= G(\\vect{r}', t'; \\vect{r}, -t)\n    \\end{align*}\n    \\vspace{-26pt}\n    \\begin{figure}\n        \\centering\n    \\includegraphics[width=0.9\\textwidth]{Reciprocity.pdf}\n    \\end{figure}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    In the time-domain, the Green's function is symmetric, but with an added minus sign on the time variables.\n    This is because of causality (see Morse and Feshbach).\n\\item\n    Think of $ G(\\vect{r}, t; \\vect{r}', t') $ as having an impulse at $ (\\vect{r}', t') $ and measuring it at $ (\\vect{r}, t) $.\n    Then reciprocity shows that interchanging sources and measurements leads to identical results.\n\\item\n    Mathematically, time-domain reciprocity related to the pseudo-inner product\n    \\begin{align*}\n        \\pinprod{u}{v} &= \\int \\iiint u(\\vect{r}, t) v(\\vect{r}, -t) \\d^3 \\vect{r} \\d t\n    \\end{align*}\n    and operators which are ``self-adjoint'' under it:\n    \\begin{align*}\n        \\pinprod{\\L u}{v} &= \\pinprod{u}{\\L v}\n    \\end{align*}\n    \n\\end{itemize}\n\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Causality}\n\n    Causality:\n    \\begin{align*}\n        G(\\vect{r}, t; \\vect{r}', t') = 0 \\quad \\text{for } t < t'\n    \\end{align*}\n\n    Special relativity:\n    \\begin{align*}\n        G(\\vect{r}, t; \\vect{r}', t') = 0 \\quad \\text{for } \\left| \\vect{r} - \\vect{r}' \\right| > c (t - t')\n    \\end{align*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    The Green's function can tell us if a system is causal or not.\n\\item\n    Causality means that an effect cannot precede a cause, so the impulse response (Green's function) cannot appear before the impulse itself.\n    I.e., the Green's function has to be zero for $ t < t' $.\n\\item\n    In special relativity, causality means that information cannot propagate faster than light.\n    There is a corresponding restriction on the Green's function.\n\\item\n    Compare these causal Green's function with the Green's function for a self-adjoint problem: they are incompatible.\n    So we cannot have a causal system which is also self-adjoint in time.\n%\\item\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Symmetry and invariance}\n    \n    Time-invariance:\n    \\begin{align*}\n        G(t,t') &= G(t - t')\n    \\end{align*}\n\n    Spatial-invariance:\n    \\begin{align*}\n        G(\\vect{r},\\vect{r}') &= G(\\vect{r} - \\vect{r}')\n    \\end{align*}\n\n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    A time-invariant system is one whose behaviour doesn't change over time.\n    That is, if we delay our input, we'll get the exact same output, just delayed by an equal amount.\n\\item\n    In that case, can show that the Green's function only depends on the difference between $ t $ and $ t' $.\n    (See Gerlach.)\n\\item\n    Recall: in linear time-invariant (LTI) systems, the impulse response is written as $ h(t - t') $: this is why!\n\\item\n    A similar thing applies to systems whose behaviour doesn't change from place to place.\n\\item\n    These properties can make it easier to find the Green's function (e.g., the free-space wave equation).\n    Also, solution is just given by convolution $ u(t) = G(t) * f(t) $.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Spectral theory}\n\n    \\begin{align*}\n        (\\L - \\lambda) u(x) &= f(x); \\quad \\B[u] = 0\n    \\end{align*}\n\n    If $ \\L = \\L^* $ and $ \\B = \\B^* $ then\n    \\begin{align*}\n        u(x) &= \\sum_n \\frac{\\inprod{f}{\\phi_n}}{\\lambda_n - \\lambda} \\phi_n(x)\n    \\end{align*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    For a self-adjoint problem, we can write out the solution as a sum of eigenfunctions of $ \\L $, where $ \\L \\phi_n(x) = \\lambda_n \\phi_n(x) $.\n\\item\n    With some work (not shown), we can directly write out the solution in terms of $ f(x) $ as a generalized Fourier series.\n    $ \\inprod{f}{\\phi_n} $ are the projections of $ f $ onto the normalized eigenfunction basis.\n\\item\n    (Technically, we're also assuming here that $ \\L $ is a \\emph{bounded} linear operator.\n    Unbounded operators have continuous sets of eigenvalues, and the theory behind them is more delicate.\n    See, e.g., Naylor and Sell's \\emph{Linear operator theory in engineering and science} or Kreyszig's \\emph{Introductory functional analysis with applications.})\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Spectral theory}\n\n    \\begin{align*}\n        u(x) &= \\int_a^b \\left( \\sum_n \\frac{\\phi_n(x) \\phi^*_n(x')}{\\lambda_n - \\lambda} \\right) f(x') \\d x'\n    \\end{align*}\n\n    \\begin{align*}\n        G(x,x') &= \\sum_n \\frac{\\phi_n(x) \\phi_n^*(x)}{\\lambda_n - \\lambda}\n    \\end{align*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    We can rewrite the last solution, and read off the Green's function.\n\\item\n    So we can write down the Green's function directly if we know the eigenfunctions/eigenvalues!\n\\item\n    It's not the nicest form because we have to sum an infinite series.\n    Finding a closed-form version like we did before would be preferable, but in 3D separation of variable problems, we won't usually have a choice.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Spectral theory}\n    \n    Green's function of $ (\\L - \\lambda) $:\n    \\begin{align*}\n        G(x,x';\\lambda) &= \\sum_n \\frac{\\phi_n(x) \\phi_n^*(x)}{\\lambda_n - \\lambda}\n    \\end{align*}\n\n    \\begin{align*}\n        \\lambda_n & \\longrightarrow \\text{ Poles of } G(x,x';\\lambda)\n        \\\\\n        \\phi_n(x) \\phi^*_n(x') & \\longrightarrow \\text{ Residues of } G(x,x';\\lambda)\n    \\end{align*}\n    \n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    We can also get the eigenvalues/eigenfunctions from the Green's function!\n\\item\n    Specifically, we need to know the Green's function of $ \\L - \\lambda $ for $ \\lambda \\in \\mathbb{C} $.\n\\item\n    The eigenvalues are simply the poles of $ G(x, x'; \\lambda) $ with respect to $ \\lambda $.\n\\item\n    The eigenfunctions $ \\phi_n(x) $ are more difficult, but if there are no repeated eigenvalues, then they can be found from the residues of $ G(x,x';\\lambda) $ at $ \\lambda = \\lambda_n $.\n\\item\n    Important point is that the Green's function can tell us a lot about spectral quantities.\n\\end{itemize}\n\n}\n\n\n\\section{Conclusion}\n\\label{sec:conclusion}\n\n\\note{}\n\n\\begin{frame}[fragile]\n    \\frametitle{Takeaways}\n    \n    \\begin{itemize}\n    \\item\n        Green's function is the impulse response.\n    \\item\n        Finding Green's function:\n        \\begin{itemize}\n        \\item\n            Source-free behaviour for $ x \\neq x' $.\n        \\item\n            Continuity/discontinuity requirements at $ x = x' $.\n        \\end{itemize}\n    \\item\n        Constructing solutions:\n        \\begin{itemize}\n        \\item\n            Systematic method using adjoint equation.\n        \\item\n            Non-zero boundary conditions behave like sources.\n        \\end{itemize}\n    \\item\n        Lots of information in the Green's function.\n    \\item\n        Green's functions $ \\Longleftrightarrow $ eigenvalues/eigenfunctions.\n    \\end{itemize}\n    \n\n\\end{frame}\n\n\\note{}\n\n\\begin{frame}[fragile]\n    \\frametitle{Further reading}\n\n    Dudley (1994), \\emph{Mathematical foundations for electromagnetic theory}.\n    Great introduction to 1D Green's functions: deals with subtleties that others ignore.\n\n    Gerlach (2010), \\emph{Linear mathematics in infinite dimensions}.\n    Nice set of online course notes for quick reference.\n \n    Balanis (2012), \\emph{Advanced engineering electromagnetics}. \n    Not very rigorous, but decent for getting the key ideas.\n\n    Morse and Feshback, \\emph{Methods of theoretical physics}.\n    Big, detailed reference. \n    Great resource for deeper insight and understanding.\n  \n\\end{frame}\n\n\\note{}\n\n\\begin{frame}[fragile]\n    \\frametitle{Further reading}\n    Collin (1990), \\emph{Field theory of guided waves}. \n    Huge chapter on Green's functions. \n    Emphasis on dyadics.\n\n    Folland (1992), \\emph{Fourier analysis and its applications}. \n    Rigorous math book. \n    Chapter on generalized functions is particularly nice.\n\n    Byron and Fuller (1992), \\emph{Mathematics of classical and quantum physics}.\n    Interesting alternative approach.\n\n    Warnick (1996), ``Electromagnetic Green functions using differential forms.''\n    For the differential forms inclined.\n\n\\end{frame}    \n\n\\note{}\n\n\\ifextended\n\\section{Bonus sections!}\n\\note{\n\\begin{itemize}\n\\item\n    These bonus slides were removed from the original presentation, which was far too long.\n\\item\n    The wave-equation derivation is somewhat unique, piecing together different ideas from different places.\n    One weakness with many derivations is that they discard the ``anti-causal'' Green's function in a seemingly arbitrary way.\n    In this derivation, causality automatically follows because initial conditions are used.\n\\item\n    The generalized function section is interesting because it shows how to rigorously deal with the delta function. \n    We use the delta function so frequently, yet we rarely see a proper definition.\n\\end{itemize}\n\n}\n\n\\section*{Spectral methods}\n\\label{sec:spectral_methods}\n\n\\note{\n\\begin{itemize}\n\\item\n    In this section, we'll look at the strong relationship between Green's functions and spectral theory.\n\\item\n    Essentially, eigenfunction expansion allows us to calculate the Green's function when direct methods don't work.\n\\item\n    A basic background in spectral theory can be found in most books covering Green's functions. \n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Eigenfunction expansion}\n\n    Problem:\n    \\begin{align*}\n        \\left( \\L - \\lambda \\right)u(x) &= f(x); \\qquad \\B[u(x)] = 0\n    \\end{align*}\n    where $ \\L $ is self-adjoint:\n    \\begin{align*}\n        \\L = \\L^* \\quad \\text{and} \\quad \\B = \\B^*\n    \\end{align*}\n    \n\\end{frame}\n\n\\note{\n    \\begin{itemize}\n    \\item\n        First we'll review a bit of eigenfunction theory, but we'll quickly see how it relates to Green's functions.\n    \\item\n        Set up a problem similar to before, but we've added a complex parameter $ \\lambda $ for later convenience.\n    \\item\n        For this section we'll insist that $ \\L $ be fully self-adjoint so that we can take full advantage of spectral theory.\n        (A brief discussion of the non-self-adjoint case can be found in Morse and Feshbach.)\n    \\item\n        Technically, we're also assuming here that $ \\L $ is a \\emph{bounded} linear operator.\n        Unbounded operators have continuous sets of eigenvalues, and the theory behind them is much more delicate.\n        See, e.g., Naylor and Sell's \\emph{Linear operator theory in engineering and science} or Kreyszig's \\emph{Introductory functional analysis with applications.}\n    \\end{itemize}\n    \n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Eigenfunction expansion}\n    \n    Eigenfunctions:\n    \\begin{align*}\n        \\L \\phi_n(x) &= \\lambda_n \\phi_n(x)\n    \\end{align*}\n    \n    Since $ \\L $ is self-adjoint,\n    \\begin{align*}\n        u(x) &= \\sum_n \\inprod{u}{\\phi_n} \\phi_n(x)\n        \\\\\n        f(x) &= \\sum_n \\inprod{f}{\\phi_n} \\phi_n(x)\n    \\end{align*}\n\n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Since $ \\L $ is self-adjoint, we know that it has a complete orthonormal set of eigenfunctions $ \\phi_n $.\n\\item\n    That is, we can expand any function (in this case $ u(x) $ and $ f(x) $) in terms of $ \\phi_n(x) $. (Generalized Fourier series.)\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Eigenfunction expansion}\n\n    \\begin{align*}\n        (\\L - \\lambda)u(x) &= f(x)\n        \\\\\n        (\\L - \\lambda) \\left[ \\sum_n \\inprod{u}{\\phi_n} \\phi_n(x) \\right] &= \\sum_n \\inprod{f}{\\phi_n} \\phi_n(x)\n        \\\\\n        \\sum_n \\inprod{u}{\\phi_n} (\\lambda_n - \\lambda) \\phi_n(x) &= \\sum_n \\inprod{f}{\\phi_n} \\phi_n(x)\n        \\\\\n        (\\lambda_n - \\lambda) \\inprod{u}{\\phi_n} &= \\inprod{f}{\\phi_n}\n    \\end{align*}\n    \n\\end{frame}\n\n\\note{\n    \\begin{itemize}\n    \\item\n        Going back to our original equation, let's expand $ u(x) $ and $ f(x) $ in terms of eigenfunctions of $ \\L $.\n    \\item\n        Using the fact that $ \\L $ is linear and $ \\L \\phi_n = \\lambda_n \\phi_n $, we can get rid of $ \\L $ (third line).\n    \\item\n        Finally, since the $ \\phi_n(x) $ are linearly independent, each term in the sums on the RHS and LHS must be equal.\n        So we get an expression for the generalized Fourier coefficients $ \\inprod{u}{\\phi_n} $.\n    \\end{itemize}\n    \n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Eigenfunction expansion}\n\n    \\begin{align*}\n        \\inprod{u}{\\phi_n} &= \\frac{\\inprod{f}{\\phi_n}}{\\lambda_n - \\lambda}\n    \\end{align*}\n\n    So\n    \\begin{align*}\n        u(x) &= \\sum_n \\inprod{u}{\\phi_n} \\phi_n(x)\n        \\\\\n        \\Aboxed{u(x) &= \\sum_n \\frac{\\inprod{f}{\\phi_n}}{\\lambda_n - \\lambda} \\phi_n(x)}\n    \\end{align*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Plugging in our new expression for the Fourier coefficients, we obtain a formula for $ u(x) $ in terms of the eigenfunctions and eigenvalues of $ \\L $.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Eigenfunction expansion}\n\n    \\vspace{-16pt}\n    \\begin{align*}\n        u(x) &= \\sum_n \\frac{\\inprod{f}{\\phi_n}}{\\lambda_n - \\lambda} \\phi_n(x)\n        \\\\\n        u(x) &= \\sum_n \\left( \\int_a^b \\frac{f(x') \\phi^*_n(x')}{\\lambda_n - \\lambda} \\d x' \\right) \\phi_n(x)\n        \\\\\n        u(x) &= \\int_a^b \\left( \\alert{\\sum_n \\frac{\\phi_n(x) \\phi^*_n(x')}{\\lambda_n - \\lambda} } \\right) f(x') \\d x'\n    \\end{align*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Usually, the inner product is defined by an integral.\n\\item\n    If we write this out and do some manipulation, we get something that looks a lot like the Green's function expression.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Spectral form of the Green's function}\n    \n    \\begin{align*}\n        u(x) &= \\int_a^b \\left( \\sum_n \\frac{\\phi_n(x) \\phi^*_n(x')}{\\lambda_n - \\lambda} \\right) f(x') \\d x'\n    \\end{align*}\n\n    \\begin{empheq}[box=\\widefbox]{align*}\n        G(x,x') &= \\sum_n \\frac{\\phi_n(x) \\phi^*_n(x')}{\\lambda_n - \\lambda}\n    \\end{empheq}\n    \n\\end{frame}\n\n\\note{\n    \\begin{itemize}\n    \\item\n        This sum really is the Green's function.\n    \\item\n        So, if we know the eigenvalues and eigenfunctions of $ \\L $, we can immediately construct the Green's function as an infinite series.\n    \\item\n        Note also that $ G(x,x') = G^*(x,x') $, as we expect because this is a self-adjoint problem.\n    \\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Spectral form of the Green's function}\n\n    Green's function of $ (\\L - \\lambda) $:\n    \\begin{align*}\n        G(x,x',\\lambda) &= \\sum_n \\frac{\\phi_n(x) \\phi^*_n(x')}{\\lambda_n - \\lambda}\n    \\end{align*}\n\n    $ \\lambda_n $ are poles of $ G(x,x',\\lambda) $.\n\n    $ \\phi_n(x) $ can be found by residue integration.\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    It also goes the other way. If we know the Green's function of $ (\\L - \\lambda) $ for any complex $ \\lambda $, then the eigenvalues of $ \\L $ are just the poles of the Green's function with respect to lambda.\n\\item\n    Eigenfunctions are a little trickier to read off, but it's possible to find them from the Green's function using residue integration.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Spectral form of the delta function}\n\n    \\begin{align*}\n        \\delta(x - x') &= (\\L - \\lambda) G(x,x') \n        \\pause\n        \\\\\n        \\delta(x - x') &= (\\L - \\lambda) \\sum_n \\frac{\\phi_n(x) \\phi^*_n(x')}{\\lambda_n - \\lambda}\n        \\pause\n        \\\\\n        \\delta(x - x') &= \\sum_n \\frac{(\\lambda_n - \\lambda) \\phi_n(x) \\phi^*_n(x')}{\\lambda_n - \\lambda}\n        \\pause\n        \\\\\n        \\Aboxed{\\delta(x - x') &= \\sum_n \\phi_n(x) \\phi^*_n(x')}\n    \\end{align*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Using our Green's function equation, we can also derive an expression for the delta function as a sum of eigenfunctions.\n\\item\n    This expression is useful when solving three-dimensional problems with separation of variables.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Example: simple harmonic oscillator}\n\n    \\begin{align*}\n        \\underbrace{\\left( \\frac{\\d^2}{\\d x^2} - \\lambda \\right)}_{\\displaystyle \\L - \\lambda} u(x) = f(x); \\quad u(0) = u(a) = 0\n    \\end{align*}\n\n    Eigenfunctions of $ \\L $:\n    \\begin{align*}\n        \\phi_n(x) &= \\sqrt{\\frac{2}{a}} \\sin\\left( \\frac{\\pi n x}{a} \\right); \\quad \\lambda_n = \\frac{\\pi n}{a}\n    \\end{align*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Let's do a simple example to illustrate the idea.\n\\item\n    For $ \\L = \\d^2/\\d x^2 $ we know that the eigenfunctions are sines and cosines.\n    The boundary conditions restrict us to just sines with $ \\lambda_n = \\pi n / a $.\n\\item\n    $ \\sqrt{2/a} $ ensures that the eigenfunctions are normalized.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Example: simple harmonic oscillator}\n    \n    \\begin{align*}\n        G(x,x') &= \\sum_n \\frac{\\phi_n(x) \\phi_n^*(x')}{\\lambda_n - \\lambda}\n        \\\\\n        G(x,x') &= \\sum_{n=0}^{\\infty} \\frac{2 \\sin\\Big( \\dfrac{\\pi n x}{a} \\Big)\\sin\\Big( \\dfrac{\\pi n x'}{a} \\Big)}{\\pi n - \\lambda a}\n    \\end{align*}\n\n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Using the formula we derived earlier, we can very quickly write out the Green's function as an infinite series.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Example: simple harmonic oscillator}\n\n    \\begin{align*}\n        G(x,x') &= \\sum_{n=0}^{\\infty} \\frac{2 \\sin\\Big( \\dfrac{\\pi n x}{a} \\Big)\\sin\\Big( \\dfrac{\\pi n x'}{a} \\Big)}{\\pi n - \\lambda a}\n    \\end{align*}\n \n    Compare with direct method:\n    \\begin{align*}\n    G(x,x') &= \\begin{cases} \\frac{\\sin\\left(\\sqrt{\\lambda}(a - x')\\right) \\sin\\left(\\sqrt{\\lambda} x\\right)}{\\sqrt{\\lambda} \\sin\\left(\\sqrt{\\lambda} a\\right)} & \\text{for } x < x' \\\\ \\frac{\\sin\\left(\\sqrt{\\lambda} x'\\right) \\sin\\left(\\sqrt{\\lambda}(a - x)\\right)}{\\sqrt{\\lambda} \\sin\\left(\\sqrt{\\lambda} a\\right)} & \\text{for } x > x' \\end{cases}\n    \\end{align*}\n       \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    We could have also solved this problem directly (Assume $ G(x,x') $ behaves like the source-free solution except at $ x = x' $. Apply the boundary conditions, continuity and discontinuity requirements to find the coefficient.) The result is shown.\n\\item\n    The direct solution is a little uglier, but it's much easier to evaluate numerically because it doesn't involve an infinite series.\n    For that reason, direct solution is usually more desireable if it actually works. \n    However, series solutions tend to be needed for solving multi-dimensional problems.\n\\item\n    Note: there's a trick for evaluating infinite series using residue calculus, and (I think) you could use this to derive the second expression from the first. You can also use residue integration to derive the first from the second.\n\\end{itemize}\n\n}\n\n\\section*{3D wave equation}\n\\label{sec:3d_wave_equation}\n\n\\note{\n\\begin{itemize}\n\\item\n    To get a taste of 3D problems, let's look at the 3D scalar wave equation in a vacuum.\n\\item\n    We'll use the time-domain because it's something that's less-frequently covered in electrical engineering books.\n\\item\n    The time domain also gives insight to some delicate issues of causality which are less clear in the frequency domain.\n\\end{itemize}\n\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{The wave equation problem}\n\n    \\begin{align*}\n        \\underbrace{\\left( \\nabla^2 - \\frac{1}{c^2} \\frac{\\partial^2}{\\partial t^2} \\right)}_{\\displaystyle \\L} u(\\vect{r}, t) &= f(\\vect{r}, t); \\qquad \\B[u] = \\alpha\n    \\end{align*}\n\n    In electromagnetism:\n    \\begin{align*}\n        \\left( \\nabla^2 - \\frac{1}{c^2} \\frac{\\partial^2}{\\partial t^2} \\right) \\vect{A}(\\vect{r}, t) &= - \\vect{J}(\\vect{r}, t)\n    \\end{align*}\n    \n\n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    The wave equation is a key component of electromagnetism. \n    Most of this course was spent learning different ways to solve the Helmholtz equation, which is just a Fourier transformed version of the wave equation.\n\\item\n    In the time domain (in the Lorentz gauge), each component of the vector potential $ \\vect{A} $ obeys the scalar wave equation, with a component of $ \\vect{J} $ as its source.\n\\item\n    We can solve a huge number of electromagnetics problems if we can solve the scalar wave equation (or the scalar Helmholtz equation).\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{The adjoint wave equation}\n\n    Find $ \\L $, $ \\L^* $, $ \\B $ and $ \\B^* $ so that\n    \\begin{align*}\n        \\inprod{\\L u}{v} &= \\inprod{u}{\\L^* v}\n    \\end{align*}\n    where\n    \\begin{align*}\n        \\inprod{u}{v} = \\int_{t_i}^{t_f} \\int_V u(\\vect{r}, t) \\conj{v}(\\vect{r}, t) \\d^3 \\vect{r} \\d t\n    \\end{align*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    To construct $ u(\\vect{r},t) $ in terms of the Green's function, we proceed similar to the 1D case.\n\\item\n    The first step is to find the adjoint operators and adjoint boundary conditions for the wave equation.\n\\item\n    Before our inner product was an integral over the single variable $ x $.\n    Now, it's an integral over all four variables $ x, y, z, t $.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{The adjoint wave equation}\n\n    \\vspace{-24pt}\n    \\begin{align*}\n        \\inprod{\\L u}{v} &= \\int_{t_i}^{t_f} \\int_V \\left( \\nabla^2 u - \\frac{1}{c^2} \\frac{\\partial^2 u}{\\partial t^2} \\right) \\conj{v} \\d^3 \\vect{r} \\d t\n    \\end{align*}\n    \n    Use Green's identity\n    \\begin{align*}\n        \\int_V \\left( \\conj{v} \\nabla^2 u - u \\nabla^2 \\conj{v} \\right) &= \\oint_{\\partial V} \\left( \\conj{v} \\frac{\\partial u}{\\partial n} - u \\frac{\\partial \\conj{v}}{\\partial n} \\right) \\d S\n    \\end{align*}\n    and integration by parts\n    \\begin{align*}\n        \\int_{t_i}^{t_f} \\left( \\frac{\\partial^2 u}{\\partial t^2} \\conj{v} - u \\frac{\\partial^2 \\conj{v}}{\\partial t^2} \\right) \\d t &= \\left[ \\conj{v} \\frac{\\partial u}{\\partial t} - u \\frac{\\partial \\conj{v}}{\\partial t} \\right]_{t_i}^{t_f}\n    \\end{align*}\n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    To find $ \\L^* $ and $ \\B^* $, we write out $ \\inprod{\\L u}{v} $ and then try to rewrite it in the form $ \\inprod{u}{\\L^* v} $ using theorems from calculus.\n\\item\n    Green's identity is essentially a 3D version of the integration by parts that we used in the 1D case.\n    Note that $ V $ is a volume and $ \\partial V $ is the boundary of that volume.\n\\item\n    We use Green's identity to deal with the spatial derivative part $ \\conj{v} \\nabla^2 u $.\n\\item\n    We use 1D integration by parts to deal with the time derivative part.\n\\end{itemize}\n\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{The adjoint wave equation}\n\n    Result:\n    \\begin{IEEEeqnarray*}{rCl}\n        \\int_{t_i}^{t_f} \\int_V \\left( \\L u \\right) \\conj{v} \\d^3 \\vect{r} \\d t &=& \\int_{t_i}^{t_f} \\int_V u \\conj{\\left( \\L v \\right)} \\d^3 \\vect{r} \\d t + \n        \\\\ && + \\int_{t_i}^{t_f} \\oint_{\\partial V} \\left( \\conj{v} \\frac{\\partial u}{\\partial n} - u \\frac{\\partial \\conj{v}}{\\partial n} \\right) \\d S \\d t - \n        \\\\ && - \\frac{1}{c^2} \\left[ \\int_{V} \\left( \\conj{v} \\frac{\\partial u}{\\partial t} - u \\frac{\\partial \\conj{v}}{\\partial t} \\right) \\d V \\right]_{t_i}^{t_f}\n    \\end{IEEEeqnarray*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Not pretty! Important thing is that it's similar to what we had in the 1D case.\n\\item\n    The first term is $ \\inprod{\\L u}{v} $ and the second term is $ \\inprod{u}{\\L v} $.\n    So, for the wave equation $ \\L = \\L^* $.\n\\item\n    The last two terms are just a big ugly conjunct.\n    The first one depends only on the spatial boundary conditions ($ \\partial V $ is the boundary of the volume $ V $), while the second one depends only on the temporal boundary conditions.\n\\item\n    Given boundary conditions on $ u $, the adjoint boundary conditions are the ones that make these last two terms go to zero.\n    E.g., if $ u(\\vect{r}, t) = 0 $ over the whole boundary, then we would need $ v(\\vect{r}, t) = 0 $ over the whole boundary as well to cancel out the second-last integral.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Green's problems}\n\n    Original problem:\n    \\begin{align*}\n        \\L u(\\vect{r}, t) &= f(\\vect{r}, t); \\quad \\B[u] = \\alpha\n    \\end{align*}\n    Green's problem:\n    \\begin{align*}\n        \\L G(\\vect{r}, t; \\vect{r}', t') &= \\delta^3(\\vect{r} - \\vect{r}') \\delta(t - t'); \\quad \\B[G] = 0\n    \\end{align*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Set up the Green's function problem.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Solution to the wave equation}\n\n    \\begin{IEEEeqnarray*}{rCl}\n        u(\\vect{r}, t) &=& \\int_{t_i}^{t_f} \\int_{V'} f(\\vect{r}', t') G(\\vect{r}, t; \\vect{r}', t') \\d^3 \\vect{r}' \\d t' + \n        \\\\ && - \\int_{t_i}^{t_f} \\oint_{\\partial V'} \\left( G \\frac{\\partial u}{\\partial n'} - u \\frac{\\partial G}{\\partial n'} \\right) \\d S' \\d t' - \n        \\\\ && + \\frac{1}{c^2} \\left[ \\int_{V'} \\left( G \\frac{\\partial u}{\\partial t'} - u \\frac{\\partial G}{\\partial t'} \\right) \\d V' \\right]_{t_i}^{t_f}\n    \\end{IEEEeqnarray*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Write down the solution using the conjunct. (Can derive this using inner products, similar to what we did in 1D).\n\\item\n    The first integral gives the effect of the source term $ f(\\vect{r}, t) $.\n\\item\n    The second integral gives the effect of the boundary conditions on $ u $.\n\\item\n    The third integral gives the effect of the initial conditions on $ u $.\n\\item\n    Note that $ G(\\vect{r}, t; \\vect{r}', t') $ obeys the boundary conditions with respect to $ \\vect{r}, t $ and the \\emph{adjoint} boundary conditions with respect to $ \\vect{r}', t' $.\n    Use this for a given problem to simplify the last two terms.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Finding the Green's function}\n\n    \\begin{align*}\n        \\left( \\nabla^2 - \\frac{1}{c^2} \\frac{\\partial^2}{\\partial t^2} \\right) G(\\vect{r}, t; \\vect{r}', t') &= \\delta^3(\\vect{r} - \\vect{r}') \\delta(t - t')\n    \\end{align*}\n\n    Initial conditions:\n    \\begin{align*}\n        G(\\vect{r}, 0; \\vect{r}', t') &= \\left. \\frac{\\partial G(\\vect{r},t; \\vect{r}', t')}{\\partial t} \\right|_{t = 0} = 0\n    \\end{align*}\n    \n    Boundary conditions:\n    \\begin{align*}\n        \\lim_{|\\vect{r}| \\to \\infty} G(\\vect{r}, t; \\vect{r}', t') &\\to 0\n    \\end{align*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Now let's look at how we can actually solve the Green's function problem.\n\\item\n    We'll assume that we have an initial condition problem, and that we are interested in all of space (boundaries are at infinity).\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Finding the Green's function}\n\n    Translation invariance:\n    \\begin{align*}\n        G(\\vect{r}, t; \\vect{r}', t') &= G(\\vect{r} - \\vect{r}', t - t')\n    \\end{align*}\n\n    Let $ \\vect{R} = \\vect{r} - \\vect{r}' $ and $ \\tau = c(t - t') $ so that \n    \\begin{align*}\n        \\left( \\nabla_R^2 - \\frac{\\partial^2}{\\partial \\tau^2} \\right) G(\\vect{R}, \\tau) &= \\delta^3(\\vect{R}) \\delta(\\tau)\n    \\end{align*}\n\n   \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Because the wave equation is translation invariant, we can simplify the Green's function to make the problem easier to solve.\n\\item\n    We define new variables $ \\vect{R} = \\vect{r} - \\vect{r}' $ and $ \\tau = t - t' $.\n\\item\n    Note that $ \\nabla^2 $ is the laplacian with respect to $ \\vect{R} $.\n\\end{itemize}\n\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Finding the Green's function}\n    \n    \\begin{align*}\n        \\left( \\nabla_R^2 - \\frac{\\partial^2}{\\partial \\tau^2} \\right) G(\\vect{R}, \\tau) &= \\delta^3(\\vect{R}) \\delta(\\tau)\n    \\end{align*}\n\n    Spatial Fourier transform:\n    \\begin{align*}\n        \\left( k^2 - \\frac{\\partial^2}{\\partial \\tau^2} \\right) \\ft{G}(\\vect{k}, \\tau) &= \\delta(\\tau)\n    \\end{align*}\n    so\n    \\begin{align*}\n        \\ft{G}(\\vect{k},\\tau) &= \n        \\begin{cases}\n            A \\cos(k \\tau) + B\\sin(k \\tau) & \\text{for } \\tau < 0\n            \\\\\n            C \\cos(k \\tau) + D\\sin(k \\tau) & \\text{for } \\tau > 0\n        \\end{cases}\n    \\end{align*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Apply the spatial Fourier transform:\n    \\begin{align*}\n        \\ft{G}(\\vect{k}, \\tau) &= \\iiint_{\\mathbb{R}^3} G(\\vect{R}, \\tau) e^{- j \\vect{k} \\cdot \\vect{R} } \\d^3 \\vect{R}\n    \\end{align*}\n\\item\n    This reduces it to a 1D initial condition problem in time.\n\\item\n    Solve this using the fact that $ \\ft{G}(\\vect{k},\\tau) $ obeys the source-free equation except at $ \\tau = 0 $.\n\\end{itemize}\n\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Finding the Green's function}\n\n    \n    \\begin{align*}\n        \\ft{G}(\\vect{k},\\tau) &= \n        \\begin{cases}\n            A \\cos(k \\tau) + B\\sin(k \\tau) & \\text{for } \\tau < 0\n            \\\\\n            C \\cos(k \\tau) + D\\sin(k \\tau) & \\text{for } \\tau > 0\n        \\end{cases}\n    \\end{align*}\n    \n    \\begin{itemize}\n    \\item\n        Initial conditions give $ A = B = 0 $.\n    \\item\n        Continuity at $ t = t' $ gives $ C = 0 $.\n    \\item\n        Discontinuity at $ t = t' $ gives $ D = -1/k $.\n    \\end{itemize}\n\n    \\begin{align*}\n        \\ft{G}(\\vect{k},\\tau) &= %- \\frac{\\sin(k \\tau)}{k} U(\\tau)\n        \\begin{cases}\n            0 & \\text{for } \\tau < 0\n            \\\\\n            -\\dfrac{\\sin(k \\tau)}{k} & \\text{for } \\tau > 0\n        \\end{cases}\n    \\end{align*}\n\n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Apply initial conditions and continuity requirements to find the coefficients.\n\\item\n    To apply initial conditions: $ \\ft{G}(\\vect{k}, \\tau) $ and its derivative must be zero when $ t = 0 $ or $ \\tau = -c t' $.\n    Remember that that we are only seeking a solution for $ t > 0 $, and so $ t' > 0 $.\n\\end{itemize}\n\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Finding the Green's function}\n\n    Inverse Fourier transform for $ \\tau > 0 $:\n    \\begin{align*}\n        G(\\vect{R},\\tau) &= \\frac{1}{8 \\pi^3} \\int_{\\mathbb{R}^3} \\ft{G}(\\vect{k},\\tau) e^{j \\vect{k} \\cdot \\vect{R}} \\d^3 \\vect{k}\n        \\\\\n        G(\\vect{R},\\tau) &= \\frac{-1}{8 \\pi^3} \\int_{\\mathbb{R}^3} \\frac{\\sin(k \\tau)}{k} e^{j \\vect{k} \\cdot \\vect{R}} \\d^3 \\vect{k}\n    \\end{align*}\n\n    Use spherical coordinates in $ \\vect{k} $: $ (k, \\theta, \\phi) $.\n    \\begin{align*}\n        G(\\vect{R},\\tau) &= \\frac{-1}{8 \\pi^3} \\int_0^{2 \\pi} \\int_0^\\pi \\int_0^\\infty \\frac{\\sin(k \\tau)}{k} e^{j k R \\cos(\\theta)} k^2 \\sin(\\theta) \\d k \\d \\theta \\d \\phi\n    \\end{align*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    To recover the Green's function from $ \\ft{G}(\\vect{k}, \\tau) $, apply an inverse Fourier transform.\n    (Only really need to do it for $ \\tau > 0 $: just remember that $ G = 0 $ for $ \\tau < 0 $.)\n\\item\n    Use spherical coordinates in $ \\vect{k} $-space to evaluate the integral.\n    Define $ k = \\left| \\vect{k} \\right| $.\n    Define $ \\theta $ as the angle between $ \\vect{k} $ and $ \\vect{R} $ so that $ \\vect{k} \\cdot \\vect{R} = k R \\cos(\\theta) $.\n    Define $ \\phi $ as the remaining angle required to complete the coordinate system.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Finding the Green's function}\n    \n    \\begin{align*}\n        G(\\vect{R},\\tau) &= \\frac{-1}{8 \\pi^3} \\int_0^{2 \\pi} \\int_0^\\pi \\int_0^\\infty \\frac{\\sin(k \\tau)}{k} e^{j k R \\cos(\\theta)} k^2 \\sin(\\theta) \\d k \\d \\theta \\d \\phi\n        \\\\\n        G(\\vect{R},\\tau) &= \\frac{-1}{4 \\pi^2} \\int_0^\\infty k \\sin(k \\tau) \\left[ \\int_0^\\pi \\sin(\\theta) e^{j k R \\cos(\\theta)} \\d \\theta \\right] \\d k\n        \\\\\n        G(\\vect{R},\\tau) &= \\frac{-1}{4 \\pi^2} \\int_0^\\infty k \\sin(k \\tau) \\left[ \\frac{2 \\sin(k R)}{k R} \\right] \\d k\n        \\\\\n        G(\\vect{R},\\tau) &= \\frac{-1}{2 \\pi^2 R} \\int_0^\\infty \\sin(k \\tau) \\sin(k R) \\d k\n    \\end{align*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Do the $ \\theta $ and $ \\phi $ integrals.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Finding the Green's function}\n\n    \\begin{align*}\n        G(\\vect{R},\\tau) &= \\frac{-1}{2 \\pi^2 R} \\int_0^\\infty \\sin(k \\tau) \\sin(k R) \\d k\n        \\\\\n        G(\\vect{R},\\tau) &= \\frac{-1}{4 \\pi^2 R} \\int_{-\\infty}^\\infty \\sin(k \\tau) \\sin(k R) \\d k\n        \\\\\n        G(\\vect{R},\\tau) &= \\frac{-1}{4 \\pi^2 R} \\int_{-\\infty}^\\infty \\left( \\frac{e^{j k \\tau} - e^{-j k \\tau}}{2 j}\\right) \\left( \\frac{e^{j k R} - e^{-j k R}}{2j}\\right) \\d k\n        \\\\\n        G(\\vect{R},\\tau) &= \\frac{1}{16 \\pi^2 R} \\int_{-\\infty}^\\infty \\left( e^{j k (\\tau + R)} - e^{-j k (\\tau - R)} - e^{j k (\\tau - R)} + e^{-j k (\\tau + R)} \\right) \\d k\n    \\end{align*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Note that $ \\sin(k\\tau) \\sin(k R) $ is even with respect to $ k $.\n    So we can divide by 2 and take the integral over $ - \\infty < k < \\infty $.\n\\item\n    Then, write out the complex exponentials.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Finding the Green's function}\n    \n    \\begin{align*}\n        G(\\vect{R},\\tau) &= \\frac{1}{16 \\pi^2 R} \\int_{-\\infty}^\\infty \\left( e^{j k (\\tau + R)} - e^{-j k (\\tau - R)} - e^{j k (\\tau - R)} + e^{-j k (\\tau + R)} \\right) \\d k\n        \\\\\n        G(\\vect{R},\\tau) &= \\frac{1}{16 \\pi^2 R} 2 \\pi \\left[ \\delta(\\tau + R) - \\delta(\\tau - R) - \\delta(\\tau - R) + \\delta(\\tau + R) \\right]\n    \\end{align*}\n    But $ \\tau > 0 $ and $ R > 0 $ so $ \\delta(\\tau + R) = 0 $ and we have\n    \\begin{align*}\n        G(\\vect{R},\\tau) &= \\frac{- \\delta(\\tau - R)}{4 \\pi R}\n    \\end{align*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Use the identity\n    \\begin{align*}\n        \\int_{-\\infty}^{\\infty} e^{j k \\xi} \\d k &= 2 \\pi \\delta (\\xi)\n    \\end{align*}\n\\item\n    Note that $ \\tau > 0 $ (otherwise $ G = 0 $, from before) and $ R = \\left| \\vect{r} - \\vect{r}' \\right| > 0 $.\n    So $ \\delta(\\tau + R) = 0 $.\n\\item\n    Reducing, we obtain the Green's function for $ \\tau > 0 $.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Green's function for the wave equation}\n    \n    \\begin{align*}\n    G(\\vect{r}, t; \\vect{r}', t') &= \\begin{cases} - \\frac{\\delta\\left( c(t - t') - \\left| \\vect{r} - \\vect{r'} \\right| \\right)}{4 \\pi \\left| \\vect{r} - \\vect{r}' \\right|} & \\text{for } t > t' \\\\ 0 & \\text{for } t < t' \\end{cases}\n    \\end{align*}\n\n    With zero boundary/initial conditions:\n    \\begin{align*}\n        u(\\vect{r}, t) &= \\int_{t_i}^{t_f} \\int_{\\mathbb{R}^3} G(\\vect{r}, t; \\vect{r}', t') f(\\vect{r}', t') \\d^3 \\vect{r}' \\d t'\n        \\\\\n        u(\\vect{r}, t) &= \\int_{\\mathbb{R}^3} \\frac{-f\\left(\\vect{r}, t - \\frac{|\\vect{r} - \\vect{r}'|}{c}\\right)}{4 \\pi |\\vect{r} - \\vect{r}'|} \\d^3 \\vect{r'}\n    \\end{align*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Plug back in expressions for $ \\tau $ and $ R $: we obtain the full Green's function for the wave equation.\n\\item\n    Assuming the boundary/initial conditions are zero, the conjunct terms cancel.\n\\item\n    We are left with an integral formula for $ u(\\vect{r}, t) $.\n\\item\n    Note that, because of the delta function, the integral over time disappears.\n    We are left with the so-called ``retarded'' expression for $ u(\\vect{r}, t) $.\n\\item\n    Essentially, when measuring a response at $ (\\vect{r}, t) $, we only ``see'' the source as it appeared at $ t - |\\vect{r} - \\vect{r}'|/c $.\n    I.e., there is a speed of light delay in the propagation of information!\n\\end{itemize}\n\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Vector potential: initial condition problem}\n    \n    \\begin{align*}\n        \\left( \\nabla^2 - \\frac{1}{c^2} \\frac{\\partial^2}{\\partial t^2} \\right) \\vect{A}(\\vect{r}, t) &= - \\vect{J}(\\vect{r}, t)\n    \\end{align*}\n    \n    For initial conditions, we have the ``retarded potential'':\n    \\begin{align*}\n        \\vect{A}(\\vect{r}, t) &= \\int_{\\mathbb{R}^3} \\frac{\\vect{J}\\left(\\vect{r}, t - \\frac{|\\vect{r} - \\vect{r}'|}{c}\\right)}{4 \\pi |\\vect{r} - \\vect{r}'|} \\d^3 \\vect{r'}\n    \\end{align*}\n\n    \\begin{align*}\n        \\ft{\\vect{A}}(\\vect{r}, \\omega) &= \\int_{\\mathbb{R}^3} \\ft{\\vect{J}}\\left(\\vect{r}, \\omega \\right) \\frac{e^{- j \\frac{\\omega}{c} | \\vect{r} - \\vect{r}' |}}{4 \\pi |\\vect{r} - \\vect{r}'|} \\d^3 \\vect{r'}\n    \\end{align*}\n    \n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Concrete example is the vector potential, which obeys the wave equation with the current density $ \\vect{J} $ as its source. (In the Lorentz gauge.)\n\\item\n    Note, the time-dependent vector potential is the same as the static vector potential, but the source is just evaluated with a speed-of-light delay!\n\\item\n    Taking a Fourier transform, we get the expression from Harrington.\n\\end{itemize}\n\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Vector potential: final value problem}\n    \n    \\begin{align*}\n        \\left( \\nabla^2 - \\frac{1}{c^2} \\frac{\\partial^2}{\\partial t^2} \\right) \\vect{A}(\\vect{r}, t) &= - \\vect{J}(\\vect{r}, t)\n    \\end{align*}\n    \n    For final conditions, we have the ``advanced potential'':\n    \\begin{align*}\n        \\vect{A}(\\vect{r}, t) &= \\int_{\\mathbb{R}^3} \\frac{\\vect{J}\\left(\\vect{r}, t + \\frac{|\\vect{r} - \\vect{r}'|}{c}\\right)}{4 \\pi |\\vect{r} - \\vect{r}'|} \\d^3 \\vect{r'}\n    \\end{align*}\n \n    \\begin{align*}\n        \\ft{\\vect{A}}(\\vect{r}, \\omega) &= \\int_{\\mathbb{R}^3} \\ft{\\vect{J}}\\left(\\vect{r}, \\omega \\right) \\frac{e^{+ j \\frac{\\omega}{c} | \\vect{r} - \\vect{r}' |}}{4 \\pi |\\vect{r} - \\vect{r}'|} \\d^3 \\vect{r'}\n    \\end{align*}\n       \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    For final conditions problems, we get something weird: we get an ``advanced potential'' where the field $ \\vect{A} $ depends on the source $ \\vect{J} $ at some time in the future. \n\\item\n    So it seems that causality is tied to our use of initial conditions (rather than final conditions) in time.\n\\item\n    This is also related to uniqueness breaking down for lossless time-harmonic fields.\n    Harrington fixes this by defining ``lossless'' as the limit of low loss (not very satisfactory, since the lossless case is more fundamental).\n    Alternatively, we can fix uniqueness by insisting that we have \\emph{initial} conditions in the time domain.\n\\item\n    For more, see the book chapter ``Causation in classical mechanics'' by Sheldon Smith.\n\\end{itemize}\n}\n\n\\section*{Generalized functions}\n\\label{sec:generalized_functions}\n\n\\note{\n    \\begin{itemize}\n    \\item\n        Delta functions play a key role in Green's functions (and electrical engineering in general), but tend to lead to hand-waving.\n    \\item\n        Worth seeing how they can be rigorously defined before moving on.\n    \\item\n        Machinery for this is Schwartz's theory of distributions (generalized functions).\n    \\item\n        See Folland (1992), \\emph{Fourier analysis and its applications}, Chapter 9 for more.\n    \\end{itemize}\n    \n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Typical delta function definition}\n    \n    Typical ``definition'' of $ \\delta(x - x_0) $:\n    \\begin{align*}\n        \\delta(x-x_0) &= 0 \\quad \\text{for} \\quad x \\neq x_0\n    \\end{align*}\n    \\begin{align*}\n        \\int_{-\\infty}^{\\infty} \\delta(x-x_0) &= 1\n    \\end{align*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Often see definitions like this one.\n\\item\n    Often said to imply that $ \\delta(x - x_0) = \\infty $ at $ x = x_0 $.\n\\item\n    Might be okay intuitively, but very imprecise mathematically.\n\\item\n    There is no true function which satisfies both of these requirements!\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Generalized functions}\n    \n    $ f(x) $ defines a linear operator $ \\phi(x) $ via\n    \\begin{align*}\n        f[\\phi] &= \\int_{-\\infty}^{\\infty} f(x) \\phi(x) \\d x\n    \\end{align*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Let's see if we can generalize the idea of a ``function'' so that it includes delta functions.\n\\item\n    Given a function $ f(x) $, we can use it to define a linear operator (a functional, to be exact) on other functions $ \\phi(x) $.\n\\item\n    $ f[\\cdot] $ is a linear operator. It takes a function $ \\phi(x) $ and returns the number\n    \\begin{align*}\n        f[\\phi] &= \\int_{-\\infty}^{\\infty} f(x) \\phi(x) \\d x\n    \\end{align*}\n\\item\n    If we ensure that $ \\phi(x) $ is very well-behaved, then every function $ f(x) $ defines an operator in this way.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Generalized functions}\n\n    If we have $ f[\\phi] $, but no $ f(x) $, then $ f $ is a generalized function.\n    \n    \\textbf{Symbolically}, we write\n    \\begin{align*}\n        f[\\phi] &\\stackrel{s}{=} \\int_{-\\infty}^{\\infty} f(x) \\phi(x) \\d x\n    \\end{align*}\n    \n\\end{frame}\n\n\\note{\n    \\begin{itemize}\n    \\item\n        It's possible to have an operator $ f[\\phi] $, but we can't find an $ f(x) $ to implement it via an integral.\n    \\item\n        Then $ f(x) $ is a generalized function. It is not a function in its own right, but it is defined purely by its action on other functions $ f[\\phi] $.\n    \\item\n        We still symbolically write\n        \\begin{align*}\n            f[\\phi] &\\stackrel{s}{=} \\int_{-\\infty}^{\\infty} f(x) \\phi(x) \\d x\n        \\end{align*}\n        but this just suggestive notation. \n        It is not actually an integral unless $ f(x) $ is a ``proper'' function!\n    \\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Defining the delta function}\n\n    $ \\delta(x-x_0) $ is a generalized function defined by the sifting property\n    \\begin{align*}\n        \\delta_{x_0}[\\phi] &= \\phi(x_0) \\stackrel{s}{=} \\int_{-\\infty}^{\\infty} \\delta(x - x_0) \\phi(x) \\d x\n    \\end{align*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    We can define a simple linear operator via the sifting property $ \\delta_{x_0}[\\phi] = \\phi(x_0) $.\n\\item\n    There is no actual function $ \\delta(x - x_0) $ which gives\n    \\begin{align*}\n        \\int_{-\\infty}^{\\infty} \\delta(x - x_0) \\phi(x) \\d x &= \\phi(x_0)\n    \\end{align*}\n    so $ \\delta(x - x_0) $ is a generalized function and the above integral is purely symbolic.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Delta function derivatives}\n    \n    We can define derivatives too:\n    \\begin{align*}\n        \\delta^{(n)}_{x_0}[\\phi] &= (-1)^n \\phi^{(n)}(x_0) \\stackrel{s}{=} \\int_{-\\infty}^{\\infty} \\delta^{(n)}(x - x_0) \\phi(x) \\d x\n    \\end{align*}\n\n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Generalized function theory lets us make sense of the derivatives of the delta function too.\n\\item\n    $ \\delta_{x_0}^{(n)} $ is just an operator that picks out the value of the $ n $th derivative of $ \\phi(x) $ at the point $ x_0 $.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Delta function limits}\n    \n    \\begin{align*}\n        \\lim_{\\epsilon \\to 0} f_\\epsilon(x) &= \\delta(x)\n    \\end{align*}\n    if and only if\n    \\begin{align*}\n        \\lim_{\\epsilon \\to 0} f_\\epsilon[\\phi] = \\lim_{\\epsilon \\to 0} \\int_{-\\infty}^{\\infty} f_\\epsilon(x) \\phi(x) \\d x &= \\phi(0)\n    \\end{align*}\n    \n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Often useful to show that some set of actual functions $ f_\\epsilon(x) $ ``approach'' the delta function in a limit.\n\\item\n    To do this, we need to show that the sifting property is obeyed in the limit.\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Delta function limits}\n    Limit of Gaussian functions:\n    \\begin{align*}\n        \\delta(x) &= \\lim_{\\epsilon \\to 0} \\frac{1}{\\sqrt{2 \\pi} \\epsilon} e^{- x^2/ 2 \\epsilon^2}\n    \\end{align*}\n    Limit of Lorentzian functions:\n    \\begin{align*}\n        \\delta(x) &= \\lim_{\\epsilon \\to 0} \\frac{1}{\\pi} \\frac{\\epsilon}{t^2 + \\epsilon^2}\n    \\end{align*}\n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Two examples of delta function limits.\n\\item\n    Confirms our intuition of the delta function as a limit of sharply-peaked functions.\n\\item\n    In fact, basically any limit of sharply-peaked functions of area 1 will work: see Folland (Theorem 9.2).\n\\end{itemize}\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Delta function limits}\n    A more interesting example:\n    \\begin{align*}\n        \\frac{1}{2 \\pi} \\int_{-\\infty}^{\\infty} e^{j x t} \\d t &= \\delta(x)\n    \\end{align*}\n    because\n    \\begin{align*}\n        \\lim_{\\epsilon \\to 0} \\frac{1}{2 \\pi} \\int_{-\\infty}^{\\infty} e^{-\\epsilon^2 t^2} e^{j x t} \\d t = \\delta(x)\n    \\end{align*}\n\n\\end{frame}\n\n\\note{\n    \\begin{itemize}\n    \\item\n        Example of a common, but unintuitive expression for the Delta function.\n    \\item\n        Can show that it's true by expressing it as a delta function limit. (If you want to go through it, use Theorem 9.2 from Folland.)\n    \\end{itemize}\n    \n}\n\n\\begin{frame}[fragile]\n    \\frametitle{What does this mean for Green's functions?}\n    \n    \\begin{align*}\n        \\L G(x, x') &= \\delta(x - x')\n    \\end{align*}\n    actually means\n    \\begin{align*}\n        \\left( \\L G \\right)[\\phi]  &= \\phi(x') \\stackrel{s}{=} \\int_{-\\infty}^\\infty \\left( \\L G(x, x')\\right) \\phi(x) \\d x\n    \\end{align*}\n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    Technically, the Green's function is a generalized function such that $ \\L G $ is the delta function (it has the sifting property).\n\\end{itemize}\n\n}\n\n\\begin{frame}[fragile]\n    \\frametitle{Takeaway}\n    \n    \\begin{center}\n        If in doubt, think of $ \\delta(x - x_0) $ as an operator!\n    \\end{center}\n\n\\end{frame}\n\n\\note{\n\\begin{itemize}\n\\item\n    In practise, thinking of $ \\delta(x - x_0) $ as a function is usually fine.\n\\item\n    But if anything starts to seem fishy, it's good to remember that $ \\delta(x - x_0) $ is actually an operator $ \\delta_{x_0}[\\phi] $, and not a function.\n\\end{itemize}\n    \n}\n\\fi\n\n\\end{document}\n", "meta": {"hexsha": "5a9e42d368a0b94d247fe3891cc1f5711a640b0d", "size": 88004, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Greens_functions_presentation.tex", "max_stars_repo_name": "cdeimert/Greens_functions", "max_stars_repo_head_hexsha": "ea7b7c4ae978de8d860fbf7729fda76aeaaee405", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Greens_functions_presentation.tex", "max_issues_repo_name": "cdeimert/Greens_functions", "max_issues_repo_head_hexsha": "ea7b7c4ae978de8d860fbf7729fda76aeaaee405", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Greens_functions_presentation.tex", "max_forks_repo_name": "cdeimert/Greens_functions", "max_forks_repo_head_hexsha": "ea7b7c4ae978de8d860fbf7729fda76aeaaee405", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1299744432, "max_line_length": 347, "alphanum_fraction": 0.6079723649, "num_tokens": 29130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3051849893088142}}
{"text": "\\section{Preliminaries}\\label{s:preliminaries}\n\nBefore discussing the method, it is important to cover necessary background. The overall technique is suitable for modelling ambiguities in articulated subjects, including quadrupedal animals and humans. To demonstrate results on both object classes, separate 3D deformable models are employed. For animals, this chapter continues using the Skinned Multi-Animal Linear (SMAL)~\\cite{xxx} model relied upon in previous chapters. For modelling humans, the popular Skinned Multi-\\emph{Person} Linear model (SMPL)~\\cite{xxx} is used. Fortunately, both models are designed as drop in replacements for each other so this detail can be abstracted during description of the method. This section begins by clarifying the abstraction, details a standard single hypothesis approach for 3D reconstruction before a detailed explanation of normalizing flows.\n\n\\subsection{3D Morphable Model (SMPL/SMAL).}\n\nBoth SMAL and SMPL are 3D morphable models representing quadrupedal animals and humans respectively. Each supplies a set of triangles and a function $v(\\pose,\\shape): \\R{\\npose} \\times \\R{\\nshape} \\mapsto \\RR{3}{V}$ which outputs a set of vertex positions from pose $\\pose \\in \\R{\\npose}$ and shape $\\shape \\in \\R{nshape}$ parameters. Recall pose is determines joint angles and shape governs global body proportions (e.g. limb lengths). Parameters are also required to express the model's translation and orientation, which can be condensed into a variable $\\posn$. A 3D model of the subject given pose, shape and position parameters is therefore given as $\\posn * v(\\pose,\\shape)$. A comparison between properties of each model is given in Table XXX. \n\n% \\begin{table}\n    \n% \\end{table}\n% parameterizes of quadrupedal animals and hum be viewed as models of SMPL is a model of the human body parameterized by axis-angle rotations $\\theta \\in \\mathbb{R}^{69}$ of 23 body joints, the shape coefficients $\\beta \\in \\mathbb{R}^{10}$ modelling shape variations, and a global rotation $\\gamma \\in \\mathbb{R}^{3}$.\n% SMPL defines a \\emph{skinning function}  $S: (\\theta, \\beta, \\gamma) \\mapsto V$ that maps the body parameters to the vertices $V \\in \\mathbb{R}^{6890\\times 3}$ of a 3D mesh.\n% The skinngin n itself is non-linear due to the conversion of the rotation angles into rotation matrices when the kinematic tree is assembled.\n\n\\subsection{Predicting the 3D model parameters from a single image.}\n\nGiven an image $\\mathbf{I}$ containing a person, the goal is to recover the 3D model parameters $(\\pose,\\shape,\\posn)$ that provide the best possible 3D reconstruction. \n%$(\\theta, \\beta, \\gamma)$ that provide the best 3D reconstruction of it.\nConceptually, this is an inverse problem since the image $\\mathbf{I} = \\Gamma(\\posn * v(\\pose,\\shape), \\eta)$ can be thought to be generated from model parameters $(\\pose,\\shape)$, position $\\posn$ plus a number of unknown factors $\\eta$ capturing details of the appearance, background etc.\n%$\\mathbf{I} = \\Gamma(S(\\theta, \\beta, \\gamma), \\eta)$ \n\n% can be thought to be generated from the SMPL parameters $(\\theta, \\beta, \\gamma)$ plus a number of unknown factors $\\eta$ capturing details of the appearance, background, etc.\nExisting algorithms~\\cite{kanazawa18learning} cast this as learning a deep network $G(I) = (\\pose, \\shape, \\posn, f)$ that predict the model parameters and a focal length $f$ for a perspective camera $\\proj_{f}$ observing the subject. As is common practice, in this chapter a fixed set of camera parameters are used.\n%$G(I) = (\\theta, \\beta, \\gamma, t)$ that predicts the SMPL parameters as well as the %scale $s \\in \\mathbb{R}$ and\n% translation $t \\in \\mathbb{R}^3$ of the perspective camera observing the person. We assume a fixed set of camera parameters.\n% \\rk{TODO: Ben refines: The camera defines a function $\\pi_{s,t}(X) = sx + t_{x}, sy + t_{y}$ projecting 3D points $X\\in\\mathbb{R}^3$ to 2D image coordinates: https://github.com/nkolot/SPIN/blob/b95a00a7c0147f2c5bee0874ba0972c6389b6f99/demo.py}.\nAs demonstrated in previous chapters, during training the camera is used to constrain the reconstructed 3D mesh and the annotated 2D keypoints to be consistent.\nSince most datasets only contain annotations for a small set of keypoints (\\cite{guler2018densepose} is an exception), and since these keypoints do not necessarily correspond directly to any of the 3D mesh vertices, a mechanism is used to translate between them. \nThis mechanism is a fixed linear regressor which determines the 3D locations of the joints. This can be viewed as $\\posn * v(\\pose,\\shape)\\jointselect)$, where the mesh vertices are post-multiplied by a $V \\times J$ matrix $\\jointselect$.\nAs usual, the 3D joint positions can be compared to available 2D annotations by means of the projection function $\\proj_{f}$. Model 2D annotations are therefore given as $\\proj_{f}(\\posn * v(\\pose,\\shape)\\jointselect))$.\n\n\\subsection{Normalizing flows.}\n\n% The idea of normalizing flows (NF) is to represent a complex distribution $p(X)$ on a random variable $X$ as a much simpler distribution $p(z)$ on a transformed version $z=f(X)$ of $X$.\n% The transformation $f$ is learned so that $p(z)$ has a fixed shape, usually a Normal $p(z) \\sim \\mathcal{N}(0,1)$. Furthermore, $f$ itself must be \\emph{invertible} and \\emph{smooth}.\n% In this paper, we utilize a particular version of NF dubbed RealNVP \\cite{dinh17density}.\n% A more detailed explanation of NF and RealNVP has been deferred to the supplementary.\n\nThe idea of normalizing flows is to represent a complex distribution $p(Y)$ on a random variable $Y$ as a much simpler distribution $p(z)$ on a transformed version $z=f(Y)$ of $Y$.\nThe transformation $f$ is learned so that $p(z)$ has a fixed shape, usually a Normal $p(z) \\sim \\mathcal{N}(0,1)$.\nFurthermore, $f$ itself must be \\emph{invertible} and \\emph{smooth}.\nIn this case, the relation between $p(\\theta)$ and $p(z)$ is given by a change of variable\n$$\n p(z = f(Y)) =  \\left| \\frac{df(Y)}{dY} \\right| p(Y),\n$$\nwhere, for notational simplicity, we have assumed that $z,X\\in\\mathbb{R}^D$ are vectors.\n\nThe challenge is to learn $f$ from data in a way that maintains its invertibility and smoothness.\nThis is done by decomposing $z = f_L \\circ \\dots \\circ f_1 (Y)$ in $n$ layers, where $Y_l = f_l(Y_{l-1})$, $y = Y_n$ and $Y=Y_0$, and each layer is in turn smooth and invertible.\nThen one can write\n$$\n \\log p(z = f(Y)) =\n \\log p(Y) + \\sum_{l=1}^L \\log \\left| \\frac{df_l(Y_{l-1})}{dY_{l-1}} \\right|.\n$$\nNow the challenge reduces to making sure that individual layers are in fact smooth and invertible and that their inverses and Jacobian determinants are easy to compute.\nRealNVP~\\cite{dinh17density} does so by writing each layer as $f_l(Y_{0:d,l}, Y_{d:D,l-1}) = \\big(Y_{0:d,l-1},~ Y_{d:D,l-1} \\odot e^{g_l(Y_{0:d,l-1})} + h_i(Y_{0:d,l-1})\\big)$ where $g_l,h_l:\\mathbb{R}^d \\rightarrow \\mathbb{R}^{D-d}$ are two arbitrary neural networks.\n\n\\subsubsection{Theoretical comparison to other methods of modelling ambiguities}\nTODO.\n\n\n", "meta": {"hexsha": "23b7c9051f7fb183c67454852d0e9b6456f673bc", "size": 7024, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapter6/2_preliminaries.tex", "max_stars_repo_name": "benjiebob/phd-thesis-template", "max_stars_repo_head_hexsha": "2fd86bb807b830c06944d9c59962939d9a95ca7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter6/2_preliminaries.tex", "max_issues_repo_name": "benjiebob/phd-thesis-template", "max_issues_repo_head_hexsha": "2fd86bb807b830c06944d9c59962939d9a95ca7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter6/2_preliminaries.tex", "max_forks_repo_name": "benjiebob/phd-thesis-template", "max_forks_repo_head_hexsha": "2fd86bb807b830c06944d9c59962939d9a95ca7a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 111.4920634921, "max_line_length": 843, "alphanum_fraction": 0.7468678815, "num_tokens": 1922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.30518498895749824}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\marginpar{Monday\\\\ 2020-4-6, \\\\ compiled \\\\ \\today}\n\n\\subsection{General solution of the Dirac equation}\n\nWe have imposed that solutions of the Dirac equation are solutions of the KG equation and vice-versa, so a general solution of the Dirac equation should look like those we found when discussing the Klein-Gordon equation: \n%\n\\begin{align}\n\\psi (x) = \\psi_{+ } (x) + \\psi_{-} (x) \n\\sim \\eval{e^{-ikx} u(k) + v(k) e^{ikx}}_{k_0 = \\omega_{k}}\n\\,,\n\\end{align}\n%\nwhere the subscript \\(+\\) or \\(-\\) refers to the sign of the energy of the solution, and now \\(u(k)\\) and \\(v(k)\\) are spinors in momentum space. \nWe use the \\(\\sim\\) sign since these are only plane wave solutions, a general solution will be an integral of these over momentum space.\n\nIf we apply the Dirac operator \\(i \\slashed{\\partial} - M\\) to these we find \n%\n\\begin{subequations}\n\\begin{align}\n\\qty( i \\slashed{\\partial} - M) \\psi_{+} \\sim e^{-ikx} \\qty(\\slashed{k} - M) u(k) &= 0 \\\\\n\\qty( i \\slashed{\\partial} - M) \\psi_{-} \\sim -e^{ikx} \\qty(\\slashed{k} + M) v(k) &= 0\n\\,,\n\\end{align}\n\\end{subequations}\n%\nso, since the exponentials are nonzero we can write these two equations as \n%\n\\boxalign{\n\\begin{align}\n\\qty(\\slashed{k}- M) u(k) = 0 \n\\qquad \\text{and} \\qquad\n\\qty(\\slashed{k} + M) v(k) = 0\n\\,.\n\\end{align}}\n\nLet us now assume that the particle we are considering is not massless, so we can go in its rest frame. \nIf we were to consider a massless particle, we could work with the \\(N=2\\) Weyl spinors. Instead, we will need the \\(N=4\\) Dirac spinors. \n\nIn the rest frame \\(k^{\\mu } = (M, \\vec{0})\\), so the two equations read \n%\n\\begin{subequations}\n\\begin{align}\n0&= \\qty(\\slashed{k} - M) u(k)  \\\\\n&= \\qty(\\gamma^{\\mu }k_{\\mu } - M) u(k)  \\\\\n&= \\qty(\\gamma^{0} M - M ) u(k) = M \\qty(\\gamma^{0} - \\mathbb{1}) u(k)  \\\\\n&=M\\qty( \\left[\\begin{array}{cc}\n\\mathbb{1} & 0 \\\\ \n0 & -\\mathbb{1}\n\\end{array}\\right] \n-\n\\left[\\begin{array}{cc}\n\\mathbb{1} & 0 \\\\ \n0 & \\mathbb{1}\n\\end{array}\\right]\n) u(k)  \\\\\n&= \\left[\\begin{array}{cc}\n0 & 0 \\\\ \n0 & -2 \\mathbb{1}\n\\end{array}\\right] M u(k) =0\n\\,,\n\\end{align}\n\\end{subequations}\n%\nso a generic solution looks like \n%\n\\begin{subequations}\n\\begin{align}\nu(M) = c \\left[\\begin{array}{c}\n\\xi  \\\\ \n0\n\\end{array}\\right]\n\\,.\n\\end{align}\n\\end{subequations}\n\nNote that we are using the Dirac representation, but if we were to choose a different one the spinors would look different. \nFor \\(v(k)\\) the equation looks like \n%\n\\begin{subequations}\n\\begin{align}\nM \\qty(\\gamma^{0} + \\mathbb{1}) v(M) =\n\\left[\\begin{array}{cc}\n2 \\mathbb{1} & 0 \\\\ \n0 & 0\n\\end{array}\\right] M v(M) = 0\n\\,,\n\\end{align}\n\\end{subequations}\n%\nso \n%\n\\begin{subequations}\n\\begin{align}\nv(M) = c \\left[\\begin{array}{c}\n0 \\\\ \n\\xi \n\\end{array}\\right]\n\\,.\n\\end{align}\n\\end{subequations}\n\nHere \\(\\xi \\) is a two-dimensional vector, while \\(c\\) is a normalization constant. \nWe have two independent solutions for each case, so in total there are four independent ones. \nA basis we can choose is \n%\n\\begin{subequations}\n\\begin{align}\nu_{r} (M) = \\sqrt{2M} \\left[\\begin{array}{c}\n\\xi_{r} \\\\ \n0\n\\end{array}\\right]\n\\qquad \\text{and} \\qquad\nv_{r} (M) = \\sqrt{2M} \\left[\\begin{array}{c}\n0 \\\\\n\\xi_{r} \n\\end{array}\\right]\n\\,,\n\\end{align}\n\\end{subequations}\n%\nwhere \\(r=1,2\\) and \\((\\xi_{r})^{i} = \\delta^{i}_{r}\\) are unit vectors, a basis for the 2D space. \n\nIf we choose this normalization, then we will have \\(\\overline{u}_{r}(M) u_s(M) = 2 M \\delta_{rs}\\) and \\(\\overline{v}_{r}(M) v_s(M) =- 2 M \\delta_{rs}\\), while all the \\(u\\)s and the \\(v\\)s are respectively orthogonal: \\(\\overline{u}_{r} v_s =  \\overline{v}_{r} u_s = 0\\). \n\nThis choice corresponds to having chosen to have the spin of the particle along the third axis, as we shall see shortly. \n\nThe fact that we were able to find a basis of four independent vectors for the solution means that the solution of the Dirac equation has four independent degrees of freedom, two of which have positive energy and two of which have negative energy. \n\nWe put ourselves in the rest frame: if we wish to compute the solutions \\(u(k)\\) and \\(v(k)\\) in a generic frame we need to perform a Lorentz boost from the rest frame. \nIn order to study how this boost affects the spinor, we need to study the spinorial representation of the Lorentz boost, \\(S(\\Lambda)\\). \n\nInstead of explicitly writing out the full representation of the Lorentz matrix we are interested in, which is long and complicated, we can use the following trick: \n%\n\\begin{subequations}\n\\begin{align} \\label{eq:on-shell-equality}\n\\qty(\\slashed{k} - M) \\qty(\\slashed{k} + M)\n&=\n\\qty(\\slashed{k} + M) \\qty(\\slashed{k} - M) \\\\\n&= \\gamma^{\\mu } \\gamma^{\\nu } k_{\\mu }k_{\\nu } - M^2   \\\\\n&= \\frac{1}{2} \\qty{\\gamma^{\\mu }, \\gamma^{\\nu }} k_{\\mu } k_{\\nu } - M^2 = k^2-M^2 = 0\n\\,,\n\\end{align}\n\\end{subequations}\n%\nsince \\( \\frac{1}{2} \\qty{\\gamma^{\\mu }, \\gamma^{\\nu }} = \\eta^{\\mu \\nu }\\), and the square of the 4-momentum always corresponds to the mass of the particle under our assumptions (of working on-shell).\n\nThis allows us to quickly prove that the ansatz \n%\n\\begin{align}\nu(k) = C (\\slashed{k} + M) u(M)\n\\,\n\\end{align}\n%\nsatisfies the KG equation (with positive energy), since \n%\n\\begin{align}\n(\\slashed{k} - M) u(k) = C \\qty(k^2 - M^2) u(M) = 0\n\\,,\n\\end{align}\n%\nwhich follows from the identity \\eqref{eq:on-shell-equality} which we just proved.\nSo, we can get a solution in a generic frame by applying a known operator onto the res\n\n% \\todo[inline]{But then we could use something which is not \\(u(M)\\) for our rest-frame solution, right?}\n\nSimilarly, for the negative-energy case we have the solution \n%\n\\begin{align}\nv(k) = C (\\slashed{k} - M )v(M)\n\\,,\n\\end{align}\n%\nwhich will satisfy \\((\\slashed{k} + M) v(k) = 0\\).\n\nThe constant \\(C\\) is for normalization, and we choose it such that the normalization is the same as in the rest frame: so, the identities to be satisfied are \n%\n\\begin{subequations}\n\\begin{align} \\label{eq:normalization-spinor}\n\\overline{u}_{r} (k) u_{s}(k) &= 2 M \\delta_{rs}  \\\\\n\\overline{v}_{r} (k) v_{s}(k) &= - 2 M \\delta_{rs}  \\\\\n\\overline{u}_{r} (k) v_{s}(k) &=   \n\\overline{v}_{r} (k) u_{s}(k) = 0  \n\\,.\n\\end{align}\n\\end{subequations}\n\n\\begin{claim}\nThe final result we get from this manipulation is \n%\n\\begin{subequations} \\label{eq:dirac-equation-solutions}\n\\begin{align}\nu_r (k) &= \\frac{(\\slashed{k} + M)}{\\sqrt{2 M \\qty(\\omega_{k} + M )}} u_r (M)\n= \\left[\\begin{array}{c}\n\\xi_{r}\\sqrt{\\omega_{k} + M} \\\\ \n\\displaystyle\n\\frac{\\vec{k} \\cdot \\vec{\\sigma}}{\\sqrt{\\omega_{k} + M}} \n\\xi_{r}\n\\end{array}\\right] \\label{eq:positive-energy-dirac-solution-momentum-space}\\\\\nv_r (k) &= \\frac{(-\\slashed{k} + M)}{\\sqrt{2 M \\qty(\\omega_{k} + M )}} v_r (M)\n= \\left[\\begin{array}{c}\n\\displaystyle\n\\frac{\\vec{k} \\cdot \\vec{\\sigma}}{\\sqrt{\\omega_{k} + M}} \\xi_{r}\\\\\n\\xi_{r}\\sqrt{\\omega_{k} + M} \n\\end{array}\\right]\n\\,.\n\\end{align}\n\\end{subequations}\n\\end{claim}\n\nThe first solution is the positive-energy one, the second is the negative-energy one. \nNotice that the expression \\(\\vec{k} \\cdot \\vec{\\sigma}\\) yields a \\(2 \\times 2\\) complex matrix, which is applied to the vector \\(\\xi_{r}\\).\n\nWe prove the second equality for the positive energy solution. \n\n\\begin{proof}\nWe begin by writing out the operator \n%\n\\begin{subequations}\n\\begin{align}\n\\slashed{k}  = \\gamma^{\\mu } \\eta_{\\mu \\nu } k^{\\nu }\n= \\left[\\begin{array}{cc}\n\\mathbb{1} \\omega_{k} & 0 \\\\ \n0 & -\\mathbb{1} \\omega_{k}\n\\end{array}\\right]\n- \n\\left[\\begin{array}{cc}\n0 & \\vec{k} \\cdot \\vec{\\sigma} \\\\ \n-\\vec{k} \\cdot \\vec{\\sigma} & 0\n\\end{array}\\right]\n= \\left[\\begin{array}{cc}\n\\mathbb{1} \\omega_{k} & -\\vec{k} \\cdot \\vec{\\sigma} \\\\ \n\\vec{k} \\cdot \\vec{\\sigma} & - \\mathbb{1} \\omega_{k}\n\\end{array}\\right]\n\\,.\n\\end{align}\n\\end{subequations}\n\nSo, when we apply this (plus \\(M\\) times the identity) to the solution \n%\n\\begin{subequations}\n\\begin{align}\nu_r(M) = \\sqrt{2M} \\left[\\begin{array}{c}\n\\xi_{r} \\\\ \n0\n\\end{array}\\right]\n\\,,\n\\end{align}\n\\end{subequations}\n%\nwe get: \n%\n\\begin{subequations}\n\\begin{align}\n\\qty(\\slashed{k} + M) u_{r}(M) = \n\\sqrt{2M} \\left[\\begin{array}{c}\n\\qty(\\omega_{k} + M)  \\xi_{r} \\\\ \n\\qty(\\vec{k} \\cdot \\vec{\\sigma}) \\xi_{r}\n\\end{array}\\right]\n\\,,\n\\end{align}\n\\end{subequations}\n%\nwhich we can divide by \\(\\sqrt{2M (\\omega_{k} + M)}\\) to find the desired expression, equation \\eqref{eq:positive-energy-dirac-solution-momentum-space}.\n\\end{proof}\n\n\\begin{claim}\nThe conjugate spinors \\(\\overline{u}\\) and \\(\\overline{v}\\) in momentum space read respectively: \n%\n\\begin{subequations}\n\\begin{align}\n\\overline{u}_{r} (k) = \\overline{u}_{r}(M) \\frac{\\qty(\\slashed{k} + M)}{\\sqrt{2 (\\omega_{k} + M)}}\n= \\left[\\begin{array}{cc}\n\\xi_{r}^{\\top} \\sqrt{\\omega_{k} + M}, & \n\\displaystyle\n- \\xi_{r}^{\\top} \\frac{\\vec{k} \\cdot \\vec{\\sigma}}{\\sqrt{\\omega_{k} + M}}\n\\end{array}\\right] \\\\\n\\overline{v}_{r} (k) = \\overline{v}_{r}(M) \\frac{\\qty(-\\slashed{k} + M)}{\\sqrt{2 (\\omega_{k} + M)}}\n= \\left[\\begin{array}{cc}\n\\displaystyle\n\\xi_{r}^{\\top} \\frac{\\vec{k} \\cdot \\vec{\\sigma}}{\\sqrt{\\omega_{k} + M}}, &\n-\\xi_{r}^{\\top} \\sqrt{\\omega_{k} + M}\n\\end{array}\\right]\n\\,.\n\\end{align}\n\\end{subequations}\n\\end{claim}\n\n\\begin{proof}\nRecall that \\(\\overline{u} = u ^\\dag \\gamma^{0}\\), and that in our representation \n%\n\\begin{subequations}\n\\begin{align}\n\\gamma^{0} = \\left[\\begin{array}{cc}\n\\mathbb{1} & 0 \\\\ \n0 & -\\mathbb{1}\n\\end{array}\\right]\n\\,.\n\\end{align}\n\\end{subequations}\n\nWe can then compute \n%\n\\begin{subequations}\n\\begin{align}\n\\overline{u}_{r} (k) &= \\left[\\begin{array}{c}\n\\xi_{r}\\sqrt{\\omega_{k} + M} \\\\ \n\\displaystyle\n\\frac{\\vec{k} \\cdot \\vec{\\sigma}}{\\sqrt{\\omega_{k} + M}} \n\\xi_{r}\n\\end{array}\\right] ^\\dag\n\\gamma_0  \\\\\n&= \\left[\\begin{array}{cc}\n\\xi_{r}^{\\top} \\sqrt{\\omega_{k} + M}, & \n\\xi_{r}^{\\top} \\displaystyle\n\\frac{(\\vec{k} \\cdot \\vec{\\sigma})}{\\sqrt{\\omega_{k} + M}}\n\\end{array}\\right] \\gamma_0   \\marginnote{\\(\\vec{k}\\) and \\(\\xi_{r}\\) are real, \\(\\sigma = \\sigma ^\\dag\\).}\\\\\n&=  \\left[\\begin{array}{cc}\n\\xi_{r}^{\\top} \\sqrt{\\omega_{k} + M}, & \n-\\xi_{r}^{\\top} \\displaystyle\n\\frac{(\\vec{k} \\cdot \\vec{\\sigma})}{\\sqrt{\\omega_{k} + M}}\n\\end{array}\\right]\n\\,.\n\\end{align}\n\\end{subequations}\n\nThe computation for the negative energy solution is analogous.\n\\end{proof}\n\n\\begin{claim}\nWe can derive the normalization conditions \\eqref{eq:normalization-spinor} from the explicit expressions of the solutions.\n\\end{claim}\n\n\\begin{proof}\nWriting out the multiplication explicitly for the real solutions we have: \n%\n\\begin{subequations}\n\\begin{align}\n\\overline{u}_{r}(k) u_s(k) &=\n\\left[\\begin{array}{cc}\n\\xi_{r}^{\\top} \\sqrt{\\omega_{k} + M}, & \n\\displaystyle\n- \\xi_{r}^{\\top} \\frac{\\vec{k} \\cdot \\vec{\\sigma}}{\\sqrt{\\omega_{k} + M}}\n\\end{array}\\right]\n\\left[\\begin{array}{c}\n\\xi_{s}\\sqrt{\\omega_{k} + M} \\\\ \n\\displaystyle\n\\frac{\\vec{k} \\cdot \\vec{\\sigma}}{\\sqrt{\\omega_{k} + M}} \n\\xi_{s}\n\\end{array}\\right]  \\\\\n&= \\xi_{r}^{\\top} \\sqrt{\\omega_{k} +M }\n\\xi_{s} \\sqrt{\\omega_{k} + M}\n- \\xi_{r}^{\\top} \n\\frac{(\\vec{k} \\cdot \\vec{\\sigma})}{\\sqrt{\\omega_{k} + M}}\n\\frac{(\\vec{k} \\cdot \\vec{\\sigma})}{\\sqrt{\\omega_{k} + M}}\n\\xi_{s}  \\label{eq:normalization-condition-step-positive-energy}\\\\\n&= \\delta_{rs} (\\omega_{k} + M) - \\delta_{rs} \\frac{\\abs{k}^2}{\\omega_{k} + M}  \\\\\n&= \\delta_{rs} \\frac{(\\omega_{k} + M)^2 - \\abs{k}^2}{\\omega_{k} + M}  \\\\\n&= \\delta_{rs} \\frac{M^2 + 2 \\omega_{k} M + \\omega_{k}^2 - \\abs{k}^2}{\\omega_{k} + M} = 2M \\delta_{rs}  \\frac{\\omega_{k} + M}{\\omega_{k} + M}\n\\marginnote{Used \\(\\omega_{k}^2 - \\abs{k}^2 = M^2\\)}\n\\,,\n\\end{align}\n\\end{subequations}\n%\nwhere we applied the identity \n%\n\\begin{align}\n(\\vec{a} \\cdot \\vec{\\sigma}) (\\vec{b} \\cdot \\vec{\\sigma}) = \\qty(\\vec{a} \\cdot \\vec{b}) \\mathbb{1} + i \\qty(\\vec{a} \\times \\vec{b}) \\cdot \\vec{\\sigma} \n\\,,\n\\end{align}\n%\nwhich follows from the commutation and anticommutation relations \n%\n\\begin{subequations}\n\\begin{align}\n\\qty[\\sigma_{a}, \\sigma_{b}] &= 2i \\epsilon_{abc} \\sigma_{c}  \\\\\n\\qty{\\sigma_{a}, \\sigma_{b}} &= 2\\delta_{ab} \\mathbb{1}\n\\,.\n\\end{align}\n\\end{subequations}\n\nNow we can replicate the calculation for the negative energy solution: \n%\n\\begin{subequations}\n\\begin{align}\n\\overline{v}_{r} v_s &=\n\\left[\\begin{array}{cc}\n\\displaystyle\n\\xi_{r}^{\\top} \\frac{\\vec{k} \\cdot \\vec{\\sigma}}{\\sqrt{\\omega_{k} + M}}, &\n-\\xi_{r}^{\\top} \\sqrt{\\omega_{k} + M}\n\\end{array}\\right]\n\\left[\\begin{array}{c}\n\\displaystyle\n\\frac{\\vec{k} \\cdot \\vec{\\sigma}}{\\sqrt{\\omega_{k} + M}} \\xi_{s}\\\\\n\\xi_{s}\\sqrt{\\omega_{k} + M} \n\\end{array}\\right]  \\\\\n&= \\delta_{rs} \\qty( \\frac{\\abs{k}^2}{\\omega_{k} + M}  - \\omega_{k} - M) \\\\\n&= -2M \\delta_{rs}\n\\,,\n\\end{align}\n\\end{subequations}\n%\nwhere we skipped some steps since we can recognize the opposite of the expression we found earlier, equation \\eqref{eq:normalization-condition-step-positive-energy}. \n\nFor the mixed terms, instead, we get \n%\n\\begin{subequations}\n\\begin{align}\n\\overline{v}_{r} u_{s} &= \n\\left[\\begin{array}{cc}\n\\displaystyle\n\\xi_{r}^{\\top} \\frac{\\vec{k} \\cdot \\vec{\\sigma}}{\\sqrt{\\omega_{k} + M}}, &\n-\\xi_{r}^{\\top} \\sqrt{\\omega_{k} + M}\n\\end{array}\\right]\n\\left[\\begin{array}{c}\n\\xi_{s}\\sqrt{\\omega_{k} + M} \\\\ \n\\displaystyle\n\\frac{\\vec{k} \\cdot \\vec{\\sigma}}{\\sqrt{\\omega_{k} + M}} \n\\xi_{s}\n\\end{array}\\right]  \\\\\n&= \\xi_{r}^{\\top} \\frac{\\vec{k} \\cdot \\vec{\\sigma}}{\\sqrt{\\omega_{k} + M}}\n\\xi_{s} \\sqrt{\\omega_{k} +M} - \n\\xi_{r}^{\\top} \\frac{\\vec{k} \\cdot \\vec{\\sigma}}{\\sqrt{\\omega_{k} + M}}\n\\xi_{s} \\sqrt{\\omega_{k} +M} = 0 = \\overline{u}_{r} v_s\n\\label{eq:normalization-orthogonality-positive-negative-solutions}\n\\,.\n\\end{align}\n\\end{subequations}\n\\end{proof}\n\n\\begin{claim}\nThe following identities hold:\n%\n\\begin{subequations}\n\\begin{align} \nu_{r}^\\dag (k) u_{s}(k) &= 2 \\omega_{k}\\delta_{rs}  \\\\\nv_{r}^\\dag (k) v_{s}(k) &= 2 \\omega_{k} \\delta_{rs}  \\\\\nu_{r}^\\dag (k) v_{s}(-k) &=   \nv_{r}^\\dag (k) u_{s}(-k) = 0  \n\\,.\n\\end{align}\n\\end{subequations}\n\nNotice that now we have a dagger instead of a bar.\n\\end{claim}\n\n\\begin{proof}\nIn order to see what these solutions are we need to compute \\(u_{r} ^\\dag\\): the difference between it and \\(\\overline{u}_{r}\\) is the lack of multiplication by \\(\\gamma^{0}\\), which in our representation means that the sign of the second component is not flipped. \nSo, in the calculation at step \\eqref{eq:normalization-condition-step-positive-energy} we have instead \n%\n\\begin{subequations}\n\\begin{align}\n\\xi_{r}^{\\top} \\sqrt{\\omega_{k} +M }\n\\xi_{s} \\sqrt{\\omega_{k} + M}\n- \\xi_{r}^{\\top} \n\\frac{(\\vec{k} \\cdot \\vec{\\sigma})}{\\sqrt{\\omega_{k} + M}}\n\\frac{(\\vec{k} \\cdot \\vec{\\sigma})}{\\sqrt{\\omega_{k} + M}}\n\\xi_{s}\n&= \\delta_{rs} \\frac{\\omega_{k}^2 + M^2 + 2 \\omega_{k} M + \\abs{k}^2}{\\omega_{k} + M}  \\\\\n&=2 \\delta_{rs} \\omega_{k}\n\\,,\n\\end{align}\n\\end{subequations}\n%\nwhere we applied a similar line of reasoning to the other proof. The negative sign makes it so instead of cancelling the \\(\\omega_{k}^2\\) term we cancel the \\(M^2\\) term.\n\nFor the negative energy solution we have basically the same thing.\nLet us consider the product of the negative and positive solutions: if we swap the sign we find that the result is nonzero since the terms in \\eqref{eq:normalization-orthogonality-positive-negative-solutions} do not cancel anymore. \n\nHowever, if we flip the sign of one of the two momenta the terms cancel.\n\\end{proof}\n\n\\end{document}\n", "meta": {"hexsha": "edf83b1ab744663c43876e7cb775ba6b3d452183", "size": 15244, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ap_second_semester/theoretical_physics/mar30.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "ap_second_semester/theoretical_physics/mar30.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ap_second_semester/theoretical_physics/mar30.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 32.025210084, "max_line_length": 274, "alphanum_fraction": 0.6425478877, "num_tokens": 5593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.5428632831725051, "lm_q1q2_score": 0.3051849889574982}}
{"text": "\\documentclass[sigconf,edbt]{acmart-edbt-workshops}\n\n\\usepackage{booktabs} % For formal tables\n\\usepackage{hyperref}       % hyperlinks\n\\usepackage{url}            % simple URL typesetting\n\\usepackage{booktabs}       % professional-quality tables\n\\usepackage{amsfonts}       % blackboard math symbols\n\\usepackage{nicefrac}       % compact symbols for 1/2, etc.\n\\usepackage{microtype}      % microtypography\n\\usepackage{cleveref}\n\\usepackage{amsmath,amssymb}             % AMS Math\n\\usepackage{dsfont}\n\\usepackage{mathtools}\n\n\\usepackage{algorithm}\n\\usepackage{algpseudocode}\n\n\\usepackage{tikz}\n\n\\usepackage{array}\n\\usepackage{multirow}\n\n\\usetikzlibrary{shapes,backgrounds, calc, shadings, arrows,decorations.pathmorphing,backgrounds,fit,positioning,shapes.symbols,chains}\n\\pgfdeclareradialshading{ballshading}{\n \\pgfpoint{-10bp}{10bp}}\n {color(0bp)=(gray!50!black);\n  color(9bp)=(gray!50!black);\n  color(18bp)=(gray!50!black);\n  color(25bp)=(gray!50!black);\n  color(50bp)=(black)}\n\n\\tikzstyle{peers}=[draw,circle, minimum width=10pt]\n\\tikzstyle{superpeers}=[draw,circle,minimum width=20pt]\n\n\\tikzset{\n%Define standard arrow tip\n>=stealth',\n%Define style for different line styles\nhelp lines/.style={dashed, thick},\naxis/.style={<->},\nimportant line/.style={thick},\nconnection/.style={thick, dotted},\n}\n\\newcommand\\A{\\ensuremath{\\mathcal{A}}}\n\\newcommand\\B{\\ensuremath{\\mathcal{B}}}\n\n\\newcommand\\cmbox[1]{\n  \\fbox{\\lower0.75cm\n    \\vbox to 1.0cm{\\vfil\n      \\hbox to 1.7cm{\\hfil\\parbox{1.4cm}{\\centering #1}\\hfil}\n      \\vfil}%\n  }%\n}\n\n\\newcommand\\cmlegend[1]{\n  {\\lower0.75cm\n    \\vbox to 1.0cm{\\vfil\n      \\hbox to 0.7cm{\\hfil #1}\n      \\vfil}%\n  }%\n}\n\n% Copyright\n\\setcopyright{rightsretained}\n\n% DOI\n\\acmDOI{}\n\n% ISBN\n\\acmISBN{978-3-89318-078-3}\n\n%Conference\n\\acmConference[EDBT 2018]{21st International Conference on Extending Database Technology (EDBT)}{March 26-29, 2018}{Vienna, Austria} \n\\acmYear{2018}\n\n\\settopmatter{printacmref=false, printccs=false, printfolios=false}\n\n\\pagestyle{plain} % removes running headers\n\n\\def\\HCBR{{\\sc HCBR}}\n\\def\\bfHCBR{{\\sc \\bf HCBR}}\n\n\\newcommand{\\mynote}[1]{{\\bf  \\textcolor{blue}{#1}}}\n\\begin{document}\n\\title{Binary Classification With Hypergraph Case-Based Reasoning}\n%\\titlenote{Produces the permission block, and copyright information}\n%\\subtitle{Extended Abstract}\n%\\subtitlenote{The full version of the author's guide is available as\n%  \\texttt{acmart.pdf} document}\n  \n\n\\author{Alexandre Quemy} \n\\affiliation{%\n \\institution{IBM Software Lab}\n \\city{Cracow} \n \\country{Poland}}\n\\affiliation{%\n  \\institution{Faculty of Computing, Pozna\\'n University of Technology}\n  \\city{Pozna\\'n} \n  \\country{Poland}\n}\n\\email{aquemy@pl.ibm.com}\n\n\n% The default list of authors is too long for headers}\n% \\renewcommand{\\shortauthors}{B. Trovato et al.}\n\\renewcommand{\\shortauthors}{}\n\n\n\\begin{abstract}\nBinary classification is one of the most common problem in machine learning. It consists in predicting whether a given element is of a particular class. In this paper, a new algorithm for binary classification is proposed using a hypergraph representation. Each element to be classified is partitioned according to its interactions with the training set. For each class, the total support is calculated as a convex combination of the {\\it evidence} strength of the element of the partition. The evidence measure is pre-computed using the hypergraph induced by the training set and iteratively adjusted through a training phase. It does not require structured information, each case being represented by a set of {\\it agnostic information} atoms. Empirical validation demonstrates its high potential on a wide range of well-known datasets and the results are compared to the literature. The time complexity is given and empirically validated. Its capacity to provide good accuracy with few examples is also studied.\n\\end{abstract}\n\n\\maketitle\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Introduction}\\label{sec:intro}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nIn many real-life situations, one tries to take a decision based on previous {\\it similar} situations. Each situation is described by a certain amount of information, either collected by an expert according to the relevance of the information, or automatically by some sensors or algorithms. Those situations share similarities on which to make analogies or counter-examples in order to take a new decision. Conversely, in general, if two situations do not share any common characteristic, then they are totally independent, i.e. it is impossible to infer one's outcome from the other one. The purpose of supervised machine learning algorithms is to exploit the available information and interactions between past cases or examples in order to build a model or infer the key rules to take correct decisions.\n\nDue to the large variety of concrete situations that can be reduced to binary classification, it is one of the most studied problems in machine learning. In this paper, we investigate the problem of binary prediction under a supervised setting, i.e. given a history of previous situations labeled with the correct output.\n\nThis paper contributes to binary classification with a new algorithm called Hypergraph Case-Based Reasoning (\\HCBR). The idea is to create a hypergraph where each element of the training set is a hyperedge and vertices are represented by the features describing the elements. The intersections between edges create a partition for each case, and we model the support for each class as a convex combination of the elements of this partition. Each of those elements is valued according to its importance w.r.t. to the set of all the hyperedges it belongs to and their respective labels.\n\nThe well-known \"no free lunch\" theorem states that there is no unique algorithm that can outperform all the others in supervised learning. However, the case description and representation play a preponderant role in the performances but the algorithms are very often constrained by being designed to a specific representation that may not be suitable for a given problem or user data. The proposed method is totally agnostic about the representation\\footnote{With the exception that the current version must work on discrete information.} and does not require structured representations. For instance, it can work on atomic representations such as Bag-of-Word representations for texts where an atom is a single word (or $n$-gram). In this case, two elements would not have the same number of elements and it may be hard to properly define the case domain.\n\nThe plan of the paper is as follows: in Section \\ref{sec:problem} the problem of binary classification is formalized in the particular case of a finite countable set of information. The contribution of this paper is divided into two parts: Section \\ref{sec:model} defines the \\HCBR~ algorithm and Section \\ref{sec:experiments} presents empirical results on 8 datasets from the UC Irvine Machine Learning Repository (UCI)\\footnote{\\href{http://archive.ics.uci.edu/ml/index.php}{http://archive.ics.uci.edu/ml/index.php}} and the LIBSVM\\footnote{\\href{https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/binary.html}{https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/binary.html}}. The paper ends in Section \\ref{sec:conclusion} with a discussion about the results, future work, and possible improvements.\n\n\\section{Classification and Hypergraph}\n\\label{sec:state_of_art}\n\nHypergraphs generalize graphs and can be used to represent higher order relations while graphs are limited to binary relations. A hypergraph is defined by a set of vertices and a collection of hyperedges where each hyperedge is a subset of this set of vertices. Therefore, a graph is a special case of hypergraph for which each hyperedge contains only two vertices. We will formally introduce hypergraphs in Section \\ref{sec:rep}.\nRecently hypergraphs have been used as data representation, and some classification algorithms on hypergraph have been proposed. A vast majority of approaches models the objects to classify as the set of vertices and constructs the hyperedges as the representation of a metric. This conventional approach is known as {\\it neighborhood-based} hypergraph. The metric relies on some assumptions on the data or a specific representation (e.g. Zernike moment and histogram of oriented gradient (HOG) to measure the distance between images in \\cite{ijcai2017-387}) and for each vertex, a hyperedge is created to represent its $k$-nearest neighbors \\cite{5540012}. The problem of classification on hypergraph consists in labeling some unlabeled vertices given a training set such that all vertices in a same hyperedge have the same label. As all the vertices are known a priori, the problem is part of transductive learning. To learn the labels, the standard approach is to minimize a cost function based on a hypergraph equivalent of a graph Laplacian \\cite{NIPS2006_3128,ijcai2017-387} with a structural risk:\n\\begin{align}\nC(x) = x^t \\Delta x + \\mu ||x - y||^2\n\\end{align} where $\\Delta$ is the hypergraph Laplacian, $\\mu >0$ a regularization factor and $||.||$ a norm. The vector $y$ represents the initial labels for all vertices with $y_i = 0$ for unlabeled vertices, a negative (resp. positive) value for label -1 or 1.\n\nOn the contrary, the method proposed in this paper models the elements to classify as the hyperedges and the vertices as the different components of those elements. As far as we know, there is no previous work that uses this modeling choice. In addition, it does not require knowing all the elements before building the model: our approach is inductive. If the literature focus on the method to build the hyperedges, the proposed framework has a straightforward hypergraph construction and rather focus on model selection.\n\n\\section{Problem definition}\n\\label{sec:problem}\n\nConsider a countable finite space of information $\\mathbb{F}$ and its $\\sigma$-algebra $\\mathcal P({\\mathbb F})$ defined as the powerset of $\\mathbb F$. We call {\\it case} an element of $\\mathcal P({\\mathbb F})$. In practice, it is very likely that only a subset of $\\mathcal P({\\mathbb F})$ may appear (for instance if two features encode two contradictory propositions or if every case has the same number of features). The real class for any case is defined by the unknown measurable mapping:\n\\begin{align*}\n   J \\colon \\mathcal P({\\mathbb F}) & \\to \\{0,1 \\} \\\\\n   x &\\mapsto J(x)\n\\end{align*}\n\nGiven an example set $X$ of $n$ cases, the classification problem consists in minimizing the prediction errors for all the elements of $\\mathcal P({\\mathbb F})$, that is to say finding a decision mapping $\\bar J \\colon \\mathcal P({\\mathbb F}) \\to \\{0,1 \\}$ such that:\n\\begin{align}\n\\label{eq:pb} \n \\forall X \\in \\mathcal P({\\mathbb F})^n, ~ \\underset{\\bar J}{\\min} \\sum_{x \\in \\mathcal P({\\mathbb F})} \\mathds{1}_{\\{J(x) \\neq \\bar J(x)\\}}\n\\end{align}\nIn other words, for any possible training set, we want to find an estimation of the exact mapping $J$ and thus it is a functional problem.\nNotice that in this paper we do not consider {\\it uncertainty}: if two situations are described the same in $\\mathbb{F}$, then they have the same label.\n\n\\section{Hypergraph Case-Based Reasoning}\n\\label{sec:model}\n\n\\subsection{Representation And Projection}\n\\label{sec:rep}\n\nBefore describing \\HCBR, we recall the definition of a hypergraph and induced hypergraph. For more results on hypergraphs, we refer the reader to \\cite{berge1984hypergraphs}.\n\\begin{definition}[Hypergraph]\nA hypergraph is defined by $H = (V, X)$ with $V$ a set of vertices, $X$ the hyperedges such that $\\forall x \\in X, ~ x \\subseteq V$.\n\\end{definition}\n\\noindent\nA hypergraph can be viewed as a collection of subsets $X$ of a given set of vertices $V$. It is sometimes convenient to define a hypergraph solely by a collection of sets. In this case, the set of vertices, denoted $V_X$, is implicitly defined as the union of edges.\n\n\\begin{definition}[Induced Subhypergraph]\nThe subhypergraph $H[A]$ induced by $A \\subseteq V$ is defined by $H[A] = (A, X_A)$ with $X_A = \\{ x \\cap A ~ | ~ x \\cap A \\neq \\emptyset\\}$.\n\\end{definition}\n\\begin{figure}[!h]\n  \\centering\n  \\def\\firstcircle{(0,0) ellipse (1.5cm and 1cm)}\n  \\def\\secondcircle{(80:-1cm) ellipse (1.5cm and 1cm)}\n  \\def\\thirdcircle{(0:2cm) ellipse (1.5cm and 1cm)}\n  \\begin{tikzpicture}[scale=0.5, every node/.style={scale=1}]\n      \\begin{scope}[fill opacity=0.3]\n          \\filldraw[fill=gray, xscale=1.4, yscale=1.4] (-0.0,-0.0) plot [smooth cycle,tension=0.7, shift={(-4,-3.2)}] coordinates {(3,1) (5,1.2) (7,1) (8,3) (7,4.5) (5,4.5) (2,4) (1.7,2.5)};\n          %\\filldraw[fill=gray] (-3.5,-3.5) rectangle (4,2);\n          \\fill[red, rotate=30, xscale=1.4, yscale=1.4] \\firstcircle;\n          \\fill[green, rotate=35, xscale=1.4, yscale=1.4] \\secondcircle;\n          \\fill[blue, xscale=1.4, yscale=1.4] \\thirdcircle;\n          \\draw[rotate=30, xscale=1.4, yscale=1.4] \\firstcircle;\n          \\draw[rotate=35, xscale=1.4, yscale=1.4] \\secondcircle;\n          \\draw[xscale=1.4, yscale=1.4] \\thirdcircle;\n\n      \\end{scope}\n      \\node at (4,-2.7) {$\\mathbb{F}$};\n      \\node at (0.5,1) {$x_1$};\n      \\node at (0,-2.3) {$x_2$};\n      \\node at (3,1) {$x_3$};\n\n      \\node at (-0.8  ,0.5) {$e_1$};\n      \\node at (1.4  ,0.7) {$e_2$};\n      \\node at (1.2  ,-0.3) {$e_3$};\n      \\node at (3.6  , -0.1) {$e_4$};\n      \\node at (2  , -0.7) {$e_5$};\n      \\node at (-0.4  ,-1) {$e_6$};\n      \\node at (1  ,-1.7) {$e_7$};\n  \\end{tikzpicture}\n  \\caption{\\label{case_base} The family $\\mathcal E = \\{ e_i \\}_{i}$ forms the partition obtained by the union of the projection of cases and represents how the three cases share information.}\n\\end{figure}\n\nA set of examples $X$ can be seen as a hypergraph $H = (\\mathbb F, X)$, i.e. such that each example is a hyperedge (Figure \\ref{case_base}). In practice, we do not need to know $\\mathbb{F}$ as we can always use the implicit hypergraph $H = (\\mathbb{F}_X, X)$ where $\\mathbb{F}_X$ is the restriction of $\\mathbb{F}$ to the features that appear in the sample $X$.\n\\begin{definition}[Projection defined by a subhypergraph]\nThe projection operator $\\pi_H$ over a hypergraph $H = (V, X)$ for any $A \\subseteq V$ is defined by $\\pi_H(A) = \\{ e \\subseteq A ~ | ~ \\exists X' \\subseteq X_A, ~ e = \\underset{x \\in X'}{\\bigcap} x \\}$.\n\\end{definition}\nFor a case $x$, the operator $\\pi$ takes the subhypergraph $H[x]$ and returns the partition of the features of $x$ defined by the intersection family induced by $H[x]$. Each element of $\\pi_H(x)$ is a (sub)set of features. For instance, in Figure \\ref{case_base}, $\\pi_H(x_1) = \\{ e_1, e_2, e_3, e_6 \\}$ and in Figure \\ref{new_case_schema}, the projection of $x$ (in yellow) on $H$ is represented by the family $\\{ e'_i\\}_i$.\nFor convenience, for a given $H = (V_X, X)$, we denote by $\\mathcal{E}_H = \\{e_i\\}^m_{i=1} = \\{ e \\in \\underset{x \\in X}{\\cup} \\pi_H(x)\\}$ that is to say, the partition of $V_X$ obtained by the intersection of the edges. This partition is unique to a hypergraph.\n\nWe call {\\it discretionary features} of $x$ (w.r.t. $H$) the set (possibly empty) of features that are not in any element of the projection $\\pi_H(x)$, denoted $D_x$. It can be interpreted as the features of $x$ that do not belong to any hyperedge. If a hypergraph induced by a set of examples represents a knowledge base at a given moment, the discretionary features of $x$ are new pieces of information that were never encountered before. For instance, considering the hypergraph composed of $x_1$ and $x_2$ as illustrated by Figure \\ref{case_base}, the set of discretionary features of $x_3$ is $e_4$. In Figure \\ref{new_case_schema}, the yellow case $x$ has no discretionary feature: all its features are present at least in one example.\n\n\\begin{figure}[b]\n  \\def\\firstcircle{(0,0) ellipse (1.5cm and 1cm)}\n  \\def\\secondcircle{(80:-1cm) ellipse (1.5cm and 1cm)}\n  \\def\\thirdcircle{(0:2cm) ellipse (1.5cm and 1cm)}\n  \\begin{tikzpicture}[scale=0.5, every node/.style={scale=0.7}]\n      \\begin{scope}[fill opacity=0.3]\n          \\filldraw[fill=gray, xscale=1.4, yscale=1.4] (-3.5,-3.5) plot [smooth cycle,tension=0.7, shift={(-4,-3.2)}] coordinates {(3,1) (5,1.2) (7,1) (8,3) (7,4.5) (5,4.5) (2,4) (1.7,2.5)};\n          %\\filldraw[fill=gray] (-3.5,-3.5) rectangle (4,2);\n          \\fill[red, rotate=30, xscale=1.4, yscale=1.4] \\firstcircle;\n          \\fill[green, rotate=35, xscale=1.4, yscale=1.4] \\secondcircle;\n          \\fill[blue, xscale=1.4, yscale=1.4] \\thirdcircle;\n          \\draw[rotate=30, xscale=1.4, yscale=1.4] \\firstcircle;\n          \\draw[rotate=35, xscale=1.4, yscale=1.4] \\secondcircle;\n          \\draw[xscale=1.4, yscale=1.4] \\thirdcircle;\n\n          \\fill[yellow, rotate=110, xscale=1, yscale=1, xshift=-10, yshift=15] \\secondcircle;\n          \\draw[rotate=110, xscale=1, yscale=1, xshift=-10, yshift=15] \\secondcircle;\n\n      \\end{scope}\n      \\node at (4,-2.7) {$\\mathbb{F}$};\n      \\node at (0.5,1.3) {$x_1$};\n      \\node at (0,-2.3) {$x_2$};\n      \\node at (3,1) {$x_3$};\n\n      \\node at (-0.8  ,0.5) {$e_1$};\n      \\node at (0.2  ,0.6) {$e_1'$};\n      \\node at (1.5  ,0.7) {$e_2$};\n      \\node at (1.05  ,0.5) {$e_2'$};\n      \\node at (1.2  ,-0.2) {$e_3'$};\n      \\node at (1.675  , 0.15) {$e_3$};\n      \\node at (3.6  , -0.1) {$e_4$};\n      \\node at (2  , -0.7) {$e_5$};\n      \\node at (1.5 , -0.8) {$e_5'$};\n      \\node at (-0.6  ,-1.2) {$e_6$};\n      \\node at (0.3  ,-0.7) {$e_6'$};\n      \\node at (1  ,-1.4) {$e_7'$};\n      \\node at (0.5  ,-2) {$e_7$};\n  \\end{tikzpicture}\n  \\begin{tikzpicture}[auto, thick, scale=0.6, every node/.style={scale=0.8}, baseline={(-2,-0)}]\n    % Place super peers and connect them\n    \\node[superpeers, fill=red!30] (c1) at  (0,-4) {$x_1$};\n    \\node[superpeers, fill=blue!30] (c2) at  (2,-4) {$x_2$};\n    \\node[superpeers, fill=green!30] (c3) at  (-2,-4) {$x_3$};\n    \\node[superpeers, fill=yellow!30] (c4) at (0,0) {$x$};\n    %\\foreach \\source/\\dest in {a/b, a/c, a/d, b/c, c/d,a/e,d/e}\n    %  \\path (\\source) edge (\\dest);\n     \\node[peers, fill=black!10, label=above:{$e_2'$}] (e2) at (-2.5,-2) {};\n     \\node[peers, fill=black!10, label={[xshift=0.05cm, yshift=-0.05cm]{$e_3'$}}] (e3) at (-1.5,-2) {};\n     \\node[peers, fill=black!10, label={[xshift=-0.1cm, yshift=-0.05cm]{$e_5'$}}] (e5) at (-0.5,-2) {};\n     \\node[peers, fill=black!10, label={[xshift=0.1cm, yshift=-0.1cm]{$e_1'$}}] (e1) at (0.5,-2) {};\n     \\node[peers, fill=black!10, label={[xshift=-0.1cm, yshift=-0.1cm]{$e_6'$}}] (e6) at (1.5,-2) {};\n     \\node[peers, fill=black!10, label=above:{$e_7'$}] (e7) at (2.5, -2) {};\n\n\n     \\path[<-] (c4) edge (e1);\n     \\path[<-] (c4) edge (e2);\n     \\path[<-] (c4) edge (e3);\n     \\path[<-] (c4) edge (e5);\n     \\path[<-] (c4) edge (e6);\n     \\path[<-] (c4) edge (e7);\n\n     \\path[->] (c1) edge (e1);\n     \\path[->] (c1) edge (e2);\n     \\path[->] (c1) edge (e3);\n     \\path[->] (c1) edge (e6);\n\n     \\path[->] (c2) edge (e3);\n     \\path[->] (c2) edge (e5);\n     \\path[->] (c2) edge (e6);\n     \\path[->] (c2) edge (e7);\n\n     \\path[->] (c3) edge (e2);\n     \\path[->] (c3) edge (e3);\n     \\path[->] (c3) edge (e5);\n\n  \\end{tikzpicture}\n  \\caption{\\label{new_case_schema} The projection of $x$ on $H$ is represented by the family  $\\{ e'_i\\}_i$. Under the projection lies a graph representation of $x$ with the partition elements $\\{ e_i\\}_i$ and their respective connections to the cases $\\{x_i\\}_i$, in particular, $D_x = \\emptyset$.}\n\\end{figure}\n\nFor any set of features $x \\subseteq \\mathbb F$, we define $d_H(x) = \\{ x' \\in X ~ | ~ x \\cap x' \\neq \\emptyset \\}$ the set of edges sharing some features with $x$. In particular, the set $d_H$ can be split into $d_H^{(1)}$ and $d_H^{(0)}$ depending on the label of the case and defined by $d_H^{(l)}(x) = \\{x' \\in d_H(x) ~ | ~ J(x') = l \\}$. $|d_H(x)|$ corresponds to the number of cases the case $x$ intersects while $|d_H^{(l)}(x)|$ counts the number of times the class $l$ is used among this set of intersecting cases. Note that if $x \\not \\in X$ and $|d_H(x)| = 0$, then $x = D_x$, i.e. the case $x$ is in relation with no case in $X$. In the hypergraph literature, $|d(x)|$ is called the {\\it degree} of a hyperedge and its domain of definition is restricted to $X$.\n\nFrom now, we consider only the specific hypergraph generated by the set of examples $X$. For the sake of readability, we remove the subscript $H$.\n\n\\subsection{Model Space}\n\nIn many binary classification approaches such as SVM or logistic regression, the model space consists of the set of hyperplanes of a given inner product space, usually $\\mathbb{R}^M$. A hyperplane in $\\mathbb{R}^M$ is uniquely defined by $M+1$ parameters. For an input vector $x$, its margin $m(w,x)$ is defined by its distance to a hyperplan defined by $w$ and is negative in case $x$ is wrongly classified, positive otherwise. Thus, the problem consists in finding the {\\it best} parametrization to minimize a loss function summed over the training set. For instance, the Perceptron algorithm minimizes the 0-1 loss, SVM the hinge loss, and the Logistic Regression uses the log loss. Those functions are defined by \\eqref{eqn:loss_functions}.\n\\begin{align}\n  \\label{eqn:loss_functions}\n  \\begin{matrix}\n    L_{01}({w}, {x}) & = & \\mathds{1}_{\\{ m({w}, {x}) \\leq 0 \\}} \\hfill \\\\\n    L_{\\text{hinge}}({w}, {x}) & = & \\max(0, 1 - m({w}, {x})) \\hfill \\\\\n    L_{\\log}({w}, {x}) & = & \\ln(1 + e^{- m{w}, {x})}) \\hfill\n  \\end{matrix}\n\\end{align}\n\nIn this paper, we relax the three implicit constraints on the input vector space:\n\\begin{enumerate}\n\\item we do not assume to have any inner product or metric embedded with the input vector space,\n\\item we do not assume the cardinality of the input vectors, such that it is possible to build a model and make predictions on incomplete systems (for instance missing in some rows in a database or Bag-of-Words representation),\n\\item we do not assume anything about the concrete {\\it representation} of features while in most classification methods, all the features belongs to the same space, often $\\mathbb{R}$.\n\\end{enumerate}\nAs a counterpart, \\HCBR~ relies on two assumptions: (i) the correct class of an input vector is the result of its features only and (ii) if two input vectors $x$ and $x'$ do not share any feature, they are {\\it independent} i.e. $x$ cannot help to understand the correct class of $x'$ and vice versa. As a result, \\HCBR~  produces only {\\it local} models because if a new input vector is independent of all examples, it is impossible to generate a prediction. On the contrary, a hyperplane model is {\\it global} in a sense that it can produce a prediction for any element of $\\mathbb{R}^M$.\nA concrete situation for which such assumptions are natural is a justice trial. Cases are composed of some elements, and the correct label is the result of a reasoning that can possibly use analogies or counter-examples with a set of past cases on top of the legal texts. However, if a judge or lawyer wants to use $x$ to justify the outcome of $x'$, $x'$ must have similarities with $x$.\n\nLet us formally define the model space. Given the hypergraph $H = (\\mathbb F, X)$ defined by a training set $X$ and its associated partition $\\mathcal{E} = \\{e_i\\}_i^m$, the relation between an example $x$ and its class is modeled by\n\\begin{align}\n\\label{eqn:model}\n\\left\\{\\begin{matrix}\ns_{w, \\mu}({x}) & = & \\underset{i = 1}{\\overset{m}\\sum} w({e}_i, {x}) \\mu({e}_i)% = <\\mathbf{w}_i, \\mathbf{\\mu}_i >_{( \\mathbf{X}, \\mathbf{y})}\n\\\\\n\\underset{i = 1}{\\overset{m}\\sum} w({e}_i,{x}_j) & = & 1 ~ \\hfill \\forall 1 \\leq i \\leq n\\\\\n\\underset{i = 1}{\\overset{n}\\sum} \\mu({e}_i) & = & 1 \\hfill \\forall 1 \\leq i \\leq m \\hfill\n\\end{matrix}\\right.\n\\end{align} where $w({e}_i, {x}_j) \\geq 0$ models the importance of ${e}_i$ in ${x}_j$ and $\\mu({e}_i)$ the support of ${e}_i$ for class 1 w.r.t. whole training set. For this reason, we call $\\mu$ the {\\it intrinsic strength} of $e_i$. The assumption (ii) implies that if ${e}_i \\cap {x}$ then $w({e}_i, {x}) = 0$. For readability, we write $s$ in place of $s_{w, \\mu}$.\n\nThe classification rule consists in selecting the class with the total highest support.\n \\begin{align} \\tag{R1} \\label{eqn:decision_rule}\n \\forall x \\in \\mathcal{P}(\\mathbb F), ~ \n   \\bar J(x) =  \\left\\{\\begin{matrix}\n  1 & ~s(x) > 0\\\\ \n  0 & ~s(x) \\leq  0\n  \\end{matrix}\\right.\n  \\end{align} Our goal is to select $w$ and $\\mu$ such that the classification rule \\eqref{eqn:decision_rule} provides a good solution to the original problem \\eqref{eq:pb}. For this purpose, we proceed in three steps:\n\n  \\begin{enumerate}\n  \\item Define $w$ and $\\mu$ to capture as much information as possible from $\\mathcal E$ for any $X$ (Section \\ref{sec:model_selection}).\n  \\item Train the model to adjust the intrinsic strength on a specific $X$ using the classification rule \\eqref{eqn:decision_rule} (Section \\ref{sec:decision_training}).\n  \\item Refine the classification rule \\eqref{eqn:decision_rule} to take into account the local nature of the model (Section \\ref{sec:decision_training}).\n  \\end{enumerate} A summary and high level view of \\HCBR~ is given by Algorithm~\\ref{algo:HCBR}.\n\n\\algrenewcommand\\algorithmicindent{1.0em}%\n\\begin{algorithm}\n  \\caption{HCBR (High level view)}\\label{algo:HCBR}\n  \\begin{algorithmic}[1]\n    \\State Build $H$ and $\\mathcal E$ from $X$.\n    \\State Calculate $w$ and $\\mu$ on $\\mathcal E$.\n    \\State Adjust $\\mu$ with training algorithm \\ref{training} on $X$ using rule \\eqref{eqn:decision_rule}\n    \\For{each $x$ in test set}\n        \\State Calculate the projection $\\pi(x)$.\n        \\State Calculate the support $s(x)$ using the projection.\n        \\State Predict using the updated rule \\eqref{eqn:updated_cr}.\n    \\EndFor\n  \\end{algorithmic}\n\\end{algorithm}\n\n\nWhile SVM aims at separating the data using a single hyperplane in the original input vector space, \\HCBR~ tries to explain the decision for each case by a convex combination expressed in a lower dimensional space $\\mathcal E$ generated by the data. In addition, the convex combinations depend on each other since the elements of $\\mathcal E$ are by definition the features resulting in the case intersections. For any case, the decision rule is a combination of the strength of the elements of its projection on the hypergraph.\n\n\\subsection{Model Selection}\n\\label{sec:model_selection}\n\nIn this section, we define how to concretely select and calculate $w$ and $\\mu$ for a given hypergraph. To ease the notation and for practical reasons, the measure $\\mu$ is provided w.r.t. the intersection family $\\mathcal E$ of the hypergraph induced by the training set $X$. However, $\\mu$ can be defined over any partition of $\\mathbb F$.\n\nFor $x$ and $x'$ in $\\mathcal P({\\mathbb F})$, a basic quantitative measure on the importance of $x'$ w.r.t. $x$ can be expressed by $\\frac{|x \\cap x'|}{|x|}$, i.e. how much $x'$ overlaps with $x$. This measure is a sort of {\\it potential} for an analogy with $x$. Potential because it does not account for the individual importance of the features and simply holds the idea that the larger is a subset of features in a case, the higher is the chance it holds important features to decide the outcome.\n\nLet us consider $\\mathcal E$ and an example $x \\in X$.\n\\begin{definition}[Intrinsic strength w.r.t. $x$]\n  The intrinsic strength of $e \\in \\mathcal E$ w.r.t. $x \\in X$ is defined by \\begin{align}\n    \\begin{split}\n    \\forall l \\in \\{ 0, 1\\}, ~ S^{(l)}(e, x) & = \\frac{|d^{(l)}(e)| \\frac{|x \\cap e|}{|x|}}{\\underset{e_j \\in \\mathcal E}{\\sum}|d^{(l)}(e_j)|  \\frac{|x \\cap e_j|}{|x|}} \\\\\n    & = \\frac{|d^{(l)}(e)|  |x \\cap e|}{\\underset{e_j \\in \\mathcal E}{\\sum}|d^{(l)}(e_j)| |x \\cap e_j|}\n    \\end{split}\n    \\end{align}\n  %\\mynote{Maybe it would be better to define it over any partition first.}\n\\end{definition}\n\\noindent\nIn particular, for a given $x \\in X$, $S^{(l)}(e_i, x) =0$ if $e_i$ is not part of the projection of $x$ on $H$. Also, $\\underset{e \\in \\mathcal E}{\\sum} S^{(l)}(e, x) = 1$ which can be interpreted as how much $e$ accounts for the set of labels $l$ the element $x$ holds in its projection.\nThe more $e_i$ belongs to many cases with the same class $l$ and the higher $S^{(l)}(e_i, x)$ is. Conversely, for a fixed number of cases, the more $e_i$ describes $x$, the higher $S^{(l)}(e_i, x)$ is. As $\\forall e_i \\in \\mathcal E, ~ |d(e_i)| > 0$, either we have $S^{(1)}(e_i, x) \\neq 0$ or $S^{(0)}(e_i, x) \\neq 0$. We have $S^{(l)}(e_i, x) = 0$ only when all the cases in which $e_i$ results of are labeled with the opposite class $\\bar l$. For $S^{(l)}(e_i, x) = 1$, it needs both the unanimity of labels for the cases in which $e_i$ belongs to and that $e_i = x$. The relation $e_i = x$ implies that $x$ does not share any feature with any other examples or that $x$ is included into another example.\n\\begin{definition}[Intrinsic strength w.r.t. a hypergraph $H$]\n  \\label{intrinsic_strength}\n  The instrinsic strength of $e \\in \\mathcal{E}$ w.r.t. $H = (\\mathbb{F}_X, X)$ is defined by\n  \\begin{align}\n  \\begin{split}\n  \\forall l \\in \\{ 1, 0 \\}, ~ S^{(l)}(e) & = \\frac{|e|}{ \\underset{e' \\in \\mathcal{E}}{\\sum} |e'|} \\underset{x \\in d^{(l)}(e)}{\\sum} S^{(l)}(e, x) \\\\\n  & = \\frac{|e|}{|\\mathbb{F}_X|} \\underset{x \\in d^{(l)}(e)}{\\sum} S^{(l)}(e, x)\n   \\end{split}\n  \\end{align} The measure $S^{(l)}(e)$ is simply the sum of the relevance for all the examples $e$ belongs too. The more $e$ belongs to several cases, the more information it has to support a class or another. As $\\mathcal E$ represents the sets of features that appear all the time together, we favor the larger $e \\in \\mathcal E$ as they hold more information to explain a decision.\n  The normalized version is defined by:\n    \\begin{align}\n  \\forall l \\in \\{ 1, 0 \\},~ \\mu^{(l)}(e) & = \\frac{S^{(l)}(e)}{ \\underset{e' \\in \\mathcal{E}}{\\sum} S^{(l)}(e')}\n  \\end{align}\n\\end{definition} \nFinally, the measure $\\mu$ is simply defined by the difference between the strength of both classes:\n\\begin{align}\n  \\mu(e) = \\mu^{(1)}(e) - \\mu^{(0)}(e)\n\\end{align}\n\n\nFor any case $x$, the projection on the hypergraph $\\pi(x)$ intersects with some elements of $\\mathcal E$. We use this intersection to define $w$ by\n\\begin{align}\n w(e, x) = \\frac{|x \\cap e|}{|x \\setminus D_x|}\n \\end{align}, i.e. we modulate the strength of an element of the partition by its importance in $x$ w.r.t. set inclusion.\nIn a sense, the projection on the hypergraph provides all the possible analogies with the training set, either seen as a support for a particular outcome $l$ or as a counter-example. The intrinsic strength of each element of this partition is a measure of ``how much it can be considered as a counter-example or an analogy'' taking into account simultaneously all the analogies between the examples that are in relation with the considered case. It favors the importance of the relation (the more features it shares, the stronger is the analogy) but also the quality of the relation (the more examples sharing the same class the stronger the analogy). \n\n\n~\\\\\\noindent\n{\\bf Example:} Consider the hypergraph in Figure \\ref{case_base} made of $x_1$, $x_2$ and $x_3$ arbitrarily labeled with resp. 1, 0 and 1. Arbitrarily, we assume the cardinal of the elements of $\\mathcal E$ to be $\\#e = (2,1,2,3,1,2,3)$ such that the cardinal of cases are $\\#x = (7, 8, 7)$ and $|\\mathbb{F}_X| = 14$. The values of $|d^{(l)}(e)|$ can be summarized by the vectors $\\#d^{(0)} = (0, 0, 1, 0, 1, 1, 1)$ and $\\#d^{(1)} = (1 , 2, 2, 1, 1, 1, 0)$. Let us calculate $S^{(0)}(e_3)$:\n\n\\begin{align*}\nS^{(1)}(e_3, x_1) & = \\frac{2 \\times 2}{2 \\times 1 + 1 \\times 2 + 2 \\times 2 + 1 \\times 2} = \\frac 4 {10} \\\\\nS^{(1)}(e_3, x_2) & = \\frac{2 \\times 2}{2 \\times 2 + 1 \\times 1 + 1 \\times 2 + 0 \\times 3} = \\frac 4 {7} \\\\\nS^{(1)}(e_3, x_3) & = \\frac{2 \\times 2}{2 \\times 1 + 2 \\times 2 + 3 \\times 1 + 1 \\times 1} = \\frac 4 {10}\n\\end{align*}\n which we interpret as $e_3$ being responsible for $\\frac{4}{10}$ of the support toward class 1 in $x_1$ and $x_3$, while $\\frac{4}{7}$ for $x_2$.\nThis lead to\n$$S^{(1)}(e_3) = \\frac 2 {14} \\big[ \\frac 4 {10} + \\frac 4 {7} + \\frac 4 {10}\\big] \\simeq 0.1959$$\n\nSimilarly, we calculate the support for each $e$ and both labels. We summarize this into the following vectors:\n\n\\begin{align*}\nS^{(1)} & \\simeq (\n0.0286,\n0.0286,\n0.1959 ,\n0.0643,\n0.0173,\n0.0694, \n0.0000) \\\\ S^{(0)} &\\simeq (\n0.0000,\n0.0000,\n0.2024,\n0.0000,\n0.0327,\n0.1071, \n0.0000)\\end{align*} After normalization, we obtain the intrinsic strength:\n$$\\mu \\simeq (0.0707, 0.0707, 0.0060, 0.1591, -0.0345, -0.0818, -0.1901)^T$$\nLet us evaluate the model on the three examples:\n\\begin{align*}\n  s(x_1) & = \\frac{2}{7}\\mu(e_1) + \\frac{1}{7}\\mu(e_2) + \\frac{2}{7}\\mu(e_3) + \\frac{2}{7}\\mu(e_6) \\simeq 0.0086\\\\\n  s(x_2) & = \\frac{2}{8}\\mu(e_3) + \\frac{1}{8}\\mu(e_5) + \\frac{2}{8}\\mu(e_6) + \\frac{3}{8}\\mu(e_7) \\simeq -0.0946\\\\\n  s(x_3) & = \\frac{1}{7}\\mu(e_2) + \\frac{2}{7}\\mu(e_3) + \\frac{3}{7}\\mu(e_4) + \\frac{1}{7}\\mu(e_5) \\simeq 0.0751\\\\\n\\end{align*}\nAs a result, $x_1$ and $x_3$ are labeled $1$ and $x_2$ is labeled $0$. All three cases are correctly labeled. The highest support is given for case $x_2$ and $x_3$ while the support for $x_1$ is one order of magnitude lower then for $x_3$. This is because the discretionary features of $x_3$ are larger while the intersection with $x_2$ is lower than for $x_1$ ($\\frac 3 8$ of $x_3$ against $\\frac 4 7$ of $x_1$).\n\nConsider a new case $x$ as described on Figure \\ref{new_case_schema}. Its support is given by $s(x) = \\underset{e \\in \\pi(x)}{\\sum} w(e, x)\\mu(e)$ with $\\pi(x) = \\{ e_1, e_2, e_3, e_5, e_6, e_7\\}$. It is impossible for $x$ to be classified as $1$ because the highest support would be for a maximal intersection with $e_1$, $e_2$, $e_3$ and minimal for $e_5$, $e_6$ and $e_7$ such that $s(x) = \\frac{1}{8}(2 \\mu(e_1) + \\mu(e_2) + 2 \\mu(e_3) + \\mu(e_5) + \\mu(e_6) + \\mu(e_7)) \\simeq -0.0103 < 0$. It can be explained by the fact that the support for 1 is provided by a larger set of features (11 features versus 8). On top of that, the intersections between positive cases ($e_2$ and $e_3$) are too small (1 for $e_2$ compared to e.g. 3 for $e_7$) or include also negative cases ($e_3$).\n\n\\subsection{Training and Decision}\n\\label{sec:decision_training}\n\nIn this section, we give an algorithm to adjust the intrinsic strength $\\mu({e}_i)$ in order to minimize a hinge loss and we update the classification rule to take into account the fact the model cannot provide predictions over $\\mathbb F$ entirely.\n\nOnce the model is built, it can be evaluated on the training set. Analogously to SVM, we define the margin as the distance to the correct class, i.e. $m(w, \\mu, x) = s_{w,\\mu}(x)|J(x) - \\bar J(x)|$. To improve the pertinence of the strength of the elements of $\\mathcal{E}$, we use the iterative algorithm described by Algorithm \\ref{training} to minimize the hinge loss over the training set $X$.\nWhen and only when a classification for a case $x$ is wrong, it modifies each element of its projection by lowering its strength for the wrong class and increasing it for the proper class. The margin is split between the element of the projection w.r.t. their respective weight in $x$ i.e. $w(e,x)$. If a case $x$ is wrongly classified, it is due to the cases intersecting with it. Indeed, if $x$ was not intersecting with any other example, its projection would be itself, and its support toward the wrong class would be 0 and positive for the real class. In other words, $x$ would be correctly classified. Thus, the idea is not to directly bring the support of $x$ to the correct class but to gradually adjust the weights such that the neighbors are modified enough for $x$ to be correctly classified. In particular, it is sensitive to the order in which the cases are considered: a modification in the strength of any $e \\in \\mathcal{E}$ impacts all cases in which it appears and potentially changes the predicted class for those cases. In addition, there is no guarantee of convergence. Future work will focus on the optimal order or a modification schema such that the algorithm converges. Investigating other minimizing functions is also considered.\n\\algrenewcommand\\algorithmicindent{1.0em}%\n\\begin{algorithm}\n  \\caption{Model training}\\label{training}\n  \\begin{flushleft}\n  \\textbf{Input:} \\\\\n    ~~- $X$: training set \\hfill\\\\\n    ~~- $y$: correct labels for $X$\\\\\n    ~~- $k$: number of training iterations\\\\\n    ~~- $\\mu^{(1)}, \\mu^{(0)}$: weights calculated with \\eqref{intrinsic_strength}\\\\\n    \\textbf{Output:} \\\\\n    ~~- Modified vectors $\\mu^{(1)}, \\mu^{(0)}$\n  \\end{flushleft}\n  \\begin{algorithmic}[1]\n      \n      \\For{$k$ \\texttt{iterations}}\n        \\For{$x_i \\in X$}\n          \\State $\\bar y_i \\gets \\bar J(x_i)$\n          \\If{$\\bar y_i \\neq y_i$}\n            \\For{$e \\in \\pi(x_i)$}\n              \\State $\\mu^{(y_i)}(e) \\gets \\mu^{(y_i)}(x_i) + w(e,x_i) |\\mu(e)|$\n              \\State $\\mu^{(\\bar y_i)}(e) \\gets \\mu^{(\\bar y_i)}(x_i) - w(e,x_i) |\\mu(e)|$\n            \\EndFor\n          \\EndIf\n        \\EndFor\n      \\EndFor\n  \\end{algorithmic}\n\\end{algorithm}\n\n\nThe measure $\\mu$ is defined as the difference of support for both classes. Thus, by linearity we can rewrite\n\\begin{align}\n \\begin{split}\ns(x) & = \\underset{i = 1}{\\overset{m}\\sum} w({e}_i, {x}) \\mu^{(1)}({e}_i) - \\underset{i = 1}{\\overset{m}\\sum} w({e}_i, {x}) \\mu^{(0)}({e}_i) \\\\\n           & = s^{(1)}(x) - s^{(0)}(x)\\hfill\n \\end{split}\n\\end{align}\nThis form is convenient because we can control how much evidence we need to support a specific class using the following constraints and a familly $\\eta$ of four hyperparameters:\n\\begin{subequations}\n\\begin{align}\n  \\tag{$C_0$}\n  s^{(0)}(x) > \\max(\\frac{\\bar \\eta_0}{1 - \\bar \\eta_0}s^{(1)}(x), \\eta_0) \\geq 0\\label{eqn:n0} \\\\\n  \\tag{$C_1$}\n  s^{(1)}(x) > \\max(\\frac{\\bar \\eta_1}{1 - \\bar \\eta_1}s^{(0)}(x), \\eta_1) \\geq 0\\label{eqn:n1}\n\\end{align}\n\\end{subequations} with $\\eta_0, \\eta_1 \\in \\mathbb{R}^+$ and $\\bar \\eta_0, \\bar \\eta_1 \\in [0,1]$.\nThe constraints on $\\eta_0$ and $\\eta_1$ defines a minimal amount of support respectively toward class 0 and 1 while $\\bar \\eta_0$ and $\\bar \\eta_1$ requires the support toward a class to be significantly higher than the support for the other class.\nAs $\\mu$ is normalized over the partition $\\mathcal E$, the value of $\\eta_0$ and $\\eta_1$ must be set w.r.t. the hypergraph. On the contrary, $\\bar \\eta_1$ and $\\bar \\eta_0$ can be set independently of the hypergraph.\n\nThose constraints may be used to design a decision rule for new cases depending on the application or the dataset. The most generic decision rule is as follows:\n\\begin{align}\n\\label{eqn:decision_rule_revised}\n   \\tilde J(x) =  \\left\\{\\begin{matrix}\n  1 & ~ s( x) > 0 & \\text{ and } C_1 \\hfill\\\\ \n  0 & ~  s( x) \\leq 0 &\\text{ and } C_0 \\hfill\\\\\n  l_1 & ~ s( x) > 0 & \\text{ and not } C_1 \\hfill\\\\ \n  l_0 & ~  s( x) \\leq 0 & \\text{ and not } C_0 \\hfill\n  \\end{matrix}\\right.\n  \\end{align} where $l_1, l_0$ are two labels. A representation is given by Figure~\\ref{decision_space}.\nThose hyperparameters are intended to model the ``burden of proof''. For instance, in a trial, one is assumed innocent until proven guilty which implies the support for the class \"guilty\" must be {\\it beyond a reasonable doubt} (where the term reasonable is defined by the jurisprudence of the applicable country). In case $\\eta_0 = \\eta_1 = \\bar \\eta_0 = \\bar \\eta_1$ (and $l_0 = 0$ and $l_1 = 1$), then the decision rule is equivalent to the original one defined by \\eqref{eqn:decision_rule}.\n\\begin{figure}\n \\begin{tikzpicture}[scale=1.0]\n    %Draw axis\n    \\coordinate (y) at (0,2);\n    \\coordinate (x) at (3,0);\n    \\coordinate (mx) at (-3,0);\n    \\draw[axis] (y) -- (0,0) --  (x);\n    \\draw[axis] (y) -- (0,0) --  (mx);\n    %Important coordinates. These are used in both figures and can be\n    %moved to a seperate settings files\n    %% These coordinates deside where boxes start on the y axis\n    \\coordinate (alphaas) at ($0.4*(y)$);\n    \\coordinate (alphabs) at ($0.3*(y)$);\n    %% These coordinates deside where boxes end on the x axis\n    \\coordinate (cfas) at ($1*(x)$);\n    \\coordinate (cfbs) at ($-1*(x)$);\n    %These sets the interest rate lines \n    \\coordinate (rl) at ($.4*(x)$);\n    \\coordinate (rr) at ($-.2*(x)$);\n\n   \n    \\draw (0,1.8) node[label={[shift={(-0.2,-0.15)}]$1$}] {} -- (3,1.8);\n    \\draw (0,1.8) node[left] {} -- (-3,1.8);\n\n\n    \\draw[help lines] let \\p1=(alphaas), \\p2=(cfas) in \n    (\\x2, \\y1) node[right] {$\\bar{\\eta}_1$} -| (\\p1);\n    %node[below] {$\\mathit{NV^\\A_s}$};\n    %Second, let us connect alpha^\\B_s og NV^B_s\n    \\draw[help lines] let \\p1=(alphabs), \\p2=(cfbs) in \n    (\\x2, \\y1) node[left] {$\\bar{\\eta}_0$} -| (\\p1);\n    %node[below] {$\\mathit{NV^\\B_s}$};\n    %A line seperating the boxes.\n    \\draw[help lines] let \\p1=(rl), \\p2=(0,1.8) in\n    (\\p1) node[below] {$\\eta_1$} -- (\\x1, \\y2);\n\n    \\draw[help lines] let \\p1=(rr), \\p2=(0,1.8) in\n    (\\p1) node[below] {$\\eta_0$} -- (\\x1, \\y2);\n    %%%%%%%%%%%%%%%%%%%%%%\n    %The small boxes will be assinged letter\n    %%%%%%%%%%%%%%%%%%%%%%\n    %%C\n    \\draw let \\p1=($(alphaas)-(alphabs)$), \\p2=(rl), \\p3=(alphabs) in\n    ($(.5*\\x2, 2.5*\\y3)$) node {$l_1$};\n    %%D\n    \\draw let \\p1=($(alphaas)-(alphabs)$), \\p2=($(cfas)-(rl)$),\n    \\p3=(alphabs), \\p4=(rl) in\n    ($(.5*\\x2+\\x4, 2.*\\y3)$) node {$1$};\n    %%E\n    \\draw let \\p1=(alphabs), \\p2=(rl) in\n    ($(.5*\\x2, .5*\\y1)$) node {$l_1$};\n    %%F\n    \\draw let \\p1=(alphabs), \\p2=($(cfas)-(rl)$), \\p3=(rl) in\n    ($(.5*\\x2+\\x3, .5*\\y1)$) node {$l_1$};\n\n\n\n    %%C\n    \\draw let \\p1=($(alphaas)-(alphabs)$), \\p2=(rr), \\p3=(alphabs) in\n    ($(.5*\\x2, 2.5*\\y3)$) node {$l_0$};\n    %%D\n    \\draw let \\p1=($(alphaas)-(alphabs)$), \\p2=($(cfbs)-(rr)$),\n    \\p3=(alphabs), \\p4=(rr) in\n    ($(.5*\\x2+\\x4, 2.*\\y3)$) node {$0$};\n    %%E\n    \\draw let \\p1=(alphabs), \\p2=(rr) in\n    ($(.5*\\x2, .5*\\y1)$) node {$l_0$};\n    %%F\n    \\draw let \\p1=(alphabs), \\p2=($(cfbs)-(rr)$), \\p3=(rr) in\n    ($(.5*\\x2+\\x3, .5*\\y1)$) node {$l_0$};\n\n\n\n    \\draw (0,0) node[below] {$0$};\n    \\draw (3,0) node[below] {$s(x)$};\n    \\draw (0,2) node[above] {$\\frac{\\max(s^{(1)}(x), s^{(0)}(x))}{s^{(1)}(x) + s^{(0)}(x)}$};\n  \\end{tikzpicture}\n  \\caption{\\label{decision_space} Representation of the updated decision rule \\eqref{eqn:decision_rule_revised}.}\n\\end{figure}\nIn case $x$ has too many discretionary features, this classification rule is likely to be irrelevant. Indeed, the intersection between $x$ and $\\mathbb{F}_X$ is to small to hold enough information and make strong analogies with $x$. To overcome this drawback, $\\mathcal P({\\mathbb F})$ is split into two subsets:\n\\begin{itemize}\n  \\item $\\mathcal{F}_1 = \\{ x \\in \\mathcal P({\\mathbb F}) ~ | ~ |x \\cap \\mathbb{F}_X| \\geq \\delta\\}, ~ \\forall \\delta \\in \\mathbb{N}$\n  \\item $\\mathcal{F}_2 = \\mathcal P({\\mathbb F}) \\setminus \\mathcal{F}_1$\n\\end{itemize}\n$\\mathcal{F}_1$ corresponds to the elements such that they share some features with the examples. An alternative may be considered by using $\\mathcal{F}_1 = \\{ x \\in \\mathcal P({\\mathbb F}) ~ | ~ \\frac{D_x}{|x|} \\leq \\delta\\}, ~ \\forall \\delta \\in [0,1]$. In this case, $\\mathcal{F}_1$ contains the elements for which we have enough information provided by the examples. From our preliminary tests, the choice depends on the dataset structure.\n\nFinally, the decision rule for new cases is built as follows:\n\\begin{align}\n\\tag{R2} \\label{eqn:updated_cr}\n \\bar J(x) = \\left\\{\\begin{matrix}\n \\tilde J(x) & \\text{if} ~ x \\in \\mathcal{F}_1 \\\\\n o_x & \\text{if} ~ x \\in \\mathcal{F}_2\n\\end{matrix}\\right.\n\\end{align} where $o_x$ is one draw from a random variable that has Bernoulli law with parameter $p=\\frac{|\\{x \\in X | J(x) = 1 \\}|}{|X|}$, i.e. the prevalence of $1$ in $X$. This assumes that $X$ is correctly representing $\\mathcal P({\\mathbb F})$ (or that the prevalence does not change in time for sequential problems in which the new cases are generated by an unknown random measure). The rational behind is that if for a case $x$, it is not possible to exploit the model built on the hypergraph, then we can still consider that $J$ acts as a Bernoulli random variable and use a maximum likelihood estimation for $p$. In a sense, it is extending the {\\it local} model to the entire input vector space $\\mathcal{P}(\\mathbb F)$.\n\n\n\\subsection{Complexity}\n\\label{sec:complexity}\n\n\n{\\bf Model Building:} Given $X \\in \\mathcal P({\\mathbb F})^n$, constructing $\\mathcal{E}_H$ can be done in $\\mathcal{O}(\\underset{x \\in X}{\\sum}|x|)$ by using a Partition Refinement data structure~\\cite{Paige:1987:TPR:37185.37186}. Given $x \\in X$, calculating the family $\\{S(e, x)\\}_{e \\in \\mathcal{E}_H}$ can be done in $\\mathcal{O}(|x|)$ by asking for each feature of $x$ the $e$ it belongs to and maintaining the size of each $e$ during the construction of $\\mathcal{E}_H$. Thus, calculating $\\{S(e, x)\\}_{e \\in \\mathcal{E}_H}$ for all $x \\in X$ can be done in $\\mathcal{O}(\\underset{x \\in X}{\\sum}|x|)$. On $m$-uniform hypergraphs (when all cases are described with $m$ features) with $n$ hyperedges, it becomes $\\mathcal{O}(mn)$. \n\nCalculating $\\{S(e)\\}_{e \\in \\mathcal{E}_H}$ and $\\mu$ can be done in $\\mathcal{O}(|\\mathcal{E}_H|)$ because it requires to iterate over $\\mathcal{E}_H$. An obvious upper bound on $|\\mathcal{E}_H|$ is $|\\mathbb{F}_X|$ i.e. the number of vertices in the hypergraph. The worst-case cardinal of $\\mathcal{E}_H$ is when each $x \\in X$ intersects with all the others and none of them is strictly a subset of any other. Thus, $|\\mathcal{E}_H| \\leq \\min(2^n -1, |\\mathbb{F}_X|)$.\\\\\n\n\\noindent\n{\\bf Learning Phase:} For each wrongly classified $x \\in X$, the training requires at most $\\mathcal{O}(|x|)$ steps (maximal cardinal for $\\pi(x)$). The worst-case scenario is when the model wrongly classifies every $x \\in X$. Thus, the learning phase worst-case complexity is $\\mathcal{O}(k \\underset{x \\in X}{\\sum}|x|)$ and on $m$-uniform hypergraphs it becomes $\\mathcal{O}(k m n)$.\\\\\n\n\\noindent\n{\\bf Model Query:} For a case $x \\in \\mathcal P({\\mathbb F})$, the projection can be done in $\\mathcal{O}(|x|)$. Calculating the classification rule also requires at most $\\mathcal{O}(|x|)$ (maximal cardinal for $\\pi(x)$).\n\n\n\\section{Experiments}\n\\label{sec:experiments}\n\nThe experiments are broken down into two parts: the comparison with literature results in terms of classification performance, and intrinsic performance (computation time and influence of parameters).\n\n For the first part, we measured the confusion matrix obtained over all the runs but also after each prediction. From this confusion matrix, we calculated the standard performance indicators: accuracy, recall, specificity, precision, negative prediction value, $F_1$-score and Matthews correlation coefficient. Denoting by TP the number of true positives, TN the true negatives, FP the false positives and FN the false negative, the $F_1$-score and Matthews correlation coefficient are defined by:\n\\begin{align*}\nF_1 & = \\frac{2 TP}{ 2TP + FP + FN} \\\\\n    & \\\\\nMCC & = \\frac{TP \\times TN - FP \\times FN}{\\sqrt{(TP + FP)(TP + FN)(TN + FP)(TN + FN)}}\n\\end{align*}\n$F_1$- score and Matthews correlation coefficients respectively belongs to $[0,1]$ and $[-1,1]$ and the closer to 1, the better it is. Both takes into account false positive and false negatives. In particular, Matthews correlation coefficient is very adapted for binary classification on unbalanced dataset (with a prevalence far from $0.5$). However, as many studies do not report them, we will base our comparison with literature results on the accuracy defined by:\n\\[\n  ACC = \\frac{TP + TN}{TP + TN + FP + FN}\n\\]\n\nFor the second part, we studied the computation time depending on the number of cases and the size of each case in order to validate the worst-case complexity given in Section \\ref{sec:complexity}. We also studied the influence of the training set size on the accuracy.\n\nThe integrality of the data used for the experiments, as well as the scripts to transform them and analyze the results are available in the \\HCBR~ Github repository\\footnote{\\href{https://github.com/aquemy/HCBR}{https://github.com/aquemy/HCBR}} and the whole experimental campaign starting from the raw data can be reproduced in \"one click\". \n\n\\begin{table*}[tb]\n\\begin{center}\n  \\caption{Datasets description. }\n  %\\resizebox{12cm}{!}{\n  \\begin{small}\n  \\begin{tabular}{|l|c|c|c|c|c|c|c|}\n    \\hline\n     & Cases & Total Features & Unique & Min. Size & Max. Size & Average Size & Real \\\\\n    \\hline\n    \\texttt{adult} & 32561 & 418913 & 118 & 10 & 13 & 12.87 & No\\\\\n    \\texttt{audiology} & 200 & 13624 & 376 & 70 & 70 & 70 & No\\\\\n    \\texttt{breasts} & 699 & 5512 & 80 & 8 & 8 & 8 & No \\\\\n    %\\texttt{diabete} & 768 & 4889 & 1255 & 8 & 8 & 8 \\\\\n    %\\texttt{german\\_numbers} & 1000 & 24725 & 274 & 24 & 25 & 24 \\\\\n    \\texttt{heart} & 270 & 3165 & 344 & 12 & 13 & 12.99 & Yes\\\\\n    \\texttt{mushrooms} & 8124 & 162374 & 106 & 20 & 20 & 20 & No\\\\\n    \\texttt{phishing} & 11055 & 319787 & 808 & 29 & 29 & 29 & No\\\\\n    \\texttt{skin} & 245057 & 734403 & 768 & 3 & 3 & 3 & Yes\\\\\n    \\texttt{splice} & 3175 & 190263 & 237 & 60 & 60 & 60 & No\\\\\n    %\\texttt{fourclass} & 862 & 2239 & 346 & 2 & 3 & 2 \\\\\n    %\\texttt{covetype} & 39274 & 418831 & 13183 & 11 & 11 & 11 \\\\\n    \\hline\n  \\end{tabular}\n  %}\n  \\end{small}\n  \\label{table:dataset}\n\\end{center}\n\\end{table*}\n\\subsection{Classification performance}\n\nTo validate the approach, 8 datasets for binary classification have been used. They are available either from the UCI Machine Learning Repository\\footnote{\\href{https://archive.ics.uci.edu/ml/index.php}{https://archive.ics.uci.edu/ml/index.php}}\n or provided with the LIBSVM\\footnote{\\href{https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/binary.html}{https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/binary.html}}\n : \\texttt{adult}, \\texttt{audiology}, \\texttt{breasts}, \\texttt{heart}, \\texttt{mushrooms}, \\texttt{phishing}, \\texttt{skin} and \\texttt{splice}. For each dataset, the original features \\texttt{(name=value)} are converted into a unique identifier and the union of all such identifiers constitute the information set $\\mathbb{F}$ considered by the algorithm. Notice that there is no need to remove the rows with empty values. The dataset \\texttt{audiology} initially contains several classes corresponding to several ear abnormalities. They are grouped to obtain two classes (normal ear and abnormal ear). able \\ref{table:dataset} describes each dataset. The minimal, maximal and average size give information about the case sizes (notice some cases are missing values for \\texttt{adult}, \\texttt{heart} and \\texttt{mushrooms} datasets). The unique features are the number of \\texttt{(name=value)} in the original dataset. In addition, two datasets have at least one real-valued attribute as indicated by the column \"Real\" in Table \\ref{table:dataset}. \n\nThe validation was made using a 10-fold cross-validation: each dataset has been split into 10 equal sized samples, 90\\% has been used as training set and the remaining 10\\% to test the classification. Each subsample is used once as testing set and the final metrics are calculated as the average of the 10 runs. The training set was not rebalanced and kept the original prevalence. The of training steps $k$ was adjusted with a manual trial and errors approach, the familly $\\eta$ set to $\\eta_0 = \\eta_1 = \\bar \\eta_0 = \\bar \\eta_1 = 0$ and $\\delta$ was set to $1$. Further work will focus on automatic parameter tuning. \n\\begin{figure}[!h]\n\\centering\n\\includegraphics[scale=0.35]{img/output_run_0_confusion_matrix_1.png}\n\\caption{Evolution of the confusion matrix during the prediction phase for \\texttt{phishing} dataset.}\n\\label{fig:evolution_phishing}\n\\end{figure}\nThe average confusion matrix obtained for each dataset is showed in Table \\ref{table:confusion_matrix}. The performance indicators are reported in Table \\ref{table:perf_indicators}. The proposed algorithm performs very well on a wide range of datasets as reported by \\cref{table:confusion_matrix,table:perf_indicators}, in particular when they contain strong predictors as it is the case for \\texttt{mushroom}. The accuracy is contained in a range from 0.8206 (\\texttt{adult}) to 1 (\\texttt{mushrooms}) while the $F_1$-score is bounded by 0.8653 (\\texttt{heart}) and 1 (\\texttt{mushrooms}). On \\texttt{adult}, the accuracy is only 6\\% higher than the prevalence. A model consisting in returning 1 for any point would be only 6\\% worse. This relatively poor performance in learning the underlying decision mapping is better reflected by the Matthews correlation coefficient of $0.51$.\n\nThe false positives and false negatives are equilibrated for each dataset, despite a huge variation in the prevalence (between 20\\% and 64\\%, cf. Table \\ref{table:confusion_matrix}) which may be a desirable property depending on applications. In addition, the results were obtained with non-balanced training sets which are known to be a problem for many machine learning algorithms. Moreover, the performance indicators remain stable during the whole prediction phase as shown on Figure \\ref{fig:evolution_phishing} for the dataset \\texttt{phishing} (similar result is observed for all datasets).\n\nFor a given case, the support is a metric of confidence in the prediction as illustrated in Figure \\ref{fig:phishing_predictive_measure}. In general, the wrongly classified cases have a smaller difference between the evidence for each class which confirm the interest in the hyperparameters $\\eta$ and $\\bar \\eta$ used in \\eqref{eqn:updated_cr}.\n\n\\begin{figure}[!h]\n\\centering\n\\includegraphics[scale=0.35]{img/output_run_0_diff_pred_1.png}\n\\caption{Difference between the weight assigned to both classes for each decision on \\texttt{phishing} (average). Similar results are observed for all datasets.}\n\\label{fig:phishing_predictive_measure}\n\\end{figure}\n\nTo compare the results of the proposed method, we explored the best results from the literature for each dataset. The comparison with \\texttt{audiology} is not relevant due to the transformation into a two-class problem. The results are summarized in Table \\ref{table:prev_results}. In \\cite{doi:10.1504/IJBISE.2016.081590}, 5 rule-based classification techniques dedicated to medical databases are compared and achieve at best 95.85\\% and 82.96\\% accuracy resp. on \\texttt{breast}, and \\texttt{heart} datasets. Comparing bayesian approaches, \\cite{Jiang:2012:LIW:2124637.2124641} demonstrated 97.35\\% (\\texttt{breast}) and 83.00\\% (\\texttt{heart}) accuracy. A 5 layers neural network with fuzzy inference rules achieved 87.78\\% on \\texttt{heart} \\cite{sagir2017hybridised} while a k-NN algorithm reached 99.96\\% on \\texttt{mushrooms} \\cite{Das:2001:FWB:645530.658297}. The best alternative among 6 rules-based classification methods achieved 95.84\\% on \\texttt{breast} and 100.00\\% on \\texttt{mushroom} \\cite{HADI2017287}. Using 80\\% of \\texttt{phishing} as training set, an adaptative neural network achieved an average accuracy of 93.76\\% (among 6 alternatives) with the best run at 94.90\\% \\cite{7727750}. Still on \\texttt{phishing}, \\cite{7881507} proposes to combine several classifiers and reaches 97.75\\% accuracy for the best hybrid model (and demonstrates 97.58\\% for Random Forest classifier). On \\texttt{adult}, the comparison of several classifiers (naive bayes, decision tree, ...) demonstrated at most 86.25\\% accuracy \\cite{kou2012evaluation} while a Support Vector Machine approach reached 85.35\\% \\cite{Lee2001}. On \\texttt{splice}, a method using Fuzzy Decision Trees \\cite{5409447} reaches 94.10\\% accuracy and a neural network combined to boosting \\cite{catak2017} 97.54\\%. On \\texttt{breast}, Support Vector Machine approaches reached resp. 96.87\\%, 98.53\\%, 99.51\\% accuracy \\cite{CHEN20119014, POLAT2007694, akay2009support}, 99.26\\% and 97.36\\% for neural network based techniques \\cite{MARCANOCEDENO20119573, ubeyli2007implementing}, 98.1\\% for a bayesian network method \\cite{fallahi2011expert}, or 94.74\\% using Decision Trees \\cite{quinlan1996improved}. On \\texttt{skin}, \\cite{catak2017} reports 98.94\\% accuracy against 99.68\\% for Decision Tree based method~\\cite{6627823}. The best result, as far as we know, is 99.92\\%, obtained by a Generalized Linear Model~\\cite{basterrech2015generalized} (with 80\\% training set).\n\nThe accuracy is slightly lower than the best results from the literature (\\texttt{adult} 82.06\\% against 86.25\\%, \\texttt{breast} 96.96\\% against 99.51\\%, \\texttt{heart} 85.77\\% against 87.78\\%, \\texttt{phishing} 96.05\\% against 97.75\\%, \\texttt{splice} 94.43\\% against 97.54\\%, \\texttt{skin} 98.65\\% against 99.92\\%). We explain this by at least two factors. First, the best methods on a given dataset are often dedicated to this dataset with {\\it ad-hoc} or engineered parts which is not the case of \\HCBR. Secondly, the hyperparameter familly $\\eta$ have not been tuned but as we will show in next section, they might have a decisive impact on performance.\n\\HCBR~ performed better than Bayes classifier in two thirds of cases. Bayes classifier performs better on \\texttt{breast} by \\~1\\% which represents less than one case wrongly classified. Similar results are observed with Decision Trees. However, the 1\\% difference on \\texttt{skin} represents an average of 7 cases misclassified in comparison in favor of Bayes. It performs better than Rule-based approaches (or gives similar results on \\texttt{mushrooms} with an accuracy of 1) in the four considered references on three different datasets. Notice that combined with Neural Network, Rule-based achieves the state-of-art result on \\texttt{heart} dataset. Except for \\texttt{phishing}, Neural Network returns better results ($0.46$ more cases with correct classification in average for \\texttt{breast}, $71$ for skin and almost $10$ for \\texttt{splice}). Last, SVM gives better results in all three cases, but appear only as best results in two datasets.\n\\begin{table}[htbp]\n\\begin{center}\n  \\caption{Average confusion matrix obtained with a 10-fold cross-validation.}\n %\\resizebox{12cm}{!}{\n  \\begin{small}\n  \\begin{tabular}{|l|c|c|c|c|c|c|c|c|c|c|c|}\n    \\hline\n     & TP & FN & FP & TP & Prevalence\\\\\n    \\hline\n    \\texttt{adult} & 2182.40 & 295.30 & 288.50 & 488.80 & 0.7586\\\\\n    \\texttt{audiology} & 12.70 & 0.10 & 0.00 & 6.20 & 0.6048\\\\\n    \\texttt{breast} & 23.00 & 1.40 & 0.70 & 43.90 & 0.3338\\\\\n    \\texttt{heart} & 12.40 & 1.80 & 1.90 & 9.90 & 0.5107\\\\\n    \\texttt{mushrooms} & 390.60 & 0.00 & 0.00 & 420.40 & 0.4804\\\\\n    \\texttt{phishing} & 595.40 & 23.80 & 19.80 & 465.00 & 0.5562\\\\\n    \\texttt{skin} & 4886.30 & 132.40 & 199.40 & 19286.90 & 0.2075\\\\\n    \\texttt{splice} & 155.70 & 9.10 & 8.50 & 142.70 & 0.5164\\\\\n    \\hline\n  \\end{tabular}\n  \\end{small}\n  %}\n  \\label{table:confusion_matrix}\n\\end{center}\n\\end{table}\n\\begin{table*}[htbp]\n\\begin{center}\n  \\caption{Average performances obtained with a 10-fold cross-validation.}\n %\\resizebox{12cm}{!}{\n  \\begin{small}\n  \\begin{tabular}{|l|c|c|c|c|c|c|c|c|c|c|c|}\n    \\hline\n     & Accuracy (standard dev.) & Recall & Specificity & Precision & Neg. Pred. Value & $F_1$ score & Matthews corr. coef.\\\\\n    \\hline\n    \\texttt{adult} & 0.8206 (0.0094) & 0.8832 & 0.6233 & 0.8808 & 0.6290 & 0.8820 & 0.5081\\\\\n    \\texttt{audiology} & 0.9947 (0.0166) & 1.0000 & 0.9875 & 0.9917 & 1.0000 & 0.9957 & 0.9896\\\\\n    \\texttt{breasts} & 0.9696 (0.0345) & 0.9691 & 0.9676 & 0.9479 & 0.9844 & 0.9575 & 0.9344\\\\\n    \\texttt{heart} & 0.8577 (0.0943) & 0.8695 & 0.8437 & 0.8699 & 0.8531 & 0.8653 & 0.7178\\\\\n    \\texttt{mushrooms} & 1.0000 (0.0000) & 1.0000 & 1.0000 & 1.0000 & 1.0000 & 1.0000 & 1.0000\\\\\n    \\texttt{phishing} & 0.9605 (0.0081) & 0.9680 & 0.9514  & 0.9615 & 0.9590 & 0.9647 & 0.9199\\\\\n    \\texttt{skin} & 0.9865 (0.0069) & 0.9608 & 0.9932  &0.9736 & 0.9898 & 0.9672 & 0.9587 \\\\\n    \\texttt{splice} & 0.9443 (0.0124) & 0.9478 & 0.9398 & 0.9450 & 0.9441 & 0.9463 & 0.8884\\\\\n    \\hline\n  \\end{tabular}\n  \\end{small}\n  %}\n  \\label{table:perf_indicators}\n\\end{center}\n\\end{table*}\n\\begin{table}[tb]\n\\begin{center}\n  \\caption{Previous literature results measured as the highest accuracy obtained by the authors.}\n  %\\resizebox{12cm}{!}{\n  \\begin{small}\n\\begin{tabular}{|c|c|l|c|}\n\\hline\n Dataset & Ref. & Type & Accuracy   \\\\ \\hline\n\\multirow{2}{*}{\\texttt{adult}} & \\cite{kou2012evaluation} & Many classifiers &  86.25\\% \\\\\n& \\cite{Lee2001} & SVM & 85.35\\% \\\\ \n& & \\bfHCBR & {\\bf 82.06\\%} \\\\ \\hline\n \\multirow{10}{*}{\\texttt{breast}} & \\cite{akay2009support}  & SVM & 99.51\\% \\\\ \n & \\cite{MARCANOCEDENO20119573} & Neural Network & 99.26\\% \\\\ \n & \\cite{POLAT2007694} & SVM & 98.53\\% \\\\ \n & \\cite{fallahi2011expert} & Bayes & 98.1\\% \\\\ \n & \\cite{ubeyli2007implementing} & Neural Network & 97.36\\% \\\\ \n & \\cite{Jiang:2012:LIW:2124637.2124641} & Bayes & 97.35\\% \\\\ \n & & {\\bf \\bfHCBR} & {\\bf 96.96\\%} \\\\\n & \\cite{CHEN20119014} & SVM & 96.87\\% \\\\\n & \\cite{doi:10.1504/IJBISE.2016.081590} & Rule-based & 95.85\\% \\\\\n & \\cite{HADI2017287} & Rule-based & 95.84\\% \\\\\n & \\cite{quinlan1996improved} & Decision Tree & 94.74\\% \\\\ \\hline\n \\multirow{3}{*}{\\texttt{heart}} & \\cite{sagir2017hybridised} & Neural Network + Rule-based & 87.78\\%\\\\\n & & {\\bf \\bfHCBR} & {\\bf 85.77\\%} \\\\\n & \\cite{Jiang:2012:LIW:2124637.2124641} & Bayes & 83.00\\% \\\\ \n & \\cite{doi:10.1504/IJBISE.2016.081590} & Rule-based & 82.96\\% \\\\ \\hline\n \\multirow{2}{*}{\\texttt{mushrooms}} &  \\cite{HADI2017287} & Rule-Based & 100.00\\% \\\\ \n  & & {\\bf \\bfHCBR} & {\\bf 100.00\\%} \\\\\n  & \\cite{Das:2001:FWB:645530.658297} & k-NN & 99.96\\% \\\\ \\hline\n \\multirow{3}{*}{\\texttt{phishing}} & \\cite{7881507} & Ensemble & 97.75\\% \\\\ \n &  \\cite{7881507} & Random-Forest & 97.58\\% \\\\ \n & & {\\bf \\bfHCBR}& {\\bf  96.05\\%} \\\\\n & \\cite{7727750} & Neural Network &  94.90\\% \\\\\\hline\n \\multirow{3}{*}{\\texttt{skin}} & \\cite{basterrech2015generalized} & Generalized Linear Model & 99.92\\% \\\\ \n & \\cite{6627823} & Decision Tree & 99.68\\% \\\\ \n & \\cite{catak2017} & Neural Network + Boosting & 98.94\\% \\\\\n & & {\\bf \\bfHCBR} & {\\bf 98.65\\%} \\\\ \\hline\n \\multirow{2}{*}{\\texttt{splice}} & \\cite{catak2017} & Neural Network + Boosting & 97.54\\% \\\\\n & & {\\bf \\bfHCBR} & {\\bf 94.43\\%} \\\\\n & \\cite{5409447} & (fuzzy) Decision Tree & 94.10\\% \\\\ \\hline\n\\end{tabular}\n\\end{small}\n  %}\n  \\label{table:prev_results}\n\\end{center}\n\\end{table}\n\\subsection{Intrinsic performance}\n\nIn this section, we evaluate the capacity of \\HCBR~ to build an efficient model (w.r.t. the accuracy measure) with few examples. We also study the influence of the two main parameters (number of examples and size of the examples) on the computation time.\\\\\n\n\\noindent\n{\\bf Training set size:} To evaluate \\HCBR, we used a standard 90-10 dataset split in the previous section. Additionally, we studied the accuracy depending on the split from 1\\% to 99\\%. For each split value, we performed 100 runs with random splits and averaged the accuracy. As shown in Figure \\ref{fig:accuracy}, \\HCBR~ reaches its maximal accuracy with about 15\\% of the dataset as examples. The dataset \\texttt{adult} shows a constant results from 1\\% while for \\texttt{audiology} more than 40\\% is required to achieve over 90\\% accuracy. Despite the datasets having different sizes (e.g. \\texttt{skin} is 350 larger than \\texttt{breast}), the trajectories look the same. Further work should focus on determining the optimal training set size depending on the size of cases and the underlying measure to generate them in $\\mathcal P({\\mathbb F})$ (as it influences the induced hypergraph, it influences the strength measure and thus the decisions). Additional experiments need to be performed to fairly compare those results to the existing algorithms. However, it is commonly accepted that non-linear classifiers requires very large training sets.\\\\\n\\begin{figure}[!h]\n\\centering\n\\includegraphics[scale=0.35]{img/accuracy_by_examples.png}\n\\caption{Accuracy depending on the percentage of the dataset used as training set.}\n\\label{fig:accuracy}\n\\end{figure}\n\n%\\newpage\n\\noindent\n{\\bf Computation Time:} We generated a casebase of $n$ cases of size $m$ such that case $i$ is described by $\\{i, ...,  i+m\\}$ i.e., each case is partitioned into $m$ elements (one discretionary feature). This is the worst-case scenario in terms of the size of $\\mathcal{E}$ if $m < n$ because the family grows exponentially in function of $m$ or $n$. We split the computation time into constructing the hypergraph (and determining the intersection family) and calculating the strength of the partition. The results are illustrated in Figure \\ref{fig:time}. By increasing $n$ with a fixed $m$, the partition grows exponentially and thus, it is expected to have an exponential curve for the strength computation. On the contrary, building the hypergraph can be done in linear time when $m$ fixed. When $n$ is fixed and $m$ increases, constructing the hypergraph is still doable in linear time as expected. Interestingly, calculating the strength has two phases: if $m \\leq n$, increasing $m$ exponentially increases the time (because $\\mathcal{E}$ exponentially increases) but if $m > n$, increasing $m$ cannot results in an exponential growth in the computation time (because $\\mathcal{E}$ grows linearly).\n\n\\begin{figure}[!h]\n\\centering\n\\includegraphics[scale=0.35]{img/time_k.png}\n\\hfill\n\\includegraphics[scale=0.35]{img/time_n_old.png}\n\\caption{At the top, computation time to build the model (hypergraph construction + strength calculation) depending on $n$ ($m = 10$), and at the bottom, depending on $m$ ($n = 100$). The case $i$ is described by $\\{i, ...,  i+m\\}$ such that each case is partitionned into $m$ elements (one discretionary feature). Right scale for bulding and left scale for strength.}\n\\label{fig:time}\n\\end{figure}\n\n~\\\\\\noindent\n{\\bf Hyperparameters $\\eta$:} We used a 90-10 split and set $\\eta_0 = \\eta_1$ to ease the visualization. Instead of using the decision function defined by \\eqref{eqn:decision_rule_revised}, we did not produce a prediction if the constraints $C_1$ or $C_0$ were not respected. It can be viewed as creating a third class {\\it unknown} for which we consider we cannot produce a decision. We measured the accuracy and the test set size ratio for which a prediction has been produced for different values of $\\eta := \\eta_0 = \\eta_1$. If $\\bar J$ correctly approximates $J$, increasing $\\eta$ should increase the accuracy while the test set ratio should remain high. Additionally, we plot the test set ratio in function of the accuracy and calculate the Pareto frontier\\footnote{Points such that improving one component would degrades the other one.} which represents the best compromises accuracy/ratio. The closer the points are to $(1,1)$ the better it is. A Pareto frontier consisting of $(1,1)$ represents the perfect model (e.g. reached on \\texttt{mushroom} dataset). Figures \\ref{fig:meta_phishing}, \\ref{fig:meta_breast}, \\ref{fig:meta_heart} and \\ref{fig:meta_adult} provides the result for the best and worst two datasets. Figure \\ref{fig:meta_all} shows all of the four Pareto frontiers. \n\\begin{figure}[!h]\n\\centering\n\\includegraphics[scale=0.35]{img/meta_phishing.png}\n\\hfill\n\\includegraphics[scale=0.35]{img/meta_pareto_phishing.png}\n\\caption{Influence of $\\eta$ on \\texttt{phishing} dataset.}\n\\label{fig:meta_phishing}\n\\end{figure}\nAs expected, the results are better on \\texttt{phishing} and \\texttt{breast}. On \\texttt{phishing}, \\texttt{breast} and \\texttt{heart}, the accuracy globally increases with $\\eta$ while on \\texttt{heart} the accuracy slightly decreases indicating poor influence of the hyperparameters and model. \n\nNotice that for certain values of $\\eta$ it is possible to reach 100\\% accuracy with \\texttt{heart} while it is not with \\texttt{breast}. Also, for high values of $\\eta$, we observe a fall in accuracy for \\texttt{breast}. We suspect those two phenomena to appear because we used the same value for $\\eta_0$ and $\\eta_1$. \n\n\\begin{figure}[!h]\\centering\n\\includegraphics[scale=0.35]{img/meta_breast.png}\n\\hfill\n\\includegraphics[scale=0.35]{img/meta_pareto_breast.png}\n\\caption{Influence of $\\eta$ on \\texttt{breast} dataset.}\n\\label{fig:meta_breast}\n\\end{figure}\n\\begin{figure}[!h]\n\\centering\n\\includegraphics[scale=0.35]{img/meta_heart.png}\n\\hfill\n\\includegraphics[scale=0.35]{img/meta_pareto_heart.png}\n\\caption{Influence of $\\eta$ on \\texttt{heart} dataset.}\n\\label{fig:meta_heart}\n\\end{figure}\n\\begin{figure}[!h]\\centering\n\\includegraphics[scale=0.35]{img/meta_adult.png}\n\\hfill\n\\includegraphics[scale=0.35]{img/meta_pareto_adult.png}\n\\caption{Influence of $\\eta$ on \\texttt{adult} dataset.}\n\\label{fig:meta_adult}\n\\end{figure}\nMore work is required to fully study the influence of the hyperparameters $(\\eta_0, \\eta_1, \\bar \\eta_0, \\bar \\eta_1)$ and how to select $l_0$ and $l_1$. We believe it is the key to improve the overall performance, and it is possible to derivate the best values from the training set. Also, a comparison with binary classification methods that provide a prediction confidence metric is necessary.\n\\begin{figure}[!h]\\centering\n\\includegraphics[scale=0.35]{img/meta_pareto_all_front.png}\n\\caption{Pareto Frontiers comparison.}\n\\label{fig:meta_all}\n\\end{figure}\n\n%\\newpage\n\\section{Conclusion}\n\\label{sec:conclusion}\n\nThis paper presented \\HCBR, a method for binary classification using a hypergraph representation of information and building a convex combination out of the induced partition to determine the support for each class. The general framework introduced by \\eqref{eqn:model} is instantiated in Section \\ref{sec:model_selection} where the support is determined using all the interactions between the hyperedges. Beyond this specific implementation, one can imagine different model selection methods to be used, e.g. using some assumptions on the data.\n\nHowever, being totally agnostic on the data representation is convenient compared to many methods such as SVM. It allows combining information from multiple sources by simply {\\it stacking} the information. It does not require transforming the data to fit the algorithm, often by designing specific ad-hoc metrics.\n\n\\HCBR~ has been tested on 8 well-known datasets and demonstrated similar accuracies when compared to the best results from the literature. The algorithm has shown a strong stability in terms of accuracy, true positive and negative rates during the whole prediction phase. We showed that the difference of class support is a good confidence indicator for the prediction. We demonstrated the capacity to obtain a good accuracy using very few examples from the dataset (10\\% to 15\\% of the training set) without balanced classes. This last property is very important for robustness as in practice, the dataset are rarely balanced. Finally, we empirically validated the exponential worst-case complexity.\n\nThis proof of concept raises many questions and offer many improvement axes. First of all, it seems relatively easy to extend the method to several classes but it needs an additional empirical validation. As most of the computational effort is on calculating the class support, adding more classes will linearly increase the computation time and thus, working on a faster algorithm or an approximation of the main measure should be investigated. The solution may come from exploring the feature selection capacity of \\HCBR. Indeed, by the hypergraph construction, it may be possible to remove from the partition some elements that do not participate enough (e.g. not being in enough cases at the same time), reducing the computation time.\nAdditionally, we plan to investigate how to generate an explanation about each prediction and one about the decision function $J$ itself, using not only the convex combination and the strength of the partition elements, but also the link between cases in a similar way a lawyer may use past cases to make analogies or counter-examples. We also work on an online version of \\HCBR~ where the hypergraph is constructed case after case, including forgetting some old past cases (which would allow handling non-stationary environment). It seems also possible not only to add new examples dynamically, but also some vertices (i.e. adding some pertinent information to some cases) without generating the whole model from scratch. \n\nEmpirically, further experiments should focus on more unstructured datasets (for instance for text classification). As stated previously, strategies for hyperparameter tunning are also a priority.\nLast but not least, we would like to answer some questions: is it possible to find a method to adjust the strength measure such that the accuracy on the training set is 1? Can we provide some quality bounds depending on the initial hypergraph and thus the dataset? How to handle continuous values?\n\n\\section*{Acknowledgment}\n\nThe author warmly thanks Pr. Robert Wrembel, Poznan University of Technology, and Dr. Jean-Fran\\c{c}ois Puget, IBM Analytics, for their useful suggestions and advice to improve this paper.\n\n\\bibliographystyle{ACM-Reference-Format}\n\\bibliography{paper} \n\n\\end{document}", "meta": {"hexsha": "e3888a799810fb17ca35cb7f864044f227cf0c04", "size": 73190, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "papers/DOLAP_2018/paper.tex", "max_stars_repo_name": "aquemy/HCBR", "max_stars_repo_head_hexsha": "bc61cf0ca0629119c8d29b146890873f92a46835", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-03-20T09:59:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-17T05:45:05.000Z", "max_issues_repo_path": "papers/DOLAP_2018/paper.tex", "max_issues_repo_name": "aquemy/HCBR", "max_issues_repo_head_hexsha": "bc61cf0ca0629119c8d29b146890873f92a46835", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "papers/DOLAP_2018/paper.tex", "max_forks_repo_name": "aquemy/HCBR", "max_forks_repo_head_hexsha": "bc61cf0ca0629119c8d29b146890873f92a46835", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-05-03T23:33:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T18:54:14.000Z", "avg_line_length": 81.7765363128, "max_line_length": 2451, "alphanum_fraction": 0.7010930455, "num_tokens": 22844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.30518498099329516}}
{"text": "\\documentclass[twocolumn,tight,times]{aastex63}\n\n\\usepackage{amsmath,amstext}\n\\usepackage[figure,figure*]{hypcap}\n\\usepackage{newtxmath} %use times font for math\n\\usepackage{longtable}\n\n\\newcommand\\aastex{AAS\\TeX}\n\\newcommand\\latex{La\\TeX}\n\n\\newcommand{\\mteff}{\\tau_\\mathrm{eff}}\n\\newcommand{\\teff}{$\\mteff$}\n\\newcommand{\\lya}{Ly$\\alpha$}\n\\newcommand{\\kms}{km~s$^{-1}$}\n\\newcommand{\\zem}{$\\mathrm{z_{med}}$}\n\\newcommand{\\hiz}{$\\mathrm{z_{high}}$}\n\\newcommand{\\loz}{$\\mathrm{z_{low}}$}\n\\newcommand{\\rchi}{$\\chi^{2}_\\mathrm{reduced}$}\n\n\\newcommand{\\Aval}{0.159}  % Power-law normalization\n\\newcommand{\\Aerr}{0.001}  % Power-law normalization error\n\\newcommand{\\Bval}{-2.022}  % Power-law exponent \n\\newcommand{\\Berr}{11.60}  % Power-law exponent error\n\n\n\n\\begin{document}\n\n\\title{Effective Opacity of the Intergalactic Medium from Galaxy Spectra Analysis}\n\n\\correspondingauthor{Jose Monzon}\n\\email{jsmonzon@ucsc.edu}\n\n\\author[0000-0002-9986-4604]{Jose S. Monzon}\n\\affiliation{University of California, Santa Cruz; 1156 High St., Santa Cruz, CA 95064, USA}\n\n\\author[0000-0002-7738-6875]{J. Xavier Prochaska}\n\\affiliation{University of California, Santa Cruz; 1156 High St., Santa Cruz, CA 95064, USA}\n\n\\author[0000-0001-9299-5719]{Khee-Gan Lee}\n\\affiliation{Kavli Institute for the Physics and Mathematics of the Universe (WPI), University of Tokyo, Kashiwa 277-8583, Japan}\n\n\\author[0000-0002-0302-2577]{John Chisholm}\n\\altaffiliation{Hubble Fellow}\n\\affiliation{University of California, Santa Cruz; 1156 High St., Santa Cruz, CA 95064, USA}\n\n\\begin{abstract}\n\nWe measure the effective opacity (\\teff) of the Intergalactic Medium (IGM) from the composite spectra of 281 Lyman-Break Galaxies (LBGs) in the redshift range $2 \\lesssim z \\lesssim 3$. Our spectra are taken from the COSMOS Lyman-Alpha Mapping And Tomographic Observations (CLAMATO) survey derived from the Low Resolution Imaging Spectrometer (LRIS) on the W.M. Keck I telescope. We generate composite spectra in two redshift intervals and fit them with spectral energy distribution (SED) models composed of simple stellar populations. Extrapolating these SED models into the \\lya\\ forest, we measure the effective \\lya\\ opacity (\\teff) in the $2.02 \\leq z \\leq 2.44$ range. At $z = 2.22$, we estimate $\\mteff = \\Aval \\pm \\Aerr$ from a power-law fit to the data. These measurements are consistent with estimates from quasar analyses at $z<2.5$ indicating that the systematic errors associated with normalizing quasar continua are not substantial. We provide a Gaussian Processes model of our results and previous \\teff\\ measurements that describes the steep redshift evolution in \\teff\\ from $z = 1.5 - 4$.\n\n\\end{abstract}\n\n\\keywords{--- Intergalactic Medium, Effective Opacity, Lyman Break Galaxy}\n\n\\section{Introduction}\n\\label{sec:intro}\n\nThe Intergalactic Medium (IGM) is a diffuse gas, mainly consisting of ionized hydrogen and helium, that permeates the space between galaxies in the large-scale cosmic web. The gas is highly ionized by the extra-galactic ultraviolet background (EUVB) radiation field and takes the form of a diffuse, $T\\sim10^4$K plasma. The trace fraction of hydrogen gas that remains neutral ($\\chi_\\mathrm{HI}$), is responsible for attenuating the radiation from the EUVB and producing the \\lya\\ forest \\citep[see][for a review]{McQuinn_2016}. Studies on the \\lya\\ forest have meshed well with cosmological theory as it is the IGM, and not the galaxies it surrounds, that governs the large-scale structure of the universe. It is considered one of the most powerful cosmological probes at $z \\geq 2$ as it holds the majority of baryons at all epochs \\citep[e.g.][]{Becker_2007} \n\n\\cite{Gunn_Peterson_1965} were the first to discern that a universe filled with neutral hydrogen (HI) would be opaque in the far-UV, especially at higher redshifts which is densest. Analyzing the spectrum of any distant, rest-frame UV-emitting object, directly points to a fluctuating and photo-ionized gas that at a given redshift, varies considerably from sight-line to sight-line \\citep{Shapley_2003}. A series of studies \\citep[e.g.][]{Dall'Aglio_2008, Faucher-Giguere_2008, Becker_2013} have since carried out careful measurements of how HI evolves to place statistical constraints on properties like density, temperature and composition. A solid understanding of the physical state of the IGM allows for subsequent research investigating galaxy formation \\citep{Hassan_2020}, the ionization history \\citep{Theuns_2002, Bernardi_2003, Kirkman_2005} and ultimately the constraints on our leading cosmological theories \\citep{Rauch_1998, Becker_2007}.\n\nStudies of the physical properties of the IGM have primarily come from the analysis of the mean optical depth of HI ($\\tau$) observed in the spectra of distant Quasi-Stellar Objects \\citep[QSOs;][]{Prochaska_2009, Becker_2007, Faucher-Giguere_2008, Kirkman_2005}. QSO's peak in the UV because of their hot accretion disks \\citep[AGN;][]{Meiksin_2009}. As a QSO's radiation traverses the space between galaxies, a series of absorption lines populate the rest-frame spectrum blueward of 1215\\AA. Because the IGM is inhomogeneous, photons interact with the intervening gas at different redshifts, causing absorption features across a multitude of wavelengths; the so-called \\lya\\ forest. For sufficiently distant objects ($z > 5$), where the IGM is the densest \\citep{Mcdonald_2006}, the absorption lines become so numerous that more than 70\\% of the flux is absorbed in the \\lya\\ forest ($\\sim$ 1020-1210\\AA). \n\nOne can directly measure values describing the attenuation from the spectra of distant objects by estimating the underlying continuum, a process that becomes increasingly difficult at higher redshifts \\citep[e..g][]{Kirkman_2005}. QSOs are much brighter and therefore easier to observe at higher redshifts, but the \\lya\\ forest can be observed in the spectra of any distant, UV-emitting source. In fact, the $z>4$ EUVB is thought to be dominated by a population of faint UV-emitting galaxies in addition to bright QSOs at $g \\sim 23$ magnitudes \\citep{Lee_2014}. Their contribution to the EUVB is caused by the young and massive stars they harbor. We set out to measure the effective \\lya\\ opacity of the IGM, \\teff\\, using the spectra of these Lyman-Break galaxies (LBGs) by exploiting their high number density \\cite[hereafter L18]{Lee_2018}.\n\nLBGs are star forming galaxies whose emission peak in the rest-frame UV and are selected based on their emission blueward of \\lya\\ in a given filter set \\citep{Steidel_1996}. The original term 'LBG' describes star-forming galaxies selected at $z \\geq 3$ by their IGM absorption, but the CLAMATO team use the term to cover all $z \\geq 2$ galaxies with a far-UV continuum. The stacked spectra of LBGs have been used to constrain the dust attenuation curve \\citep{Reddy_2016} and investigate spectral features attributable to hot stars, HII regions and outflowing gas \\citep{Shapley_2003}. \\cite{Thomas_2017} analyzed galaxy spectra to estimate \\teff\\ at $2.5 < z < 5.5$.  Using only LBG spectra, they provided an assessment of \\teff\\ without the systematic errors associated with normalizing quasar spectra.\n\nIn this work, we leverage the blue sensitivity of the Keck/LRIS spectrograph to measure \\teff\\ from low S/N LBGs spectra  at $z \\lesssim 2.5$.  Similarly, we set out to test previous work analyzing the effective opacity of the IGM by generating an estimate independent of the challenges associated with normalizing quasar spectra. Crucially, $z < 2.5$ is the regime where quasar measurements have traditionally been anchored on the grounds that one can more accurately estimate quasar continua at lower opacity.\n\nIn the following sections of this manuscript we: [2] present the CLAMATO data sample [3] describe our methodologies for creating composite spectra and fitting SED models, [4] report our measurements of \\teff and compare to previous studies, and [5] summarize and discuss this work’s findings. Throughout the paper, we adopt a concordance Lambda Cold-Dark-Matter ($\\Lambda$-CDM) cosmology with $\\Omega_{\\Lambda}$ = 0.7, $\\Omega_{m}$ = 0.3 and h = 0.7.\n\n\\section{The CLAMATO Observations and Sample Selection}\n\\subsection{CLAMATO}\n\\label{subsec:clamato}\n\nOur sample of galaxies was drawn from the 2016 and 2017 releases of the COSMOS Lyman-Alpha Mapping And Tomographic Observations (CLAMATO) which were measured by the Low Resolution Imaging Spectrometer (LRIS) on W.M. Keck I telescope \\citep{LRIS}. CLAMATO began operations in 2014 with the main goal of mapping the \\lya\\ forest tomography of the foreground IGM (these pilot observations were not applicable to our analysis). \\cite{Lee_2014} found that because galaxies dominate the foreground UV luminosity function at faint magnitudes \\textit{g} $\\sim$ 23 \\citep{Reddy_2008}, LBG spectra would almost exclusively compose the 3D tomographic reconstruction.\n\nCLAMATO is designed to systematically observe faint ($23 \\lesssim \\textit{g} \\lesssim 25$) UV-emiting sources from $2 < z < 3$, at high area densities ($\\sim 1000 deg^{2}$) and L18 reports using a total of 240 background galaxies and QSOs within a 0.157 square degree section of the COSMOS field. They also report estimated redshift values and spectra on an additional 437 objects for a total 677 reduced sources. The COSMOS field \\citep{Scoville_2007} is in the Northern Hemisphere and spans 2 square degrees. It offers a large selection of $g$-band star forming galaxies, covers a significant scale in the transverse direction ($\\sim 10$\\,Mpc) and has measurements of redshifts for the objects in the survey. \n\nThe target selection procedure for CLAMATO depends on the magnitude and probability of success, initial prioritization based on redshift, and the subsequent slit mask designs. As the COSMOS field has a rich selection of spectroscopic and multi-wavelength imaging data, L18 built CLAMATO from existing redshift catalogs \\cite{Lilly_2007, LeFevre_2015, Kriek_2015, Nanayakkara_2016} that covered their desired wavelength range ($3700\\AA < \\lambda < 4300\\AA$). To select targets, L18 fed the combined spectroscopic and photometric catalogs to an algorithm which prioritizes background $g$-band sources in the redshift range of $2.25 \\lesssim z \\lesssim 2.45$. The algorithm prefers brighter sources due to slit-packing constraints but selected targets as faint as $g = 25.3$.\n\nObservations for CLAMATO lasted a total of 15.5 nights of which about 60 hrs were spent on sky with typical total exposure time per object lasting $\\sim$ 9000s. LRIS was configured with the 600/4000 grism to achieve an approximate resolution R $\\equiv \\lambda/\\Delta\\lambda \\approx 1000$ with 1$\"$ slits between the observer-frame wavelengths of 3700A and 4400A on its Blue channel. As expected with such faint and distant sources and an average seeing of 0.7$\"$, the spectra have low signal-to-noise, S/N $< 3$ per \\AA. The data were then processed using the LowRedux routines from the XIDL software package\\footnote{http://www.ucolick.org/$\\sim$xavier/LowRedux}. Figure \\ref{fig:exspec} is an example of a reduced galaxy spectrum taken from the CLAMATO release described in L18. \n\nL18 then assigned confidence ratings from $0-4$ when estimating redshifts for each source, 0 being no attempt at all (normally reserved for corrupted data) and 4 being high confidence based on multiple lines. L18 reports that 66\\% of the objects in the sample had confidence ratings $\\geq 3$. The majority of less secure redshifts are for low priority sources used to fill spare slit space that often yielded spectra too noisy to identify. Approximately 95\\% of the objects with confidence ratings $\\geq 3$, were identified as galaxies using LBG templates from \\cite{Shapley_2003}, while the other 5\\%, were distinguished as broad-line quasars. For a more detailed outline of the selection algorithm, instrument specifications and preliminary data reduction please see L18. \n\n\n\\begin{figure*}[ht]\n    \\begin{center}\n    \\includegraphics[scale=.5]{exspec.pdf}\n    \\caption{An example spectrum of a Lyman Break Galaxy from the CLAMATO data release that fits our sample selection criteria. The spectrum shows a bright \\lya\\ emission feature and weaker ISM features that are difficult to distinguish from the noise. An error spectrum (shown in grey) is reported with each source in the CLAMATO release.}\n    \\label{fig:exspec}\n    \\end{center}\n\\end{figure*}\n\n\\subsection{Sample Selection}\n\\label{subsec:sample}\n\nMeasuring the opacity, $\\tau$, from an individual object yields a single realization of the stochastic IGM. The \\textit{effective} opacity of the IGM \\teff\\ is the average estimated over many sight-lines. We measure \\teff\\ using a composite or ``stacked\" spectrum, which is essentially an average of flux values, at each wavelength. Alternatively, we could have measured the opacity from several different spectra, and then averaged, to yield \\teff. There are two main justifications for why we chose to average our data before measuring the opacity. First, for small redshift variations, the observed continua of LBGs (or QSOs) are consistent across sight-lines, so a composite spectrum can be modeled by a single SED. Second, and more importantly, stacking improves the S/N allowing us to more accurately model the SED redward of \\lya.\n\nTo account for the fact that we are sampling the IGM with sight-lines corresponding to objects that are not at identical redshifts, we organize the CLAMATO spectra into small redshift bins of $\\Delta z = 0.25$. This yields a median redshift \\zem, which serves as a reference for the \\teff\\ values from the \\lya\\ forest. In total, there are 566 CLAMATO galaxy spectra in the $2.0 \\leq z \\leq 3.0$ interval with the majority of these sources between $2.25 < z < 2.75$ (see figure \\ref{fig:clamatohist}). We only used the $2.25 < z < 2.75$ interval because the bins to either side of it, do not contain enough spectra to create an adequate stack. We split the majority interval into two redshift intervals: \\loz\\ from $2.25 < z < 2.50$ and \\hiz\\ from $2.50 < z < 2.75$, for a combined total of 416 galaxy spectra.\n\n\\begin{figure}[ht]\n    \\begin{center}\n    \\includegraphics[width=\\columnwidth]{red_hist.pdf}\n    \\caption{Redshift distribution of the complete CLAMATO sample (show in grey) vs.\\ the reduced sample satisfying our selection criteria (show in orange).}\n    \\label{fig:clamatohist}\n    \\end{center}\n\\end{figure}\n\nOf our 416 galaxy spectra, several cover wavelengths blueward of the rest frame Lyman limit (912\\AA). For these spectra, we measure the median flux per pixel for wavelengths below the Lyman Limit and exclude those with values outside of the $\\pm 0.2$ median flux interval (see figure \\ref{fig:ll_cut}). We expect these spectra to have errors in their fluxing or sky subtraction as significant signal past the Lyman Limit is highly improbable. We further cut down our sample by imposing a blanket S/N limit, using the mean flux value in the wavelength range of 1260-1304\\AA. We found that a cut-off S/N = 1.5 excluded the poorest spectra without discarding the majority of the sample (see figure \\ref{fig:noise_scatter}). After these two cuts, we were left with 137 in the \\loz\\ interval and 142 in \\hiz\\ interval for a combined total of 279 galaxy spectra. The \\loz\\ interval has a median redshift value of 2.43 and a standard deviation of 0.074. The \\hiz\\ interval has a median redshift value of 2.58 and a standard deviation of 0.069. See appendix table \\ref{tab:clamato} for the selected sample of galaxy spectra from the CLAMATO survey.\n\n\\begin{figure}[ht]\n    \\begin{center}\n    \\includegraphics[width=\\columnwidth]{ll_hist.pdf}\n    \\caption{The complete distribution of median fl1ux values taken from spectra that extend blueward of the Lyman Limit (shown in grey). Those that are within the $\\pm\\ 0.2$ cut-off (show in orange) are still considered viable. We cut our sample aggressively, excluding 49 spectra, so as to not skew the continuum blueward of $\\sim 1130$\\AA.}\n    \\label{fig:ll_cut}\n    \\end{center}\n\\end{figure}\n\n\\begin{figure}[ht]\n    \\begin{center}\n    \\includegraphics[width=\\columnwidth]{s2n_hist.pdf}\n    \\caption{A scatter plot of our data's spectroscopic redshift vs the S/N calculated in the 1260-1304\\AA\\ range for both the \\loz\\ \\& \\hiz\\ intervals. The grey objects have been excluded by S/N cut.} \n    \\label{fig:noise_scatter}\n    \\end{center}\n\\end{figure}\n\n\\section{Composite Spectra}\n\\label{sec:composite}\n\n\\subsection{Stacking}\n\\label{subsec:stack}\n\nThe process that follows describes the preparation of individual LBG spectra prior to stacking:\n\\begin{itemize}\n  \\item To correct extinction from the Galactic interstellar medium (ISM), we passed each spectrum through a dereddening process based on the 3D Sky Map of \\cite{Green_2018}. The Sky Map, given an object's coordinates, reports $E(B-V)$ extinction values for the Milky Way which we applied to the flux array using the the reddening curve from \\cite{O'Donnell_1994} (an updated version of \\citep{CCM_1989}). No other corrections were necessary as the LRIS instrument has an atmospheric dispersion correcter and a fluxing term accounting for the atmospheric extinction.\n  \n  \\item We normalized the spectrum using values redward of \\lya, where there is no absorption features due to the IGM or ISM from 1260-1304\\AA\\ (between two SiII lines).\n  \n  \\item We trimmed the edges of the spectrum, only selecting flux data between $\\lambda_{\\rm rest} \\approx$ 1050-1400\\AA.\n  \n  \\item We shifted the spectrum to the rest frame, using the redshift values measured by CLAMATO, and rebinned to a velocity dispersion of 300 \\kms\\ per pixel using a common starting wavelength of 1000\\AA.\n\\end{itemize}\n\nWe then stacked the spectra by carrying out an unweighted, arithmetic mean of the flux values per wavelength. We chose not to weigh the spectra to better reduce cosmic variance in the \\lya\\ forest \\citep{Becker_2013}. We averaged across 137 and 142 LBG spectra for the \\loz\\ and \\hiz\\ intervals (respectively). The well behaved sections of the composites (1260-1304\\AA\\ for example) were left with S/N values $\\sim$ 30. The \\lya\\ forest (1070-1170\\AA) however, tended towards S/N values $\\sim 10$. Because in general, all individual LBG spectra edges were quite noisy (see figure \\ref{fig:exspec}) our stacks remained unconstrained blueward of $\\sim 1040$ and redward of $\\sim 1400$. See figure \\ref{fig:model} for the results of the stacking in black.\n\n\\subsection{Bootstrapping}\n\\label{subsec:bootstrap}\n\nOur primary source of error comes from sample variance within the stack and not from the S/N values of each individual spectrum. To assess the error in \\teff, we used a bootstrapping approach, following the example of \\cite{Worseck_2014}. The following details our process for constructing a covariance matrix that assesses correlated errors in our \\teff\\ measurements in each redshift interval:\n\\begin{itemize}\n    \\item To estimate sample variance, we chose a random selection of LBG spectra, within each redshift interval (allowing for duplicates), equal to the number of spectra that comprised each original composite (137 for \\loz\\ and 142 for \\hiz).\n\n    \\item We stacked the random selection in the same way as detailed above for creating the original composite.\n    \n    \\item We repeated the first two steps to generate 5,000 randomized composites.\n    \n    \\item to normalize the randomized composites, we subtracted the original composite from each of them individually.\n    \n    \\item We compiled the randomized composites into an $I x J$ matrix (where $I$ = 5,000 and $J$ is the length of our wavelength array ($\\sim 1000$)) and dotted this matrix with its transpose to create a full covariance matrix. See figure \\ref{fig:model} for the the 1D diagonal results of the error analysis in grey. \n\\end{itemize}\n\n\\begin{figure*}[ht]\n    \\centering\n    \\includegraphics[scale = .5]{composite_models.pdf}\n    \\caption{The un-shuffled \\loz\\ and \\hiz\\ composite spectra and their SED fits. The SED fits are two-toned, showing the region in which the fit is constrained by our data (red), and where the fit is extrapolated to measure the forest (blue). The excess flux in the model, blueward of \\lya\\ is caused by HI attenuation by the IGM. The error spectrum is based on the bootstrap matrix (plotted in grey; see \\ref{subsec:bootstrap}). Some of the most prominent ISM transitions are denoted in grey and were not included in the fit.}\n    \\label{fig:model}\n\\end{figure*}\n\n\\subsection{SED Modeling}\n\\label{subsec:models}\n\nTo measure \\teff, we estimated the unabsorbed flux of the composites in the \\lya\\ forest. Following the example of \\cite{Paris_2011}, we extrapolated blueward of \\lya\\ from a well behaved section of our spectra. We modelled the unabsorbed continua using an SED modeling technique designed by \\cite{Chisholm_2019} (hereafter C19) to fit simple stellar population (SSPs) models from the Starburst99 (SB99) database \\citep{Leitherer_1999}. There are 50 SB99 single age, single metallicity stellar population models investigated in C19 where each model was created using  a Kroupa IMF with a high-mass exponent of 2.3, a low-mass exponent of 1.3, and a high-mass cutoff of 100~M$_\\odot$. As star light between 1200-2000\\AA\\ is dominated by young massive O-stars \\citep{Leitherer_1999}, we only investigate a narrow regime of stellar ages: 1, 2, 3, 4, 5, 8, 10, 20, 40 Myr, each with 5 different metallicities: 0.05, 0.2, 0.4, 1.0, 2.0 $Z_\\odot$. The FUV stellar continuum does not dramatically change for B-star dominated stellar populations between 40-200 Myr \\citep{de_Mello_2000, Rix_2004}, thus we use an upper age of 40 Myr. Each model is fully theoretical and does not include ISM lines. They were created by sampling the high-mass portion of the Hertzsprung-Russell diagram up to temperatures of 20,000 K and a high-mass cut-off of 100 $M_{\\odot}$.\n\nThe modeling technique assumes that the spectra are combinations of multiple bursts of single age, single metallicity stellar populations and fits them with a uniform dust screen model dependent on four parameters: stellar attenuation ($E(B-V)$), the selected reddening curve ($\\kappa_{\\lambda})$, and linear coefficients ($X_{i}$) of each SB99 model ($M_{i}$) (see equation 1 from C19). The stellar attenuation $E(B-V)$ is allowed to range from 0.0 to 5.0. C19 selects the reddening curve from \\cite{Reddy_2016} as it extends closer to the ionizing continua of massive stars ($\\sim$ 950\\AA) than other models. C19 found that changing the attenuation law to that of \\cite{Calzetti_2000} reddens the inferred $E(B-V)$ by 0.01 mag.\n\nThe SED shape and observed stellar continuum can be fully described by these four parameters. Though the technique readily allows for more parameter constraints on the SED model, we did not define a free parameter for the absorption caused by the IGM (\\teff). To do so, we would have had to subscribe to a predetermined functional form for the redshift evolution of \\teff. Instead, we explored the results independent of any such formalism.\n\nUsing MPFIT \\citep{Markwardt_2009}, an IDL-based, least-squares fitting package\\footnote{https://pages.physics.wisc.edu/~craigm/idl/cmpfit.html}, we determined the linear combination of coefficients ($X_{i} \\geq 0$) that best describe the observed stellar continuum. The linear coefficients can also be translated to light fractions ($\\mathrm{L_{frac}}$) that each model $M_{i}$ contributes to the total intrinsic flux at 1270\\AA. Using these light fractions, we can estimate the age and the metallicity of the source (see table \\ref{tab:params}). These light-weighted properties of our simple stellar populations are driven by spectral features which are less degenerate than the spectral shape alone. C19 explores the stability of the fitting procedure by measuring the change in flux (per wavelength index) for variations in metallicity and age of model $M_{i}$. Increasing the age of a 0.2 $Z_{\\odot}$ model from 2Myr to 8Myr, changed the integrated root square flux of the SED by 2.4 in the 1250-1350\\AA\\ region. Increasing the metallicity of a 5 Myr model from 0.05$Z_{\\odot}$ to 0.4$Z_{\\odot}$, changed the integrated root square flux of the SED by 2.1 in the same wavelength region.\n\nThe following procedure was used to apply the C19 SED modeling technique to our two LBG composites and 10,000 randomized iterations (we used the 1D error spectra defined in section \\ref{subsec:bootstrap} for each redshift bin accordingly):\n\\begin{itemize}\n    \\item We masked out 14 ISM absorption lines and non-resonant emissions ($\\pm$ 500 \\kms) redward of \\lya\\ that would otherwise contaminate the fitting (see table \\ref{tab:ISM})\n    \n    \\item We fit our data in the 1225-1400\\AA\\ range, to take advantage of the unattenuated sections of our spectra and extrapolated the continuum into the \\lya\\ forest\n    \n    \\item Using the attenuation curve from \\cite{Reddy_2016}, we reddened our fitting results and normalized them in the same range as the composites (1260-1304\\AA).\n    \n    \\item We rebinned the SED models to a matching velocity dispersion of 300\\kms. See table \\ref{tab:params} for the fitted parameters. In the end we were left with the unabsorbed continua of our two composites and those of the 10,000 bootstrap iterations.\n\\end{itemize}\n\n\\begin{table}[ht]\n    \\centering\n    \\caption{The transition lines between $\\sim 1230-1400\\AA$ excluded from our SB99 fitting. Most of these ions are from the ISM \\citep{Leitherer_2011} and were masked so that the fit could be extended blueward of \\lya. Each line was padded with a $\\pm$ 500 \\kms buffer.}\n    \\label{tab:ISM}\n    \\vskip0.1in\n    \\begin{tabular}{c|c}\n    \\hline\n    \\hline\n    Ion & $\\lambda_{lab} (\\AA)$\\\\\n    \\hline\n    HI & 1215.67\\\\\n    NV & 1238.82\\\\\n    NV & 1242.80\\\\\n    SiII & 1260.42\\\\\n    SiIII & 1294.54\\\\\n    CIII & 1296.33\\\\\n    SiIII & 1296.74\\\\\n    SiIII & 1298.93\\\\\n    OI & 1302.17\\\\\n    SiII & 1304.37\\\\\n    NiII & 1317.22\\\\\n    CII & 1334.53\\\\\n    CII∗ & 1335.71\\\\\n    SiIV & 1393.76\\\\\n    SiIV & 1402.77\\\\\n    \\hline\n    \\end{tabular}\n\\end{table}\n\n\n\\begin{table*}[ht]\n\\begin{center}\n\\caption{Best fit parameters and derived values from the SB99 SED modeling for our two composites}\n\\label{tab:params}\n\\vskip0.1in\n\\begin{tabular}{c|c|c|c|c|c}\n\\hline\n\\hline\nRedshift interval & $N_{spec}$ & $\\chi^{2}$ & $E(B-V)$ & Age (Myr) & Metalicity ($Z_\\odot$)\\\\\n\\hline\n$2.43$ (\\loz) & 137 & 4.048 & 0.261 & 6.8 & 0.05\\\\\n$2.58$ (\\hiz) & 142 & 2.345 & 0.235 & 5.0 & 0.05\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\end{table*}\n\nTo demonstrate the stability of our selected fitting technique, we include the fitted SED of a low-$z$ galaxy, CG 274, which has negligible attenuation by the IGM (see figure \\ref{fig:sb99}). This spectrum was taken by the Cosmic Origins Spectrograph (COS) on the Hubble Space Telescope using the G130M grating and a central wavelength of 1291\\AA\\ (Program ID: 15099; PI: Chisholm) . At a redshift $z = 0.0148$, it does not exhibit any notable \\lya\\ forest absorption. We modelled its flux redward of \\lya\\ in a similar fashion to the $z \\sim 2$ composites and then extrapolated blueward. We find that the extrapolation accurately reproduces the stellar continuum shape, validating our procedure.\n\n\\begin{figure*}[ht]\n    \\begin{center}\n    \\includegraphics[scale=.5]{CG274_sb99.pdf}\n    \\caption{An example of the C19 SB99 fitting routine successfully modeling the continuum shape blueward of \\lya. CG 274 was normalized at 1270\\AA\\ and was fit in the 1223-1406\\AA\\ region. The SED model extends to $\\sim$ 1100\\AA. There are two earth-glow sky emission features (shown in green) at 1195\\AA\\ and 1290\\AA\\ several ISM absorption lines that are not part of the actual galaxy spectrum. Figure 2 from \\citet{Chisholm_2015} also demonstrates similar success at reproducing the blue continuum.}\n    \\label{fig:sb99}\n    \\end{center}\n\\end{figure*}\n\n\n\\section{\\teff\\ Measurements \\& Associated Errors}%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:Effective Opacity Measurements}\n\nArmed with an SED model for each composite and bootstrap realization, we analyzed the \\lya\\ forest to measure an effective opacity at each wavelength index. We used the 1070-1170\\AA\\ range to avoid continuum fitting problems associated with rapidly changing emission-line profiles, and possible contamination from the proximity effect \\citep{Kirkman_2005}. For each stack, we masked the following forest ISM lines with a $\\pm$ 5\\AA\\ buffer: 1083.99, 1117.97, 1122.52, 1128.01, 1144.93, 1152.81\\AA. Next, we measured the effective opacity of every stack/model pair for each wavelength index. \n\n\\begin{equation}\n        \\tau_{\\rm eff} = -\\ln \\frac{F_{\\rm obs}}{F_{\\rm model}} \\;\\;\n        \\label{eq:teff}\n\\end{equation}\nHere, $F_{\\rm obs}$ is the average flux and $F_{\\rm model}$ is the extrapolated SED. \n\n\\subsection{Metal Corrections}\n\nAs we hoped to compare our \\teff\\ directly to other works that carry out similar analyses \\citep{Schaye_2003, Kirkman_2005, Becker_2013}, we corrected our values for absorption from metal lines. Though there are several ways of addressing the contribution to \\teff\\ from metal absorption (or damped absorbers in the case of quasar spectra) we followed the example of \\cite{Kirkman_2005} by subtracting the\nmetal absorption statistically. We chose to apply this method because their solution did not require identification of contaminating metal lines by eye like that of \\cite{Schaye_2003}. Instead \\cite{Kirkman_2005} built on a method originally designed by \\cite{Tytler_2004} and estimated the metal absorption over the extended redshift range (1.7-3.54) using a sample of 52 quasars.\n\nIn general the absorption due to metals in composite spectra essentially scales the mean flux by a relatively minor factor, which becomes increasingly less important at higher redshifts ($z \\sim 4$) \\citep{Becker_2013}. In fact \\cite{Faucher-Giguere_2008} compared the two correction methods from \\cite{Schaye_2003} and \\cite{Kirkman_2005}, finding that either method was accurate to the level of their statistical error bars.\n\nTo find the metal contribution as a function of rest-frame wavelength, we used \\cite[equation 1]{Kirkman_2005}. They define DM as the amount of absorption from metal lines alone, as originally coined in \\cite{Tytler_2004}. We converted the DM value to $\\tau_{M}$ despite the fact that DM is approximately equal to $\\tau_{M}$ for z $\\sim$ 2.\n\n\\begin{equation}\n        DM = 0.0156 - (4.646 * 10^{-5})(\\lambda_{rest} - 1360\\AA)) \\;\\;\n        \\label{eq:DM}\n\\end{equation}\n\n\\begin{equation}\n        \\tau_{M} = ln(1 + DM) \\;\\;\n        \\label{eq:tauM}\n\\end{equation}\nWhere $\\tau_{M}$ is the contribution to the absorption from metals and where $\\lambda_{rest}$ is a wavelength index in the forest of the stack. Then, by subtracting the contribution from metals we were left with corrected values of \\teff.\n\n\\begin{equation}\n        \\tau_{\\rm eff} = \\tau_{\\rm total} - \\tau_{M}\\;\\;\n        \\label{eq:corrected}\n\\end{equation}\nWhere $\\tau_{total}$ is simply the total observed optical depth and \\teff\\ is the observed optical depth that has been corrected for metal absorption. \n\n\\subsection{Redshift Interval}\n\nFinally, because we were interested in measuring the redshift evolution of \\teff\\, we converted the wavelength arrays to values of $z$, sampling the entirety of the redshift window included in each stack.\n\n\\begin{equation}\n        z_{i} = (\\lambda_{rest}/1216\\AA)(1 + z_{med}) - 1  \\;\\; \n        \\label{eq:zi}\n\\end{equation}\nWhere $z_{i}$ is the redshift of a particular absorber in the IGM and \\zem\\ is the median redshift value of each stack. Because the \\zem\\ values of our two composite intervals were similar, their redshift coverage overlapped (see appendix table \\ref{tab:tau_vals}). Combining both redshift intervals, we were left with a total of 88 indices (56 from the \\hiz\\ interval and 58 from the \\loz\\ interval) from which we measured \\teff\\ in the 1070-1170\\AA\\ range. This combined redshift sample extended from 2.02 - 2.44, with a median value of 2.22.\n\n\\subsection{Error Estimates on \\teff}\n\nThe errors on the \\teff\\ values ($\\sigma_{\\tau}$) were directly measured from the bootstrap analysis but were not simply the standard deviation of each redshift interval across the bootstrap. Instead, we report the diagonals of the covariance matrices in \\teff (found using the same method as described in \\ref{subsec:bootstrap}). We did not report uncertainty for redshift values as they were only dependent on the \\zem\\ and $\\lambda_{i}$, neither of which had defined errors. For our combined set of measurements and their 1D errors, see appendix table \\ref{tab:tau_vals}.\n\n\\subsection{Power Law Fitting}\n\nUsing a least-squares formalism and the full bootstrap-generated covariance matrices, we fit our combined measurements of \\teff\\ with the following analytic power-law function.\n\n\\begin{equation}\n        \\tau_{\\rm eff} = A[(1+z)/(1+z_{piv})]^{B}  \\;\\;\n        \\label{eq:powerlaw}\n\\end{equation}\nwhere $A$ and $B$ are the scale factor and power-law index parameters. The $z_{piv}$ value included in the fitting function, shifts the power-law index pivot, normalizing the fit to our redshift range \\citep{Becker_2013}. We chose $z_{piv} = 2.22$ as it is the median value of our \\lya\\ forest redshift distribution as measured from \\ref{eq:zi}. Our best fit scale factor and power-law index parameters are $A = \\Aval \\pm \\Aerr$ and $B = \\Bval \\pm \\Berr$ respectively. As shown in figure \\ref{fig:powerlaw}, the measurements scatter about this curve in a roughly stochastic manner consistent with the uncertainty estimates. One does, however, identify a set of measurements that lie significantly above the model at $z \\sim 2.1-2.2$. We attribute these fluctuations to spectral features not smoothed out in our composite spectra. They have not greatly influenced the model because of their small number and significant error estimates.\n\n\\subsection{Redshift Evolution in \\teff}\n\\label{subsec:literature}\n\nWith a best fit power law index error $\\sigma_{B}$ = \\Berr, we report poor sensitivity to the known evolution of \\teff\\ at redshifts higher than $z = z_{piv}$. In short, the redshift evolution of \\teff\\ past $z \\sim 3$ was difficult to model given the scatter of our measurements in our narrow redshift window $\\Delta z \\sim 0.5$ (see figure \\ref{fig:powerlaw}).\n\nEvaluating our model at $z = z_{piv}$ we found \\teff\\ = \\Aval $\\pm$ \\Aerr. This uncertainty does not include a contribution from the error in our power law index parameter. We exluded $\\sigma_{B}$ in our error estimate at $z = z_{piv}$ because our data were not sensitive to that parameter. We note that our statistical estimate in the uncertainty of \\teff at $z = z_{piv}$ ignores systematic errors which we expect to be at at least 10\\%.\n\nComparing our linear fit's prediction of \\teff\\ at $z = z_{piv}$ to previous estimates from analysis of quasar spectra; \\cite{Kirkman_2005} and \\cite{Becker_2013} \\teff\\ = 0.143, 0.152 (respectively), we found good agreement. We did not find similar compliance with the power law fit from \\cite{Schaye_2003} as they predicted \\teff = 0.298 at $z = z_{piv}$. This might be because their sample of 21 quasars were significantly contaminated by metal lines, resulting in slight overestimation around $z \\sim 2$.\n\n\\begin{figure*}[ht]\n    \\centering\n    \\includegraphics[scale=.5]{least_squares.pdf}\n    \\caption{Our measurements of \\teff\\ as a function of redshift from both redshift intervals. Though we used the full covariance matrix to fit our data with the power law from \\ref{eq:powerlaw}, only the diagonals of the matrix are shown. The best fit, is plotted by the dotted line with a 1$\\sigma$ uncertainty in the power-law exponent as solid lines.}\n    \\label{fig:powerlaw}\n\\end{figure*}\n\nTo further compare results against previous works \\citep{Schaye_2003, Kirkman_2005, Becker_2013} and to model the redshift evolution of \\teff past $z \\sim 3$, we looked to Gaussian Processes (GP). While common practice is to fit such data with a power-law (equation \\ref{eq:powerlaw}), recent datasets are not sufficiently well-described by this model \\citep{Becker_2013}. Therefore, we analyzed our data alongside the results from \\cite{Schaye_2003, Kirkman_2005, Becker_2013} with a GP model which solves for the optimal functional form describing the data. After experimentation, we settled on a Radial Basis Function (RBF) kernel which has mean-square derivatives of all orders and thus creates a smooth fit (see figure \\ref{fig:gaussian}). This model is provided by the SciKit Learn toolbox\\footnote{https://scikit-learn.org/~gaussian.process.kernels.RBF} \\citep{scikit-learn}. We did not fit the GP model with our full covariance matrix nor did we use any of the reported 2D errors for  \\citep{Schaye_2003, Kirkman_2005, Becker_2013}. Instead, to simplify the analyses, we only used the 1D diagonals as errors in our measurement.\n \n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=\\columnwidth]{gaussian_model.pdf}\n    \\caption{The best fit GP model and associated uncertainty. All of the data points included in the figure \\citep{Schaye_2003, Kirkman_2005, Becker_2013} were corrected for intervening metals (and optically thick absorbers in the case of the QSO studies). All analyses shown, were used to constrain the GP model which successfully predicts the steep redshift evolution in \\teff.}\n    \\label{fig:gaussian}\n\\end{figure}\n\n\\section{Summary and Concluding Remarks} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:conclusions}\n\nWe used 281 LBG spectra collected by the CLAMATO survey to create two composite spectra in the following redshift intervals: $2.25 < z < 2.5$ and $2.5 < z < 2.75$. The normalized composites were fit with simple stellar population SB99 models at rest wavelengths 1225-1400\\AA. Extrapolations of these models blueward of \\lya\\ provided estimates of the effective optical depth \\teff\\ of the IGM from $z \\approx 2.0 -2.5$. We derived bootstrap-generated errors based on the variance in our LBG stacking and propagated these through to the SED fitting.\n\nOur primary results are:\n\n1) A best-fit to the power-law $\\mteff = A[(1+z)/(1+2.22)]^{B}$, giving measurements $A = \\Aval \\pm \\Aerr$ and $B = \\Bval \\pm \\Berr$.\n\n2) Our estimate of \\teff\\ = \\Aval $\\pm$ \\Aerr at $z = 2.22$ is in good agreement with previous estimations based on quasar analysis. This demonstrates that quasar continuum estimations at $z<2.5$ is not subject to large systematic uncertainties.\n\n3) A Gaussian Processes prediction of the redshift evolution of \\teff\\ using a Radial Basis Kernel. In conjunction with \\cite{Schaye_2003, Kirkman_2005, Becker_2013} we show strong evolution in \\teff\\ at $z > 2$.\n\nAs we progress to the next generation of large-scale galaxy surveys at $z>2$ (e.g.\\ Prime Focus Spectrograph survey), it is possible that measurements of \\teff\\ will be drawn primarily from analyses of LBGs. Of course, a continued comparison between quasars and galaxies will\nbe critical to assess systematic uncertainties associated with continuum estimation.\n \n\\begin{acknowledgements}\n\nWe thank the anonymous referee for careful reading of the original manuscript and their insightful suggestions. Jose Monzon would like to thank Marie Lau, Sunil Sihma and Jiani Ding for their input with several aspects of this project. The data presented herein were obtained at the W.M. Keck Observatory, which is operated as a scientific partnership among the California Institute of Technology, the University of California and the National Aeronautics and Space Administration (NASA). The Observatory was made possible by the generous financial support of the W.M. Keck Foundation. The authors also wish to recognize and acknowledge the very significant cultural role and reverence that the summit of Maunakea has always had within the indigenous Hawai$'$ian community. We are most fortunate to have the opportunity to conduct observations from this mountain. Support for this work was provided by NASA through the NASA Hubble Fellowship grant \\#51432 awarded by the Space Telescope Science Institute, which is operated by the Association of Universities for Research in Astronomy, Inc., for NASA, under contract NAS5-26555. Based on observations made with the NASA/ESA Hubble Space Telescope, obtained from the data archive at the Space Telescope Science Institute. STScI is operated by the Association of Universities for Research in Astronomy, Inc. under NASA contract NAS 5-26555.Support for this work was provided by NASA through grant number 15099 from the Space Telescope Science Institute, which is operated by AURA, Inc., under NASA contract NAS 5-26555.\n\n\\end{acknowledgements}\n\n\\bibliography{IGM_refs.bib}\n\n\\appendix\n\n\\begin{center}\n\\begin{longtable}{l|c|c|c}\n\\caption{The sample of CLAMATO LBGs used in our composite analysis}\n\\label{tab:clamato}\n\\hline\n\\textbf{CLAMATO ID} & \\textbf{RA} & \\textbf{DEC} & \\textbf{z}\\\\\n\\hline\n\\endfirsthead\n\\multicolumn{4}{c}\n{\\tablename\\ \\thetable} \\\\\n\\hline\n\\textbf{CLAMATO ID} & \\textbf{RA} & \\textbf{DEC} & \\textbf{z}\\\\\n\\hline\n\\endhead\n\\hline \\multicolumn{4}{r}{\\textit{Continued on next page}} \\\\\n\\endfoot\n\\hline\n\\endlastfoot\ncl2016comb-zsp2.3-00871 & 150.08844 & 2.24847 & 2.301 \\\\\ncl2016comb-zsp2.6-00923 & 150.0679 & 2.15819 & 2.621 \\\\\ncl2016comb-zsp2.5-00941 & 150.03569 & 2.2896 & 2.45 \\\\\ncl2016comb-zsp2.7-00954 & 150.02919 & 2.25323 & 2.66 \\\\\ncl2016comb-zsp2.4-01012 & 150.05318 & 2.1513 & 2.516 \\\\\ncl2016comb-zsp2.6-01016 & 150.02277 & 2.14595 & 2.624 \\\\\ncl2016comb-zsp2.4-01321 & 150.02322 & 2.37721 & 2.384 \\\\\ncl2016comb-zsp2.7-01349 & 150.0231 & 2.31791 & 2.675 \\\\\ncl2016comb-zsp2.6-01865 & 150.1011 & 2.24173 & 2.647 \\\\\ncl2016comb-zph2.5-12541 & 150.10332 & 2.2585 & 2.438 \\\\\ncl2016comb-zph2.6-12722 & 150.09888 & 2.16134 & 2.416 \\\\\ncl2016comb-zph2.3-12836 & 150.04671 & 2.25102 & 2.284 \\\\\ncl2016comb-zph2.6-15035 & 150.09714 & 2.45167 & 2.479 \\\\\ncl2016comb-zph2.4-15059 & 150.16531 & 2.42249 & 2.506 \\\\\ncl2016comb-zph2.3-15171 & 150.09419 & 2.34853 & 2.273 \\\\\ncl2016comb-zph2.6-15218 & 150.17313 & 2.3254 & 2.613 \\\\\ncl2016comb-zsp2.6-15363 & 149.98645 & 2.37884 & 2.545 \\\\\ncl2016comb-zsp2.4-15373 & 150.00044 & 2.37243 & 2.42 \\\\\ncl2016comb-zph2.4-15473 & 150.04306 & 2.31694 & 2.44 \\\\\npc06-zph2.3-15159 & 150.09453 & 2.35827 & 2.466 \\\\\npc06-zsp2.4-00852 & 150.06163 & 2.28314 & 2.377 \\\\\ncpilot06-zsp2.7-00857 & 150.09343 & 2.27371 & 2.65 \\\\\ncpilot06-zsp2.7-01260 & 150.07938 & 2.3406 & 2.679 \\\\\ncpilot06-zsp2.7-01276 & 150.0798 & 2.30685 & 2.679 \\\\\ncpilot06-zsp2.7-01324 & 150.03629 & 2.37356 & 2.73 \\\\\ncpilot05-zph2.3-12714 & 150.0827 & 2.16487 & 2.26 \\\\\ncpilot02-zph2.5-12826 & 150.00772 & 2.24664 & 2.525 \\\\\ncpilot02-zph2.5-12988 & 149.98288 & 2.1657 & 2.42 \\\\\ncpilot02-zsp2.3-00962 & 150.00296 & 2.24145 & 2.267 \\\\\ncpilot02-zsp2.3-01013 & 149.96033 & 2.15784 & 2.297 \\\\\ncpilot02-zsp2.4-00965 & 149.99504 & 2.2398 & 2.442 \\\\\ncpilot02-zsp2.4-01882 & 149.99516 & 2.23734 & 2.45 \\\\\ncpilot02-zsp2.5-00990 & 149.98834 & 2.20705 & 2.458 \\\\\ncpilot02-zsp2.6-00986 & 149.99481 & 2.21234 & 2.556 \\\\\ncpilot02-zsp2.6-01009 & 150.0136 & 2.16877 & 2.623 \\\\\ncpilot02-zsp2.7-00982 & 150.02107 & 2.21256 & 2.658 \\\\\ncpilot09-zph2.5-15182 & 150.12419 & 2.34884 & 2.513 \\\\\ncpilot09-zph2.5-15268 & 150.15688 & 2.30079 & 2.505 \\\\\ncpilot09-zph2.6-12505 & 150.21675 & 2.36974 & 2.408 \\\\\ncpilot09-zph2.6-15214 & 150.11501 & 2.3276 & 2.551 \\\\\ncpilot09-zph2.7-15220 & 150.12335 & 2.32413 & 2.623 \\\\\ncpilot09-zsp2.5-00856 & 150.161 & 2.2759 & 2.504 \\\\\ncpilot09-zsp2.5-01753 & 150.15979 & 2.37123 & 2.458 \\\\\ncpilot09-zsp2.5-01754 & 150.14763 & 2.36719 & 2.452 \\\\\ncpilot09-zsp2.6-01252 & 150.16002 & 2.35477 & 2.556 \\\\\ncpilot09-zsp2.6-01262 & 150.11871 & 2.33762 & 2.552 \\\\\ncpilot09-zsp2.7-00858 & 150.14117 & 2.27234 & 2.747 \\\\\ncpilot08-zph2.2-12568 & 150.16913 & 2.23838 & 2.451 \\\\\ncpilot08-zph2.3-01886 & 150.21675 & 2.36974 & 2.305 \\\\\ncpilot08-zph2.5-12604 & 150.1651 & 2.22747 & 2.437 \\\\\ncpilot08-zsp2.3-00892 & 150.10474 & 2.21573 & 2.324 \\\\\ncpilot08-zsp2.4-00877 & 150.12111 & 2.23542 & 2.432 \\\\\ncpilot08-zsp2.7-00889 & 150.14442 & 2.21977 & 2.702 \\\\\ncpilot08-zsp2.7-00903 & 150.1205 & 2.1923 & 2.688 \\\\\ncpilot08-zsp2.7-00933 & 150.10455 & 2.13738 & 2.69 \\\\\ncpilot03-zph2.4-15492 & 149.95932 & 2.30758 & 2.555 \\\\\ncpilot03-zph2.6-12812 & 150.0199 & 2.26976 & 2.42 \\\\\ncpilot03-zsp2.3-01330 & 149.99364 & 2.36083 & 2.256 \\\\\ncpilot03-zsp2.5-01345 & 150.0118 & 2.32297 & 2.467 \\\\\ncpilot03-zsp2.6-01352 & 150.01968 & 2.31087 & 2.624 \\\\\ncpilot12-zph2.4-14888 & 150.24263 & 2.35848 & 2.278 \\\\\ncpilot12-zph2.4-14925 & 150.23189 & 2.33713 & 2.456 \\\\\ncpilot12-zph2.4-15146 & 150.22118 & 2.37094 & 2.52 \\\\\ncpilot12-zph2.6-12247 & 150.24257 & 2.27782 & 2.525 \\\\\ncpilot12-zph2.6-14947 & 150.2346 & 2.33237 & 2.505 \\\\\ncpilot12-zph2.6-15161 & 150.22186 & 2.36248 & 2.5 \\\\\ncpilot12-zph2.6-15173 & 150.22505 & 2.35619 & 2.507 \\\\\ncpilot12-zsp2.5-01268 & 150.21138 & 2.32292 & 2.46 \\\\\ncpilot12-zsp2.5-01274 & 150.22343 & 2.3072 & 2.491 \\\\\ncpilot12-zsp2.7-01272 & 150.19978 & 2.3155 & 2.738 \\\\\nnpc05-zph2.3-12595 & 150.07341 & 2.23328 & 2.303 \\\\\nnpc05-zph2.3-12701 & 150.07675 & 2.17348 & 2.486 \\\\\nnpc05-zph2.5-12653 & 150.06866 & 2.18897 & 2.3 \\\\\nnpc05-zsp2.3-00964 & 150.05905 & 2.24059 & 2.283 \\\\\nnpc05-zsp2.4-01861 & 150.08061 & 2.24284 & 2.437 \\\\\nc16-24-zph2.4-15103 & 150.22504 & 2.39841 & 2.645 \\\\\nc16-24-zph2.4-15121 & 150.2166 & 2.37826 & 2.373 \\\\\nc16-24-zph2.6-17723 & 150.21797 & 2.49178 & 2.645 \\\\\nc16-24-zph2.7-17497 & 150.22946 & 2.47711 & 2.66 \\\\\nc16-24-zsp2.5-01778 & 150.19771 & 2.48577 & 2.49 \\\\\nc16-24-zsp2.6-01219 & 150.20456 & 2.45545 & 2.58 \\\\\nc16-24-zsp2.7-01779 & 150.20668 & 2.48269 & 2.676 \\\\\nc16-11-zph2.4-12707 & 150.20447 & 2.17102 & 2.37 \\\\\nc16-11-zph2.5-12304 & 150.22772 & 2.23602 & 2.493 \\\\\nc16-11-zph2.5-12634 & 150.18759 & 2.20976 & 2.48 \\\\\nc16-11-zsp2.3-00873 & 150.19859 & 2.24642 & 2.367 \\\\\nc16-11-zsp2.4-00884 & 150.20885 & 2.22566 & 2.437 \\\\\nc16-11-zsp2.5-00834 & 150.23257 & 2.14658 & 2.638 \\\\\nc16-20-zph2.6-17715 & 150.09602 & 2.49511 & 2.536 \\\\\nc16-20-zph2.6-26486 & 150.06027 & 2.3877 & 2.55 \\\\\nc16-20-zsp2.5-01241 & 150.07576 & 2.38064 & 2.466 \\\\\nc16-20-zsp2.7-01233 & 150.08762 & 2.39438 & 2.702 \\\\\nc16-22-zph2.4-15040 & 150.13757 & 2.44066 & 2.51 \\\\\nc16-22-zph2.6-17758 & 150.10231 & 2.47219 & 2.606 \\\\\nc16-22-zsp2.5-01239 & 150.14885 & 2.38391 & 2.505 \\\\\nc16-18-zph2.6-15288 & 149.95987 & 2.45353 & 2.515 \\\\\nc16-18-zph2.6-15292 & 149.95877 & 2.45022 & 2.627 \\\\\nc16-18-zsp2.4-01589 & 150.01366 & 2.46674 & 2.417 \\\\\ncl2017comb-zsp2.5-00834 & 150.23257 & 2.14658 & 2.637 \\\\\ncl2017comb-zsp2.3-00871 & 150.08844 & 2.24847 & 2.301 \\\\\ncl2017comb-zsp2.6-00923 & 150.0679 & 2.15819 & 2.622 \\\\\ncl2017comb-zsp2.7-00954 & 150.02919 & 2.25323 & 2.657 \\\\\ncl2017comb-zsp2.6-00966 & 150.03355 & 2.23549 & 2.555 \\\\\ncl2017comb-zsp2.4-01003 & 150.05382 & 2.185 & 2.56 \\\\\ncl2017comb-zsp2.4-01012 & 150.05318 & 2.1513 & 2.452 \\\\\ncl2017comb-zsp2.6-01016 & 150.02277 & 2.14595 & 2.623 \\\\\ncl2017comb-zsp2.3-01181 & 150.33495 & 2.36654 & 2.315 \\\\\ncl2017comb-zsp2.5-01239 & 150.14885 & 2.38391 & 2.507 \\\\\ncl2017comb-zsp2.5-01245 & 150.1015 & 2.37672 & 2.464 \\\\\ncl2017comb-zsp2.4-01265 & 150.06456 & 2.32904 & 2.447 \\\\\ncl2017comb-zsp2.4-01321 & 150.02322 & 2.37721 & 2.376 \\\\\ncl2017comb-zsp2.7-01349 & 150.0231 & 2.31791 & 2.678 \\\\\ncl2017comb-zsp2.6-01865 & 150.1011 & 2.24173 & 2.646 \\\\\ncl2017comb-zph2.5-12541 & 150.10333 & 2.25851 & 2.437 \\\\\ncl2017comb-zph2.6-12722 & 150.09888 & 2.16134 & 2.417 \\\\\ncl2017comb-zsp2.3-12836 & 150.04671 & 2.25102 & 2.284 \\\\\ncl2017comb-zph2.5-14852 & 150.3867 & 2.37505 & 2.456 \\\\\ncl2017comb-zph2.6-15035 & 150.09714 & 2.45167 & 2.479 \\\\\ncl2017comb-zsp2.5-15059 & 150.16531 & 2.42249 & 2.506 \\\\\ncl2017comb-zph2.3-15171 & 150.09421 & 2.34853 & 2.274 \\\\\ncl2017comb-zph2.6-15218 & 150.17313 & 2.3254 & 2.613 \\\\\ncl2017comb-zsp2.4-15373 & 150.00044 & 2.37243 & 2.418 \\\\\ncl2017comb-zph2.7-15399 & 150.0201 & 2.35363 & 2.689 \\\\\ncl2017comb-zph2.4-15473 & 150.04306 & 2.31694 & 2.44 \\\\\ncl2017comb-zsp2.6-15492 & 149.95932 & 2.30758 & 2.555 \\\\\ncl2017comb-zsp2.6-17758 & 150.10231 & 2.47219 & 2.606 \\\\\npc06-zph2.3-15159 & 150.09453 & 2.35827 & 2.461 \\\\\npc06-zsp2.4-00852 & 150.06163 & 2.28314 & 2.375 \\\\\ncpilot06-zsp2.7-00857 & 150.09343 & 2.27371 & 2.65 \\\\\ncpilot06-zsp2.7-01260 & 150.07938 & 2.3406 & 2.679 \\\\\ncpilot06-zsp2.7-01276 & 150.0798 & 2.30685 & 2.679 \\\\\ncpilot05-zph2.3-12714 & 150.0827 & 2.16487 & 2.26 \\\\\ncpilot05-zsp2.7-00994 & 150.04597 & 2.20114 & 2.709 \\\\\ncpilot02-zph2.5-12826 & 150.00772 & 2.24664 & 2.525 \\\\\ncpilot02-zph2.5-12988 & 149.98288 & 2.1657 & 2.42 \\\\\ncpilot02-zsp2.3-00962 & 150.00296 & 2.24145 & 2.267 \\\\\ncpilot02-zsp2.3-01013 & 149.96033 & 2.15784 & 2.297 \\\\\ncpilot02-zsp2.4-00965 & 149.99504 & 2.2398 & 2.442 \\\\\ncpilot02-zsp2.4-01882 & 149.99516 & 2.23734 & 2.45 \\\\\ncpilot02-zsp2.5-00990 & 149.98834 & 2.20705 & 2.458 \\\\\ncpilot02-zsp2.6-00986 & 149.99481 & 2.21234 & 2.556 \\\\\ncpilot02-zsp2.6-01009 & 150.0136 & 2.16877 & 2.623 \\\\\ncpilot02-zsp2.7-00982 & 150.02107 & 2.21256 & 2.658 \\\\\ncpilot09-zph2.5-15182 & 150.12419 & 2.34884 & 2.513 \\\\\ncpilot09-zph2.5-15268 & 150.15688 & 2.30079 & 2.502 \\\\\ncpilot09-zph2.6-12505 & 150.14354 & 2.28177 & 2.408 \\\\\ncpilot09-zph2.6-15214 & 150.11501 & 2.3276 & 2.552 \\\\\ncpilot09-zph2.7-15220 & 150.12335 & 2.32413 & 2.623 \\\\\ncpilot09-zsp2.5-00856 & 150.161 & 2.2759 & 2.504 \\\\\ncpilot09-zsp2.5-01753 & 150.15979 & 2.37123 & 2.46 \\\\\ncpilot09-zsp2.5-01754 & 150.14763 & 2.36719 & 2.455 \\\\\ncpilot09-zsp2.6-01252 & 150.16002 & 2.35477 & 2.556 \\\\\ncpilot09-zsp2.6-01262 & 150.11871 & 2.33762 & 2.552 \\\\\ncpilot09-zsp2.7-00858 & 150.14117 & 2.27234 & 2.747 \\\\\ncpilot08-zph2.2-12568 & 150.16913 & 2.23838 & 2.451 \\\\\ncpilot08-zph2.3-01886 & 150.12947 & 2.2072 & 2.305 \\\\\ncpilot08-zph2.5-12604 & 150.1651 & 2.22747 & 2.437 \\\\\ncpilot08-zsp2.3-00892 & 150.10474 & 2.21573 & 2.321 \\\\\ncpilot08-zsp2.4-00877 & 150.12111 & 2.23543 & 2.432 \\\\\ncpilot08-zsp2.7-00889 & 150.14442 & 2.21977 & 2.71 \\\\\ncpilot08-zsp2.7-00903 & 150.1205 & 2.1923 & 2.685 \\\\\ncpilot08-zsp2.7-00933 & 150.10455 & 2.13738 & 2.69 \\\\\ncpilot03-zsp2.3-01330 & 149.99364 & 2.36083 & 2.256 \\\\\ncpilot03-zsp2.7-00951 & 150.0182 & 2.25944 & 2.673 \\\\\ncpilot12-zph2.4-14888 & 150.24263 & 2.35848 & 2.278 \\\\\ncpilot12-zph2.4-14925 & 150.23189 & 2.33713 & 2.456 \\\\\ncpilot12-zph2.4-15146 & 150.22118 & 2.37094 & 2.517 \\\\\ncpilot12-zph2.6-12247 & 150.24257 & 2.27782 & 2.525 \\\\\ncpilot12-zph2.6-14947 & 150.2346 & 2.33237 & 2.505 \\\\\ncpilot12-zph2.6-15161 & 150.22186 & 2.36248 & 2.5 \\\\\ncpilot12-zph2.6-15173 & 150.22505 & 2.35619 & 2.507 \\\\\ncpilot12-zsp2.5-01268 & 150.21138 & 2.32292 & 2.46 \\\\\ncpilot12-zsp2.5-01274 & 150.22343 & 2.3072 & 2.491 \\\\\ncpilot12-zsp2.5-01678 & 150.22528 & 2.3512 & 2.484 \\\\\ncpilot12-zsp2.7-01272 & 150.19978 & 2.3155 & 2.738 \\\\\nnpc05-zph2.3-12595 & 150.07341 & 2.23328 & 2.303 \\\\\nnpc05-zph2.3-12701 & 150.07675 & 2.17348 & 2.486 \\\\\nnpc05-zph2.5-12653 & 150.06866 & 2.18897 & 2.3 \\\\\nnpc05-zsp2.3-00964 & 150.05905 & 2.24059 & 2.281 \\\\\nnpc05-zsp2.4-01861 & 150.08061 & 2.24284 & 2.437 \\\\\nc16-24-zph2.4-15103 & 150.22504 & 2.39841 & 2.642 \\\\\nc16-24-zph2.4-15121 & 150.2166 & 2.37826 & 2.375 \\\\\nc16-24-zph2.6-17723 & 150.21797 & 2.49178 & 2.645 \\\\\nc16-24-zph2.7-17497 & 150.22946 & 2.47711 & 2.628 \\\\\nc16-24-zsp2.5-01778 & 150.19771 & 2.48577 & 2.535 \\\\\nc16-24-zsp2.6-01219 & 150.20456 & 2.45545 & 2.586 \\\\\nc16-24-zsp2.7-01779 & 150.20668 & 2.48269 & 2.675 \\\\\nc16-11-zph2.3-12434 & 150.23575 & 2.1661 & 2.31 \\\\\nc16-11-zph2.3-12690 & 150.21985 & 2.17724 & 2.61 \\\\\nc16-11-zph2.4-12707 & 150.20447 & 2.17102 & 2.37 \\\\\nc16-11-zph2.5-12304 & 150.22772 & 2.23602 & 2.489 \\\\\nc16-11-zph2.5-12634 & 150.18759 & 2.20976 & 2.48 \\\\\nc16-11-zsp2.4-00884 & 150.20885 & 2.22566 & 2.438 \\\\\nc16-20-zph2.6-17715 & 150.09602 & 2.49511 & 2.538 \\\\\nc16-20-zph2.6-26486 & 150.06027 & 2.3877 & 2.55 \\\\\nc16-20-zsp2.5-01241 & 150.07576 & 2.38064 & 2.469 \\\\\nc16-20-zsp2.7-01233 & 150.08762 & 2.39438 & 2.703 \\\\\nc16-22-zph2.4-15040 & 150.13757 & 2.44066 & 2.51 \\\\\nc16-18-zph2.6-15288 & 149.95987 & 2.45353 & 2.515 \\\\\nc16-18-zph2.6-15292 & 149.95877 & 2.45022 & 2.627 \\\\\nc16-18-zsp2.4-01589 & 150.01366 & 2.46674 & 2.415 \\\\\nc16-18-zsp2.5-01298 & 149.97008 & 2.43493 & 2.458 \\\\\nc17-27s-zph2.4-12455 & 150.24768 & 2.15066 & 2.294 \\\\\nc17-27s-zph2.5-12355 & 150.25565 & 2.21225 & 2.578 \\\\\nc17-27s-zph2.5-32293 & 150.2847 & 2.21318 & 2.503 \\\\\nc17-27s-zph2.6-12374 & 150.27167 & 2.20637 & 2.615 \\\\\nc17-27s-zph2.7-12405 & 150.27063 & 2.18604 & 2.58 \\\\\nc17-27s-zph2.7-32286 & 150.27771 & 2.21997 & 2.495 \\\\\nc17-27s-zsp2.3-00805 & 150.30594 & 2.19577 & 2.323 \\\\\nc17-27s-zsp2.5-00785 & 150.27141 & 2.24478 & 2.506 \\\\\nc17-27s-zsp2.6-00783 & 150.28088 & 2.24953 & 2.579 \\\\\nc17-27s-zsp2.6-00793 & 150.27214 & 2.2301 & 2.611 \\\\\nc17-27s-zsp2.6-00823 & 150.26257 & 2.16603 & 2.601 \\\\\nc17-28s-zph2.6-12252 & 150.30026 & 2.27421 & 2.581 \\\\\nc17-28s-zph2.6-14978 & 150.29825 & 2.31653 & 2.576 \\\\\nc17-28s-zsp2.4-01216 & 150.26845 & 2.2975 & 2.408 \\\\\nc17-28s-zsp2.5-00771 & 150.27863 & 2.27316 & 2.53 \\\\\nc17-28s-zsp2.5-01189 & 150.29594 & 2.3454 & 2.465 \\\\\nc17-28s-zsp2.5-01193 & 150.30426 & 2.33754 & 2.448 \\\\\nc17-28s-zsp2.5-01201 & 150.25424 & 2.33063 & 2.468 \\\\\nc17-28s-zsp2.5-01203 & 150.25378 & 2.32426 & 2.468 \\\\\nc17-29-zph2.3-33410 & 150.28709 & 2.41177 & 2.312 \\\\\nc17-29-zph2.5-33398 & 150.29295 & 2.42088 & 2.402 \\\\\nc17-29-zph2.5-33402 & 150.30779 & 2.41704 & 2.545 \\\\\nc17-29-zph2.6-14815 & 150.30571 & 2.39347 & 2.47 \\\\\nc17-29-zph2.6-17483 & 150.31509 & 2.49175 & 2.4 \\\\\nc17-29-zph2.6-34570 & 150.28142 & 2.48831 & 2.559 \\\\\nc17-29-zph2.7-14804 & 150.31004 & 2.39676 & 2.566 \\\\\nc17-29-zph2.8-14723 & 150.31305 & 2.45708 & 2.567 \\\\\nc17-29-zsp2.3-01174 & 150.25618 & 2.38222 & 2.313 \\\\\nc17-29-zsp2.6-01157 & 150.29317 & 2.45171 & 2.556 \\\\\nc17-62-zph2.3-14818 & 150.34473 & 2.39424 & 2.279 \\\\\nc17-62-zph2.4-14776 & 150.37248 & 2.41991 & 2.471 \\\\\nc17-62-zph2.4-17503 & 150.33798 & 2.47542 & 2.403 \\\\\nc17-62-zph2.5-14742 & 150.32265 & 2.44352 & 2.505 \\\\\nc17-62-zph2.5-14763 & 150.32812 & 2.42992 & 2.555 \\\\\nc17-62-zph2.6-14751 & 150.31796 & 2.43698 & 2.551 \\\\\nc17-62-zph2.7-17517 & 150.3484 & 2.46721 & 2.587 \\\\\nc17-62-zsp2.5-01159 & 150.35135 & 2.44302 & 2.452 \\\\\nc17-62-zsp2.5-01168 & 150.31071 & 2.40391 & 2.496 \\\\\nc17-62-zsp2.5-01502 & 150.3588 & 2.48178 & 2.471 \\\\\nc17-62-zsp2.5-01512 & 150.35596 & 2.4634 & 2.471 \\\\\nc17-61L-zph2.5-14882 & 150.34009 & 2.35964 & 2.452 \\\\\nc17-61L-zph2.5-15010 & 150.32918 & 2.30061 & 2.317 \\\\\nc17-61L-zph2.5-32231 & 150.32224 & 2.28384 & 2.586 \\\\\nc17-61L-zph2.6-12224 & 150.31772 & 2.28078 & 2.534 \\\\\nc17-61L-zph2.6-14940 & 150.36411 & 2.33619 & 2.494 \\\\\nc17-61L-zph2.6-15018 & 150.37976 & 2.29622 & 2.496 \\\\\nc17-61L-zph2.6-33462 & 150.37938 & 2.33715 & 2.498 \\\\\nc17-61L-zph2.8-32238 & 150.38272 & 2.2858 & 2.658 \\\\\nc17-61L-zsp2.5-01187 & 150.35432 & 2.35273 & 2.453 \\\\\nc17-61L-zsp2.6-00767 & 150.31223 & 2.27923 & 2.578 \\\\\nc17-61L-zsp2.7-01205 & 150.34872 & 2.32137 & 2.657 \\\\\nc17-61L-zsp2.7-01212 & 150.37012 & 2.30588 & 2.655 \\\\\nc17-60L-zph2.3-32330 & 150.35461 & 2.14912 & 2.272 \\\\\nc17-60L-zph2.5-12291 & 150.35986 & 2.24675 & 2.455 \\\\\nc17-60L-zph2.5-12400 & 150.32335 & 2.18807 & 2.502 \\\\\nc17-60L-zph2.6-12359 & 150.36682 & 2.21295 & 2.483 \\\\\nc17-60L-zph2.6-12375 & 150.32465 & 2.20695 & 2.49 \\\\\nc17-60L-zph2.6-12432 & 150.36377 & 2.16507 & 2.576 \\\\\nc17-60L-zph2.6-32321 & 150.36781 & 2.15833 & 2.614 \\\\\nc17-60L-zph2.7-12334 & 150.38455 & 2.22249 & 2.728 \\\\\nc17-60L-zph2.9-32309 & 150.31273 & 2.17346 & 2.67 \\\\\nc17-60L-zsp2.3-00826 & 150.31908 & 2.16216 & 2.313 \\\\\nc17-60L-zsp2.5-00794 & 150.31914 & 2.22503 & 2.493 \\\\\nc17-60L-zsp2.6-00819 & 150.37843 & 2.17079 & 2.551 \\\\\nc17-60L-zsp2.6-01719 & 150.31601 & 2.24457 & 2.583 \\\\\nc17-60L-zsp2.7-00788 & 150.39108 & 2.24033 & 2.738 \\\\\nc17-60L-zsp2.7-00802 & 150.34006 & 2.20841 & 2.729 \\\\\npc22L-zph2.3-17733 & 150.14896 & 2.4883 & 2.38 \\\\\npc22L-zph2.5-26344 & 150.10031 & 2.46256 & 2.477 \\\\\npc22L-zph2.8-33515 & 150.15773 & 2.4089 & 2.463 \\\\\np18-zph2.5-15320 & 150.00002 & 2.42489 & 2.63 \\\\\np18-zph2.6-15055 & 150.0636 & 2.42693 & 2.52 \\\\\np18-zph2.7-34724 & 150.05705 & 2.4823 & 2.392 \\\\\np18-zsp2.4-01220 & 150.06973 & 2.45253 & 2.423 \\\\\np15l-zph2.5-15385 & 149.94215 & 2.36591 & 2.477 \\\\\np15l-zph2.5-15435 & 149.95938 & 2.33549 & 2.506 \\\\\np15l-zph2.6-33610 & 149.99947 & 2.33633 & 2.583 \\\\\np15l-zsp2.6-01875 & 149.93594 & 2.29014 & 2.552 \\\\\np15l-zsp2.7-01354 & 149.94077 & 2.30644 & 2.681 \\\\\n\\end{longtable}\n\\end{center}\n\n\\begin{center}\n\\begin{longtable}{c|c|c}\n\\caption{\\teff\\ values and corresponding 1D errors for the \\loz\\ and \\hiz\\ redshift interval. The latter's values are appended to the former's and are separated by a row of dashes.}\n\\label{tab:tau_vals}\n\\hline\n\\textbf{z} & \\textbf{\\teff} & \\textbf{$\\tau_{\\sigma}$} \\\\\n\\hline\n\\endfirsthead\n\\multicolumn{3}{c}\n{\\tablename\\ \\thetable} \\\\\n\\hline\n\\textbf{z} & \\textbf{\\teff} & \\textbf{$\\tau_{\\sigma}$} \\\\\n\\hline\n\\endhead\n\\hline \\multicolumn{3}{r}{\\textit{Continued on next page}} \\\\\n\\endfoot\n\\hline\n\\endlastfoot\n2.0285 & 0.2115 & 0.0926 \\\\\n2.0315 & 0.0508 & 0.0761 \\\\\n2.0345 & 0.0128 & 0.0736 \\\\\n2.0376 & 0.0628 & 0.088 \\\\\n2.0406 & 0.0167 & 0.0763 \\\\\n2.0437 & 0.0372 & 0.0801 \\\\\n2.0467 & 0.1107 & 0.0932 \\\\\n2.0497 & 0.0136 & 0.084 \\\\\n2.0528 & 0.1023 & 0.0828 \\\\\n2.0742 & 0.1106 & 0.078 \\\\\n2.0773 & 0.0145 & 0.0741 \\\\\n2.0804 & 0.237 & 0.0857 \\\\\n2.0835 & 0.2226 & 0.086 \\\\\n2.0866 & 0.1933 & 0.0822 \\\\\n2.0897 & 0.1386 & 0.0682 \\\\\n2.0928 & 0.1717 & 0.0686 \\\\\n2.0958 & 0.061 & 0.071 \\\\\n2.0989 & 0.1111 & 0.0719 \\\\\n2.102 & 0.2439 & 0.0763 \\\\\n2.1052 & 0.2527 & 0.0732 \\\\\n2.1083 & 0.2786 & 0.0772 \\\\\n2.1114 & 0.3183 & 0.0822 \\\\\n2.1145 & 0.1146 & 0.0651 \\\\\n2.1176 & 0.0425 & 0.0682 \\\\\n2.1207 & 0.0495 & 0.0684 \\\\\n2.1238 & 0.1718 & 0.0663 \\\\\n2.127 & 0.152 & 0.0657 \\\\\n2.1301 & 0.2382 & 0.0723 \\\\\n2.1332 & 0.0281 & 0.0759 \\\\\n2.1364 & 0.3557 & 0.0854 \\\\\n2.1395 & 0.3383 & 0.0831 \\\\\n2.1426 & 0.3668 & 0.0716 \\\\\n2.1458 & 0.3355 & 0.0665 \\\\\n2.1489 & 0.279 & 0.0623 \\\\\n2.1997 & 0.2233 & 0.058 \\\\\n2.2029 & 0.2031 & 0.0545 \\\\\n2.2061 & 0.3617 & 0.0625 \\\\\n2.2094 & 0.3471 & 0.0649 \\\\\n2.2126 & 0.1102 & 0.0527 \\\\\n2.2158 & 0.0969 & 0.0503 \\\\\n2.219 & 0.1706 & 0.0533 \\\\\n2.2222 & 0.2714 & 0.0616 \\\\\n2.2254 & 0.1884 & 0.0541 \\\\\n2.2449 & 0.1062 & 0.0486 \\\\\n2.2481 & 0.0974 & 0.0498 \\\\\n2.2677 & 0.1961 & 0.0565 \\\\\n2.2709 & 0.146 & 0.052 \\\\\n2.2742 & 0.098 & 0.0474 \\\\\n2.2775 & 0.1193 & 0.0455 \\\\\n2.2808 & 0.1897 & 0.0492 \\\\\n2.284 & 0.1481 & 0.0488 \\\\\n2.2873 & 0.1862 & 0.0438 \\\\\n2.2906 & 0.2515 & 0.0533 \\\\\n2.2939 & 0.1222 & 0.046 \\\\\n2.2972 & 0.2033 & 0.0458 \\\\\n2.3005 & 0.1946 & 0.0572 \\\\\n- & - & - \\\\\n2.1566 & 0.3301 & 0.0692 \\\\\n2.1597 & 0.3741 & 0.0739 \\\\\n2.1629 & 0.196 & 0.0678 \\\\\n2.1661 & 0.2386 & 0.0635 \\\\\n2.1692 & 0.2195 & 0.0617 \\\\\n2.1724 & 0.0898 & 0.0631 \\\\\n2.1756 & 0.1067 & 0.0584 \\\\\n2.1787 & 0.0725 & 0.0618 \\\\\n2.1819 & 0.1125 & 0.0601 \\\\\n2.1851 & 0.0345 & 0.0557 \\\\\n2.2075 & 0.1165 & 0.0516 \\\\\n2.2107 & 0.0854 & 0.061 \\\\\n2.2139 & 0.1759 & 0.0558 \\\\\n2.2171 & 0.1038 & 0.0536 \\\\\n2.2204 & 0.2195 & 0.0607 \\\\\n2.2236 & 0.1268 & 0.0482 \\\\\n2.2268 & 0.11 & 0.0584 \\\\\n2.23 & 0.2422 & 0.0587 \\\\\n2.2333 & 0.1673 & 0.0534 \\\\\n2.2365 & 0.2795 & 0.0576 \\\\\n2.2397 & 0.1813 & 0.0534 \\\\\n2.243 & 0.247 & 0.0515 \\\\\n2.2462 & 0.1324 & 0.051 \\\\\n2.2495 & 0.0812 & 0.0458 \\\\\n2.2527 & 0.0554 & 0.0523 \\\\\n2.256 & 0.0118 & 0.0503 \\\\\n2.2592 & 0.0793 & 0.0481 \\\\\n2.2625 & 0.0745 & 0.0489 \\\\\n2.2658 & 0.128 & 0.057 \\\\\n2.269 & -0.0031 & 0.0505 \\\\\n2.2723 & 0.182 & 0.0436 \\\\\n2.2756 & 0.2785 & 0.05 \\\\\n2.2789 & 0.2218 & 0.0582 \\\\\n2.2821 & 0.2094 & 0.0561 \\\\\n2.2854 & 0.2975 & 0.0498 \\\\\n2.3384 & 0.2053 & 0.0461 \\\\\n2.3418 & 0.2232 & 0.0447 \\\\\n2.3451 & 0.3334 & 0.0586 \\\\\n2.3485 & 0.3247 & 0.0542 \\\\\n2.3518 & 0.2601 & 0.0509 \\\\\n2.3552 & 0.098 & 0.0411 \\\\\n2.3585 & 0.2244 & 0.055 \\\\\n2.3619 & 0.1617 & 0.05 \\\\\n2.3652 & 0.1963 & 0.0481 \\\\\n2.3855 & 0.0616 & 0.0463 \\\\\n2.3889 & 0.0763 & 0.0377 \\\\\n2.4093 & 0.1726 & 0.0505 \\\\\n2.4127 & 0.204 & 0.0465 \\\\\n2.4161 & 0.215 & 0.0362 \\\\\n2.4195 & 0.1851 & 0.0385 \\\\\n2.4229 & 0.1438 & 0.0376 \\\\\n2.4264 & 0.1895 & 0.04 \\\\\n2.4298 & 0.1142 & 0.0431 \\\\\n2.4332 & 0.1336 & 0.04 \\\\\n2.4367 & 0.1676 & 0.0468 \\\\\n2.4401 & 0.1135 & 0.0408 \\\\\n2.4436 & 0.1519 & 0.0428 \\\\\n2.447 & 0.0025 & 0.0363 \\\\\n\\end{longtable}\n\\end{center}\n\n\\end{document}", "meta": {"hexsha": "c2f85c552b3005bae63670b9a45541291b2b527e", "size": 60193, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "manuscript/arxiv/tau_eff/tau_eff.tex", "max_stars_repo_name": "profxj/lbg_da", "max_stars_repo_head_hexsha": "468f3aa47d2bf7c02b4a8eff659554c4b2449e31", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "manuscript/arxiv/tau_eff/tau_eff.tex", "max_issues_repo_name": "profxj/lbg_da", "max_issues_repo_head_hexsha": "468f3aa47d2bf7c02b4a8eff659554c4b2449e31", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "manuscript/arxiv/tau_eff/tau_eff.tex", "max_forks_repo_name": "profxj/lbg_da", "max_forks_repo_head_hexsha": "468f3aa47d2bf7c02b4a8eff659554c4b2449e31", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 75.24125, "max_line_length": 1567, "alphanum_fraction": 0.7222434502, "num_tokens": 21461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3051849809932951}}
{"text": "\\section{Data-driven based SHM Techniques: Related work}\r\n\\label{sec33}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nThe importance of SHM systems originated from their ability to monitor the condition of structures in a real-time.\r\nSHM systems are implemented using data-driven methods, which require a huge amount of data that are captured by monitoring the status of a structure.\r\n\r\nThe process of extracting features from structures in conventional techniques needs a lot of time and requires experts in the field. \r\nTherefore, introducing machine learning methods to the feature extraction process became necessary.\r\nHence, deep learning methods have the capability to generalise and learn new features by themselves which improves their functionality in damage estimation.\r\n\r\nDL approach makes it possible to use registered data in their raw form without any need to perform feature extraction, hence, such an approach has an end-to-end structure which automatically learns and discovers the hidden features in a high dimensional input data~\\cite{LeCun, Networks}. \r\nFigure ~\\ref{fig:DL_ML} illustrates the main differences between the conventional ML-based SHM and DL-based SHM approaches.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\\begin{figure}[!h]\r\n%\t\\begin{center}\r\n%\t\t\\includegraphics[width=1\\textwidth]{Figures/Chapter_2/DL_vs_ML.png}\r\n%\t\\end{center}\r\n%\t\\caption{(a) Conventional ML based SHM vs. (b) DL based SHM.}\r\n%\t\\label{fig:DL_ML}\r\n%\\end{figure} \r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\begin{figure}[!ht]\r\n\t\\centering\r\n\t\\begin{subfigure}{1\\textwidth}\t\t\r\n\t\t\\centering\r\n\t\t\\includegraphics[width=1\\textwidth]{Figures/Chapter_3/conventional_ML.png}\r\n\t\t\\caption{} \r\n\t\t\\label{fig:ML_conventional}\r\n\t\\end{subfigure}\r\n\t\\\\\r\n\t\\begin{subfigure}{1\\textwidth}\r\n\t\t\\centering\r\n\t\t\\includegraphics[width=1\\textwidth]{Figures/Chapter_3/DL_approach.png}\r\n\t\t\\caption{} \r\n\t\t\\label{fig:DL_approach}\r\n\t\\end{subfigure}\t\r\n\t\\caption{(a) Conventional ML based SHM vs. (b) DL based SHM.}\r\n\t\\label{fig:ML_vs_DL}\r\n\\end{figure}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\textcite{Worden2007} have proposed several axioms related to SHM systems implemented using machine learning methods. \r\nAccording to them, damage detection can be performed in unsupervised learning, however, recognising the damage type and how significant it is can not be performed without supervised learning. \r\nMoreover, the feature extraction process is essential for damage detection and it can be performed through analysing and processing the signals captured by the sensors (e.g. PZT actuators), then converting it to damage information.\r\nTherefore, introducing machine learning methods to the feature extraction process became necessary, hence machine learning methods have the capability to generalise and learn new features by themselves which improves their functionality in damage estimation.\r\n\r\nIn recent years data-driven methods based on Machine learning and especially deep learning have been increased in a significant way. \r\nIn the following, methods for damage estimations based on machine learning and deep learning techniques for features extraction are presented. \r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%PZT + SVM\r\n\\textcite{Das2010} presented a method for estimating several types of defects (delamination, saw cut, notches and drilled holes) in composite material. For this purpose, a collection of PZT transducers were attached to the surface of the structure to generate and register Lamb waves propagation. \r\nAccordingly, a time-frequency domain were utilised to extract features relates to defects from the registered response. Those extracted features were fed to one-class SVM, which performs classification and damage estimation. \r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%% PZT + SVM\r\nMoreover, \\textcite{Dib2018} proposed a novelty classifier based on one-class SVM for detecting damage. The method was conducted by extracting data from damage impact on glass-fibre composite plate, then evaluating the performance on the classifier. To extract the necessary features from the propagated wave, the registered signal was segmented into L time bins, then, the Fourier transform was applied on each time bin.\r\nAccordingly, the features vector was constructed from the signal phase and its amplitude for each segmented time bin.\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PZT + PCA+ KNN + SVM\r\n\\textcite{Vitola2016} developed a damage detection and classification methodology that was examined on aluminium plates.\r\nAn array of PZT transducers was placed on the plate surface to sense wave propagation in the structure.\r\nThe methodology is based on the use of principal component analysis (PCA), and machine learning techniques for recognising patterns. \r\nPCA means to analyse a large amount of information by finding the principal components.\r\nHowever, the PCA method is not invariant to scaling, hence data must be normalized~\\cite{Tibaduiza2016}. \r\nNext, normalised data is fed to several machine learning models for training. \r\nFor this purpose, several classification algorithms were applied, Decision trees, KNN and SVM. \r\nHowever, only few of these models presented good outputs in damage detection. \r\n%%%%%%%%%%%%%%%%%%%%%%%%%%% KNN\r\n\r\n\\textcite{Godin2004} applied Acoustic Emission signals (AE) in their approach, which happen due to a sudden release of stored energy when damage occurs.\r\nAE signals contain important information about the discriminative features \r\nfor the damage type such as fibre breakage, de-cohesion of the interface or a crack in the matrix in composite materials.\r\nAuthors in this work presented supervised and unsupervised classifiers to recognise different damage patterns through grouping AE signals from the tensile tests of unidirectional glass/polyester composite into a number of different classes. \r\nFor clustering AE signals, K-means algorithm was used. AE signals were clustered based on several metrics such as the AE signal duration, amplitude, rise time and the number of counts to the peak.\r\nAccordingly, the clustered labelled data is fed into a KNN supervised classifier.\r\nA trained classifier is able to classify new coming data accordingly.\r\nRegarding the unsupervised classification, Kohonen classifier was utilised~\\cite{58325}, which is a self-organising map (SOM) which is a neural network consisting of neurons as processing units. \r\n%%%%%%%%%%%%%%%%%%%%%%%%%%% KNN\r\n\r\n\\textcite{Pashmforoush2014} proposed a technique to classify damage of various lay-up configurations in glass/polyester composites.\r\nFor this purpose, the K-means algorithm with the genetic algorithm were utilised. PCA was used to reduce the data dimensionality.\r\nNext, a combination of the K-means algorithm with the genetic algorithm is used for clustering the data. \r\nThe reason for applying the genetic algorithm is to find the optimal number of cluster centres for the KNN algorithm.\r\nParameters of the AE signals such as peak amplitude, frequency, rise time, energy and the duration were estimated for each cluster and utilised as discriminative features. \r\nAE signal frequency was found to be a good feature for discrimination. Accordingly, AE signals with the highest frequency were corresponding to fibre breakage, and AE signals with the lowest frequency were corresponding to matrix cracking, and the frequencies range in-between were corresponding to the debonding defect. \r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%% PZT + ConvNet\r\n%\\textcite{Sammons2016} utilised X-ray computed tomography for estimating the delaminations in a CFRP. For this purpose, they utilised the Convolutional Network (ConvNet ) for performing image segmentation of the defected input images to estimate the delaminations. There ConvNet was capable of identifying  and quantifying small delaminations. \r\n%Unfortunately, the ConvNet could not recognise delaminations with large sizes.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%% PZT + ConvNet\r\n%\r\n%Moreover, \\textcite{Chetwynd2008} have investigated curved carbon fibre composite panel for damage localisation. \r\n%Accordingly, stiffeners were used during the experiments to represent real-life damage. \r\n%For this purpose, authors attached a combination of PZT transducers on the panel used to generate and receive Lamb waves that propagate through the structure. \r\n%During their propagation through the structure, Lamb waves encounter defects, which affects their propagation response. \r\n%The collected response was transformed into a novel scaler index using outlier analysis~\\cite{Beniger1980}, which was then fed to MLP. \r\n%The MLP used for classification and regression applications of damage detection. \r\n%Classification operation is responsible for predicting whether there is damage or not in a specific location. \r\n%Where the regression operation is responsible for the exact estimation of the damage location.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%% Ful wavefield +ConvNets\r\nFull wavefield scanning using SLDV is a time consuming, however, by simply reducing the number of scanning points will result in low-quality images. \r\n\\textcite{esfandabadideep} proposed a compressive Sensing technique using ConvNets to enhance the resolution for images captured by SLDV while decreasing the number of measurement scan points down to \\(10\\%\\) of the number of the full gird scanning points. \r\nAlthough, the proposed technique enhanced the image resolution, however, there is a side effect, which resembles the fact when enhancing the resolution, the most affected region is the damaged area. \r\nAccordingly, the damage features will be altered.\r\nFurthermore,~\\textcite{Melville2018} proposed a technique for damage detection in thin metal plates (aluminum and steel), using full wavefield data scanned by SLDV. \r\nUsing this data to train a deep neural network of 4 hidden layers including 2 convolutional layers for features extraction and 2 fully connected layers. Their results show good results when compared with traditional machine learning SVM.\r\nMoreover,~\\textcite{Melville2017} introduced a method for detecting damage in structures based on the k-means algorithm. \r\nThe method is known as \\say{dictionary learning} which uses full wavefield data collected from thin metal plates. \r\nThe method was applied to structures with different material types and thickness, that were not used during training to prove how well the model in damage detection in various conditions. \r\nHowever, their works was not implemented for further step which is damage localization and classification.\r\n%% SECTION HEADER ////////////////////////////////////////////////////////////////////////////////\r\n\\subsection{Guided waves Based SHM through DL}\r\nThe guided waves approach is widely utilised in SHM/NDT, due to the fact it is able to detect very small damage sizes ~\\cite{Guemes2020}. \r\nDamage detection and identification approaches using guided waves are based on the measurements of the PZT sensors whether bonded or embedded into the investigated structure. \r\nIn which, PZT sensor(s) responsible for the excitation of the structure by a short ultrasonic pulse (usually, the used frequency is in the range of a hundreds of kHz) that propagates through an investigated structure such as plates or pipes as an elastic wave.\r\nThe registered signals (baseline) are stored and compared with other registered signals acquired through the lifetime of the investigated structure.\r\nDamage detection using the baseline subtraction approach for guided waves is based on subtracting damage-free registered measurements from the newly registered measurements to obtain the new changes that occurred to the structure.\r\nThese changes are considered as damage information.\r\nThe baseline approach is effective in controlled environments where the variations of the operational/environments (i.e. considerations of multiple sensing modalities, uncertainty in material properties, bounding conditions, etc ) are negligible ~\\cite{Yuan2020}.  \r\nSuch variations can alter registered data leading to false alarms.\r\nThe effect of such variations can be reduced through physics-based modeling, which can simulate an undamaged scenario (baseline) for the wave propagation through the investigated structure.\r\nThen, the simulated baseline can be used in the subtraction for damage detection.\r\nHowever, for real-world structures, it is difficult to tune the model parameter to match the experimental registered data.\r\nAccordingly, data-driven techniques based on ML and DL approaches can be the solution and deliver a robust models for many real-life variations.\r\n\r\nIn the following, several guided wave for SHM/NDT based on data-driven techniques for damage detection and localisation are presented.\r\n\\textcite{Melville1949} proposed a CNN model for the prediction of damage state in thin metal plates to overcome the issue of inaccurate representation of guided wave propagation when applying conventional approaches. \r\nThe model utilizes the full wavefield scans of thin plates (aluminum).\r\nMoreover, the acquired raw data used for training the model was divided into undamaged and damaged states equally.\r\nThe model achieved higher accuracy regarding damage  \\(99.98\\%\\) when compared to SVM that achieved \\(62\\%\\).\r\n\\textcite{Sammons2016} proposed a CNN model based on X-ray computed tomography for delamination estimation in a composite structure.\r\nFurthermore, image segmentation was applied to the input images to identify the damage.\r\nHowever, the model was only able to identify small delaminations.\r\nMoreover,~\\textcite{Chetwynd2008} presented a multi-layer perceptron (MLP) network for damage detection in curved composite panels, in which, stiffeners were added to represent the damage.\r\nThe Authors in this work investigated the propagation of Lamb waves through the panel in which they were generated and registered by a PZT array.\r\nFurthermore, for each Lamb wave response, a novelty index was obtained.\r\nThe index value is compared to some threshold value, in which if the index value exceeds the threshold it implies that there is damage in the structure.\r\nAccordingly, the MLP network was fed by obtained novelty indexes, and performed two operations: classification and regression.\r\nThe classification network was designed to define three convex regions of the panel then to determine whether the panel is damaged or not.\r\nOn the other hand, the regression network is capable of estimating the exact location of the damage.\r\nFurthermore,~\\textcite{DeFenza2015} proposed an artificial neural network (ANN) model for damage detection in plates made of aluminum alloys and composite utilising Lamb waves.\r\nResponse data of wave propagation were used to calculate damage indexes which were fed into the model as an input.\r\nAccordingly, the model performs automatic feature extraction in conjunction with the probability ellipse-based method. \r\nThe ANN model and probability ellipse (PE) method were applied to identify damage location.\r\nThe results from the ANN model and the PE presents how it is useful to apply damage indexes as a baseline for such methods in order to evaluate damage in aluminum and composite structures. \r\nEwald et al.~\\cite{Ewald2019} present a CNN model called (DeepSHM) for signal classification using Lamb waves.\r\nFurthermore, the model provides an end-to-end approach for SHM by utilising response signals captured by sensors.\r\nMoreover, response signals were preprocessed by wavelet transform to get the wavelet coefficient matrix (WCM).\r\nFurther, the CNN model was trained with the WCM to obtain neural weights.\r\n%\\textcite{Ijjeh2021} presented a fully convolutional network (FCN)  for damage identification in composite plates base on a supervised learning approach.\r\n%Furthermore, the authors utilised a full wavefield of Lamb waves propagation, which was numerically generated resembling measurements acquired by scanning laser Doppler vibrometer (SLDV).\r\n%The model performs a pixel-wise segmentation that is able to identify the delamination which results in damaged and undamaged classes.\r\n%Moreover, the model results were validated through a comparison with a conventional wavefield signal processing method i.e. adaptive wavenumber filtering~\\cite{Radzienski2019,Kudela2018}.\r\n%The proposed model achieved an accuracy of \\(93.3\\%\\) in damage detection on numerical data compared to  \\(64.8\\%\\) with the conventional method.\r\n%Furthermore, the proposed model was verified on experimental data and it proved its ability for generalisation.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\\subsection{Vibration based SHM though DL}\r\n%\\label{sec24}\r\n%The vibration-based approach for damage assessment using ML techniques has been investigated thoroughly  for several SHM applications.\r\n%Furthermore, introducing DL techniques for data-driven SHM applications has presented new scopes for investigating large scale structures and enhanced the process of data acquisition and processing of large datasets acquired by sensors of different types~\\cite{Carden2004,Sohn1996}.\r\n%Generally, the conventional approach for damage localisation requires prior knowledge of the approximate damage locations~\\cite{Xu2018,Dorafshan2016}. \r\n%Therefore, the identification process regarding candidates for the damaged locations is complex and can consume plenty of time.\r\n%Damage locations identification under the vibrational approach is based on the fact that the damage cause changes in the vibration characteristics such as modal shapes, frequencies, and damping~\\cite{Doebling1998},\r\n%which can be utilised in the identification of damaged locations from the registered data response of a structure.\r\n%A vibration-based approach can be categorised into two classes:\r\n%model-based (parametric) and non-model-based or (non-parametric).\r\n%Parametric methods require computational models and associated assumptions about the investigated structure.\r\n%In general parametric methods can achieve good accuracy, however, there is no guarantee regarding the availability of accurate information about the structural system in the real-world~\\cite{Azimi2020}. \r\n%As a result, the non-parametric methods arise due to the challenges in developing robust computational models. \r\n%With non-parametric methods, there are no prior assumptions about the structural system.\r\n%\r\n%In the following, several vibration-based for SHM using DL techniques are presented.\r\n%Authors in~\\cite{Abdeljaber2017} introduced a damage identification approach based on output-only response data.\r\n%In which, various damage cases (loose bolt) were investigated, accordingly training data were generated based on the acceleration response.\r\n%Authors in this approach have trained several CNNs separately regarding each damage case, and accordingly, the probability of damage (PoD) was determined.\r\n%By investigating scenarios of undamaged, single damage and multiple damage cases, they obtained \\(0.54\\%\\) average error for specifically identified cases.\r\n%\r\n%Authors in~\\cite{Lin2017} introduced a new approach to structural damage detection using CNN.\r\n%Moreover, the authors have developed a numerical model of simply supported Euler Bernoulli beam.\r\n%The detection model was designed to learn features and to identify damaged locations, moreover, it led to excellent results regarding the accuracy of damaged locations on the noise-free and noisy dataset.\r\n%Wang and Cha in~\\cite{Cha2018} proposed an unsupervised CNN model, that is able to extract the feature representations from the unlabelled data.\r\n%The authors in their model used raw acceleration signals (sensitive to the damage presence) that were acquired from an intact lab-scale steel bridge.\r\n%Then, the acquired response vector was normalised followed by applying the continuous wavelet transform (CWT) and fast Fourier transform (FFT).\r\n%The output was then fed into a CNN auto-encoder,\r\n%Accordingly, the extracted damage features were fed into one-class (OC) SVMs as novelty detectors corresponding to the sensors.\r\n%Consequently, the approximation of damage location (loose-bolt) was estimated based on the locations of the sensors with the highest novelty rates.\r\n%\r\n%Motivated by human vision and thinking, authors in~\\cite{Cha2018} presented a computer vision and deep-learning framework for anomaly detection.\r\n%The proposed approach consists of two steps.\r\n%In the first step, data conversion by data visualisation is carried out, in which it mimics human vision and thinking.\r\n%In data visualisation,  the registered data response of acceleration is transformed into images plotted in gray-scale. \r\n%In the second step, the training dataset is labeled manually, then fed into deep convolutional neural networks (DCNNs).\r\n%The proposed technique was tested on one-year data and achieved a global accuracy of \\(87,0\\%\\) and it could be used for real-time SHM.\r\n%Moreover, Tang et al. in~\\cite{Tang2019} presented a DL technique for data anomaly detection which can be considered as an improved technique to the previous work in~\\cite{Cha2018}.\r\n%Initially, the raw time series measured data are split into segments, and data in the time and frequency domain are visualised. \r\n%Images related to each section are stacked as a single dual-channel (red and green).\r\n%Then, the training dataset is fed into a CNN that learns how to perform data anomaly classification.\r\n%The main difference between the previous approach and this approach was in using imbalanced data in which the number of samples of different classes was unequal, however, in this approach the used data were balanced.\r\n%Finally, the comparison shows that this approach outperformed the previous one and achieved higher accuracy for all data anomaly patterns.\r\n%\r\n%Authors in~\\cite{Wu2019} presented a study of the deep CNN method in estimating the dynamic response of a linear single-degree-of-freedom (SDOF) system, a nonlinear SDOF, and a multidegree of freedom (MDOF) streel frame.\r\n%In some cases, the convolutional kernel can approximate the numerical integration operator, and the convolutional layer can be interpreted as a dominant frequency extraction operator.\r\n%Moreover, different cases of noise-contaminated signals were investigated. \r\n%Additionally, MLP method was used as a reference to the proposed CNN approach.\r\n%A comparison between the results obtained by the MLP and CNN shows that the CNN approach is more accurate and robust against noisy input data.\r\n%\r\n%Authors in ~\\cite{Oh2019}  presented a study of the CNN technique for SHM application for response estimation of tall buildings under wind excitation.\r\n%The proposed CNN model was trained on measured structural response data which take wind data measured as inputs in order to predict strains in future wind loads.\r\n%In order to measure the performance of the proposed technique, it was verified with unseen data never used at the training phase and it was able to accurately estimate the maximum and minimum strains.\r\n%Authors in~\\cite{Li2020} proposed a CNN model for damage detection of a bridge structure.\r\n%Moreover, the authors compared the performance of the CNN model with other techniques such as random forest, SVM, KNN, and decision tree, and the results showed that the accuracy was enhanced by at least \\(15\\%\\).\r\n%\r\n%Since the acceleration response signal is highly prone to noise~\\cite{Azimi2020}, researchers begin utilising other types of sensor data or use alternative features.  \r\n%Li et al. in ~\\cite{Li2020a} investigated damage in bridge structure accordingly, proposed a supervised learning technique based on the CNN model.\r\n%Dataset was acquired by deflection of a scaled-down model bridge by a fibre-optic gyroscope.\r\n%Then, the dataset was fed into a 1D-CNN model to classify three states of damage and an intact class (benchmark/damage-free).\r\n%To investigate the performance of the proposed model, a cross-validation technique was applied. \r\n%It showed that the accuracy of the CNN model increased by at least \\(15.3\\%\\) over other conventional methods such as SVM, KNN, decision trees, and random forests.\r\n%Authors in \\cite{Lopez-Pacheco2020} introduced a novel frequency-domain convolutional neural network (FDCNN) for damage detection based on Bouc-Wen hysteric model~\\cite{Ismail2009}.  \r\n%In the FDCNN method utilises only acceleration measurements for damage diagnosis, that are sensitive to environmental noise.\r\n%Moreover, FDCNN reduces the computational time during the learning process, which increase noise robustness.\r\n%The FDCNN introduced the spectral pooling operator responsible for attenuating the noise in measurements.\r\n%The proposed method was validated through comparing it with different CNN model. \r\n%The performance of the proposed method was higher regarding damage identification in building structures.\r\n%\r\n%Finally, with smart monitoring as a target, authors in~\\cite{Hung2020}  proposed a hybrid deep learning model for damage detection for SHM.\r\n%The proposed model can deal with different damage levels and accurately detect damage by combining 1D-CNN and Long-Short Term Memory (LSTM) into a single end-to-end model fed by the raw time-series, and as a result, avoiding signal preprocessing step.\r\n%Moreover, the proposed model verified that with low noise levels,  accurate damage detection can be achieved.", "meta": {"hexsha": "69d39c8d84fed1f1d4dd237f0b378f1d7f4e342b", "size": 25608, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "reports/project_reports/Ijjeh_thesis_template/Chapters/Chapter3/sect33.tex", "max_stars_repo_name": "IFFM-PAS-MISD/aidd", "max_stars_repo_head_hexsha": "9fb0ad6d5e6d94531c34778a66127e5913a3830c", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-03T05:36:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T05:36:07.000Z", "max_issues_repo_path": "reports/project_reports/Ijjeh_thesis_template/Chapters/Chapter3/sect33.tex", "max_issues_repo_name": "IFFM-PAS-MISD/aidd", "max_issues_repo_head_hexsha": "9fb0ad6d5e6d94531c34778a66127e5913a3830c", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "reports/project_reports/Ijjeh_thesis_template/Chapters/Chapter3/sect33.tex", "max_forks_repo_name": "IFFM-PAS-MISD/aidd", "max_forks_repo_head_hexsha": "9fb0ad6d5e6d94531c34778a66127e5913a3830c", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 113.8133333333, "max_line_length": 422, "alphanum_fraction": 0.7808887848, "num_tokens": 5100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3051849809932951}}
{"text": "% SciPy: Posters are commonly 36 or 42 inches tall and can be 72 inches wide.\n\\documentclass[a0paper,fleqn]{betterposter}\n\\usepackage{bm}\n\\graphicspath{{figures/}}\n\\usepackage[hidelinks]{hyperref}\n\n% Uncomment the following commands to customise the format\n\n%% Setting the width of columns\n% Left column\n\\setlength{\\leftbarwidth}{0.27\\paperwidth}\n% Right column\n\\setlength{\\rightbarwidth}{0.27\\paperwidth}\n\n%% Setting the column margins\n% Horizontal margin\n%\\setlength{\\columnmarginvertical}{0.05\\paperheight}\n% Vertical margin\n%\\setlength{\\columnmarginhorizontal}{0.05\\paperheight}\n% Horizontal margin for the main column\n%\\setlength{\\maincolumnmarginvertical}{0.15\\paperheight}\n% Vertical margin for the main column\n%\\setlength{\\maincolumnmarginhorizontal}{0.15\\paperheight}\n\n% Text font\n\\renewcommand{\\fontsizestandard}{\\fontsize{32}{46} \\selectfont}\n% Main column font\n\\renewcommand{\\fontsizemain}{\\fontsize{148.00}{280.00} \\selectfont}\n% Title font\n\\renewcommand{\\fontsizetitle}{\\fontsize{101.50}{152.00} \\selectfont}\n% Author font\n\\renewcommand{\\fontsizeauthor}{\\fontsize{33.55}{47.3} \\selectfont}\n\\newcommand{\\fontsizeinstitution}{\\fontsize{20}{25} \\selectfont}\n% Section font\n\\renewcommand{\\fontsizesection}{\\fontsize{61.00}{86.00} \\selectfont}\n\\renewcommand{\\fontsizesubsection}{\\fontsize{48.00}{57.00} \\selectfont}\n\n% Changing font sizes for a specific text segment\n% Place the text inside brackets:\n% {\\fontsize{28}{35} \\selectfont Your text goes here}\n\n%% Changing colours\n% Background of side columns\n%\\renewcommand{\\columnbackgroundcolor}{black}\n% Font of side columns\n%\\renewcommand{\\columnfontcolor}{gray}\n% Background of main column\n%\\renewcommand{\\maincolumnbackgroundcolor}{empirical}\n%\\renewcommand{\\maincolumnbackgroundcolor}{theory}\n%\\renewcommand{\\maincolumnbackgroundcolor}{methods}\n%\\renewcommand{\\maincolumnbackgroundcolor}{intervention}\n% Font of main column\n%\\renewcommand{\\maincolumnfontcolor}{gray}\n\n% Disable hyphenation\n\\hyphenpenalty=10000\n\\exhyphenpenalty=10000\n\n\\begin{document}\n\\betterposter{\n % MAIN COLUMN\n\n \\maincolumn{\n  % Main space\n\n  \\textbf{pyhf} is a \\textbf{pure Python} statistical fitting library that uses \\textbf{tensors} and \\textbf{autograd} to speed up physics analysis at the LHC\n }{\n  % Bottom space\n\n  % QR code\n  \\qrcode{qr_code.pdf}{smartphoneWhite}{\n   \\textbf{Take a picture} to\n   \\\\visit the pyhf website\\\\\n   \\href{https://diana-hep.org/pyhf}{https://diana-hep.org/pyhf}\n  }\n }\n\n}{\n % LEFT COLUMN\n\n \\title{pyhf}\n \\vspace{-1em}\n \\textbf{pure Python implementation of HistFactory}\n\n \\author{{\\href{https://www.matthewfeickert.com/}{\\underline{Matthew Feickert}$^{1}$}}, \\href{http://www.lukasheinrich.com/}{Lukas Heinrich$^{2}$}, \\href{https://giordonstark.com/}{Giordon Stark$^{3}$}, \\href{http://theoryandpractice.org/}{Kyle Cranmer$^{4}$}}\n \\institution{1 Southern Methodist University,~~~2 CERN,~~~3 University of California Santa Cruz,~~~4 New York University}\n %\n \\section{HistFactory}\n One of the most widely used statistical models in \\textbf{high energy physics} for binned measurements and searches\n\n \\begin{center}\n  \\includegraphics[width=\\textwidth]{HistFactory_result_examples.png}\n \\end{center}\n %\n \\vspace{-0.5em}\n \\begin{minipage}{0.29\\textwidth}\n  \\begin{center}\n   \\textbf{Standard Model}\n  \\end{center}\n \\end{minipage}%\n \\quad\n \\begin{minipage}{0.36\\textwidth}\n  \\begin{center}\n   \\textbf{Supersymmetry}\n  \\end{center}\n \\end{minipage}%\n \\quad\n \\begin{minipage}{0.27\\textwidth}\n  \\begin{center}\n   \\textbf{Exotic Physics}\n  \\end{center}\n \\end{minipage}%\n %\n \\vspace{2em}\n %\n\n \\textbf{Declarative binned likelihoods}\n \\vspace{1em}\n \\[\n  f(\\bm{n}, \\bm{a} \\,|\\,\\bm{\\phi},\\bm{\\chi}) = \\underbrace{\\color{blue}{\\prod_{c\\in\\mathrm{\\,channels}} \\prod_{b \\in \\mathrm{\\,bins}_c}\\textrm{Pois}\\left(n_{cb} \\,\\middle|\\, \\nu_{cb}\\left(\\bm{\\eta},\\bm{\\chi}\\right)\\right)}}_{\\substack{\\text{Simultaneous measurement}\\\\%\n    \\text{of multiple channels}}} \\underbrace{\\color{red}{\\prod_{\\chi \\in \\bm{\\chi}} c_{\\chi}(a_{\\chi} |\\, \\chi)}}_{\\substack{\\text{constraint terms}\\\\%\n    \\text{for }\\text{``auxiliary measurements''}}}\n \\]\n %}\n \\vspace{1em}\n\n \\textcolor{blue}{Primary Measurement}:\n \\begin{itemize}\n  \\item Multiple disjoint ``channels'' (e.g. event observables) each with multiple bins of data\n  \\item Example parameter of interest: strength of physics signal, $\\mu$\n \\end{itemize}\n \\textcolor{red}{Auxiliary Measurements}:\n \\begin{itemize}\n  \\item Nuisance parameters (e.g. in-situ measurements of background samples)\n  \\item Systematic uncertainties (e.g. normalization, shape, luminosity)\n \\end{itemize}\n\n \\vfill\n \\section{Performance}\n Efficient use of tensor computation makes pyhf fast\n \\begin{center}\n  \\includegraphics[width=\\textwidth]{performance_only.pdf}\n \\end{center}\n Competitive with traditional \\texttt{C++} implementation --- often faster\n % \\vspace{-1em}\n %\n \\vfill\n \\subsection{Hardware Acceleration}\n For ML-library tensor backends the computational graph can be transparently placed on hardware accelerators: \\textbf{GPUs} and \\textbf{TPUs} for order of magnitude speed-up in computation\n \\begin{center}\n  \\includegraphics[width=\\textwidth]{scaling_hardware.pdf}\n \\end{center}\n}{\n % RIGHT COLUMN\n\n \\subsection{Implementation}\n \\begin{center}\n  \\includegraphics[width=0.9\\textwidth]{computational_graph3.pdf}\n \\end{center}\n The computational graph of multidimensional array operations for likelihood function of a physics analysis defined through HistFactory\n\n %\n \\vspace{0.5em}\n %\n \\begin{minipage}{0.33\\textwidth}\n  \\begin{center}\n   \\includegraphics[width=\\textwidth]{NumPy_logo.pdf}\n  \\end{center}\n \\end{minipage}%\n \\quad\n \\begin{minipage}{0.33\\textwidth}\n  \\begin{center}\n   \\includegraphics[width=\\textwidth]{TensorFlow_logo.pdf}\n  \\end{center}\n \\end{minipage}%\n \\quad\n \\begin{minipage}{0.33\\textwidth}\n  \\begin{center}\n   \\includegraphics[width=0.85\\textwidth]{Pytorch_logo.pdf}\n  \\end{center}\n \\end{minipage}%\n %\n \\vspace{0.5em}\n %\n\n Use of $n$-dimensional array (``tensor'') operations through a common API layer around high performance tensor libraries\n\n \\vspace{-1em}\n \\subsection{JSON Specification}\n The full likelihood can be expressed as a \\textbf{single JSON document}\\\\\n Archive friendly for analysis presentation\n \\vspace{0.5em}\n \\begin{center}\n  \\includegraphics[width=0.9\\textwidth]{carbon_JSON_spec.png}\n \\end{center}\n \\vspace{-1em}\n \\begin{center}\n  {\\fontsizeinstitution\\textbf{Example:} 2 binned single channel with 2 samples with 1 parameter of interest and 1 nuisance parameter}\n \\end{center}\n \\begin{center}\n  \\includegraphics[width=0.9\\textwidth]{carbon_pyhf_CLs.png}\n \\end{center}\n\n \\vspace{1em}\n \\vfill\n \\begin{minipage}{0.58\\textwidth}\n  \\begin{center}\n   \\href{http://iris-hep.org/}{\\includegraphics[width=\\textwidth]{IRIS-HEP_logo}}\n  \\end{center}\n \\end{minipage}%\n \\quad\n \\begin{minipage}{0.38\\textwidth}\n  \\begin{center}\n   \\href{https://pypi.org/project/pyhf/}{\\includegraphics[width=\\textwidth]{pyhf_PyPI.pdf}}\n  \\end{center}\n  \\vspace{1em}\n  \\begin{center}\n   \\href{https://doi.org/10.5281/zenodo.1169739}{\\includegraphics[width=\\textwidth]{zenodo_doi.pdf}}\n  \\end{center}\n  \\vspace{3em}\n \\end{minipage}%\n}\n\\end{document}\n", "meta": {"hexsha": "0aa8c289aac4efc63f3bdb942ccad11ffd660285", "size": 7150, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "poster.tex", "max_stars_repo_name": "matthewfeickert/SciPy2019-Poster", "max_stars_repo_head_hexsha": "84f1f0ba4b0156417372f097810c3614a168e1c7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-07-09T07:13:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-16T20:13:30.000Z", "max_issues_repo_path": "poster.tex", "max_issues_repo_name": "matthewfeickert/SciPy2019-Poster", "max_issues_repo_head_hexsha": "84f1f0ba4b0156417372f097810c3614a168e1c7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-07-09T05:18:25.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-09T05:18:25.000Z", "max_forks_repo_path": "poster.tex", "max_forks_repo_name": "matthewfeickert/SciPy2019-Poster", "max_forks_repo_head_hexsha": "84f1f0ba4b0156417372f097810c3614a168e1c7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-11T11:13:51.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-11T11:13:51.000Z", "avg_line_length": 31.9196428571, "max_line_length": 269, "alphanum_fraction": 0.7394405594, "num_tokens": 2168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.305184973029092}}
{"text": "\\section{Previous work}\n\nControlling the spread of infections is by no means a new problem, and many models have previously been used to describe the distribution and spread of epidemic diseases.\n\nThe models previous scientists used can mainly be divided into three categories. Brief overviews of the three by the sequence of their advent are as follows.\n\\begin{enumerate}\n\t\\item \\textbf{\\emph{Standard SIR(susceptible-infected-removed) models and its deriveratives:}}The model is first put forward by \\textbf{Kemraek} and \\textbf{MeKendriek} in 1927\\cite{SIR}and is the most classic model. Many successive models are based on it. It regards the epidemic area as a whole and divides people into different groups, such as susceptible group, infected group and removed group. It depends on differential equations to describe the relationship between volumes of different groups, thus making scientific and quantitative description. Details of the model will be explained in the successive sections.\n\t      \\par Many other models are derived from this very basic SIR model, such as SIS model\\cite{SIS} which deals with situations where a infected and later recovered individual can turn back to be a susceptible individual, and SEIR model\\cite{SEIR} which deals with the situations where incubation period of the epidemic disease is not negligible. Previous scientists gained great achievements by using SIR model - they simulated the trends of epidemic diseases, calculated the rough volume of each group in different periods of epidemics and, most importantly, successfully analyse the contribution of different parameters to stability of system.\n\t      \\par Despite the fundamental and important standing of SIR model, its drawbacks are easy to realize. It is difficult to study geographic characters of the spread of diseases, because the model doesn't contain any geographic information. Also, each person in the system is not individually recognized and the complex relationships among individuals are hardly considered, since it regards the epidemic area as a homogeneous system - in another word, each person in the system is just like a molecule in a cup of water and the relationships of any two pairs are identical. Additionally, it is a deterministic model witch hardly resemble the factual system in which many fortuitous factors matter.\n\t\\item \\textbf{\\emph{Statistical model:}}This model is less intensely studied than the other two models. In this model, researchers mainly use possible functions whose forms are known but parameters unknown to fit the currently available data, aiming at predicting the trend of epidemics. Although the model is somewhat phenomenological and catch little intrinsic logic, it is quite useful in real practice and it allows us to have a quick view of the trend without getting convoluted into the depth of the problem. Anyhow, we will not go further into this kind of models.\n\t\\item \\textbf{\\emph{Spatial simulation model:}}This category of models are the focus recently. They mainly contains models using cellular automaton (CA), models considering networks among people(eg. small world network), models using GIS\\cite{GIS}, etc. Take models using CA as an example. We define different types of points, which are put in lattices of a plane, and regard the spread of diseases between people as the interaction between nearby points. The process of evolution and spatial distribution of virus can be simulated with the aid of computer program. Clearly, due to the consideration of individuals separately, the results are more accurate than previous two categories.\n\n\t      This category of models taking the relationship among people and geographic information into account has advantages over others when figuring out the geographic characters of the spread. Moreover, it can give more accurate results since its high resemblance of real situation. Accurate as the models are, they are highly complicated and some of them are difficult to apply both for the complexity of programming and great amount of computation.\n\\end{enumerate}", "meta": {"hexsha": "d51be8b87605534468eb15952de73a604843aada", "size": 4077, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "PreviousWork.tex", "max_stars_repo_name": "EveryBreathYouTake/MCM-", "max_stars_repo_head_hexsha": "77fe13c466e6f6fd7e0c38908eb9bd220c7872e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PreviousWork.tex", "max_issues_repo_name": "EveryBreathYouTake/MCM-", "max_issues_repo_head_hexsha": "77fe13c466e6f6fd7e0c38908eb9bd220c7872e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PreviousWork.tex", "max_forks_repo_name": "EveryBreathYouTake/MCM-", "max_forks_repo_head_hexsha": "77fe13c466e6f6fd7e0c38908eb9bd220c7872e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-26T03:53:40.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-26T03:53:40.000Z", "avg_line_length": 291.2142857143, "max_line_length": 701, "alphanum_fraction": 0.8145695364, "num_tokens": 798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.30518497267777606}}
{"text": "\\section{Inversion properties}\r\nAn inversion is a template class of the underlying data vector Vec and the matrix type Mat.\r\nIt is initialised with one of the following constructors:\r\n\\begin{lstlisting}\r\n//! very simple and empty inversion\r\nInversion( bool verbose = false, bool dosave = false ) \r\n//! Usual inversion constructor with data and FOP\r\nInversion( Vec data, ModellingBase & forward, bool verbose, dosave)\r\n//! Complete constructor including transformations\r\nInversion( Vec data, ModellingBase & forward, \r\n    Trans & transData, Trans & transModel, bool verbose, bool dosave )\r\n\\end{lstlisting}\r\nThe properties are not visible itself, instead there are setter and getter functions. Setters:\r\n\\begin{lstlisting}\r\nsetRelativeError( double/Vec error);  //! set relative data error\r\nsetAbsoluteError( double/Vec error);  //! set absolute data error\r\nsetForwardOperator( ModellingBase & forward ); //! set forward operator\r\nsetTrans( transData, transModel );   //! set transformations\r\nsetTransData( transData );           //! set data transformation\r\nsetTransModel( transModel );         //! set model transformation\r\nsetLineSearch( bool isLinesearch );  //! switch line search on/off\r\nsetRobustData( bool isRobust );      //! IRLS (robust) data weighting\r\nsetBlockyModel( bool isBlocky );     //! IRLS (blocky) model constraints\r\nsetLambda( double lambda );          //! regularisation strength\r\nsetOptimizeLambda( bool optLambda ); //! L-curve optimization\r\nsetMaxIter( int maxIter );           //! define maximum iteration number\r\nsetModel( Vec model );               //! set model vector\r\nsetModelRef( Vec referenceModel );   //! set reference model vector\r\nsetCWeight( Vec cWeight );           //! set constraint control vector\r\nsetMWeight( mWeight );               //! set model control vector\r\n\\end{lstlisting}\r\nGetter%Vec error();\r\n\\begin{lstlisting}\r\nModellingBase & forwardOperator();     //! forward operator\r\nuint boundaryCount(), modelCount(), dataCount();//! # boundaries/cells/data\r\nbool lineSearch(), blockyModel(), robustData(), optimizeLambda();//!options\r\ndouble getLambda();                   //! regularisation strength\r\nint maxIter();                        //! maximum iteration number\r\nVec model(), response(), roughness(); //! model/response/roughness vector\r\nVec cWeight(), mWeight();             //! constraint/model control vector\r\ngetPhiD(), getPhiM(), getPhi(), getChi2(); //! objective function parts\r\n\\end{lstlisting}\r\nRun inversion and other actions\r\n\\begin{lstlisting}\r\nVec model = run();               //! runs the whole inversion\r\nVec model = oneStep();           //! runs one inversion step\r\nVec model = runChi1();           //! runs changing lambda such that chi^2=1\r\nrobustWeighting();               //! applies robust data weighting\r\nconstrainBlocky();               //! apply blocky model contraints\r\nechoStatus();                    //! echo chi2/phi/phiD/phiM/iteration\r\nVec modelCellResolution( iRes ); //! compute a column of resolution matrix\r\n\\end{lstlisting}\r\n\r\n\\clearpage\r\n\\section{Mesh types and mesh generation}\\label{app:meshes}\r\nThere are different mesh types and ways how to generate them. There is only one base mesh class holding the nodes/vertices/coordinates, cells (defined by the bounding vertices) and boundaries revealing the neighboured cells.\r\nEvery node, cell and boundary has a marker that defines the behaviour in modelling (e.g. an electrode node or boundary conditions) or inversion (e.g. the region number or a known sharp boundary).\r\n\r\n\\subsection*{0d mesh}\r\nZero dimension means that there are several parameters without any neighbouring relation.\r\nConsequently 0th order constraints are used.\r\nThere is no special mesh generator, instead a 1d mesh is created and the constraint type is set to zero.\r\nAlternatively, the forward operator is initialised without mesh and the parameter number is set by setParameterCount.\r\n\\subsection*{1d mesh}\r\nA real 1d mesh subdivides the subsurface in vertically or horizontally aligned elements and can be created by the following functions:\r\n\\begin{lstlisting}\r\n/*! Generate 1d mesh with nCells cells (size 1) and nCells+1 nodes */\r\nMesh createMesh1D( uint nCells, uint nClones = 1 );\r\n/*! Generate simple one dimensional mesh with nodes in RVector pos */\r\nMesh createMesh1D( const RVector & x );\r\n\\end{lstlisting}\r\nnClones can be used to create models for different parameters such as resistivity and phase.\r\nResult is one mesh with two sub-meshes that are individual regions.\r\nSee section~\\ref{sec:dc1dsmooth} for an example.\r\n\r\n\\subsection*{1d block model}\r\nA 1d block model consists of (nLayers-1) thicknesses and nLayers values for a number of properties.\r\nThe thicknesses and properties are individual 1d meshes.\r\n\\begin{lstlisting}\r\n/*! Generate 1D block model of thicknesses and properties */\r\nMesh createMesh1DBlock( uint nLayers, uint nProperties = 1 );\r\n\\end{lstlisting}\r\nSee section~\\ref{sec:dc1dblock} for a resistivity block inversion or \\ref{sec:blockjoint} for joint block inversion using two properties.\r\n\r\n\\subsection*{2d regular mesh}\r\nA regular (FD like) 2d model consists of regularly spaced rectangles.\r\nThey can be created by the number of elements in x- or y-direction or vectors of the enclosing nodes:\r\n\\begin{lstlisting}\r\n/*! Generate simple 2d mesh with xDim*yDim cells of size 1 */\r\nMesh createMesh2D( uint xDim, uint yDim );\r\n/*! Generate simple 2d mesh from node vectors x and y */\r\nMesh createMesh2D( const RVector & x, const RVector & y );\r\n\\end{lstlisting}\r\n\r\n\\subsection*{2d general mesh}\r\nGenerally a 2d mesh - a regular one is just a special case - can consist of triangles or quadrangles (deformed rectangles) or a mix of it. \r\nThey are created by mesh generators such as triangle \\citep{triangle}.\r\nInput for the mesh is a piece-wise linear complex (PLC) comprising nodes edges and region markers.\r\nMeshing is done externally and loaded using \\lstinline|Mesh.load(filename);|.\r\n\r\n\\subsection*{3d regular mesh}\r\nA regular (FD like) 3d model consists of regularly spaced hexahedra.\r\nThey can be created by the number of elements in x/y/z-direction or vectors of the enclosing nodes:\r\n\\begin{lstlisting}\r\n/*! Generate regular 3d mesh with xDim*yDim*zDim cells of size 1 */\r\nMesh createMesh3D( uint xDim, uint yDim, uint zDim );\r\n/*! Generate regular 3d mesh from node vectors x, y and z */\r\nMesh createMesh3D( const RVector & x, & y, & z );\r\n\\end{lstlisting}\r\n\r\n\\subsection*{3d general mesh}\r\nAt the moment, a 3d mesh can consist of tetrahedrons or hexahedrons, but prisms or pyramids could be easily implemented.\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\clearpage\r\n\\section{Region properties and region map file}\\label{app:regions}\r\nSome properties can be set for each region individually using \\lstinline|f.region(i).|\r\n\\begin{lstlisting}\r\nsetMarker( int marker );\r\nsetBackground( bool background );\r\nsetSingle( bool single );\r\nsetStartVector( const RVector & start );\r\nsetStartValue( double start );\r\nsetModelControl( double mc );\r\nsetModelControl( const RVector & mc );\r\nsetBoundaryControl( double or RVector bc );\r\n%setZPower( double zpower );\r\nsetZWeight( double zweight );\r\nsetTransModel( Trans & tM );\r\nsetConstraintType( uint type );\r\nsetLowerBound( double lb );\r\nsetUpperBound( double ub );\r\n\\end{lstlisting}\r\n\r\n\\begin{lstlisting}\r\nuint parameterCount(), boundaryCount(); //! parameters/boundaries\r\n\\end{lstlisting}\r\n\r\nThe region manager controls the individual regions.\r\nIt is initialised from the forward operator and interprets the mesh with its markers\r\n\\begin{lstlisting}\r\nsetMesh( const Mesh & mesh );\r\nRegion * createRegion( int marker, const Mesh & mesh ); //! create region\r\nRegion * region( int marker ); //! get an individual region by marker\r\nuint parameterCount(), constraintCount(), boundaryCount(); //! counters\r\nRVector createStartVector();  //! create starting model vector\r\nRVector createModelControl(), createBoundaryControl(); //! create vectors\r\nRVector createFlatWeight( double zPower, double minZWeight ); //! zpower\r\nloadMap( const std::string & fname ); //! set region properties from file\r\n\\end{lstlisting}\r\n\r\nThe latter region map file simplifies the setting of region properties and is comfortable for testing different values.\r\nIt is a column file with the description of the columns in the first row after a \\# sign:\r\n\\begin{verbatim}\r\n#No start Ctype MC  zWeight Trans lBound uBound\r\n0   100   1     1   0.2  \t  log   50     1000\r\n1   30    0     0.2 1       log   10     200\r\n\\end{verbatim}\r\nThe example represents a two layer case, e.g. an unsaturated (0) and a saturated (1) zone with different starting resistivities.\r\nSmoothness constraints with enhanced layering is applied in the first and minimum length in the latter.\r\nBoth use a log/logLU transformation with specific upper and lower bounds.\r\n\r\nInstead of the number, an asterisk (*) can be used to set properties for all regions.\r\nIn one region file, several blocks as above can be stated, e.g.\r\n\\begin{verbatim}\r\n#No start Trans\r\n*   100   log\r\n#No lBound uBound\r\n1   20     300\r\n2   50     1000\r\n\\end{verbatim}\r\ndefines an equal model transformation and starting value, but different lower and upper bounds.\r\n\r\nThere are two special types of regions: background and single regions.\r\nThe background region is not part of the inversion, the values are prolongated (filled up) for the forward run.\r\nOn the contrary, the cells of a single region are held constant and treated as one parameter in inversion.\r\nThey are specified as above using the keywords \\verb|background| and \\verb|single|, e.g.\r\n\\begin{verbatim}\r\n#No single\r\n*\t1\r\n#No background\r\n0\t1 \r\n\\end{verbatim}\r\ndefines all regions as single parameter regions except number zero, which is background.\r\n\r\nBy default, regions are decoupled from each other, i.e. there are no smoothness contraints at the boundary.\r\nHowever, it might be useful to have those, e.g. by constraining a region of known parameters by borehole data to the neighboring cells or just to stabilize inversion.\r\nIn this case, inter-region constraints can be defined in the region file. \r\nThe text\r\n\\begin{verbatim}\r\n#Inter-region\r\n* \t*\t  0.1\r\n1   2   1\r\n\\end{verbatim}\r\nsets weak connection between all regions, except regions 1 and 2 are normally connected.\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\clearpage\r\n\\section{Transformation functions}\\label{app:trans}\r\nFor data and model parameter arbitrary transformations can be applied.\r\nA transformation is a C++ class derived from a base class (the identity transformation), which mainly consists of four functions, each returning a vector for a given vector:\r\n\\begin{description}\r\n\\item[trans] the forward transformation function: $y(x)$\r\n\\item[invTrans] the inverse of the function: $x(y)$\r\n\\item[deriv] the derivative of the function: $y'(x)$\r\n\\item[error] the transformation of associated errors $\\delta y(\\delta x)$\r\n\\end{description}\r\nThe latter is defined in the base class.\r\nThe inversion as mathematical operation is done in the $y$ domain, whereas the physics is described in the $x$ domain.\r\n\r\nBesides the presented transformations, you can define your own transformations by deriving from the base class and overwriting the first three functions.\r\nIf the inverse transformation is not known analytically, there is a class \\textbf{TransNewton}, in which the inverse function is obtained by Newton iteration.\r\n\r\nHowever, there are a lot of already existing transformation classes that can be used or combined:\r\n\r\n\\subsection*{Basic transforms}\r\n\\begin{description}\r\n\\item[TransLinear](a,b): $y(x)=a*x+b$\r\n\\item[TransPower]($n$): $y(x)=x^n$\r\n\\item[TransExp]($x_0$,$y_0$): $y(x)=y_0\\cdot e^{-x/x_0}$\r\n\\item[TransInv]: $y(x)=1/x$ (specialisation of TransPower)\r\n\\item[TransLog]: $y(x)=\\log(x)$\r\n\\end{description}\r\n\r\n\\subsection*{Range transforms}\r\nThe logarithm restricts $x$ to be positive, i.e. sets a lower bound 0.\r\nInstead of 0, a lower bound $x_l$ can be set.\r\nBy combining two logarithmic functions a lower and an upper bound can be combined.\r\nSimilar can be obtained by a cotangens function.\r\n\r\n\\begin{description}\r\n\\item[TransLog]($x_l$): $y(x)=\\log(x-x_l)$\r\n\\item[TransLogLU]($x_l$,$x_u$): $y(x)=\\log(x-x_l)-\\log(x_u-x)$\r\n\\item[TransCotLU]($x_l$,$x_u$): $y(x)=-\\cot((x-x_l)/(x_u-x)\\cdot\\pi)$\r\n\\end{description}\r\n\r\n\\subsection*{Combination}\r\nDifferent transformations can be combined by either\\\\\r\n\\textbf{TransNest}($y^1$,$y^2$): $y(x)=y^1(y^2(x))$\\\\\r\n\\textbf{TransAdd}($y^1$,$y^2$): $y(x)=y^1(x)+y^2(x)$\\\\\r\nSince for the latter the inverse cannot be combined by the two inverses, it is derived from \\lstinline|transNewton|, a base class whose inverse is achieved by a Newton iteration.\r\nSo any not-so-easily-invertible function can be derived from \\lstinline|transNewton| and does not require to define \\lstinline|invTrans|.\r\n\r\nThere is a cumulative transformation \\lstinline|CumulativeTrans|, which applies a vector of transformations for different part of the model.\r\nThis meta-transformation is applied in the region technique but can also be defined for one region.\r\nMore often it is used to combine different data or model types, see sections \\ref{sec:mt1d}, \\ref{sec:ttoffset} and \\ref{sec:jointdcem} for examples.\r\n\r\n\\subsection*{Special transformations}\r\nSome geophysically relevant transformations have been already defined:\r\n\\begin{description}\r\n\\item[TransLogMult]($y_0$) is a \\textbf{TransNest} of \\textbf{TransLog} and \\textbf{TransMult}: $y(x)=y_0\\log(x_0)$, e.g. for using the logarithm of the apparent resistivity ($\\rho^a=G R$)\r\n\\item[TransCRIM]($\\phi$,$\\epsilon_m$,$\\epsilon_w$): the complex refractive index model (CRIM) - derived from \\textbf{TransLinear}\r\n\\item[TransArchie]($\\rho_w$) - Archie's equation, derived from \\textbf{TransPower}\r\n\\end{description}\r\n\r\nNote that there are predefined types based on real (double) vectors beginning with an R, e.g. \\lstinline|RTransLogLU| is actually \\lstinline|TransLogLU< RVector >|.\r\n\r\n\r\n\\section{Vectors and Matrix types}\\label{app:matrix}\r\n\\sperre\r\n\r\n\\lstinline|std::vector|\r\n\r\n\\lstinline|template< class ValueType > class Vector|\r\n\r\n\\lstinline|RVector|,\\lstinline|FVector|, \\lstinline|BVector|,\\lstinline|IVector|\r\n\r\n\\lstinline|load/save|\r\n\r\ncomplex values using Complex = \\lstinline|std::complex<double>| as a vector \\lstinline|CVector|\r\n\r\n\\lstinline|template < class ValueType > class Matrix|\r\n\r\n\\lstinline|RMatrix|, \\lstinline|FMatrix|\r\n\r\n\\lstinline|load/saveMatrixCol|\r\n\r\n\\lstinline|template< class ValueType, class IndexType > class SparseMapMatrix|\r\n\r\n\\lstinline|RSparseMapMatrix| for double and unsigned int\r\n\r\nmodelling column-compressed sparse matrix \\lstinline|SparseMatrix|\r\n\r\n\\subsection{Block-Matrices}\r\nLarge matrices for Jacobian (J) and constraint matrix (C)\r\n\r\nholding individual matrices by stacking matrices saves space and makes allocation easier\r\n\r\nHorizontal stacking (H types): individual models (or model parts)\r\n\r\nVertical stacking (V types): individual data (J) or constraints (C)\r\n\r\n2 matrices (2) of arbitrary type, N matrices (N) of identical type, repetition (R) of identical matrices\r\n\r\n\\lstinline|H2Matrix< Matrix1, Matrix2 >|\r\nexample: 2 data sets for 1 model\r\n\r\n\\lstinline|V2Matrix< Matrix1, Matrix2 >| example: 1 model, 2 data sets\r\n\r\n\\lstinline|D2Matrix< Matrix1, Matrix2 >| example: 2 models, 2 data sets\r\n\r\n\\lstinline|HNMatrix< Matrix >| example: LCI \r\n\r\n\\lstinline|VNMatrix< Matrix >| (N vertical identical matrices)\r\n\r\n\\lstinline|DNMatrix< Matrix >| (diagonal matrices, Block-Jacobi)\r\nexample: LCI (identical models with individual Jacobians)\r\n\r\n\\lstinline|DRMatrix< Matrix >| (\r\nexample: ", "meta": {"hexsha": "5cb28496595950ff9aa9b553b08d3efcdcaf649b", "size": 15610, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/tutorial/appendix.tex", "max_stars_repo_name": "mjziebarth/gimli", "max_stars_repo_head_hexsha": "196ac4d6dd67e0326cccc44a87b367f64051e490", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-07-10T00:56:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T12:43:38.000Z", "max_issues_repo_path": "doc/tutorial/appendix.tex", "max_issues_repo_name": "ivek1312/gimli", "max_issues_repo_head_hexsha": "5fafebb7c96dd0e04e2616df402fa27a01609d63", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/tutorial/appendix.tex", "max_forks_repo_name": "ivek1312/gimli", "max_forks_repo_head_hexsha": "5fafebb7c96dd0e04e2616df402fa27a01609d63", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-29T04:28:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T04:28:40.000Z", "avg_line_length": 50.3548387097, "max_line_length": 225, "alphanum_fraction": 0.7322869955, "num_tokens": 3844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878696277514, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3051412967047409}}
{"text": "\\section{Our Construction}\\label{sec:construction}\n\n\n\n\\subsection{Overview}\nFirst we describe our join algorithm without any privacy and then we will discuss how this translates to the secret shared setting. As depicted in \\figureref{fig:mapping}, the algorithm can be broken into the following phases:\n\\begin{enumerate}\n\t\\item \\label{step:overview1}  $Y$ is inserted into a cuckoo hash table $\\ytable$ based on the join-key(s). That is, let us assume the columns $Y_1$ and $X_1$ are the join keys. Then \n\trow $Y[i]$ is inserted at $\\ytable[j]$ for some $j\\in \\{h_0(Y_1[i]), h_1(Y_1[i])\\}$.\n\t\\item \\label{step:overview2} Each row $X[i]$ will need to be compared with the rows $\\ytable[j]$ for $j\\in \\{h_0(X_1[i]), h_1(X_1[i])\\}$. This will be achieved by mapping $\\ytable[h_0(X_1[i])]$ to a new row $\\widehat{Y}^0[i]$ and $\\ytable[h_1(X_1[i])$ to $\\widehat{Y}^1[i]$. \n\t\\item \\label{step:overview3} It is now the case that if row $X[i]$ has a machining key in $Y$, the this row will be located at $\\widehat{Y}^0[i]$ or $\\widehat{Y}^1[i]$. As such, these rows can directly be compared to determine if there is a match on the join keys and the where clause evaluates to true. Let $b_i=1$ if there is such a match and $0$ otherwise.\n\t\\item \\label{step:overview4} Various types of joins can then be constructed from locally comparing row $i$ from these tables, i.e. $X[i],\\widehat{Y}^0[i], \\widehat{Y}^1[i]$. For example, an inner join is constructed from all the rows where $b_i=1$ by selecting the values from $X[i]$ and either $\\widehat{Y}^0[i]$ or $\\widehat{Y}^1[i]$ depending on which one matches. If there is no match, then that output row is set to \\Null.\n\\end{enumerate} \n\nThe main challenge in bringing the described algorithm to the secret shared setting is constructing the cuckoo hash table $\\ytable$ and selecting rows from $\\ytable$ without leaking sensitive information. We achieve this with the use an MPC friendly \\emph{randomized encoding} and a new three-party protocol called an \\emph{oblivious switching network}.\n\n%Our core protocol is a technique for obliviously mapping together rows with equal join-keys. For the $i$th secret shared row $\\share{X}[i]$ and for some $j_0,j_1$, our protocol obliviously maps rows $\\share{Y[j_0]},\\share{Y[j_1]}$ to the $i$th row of two new tables $\\share{\\widehat{Y}^0},\\share{\\widehat{Y}^1}$ such that if $Y$ contains a row with matching keys then either $\\share{\\widehat{Y}^0}[i]$ or $\\share{\\widehat{Y}^1}[i]$ will be this row. If no such key exists in $Y$ then an arbitrary rows from $Y$ are mapped to these locations. Once the mapping is performed the final output table can be constructed by an MPC protocol\\cite{aby3} that directly compares the keys for the row of $\\share{X}[i]$ with $\\share{\\widehat{Y}^0}[i]$ and $\\share{\\widehat{Y}^1}[i]$. If the keys match then the output row is constructed and otherwise a dummy \\Null row is constructed. \n\nLet us continue to assume that the columns $X_1$ and $Y_1$ are the join-keys. Our protocol begins by generating a \\emph{randomized encoding} for each of the secret shared join-key $\\share{x_i}\\in \\share{X_1}$ and $ \\share{y_i}\\in \\share{Y_1}$. \\figureref{fig:randomized-encode-ideal} contains the ideal functionality for this encoding which takes secret shares from the parties, apply a PRF $F_k$ to the reconstructed value using a internally sampled key $k$, and returns the resulting value to one of the three parties. For $\\share{ x_i}:= \\share{X_1}[i]$, \\Party{0} will learn $F_k(x_i)$ while \\Party{1} will learn $F_k(y_i)$ for $\\share{ y_i}:=\\share{Y_1}[i]$. Since the join-keys $x_i$ (resp. $y_i$) are unique and $k$ is not known, this reveals no information to \\Party{0} (resp. \\Party{1}).\n\nParty \\Party{1} proceeds by constructing a \\emph{secret shared} cuckoo hash table $\\shareTwo{\\ytable}$ from the rows of $\\share{Y}$ where the hash function values for row $i$ are defined as $h_j(y_i) = H( j || F_k(y_i))$. Note that \\Party{1} knows only the randomized encodings $F_k(y_i)$ of each row $Y[i]$, and not the contents of the row itself. The goal in this step is to construct a secret shared cuckoo table $\\shareTwo{\\ytable}$ such that row $Y[i]$ is located at $\\ytable[h_j(y_i)]$ for some $j$. We construct  $\\shareTwo{\\ytable}$ using a three-party \\emph{oblivious permutation protocol} where \\Party{1} inputs a permutation $\\pi$, all parties input secret shares of $Y$, and the result is secret shares of ``$Y$ permuted according to $\\pi$'' which forms $\\ytable$ (details follow later). This completes \\stepref{step:overview1} and is the first transformation shown in \\figureref{fig:mapping}.\n\nIt is now the case that $\\shareTwo{\\ytable}$ is a valid cuckoo hash table of $\\share Y$ which is secret shared between \\Party{0} and \\Party{1}. Party \\Party{0}, who knows the randomized encodings $F_k(x_i)$ for all $\\share{ x_i}:= \\share{X_1}[i]$, now must compare the rows of $\\shareTwo{\\ytable}$ indexed by $h_j(x_i)= H( j || F_k(x_i))$ with the row $\\share X[i]$. In particular, assuming we use two cuckoo hash functions, then \\Party{0} constructs two \\emph{oblivious switching networks} that maps the shares $\\shareTwo{\\ytable[{h_0(x_i)}]}$ and $\\shareTwo{\\ytable[{h_1(x_i)}]}$ to be ``aligned\" with $\\share X[i]$. Exactly how such a network operates is discussed later but the result is two new tables $\\shareTwo{\\widehat{Y}^0},\\shareTwo{\\widehat{Y}^1}$ such that $\\ytable[{h_j(x_i)}]=\\widehat{Y}^j[i]$. This completes \\stepref{step:overview2} and is the second transformation shown in \\figureref{fig:mapping}.\n\nOnce the shares of $\\widehat{Y}^0[i]={\\ytable[{h_0(x_i)}]}, Y_1'[i]={\\ytable[{h_1(x_i)}]}$ are obtained using the switching network, the parties employ an MPC protocol to directly compare these rows with $\\share{X}[i]$. That is, they compute a bit $\\share{b}$ which equals one if the join-keys are equal and the \\texttt{where} clause $P(\\shareTwo{\\widehat{Y}^j}[i],\\share{X}[i])$ outputs one for some $j$. For each row, the output row for an inner join is constructed as $S(\\shareTwo{\\widehat{Y}^j}[i],\\share{X}[i])$ using MPC where $S$ is the user defined selection circuit. In addition, the MPC circuit outputs the secret shared flag $\\share{b}$ indicating whether this row is set to \\texttt{NULL}. \n\nLeft joins work in a similar way except that all rows of $X$ are output and marked not \\texttt{NULL}. Finally, unions can be computed by including all of $Y$ in the output and all of the rows of $X$ where the comparison bit $\\share{b}$ is zero. Regardless of the type of join, the protocols do not reveal any information about the tables. In particular, not even the cardinality of the join is revealed due to the use of \\texttt{NULL} rows.\n\n\\begin{figure}\\centering\n\t\\frame{\t\\begin{tikzpicture}[scale=0.48, every node/.style={scale=0.48}]\n\t\t\\draw (0, 0) node[inner sep=0] {{\\includegraphics[trim={0cm 7cm 14cm 1cm},clip,width=\\textwidth]{diga.pdf}}};\n\t\t\\draw (-7.9cm,4cm) node {\\large$\\share{Y}$};\n\t\t\\draw (7.2cm,4cm) node {\\large$X$};\n\t\t\\draw (-3.7cm,4cm) node {\\large$\\ytable=\\textsf{Cuckoo}(Y)$};\n\t\t%\t\\draw (3.8cm,4.6cm) node {\\large Selections w/ $h_0(x),h_1(x)$};\n\t\t\\draw (3.3cm,4cm) node { \\large$\\widehat{Y}^0$};\n\t\t\\draw (5.2cm,4cm) node { \\large$\\widehat{Y}^1$};\n\t\t\n\t\t\\draw (-5.8cm,-4.5cm) node { 1) Cuckoo hash  $Y$  };\n\t\t\\draw (-5.8cm,-5.0cm) node { using oblv. permutation.};\n\t\t\\draw (-5.8cm,-5.5cm) node { $\\exists j$ s.t. $T[h_j(Y[i])]=Y[i]$. };\n\t\t\n\t\t\n\t\t\\draw (-0.3cm,-4.5cm) node { 2) Select Cuckoo locations $T[h_j(X[i])]$  };\n\t\t\\draw (-0.3cm,-5.0cm) node { using oblv. switching network.};\n\t\t\\draw (-0.3cm,-5.5cm) node { $\\widehat{Y}^j[i]=T[h_j(X[i])]$.};\n\t\t\n\t\t\n\t\t\n\t\t\\draw (5.4cm,-4.5cm) node { 3) Compare $\\widehat{Y}^0[i],\\widehat{Y}^1[i]$ w/ $X[i]$};\n\t\t\\draw (5.4cm,-5.0cm) node { using MPC circuit and  };\n\t\t\\draw (5.4cm,-5.5cm) node {construct output row. };\n\t\t\\end{tikzpicture}}\n\t\\caption{Overview of the join protocol using oblivious switching network.\\label{fig:mapping}}\n\\end{figure}\n\n\\subsection{Randomized Encodings}\n\nThe randomized encoding functionality \\f{encode} of \\figureref{fig:randomized-encode-ideal} enables the parties to coordinate their secret shares without revealing the underlying values. In particular, the parties will construct a cuckoo hash table using these encodings. The functionality takes as input several tuples $(\\share{B_i},\\share{X_i},\\Party{i})$ where $B_i\\in\\{0,1\\}^d$ is an array of $d$ bits, $ X_i\\in(\\{0,1\\}^\\sigma)^{d}$ is a array of $d$ strings and  $\\Party{i}$ that denotes that party $\\Party{i}$ should be output the encodings for this tuple. The functionality assigns a random $\\ell$ bit encoding for each input $x\\in \\{0,1\\}^\\sigma$. For $j\\in[d]$, if the bit $B_i[j]=0$ then the functionality outputs the encoding for $X_i[j]$ and otherwise a random $\\ell$ bit string. Looking forward, $B_i[j]=0$ will mean that the key $X_i[j]$ is actually set to \\Null and a random encoding should be returned.\n\n\n\n\\begin{figure}[ht]\n\t\\framebox{\\begin{minipage}{0.95\\linewidth}\n\t\t\tParameters: Input string size of $\\sigma$ bits and output encoding size of $\\ell$ bits.\\\\\n\t\t\t\n\t\t\t{\\bf [Encode]} Upon receiving command $(\\textsc{Encode},$ $\\{(\\share{B_i},\\share{X_i}, \\Party{i})\\})$ from all parties where $X_i\\in (\\{0,1\\}^\\sigma)^{d_i}, B_i\\in\\{0,1\\}^{d_i}$ for some $d_i\\in \\mathbb{Z}^*$. \n\t\t\t\\begin{enumerate}\t\t\t\t\n\t\t\t\t\\item Sample a uniformly random $F:\\{0,1\\}^\\sigma \\rightarrow \\{0,1\\}^\\ell$. Define $F':\\{0,1\\}\\times \\{0,1\\}^\\sigma \\rightarrow \\{0,1\\}^\\ell$ as  $F'(b,x) = \\overline{b}F(x) + br$ where $r\\gets\\{0,1\\}^\\ell$ is sampled each call.\n\t\t\t\t\n\t\t\t\t\\item For each $(\\share{ B_i},\\share{ X_i},\\Party{i})$, send $\\{F'(b,x)\\mid (b,x)\\in \\textsc{zip}(B_i,X_i)\\}$ to $\\Party{i}$. \n\t\t\t\\end{enumerate}\n\t\\end{minipage}}\n\t\\caption{The Randomized Encoding ideal functionality \\f{encode}}\n\t\\label{fig:randomized-encode-ideal}\t\n\\end{figure}\n\n\n\\paragraph{LowMC Encodings}\nWe realize this functionality using the LowMC block cipher\\cite{lowmc}. When implemented with the honest majority MPC protocols\\cite{highthroughput}, this approach results in extremely high throughput, computing up to one million encodings per second. Once the parties have their secret shared inputs, they sample a secret shared LowMC key uniformly and encrypt each input under that key using the MPC protocol. These encryptions are revealed as the encodings to the appropriate party.\n\n\nThe LowMC cipher is parameterized by a block size $\\ell$, keys size $\\kappa$, s-boxes per layer $m$ and the desired data complexity $d$. To set these parameters, observe that the adversary only sees a bounded number of block cipher outputs (encodings) per key. As such, the data complexity can be bounded by this value. For our implementation we upper bound the number of outputs by $d= 2^{30}$. The remaining parameters are set to be $\\ell\\in\\{80, 100\\}$ and $m=14$ which results in $r=13$ rounds and computational security of $\\kappa=128$ bits\\cite{lowmc}. The circuit for $\\ell=80$ contains 546 \\textsc{and} gates (bits of communication).\n\n%We show simulation of this approach with statistical correctness of $\\lambda$ bits. First, by the assumption that LowMC is indistinguishable from an ideal cipher, \n%\n%\\paragraph{Long Encodings} \n\n\nOne issue with the LowMC approach alone is that the input size is fixed to be at most $\\ell\\in\\{80,100\\}$ bits. However, we will see that the larger join protocol requires an arbitrary input size $\\sigma$. This is accommodated by applying a universal hash function to the input shares. Specifically, the parties jointly pick a random matrix $E\\gets\\{0,1\\}^{\\sigma\\times \\ell}$. The parties can then locally multiply each secret shared input before it is sent into the LowMC block cipher.\n\nThe security of this transformation follows from $xE\\neq x'E$ with overwhelming probability if $x\\neq x'$. In particular, $f(x)=xE$ is a universal hash function given that $E$ is independent of $x$. As such the probability that $f(x)=f(x')$ for any $x\\neq x'$  is $2^{-\\ell}$. Applying the birthday bound we obtain that probability of any collisions among the tuples is $2^{-\\ell+p}$ where $p=\\log_2 D^2/2=2\\log_2(D)-1$ and $D=\\sum_i d_i$.\n\nConditioned on the inputs to the block cipher being unique, the outputs of the block cipher is also distinct and indistinguishable from random $\\ell$ bit strings. As such, in the simulation the real outputs can be replaced with that of the ideal functionality so long as $2^{-\\ell+p}$ is statistically negligible, i.e. $\\ell-p\\geq\\lambda$.\n\n\n%$n*n=n^2$\n%$(D-1) + (D-2)+...+1 = \\sum_{i=1}^D (D-i)= D^2/2 = (2n)^2/2=2n^2$\n\n%\n%To preserve security we require the probability of the following game outputting 1 be negligible in $\\lambda$. \n%\\begin{quote}\n%Have the adversary select two sets $X,Y\\subset \\{0,1\\}^{m}$ of size $n_1,n_2\\in poly(\\lambda)$  respectively and then a uniformly random matrix $E\\gets \\{0,1\\}^{m\\times \\sigma}$ is sampled. If there exists distinct $x\\in X$ and $y\\in Y$ such that $xE = yE$, output 1, otherwise 0. \n%\\end{quote}\n\n%First observe that this use of $E$ is a universal hash function. \n\n%Therefore, fixing any distinct $x\\in X, y\\in Y$, it holds that $\\Pr[xE=yE]=2^{-\\sigma}$. Applying a union bound over all pairs of items, the overall probability of a collision is $2^{-\\sigma}n_1n_2$. By setting $\\sigma \\geq \\lambda + \\log_2(n_1) + \\log_2(n_2)$, we ensure that the collision probability is bounded by the statistical  security $2^{-\\lambda}$.\n\n%In practice, we set $\\lambda=40$ and choose $\\sigma =80$ if $n_1=n_2=n\\leq 2^{20}$ and $\\sigma=100$ otherwise (supporting $n\\leq 2^{30}$). \n\n\n\n\\begin{figure}[ht]\n\t\\framebox{\\begin{minipage}{0.95\\linewidth}\n\t\t\tParameters: Input, output size of $\\sigma$, $\\ell$ bits (respectively). Computational security parameter $\\kappa$.\\\\\n\t\t\t\n\t\t\t{\\bf [Encode]} Upon receiving command $(\\textsc{Encode},$ $\\{(\\share{B_i}, \\share{X_i}, \\Party{i})\\})$ from all parties where each $X_i\\in (\\{0,1\\}^\\sigma)^{d_i}$. Let $d=\\max_i(d_i)$.\n\t\t\t\\begin{enumerate}\n\t\t\t\t\\item If $\\sigma >\\ell,$ the parties jointly sample a matrix $E\\in\\{0,1\\}^{\\sigma\\times \\ell}$. Otherwise $E$ is the ${\\sigma\\times \\ell}$ identity matrix.\n\t\t\t\t\t\n\t\t\t\t \\item The parties have \\f{mpc} evaluate the following circuit:\n\t\t\t\t\\begin{enumerate}\t\t\t\t\n\t\t\t\t\t\\item Uniformly sample a key $k$ for a LowMC cipher with block size $\\ell$, computational security $\\kappa$ and data complexity at least $d$ blocks.\n\t\t\t\t\t\\item For each $(\\share{B_i}, \\share{X_i}, \\Party{i})$ input pair, reveal $\\{ F'(b,x) \\mid (b,x)\\in \\textsc{zip}(B_i, X_i)\\}$ to \\Party{i} where $F'(b,x)=\\textsf{LowMC}_k(xE)\\oplus br$ and $r\\gets\\{0,1\\}^\\ell$ is sampled for each call.\n\t\t\t\t\\end{enumerate}\n\t\t\t\n\t\t\\end{enumerate}\n\n\t\\end{minipage}}\n\t\\caption{The randomized encoding LowMC protocol.}\n\t\\label{fig:randomized-encode-lowMC}\t\n\\end{figure}\n\n\n\n\\subsection{Oblivious Switching Network}\n\nThe ideal functionality of a switching network was introduced by Mohassel and Sadeghian\\cite{MS13}. It obliviously transform a vector $A=\\{A_1,...,A_n\\}$ such that the output is $A'=\\{A_{\\pi(1)}, ..., A_{\\pi(m)}\\}$ for an arbitrary function $\\pi : [m]\\rightarrow[n]$. The accompanying protocol of \\cite{MS13} was designed in the two party setting where the first party inputs $A$ while the second party inputs a description of $\\pi$. \\iffullversion\nThis switching network require  $O(n\\log n)$ cryptographic operations. Building on this general paradigm, we \n\\else \nWe\n\\fi\nintroduce a \\emph{new} oblivious switching network protocol tailored for the honest majority setting with significantly efficiency improves. Our protocol has $O(n)$ overhead and is constant round. \\cite{MS13} requires $O(n\\log n)$ communication/computation and log rounds. %Moreover, our protocol can be instantiated with information theoretic security. \n\n\\newcommand{\\programmer}{\\ensuremath{P_{\\textsf{p}}}\\xspace}\n\\newcommand{\\sender}{\\ensuremath{P_{\\textsf{s}}}\\xspace}\n\\newcommand{\\receiver}{\\ensuremath{P_{\\textsf{r}}}\\xspace}\n\nThe ideal functionality of our protocol is given in \\figureref{fig:perm-ideal} with three parties, a programmer \\programmer, a sender \\sender and a receiver \\receiver. \\programmer has a description of  $\\pi$ while \\sender has a vector $A$ containing $n$ elements each consisting of $\\sigma$ bits. \\programmer and  \\receiver are each output a share of $\\shareTwo{A'}$ s.t. $A'=\\{A_{\\pi(1)}, ..., A_{\\pi(m)}\\}$.  Later we will discuss the case where $A$ is secret shared.\n\n\n\\begin{figure}[ht]\n\t\\framebox{\\begin{minipage}{0.95\\linewidth}\n\t\t\tParameters: $3$ parties denoted as the \\programmer, \\sender and \\receiver. Elements are strings in $\\{0,1\\}^\\sigma$. An input vector size of $n$ and output size of $m$.\n\t\t\t\n\t\t\t{\\bf [Switch]} Upon the command $(\\textsc{switch}, \\pi)$ from the \\programmer and $(\\textsc{switch}, A)$ from the \\sender:\n\t\t\t\\begin{enumerate}\n\t\t\t\t\\item Interpret $\\pi: [m]\\rightarrow [n]$ and $A\\in (\\{0,1\\}^{\\sigma})^n$. \n\t\t\t\t\\item Compute $B$ s.t. $\\forall i\\in [m], A_{\\pi(i)} = B_i$.\n\t\t\t\t\\item Generate $\\shareTwo{B}$ and send $\\shareTwo{B}_0$ to \\programmer and $\\shareTwo{B}_1$ to \\receiver.\n\t\t\t\\end{enumerate}\n\t\\end{minipage}}\n\t\\caption{The Oblivious Switching Network ideal functionality \\f{switch}}\n\t\\label{fig:perm-ideal}\t\n\\end{figure}\n\n\n\\paragraph{Permutation Network}\\label{sec:perm}\n\nWe begin with a restricted class of switching networks where the programming function $\\pi$ is injective. {That is, each input element $A_i$ will be mapped to a maximum of one location in the output.}  \\programmer samples two random functions $\\pi_0,\\pi_1$ such that $\\pi_1 \\circ \\pi_0 = \\pi$, $\\pi_0:[n]\\rightarrow [n]$ is bijective and $\\pi_1:[m]\\rightarrow [n]$ is injective.  \\programmer sends   $\\pi_1$ to  \\receiver and $\\pi_0, S\\gets \\{0,1\\}^{\\sigma\\times n}$ to  \\sender who sends $B := \\{A_{\\pi(1)} \\oplus S_0, ...,A_{\\pi(n)} \\oplus S_n \\}$ to  \\receiver. The final shares of $A'=\\pi(A)$ are defined as  \\programmer holding $\\shareTwo{A'}_0:=\\{S_{\\pi_1(1)}, ..., S_{\\pi_1(m)}\\}$ and the \\receiver holding $\\shareTwo{A'}_1:=\\{B_{\\pi_1(1)}, ..., B_{\\pi_1(m)}\\}$.\n\n\nThe simulation of this protocol is perfect. The view of \\sender contains a uniform permutation $\\pi_0$ and vector $S$.  Similarly, the view of  \\receiver contains $\\pi_1$ which is uniformly distributed (when $\\pi_0$ is unobserved) and the uniform vector $B$. A simulator can sample these directly on behalf of the honest parties.\n\nIn our computational secure setting,  $\\pi_0,S$ can be generated locally by \\Party{0} and \\Party{1} using a common source of randomness, e.g. a seeded PRG. This reduces the rounds to 1.  \n\n\\paragraph{Duplication Network}\\label{sec:dup}\n\nNext we consider a second type of network where $\\pi : [n]\\rightarrow[n]$,  $\\pi(1)=1$ and $\\pi(i)\\in \\{i, \\pi(i-1)\\}$ for $i=2,...,n$. That is, each output position is either a copy of the same input position or is a duplicate of the previous output position, e.g. $A'=\\{A_1,A_1,A_3,A_4,A_4,A_4\\}$ where $A_1,A_4$ were duplicated into the next position(s). This transformation can be characterized by a vector $b\\in\\{0,1\\}^{n}$ where $b_i=1$ denotes that the output position $i$ should be a copy of output position $i-1$.\n\n\\iffullversion\nThis observation gives rise to a natural protocol: for $i=1,...,m$, if $b_i=1$ then use MPC to copy $A_{i-1}$ into $A_{i}$. The primary challenge is to achieve this while using a constant number of communication rounds which prevents the use of a generic (secret sharing) MPC protocol such as \\cite{aby3, highthroughput}.\n\\fi\n\nAs a warm-up, suppose that the \\sender inputs $A_{i-1},A_{i}$ and that  \\programmer  \\& \\sender should receive a share of $\\shareTwo{B_{i}}$ such that $B_{i}:=A_{i-b_i}$. \\sender samples three uniform strings $\\shareTwo{B_{i}}_1, w_0,w_1\\gets \\{0,1\\}^\\sigma$ and a uniform bit $\\phi\\gets \\{0,1\\}$. \\sender constructs two messages $m_0=A_{i}^1\\oplus \\shareTwo{B_{i}}_1\\oplus w_\\phi$ and $m_1= A_{i-1}\\oplus \\shareTwo{B_{i}}_1 \\oplus w_{\\phi\\oplus 1}$.  \\sender sends $w_0,w_1$ to the \\receiver and sends $m_0,m_1,\\phi$ to  \\programmer who sends $\\rho=\\phi\\oplus b_i$ to  \\receiver. The final shares are constructed by having  \\receiver send $w_\\rho$ to  \\programmer who computes $\\shareTwo{B_{i}}_0:=m_{b_i}\\oplus w_{\\rho}$.\n\n\nThe simulation of this protocol is also perfect. \\programmer learns $m_0=A_{i}\\oplus \\shareTwo{B_{i}}_1\\oplus w_\\phi, m_1=A_{i-1}\\oplus \\shareTwo{B_{i}}_1\\oplus w_{1\\oplus \\phi}, w_{b_i\\oplus \\phi}$. As such, they can compute $\\shareTwo{B_i}_0=A_{i-b_i}\\oplus \\shareTwo{B_{i}}_1$ but not $A_{i-\\overline{b_i}}\\oplus \\shareTwo{B_{i}}_1$. \\receiver only learns $w_0,w_1$ and $\\rho=b_i\\oplus \\phi$ which can be trivially simulated. In our computationally secure setting observe that $w_0,w_1,\\phi$  are uniformly random and sending them can be optimized away with a pre-shared PRG seed.\n\n\nThe protocol just described considers the setting where the messages $A_{i-1},A_{i}$ are the private input of  \\sender. However, we require that at each iteration the messages being selected is either $B_{i-1}$ or $A_{i}$ where $\\shareTwo{B_{i-1}}$ was computed in the previous iteration. In this case  \\sender inputs their share of $B_{i-1}$ instead of $A_{i-1}$ while the \\programmer computes $\\shareTwo{B_{i}}_0:=m_{b_i}\\oplus w_{\\rho}\\oplus b_i\\shareTwo{B_{i-1}}_0$. \n\nNote that this protocol outputs shares to \\sender as opposed to  \\receiver. This can be corrected by having \\sender secret share $\\shareTwo{B}_1$ between \\receiver \\& \\programmer but we prefer to leave the protocol as is for composability reasons.\n\n\\paragraph{Shared Inputs}\n\n\nThe protocols and functionality described above assume the vector being transformed is the private input of the \\sender. However, our larger  protocols will require the transformations to be applied to secret shared vectors. In particular, the parties hold  $\\share{A}$.\nAs described in [shared Switch] of \\figureref{fig:switching-net}, the parties first locally convert $\\share{A}$ into $\\shareTwo{A}$ between \\sender and \\programmer. They run \\f{switch} where  \\sender inputs their share $B=\\shareTwo{A}_0$. \\programmer and \\receiver receive $\\shareTwo{\\pi(B)}$ from \\f{switch} where \\programmer holds $\\shareTwo{\\pi(B)}_0$. \\programmer  locally define $\\shareTwo{C}_0:=\\shareTwo{\\pi(B)}_0\\oplus \\pi(\\shareTwo{A}_1)$ and \\receiver defines $\\shareTwo{C}_1:=\\shareTwo{\\pi(B)}_1$. It is easy to verify that $C=\\pi(A)$. Simulation of this protocol essentially equivalent to simulating the call to \\f{switch} since there is no added communication.\n\n\n\\paragraph{Universal Switching Network}\\label{sec:switch}\n\nA universal switching network supporting an \\emph{arbitrary}  $\\pi : [m]\\rightarrow [n]$ can be constructed in three phases\\cite{MS13}: %In particular, the input vector $A$ will have three transformations applied\n $A\\overset{\\pi_1}{\\rightarrow}B\\overset{\\pi_2}{\\rightarrow}C\\overset{\\pi_3}{\\rightarrow}D=\\pi(A)$.\n\\begin{enumerate}\n\t\\item $B:=\\pi_1(A)$:  The input vector $A$ is permuted by the injective function $\\pi_1:[m]\\rightarrow[n]$ such that if $\\pi$ maps an input position $i$ to $k$ outputs positions (i.e. $k=|preimage(\\pi,i)|=|\\{ j : \\pi(j)=i \\}|$), then there exists a $j$ such that $\\pi_1(j)=i$  and $\\{\\pi_1(j)+ 1,...,\\pi_1(j )+k \\} \\cap image(\\pi) = \\emptyset$. That is, wherever position $i$ is mapped by $\\pi_1$, it should be followed by $k-1$ positions that do not appear in the final output. \n\t\n\t\\item $C:=\\pi_2(B)$: The intermediate vector $B$ is transformed by a \\emph{duplication network}  $\\pi_2:[m]\\rightarrow[m]$ which is defined as follows. If position $A_i$ is mapped to $k$ positions in $\\pi(A)$, then $\\{ C_{j},...,C_{j+k}\\} = \\{A_i\\}=\\{B_j\\}$ where $\\pi_1(j)=i$. That is, copies $B_{j}$ into the next $k-1$ positions. \n\t\n\t\\item $D:=\\pi_3(C)$: The final transformation $\\pi_3:[m]\\rightarrow[m]$  permutes $C$ to have the same ordering as $\\pi(A)$. That is, the elements $\\{ C_{j},...,C_{j+k}\\}$ which all have the value  $A_i$ are arbitrary mapped to the $k$ positions $\\{ j : \\pi(j)=i \\}$.\n\\end{enumerate}\nObserve that steps $\\pi_1,\\pi_3$ can both be implemented using the oblivious permutation protocol while $\\pi_2$ can be implemented with a duplication network.\n\\figureref{fig:switching-net} provides a formal description of the full switching network protocol.\n\nThe simulation of the full protocol ([switch] of \\figureref{fig:switching-net}) essentially follows from the simulation of the permutation and duplication protocols. That is, simulation of step b) and d) of [switch] follows the simulation of \\sectionref{sec:perm} and step c) follows from the simulation of \\sectionref{sec:dup}.\n\n\\begin{figure}[ht!]\n\t\\framebox{\\begin{minipage}{0.95\\linewidth}\\small\n\t\t\tParameters: $3$ parties denoted as \\programmer, \\sender and \\receiver. Elements are strings in $\\{0,1\\}^\\sigma$. An input, output vector size of $n, m$.\\\\\n\t\t\t\n\t\t\t\n\t\t\t{\\bf [Permute]} Upon the command $(\\textsc{Permute}, \\pi)$ from  \\programmer and $(\\textsc{Permute}, A)$ from  \\sender.  $\\pi: [m]\\rightarrow [n]$ is parsed as a \\emph{injective} function and  $A\\in \\{0,1\\}^{n\\times \\sigma}$ as a vector of $n$ elements. Then:\n\t\t\t\t\\begin{enumerate}[leftmargin=.8cm]\n\t\t\t\t\t\\item If $n<m$,  \\sender redefines $A$ to be $A := A || \\{0\\}^{(m-n)\\times \\sigma}$ and all parties redefine $n:=m$.\n\t\t\t\t\t\\item  \\programmer samples a uniformly random bijective function $\\pi_0 : [n]\\rightarrow[n]$ and computes the injective function $\\pi_1 :[n] \\rightarrow[m]$ such that $\\pi_1\\circ \\pi_0 = \\pi$.  $\\pi_0 $ and a random vector $S\\gets \\{0,1\\}^{n\\times \\sigma}$ are sent to  \\sender.\n\t\t\t\t\t\\item  \\sender computes and sends $B := \\{ A_{\\pi_0(1)} \\oplus S_1, ..., A_{\\pi_0(n)} \\oplus S_n\\}$ to  \\receiver.\n\t\t\t\t\t\\item  \\programmer sends $\\pi_1$ and a random vector $T\\gets\\{0,1\\}^{m\\times\\sigma}$ to  \\receiver who outputs $C^0:=\\{B_{\\pi_1(1)} \\oplus T_1,...,B_{\\pi_1(m)}\\oplus T_m\\}$.  \\programmer outputs $C^1:=\\{ S_{\\pi_1(1)}\\oplus T_1,...,S_{\\pi_1(m)}\\oplus T_m\\}$.\n\t\t\t\t\\end{enumerate}\n\t\t\t\t\n\t\t\t\t{\\bf [Switch]} Upon the command $(\\textsc{Switch}, \\pi)$ from  \\programmer and $(\\textsc{Switch}, A)$ from  \\sender. $\\pi: [m]\\rightarrow [n]$ is parsed as a function and  $A\\in \\{0,1\\}^{n\\times \\sigma}$ as a vector of $n$ elements. Then:\n\t\t\t\t\\begin{enumerate}[leftmargin=.8cm]\n\t\t\t\t\t\n\t\t\t\t\t\\item  \\programmer samples an injective function $\\pi_1:[m]\\rightarrow [n]$ such that for $i\\in image(\\pi)$ and $k=|preimage(\\pi, i)|$, there exists a $j$ where $\\pi_1(j)=i$ and $\\{\\pi_1(j+1), ...,\\pi_1(j+k) \\}\\cap image(\\pi)=\\emptyset$.\n\t\t\t\t\t\n\t\t\t\t\t \\programmer  sends $(\\textsc{Permute}, \\pi_1)$ to \\proto{switch} and  \\sender sends $(\\textsc{Permute}, A)$.  \\programmer receives $B^{0}\\in \\{0,1\\}^{m\\times \\sigma}$ in response and  \\receiver receives $B^{1}\\in \\{0,1\\}^{m\\times \\sigma}$. \n\t\t\t\t\t\n\t\t\t\t\t\\item  \\programmer  computes the vector $b\\in\\{0,1\\}^{m}$ such that for $i\\in image(\\pi)$ and $k=|preimage(\\pi, i)|$, $b_j = 0$ and $b_{j+1}=...=b_{j+k}=1$ where $\\pi_1(j)=i$.\n\t\t\t\t\t\n\t\t\t\t\t \\receiver samples three $m$ element vectors $C^{1}, W^0,W^1\\gets \\{0,1\\}^{m\\times \\sigma}$ and $\\phi\\gets\\{0,1\\}^m$. They set $C^{1}_1:=B^{1}_1$ and computes \n\t\t\t\t\t\\begin{align*}\n\t\t\t\t\t\tM^0_i&:= B^1_{i}\\ \\ \\, \\oplus C^{1}_i \\oplus W^{\\phi_i}_i\\\\\n\t\t\t\t\t\tM^1_i&:= C^1_{i-1} \\oplus C^{1}_i \\oplus W^{\\phi_i\\oplus 1}_i\n\t\t\t\t\t\\end{align*}\n\t\t\t\t\tfor $i\\in \\{2,...,m\\}$.  \\receiver sends $M,\\phi$ to  \\programmer and $C^{1},W$ to  \\sender.  \\programmer sends $\\rho:=\\phi\\oplus b$ to  \\sender who responds with $\\{ W^{\\rho_i}_i : i\\in [m] \\}$.  \\programmer defines $C^{0}_1:=B^{0}_1$ and computes \n\t\t\t\t\t$$\n\t\t\t\t\t\tC^{0}_i:= M^{b_i}_i \\oplus W^{\\rho_i}_i\\oplus b_iC^{0}_{i-1}\n\t\t\t\t\t$$\n\t\t\t\t\tfor $i\\in \\{2,...,m\\}$.\n\t\t\t\t\t\\item \\programmer computes the permutation $\\pi_3$ such that for  $i\\in image(\\pi)$ and $k=|preimage(\\pi, i)|$, $\\{\\pi_3(\\ell) : \\ell\\in preimage(\\pi, i)\\}=\\{j, ..., j +k\\}$ where $i=\\pi_1(j)$.\t \\programmer sends $(\\textsc{Permute}, \\pi_3)$ to \\proto{switch} and  \\sender sends $(\\textsc{Permute}, C^{1})$.  \\programmer receives $S\\in \\{0,1\\}^{m\\times \\sigma }$ in response.  \\receiver receives and outputs $D^{1}\\in \\{0,1\\}^{m\\times \\sigma }$.\n\t\t\t\t\t\n\t\t\t\t\t \\programmer outputs $D^{0}_i:=S_i\\oplus C^{0}_{\\pi_3(i)}$ for $i\\in [m]$.\n\t\t\t\t\\end{enumerate}\n\t\t\t\t\n\t\t\t\t{\\bf [Shared Switch]} Upon the command $(\\textsc{SharedSwitch},$ $\\pi, \\shareTwo{A}_0)$ from \\programmer and $(\\textsc{SharedSwitch}, \\shareTwo{A}_1)$ from \\sender. $\\pi: [m]\\rightarrow [n]$ is parsed as a function and  $A\\in \\{0,1\\}^{n\\times \\sigma}$ as a vector of $n$ elements.\n\t\t\t\t\\begin{enumerate}\n\t\t\t\t\t\\item \\programmer sends $(\\textsc{Switch}, \\pi)$ to \\proto{switch} and \\receiver sends $(\\textsc{Switch}, \\shareTwo{A}_1)$. \n\t\t\t\t\t\\item In response, \\programmer and \\receiver respectively receive $\\shareTwo{B}_0$ and $\\shareTwo{B}_1$. \\programmer outputs $\\shareTwo{B}_0\\oplus \\pi(\\shareTwo{A}_0)$ and \\receiver outputs $\\shareTwo{B}_1$.\n\t\t\t\t\\end{enumerate}\n\t\\end{minipage}}\n\t\\caption{The Oblivious Switching Network protocol \\proto{switch}. }\n\t\\label{fig:switching-net}\t\n\\end{figure}\n\n\n\n\\subsection{Join Protocols}\\label{sec:join}\n\nOur join protocol can be divided into four phases:\n\n\\begin{enumerate}\n\t\\item Compute randomized encodings of the join-columns/keys. \n\t\\item Party \\Party{1} constructs a cuckoo table $T$ for table $Y$ and arranges the secret shares using a permutation protocol. \n\t\\item For each row $x$ in $X$, \\Party{0} uses an oblivious switching network to map  the corresponding location $i_1,i_2$ of the cuckoo hash table to a secret shared tuple $(x, T[{i_1}], T[{i_2}])$.\n\t\\item The join-key(s) of $x$ is compared to that of $T[{i_1}], T[{i_2}]$. If one of them match then the corresponding output row is populated; otherwise the output row is set to \\texttt{NULL}.\n\\end{enumerate} \nSteps 1 through 3 are performed by the Map routine of \\figureref{fig:full_proto} while step 4 is performed in \\figureref{fig:full_proto2}. \\figureref{fig:full_ideal} contains the ideal functionality of the join protocol.\n\n\n\n\\paragraph{Randomized Encodings}\nWe begin by generating randomized encodings of the columns being used for the join-keys. For example, \n\\iffullversion\n$$\n\t\\texttt{select }* \\texttt{ from } X \\texttt{ inner join } Y \\texttt{ on } X_1 = Y_1 \\texttt{ and } X_2 = Y_3\n$$\n\n\\else\nselecting all columns of $X$ and $Y$ where $X_1 = Y_1 \\texttt{ and } X_2 = Y_3$.\n\\fi\nIn this case there are two join-keys, $X_1,X_2$ from $X$ and $Y_1,Y_3$ from $Y$. The protocol has \\Party{0} learn the randomized encoding for each row of $X$ and \\Party{1} learn them for $Y$. Importantly, is that after a previous join operation, some (or all) of the rows being joined can be \\texttt{NULL}. We require that the randomized encodings of these rows not reveal that they are \\texttt{NULL}. For table $X$, a special column $\\XNull$ encodes if for each row is logically \\texttt{NULL}. The \\f{encode} functionality will then return a random encoding for all \\texttt{NULL} rows. Specifically, the parties will send $(\\textsc{Encode}, \\{(\\share{\\XNull}, \\share{X_{j_1}||...||X_{j_l}}, \\Party{0}), (\\share{\\YNull}, \\share{Y_{k_1}||...||$ $Y_{k_l}}, \\Party{1})\\})$ to \\f{encode} where $j_1,...,j_l$ and $k_1,...,k_l$ index the join-keys of $X$ and $Y$. Let $\\mathbb{E}_x,\\mathbb{E}_y\\in(\\{0,1\\}^{\\ell})^n$ be the encodings that \\Party{0} and \\Party{1} respectively receive from \\f{encode}.\n\n\nFor correctness, we require the encoding bit-length $\\ell$ to be sufficiently large such that the probability of a collision between encodings is statistically negligible. Given that there are a total of $D=2n$ encodings, the probability of this is at most $2^{-\\ell+2\\log_2 D-1}$ which we require to be less than $2^{-\\lambda}$, therefore $\\ell\\geq \\lambda+2\\log_2 D -1$. Our implementation uses $\\lambda=40$ and $\\ell\\in\\{80,100\\}$ depending on $D$.\n\n% Following the same logic as before, the probability that $x'$ collides with some $y'$ is $2^{-\\sigma}n_1n_2$ and therefore the resulting encodings are uniformly distributed and unique with overwhelming probability. \n\n%\\todo{Pr. of collision.}\n\n%Putting everything together, the parties sample $E\\gets\\{0,1\\}^{m\\times \\sigma}$ if $m>\\sigma$ and $E=I$ otherwise. For $i\\in[n]$ and $Z\\in\\{X[i],Y[i]\\}$, let  $\\share{Z_{j_1}},...,\\share{Z_{j_l}}$ be the join-keys of row $i$. A secret shared value $r\\gets\\{0,1\\}^\\sigma$ is sampled and the parties compute $\\share{z'}:=\\share{Z_{j_1}||...||Z_{j_l}}E \\oplus \\share{\\overline{b}}\\share{r}$. \\share{z'} is sent to \\f{encode}. Party \\Party{0} receives the randomized encodings $\\mathbb{E}_x$ for the join-keys of $X$ and \\Party{1} receives the encodings $\\mathbb{E}_y$ for $Y$.\n\n\\paragraph{Constructing the Cuckoo Table}\n\nThe next phase of the protocol is for \\Party{1} to construct a secret shared cuckoo table for $Y$ where each row is inserted based on its encoding in $\\mathbb{E}_y$. \\Party{1} locally inserts the encodings $\\mathbb{E}_y$ into a plain cuckoo hash table $t$ with $m$ slots using the algorithm specified in \\sectionref{sec:prelim}. We assume two hash functions are used. \\Party{1} samples an injective function $\\pi : m\\rightarrow m$ such that  $t[j]=\\mathbb{E}_y[i]$, then $\\pi(j)=i$.\n\\iffullversion\n That is, $\\pi$ defines the mapping from each row's original position in the table $Y$ to the corresponding position in the cuckoo table $t$.\n\\fi\n\nParties \\Party{0} and \\Party{1} convert $\\share{Y}$ to $\\shareTwo{Y}$ such that \\Party{0} holds $\\shareTwo{Y}_0$. \n\\Party{1} sends $(\\textsc{SharedSwitch}, \\pi, \\shareTwo{Y}_1)$ to \\f{switch} and \\Party{0} sends $(\\textsc{SharedSwitch}, \\shareTwo{Y}_0)$.\nIn response \\f{switch} sends $\\shareTwo{\\ytable}_{1}$ to \\Party{1}  and $\\shareTwo{\\ytable}_{0}$ to \\Party{2}. \nIt is now the case that $\\ytable$ is a valid secret shared cuckoo hash table of $Y$.\n\\iffullversion\n In particular, for a given row $Y[i]$ with encoding $e=\\mathbb{E}_y[i]$, there exists a $j\\in \\{h_1(e),h_2(e)\\}$ such that  $\\ytable[j] = Y[i]$. Here, the $h_0,h_1$ functions are hash functions used to construct the cuckoo table $\\ytable$. Another important observation is that $\\pi$ is a permutation and therefore the more efficient permutation protocol can be used in place of the universal switching protocol.\n\nWe note that some of the columns of the tables may be secret shared in arithmetic group as opposed to binary shares. In this case the switching network will use the appropriate arithmetic operation as note in \\sectionref{sec:switch}. \n\\fi\n\n\\paragraph{Selecting from the Cuckoo Table}\n\nThe next phase of the protocol is for each row of $X$, select the appropriate rows of $\\ytable$ so the keys can be compared. \\Party{0} knows that if the join-keys of the $X[i]$ row will match with a row from $Y$, then this row will be at $\\ytable[j]$ for some $j\\in \\{h_1(e),h_2(e)\\}$ where  $e=\\mathbb{E}_x[i]$. \n\nTo obliviously compare these rows, \\Party{0} will construct two switching networks with programming $\\pi_1,\\pi_2 : n\\rightarrow m$ such that if $h_l(\\mathbb{E}_x[i])=j$ then $\\pi_l(i)=j$. Each of these will be used to construct the tables $\\shareTwo{\\widehat{Y}^1},\\shareTwo{\\widehat{Y}^2}$ which are the result of applying the switching networks $\\pi_1,\\pi_2$ to $\\shareTwo{\\ytable}$. \n\\iffullversion\nIn particular, for the $i$th row $X[i]$ it is now the case that if $X[i]$ has a matching row in $Y$ then it will be contained at  $\\widehat{Y}^1[i]$ or $\\widehat{Y}^2[i]$. \n\\fi\n\n\n\\paragraph{Inner Join}\n\nGiven the three secret shared tables $\\share{X},\\shareTwo{\\widehat{Y}^1},\\shareTwo{\\widehat{Y}^2}$ as described above, the parties do a linear pass over the $n$ rows to construct the join between $X$ and $Y$. Recall that the inner join consists of all the selected columns from the rows $X[i],Y[j]$ where  the join-keys of the rows $X[i]$ and $Y[j]$ are equal. \n\nIf row $X[i]$ has a matching row in $Y$ then this row will occupy either ${\\widehat{Y}^1}[i]$ or ${\\widehat{Y}^2}[i]$. To determine which, the parties input the secret shares of these rows to an MPC protocol where the join-keys are compared. For each $i$ and rows ${\\widehat{Y}^1}[i],{\\widehat{Y}^2}[i]$ the bits $c_1[i],c_2[i]$ are generated where $c_l[i]=1$ iff the join-keys of ${\\widehat{Y}^l}[i]$ are equal to that of $X[i]$. The MPC circuit then computes  $Y'[i]:=c_1[i]{\\widehat{Y}^1}[i]\\oplus c_2[i]{\\widehat{Y}^2}[i]$ and $\\YNull'[i]:=\\YNull'[i]\\vee \\neg(c_1[i]\\oplus c_2[i])$. That is, $Y'[i]$ is a \\Null row if it was already \\Null or none of the comparisons were equal. % $c[i]$ encodes whether the $i$th row of $Y'$ is not \\texttt{NULL}. If so, then $Y'[i]$ is the row of $Y$ which has matching join-keys with $X[i]$.\n\nNext, the \\texttt{where} clause further filters the output table as a function of $Y'[i]$ and $X[i]$. \n\\iffullversion\nFor example, the query may specify that only rows where $Y_2'[i] + X_3[i] > 22$  are to be selected. Regardless of the exact where clause, the \n\\else \nThe\n\\fi\nMPC protocol sets the \\texttt{NULL}-bit of the final output table $Z$ as $\\ZNull[i] :=\\XNull[i] \\vee \\YNull'[i] \\vee \\neg  P(Y'[i], X[i])$ where $P$ is the predicate function specified by the \\texttt{where} clause.\nFinally, the computation specified by the \\texttt{select} query is performed, e.g. copying the columns of $X,Y$ or computing a function of them. \n\n%Specifically, the columns of the output table can either be directly copied from the input tables $X,Y$ or can be a function of the given row. \n%\\iffullversion\n%For example, the query could be of the form \n%$$\n%\\texttt{select } X_1, Y_2 + X_3 \\texttt{ from } X \\texttt{ inner join } Y \\texttt{ on } X_1 = Y_1\n%$$\n%In this case the first column of the output will be $X_1$ while the second column will consist of the second column of $Y$ plus the third column of $X$. \n%\\fi\n%In general we view the \\texttt{select} clause as a function which takes the rows $X[i]$ and $Y'[i]$ and computes a new row with the specified columns. \n\n\\iffullversion\n\\paragraph{Optimizations}\nSeveral optimizations can be applied to this protocol. First, observe that only columns of $Y$ which explicitly appear in the query need to be input to the switching networks. This reduces the amount of data to be sent and improves performance. Secondly, when comparing the join-columns, instead of computing the equality circuit between all of these columns it suffices to compare the randomized encodings. In the event that the join-column(s) contain many bits, comparing the encodings can reduce the size of the equality circuit. In addition, observe that including columns from $X$ in the output table is essentially free due to these secret share columns simply being copied from $X$. Leveraging this the queries can be optimized by ensuring that the majority of the output columns are taken from $X$. Moreover, if a join-column from $Y$ is in the \\texttt{select} clause, this output column can be replaced with the matching column in $X$.\n\nAlso observe that the computation perform heavily lends itself to SIMD instructions. That is, the same computation is repeatedly applied to each row of the output table. Modern MPC protocol such as the ABY$^3$ framework \\cite{aby3,highthroughput} are optimized for this setting and can process billions of binary circuit gates per second\\cite{highthroughput}. In addition the ABY$^3$ framework can switch between using binary and arithmetic circuits based on which is most efficient for the given computation. \n\\fi\n\n\\paragraph{Left/Right Join}\n\nA left join query is similar to an inner join except that all of the rows from the left table $X$ are included. All rows that are in the inner join are computed as before. For rows only in $X$, the bit $\\YNull'[i]$ will equal one and is used to initialize the missing columns from $Y$ to a default, typically \\texttt{NULL}. A right join can be implemented symmetrically.\n\n\\paragraph{Union and Set Minus}\n\nOur framework is also capable of computing the union of two tables with respect to the join-keys. Specifically, we define the union operator as taking all of the rows from the left table and all of the rows from the right table that would not be present in the inner join. First we compute $Y\\backslash X$ by only including $X[i]$ if $Y'[i]$ is \\Null, i.e. $X[i]$ has no matching row in $Y$. The union of $X$ and $Y$ is then constructed as $(Y\\backslash X) || X$ where the $||$ operator denotes the row-wise concatenation of $X$ to the end of $Y\\backslash X$.\n\n\n\\paragraph{Full Join}\n\nWe construct a full join as $(X$ left join $Y)$ union $Y$. The left join merge the rows in the intersection and the union includes the missing rows of $Y$. The overhead of this protocol is effectually twice that of the other protocols. \n\nWe note that under some restrictions on the tables being joined, a more efficient protocol for full joins can be achieved. We defer an explanation of this technique to \\sectionref{sec:threatlog}.\n\n\\paragraph{Security} The simulation of these protocols directly follow from the composibility of the subroutines \\f{encode}, \\f{switch} and \\f{mpc}. First, the output of \\f{encode} simply outputs random strings and it is therefore straightforward to simulate.  \\f{switch} and \\f{mpc} both output secret shared values. Finally, correctness is straight forward to analysis and holds so long as there is no encoding collisions and cuckoo hashing succeeds. Parameters are chosen appropriately so these failure events happen with probability at most $2^{-\\lambda}$.\n\n\\begin{figure}[ht]\n\t\\framebox{\\begin{minipage}{0.95\\linewidth}\n\t\t\tParameters: Table size $n$. For all command, $X,Y$ are tables and $\\{X_j \\mid j\\in J\\}$ and $\\{Y_k \\mid k\\in K\\}$ are the join-keys of $X$ and $Y$ respectively. $S$ is the \\texttt{select} function and $P$ is the \\texttt{where} predicate.\\\\\n\t\t\t\n\t\t\t{\\bf [Map]} Upon receiving command $(\\textsc{Map},\\share{X},J, \\share{Y}, K)$ from all parties. %Let $n_x$ and $n_y$ be the number of rows $X$ and $Y$ has respectively.\n\t\t\t\\begin{enumerate}\n\t\t\t\t\\item The parties send $(\\textsc{Encode}, \\{(\\share{\\XNull}, \\share{X_{J_1}||...||X_{J_l}}, $ $\\Party{0}), (\\share{\\YNull}, \\share{Y_{K_1}||...||Y_{K_l}}, \\Party{1})\\})$ to \\f{encode} where $l=|J|=|K|$. \\Party{0} receives $\\mathbb{E}_x$ and \\Party{1} receives $\\mathbb{E}_y$ from \\f{encode}.\n\n\t\t\t\t\\item \\Party{1} constructs a cuckoo hash table $t$ for the set $\\mathbb{E}_y$. Define $\\pi_0$ such that $\\pi_0(j)=i$ where $\\mathbb{E}_y[i]=t[j]$.\n\t\t\t\t\n\t\t\t\t\\item \\Party{0} and \\Party{1} convert \\share{Y} to \\shareTwo{Y}. \\Party{1} sends $(\\textsc{SharedSwitch}, \\pi_0, \\shareTwo{Y}_1)$ to \\f{switch} and \\Party{0} sends $(\\textsc{SharedSwitch}, \\shareTwo{Y}_0)$.\n\t\t\t\t\\Party{1} receives $\\shareTwo{\\ytable}_{1}$ and \\Party{2} receives $\\shareTwo{\\ytable}_{0}$ from \\f{switch}.\n\t\t\t\t\n\t\t\t\t\\item Let $h_1,...,h_w$ be the cuckoo hash functions. \\Party{1} defines $\\pi_1,...,\\pi_w$ such that $\\pi_l(i)=j$ where $h_l(\\mathbb{E}_x[i])=j$.\n\t\t\t\t\n\t\t\t\t\\item For $l\\in[w]$, \\Party{1} sends $(\\textsc{SharedSwitch}, \\pi_l, \\shareTwo{T}_1)$ to \\f{switch} and \\Party{2} sends $(\\textsc{SharedSwitch}, \\shareTwo{T}_0)$. \\Party{0} receives $\\shareTwo{\\widehat{Y}^l}_0$ and \\Party{1} receives $\\shareTwo{\\widehat{Y}^l}_1$ from \\f{switch}.\n\t\t\t\t\n\t\t\t\t\\item The parties convert  $\\{\\shareTwo{\\widehat{Y}^l}\\}_{l\\in[w]}$ to $\\{\\share{\\widehat{Y}^l}\\}_{l\\in[w]}$ and output them.\n\t\t\t\\end{enumerate}\n\t\t\\end{minipage}}\n\t\t\\caption{Join protocols $\\proto{join}$.}\n\t\\label{fig:full_proto}\t\n\\end{figure}\n\n\n\\begin{figure}[ht]\n\t\\framebox{\\begin{minipage}{0.95\\linewidth}\n%\t\t\t{\\bf [Compare]} Upon receiving command $(\\textsc{Compare},\\share{X},$ $J, \\{\\share{\\widehat{Y}^l}\\}_{l\\in[w]}, K)$ from all parties. The parties have \\f{mpc} evaluate the following circuit:\n%\t\t\t\\begin{enumerate}\n%\t\t\t\t\\item For $l\\in[w]$ and $i\\in[n]$, $\\share{c_l}[i]:= \\wedge_j( \\share{X_{J_j}}[i]=\\share{\\widehat{Y}^l_{K_j}}[i])$.\n%\t\t\t\t$\\share{c}[i]:= \\vee_l \\share{c_l}[i]$ and $\\share{Y'}[i]:= \\oplus_l { \\share{c_l}[i] \\cdot \\share{\\widehat{Y}^l}[i]}$.\n%\t\t\t\t\n%\t\t\t\t\\item Output $\\share{c}$ and \\share{Y'}.\n%\t\t\t\\end{enumerate}\n%\t\t\t\n\t\t\t\n\t\t\t{\\bf [Join]}  Upon receiving command $(\\textsc{Join}, type, \\share{X},$ $J, \\share{Y}, K, S, P)$ from all parties.\n\t\t\t\\begin{enumerate}\n\t\t\t\t\\item The parties send $(\\textsc{Map},\\share{X},J, \\share{Y}, K)$ to \\proto{join} and receive $\\{\\share{\\widehat{Y}^l}\\}_{l\\in[w]}$.\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\\item The parties have \\f{mpc} evaluate the following circuit:\n\t\t\t\tFor $l\\in[w]$ and $i\\in[n]$, $\\share{c_l}[i]:= \\wedge_j( \\share{X_{J_j}}[i] \\overset{?}{=} \\share{\\widehat{Y}^l_{K_j}}[i])$.\n\t\t\t\tFor  $i\\in[n],$ $\\share{Y'}[i]:= \\oplus_l { \\share{c_l}[i] \\cdot \\share{\\widehat{Y}^l}[i]}$ and $\\share{\\YNull'}[i]:= \\share{\\YNull'}[i]\\wedge \\neg(\\oplus_l \\share{c_l}[i])$.\n\t\t\t\t\t\t\t\t\n\t\t\t\t\\item If $type=\\textsc{InnerJoin}$, define the output table $Z$ by having \\f{mpc} evaluate:\n\t\t\t\t For $i\\in [n],$ $\\share{\\ZNull}[i]:=\\share{\\XNull}[i] \\vee \\share{\\YNull'}[i] \\vee \\neg P(\\share{X}[i], \\share{Y'}[i])$ and $\\share{Z}[i]:=S(\\share{X}[i], \\share{Y'}[i])$.\n\n\t\t\t\t\\item If $type=\\textsc{LeftJoin}$, define the output table $Z$ by having \\f{mpc} evaluate:\n\t\t\t\tFor $i\\in [n],$ $\\share{\\ZNull}[i]:=\\share{\\XNull}[i] \\vee \\neg P(\\share{X}[i], \\share{Y'}[i])$ and $\\share{Z}[i]:=S(\\share{X}[i], \\share{Y'}[i])$.\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\\item If $type=\\textsc{Union}$, define the output table $Z$ by having \\f{mpc} evaluate:\n\t\t\t\tFor $i\\in [n], \\share{\\ZNull}[i]:= \\share{\\XNull}[i] \\vee \\neg P(\\share{X}[i], \\Null)$ and $\\share{Z}[i]:=S(\\share{X}[i], \\Null)$. \n\t\t\t\t\n\t\t\t\tFor $i\\in [n+1,2n], \\share{\\ZNull}[i]:= \\share{\\YNull}[i] \\vee \\neg \\share{\\XNull}[i] \\vee \\neg P(\\Null, \\share{Y'}[i])$ and $\\share{Z}[i]:=S(\\Null, \\share{Y'}[i])$.\n\t\t\t\t\n\t\t\t\t\\item If  $type=\\textsc{FullJoin}$, all parties sending $(\\textsc{Join}, \\textsc{LeftJoin}, \\share{X}, J, \\share{Y}, K, S', P)$ to $\\proto{join}$ and receiving $\\share{X'}$ in response. They then send $(\\textsc{Join}, \\textsc{Union}, \\share{X'}, J, \\share{Y}, K, S'', P')$  to $\\proto{join}$ and output the response, where $S',S''$ and $P'$ are appropriately updated version of $S,P$.\n\t\t\t\\end{enumerate}\n\t\\end{minipage}}\n\t\\caption{Join protocols $\\proto{join}$ continued.}\n\t\\label{fig:full_proto2}\t\n\\end{figure}\n\n\n\n\\begin{figure}[ht]\n\t\\framebox{\\begin{minipage}{0.95\\linewidth}\n\t\t\t{\\bf [Join]}  Upon receiving command $(\\textsc{Join}, type, \\share{X},$ $J, \\share{Y}, K, S, P)$ from all parties. Let $n_X$ and $n_Y$ denote the number of rows in $X,Y$ respectively.\n\t\t\t\\begin{enumerate}\n\t\t\t\t\\item Define $\\textsc{Keys}(X,J,i)=(X_j[i])_{j\\in J}$.\n\t\t\t\t\n\t\t\t\t\\item If the collections $\\{ \\textsc{Keys}(X,J,i) \\mid i\\in n \\wedge \\XNull[i]=0 \\}$ or $\\{\\textsc{Keys}(Y,K,i) \\mid i\\in n\\wedge \\YNull[i]=0 \\}$ contains duplicates, output $\\bot$.\n\t\t\t\t\n\t\t\t\t\\item If $type=\\textsc{InnerJoin}$, let the rows of $Z$ be $\\{ S(X[i],Y[j]) \\mid \\exists i,j\\text{ s.t. }\n\t\t\t\t\\neg\\XNull[i]\\wedge \\neg\\YNull[j]\\wedge \\textsc{Keys}(X,J,i)\\overset{?}{=}\\textsc{Keys}(Y,K,j) \\wedge P(X[i],Y[i]) \\}$ along with zero or more \\Null rows s.t. $Z$ has $n_X$ rows.\n\t\t\t\t\n\t\t\t\t\\item If $type=\\textsc{LeftJoin}$, let the rows of $Z$ be $\\{ S(X[i],Y[j]) \\mid \\exists i,j\\text{ s.t. }\n\t\t\t\t\\neg\\XNull[i]\\wedge \\neg\\YNull[j]\\wedge \\textsc{Keys}(X,J,i)\\overset{?}{=}\\textsc{Keys}(Y,K,j) \\wedge P(X[i],Y[i])\\}\n\t\t\t\t\\cup \n\t\t\t\t\\{ S(X[i],\\Null) \\mid \\exists i,\\forall j\\text{ s.t. } \\neg\\XNull[i]\\wedge \\textsc{Keys}(X,J,i) \\neq\\textsc{Keys}(Y,K,j) \\wedge P(X[i],\\Null)\\}$ along with zero or more \\Null rows s.t. $Z$ has $n_X$ rows.\n\t\t\t\t\n\t\t\t\t\\item If $type=\\textsc{Union}$, let the rows of $Z$ be $\\{ S(X[i],\\Null) \\mid \\exists i \\text{ s.t. }\n\t\t\t\t\\neg\\XNull[i]\\wedge P(X[i],\\Null)\\} \n\t\t\t\t\\cup\n\t\t\t\t\\{ S(\\Null, Y[i]) \\mid \\exists i,\\forall j\\text{ s.t. } \\neg\\YNull[i]\\wedge \\textsc{Keys}(X,J,j) \\neq\\textsc{Keys}(Y,K,i) \\wedge P(\\Null, Y[i])\\}$\n\t\t\t\talong with zero or more \\Null rows s.t. $Z$ has $n_X+n_Y$ rows.\n\t\t\t\t\n\t\t\t\t\\item If  $type=\\textsc{FullJoin}$, let the rows of $Z$ be $\\{ S(X[i],Y[j]) \\mid \\exists i,j\\text{ s.t. }\n\t\t\t\t\\neg\\XNull[i]\\wedge \\neg\\YNull[j]\\wedge \\textsc{Keys}(X,J,i)\\overset{?}{=}\\textsc{Keys}(Y,K,j) \\wedge P(X[i],Y[i]) \\}\n\t\t\t\t\\cup \n\t\t\t\t\\{ S(\\Null, Y[i]) \\mid \\exists i,\\forall j\\text{ s.t. }\n\t\t\t\t\\neg\\YNull[i]\\wedge \\textsc{Keys}(X,J,j)\\neq\\textsc{Keys}(Y,K,i) \\wedge P(\\Null, Y[i])\\}\n\t\t\t\t\\cup \n\t\t\t\t\\{ S(X[i], \\Null) \\mid \\exists i,\\forall j\\text{ s.t. }\n\t\t\t\t\\neg\\XNull[i]\\wedge \\textsc{Keys}(X,J,i)\\neq\\textsc{Keys}(Y,K,j) \\wedge P(X[i], \\Null)\\}$\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\\item Output $\\share{Z}$ to the parties.\n\t\t\t\\end{enumerate}\n\t\\end{minipage}}\n\t\\caption{Join functionality $\\f{join}$.}\n\t\\label{fig:full_ideal}\t\n\\end{figure}\n\n\n\\subsection{Non-unique Join on Column}\n\n\nWhen values in the join-column are not unique within a single table, the security guarantees begin to erode. Recall that the randomized encodings for $X,Y$ are revealed to \\Party{0}, \\Party{1} respectively. Repeated values in the join-columns will lead to duplicate randomized encodings and therefore reveal their location. Learning the distribution of these duplicates reveals that the underlying table has the same distribution. In the event that only one of the tables contains duplicates, the core protocol can naturally be extended to compute the various join operations subject to \\Party{0} learning the duplicate distribution. This is achieved by requiring the left table $X$ contain the duplicates rows. After learning the randomized encodings for this table \\Party{0} can program the switching networks appropriately to query the duplicate locations in the cuckoo hash table. \n\n\nWhen both tables contain duplicates we fall back to a less secure protocol architecture. This is required due to the cuckoo table not supporting duplicates. First, \\Party{1} samples two random permutations $\\pi_0,\\pi_1$ and computes $X'=\\pi_1(X),Y'=\\pi_2(Y)$ using the oblivious permutation protocol. \\Party{0} then learns all of the randomized encodings for the permuted tables $X'$ and $Y'$. Given this, \\Party{0} can compute the size of the output table and inform the other two parties of it. Alternatively, an upper bound on the output table size can be communicated. Let $n'$ denote this value. \\Party{0} can then construct two switching networks which map the rows of $X'$ and $Y'$ to the appropriate rows of the output table. The main disadvantage of this approach is that \\Party{0} learns the size of the output, the distribution of duplicate rows and how these duplicate rows are multiplied together. However, unlike \\cite{LTW13} which takes a conceptually similar approach, our protocol does not leak any information to \\Party{1} and \\Party{2}, besides the value $n'$.\n\n%When both tables contain duplicates we fall back to the less secure protocol architecture of Laur et al.\\cite{LTW13}. In particular, this style of protocol  performs an oblivious shuffling of the table rows and then reveals all of the randomized encodings to all of the parties. Given this information the parties can construct the desired join. We suggest that the performance of these two primitive can be improved over \\cite{LTW13} by 1) implementing the random shuffle using two random permutation networks from \\sectionref{sec:switch} where party 0 and 1 both privately sample one of the permutations. 2) Replace the use of AES with our improved randomized encodings (LowMC and random binary matrix). Given these optimization the overhead of these protocols should be comparable to our standard join techniques. The major shortcoming of this approach is that the duplicate distribution and the size of join is revealed to all of the parties. As discussed in the related work section, this can limit several important application such as threat log comparison. \n\n\\subsection{Revealing Results}\n\nRevealing a secret shared table $\\share{X}$ requires two operations. First observe that the data in the \\texttt{NULL} rows is not cleared out by the join protocols. This is done as an optimization. As such naively reconstructing these rows would lead to significant leakage. Instead $X[i]$  is updated as $X[i]=(\\neg\\XNull[i])\\cdot X[i]$. %This ensures that all \\texttt{NULL} rows have a deterministic value and therefore can be simulated. \nThe second operation is to perform an oblivious shuffle of the rows. This operation randomly reorders all the rows without revealing the ordering to any of the parties. This step is necessary since the original ordering of the result table is input-dependent. For example, say $X$ is a list of patents info, $Y$ is patent billing status, and $Z$ is a list of patent diseases. Say we reveal $\\texttt{select } X.name, Y.balance \\texttt{ from } X,Y \\texttt{ on } X.id=Y.id$ and $\\texttt{select } X.gender, Z.desease \\texttt{ from } X,Z \\texttt{ on } \\allowbreak X.id=Z.id$. Without reordering you could connect $X.name, X.gender, Y.balance$ and $Z.desease$ by the row index and infer secret information. However, by randomly shuffling this connection is destroyed and the reveal can be simulated.\n\n\n%Concretely, this ordering can be used to correlate between two different output tables. For example, the row ordering of say $X\\cap Y$ and $X\\cap Z$ will be the same up to some rows being \\texttt{NULL} while other may not. %In the case of sets this ordering does not reveal additional information since it can be inferred given the ideal output, e.g. set intersection, then the shuffling can be omitted. However, this is not true in general when the items being joined are key-value pairs. \n\n\n\\section{Computing a Function of a Table}\\label{sec:card}\n\nIn addition to join queries, our framework can perform computation on a single secret shared table. For example, selecting $X_1+X_2$  where $X_3>42$. For each row $i$ we generate the corresponding output row $Z[i]$ by computing the new \\texttt{NULL}-bit as $\\ZNull[i] := \\XNull[i] \\vee P(X[i])$ where $P(\\cdot)$ is the \\texttt{where} predicate. The new column(s), e.g. $Z_1=X_1+X_2$, can then be constructed in a straightforward MPC protocol, e.g. \\cite{aby3,highthroughput}. The key property is that all of the operations are with respect to a single row of $X$, allowing them to be evaluated in parallel. \n\nOur framework also considers a second class of functions on a table that allow computation between rows. For example, computing the sum of a column. We refer to this broad class of operations as an aggregation function. Depending on the exact computation, various levels of efficiencies can be achieved. Our primary approach is to employ the ABY$^3$ framework \\cite{aby3} to express the desired computation in an efficient way and then to evaluate the resulting circuit. Next we highlight a sampling of some important aggregation operations:\n\\begin{itemize}\n\t\\item Sum: For a column $\\share{X_j},$ compute $\\share{s}=\\sum_i \\share{X_j}[i]$ where $X_j[i]\\in \\mathbb{Z}_{2^\\ell}$ and $i$ indexes only non-\\Null rows. The parties compute $\\shareA{s}:=\\sum_{i\\in [n]}\\textsf{B2A}((\\neg\\share{\\XNull}[i]) \\cdot \\share{X_j}[i])$ where $\\textsf{B2A}$ is the boolean to arithmetic share conversion of \\cite{aby3}. In total this requires $2n\\ell$ binary gates and $\\ell+1$ rounds\\cite{aby3}. The parties can then convert $\\shareA{s}$ back to \\share{s} if desired. %Alternatively, $n\\ell\\log \\ell$ binary gates and $\\log \\ell$ rounds can be used\\cite{aby3}. \n\t\n\t\\item Count/Cardinality: Here, we consider two cases. 1) In the general case there is an arbitrary table over which the count is being computed. This is performed by computing $\\shareA{s}:=\\sum_{i\\in [n]}\\textsf{B2A}(\\neg\\share{\\XNull}[i])$ \n\t\\iffullversion \n\tThe more efficient bit injection protocol\\cite{aby3} can be used to convert each bit to an arithmetic sharing in a constant number of rounds. In particular, the malicious secure bit injection protocol provided in \\cite{aby3} is suggested due to it reducing the overall communication. \n\t\\fi\n\t\n\t2) Consider case where some of the parties should learn the cardinality of a join without a \\texttt{where} clause. %The core idea is that given the randomized encodings for these tables $\\mathbb{E}_x,\\mathbb{E}_y$, the cardinality/count is exactly $|\\mathbb{E}_x \\cap \\mathbb{E}_y|$. \n\tFirst, w.l.o.g. let us assume that \\Party{2} should learn the cardinality. The randomized encodings $\\mathbb{E}_x,\\mathbb{E}_y$ are respectively revealed \\Party{0} and \\Party{1}  as done in the standard join protocol. These encodings are then sent to \\Party{2} in a random order. \\Party{2} outputs $|\\mathbb{E}_x \\cap \\mathbb{E}_y|$ as the count/cardinality. In the event that \\Party{0} or \\Party{1} should also learn the cardinality, \\Party{2} sends $|\\mathbb{E}_x \\cap \\mathbb{E}_y|$ to them.\n\t\n\t\\item  Min/Max: We propose a recursive algorithm where the min/max of the first and second half of the rows is recursively computed. The final result is then the min/max of these two values.  Concerning \\texttt{NULL} rows, the corresponding value can be initialized to a maximum or minimum sentential value which guarantee that the other value will be propagated. The overall complexity of this approach is $O(n\\ell)$ binary gates and $O(\\ell log n)$ rounds when using a basic comparison circuit\\cite{aby3}.\n\\end{itemize}\n\nMore generally, any polynomial time function can generically be expressed using the ABY$^3$ framework\\cite{aby3}. However, the resulting efficiency may not be adequate for practical deployment.  \n\n\\iffalse\n\\section{Beyond Three Parties}\nIn some settings where many parties are providing tables to be computed on, the three party requirement with at most one corruption may not be adequate. In particular, a larger corruption threshold such as 3-out-of-5 or 4-out-of-7 may be desirable. Our protocol can naturally be extended to these setting with some caveats. First, the binary circuit based MPC protocol\\cite{highthroughput}, which our standard three party protocol relies on, can be naturally extended to these larger (honest majority) corruption thresholds. One limitation is that the number of shares is exponential in the number of parties.  Alternatively, several other protocol without this limitation such as\\cite{DBLP:conf/crypto/ChidaGHIKLN18} have been proposed. Another implementation challenge is how to instantiate share conversion that some of the aggregation steps rely on. In the three party case \\cite{aby3} provides specification. We note that such share conversions can generically be implemented using an MPC protocol but leave efficient instantiations to future work.\n\nThis change immediately implies that no minority set of corrupted parties can decrypt/reconstruct the secret shared tables. However, our three party protocol also requires \\Party{0} and \\Party{1} learning the randomized encodings in the clear. If the adversary learns both sets of randomized encodings they can infer information about the cardinality of the join. As such, our protocol offers two levels of security. When the adversary corrupts \\Party{0} and \\Party{1} the cardinality of $\\mathbb{E}_x \\cap \\mathbb{E}_y$ is revealed. Otherwise, if an honest majority is present then the view of the corrupted parties can be simulated in the semi-honest setting. \n\n\n\\fi\n", "meta": {"hexsha": "89dde716b3cbf4f4d70132bf06bc6b9294895e71", "size": 58815, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/construction.tex", "max_stars_repo_name": "vincehong/aby3", "max_stars_repo_head_hexsha": "1a5277b37249545e967fc58a9235666a2453c104", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-04T15:30:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-04T15:30:51.000Z", "max_issues_repo_path": "tex/construction.tex", "max_issues_repo_name": "vincehong/aby3", "max_issues_repo_head_hexsha": "1a5277b37249545e967fc58a9235666a2453c104", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/construction.tex", "max_forks_repo_name": "vincehong/aby3", "max_forks_repo_head_hexsha": "1a5277b37249545e967fc58a9235666a2453c104", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 110.3470919325, "max_line_length": 1079, "alphanum_fraction": 0.7057893395, "num_tokens": 18244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3051412967047408}}
{"text": "\\section{Abstract}\n\\label{sec:abstract_en}\n\nFinancial companies from all around the world have started to focus their investments in quantitative and algorithmic funds. Those methods run in server applications that execute automatic trades. It is important to distinguish high frequency trading from machine learning trading. The latter is used and analyzed in detail in the present work.\n\nThis project explains the development of a trading strategy on Bitcoins based on machine learning techniques. A pipeline proposal is shown which is based on Lopez de Prado's book (\\cite{lopez_de_prado}). Some modifications are introduced in the book's pipeline to adjust a momentum primary model on Bitcoins, and to incorporate and study features that would let estimate the size of the primary model bets (secondary model to be trained on top of the first model). The range of features to analyze goes from financial metrics derived from Bitcoin prices and volumes, to Bitcoin and blockchain related features and finally social indexes which incorporate interest and animosity towards Bitcoin itself.\n\nThe pipeline proposed in \\cite{lopez_de_prado} and implemented in this thesis rigorously handles the dataset, the involved models and finally the posterior backtesting strategies. Details about statistical foundation of the involved methods, algorithm complexity and implementation and domain explanations (such as those related to cryptocurrencies) can be found. The pipeline allows to gather enough information to compare and decide whether a propose strategy is good enough to be implemented. We will use this to compare models that introduce microstructure indexes such as SADF (Supremum Augmented Dickey Fuller) in comparison and conjunction with social indexes.\n\n\n", "meta": {"hexsha": "937ae78584c9ad69d10761e9cc9bbfc9d6f0ad7b", "size": 1763, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/abstract_en.tex", "max_stars_repo_name": "agalbachicar/swing_for_the_fences", "max_stars_repo_head_hexsha": "3871e88884a90e5c9dd80d71b20b811485007273", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/abstract_en.tex", "max_issues_repo_name": "agalbachicar/swing_for_the_fences", "max_issues_repo_head_hexsha": "3871e88884a90e5c9dd80d71b20b811485007273", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/abstract_en.tex", "max_forks_repo_name": "agalbachicar/swing_for_the_fences", "max_forks_repo_head_hexsha": "3871e88884a90e5c9dd80d71b20b811485007273", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 160.2727272727, "max_line_length": 701, "alphanum_fraction": 0.8304027226, "num_tokens": 315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5660185498374788, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.30507450096037675}}
{"text": "\\documentclass[11pt]{article}\n\\usepackage{graphicx}\n\\usepackage{amsmath}\n\\usepackage{pifont}\n\\usepackage{setspace}\n\\usepackage{hyperref}\n\\usepackage{enumitem}\n\\usepackage{color}\n\\usepackage{sectsty}\n% \\usepackage{raisebox}\n% \\usepackage{geometry}\n% \\usepackage{fancyhdr}\n% \\pagestyle{fancy}\n% \\lfoot{\\emph{CV: Christopher Harman after discussion with Dr. S. Flockton}}\n\\definecolor{darkblue}{rgb}{0.,0.,0.7}\n\\sectionfont{\\color{darkblue}}\n\\subsectionfont{\\color{darkblue}}\n\n\\oddsidemargin  -0.25in\n\\evensidemargin 0.25in\n\\textwidth      7.0in\n\\headheight     0.0in\n\\topmargin      -0.8in\n%\\textheight=9.5in\n\\textheight=10.0in\n\\onehalfspacing\n\n\\begin{document}\n\\thispagestyle{empty}\n\n\\title{Clear Cut: Algorithm Design}\n% \\author{Christopher Harman}\n\\maketitle\n\\tableofcontents\n\n\\newpage\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%% INPUT DATA DESCRIPTION %%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Input data}\nThe input data is an image of arbitrary size, $M \\times N$, where $M$ is the horizontal dimension and $N$ is the vertical dimension of the image. Most images have three channels (RGB = ``Red-Green-Blue\"), this means an array with three $M \\times N$ arrays. Images with exif data are checked and modified so that the image is imported in the intended orientation, e.g. in case the image is a photo taken from a phone camera.\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%% IMAGE SIZE REDUCTION %%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\subsection{Image size reduction}\nTo improve the efficiency of the edge detection algorithm, the image size is reduced to that the average image dimension is less than 500 pixels in length. The final image size to be thrown into the algorithm is $M_{\\text{eff}} \\times N_{\\text{eff}}$, where\n\\begin{equation}\n\\dfrac{M_{\\text{eff}} N_{\\text{eff}}}{2}<500~\\text{pxl} \\text{.}\n\\label{im_reduction_condition}\n\\end{equation}\nThe image is currently reduced slowly by max pooling. This relies on calculating the smallest kernel size and repeating the max pooling process until the condition in Equation~\\ref{im_reduction_condition} is satisfied. This can be implemented more effectively by calculating the smallest kernel that would satisfy the condition in Equation~\\ref{im_reduction_condition} after just one implementation of max pooling.\n\nAs it currently exists, the process consists of determining the smallest number that divides the height (width) of the image to return an integer. If there is no such factor, i.e. the height (width) is a prime number, the image is cropped by removing the single pixel row (column) at the $M_{\\text{eff}}^{th}$ ($N_{\\text{eff}}^{th}$) index. By definition this would result in that image dimension being divisible by 2, which is then the number of pixels of the smallest kernel in that dimension. Throughout the image reduction process, the values ~{($M_{\\text{eff}}$,~$N_{\\text{eff}}$,~$M_{\\text{kernel}}$,~$N_{\\text{kernel}}$)} are stored in a Python dictionary to keep a record of the image reduction history.\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%% EDGE DETECTION PROCEDURE %%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Edge detection procedure}\n\\subsection{\\label{sec:grad_img}The gradient image}\n\\begin{center}\n\\texttt{For Python code, refer to the {\\bf traceObjectsInImage()} function in edgeUtility.py}\n\\end{center}\nIn order to determine the edges of an image, we must choose a criteria to distinguishing a single pixel located at $(i_0,j_0)$ as being part of ``an edge''. We would refer to such pixels as ``edge pixels'' or ``non-edge pixels'' in future. This is achieved by mathematically comparing its value to those of its surrounding pixels. The simplest method to adopt is to consider only the pixels neighbouring pixels $(i,j)$, i.e. any combination of pixels that satisfy\n\\begin{equation}\ni_0-1 \\leq i \\leq i_0+1\\text{, and }j_0-1 \\leq j \\leq j_0+1\\text{.}\n\\end{equation}\nA more advanced technique could extend the range of neighbouring pixels. For a pixel not located on the perimeter of the image, it would have 8 neighbouring pixels.\n\nThe mathematical quantity we are interested in is the difference in value between a selected pixel and it's neighbouring pixels. For the simple case, an edge pixel would be identified as having a large difference in value between any adjacent neighbouring pixel and itself. This simplest case works well for an image with sharp edges, but not so well for an image with blurry edges. With eight neighbouring pixels, we would have to calculate eight gradients per pixel. It turns out that we can more efficient in calculating the gradients and only count four instead. This is because when the neighbouring pixel has the gradient calculated, it would be the same magnitude but a different sign. The sign is irrelevant for determining the ``sharpness'' between pixels. This means that the eight gradient per pixel method would double-count the number of gradients; therefore we need only calculate four gradients per pixel instead.\n\nThus for a generic pixel at $(i,j)$, the difference in value between pixels $(i-1,j-1)$, $(i+1,j)$, $(i,j+1)$, and $(i+1,j+1)$ is calculated. These four directions are a choice and are not expected to make a difference in the final result. Note that not all gradients can be calculated if the pixel under consideration sits along the perimeter of the image. That each pixel in the ``image space'' has four unique gradients calculated, means that we will obtain a ``gradient space'' of size $2M_{\\text{eff}} \\times 2N_{\\text{eff}}$.\n\n\\subsection{Dealing with image channels}\n\\subsubsection{Obtaining gradient images}\n\\begin{center}\n\\texttt{For Python code, refer to the {\\bf traceObjectsInImage()} function in edgeUtility.py}\n\\end{center}\nEach of the RGB channels have the edge detection algorithm specified in Section~\\ref{sec:grad_img} applied to them. This is achieved by writing out the results to a single array of size $6M_{\\text{eff}} \\times 2N_{\\text{eff}}$, where each channel's gradient image is offset as follows:\n\\begin{itemize}\n  \\item the Red channel gradient array exists in the domain $(0,~2M_{\\text{eff}}-1)$,\n  \\item the Green channel gradient array exists in the domain $(2M_{\\text{eff}},~4M_{\\text{eff}}-1)$, and\n  \\item the Blue channel gradient array exists in the domain $(4M_{\\text{eff}},~6M_{\\text{eff}}-1)$.\n\\end{itemize}\nRecall that we could only reduce the number of gradients per pixel if we ignore the gradients sign. Therefore, we must take care to only add up the gradient images element-wise AFTER taking the magnitude of each element first. The initial step in edge detection is to determine whether an (rgb) pixel in the reduced image is, or is not, part of an edge; this turns each pixel into a ``yes'' or ``no'' (boolean) answer. We therefore set a numerical upper and lower limit on what is an edge pixel, and what is not. We implement this through a variable parameter called \\texttt{imCut}, whereby an edge pixel is one in which the gradient lives between:\n\\begin{equation}\n255\\times \\texttt{imCut}< \\text{Gradient}_{\\text{edge pixel}} < 255\\times (1-\\texttt{imCut})\\text{.}\n\\end{equation}\nWe have found $\\texttt{imCut} = 0.07 \\pm 0.02$ to work effectively. We have found both the upper limit and lower limit are necessary to extract clear edge pixels for any image. The lower limit is understandable because it determines adjacent pixels with too similar a colour as not being an edge pixel, however, the upper limit is less trivial. We believe the upper limit is necessary to remove random fluctuations in light/darkness within an image. These may be the result of tiny defective regions of photographical film that cannot be seen by the human eye when the image view at a larger scale that the size of the defect.\n\n\\subsubsection{Returning detected edges in reduced image size}\n\\begin{center}\n\\texttt{For Python code, refer to the {\\bf mergeChannelsTracedImage()} function in edgeUtility.py}\n\\end{center}\nWe now have three gradient space arrays. However, we only want one gradient space array to say whether a single (rgb) pixel in the reduced image is an edge or not. This means we that we need to merge each of the gradient arrays into a single gradient array, and then reduce this gradient array to be the same size as the reduced image. The idea behind the merge is that \\textbf{the more channels that detect an edge, the more likely it is to be an edge}. This is in agreement with human perception that an orange boat on a blue sea is far more distinct object than a blue boat on a blue sea. We therefore simply add up each gradient image element-wise to form our final gradient image.\n\nThis final gradient image is still roughly double the width and double the height of the reduced image. We reduce the gradient image to the same size as the reduced image using max pooling of $(2 \\times 2)$-sized kernels. Therefore the final ``edge value'' of each (rgb) pixel of the reduced image is determined by the largest gradient of that pixel and its neighbouring pixel. This in turn determines whether it is an edge pixel or not.\n\n\\subsection{Cleaning the edge data}\nNow that we have two arrays of the same size, we can mask the edge image on top of the reduced image to view our current results. In doing so for a number of unique images, we observe  two main features:\n\\begin{enumerate}\n  \\item There exist spurious regions of edge pixels with a size of the order of a few pixels. \\textbf{Solution: remove tiny regions of edge data.}\n  \\item There are edge pixels around the perimeter of objects in the reduced image, but with the occasional break, whereby no edge pixels exist. \\textbf{Solution: extrapolate long regions of edge data.}\n\\end{enumerate}\n\n\\subsubsection{Removing small scale edge data}\n\\begin{center}\n\\texttt{For Python code, refer to the {\\bf edgeKiller()} function in edgeUtility.py}\n\\end{center}\nTo accomplish this task, we first need to decide what a small scale is. This is necessary for object recognition because many complicated objects are made of smaller, perhaps even more complicated objects. Fundamentally, if an object is identified as being surrounded by a continuous border of edge pixels, then the smallest object would be three pixels in size. This because the border must be at least one pixel thick and the central pixel must not be recognised as an edge (two pixels either side of a non-edge pixel in the $x$ and $y$ direction), i.e. a square drawn around the perimeter of a $3 \\times 3$ pixel grid. Practically, it is the choice of the user to specify a tolerance to the size of the object. Take the example of a cat. Users may want to extract certain features of the cat, depending on some objective scaling into the cat (see Table~\\ref{cat_table}).\n\n\\begin{table}[h]\n\\begin{center}\n\\begin{tabular}{|c|c|c|c|c|c|}\n\\hline\n{\\bf Feature/object} & {\\bf User 1} & {\\bf User 2} & {\\bf User 3} & {\\bf User 4}\\\\\n\\hline\n{\\bf Cat} & y & y & y & y\\\\\n\\hline\n{\\bf Nose} & n & y & y & y\\\\\n\\hline\n{\\bf Eye} & n & n & y & y\\\\\n\\hline\n{\\bf Iris} & n & n & n & y\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\label{cat_table}\n\\end{table}\n\nTo this end, a user may specific their pixel tolerance using the parameter \\texttt{objectTolerance}. Any edge pixels that are found within a border of size $(2\\times \\texttt{objectTolerance}+1) \\times (2\\times \\texttt{objectTolerance}+1)$, where the border does not contain any edge pixels, are killed off.\n\n% include visualisations here\n\n\\subsubsection{Expand large-length edge data}\n\\begin{center}\n\\texttt{For Python code, refer to the {\\bf edgeFiller()} function in edgeUtility.py}\n\\end{center}\nTo address the issue of small gaps within edges, we extrapolate any edges subject to number of consecutive edge pixels in a given direction. The minimum number of consecutive edge pixels required for the extrapolation to happen is embodied in the parameter \\texttt{edge\\_bias}. The extrapolation basically runs through each edge pixels and determines the number of consecutive edge pixels in each of the eight directions $(-1,-1)$, $(-1,0)$,$(-1,+1)$, $(0,-1)$, $(0,+1)$, $(+1,-1)$, $(+1,0)$,and $(+1,+1)$. If the number of edge pixels in a direction is greater than $\\texttt{edge\\_bias}$, change the first non-edge pixel in that direction to an edge pixel.\n\n% include visualisations here\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%% OBJECT EXTRACTION PROCEDURE %%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Object extraction procedure}\n\\subsection{Theoretical set up}\nRandomly pick an initial edge pixel. Determine the directions in which the neighbouring pixel is also an edge pixel. For the directions which have an edge pixel, (recursively) determine if the pixel in that same direction is also an edge pixel until it is not an edge pixel. Note down the number of edge pixels in this direction and add it to the number of edge pixels (until a non-edge pixel is found) in the exact opposite direction. This will result in four lengths - which we will call \\textit{thicknesses} - in each of the directions:\n\\begin{itemize}\n  \\item horizontal: $(-1,0)\\rightarrow (+1,0)$,\n  \\item vertical: $(0,-1)\\rightarrow (0,+1)$, \n  \\item positive gradient diagonal: $(-1,-1)\\rightarrow (+1,+1)$, \n  \\item negative gradient diagonal: $(-1,+1)\\rightarrow (+1,-1)$.\n\\end{itemize}\n\nThe shortest thickness of consecutive edge pixels at the initial edge pixel will be referred to as the \\textbf{race start line}. The length of the race start line is defined to be in the $\\hat{y}$-direction of the Cartesian coordinate system $\\hat{C}: (\\hat{x},\\hat{y})$. The initial direction of the \\textbf{race path} must have a non-zero $\\hat{x}$-component, i.e. the initial path vector is $\\vec{O}=a\\hat{x}+b\\hat{y}$, where $a \\neq 0$.\n\n\\subsection{Definition of an object}\n\\begin{center}\n\\texttt{We define an object within an image as the set of pixels that residue\\\\ within an enclosed path of edge pixels. The enclosed path must return\\\\ through the race start line with an $\\hat{\\texttt{x}}$-component that has the same sign\\\\ as that in\n\t which the path was initialised.}\n\\end{center}\nThere are two very important concepts to understand within this definition:\n\\begin{itemize}\n  \\item \\textit{... an enclosed path ...}: this means we should be able to draw a continuous path of edge pixels that start and end at the same edge pixel coordinate.\n  \\item \\textit{... $\\hat{x}$-component that has the same sign ...}: this means that the path of edge pixels must have an initial path vector with an $\\hat{x}$-component with the same sign as the $\\hat{x}$-component of the (final) path vector that crosses past the start race line. Since the path is determined by when the path has crossed the start race line, it means the path could not have gone back on itself whereby it remains along the ``same edge''. % Need to include visualisations here of starting at the bottom of a hangmans knot, and starting at the top of the knot.\n\\end{itemize}\n\n\\subsection{Stepping into the edge path}\nThe edge path cannot be stepped by an entirely random process as the code would take too long to run and possible return nonsense (see Brownian motion). However, neither can the steps be too systematic as this may guarantee that some forks in the edges are never taken, thus losing potential objects. At each step, there must be some notion of moving in a direction roughly orthogonal to the shortest pixel thickness that is also away from pixel at the previous step. Therefore, the step is chosen to be close to the vector orthogonal to the start line for that current pixel, but with a small random fluctuation in the ($\\hat{y}$-)direction of the start line.\n\n\\begin{figure}[h!]\n\\centering\n\\includegraphics[width=15.0cm]{visuals/edge_id_aids/Path_algorithm.png}\n\\caption{\\small{Visualisation of the random path method. This image shows two paths starting at the same initial edge pixel (white square) with the same steps up $i=3$. At this point the path the random vector off the $i=3$ start line may either go into the upper or lower fork of the edge. The green cone has been drawn to detail that the random path vector has a specified length (the radius of the cone) but the random direction is constrained to within the green cone.}}\n\\label{singleField_PtPlot_fig}\n\\end{figure}\n\n\n\n\\end{document}", "meta": {"hexsha": "7f54b932a8ba7ea5ee8f2c6b44fa3b8b65fed955", "size": 16569, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "documentation/clearCut_algorithm_design.tex", "max_stars_repo_name": "chrispdharman/clear-cut", "max_stars_repo_head_hexsha": "799398172861bc2e98465e198b68a2af26abb461", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "documentation/clearCut_algorithm_design.tex", "max_issues_repo_name": "chrispdharman/clear-cut", "max_issues_repo_head_hexsha": "799398172861bc2e98465e198b68a2af26abb461", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-05-06T17:44:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:19:26.000Z", "max_forks_repo_path": "documentation/clearCut_algorithm_design.tex", "max_forks_repo_name": "chrispdharman/clear-cut", "max_forks_repo_head_hexsha": "799398172861bc2e98465e198b68a2af26abb461", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 86.296875, "max_line_length": 928, "alphanum_fraction": 0.7335385358, "num_tokens": 4032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.30507449306892004}}
{"text": "\\documentclass[a4paper]{article}\n\n%\n% Packages\n%\n\n%% styling for this document\n\\usepackage{tex/docstyle}\n\n%% Test\n\\usepackage{blindtext}\n\n%\n% Metadata\n%\n\n\\title{A Template for a Notebook}\n\\author{\n  Naoki Pross\n}\n\\date{\\today}\n\n%\n% Document\n%\n\n\\begin{document}\n\\maketitle\n\\tableofcontents\n\n\\section{Introduction}\n\\blindtext\n\\[\n  U = R \\cdot I \\iff\n  \\int_L \\mathbf{E \\cdot \\hat{l}} \\mathrm{d}l = \n  R \\int_{S} \\sigma \\mathbf{E \\cdot \\hat{n}} \\mathrm{d}s\n\\]\n\n\\newpage\n\n\\section{Atomic structures}\n\\makefigure[A sample figure]{6cm}\n\\makegrid{18}\n\n\n\\end{document}\n", "meta": {"hexsha": "b0eb6c9b548f970a18fefda68cbe293464eed23a", "size": 561, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "notebook/Doc.tex", "max_stars_repo_name": "NaoPross/TexTemplates", "max_stars_repo_head_hexsha": "bf74f15ff9f211a5dd11e7a102426019b6289024", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebook/Doc.tex", "max_issues_repo_name": "NaoPross/TexTemplates", "max_issues_repo_head_hexsha": "bf74f15ff9f211a5dd11e7a102426019b6289024", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebook/Doc.tex", "max_forks_repo_name": "NaoPross/TexTemplates", "max_forks_repo_head_hexsha": "bf74f15ff9f211a5dd11e7a102426019b6289024", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 11.9361702128, "max_line_length": 56, "alphanum_fraction": 0.6809269162, "num_tokens": 190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.30507449306892004}}
{"text": "% Allow relative paths in included subfiles that are compiled separately\n% See https://tex.stackexchange.com/questions/153312/\n\n\\providecommand{\\main}{..}\n\\documentclass[\\main/thesis.tex]{subfiles}\n\\externaldocument{}\n\n% \\iffalse\n% - Capturing and playing sound, digitally\n% - Representation (single frame vs multi(spectrum))\n% - Creating sound\n%     - Sound can be created functionally\n%     - sound can be created piece by piece \n% - a quick history/summary of computer music technology (the parts of it that are relevant to our project)\n%     - Define vsts, synth parameters, filters, eqs since some they're involved in some of the previous works.\n% - Past work involving heuristic search and digital synths\n% - Past work involving generative neural nets\n% - Our work and how it's different or extends past work \n%     - How it can be replicated\n% \\fi\n\n% todos:\n% properly use amplitude and magnitude and power\n% haven't described timbre \n% make reconstruction wave include multiple waveforms and how they go missing if sampling rate too slow\n% haven't described nyquist frequency\n    \n\\begin{document}\n\n\\chapter{Background and Related Work}\n\\label{section:background}\nThis chapter aims to provide a background for the subsequent chapters by providing a quick overview of four important topics:\\\\ \n\\begin{enumerate}[label=(\\roman*)]\n\\item Digital sound, its features, and concepts that have been fundamental to our work.\n\\item Common digital synthesis techniques.\n\\item The applications of artificial neural networks (ANNs) for feature extraction and sound production. Although similar results can be yielded from either approach, we distinguish ANN based techniques from tradition digital signal processing (DSP).\n\\item Related works and their relative similarities and distinctions.\n\\end{enumerate}\n\\section{Digital Audio: Sound from Numbers}\n\\label{sec:digital_audio}\nSound is the result of a series of physical events. Most of what we hear is the product of physical disturbances, causing vibrations in our mutually shared, immersive mediums. Sound waves are vibrations traveling through air as part of an expanding, spherical wave front, exponentially losing intensity as they travel away from the source~\\cite{cook1999chap4}. \n\\\\\n\n% [graph describing wave amplitude, phase and frequency here]\nA sound wave can be viewed as the result of a function which governs amplitude through time, where time and amplitude exist in continuous dimensions. Waves can be approximated via a series of samples, associating time steps to a discrete range of amplitude values. \nGiven a wave generation method, computers can make sound by sending a series of discrete values to a digital to analogue converter(DAC), which in turn can\ncreate vibrations within a speaker.  \\textit{Digital synthesis} of audio is the process of creating these discrete values. \n\\\\\n\n\\subsection{Sampling Rates and Quality of Digital Audio}\n\\label{sec_sampling_rates}\nIn 1963, Mathews wrote on the potential and utility of computers as digital instruments~\\cite{mathews1963digital}. He presented a snapshot of digital audio technology of his time and made predictions on what would be possible in the future~\\cite{mathews1963digital}. This work by Mathews makes the robust foundations of digital signal processing apparent. Many of the techniques described by Mathews have not only remained popular and relatively unchanged, but also benefited from the increase of computational power throughout the decades~\\cite{mack2011fifty,smith1991viewpoints}. For instance, Mathews described a general method for computers to capture and internally represent audio: by discretely sampling continuous pressure waves of sound and recreating the sound from the recorded numbers. \n\nSound can take on the physical characteristics of a waveform~\\cite{cook1999chap4}. Imagine the curve shown in Figure~\\ref{fig_sampling_rate} is representative of a sound wave we would like to digitally capture. As the sound travels through a microphone, sensors record samples of information about it at fixed intervals. This means that the original, analogue waveform is now recorded as a discrete, digital signal. Each recorded sample would represent the amplitude of the wave at a time-step. The more packets of information we get, the better our digital recreation of the original sound.\n\nIn this context, \\textit{sampling rate}, is an important feature of digital sound, referring to the number of samples per second of audio (measured in hertz, or Hz). Sampling rate is not the only important factor when recording audio as it is important to record with not just speed, but also precision. Assuming perfect sensors, precision is the range of possible values we can assign to each sample. It is determined by bit depth: the number of bits we have to represent the values of each sample.  Today, standard quality audio often refers to sampling rates of 44.1 kHz and 48 kHz and bit depth of 16 (that is, $2^{16}$ discrete values), while \\enquote{high quality} audio indicates an increase in bit rate or bit depth~\\cite{reiss2016meta}. Although subject to diminishing returns, high quality audio (e.g., 96 kHz/24-bit) may be preferable to most musicians and audio-engineers. In a meta-analysis of digital sound perception, Reiss found a small but statistically significant portion of people are able to discriminate the effect of standard and high quality audio with no prior training, and a dramatically higher detection rate after extensive training~\\cite{reiss2016meta}. \n\n\n\\begin{figure}[tbp]\n\n\\centering\n\\includegraphics[width=1\\linewidth,angle =-90 ]{images/periodic_function_decimation.png}\n\\caption{Inadequate sampling rates can make reconstruction ambiguous. While reconstruction is possible in this case, consider the case when multiple signals with varying frequencies are overlapped, or the case when samples are further apart than 1 wave length.} \n\\label{fig_sampling_rate}\n\\end{figure}\n\n\n\\subsection{Loudness, Amplitudes and Envelopes}\n\\label{sec:adsr}\nLoudness is a subjective description of a sound's intensity or energy levels. It varies based on the complexity of sounds, the frequencies present, and hearing ability of the listener~\\cite{fletcher1933loudness,cook1999chap6}. It can only be measured relatively, by establishing a benchmark sound and surveying populations on the relative intensities~\\cite{cook1999chap6}. Since loudness and intensity of sound correlate with the amplitude of digital waveforms (the values assigned to the samples), an imperfect but convenient alternative method for inferring the loudness of digital sounds is to compare relative amplitudes. A common function for inferring the loudness of digital signals is to apply the Root Mean Square (RMS) function to its samples~\\cite{zwicker1977procedure}. \n\nSounds typically vary in intensity as they unfold. This change in intensity is often described by the \\textit{envelope} of the sound, particularly in shorter samples. For digital sounds, Mitchell describes the envelope as either of the borders (since samples typically take the range of -1 to 1) that are created by graphing a signal and connecting the local absolute peak values~\\cite{mitchell2009basicsynthChap6}. In electronic music production, the envelope is generally defined using 4 features: Attack, Decay, Sustain, and Release (ADSR). Attack describes how quickly the peak loudness is reached. Decay for how quickly the sound drops to sustain level. Sustain is the duration of sustaining intensity (for example, how long a finger is kept on a piano key). Release describes the speed of fading to silence (how fast the sound decays once the piano key is released). We will describe our method of approximating the envelope of sounds in Section~\\ref{sec:fourier_transforms}.\n\nEnvelopes can be mathematically described and used to shape signals. A common approach in digital sound synthesis is to output all samples at a consistent amplitude and apply an envelope later down the synthesis chain. Digital and analog synthesizers often have built-in ADSR modules to shape the volume of the output and other parameters.  \n\n% [Graph of envelope shaping a signal]\n% note: make sure you're using terms signal and waveform properly\n\\subsection{Frequency, Pitch and Spectrograms}\n\\textit{Frequency} is used to describe number of repetitions within a time-frame, or how frequently a cycle is repeated. As discussed before, frequency of an audio signal is often measured in unit of \\textit{hertz} (cycles per second). Most sounds, particularly those from non-virtual sources, are a combination of multiple different pressure waves with different frequencies and amplitudes. \\textit{Pitch}, is a perceptual property that is tied to the frequencies present in a sound. How we perceive and describe the pitch of a sound (e.g., high-pitched vs low-pitched) is heavily dependent on the characteristics (frequency, amplitude, duration, etc) of the waveforms it contains. Some sounds, such as piano keys or pure tones have a discernible pitch. Others, such as \\enquote{pink noise} or the sound of rain, do not. Yet another factor to consider is the hearing ability of the subject, which varies between people based on factors such as age, environment, and musical training~\\cite{reiss2016meta,alain2007age,newman2012grm7}. \n\n% We often do not have access to the time-variant systems which create sounds. If we have access to a recording of their outputs (i.e digital sound), we can make approximations about their characteristics. \nSpectrograms are graphs used to depict the duration and amplitude of frequencies present in a sound. To create spectrograms, sound must be decomposed into a set of simpler functions. A common method for the breakdown of complex, time-variant functions is the Fourier transformation and its many variations. One such method is the discrete Fourier transformation (DFT) and the inverse DFT. DFT and inverse DFT can convert digital sound from its time domain representation (sequence of samples) to its frequency domain representation (sets of frequency ranges and their amplitude) and vice versa. We share some examples along with our methodology of creating spectrograms in Section~\\ref{sec:fourier_transforms}.\\\\\\\\\n\n% [spectrogram figures]\n\n% https://en.wikipedia.org/wiki/Frequency_domain#/media/File:Fourier_transform_time_and_frequency_domains_(small).gif\n\n\\section{Digital Audio Synthesis}\n\\label{sec_digital_synthesis}\nThe phenomena of sound at intensities we commonly encounter can be described as a product of a \\textit{linear system} of functions~\\cite{cook1999chap4}. A linear system is a system where the transformation of overlapping inputs is equal to the sum of the separately transformed inputs~\\cite{lyons2004understandingChap1,cook1999chap4}. In a linear system $\\mathcal{S}$ with valid inputs and outputs $x(i)$ and $y(i)$, if we have:\n\n\\begin{equation}\n \\mathcal{S}(x(i_1)) \\xrightarrow{generates} y(i_1)\n\\end{equation}\n\\begin{center}\n    and\n\\end{center}\n\\begin{equation}\n\\mathcal{S}(x(i_2)) \\xrightarrow{generates}y(i_2)\n\\end{equation}\n\nThe output of the system given both inputs is the sum of the individual outputs, or:\n\\begin{equation}\n \\mathcal{S}(x(i_1)+x(i_2)) \\xrightarrow{generates} y(i_1)+y(i_2) \n\\end{equation}\n\\\\\nThis concept has important implications digital audio creation and analysis. Simple tones can be combined to create complex sounds, and complex sounds can be broken down for easier analysis~\\cite{lyons2004understandingChap1}. It also allows experiments with simple sine waves to remain relevant in complex sound domains~\\cite{cook1999chap4}.\n\n% [graph of addition of two sine waves making a complex sine wave ]\n% \\\\\n\nVarious sound synthesis techniques have been developed by treating sound as a sequence of values. Linear systems are commonly used in creation of musical tones, while non-linear systems are used for introduction of distortion and noise where needed. In their taxonomy of digital synthesis techniques, Smith defines four families of algorithms: algorithms that process and modulate existing sounds (e.g., granular synthesis, wavelets), spectral models that aim to create a particular spectrum of sound (e.g., additive, subtractive), physical models which emulate the physics of real instruments, and abstract models (e.g., wave shaping, Karplus-Strong), often used for adding harmonics or distortion to simple sound signals~\\cite{smith1991viewpoints}. \n\nSynthesizers are engines of synthesis that make use of one or more of these techniques for sound generation. Selection of the appropriate synthesis method depends not only on the expectations for the end product, but also the features of the synthesizer itself. Whether in goal oriented tasks such as text-to-speech or in creative endeavors such as ambient-noise generation, it is often desirable to work with systems that are quick, adaptable and tractable. For example, one might desire a text-to-speech system where slight changes to input parameters can introduces slight changes to the speech patterns, utterances, voices, etc. This ability to quickly modify and audition sounds becomes a necessity when the synthesizer is being used as a creative instrument in of itself, rather than an emulator for existing instruments and sounds. \n\nOften used methods of digital sound generation are \\enquote{additive} and \\enquote{subtractive} synthesis, umbrella terms for some of the most simple and common methods of digital synthesis~\\cite{mitchell2009basicsynthChap1}. \nIn additive synthesis, sounds are built as a sum of signals, where signals are outputs of oscillators (periodic wave generators).  In subtractive synthesis, segments of a complex signal are removed until a desired sound is reached. A chain of one or more \\textit{digital filters}, which can subtract or reduce frequency ranges, are often used in subtractive synthesis. Digital \\textit{low-pass filters} lower the amplitude of signals with frequencies higher than a given \\textit{cutoff}, while \\textit{high-pass} filters remove lower than threshold frequencies. It is not uncommon for percussive sounds to have noisy, chaotic high frequency content during their short attack period, followed by harmonic low/medium frequencies~\\cite{lakatos2000common}.\n\n\n% \\subsection{Analog Synthesizer}\n% Talk about analog synthesis briefly, so the word synthesizer feels less abstract...\n\\subsection{Virtual Synthesizers}\nNearly 5 decades ago, Mathews claimed that any sound can be recreated via a computer by high frequency sampling of pressure waves~\\cite{mathews1963digital}. He noted that since \\enquote{a very high sampling rate is required...if this process is to be useful musically, programs for generating samples from the parameters of notes must be written}~\\cite{mathews1963digital}. The methods of synthesis discussed here are a major component of such programs. With the exception of physical synthesis, modern chips are more than capable of simultaneously running many instances of these algorithms. To further assist with their musical utility, the majority of digital synthesis systems work in tandem with programs such as Musical Instrument Digital Interface (MIDI), which can modulate the parameters of these synthesis methods by modulating information pertaining to ADSR and other note characteristics, often in real time~\\cite{moog1986midi}.  \n\n The rise of Digital Audio Workstations (DAWs)~\\cite{leider2004digital} and Virtual Studio Technology (VST) plug-ins~\\cite{tanev2013virtual} have rapidly transformed the sonic and material landscape of music production in the recent years. Coupled with this rise in popularity is a vast array of commercial products and services which cater to the need of amateur and professional music producers for unique sounds, often by provision of audio samples; one-shot drum samples, long sustained notes (referred to as pads or textures), and loops (percussive or melodic) are common deliverables. Two notable examples of these commercial services are \\textit{loopmasters}\\footnote{loopmasters.com} and \\textit{splice.com}\\footnote{splice.com}. VST plug-ins can emulate analogue synthesizers and effects,  however,  due to their (often) complex interface, some producers may find VST plugins daunting to work with from scratch. In many cases, VST plug-in vendors or unaffiliated enthusiasts sell additional presets for these plugins, targeted towards producers who do not have the time or interest in creating their own. The flexibility of the VST technology allows producers to modify these presets until their desired sound is reached.\n \n\\section{Neural Networks And Sound}\n\\label{bg:NN}\nIn Section~\\ref{sec:digital_audio}, we defined digital synthesis as the \\enquote{process of generating discrete values which approximate sound waves}. We also established that manual generation of these values at high sampling rates is near impossible; a problem which has motivated a wide variety of synthesis techniques which aim to create signals within a linear (or mostly linear) system. The recent exponential increase in computing power has been coupled with a wide range of research in probabilistic sound generation, mainly via generative neural networks. \n% deterministically, if the input parameters to the system do not change, the output of the system will remain the same \\footnote{talk about noise generation methods and seeding}.\n\nArtificial Neural networks (ANNs) map inputs to outputs via a large network of parameters and activation functions. Given the right network shape and parameter weights, they can approximate a large set of functions~\\cite{cybenko1989approximation,cardaliaguet1992approximation}. ANNs are often deployed when we do not have access to the system of functions which guide a process, but a mapped set of inputs and the corresponding outputs are available. Given this set, the parameters of a neural network can be tuned for approximating the effect of the system on any valid input. The architecture of the neural network (e.g., number of layers, connections, activation functions) is often selected via trial and error ~\\cite{bergstra2012random,bergstra2011algorithms,ba2013adaptive}. By definition, these approximations will never be more accurate than the system that is being approximated. \n\nSince their emergence in the 1950's, research on ANNs has gone through several eras of stunted growth~\\cite{basheer2000artificial,anderson1988neurocomputing}.  In the last decade, the increase in the affordability of high performance graphic cards has been coupled with a major resurgence of interest for ANNs and the emergence of a number of domain specific variations of the traditional ANN architectures (see Section~\\ref{related}). \n\nGenerative neural networks (GNNs) are utilized for the completion of sequences of values; often by taking an incomplete sequence as input and outputting the most likely value for the next step. The WaveNet architecture introduced in 2016 is considered a seminal breakthrough in the usage ANNs for sound synthesis~\\cite{oord2016wavenet} by surpassing state of the art speech synthesis techniques, which create outputs with the the combination of previously recorded audio snippets~\\cite{schwarz2007corpus}. When trained on a large corpus of audio samples, GNNs such WaveNet can learn the \\enquote{predictive distribution for each\naudio sample conditioned on all previous ones}~\\cite{oord2016wavenet}. Once this distribution is learned, it can be used to create sounds 1 sample at a time, a slow process, as Mathews predicted~\\cite{mathews1963digital}. \\\\\n% Parallel WaveGAN has only 1.44 M parameters and can generate 24 kHz speech waveform 28.68 times faster than real-time on a single GPU environment. Perceptual listening test results verify that our proposed method achieves 4.16 mean opinion score within a Transformer-based text-to-speech framework, which is comparative to the best distillation-based Parallel WaveNet system.\n\n\n% \\section{Goal Oriented Novel Sound Generation}\n\n\n% \\subsection{Tool Selection}\n% We define \\enquote{goal oriented novel sound generation} as any work that seeks to implement a system that is capable of generating novel sounds with a desired characteristic. Based on our review of relevant works, we believe that \\enquote{goal oriented audio generation} necessitates two essential components: A tool-set for the analysis of sound and a tool-set for creation of sound. As a result, we base our work around learning of the distinguishing features of various sound groups (i.e different types of drums) and using the learned features for generation of sound. In Section~\\ref{sec_methodology} we introduced these components as the virtual ear and virtual synthesizer. \n\n%  Thus far we have discussed various techniques at our disposal for the implementation of a virtual ear and synthesizers. In the upcoming Sections, we will discuss the implementations and the subsequent results. Here, we will review a variety of works which fall under our definition of \\enquote{goal oriented novel sound generation}. Particularly, we are interested in a discussion of goals, chosen methods for the feature extraction, and chosen methods of sound synthesis. \n\n\\subsection{Related Works}\n\\label{related}\n\n\\begin{center}\n\\begin{table}[]\n% \\resizebox{\\linewidth}{!}{\n\\begin{tabular}{||c c c c||} \n\\hline\nwork & feature extraction & synthesis & specilization  \\\\\n\t\\hline\nOord et al.~\\cite{oord2016wavenet} & CNN & CNN &Speech \\\\ \n\t\\hline\nYamamoto et a.l~\\cite{yamamoto2020parallel} & GAN & GAN&Speech  \\\\ \n\t\\hline\nAouameur et al.~\\cite{aouameur2019neural} & Latent layer& Decoding of Latent Layers & Percussion  \\\\ \n\t\\hline\nRamires et al.~\\cite{ramires2020neural} & Latent layer & FeedForward Network & Percussion  \\\\ \n\t\\hline\nYee-King et al.~\\cite{yee2018automatic} & LSTM on Paremters & DSP & Synth Pads  \\\\ \n\t\\hline\n\\end{tabular}\n%}\n\\caption{Quick reference for related works}\n\\end{table}\n\\end{center}\n\nANN or DSP approaches can be taken towards the implementation of a virtual ear and a virtual synthesizer. The recent development of ANN frameworks has led to works which have utilized ANNs for both components~\\cite{oord2016wavenet,yamamoto2020parallel,ramires2020neural}. Also common are works which have leveraged a mixture of both approaches, often by utilization of ANNs for the virtual ear and DSP methods for synthesis~\\cite{aouameur2019neural,yee2018automatic}.\n\nMany deep neural network models have been proposed and utilized for the purpose of signal generation in recent years. WaveGans and WaveNet have been subject to significant improvements and experiments since their proposal~\\cite{nsynth2017,yamamoto2020parallel,oord2017parallel}. Specifically for the generation of percussive sounds, a recent work by Aoumaeur et al.~\\cite{aouameur2019neural} utilizes variational AutoEncoders (VAE's) for generation of drum sound spectrograms, which are then converted to sound using a Multi-head CNN model~\\cite{aouameur2019neural}. Another recent work by Ramires et al.~\\cite{ramires2020neural} also uses neural networks for this purpose, where a feedforward neural network capable of creating sounds is guided by a small number of parameters which represent the producer's desired characteristics for a drum sound. \n\nAutomatic programming of virtual synthesizers has also been a topic of interest. Genetic Algorithms have long been utilized for the generation of new sounds with various sound-engines~\\cite{johnson1999exploring,dahlstedt2001creating,hornermachinetongues,macret2012automatic}. More recent work by Yee-King et al.~\\cite{yee2018automatic} used Long Short-Term Memory (LSTM) models and genetic algorithms to find the exact parameters used to create a group of sounds. The sounds approximated were made by the same virtual synthesizer, not an external source; making the eventual replication certain even with random search. In addition, the work by Yee-King et al.~\\cite{yee2018automatic} is generally more focused on pads and textures rather than drums, and feature matching appears to not be concerned with the envelope of the sounds but rather the frequency content within arbitrary time windows. Yet another recent work by Esling et al. used a large dataset of over 10,000 presets for a commercial VST synthesizer to learn a latent parameter space which can be sampled for creation of new programs for audio synthesizers~\\cite{esling2019universal}. This bespoke latent space requires large amounts of synthesizer programs for the initial training, and cannot be used for other virtual synthesizers. In the work presented here, we take a different approach to automatic programming of synthesizers by aiming for rapid approximation of percussion sounds with no previous knowledge about the sonic capabilities of our virtual synthesizer and exploring the actual parameter space rather than its latent representation. Unlike previous related works, no prior examples of audio made by the synthesizer nor examples of manually generated programs are needed for our approach. Any synthesizer can be integrated into our system so long as \\begin {enumerate*} [label=\\itshape\\alph*\\upshape)]\n  \\item its parameters are known,\n  \\item the system can randomly modify its parameters, and\n  \\item The system can render and extract the sound output for virtual listening tests.\n\\end{enumerate*}  \nThese requirements are not strict as VST synthesizers meet these expectations by design, giving our project a large scope of applicability. \n\\end{document}\n", "meta": {"hexsha": "386af1bb6d57afa7441b4b60193c80c20adcd76a", "size": 25486, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/2_background.tex", "max_stars_repo_name": "abramhindle/SSS_thesis", "max_stars_repo_head_hexsha": "fcce1b5b7cc97fbb803e8ef121fdfcccb039d12f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tex/2_background.tex", "max_issues_repo_name": "abramhindle/SSS_thesis", "max_issues_repo_head_hexsha": "fcce1b5b7cc97fbb803e8ef121fdfcccb039d12f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/2_background.tex", "max_forks_repo_name": "abramhindle/SSS_thesis", "max_forks_repo_head_hexsha": "fcce1b5b7cc97fbb803e8ef121fdfcccb039d12f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 137.0215053763, "max_line_length": 1882, "alphanum_fraction": 0.808875461, "num_tokens": 5558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.30507449306892004}}
{"text": "\\documentclass[]{spie}  %>>> use for US letter paper\n%\\documentclass[a4paper]{spie}  %>>> use this instead for A4 paper\n%\\documentclass[nocompress]{spie}  %>>> to avoid compression of citations\n\n\\renewcommand{\\baselinestretch}{1.0} % Change to 1.65 for double spacing\n\\let\\proof\\relax \n\\let\\endproof\\relax\n\\usepackage{amsmath,amsfonts,amssymb,amsthm}\n\\usepackage{graphicx}\n\\usepackage[colorlinks=true, allcolors=blue]{hyperref}\n\\usepackage{chngcntr}\n\\usepackage{hyperref}\n\\usepackage{courier}\n \n\\counterwithin{figure}{section}\n\\counterwithin{table}{section}\n\n\\DeclareMathAlphabet{\\pazocal}{OMS}{zplm}{m}{n}\n\n\\newtheorem{prop}{Proposition}\n\\theoremstyle{definition}\n\\newtheorem*{defn*}{Definition}\n\\newtheorem{defn}{Definition}\n\n\\newcommand{\\ax}{\\vec{x}}\n\n\n\\title{Python code description of the Feature Based Scheduler}\n\n\\author[a]{Elahesadat Naghib}\n\n%\\authorinfo{Further author information: (Send correspondence to E. N.)\\\\ E.N.: E-mail: enaghib@princeton.ed\\\\  R.J.V.: E-mail: rvdb@princeton.edu}\n\n% Option to view page numbers\n\\pagestyle{plain} \n \n\\begin{document} \n\\maketitle\n\n%\\begin{abstract}\n\n%Feature-based Scheduler offers a sequencing strategy for ground-based telescopes. This scheduler is designed in the framework of Markovian Decision Process (MDP), and consists of a sub-linear online controller, and an offline supervisory control-optimizer. Online control law is computed at the moment of decision for the next visit, and the supervisory optimizer trains the controller by simulation data. Choice of the Differential Evolution (DE) optimizer, and introducing a reduced state space of the telescope system, offer an efficient and parallelizable optimization algorithm. In this study, we applied the proposed scheduler to the problem of Large Synoptic Survey Telescope (LSST). Preliminary results for a simplified model of LSST is promising in terms of both optimality, and computational cost.\n\n%\n%\\vspace{1cm}\n%\\end{abstract}\n%\n%\\keywords{Telescope scheduler, Observation scheduling, Observing strategy, LSST, Decision making, Evolutionary Algorithm, Optimal control, Optimization}\n\n\n\\begin{center}\n\\textbf{Key terms and notations}\\\n\\noindent\\rule{\\textwidth}{0.4pt}\n\\end{center}\n\\begin{tabular}{ l l  }\n$t$& GMT time in Julian Date,\\\\ %$2459215.5 \\leq t \\leq 2462867.5$ i.e. from January 1, 2021, to January 1, 2031\\\\\n$\\tau_s(t)$& beginning of the night that $t$ lies in,\\\\\n$\\tau_e(t)$& end of the night that $t$ lies in,\\\\\n$id(t)$& ID of the field that is visited at $t$, $id \\in \\{1,2,3,...,4206\\},$\\\\\n$\\theta_{l}(i,t)$& time of the last visit of field $i$ before $\\tau_s(t)$, $\\theta_{l}(i,t) = \\infty$ if field $i$ is not visited before $\\tau_s(t)$,\\\\\n$\\theta_{l}^N(i,t)$& time of the last visit of field $i$ between $\\tau_s(t)$ and $t$, $\\theta_{l}^N(i,t) = \\infty$ if field $i$ is not visited in this interval,\\\\\n$n(i,t)$ & number of the visits of field $i$ before $\\tau_s(t)$\\\\\n$n^N(i,t)$ & number of the visits of field $i$ between $\\tau_s(t)$ and $t$, $0 \\leq n^N(i,t) \\leq 3$\\\\\n$SM_{i,j}$& slew time from field $i$ to field $j$, $SM \\in \\mathbb{R}^{4206 \\times 4206}$ is a given slew matrix,\\\\\n$alt(i,t)$ & altitude of the center of field $i$ at $t$, $-\\frac{\\pi}{2} \\leq alt(i,t) \\leq \\frac{\\pi}{2}$,\\\\\n$ha(i,t)$ & hour angle of the center of field $i$ at $t$, $-12 \\leq ha(i,t) \\leq 12$\\\\\n$\\tau_{rise}(i,t)$ & rising time of field $i$ above the 1.4 airmass horizon at current night, $\\tau_{rise}(i,t) = -\\infty$ if $i$ never sets down,\\\\\n$\\tau_{set}(i,t)$ & setting time of field $i$ below the 1.4 airmass horizon at current night, $\\tau_{set}(i,t) = \\infty$ if $i$ never sets down,\\\\\n$M_{\\phi}(t)$ & percent of the Moon's surface illuminated at $t$,\\\\\n$M_{sep}(i,t)$ & Moon's separation from field $i$ at $t$, $0 \\leq M_{sep}(i,t) \\leq \\pi$,\\\\\n$W_1,~W_2$ & given constant time window in which a revisit is valid, $0 < W_1 < W_2$\\\\\n$time slots$\\\\\n$visibility$\\\\\n$brightness$\\\\\n\\end{tabular}\\\\\n\\noindent\\rule{\\textwidth}{0.4pt}\\\\\n\n\\section{FB scheduler code in Summary}\\label{sec:intro}  \nCode repository on github: \\href{https://github.com/elahesadatnaghib/LSSTschedulerV2} {FB Scheduler}\n\n\\textbf{Main files}:\n\\begin{itemize}\n\\item \\textbf{CreatDB.py}:  creates the database, tables, data structure, and feeds the model parameters into the database.\n\\item \\textbf{FieldDataGenerator.py}: evaluates  fields' predictable data such as altitude, at certain time intervals and writes them on the database. \n\\item \\textbf{FBDE.py}: is where the heart of the scheduler is. it (1) reads the data in, stores the field data into field objects, (2) for each visit, loops over the field objects and (3) update the timing and the fields for the next visit decision.\n\\item \\textbf{UpdateDB.py}: reads the out put of FBDE.py (the visit sequence), (1) evaluates the statistics and history dependent variable required for the next episode scheduling and (2) writes them into the database \n\\end{itemize}\n\n\\newpage\n\\section{FB scheduler code in details}\n\\vspace{1cm}\n\nClass DataFeed\\\\\n\\indent connect to database \\\\\n\\indent read in ID, RA, Dec, Science label, $\\theta_{l}(i,t)$, and $n(i,t)$ of all fields\\\\\n\\indent read in $alt(i,t)$, $ha(i,t)$, visibility, cloud coverage, and brightness of the fields for all time intervals\\\\\n\\indent read in model parameters: $\\infty$, $\\epsilon$, Exposure time, $W_1,~W_2$, maximum number of visit per night\\\\\n\\indent read in slew times from file\\\\\n\\indent create and initialize field(\\textit{FiledState}) objects, one object for each field\\\\\n\\indent create episode(\\textit{EpisodeStatus}) object, one object for one episode of scheduling (mostly a night)\\\\\n\n\n\\noindent Class Scheduler(DataFeed)\\\\\n\\indent scheduler\\\\\n\\indent \\indent initialize episode\\\\\n\\indent \\indent create output sequence structure\\\\\n\\indent \\indent $while~ t <$ end of the episode\\\\\n\\indent \\indent \\indent $for$ all fields\\\\\n\\indent \\indent \\indent \\indent update field feasibility\\\\\n\\indent \\indent \\indent \\indent evaluate cost of feasible fields\\\\\n\\indent \\indent \\indent make the decision of next visit based on the costs\\\\\n\\indent \\indent \\indent simulate the visit \\{evaluate the visit time, update the target field object\\}\\\\\n\\indent \\indent \\indent record visit in a text file and in the output array\\\\\n\\indent \\indent \\indent update the episode \\{update $t$, update current field, update current filter\\}\\\\\n\\indent \\indent \\indent update all fields variable\\{$alt(i,t)$, $ha(i,t)$, visibility, cloud coverage, and brightness, $SM_{i,current field}$\\}\\\\\n\\indent \\indent save the output array containing sequence of the visits for the episode\\\\\n\n\n\\noindent Class EpisodeStatus\\\\\n\\noindent \\texttt{keeps track of the timing and other changing variables with time}\\\\\n\\indent initial variables: \\{$\\tau_s(t)$, $\\tau_e(t)$, time intervals where the fields data are calculated at\\}\\\\\n\\indent updatable variables: \\{$t$, decision number, last visited field, current filter\\}\\\\\n\n\n\\noindent Class FieldState\\\\\n\\noindent \\texttt{keeps track of the state of each field}\\\\\n\\indent initial variables for the $i^{th}$ object (a field): \\{ID, RA, Dec, Science label, $\\theta_{l}(i,t)$, and $n(i,t)$\\}\\\\\n\\indent data stored in the $i'th$ object (a field):\\\\\n\\indent \\{$alt(i,t)$, $ha(i,t)$, visibility, cloud coverage, and brightness, for all time slots, and $SM_{i, all other fields}$\\}\\\\\n\\indent updatable variables:\\\\\n\\indent \\{$alt(i,t)$, $ha(i,t)$, visibility, cloud coverage, and brightness, for the current time, $SM_{i,current field}$\\}\\\\\n\\indent updatable variables by calculation: \\{time since last visit, time to become invisible, feasibility, cost\\}\n\n\n\\newpage\n\\section{Run the scheduler}\n\\vspace{1cm}\n\n\\subsection{Required packages}\nCode is developed in Python2.7.10, and the following packages are required to be installed:\n\n\\begin{itemize}\n\\item PyEphem\n\\item Numpy\n\\item SQLite3\n\\item JSON\n\\item Pandas\n\\item time\n\\item Matplotlib\n\\item ProgressBar\n\\end{itemize}\n\n\n\\subsection{Required data}\nLabeled field information: \"/NightDataInLIS/Constants/fieldID.lis\", can be downloaded \\href{https://www.dropbox.com/s/0dfuuffx9aoyfix/fieldID.lis?dl=0}{here}\\\\\nSlew matrix: \"/NightDataInLIS/Constants/slewMatrix.dat.lis\", can be downloaded \\href{https://www.dropbox.com/s/6gdyv4pofzb57vz/slewMatrix.dat?dl=0}{here}\n\n\n\n\n\\subsection{Quick start with FB scheduler code}\n\nScheduling of the LSST is a history dependent procedure, and the validity of the decisions in a certain night depends on the successful scheduling of all previous nights, evaluating the history dependent data (such as total number of visits), and storing them in the database.\n\n\\begin{enumerate}\n\\item \\textbf{init\\_setup.py} is a one-time procedure: creates a database in the main directory with field's data for 10 nights, starting from 2021/01/01, (takes around 3 minutes)\n\\item \\textbf{run.py}: schedules 10 nights starting from 2021/01/01. It also updates the database after each night of scheduling is completed. log and numpy output of individual nights will be store in \"/Output\" directory, and the mp4 output of each night will be stored in \"/Visualizations\" directory (all takes around 10 minutes).\n\\end{enumerate}\n\n\n%\n%\\begin{figure}\n%\\centering\n%\\includegraphics[width=0.8\\textwidth, trim={5cm 0 0 0}, clip]{Figures/BldgBlock.pdf}\n%\\label{fig_qud}\\caption{ }\n%\\end{figure}\n\n\n%\n%\n%This report reflects the details of Feature-based Telescope Scheduler's design. Including the features, basis functions, hard constraints, cost function, and the performance function as they are at the end of Oct. 2016. \n%\n%In summary, there are seven features (\\ref{sec_f}) for each field, with the total of 4206 fields that need to be evaluated at most at the end of each visit. Basis functions (\\ref{sec_bf}) are designed to transform the raw features to decision criteria that are at the same time properly scaled and comparable to each other. There are seven Basis functions evaluated at the end of each visit for feasible fields upon which the decision is entirely based on. In other words, decision is independent of the time and the history of the observation, because all of the determining history dependent information is reflected in the Basis functions trough features. \n%\n%Two candidates for cost function is proposed in \\ref{sec_cf}, \\textit{Linear Cost Function}, and \\textit{Quadratic Cost Function}. The former cost function is what we used in the earlier versions of the scheduler, and the latter cost function is introduced for the first time in this report. In \\ref{sec_comp} it is shown that the Quadratic Cost Function outperforms the Linear Cost Function (in the current setting of the scheduler). Performance Function (\\ref{sec_perf}) that measures the quality of a sequence of visits reflects the performance of the scheduler after a night of telescope's operation with the scheduler. Current performance function is a scalar value evaluated by linear combination of six different criteria. Section \\ref{sec_opt} explains the details of training procedure of the Cost Function's parameters for both Linear and Quadratic candidates. \n%%Finally, this report is concluded with a list of next step's improvements and additions that are to be made to the Feature-based Scheduler.\n%\n%\\begin{center}\n%\\textbf{Key terms and notations}\\\n%\\noindent\\rule{\\textwidth}{0.4pt}\n%\\end{center}\n%\\begin{tabular}{ l l  }\n%$t$& GMT time in Julian Date,\\\\ %$2459215.5 \\leq t \\leq 2462867.5$ i.e. from January 1, 2021, to January 1, 2031\\\\\n%$\\tau_s(t)$& beginning of the night that $t$ lies in,\\\\\n%$\\tau_e(t)$& end of the night that $t$ lies in,\\\\\n%$id(t)$& ID of the field that is visited at $t$, $i \\in \\{1,2,3,...,4206\\},$\\\\\n%$\\theta_{l}(i,t)$& time of the last visit of field $i$ before $\\tau_s(t)$, $\\theta_{l}(i,t) = \\infty$ if field $i$ is not visited before $\\tau_s(t)$,\\\\\n%$\\theta_{l}^N(i,t)$& time of the last visit of field $i$ between $\\tau_s(t)$ and $t$, $\\theta_{l}^N(i,t) = \\infty$ if field $i$ is not visited in this interval,\\\\\n%$n^N(i,t)$ & number of the visits of field $i$ between $\\tau_s(t)$ and $t$, $0 \\leq n^N(i,t) \\leq 3$\\\\\n%$SM_{i,j}$& slew time from field $i$ to field $j$, $SM \\in \\mathbb{R}^{4206 \\times 4206}$ is a given slew matrix,\\\\\n%$alt(i,t)$ & altitude of the center of field $i$ at $t$, $-\\frac{\\pi}{2} \\leq alt(i,t) \\leq \\frac{\\pi}{2}$,\\\\\n%$ha(i,t)$ & hour angle of the center of field $i$ at $t$, $-12 \\leq ha(i,t) \\leq 12$\\\\\n%$cd(i,t)$ & co-added depth, measure of the cumulative information of collected from field $i$ in visits before $\\tau_s(t)$,\\\\\n%$\\tau_{rise}(i,t)$ & rising time of field $i$ above the 1.4 airmass horizon at current night, $\\tau_{rise}(i,t) = -\\infty$ if $i$ never sets down,\\\\\n%$\\tau_{set}(i,t)$ & setting time of field $i$ below the 1.4 airmass horizon at current night, $\\tau_{set}(i,t) = \\infty$ if $i$ never sets down,\\\\\n%$M_{\\phi}(t)$ & percent of the Moon's surface illuminated at $t$,\\\\\n%$M_{sep}(i,t)$ & Moon's separation from field $i$ at $t$, $0 \\leq M_{sep}(i,t) \\leq \\pi$,\\\\\n%$W_1, W_2$ & given constant time window in which a revisit is valid, $0 < W_1 < W_2$\\\\\n%\\end{tabular}\\\\\n%\\noindent\\rule{\\textwidth}{0.4pt}\\\\\n%\\newpage\n%\\section{Features}\\label{sec_f}\n%\n%\\begin{itemize}\n%\n%\\item Slew time from field $ID(t)$ to field $i = 1 \\dots 4206$\\\\\n%\\begin{center}\n%$f_1(i,t) := SM_{id(t), i}$\n%\\end{center}\n%\n%\\item $f_2(i,t)$ summarizes the history of visits of field $i$ into two elements, $f_2^1$, time past since the last visit before $\\tau_s(t)$, and $f_2^2$, time past since the last visit after $\\tau_s(t)$. The first element reflects the overall urgency of a visit for field $i$, and the second element need to be known to revisit a field in a valid window during a night. $f_2$ is a key feature in the sense that it detaches the decision of time $T$ from all $t < T$. However, the perfect decision requires a full information of the history, therefore the decision based on $f_2$ is only an approximation of the perfect decision. In other words, the original time dependent system is approximated by a Markovian system in which only the most important information of the history is taken into account. Of course, at any point that more details from history was critical for the decision, we have to extend the definition of $f_2$, that would, however, add a non-negligible computational cost to the training procedure.\n%\n%\\begin{center}\n%$f_2(i,t) = (f_2^1(i,t), f_2^2(i,t)) := (t - \\theta_l(i,t), t - \\theta_l^N(i,t))$\n%\\end{center}\n%\\item Altitude of the field is a determining factor in the quality of the visit, therefore one of the features, $f_3$, is devoted to bring this information to the decision making procedure.\n%\\begin{center}\n%$f_3(i,t) := alt(i,t)$\n%\\end{center}\n%\\item Although high altitudes are preferable for observation, but depend on the declination there is a threshold for each field's altitude. Therefore, what actually matters is whether a field is visited in the highest altitude it can ever reach. This information can be extracted from Hour Angle, $f_4$, of a field (that is preferred to be close to 0).\n%\\begin{center}\n%$f_4(i,t) := ha(i,t)$ \n%\\end{center}\n%\\item Co-added depth, $f_5$, offers feedback information to the decision making procedure. For each field, this feature measures the overall quality of the visits of field $i$, before $t$, that the overall urgency of visiting field $i$ at $t$ is depend upon. The fact that the co-added depth measure is a computationally expensive evaluation that involves heavy image processing, has a minimal negative effect on the scheduling performance. Because, the total number of visits of a given field is a lot more than 3 times (maximum number of visits at a single night), in addition, there is a separation of 2 to 3 nights between visits of a field that occurs at different nights, therefore, updates of the co-added depth values can be delayed by 2 to 3 days without a noticeable negative effect to the scheduling performance.\n%\\begin{center}\n%$f_5(i,t) := cd(i,t)$ \n%\\end{center}\n%\\item $f_6$ reflects the duration of future visibility of a field that determines its same night revisit urgency, and is defined to detached the decision of time $T$ from all $t >T$. \n%\\begin{center}\n%$f_6(i,t) := \\begin{cases} \\tau_{set}(i,t) - t,& \\text{if } \\tau_{rise}(i,t) < t \\\\ 0,  & \\text{otherwise} \\end{cases}$\n%\\end{center}\n%\n%\\item $f_7$ is the background sky brightness, which temporarily is defined by two important parameters that determine the sky brightness, the Moon phase and its separation from field $i$ at $t$.\n%\\begin{center}\n%$f_7(i,t) := (f_7^1(t), f_7^2(i,t)) := (M_{\\phi}(t), M_{sep}(i,t))$\n%\\end{center}\n%\\end{itemize}\n%\n%\\section{Basis functions}\\label{sec_bf}\n%Basis functions are mainly designed to scale the features and reflect their direct or inverse relation with the overall cost of a visit. There has been minimum effort put on crafting the basis functions. Of course an engineered design by experts would result in a more desirable model that offers a space of search for optimization algorithm which contains better optimums with higher probability. But in the current version of the scheduler, most of the efforts to find an optimum solution is assumed to be done by the optimization part rather than the design of hand crafted basis functions.\n%\n%\\begin{itemize}\n%\\item Scaled slew time from $ID(t)$ to $i$, it is scaled in a way that the most frequent values lie between about 3 to 5.\n%\\begin{center}\n%$F_1(f_1(i,t)) = \\frac{f_1(i,t)}{5 ~sec},$\n%\\end{center}\n%\\item $F_2$ is designed to reflect the urgency of the same night revisit of field $i$ at time $t$. The least urgent situation is when a field has never been visited ($n^N(i,t) = 0$), or it has already received its second visit ($n^N(i,t) = 2$), in this case, $F_2$ as an element of cost function, takes its maximum value. A moderately urgent case is when a field is visited only once and needs a second visit at the same night, but it will be visible for more than 30 minutes. Finally, the most urgent case is when a field is visited only once and it will be visible less than 30 minutes, in which $F_2$ takes its minimum value to pose the least contribution to the cost of visiting such field.\n%\\begin{center}\n%$F_2(n^N(i,t), f_2^2(i,t), f_6(i,t)) = \\begin{cases}  5 & \\text{if } n^N(i,t) \\in \\{0,2\\},\\\\ 5\\times (1-\\exp(-0.000694 f_2^2(i,t))) & \\text{if } n^N(i,t) = 1 \\text{ and } f_6(i,t) \\geq 30~minutes,\\\\ 0& \\text{if } n^N(i,t) = 1 \\text{ and } f_6(i,t) < 30~minutes, \\end{cases}$\n%\\end{center}\n%\\item $F_3$ reflects the overall urgency of visiting field $i$ at $t$, by simply reversing the time past from last visit of $i$ before $\\tau_s(t)$. \n%\\begin{center}\n%$F_3(f_2^1(i,t)) = \\frac{1}{f_2^1(i,t)},$\n%\\end{center}\n%\\item For $F_4$,  first the altitude $f_3$ is normalized between 0 to 1, then subtracted from 1 to reflect its relationship to the cost of the visit.\n%\\begin{center}\n%$F_4(f_3(i,t)) = (1 - \\frac{2 f_3(i,t)}{\\pi}),$\n%\\end{center}\n%\\item To make sure that we wont undermine a field because of its declination that doesn't let it reach higher altitudes, $F_5$ is designed to assign a same cost to fields with the same separation from the meridian, hence from the highest altitude they can ever reach.\n%\\begin{center}\n%$F_5(f_4(i,t)) = |\\frac{ f_4(i,t)}{12}|,$\n%\\end{center}\n%\\item $F_6$ is the normalized co-added depth, $f_5$, that increasingly grow throughout the telescope's years of operation. \n%\\begin{center}\n%$F_6(f_5(i,t)) = \\frac{f_5(i,t)}{\\max\\limits_i(f_5(i,t)) +1},$\n%\\end{center}\n%\\item $F_7$ is a normalized measure of brightness of the sky in the background of field $i$, at $t$. It is temporarily designed to adopt the Moon phase, $f_7^1$, and the Moon separation, $f_7^2$ to return a value between 0 to 1 as a measure of brightness.\n%\\begin{center}\n%$F_7(f_7(i,t)) = \\begin{cases} \\exp(-\\frac{10}{\\pi} f_7^2(i,t)),  & \\text{if }  0 \\leq f_7^1(t) < 0.2 \\\\ \\exp(-\\frac{2}{\\pi} f_7^2(i,t)),  & \\text{if }  0.2 \\leq f_7^1(t) < 0.5\\\\ \\exp(-\\frac{1}{\\pi} f_7^2(i,t)),  & \\text{if }  0.5 \\leq f_7^1(t) < 0.8 \\\\ 1- \\frac{f_7^2(i,t)}{2 \\pi},  & \\text{otherwise}\\end{cases}$\n%\\end{center}\n%\\end{itemize}\n%\n%\\section{Feasibility}\\label{sec_feas}\n%\n%\\begin{defn*} $\\sigma_t \\subset \\{1,2,\\dots, 4206\\}$ is the set of all feasible fields at $t$. Field $i \\in \\sigma_t$ if and only if:\n%\\begin{enumerate}\n%\\item $ \\tau_{rise}(i,t) \\leq t \\leq \\tau_{set}(i,t) $ (field $i$ has to be above 1.4 airmass horizon at $t$)\n%\\item $f_2^2(i,t) = -\\infty$ ($i$ is not visited between $\\tau_s(t)$ and $t$) or $W_1 \\leq f_2^2(i,t) \\leq W_2$ (time past since the last visit has to lie in the valid revisit window)\n%\\item $n^N(i,t) \\leq 2$ ($i$ is not visited more than twice between $\\tau_s(t)$ and $t$)\n%\\item  $f_1(i,t) \\leq 20~sec$ (slew time from $ID(t)$ to $i$ is less than 20 seconds)\n%\\item $M_{sep}(i,t) \\geq 30~deg$ (field $i$ is at least 30 degrees separated from the Moon)\n%\\end{enumerate}\n%\\end{defn*}\n%\n%\n%\\section{Cost function}\\label{sec_cf}\n%\n%Linear Cost Function is a linear combination of the Basis Functions, with coefficients $c = [c_1,\\dots, c_7]$ that are determined by the offline optimization algorithm.\\\\\n%\n%For the $j^th$ decision made at $t_j$:\n%\\begin{center}$CF_l(j) = \\sum\\limits_{k=1}^7  c_k F_k(i,t_j),$\\end{center}\n%\n%Quadratic Cost Function contains both linear terms and pairwise quadratic terms of the Basis Functions, with 56 coefficient. Considering the quadratic terms offers a more flexible structure that exploits possible correlation of the different Basis Functions which defines a larger space of search for best coefficients, hence possibly a better solution. On the other hand, this eight times larger search space requires more computational resources.\n%\n%For the $j^th$ decision made at $t_j$:\n%\\begin{center} $CF_q(j) = \\sum\\limits_{k=1}^7  c_k F_k(i,t_j) + \\sum\\limits_{k=1}^m \\sum\\limits_{l=1}^m  d_{kl} F_k(i,t_j) F_l(i,t_j) ,$\\end{center}\n%\n%Note that both functions are linear with respect to their free parameters.\n%\n%\\section{Decision Function}\\label{sec_df}\n%\n%For the $j^th$ decision made at $t_j$:\\\\\n%\\begin{center}  $ID(t_j)= \\text{argmin}_{\\sigma_{t_j} }CF(j),$\\end{center}\n%\n%\n%\\section{Performance Function}\\label{sec_perf}\n%\n%Current performance function is defined over a night of observation between $t_0 = 2457633.489641$ (2016/9/1 23:45:05 GMT), and $T = 2457633.892419$ (2016/9/2 09:25:05 GMT). Let $N_v$ be the number of visits between $t_0$ and $T$, then,\n%\n%\\begin{center}\n%$P(t_0,T) = \\frac{1}{N_v}( P_1 \\sum\\limits_{j = 1}^{N_v} CF(j) +P_2 \\sum\\limits_{j = 1}^{N_v} f_1(ID(t_j),t_j) +P_3 \\sum\\limits_{j = 1}^{N_v} f_3(ID(t_j),t_j)) + \\frac{1}{T-t_0}(P_4N_{triple} + P_5 N_{double} + P_6 N_{single})$\n%\\end{center}\n%\n%Where, $N_{triple}, N_{double}, \\text{and } N_{single}$ are the number of fields visited three, two, and one time(s) respectively, between $t_0$ and $T$.\n%\n%For the current version of the training algorithm, preference parameters are set as follow:\\\\\n%\n%$P = [P_1,\\dots,P_6] = [-1,-1,4,0,3,-10]$\n%\n%\\section{Optimization}\\label{sec_opt}\n%\n%Differential Evolution (DE) algorithm explores and exploits a finite space of solutions and returns the solution by which a scalar objective function is maximized amongst all visited points. DE never guarantees a 100\\% global optimality. However increasing the number of trials and iterations increases confidence in the global optimality of the solution.\n%\n%To find the parameters of cost function, first we randomly initialize $N_p$ different sets of parameters. Then, let each of the settings run the LSST simulator, for a night of observation. Then we measure the scalar performance function $P(t_0,T)$. Based on the values of the parameters and objective function, DE, suggests a set of new $N_p$ controllers which on average work better than the previous controllers. Then iterates this procedure, until there is no improvement in the best observed performance. A pseudo code of the basic DE algorithm can be found in Appendix \\ref{app_code}.\n%\n%To be able to compare the performance of Linear Cost Function versus Quadratic Cost Function, instead of terminating the training based on the performance function progress (that is not known until the end of the training), we limited the number of iterations to 20 (smaller than the expected number of iterations in the normal termination setting), with $N_p = 50$. This modification allocates a same computational budget for both cost functions. (Elapsed time: 12 hours, CPU 1.6 GHz Intel Core i5)\n%\n%Best solution found for Linear Cost Function:\\\\\n%\\indent $c = [1.3, 9.8, 5.2, 6.4, 0.16, 7.11, 8.7]$\n%\n%Best solution found for Quadratic Cost Function:\\\\\n%\\indent $c = ~[4.2,  ~~7.3,  ~~3.2, ~~ 7.4, ~~ 2.5,~~  2.3, ~~2.1]$\\\\\n%\\indent $d = \\begin{bmatrix}\n%0.61&   4.1& 1.9& 8.5& 4.7& 8.3&  4.7\\\\\n%2.8 &  6.6 &  3.9& 5.6& 4.0& 5.6&  4.0\\\\\n%7.9 & 8.0 &  2.0& 6.4 & 5.3& 5.4&  5.8\\\\\n%6.5& 5.8&6.8&   4.8& 4.8& 4.5&  1.4\\\\\n%6.7& 2.5&4.5& 5.3& 8.0&  4.6& 4.1\\\\\n%2.0&  4.6& 4.3& 3.6& 4.9&  5.9& 9.3\\\\\n%1.4& 9.2& 3.6&3.2&4.2&7.2& 6.2\n%\\end{bmatrix}$\n%\n%\n%\\section{Simulation results and comparison}\\label{sec_comp}\n%\n%In this section four different simulations are presented: \n%\\begin{itemize}\n%\\item $S_1:$ 100 days of scheduling with the Linear Cost Function starting from 2016/9/1\n%\\item $S_2:$ 100 days of scheduling with the Quadratic Cost Function starting from 2016/9/1\n%\\item $S_3:$ 365 days of scheduling with the Linear Cost Function starting from 2016/9/1\n%\\item $S_1:$ 315 days of scheduling with the Quadratic Cost Function starting from 2016/9/1\n%\\end{itemize}\n%\n%\\subsection{Simulation timing}\n%A trained Feature-based scheduler contains four different phases:\n%\n%\\begin{enumerate}\n%\\item \\textbf{Preprocessing and data generation} generates lookup tables for predictable data such as altitude to avoid evaluation of them in on-line scheduling. This phase also process the history of the observation and returns the summarized information that we use as a substitute for looking into the history. Time required for this phase is currently depend on the length of history, however it can be optimized to become independent of the size of past scheduling sequence, that would take up to 20 seconds for each individual night.\n%\\item \\textbf{Import data} is to read the data generated at the previous phase, and it takes about 13 seconds.\n%\\item \\textbf{Online scheduling} is the heart of the scheduler that makes the sequential decisions, and it takes about 70 seconds, but it is linearly dependent on the length of the night.\n%\\item \\textbf{Writing on the database} record the data into the database and it takes up to 2 seconds.\n%\\end{enumerate}\n%\n%Timings are based on the simulation runs on a 1.6 GHz Intel Core i5 CPU with 4 GB 1600 MHz DDR3, which sums up to 105 seconds for each night of scheduling.\n%\n%Table \\ref{tab_sim} demonstrates the most important statistics of the output of above-mentioned simulations. In terms of the number of visits Quadratic Cost function outperforms the Linear Cost Function with 0.4 visit per hour (1460 visit per year). Superiority of the Quadratic Cost Function is not noticeable in the average of visits altitude, however, comparing the average value with the best night and the worst night shows that it offers a more consistent performance over different nights compare to the Linear Cost Function.\n%\n%\\begin{table}\n%\\label{tab_sim}\\caption{Simulation statistics}\n%\\begin{tabular}{l c c | c c}\n%Simulation            & $S_1$ & $S_2$ & $S_3$ & $S_4$  \\\\\n%\\hline\n%number of visits per hour      \t\t\t\t& 103.74 & \\textbf{104.16} & 103.71 & \\textbf{104.17}  \\\\\n%ratio of the triple visits to total number of visits   & 0.29 & 0.25 & 0.29 & 0.25\\\\\n%ratio of the double visits to total number of visits &0.57 & \\textbf{0.62} & 0.56 & \\textbf{0.61}\\\\\n%ratio of the single visits to total number of visits  & 0.15 & \\textbf{0.13} & 0.15 & \\textbf{0.14}\\\\\n%\\hline\n%average altitude of all visits (deg) \t\t\t\t & 67.35&\\textbf{67.86}&66.84&\\textbf{67.40}\\\\\n%highest altitude average of a night of simulation &79.97&76.74&79.97&76.74\\\\\n%lowest altitude average of a night of simulation &59.97&61.69&58.64&59.49\\\\\n%average slew time of all visits (sec) \t\t\t\t & \\textbf{4.27}&4.58&4.73&\\textbf{4.58}\\\\\n%lowest slew time average of a night of simulation &4.43&4.39&4.43&4.39\\\\\n%highest slew time average of a night of simulation &5.07&4.86&5.07&4.94\\\\\n%\\hline\n%median number of visits of a field normalized by the simulation length \t\t\t& 0.29&0.31& 0.30&0.29\\\\\n%average number of visits of a field normalized by the simulation length \t\t\t&0.35&0.36&0.28&0.28\\\\\n%median of the time separation between $1^{st}$ and $2^{nd}$ visits& 16.17 & 15.71&16.20& 16.07\\\\\n%median of the time separation between $2^{nd}$ and $3^{rd}$ visits& 18.43 & 18.71&18.81& 18.80\\\\\n%\\end{tabular}\n%\\end{table}\n%%op:  with Linear Cost Function over 365 nights. bottom\n%\n%Figures \\ref{fig_lin} and \\ref{fig_qud}, show the visit statistics of Linear Cost Function and Quadratic Cost Function respectively. Histogram presents the distribution of the frequency of visits of a field which we ideally prefer to be as concentrated as possible (uniform coverage of the sky). The bottom bar graphs show the number of visits of each field, $i = 1\\dots4206$, which we prefer to be as uniformly distributed as possible.\n% \n%\\begin{figure}\\label{fig_lin}\n%\\centering\n%\\includegraphics[width=0.8\\textwidth ]{Figures/Linear365.png}\n%\\label{fig_lin}\\caption{Linear Cost Function}\n%\\end{figure}\n%\n%\\begin{figure}\n%\\centering\n%\\includegraphics[width=0.8\\textwidth]{Figures/Quad315.png}\n%\\label{fig_qud}\\caption{Quadratic Cost Function}\n%\\end{figure}\n%\n%\\newpage\n%\\appendix\n%\n%\\section{Basic Differential Evolution Algorithm}\\label{app_code}\n%Notation:\\\\\n%$C{r}$: Crossover rate,\\\\\n%$F$: Mutation factor,\\\\\n%$N_p$: Population size,\\\\\n%$\\ax^{L}$: Initialization lower bound, (not necessarily a lower bound on the solution.)\\\\\n%$\\vec{\\rho}\\mid^{1}_{0}$: Uniformly random value between 0 and 1,\\\\\n%$\\ax^{u}$: Initialization upper bound, (not necessarily an upper bound on the solution.)\\\\\n%$\\ax_{i}^{(0)}$: Initial individuals,\\\\\n%\n%{\\footnotesize\n%\\hrule\n%\\begin{tabbing}\n%\\hspace{0.5cm} \\= \\hspace{0.5cm} \\=  \\hspace{0.5cm} \\= \\hspace{0.5cm} \\=\\\\\n%\\textbf{begin} \\\\\n%\\> Initialize algorithm settings: $C{r}$, $F$\\\\\n%\\> \\textbf{for} ($i=1,\\ldots,N_{p}$) \\\\\n%\n% \\> \\> $P^{(0)}\\leftarrow \\ax_{i}^{(0)}=\\ax^{L}+\\vec{\\rho}\\mid^{1}_{0}(\\ax^{U}-\\ax^{L})$~~\\textbf{end} ~~\\% \\verb\"Initialize\" \\\\\n%\n%\\> \\textbf{while} (not optimal) \\textbf{do begin} \\\\\n%\n% \\>  \\textbf{for} ($i=1,\\ldots,N_{p}$) \\textbf{do begin}~~\\% \\verb\"Perform mutation\" \\\\\n%\n% \\> \\> $\\vec{u}_{i}^{k+1}\\leftarrow$ \\textbf{mutate} \\\\\n%\n% \\> \\>  \\textbf{for} ($j=1,\\ldots,N_{p}$) \\textbf{do begin} ~~\\% \\verb\"Crossover with target\" \\\\\n%\n% \\> \\> \\> \\textbf{if} $\\rho\\mid_{0}^{1} < C{r}$ \\textbf{do begin}\\\\\n%\n% \\> \\> \\> \\> $u_{ij}^{k+1} \\leftarrow x_{ij}^{k}$~~\\textbf{end} \\\\\n%\n% \\> \\> \\textbf{end} \\\\\n%\n% \\> \\> $\\ax_{i}^{k+1}\\leftarrow$ \\textbf{selection} $[\\ax_{i}^{k},\\vec{u}_{i}^{k+1}]$ ~~\\% \\verb\"Perform selection\" \\\\\n%\n% \\> \\textbf{end} \\\\\n%\n%$k \\leftarrow k+1$ \\\\\n%\\textbf{end}\n%\\end{tabbing}\n%\\hrule}\n%\n%\n\n\\newpage\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\end{document} \n", "meta": {"hexsha": "f22812e06cb393d892a9924df1d13b6338f1880f", "size": 31190, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "CodeDescription/FBSchedulerCodeDescription.tex", "max_stars_repo_name": "elahesadatnaghib/FB-Scheduler-v2", "max_stars_repo_head_hexsha": "6cd01df0ff1e67057a5425a4473f3220f73bbd62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-23T14:01:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-23T14:01:04.000Z", "max_issues_repo_path": "CodeDescription/FBSchedulerCodeDescription.tex", "max_issues_repo_name": "elahesadatnaghib/FB-Scheduler-v2", "max_issues_repo_head_hexsha": "6cd01df0ff1e67057a5425a4473f3220f73bbd62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CodeDescription/FBSchedulerCodeDescription.tex", "max_forks_repo_name": "elahesadatnaghib/FB-Scheduler-v2", "max_forks_repo_head_hexsha": "6cd01df0ff1e67057a5425a4473f3220f73bbd62", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 66.3617021277, "max_line_length": 1018, "alphanum_fraction": 0.7136582238, "num_tokens": 9571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832058771035, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3050744846858569}}
{"text": "\\section{Programming language}\n\nWe define a programming language that is both simple and powerful enough to conclusively describe weak memory models to the extent they may be available to the programmer. Throughout this work, we will refer to this language as SALPL, abbreviating the first description of the ``simple assembly-like programming language'' \\cite{kupersteinetal10} defined by Kuperstein, Vechev and Yahav in \\cite{kupersteinetal10}, on which SALPL is based. A SALPL program has only integer-type variables, but it can perform comparisons that return boolean values, which in turn can be operated on using boolean operators. Boolean values are used in conditionals and may have the values $true$, $false$, or $*$, all of which are also valid literals. Comments are defined as in C, with \\lstinline{//} prepending line comments and \\lstinline{/*} and \\lstinline{*/} enclosing block comments.\\\\\n\nIn this section, we will group code placeholders using $[\\:]$-brackets, which might have a * appended for an arbitrary number of the code specified.\n\n\\paragraph{Accepting program state}\n\nA valid SALPL program must have the following structure:\n\n\\begin{lstlisting}[frame=single, mathescape]\nbeginit\n\t$[store\\:statement]*$\nendinit\n\n$[process\\:declaration]*$\n\n$[assertion]$\n\\end{lstlisting}\n\n\\paragraph{Assertion}\n\nThe assertion may be appended to the end of the program. Its syntax is derived from the boolean program syntax used by the Fender \\cite{fender} model checker. The boolean expression therein may only refer to global variables, constants, or program counters of the form \\lstinline$pc($$i$\\lstinline$)$, with $i$ being a valid process index. The value of a program counter may be that of any valid label of the process $i$.\n\n\\begin{lstlisting}[frame=single, mathescape]\nassert(always($boolean\\:expression$))\n\\end{lstlisting}\n\n\\paragraph{Process declaration}\n\nEvery process must have a unique integer identifier $i$.\n\n\\begin{lstlisting}[frame=single, mathescape]\nprocess $i$:\n\t$[statement]*$\n\\end{lstlisting}\n\n\\paragraph{Statement}\nA $statement$ can be any of the following: \\emph{store statement}, \\emph{load statement}, \\emph{local assignment statement}, \\emph{label}, \\emph{goto statement}, \\emph{flush statement}, \\emph{fence statement}, \\emph{abort statement}, \\emph{nop statement}, \\emph{if-else block}.\n\n\\paragraph{Store statement}\nGenerally, the store statement writes the right-hand side expression to the buffer, pending commitment to remote memory. In the special case where flushes are to be excluded, as it will be the case later on in this work, the store statement may be viewed as an immediate and deterministic remote write operation. The left-hand side identifier must be a global variable.\n\n\\begin{lstlisting}[frame=single, mathescape]\nstore $variable\\:identifier$ = $integer\\:expression$;\n\\end{lstlisting}\n\n\\paragraph{Load statement}\nGenerally, the load statement reads the most recent relevant value from the buffer, and it only reads from remote memory if the buffer doesn't contain any values of the desired variable. In the special case where flushes are to be excluded, as it will be the case later on in this work, the load statement may be viewed as an unconditional remote read operation. The left-hand side identifier must be a local variable, while the right-hand side identifier must be a global variable.\n\n\\begin{lstlisting}[frame=single, mathescape]\nload $variable\\:identifier$ = $variable\\:identifier$;\n\\end{lstlisting}\n\n\\paragraph{Local assignment statement}\nThe left-hand side identifier must be a local variable. The \\emph{integer expression} may be an integer literal, an integer variable symbol, or any integer operation on them.\n\n\\begin{lstlisting}[frame=single, mathescape]\n$variable\\:identifier$ = $integer\\:expression$;\n\\end{lstlisting}\n\n\\paragraph{Label}\nThe statement following the colon may not be another label. The label value $i$ must be unique within its process.\n\n\\begin{lstlisting}[frame=single, mathescape]\n$i$: $statement$\n\\end{lstlisting}\n\n\\paragraph{Goto statement}\nThe label value $i$ must be a valid label within the calling process.\n\n\\begin{lstlisting}[frame=single, mathescape]\ngoto $i$;\n\\end{lstlisting}\n\n\\paragraph{Flush statement}\nFlushing will iterate through all global variables and non-deterministically commit the first value of the respective variable to remote memory and remove that value from the buffer. If a variable does not have any values to be committed, it will be ignored.\n\n\\begin{lstlisting}[frame=single, mathescape]\nflush;\n\\end{lstlisting}\n\n\\paragraph{Fence statement}\nWithout any operations on the buffer or memory, fences just assume the buffer to be empty from then on. If the buffer is not empty, the fence blocks until it becomes empty.\n\n\\begin{lstlisting}[frame=single, mathescape]\nfence;\n\\end{lstlisting}\n\n\\paragraph{Abort statement}\nAborts the program with the $message$ argument as the error message.\n\n\\begin{lstlisting}[frame=single, mathescape]\nabort(\"$message$\");\n\\end{lstlisting}\n\n\\paragraph{Nop statement}\nDoes nothing.\n\n\\begin{lstlisting}[frame=single, mathescape]\nnop;\n\\end{lstlisting}\n\n\\paragraph{If-else block}\nIf the \\emph{boolean expression} evaluates to \\emph{true}, the \\emph{statement} block right after the conditional is carried out, omitting the \\emph{else block}, if it exists. If it evaluates to \\emph{false}, jumps to the point after the first \\emph{statement} block. If it evaluates to \\lstinline$*$, i.e. \\emph{undecided}, it will non-deterministically simulate an evaluation to either \\emph{true}, or \\emph{false}.\n\n\\begin{lstlisting}[frame=single, mathescape]\nif ($boolean\\:expression$)\n\t$[statement]*$\n$[else\\:block]?$\nendif;\n\\end{lstlisting}\n\nwith the \\emph{else block} being:\n\n\\begin{lstlisting}[frame=single, mathescape]\nelse\n\t$[statement]*$\n\\end{lstlisting}", "meta": {"hexsha": "5e28bfd1cbbd29dc9f18731413bb4401ffd4234e", "size": 5794, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/writeup/language.tex", "max_stars_repo_name": "hetmeter/awmm", "max_stars_repo_head_hexsha": "8d65b1246898b27db1ac5a6542465f71e27b1603", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/writeup/language.tex", "max_issues_repo_name": "hetmeter/awmm", "max_issues_repo_head_hexsha": "8d65b1246898b27db1ac5a6542465f71e27b1603", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/writeup/language.tex", "max_forks_repo_name": "hetmeter/awmm", "max_forks_repo_head_hexsha": "8d65b1246898b27db1ac5a6542465f71e27b1603", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.6890756303, "max_line_length": 873, "alphanum_fraction": 0.7780462547, "num_tokens": 1401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.30505027741005447}}
{"text": "\\chapter{\\label{chap:interpolation}Some notes on the interpolation}\n\nIn \\wannier{} v.2.1, a new flag {\\tt use\\_ws\\_distance} has been \nintroduced. Setting it to {\\tt .false.} reproduces the \n``standard'' behavior of \\wannier{} in v.2.0.1 and earlier,\nwhile setting it to {\\tt .true.} changes the interpolation method\nas described below. In general, this allows a smoother interpolation,\nhelps reducing (a bit) the number of $k-$points required for interpolation,\nand reproduces the band structure of large supercells sampled at $\\Gamma$ \nonly (setting it to {\\tt .false.} produces instead flat bands, which \nmight instead be the intended behaviour for small molecules carefully\nplaced at the centre of the cell).\n\nThe core idea rests on the fact that the Wannier functions $w_{n\\bvec{R}}(\\bvec{r})$\nthat we build from $N\\times M\\times L$ $k-$points are actually periodic \nover a supercell of size $N\\times M\\times L$, but when you use \nthem to interpolate you want them to be \\emph{zero} outside this supercell. \nIn 1D it is pretty obvious want we mean here, but in 3D what you really \nwant that they are zero outside the Wigner--Seitz cell of the \n$N\\times M\\times L$ superlattice.\n\nThe best way to impose this condition is to check that every real-space \ndistance that enters in the $R\\to k$ Fourier transform is the shortest possible \namong all the $N\\times M\\times L-$periodic equivalent copies. \n\nIf the distances were between unit cells, this would be trivial, but the \ndistances are between Wannier functions which are not centred on $\\bvec R=0$. \nHence, when you want to consider the matrix element of a generic operator $\\bvec O$\n(i.e., the Hamiltonian)  $\\langle w_{i\\bvec 0}(\\bvec{r})|\\bvec{O}|w_{j\\bvec{R}}(\\bvec{r})\\rangle$ \nyou must take in account that the centre $\\bvec{\\tau}_i$ of $w_{i\\bvec 0}(\\bvec{r})$ may \nbe very far away from $\\bvec{0}$ and the centre $\\bvec{\\tau}_j$ of $w_{j\\bvec{R}}(\\bvec{r})$\nmay be very far away from $\\bvec{R}$.\n\nThere are many way to find the shortest possible distance between $w_{i\\bvec{0}}(\\bvec{r})$ and \n$w_{j\\bvec{R}}(\\bvec{r}-\\bvec{R})$, the one used here is to consider the distance\n$\\bvec{d}_{ij\\bvec{R}} = \\bvec{\\tau}_i - (\\bvec{\\tau}_j+\\bvec{R})$\nand all its superlattice periodic equivalents\n$\\bvec{d}_{ij\\bvec{R}}+ \\bvec{\\tilde R}_{nml}$, with \n$\\bvec{\\tilde R}_{nml} = (Nn\\bvec{a}_1 + Mm\\bvec{a}_2 + Ll\\bvec{a}_3)$\nand $n,l,m = {-3,-2,...0,...3}$.\n\nThen,\n\\begin{enumerate}\n\\item if $\\bvec{d}_{ij\\bvec{R}}+ \\bvec{\\tilde R}_{nml}$ is inside the  \n  $N\\times M \\times L$ super-WS cell, then it is the shortest, take it and quit\n\n\\item if it is outside the WS, then it is not the shortest, throw it away\n\n\\item if it is on the border/corner of the WS then it is the shortest, but there \nare other choices of $(n,m,l)$ which are equivalent, find all of them\n\\end{enumerate}\n\nBecause of how the Fourier transform is defined in the \\wannier{} code (not the only \npossible choice) it is only $\\bvec{R}+\\bvec{\\tilde R}_{nml}$ \nthat enters the exponential, but you still have to consider the distance \namong the actual centres of the Wannier functions. Using \nthe centres of the unit-cell to which the Wannier functions belong \nis not enough (but is easier, and saves you one index).\n\nPoint 3 is not stricly necessary, but using it helps enforcing the \nsymmetry of the system in the resulting band structure. You \nwill get some small but evident symmetry breaking in the band \nplots if you just pick one of the equivalent $\\bvec{\\tilde R}$ vectors.\n\nNote that in some cases, all this procedure does absolutely nothing,\nfor instance if all the Wannier function centres are very close to 0 \n(e.g., a molecule carefully placed in the periodic cell).\n\nIn some other cases, the effect may exist but be imperceptible. E.g.,\nif you use a very fine grid of $k-$points, even if you don't centre \neach functions perfectly, the periodic copies will still be so far away \nthat the change in centre applied with $\\tt use\\_ws\\_distance$ does not matter. \n\nWhen instead you use few $k-$points, activating the $\\tt use\\_ws\\_distance$\nmay help a lot in avoiding spurious oscillations of the band structure\neven when the Wannier functions are well converged.\n", "meta": {"hexsha": "ddcad4c48a3872ad7659511f1c42097cd0259528", "size": 4193, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "wannier90_2.1/doc/user_guide/interpolation.tex", "max_stars_repo_name": "comscope/comsuite", "max_stars_repo_head_hexsha": "d51c43cad0d15dc3b4d1f45e7df777cdddaa9d6c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2019-06-15T18:08:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T05:01:29.000Z", "max_issues_repo_path": "wannier90_2.1/doc/user_guide/interpolation.tex", "max_issues_repo_name": "comscope/Comsuite", "max_issues_repo_head_hexsha": "b80ca9f34c519757d337487c489fb655f7598cc2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wannier90_2.1/doc/user_guide/interpolation.tex", "max_forks_repo_name": "comscope/Comsuite", "max_forks_repo_head_hexsha": "b80ca9f34c519757d337487c489fb655f7598cc2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2019-06-05T02:57:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T02:54:25.000Z", "avg_line_length": 54.4545454545, "max_line_length": 98, "alphanum_fraction": 0.7362270451, "num_tokens": 1204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.30492725832042367}}
{"text": "\n% This LaTeX was auto-generated from an M-file by MATLAB.\n% To make changes, update the M-file and republish this document.\n\n\n\n    \n    \n      \\subsection{gp1.m}\n\n\\begin{par}\n\\textbf{Summary:} Compute joint predictions for the FITC sparse approximation to multiple GPs with uncertain inputs. Predictive variances contain uncertainty about the function, but no noise. If gpmodel.nigp exists, individual noise contributions are added.\n\\end{par} \\vspace{1em}\n\\begin{verbatim}function [M, S, V] = gp1d(gpmodel, m, s)\\end{verbatim}\n\\begin{par}\n\\textbf{Input arguments:}\n\\end{par} \\vspace{1em}\n\\begin{verbatim}gpmodel    GP model struct\n  hyp      log-hyper-parameters                                  [D+2 x  E ]\n  inputs   training inputs                                       [ n  x  D ]\n  targets  training targets                                      [ n  x  E ]\n  nigp     (optional) individual noise variance terms            [ n  x  E ]\nm          mean of the test distribution                         [ D  x  1 ]\ns          covariance matrix of the test distribution            [ D  x  D ]\\end{verbatim}\n\\begin{par}\n\\textbf{Output arguments:}\n\\end{par} \\vspace{1em}\n\\begin{verbatim}M          mean of pred. distribution                            [ E  x  1 ]\nS          covariance of the pred. distribution                  [ E  x  E ]\nV          inv(s) times covariance between input and output      [ D  x  E ]\\end{verbatim}\n\\begin{par}\nCopyright (C) 2008-2013 by Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen.\n\\end{par} \\vspace{1em}\n\\begin{par}\nLast modified: 2013-03-05\n\\end{par} \\vspace{1em}\n\n\n\\subsection*{High-Level Steps} \n\n\\begin{enumerate}\n\\setlength{\\itemsep}{-1ex}\n   \\item If necessary, compute kernel matrix and cache it\n   \\item Compute predicted mean and inv(s) times input-output covariance\n   \\item Compute predictive covariance matrix, non-central moments\n   \\item Centralize moments\n\\end{enumerate}\n\n\\begin{lstlisting}\nfunction [M, S, V] = gp1(gpmodel, m, s)\n\\end{lstlisting}\n\n\n\\subsection*{Code} \n\n\n\\begin{lstlisting}\nif ~isfield(gpmodel,'induce') || numel(gpmodel.induce)==0,\n    [M, S, V] = gp0(gpmodel, m, s); return; end\n\npersistent iK iK2 beta oldX;\nridge = 1e-6;                        % jitter to make matrix better conditioned\n[n, D] = size(gpmodel.inputs);    % number of examples and dimension of inputs\nE = size(gpmodel.targets,2);         % number of examples and number of outputs\nX = gpmodel.hyp; input = gpmodel.inputs; targets = gpmodel.targets;\n\n[np pD pE] = size(gpmodel.induce);     % number of pseudo inputs per dimension\npinput = gpmodel.induce;                                   % all pseudo inputs\n\n% 1) If necessary: re-compute cached variables\nif numel(X) ~= numel(oldX) || isempty(iK) || isempty(iK2) || ... % if necessary\n              sum(any(X ~= oldX)) || numel(iK2) ~=E*np^2 || numel(iK) ~= n*np*E\n  oldX = X;                                        % compute K, inv(K), inv(K2)\n  iK = zeros(np,n,E); iK2 = zeros(np,np,E); beta = zeros(np,E);\n\n  for i=1:E\n    pinp = bsxfun(@rdivide,pinput(:,:,min(i,pE)),exp(X(1:D,i)'));\n    inp = bsxfun(@rdivide,input,exp(X(1:D,i)'));\n    Kmm = exp(2*X(D+1,i)-maha(pinp,pinp)/2) + ridge*eye(np);  % add small ridge\n    Kmn = exp(2*X(D+1,i)-maha(pinp,inp)/2);\n    L = chol(Kmm)';\n    V = L\\Kmn;                                             % inv(sqrt(Kmm))*Kmn\n    if isfield(gpmodel,'nigp')\n      G = exp(2*X(D+1,i))-sum(V.^2)+gpmodel.nigp(:,i)';\n    else\n      G = exp(2*X(D+1,i))-sum(V.^2);\n    end\n    G = sqrt(1+G/exp(2*X(D+2,i)));\n    V = bsxfun(@rdivide,V,G);\n    Am = chol(exp(2*X(D+2,i))*eye(np) + V*V')';\n    At = L*Am;                                    % chol(sig*B) [thesis, p. 40]\n    iAt = At\\eye(np);\n% The following is not an inverse matrix, but we'll treat it as such: multiply\n% the targets from right and the cross-covariances left to get predictive mean.\n    iK(:,:,i) = ((Am\\(bsxfun(@rdivide,V,G)))'*iAt)';\n    beta(:,i) = iK(:,:,i)*targets(:,i);\n    iB = iAt'*iAt.*exp(2*X(D+2,i));              % inv(B), [Ed's thesis, p. 40]\n    iK2(:,:,i) = Kmm\\eye(np) - iB; % covariance matrix for predictive variances\n  end\nend\n\nk = zeros(np,E); M = zeros(E,1); V = zeros(D,E); S = zeros(E);       % allocate\ninp = zeros(np,D,E);\n\n% 2) Compute predicted mean and inv(s) times input-output covariance\nfor i=1:E\n  inp(:,:,i) = bsxfun(@minus,pinput(:,:,min(i,pE)),m');\n\n  L = diag(exp(-X(1:D,i)));\n  in = inp(:,:,i)*L;\n  B = L*s*L+eye(D);\n\n  t = in/B;\n  l = exp(-sum(in.*t,2)/2); lb = l.*beta(:,i);\n  tL = t*L;\n  c = exp(2*X(D+1,i))/sqrt(det(B));\n\n  M(i) = sum(lb)*c;                                            % predicted mean\n  V(:,i) = tL'*lb*c;                     % inv(s) times input-output covariance\n  k(:,i) = 2*X(D+1,i)-sum(in.*in,2)/2;\nend\n\n% 3) Compute predictive covariance matrix, non-central moments\nfor i=1:E\n  ii = bsxfun(@rdivide,inp(:,:,i),exp(2*X(1:D,i)'));\n\n  for j=1:i\n    R = s*diag(exp(-2*X(1:D,i))+exp(-2*X(1:D,j)))+eye(D); t = 1./sqrt(det(R));\n    ij = bsxfun(@rdivide,inp(:,:,j),exp(2*X(1:D,j)'));\n    L = exp(bsxfun(@plus,k(:,i),k(:,j)')+maha(ii,-ij,R\\s/2));\n    if i==j\n      S(i,i) = t*(beta(:,i)'*L*beta(:,i) - sum(sum(iK2(:,:,i).*L)));\n    else\n      S(i,j) = beta(:,i)'*L*beta(:,j)*t; S(j,i) = S(i,j);\n    end\n  end\n\n  S(i,i) = S(i,i) + exp(2*X(D+1,i));\nend\n\n% 4) Centralize moments\nS = S - M*M';\n\\end{lstlisting}\n", "meta": {"hexsha": "2f9077165de9204b7dd70af6cb971ac5ba1b4288", "size": 5369, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/tex/gp1.tex", "max_stars_repo_name": "SJTUGuofei/pilco-matlab", "max_stars_repo_head_hexsha": "a0b48b7831911837d060617903c76c22e4180d0b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 53, "max_stars_repo_stars_event_min_datetime": "2016-12-17T15:15:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T16:59:27.000Z", "max_issues_repo_path": "doc/tex/gp1.tex", "max_issues_repo_name": "sahandrez/quad_pilco", "max_issues_repo_head_hexsha": "2c99152e3a910d147cd0a52822da306063e6a834", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-24T11:02:23.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-24T11:09:45.000Z", "max_forks_repo_path": "doc/tex/gp1.tex", "max_forks_repo_name": "sahandrez/quad_pilco", "max_forks_repo_head_hexsha": "2c99152e3a910d147cd0a52822da306063e6a834", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 36, "max_forks_repo_forks_event_min_datetime": "2017-04-19T06:55:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-19T10:19:12.000Z", "avg_line_length": 37.2847222222, "max_line_length": 257, "alphanum_fraction": 0.5621158503, "num_tokens": 1719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7025300698514777, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.30488502878292945}}
{"text": "\\documentclass[a4paper,11pt]{article}\n\n\\usepackage[T1]{fontenc} \\usepackage{lmodern} \\usepackage[utf8]{inputenc}\n\\usepackage[english]{babel} \\usepackage{csquotes}\n\\usepackage{float} \\usepackage{graphicx,subfigure}\n\\usepackage{amssymb,amsmath,epstopdf} %\\usepackage{siunitx}\n\\usepackage[nodayofweek]{datetime}\n\\usepackage[top=3.0cm,bottom=2.0cm,left=2.5cm,right=2.5cm,headheight=30pt]{geometry}\n\\usepackage{natbib} \n\\usepackage{fancyhdr} \\pagestyle{fancy} \\usepackage{lastpage}\n\\usepackage{parskip} \\setlength{\\parskip}{.5em} \\setlength{\\parindent}{1em}\n\\usepackage[colorlinks=true,allcolors=blue]{hyperref} \\hypersetup{\n\tpdfauthor={Michaël Defferrard, Soroosh Shafiee},\n\tpdftitle={Incremental Gradient Methods},\n\tpdfsubject={Project proposal}\n}\n\\lhead{Advanced Topics in Data Sciences\\\\ Project report}\n\\chead{\\hspace{2cm}EPFL\\\\ \\hspace{2cm}\\shortdate\\today}\n\\rhead{Michaël \\textsc{Defferrard}\\\\ Soroosh \\textsc{Shafiee}}\n\\cfoot{}\n\n\\newcommand{\\R}{\\mathbb{R}}\n\\newcommand{\\B}{\\mathcal{B}}\n\\newcommand{\\eqnref}[1]{(\\ref{eqn:#1})}\n\\newcommand{\\figref}[1]{Figure~\\ref{fig:#1}}\n\\newcommand{\\prox}{\\textrm{prox}}\n%\\DeclareMathOperator*{\\prox}{prox}\n\n\\begin{document}\n\n\\begin{center}\n\t\\Large{\\textbf{\\textsc{Incremental Gradient Methods}}}\n\\end{center}\n\nThis project is aimed to be a way for us to better understand and thinker with\nthe recent advances in Stochastic Gradient Descent algorithms, specifically\nthe recent SAGA \\cite{defazio_saga_2014}. This method is similar in spirit to\nthe previously developed SAG, SDCA, MISO and SVRG. This class of algorithms have\nbeen developed to solve problems of the form\n\\begin{equation} \\label{eqn:problem}\n\t\\min_{x \\in \\R^d} \\frac{1}{n} \\sum_{i=1}^n f_i(x) + h(x),\n\\end{equation}\nwhere each $f_i$ is convex and has Libschitz continuous derivatives with\nconstant $L$ or is strongly convex with constant $\\mu$; and $h$ is a convex but\npotentially non-differentiable function (his proximal operator is however easy\nto compute). While computing the full gradient would be prohibitive due to large\n$d$ and $n$, these iterative stochastic algorithms reduce the computational cost\nof optimization by only computing the gradient of a subset of the functions\n$f_i$ at each step.\n\nMany machine learning problems can be cast in \\eqnref{problem}, such as\n(constrained) Least-Square or Logistic Regressions with $\\ell_1$ or $\\ell_2$\nregularization; where $x$ would represent the model parameters, $f_i$ the data\nfidelity term applied to a particular sample $i$, and $h$ a regularization or\nindicator function of a convex set.\n\nIn this project we explored two approaches to improve SAGA towards two different\ngoals:\n\\begin{itemize}\n\t\\item A \\textbf{memory-efficient SAGA}, by way of computing and storing\n\t\tgradients over mini-batches instead of single samples, as is done for\n\t\tthe infamous Stochastic Gradient Descent \\cite{konevcny2014ms2gd}. It turns out that this\n\t\tapproach is also faster than the original algorithm as it exploits the\n\t\tvectorial capabilities of modern processing units.\n\t\\item A \\textbf{time-efficient SAGA}, by way of distributing the gradient\n\t\tcomputation over many CPU cores while fusing the results and updating\n\t\tthe model parameters on the master. The similar approach is also presented in \\cite{lee2015distributed} for SVRG algorithm.\n\\end{itemize}\n\n\\section{SAGA algorithm} \\label{sec1}\n\nThe algorithm starts with some known initial vector $x^0 \\in \\R^d$ and known\nderivatives $f_i' (\\phi_i^0) \\in \\R^d$ with $\\phi_i^0 = x^0$ for each $i$. These\nderivatives are stored in a table data-structure of length $n$, or alternatively\na $n \\times d$ matrix. It uses a step size of $\\gamma$\\footnote{The authors\nrecommend a learning rate of $\\gamma=1/(2(\\mu n+L))$ in the strongly convex\ncase, $\\gamma=1/(3(\\mu n+L))$ if the strong convexity requirement only holds on\naverage and $\\gamma=1/(3L)$ for non-strongly convex problems.} and, given the\nvalue of $x^k$ and of each $f_i' (\\phi_i^k)$ at the end of iteration $k$, makes\nthe following updates for iteration $k+1$:\n\\begin{enumerate}\n\\item Pick a $j$ uniformly at random.\n\\item Take $\\phi_j^{k+1} = x^k$, and store $f_j'(\\phi_j^{k+1})$ in the table.\n\tAll other entries in the table remain unchanged. The quantity $\\phi_j^{k+1}$\n\tis not explicitly stored.\n\\item Update $x$ using $f_j'(\\phi_j^{k+1})$, $f_j'(\\phi_j^k)$ and the table\n\taverage:\n\t\\begin{equation} \\label{eqn:saga}\n\tw^{k+1} = x^k - \\gamma \\left[ f_j'(\\phi_j^{k+1}) - f_j'(\\phi_j^k)\n\t+ \\frac1n \\sum_{i=1}^n f_i'(\\phi_i^k) \\right] ,\n\t\\end{equation}\n\t$$x^{k+1} = \\prox_\\gamma^h (w^{k+1}).$$\n\\end{enumerate}\n\nAs the authors of \\cite{defazio_saga_2014}, we tested our algorithms by training\na linear regression model (with $\\ell_1$ or $\\ell_2$ regularization) on the\nMillion Song dataset\\footnote{\n\\url{http://labrosa.ee.columbia.edu/millionsong}}. The problem, as stated on the\nUCI repository\\footnote{\n\\url{http://archive.ics.uci.edu/ml/datasets/YearPredictionMSD}} where the data\nwas downloaded from, is to predict the release year of a song from audio\nfeatures.\n\n\\section{Mini-batch SAGA}\n\nWe first form $\\frac{n}m$ mini-batches $\\{\\B_i\\}_{i=1}^{\\frac{n}m}$ of size\n$|\\B_i| = m$ and take gradients w.r.t. them, such that the gradient matrix is of\nsize $\\frac{n}m \\times d$ instead of $n \\times d$. The updates for iteration\n$k+1$ then becomes:\n\\begin{enumerate}\n\\item Pick a $i$ uniformly at random in $[1, \\frac{n}m]$.\n\\item Take $\\phi_j^{k+1} = x^k \\ \\forall \\ j \\in \\B_i$, and store $\\frac1m\n\t\\sum_{j\\in\\B_i} f_j'(\\phi_j^{k+1})$ in the table.\n\\item Update $x^{k+1} = \\prox_\\gamma^h \\left\\{\n\tx^k - \\gamma \\left[ \\frac1m \\sum_{j\\in\\B_i} f_j'(\\phi_j^{k+1})\n\t- \\frac1m \\sum_{j\\in\\B_i} f_j'(\\phi_j^k)\n\t+ \\frac1n \\sum_{i=1}^m \\sum_{j\\in\\B_i} f_j'(\\phi_j^k) \\right] \\right\\}.$\n\\end{enumerate}\n\nNote that one can usually vectorize the computation of $\\sum_{j\\in\\B_i}\nf_j'(\\phi_j^k)$. E.g. for a least-square problem $\\min_x \\frac12 \\|Ax -\ny\\|_2^2$, the gradient is given by $A_{\\B_i}^T A_{\\B_i} x$, where $A_{\\B_i}$\nrepresents the $m$ columns of $A$ selected by the mini-batch $\\B_i$. That is\nwhere the computational advantage of the mini-batch approach comes from.\n\nNote that mini-batches can be formed during initialization and kept intact for\nthe whole training. They can alternatively be reformed at the beginning of each\ntraining epoch. While this is much more expensive, because the gradient matrix\nhas to be initialized again, we found no difference in performance.\n\n\\subsection{Experiments}\n\nWhile the convergence rate is the same for all mini-batch sizes given the same\nlearning rate, larger mini-batches need a smaller learning rate to avoid\ndivergence.  We therefore ran experiments with various mini-batch sizes $m$;\nwith an optimized learning rate $\\gamma$ for each. \\figref{eval_saga_mb} clearly\nshows that mini-batch SAGA can outperform regular SAGA in convergence time while\nrequiring less memory. Other simulation results as well as the problem explanation can be found in Ipython notebook file. This file contains the authors of \\cite{defazio_saga_2014} implementation in Cython which is used to assess our implementation.\n\n\\begin{figure*}[ht]\n\t\\centering\n\t\\subfigure[Working memory to store gradients.]{\n\t\t\\label{fig:memory}\n\t\t\\includegraphics[height=3cm,width=7cm]{figs/memory}}\n\t\\hspace{0pt}\n\t\\subfigure[$R^2$ score on test set after 100s training.]{\n\t\t\\label{fig:r2_score}\n\t\t\\includegraphics[height=3cm,width=7cm]{figs/r2_score}}\n\t\\\\\n\t\\subfigure[Objective w.r.t. running time.]{\n\t\t\\label{fig:perf}\n\t\t\\includegraphics[height=4cm,width=12cm]{figs/perf}}\n\t\\caption{Performance evaluations of mini-batch SAGA w.r.t. various\n\tmini-batch sizes $m$.}\n\t\\label{fig:eval_saga_mb}\n\\end{figure*}\n\n\\section{Distributed SAGA}\n\n\\begin{figure*}[ht]\n\t\\centering\n\t\\subfigure[First variant.]{\n\t\t\\label{fig:architecture_1}\n\t\t\\includegraphics[height=3cm,width=0.48\\columnwidth]{figs/architecture_1}}\n\t\\hspace{0pt}\n\t\\subfigure[Second variant.]{\n\t\t\\label{fig:architecture_2}\n\t\t\\includegraphics[height=3cm,width=0.48\\columnwidth]{figs/architecture_2}}\n\t\\caption{Two variants of distributed SAGA.}\n\t\\label{2figs-show}\n\\end{figure*}\n\n\\paragraph{Variant I.} A first approach, shown in \\figref{architecture_1}, is to\nrandomly partition the $n$ data points onto $m$ machines with $n/m$ local data\npoints on each to parallelize the computation of \\eqnref{saga}. Formally\nspeaking, at each epoch, we first randomly partition the data into $m$ different\nsets. We then apply the SAGA algorithm presented in Section~\\ref{sec1} for each\ndataset on $m$ different machine. After one pass over each subset, the results\nare combined by updating the gradient table and candidate solution. The updates\nfor epoch $e$ for each $k+1$ then become:\n\\begin{enumerate}\n\t\\item Randomly partition the dataset into $m$ non-overlapping sets $R_1,\n\t\t\\cdots, R_m$.\n\t\\item For each machine $s \\in \\{ 1, \\cdots, m \\}$, pick a random sample\n\t\t$x^k(s)$ from $R_s$.\n\t\\begin{enumerate}\n\t\t\\item If $ k = 1 $ then $x^k(s) = x(e)$.\n\t\t\\item Take $\\phi_j^{k+1}(s) = x^k(s)$.\n\t\t\\item Update $x^{k+1}(s) = \\prox_\\gamma^h \\left\\{ \n\t\t\tx^k(s) - \\gamma \\left[ f_j'(\\phi_j^{k+1}(s)) - f_j'(\\phi_j^k(s))\n\t\t\t+ \\frac1n \\sum_{j \\in R_i} f_j'(\\phi_j^k(s)) \\right] \\right\\}.$\n\t\t\\item If $ k > n/m$, break.\n\t\t\\item $k = k+1$.\n\t\\end{enumerate}\t\n\t\\item Merge the results with $ x(e+1) = \\frac{1}{m} \\sum_{s=1}^m x^k(s)$.\n\\end{enumerate}\n\n\\paragraph{Variant II.} A second approach, shown in \\figref{architecture_2},\nis to randomly pick $m$ data points and send one to each of the $m$ machines.\nEach machine then computes \\eqnref{saga} in parallel. All results are finally\naveraged. The updates for iteration $k+1$ then become:\n\\begin{enumerate}\t\n\t\\item For each machine $s \\in \\{ 1, \\cdots, m \\}$\n\t\\begin{enumerate}\n\t\t\\item Pick a random number $j$ in $[1, n]$.\n\t\t\\item Take $\\phi_j^{k+1}(s) = x^k(s)$, and store $f_j'(\\phi_j^{k+1}(s))$\n\t\t\tin the table.\n\t\t\\item Update $x^{k+1}(s) = \\prox_\\gamma^h \\left\\{\n\t\t\tx^k(s) - \\gamma \\left[ f_j'(\\phi_j^{k+1}(s)) - f_j'(\\phi_j^k(s))\n\t\t\t+ \\frac1n \\sum_{i=1}^n f_i'(\\phi_i^k(s)) \\right] \\right\\}.$\n\t\\end{enumerate}\n\t\\item Merge the results with $ x^{k+1} = \\frac{1}{m} \\sum_{s=1}^m\n\t\tx^{k+1}(s)$.\n\\end{enumerate}\n\n\\subsection{Experiments}\n\nIn this experiment, we set the $\\ell_2$ regularization factor to $5\\times\n10^{-4}$ while we use $n=10^4$ training samples and $m=8$ different machines (or\nCPU cores). \\figref{distributed_perf} shows the performance of our distributed\nmethods. A good choice of learning rate, as for all gradient methods, is crucial\nas shown in \\figref{arch1_lr} and \\figref{arch2_lr}. Moreover,\n\\figref{arch2_par} presents the required time for 1000 iterations using\ndifferent models, namely using parfor loop which is the pure distributed\nimplementation, for loop which is a serial implementation, and vectorized\nimplementation which relies on parallel implementation of linear algebra\nlibraries in MATLAB. The results show an heavy communication overhead for\nparfor.\n\n\\begin{figure*}[ht]\n\t\\centering\n\t\\subfigure[Variant I: learning rate.]{\n\t\t\\label{fig:arch1_lr}\n\t\t\\includegraphics[width=0.31\\columnwidth]{figs/arch1_lr.eps}}\n\t\\hspace{0pt}\n\t\\subfigure[Variant II: different parallelizations.]{\n\t\t\\label{fig:arch2_par}\n\t\t\\includegraphics[width=0.31\\columnwidth]{figs/arch2_par.eps}}\n\t\\hspace{0pt}\n\t\\subfigure[Variant II: learning rate.]{\n\t\t\\label{fig:arch2_lr}\n\t\t\\includegraphics[width=0.31\\columnwidth]{figs/arch2_lr.eps}}\n\t\\caption{Performance measures of distributed SAGA.}\n\t\\label{fig:distributed_perf}\n\\end{figure*}\n\n\\figref{conv} compares the two proposed approaches in term of convergence\nrate. Variant I converges faster in running time while variant II converges\nfaster in the number of iterations.\n\n\\begin{figure*}[ht]\n\t\\centering\n\t\\subfigure[Convergence w.r.t. the number of iterations.]{\n\t\t\\label{fig:conv_iterations}\n\t\t\\includegraphics[width=0.31\\columnwidth]{figs/conv_iterations.eps}}\n\t\\hspace{0pt}\n\t\\subfigure[Convergence w.r.t. running time.]{\n\t\t\\label{fig:conv_time}\n\t\t\\includegraphics[width=0.31\\columnwidth]{figs/conv_time.eps}}\n\t\\caption{Comparison between two distributed SAGA algorithms and regular SAGA.}\n\t\\label{fig:conv}\n\\end{figure*}\n\n\\bibliography{refs}\n\\bibliographystyle{abbrv}\n\n\\end{document}\n", "meta": {"hexsha": "fbe1be0adf48513d3bff1d7f656ee2262f97c209", "size": 12184, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report.tex", "max_stars_repo_name": "mdeff/saga", "max_stars_repo_head_hexsha": "040c262aaabfa6eacf2bd67fb0a05d95feed83a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2016-09-07T10:41:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-25T16:48:18.000Z", "max_issues_repo_path": "report.tex", "max_issues_repo_name": "mdeff/saga", "max_issues_repo_head_hexsha": "040c262aaabfa6eacf2bd67fb0a05d95feed83a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report.tex", "max_forks_repo_name": "mdeff/saga", "max_forks_repo_head_hexsha": "040c262aaabfa6eacf2bd67fb0a05d95feed83a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2016-09-07T16:49:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-16T03:14:04.000Z", "avg_line_length": 45.4626865672, "max_line_length": 249, "alphanum_fraction": 0.7358010506, "num_tokens": 3899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.3047827696346016}}
{"text": "\\documentclass[oneside,openright]{report}\n\\usepackage[ruled,vlined]{algorithm2e}\n\\usepackage{color}\n\\definecolor{darkblue}{cmyk}{1,1,0,0.7}\n\\usepackage[dvipdfm,colorlinks=true,linkcolor=darkblue]{hyperref}\n\\newcommand{\\note}[1]{$[\\![$NB: #1$]\\!]$}\n\\setlength{\\parindent}{0pt}\n%\\setlength{\\topmargin}{-40pt}\n%\\setlength{\\oddsidemargin}{-16pt}\n%\\setlength{\\evensidemargin}{-16pt}\n%\\setlength{\\textwidth}{522pt}\n%\\setlength{\\textheight}{700pt}\n\\setcounter{secnumdepth}{3}\n\\setcounter{tocdepth}{3}\n\n\\title{Speeding up the Conjugate Gradient: EigenCG}\n\\author{Andrew Pochinsky, Sergey Syritsyn}\n\\catcode`\\$=11\n\\date{$Id: eigen-cg.tex 1307 2010-01-17 21:48:14Z avp $\\\\\nRelease working}\n\\catcode`\\$=3\n\n\\begin{document}\n\\maketitle\n\\thispagestyle{empty}\\hbox{}\n\\vfill\n\\copyright 2010 Massachusetts Institute of Technology\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\nLIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\\pagebreak\n\n\\tableofcontents\n%\\vfill\n%\\pagebreak\n\n\\listofalgorithms\n%\\vfill\n%\\pagebreak\n\n\\chapter{ALGORITHMS}\n\\section{Conjugate gradient}\nThe equation\n\\[\n   M^\\dagger M \\psi = \\chi\n\\]\ncan be solved by the conjugate gradient method if the condition number of\n $M^\\dagger M$ is small enough. Function \\texttt{plainCG()} implements the standard CG solver.\n\\begin{function}\n\\KwIn{$M$, the matrix}\n\\KwIn{$\\chi$, the right hand side of the linear equation}\n\\KwIn{$n$, the maximum number of iterations}\n\\KwIn{$\\epsilon$, required precision}\n\\KwOut{$\\psi$, approximate solution}\n\\KwOut{$r$, final residue}\n\\KwOut{$k$, number of iterations used}\n\\KwOut{$z$, was the last $\\pi$ a zero vector of $M$?}\n\\SetKw{Break}{break}\n\\SetKw{Or}{or}\n\\SetKw{False}{false}\n\\SetKw{True}{true}\n\\DontPrintSemicolon\n\\Begin{\n  $\\psi\\leftarrow 0$\\;\n  $\\rho\\leftarrow \\chi$\\;\n  $\\pi\\leftarrow \\rho$\\;\n  $r\\leftarrow\\langle \\rho,\\rho\\rangle$\\;\n  $\\epsilon\\leftarrow r \\times\\epsilon$\\;\n  $k\\leftarrow 0$\\;\n  \\While{$r > \\epsilon$ \\and $k < n$}{\n    $\\omega\\leftarrow M\\pi$\\;\n    $\\zeta\\leftarrow M^{\\dagger}\\omega$\\;\n    $c\\leftarrow \\langle \\omega,\\omega\\rangle$\\;\n    \\lIf{$c = 0$}{\n      \\Return{$\\psi$, $r$, $k$, \\True}\n    }\\;\n    $a\\leftarrow r/c$\\;\n    $\\rho\\leftarrow \\rho - a \\zeta$\\;\n    $g\\leftarrow \\langle \\rho,\\rho\\rangle$\\;\n    $\\psi\\leftarrow \\psi + a \\pi$\\;\n    $k\\leftarrow k + 1$\\;\n    \\lIf{$ g<\\epsilon$}{ \\Return{$\\psi$, $g$, $k$, \\False}}\\;\n    $b\\leftarrow g/r$\\;\n    $r\\leftarrow g$\\;\n    $\\pi\\leftarrow \\rho + b \\pi$\\;\n  }\n  \\Return {$\\psi$, $r$, $k$, \\False}\\;\n}\n\n\\caption{plainCG($M$, $\\chi$, $n$, $\\epsilon$)}\n\\end{function}\n\n\\section{Mixed Conjugate Gradient}\nOn many platforms reducing precision of the operator results in considerable speedup. If one needs the double precision inverter, one can use \\texttt{mixedCG()} if implementations of $M$ are available in both precisions. It is convenient to have two separate tolerance levels: one for the full inverter, and another for the inner fast one.\n\n\\begin{function}\n\\KwIn{$M$, the matrix in double precision}\n\\KwIn{$M_1$, the matrix in single precision}\n\\KwIn{$\\chi$, the right hand side of the linear equation}\n\\KwIn{$n$, the maximum number of iterations}\n\\KwIn{$\\epsilon$, required total precision}\n\\KwIn{$\\epsilon_1$, required inner precision}\n\\KwOut{$\\psi$, approximate solution}\n\\KwOut{$r$, final residue}\n\\KwOut{$k$, number of iterations used}\n\\KwOut{$z$, was the last $\\pi$ a zero vector of $M$?}\n\\SetKw{Break}{break}\n\\SetKw{And}{and}\n\\SetKw{False}{false}\n\\SetKw{True}{true}\n\\SetKwFunction{plainCG}{plainCG}\n\\DontPrintSemicolon\n\\Begin{\n  $\\psi\\leftarrow 0$\\;\n  $r\\leftarrow \\langle\\chi,\\chi\\rangle$\\;\n  $\\epsilon\\leftarrow r\\times\\epsilon$\\;\n  $k\\leftarrow 0$\\;\n  \\While{$k < n$}{\n    $\\eta\\leftarrow\\chi - M^\\dagger \\times M \\times \\psi$\\;\n    $r\\leftarrow\\langle\\eta,\\eta\\rangle$\\;\n    \\lIf{$r<\\epsilon$}{\\Return{$\\psi$, $r$, $k$, \\False}}\\;\n    $\\eta\\leftarrow\\eta/$sqrt$(r)$\\;\n    $\\delta, q, m, z\\leftarrow$\\plainCG{$M_1$, $\\eta$, $n-k$, $\\max(\\epsilon/r, \\epsilon_1)$}\\;\n    \\lIf{$z$ \\And $m=0$}{\\Return{$\\psi$, $r\\times q$, $k$, \\True}}\\;\n    $\\psi\\leftarrow\\psi+$sqrt$(r)\\times\\delta$\\;\n    $k\\leftarrow k + m$\\;\n  }\n  $\\eta\\leftarrow\\chi - M^\\dagger \\times M \\times \\psi$\\;\n  $r\\leftarrow\\langle\\eta,\\eta\\rangle$\\;\n  \\Return{$\\psi$, $r$, $k$, \\False}\\;\n}\n\\caption{mixedCG($M$, $M_1$, $\\chi$, $n$, $\\epsilon$, $\\epsilon_1$)}\n\\end{function}\n%\\end{document}\n%%%%%%%%%%%%%%%%%%%%%%%% TODO\n\\section{EigenCG}\nIf the condition number of $M^\\dagger M$ is large, convergence of the conjugate gradient is slow. In this case one could try to improve the situation by finding small eigenvectors of $M^\\dagger M$ and projecting them out of the solver. One variant of this method is given by \\texttt{eigenCG}. The low eigen space is managed by $S$ which is manipulated by the set of routines described in the following sections.\n\nSince single precision is 50\\% faster than double precision for clover action on the BlueGene,\nwe use two representations of $M$ and construct the eigen space in single precision. \nIt is not strictly necessary, though.\n\n\\begin{function}\n\\SetKwInOut{KwInOut}{In/out}\n\\KwInOut{$S$, the eigen space state}\n\\KwIn{$M$, the matrix in double precision}\n\\KwIn{$M_1$, the matrix in single precision}\n\\KwIn{$\\chi$, the right hand side of the linear equation}\n\\KwIn{$n$, the maximum number of iterations}\n\\KwIn{$\\epsilon$, required total precision}\n\\KwIn{$\\epsilon_1$, required inner precision}\n\\KwOut{$\\psi$, approximate solution}\n\\KwOut{$r$, final residue}\n\\KwOut{$k$, number of iterations used}\n\\KwOut{$z$, was the last $\\pi$ a zero vector of $M$?}\n\\SetKw{Break}{break}\n\\SetKw{And}{and}\n\\SetKw{False}{false}\n\\SetKw{True}{true}\n\\SetKwFunction{innerCG}{innerCG}\n\\DontPrintSemicolon\n\\Begin{\n  $\\psi\\leftarrow 0$\\;\n  $r\\leftarrow \\langle\\chi,\\chi\\rangle$\\;\n  $\\epsilon\\leftarrow r\\times\\epsilon$\\;\n  $k\\leftarrow 0$\\;\n  \\While{$k < n$}{\n    $\\eta\\leftarrow\\chi - M^\\dagger \\times M \\times \\psi$\\;\n    $r\\leftarrow\\langle\\eta,\\eta\\rangle$\\;\n    \\lIf{$r<\\epsilon$}{\\Return{$\\psi$, $r$, $k$, \\False}}\\;\n    $\\eta\\leftarrow\\eta/$sqrt$(r)$\\;\n    $\\delta, q, m, z\\leftarrow$\\innerCG{$S$, $M_1$, $\\eta$, $n-k$, $\\max(\\epsilon/r, \\epsilon_1)$}\\;\n    \\lIf{$z$ \\And $m = 0$}{\\Return{$\\psi$, $r\\times q$, $k$, \\True}}\\;\n    $\\psi\\leftarrow \\psi + $sqrt$(r)\\times\\delta$\\;\n    $k\\leftarrow k + m$\\;\n  }\n  $\\eta\\leftarrow\\chi - M^\\dagger \\times M \\times \\psi$\\;\n  $r\\leftarrow\\langle\\eta,\\eta\\rangle$\\;\n  \\Return{$\\psi$, $r$, $k$, \\False}\\;\n}\n\\caption{eigenCG($S$, $M$, $M_1$, $\\chi$, $n$, $\\epsilon$, $\\epsilon_1$)}\n\\end{function}\n\nThe \\texttt{innerCG} is very similar to \\texttt{plainCG}. There are two differences: (a) the initial values of $\\rho$ and $\\psi$ are obtained from $S$, and (b) $S$ is updated after every application of $M^\\dagger M$.\n\n\\begin{function}\n\\SetKwInOut{KwInOut}{In/out}\n\\KwInOut{$S$, the eigen space state}\n\\KwIn{$M$, the matrix}\n\\KwIn{$\\chi$, the right hand side of the linear equation}\n\\KwIn{$n$, the maximum number of iterations}\n\\KwIn{$\\epsilon$, required precision}\n\\KwOut{$\\psi$, approximate solution}\n\\KwOut{$r$, final residue}\n\\KwOut{$k$, number of iterations used}\n\\KwOut{$z$, was the last $\\pi$ a zero vector of $M$?}\n\\SetKw{Break}{break}\n\\SetKw{And}{and}\n\\SetKw{False}{false}\n\\SetKw{True}{true}\n\\SetKwFunction{eigSpStart}{eigSpStart}\n\\SetKwFunction{eigSpUpdate}{eigSpUpdate}\n\\DontPrintSemicolon\n\\Begin{\n  $\\psi\\leftarrow$\\eigSpStart($S$, $\\chi$)\\;\n  $\\rho\\leftarrow\\chi-M^\\dagger\\times M \\times \\psi$\\;\n  $\\pi\\leftarrow \\rho$\\;\n  $r\\leftarrow\\langle \\rho,\\rho\\rangle$\\;\n  \\lIf{$r = 0$}{\n     \\Return{$\\psi$, 0, 0, \\False}\n  }\\;\n  $k\\leftarrow 0$\\;\n  \\While{$r > \\epsilon$ \\And $k < n$}{\n    $\\omega\\leftarrow M\\pi$\\;\n    $\\zeta\\leftarrow M^{\\dagger}\\omega$\\;\n    $c\\leftarrow \\langle \\omega,\\omega\\rangle$\\;\n    \\lIf{$c = 0$}{\n      \\Return{$\\psi$, $r$, $k$, \\True}\n    }\\;\n    \\eigSpUpdate{$S$, $\\pi$, $\\zeta$}\\;\n    $a\\leftarrow r/c$\\;\n    $\\rho\\leftarrow \\rho - a \\zeta$\\;\n    $ g \\leftarrow \\langle \\rho,\\rho\\rangle$\\;\n    $\\psi\\leftarrow \\psi + a \\pi$\\;\n    $k\\leftarrow k + 1$\\;\n    \\lIf{$ g<\\epsilon$}{\\Return {$\\psi$, $g$, $k$, \\False }} \\;\n    $b\\leftarrow g/r$\\;\n    $r\\leftarrow g$\\;\n    $\\pi\\leftarrow \\rho + b \\pi$\\;\n  }\n  \\Return {$\\psi$, $r$, $k$, \\False}\n}\n\\caption{innerCG($S$, $M$, $\\chi$, $n$, $\\epsilon$)}\n\\end{function}\n\n\\section{Eigen space state}\nHere are routines operating on the eigen space state $S$.\nIn the production implementation $S$ is likely to be a part of the solver state\n\\subsection{Constructor, \\texttt{eigSpInit()}}\nInitialize state variables and allocate space. The tolerance $\\epsilon$ controls how small\na vector has to be to be considered a round-off error.\n\\begin{function}\n\\KwIn{$n$, the number of eigenvectors to keep}\n\\KwIn{$m$, the maximum dimension of the eigen space, $m > n$}\n\\KwIn{$\\epsilon$, required precision}\n\\KwOut{$S$, the eigen space state}\n\\SetKw{False}{false}\n\\SetKw{True}{true}\n\\DontPrintSemicolon\n\\Begin{\n $S\\leftarrow$ alloc structure\\;\n $S.k\\leftarrow 0$\\;\n $S.n\\leftarrow n$\\;\n $S.m\\leftarrow m$\\;\n $S.\\epsilon\\leftarrow \\epsilon$\\;\n $S.blocked \\leftarrow$\\False\\;\n $S.ready \\leftarrow$\\False\\;\n $S.w\\leftarrow$ alloc $n$ vectors\\tcp*{space for eigenvectors $w$}\\;\n $S.Aw\\leftarrow$ alloc $n$ vectors\\tcp*{space for $Aw$}\\;\n $S.v\\leftarrow$ alloc $m$ vectors\\tcp*{space for basis vectors $v$}\\;\n $S.Av\\leftarrow$ alloc $m$ vectors\\tcp*{space for $Av$}\\;\n $S.H\\leftarrow$ alloc $m\\times m$ complex matrix\\tcp*{space for $\\langle v,Av\\rangle$}\\;\n $S.U\\leftarrow$ alloc $m\\times m$ complex matrix\\tcp*{space for $H^{-1}$}\\;\n $S.\\lambda\\leftarrow$ alloc $m$ reals\\tcp*{space for eigenvalues}\\;\n $S.\\beta\\leftarrow$ alloc $(m-1)$ reals\\tcp*{space for off-diagonal}\\;\n  \\Return {$S$}.\n}\n\\caption{eigSpInit($n$, $m$, $\\epsilon$)}\n\\end{function}\n\n\\subsection{Destructor, \\texttt{eigSpFini()}}\nFree all allocated space and free the structure\n\\begin{function}\n\\SetKwInOut{KwInOut}{In/out}\n\\KwInOut{$S$, the eigen space state}\n\\SetKw{False}{false}\n\\SetKw{True}{true}\n\\DontPrintSemicolon\n\\Begin{\n free $S.w$\\;\n free $S.Aw$\\;\n free $S.v$\\;\n free $S.Av$\\;\n free $S.H$\\;\n free $S.U$\\;\n free $S.\\lambda$\\;\n free $S.\\beta$\\;\n free $S$\\;\n}\n\\caption{eigSpFini($S$)}\n\\end{function}\n\n\\subsection{Update Activation, \\texttt{eigSpEnable()}}\nIt is useful to be able to shut down and enable the updater.\n\\begin{function}\n\\SetKwInOut{KwInOut}{In/out}\n\\KwInOut{$S$, the eigen space state}\n\\SetKw{False}{false}\n\\SetKw{True}{true}\n\\DontPrintSemicolon\n\\Begin{\n $S.$blocked$\\leftarrow$\\False\\;\n}\n\\caption{eigSpEnable($S$)}\n\\end{function}\n\n\\subsection{Update Deactivation, \\texttt{eigSpDisable()}}\nIt is useful to be able to shut down and enable the updater.\n\\begin{function}\n\\SetKwInOut{KwInOut}{In/out}\n\\KwInOut{$S$, the eigen space state}\n\\SetKw{False}{false}\n\\SetKw{True}{true}\n\\DontPrintSemicolon\n\\Begin{\n $S.$blocked$\\leftarrow$\\True\\;\n}\n\\caption{eigSpDisable($S$)}\n\\end{function}\n\n\\subsection{Starting the solver, \\texttt{eigSpStart()}}\nWhen $S$ is ready, the solver starter subtracts found eigenvectors and adjusts\nthe solution accordingly. For this routine to work, $S.Aw$ must be orthonormal, e.g.,\n$\\langle S.Aw[i], S.Aw[j]\\rangle=\\delta_{ij}$ and\n$S.Aw[k]=M^\\dagger M S.w[k]$ for each $k$.\n\\begin{function}\n\\KwIn{$S$, the eigen space state}\n\\KwIn{$\\chi$, the right hand side}\n\\KwOut{$\\psi$, the partial solution}\n\\SetKw{False}{false}\n\\SetKw{True}{true}\n\\DontPrintSemicolon\n\\Begin{\n  $\\psi\\leftarrow 0$\\;\n  \\If{$S.$ready}{\n    \\For(// remove eigen space parts from $\\rho$ and $\\psi$){$0\\le k < S.n$}{\n      $a\\leftarrow\\langle S.Aw[k], \\chi\\rangle$\\;\n      $\\psi\\leftarrow\\psi-a\\times S.w[k]$\\;\n    }\n  }\n  \\Return{$\\rho$, $\\psi$}\\;\n}\n\\caption{eigSpStart($S$, $\\chi$)}\n\\end{function}\n\n\\subsection{Updating the state, \\texttt{eigSpUpdate()}}\nAdd a pair $\\psi$, $\\chi=M^\\dagger M \\psi$ to $S$. The external procedure \\texttt{EigenV()} computes\nthe transformation to the eigenbasis with the eigenvalues in the increasing order.\n\\begin{function}\n\\SetKwInOut{KwInOut}{In/out}\n\\KwInOut{$S$, the eigen space state}\n\\KwIn{$\\psi$, a new eigen space vector}\n\\KwIn{$\\chi$, computed $M^\\dagger M \\psi$}\n\\SetKw{False}{false}\n\\SetKw{True}{true}\n\\SetKwFunction{eigSpBuildLow}{eigSpBuildLow}\n\\DontPrintSemicolon\n\\Begin{\n  \\lIf{S.blocked}{\n    \\Return{}\\;\n  }\n  $k\\leftarrow S.k$\\;\n  \\tcp{add and normalize $\\psi$ and $\\chi$ to $S$}\n  $S.v[k]\\leftarrow\\psi$\\;\n  $S.Av[k]\\leftarrow\\chi$\\;\n  $a\\leftarrow\\langle\\psi, \\psi\\rangle$\\;\n  \\For{$0 \\le i < k$}{\n    $b\\leftarrow\\langle S.v[i], S.v[k]\\rangle$\\;\n    $c\\leftarrow a-|b|^2$\\;\n    \\tcp{check that there is something left still}\n    \\lIf{$c < a\\times S.\\epsilon$}{\\Return{}\\;}\n    $S.v[k]\\leftarrow  S.v[k] - b \\times S.v[i]$\\;\n    $S.Av[k]\\leftarrow S.Av[k] - b \\times S.Av[i]$\\;\n    $a\\leftarrow c$\\;\n  }\n  $a\\leftarrow\\langle S.v[k], S.v[k]\\rangle$\\;\n  $d\\leftarrow 1/$sqrt$(a)$\\;\n  $S.v[k]\\leftarrow d \\times S.v[k] $\\;\n  $S.Av[k]\\leftarrow d \\times S.Av[k]$\\;\n  $S.k\\leftarrow S.k + 1$\\;\n  \\tcp{space is full. Find eigenvalues}\n  \\If{$S.k = S.m$}{\n    \\eigSpBuildLow{$S$}\\;\n    $S.k\\leftarrow S.n$\\;\n    $S.ready\\leftarrow\\True$\\;\n  }\n}\n\\caption{eigSpUpdate($S$, $\\psi$, $\\chi$)}\n\\end{function}\n\n\\begin{function}\n\\SetKwInOut{KwInOut}{In/out}\n\\KwInOut{$S$, the eigen space state}\n\\SetKw{False}{false}\n\\SetKw{True}{true}\n\\SetKwFunction{EigenT}{EigenT}\n\\SetKwFunction{eigSpOrtho}{eigSpOrtho}\n\\DontPrintSemicolon\n\\Begin{\n    \\tcp{compute $S.H$}\n    \\For{$0\\le i < S.m$}{\n       $S.H[i,i]\\leftarrow $Re$\\langle S.v[i],S.Av[i]\\rangle$\\;\n       \\For{$0\\le j < i$}{\n          $a\\leftarrow\\langle S.v[j],S.Av[i]\\rangle$\\;\n          $S.H[j,i]\\leftarrow a$\\;\n          $S.H[i,j]\\leftarrow $conj$(a)$\\;\n       }\n    }\n    $S.U\\leftarrow$\\EigenT{$S.H$, $S$}\\;\n    \\tcp{Compute $S.Aw$ and $S.w$}\n    \\For{$0\\le i < S.n$}{\n       $S.w[i]\\leftarrow 0$\\;\n       $S.Aw[i]\\leftarrow 0$\\;\n       \\For{$0\\le j < S.m$}{\n         $S.w[i]\\leftarrow S.w[i] + S.U[i.j] \\times S.v[j]$\\;\n         $S.Aw[i]\\leftarrow S.Aw[i] + S.U[i,j] \\times S.Av[j]$\\;\n       }\n    }\n    \\tcp{Copy $S.w$ and $S.Aw$ back to $S.v$ and $S.Av$}\n    \\For{$0\\le i < S.n$}{\n       $S.v[i]\\leftarrow S.w[i]$\\;\n       $S.Av[i]\\leftarrow S.Aw[i]$\\;\n    }\n    \\eigSpOrtho{$S$}\\;\n}\n\\caption{eigSpBuildLow($S$)}\n\\end{function}\n\n\\subsection{Recomputing the operator, \\texttt{eigSpRecompute()}}\nIf too many linear algebra operations were performed, one might want to\nrecompute the operator.\n\\begin{function}\n\\SetKwInOut{KwInOut}{In/out}\n\\KwInOut{$S$, the eigen space state}\n\\KwIn{$M_1$, the right hand side}\n\\SetKw{False}{false}\n\\SetKw{True}{true}\n\\SetKwFunction{eigSpOrtho}{eigSpOrtho}\n\\DontPrintSemicolon\n\\Begin{\n  \\For(// compute $S.Av$){$0\\le i < S.k$}{\n    $S.Av[i] = M^\\dagger \\times M \\times S.v[i]$\\;\n  }\n  \\If{$S.$ready}{\n    \\For(// compute $S.Aw$){$0\\le i < S.n$}{\n       $S.Aw[i] = M^\\dagger \\times M \\times S.w[i]$\\;\n    }\n    \\eigSpOrtho{$S$}\\;\n    }\n}\n\\caption{eigSpRecompute($S$, $M_1$)}\n\\end{function}\n\n\\begin{function}\n\\SetKwInOut{KwInOut}{In/out}\n\\KwInOut{$S$, the eigen space state}\n\\SetKw{False}{false}\n\\SetKw{True}{true}\n\\DontPrintSemicolon\n\\Begin{\n    \\For(// reorthogonalize $S.Aw$){$0\\le i < S.n$}{\n       \\For{$0\\le j < i$}{\n          $a\\leftarrow \\langle S.Aw[j], S.Aw[i]\\rangle$\\;\n          $S.Aw[i]\\leftarrow S.Aw[i] - a \\times S.Aw[j]$\\;\n          $S.w[i]\\leftarrow S.w[i] - a \\times S.w[j]$\\;\n       }\n       $a \\leftarrow \\langle S.Aw[i], S.Aw[i]\\rangle$\\;\n       $b\\leftarrow 1/$sqrt $a$\\;\n       $S.Aw[i]\\leftarrow b \\times S.Aw[i]$\\;\n       $S.w[i]\\leftarrow b \\times S.w[i]$\\;\n   }\n}\n\\caption{eigSpOrtho($S$)}\n\\end{function}\n\n\\end{document}\n", "meta": {"hexsha": "4103aad9709263cacf81474acbe8a5304ba95736", "size": 16434, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "noweb/eigen-cg.tex", "max_stars_repo_name": "usqcd-software/mdwf", "max_stars_repo_head_hexsha": "71327aea0cbcd21107518165800989496d87d4b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-24T06:44:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-24T06:44:43.000Z", "max_issues_repo_path": "noweb/eigen-cg.tex", "max_issues_repo_name": "usqcd-software/mdwf", "max_issues_repo_head_hexsha": "71327aea0cbcd21107518165800989496d87d4b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "noweb/eigen-cg.tex", "max_forks_repo_name": "usqcd-software/mdwf", "max_forks_repo_head_hexsha": "71327aea0cbcd21107518165800989496d87d4b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3346855984, "max_line_length": 411, "alphanum_fraction": 0.6524278934, "num_tokens": 5784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.30474335585607076}}
{"text": "\\graphicspath{{Pics/}}\n\n\\newpage\\section{Circles and Radical Axises}\n\t\n\t\n\t\n\t\\prob{}{}{E}{In $\\triangle ABC$, $H$ is the orthocenter, and $AD, BE$ are arbitrary cevians. Let $\\omega_1, \\omega_2$ denote the circles with diameters $AD, BE$ resp. $HD, HE$ meet $\\omega_1, \\omega_2$ again at $F,G$. $DE$ meet $\\omega_1, \\omega_2$ again at $P_1,P_2$. $FG$ meet $\\omega_1, \\omega_2$ again at $Q_1,Q_2$. $P_1H, P_2H$ meet $\\omega_1, \\omega_2$ at $R_1,R_2$ and $Q_1H, Q_2H$ meet $\\omega_1, \\omega_2$ at $S_1, S_2$. $P_1Q_1\\cap P_2Q_2\\equiv X$ and $R_1S_1\\cap R_2S_2\\equiv Y$. Prove that $X,Y,H$ are collinear.}\n\t\n\t\t\\solu{Too much info...}\n\t\t\n\t\t\n\t\n\t\n\t\n\t\\lem{Pseudo Miquel's Theorem}{In a $\\triangle ABC$ let $E,F$ be points on $AC,AB$ and $D$ be a point on $\\odot (ABC)$. Let $X=\\odot (BFD)\\cap \\odot (CED)$ then $E,F,X$ are collinear.}\n\t\n\t\t\\fig{.5}{PseudoMiquel}{Notice the collinearity}\n\t\n\t\n\t\n\t\n\t\n\t\n\t\\prob{https://artofproblemsolving.com/community/c74453h1225408_some_geometric_problems}{buratinogigle's proposed problems for Arab Saudi team 2015}{E}{Let $ABC$ be a triangle and $(K)$ is a circle that touches segments $CA, AB$ at $E, F$, reps. $M, N$ lie on $(K)$ such that $BM, CN$ are tangent to $(K)$. $G, H$ are symmetric of $A$ through $E, F$. The circle passes through $G$ and touches to $(K)$ at $N$ that cuts $CA$ again at $S$. The circle passes through $H$ and touches $(K)$ at $M$ that cuts $AB$ again at $T$. Prove that the line passes through $K$ and perpendicular to $ST$ always passes through a fixed point when $(K)$ changes.}\n\t\n\t\t\\fig{.7}{SATST2015proposed_by_bura/derakynay1134-3}{}\n\t\n\t\n\t\n\t\\prob{https://artofproblemsolving.com/community/c6h17322p118681}{ISL 2002 G8}{M}{Let two circles $S_{1}$ and $S_{2}$ meet at the points $A$ and $B$. A line through $A$ meets $S_{1}$ again at $C$ and $S_{2}$ again at $D$. Let $M$, $N$, $K$ be three points on the line segments $CD$, $BC$, $BD$ respectively, with $MN$ parallel to $BD$ and $MK$ parallel to $BC$. Let $E$ and $F$ be points on those arcs $BC$ of $S_{1}$ and $BD$ of $S_{2}$ respectively that do not contain $A$. Given that $EN$ is perpendicular to $BC$ and $FK$ is perpendicular to $BD$ prove that $\\angle EMF=90^{\\circ}$.}\n\t\n\t\t\n\t\t\\solu{When one single property can produce a lot others, and we need to prove this property, assume the property to be true and work backwards.}\n\t\n\t\n\t\n\t\\prob{https://artofproblemsolving.com/community/c6h79788p456609}{APMO 1999 P3}{E}{Let $\\Gamma_1$ and $\\Gamma_2$ be two circles intersecting at $P$ and $Q$. The common tangent, closer to $P$, of $\\Gamma_1$ and $\\Gamma_2$ touches $\\Gamma_1$ at $A$ and $\\Gamma_2$ at $B$. The tangent of $\\Gamma_1$ at $P$ meets $\\Gamma_2$ at $C$, which is different from $P$, and the extension of $AP$ meets $BC$ at $R$.\tProve that the circumcircle of triangle $PQR$ is tangent to $BP$ and $BR$.}\n\t\n\t\n\t\n\t\\prob{https://artofproblemsolving.com/community/c6h1751587p11419585}{USA TST 2019 P1}{E}{Let $ABC$ be a triangle and let $M$ and $N$ denote the midpoints of $\\overline{AB}$ and $\\overline{AC}$, respectively. Let $X$ be a point such that $\\overline{AX}$ is tangent to the circumcircle of triangle $ABC$. Denote by $\\omega_B$ the circle through $M$ and $B$ tangent to $\\overline{MX}$, and by $\\omega_C$ the circle through $N$ and $C$ tangent to $\\overline{NX}$. Show that $\\omega_B$ and $\\omega_C$ intersect on line $BC$.}\\label{problem:usatst2019p1}\n\t\t\n\t\t\n\t\t\\solu{[Spiral Similarity]\n\t\t\t\n\t\t\tLet $ \\omega_C \\cap BC = P $. If we extend $ NP $ to meet $ AB $ at $ R $, we get $ XANR $ cyclic. Similarly, if $ \\odot XAM\\cap AC = Q $, then we have to prove $ QM\\cap NR = P $.\\\\\n\t\t\t\n\t\t\tSuppose $ QM\\cap NR = P' $. Then by spiral similarity, $ X $ takes $ Q\\to M $ and $ N\\to R $. It also takes $ Q\\to N $ and $ M\\to R $. So $ XMP'R $ is cyclic. We now show that $ XMPR $ is also cyclic, which will prove $ P=P' $.\\\\\n\t\t\t\n\t\t\tLet $ T = \\odot ABC \\cap \\odot XAN $. By spiral similarity, $ T $ takes $ R\\to B $ and $ N\\to C $. It also takes $ R\\to N $ and $ B\\to C $, which means $ RBPT $ is cyclic. \\\\\n\t\t\t\n\t\t\t\\begin{minipage}{.45\\linewidth}\n\t\t\t\tBy spiral similarity, we have, $ \\triangle TXA \\sim \\triangle TNC,\\ \\triangle TXN \\sim \\triangle TAC,\\ \\triangle TBA \\sim \\triangle TPN $\n\t\t\t\tWhich implies,\n\t\t\t\t\n\t\t\t\t\\begin{align*}\n\t\t\t\t\\frac{XN}{TN} = \\frac{AC}{TC},\\ & \\frac{XA}{TA} = \\frac{NC}{TC}\\\\[.5em]\n\t\t\t\t\\implies \\frac{XN}{XA} &= 2\\frac{TN}{TA}\n\t\t\t\t\\end{align*}\n\t\t\t\t\n\t\t\t\tAnd so, \n\t\t\t\t\n\t\t\t\t\\begin{align*}\n\t\t\t\t\\frac{AB}{TA}=\\frac{NP}{TN}\\quad \\implies\\frac{2AM}{NP} &= \\frac{TA}{TN} = \\frac{XA}{XN}2\\\\[.5em]\n\t\t\t\t\\implies \\frac{AM}{NP} &= \\frac{XA}{XN}\n\t\t\t\t\\end{align*}\n\t\t\t\\end{minipage}\\hfill%\n\t\t\t\\begin{minipage}{.55\\linewidth}\n\t\t\t\t\\figdf{}{USATST2019P1_new}{}\n\t\t\t\\end{minipage}\n\t\t\t\n\t\t\t\\vspace{1.5em}\n\t\t\t\n\t\t\tWhich means $ \\triangle XAM \\sim \\triangle XNP $ since $ \\angle XAM = \\angle XNP $, which concludes the proof.\n\t\t}\n\t\t\n\t\t\\solu{[Clever Observation]\n\t\t\tReflect $ A $ over $ X $ to $ A' $. Draw the circle with center $ X $ with radius $ XA $. Call it $ \\omega $. Let $ P=\\omega\\cap\\odot ABC $. Let $ Q=A'B\\cap \\omega $.\n\t\t\t\t\t\t\n\t\t\t\\begin{minipage}{.45\\linewidth}\n\t\t\t\tWe will show that $ M, P, B, Q $ are cyclic, and $ XM $ is tangent to the circle.\\\\\n\t\t\t\t\n\t\t\t\tFirst, we have $ AQ\\perp A'B $. So $ MB=MQ $. Now,\n\t\t\t\t\\begin{align*}\n\t\t\t\t\\measuredangle MPQ &= \\measuredangle APQ - \\measuredangle APM\\\\\n\t\t\t\t&=\\measuredangle AA'Q - \\measuredangle ANM \\\\\n\t\t\t\t&= \\measuredangle AXM - \\measuredangle XAM\\\\\n\t\t\t\t&=\\measuredangle AMX \\\\\n\t\t\t\t&= \\measuredangle MBQ\n\t\t\t\t\\end{align*}\n\t\t\t\tSo $ M, Q, P, B $ is cyclic. Also since $ MQ=MB $, and $ XM\\parallel BQ $, $ XM $ is tangent to $ \\odot MPBQ $, and $ \\odot MPBQ = \\omega_B $.\n\t\t\t\\end{minipage}\\hfill %\n\t\t\t\\begin{minipage}{.5\\linewidth}\n\t\t\t\t\\figdf{}{USATST2019P1_1}{}\n\t\t\t\\end{minipage}\n\t\t\t\n\t\t\t\\vspace{1em}\n\t\t\t\n\t\t\tSimilarly $ \\omega_C $ passes through $ P $, and by Miquel's theorem, their intersection lies on $ BC $.\n\t\t}\n\t\t\n\t\n\t\n\t\n\t\\prob{http://artofproblemsolving.com/community/c6h1751587p11419916}{USA TST 2019 P1 parallel problem}{E}{Pick a point $X$ such that $AX$ is parallel to $BC$. Let $M,N$ be the midpoints of $AB,AC$. Let $w_b$ be the circle passing through $M$ and $B$ tangent to $(AXB)$ and define $w_c$ similarly. Show that $w_b, w_c$ intersect on $(AMN)$.}\n\t\n\t\\solu{Doing a $ \\sqrt{\\frac{bc}{2}} $ inversion in \\autoref{problem:usatst2019p1} one ends up with this parallel problem.}            \n\t\n\t\n\t\\prob{https://artofproblemsolving.com/community/c6h374251p2066133}{Sharygin 2010 P3}{E}{Points $A', B', C'$ lie on sides $BC, CA, AB$ of triangle $ABC.$ for a point $X$ one has $\\angle AXB =\\angle A'C'B' + \\angle ACB$ and $\\angle BXC = \\angle B'A'C' +\\angle BAC.$ Prove that the quadrilateral $XA'BC'$ is cyclic.}\n\t\n\t\t\\fig{.8}{sharygin_2010_3}{}\n\t\n\t\n\t\\prob{https://artofproblemsolving.com/community/c6h1671293p10632360}{IMO 2018 P6}{M}{A convex quadrilateral $ABCD$ satisfies $AB\\cdot CD = BC\\cdot DA$. Point $X$ lies inside $ABCD$ so that \\[\\angle{XAB} = \\angle{XCD}\\quad\\,\\,\\text{and}\\quad\\,\\,\\angle{XBC} = \\angle{XDA}.\\]Prove that $\\angle{BXA} + \\angle{DXC} = 180^\\circ$.}\n\t\n\t\t\n\t\t\\proof{Let $ P = AB\\cap CD,\\ Q = AD\\cap BC $\\\\\n\t\t\t\n\t\tFrom the first condition, we get that $ \\dfrac{AB}{BC} = \\dfrac{AD}{DC} $, implying that the angle bisectors of $ \\angle DAB, \\angle DCB $ meet on $ BD $.\\\\\n\t\t\n\t\tAnd from the second condition, we have $ X = \\odot QBD \\cap \\odot PAC $\\\\\n\t\t\n\t\t\t\\figdf{1}{imo2018p6}{IMO 2018 P6, Simple Angle-Chase proof.}\n\t\t\n\t\tLet us define the point $ R $ such that $ AR, CR $ are isogonal to $ AC $ wrt to $ \\angle DAB, \\angle DCB $ respectively. In $ \\triangle RAC $, we have, the bisectors of $ \\angle RAC, \\angle RCA $ meet on the line $ BRD $, meaning that $ RB $ bisects $ \\angle ARC $.\\\\\n\t\t\n\t\tLet $ \\odot ARM \\cap \\odot DRC = Y $. We have,\n\t\t\n\t\t\t\\begin{align*}\n\t\t\t\t\\measuredangle AYC &= \\measuredangle AYR + \\measuredangle RYC\\\\\n\t\t\t\t\t&= \\measuredangle ABR + \\measuredangle RDP\\\\\n\t\t\t\t\t&= \\measuredangle BPD\\\\\n\t\t\t\t\t\\implies \\square PAYC &\\text{ is cyclic.}\n\t\t\t\\end{align*}\t\n\t\t\n\t\tAnd,\n\t\t\n\t\t\t\\begin{align*}\n\t\t\t\t\\measuredangle BYD &= \\measuredangle BYR + \\measuredangle RYD\\\\\n\t\t\t\t\t&= \\measuredangle BAR + \\measuredangle RCD\\\\\n\t\t\t\t\t&= \\measuredangle CAD + \\measuredangle BCA\\\\\n\t\t\t\t\t&= \\measuredangle CQD\\\\\n\t\t\t\t\t\\implies \\square QBYD &\\text{ is cyclic.}\n\t\t\t\\end{align*}\n\t\t\t\n\t\tSo, $ Y \\equiv X $. So, \n\t\t\t\n\t\t\t\\[\\measuredangle BYA + \\measuredangle DYC = \\measuredangle BRA + \\measuredangle DRC = \\measuredangle BRA + \\measuredangle ARD = 180^\\circ \\]\n\t\t}\n\n\n\t\\prob{}{Sharygin 2010}{E}{In $\\triangle ABC$, let $ AL_a, AM_a $ be the external and internal bisectors of $ \\angle A $ with $ L_a, M_a $ lying on $ BC $. Let $ \\omega_a $ be the reflection of the circumcircle of $ \\triangle AL_aM_a $wrt the midpoint of $ BC $. Let $ \\omega_a $ be defined similarly. Prove that $ \\omega_a, \\omega_b $ are tangent to each other iff $ \\triangle ABC $ is a right-angled triangle.}", "meta": {"hexsha": "34f5d2190d49e5663595e496ac5bc75a6a308698", "size": 8862, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "geo/sec6_circle.tex", "max_stars_repo_name": "M-Ahsan-Al-Mahir/BCS_Question_Bank", "max_stars_repo_head_hexsha": "83ff9b542999386ea182863e4f25f0b488d3984f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 48, "max_stars_repo_stars_event_min_datetime": "2020-10-14T17:15:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T19:47:04.000Z", "max_issues_repo_path": "geo/sec6_circle.tex", "max_issues_repo_name": "AnglyPascal/BCS_Question_Bank", "max_issues_repo_head_hexsha": "83ff9b542999386ea182863e4f25f0b488d3984f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geo/sec6_circle.tex", "max_forks_repo_name": "AnglyPascal/BCS_Question_Bank", "max_forks_repo_head_hexsha": "83ff9b542999386ea182863e4f25f0b488d3984f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-10-15T08:59:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T15:19:26.000Z", "avg_line_length": 57.9215686275, "max_line_length": 643, "alphanum_fraction": 0.6411645227, "num_tokens": 3221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.3047433473409021}}
{"text": "\\chapter{Fundamentals of Quantum Information Theory}\n\\chaptermark{Quantum Information Theory}\n\nThis chapter extends the ideas of classical information theory to quantum information theory. We shall explore what quantum information is, how it differs in a very fundamental way from classical information and how quantum entanglement, an important feature of quantum information theory, can be quantified.\n\n\\section{Why a Classical and a Quantum Theory?}\nThe relation between the laws governing the physical world and those governing the processing and transfer of information is symmetrical. Information is always coded into and sent through physical systems. On the other hand, a physical system itself can be thought of as an information processor which takes the initial state of the system as input, does some computations on it which evolve the state of the system, and gives the final state of the system as its output. When we make a measurement on a physical system we are actually retrieving information stored in that system.\n\\par This symmetry suggests that the laws of information processing should completely depend on the laws governing the states of physical systems, which in turn means that as our understanding of the physical universe evolves the theoretical framework of processing and sending of information will also have to be revised. That is why a need for developing a quantum theory of information was felt. As quantum physics gained recognition among the physicists as a more complete picture of reality than classical physics, attempts were made to generalize the ideas of classical information theory to quantum physical systems.\n\\par We still use classical mechanics and classical information theory because they work within the limits of our experience. This is how we perceive the world and this is how we communicate with others. Even when in the future communication through quantum channels becomes the norm, we will probably still be encoding and transmitting classical information through them.\n\n\\section{Quantum Information and the Qubit}\n\\par An important property of quantum systems is that of superposition. A quantum mechanical system can be in a superposition of many different states and only adopt one of them when a measurement is made on it. Therefore when dealing with information encoded in quantum systems, the theory has to be adjusted to work within the quantum realm.\n\\par Let us start by considering what kind of quantum system we can use to represent the quantum analogue of a classical bit - i.e. a quantum bit or qubit. A good system of choice will be a spin-half particle which has two perfectly distinguishable outcomes spin-up and spin-down along a chosen basis, or a photon whose outcomes then are horizontal or vertical polarization. On the surface it does look just like a classical bit. But a quantum system such as the spin-half particle we considered differs from a classical one in a very fundamental way. Even though the particle after measurement will either be in spin-up or in spin-down state, the general state before measurement is a superposition of the two.\n\\begin{align*}\n\\Ket{\\psi} = \\alpha \\Ket{\\downarrow}_z + \\beta \\Ket{\\uparrow}_z\n\\end{align*}\nwhere $\\alpha$ and $\\beta$ are two complex numbers such that $|\\alpha|^2$ and $|\\beta|^2$ are the probabilities of finding the particle in spin-down and spin-up states respectively. By condition of normalization for a physical system, $|\\alpha|^2 + |\\beta|^2 = 1$.\n\n\n\\section{Quantifying Quantum Information}\n\\par Once again we should remind the reader that the qubit is a \\textit{unit} for measuring quantum information. We now discuss the \\textit{quantity}, i.e. \\textit{quantum information}, for which it is a unit. In section 1.2 we discussed how to define a measure for information encoded in a classical system. Here we will generalize that idea to define a measure that also works for quantum information.\n\\par In quantum mechanics, unlike classical mechanics, we encounter systems which may have non-orthogonal states: states which are not completely distinguishable from each other in an experiment. The Shannon entropy no longer works because of the possibility of non-orthogonal quantum bits. So we need an information measure which works for both orthogonal as well as non-orthogonal states while fulfilling the requirements that we outlined in 1.2 for an information measure. This role is fulfilled by the \\textbf{Von Neumann Entropy}.\n\\subsection{Von Neumann Entropy}\nIf $\\hat{\\rho}$ represents the density matrix for our physical system, then the information content of that system will be its Von Neumann entropy\n\\begin{align*}\nS(\\hat{\\rho}) = - tr\\{ \\hat{\\rho} \\log \\hat{\\rho} \\}\n\\end{align*}\nFor orthogonal states, this will reduce to the Shannon entropy.\n\\par In the above formula for Von Neumann entropy, the presence of a matrix log makes the calculation a bit tricky. There is another way we can make the calculations easier. That includes writing an equivalent form of the density matrix in an orthogonal basis, also known as diagonalization.\nWe know that the density matrix is a Hermitian matrix. If we write it in a basis of its orthogonal eigenvectors $\\ket{e_i}$, then its diagonal form is\n\\begin{align*}\n\\hat{\\rho} = \\sum q_i \\ket{e_i} \\bra{e_i}\n\\end{align*}\nwhere $q_i$ are the real eigenvalues of the density matrix.\n\\par Now it should be noted that this new density matrix represents a \\textit{different} preparation procedure for a quantum state which can be in any of the orthogonal states $\\ket{e_i}$ with probabilities $q_i$. But even though the density matrix is that of a different preparation procedure, its observable properties that are relevant in physical experiments remain unchanged. This is because the physically observable properties are basis independent and this diagonalization process is simply rewriting a density matrix in an alternative basis (that of its eigenvectors).\n\\par So it does not matter for the Von Neumann entropy which of these two bases we write our density matrix in. The result will remain the same. So we can simply apply the formula for Shannon entropy where $q_i$ are the probabilities for orthogonal eigenstates $\\ket{e_i}$.\n\\begin{align*}\nS(\\hat{\\rho}) &= - tr\\{ \\hat{\\rho} \\log \\hat{\\rho} \\} \\\\\n              &= - \\sum q_i \\log q_i\n\\end{align*}\n\n\\subsection{Quantum Data Compression}\n\\par In section 1.2 we saw that any long classical message can be compressed to the information content of the probability distribution of the symbols given by its Shannon entropy. Using similar reasoning, we can easily derive the conclusion that a message encoded using quantum states can be compressed to the information content of the states, given by their Von Neumann entropy.\n\\par Here we should note that in quantum information we can encounter states that are non-orthogonal (not completely distinguishable). When the states are non-orthogonal, their information content will be smaller because we cannot distinguish between them perfectly and so we gain less information. The maximum information content will be for orthogonal states which we can completely distinguish and hence get more information out of.\n\\par Hence it follows that a message consisting of non-orthogonal states can be compressed more than a message consisting of orthogonal states.\n\n\\section{Capacity of a Noisy Quantum Channel}\n\\par In section 1.3 we looked into the maximum capacity of a noisy classical information channel carrying classical bits. In this section, we will look at the maximum bound for sending classical bits over a noisy quantum channel.\n\\par We model the situation like this: Alice sends Bob a message consisting of alphabets that are each encoded in a respective pure state $\\psi_i$ occurring with probability $p_i$. As a simple example we can assume that the states are polarizations of photons sent along a fiber-optic cable. Along the way, due to interaction with the environment or by actions of an eavesdropper, the pure state $\\psi_i$ might turn into a mixed state $\\rho_i$ since the knowledge of the environment would be incomplete. Upon receiving the message Bob now has to discriminate between mixed states rather than the original pure states and hence his capacity to extract information is reduced.\n\\par Without the environmental noise, the information content would have been the Von Neumann entropy of the original mixture of alphabets $\\rho = \\sum_i p_i \\rho_i$. We seek to know how much the capacity of Bob to gain information from the message is reduced. Or rather, we want to know the limit on how much classical information can be sent reliably over the channel. That limit is provided by the \\textit{Holevo bound}.\n\\subsection{Holevo Bound}\n\\par The Holevo bound gives the maximum limit that is achievable for reliably transmitting classical information over a quantum channel. It is represented by $\\chi$ as follows.\n\\begin{align*}\n\\chi(\\rho) = S(\\rho) - \\sum_i p_i S(\\rho_i)\n\\end{align*}\nwhich is the difference between the von Neumann entropy of the whole and the average von Neumann entropy of the parts.\n\\par The Holevo bound is always a positive quantity. In the classical limit, it approaches the Shannon mutual information for the capacity of a noisy classical channel.\n\n\\section{Degree of Similarity between States}\n\\par There are a number of measures to quantify how similar or dissimilar two given states are. The most commonly encountered in our treatment of the subject will be the fidelity and relative entropy.\n\\subsection{Fidelity}\n\\par Fidelity is a measure of closeness between two states. If the states are represented by density matrices $\\rho$ and $\\sigma$, then their fidelity is\n\\begin{align*}\nF(\\rho,\\sigma) = tr \\left[ \\sqrt{ \\sqrt{\\rho} \\sigma \\sqrt{\\rho} } \\right]\n\\end{align*}\nwhere the square root is a matrix square root.\n\\par The value of fidelity ranges from 0 to 1. For completely dissimilar states, the fidelity is 0. For completely similar states (i.e; the same state), its value is 1.\n\\subsection{Relative Entropy}\n\\par The relative entropy between two states represented by density matrices $\\rho$ and $\\sigma$ is\n\\begin{align*}\nS(\\rho||\\sigma) &= tr ( \\rho \\log \\rho - \\rho \\log \\sigma )\n\\end{align*}\nThis quantity is also known as the \\textbf{Kullback–Leibler distance} of the two density matrices.\n\\\\ Some properties of the relative entropy are:\n\\begin{itemize}\n  \\item $S(\\sigma||\\sigma) = 0$. The distance between a state and itself is zero.\n  \\item Relative entropy is additive, just like the von Neumann entropy.\n  \\item Mixing of physical states decreases the distance between them. Less distance $\\rightarrow$ less distinguishable.\n  \\item The relative entropy is invariant under unitary transformations.\n  \\item A partial trace of the states decreases their relative entropy and hence their distinguishability.\n\\end{itemize}\n\n\\section{Detecting Quantum Entanglement}\n\\par When dealing with quantum information systems, we need ways to determine whether or not a particular state is entangled. For a start, let us look at a basic property of entangled states.\n\\par We have already seen in section 2.4 that an entangled state cannot be factorized in terms of individual states of its constituent subsystems. What this means is that if we take only part of an entangled system, we will always have a lack of knowledge about its state. Which means that it will be a mixed state. More formally, we say that the reduced density matrix of an entangled state is always a mixed state.\n\\begin{align*}\ntr \\{ ( tr_B \\{\\hat{\\rho}\\} )^2 \\} < 1\n\\end{align*}\nFor a maximally entangled state, the reduced density matrix will be maximally mixed and its trace will be 0.5.\n\\par However, this test has a serious limitation. It does not work for mixed states where we already have a lack of information about the parts.\n\\par While looking for entanglement in an experiment we need a way to differentiate with certainty between an entangled and a disentangled state. We need experiments that give different results for entangled and disentangled states. This brings us to the topic of entanglement witnesses.\n\\subsection{Entanglement Witnesses}\nAn entanglement witness $W$ is a Hermitian operator which distinguishes between entangled and disentangled states. The expectation value for $W$ is different for an entangled state than a disentangled state.\n\\par Let $\\tau$ be the set of all density matrices, $E$ be its subset consisting of entangled states and $D$ be its subset consisting of disentangled states.\n\\par The set of all disentangled states $D$ is convex. Convexity here means that given any two points in the set, the line joining the points is completely within the set. If $\\rho_1^{AB}$ and $\\sigma_1^{AB}$ are separable states then they can be written in the form\n\\begin{align*}\n\\rho_1^{AB} &= \\sum_i p_i \\rho_i^A \\otimes \\rho_i^B \\\\\n\\sigma_1^{AB} &= \\sum_i p_i \\sigma_i^A \\otimes \\sigma_i^B\n\\end{align*}\nA linear combination of $\\rho_1^{AB}$ and $\\sigma_1^{AB}$\n\\begin{align*}\np \\rho_1^{AB} + (1-p) \\sigma_1^{AB} = p \\sum_i p_i \\rho_i^A \\otimes \\rho_i^B + (1-p) \\sum_i q_i \\sigma_i^A \\otimes \\sigma_i^B\n\\end{align*}\nis also a disentangled state.\n\\par The convexity of the set of disentangled states is a useful property in detecting entanglement. A corollary of the Hahn-Banach theorem from functional analysis is that given a convex set and a point outside of it, there exists a plane that the point is on one side of it and the set is on the other side. To detect entanglement we just need to determine if a given state is inside the disentangled set $D$ or outside of it. The plane that will separate the two is the entanglement witness we look for.\n\\begin{figure}\n  \\begin{center}\n    \\includegraphics[scale=0.52]{figures/entanglementwitness.png}\n    \\caption{$D$ is the set of disentangled states and $E$ is the set of entangled states. If there exists a Hermitian operator $W$ which defines a plane between the two sets, then $W$ is called an entanglement witness.\\newline Image courtesy of Vlatko Vedral, \\textit{Introduction to Quantum Information Science} \\cite{vedralqitbook}}\n    \\label{fig: Entanglement Witnesses}\n  \\end{center}\n\\end{figure}\n\\par To define the witness $W$, first consider an arbitrary vector space $V$. A plane in $V$ is specified by the vectors $\\ket{\\psi}$ such that\n\\begin{align*}\n\\braket{w \\mid \\psi} = 0\n\\end{align*}\nwhere $w$ is a unit vector orthogonal to the plane.\n\\par Hermitian operators can also be thought of as vectors and an inner product can be defined for them as\n\\begin{align*}\n\\braket{O_1 \\mid O_2} = tr \\left( O_1^{\\dagger} O_2 \\right)\n\\end{align*}\nFor a Hermitian operator, that will become\n\\begin{align*}\n\\braket{O_1 \\mid O_2} = tr \\left( O_1 O_2 \\right)\n\\end{align*}\nUsing this inner product, we can define a plane in the space of Hermitian operators $\\tau$,\n\\begin{align*}\ntr ( w \\rho ) = 0\n\\end{align*}\nThe term on the right side can be a non-zero constant but we choose zero by convention.\n\\par Now suppose we have an entangled state $\\sigma$. Then by our reasoning so far there exists a plane defined by a Hermitian operator $W$ such that $\\sigma$ resides on one side and the convex set of all disentangled states resides on the other side. The points on the plane are defined by\n\\begin{align*}\ntr ( \\rho W ) = 0\n\\end{align*}\n\\par For each disentangled state $\\rho_D$ we can either have $tr (\\rho_D W) \\geq 0$ or $tr (\\rho_D W) \\leq 0$. We choose $W$ such that $tr (\\rho_D W) \\geq 0$. Then for all entangled states $\\sigma$ on the other side of the plane, $tr (\\sigma W) < 0$.\n\\par Thus our test for entanglement becomes:\n\\begin{align*}\n  tr (\\sigma W) < 0 &\\rightarrow \\sigma \\text{ is entangled} \\\\\n  tr (\\rho_D W) \\geq 0 &\\rightarrow \\rho_D \\text{ is disentangled}\n\\end{align*}\n\\par Whenever an entangled state exists an entanglement witness will also exist. Although in practice they can be hard to find. In the case of two qubits, entanglement witnesses are relatively easier to find. As the dimensionality of the system becomes larger, the search becomes harder and harder. \\cite{vedralqitbook}\n\n\\subsection{The Peres-Horodecki criterion}\nThe Peres-Horodecki criterion is a reliable test of whether or not a bipartite state is entangled. The test proceeds as follows:\n\\begin{enumerate}\n  \\item Take a partial transpose of the density matrix.\n  \\item If the resultant matrix has a negative eigenvalue, then the state is entangled. Otherwise, the state is separable. (Reminder: A valid density matrix always has eigenvalues $\\geq 0$)\n\\end{enumerate}\n\\par To calculate the partial transpose of the density matrix, we start by writing the basis states of qubit $A$ as $\\ket{i}$ and $\\ket{j}$ and the basis states of $B$ as $\\ket{k}$ and $\\ket{l}$. The density operator of the full system then is\n\\begin{align*}\n\\rho = \\sum_{ijkl} p_{ijkl} \\ket{i} \\bra{j} \\otimes \\ket{k} \\bra{l}\n\\end{align*}\nThe partial transpose with respect to $B$ will be\n\\begin{align*}\n\\left( \\ket{k} \\bra{l} \\right)^T = \\ket{l} \\bra{k}\n\\end{align*}\nBy applying this transformation to the density operator, we get the partial transpose of that density operator.\n\\begin{align*}\n\\rho^{T_B} = (I \\otimes T) \\rho = \\sum_{ijkl} p_{ijkl} \\ket{i} \\bra{j} \\otimes \\ket{l} \\bra{k}\n\\end{align*}\n\\par After calculating the eigenvalues of this resultant matrix, if we find a negative eigenvalue then the state is entangled. If all the eigenvalues are zero or positive then the state is separable. \\cite{vedralteleportation}\n\n\\section{Quantifying Quantum Entanglement}\n\\par We have seen that there are states that are entangled and states that are disentangled. Now let us go into a little more detail on the subject and ask the question of how to quantify the degree of entanglement contained in a given system. That is, measuring \\textquotedblleft how much\\textquotedblright\\  entanglement is contained within a system. It turns out that we can also concentrate entanglement from a number of partially entangled states to form a smaller number of maximally entangled states.\n\\par We first specify the \\textbf{desirable properties} that any \\textquoteleft decent\\textquoteright\\ measure of entanglement should have. \\cite{vedralteleportation}\n\\begin{enumerate}\n  \\item For any separable state $\\rho$ the measure of entanglement should be zero.\n        \\begin{align*} E(\\rho) = 0 \\end{align*}\n  \\item A local unitary transformation, which is a unitary transformation of the form $U_A \\otimes U_B$ and represents a change of basis, should not change the amount of entanglement in a state.\n        \\begin{align*} E(\\rho) = E(U_A \\otimes U_B \\rho U_A^{\\dagger} \\otimes U_B^{\\dagger}) \\end{align*}\n  \\item Local operations \\& classical communication (LOCC) - the act of classically communicating the results of local operations on the subsystems - and sub-selection cannot increase the expected entanglement \\cite{vedralteleportation}. If we start with an ensemble in state $\\rho$ and end up with sub-ensembles in states $\\rho_i$ occurring with probabilities $p_i$, then\n        \\begin{align*} E(\\rho) \\geq \\sum_i p_i E(\\rho_i) \\end{align*}\n  \\item Given two pairs of entangled particles in total state $\\rho = \\rho_1 \\otimes \\rho_2$, their entanglement is additive.\n        \\begin{align*} E(\\rho) = E(\\rho_1) + E(\\rho_2) \\end{align*}\n\\end{enumerate}\n\\par Now we shall look at some actual measures of entanglement which fulfill these requirements to be \\textquoteleft decent\\textquoteright\\  entanglement measures. \\cite{plenioentanglementmeasures}\n\n\\subsection{Entropy of Entanglement}\n\\par The entropy of entanglement is, in simple terms, the von Neumann entropy of the reduced density matrix of the given pure state.\n\\begin{align*}\nS(\\rho_A) = - tr \\{ \\rho_A \\log \\rho_A \\}\n\\end{align*}\nwhere $\\rho_A$ is the reduced density matrix for subsystem $A$, obtained by tracing out subsystem $B$. That is, $\\rho_A = tr_B \\{\\rho_{AB}\\}$.\n\\par Entropy of entanglement suffers from the limitation that it only works as a good measure of entanglement for pure states. It does not work when mixed states are involved.\n\n\\subsection{Linear Entropy of Entanglement}\n\\par Linear entropy of entanglement is a linear approximation to the entropy of entanglement, in the same way that linear entropy is the linear approximation to von Neumann entropy. It is easier to calculate than the entropy of entanglement. The basic idea is the same: tracing out subsystem $B$ to obtain the reduced density matrix for subsystem $A$ and then taking its linear entropy.\n\\begin{align*}\nS_L(\\rho_A) = 1 - tr(\\rho_A^2)\n\\end{align*}\n\\par This measure also suffers from the same problem as the entropy of entanglement. It does not work for mixed states. It can only work as a decent entanglement measure for pure states.\n\n\\subsection{Renyi Entanglement Entropy}\nRenyi entanglement entropy of a density matrix $\\rho$ is also defined in terms of its reduce density matrix $\\rho_A$ or $\\rho_B$.\n\\begin{align*}\nS_\\alpha (\\rho_A) &= \\frac{1}{1-\\alpha} \\log (tr\\{\\rho_A^\\alpha\\}) , \\quad \\alpha \\neq 1 \\: \\text{and} \\: \\alpha > 0\n\\end{align*}\nIn terms of the eigenvalues of the reduced density matrix $q_i$,\n\\begin{align*}\nS_\\alpha (\\rho_A) &= \\frac{1}{1-\\alpha} \\log \\left( \\sum_i q_i^\\alpha \\right)\n\\end{align*}\nwhere $\\alpha$ is the Renyi index.\n\\par In the limit $\\alpha \\rightarrow 1$ it approaches the von Neumann entropy.\n\n\\subsection{Negativity}\n\\par Peres-Horodecki criterion tests for entanglement by presence of negative eigenvalues under partial transpose. Negativity is a measure of how negative the resulting matrix is. Mathematically, it is defined as\n\\begin{align*}\nN(\\rho) = \\frac{\\lVert \\rho^{T_A} \\rVert_1 - 1}{2}\n\\end{align*}\nwhere $\\rho^{T_A}$ is the partial transpose of the density matrix with respect to $A$ and $\\lVert . \\rVert_1$ denotes the trace norm.\n\\par Negativity has the property of non-increase under LOCC. But it does not have the additivity property. This brings us to logarithmic negativity.\n\n\\subsection{Logarithmic Negativity}\n\\par The logarithmic negativity of a bipartite state is\n\\begin{align*}\nE_N(\\rho) = log_2 \\lVert \\rho^{T_A} \\rVert_1\n\\end{align*}\n\\par Logarithmic negativity is additive and provides an upper bound on how much entanglement can be distilled from a system.\n\n\\subsection{Concurrence}\n\\par Concurrence of a bipartite state $\\rho$ is defined as\n\\begin{align*}\nC(\\rho) = max(0, \\lambda_1 - \\lambda_2 - \\lambda_3 - \\lambda_4)\n\\end{align*}\ni.e. the greater one of these two quantities. The numbers $\\lambda_1 > \\lambda_2 > \\lambda_3 > \\lambda_4$ are eigenvalues of the Hermitian matrix\n\\begin{align*}\nR = \\sqrt{ \\sqrt{\\rho} \\tilde{\\rho} \\sqrt{\\rho} }\n\\end{align*}\nin which\n\\begin{align*}\n\\tilde{\\rho} = ( \\sigma_y \\otimes \\sigma_y ) \\rho^* ( \\sigma_y \\otimes \\sigma_y )\n\\end{align*}\nwhere $\\rho^*$ is the complex conjugate of $\\rho$ and $\\sigma_y$ is the Pauli spin matrix known by the same label.\n\\par The value of concurrence ranges from 0 to 1. It is 0 for separable states and 1 for the maximally entangled state.\n\\par For multipartite states, concurrence takes on a more complicated form than the one shown here.\n\n\\subsection{Relative Entropy of Entanglement}\n\\par The basic idea for relative entropy of entanglement is based on distinguishability and geometrical distance. In this approach, when given a state $\\sigma$, we compare its distance to each state from the whole set of disentangled states $D$ and pick the state $\\rho$ which has the minimum distance from $\\sigma$. The relative entropy of entanglement is thus this minimum distance.\n\n\\begin{align*}\nE_{RE}(\\sigma) = \\underset{\\rho \\in D}{\\min}  D(\\sigma||\\rho)\n\\end{align*}\n\n\\begin{figure}[h]\n  \\begin{center}\n    \\includegraphics[scale=0.25]{figures/entanglement-distance.png}\n    \\caption{Relative entropy of entanglement: the distance from the nearest disentangled state\\newline $\\sigma$ is the state for which the quantity is to be measured. Over the whole state of disentangled states $\\{\\rho\\}$, the state $\\rho^*$ has the minimum distance from $\\sigma$. The distance to $\\rho^*$ is the relative entropy of entanglement of $\\sigma$.\\newline Image courtesy of Vlatko Vedral, \\textit{Introduction to Quantum Information Science} \\cite{vedralqitbook}}\n    \\label{fig: Relative Entropy of Entanglement}\n  \\end{center}\n\\end{figure}\n\n\\par Here the function $D$ is a measure of separation between the two density matrices. There are a number of separation measures available to define the \\textquoteleft distance\\textquoteright \\  between two density matrices. Though it should be noted that not all distance measures will generate a \\textquoteleft decent\\textquoteright \\  entanglement measure by our criteria. Those requirements have to be kept in mind when looking for an entanglement measure.\n\n\\par One distance measure which generates an entanglement measure satisfying the \\textquoteleft decency\\textquoteright \\  criteria is the Kullback-Leibler distance - alternatively known as the relative entropy - that we talked about in section 3.5.2.\n\\begin{align*}\nS(\\sigma||\\rho) &= tr \\{ \\sigma \\log \\sigma - \\sigma \\log \\rho \\}\n\\end{align*}\n\\par We can plug this into the formula for relative entropy of entanglement to generate an entanglement measure. We can similarly use many other distance measures in place of the Kullback-Leibler distance.\n\\par Relative entropy of entanglement is an important quantity because we can plug in various distance measures in place of the distance function $D$ and so we can derive many other entanglement measures from it - provided that they satisfy the criteria for decent entanglement measures. \\cite{vedralteleportation}\n\n", "meta": {"hexsha": "137207522a9cd5f14126454579817dbc5122a65f", "size": 25609, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/chapter-03.tex", "max_stars_repo_name": "saad440/undergrad-project", "max_stars_repo_head_hexsha": "6e4ddf112219c1e884ca2b2657852d54524c282c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-06-13T00:02:19.000Z", "max_stars_repo_stars_event_max_datetime": "2016-06-13T00:02:19.000Z", "max_issues_repo_path": "chapters/chapter-03.tex", "max_issues_repo_name": "saad440/undergrad-project", "max_issues_repo_head_hexsha": "6e4ddf112219c1e884ca2b2657852d54524c282c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/chapter-03.tex", "max_forks_repo_name": "saad440/undergrad-project", "max_forks_repo_head_hexsha": "6e4ddf112219c1e884ca2b2657852d54524c282c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 98.1187739464, "max_line_length": 711, "alphanum_fraction": 0.7731266352, "num_tokens": 6359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.304743347340902}}
{"text": "%Chapter 3\r\nPredicting disorder from XANES spectra requires a sophisticated model or algorithm capable of extracting non-linear features from the data. Increasing the disorder in the structure does not simply shift or scale the spectrum by a scalar; instead, disorder alters the spectrum in a complex and unknown way, for which we rely on machine learning  (ML) to discern. The general goal of ML is to recognize patterns in data, iteratively learning to solve complex, non-linear problems and make powerful predictions on new, unseen data \\cite{ML-and-the-physical-sci}. Due to the integral role ML plays in this thesis, the following chapter serves to establish how neural networks fundamentally operate and define all the terms necessary for understanding the neural network implementations discussed in chapter \\ref{ch:results}.\r\n\r\nWe begin by clarifying and distinguishing the following commonly misused terms: machine learning (ML), deep learning, and artificial intelligence (AI). ML is the most general term out of the three, referring to the computational technique of fitting a model on a dataset via an iterative training process. The models created in ML can either be regressors or classifiers: the former predicts a continuous range of values, whereas the latter is a discrete predictor. Artificial neural networks (ANNs), or neural networks (NNs) for short, are one example of a machine learning model that tends to be complex and computationally intensive to train. As a result, ANNs are often highly non-linear models capable of solving complex tasks such as object detection \\cite{szegedy2013deep} or speech recognition \\cite{ms-speech-recognition-paper} \\cite{speech-recognition}. Neural networks were originlly inspired by biological nervous systems, and fittingly, their graphical representations include terms such as ``nodes'' and ``connections.'' The field of ML involving ANNs with many layers is referred to as deep learning \\cite{schmidhuber2015deep}. AI is a subfield of deep learning where a neural network is trained to generate human-like responses. Common examples of AI are generative chatbots \\cite{chatbots} and a virtual assistants \\cite{virtual-assistants} \\cite{virtual-assistants2}. \r\n\r\nUsing the above terminology, we can reframe the goal of this thesis: to predict disorder from XANES, we utilize deep learning to train a regression-based artificial neural network. The following sections walk through the mathematical process of training a simple neural network. In practice, sophisticated APIs such as Google's TensorFlow \\cite{tensorflow2015-whitepaper} or Facebook's PyTorch \\cite{pytorch-paper} handle the mathematical backend and optimization; however, one must first build a fundamental understanding of the methods these frameworks are executing before attempting to implement them.\r\n\r\n\\section{Feedforward and Backpropagation in ANNs}\r\n\r\n% Understanding how a neural network makes a prediction requires a solid grasp of linear algebra. \r\nThe process where an ANN passes information from the input to the subsequent layers to make a prediction is called the ``feedforward process.'' The process of updating the parameters of a neural network is called backpropagation. Whereas feedforward is essentially a chain of linear algebra operations, backpropagation relies principally on vector calculus. Neither action is particularly mathematically complicated; however, there are many parts, and it is easy to get lost in the sea of similar-looking partial derivatives. In this next section (\\ref{sec:feedfoward}), we explicitly walk through the mathematics of the feedforward process for a fully connected (affine) neural network.\r\n\r\n\\subsection{Feedforward} \\label{sec:feedfoward}\r\n\r\nConsider the neural network in Figure \\ref{fig:simpleNN}: it contains an input layer with three nodes, a single hidden layer with five nodes, and an output layer with two nodes. The input layer (zeroth layer) has a cardinality of $ \\mu=3 $ and is represented in Einstein notation\\footnote{Recall that in Einstein notation repeated indices are implicitly summed over. For example, ${u^i = A^i_j x_j = \\sum_{j=1}^5 A_{ij} x_j}$ } as the covector (row vector) $ x_\\mu $. Each edge in the graph represents a weight that will be multiplied by the connecting node on its left in the feedforward process. First, each node in the input layer is multiplied by the weight of the connecting edge and added together. Applying this operation for all input nodes and weights can thus be represented as the inner (dot) product of the input layer row vector and a weights matrix. The hidden layer (first layer) has a cardinality of $ \\nu=5 $. Thus, the resulting inner product is $ x_\\mu W_\\nu^{\\mu(1)} $, where $ W_\\nu^{\\mu(1)} $ represents the matrix of weights connecting the zeroth and first layer. While this result has the correct dimensionality for the hidden layer, there are still two operations required to produce the actual values for the nodes $ h_\\nu^{(1)} $. First, a small trainable parameter, $ b_\\nu $  is added to every element in the resulting vector from the previous calculation. The values in this row vector are called biases and introduced to prevent overfitting---i.e. the phenomenon where a model predicts the training data well but does not generalize to reliably predict unseen data. Biases are a regularization parameter. Regularization techniques are discussed below, and an example is provided in Figure \\ref{fig:overfitting}. The final operation applied to produce the first hidden layer's values is known as an activation function. These functions are applied element-wise to the layer, and without them, neural networks would be unable to learn non-linear features. There are several types of activation functions, the three most common being sigmoid, $\\tanh$, and ReLU.\r\n\r\n\r\n\\subsubsection{Sigmoid and Tanh}\r\nThe sigmoid and tanh activation functions are defined as the following:\r\n\\begin{equation}\r\n    \\label{sigmoid}\r\n    \\sigma (x) = \\frac{1}{1 + e^{-x}}\r\n\\end{equation}\r\n\r\n\\begin{equation}\r\n    \\label{eqn:tanh}\r\n    \\tanh(x) = \\frac{e^x - e^{-x}}{e^x + e^{-x}} \r\n\\end{equation}\r\n\r\n\\noindent Note, sometimes the term ``sigmoid'' is used to refer to the shape an s-shaped curve, so both equations (\\ref{sigmoid}) and (\\ref{eqn:tanh}) are considered sigmoids. In machine learning, however, the sigmoid function always refers to equation (\\ref{sigmoid}). Note that the sigmoid function maps the input between zero and one. Hence, the it is often used in the final layer of ANNs to output a probability. Note that sigmoid asymptoically approach their minimum and maximum values (for sigmoid, 0 to 1; for tanh -1 to 1) around $ {x=-4} $ and $ {x=4} $ respectively, meaning that the sigmoid activation function is only useful within that limited range of input values. One issue with both the sigmoid and tanh activation functions is the potential for creating a vanishing gradient, the phenomenon where a small gradient from deeper network layers causes the gradients of earlier layers to also be near-zero due to the chain rule in backpropogation\\footnote{An in-depth explanation of chaining gradients during backpropgation will be discussed in section \\ref{sec:backprop}}. The gradient of either of these functions approaches zero for values above four. This asymptotic approach hurts the ability of the NN to meaningfully update its trainable parameters  \\cite{nn-regularization}. The importance of calculating the gradients of these activation functions will be discussed in section \\ref{sec:backprop} within the context of backpropagation. \r\n\r\n\\begin{figure}[h!]\r\n    \\centering\r\n    \\includegraphics[width=\\linewidth]{Chapters/Figures/sigmoids2.pdf}\r\n    \\caption[Common Activation Functions]{Plotted above are three common activation functions: sigmoid, $\\tanh$, and ReLU. Sigmoid and tanh are particularly useful for scaling the output of a neural network layer to be within a given range. ReLU and its variations are useful for deep ANNs, where vanishing gradients are problematic.}\r\n    \\label{fig:ActivationFunctions}\r\n\\end{figure}\r\n\r\n\\subsubsection{ReLU}\r\nThe \\textbf{Re}ctified \\textbf{L}inear \\textbf{U}nit activation function (ReLU) has become an important staple of machine learning. Conventially, it is written as $ f(x) $ and defined as:\r\n\\begin{equation}\r\nf(x)=\r\n\\begin{cases}\r\n    0 & \\text{if } x <= 0 \\\\\r\n    x & \\text{if } x > 0\r\n\\end{cases}\r\n\\end{equation}\r\n\r\n\\noindent ReLU is important because it provides a much greater range in values as outputs. Whereas sigmoid and $\\tanh$ saturate around ${x=4}$, ReLU never saturates for linear values. Additionally, ReLU is simple to calculate and tends to help neural networks converge quickly. Further, because ReLU returns 0 for any negative value fed forward into the node, many ReLU activation functions in a given model help lead to sparser layers, reducing the overall complexity of the model and helping to prevent overfitting. Arguably its greatest benefit is the reduced likelihood of creating a vanishing gradient \\cite{orig-relu}. \r\n\r\n\r\n\\begin{figure}[h]\r\n    \\centering\r\n    \\includegraphics[width=\\linewidth]{Chapters/Figures/overfittingOrig2.pdf}\r\n    \\caption[Overfitting]{The green curve represents a model overfitting a binary classification problem. Although it makes near-perfect predictions for the training data in this figure, the model will not generalize as well as the simpler black curve when it tries to predict new, unseen data. Introducing biases and dropout layers in neural networks are strategies to prevent overfitting to reduce the model variance and fit the data like the black curve.}\r\n    \\label{fig:overfitting}\r\n\\end{figure}\r\n\r\n\r\nWith the inner product of the input nodes weight matrix calculated, the baises added, and then the activation function applied to each node, we arrive at the final final vector for the first hidden layer: $ h_\\nu^{(1)} $. Mathematically, $ h_\\nu^{(1)} = \\sigma\\left( x_\\mu W_\\nu ^\\mu + b_\\nu \\right) $. To calculate the next layer, the process is now repeated---only $ h_\\nu^{(1)} $ is used instead of the input layer, and the output\r\n$ \\hat{y} = \\sigma \\left( h_\\nu^{(1)} W_\\kappa ^\\nu + b_\\kappa \\right)$ is the final output of the neural network. The equations for each step as well as the dimensionality of each layer can be found in Figure \\ref{fig:simpleNN}.\r\n\r\n\\begin{figure}[h!]\r\n    \\centering\r\n    \\includegraphics[width=\\linewidth]{Chapters/Figures/einstein_NN_2.pdf}\r\n    \\caption[Neural Network Example]{This diagram of a fully connected (affine) neural network has a single hidden layer and two output nodes. The tensors for each hidden layer are written in Einstein notation. The implicitly summed over greek letters and dimensionality are written below the tensors for clarification.}\r\n    \\label{fig:simpleNN}\r\n\\end{figure}\r\n\r\n\\subsection{Loss Metrics and Regularization}\r\nIn order to update the network parameters, it is necessary to evaluate the quality of every prediction the neural network makes. The measure of error for prediction is referred to as the \\textit{loss}, whereas the summed total of all the losses is called the \\textit{cost}. For regression problems, the two most common cost functions are the mean squared error and the mean absolute error \\cite{regularization-2017survey}. Without regularization, they are defined as:\r\n\r\n\\begin{align}\r\n    \\label{eqn:lossFunctions-no-reg}\r\n    \\text{MSE} &= \\frac{1}{n} \\sum_i \\left( \\hat{y_i} - y_i \\right)^2\\\\\r\n    \\text{MAE} &= \\frac{1}{n} \\sum_i \\abs*{\\hat{y_i} - y_i}\r\n\\end{align}\r\n\r\n\\noindent where $ n $ is the number of training samples. Either cost metric can be regulated. The two most common regularizations are L1 (LASSO) and L2 (Ridge). Applied to the MSE, equation (\\ref{eqn:lossFunctions-no-reg}) with regularization becomes: \r\n\r\n\\begin{align}\r\n    \\label{eqn:lossFunctions}\r\n    \\text{L1 MSE: } J &= \\frac{1}{n} \\sum_i (\\hat{y_i} - y_i)^2 + \\lambda \\sum_j \\abs*{W_j}\\\\\r\n    \\text{L2 MSE: } J &= \\frac{1}{n} \\sum_i \\left( \\hat{y_i} - y_i \\right)^2 + \\lambda \\sum_j (W_j)^2\r\n\\end{align}\r\n\r\n\\noindent where $ W_j $ is the $ j^{th} $ weight for training sample \\textit{i}, and $\\lambda$ is the regularization hyper-parameter. \r\n\r\nOne simple equation\\footnote{This is a simple version of stochastic gradient descent, which will be discussed in depth in section \\ref{sec:optimizers} } for updating the weights for loss L is as follows:\r\n\\begin{equation}\r\n    % W := (1-\\alpha \\lambda)W - \\frac{\\partial L}{\\partial W}\r\n    W_j := W_j - \\alpha \\frac{\\partial L}{\\partial W_j}\r\n\\end{equation}\r\n\r\n\\noindent where $\\alpha$ is the learning rate. L2 regularization is often referred to as weight decay. Every iteration, the weights are pushed closer to zero due to the multiplication of the weights by a value $<1$. L1 is known as LASSO (least absolute shrinkage and selection operator) because it shrinks the less important features' coefficients to zero. This is because for small values, $\\abs*{W_i}$ is a much stiffer penalty than $(W_i)^2$. Thus, L1 is a good choice when there are dozens of features \\cite{nn-regularization}. \r\n\r\n% \\noindent Explicitly, for one component of the hidden layer:\r\n\r\n% \\begin{align}\r\n%     h_j &= \\sigma(w_{1j}x_1 + w_{2j}x_2 + w_{3j}x_3 + w_{4j}x_4 + w_{5j}x_5 + b_j) \\\\\r\n%         &= \\sigma\\Big(\\sum_{i=1}^{i=5}w_{ij}x_{i} + b_j\\Big)\r\n% \\end{align}\r\n\r\nIncluding biases in the loss function is not the only way to regularize a model. Dropout layers are an entirely different method of regularization used exclusively for neural networks \\cite{dropout-srivastava2014}. The idea is to introduce a hidden layer with a probability ``dropping out,'' i.e. ignored. Large weights in a neural network are indicative of a high-variance network, likely to be overfitting the data. By introducing layers with a probability of dropping out, the inward connections to the next layer change stochastically from batch to batch. The result of this behavior has the effect of adding noise to the network, similar to the inclusion of biases \\cite{conv-dropout-layers} \\cite{conv-dropout-layers2}.\r\n\r\n\\subsection{Backpropagation} \\label{sec:backprop}\r\nBackpropagation is the process of updating all the trainable parameters of the machine learning model, including weights, biases, and any other trainable parameters. The partial derivative requires repeated use of the chain rule. The output of the neural network in Figure \\ref{fig:simpleNN} can be written as a functional:\r\n\r\n% \\begin{equation}\r\n%     \\hat{y} = \\sigma\\left( g \\left( f() \\right) \\right)\r\n% \\end{equation}\r\n% \\noindent This would be a network with inputs $(x, y)$, two hidden layers ($ f $  and $ g $ ), and output with activation function sigma. Let's say the loss is the RMS loss. Thus,\r\n\r\n\\begin{equation}\r\n    \\label{eqn:functional}\r\n    \\hat{y} = \\sigma \\bigl( h_\\nu ^{(1)} \\left( x_\\nu \\right) \\bigr)\r\n\\end{equation}\r\n\r\n\\noindent Here (\\ref{eqn:functional}), the output layer $ \\hat{y} $ is a function of the hidden layer $ h_\\nu ^{(1)} $, which in turn is a function of the input layer $ x_\\mu $. Consider the MSE cost without regularization: \r\n\r\n\r\n\\begin{align}\r\n    \\label{eqn:mse}\r\n    J = \\text{MSE} &= \\frac{1}{n} \\sum_i \\left( \\hat{y_i} - y_i \\right)^2\r\n\\end{align}\r\n\r\n\\noindent Note that $ J $ is really $ J(\\hat{y}) $, meaning that it is a function of the output functional (\\ref{eqn:functional}). For well-behaved functions, such as (\\ref{eqn:mse}), the derivative of a summation is equal to the summation of the derivatives of each term. To see how much to shift the weights, calculate the gradients for each layer. The first partial derivative is trivial:\r\n\r\n\\begin{equation}\r\n    \\frac{\\partial J}{\\partial J} = 1\r\n\\end{equation}\r\n\r\n% \\noindent For the next layer going backwards (the output layer):\r\n\r\n% \\begin{equation}\r\n% \\frac{\\partial \\hat{y}}{\\partial J} = \\frac{\\partial J}{\\partial J}\\frac{\\partial \\hat{y}}{\\partial J}\r\n% \\end{equation}\r\n\r\n\r\n% \\noindent For the next nested-function is the sigmoid, $ \\sigma $. Taking its derivative:\r\n\r\n% \\begin{equation}\r\n% \\frac{\\partial J}{\\partial \\sigma} = \\frac{\\partial J}{\\partial \\hat{y}} \\frac{\\partial \\hat{y}}{\\partial \\sigma}\r\n% \\end{equation}\r\n\r\n\r\n% \\noindent The next layer is the hidden layer before the activation function. For simplicity it will be referred to as $ g $ where $ g = x_\\mu W_\\nu ^\\mu + b_\\nu $.  \r\n\r\n% \\begin{equation}\r\n%     \\frac{\\partial J}{\\partial g} = \\frac{\\partial J}{\\partial \\hat{y}} \\frac{\\partial \\hat{y}}{\\partial \\sigma} \\frac{\\partial \\sigma}{\\partial g}\r\n% \\end{equation}\r\n\r\n\r\n% \\noindent The next layer is the input layer, $ X_\\mu $ has no trainable parameters, so the process for this network architecture is complete. If there were more hidden layers, the chaining rule would continue by multiplying the gradient calculated in the previous step by the gradient of the next layer with respect to the previous layer (towards the input layer). \r\n\r\n% \\begin{equation}\r\n%     \\frac{\\partial L}{\\partial f} = \\frac{\\partial L}{\\partial \\hat{y}} \\frac{\\partial \\hat{y}}{\\partial \\sigma} \\frac{\\partial \\sigma}{\\partial g} \\frac{\\partial g}{\\partial f}\r\n% \\end{equation}\r\n\r\n% \\subsection{Concrete Example}\r\n\r\n% Finally, we will repeat the backpropogation process of updating the weights for the previous example as explicitly as possible. Consider again the functional $ \\hat{y} $ in equation (\\ref{eqn:functional}) and the L2 loss in equation (\\ref{eqn:lossFunctions}), rewritten here as $ L $ . To determine how do shift the weights in the function, want to know $\\frac{\\partial J}{\\partial W}$, where $ W  $ is short for $ W_\\kappa ^{\\nu (2)} $, the weight matrix connected to the second layer (the output layer). \r\n\r\n% \\begin{align}\r\n% L = \\frac{1}{m}\\sum(\\hat{y} - y)^2 \\\\\r\n% \\end{align}\r\n\r\n% \\noindent As before, the first partial derivative is trivial\r\n\r\n% \\begin{equation}\r\n%     \\frac{\\partial J}{\\partial J} = 1\r\n% \\end{equation}\r\n\r\n\\noindent and the next partial derivative is also straightforward\\footnote{The astute may notice that if we instead chose MAE, we encounter a problem taking the derivative when $ {\\hat{y}=y} $. Usually zero is returned instead or the MAE is approximated with a differentiable function. Otherwise using MAE is straightforward: \r\n$\r\n\\dfrac{\\partial J_\\text{MAE}}{\\partial \\hat{y}} = \r\n\\begin{cases}\r\n  +1,\\quad \\hat{y} > y\\\\\r\n  -1,\\quad \\hat{y} < y\r\n\\end{cases}\r\n$\r\n}:\r\n\r\n\\begin{equation}\r\n\\frac{\\partial J}{\\partial \\hat{y}} = \\frac{2}{n}\\sum_i (\\hat{y}_i - y_i )\r\n\\end{equation}\r\n\r\n\\noindent Applying the chain rule yields:\r\n\r\n\\begin{equation}\r\n\\label{eqn:dldy}\r\n\\frac{\\partial J}{\\partial \\hat{y}} = \\frac{\\partial J}{\\partial J}\\frac{\\partial J}{\\partial \\hat{y}} \\\\\r\n= 1 \\cdot \\frac{2}{n} \\sum_i (\\hat{y}_i - y_i )\r\n\\end{equation}\r\n\r\n\\noindent The next required term in the chain is the derivative of the loss with respect to the sigmoid:\r\n\r\n\\begin{equation}\r\n\\frac{\\partial J}{\\partial \\sigma} = \\frac{\\partial J}{\\partial \\hat{y}} \\frac{\\partial \\hat{y}}{\\partial \\sigma}\r\n\\end{equation}\r\n\r\n\\noindent We already found the first term (\\ref{eqn:dldy}), and the second term is trivial.\r\n\r\n\\begin{equation}\r\n    \\frac{\\partial \\hat{y}}{\\partial \\sigma} = 1 \\\\\r\n    \\implies \\frac{\\partial J}{\\partial \\sigma} =  \\frac    {\\partial J}{\\partial \\hat{y}} \\frac{\\partial \\hat{y}}  {\\partial \\sigma} \\\\\r\n    = \\frac{2}{n} \\sum_i (\\hat{y_i} - y_i ) \\cdot 1\r\n\\end{equation}\r\n\r\n\\noindent At this point, we have the derivative $ (\\partial J / \\partial \\sigma) $ for the $ \\sigma $ in the final layer $ \\hat{y} = \\sigma \\left( h_\\nu W_\\kappa ^\\nu + b_\\kappa \\right) $. The next derivative in the chain will be $( \\partial J / \\partial g )$ where $ g = h_\\nu W_\\kappa ^\\nu + b_\\kappa $. Continuing the chain,\r\n\r\n\\begin{equation}\r\n\\frac{\\partial J}{\\partial g} = \\frac{\\partial J}{\\partial \\hat{y}} \\frac{\\partial \\hat{y}}{\\partial \\sigma} \\frac{\\partial \\sigma}{\\partial g}\r\n\\end{equation}\r\n\r\n\\noindent where\r\n\r\n\\begin{align}\r\n\\sigma(g) &= \\dfrac{1}{1 + e^{-g}} \\\\\r\n\\implies \\frac{\\partial \\sigma}{\\partial g} &= \\sigma(g)(1 - \\sigma(g))\r\n\\end{align}\r\n\r\n\\noindent Combining these previously calculated terms yields:\r\n\r\n\\begin{equation}\r\n\\frac{\\partial J}{\\partial g} = \\frac{2}{n} \\left( \\sum_i (\\hat{y}_i - y_i ) \\right) \\cdot 1 \\cdot  \\sigma(z)(1 - \\sigma(z))\r\n\\end{equation}\r\n\r\nNow comes the good part. Recall that the trainable parameters in the network are the weights $ W $ and biases $ b $. The next step is to calculate the gradients with respect to each of these parameters. This, in turn, will be used to update the parameter.\r\n\r\n\\begin{equation}\r\n\\frac{\\partial J}{\\partial W} = \\frac{\\partial J}{\\partial g}\\frac{\\partial g}{\\partial W} = \\frac{\\partial J}{\\partial \\hat{y}} \\frac{\\partial \\hat{y}}{\\partial \\sigma} \\frac{\\partial \\sigma}{\\partial g} \\frac{\\partial g}{\\partial W}\r\n\\end{equation}\r\n\r\n\\noindent The last partial derivative in the chain is\r\n\r\n\\begin{equation}\r\n\\frac{\\partial g}{\\partial W} = W\r\n\\end{equation}\r\n\r\n\r\n\\noindent So,\r\n\r\n\\begin{equation}\r\n\\frac{\\partial J}{\\partial W} = \\frac{2}{n} \\left( \\sum_i (\\hat{y}_i - y_i ) \\right) \\cdot 1 \\cdot  \\sigma(z)(1 - \\sigma(g)) \\cdot W\r\n\\end{equation}\r\n\r\n\\noindent For the baises,\r\n\r\n\\begin{align}\r\n\\label{eqn:dLdW}\r\n\\frac{\\partial J}{\\partial b} &= \\frac{\\partial J}{\\partial g} = \\frac{\\partial J}{\\partial \\hat{y}} \\frac{\\partial \\hat{y}}{\\partial \\sigma} \\frac{\\partial \\sigma}{\\partial g} \\frac{\\partial g}{\\partial b} \\\\\r\n\\frac{\\partial g}{\\partial b} &= 1 \\\\\r\n\\implies \\frac{\\partial J}{\\partial b} &= \\frac{2}{n} \\left( \\sum_i (\\hat{y}_i - y_i ) \\right) \\cdot 1 \\cdot  \\sigma(g)(1 - \\sigma(g)) \\cdot 1\r\n\\end{align}\r\n\r\nNote that $ W $ is actually $ W_\\kappa ^{\\nu (2)} $, a matrix of weights, and b is actually $ b_\\kappa $, a row vector of biases. Thus, the above equation (\\ref{eqn:dLdW}) is just the partial derivative for one term in the weight matrix or bias covector. Repeating the process for each term in the matrix $ W $  and vector $ b $  yields the gradients $ \\grad_w L $  and $ \\grad_B L $, which represent the gradient of the loss function with respect to the weights and biases, respectively. This is the origin of the term, ``gradient descent,'' an optimization algorithm discussed in the next section. This was just the process to calculate the gradients need to update weights for the final layer, but one can see how continuing the process of chaining partial derivatives will yield the gradients for earlier layers in the network. \r\n\r\n\\section{Optimizers} \\label{sec:optimizers}\r\nHaving calculated all the gradients via backpropagation, the weights and biases of the network can now be adjusted. The general idea of gradient descent relies on the fact that the gradient of any function points in the direction of the steepest increase. Thus, to optimize the network---which is equivalent to finding the parameters that minimize the value of the loss function---the weights and biases are updated by shifting their values in the opposite direction of the gradient of the loss function with respect to the weights, $ \\grad_w L $. Gradient descent is the core principle of machine learning; this efficient algorithm for systematically updating model parameters made it possible to develop deep neural networks and train them with large datasets. Numerous improvements have been made to gradient descent since its inception \\cite{cauchy-orig-grad-descent}, AdamW \\cite{AdamW-orig} being the current state-of-the-art. In this section, we introduce several optimization algorithms to provide context for Adam, the optimizer used for training our model. In the previous section (\\ref{sec:backprop}), the gradients of the weights $ W $ and biases $ b $ were written explicitly. For simplicity, the variable $ \\theta $ is introduced to refer to either parameter. As before, $ J(\\theta) $  is the cost function; it could be the MAE, MSE, or any other differentiable measurement of fit quality.\r\n\r\n\\subsubsection{Gradient Descent}\r\nVanilla gradient descent \\cite{gradient-descent-rev-article} updates the parameters in the following way:\r\n\r\n\\begin{equation}\r\n    \\label{batch-grad-descent}\r\n    \\theta := \\theta - \\eta \\cdot \\grad_\\theta J(\\theta)\r\n\\end{equation}\r\n\r\n\\noindent Here (\\ref{batch-grad-descent}), $ \\eta $ is a \\textit{hyperparameter} known as the learning rate. A hyperparameter is a user-defined parameter that must be chosen before the training process begins; it is not a trainable parameter. Hyperparameters can be ``tuned'' by repeating the entire training process with various hyperparameters set. Typically, one trains the model with a variety of hyperparameters over a short number of epochs. Once satisfied, the number of epochs is increased, and the training is repeated with the best-found hyperparameters. One limitation to gradient descent is the need for the entire cost $ J $ to be calculated. For large datasets, this can become impractical. Two common variants are batch gradient descent and stochastic gradient descent (SGD). In the former, the training set is divided into batches, and the gradient is updated after each batch. One iteration through all the batches is called an \\textit{epoch}. In the latter, the gradient is calculated using the loss function instead of the cost function---i.e. the gradient is calculated, and the parameters are updated after each training sample. Both methods greatly reduced training time with the help of optimized, parallel computing \\cite{stoch-grad-desc-parallel}. By updating the parameters after every training sample, SGD will move in the direction of the true gradient. The major limit to these methods, however, is the fixed learning rate \\cite{grad-desc-limits}. If the learning rate $ \\eta $ is too large, the algorithm will be unstable and ``bounce'' around the global minimum of the cost function. If $ \\eta $ is too small, the algorithm will, at best, take a long time to train, and at worst, end up stuck in a local minimum. \r\n\r\n\\subsubsection{Stochastic Gradient Descent with Momentum}\r\nCompared to regular SGD, stochastic gradient descent with momentum \\cite{grad-desc-with-mom-orig} can greatly reduce the time to convergence. The general idea is to add a fraction of the previous parameter update to the current update. The exponential moving average (EMA) is an averaging of points within a period that puts greater weight on more recent points\\footnote{In contrast a simple moving average treats each point as equally significant}. Here, $ S_t $ is the $ t^{th} $  value in the sequence S, and $ V_t $ is the $ t^{th} $  value in the new exponential moving averaged sequence, $ V $ .\r\n\r\n% \\begin{align}\r\n%     % \\label{eq:SGD}\r\n%     & V_1 = \\beta V_0 + \\left(1 - \\beta \\right) S_1 \\\\\r\n%     & V_2 = \\beta V_1 + \\left(1 - \\beta \\right) S_2 \\\\\r\n%     & ...\r\n% \\end{align}\r\n\\begin{equation}\r\n    \\label{eq:SGD-w-momentum}\r\n    V_t = \\beta V_{t-1} + (1 - \\beta)S_t\r\n\\end{equation}\r\n\r\n\\noindent where $ \\beta \\epsilon [0,1]$, a hyperparameter which partly defines how much weight the previous $ 1/(1-\\beta) $ terms of S contribute\\footnote{Typically 0.90 is a good starting point}. EMA's are common in market forecasting, so often $ S_t $  is the price at time $ t $. The continuous update for SGD with momentum is as follows:\r\n\r\n\\begin{align}\r\n    V_t &= \\beta V_{t-1}  + \\left( 1 - \\beta \\right) \\grad_\\theta J \\left( \\theta \\right)\\\\\r\n    w &= W - \\alpha V_t\r\n\\end{align}\r\n\r\n\r\nHere, $ \\alpha $  is the learning rate, as always. To be clear, $\\grad_w L$ is the gradient of the loss function with respect to the weights. Note that the cost function $ J(\\theta) $ may instead be the loss function $ L(\\theta) $ if updates are performed after each training sample (i.e.~a batch size of one). SGD with momentum tends to perform better than SGD because it gives a closer estimate of the full gradient from the batch than SGD. Additionally, the momentum helps push the update through ravine-shaped local minima in the correct direction, whereas SGD tends to oscillate back and forth along the ravine's steeper dimension \\cite{qian1999momentum}.\r\n\r\n\\subsubsection{Root Mean Squared Propagation}\r\nRoot Mean Squared Propagation (RMSprop)\\footnote{RMSprop has an interesting history. It is an unpublished algorithm, first introduced by Geoff Hinton in an online series of lectures. Nevertheless, it is an incredibly popular algorithm and included in most ML platforms.} is another variant of SGD designed to improve convergence speed and remedy Adagrad's \\cite{adagrad} tendency to rapidly diminishing gradients \\cite{improving-rprop}\\cite{2017marginal-adagrad}. The idea is to dampen oscillations in directions when the predictions are close to the cost function's minimum and accelerate movement when far away. In RMSprop, we keep a moving average of the squared gradients for each weight and use these to divide the learning rate by an exponentially decaying average. As before, $\\grad_\\theta J$ is the gradient of the cost with respect to weights.\r\n\r\n\\begin{align}\r\n    \\label{eqn:RMS_Prop}\r\n    & S_{k+1} = \\beta S_k + (1 - \\beta)(\\grad_\\theta J \\cdot \\grad_\\theta J) \\\\\r\n    & \\theta_{k+1} = \\theta_k - \\alpha \\frac{\\grad_\\theta J}{\\sqrt{S_{k+1}} + \\epsilon}\r\n\\end{align}\r\n\r\n\\noindent The hyperparameter $ \\epsilon $ is included in the denominator to prevent a possible division by zero as well as provide more stability.\\footnote{Typical values for $ \\alpha $  and $ \\beta $  are 0.001 and 0.9, respectively.} \r\n\r\n\\subsubsection{Adaptive Moment Estimator}\r\nAdaptive Moment Estimator (Adam) is a combination of RMSprop and SGD with momentum. Adam uses the squared gradients to scale the learning rate for each parameter (similar to RMS prop), and it uses a moving average of the gradient (similar to SGD with momentum).\r\n\r\n\\begin{align} \r\n    \\begin{split} \r\n    m_t &= \\beta_1 m_{t-1} + (1 - \\beta_1) (\\grad_\\theta J) \\\\ \r\n    v_t &= \\beta_2 v_{t-1} + (1 - \\beta_2) (\\grad_\\theta J \\cdot \\grad_\\theta J) \r\n    \\end{split} \r\n\\end{align}\r\n\r\n\\noindent The new parameters in this algorithm, $ m_{t-1} $ and $ v_{t-1} $ are the first and second moments of the gradient (the mean and variance), respectively. Adam's 80,000 citations in the six years since its publication gives some indication of the importance and power of this algorithm \\cite{orig-ADAM-paper}. This was the chosen algorithm for training our neural network for predicting disorder in XANES.\r\n\r\n\\section{Normalization} \\label{sec:normalization}\r\nNormalization is an important step for any machine learning algorithm. There are three types of normalization utilized in our training process: feature normalization, label normalization, and batch normalization. Without feature normalization, a model will put greater weight on features with larger values. For example, if a model is trained to predict surface stress of a silica bead in silicone gel given the diameter of the bead in microns and the adhesion energy in $ \\text{mNm}^{-1} $, the model would learn to ignore the bead's size in its predictions. This is because the particle's size is $ 1000\\times $ smaller than the adhesion energy \\cite{williamsThesis}. To correct this scaling issue each feature is ``normalized'' on the training data to be on the same scale. Often a z-score is used to center the features around a mean of zero with a standard deviation of one. This is known as standardizing or applying a standard-scalar \\cite{statsTextbook}.\r\n\r\n\\begin{equation}\r\n    \\label{z-score}\r\n    Z_{norm}^{(i)} = \\dfrac{x_i-\\mu}{\\sqrt{\\sigma^2-\\epsilon}}\r\n\\end{equation}\r\n\r\n\\noindent In our neural network, the training features are normalized in this way. \r\n\r\nFor the same reasons feature normalization is important, the training labels must also be normalized. Instead of using the standard scalar, the labels are normalized using min-max normalization, which normalizes the values between zero and one. This is useful when the labels are known to be evenly distributed over a range. To scale the $ i^{th} $ label (y) via min-max scaling:\r\n\r\n\\begin{equation}\r\n    Z_{norm}^{(i)} = \\dfrac{x_i - \\text{Min}(y)}{\\text{Max}(y) - \\text{Min}(y)}\r\n    \\label{eqn:min-max-scaler}\r\n\\end{equation}\r\n\r\nScaling the training features means the neural network will predict the scaled values. The prediction can be ``un-scaled'' to retrieve the real, predicted values via:\r\n\r\n\\begin{equation}\r\n    y^{(i)} = - \\dfrac{Z_{norm}^{(i)}\\left(\\text{Max}(y) - \\text{Min}(y)\\right)}{\\text{Min(y)}}\r\n\\end{equation}\r\n\r\n\\noindent It is important that the scaling parameters $ \\mu,~\\sigma,~\\text{Min}(y)$ and $\\text{Max}(y) $ come from the training set---not the testing or validation set. Using the values from the entirety of data constitutes a form of \\textit{data leakage}, where the training process is given a hint of the validation or test data. It is important that the model never sees the testing or validation until testing or validation time; otherwise, the model is unlikely to generalize as well to unseen data as one might expect given a loss curve.\r\n\r\nBatch normalization is a technique designed to make NN's more robust to internal covariate shift \\cite{batch-norm-orig}. Covariate shift refers to a systematic difference between the training and validation data, or in the context of a training batch, a systematic shift in the distribution of data from batch to another \\cite{batch-norm-conference}. For example, if a NN is trained for binary classification to predict whether or not an image includes a cat---and the network is trained on images of only black cats---the network is unlikely to make a correct prediction when it encounters an image of an orange cat.\r\n\r\nThe idea of batch normalization is to normalize each hidden layer similar to how training data or labels are normalized; however, whereas normalizing the training data centers the dataset or labels using fixed parameters such as the mean and variance, in batch normalization the mean and variance of the batch normalization are learnable parameters. In batch normalization, the values for a hidden layer are scaled via:\r\n\r\n\\begin{equation}\r\n\\widetilde{Z}_i = \\gamma Z_{norm}^{(i)} - \\beta\r\n\\end{equation}\r\n\r\n\\noindent Notice that if $\\sqrt{\\sigma^2 + \\epsilon}$ and $\\gamma = \\mu$, we get equation (\\ref{z-score}), i.e. the hidden layer is normalized in the same way as the input layer. This is generally not useful, however, because normalizing all parameters to be centered around zero causes the sigmoid-like activation functions to be mostly focused on the linear regime.\r\n\r\n% The general structure of implementing batch normalization looks something like this:\r\n% \\begin{align}\r\n% \\text{first pass: }& x \\cdot \\theta^T \\rightarrow z \\\\\r\n% \\text{batch normalize: }& z \\rightarrow \\widetilde{z} \\\\\r\n% \\text{apply activation function: }& g(\\widetilde{z}) = a \\\\\r\n% \\text{second pass: }& a \\cdot \\theta^T\r\n% \\end{align}\r\n\r\n% Note, this is for one batch, so $x$ is the $i^{th}$ batch. \r\n\r\nThe output of the batch normalization is passed forward to the next hidden layer of the network, while the normalized input is retained in the current layer. Normalizing the hidden layers for each batch means that later hidden layers do not have to adapt as much to the earlier hidden layers. Consequently, this allows the deeper layers to do a better job tuning themselves a little more independently of the other layers, improving performance and speeding up the learning process. Note, because each batch is scaled $(z \\rightarrow \\widetilde{z})$, a small amount of noise is added, which acts as a slight form of regularization\\footnote{Note, while batch-norm adds regularization, this is not intended to be used as a form of regularization. L1, L2 regularization or dropout layers should be used instead.}. Recently, several papers  \\cite{batch-norm-conference} \\cite{whybatchnorm2} \\cite{whybatchnorm3} have been published disputing the reason batch normalization improves the model performance; none, however, dispute its efficacy. Data augmentation may be vital in building the neural network trained on simulation data to predict experimental data, for which there is a sparsity of data for training. \r\n\r\n\\section{Data Sparsity}\r\nUnfortunately, not all project goals include a plethora of diverse training data. This section introduces two techniques for dealing with training data: data augmentation and transfer learning. Data augmentation can be a valuable technique even with an abundance of training data. Transfer learning, on the other hand, aims to solve a complex problem with little data by first training the model on an easier problem with ample data.\r\n\r\n\\subsection{Data Augmentation}\r\nData augmentation is a technique for expanding the size and variance of the training data for machine learning purposes. It has been critically important for developing powerful deep neural networks, particularly in the domain of image processing \\cite{data-augmentation1}\\cite{data-augmentation2} \\cite{data-augmentation3} \\cite{data-augmentation4}. Consider the example in section \\ref{sec:normalization} of a cat-vs-not-cat binary classifier. The idea of data augmentation is to take the dataset containing only images of the black cats and add new images created from the original dataset. Common methods of data augmentation are image cropping, image rotation, and introducing image filters that alter the color, sharpness, or contrast. In the case of the black-cats-only dataset, color filtering may train the network to become color agnostic and correctly classify an image of an orange cat without ever having seen one. For signal processing, including absorption spectroscopy, common methods for expanding the training data size include the introduction of Gaussian noise and shifting the spectra horizontally \\cite{data-augmentation5}. By artificially expanding the size and complexity of training data, data augmentation helps prevent models from overfitting.\r\n\r\n\\subsection{Transfer Learning}\r\nTransfer learning was first introduced in 1976 to \\cite{transferlearning-reminder} \\cite{transferlearning2} \\cite{transferlearning3}. The idea is to alter a model trained on one task to be able to solve a new but similar task. One famous example involves a neural network originally trained to classify pastries, which, utilizing transfer learning, was re-purposed for detecting cancer cells \\cite{ny-pastry-article}. Consider a model first trained on dataset $ A $ with the final goal of predicting dataset $ B $. Note that $ A $ and $ B $ in this example are not a train-test split but, instead, inherently different problems. By pre-training the model on $ A $ to solve a similar task with $ B $, the model learns inductive biases which encourage the model's parameters $ \\theta_B $ to be similar to $ \\theta_A $. This may have the effect of training the model to learn low-level features that may not have been learned from $ B $ alone  \\cite{transferBook}. Transfer learning using simulations as training data is a cutting-edge topic of research in ML and particularly in AI. Modern autonomous driving systems rely on testing and training their models using driving simulations to bolster their practice time beyond what would be possible from real-world driving tests alone  \\cite{mit-self-driving-car-simulations}. A significant time has been invested in creating platforms specifically for developing autonomous driving systems \\cite{carla-dosovitskiy2017}. \r\n\r\nApplying transfer learning to incredibly sparse datasets---attempting to teach the model from just a few examples---is called few-shot learning\\footnote{Other common terms are ``one-shot''  \\cite{one-shot-learning} and ``zero-shot'' \\cite{zero-shot-learning} learning. These both refer to the same concept but with only one or even zero training examples, respectively} \\cite{few-shot-learning}. This is a very hot area of modern research, as there are many instances in which real-world data is incredibly expensive to acquire, but simulating or obtaining similar data is possible.\r\nIn the context of this thesis, transfer learning will be an important tool for creating a neural network capable of predicting disorder from an experimental XANES spectrum. Because of the sparsity of experimental data, it is unfeasible to train the neural network on experimental data alone. Instead, we rely on simulated XANES spectra created with FEFF. The systematic differences between the simulated XANES spectra and the experimental counterparts, however, suggest a neural network trained purely off simulation spectra will not perform well when it encounters an experimental spectrum for the first time. Applying the principles of transfer learning: the neural network can first be trained with the simulated XANES spectra, for which there are ample examples. Then, using the limited number of experimental data---included extra examples created via data augmentation---the network can be trained again via transfer learning.\r\n\r\n\r\n\\section{Covolutional Neural Networks}\r\nConvolution is a mathematical operation for combining two functions, the result of which is a third function revealing the effect of the second function on the first \\cite{Boas-mathmethods}. The convolution of two continuous functions, $ f $ and $ g $, is a special type of integral transformation. The result is the integral of the product of $ f $ and the shifted inverse of $ g $, where $ f $ can be thought of as the input function and $ g $ is often referred to as the kernel.\r\n\r\n\\begin{equation}\r\n    f \\otimes g = \\int_{-\\infty}^{\\infty} f(j)g(i-j) \\,dj \r\n\\end{equation}\r\n\r\n\\noindent The variable $ i $ (no relation to the imaginary number) is represents the weighted-shift in the function $ g(\\tau) $. Different values of $ i $ emphasize different parts of the other function, $ f(\\tau) $.  \r\n\r\nIn computer science, convolutions are an important and powerful tool for signal and image processing \\cite{1dconv-NN-survey} \\cite{deepCNNforImages}. Because images and signals---which can be thought of as a 1D image---are comprised of a discrete number of points (e.g.~pixels), a modified formula is required to perform the convolution. The convolution of the signal $ f $ with the kernel $ g $ can be written as \\cite{cornell-convs}:\r\n\r\n\\begin{equation}\r\n    \\label{eqn:cs-1dconv}\r\n    f \\otimes g = \\sum_{j=1}^m g(j) \\cdot  f(i-j+m/2)\r\n\\end{equation}\r\n\r\n\\noindent Here (\\ref{eqn:cs-1dconv}), $ m $ is the length of the kernel $ g $, and $ i $ and $ j $ are hyperparameters. To demonstrate visually, consider a simple, example absorption spectrum with only 10 data points (\\ref{fig:conv-ex-spectrum}).\r\n\r\n\\begin{figure}[h!]\r\n    \\centering\r\n    \\includegraphics[width=.75\\linewidth]{Chapters/Figures/conv-example.pdf}\r\n    \\caption[Toy Absorption Spectrum]{A simple abosrption spectrum for demonstration purposes.}\r\n    \\label{fig:conv-ex-spectrum}\r\n\\end{figure}\r\n \r\n\\noindent Each data point, $ (E, \\mu) $ in the spectrum is described as a feature vector, where the feature is the energy value for a given point $ (E, \\mu) $. The vector, $ f $,  is depicted below with boxes to represent each element in the vector. Zeros are padded on both sides for reasons that will become clear soon. \r\n\r\n\\begin{table}[h!]\r\n    \\centering\r\n    \\begin{tabular}{c|c|c|c|c|c|c|c|c|c|c|c|c|}\r\n    \\cline{2-13}\r\n    \\textit{f} = & 0 & .09 & .10 & .09 & .70 & .80 & .68 & .60 & .62 & .63 & .60 & 0 \\\\ \\cline{2-13}\r\n    \\end{tabular}\r\n\\end{table}\r\n\r\n\\noindent Additionally, consider the kernel, $ g $  \r\n\r\n\\begin{table}[h!]\r\n\\centering\r\n    \\begin{tabular}{lccc}\r\n    \\cline{2-4}\r\n    \\multicolumn{1}{l|}{\\textit{g} =} & \\multicolumn{1}{c|}{.1} & \\multicolumn{1}{c|}{.1} & \\multicolumn{1}{c|}{.1} \\\\ \\cline{2-4}                 \r\n    \\end{tabular}\r\n\\end{table}\r\n\r\n\\noindent The convolution works by multiplying each element in the input vector $ f $ by the corresponding element in the kernel $ g $ and summing the results. The kernel then moves to be centered around the next element in $ f $. One way to think about this process is a kernel or filter sliding over an input signal. Applying the kernel $ g $ onto the first index of $ f $ yields: \r\n\r\n\\begin{table}[h!]\r\n    \\centering\r\n    \\begin{tabular}{|c|c|c|c|c|c|c|c|c|c|c|c|}\r\n    \\hline\r\n    0  & .09 & .10 & .09 & .70 & \\multicolumn{1}{c|}{.80} & \\multicolumn{1}{c|}{.68} & \\multicolumn{1}{c|}{.60} & .62 & .63 & .60 & 0 \\\\ \\hline\r\n    .1 & .1  & .1  &     &     &                          &                          &                          &     &     &     &   \\\\ \\hline\r\n    \\end{tabular}\r\n\\end{table}\r\n$$ \r\nh(1) = (0)(.1) + (.09)(.1) + (.10)(.1) = 0.019\r\n$$\r\n\r\n\\noindent where $ h(1) $ is 1st index of the resulting vector. For the next point, the kernel shifts to be centered around it. \r\n\r\n\\begin{table}[h!]\r\n    \\centering\r\n    \\begin{tabular}{|c|c|c|c|c|c|c|c|c|c|c|c|}\r\n    \\hline\r\n    0 & .09 & .10 & .09 & .70 & \\multicolumn{1}{c|}{.80} & \\multicolumn{1}{c|}{.68} & \\multicolumn{1}{c|}{.60} & .62 & .63 & .60 & 0 \\\\ \\hline\r\n      & .1  & .1  & .1  &     &                          &                          &                          &     &     &     &   \\\\ \\hline\r\n    \\end{tabular}\r\n\\end{table}\r\n\r\n$$ \r\nh(2) = (.09)(.1) + (.10)(.1) + (.09)(.1) = 0.028\r\n$$\r\n\r\n\\noindent The final resulting vector is:\r\n\r\n\\begin{table}[h!]\r\n    \\centering\r\n    \\begin{tabular}{c|c|c|c|c|c|c|c|c|c|c|}\r\n    \\cline{2-11}\r\n    \\textit{h} = & .019 & .028 & .089 & .159 & .218 & .208 & .190 & .185 & .185 & .123 \\\\ \\cline{2-11} \r\n    \\end{tabular}\r\n\\end{table}\r\n\r\n\\begin{figure}[h!]\r\n    \\label{fig:conv-res-spectrum}\r\n    \\centering\r\n    \\includegraphics[width=.75\\linewidth]{Chapters/Figures/conv-example-res.pdf}\r\n    \\caption[1D Convolution Result]{The result of the 1D convolution of kernel $ g = (.1, .1, .1) $  on the spectrum in Figure \\ref{fig:conv-ex-spectrum} is plotted above.}\r\n\\end{figure}\r\n\r\nThe toy example was chosen to demonstrate the basics of a 1D convolution. In this example, the input spectrum was a vector of length ten and the kernel of length three. In the context of applying a 1D convolution to a neural network, the size of the input vector is the cardinality of the hidden layer directly preceding the convolutional layer. Often the hidden layer's output, represented as a vector, is reshaped into an n-dimensional tensor before applying the convolution. To apply a 1D-convolution to a Tensor of rank $ n $, simply apply the convolution to each of the n-vectors separately, ensuring to pad the ends of each vector with zeros. Layers with dimensionality greater than one can be ``un-raveled''. Alternatively, the layers of each dimension can be truncated or ``pooled'' by averaging the layers that are stacked on one another (or taking the max of each layer) until the desired dimensionality is achieved. A common way to achieve this is with a max-pooling layer or an average pooling layer. Max pooling and average pooling layers also have the additional benefit of downsampling the feature space, tending to make the network more robust to slight variations in the position of features in the input image or signal. This is referred to as ``local translation invariance'' \\cite{local-translation-invariance}.\r\n\r\nAnother important possible change in the above example is the stride length. In the above example, we ``slid'' the kernel across the input spectrum one point at a time. This is referred to as a stride size or stride length of one. The stride could be any integer less than the length of the input vector $ f $, though in practice, typically stride lengths tend to be one or close to one. Lastly, in the above example, we only applied one convolutional kernel, or ``filter.'' In practice, many filters are applied sequentially. In the above example, the filter $ g = (.1, .1, .1) $ was simply decided upon \\textit{a priori}. In practice, the values for each filter in the convolutional layer are initialized randomly or according to the specified initialization function. The default in Keras is Glorot Uniform. The values of each filter are trainable parameters that evolve to produce the best final prediction given the subsequent layers in the neural network.\r\n\r\n\r\n\\section{How to Train a Neural Network}\r\nBuilding a successful neural network requires a combination of intuition and procedural know-how. The first key is to start with a simple model, perhaps a single hidden. \\textit{If you start with a complex model including data augmentation and regularization, you will never be able to tune the hyperparameters and find a good solution}. A good strategy is to pick a simple architecture and reasonable hyperparameters and train the model on a small subset of training samples, say 1--10 samples. Then, train the model over ten or so epochs and see if the training cost decreases and whether you can overfit it. If you can overfit the small sample size, it means the code is working, and the network architecture makes sense. Now is the time to increase the number of samples in the training data, either to the full train-test split or a subset of if working with ``big data.''\\footnote{Big data has become a nebulous term, but a reasonable example is when there is so much data that the dataset cannot be loaded into the computer's memory (RAM) at the same time.} Next, you can run a broad hyperparameter search. Afterward, run maybe 20 epochs and see how the training and validation loss is moving. If they both are going down, the architecture looks good. If not, start over. Ideally, the training and validation loss curves will be decreasing together like in figure \\ref{fig:Example-Training-Loss-Curve}. If the model still does not predict well after hyperparameter tuning, the model is underfitting, and a more complex architecture is required (add more layers).\r\n\r\n\\begin{figure}\r\n    \\includegraphics[width=\\linewidth]{Chapters/Figures/epoch_loss1.pdf}\r\n    \\caption[Example ANN Training Curve]{In this example loss curve, the x-axis is the epoch, and the y-axis is the mean squared error of the predictions. The red curve is the training data, and the blue curve is the validation set. Notice how both curves decrease together, but the training curve has a smaller error than the validation curve. This is the expected behavior of a model that is not overfitting and training properly.}\r\n    \\label{fig:Example-Training-Loss-Curve}\r\n\\end{figure}\r\n\r\nIdeally, the training and validation loss will decrease together over many epochs. It is more likely, however, that after many epochs, the training loss will continue to decrease while the validation loss plateaus. This is the point to start introducing regularization such as dropout layers as well and considering data augmentation. These techniques will allow the model to continue decreasing the validation loss and prevent overfitting. The main goal of training is to minimize the validation loss. The placement of dropout layers and the type of data augmentation are subject to trial and error. Generally, it is best to include dropout layers after a ReLU activation and before an affine layer. There has been some research suggesting the inclusion of low-probability dropout layers after convolutional layers tends to improve model performance \\cite{conv-dropout-layers} \\cite{conv-dropout-layers2}, but these rules do not work for every network, and it is still worth trying many options while training.\r\n\r\n\r\n\r\n% \\section{Autoencoders if they become useful}\r\n% Talk about how autoencoders work. Give a nice broad explanation and really go into the math. Include some nice diagrams\r\n\r\n% Here's \\cite{ng2011sparse} a good source to read and model off of. Here \\cite{Bhowick2019} is another paper that might be interesting to read. It's about getting noise-free data from the original data using an autoencoder. Neat idea, and could actually be very relevant because they're using geophysical data.\r\n\r\n\r\n\r\n", "meta": {"hexsha": "7b79e6b89b024503e1d8c62939b12fc10fb88e40", "size": 51744, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapters/Chapter3.tex", "max_stars_repo_name": "jthaller/BNL_Thesis", "max_stars_repo_head_hexsha": "1b748993f7ed76de12972f1bc75fedeebee8b7d5", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapters/Chapter3.tex", "max_issues_repo_name": "jthaller/BNL_Thesis", "max_issues_repo_head_hexsha": "1b748993f7ed76de12972f1bc75fedeebee8b7d5", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapters/Chapter3.tex", "max_forks_repo_name": "jthaller/BNL_Thesis", "max_forks_repo_head_hexsha": "1b748993f7ed76de12972f1bc75fedeebee8b7d5", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 104.5333333333, "max_line_length": 2090, "alphanum_fraction": 0.7439703154, "num_tokens": 12859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3047433395971459}}
{"text": "\\section{Gradients}\\label{derivs}\r\n\\index{Gradients|ff}\\index{Derivatives|(}\r\nBy ``gradients'' we generally mean ``the derivative of the energy with respect\r\nto coordinates''.  The two most commonly used gradients are with respect to\r\nCartesian coordinates, in which case the units are kcal/mol/\\AA ngstrom, or\r\nwith respect to internal coordinates, in which case the units are either \r\nkcal/mol/\\AA ngstrom or kcal/mol/radian, depending on whether the coordinate is\r\na distance (in which case it would be kcal/mol/\\AA ngstrom) or an angle or\r\ndihedral (in which case it would be kcal/mol/radian). The particular gradient\r\nactually being used at any given point should be clear from the context. In all\r\ncases, the gradient can be regarded as the following derivative\r\n$$\r\ng_i = \\frac{d(\\Delta H_f)}{dx_i}\r\n$$\r\nIn discussion ``gradient'' will be reserved for the derivative with respect to\r\ncoordinates flagged for optimization (internal or Cartesian), and\r\n``derivative'' will be used for both gradients and terms which are used to\r\ncalculate gradients, such as Cartesian derivatives which are used to calculate\r\ninternal coordinate gradients.\r\n\r\nThere are four very different ways to calculate gradients, although all four\r\nresult in the same type of derivative.  The four ways are:\r\n\\begin{description}\r\n\\item[Frozen density matrix finite difference derivatives]~\\\\\r\n\\index{Wavefunctions!variational}\r\nIn these procedures, once an SCF has been achieved, the derivatives can be \r\ncalculated using the density matrix from the SCF calculation.  These methods \r\ncan only be used with variationally optimized wavefunctions. \r\n\r\nBy default, the derivatives are worked out by calculating the energy of each\r\npair of atoms, then re-calculating the energy after a small displacement has\r\nbeen made, and then calculating the derivative from the differences in the\r\nenergies and the step.  This is the default, and is the fastest.  If this\r\nmethod is {\\em not} wanted, specify \\comp{ANALYT}.\r\n\r\n\\item[Analytical derivatives, using frozen density matrix approximation]~\\\\\r\nNot as fast as the first method, but more accurate.  Useful when finite\r\ndifference derivatives are suspected to be of insufficient accuracy.  When\r\nanalytical derivatives are wanted, specify \\comp{ANALYT}.  Analytical\r\nderivatives cannot be used with non-variational finite difference derivatives.\r\n\r\n\\item[Non-variational finite difference derivatives]~\\\\ \r\nFor non-variational \\index{Wavefunctions!non-variational}wavefunctions (systems\r\nfor which the electronic energy is modified after the SCF calculation is done,\r\ne.g.\\ C.I.\\ calculations), a  sophisticated derivative routine in \\comp{DERNVO}\r\ncalculates the effect on the  derivative of the post-SCF energy terms.  This\r\nmethod is used automatically in RHF C.I.\\ calculations.  If this method is {\\em\r\nnot} wanted, specify \\comp{NOANCI}.\r\n\r\n\\item[Brute force gradients]~\\\\\r\nThese should be avoided whenever possible.  To calculate the gradient, a small\r\nchange is made in the desired coordinate, then a full SCF is done, and the\r\ngradient calculated from\r\n$$ \r\ng_i = \\frac{\\Delta H_f-\\Delta H_f'}{x-x^{'}}.\r\n$$ \r\nThese gradients are very slow, and are of poor accuracy, but sometimes they\r\nare the only way to obtain  gradients.  These derivatives cannot be used\r\nwith variationally optimized wavefunctions, but can be used with \r\nnon-variational wavefunctions by specifying \\comp{NOANCI}.  \r\n\\end{description}\r\n\r\nNote that \\comp{ANALYT} and \\comp{NOANCI} apply to two very different things:\r\n\\comp{ANALYT} applies to the derivatives using a frozen density matrix\r\napproximation, and uses true analytical methods.  \\comp{NOANCI} prevents\r\nLiotard's C.I.\\ derivative method being used.  Of course \\comp{NOANCI} has no\r\nmeaning for variationally optimized wavefunctions.\r\n\r\n\\subsection{Frozen density matrix finite difference derivatives}\r\n\r\nThe first step in calculating the gradients is to calculate the derivatives\r\nwith respect to Cartesian coordinates.  This is done in subroutine DCART.\r\n\\index{DCART}\r\n\r\nDCART calculates the energy of each pair of atoms, then moves one atom a small\r\ndistance ($10^{-4}$\\AA ) in each of the three Cartesian directions.  The\r\ndensity matrix for the atom-pair is not changed during this calculation, but is\r\nset equal to the SCF density matrix. The derivative for each atom is then\r\ncalculated  from:\r\n$$\\left (\\frac{dE}{dx}\\right )_A = \\sum_{B\\neq A}\\frac{E_{AB}-E_{AB}^{'}}{\\delta_x}, $$\r\n$$\\left (\\frac{dE}{dy}\\right )_A = \\sum_{B\\neq A}\\frac{E_{AB}-E_{AB}^{'}}{\\delta_y}, $$\r\n$$\\left (\\frac{dE}{dz}\\right )_A = \\sum_{B\\neq A}\\frac{E_{AB}-E_{AB}^{'}}{\\delta_z}. $$\r\nwhere $E_{AB}^{'}$ is the energy of the pair of atoms after displacement in the\r\nappropriate direction.  For a stationary point, these derivatives are zero.\r\n\r\nTo convert from Cartesian coordinate (c.c.) derivatives into gradients (i.c.),\r\nthe sum\r\n$$\r\ng_i = \\sum_j\\frac{dE}{d({\\rm c.c.}_j)}\\frac{d({\\rm c.c.}_i)}{d({\\rm i.c.}_j)} \r\n$$\r\nmust be evaluated.  Evaluation of  \r\n$\\frac{d({\\rm c.c.}_i)}{d({\\rm i.c.}_j)}$  \r\nis quite simple, and in done in routine JCARIN.\r\n\r\n\\subsection{Hessian matrix in \\comp{FORCE} calculations}\\index{Hessian|(}\\label{ssd}\r\n\\index{Single-sided derivatives}\r\nThe Hessian matrix is the matrix of second derivatives of the energy with\r\nrespect to geometry. The most important Hessian is that used in the\r\n\\comp{FORCE} calculation.  Normal modes are expressed as Cartesian\r\ndisplacements, consequently the Hessian is based on Cartesian rather than\r\ninternal coordinates.\r\n\r\n\\index{Derivatives!``single-sided''} \r\nAlthough first derivatives are relatively easy to calculate, second derivatives\r\nare not.  The simplest, although not an elegant, way to calculate~\\cite{pulayf}\r\nsecond derivatives is to calculate first derivatives for a given geometry, then\r\nperturb the geometry, do an SCF calculation on the new geometry, and\r\nre-calculate the derivatives. The second derivatives can then be calculated\r\nfrom the difference of the two first derivatives divided by the step size. \r\nThis method, which is used in the EigenFollowing routine, is called\r\n`single-sided' derivatives.\r\n\r\nThe Hessian is quite sensitive to geometry, and should only be evaluated at\r\nstationary points.  Because of this sensitivity, ``double-sided'' derivatives\r\n\\index{Derivatives!``double-sided''} are used:\r\n$$\r\nH_{i,j} = \\frac{g_i^{+\\delta_j}-g_i^{-\\delta_j}}{2\\delta}.\r\n$$\r\nNote the asymmetry in the treatment of the Cartesian coordinates $i$ and $j$.\r\nIt can be shown that \r\n$$\r\n\\frac{g_j^{+\\delta_i}-g_j^{-\\delta_i}}{2\\delta} = \\frac{g_i^{+\\delta_j}-g_i^{-\\delta_j}}{2\\delta}.\r\n$$\r\nTo help improve precision, the Hessian is calculated from\r\n$$\r\nH_{i,j} = \\frac{1}{2}\\left ( \\frac{g_j^{+\\delta_i}-g_j^{-\\delta_i}}{2\\delta} + \\frac{g_i^{+\\delta_j}-g_i^{-\\delta_j}}{2\\delta} \\right ).\r\n$$\r\n\\index{Hessian|)}\r\n\\index{Derivatives|)}\r\n", "meta": {"hexsha": "644f83803df48b033abb8ebf2be0914a60933189", "size": 6865, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "manuals/MOPAC2000_manual/t_gradients.tex", "max_stars_repo_name": "openmopac/MOPAC-archive", "max_stars_repo_head_hexsha": "01510e44246de34a991529297a10bcf831336038", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-16T20:53:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T20:54:11.000Z", "max_issues_repo_path": "manuals/MOPAC2000_manual/t_gradients.tex", "max_issues_repo_name": "openmopac/MOPAC-archive", "max_issues_repo_head_hexsha": "01510e44246de34a991529297a10bcf831336038", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "manuals/MOPAC2000_manual/t_gradients.tex", "max_forks_repo_name": "openmopac/MOPAC-archive", "max_forks_repo_head_hexsha": "01510e44246de34a991529297a10bcf831336038", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.8076923077, "max_line_length": 137, "alphanum_fraction": 0.7497450838, "num_tokens": 1761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.30470691462579397}}
{"text": "\\section{Introduction}\\label{sec-intro}\n\n% , further referred to simply as \\emph{effects}\n\n\\emph{Monads}, introduced to functional programming\nby~\\citet{1995_wadler_monads}, are a powerful and general approach for\ndescribing effectful (or impure) computations using pure functions. The key\ningredient of the monad abstraction is the \\emph{bind} operator, denoted by\n\\hs{>>=} in Haskell\\footnote{We use Haskell throughout this paper, but the\npresented results are not specific to Haskell and do not require any advanced\nfeatures of the Glasgow Haskell Compiler (any Haskell98~\\citep{haskell98}\ncompliant compiler will do). Furthermore, we release two libraries for selective\napplicative functors along with this paper: for Haskell and OCaml.}:\n\n\\vspace{1mm}\n\\begin{minted}[xleftmargin=10pt]{haskell}\n(>>=) :: Monad f => f a -> (a -> f b) -> f b\n\\end{minted}\n\\vspace{1mm}\n\n\\noindent\nThe operator takes two arguments: an effectful computation \\hs{f}~\\hs{a}, which\nyields a value of type~\\hs{a} when executed, and a recipe, i.e. a pure function\nof type \\hs{a}~\\hs{->}~\\hs{f}~\\hs{b}, for turning~\\hs{a} into a subsequent\ncomputation of type \\hs{f}~\\hs{b}. This approach to composing effectful\ncomputations is inherently sequential: until we execute the effects in\n\\hs{f}~\\hs{a}, there is no way of obtaining the computation \\hs{f}~\\hs{b},\ni.e. these computations can only be performed in sequence.\n\nConsider a simple example, where we use the monad \\hs{f}~\\hs{=}~\\hs{IO} to\ndescribe an effectful program that prints \\hs{\"pong\"} if the user enters\n\\hs{\"ping\"}:\n\n\\vspace{1mm}\n\\begin{minted}[xleftmargin=10pt]{haskell}\npingPongM :: IO ()\npingPongM = getLine >>= \\s -> if s@\\,@==@\\,@\"ping\" then putStrLn \"pong\" else pure ()\n\\end{minted}\n\\vspace{1mm}\n\n\\noindent\nThe first argument of the bind operator reads a string using\n\\hs{getLine}~\\hs{::}~\\hs{IO}~\\hs{String}, and the second argument is the\nfunction of type \\hs{String}~\\hs{->}~\\hs{IO}~\\hs{()}, which prints \\hs{\"pong\"}\nwhen~\\hs{s}~\\hs{==}~\\hs{\"ping\"}.\n\nThis way of composing effects is sometimes unsatisfactory. To \\emph{inspect} the\nfunction \\hs{\\s}~\\hs{->}~\\hs{...}, we need an~\\hs{s}, which becomes available\nonly during execution; we are therefore unable to predict the effects that\n\\hs{pingPongM} might perform: instead of conditionally executing \\hs{putStrLn},\nas intended, it might delete a file from disk, or launch proverbial missiles. As\nwe will see in sections~\\S\\ref{sec-static} and~\\S\\ref{sec-haxl}, in some\napplications it is desirable to know all possible effects \\emph{statically},\ni.e. before the execution.\n\n\\emph{Applicative functors}, introduced by~\\citet{mcbride2008applicative}, can\nbe used for composing statically known collections of effectful computations, as\nlong as these computations are \\emph{independent} from each other. The key\ningredient of applicative functors is the \\emph{apply} operator, denoted\nby~\\hs{<*>}:\n\n\\vspace{1mm}\n\\begin{minted}[xleftmargin=10pt]{haskell}\n(<*>) :: Applicative f => f (a -> b) -> f a -> f b\n\\end{minted}\n\\vspace{1mm}\n\\newpage\n\n\\noindent\nThe operator takes two effectful computations, which --- independently ---\ncompute values of types \\hs{a}~\\hs{->}~\\hs{b} and \\hs{a}, and returns their\ncomposition that performs both computations, and then applies the obtained\nfunction to the obtained value producing the result of type \\hs{b}. Crucially,\nboth arguments and associated effects are known statically, which, for example,\nallows us to pre-allocate all necessary computation resources upfront\n(\\S\\ref{sec-static}) and execute all computations in parallel\n(\\S\\ref{sec-haxl}).\n\nAlas, our ping-pong example cannot be expressed using applicative functors.\nSince the two computations must be independent, the best we can do is to print\n\\hs{\"pong\"} unconditionally:\n\n\\vspace{0.5mm}\n\\begin{minted}[xleftmargin=10pt]{haskell}\npingPongA :: IO ()\npingPongA = fmap (\\s -> id) getLine <*> putStrLn \"pong\"\n\\end{minted}\n\\vspace{0.5mm}\n\n\\noindent\nWe use \\hs{fmap}~\\hs{(\\s}~\\hs{->}~\\hs{id)} to replace the input string \\hs{s},\nwhich we now have no need for, with the identity function\n\\hs{id}~\\hs{::}~\\hs{()}~\\hs{->}~\\hs{()}, thus matching the return type of\n\\hs{putStrLn}~\\hs{\"pong\"}~\\hs{::}~\\hs{IO}~\\hs{()}. We cannot execute the\n\\hs{putStrLn} effect conditionally but, on the positive side, the effects are no\nlonger hidden behind opaque effect-generating functions, which makes it possible\nfor the applicative functor \\hs{f}~\\hs{=}~\\hs{IO} to statically know the two\neffects embedded in \\hs{pingPongA}.\n\nAt this point the reader is hopefully wondering: can we combine the advantages\nof applicative functors and monads, i.e. allow for conditional execution of some\neffects while retaining the ability to statically know all effects embedded in\na computation? It will hardly be a surprise that the answer is positive, but it\nis far from obvious what the right abstraction should be. For example, one might\nconsider adding a new primitive called \\hs{whenS} to \\hs{IO}:\n\n\\vspace{0.5mm}\n\\begin{minted}[xleftmargin=10pt]{haskell}\nwhenS :: IO Bool -> IO () -> IO ()\n\\end{minted}\n\\vspace{0.5mm}\n\n\\noindent\nThis primitive executes the first computation, and then uses the obtained\n\\hs{Bool} to decide whether to execute the second computation or not. Let us\nrewrite the ping-pong example using \\hs{whenS}:\n\n\\vspace{0.5mm}\n\\begin{minted}[xleftmargin=10pt]{haskell}\npingPongS :: IO ()\npingPongS = whenS (fmap (\"ping\"==) getLine) (putStrLn \"pong\")\n\\end{minted}\n\\vspace{0.5mm}\n\n\\noindent\nWe replace the input string~\\hs{s} with \\hs{True} if it is equal to \\hs{\"ping\"},\nand \\hs{False} otherwise, thereby appropriately \\emph{selecting} the subsequent\neffectful computation. This approach gives us both conditional execution of\n\\hs{putStrLn}~\\hs{\"pong\"}, and static visibility of both effects. Crucially,\n\\hs{whenS} must be an \\hs{IO} primitive instead of being implemented in terms of\nthe monadic bind (\\hs{>>=}), because the latter would result in wrapping\n\\hs{putStrLn} into an opaque function, as in \\hs{pingPongM}.\n\nThe main idea of this paper is that \\hs{whenS}, as well as many other similar\ncombinators, can be seen as special cases of a new intermediate abstraction,\ncalled \\emph{selective applicative functors}, whose main operator for composing\neffectful computations is \\emph{select}:\n\n\\vspace{0.5mm}\n\\begin{minted}[xleftmargin=10pt]{haskell}\nselect :: Selective f => f (Either a b) -> f (a -> b) -> f b\n\\end{minted}\n\\vspace{0.5mm}\n\n\\noindent\nIntuitively, the first effectful computation is used to select what happens\nnext: if it yields a \\hs{Left}~\\hs{a} you \\emph{must execute} the second\ncomputation in order to produce a \\hs{b} in the end; otherwise, if it yields a\n\\hs{Right}~\\hs{b}, you \\emph{may skip} the subsequent effect, because you have\nno use for the resulting function.\n\nThe contributions of this paper are as follows:\n\n\\vspace{-1mm}\n\\begin{itemize}\n    \\item We introduce \\emph{selective applicative functors} as a general\n    abstraction situated between applicative functors and monads, characterising\n    the relationships between all three abstractions with a set of laws, and\n    defining a few important instances (\\S\\ref{sec-selective}).\n    \\item We discuss applications of the abstraction on two real-life case\n    studies: the OCaml build system \\Dune~\\citep{dune} (\\S\\ref{sec-static}) and\n    Facebook's \\Haxl library~\\cite{marlow2014haxl} (\\S\\ref{sec-haxl}).\n    \\item We present \\emph{free selective applicative functors} and show how to\n    use them to implement embedded domain-specific languages with both\n    conditional effects and static analysis (\\S\\ref{sec-free}).\n\\end{itemize}\n\nWe discuss alternatives to selective applicative functors and related work in\nsections~\\S\\ref{sec-alternatives} and \\S\\ref{sec-related}.\n", "meta": {"hexsha": "4235f783feab8c2c2dbb8dd530c91977bbf180db", "size": 7746, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/1-intro.tex", "max_stars_repo_name": "simonmar/selective", "max_stars_repo_head_hexsha": "8016a197fd2cbaa116b593ebc4699fc93b6d4b5e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paper/1-intro.tex", "max_issues_repo_name": "simonmar/selective", "max_issues_repo_head_hexsha": "8016a197fd2cbaa116b593ebc4699fc93b6d4b5e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/1-intro.tex", "max_forks_repo_name": "simonmar/selective", "max_forks_repo_head_hexsha": "8016a197fd2cbaa116b593ebc4699fc93b6d4b5e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.5647058824, "max_line_length": 84, "alphanum_fraction": 0.7452878905, "num_tokens": 2257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251201477015, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.30451456951763156}}
{"text": "%!TEX root=../Selex.tex\n\\section*{Discussion} % (fold)\n\\label{sec:discussion}\n\n% Summary of the study\nThe over-arching objective of this simulation study was to compare the performance of assuming more structural complexity in selectivity when in fact the real data come from a simple stationary process, and assuming simple structural complexity when real data come from a fishery with dynamic changes in selectivity.  To address this objective, a simulation model conditioned on length-based selectivity and variable length-at-age by year was used to generate simulated data for four alternative assessment models that assumed: (a) selectivity was length-based and stationary, (b) selectivity was length-based and changed discretely in four time periods, and (c) selectivity was age-based and allowed to change each year, and (d) selectivity was age-based and interpolated over age and year using a bicubic spline and 60 equally spaced knots.  From the perspective of a na\\\"ive analyst who is unfamiliar with the history of the fishery and the source of the catch-age data, adopting a penalized time-varying selectivity may be more appropriate than assuming constant selectivity.  This general result is also consistent with a similar simulation study that examined time-varying changes in catchability \\citep{wilberg2006performance}.\n\nThe addition of age-composition information into stock assessments greatly enhances the estimability of the underlying production function and related reference points \\citep{magnusson2007mfd}.  In addition, age-composition information can also contribute to the estimation of over-all population scale via catch-curves and fixed assumptions about natural mortality and fisheries selectivity.  However, as assumptions about natural mortality and selectivity are relaxed (and freely estimated), information about population scaling degrades \\citep{hilborn1992quantitative}. If the relative abundance index available for fitting lacks contrasting information to resolve confounding between overall productivity and population scale, the move towards more flexible selectivity models will lead to greater uncertainty.  In such cases where it is known that selectivity has changed over time, the addition of prior information on population scaling (i.e., priors for $B_o$ or survey $q$) will particularly valuable. \n\nEarlier versions of the multivariate logistic likelihood for the age-composition data added a small fixed constant (1.e-30) to the observed and predicted age-proportions to ensure that the function remained defined when observed proportions-at-age were equal to 0 (i.e., this was done to avoid taking the natural logarithm of 0).  It turns out that the value of the fixed constant would have slight influences on the results and in some cases prevent the non-linear search routine from converging to a solution.  Adding a small constant to 0-observations that are likely to have high measurement error is akin to imputing data and is probably not a safe practice in the long-run.  As an alternative approach, we adopted a method used by \\cite{richards1997visualizing} where observed 0 proportions-at-age (or some minimum proportion, e.g., 2\\% in their paper) were pooled with the adjacent year class for that year only.  For example, if the observed proportion of age-4 fish in 1985 was equal to 0, the estimation model would compute the likelihood for the number of age 4--5 fish in 1986;  there is no likelihood component for age-4 fish in 1985.  This pooling of year classes eliminates the need for adding small, potentially influential, constants to the likelihood. There is also a small caveat on this pooling approach: if a given cohort never appears in catch-age data (i.e., a complete year-class recruitment failure), the estimation model will equally split the year class into the adjacent cohort.  \n\nChanges in selectivity over time are also a special case of time-varying catchability.  It has already been demonstrated that additional sources of information, such as tagging data \\citep{martell2002implementing}, and/or area swept information \\citep{winters1985interaction}, would reduce the confounding between stock size and stock productivity.  Statistical catch-at-age models rely on a separability assumption where year and age effects in the observed catch-at-age data can be partitioned into fishing mortality and selectivity, respectively.  Having auxiliary information on either one of these effects from area-swept estimates of relative fishing mortality or size-based selectivity based on tag return data would reduce potential confounding and improve the estimability of time-varying parameters \\citep[e.g.,][]{sinclair2002disentangling}.\n\nThis simulation study examined the specific case where the true underlying selectivity is length-based and the corresponding age-based selectivity changes over time due to changes in growth rates.  Selectivity is a product of vulnerability and availability.  Vulnerability is the probability of catching a fish at a given time/location assuming the fish is available to harvest.  Availability is the probability of fish being present in the time/location where fishing activity is occurring.  These two processes are completely confounded and cannot be separated without additional information that directly measures either vulnerability or availability.  As a result of these two processes, the definition of fisheries selectivity may have many subtle differences among fisheries, or even among years in a given fishery.  Moreover, changes in harvest policy, or changes in allocation among regulatory areas, or fishing fleets, can result in dramatic changes in age-based selectivity due to time/area interactions between various fishing fleets and stock distribution.  Given such complexities, it might be preferable to always adopt an age-based time-varying selectivity sub model in statistical catch-age assessments. Initial assessments could start with very high penalty weights to constrain how much selectivity is allowed to vary (e.g., $\\lambda^{(3)}$), then begin to relax the penalty and examine the sensitivity of both model fit and policy performance to the assumed penalty weight.  Simply assuming a fixed selectivity model, or even block selectivities, is akin to extremely large penalty weights on time-varying selectivity.  In this regard, this simulation presented a 'worst-case' scenario for time-varying selectivity.  Future work could simulate the application of time-varying selectivity in conjunction with a set of rules governing adjustment of the $\\lambda^{(3)}$  and directly explore its performance (i.e., Table \\ref{tab:rankorder}).\n\nOne potential concern with the addition of more and more selectivity coefficients is that the assessment model begins to over-fit the age-composition data and explain the observed data with additional recruitment variation and more complex selectivity coefficients.  This result was observed in the Monte Carlo simulations in this study where the underlying data were generated with extremely complex selectivity patterns and the estimation model had a very flexible selectivity model with many estimated parameters.  Such an over-parameterized model would be of less utility in forecasting due to large uncertainties and confounding in selectivity and recruitment deviations in the terminal year. However, the true uncertainty would be better represented, which might lead to more realistic expectations in a decision table framework.  Penalized likelihoods can ameliorate this to some extent, but we've also shown that the use of interpolation methods (e.g., bicubic splines) for computing age-specific selectivity coefficients each year can perform well.  The subjective issue of importance in the case of using a bicubic spline is the number of spline knots that should be estimated for the year effect.  Presumably model selection could proceed in similar fashion as a stepwise-selection that was proposed by  \\cite{thorson2012stepwise}.  Rules for this procedure could also be tested in similar simulation studies such as this one.\n\n The vast majority of assessment models are age-based requiring age-specific estimates of fishing mortality rates, and hence age-based selectivity \\citep{gavaris2002sif}.  Adopting a fixed age-based selectivity model would certainly lead to erroneous errors if the true underlying model is length-based and substantial changes in growth rates have occurred over time.  Two options for dealing with this problem are: (1) model length-based selectivity and using empirical length-age data, or (2) model age-based selectivity but allow selectivity to change over time. The first option requires unbiased estimates of length-at-age.  These cannot be obtained if composition data are sampled using length-selective gear and there is any appreciable variance in length for a given age. The second option is being explored by the International Pacific Halibut Commission for dealing with changes in selectivity associated with changes in size-at-age and stock distribution \\citep{stewart2012assessment}.  Selectivity in the directed Pacific halibut fishery is length-based given evidence from hooking success studies. There are minimum size-limits in place, so age-specific retention rates vary with changes in size-at-age over time.  The transition to time-varying age-based selectivity was adopted primarily because it solved a retrospective bias that has been of major concern for this stock in recent years.\n\n% MOve to discussion\n% It is fairly typical to see such lags in estimates of abundance, even in age-structured models \\citep{walters2004simple,cox2008practical}\n\nA better alternative to specific case studies would be to develop a closed-loop feedback control system and an appropriate loss function to better elucidate which selectivity parameterization is more appropriate for achieving intended management objectives.  This is also known in the fisheries realm as management strategy evaluation \\citep{de1986simulation,Cooke1999,smith1999implementing}.  Having an appropriate loss function to judge the performance of each alternative model would greatly improve model selection criterion from a policy performance perspective.\n\n% section discussion (end)\n\n\\section*{Acknowledgments} % (fold)\n\\label{sec:acknowledgments}\n\tThe authors would like to thank the organizers of the CAPAM workshop held on March 12-14, 2013 in La Jolla California.  The first author would also like to thank James Ianelli and Dave Fournier for the assistance in developing the bicubic spline model for this application.  Thanks to Bruce Leaman, Andre Punt, Allen Hicks, Robyn Forrest, Ray Hilborn, James Thorson, and many other for feedback on earlier presentations of this work and the provision of the Pacific hake data.\n% section acknowledgments (end)", "meta": {"hexsha": "6b808b70697108aa87996511869914c3740298c7", "size": 10852, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "fba/CAPAM/WRITEUP/Discussion/Discussion.tex", "max_stars_repo_name": "krHolt/iSCAM", "max_stars_repo_head_hexsha": "b6e1f1b5c3f81e1860a983cbafd18221d365fdb6", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fba/CAPAM/WRITEUP/Discussion/Discussion.tex", "max_issues_repo_name": "krHolt/iSCAM", "max_issues_repo_head_hexsha": "b6e1f1b5c3f81e1860a983cbafd18221d365fdb6", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fba/CAPAM/WRITEUP/Discussion/Discussion.tex", "max_forks_repo_name": "krHolt/iSCAM", "max_forks_repo_head_hexsha": "b6e1f1b5c3f81e1860a983cbafd18221d365fdb6", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 361.7333333333, "max_line_length": 1958, "alphanum_fraction": 0.8210468116, "num_tokens": 2164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.5039061705290806, "lm_q1q2_score": 0.3043249847778057}}
{"text": "\\section{Adjusting the queuing model}\\label{sec:scenarios}\n\nThis section is comprised of several `what-if' scenarios --- a classic component\nof healthcare operational research --- under the novel parameterisation of the\nqueue established in Section~\\ref{sec:model}. The outcomes of interest in this\nwork are server (resource) utilisation and system times as these metrics capture\nthe driving forces of cost and flow as well as the overall state of the system,\nits staff and its patients. Specifically, the objective of these experiments is\nto address the following questions:\n\\begin{itemize}\n    \\item How would the system be affected by a change in overall patient\n        arrivals?\n    \\item How is the system affected by a change in resource availability (i.e.\\\n        a change in \\(c\\))?\n    \\item How is the system affected by patients moving between clusters?\n\\end{itemize}\n\nOwing to the nature of the observed data, the queuing model parameterisation\nand its assumptions, the effects on the chosen metrics in each scenario are\ngiven in relative terms with respect to the base case. The base case being those\nresults generated from the best parameter set recorded in\nTable~\\ref{tab:comparison}. In particular, the data from each scenario is scaled\nby the corresponding median value in the base case meaning that a metric having\na value of 1 is `normal'.\n\nAs mentioned in Section~\\ref{sec:intro}, the source code used throughout this\nwork is available online and has been archived online~\\cite{Wilde2020github}. In\naddition to this, the datasets generated from the simulations in this section\nhave been archived along with those generated from the parameter\nsweep~\\cite{Wilde2020results}.\n\n\n\\subsection{Changes to overall patient arrivals}\\label{subsec:arrivals}\n\nChanges in overall patient arrivals to a queue reflect real-world scenarios\nwhere some stimulus is improving (or worsening) the condition of the patient\npopulation. Examples of stimuli could include an aging population or independent\nlife events that lead to a change in deprivation such as an accident or job\nloss. Within this model, overall patient arrivals are altered using a scaling\nfactor denoted by \\(\\sigma\\in\\mathbb{R}\\). This scaling factor is applied to the\nmodel by multiplying each cluster's arrival rate by \\(\\sigma\\). That is, for\ncluster \\(i\\), its new arrival rate, \\(\\hat\\lambda_i\\), is given by:\n\\begin{equation}\\label{eq:lambda}\n    \\hat\\lambda_{i} = \\sigma\\lambda_i\n\\end{equation}\n\n\\begin{figure}\n    \\centering\n    \\begin{subfigure}{.5\\imgwidth}\n        \\includegraphics[width=\\linewidth]{lambda_time}\n        \\caption{}\\label{fig:lambda_time}\n    \\end{subfigure}\\hfill%\n    \\begin{subfigure}{.5\\imgwidth}\n        \\includegraphics[width=\\linewidth]{lambda_util}\n        \\caption{}\\label{fig:lambda_util}\n    \\end{subfigure}\n    \\caption{%\n        Plots of \\(\\sigma\\) against relative (\\subref{fig:lambda_time})~system\n        time and (\\subref{fig:lambda_util})~server utilisation.\n    }\\label{fig:lambda}\n\\end{figure}\n\nFigure~\\ref{fig:lambda} shows the effects of changing patient arrivals on\n(\\subref{fig:lambda_time})~relative system times and\n(\\subref{fig:lambda_util})~relative server utilisation over values of \\(\\sigma\\)\nfrom \\input{tex/lambda_scaling_min} to \\input{tex/lambda_scaling_max} at a\nprecision of \\input{tex/lambda_scaling_step}. Specifically, each plot in the\nfigure (and the subsequent figures in this section) shows the median and\ninterquartile range (IQR) of each relative attribute. These metrics provide an\ninsight into the experience of the average user (or server) in the system, and\nin the stability or variation of the body of users (servers).\n\nWhat is evident from these plots is that things are happening as one might\nexpect: as arrivals increase, the strain on the system increases. However, it\nshould be noted that it also appears that the model has some amount of slack\nrelative to the base case. Looking at Figure~\\ref{fig:lambda_time}, for\ninstance, the relative system times (i.e.\\ the relative length of stay for\npatients) remains unchanged up to \\(\\sigma \\approx 1.2\\), or an approximate 20\\%\nincrease in arrivals of COPD patients. Beyond that, relative system times rise\nto an untenable point where the median time becomes orders of magnitude above\nthe norm.\n\nHowever, Figure~\\ref{fig:lambda_util} shows that the situation for the system's\nresources reaches its worst case near to the start of that spike in relative\nsystem times (at \\(\\sigma \\approx 1.4\\)). That is, the median server utilisation\nreaches a maximum (this corresponds to constant utilisation) at this point and\nthe variation in server utilisation disappears entirely.\n\n\n\\subsection{Changes to resource availability}\\label{subsec:resources}\n\nAs is discussed in Section~\\ref{sec:model}, the resource availability of the\nsystem is captured by the number of parallel servers in the system, \\(c\\).\nTherefore, to modify the overall resource availability, only the number of\nservers need be changed. This kind of sensitivity analysis is usually done to\ndetermine the opportunity cost of adding service capacity to a system, e.g.\\\nwould adding \\(n\\) servers sufficiently increase efficiency without exceeding\na budget?\n\nTo reiterate the beginning of this section, all suitable parameters are given in\nrelative terms. This includes the number of servers here. By doing this, the\nchanges in resource availability are more easily seen, and do away with any\nconcerns as to what a particular number of servers exactly reflects in the real\nworld.\n\n\\begin{figure}\n    \\centering\n    \\begin{subfigure}{.5\\imgwidth}\n        \\includegraphics[width=\\linewidth]{servers_time}\n        \\caption{}\\label{fig:servers_time}\n    \\end{subfigure}\\hfill%\n    \\begin{subfigure}{.5\\imgwidth}\n        \\includegraphics[width=\\linewidth]{servers_util}\n        \\caption{}\\label{fig:servers_util}\n    \\end{subfigure}\n    \\caption{%\n        Plots of the relative number of servers against relative\n        (\\subref{fig:servers_time})~system time and\n        (\\subref{fig:servers_util})~server utilisation.\n    }\\label{fig:servers}\n\\end{figure}\n\nFigure~\\ref{fig:servers} shows how the relative resource availability affects\nrelative system times and server utilisation. In this scenario, the relative\nnumber of servers took values from \\input{tex/num_servers_change_min} to\n\\input{tex/num_servers_change_max} at steps of\n\\input{tex/num_servers_change_step} --- this is equivalent to a step size of 1\nin the actual number of servers. Overall, these figures fortify the\nclaim from the previous scenario that there is some room to manoeuvre so that\nthe system runs `as normal' but pressing on those boundaries results in massive\nchanges to both resource requirements and system times.\n\nIn Figure~\\ref{fig:servers_time} this amounts to a maximum of 20\\% slack in\nresources before relative system times are affected; further reductions quickly\nresult in a potentially tenfold increase in the median system time, and up to 50\ntimes once resource availability falls by 50\\%. Moreover, the variation in the\nbody of the relative times (i.e.\\ the IQR) decreases as resource availability\ndecreases. The reality of this is that patients arriving at a hospital are\nforced to consume larger amounts of resources (simply by being in a hospital)\nregardless of their condition, putting added strains on the system.\n\nMeanwhile, it appears that there is no tangible change in relative system times\ngiven an increase in the number of servers. This indicates that the model\ncarries sufficient resources to cater to the population under normal\ncircumstances, and that adding service capacity will not necessarily improve\nsystem times.\n\nAgain, Figure~\\ref{fig:servers_util} shows that there is a substantial change in\nthe variation in the relative utilisation of the servers. In this case, the\nvariation dissipates as resource levels fall and increases as they increase.\nWhile the relationship between real hospital resources and the number of servers\nis not exact, having variation in server utilisation would suggest that parts of\nthe system may be configured or partitioned away in the case of some significant\npublic health event (such as a global pandemic) without overloading the system.\n\n\n\\subsection{Moving arrivals between clusters}\\label{subsec:moving}\n\nThis scenario is perhaps the most relevant to actionable public health research\nof those presented here. The clusters identified in this work could be\ncharacterised by their clinical complexities and resource requirements, as done\nin Section~\\ref{subsec:overview}. Therefore, being able to model the movement of\nsome proportion of patient spells from one cluster to another will reveal how\nthose complexities and requirements affect the system itself. The reality is\nthen that if some public health policy could be implemented to enact that\nmovement informed by a model such as this then real change would be seen in the\nreal system.\n\nIn order to model the effects of spells moving between two clusters, the\nassumption is that services remain the same (and so does each cluster's \\(p_i\\))\nbut their arrival rates are altered according to some transfer proportion.\nConsider two clusters indexed at \\(i, j\\), and their respective arrival rates,\n\\(\\lambda_i, \\lambda_j\\), and let \\(\\delta \\in [0, 1]\\) denote the proportion of\narrivals to be moved from cluster \\(i\\) to cluster \\(j\\). Then the new arrival\nrates for each cluster, denoted by \\(\\hat\\lambda_i, \\hat\\lambda_j\\)\nrespectively, are:\n\\begin{equation}\\label{eq:moving}\n    \\hat\\lambda_i = \\left(1 - \\delta\\right) \\lambda_i\n    \\quad \\text{and} \\quad\n    \\hat\\lambda_j = \\delta\\lambda_i + \\lambda_j\n\\end{equation}\n\nBy moving patient arrivals between clusters in this way, the overall arrivals\nare left the same since the sum of the arrival rates is the same. Hence, the\n(relative) effect on server utilisation and system time can be measured\nindependently.\n\nFigures~\\ref{fig:moving_time}~and~\\ref{fig:moving_util} show the effect of\nmoving patient arrivals between clusters on relative system time and relative\nserver utilisation respectively. In each figure, the median and IQR for the\ncorresponding attribute is shown, as in the previous scenarios. Each scenario\nwas simulated using values of \\(\\delta\\) from \\input{tex/moving_clusters_min} to\n\\input{tex/moving_clusters_max} at steps of \\input{tex/moving_clusters_step}.\n\nConsidering Figure~\\ref{fig:moving_time}, it is clear that there are some cases\nwhere reducing particular types of spells (by making them like another type of\nspell) has no effect on overall system times. Namely, moving the high\nresource requirement spells that make up Cluster 0 and Cluster 3 to any other\ncluster. These clusters make up only 10\\% of all arrivals and this figure shows\nthat in terms of system times the model is able to handle them without concern\nunder normal conditions. The concern comes when either of the other clusters\nmoves to Cluster 0 or Cluster 3. Even as few as one in five of the low\ncomplexity, low resource needs arrivals in Cluster 2 moving to either cluster\nresults in large jumps in the median system time for all arrivals, and soon\nafter, as in the previous scenario, any variation in the system times\ndisappears indicating an overborne system.\n\nWith relative server utilisation, the story is much the same. The normal levels\nof high complexity, high resource arrivals from Cluster 3 are absorbed by the\nsystem and moving these arrivals to another cluster bears no effect on resource\nconsumption levels. Likewise, either of the low resource need clusters moving\neven slightly toward high resource requirements completely overruns the system's\nresources. However, the relative utilisation levels of the system resources can\nbe reduced by moving arrivals from Cluster 0 to either Cluster 1 or Cluster 2,\ni.e.\\ by reducing the overall resource requirements of such spells.\n\nIn essence, this entire analysis offers two messages: that there are several\nways in which the system can get worse and even overwhelmed but, more\nimportantly, that any meaningful impact on the system must come from a stimulus\noutside of the system that results in more healthy patients arriving to the\nhospital. This is non-trivial; the first two scenarios in this analysis show\nthat there are no quick solutions to reduce the effect of COPD patients on\nhospital capacity or length of stay. The only effective intervention is found\nthrough inter-cluster transfers.\n\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=\\imgwidth]{moving_time}\n    \\caption{%\n        Plots of proportions of each cluster moving to another against relative\n        system time.\n    }\\label{fig:moving_time}\n\\end{figure}\n\n\\begin{figure}\n    \\centering\n    \\includegraphics[width=\\imgwidth]{moving_util}\n    \\caption{%\n        Plots of proportions of each cluster moving to another on relative\n        server utilisation.\n    }\\label{fig:moving_util}\n\\end{figure}\n", "meta": {"hexsha": "e9531716d2fe82eec014ac780c4a5c14474c4355", "size": 12935, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "sections/scenarios.tex", "max_stars_repo_name": "drvinceknight/copd-paper", "max_stars_repo_head_hexsha": "387a14f886d3c562228bb4be45abdd7ed996eda1", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sections/scenarios.tex", "max_issues_repo_name": "drvinceknight/copd-paper", "max_issues_repo_head_hexsha": "387a14f886d3c562228bb4be45abdd7ed996eda1", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-06-28T13:59:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T12:15:13.000Z", "max_forks_repo_path": "sections/scenarios.tex", "max_forks_repo_name": "drvinceknight/copd-paper", "max_forks_repo_head_hexsha": "387a14f886d3c562228bb4be45abdd7ed996eda1", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-23T20:29:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T20:29:08.000Z", "avg_line_length": 53.2304526749, "max_line_length": 80, "alphanum_fraction": 0.7837649787, "num_tokens": 2954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318479832805, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3043249847778057}}
{"text": "% declare document class and geometry\n\\documentclass[12pt]{article} % use larger type; default would be 10pt\n\\usepackage[margin=1in]{geometry} % handle page geometry\n\n\\input{../header.tex}\n\n\\title{Astro 270 -- Astrophysical Dynamics -- Lec01-02}\n\\author{UCLA, Fall 2014}\n\\date{\\formatdate{02}{10}{2014}} % Activate to display a given date or no date (if empty),\n         % otherwise the current date is printed \n%\\date{\\formatdate{07}{10}{2014}} \n\n\\begin{document}\n\\setlength{\\unitlength}{1mm}\n\\maketitle\n\n\n\\textit{Read Chapters 1 and Sections 2.1-2.3}\n\n\\section{Galaxy Dynamics}\nSince there are so many stars, can treat the system either as a fluid\nor as a system of particles. We may want to consider it as a particle\nif we want to account for star-interactions or as a fluid to consider\nits bulk motion. We will have a distribution function which is a\nfunction of position, velocity and time. We typically normalize this\nsuch that it is normalized to unity when integrated over phase space\n\\begin{equation}\n\\int f(\\v{x},\\v{v},\\v{t}) d^3\\v{x} d^3\\v{v} = 1\n\\end{equation}\nThe mean free path should be small in comparison to the macroscopic\nlength scales if we're assuming that it's a fluid in the\n\\textbf{continuum approximation}. Quantities such as the density and\nvelocity are continuous and they are independent parameters. \n\n\nWe have three regimes that we can deal with if we abandon the fluid\napproximatiosn\n\\begin{itemize}\n\\item Lumpy\n\\item Smooth - fluid approximation\n\\item In-between - globular clusters\n\\end{itemize}\nAny system that we want to describe, we can do it any of these three\nways but we have to pick which one. \n\n\\section{Defining Basic Parameters}\n\nWe have two particles at two positions $\\v{x_1}$ and $\\v{x_2}$ We'll\ndefine the difference between them $\\v{x_{12}}$. The gravitational\nacceleration between them is given by $\\v{\\ddot{r}} = \\frac{G\n  m_2}{|\\v{x_{12}}|^3} \\v{x_{12}}$\n\n\\begin{equation}\n\\v{\\ddot{x_1}} = \\sum_{j\\ne 1} \\frac{G\n  m_j}{|\\v{x_{ji}}|^3} \\v{x_{ji}}\n\\end{equation}\nWE can express this in terms of a potential\n\\begin{equation}\n\\v{\\ddot{x_i}} = \\frac{\\pd \\Phi}{\\pd x_i} = -\\v{\\nabla} \\Phi\n\\end{equation}\nNow let's define the gravitational potential\n\\begin{equation}\nW = -\\frac{1}{2} \\sum_i \\sum_{j\\ne i} \\frac{Gm_1 m_j}{|x_{ij}|} =\n\\frac{1}{2} \\sum_i m_i \\Phi (x_i)\n\\end{equation}\nWe can rewrite this in terms of a typical radius $r_h$\n\\begin{equation}\nW = -\\alpha \\frac{GM^2}{r_h}\n\\end{equation}\nKinetic energy is just\n\\begin{equation}\nT = \\frac{1}{2} \\sum_j m_j |\\dot{x_j}|^2\n\\end{equation}\nIn an isolated system\n\\begin{equation}\nE = T + W = constant\n\\end{equation}\n\\subsection{Virial Theorem} \nLet's take the moment of inertia of the system which is defined as\n\\begin{equation}\nI = \\sum_i m_i |x_i^2|\n\\end{equation}\nRight now we are concerned with the second derivative of the moment of\ninertia and subsituting in our previous expresion for $\\v{\\ddot{x_i}}$\n\\begin{equation}\n\\ddot{I} = 2\\sum_i (m_i |\\vec{v_i}|^2 + 2m_i \\v{\\ddot{x_i}} - \\v{x_i} )\n= 4T + 2 \\sum_i m_i \\v{x_i} ( \\sum_{j\\ne1} \\frac{G m_j(\\v{x_j} -\n  \\v{x_j})}{|\\v{x_j} - \\v{x_j}|})\n\\end{equation}\n\\begin{equation}\n\\sum_i \\sum_{j\\ne i} G m_i m_j \\frac{\\v{x_j} \\cdot (\\v{x_j} -\n  \\v{x_i})}{|\\v{x_j} - \\v{x_i}|^3} = \\sum_j \\sum_{i\\ne j} G m_i m_j\n\\frac{x_j \\cdot (\\vec{x_i} - x_j)} {|\\v{x_i} - \\v{x_j}|^3}\n\\end{equation}\nThese are equivalent, meaning that they are equal to half of the sum,\nwhich is\n\\begin{equation}\n\\frac{1}{2} G m_i m_j \\sum_i \\sum{j\\ne i} (\\v{x_i} - \\v{x_j})(\\v{x_j} - \\v{x_i})\n/ (|\\v{x_i} - \\v{x_j}|^3)\n\\end{equation}\nTaking out the minsu sign we get our expression for W\n\\begin{equation}\nW = -\\frac{1}{2} \\sum_i \\sum_{j\\ne i} \\frac{Gm_1 m_j}{|x_{ij}|} \n\\end{equation}\nSo oerall\n\\begin{equation}\n\\ddot{I} = 4T + 2W\n\\end{equation}\n\\begin{equation}\n2T + W = 0\n\\end{equation}\nNote that this only occurs if the system is in a\nbound isolated system in equilibrium. The overal energy of the system\nis T + W, we can say for any gravitational system\n\\begin{equation}\nE = W / 2\n\\end{equation}\nThis is most used to estimate the masses of things. \n\n\\section{Continuum}\nWe expressed the previous sections in terms of sums, but now we want\nto take out the particle-partical interactions and put it in terms of\n$\\rho(\\v{x})$ \nNow our potential is defined as\n\\begin{equation}\n\\Phi(\\v{x}) = -G \\int \\frac{\\rho(\\v{x'})}{|\\v{x} - \\v{x'}|} d^3x'\n\\end{equation}\nWe can use Gauss's therem to state\n\\begin{equation}\n\\int \\v{\\nabla} \\Phi \\v{d^2s} = 4\\pi G M_{enclose}\n\\end{equation}\nWe can then use the divergence theorem\n\\begin{equation}\n\\int \\nabla^2 \\Phi \\v{d^3x} = \\int \\v{\\nabla} \\Phi \\cdot d^2\\v{s}\n\\end{equation}\nWhat we get then is that the integral of the divergence over the\nvolume:\n\\begin{equation}\n\\int \\nabla^2 \\Phi d^3\\v{x} = 4\\pi G \\int \\rho(\\v{x'}) d^3\\v{x'}\n\\end{equation}\nWe then end up with Poissons equation because we can drop the integral\n\\begin{equation}\n\\nabla^2 \\Phi = 4\\pi G \\rho\n\\end{equation}\nThis is an important equation that we'll come back to. Also in the\ncontinuum approximation, we have an expression for the gravitational\npotential W which is analogous to our previous definition in terms of\nthe summation\n\\begin{equation} \nW = \\frac{1}{2} \\int \\rho(\\v{x'}) \\Phi(\\v{x'}) d^3\\v{x}\n\\end{equation}\nWith these results, we can start applying it to simple situations. The\nsimplest one is a spherical potential. \n\n\n\\section{Spherical potential}\nWe can use the spherical symmetry to make two claims. A body inside a\nspherical shell of matter does not experience any force from outside\nof the shell. OUtisde of the shell, the force is the same as a point\nmass all at the center. This is due to Gauss' theorem. The\ncontribution at a distance of r of an infinitesimal shell of thickess $dr$ at distance r'\n\\begin{equation}\n\\delta \\Phi = - \\frac{G M_{shell}}{r} = - \\frac{4\\pi G r'^2\n  \\rho(r')}{r}\n\\end{equation}\nif r is less than r' then there is no force, but there is still a\npotential, but it is a constant. We can choose what that constant is\nso that we have a meaningful potential. We choose it such that the\ncontribution of the potential is continuous at the boundary. So to do\nthat, we can choose that the contribution is \n\\begin{equation}\n\\frac{-G M_{shell}}{r'} = - \\frac{4\\pi G r'^2 \\rho(r') dr'}{r'}\n\\end{equation}\nThat is independent of our location r.\n\nIn total, we now combine those two where the first term is for the\ninterior protion\n\\begin{equation}\n\\phi(r) = -G\\left[ \\frac{1}{r} \\int^r_0 r\\pi \\rho(r') dr' +\n    \\int_r^{\\infty} 4\\pi \\rho(r') r' dr' \\right]\n\\end{equation}\nThe interior's potential is not zero, but the derivative is zero\n\nDark matter tends to aggregate in a spherical halo, so we will use\nthis formalism for a first order approximation for the potential of\nwhat a galaxy is doing.\n\n\\section{Velocity}\nOne of the key observables in a galaxy or in any dynamical system are\nvelocities which helps us see what is happening but also how it\nevolves. We use the velocity of the galaxy to measure the mass of the\ngalaxy. The circular velocity is \n\\begin{equation}\n\\frac{v_c^2}{r} = \\frac{GM(r)}{r^2}\n\\end{equation}\n\\begin{equation}\nv_c^2 = \\frac{GM(r)}{r} = -rF(r) = r(\\v{\\nabla}{\\Phi})\n\\end{equation}\nThe other velocity that is an important determinant of the evolution\nof a system is the escape velocity which is defined in terms of how\nmuch energy it takes for a particle to reach infinity (i.e. where E =\n0) from where it\nstarts off. That makes it easy that we can write it from conservation\nof energy\n\\begin{equation}\n\\frac{mv_e^2}{2} + m\\Phi(r) = 0\n\\end{equation}\n\\begin{equation}\nv_e^2 = -2\\Phi(r)\n\\end{equation}\n\\subsubsection{Homogeneous Sphere}\nLet's look at some examples of spherical systems and see what their\npotentials are and how the systems might effect the behavior or\nparticles. The simplest is a homogeneous sphere. \n\\begin{equation}\n\\phi = const\n\\end{equation}\n\\begin{equation}\nM_{enc} = \\int_0^r 4\\pi r'^2 \\rho dr' = \\frac{4}{3} \\pi r^3 \\rho\n\\end{equation}\nThe total force is \n\\begin{equation}\nF(r) = - \\frac{GM(r)}{r^2} = - \\frac{4\\pi G\\rho}{3} r\n\\end{equation}\nThis is the differential equation for a harmonic oscillator. The core\nof a cluster can be approximated as such. Meaning\n\\begin{equation}\n\\ddot{r} = -\\omega^2r\n\\end{equation}\nWe get an equation for\n\\begin{equation}\n\\omega^2 = \\frac{4\\pi G}{3} \\rho\n\\end{equation}\nThe period of this oscillation is\n\\begin{equation}\nP = \\frac{2\\pi}{\\omega}  = \\sqrt{\\frac{3\\pi}{G\\rho}}\n\\end{equation}\nEach star has an oscillation. THe question now arises, if we have a\nKeplerian orbit, the period of the rotation is equal to the period of\nthe oscillation. Are these the same? No, see homework\n\n\\section{Dynamical Time}\nAt this point we have this timescale of a period. Let's define an\nimportant timescale that we encounter, which is the \\textbf{dynamical time} of\na system. It is defined as \n\\begin{equation}\nt_{dyn} = (\\frac{3\\pi}{16 G\\rho}) = P/4\n\\end{equation}\nThis is not dependent on our system\nWe can say in general\n\\begin{equation}\nt \\sim (G\\rho)^{1/2} \n\\end{equation}\nTHis corresponds to the time between the peak and the middle of an\noscillation, or the average to the furthest it'll go. This dynamical\ntime is the time that any given system or a particle within a stellar\nsystem will do something dramatic like cross the system. It is related\nintimately with the free-fall time. \n\n\\subsubsection{Back to Homogeneous Sphere}\nIf the radius of the homogeneous sphere b is interior to our radius\n(i.e. we're outside of the sphere) then it acts as a point mass\n\\begin{equation}\n\\Phi_{r <b} = -\\frac{GM_{tot}}{r}\n\\end{equation}\nIf radius is less than B. The potential needs to be written in two terms\nof to describe the potential, the first of which is r dependent and\nthe other which is r' dependent\n\\begin{equation}\n- G \\left[ \\frac{1}{r} \\frac{4\\pi\\rho r^3}{3} + \\int^b_3 4\\pi\\rho r'dr'\\right]\n\\end{equation}\nWhich can be written as \n\\begin{equation}\n-\\frac{GM_{tot}}{b} \\left[ \\frac{r^2}{b^2} + \\frac{3}{2} ( 1 -\n  \\frac{r^2}{b^2})\\right] = - \\frac{GM_{tot}}{b} \\left[ \\frac{3}{2} -\n  \\frac{r^2}{2b^2}\\right]\n\\end{equation}\nNow is this continuous at r=b. Yes, it's a quick check. Our choice of\nconstants was appropriate to ensure that the potential is\ncontinuous. \n\n\\subsubsection{Singular Isothermal Sphere}\nMeans that the energy distribution and so\n\\begin{equation}\n\\rho = \\rho_0 \\left(\\frac{r_0}{r}\\right)^2\n\\end{equation}\nCharacteristics of the isothermal sphere will not b e derived\n\\begin{equation}\nM(r) = \\int_0^r 4\\pi r^2 dr \\rho(r) = M_0 \\frac{r}{r_0}\n\\end{equation}\nIn this case\n\\begin{equation}\nM_0 = 4\\pi \\rho_0 r_0^3\n\\end{equation}\n\\begin{equation}\nv_c^2 = \\frac{GM(r)}{r} = const = \\frac{GM_0}{r_0}\n\\end{equation}\nThis implies that the circulal velocity is a cosntant with radius. so it has a flat rotation curvce. This tells us that the isothermal sphere is a good approximation for a galaxy.\n\n\\begin{equation}\n\\Phi(r) = -G[\\frac{1}{r} \\int_0^r 4\\pi \\rho(r') r'^2 dr + \\int^\\infty_r 4\\pi \\rho(r') r'^2 dr']\n\\end{equation}\nTHis is not an appropriate way to treat the isothermal sphere as the integral will not covnerge. It is more useful to look at differences in potential\n\\begin{equation}\n\\Phi(r) - \\Phi(r_0) = -G\\int_0^r \\frac{M(r')}{r'^2} dr = \\frac{GM_0}{r_0} \\int_{r_0}^r \\frac{dr'}{r'} = v_c^2 \\ln(r/r_0)\n\\end{equation}\n\n\\subsection{Plummer Model}\nWe're going to now start wiht a potential and try to work back to a density distribution. We know the potential for a point mass \n\\begin{equation}\n\\Phi(r) = -\\frac{GM}{r}\n\\end{equation}\nNow let's generalize that\n\\begin{equation}\n\\Phi(r) = -\\frac{GM}{\\sqrt{r^2 + b^2}}\n\\end{equation}\nThis makes it so that the potential converges at r = 0. B is some scale radius which tells us where the model goes from being roughly constant to looking like the point mass. We get the density distribution by invoking Poisson's equation\n\\begin{equation}\n\\nabla^2\\Phi = 4\\phi G\\rho\n\\end{equation}\nIn spherical coordinates\n\\begin{equation}\n\\frac{1}{r^2} \\frac{d}{dr} ( r^2 \\frac{d\\Phi}{dr})\n\\end{equation}\nThe result is \n\\begin{equation}\n4\\pi G\\rho = \\frac{3GMb^2}{(r^2 + b^2)^{3/2}}\n\\end{equation}\n\\begin{equation}\n\\rho(r) = \\frac{3M/4\\pi b^3}{(1+r^2/b^2)^{5/2}}\n\\end{equation}\nAs r goes to zero we get a constant density distrubtion\n\\begin{equation}\n\\frac{3M}{4\\pi b^3}\n\\end{equation}\nand r goes to infinity\n\\begin{equation}\n\\rho \\sim r^{-5}\n\\end{equation}\nThis is nice because the density falls off \nHowever, orbits cannot be described analytically in this model. A different model for this is the isochrone potential. \n\\begin{equation}\n\\Phi(r) = -\\frac{GM}{b + \\sqrt{b^2+r^2}}\n\\end{equation}\n\n\n\\section{Two-power density model}\n\\begin{equation}\n\\rho(r) = \\frac{\\rho_0}{(r/1)^{\\alpha} ( 1 + r/a)^{\\beta-\\alpha}}\n\\end{equation}\n\nLook up Dehnen models, Herquist model, Jaffe model, NFW\n\n\n\\subsection{Defionitions}\n\\subsubsection{Integrals of motion}\nFunction \n\\begin{equation}\nI(\\v{x}, \\v{v}) = I(\\v{x_0}, \\v{v_0}) \n\\end{equation}\nInviariant along the orbit of a particle. For energy conservation, it means that energy is an integral of motion. This is different from a constant of motion\n\\subsubsection{Constant of motion}\n\\begin{equation}\nC(\\v{x},\\v{v}, t) = C(\\v{x_o}, \\v{v_0},t)\n\\end{equation}\nAn example is that if we know the equations of motion we can determine at some specific time $t_0$ what the position must or will be in the future. So the three space cooordinates and three velocity coordinates are related to constants of motion that are determined by the constraints determined of the constants of motion. We are more interested in the integrals of motion\n\n\\section{Various Integrals of Motion}\nFor these purposes let us assume that the potential is static or invariant\n\\subsection{Energy}\nLet's consider the dot product between\n\\begin{equation}\n\\dot{r} \\cdot \\ddot{r} = -\\dot{r} \\cdot \\v{\\nabla} \\Phi\n\\end{equation}\n\\begin{equation}\n\\frac{d}{dt} (\\frac{1}{2} |\\dot{r}|^2) = \\frac{d\\Phi(r)}{dt}\n\\end{equation}\nOops.\n\n\n\\subsection{Energy}\nAssume spherically symmetric\n\\begin{equation}\n\\Phi = \\Phi(r)\n\\end{equation}\n\\begin{equation}\n\\ddot{r} = F(r) \\uv{r}\n\\end{equation}\n\\begin{equation}\n\\v{r}\\times \\v{F} = 0 = \\v{r} \\times \\v{\\ddot{r}}\n\\end{equation}\n\\begin{equation}\n\\frac{d}{dt} (\\v{r} \\v{\\dot{r}}) = 0\n\\end{equation}\nSo we get three conservations\n\\begin{equation}\n\\v{L} = \\v{r}\\times \\v{v}\n\\end{equation}\n\nLessing this to axisymmetric, we know that the symmetry that we can work with is the azimuthal angle $\\phi$.\n\\begin{equation}\n\\frac{\\pd \\Phi}{\\pd \\phi} = 0\n\\end{equation}\nMeans that phi is conserved\n\n\\section{Fuckballsacks}\n\n\\begin{equation}\n\\v{r} = r\\uv{r}\n\\end{equation}\nUnit vector shit\nSee classical notes. \n\n\n\n\\end{document}\n", "meta": {"hexsha": "a2bad7c45b69a92698e36706d4c30b8235541399", "size": 14638, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "astrodynamics/lec01-02.tex", "max_stars_repo_name": "paulinearriaga/phys-ucla", "max_stars_repo_head_hexsha": "48084dbbac2f8a4748c1fdaaf63a4cebaae16809", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "astrodynamics/lec01-02.tex", "max_issues_repo_name": "paulinearriaga/phys-ucla", "max_issues_repo_head_hexsha": "48084dbbac2f8a4748c1fdaaf63a4cebaae16809", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "astrodynamics/lec01-02.tex", "max_forks_repo_name": "paulinearriaga/phys-ucla", "max_forks_repo_head_hexsha": "48084dbbac2f8a4748c1fdaaf63a4cebaae16809", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.103117506, "max_line_length": 373, "alphanum_fraction": 0.7145784943, "num_tokens": 4905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.30432497759345306}}
{"text": "﻿\\chapter{Attention Mechanism}\r\n\\section{Introduction}\r\nIn this section, we will focus on the deep learning models, the first one being a bidirectional LSTM and the second one an attention layer is added to this LSTM. But it is need to use another text embedding in order to work with LSTM. Indeed, tf-idf create a sparse matrix with each row corresponding to a value for a given word. This means that the order of the words are lost. In order to solve this, word2vec\\cite{Mikolov2013} is used. It allows matching words to continuous vectors of a given size with interesting properties. Another method, which consists in making word embedding as tuning parameters will be used.\r\n\\section{Text to Vectors}\r\n\\subsection{Word2Vec}\r\nWord2Vec comes in two fashions: continuous bag of words (CBOW) and skip gram. It is originally designed to predict a word given a context. For instance, given two previous words and the next two words, which word is the most likely to take place between them. But it appears that the hidden representation of these words works well as word embedding and has very interesting properties such that words with similar meaning have similar vector representation. It is also possible to perform arithmetic that captures information such as singular, plural or even capital and countries. For example, we have that $dog - dogs \\approx cat - cats$ but also $Paris - France \\approx Berlin - Germany$. \\\\\r\n\r\nIt is possible to visualize these relationships by using t-SNE for projecting high dimensions word vectors in 2D space. The results of various relationships can be seen at \\textbf{Figure \\ref{fig:chap4:word2vec}}.\r\n\\begin{figure*}\r\n \\centering\r\n \\includegraphics[width=\\textwidth]{images/chapitre4/linear-relationships}\r\n \\caption{Relationships between different words with t-SNE dimensionality reduction. }\r\n \\label{fig:chap4:word2vec}\r\n\\end{figure*}\r\n\\subsubsection{How does it work?} \r\nAs the original authors did not intend this kind of result, Xin Rong\\cite{Rong2014} did a good job explaining how it works. \r\nLet V be the size of the vocabulary and that there is only one word in the CBOW model, it give \\textbf{Figure \\ref{fig:chap4:CBOW}} models. \r\n\\begin{figure*}\r\n \\centering\r\n \\includegraphics[width=\\textwidth]{images/chapitre4/CBOW}\r\n \\caption{A simple CBOW model with only one word in the context}\r\n \\label{fig:chap4:CBOW}\r\n\\end{figure*}\r\nEach word is encoded as a one-hot vector of size V. That means that it is a sparse vector full of zeros except for the position assigned to that word which is one. The hidden layer is computed as \r\n\\begin{equation}\r\n \\mathbf{h} = \\mathbf{W^Tx}\r\n\\end{equation}\r\nWhere $\\mathbf{W^{V \\times N}}$ is the weight matrix to optimize over. \r\nThe output layer values are computed as \r\n\\begin{equation}\r\n \\mathbf{Y} = \\mathbf{W'^Th}\r\n\\end{equation}\r\nAs before $\\mathbf{W'^{N \\times V}}$ is also a weight matrix to optimize. The loss can be computed as softmax cross entropy. \\\\\r\n\r\nIt is also possible to make the opposite: predicting the context given a single input word. This is the skip-gram model. In this case the loss becomes \\textbf{Equation \\ref{eq:loss}}.\r\n\\begin{equation}\r\n E = - \\sum_{c=1}^C u_{j^*_c} + C \\cdot \\sum_{j' = 1}^V \\exp(u_{j'}) \\ \\label{eq:loss}\r\n\\end{equation}\r\n$j_c^*$ is the index of the cth output context word and $u_{j^*_c}$ is the score of the jth word in the vocabulary for the cth context word. Finally, the embedding that is used are the value of the hidden layers produced for a given word. \r\n\\begin{figure*}\r\n \\centering\r\n \\includegraphics[width=\\textwidth]{images/chapitre4/skip-gram}\r\n \\caption{Skip-gram model with multiple outputs.}\r\n \\label{fig:chap4:skip-gram}\r\n\\end{figure*}\r\n\\section{LSTM}\r\nLSTM or Long Short Term Memory\\cite{Hochreiter1997LongSM} is a kind of recurrent neural network that fits well to temporal or sequential input such as texts. A RNN is a type of neural network where the hidden state is fed in a loop with the sequential inputs. There are usually shown as unrolled version of it (\\textbf{Figure \\ref{fig:chap4:RNN_unroll}}). Each of the $X_i$ being one value in the sequence.\\\\\r\n\r\nIn this case, $X_i$ values are word vectors. There are two possibilities, either use pre-trained vector with word2vec or make $X_i$ inputs a parameter to learn in the same way as it works for the Word2Vec algorithm, having a one-hot encoding of the word and a matrix of weights to tune. Each method will be used. \\\\\r\n\r\nRecurrent Neural Networks do not works very well with long-term dependencies, that is why LSTM have been introduced. It is made of an input gate, an output gate and a forget gate that are combined in \\textbf{Equation \\ref{eq:LSTM}}.\r\n\\begin{figure}\r\n \\centering\r\n \\includegraphics[width=\\textwidth]{images/chapitre4/RNN-unrolled.png}\r\n \\caption{Unrolled RNN (Understanding LSTM Networks, \\url{https://colah.github.io/posts/2015-08-Understanding-LSTMs/)}}\r\n \\label{fig:chap4:RNN_unroll}\r\n\\end{figure} \r\n\\begin{align} \\label{eq:LSTM}\r\n f_t &= \\sigma_g(\\mathbf{W}_f x_t + \\mathbf{U}_fh_{t-1} + b_f)\\\\\r\n i_t &= \\sigma_g(\\mathbf{W}_i x_t + \\mathbf{U}_ih_{t-1} + b_i)\\\\\r\n o_t &= \\sigma_g(\\mathbf{W}_o x_t + \\mathbf{U}_oh_{t-1} + b_o)\\\\\r\n c_t &= f_t \\circ c_{t-1} + i_t \\circ \\sigma_c(\\mathbf{W}_cx_t + \\mathbf{U}_c h_{t-1} + b_c)\\\\\r\n h_t &= o_t \\circ \\sigma_h (c_t)\r\n\\end{align}\r\n\\textbf{Figure \\ref{fig:chap4:LSTM-gates}} shows how it works.\r\n\\begin{figure}\r\n \\centering\r\n \\includegraphics[width=0.6\\textwidth]{images/chapitre4/LSTM1.jpeg}\r\n \\caption{LSTM gates, \\\\ \\url{https://hackernoon.com/understanding-architecture-of-lstm-cell-from-scratch-with-code-8da40f0b71f4)}}\r\n \\label{fig:chap4:LSTM-gates}\r\n\\end{figure} \r\nA bidirectional LSTM works the same way, but the input is fed in the two directions, from the start to the end and from the end to the start.\r\n\\section{Attention Mechanism}\r\nAttention mechanism\\cite{zhou-etal-2016-attention,Vaswani2017AttentionIA} adds an extra layer between LSTM outputs and the final output of the network. It merges word-level features into sentence features using a weight vector. \\\\\r\n\r\n\\begin{figure}\r\n \\centering\r\n \\includegraphics[width=\\textwidth]{images/chapitre4/attention.png}\r\n \\caption{Bidirectional LSTM Model With Attention}\r\n \\label{fig:chap4:attention}\r\n\\end{figure}\r\nOutputs sequence of the LSTM is summed element-wise in order to merge them. We have that $h_i = [\\overrightarrow{h_i} + \\overleftarrow{h_i}]$, $\\overrightarrow{h_i}$ and $\\overleftarrow{h_i}$ begin the outputs i of sequence in each direction as show at \\textbf{Figure \\ref{fig:chap4:attention}}.\\\\\r\nLet’s $H$ be a matrix of the concatenation of all the $h_i$, \r\n\\begin{equation}\r\n H = [h_1,h_2,...,h_T]\r\n\\end{equation}\r\nWhere T is the sequence length. \r\nThen we define \r\n\\begin{align}\r\n M &= \\tanh(H)\\\\\r\n \\alpha &= softmax(w^TM) \\\\\r\n r &= H \\alpha^T \r\n\\end{align}\r\nFinally, we compute $h^* = \\tanh(r)$.\r\nFor the classification, it uses a softmax classifier as $\\hat{p}(y|S) = softmax(W^Sh^* + b)$. Originally the loss function is the negative log likelihood, but as in this case it is a binary classification I used binary cross entropy. \r\n\\section{Results}\r\n\\subsection{Methodology}\r\nIn order to train the models and perform hyper parameters optimization grid search have been used when it was possible (on the liar-liar dataset) and knwoleadge acquired there have been used in order to tune parameters for the networks on the \\textbf{Fake News Corpus}. In addition, in order to find the best parameters among all tested with gird search, for each metric, the training epochs having the highest validation value for those metrics have been chosen. \\\\\r\n\r\nAll the models have been trained using adam optimizer and initialized using a normal distribution for the weights. \\\\\r\n\r\nAs SMOTE cannot be used on the \\textbf{Fake News Corpus} dues to the size of the corpus, in order to rebalance the dataset the minority class have been over sampled by feeding multiple times the same input by looping through them. \r\n\\subsection{Liar-Liar dataset results}\r\nAs explained earlier, both models have been trained using different embedding: the first one being pre-trained word2vec vectors of size 300 and the second one being a tunable parameter with different embedding size.\r\n\\subsubsection{LSTM}\r\nWhen it comes to LSTM trained on liar-liar dataset, it simply does not works. It classifies almost all the texts as being from the same class. Although, it reaches a good score on the training data, it does not manage to generalize correctly. \\textbf{Figure \\ref{fig:chap4:lstm2}} shows the recall, precision and f1-score and loss for training and testing set of the best models for the LSTM using word2vec. We can see that even if the training score increase, the testing values oscillate. \\\\\r\n\r\n\\begin{figure}\r\n \\centering\r\n \\includegraphics[width=\\textwidth]{images/chapitre4/lstm2}\r\n \\caption{Best LSTM With word2vec}\r\n \\label{fig:chap4:lstm2}\r\n\\end{figure}\r\nWhen training the models with word embedding as tunable parameters, the results slightly improve, with an average precision between $55\\%$ and $60\\%$. This can be seen at \\textbf{Figure \\ref{fig:chap4:lstm1}}. \\\\\r\nThe training was stopped after 200 iterations because the validation score was not improving anymore. \r\n\\begin{figure}\r\n \\centering\r\n \\includegraphics[width=\\textwidth]{images/chapitre4/lstm1}\r\n \\caption{Best LSTM with word embedding as tunable parameters.}\r\n \\label{fig:chap4:lstm1}\r\n\\end{figure}\r\n\r\n\\subsection{Attention Mechanism}\r\nWe could think that adding an extra layer to such a bad model would not make any improvement and be useless, but adding an attention layer does improve a little the results. When using word2vec embedding, the best epoch reaches up to $62.9595\\%$ of average accuracy, which is better than the simple LSTM. Because there are a lot of models with different parameters, it is interesting to look at the distribution of the results for the best epochs by fixing parameters one by one. \\textbf{Figure \\ref{fig:chap4:att1:confInt}} shows the $95\\%$ confidence interval for precision for a fixed parameter. \\\\\r\n\\begin{figure}\r\n \\centering\r\n \\includegraphics[width=\\textwidth]{images/chapitre4/confInt_precision_liar_attention_word2vec}\r\n \\caption{Confidence Interval of Precision for Each Parameter Value}\r\n \\label{fig:chap4:att1:confInt}\r\n\\end{figure}\r\nIt shows that it is better to use fewer hidden units in the model, and only a single layer. The sequence length has a very small impact on the precision. Actually, the best model uses a sequence length of 20. \\\\\\\r\nThe precision of the different models range from $53\\%$ to $63\\%$ (\\textbf{Figure \\ref{fig:chap4:att1:distPrecision}}.)\r\n\\begin{figure}\r\n \\centering\r\n \\includegraphics[width=\\textwidth]{images/chapitre4/distplot_precision_liar_attention_word2vec}\r\n \\caption{Distribution of the precision of best epochs for all the models trained with word2vec embedding.}\r\n \\label{fig:chap4:att1:distPrecision}\r\n\\end{figure}\r\nThe training plot of the model that reaches the maximum precision can be seen at \\textbf{figure \\ref{fig:chap4:att1:train}}. It shows that after the 25th iteration, the validation values start to decrease, which is a sign of overfitting. \\\\\r\n\r\n\\begin{figure}\r\n \\centering\r\n \\includegraphics[width=\\textwidth]{images/chapitre4/attention1}\r\n \\caption{Training and validation of the model with top precision trained with word2vec embedding.}\r\n \\label{fig:chap4:att1:train}\r\n\\end{figure}\r\nFinally, there is the models where the embedding is a tunable parameter. The \\textbf{Figure \\ref{fig:chap4:att3:confInt2}} shows that in this case, the longer the sequence the better, and that as before using few hidden units perform better. In this case, variation has a wider range than when using word2vec. \r\n\\begin{figure}\r\n \\centering\r\n \\includegraphics[width=\\textwidth]{images/chapitre4/confInt_precision_liar_attention_200}\r\n \\caption{Training and Validation of the Model With top Precision}\r\n \\label{fig:chap4:att3:confInt2}\r\n\\end{figure}\r\nThere are a few models that have top precision higher than $75\\%$, but looking at the training plot (\\textbf{Appendix \\ref{Appendix2}, Figure \\ref{appendix2:training_plot1}}) shows that the model does not perform well. Because in particular case precision in not a good indicator of how well a model perform, f1-score will be used instead, as it is a balance between precision and recall. \\\\\r\nAnd the best f1-score obtained is $0.55384$, which is quite smaller than the $0.63$ for the model using word2vec. The training plot is at \\textbf{Figure \\ref{fig:chap4:att3:f1}}. We can see that there is still room for improvement, the next step is to see what happens when training on more epochs. \\\\\r\n\r\n\\begin{figure}\r\n \\centering\r\n \\includegraphics[width=\\textwidth]{images/chapitre4/attention-f1}\r\n \\caption{Training and validation of the model with top f1-score}\r\n \\label{fig:chap4:att3:f1}\r\n\\end{figure}\r\nTraining on 1000 epochs rather than 200 does not improve validation score, but it does for training (\\textbf{Figure \\ref{fig:chap4:att3:f1.1}}). \\\\\r\n\\begin{figure}\r\n \\centering\r\n \\includegraphics[width=\\textwidth]{images/chapitre4/attention3}\r\n \\caption{Training on 1000 epochs rather than 200}\r\n \\label{fig:chap4:att3:f1.1}\r\n\\end{figure}\r\n\\subsection{Result Analysis}\r\nThe previous section shows a few things\r\n\\begin{itemize}\r\n \\item LSTMs do not work well,\r\n \\item Adding attention layer improve LSTM results,\r\n \\item Using word2vec rather than training the embedding gives better results.\r\n\\end{itemize}\r\nIt also shows that despite reaching a very good precision, recall and f1-score on the training set it does not perform well on the validation set. This is a sign of overfitting. In order to avoid this, multiple methods have been applied without showing any improvement. \\\\\r\n\r\nThe following methods have been applied: \r\n\\begin{itemize}\r\n \\item Dropout\\cite{srivastava2014dropout}, \r\n \\item batch-normlaziation\\cite{Ioffe2015},\r\n \\item reducing network capacity (fewer hidden layers, lower embedding dimensions, less training parameters with word2vec),\r\n \\item Early stopping of training.\r\n\\end{itemize}\r\nThe highest gain was from using word2vec embedding. This significantly reduces the amount of training parameters, secondly dropout also helped a little. \r\n\\subsection{Testing}\r\nThe same way as in \\textbf{Chapter \\ref{chap3}}, the models will be trained on the parameters that produced the best results on the training set, and trained on training and validation set, and tested on testing set. \\\\\r\nThe parameters used for training are given at \\textbf{Table \\ref{table:chap4:param}}.\r\n\\begin{table}[h]\r\n \\begin{tabular}{|c|ccccc|}\r\n \\hline\r\n model & embedding size & Sequence Length & num hiddens & dropout & Early Stop\\\\\r\n \\hline\r\n LSTM & 300 & 10 & 50 & 0.75 & 126\\\\\r\n LSTM + word2vec & 300 & 10 & 50 & 0.0 & 160\\\\\r\n Attention & 10 & 20 & 10 & 0.75 & 400\\\\\r\n Attention + word2vec & 300 & 20 & 5 & 0.75 & 25\\\\\r\n \\hline\r\n \\end{tabular}\r\n \\caption{Parameters used for training}\r\n \\label{table:chap4:param}\r\n\\end{table}\r\nThe results for all four models are given at \\textbf{Table \\ref{table:chap4:results}}. It shows that the model that works the best is attention network using word2vec embedding, with an accuracy of $61\\%$, which is equivalent to ridge classifiers and linear svm. The three other models do not perform well, all having a average precision around $55\\%$, which is close to being a random classifier. \r\n\\begin{table}\r\n\\centering\r\n\\begin{subtable}{\\textwidth}\r\n\\begin{tabular}{lrrrrr}\r\n\\toprule\r\n{} &         fake &     reliable &  accuracy &    macro avg &  weighted avg \\\\\r\n\\midrule\r\nf1-score  &     0.440574 &     0.649551 &  0.569061 &     0.545062 &      0.558340 \\\\\r\nprecision &     0.508274 &     0.599526 &  0.569061 &     0.553900 &      0.559698 \\\\\r\nrecall    &     0.388788 &     0.708683 &  0.569061 &     0.548736 &      0.569061 \\\\\r\nsupport   &  1106.000000 &  1428.000000 &  0.569061 &  2534.000000 &   2534.000000 \\\\\r\n\\bottomrule\r\n\\end{tabular}\r\n\\caption{Simple LSTM}\r\n\\end{subtable}\r\n\\begin{subtable}{\\textwidth}\r\n \\begin{tabular}{lrrrrr}\r\n \\toprule\r\n {} &         fake &     reliable &  accuracy &    macro avg &  weighted avg \\\\\r\n \\midrule\r\n f1-score  &     0.481724 &     0.623040 &  0.563536 &     0.552382 &      0.561361 \\\\\r\n precision &     0.500000 &     0.606906 &  0.563536 &     0.553453 &      0.560245 \\\\\r\n recall    &     0.464738 &     0.640056 &  0.563536 &     0.552397 &      0.563536 \\\\\r\n support   &  1106.000000 &  1428.000000 &  0.563536 &  2534.000000 &   2534.000000 \\\\\r\n \\bottomrule\r\n \\end{tabular}\r\n \\caption{LSTM + word2vec}\r\n\\end{subtable}\r\n\\begin{subtable}{\\textwidth}\r\n\\begin{tabular}{lrrrrr}\r\n\\toprule\r\n{} &         fake &     reliable &  accuracy &    macro avg &  weighted avg \\\\\r\n\\midrule\r\nf1-score  &     0.486636 &     0.615597 &  0.560379 &     0.551116 &      0.559310 \\\\\r\nprecision &     0.496241 &     0.606803 &  0.560379 &     0.551522 &      0.558546 \\\\\r\nrecall    &     0.477396 &     0.624650 &  0.560379 &     0.551023 &      0.560379 \\\\\r\nsupport   &  1106.000000 &  1428.000000 &  0.560379 &  2534.000000 &   2534.000000 \\\\\r\n\\bottomrule\r\n\\end{tabular}\r\n\\caption{Attention network}\r\n\\end{subtable}\r\n\\begin{subtable}{\\textwidth}\r\n\\begin{tabular}{lrrrrr}\r\n\\toprule\r\n{} &         fake &     reliable &  accuracy &    macro avg &  weighted avg \\\\\r\n\\midrule\r\nf1-score  &     0.511397 &     0.676721 &  0.610892 &     0.594059 &      0.604563 \\\\\r\nprecision &     0.565789 &     0.636252 &  0.610892 &     0.601021 &      0.605497 \\\\\r\nrecall    &     0.466546 &     0.722689 &  0.610892 &     0.594618 &      0.610892 \\\\\r\nsupport   &  1106.000000 &  1428.000000 &  0.610892 &  2534.000000 &   2534.000000 \\\\\r\n\\bottomrule\r\n\\end{tabular}\r\n\\caption{Attention Network + word2vec}\r\n\\end{subtable}\r\n\\caption{Results for the differents models trained with parameters given at \\textbf{Table \\ref{table:chap4:param}}.}\r\n\\label{table:chap4:results}\r\n\\end{table}\r\n\\section{Attention Mechanism on fake news corpus}\r\n\\subsection{Model Selection}\r\nThe two models using word2vec embedding have shown to work better than their counterparts, this why only these two methods will be tested on \\textbf{Fake News Corpus} for comparison as very good results have already been obtained. \\\\\r\n\r\nIt shows out that in this case LSTMs works better than Attention Mechanism, but as in previous section does not reach machine learning results. \\\\\r\n\r\nThe best LSTM obtained use sequence of 200 words and 200 hidden layers, with an average precision of $0.929376$ on the validation set. The training plots of this particular model are shown at \\textbf{Figure \\ref{chap4:fig:lstm5.1}}.\\\\\r\n\\begin{figure*}\r\n \\centering\r\n \\includegraphics[width=\\textwidth]{images/chapitre4/lstm5}\r\n \\caption{Training plots of the best LSTM using word2vec embedding.}\r\n \\label{chap4:fig:lstm5.1}\r\n\\end{figure*} \r\n\r\nIn the case of attention mechanism, training on the \\textbf{Fake News Corpus} has shown to be harder than on the \\textbf{Liar-Liar Corpus} as using too large learning rate would lead to oscillating loss and too small learning rate lead to halting the loss decrease. This can be seen at \\textbf{Appendix \\ref{appendix2:training_plot2}}. \\\\\r\n\r\nThe same parameters as for the LSTM will be used for training the Attention Network. Its training plot is available at \\textbf{Figure \\ref{chap4:fig:attention5}}.\r\n\\begin{figure*}\r\n \\centering\r\n \\includegraphics[width=\\textwidth]{images/chapitre4/attention5}\r\n \\caption{Training plots of the best attention network using word2vec embedding.}\r\n \\label{chap4:fig:attention5}\r\n\\end{figure*} \r\nThe final results are given at \\textbf{Table \\ref{table:chap4:results2}}. It shows that for the same parameters LSTM works better than Attention Network on this particular dataset. It shows that LSTM place below Linear SVM and Ridge Classifier and above Decision Tree and Na\\\"{i}ve-Bayes in terms of accuracy. \r\n\\begin{table}\r\n \\begin{subtable}{\\textwidth}\r\n  \\begin{tabular}{lrrrrr}\r\n  \\toprule\r\n  {} &          fake &      reliable &  accuracy &     macro avg &  weighted avg \\\\\r\n  \\midrule\r\n  f1-score  &      0.856568 &      0.947577 &  0.923217 &      0.902073 &      0.924724 \\\\\r\n  precision &      0.806655 &      0.969503 &  0.923217 &      0.888079 &      0.928611 \\\\\r\n  recall    &      0.913066 &      0.926621 &  0.923217 &      0.919843 &      0.923217 \\\\\r\n  support   &  17496.000000 &  52181.000000 &  0.923217 &  69677.000000 &  69677.000000 \\\\\r\n  \\bottomrule\r\n  \\end{tabular}\r\n  \\caption{LSTM + word2vec results on \\textbf{Fake News Corpus}}\r\n \\end{subtable}\r\n \\begin{subtable}{\\textwidth}\r\n  \\begin{tabular}{lrrrrr}\r\n  \\toprule\r\n  {} &      reliable &          fake &  accuracy &     macro avg &  weighted avg \\\\\r\n  \\midrule\r\n  f1-score  &      0.850296 &      0.687493 &  0.797566 &      0.768894 &      0.809416 \\\\\r\n  precision &      0.952876 &      0.561344 &  0.797566 &      0.757110 &      0.854562 \\\\\r\n  recall    &      0.767655 &      0.886774 &  0.797566 &      0.827215 &      0.797566 \\\\\r\n  support   &  52181.000000 &  17496.000000 &  0.797566 &  69677.000000 &  69677.000000 \\\\\r\n  \\bottomrule\r\n  \\end{tabular}\r\n  \\caption{Attention Network + word2vec on \\textbf{Fake News Corpus}}\r\n \\end{subtable}\r\n \\caption{Final result on testing set for LSTM and attention network using word2vec.}\r\n \\label{table:chap4:results2}\r\n\\end{table}\r\nIt is likely to be possible to reach results as well as LSTM or even better for the Attention Network, but due to technical and time constraints I was not able to experiment further. For instance, using longer sequence length and more hidden units with a smaller learning rate might have overcome this problem. \r\n\\section{Conclusion}\r\nIn this chapter I have investigated how state-of-the-art deep learning models work on fake news detection, and it shows that for the particular case of fake news detection it does not outperform traditional machine learning methods. I have also made some addition to the original model that improves the performances by a few percent by replacing the tunable word embedding by constant one using word2vec. It shows out that it helps reduce overfitting and increase result on the testing set. \\\\\r\n\r\nA hypothesis to explain why these two deep learning methods do not works as well as machine learning methods is the fact that in this case text are required to be the same size. Which means that some of them require some padding and the other are srunk. In the second case, information is lost. \\\\\r\n\r\nIn addition, it shows that \\textbf{Liar-Liar Corpus} is hard to work on, with $60\\%$ precision, when \\textbf{Fake News Corpus} still have good results. ", "meta": {"hexsha": "16ab9351d4abf2d762bbb524a16649d10bb72133", "size": 22590, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "reviews/final/chapter4.tex", "max_stars_repo_name": "SimonKenoby/Master-Thesis-Fake-News-Dectection", "max_stars_repo_head_hexsha": "2c3a5e82d4c7d6294ca87c265a1b638d61f2cb08", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-06-04T22:39:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T08:15:14.000Z", "max_issues_repo_path": "reviews/final/chapter4.tex", "max_issues_repo_name": "SimonKenoby/Master-Thesis-Fake-News-Dectection", "max_issues_repo_head_hexsha": "2c3a5e82d4c7d6294ca87c265a1b638d61f2cb08", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-22T12:00:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-24T19:09:04.000Z", "max_forks_repo_path": "reviews/final/chapter4.tex", "max_forks_repo_name": "SimonKenoby/Master-Thesis-Fake-News-Dectection", "max_forks_repo_head_hexsha": "2c3a5e82d4c7d6294ca87c265a1b638d61f2cb08", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 70.1552795031, "max_line_length": 696, "alphanum_fraction": 0.732226649, "num_tokens": 6352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.304324977593453}}
{"text": "\\chapter{6. Vehicle and Control Tests}\n\nIn this chapter the control strategy is applied to the real scale PEV and an stability and robustness analysis is presented as well. Due to the possibility of controlling the PEV remotely (through the Bluetooth module and the Android app) two models were studied simultaneously. After the proper analysis and validation in MATLAB, the control strategy was implemented in the Arduino boards and the PEV was tested several times. Here the results of these tests are presented.\n\n\\section{Control Strategy Analysis}\n\nThe control strategy works in parallel with the dynamic model of the vehicle. It receives the sensor data as inputs; that information, along with with the gains and the actual speed of the vehicle, gives result to the output signal $M_{t}$ that tilts the vehicle.\n\nRegarding the sensors, the rotary encoder in the rear wheel and the pair of inertial motion units provide the necessary data. The longitudinal speed given by the rotary encoder is used to calculate the gains of the model as well. The actuated motor is the tilting NIDEC motor, since the steering motor only responses to the driver's inputs and the handle bar motor only does the haptic feedback to the driver.\n\n\\begin{figure}[!h]\n\t\\includegraphics[width=1\\linewidth]{figs/06/strategy3}\n\t\\caption{Workflow of the control strategy: input from IMU and output to tilting actuator}\n\t\\label{strategy}\n\\end{figure}\n\n\\newpage\n\\subsection{Model Parameters}\n\nTo calculate the gains of the control strategy it is first needed to obtain or measure the \\textbf{parameters to complete the dynamic model}. This includes the vehicle and the wheels variables: \n\n$\\hspace{2cm} m \\enspace L_{f} \\enspace L_{r} \\enspace I_{x} \\enspace I_{z} \\enspace C_{f} \\enspace C_{r} \\enspace \\lambda_{f} \\enspace \\lambda_{r} \\enspace ...$.\n\nTherefore, the model presented in Chapter 3 needs to be calculated for the PEV characteristics. Both the vehicle with and without the driver were modelled in CAD software (Solidworks). By indicating the material of each body the necessary properties for the control model were extracted.\n\nThe geometrical parameters -- $h \\enspace L_{f} \\enspace L_{r} \\enspace R_{wf}\\enspace R_{wr}\\enspace b$ -- were measured directly from the model. The dynamic parameters -- $m \\enspace I_{x} \\enspace I_{z} \\enspace ...$ --, on the other side, were extracted from the mass properties.\n\n\\begin{table*}[h!]\n\\centering\n\t\\begin{tabular}{l|cc|l|l}\n\t%\\hline\n\t\\textbf{Name}      &  \\textbt{\\begin{tabular}[c]{@{}l@{}}Driver\\\\ included\\end{tabular}} & \\textbt{\\begin{tabular}[c]{@{}l@{}}No driver\\\\ included\\end{tabular}}   & \\textbf{Units}         & \\textbf{Description}                                   \\\\\n\t\\hline\n\t$m$                  & 115                       & 35                          & kg                     & Total mass of the vehicle                              \\\\\n\t$h$                 & 0.91                      & 0.36                        & m                      & Position of the center of gravity G on the z axis      \\\\\n\t$L_f$                & 0.718                     & 0.518                       & m                      & Distance from center of gravity to front axle          \\\\\n\t$L_r$               & 0.61                      & 0.81                        & m                      & Distance from center of gravity to rear axle           \\\\\n\t$m_f$               & 52.82                     & 21.35                       & kg                     & Mass supported by the front wheels                     \\\\\n\t$m_r$                & 62.18                     & 13.65                       & kg                     & Mass supported by the rear wheel                       \\\\\n\t$I_x$               & 25.14                     & 4.00                        & kg m^2\t\t\t\t  & Vehicle roll moment of inertia                         \\\\\n\t$I_z$                & 17.8                      & 10.93                       & kg m^2\t\t\t\t  & Vehicle yaw moment of inertia                          \\\\\n\t$I_{wheel\\,f\\,\\theta}$ & 0.05                      & 0.05                        & kg m^2\t\t\t\t  & Tilting inertia of each front wheel about its own axis \\\\\n\t$I_{wheel\\,f\\,rot}$  & 0.11                      & 0.11                        & kg m^2\t\t\t\t  & Inertia of each front wheel about its rotating axis    \\\\\n\t$I_{wheel\\,f\\,\\phi}$ & 0.05                      & 0.05                        & kg m^2\t\t\t\t  & Yaw inertia of each front wheel about its own axis     \\\\\n\t$I_{wheel\\,r\\,\\theta}$ & 0.16                      & 0.16                        & kg m^2\t\t\t\t  & Tilting inertia of the rear wheel about its own axis   \\\\\n\t$I_{wheel\\,r\\,rot}$  & 0.32                      & 0.32                        & kg m^2\t\t\t\t  & Inertia of the rear wheel about its rotating axis      \\\\\n\t$I_{wheel\\,r\\,\\phi}$ & 0.16                      & 0.16                        & kg m^2\t\t\t\t  & Yaw inertia of the rear wheel about its own axis       \\\\\n\t$R_{w\\,f}$          & 0.218                     & 0.218                       & m                      & Front wheel radius                                     \\\\\n\t$R_{w\\,r}$           & 0.315                     & 0.315                       & m                      & Rear wheel radius                                      \\\\\n\t$F_{z\\,f}$          & 259.10                    & 104.71                      & N                      & Vertical reaction in each front wheel                  \\\\\n\t$F_{z\\,r}$          & 609.95                    & 133.93                      & N                      & Vertical reaction in the rear wheel                    \\\\\n\t$C_f$               & 7277.45                   & 2690.05                     & N/rad                  & Cornering stiffness of each front wheel                \\\\\n\t$C_r$               & 20454.62                  & 3501.36                     & N/rad                  & Cornering stiffness of the rear wheel                  \\\\\n\t$\\lambda_f$          & 231.90                    & 79.70                       & N/rad                  & Camber stiffness of each front wheel                   \\\\\n\t$\\lambda_r$          & 731.44                    & 105.33                      & N/rad                  & Camber stiffness of the rear wheel                     \\\\\n\t$b$                  & 0.92                      & 0.92                        & m                      & Width of the vehicle in the base                       \\\\\n\t$M_{max}$            & 518.949                   & 157.941                     & Nm                     & Maximum tilt torque before rolling over    \t\t\t   \\\\\n\t%\\hline\n\t\\end{tabular}\n\t\\\\[20pt]\n\t\\caption{PEV parameters extracted from Solidworks model}\n\\end{table*}\n\n\\subsection{Driver Modelling}\n\n\\begin{marginfigure}[5cm]\n\t\\includegraphics[width=1\\linewidth]{figs/06/driver}\n\t\\caption{Driver model in the PEV}\n\\end{marginfigure}\nThe driver was modeled as a 80kg person seated and in driving position. Due to the location of the body, the center of gravity and the moments of inertia changed considerably. The variability in the weight and the position of the driver will be overcome by the uncertainly analysis presented below.\n\n\\subsection{Tire Stiffness}\n\nIn regards to the tires, the stability and handling depends strongly on the tire properties -- cornering stiffness and camber stiffness. Mathematical models are available to predict vehicle handling. However, very little data is available on properties of bicycle and tricycle tires currently on the market.\n\nIn Windes et. al., 2013\\cite{windes2013experimental}, the authors focus on the experimental determination of the cornering and camber stiffness of several different\ntypes of bicycle and tricycle tires. Indeed, they designed and built an machine for measuring cornering and camber stiffness using the back-to-back method. In this way, the cornering and camber stiffness were obtained over a range of vertical loads.\n\nKnowing the mass balance of the PEV -- $m_{f} \\enspace m_{r}$ -- , the vertical loads of each wheel were estimated: $F_{z\\,f} \\enspace F_{z\\,r}$. Then, using the quadratic relationships presented in Windes et. al., the cornering and camber stiffness were obtained.\n\nThe PEV is mounting a Continental Grand Prix 4000 SII tire, which is not modeled in the mentioned paper. Nevertheless, an average estimation from those selected tires was calculated and the relation between the stiffness and the vertical load was estimated for this tire: \\[C=\\frac{F_{z}^2}{3690}+\\frac{F_{z}}{2.38} \\quad\\quad \\lambda=\\frac{F_{z}^2}{66085}+\\frac{F_{z}}{85.47}\\] \n\\begin{figure*}[b]\n\t\\includegraphics[width=0.95\\linewidth]{figs/06/tire}\n\t\\caption{Cornering and camber stiffness in function of the vertical load}\n\t\\\\[-1cm]\n\\end{figure*}\n\\newpage\n\n\\subsection{Simulink Model}\n\nThe control strategy stability and robustness was studied in MATLAB and Simulink. The model is illustrated in Figure \\ref{model}.\n\n\\begin{figure*}[!h]\n\t\\includegraphics[width=1\\linewidth]{figs/06/model}\n\t\\caption{Simulink model}\n\t\\label{model}\n\\end{figure*}\n\\begin{marginfigure}[5cm]\n\t\\includegraphics[width=1.2\\linewidth]{figs/06/control2}\n\t\\caption{Control strategy schematic}\n\\end{marginfigure}\nThe steering input from the driver is include as a disturbance in the system, whose effect on the perceived lateral acceleration $a_{per}$ should be canceled by the tilt torque $M_{t}$. This fact is taken into account with the feedforward gains $K_{d}=\\Big[K_{\\delta} \\quad K_{\\dot{\\delta}}\\Big]^{T}$\n\nThe vehicle is modeled with the differential equation \\[\\dot{x_{i}}=\\Big[A_{i}\\Big]x_{i}+\\Big[B_{id}\\Big]d+\\Big[B_{iu}\\Big]u\\]\nThis differential equation is integrated to get the state vector $x_{i}$. The regulator problem is then completed with the feedback loop of the state vector, optimized to minimize the perceived lateral acceleration $a_{per}$.\n\nFor the next sections, it is fundamental to do a distinction between the open and the closed loop systems:\n\n\\minipage{0.4\\textwidth}\n\t\\hspace{0.25cm}--Open-loop system\n\\endminipage\\hfill\n\\minipage{0.6\\textwidth}\n\t\\[\\dot{x_{s}}=\\Big[A_{s}\\Big]x_{s}+\\Big[B_{s}\\Big]u \\]\\[y=\\Big[I\\Big]_{7x7}x_{s}\\]\n\\endminipage\\hfill\n\\minipage{0.4\\textwidth}\n\t\\hspace{0.25cm}--Closed-loop system\n\\endminipage\\hfill\n\\minipage{0.6\\textwidth}\n\t\\[\\dot{x_{s}}=\\Big(\\big[A_{s}\\big]-\\big[B_{s}\\big]\\big[K\\big]\\Big)x_{s}+\\big[B_{s}\\big]u \\]\\[y=\\big[I\\big]_{7x7}x_{s}\\]\n\\endminipage\\hfill\n\n\\hspace{0.5cm}with $x_{s}=\\begin{bmatrix}\\dot{y} & \\dot{\\psi} & \\theta & \\dot{\\theta}\t& a_{per} & \\delta & \\dot{\\delta} \\end{bmatrix}^{T}$\n\n\\newpage\n\\subsection{Feedback and Feedforward Gains}\n\nFollowing the methodology explained in \\textit{Chapter 3 - Control Strategy Summary}, the feedback and feedforward gains are obtained. The influence of the inverse velocity term in the gain scheduling stage was also studied.\n\nOnce the dynamic model is completed with the PEV parameters, the gains are obtained from the Riccati and Sylvester equations:\n\n\\begin{itemize}\n\\begin{itemize}\n\\item Feedback Gains: Riccati equation \n\n$\\hspace{1.5cm} M_{1}\\,A_{i} + A_{i}^{T}\\,M_{1} - M_{1}\\,B_{iu}\\,R_{u}^{-1}B_{iu}^{T}M_{1} + Q_{x}=0$\n\n$\\hspace{3.5cm} K=R_{u}^{-1}\\,B_{iu}^{T}\\,M_{1}$\n\n\\item Feedback Gains: Slyvester equation \n\n$\\hspace{1cm}M_{2}\\,A_{e}+(A_{i}^{T}-M_{1}\\,B_{iu}\\,R_{u}^{-1}\\,B_{iu}^{T})M_{2}+M_{1}\\,B_{id}\\,C_{e}=0$\n\n$\\hspace{3.5cm} K_{d}=R_{u}^{-1}\\,B_{iu}^{T}\\,M_{2}$\n\n\\end{itemize}\n\\end{itemize}\n\n\\marginnote{\\begin{tabular}{l|ccc|}\n                       & $K_{C}$ & $K_{V}$ & $K_{1/V}$ \\\\[5pt] \\hline \\\\[-5pt] \n$K_{a_{per}}^{'}$      & -0.56   & -0.27   & 0.52      \\\\[5pt]\n$K_{\\dot{\\psi}}^{'}$   & 19.14   & -4.09   & -16.63    \\\\[5pt]\n$K_{\\theta}^{'}$       & 242.92  & -2.51   & 5.54      \\\\[5pt]\n$K_{\\dot{\\theta}}^{'}$ & 64.40   & -0.46   & 0.84      \\\\[5pt]\n$K_{a_{per}^{I}}^{'}$  & -0.32   & 0       & 0         \\\\[5pt]\n$K_{\\delta}^{'}$       & 1228.56 & -270.84 & -1121.79  \\\\[5pt]\n$K_{\\dot{\\delta}}^{'}$ & 220.54  & -59.70  & -201.26   \\\\[5pt] \\hline\n\\end{tabular}}\n\nThe obtained gains are transformed so that the state vector is fully measurable:\n\\begin{eqnarray}\nK_{a_{per}}^{'}=\\frac{K_{\\dot{y}}}{a_{11}+ha_{41}+K_{\\dot{y}}\\,(b_{u1}+hb_{u4})} \\\\[10pt]\nK_{\\dot{\\psi}}^{'}=\\frac{K_{\\dot{\\psi}}(a_{11}+ha_{41})-K_{\\dot{y}}(a_{12}+ha_{42}+V_{x})}{a_{11}+ha_{41}+K_{\\dot{y}}\\,(b_{u1}+hb_{u4})} \\\\[10pt]\nK_{\\theta}^{'}=\\frac{K_{\\theta}(a_{11}+ha_{41})-K_{\\dot{y}}(a_{13}+ha_{43}-g)}{a_{11}+ha_{41}+K_{\\dot{y}}\\,(b_{u1}+hb_{u4})} \\\\[10pt]\nK_{\\dot{\\theta}}^{'}=\\frac{K_{\\dot{\\theta}}(a_{11}+ha_{41})-K_{\\dot{y}}(a_{14}+ha_{44})}{a_{11}+ha_{41}+K_{\\dot{y}}\\,(b_{u1}+hb_{u4})} \\\\[10pt]\nK_{a_{per}^{I}}^{'}=\\frac{K_{a_{per}^{I}}(a_{11}+ha_{41})}{a_{11}+ha_{41}+K_{\\dot{y}}\\,(b_{u1}+hb_{u4})} \\\\[10pt]\nK_{\\delta}^{'}=\\frac{K_{\\delta}(a_{11}+ha_{41})-K_{\\dot{y}}(b_{\\delta 1}+hb_{\\delta 4})}{a_{11}+ha_{41}+K_{\\dot{y}}\\,(b_{u1}+hb_{u4})} \\\\[10pt]\nK_{\\dot{\\delta}}^{'}=\\frac{K_{\\dot{\\delta}}(a_{11}+ha_{41})}{a_{11}+ha_{41}+K_{\\dot{y}}\\,(b_{u1}+hb_{u4})}\n\\end{eqnarray}\n\n\\[K^{'}=\\begin{bmatrix}\nK_{a_{per}}^{'} & K_{\\dot{\\psi}}^{'} & K_{\\theta}^{'} & K_{\\dot{\\theta}}^{'} & K_{a_{per}^{I}}^{'} & K_{\\delta}^{'} & K_{\\dot{\\delta}}^{'}\n\\end{bmatrix} \\]\n\n\\newpage\n\\begin{figure*}[!h]\n\t\\includegraphics[width=0.8\\linewidth]{figs/06/control/model_gains}\n\t\\caption{Gains relation with velocity. Velocity inverse term is not considered}\n\t\\label{model_gains}\n\t\\\\[-0.5cm]\n\\end{figure*}\n\n\\newpage\n\\begin{figure*}[!h]\n\t\\includegraphics[width=0.8\\linewidth]{figs/06/control/model_gains_inverse}\n\t\\caption{Gains relation with velocity. Velocity inverse term is considered}\n\t\\label{model_gains_inverse}\n\t\\\\[-0.5cm]\n\\end{figure*}\n\n\\newpage\nIn Figures \\ref{model_gains} and \\ref{model_gains_inverse} the gains of the PEV without driver have been represented. The gains curves are estimated as a least square estimation of some discrete points. As was indicated in previous chapters, the gain scheduling as function of the longitudinal velocity was designed to depend on three terms $K_{c}$, $K_{V}$ and $K_{1/V}$  with:\n\n$\\hspace{2.5cm}\\begin{pmatrix} K_{c} \\\\ K_{V} \\\\ K_{1/V} \\end{pmatrix}=(M^{T}\\,M)^{-1}\\,M^{T}\\,K_{M}$\n\nIf the inverse term $K_{1/V}$ is not considered, then the gain scheduling only depends linearly on the velocity:\n\n$\\hspace{2.5cm}\\begin{pmatrix} K_{c} \\\\ K_{V} \\end{pmatrix}=(M^{T}\\,M)^{-1}\\,M^{T}\\,K_{M}$\n\n\\subsection{Stability}\n\nIf the system is studied without feedback control, it is inherently unstable. The instability can be visualized through different indicators. \n\nThe system matrix $\\big[A_{s}\\big]$ is non-negative defined, meaning that it has positive eigenvalues. The eigenvalues of $\\big[A_{s}\\big]$ represent the open poles of the system, and if a pole is in the positive side of the real numbers, then it means that the system is unstable.\n\n \\[eig(\\big[A_{s}\\big])=\\begin{bmatrix}0 \\\\ -92.47 \\\\ -43.38 \\\\ -4.06 \\\\ 3.61 \\\\ -0.5 \\\\ -1 \\end{bmatrix}\\]\n \nThe eigenvalues are usually represented in the pole-zero map. The poles (represented with a cross $X$) are the roots of denominator of the system transfer function, while the zeros (represented with a circle $O$) are the roots of the numerator. In figure \\ref{pole_zero_map_1}, a pole-zero map has been included for each system transfer function. The input is the torque $M_{t}$ and the outputs are the remaining systems variables: $a_{per} \\quad \\dot{\\psi} \\quad \\theta \\quad \\dot{\\theta} \\quad \\a_{per}^{I}$.\n\nAll transfer functions share a common pole in the positive real axis, which makes the system unstable. The transfer functions can also share some poles and zeros. \n\n\\newpage\n\\begin{figure}[!h]\n\t\\includegraphics[width=1.15\\linewidth]{figs/06/control/pole_zero_map_1}\n\t\\caption{Pole zero map of the open--loop system (unstable)}\n\t\\label{pole_zero_map_1}\n\t\\\\[-1cm]\n\\end{figure}\n\nSimulating the response of the system to a disturbance $\\delta,\\,\\dot{\\delta}$ makes the state variables unstable and tend to infinite values:\n\n\\begin{figure}[!h]\n\t\\includegraphics[width=1.15\\linewidth]{figs/06/control/response_1}\n\t\\caption{Unstable response of the open--loop system, without control feedback}\n\t\\label{response_1}\n\t\\\\[-1.3cm]\n\\end{figure}\n\nLooking at the ranks of the observability and controllability matrix of the system: \\[Ob=\\begin{bmatrix}C & C\\,A & C\\,A^{2} & ... & C\\,A^{6}\\end{bmatrix}^{T}\\] \\[Co=\\begin{bmatrix}B & A\\,B & A^{2}\\,B & ... & A^{6}\\,B\\end{bmatrix}\\]\nThe system is observable if $Ob$ has full rank ($A_{7x7}$) and is controllable if $Co$ has also full rank ($A_{7x7}$). Therefore, the open loop system is observable ($rank(Ob)=7$), but not controllable ($rank(Ob)=7$)\n\nIf the system is controlled with the feedforward and feedback gains, then the system stabilizes. The matrix $\\big[A_{s}\\big]$ is definite non-positive, with all its eigenvalues located in the negative side of the pole map. However, a pair of conjugate imaginary poles and positive zeros are introduced to effectively stabilize the system.\n \\[eig(\\big[A_{s}\\big]-\\big[B_{s}\\big]\\big[K\\big])=\\begin{bmatrix}-81.87 \\\\-44.56 + 11.53i \\\\-44.56 - 11.53i \\\\-4.917\\\\-5.478\\\\-0.50\\\\-1\\end{bmatrix}\\]\nThe pole-zero map and the response of the system are indeed stable:\n \n\\begin{figure}[!h]\n\t\\includegraphics[width=1.15\\linewidth]{figs/06/control/pole_zero_map_2}\n\t\\caption{Pole zero map of the closed--loop system (stable)}\n\t\\\\[-0.5cm]\n\\end{figure}\n\n\\begin{figure}[!h]\n\t\\includegraphics[width=1.15\\linewidth]{figs/06/control/response_2}\n\t\\caption{Stable response of the closed--loop system, with control feedback}\n\t\\\\[-5cm]\n\\end{figure}\n\n\\newpage\n\\subsection{Robustness}\n\nThe $\\mu$-analysis makes it possible to carry out a posteriori robust studies with respect to the parametric variations of the model, or the neglected dynamics, taking into account the structure and the nature of the uncertainties.\n\nAccording to the generalized small gains theorem, checking the robustness of the stability of the closed loop, amounts to calculating the singular values of the transfer function $\\mu(H(jw))$. The system is stable if these values are under 1 $\\mu(H(jw))<1$ and if in addition $\\mu(H(jw))$ is small, the stability of the system is robust.\n\n\\begin{figure}[!h]\n\t\\includegraphics[width=1\\linewidth]{figs/06/control/singular_values_1}\n\t\\caption{Singular values of the open--loop system}\n\t\\\\[-1cm]\n\\end{figure}\n\nHigh-gain feedback in low-frequency ranges is a way to deal with the effects of unknown biases and disturbances acting on the process output. The control feedback increases the singular values (the principal gains of the frequency response) at 10 to 100 Hz range, but it remains below $\\mu=0\\,dB=20 \\log (1)$.\n\\begin{figure}[!h]\n\t\\includegraphics[width=1\\linewidth]{figs/06/control/singular_values_2}\n\t\\caption{Singular values of the closed--loop system}\n\t\\\\[-5cm]\n\\end{figure}\n\n\\newpage\nApart from being stable, the system has deal with the effects of uncertainty. Reducing the effects of some forms of uncertainty (initial conditions, low-frequency disturbances) without increasing the effects of the sensor noise or the model uncertainty is the primary job of the feedback control system.\n\nAt the heart of robust control is the concept of an uncertain LTI system. Model uncertainty arises when system gains or other parameters are not precisely known, or can vary over a given range. The following table summarizes the model parameters and their variation over the nominal value.\n\n\\begin{table}\n\t\\centering\n\t\\begin{tabular}{c|cc|c}\n\t & \\textbf{Value} & \\textbf{Deviation\\%} &      \\\\ \\hline\n\t$L_{f}$       & 0.51          & 5         & $m$       \\\\\n\t$L_{r}$       & 0.81          & 5         & $m$       \\\\\n\t$h$           & 0.36          & 15        & $m$       \\\\\n\t$m$           & 35            & 20        & $kg$      \\\\\n\t$I_{z}$       & 11            & 50        & $kg\\,m^2$ \\\\\n\t$I_{x}$       & 4             & 50        & $kg\\,m^2$ \\\\\n\t$C_{f}$       & 3500          & 25        & $N/rad$   \\\\\n\t$C_{r}$       & 3000          & 25        & $N/rad$   \\\\\n\t$\\lambda_{f}$ & 200           & 25        & $N/rad$   \\\\\n\t$\\lambda_{r}$ & 200           & 25        & $N/rad$   \\\\ \\hline \n\t\\end{tabular}\n\t\\caption{Parameters Deviations}\n\t\\\\[6pt]\n\\end{table}\n\nOnce formulated, high-level system robustness tools can help to analyze the potential degradation of stability and performance of the closed-loop system brought on by the system model uncertainty.\n\nThe parameter uncertainties mean uncertain pole and zero locations. Fortunately, among the represented poles, none of them is moving towards the positive real part, which will produce instabilities.\n\n\\begin{figure}[!h]\n\t\\includegraphics[width=1.1\\linewidth]{figs/06/control/pole_zero_map_uncertainty_1}\n\t\\caption{Uncertainty in the pole zero map of the open--loop system}\n\t\\\\[-5cm]\n\\end{figure}\n\\newpage\n\\begin{figure}[!h]\n\t\\includegraphics[width=1.1\\linewidth]{figs/06/control/pole_zero_map_uncertainty_2}\n\t\\caption{Uncertainty in the pole zero map of the closed--loop system}\n\t\\\\[-1cm]\n\\end{figure}\n\nRegarding the singular values of the closed-loop system, these values are not affected by the parameters uncertainties.\n\n\\begin{figure*}[!h]\n\t\\includegraphics[width=1\\linewidth]{figs/06/control/singular_values_uncertainty}\n\t\\caption{Uncertainty in the singular values of the open and closed--loop system}\n\\end{figure*}\n\n%\\begin{figure}[!h]\n%\t\\includegraphics[width=1\\linewidth]{figs/06/control/singular_values_uncertainty_1}\n%\t\\caption{Uncertainty in the singular values of the open--loop system}\n%\\end{figure}\n%\\begin{figure}[!h]\n%\t\\includegraphics[width=1\\linewidth]{figs/06/control/singular_values_uncertainty_2}\n%\t\\caption{Uncertainty in the singular values of the closed--loop system}\n%\\end{figure}\n\nNotions such as gain and phase margins help to quantify the sensitivity of stability and performance in the face of model uncertainty, which is the imprecise knowledge of how the control input directly affects the feedback variables.\n\n\\begin{marginfigure}[1cm]\n\t\\includegraphics[width=0.8\\linewidth]{figs/06/control/margin}\n\t\\caption{Gain and phase margin}\n\\end{marginfigure}\nThe gain margin is the amount of gain increase or decrease required to make the loop gain unity at the frequency where the phase angle is $–180\\degree$. Similarly, the phase margin is the difference between the phase of the response and $–180\\degree$ when the loop gain is 1.\n%\\begin{lstlisting}[style=codematlab2]\n%GainMargin: 0.0707\n%GMFrequency: 4.4670\n%PhaseMargin: 76.0715\n%PMFrequency: 50.6347\n%DelayMargin: 0.0262\n%DMFrequency: 50.6347\n%\\end{lstlisting}\n\n\\newpage\n\nIf the stability robustness margin is greater than 1 it means that the uncertain system is stable for all values of its modeled uncertainty. Being less than 1 implies that certain allowable values of the uncertain elements lead to instability. In our system only bounds on the exact stability margin were computed. The exact robust stability margin is guaranteed to lie in between these upper and lower bounds.\n\\begin{lstlisting}[style=codematlab2]\n\t\tLowerBound: 0.9099\n\t\tUpperBound: 1.9902\n\t\tDestabilizingFrequency: 0.1005\n\\end{lstlisting}\nA nominally stable uncertain system is generally unstable for specific values of its uncertain elements. Determining the values of the uncertain elements closest to their nominal values for which instability occurs is a robust stability calculation.\n%\\begin{marginfigure}[-5cm]\n%\t\\includegraphics[width=0.65\\linewidth]{figs/06/control/destabilizing}\n%\t\\caption{Destabilizing Parameters}\n%\\end{marginfigure}\n\\begin{lstlisting}[style=codematlab2]\nDestabilizing Parameters:\n\t\tC_f: 5.2414e+03\n\t\tC_r: 1.5074e+03\n\t\tI_x: 0.0196\n\t\tI_z: 0.0540\n\t\tL_f: 0.5607\n\t\tL_r: 0.7294\n\t\th: 0.2525\n\t\tlanda_f: 299.5095\n\t\tlanda_r: 100.4905\n\t\tm: 48.9313\n\\end{lstlisting}\n\nIf the uncertain system is stable for all values of uncertain elements within their allowable ranges, the uncertain system is robustly stable. Conversely, if there is a combination of element values that cause instability, and all lie within their allowable ranges, then the uncertain system is not robustly stable.\n\\begin{lstlisting}[style=codematlab2,frame=single]\n\tUncertain system is possibly not robustly stable to modeled uncertainty.\n\t-- It can tolerate up to 91% of the modeled uncertainty.\n\t-- A destabilizing combination of 199% of the modeled uncertainty was found.\n\t-- This combination causes an instability at 0.1 rad/seconds.\n\t-- Sensitivity with respect to the uncertain elements are:\n\t'C_f' is 27%. Increasing 'C_f' by 25% leads to a 7% decrease in the margin.\n\t'C_r' is 17%. Increasing 'C_r' by 25% leads to a 4% decrease in the margin.\n\t'I_x' is 78%. Increasing 'I_x' by 25% leads to a 20% decrease in the margin.\n\t'I_z' is 28%. Increasing 'I_z' by 25% leads to a 7% decrease in the margin.\n\t'L_f' is 6%.  Increasing 'L_f' by 25% leads to a 2% decrease in the margin.\n\t'L_r' is 9%.  Increasing 'L_r' by 25% leads to a 2% decrease in the margin.\n\t'h' is 8%.    Increasing 'h' by 25% leads to a 2% decrease in the margin.\n\t'landa_f' is 5%. Increasing 'landa_f' by 25% leads to a 1% decrease in the margin.\n\t'landa_r' is 5%. Increasing 'landa_r' by 25% leads to a 1% decrease in the margin.\n\t'm' is 12%. Increasing 'm' by 25% leads to a 3% decrease in the margin.\n\\end{lstlisting}\n\n%\\begin{figure}[!h]\n%\t\\includegraphics[width=1\\linewidth]{figs/06/control/open_loop_responses_input_sensitivities_uncertainty}\n%\t\\caption{Open loop responses and input sensitivities}\n%\\end{figure}\n\n\\newpage\n\\section{Experiments}\n\nOnce the control system was developed and the PEV was fully fabricated, the test and validation stage started. First, some tests were run to validate the sensor data. Second, the electronics were tested, along with the live streaming of data through Bluetooth. Finally, the control feedback was implemented in Arduino and tested several times.\n\n\\begin{figure}[!h]\n\t\\includegraphics[width=1\\linewidth]{figs/06/P1060127}\n\t\\caption{PEV outside the MIT Media Lab}\n\t\\\\[-1.2cm]\n\\end{figure}\n\\subsection{Test Setup}\n\n\\begin{marginfigure}[6cm]\n\t\\includegraphics[width=1\\linewidth]{figs/06/circuit}\n\t\\caption{Testing setup schematic}\n\\end{marginfigure}\nWith the intention of comparing the experimental results with the carried out simulations, the PEV was tested under some controlled conditions. The 6th floor of the MIT Media Lab was selected as the test field due to the available space and the accessibility of the room. The geometry of the experiment was limited by two circumferences of known radius ($R=2.5m$). These circumferences were delimited by some cardboard boxes laid on the floor.\n\nAs has been stated below, the first tests were run to validate the data coming from the sensors. The throttle potentiometer did not implicate any problem, neither did the rotary encoder at the rear wheel. On the contrary, the pair of IMUs (in the frame and in the handle bar) presented some problems.\n\\begin{itemize}\n\\begin{itemize}\n\\item In the calibration stage, the IMUs seemed to lose the 'north pole' every time the PEV was transported from one floor to another. However, when testing in the same floor, these problem did not appear. To solve this issue, the IMUs had to be calibrated again with each test. \n\n\\item This calibration problem also affected considerably the initial absolute orientation of both IMUs, meaning that the relative angle between them --for the $\\delta$ angle, for example-- had a initial drift.\n\n\\item The noise coming from the accelerometer and the gyroscope was excessive for a good control feedback. Each signal coming from the IMU was filtered with a simple one dimensional Kalman filter. Some preliminary tests were necessary to estimate the parameters of each Kalman filter: $p,\\, q,\\,k$.\n\n\\end{itemize}\n\\end{itemize}\n\nThe data was gathered using one of the Bluetooth modules, that sent the data to the computer, where the selected variables were saved in a .csv file. Afterwards, the data and the video from the front camera were a synchronized using an script in Matlab.\n\n\\begin{figure}[!h]\n\t\\includegraphics[width=1\\linewidth]{figs/06/live}\n\t\\caption{Live streaming through Bluetooth module}\n\t\\\\[-1cm]\n\\end{figure}\n\nThe PEV was tested with and without the tilting mechanism, thanks to the modularity of the front suspension design. The non-tilting PEV was used for the tests where the sensor data was being validated and for the tests where the control strategy was implemented. After all the systems had been validated, the PEV was modified to allow the tilting and the final experiments were carried out.\n \n\\begin{figure*}[b]\n\t\\includegraphics[width=1\\linewidth]{figs/06/test_1}\n\t\\caption{Testing setup}\n\t\\\\[-1.5cm]\n\\end{figure*}\n\n\\newpage\n\n\\subsection{Test Results}\n\nThe improvement of the PEV from the first to the last test was evident. The vehicle was exhaustively tested to improve the steering response as well as the remote control from the Android app. The mechanical robustness of the vehicle was put to the test during these experiments.\n\nIn the next set of pictures (Figure \\ref{scene_2}), two turns to the circumference are illustrated. Before running any test, the PEV team consensually decided not to put in risk the integrity of any member, so it was decided to experiment only with driverless PEV. The main focus of these tests was the validation of the mechanics, the electronics and the control strategy. \n\nIt is important to recall that at the test stage any false step can imply the breaking of the PEV or in the worst case scenario, the harm of the researches. A testing vehicle can suppose a danger if it gets out of control, so some safety measures, both at the hardware and the software level were implemented.\n\nTherefore, since it was a driverless test, the PEV was remotely controlled, both at the steering and at the throttle. In this experiment, the control of the PEV was smooth, and the data was correctly gathered for the afterwards analysis.\n\nWith regards to the tilting mechanism, it successfully worked properly, meaning that the front suspension geometry was appropriate and that the selection of the components was satisfactory. In addition, the self limitation of the geometry limited the tilting angle to a maximum, thus preventing the PEV from rolling over when tilting.\n\n\\begin{figure*}[!h]\n\t\\includegraphics[width=1\\linewidth]{figs/06/scene_2}\n\t\\caption{Testing scene}\n\t\\label{scene_2}\n\\end{figure*}\n\n\\newpage\n\n\\begin{marginfigure}\n\t\\includegraphics[width=1.15\\linewidth]{figs/06/scene00151}\n\t\\caption{PEV tilting during the test}\n\\end{marginfigure}\nEven though the control strategy was not fully validated, the implementation of the feedback and feedforward gains showed that the torque $M_{t}$ was giving good inputs for the tilting.\n\nThe main problem with the control strategy was focused on the integration of the perceived lateral acceleration ($a_{per}^{I}$). The integration of a signal coming from the IMU was reviewed in the chapter 4, where the velocity of the MiniPEV was estimated from the longitudinal linear acceleration. The similarities between the two challenges seem obvious. That is why the control strategy had to be finally reduced to the output variable  $a_{per}$ instead of $a_{per}^{I}$\n\nIn figures \\ref{Picture1},\\ref{Picture2}, \\ref{Picture3} and \\ref{Picture4} a sample of the carried out test has been included. This experiment was carried out allowing the tilting of the vehicle, and the control strategy was almost similar to the one presented previously in this chapter. The only difference can be found in the output variable, that is the $a_{per}$ instead of $a_{per}^{I}$. \n\nAs was already mentioned, lateral stability is obtained when $a_{per}=0$. The control of the integrated value of $a_{per}$ avoids the model errors due to parameters uncertainty, neglected dynamics or linearization of the model. Therefore, these are the errors that can appear if only the $a_{per}$ is controlled. In this case the process to obtain the gains is completely similar.\n\nThe Figure \\ref{Picture1} represents the disturbance of the model, that is, the input from the driver. The steering angle indicates the desired direction. In this case, the vehicle does turn to the left before turning to the right. The reader can visualize the inherent noise in the steering rate $\\dot{\\delta}$. Even though the Kalman filter revokes some of the signal noise, it is important to remind that the gyroscope data is very prone to vibrations.\n\\begin{figure}[!h]\n\t\\includegraphics[width=1\\linewidth]{figs/06/tests/Picture1b}\n\t\\caption{Disturbance signal; input from the driver $\\delta$ and $\\dot{\\delta}$}\n\t\\label{Picture1}\n\\end{figure}\n\\newpage\n\nThe velocity of the vehicle has been included in Figure \\ref{Picture2}. This test was carried out at low speed, in order to have the vehicle under control if necessary. The lateral perceived acceleration $a_{per}$ is noisy as well, whereas the yaw rate $\\dot{\\psi}$ is more smooth. Anyway, the data confirms that both variables are properly calculated. \n\nBefore any input from the driver --when the vehicle is going in a straight line-- both the $a_{per}$ and the $\\dot{\\psi}$ are null. Just when the driver turns the handle bar and steers the front wheels, the yaw rate starts to increase (meaning a left turn) and the perceived acceleration takes negative values synchronously. Just when the steering angle is changed to the opposite direction, these two signals invert their values.\n\n\\begin{figure}[!h]\n\t\\includegraphics[width=1\\linewidth]{figs/06/tests/Picture2b}\n\t\\caption{Vehicle variables: longitudinal velocity, perceived lateral acceleration and yaw rate}\n\t\\label{Picture2}\n\\end{figure}\n\nThe response of the control strategy is to apply a torque $M_{t}$ so that the effect of the disturbance $\\delta$ on the perceived lateral acceleration $a_{per}$ is canceled. Using the gains calculated previously, the torque required from the tilting motor is represented in the Figure \\ref{Picture4}. \n\nThe control objective is obtained with very satisfying performances; $a_{per}$ does not exceed $1m/s^2$ and the maximum tilting torque value is 10 Nm. The fact that more torque is required to the right turn is due to the fact that the steering input is higher in this case, so that demanding more torque.\n\\begin{figure}[!h]\n\t\\includegraphics[width=1\\linewidth]{figs/06/tests/Picture4b}\n\t\\caption{Torque required by the control system to tilt the PEV}\n\t\\label{Picture4}\n\t\\\\[-3cm]\n\\end{figure}\n\n\\newpage\nThe applied torque in the tilting motor leans the PEV and as a consequence, there is a change in the tilting angle $\\theta$ and in the tilting rate $\\dot{\\theta}$. In this case the maximum tilting angle goes over $0.15 rad=8 deg.$, which is not very high due to the low speed of the test.\n \n\\begin{figure}[!h]\n\t\\includegraphics[width=1\\linewidth]{figs/06/tests/Picture3b}\n\t\\caption{Control strategy results}\n\t\\label{Picture3}\n\\end{figure}\n\nOverall, the carried out tests were satisfactory in almost every way. The exclusion of  the integrate of the perceived lateral acceleration from the control strategy changed the properties and the robustness of the system, but far from ruining the developed control model, this fact introduced a much simpler and effective model. While it is true that some errors can rise --parameters uncertainty, neglected dynamics or model linearization -- the reduced model successfully tilt the vehicle. \n\n%\\begin{figure*}[!h]\n%\t\\includegraphics[width=1\\linewidth]{figs/06/tests/Picture5}\n%\t\\caption{Control strategy results}\n%\t\\label{Picture5}\n%\\end{figure*}\n\n\\begin{figure}[b]\n\t\\includegraphics[width=1\\linewidth]{figs/06/test_2}\n\t\\caption{PEV testing}\n\\end{figure}\n\n\n\n", "meta": {"hexsha": "5e7048a00bb636097fe49643dc962cb087111988", "size": 35503, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "pages/06modelValidation.tex", "max_stars_repo_name": "imartinezl/MIT-Media-Lab-latex-thesis", "max_stars_repo_head_hexsha": "f547c9879ca2c2b12ee57ceff9d533061167b701", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-11-25T16:15:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-08T15:09:27.000Z", "max_issues_repo_path": "pages/06modelValidation.tex", "max_issues_repo_name": "imartinezl/MIT-Media-Lab-latex-thesis", "max_issues_repo_head_hexsha": "f547c9879ca2c2b12ee57ceff9d533061167b701", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pages/06modelValidation.tex", "max_forks_repo_name": "imartinezl/MIT-Media-Lab-latex-thesis", "max_forks_repo_head_hexsha": "f547c9879ca2c2b12ee57ceff9d533061167b701", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-10-31T00:54:01.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-16T07:29:54.000Z", "avg_line_length": 68.0134099617, "max_line_length": 510, "alphanum_fraction": 0.6907021942, "num_tokens": 9800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.30426587413615436}}
{"text": "\\documentclass{scrartcl}\n\\usepackage[a4paper,left=1in,right=1in,top=1.2in,bottom=1in]{geometry}\n\\usepackage{siunitx}\n\\usepackage{graphicx}\n\\usepackage{mathtools}\n\\setkomafont{disposition}{\\normalfont\\bfseries}\n\\newcommand*\\diff{\\mathop{}\\!\\mathrm{d}}\n\\newcommand*\\Diff[1]{\\mathop{}\\!\\mathrm{d^#1}}\n\\newcommand*\\colvec[3][]{\n    \\begin{pmatrix}\\ifx\\relax#1\\relax\\else#1\\\\\\fi#2\\\\#3\\end{pmatrix}\n}\n\n%title\n\\title{Exercise 04:\\\\Supervised Learning}\n\\subtitle{Theoretical Neuroscience II}\n\\author{Johannes G\\\"atjen \\and Lorena Morton}\n\n%use these for structure/overview\n\\newcommand\\Question{%\n  \\textbf{Question:}%\n}\n\\newcommand\\Answer{%\n  \\textbf{Answer:}%\n}\n\n\\begin{document}\n\\maketitle\n\n\\section{Training of feed-forward connections}\n\\begin{figure}[h]\n\\centering\n\\includegraphics[trim = {0.8cm 0 0.5cm 0.2cm}, width=0.48\\textwidth, clip]{../pics/lin_mean}\\includegraphics[trim = {0.8cm 0 0.5cm 0.2cm}, width=0.48\\textwidth, clip]{../pics/lin_noise}\\\\\n\\includegraphics[trim = {0.8cm 0 0.5cm 0.2cm}, width=0.48\\textwidth, clip]{../pics/cons_mean}\\includegraphics[trim = {0.8cm 0 0.5cm 0.2cm}, width=0.48\\textwidth, clip]{../pics/cons_noise}\n\\caption{Left: Mean response of selected neurons to different frequencies (tuning curve). Right:~Ensemble of actual noisy responses of the same neurons. Note the larger scale on the y axis. Top: Standard deviation for tuning curve increases linearly with frequency ($\\kappa = 0.22$). Bottom: Constant standard deviation ($\\sigma = 30\\si{Hz}$).}\n\\end{figure}\n\n\n\\begin{figure}\n\\centering\n\\includegraphics[trim = {1cm 0 1cm 0.3cm}, width = 0.9\\textwidth, clip]{../pics/cov}\n\\caption{Covariance matrices for the activity of the linear and constant standard deviation populations. Left: Calculated from mean activity. Right: Calculated from noisy activity. It can be seen, that neurons close to each other are positively correlated and neurons further apart are anti-correlated.}\n\\end{figure}\n\\clearpage\n\n\\section{Decoding the downstream activity}\n\n\\begin{figure}[h]\n\\centering\n\\includegraphics[trim = {0.7cm 0 0.5cm 0.2cm}, width = 0.7\\textwidth, clip]{../pics/tuning}\n\\caption{The decoded downstream activity plotted against the input ($\\sigma=30\\si{Hz}$, $\\kappa=0.22$, $N=M=40$). In a perfectly tuned network the points would form a straight line on the diagonal ($x=y$). Here aside from some noise, the tuning fits well for low to medium high frequency ranges. For very low inputs the decoded frequency is very inaccurate, ranging up to over 800 \\si{Hz}. For inputs larger than ca.\\ 750\\si{Hz} the decoded frequencies are too low, due to the inaccurate input coming from the upstream population.}\n\\end{figure}\n\n\\begin{figure}\n\\centering\n\\includegraphics[trim = {0.7cm 0 0.5cm 0.2cm}, width = 0.7\\textwidth, clip]{../pics/sigma}\n\\caption{The tuning (in)accuracy measured by the root mean square error (where error is taken as difference between input and decoded frequency) for $10000$ random inputs as a function of the $\\sigma$ parameter ($\\kappa=0.22$, $N=M=40$). The error grows linearly with $\\sigma$.}\n\\end{figure}\n\n\\begin{figure}\n\\centering\n\\includegraphics[trim = {0.7cm 0 0.5cm 0.2cm}, width = 0.7\\textwidth, clip]{../pics/numN}\n\\caption{Tuning error as a function of the number of neurons in both the upstream and downstream populations ($\\sigma=30\\si{Hz}$, $\\kappa=0.22$, $N=M$). A higher number of neurons allows slightly more accurate decoding.}\n\\end{figure}\n\n\\begin{figure}\n\\centering\n\\includegraphics[trim = {0.7cm 0 0.5cm 0.2cm}, width = 0.7\\textwidth, clip]{../pics/kappa}\n\\caption{Tuning error as a function of $\\kappa$ ($\\sigma=30\\si{Hz}$, $N=M=40$). For $\\kappa < 0.5$ the error grows quickly with increasing $\\kappa$, for larger values the growth in error is less pronounced.}\n\\end{figure}\n\n\\end{document}", "meta": {"hexsha": "d0f18fd57b5ce89d86d47d8931aeea9d4081435d", "size": 3762, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ex4/pdf/ex4.tex", "max_stars_repo_name": "gaetjen/TNSII_Exercises", "max_stars_repo_head_hexsha": "d82eb790132e9066c6ad41e7f90ba193145a2e8f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ex4/pdf/ex4.tex", "max_issues_repo_name": "gaetjen/TNSII_Exercises", "max_issues_repo_head_hexsha": "d82eb790132e9066c6ad41e7f90ba193145a2e8f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ex4/pdf/ex4.tex", "max_forks_repo_name": "gaetjen/TNSII_Exercises", "max_forks_repo_head_hexsha": "d82eb790132e9066c6ad41e7f90ba193145a2e8f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.985915493, "max_line_length": 531, "alphanum_fraction": 0.7413609782, "num_tokens": 1184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3042658665428101}}
{"text": "\\pdfoutput=1\n\\documentclass[twocolumn]{aastex62}\n%%\\documentclass[]{emulateapj}\n\n%Accepted/received/... %%\n\n\\received{xxx}\n\\revised{yyy}\n\\accepted{zzz}\n\n%% Command to document which AAS Journal the manuscript was submitted to.\n\\submitjournal{AAS Journals}\n\n%% Short title/authors\n\n\\shorttitle{LXUV History of TRAPPIST-1}\n\\shortauthors{Fleming et al.}\n\n%% Begin document, title, packages %%\n\\usepackage{hyperref}\n\\usepackage{xspace}\n\\usepackage{graphicx}\n\\usepackage{amsmath}\n\\usepackage[caption=false]{subfig}\n\\usepackage[ruled,vlined]{algorithm2e}\n\n%% Custom commands\n\\def\\mearth{{\\rm\\,M_\\oplus}}\n\\def\\rearth{{\\rm\\,R_\\oplus}}\n\\def\\msun{{\\rm\\,M_\\odot}}\n\\def\\rsun{{\\rm\\,R_\\odot}}\n\\def\\lsun{{\\rm\\,L_\\odot}}\n\\def\\gsim{~\\rlap{$>$}{\\lower 1.0ex\\hbox{$\\sim$}}}\n\\def\\lsim{~\\rlap{$<$}{\\lower 1.0ex\\hbox{$\\sim$}}}\n\n\\newcommand{\\xxx}[1]{{\\textbf{#1}}}\n\\newcommand{\\vplanet}[0]{\\texttt{VPLanet}\\xspace}\n\\newcommand{\\emcee}[0]{\\texttt{emcee}\\xspace}\n\\newcommand{\\approxposterior}[0]{\\texttt{approxposterior}\\xspace}\n\\newcommand{\\eqtide}[0]{\\texttt{EQTIDE}\\xspace}\n\\newcommand{\\stellar}[0]{\\texttt{STELLAR}\\xspace}\n\\newcommand{\\kepler}[0]{\\textit{Kepler}\\xspace}\n\\newcommand{\\jwst}[0]{\\textit{JWST}\\xspace}\n\n%% Begin doc %%\n\\begin{document}\n\n\\title{On The XUV Luminosity Evolution of TRAPPIST-1}\n\n%% AUTHORS %%\n\n%%\\correspondingauthor{David P. Fleming}\n%%\\email{dflemin3@uw.edu}\n\n%%\\author[0000-0001-9293-4043]{David P. Fleming}\n\\author[0000-0001-9293-4043]{David P. Fleming}\n\\affil{Astronomy Department, University of Washington \\\\\nBox 951580, Seattle, WA 98195}\n\\affil{NASA NExSS - Virtual Planetary Laboratory Lead Team, USA}\n% ORCID 0000-0001-9293-4043\n\n\\author{Rory Barnes}\n\\affiliation{Astronomy Department, University of Washington \\\\\nBox 951580, Seattle, WA 98195}\n\\affil{NASA NExSS - Virtual Planetary Laboratory Lead Team, USA}\n% no orcid\n\n\\author[0000-0002-0296-3826]{Rodrigo Luger}\n\\affil{NASA NExSS - Virtual Planetary Laboratory Lead Team, USA}\n\\affiliation{Center for Computational Astrophysics, Flatiron Institute \\\\\nNew York, NY 10010}\n% ORCIF 0000-0002-0296-3826\n\n\\author[0000-0002-9623-3401]{Jacob T. VanderPlas}\n\\affiliation{Google \\\\\n601 N 34th St, Seattle, WA 98103}\n% ORCID 0000-0002-9623-3401\n\n%% ABSTRACT %%\n\n\\begin{abstract}\n\nWe model the long-term XUV luminosity of TRAPPIST-1 to constrain the evolving high-energy radiation environment experienced by its planetary system. Using Markov Chain Monte Carlo (MCMC), we derive probabilistic constraints for TRAPPIST-1's stellar and XUV evolution that account for observational uncertainties, degeneracies between model parameters, and empirical data of low-mass stars. We constrain TRAPPIST-1's mass to $m_{\\star} = 0.089 \\pm{0.001}$ M$_{\\odot}$ and find that its early XUV luminosity likely saturated at $\\log_{10}(L_{XUV}/L_{bol}) = -3.03^{+0.23}_{-0.12}$. From the posterior distribution, we infer that there is a ${\\sim}40\\%$ chance that TRAPPIST-1 is still in the saturated phase today, suggesting that TRAPPIST-1 has maintained high activity and $L_{XUV}/L_{bol} \\approx 10^{-3}$ for several Gyrs. TRAPPIST-1's planetary system therefore likely experienced a persistent and extreme XUV flux environment, potentially driving significant atmospheric erosion and volatile loss. The inner planets likely received XUV fluxes ${\\sim}10^3 - 10^4\\times$ that of the modern Earth during TRAPPIST-1's ${\\sim}1$ Gyr-long pre-main sequence phase. Deriving these constraints via MCMC is computationally non-trivial, so scaling our methods to constrain the XUV evolution of a larger number of M dwarfs that harbor terrestrial exoplanets would incur significant computational expenses. We demonstrate that \\approxposterior, an open source Python machine learning package for approximate Bayesian inference using Gaussian processes, accurately and efficiently replicates our analysis using $980\\times$ less computational time and $1330\\times$ fewer simulations than MCMC sampling using \\emcee. We find that \\approxposterior derives constraints with mean errors on the best fit values and $1\\sigma$ uncertainties of $0.61\\%$ and $5.5\\%$, respectively, relative to \\emcee.\n\n\\end{abstract}\n\n%% Keywords %%\n\n\\keywords{}\n\n%% Intro %%\n\n\\section{Introduction} \\label{sec:intro}\n\nThe James Webb Space Telescope (JWST) is poised to detect and characterize the first terrestrial exoplanet atmospheres via transmission spectroscopy. This search will likely focus on planets orbiting nearby M dwarfs given their favorable relative transit depths, the potential buildup of biosignature gases due to UV-driven photochemisty \\citep{Segura2005}, and the large occurrence rates of M dwarf planets \\citep{Dressing2015}. The correct interpretation of those observations, however, is predicated on understanding the system's long-term evolution, most importantly processes that could impact the planet's atmospheric state and habitability, such as atmospheric escape, water loss, and the potential buildup of an abiotic O$_2$ atmosphere \\citep{Watson1981,Lammer2003,MurrayClay2009,Luger2015}. These volatile escape mechanisms are partially driven by the host star's XUV luminosity (X-ray and EUV emission ranging over approximately 1-1000\\AA), and therefore characterizing the long-term stellar XUV evolution of late M-dwarfs is critical to assessing the present state of their planets, including habitability.\n\nHigh-energy stellar radiation originates from the corona via the heating of magnetically-confined plasma \\citep{Vaiana1981}. The stellar magnetic field is likely generated via differential rotation within the stellar convective envelope \\citep{Parker1955}, linking rotation to stellar activity and XUV emission. Stellar rotation rates slow over time due to magnetic braking \\citep{Skumanich1972}, causing XUV emission to decline with time. The X-ray luminosity ($L_{X}$) of FGK stars, for example, has been empirically shown to monotonically decrease with age \\citep{Jackson2012}. This trend has also been observed for commonly-used proxies for stellar age, rotation period and Rossby number \\citep[Ro = $P_{rot}/\\tau$ for convective turnover timescale $\\tau$,][]{Pizzolato2003,Wright2011}. \n\nStellar activity evolution is characterized by two distinct phases. First, in the saturated phase, young, rapidly-rotating stars ($\\mathrm{Ro}\\lsim 0.1$) maintain a constant $L_{X}/L_{bol} \\approx 10^{-3}$ \\citep{Wright2011,Jackson2012}. Then, at longer rotation periods and larger Ro, stars transition to the unsaturated phase in which $L_{X}/L_{bol}$ exponentially decays over time \\citep{Pizzolato2003,Ribas2005}. Recent work has shown that the stellar dynamo processes that generate magnetic fields and drive XUV emission in fully-convective M dwarfs follow the same evolution with Ro as described above for solar-type stars \\citep{Wright2016,Wright2018}. We can therefore apply this model to examine the XUV evolution of individual fully-convective stars.\n\nTRAPPIST-1 \\citep{Gillon2016,Gillon2017}, an ultracool dwarf located 12 pc from Earth, harbors 7 approximately Earth-sized transiting planets that are prime targets for JWST transmission spectroscopy observations \\citep{Morley2017,Lincowski2018,Lustig2019}. TRAPPIST-1's high observed L$_{X}$ \\citep{Wheatley2017}, short photometric rotation period \\citep[3.3 d, ][]{Luger2017}, and low Rossby number \\citep[Ro $\\approx 0.01$, ][]{Roettenbacher2017} suggest that TRAPPIST-1 is still saturated today \\citep{Pizzolato2003,Wright2011,Wright2018}. Both \\citet{Roettenbacher2017} and \\citet{Morris2018} suggest that the photometrically-determined rotation period is inaccurate, with the latter study proposing that the 3.3 d period corresponds to a characteristic timescale for active regions on the stellar surface. TRAPPIST-1's $v \\sin i = 6$ km s$^{-1}$ \\citep{Barnes2014}, however, implies a rotation period of ${\\sim}1$ d for $i = 90^{\\circ}$, providing evidence that TRAPPIST-1's rapid rotation is physical and consistent with saturation \\citep[$P_{rot} \\lsim 20$ d,][]{Wright2018}. \n\nThe TRAPPIST-1 planetary system currently receives significant high-energy fluxes \\citep{Bourrier2017b,Wheatley2017,Peacock2019}, possibly a consequence of TRAPPIST-1 remaining in the saturated regime. These fluxes were likely more extreme during the pre-main sequence, driving significant water loss and potentially rendering the planets uninhabitable \\citep{Bolmont2017,Bourrier2017a}. Here, we model the long-term stellar and XUV evolution of TRAPPIST-1 to characterize the evolving XUV environment of its planetary system. We use MCMC to derive probability distributions for our model parameters that describe the XUV evolution that are consistent with TRAPPIST-1's observed properties and their uncertainties.\n\nTRAPPIST-1 is not the only system that merits this modelling, however, as the Transiting Exoplanet Survey Satellite will likely discover additional transiting planets orbiting in the habitable zone of nearby M dwarfs \\citep{Barclay2018}, some of which may be suitable targets for atmospheric characterization with JWST. In this work, we show that stellar XUV histories can be accurately inferred using machine learning \\citep[\\approxposterior, ][]{FlemingVanderPlas2018}, but using $980\\times$ less computational resources than traditional MCMC methods. This speed-up enables our methods to scale to additional stars that host potential targets for atmospheric characterization and is generalizable to a large number of applications, potentially enabling Bayesian statistical analyses that are otherwise intractable with traditional MCMC approaches, e.g. \\emcee \\citep{ForemanMackey2013}.\n\nWe describe our model and statistical methods in $\\S$~\\ref{sec:methods}. We present our results and demonstrate the ability of machine learning to reproduce our analysis in $\\S$~\\ref{sec:results}, and discuss the implications of our results in $\\S$~\\ref{sec:discussion}. In $\\S$~\\ref{sec:app}, we describe the \\approxposterior algorithm and discuss its convergence properties.\n\n\\section{Methods} \\label{sec:methods}\n\n\\subsection{Simulating XUV Evolution with \\vplanet} \\label{sec:model}\n\nWe simulate TRAPPIST-1's stellar evolution using the \\stellar module in \\vplanet\\footnote{\\vplanet is publicly available at \\href{https://github.com/VirtualPlanetaryLaboratory/vplanet}{https://github.com/VirtualPlanetaryLaboratory/vplanet}.} \\citep{Barnes2019}, which performs a bicubic interpolation over mass and age of the \\citet{Baraffe2015} stellar evolution tracks. The \\citet{Baraffe2015} models (also employed by both \\citet{Burgasser2017} and \\citet{vanGrootel2018} to constrain TRAPPIST-1's stellar properties) were computed for solar metallicity stars and hence are suitable for TRAPPIST-1 whose [Fe/H] is consistent with solar \\citep[][see also \\citet{Burgasser2017}]{Gillon2016}.\n\nWe assume TRAPPIST-1's L$_{XUV}$ evolution traces that of L$_{X}$ and use the \\citet{Ribas2005} model,\n\\begin{align}\n\\label{eqn:lxuv}\n\\frac{L_\\mathrm{XUV}}{L_\\mathrm{bol}} = \\left\\{\n\t\t\t\t\\begin{array}{lcr}\n\t\t\t\t\tf_\\mathrm{sat} &\\ & t \\leq t_\\mathrm{sat} \\\\\n\t\t\t\t\tf_\\mathrm{sat}\\left(\\frac{t}{t_\\mathrm{sat}}\\right)^{-\\beta_\\mathrm{XUV}} &\\ & t > t_\\mathrm{sat}\n\t\t\t\t\\end{array}\n\t\t\t\t\\right.,\n\\end{align}\nwhere $f_{sat}$ is the constant ratio of stellar XUV to bolometric luminosity during the saturated phase, $t_{sat}$ is the duration of the saturated phase, and $\\beta_{XUV}$ is the exponent that controls how steeply L$_{XUV}$ decays after saturation. In practice, we define $f_{sat} = \\log_{10}(L_{XUV}/L_{bol})$ and transform Eqn.~(\\ref{eqn:lxuv}) accordingly.\n\nNote that each \\vplanet simulation (and hence likelihood calculation, see $\\S$~\\ref{sec:mcmc:like}) in principle only requires interpolating the \\citet{Baraffe2015} $L_{bol}$ tracks and evaluating an explicit function of time to compute $L_{XUV}$, both computationally-cheap tasks. \\vplanet, however, is a general purpose code designed to simulate the evolution of an exoplanetary system and its host star by simultaneously integrating coupled ordinary differential equations and explicit functions of time that describe the evolution. This generalized structure requires numerous steps to facilitate physical couplings, such as validation steps and a host of intermediate calculations \\citep[for more details, see][]{Barnes2019}. Moreover, \\stellar simultaneously evolves a star's radius, effective temperature, radius of gyration, $L_{XUV}$, and rotation rate in addition to $L_{bol}$, adding computational overhead. Each \\vplanet simulation using \\stellar therefore lasts about 10s.\n\n% extra\n% The L$_{X}$ evolution of fully-convective stars follows the same broken power law model examined for partially-convective FGK stars \\citep{Wright2016,Wright2018}. \n\n\\subsection{Markov Chain Monte Carlo Analysis} \\label{sec:mcmc}\n\nWe use \\texttt{emcee}, a Python implementation of the affine-invariant Metropolis-Hastings MCMC sampling algorithm \\citep{ForemanMackey2013}, to infer posterior probability distributions for our model parameters that describe the evolution of TRAPPIST-1. These distributions are conditioned on observations of TRAPPIST-1, the activity evolution of late-type stars, and account for both observational uncertainties and correlations between parameters. Our model parameters that we fit for via MCMC comprise the state vector\n\\begin{equation} \\label{eqn:state}\n    \\textbf{x} = \\{m_{\\star}, f_{sat}, t_{sat}, \\mathrm{age}, \\beta_{XUV}\\},\n\\end{equation}\nwhere $m_{\\star}$ and age are the stellar mass and age, respectively, and the other parameters are defined by Eqn.~(\\ref{eqn:lxuv}). All of the code used to perform the simulations and analysis in this work is publicly available online.\\footnote{ \\href{https://github.com/dflemin3/trappist}{https://github.com/dflemin3/trappist}}\n\n\\subsection{Prior Probability Distributions} \\label{sec:mcmc:priors}\n\nSince we have few available observable properties of TRAPPIST-1 to use to condition our analysis ($L_{bol}$ and $L_{XUV}/L_{bol}$, see $\\S$~\\ref{sec:mcmc:like}), our prior probability distributions will strongly impact our results. We use previous studies and empirical data of late M dwarfs to assemble the best available constraints to serve as priors for our MCMC analysis. We list our adopted prior probability distributions in Table~\\ref{tab:priors}.\n\nFollowing \\citet{vanGrootel2018}, we rely on TRAPPIST-1's luminosity and age to constrain its mass. We therefore adopt a simple uniform prior of $m_{\\star} \\sim \\mathcal{U}(0.07, 0.11)$ M$_{\\odot}$. For the age, we use the empirical estimate for TRAPPIST-1 derived by \\citet{Burgasser2017}, age $\\sim \\mathcal{N}(7.6, 2.2^2)$ Gyr, as their thorough analysis considered both observations of TRAPPIST-1 and a host of empirical age indicators for ultracool dwarfs. This age distribution is consistent with \\citet{Gonzales2019} who conclude that TRAPPIST-1 is a field-age dwarf based on their spectral energy distribution modeling. We cap the maximum age we consider at 12 Gyr. Younger ages have been suggested based on TRAPPIST-1's activity \\citep[e.g.~$\\gsim 500$ Myr,][]{Bourrier2017b}, but here we argue that behavior is consistent with an extended saturation timescale.\n\nWe construct an empirical $f_{sat} = \\log_{10}(L_{XUV}/L_{bol})$ distribution from the sample of fully-convective, saturated M dwarfs with observed $L_{X}$ from \\citet{Wright2011}. For each star in the \\citet{Wright2011} sample, we follow \\citet{Wheatley2017} and estimate $L_{XUV}$ as a function of L$_{X}$ using Eqn.~(2) from \\citet{Chadney2015}. We find that the distribution is well-approximated by a normal distribution, $f_{sat} \\sim \\mathcal{N}(-2.92, 0.26^2)$, and we adopt it as our prior.  \n\nThe duration of the saturated phase is estimated to be $t_{sat} \\approx 100$ Myr for FGK stars \\citep{Jackson2012}. Studies of stellar activity of late type stars as a function of stellar age, or its proxy, rotation period, indicate that the activity lifetime, and hence duration of the saturated phase, is likely longer for later-type stars \\citep{Shkolnik2014,Wright2011,West2015}, with fully-convective M dwarfs potentially remaining active throughout their lifetimes \\citep[$t_{sat} \\gsim 7$ Gyr,][]{West2008,Schneider2018}. Furthermore, the spin-down timescales of late M dwarfs increases with decreasing stellar mass \\citep{Delfosse1998}, with late M dwarfs retaining rapid rotation longer than earlier-type stars and hence remaining active for up to $P_{rot} \\approx 86$ d \\citep{West2015}, much longer than TRAPPIST-1's estimated rotation period. Given these constraints, we adopt a broad uniform $t_{sat}$ prior distribution capped by the maximum age we consider, $t_{sat} \\sim \\mathcal{U}(0.1, 12)$ Gyr. \n\nIn the unsaturated phase, $L_{X}$, and hence $L_{XUV}$, decay exponentially with power law slope $\\beta_{XUV}$ \\citep{Ribas2005}. \\citet{Jackson2012} find that $\\beta_{XUV}$ does not significantly vary with stellar mass in their sample of FGK stars. Since \\citet{Wright2016} found that the X-ray evolution of fully-convective stars is qualitatively similar to that of partially-convective FGK stars, we adopt the $\\beta_{XUV}$ distribution of late K dwarfs from the \\citet{Jackson2012} sample as our prior, $\\beta_{XUV} \\sim \\mathcal{N}(-1.18, 0.31^2)$.\n\n\\begin{deluxetable}{lcc}\n\\tabletypesize{\\small}\n\\tablecaption{Prior Distributions \\label{tab:priors}}\n\\tablewidth{0pt}\n\\tablehead{\n\\colhead{Parameter [units]} & \\colhead{Prior} & \\colhead{Notes}\n}\n\\startdata\n$m_\\star$ [$M_{\\odot}$] & $\\mathcal{U}(0.07, 0.11)$ & -- \\\\  \n$f_{sat}$ & $\\mathcal{N}(-2.92, 0.26^2)$ & \\citet{Wright2011}  \\\\\n$t_{sat}$ [Gyr] & $\\mathcal{U}(0.1, 12)$ & -- \\\\\nage [Gyr] & $\\mathcal{N}(7.6, 2.2^2)$ & \\citet{Burgasser2017} \\\\\n$\\beta_{XUV}$ & $\\mathcal{N}(-1.18, 0.31^2)$ & \\citet{Jackson2012}\n\\enddata \n\\end{deluxetable}\n\n\\subsection{Likelihood Function and Convergence} \\label{sec:mcmc:like}\n\nWe further condition our analysis on TRAPPIST-1's observed bolometric luminosity, $L_{bol} = 5.22 \\pm{0.19} \\times 10^{-4} \\ L_{\\odot}$ \\citep[][but see also \\citet{Gonzales2019}]{vanGrootel2018}, and $L_{XUV}/L_{bol} = 7.5 \\pm{1.5} \\times 10^{-4}$ \\citep{Wheatley2017}. In other words, we require that our forward models (\\vplanet simulations) yield results that are consistent with the observations of TRAPPIST-1 and their uncertainties. \n\nFor a given state vector \\textbf{x}, we define the natural logarithm of our likelihood function, $\\ln \\mathcal{L}$, as\n\\small\n\\begin{equation} \\label{eqn:lnlike}\n    \\ln \\mathcal{L} \\propto -\\frac{1}{2} \\left[ \\frac{(L_{bol} - L_{bol}(\\textbf{x}))^2}{\\sigma_{L_{bol}}^2} + \\frac{(L_{XUV}/L_{bol} - L_{XUV}/L_{bol}(\\textbf{x}))^2}{\\sigma_{L_{XUV}/L_{bol}}^2} \\right] \\\\\n\\end{equation}\n\\normalsize\nwhere $L_{bol}$, $L_{XUV}/L_{bol}$ and $L_{bol}(\\textbf{x})$, $L_{XUV}/L_{bol}(\\textbf{x})$ are the observed values and \\vplanet outputs given \\textbf{x}, respectively, and $\\sigma_{L_{bol}}$ and $\\sigma_{L_{XUV}/L_{bol}}$ are the observational uncertainties. For each \\textbf{x}, we compute the natural logarithm of the posterior probability at $\\textbf{x}$, lnprobability, required for ensemble MCMC sampling as $f(\\textbf{x}) = \\ln \\mathcal{L}(\\textbf{x}) + \\ln \\mathrm{Prior}(\\textbf{x})$. We use the distributions described in $\\S$~\\ref{sec:mcmc:priors} to calculate the natural logarithm of the prior probability of \\textbf{x}, $\\ln \\mathrm{Prior}(\\textbf{x})$. \n\nWe run our MCMC with 100 parallel chains for 10,000 iterations, initializing each chain by randomly sampling each element of \\textbf{x} from their respective prior distributions. During each step of the MCMC chain, \\vplanet takes \\textbf{x} as input and simulates TRAPPIST-1's evolution up to the age in \\textbf{x}, predicting $L_{bol}$ and $L_{XUV}/L_{bol}$ to evaluate $\\ln \\mathcal{L}$. We discard the first 500 iterations as burn-in and assess the convergence of our MCMC chains by computing the integrated autocorrelation length and acceptance fraction for each chain. We find a mean acceptance fraction of 0.48 and a minimum and mean number of iterations per integrated autocorrelation length of 93 and 132, respectively, indicating that our chains have converged \\citep{ForemanMackey2013}. Given our integrated autocorrelation lengths, our MCMC chain yielded about 10,000 effective samples from the posterior distribution.\n\n\\subsection{Inference with \\approxposterior} \\label{sec:methods:approx}\n\nThe methods presented above can be applied to any late-type star to constrain its $L_{XUV}$ history, given suitable priors and observational constraints. Our MCMC analysis, however, required 4,070 core hours on the University of Washington's Hyak supercomputer to converge. The main computational cost is incurred by running a ${\\sim}10$s \\vplanet simulation each MCMC step to evaluate $\\ln \\mathcal{L}$, requiring ${\\sim}1,000,000$ simulations in total for the full MCMC analysis. Assuming similar convergence properties, repeating this analysis for even a modest sample of 30 stars would require~${\\sim} 122,000$ core-hours, a significant computational expense. Moreover, performing a similar analysis with a more computationally-expensive model would only exacerbate this issue.\n\nTo mitigate the computational cost, we apply \\approxposterior\\footnote{\\approxposterior is publicly available at \\href{https://github.com/dflemin3/approxposterior}{https://github.com/dflemin3/approxposterior}.}, an open source Python machine learning package \\citep{FlemingVanderPlas2018}, to compute an accurate approximation to the true MCMC-derived posterior distribution for TRAPPIST-1's XUV evolution. \\approxposterior, a modified implementation of the ``Bayesian Active Learning for Posterior Estimation\" (BAPE) algorithm of \\citet{Kandasamy2017}, trains a Gaussian process (GP, see \\citet{Rasmussen2006}) replacement for the lnprobability evaluation, learning on the results of \\vplanet simulations. The GP is then used within an MCMC sampling algorithm, e.g. \\emcee, to quickly obtain the posterior distribution. In our case, predicting the lnprobability using the GP (${\\sim} 130 \\mu$s) is $80,000 \\times$ faster than running \\vplanet (10s) each lnprobability evaluation, yielding a massive reduction in computational cost.\n\nFollowing \\citet{Kandasamy2017}, \\approxposterior iteratively improves the GP's predictive ability by identifying high-likelihood regions in parameter space, and hence high posterior density regions, where the GP predictions are uncertain. \\approxposterior then evaluates \\vplanet in those regions to supplement the training set, improving the GP's predictive ability in the relevant regions of parameter space, while minimizing the number of forward model evaluations required for suitable predictive accuracy. Similar techniques using a GP surrogate model have been shown to rapidly and accurately infer Bayesian posterior distributions for computationally-expensive cosmology studies \\citep[e.g.][]{Bird2019,McClintock2019}. \n\nTo model the covariance between points in the GP training set, we use a squared exponential kernel,\n\\begin{equation} \\label{eqn:kernel}\nk(x_i, x_j) = \\exp \\left( - \\frac{(x_i - x_j)^2}{2l^2} \\right),\n\\end{equation}\nwhere $x_i$ and $x_j$ are two arbitrary points in parameter space and $l$ is a hyperparameter that controls the scale length of the correlations. We assume correlations in each dimension have different scale lengths and fit for each $l$ by optimizing the GP's marginal likelihood of the training set data using Powell's method \\citep{Powell1964}, randomly restarting this optimization 10 times to mitigate the influence of local extrema. To ensure our solution is numerically stable, we add a small white noise term of $\\ln(\\sigma_{\\mathrm{w}}) = -15$ to the diagonal of the GP covariance matrix. \n\nWe initially trained the GP on a set of 50 \\vplanet simulations with initial conditions sampled from our prior distributions. We then ran \\approxposterior until it converged after 7 iterations. Each iteration, \\approxposterior selected 100 new training points according to the \\citet{Kandasamy2017} point selection criterion. \\approxposterior ran \\vplanet at each point for a total of 750 training samples. The trained GP was then used within \\emcee to quickly obtain the approximate posterior distribution following the same MCMC sampling procedure described above. In $\\S$~\\ref{sec:app}, we provide additional information about the \\approxposterior algorithm and its convergence properties.\n\n%% Results %%\n\n\\section{Results} \\label{sec:results}\n\n\\subsection{The Evolution of TRAPPIST-1}\n\nIn Fig.~\\ref{fig:corner}, we display the posterior probability distributions for our model parameters derived using MCMC with \\vplanet and \\emcee. We adopt the median values of the marginal distributions as our best-fit solutions and derive the lower and upper uncertainties using the 16th and 84th percentiles, respectively. We list these values in Table~\\ref{tab:constraints}.\n\nTRAPPIST-1 likely maintained a large $L_{XUV}$ throughout its lifetime as we find $f_{sat} = -3.03^{+0.23}_{-0.12}$ and $t_{sat} = 6.64^{+3.53}_{-3.13}$ Gyr, consistent with observed $L_{XUV}/L_{bol}$ and long activity lifetimes of late M dwarfs \\citep{West2008,Wright2018}. The long upper-tail in the marginal $f_{sat}$ distribution arises from the combination of the degeneracy between $f_{sat}$ and $t_{sat}$ and from our strong empirical $f_{sat}$ prior that disfavors $f_{sat} \\gsim -2.5$. The degeneracy stems from our model attempting to match TRAPPIST-1's observed $L_{XUV}/L_{bol}$. For example, larger values of $f_{sat}$ produce high initial $L_{XUV}/L_{bol}$, requiring shorter $t_{sat}$, and hence an earlier transition to unsaturated $L_{XUV}/L_{bol}$ decay, to decrease $L_{XUV}/L_{bol}$ to its observed value, and vice versa. \n\nAlthough our $t_{sat}$ prior distribution, based on empirical measurements of late M-dwarfs (see $\\S$~\\ref{sec:mcmc:priors}), equally favors both short and long saturation timescales, the marginal posterior density for $t_{sat}$ steeply declines for $t_{sat} \\lsim 4$ Gyr. This decline implies that ultracool dwarfs like TRAPPIST-1 likely remain saturated for many Gyrs. Our analysis strongly disfavors short saturation timescales, with only a $0.5\\%$ chance that $t_{sat} \\leq 1$ Gyr, the saturation timescale adopted by \\citet{Luger2015} in their analysis of water loss from exoplanets orbiting in the habitable zone of late M dwarfs and in \\citet{Lincowski2018}. From the posterior distribution, we infer that there is a $40\\%$ chance that TRAPPIST-1 is still in the high-$L_{XUV}/L_{bol}$ saturated phase today, suggesting that the TRAPPIST-1 planets could have undergone prolonged volatile loss.\n\n\\begin{figure*}[t]\n\\centering\n\t\\includegraphics[width=0.75\\textwidth]{trappist1Corner.pdf}\n   \\caption{Joint and marginal posterior probability distributions for the TRAPPIST-1 stellar parameters given in Eqn.~(\\ref{eqn:state}) made using \\texttt{corner} \\citep{ForemanMackey2016}. The black vertical dashed lines on the marginal distributions indicate the median values and lower and upper uncertainties from the 16th and 84th percentiles, respectively. The blue curves superimposed on the marginal distributions display the adopted prior probability distribution for each parameter. From the posterior, we infer that there is a $40\\%$ chance that TRAPPIST-1 is still in the saturated phase today.}%\n    \\label{fig:corner}%\n\\end{figure*}\n\nThe marginal age and $\\beta_{XUV}$ posterior distributions reflect their prior distributions as for the former, $L_{bol}$ is not sufficient to constrain TRAPPIST-1's age beyond our adopted prior because the luminosities of ultracool dwarfs do not significantly change during the main sequence \\citep{Baraffe2015}. The marginal posterior for $\\beta_{XUV}$ does not vary from the prior because our XUV model is over-parameterized with 3 parameters to fit 2 observations, although all are motivated by empirical data and hence merit inclusion. Our model prefers to exploit the degeneracy between $f_{sat}$ and $t_{sat}$ to match TRAPPIST-1's observed $L_{XUV}$ in our MCMC instead of varying the slope of the unsaturated $L_{XUV}$ decay. Even though our model is over-parameterized, the observations of TRAPPIST-1 used to condition our probabilistic model do in fact influence the posterior distribution as the reduction in posterior variance relative to the prior can be seen in the joint posterior and marginal distributions of Fig.~\\ref{fig:corner} for $m_{\\star}$, $f_{sat}$, and $t_{sat}$.\n\nIn the joint posterior distribution, age and $\\beta_{XUV}$ weakly correlate with $f_{sat}$, requiring a narrow spread of $f_{sat} \\approx -3.05$ for young ages and steeper $\\beta_{XUV}$, respectively. $\\beta_{XUV}$ and $t_{sat}$ are uncorrelated, except at short $t_{sat}$ where steep $\\beta_{XUV}$ are disfavored as this evolution would underpredict the observed $L_{XUV}$. We constrain TRAPPIST-1's mass to $m_{\\star} = 0.089 \\pm{0.001}$ M$_{\\odot}$, in a good agreement with and $6\\times$ more precise than the value derived by \\citet{vanGrootel2018}. In $\\S$~\\ref{sec:evol}, we consider how this mass constrain impacts TRAPPIST-1's predicted radius.\n\nFinally, we estimate the Monte Carlo standard error (MCSE) for each model parameter. The MCSE does not reflect the inherent probabilistic uncertainty in our model that arises from conditioning on data with uncertainties, but rather it approximates the error incurred by estimating parameters using an ensemble of MCMC chains of finite length. Using the batch means method \\citep{Flegal2008,Flegal2010}, we find MCSEs for $m_{\\star}$, $f_{sat}$, $t_{sat}$, age, and $\\beta_{XUV}$ of $3.41 \\times 10^{-6}$, $1.23 \\times 10^{-3}$, $2.0 \\times 10^{-2}$, $1.30 \\times 10^{-2}$, and $2.12 \\times 10^{-3}$, respectively. These errors are much less than the posterior uncertainty and can be safely ignored.\n\n%% approxposterior %%\n\n\\subsection{Comparison with \\approxposterior} \\label{sec:approx}\n\n% Extra\n%If using a slower model than ours, perhaps one that models stellar evolution by interpolating tracks over mass, age, and metallicity to additionally constrain [Fe/H], or if testing alternate models of $L_{XUV}$ evolution for model comparisons, the computational expense will grow, exacerbating this issue.\n\n\\begin{figure*}\n\\centering\n\t\\includegraphics[width=0.75\\textwidth]{apCorner.pdf}\n   \\caption{Same format as Fig.~\\ref{fig:corner}, but derived by \\approxposterior. \\approxposterior recovered constraints and parameter correlations that are in good agreement with the \\emcee MCMC, but requiring $980\\times$ less computational resources.}%\n    \\label{fig:approx}%\n\\end{figure*}\n\nWe compare the approximate posterior distribution derived using \\approxposterior with our previous results (referred to as the fiducial MCMC). We display the approximate joint and marginal posterior distributions in Fig.~\\ref{fig:approx} and list the marginal constraints derived by both methods in Table~\\ref{tab:constraints}.\n\nAs seen in Fig.~\\ref{fig:approx}, \\approxposterior recovers the non-trivial correlations between model parameters seen in the fiducial MCMC posterior distribution. We emphasize this good agreement by overplotting the \\approxposterior estimated posterior distribution (blue) on top of the fiducial MCMC results (black) in Fig.~\\ref{fig:stacked}.\n\nOur parameter constraints derived using \\approxposterior are in good agreement with those inferred using \\emcee. We find average errors in parameter medians and $1\\sigma$ uncertainties of $0.61\\%$ and $5.5\\%$, respectively, relative to the constraints deriving using \\emcee. These differences are larger than the MCSEs because the GP employed by \\approxposterior is an accurate, yet imperfect, surrogate for the lnprobability calculation. \\approxposterior tends to underestimate parameter uncertainties by a few percent because its algorithm preferentially selects high-likelihood points to expand its training set (see $\\S$~\\ref{app:augment}). This concentration of high-likelihood points slightly biases the inferred GP scale lengths, $l$, towards smaller values, effectively overfitting. The smaller values of $l$ shrink the estimated posterior distribution, producing the underestimated parameter uncertainties. We mitigate this effect by adding a small white noise term to the diagonal of the GP covariance matrix.\n\nNot only can \\approxposterior accurately recover Bayesian parameter constraints and correlations, it does so extremely quickly. \\approxposterior requires only about 4 core hours to estimate the approximate posterior distribution, a factor of $980\\times$ faster than our fiducial MCMC. Moreover, \\approxposterior used $1330\\times$ fewer \\vplanet simulations to build its training set than the ${\\sim}10^6$ simulations ran by the fiducial MCMC for likelihood evaluations. This reduction in computational expense arises from a combination of \\approxposterior's GP-based lnprobability predictions only taking ${\\sim}130\\mu$s, compared to the much longer $10$s per \\vplanet simulation, and its intelligent iterative training set augmentation algorithm. \\approxposterior's efficient selection of the GP's training set focuses on high-likelihood regions to improve the GP's predictive ability in relevant regions of parameter space while minimizing the training set size.\n\n\\begin{figure*}\n\\centering\n\t\\includegraphics[width=0.75\\textwidth]{stacked.pdf}\n   \\caption{Same format as Fig.~\\ref{fig:corner}, but with the fiducial posterior distribution in black and the \\approxposterior-derived posterior distribution in blue. The joint and marginal posterior distributions estimated by \\approxposterior are in excellent agreement with our fiducial \\emcee-derived results.}%\n    \\label{fig:stacked}%\n\\end{figure*}\n\nOur findings demonstrate that \\approxposterior can be used to estimate accurate approximations to the posterior probability distributions of the parameters that control stellar XUV evolution in late M dwarfs, but significantly faster than traditional MCMC methods. Note that \\approxposterior is agnostic to the underlying forward model it learns on, enabling Bayesian parameter inference with other computationally-expensive forward models.\n\n% deprecated\n% The posterior distribution derived by \\approxposterior, however, is not an exact match. \\approxposterior underestimates the magnitude of both the age and $\\beta_{XUV}$ uncertainties by ${\\sim}30\\%$ and predicts that there is a $39\\%$ chance that TRAPPIST-1 is still saturated today, $9\\%$ smaller than the fiducial MCMC-derived value.\n\n\\begin{deluxetable*}{lcccc}\n\\caption{Parameter Constraints and Errors} \\label{tab:constraints}\n\\tabletypesize{\\small}\n\\tablehead{\n\\colhead{Parameter [units]} & \\colhead{\\vplanet-\\emcee MCMC} & \\colhead{\\approxposterior MCMC} & \\colhead{\\approxposterior Relative Error} & \\colhead{Monte Carlo Error}\n}\n\\startdata\n$m_\\star$ [$M_{\\odot}$] & $0.089^{+0.001}_{-0.001}$ &  $0.089^{+0.001}_{-0.001}$ & ${<}0.1\\%$ & $3.41\\times 10^{-6}$ \\\\  \n$f_{sat}$ & $-3.03^{+0.23}_{-0.12}$ & $-3.03^{+0.23}_{-0.12}$ & ${<}0.1\\%$ & $1.23\\times 10^{-3}$  \\\\\n$t_{sat}$ [Gyr] & $6.64^{+3.53}_{-3.13}$ & $6.76^{+3.52}_{-3.10}$ & $1.81\\%$ & $2.0\\times 10^{-2}$ \\\\\nage [Gyr] & $7.46^{+2.01}_{-2.10}$ & $7.57^{+1.87}_{-1.93}$ & $1.47\\%$ & $1.30 \\times 10^{-3}$ \\\\\n$\\beta_{XUV}$ & $-1.16^{+0.31}_{-0.30}$ & $-1.15^{+0.29}_{-0.29}$ & $0.86\\%$ & $2.12\\times 10^{-3}$ \\\\\nP$(\\mathrm{saturated})$ & $0.40$ & $0.39$ & $2.5\\%$ & $3.30 \\times 10^{-3}$ \\\\\n\\enddata \\vspace*{0.1in}\n\\tablecomments{Best fit values and uncertainties are derived using the medians, $16^{th}$, and $84^{th}$ percentiles from the marginal posterior distributions, respectively. P$(\\mathrm{saturated})$ indicates the posterior probability that TRAPPIST-1 is still in the saturated regime today. The relative errors are computed as the absolute percent difference between the best fit values derived by \\emcee and \\approxposterior. The \\approxposterior-derived results are in good agreement with the fiducial \\emcee MCMC.}\n\\end{deluxetable*}\n\n\\subsection{TRAPPIST-1's Evolutionary History and Its Planets' XUV Environment} \\label{sec:evol}\n\nHere we consider plausible stellar evolutionary histories for TRAPPIST-1 by simulating 100 samples from the posterior distribution. We plot the evolution of TRAPPIST-1's $L_{bol}$, $L_{XUV}$, and radius in Fig.~\\ref{fig:evol} and compare our models to the measured values. \n\n\\begin{figure*}[t]\n\t\\includegraphics[width=\\textwidth]{trappist1Evol.pdf}\n   \\caption{Plausible evolutionary histories of TRAPPIST-1's $L_{bol}$ (left), $L_{XUV}$ (center), and radius (right) using 100 samples drawn from the posterior distribution and simulated with \\vplanet. In each panel, the blue shaded regions display the 1, 2, and 3 $\\sigma$ uncertainties. The insets display the marginal distributions (black) evaluated at the age of the system, with the blue dashed lines indicating the observed value and +/- 1 $\\sigma$ uncertainties. The radius, $L_{bol}$, and $L_{XUV}$ constraints are adopted from \\citet{vanGrootel2018} and \\citet{Wheatley2017}, respectively, by convolving the \\citet{vanGrootel2018} $L_{bol}$ measurement with the $L_{XUV}/L_{bol}$ constraints from \\citet{Wheatley2017}.}%\n    \\label{fig:evol}%\n\\end{figure*}\n\nTRAPPIST-1 remains saturated throughout its $1$ Gyr-long pre-main sequence, with both $L_{XUV}$ and $L_{bol}$ decreasing by a factor of ${\\sim}40$ before stabilizing on the main sequence. TRAPPIST-1's radius likely shrank by roughly a factor of 4 along the pre-main sequence. We derive a present-day radius $R_{\\star} = 0.112 \\pm{0.001} \\ R_{\\odot}$ from the posterior distribution, a value that is ${\\sim} 7\\%$ smaller than the \\citet{vanGrootel2018} constraint, $R_{\\star} = 0.121 \\pm {0.003} \\ R_{\\odot}$, that was computed from their inferred mass and TRAPPIST-1's density \\citep{Delrez2018}. This difference arises from the likely underprediction of TRAPPIST-1's radius by the \\citet{Baraffe2015} models, consistent with stellar evolution models often underestimating the radii of late M dwarfs \\citep{Reid2005,Spada2013}. \n\nAn alternate explanation to account for its inflated radius is that TRAPPIST-1 has super-solar metallicity \\citep{Burgasser2017,vanGrootel2018}, but \\citet{vanGrootel2018} found in their modeling that TRAPPIST-1 required a metallicity of [Fe/H] = 0.4 to reproduce its density and radius. \\citet{vanGrootel2018} show that as this result is $4.5\\sigma$ off from the best fit value from \\citet{Gillon2016}, who found [Fe/H] $= 0.04 \\pm{0.08}$. The super-solar hypothesis is therefore strongly disfavored by the observational data. If we instead compute the radius from our marginal stellar mass posterior distribution and the observed density \\citep{Delrez2018}, we obtain $R_{\\star} = 0.120 \\pm{0.002} \\ R_{\\odot}$, in agreement with \\citet{vanGrootel2018} who used the same procedure.\n\nSince TRAPPIST-1 could still be saturated today, its planetary system has likely experienced a persistent extreme XUV environment. In Fig.~\\ref{fig:fluxes}, we probe the distribution of XUV fluxes, $F_{XUV}$, derived from our posterior distributions for each TRAPPIST-1 planet when the system was 0.01, 0.1, and 1 Gyr old. We normalize these values by the $F_{XUV}$ received by Earth during the mean solar cycle \\citep[$F_{XUV,\\oplus} = 3.88$ erg s$^{-1}$cm$^{-2}$,][]{Ribas2005} and assume the planets remained near their current semi-major axes after migration in the natal protoplanetary disk halted \\citep{Luger2017}. \n\nWe infer that TRAPPIST-1b likely received extreme $F_{XUV}/F_{XUV, \\oplus} \\gsim 10^4$ during the early pre-main sequence before decaying to the present-day $F_{XUV}/F_{XUV, \\oplus} \\approx 10^3$, consistent with estimates from \\citet{Wheatley2017}. The extended upper-tail of the $F_{XUV}$ distributions corresponds to the large $f_{sat}$ values permitted by the posterior distributions. The likely habitable zone planets, e, f, and g, similarly experienced severe XUV fluxes ranging from $F_{XUV}/F_{XUV, \\oplus} \\approx 10^2 - 10^{3.5}$ throughout the pre-main sequence. Even today, e, f, and g receive $F_{XUV}/F_{XUV, \\oplus} \\approx 10^2$, far in excess of the modern Earth, due to TRAPPIST-1's large present $L_{XUV}$, its extended saturated phase, and the close proximity of M dwarf HZ planets to their host star. These significant high energy fluxes likely drove an extended epoch of substantial atmospheric escape and water loss from the TRAPPIST-1 planets, potentially producing substantial abiotic O$_2$ atmospheres \\citep{Luger2015,Bolmont2017,Bourrier2017a}.\n\n\\begin{figure}\n\t\\includegraphics[width=0.98\\columnwidth]{fluxes.pdf}\n   \\caption{$F_{XUV}/F_{XUV,\\oplus}$ for each TRAPPIST-1 planet derived from samples drawn from the posterior distribution and simulated using \\vplanet when the system was 0.01, 0.1, and 1 Gyr old. The latter age corresponds to the approximate age at which TRAPPIST-1 entered the main sequence. The TRAPPIST-1 planetary system has likely endured a long-lasting extreme XUV environment.}%\n    \\label{fig:fluxes}%\n\\end{figure}\n\n%% Discussion %%\n\n\\section{Discussion and Conclusions} \\label{sec:discussion}\n\nHere, we used MCMC to derive probabilistic constraints for TRAPPIST-1's stellar and $L_{XUV}$ evolution to characterize the evolving XUV environment of its planetary system. We inferred that TRAPPIST-1 likely maintained high $L_{XUV}/L_{bol} \\approx 10^{-3}$ throughout its lifetime, with a $40\\%$ chance that TRAPPIST-1 is still in the saturated regime today. Our results indicate that at least some ultracool dwarfs can sustain large $L_{XUV}$ in the saturated regime for Gyrs, consistent with activity lifetimes of late M dwarfs \\citep{West2008}. We suggest that studies of volatile loss from planets orbiting ultracool dwarfs model the long-term $L_{XUV}$ evolution of the host star, or at least assume saturation timescales of $t_{sat}{\\gsim}4$ Gyrs. Our choice of prior distributions strongly impacts our results as our inference hinges on only two measured properties of TRAPPIST-1, $L_{XUV}$ and $L_{bol}$. To mitigate this effect, we consulted previous studies and empirical observations of the activity evolution of late M dwarfs to construct realistic prior distributions.\n\nThe TRAPPIST-1 planets likely experienced significant XUV fluxes during the pre-main sequence, potentially driving extreme atmospheric erosion and water loss \\citep{Bolmont2017,Bourrier2017a}. The high-energy fluxes incident on the inner-most planets throughout this phase were probably large enough for atmospheric mass loss to be recombination-limited ($F_{UV} \\gsim 10^4$ g s$^{-1}$ cm$^{-2}$) and scale as $\\dot{m} \\sim F_{XUV}^{0.6}$ \\citep{MurrayClay2009}, as opposed to the oft-assumed energy-limited escape \\citep[$\\dot{m} \\sim F_{XUV}$,][]{Watson1981,Lammer2003}, potentially inhibiting volatile loss. If the TRAPPIST-1 planets did lose significant amounts of water as our estimates suggest, they must have formed with a large initial volatile inventory to account for their observed low densities \\citep{Grimm2018}.\n\nWe demonstrated that the open source Python machine learning package, \\approxposterior \\citep{FlemingVanderPlas2018}, can efficiently compute an accurate approximation to the posterior distribution using an adaptive learning GP-based method, requiring $1330\\times$ fewer \\vplanet simulations and a factor of $980\\times$ less core hours than traditional MCMC approaches. The posterior distributions derived by \\approxposterior reproduced the non-trivial parameter correlations and best-fit values uncovered by our fiducial MCMC analysis. We find that \\approxposterior recovers the best-fit values and $1\\sigma$ uncertainties of our model parameters with an average error of $0.61\\%$ and $5.5\\%$, respectively, relative to our constraints derived using \\emcee. If future observations of TRAPPIST-1 refine its fundamental parameters, and possibly $L_{XUV}/L_{bol}$, \\approxposterior can be used to rapidly and accurately replicate our analysis to update our constraints.  \n\nFinally, we note that our methodology constrains parameters that describe the long-term XUV evolution of TRAPPIST-1, conditioned on measurements. In principle, this approach can be extended to obtain evolutionary histories of planetary systems in general.  For example, in Figures~\\ref{fig:evol} and \\ref{fig:fluxes}, we examined the long-term evolution of TRAPPIST-1 and the evolving XUV fluxes received by its planetary system, respectively, with samples drawn from the posterior distribution. Future research can combine those results with additional physical effects, e.g. water loss or tidal dissipation, to build a probabilistic model for the long-term evolution of the planetary system, given our model for the underlying physics, to characterize its present state. In other words we could infer the evolutionary history of a planet or planetary system given suitable observational constraints. While simulating additional physical effects will inevitably increase the computational expense, we have demonstrated that \\approxposterior can enable such efforts and provide insight into the histories of stars and their planets.\n\n% Extra\n% \\xxx{Applying these methods to other M dwarfs, however, requires measuring their current $L_{X}$ or $L_{XUV}$, a difficult task given that most M and ultracool dwarfs are faint and that much of the stellar EUV radiation is absorbed by neutral interstellar hydrogen \\citep{Airapetian2019}. These quantities, however, can be reconstructed via empirical scaling relations \\citep[e.g.][]{Linsky2014}. The accuracy and massive reduction in compute time afforded by \\approxposterior enables our analysis to scale to a larger sample of late M dwarfs to constrain their XUV histories.}\n\n\n%% ACKNOWLEDGEMENTS %%\n\\acknowledgments\nWe thank the anonymous referee for their careful reading of our manuscript and insightful comments. This work was facilitated though the use of advanced computational, storage, and networking infrastructure provided by the Hyak supercomputer system and funded by the Student Technology Fund at the University of Washington. DPF was supported by NASA Headquarters under the NASA Earth and Space Science Fellowship Program - Grant 80NSSC17K0482.  This work was supported by the NASA Astrobiology Program Grant Number 80NSSC18K0829 and benefited from participation in the NASA Nexus for Exoplanet Systems Science research coordination network.\n\n%% SOFTWARE %%\n\\software{\\approxposterior: \\citet{FlemingVanderPlas2018}, \\texttt{corner}: \\citet{ForemanMackey2016}, \\texttt{emcee}: \\citet{ForemanMackey2013}, \\texttt{george}: \\citet{george}, \\vplanet: \\citet{Barnes2019}} \n\n\\appendix\n\\approxposterior is an implementation of the ``Bayesian Active Posterior Estimation\" (BAPE) algorithm developed by \\citet{Kandasamy2017}, but with several modifications to afford the user more control over the inference. Below, we qualitatively describe this algorithm, define parameters, and suggest typical values. We then discuss \\approxposterior's convergence scheme.\n\n\\section{\\approxposterior Algorithm and Convergence} \\label{sec:app}\n\nQualitatively, the \\approxposterior algorithm is as follows. First, assume a forward model with $d$ input parameters that is designed to reproduce some set of observations. In our case, $d$, the dimensionality of parameter space, is five. The model parameters have an input domain, $D$, that is defined by the user. The parameters are further described by a prior probability distribution based on the user's prior belief for how the model parameters are distributed.  Next, the user generates a training set, $T$, consisting of $m_0$ forward model simulations distributed across the parameter space. The user chooses how the $m_0$ samples are distributed throughout parameter space according to their preferred experimental design. \\approxposterior then trains a GP on $T$ to construct a non-parametric model (sometimes called a ``surrogate model\") that represents the outcomes of the forward model over the parameter space. Crucially, GPs also generate an uncertainty for the surrogate model at every point in parameter space.\n\n\\approxposterior then identifies $m$ more locations in parameter space to apply the forward model and add to $T$. The new locations are selected by determining the regions that the GP has identified as having both a high lnprobability, i.e. high posterior density, and a high predictive uncertainty. This selection is accomplished by maximizing a utility function ($u$, described below) that quantifies where the GP predicts high posterior density and high uncertainty in parameter space, focusing resources on parameter combinations that are likely to be consistent with the observations. \\approxposterior re-trains the GP with the augmented $T$. The GP is then passed to an MCMC algorithm, e.g. \\emcee, that samples the parameter space to obtain the approximate posterior distributions of the model parameters.\n\nAt the end of each iteration, \\approxposterior checks if a convergence condition (described in $\\S$~\\ref{sec:app:convergence}) has been met. If the algorithm  has not yet converged, \\approxposterior selects an additional $m$ new points to add to $T$, re-trains the GP, and again estimates the posterior distribution. This process repeats until convergence or until \\approxposterior has run the maximum number of iterations, $n_{max}$, set by the user. In Algorithm~\\ref{app:algo}, we list the aforementioned steps that comprise this algorithm.\n\n\\begin{algorithm} \\label{app:algo}\n\\SetAlgoLined\n Assume an input domain $D$, GP prior on $f(\\textbf{x})$ \\\\\n Generate a training set, $T$, consisting of $m_0$ pairs of $(\\textbf{x}, f(\\textbf{x}))$ \\\\\n \\For{$t=0, 1, ..., n_{\\mathrm{max}}$}{\n    \\For{$i=0, 1, ..., m$}{\n      Find \\textbf{x}$^+$ = argmax$_{\\textbf{x} \\in D}$ $u(\\textbf{x})$ \\\\\n       Compute $f(\\textbf{x$^+$})$ \\\\\n       Append $(\\textbf{x$^+$}, f(\\textbf{x$^+$}))$ to $T$ \\\\\n       Re-train GP, optimize GP hyperparameters given augmented $T$ \\\\\n   }\n   Use MCMC to obtain approximate posterior distribution with GP surrogate for $f(\\textbf{x})$ \\\\\n   \\If{$\\mathrm{converged}$}{\n        \\textbf{break} \\\\\n    }\n }\n\\caption{\\approxposterior Approximate Inference Pseudo Code}\n\\end{algorithm}\n\nIn Algorithm~\\ref{app:algo}, we define $f(\\textbf{x}) = \\mathcal{\\ln L}(\\textbf{x})$ + $\\ln \\mathrm{Prior}(\\textbf{x})$ as the lnprobability function used for MCMC sampling with \\emcee and \\textbf{x}$^+$ as the point in parameter space selected by maximizing $u$. For our application, evaluating $f(\\textbf{x})$ requires running a \\vplanet simulation to compute $\\mathcal{\\ln L}(\\textbf{x})$ (see $\\S$~\\ref{sec:mcmc:like}). By placing a GP prior with a squared exponential kernel on $f(\\textbf{x})$, we assume that the function is smooth and continuous, both reasonable assumptions for modeling the posterior density. For inference problems that are liable to violate these assumptions, other kernels, e.g. the Ornstein-Uhlenbeck kernel, may be more appropriate (we refer the reader to \\citet{Rasmussen2006} for detailed descriptions of common GP kernels and their mathematical properties). \\approxposterior uses \\texttt{george} \\citep{george} for all GP calculations and hence users can apply any kernels implemented in that software package. \n\n\\approxposterior has several free parameters that can be set by the user: $m_0$, the size of the initial training set (50 in our case), $n_{\\mathrm{max}}$, the maximum number of iterations (15), $m$, the number of new points to select each iteration where the forward model will be evaluated (100 per iteration), and $\\epsilon$, the convergence threshold (0.1). Typically, we find that $n_{\\mathrm{max}}=2-3 \\times d$, $m, m_0 = 10-20 \\times d$, and $\\epsilon = 0.1$ work well in practice, although performance may vary depending on the use case. For a complete list of \\approxposterior parameters, we refer the reader to the online documentation.\\footnote{ \\href{https://dflemin3.github.io/approxposterior}{https://dflemin3.github.io/approxposterior/}}\n\nNote that \\approxposterior does not linearly transform the parameter space to the unit hypercube as did \\citet{Kandasamy2017}. Moreover, \\approxposterior does not fix the covariance scale lengths, instead opting to estimate all GP kernel hyperparameters by maximizing the marginal likelihood of the GP, given its training set, at a user-specified cadence. In Algorithm~\\ref{app:algo}, we optimize the GP hyperparameters each time a new point is added to the training set, but in practice we found this is unnecessary, especially at later iterations when the GP has developed a reasonable approximation of the posterior. The authors prefer to optimize the GP hyperparameters twice per iteration, once after half of the $m$ new points have been selected, and again after all $m$ points have been selected.\n\n\\subsection{Augmenting the Training Set} \\label{app:augment}\n\nEach iteration, \\approxposterior selects $m$ new points to add to the GP's training set by maximizing the utility function, $u$. To motivate the choice of $u$, consider the following argument based on \\citet{Kandasamy2017}: \\approxposterior assumes that the forward model the GP learns on, here \\vplanet via $\\ln \\mathcal{L}$, is computationally-expensive to run, and hence \\approxposterior seeks to minimize the number of forward model evaluations required to build its training set. For inference problems, it is natural to select high-lnprobability regions in parameter space to augment the GP training set as this is where the posterior density is large. Furthermore, selecting regions in parameter space where the GP's predictive uncertainty is already small offers little value, compared to regions where its predictions are more uncertain, as additional points in low-uncertainty regions are unlikely to alter the GP's predictions.\n\nWith these considerations in mind, \\citet{Kandasamy2017} leverage the analytic properties of GPs to derive the ``exponentiated variance\" utility function, given by their Eq.~(5)\n\\begin{equation} \\label{app:eq:bape}\n    u_{\\textrm{EV}}(\\textbf{x}) = \\exp(2 \\mu_t(\\textbf{x}) + \\sigma_t^2(\\textbf{x}))(\\exp(\\sigma_t^2(\\textbf{x})) - 1),\n\\end{equation}\nwhere $\\mu_t(\\textbf{x})$ and $\\sigma_t^2(\\textbf{x})$ are the mean and variance of the GP's predictive conditional distribution evaluated at \\textbf{x}, respectively, for the $t^{th}$ \\approxposterior iteration. To select each point, we maximize Eqn.~(\\ref{app:eq:bape}) using the Nelder-Mead method \\citep{Nelder1965}. Note that this optimization is rather cheap since it only requires evaluating the GP's predictive conditional distribution, so this task is not a significant computational bottleneck. We restart this optimization 5 times to reduce the influence of local extrema. Note that in practice, we optimize the natural logarithm of the utility function to ensure numerical stability.\n\n\\begin{figure*}[h]\n\\centering\n\t\\includegraphics[width=0.75\\textwidth]{points.pdf}\n   \\caption{Same as Fig.~\\ref{fig:approx}, but overplotted with the training set for \\approxposterior's GP. The orange points display the initial training points whereas the blue points display the points iteratively selected by maximizing the \\citet{Kandasamy2017} utility function, Eqn.~(\\ref{app:eq:bape}). By design, \\approxposterior selected points to expand its training set in regions of high posterior density, improving its GP's predictive accuracy in the most relevant regions of parameter space while seldom wasting computational resources in the low likelihood regions.}%\n    \\label{fig:points}%\n\\end{figure*}\n\nAs demonstrated in \\citet{Kandasamy2017}, Eqn.~(\\ref{app:eq:bape}) identifies high-likelihood points where the GP's predictions are uncertain, significantly reducing the cost of training an accurate GP surrogate model. We highlight this behavior for our own application in Fig.~\\ref{fig:points} by displaying the approximate posterior distribution derived by \\approxposterior from Fig.~\\ref{fig:approx} overplotted with the initial training set in orange and the points selected by sequentially maximizing Eqn.~(\\ref{app:eq:bape}) in blue. Given the small initial training set, \\approxposterior successfully selects high-posterior density points in parameter space to augment the GP's training set. Some points are selected in low-likelihood regions early on, typically near the edges of parameter space where the GP's uncertainty was initially large.\n\n% extra\n%\\xxx{\\citet{Wang2018} derive the entropy-based utility function (``Adaptive Gaussian Process\", AGP) that is designed to select the point \\textbf{x} that, when added to the GP training set $T$, maximizes the information gain for the inference problem. The \\citet{Wang2018} utility function given by their Eq.~(7)}\n%\\begin{equation} \\label{app:eq:agp}\n%    u_{\\textrm{AGP}}(\\textbf{x}) = \\mu_t(\\textbf{x}) + \\frac{1}{2}\\ln{(2\\pi e \\sigma_t^2(\\textbf{x}))}\n%\\end{equation}\n%where $e$ is Euler's number.\n\n\\subsection{Convergence} \\label{sec:app:convergence}\n\nWe assess the convergence of the \\approxposterior algorithm by comparing the means of the approximate marginal posterior distributions over successive iterations. We consider an \\approxposterior run ``converged\" if the differences between the marginal posterior means, relative to the widths of the marginal posteriors, are less than a tolerance parameter, $\\epsilon$, for $k_{max}$ consecutive iterations. Effectively, this criterion checks if the expected value of each model parameter over the posterior distribution varies by ${\\leq}{\\epsilon}$ standard deviations from the previous iteration's expected values. That is, we require the \\approxposterior convergence diagnostic $z_{t,j}{\\leq}{\\epsilon}$ for all $j$, where\n\\begin{equation}\n    z_{t,j} = |\\mu_{t,j} - \\mu_{t-1,j}| / \\sigma_{t-1,j},\n\\end{equation}\n and $\\mu_{t,j}$ and $\\sigma_{t,j}$ are the mean and standard deviation of the approximate marginal posterior distribution for the $t^{th}$ iteration and the $j^{th}$ parameter. This quantity is analogous to the ``z-score\" commonly used in many statistical tests. Following \\citet{Wang2018}, we require this condition to be satisfied for $k_{max}$ consecutive iterations to ensure \\approxposterior is producing a consistent result. With this scheme, \\approxposterior tolerates deviations from the previous estimate that are less than, or at least consistent with, the previous values, given the inherent uncertainty implied by the width of the posterior distribution. For our application, we adopted conservative choices of $\\epsilon = 0.1$ and $k_{max} = 5$. Each \\approxposterior iteration, we also visually inspected the estimated posterior distribution to ensure convergence. \n\nIn Fig.~\\ref{fig:convergence}, we display the convergence diagnostic quantity, $z_t$, as a function of iteration for each model parameter for the \\approxposterior run presented in the main text. \\approxposterior quickly finds a consistent result as $z_t$ decreases below our convergence threshold within the first few iterations. For each parameter, $z_t$ continues to decrease until iteration 3 before stabilizing. The evolution of $z_t$ is not monotonic, however, owing to the stochastic nature of GPs, our hyperparameter optimization scheme, and MCMC sampling that can cause these values to occasionally be slightly worse than previous iterations. Requiring convergence over $k_{max}$ consecutive iterations mitigates the impact of this stochasticity.\n\n\\begin{figure*}[h]\n\\centering\n\t\\includegraphics[width=0.75\\textwidth]{convergence.pdf}\n   \\caption{The \\approxposterior convergence diagnostic, $z_t$, as a function of iteration for the run presented in the main text. Note that in \\approxposterior, the initial iteration is iteration 0. The black dashed line indicates our adopted convergence threshold of $\\epsilon = 0.1$. \\approxposterior quickly converges to a consistent and accurate result.}%\n    \\label{fig:convergence}%\n\\end{figure*}\n\n% extra\n% \\xxx{We validate our approximate inference procedure by applying \\approxposterior to a synthetic 5-dimensional test case designed to reflect the computational difficulties encountered in our science application, i.e. learning and approximating non-Gaussian posterior distributions (see $\\S$~\\ref{sec:approx}). Our goal for this experiment is to assess \\approxposterior's accuracy relative to canonical MCMC methods, e.g. \\emcee, and quantify any biases that may exist in our approximate methods.}\n% \\xxx{We adopt Eqn.~(\\ref{eqn:rosenbrock}) with $d=5$ as our likelihood function for this experiment and apply a uniform prior over $[-5,5]$ for each $x_i$. Using \\emcee, we first draw samples from the posterior distribution using 100 parallel walkers for 10,000 iterations. Then, we replicate this inference with \\approxposterior using the exact same MCMC procedure as our \\emcee case. The results of this experiment are discussed and compared below.}\n% \\xxx{In this experiment, we infer the posterior probability distribution of a $d$-dimensional state vector, \\textbf{x}, using MCMC with both \\emcee and \\approxposterior got a synthetic test example. For our test likelihood function, we use a multidimensional-generalization of the analytic, non-linear Rosenbrock function \\citep{Rosenbrock1960}. The Rosenbrock function is commonly used as a test case for both optimization \\citep[e.g.][]{Rosenbrock1960} and GP-based approximate inference problems \\citep[e.g.][]{Wang2017}. This function is useful for our purposes because, when used as a likelihood function, it encodes non-trivial correlations between parameters that produce non-Gaussian posterior distributions, presenting a challenge for \\approxposterior that is qualitatively similar to that posed by our science application. Following the transformation from \\citet{Wang2017}, we define the Rosenbrock function for $d$ dimensions as}\n%\\begin{equation} \\label{eqn:rosenbrock}\n%f(\\textbf{x}) = -\\sum_{i=1}^{d-1} \\left[ (x_{i+1} - x_i^2)^2 + 0.01(1-x_i)^2 \\right]\n%\\end{equation}\n%\\xxx{where \\textbf{x} is the state vector and $x_i$ is the $i^{th}$ element of \\textbf{x}.} \n%\\xxx{At the final iteration, we find percent errors between medians of the \\approxposterior and fiducial MCMC marginal distributions of $0.027\\%$, $-0.0048\\%$, $-1.7\\%$, $-0.95\\%$, and $-0.64\\%$ for the five parameters in \\textbf{x}, respectively. Similarly for the errors on the $1\\sigma$ uncertainties at the final iteration, we find $-0.23\\%$, $3.6\\%$, $0.83\\%$, $9.6\\%$, and  $8.95\\%$.}\n\n\n%% BIBLIOGRAPHY %%\n\n\\bibliography{trappist}\n\n% End of file\n\\end{document}", "meta": {"hexsha": "cfb0e1fbfaaa83b56086079a9d9cd1163b03649e", "size": 62513, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Paper/arxiv/trappist.tex", "max_stars_repo_name": "dflemin3/trappist", "max_stars_repo_head_hexsha": "1aeb273f49678d685addc540cd4444ff045bc601", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-12T18:51:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-12T18:51:46.000Z", "max_issues_repo_path": "Paper/arxiv/trappist.tex", "max_issues_repo_name": "dflemin3/trappist", "max_issues_repo_head_hexsha": "1aeb273f49678d685addc540cd4444ff045bc601", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Paper/arxiv/trappist.tex", "max_forks_repo_name": "dflemin3/trappist", "max_forks_repo_head_hexsha": "1aeb273f49678d685addc540cd4444ff045bc601", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-08T18:49:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-08T18:49:03.000Z", "avg_line_length": 150.2716346154, "max_line_length": 1881, "alphanum_fraction": 0.7778542063, "num_tokens": 16379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.30426586654281007}}
{"text": "\\section{Non-equilibrium Green function}\n\n\\begin{framenologo}\n  \\frametitle{Non-equilibrium Green function}\n  \\tableofcontents[currentsection]\n\\end{framenologo}\n\n\\subsection{Density matrix}\n\n\\begin{frame}\n  \\frametitle{Density matrix}\n  \\framesubtitle{Recollection of basic equations}\n\n  \\begin{block}{Basic equations for Green function techniques}\n    \\vskip-2ex\n\\input{../equations.tex}\n  \\end{block}\n\n\\end{frame}\n\n\\begin{frame}\n  \\frametitle{Density matrix}\n  \\framesubtitle{Equilibrium}\n\n  \\begin{itemize}\n    \\item All electrodes have same Fermi-distribution and here the density is easily\n    calculated using \\emph{only} the Green function\n  \\end{itemize}\n\n  \\begin{block}<+->{Equilibrium density matrix $V=0$}\n    \\vskip -2ex\n    \\begin{align*}\n      \\DM &= \\frac1{2\\pi}\\iint_\\BZ\\dEBZ\\cd \\kk \\dd\\E\\, %\n      \\G_\\kk \\sum_\\idxE\\Scat_{\\idxE,\\kk} \\G^\\dagger_\\kk\\eikr n_F(\\E) %\n      \\\\\n      \\DE &= \\frac i{2\\pi}\\iint_\\BZ\\dEBZ\\cd \\kk\\dd\\E\\, %\n      \\G_\\kk \\big[\\SE_{\\kk}-\\SE^\\dagger_{\\kk} \\big]\n      \\G^\\dagger_\\kk\\eikr n_F(\\E) & \\SE_\\kk = \\sum_\\idxE \\SE_{\\idxE,\\kk} %\n      \\\\\n      \\DE & = \\frac i{2\\pi}\\iint_\\BZ\\dEBZ\\cd \\kk\\dd\\E\\, %\n      \\G_\\kk \\left[%\n        \\G^{\\dagger,-1}_\\kk - \\G^{-1}_\\kk + 2i\\eta\\SO_\\kk %\n      \\right]\\G^\\dagger_\\kk\\eikr n_F(\\E)\n      \\\\\n      \\DE & = \\frac i{2\\pi}\\iint_\\BZ\\dEBZ\\cd \\kk\\dd\\E%\n      \\left[\\G_\\kk  - \\G^\\dagger_\\kk + 2i\\eta\\G_\\kk\\SO_\\kk\\G^\\dagger_\\kk %\n      \\right]\\eikr n_F(\\E)\n      \\\\\n      &\\approxeq \\frac i{2\\pi}\\iint_\\BZ\\dEBZ\\cd \\kk\\dd\\E%\n      \\left[\\G_\\kk  - \\G^\\dagger_\\kk \\right]\\eikr n_F(\\E)\n    \\end{align*}\n  \\end{block}\n  \n\\end{frame}\n\n\n\\begin{frame}\n  \\frametitle{Density matrix}\n  \\framesubtitle{Non-equilibrium}\n\n  \\begin{itemize}\n    \\item Electrodes \\emph{may} have different Fermi-distribution (at least two different)\n  \\end{itemize}\n\n  \\begin{block}<+->{Non-equilibrium density matrix $V\\neq0$}\n    \\begin{itemize}\n      \\item Non-equilibrium density may conveniently be split into an equilibrium part and\n      a non-equilibrium ``correction''\n    \\end{itemize}\n    \\begin{align*}\n      \\DM &= \\frac1{2\\pi}\\iint_\\BZ\\dEBZ\\cd \\kk \\dd\\E\\, %\n      \\G_\\kk \\sum_\\idxE\\Scat_{\\idxE,\\kk} \\G^\\dagger_\\kk\\eikr n_{F,\\idxE}(\\E) %\n      \\\\\n      \\DM=\\DE^\\idxE+\\DN^\\idxE &=\\DE^\\idxE+\n      \\frac1{2\\pi}\\sum_{\\idxE'\\neq\\idxE}\\iint_\\BZ\\dEBZ\\cd \\kk\\dd\\E\\, %\n      \\G_\\kk \\Scat_{\\idxE',\\kk}\n      \\G^\\dagger_\\kk\\eikr\\big[n_{F,\\idxE'}(\\E)-n_{F,\\idxE}(\\E)\\big]\n      \\uncover<3->{\n      \\\\\n      \\DM=\\DE^\\varsigma+\\DN^\\varsigma &=\\DE^\\varsigma+\n      \\frac1{2\\pi}\\sum_{\\idxE'\\neq\\varsigma}\\iint_\\BZ\\dEBZ\\cd \\kk\\dd\\E\\, %\n      \\G_\\kk \\Scat_{\\idxE',\\kk}\n      \\G^\\dagger_\\kk\\eikr\\big[n_{F,\\idxE'}(\\E)-n_{F,\\varsigma}(\\E)\\big]\n      }\n    \\end{align*}\n    \\begin{itemize}\n      \\item<+-> %\n      Note that if two electrodes have the same Fermi-distribution we have\n      $n_{F,\\idxE}=n_{F,\\idxE'}$\n\n      \\item<+-> %\n      Enables the reduction of ($N_\\idxE$) different equations to the number of different\n      chemical potentials ($N_\\varsigma$)\n\n    \\end{itemize}\n\n  \\end{block}\n  \n\\end{frame}\n\n\n\\subsection{Numeric integration}\n\n\\begin{frame}\n  \\frametitle{Numeric integration}\n  \\framesubtitle{Equilibrium}\n\n  Calculation of $\\DE^\\varsigma$:\n\n  \\begin{center}\n    \\def\\eta{0.1}%\n    \\def\\radius{3.25}%\n    \\def\\lineS{-1}%\n    \\def\\poles{4}%\n    \\def\\poleSep{.25}%\n    % Calculate alpha angle\n    \\pgfmathparse{\\poleSep*(\\poles+.5)/\\radius}%\n    \\edef\\betaA{\\pgfmathresult}%\n    \\pgfmathparse{atan(\\betaA)}%\n    \\edef\\alphaA{\\pgfmathresult}%\n    \\pgfmathparse{asin(\\betaA)}%\n    \\edef\\betaA{\\pgfmathresult}%\n    \\begin{tikzpicture}[scale=.75]\n      \n      % The axes\n      \\begin{scope}[draw=gray!80!black,thick,->]\n        \\draw (-2*\\radius+\\lineS-.5,0) -- (\\radius+1.5,0) node[text=black,below] {$E$};\n        \\draw (0,0) -- (0,\\radius+.5) node[text=black,left] {$\\Im$};\n      \\end{scope}\n      \\node[below] at (0,0) {$\\mu$};\n      \n      % The specific coordinates on the path\n      \\coordinate (EB) at (-2*\\radius+\\lineS,\\eta);\n      \\coordinate (C-mid) at ({-\\radius+\\lineS-sin(\\alphaA)*\\radius},{cos(\\alphaA)*\\radius});\n      \\coordinate (C-end) at (\\lineS,{\\poleSep*(\\poles+.5)});\n      \\coordinate (L-end) at (\\radius,{\\poleSep*(\\poles+.5)});\n      \\coordinate (L-end-end) at (\\radius+1,{\\poleSep*(\\poles+.5)});\n      \\coordinate (real-L-end) at (\\radius,\\eta);\n      \\coordinate (real-L-end-end) at (\\radius+1,\\eta);\n      \n      \\begin{scope}[thick]\n        \n        % The path (we draw it backwards)\n        \\draw[->-=.3,very thick] (L-end) -- node[above right] \n        {$\\mathcal L$} (C-end);\n        \\draw[->-=.333,->-=.666,very thick] (C-end) to[out=90+\\betaA,in=\\alphaA] (C-mid)\n        node[above] \n        {$\\mathcal C$}\n        to[out=180+\\alphaA,in=90] (EB);\n        \\draw[->-=.25,->-=.75] (EB) -- (real-L-end) node[above left] {$\\mathcal R$};\n\n        % draw the continued lines\n        \\draw[densely dotted] (real-L-end) -- (real-L-end-end);\n        \\draw[densely dotted] (L-end) -- (L-end-end);\n\n      \\end{scope}\n      \n      % Draw the poles\n      \\foreach \\pole in {1,...,14} {\n          \\ifnum\\pole>\\poles\n          \\draw (0,\\pole*\\poleSep) circle (2pt);\n          \\else\n          \\fill (0,\\pole*\\poleSep) circle (2pt);        \n          \\fi\n      }\n      \\node[left,anchor=east] at (0,{\\poleSep*(\\poles/2+.5)}) {$z_\\nu$};\n\n      % correct size\n      \\path[use as bounding box] (-8,-.5) rectangle ++(13,4.5);\n\n      \\draw[densely dotted] (real-L-end-end) to[out=0,in=0] (L-end-end);\n      \\draw[densely dotted,thick] (EB) -- ++(-.5,0);\n\n      \\uncover<2->{\n          \\begin{scope}\n            \\def\\muS{.5}%\n            \\node[below] at (\\muS,0) {$\\mu'$};\n\n            \n      % The specific coordinates on the path\n      \\coordinate (EB) at (-2*\\radius+\\lineS+\\muS,\\eta);\n      \\coordinate (C-mid) at ({-\\radius+\\lineS-sin(\\alphaA)*\\radius+\\muS},{cos(\\alphaA)*\\radius});\n      \\coordinate (C-end) at (\\lineS+\\muS,{\\poleSep*(\\poles+.5)});\n      \\coordinate (L-end) at (\\radius+\\muS,{\\poleSep*(\\poles+.5)});\n      \\coordinate (L-end-end) at (\\radius+1+\\muS,{\\poleSep*(\\poles+.5)});\n      \\coordinate (real-L-end) at (\\radius+\\muS,\\eta);\n      \\coordinate (real-L-end-end) at (\\radius+1+\\muS,\\eta);\n      \n      \\begin{scope}[thick,color=good]\n        \n        % The path (we draw it backwards)\n        \\draw[->-=.3,very thick] (L-end) -- node[above right] \n        {$\\mathcal L$} (C-end);\n        \\draw[->-=.333,->-=.666,very thick] (C-end) to[out=90+\\betaA,in=\\alphaA] (C-mid)\n        node[above] \n        {$\\mathcal C$}\n        to[out=180+\\alphaA,in=90] (EB);\n        \\draw[->-=.25,->-=.75] (EB) -- (real-L-end) node[above left] {$\\mathcal R$};\n\n        % draw the continued lines\n        \\draw[densely dotted] (real-L-end) -- (real-L-end-end);\n        \\draw[densely dotted] (L-end) -- (L-end-end);\n\n      \\end{scope}\n      \n      % Draw the poles\n      \\foreach \\pole in {1,...,14} {\n          \\ifnum\\pole>\\poles\n          \\draw (\\muS,\\pole*\\poleSep) circle (2pt);\n          \\else\n          \\fill (\\muS,\\pole*\\poleSep) circle (2pt);        \n          \\fi\n      }\n\n      \\draw[densely dotted] (real-L-end-end) to[out=0,in=0] (L-end-end);\n      \\draw[densely dotted,thick] (EB) -- ++(-.5,0);\n    \\end{scope}\n\n}\n\n    \\end{tikzpicture}\n  \\end{center}\n\n  \\begin{equation*}\n    \\oint\\cd \\E = \n    \\textcolor{good}{\\int_{\\mathcal{R}}\\cd \\E} +\n    \\int_{\\mathcal{L}}\\cd \\E +\n    \\int_{\\mathcal{C}}\\cd \\E\n    = \n    i2\\pi \\sum_\\nu z_\\nu\n  \\end{equation*}\n\n  \\vskip 1em\n  Applying the residue theorem from complex analysis.\n\n\\end{frame}\n\n\\begin{frame}\n  \\frametitle{Numeric integration}\n  \\framesubtitle{Equilibrium}\n\n  \\begin{block}{Example of numeric integration of equilibrium contour}\n    \\begin{itemize}\n      \\item Ensure the lowest integrated energy is \\emph{far} below the lowest\n      eigenvalue of your system\n    \\end{itemize}\n    \n    \\begin{center}\n      \\begin{tikzpicture}[scale=.8]\n        \\begin{axis}[width=14cm,height=8cm,name=circ,only marks,\n          ymin=0,ymax=15.5,xmin=-31,xmax=1.5,\n          xtick={-28,-24,-20,-16,-12,-8,-4},\n          extra x ticks={0.25},extra x tick label={$\\mu$},\n          xlabel={Real Energy [eV]},\n          ylabel={Imaginary Energy [eV]}]\n          \\addplot table {../data/EQ_circle.dat};\n          \\addplot table {../data/EQ_fermi.dat};\n          \\addplot table {../data/EQ_pole.dat};\n          \\draw[densely dashed,green!50!black,very thick] (axis cs:-30,0.1) --\n          (axis cs:2,0.1);\n          \\draw[->,>=latex] (axis cs:-.5,0) -- (axis cs:-8.75,2.2);\n          \\draw[->,>=latex] (axis cs:-.5,1.25) -- (axis cs:-8.75,10.75);\n          \\node[rotate=35] at (axis cs:-21.5,11.5) {Gauss-Legendre};\n        \\end{axis}\n        \\begin{axis}[width=6cm,height=5cm,only marks,\n          at={($(circ.south)+(0,1cm)$)},anchor=south,\n          xtick={-0.5,0,0.5},\n          extra x ticks={0.25},extra x tick label={$\\mu$},\n          xmin=-.5,xmax=.75,ymin=0,ymax=1.3]\n          \\addplot table {../data/EQ_circle.dat};\n          \\addplot table {../data/EQ_fermi.dat};\n          \\addplot table {../data/EQ_pole.dat};\n          \\draw[<->] (axis cs:.3,0.568494) -- node[sloped,anchor=south] {$2\\pi k_BT$} (axis cs:.3,0.406067);\n          \\draw[densely dashed,green!50!black,very thick] \n          (axis cs:-1,0.03) -- (axis cs:1,0.03);\n          \\node[anchor=south] at (axis cs:0.25,1) {Gauss-Fermi};\n          \\node[rotate=90,anchor=south] at (axis cs:0.25,.5) {Poles};\n        \\end{axis}\n      \\end{tikzpicture}\n\n    \\end{center}\n  \\end{block}\n\n\\end{frame}\n\n\n\\pgfplotsset{my c/.style={/tikz/color=#1, /tikz/fill=#1}}\n\n\\begin{frame}\n  \\frametitle{Numeric integration}\n  \\framesubtitle{Algorithms}\n\n  \\begin{block}{Quadrature methods}\n    TranSiesta implements a wide range of quadrature methods\n    \\begin{itemize}[<+->]\n      \\item Newton-Cotes quadratures\n      \\item Gauss-Legendre\n      \\begin{itemize}[<.->]\n        \\item<+-> Even quadrature method ($-x_{-i} = x_i$)\n        \\item Opportunity to only integrate half of the interval\n      \\end{itemize}\n      \\item Continued fraction\n      \\item \\dots\n    \\end{itemize}\n  \\end{block}\n\n  \\begin{center}\n    \\begin{tikzpicture}[scale=.8]\n      \\begin{axis}[width=17cm,height=8cm,only marks,\n        ymin=0,ymax=20.5,xmin=-41,xmax=1.5,\n        xtick={-36,-32,-28,-24,-20,-16,-12,-8,-4},\n        xlabel={Real Energy [eV]},\n        ylabel={Imaginary Energy [eV]}]\n        \\only<1>{\n        \\addplot+[my c=red!70!black] table {../data/siesta_30_simpson.dat};}\n        \\only<2>{\n        \\addplot+[my c=blue!70!black] table {../data/siesta_30_legendre.dat};}\n        \\only<3->{\n        \\addplot+[my c=green!70!black] table {../data/siesta_30_legendre_right.dat};}\n      \\end{axis}\n    \\end{tikzpicture}\n  \\end{center}\n  \n  \\doicite{Papior \\etal: \\doi{10.1016/j.cpc.2016.09.022}}\n\n\\end{frame}\n\n\n\\begin{frame}\n  \\frametitle{Numeric integration}\n  \\framesubtitle{Non-equilibrium}\n\n  \\begin{block}{Example of numeric integration of non-equilibrium contour}\n    The non-equilibrium density is conceptually much easier:\n    \\begin{equation*}\n      \\DN \\propto n_{F,\\idxE}(\\E) - n_{F,\\idxE'}(\\E)\n    \\end{equation*}\n\n    \\begin{center}\n      \\begin{tikzpicture}[scale=.8]\n        \\begin{axis}[width=15cm,height=8cm,\n          ymin=0,ymax=2,xmin=-1,xmax=1,gen/.style={only marks,opacity=.7},\n          xlabel={Energy [eV]},\n          ylabel={Weight}]\n          \\only<1>{\n              %\\addplot[gen,bad,domain=-.3:.3,samples=25] {1./(exp((x-0.25)/0.01) + 1)-\n              %    1./(exp((x+0.25)/0.01) + 1)};\n              \\addplot[gen,good,domain=-.55:.55,samples=30] {1./(exp((x-0.5)/0.01)\n                  + 1)- 1./(exp((x+0.5)/0.01) + 1)};\n              %\\draw[<->,bad,very thick] (axis cs:-.25, 0.3) -- (axis cs:.25,0.3) node[midway,above]\n              %{$n_F(\\E+0.25\\,\\mathrm{eV}) - n_F(\\E-0.25\\,\\mathrm{eV})$};\n              \\draw[<->,good,very thick] (axis cs:-.5, 1.3) -- (axis cs:.5,1.3) node[midway,above]\n              {$n_F(\\E+0.5\\,\\mathrm{eV}) - n_F(\\E-0.5\\,\\mathrm{eV})$};\n              \\node[below left] at (rel axis cs:.9,.9) {2 different $\\mu$};\n          }\n          \\only<2>{\n              \\addplot[gen,ok,domain=-.05:0.55,samples=25] {1./(exp((x-0.5)/0.01)+1)-1./(exp((x)/0.01)+1)};\n              \\addplot[gen,good,domain=-.55:.55,samples=30] {1./(exp((x-0.5)/0.01)+1)-1./(exp((x+0.5)/0.01)+1)};\n              \\addplot[gen,bad,domain=-.55:.05,samples=25] {1./(exp((x)/0.01)+1)- 1./(exp((x+0.5)/0.01)+1)};\n              \\draw[<->,very thick,bad] (axis cs:-.5, 0.6) -- (axis cs:0,0.6) node[midway,above] \n              {$n_F(\\E) - n_F(\\E-0.5\\,\\mathrm{eV})$};\n              \\draw[<->,very thick,ok] (axis cs:0, 0.2) -- (axis cs:0.5,0.2) node[midway,above]\n              {$n_F(\\E+0.5\\,\\mathrm{eV}) - n_F(\\E)$};\n              \\draw[<->,very thick,good] (axis cs:-.5, 1.3) -- (axis cs:.5,1.3) node[midway,above]\n              {$n_F(\\E+0.5\\,\\mathrm{eV}) - n_F(\\E-0.5\\,\\mathrm{eV})$};\n\n              \\node[below left] at (rel axis cs:.9,.9) {3 different $\\mu$};\n          }\n\n        \\end{axis}\n      \\end{tikzpicture}\n    \\end{center}\n  \\end{block}\n\n\\end{frame}\n\n\n% Skip the last summation of results page\n\\endinput\n\n\\begin{frame}\n  \\frametitle{Non-equilibrium Green function}\n  \\footnotesize\n\n  \\vskip -2ex\n  \\begin{columns}\n\n    \\column{.5\\textwidth}\n    \\begin{block}{Basic equations}\n      \\vskip-2ex\n\\input{../equations.tex}\n    \\end{block}\n\n    \\column{.5\\textwidth}\n    \\begin{block}{Local Density of States}\n      \\vskip-2ex\n      \\begin{align*}\n        \\rho_{\\nu}(\\E) &= -\\frac1\\pi\\Im[\\G(\\E) \\SO]_{\\nu} = \\sum_\\idxE\\rho_\\nu^\\idxE(\\E) +\n        \\text{bound states}\n        \\\\\n        \\rho_{\\nu}^{\\idxE}(\\E) &= \\frac1{2\\pi}\\Re[\\Spec_\\idxE(\\E) \\SO]_{\\nu}\n      \\end{align*}\n    \\end{block}\n\n  \\end{columns}\n\n  \\begin{block}{Density matrix using non-equilibrium Green functions}\n    \\vskip -2ex\n    \\begin{align*}\n      \\DM &=\\frac1{2\\pi}\n      \\iint_\\BZ\\dEBZ\\cd \\kk \\dd\\E\\, \\sum_\\idxE\\Spec_{\\idxE,\\kk}(\\E) n_{F,\\idxE}(\\E)\n      \\eikr\n      \\\\\n      \\DM^\\varsigma &=\\frac i{2\\pi}\\iint_\\BZ\\dEBZ\\cd \\kk\\dd\\E%\n      \\left[\\G_\\kk  - \\G^\\dagger_\\kk \\right]\\eikr n_{F,\\varsigma}(\\E)\n      +\n      \\frac1{2\\pi}\\sum_{\\idxE|\\varsigma_\\idxE\\neq\\varsigma}\\iint_\\BZ\\dEBZ\\cd \\kk\\dd\\E\\, %\n      \\G_\\kk \\Scat_{\\idxE,\\kk}\n      \\G^\\dagger_\\kk\\eikr\\big[n_{F,\\varsigma_\\idxE}(\\E)-n_{F,\\varsigma}(\\E)\\big]\n      & \\text{$\\varsigma = \\{\\mu, k_BT\\}$}\n    \\end{align*}\n  \\end{block}\n\n  \\begin{block}{Transmission}\n    \\vskip-2ex\n    \\begin{columns}\n      \n      \\column{.45\\linewidth}\n      \\begin{align*}\n        \\T_{\\idxE\\mto\\idxE'}(\\E) &=\n        \\Tr\\big[\\Scat_{\\idxE'}(\\E)\\G(\\E)\\Scat_{\\idxE}(\\E)\\G^\\dagger(\\E)\\big]\\quad\\text{, for $\\idxE\\neq\\idxE'$}\n        \\\\\n        \\T_{\\idxE}(\\E) &\\equiv\\sum_{\\idxE'\\neq\\idxE}\\T_{\\idxE\\mto\\idxE'} (\\E)\n        \\\\\n        \\RE_\\idxE(\\E) & %=\\mathbf 1 -\\T_\\idxE (\\E)\n        = \\mathbf 1 -\\Big\\{\n        \\im \\Tr\\big[(\\G(\\E)-\\G^\\dagger(\\E))\\Scat_\\idxE(\\E)\\big]\n        -\\Tr[\\Scat_\\idxE(\\E) \\G(\\E)\\Scat_\\idxE(\\E)\\G^\\dagger(\\E)]\n        \\Big\\}\n        \\\\\n        I_{\\idxE\\mto\\idxE'} &= \\frac{e^2}{h}\\iint\\cd\\E\\dd\\kk\\, \\T_{\\idxE\\mto\\idxE'}(\\E)[n_{F,\\idxE}(\\E) - n_{F,\\idxE'}(\\E)].\n      \\end{align*}\n\n      \\column{.41\\linewidth}\n      \\vskip -2em\n      \\begin{equation*}\n        \\JJ_{\\idxE,\\nu\\mu} = \\frac e h \\Im\\big[\n        \\Spec_{\\idxE,\\nu\\mu}(\\HH_{\\mu\\nu} - \\E\\SO_{\\mu\\nu})\n        -\n        \\Spec_{\\idxE,\\mu\\nu}(\\HH_{\\nu\\mu} - \\E\\SO_{\\nu\\mu})\\big]\n      \\end{equation*}\n\n    \\end{columns}\n  \\end{block}\n  \n\\end{frame}\n\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: \"talk\"\n%%% End:\n", "meta": {"hexsha": "1c1ce4bb5f776c8deb500c67fd1c4380383902f0", "size": 15480, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ts-tbt-sisl-tutorial-master/presentations/03/negf.tex", "max_stars_repo_name": "rwiuff/QuantumTransport", "max_stars_repo_head_hexsha": "5367ca2130b7cf82fefd4e2e7c1565e25ba68093", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-25T14:05:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-25T14:05:45.000Z", "max_issues_repo_path": "ts-tbt-sisl-tutorial-master/presentations/03/negf.tex", "max_issues_repo_name": "rwiuff/QuantumTransport", "max_issues_repo_head_hexsha": "5367ca2130b7cf82fefd4e2e7c1565e25ba68093", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-03-31T03:17:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-31T03:17:38.000Z", "max_forks_repo_path": "ts-tbt-sisl-tutorial-master/presentations/03/negf.tex", "max_forks_repo_name": "rwiuff/QuantumTransport", "max_forks_repo_head_hexsha": "5367ca2130b7cf82fefd4e2e7c1565e25ba68093", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-27T10:27:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-17T10:18:18.000Z", "avg_line_length": 33.43412527, "max_line_length": 124, "alphanum_fraction": 0.5486434109, "num_tokens": 5784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.30426586654281007}}
{"text": "\\chapter{Representing IACT data}\n%\nIACTs aim at reconstructing the energy, source position and particle type of\ncosmic rays via their Cherenkov-light. The Cherenkov-light flashes that are\nonly nano seconds in duration are measured and can be separated from background\nlight from stars or ambient light by their brightness and topology within the\ncamera image. There are different ways to represent air-shower data. FACT uses\nthe so called largest-pulse representation (LP), whereas this work focuses on a novel\ndata format, both of which are described in the following chapter.\n\n\\section{The Largest-Pulse representation}\n%\nData taken by an Imaging Air Cherenkov Telescope, like FACT, is usually represented in so called time series.\nThese time series owe their name to the fact that they represent voltages at\nthe photosensors over time. Within these time series lie so called large- or main-pulses\nthat represent the increased voltage that a charge deposition of an air-shower\ncauses. So, by looking for those main-pulses, shower events can be found upon\nthe detector noise and ambient light in the camera. Of course, the main-pulses\nconsist of multiple photon signals and noise superposed over time, but in this\nstate they are electric pulses representing the response of very specific\nhardware. So rather than measuring physical properties, this means that the\ncharge deposit has to be interpretated to be transferred into physics\nobservables, independent of these specifics.\nSuch interpretations always include assumptions of physical and technical\nkinds. By integrating the charge in one pixel an equivalent of a photon count\ncan be obtained, called the \\textit{photon equivalent} (PE). So the first\nobservable in this representation is the PE which corresponds to the best\nestimate of the number of photons measured per pixel. The photon counts are\nspatially located by the corresponding pixel they are assigned to. The 1440\npixels of FACT are the determining grid that yield the spatial coordinates of\nevery shower event.\n\nThe second observable is the time. When the telescope is triggered and records\ndata the arrival time of the event is measured via the time information within\nthe time series. From the time series a quantized timing information per pixel\ncan be developed by dividing the event into time slices. From this the arrival\ntime of the photons per pixel can be calculated by averaging.\n\nThus, the arrival times $t$ per pixel are the second observable of the LP event\nrepresentation, besides the photon-equivalents.\n\n\\begin{figure}\n  \\begin{subfigure}{0.475\\textwidth}\n    \\includegraphics[width=1.1\\textwidth, page=40]{Plots/cleaning_facttools_pe_20131104_162.pdf}\n  \\end{subfigure}\n  \\begin{subfigure}{0.475\\textwidth}\n    \\includegraphics[width=1.1\\textwidth, page=40]{Plots/cleaning_facttools_arrival_times_20131104_162.pdf}\n  \\end{subfigure}\n  \\caption{The measured observables of the LP representation are shown as scatter plots within the pixels. On the left the distribution of photon-equivalents $c$ of a typical shower event (Crab observation on November, 4th 2013, run 162, event 80) is shown. On the right the arrival times of that event's photons with respect to the mean arrival time in ns are displayed.}\n  \\label{fig:mainpulse}\n\\end{figure}\n\n\\section{The PhotonStream representation}\n\\label{sec:phs}\n%\nThe PhotonStream representation aims at creating a data format consisting of photons by storing their observed physical properties. This data representation, its extraction from the data and the cleaning process are based on Sebastian Mueller's work \\cite{sebastian, photonstream, phs}. From the measured time series single photons are extracted instead of deriving photon counts in pixels. Each of these photons is assigned an arrival time and pixel, creating a list of arrival times per photon for each pixel. By doing so, a 3-dimensional data set is created, which can be represented in form of so called point clouds (\\autoref{fig:point_cloud}).\n%\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=0.95\\textwidth]{Plots/event2.png}\n  \\caption{Uncleaned event represented by the 3-dimensional point cloud of the Photonstream. Every blue sphere represents a measured photon in the corresponding time slice and pixel.}\n  \\label{fig:point_cloud}\n\\end{figure}\n%\n\\subsection{Single Photon Extraction}\n%\nTo generate the PhotonStream data from the measured time series, single photons\nneed to be found and extracted. FACT is sampling recorded events with a\nfrequency of $\\SI{2}{\\giga\\hertz}$. This yields a very high time resolution, but still quantized values within the time series. The time series consists of multiple signals\nof single photons and different kinds of noise. Among the latter are several\nelectronic artifacts. The photon extraction does not take such artifacts into\naccount, so the data has to be cleaned of those at first. Unfortunately there\nare rare kinds of artifacts that can not be handled and may remain in the\ncalibrated data.\n\nThe transformation of data to the PhotonStream consists of two steps:\n%\n\\begin{enumerate}\n  \\item find single photons and determine their arrival times\n  \\item subtract those photons from the time series until only noise is left\n\\end{enumerate}\n%\nTo achieve this, two templates are used. Firstly, the ideal template of a\nsingle photon pulse $T_1$ is generated. It represents the discharge-pulse of a\nGAPD when measuring a photon. This template is used to subtract found photons\nfrom the remaining time series. To find these pulses the rising edge of that\ntemplate is used. This template $T_2$ represents the first\n$\\SI{10}{\\nano\\second}$ of $T_1$. This way, the detector's specific responses can be cancelled out.\n\nTo extract all photons from a time series an iterative algorithm is used, that\nfinds rising edges of single photons and then extracts the full photon pulse\n$T_1$. An example is shown in \\autoref{fig:extraction}.\n%\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=\\textwidth]{Plots/example_extraction_seed_5.png}\n  \\caption{Example of the photon extraction from a calibrated time series (generated by the single photon extractor~\\cite{singlephs}). Shown are several steps of the iterative extraction for the time series of a single pixel. The top frame shows the full time series as returned from the calibration process. The red vertical line shows the time position of the first found photon. After subtracting the photon pulse template $T_1$, the series as shown in the frame below remains, where another photon is found at the same position (red vertical line). The extraction continues until the time series in the bottom frame remains, which is considered noise. The extracted photon arrival times represent the PhotonStream for this specific pixel.}\n  \\label{fig:extraction}\n\\end{figure}\n%\n\\newpage\nRed vertical lines\nindicate the time position of a found rising edge template $T_2$. The time\nseries of a single pixel is correlated with $T_2$ to find the maximum of that\ncorrelation. The response is defined as\n%\n\\begin{equation}\n  R[t] = A_\\text{pixel}[t]\\cdot T_2[t] \\, .\n\\end{equation}\n%\nThe maximum of the response is identified as the arrival time of a photon pulse.\nAfter such a pulse has been found, the full photon pulse template $T_1$ is\nsubtracted. The remaining time series is then searched for further photon\npulses until only noise is left. The stopping-criterion defining the last\niteration step is reached when the maximum of the response $R[t]$ drops below\nhalf of the maximum of the response to a single-pulse.\nEvery found arrival time of a photon is written to a list containing the\nPhotonStream for the specific event and pixel.\n", "meta": {"hexsha": "f7f2d15e2bf7ac944dc6a90b6e71c262c47dc8d1", "size": 7667, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "content/05_iact_data.tex", "max_stars_repo_name": "KevSed/Master-Thesis", "max_stars_repo_head_hexsha": "89175c8acef3c982a6c79ab641cd150f1cd91621", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "content/05_iact_data.tex", "max_issues_repo_name": "KevSed/Master-Thesis", "max_issues_repo_head_hexsha": "89175c8acef3c982a6c79ab641cd150f1cd91621", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "content/05_iact_data.tex", "max_forks_repo_name": "KevSed/Master-Thesis", "max_forks_repo_head_hexsha": "89175c8acef3c982a6c79ab641cd150f1cd91621", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 64.4285714286, "max_line_length": 743, "alphanum_fraction": 0.801617321, "num_tokens": 1730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.30426586654281007}}
{"text": "%%% lecture 06 %%%\n\\documentclass{beamer}\n\\usepackage[utf8]{inputenc}\n\\usepackage{algorithm2e, amsmath, amssymb, amsfonts, graphicx}\n% allow section.equation numbering\n\\numberwithin{equation}{section}\n% use boadilla theme\n\\usetheme{Boadilla}\n% remove navigation symbols\n\\usenavigationsymbolstemplate{}\n% get numbered figure captions\n\\setbeamertemplate{caption}[numbered]\n% changes itemize to circle + other things\n\\useoutertheme{split}\n\\useinnertheme{circles}\n\n% command for the title string. change for each lecture\n\\newcommand{\\lecturetitle}{Intro to Optimization, Part 1}\n% allow automatic alert-highlighted references and hyperlinks\n\\newcommand{\\aref}[1]{\\alert{\\ref{#1}}}\n\\newcommand{\\ahref}[2]{\\href{#1}{\\alert{#2}}}\n% title page stuff. brackets content displayed in footer bar\n\\title[\\lecturetitle]{\\lecturetitle}\n% metadata. content in brackets is displayed in footer bar\n\\author[Derek Huang (BAC Advanced Team)]{Derek Huang}\n\\institute{BAC Advanced Team}\n\\date{December 30, 2021}\n\n% change \"ball\" bullet to numbered bullet and section title for section\n\\setbeamertemplate{section in toc}{\\inserttocsectionnumber.~\\inserttocsection}\n% change ball to gray square (copied from stackoverflow; \\par needed for break)\n\\setbeamertemplate{subsection in toc}{        \n    \\hspace{1.2em}{\\color{gray}\\rule[0.3ex]{3pt}{3pt}}~\\inserttocsubsection\\par}\n% use default enumeration scheme\n\\setbeamertemplate{enumerate items}[default]\n% required line that fixes the problem of \\mathbf, \\bf not working in beamer\n% for later (post-2019) TeX Live installations. see the issue on GitHub:\n% https://github.com/josephwright/beamer/issues/630\n\\DeclareFontShape{OT1}{cmss}{b}{n}{<->ssub * cmss/bx/n}{}\n\n\\begin{document}\n\n% title slide\n\\begin{frame}\n    \\titlepage\n    \\centering\n    % relative path may need to be updated depending on .tex file location\n    \\includegraphics[scale = 0.1]{../bac_logo1.png}\n\\end{frame}\n\n% table of contents slide\n\\begin{frame}{Overview}\n    \\tableofcontents\n\\end{frame}\n\n\\section{Convex optimization}\n\n\\begin{frame}{Motivation}\n    \\begin{itemize}\n        \\item\n        Let $ \\mathbf{X} \\in \\mathbb{R}^{N \\times d} $ be the input matrix,\n        $ \\mathbf{y} \\in \\mathbb{R}^N $ the response vector. Consider\n        fitting a linear regression model s.t. we minimize the\n        absolute value of the residuals. Optimal $ \\hat{\\mathbf{w}} \\in\n        \\mathbb{R}^d $, $ \\hat{b} \\in \\mathbb{R} $ solve\n        \\begin{equation*}\n            \\begin{array}{ll}\n                \\displaystyle\\min_{\\mathbf{w}, b} &\n                    \\Vert\\mathbf{y} - \\mathbf{Xw} - b\\mathbf{1}\\Vert_1\n            \\end{array}\n        \\end{equation*}\n\n        \\item\n        Model parameter estimation is an optimization problem.\n\n        \\item\n        Quite hard to solve. May be recast as the linear program (LP)\n        \\cite{bv_convex_opt}\n        \\begin{equation*}\n            \\begin{array}{ll}\n                \\displaystyle\\min_{\\mathbf{w}, b, \\mathbf{t}} &\n                    \\mathbf{1}^\\top\\mathbf{t} \\\\\n                \\text{s.t.} &\n                    -\\mathbf{t} \\preceq \\mathbf{y} - \\mathbf{Xw} - b\\mathbf{1}\n                    \\preceq \\mathbf{t} \\\\\n                & \\mathbf{t} \\succeq \\mathbf{0}\n            \\end{array}\n        \\end{equation*}\n        Here $ \\mathbf{t} \\in \\mathbb{R}^N $. Algorithms for solving LPs\n        are quite reliable \\cite{bv_convex_opt}.\n    \\end{itemize}\n\\end{frame}\n\n\\subsection{Convex sets and functions}\n\n\\begin{frame}{Convex sets and functions}\n    \\begin{itemize}\n        \\item\n        Optimization problems broadly categorized as convex vs. nonconvex\n        $ \\Rightarrow $ we need to know what convexity means.\n\n        \\item\n        \\textit{Definition.} Let $ \\mathbf{x}_1, \\mathbf{x}_2 \\in\n        \\mathbb{R}^n $, $ \\mathbf{x}_1 \\ne \\mathbf{x}_2 $. The \\textit{line}\n        passing through points $ \\mathbf{x}_1, \\mathbf{x}_2 $ is\n        $ \\{\\theta\\mathbf{x}_1 + (1 - \\theta)\\mathbf{x}_2 :\n        \\theta \\in \\mathbb{R}\\} $. The \\textit{line segment} connecting\n        points $ \\mathbf{x}_1, \\mathbf{x}_2 $ is $ \\{\\theta\\mathbf{x}_1 +\n        (1 - \\theta) \\mathbf{x}_2 : \\theta \\in [0, 1]\\} $\n        \\cite{bv_convex_opt}.\n    \\end{itemize}\n    \\begin{figure}\n        \\centering\n        \\includegraphics[scale = 0.3]{bv_fig_2.1.png}\n        % remove excess space\n        \\vspace{-10 pt}\n        \\caption{\n            The $ \\mathbf{x}_1, \\mathbf{x}_2 $ line and line segment\n            parametrized by $ \\theta $\\footnote{\n                Figure 2.1 from Boyd and Vandenberghe's\n                \\textit{Convex Optimization}.\n            }.\n        }\n    \\end{figure}\n\\end{frame}\n\n\\begin{frame}{Convex sets and functions}\n    \\begin{itemize}\n        \\item\n        \\textit{Definition.} A set $ C \\subseteq \\mathbb{R}^n $ is\n        \\textit{affine} if $ \\forall \\mathbf{x}, \\mathbf{y} \\in C $,\n        $ \\alpha \\in \\mathbb{R} $, $ \\alpha\\mathbf{x} + (1 - \\alpha)\\mathbf{y}\n        \\in C $, i.e. $ C $ contains the $ \\mathbf{x}, \\mathbf{y} $ line.\n\n        \\item\n        \\textit{Definition.} Let $ C \\subseteq \\mathbb{R}^n $. The\n        \\textit{affine hull} of $ C $, denoted $ \\operatorname{aff} C $, is\n        s.t. $ \\operatorname{aff} C \\triangleq \\{\n            \\sum_{i = 1}^k\\theta_i\\mathbf{x}_i : \\mathbf{x}_1, \\ldots\n            \\mathbf{x}_k \\in C, \\theta_1, \\ldots \\theta_k \\in \\mathbb{R},\n            \\sum_{i = 1}^k\\theta_i = 1\n        \\} $ \\cite{bv_convex_opt}.\n\n        \\item\n        \\textit{Definition.} A set $ C \\subseteq \\mathbb{R}^n $ is\n        \\textit{convex} if $ \\forall \\mathbf{x}, \\mathbf{y} \\in C $,\n        $ \\alpha \\in [0, 1] $,\n        $ \\alpha\\mathbf{x} + (1 - \\alpha)\\mathbf{y} \\in C $, i.e. $ C $\n        contains the $ \\mathbf{x}, \\mathbf{y} $ line segment.\n    \\end{itemize}\n    \\begin{figure}\n        \\centering\n        \\includegraphics[scale = 0.2]{bv_fig_2.2.png}\n        % remove excess space\n        \\vspace{-10 pt}\n        \\caption{\n            Convex and nonconvex sets. Only the leftmost set is\n            convex\\footnote{\n                Figure 2.2 from Boyd and Vandenberghe's\n                \\textit{Convex Optimization}.\n            }.\n        }\n        % remove excess space\n        \\vspace{-10 pt}\n    \\end{figure}\n    \\begin{itemize}\n        \\item\n        \\textit{Definition.} Let $ C \\subseteq \\mathbb{R}^n $. The\n        \\textit{convex hull} of $ C $, denoted $ \\operatorname{conv} C $, is\n        s.t. $ \\operatorname{conv} C \\triangleq \\{\n            \\sum_{i = 1}^k\\theta_i\\mathbf{x}_i : \\mathbf{x}_1, \\ldots\n            \\mathbf{x}_k \\in C, \\theta_1, \\ldots \\theta_k \\in [0, 1],\n            \\sum_{i = 1}^k\\theta_i = 1        \n        \\} $.\n    \\end{itemize}\n    % adjust spacing since there is a footnote\n    \\bigskip\n\\end{frame}\n\n\\begin{frame}{Convex sets and functions}\n    \\begin{itemize}\n        \\item\n        If $ C $ affine, then $ \\operatorname{aff} C = C $, while if $ C $\n        convex, then $ \\operatorname{conv} C = C $.\n    \\end{itemize}\n    \\begin{figure}\n        \\centering\n        % remove excess space\n        \\vspace{-3 pt}\n        \\includegraphics[scale = 0.24]{bv_fig_2.3.png}\n        % remove excess space\n        \\vspace{-10 pt}\n        \\caption{\n            Examples of $ \\mathbb{R}^2 $ convex hulls\\footnote{\n                Figure 2.3 from Boyd and Vandenberghe's\n                \\textit{Convex Optimization}.\n            }.\n        }\n        % remove excess space\n        \\vspace{-10 pt}\n    \\end{figure}\n    \\begin{itemize}\n        \\item\n        \\textit{Definition.} Let $ C \\subseteq \\mathbb{R}^n $. The\n        \\textit{relative interior} of $ C $, denoted\n        $ \\operatorname{relint} C $, is s.t. $ \\operatorname{relint} C\n        \\triangleq \\{\\mathbf{x} \\in C : B(\\mathbf{x}, r) \\cap\n        \\operatorname{aff} C \\subseteq C, r \\in (0, \\infty)\\} $\n        \\cite{bv_convex_opt}. Here\n        $ B(\\mathbf{x}, r) \\triangleq \\{\\mathbf{x}' \\in \\mathbb{R}^n :\n        \\Vert\\mathbf{x}' - \\mathbf{x}\\Vert \\le r\\} $ for some norm\n        $ \\Vert\\cdot\\Vert $\\footnote{\n            All norms define the same relative interior \\cite{bv_convex_opt}.        \n        }.\n\n        \\item\n        \\textit{Definition.} $ f : \\mathcal{M} \\rightarrow\n        \\mathbb{R} $, $ \\mathcal{M} \\subseteq \\mathbb{R}^n $, is\n        \\textit{convex} if $ \\mathcal{M} $ convex and if\n        $ \\forall \\mathbf{x}, \\mathbf{y} \\in \\mathcal{M} $,\n        $ \\forall \\alpha \\in [0, 1] $,\n        $ f(\\alpha\\mathbf{x} + (1 - \\alpha)\\mathbf{y}) \\le\n        \\alpha f(\\mathbf{x}) + (1 - \\alpha)f(\\mathbf{y}) $.\n\n        \\item\n        \\textit{Definition.} $ f : \\mathcal{M} \\rightarrow \\mathbb{R} $ is\n        \\textit{concave} if $ -f $ is convex.\n    \\end{itemize}\n\n    % spacing for footnote\n    \\bigskip\n\\end{frame}\n\n\\begin{frame}{Convex sets and functions}\n    \\begin{itemize}\n        \\item\n        Affine and linear functions are both convex and concave.\n    \\end{itemize}\n    \\begin{figure}\n        \\centering\n        % remove extra space\n        \\vspace{-3 pt}\n        \\includegraphics[scale = 0.24]{bv_fig_3.1.png}\n        % remove extra space\n        \\vspace{-5 pt}\n        \\caption{Graph of a convex function\\footnote{\n            Figure 3.1 from Boyd and Vandenberghe's\n            \\textit{Convex Optimization}.\n        }. }\n        % remove excess space\n        \\vspace{-10 pt}\n    \\end{figure}\n    \\begin{itemize}\n        \\item\n        \\textit{Examples.}\n        \\begin{itemize}\n            \\item\n            \\textit{Exponential.} $ \\forall a \\in \\mathbb{R} $, $ e^{ax} $\n            convex on $ \\mathbb{R} $ \\cite{bv_convex_opt}.\n\n            \\item\n            \\textit{Powers.} $ x^a $ convex on $ (0, \\infty) $ if\n            $ a \\in (\\infty, 0] \\cup [1, \\infty) $, concave if\n            $ a \\in [0, 1] $. $ \\forall a \\in [1, \\infty) $, $ |x|^a $ convex\n            on $ \\mathbb{R} $ \\cite{bv_convex_opt}.\n\n            \\item\n            \\textit{Logarithms.} $ \\log x $ concave on $ (0, \\infty) $.\n\n            \\item\n            \\textit{Norms.} Any norm on $ \\mathbb{R}^n $ is convex\n            \\cite{bv_convex_opt}, e.g. $ \\ell^p $-norm.\n        \\end{itemize}\n    \\end{itemize}\n\n    % spacing for footnote\n    \\bigskip\n\\end{frame}\n\n\\begin{frame}{Convex sets and functions}\n    \\begin{itemize}\n        \\item\n        \\textit{Theorem.} Let $ f : \\mathcal{M} \\rightarrow \\mathbb{R} $ be\n        differentiable $ \\forall \\mathbf{x} \\in \\mathcal{M} $. $ f $\n        convex $ \\Leftrightarrow \\mathcal{M} $ convex, $ \\forall \\mathbf{x},\n        \\mathbf{y} \\in \\mathcal{M} $, $ f(\\mathbf{y}) \\ge f(\\mathbf{x}) +\n        \\nabla f(\\mathbf{x})^\\top(\\mathbf{y} - \\mathbf{x}) $\n        \\cite{bv_convex_opt}.\n    \\end{itemize}\n    \\begin{figure}\n        \\centering\n        % remove extra space\n        \\vspace{-5 pt}\n        \\includegraphics[scale = 0.3]{bv_fig_3.2.png}\n        % remove extra space\n        \\vspace{-10 pt}\n        \\caption{Convex function bounded below by tangent line\\footnote{\n            Figure 3.2 from Boyd and Vandenberghe's\n            \\textit{Convex Optimization}.\n        }. }\n        % remove excess space\n        \\vspace{-15 pt}\n    \\end{figure}\n    \\begin{itemize}\n        \\item\n        \\textit{Theorem.} Let $ f : \\mathcal{M} \\rightarrow \\mathbb{R} $ be\n        twice differentiable $ \\forall \\mathbf{x} \\in \\mathcal{M} $.\n        $ f $ convex $ \\Leftrightarrow \\mathcal{M} $ convex, $ \\forall\n        \\mathbf{x} \\in \\mathcal{M} $, $ \\nabla^2f(\\mathbf{x}) \\succeq\n        \\mathbf{0} $ \\cite{bv_convex_opt}.\n\n        \\item\n        \\textit{Remark.} If $ \\mathcal{M} \\subseteq \\mathbb{R} $ convex,\n        reduces to $ \\forall x \\in \\mathcal{M}, f''(x) \\ge 0 $.\n    \\end{itemize}\n\n    % spacing for footnote\n    \\medskip\n\n\\end{frame}\n\n\\subsection{Optimization problems}\n\n\\begin{frame}{Optimization problems}\n    \\begin{itemize}\n        \\item\n        \\textit{Definition.} Let $ \\mathcal{M}_f, \\mathcal{M}_\\mathbf{u},\n        \\mathcal{M}_\\mathbf{v} \\subseteq \\mathbb{R}^n $. For\n        $ f: \\mathcal{M}_f \\rightarrow \\mathbb{R} $, $ \\mathbf{u} :\n        \\mathcal{M}_\\mathbf{u} \\rightarrow \\mathbb{R}^p $,\n        $ \\mathbf{v} : \\mathcal{M}_\\mathbf{v} \\rightarrow \\mathbb{R}^q $, a\n        \\textit{standard form} optimization problem is\\footnote{\n            Assume the problem is well-defined, i.e. \\textit{feasible}\n            (solvable) and bounded below.\n        }\n        \\cite{bv_convex_opt}\n        \\begin{equation} \\label{opt_prob_std}\n            \\begin{array}{ll}\n                \\displaystyle\\min_\\mathbf{x} & f(\\mathbf{x}) \\\\\n                \\text{s.t.} & \\mathbf{u}(\\mathbf{x}) \\preceq \\mathbf{0} \\\\\n                & \\mathbf{v}(\\mathbf{x}) = \\mathbf{0}\n            \\end{array}\n        \\end{equation}\n        $ \\mathbf{x} \\in \\mathbb{R}^n $ is the \\textit{optimization\n        variable} \\cite{bv_convex_opt}. $ \\mathbf{u} \\triangleq\n        [ \\ u_1 \\ \\ldots \\ u_p \\ ]^\\top $ gives $ p $ \\textit{inequality\n        constraints}, $ \\mathbf{v} \\triangleq [ \\ v_1 \\ \\ldots \\ v_q \\ ]^\\top $\n        gives $ q $ \\textit{equality constraints}.\n\n        \\item\n        \\textit{Definition.} The \\textit{domain} of (\\aref{opt_prob_std}) is\n        $ \\tilde{\\mathcal{M}} \\triangleq \\mathcal{M}_f \\cap\n        \\mathcal{M}_\\mathbf{u} \\cap \\mathcal{M}_\\mathbf{v} \\ne \\emptyset $\n        \\cite{bv_convex_opt}.\n\n        \\item\n        Problem is \\textit{unconstrained} if no constraints,\n        \\textit{constrained} otherwise. Note maximization of $ f $ \n        equivalent to minimization of $ -f $.\n\n        \\item\n        \\textit{Definition.} (\\aref{opt_prob_std}) is a\n        \\textit{convex optimization problem} if functions\n        $ f, u_1, \\ldots u_p $ are convex and functions $ v_1, \\ldots v_q $\n        are affine \\cite{bv_convex_opt}.\n    \\end{itemize}\n\n    % spacing for footnote\n    \\medskip\n\\end{frame}\n\n\\begin{frame}{Optimization problems}\n    \\begin{itemize}\n        \\item\n        \\textit{Examples.}\n        \\begin{itemize}\n            \\item\n            \\textit{Weighted linear least squares.} Let $ \\mathbf{\\Gamma}\n            \\triangleq \\operatorname{diag}(\\gamma_1, \\ldots \\gamma_N) \\succ\n            \\mathbf{0} \\in \\mathbb{R}^{N \\times N} $ be the data weighting\n            matrix. The unconstrained problem to solve is\n            \\begin{equation*}\n                \\begin{array}{ll}\n                    \\displaystyle\\min_{\\mathbf{w}, b} &\n                    \\Vert\n                        \\mathbf{\\Gamma}^{1 / 2}(\\mathbf{y} - \\mathbf{Xw} -\n                        b\\mathbf{1})\n                    \\Vert_2^2\n                \\end{array}\n            \\end{equation*}\n\n            \\item\n            \\textit{SVM dual problem.} Note $ \\mathbf{X} \\triangleq\n            [ \\ \\mathbf{x}_1 \\ \\ldots \\mathbf{x}_N \\ ]^\\top $. The problem is\n            \\begin{equation*}\n                \\begin{array}{ll}\n                    \\displaystyle\\max_\\alpha & \\mathbf{1}^\\top\\alpha -\n                    \\frac{1}{2}\\alpha^\\top\\mathbf{H}\\alpha \\\\\n                    \\text{s.t.} & \\alpha^\\top\\mathbf{y} = 0 \\\\\n                    & \\mathbf{0} \\preceq \\alpha \\preceq C\\mathbf{1}\n                \\end{array}\n            \\end{equation*}\n            Here $ \\alpha \\in \\mathbb{R}^N $,\n            $ \\mathbf{H} \\in \\mathbb{R}^{N \\times N} $ is such that\n            $ h_{ij} = y_iy_j\\mathbf{x}_i^\\top\\mathbf{x}_j $, $ C > 0 $.\n\n            \\item\n            Both problems are \\textit{quadratic programs}. Quadratic programs\n            have convex, quadratic objectives and affine constraints (if any)\n            \\cite{bv_convex_opt}.\n        \\end{itemize}\n    \\end{itemize}\n\\end{frame}\n\n\\subsection{Feasibility and optimality}\n\n\\begin{frame}{Feasibility and optimality}\n    \\begin{itemize}\n        \\item\n        \\textit{Definition.} Let $ \\mathbf{u}, \\mathbf{v},\n        \\tilde{\\mathcal{M}} $ be defined as in (\\aref{opt_prob_std}).\n        $ \\mathbf{x}' \\in \\tilde{\\mathcal{M}} $ is \\textit{feasible} if\n        $ \\mathbf{x}' \\in \\mathcal{X}^*\n        \\triangleq \\{\\mathbf{x} \\in \\tilde{\\mathcal{M}} :\n        \\mathbf{u}(\\mathbf{x}) \\preceq \\mathbf{0}, \\mathbf{v}(\\mathbf{x}) =\n        \\mathbf{0}\\} $. $ \\mathcal{X}^* $ is the \\textit{feasible set}\n        \\cite{bv_convex_opt}.\n\n        \\item\n        \\textit{Definition.} The \\textit{optimal value} $ p^* $\n        of an optimization problem, as defined in (\\aref{opt_prob_std}), is\n        such that $ p^* = \\inf\\{f(\\mathbf{x}) : \\mathbf{x} \\in\n        \\mathcal{X}^*\\} $ \\cite{bv_convex_opt}.\n\n        \\item\n        \\textit{Definition.} $ \\mathbf{x}^* $ is \\textit{[globally] optimal}\n        if $ \\mathbf{x}^* \\in \\mathcal{X}^* $ and $ f(\\mathbf{x}^*) = p^* $ \n        \\cite{bv_convex_opt}.\n\n        \\item\n        \\textit{Definition.} $ \\mathbf{x}' $ is \\textit{locally optimal} if\n        $ \\mathbf{x}' \\in \\mathcal{X}^* $ and $ \\exists r \\in (0, \\infty) $\n        such that $ f(\\mathbf{x}') = \\inf\\{\n            f(\\mathbf{x}) : \\mathbf{x} \\in \\mathcal{X}^*,\n            \\Vert\\mathbf{x}' - \\mathbf{x}\\Vert_2 \\le r\n        \\}$ \\cite{bv_convex_opt}.\n\n        \\item\n        \\textit{Theorem.} Suppose (\\aref{opt_prob_std}) is a \\alert{convex}\n        optimization problem. If $ \\mathbf{x}' $ is locally optimal, then\n        $ \\mathbf{x}' $ is [globally] optimal.\n\n        \\item\n        \\textit{Theorem.} Suppose (\\aref{opt_prob_std}) is a \\alert{convex}\n        optimization problem and objective $ f $ differentiable.\n        $ \\mathbf{x}^* \\in \\tilde{\\mathcal{M}} $ optimal\n        $ \\Leftrightarrow \\mathbf{x}^* \\in \\mathcal{X}^* $,\n        $ \\forall \\mathbf{x} \\in \\mathcal{X}^* $,\n        $ \\nabla f(\\mathbf{x}^*)^\\top(\\mathbf{x} - \\mathbf{x}^*) \\ge 0 $.\n        If no constraints, reduces to $ \\nabla f(\\mathbf{x}^*) = \\mathbf{0} $\n        \\cite{bv_convex_opt}.\n    \\end{itemize}\n\\end{frame}\n\n\\section{Duality}\n\n\\subsection{The Lagrangian dual}\n\n\\begin{frame}{The Lagrangian dual}\n    \\begin{itemize}\n        \\item\n        \\textit{Definition.} The \\textit{Lagrangian} $ \\mathcal{L}_f :\n        \\tilde{\\mathcal{M}} \\times \\mathbb{R}^p \\times \\mathbb{R}^q \\rightarrow\n        \\mathbb{R} $ of (\\aref{opt_prob_std}) is s.t.\n        \\begin{equation} \\label{std_lagrangian}\n            \\mathcal{L}_f(\\mathbf{x}, \\lambda, \\nu) \\triangleq f(\\mathbf{x}) +\n            \\lambda^\\top\\mathbf{u}(\\mathbf{x}) + \\nu^\\top\\mathbf{v}(\\mathbf{x})\n        \\end{equation}\n        $ \\lambda \\in \\mathbb{R}^p $, $ \\nu \\in \\mathbb{R}^q $ are the\n        \\textit{Lagrange multipliers} or \\textit{dual variables}.\n\n        \\item\n        \\textit{Definition.} The \\textit{[Lagrangian] dual} $ f_d :\n        \\tilde{\\mathcal{M}}_d \\rightarrow \\mathbb{R} $ of \n        (\\aref{opt_prob_std}), is s.t.\n        \\begin{equation} \\label{std_dual}\n            f_d(\\lambda, \\nu) \\triangleq\n            \\inf_{\\mathbf{x} \\in \\tilde{\\mathcal{M}}}\n            \\{\\mathcal{L}_f(\\mathbf{x}, \\lambda, \\nu)\\}\n        \\end{equation}\n        Here $ \\tilde{\\mathcal{M}}_d \\subseteq \\mathbb{R}^p \\times\n        \\mathbb{R}^q $. $ f_d $ is \\alert{always} concave, even if the\n        problem (\\aref{opt_prob_std}) is nonconvex \\cite{bv_convex_opt}.\n        $ (\\lambda, \\nu) \\in \\tilde{\\mathcal{M}}_d $ with $ \\lambda \\succeq\n        \\mathbf{0} $ is called \\textit{dual feasible} \\cite{bv_convex_opt}.\n\n        \\item\n        \\textit{Theorem.} $ \\forall (\\lambda, \\nu) \\in \\tilde{\\mathcal{M}}_d $,\n        $ \\lambda \\succeq \\mathbf{0} $, $ f_d(\\lambda, \\nu) \\le p^* $.\n\n        \\item\n        For any dual feasible $ (\\lambda, \\nu) $, $ f_d(\\lambda, \\nu) $\n        gives a lower bound to the optimal value of the original optimization\n        problem.\n    \\end{itemize}\n\n    % more footnote spacing\n    \\medskip\n\\end{frame}\n\n\\begin{frame}{The Lagrangian dual}\n    \\begin{itemize}\n        \\item\n        If we allow infinite values, (\\aref{opt_prob_std}) can be written as\n        the unconstrained\n        \\begin{equation*}\n            \\begin{array}{ll}\n                \\displaystyle\\min_\\mathbf{x} &\n                \\displaystyle f(\\mathbf{x}) + \\tilde{\\mathbb{I}}^\\infty_{\\{\n                    \\mathbf{x}' \\in \\mathbb{R}^p : \\mathbf{x}' \\preceq\n                    \\mathbf{0}\n                \\}}\\circ\\mathbf{u}(\\mathbf{x}) +\n                \\tilde{\\mathbb{I}}^\\infty_{\\{\\mathbf{0}\\}} \\circ\n                \\mathbf{v}(\\mathbf{x})\n            \\end{array}\n        \\end{equation*}\n        % \\displaystyle used inline to raise the superscript more\n        $ \\displaystyle\\tilde{\\mathbb{I}}_A^\\infty $  is such that for set\n        $ A $, $ \\displaystyle\\tilde{\\mathbb{I}}_A^\\infty(x) = 0 $ if\n        $ x \\in A $, else\n        $ \\displaystyle\\tilde{\\mathbb{I}}_A^\\infty(x) = \\infty $.\n\n        \\item\n        $ \\lambda^\\top\\mathbf{u} $, $ \\nu^\\top\\mathbf{v} $ are linear\n        underestimators of $ \\displaystyle\\tilde{\\mathbb{I}}^\\infty_{\\{\n            \\mathbf{x}' \\in \\mathbb{R}^p : \\mathbf{x}' \\preceq \\mathbf{0}\n        \\}}\\circ\\mathbf{u} $, $ \\displaystyle\n        \\tilde{\\mathbb{I}}^\\infty_{\\{\\mathbf{0}\\}}\\circ\\mathbf{v} $ when\n        $ \\lambda \\succeq \\mathbf{0} $, intuitively justifying why $ f_d $\n        yields a lower bound for $ p^* $ \\cite{bv_convex_opt}.\n\n        \\item\n        A natural question is to find the closest underestimator to the\n        original problem, i.e. $ \\lambda^*, \\nu^* $ s.t.\n        $ p^* - f_d(\\lambda^*, \\nu^*) $ is minimized.\n\n        \\item\n        \\textit{Definition.} Let $ f_d $ be the dual for\n        (\\aref{opt_prob_std}). The \\textit{dual problem} for\n        (\\aref{opt_prob_std}) is\n        \\begin{equation} \\label{opt_prob_std_dual}\n            \\begin{array}{ll}\n                \\displaystyle\\max_{\\lambda, \\nu}& f_d(\\lambda, \\nu) \\\\\n                \\text{s.t.} & \\lambda\\succeq \\mathbf{0}\n            \\end{array}\n        \\end{equation}\n        $ \\lambda^*, \\nu^* $ is \\textit{dual optimal} if optimal for\n        (\\aref{opt_prob_std_dual}). (\\aref{opt_prob_std}) is the\n        \\textit{primal problem}.\n    \\end{itemize}\n\n    % spacing for the footnote\n    \\bigskip\n\\end{frame}\n\n\\begin{frame}{The Lagrangian dual}\n    \\begin{itemize}\n        \\item\n        \\textit{Example.} Consider solving an undetermined linear system with\n        a minimum $ \\ell^2 $-norm solution\\footnote{\n            Squared $ \\ell^2 $-norm is differentiable and does not change the\n            solution.\n        }. I.e. for $ q < n $, we want to\n        solve\n        \\begin{equation*}\n            \\begin{array}{ll}\n                \\displaystyle\\min_\\mathbf{x} & \\Vert\\mathbf{x}\\Vert_2^2 \\\\\n                \\text{s.t.} & \\mathbf{Ax} = \\mathbf{b}\n            \\end{array}\n        \\end{equation*}\n        Here $ \\mathbf{A} \\in \\mathbb{R}^{q \\times n} $, $ \\mathbf{b} \\in\n        \\mathbb{R}^q $. The Lagrangian $ \\mathcal{L} : \\mathbb{R}^n \\times\n        \\mathbb{R}^q \\rightarrow \\mathbb{R} $ is s.t.\n        $ \\mathcal{L}(\\mathbf{x}, \\nu) \\triangleq \\mathbf{x}^\\top\\mathbf{x} \n        + \\nu^\\top(\\mathbf{Ax} - \\mathbf{b}) $. Fixing $ \\nu $, $ \\mathcal{L} $\n        is convex in $ \\mathbf{x} $, so at its minimizer $ \\mathbf{x}_\\nu $,\n        $ \\nabla_\\mathbf{x}\\mathcal{L}(\\mathbf{x}_\\nu, \\nu) =\n        2\\mathbf{x}_\\nu + \\mathbf{A}^\\top\\nu = \\mathbf{0} \\Rightarrow\n        \\mathbf{x}_\\nu = -\\frac{1}{2}\\mathbf{A}^\\top\\nu $. Then,\n        \\begin{equation*}\n            f_d(\\nu) \\triangleq \\inf_{\\mathbf{x} \\in \\mathbb{R}^n}\n                \\mathcal{L}(\\mathbf{x}, \\nu) =\n                \\mathcal{L}(\\mathbf{x}_\\nu, \\nu) =\n                -\\frac{1}{4}\\nu^\\top\\mathbf{AA}^\\top\\nu - \\mathbf{b}^\\top\\nu\n        \\end{equation*}\n        $ \\forall \\nu \\in \\mathbb{R}^q $, $ f_d(\\nu) \\in \\mathbb{R} $, so\n        $ \\operatorname{dom}f_d = \\mathbb{R}^q $. $ -f_d $ is convex,\n        $ \\mathbf{AA}^\\top \\succeq \\mathbf{0} $\\footnote{\n            $ \\forall \\mathbf{x} \\in \\mathbb{R}^n,\n            \\mathbf{x}^\\top\\mathbf{AA}^\\top\\mathbf{x} =\n            \\big(\\mathbf{A}^\\top\\mathbf{x}\\big)^\\top\\mathbf{A}^\\top\\mathbf{x} =\n            \\Vert\\mathbf{A}^\\top\\mathbf{x}\\Vert_2^2 \\ge 0 $.\n        }.\n    \\end{itemize}\n\n    % spacing for footnote\n    \\medskip\n\\end{frame}\n\n\\subsection{Strong duality}\n\n\\begin{frame}{Strong duality}\n    \\begin{itemize}\n        \\item\n        \\textit{Definition.} Let $ d^* $ denote the optimal value of the dual\n        problem (\\aref{opt_prob_std_dual}). The property $ d^* \\le p^* $ is\n        \\textit{weak duality}, which always holds \\cite{bv_convex_opt}.\n\n        \\item\n        \\textit{Definition.} If $ d^* = p^* $, we say that\n        \\textit{strong duality} holds.\n\n        \\item\n        \\textit{Theorem.} If (\\aref{opt_prob_std}) is a convex problem and\n        Slater's condition holds, i.e. $ \\exists \\mathbf{x} \\in\n        \\operatorname{relint}\\tilde{\\mathcal{M}} $ s.t.\n        $ \\mathbf{u}(\\mathbf{x}) \\prec \\mathbf{0} $,\n        $ \\mathbf{v}(\\mathbf{x}) = \\mathbf{0} $, strong duality holds\n        \\cite{bv_convex_opt}.\n\n        \\item\n        If (\\aref{opt_prob_std}) convex and $ u_1, \\ldots u_k $ affine,\n        $ k \\le p $, Slater's condition can be refined s.t. if\n        $ \\exists \\mathbf{x} \\in\n        \\operatorname{relint}\\tilde{\\mathcal{M}} $ s.t.\n        $ u_1(\\mathbf{x}) \\le 0, \\ldots u_k(\\mathbf{x}) \\le 0 $,\n        $ u_{k + 1}(\\mathbf{x}) < 0, \\ldots u_p(\\mathbf{x}) < 0 $,\n        $ \\mathbf{v}(\\mathbf{x}) = \\mathbf{0} $, strong duality\n        holds \\cite{bv_convex_opt}.\n\n        \\item\n        If (\\aref{opt_prob_std}) convex, $ \\mathbf{u} $ affine,\n        $ \\tilde{\\mathcal{M}} = \\mathbb{R}^n $, strong duality holds if\n        $ |\\mathcal{X}^*| > 0 $.\n\n        \\item\n        \\textit{Definition.} Suppose strong duality holds for\n        (\\aref{opt_prob_std}). Let $ \\mathbf{x}^* $ be primal optimal and\n        $ \\lambda^*, \\nu^* $ be\n        dual optimal. Then, $ \\forall i \\in \\{1, \\ldots p\\} $,\n        $ \\lambda_i^* > 0 \\Rightarrow u_i(\\mathbf{x}^*) = 0 $, i.e.\n        \\textit{complementary slackness} holds \\cite{bv_convex_opt}.\n\n        \\item\n        Equivalently, one can write $ u_i(\\mathbf{x}^*) < 0 \\Rightarrow\n        \\lambda_i^* = 0 $.\n    \\end{itemize}\n\\end{frame}\n\n\\subsection{Karush-Kuhn-Tucker conditions}\n\n\\begin{frame}{Karush-Kuhn-Tucker conditions}\n    \\begin{itemize}\n        \\item\n        Many problems have differentiable objectives and constraints.\n\n        \\item\n        \\textit{Definition.} Suppose strong duality holds for\n        (\\aref{opt_prob_std}) and $ f $, $ \\mathbf{u} $, $ \\mathbf{v} $\n        differentiable. Then, the following conditions must hold.\n        \\begin{enumerate}\n            \\item\n            \\textit{Stationarity.} $ \\nabla f(\\mathbf{x}^*) +\n            \\nabla\\mathbf{u}(\\mathbf{x}^*)^\\top\\lambda^* +\n            \\nabla\\mathbf{v}(\\mathbf{x}^*)^\\top\\nu^* = \\mathbf{0} $.\n\n            \\item\n            \\textit{Primal feasibility.} $ \\mathbf{u}(\\mathbf{x}^*) \\preceq\n            \\mathbf{0} $, $ \\mathbf{v}(\\mathbf{x}^*) = \\mathbf{0} $.\n\n            \\item\n            \\textit{Dual feasibility.} $ \\lambda^* \\succeq \\mathbf{0} $.\n\n            \\item\n            \\textit{Complementary slackness.} $ \\mathbf{u}(\\mathbf{x}^*)^\\top\n            \\lambda^* = 0 $.\n        \\end{enumerate}\n        These are the \\textit{Karush-Kuhn-Tucker conditions}\n        \\cite{bv_convex_opt}.\n\n        \\item\n        Note $ \\mathbf{x}^* =\n        \\arg\\min_{\\mathbf{x} \\in \\tilde{\\mathcal{M}}}\n        \\mathcal{L}_f(\\mathbf{x}, \\lambda^*, \\nu^*) \\Rightarrow\n        \\nabla_\\mathbf{x}\\mathcal{L}_f(\\mathbf{x}^*, \\lambda^*, \\nu^*) =\n        \\mathbf{0} $, where\n        \\begin{equation*}\n            \\nabla_\\mathbf{x}\\mathcal{L}_f(\\mathbf{x}^*, \\lambda^*, \\nu^*)\n            \\triangleq  \\nabla f(\\mathbf{x}^*) +\n            \\nabla\\mathbf{u}(\\mathbf{x}^*)^\\top\\lambda^* +\n            \\nabla\\mathbf{v}(\\mathbf{x}^*)^\\top\\nu^*\n        \\end{equation*}\n        By strong duality, $ f(\\mathbf{x}^*) = f_d(\\lambda^*, \\nu^*)\n        \\triangleq \\inf_{\\mathbf{x} \\in \\tilde{\\mathcal{M}}}\\{\n            \\mathcal{L}_f(\\mathbf{x}, \\lambda^*, \\nu^*)\n        \\} $.\n\n        \\item\n        Complementary slackness is equivalently written as\n        $ \\lambda_i^*u_i(\\mathbf{x}^*) = 0 $,\n        $ \\forall i \\in \\{1, \\ldots p\\} $, as \n        $ \\mathbf{u}(\\mathbf{x}^*)^\\top\\lambda^* = 0 \\Leftrightarrow\n        u_i(\\mathbf{x}^*) < 0 \\Rightarrow \\lambda_i^* = 0 $.\n    \\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Karush-Kuhn-Tucker conditions}\n    \\begin{itemize}\n        \\item\n        KKT conditions are \\alert{necessary} optimality conditions for\n        differentiable optimization problems where strong duality holds.\n\n        \\item\n        But if (\\aref{opt_prob_std}) is convex and $ \\mathbf{x}^*, \\lambda^*,\n        \\nu^* $ satisfy the KKT conditions, then strong duality holds,\n        $ \\mathbf{x}^* $ is primal optimal, $ (\\lambda^*, \\nu^*) $ is dual\n        optimal.\n\n        \\item\n        KKT conditions are \\alert{sufficient} for optimality if the problem is\n        convex.\n        \n        \\item        \n        Furthermore, if $ \\mathbf{x}^* $ also satisfies Slater's\n        condition, then KKT conditions become \\alert{necessary and sufficient}\n        for optimality.\n\n        \\item\n        In summary:\n        \\begin{enumerate}\n            \\item\n            Strong duality $ \\Rightarrow $ KKT conditions satisfied.\n\n            \\item\n            Convex problem, KKT conditions $ \\Rightarrow $ strong duality.\n\n            \\item\n            Convex problem, Slater's condition, KKT conditions\n            $ \\Leftrightarrow $ strong duality.\n        \\end{enumerate}\n    \\end{itemize}\n\\end{frame}\n\n\n% BibTeX slide for references. should use either acm or ieeetr style\n\\begin{frame}{References}\n    \\bibliographystyle{acm}\n    % relative path may need to be updated depending on .tex file location\n    \\bibliography{../master_bib}\n\\end{frame}\n\n\\end{document}", "meta": {"hexsha": "d5d41d0a2fcf6abaacc2683970291e7249eb6299", "size": 29566, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "lessons/lecture_06/lecture_06.tex", "max_stars_repo_name": "phetdam/bac-advanced-ml", "max_stars_repo_head_hexsha": "26de8661c3c5f00c13353e2d695ebf316545a037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lessons/lecture_06/lecture_06.tex", "max_issues_repo_name": "phetdam/bac-advanced-ml", "max_issues_repo_head_hexsha": "26de8661c3c5f00c13353e2d695ebf316545a037", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lessons/lecture_06/lecture_06.tex", "max_forks_repo_name": "phetdam/bac-advanced-ml", "max_forks_repo_head_hexsha": "26de8661c3c5f00c13353e2d695ebf316545a037", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8005249344, "max_line_length": 85, "alphanum_fraction": 0.5554352973, "num_tokens": 9852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213368305399, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3039725338127545}}
{"text": "% !BIB TS-program = biber\n% !BIB program = biber\n\n\\documentclass{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage[top= 2cm, bottom=2cm, left=2cm, right=2cm]{geometry}\n\\usepackage{amsmath, amsfonts, graphicx}\n\\usepackage{url}\n\n\\usepackage[backend=biber, sorting=none]{biblatex}\n\\addbibresource{references.bib}\n\n\\begin{document}\n\n\\title{CS291D Final Report: a Basic Zerocash Implementation}\n\\author{Gwyneth Allwright, Karl Wang, Dewei Zeng}\n\n\\maketitle\n\n\\section*{Abstract}\nIn this project, we attempt a basic implementation of Zerocash \\cite{zerocash} in Python. Zerocash is a ledger-based digital currency that makes use of zero-knowledge Succinct Non-Interactive Arguments of Knowledge (zk-SNARKs) to provide stronger privacy guarantees than currencies such as Bitcoin \\cite{bitcoin} and Zerocoin \\cite{zerocoin}. This functionality is provided through a decentralized anonymous payment (DAP) scheme that hides a transaction's origin, destination and amount. We follow \\cite{zerocash} to implement the following core functions: \\texttt{Setup}, \\texttt{CreateAddress}, \\texttt{Receive}, \\texttt{Mint}, \\texttt{VerifyTransaction}, \\texttt{Pour}, \\texttt{KeyGen}, \\texttt{Prove} and \\texttt{Verify}, which form the foundations of Zerocash.\n\n\\tableofcontents\n\n\\newpage\n\n\\section{Introduction}\nData on blockchains such as Bitcoin is public, including the sender, receiver and the amount of money transferred in a payment. While Bitcoin users often utilize different identities to disguise their transactions, it is possible to gain access to both the structure of the transaction graph and the values and dates of transactions. Zerocoin, a cryptographic extension to Bitcoin, aims to introduce better privacy guarantees without requiring new trusted parties, but it still cannot hide the location that money is sent to, as well as the amount of money that is transferred \\cite{zerocoin}. In addition, it lacks some features of fully-fledged cryptocurrencies, such as payments of exact values.\n\nIn order to solve these problems with Bitcoin and Zerocoin, a new digital currency known as Zerocash was devised. Zerocash makes the sender, receiver and amount of money transferred in a payment anonymous, while also improving on the efficiency of Zerocoin \\cite{zerocash}. These outcomes are achieved with the help of zk-SNARKs, which are efficient variants of zero-knowledge proofs of knowledge. Zero-knowledge proofs allow the prover of a certain statement to demonstrate that the statement in question is true without revealing additional information about the statement that could result in a compromise of privacy.\n\nOne of the primary objectives of this project is to explore zk-SNARKs and their potential applications in the world of blockchains and cryptocurrencies. To achieve this, we use existing zk-SNARK tooling to implement a minimal version of Zerocash in Python with the purpose of gaining a better understanding of Zerocash's theoretical underpinnings. This would be a first step towards demonstrating that zk-SNARKs are a feasible method of enhancing the privacy and performance of transactions on a simple blockchain. Next steps would include benchmarking and comparisons to a blockchain with similar functionality that does not make use of zk-SNARKs.\n\n\\section{Problem Definition}\nWe wish to understand how to incorporate zk-SNARKs into a basic blockchain in order to improve the blockchain's privacy guarantees. The setup of our scheme must not require any trust beyond a one-time trusted setup of public parameters. The implementation needs to support the minting, merging and splitting of coins without exposing the identities of the users who perform the transactions and the amounts of the currency involved.\n\n\\section{Solution}\nThe above objectives can be achieved through the combination of zk-SNARKs and a decentralized anonymous payment (DAP) scheme. As part of the Zerocash DAP scheme, we implement the following core functions: \\texttt{Setup}, \\texttt{CreateAddress}, \\texttt{Receive}, \\texttt{Mint}, \\texttt{VerifyTransaction} and \\texttt{Pour} \\cite{zerocash}. For the zk-SNARK, we require the additional functions (\\texttt{KeyGen}, \\texttt{Prove}, \\texttt{Verify}) \\cite{zerocash}. In the sections that follow, we provide an overview of the DAP scheme, zk-SNARK and their core functions.\n\n\\subsection{DAP Scheme}\n\\subsubsection{Basecoin}\nThe Zerocash system is applied on top of a ledger-based currency (e.g.\\ Bitcoin). This ledger-based currency is referred to as the \\emph{basecoin}. All basecoin transactions are recorded in an append-only ledger, which can be accessed by all Zerocash users at all times.\n\nIn addition to the basecoin transactions, Zerocash includes two new kinds of transactions --- minting and pouring --- which will be described later. Mint and pour transactions are also recorded in the basecoin ledger.\n\n\\subsubsection{Public Parameters}\nIn addition to the ledger, users have access to a set of public parameters. These are part of the one-time trusted setup that takes place before other functions are allowed to execute.\n\n\\subsubsection{Address Key Pairs}\nUsers may generate as many public and private address key pairs as they desire. The public address keys are published with the purpose of allowing users to make payments among themselves. The secret keys are used for receiving payments.\n\n\\subsubsection{Coins}\nCoins are data structures that encapsulate the following information:\n\\begin{itemize}\n\\item A coin commitment, which is a string that we append to the ledger once the coin is minted.\n\\item A coin value (between 0 and some parameter $v_{\\text{max}}$) that specifies the coin denomination in basecoin units.\n\\item A coin serial number, which is a string that uniquely identifies the coin and is used to prevent double-spending.\n\\item A coin address --- the public address key of the user who owns the coin.\n\\end{itemize}\n\n\\subsubsection{Coin-Related Data Structures}\nThe Zerocash protocol requires us to maintain the following coin-related information:\n\\begin{itemize}\n\\item A Merkle tree over coin commitments.\n\\item A list of coin commitments that appear in mint and pour transactions.\n\\item A list of all coin serial numbers that appear in pour transactions.\n\\end{itemize}\nFor efficiency reasons, it is useful to store the latter two lists (which could also be obtained from the ledger) separately.\n\n\\subsubsection{New Transaction 1: Mint}\nMint transactions are used to create coins. At its most basic, a mint transaction can be described as a tuple $(\\text{cm}, v)$, where $\\text{cm}$ is the commitment of the minted coin and $v$ is its value. Whenever a coin is minted, this tuple is placed on the ledger.\n\n\\subsubsection{New Transaction 2: Pour}\nPour transactions record the pouring of two input coins into two new output coins (thereby spending the two initial coins). At its most basic, a pour transaction can be described as a tuple $(\\text{rt}, \\, {\\text{sn}}^{\\text{old}}_1, \\, {\\text{sn}}^{\\text{old}}_2, \\, {\\text{cm}}^{\\text{new}}_1, \\, {\\text{cm}}^{\\text{new}}_2, \\, v_{\\text{pub}}, \\, \\text{info})$, where rt is the root of the Merkle tree over coin commitments, the sn are the serial numbers of the old coins, the cm are the commitments of the new coins, $v_{\\text{pub}}$ is a coin value and info is an arbitrary string. Pour transactions may also include implementation-specific information.\n\n\\subsection{zk-SNARK}\nThe zk-SNARK construction consists of a tuple of polynomial-time functions (\\texttt{KeyGen}, \\texttt{Prove}, \\texttt{Verify}). In what follows below, we give a high-level overview of these functions and their properties.\n\n\\subsubsection{Arithmetic Circuits}\nFor a given field $\\mathbb{F}$, an arithmetic circuit $C$ takes as input $n$ field elements $\\in \\mathbb{F}$ and returns $m$ field elements $\\in \\mathbb{F}$. We can therefore think of $C$ as a map $\\mathbb{F}^n \\longrightarrow \\mathbb{F}^m$.\n\nIn the Zerocash construction, we decompose the circuit input that lives in $\\mathbb{F}^n$ into a main input and auxiliary input, where the latter is known as the \\emph{witness}. If the dimensions of these two subinputs are $u$ and $v$ respectively, then we can write $C$: $\\mathbb{F}^u \\times \\mathbb{F}^v \\longrightarrow \\mathbb{F}^m$.\n\n\\subsubsection{Circuit Satisfiability}\nzk-SNARKs can be described in terms of arithmetic circuit satisfiability. The key relationship involved is the following:\n\n\\begin{equation}\n\\text{For a given} \\,\\,\\, X \\in \\mathbb{F}^u, \\,\\,\\, \\exists A \\in \\mathbb{F}^v \\,\\,\\, \\text{such that} \\,\\,\\, C(X, A) = 0^{m}.\n\\label{zk-snark-definition}\n\\end{equation}\n\\newline\n\nThe set of all $X$ that satisfy Equation \\ref{zk-snark-definition} form the set $\\mathbb{L}_C$. The statement that a prover would want to demonstrate is that for a given $X$, we have $X \\in \\mathbb{L}_C$.\n\n\\subsubsection{Important zk-SNARK Functions}\n\n\\begin{enumerate}\n\n\\item {\\texttt{KeyGen}}:\n\nThe function \\texttt{KeyGen} is used to sample a proving key and a verification key for the zk-SNARK. These keys are both public parameters. Their purpose is to help prove that a certain $X$ is a member of the set $\\mathbb{L}_C$.\n\n\\texttt{KeyGen} takes as input the security parameter and zk-SNARK circuit $C$, and returns a key pair.\n\n\\item {\\texttt{Prove}}:\n\nThe function \\texttt{Prove} takes as input a proving key, as well as a pair $(X, A)$ --- where $X$ represents a main input for the circuit $C$ and $A$ the witness. It returns a proof $\\Pi$ for the statement that $X \\in \\mathbb{L}_C$.\n\n\\item {\\texttt{Verify}}:\n\nThe function \\texttt{Verify} takes as input a verification key, the circuit's main input $X$ and a proof $\\Pi$. It outputs $1$ if there is sufficient evidence that $x \\in \\mathbb{L}_C$, and 0 otherwise.\n\n\\end{enumerate}\n\n\\subsubsection{zk-SNARK Properties}\n\\begin{itemize}\n\\item \\emph{Completeness.} Intuitively, this property means that an honest prover can convince the verifier that $X \\in \\mathbb{L}_C$. More mathematically, it means that with probability\n\n\\begin{equation}\nP(\\lambda) = 1 - \\text{negl}(\\lambda),\n\\end{equation}\n\nwhere $\\lambda$ is the security parameter, the output of \\texttt{Verify} will be $1$ after going invoking \\texttt{KeyGen} and \\texttt{Prove} to correctly generate a proof for a circuit input $X \\in \\mathbb{L}_C$.\n\n\\item \\emph{Succinctness.} This property has two components. First, it means that a proof $\\Pi$ that was generated from \\texttt{Prove} has $\\mathcal{O}(1)$ bits for a given security parameter. Second (again for a fixed security parameter), \\texttt{Verify} has time complexity $\\mathcal{O}(X)$.\n\n\\item \\emph{Proof of knowledge} (intuitive idea). If a proof is verified to be correct, then the prover ``knows\" (is able to extract) a witness that corresponds to the instance, with certain guarantees around the time complexity of the extraction.\n\n\\item \\emph{Zero knowledge}. The proof does not leak information about the witness.\n\\end{itemize}\n\n\\subsection{Key Zerocash Functions}\nThe DAP scheme described above is implemented by means of a tuple of polynomial-time algorithms (\\texttt{Setup}, \\texttt{CreateAddress}, \\texttt{Mint}, \\texttt{Pour}, \\texttt{VerifyTransaction}, \\texttt{Receive}). In this section, we describe the arguments, outputs and interrelation of these functions.\n\n\\subsubsection{\\texttt{Setup}}\nThe purpose of \\texttt{Setup} is to perform the one-time trusted setup of public parameters. It takes as input a security parameter and produces the following list of public parameters as output:\n\\begin{itemize}\n\\item (pk$_{\\text{POUR}}$, vk$_{\\text{POUR}}$): a proving and verification key pair for the zk-SNARK. These are sampled from \\texttt{KeyGen}.\n\\item pp$_{\\text{enc}}$: parameters for the encryption scheme.\n\\item pp$_{\\text{sig}}$: parameters for the digital signature scheme.\n\\end{itemize}\nAll three of the above are functions of the provided security parameter.\n\n\\subsubsection{\\texttt{CreateAddress}}\nThe purpose of \\texttt{CreateAddress} is to generate public-private address key pairs for users. It takes as input the public parameters generated by \\texttt{Setup} and produces a key pair as output.\n\n\\subsubsection{\\texttt{Mint}}\nThe purpose of a call to \\texttt{Mint} is the creation of a coin. It takes as input the public parameters generated by \\texttt{Setup}, the value of the coin to be minted and the public address key of the coin's owner. It returns a coin data structure for the minted coin, along with the associated mint transaction. The mint transaction is a tuple containing (at minimum) a coin commitment and value.\n\n\\subsubsection{\\texttt{Pour}}\n\\texttt{Pour} is easily one of the most complicated functions in the Zerocash system. It is used to ``pour\" two old coins into two new ones, such that the sum of the two old coins equals the sum of the two new ones. The latter sum could potentially an additional value $v_{\\text{pub}}$ that is publicly spent in the transaction. In this case, the balance equation would be \n\n\\begin{equation}\nv_1^{\\text{old}} + v_2^{\\text{old}} = v_1^{\\text{new}} + v_2^{\\text{new}} + v_{\\text{pub}}.\n\\label{balance}\n\\end{equation}\n\\newline\n\nThe \\texttt{Pour} operation could have multiple purposes, including switching coin denominations, making public payments and transferring coin ownership.\n\n\\texttt{Pour} takes the following as input:\n\n\\begin{itemize}\n\\item The public parameters generated by \\texttt{Setup}.\n\\item The root of the Merkle tree over coin commitments.\n\\item The coin data structures for two old coins.\n\\item The secret address keys for the owners of the two old coins.\n\\item The authentications paths for each of the old coin commitments to the root of the Merkle tree.\n\\item Two new coin values.\n\\item The public address keys for the owners of the two new coins.\n\\item A coin value $v_\\text{pub}$. This is amount that will be \\emph{publicly} spent in the pour transaction --- for example, to pay a transaction fee or to purchase coins.\n\\item An information string.\n\\end{itemize}\n\nOne of the primary tasks performed in \\texttt{Pour} is to prove or disprove the following: \\newline\n\n\\fbox{\\parbox{\\textwidth}{\n\\medskip\nFor the provided Merkle tree root, serial numbers of the old coins and coin commitments for the two new coins, there are two old coins, two news coins and a secret address key such that the following statements hold:\n\n\\begin{itemize}\n\\item All four of the coins have the correct commitments.\n\\item For both of the old coins, the provided secret address key matches the secret address key that is generated from the public address key that forms part of the old coin's data structure.\n\\item The serial numbers of the old coins are correct.\n\\item The two commitments of the old coins feature in the provided Merkle tree. This is to ensure that the old coins have been previously minted.\n\\item The balance equation for the old and new coin values, Equation \\eqref{balance}, is preserved.\n\\end{itemize}}}\n\\medskip\n\nIn order to perform the generation and verification of the proof, we turn to zk-SNARKs. Recall that the circuit $C$ was generated in the \\texttt{Setup} step. $C$ takes a main input $X$ and witness $A$ that are constructed as follows:\n\n\\begin{align}\nX &= \\left( \\text{rt}, \\, {\\text{sn}}^{\\text{old}}_1, \\, {\\text{sn}}^{\\text{old}}_2, \\, {\\text{cm}}^{\\text{new}}_1, \\, {\\text{cm}}^{\\text{new}}_2, \\, v_{\\text{pub}}, \\, h_{\\text{Sig}}, \\, h_1, \\, h_2 \\right) \\\\ \nA &= \\left( \\text{path}_1, \\, \\text{path}_2, \\, {\\text{c}}^{\\text{old}}_1, \\, {\\text{c}}^{\\text{old}}_2, \\, {\\text{addr}}^{\\text{old}}_{\\text{sk}, 1}, \\, {\\text{addr}}^{\\text{old}}_{\\text{sk}, 2}, \\, {\\text{c}}^{\\text{new}}_1, \\, {\\text{c}}^{\\text{new}}_2 \\right),\n\\end{align}\n\\newline\n\nwhere rt is the root of the Merkle tree over coin commitments, the sn are the coin serial numbers, the cm are the coin commitments, $v_{\\text{pub}}$ is the publicly spent amount in the pour transaction, the $h$ are parameters used to ensure non-malleability, the paths are Merkle tree authentication paths for the two old coins, the c are the coins themselves and the addr are the secret address keys associated with the old coins.\n\n\\texttt{Pour} also appends its transaction to the ledger. Note that a transaction tuple does not reveal any of the coin values or recipient addresses besides from $v_{\\text{pub}}$ --- it contains only the following information: \n\n\\begin{equation}\n\\left(\\text{rt}, \\, {\\text{sn}}^{\\text{old}}_1, \\, {\\text{sn}}^{\\text{old}}_2, \\, {\\text{cm}}^{\\text{new}}_1, \\, {\\text{cm}}^{\\text{new}}_2, \\, v_{\\text{pub}}, \\, \\text{info}, \\, *\\right),\n\\end{equation}\n\n\nwhere $*$ is implementation-specific, but would likely include the zero-knowledge proof $\\Pi$ generated by $\\texttt{Prove}$.\n\n\\texttt{Pour} returns the transaction data structure and the two new coins.\n\n\\subsubsection{\\texttt{Receive}}\n\\texttt{Receive} is used to receive payments. It takes as input the ledger and the address key pair of the recipient. It returns a set of coin objects that have not been spent by the recipient, but that were paid to the recipient through \\texttt{Pour} transactions. This excludes coins that were minted by the recipient.\n\n\\subsubsection{\\texttt{VerifyTransaction}}\nThe purpose of \\texttt{VerifyTransaction} is to determine whether or not a provided transaction is valid. It takes as input the ledger, the public parameters generated by \\texttt{Setup} and a mint or pour transaction. It returns $1$ if the transaction is valid, and $0$ otherwise. In theory, \\texttt{VerifyTransaction} could be utilized by both individual users and the nodes of the distributed system.\n\n\\section{Related Work}\nAlthough there has been an extensive amount of research related to zk-SNARKs, only a few have made their way into cryptographic tools \\cite{zk-snarks-blockchains-chapter}. Nevertheless, zk-SNARKs are especially useful for blockchains --- for reasons other than the mere improvement of privacy guarantees. For example, zk-SNARK proofs are non-interactive, which means that verifiers can check a proof at their leisure, without collaborating with the prover. In addition, zk-SNARKs proofs are concise, which means that they can be verified efficiently. These properties can be used to improve the scalability of blockchains \\cite{zk-snarks-blockchains-chapter}.\n\nIt should therefore come as no surprise the zk-SNARKs have been used in blockchain systems other than Zerocash. An example of such a system is CODA \\cite{coda}, where one of the main ideas is to bundle up a group of transactions, calculate a zero-knowledge proof for each, and then provide a single proof that can be used to verify them all \\cite{zk-snarks-blockchains-chapter}. There has also been some Zerocash-inspired work that explores integrating zk-SNARKs into Ethereum \\cite{zeth}.\n\nIn addition to the various blockchain systems that capitalize on zk-SNARKs, there are also variations of zero-knowledge proofs themselves. These include zero-knowledge Succinct Transparent Arguments of Knowledge (zk-STARKs) and bulletproofs.\n\nOne of the main advantages of zk-STARKs over zk-SNARKs is the excellent security provided by zk-STARKs --- for example, they do not require a trusted setup. However, due to their large proof size, which grows as $\\mathcal{O}(\\log^ 2{|C|})$ with respect to the circuit size $|C|$, zk-STARKs are currently not as practical as zk-SNARKs. For the latter, the proof size remains constant as $|C|$ increases \\cite{zk-snarks-blockchains-chapter}.\n\nBulletproofs also do not require a trusted setup. However, their proof size scales as $\\mathcal{O}(\\log{|C|})$, which again makes them (generally) less performant than zk-SNARKs \\cite{zk-snarks-blockchains-chapter}.\n\n\\section{Evaluation}\nOur attempt to implement a basic version of Zerocash in Python was partially successful. First, we were able to build a basic blockchain from scratch. Second, we made our blockchain distributed through the implementation of a \\texttt{Node} class, where different nodes could be run on different ports of the same machine. Third, we managed to build most Zerocash functionalities on top of our blockchain. Lastly, we integrated our code with the C++ zk-SNARK library libsnark and constructed the portion of the NP Statement POUR that checks for coin values. However, we struggled to construct the rest of POUR, which was mostly due to the lack of documentation and tooling on zk-SNARKs.\n\n\\printbibliography\n\n\\end{document}", "meta": {"hexsha": "cbb5e4f6ba6368179c2a7face8a50c51d6e31922", "size": 20344, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/final_report.tex", "max_stars_repo_name": "gwynethallwright/cs291d_project", "max_stars_repo_head_hexsha": "7d9bbb32acec855e777b93b88153869393d458d3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "report/final_report.tex", "max_issues_repo_name": "gwynethallwright/cs291d_project", "max_issues_repo_head_hexsha": "7d9bbb32acec855e777b93b88153869393d458d3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/final_report.tex", "max_forks_repo_name": "gwynethallwright/cs291d_project", "max_forks_repo_head_hexsha": "7d9bbb32acec855e777b93b88153869393d458d3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 87.313304721, "max_line_length": 765, "alphanum_fraction": 0.7699075895, "num_tokens": 5166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.30397252510735806}}
{"text": "\\subsection{Encoding Functions in Process Calculi}\n\\label{sec:blue}\nProcess Calculi are used to describe the structure and behaviour of concurrent processes.  As a basis for the design of programming languages, a calculus should be able to encode canonical calculations with functions.  Encoding the $\\lambda$-calculus, the canonical form of functional programming, to a processes calculus could be done either indirectly or directly.  \n\n\\subsubsection{Indirect Encoding}\nIn \\cite{function_as_process}, Milner gave translation rules from both the lazy $\\lambda$-calculus and the call-by-value $\\lambda$-calculus to his $\\pi$-calculus.  Based on this work, in an higher-order $\\pi$-calculus, functions could be encoded into processes and then passed around the network as a value.  Later, Sangiorgi pointed out that the higher-order approach is unnecessary since the plain $\\pi$-calculus could simulate this higher-order feature by passing a name that points to the encoding process\\cite{HOPI}.\n\nThe main drawback of the two indirect encoding approaches is its inefficiency in translation and reduction.  Indirect encoding will yield a mass of intermediate variables.  Moreover, without a direct representation for functions, complex substitutions of variables for functions are unavoidable during reductions.\n\n\\subsubsection{The Blue Calculus: Encoding Functions in a Direct Style}\nBoudol's blue calculus, $\\pi^*$, is a direct extension of both the $\\lambda$-calculus and the $\\pi$-calculus.  In fact, Boudol defined two calculi in \\cite{Blue}: a name-passing $\\lambda$-calculus ($\\lambda^*$) and an extended $\\pi$-calculus without summation and matching ($\\pi^*$).  The $\\lambda^*$-calculus has $\\lambda$-style syntax and $\\pi$-style reduction relation (Table \\ref{lambda_star}).  It is used as an intermediate language when translating $\\lambda$-terms to $\\pi^*$-terms.  The $\\pi^*$-calculus contains primitives from both the $\\lambda^*$-calculus and the $\\pi$-calculus so that the translation from both languages is straightforward.\n\n\\begin{table} [h]\n  \\begin{center}\n  \\includegraphics[scale=0.5]{lambda_star.png}\n  \\end{center}\n  \\caption{The $\\lambda ^*$-calculus}\n  \\label{lambda_star}\n\\end{table}\n\nThe $\\lambda^*$-calculus differs from the $\\lambda$-calculus in two aspects:\n\\begin{inparaenum}[(i)]\n  \\item The argument ($N$) in an application ($M N$) must be a variable.\n  \\item A convenient notation for name declaration, $def\\ x\\ =\\ N\\ in\\ M$, is allowed.\n\\end{inparaenum}\nIt is important to note that the $\\lambda^*$-calculus only contains the call-by-name evaluation.  This simplifies subsequent studies on relationship between the $\\lambda$-calculus and other calculi.  Translations from $\\lambda$ to $\\lambda^*$ is similar to Launchbury's encoding in \\cite{Launchbury93anatural}:\n\n\\begin{center}\n  \\begin{tabular}{ r c l  c}\n$x^*$&=&$x$&\\\\\n$(\\lambda xM)^*$&=&$\\lambda xM^*$&\\\\\n$(M N)^*$&=&$(def\\ v = N^*\\ in\\ (M^*v))$&($v$ fresh)\\\\\n  \\end{tabular}\n\\end{center}\n\nAs mentioned earlier, both the $\\lambda^*$-calculus and the $\\pi$-calculus (without summation and matching) could be translated to the  $\\pi^*$-calculus (see Table \\ref{trans_blue}).  In addition, a CPS \\footnote{continuation passing style} transform from the $\\pi^*$-calculus to the $\\pi$-calculus is given in \\cite{Blue} as well.  Lastly, Silvano Dal-zilio \\cite{Dal-Zilio97implicitpolymorphic} proposed a implicit polymorphic type sytem for the $\\pi^*$-calculus as an improvement of the original simple type system in \\cite{Blue}.\n\n\\begin{table}[h]\n  \\begin{center}\n  \\begin{tabular}{ l r c l r}\nsyntax:\\\\\n&$P$&::=& $A\\ |\\ D\\ |\\ (P\\ |\\ P)\\ |\\ (\\nu x)P$&processes\\\\\n&$A$&::=& $u\\ |\\ (\\lambda u)P\\ |\\ (Pu)$&agents\\\\\n&$D$&::=& $\\langle u\\ =\\ P\\rangle\\ |\\ \\langle u\\ \\Leftarrow P\\rangle$& declarations\\\\\nstructural equivalence:\\\\\n&$(P\\ |\\ Q)$&$\\equiv$&$(Q\\ |\\ P)$&commutativity\\\\\n&$((P\\ |\\ Q)\\ |\\ R)$&$\\equiv$&$(P\\ |\\ (Q\\ |\\ R))$&associativity\\\\\n&$((\\nu u)P\\ |\\ Q)$&$\\equiv$&$(\\nu v)(P\\ |\\ Q)\\ \\ (u\\ is\\ not \\ free\\ in\\ Q)$&scope migration\\\\\n&$(P\\ |\\ Q)u$&$\\equiv$&$(Pu\\ |\\ Qu)$&distributivity\\\\\n&$((\\nu u)P)v$&$\\equiv$&$(\\nu u)(Pv)\\ \\ (u\\ \\neq\\ v)$&\\\\\n&$Du$&$\\equiv$&$D$&\\\\\n&$\\langle u\\ =\\ P\\rangle$&$\\equiv$&$\\langle u\\ \\Leftarrow\\  (P\\ |\\ \\langle u\\ =\\ P\\rangle )\\rangle$&duplication\\\\\nreduction:\\\\\n&$((\\nu u)P)v$&$\\rightarrow$&$[v/u]P$&$\\beta$\\\\\n&$(u\\ |\\ \\langle u\\ \\Leftarrow\\ P \\rangle)$&$\\rightarrow$&$P$&resource fetching\n  \\end{tabular}\n  \\end{center}\n  \\caption{The $\\pi^*$-Calculus}\n  \\label{blue}\n\\end{table}\n\n\\begin{table}[h]\n  \\begin{center}\n  \\begin{tabular}{ r c l r c l}\n$[x]u$&=&$\\overline{x}u$&$[\\overline{u}v_1\\cdots v_k]$&=&$uv_1\\cdots v_k$\\\\\n$[\\lambda xL]u$&=&$u(x,v)[L]v$&$[u(v_1, \\cdots ,v_k)P]$&=&$\\langle u\\ \\Leftarrow\\ (\\lambda v_1 \\cdots v_k)[P]\\rangle$\\\\\n$[Lx]u$&=&$(\\nu x)([L]v\\ | \\ \\overline{v}xu)$&$[!u(v_1, \\cdots ,v_k)P]$&=&$\\langle u\\ =\\ (\\lambda v_1 \\cdots v_k)[P]\\rangle$\\\\\n$[def\\ x\\ =\\ N\\ in\\ L]u$&=&$(vx)([L]u\\ |\\ !x(v)[N]v)$&$[P\\ |\\ Q]$&=&$([P]\\ |\\ [Q])$\\\\\n&&&$[(\\nu u)P]$&=&$(\\nu u)[P]$\n  \\end{tabular}\n  \\end{center}\n  \\caption{Translation from $\\lambda^*$-calculus and $\\pi$-calculus to $\\pi^*$-calculus}\n  \\label{trans_blue}\n\\end{table}\n", "meta": {"hexsha": "15252e8a4435d4060aaf821ef03b927ac809af4b", "size": 5158, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "s1024484/ReviewReport/Jan2012/full/blue.tex", "max_stars_repo_name": "Jiansen/TAkka", "max_stars_repo_head_hexsha": "d2410190552aeea65c1da5f0ae05f08ba1f4d102", "max_stars_repo_licenses": ["BSD-Source-Code"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-09-11T14:35:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-27T06:36:09.000Z", "max_issues_repo_path": "s1024484/ReviewReport/Sep2011/blue.tex", "max_issues_repo_name": "Jiansen/TAkka", "max_issues_repo_head_hexsha": "d2410190552aeea65c1da5f0ae05f08ba1f4d102", "max_issues_repo_licenses": ["BSD-Source-Code"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "s1024484/ReviewReport/Sep2011/blue.tex", "max_forks_repo_name": "Jiansen/TAkka", "max_forks_repo_head_hexsha": "d2410190552aeea65c1da5f0ae05f08ba1f4d102", "max_forks_repo_licenses": ["BSD-Source-Code"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 68.7733333333, "max_line_length": 653, "alphanum_fraction": 0.6752617294, "num_tokens": 1710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.303972525107358}}
{"text": "\\chapter{Methodology}\n\nIn this chapter, the experiment's methodology is summarized and abstracted in regards to the research goals, experimental setup and program implementation of the work. The process of preparing and benchmarking neural networks with varying arithmetic precisions, as well as the creation of an end-to-end system for carrying out these tests, is detailed. In brief, trained models are obtained from the scientific community for each architecture form various resources, model weights are extracted and inference calculations are made at different precisions.\n\n\\section{Experimental summary}\nThe goal of this work is to study how performing inference calculations with reduced arithmetic precision affects two measures: runtime and accuracy. Given a convolutional neural network model $M$, runtime $R$ and accuracy $A$ of inference with $M$ are calculated with a varying GEMM mode $C \\in{eigen, gemmlowp}$ where $eigen$ \\cite{eigen} uses 32-bit floating-point representation and $gemmlowp$ \\cite{gemmlowp} uses quantized 8-bit integers. $gemmlowp$ also performs quantization, the process of which is detailed in Section \\ref{sec:quantization}. A reference implementation using Caffe \\cite{caffe} was implemented, as described in Section \\ref{sec:caffe}.\n\nConcretely, formula \\ref{eqn:conv} on page \\pageref{eqn:conv} is either computed in full float precision with eigen or with quantized values with gemmlowp as described in the formulas in Section \\ref{sec:quantization}.\n\n\\section{Model architectures}\nThe models used in this work were chosen because they represent small, medium and large model sizes in terms of *the number of trainable weight parameters*. Additionally, in their number of convolutions, they trend upwards, generally exponentially, which creates a natural environment for the comparison of runtimes of convolutions (see Figure \\ref{fig:trend}). ``LeNet'' \\cite{mnist} and ``cifar-10\\_quick'' \\cite{cifar} represent the two smaller models. The larger models include the popular ``VGG-16'' and the even larger ``VGG-19'' \\cite{return}. The medium-sized models included in experimentation consist of the revolutionary ``ResNet50'' and ``ResNet101'' \\cite{resnets2} models. For the purpose of the experiments the convolution layers are of most interest. Each model has a different number of these layers. LeNet has a mere two such layers, cifar-10\\_quick has three, and VGG-16 and VGG-19 have 13 and 16 convolution layers, respectively. Refer to Table \\ref{tbl:cnns} on page \\pageref{tbl:cnns} for the layer outline of these model architectures. ResNet50 and ResNet101 have---by far---the most number of layers, totaling 53 such operations for ResNet50, and 104 operations for ResNet101.\n\n\\bildklein{figures/trend.png}{Convolution counts}{The relationship between convolution counts for the models used.}{fig:trend}\n\nThe model architectures and their relevant properties are highlighted in Table \\ref{tbl:models} on page \\pageref{tbl:models}, while some diagrams of varying model designs are displayed in Figures \\ref{fig:vgg16_design} and \\ref{fig:resnet_design}.\n\n\\bildgross{figures/vgg16.png}{Design of the VGG-16 architecture}{Design of the VGG-16 architecture. [Image courtesy of book.paddlepaddle.org]}{fig:vgg16_design}\n\n\\bildgross{figures/resnet.png}{Design of the ResNet architecture}{Design of the ResNet architecture. [Image courtesy of book.paddlepaddle.org]}{fig:resnet_design}\n\n\\begin{table}[]\n\\centering\n\\caption[Model properties]{The models and their properties.}\n\\label{tbl:models}\n\\begin{tabular}{lllllll}\n\\textbf{Model}     & \\textbf{layers} & \\textbf{params} & \\textbf{input} & \\textbf{convs} & \\textbf{pools} & \\textbf{products} \\\\\nLeNet     & 4               & 430.5K          & 1x28x28        & 2              & 2              & 2                 \\\\\ncifar-10  & 5               & 145.4K          & 3x32x32        & 3              & 3              & 2                 \\\\\nVGG-16    & 16              & 138.3M          & 3x224x224      & 13             & 5              & 3                 \\\\\nVGG-19    & 19              & 143.7M          & 3x224x224      & 16             & 5              & 3                 \\\\\nResNet50  & 50              & 25.6M           & 3x224x224      & 53             & 2              & 1                 \\\\\nResNet101 & 101             & 44.5M           & 3x224x224      & 104            & 4              & 1                \n\\end{tabular}\n\\end{table}\n\n\\section{Inference inputs}\n\\label{sec:infinputs}\nThe size and nature of inputs also differs amongst models used. The LeNet models uses its famous MNIST handwritten database dataset of hand-written digits \\cite{mnist}. These are one-channel (gayscale) images of size $28\\times28$. The cifar-10\\_quick model is fed with $32\\times32$ 3-channel (RGB) images. They are mean-image normalized. All four other models take ImageNet images as input, specifically the first 1000 images of the ILSVRC 2012 competition's validation set \\cite{imagenet}. They are either mean-pixel or mean-image normalized, depending on what was done at training-time, and are of size $224\\times224$.\n\n\\section{Breaking down the low-precision process}\nThe requirements for integrating low precision into convolutions can be broken down into several components. Some of these can---and are---obtained or performed offline, while others are strictly online run-time processes. These components are, briefly: result matrix quantization parameters, input quantization parameters, weight quantization parameters, the actual quantization process for inputs, activations and weights, the GEMM operation, and dequantization. Table \\ref{tbl:gemmlowp} on page \\pageref{tbl:gemmlowp} shows the different steps involved, whether they can be performed offline, and whether they are involved in calculating timings for the experiments. The quantization method is highlighted in Section \\ref{sec:quantization}.\n\n\\section{Implementation details}\n\\subsection{Caffe feature and weight extraction}\n\\label{sec:caffe}\nCaffe is a popular deep-learning framework born out of Berkeley College \\cite{caffe}. It has a vast number of publicly-accessible models made available, and processes in 32-bit float \\cite{caffe}, thus making it a good candidate for building into our custom system as a means to select models, provide model weights and baseline features, and reference against the custom implementation to make sure it is bug-free.\n\nAt this point, it may also be of use to keep track of the number representations of the various libraries involved in extracting weights and features, as to be able to effectively compare to the Caffe baseline, and to keep our weights in the right precision.\n\nWeights are extracted from the forward-pass of the Caffe network, instantiated through Caffe's ``Caffe.Net()'' method, taking a .prototxt and .caffemodel file and called with ``Caffe.Net.().forward()'' \\cite{caffe}. Caffe processes in single floating-point precision, so the current state is 32-bit. After extraction, weights are saved via Python's Numpy package, which uses double precision \\cite{scipy}, so our precision is maintained.\n\nFirst in the pipeline of the Caffe feature extraction is, after the forward pass, the saving of activations by Python's Numpy \\cite{scipy}. Therefore the reference features are of the correct precision and are comparable to the 32-bit experiment results.\n\nThe inputs, having values typically ranging from 0-255, are inherently integers and remain so until activated in the first layer of the network (or rather are represented by floats with a trailing ``.0'', unless quantized), where they either remain integers (in integer mode) or become floats due to multiplication with weights.\n\n\\subsection{Inference}\nAll experiments were run on an Intel Core i5-2520M CPU @ 2.50GHz x 4 with 3.7 GB of RAM. The operating system was Ubuntu 16.04 LTS 64-bit. Additionally, auxiliary experiments were run on a Raspberry Pi 3 (see Section \\ref{sec:pi}.\n\nIn both modes, input is run through the custom system related to this work. The system includes bare-bones implementations of all relevant layers: convolution, pooling, ReLU, fully-connected, batch-normalization, scale, and eltwise. The inference files and makefiles are automatically generated via a script-generation script written in Python, which parses the Caffe prototxt files and outputs a C++ script in the most minimal way possible. Great care has been taken in ensuring that the script is minimal: all large objects are passed-by-reference when possible, eigen routines are called conservatively, the loading of parameters, weights and inputs, handled by the Armadillo package \\cite{eigen_vs_armadillo}, is optimized, and the compiler is set to optimize for speed. The options used at compile time are as follows: \n\n\\lstset{language=make}\n-c -O3 -march=native -std=c++11\n\nThe option ``-O3'' sets the compiler to make full optimization: it attempts to reduce code size and execution time, and performs all other optimizations possible. Furthermore, ``-march=native'' tells the compiler to use the platform-specific assembly code instructions.\n\n\\subsection{Integrating low precision}\nThe low-arithmetic precision module was taken from gemmlowp, a ``small self-contained low-precision GEMM library'' \\cite{gemmlowp}. Gemmlowp performs several tasks needed for the experiments in this work. Apart from performing the actual GEMM procedure, gemmlowp quantizes inputs, dequantizes, retrieves parameters needed for these quantizations, and quantizes weights. This section will detail the processes involved in replacing regular floating-point GEMM operations with a custom call to the gemmlowp module.\n\n\\begin{table}[]\n\\centering\n\\caption[Low-precision GEMM broken down by process]{Subprocesses of low-precision GEMM. Although low-precision arithmetic is in theory faster, computation time can quickly add up with other online operations.}\n\\label{tbl:gemmlowp}\n\\begin{tabular}{lll}\n\\textbf{Process}                                       & \\textbf{possible offline?} & \\textbf{incl. in timing?} \\\\\nCalculate input matrix MIN/ MAX     & yes                        & yes                       \\\\\nCalculate weight matrix MIN/ MAX     & yes                        & no                        \\\\\nCalculate activation matrix MIN/ MAX & can estimate               & no                        \\\\\nQuantize input matrix                & yes                        & yes                       \\\\\nQuantize weight matrix               & yes                        & no                        \\\\\nGEMM                                 & no                         & yes                       \\\\\nDequantize activation matrix         & no                         & yes                      \n\\end{tabular}\n\\end{table}\n\nOne of the convenient realities that makes low-precision GEMM work is the fact that many---and sometimes all---of the parameters can be calculated offline \\cite{warden_quantize}. For the weights of a cnn, this is always the case, as the weight parameters are learned at training-time. Thus, the minimum and maximum of these matrices can be stored as constants. For the inputs, it is also possible to collect parameters offline. This is straightforward for standard RGB images, known to hold values in the range [0-255]. The exact processes that accompany these calculations are detailed in the equations in Section \\ref{sec:quantization}.\n\nFor result/ activation parameters, this is a bit more complex. One cannot know beforehand the resulting matrices at each convolution. However, it's possible to collect estimations of these parameters using the training images. In this experiment, these parameters are gathered prior to runtime using a \"hold-off\" set whose distinct purpose is to provide runtime parameters. This is all done offline, as it is equivalent to collecting the same parameters at training time. This cuts down on timing and apparently doesn't cost much in terms of accuracy, as is explained in the next chapter.\n\nQuantizing inputs and weights, like finding their parameters, can also be done offline. However here, quantization parameters and quantizations of the input layer have been treated equally with other activation layers, and thus are computed online. We assume for the purposes of these experiments that the input matrix range was not known beforehand.\n\nGEMM itself is an online operation, as well as dequantizing activation matrices, as results are of course not known until after GEMM.", "meta": {"hexsha": "247f5928a44bd306bdb597e633d96e0ebe8586b2", "size": 12474, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/chapters/methodology.tex", "max_stars_repo_name": "KaiserKlayton/lpa_cnn", "max_stars_repo_head_hexsha": "93d7b7b31d458b9ca002612df0882aa039b5885a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-06-17T00:28:31.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-30T06:39:30.000Z", "max_issues_repo_path": "tex/chapters/methodology.tex", "max_issues_repo_name": "claytonvioland/lpa_cnn", "max_issues_repo_head_hexsha": "93d7b7b31d458b9ca002612df0882aa039b5885a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2017-08-15T13:05:39.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-24T03:01:01.000Z", "max_forks_repo_path": "tex/chapters/methodology.tex", "max_forks_repo_name": "claytonvioland/lpa_cnn", "max_forks_repo_head_hexsha": "93d7b7b31d458b9ca002612df0882aa039b5885a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 137.0769230769, "max_line_length": 1200, "alphanum_fraction": 0.7368125701, "num_tokens": 2810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.303972525107358}}
{"text": "% !TEX root = altosaar-2020-thesis.tex\n\\chapter{Introduction}\\label{ch:intro}\n\\lettrine[image=true,lines=3]{design/F}{rom} the development of novel antibiotics~\\citep{stokes2020a-deep} to cataloging sources of light in the night sky~\\citep{regier2019cataloging}, many domains in science can benefit from applied machine learning methods. However, the utility of such methods hinges on building the structure of a problem---knowledge about the data or task---into a machine learning solution. Whether the setting is statistical physics or recommender systems, an off-the-shelf machine learning method can serve as a starting point. But performance is sacrificed when a method cannot be customized to the specifics of an applied scientific problem. This thesis focuses on probabilistic modeling, where what is known about a problem can be molded into assumptions about a probability distribution. We develop probabilistic modeling methods that use the structure of a problem to yield meaningful solutions in the study of models with large numbers of random variables in statistical physics systems and recommender systems. In tandem, this thesis develops an algorithm to improve the accuracy of approximations to probabilistic models, through the use of the structure of a probability model during optimization. By both building scalable probabilistic modeling methods tailored to answer scientific questions, and improving flexible probabilistic modeling methods themselves, we highlight the reciprocal relationship between these aims.% suiting machine learning methods to a scientific domain and developing flexible probabilistic modeling techniques.\n\nOne example of an applied problem in statistical physics is the study of probable configurations of atoms in a material. Simulating a material to find likely configurations of atoms with statistical physics models can be expensive, but designing materials with improved properties is valuable~\\citep{schmidt2019recent}. The computational cost of these simulations for studying statistical physics models can be reduced by doing math, for example in analytical calculations to develop approximations or to incorporate knowledge of how neighboring atoms interact into simulations~\\citep{swendsen1987nonuniversal}. A challenge in studying statistical physics models is balancing problem-specific customization with the resulting computational savings. Machine learning techniques applied to statistical physics systems can be used to develop generic methods that exploit problem structure for better performance. These methods can be re-used across models, saving practitioners time.\n\nWhere statistical physics concerns probable configurations of interacting atoms, recommender systems find items a user is likely to interact with~\\citep{koren2009matrix}. For example, humans eat. A meal recommender system can predict which meals someone is likely to consume. Such a recommendation model might inform its predictions using the history of meals a user has eaten, namely which foods comprise those meals. A property of this type of data is that items (meals) are associated with unordered collections of attributes (sets of foods). This means that the number of possible meals a user might consume is very large. Existing methods for this type of data either cannot scale to large numbers of datapoints, or fail to accurately predict which items a user is likely to consume. This highlights the need to imbue a recommendation model with both properties of the data (such as meals represented as unordered sets) and the goals of the recommendation problem, or accurate prediction of which items a user will consume.\n\n% define variational approximation here?\nBoth statistical physics models and recommender systems can be framed as probability models, the former as probable configurations of atoms, and the latter as probable items users may consume. Probabilistic modeling relies on inferring the parameters of a probability model using knowledge about the structure of the problem. For example, knowledge in the form of data regarding which meals someone has eaten can inform the predictions of a recommendation model; or, knowledge of how neighboring atoms interact in a material can be used in a probabilistic model of that material.\n\nPractitioners that work with probability models seek probabilistic inferences. For example, the goals of such inferences include computing probabilities, summing over the random variables in a probability model, or finding likely configurations of random variables. Common inference methods are Markov Chain Monte Carlo~\\citep{metropolis1953equation}, variational inference~\\citep{blei2017variational}, and maximum likelihood estimation~\\citep{bishop2006pattern}. This thesis uses variational inference and maximum likelihood estimation, as both algorithms can be scaled to large probability models~\\citep{hoffman2013stochastic,robbins1951a-stochastic}. In particular, the variational inference algorithm can aid probabilistic inference in interacting systems of random variables found in statistical physics models. However, variational inference is sensitive to the initial choice of parameters governing the probability of the random variables under study. The accuracy of inferences of likely configurations of random variables can suffer, depending on this choice of initial parameters. Inference algorithms such as variational inference are utile in applied domains insofar as their performance is independent of the initial choice of parameters.\n\nThis thesis is organized as follows. \\Cref{ch:background} introduces probabilistic models and gives examples of their use in statistical physics and recommender systems. We also review two approaches for statistical inference in probability models: variational inference and maximum likelihood estimation. \\Cref{ch:hvm} develops and applies variational inference methods for statistical physics models. We show that exploiting the structure of a statistical physics model in a variational inference method is advantageous. This work was presented in \\citet{altosaar2019hierarchical}. \\Cref{ch:rfs} develops probability models for recommending items with sets of attributes and is based on \\citet{altosaar2020rankfromsets:}. Similar to variational methods in physics, accounting for the structure of the problem helps: probability models that represent set-valued datapoints and the goals of the recommendation task are accurate and scalable. \\Cref{ch:pvi} develops \\gls{PVI} based on \\citet{altosaar2018proximity}. \\gls{PVI} is an inference algorithm that is imbued with information about a probability distribution we wish to infer. In this case, the structure of the problem is information about a probability distribution, which is used to inform an algorithm for fitting a probability model. We show how this enables \\gls{PVI} to obtain accurate solutions. Finally, \\Cref{ch:discussion} reviews how knowledge about a problem is useful in building probabilistic models for science solutions. We apply the \\gls{PVI} algorithm developed in \\Cref{ch:pvi} to the statistical physics setting of \\Cref{ch:hvm} and the recommender systems application of \\Cref{ch:rfs}. This highlights that methods development goes hand-in-hand with the aims of applied probabilistic modeling. We close with a discussion of extensions of this line of work.\n\n", "meta": {"hexsha": "5ade5205db067492dfad68b69309e9c16e901a05", "size": 7377, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ch_intro.tex", "max_stars_repo_name": "altosaar/thesis", "max_stars_repo_head_hexsha": "287484c87db0eca46f4cdae70ff8582bd66ce5a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-05-21T18:56:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-26T12:18:53.000Z", "max_issues_repo_path": "ch_intro.tex", "max_issues_repo_name": "altosaar/thesis", "max_issues_repo_head_hexsha": "287484c87db0eca46f4cdae70ff8582bd66ce5a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch_intro.tex", "max_forks_repo_name": "altosaar/thesis", "max_forks_repo_head_hexsha": "287484c87db0eca46f4cdae70ff8582bd66ce5a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 461.0625, "max_line_length": 1835, "alphanum_fraction": 0.8329944422, "num_tokens": 1411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.303972525107358}}
{"text": "In this section, we consider a particular application of the proposed approach\nto probabilistic transient analysis presented in \\sref{chaos-transient-analysis}\nin order to illustrate its usage in practice. We begin by describing the\nscenario being considered.\n\n\\subsection{\\problemtitle}\n\nAt Stage~1 in \\fref{chaos-overview}, the quantity of interest \\g is the\ntransient power and temperature profiles corresponding to a given workload. Let\nus now specify the parameters \\vu that make \\g uncertain to the designer of the\nsystem.\n\nAs discussed in \\sref{power-model}, the total dissipation of power is composed\nof two major components: dynamic and static. The influence of process variation\non dynamic power is known to be negligibly small \\cite{srivastava2010}; on the\nother hand, the variability in static power is substantial, with the\nsubthreshold leakage current contributing the most \\cite{juan2011, juan2012}.\nWith this in mind, we focus our attention on the subthreshold leakage and, more\nspecifically, on the effective channel length, which is denoted by \\u, since it\nhas the strongest influence on this leakage (including its impact on other\nimportant parameters such as the threshold voltage) and is severely deteriorated\nby process variation \\cite{chandrakasan2000}.\n\n\\inputfigure{chaos-beta-gaussian}\nIt is well known that the dispersion of the effective channel length around its\nnominal value resembles the bell shape of Gaussian distributions. Therefore,\nsuch variations are often conveniently modeled using Gaussian random variables\n\\cite{bhardwaj2006, ghanta2006, huang2009a, shen2009, chandra2010,\nsrivastava2010, juan2011, juan2012, lee2013}. Due to the underlying physics and\nfor demonstration purposes, we take a step further and embed into the model the\nfact that the effective channel length---occupying the space between the drain\nand source of a transistor---cannot be arbitrarily large or take negative\nvalues, which Gaussian distributions allow it to do. In other words, we require\nthe model of \\u to have a bounded support. To this end, we propose to model the\neffective channel length and other physically bounded parameters using the\nfour-parameter family of beta distributions as\n\\begin{equation} \\elab{beta-distribution}\n  \\u \\sim \\mathrm{Beta}(a, b, c, d)\n\\end{equation}\nwhere $a$ and $b$ are the shape parameters, and $c$ and $d$ are the left and\nright bounds of the support, respectively. The parameters $a$ and $b$ can be\nchosen so that the frequently observed bell shape is preserved. An illustration\nis given in \\fref{chaos-beta-gaussian} where a beta distribution is fitted to\nthe standard Gaussian distribution; alternatively, one can match probabilistic\nmoments. It can be seen that the curves are nearly indistinguishable; however,\nthe beta one has a bounded support $[-4, 4]$, which can potentially lead to more\nrealistic models.\n\nThe variability in \\u is split into global and local parts \\cite{shen2009,\nchandra2010, juan2012}, which are denoted by $\\u_\\overall$ and $\\u_\\local$,\nrespectively. The former can be treated as a composition of inter-lot,\ninter-wafer, and inter-die variations, and the latter as a composition of\nintra-die variations. The variability $\\u_\\overall$ is assumed to be shared by\nall the \\np processing elements, whereas each processing element is assumed to\nhave its own local parameter $\\u_{\\local, i}$. The effective channel length of\nprocessing element~$i$ is then modeled using the following formula:\n\\[\n  \\u_i = \\u_\\nominal + \\u_\\overall + \\u_{\\local, i}\n\\]\nwhere $\\u_\\nominal$ is the nominal value of the effective channel length.\nConsequently, the uncertain parameters of the problem are\n\\[\n  \\vu = (\\u_{\\local, 1}, \\dotsc, \\u_{\\local, \\np}, \\u_\\overall): \\Omega \\to \\real^{\\np + 1}.\n\\]\n\nGlobal variations are typically assumed to be uncorrelated with respect to the\nlocal ones. The latter, however, are known to have high spatial correlations.\nSimilarly to the treatment in \\cref{uncertainty-process-fabrication}, we model\nthese correlations using the composite correlation function given in\n\\eref{bayes-correlation}, which is inspired by the variation patterns induced by\nthe fabrication process \\cite{friedberg2005, chandrakasan2000, cheng2011}.\nSpecifically, the correlation function imposes similarities between those\nlocations on the die that are close to each other as well as between those\nlocations that are at the same distance from the center of the die; see also\n\\cite{ghanem1991, ghanta2006, bhardwaj2008, huang2009a, lee2013}.\n\nAlthough \\eref{bayes-correlation} captures certain features that are\ncharacteristic of the fabrication process, it is still an idealization. In\npractice, it can be difficult to make a justifiable choice and tune such a\nformula, which is a prerequisite for techniques based on the continuous \\ac{KL}\ndecomposition, such as those discussed in \\sref{chaos-past}. A correlation\nmatrix, on the other hand, can be readily estimated from measurements and thus\nis a more probable input to probabilistic analysis. Hence, we use\n\\eref{bayes-correlation} for the sole purpose of constructing a correlation\nmatrix of $\\set{\\u_{\\local, i}}_{i = 1}^\\np$. For convenience, this correlation\nmatrix is extended by one dimension in order to accommodate $\\u_\\overall$ along\nwith $\\set{\\u_{\\local, i}}_{i = 1}^\\np$. Thus, the matrix acquires one\nadditional nonzero diagonal element equal to unity; the resulting matrix is the\ncorrelation matrix of \\vu denoted by $\\correlation{\\vu}$.\n\nLet us now be more specific about the power model in \\eref{chaos-power-model}.\nIn the ongoing scenario, \\f can be rewritten as the following summation:\n\\[\n  \\f(i, \\vq, \\vu) = \\f_\\dynamic(i) + \\f_\\static(\\vq, \\vu)\n\\]\nwhere $\\f_\\dynamic: \\natural[+] \\to \\real^\\np$ and $\\f_\\static: \\real^\\np \\times\n\\real^\\nu \\to \\real^\\np$. Without loss of generality, the dynamic component\n$\\f_\\dynamic$ is assumed to be given as a dynamic power profile (recall\n\\eref{power-profile}) denoted by $\\mp_\\dynamic$. Similarly to\n\\sref{bayes-results}, the modeling of the static component $\\f_\\static$ is based\non \\up{SPICE} simulations of a reference electrical circuit composed of\n\\up{BSIM4} devices \\cite{bsim} configured according to the 45-nm \\up{PTM}\n\\up{HP} model \\cite{ptm}; specifically, we use a series of \\up{CMOS} invertors.\nThe simulations are performed with respect to a sufficiently wide fine-grained\ntwo-dimensional grid---the effective channel length against temperature---and\nthe results are tabulated. An interpolation technique is then utilized whenever\nit is necessary to calculate $\\f_\\static$ at a point within the range of the\ngrid.\n\nLastly, in order to be able to perform temperature calculations, an adequate\nthermal \\up{RC} circuit should be constructed. Given the specification of the\nplatform under consideration---including the floorplan of the die and the\nconfiguration of the thermal package---this circuit is obtained by means of\nHotSpot \\cite{skadron2003}. The structure of the circuit is the one described in\n\\sref{temperature-model}.\n\nTo conclude, in this section, we address the variability in the effective\nchannel length. The input to our analysis is composed of the marginal\ndistributions of the uncertain parameters \\vu, which are beta distributions, and\nthe corresponding correlation matrix $\\correlation{\\vu}$. Let us now go over the\nother stages of our methodology presented in \\sref{chaos-uncertainty-analysis}\nand depicted in \\fref{chaos-overview}.\n\n\\subsection{Probability Transformation}\n\nAt Stage~2 in \\fref{chaos-overview}, \\vu should be processed in order to extract\na vector of mutually independent random variables \\vz via a suitable\ntransformation $\\transform$; see \\eref{chaos-transformation}. Following the\nguidance given in \\sref{chaos-transformation}, the most apposite $\\transform$ in\nthe ongoing scenario is the Nataf transformation. The whole procedure is\ndescribed in detail in \\xref{probability-transformation} and can be seen in\n\\eref{probability-transformation}.\n\nUsing this specific $\\transform$, arbitrary marginal distributions can be\nprescribed for \\vz. There are no restrictions in this regard as long as a\nsuitable polynomial basis can be constructed, which is discussed in\n\\sref{chaos-construction}. We let \\vz have beta distributions, keeping \\vu and\n\\vz in the same family of distributions.\n\nSince the number of stochastic dimensions, which is $\\nu = \\np + 1$ in the case\nof \\vu, directly impacts the computational cost of \\ac{PC} expansions, which is\nnoted in \\sref{chaos-construction}, one should consider the possibility of model\norder reduction before constructing these expansions. Therefore, the reduction\nprocedure described in \\xref{probability-transformation} in connection with\n$\\transform$ is assumed to be engaged in this transformation. The reduced\ndimensionality is denoted by \\nz.\n\n\\subsection{Surrogate Construction}\n\nAt Stage~3 in \\fref{chaos-overview}, the uncertain parameters, power model, and\ntemperature model developed in the previous subsections are to be fused together\nunder the desired workload $\\mp_\\dynamic$ in order to produce the corresponding\nstochastic power and temperature profiles denoted by \\mp and \\mq, respectively.\n\nIn the current scenario, the construction of \\ac{PC} expansions is based on the\nJacobi polynomial basis, since it is preferable in situations involving\nbeta-distributed parameters \\cite{xiu2010}. To give a concrete example, for a\ndual-core platform ($\\np = 2$) with two stochastic dimensions ($\\nz = 2$), the\nsecond-level \\ac{PC} expansion ($\\lc = 2$) of temperature at time step~$i$ is as\nfollows:\n\\begin{equation} \\elab{chaos-expansion-example}\n  \\begin{split}\n    \\chaos{2}{2}{\\vq_i}\n    =    {} & \\hat{\\vq}_{i, (0, 0)} \\psi_{(0, 0)} +\n              \\hat{\\vq}_{i, (1, 0)} \\psi_{(1, 0)} +\n              \\hat{\\vq}_{i, (0, 1)} \\psi_{(0, 1)} \\\\\n    {} + {} & \\hat{\\vq}_{i, (1, 1)} \\psi_{(1, 1)} +\n              \\hat{\\vq}_{i, (2, 0)} \\psi_{(2, 0)} +\n              \\hat{\\vq}_{i, (0, 2)} \\psi_{(0, 2)}\n  \\end{split}\n\\end{equation}\nwhere the coefficients $\\set{\\hat{\\vq}_{i \\vj}}$ are vectors with two elements\ncorresponding to the two processing elements. Regarding the basis,\n\\begin{align*}\n  & \\psi_{(0, 0)}(\\vz) = 1, \\\\\n  & \\psi_{(1, 0)}(\\vz) = 2 z_1, \\\\\n  & \\psi_{(0, 1)}(\\vz) = 2 z_2, \\\\\n  & \\psi_{(1, 1)}(\\vz) = 4 z_1 z_2 \\\\\n  & \\psi_{(2, 0)}(\\vz) = \\frac{15}{4} z_1^2 - \\frac{3}{4}, \\text{ and} \\\\\n  & \\psi_{(0, 2)}(\\vz) = \\frac{15}{4} z_2^2 - \\frac{3}{4}.\n\\end{align*}\nThe Jacobi polynomials have two parameters \\cite{xiu2010}, and the ones shown\nabove correspond to the case where both parameters are equal to two. Such a\nseries can be shorter or longer, depending on the accuracy requirements given by\n\\lc. The expansion of power has the same structure but different coefficients.\n\nThe next step is to compute the coefficients of power $\\set{\\hat{\\vp}_{i \\vj}}$\nin \\eref{chaos-recurrence}, which subsequently yield the coefficients of\ntemperature $\\set{\\hat{\\vq}_{i \\vj}}$. As discussed in\n\\sref{chaos-construction}, these computations involve multidimensional\nintegration with respect to the distribution of \\vz, and they should be\nperformed numerically using an adequate quadrature $\\quadrature{\\nz}{\\lq}$. When\nbeta distributions are involved, the natural choice is Gauss--Jacobi\nquadratures, which belong to the class of Gaussian quadratures introduced in\n\\xref{numerical-integration}. Given $\\quadrature{\\nz}{\\lq}$, the coefficients\nare computed as shown in \\eref{chaos-coefficient}. It is important to note that\n\\lq should be chosen in such a way that the quadrature is exact for polynomials\nof total order up to at least $2 \\lc$, that is, twice the level of \\ac{PC}\nexpansions, which is discussed in \\sref{chaos-construction}. Consequently, $\\lq\n\\geq \\lc$, since the quadrature is Gaussian.\n\nTo summarize, we have completed four out of five stages of the proposed\nframework depicted in \\fref{chaos-overview}. The result is a lightweight\nsurrogate for the entire system. At each time step, the surrogate is composed of\ntwo \\np-valued polynomials---one is for power, and the other one for\ntemperature---which are defined in terms of \\nz mutually independent random\nvariables.\n\n\\subsection{Post-Processing}\n\nAt Stage~4 in \\fref{chaos-overview}, the constructed expansions are utilized in\norder to assist the designer in analyzing the impact of process variation on\npower- and temperature-related characteristics of the system that is being\ndeveloped. Consider, for example, \\eref{chaos-expansion-example}. It can be seen\nthat the surrogate model has a negligibly small computational cost: for any\noutcome of \\vz, one can readily calculate the corresponding temperature by\nplugging this outcome into \\eref{chaos-expansion-example}; the same applies to\npower. Therefore, the representation can be trivially analyzed in order to\nretrieve various statistics about the system. Let us illustrate a few of them\nusing the expansion given in \\eref{chaos-expansion-example}.\n\n\\inputfigure{chaos-application-power}\n\\inputfigure{chaos-application-temperature}\nAssume that the dynamic power profile $\\mp_\\dynamic$ is the one shown in\n\\fref{chaos-application-power}. Having constructed a surrogate with respect to\nthis profile, we can calculate, for instance, the expectation and variance of\nthe temperature that the system has at a certain moment in time, which is a\ntrivial operation given the formulae in \\eref{chaos-moments}. For the whole time\nspan of $\\mp_\\dynamic$, these quantities are plotted in\n\\fref{chaos-application-temperature} where the dashed lines correspond to one\nstandard deviation above the corresponding expectations. The displayed curves\nclosely match those obtained via \\ac{MC} sampling with $\\no = 10^4$ samples;\nhowever, our method takes less than a second, whereas \\ac{MC} sampling takes\nmore than a day, which will be discussed further in\n\\sref{chaos-transient-results}. In addition, the \\ac{PDF} of the temperature at\nthat moment can be estimated. This operation is performed by sampling the\nsurrogate, in which case we might obtain curves similar to those shown in\n\\fref{chaos-application-density}, which is a part of a different example given\nin \\sref{chaos-transient-results}.\n", "meta": {"hexsha": "e7d524753eda8a85f9e3b4d38fee5f96fcc24036", "size": 14195, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "include/uncertainty/process/development/transient-application.tex", "max_stars_repo_name": "IvanUkhov/thesis", "max_stars_repo_head_hexsha": "95a7e2ee7664b94156906322610555e36e53cfe0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/uncertainty/process/development/transient-application.tex", "max_issues_repo_name": "IvanUkhov/thesis", "max_issues_repo_head_hexsha": "95a7e2ee7664b94156906322610555e36e53cfe0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/uncertainty/process/development/transient-application.tex", "max_forks_repo_name": "IvanUkhov/thesis", "max_forks_repo_head_hexsha": "95a7e2ee7664b94156906322610555e36e53cfe0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.1458333333, "max_line_length": 92, "alphanum_fraction": 0.7711165903, "num_tokens": 3624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3039725175901484}}
{"text": "% Summary of using velocity dispersions as an age proxy -- lit review\n\\subsection{Kinematic ages}\n\nThe star forming molecular gas clouds observed in the Milky Way have a low\nout-of-plane, or vertical, velocity \\citep[\\eg][]{stark1989, stark2005,\naumer2009, martig2014, aumer2016}.\nIn contrast, the vertical velocities of older stars are observed to be larger\nin magnitude on average \\citep{stromberg1946, wielen1977, nordstrom2004,\nholmberg2007, holmberg2009, aumer2009, casagrande2011, ting2019, yu2018}.\nThere are two possible explanations for this observed increase in velocity\ndispersion with age: either stars are born kinematically `cool' and their\norbits are heated over time via interactions with giant molecular clouds\n\\citep[see][for a review of secular evolution in the MW]{sellwood2014}, or\nstars formed kinematically `hotter' in the past \\citep[\\eg][]{bird2013}.\nEither way, the vertical velocity dispersions of thin disk stars are observed\nto increase with stellar age.\nThis behavior is codified by Age-Velocity dispersion Relations (AVRs), which\ntypically express the relationship between age and velocity dispersion as a\npower law: $\\sigma_v \\propto t^\\beta$, with free parameter, $\\beta$\n\\citep[\\eg][]{holmberg2009, yu2018}.\nThese expressions can be used to infer the ages of groups of stars from their\nvelocity dispersions, as we did in \\citet{lu2021}\n\nKinematic ages have been used to explore the evolution of cool dwarfs for over\na decade.\n\\citet{west2004, west2006} found that the fraction of magnetically active M\ndwarfs decreases over time, by using the vertical distances of stars from the\nGalactic mid-plane as an age proxy, and \\citet{west2008} used kinematic ages\nto calculate the expected activity lifetime for M dwarfs of different spectral\ntypes.\n\\citet{faherty2009} used tangential velocities to infer the ages of M, L and T\ndwarfs, and showed that dwarfs with lower surface gravities tended to be\nkinematically younger, and \\citet{kiman2019} used velocity dispersion as an\nage proxy to explore the evolution of H$\\alpha$ equivalent width (a magnetic\nactivity indicator), in M dwarfs.\n\n% After the development of a radiative core, little angular momentum is\n% transported between the core and convective envelope and, if wind-braking\n% slows the surface substantially before the two zones recouple, the core may\n% rotate much more quickly than the envelope.\n% The Sun rotates almost as a solid body \\citep[\\eg][]{thompson1996}, so it is\n% expected that the cores and envelopes of Solar-like stars eventually\n% re-couple, with angular momentum efficiently transported between them.\n% The timescales for recoupling have been studied extensively and explored in\n% theoretical models for decades \\citep[\\eg][]{endal1981, macgregor1991,\n% denissenkov2010, gallet2013, lanzafame2015}.\n\nAVRs are usually calibrated in Galactocentric velocity coordinates (\\vx, \\vy,\n\\vz\\ or $UVW$), and these velocities can only be calculated with full 6D\npositional and velocity information, however most \\kepler\\ rotators do not\nhave RV measurements\\footnote{Although RVs for most will be released in \\gaia\\\nDR3}.\nIn Angus \\etal\\ (2020) we used velocity in the direction of Galactic latitude\n(\\vb) as a stand-in for \\vz\\ because, in the {\\it Galactic} coordinate system,\nvelocities can be calculated from 3D positions and {\\it 2D} proper motions.\nThe \\kepler\\ field lies at low Galactic latitude, so \\vb\\ is a close\napproximation to \\vz.\nThough \\vb\\ velocity dispersion does not equal \\vz\\ velocity dispersion, it\nstill increases monotonically over time and provides accurate age rankings for\n\\kepler\\ stars.\nUnfortunately however, given that AVRs are calibrated in {\\it Galactocentric}\ncoordinates (\\vx, \\vy, \\vz), we could not directly translate \\vb\\ velocity\ndispersions to ages.\n\nIn this paper, our aim was to use kinematic ages to calibrate a new\ngyrochronology relation, for which four main steps were required.\nFirstly, we inferred {\\it vertical} velocity, \\vz, for each star without an RV\nmeasurement by marginalizing over missing RVs using a hierarchical Bayesian\nmodel (see section \\ref{sec:velocity_inference}).\nSecondly, we calculated velocity dispersion for every star using a moving, or\nrolling dispersion method (see section \\ref{sec:velocity_dispersion}).\nThirdly, these velocity dispersions were converted into ages using an AVR\n\\citep[][section \\ref{sec:avr}]{yu2018}.\nFinally, we used a Gaussian process model to capture the complexities of\nstellar rotational evolution and calibrated a new gyrochronology relation\nusing our kinematic ages, plus benchmark cluster and asteroseismic stars in\nsection \\ref{sec:gp_model}.\n", "meta": {"hexsha": "94ce4bfc5974253ee5581e6a3528d84711da696c", "size": 4646, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/intro_kinematics.tex", "max_stars_repo_name": "RuthAngus/aviary", "max_stars_repo_head_hexsha": "73c11348b32c29ffb0bd3d1d6179df95e89c3121", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paper/intro_kinematics.tex", "max_issues_repo_name": "RuthAngus/aviary", "max_issues_repo_head_hexsha": "73c11348b32c29ffb0bd3d1d6179df95e89c3121", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/intro_kinematics.tex", "max_forks_repo_name": "RuthAngus/aviary", "max_forks_repo_head_hexsha": "73c11348b32c29ffb0bd3d1d6179df95e89c3121", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.5641025641, "max_line_length": 78, "alphanum_fraction": 0.7974601808, "num_tokens": 1151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631556226291, "lm_q2_score": 0.5, "lm_q1q2_score": 0.30383157781131453}}
{"text": "\\chapter*{Appendix}\\label{chap:app}\n\\addcontentsline{toc}{chapter}{Appendix}\n\\setcounter{section}{0}\n\\setcounter{figure}{0}\n\\renewcommand{\\thesection}{\\Alph{section}}\n\\renewcommand{\\thesubsection}{\\Alph{section}.\\arabic{subsection}}\n\\numberwithin{figure}{section}\n\\renewcommand{\\thefigure}{\\Alph{section}.\\arabic{figure}}\n\n\\vspace{-0.5cm}\n\n\\section{Big Bang Nucleosynthesis}\n\n\\subsection{Temperature Evolution and Universe's Expansion}\\label{sec:evo}\n\nWhen a neutrinophilic BSM particle is present, the differential equations governing the evolution of $T_\\nu$ and $T_\\gamma$ read:\n\\begin{subnumcases}{\\hspace{-2.8cm}\\textrm{Neutrinophilic }}\n\\label{eq:dTgamdt_DM_nu}\n    \\!\\! \\,\\, \\frac{dT_\\nu}{dt} = -\\frac{ 12 H \\rho_\\nu +3 H( \\rho_{\\chi} + p_{\\chi})  - 3 \\frac{\\delta \\rho_{\\nu}}{\\delta t}}{3 \\, \\frac{\\partial \\rho_\\nu}{\\partial T_\\nu } +  \\frac{\\partial \\rho_{\\chi}}{\\partial T_\\nu } }\\,, \\\\\n    \\!\\! \\,\\, \\frac{dT_{\\gamma}}{dt}  =- \\frac{  4 H \\rho_{\\gamma} + 3 H \\left( \\rho_{e} + p_{e}\\right) + 3 H \\, T_\\gamma \\frac{dP_{\\text{int}}}{dT_\\gamma}+3 \\frac{\\delta \\rho_{\\nu}}{\\delta t}  }{ \\frac{\\partial \\rho_{\\gamma}}{\\partial T_\\gamma} + \\frac{\\partial \\rho_e}{\\partial T_\\gamma} +T_\\gamma \\frac{d^2 P_{\\text{int}}}{dT_\\gamma^2} }\\,,\n\\end{subnumcases}\nwhilst for an electrophilic particle, they are given by:\n\\begin{subnumcases}{\\textrm{Electrophilic }}\n    \\!\\! \\,\\, \\frac{dT_\\nu}{dt} = -\\frac{ 12  H \\rho_\\nu  -  3 \\frac{\\delta \\rho_{\\nu}}{\\delta t}}{3 \\, \\frac{\\partial \\rho_\\nu}{\\partial T_\\nu }}\\,, \\\\\n    \\!\\! \\,\\, \\frac{dT_{\\gamma}}{dt}  =- \\frac{  4 H \\rho_{\\gamma} + 3 H \\left( \\rho_{e} + p_{e}\\right) +  3 H \\left( \\rho_{\\chi} + p_{\\chi}\\right) + 3 H \\, T_\\gamma \\frac{dP_{\\text{int}}}{dT_\\gamma}+ 3\\frac{\\delta \\rho_{\\nu}}{\\delta t}  }{ \\frac{\\partial \\rho_{\\gamma}}{\\partial T_\\gamma} + \\frac{\\partial \\rho_e}{\\partial T_\\gamma} + \\frac{\\partial \\rho_{\\chi}}{\\partial T_\\gamma} +T_\\gamma \\frac{d^2 P_{\\text{int}}}{dT_\\gamma^2} } \\ , \\label{eq:dTgamdt_DM_e}\n\\end{subnumcases}\nwhere $\\rho_i$ and $p_i$ correspond to the energy density and pressure of a given particle respectively, $H = \\sqrt{(8\\pi/3)\\,\\sum_i \\rho_i/M_{\\rm Pl}^2}$ is the Hubble parameter, $M_{\\rm Pl} = 1.22\\times 10^{19}\\,\\text{GeV}$ the Planck mass, and $P_{\\rm int}$ and its derivatives account for finite temperature corrections. The reader is referred to~\\cite{Escudero:2018mvt} for further details. Here, $\\delta \\rho_{\\nu} /\\delta t$ corresponds to the energy exchange rate between neutrinos and electrons. Accounting for Fermi-Dirac statistics in the rates and setting $m_e = 0$, it reads~\\cite{Escudero:2019new}:\n\\begin{align}\\label{eq:energyrates_nu_SM}\n& \\left. \\frac{\\delta \\rho_{\\nu}}{\\delta t}  \\right|_{\\rm SM} = \\frac{G_F^2}{\\pi^5} \\left( 1 - \\frac{4}{3} s_W^2 + 8 s_W^4 \\right) \\times  \\left[ 32 \\, f_a^{\\rm FD} \\,  \\left( T_\\gamma^9-T_{\\nu}^9  \\right) +  56 \\,f_s^{\\rm FD} \\,   T_\\gamma^4 \\, T_{\\nu}^4 \\, \\left( T_\\gamma - T_{\\nu}\\right)\\right] \\,,\n\\end{align}\nwhere $s_{\\mathrm{W}}^2 = 0.223$~\\cite{pdg}, $G_{\\mathrm{F}}$ is Fermi's constant, $f_a^{\\rm FD} = 0.884$, $f_s^{\\rm FD} = 0.829$, and we account for the electron mass as in~\\cite{Escudero:2019new}. \n\nWe solve Equations~\\eqref{eq:dTgamdt_DM_nu} -- \\eqref{eq:dTgamdt_DM_e} for $1\\,\\text{keV} < T_\\gamma < 30\\,\\text{MeV}$. We start the integration at $t_0 = 1/(2 H)|_{T = 30\\,\\text{MeV}}$ for which we use as an initial condition $T_\\gamma = T_\\nu = 30 \\,\\text{MeV}$, since for such high temperatures SM neutrino-electron interactions are highly efficient. By solving this set of differential equations, we find all the key background evolution quantities as a function of time, scale factor and temperature. In addition, we evaluate the number of effective relativistic degrees of freedom $N_{\\rm eff}$ as relevant for CMB observations,\n\\begin{align}\\label{eq:Neff}\nN_{\\rm eff} \\equiv \\frac{8}{7}\\left(\\frac{11}{4} \\right)^{4/3} \\left( \\frac{\\rho_{\\text{rad}}-\\rho_\\gamma}{\\rho_\\gamma}\\right) = 3 \\left(\\frac{11}{4} \\right)^{4/3} \\left(\\frac{T_\\nu}{T_\\gamma}\\right)^4 \\, ,\n\\end{align} \nwhere in the last step we have assumed that $\\rho_{\\text{rad}} = \\rho_\\nu + \\rho_\\gamma$. By solving this system of equations in the SM we find $N_{\\rm eff}^{\\rm SM} = 3.046$~\\cite{Escudero:2019new}, a result that is in perfect agreement with state-of-the-art calculations~\\cite{Mangano:2005cc,deSalas:2016ztq}.  \n\n\\subsection{Consistency Checks of Modified BBN Code}\\label{app:ConsistencyChecks}\\vspace{-0.2cm}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nWe checked whether our modifications do not significantly change the values of the primordial helium and deuterium abundances in Standard Model BBN compared to the base version of \\texttt{PRIMAT}. Table \\ref{tab:SBBNcheck} shows the relative difference in the output of the two codes and it is clear that the accuracy is better than $0.1\\%$.\n\\begin{table}[h]\n    \\centering\n    {\\def\\arraystretch{1.35}\n    \\begin{tabular}{c|c|c|c}\n        \\toprule\n      $\\,\\,$   \\textbf{Abundances} $\\,\\,$ & $\\,\\,$ \\texttt{PRIMAT}$\\,\\,$ & $\\,\\,$ \\textbf{Modified} \\texttt{PRIMAT} $\\,\\,$ & $\\,\\,$ \\textbf{Relative Difference (\\%)} $\\,\\,$ \\\\\n        \\hline\\hline\n        $Y_{\\mathrm{p}}$ & 0.24709 & 0.24717 & 0.03\\\\\n        $10^5\\times {\\rm D/H}|_{\\rm P}$ & 2.4592 & 2.4613 & 0.08 \\\\ \\hline  \\hline\n    \\end{tabular}}\\vspace{-0.1cm}\n    \\caption{Primordial abundances as computed using \\texttt{PRIMAT} and our modified version with $\\Omega_{\\mathrm{b}} h^2 = 0.02225$ and $\\tau_n = 879.5$ s.}\n    \\label{tab:SBBNcheck}\n\\end{table} \n\\vspace{-0.5cm}\n\n\\begin{figure}[t]\n    \\centering\n    \\includegraphics[width=0.5\\textwidth]{figures/Neffcheck.pdf}\\vspace{-0.5cm}\n    \\caption{Relative difference in the primordial abundances between the default version of \\texttt{PRIMAT} and our modified version of it as a function of $\\Delta N_{\\mathrm{eff}}$. Predictions are done using $\\Omega_{\\mathrm{b}} h^2 = 0.02225$ and $\\tau_n = 879.5$ s.}\n    \\label{fig:CheckDeltaNeff}\n\\end{figure}\n\n\\noindent We also compared our modifications to \\texttt{PRIMAT} when massless dark radiation is present, which we parametrize in terms of $\\Delta N_{\\rm eff}$. In \\texttt{PRIMAT} this is done by increasing $N_{\\mathrm{eff}}$ directly in the Friedmann equations while in our modified version of the code it is done by including the evolution of a non-interacting, relativistic component. The result is shown in Figure \\ref{fig:CheckDeltaNeff}.\nThe test shows an accuracy better than $0.1\\%$ for all relevant nuclides in the range $0 \\leq \\Delta N_{\\rm eff} \\leq 1$.\n\n\\begin{figure*}[t]\n    \\begin{center}\n    \\begin{tabular}{cc}\n     \\hspace{-0.5cm} \\includegraphics[width=0.46\\textwidth]{figures/NollettNU.pdf}  \\hspace{0.4cm} \\includegraphics[width=0.45\\textwidth]{figures/NollettEE.pdf}\n      \\end{tabular}\n      \\end{center}\\vspace{-0.8cm}\n    \\caption{Comparison with previous literature for the primordial abundances $Y_{\\mathrm{P}}$ and $\\mathrm{D}/\\mathrm{H}|_{\\mathrm{P}}$ as a function of the mass of a Majorana BSM particle that couples exclusively to neutrinos (left panels) or electrons (right panels). The solid lines are from this work and the dashed lines from ~\\cite{Nollett:2013pwa} and~\\cite{Nollett:2014lwa}.}\n    \\label{fig:mccabe}\n    \\vspace{-0.5cm}\n\\end{figure*}\n\n\\subsection{Comparison with Previous Literature}\\vspace{-0.2cm} \\label{app:ComparisonsLiterature}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nIn this appendix we make a direct comparison between our results and those reported in~\\cite{Nollett:2013pwa} and~\\cite{Nollett:2014lwa}. Refs~\\cite{Nollett:2013pwa} and~\\cite{Nollett:2014lwa} used a modified version of the Kawano code~\\cite{Kawano:1988vh,Kawano:1992ua}. In Figure \\ref{fig:mccabe}, we consider two cases: a Majorana fermion that is purely neutrinophilic or electrophilic. We compute the predictions for helium and deuterium using $\\tau_{\\mathrm{n}} =  880.1$ s and $\\Omega_{\\mathrm{b}}h^2 = 0.022 $ as in~\\cite{Nollett:2013pwa} and~\\cite{Nollett:2014lwa}. We observe a few small differences:\n\\begin{enumerate}[leftmargin=0.5cm,itemsep=0pt]\\vspace{-0.1cm}\n    \\item Our predicted values of $\\mathrm{D}/\\mathrm{H}|_{\\mathrm{P}}$ are smaller than those reported in~\\cite{Nollett:2013pwa,Nollett:2014lwa}. Since the difference is WIMP mass independent, we attribute it to updated nuclear reaction rates in \\texttt{PRIMAT}. \n    \\item The predicted values of $Y_{\\mathrm{P}}$ are slightly different for $ 1 \\,\\text{MeV} \\lesssim   m_{\\chi} \\lesssim 15 \\,\\text{MeV}$. The reason is twofold:\n    \\begin{enumerate}[leftmargin=0.5cm,itemsep=0pt]\\vspace{-0.1cm}\n    \\item \\cite{Nollett:2013pwa,Nollett:2014lwa} considered that neutrinos decoupled instantaneously and tracked the temperature evolution by using entropy conservation, while we solve for the time evolution of neutrino decoupling. Imposing entropy conservation leads to a feature in the neutrino temperature evolution that affects both the Universe's expansion and the proton-to-neutron conversion rates, see Figure 2 of \\cite{Escudero:2018mvt}.\n    \\item \\cite{Nollett:2013pwa,Nollett:2014lwa} considered instantaneous neutrino decoupling at $T_\\nu^{\\rm dec} = 2.0\\,\\text{MeV}$, while an estimate based on the actual neutrino temperature time evolution yields $T_\\nu^{\\rm dec} = 1.91\\,\\text{MeV}$ \\cite{Escudero:2018mvt}. Considering a smaller neutrino decoupling temperature leads to an impact on the proton-to-neutron rates and also reduces the impact of heavier BSM species in neutrino decoupling. \n    \\end{enumerate}\n\\end{enumerate}\\vspace{-0.1cm}\nWe have also compared our predictions of $Y_{\\mathrm{P}}$ and $\\mathrm{D}/\\mathrm{H}|_{\\mathrm{P}}$ with those reported in~\\cite{Boehm:2013jpa} (which used  \\texttt{PArthENoPEv1} \\cite{Pisanti:2007hk}, see \\cite{Consiglio:2017pot} for an updated version of the code). We find good overall agreement with~\\cite{Boehm:2013jpa} and small differences similar to those we find when comparing to~\\cite{Nollett:2013pwa,Nollett:2014lwa}. Note that~\\cite{Wilkinson:2016gsy} provided updated bounds to those presented in~\\cite{Boehm:2013jpa} although the predictions for $Y_{\\mathrm{P}}$ and $\\mathrm{D}/\\mathrm{H}|_{\\mathrm{P}}$ are not displayed in that reference.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Conservative Range for the Baryon Density from CMB observations} \\label{app:Omegab}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nIn the BBN+$\\Omega_{\\rm b}h^2$ analysis we consider $\\Omega_{\\mathrm{b}} h^2 = 0.02225 \\pm 0.00066$ to be a conservative and cosmological model independent determination of the baryon energy density by current CMB observations. $\\Omega_{\\mathrm{b}} h^2 = 0.02225 \\pm 0.00066$ has a $4.4$ times larger error bar than the one associated with $\\Lambda\\text{CDM}$ using Planck 2018 observations~\\cite{Aghanim:2018eyx}, and furthermore, it covers well the inferred value of $\\Omega_{\\mathrm{b}} h^2$ in a well-motivated 12-parameter extensions of $\\Lambda$CDM using different data sets~\\cite{DiValentino:2016hlg,DiValentino:2017zyq}. In Figure \\ref{fig:omegab}, one can appreciate that indeed the range with a central value of $\\Omega_{\\mathrm{b}} h^2 = 0.02225 \\pm 0.00066$ covers very well the posterior distributions of $\\Omega_{\\mathrm{b}} h^2 $ of such a 12-parameter extension of $\\Lambda$CDM including various data sets in conjuntion to Planck CMB observations. \n\n\\begin{figure}[t]\n    \\centering\n    \\includegraphics[width=0.6\\textwidth]{figures/omegabposteriors.pdf}\\vspace{-0.3cm}\n    \\caption{Illustration of the parameter range for the baryon density we consider in the BBN+$\\Omega_{\\mathrm{b}}h^2$ analysis as compared to the best-fit values and errors given in Table II of \\cite{DiValentino:2017zyq}. The authors of \\cite{DiValentino:2017zyq} infer $\\Omega_{\\mathrm{b}}h^2$ in a well-motivated 12-parameter extension to $\\Lambda$CDM using the different data sets shown in the legend. Note in particular that our conservative range for the baryon density encompasses all derived central values and errors.}\n    \\label{fig:omegab}\n\\end{figure}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Implications for Lithium-7 and Helium-3}\n\\label{app:cosmo_imp_other}\nWe show the evolution of the primordial $^7\\mathrm{Li}/\\mathrm{H}|_{\\mathrm{P}}$ and $^3\\mathrm{He}/\\mathrm{H}|_{\\mathrm{P}}$ abundances in Figure \\ref{fig:Cosmoimply_other} as a function of the mass of a thermal BSM particle. We note that the upper panels do not include any confidence intervals, since it is well known that current measurements of the primordial lithium-7 are in disagreement with SM predictions using the baryon-to-photon ratio inferred from CMB observations \\cite{pdg}. The excluded regions in the lower panels are based on observations of helium-3 in our galaxy \\cite{Bania:2002yj}. Helium-3 can be both produced and destroyed in stars, which makes it difficult to precisely determine the time evolution of its primordial abundance \\cite{VangioniFlam:2002sa}. Therefore, we have not included measurements of either lithium-7 or helium-3 in our analysis. Nevertheless, if the situation changes in the future, it will be straightforward to obtain bounds from Figure \\ref{fig:Cosmoimply_other} and see how it improves the current BBN constraints.\n\\clearpage\n\n\\begin{figure}[!ht]\n    \\centering\n    \\includegraphics[width=0.46\\textwidth]{figures/Nu_extra_abundance_plot.pdf} \\qquad\n    \\includegraphics[width=0.45\\textwidth]{figures/EE_extra_abundance_plot.pdf}\n    \\caption{Cosmological impact of light BSM particles in thermal equilibrium with the SM plasma as a function of their mass $m_\\chi$. The \\textit{left/right panels} correspond to neutrinophilic/electrophilic particles. \\textit{Upper panels:} The lithium-7 primordial abundance $^7\\mathrm{Li}/\\mathrm{H}|_{\\mathrm{P}}$. Measurements of $^7\\mathrm{Li}/\\mathrm{H}|_{\\mathrm{P}}$ are not shown for clarity, see e.g. \\cite{pdg} for current measurements. \\textit{Lower panels:} The helium-3 primordial abundance $^3\\mathrm{He}/\\mathrm{H}|_{\\mathrm{P}}$. The grey contours correspond to an upper limit as reported by~\\cite{Bania:2002yj}. The predictions are made with $\\Omega_{\\mathrm{b}} h^2 = 0.021875$ and $\\tau_n = 879.5\\,\\text{s}$.}\n    \\label{fig:Cosmoimply_other}\n\\end{figure}\n\n\\subsection{CMB-S4 Forecast}\n\\label{app:CMBfisher}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nIn order to forecast the reach of CMB-S4 constraints, we first choose a fiducial cosmology with cosmological parameters equal to the Planck 2018 TTTEEE+lowE mean values as in Table 2 of \\cite{Aghanim:2018eyx}, which are reproduced below in Table \\ref{tab:FisherResults}.\nThe fiducial helium abundance is obtained by running \\texttt{PRIMAT} within the Standard Model and fiducial cosmology.\\\\\\\\\n\\noindent To forecast the sensitivity of future CMB experiments, we employ the same procedure as used in the CMB-S4 Science Book \\cite{Abazajian:2016yjj}. Assuming Gaussian statistics, the Fisher matrix for CMB experiments is given by\n\\begin{equation}\nF_{i j}=\\sum_{X, Y} \\sum_{\\ell=\\ell_{\\min }}^{\\ell_{\\max }} \\frac{\\partial \\mathcal{C}_{\\ell}^{X}}{\\partial \\theta_{i}}\\left[\\mathbf{C}_{\\ell}^{X Y}\\right]^{-1} \\frac{\\partial \\mathcal{C}_{\\ell}^{Y}}{\\partial \\theta_{i}}\n\\end{equation}\nwith indices $X = ab$, $Y = cd$ and $a,b,c,d\\in\\{T,E,B\\}$. \nThe covariance matrix $\\mathbf{C}_\\ell^{XY}$ for each multipole $\\ell$ is defined as\n\\begin{align}\n    \\mathbf{C}_\\ell^{abcd} =& \\frac{1}{(2\\ell+1)f_{\\mathrm{sky}}}\\left[\\left(\\mathcal{C}_\\ell^{ac}+N_\\ell^{ac}\\right)\\left(\\mathcal{C}_\\ell^{bd}+N_\\ell^{bd}\\right)\n    + \\left(\\mathcal{C}_\\ell^{ad}+N_\\ell^{ad}\\right)\\left(\\mathcal{C}_\\ell^{bc}+N_\\ell^{bc}\\right)\\right]\\ ,\n\\end{align}\nwith $f_{\\mathrm{sky}}$ the effective fraction of sky covered by the experiment, $\\mathcal{C}_\\ell^X$ the simulated CMB power spectra and $N_\\ell^X$ (Gaussian) noise power spectra. The noise is approximated as\n\\begin{align}\n    N_\\ell^{aa} = (\\Delta X)^2\\exp\\left(\\frac{\\ell(\\ell+1)\\theta^2_{\\mathrm{FWHM}}}{8\\ln2}\\right)\\ ,\n\\end{align}\nwhere $\\Delta X \\in \\{\\Delta T,\\Delta P\\}$ and $N_\\ell^{TE} = 0$.\nWe adopt a similar configuration as used in the CMB-S4 Science Book: lensed power spectra with $\\ell_{\\mathrm{min}} = 30$, $\\{\\ell_{\\mathrm{max}}^{TT}, \\ell_{\\mathrm{max}}^{TE}\\} = 3000$, $\\{\\ell_{\\mathrm{max}}^{EE},\\ell_{\\mathrm{max}}^{BB}\\} = 5000$, $f_{\\mathrm{sky}} = 0.4$, $\\theta_{\\mathrm{FWHM}} = 1'$, $\\Delta T = 1$ $\\mu$K-arcmin and $\\Delta P = \\sqrt{2}$ $\\mu$K-arcmin.\\\\\\\\\nThe \\texttt{CLASS} code \\cite{Blas:2011rf} is used to obtain the power spectra. The numerical derivatives are computed using the symmetric derivative $\\mathcal{C}_\\ell'(\\theta) = \\left[\\mathcal{C}_\\ell(\\theta+\\Delta\\theta)-\\mathcal{C}_\\ell(\\theta-\\Delta\\theta)\\right]/(2\\Delta\\theta)$, with fiducial parameter $\\theta$ and stepsize $\\Delta\\theta$. The stepsizes used are of order $\\Delta\\theta_i \\sim \\sigma(\\theta_i)$, as to output a more reliable estimate of the confidence level \\cite{Perotto:2006rj}. The CMB-S4 Fisher matrix is then added to the Planck 2018 low-$\\ell$ TTTEEE+lowP+lowE Fisher matrix to obtain the combined constraints. The fiducial parameters and step sizes used in our computations, together with the forecasted sensitivities, are listed in Table \\ref{tab:FisherResults}. We find good overall agreement with the forecasts performed in \\cite{Abazajian:2016yjj} within $\\Lambda$CDM. \n\n\\begin{table}[!ht]\n\\begin{center}\n{\\def\\arraystretch{1.35}\n\\resizebox{\\textwidth}{!}{\n\\begin{tabular}{p{2cm}|p{2.7cm}|p{2cm}|p{2cm}|p{3.5cm}}\n\\hline\\hline\n\t\\hfil \\textbf{Parameter} &\\hfil  \\textbf{Fiducial Value} &\\hfil  $\\boldsymbol{\\Delta\\theta}$ &\\hfil  \\textbf{CMB-S4} &\\hfil  \\textbf{CMB-S4+Planck} \\\\ \\hline\\hline\n   \t\\hfil $\\Omega_{\\mathrm{b}}h^2$ &\\hfil  0.02236 & \\hfil $3\\times 10^{-5}$ &\\hfil $4.9\\times 10^{-5}$ &\\hfil  $4.7\\times 10^{-5}$\\\\ \\hline\n   \t\\hfil $\\Omega_{\\mathrm{c}}h^2$ &\\hfil  0.1202 & \\hfil $6\\times 10^{-4}$ &\\hfil $1.8\\times 10^{-3}$ &\\hfil  $1.3\\times 10^{-3}$\\\\ \\hline\n   \t\\hfil $100\\theta_{\\mathrm{s}}$ &\\hfil  1.04090 &\\hfil  $2\\times 10^{-4}$ &\\hfil  $2.3\\times 10^{-4}$&\\hfil  $1.8\\times 10^{-4}$\\\\ \\hline\n   \t\\hfil $\\ln(10^{10}A_{\\mathrm{s}})$ &\\hfil  3.045 & \\hfil $9.5\\times 10^{-3}$  &\\hfil  $1.2\\times 10^{-2}$ &\\hfil  $8.1\\times 10^{-3}$\\\\ \\hline\n   \t\\hfil $n_{\\mathrm{s}}$ &\\hfil  0.9649 & \\hfil  $2\\times 10^{-3}$ &\\hfil  $3.7\\times 10^{-3}$ &\\hfil  $2.9\\times 10^{-3}$\\\\ \\hline\n   \t\\hfil $\\tau$ & \\hfil 0.0544 & \\hfil $6\\times 10^{-3}$ & \\hfil $7.2\\times 10^{-3}$ & \\hfil $4.8\\times 10^{-3}$\\\\ \\hline\n   \t\\hfil $N_{\\mathrm{eff}}$ & \\hfil 3.046 &$ \\hfil 3\\times 10^{-2}$ & \\hfil $1.1\\times 10^{-1}$ & \\hfil $8.1\\times 10^{-2}$\\\\ \\hline\n   \t\\hfil $Y_{\\mathrm{P}}$ & \\hfil 0.2472 & \\hfil $4\\times 10^{-3}$ & \\hfil $6.1\\times 10^{-3}$ & \\hfil $4.3\\times 10^{-3}$\\\\  \\hline \\hline\n\n\\end{tabular}}\n}\n\\end{center}\n\\vspace{-0.2cm}\n\\caption{Forecasted sensitivities of CMB-S4 and CMB-S4+Planck 2018 for the parameters of $\\Lambda\\mathrm{CDM}+N_{\\mathrm{eff}}+Y_{\\mathrm{P}}$. The column $\\Delta\\theta$ refers to the stepsizes used to compute the numerical derivatives.}\n\\label{tab:FisherResults}\n\\end{table}\n\\clearpage\n\n\\section{Neutrino Propagation}\\label{sec:assumptions}\n\n\\subsection{Neutrino Masses}\\label{sec:neutrinomass}\n\nIn this section we will present the contribution to the neutrino mass matrix that arises due to interaction term in \\eqref{eq:effective lagrangian}. The Majorana mass term for the neutrino is of the form;\n\\begin{equation}\\label{eq:neutrino mass}\n  \\frac{1}{2}(m_\\nu)_{\\alpha\\beta}\\left(\\bar{\\nu}^\\alpha_L \\nu^\\beta_L + \\text{h.c.}\\right)\n\\end{equation}\nWe are interested in the mass matrix $(m_\\nu)_{\\alpha\\beta}$. To do so, we will need to distinguish between the two cases where either (i) $\\delta$ is a real scalar field, or, (ii) $\\delta$ is a complex scalar field.\n\\paragraph{Case 1: Real Scalar Field}\nIn this case, there is only one diagram that contributes to the neutrino mass, as shown in Figure \\ref{fig:onelooprealdiag}. As in \\cite{Farzan2010, Boehm2006, Farzan2011}, the result in the real case is;\n\\begin{equation}\\label{eq:oneloopmass result}\n  (m_\\nu)_{\\alpha\\beta} = \\sum_{i}{\\frac{g_{i\\alpha}g_{i\\beta}}{16\\pi^2}m_{N^i}\\left(\\log\\frac{\\Lambda^2}{m_{N^i}^2} - \\frac{m_\\delta^2}{m_{N^i}^2 - m_\\delta^2}\\log\\frac{m_{N^i}^2}{m_\\delta^2}\\right)}\n\\end{equation}\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=0.7\\linewidth]{oneloopreal}\n  \\caption{The one loop diagram contributing to the neutrino mass in the case that $\\delta$ is a real scalar. The external neutrinos are evaluated at zero incoming momenta so as to extract only the mass contribution as opposed to the quadratic derivative interactions.}\n  \\label{fig:onelooprealdiag}\n\\end{figure}\n\n\\paragraph{Case 2: Complex Scalar Field}\n\n\n\nTo repeat the calculation for the complex scalar field, we should first think about the scalar degrees of freedom. Since the field is in the trivial representation of the electroweak gauge group, the most general hermitian mass term for $\\delta$ can be written as \\cite{Farzan2010};\n\\begin{equation}\n  V_m = M^2 \\delta^{\\dagger} \\delta - \\frac{1}{2}(m^2 \\delta\\delta + \\text{h.c.})\n\\end{equation}\nConsider expanding the scalar field as $\\delta = \\tfrac{1}{\\sqrt{2}}(\\delta_1 + i\\delta_2)$ where $\\delta_{1,2}$ are both real fields. Expanding the terms above in terms of these real degrees of freedom;\n\\begin{dmath}\n  V_m = \\frac{1}{2}M^2(\\delta_1 + i\\delta_2)(\\delta_1 - i\\delta_2) - \\frac{1}{4}m^2\\left((\\delta_1 + i\\delta_2)(\\delta_1 + i\\delta_2) + (\\delta_1 - i\\delta_2)(\\delta_1 - i\\delta_2)\\right)\n\\end{dmath}\nCollecting the terms together for each field we find;\n\\begin{equation}\n  V_m = \\frac{1}{2}(M^2 - m^2)\\delta_1^2 + \\frac{1}{2}(M^2 + m^2)\\delta_2^2\n\\end{equation}\nWe can then immediately see that the mass eigenstates are simply $\\delta_1$ and $\\delta_2$ themselves, with masses $m^2_{\\delta_1} = M^2 - m^2$, $m^2_{\\delta_2} = M^2 + m^2$. The lighter of these will be our Dark Matter candidate. Also note that interaction term \\eqref{eq:effective lagrangian} is diagonal in this mass basis;\n\\begin{equation}\n  \\mathcal{L}_{\\text{int}} = g_{i\\alpha}\\bar{N}^i_R \\nu^\\alpha_L (\\delta_1 + i \\delta_2)\n\\end{equation}\nThe contributions to the neutrino mass are then two diagrams of the form in Figure \\ref{fig:onelooprealdiag}. One will have $\\delta_1$ running round the loop, whilst the other will have $\\delta_2$. We note that the only difference between them is that the second diagram will have two couplings with an extra factor of $i$, $(ig_{i\\alpha})(ig_{i\\beta}) = -g_{i\\alpha}g_{i\\beta}$. As such the second will come with a negative sign. The total contribution is then a sum of two contributions of the form \\eqref{eq:oneloopmass result}. Importantly, we see that the dependence on the cutoff drops out in the complex case and we find;\n\\begin{equation}\n  (m_\\nu)_{\\alpha\\beta} = \\sum_{i}{\\frac{g_{i\\alpha}g_{i\\beta}}{16\\pi^2}m_{N^i}\\left(\\frac{m_{\\delta_2}^2}{m_{N^i}^2 - m_{\\delta_2}^2}\\log\\frac{m_{N^i}^2}{m_{\\delta_2}^2} - \\frac{m_{\\delta_1}^2}{m_{N^i}^2 - m_{\\delta_1}^2}\\log\\frac{m_{N^i}^2}{m_{\\delta_1}^2}\\right)}\n\\end{equation}\n\n\n\n\\subsection{Why do we only have to worry about one process?}\\label{sec:oneprocess}\n\n\n\nIn Section \\ref{sec:crosssection} where we detailed how to do the calculation for $\\nu\\nu \\rightarrow \\delta\\delta$, we neglected to calculate the cross section for other processes within the model that may also lead to a neutrino interaction. These additional processes are as follows;\n\\begin{enumerate}\n  \\item \\textit{$\\nu\\nu \\rightarrow NN$:} One can construct scenarios in parameter space where this dominates. However the centre of mass energy: $E_{\\mathrm{com}} = \\sqrt{2 E_\\nu m_\\nu}$ where $m_\\nu$ is the mass of the cosmic neutrino background neutrino, is close to the mass of the lightest scalar $\\delta$. By construction if the scalar is the dark matter candidate, then the mass of $N$, $m_N$, must be larger. Thus, even in scenarios where the centre of mass energy is large enough to produce two $N$ particles, the cross section is likely to lie at the front tail of the distribution and so be subdominant.\n  \\item $\\nu N \\rightarrow \\nu N$: There is an $s$-channel and a $t$-channel diagram for this process. Independent of this however, we have assumed that $N$ is not the dark matter candidate. As such, we expect the relic density to be very low in comparison to all other particles. The vertex structure ensures that we expect the cross section to be of a similar order of magnitude to the $\\nu\\nu \\rightarrow \\delta\\delta$ case. Hence, the contribution to the mean free path is negligible.\n  \\item $\\nu\\delta \\rightarrow \\nu\\delta$: It is not immediately clear as to whether this will be negligible. Firstly, there is a $t$-channel process that will have a similar algebraic cross section as previously calculated in $\\nu\\nu \\rightarrow \\delta\\delta$. There is also an $s$-channel process, whose cross-section we obtain from \\cite{Franarin2018}. Secondly, we must check the contribution to the mean free path in two regimes;\n  \\begin{itemize}\n    \\item On a cosmological scale where $n_\\delta$ is given by the relic density of dark matter,\n    \\item On a galactic scale, where the density is much higher within the dark matter halo.\n  \\end{itemize}\n\\end{enumerate}\nNote that neglecting these processes is of course a simplifying assumption about the nature of the cross-sections, but they do not affect the interpretation of the results. This is because including any of the additional contributions above can only \\textit{improve} the bounds; for a given $\\ell$, introducing a new process increases the effective cross section, and reduces the mean free path leading to tighter constraints.\n\n\\subsection{Contribution from $\\nu\\delta \\rightarrow \\nu\\delta$}\nAs mentioned above, we must check whether the $\\nu\\delta \\rightarrow \\nu\\delta$ process contributes significantly to the mean free path of the blazar neutrino. In what follows, we will find that it does not contribute significantly. This is due to the fact that, even within the galactic halo, the cross-section is too small to generate a significant contribution.\n\n\\vspace{-0.5cm}\n\n\\subsubsection{$t$-Channel Cross Section}\\label{sec:tchannel}\n\nThe relationship;\n\\begin{equation}\n    u = m_\\delta^2 - \\frac{1}{2}s - \\sqrt{s\\left(\\frac{1}{4}s - m_\\delta^2\\right)}\\cos\\theta\n\\end{equation}\nalong with the observation that for $\\nu\\delta \\rightarrow \\nu\\delta$ with $m_\\delta \\sim \\mO(\\mathrm{MeV})$ and $E_\\nu \\sim \\mO(TeV)$, it follows that $s \\sim \\mO(GeV) \\gg m_\\delta$. This then implies in this energy regime, $u \\simeq s$. By crossing symmetry, we then deduce that the dependence of $\\sigma_t(\\nu\\delta \\rightarrow \\nu\\delta)$ on the centre of mass energy is just given by $\\sigma(s)$ as in \\eqref{eq:sigma}. To compare $\\sigma(\\nu\\nu \\rightarrow \\delta \\delta)$ and $\\sigma_t(\\nu\\delta \\rightarrow \\nu\\delta)$ we need only to evaluate $\\sigma(s)$ at the different centre of mass energies, $s = 2E_\\nu m_\\nu$ and $s = 2 E_\\nu m_\\delta$. For an explicit comparison, we put in the values $g_e = 3 \\times 10^{-3}$, $g_\\mu = 10^{-2}$, $g_\\tau = 3\\times 10^{-1}$, $m_\\delta = 0.5 \\, \\textrm{MeV}$, $m_\\nu = 0.15 \\, \\textrm{eV}$, $m_N = 5\\,\\textrm{MeV}$. We find;\n\\begin{equation}\n  \\sigma(\\nu\\nu \\rightarrow \\delta\\delta) \\simeq 4.7\\times 10^{-10} \\, \\textrm{MeV}^{-2}, \\quad \\sigma_t(\\nu\\delta \\rightarrow \\nu\\delta) \\simeq 6.2\\times 10^{-16}\\, \\textrm{MeV}^{-2}\n\\end{equation}\nSo we find there is a difference of five to six orders of magnitude. After computing the number density of the dark matter in the galactic and cosmological cases, we will use this to deduce that the $t$-channel does not contribute.\n\n\\vspace{-0.5cm}\n\n\\subsubsection{$s$-Channel Cross Section}\\label{sec:schannel}\nWe obtain an analytic expression for the $s$-channel cross-section from \\cite{Franarin2018};\n\\begin{equation}\n  \\sigma_s(\\nu_\\mu\\delta \\rightarrow \\nu_\\ell \\delta) = \\frac{g_\\mu^2 g_\\ell^2}{16\\pi}\\frac{(m_N^2 - m_\\delta^2)^2}{m_N^2 + m_\\delta^2} \\frac{1}{(s - m_N^2)^2 + \\Gamma_N^2 m_N^2}\n\\end{equation}\nwhere $\\Gamma_N$ is the width of $N$, it is given by;\n\\begin{equation}\\label{eq:sigma_s}\n  \\Gamma_N = \\sum_{\\ell}{\\frac{g_\\ell^2}{16\\pi} \\frac{(m_N^2 - m_\\delta^2)^2}{m_N^3}}\n\\end{equation}\nIn this case, we simply do an order of magnitude estimate with;\n\\begin{equation}\n  m_N = \\mO(\\textrm{MeV}), \\quad m_\\delta = \\mO(\\textrm{MeV}), \\quad s - m_N^2 = \\mO(\\textrm{GeV}^2), \\quad g = \\mO(10^{-2})\n\\end{equation}\nWe note that this implies that $(s - m_N^2)^2 \\gg \\Gamma_N^2 m_N^2$. Putting these into \\eqref{eq:sigma_s}, we find;\n\\begin{equation}\n  \\sigma_s(\\nu\\delta \\rightarrow \\nu\\delta) \\simeq \\mO(10^{-21}\\,\\textrm{MeV}^{-2})\n\\end{equation}\nAs such we deduce that the contribution is certainly negligible at this energy, since even if the number density of $\\delta$ was high enough, the $t$-channel process will dominate by $4$ or $5$ orders of magnitude. \n\n\\subsubsection{The interference term}\\label{sec:interference}\nTo argue that the interference term between the $s$ and the $t$ channel amplitudes, which we denote $\\mM_s$ and $\\mM_t$ respectively, also leads to a negligible contribution to the cross section, we note that by the triangle inequality;\n\\begin{equation}\n    \\Abs{\\mM_s + \\mM_t} \\leq \\Abs{\\mM_s} + \\Abs{\\mM_t} \\Rightarrow \\Abs{\\mM_s + \\mM_t}^2 \\leq \\Abs{\\mM_s}^2 + \\Abs{\\mM_t}^2 + 2\\Abs{\\mM_s}\\Abs{\\mM_t}\n\\end{equation}\nFurthermore, integrals of these quantities which ultimately lead to the total cross section will satisfy equivalent relations due to the positive definite nature of the integrands. Finally then, if we denote the amplitude for $\\nu\\nu \\rightarrow \\delta\\delta$ as $\\mM$, the calculations in the previous two sections indicate that $\\Abs{\\mM_s}^2 \\sim \\mO(10^{-10})\\Abs{\\mM}^2$ and $\\Abs{\\mM_t}^2 \\sim \\mO(10^{-6})\\Abs{\\mM}^2$. Hence, by the triangle inequality, we deduce that $\\Abs{\\mM_s}\\Abs{\\mM_t} \\sim \\mO(10^{-8})\\Abs{\\mM}^2$ and therefore leads to a neglible contribution to the total squared amplitude, $\\Abs{\\mM_s + \\mM_t}^2 \\sim \\Abs{\\mM_t}^2 \\sim \\mO(10^{-6})\\Abs{\\mM}^2$. Hence we deduce that the total cross section for $\\nu\\delta \\rightarrow \\nu\\delta$, where $\\nu$ in the initial state has energy $\\mO(\\mathrm{TeV})$ satisfies $\\sigma(\\nu\\delta \\rightarrow \\nu\\delta) \\sim 10^{-6} \\cdot \\sigma(\\nu\\nu\\rightarrow \\delta\\delta)$. It therefore remains to check the number density of dark matter in the cosmological and galactic cases and compute the mean free path using the $t$-channel cross-section.\n\n\\subsubsection{Number Density on Cosmological Scales}\nThe dark matter density on a cosmological scale, at a redshift $z$, is given by \\cite{Farzan2014};\n\\begin{equation}\n  n(z) = \\frac{\\Omega_{\\textrm{DM},0}\\rho_c}{m_{\\textrm{DM}}}(1 + z)^3 \\simeq 1.26 \\times 10^{-3} (1 + z)^3 \\left(\\frac{\\textrm{MeV}}{m_{\\textrm{DM}}}\\right) \\, \\textrm{cm}^{-3}\n\\end{equation}\nwhere we have used $\\Omega_{\\textrm{DM},0} \\simeq 0.265$ and $\\rho_c = 3H_0^2/8G \\simeq 4.77\\, \\textrm{keV}\\,\\textrm{cm}^{-3}$. This is $5$ orders of magnitude below the cosmic neutrino background number density. So in order to be relevant, $\\sigma(\\nu\\delta \\rightarrow \\nu\\delta)$ would have to be approximately $10^5$ times larger than $\\sigma(\\nu\\nu \\rightarrow \\delta\\delta)$, evaluated at the neutrino energy. From Sections \\ref{sec:tchannel}, \\ref{sec:schannel}, and \\ref{sec:interference}, we see this is not the case, and indeed the cross-section is significantly smaller than the $\\nu\\nu \\rightarrow \\delta\\delta$ cross-section.  We can therefore neglect this cross section as the neutrino travels to the Milky Way.\n\n\\subsubsection{Number Density on Galactic Scales}\nAfter deducing that the contribution to the mean free path from interaction with dark matter is negligible on cosmological scales, we just have to check whether the galactic overdesnity could lead to a significant contribution. As in \\cite{Franarin2018}, we use the Einasto profile with $\\alpha = 0.15$ and $R_0 = 20\\,\\textrm{kpc}$ to model the dark matter energy density;\n\\begin{equation}\n  \\rho_{\\textrm{DM}}(r) = 7.2 \\times 10^{-2}\\,\\textrm{GeV} \\, \\textrm{cm}^{-3}\\, \\cdot \\exp\\left(-\\frac{2}{\\alpha}\\left(\\left(\\frac{r}{R_0}\\right)^\\alpha - 1\\right)\\right)\n\\end{equation}\nWe can obtain the number density by dividing by the mass of the dark matter particle, $m_\\delta \\simeq \\mO(10^{-3} \\, \\textrm{GeV})$. Now, note that this is maximal when $r = 0$. In order to put an upper bound on the contribution to the optical depth, we assume that the whole halo has this maximal number density. With $m_\\delta = 1\\, \\textrm{MeV}$;\n\\begin{equation}\n  n_{\\textrm{DM}}^{\\textrm{max}} \\simeq \\frac{\\rho_{\\textrm{DM}}(r = 0)}{m_\\delta} \\simeq 4.4 \\times 10^{7} \\, \\textrm{cm}^{-3} \\simeq 10^{5} n^0_{\\nu}\n\\end{equation}\nNow we are in a position to see why this does not contribute to the suppression of the neutino flux from the blazar. Whilst the combination of $n^{\\textrm{max}}_{\\textrm{DM}} \\sigma_t(\\nu\\delta\\rightarrow\\nu\\delta)$ is now of the same order of magnitude as $n_\\nu \\sigma(\\nu\\nu\\rightarrow \\delta\\delta)$, the relevant consideration is the probability that such an interaction ($\\nu\\delta \\rightarrow \\nu\\delta$) occurs. This is dependent on the ratio between the length scale at which such a high number density is observed (i.e. the galactic radius), and the mean free path. Here, the mean free path, $\\ell$, is $\\mO(\\textrm{Gpc})$, so the probability of survival is $\\sim \\exp(-d_{g}/\\ell)$ where $d_g \\simeq 1\\,\\textrm{kpc}$ is the galactic radius. We see that this is approximately unity. Finally, note that in the case where the mean free path is $\\mO(\\textrm{kpc})$, we would not expect the neutrino to reach anywhere close to the galaxy, so this would be inconsequential also. Hence we deduce that both in the cosmological and galactic settings, the contribution from $\\nu\\delta \\rightarrow \\nu\\delta$ is negligible in comparison to the dominant $t$-channel process $\\nu\\nu \\rightarrow \\delta\\delta$.\n\nTo end this section, we emphasise that whilst we have neglected the contribution from these other processes, including any/all of them can only improve the bounds as the mean free path will decrease with new interactions. As such, it is only for the sake of simplicity that we make the assumptions, \\textit{not} at the cost of the validity of the bounds.\n\n\n\n\\subsection{Mass Splitting in the Complex Case}\\label{sec:complexsplit}\n\n\n\nWe assume that each of the mass eigenstates is equally abundant $\\nu_1, \\bar{\\nu}_1, \\nu_2, \\ldots$, with a number density given by;\n\\begin{equation}\n  n_{\\nu_i} = \\frac{1}{6} n_\\nu = \\frac{1}{6} \\cdot 340 \\, \\textrm{cm}^{-3}\n\\end{equation}\nNow, the contribution from each mass eigenstate to the inverse mean free path $\\ell^{-1}$ is given by $n_{\\nu_i} \\sigma(\\nu_\\mu X \\rightarrow Y )$. Importantly we argued in the last section that we thus need only consider $\\sigma(\\nu_\\mu \\nu \\rightarrow \\delta \\delta)$. Now, in the real case, there is nothing more to say as there is only one scalar mass eigenstate. In the complex case however, we must consider the following. The theory we are considering is effective up to some scale $\\Lambda$. It therefore does not have to explicitly respect any of the symmetries that might apply in the UV. Indeed all we assume is that the new dark sector particles are odd under a $\\mathbb{Z}_2$ symmetry, to ensure there is a stable candidate. As such, writing $\\delta = \\tfrac{1}{\\sqrt{2}}(\\delta_1 + i \\delta_2)$, the most general hermitian mass term can be written;\n\\begin{equation}\n  V_m = M^2 \\delta\\dagg \\delta - \\frac{1}{2}(m^2 \\delta \\delta + \\textrm{h.c.})\n\\end{equation}\nThis leads to a mass splitting between the mass eigenstates $\\delta_{1,2}$ given by $\\Delta m_{12}^2 = 2m^2$. Now, we consider the possible processes $\\nu\\nu \\rightarrow \\textrm{scalars}$. We have;\n\\begin{equation*}\n\\nu\\nu \\rightarrow \\delta_1 \\delta_1, \\quad \\nu\\nu \\rightarrow \\delta_1 \\delta_2, \\quad \\nu\\nu \\rightarrow \\delta_2 \\delta_2\n\\end{equation*}\nFrom this we see that there are a couple of scenarios that might occur kinematically. We assume that the lightest scalar is $\\delta_1$, and that the first process can happen. Then it may the case that either (i) only the first process can occur, (ii) only the first and second processes can occur, or, (iii) all the processes can occur. This is where we make our simplifying assumption, which unlike the first case, will not necessarily improve the bounds if put in at a later date. We assume that if the first occurs, then the next two may also occur. This is equivalent to saying that there is a small mass gap between the two eigenstates. To simplify the situation then we assume that $m$ is small compared to $M$, and therefore that we can approximate;\n\\begin{equation}\n  \\sigma(\\nu\\nu \\rightarrow \\delta_1 \\delta_1) + \\sigma(\\nu\\nu \\rightarrow \\delta_1 \\delta_2) + \\sigma(\\nu\\nu \\rightarrow \\delta_2 \\delta_2) \\simeq 3 \\sigma(\\nu\\nu \\rightarrow \\delta_1 \\delta_1)\n\\end{equation}\n\n\n\n\\subsection{Redshift Considerations}\n\n\n\nDuring the cosmological propagation, both the number density of the cosmic neutrino background neutrinos, and the energy of the blazar neutrino will be affected by redshift. Let the values now be denoted $n_\\nu^0$ and $E_\\nu^0$ respectively, then at a redshift $z$;\n\\begin{equation}\n  n_\\nu(z) = n_\\nu^0 (1 + z)^3, \\quad E_\\nu(z) = (1 + z)E_\\nu^0\n\\end{equation}\nWe now make the observation that the source of the $290 \\, \\textrm{TeV}$ neutrino is at a redshift $z = 0.3365$. In the case of the energy this means that the maximum possible multiplicative factor is $(1 + 0.3365)$, but this is within the confidence bounds on the energy measured at IceCube, so can be neglected. The redshift of the number density is not negligible however, although it only improves the bounds. We take the result from \\cite{Farzan2014} that the optical depth is given by;\n\\begin{equation}\n  \\tau = c\\int_{z = z_1}^{z = z_2}{\\upd{z}\\frac{\\ud t}{\\ud z}n(z)\\sigma(z)}\n\\end{equation}\nNow, the energy of the muon observed at IceCube had a 1$\\sigma$ confidence interval of $23.7 \\pm 2.8$ TeV \\cite{IceCube2018}. This can be translated into an error on the energy of the incoming neutrino of an order 100 TeV. With this observation, we note that the energy of the 290 TeV neutrino at its source, i.e. before it is redshifted during the propagation, will lie within these bounds. Therefore, to simplify the analysis, we assume that $\\sigma(z) = \\sigma(E_\\nu(z))$ does not depend on the redshift, $z$. With this assumption in mind, the expression above reduces to; \n\\begin{equation}\n  \\tau = c n_\\nu^0 \\sigma(E_\\nu^0) \\int_{z = z_1}^{z = z_2}{\\upd{z}(1 + z)^3 \\frac{\\ud t}{\\ud z}}\n\\end{equation}\nWe can relate $\\ud t/\\ud z$ to the Hubble rate via;\n\\begin{equation}\n  \\frac{\\ud t}{\\ud z} = -\\frac{1}{(1 + z)H(z)}\n\\end{equation}\nwhere;\n\\begin{equation}\n  H(z) = H_0 \\sqrt{\\Omega_\\Lambda + \\Omega_{m,0}(1 + z)^3}\n\\end{equation}\nWe will take the values $\\Omega_\\Lambda \\simeq 0.65$, $\\Omega_{m,0} \\simeq 0.315$, $H_0 \\simeq 6.73 \\times 10^{4}\\, \\textrm{km}\\,\\textrm{s}^{-1}\\textrm{Gpc}^{-1}$ \\cite{Planck}, $c = 3\\times 10^{5}\\,\\textrm{km s}^{-1}$. Letting $\\ell_0^{-1} := n_\\nu^0 \\sigma(E_\\nu^0)$ to find;\n\\begin{equation}\n  \\tau = \\left(\\frac{\\ell_0}{\\text{Gpc}}\\right)^{-1} \\left(\\frac{c \\, / \\, \\text{km s}^{-1}}{H_0 \\, /\\, \\text{km s}^{-1}\\text{Gpc}^{-1}}\\right) \\cdot \\int_{z = z_1}^{z = z_2}{\\upd{z}\\frac{(1 + z)^2}{\\sqrt{\\Omega_\\Lambda + \\Omega_{m,0}(1 + z)^3}}} \\simeq 1.90 \\left(\\frac{\\ell_0}{\\textrm{Gpc}}\\right)^{-1}\n\\end{equation}\n\n\n\\subsection{Including Neutrino Mass Hierarchies}\n\n\nThe last technicality to introduce into the computation of the bounds are the facts that;\n\\begin{enumerate}\n  \\item The neutrino \\textit{mass} eigenstates and \\textit{flavour} eigenstates are not the same\n  \\item The neutrino masses are unknown, and indeed have two possible orderings (for the mass eigenstates); the \\textit{normal hierarchy} and the \\textit{inverted hierarchy}.\n\\end{enumerate}\nWithin our calculation we aim to present the situation for both of these cases.\n\n\\subsubsection{Mass Eigenstates and the PMNS Matrix}\n\nWithin the Standard Model, we expect neutrinos to be massless. Experiments illustrating phenomena such as neutrino oscillations contradict this fact and we now believe they do indeed have a small mass. This complicates matters however for the reason mentioned above. The flavour eigenstates and the mass eigenstates are no longer the same in this case. Instead they are related by the \\textit{PMNS} matrix\\footnote{Pontecorvo-Maki-Nakagawa-Sakata}. This encodes a unitary transformation between the flavour basis and the mass basis:\n\\begin{equation}\n\\nu_\\ell := \\begin{pmatrix} \\nu_e \\\\ \\nu_\\mu \\\\ \\nu_\\tau \\end{pmatrix} = \\thrbythr{U_{e1} & U_{e2} & U_{e3}}{U_{\\mu1} & U_{\\mu2} & U_{\\mu3}}{U_{\\tau1} & U_{\\tau2} & U_{\\tau3}} := U \\nu_i\n\\end{equation}\n\n\\subsubsection{The Mass Hierarchy}\n\nA key fact in this discussion is that ultimately we do not know the absolute values, nor the ordering of the mass eigenstates. There are two common alternatives, which are illustrated in Figure 2 in \\cite{King};\n\\begin{enumerate}\n  \\item \\textit{Normal Ordering:} In the normal hierarchy, $\\nu_3$ is the most massive state, whilst $\\nu_1$ and $\\nu_2$ are lighter.\n  \\item \\textit{Inverted Ordering:} On the other hand, in the inverted case, $\\nu_3$ is the lightest, whilst $\\nu_1$ and $\\nu_2$ are heavier.\n\\end{enumerate}\n\n\\subsubsection{Constraints on the Masses}\n\nWe can go slightly further, whilst we do not know the precise masses of the neutrinos we have (i) a bound on the total sum of the masses that comes from Cosmology, and, (ii) values for the mass difference between the eigenstates. To be more precise;\n\\begin{itemize}\n  \\item Combining constraints from Cosmic Microwave Background (CMB) anisotropies, Baryon Acoustic Oscillations, Type 1A Supernovae, and, CMB lensing, we will use the constraint \\cite{Couchot2017};\n  \\begin{equation}\n    \\sum{m_{\\nu_i}} < 0.17 \\, \\textrm{eV}\n  \\end{equation}\n  \\item We also know the squared mass differences between some of the mass eigenstates \\cite{Couchot2017};\n  \\begin{align}\n    \\Delta m_{12}^2 = m_2^2 - m_1^2 &= 7.37 \\times 10^{-5}\\,\\textrm{eV}^2 \\\\\n    \\Delta m^2 = m_3^2 - \\frac{1}{2}(m_1^2 + m_2^2) &= +2.50 \\times 10^{-3} \\, \\textrm{eV}^2\\, \\textrm{(NH)} \\\\\n    &= -2.46 \\times 10^{-3} \\, \\textrm{eV}^2\\, \\textrm{(IH)}\n  \\end{align}\n\\end{itemize}\nFrom the last of these constraints we see that fixing one of the masses automatically fixes the others. In our analysis we intend to vary one of the masses of the mass eigenstates and use the squared mass differences to compute the other masses, remaining within the bound set by the cosmological considerations. We will present the analysis in both the normal and inverted cases.\n\n\n\\subsection{The Coupling Constants}\n\n\nThere is one final consequence of the non-coincidence of the mass and flavour eigenstates. We are considering a coupling in the Lagrangian of the form;\n\\begin{equation}\n  \\mL_{\\textrm{new}} = \\sum_{\\ell}{g_\\ell \\delta \\bar{N}_R \\nu_{\\ell, L} + \\textrm{h.c.}}\n\\end{equation}\nwhere importantly, the $\\nu_{\\ell}$ are the flavour eigenstates. Furthermore, we quoted constraints on the couplings $g_\\ell$ in this flavour basis e.g. $g_{\\ell} < 10^{-3}$ in the case of real dark matter. Now consider expanding in the mass basis;\n\\begin{equation}\n  \\mL = \\delta \\bar{N}_R \\sum_{\\ell}{g_\\ell \\sum_{i}{U_{\\ell i}\\nu_{i, L}}} + \\textrm{h.c.} := \\sum_i{g_i \\delta \\bar{N}_R \\nu_{i, L}}\n\\end{equation}\nWe have defined the couplings to the neutrino mass eigenstates;\n\\begin{equation}\n  g_i := \\sum_{\\ell}{U_{\\ell i}g_{\\ell}}\n\\end{equation}\nNow, importantly, these will inherit constraints from the constraints on the flavour basis couplings, and are just related by a linear transformation. This means that we can still parametrise our constraints in terms of the flavour couplings. The context of these comments is that the cosmic neutrino background consists of decoherent mass eigenstates. Therefore instead of considering flavour processes $\\nu_\\mu \\nu_\\ell, \\nu_\\mu \\bar{\\nu}_\\ell \\rightarrow \\delta\\delta$, we should instead consider $\\nu_\\mu \\nu_i \\rightarrow \\delta \\delta$. To do so we should use the $\\set{g_i}$ couplings at the $\\nu_i \\delta N$ vertex, which we can compute as above. We also make use of the mass eigenstate masses as discussed above to compute the centre of mass energy in each of the different cases $i = 1,2,3$. Finally, we will assume that each of the mass eigenstates is equally abundant in the cosmic neutrino background so that we can take the number density of each species to be $n_\\nu/6$ as noted previously.\n\n\\subsection{Neutrino Clustering}\n\n\nThis is the phenomenon relating to the gravitational clustering of neutrinos at late times once they become non-relativistic. This can increase their density inside gravitational wells such as the Milky Way today.  An important reference is \\cite{Ringwald2004} which discusses the clustering of cosmic neutrino background neutrinos onto cold dark matter. In the context of this work, this would affect the number density $n_\\nu(z)$ as the astrophysical neutrino passed through different dark matter distributions. In regions where there is more cold dark matter, \\cite{Ringwald2004} suggests that we should also see more cosmic neutrino background neutrinos. A precision analysis of the propagation of the neutrinos from the blazar should take this into account.\n\nThis being said, \\cite{Ringwald2004} only extends the analysis to the local group\\footnote{The \\textit{Greisen-Zatsepin-Kuzmin} zone}, across distances of $\\textrm{Mpc}$. This is ultimately small scale structure in the context of $\\textrm{Gpc}$ propagation. Figure 8 in \\cite{Ringwald2004} illustrates the density contrast of the neutrinos on this scale. We see that density constrasts of $\\mO(2)$ are realistic, so including this effect could strengthen the bounds. Even an increase of an order of magnitude within the local group would only change the optical depth at the percent level, so we neglect this effect in this work.\n\n\\begin{figure}[t]\n \\centering\n \\includegraphics[width=.5\\textwidth]{ebl.pdf}\n \\caption{The probability, $\\exp(-\\tau)$, where $\\tau$ is the optical depth, of a photon produced in the blazar jet reaching the Earth due to interactions with the EBL. We see that at Fermi-LAT energies, $\\mO(290) \\, \\mathrm{GeV}$, this probability is close to 1, whilst at the higher, HAWC energies, $\\mO(1 - 100) \\, \\mathrm{TeV}$, there is significant attenuation of the flux due to scatterings $\\gamma\\gamma \\rightarrow e^{+}e^{-}$. These calculations are based on \\cite{DeLavallaz:2011ju}.}\n \\label{fig:ebl}\n\\end{figure}\n\n\\subsection{Discussion regarding the consistency of the neutrino and photon flux}\\label{sec:consistent}\n\nIn this subsection we would like to discuss the neutrino flux we use above and see how it compares to the observed photon flux.  The discussion here is a simple sanity check, this subsection therefore on its own contains no results which have any impact on the bound we obtain later. In particular, we are not using the photon flux to derive a bound, we just aim to discuss the discrepancy between the two fluxes.\n\nLet us recall how neutrinos and photons are thought to be generated in the relativistic jets of active galaxies. In the hadronic scenario, highly boosted protons interact with photons in the jet from e.g. electron synchotron radiation. This leads to the production of neutral and charged pions via resonances (for example $p\\gamma \\rightarrow \\Delta^+ \\rightarrow p\\pi^0$) or direct production (for example $p\\gamma \\rightarrow n\\pi^+$). These highly relativistic pions then decay via $\\pi^0 \\rightarrow \\gamma \\gamma$ and $\\pi^+ \\rightarrow \\ell^+ \\nu_\\ell$ where $\\ell$ is a lepton \\cite{Mucke:1998mk, Szabo:1994qx}. This leads to a production of neutrinos and photons with $F_\\nu \\sim F_\\gamma$ within the jet \\cite{Keivani2018}. We might expect that the detection of high energy neutrinos should thus be accompanied by the EM emission of pionic gamma-rays. If this were the case, we would indeed expect the luminosities of the neutrinos and the photons to be comparable, $F_\\nu \\sim F_\\gamma$, as was assumed in \\cite{Kelly}.  Unlike the HAWC constraint, the Fermi-LAT data consisted of an actual measurement, and those authors used this assumption to make a direct prediction for the neutrino flux.\n\nThe assumption that $F_\\nu \\sim F_\\gamma$ is however conservative --- since the neutrinos are weakly interacting, they escape the jet without attenuation to the flux. On the other hand, the photons produced by neutral pion decays, may \\textit{not} be observed due to electromagnetic processes which may occur in the jet or attenuation during propagation across on the Universe. In the latter case this is due to $\\gamma\\gamma \\rightarrow e^+ e^-$ attentuation on the Extragalactic Background Light (EBL) \\cite{Finke:2009xi}.  In Figure \\ref{fig:ebl} we use code developed by one of the authors for a previous project \\cite{DeLavallaz:2011ju} to show the attentuation due to pair production on the EBL for high energy photons from a blazar at redshift $z=0.34$ is not very important at the Fermi-LAT energies considered in \\cite{Kelly} ($<$ 290 GeV) but really cuts off the photon flux at the HAWC energies relevant here (0.8 TeV --- 74 TeV). Because of this, the HAWC data acting as an upper bound is in no conflict with the jet physics.\n\nThe HAWC data in Table \\ref{tab:luminosity} shows that the photon flux at this energy is less than the neutrino flux we have assumed.  Given the fact it is much easier for photons to be attenuated and to lose energy than neutrinos, we assume this is in fact what has happened and note that we have assumed the lower of the two possible estimates of the neutrino flux based on the observed event.", "meta": {"hexsha": "47ed2a8b22f32d82f46367ddf8faab0e1dab9b51", "size": 49865, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Report/appendix.tex", "max_stars_repo_name": "james-alvey-42/TransferReport", "max_stars_repo_head_hexsha": "e7acd36cf7bc0a06b2250aba43a839a963f8196a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Report/appendix.tex", "max_issues_repo_name": "james-alvey-42/TransferReport", "max_issues_repo_head_hexsha": "e7acd36cf7bc0a06b2250aba43a839a963f8196a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Report/appendix.tex", "max_forks_repo_name": "james-alvey-42/TransferReport", "max_forks_repo_head_hexsha": "e7acd36cf7bc0a06b2250aba43a839a963f8196a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 115.6960556845, "max_line_length": 1207, "alphanum_fraction": 0.7239747318, "num_tokens": 15641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.4493926344647596, "lm_q1q2_score": 0.3036836343299769}}
{"text": "\\input format.tex\n\\input defs.tex\n\n%% begin presentation\n\n\\title{\\large \\bfseries Distributed Deep Q-Learning}\n\n\\author{Hao Yi Ong, Kevin Chavez, and Augustus Hong\\\\[3ex]\nCME 323, Stanford University}\n\n\\date{June 3, 2015}\n\n\\begin{document}\n\n\\frame{\n\\thispagestyle{empty}\n\\titlepage\n}\n\n\\section{Introduction}\n\n\\begin{frame}{Motivation}\n  \\begin{itemize}\\itemsep=12pt\n  \n    \\item long-standing challenge of reinforcement learning (RL)\n    \\vspace*{0.5em}\n    \\begin{itemize}\n        \\item control with high-dimensional sensory inputs (\\eg, vision, speech)\n        \\item shift away from reliance on hand-crafted features\n    \\end{itemize}\n    \n    \\item utilize breakthroughs in deep learning for RL \\cite{M+:13,M+:15}\n    \\vspace*{0.5em}\n    \\begin{itemize}\n        \\item extract high-level features from raw sensory data\n        \\item learn better representations than handcrafted features with neural network architectures used in supervised and unsupervised learning\n    \\end{itemize}\n\n    \\item create fast learning algorithm\n    \\vspace*{0.5em}\n    \\begin{itemize}\n        \\item train efficiently with stochastic gradient descent (SGD)\n        \\item distribute training process to accelerate learning \\cite{D+:12}\n    \\end{itemize}\n\n  \\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Success with Atari games}\n    \\begin{figure}\n        \\centering\n        \\includegraphics[width=0.8\\textwidth]{atari-ex1.png}\n    \\end{figure}\n    \\begin{figure}\n        \\centering\n        \\includegraphics[width=0.8\\textwidth]{atari-ex2.png}\n    \\end{figure}\n\\end{frame}\n\n\\begin{frame}{Goals}\n    distributed deep RL algorithm\n    \\vspace*{0.5em}\n    \\begin{itemize}\\itemsep=12pt\n        \n        \\item robust neural network agent\n        \\vspace*{0.5em}\n        \\begin{itemize}\n            \\item must succeed in challenging test problems\n        \\end{itemize}\n\n        \\item control policies with high-dimensional sensory input\n        \\vspace*{0.5em}\n        \\begin{itemize}\n            \\item obtain better internal representations than handcrafted features\n        \\end{itemize}\n\n        \\item fast training algorithm\n        \\vspace*{0.5em}\n        \\begin{itemize}\n            \\item efficiently produce, use, and process training data\n        \\end{itemize}\n\n    \\end{itemize}\n\\end{frame}\n\n\\section{Mathematical formulation}\n\n\\begin{frame}{Playing games}\n    \\begin{figure}\n        \\centering\n        \\includegraphics[width=0.8\\textwidth]{background.pdf}\n    \\end{figure}\n    \\textbf{objective:} learned policy maximizes future rewards\n    \\[\n        R_{t} = \\sum_{t'=t}^{T} \\gamma^{t'-t}r_{t'},\n    \\]\n    \\begin{itemize}\n        \\item discount factor $\\gamma$\n        \\item reward change at time $t'$ $r_{t'}$\n    \\end{itemize}\n\\end{frame}\n\n\\begin{frame}{State-action value function}\n    \\begin{itemize}\\itemsep=12pt\n        \n        \\item basic idea behind RL is to estimate\n        \\[\n            Q^{\\star}\\left(s, a\\right) = \n            \\max_{\\pi}\\Expect\\left[R_{t} \\mid s_{t} = s, a_{t} = a, \\pi \\right],\n        \\]\n        where $\\pi$ maps states to actions (or distributions over actions)\n\n        \\item optimal value function obeys Bellman equation\n        \\[\n            Q^{\\star}\\left(s,a\\right) = \n            \\Expect_{s' \\sim \\mathcal{E}} \\left[r + \\gamma \\max_{a'}Q^{\\star}\\left(s',a'\\right)\\mid s, a \\right],\n        \\]\n        where $\\mathcal{E}$ is the MDP environment\n\n    \\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Q-network}\n    \\begin{itemize}\\itemsep=12pt\n\n        \\item trained by minimizing a sequence of loss functions\n        \\[\n            L^{(i)}\\left(\\theta^{(i)}\\right) =\n            \\Expect_{s,a \\sim \\rho\\left(\\cdot\\right)}\n            \\left[\\left(y^{(i)} - Q\\left(s,a;\\theta^{(i)}\\right)\\right)^{2}\\right],\n        \\]\n        with\n        \\vspace*{0.5em}\n        \\begin{itemize}\n            \\item iteration number $i$, $i$th network parameters $\\theta^{(i)}$\n            \\item target $y^{(i)} = \\Expect_{s'\\sim\\mathcal{E}}\\left[ r + \\gamma\\max_{a'}Q\\left(s',a';\\theta^{(i-1)}\\right) \\mid s,a \\right]$\n            \\item ``behavior distribution'' (exploration policy) $\\rho\\left(s,a\\right)$\n        \\end{itemize}\n\n        \\item architecture varies according to application\n\n    \\end{itemize}\n\\end{frame}\n\n\\section{Serial algorithm}\n\n\\begin{frame}{Preprocessing}\n    \\begin{figure}\n        \\centering\n        \\includegraphics[width=0.9\\textwidth]{process.pdf}\n    \\end{figure}\n\\end{frame}\n\n\\begin{frame}{Q-learning}\n    \\begin{itemize}\\itemsep=12pt\n\n        \\item optimize Q-network loss function via\n        \\[\n            Q\\left(s,a\\right) :=\n            Q\\left(s,a\\right) +\n            \\alpha \\left( r + \\gamma\\max_{a'}Q\\left(s',a'\\right) - Q\\left(s,a\\right) \\right)\n        \\]\n        \n        \\item trains optimal policy using ``behavior policy'' (off-policy)\n        \\vspace*{0.5em}\n        \\begin{itemize}\n            \\item learns policy $\\pi^{\\star}\\left(s\\right) = \\argmax_{a}Q\\left(s,a;\\theta\\right)$\n            \\item uses an $\\epsilon$-greedy strategy (behavior policy) for state-space exploration\n        \\end{itemize}\n    \n    \\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Experience replay}\n    a kind of short-term memory\n    \\vspace*{0.5em}\n    \\begin{itemize}\\itemsep=12pt\n\n        \\item store agent's experiences at each time step\n        \\[\n            e_{t} = \\left(s_{t},a_{t},r_{t},s_{t+1}\\right)\n        \\]\n        \n        \\item experiences form a replay memory dataset\n        \\[\n            \\mathcal{D} = \\left\\{ e_{1}, \\ldots, e_{N} \\right\\},\n        \\]\n        where $N$ is the fixed memory capacity\n\n        \\item execute Q-learning updates with samples of experience\n        \\[\n            e \\sim \\mathcal{D}\n        \\]\n\n    \\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Serial deep Q-learning}\n    \\begin{tabbing}\n        {\\bf given} replay memory $\\mathcal{D}$ with capacity $N$ \\\\*[\\smallskipamount]\n        {\\bf initialize} Q-networks $Q$, $\\hat{Q}$ with same random weights $\\theta$ \\\\*[\\smallskipamount]\n        {\\bf repeat} until timeout \\\\\n            \\qquad \\= {\\bf initialize} frame sequence $s_{1}=\\left\\{ x_{1} \\right\\}$ and preprocessed state $\\phi_{1} = \\phi\\left(s_{1}\\right)$ \\\\\n            \\> for \\(t\\) = 1, \\(\\ldots\\) , \\(T\\) \\\\\n            \\qquad \\qquad \\= 1.\\ select action $ a_{t} = \\bigg\\{\n            \\begin{tabular}{ll}\n                $\\max_{a}Q\\left(\\phi\\left(s_{t}\\right),a;\\theta\\right)$ & w.p. $1 - \\epsilon$ \\\\\n                \\text{random action} & otherwise\n            \\end{tabular} $ \\\\\n            \\> 2.\\ execute action $a_{t}$ and observe reward $r_{t}$ and frame $x_{t+1}$ \\\\\n            \\> 3.\\ append $s_{t+1} = \\left(s_{t}, a_{t}, x_{t+1}\\right)$ and preprocess $\\phi_{t+1} = \\phi\\left(s_{t+1}\\right)$ \\\\\n            \\> 4.\\ store experience $\\left(\\phi_{t},a_{t},r_{t},\\phi_{t+1}\\right)$ in $\\mathcal{D}$ \\\\\n            \\> 5.\\ uniformly sample minibatch $\\left( \\phi_{j},a_{j},r_{j},\\phi_{j+1} \\right) \\sim \\mathcal{D}$ \\\\\n            \\> 6.\\ set $ y_{j} = \\bigg\\{\n            \\begin{tabular}{ll}\n                $r_{j}$ & if $\\phi_{j+1}$ terminal \\\\\n                $r_{j} + \\gamma\\max_{a'}\\hat{Q}\\left(\\phi_{j+1},a';\\theta\\right)$ & otherwise\n            \\end{tabular} $ \\\\\n            \\> 7.\\ perform gradient descent step for $Q$ on minibatch \\\\\n            \\> 8.\\ every C steps reset $\\hat{Q} = Q$\n    \\end{tabbing}\n\\end{frame}\n\n\\section{Distributed algorithm}\n\n\\begin{frame}{Model parallelism}\n    for each Q-network\n    \\vspace*{0.5em}\n    \\begin{itemize}\\itemsep=12pt\n\n        \\item partition model across CPUs/GPUs\n        \\vspace*{0.5em}\n        \\begin{itemize}\n            \\item up to availability of CPU/GPU resources\n            \\item uses Caffe deep learning framework\n        \\end{itemize}\n\n        \\item \\todo{Kevin/Hao Yi: How does caffe use CPU/GPU resources? How does complexity scale for implementation? Answers question of how our algorithm scale for model.}\n\n    \\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Data parallelism}\n    \\textbf{downpour SGD:} generic asynchronous distributed SGD\n    \\begin{figure}\n        \\centering\n        \\includegraphics[width=0.8\\textwidth]{data-par.pdf}\n    \\end{figure}\n\\end{frame}\n\n\\begin{frame}{Implementation}\n    \\begin{itemize}\\itemsep=12pt\n\n        \\item data shards are generated locally on each model worker in real-time\n        \\vspace*{0.5em}\n        \\begin{itemize}\n            \\item data is stored independently for each worker\n            \\item since game emulation is simple, generating data is fast\n            \\item simple fault tolerance approach: regenerate data if worker dies\n        \\end{itemize}\n\n        \\item algorithm scales very well with data\n        \\vspace*{0.5em}\n        \\begin{itemize}\n            \\item since data lives locally on workers, no data is sent\n        \\end{itemize}\n\n    \\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Implementation}\n    \\begin{itemize}\\itemsep=12pt\n\n        \\item bottleneck is parameter update time on parameter server\n        \\vspace*{0.5em}\n        \\begin{itemize}\n            \\item \\eg, if parameter server gradient update takes 2 ms, then we can only do up to 500 updates per second (using buffers, etc.)\n        \\end{itemize}\n\n        \\item trade-off between parallel updates and model staleness\n        \\vspace*{0.5em}\n        \\begin{itemize}\n            \\item because worker is likely using a stale model, the updates are ``noisy'' and not of the same quality as in serial implementation\n        \\end{itemize}\n\n    \\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Implementation}\n    communication pattern\n    \\vspace*{0.5em}\n    \\begin{itemize}\\itemsep=12pt\n        \n        \\item one-to-all and all-to-one, but asynchronous for every minibatch\n\n        \\item like multiple asynchronous all-reduces\n\n    \\end{itemize}\n\\end{frame}\n\n\\section{Numerical experiments}\n\n\\begin{frame}{Evaluation}\n    \\begin{figure}\n        \\centering\n        \\includegraphics[height=0.6\\textheight]{snake.png}\n    \\end{figure}\n\\end{frame}\n\n\\begin{frame}{Snake}\n    \\begin{itemize}\\itemsep=12pt\n        \n        \\item parameters\n        \\vspace*{0.5em}\n        \\begin{itemize}\n            \\item snake length grows with number of apples eaten\n            \\item one apple at any time, regenerated once eaten\n            \\item $n \\times n$ array, with walled-off world\n            \\item want to maximize score, equal to snake length\n        \\end{itemize}\n\n        \\item complexity\n        \\vspace*{0.5em}\n        \\begin{itemize}\n            \\item four possible states for each cell: $\\left\\{ \\mbox{empty, head, body, apple} \\right\\}$\n            \\item state space cardinality is $O\\left(n^{8}\\right)$\n            \\item four possible actions: $\\left\\{ \\mbox{north, south, east, west} \\right\\}$\n        \\end{itemize}\n\n    \\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Results}\n    \n\\end{frame}\n\n\\section{Conclusion}\n\n\\begin{frame}{Summary}\n    \n\\end{frame}\n\n\\section*{}\n\n\\begin{frame}[allowframebreaks]{References}\n    \\bibliography{IEEEabrv,slides}\n\\end{frame}\n\n\\section*{Appendix}\n\n\\begin{frame}{Theoretical complications}\n    deep learning algorithms require\n    \\vspace*{0.5em}\n    \\begin{itemize}\\itemsep=12pt\n\n        \\item huge training datasets\n\n        \\item independence between samples\n\n        \\item fixed underlying data distribution\n\n    \\end{itemize}\n\\end{frame}\n\n\\begin{frame}{Deep Q-learning}\n    avoids theoretical complications\n    \\vspace*{0.5em}\n    \\begin{itemize}\\itemsep=12pt\n\n        \\item greater data efficiency\n        \\vspace*{0.5em}\n        \\begin{itemize}\n            \\item each experience potentially used in many weight udpates\n        \\end{itemize}\n\n        \\item reduce correlations between samples\n        \\vspace*{0.5em}\n        \\begin{itemize}\n            \\item randomizing samples breaks correlations from consecutive samples\n        \\end{itemize}\n\n        \\item experience replay averages behavior distribution over states\n        \\vspace*{0.5em}\n        \\begin{itemize}\n            \\item smooths out learning\n            \\item avoids oscillations or divergence in gradient descent\n        \\end{itemize}\n\n    \\end{itemize}\n\\end{frame}\n\n\\end{document}", "meta": {"hexsha": "9fcf671238ba84522f74391d6e66e0267417e3cc", "size": 12036, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "slides/slides.tex", "max_stars_repo_name": "kjchavez/distributed-deep-q", "max_stars_repo_head_hexsha": "f3660f30dbc4756433cab4a97e0ffba8e6e5c418", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2015-06-03T23:53:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-07T09:56:09.000Z", "max_issues_repo_path": "slides/slides.tex", "max_issues_repo_name": "kjchavez/distributed-deep-q", "max_issues_repo_head_hexsha": "f3660f30dbc4756433cab4a97e0ffba8e6e5c418", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slides/slides.tex", "max_forks_repo_name": "kjchavez/distributed-deep-q", "max_forks_repo_head_hexsha": "f3660f30dbc4756433cab4a97e0ffba8e6e5c418", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2015-06-14T16:22:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T01:22:27.000Z", "avg_line_length": 30.7040816327, "max_line_length": 173, "alphanum_fraction": 0.6058491193, "num_tokens": 3454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3036429639767094}}
{"text": "% !TEX root =  paper.tex\n\n\\section{Method}\n%\\begin{figure*}[t!]\n%\t\\begin{center}\n%\t\t\\subfloat[]{\\includegraphics[width=0.24\\linewidth]{./figures/methods/multicut_input.png}}\n%\t\t\\subfloat[]{\\includegraphics[width=0.24\\linewidth]{./figures/methods/pre-multicut.png}}\n% \t\t\\subfloat[]{\\includegraphics[width=0.24\\linewidth]{./figures/methods/multicut-graph.png}}\n% \t\t\\subfloat[]{\\includegraphics[width=0.24\\linewidth]{./figures/methods/post-multicut.png}}\n% \t\\end{center}\n% \t\\caption{Outline of our approach, from left to right: result of the pixel-based segmentation and agglomeration algorithm; segments of several neurons from the initial segmentation; extracted skeletonized network of those segments; improved 3D reconstruction of the selected segments after graph construction and partitioning with constraints.}\n% \t\\label{fig:overview}\n% \\end{figure*}\n\n%There are two types of errors that can occur in connectomics segmentations: \\textit{split errors} and \\textit{merge errors}. \n%In a split error, two segments should have been merged into one neuronal process (Fig.~\\ref{fig:improved-reconstruction}). \n%In a merge error, one segment corresponds to more than one neuron.\n%Generally, it is much more difficult to correct merge errors than to correct split errors, as the space of possible split proposals grows quickly~\\cite{parag2015properties}.\n%Thus, most reconstruction approaches are tuned towards over-segmentation with many more split than merge errors. \n%The input of our method is the over-segmentation of EM image volumes from state-of-the-art pipelines.\n\nOur method is illustrated in Fig.~\\ref{fig:teaser_pipeline}.\nFrom the input segmentation we generate a graph $G$ with nodes $N$ and edges $E$ with weights $w_e$. \nThe nodes correspond to labeled segments from the input data with edges between merge candidates.\nWe propose the following three steps to formulate and then partition the graph while obeying constraints from the underlying biology.\nFirst, we only consider merging segments based on a skeletonized representation of the input segmentation (Fig.~\\ref{fig:teaser_pipeline}a).\nThis enables us to reduce the number of edges in the graph based on prior knowledge on the shape of neuronal processes.\nSecond, we train a convolutional neural network that learns biological constraints based on the shapes of the input segmentation (Fig.~\\ref{fig:teaser_pipeline}b).\nThis network generates probabilities that segments belong to the same neuron based only on the segmentations. \nAn example of one such learned constraint is that neurons have small turning radii (Fig.~\\ref{fig:turn-radii}).\nThird, we partition the graph using a lifted multicut formulation with additional acyclic constraints to enforce global biological constraints (Fig.~\\ref{fig:teaser_pipeline}c).\nThe lifted multicut solution is globally consistent which we then augment to produce a tree-structured graph (i.e., one with no cycles).\n\n\\subsection{Skeleton-Based Graph Generation}\n%\\subsubsection{Node Generation}\n\\label{sec:skeletonization}\nMost region merging methods create a region graph by removing small-sized segments and linking each pair of adjacent segments, which can still lead to a large graph size due to the irregular shape of neural structures.\nWe use a skeleton representation of the segmentation to reduce the graph size with the geometric constraints on the connectivity of two adjacent segments to prune edges.\n% a bit trivial, as everyone is doing this. maybe no need to mention\n% \\subsubsection{Node Pruning}\n% %The simplest node generation strategy creates one node for every unique segment label in the input volume. \n% Some labels in the volume correspond to very small structures that are likely the result of segmentation errors, typically in regions with noisy raw image data. \n% It is difficult to extract useful shape features from these segments because of their small, often random, shape. \n% We prune these nodes from the graph by removing all segments with fewer than a empirical threshold $t_{seg} = 20,000$ voxels. \n% This removes on average \\TODO{XX}\\% of the segments in our  datasets (Sec.~\\ref{sec:dataset}), leaving us with around $\\TODO{XX}$ nodes per dataset (\\TODO{X nodes per micrometer}). \n% Despite the large number of segments, these regions only take up \\TODO{XX}\\% of the total volume on average.\n\n% \\subsubsection{Edge Pruning}\n\n\\begin{figure}[t]\n\t\\centering\n\t\\begin{minipage}{0.45\\linewidth}\n\t\t\\includegraphics[width=\\linewidth]{./figures/skeleton1.png}\t\t\n\t\\end{minipage}\n\t\\hfill\n\t\\begin{minipage}{0.45\\linewidth}\n\t\t\\includegraphics[width=\\linewidth]{./figures/skeleton2.png}\t\t\n\t\\end{minipage}\n\t\\begin{minipage}{0.45\\linewidth}\n\t\t\\includegraphics[width=\\linewidth]{./figures/skeleton3.png}\t\t\n\t\\end{minipage}\n\t\\hfill\n\t\\begin{minipage}{0.45\\linewidth}\n\t\t\\includegraphics[width=\\linewidth]{./figures/skeleton4.png}\t\t\n\t\\end{minipage}\n\t\\caption{Example skeletons (in black) extracted from segments using a variant of the TEASER algorithm~\\cite{sato2000teasar}. These skeletons not only capture the shape of the segmentation, but also provide endpoints useful for region merging proposals.}\n\t\\label{fig:skeletonization}\n\\end{figure}\n\n%A typical approach for generating edges produces one between all adjacent segments. \n%Two segments $l_1$ and $l_2$ are considered adjacent if there is a pair of adjacent voxels with one labeled $l_1$ and the other labeled $l_2$.\n%For example, pixel-based agglomeration methods such as mean agglomeration~\\cite{lee2017superhuman} or waterz~\\cite{funke2017deep} consider all pairs of adjacent segments for merging.\n%However, this method produces too many edges in the graph for graph-based optimization approaches. \nOur key observation is that if two segments belong to the same neuronal process, their skeleton end points should satisfy certain geometric constraints.\nTo extract the skeleton from each segment, we use a variant~\\cite{zhao2014automatic} of the TEASER algorithm~\\cite{sato2000teasar}. \nThis skeletonization algorithm repeatedly uses Dijkstra's algorithm to find the farthest voxel from a seed location. \nSince this algorithm is non-linear in the number of voxels, we downsample the datasets so that there are voxel samples every $\\SI{30}{\\nano\\meter}$ in each dimension.\nEmpirically, this reduced the running time for skeletonization by $30\\times$ with minimal reduction in skeleton accuracy (${\\sim}5\\%$ fewer branches). \nFig.~\\ref{fig:skeletonization} shows four examples of extracted skeletons (in black). \nThese skeletons consist of a sequence of \\textit{joints}, locations that are locally a maximum distance from the segment boundary, with line segments connecting successive joints. \nWe refer to joints that have only one connected neighbor as \\textit{endpoints}. \nWe find that approximately 70\\% of the segments that are erroneously split have nearby endpoints (Fig.~\\ref{fig:merge_candidates}). \n\nTwo segments, $s_1$ and $s_2$, receive a corresponding edge if the two following conditions hold.\nFirst, endpoints in either $s_1$ or $s_2$ are within $t_{low}$ nm of any voxel in the other segment.\nSecond, there are endpoints in $s_1$ and in $s_2$ that are within $t_{high}$ nm of each other.\nWe store the midpoints between the two endpoints as the center of the potential merge in the set $\\mathbb{S}_c$. \nThis algorithm produces a set of segments to consider for merging. \nOnly these pairs have a corresponding edge in the constructed graph.\nWe provide an empirical analysis of these parameters on the structure of the graph in the supplemental materials.\n\n\\begin{figure}[t]\n\t\\begin{minipage}{0.4\\linewidth}\n\t\t\\includegraphics[width=\\linewidth]{./figures/constraint_error.png}\n\t\\end{minipage}\n\t\\hfill\n\t\\begin{minipage}{0.55\\linewidth}\n\t\t\\includegraphics[width=\\linewidth]{./figures/constraint_success.png}\n\t\\end{minipage}\n\t\\caption{Geometric constraints for region merging. We show two region merging proposals. On the left, the segments do not belong to the same neuron, as evidenced by the sharp turning radius indicated by the arrow; while on the right, the segments should be merged due to the continuity of the 3D shape. Instead of using handcrafted geometric features, we train a convolutional neural networks to automatically learn them from the ground truth labels.}\n\t\\label{fig:turn-radii}\n\\end{figure}\n\\subsection{Learning-based Edge Weight}\n\\label{sec:edge-weights}\nWe assign an edge weight $w_e$ to each edge corresponding to the probability that two nodes belong to the same neuronal process.\nWe train a 3D CNN model to learn these geometric constraints for valid connection between two segments from labeled volume.\n\\\\~\\\\\n\\noindent\\textbf{Edge Probability}\nTo predict the probabilities that two segments belong to the same neuron, we train a feed-forward convolutional network with three \\textit{VGG-style} convolution blocks~\\cite{chatfield2014return} and two fully connected layers before the final sigmoid activation. \n\nFor the input of the network, we extract a cubic region of interest (ROI) around each midpoint $e$ in $\\mathbb{S}_c$ as input to the CNN. \nThe CNN receives three input channels for every voxel in the ROI around segments $l_1$ and $l_2$. \nThe input in all of the channels is in the set $\\{-0.5, 0.5\\}$. \nThe first channel is $0.5$ only if the corresponding voxel has label $l_1$. \nThe second channel is $0.5$ only if the corresponding voxel has label $l_2$. \nThe third channel is $0.5$ if the corresponding voxel is either $l_1$ or $l_2$.\nWe do not use the raw EM image information to avoid the need to retrain the network on datasets that have been stained differently or imaged at different resolution. \nThis reduces the need for generating costly manually-labeled ground truth. \n\n\n%The first two max pooling layers are anisotropic with pooling only in the $x$ and $y$ dimensions. \n%The output of this final pooling step is flattened into a 1D vector that is input into . \n%The final layer produces probabilities with a sigmoid activation function~\\cite{funahashi1989approximate}. \n%All of the other activation functions are .\n\n% covered in the experiment\n%For training we use a stochastic gradient descent optimizer with Nesterov's accelerated gradient~\\cite{nesterov1983method}. \n%We employ dropouts of $0.2$ after every pooling layer and the first dense layer, and a dropout of $0.5$ after the final dense layer to prevent overfitting. \n%We discuss all other network parameters in Sec.~\\ref{sec:network-parameters}.\n\n\\begin{figure}[t]\n\t\\centering\n\t\\begin{minipage}{0.32\\linewidth}\n\t\t\\includegraphics[width=\\linewidth]{./figures/split_error1.png}\t\t\n\t\\end{minipage}\n\t\\hfill\n\t\\begin{minipage}{0.32\\linewidth}\n\t\t\\includegraphics[width=\\linewidth]{./figures/split_error2.png}\t\t\t\t\n\t\\end{minipage}\n\t\\hfill\n\t\\begin{minipage}{0.32\\linewidth}\n\t\t\\includegraphics[width=\\linewidth]{./figures/split_error3.png}\n\t\\end{minipage}\n\t\\caption{Three erroneously split segments.}\n\t\\label{fig:merge_candidates}\n\\end{figure}\n\\subsection{Optimization-Based Graph Partition}\n\\label{sec:optimization}\nAfter graph construction, we segment the graph in a globally consistent manner while enforcing topological constraints on the output.\n\\\\~\\\\\n%\\subsubsection{Lifted Multicut}\n\\noindent\\textbf{Lifted Multicut}\nAfter constructing the graph we seek to partition it into labels where every label corresponds to a neuronal process. \nWe formulate this graph partitioning problem as a multicut problem.\nThere are two primary benefits to using a multicut formulation. \nFirst, the number of segments in the final graph is not predetermined but depends on the input. \nSecond, this minimization produces globally consistent solutions (i.e., a boundary remains only if the two corresponding nodes belong to unique segments)~\\cite{keuper2015efficient}.\n\nWe apply the algorithms of Keuper et al.~\\cite{keuper2015efficient} to produce a feasible solution to the multicut problem using greedy additive edge contraction.\nFollowing their example, we employ the generalized lifted multicut formulation.\nTraditional multicut solutions only consider the probabilities that two adjacent nodes belong to the same segment. \nIn the lifted extension to the problem, we can penalize non-adjacent nodes that belong to different segments. \nThese penalties between non-adjacent nodes are called lifted edges. \nIdeally these lifted weights represent the probability that two nodes belong to the same neuron.\nHowever, determining such probabilities is computationally expensive.\nWe approximate these probabilities by finding the maximal probable path between any two nodes using Dijkstra's algorithm~\\cite{keuper2015efficient}.\nThis is an underestimate of the probability that two nodes belong to the same neuron since it does not consider all possible paths.\nSince our graphs are sufficiently small, we can generate lifted edges between all pairs of nodes. \n\\\\~\\\\\n\\noindent\\textbf{Edge Weight} \nWe need to convert the probabilities into the following weighting scheme to solve the multicut problem with this heuristic~\\cite{keuper2015efficient,andres2011probabilistic}.\nGiven the probability that the nodes belong to the same neuron is $p_e$, the edge weight $w_e$ is defined as\n%p_e &=\\mbox{CNN}(x_1, x_2) \\\\\n\\begin{align}\nw_e = \\log{\\frac{p_e}{1 - p_e}} + \\log{\\frac{1 - \\beta}{\\beta}},\n\\end{align}\nwhere $\\beta$ is a tunable parameter that encourages over- or under-segmentation. \nSince, there are many more lifted edges than adjacent edges, we scale down the lifted weights proportionally to their total number  \n~\\cite{beier2017multicut}.\n\\\\~\\\\\n%\\subsubsection{Topological Constraints}\n\\noindent\\textbf{Topological Constraints}\nBy reformulating the segmentation problem as a graph partitioning one, we can enforce some global constraints on our result based on the underlying biology.\nTraditional hierarchical clustering algorithms do not rely on such constraints but consider local decisions independently.\nWe enforce a global constraint that neurons are tree-structured and should not contain cycles. \nThe multicut problems returns a series of ``collapsed'' edges between nodes that belong to the same neuron.\nWe iterate over these edges in order of the probability of merge generated by our CNN. \nWe ``collapse'' an edge only if it does not create a cycle in the graph.\n", "meta": {"hexsha": "89ab53d718343fff0c7b562f916e38ad19e6696a", "size": 14258, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "papers/eccv2018/2_method.tex", "max_stars_repo_name": "romil797/ibex", "max_stars_repo_head_hexsha": "898134a96e299d8106d9deb7b217671c39bfeca2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "papers/eccv2018/2_method.tex", "max_issues_repo_name": "romil797/ibex", "max_issues_repo_head_hexsha": "898134a96e299d8106d9deb7b217671c39bfeca2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "papers/eccv2018/2_method.tex", "max_forks_repo_name": "romil797/ibex", "max_forks_repo_head_hexsha": "898134a96e299d8106d9deb7b217671c39bfeca2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 75.4391534392, "max_line_length": 452, "alphanum_fraction": 0.7914153458, "num_tokens": 3393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850402140659, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.3035915637196329}}
{"text": "\\documentclass[english]{../thermomemo/thermomemo}\n\\usepackage[utf8]{inputenc}\n\\usepackage{amsmath}\n\\usepackage{array}% improves tabular environment.\n\\usepackage{dcolumn}% also improves tabular environment, with decimal centring.\n\\usepackage{booktabs}\n\\usepackage{todonotes}\n\\presetkeys{todonotes}{inline}{}\n\\usepackage{subcaption,caption}\n\\usepackage{xspace}\n\\usepackage{tikz}\n\\usetikzlibrary{arrows}\n\\usetikzlibrary{snakes}\n\\usepackage{verbatim}\n\\usepackage{hyperref}\n\\usepackage{mhchem}\n\\usepackage{siunitx}\n%\n\\usepackage{xcolor}\n\\hypersetup{\n  colorlinks,\n  linkcolor={red!50!black},\n  citecolor={blue!50!black},\n  urlcolor={blue!80!black}\n}\n%\n% Kolonnetyper for array.sty:\n\\newcolumntype{C}{>{$}c<{$}}\n\\newcolumntype{L}{>{$}l<{$}}\n%\n\\newcommand*{\\unit}[1]{\\ensuremath{\\,\\mathrm{#1}}}\n\\newcommand*{\\uunit}[1]{\\ensuremath{\\mathrm{#1}}}\n%\\newcommand*{\\od}[3][]{\\frac{\\mathrm{d}^{#1}#2}{\\mathrm{d}{#3}^{#1}}}% ordinary derivative\n\\newcommand*{\\od}[3][]{\\frac{\\dif^{#1}#2}{\\dif{#3}^{#1}}}% ordinary derivative\n\\newcommand*{\\pd}[3][]{\\frac{\\partial^{#1}#2}{\\partial{#3}^{#1}}}% partial derivative\n\\newcommand*{\\pdc}[3]{\\frac{\\partial^{2}#1}{\\partial{#2}\\partial{#3}}}% partial derivative\n\\newcommand*{\\pdt}[3][]{{\\partial^{#1}#2}/{\\partial{#3}^{#1}}}% partial\n                                % derivative for inline use.\n\\newcommand{\\pone}[3]{\\frac{\\partial #1}{\\partial #2}_{#3}}% partial\n                                % derivative with information of\n                                % constant variables\n\\newcommand{\\ponel}[3]{\\frac{\\partial #1}{\\partial #2}\\bigg|_{#3}} % partial derivative with informatio of constant variable. A line is added.\n\\newcommand{\\ptwo}[3]{\\frac{\\partial^{2} #1}{\\partial #2 \\partial\n    #3}} % partial differential in two different variables\n\\newcommand{\\pdn}[3]{\\frac{\\partial^{#1}#2}{\\partial{#3}^{#1}}}% partial derivative\n\n% Total derivative:\n\\newcommand*{\\ttd}[2]{\\frac{\\mathrm{D} #1}{\\mathrm{D} #2}}\n\\newcommand*{\\td}[2]{\\frac{\\mathrm{d} #1}{\\mathrm{d} #2}}\n\\newcommand*{\\ddt}{\\frac{\\partial}{\\partial t}}\n\\newcommand*{\\ddx}{\\frac{\\partial}{\\partial x}}\n% Vectors etc:\n% For Computer Modern:\n\n\\DeclareMathAlphabet{\\mathsfsl}{OT1}{cmss}{m}{sl}\n\\renewcommand*{\\vec}[1]{\\boldsymbol{#1}}%\n\\newcommand*{\\vektor}[1]{\\boldsymbol{#1}}%\n\\newcommand*{\\tensor}[1]{\\mathsfsl{#1}}% 2. order tensor\n\\newcommand*{\\matr}[1]{\\tensor{#1}}% matrix\n\\renewcommand*{\\div}{\\boldsymbol{\\nabla\\cdot}}% divergence\n\\newcommand*{\\grad}{\\boldsymbol{\\nabla}}% gradient\n% fancy differential from Claudio Beccari, TUGboat:\n% adjusts spacing automatically\n\\makeatletter\n\\newcommand*{\\dif}{\\@ifnextchar^{\\DIfF}{\\DIfF^{}}}\n\\def\\DIfF^#1{\\mathop{\\mathrm{\\mathstrut d}}\\nolimits^{#1}\\gobblesp@ce}\n\\def\\gobblesp@ce{\\futurelet\\diffarg\\opsp@ce}\n\\def\\opsp@ce{%\n  \\let\\DiffSpace\\!%\n  \\ifx\\diffarg(%\n    \\let\\DiffSpace\\relax\n  \\else\n    \\ifx\\diffarg[%\n      \\let\\DiffSpace\\relax\n    \\else\n      \\ifx\\diffarg\\{%\n        \\let\\DiffSpace\\relax\n      \\fi\\fi\\fi\\DiffSpace}\n\\makeatother\n%\n\\newcommand*{\\me}{\\mathrm{e}}% e is not a variable (2.718281828...)\n%\\newcommand*{\\mi}{\\mathrm{i}}%  nor i (\\sqrt{-1})\n\\newcommand*{\\mpi}{\\uppi}% nor pi (3.141592...) (works for for Lucida)\n%\n% lav tekst-indeks/subscript/pedex\n\\newcommand*{\\ped}[1]{\\ensuremath{_{\\text{#1}}}}\n\\newcommand*{\\ap}[1]{\\ensuremath{^{\\text{#1}}}}\n\\newcommand*{\\apr}[1]{\\ensuremath{^{\\mathrm{#1}}}}\n\\newcommand*{\\pedr}[1]{\\ensuremath{_{\\mathrm{#1}}}}\n%\n\\newcommand*{\\volfrac}{\\alpha}% volume fraction\n\\newcommand*{\\surften}{\\sigma}% coeff. of surface tension\n\\newcommand*{\\curv}{\\kappa}% curvature\n\\newcommand*{\\ls}{\\phi}% level-set function\n\\newcommand*{\\ep}{\\Phi}% electric potential\n\\newcommand*{\\perm}{\\varepsilon}% electric permittivity\n\\newcommand*{\\visc}{\\mu}% molecular (dymamic) viscosity\n\\newcommand*{\\kvisc}{\\nu}% kinematic viscosity\n\\newcommand*{\\cfl}{C}% CFL number\n\n\\newcommand*{\\cons}{\\vec U}\n\\newcommand*{\\flux}{\\vec F}\n\\newcommand*{\\dens}{\\rho}\n\\newcommand*{\\svol}{\\ensuremath v}\n\\newcommand*{\\temp}{\\ensuremath T}\n\\newcommand*{\\vel}{\\ensuremath u}\n\\newcommand*{\\mom}{\\dens\\vel}\n\\newcommand*{\\toten}{\\ensuremath E}\n\\newcommand*{\\inten}{\\ensuremath e}\n\\newcommand*{\\press}{\\ensuremath p}\n\\renewcommand*{\\ss}{\\ensuremath a}\n\\newcommand*{\\jac}{\\matr A}\n%\n\\newcommand*{\\abs}[1]{\\lvert#1\\rvert}\n\\newcommand*{\\bigabs}[1]{\\bigl\\lvert#1\\bigr\\rvert}\n\\newcommand*{\\biggabs}[1]{\\biggl\\lvert#1\\biggr\\rvert}\n\\newcommand*{\\norm}[1]{\\lVert#1\\rVert}\n%\n\\newcommand*{\\e}[1]{\\times 10^{#1}}\n\\newcommand*{\\ex}[1]{\\times 10^{#1}}%shorthand -- for use e.g. in tables\n\\newcommand*{\\exi}[1]{10^{#1}}%shorthand -- for use e.g. in tables\n\\newcommand*{\\nondim}[1]{\\ensuremath{\\mathit{#1}}}% italic iflg. ISO. (???)\n\\newcommand*{\\rey}{\\nondim{Re}}\n\\newcommand*{\\acro}[1]{\\textsc{\\MakeLowercase{#1}}}%acronyms etc.\n\\newcommand*{\\ousum}[2]{\\overset{#1}{\\underset{#2}{\\sum}}}\n\n\\newcommand{\\nto}{\\ensuremath{\\mbox{N}_{\\mbox{\\scriptsize 2}}}}\n\\newcommand{\\chfire}{\\ensuremath{\\mbox{CH}_{\\mbox{\\scriptsize 4}}}}\n%\\newcommand*{\\checked}{\\ding{51}}\n\\newcommand{\\coto}{\\ensuremath{\\text{CO}_{\\text{\\scriptsize 2}}}}\n\\newcommand{\\celsius}{\\ensuremath{^\\circ\\text{C}}}\n\\newcommand{\\clap}{Clapeyron~}\n\\newcommand{\\subl}{\\ensuremath{\\text{sub}}}\n\\newcommand{\\spec}{\\text{spec}}\n\\newcommand{\\sat}{\\text{sat}}\n\\newcommand{\\sol}{\\text{sol}}\n\\newcommand{\\liq}{\\text{liq}}\n\\newcommand{\\vap}{\\text{vap}}\n\\newcommand{\\amb}{\\text{amb}}\n\\newcommand{\\tr}{\\text{tr}}\n\\newcommand{\\crit}{\\text{crit}}\n\\newcommand{\\entr}{\\ensuremath{\\text{s}}}\n\\newcommand{\\fus}{\\text{fus}}\n\\newcommand{\\flash}[1]{\\ensuremath{#1\\text{-flash}}}\n\\newcommand{\\spce}[2]{\\ensuremath{#1\\, #2\\text{ space}}}\n\\newcommand{\\spanwagner}{\\text{Span--Wagner}}\n\\newcommand{\\triplepoint}{\\text{TP triple point}}\n\\newcommand{\\wrpt}{\\text{with respect to}\\xspace}\n\\newcommand{\\excess}{\\text{E}\\xspace}\n\\newcommand{\\comb}{\\text{comb}\\xspace}\n\\newcommand{\\FH}{\\text{FH}\\xspace}\n\\newcommand{\\SG}{\\text{SG}\\xspace}\n\\newcommand{\\NC}{\\text{NC}\\xspace}\n\\newcommand{\\NGr}{\\text{NG}\\xspace}\n\\newcommand{\\res}{\\text{R}\\xspace}\n\\newcommand{\\scomp}{\\text{s}\\xspace}\n\\newcommand{\\nsc}{\\text{ns}\\xspace}\n\n\\title{Phase envelope modelling}\n\\author{Morten Hammer}\n\n\\graphicspath{{gfx/}}\n\n\\begin{document}\n\\frontmatter\n\\tableofcontents\n\\section{Introduction}\nThe intention of this memo is to describe the equations used for mapping phase envelopes in thermopack.\n\n\n\\section{Liquid-Vapor envelopes}\n\nThe equations:\n\n\\begin{align}\n   g_i &= \\ln K_i + \\ln \\varphi^\\vap_i - \\ln \\varphi^\\liq_i , \\quad\n   i=1,\\dots,n \\label{eq:fug_eq}\\\\\n   g_{n+1} &= \\overset{n}{\\underset{i=1}{\\sum}}\\left(Y_i-X_i\\right), \\label{eq:sum_eq} \\\\\n   g_{n+2} &= S - S_\\spec \\label{eq:spec_eq}.\n\\end{align}\n\nRelation between overall composition and phase compositions:\n\\begin{align}\n  \\label{eq:comp1}\n  \\vektor{X} &= \\frac{\\vektor{Z}}{1-\\beta+\\beta \\vektor{K}},\\\\\n  \\label{eq:comp2}\n  \\vektor{Y} &= \\frac{\\vektor{K}\\vektor{Z}}{1-\\beta+\\beta \\vektor{K}}.\n\\end{align}\n\nVector form of the equations:\n\\begin{equation}\n  \\label{eq:G}\n  \\vektor{G}\\left(\\vektor{W}\\right) = \\begin{pmatrix}\n    g_1 \\\\\n    \\vdots \\\\\n    g_{n+2}\n  \\end{pmatrix}\n\\end{equation}\n\nVariables:\n\\begin{equation}\n  \\label{eq:W}\n  \\vektor{W} = \\begin{pmatrix}\n    \\ln \\vektor{K} \\\\\n    \\ln T \\\\\n    \\ln P\n  \\end{pmatrix}\n\\end{equation}\n\\subsection{Differentials}\nThe Jacobean matrix needs the following differentials:\n\\begin{equation}\n   \\pd{X_i}{\\ln K_i} = -\\frac{K_iZ_i\\beta}{\\left(1-\\beta+\\beta K_i\\right)^2} = -\\frac{K_iX_i\\beta}{\\left(1-\\beta+\\beta K_i\\right)} = -\\beta\\frac{Y_iX_i}{Z_i}.\n\\end{equation}\n\n\\begin{equation}\n   \\pd{Y_i}{\\ln K_i} = -K_i\\frac{K_i Z_i\\beta}{\\left(1-\\beta+\\beta K_i\\right)^2} + K_i\\frac{Z_i\\beta}{\\left(1-\\beta+\\beta K_i\\right)} = -\\frac{\\left(1-\\beta\\right)}{\\beta}\\pd{X_i}{K_i} = \\left(1-\\beta\\right)\\frac{Y_iX_i}{Z_i}.\n\\end{equation}\n\n\\begin{equation}\n   \\pd{g_i}{\\ln K_j} = \\delta_{ij} + \\left(\\left(1-\\beta\\right)\\pd{\\ln \\varphi^\\vap_i}{Y_j} + \\beta\\pd{\\ln \\varphi^\\liq_i}{X_j}\\right)\\frac{X_jY_j}{Z_j}.\n\\end{equation}\n\n\\begin{equation}\n   \\pd{g_{n+1}}{\\ln K_j} = \\frac{X_jY_j}{Z_j}.\n\\end{equation}\n\n\\section{Extension to include solids}\n\n%z = beta*Y + (1-beta-beta_\\scomp)*x + beta_\\scomp\n%y = Kx\n% sum(y) = 1\n% sum(x) = 1\n% phi_\\scomp - phi_g*y = 0\n\nSince $\\beta$ will vary along the saturation lines, it must be included as a variable. The same applies for $\\beta_\\sol$. Typically one of these will be fixed to zero when mapping a three-phase line, while the other is a variable.\n\nThe equation set must be extended with the following equilibrium relation:\n\\begin{equation}\n  \\label{eq:soleq}\n   g_{n+3} = \\ln \\varphi^\\vap_\\scomp + \\ln Y_\\scomp - \\ln \\varphi^\\sol .\n\\end{equation}\n\nEarlier it was assumed, $\\beta_\\vap = \\beta$, and $\\beta_\\liq = 1-\\beta$. There are three options when extending to include solids, (1) to continue to assume this within the vapor-liquid part of the mixture, or (2) to use $\\beta_\\liq = 1-\\beta-\\beta_\\sol$, or (3) to introduce a new variable for $\\beta_\\liq$. Since we typically need to specify one of the phase fractions to be zero, only the first and the last option can be used.\n\nFor the first option, the corrected fluid composition, $Z_i^*$, becomes,\n\\begin{equation}\n  Z_i^* = \\begin{cases}\n    \\frac{Z_i - \\beta_\\sol}{1-\\beta_\\sol},& \\text{if } i = s\\\\\n    \\frac{Z_i}{1-\\beta_\\sol},            & \\text{otherwise}.\n\\end{cases}\n\\label{eq:z_mod}\n\\end{equation}\n\nFor the third option, the new mass balance for the solid component, $Z_\\scomp$, becomes:\n\\begin{equation}\n  Z_i = \\begin{cases}\n    \\beta_\\vap Y_i + \\beta_\\liq X_i + \\beta_\\sol,& \\text{if } i = s\\\\\n    \\beta_\\vap Y_i + \\beta_\\liq X_i,            & \\text{otherwise}.\n\\end{cases}\n\\end{equation}\nEquation \\ref{eq:G} for the fluid equilibrium then changes form completely. To simplify, it is therefore suggested to use the first approach.\n\nSubstituting Equation \\ref{eq:z_mod} into equations \\ref{eq:comp1} we get,\n\\begin{equation}\n  X_i = \\begin{cases}\n    \\frac{Z_i - \\beta_\\sol}{\\left(1-\\beta_\\sol\\right)\\left(1-\\beta+\\beta K_\\scomp\\right)},& \\text{if } i = s\\\\\n    \\frac{Z_i}{\\left(1-\\beta_\\sol\\right)\\left(1-\\beta+\\beta K_\\scomp\\right)},            & \\text{otherwise}.\n\\end{cases}\n \\end{equation}\nTo calculate $\\vektor{Y}$, we still use, $Y_i=K_iX_i$.\n% \\begin{align}\n%   X_\\scomp &= \\frac{Z_\\scomp -\\beta_\\sol}{1-\\beta-\\beta_\\sol+\\beta K_\\scomp},\\\\\n%   Y_\\scomp &= K_\\scomp\\frac{Z_\\scomp -\\beta_\\sol}{1-\\beta-\\beta_\\sol+\\beta K_\\scomp}.\n% \\end{align}\nTo calculate the real gas ($\\tilde{\\beta}_\\vap$) and liquid ($\\tilde{\\beta}_\\liq$) phase fractions, the mass balance for the solid component yields,\n\\begin{align}\n  \\tilde{\\beta}_\\vap &= \\frac{Z_{is} - X_{is} +\n    \\beta_\\sol \\left( X_{is} - 1\\right)}{Y_{is}-X_{is}} \\\\\n  \\tilde{\\beta}_\\liq &= 1 - \\tilde{\\beta}_\\vap - \\beta_\\sol\n\\end{align}\n\\subsection{Additional differentials}\n\\begin{equation}\n   \\pd{X_i}{\\beta} = -\\frac{Z_i^*\\left(K_i - 1\\right)}{\\left(1-\\beta+\\beta K_i\\right)^2} = -\\frac{X_i\\left(Y_i - X_i\\right)}{Z_i^*}.\n\\end{equation}\n\n\\begin{equation}\n   \\pd{Y_i}{\\beta} = -\\frac{K_i Z_i^* \\left(K_i - 1\\right)}{\\left(1-\\beta+\\beta K_i\\right)^2} = -\\frac{Y_i\\left(Y_i - X_i\\right)}{Z_i^*}.\n\\end{equation}\n\n\\begin{equation}\n  \\pd{X_i}{\\beta_\\sol} = \\begin{cases}\n    \\frac{X_i}{\\left(1-\\beta_\\sol\\right)}\\left(1-\\frac{1}{Z_i^*}\\right),& \\text{if } i = s\\\\\n    \\frac{X_i}{\\left(1-\\beta_\\sol\\right)},            & \\text{otherwise}.\n\\end{cases}\n \\end{equation}\n\n\\begin{equation}\n   \\pd{Y_i}{\\beta_\\sol} = K_i\\pd{X_i}{\\beta_\\sol}.\n\\end{equation}\n\n\\begin{align}\n   \\pd{g_i}{\\beta} &= -\\overset{n}{\\underset{j=1}{\\sum}}\\left(\\pd{\\ln \\varphi^\\vap_i}{Y_j}Y_j - \\pd{\\ln \\varphi^\\liq_i}{X_j}X_j\\right)\\frac{\\left(Y_i - X_i\\right)}{Z_i^*}\\\\\n   \\pd{g_{n+1}}{\\beta} &= \\overset{n}{\\underset{i=1}{\\sum}}\\left(K_i-1\\right)\\pd{X_i}{\\beta}.\n\\end{align}\nThe differential with regards to $\\beta_\\sol$ will have the same\nshape.\n\n\\begin{equation}\n   \\pd{g_{n+3}}{\\ln K_i} = \\left(\\pd{\\ln\n       \\varphi^\\vap_\\scomp}{Y_i} +\n     \\frac{\\delta_{is}}{Y_\\scomp}\\right) \\pd{Y_i}{\\ln K_j} = \\left(\\pd{\\ln\n       \\varphi^\\vap_\\scomp}{Y_i} +\n     \\frac{\\delta_{is}}{Y_\\scomp}\\right) \\left(1-\\beta\\right)\\frac{Y_iX_i}{Z_i^*}.\n\\end{equation}\n\n\\begin{equation}\n   \\pd{g_{n+3}}{\\ln T} = T\\left(\\pd{\\ln \\varphi^\\vap_\\scomp}{T} - \\pd{\\ln \\varphi^\\sol}{T}\\right).\n\\end{equation}\n\n\\begin{equation}\n   \\pd{g_{n+3}}{\\ln P} = P\\left(\\pd{\\ln \\varphi^\\vap_\\scomp}{P} - \\pd{\\ln \\varphi^\\sol}{P}\\right).\n\\end{equation}\n\n\\begin{equation}\n   \\pd{g_{n+3}}{\\beta} = \\overset{n}{\\underset{i=1}{\\sum}}\\pd{\\ln \\varphi^\\vap_\\scomp}{Y_i}\\pd{Y_i}{\\beta} + \\frac{1}{Y_\\scomp}\\pd{Y_\\scomp}{\\beta}.\n\\end{equation}\n\nThe differential with regards to $\\beta_\\sol$ will have the same shape.\n\\subsection{Liquid-solid or vapor-solid equilibrium}\nOne equilibrium and on specification equation is required,\n\\begin{align}\n   g_{1} &= \\ln \\varphi^\\vap_\\scomp + \\ln Y_\\scomp - \\ln \\varphi^\\sol,\\\\\n   g_{2} &= S - S_\\spec \\label{eq:spec_eq_ls}.\n\\end{align}\nVariables:\n\\begin{equation}\n  \\label{eq:W_ls}\n  \\vektor{W} = \\begin{pmatrix}\n    \\ln T \\\\\n    \\ln P\n  \\end{pmatrix}\n\\end{equation}\nOne of the variables must be specified, and $\\beta_\\sol$ must be set. The fluid mole fractions then become,\n\\begin{equation}\n  Y_i = \\begin{cases}\n    \\frac{Z_\\scomp - \\beta_\\sol}{1-\\beta_\\sol}, & \\text{if } i = s\\\\\n    \\frac{Z_i}{1-\\beta_\\sol}, & \\text{otherwise}.\n  \\end{cases}\n\\end{equation}\n\nFor $Y_i$ the differentials are,\n\\begin{equation}\n  \\pd{Y_i}{\\beta_\\sol} = \\begin{cases}\n    \\frac{Y_i - 1}{1-\\beta_\\sol}, & \\text{if } i = s\\\\\n    \\frac{Y_i}{1-\\beta_\\sol}, & \\text{otherwise}.\n  \\end{cases}\n\\end{equation}\nUsing these the other differentials are simple.\n\n\\section{Illustrations}\nFigure \\ref{fig:envelope} show an example of the phase diagram of a\nmulticomponent mixture with approximately \\SI{91}{\\percent} \\ce{CO2}.\n\\begin{figure}[ht]\n  \\centering\n  \\includegraphics[width=0.6\\textwidth]{envelope}\n  \\caption{Illustration of a multicomponent mixture\n    (\\ce{CO2}-\\ce{H2}-\\ce{N2}-\\ce{O2}-\\ce{CH4}) with all its phase\n    areas. The blue and the black line encircle the vapor-liquid\n    region. Above the red line and left of the orange line we have the\n    vapor solid region. The green line is the solid appearance line in\n    from the liquid phase. Right of the orange and left of the black\n    and brown line there is a vapor-liquid-solid line. Between the\n    purple and green line there is a liqid solid region. The mole\n    fraction vector of the mixture is\n    $\\left[0.9094,0.0103,0.0402,0.0184,0.0217\\right]$}.\n  \\label{fig:envelope}\n\\end{figure}\n\n\\section{Two-component system}\nFor a two-component system there is no three phase area, only a three\nphase line. This means, that at the same temperature and pressure,\nseveral equilibrium states can be found. The state differ only in\ndifferent solid fraction and different fluid phase fractions. That is;\nwhile dry-ice freeze, the phase compositions are constant. The\nchemical potential of the component freezing then remain constant, as\nseen from Equation \\ref{eq:soleq}.\n\nThis is illustrated in Figure \\ref{fig:envelope2}. Figure\n\\ref{fig:envelope2} show the phase diagram of a mixture containing\n\\SI{87.5}{\\percent} \\ce{CO2} and \\SI{12.5}{\\percent} \\ce{N2}.\n\n\\begin{figure}[ht]\n  \\centering\n  \\includegraphics[width=0.6\\textwidth]{envelope2}\n  \\caption{Illustration of a binary mixture (\\ce{CO2}-\\ce{N2}) with all\n    its phase areas. The blue and the black line encircle the\n    vapor-liquid region. Above the red line and left of the orange\n    line we have the vapor solid region. The green line is the solid\n    appearance line in from the liquid phase. It is seen that there is\n    no three phase area, only a line, as the orange and black line\n    coincide. The mole fraction vector of the mixture is\n    $\\left[0.875,0.125\\right]$}.\n  \\label{fig:envelope2}\n\\end{figure}\n\nThe Gibbs' phase rule, state that the degree of freedom ($F$) is given\nas number of components ($C$) and number of phases ($P$),\n\\begin{equation}\n  F = C - P + 2.\n\\end{equation}\nFor three phases and two components, the degree of freedom\nbecome 1. That is; the it is not possible to change the temperature\nindependently of the pressure, giving a three-phase line in\ntemperature-pressure space.\n\nApplying the same rule to pure \\ce{CO2}, no degree of freedom is seen\nfor the three-phase region, giving a triple point in\ntemperature-pressure space.\n\n% \\clearpage\n% \\bibliographystyle{plain}\n% \\bibliography{../thermopack}\n\n\\end{document}\n", "meta": {"hexsha": "f0d8bfe2a0c1a25b8c2f025d64544b88b6c726e5", "size": 16406, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/memo/envelopes/envelopes.tex", "max_stars_repo_name": "SINTEF/Thermopack", "max_stars_repo_head_hexsha": "63c0dc82fe6f88dd5612c53a35f7fbf405b4f3f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2020-10-14T07:51:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T04:59:23.000Z", "max_issues_repo_path": "doc/memo/envelopes/envelopes.tex", "max_issues_repo_name": "SINTEF/Thermopack", "max_issues_repo_head_hexsha": "63c0dc82fe6f88dd5612c53a35f7fbf405b4f3f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2020-10-26T11:43:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T22:06:30.000Z", "max_forks_repo_path": "doc/memo/envelopes/envelopes.tex", "max_forks_repo_name": "SINTEF/Thermopack", "max_forks_repo_head_hexsha": "63c0dc82fe6f88dd5612c53a35f7fbf405b4f3f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2020-10-27T13:04:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T04:59:24.000Z", "avg_line_length": 38.6023529412, "max_line_length": 431, "alphanum_fraction": 0.6738388394, "num_tokens": 5918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3033028244009829}}
{"text": "\\documentclass[fleqn]{goose-article}\n\n\\title{Energy barrier}\n\\author{Tom de Geus}\n\\hypersetup{pdfauthor={T.W.J. de Geus}}\n\n\\begin{document}\n\n\\maketitle\n\n\\section*{Protocol}\n\nThe protocol is as follows.\n\\begin{enumerate}\n    \\item An element is selected for triggering\n    (in the example below chosen in the center of the system).\n    Its location is denoted by $\\vec{r}'$.\n\n    \\item A perturbation around a stress- and strain-free configuration is considered.\n    To this end, the selected element (only) is subjected to an eigen stress\n    $\\bm{\\sigma}'$.\n    The corresponding equilibrium configuration then constitutes to\n    the perturbation that will be used.\n    It is characterised by the stress field $\\delta \\vec{u} (\\vec{r})$, and corresponding\n    stress $\\delta \\bm{\\sigma} (\\vec{r})$\n    and strain $\\delta \\bm{\\varepsilon} (\\vec{r})$ fields.\n\n    \\item Two types of perturbations are considered:\n    \\begin{itemize}\n        \\item Simple shear:\n        $\\bm{\\sigma}' = \\bm{\\sigma}'_s = \\vec{e}_x \\vec{e}_y + \\vec{e}_x \\vec{e}_y$.\n        Gives: $\\delta \\vec{u}_s (\\vec{r})$, $\\delta \\bm{\\sigma}_s (\\vec{r})$, and\n        $\\delta \\bm{\\varepsilon}_s (\\vec{r})$.\n\n        \\item Pure shear:\n        $\\bm{\\sigma}' = \\bm{\\sigma}'_p = \\vec{e}_x \\vec{e}_x - \\vec{e}_y \\vec{e}_y$.\n        Gives: $\\delta \\vec{u}_p (\\vec{r})$, $\\delta \\bm{\\sigma}_p (\\vec{r})$, and\n        $\\delta \\bm{\\varepsilon}_p (\\vec{r})$.\n    \\end{itemize}\n\n    For the triggered element the strain (and) stress are empirically\n    of the following structure:\n    \\begin{itemize}\n        \\item Simple shear perturbation:\n        $\\delta \\bm{\\varepsilon}_s (\\vec{r}') = \\delta \\gamma (\\vec{e}_x \\vec{e}_y + \\vec{e}_x \\vec{e}_y)$\n        \\item Pure shear perturbation:\n        $\\delta \\bm{\\varepsilon}_p (\\vec{r}') = \\delta \\mathcal{E} (\\vec{e}_x \\vec{e}_x - \\vec{e}_y \\vec{e}_y)$\n    \\end{itemize}\n\n    \\item A perturbation $\\Delta \\vec{u}(\\vec{r}) = s \\delta \\vec{u}_s (\\vec{r}) + p \\delta \\vec{u}_p (\\vec{r})$\n    is then applied such that the yield surface is reached in the triggered element in such\n    a way that the change in potential energy introduced by the perturbation is minimal.\n\n\\end{enumerate}\n\n\\begin{figure}[htp]\n    \\centering\n    \\captionsetup[subfigure]{justification=centering}\n    \\begin{minipage}[t]{.49\\textwidth}\n        \\centering\n        \\includegraphics[width=\\textwidth]{perturbation_simple-shear_pos.pdf}\n        \\subcaption{\n            Simple shear:\n            $\\delta \\vec{u}_s (\\vec{r})$\n        }\n        \\label{fig:perturbation:simple-shear:pos}\n    \\end{minipage}\n    \\hfill\n    \\begin{minipage}[t]{.49\\textwidth}\n        \\centering\n        \\includegraphics[width=\\textwidth]{perturbation_pure-shear_pos.pdf}\n        \\subcaption{\n            Pure shear:\n            $\\delta \\vec{u}_p (\\vec{r})$\n        }\n        \\label{fig:perturbation:pure-shear:pos}\n    \\end{minipage}\n    \\\\\n    \\begin{minipage}[t]{.49\\textwidth}\n        \\centering\n        \\includegraphics[width=\\textwidth]{perturbation_simple-shear_neg.pdf}\n        \\subcaption{\n            Simple shear:\n            $- \\delta \\vec{u}_s (\\vec{r})$\n        }\n        \\label{fig:perturbation:simple-shear:neg}\n    \\end{minipage}\n    \\hfill\n    \\begin{minipage}[t]{.49\\textwidth}\n        \\centering\n        \\includegraphics[width=\\textwidth]{perturbation_pure-shear_neg.pdf}\n        \\subcaption{\n            Pure shear:\n            $- \\delta \\vec{u}_p (\\vec{r})$\n        }\n        \\label{fig:perturbation:pure-shear:neg}\n    \\end{minipage}\n    \\caption{\n        Perturbation modes.\n        The shown colour is the energy change resulting from the perturbation.\n    }\n    \\label{fig:perturbation}\n\\end{figure}\n\n\\begin{figure}[htp]\n    \\centering\n    \\begin{minipage}[t]{.49\\textwidth}\n        \\centering\n        \\includegraphics[width=\\textwidth]{perturbation_phase-diagram_energy.pdf}\n    \\end{minipage}\n    \\hfill\n    \\begin{minipage}[t]{.49\\textwidth}\n        \\centering\n        \\includegraphics[width=\\textwidth]{perturbation_phase-diagram_energy-contour.pdf}\n    \\end{minipage}\n    \\caption{\n        Change of internal energy, $\\Delta E$, for a perturbation:\n        $\\Delta \\vec{u}(\\vec{r}) = s \\delta \\vec{u}_s (\\vec{r}) + p \\delta \\vec{u}_p (\\vec{r})$.\n        A contour plot is also shown.\n    }\n    \\label{fig:energy}\n\\end{figure}\n\n\\begin{figure}[htp]\n    \\centering\n    \\captionsetup[subfigure]{justification=centering}\n    \\begin{minipage}[t]{.49\\textwidth}\n        \\centering\n        \\includegraphics[width=\\textwidth]{perturbation_phase-diagram_sig.pdf}\n        \\subcaption{\n            Equivalent stress.\n        }\n        \\label{fig:phase-diagram:sig}\n    \\end{minipage}\n    \\hfill\n    \\begin{minipage}[t]{.49\\textwidth}\n        \\centering\n        \\includegraphics[width=\\textwidth]{perturbation_phase-diagram_eps.pdf}\n        \\subcaption{\n            Equivalent strain.\n        }\n        \\label{fig:phase-diagram:eps}\n    \\end{minipage}\n    \\caption{\n        Resulting\n        \\subref{fig:phase-diagram:sig} equivalent stress and\n        \\subref{fig:phase-diagram:eps} equivalent strain\n        for a perturbation:\n        $\\Delta \\vec{u}(\\vec{r}) = s \\delta \\vec{u}_s (\\vec{r}) + p \\delta \\vec{u}_p (\\vec{r})$.\n    }\n    \\label{fig:phase-diagram}\n\\end{figure}\n\n\\clearpage\n\n\\section*{Exploring the yield surface}\n\n\\paragraph{Yield surface}\n\nInitially the strain deviator in the triggered element reads\n\\begin{equation}\n    \\bm{\\varepsilon}_\\mathrm{d}(\\vec{r}') =\n    \\begin{bmatrix}\n        \\mathcal{E} & \\gamma \\\\\n        \\gamma & - \\mathcal{E}\n    \\end{bmatrix}\n\\end{equation}\nAfter triggering the strain deviator is\n\\begin{equation}\n    \\bm{\\varepsilon}_\\mathrm{d}^*(\\vec{r}') =\n    \\begin{bmatrix}\n        \\mathcal{E} + p \\delta \\mathcal{E} & \\gamma + s \\delta \\gamma \\\\\n        \\gamma + s \\delta \\gamma & - \\mathcal{E} - p \\delta \\mathcal{E}\n    \\end{bmatrix}\n\\end{equation}\nTo reach the yield surface one thus needs to solve\n\\begin{equation}\n    (\\mathcal{E} + p \\delta \\mathcal{E})^2 +\n    (\\gamma + s \\delta \\gamma)^2 =\n    \\varepsilon_y^2\n\\end{equation}\nfor $(s, p)$ (with $\\varepsilon_y$ the relevant yield strain).\n\n\\paragraph{Change of energy}\n\nThe energy in the system reads\n\\begin{equation}\n    E = \\frac{1}{2} \\int_\\Omega\n        \\bm{\\sigma}(\\vec{r}) : \\bm{\\varepsilon}(\\vec{r})\n    \\; \\mathrm{d} \\Omega\n\\end{equation}\nAfter triggering:\n\\begin{equation}\n    E^* = \\frac{1}{2} \\int_\\Omega\n        (\\bm{\\sigma}(\\vec{r}) + \\Delta \\bm{\\sigma}(\\vec{r})) :\n        (\\bm{\\varepsilon}(\\vec{r}) + \\Delta \\bm{\\varepsilon}(\\vec{r}))\n    \\; \\mathrm{d} \\Omega\n\\end{equation}\nwhere\n$\\Delta \\bm{\\sigma}(\\vec{r}) = s \\delta \\bm{\\sigma}_s(\\vec{r}) + p \\delta \\bm{\\sigma}_p(\\vec{r})$\nand\n$\\Delta \\bm{\\varepsilon}(\\vec{r}) = s \\delta \\bm{\\varepsilon}_s(\\vec{r}) + p \\delta \\bm{\\varepsilon}_p(\\vec{r})$.\nIt is straightforward to show that the change of energy\n\\begin{equation}\n    \\Delta E = E^* - E =\n    \\int_\\Omega\n        \\big(\\bm{\\sigma}(\\vec{r}) + \\tfrac{1}{2} \\Delta \\bm{\\sigma}(\\vec{r}) \\big) :\n        \\Delta \\bm{\\varepsilon}(\\vec{r})\n    \\; \\mathrm{d} \\Omega\n\\end{equation}\nwhereby in practice integration is performed numerically, e.g.\\\n\\begin{equation}\n    \\Delta E = E^* - E =\n    \\sum\\limits_q\n        \\delta \\Omega_q \\;\n        \\big(\\bm{\\sigma}_q + \\tfrac{1}{2} \\Delta \\bm{\\sigma}_q \\big) :\n        \\Delta \\bm{\\varepsilon}_q\n\\end{equation}\n\n\\clearpage\n\n\\section*{Example}\n\nTwo examples are included:\nA homogeneous medium that is subjected to shear in \\cref{fig:example:shear}, and\nthe same problem additionally subjected to a vertical perturbation\nof the top and bottom boundaries \\cref{fig:example:prestress}.\n\n\\begin{figure}[htp]\n    \\centering\n    \\captionsetup[subfigure]{justification=centering}\n    \\begin{minipage}[t]{.40\\textwidth}\n        \\centering\n        \\includegraphics[width=\\textwidth]{example_shear_config.pdf}\n        \\subcaption{Initial configuration.}\n    \\end{minipage}\n    \\hspace{0.01\\textwidth}\n    \\begin{minipage}[t]{.40\\textwidth}\n        \\centering\n        \\includegraphics[width=\\textwidth]{example_shear_config-perturbed.pdf}\n        \\subcaption{After perturbation.}\n    \\end{minipage}\n    \\\\\n    \\begin{minipage}[t]{.31\\textwidth}\n        \\centering\n        \\includegraphics[width=\\textwidth]{example_shear_phase-diagram_eps.pdf}\n        \\subcaption{$\\varepsilon$}\n    \\end{minipage}\n    \\hfill\n    \\begin{minipage}[t]{.31\\textwidth}\n        \\centering\n        \\includegraphics[width=\\textwidth]{example_shear_phase-diagram_energy.pdf}\n        \\subcaption{$\\Delta E$}\n    \\end{minipage}\n    \\hfill\n    \\begin{minipage}[t]{.31\\textwidth}\n        \\centering\n        \\includegraphics[width=\\textwidth]{example_shear_phase-diagram_energy-contour.pdf}\n        \\subcaption{$\\Delta E$}\n    \\end{minipage}\n    \\caption{\n        (a--b) Starting and perturbed configuration for a homogeneous sheared system.\n        (c--e) Phase diagram of a perturbation\n        $\\Delta \\vec{u}(\\vec{r}) = s \\delta \\vec{u}_s (\\vec{r}) + p \\delta \\vec{u}_p (\\vec{r})$\n        of the configuration in (a).\n        The perturbation is applied based on $(s, p)$ that lie on the yield surface and\n        that minimise the increase in potential\n        energy, as shown using a red dot.\n    }\n    \\label{fig:example:shear}\n\\end{figure}\n\n\\begin{figure}[htp]\n    \\centering\n    \\captionsetup[subfigure]{justification=centering}\n    \\begin{minipage}[t]{.40\\textwidth}\n        \\centering\n        \\includegraphics[width=\\textwidth]{example_prestress_config.pdf}\n        \\subcaption{Initial configuration.}\n    \\end{minipage}\n    \\hspace{0.01\\textwidth}\n    \\begin{minipage}[t]{.40\\textwidth}\n        \\centering\n        \\includegraphics[width=\\textwidth]{example_prestress_config-perturbed.pdf}\n        \\subcaption{After perturbation.}\n    \\end{minipage}\n    \\\\\n    \\begin{minipage}[t]{.31\\textwidth}\n        \\centering\n        \\includegraphics[width=\\textwidth]{example_prestress_phase-diagram_eps.pdf}\n        \\subcaption{$\\varepsilon$}\n    \\end{minipage}\n    \\hfill\n    \\begin{minipage}[t]{.31\\textwidth}\n        \\centering\n        \\includegraphics[width=\\textwidth]{example_prestress_phase-diagram_energy.pdf}\n        \\subcaption{$\\Delta E$}\n    \\end{minipage}\n    \\hfill\n    \\begin{minipage}[t]{.31\\textwidth}\n        \\centering\n        \\includegraphics[width=\\textwidth]{example_prestress_phase-diagram_energy-contour.pdf}\n        \\subcaption{$\\Delta E$}\n    \\end{minipage}\n    \\caption{\n        (a--b) Starting and perturbed configuration for a homogeneous sheared system.\n        (c--e) Phase diagram of a perturbation\n        $\\Delta \\vec{u}(\\vec{r}) = s \\delta \\vec{u}_s (\\vec{r}) + p \\delta \\vec{u}_p (\\vec{r})$\n        of the configuration in (a).\n        The perturbation is applied based on $(s, p)$ that lie on the yield surface and\n        that minimise the increase in potential\n        energy, as shown using a red dot.\n    }\n    \\label{fig:example:prestress}\n\\end{figure}\n\n\n\\end{document}\n", "meta": {"hexsha": "6515fdcb54dbdbc5c7cb6d50fa586744b2583881", "size": 10898, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "python-examples/trigger-barrier/readme.tex", "max_stars_repo_name": "tdegeus/FrictionQPotGooseFEM", "max_stars_repo_head_hexsha": "094d3dbe3a458b56203e5151157b26ca5bb6b497", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python-examples/trigger-barrier/readme.tex", "max_issues_repo_name": "tdegeus/FrictionQPotGooseFEM", "max_issues_repo_head_hexsha": "094d3dbe3a458b56203e5151157b26ca5bb6b497", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2020-10-16T14:15:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T16:56:17.000Z", "max_forks_repo_path": "python-examples/trigger-barrier/readme.tex", "max_forks_repo_name": "tdegeus/FrictionQPotGooseFEM", "max_forks_repo_head_hexsha": "094d3dbe3a458b56203e5151157b26ca5bb6b497", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1630094044, "max_line_length": 113, "alphanum_fraction": 0.6286474582, "num_tokens": 3401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283035, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.3032820817337032}}
{"text": "\\documentclass{article}\n\n\\usepackage{mathrsfs, amsmath}    % need for subequations\n\\usepackage{verbatim}   % useful for program listings\n\\usepackage{color}      % use if color is used in text\n\\usepackage{hyperref}   % use for hypertext links, including those to external documents and URLs\n\n\\allowdisplaybreaks\n\n\\begin{document}\n\\section{Decision Trees}\nDecision tree learning is a type of supervised learning algorithm, whose goal is to take an object $O$ and assign it a prediction $y$ based on a vector of $M$ features $x_m$. The prediction $y$ can be drawn from a set of discrete classes (classification tree) or a set of continuous numbers (regression tree). A decision tree is a type of graph, in which each node represents an element of the prediction process. Assigned to each node is a feature $x_m$. The local decision process at each node is to decide which child node to travel to based on the value of $x_m$. The terminal nodes of the tree are known as leafs. The leafs are labeled with the possible values of the prediction $y$. Thus by traversing the decision tree from the root node to a terminal leaf each object $O$ can be assigned a prediction. The question becomes how do we train a decision tree to best predict the properties of a given dataset? Another way of formulating this question is, when growing the tree, how can we decide which feature to select at each node for the decision process?\n\n\\begin{lstlisting}[language=Python]\n\nclass DecisionNode:\n    def __init__(self, feature_index=None, threshold=None,\n                 leaf_value=None, left_child=None, right_child=None):\n        self.feature_index = feature_index          \n        self.threshold = threshold          \n        self.leaf_value = leaf_value                  \n        self.left_child = left_child      \n        self.right_child = right_child\n\\end{lstlisting}\n\n\\section{Splitting Algorithms}\nThe id3 algorithm is used\n\\end{document}", "meta": {"hexsha": "3a22b4ed0725657b8775e139fd13fabf4a18c602", "size": 1928, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "writing/random_forest/random_forest.tex", "max_stars_repo_name": "mattdornfeld/mattdornfeld.github.io", "max_stars_repo_head_hexsha": "68247c6f8250bb2c8201ff0536a1eb82a99215ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "writing/random_forest/random_forest.tex", "max_issues_repo_name": "mattdornfeld/mattdornfeld.github.io", "max_issues_repo_head_hexsha": "68247c6f8250bb2c8201ff0536a1eb82a99215ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "writing/random_forest/random_forest.tex", "max_forks_repo_name": "mattdornfeld/mattdornfeld.github.io", "max_forks_repo_head_hexsha": "68247c6f8250bb2c8201ff0536a1eb82a99215ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 68.8571428571, "max_line_length": 1062, "alphanum_fraction": 0.7458506224, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.30328208173370313}}
{"text": "\\chapter{\\GP Performance Testing}\n\\label{chap:GPtesting}\n\nBefore installation all of the \\GP fibers were tested for throughput\nperformance using the Wisconsin Test Stand\n\\citep{Bershady04,Crause08,Eigenbrot12}. This stand is a\ndouble-differential imaging comparator. It consists of an input stage\nthat reimages an illuminated aperture through a controllable aperture\nat an intermediate pupil, and an output stage that consists of a\ncollimator that places the output pupil from the reimager or fiber\noutput onto a CCD detector. The experiment consists of measuring the\ninput beam differentially between a straight-through configuration and\nthe collimated fiber output. During the entire process the stability\nof the filtered input beam is monitored with a photo diode.\n\nTests were performed in the Johnson $V$ band with an input beam set to\nmatch the WIYN input beam of \\f6.3 without the 17\\% central\nobstruction of the telescope. The total throughput ($T_{\\rm tot}$) is\ndefined as all of the fiber-output light captured by the CCD (roughly\ncorresponding to \\f2.2, compared with the fiber numerical aperture\nof \\f2.3)\n%From 54mm L3 / 1024px * 0.024mm/px. NA = 0.22 and N = (2*arctan(NA))^-1\ndivided by the all of the light from the input beam captured by the\nsame CCD. This gives a good indication of the total transmission\nthrough the fiber, but ignores the effects of FRD on the delivered\nthroughput on the Bench Spectrograph due to the optical stops\ntherein. FRD describes the tendency for fibers to increase the entropy\nin an optical beam; light injected into a fiber at a particular\n$f$-ratio emerges at a smaller (faster) $f$-ratio \\citep{Angel77}.\n\nThe primary impact of FRD is from light loss from obstructions inside\nthe Bench Spectrograph as detailed in \\cite{Bershady04} and\n\\cite{Bershady05}.  With the upgrade \\citep{Bershady08} the low-order\ngratings and camera objective are sufficiently near the pupil and are\nof sufficient size that the limiting stop is from the collimator. The\ncamera objective does begin to vignette for off-axis fields point in\nwavelength and pseudo-slit position, but for operational purposes we\nconsider the on-axis field point for defining throughput losses due\nto FRD.  The collimator accepts light up to \\f4 with only minimal\nobstruction, and is completely unobstructed at \\f4.4, while the\noptical design (in terms of aberrations) is optimized for \\f5.\n\nTo characterize the impact of FRD on the the delivered throughput we\ndefine the quantity\n\\begin{equation}\n\\label{GPtesting:eq:T_FRD}\n  T_{\\mathrm{4}} = \\frac{F_{\\mathrm{out}}(f<\\f4)}{F_{\\mathrm{in}}(f<\\f6.3)},\n\\end{equation}\nwhere $F_\\mathrm{in}$ and $F_\\mathrm{out}$ represent flux from the the\ninput and fiber output beams, respectively. $T_4$ is essentially a\nthroughput measurement that accounts for the impact of FRD, and should\nbe representative of how the fibers will perform as part of the\nWIYN/Bench system.  We compute comparable quantities for output\nf-ratios of \\f4.5 and \\f5.  The throughput in each of these apertures,\nas well as the total throughput are included in Table\n\\ref{GPtesting:tab:GP_cal_full} as $T_{\\rm tot}$, $T_4$, $T_{4.4}$,\n$T_{5}$.\n\n\\begin{figure*}[htb]\n  \\centering\n  \\includegraphics[width=0.4\\textwidth]{Appendix/figs/gradpak_map.pdf}\n  \\includegraphics[width=0.4\\textwidth]{Appendix/figs/gradpak_L_map.pdf}\n\\vskip -0.25in\n\\caption[\\GP throughput and and FRD\nlosses]{\\label{GPtesting:fig:TL_FRD}\\fixspacing Maps of laboratory\n  measurements of the \\GP IFU performance. Throughput\n  ($T_{\\mathrm{FRD}}$, Equation \\ref{GPtesting:eq:T_FRD}) is shown in\n  the left-hand panel, while throughput losses ($L_{\\mathrm{FRD}}$,\n  Equation \\ref{GPtesting:eq:L_FRD}), is shown in the right-hand\n  panel. Performance values are given in the color scale at the top of\n  each panel.}\n\\end{figure*}\n\n\\begin{figure}\n  \\centering\n  \\includegraphics[width=0.8\\textwidth]{Appendix/figs/gradpak_facefig.pdf}\n  \\caption[\\GP face and polishing\n  detail]{\\label{GPtesting:fig:gradpak_face}\\fixspacing Detail of \\GP\n    fiber face\n    after polishing. The \\val{25.4}{\\mu m} (0\\farcs24) shims between each\n    block fiber-size group are visible in the central array. The hole\n    in the 5th fiber row from the bottom is a fiber that was broken\n    during polishing. The two sky-fiber groups, not shown to scale,\n    have locations marked in Figure \\ref{891_1:fig:GradPak}.  The\n    \\val{200}{\\mu m} (1\\farcs87) sky fibers are not visible in this image\n    due to imperfect illumination conditions at the slit end when this\n    picture was taken.}\n\\end{figure}\n\nFigure \\ref{GPtesting:fig:TL_FRD} contains throughput measurements for all of\nthe active \\GP fibers. Throughput losses caused by FRD are spatially\ncoherent and are larger on the top and left (North and East) side of\nthe IFU. This is likely due to surface scattering at the IFU face\n\\citep{Eigenbrot12} caused by an uneven polish. Figure\n\\ref{GPtesting:fig:gradpak_face} shows evidence of this variable polish in the\ntwo sky fiber groups; the SW sky group show significantly worse polish\nthan the NE group and has a correspondingly lower throughput. It is\nimportant to note that the FRD losses do \\emph{not} appear to be\ncaused by edge fibers pushing against the aluminum structure, as\nevidenced by the relatively high throughput seen on the left side of\nthe IFU. This is consistent with previous studies \\citep{Bershady04}\nthat suspected removal from an IFU molding fixture to be the primary\ncause of stress-induced FRD. Variations in polish quality appears to\nbe caused by detritus from the aluminum fixture.\n\nAs a check on the lab measurements of $T_4$ we also compare total\nfiber transmission recorded during the observing program described in\n\\S\\ref{891_1:sec:obs}. For these measurements a stitched dome flat (see\n\\S\\ref{891_1:sec:flats} was used as a good approximation of a uniform\nillumination at the fiber input. The total light transmitted by each\nfiber is computed by adding together all wavelength channels for each\nfiber after the data were spectrally extracted. Figure\n\\ref{GPtesting:fig:count_tput} shows are comparison between lab\n($T_4$) and on-telescope performance. ``Counts'' in this figure are\nfrom dome-flats combined as described in \\S\\ref{891_1:sec:flats}), and\nare the sum across all wavelengths of the extracted fiber traces.  As\nexpected from Figure \\ref{GPtesting:fig:TL_FRD} the highest\nthroughputs are found in the middle of the array, with a gradual drop\noff in performance towards the end of the slit. The right panel of\nFigure \\ref{GPtesting:fig:count_tput} shows a tight correlation\nbetween our lab measurements and the on-sky performance. This shows\nthat stresses during installation and the performance of the Bench\nSpectrograph only cause a $\\pm$5\\% rms modulation in the throughput\ncompared to what was measured in the lab.\n\nWe also measure the magnitude of FRD experienced by each\nfiber. Because FRD represents a scattering of input light to larger\noutput angles a comparison between throughput at two different output\n$f$-ratios gives an approximation of the severity of FRD in each\nfiber. We define\n\\begin{equation}\n\\label{GPtesting:eq:L_FRD}\n  L_\\mathrm{FRD} = 1 - \\frac{T_5}{T_4},\n\\end{equation}\nwhich quantifies the amount of light scattered to smaller $f$-ratios\n(larger angles) than \\f5 as a measure of the severity of FRD\nexperienced by each fiber.\n\n\\begin{figure*}\n  \\centering\n  \\includegraphics[width=\\textwidth]{Appendix/figs/gradpak_count_plots.pdf}\n  \\caption[\\GP on-bench throughput\n  performance]{\\label{GPtesting:fig:count_tput}\\fixspacing Left:\n    Relative fiber\n    transmission measured \\emph{in-situ} on the WIYN Bench\n    Spectrograph. Vertical lines demark transition between different\n    fiber sizes, as labeled. Right: Comparison between the\n    \\emph{in-situ} performance and $T_4$, as measured in the lab after\n    construction. The dashed line represents a linear regression to\n    the data with given correlation coefficient and scatter. Points\n    are color-coded by fiber number (slit position), and sky fibers\n    are marked with black squares.}\n\\end{figure*}\n\n\\begin{figure*}\n  \\centering\n  \\includegraphics[width=\\textwidth]{Appendix/figs/gradpak_Lplots.pdf}\n  \\caption[\\GP on-bench FRD\n  losses]{\\label{GPtesting:fig:FRD_loss}\\fixspacing Performance\n    metrics for \\GP. $L_\\mathrm{FRD}$ (Equation\n    \\ref{GPtesting:eq:L_FRD}) as a function of slit location (right)\n    and $T_4$ (transmission through an \\f4 aperture). Points are\n    color-coded by fiber number (slit position), and sky fibers are\n    marked with black squares.}\n\\end{figure*}\n\nTable \\ref{GPtesting:tab:GP_cal_full} contains measurements and Figure\n\\ref{GPtesting:fig:TL_FRD} shows a map of $L_\\mathrm{FRD}$ for each\n\\GP fiber. Figure \\ref{GPtesting:fig:FRD_loss} compares this quantity\nwith $T_4$. We find that fibers with low $T_4$ also tend to have high\nFRD losses ($L_\\mathrm{FRD}$), which indicates that FRD is a\nsignificant source of throughput loss in the \\GP and Bench\nSpectrograph system.  However this is relatively more pronounced for\nsmaller fiber sizes, as seen in the bifurcation in the right-hand\npanel of Figure \\ref{GPtesting:fig:FRD_loss}. Smaller fibers tend to\nsuffer from larger amounts of FRD, which may have been caused in \\GP\ndue to handling-induced stresses; these fibers were more likely to\nbend and tangle during construction.  The corollary is that lower\nthroughput in larger fibers isn't always the result of increased FRD.\n\nA complete set of measurements showing FRD losses as a function of\noutput $f$-ratio for each fiber can be found in the supplemental\nmaterials online at \\url{www.astro.wisc.edu/~eigenbrot/PAK}.\n\n% \\input{gradpak_lab_table}\n\n\\bibliographystyle{thesis}\n\\bibliography{ms_n891_paper}\n\n\\chapter{Grating Optimization}\n\\label{chap:grating}\n\n\\begin{figure*}[htb]\n\\centering\n\\vskip -1.25in\n  \\includegraphics[width=\\textwidth]{Appendix/figs/blaze_comp_land.pdf}\n\\vskip -1.25in\n\\caption[NGC 891 observing program grating\noptimization]{\\label{fig:grating_comp}\\fixspacing Efficiency\n  comparison between 400@4.2 and 600@10.1 gratings based on dome-flat\n  exposures using the same fibers, spectrograph camera-collimator\n  angle, and lamp temperature and intensity. Details are provided in\n  text. The top panel shows counts for each grating, while the bottom\n  panel shows their ratio and the prediction (line) based on the blaze\n  functions for idealized gratings.}\n\\end{figure*}\n\n% inferring camera fl. of 277.1mm,\n% 400@4.2 with alpha=21.8 covers 3597-7867 A; blaze wave is 3496 A.\n% 400@4.2 with alpha=21.53 covers 3372-7640 A; blaze wave is 3496 A.\n% 600@10.1  with alpha=24.33 covers 3795-6657; blaze wave is 5666 A.\n\n% Notes: effective camera fl at central waves of 5524 (g600) and 5733\n% (g400) is 277.1 mm compared to nominal value of 285 mm. This is due to\n% chromatic behvior of all-refractive camera and the ned to\n% significantly modify focus for good image-quality across our primary\n% bandpass.\n\n% The band-pass in the plots can be shifted redward or bluerward with a\n% commensurate shift (or offset) in the camera-collimator angle\n% w.r.t. what is plotted here.\n\nWe chose the 400@4.2 grating out of the library of gratings available\non the WIYN Bench Spectrograph because it allows us to capture\nsimultaneously spectra from Ca H\\&K to \\Ha while still maintaining\nrelatively high efficiency at the blue end of the spectrum.  To\noptimize our grating choice we compared the 400@4.2 grating to the\n600@10.1 grating. The latter provides a narrower wavelength range but\nat higher resolution, and, most importantly, the covered range is\nmarginally sufficient to meet our scientific objectives.  The 600@10.1\ngrating is often the ``go to'' grating for low-resolution programs\ncentered around \\val{5500}{\\AA}, particularly because it is the newest\nreflection grating and purportedly has the highest diffraction\nefficiency.\n\nFor testing during engineering time we compared the 400@4.2 grating\nset to 21.8$^{\\circ}$ and the 600@10.1 grating set to 24.33$^{\\circ}$,\nboth for a fixed camera-collimator angle of 30$^{\\circ}$ (this is the\nnominal configuration for low-order gratings).\\footnote{At these\n  wavelengths the effective camera focal-length for this\n  all-refractive compound optic is 277.1 mm not the nominal 285 mm\n  quoted in reference manuals.} These grating incidence angles gave\nwavelength ranges of \\val{3600}{\\AA}$< \\lambda <$ \\val{7867}{\\AA} and\n\\val{3794}{\\AA}$< \\lambda <$ \\val{6655}{\\AA}, respectively. The blue\nHydra cable (300 $\\mu$m core fibers) was used to observe dome flats\nilluminated with identical lamp intensity (and temperature)\nsettings. The dome lamps are known to be stable to better than 10\\%\nover a broad wavelength range. Although we were concerned that\ntemperature instability might be a factor at the blue end of our\nspectral range, our results are consistent with a highly stable\nillumination over our full spectral range.\n\nThe fiber flux in the dome-flat spectra was measured on the raw\ntwo-dimensional images before extraction. This was done in order to\nexclude defocus effects from the fractional flux extracted along the\ntrace in wavelength, and between the two grating configurations for\nwhich the detailed focus changes with wavelength are different.\nIdentical fibers and extraction regions were measured in both\nconfigurations. The regions account for a small lateral shift along\nthe slit due to a slight difference in the alignment angle between\ngratings orthogonal to the dispersion axis (this variance is just a\nmechanical tolerance in the grating mount). Taking advantage of the\nnumerous broken Hydra fibers, we identified well-separated\ntransmitting fibers that had ample separation for extracting ``on''\nand ``off'' signal regions (or apertures) at all wavelengths.  These\napertures were 10-11 pixels wide, and were adjacent on the CCD.  The\nresulting counts were differenced and then scaled for the\ncorresponding exposure time and linear dispersion. \n\nFigure \\ref{fig:grating_comp} shows the result of this experiment. It\nis evident from the top panel that the 400@4.2 has greater efficiency\ncompared to the 600@10.1 grating blueward of 4700\\AA. Since the\nspectrograph configurations were identical except for the gratings,\nunder the assumption that the dome-flat illumination was constant, the\nratio of the two curves is equivalent to the ratio of the grating\nblaze functions. As the bottom panel shows, this is very close to what\nwould be expected from simply computing the theoretical blaze\nfunctions for idealized versions of these two gratings. If anything,\nthe 400@4.2 appears to have 10\\% higher efficiency across all\nwavelengths than the idealized case.\n\n\\begin{figure*}[htb]\n  \\centering\n\\vskip -1.25in\n  \\includegraphics[width=\\textwidth]{Appendix/figs/blaze_plot_land.pdf}\n\\vskip -1.25in\n\\caption[Comparison of coverage and blaze for 400 and 600 l/mm\ngratings]{\\label{fig:spec_config}\\fixspacing Wavelength blaze and\n  coverage for the Bench Spectrograph and the 400 l/mm grating blazed\n  at 4.2 deg (top panel) and the 600 l/mm grating blazed at 10.1 deg\n  (bottom panel) as a function of grating incidence angle and\n  camera-collimator angle with the central wavelength held\n  constant. Upper and lower wavelength limits and the blaze peak are\n  marked with the red, blue, and thick-dashed lines, respectively. The\n  minimal desired wavelength range between the most blue-shifted Ca-K\n  line and most redshifted H$\\alpha$ lines (3937-6480\\AA; 300-800\n  \\kms) is shown as the grey shaded region The camera-collimator angle\n  is marked with the thin dotted line, and corresponds to the\n  right-hand vertical scale; the nominal value of 30 deg is marked\n  with a dot.}\n\\end{figure*}\n\nSince we are working with a bench-mounted spectrograph that in\nprinciple is highly configurable, we also considered if additional\nspectrograph layout modification might further optimize\nperformance. In particular, by altering both the grating (incidence)\nangle and the camera-collimator angle, it is possible to change the\nblaze wavelength while keeping the wavelength coverage on the detector\nroughly constant. The concept is illustrated in \\ref{fig:spec_config}.\nThe effect of increasing the camera-collimator angle for low-blaze\ngratings shifts the blaze wavelength to the blue. This is not\ndesirable for the 400@4.2 grating which already has a very blue blaze\nwavelength at the nominal camera-collimator angle of 30$^{\\circ}$, but\nthis is potentially relevant for the 600@10.1 grating. Unfortunately,\nsignificant shifts of the blaze wavelength require very large\ncamera-collimator angles that are both geometrically impractical on\nthe existing optical bench and lead to an unacceptable decrease in\nspectral coverage. The exercise does conclude that a larger\ncamera-collimator angle of roughly 40$^{\\circ}$ would be preferable\nfor the 600@10.1 grating, but its performance in the far blue would\nstill fall short of the 400@4.2 grating.\n", "meta": {"hexsha": "a62450d3084df9ff06936e0b3c643b6e384c7c37", "size": 16942, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Appendix/Appendix.tex", "max_stars_repo_name": "eigenbrot/eigenbrot-thesis", "max_stars_repo_head_hexsha": "113dfb95996777e2b36785d7ee80a824a671ab09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Appendix/Appendix.tex", "max_issues_repo_name": "eigenbrot/eigenbrot-thesis", "max_issues_repo_head_hexsha": "113dfb95996777e2b36785d7ee80a824a671ab09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Appendix/Appendix.tex", "max_forks_repo_name": "eigenbrot/eigenbrot-thesis", "max_forks_repo_head_hexsha": "113dfb95996777e2b36785d7ee80a824a671ab09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.6149068323, "max_line_length": 78, "alphanum_fraction": 0.7859166568, "num_tokens": 4454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.30327734761331754}}
{"text": "\\section{An Introduction to Isabelle}\n\\label{subsect.an.overview.of.isabelle}\n\nWe now provide a brief introduction to the key concepts and syntax of Isabelle/HOL.\nFamiliar readers may skip to Section~\\ref{sect.abstract.convergence}.\nA more detailed introduction can be found in the standard tutorial material~\\cite{DBLP:books/sp/NipkowK14}.\n\n\\paragraph{Syntax of expressions.}\n\nIsabelle/HOL is a logic with a strict, polymorphic, inferred type system.\n\\emph{Function types} are written $\\tau_1 \\Rightarrow \\tau_2$, and are inhabited by \\emph{total} functions, mapping elements of $\\tau_1$ to elements of $\\tau_2$.\nWe write $\\tau_1 \\times \\tau_2$ for the \\emph{product type} of $\\tau_1$ and $\\tau_2$, inhabited by pairs of elements of type $\\tau_1$ and $\\tau_2$, respectively.\nIn a similar fashion to Standard ML and OCaml, \\emph{type operators} are applied to arguments in reverse order, and therefore $\\tau\\ \\isa{list}$ denotes the type of lists of elements of type $\\tau$, and $\\tau\\ \\isa{set}$ denotes the type of mathematical (i.e., potentially infinite) sets of type $\\tau$.\nType variables are written in lowercase, and preceded with a prime: ${\\isacharprime}a \\Rightarrow {\\isacharprime}a$ denotes the type of a polymorphic identity function, for example.\n\\emph{Tagged union} types are introduced with the $\\isacommand{datatype}$ keyword, with constructors of these types usually written with an initial upper case letter.\n\nIn Isabelle/HOL's term language we write $\\isa{t} \\mathbin{::} \\tau$ for a \\emph{type ascription}, constraining the type of the term $\\isa{t}$ to the type $\\tau$.\nWe write $\\lambda{x}.\\: t$ for an anonymous function mapping an argument $\\isa{x}$ to $\\isa{t(x)}$, and write the application of term $\\isa{t}$ with function type to an argument $\\isa{u}$ as $\\isa{t\\ u}$, as usual.\nTerms of list type are introduced using one of two constructors: the empty list $[\\,]$ or `nil', and the infix operator $\\isa{\\#}$ which is pronounced ``cons'', and which prepends an element to an existing list.\nWe use $[t_1, \\ldots, t_n]$ as syntactic sugar for a list literal, and $\\isa{xs} \\mathbin{\\isacharat} \\isa{ys}$ to express the concatenation (appending) of two lists $\\isa{xs}$ and $\\isa{ys}$.\nWe write $\\{\\,\\}$ for the empty set, and use usual mathematical notation for set union, disjunction, membership tests, and so on: $\\isa{t} \\cup \\isa{u}$, $\\isa{t} \\cap \\isa{u}$, and $\\isa{x} \\in \\isa{t}$.\nWe write $t \\longrightarrow s$ for logical implication between formulae (terms of type $\\isa{bool}$).\nStrictly speaking Isabelle is a logical framework, providing a weak meta-logic within which object logics are embedded, including the Isabelle/HOL object logic that we use in this work.\nAccordingly, the implication arrow of Isabelle's meta-logic, $\\isa{t} \\Longrightarrow \\isa{u}$, is required in certain contexts over the object-logic implication arrow, $t \\longrightarrow s$, already introduced.\nHowever, for purposes of an intuitive understanding, the two forms of implication can be regarded as equivalent by the reader, with the requirement to use one over the other merely being an implementation detail of Isabelle itself.\nWe will sometimes use the shorthand ${\\isasymlbrakk}\\isa{H}_1{\\isacharsemicolon}\\ \\ldots{\\isacharsemicolon}\\ \\isa{H}_n{\\isasymrbrakk}\\ {\\isasymLongrightarrow}\\ C$ instead of iterated meta-logic implications, i.e., $H_1\\ {\\isasymLongrightarrow}\\ \\ldots\\ {\\isasymLongrightarrow}\\ H_n\\ {\\isasymLongrightarrow}\\ C$.\n\n\\paragraph{Definitions and theorems.}\n\nNew non-recursive definitions are entered into Isabelle's global context using the $\\mathbf{definition}$ keyword.\nRecursive functions are defined using the $\\mathbf{fun}$ keyword, and support pattern matching on their arguments.\nAll functions are total, and therefore every recursive function must be provably terminating.\nThe termination proofs in this work are generated automatically by Isabelle itself.\n\nInductive relations are defined with the $\\mathbf{inductive}$ keyword.\nFor example, the definition\n\\begin{isabelle}\n\\isacommand{inductive} only-fives\\ {\\isacharcolon}{\\isacharcolon}\\ {\\isachardoublequoteopen}nat\\ list\\ {\\isasymRightarrow}\\ bool{\\isachardoublequoteclose}\\ \\isakeyword{where}\\\\\n~~~~{\\isachardoublequoteopen}only-fives\\ {\\isacharbrackleft}{\\isacharbrackright}{\\isachardoublequoteclose}\\ {\\isacharbar}\\\\\n~~~~{\\isachardoublequoteopen}{\\isasymlbrakk}\\ only-fives\\ xs\\ {\\isasymrbrakk}\\ {\\isasymLongrightarrow}\\ only-fives {\\isacharparenleft}5\\#xs{\\isacharparenright}{\\isachardoublequoteclose}\n\\end{isabelle}\n\\noindent\nintroduces a new constant $\\isa{only-fives}$ of type $\\isa{nat list} \\Rightarrow \\isa{bool}$.\nThe two clauses in the body of the definition enumerate the conditions under which $\\isa{only-fives}\\ \\isa{xs}$ is true, for arbitrary $\\isa{xs}$: firstly, $\\isa{only-fives}$ is true for the empty list; and secondly, if you know that $\\isa{only-fives}\\ \\isa{xs}$ is true for some $\\isa{xs}$, then you can deduce that $\\isa{only-fives}\\ (5\\#\\isa{xs})$ (i.e., $\\isa{xs}$ prefixed with the number 5) is also true.\nMoreover, $\\isa{only-fives}\\ \\isa{xs}$ is true in no other circumstances---it is the \\emph{smallest} relation closed under the rules defining it.\nIn short, the clauses above state that $\\isa{only-fives}\\ \\isa{xs}$ holds exactly in the case where $\\isa{xs}$ is a (potentially empty) list containing only repeated copies of the natural number $5$.\n\nLemmas, theorems, and corollaries can be asserted using the $\\isacommand{lemma}$, $\\isacommand{theorem}$, and $\\isacommand{corollary}$ keywords, respectively.\nThere is no semantic difference between these keywords in Isabelle.\nFor example,\n\\begin{isabelle}\n~~~~\\isakeyword{assumes}\\ \\=\\kill\n\\isacommand{theorem} only-fives-concat{\\isacharcolon}\\\\\n~~~~\\isakeyword{assumes}\\>only-fives\\ xs \\isakeyword{and}\\ only-fives\\ ys\\\\\n~~~~\\isakeyword{shows}\\>only-fives (xs \\isacharat ys)\n\\end{isabelle}\n\\noindent\nconjectures that if $\\isa{xs}$ and $\\isa{ys}$ are both lists of fives, then their concatenation $xs \\mathbin{\\isacharat} ys$ is also a list of fives.\nIsabelle then requires that this claim be proved by using one of its proof methods, for example by induction.\nSome proofs can be automated, whilst others require the user to provide explicit reasoning steps.\nThe theorem is assigned a name, here $\\isa{only-fives-concat}$, so that it may be referenced in later proofs.\n\n\\paragraph{Locales.}\n\nLastly, we use \\emph{locales}---or local theories~\\cite{DBLP:conf/tphol/KammullerWP99,DBLP:conf/types/HaftmannW08}---extensively to structure the proof, as shown in Figure~\\ref{fig.proof.structure}.\nIn programming terms, Isabelle's locales may be thought of as an interface with associated laws that implementations must obey.\nIn particular, a declaration of the form\n\\begin{isabelle}\n~~~~\\isakeyword{assumes}\\ \\=\\kill\n\\isacommand{locale} semigroup =\\\\\n~~~~\\isakeyword{fixes}\\>f\\ {\\isacharcolon}{\\isacharcolon}\\ {\\isachardoublequoteopen}{\\isacharprime}a\\ {\\isasymRightarrow}\\ {\\isacharprime}a{\\isachardoublequoteclose}\\ {\\isasymRightarrow}\\ {\\isacharprime}a{\\isachardoublequoteclose}\\\\\n~~~~\\isakeyword{assumes}\\>{\\isachardoublequoteopen}f\\ x\\ (f\\ y\\ z)\\ =\\ f\\ (f\\ x\\ y)\\ z{\\isachardoublequoteclose}\n\\end{isabelle}\n\\noindent\nintroduces a locale, with a fixed, typed constant $\\isa{f}$, and a law asserting that $\\isa{f}$ is associative.\nFunctions and constants may now be defined, and theorems conjectured and proved, within the context of the $\\isa{semigoup}$ locale, i.e. definitions may be made ``generic'' in a semigroup.\nThis is indicated syntactically by writing $(\\isacommand{in}\\ \\isa{semigroup})$ before the name of the constant being defined, or the theorem being conjectured, at the point of definition or conjecture.\nAny function, constant, or theorem, marked in this way may make reference to $\\isa{f}$, or the fact that $\\isa{f}$ is associative.\n\\emph{Interpreting} a locale---such as $\\isa{semigroup}$ above---involves providing a concrete implementation of $\\isa{f}$ coupled with a proof that the concrete implementation satisfies the associated law, and is akin to implementing an interface.\nOnce interpreted, all functions, definitions, and theorems made within the $\\isa{semigroup}$ locale become available to use for that concrete implementation.\nLike interfaces, locales may be extended with new functionality, and may be specialised, by other ``sublocales'', forming a hierarchy.\n", "meta": {"hexsha": "b23146e965f40a29205fb5bb3df8a9bbb1ada5f2", "size": 8384, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/isabelle.tex", "max_stars_repo_name": "trvedata/crdt-isabelle", "max_stars_repo_head_hexsha": "8fde89bfb5e88acce000ac26e45f3f1cfe334e6e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 62, "max_stars_repo_stars_event_min_datetime": "2017-07-09T22:49:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T07:18:10.000Z", "max_issues_repo_path": "paper/isabelle.tex", "max_issues_repo_name": "trvedata/crdt-isabelle", "max_issues_repo_head_hexsha": "8fde89bfb5e88acce000ac26e45f3f1cfe334e6e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-04-29T14:33:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-17T09:22:42.000Z", "max_forks_repo_path": "paper/isabelle.tex", "max_forks_repo_name": "trvedata/crdt-isabelle", "max_forks_repo_head_hexsha": "8fde89bfb5e88acce000ac26e45f3f1cfe334e6e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-03-03T00:36:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T02:18:48.000Z", "avg_line_length": 102.243902439, "max_line_length": 410, "alphanum_fraction": 0.7591841603, "num_tokens": 2280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.3032773402500584}}
{"text": "\\documentclass[11pt]{amsart}\n\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{tikz}\n\\usepackage{fp}  % Prevents issues with arithmetic overflow.\n\\usepackage{pgfplots}\n\\usepackage{xcolor}\n\\usepackage[hidelinks]{hyperref}\n\\usepackage[section]{placeins}  % Prevents figure placement outside of section.\n\\usetikzlibrary{arrows, fixedpointarithmetic}\n\n\\newcommand{\\shaft}{\\mathrm{shaft}}\n\n\\definecolor{matlab1}{rgb}{0, 0.4470, 0.7410}\n\\definecolor{matlab2}{rgb}{0.8500, 0.3250, 0.0980}\n\\definecolor{matlab3}{rgb}{0.9290, 0.6940, 0.1250}\n\\definecolor{matlab4}{rgb}{0.4940, 0.1840, 0.5560}\n\\definecolor{matlab5}{rgb}{0.4660, 0.6740, 0.1880}\n\\definecolor{matlab6}{rgb}{0.3010, 0.7450, 0.9330}\n\\definecolor{matlab7}{rgb}{0.6350, 0.0780, 0.1840}\n\n\\title{MEKF}\n\\author{Makani Technologies LLC}\n\\date{October 2016\\; (DRAFT)}\n\n\\begin{document}\n\\maketitle\n\n\\section{States}\n\n\\begin{equation}\n  C_g^b \\approx \\hat C_g^b (I + [\\psi_{gb}^g]_{\\times})\n\\end{equation}\n\n\\begin{equation}\n  \\vec{b} \\approx \\hat{b} + \\delta \\vec{b}\n\\end{equation}\n\n\\section{Propagate}\n\n\\begin{equation}\n  \\delta \\vec{\\theta} = (\\vec{\\omega} - \\vec{b}) \\cdot \\Delta t\n\\end{equation}\n\n\\begin{equation}\n  \\delta q = q(\\delta \\vec{\\theta})\n\\end{equation}\n\n\\begin{equation}\n  {q_g^b}_{k|k-1} = {q_g^b}_{k-1|k-1} \\star \\delta q\n\\end{equation}\n\n\n\\begin{equation}\n  \\delta \\vec{x} = [\\delta \\vec{\\theta}, \\delta \\vec{b}]^T\n\\end{equation}\n\n\\begin{equation}\n  \\mathbf{F} = \\begin{bmatrix}\n    \\mathbf{C}(\\delta q) & \\Delta t \\cdot \\mathbf{I} \\\\\n    \\mathbf{0}           & \\mathbf{I} \\\\\n  \\end{bmatrix}\n\\end{equation}\n\n\\begin{equation}\n  \\mathbf{\\hat{x}}_{k+1|k} = \\mathbf{F} \\mathbf{\\hat{x}}_{k|k} +\n                             \\mathbf{B} \\mathbf{w}_{k}\n\\end{equation}\n\n\\begin{equation}\n  \\mathbf{P} = \\mathbf{U} \\mathbf{D} \\mathbf{U}^T\n\\end{equation}\n\n\\begin{equation}\n  \\mathbf{F}_k = \\frac{\\partial \\mathbf{f}}{\\partial \\mathbf{x}} \\bigg|_{\\mathbf{\\hat{x}}_{k-1|k-1}}\n\\end{equation}\n\n\\begin{eqnarray}\n  P_{k+1|k} &=& F_k P_{k|k} F_k^T + Q_k \\\\\n            &=& F_k U_{k|k} D_{k|k} U_{k|k}^T F_k^T + B Q_k B^T \\\\\n            &=& W_{k|k} D_{k|k} W_{k|k}^T\n\\end{eqnarray}\n\n\n\\begin{equation}\n  \\mathbf{D}_w = \\begin{bmatrix}\n    \\mathbf{D}_{k|k} & \\mathbf{0} \\\\\n    \\mathbf{0}       & \\mathbf{D}_q \\\\\n  \\end{bmatrix}\n\\end{equation}\n\n\\begin{equation}\n  \\mathbf{W} = [\\mathbf{F} \\mathbf{U}, \\mathbf{B}]\n\\end{equation}\n\n\n\\section{Correct}\n\n\\begin{equation}\n  h(\\mathbf{x}) \\equiv C_g^b \\vec{v}_g\n                \\approx \\hat{C}_g^b (\\mathbf{I} + \\delta \\vec{\\theta}_{\\times}) \\vec{v}_g\n\\end{equation}\n\n\\begin{equation}\n  \\frac{\\partial h}{\\partial \\delta \\vec{\\theta}} = -[\\hat{C}_g^b \\vec{v}_g]_{\\times}\n\\end{equation}\n\n\\end{document}\n", "meta": {"hexsha": "db3cd051bf1278a1f3ac78cdafd0ee66ce6c4adb", "size": 2689, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "documentation/control/estimator/mekf.tex", "max_stars_repo_name": "leozz37/makani", "max_stars_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1178, "max_stars_repo_stars_event_min_datetime": "2020-09-10T17:15:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:59:35.000Z", "max_issues_repo_path": "documentation/control/estimator/mekf.tex", "max_issues_repo_name": "leozz37/makani", "max_issues_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-22T05:22:35.000Z", "max_forks_repo_path": "documentation/control/estimator/mekf.tex", "max_forks_repo_name": "leozz37/makani", "max_forks_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 107, "max_forks_repo_forks_event_min_datetime": "2020-09-10T17:29:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T09:00:14.000Z", "avg_line_length": 24.4454545455, "max_line_length": 100, "alphanum_fraction": 0.6322052808, "num_tokens": 1141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3032773328867992}}
{"text": "\nThe \\eslmod{histogram} module is for collecting scores, fitting\nthem to expected distributions, and displaying them.\n\nThe histogram automatically reallocates its bins as data points\narrive, so the caller only needs to provide some initial guidance\nabout bin size and ``phase'' (offset of the bins relative to the real\nnumber line).  It accumulates counts in 64-bit unsigned integers, so\nit can handle over $10^19$ total counts.  Optionally (and provided\nthat the caller knows it has enough memory to support this), a\n``full'' histogram can be created and used to collect a sorted vector\nof raw (unbinned) values.\n\nVarious different ways of fitting histogram data to different sorts of\nexpected distributions are supported, with interfaces to all of\nEasel's statistical distribution modules. Data fitting is oriented\ntoward the case where the values are scores, with high scores being of\nthe most interest; for instance, routines for obtaining and fitting\nthe right (high-scoring) tail are provided, but not for the left tail.\n\nSeveral of the output functions output data as XY data files suitable\nfor input into the popular and freely available \\prog{xmgrace}\ngraphing program [\\url{http://plasma-gate.weizmann.ac.il/Grace/}].\n\nThe API for the \\eslmod{histogram} module is summarized in\nTable~\\ref{tbl:histogram_api}.\n\n\\begin{table}[hbp]\n\\begin{center}\n{\\small\n\\begin{tabular}{|ll|}\\hline\n    \\apisubhead{Collecting data in an \\ccode{ESL\\_HISTOGRAM}}\\\\\n\\hyperlink{func:esl_histogram_Create()}{\\ccode{esl\\_histogram\\_Create()}} & Create a new \\ccode{ESL\\_HISTOGRAM}.\\\\\n\\hyperlink{func:esl_histogram_CreateFull()}{\\ccode{esl\\_histogram\\_CreateFull()}} & A \\ccode{ESL\\_HISTOGRAM} to keep all data samples.\\\\\n\\hyperlink{func:esl_histogram_Destroy()}{\\ccode{esl\\_histogram\\_Destroy()}} & Frees a \\ccode{ESL\\_HISTOGRAM}.\\\\\n\\hyperlink{func:esl_histogram_Add()}{\\ccode{esl\\_histogram\\_Add()}} & Add a sample to the histogram.\\\\\n    \\apisubhead{Declarations about binned data, before fitting}\\\\\n\\hyperlink{func:esl_histogram_DeclareCensoring()}{\\ccode{esl\\_histogram\\_DeclareCensoring()}} & Collected data were left-censored.\\\\\n\\hyperlink{func:esl_histogram_DeclareRounding()}{\\ccode{esl\\_histogram\\_DeclareRounding()}} & Declare collected data were no more accurate than bins.\\\\\n\\hyperlink{func:esl_histogram_SetTail()}{\\ccode{esl\\_histogram\\_SetTail()}} & Declare only tail $>$ some threshold is considered \"observed\".\\\\\n\\hyperlink{func:esl_histogram_SetTailByMass()}{\\ccode{esl\\_histogram\\_SetTailByMass()}} & Declare only right tail mass is considered \"observed\".\\\\\n    \\apisubhead{Accessing raw data samples}\\\\\n\\hyperlink{func:esl_histogram_GetRank()}{\\ccode{esl\\_histogram\\_GetRank()}} & Retrieve n'th high score.\\\\\n\\hyperlink{func:esl_histogram_GetData()}{\\ccode{esl\\_histogram\\_GetData()}} & Retrieve vector of all raw scores.\\\\\n\\hyperlink{func:esl_histogram_GetTail()}{\\ccode{esl\\_histogram\\_GetTail()}} & Retrieve all raw scores above some threshold.\\\\\n\\hyperlink{func:esl_histogram_GetTailByMass()}{\\ccode{esl\\_histogram\\_GetTailByMass()}} & Retrieve all raw scores in right tail mass.\\\\\n    \\apisubhead{Setting expected counts}\\\\\n\\hyperlink{func:esl_histogram_SetExpect()}{\\ccode{esl\\_histogram\\_SetExpect()}} & Set expected counts for complete distribution.\\\\\n\\hyperlink{func:esl_histogram_SetExpectedTail()}{\\ccode{esl\\_histogram\\_SetExpectedTail()}} & Set expected counts for right tail.\\\\\n    \\apisubhead{Output}\\\\\n\\hyperlink{func:esl_histogram_Write()}{\\ccode{esl\\_histogram\\_Write()}} & Print a \"pretty\" ASCII histogram.\\\\\n\\hyperlink{func:esl_histogram_Plot()}{\\ccode{esl\\_histogram\\_Plot()}} & Output a histogram in xmgrace XY format.\\\\\n\\hyperlink{func:esl_histogram_PlotSurvival()}{\\ccode{esl\\_histogram\\_PlotSurvival()}} & Output $P(X>x)$ in xmgrace XY format.\\\\\n\\hyperlink{func:esl_histogram_PlotQQ()}{\\ccode{esl\\_histogram\\_PlotQQ()}} & Output a Q-Q plot in xmgrace XY format.\\\\\n\\hyperlink{func:esl_histogram_Goodness()}{\\ccode{esl\\_histogram\\_Goodness()}} & Evaluate fit between observed, expected. \\\\\n\\hline\n\\end{tabular}\n}\n\\end{center}\n\\caption{The \\eslmod{histogram} API.}\n\\label{tbl:histogram_api}\n\\end{table}\n\n\\subsection{Example of using the histogram API}\n\nThe example code below stores 10,000 samples from a Gumbel\ndistribution in a histogram, retrieves a vector containing the sorted\nsamples, fits a Gumbel distribution to that dataset, sets the expected\ncounts in the histogram, prints the observed and expected counts in an\nASCII histogram, and evaluates the goodness-of-fit.\n\n\\input{cexcerpts/histogram_example}\n\nSome points of interest:\n\n\\begin{itemize}\n\\item When the histogram is created, the arguments \\ccode(-100, 100, 0.5)\n      tell it to bin data into bins of width 0.5, initially\n      starting at -100 and ending at 100. This initialization\n      is described below (see ``Specifying binning of data values'').\n\n\\item Samples are collected one at a time with\n  \\ccode{esl\\_histogram\\_Add()}.\n\n\\item After the data have been collected in a \\emph{full} histogram, a\n   vector of sorted raw data values can be retrieved using functions\n   like \\ccode{esl\\_histogram\\_GetData()}, and used to fit parameters\n   of an expected distribution to the data.\n\n\\item In addition to the observed binned counts, you can optionally\n   set \\emph{expected} binned counts in the histogram by calling\n   \\ccode{esl\\_histogram\\_SetExpect()} and providing pointers\n   to an appropriate distribution function and its parameters.\n\n\\item The \\ccode{esl\\_histogram\\_Print()} function shows an ASCII text\n   representation of the observed counts (and expected counts, if set)\n   that looks a lot like FASTA's nice histogram output.\n\n\\item The \\ccode{esl\\_histogram\\_Goodness()} function compares the\n   observed and expected binned counts, and calculates two goodness of\n   fit tests: a G-test, and a $\\chi^2$ test.\n\\end{itemize}\n\n\n\\subsection{Specifying binning of data values}\n\nThe histogram collects data values into bins. When the histogram is\ncreated, the bin width and the relative offset of the bins is\npermanently set, and an initial range is allocated. \n\nFor example, the call \\ccode{esl\\_histogram\\_Create(-10, 10, 0.5)}\ncreates 40 bins of width 0.5 from -10 to 10, with the first bin\ncollecting scores from $-10 < x \\leq -9.5$, and the last bin\ncollecting scores $9.5 < x \\leq 10.0$.\n\nThe lower bound of the initialization permanently sets the relative\noffset of the bins. That is, \\ccode{esl\\_histogram\\_Create(-10, 10,\n0.5)} makes the first bin $-10 < x \\leq -9.5$, whereas\n\\ccode{esl\\_histogram\\_Create(-10.1, 9.9, 0.5)} makes the first bin\n$-10.1 < x \\leq -9.6$.\n\nAside from that, the initial range is only a suggestion. You can add\nany real-valued $x$ to the histogram. The histogram will silently\nreallocate itself to a wider range as needed.  The ability of a\nhistogram to store data is effectively unlimited. Up to $2^{64}-1$\n(more than $10^{19}$) counts can be collected. The histogram requires 16\nbytes of storage per bin, and the number of bins it allocates scales\nas $x_{\\mbox{max}} - x_{\\mbox{min}} / w$.\n\n\\subsection{Optional collection of raw data values: full histograms}\n\nNormally a histogram would store only binned counts, so it can\nefficiently summarize even very large numbers of samples.\n\nIn some cases it is useful to keep a list of the raw data values --\nfor instance, for more accurate parameter fitting to expected\ndistributions. This can be done by creating a ``full'' histogram with\n\\ccode{esl\\_histogram\\_CreateFull()} instead of\n\\ccode{esl\\_histogram\\_Create()}. (The example code above did this,\nbecause it did parameter fitting to the raw data.) After data have\nbeen collected in a full histogram, individual raw values or pointers\nto sorted arrays of raw values can be retrieved using the\n\\ccode{esl\\_histogram\\_Get*} functions.\n\nA full histogram may require much more memory: about 4 bytes per data\npoint. You may not want to use full histograms if your problem\ninvolves collecting many ($> 10^9$, say) data points.\n\n\n\n\\subsection{Different parameter fitting scenarios}\n\nBy default, the data you collect are assumed to be \\emph{complete}.\nYou observed all samples; if you fit to any expected distribution, the\nexpected distribution is assumed to describe the complete data; the\nparameters of the expected distribution are to be fitted to an array\nof the complete raw data samples; and any goodness of fit test is to\nbe applied to the complete data. This is the simplest, most obvious\ncase.\n\nOther situations may arise. In addition to complete data, Easel is\ndesigned to deal with four other cases:\n\n\\begin{enumerate}\n\\item The collected data are complete, and they are fit to a\n      distribution that describes the complete data, but parameter\n      fitting is done only in the right (highest-scoring) tail. This\n      makes parameter fitting focus on the most important,\n      high-scoring region of a score distribution, and ignore\n      low-scoring outliers.\n\n\\item The collected data are complete, but they are fit to a\n      distribution that only describes the right (highest scoring)\n      tail, and the goodness-of-fit test is only performed on that\n      tail. This case arises when we don't know the form of the\n      expected distribution for the complete data, but the tail\n      follows a predictable decay (an exponential tail, for example).\n\n\\item The collected data are left-censored such that no values $<\n      \\phi$ were recorded in the histogram, but the data are fit to a\n      complete distribution that predicts the probability even of the\n      censored (unobserved) values. Goodness of fit is only evaluated\n      in the observed data. (This case is what is actually meant by\n      left-censored data.)\n\n\\item The high-scoring right tail of the collected data are fit as the\n      \\emph{binned} counts in the histogram (not raw sample values) to\n      a distribution that describes the tail, such as an\n      exponential. This case becomes useful when the raw data values\n      have limited precision (because of rounding, for example), which\n      can cause numerical problems with parameter fitting to tails.\n      Another case where this is useful is when there are so many data\n      points that the data must be binned just as a matter of\n      practicality (not enough memory to hold a full histogram).\n\\end{enumerate}\n\nA variety of other situations can be dealt with by using different\ncombinations of the function calls that deal with these four cases.\n\n\n\\subsubsection{Focusing parameter fitting on the highest scores}\n\nAn example of focusing a Gumbel parameter fit on the right half of an\nobserved distribution:\n\n\\input{cexcerpts/histogram_example2}\n\nThe key differences from the complete data case are:\n\n\\begin{itemize}\n\\item Only the high-scoring 50\\% of the data samples are\n      retrieved, by calling \n      \\ccode{esl\\_histogram\\_GetTailByMass(h, 0.5, \\&xv, \\&n, \\&z)}.\n      This returns \\ccode{z}, the number of samples that \n      were \\emph{censored}.\n\n\\item These data are fit to a Gumbel distribution\n      as a \\emph{left-censored} dataset by calling\n      \\ccode{esl\\_gumbel\\_FitCensored(xv, n, z, xv[0], \\&mu, \\&lambda)}.\n\\end{itemize}\n\nThe expected counts and the goodness of fit tests are still evaluated\nfor the complete data, even though the fit was performed only on the\nhighest scores.\n\n\n\\subsubsection{Fitting to a tail distribution}\n\nAn example of fitting an exponential tail to the high-scoring 10\\% of\na Gumbel-distributed dataset:\n\n\\input{cexcerpts/histogram_example3}\n\nThe differences to note are:\n\n\\begin{itemize}\n\\item The tail is fit as if it is \\emph{complete} data as far\n      as the exponential distribution is concerned.\n\n\\item As a result, to use the exponential tail to predict expected\n      data, we have to keep in mind how much probability mass the tail\n      is supposed to predict (here, 10\\%), and that\n      is provided to\n      \\ccode{esl\\_histogram\\_SetExpectedTail()}, which specifically\n      calculates expected counts for a tail.\n\\end{itemize}\n\n\\subsubsection{Fitting left-censored data}\n\nFitting a Gumbel distribution to data that are \\emph{truly} left\ncensored looks a lot like the case where we extracted the high scoring\ndata for a censored fit:\n\n\\input{cexcerpts/histogram_example4}\n\n\\subsubsection{Fitting binned data to a tail distribution}\n\nNormally, you want to fit parameters to the actual individual data\nsamples, not to binned data, because you'll get more accurate results.\nAn exception can arise when the data samples have limited precision\nbecause they've been rounded off. Most distributions are not sensitive\nto this, but some tail densities are, especially those with\nsingularities ($P(X=x) \\rightarrow \\infty$) at their origin. In such a\ncase, a fit to binned data may be superior, especially if you can\nmatch the histogram's bins to the rounding procedure that was used.\n\nThe following code shows an example of fitting for samples that were\nalready rounded up to the nearest integer before adding them to the\nhistogram:\n\n\\input{cexcerpts/histogram_example5}\n\nIssues to note:\n\n\\begin{itemize}\n\\item The \\ccode{esl\\_histogram\\_Create(-100, 100, 1.0)} call\n      defined bins that exactly match the rounding procedure\n      defined by \\ccode{ceil(x)} -- all $x$ that are rounded\n      to the same value by \\ccode{ceil(x)} would also go in\n      the same bin of the histogram.\n\n\\item The \\ccode{esl\\_histogram\\_SetTailByMass()} function sets flags\n      in the histogram to demarcate the desired tail.  However,\n      because the data have been binned, and we can only define the\n      tail by a range of bins, it will generally be impossible to\n      match the requested tail mass with adequate accuracy; the actual\n      tail mass is $\\geq$ the requested tail mass. It is returned\n      to the caller, and it is the actual mass, not the requested mass,\n      that should be used when setting expected counts.\n\n\\item The \\ccode{esl\\_histogram\\_SetRounding()} declaration\n      sets a flag in the histogram that tells binned parameter\n      fitting functions that the origin of the fitted\n      density ($\\mu$) should be set at the lower bound of the smallest bin,\n      rather than the smallest raw data value observed in that \n      bin. \n\\end{itemize}\n\n\n", "meta": {"hexsha": "d8e39d3369b8905f49c7ce41a283ba75c4e2d134", "size": 14216, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "hmmer-3.3/easel/esl_histogram.tex", "max_stars_repo_name": "WooMichael/Project_Mendel", "max_stars_repo_head_hexsha": "ff572f7ce7f9beca148f7351cf34dbf11d670bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hmmer-3.3/easel/esl_histogram.tex", "max_issues_repo_name": "WooMichael/Project_Mendel", "max_issues_repo_head_hexsha": "ff572f7ce7f9beca148f7351cf34dbf11d670bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hmmer-3.3/easel/esl_histogram.tex", "max_forks_repo_name": "WooMichael/Project_Mendel", "max_forks_repo_head_hexsha": "ff572f7ce7f9beca148f7351cf34dbf11d670bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.3866666667, "max_line_length": 151, "alphanum_fraction": 0.7595666854, "num_tokens": 3722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073507867328, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.30316846286102095}}
{"text": "\\documentclass[fleqn]{anstrans}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\title{Inception Neural Networks for Isotope Identification}\n\\author{Samuel Dotson, Mark Kamuda, and Kathryn D. Huff}\n\n\\institute{\nDept. of Nuclear, Plasma and Radiological Engineering, University of Illinois at Urbana-Champaign \\\\\nsgd2@illinois.edu\n}\n\n%%%% packages and definitions (optional)\n\\usepackage{graphicx} % allows inclusion of graphics\n\\usepackage{booktabs} % nice rules (thick lines) for tables\n\\usepackage{microtype} % improves typography for PDF\n\\usepackage{xspace}\n\\usepackage{tabularx}\n\\usepackage{subcaption}\n\\usepackage{enumitem}\n\\usepackage{placeins}\n\\usepackage{amsmath}\n\\include{acros}\n\\newcolumntype{c}{>{\\hsize=.56\\hsize}X}\n\\newcolumntype{b}{>{\\hsize=.7\\hsize}X}\n\\newcolumntype{s}{>{\\hsize=.74\\hsize}X}\n\\newcolumntype{f}{>{\\hsize=.1\\hsize}X}\n\\newcolumntype{a}{>{\\hsize=.45\\hsize}X}\n\\usepackage{titlesec}\n\\titleformat*{\\subsection}{\\normalfont}\n\n\\begin{document}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Introduction}\nThe development of algorithms that can accurately identify the isotopic sources of low-resolution gamma-ray \nspectra is an advancement in current spectroscopy workflows \\cite{rawool-sullivanStepsAutomatedGamma2010}.\nPrevious work shows how isotope identification can be performed using \nartificial neural networks \n\\cite{kamudaAutomatedIsotopeIdentification2018,kamudaComparisonMachineLearning2018a,kamudaAutomatedIsotopeIdentification2017b}. \nThis paper introduces a new feature to the existing architecture of the Artificial Neural Network for Spectroscopic Analysis (\\texttt{annsa}) package, known as an Inception Neural Network (INN). \nAn INN implements inception layers that consist of wide convolution layers with several filters, rather than the typical single-filter layer found in simple convolutional neural networks (CNN).\nThis paper also demonstrates improved methods for simulating spectra to better emulate the background radiation found in real measurements. \nThe features of a gamma-ray spectrum vary depending on the full width at half max (FWHM) of the photopeaks. \nSimultaneously applying multiple filters of different sizes allows an INN to capture more features during a single layer than a CNN. \nWe hypothesize that an INN will also be robust to changes in background radiation thereby generalizing the \\texttt{annsa} framework to more scenarios. \nWe compare the accuracy of an INN to a simple CNN to determine if the improvement in accuracy warrants the increased computational complexity. \nFinally, new training data will be obtained through simulations with the GADRAS-DRF software \\cite{mitchellGADRASIsotopeID2014}.\n\n\\section{Theory -- Artificial Neural Networks}\n\nAn artificial neural network (ANN) maps values from ${\\mathbb{R}}_{N}$ to ${\\mathbb{R}}_{K}$ by mimicking biological \nneurons. Examples of an arbitrary neural net and a single neuron are shown in Figures $\\ref{fig:dense-nn}$ and $\\ref{fig:neuron}$. \n\n\\begin{figure}[ht]\n\\centering\n\\includegraphics[width=0.5\\textwidth]{../figures/dense-layer-figure.png}\n\\caption{An arbitrary neural network that maps values with weights (arrows) \\cite{kamudaComparisonMachineLearning2018a}.}\n\\label{fig:dense-nn}\n\\end{figure}\n\\begin{figure}[ht]\n\\centering\n\\includegraphics[width=0.5\\textwidth]{../figures/neuron-figure.png}\n\\caption{A single neuron being passed through an activation function, $\\textit{f}$ \\cite{kamudaComparisonMachineLearning2018a}.}\n\\label{fig:neuron}\n\\end{figure}\n\nThe sum of the inputs times the weights, $x$, pointing to a neuron are passed through an activation function.\nIn this paper we used a rectified linear unit ($\\textit{relu}$),\n\t\\begin{align}\n                x &= \\sum_{n=1}^{N}A_i w_{ij} [-],\n\t\\end{align}\n\n\t\\begin{align}\n\t\trelu = argmax(0, x) [-],\n\t\\end{align}\n\nThe $\\textit{relu}$ function will turn $on$ a neuron if $x$ is greater than 0, otherwise the neuron stays off.\nThis result becomes the input for the next layer, as shown in Figure $\\ref{fig:neuron}$ \nAn artificial neural network may be trained by iteratively updating the weights of a network by minimizing an error function, $E$. \nThe weights are updated through back propagation by taking the derivative of $E$ with respect to the weights. \nThe error function minimized during training of the INN is cross-entropy,\n\n\t\\begin{align}\n\t\tE = -\\sum_{c}^{M}y_{o,c}\\ln{p_{o,c}} [-].\n\t\\end{align}\n\nEq. 2 shows the cross-entropy for multiclass classification for cases with more than two possible labels \nfor a given input. $M$ is the total number of labels for a given model, in this case it corresponds to 29 \nradionuclides \\cite{nationalcommitteeonradiationinstrumentationn42AmericanNationalStandard2016}. Variable $y_{o,c}$ is binary, indicating whether observation, $o$, has the correct label, $c$. \nVariable $p_{o,c}$ is the probability that $o$ is a member of $c$. The complete INN model is shown in Figure $\\ref{fig:inn-layer}$ and Figure $\\ref{fig:inn-full}$ \nThe input for the INN is a 3$\"$x3$\"$ NaI spectrum of 1024 channels and the final output is a softmax given by,\n\n\n\n\t\\begin{align}\n\t\tsoftmax(z_j) = \\frac{e^{z_j}}{\\sum_{k=1}^{k}} [-].\n\t\\end{align}\n\n\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.5\\textwidth]{../figures/inn_layer_improved.png}\n    \\caption{A gamma spectrum shown as the input for the first inception layer.}\n    \\label{fig:inn-layer}\n\\end{figure}\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.5\\textwidth]{../figures/inn-full-figure.png}\n    \\caption{A zoomed out example of a full inception neural network.}\n    \\label{fig:inn-full}\n\\end{figure}\n\nThe input data is passed through three inception layers and, after flattening, the output is passed to a dense layer which gives the final softmax output. \nEach inception layer typically has a bottleneck, a convolution, and a \nconcatenation \\cite{szegedyGoingDeeperConvolutions2014,szegedyRethinkingInceptionArchitecture2015}.\nThe input spectra are a one-dimensional array with length equal to the number of channels in the detector. The purpose of the bottleneck is to reduce dimensionality without losing information. The bottleneck layer is ignored in this research because spectra are already 1D arrays.   \nThe convolution layer uses filters to select features of a spectrum with local spatial significance and lack long-range relationships. \nOnce the convolution has been done with several filters in parallel, the outputs of each of those convolutions are concatenated into a single tensor and passed to the next inception layer, or dense layer if the last layer has been reached. \nJust like a typical CNN, shown in Figure $\\ref{fig:cnn}$, the final step after feature identification is classification. \nClassification is performed by using a dense, or fully connected, layer with weights corresponding to a probability for a certain label. \nIn this case, the corresponding labels are radionuclides.\n\n\\begin{figure}[ht]\n\t\\centering\n\t\\includegraphics[width=0.5\\textwidth]{../figures/cnn-figure.png}\n\t\\caption{An example of a typical convolutional neural network \\cite{kamudaComparisonMachineLearning2018a}.}\n\t\\label{fig:cnn}\n\\end{figure}\n\n\\section{Methods}\n\\subsection{$\\textit{Training Set Creation}$}\nIt is infeasible to obtain enough real gamma spectrum measurements to properly train a neural network. \nThus all of the datasets used to train the neural network were simulated using GADRAS-DRF \\cite{mitchellGADRASIsotopeID2014}. \nThe 29 isotopes in the dataset are based on the American National Standards Institute performance criteria for handheld instruments for the detection and identification of radionuclides, ANSI N42-34-2015 \\cite{nationalcommitteeonradiationinstrumentationn42AmericanNationalStandard2016}. \nPrevious work \\cite{kamudaComparisonMachineLearning2018a} used a uniform distribution of background isotopes and a constant average count of 65 counts per second (cps) for the background. \nSimulating background radiation in this manner fails to capture the variability of real background spectra.\nWe are updating the simulation protocol to include variations in background conditions. New simulated data will include random noise in a range of 40 to 200 cps. \nWe believe this range is realistic for background radiation.\n\n\\subsection{$\\textit{Network Structure and Hyperparameters}$}\nA neural network can memorize training sets resulting in overtraining and a misidentification of novel data. \nThis is especially true for an INN, whose weights are difficult to tune with simple back propagation.\nTo solve this problem during training, we include an intermediate softmax output allowing for error corrections before the entire forward pass is complete. \nThis branch is ignored during prediction, but offers a way to prevent overtraining. \nIn the fully connected layer, dropout regularization forces the neural network to learn new pathways. \nHyperparameters can be used to optimize performance and prevent overfitting of the model.\nThere is no way to know which hyperparameters will influence the model before training, so a random hyperparameter search is performed to find a set of hyperparameters close to the ideal set\\cite{bergstraRandomSearchHyperParameter2012}. \nFor CNN structures, like the INN, hyperparameters include the sizes of convolutional filters, the output size (how many filters of each size), the number of nodes in a dense layer, and dropout rate \\cite{kamudaComparisonMachineLearning2018a} shown in Table \\ref{tab:hyper}. We also include two INN-specific hyperparameters: Number of inception layers and number of filters per layer. Having a choice in the number of filters exemplifies the benefit of using an INN. Instead of convolving an input with filters of only a single size we can convolve many filter sizes and then concatenate the result as in Figure \\ref{fig:inn-layer}.\n\n\\begin{table}[ht]\n\\caption{Hyperparameter Space for INN}\n\\centering\n\\begin{tabular}{l r}\n\\hline\\hline\nHyperparameter & {Values}\\\\\n\\hline\n\\#inception layers & {1,2,3}\\\\\n\\#filters & {3,4,5}\\\\\noutput size & {3,5,7,9,11}\\\\\nkernel size & {5, 10, 15, 20, 25, 30, 35,}\\\\ \n\t\t\t& {40, 45, 50, 55, 60}\\\\\ndropout rate & {{0.0, 0.1, 0.2, 0.3, 0.4, 0.5}}\\\\ \ndense layer size & {32, 64, 128, 256}\\\\\n\\hline\n\\end{tabular}\n\\label{tab:hyper}\n\\end{table}\n\n\\subsection{$\\textit{Benchmark Techniques}$}\n\nIn order to compare the efficiency of an INN to a traditional CNN we will use the data and results from \\cite{kamudaComparisonMachineLearning2018a} to train and benchmark the INN. Then we will retrain the CNN and the INN using new and varied data. These comparisons will allow us to determine if, and by how much, an INN is an improvement over a CNN. It will also show us how dataset creation affects the robustness of the models.   \nThe INN will be considered superior to CNN performance if equivalent training reduces prediction variance. \nFor concreteness, a 10$\\%$ increase in training time should correspond to a 10$\\%$, or greater, decrease in the variance for the INN when compared with the training time and variance of the CNN.\n\n\\section{Conclusion}\n\nIn this study, we compare the accuracy of two neural networks, a convolutional neural network with two convolutional layers and an inception neural network with three inception layers, for identifying radioactive isotopes in low-resolution gamma-ray spectra. \nWe hypothesize that an INN will exhibit an increase in robustness commensurate to its computational complexity and training the neural networks with larger and varied datasets will also improve their robustness. \nImprovements to the identification of isotopes present in a sample of radioactive material will have implications for national security and nuclear nonproliferation.\n\n\\section{Acknowledgments}\n\nThis work was funded by the Consortium for Verification Technology under Department of Energy National Nuclear Security Administration award number \nDE-NA0002534.  \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\bibliographystyle{ans}\n\\bibliography{bibliography.bib}\n\\end{document}\n", "meta": {"hexsha": "b680f7a041d2edc03979104585874482a726aacd", "size": 12085, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "final/dotson-inn-ans.tex", "max_stars_repo_name": "arfc/2019-dotson-inception-ans", "max_stars_repo_head_hexsha": "889e6875c1d0124d6f4dd01dcc0862d294eb3351", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-01T22:49:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-01T22:49:05.000Z", "max_issues_repo_path": "final/dotson-inn-ans.tex", "max_issues_repo_name": "arfc/dotson-inception-ans", "max_issues_repo_head_hexsha": "889e6875c1d0124d6f4dd01dcc0862d294eb3351", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-07-01T22:56:17.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-02T14:34:11.000Z", "max_forks_repo_path": "final/dotson-inn-ans.tex", "max_forks_repo_name": "arfc/dotson-inception-ans", "max_forks_repo_head_hexsha": "889e6875c1d0124d6f4dd01dcc0862d294eb3351", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 63.9417989418, "max_line_length": 631, "alphanum_fraction": 0.7769962764, "num_tokens": 2941, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3031501653928569}}
{"text": "% !TEX root = omar-thesis.tex\n\\chapter{Introduction}\\label{chap:intro}\n% \\vspace{-14px}\n\\includegraphics[width=\\textwidth]{Picasso-Bull-Progression-cropped.png}\n\\begin{flushright}\n\\emph{Bull} (plates 3, 6, 9 and 11)\\\\\nPablo Picasso (1881-1973)\\end{flushright}\n% http://www.artyfactory.com/art_appreciation/animals_in_art/pablo_picasso.htm\n%\\vspace{-5px}\n% \\begin{quote}\\textit{The recent development of programming languages suggests that the simul\\-taneous achievement of simplicity \n% and generality in language design is a serious unsolved \n% problem.}\\begin{flushright}--- John Reynolds (1970) \\cite{Reynolds70}\\end{flushright}\n% \\end{quote}\n%\\begin{quote}\n%\\textit{Try to imagine that you are a tree. How do you want to look out here?}\n%\\textit{You want your tree to have some character.}\n%\\begin{flushright} --- Bob Ross, \\emph{The Joy of Painting}\\end{flushright}\n%\\end{quote}\n\n% \\vspace{-7px}\n\\section{Motivation}\\label{sec:intro-motivation}\n% \\vspace{-6px}\n%Programming languages come in many sizes. The smallest languages -- for example, the various ``lambda calculi'' -- isolate language primitives of interest for the benefit of students, researchers and language designers interested in studying their mathematical properties. These studies inform the design of ``full-scale'' programming \n%\\footnote{Throughout this work, words and phrases that should be read as having an intuitive or informal meaning, rather than a strict mathematical meaning, will be introduced with quotation marks.} \n% languages, which combine several such primitives, or generalizations thereof. Full-scale languages are interesting objects of formal study in their own right. They also serve as useful tools for software developers, allowing them to construct, reason about and modularly organize large software systems.\n% A single mathematical structure can often take on many syntactic forms. \n% Formal mathematical structures often come equipped with\n% Experienced mathematicians and programmers define formal structures \\emph{compositionally}, drawing from libraries by instantiating more abstract structures. This ultimately increases productivity, because clients of these abstract structures do not need to expend effort to establish the associated definitions and proofs anew, for each specialized structure of interest. %Instead, they need only instantiate the definitions and proofs established by a library provider in a more abstract setting.\n\nExperienced mathematicians and programmers define formal structures \\emph{compositionally}, drawing from libraries of ``general-purpose'' abstractions. The problem that motivates this work is that the resulting terms are sometimes syntactically unwieldy, and, therefore, cognitively costly. % This can neutralize the cognitive benefits of abstraction and composition. We go, therefore, in search of a mechanism of syntactic control that maintains strong compositional reasoning principles. %This can lower productivity, readability and other quality attributes of interest.  %This saves time, one does not need to establish associated definitions and proofs anew, for each specialized structure of interest.\n\nConsider, for example, natural numbers. It is straightforward to define the natural numbers, $n$, with an inductive structure:\n\\[ n ::= \\textbf{z} ~\\vert~ \\textbf{s}(n)\\]\nBy defining natural numbers inductively, we immediately inherit a \\emph{structural induction principle} -- we can establish that some property $P$ holds over the natural numbers if we establish $P(\\textbf{z})$ and $P(\\textbf{s}(n))$ assuming $P(n)$. The problem, of course, is that drawing particular natural numbers by repeatedly applying $\\textbf{s}$ very quickly becomes syntactically unwieldy (in fact, the syntactic cost of the drawing grows linearly with $n$.)\\footnote{We use the word ``drawing'' throughout this document to emphasize that syntactic cost is a property of the visual representation of a structure, rather than a semantic property.}\n\nSimilarly, it is easy to define lists of natural numbers with an inductive structure:\n\\[ \\vec{n} ::= \\textbf{nil} ~\\vert~ \\textbf{cons}(n, \\vec{n}) \\]\nThe problem once again is that drawings of particular lists quickly become unwieldy, and fail to resemble ``naturally occurring'' drawings of lists of numbers.\n\nConsider a third more sophisticated example (which will be of particular relevance later in this work): when defining a programming language or logic, one often needs various sorts of tree structures equipped with metaoperations\\footnote{...so named to distinguish them from the ``object level'' operations of the language being defined.} related to variable binding, e.g. substitution. Repeatedly defining these structures ``from scratch'' is quite tedious, so language designers have instead developed  a more general structure: the \\emph{abstract binding tree (ABT)} \\cite{Aczel78,pfpl,gabbay2002new}. Briefly, an ABT is an ordered tree structure, classified into one of several \\emph{sorts}, where each node is either a \\emph{variable}, $x$, or an \\emph{operation} of the following form:\n%\\footnote{Some prior exposure to (single-sorted) ASTs is assumed here. See Sec. \\ref{sec:preliminaries} for other preliminaries.} \n\\begin{equation*}\n\\abop{op}{\\vec{x}_1.\\mathit{a}_1; \\ldots; \\vec{x}_n.\\mathit{a}_n}\n\\end{equation*} \nwhere $\\texttt{op}$ identifies an \\emph{operator} and each of the $n \\geq 0$ \\emph{arguments} $\\vec{x}_i.\\mathit{a}_i$ binds the (possibly empty) sequence of variables $\\vec{x}_i$ within the subtree $a_i$. The left side of the syntax chart in Figure \\ref{fig:simple-example} summarizes the relevant operational forms for a sort called $\\mathsf{CalcExp}$. ABTs of this sort are the expressions of a small arithmetic programming language,  $\\simplelang$. By using  ABTs as infrastructure in the definition of $\\simplelang$, we need not manually define the ``boilerplate'' metaoperations, like substitution, and reasoning principles, like structural induction, that are necessary to define $\\simplelang$'s semantics and to prove it correct. {Harper gives a detailed account of ABTs, and many other examples of their use, in his book \\cite{pfpl}.} \n\n %and reasoning principles, e.g. {structural induction}, so we need not define this  machinery manually. \n% -- the arities of the operators can be read off from these forms ($\\anumintro{n}$ is a number-indexed family of nullary operators.) \n\n\\begin{figure}\n\\hspace{-5px}$\\begin{array}{lrlllll}\n\\textbf{Sort} & & & \\textbf{Operational Form} & \\textbf{Stylized Form} & \\textbf{Textual Form} & \\textbf{Description}\\\\\n\\mathsf{CalcExp} & e & ::= & x & x & x & \\text{variable}\\\\\n&&& \\aletplain{e}{x}{e} & \\letplain{x}{e}{e} & \\letplain{x}{e}{e} & \\text{binding}\\\\\n&&& \\anumintro{n} & \\numintro{n} & \\numintro{n} & \\text{numbers}\\\\\n&&& \\aplus{e}{e} & e + e & e\\texttt{ + }e & \\text{addition} \\\\\n% &&& \\aminus{e}{e} & e - e & e\\texttt{ - }e & \\text{subtraction}\\\\\n&&& \\amult{e}{e} & e \\times e & e\\texttt{ * }e & \\text{multiplication}\\\\\n&&& \\adiv{e}{e} & \\frac{e}{e} & e\\texttt{ / }e & \\text{division}\\\\\n&&& \\apow{e}{e} & {e}^{e} & e\\verb|^|e & \\text{exponentiation}\\\\\n\\end{array}$\n\\caption[Syntax of $\\simplelang$]{Syntax of $\\simplelang$. Metavariable $n$ ranges over natural numbers and $\\numintro{n}$ abbreviates the numeral forms (one for each natural number $n$, drawn in \\texttt{typewriter} font.) A formal definition of the stylized and textual syntax of $\\simplelang$ would require 1) defining these numeral forms explicitly; 2) defining a parenthetical form; 3) defining the precedence and associativity of each infix operator; and 4) defining whitespace conventions.}\n\\label{fig:simple-example}\n% \\vspace{-5px}\n\\end{figure}\n\n% \\subsection{Syntax Matters}\nThe problem with this approach is, again, that drawing a non-trivial $\\simplelang$ expression in operational form is syntactically costly. For example, we will consider the following drawing in our discussion below:\n\\begin{subequations}\\label{drawings:simple}\\begin{equation}\\label{simple-example-op-form}\n\\adiv{\\anumintro{\\textbf{s}(\\textbf{z})}}{\n\t\\apow{\\anumintro{\\textbf{s}(\\textbf{s}(\\textbf{z}))}}{\\adiv{\\anumintro{\\textbf{s}(\\textbf{z})}}{\\anumintro{\\textbf{s}(\\textbf{s}(\\textbf{z}))}}}\n}\\end{equation}\n% This is an example of a common problem: instantiating a general-purpose abstraction, here for defining ABTs, can be  structurally economical but  \\emph{syntactically costly} (or \\emph{cognitively costly} in some other sense, as we will discuss in Section \\ref{sec:syntactic-properties}.) Mathematics is ultimately a human activity, so these costs are worthy of consideration.\n\n\\subsection{Informal Mathematical Practice}\nWithin a document intended only for human consumption, it is easy to informally outline less costly alternative syntactic forms. \n\nFor example, mathematicians generally use the Western Arabic numeral forms when drawing particular natural numbers, e.g. $2$ is taken as a syntactic alternative to $\\textbf{s}(\\textbf{s}(\\textbf{z}))$. \n\nSimilarly, mathematicians might informally define alternative list forms, e.g. $[0, 1, 2]$ as a syntactic alternative to: \n\\[\\textbf{cons}(\\textbf{z}, \\textbf{cons}(\\textbf{s}(\\textbf{z}), \\textbf{cons}(\\textbf{s}(\\textbf{s}(\\textbf{z})), \\textbf{nil})))\\]\n\nThe middle columns of the syntax chart in Figure \\ref{fig:simple-example} suggest two alternative forms for every ABT of sort $\\mathsf{CalcExp}$. We can draw the ABT from Drawing (\\ref{simple-example-op-form}) in an alternative \\emph{stylized form}:\n% div(num[1]; pow(num[2]; div(num[1]; num[2]))\n% \\begin{subequations}\n% \\begin{equation}\\label{simple-example-op-form}\n% \\adiv{\\anumintro{1}}{\n% \t\\apow{\\anumintro{2}}{\\anumintro{3}}\n% }\\end{equation}\n\\begin{equation}\\label{simple-example-sty-form}\n\\frac{\\numintro{1}}{{\\numintro{2}^{\\frac{\\numintro{1}}{\\numintro{2}}}}}\n\\end{equation}\nor in an alternative \\emph{textual form}:\n\\begin{equation}\\label{simple-example-txt-form}\n\\texttt{1 / 2\\textasciicircum(1/2)}\n\\end{equation}\n\\end{subequations}\n\nMathematicians also sometimes supplement alternative primitive forms like these with various \\emph{derived forms}, which  identify ABTs indirectly according to stated context-independent \\emph{desugaring rules}. For example, the following desugaring rule defines a derived stylized form for square root calculations:\n% \\begin{subequations}\n% \\begin{subequations}[intermezzo]\n\\begin{equation}\\label{rule:simplelang-sqrt}\n\\sqrt{e} \\rightarrowtriangle e^{\\frac{\\numintro{1}}{\\numintro{2}}}\n\\end{equation}\n% \\end{subequations}\nThe reader can desugar a drawing of an ABT by recursively applying desugaring rules wherever a syntactic match occurs. A desugared drawing consists only of the {primitive forms} from Figure \\ref{fig:simple-example}. \nFor example, the following drawing desugars to Drawing (\\ref{simple-example-sty-form}), which in turn corresponds to Drawing (\\ref{simple-example-op-form}) as discussed above:\n\\begin{equation*}\\tag{\\ref*{drawings:simple}d}\n\\frac{\\numintro{1}}{\\sqrt{\\numintro{2}}}\n\\end{equation*}\n%No new operators are introduced.\n\n% Syntactically, however, this practice has its limits. \n\n% Mathematicians often invent specialized syntactic forms in order to visually represent the formal structures that they define. \n% % For example, Figure \\ref{fig:simple-example} defines three different ways to draw any abstract syntax tree (AST) of sort  $\\mathsf{CalcExp}$. ASTs of this sort are the expressions of a small arithmetic programming language, $\\simplelang$.\\footnote{Some familiarity with abstract syntax trees is preliminary to this work. See Sec. \\ref{sec:preliminaries} for citations and a more thorough discussion of preliminaries.}\n% % Mathematicians, like painters, exercise creative license when they draw the structures that arise in their work. \n% % Mathematicians, like painters, exercise creativity when they draw the structures that arise in their work. \n% % Mathematicians often define structurally redundant syntactic forms. \n% %, i.e. forms that are syntactically distinct but that identify the same formal structure. \n% % When defining the syntax of a programming language, language designers often define structurally redundant syntactic forms. \n% % Mathematicians, like painters, draws these trees in a variety of styles.  \n% % There are many ways to draw trees of this sort. \n% % There are many ways to draw a tree. \n% % Most formal structures are defined as modes of use of more primitive formal structures. For example, the expressions of a variety of programming languages are all defined as particular sorts of \\emph{abstract syntax trees}.  \n% For example, the three drawings below all identify the same tree structure  of sort $\\mathsf{CalcExp}$, differing according to the syntax chart in Figure \\ref{fig:simple-example} only in that the first drawing is in a general \\emph{operational form}, whereas the second drawing is in a specialized \\emph{stylized form} and the third is in a specialized \\emph{textual form}:\n% %\n% % differing only in that Drawing (\\ref*{simple-example-op-form}) is in \\emph{operational form}, Drawing (\\ref*{simple-example-sty-form}) is in \\emph{stylized form} and Drawing (\\ref*{simple-example-txt-form}) is in \\emph{textual form}:\n% \\begin{subequations}\n% \\begin{equation}\\label{simple-example-op-form}\n% \\adiv{\\anumintro{1}}{\n% \t\\apow{\\anumintro{2}}{\\anumintro{3}}\n% }\\end{equation}\n% \\begin{equation}\\label{simple-example-sty-form}\n% \\frac{\\numintro{1}}{{\\numintro{2}^{\\numintro{3}}}}\n% \\end{equation}\n% \\begin{equation}\\label{simple-example-txt-form}\n% \\texttt{1 / 2\\textasciicircum3}\n% \\end{equation}\n% \\end{subequations}\n% \\noindent\n% Trees of this sort are the expressions of $\\simplelang$, a simple arithmetic programming language. \n\n% These drawings identify the same AST, meaning that they are all drawn from the same row of the syntax chart at every level. In other words, these drawings are structurally indistinct. \n\n% In particular, let us consider a simple programming language, $\\simplelang$, for performing arithmetic calculations with numbers. The expressions of $\\simplelang$ are \\emph{abstract syntax trees (ASTs)} of a sort defined by the syntax chart in Figure \\ref{fig:simple-example}.\\footnote{Familiarity with abstract syntax trees is preliminary to this work (see Sec. \\ref{sec:preliminaries} for other preliminaries.)}  For example, the following expression is drawn in stylized form:\n% The same expression is drawn in textual form as follows:\n% \\noindent\n% and in operational form as follows:\n\nWhen defining the semantics of a language like $\\simplelang$, it is customary to adopt an \\emph{identification convention} whereby drawings that identify the same underlying ABT structure, like Drawings (\\ref{drawings:simple}), are considered interchangeable. %only if they are drawn from different rows of the syntax chart in Figure \\ref{fig:simple-example}. \nFor example, consider the semantic  judgement $\\isvalU{e}$, which establishes certain  $\\simplelang$ expressions as \\emph{values} (as distinct from expressions that can be arithmetically simplified or that are erroneous.) The following inference rule establishes that every number expression is a value:\\footnote{Some familiarity with inductively defined judgements and inference rules like these is preliminary to this work. See Sec. \\ref{sec:preliminaries} for citations and further discussion of necessary preliminaries.}\n\\begin{equation}\\label{rule:num-val}\n\\inferrule{ }{\n\t\\isvalU{\\anumintro{n}}\n}\n\\end{equation}\nAlthough this rule is drawn using the operational form for number expressions, we can apply it to derive that $\\isvalU{\\numintro{2}}$, because $\\numintro{2}$ and $\\anumintro{2}$  identify the same ABT.\n\n% In summary, it is both the case that ``syntax doesn't matter'' (semantically) and that syntax matters (cognitively). %i.e.  because mathematics is a human activity that alternative and derived forms matter (cognitively).%Syntax matters because mathematics and programming are human activities. \n\n\n% \\subsection{Syntax Doesn't Matter  (Semantically)}\n% It is worth emphasizing here that these common syntactic practices are not motivated by semantic considerations. Indeed, \n\n\n\n% \\subsection{Syntax Matters (Cognitively)}\n% %Our semantics would be no weaker if we had defined only, for example, the operational forms. \n% %The answer, of course, is that from the perspective of a human programmer, syntax \\emph{does} matter. \n% % If different drawings of a $\\simplelang$ expression are not semantically distinguishable, why did we bother to define alternative syntactic forms at all?\n% Syntactic sugar matters because mathematics and programming are human activities. Different visual representations of a formal structure can and must be distinguished by the \\emph{cognitive costs} that human programmers incur as they produce or examine them.\\footnote{In fact, we should be interested in sensory modalities other than vision, if only because many humans lack sufficient eyesight. Alas, this topic is beyond the scope of our present work.}% Drawings of formal structures serve as \\emph{user interfaces} to the underlying structures themselves.\n\n% For example, a human programmer might distinguish drawings of $\\simplelang$ expressions in stylized or textual form, like Drawings (\\ref{simple-example-sty-form}) through (\\ref{simple-example-derived-form}) above, as less ``crowded'' and more ``familiar'' than those in operational form, because they follow the usual arithmetic conventions or close approximations thereof. This might help the human  programmer extract meaning from such drawings more quickly. Similarly, drawings in textual form involve only text, which can lower the costs involved in their production. Of course, drawings in operational form can bring cognitive benefits as well -- dispensing with various syntactic complexities (e.g. related to  precedence and associativity) can simplify metatheoretic reasoning and implementation efforts. \n\n% We will cover more rigorous operationalizations of the necessarily broad notion of cognitive cost in Section \\ref{sec:syntactic-properties}. %Mistakes may also be less frequent when producing drawings in stylized or textual form (for $\\simplelang$ expressions, perhaps only because operational forms use more parentheses). \n\n% \\subsection{Derived Forms}\n% %The forms defined by the syntax chart in Figure \\ref{fig:simple-example} suffice to allow programmers to draw any $\\simplelang$ expression. However, \n% In seeking to lower cognitive costs, syntax designers  often  include additional \\emph{derived forms}  in a syntax definition. Unlike the \\emph{primitive forms}  defined in Figure \\ref{fig:simple-example}, which identify trees directly, derived forms identify trees indirectly, through a context-independent {desugaring} rule.   \n% %We can define a desugaring transformation by stating a rewrite rule. \n% For example, the following desugaring rule defines a derived stylized form for calculating the square root of a $\\simplelang$ expression:\n% % \\begin{subequations}\n% \\begin{equation}\\label{rule:simplelang-sqrt}\n% \\sqrt{e} \\rightarrowtriangle e^{\\frac{\\numintro{1}}{\\numintro{2}}}\n% \\end{equation}\n% % Similarly, the following rewrite rule, if included in the definition of the textual syntax of expressions, defines a derived form for negating a $\\simplelang$ expression:\\footnote{Notice that the right-hand side of this rule is in operational form, rather than textual. For $\\footnotesimplelang$, it is not necessary to prevent textual and operational forms from being interspersed within a single drawing -- no ambiguities can arise. For richer syntax definitions, this may no longer be the case. The desugaring process must then be modified to first convert the pattern on the righthand side of a desugaring rule like Rule (\\ref{rule:simplelang-negate}) to the desired form variant before it is applied.}\n% % \\begin{equation}\\label{rule:simplelang-negate}\n% % \\texttt{-}e \\rightarrowtriangle \\amult{e}{\\anumintro{-1}}\n% % \\end{equation}\n% % \\end{subequations}\n% % \\noindent \n% Desugaring a drawing of a tree involves first recursively desugaring the drawings of its subtrees. If the drawing is in primitive form, desugaring is complete.  If the drawing is in derived form, we apply the corresponding desugaring rule (here, we  have only one choice.) The desugared drawing will identify a tree immediately, i.e. it will consist only of primitive forms. No new trees are introduced, so the semantics is unchanged. %Derived forms affect only cognitive cost.\n%Similarly, we might define a derived form for taking an arbitrary root of an expression as follows:\n% \\begin{align*}\n% \\sqrt[e']{e} & \\rightarrowtriangle e^{\\frac{\\numintro{1}}{e'}}\n% \\end{align*}\n\n\\subsection{Derived Forms in General-Purpose Languages}\nWe would need to define only a few more derived arithmetic forms to satisfyingly capture the  idioms that arise in the limited domains where a simple language of arithmetic operations like $\\simplelang$ might be useful. %Consequently, there is little opportunity to go beyond simple derived forms like these. \nHowever, programming languages in common use today are substantially more semantically expressive. Indeed, many mathematical structures, including natural numbers, lists and ABTs, can be adequately expressed within contemporary ``general-purpose'' programming languages. %Mathematics has become supplanted by particular formal system. \nConsequently, the problems of syntactic cost just discussed at the level of the ambient mathematics also arise ``one level down'', i.e. when writing programs. For example, we want syntactic sugar not only for mathematical natural numbers, lists and $\\simplelang$ expressions, but also for \\emph{encodings} of these structures within a general-purpose programming language.% .) %https://github.com/jonsterling/sml-abt or https://github.com/RedPRL/sml-typed-abts.) \n\nWe can continue to rely on the informal notational conventions described above only as long as programs are drawn solely for human consumption. These conventions break down when we need drawings of programs to themselves exist as formal structures suitable for consumption by other programs, i.e. \\emph{parsers}, which check whether drawings are well-formed relative to a \\emph{syntax definition} and produce structures suitable for consumption by yet other programs, e.g. compilers. %This, of course, is the regime of contemporary computer programming.\n\n% The problem is that nearly all contemporary languages are designed so that drawings of programs can be consumption both by humans and by another program -- a parser -- which checks whether drawings are well-formed and produces a structure suitable for consumption by various other useful programs, e.g. editors and compilers.\n\n\n% Programmers address these problems by informally stating alternative and derived forms, as in handwritten or typeset mathematics, because a drawing of a program must be suitable for consumption both by humans and by % This limits the control that programmers have over syntactic cost.\n\n% In contemporary practice, other programs -- parsers -- consume drawings of programs, which generate corresponding structures for execution by modern computer hardware. As such, we cannot rely on an informal approach that defers ultimately to the intuitions of a human reader. Instead, we must define the syntactic conventions that we wish to use with rigor. \n\nConstructing a formal syntax definition is not itself an unusually difficult task for an experienced programmer, and there are many \\emph{syntax definition systems} that help with this task (Sec. \\ref{sec:existing-approaches} will cover several examples.) The problem is that when designing the syntax of a general-purpose language, the language designer cannot hope to anticipate all library constructs for which derived forms might one day be useful. At best, the language designer can bundle certain libraries together into a ``standard library'', and privilege select constructs defined in this library with derived forms. \n\n% as these ``general-purpose'' languages have evolved, many other derived forms have become incorporated into their syntax definitions.\\footnote{The same dynamic is apparent in the progression of ``pen and paper'' and typeset mathematics.}  \nFor example, the textual syntax of Standard ML (SML), a general-purpose language in the functional tradition, defines derived forms for constructing and pattern matching on lists \\cite{mthm97-for-dart,harper1997programming}. In SML, the derived expression form \\lstinline{[x, y, z]} desugars to an expression equivalent to:\n\\begin{lstlisting}[numbers=none]\nCons(x, Cons(y, Cons(z, Nil)))\n\\end{lstlisting}\nassuming \\li{Nil} and \\li{Cons} stand for the list constructors exported by the SML Basis library (i.e. SML's ``standard library''.)\\footnote{The desugaring actually uses unforgeable identifiers bound permanently to the list constructors, to ensure that the desugaring is context independent. We will return to the concept of context independence throughout this work.} Other languages similarly privilege select standard library constructs with derived forms:\n\n\\begin{itemize}\n\\item OCaml \\cite{ocaml-manual} defines derived forms for strings (defined as arrays of characters.)\n\\item Haskell \\cite{jones2003haskell} defines derived forms for encapsulated commands (and, more generally, values of any type equipped with monadic structure.)\n\\item Scala \\cite{odersky2008programming} defines derived XML forms as well as string splicing forms, which capture the idioms of string concatenation.\n\\item F\\# \\cite{syme2012expert}, Scala \\cite{shabalin2013quasiquotes} and various other languages define derived forms for encodings of the language's own terms (these are referred to as \\emph{quasiquotation} forms.)\n\\item Python \\cite{python} defines derived forms for mutable sets and dictionaries.\n\\item Perl \\cite{perlre} defines derived regular expression forms.\n\\end{itemize}\n\nThese choices are, fundamentally, made according to \\emph{ad hoc} design criteria -- there are no clear semantic criteria that fundamentally distinguish standard library constructs privileged with derived forms from those defined in third-party libraries. \n%Indeed, it is considered a virtue for a standard library can be separated from the language definition. \nIndeed, as the OCaml community has moved away from a single standard library in favor of competing bundles of third-party libraries (e.g. Batteries Included \\cite{OCaml-batteries} and Core \\cite{OCaml-core}), this approach has become starkly impractical.% This puts into question the practice of bundling a single standard library with  entirely.\n\n\\section{Existing Mechanisms of Syntactic Control}\nA more parsimonious approach would be to eliminate derived forms  specific to standard library constructs from language definitions in favor of mechanisms that give more syntactic control to third-party library providers.\n\nIn this section, we will give a brief overview of existing such mechanisms and speak generally about the problems that they present to motivate our novel contributions in this area. We will return to give a detailed overview of these various existing mechanisms of syntactic control in Section \\ref{sec:existing-approaches}. \n\n\\subsection{Syntax Dialects}\\label{sec:problems-with-dialects}\nOne approach that a library provider can take when seeking more syntactic control is to use a syntax definition system to construct a \\emph{syntax dialect}, i.e. a new syntax definition that extends the original syntax definition with new derived forms. \n%library-specific (a.k.a. ``domain-specific'') \n\nFor example, Ur/Web extends Ur's textual syntax with derived forms for SQL queries, XHTML elements and other constructs defined in a  web programming library \\cite{conf/popl/Chlipala15,conf/pldi/Chlipala10}. Figure \\ref{fig:urweb} demonstrates how XHTML expressions that contain strings can be drawn in Ur/Web. The desugaring of this derived form (not shown) is substantially more verbose and, for programmers familiar with the standardized syntax for XHTML \\cite{xhtml}, substantially more obscure. % Such dialects are sometimes qualitatively taxonomized as amongst the ``domain-specific language'' for this reason \\cite{fowler2010domain}. %Syntactic cost is often assessed qualitatively \\cite{green1996usability}, though quantitative metrics can be defined. \n\\begin{figure}[h]\n\\begin{lstlisting}[numbers=none]\nval p = SURL<xml><p>Hello, {[EURLjoin \" \" [first, last]SURL]}!</p></xml>EURL\n\\end{lstlisting}\n\\caption{Derived XHTML forms in Ur/Web}\n\\label{fig:urweb}\n\\end{figure}                           \n\nSyntax definition systems like Camlp4 \\cite{ocaml-manual}, Copper \\cite{conf/gpce/WykS07} and SugarJ/Sugar* \\cite{erdweg2011sugarj,erdweg2013framework}, which we will discuss in Sec. \\ref{sec:syntax-dialects}, have simplified the task of defining ``library-specific'' (a.k.a. ``domain-specific'') syntax dialects like Ur/Web, and have thereby contributed to their ongoing proliferation.\n%The desugaring, not shown, is substantially more verbose and, for programmers who are familiar with XHTML forms, substantially more obscure than the drawing above. %We will consider other examples of data structures where syntactic cost becomes a legitimate concern for client programmers in Sec. \\ref{sec:motivating-examples}. \n%after first reviewing simpler approaches that also help library providers control syntactic cost, albeit to a more limited extent, \n% Syntax definition systems \n% The most syntactically expressive of the mechanisms that we will detail in Section \\ref{sec:existing-approaches} are \n\n\n%Full-scale languages are also interesting objects of mathematical study. Uniquely, however, they are also designed for use by humans. Consequently, their designers  typically define both an abstract syntax and a textual syntax. This textual syntax serves as the primary interface between human programmers and the language, so it is common to define various \\emph{derived forms}, i.e. forms defined by a context-independent \\emph{desugaring} to a set of \\emph{base forms}. These serve to decrease the \\emph{syntactic cost} or \\emph{cognitive cost} of selected idioms. \n%In some cases, a derived form is designed to capture an idiom77Gu that involves only the primitive constructs of the language. \n\n%The hope amongst some language designers is that a limited number of derived forms like these will suffice to produce a ``general-purpose'' textual syntax, i.e. one that is accepted as suitable for use across a wide variety of application domains. Alas, a stable design that fully achieves this ideal has yet to emerge, as evidenced by the diverse array of \\emph{syntax dialects} -- dialects that introduce only new derived forms -- that continue to proliferate around all major contemporary languages. \n\n%In fact, tools that aid in the construction of so-called  ``domain-specific'' language dialects (DSLs)\\footnote{In some parts of the literature, such dialects are called ``external DSLs'', to distinguish them from  ``internal'' or ``embedded DSLs'', which are actually  library interfaces that only ``resemble'' distinct dialects \\cite{fowler2010domain}.} seem only to be becoming more prominent over time. \n\n%\\subsection{Why are there so many language dialects?}\n%{This calls for an investigation}: why is it that programmers and researchers are still so often unable to satisfyingly express the constructs that they seek in libraries, as modes of use of the ``general-purpose'' primitives already available in major languages today, and instead see a need for new language dialects?\n\n%Perhaps the most common sort of dialect is the \\emph{syntax dialect} -- a dialect that introduces only new derived syntactic forms, motivated by a desire to decrease the {syntactic cost} of working with one or more library constructs of interest. \n%Put another way, syntax dialects can be specified by a context-independent expansion to the existing language that they are based on. \n%For example, Ur/Web is a syntax dialect of Ur (a language that itself descends from ML \\cite{conf/pldi/Chlipala10}) that builds in derived forms for SQL queries, HTML elements and other datatypes used in the domain of web programming \\cite{conf/popl/Chlipala15}. %Syntactic cost is often assessed qualitatively \\cite{green1996usability}, though quantitative metrics can be defined. \n%This is not an isolated example -- we will consider a number of additional types of data that similarly stand to benefit from the availability of specialized derived forms in Sec. \\ref{sec:motivating-examples}. \n%Tools like Camlp4 \\cite{ocaml-manual}, Sugar* \\cite{erdweg2011sugarj,erdweg2013framework} and Racket \\cite{Flatt:2012:CLR:2063176.2063195}, which we will discuss in Sec. \\ref{sec:existing-approaches}, have lowered the engineering costs of constructing syntax dialects in such situations, further contributing to their proliferation. \n\n%More advanced dialects introduce new type structure, going beyond what is possible with only new derived forms. As a simple example, the static and dynamic semantics of records cannot be expressed by context-independent expansion to a language with only nullary and binary products. Various languages have explored ``record-like'' primitives that go further, supporting functional update operators, width and depth coercions (sometimes implicit)%\\cite{Cardelli:1984:SMI:1096.1098}\n%, methods, prototypic dispatch and other such ``semantic embellishments'' that in turn cannot be expressed by context-independent expansion to a language with only standard record types (we will detail an  example in Sec. \\ref{sec:metamodules-motivating-examples}). OCaml primitively builds in the type structure of polymorphic variants, open datatypes and  operations that use format strings like $\\mathtt{sprintf}$ \\cite{ocaml-manual}. ReactiveML builds in primitives for functional reactive programming \\cite{mandel2005reactiveml}. ML5 builds in high-level primitives for distributed programming based on a modal lambda calculus \\cite{Murphy:2007:TDP:1793574.1793585}. Manticore \\cite{conf/popl/FluetRRSX07} and AliceML  \\cite{AliceLookingGlass} build in parallel programming primitives with a more elaborate type structure than is found in simpler accounts of parallelism. \n%MLj builds in the type structure of the Java object system (motivated by a desire to interface safely and naturally with Java libraries) \\cite{Benton:1999:IWW:317636.317791}. Other dialects do the same for other foreign languages, e.g. Furr and Foster describe a dialect of OCaml that builds in the type structure of C \\cite{Furr:2005:CTS:1065010.1065019}. Tools like proof assistants and logical frameworks are used to specify and reason metatheoretically about dialects like these, and tools like compiler generators and language frameworks \\cite{erdweg2013state} lower their implementation cost, again contributing to their proliferation. \n\n% \\vspace{-5px}\n%\\subsection{Problems with the Dialect-Oriented Approach}\\label{sec:problems-with-dialects}\nMany have argued that a proliferation of syntax dialects is harmless or even desirable, because programmers can simply choose the right syntax dialect for each job at hand \\cite{journals/stp/Ward94}. However, we argue that this ``dialect-oriented approach'' is difficult to reconcile with the best practices of ``programming in the large''  \\cite{DeRemer76}, i.e. developing large programs ``consisting of many small programs (modules), possibly written by different people'' whose interactions are mediated by a reasonable type and binding discipline. The problems that tend to arise are summarized below; a more systematic treatment will follow in  Sec. \\ref{sec:syntax-dialects}.\n\n\\subsubsection{Problem 1: Conservatively Combining Syntax Dialects}\nThe first problem with the dialect-oriented approach is that clients  cannot always combine different syntax dialects when they want to use derived forms that they define together. This is problematic because client programs  cannot be expected to fall cleanly into a single preconceived ``problem domain'' -- large programs use many libraries \\cite{DBLP:conf/sac/LammelPS11}.\n\nFor example, consider a syntax dialect, $\\mathcal{H}$, defining derived forms for working with encodings of HTML elements, and another syntax dialect, $\\mathcal{R}$,  defining derived forms for working with encodings of regular expressions. Some programs will undoubtedly need to manipulate HTML elements as well as regular expressions, so it would be useful to construct a ``combined dialect'' where all of these derived forms are defined. \n\nFor this notion of ``dialect combination'' to be well-defined at all, we must first have that $\\mathcal{H}$ and $\\mathcal{R}$ are defined under the same syntax definition system. In practice, there are many useful syntax definition systems, each differing subtly from the others. %If the dialect designers  have not  chosen the same syntax definition system, then ``dialect combination'' is not systematic (in the way that importing different libraries is systematic.)%$\\mathcal{H} \\cup \\mathcal{R}$ is simply undefined.% (e.g. parser combinator libraries like Haskell's \\li{parsec} \\cite{parsec}.)\n\nIf $\\mathcal{H}$ and $\\mathcal{R}$ are coincidentally defined under the same syntax definition system, we must also have that this system operationalizes the notion of dialect combination, i.e. it must define some operation $\\mathcal{H} \\cup \\mathcal{R}$ that creates a dialect that extends both $\\mathcal{H}$ and $\\mathcal{R}$, meaning that any form defined by either $\\mathcal{H}$ or $\\mathcal{R}$ must be defined by $\\mathcal{H} \\cup \\mathcal{R}$. Under systems that do not define such an operation (e.g. Racket's dialect preprocessor \\cite{Flatt:2012:CLR:2063176.2063195}), clients can only manually  ``copy-and-paste'' or factor out portions of the constituent dialect definitions to construct the ``combined'' dialect. This is not systematic and, in practice, it can be quite tedious and error-prone. %In both this and the previous case, ``dialect combination'' is a strictly informal notion, left to library clients to operationalize through manual labor (hence the quotes).\n\nEven if we restrict our interest  to dialects defined under a common syntax definition system that does operationalize the notion of dialect combination (or similarly one that allows clients to systematically combine \\emph{dialect fragments}), we still have a problem: there is generally no guarantee that the combined dialect will conserve important properties that can be established about the constituent dialects in isolation (i.e. \\emph{modularly}.) In other words, establishing $P(\\mathcal{H})$ and $P(\\mathcal{R})$ is not sufficient to establish $P(\\mathcal{H} \\cup \\mathcal{R})$ for many useful properties $P$. Clients must re-establish such properties for each combined dialect that they construct.%In other words, any putative ``combined language'' must formally be considered a  distinct system for which one must derive essentially all metatheorems of interest anew, guided only informally by those derived for the dialects individually. %There is no well-defined mechanism for constructing such a ``combined language'' in general. \n\nOne important property of interest is \\emph{syntactic determinism} -- that every derived form has at most one desugaring. It is not difficult to come up with examples where combining two deterministic syntax dialects produces a non-deterministic dialect. For example, consider two syntax dialects defined under a system like Camlp4: $\\mathcal{D}_1$ defines derived forms for sets, and $\\mathcal{D}_2$ defines derived forms for finite maps, both delimited by \\verb~{<~ and \\verb~>}~.\\footnote{In OCaml, simple curly braces are already reserved by the language for record types and values.} Though each dialect defines a deterministic grammar, i.e. $\\mathrm{det}(\\mathcal{D}_1)$ and $\\mathrm{det}(\\mathcal{D}_2)$, when the grammars are na\\\"ively combined by Camlp4, we do not have that $\\mathrm{det}(\\mathcal{D}_1 \\cup \\mathcal{D}_2)$ (i.e. syntactic ambiguities arise under the combined dialect.) In particular, \\verb~{<>}~ can be recognized as either the empty set or the empty finite map. %A recent version of Python added derived forms for mutable sets. Due to a conflict with dictionary syntax, however, there is no derived form for the empty set.)\n %A third syntax dialect might come along that uses the same forms that $\\mathcal{D}_2$ defines, but for ordered finite maps.\n\nSchwerdfeger and Van Wyk have developed a modular grammar-based syntax definition system, implemented in Copper \\cite{conf/gpce/WykS07}, that guarantees that determinism is conserved when syntax dialects (of a certain restricted class) are combined \\cite{conf/pldi/SchwerdfegerW09,schwerdfeger2010context} as long as each constituent dialect prefixes all newly introduced forms with starting tokens drawn from disjoint sets. We will describe the difficulties that this requirement causes in Section \\ref{sec:syntax-dialects}.\n\n\n\\subsubsection{Problem 2: Abstract Reasoning About Derived Forms}\\label{sec:abs-reasoning-intro}\nEven putting aside the difficulties of conservatively combining syntax dialects, there are questions about how \\emph{reasonable}  sprinkling library-specific derived forms throughout a large software system might be. \nFor example, consider the perspective of a programmer attempting to comprehend (i.e. reason about) the program fragment in Figure \\ref{fig:K-dialect}, which is drawn under a syntax dialect constructed by combining a number of dialects of Standard ML's textual syntax.\n\n\\begin{figure}[h]\n\\begin{lstlisting}\nval w = compute_w ()\nval x = compute_x w\nval y = {|(!R)@&{&/x!/:2_!x}'!R}|}\n\\end{lstlisting}\n\\caption{An example of unreasonable program text}\n\\label{fig:K-dialect}\n\\end{figure}\n\nIf the programmer happens to be familiar with the (intentionally terse) syntax of the stack-based database query processing language K \\cite{Whitney:2001:LOR:376284.375783}, then Line 3 might pose few difficulties. If the programmer does not recognize this syntax, however, there are no simple, definitive protocols for answering questions like:\n\\begin{enumerate}\n\\item \\textbf{(Responsibility)} Which constituent dialect defined the derived form that appears on Line 3?\n\\item \\textbf{(Segmentation)} Are the characters \\li{x} and \\li{R} on Line 3 parsed as spliced expressions \\li{x} and \\li{R} (i.e. expressions of variable form), or parsed in some other way peculiar to this form?\n\\item \\textbf{(Capture)} If \\li{x} is in fact a spliced expression, does it refer to the binding of \\li{x} on Line 2? Or might it capture an unseen binding introduced in the desugaring of Line 3?\n\\item \\textbf{(Context Dependence)} If \\li{w}, on Line 1, is renamed, could that possibly break the program, or change its meaning? In other words, might the desugaring of Line 3 assume that some variable identified as \\li{w} is in scope (even though \\li{w} is not mentioned in the text of Line 3)?\n\\item \\textbf{(Typing)} What type does \\li{y} have?\n\\end{enumerate}\n\nIn short, syntax dialects do not come with useful principles of \\emph{syntactic abstraction}: if the desugaring of the program is held abstract, programmers can no longer reason about types and binding (i.e. answer questions like those above) in the usual disciplined manner. This is burdensome at all scales, but particularly when programming in the large, where it is common to encounter a program fragment drawn by another programmer, or drawn  long ago. Forcing the programmer to examine the desugaring of the drawing in order to reason about types and binding defeats the ultimate purpose of using syntactic sugar -- lowering cognitive cost (we expand on the notion of cognitive cost in Sec. \\ref{sec:syntactic-properties}.) \n\n\n%In other words, encountering an unfamiliar derived form has made it difficult for the programmer to maintain the usual \\emph{type discipline} and \\emph{binding discipline}. %Compelling the programmer to examine the desugaring directly defeat the purpose of defining the derived form -- decreasing cognitive cost. Indeed, it substantially increases cognitive cost.\n\nIn contrast, when a programmer encounters, for example, a function call like the call to \\li{compute_x} on Line 3, the analagous questions can be answered by following clear protocols that become ``cognitive reflexes'' after sufficient experience with the language, even if the programmer has no experience with the library defining \\li{compute_x}:\n\\begin{enumerate}\n\\item The language's syntax definition determines that \\li{compute_x w} is an expression of function application form.\n\\item Similarly, \\li{compute_x} and \\li{w} are definitively expressions of variable form.\n\\item The variable \\li{w} can only refer to the binding of \\li{w} on Line 1.\n\\item The variable \\li{w} can be renamed without knowing anything about the value that \\li{compute_x} stands for.\n\\item The type of \\li{x} can be determined to be \\li{B} by determining that the type of \\li{compute_x} is \\li{A -> B} for some \\li{A} and \\li{B}, and checking that \\li{w} has type \\li{A}. Nothing else needs to be known about the value that \\li{compute_x} stands for. In Reynolds' words \\cite{B304}:\n\\begin{quote}\n\\emph{Type structure is a syntactic discipline for enforcing levels of abstraction.}\n\\end{quote}\n\\end{enumerate}\n\n\n\n% In summary, syntax dialects give library providers so much syntactic control that it creates problems for client programmers.\n%A related issue arises when one works within a language with a module system, i.e. a system that supports interacting through a defined interface with various implementations of that interface. For example, consider different regular expression engines that differ only with regard to their performance in various circumstances, or different parser generators that accept the same class of grammar. Ideally, one would like to be able to define derived forms once such that they operate only through the common interface. To do so today requires both an awkward syntactic trick and coordination between library providers, as we will discuss in Sec. \\ref{sec:syntax-examples-regexps}. Ideally, this would not be necessary.\n\n%It is thus infeasible to simply allow different contributors to a software system to choose their own favorite dialect for each component they are responsible for. \n%It it clear that dialects are better rhetorical devices than practical engineering artifacts. \n\n%Due to this paucity of modular reasoning principles, the ``dialect-oriented'' approach is problematic for software development ``in the large''. %Large software projects and software ecosystems must pick a single language that does provide powerful modular reasoning principles and, to benefit from them, stay inside it.\n\n% \\subsection{Central Planning Considered Harmful}\n% Dialects do sometimes have a less direct influence on large-scale software development: they can help convince the designers in control of comparatively popular languages, like OCaml and Scala, to include some variant of the primitives that they feature into backwards-compatible language revisions. %These decisions are increasingly influenced by community processes, e.g. the Scala Improvement Process.  %This approach concentrates power as well as responsibility over maintaining metatheoretic guarantees in the hands of a small group of language designers, though increasingly influenced by various community processes (e.g. the Scala Improvement Process). \n% %Dialects thus serve the role of rhetorical vehicles for new ideas, rather than direct artifacts. \n% %Over time, accepting such extensions has caused these languages to balloon in size. \n% This \\emph{ad hoc} approach is unsustainable, for three main reasons. First, as we will demonstrate in Sec. \\ref{sec:motivating-examples}, there are simply too  many potentially useful such primitives, and many of these capture idioms common only in relatively narrow application domains. It is unreasonable to expect language designers to be able to evaluate all of these use cases in a timely and informed manner. Second, primitives introduced earlier in a language's lifespan can end up monopolizing finite ``syntactic resources'', forcing subsequent primitives to use ever more esoteric forms. And third, primitives that prove after some time to be flawed in some way cannot be removed or modified without breaking backwards compatibility. For these reasons, language designers are justifiably reticent to add new primitives to major languages.%Because there is often no empirical data about how useful a construct is in practice until it is available in a major language, decisions about which constructs to include are often informed only by intuition (and are thus)\n% %Recalling the words of  Reynolds, which are clearly as relevant today as they were almost half a century ago \\cite{Reynolds70}: %This approach is antithetical to the ideal of a truly \\emph{general-purpose language} described at the beginning of this section.\n% %\\newpage\n\n%\\subsection{Toward More Reasonable Primitives}\n%These \n%This leaves two possible paths forward. One is to simply eschew ``niche'' derived forms and settle on the existing designs, which might be considered to sit at a ``sweet spot'' in the overall language design space (accepting that in some circumstances, this leads to  high cognitive cost). \n\n\n%Similarly, it recently introduced ``open datatypes'', which subsume its previous more specialized exception type, and captures many use cases for .\n\n%Viewed ``dually'', one might equivalently ask for a language that builds in a core that is as small as possible, but provides expressive power comparable to languages with much larger cores. This is our goal in the work being proposed\n\n%Similarly, it recently introduced ``open datatypes'', which subsume its previous more specialized exception type, and captures many use cases for .\n\n%Viewed ``dually'', one might equivalently ask for a language that builds in a core that is as small as possible, but provides expressive power comparable to languages with much larger cores. This is our goal in the work being proposed. \n\n\\subsection{Term Rewriting Systems}\nAn alternative approach that a library provider can consider when seeking to control syntactic cost is to leave the context-free syntax of the language fixed and instead contextually repurpose existing syntactic forms using a \\emph{term rewriting system}. We will review various term rewriting systems in detail in Sec. \\ref{sec:non-local-term-rewriting} and Sec. \\ref{sec:macro-systems}. \n\nNa\\\"ive term rewriting systems suffer from problems analagous to those that plague syntax definition systems. In particular, it is difficult to conserve determinism, i.e. separately defined rewriting rules might attempt to rewrite the same term differently. Moreover, it can be difficult to determine which rewriting rule, if any, is responsible for a particular term, and to reason about types and binding given a drawing of a program subject to a large number of rewriting rules without examining the rewritten program.\n\nModern \\emph{term-rewriting macro systems}, however, have made some progress toward addressing these problems. In particular:\n\\begin{enumerate}\n\\item Macro systems require that the client explicitly apply the intended rewriting (implemented by a macro) to the term that is to be rewritten, thereby addressing the problems of conflict and determining responsibility. However, it is often unclear whether a given macro  is repurposing the form of a given argument or sub-term thereof, as opposed to treating it parametrically by inserting it unmodified into the generated expansion. This is closely related to the problem of determining a {segmentation}, discussed above.\n\\item Macro systems that enforce \\emph{hygiene}, which we will return to in Sec. \\ref{sec:macro-systems}, address many of the problems related to reasoning about binding. \n\\item The problem of reasoning about types has been relatively understudied, because most research on macro systems has been for languages in the Lisp tradition that lack rich static type structure \\cite{mccarthy1978history}. That said, some progress has also been made on this front with the design of \\emph{typed macro systems}, like Scala's macro system \\cite{ScalaMacros2013}, where annotations constrain the macro arguments and the generated expansions.\n\\end{enumerate}\n\nThe main problem with term-rewriting macros, then, is that they afford library providers only limited syntactic control -- they must find creative ways to repurpose existing forms. For example, consider the  XHTML and K examples above. In both cases, the syntactic conventions are quite distinct from those of ML-like languages (and, for that matter, languages that use S-expression.) % Moreover, these existing forms normally have other meanings, so contextually repurposing them can be confusing \\cite{pane1996usability}.\n\nIt is tempting in these situations to consider repurposing string literal forms. For example, we might wish to apply a macro \\li{html!} (following Rust's convention of using a post-fix \\li{!} to distinguish macro names from variables) to rewrite string literals containing Ur/Web-style XHTML syntax as follows:\n\\begin{lstlisting}[numbers=none]\n  html! \"SSTR<p>Hello, {[join \" \" [first, last]]}!</p>ESTR\"\n\\end{lstlisting}\n\nThe problem here is that there is no way to extract the spliced expressions from the supplied string literal forms while satisfying the context independence condition, because variables that come from these spliced terms (e.g. \\li{join}) are indistinguishable from variables that inappropriately appear free relative to the expansion. In addition, the problem of segmentation becomes even more pernicious: to a human or tool unaware of Ur/Web's syntax, it is not immediately apparent which particular subsequences of the string literals supplied to \\li{html!} are segmented out as spliced expressions. Reader macros have essentially the same problem  \\cite{DBLP:journals/jfp/FlattCDF12}.\n\n\\section{Contributions}\\label{sec:contributions}\n%%Our broad aim in the work being proposed is to introduce primitive language mechanisms that give library providers the ability to  express new syntactic expansions as well as new types and operators in a safe and modularly composable manner. \n%To summarize our motivating argument: the widespread proliferation of syntax dialects and syntax definition systems suggests that programmers value library-specific (a.k.a. domain-specific) syntactic sugar. However, the dialect-oriented approach seems to be incompatible with the best practices of programming in the large.  \n\nThis work introduces a system of \\textbf{typed literal macros (TLMs)} that gives library providers substantially more syntactic control than existing typed term-rewriting macro systems while maintaining the ability to reason abstractly about types, binding and segmentation.% abstract reasoning principles. % comparable to the level of control they have when defining a syntax dialect.\n\nClient programmers apply TLMs to \\emph{generalized literal forms}. For example, in Figure \\ref{fig:first-tsm-example} we apply a TLM named \\li{#\\dolla#html} to a generalized literal form delimited by backticks. TLM names are prefixed by \\li{#\\dolla#} to clearly distinguish TLM application from function application. The semantics delegates control over the parsing and expansion of each literal body to the applied TLM during a semantic phase called \\emph{typed expansion}, which generalizes the usual typing phase. \n\\begin{figure}[ht!]\n\\begin{lstlisting}[numbers=none,xleftmargin=0px]\n$html `SURL<p>Hello, {[join ($str ' ') ($strlist [first, last])]}</p>EURL`\n\\end{lstlisting}\n\\caption[An example of a TLM being applied to a generalized literal form]{An example of a TLM being applied to a generalized literal form. The literal body, in green, is initially left unparsed according to the language's context-free syntax.}\n% \\vspace{-5px}\n\\label{fig:first-tsm-example}\n\\end{figure}\n\nGeneralized literal forms subsume a variety of common syntactic forms because the context-free syntax of the language only defines which outer delimiters are available. \\emph{Literal bodies} (in green in Figure \\ref{fig:first-tsm-example}) are otherwise syntactically unconstrained and left unparsed. For example, the \\li{#\\dolla#html} TLM is free to use an Ur/Web-inspired HTML syntax (compare Figure \\ref{fig:first-tsm-example} to Figure \\ref{fig:urweb}.) This choice is not imposed by the language definition. Generalized literal forms have no TLM-independent meaning.\n% Because the context-free syntax is never extended, syntactic conflicts are not a concern.\n\n% The semantics delegates control over the parsing and expansion of each literal body to the applied TLM during a semantic phase called \\emph{typed expansion}, which generalizes the usual typing phase. %As such, the semantics can take the type and binding structure of the surrounding program into account when validating the expansion that the TLM programmatically generates to ensure that clients can answer critical questions related to types and binding, like those enumerated in Section \\ref{sec:abs-reasoning-intro}. Clients need not have knowledge of the implementation of the TLM or of the generated expansion, i.e. there are useful principles of syntactic abstraction.\n\nThe primary technical challenge has to do with the fact that the applied TLM needs to be able to parse terms out of the literal body for inclusion in the expansion. We refer to these as \\emph{spliced terms}. For example, Figure \\ref{fig:first-tsm-example-marked} reveals the locations of the spliced expressions in Figure \\ref{fig:first-tsm-example} by coloring them black. We have designed our system so that a figure like this, which presents a \\emph{segmentation} of each literal body into spliced terms (in black) and characters parsed in some other way by the applied TLM (in color), can always be automatically generated no matter how each applied TLM has been implemented. \n\n\\begin{figure}[h]\n\\begin{lstlisting}[numbers=none,xleftmargin=0px]\n$html `SURL<p>Hello, {[EURLjoin ($str ' ') ($strlist [firstSCSS,ECSS last])SURL]}</p>EURL`\n\\end{lstlisting}\n\\caption{The segmentation of the example from Figure \\ref{fig:first-tsm-example}}\n\\label{fig:first-tsm-example-marked}\n\\end{figure}\n\nNotice that both arguments to \\li{join} are themselves of TLM application form -- the TLMs named \\li{#\\dolla#str} and \\li{#\\dolla#strlist} are applied to generalized literal forms  delimited by quotation marks and square brackets, respectively. The bracket-delimited literal form, in turn, contains two spliced expressions of variable form -- \\li{first} and \\li{last}.\n \n % We design our mechanism such that these locations can easily be determined from the output of the TLM. This is essential for our hygiene mechanism, and it is also useful in that this information can be presented to the user (e.g. as shown in Figure \\ref{fig:first-tsm-example-marked}). %As such, we must develop a mechanism where 1) the positions of spliced subterms can be determined without examining the macro implementation (e.g. so that they can be presented to the user differently by an editor or pretty-printer, ;  and 2) the hygiene mechanism must give only portions of the expansion that correspond to these spliced subterms access to the application site context. \n\n\n\nTLMs come equipped with useful principles of syntactic abstraction. We will more precisely characterize these abstract reasoning principles as we proceed. For now, to develop some intuitions, consider Figure \\ref{fig:K-tsm-example}, which uses TLMs to express the ``unreasonable'' example from Figure \\ref{fig:K-dialect}.\n\\begin{figure}[h]\n\\vspace{-3px}\n\\begin{lstlisting}[numbers=none,xleftmargin=0px]\n  val w = compute_w ()\n  val x = compute_x w\n  val y = $kquery `SURL(!R)@&{&/EURLxSURL!/:2_!EURLxSURL}'!R}EURL`\n\\end{lstlisting}\n\\vspace{-5px}\n\\caption{TLMs make examples like the one from Figure \\ref{fig:K-dialect} more reasonable.}\n\\vspace{-3px}\n\\label{fig:K-tsm-example}\n\\end{figure}\n\n\\noindent\nWithout examining the expansion of Line 3, we can reason as follows:\n\n\\begin{enumerate}\n\\item \\textbf{(Responsibility)} The applied TLM, \\li{$kquery}, is solely responsible for typed expansion of the literal body. \n\\item \\textbf{(Segmentation)} By examining the segmentation, we know that the two instances of \\li{x} on Line 3 are parsed as spliced expressions, whereas \\li{R} is parsed in some other way peculiar to this form.\n\\item \\textbf{(Capture)} The system prevents capture, so the spliced expression \\li{x} must refer to the binding of \\li{x} on Line 2 -- it cannot capture an unseen binding introduced in the expansion of Line 3.\n\\item \\textbf{(Context Dependence)} The system enforces context independence, so the expansion of Line 3 cannot  rely on the fact that, for example, \\li{w} is in scope.\n\\item \\textbf{(Typing)} An explicit type annotation on the definition of \\li{$kquery} determines the type that every expansion it generates will have. We will see an example of a TLM definition in Chapter \\ref{chap:uetsms}. \n\nMoreover, each segment in the segmentation also comes paired with the type it is expected to have. This information is usually not necessary to reason about typing, but it can be conveyed to the programmer upon request by the program editor if desired. %TLM definitions follow the usual scoping rules, so it is easy to ``jump to the definition'' of \\li{$kquery}.\n\\end{enumerate}\n\n% The primary technical challenge has to do with the fact that the applied TLM needs to be able to parse terms out of the literal body for inclusion in the expansion. We refer to these as \\emph{spliced terms}. For example, Figure \\ref{fig:first-tsm-example-marked} reveals the locations of the spliced expressions in Figure \\ref{fig:first-tsm-example} by coloring them black. We have designed our system so that a figure like this, which presents a \\emph{segmentation} of each literal body into spliced terms (in black) and characters parsed in some other way by the applied TLM (in green), can always be automatically generated no matter how each applied TLM has been implemented. \n\n\n% \\begin{figure}[h]\n% \\begin{lstlisting}\n% PElement Nil Seq(\n% \tTextNode \"Hello, \", \n% \tSeq(TextNode (join(\" \", Cons(first, Cons(second, Nil)))), \n% \tTextNode \"!\"))\n% \\end{lstlisting}\n% \\caption{The desugaring.}\n% \\end{figure}\n\n\n% There is also no ambiguity with regard to which TLM has control over each form, and searching for the definition of a TLM is no more difficult than searching for any other binding, i.e. there are well-defined scoping rules.\n\n% In other words, TLMs maintain a useful notion of syntactic abstraction. %More specifically, TLMs maintain a \\emph{hygienic binding discipline}, meaning that questions Questions 4 and 5 above were concerned with are disallowed entirely. \n% We will, of course, make this notion more technically precise as we continue.\n\n\\subsection{Outline}\n% The remainder of this document is organized as follows.\n\nAfter introducing necessary background material and summarizing the related work in greater detail in Chapter \\ref{chap:background}, we formally introduce TLMs in Chapter \\ref{chap:uetsms} by integrating them into a simple language of expressions and types. The introductory examples above can be expressed using the language introduced in Chapter \\ref{chap:uetsms}. \n\n% In the remaining chapters, we enrich the language developed in Chapter \\ref{chap:uetsms} with advanced features based on those found in full-scale general-purpose languages like ML and Scala, and enhance our TLM mechanism with these new features.\n\nIn Chapter \\ref{chap:uptsms}, we add structural pattern matching to the language of Chapter \\ref{chap:uetsms} and introduce \\emph{pattern TLMs}, i.e. TLMs that generate patterns rather than expressions.\n\n% We next develop a more sophisticated account of TLMs in Chapters \\ref{chap:ptsms} and \\ref{chap:static-eval}, with the aim of working out details necessary to integrate TLMs into full-scale general-purpose languages like ML or Scala. %These two chapters constitute Part \\ref{part:parametric-tsms} of our contributions.\n\nIn Chapter \\ref{chap:ptsms}, we equip the language of Chapter \\ref{chap:uptsms} with type functions and an ML-style module system. We then introduce \\emph{parametric TLMs}, i.e. TLMs that take type and module parameters. Parameters serve two purposes:\n\\begin{enumerate}\n\\item They enable TLMs that operate not just at a single type, but over a type- and module-parameterized family of types. For example, rather than defining a TLM \\li{#\\dolla#strlist} for string lists and another TLM \\li{#\\dolla#intlist} for integer lists, we can define a single parametric TLM \\li{#\\dolla#list} that operates uniformly across the type-parameterized family of list types. \n\\item They allow the expansions that TLMs generate to refer to application site bindings in a context independent manner. \n\\end{enumerate}\nWe also demonstrate support for partial parameter application in TLM abbreviations, which decreases the syntactic cost of this explicit parameter passing style. Figure \\ref{fig:first-ptsm-example-marked} demonstrates all of these features.\n\n\\begin{figure}[h]\n\\begin{lstlisting}[numbers=none,xleftmargin=0px]\nlet syntax $strlist = $list string in \n$html `SURL<p>Hello, {[EURLjoin ($str ' ') ($strlist [firstSURL,EURL last])SURL]}</p>EURL`\n\\end{lstlisting}\n\\caption{The example from Figure \\ref{fig:first-tsm-example-marked} expressed using parametric TLMs}\n\\label{fig:first-ptsm-example-marked}\n\\end{figure}\n\nIn these first chapters, we assume for the sake of technical simplicity that each TLM definition is self-contained, needing no access to libraries or to other TLMs. This is an impractical assumption in practice. We relax this assumption in Chapter \\ref{chap:static-eval}, introducing a \\emph{static environment} shared between TLM definitions. We also give examples of TLMs that are useful for defining other TLMs, e.g. TLMs that implement parser generators and quasiquotation.\n\n%\\item \\textbf{Type-specific languages}, or \\textbf{TSLs}. TSLs, described \nIn Chapter \\ref{chap:tsls}, we develop a mechanism of \\emph{TLM implicits} that allows library clients to contextually designate, for any type, a privileged TLM at that type. The semantics applies this privileged TLM implicitly to unadorned literal forms that appear where a term of the associated type is expected. For example, if we designate \\li{#\\dolla#str} as the privileged TLM at the \\li{string} type and \\li{#\\dolla#strlist} as the privileged TLM at the \\li{list(string)} type, we can express the example from Figure \\ref{fig:first-tsm-example-marked} instead as shown in Figure \\ref{fig:first-tsm-example-implicit} (assuming \\li{join} has type \\li{string -> list(string) -> string}.) \n\\begin{figure}[h]\n\\begin{lstlisting}[numbers=none]\n$html`SURL<p>Hello, {[EURLjoin ' ' [firstSURL,EURL last]SURL]}</p>EURL`\n\\end{lstlisting}\n\\caption{The example from Figure \\ref{fig:first-tsm-example-marked} drawn to take advantage of TLM implicits}\n\\label{fig:first-tsm-example-implicit}\n\\end{figure}\n\n\\noindent This approach is competitive in cost with library-specific syntax dialects (e.g. compare Figure \\ref{fig:first-tsm-example-implicit} to Figure \\ref{fig:urweb}), while maintaining the abstract reasoning principles characteristic of our approach. To further demonstrate the favorable economics of this approach, Figure \\ref{fig:big-html-example} gives an example of a function that produces a value of type \\li{html}. The body of this function assumes implicit TLM designations at seven different types (the unspliced segments are typeset in a color corresponding to the type that the enclosing literal form is being checked against.) This collection of TLMs, together with the mechanism for applying them implicitly, obviates the need for a web-programming-specific syntax dialect of our language like Ur/Web. An analysis of string literals used in open source projects discovered a wide variety of other examples like this \\cite{TSLs}.\n\n\\begin{figure}[h]\n\\begin{lstlisting}[deletekeywords={for}, escapechar=@]\nfun resultsFor(searchQuery : string, page : int) : html => \n  let imageBase : url = `SURIimages.example.comEURI` in \n  let bgImage : url = `SURI$EURIimageBaseSURI$/background.pngEURI` in \n  `SHTML<html>\n  <head>\n    <title>Search Results</title>\n    <style>{EHTML{SCSS\n      body { background-image: url({ECSSbgImageSCSS})} }\n      .search { background-color: {ECSSdarken(`SCOLOR#aabbccECOLOR`, `SPCT10%EPCT`)SCSS} }\n    ECSS}SHTML}</style>\n  </head><body>\n    <h1>Results for {[EHTMLsearchQuerySHTML]}</h1>\n    <div class=\"search\">\n      Search again: {EHTMLsearchBox \"SSTRGo!ESTR\"SHTML}\n    </div>\n    {EHTMLformatResults (db, \n       `SSQLSELECT * FROM products WHERE {ESQLsearchQuerySSQL} iSHTMLEHTMLn titleESQL`,\n       10, page)SHTML}\n  </body>\n  </html>EHTML`\n\\end{lstlisting}\n\\caption{A non-trivial example demonstrating implicit TLM application at seven different types: \\li{SURIurlEURI}, \\li{SHTMLhtmlEHTML}, \\li{SCSScssECSS}, \\li{SCOLORcolorECOLOR}, \\li{SPCTpercentageEPCT}, \\li{SSTRstringESTR} and \\li{SSQLsqlESQL}}\n\\label{fig:big-html-example}\n\\end{figure}\n%\\item \\textbf{Metamodules}, introduced in Sec. \\ref{sec:metamodules}, reduce the need to primitively build in the type structure of constructs like records (and variants thereof),  labeled sums and other interesting constructs that we will introduce later by giving library providers programmatic ``hooks'' directly into the semantics, which are specified as a \\emph{type-directed translation semantics} targeting a small \\emph{typed internal language} (introduced in Sec. \\ref{sec:VerseML}). %For example, a library provider can implement the type structure of records with a metamodule that:\n%\\begin{enumerate}\n%\\item introduces a type constructor, \\lstinline{record}, parameterized by finite mappings from labels to types, and defines, programmatically, a translation to unary and binary product types (which are built in to the internal language); and \n%\\item introduces operators used to work with records, minimally record introduction and elimination (but perhaps also various functional update operators), and directly implements the logic governing their typechecking and translation to the IL (which builds in only nullary and binary products). \n%\\end{enumerate}\n%We will see direct analogies between ML-style modules (which our mechanisms also support) and metamodules later.\n%\\end{enumerate} \n\n\n% As vehicles for this work, we will define a small programming language in each of the three parts just mentioned, each building conceptually upon the previous language. All of our formal contributions are relative to these small languages.\n\nWe conclude in Chapter \\ref{chap:conclusion} with a discussion of the present limitations of TLMs, and outline various directions for future work.\n\n\\subsection{Thesis Statement}\nIn summary, this work defends the following statement:\n\n\\begin{quote}\nA programming language (in the ML tradition) can give library providers the ability to %meta\\-pro\\-gram\\-matic\\-ally \nprogrammatically control the parsing and expansion of expressions and patterns of generalized literal form such that clients can reason abstractly about responsibility, segmentation, types and binding. %These  primitives are  expressive enough to subsume the need for a variety of primitives that are, or would need to be, built in to comparable contemporary languages.\n\\end{quote}\n\n\\section{VerseML}\n\nThe code examples in this document are written in a new full-scale functional language called VerseML.\\footnote{We distinguish VerseML from Wyvern, which is the language described in our prior publications about some of the work that we will describe, because Wyvern is a group effort evolving independently.} VerseML is the language of Chapter \\ref{chap:tsls}  extended with some additional conveniences that are commonly found in other functional languages (in particular, in the ML family of languages) and, notionally, orthogonal to TLMs (e.g. higher-rank polymorphism \\cite{conf/icfp/DunfieldK13}, signature abbreviations, and syntactic sugar that is not library-specific, e.g. for curried functions.) %VerseML is, as its name suggests, a conceptual descendent of ML. It diverges from other dialects of ML that have a similar type structure in that it has a bidirectional type system \\cite{Pierce:2000:LTI:345099.345100} (like, for example, Scala \\cite{OdeZenZen01}) for reasons that have to do with the mechanism of TLM implicits described in Chapters \\ref{chap:tsls} and \\ref{chap:ptsms}. \n%The reason we will not follow Standard ML \\cite{mthm97-for-dart} in giving a complete formal definition of VerseML in this work is both to emphasize that the primitives we introduce are ``insensitive'' to the details of the underlying type structure of the language (so TLMs can be considered for inclusion in a variety of languages, not only dialects of ML), and to avoid distracting the reader (and the author) with definitions that are already well-understood in the literature and that are orthogonal to those that are the focus of this work. \nWe will not formally define these features mainly to avoid unnecessarily complicating our presentation with details that are not essential to the ideas introduced herein. As such, all examples written in VerseML should be understood to be informal motivating material for the subsequent formal material. %We anticipate that future full-scale language specifications will be able to combine the ideas  in the proposed work without trouble. %The purpose of the work being proposed is to serve as a reference for those interested in the new constructs we introduce, not to serve as a language specification. \n%We will give a brief overview of these languages are organized in Sec. \\ref{sec:VerseML}.\n\n%TLMs, like other macro systems, perform \\emph{static code generation} (also sometimes called \\emph{static} or \\emph{compile-time metaprogramming}), meaning that the relevant rules in the static semantics of the language call for the evaluation of \\emph{static functions} that generate term encodings. Static functions are functions that are evaluated statically, i.e. during typing. %Library providers write these static functions using the VerseML \\emph{static language} (SL).  \n%Maintaining a separation between the static (or ``compile-time'') phase and the dynamic (or ``run-time'') phase is an important facet of VerseML's design. % static code generation. %We will  also introduce a simple variant of each of these primitives that leverages VerseML's support for local type inference to further reduce syntactic cost in certain common situations. \n\n\\section{Disclaimers}\nBefore we continue, it may be prudent to explicitly acknowledge that eliminating the need for syntax dialects would indeed be asking for too much: certain syntax design decisions are fundamentally incompatible with others or require coordination across a language design. We aim only to diminish the need for syntax dialects by finding a reasonable ``sweet spot'' in the design space, not to give control over all design decisions to library providers. %We summarize some of the situations that we explicitly do not consider here in Sec. \\ref{sec:future-work}. % out a larger design space within a single language, VerseML.%a subset of constructs that can be specified by a semantics of a certain ``shape'' specified by VerseML (we will make this more specific later). %There is nothing ``universal'' about VerseML.\n\nIt may also be prudent to explicitly acknowledge that library providers could use TLMs  to define syntactic forms that are ``in poor taste.'' In practice, programmers should defer to established community guidelines before defining their own TLMs (following the example of languages that support operator overloading or \\emph{ad hoc} polymorphism using type classes \\cite{Hall:1996:TCH:227699.227700,conf/popl/DreyerHCK07}, which also have some potential for ``abuse'' or ``overuse''.) %For most programmers, using VerseML will not require explicitly defining a TLM on their own.%be substantially different from using a language like ML or one of its dialects. \nThe majority of programmers should very rarely need to define a TLM on their own. The reasoning principles that we will develop ensure that even poorly designed TLMs cannot prevent clients from reasoning abstractly about the behavior of a program.\n\n%Finally, VerseML is not designed as a dependently-typed language like Coq, Agda or Idris. %because these languages do not maintain a phase separation between ``compile-time'' and ``run-time.'' This phase separation is useful for programming tasks (where one would like to be able to discover errors before running a program, particularly programs that may have an effect) but less so for theorem proving tasks (where it is mainly the fact that a pure expression is well-typed that is of interest, by the propositions-as-types principle). \n", "meta": {"hexsha": "fc9980b4627c99ed5028f78e32c65847d01defde", "size": 77186, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "intro.tex", "max_stars_repo_name": "cyrus-/thesis", "max_stars_repo_head_hexsha": "18df98bb9eea243f361558102d6331e8caab306d", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2016-02-08T10:04:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T14:57:05.000Z", "max_issues_repo_path": "intro.tex", "max_issues_repo_name": "cyrus-/thesis", "max_issues_repo_head_hexsha": "18df98bb9eea243f361558102d6331e8caab306d", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-04-19T22:34:20.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-20T19:45:26.000Z", "max_forks_repo_path": "intro.tex", "max_forks_repo_name": "cyrus-/thesis", "max_forks_repo_head_hexsha": "18df98bb9eea243f361558102d6331e8caab306d", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-04-19T22:24:32.000Z", "max_forks_repo_forks_event_max_datetime": "2016-04-19T22:24:32.000Z", "avg_line_length": 132.8502581756, "max_line_length": 1151, "alphanum_fraction": 0.7893141243, "num_tokens": 17799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3031501573425136}}
{"text": "% !TEX TS-program = xelatex\n% !TEX encoding = UTF-8 Unicode\n\\documentclass[11pt,a4paper]{article}\n\\usepackage{amsmath,amssymb}\n\\usepackage{empheq}\n\\usepackage[semibold]{ebgaramond}\n\\usepackage[cmintegrals,cmbraces]{newtxmath}\n\\usepackage{ebgaramond-maths}\n\\usepackage{bm}\n\\usepackage[OMLmathrm, OMLmathsfit, rmdefault=mdugm]{isomath}\n\\usepackage{tocbibind}\n\n\\makeatletter\n  \\DeclareSymbolFont{ntxletters}{OML}{ntxmi}{m}{it}\n  \\SetSymbolFont{ntxletters}{bold}{OML}{ntxmi}{b}{it}\n  \\re@DeclareMathSymbol{\\leftharpoonup}{\\mathrel}{ntxletters}{\"28}\n  \\re@DeclareMathSymbol{\\leftharpoondown}{\\mathrel}{ntxletters}{\"29}\n  \\re@DeclareMathSymbol{\\rightharpoonup}{\\mathrel}{ntxletters}{\"2A}\n  \\re@DeclareMathSymbol{\\rightharpoondown}{\\mathrel}{ntxletters}{\"2B}\n  \\re@DeclareMathSymbol{\\triangleleft}{\\mathbin}{ntxletters}{\"2F}\n  \\re@DeclareMathSymbol{\\triangleright}{\\mathbin}{ntxletters}{\"2E}\n  \\re@DeclareMathSymbol{\\partial}{\\mathord}{ntxletters}{\"40}\n  \\re@DeclareMathSymbol{\\flat}{\\mathord}{ntxletters}{\"5B}\n  \\re@DeclareMathSymbol{\\natural}{\\mathord}{ntxletters}{\"5C}\n  \\re@DeclareMathSymbol{\\star}{\\mathbin}{ntxletters}{\"3F}\n  \\re@DeclareMathSymbol{\\smile}{\\mathrel}{ntxletters}{\"5E}\n  \\re@DeclareMathSymbol{\\frown}{\\mathrel}{ntxletters}{\"5F}\n  \\re@DeclareMathSymbol{\\sharp}{\\mathord}{ntxletters}{\"5D}\n  \\re@DeclareMathAccent{\\vec}{\\mathord}{ntxletters}{\"7E}\n\\makeatother\n\n\\usepackage{array}\n\\usepackage{enumitem}\n% to produce a comma between multiple footnotes / https://tex.stackexchange.com/questions/40072/incompatibility-between-footmisc-option-multiple-and-hyperref/62091#62091\n\\let\\oldFootnote\\footnote\n\\newcommand\\nextToken\\relax\n\\renewcommand\\footnote[1]{%\n    \\oldFootnote{#1}\\futurelet\\nextToken\\isFootnote}\n\\newcommand\\isFootnote{%\n    \\ifx\\footnote\\nextToken\\textsuperscript{,}\\fi}\n\n\\defaultfontfeatures{Ligatures=TeX} % makes this a feature for all selected fonts\n\\usepackage{esint}\n\\usepackage{polyglossia}\n\\setmainlanguage{english}\n\\usepackage[text={18cm,26cm},centering]{geometry} % \n\\usepackage{natbib}\n\\usepackage{graphicx}\n\\graphicspath{{./pics/}}\n\\usepackage{wrapfig}\n\\usepackage{mdframed}\n\\usepackage{lipsum}\n\\usepackage[usenames,dvipsnames,svgnames,table]{xcolor}\n\\usepackage{hyperref}\n\\usepackage{url}\n\\usepackage[export]{adjustbox}\n\n\\hypersetup{\n  colorlinks,\n  citecolor=bleuSU,\n  linkcolor=bleuSU\n}\n\\definecolor{bleuSU}{RGB}{26,39,101}\n\n\\usepackage[normalem]{ulem}\n\\makeatletter\n\\renewcommand*{\\uuline}{%\n  \\bgroup\n  \\UL@setULdepth\n  \\markoverwith{%\n    \\lower\\ULdepth\\hbox{%\n      \\kern-.03em%\n      \\vtop{%\n        \\hrule width.2em%\n        \\kern 0.6pt % distance between the two underlines\n        \\hrule\n      }%\n      \\kern-.03em%\n    }%\n  }%\n  \\ULon\n}\n\\makeatother\n\\setlength{\\ULdepth}{-2pt}  % distance from double underline to letter\n\n\\usepackage{environ}\n\\newtoggle{corrige}\n\n\\NewEnviron{answer}{%\n  \\iftoggle{corrige}\n    {\\begin{mdframed}\\textbf{Answer: } \\BODY\\end{mdframed}}\n    {}%\n  }\n\n\\newcommand{\\delS}{\\delta S}\n\\newcommand{\\delA}{\\delta A}\n\\newcommand{\\delh}{\\delta h}\n\\newcommand{\\delt}{\\delta t}\n\\newcommand{\\delz}{\\delta z}\n\\newcommand{\\delbx}{\\delta \\matrixsym x}\n\\newcommand{\\lp}{\\left(}\n\\newcommand{\\rp}{\\right)}\n\\newcommand{\\itA}{\\textit A}\n\\newcommand{\\itB}{\\textit B}\n\\newcommand{\\dAB}{\\mathcal D_{AB}}\n\\newcommand{\\bA}{\\matrixsym A}\n\\newcommand{\\bff}{\\matrixsym{f}}\n\\newcommand{\\bF}{\\matrixsym{F}}\n\\newcommand{\\bj}{\\matrixsym{j}}\n\\newcommand{\\bJ}{\\matrixsym J}\n\\newcommand{\\bn}{\\matrixsym{n}}\n\\newcommand{\\bN}{\\matrixsym N}\n\\newcommand{\\bP}{\\matrixsym{P}}\n\\newcommand{\\br}{\\matrixsym r}\n\\newcommand{\\bt}{\\matrixsym t}\n\\newcommand{\\be}{\\matrixsym e}\n\\newcommand{\\bu}{\\matrixsym u}\n\\newcommand{\\bv}{\\matrixsym v}\n\\newcommand{\\bw}{\\matrixsym w}\n\\newcommand{\\bx}{\\matrixsym x}\n\\newcommand{\\pd}[2]{\\frac{\\partial #1}{\\partial #2}}\n\\newcommand{\\D}[2]{\\frac{D #1}{D #2}}\n\\newcommand{\\dd}[2]{\\frac{\\mathrm d #1}{\\mathrm d #2}}\n\\newcommand{\\dA}{\\mathrm dA}\n\\newcommand{\\dV}{\\mathrm dV}\n\\newcommand{\\dS}{\\mathrm dS}\n\\newcommand{\\prg}[1]{\\paragraph{$\\rhd$ #1}}\n\\newcommand{\\alphaijkl}{\\alpha_{ijkl}}\n\\newcommand{\\Aijkl}{A_{ijkl}}\n\\newcommand{\\delij}{\\delta_{ij}}\n\\newcommand{\\sigij}{\\sigma_{ij}}\n\\newcommand{\\sigji}{\\sigma_{ji}}\n\\newcommand{\\sigxy}{\\sigma_{xy}}\n\\newcommand{\\matL}{\\mathcal L}\n\\newcommand{\\matO}{\\mathcal O}\n\\newcommand{\\matS}{\\mathcal S}\n\\newcommand{\\kij}{k_{ij}}\n\\newcommand{\\tensor}[1]{\\smash{\\uuline{#1}{}}}\n\\setlength{\\parindent}{0pt} % remove indent\n  \n\\begin{document}\n\\setlength{\\unitlength}{1cm}\n\\noindent\n\\parbox{\\textwidth}{\n\\textsc{\nSorbonne Université  \n\\hfill\nYear 2021-2022\n}\n}\n\\parbox{\\textwidth}{\n\\textsc{\nFaculté des Sciences\n\\hfill\nPhysics of Fluids \\& Nonlinear Physics\n}\n}\n\n\\begin{center}\n\\Large\n\\textbf{Hydrodynamics} \\\\ \n\\textsl{Tutorial 1: fluid motion} \\\\[1ex]\n\\end{center}\n\n%\\vspace{5mm}\n\\section{Dimensional analysis}\n\\togglefalse{corrige}\n\n\\paragraph{$\\rhd$ Imbibition.}  \n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[height=5cm,valign=m]{capillaryrise.JPG}\n    \\hspace{1cm}\n    \\includegraphics[valign=m,page=2]{lucas.pdf}\n    \\caption{\\textbf{Maximal ascension.} Left: the maximal height for capillary ascension depends on tube radius $R$. Right: maximal height $h$ observed for the capillary rise of ethanol in tubes of different radii $R$ (data from the authors).}\n    \\label{fig:jurin}\n\\end{figure}\nA narrow capillary tube is brought into contact with a wetting liquid. The liquid spontaneously rises in the tube up to a height $h$ (figure~\\ref{fig:jurin}). This height depends a priori on the \\textit{surface tension} $\\gamma$ ($[\\gamma] = \\mathsf{MT}^{-2}$), gravity $g$, density $\\rho$ and on the tube radius $R$ :\n\\begin{equation}\nh = f(\\gamma, \\rho, g, R)\n\\end{equation}\n\\begin{enumerate}\n\\item Using the characteristic scales $\\rho$, $g$ and $R$, show that the previous functional relation can be rewritten as:\n\\begin{equation}\n\\mathrm \\pi = \\mathcal F(\\mathrm \\pi_1),\n\\end{equation}\nwhere $\\mathrm \\pi$ corresponds to the nondimensional height (the observable), and $\\mathrm\\pi_1$ to the non-dimensional surface tension. Write the expression for $\\mathrm\\pi$ and $\\mathrm\\pi_1$ (that we will take proportional to $h$ and $\\gamma$ respectively).\n\\begin{answer}\n\\begin{equation*}\n\\pi = \\frac{h}{R} \\quad \\text{ and } \\quad \\pi_1 = \\frac{\\gamma}{\\rho g R^2}\n\\end{equation*}\n\\end{answer}\n\n\\item Experiments and physical analysis show that $\\mathcal F(x) = 2x$. What is the scaling law of $h$ with respect to $R$ ? Is it compatible with the experimental results reported~\\ref{fig:jurin} ?\n\\begin{answer}\nWe have $h = \\frac{2\\gamma}{\\rho g R}$ therefore $h \\propto \\frac{1}{R}$, compatible with the experimental results.\n\\end{answer}\n\\end{enumerate}\n\n\\paragraph{$\\rhd$ Molecular diffusion.} A drop of dye is delicately deposited in a liquid. Due to constant molecular motion and collisions, the area expands by \\textit{diffusion} -- a process whose efficiency is characterised with the diffusion coefficient $D$ (of dimension $[D] = \\mathsf{L^2T^{-1}}$). \n\\begin{enumerate}[resume]\n\\item Using dimensional analysis show that the dye drop spreads following a square root law at long times $R(t) \\propto t^{1/2}$.\n\\begin{answer}\n$h = a \\sqrt{Dt}$\n\\end{answer}\n\\end{enumerate}\n\\paragraph{$\\rhd$ Turbulent diffusion.} \\textit{(from \\citet{Eggers2015})}. We consider again the previous experiment but now the liquid is vigorously stirred, so as as to create turbulent motions stirring and mixing the dye. This process is a priori much more efficient than simple molecular diffusion, so that we neglect the latter in the following. The stirring intensity is characterised with $\\varepsilon$, the energy quantity per unit time and mass in the liquid. \n\\begin{enumerate}[resume]\n\\item what is the dimension of $\\varepsilon$ ?\n\\begin{answer}\n$[\\varepsilon] = \\mathsf{L}^2\\mathsf{T}^{-3}$\n\\end{answer}\n\n\\item Show that the drop area now grows according to\n\\begin{equation}\nR(t) = A \\lp \\varepsilon t^3\\rp^{1/2},\n\\end{equation}\nwhere $A$ is a dimensionless universal constant. This result is the signature of a process much more efficient than molecular diffusion, and known as \\textit{Richardson's law} \\citep{Richardson1926,Eggers2015}.\n\\end{enumerate}\n\n\n\\section{Starting plane shear flow}\n\\begin{figure}[h]\n\\begin{center}\n\\includegraphics{transient_couette.pdf}\n\\end{center}\n\\caption{\\textbf{Transient of a Couette flow}. Several successive velocity profiles are shown here as a function of the nondimensional time $\\bar t = \\nu t / h^2$.}\n\\end{figure}\n\n\\noindent We are interested here in the setting up of a fluid flowing in between two parallel plates of infinite extension when one of them is suddenly set into motion \\citep{Batchelor1967,Ockendon1995}. The plates are separated with a distance~$h$. At $t=0$ the upper plate is abruptly set into motion at velocity $\\matrixsym U = (U,0,0)$. The fluid, at rest until that moment, starts progressively to move due to momentum diffusion until it reaches the Couette steady-state. Note also that there is no imposed pressure gradient and that momentum diffusion is the only cause for fluid motion. The dynamic viscosity of the fluid is noted~$\\mu$, the kinematic viscosity $\\nu$ and we neglect the action of gravity. We will consider an translation-invariant evolution along the two directions parallel to the plates (this amounts to consider a \\textbf{parallel} flow) and we will also suppose that the flow is \\textbf{incompressible}\\footnote{Over very short times of the order $h/c$ with $c$ the sound celerity in the fluid, this hypothesis can be invalidated. But we can put figures to get an idea by taking e.g. water as a working fluid ($c\\simeq 1500 \\text{m}\\cdot\\text{s}^{-1}$) and $h = 1 \\text{cm}$ as the distance between the plates. The acoustic timescale. is then of the order of 7 $\\mu$s to be compared with the diffusive timescale exceeding a minute (7 orders of magnitude apart!). Moreover it is quite possible that in the experimental setup the starting of the plate cannot be considered impulsive over the acoustic timescale.}.\n\\begin{enumerate}\n    \\item Propose an estimation of the order of magnitude of the viscous shear stress exerted on one of the plate in the steady limit, along with an estimation of the typical transient timescale.\n\\begin{answer}\nThe viscous shear stress $\\tau$ corresponds to the product between viscosity and the wall shear, that we can estimate here with $U/h$.\n We therefore get;\n $$\n \\tau \\sim \\mu \\frac{U}{h}.\n $$\nThe typical transient timescale is a \\textbf{diffusive} timescale (vertical diffusion of horizontal momentum) and is $h^2/\\nu$.\n\\end{answer}\n    \\item Write down the equations expressing mass and momentum conservation (using scalar projections), along with the boundary conditions and the initial condition of the problem. Beware of neglecting the unsteady terms.\n     \\item Nondimensionalise the equations using the natural scales of the problem by setting $y = h \\bar y, u = U \\bar u$ and $t = h^2 \\bar t / \\nu$. \n    \\begin{answer}\n    We get :\n    $$\n    \\pd{\\bar u}{\\bar t} = \\frac{\\partial^2 \\bar u}{\\partial \\bar y^2},\n    $$\n    associated to \n    \\begin{empheq}[left=\\empheqlbrace]{alignat=2}\n&\\text{bottom plate no-slip condition} :\\qquad &  \\bar u(0,\\bar t) = 0,\\nonumber \\\\\n&\\text{upper plate no-slip condition} :\\qquad & \\bar u(1,\\bar t) = 1,\\nonumber\\\\\n&\\text{initial condition} :\\qquad & \\bar u(\\bar y,0) = 0.\\nonumber\n\\end{empheq}\n    \\end{answer}\n    \\item In the steady limit, determine the flow profile $\\bar u_\\text{couette}(\\bar y)$ along with its gradient, and deduce the dimensioned value of the wall shear stress both at the bottom and at the top plate. \n\\end{enumerate}\n\\noindent We now seek to describe the onset of this flow with a solution of the form:\n\\begin{equation}\n\\bar u(\\bar y,\\bar t) = \\bar u_\\text{couette}(\\bar y) + \\bar u_\\text{unst}(\\bar y,\\bar t)\n\\label{eq:profile}\n\\end{equation}\n\\begin{enumerate}[resume]\n    \\item Injecting the profile~(\\ref{eq:profile}) in the equations for motion, obtain a new set of equations and boundary conditions for $\\bar u_\\text{unst}(\\bar y,\\bar t)$. What is the initial condition for  $\\bar u_\\text{unst}(\\bar y,0)$ ? \n    \\begin{answer}\n    Same equation (linearity). Homogeneous BC and $\\bar u_\\text{unst}(\\bar y,0) = -\\bar y$.\n    \\end{answer}\n    \\item We look for a solution by using the variable separation technique, i.e. we pose $\\bar u_\\text{unst}(\\bar y,\\bar t) = f(\\bar y)g(\\bar t)$. Obtain the equations governing $f(\\bar y)$ and $g(\\bar t)$ along with the general form of the solutions.\n    \\item Show that the application of the boundary conditions imposes a quantisation condition on the solutions. Deduce the form of the velocity profile as a Fourier series whose coefficients are yet to be determined.\n    \\item Demonstrate the orthogonality relation:\n    $$\n     \\int_0^1 \\sin(n \\pi x) \\sin(m \\pi x) \\, \\mathrm dx = \\begin{cases*} 0 & if  $n \\neq m$ \\\\ \\frac{1}{2} & if $n = m$ \\end{cases*}\n    $$\n    \\item Exploit the orthogonality relation so as to determine the flow transient, then show that the dimensioned expression for the velocity field is\n    \\begin{equation}\n    u(y,t) = \\frac{U y}{h} + \\sum_{n=0}^\\infty \\frac{2U}{n\\mathrm\\pi} \\lp-1\\rp^n \\sin\\lp\\frac{n\\mathrm\\pi y}{h}\\rp e^{-\\frac{n^2 \\mathrm\\pi^2}{h^2}\\nu t}\n    \\end{equation}\n\\item What is the asymptotic solution? What is the first correction for long times?\n\\end{enumerate}\n\\subsection*{Short project}\nDesign a numerical code to solve this problem. Compare the numerical solution with the (truncated) series. How many terms are required? Does this number change with time? Represent the evolution of the bottom wall shear stress with time and compare it with the truncated series. Same question but for the \\textit{upper} plate. Why does it fail at short times? \n%    \\item Calculer l'évolution de la contrainte de cisaillement sur la plaque du haut et sur la plaque du bas. \n%    \\item Tracer numériquement le champ de vitesse et l'évolution de la contrainte en tronquant la série. Combien de termes est-il nécessaire de garder pour avoir une représentation convergée ? \n\n\\section{Poiseuille flow in a tube of arbitrary shape}\n\\noindent A fluid flows in a tube of uniform section (not necessarily circular) under the action of a constant pressure gradient $-\\frac{\\partial p}{\\partial x}$. We suppose that the flow is fully established (no $x$ dependency) and parallel ($v = w = 0$). For given tube section $A$ and pressure gradient, we look for the tube geometry that minimises the total viscous force exerted on the wall \\citep{Ockendon1995}.\n\\begin{figure}[h]\n\\begin{center}\n\\includegraphics[width=9cm]{poiseuille_shapes.pdf}\n\\end{center}\n\\caption{A family of tubes of constant section, but with different shapes.}\n\\end{figure}\n\n\\begin{enumerate}\n\\item Show the relation:\n$$\n\\mu\\left( \\frac{\\partial^2 u}{\\partial y^2} + \\frac{\\partial^2 u}{\\partial z^2} \\right) = c.\n$$\nWhat is the the meaning of $c$ here?\n\\item Show that the total viscous force exerted on the wall takes the following expression:\n$$\n\\oiint_{\\partial D} \\mu \\frac{\\partial u}{\\partial n} \\, \\mathrm dS.\n$$\n%    $$\n%   \\sigma_{xj} (0,n_y,n_z)=\\sigma_{xy} n_y + \\sigma_{xz} n_z = \\mu ( u_{x,y} ) n_y + \\mu u_{x,z} n_z = \\mu u_{,n}\n%    $$\n\\item On using Green's formulae:\n$$\n\\iiint_V \\Psi \\nabla^2 \\varphi\\,\\mathrm dV = - \\iiint_V \\nabla \\Psi \\cdot \\nabla \\varphi\\,\\mathrm dV + \\oiint_{\\partial V} \\Psi \\frac{\\partial \\varphi}{\\partial n} \\, \\mathrm dS,\n$$\nAnswer the question.\n\\item Show that we could retrieve this result in a blink by conducting a force balance on a fluid portion.\n\\begin{answer}\nThe viscous force per unit length is $\\pd{p}{x} A$, and does not depend on the tube shape. This result might be surprising at first because we could have expected a more ``dented'' tube, or a tube exposing a higher contact surface, to bear a higher viscous force.\nBut actually if we consider a fluid portion of length $L$ flowing steadily, we see that the driving force $-\\pd{p}{x} A L$ has to be balanced with a resistive force $\\tau L$ ($\\tau$ being the viscous stress integrated on a section). Hence the result.\n\\end{answer}\n\n\\end{enumerate}\n\\bibliographystyle{jfm}\n\\bibliography{biblio_tuto}\n\\end{document}", "meta": {"hexsha": "eedece226f2ad9fe3934b27d613017e989b40cd5", "size": 16151, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tutorials/tutorial_01.tex", "max_stars_repo_name": "antko/physics-of-fluids", "max_stars_repo_head_hexsha": "307f1c25c59345943a4bce90e031ced5dde105bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tutorials/tutorial_01.tex", "max_issues_repo_name": "antko/physics-of-fluids", "max_issues_repo_head_hexsha": "307f1c25c59345943a4bce90e031ced5dde105bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorials/tutorial_01.tex", "max_forks_repo_name": "antko/physics-of-fluids", "max_forks_repo_head_hexsha": "307f1c25c59345943a4bce90e031ced5dde105bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.471875, "max_line_length": 1539, "alphanum_fraction": 0.7294285184, "num_tokens": 4965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3031501573425136}}
{"text": "\\documentclass[main.tex]{subfiles}\n\n\\begin{document}\n\\sloppy\n\\chapter{Introduction}\n\nThe human brain has been a long standing topic of research in the scientific community. Many attempts have been made to model its behaviour using methods such as modeling the low level architecture on a neurological level \\cite{frank1957perceptron} and a more abstract stochastic approach using  Bayesian inference \\cite{bourlard1988auto} .\n\nBeing able to create a general form of artificial intelligence will allow for smarter robots that can learn and perform tasks in order to assist humans. However, robots are not easy to program and each task requires a specialised set of instructions for it to be executed properly. Such programs have various (dynamical) models and control policies embedded into them in order for the robot to function properly. Intrinsic system parameters, policies and controller gains are something which the human brain can learn over time \\cite{friston2010free,knill2004bayesian, kawato1999internal}, yet a robot obviously has no such capability and tedious tweaking is required for everything to work properly.\n\nThere have been many attempts to reconcile the alluring anatomy of the brain and mathematical algorithms \\cite{friston2003learning}, yet the most prevalent approach is generative modelling which has been widely adopted by the machine learning community. By combining the flexibility of \\textit{neural networks} and probability theory these unsupervised learning algorithms can synthesise numbers, landscapes and even faces by learning latent features from training data and are called \\textit{Deep Generative Models}. They are believed to hold the promise to general AI \\cite{Goodfellow-et-al-2016}, yet  their application in robotics is scarce. Therefore, we are interested in applying such learning algorithms in the robotics field and more specifically in visuomotor control of an autonomous agent.\n\n\\section{Background}\nIn order to properly justify our research in this literature study we will define a problem space that needs solving. We will assume a 6-DOF robotic arm equipped with a camera as our autonomous agent. We wish for the agent to reach towards a visual point in space without having any knowledge of how the image is mapped to its internal kinematics. In other words, the agent has to figure out the positions of its joints based on image data which is also known as visual servoing. In addition, the agent should have some sort of \\textit{generative model} which is a learned, low dimensional and stochastic representation of its kinematic model. In fact, the reason to have a low dimensional, or latent, representation is because storing all the possible states as high dimensional images makes computations difficult and impractical. \n\n\nVisual servoing has been explored extensively yet the implementations are generally model based \\cite{hosoda1994versatile} or use reinforcement learning \\cite{levine2016learning}. In other words, so far no application exists where a complex 6-DOF agent learns a generative kinematic model.\n\n\n\\section{Research Goal}\n\nThis practical example will be used for exploration and justification of various techniques. A set of requirements and conditions will be presented that can help us maintaining focus. However, in order to allow for further research and extension the research question will be formulated more generally.\n\nIn this literature study we aim to answer the following research question: \n\\begin{quotation}\n\\begin{tabular}{|p{10cm}}\n\\textit{What unsupervised deep generative model allows an agent to infer latent system features by observing rich sensory data?}\n\\end{tabular}\n\\end{quotation}\n\nFormulating this question in such a general way allows us to explore a wider range of literature, yet the requirements for the application keeps the research focussed. We have purposefully used the term \\textit{latent system features} to indicate that the technique we propose should be valid for a wide range of applications such as both \\textit{kinematics} and \\textit{dynamics}. For simplicity we will not consider dynamics since robotic arms are well behaved in that respect [].\n\nWe define a set of requirements against which we can compare and contrast various techniques found in literature. Considering the learning nature of the brain using a generative model we also seek a technique that \\textbf{i)} can infer a latent low dimensional representation from high dimensional sensory input such as images. Furthermore, the technique should allow us to \\textbf{ii)} sample a generative model in order to make predictions. Such predictions could be used to estimate the velocity based on two images, for example.\nFinally, since we are dealing with physical actuated systems the technique must also \\textbf{iii)} provide tractable, robust and stable training dynamics.\n\nIn sections 2 and 3 we will discuss the background and relevance of neural networks and generative models, respectively. Section 4 investigates current state of the art techniques which have the potential of answering our research question. Section 5 compares and contrasts these methods against our set of requirements. We finally conclude with a short summary of this literature study and the chosen technique.\n\n\\chapter{Neural Networks}\nNeural networks are the foundation of the machine learning field of research and have been studied for more than half a century. A wide variety of neural networks exists, each using a different architecture to perform specific tasks. We will focus on unsupervised learning which consists predominantly of optimisation problems (e.g. gradient descent).  \n\nRecall that our agent is a robotic arm supplied with a camera. In terms of this literature study we aim to find a network (or a combination thereof) that can be used in vision based applications. In addition we want our agent to learn a low dimensional representation of its kinematics from the high dimensional visual data. Therefore, the network  must perform a form a dimensionality reduction. Since the landscape of neural networks is vast it is unpractical to give an overview of all possible types. Consequently, this chapter identifies only several neural networks and aims to justify why and how they are relevant to the research goal.\n\nIt is assumed that the reader has some working knowledge on neural networks. Therefore, the basic fundamentals of neural networks will not be covered in depth.\n\n\\section{Deep Neural Network}\nA neural network is a set of connected nodes (neurons) which can have multiple inputs where each node then outputs a single value. Each connection has a weight and a bias. Each node takes the sum of the weights and biases connected to that node and is fed through some activation function. A clear graphical representation can be seen in figure \\ref{fig:ann}\n\n[figure of neural network]\n\nSingle layer neural networks, which only have one input layer and one output layer are only capable of modelling linear functions. In order to model non-linear functions, which is necessary in vision applications, we have to use \\textit{deep} neural networks \\cite{LeCun2015}. Such networks are characterised by having one or more \\textit{hidden} layers in addition to the regular input and output layer.\n\nWhat makes neural networks so powerful is their capacity to optimise their weights and biases through back-propagation. By optimising a cost function through, for example, a gradient descent method we can find the weights and biases that give us the most optimal results.\n\nDeep neural networks with back propagation give us a very strong foundation which we can extend and apply to more exotic architectures.\n\n\n\\section{Autoencoder}\nWe have seen that deep neural nets form a solid foundation for various other types of networks. One of the goals of this literature study is to find a neural network that can learn a low dimensional (latent) representation from high dimensional data (e.g. images).\n\nAn autoencoder (AE) is used for such \\textit{dimensionality reduction} applications. An AE network has a symmetric hourglass shape where the input and output layers have the same amount of nodes. The layers in between keep shrinking towards the center. The goal of the autoencoder is to ensure that the output is as similar as possible to the input. The hourglass shape forces an autoencoder to only extract relevant information which can be stored in a latent space (encoding) consisting of only several neurons as seen in figure \\ref{fig:ae}. The latent representation is then fed through a decoder network which reconstructs the input. The network is penalised for errors in reconstruction. More formally, an AE learns a function $h$ with weights and biases, $w$ and $b$, that tries to approximate $x$ as much as possible, as shown in equation \\eqref{eq:ae_approx}.\n\n\\begin{equation}\n\\label{eq:ae_approx}\n  h_{w,b}(x) \\approx \\hat{x}\n\\end{equation}\n\n% TODO: Add autoencoder figure\n\nTo summarise, autoencoders enable us to learn a low dimensional representation of our high dimensional data. Once an autoencoder is trained it can also be used to reconstruct corrupt images or interpret realistic scenes from simulated training data used in transfer learning \\cite{zhuang2015supervised,kandaswamy2014improving}. This can be very beneficial when training our agent in a simulation, for example, and then using the trained network on a physical system.\n\n\n\n\\section{Boltzmann Machine}\n[explanation is not entirely clear here, nor is the connection to the rest of this document]\n\nSimilar to an autoencoder, a Restricted Boltzman Machine (RBM) aims to reconstruct data in an unsupervised manner. As shown in figure \\ref{fig:boltzmann_machine} an RBM has a single hidden layer and a layer which functions as both the input and output layer (i.e. visible units) which depends on the training phase. Interestingly, the RBM learns a \\textit{stochastic} representation of the input data instead of storing variables in a latent space like the autoencoder does. This is exceedingly interesting since the we would have to deal with the variability of natural data as seen in images \\cite{chen2003continuous}. \n\nDuring the forward pass of the training phase the activation value $a_j$ for a hidden node is determined by some probabilistic distribution $p(a_j|x_i;w_{ij})$ where $x_i$ is a visible node and $w_{ij}$ is the weight connecting node $i$ to node $j$. The type of this probability distribution is dependant on the implementation of the RBM. \n\nNow on the backward pass we let the RBM reconstruct the input and compare it to the real data, just as with an autoencoder. This comparison can be done with a Kullbackk-Leibler (KL) divergence where we try to minimise the difference in the two probability distributions, as shown in figure \\ref{fig:kl_div}. We keep updating the weights until the optimisation converges or a maximum number of iterations (epochs) has been reached.\n\nThus, an RBM is a probabilistic spin on the AE where the RBM tries to \\textit{infer} latent features of the dataset in order to make predictions when presented with new but comparable data. This is also called generative learning or \\textit{generative modeling} which will be explored in more detail in the next chapter. Even though this neural network is similar to an AE, the stochastic nature of an RBM can be a preferred attribute since it resembles the variability of natural data.\n\n\\section{Convolutional Neural Network}\n[Will obviously be expanded but it is trivial]\n\nImages can have very large dimensions. A simple image that is only 20x20 pixels already requires 400 input neurons. Using a Convolutional Neural Network (CNN) allows us to take a relatively large image and use a scanning window to sample the image. This greatly reduces the complexity and dimensionality of the neural networks used.\n\n\n\\chapter{Generative Models}\nIn statistics and probability theory generative models are widely used to create a probabilistic representation of a target through observed variables. These generative models are capable of generating new data points from a joint probability distribution, unlike \\textit{discriminative} models which have a conditional probability distribution.  Recall that the brain also uses inference and generative modelling to make predictions of the world which makes this method an interesting area of research.\n\nLately, generative models have gained a lot of traction in the machine learning community due to their ability to infer features from a probabilistic dataset where not all variables can be observed \\cite{Goodfellow-et-al-2016}. An agent which has the capability to infer latent features of the world or itself and make predictions by sampling a generative model could lead to more interesting behaviour in terms of autonomous systems. For example, our agent could use such a generative model to learn admissible kinematic states based on training data in the form of images.\n\nIn this chapter we will discuss the general math behind generative models, some examples on how they are being used in the machine learning community and why it is relevant in this literature study.\n\n\\section{Joint Probability Distribution}\nTake $z$ to be a random \\textit{unobserved} variable and $x$ to be a random \\textit{observed} variable.\nA generative model is capable of generating new values for combinations of $x$ and $z$ and is given by\n\\begin{align}\n    \\label{eq:generative_model}\n    p(x,z) = p(x|z)p(z).\n\\end{align}\n\nIn words, given a prior distribution, $p(z)$ and the likelihood, $p(x|z)$ we can generate new data for combinations of $x$ and $z$. However, the question remains how we obtain $p(x|z)$, the distribution which gives us observable variables based on the hidden variables. This might seem non-intuitive since we wish to learn the latent features from observations. This is true, but in order to make \\textit{predictions} on the observed variables (posterior) we need to find this likelihood $p(x|z)$ as seen in Bayes' rule\n\\begin{equation}\n  \\label{eq:bayes_rule}\n  \\underbrace{p(x|z)}_{\\text{likelihood}} = \\dfrac{\\underbrace{p(z|x)}_{\\text{posterior}} \\underbrace{p(x)}_\\text{evidence}}{\\underbrace{p(z)}_\\text{prior}}.\n\\end{equation}\n\nIn terms of machine learning we see from equation \\eqref{eq:bayes_rule} that expressions where the hidden variable $z$ is given are obtained through training. On the other hand, expression with $x$ given use inference to obtain $z$.\n\nGoing back to the predictive nature of the brain, we are interested in knowing the true (unobservable) state of the world based on observed variables. Essentially, we are interested in the posterior distribution $p(z|x)$. With this we can \\textit{infer} a model of the world from which we can then sample to make predictions. This is what Bayesian inference is used for.\n\n\\section{Bayesian Inference}\nWhen dealing with a dynamical system of which one or more states can not be directly measured one could apply Bayesian inference in order to infer that hidden state based on a model. A well known example is the Kalman Filter \\cite{bishop2001introduction}. We are interested in the underlaying technique of the Kalman Filter, namely Bayesian inference in order to infer hidden variables from high dimensional data. Practically speaking, for our agent we would like to infer the kinematical model based on images.\n\nFrom the previous section we have seen how we can use a generative model in order to produce new values for $x$ and $z$. However, this generative model first has to be trained in order for it to produce anything meaningful. For example, a trained generative model could be able to predict the position of a 3-DOF robotic arm from two \\textit{unseen} consecutive visual representations \\cite{watter2015embed}.\n\nA generative model is able to do so by sampling the posterior probability distribution which is dependent on the marginal likelihood as shown in \\eqref{eq:inference-integral}.\n\\begin{align}\n    \\label{eq:inference-integral}\n    p(x) = \\int p(x|z)p(z)dz\n\\end{align}\n\nEven though the integral in equation \\eqref{eq:inference-integral} can be solved theoretically, it is far from practical when dealing with the amount of data generally used in machine learning. In other words, evaluating the marginal likelihood (or evidence) in \\eqref{eq:inference-integral} is intractable leading \\eqref{eq:bayes_rule} by substitution to also become intractable.\n\nHappily, recent advances in machine learning produced solutions which can approximate the intractable true posterior $p(z|x)$ making inference possible.\n\n\\section{Variational Inference}\n\nAs we have seen Bayesian inference is a powerful tool to use statistics in order to find the probability of an outcome based on a generative model. However, the integral over the likelihood as shown in equation \\eqref{eq:inference-integral} is intractable causing the true posterior, $p(z|x)$ to also be intractable. In order to infer the kinematics of our robotic agent and be able to generate new configurations we need to be able to build the generative model and approximate the posterior. Variational inference gives us the tools for that. \n\nLet $p(z|x)$ be a probability distribution which we can not fully observe, only sample. In order to find $p(z)$ we need to sample for all combinations of $x$ and $z$ which is intractable, as we have seen. There are sampling methods such as Markov chain Monte Carlo (MCMC), yielding exact samples from the target distribution, but these are very computationally heavy and are best suited for smaller datasets \\cite{blei2017variational}. Variational inference (VI) is a method that approximates the probability density and therefore does not guarantee the same accuracy as MCMC. However, the nature of VI allows for very fast and efficient optimisation techniques such as gradient search. Assuming the geometry of the distribution to be approximated is moderately complex and well behaved, the inaccuracy of VI is acceptable and its speed then outweighs the benefits of other slower methods such as MCMC.\n\nIn order to solve the intractability of \\eqref{eq:inference-integral} and \\eqref{eq:bayes_rule} we can introduce a recognition model $q(z|x)$. The recognition model is an approximation of the true distribution $p(z|x)$. Let the recognition model and posterior distribution be parameterised by $\\phi$ and $\\theta$, respectively. For example, if the posterior is a normal distribution $\\mathcal{N}(\\mu,\\sigma^2)$ parameterised by $\\theta$ then the set is given by $\\theta = \\{\\mu, \\sigma\\}$. This will lead to the following notation $q_\\phi ( \\cdot)$ for the approximation and $p_\\theta (\\cdot)$ for the true distribution.\n\nThe posterior distribution is approximated by varying the parameter $\\phi$ such that the KL-divergence between $q_\\phi(\\cdot)$ and $p_\\theta(\\cdot)$ are minimised up to an added constant called the lower bound (ELBO or $\\mathcal{L}$). Formally we solve the optimisation problem given by\n\n\\begin{equation}\n\\label{eq:elbo}\n  \\log p(x) = \\argmin_{q_{\\phi}(z)} D_{KL}\\infdiv{q_\\phi(z)}{p_\\theta(z|x)} + \\mathcal{L}(\\phi,\\theta)\n\\end{equation}\n\nwhere $\\mathcal{L} \\leq \\log p_\\theta(x)$ since the KL-divergence is always $ \\geq 0$. This shows that this optimisation will always be an approximation since \\eqref{eq:elbo} will always have an added constant in the form of the lower bound $\\mathcal{L}$. Finding the right parameters now becomes gradient search problem which can be handled by neural networks for fast convergence and parallel computing \\cite{rezende2014stochastic,kingma2013auto}. \n\n\\chapter{Techniques}\nSo far we have investigated the fundamentals of neural networks, their implementations and statistics theory in terms of generative models. We have seen that generative models give us the ability to model the variance of natural data such as images. We can use such models to then make predictions. This is exceedingly interesting in robotics where we could use state of the art machine learning (ML) techniques in the control of robots. Returning to our goal, we want our agent to be able to infer its kinematics from images during training and then perform some action when a prior is given.\n\nIn literature two very prominent techniques are apparent that can potentially help us with our desired goal. Variational Autoencoders and Generative Adversarial Networks are both neural network based generative models \\cite{kingma2013auto,goodfellow2014generative}. These techniques are researched heavily in the machine learning community where they can perform a wide array of tasks such as image synthesis, action forecasting from static images \\cite{walker2016uncertain} and latent dynamic embedding for control \\cite{watter2015embed}. This chapter will give an overview of the workings of both techniques. Since MNIST \\footnote{MNIST is a database containing images of handwritten digits from 0-9 and is widely used as a benchmarking dataset for machine learning. \\url{http://yann.lecun.com/exdb/mnist/}} is a go-to benchmarking dataset for ML algorithms we will also identify the performance of the VAE and GAN based on this dataset. For each technique we will discuss their workings after which we identify publications that are relevant to our research for our autonomous agent.\n \n\\section{Variational Autoencoder}\nIn the previous sections we have discussed the neural network architecture for an autoencoder and variational inference in generative modelling. One of the problems in Bayesian inference is the intractability of the posterior. A variety of algorithms exist which approximate that probability density by means of variational inference. However, these methods are relatively slow or require an analytical solution of the expectations. An efficient method is proposed by \\cite{kingma2013auto} which is the Variational Autoencoder (VAE), a generative modelling neural network. Its power lays in the ability to jointly learn the parametrisation of the posterior distribution $q_\\phi(z|x)$ and the likelihood $p_\\theta(x|z)$.\n\n\\subsection{Background}\nSimilarly to a regular autoencoder, the VAE tries to reconstruct the input but it does so by minimising two loss functions: the latent loss given by the same equation as seen in equation \\eqref{eq:elbo}, and the generation loss which is a simple mean square error given by\n\\begin{equation}\n  \\lVert x-\\hat{x} \\rVert^2\n\\end{equation}\nwhere $x$ is the real data and $\\hat{x}$ is the generated data. \n\n[insert relevance to RBM]\n\n\\begin{figure}[bt]\n    \\centering\n    \\includegraphics[width=0.95\\textwidth]{VAE2}\n    \\caption{A Variational Autoencoder ingests data into an encoder network which learns $\\mu$ and $\\sigma$ to parameterise the recognition model $q_\\phi(z|x)$. The decoder then samples from the latent space which is constrained to be $\\mathcal{N}(0,1)$ and tries to reconstruct the input by minimising the KL-divergence between $q$ and $p$.}\n    \\label{fig:vae}\n\\end{figure}\n\nRecall from the previous chapter that in variational inference we try to optimise the parameters for the recognition density $q_\\phi(z|x)$ and the likelihood $p_\\theta(x|z)$. The VAE consists out of two neural networks, an encoding network and a decoding network, as seen in figure \\ref{fig:vae}. When a VAE is used for inferencing latent variables from images often convolutional networks are used to reduce the network size. In short, a VAE learns the following two things: the parameters for the recognition model $\\phi$ and the parameters for the likelihood $\\theta$ which are used to sample the latent space $z$.\n\nThe encoder network of the VAE represents the posterior approximation $q_\\phi(z|x)$. The input of the network is a dataset from which we want to learn the latent features and the output is the set of parameters $\\phi = \\{\\mu,\\sigma\\}$ assuming a Gaussian distribution in the dataset. More formally, the encoder network represents a probability distribution given by\n\\begin{equation}\n  \\label{eq:recognition_model}\n  q_\\phi(z|x) = \\mathcal{N}(z|\\mu(x), \\sigma(x)^2)\n\\end{equation}\n \nwhere the parameters $\\mu$ and $\\sigma$ can be seen as arbitrary mapping functions learned by the neural network. The objective of the encoder neural network is to minimise the KL-divergence between the learned latent space and the unit Gaussian as shown below.\n\\begin{equation}\n  \\argmin D_{KL}\\infdiv{\\mathcal{N}(z|\\mu(x), \\sigma(x)^2)}{\\mathcal{N}(0,1)}\n\\end{equation}\n\nThis constraint forces the VAE to learn sufficiently varied latent variables and not just how to memorise the dataset.\n\nOn the right hand side of figure \\ref{fig:vae} we have the decoder network that represents the likelihood $p_\\theta(x|z)$. Since we let the decoder samples from the simple latent space $z \\sim \\mathcal{N}(0,1)$, the complexity of the dataset is instead captured by the neural network $p_\\theta(x|z)$\\cite{zhao2017towards}. Both $\\theta$ and $\\phi$ are learned by back-propagating the error from the latent and generation loss through the neural network. Recall the generative model is given by \\eqref{eq:generative_model}, thus by sampling the likelihood and the latent space we can reconstruct the image.\n\nAs many other ML techniques, the VAE is benchmarked using the MNIST dataset. Given an MNIST dataset the VAE can learn the latent features of the numbers from which it can then \\textit{generate} a new but similar dataset. When the latent space $z$ is projected in 2D space (which is used for demonstrating latent feature learning) we can see how the VAE interprets the numbers and how the latent features are linearly interpolated.\n\n[MNIST figure]\n\n\\subsection{Applications}\nVariational autoencoders have seen a widespread adoption in the machine learning community for learning latent features in high dimensional data. Aside from \\textit{dreaming} of landscapes and handwritten digits there are many applications which demonstrate the use of VAEs and how it can be used in our research.\n\nRecall that our agent is a robotic arm with 6 degrees of freedom and has a camera. Our goal is for that robot to learn its own internal kinematics in the form of a generative model. This would mean that once we present the agent with a prior belief (a position in space in the form of an image) we should be able to generate a trajectory towards that point \\textit{without} performing direct inverse kinematics. The VAE could be a very useful tool to achieve our goal. Therefore, we will explore some examples in literature. \n\nIn a recent publication a VAE is trained with thousands of videos after which it is able to predict the trajectory of a set of pixels in a static image \\cite{walker2016uncertain}. As is usual in vision applications, a convolutional neural network was used to reduce the computation time and dimensionality of the network. Considering our research, a trained VAE that can predict the next state of a robotic arm from an image can be interesting. \n\nAnother important publication shows how a Kalman filter can be learned using multiple techniques including a VAE \\cite{krishnan2015deep}. The authors propose the Deep Kalman Filter (DKF) which extends the inference network with an action variable $u$ such that recognition model becomes $q_\\phi(\\vec{z} \\mid \\vec{x}, \\vec{u})$ where the arrow indicates a sequence. The neural network is parametrised by $\\theta = {\\alpha, \\beta, \\kappa}$ which allow the authors to learn the mapping functions for the latent space and observation space.\n\\begin{equation}\n  \\label{eq:deep_kalman}\n  \\begin{split}\n  z_t &\\sim \\mathcal{N}\\left(G_\\alpha (z_{t-1}, u_{t-1},\\Delta_t), S_\\beta(z_{t-1}, u_{t-1},\\Delta_t) \\right) \\\\\n  x_t &\\sim \\Pi\\left(F_\\kappa(z_t)\\right)\n  \\end{split}\n\\end{equation}\n\nThe generative model for the Kalman filter is given by equation \\eqref{eq:deep_kalman} where the latent space is normally distributed by the given non linear mapping functions, $G_\\alpha$ and $S_\\beta$, which are dependent on the previous latent state, action and time difference. By restricting the functional forms of the mapping functions, different Kalman filters can be trained demonstrating the flexibility of this framework. This method are a derivative thereof can be extremely beneficial for our autonomous agent when control actions have to be predicted. However, this is under the assumption that the DKF is trained with both sensory observations \\textit{and} corresponding actions.\n\nFinally, another promising example is a publication that has made an effort to learn the latent dynamics of various systems on which stochastic optimal control \\cite{watter2015embed} could be performed. Their method Embed to Control (E2C) uses multiple VAEs and an iterative linear quadratic regulator (iLQR) in order to learn the swing up of an inverted pendulum. In short, they accomplish this by stacking two images of a simulated pendulum which represent their states at $s_t$ and $s_{t+1}$ and training the VAE with a large dataset of such stacks. The VAE is then able to learn the state space representation of the pendulum which the iLQR controller can then use, given a desired state, to learn a swing up. \n\nThe E2C method is a promising algorithm which has the potential to be extended to larger degrees of freedom, allowing for control of complex robotic systems using raw sensory information. As long as the latent space has the Markov property, stochastic optimal control can be applied to a latentx kinematic model which has been learned in an unsupervised manner \\cite{matsubara2014latent}. \n\n\\section{Generative Adversarial Networks}\n[Mention that GANs can not model discrete data]\n\nAnother well known deep generative model is the generative adversarial network (GAN). It is a technique based on a zero-sum game where two neural networks are competing against each other \\cite{goodfellow2014generative}. Similarly to a VAE, a GAN learns a generative model from training data as well. However, a GAN does not require an inferencing network.\n\n\\subsection{Background}\n\nRecall from chapter 3 that the generative model is given by equation \\eqref{eq:generative_model} for which we need multiple dependent equations leading to intractable calculations. Where the VAE circumvents that by using a recognition model to approximate the posterior, the GAN completely cuts out the inference step. It does so by simultaneously training two neural networks, the generator ($G$) and the discriminator ($D$), which play a minimax game as shown in figure \\ref{fig:gan_minmax}. The aim of the game is for the generator to create sufficiently believable samples that the discriminator can no longer discern what is real and what is generated. \n\n\\begin{figure}[h]\n    \\centering\n    \\includegraphics[width=0.95\\textwidth]{gan_minmax}\n    \\caption{A generative adversarial net samples from a simple gaussian distribution. Both the generator and discriminator neural nets are optimized. The Jensen-Shannon divergence is used to calculate the loss between the distributions which is then back-propagated through the networks. needs citation: https://sthalles.github.io/intro-to-gans/}\n    \\label{fig:gan_minmax}\n\\end{figure}\n\nThe generator network of a GAN is fairly simple. The GAN does not make any approximations to the posterior, unlike the VAE, instead it simply assumes the latent space distribution $p(z)$ to be random noise given by $\\mathcal{N}(0,\\mathbf{I})$ where $\\mathbf{I}$ is the identity matrix. The dimensionality of the identity matrix and thus that of the latent space is heuristically determined.\n\nThe generator network represents a mapping to the data space as $G_\\theta(z)$ where $\\phi$ are the parameters of the neural network. Statistically, the generator would represent the likelihood $p(x|z)$ which combined with the prior $p(z)$ is the generative model as we've seen in equation \\eqref{eq:generative_model}.\n\nThe discriminator network $D_\\gamma(x)$, parameterised by $\\gamma$, is a lot simpler. It outputs a probability scalar indicating whether its input $x$ came from the real data or the generative model $G_\\theta(z)$. In words, the generator constantly tries to improve itself to \"fool\" the discriminator network. On the other hand, the discriminator network constantly tries to become better at catching the generator network. Both networks are jointly trained with the following value function $V(G,D)$:\n\\begin{equation}\n\\label{eq:gan_minimax}\n  \\min_{G} \\max_{D} V(D,G) = \\mathbb{E}_{x\\sim p_{data}(x)} [\\log D(x)] + \\mathbb{E}_{z\\sim p_z(z)}[\\log(1-D(G(z)))].\n\\end{equation}\n\nAs with most ML techniques the GAN is also benchmarked on the MNIST dataset. We see in figure \\ref{fig:gan_mnist} that the GAN performs really well in generating new handwritten digits. Also, linearly interpolating between the coordinates in $z$-space shows that the algorithm has clearly learned latent features as shown in figure \\ref{fig:gan_mnist_interp} .\n\n\\begin{figure}[htb]\n    \\centering\n    \\includegraphics[width=0.95\\textwidth]{gan_interp}\n    \\caption{Digits obtained by interpolating between latent variables.}\n    \\label{fig:gan_mnist_interp}\n\\end{figure}\n\n\n\\subsection{Applications}\nAs with many other ML techniques, the GAN too was originally benchmarked by synthesising images. Fortunately, it has seen immense adoption and widespread use in the scientific community, probably more so than the VAE. Some examples will be discusses in this section demonstrating the power of GANs.\n\n[will be expanded with literature i'm still trying to understand]\n\nFinally we discuss an interesting publication on using GANs for learning forward and inverse models for motor control of a 2-DOF simulated robotic arm \\cite{lenninger2017generative}. The model is trained by feeding it simulated current $S_t$ and future $S_{t+1}$ states caused by an input $u_t$. The states of the links are defined as vectors are given by $S_{t} = \\{X_t(\\theta_t),\\theta_t, \\dot{\\theta}_t\\}$, where $X_t(\\theta_t$) is the position of the end-effector. The future state $S_{t+1}$ is calculated by the simulator. During training the generator tries to reconstruct the future state and the discriminator compares it to ground truth from the simulator. Ultimately, both the forward model and the inverse model of the arm are learned under the generative model. This allows the arm to either find the control input that has caused a change in state or find the next state given a control input.\n\n\\chapter{Conclusion}\nOur goal is to find an unsupervised technique which can learn latent system features to be used in robotic applications, more specifically in applications requiring vision. In this literature study we have investigated  two important machine learning techniques, namely, variational autoencoders (VAE) and generative adversarial networks (GAN). These deep generative models are actively researched in the ML community and are believed to hold the promise for true AI. Combining such a state of the art learning algorithm in the field of robotics could pave the way to fully autonomous systems. In terms of our proposed robotic agent, we seek a technique which allows it to learn its internal kinematics in an unsupervised manner after which it can perform a task given a prior belief in the form of an image.\n\nIn this literature study we have found that the variational autoencoder is the most suitable method to proceed with our research purposes. This is according to the three main criteria which have been defined in the introduction and will be discusses next.\n\nFirstly, VAEs are explicitly designed to learn latent features from high dimensional data. Our aim is to observe raw sensory information (e.g. images) and learn a reduced representation. This \\textit{inferencing} step allows us to extract meaningful information from a scene after which we can make predictions. In contrast to VAEs, GANs have no support for this requirement unless modified \\cite{mescheder2017adversarial,chen2016infogan}. For example, if we wish to supply our agent with a prior belief, for a VAE we could represent that as a simple image of which the latent features can be inferred. For a GAN this becomes somewhat complicated as the prior belief has to be directly embedded into the latent space since there is no inference step. \n\nSecondly, both VAE and GAN learn a generative model from which we can sample in order to make predictions based on a prior belief. In this case both techniques are equal as they both have a generative model which can be sampled and are flexible in terms of scalability. However, it is important to note that VAEs require differentiation through the hidden units due to the nature of the training algorithm \\cite{goodfellow2014generative}. Thus VAEs can not have discrete latent variables. How this will affect the discrete nature of digital sensors such as encoders is unknown.\n\nThirdly, VAEs have a robust training algorithm and good convergence. Even though both VAEs and GANs have their advantages and disadvantages, their training dynamics are very different which are crucial in our robotic application. In literature we see that VAEs take longer to train than GANs. Where the GAN has $O(n)$ time-complexity the VAE requires $O(n \\log n)$ for training to complete []. In addition we see that  in contrast to GANs, VAEs produce blurry images in many benchmarks such as CIFAR-10. It is still unknown what causes the blurriness. In terms of robotic application we do not know how this effect will be translated but it is imaginable that a VAE will have a larger variance between possible states as opposed to a GAN. However, this performance does not outweigh the training dynamics where the GAN falls short. Namely, GANs are notoriously hard to train \\cite{Goodfellow-et-al-2016, arjovsky2017towards}. Because the GAN tries find the Nash-equilibrium, the convergence of the gradient descent can fail under high dimensional parameters \\cite{goodfellow2014distinguishability}. It is possible to alleviate some of the issues with the GAN by using a modified training algorithm \\cite{arjovsky2017wasserstein}. Thus, stability and convergence of a VAE during training outweigh the high performance of a GAN. In the case that the performance for sharper images is deemed necessary, there are various options available \\cite{mescheder2017adversarial, rezende2015variational, salimans2015markov}.\n\nFinally, for future work we recommend further investigation of variations of the proposed methods. Machine learning is very much an active field of research and it is quite commonplace for techniques to be combined such as VAEs with GANs \\cite{mescheder2017adversarial,hu2017unifying}. In case the performance of the \\textit{vanilla} methods seem to underperform, such combinations can be investigated to improve results. In addition, generative models tend to not have an interpretable visual representation \\cite{feichtenhofer2018have}. Therefore, further investigation can be beneficial in order to better understand what such a model has learned.\n\nIn summary, variational autoencoders offer a flexible and novel way for an autonomous agent to learn latent features of its own internal system or its surroundings. If this method is coupled with an implementation for \\textit{active} exploration of the environment, this research could lead to a novel approach for creating real autonomous agents which can learn to understand the world they live in.\n\n\\newpage\n\\renewcommand\\bibname{References}\n\\bibliographystyle{unsrt}\n\\bibliography{references}\n\n\\end{document}\n", "meta": {"hexsha": "6bd173ed6d21b5f306f9d2a9f861aceb9ef45129", "size": 39491, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "content.tex", "max_stars_repo_name": "Ortix92/literature-research", "max_stars_repo_head_hexsha": "a207c5f442e7396323082a24365dc6e31a1da1bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "content.tex", "max_issues_repo_name": "Ortix92/literature-research", "max_issues_repo_head_hexsha": "a207c5f442e7396323082a24365dc6e31a1da1bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "content.tex", "max_forks_repo_name": "Ortix92/literature-research", "max_forks_repo_head_hexsha": "a207c5f442e7396323082a24365dc6e31a1da1bf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 142.0539568345, "max_line_length": 1512, "alphanum_fraction": 0.8009419868, "num_tokens": 8735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.30315014929217027}}
{"text": "\\section{Tracer particles}\n\nTracer particles are to track the Lagrangian evolution of a model fluid using discrete particles. In hydrodynamical simulations based on an Eulerian grid (including CASTRO), thermodynamic variables at a given time are derived by solving the equations of motion of a fluid between cells. Therefore, in this scheme, the physical quantities that we can access to are not discretized quantities at any given position, but rather average values over each cell. However, employing discrete particles, passively advected with the fluid flow, allows us to obtain local instantaneous thermodynamic variables, such as the temperature and the density, at well-defined positions, independent of the spatial resolution, i.e., the spatial cell size. This means that we can follow the evolution of the fluid at any given position and time. \n\n\\noindent \\noindent CASTRO provides a tracer particle scheme with useful options. In this scheme, particles are advanced using the midpoint method either with the cell-centered velocities or the face-centered velocities (Marker-And-Cell method)\\footnote{One can simplify interpolation with the cell-centered velocity. However, this can lead to decoupling of the pressure and the velocity components, possibly resulting in instability. This can be avoided with the face-centered velocity}. The number and the initial positions of particles are flexibly determined according to the purpose of a given model. \n\n\n\\section{Initializing the Particles}\n\nOne must include the tracer particles in the {\\tt GNUmakefile} by setting\n\n\\vspace{0.1in}\n\\noindent{\\tt USE\\_PARTICLES = TRUE}.\n\\vspace{0.1in}\n\n\\noindent And the particles can be initialized via\n\n\\vspace{0.1in}\n\\noindent {\\tt {\\bf castro.do\\_tracer\\_particles }}     = 1\n\\vspace{0.1in}\n\n\\noindent in the {\\tt {\\bf inputs}} file.\n\nIf one wants to investigate the evolution of fluid motions starting from specific positions (or a certain range of area or volume), one should manually specify the positions of particles by providing an input file containing the total number and the initial positions of the particles.  \nThe input file should be in the same directory where your {\\tt inputs} file is located. The name of the input file is  determined via :\n\n\\vspace{0.1in}\n\\noindent {\\tt {\\bf particles.particle\\_init\\_file =}}{\\em particle\\_file}\n\\vspace{0.1in}\n\n\\noindent Here {\\em particle\\_file} is the user-specified name of the file. The first line in this file is\nassumed to contain the number of particles.  Each line after that contains the positions in a coordinate system adopted for your model. For 3-D cartesian coordinates, \\\\\n\n$x ~y ~z$ \\\\\n\nFor example, an input file for a model fluid with 6 particles in 2-D Cartesian coordinates may look like,\\\\\n\n\\begin{lstlisting}\n6\n3.28125e+08 9.9198e+08 \n5.46875e+08 9.9198e+08 \n7.65625e+08 9.9198e+08 \n9.84375e+08 9.9198e+08 \n1.20312e+09 9.9198e+08 \n1.42188e+09 9.9198e+08 \n\\end{lstlisting}\n\nAccording to this input file, the 6 particles will be positioned at the same height (same $y$ coordinate in the second column), equally spaced in $x$ direction (the first column except for the particle number on the first line) from $3.28\\times10^{8} {\\rm ~cm}$ to $1.42\\times 10^{9} {\\rm ~cm}$.\n\n\n\n\n\n\\section{Output file}\n\\label{particles:output_file}\n\\noindent The output files are stored in a directory whose name is determined by a variable {\\tt particles.timestamp\\_dir}. For example, if the variable is set as follows,\n\n\\vspace{0.1in}\n{\\tt  {\\bf particles.timestamp\\_dir=}} {\\em particle\\_dir},\n\\vspace{0.1in}\n\n\\noindent A directory {\\em particle\\_dir} is automatically made with the directories for the main CASTRO output file ({\\tt plt****}) once a simulation starts and the particle output files are stored inside that directory.\n\n\\vspace{0.05in}\n\\noindent The name of the output file consists of {\\tt Timestamp\\_} along with a number at the end. The number increases (typically from 00) as more processors are involved in following the trajectories of particles. In parallel computing, a computational domain is divided according to the number of processors requested. Then each processor only follows the particles on the domain assigned to that processor and records their positions and velocities at any given time in a different output file. Since it is possible for particles to move from one domain to another during the evolution, its history can be stored in different files. More output files (with larger numbers at the end of the file name) can be produced as more processors track the particles.  \n\n\\vspace{0.05in}\n\\noindent By default, the output file contains the positions and velocities of all particles at a given time, meaning [$3+ 2\\times$dimensionality] columns. For example, for particles in a 3-D domain, the columns in the output file are, \n\n\\vspace{0.1in}\n${\\rm index1}~~{\\rm index2}~~x~~ y~~ z~~ t~~ v_{\\rm x} ~~v_{\\rm y}~~ v_{\\rm z}~~ [\\rho ~~ T]$\n\\vspace{0.1in}\n\n\\noindent The first two integers correspond to the particle index and the processor number. \nOne should use the two numbers in order to identify a particle and extract its history (i.e., the trajectory in Figure \\ref{fig:particletrajectory}). \n\n\\begin{figure}[h]\n\t\\centering\n\t\\includegraphics[width=2.5in]{fluid_motion}\n\t\\includegraphics[width=2.39in]{tracer_trajectory}\n\t\\caption{A model atmosphere (\\textit{left} panel) and the trajectories of 500 particles (\\textit{right} panel) following the fluid motion on the atmosphere. The particles are initially positioned at five different heights, $y=13000\\mathrm{~km},~11000\\mathrm{~km},~ 8000\\mathrm{~km},~ 6000\\mathrm{~km}, ~38000\\mathrm{~km}$ (100 particles at each height). In the \\textit{left} panel, the arrows roughly show the fluid motion. In the \\textit{right} panel, the solid lines represent the trajectories of the particles. }\n\t\\label{fig:particletrajectory}\n\\end{figure}\n\n\n\n\\noindent One can also add the last two columns $[\\rho ~~ T]$, i.e., the local density and local temperature of fluid at the position of each particle by setting the following,\n\n\\vspace{0.1in}\n\\noindent {\\tt {\\bf particles.timestamp\\_temperature }}= 1,\\\\\n\\noindent {\\tt  {\\bf  particles.timestamp\\_density}}     = 1.\n\\vspace{0.1in}\n\n\\noindent For example, let's consider 10 particles on a domain.  If 4 out 10 particles are initially on a processor and the rest are on another processor, this means two processors are tracking the particles and two output files are produced. In the output file written by the processor with 4 particles, one can find that four lines are stored at the same time and each line corresponds to each particle info. while in the other output file for the other 6 particles, 6 lines are stored at the same time. \n\n\n\n\\vspace{0.05in}\n\n\\noindent If {\\tt {\\bf particles.write\\_in\\_plotfile=1}}, the particle data are stored in a binary file along with the main CASTRO output plotfile in directories {\\tt plt*****/Tracer/}. \n\\vspace{0.05in}\n\n\n\n\n\\subsection{Run-time Screen Output}\n\nThe verbosity written to the screen at run-time is constrolled by setting:\n\n\\noindent {\\bf particles.v } = 0 or 1 (default: 0)\\\\\n", "meta": {"hexsha": "888a7f2938448ae43f2c31527c7da3793e57a82f", "size": 7116, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Docs/Particles/Particles.tex", "max_stars_repo_name": "yingtchen/Castro", "max_stars_repo_head_hexsha": "5e9bd2f7a699a45447b92a1c9c3064f6c2e3552c", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Docs/Particles/Particles.tex", "max_issues_repo_name": "yingtchen/Castro", "max_issues_repo_head_hexsha": "5e9bd2f7a699a45447b92a1c9c3064f6c2e3552c", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Docs/Particles/Particles.tex", "max_forks_repo_name": "yingtchen/Castro", "max_forks_repo_head_hexsha": "5e9bd2f7a699a45447b92a1c9c3064f6c2e3552c", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 64.1081081081, "max_line_length": 825, "alphanum_fraction": 0.7688308038, "num_tokens": 1773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.3030952334873166}}
{"text": "\\documentclass[11pt]{article}\n%============Macros==================%\n% you don't need to change anything. start editing from main body.\n\\usepackage{amsmath,amsfonts,amssymb,amsthm, cancel, float, enumitem}\n\\usepackage{qcircuit}\n\\usepackage[margin=1in]{geometry}\n%--------------Cosmetic----------------%\n\\usepackage{mathtools}\n\\usepackage{hyperref}\n\\usepackage{fullpage}\n\\usepackage{microtype}\n\\usepackage{xspace}\n\\usepackage[svgnames]{xcolor}\n\\usepackage[sc]{mathpazo}\n\\usepackage{enumitem}\n\\setlist[enumerate]{itemsep=1pt,topsep=2pt}\n\\setlist[itemize]{itemsep=1pt,topsep=2pt}\n%--------------Header------------------%\n\\def\\course{CS 410/510 Introduction to Quantum Computing}\n\\def\\term{Portland State U, Spring 2017}\n\\def\\prof{Lecturer: Fang Song}\n\\newcommand{\\handout}[5]{\n   \\renewcommand{\\thepage}{\\arabic{page}}\n   \\begin{center}\n   \\framebox{\n      \\vbox{\n    \\hbox to 5.78in { \\hfill \\large{\\course} \\hfill }\n       \\vspace{2mm}\n       \\hbox to 6in { {\\Large \\hfill #5  \\hfill} }\n       \\vspace{2mm}\n       \\hbox to 6in { \\term \\hfill \\emph{#2}}\n       \\hbox to 6in { {#3 \\hfill \\emph{#4}}}\n      }\n   }\n   \\end{center}\n   \\vspace*{4mm}\n}\n\\newcommand{\\lecture}[4]{\\handout{#1}{#2}{#3}{#4}{{Lecture #1}}}\n\n\\def\\complex{\\mathbb{C}}\n\\def\\real{\\mathbb{R}}\n\\def\\natural{\\mathbb{N}}\n\\def\\integer{\\mathbb{Z}}\n\n\\newcommand{\\norm}[1]{\\left\\lVert#1\\right\\rVert}\n\\newcommand{\\snorm}[1]{\\lVert#1\\rVert}\n\\newcommand{\\abs}[1]{\\left\\lvert #1 \\right\\rvert}\n\\newcommand{\\ceil}[1]{\\left\\lceil #1 \\right\\rceil}\n\\newcommand{\\floor}[1]{\\left\\lfloor #1 \\right\\rfloor}\n\\newcommand{\\set}[1]{\\left\\{ #1 \\right\\}}\n\\newcommand{\\vecb}[1]{\\boldsymbol{\\vec{#1}}}\n\\newcommand{\\conj}[1]{\\overline{#1}}\n\\newcommand{\\op}[2]{#1#2#1^\\dag}\n\n\\newcommand{\\tr}{\\operatorname{Tr}}\n\\newcommand{\\se}{\\operatorname{H}}\n\\newcommand{\\vne}{\\operatorname{S}}\n\\newcommand{\\e}{\\operatorname{E}}\n\\newcommand{\\rank}{\\operatorname{rank}}\n\\renewcommand{\\det}{\\operatorname{Det}}\n\n\\newcommand{\\bra}[1]{\\langle #1 \\rvert}\n\\newcommand{\\ket}[1]{\\lvert #1 \\rangle}\n\\newcommand{\\bret}[2]{\\langle{#1}|{#2}\\rangle}\n\\newcommand{\\kret}[2]{\\ket{#1}\\bra{#2}}\n\\newcommand{\\kera}[1]{\\kret{#1}{#1}}\n\\newcommand{\\Example}[1]{{\\bf Example #1}:}\n\n\\def\\X{\\mathcal{X}}\n\\def\\Y{\\mathcal{Y}}\n\\def\\Z{\\mathcal{Z}}\n\\def\\W{\\mathcal{W}}\n\\def\\A{\\mathcal{A}}\n\\def\\B{\\mathcal{B}}\n\\def\\V{\\mathcal{V}}\n\\def\\U{\\mathcal{U}}\n\\def\\C{\\mathcal{C}}\n\\def\\D{\\mathcal{D}}\n\\def\\E{\\mathcal{E}}\n\\def\\F{\\mathcal{F}}\n\\def\\M{\\mathcal{M}}\n\\def\\R{\\mathcal{R}}\n\\def\\P{\\mathcal{P}}\n\\def\\Q{\\mathcal{Q}}\n\\def\\S{\\mathcal{S}}\n\\def\\T{\\mathcal{T}}\n\\def\\K{\\mathcal{K}}\n\\def\\L{\\mathcal{L}}\n\n\\def\\fill{   \\hfill}\n\n%=============Main Doc=================%\n\\begin{document}\n%-----Specs: change accordingly--------%\n\\def\\lecdate{May 18, 2017} % put lecture date here\n\\def\\scribe{Scribe: Asher Toback} % put your name here\n\\def\\lecnum{14} % change the lecture number\n\n\\lecture{\\lecnum}{\\lecdate}{\\prof}{\\scribe}%\n\n\\begin{center}\n{\\textsc{Version: \\today}}  \n\\end{center}\n\n%\\section{Introduction}\nSo far, we've assumed that the channels in our quantum circuits have been noiseless. Namely, that the information sent over the channel is identical to the information that is received. However, there will always be noise in real-life channels that may cause errors during transmition. In the classical setting we see these errors as bit flips in our original message. However, when we try to communicate quantum information over a quantum channel it becomes less clear what an error is, how to detect it, and how to correct it. In this paper we'll introduce the basic concepts of QECC (Quantum Error Correcting Code). We'll start by defining our Error Model, cover X-Encoding, Z-Encoding, Shor's 9-bit QECC, and arbitrary unitary QECC, and finish with a brief description of CSS Codes.   \n\n\\section{Error Models}\n\nLet's first describe how we think of communicating over a noisy channel in a classical setting. We'll be trying to communicate a bit $b\\in\\{0,1\\}$. We assume that an error occurs on the channel with probability $p\\in(0,1/2)$. Thus, we can think of our channel as:\n\n\\abovedisplayskip=0pt\\relax\n\\[\nb \\xrightarrow{\\text{Message Over a Binary Symmetric Channel} }\n\\begin{cases}\nb & \\text{ with probability } 1-p\\\\       \n1-b  & \\text{ with probability  } p            \n\\end{cases}\n\\]\n\nIn the quantum setting we similarly wish to communicate the state of our system over a channel. We know that we can represent our system state as a density matrix $\\rho$. We can then view an error on the channel as some operation $\\Phi$ occuring on our state $\\rho$ with some probability $p\\in(0,1/2)$. As this is an introduction to QECC, we'll assume that the only errors on our channel can be unitary, meaning $\\Phi = U\\rho U^\\dagger$. Our quantum error model is thus: \n\n\\abovedisplayskip=0pt\\relax\n\\[\n\\rho \\xrightarrow{\\text{Message Over a Quantum Binary Symmetric Channel}}\n\\begin{cases}\n\\rho & \\text{ with probability } 1-p\\\\       \n\\Phi\\rho  & \\text{ with probability  } p            \n\\end{cases}\n\\]\n\n\\section{Classical Solutions}\n\nThe standard way for dealing with errors in the classical setting is simply to introduce redundancies in our message. Here is basic 3-bit encoding scheme. \n\n{\n\\[0 \\xrightarrow{} 000\\]\n\\[1 \\xrightarrow{} 111\\]\n}\n\nTo decode a message we partition our received message into three bit chunks, find what the majority of each three bit section is, and assign that majority to that section. If no errors occur it's clear that we'll receive the same message we sent after decoding. However, it's also the case that if only one error occurs on a 3 bit section, then we'll also recover the original message as if no error had occured. Thus, by a simple counting argument, we see that:\n\n{\n\\[\nPr[\\text{Correct Transmission}] = (1-p)^3 + 3p(1-p)^2 = 1-(3p^2 -2p^3)\n\\]\n}\n\nAnd most importantly, when $p < 1/2$:\n{\n\\[\n1-(3p^2 -2p^3) \\leq 1 -p \n\\]\n}\n\nThus, using this encoding scheme will help the receiver receive the correct message. Now that we've demonstrated this, it's clear that we could get a better result if we simply introduce more and more redundancies into our message. Thus, we could communicate our message correctly with as high a probability as we'd like. \n\nIt's also worth nothing that, if $p>1/2$, we can simply do the same exact process as above, but at the end of the protocol we manually flip all the bits ourselves. This is due to the fact that the channel is reliable, in that we can expect it to always apply an error. Thus, we can correct for that by simply flipping all the bits at the end. However, if $p = 1/2$, then we're out of luck. The channel is just as likely to preserve our message as it is to cause on error, so we can't rely on it at all. This is clearly the worst case and represents white noise. \n\n\\section{Quantum Bit Flip Error}\n\nIt's not immediately obvious how to even approach a quantum error. Applying a unitary operation onto a quantum state can be viewed as rotating that state in the complex plane. This means there are uncountable many different types of errors that we need to correct. And, even if we knew which error were to occur, it's not immediately obvious how we could introduce redundacies like in the classical setting. Namely, we can't clone our input. \n\nTo begin tackling these issues let's first assume that the only errors that occur on our channel are X, the Pauli Matrix that represents a bit flip in the quantum setting. As a reminder, for some qubit $\\ket{\\psi} = \\alpha\\ket{0} +  \\beta\\ket{1}$:\n\n{\n\\[\\ket{\\psi} \\xrightarrow{X} \\alpha\\ket{1} + \\beta\\ket{0} \\]\n}\n\nThis is a start, but how will we deal with no cloning? It turns out there does exist a 3-bit encoding scheme which resembles the classical one which doesn't involve cloning. Namely:\n\n{\n\\[\\ket0 \\xrightarrow{X-Encoding} \\ket{000} \\]\n\\[\\ket1 \\xrightarrow{X-Encoding} \\ket{111} \\]\n}\n\nThis encoding scheme is called X-Encoding, as it will be able to correct for X errors, which we'll show shortly. First, note that, although they look similar, this encoding scheme is not: \n\n{\n\\[\\ket{\\psi} \\not\\xrightarrow{X-Encoding} \\ket{\\psi\\psi\\psi}\\]\n}\n\nIt instead works like the following. If the qubit $\\ket{\\psi} = \\alpha\\ket{0} +  \\beta\\ket{1}$, then the encoding works as follows:\n\n{\n\\[\\ket{\\psi} \\xrightarrow{X-Encoding} \\alpha\\ket{000} +  \\beta\\ket{111}\\]\n}\n\nTo see why these aren't the same, note that $(\\ket{00} + \\ket{11}) \\neq (\\ket0 + \\ket1)^{\\otimes2}$. Clearly these must be different states as the first state is maximally entangled and the other is not. \n\nNow, to achieve X-Encoding we use the following circuit.\n\n{\n\\centering\n\\includegraphics[scale=1]{X-Enc.png}\n%\\caption{}\n\\label{fig:Grammar}\n\\par \n}\n\nwhere the hollow circles are CNOT gates. It's left to the reader to verify that this behaves as intended. We now want to decode in the same way that we did in the classical setting. That is, we want to find the majority of the three qubits and assign these three qubits to be this majority instead. It turns out that this can be done, and it's done by the following circuit.\n\n{\n\\centering\n\\includegraphics[scale=1]{X-Dec.png}\n%\\caption{}\n\\label{fig:Grammar}\n\\par \n}\n\nThe last gate is the Toffoli gate, and can be thought of as a CNOT gate which depends on two control wires. Specifically, it require that both are in the state $\\ket1$ in order to apply a NOT. \n\nWith these encoding and decoding schemes let's observe that they correct an X error as claimed. We'll assume that the X error occurs on the second bit of the encoding.\n\n{\n\\[\\alpha\\ket{0} +  \\beta\\ket{1} \\xrightarrow{X-Encoding} \\alpha\\ket{000} +  \\beta\\ket{111}\\]\n\\[ \\xrightarrow{\\mathbb{I} \\otimes X \\otimes \\mathbb{I} }\\alpha\\ket{010} +  \\beta\\ket{101}\\]\n\\[\\xrightarrow{X-Decoding} (\\alpha\\ket{0} +  \\beta\\ket{1}) \\otimes \\ket{10}\\]\n}\n\nIt's left to the reader to verify that the above mappings are indeed correct. We see then that the top wire does indeed recover the original qubit, as desired! It's left to the reader to verify that this code does correct every possible X error, as long as only one error occurs in total.\n\nIt's also worth noting that the bottom two wires hold the information of the error. That is, if you measured them, you could discover which bit that the X error occurred. These are called the $syndrome$ and will be useful for future QECC.\n\nWe've thus accomplished what we set out to do, namely fix a bit flip error in the quantum setting.\n\n\\section{Quantum Phase Flip Error}\n\nWhat if an error other than a bit flip were to occur? We'll now look at the case of a Z error, or a phase flip. As a reminder, for some qubit $\\ket{\\psi} = \\alpha\\ket{0} +  \\beta\\ket{1}$:\n\n{\n\\[\\ket{\\psi} \\xrightarrow{Z} \\alpha\\ket{0} - \\beta\\ket{1}\\]\n} \n\nTo correct this error, we make an important observation. Namely: $Z\\ket+ = \\ket-$, $Z\\ket- = \\ket+$. Thus, we see that a phase flip can be thought of as a bit flip in the Hadamard basis $\\{\\ket+,\\ket-\\}$. In other words, $HZH = X$, where H is the Hadamard gate. And, since we've already corrected bit flip errors, we're essentially finished. Thus, our encoding scheme should behave as follows:\n\n{\n\\[\\ket0 \\xrightarrow{Z-Encoding} \\ket{+++} \\]\n\\[\\ket1 \\xrightarrow{Z-Encoding} \\ket{---} \\]\n}\n\nTo acheive this encoding we simply add Hadamard gates after our X-Encoding scheme:\n\n{\n\\centering\n\\includegraphics[scale=1]{Z-Enc.png}\n%\\caption{}\n\\label{fig:Grammar}\n\\par \n}\n\nOur decoding scheme similarly just adds a Hadamard gate before the X-Decoding scheme:\n\n{\n\\centering\n\\includegraphics[scale=1]{Z-Dec.png}\n%\\caption{}\n\\label{fig:Grammar}\n\\par \n}\n\nJust as before, let's say a Z-Error occurs on the second bit of our encoding. We then get:\n\n{\n\\[\\alpha\\ket{0} +  \\beta\\ket{1} \\xrightarrow{Z-Encoding} \\alpha\\ket{+++} +  \\beta\\ket{---}\\]\n\\[ \\xrightarrow{\\mathbb{I} \\otimes Z \\otimes \\mathbb{I} }\\alpha\\ket{+-+} +  \\beta\\ket{-+-}\\]\n\\[\\xrightarrow{Z-Decoding} (\\alpha\\ket{0} +  \\beta\\ket{1}) \\otimes \\ket{10}\\]\n}\n\nWhich is just what we wanted.\n\n\\section{Shor's 9-qubit QECC}\n\nWe can correct an X error and a Z error, but what if our channel's noise has the potential to apply both an X or a Z gate? Shor came up with a solution to this which is intuitive. Essentially, you feed the Z and X encodings into each other. Namely:\n\n{\n\\[Shor's: \\ket0 \\xrightarrow{Z-Encoding} \\ket{+++} \\xrightarrow{X-Encoding} (1/\\sqrt{2}(\\ket{000} + \\ket{111}))^{\\otimes3} \\]\n\\[Shor's: \\ket1 \\xrightarrow{Z-Encoding} \\ket{---} \\xrightarrow{X-Encoding} (1/\\sqrt{2}(\\ket{000} - \\ket{111}))^{\\otimes3} \\]\n}\n\nYou then X-decode this state, then Z-decode it. It turns out that this can correct 1 error on the 9-qubit encoding, which is left to the reader to verify. However, it's clear that it works due to linearity. The circuit that accomplishes these encoding and decoding schemes is as follows: \n\n{\n\\begin{figure}\n\\centering\n\\includegraphics[scale=0.65]{ShorQECC.png}\n\\caption{Shor's 9-bit QECC. All pictures from Wikipedia}\n\\label{fig:Grammar}\n\\end{figure}\n\\par \n}\n\nWhere $E$ represents the X or Z error.\n\n\\section{Arbitrary Unitary QECC}\n\nIt's natural to wonder if we can correct an error of the remaining Pauli Gate, the Y gate. Well, we know that $Y=-iXZ$. And, because we can correct $X$ and $Z$ errors, we know we can also correct Y errors. \n\nHowever, we also know that $\\forall U$ where $U$ is a unitary matrix, that $U = \\alpha I + \\beta X + \\gamma Y + \\delta Z$. Thus, as it turns out, we know there exists encoding and decoding schemes such that we can correct 1 arbitrary Unitary error.\n\n\\section{CSS Codes}\nIn this paper, we assumed that our errors were all Unitary transformations. However, we can't always make this assumption. To fix this, we use a type of QECC called CSS Codes. These general constructions are based off of classical linear ECC. The basic ideas rellies on group theory and the idea of cosets. The encoding maps certain messages into different cosets based off what the message is. We then have QECC that corrects errors just on each coset. As it turns out, given some $t\\in\\mathbb{N}$, we can correct up to $t$ errors using CSS Codes.\n\n%\\bibliographystyle{plain}\n%\\bibliography{references}\n\\end{document}\n", "meta": {"hexsha": "bd093c33e53a464420336e209c7a479448b1192e", "size": 14062, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "teaching/s17_4510_qc/170518_at_lec14.tex", "max_stars_repo_name": "fangsonghub/fangsonghub.github.io", "max_stars_repo_head_hexsha": "31a42b297a4644b307b97acd293d9111e567f5c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "teaching/s17_4510_qc/170518_at_lec14.tex", "max_issues_repo_name": "fangsonghub/fangsonghub.github.io", "max_issues_repo_head_hexsha": "31a42b297a4644b307b97acd293d9111e567f5c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-05-06T23:19:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-06T23:19:12.000Z", "max_forks_repo_path": "teaching/s17_4510_qc/170518_at_lec14.tex", "max_forks_repo_name": "fangsonghub/fangsonghub.github.io", "max_forks_repo_head_hexsha": "31a42b297a4644b307b97acd293d9111e567f5c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.8045602606, "max_line_length": 789, "alphanum_fraction": 0.7121319869, "num_tokens": 4162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3030952252287381}}
{"text": "In the tau reconstruction, $\\tauhad$ candidates are seeded from jets. Therefore, QCD events are the main source of background (BG). Nonetheless, we do not use MC simulations for these processes. Therefore, we use a \\textit{data driven method} to estimate multi-jet (MJ) background. In this section we will discuss how we derived our Multi-Jet Background (MJBG) estimation.\n\n\\subsection{Multi-Jet Background}\nTo obtain the MJBG, a variable that in principle is supposed to be uncorrelated with the shape of the MJBG is chosen. For this study, this variable is the relative sign between the charges of the $\\tauhad$ and the lepton. This defines two regions: the same sign (SS) region where $q(\\tauhad)=q(l)$ and the opposite sign region where $q(\\tauhad)=-q(l)$. Our estimate for the MJBG in the SS region is obtained by subtracting the signal and electroweak backgrounds (EWBG) contributions:\n\\begin{equation}\n\\text{MJBG}_{\\text{SS}}=\\text{Data}_{\\text{SS}}-\\text{Signal}_{\\text{SS}}-\\text{EWBG}_{\\text{SS}},\n\\label{eq19}\n\\end{equation}\nTo study the residual charge correlation, a control region (CR) for the MJBG is defined. The estimate for the MJBG in these regions is given by eq. \\ref{eq19} as well. The region described in Sec.\\ref{sec3.3}, which contains all our final selected events is called the signal region (SR). In contrast to the SR, the CR is defined by events that fail the lepton isolation criteria and that fail the Tight-ID working point criterion for the $\\tauhad$ candidate. In this region, tau candidates are required to have a looser tau-$pt$ of 25 GeV or more. This last choice was made to increase the number of candidates in the CR. The other kinematic features of the SR are maintained. A diagram showing the four regions just defined is shown in Fig.\\ref{Fig7}. Now, if we assume that charge correlation is the same in the SR and CR, we have:\n \\begin{equation}\n \\frac{\\text{MJBG}_{\\text{SR OS}}}{\\text{MJBG}_{\\text{SR SS}}}=\\frac{\\text{MJBG}_{\\text{CR OS}}}{\\text{MJBG}_{\\text{CR SS}}},\n \\end{equation}\nthen,\n \\begin{equation}\n\\text{MJBG}_{\\text{SR OS}}=\\text{MJBG}_{\\text{SR SS}}\\times \\text{RQCD}\\,\n\\label{eq36}\n\\end{equation}\nwhere $\\text{RQCD}\\equiv\\frac{\\text{MJBG}_{\\text{CR OS}}}{\\text{MJBG}_{\\text{CR SS}}}$. So, eq. \\eqref{eq36} gives the estimation of MJBG on the SROS.\n\\begin{figure}[htbp]\n\t\\centering\n\t\\includegraphics[width=0.5\\textwidth]{figures/Fig7.png}\n\t\\caption{Regions defined to estimate the MJBG contribution in the SROS region. This data-driven method is also known as the ABCD method.}\n\t\\label{Fig7}\n\\end{figure}\nTable \\ref{tab:MJ} summarises inputs into the calculation of the MJ background in the three candidate event samples. \n\n\\begin{table}[]\n\t\\resizebox{\\textwidth}{!}{%\n\t\t\\begin{tabular}{ccccc}\n\t\t\t\\rowcolor[HTML]{C0C0C0} \n\t\t\t\\textbf{Sample} & \\multicolumn{2}{c}{\\cellcolor[HTML]{C0C0C0}\\textbf{$\\mu \\tauhad$}} & \\multicolumn{2}{c}{\\cellcolor[HTML]{C0C0C0}\\textbf{$e \\tauhad$}} \\\\\n\t\t\t& 1-prong                                  & 3-prong                                 & 1-prong                                 & 3-prong                                \\\\ \\hline\n\t\t\tCR OS Data      & 476.0 $\\pm$ 22                                 & 270.0 $\\pm$ 16                               & 62.0  $\\pm$ 8                               & 39.0 $\\pm$ 6                               \\\\\n\t\t\tMC              & 28.608 $\\pm$ 4.068                               & 10.531 $\\pm$ 1.833                              & 21.058 $\\pm$ 10.808                              &              4.794 $\\pm$ 1.558                 \\\\\n\t\t\tCR SS Data      & 366.0 $\\pm$ 19                                 & 151.0 $\\pm$ 12                                 & 56.0 $\\pm$ 7                                & 28.0 $\\pm$ 5                                \\\\\n\t\t\tMC              & 3.46 $\\pm$  0.740                               & 0.381 $\\pm$ 0.229                                 & 1.152 $\\pm$ 0.458 0.444                               &                    0.843 $\\pm$             \\\\ \\hline\n\t\t\tRQCD            & 1.234 $\\pm$ 0.081                                  & 1.723 $\\pm$ 0.178                                 & 0.746 $\\pm$ 0.208                                  & 1.260 $\\pm$ 0.342                                \\\\ \\hline\n\t\t\tSR SS Data      & 95.0 $\\pm$ 10                                  & 13.0 $\\pm$ 4                                  & 113.0 $\\pm$ 11                                 & 18.0 $\\pm$ 4                                 \\\\\n\t\t\tMC              & 57.257 $\\pm$ 4.799                                & 6.761 $\\pm$ 2.363                                  & 63.585 $\\pm$ 4.793                               & 19.240 $\\pm$ 2.651                               \\\\ \\hline\n\t\t\tMJ Background   & 46.577 $\\pm$  13.825\t                               & 10.748 $\\pm$ 13.870                                & 36.887 $\\pm$  15.695                              & 0.0 $\\pm$ 15.695                                 \n\t\t\\end{tabular}%\n\t\\caption{Inputs for the calculation of the central value of the MJBG yield in the two final states, $Z\\to\\mu\\tauhad$ and $Z\\to e\\tauhad$.\n\t\tThe number of data and MC events in the CR OS and CR SS samples are given.\n\t\tThe excess of data with respect to simulation is assumed to arise from MJBG and it is used to calculate the value of RQCD.\n\t}\n\n\t\\label{tab:MJ}\n}\n\n\n\n\n\n\\end{table}\n\nFig.\\ref{Fig21} shows the jetRNN score distribution in the SRSS for the $Z\\to\\tauhad\\mu$ final state. Fig. \\ref{Fig12} shows the jetRNN score distributions for the events in the CRs. It can be seen that the samples are dominated by non-simulated background.\n\n\\begin{figure}[htbp]\n\t\\centering\n\t\\includegraphics[width=0.5\\textwidth]{figures/Fig21}\n\t\\caption{jetRNNScore distribution for 1-prong taus in the SRSS. The data to MC difference gives the shape for the MJBG contribution. After that, the shape is scaled by RQCD to obtain the MJ in the SROS.}\n\t\\label{Fig21}\n\\end{figure}\n\n\\begin{figure}[htbp]\n\t\\centering\n\t\\subfloat[]{\\label{Fig12a}{\\includegraphics[width=0.50\\textwidth]{figures/Fig12a.png}}}\n\t\\subfloat[]{\\label{Fig12b}{\\includegraphics[width=0.50\\textwidth]{figures/Fig12b.png}}}\\hfill\n\t\\subfloat[]{\\label{Fig12c}{\\includegraphics[width=0.50\\textwidth]{figures/Fig12c.png}}}\n\t\\subfloat[]{\\label{Fig12d}{\\includegraphics[width=0.50\\textwidth]{figures/Fig12d.png}}}\n\t\\caption{Left column (a,c) represents $Z\\to\\tauhad\\mu$ and $Z\\to\\tauhad e$ is in the right column (b,d). The two figures on top show the CROS and the bottom ones represent the CRSS. All of the plots show the jetRNNScore for 1 prongs. In this case the events used to calculate RQCD are the ones with jetRNNScore$<0.4$.  }\n\t\\label{Fig12}\n\\end{figure}\n\n\\subsection{Electroweak Background}\nThe electroweak background (EWBG) sources considered are $t\\bar{t}$, $\\Zjets$, Diboson and single top processes. For all of them, simulated samples are available and they are listed in Table \\ref{Table3}. At an early stage of our analysis the $\\Wjets$  simulation was checked for correctly accounting for the expected EWBG. This study is described in Appendix \\ref{wjetsstudy}. Nonetheless, the final $\\Wjets$ contribution to our background yield is so small that an updated study will not improve the quality and precision of our results.  ", "meta": {"hexsha": "6f6ebb4f06be286fbf32e95313621721833978ac", "size": 7216, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "BG.tex", "max_stars_repo_name": "diegobaronm/QTNote", "max_stars_repo_head_hexsha": "e2640e985974cea2f4276551f6204c9fa50f4a17", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BG.tex", "max_issues_repo_name": "diegobaronm/QTNote", "max_issues_repo_head_hexsha": "e2640e985974cea2f4276551f6204c9fa50f4a17", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BG.tex", "max_forks_repo_name": "diegobaronm/QTNote", "max_forks_repo_head_hexsha": "e2640e985974cea2f4276551f6204c9fa50f4a17", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 94.9473684211, "max_line_length": 834, "alphanum_fraction": 0.598808204, "num_tokens": 2054, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.3030952252287381}}
{"text": "\\renewcommand{\\nrandom}{\\num{700}}\n\\renewcommand{\\napplication}{\\num{212}}\n\\newcommand{\\ntoilet}{\\num{77}}\n\\newcommand{\\nmaxcount}{\\num{26}}\n\\newcommand{\\nsandcastle}{\\num{25}}\n\\newcommand{\\nconformant}{\\num{24}}\n\\newcommand{\\nmpec}{\\num{60}}\n\n\\section{Evaluation}\n\\label{sect:erssat-evaluation}\n\nWe evaluated the proposed~\\cref{alg:erssat} against\nthe state-of-the-art DPLL-based SSAT solver \\dcssat~\\cite{Majercik2005}\nover both random $k$-CNF and application formulas.\nThe proposed algorithm is implemented in the \\texttt{C++} language inside the \\abc~\\cite{ABC} environment.\nThe SAT solver \\minisat-2.2~\\cite{Een2003Solver} is used to answer satisfiability queries.\nFor weighted model counting,\nwe tried \\cachet~\\cite{Sang2004,Sang2005ModelCounting},\nbut the overall performance was not satisfactory.\nInstead, we resorted to a well-developed BDD package \\cudd~\\cite{CUDD}.\nWeight computation of a formula is fulfilled via a classic approach~\\cite{Darwiche2002KnowledgeCompilation} that traverses the BDD of a formula and computes the satisfying probabilities of the BDD nodes.\nOur prototyping implementation\\footnote{Available at: \\url{\\ssatabcurl}} is named \\erssat.\nA bare version of \\erssat without the clause-strengthening heuristics is called \\erssatb in the experiments.\nWe used \\ssatABCRevision in the experiments.\n\n\\subsection{Benchmark set}\nThe SSAT instances in the evaluation are hosted\nin a publicly available database\\footnote{Available at: \\url{\\ssatbenchmarkurl}}.\nWe used \\ssatBenchRevision in the experiments.\n\n\\subsubsection{Random $k$-CNF formulas}\nWe generated random $k$-CNF formulas by \\cnfgen~\\cite{Lauria2017CNFgen}.\nA collection of~\\nrandom~formulas were generated with $k$,\ni.e., the number of literals in a clause,\ntaking values from $\\{3,4,5,6,7,8,9\\}$,\nthe number of variables taking values from $\\{10,20,30,40,50\\}$,\nand clause-to-variable ratio taking values from $\\{k-1,k,k+1,k+2\\}$.\nFive formulas were sampled for each parameter combination.\nTo convert the propositional formulas into E-MAJSAT formulas,\nthe first half of the variables are existentially quantified,\nand the rest are randomly quantified with probability $0.37$.\n\n\\subsubsection{Application formulas}\n\\begin{table}[ht]\n    \\centering\n    \\caption{The families of the application formulas}\n    \\label{tbl:exist-random-ssat-families}\n    \\begin{tabular}{c|c|c}\n        Family               & Description                                               & Number       \\\\\n        \\hline\n        \\textit{Toilet-A}    & Adapted from exist-forall-exist QBFs~\\cite{Narizzano2006} & \\ntoilet     \\\\\n        \\textit{Conformant}  & Adapted from exist-forall-exist QBFs~\\cite{Narizzano2006} & \\nconformant \\\\\n        \\textit{Sand-Castle} & A probabilistic planning problem~\\cite{Majercik1998}      & \\nsandcastle \\\\\n        \\textit{Max-Count}   & Adapted from maximum model counting~\\cite{Fremont2017}    & \\nmaxcount   \\\\\n        \\textit{MPEC}        & Maximum probabilistic equivalence checking                & \\nmpec       \\\\\n    \\end{tabular}\n\\end{table}\n\nWe collected five families of application formulas for evaluation.\nTheir descriptions and the numbers of the instances in each family are summarized in~\\cref{tbl:exist-random-ssat-families}.\nThe first two families,\n\\textit{Toilet-A} and \\textit{Conformant},\nwere adapted from exist-forall-exist QBFs~\\cite{Narizzano2006}.\nWe converted the QBFs into exist-random-exist quantified SSAT formulas\nby replacing their universal quantifiers with randomized ones with probabilities $0.5$.\nThe third family \\textit{Sand-Castle} is a probabilistic conformant planning domain.\nThe problem can be encoded as E-MAJSAT formulas~\\cite{Majercik1998}.\nThe family \\textit{Max-Count} models the problems of maximum satisfiability, quantitative information flow, and program synthesis with maximum model counting~\\cite{Fremont2017}.\nWe represented the maximum model counting instances as E-MAJSAT formulas.\nThe last family \\textit{MPEC} consists of formulas that analyze the maximum probability of a probabilistic circuit to produce erroneous outputs,\nas discussed in~\\cref{chap:prob-design-eval}.\n\n\\subsection{Experimental setup}\nOur experiments were performed on a machine with~\\machineSpec.\nThe operating system was~\\osInfo.\nThe programs were compiled with~\\compiler.\nEach SSAT-solving task was limited to a CPU core,\na CPU time of~\\timelimit,\nand a memory usage of~\\memlimit.\nTo achieve reliable benchmarking,\nwe used a benchmarking framework \\benchexec\\footnote{Available at: \\url{\\benchexecurl}}~\\cite{Benchmarking-STTT},\nand assumed~\\measurement.\n\n\\subsection{Results}\n\n\\subsubsection{Random $k$-CNF formulas}\n\n\\cref{fig:erssat-quantile-random} shows the quantile plots regarding CPU time and memory usage\nof the SSAT instances derived from the random $k$-CNF formulas.\nA data point $(x,y)$ in a quantile plot indicates that\nthere are $x$ formulas processed by the respective algorithm within a resource constraint of $y$.\nIn~\\cref{fig:erssat-quantile-cputime-random},\nwe observe that \\erssat solved a similar amount of formulas as \\dcssat did.\nMoreover, the clause-strengthening heuristics improve the performance of \\erssat a lot,\nas can be seen from the huge difference between \\erssat and \\erssatb.\nOn the other hand,\n\\cref{fig:erssat-quantile-memory-random} shows that \\dcssat used much more memory than \\erssat.\nThis can be attributed to the subformula caching of \\dcssat.\nInstead, \\erssat only builds BDDs for cofactored formulas, which confined its memory footprint.\n\n\\begin{figure*}[hp]\n    \\centering\n    \\subfloat[CPU time]{\n        \\includegraphics{exist-random-ssat/evaluation/plots/quantile-cputime-Random.pdf}\n        \\label{fig:erssat-quantile-cputime-random}\n    }\\\\\n    \\subfloat[Memory usage]{\n        \\includegraphics{exist-random-ssat/evaluation/plots/quantile-memory-Random.pdf}\n        \\label{fig:erssat-quantile-memory-random}\n    }\n    \\caption{Quantile plots of random $k$-CNF formulas}\n    \\label{fig:erssat-quantile-random}\n\\end{figure*}\n\n\\subsubsection{Application formulas}\n\n\\input{exist-random-ssat/evaluation/tex/data-commands.tex}\n\\begin{table}[t]\n    \\centering\n    \\caption{Summary of the results for~\\napplication~application formulas}\n    \\label{tbl:exist-random-ssat-application}\n    \\begin{tabular}{l|ccc}\n        \\toprule\n        Algorithm                   & {\\dcssat}                                                     & {\\erssat} & {\\erssatb} \\\\\n        \\midrule\n        Solved formulas             & \\num{\\DcssatErDefaultApplicationMissingCount}\n                                    & \\num{\\ErssatDefaultBddApplicationMissingCount}\n                                    & \\num{\\ErssatBareBddApplicationMissingCount}                                            \\\\\n        \\qquad \\textit{Toilet-A}    & \\num{\\dcssatToiletA}\n                                    & \\num{\\erssatToiletA}\n                                    & \\num{\\erssatbToiletA}                                                                  \\\\\n        \\qquad \\textit{Conformant}  & \\num{\\dcssatconformant}\n                                    & \\num{\\erssatconformant}\n                                    & \\num{\\erssatbconformant}                                                               \\\\\n        \\qquad \\textit{Sand-Castle} & \\num{\\dcssatcastle}\n                                    & \\num{\\erssatcastle}\n                                    & \\num{\\erssatbcastle}                                                                   \\\\\n        \\qquad \\textit{Max-Count}   & \\num{\\dcssatMaxCount}\n                                    & \\num{\\erssatMaxCount}\n                                    & \\num{\\erssatbMaxCount}                                                                 \\\\\n        \\qquad \\textit{MPEC}        & \\num{\\dcssatMPEC}\n                                    & \\num{\\erssatMPEC}\n                                    & \\num{\\erssatbMPEC}                                                                     \\\\\n        Timeouts                    & \\num{\\DcssatErDefaultApplicationErrorTimeoutCount}\n                                    & \\num{\\ErssatDefaultBddApplicationErrorTimeoutCount}\n                                    & \\num{\\ErssatBareBddApplicationErrorTimeoutCount}                                       \\\\\n        Out of memory               & \\num{\\DcssatErDefaultApplicationErrorOutOfMemoryCount}\n                                    & \\num{\\ErssatDefaultBddApplicationErrorOutOfMemoryCount}\n                                    & \\num{\\ErssatBareBddApplicationErrorOutOfMemoryCount}                                   \\\\\n        Other inconclusive          & \\num{\\DcssatErDefaultApplicationErrorOtherInconclusiveCount}\n                                    & \\num{\\ErssatDefaultBddApplicationErrorOtherInconclusiveCount}\n                                    & \\num{\\ErssatBareBddApplicationErrorOtherInconclusiveCount}                             \\\\\n        \\bottomrule\n    \\end{tabular}\n\\end{table}\n\nThe solving results of the application formulas are summarized in~\\cref{tbl:exist-random-ssat-application}.\nFor each compared approach,\nthe numbers of its exactly solved formulas,\ntimeouts, out of memory, and other inconclusive situations are reported.\nTo study the solving performance regarding different kinds of formulas,\nwe further report the numbers of exactly solved formulas per family.\nObserve that \\dcssat exactly solved the most formulas.\nIts advantage mainly comes from family \\textit{Sand-Castle},\nwhere it solved \\num{22} formulas,\nbut \\erssat and \\erssatb only solved \\num{13} and \\num{14} formulas, respectively.\nWe will analyze why the proposed clause-containment learning is not suitable for this family later.\nTo our surprise, the proposed clause-strengthening heuristics seem not very useful on the evaluated application formulas.\nThey even worsened the performance over formulas from the family \\textit{Toilet-A}.\nWhile \\erssat and \\erssatb suffered from more timeouts than \\dcssat,\nthey did not run out of memory for any formula.\nInstead, \\dcssat tends to consume a lot of memory, because it memorizes many subformulas.\n\n\\begin{figure*}[hp]\n    \\centering\n    \\subfloat[CPU time]{\n        \\includegraphics{exist-random-ssat/evaluation/plots/quantile-cputime-Application.pdf}\n        \\label{fig:erssat-quantile-cputime-application}\n    }\\\\\n    \\subfloat[Memory usage]{\n        \\includegraphics{exist-random-ssat/evaluation/plots/quantile-memory-Application.pdf}\n        \\label{fig:erssat-quantile-memory-application}\n    }\n    \\caption{Quantile plots of application formulas}\n    \\label{fig:erssat-quantile-application}\n\\end{figure*}\n\n\\cref{fig:erssat-quantile-application} shows the quantile plots of the application SSAT formulas.\nWe can see that the clause-strengthening heuristics affected not only the effectiveness of \\erssat but also its efficiency\nfrom~\\cref{fig:erssat-quantile-cputime-application}.\nThis phenomenon indicates that the additional effort spent to strengthen a learnt clause is not worthy.\nThe reason behind this phenomenon will be inspected in the following.\n\n\\begin{figure*}[hp]\n    \\centering\n    \\subfloat[\\erssatb]{\n        \\includegraphics{exist-random-ssat/evaluation/plots/scatter-erssat.pdf}\n        \\label{fig:erssat-scatter-cputime-application}\n    }\\\\\n    \\subfloat[\\dcssat]{\n        \\includegraphics{exist-random-ssat/evaluation/plots/scatter-dcssat.pdf}\n        \\label{fig:dcssat-scatter-cputime-application}\n    }\n    \\caption{Run-time scatter plots of application formulas with \\erssat in y-axis and compared approaches in x-axis}\n    \\label{fig:erssat-scatter-application}\n\\end{figure*}\n\nTo further examine the suitability of the clause-strengthening heuristics,\nwe demonstrate the scatter plots with \\erssat in y-axis and compared approaches in x-axis\nin~\\cref{fig:erssat-scatter-application}.\nA data point $(x,y)$ in the plots indicates that there is a formula processed by both \\erssat and a compared approach,\nwhile \\erssat took a CPU time of $y$~seconds and the other approach took a CPU time of $x$~seconds.\nFrom~\\cref{fig:erssat-scatter-cputime-application},\nwe find that the clause-strengthening heuristics did improve the solving of some formulas,\nbut more often they were an overhead to \\erssatb.\n\\cref{fig:dcssat-scatter-cputime-application} also shows that\n\\dcssat was more efficient to exactly solve formulas than \\erssat over the evaluated application formulas.\n\n\\subsubsection{Clause-containment learning over the \\textit{Sand-Castle} problem}\nAs \\erssat and \\erssatb did not solve formulas from the probabilistic planning domain \\textit{Sand-Castle} quite well,\nwe look into the problem and discuss our findings here.\nThe \\textit{Sand-Castle} problem~\\cite{Majercik1998} describes an agent who wants to build a sand castle on a beach.\nThe agent has two actions to choose from: digging a moat or erecting a castle.\nA moat protects a castle from the water and increases the probability to successfully build a castle.\nThe agent must take a unique action at every stage.\nUnder the settings of conformant planning,\nthe agent must decide its strategy beforehand and does not have access to internal states\n(whether a moat has been digged or a castle has been erected) during the execution.\nGiven a finite number of stages,\nthe problem asks to compute a strategy to maximize the chance of successfully building a castle at the last stage.\nThe agent's actions are encoded with existentially quantified variables,\nand the nondeterminism in the state-transition mechanism is encoded with randomly quantified variables.\n\nA formula that encodes the \\textit{Sand-Castle} problem with $n$ stages has the form:\n\\begin{align}\n    \\pf=\\bigwedge_{i=1}^n \\pf_d^{(i)}\\land\\pf_e^{(i)},\n\\end{align}\nwhere $\\pf_d$ and $\\pf_e$ are sets of clauses used to represent the state-transition mechanism\nwhen the agent chooses to \\textit{dig} a moat or \\textit{erect} a castle, respectively.\nAs the state-transition mechanism is the same for every stage except for the variables recording the internal state,\nwe use the superscripts to indicate the stage indices.\nWe found that the \\textit{Sand-Castle} problem has the following property:\nthe clause set $\\pf_d^{(i)}$ (resp. $\\pf_e^{(i)}$) will be selected\nif and only if the agent chooses to dig a moat (resp. erect a castle) at stage~$i$.\nIn other words, each strategy of the agent (i.e., an assignment to the existentially quantified variables)\nwill select a distinct set of clauses.\nRecall that the proposed clause-containment principle aims at blocking assignments\nselecting a superset of clauses that has been selected by a previously explored assignment.\nAs a result, a learnt clause constructed based on this principle can only block the current assignment itself,\nwhich means that \\erssatb degenerates to merely brute-force search.\nThis theoretic reasoning is confirmed by the solving statistics (visible from the log files),\nwhich show that \\erssatb invoked $2^n-1$ model-counting queries.\nFor \\erssat, the situation is worse due to partial assignment pruning,\nwhich invokes additional model-counting queries to strengthen a learnt clause.\nFrom the log files, we found that \\erssat invoked twice numbers of model-counting queries than \\erssatb,\nbecause it had an additional trial but always ended in vain.\n\nOn the other hand, recall that \\dcssat is tailored to exploit the structural characteristics of planning problems.\nThe \\textit{Sand-Castle} formulas favors \\dcssat, as the subformulas are essentially the same across the stages.\nIt is not surprising the formula caching and divide-and-conquer method works well with these formulas.\n\n\\subsubsection{Approximate solving}\n\n\\begin{table}[ht]\n    \\centering\n    \\scriptsize\n    \\caption{Results of solving the \\textit{Conformant} family}\n    \\label{tbl:exist-random-ssat-conformant}\n    \\begin{adjustbox}{angle=90}\n        \\pgfplotstabletypeset[\n            every head row/.style={before row={\\toprule\n                            & \\multicolumn{4}{c}{\\dcssat} & \\multicolumn{8}{c}{\\erssat} & \\multicolumn{8}{c}{\\erssatb}\\\\},after row=\\midrule},\n            every last row/.style={after row=\\bottomrule},\n            empty cells with={--},\n            formula column/.list={0},\n            time column/.list={1,3,7},\n            prob column/.list={2,4,8},\n            lbound column/.list={5,9},\n            lbtime column/.list={6,10}\n        ]\n        {exist-random-ssat/evaluation/csv/parsed-conformant.csv}\n    \\end{adjustbox}\n\\end{table}\n\n\\begin{table}[ht]\n    \\centering\n    \\scriptsize\n    \\caption{Results of solving the \\textit{Max-Count} family}\n    \\label{tbl:exist-random-ssat-maxcount}\n    \\begin{adjustbox}{angle=90}\n        \\pgfplotstabletypeset[\n            every head row/.style={before row={\\toprule\n                            & \\multicolumn{4}{c}{\\dcssat} & \\multicolumn{8}{c}{\\erssat} & \\multicolumn{8}{c}{\\erssatb}\\\\},after row=\\midrule},\n            every last row/.style={after row=\\bottomrule},\n            empty cells with={--},\n            formula column/.list={0},\n            time column/.list={1,3,7},\n            prob column/.list={2,4,8},\n            lbound column/.list={5,9},\n            lbtime column/.list={6,10}\n        ]\n        {exist-random-ssat/evaluation/csv/parsed-MaxCount.csv}\n    \\end{adjustbox}\n\\end{table}\n\n\\begin{table}[ht]\n    \\centering\n    \\scriptsize\n    \\caption{Results of solving the \\textit{MPEC} family}\n    \\label{tbl:exist-random-ssat-mpec}\n    \\begin{adjustbox}{angle=90}\n        \\pgfplotstabletypeset[\n            every head row/.style={before row={\\toprule\n                            & \\multicolumn{4}{c}{\\dcssat} & \\multicolumn{8}{c}{\\erssat} & \\multicolumn{8}{c}{\\erssatb}\\\\},after row=\\midrule},\n            every last row/.style={after row=\\bottomrule},\n            empty cells with={--},\n            formula column/.list={0},\n            time column/.list={1,3,7},\n            prob column/.list={2,4,8},\n            lbound column/.list={5,9},\n            lbtime column/.list={6,10}\n        ]\n        {exist-random-ssat/evaluation/csv/parsed-MPEC.csv}\n    \\end{adjustbox}\n\\end{table}\n\nRecall that the proposed~\\cref{alg:erssat} solves an SSAT formula in a converging manner.\nInstead of computing the exact satisfying probability at once,\nit keeps deriving lower bounds of the satisfying probability of a formula.\nThis characteristic integrates exact and approximate solving into one approach.\nIn the following, we study the approximation ability of \\erssat.\nWe choose families \\textit{Conformant}, \\textit{Max-Count}, and \\textit{MPEC} for detailed investigation,\nbecause all of the compared approaches ran out of CPU time or memory over most of their formulas.\n\n\\cref{tbl:exist-random-ssat-conformant,tbl:exist-random-ssat-maxcount,tbl:exist-random-ssat-mpec}\nshow the approximation results over the above three families, respectively.\nFor \\dcssat, the CPU time and exact satisfying probability are reported.\nFor \\erssat and \\erssatb, in addition to the CPU and exact satisfying probability,\nthe tightest lower bound and the time elapsed to derive the lower bound are also shown in the tables.\nA formula is not shown in the tables\nif none of the approaches can solve it or derive a non-trivial lower bound for it.\n\nAs can be observed from the tables,\n\\erssat was able to derive tight lower bounds for formulas from these families,\nwhile \\dcssat suffered from timeouts over most of them.\nThe approximation ability of \\erssat makes it useful for large formulas,\nwhich cannot be exactly solved by the state-of-the-art approaches.\n\nThe above results on the random and application formulas suggest that:\n\\begin{itemize}\n    \\item The proposed solver \\erssat achieves a similar performance as \\dcssat in terms of CPU time and outperforms \\dcssat in terms of memory consumption on random formulas.\n    \\item The proposed solver \\erssat is not as good as \\dcssat at exactly solving the application formulas, which can be attributed to the overhead caused by the clause-strengthening heuristics.\n    \\item The proposed solver \\erssat is good at deriving tight lower bounds for large formulas. This approximation ability is especially valuable when the size of a formula is beyond the capability of the state-of-the-art exact solver.\n\\end{itemize}\nTo sum up, our experimental results demonstrate the unique value of the proposed clause-containment learning.", "meta": {"hexsha": "5fa81adeb233a571b889e7b60370d73bf30ca646", "size": 20339, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/exist-random-ssat/evaluation.tex", "max_stars_repo_name": "nianzelee/PhD-Dissertation", "max_stars_repo_head_hexsha": "061e22dd55b4e58b3de3b0e58bb1cbe11435decd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-11T19:38:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T19:38:13.000Z", "max_issues_repo_path": "paper/exist-random-ssat/evaluation.tex", "max_issues_repo_name": "nianzelee/PhD-Dissertation", "max_issues_repo_head_hexsha": "061e22dd55b4e58b3de3b0e58bb1cbe11435decd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/exist-random-ssat/evaluation.tex", "max_forks_repo_name": "nianzelee/PhD-Dissertation", "max_forks_repo_head_hexsha": "061e22dd55b4e58b3de3b0e58bb1cbe11435decd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 57.2929577465, "max_line_length": 236, "alphanum_fraction": 0.7009194159, "num_tokens": 5003, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5428632831725051, "lm_q1q2_score": 0.30309522522873805}}
{"text": "%  If you do not have LaTex2e installed, you will need to comment\r\n%  the first line (starting \\documentclass... )\r\n%  and uncomment the following one (starting \\documentstyle... )\r\n\\documentclass[12pt]{article} \\usepackage{epsf}\r\n%\\documentstyle[12pt,epsf]{article}\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\newif\\ifpdf\r\n%Uncomment next line for the production of Manual.pdf with pdfTeX:\r\n%\\pdftrue \\pdfcompresslevel=9\r\n\\def\\Figure#1#2{\\centering \\leavevmode \\ifpdf \\pdfimage width #2 #1.png\r\n            \\else \\tthdump{\\epsfclipon \\epsfxsize=#2 \\epsfbox{#1.ps}}\\fi}\r\n\\oddsidemargin 0.0in\r\n\\evensidemargin 0.0in\r\n\\textwidth 6.5in\r\n\\topmargin -0.75in\r\n\\textheight 9.25in\r\n\\def\\Section#1{\\section{\\sc #1}}\r\n\\def\\D  {{\\sf DUSTY}}\r\n\\def\\E#1{\\hbox{$10^{#1}$}}\r\n\\def\\eq#1{\\begin{equation} #1 \\end{equation}}\r\n\\def\\about  {\\hbox{$\\sim$}}\r\n\\def\\gaa    {\\mathrel{\\hbox{\\raise.3ex\\hbox{$>$}\\llap\r\n                                {\\lower.8ex\\hbox{$\\sim$}}}}}\r\n\\def\\laa    {\\mathrel{\\hbox{\\raise.3ex\\hbox{$<$}\\llap\r\n                                {\\lower.8ex\\hbox{$\\sim$}}}}}\r\n\\def\\ga     {\\hbox{$\\gaa$}}\r\n\\def\\la     {\\hbox{$\\laa$}}\r\n\\def\\x      {\\hbox{$\\times$}}\r\n\\def\\mic    {\\hbox{$\\mu$m}}\r\n\\def\\tV     {\\hbox{$\\tau_V$}}\r\n\\def\\Mo     {\\hbox{$M_{\\odot}$}}\r\n\\def\\Lo     {\\hbox{$L_{\\odot}$}}\r\n\\def\\Mdot   {\\hbox{$\\dot{M}$}}\r\n\\def\\kms    {\\hbox{$\\rm km\\ s^{-1}$}}\r\n\\def\\Ivezic {Ivezi\\'c}\r\n\\def\\DS     {\\displaystyle}\r\n\\def\\sub#1{_{\\rm #1}}\r\n\\def\\Frad {\\hbox{${\\cal F}\\sub{rad}$}}\r\n\\def\\Fgrav{\\hbox{${\\cal F}\\sub{grav}$}}\r\n\\def\\Te   {\\hbox{$T_e$}}\r\n\\let\\q=\\qquad\r\n\r\n% For generation of the HTML manual with tth:\r\n\\def\\tthdump#1{#1}      % For generating TeX source; ignored by tth\r\n% Redefine symbols problematic for the browser:\r\n%%tth:\\def\\ga{\\hbox{$>\\sim$}}\r\n%%tth:\\def\\la{\\hbox{$<\\sim$}}\r\n%%tth:\\def\\Mo{\\hbox{$M_o$}}\r\n%%tth:\\def\\Lo{\\hbox{$L_o$}}\r\n%%tth:\\def\\Mdot{\\hbox{$M^{dot}$}}\r\n%%tth:\\def\\Ivezic{Ivezic}\r\n\r\n%%tth:\\begin{html}<TITLE>User Manual for DUSTY</TITLE>\\end{html}\r\n%%tth: This HTML file was generated from the TeX source by\r\n%%tth: the translator TTH, which uses symbol fonts.  These fonts are\r\n%%tth: not normally enabled for Netscape running under X, because of\r\n%%tth: the way Netscape groups its fonts. If your browser has problems\r\n%%tth: displaying the math symbols in this manual, an easy fix can be found\r\n%%tth: on the TTH website at\r\n%%tth:\\begin{html}<A HREF=\"http://hutchinson.belmont.ma.us/tth/Xfonts.html\">http://hutchinson.belmont.ma.us/tth/Xfonts.html</A>\\end{html}\r\n%%tth:\\begin{html}<HR>\\end{html}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n\\begin{document}\r\n\r\n\\title                  {\\sc User Manual for DUSTY v2}\r\n\r\n\\author{ \\v Zeljko \\Ivezic\\footnote{Current address:\r\n                Department of Astronomy,\r\n                University of Washington},\r\n        Maia Nenkova \\& Moshe Elitzur\r\n        \\\\ \\\\ Department of Physics and Astronomy\r\n        \\\\    University of Kentucky, Lexington, KY 40506-0055\r\n        \\\\    [0.5in] October, 1999 (minor updates: Dec 2017)}\r\n\\date{}\r\n\\maketitle\r\n\r\n\\vfil\r\n\\begin{abstract}\r\n\r\n\\D\\ solves the problem of radiation transport in a dusty environment.  The code\r\ncan handle both spherical and planar geometries.   The user specifies the\r\nproperties of the radiation source and dusty region, and the code calculates\r\nthe dust temperature distribution and the radiation field in it. The solution\r\nmethod is based on a self-consistent equation for the radiative energy density,\r\nincluding dust scattering, absorption and emission, and does not introduce any\r\napproximations. The solution is exact to within the specified numerical\r\naccuracy.\r\n\r\n\\D\\ has built in optical properties for the most common types of astronomical\r\ndust and comes with a library for many other grains. It supports various\r\nanalytical forms for the density distribution, and can perform a full dynamical\r\ncalculation for radiatively driven winds around AGB stars. The spectral energy\r\ndistribution of the source can be specified analytically as either Planckian or\r\nbroken power-law. In addition, arbitrary dust optical properties, density\r\ndistributions and external radiation can be entered in user supplied files.\r\nFurthermore, the wavelength grid can be modified to accommodate spectral\r\nfeatures.  A single \\D\\ run can process an unlimited number of models, with\r\neach input set producing a run of optical depths, as specified. The user\r\ncontrols the detail level of the output, which can include both spectral and\r\nimaging properties as well as other quantities of interest.\r\n\r\n\\end{abstract}\r\n\r\n\\newpage\r\n\\tthdump{\\vglue 1in}\r\n%%tth:\\begin{html}<HR Width = 60%>\\end{html}\r\n\r\nThis code is copywrited, 1996--99 by Moshe Elitzur, and may not be copied\r\nwithout acknowledging its origin. Use of this code is not restricted, provided\r\nthat acknowledgement is made in each publication.  The bibliographic reference\r\nto this version of \\D\\ is \\Ivezic, \\v Z., Nenkova, M. \\& Elitzur, M., 1999,\r\nUser Manual for \\D, accessible as \r\n{\\tt https://github.com/ivezic/dusty/tree/master/dustyV2/Manual/manual.pdf}. \r\n\r\n\\tthdump{\\bigskip}\r\n\r\nMake sure that you have the current version, with the latest options and\r\nproblem fixes, by checking the \\D\\ Web site\\footnote{https://github.com/ivezic/dusty}. \r\nTo be automatically notified of these changes, ask to be placed on the \\D\\ mailing list by \r\nsending an e-mail to ivezic@astro.washington.edu.\r\n\r\n\\newpage\r\n\r\n\\tableofcontents \\vskip 0.5in\r\n\r\n\\Section{Introduction} \\label{Introduction}\r\n\r\nThe code \\D\\ was developed at the University of Kentucky by \\v Zeljko \\Ivezic,\r\nMaia Nenkova and Moshe Elitzur for a commonly encountered astrophysical\r\nproblem: radiation from some source (star, galactic nucleus, etc.) viewed after\r\nprocessing by a dusty region. The original radiation is scattered, absorbed and\r\nreemitted by the dust, and the emerging processed spectrum often provides the\r\nonly available information about the embedded object. \\D\\ can handle both\r\nplanar and centrally-heated spherical density distributions.  The solution is\r\nobtained through an integral equation for the spectral energy density,\r\nintroduced in \\cite{IE97}. The number of independent input model parameters is\r\nminimized by fully implementing the scaling properties of the radiative\r\ntransfer problem, and the spatial temperature profile is found from radiative\r\nequilibrium at every point in the dusty region.\r\n\r\nOn a Convex Exemplar machine, the solution for spherical geometry is produced\r\nin a minute or less for visual optical depth \\tV\\ up to $\\sim$ 10, increasing\r\nto 5--10 min for \\tV\\ higher than 100. In extreme cases ($\\tV \\sim 1000$) the\r\nrun time may reach 30 min or more. Run times for the slab case are typically\r\nfive times shorter. All run times are approximately twice as long on a 300 MHz\r\nPentium PC.\r\n\r\nThe purpose of this manual is to help users get quickly acquainted with the\r\ncode. Following a short description of the installation procedure (\\S2), the\r\ninput and output are described in full for the spherical case in \\S3 and \\S4.\r\nAll changes pertaining to the plane-parallel case are described separately in\r\n\\S\\ref{slab}.  Finally, \\S6 describes user control of \\D\\ itself.\r\n\r\nThis new version of \\D\\ is significantly faster than its previous public\r\nrelease. Because of the addition of many features, the structure of the input\r\nhas changed and old input files will not run on the current version.\r\n\r\n\\Section{Installation}\r\n\r\nThe FORTRAN 77 source {\\tt dustyV2.f} along with additional files, including five\r\nsample input files, come in a single compressed file dustyV2.tar.gz. This file\r\nand its unpacking instructions are available at \\D's homepage\\footnote{{\\tt\r\nhttp://faculty.washington.edu/ivezic/dusty\\_web}}. \r\n\r\n\\D\\ was developed on a Pentium PC and has been run also on a variety of Unix\r\nworkstations. It is written in standard FORTRAN 77, and producing the\r\nexecutable file is rather straightforward.  For example, on a Unix machine\r\n\r\n\\bigskip\r\n\r\n  f77 dustyV2.f -o dusty\r\n\r\n\\bigskip\\noindent If the compilation is successful you can immediately proceed\r\nto run \\D\\ without any further action. It should produce the output files {\\tt\r\nsphere1.out} and {\\tt slab1.out}, printed in appendices \\ref{sphere1} and\r\n\\ref{slab1}, respectively.  On a 300 MHz Pentium PC with \\D\\ compiled by Visual\r\nFORTRAN under Windows, these files are produced in just under 2 minutes.\r\nExecution times under Linux are roughly three times longer; the Linux/FORTRAN\r\nimplementation on the Digital alpha machine appears to be especially poor, the\r\nexecution may be as much as ten times longer. Execution times on SUN\r\nworkstations vary greatly with the model: about 1:30 min on an Enterprise 3000,\r\n3 min on SPARC Ultra 1 and 6 min on SPARC20. These run-times should provide an\r\nindication of what to expect on your machine. If \\D\\ compiles properly but the\r\nexecution seems to be going nowhere and the output is not produced in the\r\nexpected time, in all likelihood the problem reflects insufficient amount of\r\nmachine memory. As a first measure, try to close all programs with heavy demand\r\non system resources, such as ghostview and Netscape, before running \\D.  If\r\nthis does not help, the problem may be alleviated by reducing \\D's memory\r\nrequirements. Section \\ref{Memory} describes how to do that.\r\n\r\n\r\n\\Section{Input}\r\n\r\nA single \\D\\ run can process an unlimited number of models.  To accomplish\r\nthis, \\D's input is always the master input file {\\tt dusty.inp}\\footnote{{\\tt\r\ndusty.inp} must be kept with the \\D\\ executable file in the same directory.},\r\nwhich lists the names of the actual input files for all models.  These\r\nfilenames must have the form {\\tt fname.inp}, where {\\tt fname} is arbitrary\r\nand can include a full path, so that a single run may produce output models in\r\ndifferent directories. In {\\tt dusty.inp}, each input filename must be listed\r\non a separate line, with the implied extension {\\tt .inp} omitted. Since\r\nFORTRAN requires termination of input records with a carriage return, make sure\r\nyou press the ``Enter\" key after every filename you enter, especially if it is\r\nin the last line of {\\tt dusty.inp}.  Empty lines are ignored, as is all text\r\nfollowing the {\\tt `\\%'} sign (as in \\TeX).  This enables you to enter comments\r\nand conveniently switch on and off the running of any particular model.  The\r\nsample {\\tt dusty.inp}, supplied with the program, points to the five actual\r\ninput files {\\tt sphereN.inp} (N = 1--3) and {\\tt slabM.inp} (M = 1, 2). Only\r\n{\\tt sphere1} and {\\tt slab1} will be executed, since the others are commented\r\nout, providing samples of \\D's simplest possible input and output. Once they\r\nhave been successfully run you may wish to remove the {\\tt `\\%'} signs from the\r\nother entries, which demonstrate more elaborate input and output, and check the\r\nrunning of a full sequence. Your output can be verified against the\r\ncorresponding sample output files accessible on \\D's homepage.\r\n\r\nEach model is characterized by properties of the radiation source and the dusty\r\nregion, and \\D\\ produces a set of up to 999 solutions for all the optical\r\ndepths specified in the input.  The output file for {\\tt fname.inp} is {\\tt\r\nfname.out}, containing a summary of the run and a table of the main output\r\nresults. Additional output files containing more detailed tables of radiative\r\nand radial properties may be optionally produced.\r\n\r\nThe input file has a free format, text and empty lines can be entered\r\narbitrarily. All lines that start with the {\\tt `*'} sign are echoed in the\r\noutput, and can be used to print out notes and comments. This option can also\r\nbe useful when the program fails for some mysterious reason and you want to\r\ncompare its output with an exact copy of the input line as it was read in\r\nbefore processing by \\D. The occurrence of relevant numerical input, which is\r\nentered in standard FORTRAN conventions, is flagged by the equal sign `='. The\r\nonly restrictions are that all required input entries must be specified, and in\r\nthe correct order; the most likely source of an input error is failure to\r\ncomply with these requirements.  Recall, also, that FORTRAN requires a carriage\r\nreturn termination of the file's last line if it contains relevant input.\r\nSingle entries are always preceded by the equal sign, `=', and terminated by a\r\nblank, which can be optionally preceded with a punctuation mark.  For example:\r\n{\\tt T = 10,000 K} as well as {\\tt Temperature = 1.E4 degrees} and simply {\\tt\r\n{} = 10000.00} are all equivalent, legal input entries (note that comma\r\nseparations of long numbers are permitted).  Some input is entered as a list,\r\nin which case the first member is preceded by `=' and each subsequent member\r\nmust be preceded by a blank (an optional punctuation can be entered before the\r\nblank for additional separation); for example, {\\tt Temperatures  = 1E4, 2E4\r\n30,000}. Because of the special role of `=' as a flag for input entry, care\r\nmust be taken not to introduce any `=' except when required.  All text\r\nfollowing the {\\tt `\\%'} sign is ignored (as in \\TeX) and this can be used to\r\ncomment out material that includes `=' signs.  For example, different options\r\nfor the same physical property may require a different number of input entries.\r\nBy commenting out with {\\tt `\\%'}, all options may be retained in the input\r\nfile with only the relevant one switched on.\r\n\r\nThe input contains three types of data --- physical parameters, numerical\r\naccuracy parameters, and flags for optional output files.  The physical\r\nparameters include characteristics of the external radiation, properties of the\r\ndust grains, and the envelope density distribution.  Detailed description of\r\nthe program input follows, including examples marked with the `$\\bullet$' sign.\r\nEach example contains a brief explanation, followed by sample text typeset in\r\n{\\tt typewriter font} as it would appear in the input file. The sample input\r\nfiles {\\tt sphereN.inp} and {\\tt slabM.inp}, supplied with \\D, are heavily\r\ncommented to ease initial use, and can be used as templates.\r\n\r\n\\subsection\r\n                        {External Radiation}\r\n\\label{source}\r\n\r\nIn the spherical case, \\D\\ assumes that the external radiation comes from a\r\npoint source at the center of the density distribution. Thanks to scale\r\ninvariance, the only relevant property of the external radiation under these\r\ncircumstances is its spectral shape (see \\cite{IE97}).  Six different flag\r\nselected input options are available. The first three involve entry in\r\nanalytical form:\r\n\r\n\\begin{enumerate}\r\n\r\n\\item\r\n\r\nA combination of up to 10 black bodies, each described by a Planck function of\r\na given temperature. Following the spectrum flag, the number of black bodies is\r\nspecified, followed by a list of the temperatures.  When more then one\r\nblack-body is specified, the temperature list must be followed by a list of the\r\nfractional contributions of the different components to the total luminosity.\r\n\r\n\\begin{itemize}\r\n\\item A single black body:\r\n\\begin{verbatim}\r\n               Spectrum =  1\r\n           Number of BB =  1\r\n            Temperature = 10,000 K\r\n \\end{verbatim}\r\n\r\nThis could also be entered on a single line as\r\n\r\n\\hskip 1in {\\tt type = 1, N = 1, T = 1E4}\r\n\r\n\\item Two black bodies, e.g. a binary system, with the first one contributing\r\n80\\% of the total luminosity; note that the distance between the stars must be\r\nsufficiently small that the assumption of a central point source remain valid:\r\n\\begin{verbatim}\r\n               Spectrum =  1\r\n           Number of BB =  2\r\n           Temperatures = 10,000, 2,500 K\r\n           Luminosities = 4, 1\r\n\\end{verbatim}\r\n\r\n\\end{itemize}\r\n\r\n\\item\r\nEngelke-Marengo function.  This expression improves upon the black-body\r\ndescription of cool star emission by incorporating empirical corrections for\r\nthe main atmospheric effects. Engelke \\cite{Engelk} found that changing the\r\ntemperature argument of the Planck function from $T$ to $0.738\\,T[1 +\r\n79450/(\\lambda T)]^{0.182}$, where $T$ is in K and $\\lambda$ is wavelength in\r\n\\mic, adequately accounts for the spectral effect of H$^-$. Massimo Marengo\r\n\\cite{Mareng} devised an additional empirical correction for molecular SiO\r\nabsorption around 8 \\mic, and has kindly made his results available to DUSTY.\r\nThe selection of this combined Engelke-Marengo function requires as input the\r\ntemperature and the relative (to the continuum) SiO absorption depth in~\\%.\r\n\r\n\\begin{itemize}\r\n\\item Stellar spectrum parametrized with Engelke--Marengo function:\r\n\\begin{verbatim}\r\n                     Spectrum = 2\r\n                  Temperature = 2500 K\r\n         SiO absorption depth = 10 percents\r\n \\end{verbatim}\r\n\\end{itemize}\r\n\r\n\\item\r\nBroken power law of the form:\r\n$$\r\n \\lambda F_\\lambda \\propto \\cases{\r\n        0       &  $\\phantom{\\lambda(1) < {}} \\lambda \\le \\lambda(1)$   \\cr\r\n        \\lambda^{-k(1)} &  $\\lambda(1) < \\lambda \\le \\lambda(2)$        \\cr\r\n        \\lambda^{-k(2)} &  $\\lambda(2) < \\lambda \\le \\lambda(3)$        \\cr\r\n        \\vdots                                                          \\cr\r\n        \\lambda^{-k(N)} &  $\\lambda(N) < \\lambda \\le \\lambda(N + 1)$    \\cr\r\n                0       &  $\\lambda(N+1) < \\lambda$                     \\cr}\r\n$$\r\n\r\nIn this case, after the option selection the number $N$ is entered, followed by\r\na list of the break points $\\lambda(i)$, $i = 1\\dots N+1$, in \\mic\\ and a list\r\nof the power indices $k(i)$, $i = 1\\dots N$.  The wavelengths $\\lambda(i)$ must\r\nbe listed in increasing order.\r\n\r\n\\begin{itemize}\r\n\\item A flat spectrum confined to the range 0.1--1.0 \\mic:\r\n\\begin{verbatim}\r\n               Spectrum = 3\r\n                      N = 1\r\n                 lambda = 0.1, 1 micron\r\n                      k = 0\r\n\\end{verbatim}\r\nAll spectral points entered outside the range covered by \\D's wavelength grid\r\nare ignored. If the input spectrum does not cover the entire wavelength range,\r\nall undefined points are assumed zero.\r\n\\end{itemize}\r\n\\end{enumerate}\r\n\r\nThe other three options are for entry in numerical form as a separate\r\nuser-supplied input file which lists either (4) $\\lambda F_\\lambda$ (= $\\nu\r\nF_\\nu$) or (5) $F_\\lambda$ or (6) $F_\\nu$ vs $\\lambda$.  Here $\\lambda$ is\r\nwavelength in \\mic\\ and $\\nu$ the corresponding frequency, and $F_\\lambda$ or\r\n$F_\\nu$ is the external flux density in arbitrary units.\r\n\r\n\\begin{enumerate}\r\n\\setcounter{enumi}{3} \\tthdump{\\item}\r\n%%tth:\\begin{html}<LI VALUE=4>\\end{html}\r\n\r\nStellar spectrum tabulated in a file. The filename for the input spectrum must\r\nbe entered separately in the line following the numerical flag. This input file\r\nmust have a three-line header of arbitrary text followed by a two-column\r\ntabulation of $\\lambda$ and $\\lambda F_\\lambda$, where $\\lambda$ is in \\mic\\\r\nand $\\lambda F_\\lambda$ is in arbitrary units. The number of entry data points\r\nis limited to a maximum of 10,000 but is otherwise arbitrary. The tabulation\r\nmust be ordered in wavelength but the order can be either ascending or\r\ndescending. If the shortest tabulated wavelength is longer than 0.01 \\mic, the\r\nexternal flux is assumed to vanish at all shorter wavelengths.  If the longest\r\ntabulated wavelength is shorter than 3.6 cm, \\D\\ will extrapolate the rest of\r\nthe spectrum with a Rayleigh-Jeans tail.\r\n\r\n\\begin{itemize}\r\n\\item Spectrum tabulated in file {\\tt quasar.dat}:\r\n\r\n{\\tt Spectrum = 4\r\n\r\nquasar.dat}\r\n\\end{itemize}\r\n\r\n\\item  Stellar spectrum read from a file as in the previous option, but\r\n$F_\\lambda$ is specified (in arbitrary units) instead of $\\lambda F_\\lambda$.\r\n\r\n\\begin{itemize}\r\n\\item Kurucz model atmosphere tabulated in file {\\tt kurucz10.dat}:\r\n\r\n{\\tt Spectrum = 5\r\n\r\nkurucz10.dat}\r\n\\end{itemize}\r\n\r\n\\item  Stellar spectrum read from a file as in the previous option, but\r\n$F_\\nu$ is specified (in arbitrary units) instead of $F_\\lambda$.\r\n\\end{enumerate}\r\n\r\nIn the last three entry options, the filename for the input spectrum must be\r\nentered separately in the line following the numerical flag. Optionally, you\r\nmay separate the flag line and the filename line by an arbitrary number of\r\nlines that are either empty or commented out (starting with {\\tt `\\%'}). The\r\nfiles quasar.dat and kurucz10.dat are distributed with DUSTY.\r\n\r\n\r\n\\subsection               {Dust Properties}\r\n\r\nDust optical properties are described by the dust absorption and scattering\r\ncross-sections, which depend on the grain size and  material. Currently, \\D\\\r\nsupports only single-type grains, namely, a single size and chemical\r\ncomposition.  Grain mixtures can still be treated, simulated by a single-type\r\ngrain constructed from an appropriate average.  This approximation will be\r\nremoved in future releases which will provide full treatment of grain mixtures.\r\n\r\n\\subsubsection          {Chemical Composition}\r\n\\label{chemistry}\r\n\r\n\\D\\ contains data for the optical properties of six common grain types.  In\r\nmodels that utilize these standard properties, the only input required is the\r\nfractional abundance of the relevant grains.  In addition, optical properties\r\nfor other grains can be supplied by the user.  In this case, the user can either\r\nspecify directly the absorption and scattering coefficients or have \\D\\\r\ncalculate them from provided index of refraction. The various alternatives are\r\nselected by a flag, as follows:\r\n\r\n\\begin{enumerate}\r\n\r\n\\item \\D\\ contains data for six common grain types: `warm' and `cold' silicates\r\nfrom Ossenkopff et al (\\cite{Oss92}, {\\tt Sil-Ow} and {\\tt Sil-Oc}); silicates\r\nand graphite grains from Draine and Lee (\\cite{DL84}, {\\tt Sil-DL} and {\\tt\r\ngrf-DL}); amorphous carbon from Hanner (\\cite{Hann88}, {\\tt amC-Hn}); and SiC\r\nby P\\`egouri\\`e (\\cite{Peg88}, {\\tt SiC-Pg}).  Fractional number abundances\r\nmust be entered for all these grain types, in the order listed.\r\n\r\n\\begin{itemize}\r\n\\item Mixture containing only dust grains with built-in data for optical\r\nproperties:\r\n\r\n\\begin{verbatim}\r\n   optical properties index = 1\r\n   Abundances for supported grain types, standard ISM mixture:\r\n\r\n       Sil-Ow  Sil-Oc  Sil-DL  grf-DL  amC-Hn   SiC-Pg\r\n   x =  0.00    0.00    0.53    0.47    0.00     0.00\r\n \\end{verbatim}\r\n\\end{itemize}\r\nThe overall abundance normalization is arbitrary.  In this example, the\r\nsilicate and graphite abundances could have been entered equivalently as 53 and\r\n47, respectively.\r\n\r\n\\item With this option, the user can introduce up to ten additional grain types\r\non top of those built-in.  First, the abundances of the six built-in types of\r\ngrains are entered as in the previous option. Next, the number ($\\le 10$) of\r\nadditional grain types is entered, followed by the names of the data files,\r\nlisted separately one per line, that contain the relevant optical properties.\r\nThese properties are specified by the index of refraction, and \\D\\ calculates\r\nthe absorption and scattering coefficients using Mie theory.  Each data file\r\nmust start with seven header lines (arbitrary text) followed by a three-column\r\ntabulation of wavelength in \\mic, and real ({\\tt n}) and imaginary ({\\tt k})\r\nparts of the index of refraction. The number of table entries is arbitrary, up\r\nto a maximum of 10,000. The tabulation must be ordered in wavelength but the\r\norder can be either ascending or descending. \\D\\ will linearly interpolate the\r\ndata for {\\tt n} and {\\tt k} to its built-in wavelength grid.  If the supplied\r\ndata do not fully cover \\D's wavelength range, the refraction index will be\r\nassumed constant in the unspecified range, with a value equal to the\r\ncorresponding end point of the user tabulation. The file list should be\r\nfollowed by a list of abundances, entered in the same order as the names of the\r\ncorresponding data files.\r\n\r\n\\begin{itemize}\r\n\\item Draine \\& Lee graphite grains with three additional grain types whose {\\tt\r\nn} and {\\tt k} are provided by the user in data files {\\tt amC-zb1.nk}, {\\tt\r\namC-zb2.nk} and {\\tt amC-zb3.nk}, distributed with DUSTY.  These files tabulate\r\nthe most recent properties for amorphous carbon by Zubko et al \\cite{Zubko}:\r\n\r\n\\begin{verbatim}\r\n   Optical properties index = 2\r\n   Abundances of built-in grain types:\r\n         Sil-Ow  Sil-Oc  Sil-DL  grf-DL amC-Hn SiC-Pg\r\n     x =  0.00    0.00    0.00    0.22   0.00  0.00\r\n\r\n   Number of additional components = 3, properties listed in files\r\n                     amC-zb1.nk\r\n                     amC-zb2.nk\r\n                     amC-zb3.nk\r\n   Abundances for these components = 0.45, 0.10, .23\r\n \\end{verbatim}\r\n\\end{itemize}\r\n\r\n\\item This option is similar to the previous one, only the absorption and\r\nscattering coefficients are tabulated instead of the complex index of\r\nrefraction, so that the full optical properties are directly specified and there\r\nis no further calculation by \\D.  The data filename is listed in the line\r\nfollowing the option flag.  This file must start with a three-line header of\r\narbitrary text followed by a three-column tabulation of wavelength in \\mic,\r\nabsorption ($\\sigma_{\\rm abs}$) and scattering ($\\sigma_{\\rm sca}$) cross\r\nsections. Units for $\\sigma_{\\rm abs}$ and $\\sigma_{\\rm sca}$ are arbitrary,\r\nonly\r\ntheir spectral variation is relevant. The number of entries is arbitrary, with a\r\nmaximum of 10,000. The handling of the wavelength grid is the same as in the\r\nprevious option.\r\n\r\n\\begin{itemize}\r\n\\item  Absorption and scattering cross sections from the file {\\tt\r\nism-stnd.dat}, supplied with \\D, listing the optical properties for the\r\nstandard interstellar dust mixture:\r\n\r\n{\\tt Optical properties index = 3; cross-sections entered in file\r\n\r\n\\hskip 0.5in        ism-stnd.dat}\r\n\\end{itemize}\r\n\r\n\\end{enumerate}\r\n\r\n\\D's distribution includes a library of data files with the complex refractive\r\nindices of various compounds of common interest. This library is described in\r\nappendix \\ref{nklib}.\r\n\r\n\r\n\\subsubsection          {Grain Size Distribution}\r\n\r\nThe grain size distribution must be specified only when the previous option was\r\nset to {\\tt 1} or {\\tt 2}.  When the dust cross sections are read from a file\r\n(previous option set at {\\tt 3}), the present option is skipped.\r\n\r\n\\D\\ recognizes two distribution functions for grain sizes $n(a)$ --- the MRN\r\n\\cite{MRN77} power-law with sharp boundaries\r\n\\eq{\r\n         n(a) \\propto a^{-q} \\qquad \\hbox{for} \\quad\r\n                a_{\\rm min} \\le a \\le a_{\\rm max}\r\n}\r\nand its modification by Kim, Martin and Hendry \\cite{KMH94}, which replaces the\r\nupper cutoff with a smooth exponential falloff\r\n\\eq{\r\n  n(a) \\propto a^{-q} e^{-a/a_0} \\qquad \\hbox{for} \\quad a \\ge a_{\\rm min}\r\n}\r\n\\D\\ contains the standard MRN parameters $q$ = 3.5, $a_{\\rm min}$ = 0.005 \\mic\\\r\nand $a_{\\rm max}$ = 0.25 \\mic\\ as a built-in option.  In addition, the user may\r\nselect different cutoffs as well as power index for both distributions.\r\n\r\n\\begin{enumerate}\r\n\r\n\\item This is the standard MRN distribution.  No input required other than the\r\noption flag.\r\n\r\n\\item Modified MRN distribution.  The option flag is followed by listing of the\r\npower index $q$, lower limit $a_{\\rm min}$ and upper limit $a_{\\rm max}$ in\r\n\\mic.\r\n\r\n\\begin{itemize}\r\n\\item Standard MRN distribution can be entered with this option as:\r\n\r\n{\\tt  Size distribution = 2\r\n\r\n q = 3.5, a(min) = 0.005 micron, a(max) = 0.25 micron}\r\n\r\n\\item Single size grains with $a$ = 0.05 \\mic:\r\n\r\n\\begin{verbatim}\r\n     Size distribution = 2\r\n                     q = 0 (it is irrelevant in this case)\r\n                a(min) = 0.05 micron\r\n                a(max) = 0.05 micron\r\n     \\end{verbatim}\r\n\r\n\\end{itemize}\r\n\r\n\\item KMH distribution.  The option flag is followed by a list of the power\r\nindex $q$, lower limit $a_{\\rm min}$ and the characteristic size $a_0$ in \\mic.\r\n\r\n\\begin{itemize}\r\n\\item Size distribution for grains in the dusty envelope around IRC+10216 as\r\nobtained by Jura \\cite{Jura} and verified in \\Ivezic\\ \\& Elitzur \\cite{IE96b}:\r\n\r\n{\\tt  Size distribution = 3\r\n\r\n q = 3.5, a(min) = 0.005 micron, a0 = 0.2 micron}\r\n\r\n\\end{itemize}\r\n\\end{enumerate}\r\n\r\n\\subsubsection{Dust Temperature on Inner Boundary}\r\n\\label{Td}\r\n\r\nThe next input entry is the dust temperature $T_1$ (in K) on the shell inner\r\nboundary.  {\\em This is the only dimensional input required by the dust\r\nradiative transfer problem} \\cite{IE97}. $T_1$ uniquely determines $F_{e1}$,\r\nthe external flux entering the shell, which is listed in \\D's output (see \\S\r\n\\ref{default}). In principle, different types of grains can have different\r\ntemperatures at the same location. However, \\D\\ currently treats mixtures as\r\nsingle-type grains whose properties average the actual mix. Therefore, only one\r\ntemperature is specified.\r\n\r\n\\subsection{Density Distribution}\r\n\\label{density}\r\n\r\nIn spherical geometry, the density distribution  is specified in terms of the\r\nscaled radius\r\n$$\r\n                        y = {r \\over r_1}\r\n$$\r\nwhere $r_1$ is the shell inner radius.  This quantity is irrelevant to the\r\nradiative transfer problem \\cite{IE97}, therefore it is never entered. ($r_1$\r\nscales with the luminosity $L$ as $L^{1/2}$ when all other parameters are held\r\nfixed. The explicit relation is provided as part of \\D's output; see \\S\r\n\\ref{default}.) The density distribution is described by the dimensionless\r\nprofile $\\eta(y)$, which \\D\\ normalizes according to $\\int\\eta dy = 1$. Note\r\nthat the shell inner boundary is always $y = 1$.  Its outer boundary in terms\r\nof scaled radii is the shell relative thickness, and is specified as part of\r\nthe definition of $\\eta$.\r\n\r\n\\D\\ provides three methods for entering the spherical density distribution:\r\nprescribed analytical forms, hydrodynamic calculation of winds driven by\r\nradiation pressure on dust particles, and numerical tabulation in a file.\r\n\r\n\\subsubsection          {Analytical Profiles}\r\n\r\n\\D\\ can handle three types of analytical profiles: piecewise power-law,\r\nexponential, and an analytic approximation for radiatively driven winds.  The\r\nlast option is described in the next subsection on winds.\r\n\r\n\\begin{enumerate}\r\n\r\n\\item  Piecewise power law:\r\n$$\r\n \\eta(y) \\propto \\cases{\r\n        y^{-p(1)}    &  $\\phantom{y()}1   \\le y < y(1)$       \\cr\r\n        y^{-p(2)}    &  $y(1) \\le y < y(2)$       \\cr\r\n        y^{-p(3)}    &  $y(2) \\le y < y(3)$       \\cr\r\n                     &  \\qquad $\\vdots$          \\cr\r\n        y^{-p(N)}    &  $y(N - 1) \\le y \\le y(N)$ \\cr}\r\n$$\r\nAfter the option selection, the number $N$ is entered, followed by a list of the\r\nbreak points $y(i)$, $i = 1\\dots N$, and a list of the power indices $p(i)$, $i\r\n= 1\\dots N$.  The list must be ascending in $y$. Examples:\r\n\r\n\\begin{itemize}\r\n\r\n\\item Density falling off as $y^{-2}$ in the entire shell, as in a steady-state\r\nwind with constant velocity.  The shell extends to 1000 times its inner radius:\r\n\r\n\\begin{verbatim}\r\n   density type = 1;     N = 1;   Y = 1.e3;    p = 2\r\n\\end{verbatim}\r\n\r\n\\item Three consecutive shells with density fall-off softening from $y^{-2}$ to\r\na constant distribution as the radius increases by factor 10:\r\n\r\n\\begin{verbatim}\r\n              density type = 1\r\n                         N = 3\r\n          transition radii =   10   100    1000\r\n          power indices    =    2     1       0\r\n\\end{verbatim}\r\n\\end{itemize}\r\n\r\n\\item   Exponentially decreasing density distribution\r\n\\eq{\r\n          \\eta \\propto  \\exp\\left(-\\sigma\\, \\frac{y - 1}{Y - 1}\\right)\r\n}\r\nwhere $Y$ is the shell's outer boundary and $\\sigma$ determines the fall-off\r\nrate. Following the option flag, the user enters $Y$ and $\\sigma$.\r\n\r\n\\begin{itemize}\r\n\\item Exponential fall-off of the density to $e^{-4}$ of its inner value at the\r\nshell's outer boundary $Y = 100$:\r\n\r\n\\hskip 0.5in {\\tt  density type = 2; Y = 100; sigma = 4 }\r\n\\end{itemize}\r\n\\end{enumerate}\r\n\r\n\\subsubsection          {Radiatively Driven Winds}\r\n\\label{winds}\r\n\r\nThe density distribution options 3 and 4 are offered for the modeling of\r\nobjects such as AGB stars, where the envelope expansion is driven by radiation\r\npressure on the dust grains. \\D\\ can compute the wind structure by solving the\r\nhydrodynamics equations, including dust drift and the star's gravitational\r\nattraction, as a set coupled to radiative transfer.  This solution is triggered\r\nwith {\\tt density type = 3}, while {\\tt density type = 4} utilizes an analytic\r\napproximation for the dust density profile which is appropriate in most cases\r\nand offers the advantage of a much shorter run time.\r\n\r\n\\begin{enumerate}\r\n\\setcounter{enumi}{2} \\tthdump{\\item}\r\n%%tth:\\begin{html}<LI VALUE=3>\\end{html}\r\nAn exact calculation of the density structure from a full dynamics calculations\r\n(see \\cite{IE95} and references therein).  The calculation is performed for a\r\ntypical wind in which the final expansion velocity exceeds 5 \\kms, but is\r\notherwise arbitrary. The only input parameter that needs to be specified is the\r\nshell thickness $Y = r_{\\rm out}/r_1$.\r\n\r\n\\begin{itemize}\r\n\\item\r\nNumerical solution for radiatively driven winds, extending to a distance $10^4$\r\ntimes the inner radius:\r\n\r\n\\begin{verbatim}\r\n   density type = 3;     Y = 1.e4\r\n\\end{verbatim}\r\n\\end{itemize}\r\nThe steepness of the density profile near the wind origin increases with\r\noptical depth, and with it the numerical difficulties.  DUSTY handles the full\r\ndynamics calculation for models that have \\tV\\ \\la\\ 1,000, corresponding to\r\n\\Mdot\\ \\about\\ 4\\x\\E{-4} \\Mo\\ $\\rm yr^{-1}$.\r\n\r\n\\item\r\nWhen the variation of flux-averaged opacity with radial distance is negligible,\r\nthe problem can be solved analytically \\cite{IEprep}.  In the limit of\r\nnegligible drift, the analytic solution takes the form\r\n\\eq{\r\n    \\eta \\propto {1\\over y^2}\\left[{y \\over y - 1 + (v_1/v_e)^2}\\right]^{1/2}\r\n}\r\nThis density profile provides an excellent approximation under all\r\ncircumstances to the actual results of detailed numerical calculations\r\n(previous option). The ratio of initial to final velocity, $\\epsilon_v =\r\nv_1/v_e$, is practically irrelevant as long as $\\epsilon_v$ \\la\\ 0.2. The\r\nselection {\\tt density type = 4} invokes this analytical solution with the\r\ndefault value $\\epsilon_v = 0.2$. As for the previous option, the only input\r\nparameter that needs to be specified in this case is the outer boundary $Y$.\r\n\r\n\\begin{itemize}\r\n\\item\r\nAnalytical approximation for radiatively driven winds, the shell relative\r\nthickness is $Y = 10^4$:\r\n\r\n\\begin{verbatim}\r\n   density type = 4;     Y = 1.e4\r\n\\end{verbatim}\r\n\\end{itemize}\r\nRun times for this option are typically 2--3 times shorter and it can handle\r\nlarger optical depths than the previous one. Although this option suffices for\r\nthe majority of cases of interest, for detailed final fitting you may wish to\r\nswitch to the former.\r\n\r\n\\end{enumerate}\r\n\r\n\\subsubsection          {Tabulated Profiles}\r\n\r\nArbitrary density profiles can be entered in tabulated form in a file.  The\r\ntabulation could be imported from another dynamical calculation (e.g., star\r\nformation), and \\D\\ would produce the corresponding IR spectrum.\r\n\r\n\\begin{enumerate}\r\n\\setcounter{enumi}{4} \\tthdump{\\item}\r\n%%tth:\\begin{html}<LI VALUE=5>\\end{html}\r\nThe input filename must be entered separately in the line following the\r\nnumerical flag. This input file must consist of a three-line header of\r\narbitrary text, followed by a two-column tabulation of radius and density,\r\nordered in increasing radius.  The inner radius (first entry) corresponds to\r\nthe dust temperature $T_1$, entered previously (\\S \\ref{Td}).  Otherwise, the\r\nunits of both radius and density are arbitrary; \\D\\ will transform both to\r\ndimensionless variables. The number of entry data points is limited to a\r\nmaximum of 1,000 but is otherwise arbitrary. \\D\\ will transform the table to\r\nits own radial grid, with typically \\about\\ 20--30 points.\r\n\r\n\\begin{itemize}\r\n\\item Density profile tabulated in the file {\\tt collapse.dat}:\r\n\r\n\\begin{verbatim}\r\n   density type = 5;  profile supplied in the file:\r\n                      collapse.dat\r\n\\end{verbatim}\r\n\\end{itemize}\r\n\r\nThis file is supplied with \\D\\ and contains tabulation of the profile $\\eta\r\n\\propto y^{-3/2}$, corresponding to steady-state accretion to a central mass.\r\n\r\n\\end{enumerate}\r\n\r\nIn all cases, care must be taken that $\\eta$ not become so small that roundoff\r\nerrors cause spline oscillations and decrease accuracy.  To avoid such\r\nproblems, \\D\\ will stop execution with a warning message whenever $\\eta$ dips\r\nbelow \\E{-12} or its dynamic range exceeds \\E{12}.  This is particularly\r\npertinent for very steep density profiles, where the outer boundary should be\r\nchosen with care.\r\n\r\n\\subsection{Optical Depth}\r\n\r\nFor a given set of the parameters specified above, \\D\\ will generate up to 999\r\nmodels with different overall optical depths.  The list of optical depths can\r\nbe specified in two different ways.  \\D\\ can generate a grid of optical depths\r\nspaced either linearly or logarithmically between two end-points specified in\r\nthe input.  Alternatively, an arbitrary list can be entered in a file.\r\n\r\n\\begin{enumerate}\r\n\r\n\\item Optical depths covering a specified range in linear steps:  Following the\r\noption selection, the fiducial wavelength $\\lambda_0$ (in \\mic) of optical\r\ndepth $\\tau_0$ is entered.  The $\\tau_0$ grid is then specified by its two ends\r\nand the number of points ($\\le 999$).\r\n\r\n\\begin{itemize}\r\n\\item Models with 2.2 \\mic\\ optical depths including all the integers from 1 to\r\n100:\r\n\r\n\\begin{verbatim}\r\n       tau grid = 1\r\n       lambda0 = 2.2 micron\r\n       tau(min) = 1; tau(max) = 100\r\n       number of models = 100\r\n\\end{verbatim}\r\n\\end{itemize}\r\n\r\n\\item Same as the previous option, only the $\\tau_0$ range is covered in\r\nlogarithmic steps:\r\n\r\n\\begin{itemize}\r\n\\item Three models with visual optical depth $\\tau_V$ =  0.1, 1 and 10:\r\n\\begin{verbatim}\r\n       tau grid = 2\r\n       lambda0 = 0.55 micron\r\n       tau(min) = 0.1; tau(max) = 10\r\n       number of models = 3\r\n\\end{verbatim}\r\n\\end{itemize}\r\n\r\n\\item\r\nOptical depths list entered in a file: The file name is entered on a single\r\nline after the option selection. The (arbitrary) header text of the supplied\r\nfile must end with the fiducial wavelength $\\lambda_0$, preceded by the equal\r\nsign, `='. The list of optical depths, one per line up to a maximum of 999\r\nentries, is entered next in arbitrary order.  \\D\\ will sort and run it in\r\nincreasing $\\tau_0$.\r\n\r\n\\begin{itemize}\r\n\\item Optical depths from the file {\\tt taugrid.txt}, supplied with the \\D\\\r\ndistribution:\r\n\\begin{verbatim}\r\n       tau grid = 3; grid supplied in file:\r\n       taugrid.dat\r\n\\end{verbatim}\r\nThe file {\\tt taugrid.dat} is used in the sample input files {\\tt slab2.inp}\r\nand {\\tt sphere3.inp}.\r\n\\end{itemize}\r\n\\end{enumerate}\r\n\r\n\\subsection{Numerical Accuracy and Internal Bounds}\r\n\\label{numerics}\r\n\r\nThe numerical accuracy and convergence of \\D's calculations are controlled by\r\nthe next input parameter, $q_{\\rm acc}$. The accuracy is closely related to the\r\nset of spatial and wavelength grids employed by \\D. The wavelength grid can be\r\nmodified by users to meet their specific needs (see \\S\\ref{F-Grid}) and it does\r\nnot change during execution. The spatial grids are automatically generated and\r\nrefined until the fractional error of flux conservation at every grid point is\r\nless than $q_{\\rm acc}$. Whenever \\D\\ calculates also the density profile\r\n$\\eta$, the numerical accuracy of that calculation is also controlled by\r\n$q_{\\rm acc}$.\r\n\r\nThe recommended value is $q_{\\rm acc} = 0.05$, entered in all the sample input\r\nfiles. The accuracy level that can be accomplished is related to the number of\r\nspatial grid points and the model's overall optical depth.  When $\\tau_V$ \\la\\\r\n100, fewer than 30 points will usually produce a flux error of \\la\\ 1\\%\\\r\nalready in the first iteration. However, as $\\tau_V$ increases, the solution\r\naccuracy decreases if the grid is unchanged, and finer grids are required to\r\nmaintain a constant level of accuracy.  This is done automatically by \\D.  The\r\nmaximum number of grid points is bound by \\D's array dimensions, which are\r\ncontrolled by the parameter {\\tt npY} whose default value is 40. This internal\r\nlimit suffices to ensure convergence at the 5\\% level for most models with\r\n$\\tau_V$ \\la\\ 1000.\\footnote{Convergence and execution speed can be affected by\r\nthe input radiation spectral shape.  A hard spectrum heavily weighed toward\r\nshort wavelengths, where the opacity is high, can have an effect similar to\r\nlarge \\tV.} If higher levels of accuracy or larger $\\tau_V$ are needed, \\D's\r\ninternal limits on array sizes must be expanded by increasing {\\tt npY}, as\r\ndescribed in \\S\\ref{Memory}.\r\n\r\n\\subsection{Output Control}\r\n\r\nThe final input entries control \\D's output. The first is a flag that sets the\r\nlevel of \\D's verbosity during execution.  With {\\tt verbose = 1}, \\D\\ will\r\noutput to the screen a minimal progress report of its execution. With {\\tt\r\nverbose = 2} you get a more detailed report that allows tracing in case of\r\nexecution problems. {\\tt verbose = 0} suppresses all messages.  The messages\r\nare printed to the standard output device with the FORTRAN statement {\\tt\r\nwrite(*)}.  If you suspect that your system may not handle this properly,\r\nchoose {\\tt verbose = 0}.\r\n\r\nAll other output and its control is explained in the next section. Note again\r\nthat this section describes only the output for spherical models. All changes\r\nnecessitated by the planar geometry are described separately in \\S\\ref{Slab\r\nOutput}.\r\n\r\n\r\n\\Section{Output}\r\n\r\nA typical \\D\\ run generates an enormous amount of information, and the volume\r\nof output can easily get out of hand. To avoid that, \\D's default output is a\r\nsingle file that lists only minimal information about the run, as described\r\nnext. All other output is optional and fully controlled by the user.\r\n\\S\\ref{Optional Output} describes the optional output and its control.\r\n\r\n\r\n\\subsection{Default Output}\r\n\\label{default}\r\n\r\n\\D\\ always produces the output file {\\tt fname.out} for each model input {\\tt\r\nfname.inp}. In addition to a summary of the input parameters, the default\r\noutput file tabulates global properties for each of the optical depths covered\r\nin the run. The table's left column lists the sequential number {\\tt \\#\\#\\#} of\r\nthe model with the fiducial optical depth {\\tt tau0} listed in the next column.\r\nSubsequent columns list quantities calculated by \\D\\ for that {\\tt tau0}:\r\n\r\n\\begin{list}{$\\diamond$}{}\r\n\\item\r\n{\\tt F1} -- the bolometric flux, in $\\rm W\\ m^{-2}$, at the inner radius $y =\r\n1$. Only the external source contributes to {\\tt F1} since the diffuse flux\r\nvanishes there under the point-source assumption. Note that {\\tt F1} is {\\em\r\nindependent} of overall luminosity, fully determined by the scaled solution\r\n(see \\cite{IE97}). The bolometric flux emerging from the spherical distribution\r\nis {\\tt F1/$Y^2$}.\r\n\r\nAny measure of the shell dimension is irrelevant to the radiative transfer\r\nproblem and thus not part of \\D's calculations.  Still, the shell size can be\r\nof considerable interest in many applications. For convenience, the next three\r\noutput items list different measures of the shell size expressed in terms of\r\nredundant quantities such as the luminosity:\r\n\r\n\\item\r\n{\\tt r1(cm)} -- the shell inner radius where the dust temperature is {\\tt T1},\r\nspecified in the input (\\S \\ref{Td}).  This radius scales in proportion to\r\n$L^{1/2}$, where $L$ is the luminosity. The tabulated value corresponds to $L =\r\n\\E4\\ \\Lo$.\r\n\r\n\\item\r\n{\\tt r1/rc} -- where {\\tt rc} is the radius of the central source.  This\r\nquantity scales in proportion to $(T_e/T_1)^2$, where $T_e$ is the external\r\nradiation effective temperature.  The listed value is for $T_e = 10,000$ K with\r\ntwo exceptions: when the spectral shape of the external radiation is the Planck\r\nor Engelke-Marengo function, the arguments of those functions are used for\r\n$T_e$.\r\n\r\n\\item\r\n{\\tt theta1} -- the angular size, in arcsec, of the shell inner diameter. This\r\nangle depends on the observer's position and scales in proportion to $F_{\\rm\r\nobs}^{1/2}$, where $F_{\\rm obs}$ is the observed bolometric flux.  The\r\ntabulated value corresponds to $F_{\\rm obs} = \\E{-6}\\ \\rm W\\ m^{-2}$.\r\n\r\n\\item\r\n{\\tt Td(Y)} -- the dust temperature, in K, at the envelope's outer edge.\r\n\r\n\\item\r\n{\\tt err} -- the numerical accuracy, in {\\tt \\%}, achieved in the run.\r\nSpecifically, if $r$ is the ratio of smallest to largest bolometric fluxes in\r\nthe shell, after accounting for radial dilution, then the error is $(1 - r)/(1\r\n+ r)$. Errors smaller than 1\\% are listed as zero.\r\n\\end{list}\r\n\r\nWhen the density distribution is derived from a hydrodynamics calculation for\r\nAGB winds (\\S\\ref{winds}), three more columns are added to {\\tt fname.out}\r\nlisting the derived mass-loss rate, terminal outflow velocity and an upper\r\nbound on the stellar mass.  These quantities posses general scaling properties\r\nin terms of the luminosity $L$, gas-to-dust mass ratio $r_{\\rm gd}$ and dust\r\ngrain bulk density $\\rho_s$ \\cite{IEprep}.  The tabulations are for $L = \\E4\\\r\n\\Lo$, $r_{\\rm gd} = 200$ and $\\rho_s = 3\\ \\rm g~cm^{-3}$, and their scaling\r\nproperties are:\r\n\\begin{list}{$\\diamond$}{}\r\n\\item\r\n{\\tt Mdot} -- the mass loss rate in \\Mo\\ $\\rm yr^{-1}$, scales in proportion to\r\n$L^{3/4}(r_{\\rm gd}\\rho_s)^{1/2}$.  This quantity has \\about\\ 30\\% inherent\r\nuncertainty because varying the gravitational correction from 0 up to 50\\% has\r\nno discernible effect on the observed spectrum.\r\n\\item\r\n{\\tt Ve} -- the terminal outflow velocity in \\kms, scales in proportion to\r\n$L^{1/4}(r_{\\rm gd}\\rho_s)^{-1/2}$. The provided solutions apply only if this\r\nvelocity exceeds 5 \\kms.  {\\tt Ve} is subject to the same inherent uncertainty\r\nas {\\tt Mdot}.\r\n\\item\r\n{\\tt M$>$} -- an upper limit in \\Mo\\ on the stellar mass $M$, scales in\r\nproportion to $L/(r_{\\rm gd}\\rho_s)$.  The effect of gravity is negligible as\r\nlong as $M$ is less than 0.5{\\tt *M$>$} and the density profile is then\r\npractically independent of $M$.\r\n\r\n\\end{list}\r\nThere is a slight complication with these tabulations when the dust optical\r\nproperties are entered using {\\tt optical properties = 3} (\\S \\ref{chemistry}).\r\nWith this option, the scattering and absorption cross sections are entered in a\r\nfile, tabulated using arbitrary units since only their spectral shape is\r\nrelevant for the solution of the radiative transfer problem. However, the\r\nconversion to mass-loss rate requires also the grain size, and this quantity is\r\nnot specified when {\\tt optical properties = 3} is used.  \\D\\ assumes that the\r\nentered values correspond to $\\sigma/V$, the cross section per grain volume in\r\n$\\mic^{-1}$.  If that is not the case, in the above scaling relations replace\r\n$r_{\\rm gd}$ with $r_{\\rm gd}V/\\sigma$.\r\n\r\nFinally, \\D\\ assumes that the external radiation originates in a central point\r\nsource. This assumption can be tested with eqs.\\ (27) and (28) of \\cite{IE97}\r\nwhich give expressions for the central source angular size and occultation\r\neffect. From these it follows that the error introduced by the point-source\r\nassumption is no worse than 6\\% whenever\r\n\\eq{\\label{Tmin}\r\n        T_e > 2\\times\\max[T_1, (F_{e1}/\\sigma)^{1/4}].\r\n}\r\nThanks to scaling, \\Te\\ need not be specified and is entirely arbitrary as far\r\nas \\D\\ is concerned. However, compliance with the point-source assumption\r\nimplies that the output is meaningful only for sources whose effective\r\ntemperature obeys eq.\\ \\ref{Tmin}. For assistance with this requirement, {\\tt\r\nfname.out} lists the lower bound on $T_e$ obtained from this relation for\r\noptically thin sources. Since $F_{e1}$ decreases with optical depth (see\r\n\\cite{IE97}), the listed bound ensures compliance for all the models in the\r\nseries. However, in optically thick cases $F_{e1}$ may become so small that the\r\nlisted bound will greatly exceed the actual limit from eq.\\ \\ref{Tmin}. In\r\nthose cases, the true bounds can be obtained, if desired, from eq.\\ \\ref{Tmin}\r\nand the model tabulated {\\tt F1} (note again that with the point source\r\nassumption, {\\tt F1} = $F_{e1}$).\r\n\r\nBlack-body emission provides an absolute upper bound on the intensity of any\r\nthermal source. Therefore, input radiation whose spectral shape is the Planck\r\nfunction at temperature $T$ is subject to the limit $T_e \\le T$ even though\r\n$T_e$ is arbitrary in principle. In such cases $T$ must comply with eq.\\\r\n\\ref{Tmin}, otherwise \\D's output is suspect and in fact could be meaningless.\r\n\\D\\ issues a stern warning after the tabulation line of any model with input\r\nspectral shape that is either the Planck or Engelke-Marengo function whose\r\ntemperature violates eq.\\ \\ref{Tmin}.\r\n\r\n\\subsection{Optional Output}\r\n\\label{Optional Output}\r\n\r\nIn addition to the default output, the user can obtain numerous tabulations of\r\nspectra, imaging profiles and radial distributions of various quantities of\r\ninterest for each of the optical depths included in the run. This additional\r\noutput is controlled through flags entered at the end of the input file {\\tt\r\nfname.inp} that turn on and off the optional tabulations.  Setting all flags to\r\n0, as in {\\tt sphere1.inp} and {\\tt slab1.inp}, suppresses all optional\r\ntabulations and results in minimal output. A non-zero output flag triggers the\r\nproduction of corresponding output, occasionally requiring additional input.\r\nFurther user control is provided by the value of the output flag. When a\r\ncertain flag is set to 1, the corresponding output is listed in a single file\r\nthat contains the tabulations for all the optical depth solutions. Setting the\r\nflag to 2 splits the output, when appropriate, tabulating the solution for each\r\noptical depth in its own separate file. This may make it more convenient for\r\nplotting purposes, for example, at the price of many small files.  A few flags\r\ncan also be set to 3, splitting the output even further.\r\n\r\nEach of the following subsections describes in detail the optional tabulations\r\ntriggered by one of the output flags and any additional input it may require.\r\nAppendix \\ref{summary} summarizes all the output flags and the corresponding\r\noutput files they trigger, and can be used for quick reference.\r\n\r\n\r\n\\subsubsection{Properties of Emerging Spectra}\r\n\\label{fname.spp}\r\n\r\nSetting the first optional flag to 1 outputs a variety of spectral properties\r\nfor all the model solutions to the file {\\tt fname.spp}. The tabulation has\r\nfour header lines and starts with the model sequential number {\\tt \\#\\#\\#}.\r\nThe following columns list the corresponding {\\tt tau0} and the scaling\r\nparameter $\\Psi$ (see \\cite{IE97}) for the model. The subsequent columns list\r\nfluxes $f(\\lambda) = \\lambda F_\\lambda/F$, where $F = \\int\\!F_\\lambda\r\nd\\lambda$, for various wavelengths of interest:\r\n\\begin{list}{$\\diamond$}{}\r\n\\item {\\tt fV} -- relative emerging flux at 0.55 \\mic.\r\n\\item {\\tt fK} -- relative emerging flux at 2.2 \\mic.\r\n\\item\r\n{\\tt f12} -- relative emerging flux at 12 \\mic, convolved with the IRAS\r\nfilter for this wavelength.\r\n\\end{list}\r\nNext are the IRAS colors, defined for wavelengths $\\lambda_1$ and $\\lambda_2$\r\nin \\mic\\ as:\r\n\\eq{\r\n  [\\lambda_2] - [\\lambda_1]\r\n  =  \\log{\\lambda_2 f(\\lambda_2) \\over \\lambda_1 f(\\lambda_1)}\r\n  =  \\log{F_\\nu(\\lambda_2) \\over F_\\nu(\\lambda_1)}\r\n}\r\nColumns 5--7 list, in this order, {\\tt C21} = $[25] - [12]$, {\\tt C31} = $[60]\r\n- [12]$ and {\\tt C43} = $[100] - [60]$. They are followed by tabulations of:\r\n\r\n\\begin{list}{$\\diamond$}{}\r\n\\item{\\tt b8-13} -- the IRAS-defined spectral slope $\\beta_{8-13}$ between\r\n8 and 13 \\mic:\r\n$$\r\n    \\beta_{8-13} = 4.74\\log{f(13) \\over f(8)} - 1.0\r\n$$\r\n\\item{\\tt b14-22} -- the IRAS-defined spectral slope $\\beta_{14-22}$ between\r\n14 and 22 \\mic:\r\n$$\r\n    \\beta_{14-22} = 5.09\\log{f(22) \\over f(14)} - 1.0\r\n$$\r\n\\item {\\tt B9.8} -- the relative strength of the 9.8 \\mic\\ feature defined as\r\n$$\r\n    B_{9.8} = \\ln{f(9.8) \\over f_c(9.8)},\r\n$$\r\nwhere $f_c(9.8)$ is the continuum-interpolated flux across the feature.\r\n\\item\r\n{\\tt B11.3} -- the relative strength of the 11.3 \\mic\\ feature defined as\r\nabove for {\\tt B9.8}.\r\n\\item{\\tt R9.8-18} -- the ratio of the fluxes at 9.8 \\mic\\ and 18 \\mic,\r\n$f(9.8)/f(18)$.\r\n\r\n\\end{list}\r\n\r\n\\subsubsection  {Detailed spectra for each model}\r\n\\label{fname.s}\r\n\r\nThe next output flag triggers listing of detailed spectra for each model in the\r\nrun.  Setting this flag to 1 produces tables for the emerging spectra of all\r\nmodels in the single output file {\\tt fname.stb}.  Setting the flag to 2 places\r\neach table in its own separate file, where file {\\tt fname.s\\#\\#\\#} contains\r\nthe tabulation for model number {\\tt \\#\\#\\#} in the optical depth sequence\r\nlisted in the default output file (\\S\\ref{default}).\r\n\r\nIn addition to the emerging spectrum, the table for each model lists separately\r\nthe contributions of various components to the overall flux, the spectral shape\r\nof the input radiation, and the wavelength dependence of the total optical\r\ndepth. The following quantities are tabulated:\r\n\\begin{list}{$\\diamond$}{}\r\n\\item {\\tt lambda} -- the wavelength in \\mic\r\n\\item\r\n{\\tt fTot} -- the spectral shape of the total emerging flux $f(\\lambda) =\r\n\\lambda F_\\lambda/\\int\\!F_\\lambda d\\lambda$.  Values smaller than \\E{-20} are\r\nlisted as 0.\r\n\\item{\\tt xAtt} -- fractional contribution of the attenuated input radiation\r\nto {\\tt fTot}\r\n\\item{\\tt xDs} -- fractional contribution of the scattered radiation to\r\n{\\tt fTot}\r\n\\item{\\tt xDe} -- fractional contribution of the dust emission to {\\tt fTot}\r\n\\item{\\tt fInp} -- the spectral shape of the input (unattenuated) radiation\r\n\\item{\\tt tauT} -- overall optical depth at wavelength {\\tt lambda}\r\n\\item{\\tt albedo} -- the albedo at wavelength {\\tt lambda}\r\n\r\n\\end{list}\r\n\r\n\\subsubsection{Images at specified wavelengths}\r\n\\label{imaging}\r\n\r\n\\begin{figure}\r\n\\Figure{Fig1}{0.3\\hsize}\r\n%%tth:\\begin{html}<CENTER><IMG SRC=\"Fig1.jpg\" height=217></CENTER>\\end{html}\r\n\\caption{Notation for imaging output.}\\label{impact parameter}\r\n\\end{figure}\r\n\r\nThe surface brightness is a luminosity-independent self-similar distribution\r\n\\cite{IE96a} of $b/r_1$, the impact parameter scaled by the envelope inner\r\nradius (fig. \\ref{impact parameter}); note that $r_1$ is listed in the default\r\noutput file (\\S\\ref{default}) for a source luminosity \\E4~\\Lo. \\D\\ can produce\r\nmaps of the surface brightness at up to 20 wavelengths, specified in the input\r\nfile. Setting the option flag to 1 produces imaging tabulations for all the\r\nmodels of the run in the single output file {\\tt fname.itb}, setting the flag\r\nto 2 puts the table for model number {\\tt \\#\\#\\#} in its separate file {\\tt\r\nfname.i\\#\\#\\#}.\r\n\r\nFollowing the option selection flag, the number ($\\le 20$) of desired\r\nwavelengths is entered first, followed by a list of these wavelengths in \\mic.\r\n\r\n\\begin{itemize}\r\n\\item Example of additional input data required in {\\tt fname.inp} for imaging\r\noutput:\r\n\\begin{verbatim}\r\n imaging tables (all models in one file) = 1\r\n number of wavelengths = 8\r\n wavelengths = 0.55, 1.0, 2.2, 4, 10, 50, 100, 1000  micron\r\n\\end{verbatim}\r\n\\end{itemize}\r\nWhenever a specified wavelength is not part of \\D's grid, the corresponding\r\nimage is obtained by linear interpolation from the neighboring wavelengths in\r\nthe grid.  If the nearest wavelengths are not sufficiently close, the\r\ninterpolation errors can be substantial. For accurate modeling, all wavelengths\r\nspecified for imaging should be part of the grid, modifying it if necessary\r\n(see \\S\\ref{F-Grid}).\r\n\r\nEach map is tabulated with a single header line as follows:\r\n\\begin{list}{$\\diamond$}{}\r\n\\item{\\tt b} $= b/r_1$, where $b$ is the impact parameter.\r\n\\item\r\n{\\tt t(b)} = $\\tau(\\tt b)/\\tau(0)$, where $\\tau(\\tt b)$ is the overall optical\r\ndepth along a path with impact parameter {\\tt b}.  Note that $\\tau(0)$ is\r\nsimply the overall radial optical depth {\\tt tauT}, listed in the file {\\tt\r\nfname.s\\#\\#\\#} (\\S \\ref{fname.s}), and that {\\tt t(b)} doubles its value across\r\nthe shell once the impact parameter exceeds the stellar radius.\r\n\\item\r\nThe intensity, in Jy arcsec$^{-2}$, at each of the wavelengths listed in the\r\nheader line.\r\n\\end{list}\r\n\r\nA typical image contains a narrow central spike of width $b_c = 2r_c/r_1$,\r\nwhere $r_c$ is the radius of the central source \\cite{IE96a}.  Since this\r\nfeature is unresolved in most observations, it is usually of limited interest.\r\nThis spike is the only feature of the emerging intensity that depends on the\r\neffective temperature \\Te\\ of the central source, which is irrelevant to \\D's\r\ncalculations. The width of the spike scales in proportion to $T_e^{-2}$, its\r\nheight in proportion to $T_e^4$. The listed value is for $T_e = 10,000$ K with\r\ntwo exceptions: when the spectral shape of the external radiation is the Planck\r\nor Engelke-Marengo function, the arguments of those functions are used for\r\n$T_e$.\r\n\r\n\\subsubsection{Visibilities}\r\n\\label{fname.v}\r\n\r\nVisibility is the two-dimensional spatial Fourier transform of the surface\r\nbrightness distribution (for definition and discussion see \\cite{IE96a}). Since\r\nthe surface brightness is a self-similar function of $b/r_1$, the visibility is\r\na self-similar function of $q\\theta_1$ where $q$ is the spatial frequency,\r\n$\\theta_1 = 2r_1/D$ and $D$ is the distance to the source; note that $\\theta_1$\r\nis listed in the default output file for the location where $F_{\\rm obs} =\r\n\\E{-6}\\ \\rm W\\ m^{-2}$ (\\S\\ref{default}).\r\n\r\nWhen imaging tables are produced, \\D\\ can calculate from them the corresponding\r\nvisibility functions. The only required input is the flag triggering this\r\noption; if images are not requested in the first place, this entry is skipped.\r\nWhen the visibility option flag is different from zero, it must be the same as\r\nthe one for imaging. Setting both flags to 1 will add visibility tables for all\r\nmodels to the single file {\\tt fname.itb}. Setting the flags to 2 puts the\r\nimaging and visibility tables of each model in the separate file {\\tt\r\nfname.i\\#\\#\\#}, setting them to 3 further splits the output by putting each\r\nvisibility table in the separate, additional file {\\tt fname.v\\#\\#\\#}.\r\n\r\nEach visibility table starts with a single header line, which lists the\r\nspecified wavelengths in the order they were entered. The first column lists\r\nthe dimensionless scaled spatial frequency {\\tt q} = $q\\theta_1$ and is\r\nfollowed by the visibility tabulation for the various wavelengths.\r\n\r\n\r\n\\subsubsection{Radial profiles for each model}\r\n\\label{fname.r}\r\n\r\nThe next option flag triggers tabulations of the radial profiles of the\r\ndensity, optical depth and dust temperature. Setting the flag to 1 produces\r\ntabulations for all the models of the run in the single output file {\\tt\r\nfname.rtb}, setting the flag to 2 places the table for model number {\\tt\r\n\\#\\#\\#} in its own separate file {\\tt fname.r\\#\\#\\#}. The tabulated quantities\r\nare:\r\n\r\n\\begin{list}{$\\diamond$}{}\r\n\\item{\\tt y} -- dimensionless radius\r\n\\item{\\tt eta} -- the dimensionless, normalized radial density profile (\\S\r\n\\ref{density})\r\n\\item\r\n{\\tt t} -- radial profile of the optical depth variation.  At any wavelength\r\n$\\lambda$, the optical depth at radius $y$ measured from the inner boundary is\r\n{\\tt t*tauT}, where {\\tt tauT} is the overall optical depth at that wavelength,\r\ntabulated in the file {\\tt fname.s\\#\\#\\#} (\\S \\ref{fname.s}).\r\n\r\n\\item{\\tt tauF} -- radial profile of the flux-averaged optical depth\r\n\\item\r\n{\\tt epsilon} -- the fraction of grain heating due to the contribution of the\r\nenvelope to the radiation field (see \\cite{IE97}).\r\n\\item{\\tt Td} -- radial profile of the dust temperature\r\n\\item{\\tt rg} -- radial profile of the ratio of radiation pressure\r\nto gravitational force, where both forces are per unit volume:\r\n\\eq{\r\n    {\\Frad\\over\\Fgrav} = {3L\\over16\\pi GMc r_{gd}}\\,\r\n    {\\DS \\sum_i n_{d,i} a_i^2\\int\\!Q_{i,\\lambda} f_\\lambda\\,d\\lambda \\over\r\n     \\DS \\sum_i n_{d,i}\\rho_{s,i}a_i^3}\r\n}\r\nHere $f_\\lambda = F_\\lambda/\\int F_\\lambda d\\lambda$ is the local spectral\r\nshape, $\\rho_{s,i}$ is the material solid density and $n_{d,i}$ the number\r\ndensity of grains with size $a_i$.  The gas-to-dust ratio, $r_{gd}$, appears\r\nsince the gas is collisionally coupled to the dust. The tabulated value is for\r\n$\\rho_s$ = 3 g cm$^{-3}$, $L/M$ = \\E4 \\Lo/\\Mo\\ and $r_{gd} = 200$. In the case\r\nof radiatively driven winds $r_{gd}$ varies in the envelope because of the dust\r\ndrift, and this effect is properly accounted in the solution. When the dust\r\noptical properties are entered using {\\tt optical properties = 3}, grain sizes\r\nare not specified (\\S \\ref{chemistry}). This case is handled as described in\r\nthe last paragraph of \\S\\ref{default}.\r\n\r\n\\end{list}\r\n\r\nIn the case of dynamical calculation with {\\tt density type = 3} for AGB stars\r\n(\\S\\ref{winds}), the following additional profiles are tabulated:\r\n\r\n\\begin{list}{$\\diamond$}{}\r\n\\item\r\n{\\tt u} -- the dimensionless radial velocity profile normalized to the terminal\r\nvelocity {\\tt Ve}, which is tabulated for the corresponding overall optical\r\ndepth in file {\\tt fname.out} (\\S \\ref{default}).\r\n\\item\r\n{\\tt drift} -- the radial variation of $v_{\\rm g}/v_{\\rm d}$, the velocity\r\nratio of the gas and dust components of the envelope.  This quantity measures\r\nthe relative decrease in dust opacity due to dust drift.\r\n\r\n\\end{list}\r\n\r\n\\subsubsection{Detailed Run-time messages}\r\n\\label{fname.m}\r\n\r\nIn case of an error, the default output file issues a warning. Optionally,\r\nadditional, more detailed run-time error messages can be produced and might\r\nprove useful in tracing the program's progress in case of a failure. Setting\r\nthe corresponding flag to 1 produces messages for all the models in the single\r\noutput file {\\tt fname.mtb}, setting the flag to 2 puts the messages for model\r\nnumber {\\tt \\#\\#\\#} in its own separate file {\\tt fname.m\\#\\#\\#}.\r\n\r\n\\Section{Slab Geometry}\r\n\\label{slab}\r\n\r\n\\D\\ offers the option of calculating radiative transfer through a\r\nplane-parallel dusty slab. The slab is always illuminated from the left,\r\nadditional illumination from the right is optional.\r\n\r\nAs long as the surfaces of equal density are parallel to the slab boundaries,\r\nthe density profile is irrelevant: location in the slab is uniquely specified\r\nby the optical depth from the left surface.  Unlike the spherical case, there\r\nis no reference to spatial variables since the problem can be solved fully in\r\noptical-depth space.  The other major difference involves the bolometric flux\r\n$F$. In the spherical case the diffuse flux vanishes at $y = 1$ and $F =\r\nF_{e1}/y^2$, where $F_{e1}$ is the external bolometric flux at the shell inner\r\nboundary \\cite{IE97}. In contrast, $F$ is constant in the slab and the diffuse\r\nflux does not vanish on either face.  Therefore $F/F_{e1}$, where $F_{e1}$ is\r\nthe bolometric flux of the left-side source at slab entry, is another unknown\r\nvariable determined by the solution.\r\n\r\nThe slab geometry is selected by specifying {\\tt density type = 0}. The dust\r\nproperties are entered as in the spherical case, with the dust temperature\r\nspecified on the slab left surface instead of the shell inner boundary. The\r\nrange of optical depths, too, is chosen as in the spherical case. The only\r\nchanges from the spherical case involve the external radiation and the output.\r\n\r\n\\begin{figure}\r\n\\Figure{Fig2}{0.7\\hsize}\r\n%%tth:\\begin{html}<CENTER><IMG SRC=\"Fig2.jpg\" HEIGHT=237></CENTER>\\end{html}\r\n\\caption{The two possible schemes for a slab illuminated from the left.  (a)\r\nParallel rays impinging at an arbitrary angle to the normal. (b) Isotropic\r\nradiation.}\r\n\\end{figure}\r\n\r\n\\subsection{Illuminating Source(s)}\r\n\r\nExternal radiation is incident from the left side. The presence of an optional\r\nright-side source is specified by a non-zero value for {\\tt R}, the ratio of\r\nthe right-side bolometric flux at slab entry to that of the left-side source.\r\nEach input radiation is characterized by its spectral shape, which is entered\r\nexactly as in the spherical case (\\S\\ref{source}), and angular distribution.\r\nThe only angular distributions that do not break the planar symmetry involve\r\nparallel rays, falling at some incident angle, and isotropic radiation (see\r\nfigure 2). The parallel-rays distribution is specified by the cosine ($> 0.05$)\r\nof the illumination angle, the isotropic distribution is selected by setting\r\nthis input parameter to $-1$.  Since oblique angles effectively increase the\r\nslab optical depth, run-times will increase with incidence angle.\r\n\\begin{itemize}\r\n\\item\r\nSlab geometry with illumination by parallel rays normal to the left surface. In\r\nthis case, the spectral shape of the source is entered as in the spherical\r\ncase. The only change from the spherical input is that the density profile is\r\nreplaced by the following:\r\n\\begin{verbatim}\r\n     density type = 0\r\n       cos(angle) = 1.0 (spectral shape entered previously)\r\n                R = 0   (no source on the right)\r\n\\end{verbatim}\r\n\\end{itemize}\r\nTwo-sided illumination is specified by a non-zero {\\tt R}, where $0 < {\\tt R}\r\n\\le 1$. The properties of the right-side source are specified following the\r\ninput for {\\tt R}.\r\n\\begin{itemize}\r\n\\item\r\nSlab illuminated from both sides.  The left-side radiation has isotropic\r\ndistribution whose spectral shape has been entered previously.  The right-side\r\nsource has a bolometric flux half that of the left-side source and a black-body\r\nspectral shape with temperature 3,000 K.  It illuminates the slab with parallel\r\nrays incident at an angle of $60^\\circ$ from normal. The density profile is\r\nreplaced by the following:\r\n\\begin{verbatim}\r\n   density type = 0\r\n     cos(angle) = -1.0 (spectral shape entered previously)\r\n              R = 0.5\r\n   Properties of the right-side source:\r\n     cos(angle) = 0.5\r\n       Spectrum = 1;   N = 1;  Tbb = 3000 K\r\n\\end{verbatim}\r\n\\end{itemize}\r\n\r\n\\subsection{Slab Output}\r\n\\label{Slab Output}\r\n\r\nThe output-control flags are identical to those in the spherical case and the\r\noutput files are analogous, except for some changes dictated by the different\r\ngeometry.\r\n\r\n\\subsubsection{Default Output}\r\nIn the default {\\tt fname.out}. the first two columns are the same as in the\r\nspherical case (\\S\\ref{default}) and are followed by:\r\n\\begin{list}{$\\diamond$}{}\r\n\\item{\\tt Fe1} --\r\nbolometric flux, in $\\rm W\\ m^{-2}$, of the left-side source at the slab left\r\nboundary.\r\n\\item{\\tt f1} $= F/F_{e1}$, where $F$ is the overall bolometric flux.\r\nValues at and below the internal accuracy of \\D's flux computation, \\E{-3} when\r\n$q_{\\rm acc}$ = 0.05, are listed as zero.\r\n\\item{\\tt r1(cm)} -- the distance at which a point source with luminosity\r\n\\E4 \\Lo\\ produces the bolometric flux $F_{e1}$.\r\n\\item  {\\tt Td(K)} -- the dust temperature at the slab right boundary.\r\n\\item\r\n{\\tt Te(L)} -- the effective temperature, in K, obtained from $F_{e1} =\r\n\\sigma{\\tt Te}^4$.  When the slab is illuminated also from the right, a column\r\nis added next for {\\tt Te(R)}, the effective temperature obtained similarly for\r\nthe right-side flux.\r\n\\item{\\tt err} -- the flux conservation error, defined as in the spherical case.\r\n\r\n\\end{list}\r\n\r\n\\subsubsection{Spectral Profiles}\r\nUnlike the spherical case, the slab optional spectral files list properties of\r\nthe half-fluxes emerging from both sides of the slab, calculated over the\r\nforward and backward hemispheres perpendicular to the slab faces.  The\r\nmagnitudes of the bolometric half-fluxes on the slab right and left faces can\r\nbe obtained from tabulated quantities via\r\n $$ F_{\\rm right} = ({\\tt R} + {\\tt f1})\\,{\\tt Fe1}, \\qquad\r\n    F_{\\rm left}  = (1 - {\\tt f1})\\,{\\tt Fe1}. $$\r\nThe right-emerging radiation replaces the spherical output in {\\tt fname.spp},\r\n{\\tt fname.stb} and {\\tt fname.s\\#\\#\\#}, analogous tables for the left-emerging\r\nradiation are simply added to the appropriate output files. Setting the\r\nrelevant selection flags to 3 places these additional tables in their own\r\nseparate files --- {\\tt fname.zpp} for spectral properties and {\\tt\r\nfname.z\\#\\#\\#} for the detailed spectra of model number {\\tt \\#\\#\\#} in the\r\noptical depth sequence.\r\n\r\nSimilar to the {\\tt fTot} column of the spherical case, the spectral shape of\r\nthe right-emerging half-flux is printed in column {\\tt fRight}.  It consists of\r\nthree components whose fractional contributions are listed next, as in the\r\nspherical case: {\\tt xAtt} for the left-source attenuated radiation, {\\tt xDs}\r\nand {\\tt xDe} for the diffuse scattered and emitted components, respectively.\r\nSubsequent columns are as in the spherical case. The tables for the spectral\r\nshape of the left-emerging half-flux {\\tt fLeft} are analogous.\r\n\r\n\\subsubsection{Spatial Profiles}\r\nThe output for spatial profiles is similar to the spherical case. The radial\r\ndistance {\\tt y} and density profile {\\tt eta} are removed.  The relative\r\ndistance in optical depth from the left boundary, {\\tt t}, becomes the running\r\nvariable, and the tabulations of {\\tt tauF}, {\\tt epsilon} and {\\tt Td} are the\r\nsame (see \\ref{fname.r}).  The tabulation for \\Frad/\\Fgrav\\ is dropped,\r\nreplaced by three components of the overall bolometric flux: {\\tt febol} is the\r\nlocal net bolometric flux of external radiation; {\\tt fRbol} and {\\tt fLbol}\r\nare, respectively, the rightward and leftward half-fluxes of the local diffuse\r\nradiation. All components are normalized by {\\tt Fe1} so that the flux\r\nconservation relation is {\\tt febol + fRbol - fLbol} = {\\tt f1} everywhere in\r\nthe slab. Note that {\\tt fRbol} vanishes on the slab left face, {\\tt fLbol} on\r\nthe right face.\r\n\r\n\\bigskip\r\n\\D's distribution contains two sample input files, {\\tt slab1.inp} and {\\tt\r\nslab2.inp}, which can be used as templates for the slab geometry.  The output\r\ngenerated with {\\tt slab1.inp} is shown in appendix \\ref{slab1}.\r\n\r\n\r\n\\Section{User Control of \\D}\r\n\r\n\\D\\ allows the user control of some of its inner working through tinkering with\r\nactual code statements that control the spatial and spectral grids. The\r\nappropriate statements were placed in the file {\\tt userpar.inc} separate from\r\nthe main {\\tt dusty.f}, and are imbedded during compilation by the FORTRAN\r\nstatement {\\tt INCLUDE}\\footnote{{\\tt userpar.inc} must always stay with the\r\nsource code in the same directory.}. After modifying statements in {\\tt\r\nuserpar.inc} , \\D\\ must be recompiled to enable the changes.\r\n\r\n\\subsection{Array Sizes for Spatial Grid}\r\n \\label{Memory}\r\n\r\nThe maximum size of \\D's spatial grid is bound by array dimensions. These are\r\ncontrolled by the parameter {\\tt npY} which sets the limit on the number of\r\nradial points.  The default value of 40 must be decreased when \\D\\ is run on\r\nmachines that lack sufficient memory (see \\S\\ref{Introduction}) and increased\r\nwhen \\D\\ fails to achieve the prescribed accuracy (see \\S\\ref{numerics}). This\r\nparameter is defined in {\\tt userpar.inc} via\r\n\\begin{verbatim}\r\n      PARAMETER (npY=40)\r\n\\end{verbatim}\r\nTo modify {\\tt npY} simply open {\\tt userpar.inc}, change the number 40 to the\r\ndesired value, save your change and recompile.  That's all.  Every other\r\nmodification follows a similar procedure. Since \\D's memory requirements vary\r\nroughly as the second power of {\\tt npY}, the maximum value that can be\r\naccommodated on any given machine is determined by the system memory.\r\n\r\nThe parameter {\\tt npY} defines also the size {\\tt npP} of the grid used in\r\nangular integrations.  In the case of planar geometry \\D\\ uses analytic\r\nexpressions for these integrations.  Since this grid becomes redundant, {\\tt\r\nnpP} can be set to unity, allowing a larger maximum {\\tt npY}.  The procedure\r\nis described in {\\tt userpar.inc}.\r\n\r\n\\subsection{Wavelength Grid} \\label{F-Grid}\r\n\r\n\\D's wavelength grid is used both in the internal calculations and for the\r\noutput of all wavelength dependent quantities. The number of grid points is set\r\nin {\\tt userpar.inc} by the parameter {\\tt npL}, the grid itself is read from\r\nthe file {\\tt lambda\\_grid.dat}\\footnote{{\\tt lambda\\_grid.dat} must always\r\nstay with the \\D\\ executable file in the same directory.}. This file starts\r\nwith an arbitrary number of text lines, the beginning of the wavelength list is\r\nsignaled by an entry for the number of grid points.  This number must be equal\r\nto {\\tt npL} entered in {\\tt userpar.inc} and to the actual number of entries\r\nin the list.\r\n\r\nThe grid supplied with \\D\\ contains 105 points from 0.01 to $3.6\\times10^{4}$\r\n\\mic.  The short wavelength boundary is to ensure adequate coverage of input\r\nradiation from an O star, for example, which peaks at 0.1 \\mic.  Potential\r\neffects on the grain material by such hard radiation are not included in \\D.\r\nThe long wavelength end is to ensure adequate coverage at all wavelengths where\r\ndust emission is potentially significant. Wavelengths can be added and removed\r\nprovided the following rules are obeyed:\r\n\\begin{enumerate}\r\n\\item\r\nWavelengths are specified in \\mic.\r\n\\item\r\nThe shortest wavelength must be $\\le 0.01$ \\mic, the longest $\\ge\r\n3.6\\times10^{4}$ \\mic.\r\n\\item\r\nThe ratio of each consecutive pair must be $\\le$ 1.5.\r\n\\end{enumerate}\r\nThe order of entries is arbitrary, \\D\\ sorts them in increasing wavelength and\r\nthe sorted list is used for all internal calculations and output.  This\r\nprovides a simple, convenient method for increasing the resolution at selected\r\nspectral regions: just add points at the end of the supplied grid until the\r\ndesired resolution is attained.  Make sure you update both entries of {\\tt npL}\r\nand recompile \\D.\r\n\r\nIn practice, tinkering with the wavelength grid should be reserved for adding\r\nspectral features. Specifying the optical properties of the grains at a\r\nresolution coarser than that of the wavelength grid defeats the purpose of\r\nadding grid points. The optical properties of grains supported by \\D\\ are\r\nlisted on the default wavelength grid.  Therefore, modeling of very narrow\r\nfeatures requires both the entry of a finer grid in {\\tt lambda\\_grid.dat} and\r\nthe input of user-supplied optical properties (see \\S\\ref{chemistry}) defined\r\non that same grid.\r\n\r\n\\vfil\r\n\r\n\\begin{thebibliography}{99}\r\n \\bibitem{Dorsch} Dorschner, J. et al 1995, A\\&A 300, 503\r\n \\bibitem{DL84}   Draine, B.T. \\& Lee, H.M. 1984, ApJ, 285, 89\r\n \\bibitem{Engelk} Engelke, C.W. 1992, AJ 104, 1248\r\n \\bibitem{Hann88} Hanner, M.S. 1988, NASA Conf. Pub. 3004, 22\r\n \\bibitem{Henn97} Henning, Th. et al 1997, A\\&A 327, 743\r\n \\bibitem{IE95}   \\Ivezic, \\v Z. \\& Elitzur, M. 1995, ApJ, 445,415\r\n \\bibitem{IE96a}  \\Ivezic, \\v Z. \\& Elitzur, M. 1996, MNRAS 279, 1011\r\n \\bibitem{IE96b}  \\Ivezic, \\v Z. \\& Elitzur, M. 1996, MNRAS 279, 1019\r\n \\bibitem{IE97}   \\tthdump{\\Ivezic, \\v Z. \\& Elitzur, M. 1997, MNRAS 287, 799; \\newline}\r\n%%tth:\\begin{html}<A HREF=\"ftp://gradj.pa.uky.edu/moshe/scaling1.ps\">Ivezic, Z. & Elitzur, M. 1997, MNRAS 287, 799</A>\\end{html};\r\n      Erratum: MNRAS 303, 864 (1999)\r\n% \\tthdump{\\newline} Erratum: MNRAS 303, 864 (1999).\r\n \\bibitem{IEprep} \\Ivezic, \\v Z. \\& Elitzur, M., in preparation\r\n \\bibitem{Jaeger} J\\\"ager, C. et al 1994, A\\&A 292, 641\r\n \\bibitem{Jena}   Jena--St. Petersburg database of optical constants,\r\n                  accessible at \\newline\r\n                  {\\tt http://www.astro.uni-jena.de/Users/database/entry.html},\r\n \\bibitem{Jura}   Jura, M. 1994, ApJ, 434, 713\r\n \\bibitem{KMH94}  Kim S.H., Martin P.G. \\& Hendry P.D. 1994, ApJ, 422,164\r\n \\bibitem{Mareng} Marengo M. 1999, in preparation\r\n \\bibitem{MRN77}  Mathis J.S., Rumpl W. \\& Nordsieck K.H. 1977, ApJ, 217, 425\r\n \\bibitem{Oss92}  Ossenkopf, V., Henning, Th. \\& Mathis, J.S. 1992, A\\&A, 261,\r\n                  567\r\n \\bibitem{Peg88}  P\\`egouri\\`e, B. 1988, A\\&A, 194, 335\r\n \\bibitem{Roush}  Roush, T., et al 1991, Icarus, 94, 191\r\n \\bibitem{Zubko}  Zubko, V.G., et al 1996, MNRAS, 282, 1321\r\n\r\n\\end{thebibliography}\r\n\r\n\\newpage\r\n\\appendix\r\n\\section*{\\sc Appendices}\r\n \\addtocontents{toc}{\\break \\vfil}\r\n \\addcontentsline{toc}{section}{\\sc Appendices}\r\n\r\n\\Section{Output Summary} \\label{summary}\r\n\r\n\\D's default output is the file {\\tt fname.out}, described in \\S\\ref{default}.\r\nAdditional output is optionally produced through selection flags, summarized in\r\nthe following table.  The second column lists the section number where a\r\ndetailed description of the corresponding output is provided.\r\n\r\n\\begin{table}[htbp]\r\n\\begin{center}\r\n\\renewcommand{\\arraystretch}{1.3}\r\n\r\n\\caption{\\hfil Summary of all Output Options}\\label{Options Table}\r\n\\centerline{}\r\n\\renewcommand{\\arraystretch}{1.3}\r\n\\begin{tabular}{|l|r||c|c|c|}                              \\hline\r\n \\multicolumn{1}{|c|}{Output Listing}  &\r\n \\multicolumn{1}{c||}{\\S}     &\r\n \\multicolumn{3}{|c|}{Output File Triggered by Flag}  \\\\ \\cline{3-5}\r\n                  & & 1 & 2 & 3 \\\\ \\hline\r\nSpectral properties, all models  & \\ref{fname.spp}\r\n                                 & {\\tt fname.spp}\r\n                                 & {\\tt fname.spp}\r\n                                 & {\\tt fname.spp}\r\n                                 \\\\ \\cline{1-2} \\cline{5-5}\r\n\\q Slab, left-face spectra       & \\ref{Slab Output}\r\n                                 & & & {\\tt fname.zpp}\r\n                                 \\\\ \\hline\r\nDetailed spectra, each model     & \\ref{fname.s}\r\n                                 & {\\tt fname.stb}\r\n                                 & {\\tt fname.s\\#\\#\\#}\r\n                                 & {\\tt fname.s\\#\\#\\#}\r\n                                 \\\\ \\cline{1-2} \\cline{5-5}\r\n\\q Slab, left-face spectra       & \\ref{Slab Output}\r\n                                 & & & {\\tt fname.z\\#\\#\\#}\r\n                                 \\\\ \\hline\r\nImages                           & \\ref{imaging}\r\n                                 & {\\tt fname.itb}\r\n                                 & {\\tt fname.i\\#\\#\\#}\r\n                                 & {\\tt fname.i\\#\\#\\#}\r\n                                 \\\\ \\cline{1-2} \\cline{5-5}\r\n\\q Visibilities                  & \\ref{fname.v}\r\n                                 &&& {\\tt fname.v\\#\\#\\#}  \\\\\r\n                                 \\hline\r\nRadial profiles                  & \\ref{fname.r}\r\n                                 & {\\tt fname.rtb}\r\n                                 & {\\tt fname.r\\#\\#\\#}   &\r\n                                 \\\\ \\hline\r\nError messages                   & \\ref{fname.m}\r\n                                 & {\\tt fname.mtb}\r\n                                 & {\\tt fname.m\\#\\#\\#}   &\r\n                                 \\\\ \\hline\r\n\\end{tabular}\r\n\\end{center}\r\n\\end{table}\r\n\r\n\r\n\\Section{Pitfalls, Real and Imaginary} \\label{pitfalls}\r\n\r\nThis appendix provides a central depository of potential programming and\r\nnumerical problems. Some were already mentioned in the text and are repeated\r\nhere for completeness.\r\n\r\n\\begin{itemize}\r\n\\item\r\nFORTRAN requires termination of input records with a carriage return. Make sure\r\nyou press the ``Enter\" key whenever you enter a filename in the last line of\r\n{\\tt dusty.inp}.\r\n\r\n\\item\r\nIn preparing input files, the following two rules must be carefully observed:\r\n(1) all required input entries must be specified, and in the correct order; (2)\r\nthe equal sign, `=', must be entered only as a flag to numerical input. When\r\neither rule is violated and \\D\\ reaches the end of the input file while looking\r\nfor additional input, you will obtain the error message:\r\n\\begin{verbatim}\r\n     ****TERMINATED. EOF reached by RDINP while looking for input.\r\n     *** Last line read:\r\n\\end{verbatim}\r\nThis message is a clear sign that the input is out of order.\r\n\r\n\\item\r\nLinux apparently makes heavier demand on machine resources than Windows.  On\r\nany particular PC and a given value of {\\tt npY}, \\D\\ may execute properly\r\nunder Windows but not under Linux, dictating a smaller {\\tt npY}.\r\n\r\n\\item\r\n\\D's execution under the Solaris operating system occasionally gives the\r\nfollowing warning message:\r\n\\begin{verbatim}\r\n       Note: IEEE floating-point exception flags raised:\r\n            Inexact;  Underflow;\r\n        See the Numerical Computation Guide, ieee_flags(3M)\r\n\\end{verbatim}\r\nThis ominous message is triggered on Solaris also by other applications and is\r\nnot unique to \\D. The reason for it is not yet clear and it is not issued on\r\nother platforms. In spite of this statement, the code performs fine and\r\nproduces results identical to those on machines that do not issue this warning.\r\n\r\n\\item\r\nCRAY J90 machines have specific requirements on FORTRAN programs which prevent\r\n\\D\\ from running in its present form.  If you plan to run \\D\\ on this platform\r\nyou'll have to introduce some changes in the source code, such as replacing all\r\n{\\tt DOUBLE PRECISION} statements with {\\tt REAL*4} .\r\n\r\n\\end{itemize}\r\n\r\n\\vspace {1cm}\r\n\r\n\\Section{Sample Output File: {\\tt sphere1.out}} \\label{sphere1}\r\n\r\n\\begin{verbatim}\r\n ===========================\r\n  Output from program Dusty\r\n  Version: 2.0\r\n ===========================\r\n\r\n  INPUT parameters from file:\r\n  sphere1.inp\r\n\r\n* ----------------------------------------------------------------------\r\n* NOTES:\r\n* This is a simple version of an input file producing a minimal output.\r\n* ----------------------------------------------------------------------\r\n  Central source spectrum described by a black body\r\n  with temperature: 2500 K\r\n  --------------------------------------------\r\n  Abundances for supported grains:\r\n  Sil-Ow Sil-Oc Sil-DL grf-DL amC-Hn SiC-Pg\r\n  1.000  0.000  0.000  0.000  0.000  0.000\r\n  MRN size distribution:\r\n       Power q:  3.5\r\n  Minimal size: 5.00E-03 microns\r\n  Maximal size: 2.50E-01 microns\r\n  --------------------------------------------\r\n  Dust temperature on the inner boundary: 800  K\r\n  --------------------------------------------\r\n  Density described by 1/r**k with k =  2.0\r\n  Relative thickness: 1.000E+03\r\n  --------------------------------------------\r\n  Optical depth at 5.5E-01 microns: 1.00E+00\r\n  Required accuracy: 5%\r\n  --------------------------------------------\r\n\r\n  ====================================================\r\n  For compliance with the point-source assumption, the\r\n  following results should only be applied to sources\r\n  whose effective temperature exceeds 1737 K.\r\n  ====================================================\r\n\r\n  RESULTS:\r\n  --------\r\n ###   tau0   F1(W/m2)  r1(cm)    r1/rc   theta1  Td(Y) err\r\n ###     1        2        3        4        5      6    7\r\n ==========================================================\r\n   1 1.00E+00 2.88E+04 3.26E+14 8.78E+00 2.43E+00   44   0\r\n ==========================================================\r\n   (1) Optical depth at 5.5E-01 microns\r\n   (2) Bolometric flux at the inner radius\r\n   (3) Inner radius for L=1E4 Lsun\r\n   (4) Ratio of the inner to the stellar radius\r\n   (5) Angular size (in arcsec) when Fbol=1E-6 W/m2\r\n   (6) Dust temperature at the outer edge (in K)\r\n   (7) Maximum error in flux conservation (%)\r\n =================================================\r\n  Everything is OK for all models\r\n ========== THE END ==============================\r\n\\end{verbatim}\r\n\r\n\r\n\\Section{Sample Output File: \\tt slab1.out} \\label{slab1}\r\n\\begin{verbatim}\r\n ===========================\r\n  Output from program Dusty\r\n  Version: 2.0\r\n ===========================\r\n\r\n  INPUT parameters from file:\r\n  slab1.inp\r\n\r\n* ----------------------------------------------------------------------\r\n* NOTES:\r\n* This is a simple version of an input file for calculation in\r\n* planar geometry with single source illumination.\r\n* ----------------------------------------------------------------------\r\n  Left-side source spectrum described by a black body\r\n  with temperature: 2500 K\r\n  --------------------------------------------\r\n  Abundances for supported grains:\r\n  Sil-Ow Sil-Oc Sil-DL grf-DL amC-Hn SiC-Pg\r\n  1.000  0.000  0.000  0.000  0.000  0.000\r\n  MRN size distribution:\r\n       Power q:  3.5\r\n  Minimal size: 5.00E-03 microns\r\n  Maximal size: 2.50E-01 microns\r\n  --------------------------------------------\r\n  Dust temperature on the slab left boundary: 800  K\r\n  --------------------------------------------\r\n  Calculation in planar geometry:\r\n  cos of left illumination angle =   1.000E+00\r\n  R =   0.000E+00\r\n  --------------------------------------------\r\n  Optical depth at 5.5E-01 microns: 1.00E+00\r\n  Required accuracy: 5%\r\n  --------------------------------------------\r\n\r\n\r\n  RESULTS:\r\n  --------\r\n ###   tau0    Fe1(W/m2)   f1     r1(cm)  Td(K)  Te(L)  err\r\n ###     1        2         3       4       5      6     7\r\n ==========================================================\r\n   1 1.00E+00 2.59E+04  9.33E-01 3.43E+14  755 8.22E+02  0\r\n ==========================================================\r\n   (1) Optical depth at 5.5E-01 microns\r\n   (2) Bol.flux of the left-side source at the slab left boundary\r\n   (3) f1=F/Fe1, where F is the overall bol.flux in the slab\r\n   (4) Position of the left slab boundary for L=1E4 Lsun\r\n   (5) Dust temperature at the right slab face\r\n   (6) Effective temperature of the left source (in K)\r\n   (7) Maximum error in flux conservation (%)\r\n =================================================\r\n  Everything is OK for all models\r\n ========== THE END ==============================\r\n\\end{verbatim}\r\n\r\n\\newpage\r\n\\Section{Library of Optical Constants} \\label{nklib}\r\n\r\n\\D's distribution includes a library of data files with the complex refractive\r\nindices of various compounds of interest.  The files are standardized in the\r\nformat \\D\\ accepts. Included are the optical constants for the seven built-in\r\ndust types as well as other frequently encountered astronomical dust\r\ncomponents.  This library will be updated continuously at the \\D\\ site. The\r\nfollowing table lists all the files currently supplied.\r\n\r\n\\begin{table}[h]\r\n\\begin{center}\r\n\r\n\\caption{\\hfil Optical Constants Library Supplied with Dusty} \\centerline{}\r\n%\\renewcommand{\\arraystretch}{1.3}\r\n\r\n\\begin{tabular}{llrr}     \\hline \\hline\r\n \\tthdump{\\noalign{\\medskip}}\r\n \\multicolumn{1}{c}{File Name}    &\r\n \\multicolumn{1}{c}{Compound}     &\r\n \\multicolumn{1}{c}{Range (\\mic)} &\r\n \\multicolumn{1}{c}{Ref}\r\n \\\\ \\tthdump{\\noalign{\\medskip}}\r\n    \\hline\r\n    \\tthdump{\\noalign{\\smallskip}}\r\n\r\n{\\tt Al2O3-comp.nk} & Al$_2$O$_3$-compact        & 7.8 -- 200   & \\cite{Jena}  \\\\\r\n{\\tt Al2O3-por.nk}  & Al$_2$O$_3$-porous         & 7.8 -- 500   & \\cite{Jena}  \\\\\r\n{\\tt amC-hann.nk}   & amorphous carbon           & 0.04 -- 905  & \\cite{Hann88}\\\\\r\n{\\tt amC-zb1.nk}    & amorphous carbon (BE)      & 0.05 -- 1984 & \\cite{Zubko} \\\\\r\n{\\tt amC-zb2.nk}    & amorphous carbon (ACAR)\\q  & 0.04 -- 1984 & \\cite{Zubko} \\\\\r\n{\\tt amC-zb3.nk}    & amorphous carbon (ACH2)    & 0.04 -- 948  & \\cite{Zubko} \\\\\r\n{\\tt crbr300.nk}    & crystalline bronzite       & 6.7 -- 487.4 & \\cite{Henn97}\\\\\r\n{\\tt crMgFeSil.nk}  & crystalline silicate       & 6.7 -- 584.9 & \\cite{Jena}  \\\\\r\n{\\tt FeO.nk}        & FeO (5.7g/ccm)             & 0.2 -- 500   & \\cite{Jena}  \\\\\r\n{\\tt gloliMg50.nk}  & glassy olivine             & 0.2 -- 500   & \\cite{Dorsch}\\\\\r\n{\\tt glpyr300.nk}   & glassy pyroxene at 300 K   & 6.7 -- 487   & \\cite{Henn97}\\\\\r\n{\\tt glpyrMg50.nk}  & glassy pyroxene            & 0.2 -- 500   & \\cite{Dorsch}\\\\\r\n{\\tt glSil.nk}      & glassy silicate            & 0.4 -- 500   & \\cite{Jaeger}\\\\\r\n{\\tt grph1-dl.nk}   & graphite, $E \\perp c$      & 0.001 -- \\E3 & \\cite{DL84}  \\\\\r\n{\\tt grph2-dl.nk}   & graphite, $E \\parallel c$  & 0.001 -- \\E3 & \\cite{DL84}  \\\\\r\n{\\tt opyr-pwd.nk}   & ortho-pyroxenes - powder   & 5.0 -- 25    & \\cite{Roush} \\\\\r\n{\\tt opyr-slb.nk}   & ortho-pyroxenes - slab     & 5.0 -- 25    & \\cite{Roush} \\\\\r\n{\\tt OssOdef.nk}    & O-deficient CS silicate    & 0.4 -- \\E4   & \\cite{Oss92} \\\\\r\n{\\tt OssOrich.nk}   & O-rich IS silicate         & 0.4 -- \\E4   & \\cite{Oss92} \\\\\r\n{\\tt SiC-peg.nk}    & $\\alpha$-SiC               & 0.03 -- 2000 & \\cite{Peg88} \\\\\r\n{\\tt Sil-dlee.nk}   & ``Astronomical silicate\"   & 0.03 -- 2000 & \\cite{DL84}  \\\\\r\n{\\tt Sil-oss1.nk}   & warm O-deficient silicates & 0.4 -- \\E4   & \\cite{Oss92} \\\\\r\n{\\tt Sil-oss2.nk}   & cold O-rich silicate       & 0.4 -- \\E4   & \\cite{Oss92} \\\\\r\n\r\n\\noalign{\\medskip} \\hline\r\n\\end{tabular}\r\n\\end{center}\r\n\\end{table}\r\n\r\n\\end{document}\r\n", "meta": {"hexsha": "f8fc919afcf9afccb694955de07d253c2b2a9a7f", "size": 87936, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "releaseV2/Manual/manual.tex", "max_stars_repo_name": "ivezic/dusty", "max_stars_repo_head_hexsha": "89992eb4fd25290aa0bbc60730f977baac197f11", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2016-06-07T08:13:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T16:18:48.000Z", "max_issues_repo_path": "releaseV2/Manual/manual.tex", "max_issues_repo_name": "ivezic/dusty", "max_issues_repo_head_hexsha": "89992eb4fd25290aa0bbc60730f977baac197f11", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2018-01-08T05:18:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T18:37:11.000Z", "max_forks_repo_path": "releaseV2/Manual/manual.tex", "max_forks_repo_name": "ivezic/dusty", "max_forks_repo_head_hexsha": "89992eb4fd25290aa0bbc60730f977baac197f11", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-01-03T20:39:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-03T20:39:07.000Z", "avg_line_length": 47.8693522047, "max_line_length": 138, "alphanum_fraction": 0.6949144833, "num_tokens": 23278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.30305373774768574}}
{"text": "\\par\n\\section{Driver programs }\n\\label{section:SymbFac:drivers}\n\\par\n%=======================================================================\n\\begin{enumerate}\n%-----------------------------------------------------------------------\n\\item\n\\begin{verbatim}\ntestSymbFacInpMtx msglvl msgFile inETreeFile inDInpMtxFile\n                  outETreeFile outIVfile outIVLfile\n\\end{verbatim}\nThis driver program reads in an {\\tt ETree} object and a {\\tt InpMtx}\nobject and computes the symbolic factorization.\nThe {\\tt ETree} object is updated (the front sizes and boundary\nsizes may change) and is optionally written out to {\\tt outETreeFile}.\nThe old-to-new {\\tt IV} object is optionally written to\n{\\tt outIVfile}.\nThe {\\tt IVL} object that contains the symbolic factorization is\noptionally written to {\\tt outIVLfile}.\n\\par\n\\begin{itemize}\n\\item\nThe {\\tt msglvl} parameter determines the amount of output.\n\\item\nThe {\\tt msgFile} parameter determines the message file --- if {\\tt\nmsgFile} is {\\tt stdout}, then the message file is {\\it stdout},\notherwise a file is opened with {\\it append} status to receive any\noutput data.\n\\item\nThe {\\tt inETreeFile} parameter is the input file \nfor the {\\tt ETree} object. \nIt must be of the form {\\tt *.etreef} or {\\tt *.etreeb}.\nThe {\\tt ETree} object is read from the file via the\n{\\tt ETree\\_readFromFile()} method.\n\\item\nThe {\\tt inInpMtxFile} parameter is the input file \nfor the {\\tt InpMtx} object. \nIt must be of the form {\\tt *.inpmtxf} or {\\tt *.inpmtxb}.\nThe {\\tt InpMtx} object is read from the file via the\n{\\tt InpMtx\\_readFromFile()} method.\n\\item\nThe {\\tt outETreeFile} parameter is the output file for the \n{\\tt ETree} object. \nIf {\\tt outETreeFile} is {\\tt none} then the {\\tt ETree} object is not\nwritten to a file. \nOtherwise, the {\\tt ETree\\_writeToFile()} method is called to write\nthe object to \na formatted file (if {\\tt outETreeFile} is of the form \n{\\tt *.etreef}),\nor\na binary file (if {\\tt outETreeFile} is of the form {\\tt *.etreeb}).\n\\item\nThe {\\tt outIVfile} parameter is the output file for the \nvertex-to-front map {\\tt IV} object. \nIf {\\tt outIVfile} is {\\tt none} then the {\\tt IV} object is not\nwritten to a file. \nOtherwise, the {\\tt IV\\_writeToFile()} method is called to write\nthe object to a formatted file (if {\\tt outIVfile} is of the form \n{\\tt *.ivf}), or\na binary file (if {\\tt outIVfile} is of the form {\\tt *.ivb}).\n\\item\nThe {\\tt outIVLfile} parameter is the output file for the \nsymbolic factorization {\\tt IVL} object. \nIf {\\tt outIVLfile} is {\\tt none} then the {\\tt IVL} object is not\nwritten to a file. \nOtherwise, the {\\tt IVL\\_writeToFile()} method is called to write\nthe object to a formatted file (if {\\tt outIVLfile} is of the form \n{\\tt *.ivlf}), or\na binary file (if {\\tt outIVLfile} is of the form {\\tt *.ivlb}).\n\\end{itemize}\n%-----------------------------------------------------------------------\n\\item\n\\begin{verbatim}\ntestSymbFacGraph msglvl msgFile inETreeFile inGraphFile\n                 outETreeFile outIVfile outIVLfile\n\\end{verbatim}\nThis driver program reads in an {\\tt ETree} object and a {\\tt Graph}\nobject and computes the symbolic factorization.\nThe {\\tt ETree} object is updated (the front sizes and boundary\nsizes may change) and is optionally written out to {\\tt outETreeFile}.\nThe old-to-new {\\tt IV} object is optionally written to\n{\\tt outIVfile}.\nThe {\\tt IVL} object that contains the symbolic factorization is\noptionally written to {\\tt outIVLfile}.\n\\par\n\\begin{itemize}\n\\item\nThe {\\tt msglvl} parameter determines the amount of output.\n\\item\nThe {\\tt msgFile} parameter determines the message file --- if {\\tt\nmsgFile} is {\\tt stdout}, then the message file is {\\it stdout},\notherwise a file is opened with {\\it append} status to receive any\noutput data.\n\\item\nThe {\\tt inETreeFile} parameter is the input file \nfor the {\\tt ETree} object. \nIt must be of the form {\\tt *.etreef} or {\\tt *.etreeb}.\nThe {\\tt ETree} object is read from the file via the\n{\\tt ETree\\_readFromFile()} method.\n\\item\nThe {\\tt inGraphFile} parameter is the input file \nfor the {\\tt Graph} object. \nIt must be of the form {\\tt *.graphf} or {\\tt *.graphb}.\nThe {\\tt Graph} object is read from the file via the\n{\\tt Graph\\_readFromFile()} method.\n\\item\nThe {\\tt outETreeFile} parameter is the output file for the \n{\\tt ETree} object. \nIf {\\tt outETreeFile} is {\\tt none} then the {\\tt ETree} object is not\nwritten to a file. \nOtherwise, the {\\tt ETree\\_writeToFile()} method is called to write\nthe object to \na formatted file (if {\\tt outETreeFile} is of the form \n{\\tt *.etreef}),\nor\na binary file (if {\\tt outETreeFile} is of the form {\\tt *.etreeb}).\n\\item\nThe {\\tt outIVfile} parameter is the output file for the \nvertex-to-front map {\\tt IV} object. \nIf {\\tt outIVfile} is {\\tt none} then the {\\tt IV} object is not\nwritten to a file. \nOtherwise, the {\\tt IV\\_writeToFile()} method is called to write\nthe object to a formatted file (if {\\tt outIVfile} is of the form \n{\\tt *.ivf}), or\na binary file (if {\\tt outIVfile} is of the form {\\tt *.ivb}).\n\\item\nThe {\\tt outIVLfile} parameter is the output file for the \nsymbolic factorization {\\tt IVL} object. \nIf {\\tt outIVLfile} is {\\tt none} then the {\\tt IVL} object is not\nwritten to a file. \nOtherwise, the {\\tt IVL\\_writeToFile()} method is called to write\nthe object to a formatted file (if {\\tt outIVLfile} is of the form \n{\\tt *.ivlf}), or\na binary file (if {\\tt outIVLfile} is of the form {\\tt *.ivlb}).\n\\end{itemize}\n%-----------------------------------------------------------------------\n\\end{enumerate}\n", "meta": {"hexsha": "b26c758c6b144080f4263752aa6f986291402f62", "size": 5558, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ccx_prool/SPOOLES.2.2/SymbFac/doc/drivers.tex", "max_stars_repo_name": "alleindrach/calculix-desktop", "max_stars_repo_head_hexsha": "2cb2c434b536eb668ff88bdf82538d22f4f0f711", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ccx_prool/SPOOLES.2.2/SymbFac/doc/drivers.tex", "max_issues_repo_name": "alleindrach/calculix-desktop", "max_issues_repo_head_hexsha": "2cb2c434b536eb668ff88bdf82538d22f4f0f711", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-09-21T17:03:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-25T16:08:31.000Z", "max_forks_repo_path": "ccx_prool/SPOOLES.2.2/SymbFac/doc/drivers.tex", "max_forks_repo_name": "alleindrach/calculix-desktop", "max_forks_repo_head_hexsha": "2cb2c434b536eb668ff88bdf82538d22f4f0f711", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-08-29T18:41:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-29T18:41:28.000Z", "avg_line_length": 39.9856115108, "max_line_length": 72, "alphanum_fraction": 0.6831594099, "num_tokens": 1572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.30300370894963985}}
{"text": "\\documentclass{article}\n\n\\usepackage{GSReg-style}\n\n\\title{ModelSelection.jl \\\\\n       \\vspace{5mm} REPORT} \n\n%\\author{\n%  Insert author name \\\\\n%  Insert Institution/Affiliation \\\\\n%  Insert other researcher information \\\\\n%  \\texttt{insert@email.com} \\\\\n%   \\and if there are more authors\n%\\author{\n%  Insert author name \\\\\n%  insert Institution/Affiliation \\\\\n%  insert other researcher information \\\\\n%  \\texttt{insert@email.com} \\\\\n%}\n\n\\begin{document}\n\n\\maketitle\n\n\\vspace{5mm}\n\\tableofcontents\n\\clearpage\n\n\n\\section{Introduction}\nThe advantage of having thousands/millions of features to deal with complex phenomena stimulates an unprecedented number of methodological -and technological- improvements to manage the ‘curse of dimensionality’. \n\nIn Economics, this process has a dual approach with machine-learning (ML) and econometric (EC) algorithms emerging for different purposes: the former for prediction/forecasts (focusing on $\\hat{y}$) and the latter for estimation/causal inference (interested in $\\hat{\\beta}$). Alternatively, the same distinction can be expressed in Diebold’s terms as non-causal vs causal prediction, where ML algorithms are designed to reduce prediction sampling-risks -i.e. learning through cross-validation techniques- and EC methods to identify unbiased multivariate relationships -i.e. avoiding consistency issues through residual and coefficient tests for model selection. \n\nFollowing Varian’s advices, about ML and EC complementarities -i.e. merging algorithms from different families to reduce both sampling and model uncertainty-, we are developing a novel multi-layer-multi-algorithm methodology combining two reinforcing paradigms: The London School of Economics (LSE) “Testimation” approach -to obtain information about residual properties- and the Bayesian-like “Double-model averaging” -across different covariates and sub-samples. This methodology includes five complementary layers -handling cross-section, time series and panel data- see \\cite{gsreg2019}: \n\n\\begin{enumerate}\n    \\item Pre-processing: with outlier detection, missing values identification, seasonal adjustment and normalization/standardization functions; \n    \n    \\item Feature extraction: creation of logs, squares, inverses and interactions from selected variables;\n    \n    \\item Feature pre-selection: using filter and embedded ML algorithms like CFS, Variance threshold and LASSO functions; \n    \n    \\item Final feature selection: with a modified all-subset regression approach, including residual tests and model averaging capabilities; \n    \n    \\item Post-estimation fine-tuning: coefficient re-evaluation through cross-validation techniques and model averaging across different k-fold results. \n\\end{enumerate}\n\nIn order to implement this feature selection algorithm, the following syntax has been used:\n\n\\begin{lstlisting} \n  using ModelSelection\n  ModelSelection.gsr(\n    equation = \"y x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 x16 x17 x18 x19 x20 x21 x22 x23 x24 x25 x26 x27 x28 x29 x30 x31 x32 x33 x34 x35 x36 x37 x38 x39 x40 x41 x42 x43 x44 x45 x46 x47 x48 x49 x50 x51 x52 x53 x54 x55 x56 x57 x58 x59 x60 x61 x62 x63 x64 x65 x66 x67 x68 x69 x70 x71 x72 x73 x74 x75 x76 x77 x78 x79 x80 x81 x82 x83 x84 x85 x86 x87 x88 x89 x90 x91 x92 x93 x94 x95 x96 x97 x98 x99 x100 x101 x102 x103 x104 x105 x106 x107 x108 x109 x110 x111 x112 x113 x114 x115 x116 x117 x118 x119 x120 x121 x122 x123 x124 x125 x126 x127 x128 x129 x130 x131 x132 x133 x134 x135 x136 x137 x138 x139 x140 x141 x142 x143 x144 x145 x146 x147 x148 x149 x150 x151 x152 x153 x154 x155 x156 x157 x158 x159 x160 x161 x162 x163 x164 x165 x166 x167 x168 x169 x170 x171 x172 x173 x174 x175 x176 x177 x178 x179 x180 x181 x182 x183 x184 x185 x186 x187 x188 x189 x190 x191 x192 x193 x194 x195 x196 x197 x198 x199 x200 x201 x202 x203 x204 x205 x206 x207 x208 x209 x210 x211 x212 x213 x214 x215 x216 x217 x218 x219 x220 x221 x222 x223 x224 x225 x226 x227 x228 x229 x230 x231 x232 x233 x234 x235 x236 x237 x238 x239 x240 x241 x242 x243 x244 x245 x246 x247 x248 x249 x250 x251 x252 x253 x254 x255 x256 x257 x258 x259 x260 x261 x262 x263 x264 x265 x266 x267 x268 x269 x270 x271 x272 x273 x274 x275 x276 x277 x278 x279 x280 x281 x282 x283 x284 x285 x286 x287 x288 x289 x290 x291 x292 x293 x294 x295 x296 x297 x298 x299 x300 x301 x302 x303 x304 x305 x306 x307 x308 x309 x310 x311 x312 x313 x314 x315 x316 x317 x318 x319 x320 x321 x322 x323 x324 x325 x326 x327 x328 x329 x330 x331 x332 x333 x334 x335 x336 x337 x338 x339 x340 x341 x342 x343 x344 x345 x346 x347 x348 x349 x350 x351 x352 x353 x354 x355 x356 x357 x358 x359 x360 x361 x362 x363 x364 x365 x366 x367 x368 x369 x370 x371 x372 x373 x374 x375 x376 x377 x378 x379 x380 x381 x382 x383 x384 x385 x386 x387 x388 x389 x390 x391 x392 x393 x394 x395 x396 x397 x398 x399 x400 x401 x402 x403 x404 x405 x406 x407 x408 x409 x410 x411 x412 x413 x414 x415 x416 x417 x418 x419 x420 x421 x422 x423 x424 x425 x426 x427 x428 x429 x430 x431 x432 x433 x434 x435 x436 x437 x438 x439 x440 x441 x442 x443 x444 x445 x446 x447 x448 x449 x450 x451 x452 x453 x454 x455 x456 x457 x458 x459 x460 x461 x462 x463 x464 x465 x466 x467 x468 x469 x470 x471 x472 x473 x474 x475 x476 x477 x478 x479 x480 x481 x482 x483 x484 x485 x486 x487 x488 x489 x490 x491 x492 x493 x494 x495 x496 x497 x498 x499 x500 x501 x502 x503 x504 x505 x506 x507 x508 x509 x510 x511 x512 x513 x514 x515 x516 x517 x518 x519 x520 x521 x522 x523 x524 x525 x526 x527 x528 x529 x530 x531 x532 x533 x534 x535 x536 x537 x538 x539 x540 x541 x542 x543 x544 x545 x546 x547 x548 x549 x550 x551 x552 x553 x554 x555 x556 x557 x558 x559 x560 x561 x562 x563 x564 x565 x566 x567 x568 x569 x570 x571 x572 x573 x574 x575 x576 x577 x578 x579 x580 x581 x582 x583 x584 x585 x586 x587 x588 x589 x590 x591 x592 x593 x594 x595 x596 x597 x598 x599 x600 x601 x602 x603 x604 x605 x606 x607 x608 x609 x610 x611 x612 x613 x614 x615 x616 x617 x618 x619 x620 x621 x622 x623 x624 x625 x626 x627 x628 x629 x630 x631 x632 x633 x634 x635 x636 x637 x638 x639 x640 x641 x642 x643 x644 x645 x646 x647 x648 x649 x650 x651 x652 x653 x654 x655 x656 x657 x658 x659 x660 x661 x662 x663 x664 x665 x666 x667 x668 x669 x670 x671 x672 x673 x674 x675 x676 x677 x678 x679 x680 x681 x682 x683 x684 x685 x686 x687 x688 x689 x690 x691 x692 x693 x694 x695 x696 x697 x698 x699 x700 x701 x702 x703 x704 x705 x706 x707 x708 x709 x710 x711 x712 x713 x714 x715 x716 x717 x718 x719 x720 x721 x722 x723 x724 x725 x726 x727 x728 x729 x730 x731 x732 x733 x734 x735 x736 x737 x738 x739 x740 x741 x742 x743 x744 x745 x746 x747 x748 x749 x750 x751 x752 x753 x754 x755 x756 x757 x758 x759 x760 x761 x762 x763 x764 x765 x766 x767 x768 x769 x770 x771 x772 x773 x774 x775 x776 x777 x778 x779 x780 x781 x782 x783 x784 x785 x786 x787 x788 x789 x790 x791 x792 x793 x794 x795 x796 x797 x798 x799 x800 x801 x802 x803 x804 x805 x806 x807 x808 x809 x810 x811 x812 x813 x814 x815 x816 x817 x818 x819 x820 x821 x822 x823 x824 x825 x826 x827 x828 x829 x830 x831 x832 x833 x834 x835 x836 x837 x838 x839 x840 x841 x842 x843 x844 x845 x846 x847 x848 x849 x850 x851 x852 x853 x854 x855 x856 x857 x858 x859 x860 x861 x862 x863 x864 x865 x866 x867 x868 x869 x870 x871 x872 x873 x874 x875 x876 x877 x878 x879 x880 x881 x882 x883 x884 x885 x886 x887 x888 x889 x890 x891 x892 x893 x894 x895 x896 x897 x898 x899 x900 x901 x902 x903 x904 x905 x906 x907 x908 x909 x910 x911 x912 x913 x914 x915 x916 x917 x918 x919 x920 x921 x922 x923 x924 x925 x926 x927 x928 x929 x930 x931 x932 x933 x934 x935 x936 x937 x938 x939 x940 x941 x942 x943 x944 x945 x946 x947 x948 x949 x950 x951 x952 x953 x954 x955 x956 x957 x958 x959 x960 x961 x962 x963 x964 x965 x966 x967 x968 x969 x970 x971 x972 x973 x974 x975 x976 x977 x978 x979 x980 x981 x982 x983 x984 x985 x986 x987 x988 x989 x990 x991 x992 x993 x994 x995 x996 x997 x998 x999 x1000\",\n    data = dataname,\n    datanames = [:y, :x1, :x2, :x3, :x4, :x5, :x6, :x7, :x8, :x9, :x10, :x11, :x12, :x13, :x14, :x15, :x16, :x17, :x18, :x19, :x20, :x21, :x22, :x23, :x24, :x25, :x26, :x27, :x28, :x29, :x30, :x31, :x32, :x33, :x34, :x35, :x36, :x37, :x38, :x39, :x40, :x41, :x42, :x43, :x44, :x45, :x46, :x47, :x48, :x49, :x50, :x51, :x52, :x53, :x54, :x55, :x56, :x57, :x58, :x59, :x60, :x61, :x62, :x63, :x64, :x65, :x66, :x67, :x68, :x69, :x70, :x71, :x72, :x73, :x74, :x75, :x76, :x77, :x78, :x79, :x80, :x81, :x82, :x83, :x84, :x85, :x86, :x87, :x88, :x89, :x90, :x91, :x92, :x93, :x94, :x95, :x96, :x97, :x98, :x99, :x100, :x101, :x102, :x103, :x104, :x105, :x106, :x107, :x108, :x109, :x110, :x111, :x112, :x113, :x114, :x115, :x116, :x117, :x118, :x119, :x120, :x121, :x122, :x123, :x124, :x125, :x126, :x127, :x128, :x129, :x130, :x131, :x132, :x133, :x134, :x135, :x136, :x137, :x138, :x139, :x140, :x141, :x142, :x143, :x144, :x145, :x146, :x147, :x148, :x149, :x150, :x151, :x152, :x153, :x154, :x155, :x156, :x157, :x158, :x159, :x160, :x161, :x162, :x163, :x164, :x165, :x166, :x167, :x168, :x169, :x170, :x171, :x172, :x173, :x174, :x175, :x176, :x177, :x178, :x179, :x180, :x181, :x182, :x183, :x184, :x185, :x186, :x187, :x188, :x189, :x190, :x191, :x192, :x193, :x194, :x195, :x196, :x197, :x198, :x199, :x200, :x201, :x202, :x203, :x204, :x205, :x206, :x207, :x208, :x209, :x210, :x211, :x212, :x213, :x214, :x215, :x216, :x217, :x218, :x219, :x220, :x221, :x222, :x223, :x224, :x225, :x226, :x227, :x228, :x229, :x230, :x231, :x232, :x233, :x234, :x235, :x236, :x237, :x238, :x239, :x240, :x241, :x242, :x243, :x244, :x245, :x246, :x247, :x248, :x249, :x250, :x251, :x252, :x253, :x254, :x255, :x256, :x257, :x258, :x259, :x260, :x261, :x262, :x263, :x264, :x265, :x266, :x267, :x268, :x269, :x270, :x271, :x272, :x273, :x274, :x275, :x276, :x277, :x278, :x279, :x280, :x281, :x282, :x283, :x284, :x285, :x286, :x287, :x288, :x289, :x290, :x291, :x292, :x293, :x294, :x295, :x296, :x297, :x298, :x299, :x300, :x301, :x302, :x303, :x304, :x305, :x306, :x307, :x308, :x309, :x310, :x311, :x312, :x313, :x314, :x315, :x316, :x317, :x318, :x319, :x320, :x321, :x322, :x323, :x324, :x325, :x326, :x327, :x328, :x329, :x330, :x331, :x332, :x333, :x334, :x335, :x336, :x337, :x338, :x339, :x340, :x341, :x342, :x343, :x344, :x345, :x346, :x347, :x348, :x349, :x350, :x351, :x352, :x353, :x354, :x355, :x356, :x357, :x358, :x359, :x360, :x361, :x362, :x363, :x364, :x365, :x366, :x367, :x368, :x369, :x370, :x371, :x372, :x373, :x374, :x375, :x376, :x377, :x378, :x379, :x380, :x381, :x382, :x383, :x384, :x385, :x386, :x387, :x388, :x389, :x390, :x391, :x392, :x393, :x394, :x395, :x396, :x397, :x398, :x399, :x400, :x401, :x402, :x403, :x404, :x405, :x406, :x407, :x408, :x409, :x410, :x411, :x412, :x413, :x414, :x415, :x416, :x417, :x418, :x419, :x420, :x421, :x422, :x423, :x424, :x425, :x426, :x427, :x428, :x429, :x430, :x431, :x432, :x433, :x434, :x435, :x436, :x437, :x438, :x439, :x440, :x441, :x442, :x443, :x444, :x445, :x446, :x447, :x448, :x449, :x450, :x451, :x452, :x453, :x454, :x455, :x456, :x457, :x458, :x459, :x460, :x461, :x462, :x463, :x464, :x465, :x466, :x467, :x468, :x469, :x470, :x471, :x472, :x473, :x474, :x475, :x476, :x477, :x478, :x479, :x480, :x481, :x482, :x483, :x484, :x485, :x486, :x487, :x488, :x489, :x490, :x491, :x492, :x493, :x494, :x495, :x496, :x497, :x498, :x499, :x500, :x501, :x502, :x503, :x504, :x505, :x506, :x507, :x508, :x509, :x510, :x511, :x512, :x513, :x514, :x515, :x516, :x517, :x518, :x519, :x520, :x521, :x522, :x523, :x524, :x525, :x526, :x527, :x528, :x529, :x530, :x531, :x532, :x533, :x534, :x535, :x536, :x537, :x538, :x539, :x540, :x541, :x542, :x543, :x544, :x545, :x546, :x547, :x548, :x549, :x550, :x551, :x552, :x553, :x554, :x555, :x556, :x557, :x558, :x559, :x560, :x561, :x562, :x563, :x564, :x565, :x566, :x567, :x568, :x569, :x570, :x571, :x572, :x573, :x574, :x575, :x576, :x577, :x578, :x579, :x580, :x581, :x582, :x583, :x584, :x585, :x586, :x587, :x588, :x589, :x590, :x591, :x592, :x593, :x594, :x595, :x596, :x597, :x598, :x599, :x600, :x601, :x602, :x603, :x604, :x605, :x606, :x607, :x608, :x609, :x610, :x611, :x612, :x613, :x614, :x615, :x616, :x617, :x618, :x619, :x620, :x621, :x622, :x623, :x624, :x625, :x626, :x627, :x628, :x629, :x630, :x631, :x632, :x633, :x634, :x635, :x636, :x637, :x638, :x639, :x640, :x641, :x642, :x643, :x644, :x645, :x646, :x647, :x648, :x649, :x650, :x651, :x652, :x653, :x654, :x655, :x656, :x657, :x658, :x659, :x660, :x661, :x662, :x663, :x664, :x665, :x666, :x667, :x668, :x669, :x670, :x671, :x672, :x673, :x674, :x675, :x676, :x677, :x678, :x679, :x680, :x681, :x682, :x683, :x684, :x685, :x686, :x687, :x688, :x689, :x690, :x691, :x692, :x693, :x694, :x695, :x696, :x697, :x698, :x699, :x700, :x701, :x702, :x703, :x704, :x705, :x706, :x707, :x708, :x709, :x710, :x711, :x712, :x713, :x714, :x715, :x716, :x717, :x718, :x719, :x720, :x721, :x722, :x723, :x724, :x725, :x726, :x727, :x728, :x729, :x730, :x731, :x732, :x733, :x734, :x735, :x736, :x737, :x738, :x739, :x740, :x741, :x742, :x743, :x744, :x745, :x746, :x747, :x748, :x749, :x750, :x751, :x752, :x753, :x754, :x755, :x756, :x757, :x758, :x759, :x760, :x761, :x762, :x763, :x764, :x765, :x766, :x767, :x768, :x769, :x770, :x771, :x772, :x773, :x774, :x775, :x776, :x777, :x778, :x779, :x780, :x781, :x782, :x783, :x784, :x785, :x786, :x787, :x788, :x789, :x790, :x791, :x792, :x793, :x794, :x795, :x796, :x797, :x798, :x799, :x800, :x801, :x802, :x803, :x804, :x805, :x806, :x807, :x808, :x809, :x810, :x811, :x812, :x813, :x814, :x815, :x816, :x817, :x818, :x819, :x820, :x821, :x822, :x823, :x824, :x825, :x826, :x827, :x828, :x829, :x830, :x831, :x832, :x833, :x834, :x835, :x836, :x837, :x838, :x839, :x840, :x841, :x842, :x843, :x844, :x845, :x846, :x847, :x848, :x849, :x850, :x851, :x852, :x853, :x854, :x855, :x856, :x857, :x858, :x859, :x860, :x861, :x862, :x863, :x864, :x865, :x866, :x867, :x868, :x869, :x870, :x871, :x872, :x873, :x874, :x875, :x876, :x877, :x878, :x879, :x880, :x881, :x882, :x883, :x884, :x885, :x886, :x887, :x888, :x889, :x890, :x891, :x892, :x893, :x894, :x895, :x896, :x897, :x898, :x899, :x900, :x901, :x902, :x903, :x904, :x905, :x906, :x907, :x908, :x909, :x910, :x911, :x912, :x913, :x914, :x915, :x916, :x917, :x918, :x919, :x920, :x921, :x922, :x923, :x924, :x925, :x926, :x927, :x928, :x929, :x930, :x931, :x932, :x933, :x934, :x935, :x936, :x937, :x938, :x939, :x940, :x941, :x942, :x943, :x944, :x945, :x946, :x947, :x948, :x949, :x950, :x951, :x952, :x953, :x954, :x955, :x956, :x957, :x958, :x959, :x960, :x961, :x962, :x963, :x964, :x965, :x966, :x967, :x968, :x969, :x970, :x971, :x972, :x973, :x974, :x975, :x976, :x977, :x978, :x979, :x980, :x981, :x982, :x983, :x984, :x985, :x986, :x987, :x988, :x989, :x990, :x991, :x992, :x993, :x994, :x995, :x996, :x997, :x998, :x999, :x1000, :_cons],\n    method = :precise,\n    intercept = true,\n    removeoutliers = ,\n    preliminaryselection = :lasso,\n    outsample = 10,\n    criteria = [:aic, :aicc, :cp, :r2adj, :rmseout],\n    ttest = true,\n    modelavg = true,\n    residualtest = true,\n    orderresults = true,\n    kfoldcrossvalidation = Dict{Any,Any}(&quot;median&quot;=&gt;[3.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 -0.110223 0.117787 -1.06407 66.0 3.0 56.7211 0.225622 9.63996 0.927044 1.06744 0.201039 0.7426 2.4323e-6 0.655581 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0],&quot;kfolds&quot;=&gt;3,&quot;average&quot;=&gt;[3.33333 0.121148 0.033808 1.19447 -0.135271 0.0442381 -1.01926 0.0 0.0 0.0 -0.102466 0.114535 -0.896072 66.6667 2.66667 55.1408 0.206017 10.058 0.90649 1.1032 0.185638 0.671841 1.62484e-5 0.581203 0.106131 0.0382284 0.925414 0.0920784 0.0328706 0.933747 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 -0.115661 0.037252 -1.03494],&quot;datanames&quot;=&gt;Symbol[:index, :x6_b, :x6_bstd, :x6_t, :x8_b, :x8_bstd, :x8_t, :x932_b, :x932_bstd, :x932_t, :_cons_b, :_cons_bstd, :_cons_t, :nobs, :ncoef, :sse, :r2, :F, :rmse, :rmseout, :r2adj, :jbtest, :wtest, :order, :x348_b, :x348_bstd, :x348_t, :x806_b, :x806_bstd, :x806_t, :x964_b, :x964_bstd, :x964_t, :x61_b, :x61_bstd, :x61_t, :x428_b, :x428_bstd, :x428_t, :x599_b, :x599_bstd, :x599_t],&quot;tsetsize&quot;=&gt;0.0,&quot;ttest&quot;=&gt;true),\n  )\n\\end{lstlisting}\n\nThe report is structured as follows. After this introduction, the methodology is presented. In section 3, descriptive statistics are introduced. After that, LASSO results are examined. Then, All-subset-regression analysis is shown. Finally, the last section examines K-fold cross-validation outcomes.\n\n\\section{Methodology}\n\n\\subsection{Pre-processing}\nIt performs required variable transformations to improve model accuracy and feature selection. In this report, it has been used the following internal pre-processing functions:\n\n\\begin{enumerate}\n  \\item Remove-missings: Rows with missing values have been ommited for regression purposes.\n\n  \n\n\\end{enumerate}\n\\subsection{Regularization - LASSO}\nThe Least Absolute Shrinkage and Selection Operator (LASSO) algorithm is a type of regularized linear regression that uses shrinkage (see \\cite{tibshirani1996}) to obtain simple sparse models. This particular type of regression is well-suited for feature selection in models with high levels of muticollinearity, and particularly efficient in fat-data scenarios.\n\nThe LASSO regression is a Machine Learning wrapper algorithm (see \\cite{chandrashekar2014}) that performs L1 regularization on the optimization function. It adds a penalty term proportional to the sum of coefficients absolute values. With this type of regularization some estimation parameters become zero and -therefore- associated variables can eliminated from the model.\n\\begin{equation}\n    \\sum_{n=1}^{n}(y_i - \\sum_{j}x_{ij}\\beta_{j})^2 + \\lambda \\sum_{j=1}^p|\\beta_{j}|\n\\end{equation}\n\nEquation (1) entails a residual sum of squares minimization with constraint $\\sum \\beta_{j}\\leq s$. Some of the $\\beta_s$ are shrunk to zero, resulting in a more parsimonious regression model.\n\nA tuning parameter, $\\lambda$ controls the strength of the L1 penalty. $\\lambda$ is basically the amount of shrinkage:\n\nWhen $ \\lambda = 0$, no parameters are eliminated. LASSO estimates replicate OLS ones.\n\nAs $\\lambda$ increases, more and more coefficients are set to zero and associated variables can be eliminated (theoretically, when $\\lambda = \\infty$, no covariate is retained).\n\nThe choice of $\\lambda$ entails a well-known trade-off:  As $\\lambda$ increases, estimator bias increases but as $\\lambda$ decreases, estimator variance increases (i.e. omitted variables vs model over-fitting).\n\nIn this report, the $\\lambda$ parameter has been dynamically defined in order to retain up to 3 covariates.\n\nIt must be noticed that all predictors are standardized \"on-the-fly\", in order to avoid scale issues in feature selection.\n\n\\subsection{All-subset-Regression}\nUnlike other feature selection algorithms (including LASSO), All-subset-regression (ASR) approaches guarantees both in-sample and out-of-sample optimality (i.e. better information criteria results than any other method). However, it has been left aside by econometricians and machine learning practitioners because of computational concerns. Execution times for ASR algorithms in a more-than-20-covariates environement were prohibitive until now. Using existing ASR packages, a simple feature selection problem for 20 covariates usually takes more than 8000 seconds in \n\\href{https://cran.r-project.org/web/packages/MuMIn/MuMIn.pdf}{R}, and more than 500000 seconds in \\href{https://ideas.repec.org/c/boc/bocode/s457737.html#download}{Stata}. Moreover, with 25 potential covariates both algorithms are unable to obtain feasible-solutions in standard personal computers.\n\nFortunately, the \\verb ModelSelection.jl package has significantly reduced execution times, running up to 3165 times faster than Stata and 197 times faster than R (see \\cite{gsreg2019}). This improvement allows researchers to regain attention on ASR algorithms, looking for better feature selection results.\n\nIn this Julia package, the best model among $2^{n}-1$ alternatives is selected using a potentially composite ordering variable defined as the equally-weighted average of normalized (to guarantee equal weights) and harmonized (to ensure that higher values always identify better models) user's specified criteria. For in-sample adjustment, available alternatives include: Adjusted R2 (:r2adj, the default), Bayesian information criteria (:bic), Akaike and Corrected Akaike information criteria (:aic and :aicc), Mallows's Cp statistic (:cp), Sum of squared errors (also known as Residual sum of squares, :sse) and the Root mean square error (:rmse). For out-of-sample accuracy, there is available the out-of-sample root mean square error (:rmsout). Users are free to combine in-sample and out-of-sample information criteria. In this report, selected information criteria include ([:aic, :aicc, :cp, :r2adj, :rmseout]) as the key variable/s for feature selection.\n\nAdditional options applied in this report includes:\n\n\\begin{enumerate}\n  \\item Intercept has been included in all models. Alternatively, users could erase it by selecting the intercept=false boolean option.\n  \\item The outsample option identifies how many observations are used for prediction purposes. In this case, it has been set to 10.\n  \\item The user's choice has been ttest=true. Therefore, standard deviation, ttest parameters and related probabilities has been calculated.\n  \\item Across-models' average coefficients, t-tests and additional statistics were obtained using combined-criteria exponential weights because of the modelavg=true option. More precisely, each alternative model has a weight given by w1/sum(w1), where w1 is defined as exp(-delta/2) and delta is equal to max(index)-index -- where index is the above mentioned normalized, harmonized and potentially combined selection criteria--.\n  \\item The residualtest=true option enables white heteroskedasticity and Jarque-Bera normality test to be implemented for each model.\n  \\item The residualtest=true option enables white heteroskedasticity, Jarque-Bera normality test and the Breusch-Godfrey test for autocorrelation to be implemented for each model.\n  \\item User's specification of orderresults=true entails that the output matrix has been sorted by the the above mentioned normalized, harmonized and potentially combined selection criteria.\n\\end{enumerate}\n\\subsection{K-fold Cross Validation}\n\nCross-validation (CV) is a procedure used to examine feature selection robustness to re-sampling. Among different alternatives, the K-fold approach has a parameter $K$ which identifies the number of groups that a given database must be split into (see \\cite{arlot2010}). In this report user selected k-fold number is 3.\n\nThe general procedure is as follows:\n\n\\begin{enumerate}\n  \\item Randomly split the database into k disjoint -roughly equally sized- groups\n  \\item For each group:\n  \\begin{enumerate}\n    \\item Take a group as a hold out or test data set (leave-one-out scheme);\n    \\item Take the remaining groups together as a training data set;\n    \\item Fit a model on the training set and evaluate it on the test set; and\n    \\item Retain the evaluation (i.e out-of-sample Root Mean Square Error -RMSE-).\n  \\end{enumerate}\n  \\item Summarize model strengths using CV scores\n\\end{enumerate}\n\nIn \\verb ModelSelection.jl  the K-fold cross-validation is available for both LASSO pre-selection and ASR final selection. In the latter, for each K-partition $2^{p} - 1$ alternative models are fitted (where p is the number of potential covariates included in the ASR algorithm) and the candidate ‘optimal’ model is selected using the out-of-sample Root Mean Square Error (obtained from the test set). Therefore, K-candidate models are retained (one for each K-partition). The final \"best\" model is obtained using either across-model averages or medians.\n\nThis cross-validation specific alternative has been denominated as \\textit{Averaging Cross validation (ACV)} by Jung and Hu (see, \\cite{jung2015}). The authors found that:\n\n\\begin{quote}\n\"Due to the averaging effect, efficiency of the final parameter estimates obtained by ACV improves over that of the traditional K-fold CV. We note that parameter estimates of CV and ACV are identical when all the candidate ‘optimal’ models from ACV are identical to the model selected by the traditional CV.\"\n\n\\hfill Jung and Hu (2015:168)\n\\end{quote}\n\nIt is worth mentioning that K-fold preferred methodologies change depending on whether cross-section, time-series or panel data observations are employed. For the first one, standard K-fold random allocation is the gold-standard (see \\cite{arlot2010}). \n\n\\section{Descriptive Statistics}\n\nMain descriptive statistics for All-subset-regression potential covariates are presented in table 1:\n\n\\clearpage\n\n\\begin{table}[!h]\n  \\centering\n  \\caption{Descriptive Statistics for the main dataset}\n    \\begin{tabular}{|p{2cm}|p{4cm}|c|c|c|c|c|c|}\n    \\hline\n    Variable & Description & Obs. & Mean & Sd & Max & Min & \\% Miss \\\\\n    \\hline\n    \\hline\n    x263 & Insert Description & 100 & -0.07 & 1.12 & 2.81 & -2.97 & 0.00\\% \\\\ \n    x779 & Insert Description & 100 & 0.10 & 1.00 & 2.72 & -2.40 & 0.00\\% \\\\ \n    x813 & Insert Description & 100 & -0.02 & 0.88 & 3.64 & -1.77 & 0.00\\% \\\\ \n    \\_cons & Insert Description & 100 & 1.00 & 0.00 & 1.00 & 1.00 & 0.00\\% \\\\ \n    \\hline\n    \\end{tabular}\n\\end{table}\n\n\\section{Regularization results}\n\nLASSO regression is shown in the following table:\n\n\\begin{table}[!h]\n  \\centering\n  \\caption{LASSO Regression results}\n    \\begin{tabular}{l c}\n    \\hline\n    \\hline\n              & \\\\\n    Variables & y \\\\\n    \\hline\n    \\hline\n      x263 & -0.015 \\\\\n      x779 & -0.005 \\\\\n      x813 & -0.001 \\\\\n    \\hline\n    \\hline\n    Observations &  100 \\\\\n    \\lambda      &  0.282 \\\\\n    \\hline\n    \\end{tabular}\n  \\label{tab:addlabel}\n\\end{table}\n\n\n\\clearpage\n\\section{Global Search Regression}\n\n\\subsection{All sub-subset regression: Best Model and Model Averaging}\n\n\\begin{table}[!h]\n  \\centering\n  \\caption{GSReg results}\n    \n    \\begin{tabular}{l c c}\n    \\hline\n    \\hline\n                 &  Best Model               & Model Averaging            \\\\\n    Variables    &  y               & y                 \\\\\n    \\hline \n    x263     & -0.253***  & -0.264***     \\\\\n                 & 0.088        & 0.089  \\\\\n     \n    x779     & -0.230**  & -0.253**     \\\\\n                 & 0.100        & 0.103  \\\\\n     \n    x813     & -0.280**  & -0.299**     \\\\\n                 & 0.115        & 0.118  \\\\\n     \n    \\_cons     & -0.127  & -0.128     \\\\\n                 & 0.101        & 0.104  \\\\\n    \\hline\n\n    Observations &   \\multicolumn{ 1  }{c}{ 100 } \\\\\n    Criteria     &   \\multicolumn{ 1  }{c}{ [:aic, :aicc, :cp, :r2adj, :rmseout] } \\\\\n    \\hline\n    \\hline\n    \\multicolumn{ 2  }{c}{Standard errors in parentheses} \\\\\n    \\multicolumn{ 2  }{c}{*** p < 0.01, ** p < 0.05, * p < 0.1} \\\\\n    \\end{tabular}\n  \\label{tab:addlabel}\n\\end{table}\n\n\\subsection{Coefficient, t-test and selection criteria gains distributions}\n\nIn the following pages, coefficient, t-test and selection criteria distributions are presented. For each covariate, four figures are included: two bivariate density plots (a contour plot and a wireframe plot, for coefficients and t-tests distributions) and two selection criteria contribution plots (a Kernel density plot and a combined Box-Violin plot). The last two plots are used to see the combined\\_criteria\\_index variation explained by the inclusion of each covariate in the models. \nFinally, we include a unique figure where covariate relative performance is compared using the average impact of each explanatory variable on the combined\\_criteria\\_index.\n\n\\clearpage\n\n\\begin{center}\n    \\large{\\textbf{Coefficient, t-test and selection criteria gains distributions for x263 }}\n\\end{center}\n\n\\vspace{-5mm}\n\n\\begin{figure}[!ht]\n  \\centering\n  \\begin{minipage}[b]{0.46\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{contour_x263_b_t.png}\n    \\caption{Bivariate Kernel density (Contour view)}\n  \\end{minipage}\n  \\hfill\n  \\begin{minipage}[b]{0.53\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{wireframe_x263_b_t.png}\n    \\caption{Bivariate Kernel density (Contour view)}\n  \\end{minipage}\n\n  \\begin{minipage}[b]{0.48\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{Kdensity_criteria_x263.png}\n    \\caption{Selection criteria gains for including x263 (Kernel view)}\n  \\end{minipage}\n  \\hfill\n  \\begin{minipage}[b]{0.48\\textwidth}\n    \\centering    \n    \\includegraphics[width=\\textwidth]{BoxViolinDot_x263.png}\n    \\caption{Selection criteria gains for including x263 (Box-Violin view)}    \n  \\end{minipage}\n\\end{figure}\n\n\\vspace{1cm}\n\nThe following table shows main statistics of coefficient and t-test distribution \n\n\\begin{table}[!h]\n    \\centering\n    \\caption{Statistics}\n    \\begin{tabular}{|l|c|c|}\n    \\hline\n    Variable x263 Statistics &  Coefficient Distribution &  T-test Distribution  \\\\\n    \\hline\n    \\hline\n    Simple average    & -0.267      & -2.969 \\\\\n    \\hline\n    Median            & -0.266   & -2.965 \\\\\n    \\hline\n    Mode              & -0.253     & -2.884 \\\\\n    \\hline\n    Skewness          & 0.013      & 0.090 \\\\\n    \\hline\n    kurtosis          & -0.214     & -0.060 \\\\\n    \\hline\n    Positive Share    & -1.312     & -1.878 \\\\\n    \\hline\n    Significant Share & 0.000 &  \\\\\n    \\hline\n    \\end{tabular}\n\\end{table}\n\n\\clearpage\n\\begin{center}\n    \\large{\\textbf{Coefficient, t-test and selection criteria gains distributions for x779 }}\n\\end{center}\n\n\\vspace{-5mm}\n\n\\begin{figure}[!ht]\n  \\centering\n  \\begin{minipage}[b]{0.46\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{contour_x779_b_t.png}\n    \\caption{Bivariate Kernel density (Contour view)}\n  \\end{minipage}\n  \\hfill\n  \\begin{minipage}[b]{0.53\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{wireframe_x779_b_t.png}\n    \\caption{Bivariate Kernel density (Contour view)}\n  \\end{minipage}\n\n  \\begin{minipage}[b]{0.48\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{Kdensity_criteria_x779.png}\n    \\caption{Selection criteria gains for including x779 (Kernel view)}\n  \\end{minipage}\n  \\hfill\n  \\begin{minipage}[b]{0.48\\textwidth}\n    \\centering    \n    \\includegraphics[width=\\textwidth]{BoxViolinDot_x779.png}\n    \\caption{Selection criteria gains for including x779 (Box-Violin view)}    \n  \\end{minipage}\n\\end{figure}\n\n\\vspace{1cm}\n\nThe following table shows main statistics of coefficient and t-test distribution \n\n\\begin{table}[!h]\n    \\centering\n    \\caption{Statistics}\n    \\begin{tabular}{|l|c|c|}\n    \\hline\n    Variable x779 Statistics &  Coefficient Distribution &  T-test Distribution  \\\\\n    \\hline\n    \\hline\n    Simple average    & -0.259      & -2.505 \\\\\n    \\hline\n    Median            & -0.258   & -2.502 \\\\\n    \\hline\n    Mode              & -0.230     & -2.287 \\\\\n    \\hline\n    Skewness          & 0.025      & 0.184 \\\\\n    \\hline\n    kurtosis          & -0.084     & -0.042 \\\\\n    \\hline\n    Positive Share    & -1.031     & -1.172 \\\\\n    \\hline\n    Significant Share & 0.000 &  \\\\\n    \\hline\n    \\end{tabular}\n\\end{table}\n\n\\clearpage\n\\begin{center}\n    \\large{\\textbf{Coefficient, t-test and selection criteria gains distributions for x813 }}\n\\end{center}\n\n\\vspace{-5mm}\n\n\\begin{figure}[!ht]\n  \\centering\n  \\begin{minipage}[b]{0.46\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{contour_x813_b_t.png}\n    \\caption{Bivariate Kernel density (Contour view)}\n  \\end{minipage}\n  \\hfill\n  \\begin{minipage}[b]{0.53\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{wireframe_x813_b_t.png}\n    \\caption{Bivariate Kernel density (Contour view)}\n  \\end{minipage}\n\n  \\begin{minipage}[b]{0.48\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{Kdensity_criteria_x813.png}\n    \\caption{Selection criteria gains for including x813 (Kernel view)}\n  \\end{minipage}\n  \\hfill\n  \\begin{minipage}[b]{0.48\\textwidth}\n    \\centering    \n    \\includegraphics[width=\\textwidth]{BoxViolinDot_x813.png}\n    \\caption{Selection criteria gains for including x813 (Box-Violin view)}    \n  \\end{minipage}\n\\end{figure}\n\n\\vspace{1cm}\n\nThe following table shows main statistics of coefficient and t-test distribution \n\n\\begin{table}[!h]\n    \\centering\n    \\caption{Statistics}\n    \\begin{tabular}{|l|c|c|}\n    \\hline\n    Variable x813 Statistics &  Coefficient Distribution &  T-test Distribution  \\\\\n    \\hline\n    \\hline\n    Simple average    & -0.305      & -2.572 \\\\\n    \\hline\n    Median            & -0.304   & -2.567 \\\\\n    \\hline\n    Mode              & -0.280     & -2.434 \\\\\n    \\hline\n    Skewness          & 0.023      & 0.153 \\\\\n    \\hline\n    kurtosis          & -0.140     & -0.023 \\\\\n    \\hline\n    Positive Share    & -1.464     & -1.959 \\\\\n    \\hline\n    Significant Share & 0.000 &  \\\\\n    \\hline\n    \\end{tabular}\n\\end{table}\n\n\\clearpage\n\\begin{center}\n    \\large{\\textbf{Coefficient, t-test and selection criteria gains distributions for _cons }}\n\\end{center}\n\n\\vspace{-5mm}\n\n\\begin{figure}[!ht]\n  \\centering\n  \\begin{minipage}[b]{0.46\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{contour__cons_b_t.png}\n    \\caption{Bivariate Kernel density (Contour view)}\n  \\end{minipage}\n  \\hfill\n  \\begin{minipage}[b]{0.53\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{wireframe__cons_b_t.png}\n    \\caption{Bivariate Kernel density (Contour view)}\n  \\end{minipage}\n\n  \\begin{minipage}[b]{0.48\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{Kdensity_criteria__cons.png}\n    \\caption{Selection criteria gains for including _cons (Kernel view)}\n  \\end{minipage}\n  \\hfill\n  \\begin{minipage}[b]{0.48\\textwidth}\n    \\centering    \n    \\includegraphics[width=\\textwidth]{BoxViolinDot__cons.png}\n    \\caption{Selection criteria gains for including _cons (Box-Violin view)}    \n  \\end{minipage}\n\\end{figure}\n\n\\vspace{1cm}\n\nThe following table shows main statistics of coefficient and t-test distribution \n\n\\begin{table}[!h]\n    \\centering\n    \\caption{Statistics}\n    \\begin{tabular}{|l|c|c|}\n    \\hline\n    Variable _cons Statistics &  Coefficient Distribution &  T-test Distribution  \\\\\n    \\hline\n    \\hline\n    Simple average    & -0.128      & -1.223 \\\\\n    \\hline\n    Median            & -0.127   & -1.244 \\\\\n    \\hline\n    Mode              & -0.127     & -1.263 \\\\\n    \\hline\n    Skewness          & 0.018      & 0.180 \\\\\n    \\hline\n    kurtosis          & 0.016     & 0.125 \\\\\n    \\hline\n    Positive Share    & -1.293     & -1.131 \\\\\n    \\hline\n    Significant Share & 0.000 &  \\\\\n    \\hline\n    \\end{tabular}\n\\end{table}\n\n\\clearpage\n\n\\begin{figure}[!ht]\n    \\centering\n    \\caption{Covariable relevance related to selection criteria}\n    \\includegraphics[scale=0.6]{cov_relevance.png}\n\\end{figure}\n\n%In this figure it is shown that potential covariates included in the general unrrestricted model of the all-subset-regression algorithm display singnificant differences in terms of the user selected information criteria. For each explanatory variable information criteria gains were obtained as the differece between averages information criteria obtained from models which includes and excludes that covariate. Available statistics suggests that there   explanatory  that improved model accuracy.  or }} helps to increase up to a \\% the user selected information criteria. On the contrary, there    that have a deleterious impact on model accuracy. This is specially true for , which seems to decrease up to a \\% the user selected information criteria}}\n\n\\section{k-fold cross-validation}\n\n\\begin{table}[!h]\n  \\centering\n  \\caption{K-fold cross-validation Results}\n    \\begin{tabular}{l c c}\n    \\hline\n    \\multicolumn{3}{c}{K-fold scheme:\\textbf{Insert scheme}}    \\\\\n                    & 3-fold         & 3-fold \\\\\n    Variables       & Mean                    & Median          \\\\\n    \\hline\n    \\hline\n[3.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 -0.110223 0.117787 -1.06407 66.0 3.0 56.7211 0.225622 9.63996 0.927044 1.06744 0.201039 0.7426 2.4323e-6 0.655581 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0]\n\n--\n\n\n[3.33333 0.121148 0.033808 1.19447 -0.135271 0.0442381 -1.01926 0.0 0.0 0.0 -0.102466 0.114535 -0.896072 66.6667 2.66667 55.1408 0.206017 10.058 0.90649 1.1032 0.185638 0.671841 1.62484e-5 0.581203 0.106131 0.0382284 0.925414 0.0920784 0.0328706 0.933747 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 -0.115661 0.037252 -1.03494]\n\n    \\hline\n\n    Error out-sample &     &   \\\\\n                     &     &   \\\\\n    \\hline\n    \\hline\n    \\multicolumn{3}{c}{\\textit{Standard errors in parentheses}} \\\\\n    \\multicolumn{3}{c}{*** p < 0.01, ** p < 0.05, * p < 0.1} \\\\\n    \\hline\n    \\end{tabular}\n  \\label{tab:addlabel}\n\\end{table}\n\n\\addcontentsline{toc}{section}{References} \n\\bibliographystyle{unsrt}  \n\\begin{thebibliography}{1}\n\n\\bibitem{gsreg2019}\nPanigo D., Glüzmann P., Mocskos, E., Mauri Ungaro, A., Mari, V., and Monzón, N. (2019). \\textit{ModelSelection.jl: Building bridges between Machine Learning and Econometrics in Fat-Data scenarios}.Paper presented at JuliaCon2019, Baltimore-MD, United States.\n\n\\bibitem{hassani2007}\nHassani H. (2007). \\textit{Singular Spectrum Analysis: Methodology and Comparison}. Journal of Data Science, 5, 239-257.\n\n\\bibitem{lehmann2013}\nLehmann, R. (2013). \\textit{3 sigma-rule for outlier detection from the viewpoint of geodetic adjustment}. Journal of Surveying Engineering, 139(4), 157-165.\n\n\\bibitem{tibshirani1996}\nTibshirani, R. (1996). \\textit{Regression shrinkage and selection via the lasso}. Journal of the Royal Statistical Society: Series B (Methodological), 58(1), 267-288.\n\n\\bibitem{chandrashekar2014}\nChandrashekar, G., and Sahin, F. (2014). \\textit{A survey on feature selection methods}. Computers & Electrical Engineering, 40(1), 16-28.\n\n\\bibitem{gluzmann2015}\nGluzmann, P., and Panigo, D. (2015). \\textit{Global search regression: A new automatic model-selection technique for cross-section, time-series, and panel-data regressions.} The Stata Journal, 15(2), 325-349.\n\n\\bibitem{arlot2010}\nArlot, S., and Celisse, A. (2010).\\textit{A survey of cross-validation procedures for model selection}. Statistics surveys, 4, 40-79.\n\n\\bibitem{jung2015}\nJung, Y., and Hu, J. (2015). \\textit{A K-fold averaging cross-validation procedure}. Journal of nonparametric statistics, 27(2), 167-179.\n\n\\bibitem{bergmeir2012}\nBergmeir, C., and Benítez, J. M. (2012). \\textit{On the use of cross-validation for time series predictor evaluation}. Information Sciences, 191, 192-213.\n\n\\bibitem{bergmeir2018}\nBergmeir, C., Hyndman, R. J., and Koo, B. (2018). \\textit{A note on the validity of cross-validation for evaluating autoregressive time series prediction}. Computational Statistics & Data Analysis, 120, 70-83.\n\n\\bibitem{hyndman2013}\nHyndman, R. J., and Athanasopoulos, G. (2013). Measuring forecast accuracy. Gilliland M, Tashman L, Sglavo U. Business forecasting: practical problems and solutions, 177-84.\n\n\\end{thebibliography}\n\n\n\\end{document}", "meta": {"hexsha": "982cb48e3ec0c556cf0f44f632b770243412894b", "size": 39072, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "test/Latex/main.tex", "max_stars_repo_name": "JuliaTagBot/ModelSelection.jl", "max_stars_repo_head_hexsha": "62a636bce9179da262886194e9888cea37bfa13b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-29T22:48:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-29T22:48:17.000Z", "max_issues_repo_path": "test/Latex/main.tex", "max_issues_repo_name": "JuliaTagBot/ModelSelection.jl", "max_issues_repo_head_hexsha": "62a636bce9179da262886194e9888cea37bfa13b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Latex/main.tex", "max_forks_repo_name": "JuliaTagBot/ModelSelection.jl", "max_forks_repo_head_hexsha": "62a636bce9179da262886194e9888cea37bfa13b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:54:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T10:54:35.000Z", "avg_line_length": 67.1340206186, "max_line_length": 6922, "alphanum_fraction": 0.6954596642, "num_tokens": 13956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3030037010423602}}
{"text": "\\section{Introduction}\n\nAchieving an optimal runtime complexity is a fundamental challenge when it comes to designing scalable solutions for handling a large amount of data\\cite{sipser13}. Recently, quantum computing has sparked the interest of both scientists and engineers alike due to their asymptotical performance gain on some problems compared to the classical computers. While the field has witnessed rapid progress in developing new software, hardware and efficient algorithms, the core principles at play have been relatively stable. In almost every physical or abstract quantum computer, information encoding and processing occur via unitary transformations while the result is written onto classical storage via projective measurements\\cite{Nielsen2009}. In this project, we aim to investigate \\emph{measurement-based quantum computing}, a different formulation for quantum computation that provides several advantages over the circuit based model.\n\nMeasurement-based quantum computing was first proposed by Briegel and Russeldorf in 2000 \\cite{Briegel_2001} as a general framework for universal computation  by using the entanglement patterns of two-state particles. Their work was extended to include a formulation based on stabilizers, whose use in quantum mechanics have mostly been restricted to error correction \\cite{Nielsen2009, quant-ph/9705052}. The structure of a measurement-based quantum computer was later generalized into the notion of graph states, which are used to represent qubits with Ising interraction patterns via simple graphs \\cite{hein2006}. Later, several algorithms formulated for measurement-based quantum computing have been suggested \\cite{keith2014, debeaudrap2008theory}.\n\nIn this project, we started with a review of the mathematical background necessary. Graphs and their relevant proerties were introduced which were used to formulate the method of computation. Later, graph states were introduces as a general framework for studying the entanglement properties of systems of qubits which can be represented by simple graphs. The introduction of graph states involves two different formulations. One way to formulate these objects is by interaction patters. As graph states interract by specific Ising interraction patterns, their states can be found by applying the well known Ising interraction hamiltonians\\cite{ichikawa2013}. The second formulation is using the stabilizer fromalism to achieve a more compact and transparent representation of the graph state and its entanglement patterns.\n\nIn the second phase of the project, we introduce the notion of a \\emph{cluster state} which is a lattice-like graph state that we will use to describe computation with. Following this introduction, we are going to provide a mechanism to do universal computation. Lastly, we are going to provide a few examples for measurement-based algorithms, compare them to their circuit-based alternatives and discuss the possible benefits of using this formalism.", "meta": {"hexsha": "008dc490253df55c0cd548ef2bcc3b095538f84d", "size": 2993, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "documents/interim/content/intro.tex", "max_stars_repo_name": "kurabirko/phys400", "max_stars_repo_head_hexsha": "1e7608322457c090e4db8c52ff1c7c8c55a612c3", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "documents/interim/content/intro.tex", "max_issues_repo_name": "kurabirko/phys400", "max_issues_repo_head_hexsha": "1e7608322457c090e4db8c52ff1c7c8c55a612c3", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "documents/interim/content/intro.tex", "max_forks_repo_name": "kurabirko/phys400", "max_forks_repo_head_hexsha": "1e7608322457c090e4db8c52ff1c7c8c55a612c3", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 332.5555555556, "max_line_length": 935, "alphanum_fraction": 0.8352823254, "num_tokens": 566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.30300370104236013}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Overivew\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Model Interlocking Assemblies}\n\\label{sec:model}\n%\n%In this section, we introduce our conceptual representation of interlocking assemblies using a family of directed graphs. We show how this graph-based representation leads to an efficient algorithm to {\\em test} interlocking. \n%In Section~\\ref{sec:approach} we then explain how to effectively employ this representation and algorithm to {\\em design} interlocking assemblies.\n%%\\TODO{one more assumption: we focus on (dis)assemblies parts with translational motions, e.g., do not consider taking a part by rotating it first and then doing the translation.}\n\n\n\\begin{figure}[!t]\n\t\\centering\n\t%\\vspace*{-3.5mm}\n\t\\includegraphics[width=8.00cm]{images/NDBG.png}\n\t\\vspace*{-2.5mm}\n\t\\caption{Example DBGs and NDBG.\n\t\t(a\\&b) A 2D interlocking assembly and its parts-graph, where the key $P_1$ is movable along $d_2$;\n\t\t(c\\&d) Two DBGs of the assembly; and\n\t\t(e) NDBG of the assembly.\n\t\tA part with zero out-degree or in-degree in a DBG is highlighted with a red circle. \n\t\t%\\Mark{I would still consider using crossing edges, I think it will make it easier to read.I would also expand the figure  to reach to full width, i.e. add more space.}\n\t}\n\t\\vspace*{-4.0mm}\n\t\\label{fig:NDBG}\n\\end{figure}\n\n\\subsection{Graph Model}\n\\label{subsec: graphmodel}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Our Inputs\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nConsider an assembly $\\mathbf{A}$, made of $n$ parts $P_1$, $...$, $P_n$.\nWe make the following assumptions:\n1) each part $P_i$ is rigid; \n2) neighboring parts have planar surface contact only; and \n%(e.g., corner-surface and edge-surface contacts are not considered); and\n3) $\\mathbf{A}$ can be disassembled by single-part translational motions, i.e., part rotation is not required and all other parts remain fixed when removing a part.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Base DBGs\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\vspace*{1.0mm}\n\\noindent\n{\\bf Directional Blocking Graph (DBG).}\\  \nWe denote as $G(d, A)$ the {\\em directional blocking graph} of assembly $\\mathbf{A}$ for translation along direction $d$. \nThis directed graph has nodes representing the parts of $\\mathbf{A}$ and directed edges $e_{i \\rightarrow j}$ from $P_i$ to $P_j$  if and only if $P_j$ prevents any translational motion of $P_i$ along $d$. \nIn other words, $e_{i \\rightarrow j}$ can be read as ``$P_i$  is blocked by $P_j$\" in direction $d$. \nSee Figure~\\ref{fig:NDBG}(c\\&d) for two examples.\n\nIf $G(d, A)$ is {\\em strongly connected}, i.e. if every node can be reached from every other node, no part or part group is movable along $d$; see Figure~\\ref{fig:NDBG}(c). \nA part group $\\mathbf{S}$ of $\\mathbf{A}$ is locally free to translate in direction $d$ ($-d$), if and only if the out-degree (in-degree) of $\\mathbf{S}$ in $G(d, A)$ is zero; see $P_1$ in Figure~\\ref{fig:NDBG}(d).\n%there is no edge in $G(d, A)$ connecting parts in $\\mathbf{S}$ to parts in $\\mathbf{A} \\setminus \\mathbf{S}$; see $P_1$ in Figure~\\ref{fig:NDBG}(d) for an example.\n%since there is no out-edge connecting it with the other nodes in the graph; see Figure~\\ref{fig:NDBG}(d). \n\n\n\\vspace*{1.0mm}\n\\noindent\n{\\bf Non-directional Blocking Graph (NDBG).} \\\nWe represent the set of all translation directions in 2D by the unit circle denoted as $C$.\nFor every pair of parts in contact in $\\mathbf{A}$, we draw the diameter that is parallel with the contact line.\nThe drawn diameters partition $C$ into an arrangement of regions, for which the corresponding DBG $G(d, A)$ remains constant when $d$ varies over a region.\nFor any pair of parts in \n\\vspace*{5mm}\n\\setlength{\\columnsep}{13pt}\n\\begin{wrapfigure}{r}{0.32\\columnwidth}\n\t\\vspace{-6pt}\n\t\\centering\n\t\\hspace{-4pt}\n\t\\includegraphics[width=0.32\\columnwidth]{images/NDBG_Diameter.png}\n\t\\vspace{-5pt}\n\\end{wrapfigure}\ncontact (e.g., $P_1$ and $P_2$ in the inset), if there are more than two contact lines, we only retain the two diameters of $C$ (e.g., two contact lines in blue) which bound the cone of directions in which one part is free to translate relative to the other.\nThe arrangement of points and intervals on $C$ and the associated DBGs form the {\\em non-directional blocking graph} of $\\mathbf{A}$; see Figure~\\ref{fig:NDBG}(e).\n% which represents the blocking relations among parts in $\\mathbf{A}$ for all possible translation directions.\nThe NDBG for a 3D assembly can be built similarly by constructing DBGs for each regular region of a unit sphere that represents all possible translation direction in 3D; please refer to~\\cite{Wilson-1994-GeometricReasoning} for more details.\n\n\\vspace*{1.0mm}\n\\noindent\n{\\bf Base Directional Blocking Graphs.} \\\nAn NDBG represents the parts blocking relations with redundancy in two aspects.\nFirst, the DBG corresponding to an arc in $C$ can be derived by performing union operations on the DBGs associated with the two end points of the arc; see again Figure~\\ref{fig:NDBG}(e).\n%This is because the blocking relations for $d = d_1$ and $d = d_2$ are the extreme case\n%by performing union of the edges in these two graphs since \\TODO{give a reason here}.\nSecond, we can obtain $G(-d, A)$ from $G(d, A)$ easily by reversing the direction of every edge in $G(d, A)$ due to the reciprocity of  blocking relations among the parts.\n\nTherefore, it is sufficient to model the blocking relations in $\\mathbf{A}$ by using only a set of {\\em base DBGs} denoted as $\\{G(d, A)\\}$, which we select as the DBGs corresponding to the end points in a half circle of $C$.\nFor example, two DBGs in Figure~\\ref{fig:NDBG}(c\\&d) form $\\{G(d, A)\\}$.\nWe call the set of directions corresponding to the base DBGs as {\\em base directions}, denoted as $\\{d\\}$.\n%The number of base DBGs (as well as base directions) is $O(n^2)$ since every pair of parts provides either two (in contact) or zero (no contact) diameters in $C$.\nThe number of base DBGs (as well as base directions) is $O(n^2)$ since every pair of parts provides at most two diameters in $C$.  \n%\\Mark{Does this mean two contact parts cannot be blocked only along a single direction?}\n%\\Peng{You are right. Two contact parts are possible to provide one diameter. Text has been revised accordingly.}\n%\\Mark{better to have a figure showing 3D base DBGs}\n\n%Hence, if a part of part group is movable along the direction within the arc, it must be movable also along the direction corresponding to one of the end points.\n%Hence, when identifying movable parts or part groups,  we only need to test each direction corresponding to the end points (e.g., $-x, +x, -y, +y$ in Figure~\\ref{fig:NDBG}).\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Test Interlocking \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\subsection{Testing Interlocking}\n\\label{subsec: testinginterlocking}\nIn an interlocking assembly, every part and every part group are immobilized for all possible translation directions, except a single key.\nTo test immobilization of a part group $\\mathbf{S}$, we need to compute blocking relations between $\\mathbf{S}$ and $\\mathbf{A}-\\mathbf{S}$:  the part group $\\mathbf{S}$ is immobilized if $\\mathbf{S}$ is blocked by $\\mathbf{A}-\\mathbf{S}$ in all translation directions.\nExplicitly testing interlocking by checking immobilization of every part and every part group has exponential time complexity. \nHowever, treating each part group $\\mathbf{S}$ independently ignores significant redundancies in the blocking relations across the parts.\n%This huge complexity mainly arises from the redundancy of recomputing blocking relations for every parts group $\\mathbf{S}$ by considering it as a totally new unit.\n% rather than utilizing the computed blocking relations of $\\mathbf{S}$'s component parts.\n%\nWe exploit these redundancies and propose a more efficient approach to test global interlocking. \nThe key idea is to utilize the blocking relations encoded in the set of base DBGs to implicitly test immobilization of every part and every part group along a finite number of translation directions, i.e., the base directions $\\{d\\}$.\nIn detail, an assembly with at least three parts is interlocking, if all base DGBs are either\n\n\\begin{enumerate}\n\t\\item strongly connected, or \n\t\\item have only two strongly connected components one of which has a single part that is identical across all DGBs.\n\\end{enumerate}\t\n%\\vspace*{-0.5mm}\nHere the strongly connected component with a single part is the key of the assembly.\nThe direction $d$ associated with each DBG with two strongly connected components is the key part's (reversed) movable direction according to the in-edge (out-edge) of the key in the DBG.\nFor example, the assembly in Figure~\\ref{fig:NDBG}(a) is interlocking and $P_1$ is the key since its two base DBGs in Figure~\\ref{fig:NDBG}(c\\&d) satisfy the above requirement.\n% where $P_1$ is the key part and its movable direction is $\\{d_2\\}$.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Recursive Interlocking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\subsection{Recursive Interlocking}\nGenerating a $n$ pieces recursive interlocking has two steps:\n\\begin{itemize}[leftmargin=*]\n\t\\item Select the key part $P_1$ from the general voxelized shape $S$ and denote the remaing part as $R_1$\n\t\\vspace{1mm}\n\t\\item Iteratively extract pieces, one by one, forming a sequence of extracted pieces $P_1$, $P_2$, ..., $P_{n - 1}$, with $R_{n - 1}$ , the remaining part of S, as the last piece:\\begin{equation*}\n\t\tS \\rightarrow [P_1,R_1] \\rightarrow [P_1,P_2,R_2] \\rightarrow \\cdots\\rightarrow [P_1,\\cdots, P_{n-1},R_{n-1}] .\n\t\\end{equation*}\n\\end{itemize} \nRecursive interlocking property requires that any consecutive three parts have to be interlocking and the first part is the local key.\n\\begin{equation*}\n\t[{\\bf P_1}, P_2, P_3], \\cdots, [{\\bf P_{i}}, P_{i+1}, P_{i+2}], \\cdots, [{\\bf P_{n - 2}}, P_{n-1}, R_{n-1}]\n\\end{equation*}\nThe local key is marked as bold.\n\nIn \\cite{Song-2012-InterCubes}, they prove that {\\bf recursive interlocking is interlocking}. They prove the correctness of theory by discussing in different cases, which can be simpilified by the graph-based tool. For simplification, denote $R_{n-1}$ as $P_n$\n\\noindent\n\\begin{lemma}\n\tif  $ [{\\bf P_{i}}, P_{i+1}, P_{i+2}]$ is a local interlocking group, and $P_i$ is the local key, then $P_{i+1}, P_{i+2}$ are in the same strongly connected component for any DBG.\n\\end{lemma}\n\\noindent\nProof: Interlocking property means $P_{i+1}$ and $P_{i+2}$ only can be moved together in any direction when the key part $P_i$ is fixed. Therefore $P_{i+1}$ and $P_{i+2}$ are in the same strongly connect component for any DBG.\n\n\\begin{theorem}\n\tRecursive interlocking is interlocking\n\\end{theorem}\n\\noindent\nProof: According to the lemma, we have $P_i$ and $P_{i + 1}$ are in the same strongly connected component for any DBG. Then $P_2, \\cdots, P_n$ are in the same strong connected component because the strongly connected property is transitive. Then the whole assembly is interlocking by the previous definition.\n\n\\begin{corollary}\n\tConsecutive $K(K \\geq 3)$ pieces interlocking is interlocking\n\\end{corollary}\n\n\\begin{figure}[!t]\n\t\\centering\n\t%\\vspace*{-3.5mm}\n\t\\includegraphics[width=8.45cm]{images/non-recursive_interlocking.png}\n\t\\vspace*{-2.5mm}\n\t\\caption{A non-recursive interlocking 2D puzzle $A$. The dark black edges in $G(+x, A)$ do not form a cycle, which means $[P_2, P_3, P_4]$ is not interlocking. Therefore, the assembly $A$ is not recursive interlocking.\n\t}\n\t\\vspace*{-4.5mm}\n\t\\label{fig:non-recursive interlocking}\n\\end{figure}\n\nAn non-recursive interlocking example is given in Fig.\\ref{fig:non-recursive interlocking}. Given a general voxelized shape $S$, the solution number of recursive interlocking accounts for a small proportion of general interlocking and the proportion will dramatically drop when the number of parts increase. It can be explained in two aspects.\n\n\\vspace*{2mm}\n\\noindent\n{\\bf Cycle in DBGs: } The recursive interlocking usually has cycles with less than 4 vertices for any DBGs. The local interlocking group $[P_{i}, P_{i+1}, P_{i+2}]$ constrain the cycle size.\n\n\\vspace*{2mm}\n\\noindent\n{\\bf Disassembling sequence: } The recursive interlocking only have two (the order of last two pieces can be swapped) possible disassembling sequence. The general interlocking in Fig.\\ref{fig:non-recursive interlocking} has four disassembling sequences:\n\\begin{equation*}\n\t(1, 2, 3, 4), (1, 2, 4, 3), (1, 4, 2, 3), (1, 4, 3, 2)\n\\end{equation*}\n\n\\subsection{Failure Cases and Modification}\n\\label{subsec: failurecases}\nLastly, inspired by our DBG-based representation, we find that a parts-graph with a cut point cannot be interlocking, no matter what kinds of joints are planned; see Figure~\\ref{fig:Result_Furniture_Chair}(left) for an example.\nThis observation allows us to modify a given input to make it possible to be interlocking by adding a minimal number of new parts in the parts-graph in oder to remove the cut point; see Figure~\\ref{fig:Result_Furniture_Chair}(right) for an example.\n\n\\begin{figure}[!t]\n\t\\centering\n\t%\\vspace*{-3.5mm}\n\t\\includegraphics[width=8.45cm]{images/Result_Furniture_Chair.png}\n\t\\vspace*{-2.5mm}\n\t\\caption{\n\t\tLeft: a {\\textsc Chair} and its parts-graph, where a cut point (i.e., $P_5$) exists.\n\t\tRight: after adding a new part (i.e., $P_9$), our approach can generate an interlocking joint configuration, where the axial removal direction allowed by each joint is shown in the corresponding edge in the parts-graph. \n\t}\n\t\\vspace*{-4.5mm}\n\t\\label{fig:Result_Furniture_Chair}\n\\end{figure}", "meta": {"hexsha": "ae31332e4d8092ff9b42be4796a80c79729b1e46", "size": 13725, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Paper/section2-disassembly.tex", "max_stars_repo_name": "KIKI007/Candidancy-Exam", "max_stars_repo_head_hexsha": "0cba5c5dcbbf52aff7d01638edb252c486bf9444", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Paper/section2-disassembly.tex", "max_issues_repo_name": "KIKI007/Candidancy-Exam", "max_issues_repo_head_hexsha": "0cba5c5dcbbf52aff7d01638edb252c486bf9444", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Paper/section2-disassembly.tex", "max_forks_repo_name": "KIKI007/Candidancy-Exam", "max_forks_repo_head_hexsha": "0cba5c5dcbbf52aff7d01638edb252c486bf9444", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 65.0473933649, "max_line_length": 343, "alphanum_fraction": 0.7181785064, "num_tokens": 3724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.30300370104236013}}
{"text": "\\clearpage\n\\phantomsection\n\\addcontentsline{toc}{chapter}{\\protect\\numberline{}{List of Mathematical and\nPhysical Symbols}}\n\n\\chapter*{Symbols}\n\n\n\\subhead{Symbols}\n\\begin{symbollist}{\\symbsize}\n\n   \\item [\\hfil$\\rho$] mass density\n\n   \\item [\\hfil$P$] pressure  \n   \n   \\item [\\hfil$L$] luminosity   \n   \n   \\item [\\hfil$F$] flux   \n   \n   \\item [\\hfil$g$] gravitational acceleration   \n   \n   \\item [\\hfil$ z_g$] surface redshift\n\n   \\item [\\hfil$T$] temperature\n   \n   \\item [\\hfil$T_{\\rm eff}$] effective temperature (at surface)\n\n   \\item [\\hfil$T_{\\rm eff}^{\\infty}$] effective temperature at the infinity (for a remote observer)\n\n   \\item [\\hfil$M$] mass of the neutron star\n\n   \\item [\\hfil$R$] radius of the neutron star\n\n   \\item [\\hfil$R_{\\infty}$] apparent  radius of a neutron star for a remote observer \n\n   \\item [\\hfil$f_c$] color correction factor\n   \n   \\item [\\hfil$\\odot$] refers to the sun;\\eg, \\Msol for one solar mass\n\\end{symbollist}\n\n\n%------------------------------------------------------------------------------\n\n\\vspace{\\symbsep}\n\n\\subhead{Constants}\n\\begin{symbollist}{\\symbsize}\n\n   \\item [\\hfil$\\rho$] density of a heavy atomic nucleus, $\\rho=2.8 \\times 10^{14} $ g cm$^{-3}$\n   \n   \\item [\\hfil$k_{\\rm B}$] the Boltzmann constant, $k_{\\rm B} = 3806488(13)\\times 10^{−16}$ erg K$^{−1}$\n   \n  \\item [\\hfil$\\sigma_{\\rm SB}$] the Stefan-Boltzmann constant,   $\\sigma_{\\rm SB}=5.670 \\times 10^{-5}$ erg s$^{-1}$ cm$^{-2}$ K$^{-4}$\n   \n  \\item [\\hfil$R_{\\rm S}$] the Schwarzschild radius, $R_{\\rm S}= 2GM/c^2 \\sim 2.95 M/\\Msol$ km \n\n  \\item [\\hfil$G$] the gravitational constant, $G= 6.67259(85)\t10^{-8}$ cm$^3$ g$^{-1}$ s$^{-2}$ \n\n  \\item [\\hfil$a$]the radiation constant, $a=4\\sigma/c= 7.566 \\times 10^{-15}$ erg cm$^{-3}$K$^{-4}$ \n\n\n      \n\\end{symbollist}\n", "meta": {"hexsha": "97c9f7afb5aed7409aa2d7c66f21a7e9407a981e", "size": 1786, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "PhD_dissertation/subdocuments/symbols.tex", "max_stars_repo_name": "bt3gl/Examples_in_Latex", "max_stars_repo_head_hexsha": "6162ea21c035ad41e225d330ab7244567d2ca3e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-02-21T17:41:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T17:48:03.000Z", "max_issues_repo_path": "PhD_dissertation/subdocuments/symbols.tex", "max_issues_repo_name": "bt3gl/Examples_in_Latex", "max_issues_repo_head_hexsha": "6162ea21c035ad41e225d330ab7244567d2ca3e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PhD_dissertation/subdocuments/symbols.tex", "max_forks_repo_name": "bt3gl/Examples_in_Latex", "max_forks_repo_head_hexsha": "6162ea21c035ad41e225d330ab7244567d2ca3e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2016-07-24T21:52:10.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-02T11:47:49.000Z", "avg_line_length": 27.90625, "max_line_length": 136, "alphanum_fraction": 0.5923852184, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.30300370104236013}}
{"text": "% Siconos is a program dedicated to modeling, simulation and control\n % of non smooth dynamical systems.\n %\n % Copyright 2021 INRIA.\n %\n % Licensed under the Apache License, Version 2.0 (the \"License\");\n % you may not use this file except in compliance with the License.\n % You may obtain a copy of the License at\n %\n % http://www.apache.org/licenses/LICENSE-2.0\n %\n % Unless required by applicable law or agreed to in writing, software\n % distributed under the License is distributed on an \"AS IS\" BASIS,\n % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n % See the License for the specific language governing permissions and\n % limitations under the License.\n%\n\\documentclass[10pt]{article}\n\\input{macro.tex}\n\\usepackage{psfrag}\n\\usepackage{fancyhdr}\n\\usepackage{subfigure}\n%\\renewcommand{\\baselinestretch}{1.2}\n\\textheight 23cm\n\\textwidth 16cm\n\\topmargin 0cm\n%\\evensidemargin 0cm\n\\oddsidemargin 0cm\n\\evensidemargin 0cm\n\\usepackage{layout}\n\\usepackage{mathpple}\n\\makeatletter\n\\renewcommand\\bibsection{\\paragraph{References\n     \\@mkboth{\\MakeUppercase{\\bibname}}{\\MakeUppercase{\\bibname}}}}\n\\makeatother\n%% style des entetes et des pieds de page\n\\fancyhf{} % nettoie le entetes et les pieds\n\\fancyhead[L]{Template 5 : Electrical oscillator with half-wave rectifier - Pascal Denoyelle}\n%\\fancyhead[C]{}%\n\\fancyhead[R]{\\thepage}\n%\\fancyfoot[L]{\\resizebox{!}{0.7cm}{\\includegraphics[clip]{logoesm2.eps}}}%\n\\fancyfoot[C]{}%\n%\\fancyfoot[C]{}%\n%\\fancyfoot[R]{\\resizebox{!}{0.7cm}{\\includegraphics[clip]{logo_cnrs_amoi.ps}}}%\n%\\addtolength{\\textheight}{2cm}\n%\\addtolength{\\textwidth}{2cm}\n%\\pagestyle{empty}\n%\\renewcommand{\\baselinestretch}{2.0}\n\\begin{document}\n%\\layout\n\\thispagestyle{empty}\n\\title{WP2 Template 5 \\\\Simulation of an electrical oscillator \\\\\nsupplying a resistor through a half-wave rectifier}\n\\author{Pascal Denoyelle}\n\n\\date{Version 1.0 \\\\\n September 22 , 2005}\n\\maketitle\n\n\n\\pagestyle{fancy}\n\n\\section{Description of the physical problem : electrical oscillator with half-wave rectifier}\nIn this sample, a LC oscillator initialized with a given voltage across the capacitor and a null current through\nthe inductor provides the energy\nto a load resistance through a half-wave rectifier consisting of an ideal diode (see fig. \\ref{fig-CircuitRLCD}).\n\n\\begin{figure}[hp]\n\\centerline{\n  \\scalebox{0.75}{\n     \\input{CircuitRLCD.pstex_t}\n  }\n}\n\\caption{Electrical oscillator with half-wave rectifier}\n\\label{fig-CircuitRLCD}\n\\end{figure}\n\nOnly the positive wave of the oscillating voltage across the LC is provided to the resistor. The energy is dissipated\nin the resistor resulting in a damped oscillation.\n\n\n\\section{Definition of a general abstract class of NSDS : the linear time invariant complementarity system (LCS)}\n\\label{sec-def-NSDS}\nThis type of non-smooth dynamical system consists of :\n\n\\begin{itemize}\n\\item a time invariant linear dynamical system (the oscillator). The state variable of this system is denoted by $x$.\n\\item a non-smooth law describing the behaviour of the diode as a complementarity condition between current and\nreverse voltage (variables ($y,\\lambda$) )\n\\item a linear time invariant relation between the state variable $x$ and the non-smooth law\nvariables ($y,\\lambda$)\n\\end{itemize}\n\n\\subsection{Dynamical system and Boundary conditions}\n\\underline{Remark :}\nIn a more general setting, the system's evolution would be described by a DAE :\n\\[\nG \\cdot x' = A \\cdot x + E \\cdot u + b + r \n\\]\nwith $G , A , E$ matrices constant over time (time invariant system), $u , b$ source terms functions of time and $r$,\na term coming from the non-smooth law variables : $r = B \\cdot \\lambda + a$ with $B , a$ constant over time.\\\\\nWe will consider here the case of an ordinary differential equation :\n\\[\nx' = A \\cdot x + E \\cdot u + b + r \n\\]\nand an initial value problem for which the boundary conditions are $t_0 \\in \\mathbb{R} , x(t_0)= x_0$.\n\n\\subsection{Relation between constrained variables and state variables}\nIn the linear time invariant framework, the non-smooth law acts on the linear dynamical system evolution through the variable \n$r = B \\cdot \\lambda + a$. Reciprocally, the state variable $x$ acts on the non-smooth law through the relation\n$y = C \\cdot x + D \\cdot \\lambda + F \\cdot u + e$ with $C , D , F , e$ constant over time.\n\n\\subsection{Definition of the Non Smooth Law between constrained variables}\nIt is a complementarity condition between y and $\\lambda$ : $0 \\leq y \\, \\perp \\, \\lambda \\geq 0$. This corresponds\nto the behaviour of the rectifying diode, as described in \\ref{Non Smooth laws}.\n \n\\section{The formalization of the electrical oscillator with half-wave rectifier into the LCS}\n\nThe equations come from the following physical laws :\n\\begin{itemize}\n\\item the Kirchhoff current law (KCL) establishes that the sum of the currents arriving at a node is zero,\n\\item the Kirchhoff voltage law (KVL) establishes that the sum of the voltage drops in a loop is zero,\n\\item the branch constitutive equations define the relation between the current through a bipolar device\nand the voltage across it\n\\end{itemize}\nRefering to figure \\ref{fig-CircuitRLCD}, the Kirchhoff laws could be written as :\n\\[\n\\begin{array}{l}\nv_L = v_C\\\\\nv_R + v_D = v_C\\\\\ni_C + i_L + i_R = 0\\\\\ni_R = i_D\n\\end{array}\n\\]\nwhile the branch constitutive equations for linear devices are :\n\\[\n\\begin{array}{l}\ni_C = C v_C'\\\\\nv_L = L i_L'\\\\\nv_R = R i_R\n\\end{array}\n\\]\nand last the \"branch constitutive equation\" of the ideal diode that is no more an equation but instead\na complementarity condition :\n\\[ \n0 \\leq i_D \\, \\perp \\, -v_D \\geq 0\n\\]\n\nThis is illustrated on figure \\ref{fig-diode-reg} where the left-hand sketch displays the ideal diode \ncharacteristic and the right-hand sketch displays the usual exponential characteristic as stated by\nShockley's law.\n\n\\begin{figure}[htp]\n\\begin{center}\n\\includegraphics[width=12cm]{diode-caract.eps}\n\\end{center}\n\\caption{Non-smooth and smooth characteristics of a diode}\n\\label{fig-diode-reg}\n\\end{figure}\n\n\n\\subsection{Dynamical equation}\n\\label{sec-dyn-eq}\nAfter rearranging the previous equations, we obtain :\n\n\\[ \n\\left( \\begin{array}{c}\nv_L'\\\\\ni_L'\n\\end{array} \\right)\n=\n\\left( \\begin{array}{cc}\n0 & \\frac{-1}{C}\\\\\n\\frac{1}{L} & 0\n\\end{array} \\right)\n \\cdot\n\\left( \\begin{array}{c}\nv_L\\\\\ni_L\n\\end{array} \\right)\n+\n\\left( \\begin{array}{c}\n\\frac{-1}{C}\\\\\n 0\n\\end{array} \\right)\n \\cdot i_D\n\\]\nthat fits in the frame of \\ref{sec-def-NSDS} with\n\\[\nx = \n\\left( \\begin{array}{c}\nv_L\\\\\ni_L\n\\end{array} \\right)\n\\]\nand \n\\[\n\\lambda = i_D\n\\]\n\n\n\n\\subsection{Relations}\nWe recall that the $r = B \\cdot \\lambda + a$ equation is expressed with\n\n\\[\nr =\n\\left( \\begin{array}{c}\n\\frac{-1}{C}\\\\\n 0\n\\end{array} \\right)\n \\cdot i_D\n\\]\nfrom the dynamical equation (\\ref{sec-dyn-eq}).\\\\\nRearranging the initial set of equations yields :\n\\[\n-v_D = \n\\left( \\begin{array}{cc}\n-1 & 0\n\\end{array} \\right)\n \\cdot\n\\left( \\begin{array}{c}\nv_L\\\\\ni_L\n\\end{array} \\right)\n+ R i_D\n\\]\nas the second equation of the linear time invariant relation with \n\\[\ny = -v_D\n\\]\n\n\n\n\\subsection{Non Smooth laws}\n\\label{Non Smooth laws}\nThere is just the complementarity condition resulting from the ideal diode characteristic :\n\n\\[ \n0 \\leq i_D \\, \\perp \\, -v_D \\geq 0\n\\]\n\n\n\n\\section{Description of the numerical simulation: the Moreau's time-stepping scheme}\n\\subsection{Time discretization of the dynamical system}\nThe integration of the ODE over a time step $[t_i,t_{i+1}]$ of length $h$ is :\n\n\\[\n\\int_{t_i}^{t_{i+1}}x'\\,dt = \\int_{t_i}^{t_{i+1}} A \\cdot x\\,dt + \\int_{t_i}^{t_{i+1}}(E \\cdot u + b) dt + \\int_{t_i}^{t_{i+1}}r\\,dt   \n\\]\nThe left-hand term is $x(t_{i+1})-x(t_i)$. \\\\\nRight-hand terms are approximated this way :\n\\begin{itemize}\n\\item $\\int_{t_i}^{t_{i+1}} A \\cdot x\\,dt$ is approximated using a $\\theta$-method\n\\[\n\\int_{t_i}^{t_{i+1}} A \\cdot x\\,dt \\approx h \\theta (A \\cdot x(t_{i+1})) + h (1-\\theta) (A \\cdot x(t_{i}))\n\\]\n\n\\item since the second integral comes from independent sources, it can be evaluated with whatever quadrature method, for\ninstance a $\\theta$-method \n\\[\n\\int_{t_i}^{t_{i+1}}(E \\cdot u + b) dt \\approx h \\theta (E \\cdot u(t_{i+1}) + b(t_{i+1})) + \n                                                              h (1-\\theta) (E \\cdot u(t_{i}) + b(t_{i}))\n\\]\n\n\\item the third integral is approximated like in an implicit Euler integration\n\\[\n\\int_{t_i}^{t_{i+1}}r\\,dt \\approx h r(t_{i+1})\n\\]\n\\end{itemize}\nBy replacing the accurate solution $x(t_i)$ by the approximated value $x_i$, we get :\n\\[\nx_{i+1}-x_i = h \\theta (A \\cdot x_{i+1}) + h (1-\\theta) (A \\cdot x_{i}) + \n              h \\theta (E \\cdot u(t_{i+1}) + b(t_{i+1})) + h (1-\\theta) (E \\cdot u(t_{i}) + b(t_{i})) + h r_{i+1}\n\\]\nAssuming that $I - h \\theta A$ is invertible, matrix $W$ is defined as $(I - h \\theta A)^{-1}$. We get then :\n\\[\nx_{i+1} = W(I + h (1-\\theta) A) \\cdot x_{i} + \n            W (h \\theta (E \\cdot u(t_{i+1}) + b(t_{i+1})) + h (1-\\theta) (E \\cdot u(t_{i}) + b(t_{i}))) + h W r_{i+1}\n\\]\nAn intermediate variable $x_{free}$ related to the smooth part of the system is defined as :\n\\[\nx_{free} = W(I + h (1-\\theta) A) \\cdot x_{i} + \n           W (h \\theta (E \\cdot u(t_{i+1}) + b(t_{i+1})) + h (1-\\theta) (E \\cdot u(t_{i}) + b(t_{i})))\n\\]\nThus the calculus of $x_{i+1}$ becomes :\n\\[\nx_{i+1} = x_{free} + h W r_{i+1}\n\\]\n\n\\subsection{Time discretization of the relations}\nIt comes straightforwardly :\\\\\n\n$r_{i+1} = B \\cdot \\lambda_{i+1} + a$\\\\\n\n$y_{i+1} = C \\cdot x_{i+1} + D \\cdot \\lambda_{i+1} + F \\cdot u(t_{i+1}) + e$\\\\\n\n\n\\subsection{Time discretization of the non-smooth law}\nIt comes straightforwardly :\n\\[\n0 \\leq y_{i+1} \\, \\perp \\, \\lambda_{i+1} \\geq 0\n\\]\n\n\\subsection{Summary of the time discretized equations}\nThese equations are summarized assuming that there is no source term and simplified relations as for the \nelectrical oscillator with half-wave rectifier.\n\n\\begin{eqnarray*}\nW & = & (I - h \\theta A)^{-1} \\\\\nx_{free} & = & W(I + h (1-\\theta) A) \\cdot x_{i} \\\\\nx_{i+1} & = & x_{free} + h W r_{i+1} \\\\\nr_{i+1} & = & B \\cdot \\lambda_{i+1}  \\\\\ny_{i+1} & = & C \\cdot x_{i+1} + D \\cdot \\lambda_{i+1}  \\\\\n & 0 \\leq y_{i+1} \\, \\perp \\, \\lambda_{i+1} \\geq 0 & \n\\end{eqnarray*}\n\n\\subsection{Numerical simulation}\nThe integration algorithm with a fixed step is described here :\n\n\\begin{algorithm}\n\\caption{Integration of the electrical oscillator with half-wave rectifier through a fixed Moreau time stepping scheme}\n\\begin{algorithmic} \n\n\\REQUIRE $R > 0 , L > 0 , C > 0$\n\\REQUIRE Time parameters $h,T,t_0$ and $\\theta$ for the integration \n\\REQUIRE Initial value of inductor voltage $v_L = x_0(0)$\n\\REQUIRE Optional, initial value  of inductor current $i_L = x_0(1)$ (default : 0)\n\n\\STATE $n_{step} = \\frac{T - t_0}{h}$\n\n\\COMMENT{Dynamical system specification\\\\}\n\\STATE $A = \\left( \\begin{array}{cc}\n0 & \\frac{-1}{C}\\\\\n\\frac{1}{L} & 0\n\\end{array} \\right)$\n\n\\COMMENT{Relation specification\\\\}\n\\STATE $B = \\left( \\begin{array}{c}\n\\frac{-1}{C}\\\\\n 0\n\\end{array} \\right)$\n\\STATE $C = \\left( \\begin{array}{cc}\n-1 & 0\n\\end{array} \\right)$\n\\STATE $D = (R)$\n\n\\COMMENT{Construction of time independent operators\\\\}\n\\REQUIRE $I - h \\theta A$ invertible\n\\STATE $W = (I - h \\theta A)^{-1}$\n\\STATE $M = D + h C W B$\n\n\\COMMENT{Non-smooth dynamical system integration\\\\}\n\\FOR{$i=0$ to $n_{step}-1$}\n%\\STATE // Computation of $x_{free}$\n\\STATE \\begin{eqnarray*} \nx_{free} = W (I + h (1 - \\theta) A) x_i && \\textrm{// Computation of $x_{free}$} \\\\\n%\\STATE // Formalization of the one step LCP\nq = C \\cdot x_{free} &&  \\textrm{// Formalization of the one step LCP} \\\\\n%\\STATE // One step LCP solving\n(y_{i+1},\\lambda_{i+1})\\,=\\,\\textrm{solveLCP}(M,q) &&  \\textrm{// One step LCP solving} \\\\\n%\\STATE // Computation of new state\nx_{i+1} = x_{free} + h W B \\lambda_{i+1} &&  \\textrm{// Computation of new state}\n\\end{eqnarray*}\n\\ENDFOR\n\n\\end{algorithmic}\n\\end{algorithm}\n\n\n\n\\section{Comparison with numerical results coming from SPICE models and algorithms}\nWe have used the SMASH simulator from Dolphin to perform a simulation of this circuit with a smooth model\nof the diode as given by Shockley's law , with a classical one step solver (Newton-Raphson) and a choice between \nbackward-Euler and trapezoidal integrators.\n\n\\subsection{Characteristic of the diode in the SPICE model}\nThe figure (\\ref{fig-carac-diode}) depicts the static $I(V)$ characteristic of two diodes with default SPICE parameters\nand two values for the emission coefficient N : $1.0$ (standard diode) and $0.25$ (stiff diode).\n\n\\begin{figure}[hbt]\n\\begin{center}\n\\includegraphics[width=12cm]{caracdiode.eps}\n\\end{center}\n\\caption{Diodes characteristics from SPICE model with $N=0.25$ and $N=1$}\n\\label{fig-carac-diode}\n\\end{figure}\n \nThe stiff diode is close to an ideal one with a threshold of $0.2$ V.\n\n\\subsection{Simulation results}\nFigure (\\ref{fig-comp-SMASH-SICONOS-BE10us}) displays a comparison of the SMASH and SICONOS results with\na backward Euler integration and a fixed time step of 10 $\\mu$s. A stiff diode model was used in SMASH simulations.\nFor figure (\\ref{fig-comp-SMASH-SICONOS-TRAP10us}) a trapezoidal integrator was used, yielding a better accuracy.\nOne can notice that the results from both simulators are very close. The slight differences are due to the smooth \nmodel of the diode used by SMASH, and mainly to the threshold of around 0.2 V. Such a threshold\nyields small differences in the conduction state of the diode with respect to the ideal diode.\n\n\\begin{figure}[hbt]\n\\begin{center}\n\\includegraphics[width=12cm]{comp_SMASH_SICONOS_BE10us.eps}\n\\end{center}\n\\caption{SMASH and SICONOS simulation results with backward Euler integration, 10 $\\mu$s time step}\n\\label{fig-comp-SMASH-SICONOS-BE10us}\n\\end{figure}\n\n\\begin{figure}[hbt]\n\\begin{center}\n\\includegraphics[width=12cm]{comp_SMASH_SICONOS_TRAP10us.eps}\n\\end{center}\n\\caption{SMASH and SICONOS simulation results with trapezoidal integration, 10 $\\mu$s time step}\n\\label{fig-comp-SMASH-SICONOS-TRAP10us}\n\\end{figure}\n\n\n\\end{document}\n", "meta": {"hexsha": "644edc208c19e008e448f8087b41647e981e8b60", "size": 13952, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "examples/electronics/CircuitRLCD/Template-CircuitRLCD.tex", "max_stars_repo_name": "siconos/siconos-tutorials", "max_stars_repo_head_hexsha": "821365a6ce679fc3d606b272ff069134e3c6aa4b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2017-01-12T23:09:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-20T17:03:58.000Z", "max_issues_repo_path": "examples/electronics/CircuitRLCD/Template-CircuitRLCD.tex", "max_issues_repo_name": "siconos/siconos-tutorials", "max_issues_repo_head_hexsha": "821365a6ce679fc3d606b272ff069134e3c6aa4b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-01-14T13:44:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-17T13:57:27.000Z", "max_forks_repo_path": "examples/electronics/CircuitRLCD/Template-CircuitRLCD.tex", "max_forks_repo_name": "siconos/siconos-tutorials", "max_forks_repo_head_hexsha": "821365a6ce679fc3d606b272ff069134e3c6aa4b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-10-22T13:30:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-06T10:19:57.000Z", "avg_line_length": 33.3779904306, "max_line_length": 135, "alphanum_fraction": 0.7016198394, "num_tokens": 4440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832058771035, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.30300369271619976}}
{"text": "\\chapter{\\label{chapter1} Parton distribution functions} \nParton distributions are one of the central pillars of perturbative QCD,\nfactorising as they do the perturbatively incalculable long distance dynamics\npresent in calculations involving hadronic initial states. Combined with the\nperturbative description of the short-distance cross-section what could seem at\nfirst a hopeless situation is alleviated, and QCD becomes a predictive and\nuseful theory when applied to hadronic scattering.\n\nIn this chapter a brief overview of how parton distribution functions arise in\nQCD calculations will be presented.  We shall explore the prototypical example\nof the deep inelastic scattering (DIS) of leptons off a hadronic target, first\nin the \\emph{naive parton model} arising before the advent of QCD and then with\nthe QCD-improved parton model which allows for an excellent description of DIS\nmeasurements across a wide range of hard scales.\n\nThe treatment of heavy quarks in parton distributions is a particularly delicate\nissue and therefore will also be discussed in this introductory theory section.\nFinally there will be some exploration of the general properties of parton\ndistributions in order to provide a summary of the available theoretical\nconstraints upon PDFs.\n\n\\section{Partons in deep inelastic scattering}\nWe shall begin by introducing parton distribution functions as they arise in the\nearly parton model. The model was originally introduced by Feynman and\nBjorken~\\cite{feynman1,Feynmanparton,feynmanparton2, Bjorken:1968dy} in the late\n1960's in an effort to understand the scattering behaviour of hadronic states\nand successfully describes many properties observed in early deep inelastic\nscattering experiments.\n\nIn this process, a charged lepton $l$ probes a proton $P$ by the exchange of a\ngauge boson. For simplicity we shall describe here the neutral current process\nwhere a photon is exchanged. In the inelastic regime where the momentum transfer\nto the target proton is large, the proton does not survive the scattering\nprocess and fragments into an arbitrary hadronic final state $X$. The process\n$l(k) + P(p) \\to l(k^\\prime) + X$ is illustrated at tree level in Figure~\\ref{fig:DIS}. \n\n\\begin{figure}[ht]\n\\centering\n\\includegraphics[scale=0.5]{2-PDFs/figs/DIS.pdf}\n\\caption{Deep inelastic scattering of a charged lepton with a proton target.}\n\\label{fig:DIS}\n\\end{figure}\n\nIn this system we can define the standard DIS kinematic variables;  $Q^2$ denotes the momentum transfer from the electron to the target proton, $\\nu$ the energy transfer and $y$ the measure of the reaction's inelasticity, or fractional energy transfer. In the rest frame of the proton these are given by\n\\begin{eqnarray}\n Q^2 &=& -q^2 = -(k - k^{\\prime})^2, \\\\\n \\nu &=& M(E- E^\\prime), \\\\\n y &=& (q \\cdot p)/(k \\cdot p),\n\\end{eqnarray}\nwhere $M$ refers to the mass of the proton, and the inelasticity ranges between 0 (elastic scattering) and 1. $E$ and $E^\\prime$ denote the energies associated with the four-momenta $k$ and $k^\\prime$ respectively. Additionally, we may introduce the Bjorken scaling parameter $x$, central to the parton model,\n\\be x = \\frac{Q^2}{2\\nu}. \\ee\nNeglecting spin labels, the amplitude for this diagram in the Feynman gauge is given by\n\\be\\mathcal{M} = ie^2\\bar{u}(k^\\prime)\\gamma^\\mu u(k)\\left( i\\frac{g_{\\mu\\nu}}{Q^2} \\right)\\left<X\\right|J_h^\\nu\\left|P\\right>,  \\label{eq:DISme}\\ee\nwhere $J_h^\\nu$ represents the hadronic current. \nThe fundamental difficulty in attempting to compute the cross section for this process is our ignorance of the wavefunction for the hadronic states $\\left|X\\right>$ and $\\left|P\\right>$. To isolate the problem, we are able to factorise the spin averaged square of the amplitude in Equation \\ref{eq:DISme} into a leptonic ($L_{\\mu\\nu}$) and a hadronic ($W^{\\mu\\nu}$) part\n\\be |\\overline{\\mathcal M}|^2 = \\frac{1}{Q^2} L_{\\mu\\nu}W^{\\mu\\nu}, \\ee\nwhere the leptonic tensor is straightforwardly calculable:\n\\ba L_{\\mu\\nu} &=& e^2\\sum_{spin} \\bar{u}(k^\\prime)\\gamma_\\mu u(k) \\bar{u}(k)\\gamma_\\nu u(k^\\prime), \\\\\n&=& e^2 \\mathrm{ tr}\\left[ \\slashed{k}^\\prime\\gamma_\\mu\\slashed{k}\\gamma_\\nu \\right], \\\\\n&=& 4e^2[k_\\mu k^\\prime_\\nu + k_\\nu k^\\prime_\\mu - g_{\\mu\\nu}k\\cdot k^\\prime],  \\ea\nwhere here we have neglected the fermion masses. The hadronic part of the calculation is considerably more difficult to evaluate, and indeed impossible to compute from first principles in perturbation theory as it is sensitive to the low-scale, and therefore strongly coupled dynamics of the proton target:\n\\ba  \nW^{\\mu\\nu} &\\sim& \\sum_X \\left<P(p)\\right| {J_h^\\mu}^{\\dagger} \\left|X\\right>\\left<X\\right| J_h^\\nu \\left| P(p)\\right>, \\\\\n &\\sim& \\left<P(p)\\right| {J_h^\\mu}^{\\dagger} J_h^\\nu \\left| P(p)\\right>. \\ea\n\nHowever, we can gain some insight into its structure by noting that the tensor must obey the conservation requirements of the hadronic current $q_\\mu W^{\\mu\\nu}=0$ and $q_\\nu W^{\\mu\\nu}=0$. The tensor may therefore be parametrised without loss of generality by the following structure:\n\\be W_{\\mu\\nu} = -\\left( g_{\\mu\\nu} - \\frac{q_\\mu q_\\nu}{q^2}\\right) F_1(x,Q^2) +\\left(p_\\mu -q_\\mu \\frac{p \\cdot q}{q^2}\\right)\\left(p_\\nu -q_\\nu \\frac{p \\cdot q}{q^2}\\right)\\frac{1}{\\nu}F_2(x,Q^2).\\label{eq:htensor}\\ee\nHere we have introduced the parameters in our tensor $F_i$ which are known as the electromagnetic structure functions. For interactions involving parity-violating currents, there is a third contribution to the hadronic tensor arising through the $F_3$ structure function. Here the only possible functional dependence for the structure functions is upon the quantities $Q^2$ and $x$.\n\nIt is convenient now to define a projection vector $n$ with the properties $ p \\cdot n = 1$, $ n \\cdot q = 0$, and $n^2 = p^2 = 0$, where the assumption of negligible proton mass has been made. Any vector can now be written as a combination of $n$, $p$ and a component transverse to the proton momentum as a \\emph{Sudakov decomposition}. Using this projection vector we may obtain the structure functions from the hadronic tensor as so:\n\\begin{eqnarray}\n F_2 &=& \\nu n^\\mu n^\\nu W_{\\mu\\nu},  \\label{eq:proj1} \\\\\n F_L &=& F_2 - 2xF_1 = \\frac{Q^4}{\\nu^3}  p^\\mu p^\\nu W_{\\mu\\nu}, \\label{eq:proj2}\n\\end{eqnarray}\nwhere the quantity in the second equation is known as the longitudinal structure function. So far, few assumptions have been made about the form of the EM hadronic tensor $W_{\\mu\\nu}$, we have simply parametrised it in terms of a Lorentz invariant tensor structure and structure functions. Feynman's parton model allows us to describe more of the hadronic tensor with perturbation theory by proposing a composite proton formed as a bound state of fundamental, spin-$1/2$ constituents: the \\emph{partons}. \n\nThe parton model approximation states that for a sufficiently hard interaction, the virtual photon only interacts with a single point-like parton inside the target proton and we can treat the partons as approximately free particles. The hadronic tensor then admits a probabilistic expansion in terms of Parton Distributions which encode the probability of the hard photon interacting with a constituent parton carrying a faction $\\xi$ of the parent proton's momentum. The probability of interacting with a parton carrying between $\\xi$ and $\\xi+\\delta\\xi$ of the proton's momentum being given by $f(\\xi)\\delta\\xi$ where $f(\\xi)$ is the interaction probability for a parton with momentum $\\xi p$. Diagrammatically we may therefore construct the photon-hadron interaction as a weighted sum of partonic diagrams:\n\\be \\left| \\vcenter{\\hbox{\\includegraphics[height=2cm]{2-PDFs/figs/convolution1.pdf}}} \\right|^2= \\sum_i^{N_{part}}f_i(\\xi,Q^2) \\otimes \\left| \\vcenter{\\hbox{\\includegraphics[height=2cm]{2-PDFs/figs/convolution2.pdf}}}\\right|^2(\\xi), \\nonumber\\ee\nwhere we have introduced the multiplicative convolution\n\\be (f \\otimes g )(x) = \\int_0^1\\; \\frac{d\\xi}{\\xi}\\; f\\left(\\frac{\\xi}{x}\\right) g(\\xi).\\ee\nThe hadronic tensor is then given in terms of a sum of individual hard scattering partonic tensors, denoted  $\\widetilde{W}^i_{\\mu\\nu}(\\xi)$ for a target parton of type $i$. Writing the hadronic tensor as the probabilistic sum over all constituent parton types we obtain\n\\be W_{\\mu\\nu} =\\int_0^1 \\frac{d\\xi}{\\xi} \\sum_i f_i(\\xi,Q^2)\\; \\widetilde{W}^i_{\\mu\\nu}(\\xi,Q^2). \\label{eq:htensorexpan}\\ee\nAs the parton level tensors must obey the same conservation relations as the full hadronic tensor, we can once again form a general parameterization of $\\widetilde{W}^i_{\\mu\\nu}$:\n\\be \\widetilde{W}^i_{\\mu\\nu} = -\\left( g_{\\mu\\nu} - \\frac{q_\\mu q_\\nu}{q^2}\\right) \\widetilde{F_1^i}(\\xi,Q^2) +\\xi^2 \\left(p_\\mu -q_\\mu \\frac{p \\cdot q}{q^2}\\right)\\left(p_\\nu -q_\\nu \\frac{p \\cdot q}{q^2}\\right)\\widetilde{F_2^i}(\\xi,Q^2),\\ee\nwhere the factors of $\\xi^2$ arise from taking $p^\\mu \\to \\xi p^\\mu$. Substituting this form for $\\widetilde{W}^i_{\\mu\\nu}(\\xi)$ into Eqn \\ref{eq:htensorexpan} and comparing with the form in Eqn \\ref{eq:htensor}, we find two expressions for the proton EM structure functions,\n\\be F_1(x,Q^2) = \\int_0^1 \\frac{d\\xi}{\\xi} \\sum_i f_i(\\xi) \\widetilde{F_1^i}(\\xi,Q^2),  \\label{eqn:f1}\\ee\n\\be F_2(x,Q^2) = \\int_0^1 \\xi d\\xi \\sum_i f_i(\\xi) \\widetilde{F_2^i}(\\xi,Q^2). \\label{eqn:f2}\\ee\nThe naive parton level structure functions $\\widetilde{F_1^i}(\\xi,Q^2)$ describe the hard scattering subprocess involving a parton of species $i$ and may be computed by considering the parton level squared amplitude for the subprocess, $\\gamma^*(q) + q(\\xi p) \\to q(l)$ and projecting out the desired quantities with the operators defined previously. At leading order, using the parton level version of the projector Eqn \\ref{eq:proj1}:\n\\be { \\mathcal M }_\\mu = -i e_{q^i}\\bar{u}(l)\\gamma^\\mu u(\\xi p),\\ee\n\\be \\frac{n^\\mu n^\\nu}{\\xi^2} \\widetilde{W}^i_{\\mu\\nu}  = \\frac{n^\\mu n^\\nu}{\\xi^2}\\overline{\\sum} \\left| \\mathcal{M} \\right|^2_{\\mu\\nu} = 4e_{q^i}^2,\\ee\nwhere we have made the approximation that momenta transverse to the beam axis vanish. Including the phase space for the final state quark in the CM frame we obtain:\n\\be \\widetilde{F^i_2} =  2 e_{q^i}^2 \\delta(l^2),\\ee\nwhere the delta function can be rewritten in terms of $\\xi p$ and $q$:\n\\be \\delta (l^2) = \\delta ((\\xi p + q )^2 ) = \\delta (2\\xi \\nu - Q^2) = \\delta (2\\nu (\\xi - x)).\\ee \nThis is an interesting result of the analysis at leading order, the kinematical variable $x$ actually describes the momentum fraction of the interacting parton. The parton level structure function\n$\\widetilde{F^i_2}$ is therefore given by:\n\\be \\widetilde{F^i_2} = 2 e_{q^i}^2 \\delta (\\xi-x).\\ee\nThe parton level longitudinal structure function is also straightforwardly projected out of the same amplitude,\n\\be \\widetilde{F}^i_L = \\frac{Q^4}{\\xi \\nu^3}p^\\mu p^\\nu \\widetilde{W}^i_{\\mu\\nu} =  \\widetilde{F}^i_2 - \\frac{2x}{\\xi^2} \\widetilde{F}^i_1. \\ee\nAt leading order this projection, and therefore the longitudinal structure function, are exactly zero, consequently\n\\be \\widetilde{F}^i_1 = \\frac{\\xi^2}{2x} \\widetilde{F}^i_2 = e_{q^i}^2\\frac{ \\xi^2 }{x} \\delta (\\xi - x).\\ee\nWe may therefore write the full EM proton structure functions in the naive parton model as\n\\be F_1(x,Q^2) =  \\int_0^1 d\\xi \\sum_i f_i(\\xi) e_{q^i}^2\\frac{ \\xi }{x} \\delta (\\xi - x) =  \\sum_if_i(x)e^2_{q^i},\\ee\n\\be F_2(x,Q^2) = 2 \\int_0^1 \\xi d\\xi \\sum_i  f_i(\\xi) e_{q^i}^2 \\delta (\\xi-x) = 2 x \\sum_if_i(x)e^2_{q^i}.\\ee\nThese results have a number of important features. Firstly in this model the structure functions have no dependence upon the resolution parameter $Q^2$, a phenomenon known as Bjorken scaling~\\cite{Bjorken:1968dy}. This scaling effect was an important achievement of the original parton model, as it was able to describe contemporary experimental results rather well. The lack of any scale dependence in the structure functions is a consequence of the model's assumptions treating interactions with the proton's constituent partons as point like, and consequently having no characteristic length scale.\n\nSecondly we note that $F_2(x) = 2xF_1(x)$, which is known as the Callan-Gross relation~\\cite{callangross}. It illustrates a fundamental property of spin-1/2 particles, that they are unable to absorb a longitudinally polarised photon~\\cite{pQCDhandbook}.\n%\n\\section{QCD and the parton model}\nThe naive parton model was able to provide a good phenomenological description of early DIS measurements. Its success also provided great support for QCD as the correct description of the strong interaction. The phenomenon of Bjorken scaling placed substantial constraints upon the theory governing the internal dynamics of the proton. The asymptotic freedom of QCD allows for a consistent description of Bjorken-scaling, where the constituents of the hadron can be viewed as independent, non-interacting point like particles at high  values of the resolution parameter $Q^2$. The partons in Feynman's model were therefore quickly associated with the quarks and gluons of QCD.\n\\begin{figure}[t]\n\\centering\n\\includegraphics[scale=0.5]{2-PDFs/figs/d96-039f11.pdf}\n\\caption[Scaling violations in the proton structure function $F_2$]{Scaling violations in the proton structure function $F_2$. Here each curve in $x$ is scaled by a function $C(x)= 0.6(i- 0.4)$ for presentation purposes, where $i$ denotes the bin in $x$. Figure from~\\cite{Aid:1996au}.}\n\\label{fig:F2H1}\n\\end{figure}\n\nDespite the `snapshot' picture of non-interacting partons at leading order in QCD, we cannot neglect the higher order corrections to the point vertex calculated in the previous section. These corrections introduce logarithms of $Q^2$ which break the naive Bjorken scaling of the structure functions. Indeed, the measurement of such scaling violations provided one of the most powerful experimental verifications of QCD. Such violations are demonstrated in measurements of $F_2$ in Figure \\ref{fig:F2H1}. In this section we shall perform an overview of the extension of the parton model to $\\mathcal{O}(\\alpha_s)$ in QCD.\n\nAt one loop order, there are three diagrams that contribute to the $qq\\gamma$ vertex studied in the previous section; the real emission of a gluon from the initial (a) or final state (b) quarks, and the virtual correction diagram (c). Additionally at one loop order in QCD there arises a diagram initiated by a gluon splitting into a $q\\bar{q}$ pair (d).\n\n\\begin{figure}[ht]\n\\centering\n\\includegraphics[scale=0.6]{2-PDFs/figs/1loopDIS.pdf}\n\\end{figure}\n\nAll four of these diagrams are separately divergent. When appropriately regularised however, the divergences in the final state real emission and virtual correction diagrams cancel explicitly as a consequence of the IR safety of QCD, yielding a finite contribution to the cross section. However the divergences present in the real emission diagrams from the initial state partons are not subject to the same cancellations, as they modify the momenta at the interaction vertex. \n \nLike the real emission diagram of a gluon from an initial state quark, the initial state gluon diagram (d) suffers from an equivalent divergence mediated by a perturbatively calculable $g\\to q\\bar{q}$ splitting function $P_{gq}$. Including all of the finite contributions from the other contributing diagrams as the coefficient $W(x)$, the parton level structure function at next to leading order in QCD is given by\n\\ba\n \\widetilde{F_2^i}(\\xi,Q^2) &=& 2 e_i^2\\left[ \\delta(\\xi-x) \\right. \\nonumber\\\\\n \t\t\t\t &+& \\frac{\\alpha_S}{2\\pi}\\sum_j\\left(P_{ij}(\\xi)\\log\\frac{Q^2}{\\kappa^2} + W_{ij}(\\xi)\\right) \\nonumber\\\\\n\t\t\t\t &+&  \\left. \\mathcal{O}(\\alpha_S^2) \\right]. \\label{eq:f2plnlo}\n\\ea\nHere the $i$ once again refers to the partonic species at the interaction vertex, and we have introduced an infrared cutoff $\\kappa$ to regulate the parton splitting. The sum over splitting functions arises from the multiple contributions from partonic species $j$ splitting to $i$:\n\\begin{figure}[ht]\n\\centering\n\\includegraphics[scale=0.6]{2-PDFs/figs/qgq.pdf}\n\\end{figure}\n\nThe splitting functions $P_{ij}$  were known for some time at leading and next-to-leading accuracy \\cite{Gross:1973ju,Georgi:1951sr,Floratos:1977au,Altarelli:1977zs,GonzalezArroyo:1979df,Floratos:1978ny,Furmanski:1980cm,Curci:1980uw,GonzalezArroyo:1979he,Floratos:1981hs,Hamberg:1991qt}, and more recently extended to next-next-to-leading order accuracy \\cite{Moch:2004pa,Vogt:2004mw}. After convoluting the parton level functions with the PDFs, we obtain the full structure function \n\\ba\n F_2(x,Q^2) &=& \\sum_i xe_i^2\\left[\\; f_i(x) \\right.  \\nonumber\\\\\n \t\t\t\t &+& \\frac{\\alpha_S}{2\\pi}\\int_0^1 \\frac{d\\xi}{\\xi}\\sum_j\\left(P_{ij}\\left(\\frac{x}{\\xi}\\right)\\log\\frac{Q^2}{\\kappa^2} + W_{ij}(x)\\right)\\; f_j(\\xi) \\nonumber \\\\\n\t\t\t\t &+&  \\left. \\mathcal{O}(\\alpha_S^2) \\right]. \\label{eq:f2nlo}\n\\ea\nOur expression for the parton level structure function still suffers from the IR divergence when we take the limit $\\kappa\\to 0$. This issue may be resolved by concluding that the singularity arises from a breakdown of the ability of perturbation theory to describe physics in the strongly-coupled infrared. We may therefore attempt to factorise out the long distance behaviour of the structure functions into some bare parameters of the theory; analogously to the treatment of ultraviolet divergences by renormalisation of the strong coupling. In this instance we shall absorb the divergences present in the parton level structure functions into our parton distribution functions by replacing the bare quantities $f(x)$ with a physically accessible quantity measured at the \\emph{factorisation scale} $\\mu_f$. We can express these in terms of an expansion in the bare PDFs as\n\\be\nf_i(x,\\mu_F^2) = f_i(x) + \\frac{\\alpha_S}{2\\pi}\\int_0^1 \\frac{d\\xi}{\\xi} \\Delta^{(1)}_{ij}\\left(\\frac{x}{\\xi}, \\frac{\\mu_F}{\\kappa}\\right)\\; f_j(\\xi) + \\mathcal{O}(\\alpha_S^2),\n\\ee\nwhere the counter terms $\\Delta^{(n)}_{ij}$ are formed as a sum of a regular part $\\Delta^{(n)}_{r,ij}$ and a singular part $\\Delta^{(n)}_{s,ij}$, and the sum over the dummy index $j$ is implicit. The singular part of these counterterms is uniquely specified by having to remove the divergence present in the structure functions due to the collinearly divergent parton splitting. Comparing to Eqn.~\\ref{eq:f2nlo}, this divergence may be subtracted by setting\n\\be\n\\Delta^{(1)}_{s,ij} = P_{ij}\\left(\\frac{x}{\\xi}\\right)\\log\\frac{\\mu_F^2}{\\kappa^2}.\n\\ee\nUnlike the divergent part, the regular part of the counter-term is not uniquely defined by the factorisation procedure. The choice of a specific regular counter-term is known as a \\emph{factorisation scheme}; a choice consisting of shuffling terms between the regular part of the PDF definition and the coefficients present in the calculation. For example one may make a process-specific choice where all of the regular coefficients are absorbed into the PDF definition. In our example case of $F_2$ this is known as the DIS scheme~\\cite{Altarelli:1978id}, $\\Delta^{(1)}_{r,ij} = W_{ij}(x)$, in terms of which the form of the calculation becomes particularly simple:\n\\be\n F_2(x,Q^2) = 2 \\int_0^1 \\xi d\\xi \\sum_i  f^{\\mathrm{DIS}}_i(\\xi) e_{i}^2.\n\\ee\nIn practice this scheme choice is often rather unhelpful, as it does not permit a consistent definition of PDFs across multiple processes. With this in mind, the most common choice is the \\emph{Modified Minimal Subtraction} or $\\overline{\\mathrm{MS}}$ scheme where the only regular counterterms are a process independent $\\Delta^{(1)}_{r,ij} = \\log 4\\pi - \\gamma_E$. In the $\\overline{\\mathrm{MS}}$ scheme therefore our factorised PDFs are given by\n\\be \nf_i(x,\\mu_F^2) = f_i(x) + \\frac{\\alpha_S}{2\\pi} \\sum_j  \\left[\\left(P_{ij}\\left(x\\right)\\log\\frac{\\mu_F^2}{\\kappa^2} + \\log 4\\pi - \\gamma_E \\right) \\right] \\otimes f_j(x) + \\mathcal{O}(\\alpha_S^2), \\label{eq:renormpdf}\n\\ee\nand the expression for $F_2$ becomes\n\\be\nF_2(x,Q^2) = x \\sum_i e_i^2 \\left\\{ f_i(x,\\mu_F^2) +  \\frac{\\alpha_S}{2\\pi}\\int_x^1 \\frac{d\\xi}{\\xi} f_i(\\xi,\\mu_F^2)\\;\\widetilde{W}_i\\left(\\frac{x}{\\xi},\\frac{Q^2}{\\mu_F^2},\\alpha_S\\right) \\right\\},\n \\ee\nwhere the $\\widetilde{W}_i$ are the finite contributions remaining after factorisation. While the relationship between the PDFs at the factorisation scale and the bare distributions is now divergent, the renormalised quantities may be measured at some scale and used in subsequent calculations, thus making the theory predictive. In general, under a universal factorisation scheme such as $\\overline{\\mathrm{MS}}$, structure functions may be calculated as \n\\be F(x,Q^2) = \\sum_i \\int_x^1 \\frac{d\\xi}{\\xi} C_i\\left(\\frac{x}{\\xi},\\frac{Q^2}{\\mu_F^2}, \\alpha_S \\right) f_i(\\xi,\\mu_F^2), \\label{eq:DISsf} \\ee\nwhere the $C_i$ are the finite Wilson coefficients determined perturbatively and the PDFs $f_i$ encode the non-perturbative structure of the calculation. This differs from the naive parton model in that the Bjorken-scaling is now broken by logarithms of the hard scale $Q^2$, and the sum over parton species not only runs over spin-$1/2$ partons (the quarks of QCD), but also contains a contribution from an initial state gluon splitting into a quark-antiquark pair. \n\\subsection{DGLAP and PDF evolution} \\label{sec:DGLAP} As a measurable quantity, the structure function itself clearly must be independent of the unphysical factorisation scheme and scale choices. The requirement of scheme independence is of course met when the factorisation scheme is followed consistently for the definition of PDFs and Wilson coefficients in all subsequent calculations. The requirement of factorisation scale independence leads to a renormalisation group equation (RGE) for the structure function\n\\be \\mu_F \\frac{d}{d\\mu_F} F(x,Q^2) = 0,\\ee\nand consequently RGEs for the parton distributions and Wilson coefficients, once again in terms of the Altarelli-Parisi splitting functions $P_{ij}$\n\\be \\mu_F \\frac{d}{d\\mu_F}f_i(y,\\mu_F^2) = \\sum_j \\int_y^1 \\frac{dz}{z} P_{ij}\\left(\\frac{y}{z},\\alpha_S \\right) f_j(z,\\mu_F^2), \\label{eq:DGLAP}\\ee\n\\be \\mu_F \\frac{d}{d\\mu_F}C_i\\left(x,\\frac{Q^2}{\\mu_F^2}, \\alpha_S \\right) = -\\sum_i \\int_x^1 \\frac{dy}{y} C_j\\left(y,\\frac{Q^2}{\\mu_F^2}, \\alpha_S \\right) P_{ij}\\left(\\frac{x}{y},\\alpha_S \\right).\\ee\nThese are known as the Altarelli-Parisi equations~\\cite{AP} or the Dokshitzer-Gribov-Lipatov-Altarelli-Parisi (DGLAP) equations~\\cite{dokshitzer,gribovlipatov,lipatov}, and they describe how PDFs change, or \\emph{evolve} with the factorisation scale. Identically as the RGE for the running of the strong coupling performs a resummation of contributions arising from self energy diagrams, the DGLAP equation resums scale logarithms arising from collinear parton splittings. \n\nThe equations may be greatly simplified by moving to a PDF basis that largely diagonalises the matrix of splitting functions $P_{ij}$. For example we may construct a basis of \\emph{non-singlet} PDFs, e.g the valence distributions\n\\be V_i = q_i - \\bar{q_i}, \\ee\nand differences between quark sea distributions $q_s = q + \\bar{q}$\n\\begin{eqnarray}\nT_3 &=& u_s - d_s, \\\\\nT_8 &=& u_s + d_s - 2s_s,  \\\\\nT_{15} &=& u_s + d_s +s_s - 3c_s, \\\\\nT_{24} &=&  u_s + d_s +s_s + c_s - 4b_s, \\\\\nT_{35} &=&  u_s + d_s +s_s + c_s + b_s - 5t_s. \\label{eq:evolbasis2}\n\\end{eqnarray}\nAs QCD is flavour blind, the gluon contribution to the evolution of these PDFs cancels, therefore diagonalising the matrix of splitting functions in this basis. For the nonsinglet distributions the DGLAP equation reduces to\n\\be \\mu_F \\frac{d}{d\\mu_F}f^{\\mathrm{NS}}_i(y,\\mu_F^2) =\\int_z^1 \\frac{dz}{z} P^{\\mathrm{NS}}_{i}\\left(\\frac{y}{z},\\alpha_S \\right) f^{\\mathrm{NS}}_i(z,\\mu_F^2).\\label{eq:NSDGLAP}\\ee\nCompleting this basis are the gluon and the flavour singlet $\\Sigma = \\sum_i (q_i +\\bar{q}_i)$ PDFs. These remain coupled leading to a $2\\times 2$ matrix of integro-differential equations for their evolution:\n\\be\n \\mu_F \\frac{d}{d\\mu_F} \n \\begin{pmatrix} g(x,\\mu_F) \\\\  \\Sigma(x,\\mu_F) \\end{pmatrix}  =\n\\int_z^1 \\frac{dz}{z} \n  \\begin{pmatrix} P_{gg} & P_{g\\Sigma} \\\\  P_{\\Sigma g} & P_{\\Sigma\\Sigma} \\end{pmatrix} \n   \\begin{pmatrix} g(z,\\mu_F) \\\\  \\Sigma(z,\\mu_F) \\end{pmatrix}. \\label{eq:gSDGLAP}\\ee\nThese equations may be solved for a PDF at some scale $Q^2$ evolved from an initial scale $Q_0^2$. Solutions typically follow one of two procedures; arguably the most direct consists of solving the equations iteratively through numerical methods in $x$-space. This method is followed in codes such as HOPPET~\\cite{Salam:2008qg}, QCDNUM~\\cite{Botje:2010ay} and APFEL~\\cite{Bertone:2013vaa} which employ interpolation techniques to improve the speed of the solution. Alternatively the DGLAP equations may be solved by making use of the Mellin convolution theorem\n\\be \\mathcal{M}\\left\\{f \\otimes g\\right\\} = \\mathcal{M}\\left\\{f\\right\\}\\cdot \\mathcal{M}\\left\\{g\\right\\}, \\ee\nwhereby the multiplicative convolution present in equations \\ref{eq:NSDGLAP}, \\ref{eq:gSDGLAP} is reduced to a product in Mellin space; the method employed by QCD-Pegasus~\\cite{Vogt:2004ns}. In the Mellin space approach, the emphasis largely lies on a fast numerical implementation of the Mellin inversion integral.\n\nThrough either method, the solution of the DGLAP equations provides a perturbative description of the behaviour of parton distributions as they vary in scale. However we remain short of a full description of the distributions having not determined their dependence upon the momentum fraction $x$. Furthermore the precise behaviour of the PDF and structure function renormalisation may be complicated in the attempt to overcome some of the approximations we have made so far regarding the masses of quarks contributing to our parton model, which we shall address here before discussing how the $x$ behaviour of the PDFs may be elucidated.\n\\clearpage\n\\section{Treatment of heavy quarks}\nSo far in our discussion of the QCD parton model we have made the assumption that all the quarks contributing in the theory are massless, an approximation that becomes increasingly untenable when investigating scattering processes with a hard scale approaching a quark's physical mass. A careful treatment of terms depending on quark masses is therefore vital for making theoretical predictions to a dataset that spans heavy quark mass thresholds. \n\nDealing with heavy quark mass effects is a delicate issue in that different treatments generally have different regions of applicability. The specific combination of approaches to quark masses used when confronting a dataset with a broad reach in hard scale is known as a heavy quark \\emph{scheme}, although not necessarily in the spirit of factorisation or renormalisation schemes as the choice often lies in the particulars of the approximation rather than in some arbitrary shuffling of parameters. A heavy quark scheme choice can therefore potentially lead to differences with alternative calculations that do not in principle vanish in the limit of an all-orders calculation.\n\nThe space of heavy quark renormalisation schemes is bounded by two regimes where the treatment is fairly simple, the fixed flavour number scheme (FFNS) and the zero-mass variable flavour number scheme (ZM-VFNS). The remaining schemes, known as general-mass variable flavour number schemes (GM-VFNS) aim to interpolate between the FFNS and ZM-VFNS, reducing to the simpler calculations in certain kinematic limits. Motivated by observations suggesting that a more careful treatment of quark mass effects is phenomenologically relevant at the LHC~\\cite{Tung:2006tb}, a number of such schemes have arisen in an attempt to better describe experimental data. These typically differ by sub-leading terms in the method of interpolation between the two limiting regimes. We shall now outline some of the available choices and their potential impact in the case of a deep-inelastic scattering analysis. For simplicity we shall discuss a theory with $n_l$ light quarks, and attempt to introduce a single massive quark $h$ with mass $m_h$.\n\n\\subsection{The FFN and ZM-VFN schemes}\nWe consider first the kinematical regime where the hard scale of our scattering problem is of similar order or smaller than our heavy quark mass; $Q^2 \\lesssim m_h^2$. Making the assumption that the initial state proton has no intrinsic heavy quark component it is reasonable to treat the heavy quark as a purely final state particle, and the only partons in the theory are the $n_l$ light quark flavours and the gluon. In this instance, setting the factorisation and renormalisation scales $\\mu_F^2=\\mu_R^2 = \\mu^2$; the calculation of a structure function in Eqn.~\\ref{eq:DISsf} takes the form\n\\be F(n_l, Q^2, m_h^2) = \\sum_i^{n_l}  C_i\\left(n_l, \\frac{Q^2}{m_h^2}, \\frac{\\mu^2}{m_h^2}, \\frac{Q^2}{\\mu^2} \\right) \\otimes f_i(n_l, \\mu^2), \\label{eq:FFN} \\ee\nwhere the sum is over light quark flavours only and the full mass dependence of the heavy quark is intact in the calculation. The structure function can be separated into a contribution where only light flavours are present, $F^{L}$, and a contribution including the heavy flavour $F^{H}$ as,\n\\be F(n_l, Q^2, m_h^2) = F^{L}(n_l, Q^2) + F^{H}(n_l, Q^2,m_h^2), \\ee\nwhere\n\\ba\nF^{L}(n_l, Q^2) &=& \\sum_i^{n_l}  L_i\\left(n_l, \\frac{Q^2}{\\mu^2} \\right) \\otimes f_i(n_l, \\mu^2),\\\\\nF^{H}(n_l, Q^2,m_h^2) &=& \\sum_o^{n_l} H_i\\left(n_l, \\frac{Q^2}{m_h^2}, \\frac{\\mu^2}{m_h^2}, \\frac{Q^2}{\\mu^2} \\right) \\otimes f_i(n_l, \\mu^2).\n\\ea\nHere $L$ denotes the Wilson coefficients that do not contain heavy quark lines, and $H$ includes only the diagrams that do. In this instance the heavy quark structure function first contributes at $\\mathcal{O}(\\alpha_S)$ via the splitting of an initial state gluon into a $h\\bar{h}$ pair:\n\\begin{figure}[ht]\n\\centering\n\\includegraphics[scale=0.6]{2-PDFs/figs/FFNS.pdf}\n\\end{figure}\n\nThis approach is known as the \\emph{decoupling} or FFN scheme where the only quarks treated as partons are the $n_l$ light quarks. The expression in Eqn.~\\ref{eq:FFN} is unique up to terms of order $m_l^2/Q^2$ in the light quark masses which are typically treated as part of the factorisation level corrections of $\\mathcal{O}(\\Lambda^2_{\\mathrm{QCD}}/Q^2)$. While accurate in the quark mass threshold region and below, this scheme suffers from unresummed logarithms of the ratio $Q^2/m_h^2$ contained in the Wilson coefficients which can become large and damage the convergence of the perturbative series at scales much larger than the heavy quark mass.\n\nThese problems may be resolved in a scheme which treats the heavy quark as a massless parton above its mass threshold with the introduction of an associated heavy quark PDF. The subsequent renormalisation of the PDF resums the logarithmic contributions due to parton splitting via solution of the DGLAP equation, removing a significant disadvantage present in the FFN treatment. As this scheme is identical to the zero mass scheme discussed previously, but with an additional partonic flavour, this procedure is known as the Zero-Mass Variable Flavour Number (ZM-VFN) scheme. In the ZM-VFN a structure function calculation is simply\n\n\\be F(n_l+1, x,Q^2) = \\sum_i^{n_l+1} C_i\\left(n_l+1,\\frac{Q^2}{\\mu^2} \\right) \\otimes f_i(n_l+1,\\mu^2). \\label{eq:ZMVFN} \\ee\nIn this instance the heavy quark contribution to the structure function first arises now at leading order via diagrams of the type:\n\n\\begin{figure}[h]\n\\centering\n\\includegraphics[scale=0.6]{2-PDFs/figs/ZMVFNS.pdf}\n\\end{figure}\n\nIn the ZM-VFNS the heavy quark PDFs are set to zero below mass threshold and evolved as a massless parton according to the DGLAP equations for scales greater than the heavy quark mass. While this method alleviates the difficulties present in the FFN scheme at large scales, its treatment of heavy quarks only in terms of massless partons completely ignores the massive contributions to the Wilson coefficients and is therefore no longer exact. The reliability of the ZM scheme is therefore particularly reduced in the region where powers of $m_h^2/Q^2$ are significant. \n\\subsection{General mass schemes}\nAnalyses of QCD measurements are often performed by making a choice between using a suitable FFN scheme at scales in the region of heavy quark mass thresholds or a ZM scheme at high scales where the associated powers of $m_h^2/Q^2$ can be safely neglected. In either case the treatment of heavy quarks is at least unambiguous, with the ZM approach yielding a simpler procedure as there is no requirement to calculate coefficient functions with the heavy quark masses intact.\n\nFor analyses of a large dataset, potentially spanning several heavy quark thresholds and extending to very high scales, the desire to improve the perturbative reliability of the calculations has led to the development of a number of hybrid or \\emph{general mass} schemes. In such schemes the treatments generally reduce to the FFN regime at low scales and the ZM treatment at high scales, with the intermediate regime handled via some interpolation between the two. Generally in a Variable Flavour Number (VFN) scheme one requires that\n\\be F^{L}(n_l, Q^2) + \\lim_{Q^2 \\gg m_h^2} \\left[ F^{H}(n_l, Q^2,m_h^2)\\right] =  F(n_l+1, x,Q^2), \\label{eq:VFN}\\ee\ni.e. that the ZM-VFN and FFN calculations coincide at large scales, where the heavy quark mass dependance of the FFN Wilson coefficients can be neglected. The constraint in Eqn. \\ref{eq:VFN} means that parton distributions in the two schemes may be related by a perturbatively calculable transformation.\n\n\\be f_i(n_l+1,\\mu^2) = \\sum_j^{n_l}A_{ij}\\left(n_l, \\frac{\\mu^2}{m_h^2}\\right)\\otimes f_j(n_l, \\mu^2), \\label{eq:FLVreln}\\ee\nwhere the $A$ are determined to NNLO in $\\alpha_S$ in Refs.~\\cite{Buza:1995ie,Buza:1996wv}. It should be noted that the $A$ are not square matrices, with $i$ running over the $n_l+1$ partons in the zero mass scheme, and the $j$ running over the $n_l$ partons in the FFN.\n\nIn general a GM-VFN operates as a tower of FFN-type schemes with increasing $n_l$ as the scale increases over each quark mass threshold. In constructing a GM-VFN, the guiding principle is that physical observables should be continuous across these thresholds and therefore continuous across the $n_l$ and $n_l+1$ regimes. \nTaking the heavy quark mass itself as the matching point between the two regimes, we demand that the GM-VFN structure function $F^{\\text{GM}}$ obeys\n\\ba \nF^{\\text{GM}}(m_h^2) &=& \\sum_j^{n_l} C^{\\text{GM}}_j \\left(n_l, m_h^2 \\right) \\otimes f_j(n_l) \\nonumber \\\\\n&=&   \\sum_i^{n_l+1} C^{\\text{GM}}_i\\left( n_l+1, m_h^2 \\right) \\otimes f_i(n_l+1). \\label{eq:GMmatching} \n\\ea \nwhere the dependance upon the perturbative scales has been omitted for notational simplicity, and the GM superscripts refer to the coefficients in a general mass scheme. Using the relation in Eqn. \\ref{eq:FLVreln} we can express the $n_l+1$ expression in the matching Eqn. \\ref{eq:GMmatching} in terms of the $n_l$ scheme PDFs, therefore obtaining the relation\n\\ba && \\sum_j^{n_l} C^{\\text{GM}}_j \\left(n_l, m_h^2 \\right) \\otimes f_j(n_l) \\\\\n=  && \\sum_i^{n_l+1} \\sum_j^{n_l } C^{\\text{GM}}_i\\left( n_l+1, m_h^2 \\right) \\otimes A_{ij}\\left(n_l, m_h^2\\right)\\otimes f_j(n_l). \\ea\nSubsequently, we may make the identification\n\\be  C^{\\text{GM}}_j \\left(n_l, m_h^2 \\right) \n=   \\sum_i^{n_l+1} C^{\\text{GM}}_i\\left( n_l+1,m_h^2 \\right) \\otimes A_{ij}\\left(n_l, m_h^2\\right),\\label{eq:minimalGM}\\ee\nwhich provides the minimal description for the construction of a GM-VFN scheme~\\cite{Thorne:2008xf}. Ensuring that Eqn.~\\ref{eq:minimalGM} is satisfied order by order in $\\alpha_S$, we can construct the expression for the GM-VFN scheme coefficient functions above the heavy quark mass threshold. Taking the simplistic example case of Ref.~\\cite{Kramer:2000hn} with a theory including only a gluon and a single heavy quark ($h=\\bar{h}$), the GM-VFN coefficients may be constructed to order $\\alpha_S$ as\n\\ba\nC_g^{\\text{LO}}(n_l+1,m_h) &=& C_g^{\\text{LO}}(n_l,m_h), \\\\\nC_g^{\\text{NLO}}(n_l+1,m_h) &=& C_g^{\\text{NLO}}(n_l,m_h) \\nonumber \\\\\n&-& C_h^{\\text{LO}}(n_l+1,m_h)\\otimes A^{\\text{LO}}_{hg}(n_l, m_h^2). \\label{eq:ACOT}\n\\ea\nwhere the GM superscript has been omitted, the new superscript specifying the order of the term in the perturbative expansions of the quantities $C$ and $A$. Here the rightmost term in the $\\mathcal{O}(\\alpha_S)$ expression Eqn.~\\ref{eq:ACOT} is known as the \\emph{subtraction term} which ensures the cancellation of the IR-unsafe scale logs present in the FFN calculation. The ambiguity in the definition of a GM-VFNS arises upon noticing that terms proportional to powers of $m_h/Q$ may be interchanged between the Wilson coefficients in Eqn.~\\ref{eq:ACOT} without changing the final value of the structure function. In this respect changing the distribution of terms between the gluon and heavy quark initiated diagrams in Eqn.~\\ref{eq:ACOT} provides the opportunity to perform a \\emph{scheme choice}, a freedom which has been exploited by several different GM-VFN scheme implementations. \n\nThe earliest complete description of a GM-VFNS was provided by the ACOT method~\\cite{Collins:1978wz} which ensures the continuity of physical quantities through Eqn.~\\ref{eq:minimalGM}, but does not attempt to take advantage of the degeneracy in the GM-VFN procedure. An important result was achieved with the Simplified-ACOT or S-ACOT  scheme~\\cite{Collins:1998rz,Kramer:2000hn} which was able to exploit this ambiguity to considerably simplify the calculation of physical observables. In the S-ACOT scheme it was noted that shifts of the Wilson coefficients by their zero-mass limits may be absorbed into a redefinition of the GM-VFNS. That is, terms such as\n\\be C_h(n_l+1, m_h) - C_h(n_l+1, 0),\\ee\nvanish in the limit $Q^2 \\gg m_h^2$, and therefore do not spoil the interpolation between the FFN and ZM schemes. This leads to the option of shifting to a simpler scheme where the massive heavy quark initiated coefficients may instead be evaluated with the heavy quark mass set to zero. Other options for the scheme definition were explored by Thorne and Roberts in the TR type schemes~\\cite{Thorne:1997uu,Thorne:1997ga}, with the additional constraint that scale derivatives of heavy flavour structure functions should also be continuous at the matching scale.\n%\n\\subsubsection{The FONLL approach}\n%\nA more recent approach was developed by examining methods previously used to combine fixed order calculations with next-to-leading log resummation via the FONLL method~\\cite{Cacciari:1998it}. The method was extended from the original application of studying the \\pt spectrum in heavy flavour hadroproduction to the treatment of heavy quarks in DIS by Forte \\emph{et al.}~\\cite{Forte:2010ta}. The procedure begins by inverting the relationship in Eqn.~\\ref{eq:FLVreln} so as to express an $n_l$ flavour structure function in terms of $n_l+1$ flavour PDFs,\n\\be F(n_l,Q^2) = \\sum_i^{n_l} B_i\\left(\\frac{Q^2}{m_h^2}\\right)\\otimes f_i(n_l+1,Q^2), \\label{eq:FONLLmassive}\\ee\nwhere it is important to note that the sum over flavours does not include the heavy flavour PDF, and the full heavy quark mass dependence is present in the coefficients $B$. To perform a matching with the massless scheme, the ZM result in Eqn.~\\ref{eq:ZMVFN} can be expressed in terms of light flavour PDFs only, given the assumption that the heavy flavour PDF is generated perturbatively. In this case, Eqn.~\\ref{eq:ZMVFN} can be written\n\\be F(n_l+1, Q^2) = \\sum_i^{n_l} \\widetilde{C}_i\\left(n_l+1,\\frac{Q^2}{m_h^2} \\right) \\otimes f_i(n_l+1,\\mu^2). \\label{eq:FONLLmassless}\\ee\nwhere once again, the sum runs over only light flavours, this time with the heavy flavour contribution being generated via DGLAP evolution included into the modified coefficient function $\\widetilde{C}$. To understand which terms are common in the two descriptions, the massive coefficient functions may be decomposed into terms logarithmically dependant upon the heavy quark mass, and terms suppressed by powers of $m_h/Q$: \n\\be B_i\\left(\\frac{Q^2}{m_h^2}\\right) = \\overline{B}_i\\left(\\frac{Q^2}{m_h^2}\\right) + \\mathcal{O}\\left(\\frac{m_h}{Q}\\right).\\ee  \nAs only the power suppressed terms vanish in the limit of $Q^2 \\gg m_h^2$, the terms remaining must be common to both the ZM and massive scheme calculations. We can therefore express the massive structure function in a `\\emph{massless}' limit, having dropped those terms in the coefficient functions that are suppressed by powers of $m_h/Q$:\n\\be \\overline{F}(n_l,Q^2) = \\sum_i^{n_l} \\overline{B}_i\\left(\\frac{Q^2}{m_h^2}\\right)\\otimes f_i(n_l+1,Q^2).\\label{eq:FONLLdoublecount}\\ee\nThe FONLL result for the structure function is given by the sum of the massive calculation in Eqn.~\\ref{eq:FONLLmassive}, and the massless calculation in Eqn.~\\ref{eq:FONLLmassless} with the asymptotic limit of the massive calculation in Eqn.~\\ref{eq:FONLLdoublecount} subtracted. \n\\be\nF^{\\mathrm{FONLL}}(Q^2) =\\left[ F(n_l,Q^2) + F(n_l+1, Q^2) \\right] - \\overline{F}(n_l,Q^2).\n\\ee\nWith the subtraction ensuring the cancellation of terms which are double counted between the massive and massless calculations. Therefore in this expression the mass-suppressed terms present in the FFN calculation are fully accounted for in the GM scheme, with the duplicate terms subtracted. The simplicity of this approach helped to elucidate many of the differences between general mass schemes.\n\nIt should be noted that while general mass schemes suffer from an ambiguity in their definition compared to the simpler fixed-flavour and zero mass schemes, the differences between them are always of higher order compared to the calculation at hand, as is the case in any true scheme choice. Indeed, a well-defined GM-VFNS will always reduce to the decoupled result at low scales and the zero-mass result at scales much higher than the quark mass, behaving effectively as a tower of fixed flavour schemes with increasing number of partonic quarks. The general-mass schemes therefore do not suffer from a significant loss of predictive power, and are able to provide considerable improvement over the simpler schemes when dealing with datasets spanning quark mass thresholds.\n%\n\\section{General features of parton distributions}\n%\nWhile we have now described how the parton distributions functions at an experimental scale $Q^2$ may be found by evolving parton distributions from an initial scale, and discussed briefly how the renormalisation of heavy quark distributions may be accomplished, the issue of determining the functional dependence of the parton distributions upon the momentum fraction $x$ at some initial scale $f_i(x,Q_0^2)$ remains. \n\nThe number of independent PDFs to be determined is dependent upon the choice of initial scale, as quark distributions that can be considered \\emph{heavy} with respect to $Q^2_0$ may be generated perturbatively through the DGLAP procedure outlined previously. The typical choice is to determine the parton distributions at some scale $ m_s^2< Q^2_0 \\le m_c^2$ such that the flavours $c$, $b$, $t$ are produced by evolution. These scale choices minimise the number of distributions to be determined while remaining perturbatively reliable.\n\nAs the remaining seven distributions\\footnote{The gluon, the $u$, $d$, $s$ quarks and their antiquarks.} are fundamentally a parametrisation of the nonperturbative dynamics of the proton, they are by definition out of reach of a perturbative analysis. There are however some general statements that may be made of their $x$-dependence that are independent of the hard scale. The most important of which are the parton distribution \\emph{sum rules} which constrain the relative normalisation of PDFs.\n\nFirstly, the \\emph{momentum sum rule} (MSR) ensures that the parton distributions' fractional momenta sum to the momentum of the parent proton\n\\be  \\int_0^1 dx \\left[  x\\Sigma(x,Q^2) + xg(x,Q^2) \\right]= 1, \\label{eq:MSR} \\ee\nwhere $\\Sigma$ is the singlet distribution defined previously. Following this are the quark valence sum rules. These fix the quark distributions such that the resulting proton has the appropriate quantum numbers,\n\\begin{subequations}\n\\label{eq:VSR}\n\\ba \\text{up-valence:}& \\: &\\int_0^1 dx\\left( f_u(x,Q^2) - f_{\\bar{u}}(x,Q^2) \\right) = 2, \\label{eq:UVSR} \\\\\n      \\text{down-valence:}&  \\: & \\int_0^1 dx\\left( f_d(x,Q^2) - f_{\\bar{d}}(x,Q^2) \\right) = 1, \\label{eq:DVSR}\\\\\n      \\text{strange-valence:}&  \\: & \\int_0^1 dx\\left( f_s(x,Q^2) - f_{\\bar{s}}(x,Q^2) \\right) = 0. \\label{eq:SVSR} \n\\ea\n\\end{subequations}\n\nFrom these rules we may infer additional constraints upon individual PDFs. The MSR suggests a form for the large-$x$ behaviour of the distributions, in that they should parametrically tend to zero as $x\\to1$. The number sum rules in Eqns. \\ref{eq:VSR} require the valence-type distributions to be integrable over the whole $x$-range. While there is no requirement for the singlet and gluon distributions to be integrable, their first moments must be, as required by the MSR. Combining these three constraints we may parametrise the large and small-$x$ behaviour of both valence-like and gluon or singlet-like distributions as:\n\\ba f_V(x,Q_0^2) &= N_V\\;x^{\\alpha_V}(1-x)^{\\beta_V}\\,r_V(x), \\nonumber \\\\\n f_\\Sigma(x,Q_0^2) &= N_\\Sigma\\;x^{\\alpha_\\Sigma}(1-x)^{\\beta_\\Sigma}\\,r_\\Sigma(x). \\label{eq:pdflimits}\\ea\nIn these expressions, the parameters $\\alpha$ and $\\beta$ control the small and large-$x$ PDF behaviour respectively. The $\\beta$ should be such that the PDFs tend to zero smoothly at large-$x$, and the $\\alpha$ such that the valence distributions are integrable, and the first moment of the gluon and singlet are integrable. The overall PDF normalisations $N$ being constrained via the appropriate sum rules.\n\nFinally, what remains in the determination of the distributions are the remainder terms $r(x)$ which describe the PDFs between the two $x$-limits. Their determination is considerably more complex and is a ongoing source of research. Much of this thesis will be dedicated to discussing the determination of these remainder functions.\n", "meta": {"hexsha": "f77e21d32a402e4160d7224ac63317b243913780", "size": 46058, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "2-PDFs/chapter2.tex", "max_stars_repo_name": "nhartland/thesis", "max_stars_repo_head_hexsha": "a58dc2b3d8b218b3893f4a8f0c1e6bcdcc545c55", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2-PDFs/chapter2.tex", "max_issues_repo_name": "nhartland/thesis", "max_issues_repo_head_hexsha": "a58dc2b3d8b218b3893f4a8f0c1e6bcdcc545c55", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2-PDFs/chapter2.tex", "max_forks_repo_name": "nhartland/thesis", "max_forks_repo_head_hexsha": "a58dc2b3d8b218b3893f4a8f0c1e6bcdcc545c55", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 146.2158730159, "max_line_length": 1028, "alphanum_fraction": 0.7613009683, "num_tokens": 13201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.302875835208065}}
{"text": "\\documentclass[10pt,fleqn]{article}\n\\usepackage{amsmath}\n\\usepackage{cancel}\n\\usepackage[letterpaper, landscape, margin=1in]{geometry}\n\n\\setlength{\\parindent}{0pt}\n\n\\begin{document}\n\n\\section{Pseudo- visco- acoustic VTI variable density coupled second order self adjoint system}\nJohn Washbourne, Ken Bube\\\\\nSeptember 20, 2013\n\n\\section{Introduction}\nThis note shows the derivation of \\textit{time update equations} for the pseudo- visco-\nacoustic vertical transverse isotropy (VTI) variable density coupled second order self-adjoint\nsystem. We implement attenuation with a monochromatic approximation to Maxwell bodies, and use\nthis attenuation model to implement zero outgoing absorbing boundary conditions on the exterior\nof the modeling domain.\n\\vspace{10pt}\n\nThe time update equations are used to advance solutions in time, expressing the quasi-p\npressure wavefield $P_{(t + \\Delta)}$ and quasi-s pressure wavefield $M_{(t + \\Delta)}$\nat the next time step $(t + \\Delta)$ as functions of $P_{(t - \\Delta)}, P_{(t)}$ and $M_{(t - \\Delta)}, P_{(t)}$\n\n\\subsection{Symbols}\n\\begin{center}\n\\begin{tabular}{ll} \\\\[-10pt]\n$\\partial_t,\\ \\partial_x,\\ \\partial_y,\\ \\partial_z$ & $ \n\\displaystyle \\frac{\\partial }{\\partial t},\\ \n\\displaystyle \\frac{\\partial }{\\partial x},\\ \n\\displaystyle \\frac{\\partial }{\\partial y},\\ \n\\displaystyle \\frac{\\partial }{\\partial z} $ \\\\[15pt]\n$\\Delta$ & Temporal sampling \\\\[15pt]\n$\\omega, Q$ & reference frequency for attentuation, attenuation at frequency $\\omega$ \\\\[10pt]\n$P, M$ & quasi-P, quasi-S wavefields\\\\[10pt]\n$s_p(x,y,z,t),\\ s_m(x,y,z,t)$ & quasi-P, quasi-S source terms\\\\[10pt]\n$f$ & $ 1 - \\displaystyle \\frac{V_p^2}{V_s^2} $\\\\[10pt]\n$ \\widehat{\\eta} $ & $ \\sqrt{ \\displaystyle \\frac{2 \\left(\\epsilon - \\delta\\right) }{f + 2 \\epsilon } } $\\\\[10pt]\n$b$ & buoyancy = $\\displaystyle 1/\\rho $ (reciprocal density) \\\\[10pt]\n$ \\{\\ V_p,\\ \\epsilon,\\ \\widehat{\\eta}\\ \\} $ & Material parameters \\\\[10pt]\n\\end{tabular}\n\\end{center}\n\n\\newpage\n\\subsection{Coupled second order modeling system}\nEquation \\ref{eq:system} shows the modeling system with absorbing boundaries\nimplemented using amplitude only (dissipation only, no dispersion) Q.\n\\vspace{10pt}\n\nWe apply the time derivatives in the terms $\\displaystyle \\frac{\\omega}{Q} \\partial_t p$\nand $\\displaystyle \\frac{\\omega}{Q} \\partial_t m$ using a backward one-sided numerical\ndifference. We tested both forward one-sided and centered difference alternatives and\nfound them to be less stable.\n\n\\begin{equation}\n\\begin{aligned}\n&\\frac{b}{V_p^2} \\left( \\partial_t^2(P) + \\frac{\\omega}{Q} \\partial_t(P) \\right) = \\ \n\\partial_x \\left( b (1 + 2 \\epsilon) \\partial_x(P) \\right) +\n\\partial_y \\left( b (1 + 2 \\epsilon) \\partial_y(P) \\right) +\n\\partial_z \\left( b (1 - f \\widehat{\\eta}^2) \\partial_z(P) \\right) + \n\\partial_z \\left( b f \\widehat{\\eta} \\sqrt{1 - \\widehat{\\eta}^2} \\partial_z(M) \\right) + s_p \\\\[10pt]\n&\\frac{b}{V_p^2} \\left( \\partial_t^2(M) + \\frac{\\omega}{Q} \\partial_t(M) \\right) = \\ \n\\partial_x \\left( b (1 - f) \\partial_x(M) \\right) +\n\\partial_y \\left( b (1 - f) \\partial_y(M) \\right) +\n\\partial_z \\left( b (1 - f + f \\widehat{\\eta}^2) \\partial_z(M) \\right) + \n\\partial_z \\left( b f \\widehat{\\eta} \\sqrt{1 - \\widehat{\\eta}^2} \\partial_z(P) \\right) + s_m \\\\[10pt]\n\\end{aligned}\n\\label{eq:system}\n\\end{equation}\n\n\\section{Time update equations}\n\n\\subsection{Time update numerical difference formulas, first and second order}\n\\begin{equation}\n\\partial_t p = \\frac{1}{\\Delta} \\left[ p_{(t)} - p_{(t - \\Delta)} \\right]\n\\label{eq:diff1}\n\\end{equation}\n\n\\begin{equation}\n\\begin{aligned}\n\\partial_t^2 p &= \\frac{1}{\\Delta^2} \\left[ p_{(t+\\Delta)} - 2 p_{(t)} + p_{(t - \\Delta)} \\right] \\\\[10pt]\np_{(t+\\Delta)} &= \\Delta^2 \\partial_t^2 p + 2 p_{(t)} - p_{(t - \\Delta)}\n\\end{aligned}\n\\label{eq:diff2}\n\\end{equation}\n\n\\subsection{Rearrange terms for $\\partial_t^2(P)$ and $\\partial_t^2(M)$ }\n\\begin{equation}\n\\begin{aligned}\n\\partial_t^2(P) = \\ \n& \\frac{V_p^2}{b} \\left[ \n\\partial_x \\left( b (1 + 2 \\epsilon) \\partial_x(P) \\right) +\n\\partial_y \\left( b (1 + 2 \\epsilon) \\partial_y(P) \\right) +\n\\partial_z \\left( b (1 - f \\widehat{\\eta}^2) \\partial_z(P) \\right) + \n\\partial_z \\left( b f \\widehat{\\eta} \\sqrt{1 - \\widehat{\\eta}^2} \\partial_z(M) \\right) + s_p\n\\right] \n- \\frac{\\omega}{Q} \\partial_t(P) \\\\[10pt]\n\\partial_t^2(M) = \\ \n& \\frac{V_p^2}{b} \\left[ \n\\partial_x \\left( b (1 - f) \\partial_x(M) \\right) +\n\\partial_y \\left( b (1 - f) \\partial_y(M) \\right) +\n\\partial_z \\left( b (1 - f + f \\widehat{\\eta}^2) \\partial_z(M) \\right) + \n\\partial_z \\left( b f \\widehat{\\eta} \\sqrt{1 - \\widehat{\\eta}^2} \\partial_z(P) \\right) + s_m \n\\right]\n- \\frac{\\omega}{Q} \\partial_t(M) \\\\[10pt]\n\\end{aligned}\n\\nonumber\n\\end{equation}\n\n\\subsection{Apply equations \\ref{eq:diff1} and \\ref{eq:diff2}, and rearrange}\n\\begin{equation}\n\\begin{aligned}\nP^{t+\\Delta} = \\ \n& \\Delta^2\\ \\frac{V_p^2}{b} \\left[ \n\\partial_x b \\left( (1 + 2 \\epsilon) \\partial_x(P) \\right) +\n\\partial_y b \\left( (1 + 2 \\epsilon) \\partial_y(P) \\right) +\n\\partial_z b \\left( (1 - f \\widehat{\\eta}^2) \\partial_z(P) \\right) + \n\\partial_z b \\left( f \\widehat{\\eta} \\sqrt{1 - \\widehat{\\eta}^2} \\partial_z(M) \\right) + s_p \\right] \\\\[10pt]\n& \\quad - \\Delta\\ \\frac{\\omega}{Q} \\left( P^{t} - P^{t-\\Delta} \\right) \n+ 2 P^t - P^{t - \\Delta} \n\\\\[10pt]\nM^{t+\\Delta} = \\ \n& \\Delta^2\\ \\frac{V_p^2}{b} \\left[ \n\\partial_x b \\left( (1 - f) \\partial_x(M) \\right) +\n\\partial_y b \\left( (1 - f) \\partial_y(M) \\right) +\n\\partial_z b \\left( (1 - f + f \\widehat{\\eta}^2) \\partial_z(M) \\right) + \n\\partial_z b \\left( f \\widehat{\\eta} \\sqrt{1 - \\widehat{\\eta}^2} \\partial_z(P) \\right) + s_m \\right] \\\\[10pt]\n& \\quad - \\Delta\\ \\frac{\\omega}{Q} \\left( M^{t} - M^{t-\\Delta} \\right) \n+ 2 M^t - M^{t - \\Delta} \n\\end{aligned}\n\\nonumber\n\\end{equation}\n\n\\end{document}\n", "meta": {"hexsha": "f101e0b3503d739672c219aa726d90489d60d1ab", "size": 5765, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/latex_notes/VtiAcousticQ.tex", "max_stars_repo_name": "ChevronETC/WaveFD", "max_stars_repo_head_hexsha": "555cf24fc70835e789a8126a1d9866e25de4a8d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-10-28T16:59:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-25T21:55:17.000Z", "max_issues_repo_path": "docs/latex_notes/VtiAcousticQ.tex", "max_issues_repo_name": "ChevronETC/WaveFD", "max_issues_repo_head_hexsha": "555cf24fc70835e789a8126a1d9866e25de4a8d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2020-10-06T03:03:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T23:29:11.000Z", "max_forks_repo_path": "docs/latex_notes/VtiAcousticQ.tex", "max_forks_repo_name": "ChevronETC/WaveFD", "max_forks_repo_head_hexsha": "555cf24fc70835e789a8126a1d9866e25de4a8d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-26T15:19:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-26T15:19:51.000Z", "avg_line_length": 42.3897058824, "max_line_length": 113, "alphanum_fraction": 0.6603642671, "num_tokens": 2091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3028758279225509}}
{"text": "\\subsection{Results by Model Families}\n\\label{fams}\n\n\\begin{center}\n\\captionof{table}{Ranking of benchmark and horizontal models\n                  ($1~\\text{km}^2$ pixel size, 60-minute time steps):\n                  the table shows the ranks for cases with $2.5 < ADD < 25$\n                  (and $25 < ADD < \\infty$ in parentheses if they differ)}\n\\label{t:hori}\n\\begin{tabular}{|c|ccc|cccccccc|}\n\\hline\n\\multirow{2}{*}{\\rotatebox{90}{\\thead{\\scriptsize{Training}}}}\n    & \\multicolumn{3}{c|}{\\thead{Benchmarks}}\n    & \\multicolumn{8}{c|}{\\thead{Horizontal (whole-day-ahead)}} \\\\\n\\cline{2-12}\n~ & \\textit{naive}     & \\textit{fnaive}   & \\textit{paive}\n  & \\textit{harima}    & \\textit{hcroston} & \\textit{hets} & \\textit{hholt}\n  & \\textit{hhwinters} & \\textit{hses}     & \\textit{hsma} & \\textit{htheta} \\\\\n\\hline \\hline\n3 & 11      &  7 (2) &  8 (5) & 5 (7) & 4     & 3\n  &  9 (10) & 10 (9) &  2 (6) & 1     & 6 (8) \\\\\n4 & 11      &  7 (2) &  8 (3) & 5 (6) & 4 (5) & 3 (1)\n  &  9 (10) & 10 (9) &  2 (7) & 1 (4) & 6 (8) \\\\\n5 & 11      &  7 (2) &  8 (4) & 5 (3) & 4 (9) & 3 (1)\n  &  9 (10) & 10 (5) &  2 (8) & 1 (6) & 6 (7) \\\\\n6 & 11      &  8 (5) &  9 (6) & 5 (4) & 4 (7) & 2 (1)\n  & 10      &  7 (2) &  3 (8) & 1 (9) & 6 (3)  \\\\\n7 & 11      &  8 (5) & 10 (6) & 5 (4) & 4 (7) & 2 (1)\n  &  9 (10) &  7 (2) &  3 (8) & 1 (9) & 6 (3) \\\\\n8 & 11      &  9 (5) & 10 (6) & 5 (4) & 4 (7) & 2 (1)\n  &  8 (10) &  7 (2) &  3 (8) & 1 (9) & 6 (3) \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\\n\nBesides the overall results, we provide an in-depth comparison of models\n    within a family.\nInstead of reporting the MASE per model, we rank the models holding the\n    training horizon fixed to make comparison easier.\nTable \\ref{t:hori} presents the models trained on horizontal time series.\nIn addition to \\textit{naive}, we include \\textit{fnaive} and \\textit{pnaive}\n    already here as more competitive benchmarks.\nThe tables in this section report two rankings simultaneously:\nThe first number is the rank resulting from lumping the low and medium\n    clusters together, which yields almost the same rankings when analyzed\n    individually.\nThe ranks from only high demand pixels are in parentheses if they differ.\n\nA first insight is that \\textit{fnaive} is the best benchmark in all\n    scenarios:\nDecomposing flexibly by tuning the $ns$ parameter is worth the computational\n    cost.\nFurther, if one is limited in the number of non-na\\\"{i}ve methods,\n    \\textit{hets} is the best compromise and works well across all demand\n    levels.\nIt is also the best model independent of the training horizon for high demand.\nWith low or medium demand, \\textit{hsma} is the clear overall winner; yet,\n    with high demand, models with a seasonal fit (i.e., \\textit{harima},\n    \\textit{hets}, and \\textit{hhwinters}) are more accurate, in particular,\n    for longer training horizons.\nThis is due to demand patterns in the weekdays becoming stronger with higher\n    overall demand.\n\n\\begin{center}\n\\captionof{table}{Ranking of classical models on vertical time series\n                  ($1~\\text{km}^2$ pixel size, 60-minute time steps):\n                  the table shows the ranks for cases with $2.5 < ADD < 25$\n                  (and $25 < ADD < \\infty$ in parentheses if they differ)}\n\\label{t:vert}\n\\begin{tabular}{|c|cc|ccccc|ccccc|}\n\\hline\n\\multirow{2}{*}{\\rotatebox{90}{\\thead{\\scriptsize{Training}}}}\n    & \\multicolumn{2}{c|}{\\thead{Benchmarks}}\n    & \\multicolumn{5}{c|}{\\thead{Vertical (whole-day-ahead)}}\n    & \\multicolumn{5}{c|}{\\thead{Vertical (real-time)}} \\\\\n\\cline{2-13}\n~ & \\textit{hets}  & \\textit{hsma}   & \\textit{varima} & \\textit{vets} \n  & \\textit{vholt} & \\textit{vses}   & \\textit{vtheta} & \\textit{rtarima}\n  & \\textit{rtets} & \\textit{rtholt} & \\textit{rtses}  & \\textit{rttheta} \\\\\n\\hline \\hline\n3 &  2 (10) &  1  (7) & 6 (4) & 8 (6) & 10 (9)\n  &  7  (5) & 11 (12) & 4 (1) & 5 (3) &  9 (8) & 3 (2) & 12 (11) \\\\\n4 &  2  (8) &  1 (10) & 6 (4) & 8 (6) & 10 (9)\n  &  7  (5) & 12 (11) & 3 (1) & 5 (3) &  9 (7) & 4 (2) & 11 (12) \\\\\n5 &  2  (3) &  1 (10) & 7 (5) & 8 (7) & 10 (9)\n  &  6      & 11      & 4 (1) & 5 (4) &  9 (8) & 3 (2) & 12 \\\\\n6 &  2  (1) &  1 (10) & 6 (5) & 8 (7) & 10 (9)\n  &  7  (6) & 11 (12) & 3 (2) & 5 (4) &  9 (8) & 4 (3) & 12 (11) \\\\\n7 &  2  (1) &  1 (10) & 8 (5) & 7     & 10 (9)\n  &  6      & 11 (12) &\t5 (2) & 4     &  9 (8) & 3     & 12 (11) \\\\\n8 &  2  (1) &  1  (9) & 8 (5) & 7 (6) & 10 (8)\n  &  6      & 12 (10) & 5 (2) & 4     &  9 (7) & 3     & 11 \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\\n\nTable \\ref{t:vert} extends the previous analysis to classical models trained\n    on vertical time series.\nNow, the winners from before, \\textit{hets} and \\textit{hsma}, serve as\n    benchmarks.\nWhereas for low and medium demand, no improvements can be obtained,\n    \\textit{rtarima} and \\textit{rtses} are the most accurate with high demand\n    and short training horizons.\nFor six or more training weeks, \\textit{hets} is still optimal.\nIndependent of retraining and the demand level, the models' relative\n    performances are consistent:\nThe \\textit{*arima} and \\textit{*ses} models are best, followed by\n    \\textit{*ets}, \\textit{*holt}, and \\textit{*theta}.\nThus, models that can deal with auto-correlations and short-term forecasting\n    errors, as expressed by moving averages, and that cannot be distracted by\n    trend terms are optimal for vertical series.\n\nFinally, Table \\ref{t:ml} compares the two ML-based models against the\n    best-performing classical models and answers \\textbf{Q2}:\nWith low and medium demand, no improvements can be obtained again; however,\n    with high demand, \\textit{vrfr} has the edge over \\textit{rtarima} for\n    training horizons up to six weeks.\nWe conjecture that \\textit{vrfr} fits auto-correlations better than\n    \\textit{varima} and is not distracted by short-term noise as\n    \\textit{rtarima} may be due to the retraining.\nWith seven or eight training weeks, \\textit{hets} remains the overall winner.\nInterestingly, \\textit{vsvr} is more accurate than \\textit{vrfr} for low and\n    medium demand.\nWe assume that \\textit{vrfr} performs well only with strong auto-correlations,\n    which are not present with low and medium demand.\n\n\\begin{center}\n\\captionof{table}{Ranking of ML models on vertical time series\n                  ($1~\\text{km}^2$ pixel size, 60-minute time steps):\n                  the table shows the ranks for cases with $2.5 < ADD < 25$\n                  (and $25 < ADD < \\infty$ in parentheses if they differ)}\n\\label{t:ml}\n\\begin{tabular}{|c|cccc|cc|}\n\\hline\n\\multirow{2}{*}{\\rotatebox{90}{\\thead{\\scriptsize{Training}}}}\n    & \\multicolumn{4}{c|}{\\thead{Benchmarks}}\n    & \\multicolumn{2}{c|}{\\thead{ML}} \\\\\n\\cline{2-7}\n~ & \\textit{fnaive}  & \\textit{hets} & \\textit{hsma}\n  & \\textit{rtarima} & \\textit{vrfr} & \\textit{vsvr} \\\\\n\\hline \\hline\n3 & 6     & 2 (5) & 1 (4) & 3 (1) & 5 (2) & 4 (3) \\\\\n4 & 6 (5) & 2 (4) & 1 (6) & 3 (2) & 5 (1) & 4 (3) \\\\\n5 & 6 (5) & 2 (4) & 1 (6) & 4 (2) & 5 (1) & 3 \\\\\n6 & 6 (5) & 2     & 1 (6) & 4     & 5 (1) & 3 \\\\\n7 & 6 (5) & 2 (1) & 1 (6) & 4     & 5 (2) & 3 \\\\\n8 & 6 (5) & 2 (1) & 1 (6) & 4     & 5 (2) & 3 \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\\n\nAnalogously, we created tables like Table \\ref{t:hori} to \\ref{t:ml} for the\n    forecasts with time steps of 90 and 120 minutes and find that the relative\n    rankings do not change significantly.\nThe same holds true for the rankings with changing pixel sizes.\nFor conciseness reasons, we do not include these additional tables in this\n    article.\nIn summary, the relative performances exhibited by certain model families\n    are shown to be rather stable in this case study.\n", "meta": {"hexsha": "c398824193b46680f9c8a2585459891ad7dd7271", "size": 7654, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/4_stu/6_fams.tex", "max_stars_repo_name": "webartifex/urban-meal-delivery-paper-demand-forecasting", "max_stars_repo_head_hexsha": "9ee3396a24ce20c9886b4cde5cfe2665fd5a8102", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-25T19:40:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T19:40:56.000Z", "max_issues_repo_path": "tex/4_stu/6_fams.tex", "max_issues_repo_name": "webartifex/urban-meal-delivery-demand-forecasting", "max_issues_repo_head_hexsha": "9ee3396a24ce20c9886b4cde5cfe2665fd5a8102", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/4_stu/6_fams.tex", "max_forks_repo_name": "webartifex/urban-meal-delivery-demand-forecasting", "max_forks_repo_head_hexsha": "9ee3396a24ce20c9886b4cde5cfe2665fd5a8102", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.9570552147, "max_line_length": 79, "alphanum_fraction": 0.6090932846, "num_tokens": 2857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.3028758279225509}}
{"text": "\\section{Brown Dwarf vs Giant Planet}\n\\label{sec:BDvsGP}\n\\subsection{Hot Star vs Cold Star}\n\\label{sec:hot_vs_cold}\n\\cite{Marley2007} suggested that young giant planets formed by core accretion in a protoplanetary disk should\nhave a much lower entropy content at young ages than objects of same mass and age formed by gravitational collapse, \neither from a pre-stellar core or by disk instability.\nConsequently, the first type of objects should be significantly smaller, cooler and (about 100 times) fainter at young\nages than the second ones. This gave rise to the so-called ?cold start? observational signature, characteristic of young\ngiant planets formed by core accretion, vs the ?hot start? one, typical of young objects, GP?s or BD?s, formed by collapse\nto distinguish these objects from their distinct formation mechanisms. \n\nThis suggestion, however, directly relies on two assumptions. \nFirst of all, the assumption that GP?s formed by core accretion have a low entropy content implies \nthat all the energy of the accretion shock through which most of the planetary mass is processed is radiated\naway, leaving the internal energy content of the nascent planet unaffected. This is characteristic of a so-called \nsupercritical shock. In that case the radiative losses at the accretion shock act as a sink of entropy. This assumption,\nhowever, has never been verified. In fact, a proper treatment of the accretion shock at the onset of a pre-stellar core \nformation, the so-called second Larson?s core, shows that the shock in that case is sub-critical, with essentially all the \nenergy from the infalling material been absorbed by the stellar embryo \\citep{Vaytet2013, Tomida2013, Bate2014}. \nAlthough the two formation conditions differ in several ways, they share enough common processes to\nat least question the assumption of a supercritical shock for planet formation. \nThe second underlying assumption about this scenario is the assumption that BD?s form with a high entropy content. \nAgain, such an assumption is not necessarily correct. Initial conditions for brown dwarf formation are rather uncertain. \nFigure \\ref{fig:evolution} (see also \\cite{Mordasini2012a, Mordasini2013, Spiegel2012}) compares the early \nevolution of the luminosity for a 5 $M_{Jup}$ object under several assumptions. \nThe blue solid and dot-dash lines represent giant planet early evolution. \nassuming that either \nthe accretion energy is entirely converted to radiation, i.e. a supercritical \nshock condition as in \\cite{Marley2007}, or that this energy is absorbed by the planet, i.e. a sub-critical shock\nwith no radiative loss at the shock. \nThe former case yields a low entropy content thus a low luminosity at the end of\nthe accretion shock while in the second case the luminosity slowly decreases from its value at the end of the shock,\ntwo orders of magnitude brighter, for several Myr?s. The red long-dash and short-dash lines correspond to the early\nevolution of a brown dwarf \\citep{Baraffe2003} assuming an initial radius $R_i \\sim 8 R_{Jup} (\\simeq 0.8 R_{Jup})$ (short-dash) or\n$R_i \\sim 1.6~ R_{Jup}$ (long dash). This corresponds to specific entropies $\\tilde{S?} \\simeq 1.1 ? 10^9$ and \n$\\simeq 8.0 ? 10^8 erg~ g^{?1} K^{ ?1}$ , respectively.\n\n\\begin{figure}[!t]\n\\vspace{0cm}\n\\centerline{\\includegraphics[trim=0.5cm 5.5cm 0.5cm 4.5cm,clip, width=0.6\\textwidth]{fig_hot_cold_start_L2.pdf}}\n\\caption{Early evolution of a 5 Jupiter-mass object according to\ndifferent formation scenarios. Blue: object formed by core accretion assuming \neither a supercritical shock (solid line) or a subcritical shock (dash-dot line) \nat the end of the accretion process, after \\cite{Mordasini2012a}. \nRed: object formed by gravitational collapse for two arbitrary initial conditions (see text), \nafter \\cite{Baraffe2003}}\n\\label{fig:evolution}\n\\end{figure}\n\n\nAs seen in the figure, depending on the outcome of the accretion shock episode in one case and on the initial \nradius (thus entropy content) in the second case, and given the\nlong Kelvin-Helmholtz timescale for such low-mass objects (several Myrs) young planets formed by core accretion can\nbe as bright and even brighter than young BD?s for several Myrs. (Magneto)Radiation-hydrodynamics calculations of\nthe collapse of prestellar cores \\citep{Tomida2013, Vaytet2013} seem to exclude the above rather extreme \n?cold start? initial condition for a proto-BD, even though calculations have not been performed yet for such low masses.\nThey suggest initial entropy contents and radii closer to the hot-start case, the outer region of the protostellar core been\nheated up by the shock and attaining a higher entropy. Hot-start conditions for core-accretion GP?s, probably in between \nthe two above extreme cases, however, are presently not excluded. Interestingly enough, measured temperatures\nand luminosities of some directly-imaged exoplanets, notably $\\beta$ Pic b and $\\kappa$ And b, are consistent with hot-start like\nconditions and seem, so far, to exclude the coldest range of initial conditions for these objects \\citep{Currie2013,\nMarleau2013}. Therefore, at least in the absence of a better knowledge of the accretion shock \ncondition at the end of the core accretion process, the cold start - hot start argument does not provide a reliable diagnostic\nto distinguish core accretion from gravitational instability formed objects. \nFor sure there is no one-to-one correspondence between cold start vs. hot\nstart conditions and core accretion vs disk or core collapse.\n\n\\subsection {Deuterium Burning}\nThe distinction between brown dwarfs and giant planets is a topic of intense debate. \nIn 2003, the IAU has adopted the deuterium-burning (DB) minimum mass, $\\sim 10~ M_{Jup}$ , as the official distinction between the\ntwo types of objects. \nDeuterium burning has no impact on star formation and a negligible impact on stellar/BD evolution \\citep{Chabrier2000c}. \nThis is in stark contrast with the lifetime impact of hydrogen-burning, making H-burning a genuine physical mechanism\ndistinguishing objects in nuclear equilibrium for most of their lifetime, defined as stars, from objects which lack \nsignificant support against gravitational contraction and keep contracting for ever since their birth, defined as brown dwarfs.\nOne of the strongest arguments against deuterium burning to distinguish planets from brown dwarfs is\n2M 1207 b \\citep{Chauvin2005}, which is a $\\sim 4~ M_{Jup}$ companion to a $\\sim 20~ M_{Jup}$ brown dwarf. Thus, the companion is \nfirmly in the non deuterium burning mass regime, but with a system mass ratio of 20\\%, the couple appears to be best\ndescribed as an extension of the brown dwarf binary population rather than a planetary system. In contrast, it is\npresently not excluded that genuine planets formed by core accretion, characterized by a significant heavy element \nenrichment, reach masses above the deuterium burning limit and thus ignite D-burning in their core \\citep{Baraffe2008, Molliere2012, Bodenheimer2013}.\n\n\\subsection {The Brown Dwarf/Planet Overlapping Mass Regime}\nThere is now ample evidence for the existence of free floating brown dwarfs with\nmasses of the order of a few Jupiter masses in (low extinction) young clusters and in the field, see \\cite[e.g.][]{Caballero2007}, \nwith a mass distribution consistent with the extension of the stellar IMF into the BD regime. The brown\ndwarf and planet mass domains thus clearly overlap, arguing against a clear mass separation. The fundamentally\ndifferent mass distribution of exoplanets detected by radial velocity surveys, with the mass function rising below\n$\\sim 30~ M_{Jup}$ \\citep{Mayor2011}, in stark contrast with the BD mass distribution clearly suggests two \ndistinct populations, with different origins.\nOf particularly noticeable interest at this stage are the transiting objects Hat-P-2b, with a mass of $9~ M_{Jup}$ \n(Bakos et al., 2007b) and Hat-P-20b, with a mass of $7.2 M_{Jup}$ \\citep{Bakos2011}. Both objects are too dense to be brown\ndwarfs. Assuming that the observational error bars on the radius are reliable, and given the age inferred for theses \nsystem, the observed mass-radius determinations imply significant enrichment in heavy material, revealing their planetary\nnature \\citep{Leconte2009, Leconte2011}. This shows that planets at least 9 times more massive than Jupiter, close to the\nDB limit, can form according to the core-accretion scenario, possibly from the merging of lower mass planet embryos.\nNote that while massive objects like HAT-P-20 b approach the upper limit of the mass distribution predicted by the core\naccretion scenario \\citep{Mordasini2012b}, its large metal enrichment ($M_Z \\sim 340 M_{\\oplus}$, \\cite{Leconte2011}) \ncertainly excludes formation by gravitational collapse.\nAccording to the arguments given above, the present IAU definition, based on a\nclear-cut mass limit between BD?s and planets, is clearly incorrect and confusing and should be abandoned.\n\n\\section {Conclusion}\nEven though it is probably still premature to reach definitive conclusions about brown dwarf and giant planet formation \nand we must remain open to all possibilities, the confrontation of the various theories with observational constraints \nsuggests some reasonably sound conclusions. The ability of BD?s to form in isolation\nand in wide binaries; the similarity of BD number-density in low and high-density environments, indicating\nno significant dependence of BD abundances upon stellar density; the emerging observations of isolated proto-BD?s\nand pre-BD cores; the many observational properties shared by young BD?s and young stars; the observed close \nsimilarity between the pre-stellar/BD core mass function and the final stellar/BD initial mass function; \nthe BD IMF been consistent with the natural extension of the same stellar IMF down to the nearly bottom of the BD domain. \nAll these points provide evidence that dynamical interactions and dense cluster environments, disk fragmentation or photoionizing \nradiation are not required for BD formation. In contrast, all these properties are consistent with BD formation being a\nnatural scaled down version of star formation by the turbulence induced fragmentation of molecular clumps, leading\nto the formation of pre-stellar and pre-BD cores. It is not excluded, however, that, under some specific circumstances\n(very dense environment, very massive disks), the other aforementioned mechanisms might play some role but, in\nthe absence of clear observational evidence for this so far, they seem unlikely to be the dominant mechanisms for star\nand BD formation.\nConversely, the overwhelming majority of planet discoveries are consistent with planet formation by core accretion.\nAs examined in section 5.3, this scenario might also explain planet formation at large orbital distances, not mentioning\nthe possibility to explain such objects by planet scattering or outward migration. Here again, alternative scenarios like\ndisk fragmentation might occur in some places, notably in massive circumbinary disks, and thus explain some fraction of the planet population (possibly $\\sim$ 10\\% or so, \\cite[e.g.][]{Vorobyov2013}), but they can hardly be considered as\ndominant scenarios for planet formation. Hybrid scenarios invoking both gravitational fragmentation at large orbital\ndistances followed by inward migration, invoking even in some cases evaporation seem\nto raise even more problems than they bring solutions, as migration can only exacerbate problems with the gravitational \ninstability. Not only one needs to form planets by GI but one needs to prevent them to migrate rapidly all the way\ninto the star (Vorobyov and Basu, 2006b; Machida et al.,2011; Baruteau et al., 2011; Vorobyov, 2013). Migration,\nhowever, is very likely and fast given that, in that case, the disk mass must be very high, a requirement for GI to occur. \nIf planets indeed form this way, this requires very finetuning conditions, making the branching ratio for this route\nvery small.\n\nFinally, as discussed in ?\\ref{sec:BDvsGP}, there is ample evidence that the planet and brown dwarf domains overlap and that deuterium \nburning plays no particular role in the formation process. There is now growing evidence, possibly including the\nWISE survey for the field population, for the existence of non-deuterium burning free floating brown dwarfs\nand, conversely, no physical arguments against the possibility for genuine planets to ignite D-burning in their core.\nThis again shows that the IAU definition has no scientific justification and only brings scientific and mediatic \nconfusion. This also argues against the use of specific appellations for free-floating objects below the D-burning limit, these\nlatter being simply non D-burning brown dwarfs.\n\nGiven the arguments examined along this review, it seems rather secure to argue that BD?s and GP?s represent \ntwo distinct populations of astrophysical bodies which arise dominantly from two different formation mechanisms.\nWhile BD?s appear to form preferentially like stars, from the gravoturbulent fragmentation of a parent (possibly \nfilamentary) molecular clump, GP?s arguably form essentially by core accretion in a protoplanetary disk, i.e. from the\ngrowth of solids (planetesimals, pebbles) yielding eventually the accretion of a surrounding gas rich H/He envelope.\nSo, the very definition of a brown dwarf or a giant planet is intrinsically, tightly linked to its formation mechanism.\n%As briefly discussed below and in ?3.2, this latter should leave imprints which might be observationally detectable.\nAs examined in ?\\ref{sec:hot_vs_cold}, the luminosity or effective temperature at early ages, however, cannot be used as a diagnostic\nto distinguish between these two populations. On the other hand, we argue in this review that planets are necessarily\ncompanions of a central, significantly more massive object. \nConsequently, free floating objects down to a few $M_{Jup}$ can rather unambiguously be identified as genuine (non D-burning) brown dwarfs, \nand one should stop giving them different names, which simply adds to the confusion. \nThis is the most direct observational distinction between\nthe two types of objects. Ejected planets probably exist and weaken this statement but they are unlikely to represent\na significant fraction of the population. The diagnostic is less clear for wide companions to stars, except if the mass\nratio can safely exclude one of the two possibilities. According to the distinct formation scenarios, planets should\nhave a substantial enrichment in heavy elements compared with their parent star, as observed for our own solar giant\nplanets, whereas BD?s of the same mass should have the same composition as their parent cloud. As suggested in\n\\cite{Chabrier2007} and \\citep{Fortney2008}, giant planets should bear the signature of\nthis enhanced metallicity in their atmosphere. Spectroscopy or even photometry of atmospheric chemical abundances,\nnotably metal-dominated compounds like e.g. $CO$ or $CO_2$ may provide clues about the formation mechanism and thus\nhelp identifying the nature of the object. In the absence (so far) of clear observational diagnostics (mean density, \natmospheric abundances, oblateness, etc.) to get clues about these formation conditions, the very nature of some of these\nobjects might remain uncertain. As frustrating as this may sound, we will have to admit such present uncertainties, as\nignorance is sometimes part of science.", "meta": {"hexsha": "f2dece82addb47e1c706b6f22c83679180eeff32", "size": 15486, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapters/deleted exoplanets.tex", "max_stars_repo_name": "vkudak/PhD", "max_stars_repo_head_hexsha": "898b0dfc86b04471c92050253c59c0c874e92c24", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapters/deleted exoplanets.tex", "max_issues_repo_name": "vkudak/PhD", "max_issues_repo_head_hexsha": "898b0dfc86b04471c92050253c59c0c874e92c24", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapters/deleted exoplanets.tex", "max_forks_repo_name": "vkudak/PhD", "max_forks_repo_head_hexsha": "898b0dfc86b04471c92050253c59c0c874e92c24", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 93.8545454545, "max_line_length": 237, "alphanum_fraction": 0.8075035516, "num_tokens": 3511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.30287582063703666}}
{"text": "\n\\subsection{Policies}\n\nA policy maps the state onto the action\n\n\\(a_t=\\pi (s_t)\\)\n\nThe policy does not need to change over time, as discounting is constant. That is, if the policy should be different in future, it should be different now.\n\nThe policy affects the transition model, and so we have \\(P_\\pi \\).\n\n\\subsubsection{Optimal policy}\n\nThere exists a policy that is better than any other policy, under any starting state.\n\nThere is no closed form solution to finding the optimal policy.\n\nThere are instead iterative methods.\n\n", "meta": {"hexsha": "8613486cbb61f9f80c47749690ebdacb9f631083", "size": 532, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/pug/theory/computer/dynamic/01-03-policy.tex", "max_stars_repo_name": "adamdboult/nodeHomePage", "max_stars_repo_head_hexsha": "266bfc6865bb8f6b1530499dde3aa6206bb09b93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pug/theory/computer/dynamic/01-03-policy.tex", "max_issues_repo_name": "adamdboult/nodeHomePage", "max_issues_repo_head_hexsha": "266bfc6865bb8f6b1530499dde3aa6206bb09b93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-03-03T12:36:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-01T22:16:09.000Z", "max_forks_repo_path": "src/pug/theory/computer/dynamic/01-03-policy.tex", "max_forks_repo_name": "adamdboult/nodeHomePage", "max_forks_repo_head_hexsha": "266bfc6865bb8f6b1530499dde3aa6206bb09b93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6, "max_line_length": 155, "alphanum_fraction": 0.7669172932, "num_tokens": 120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.30287562875697027}}
{"text": "\\documentclass[prd]{revtex4}\n\\usepackage{amsmath, graphicx}\n\\usepackage{grffile}\n\\usepackage{dcolumn}\n\\usepackage{bm}\n\\usepackage{epsfig}\n\\usepackage{mathrsfs}  %  package for the \"curly\" fonts \n\\usepackage{subfigure}\n\\usepackage{multirow}\n\\usepackage{epstopdf}\n\\usepackage{amsmath}\n\\usepackage{algorithmicx}\n\\usepackage{amssymb}\n\\usepackage{tensor}\n\\usepackage[math]{cellspace}\n\\usepackage{bookmark}\n\\usepackage[usenames,dvipsnames]{xcolor}\n\\usepackage{hyperref}\n\\usepackage{slashed}\n\\usepackage{youngtab}\n\\usepackage{physics}\n\\usepackage{tensor}\n\n\n\\newcommand*\\apost{\\textsc{\\char13}}\n\n\\newcommand{\\TODO}[1]{{\\color{red}[}{\\color{red}TODO:} {\\color{blue}#1}{\\color{red}]}}\n\\newcommand{\\NOTE}[1]{{\\color{blue}[#1]}}\n\n\\makeatletter\n\\renewcommand*\\env@matrix[1][\\arraystretch]{%\n  \\edef\\arraystretch{#1}%\n  \\hskip -\\arraycolsep\n  \\let\\@ifnextchar\\new@ifnextchar\n  \\array{*\\c@MaxMatrixCols c}}\n\\makeatother\n\n\n\\topmargin 0.30in\n\\textheight 9.00in\n\n \\addtolength{\\voffset}{-2cm}\n \n\\begin{document}\n\n\\title{Einstein Equations and General Relativistic Hydrodynamical System in Spherically Symmetric Metric with Horizon Penetrating Coordinate}\n\n\\author{Hyun Lim}\n\n%\\pacs{}\n\\maketitle\n\nWe present a horizon penetrating coordinate for spherically symmetric metric. We adopt $G=c=1$ unit system. Consider usual Schwarzschild line element in BL coordinate for practice\n\\begin{align}\n\\label{eqn:schw_bl}\nds^2 = - \\left(1- \\frac{2M}{r} \\right) dt^2 + \\left(1- \\frac{2M}{r} \\right)^{-1} dr^2 + r^2 d\\Omega^2 \n\\end{align}\nwhere $M$ is a mass. Compare this with usual 3+1 line element form $ds^2 = - \\alpha^2 dt^2 + \\gamma_{ij} ( dx^2 + \\beta^i dt)(dx^j + \\beta^j dt)$ we can identify the lapse $\\alpha^2 = \\left(1- \\frac{2M}{r} \\right)$. As we know, the line element(Eqn.~\\ref{eqn:schw_bl}) is singular at the horizon ($r=2M$) and lapse collapse to zero. This can be problematic because equations of motion for the metric can be become exponentially unstable in the presence of a coordinate singularity without some regularization technique.\n\nOne way to resolve this problem is to move to a horizon penetrating coordinate system where this singularity is not present. The Kerr-Schild coordinates are one such coordinate system. \n\nFor example, Schwarzschild solution in spherical type Kerr-Schild coordinates\n\\begin{align}\n\\alpha &= \\sqrt{\\frac{r}{r+2M}} \\\\\n\\beta^r &= \\frac{2M}{r+2M} \\\\\n\\beta_r &=\\frac{2M}{r} \\\\\n\\beta^\\theta &= \\beta^\\varphi = 0 \\\\\nK_{ij} &= \\textrm{diag} \\left[ -\\frac{2M(r+M)}{\\sqrt{r^5 (r+2M)}} , 2M \\sqrt{\\frac{r}{r+2M}}, K_{\\theta \\theta} \\sin^2 \\theta \\right]\n\\end{align}\nSchwarzschild solution in Cartesian type Kerr-Schild coordinate\n\\begin{align}\n\\alpha &= \\sqrt{\\frac{r}{r+2M}} \\\\\n\\beta^i &= \\frac{2M}{r} \\frac{x^i}{r+2M} \\\\\n\\beta_i &=\\frac{2M x_i}{r^2} \\\\\nK_{ij} &= \\-\\frac{2M}{r^4} \\sqrt{\\frac{r}{r+2M}} \\left[ \\left( \\frac{M}{r}+2 \\right) x_i x_j - r^2 \\delta_{ij} \\right]\n\\end{align}\nwhere $x^i = (x,y,z)$ which is usual spatial Cartesian coordinate. In both cases, we can see lapse is regular at the horizon.\n\nGeneral spherical symmetric line element in polar-areal form\n\\begin{align}\n\\label{eqn:ss-met-pa}\nds^2 = - \\alpha(r)^2 dt^2 + a(r)^2 dr^2 + r^2 d \\Omega^2\n\\end{align}\nwhere $\\alpha$ is referred as lapse function. Compare with above Schwarzschild solution, $\\alpha = 1/a$. \n\nNow consider a transformation of the Schwarzschild time t coordinate to a new generic coordinate $\\hat{t}$ according to\n\\begin{align}\nd\\hat{t} = dt + a^2 \\sqrt{1-\\frac{g}{a^2}} dr\n\\end{align}\nwhere $g(r)$ is arbitrary function. Substitute this into $ds^2 = -\\alpha^2 dt^2 + a^2 dr^2 + r^2 d\\Omega^2$ gives\n\\begin{align}\nds^2 &= - \\alpha^2 \\left (d\\hat{t} - a^2 \\sqrt{1-\\frac{g}{a^2}} dr\\right)^2 + a^2 dr^2 + r^2 d\\Omega^2 \\nonumber \\\\\n&= - \\alpha^2 d \\hat{t}^2 + 2 \\sqrt{1-\\frac{g}{a^2}} d\\hat{t} dr + g dr^2 + r^2 d \\Omega^2\n\\end{align}\nCompare this with usual 3+1 framework\n\\begin{align}\nds^2 = - \\alpha^2 d \\hat{t}^2 + \\gamma_{ij} (dx^i + \\beta^i d\\hat{t}\\,)(dx^j + \\beta^j d\\hat{t}\\,)\n\\end{align}\nand so into the lapse $\\alpha = 1/\\sqrt{g}$, the shift $\\beta_i = (\\sqrt{1-g/a^2},0,0)$ or $\\beta^i = \\gamma^{ij} \\beta_j$ and the spatial metric of the constant $\\hat{t}$ hypersurface $\\gamma_{ij} = diag(g,r^2,r^2\\sin^2 \\theta)$. \n\nIf we choose $\\alpha = \\sqrt{1-2M/r} = 1/a$ and $g = 1+2M/r$ like in previous (which we will use this), we get\n\\begin{align}\nds^2 = - \\left(1 - \\frac{2M}{r} \\right) d \\hat{t}^2 + \\frac{4M}{r} d \\hat{t} dr + \\left(1+\\frac{2M}{r} \\right) dr^2 + r^2 d\\Omega^2\n\\end{align}\nwhich is Schwarzschild in Kerr-Schild coordinate (or Eddington-Finkelstein coordinate). And correspondingly, $\\alpha = \\sqrt{r/(r+2M)}$, $\\beta_i = (2M/r,0,0)$, and $\\gamma_{ij} = diag(1+2M/r,r^2,r^2\\sin^2 \\theta)$ which are same as above.\n\nAs you can see here, the KS (or EF) form of the metric represents an analytic expansion of the Schwarzschild solution from the region $2M < r< \\infty$ to  $0<r<\\infty$. Thus, we apply this coordinate transformation for our equations.\n\nIt is good to rewrite the metric into usual $3+1$ variable form i.e. keep it geometric variables (should be careful of confusion) with considering time dependent case (This is almost same as Marsa and Choptuik\\apost s paper). Here, we use $t$ for time coordinate that we used above.\n\\begin{align}\n\\label{eqn:gen-sph-met}\nds^2 = (-\\alpha^2 + a^2 \\beta^2) dt^2 + 2a^2 \\beta dt dr + a^2 dr^2 + r^2 b^2 d \\Omega^2\n\\end{align}\nwhere $\\alpha$, $a$, $b$, and $\\beta$ are functions of $r$ and $t$, and $d\\Omega^2$ is the metric of unit sphere. From this, we can calculate non-vanishing components of connection coefficients and Ricci tensors for $i,j$, and $k$ (spatial indices)\n\\begin{align}\n&\\Gamma\\indices{^r_{rr}} = \\frac{\\partial_r a}{a}, \\,\\,\\,\\,\\,\\,\\,\\, \\Gamma\\indices{^r_{\\theta \\theta}} = - \\frac{rb \\partial_r (rb)}{a^2}, \\,\\,\\,\\,\\,\\,\\,\\, \\Gamma\\indices{^\\theta_{r \\theta}} = \\frac{\\partial_r (rb)}{rb} \\nonumber  \\\\\n&\\Gamma\\indices{^r_{\\varphi \\varphi}} = -\\sin^2 \\theta \\frac{rb \\partial_r (rb)}{a^2}, \\,\\,\\,\\,\\,\\,\\,\\, \\Gamma\\indices{^\\varphi_{r \\varphi}} = \\Gamma\\indices{^\\theta_{r \\theta}} \\nonumber \\\\\n&\\Gamma\\indices{^\\theta_{\\varphi \\varphi}} = -\\sin \\theta \\cos \\theta, \\,\\,\\,\\,\\,\\,\\,\\, \\Gamma\\indices{^\\varphi_{\\varphi \\theta}} = -\\cot \\theta \\nonumber \n\\end{align}\n\\begin{align}\nR\\indices{^r_r} &= -\\frac{2}{arb} \\partial_r \\left(\\frac{\\partial_r (rb)}{a} \\right) \\\\\nR\\indices{^\\theta_\\theta} &= \\frac{1}{ar^2b^2} \\left[a-\\partial_r \\left(\\frac{rb \\partial_r (rb)}{a} \\right) \\right] \\\\\n\\end{align}\n\n%In terms of horizon penetrating coordinate, we can generalize it in 3+1 form\n%\\begin{align}\n%\\label{eqn:gen-sph-met}\n%ds^2 = (-\\alpha^2 + a^2 \\beta^2) dt^2 + 2a^2 \\beta dt dr + a^2 dr^2 + r^2 b^2 d \\Omega^2\n%\\end{align}\n%where $\\alpha$, $a$, $b$, and $\\beta$ are functions of $r$ and $t$, and $d\\Omega^2$ is the metric of unit sphere. This is nothing but ingoing Eddington-Finkelstein coordinate system (IEF). Consider Schwarzschild again in IEF\n%\\begin{align}\n%ds^2 = - \\left( 1- \\frac{2M}{r} \\right) dV^2 + 2 dV dr + r^2 d \\Omega^2\n%\\end{align}\n%Define a timelike coordinate $t = V-r$ then metric becomes\n%\\begin{align}\n%ds^2 = - \\left( 1- \\frac{2M}{r} \\right) dt^2 + \\frac{4M}{r} dt dr +  \\left( 1+ \\frac{2M}{r} \\right) dr^2 + r^2 d \\Omega^2\n%\\end{align}\n%Compare this with Eqn.~\\ref{eqn:gen-sph-met}, various following metric components can be found\n%\\begin{align}\n%\\alpha &= \\sqrt{\\frac{r}{r+2M}} \\\\\n%\\beta &=\\frac{2M}{r+2M} \\\\\n%a &=\\sqrt{\\frac{r+2M}{r}}\n%\\end{align}\n%and so on. Note that we can also fix the spatial degree of coordinate freedom by introducing a shifting areal coordinate $R \\equiv  r + f(t)$ where $f(t)$ is some undetermined function.  \n\n\\section{Theoretical Model}\n\nHere, as a beginning set up, we first use the perfect fluid approximation for the matted model. So the stress-energy tensor takes form\n\\begin{align}\n\\label{eqn:EMtPF}\nT_{ab} = (\\rho + P) u_a u_b +P g_{ab} \n\\end{align}\nwhere $u^a(r,t)$ is the 4-velocity of a given perfect element, $P(r,t)$ is the isotropic pressure, $\\rho(r,t) = \\rho_0(r,t) (1+\\epsilon(r,t))$ is the energy density, $\\rho_0 (r,t)$ is the rest-mass energy density, and $\\epsilon(r,t)$ is the specific internal energy.\n\nThe equations of motion for this case are derive from the local conservative equations for energy and baryon number such that\n\\begin{align}\n\\nabla_a T\\indices{^a_b} &= 0 \\\\\n\\nabla_a (\\rho_0 u^a) &= 0 \n\\end{align}\n\nWe are using HRSC so we would like to write this in terms of flux-conservative form such that\n\\begin{align}\n\\partial_t {\\bf U} + \\partial_i {\\bf F^i} = {\\bf \\Psi}\n\\end{align}\nwhere ${\\bf U}$, \n\\begin{align}\n{\\bf U} = \n\\begin{pmatrix}\n\\sqrt{\\gamma} W \\rho_0 \\\\\n\\sqrt{\\gamma} \\alpha T\\indices{^t_j} \\\\\n\\alpha^2 \\sqrt{\\gamma} T^{tt} - \\sqrt{\\gamma} W \\rho_0\n\\end{pmatrix}\n\\end{align}\n\nand ${\\bf F^i}$\n\\begin{align}\n{\\bf F^i} = \n\\begin{pmatrix}\n\\sqrt{\\gamma} W \\rho_0 v^i \\\\\n\\sqrt{\\gamma} \\alpha T\\indices{^i_j} \\\\\n\\alpha^2 \\sqrt{\\gamma} T^{ti} - \\sqrt{\\gamma} W \\rho_0 v^i\n\\end{pmatrix}\n\\end{align}\n\nand ${\\bf \\psi}$\n\\begin{align}\n{\\bf \\Psi} = \n\\begin{pmatrix}\n0\\\\\n\\frac{1}{2}\\sqrt{\\gamma} \\alpha T\\indices{^{ab}}g_{ab,j} \\\\\n\\alpha^2 \\sqrt{\\gamma} (T^{at} \\partial_a \\alpha - \\Gamma\\indices{^0_{ab}} T^{ab} \\alpha )\n\\end{pmatrix}\n\\end{align}\nwhere $W$ is Lorentz factor such that $W = \\alpha u^t$ and $v^i = u^i/u^t$. Under our choice of system, $u^a = (u^t, u^r, 0, 0)$ so we can reduce\n\\begin{align}\n\\partial_t ( r^2 a b W \\rho_0) + \\partial_r (r^2 a b W \\rho_0 v^r) &= 0 \\\\\n\\partial_t (r^2 a b \\alpha T\\indices{^t_r}) + \\partial_r ( r^2 a b \\alpha T\\indices{^r_r}) &= \\frac{1}{2} r^2 a b T^{ab} g_{ab,r} \\\\\n\\partial_t ( \\alpha^2 r^2 a b T^{tt} - r^2 a b W \\rho_0 ) + \\partial_r(\\alpha^2 r^2 a b T^{tr} - r^2 a b W \\rho_0 v^r) &= \\alpha r^2 ab (T^{at} \\partial_a \\alpha - \\Gamma\\indices{^0_{ab}} T^{ab} \\alpha )\n\\end{align}\n\n\nHere I omit $\\sin$ term in the metric determinant because it will be cancelled out anyway\n\nIt is useful to define variables like below\n\\begin{align}\nD &= \\rho_0 ab W  \\\\\nE &= \\rho_0 h  W^2 -P \\\\\nS &= \\rho_0 h W^2 v\\\\\n\\tau &= E-D\n\\end{align}\nAnd nonzero components of $T^{ab}$ which we are using\n\\begin{align}\nT\\indices{^t_t} &= -E \\\\\nT\\indices{^t_r} &= \\frac{ab}{\\alpha} S \\\\\nT\\indices{^r_r} &=Sv+P\\\\\nT\\indices{^\\theta_\\theta}&=T\\indices{^\\varphi_\\varphi}=P\n\\end{align}\nwhere we define fluid velocity in Eulerian observer\n\\begin{align}\nv = \\frac{ab}{\\alpha} v^r = \\frac{ab u^r}{\\alpha u^t}\n\\end{align}\nthen also $W=1 / \\sqrt{1-v^2}$ and $h=1+\\epsilon+P/\\rho_0$ which is specific enthalpy.  Then we can reduce\n\\begin{align}\n\\partial_t ( r^2 D) + \\partial_r \\left(\\frac{r^2\\alpha}{ab}D v\\right) &= 0 \\\\\n\\partial_t (r^2 S) + \\partial_r \\left( \\frac{r^2 \\alpha}{ab}( E v + P)\\right) &= \\frac{1}{2} r^2 a b T^{ab} g_{ab,r} \\\\\n\\partial_t ( r^2\\tau) + \\partial_r\\left(\\frac{r^2\\alpha}{ab}(S - D v)\\right) &= \\alpha r^2 ab (T^{at} \\partial_a \\alpha - \\Gamma\\indices{^0_{ab}} T^{ab} \\alpha )\n\\end{align}\nor in the form\n\\begin{align}\n\\partial_t {\\bf u} + \\frac{1}{r^2} \\partial_r (X r^2 {\\bf f}) = \\psi\n\\end{align}\n\\begin{align}\n{\\bf u} = \n\\begin{pmatrix}\nD \\\\\nS \\\\\n\\tau\n\\end{pmatrix}, \\,\\,\\,\\,\n{\\bf f} = \n\\begin{pmatrix}\nDv \\\\\nEv + P \\\\\nS - Dv\n\\end{pmatrix}, \\,\\,\\,\\,\n{\\bf \\psi} = \n\\begin{pmatrix}\n0 \\\\\n\\frac{ab}{2} a b T^{ab} g_{ab,r} \\\\\n\\alpha ab (T^{at} \\partial_a \\alpha - \\Gamma\\indices{^0_{ab}} T^{ab} \\alpha )\n\\end{pmatrix}\n\\end{align}\nwhere $X= \\alpha / (ab)$ which is purely geometric factor. Some detail evaluation of RHS source terms are in \\href{https://github.com/hlim88/PBH-NS/tree/master/tools}{here}\n\n\n\n\n\n\n\\iffalse\nFirst, we define variables. \n%\\begin{align}\n%{\\bf q} = \\begin{bmatrix}\n%D\\\\\n%\\Pi\\\\\n%\\Phi\n%\\end{bmatrix} , \\,\\,\\,\\,\\,\\,\\,\n%{\\bf f} = \\begin{bmatrix}\n%Dv\\\\\n%v(\\Pi+P) + P\\\\\n%v(\\Phi + P) + P\n%\\end{bmatrix} , \\,\\,\\,\\,\\,\\,\\,\n%{\\bf \\psi} = \\begin{bmatrix}\n%0\\\\\n%\\Sigma\\\\\n%-\\Sigma\n%\\end{bmatrix} \n%\\end{align}\n%where $v$ is Eulerian velocity of fluid such that $ v = a u^r / (\\alpha u^t)$, $X=\\alpha/a$ is a purely geometric quantity and\n%\\begin{align}\n%D &= a \\rho_0 W\\\\\n%\\Pi &= E-D+S\\\\\n%\\Phi &=E-D-S\\\\\n%S &= \\rho_0 h W^2 v \\\\\n%E &=\\rho_0 h W^2 - P \n%\\end{align}\nwhere $W$ is Lorentz factor such that $W = \\alpha u^t=1/\\sqrt{1-v^2}$ with fluid velocity $v =(a u^r) / (\\alpha u^t)$ and $h=1+\\epsilon+P/\\rho_0$ which is specific enthalpy. In our case, $u^a = (u^t, u^r, 0, 0)$\n\nAnd nonzero components of $T^{ab}$ which we are using\n\\begin{align}\nT\\indices{^t_t} &= -E \\\\\nT\\indices{^t_r} &= \\frac{a}{\\alpha} S \\\\\nT\\indices{^r_r} &=Sv+P\\\\\nT\\indices{^\\theta_\\theta}&=T\\indices{^\\varphi_\\varphi}=P\n\\end{align}\n\nUsing these variables under the metric which we consider, $\\nabla_a (\\rho_0 u^a)=0$ (continuity equation) gives\n\\begin{align}\n\\partial_t (\\rho_0 u^t) + \\partial_r (\\rho_0 u^r) + \\Gamma\\indices{^t_{tt}}(\\rho_0 u^t) + \\Gamma\\indices{^t_{tr}}(\\rho_0 u^r) = 0\n\\end{align} \nIn terms of our variables, $\\rho_0 u^t = D/\\alpha$, $\\rho_0 u^r = D v /a$ so\n\\begin{align}\n\\partial_t (D/\\alpha) + \\partial_r (D/\\alpha) + \\Gamma\\indices{^t_{tt}}(D/\\alpha) + \\Gamma\\indices{^t_{tr}}(D v / a) = 0\n\\end{align} \n\n$\\nabla_a T\\indices{^a_b}=0$ gives\n\\begin{align}\n\\partial_a T\\indices{^a_b} + \\Gamma\\indices{^a_{ac}}T\\indices{^c_b} - \\Gamma\\indices{^c_{ab}}T\\indices{^a_c} = 0\n\\end{align}\nThe covariant $t$-component of above equation gives energy equation $T\\indices{^t_t} = - E$\n\\begin{align}\n&\\partial_t T\\indices{^t_t} + \\Gamma\\indices{^t_{tc}}T\\indices{^c_t} - \\Gamma\\indices{^c_{tt}}T\\indices{^t_c} = 0 \\nonumber \\\\\n&\\rightarrow \\partial_t T\\indices{^t_t} + \\Gamma\\indices{^t_{tt}}T\\indices{^t_t} +\\Gamma\\indices{^t_{tr}}T\\indices{^r_t}- \\Gamma\\indices{^t_{tt}}T\\indices{^t_t} - \\Gamma\\indices{^r_{tt}}T\\indices{^t_r} = 0 \\nonumber \\\\\n&\\rightarrow \\partial_t E + \\Gamma\\indices{^t_{tr}} \\frac{a^3}{\\alpha^3} S + \\Gamma\\indices{^r_{tt}} \\frac{a}{\\alpha} S = 0\n\\end{align}\nNext, consider the covariant $r$-component \n\\begin{align}\n&\\partial_t T\\indices{^t_r} + \\Gamma\\indices{^t_{tc}}T\\indices{^c_r} - \\Gamma\\indices{^c_{tr}}T\\indices{^t_c} = 0 \\nonumber \\\\\n&\\rightarrow \\partial_t T\\indices{^t_r} + \\Gamma\\indices{^t_{tt}}T\\indices{^t_r} +\\Gamma\\indices{^t_{tr}}T\\indices{^r_r}- \\Gamma\\indices{^t_{tr}}T\\indices{^t_t} - \\Gamma\\indices{^r_{tr}}T\\indices{^t_r} = 0 \\nonumber \\\\\n&\\rightarrow \\partial_t \\left(\\frac{a}{\\alpha} S\\right) + \\Gamma\\indices{^t_{tt}}(\\frac{a}{\\alpha} S)  +\\Gamma\\indices{^t_{tr}}(Sv+P) + \\Gamma\\indices{^t_{tr}}E - \\Gamma\\indices{^r_{tr}}\\frac{a}{\\alpha} S= 0 \\nonumber \n\\end{align}\nNon-vanishing connection coefficients are evaluated via Mathematica. You can find it \\href{https://github.com/hlim88/PBH-NS/tree/master/tools}{here}. After all simplifications, we have\n\\fi\n\n%Here, we use the fact that $\\sqrt{-g} = \\alpha \\sqrt{\\gamma}$ where $\\gamma = det(\\gamma_{ij})$ which came from above metric.\n\nNow consider the Einstein\\apost s equations. Define below quantities that are appearing in the 3+1 equations\n\\begin{align}\n\\rho_{hydro} &= n_a n_b T^{ab} = \\rho_0 h W^2 - P \\\\\nS_i^{hydro} &= - \\gamma_{ia} n_b T^{ab}  = \\rho_0 h W u_i \\\\\nS_{ij}^{hydro} &= \\gamma_{ia} \\gamma_{ib} T^{ab} = P \\gamma_{ij} + \\rho_0 h u_i u_j \\\\\nS_{hydro} &= \\gamma^{ij} S_{ij} = 3 P + \\rho_0 h (W^2 -1)\n\\end{align}\n\nThe Einstein\\apost s equations in the ADM form are\n\\begin{align}\n\\label{eqn:adm:gam}\n\\partial_t \\gamma_{ij} &= - 2 \\alpha K_{ij} + D_i \\beta_j + D_j \\beta_i \\\\ \n\\label{eqn:adm:K}\n\\partial_t K\\indices{^i_j} &= \\alpha (R\\indices{^i_j} + K K\\indices{^i_j}) - D^i D_j \\alpha - 8 \\pi \\alpha \\left(S\\indices{^i_j} - \\frac{1}{2} \\delta\\indices{^i_j} (S-\\rho)\\right) \\nonumber \\\\\n& + \\beta^k \\partial_k K\\indices{^i_j} + K\\indices{^i_k} \\partial_j \\beta^k - K\\indices{^k_j} \\partial_k \\beta^i\n\\end{align}\nwhere $D_i$ is covariant derivative on spatial hypersurface. Momentum and Hamiltonian constraints are\n\\begin{align}\nR+K^2 - K_{ij} K^{ij} = 16 \\pi \\rho \\\\\nD_i K\\indices{^i_j} - D_j K = 8 \\pi S_j\n\\end{align}\n\nSubstitute hydro source terms ($\\rho$, $S$ etc) from above then we have\n\\begin{align}\n\\partial_t K\\indices{^i_j} &= \\alpha (R\\indices{^i_j} + K K\\indices{^i_j}) - \\gamma^{ik} (\\partial_i \\partial_k \\alpha - \\Gamma\\indices{^l_{ik}} \\partial_l \\alpha) - 8 \\pi \\alpha \\left(\\frac{1}{2} \\delta\\indices{^i_j} (\\rho_0 h - 2 P) + \\rho_0 h u^i u_j \\right) \\nonumber \\\\\n& + \\beta^k \\partial_k K\\indices{^i_j} + K\\indices{^i_k} \\partial_j \\beta^k - K\\indices{^k_j} \\partial_k \\beta^i \\\\\n\\partial_t \\gamma_{ij} &= - 2 \\alpha K_{ij} + D_i \\beta_j + D_j \\beta_i \\\\ \n&R+K^2 - K_{ij} K^{ij} = 16 \\pi (\\rho_0 h W^2 -P)\\\\\n&D_i K\\indices{^i_j} - D_j K = 8 \\pi \\rho_0 h W u_j\n\\end{align}\n\nFrom our choice of metric/coordinate system, we calculated non-trivial connection coefficients and Ricci tensors. Also, metric form suggests that $\\beta^i = (\\beta^r,0,0)$, $K\\indices{^i_j} = diag(K\\indices{^r_r}, K\\indices{^\\theta_\\theta},K\\indices{^\\theta_\\theta})$. Using these facts, the evolution equations for geometric quantities are\n\\begin{align}\n\\partial_t a &= - \\alpha a K\\indices{^r_r} + \\partial_r (a \\beta^r) \\\\\n\\partial_t b &= - \\alpha b K\\indices{^\\theta_\\theta} + \\frac{\\beta^r}{r} \\partial_r (r \\beta^r) \\\\\n\\partial_t K\\indices{^r_r} &= \\beta^r \\partial_r K\\indices{^r_r} + \\alpha K\\indices{^r_r} K - \\frac{1}{a} \\partial_r \\left( \\frac{\\partial_r \\alpha}{a} \\right) - \\frac{2 \\alpha}{arb} \\partial_r \\left( \\frac{\\partial_r (rb)}{a} \\right) \\nonumber \\\\\n& - 4 \\pi \\alpha \\left[ (1+2 u^r u_r) \\rho_0 h - 2P \\right] \\\\\n\\partial_t K\\indices{^\\theta_\\theta} &= \\beta^r \\partial_r K\\indices{^\\theta_\\theta} + \\alpha K\\indices{^\\theta_\\theta} K - \\frac{\\alpha}{r^2 b^2} - \\frac{1}{ar^2b^2} \\partial_r \\left( \\frac{\\alpha r b \\partial_r (rb)}{a} \\right) \\nonumber \\\\\n& - 4 \\pi \\alpha (\\rho_0 h -2 P)\n\\end{align}\nFrom constraints\n\\begin{align}\n \\frac{1}{ar^2b^2} \\left[a-\\partial_r \\left(\\frac{rb \\partial_r (rb)}{a} \\right) \\right] -\\frac{2}{arb} \\partial_r \\left(\\frac{\\partial_r (rb)}{a} \\right) + 2K\\indices{^\\theta_\\theta}(K\\indices{^\\theta_\\theta}+2 K\\indices{^r_r}) &= 16 \\pi (\\rho_0 h W^2 -P) \\nonumber \\\\\n \\frac{\\partial_t (r b)}{rb} (K\\indices{^\\theta_\\theta} - K\\indices{^r_r}) - \\partial_r K\\indices{^\\theta_\\theta} &= 4 \\pi \\rho_0 h W u_r\n\\end{align}\n\n\nWe can apply different choice of slicing (i.e. gauge choice) to reduce/determine above system. Possible (or simple) choices would be maximal or polar slicing. \n\n\\subsection{Choice of Gauge}\n\n\\subsubsection{Maximal Slicing}\nFirst, we consider maximal slicing i.e. $K=\\partial_t K = 0$ then \n\n\\begin{align}\n\\partial_t a &= - \\alpha a K\\indices{^r_r} + \\partial_r (a \\beta^r) \\\\\n\\partial_t b &=  \\frac{\\alpha b}{2} K\\indices{^r_r} + \\frac{\\beta^r}{r} \\partial_r (r \\beta^r) \\\\\n\\partial_t K\\indices{^r_r} &= \\beta^r \\partial_r K\\indices{^r_r}  - \\frac{1}{a} \\partial_r \\left( \\frac{\\partial_r \\alpha}{a} \\right) - \\frac{2 \\alpha}{arb} \\partial_r \\left( \\frac{\\partial_r (rb)}{a} \\right) \n-  \\frac{2 \\alpha}{r^2 b^2} - \\frac{2}{ar^2b^2} \\partial_r \\left( \\frac{\\alpha r b \\partial_r (rb)}{a} \\right)  \\nonumber \\\\\n& - 8 \\pi \\alpha \\left[ (2+2 u^r u_r) \\rho_0 h - 4P \\right] \n\\end{align}\nFrom constraints\n\\begin{align}\n \\frac{1}{ar^2b^2} \\left[a-\\partial_r \\left(\\frac{rb \\partial_r (rb)}{a} \\right) \\right] -\\frac{2}{arb} \\partial_r \\left(\\frac{\\partial_r (rb)}{a} \\right) - \\frac{3}{2}(K\\indices{^r_r})^2 &= 16 \\pi (\\rho_0 h W^2 -P) \\nonumber \\\\\n  \\partial_r K\\indices{^r_r} -\\frac{3 \\partial_t (r b)}{rb}  K\\indices{^r_r} &= 8 \\pi \\rho_0 h W u_r\n\\end{align}\nFluid EOM parts are same as previous\n\nFor lapse, we use \n\\begin{align}\n\\partial_t K = - D^2 \\alpha + \\alpha (K^{ij}K_{ij} + 4 \\pi (\\rho + S))+ \\beta^i D_i K\n\\end{align}\nIn our choice of gauge, this can be reduced\n\\begin{align}\nD^2 \\alpha &= \\alpha ( K^{ij} K_{ij} + 4 \\pi (\\rho + S)) = \\alpha \\left( K^{ij} K_{ij} + 8 \\pi \\left[P + \\rho_0 h \\left(W^2 - \\frac{1}{2}  \\right)\\right]\\right) \\nonumber \\\\\n&= \\alpha \\left( 2(K\\indices{^r_r})^2 + 8 \\pi \\left[P + \\rho_0 h \\left(W^2 - \\frac{1}{2}  \\right)\\right]\\right)\n\\end{align}\nAlso, for shift, we use\n\\begin{align}\n\\partial_t \\ln \\sqrt{\\gamma} = - \\alpha K + D_i \\beta^i \n\\end{align}\nIn maximal slicing, this reduces\n\\begin{align}\nD_i \\beta^i = - \\partial_t \\ln \\sqrt{\\gamma}  \n\\end{align}\nor we can write \n\\begin{align}\n\\partial_i \\beta^i = - \\partial_t \\sqrt{\\gamma}  \n\\end{align}\nThis shows that the proper volume element $\\sqrt{\\gamma}$ satisfies a continuity equation in maximal slicing.\n\nIn terms of our metric choice and variable\n\\begin{align}\n\\partial_r \\beta^r = \\frac{b}{2b+\\beta^r} \\left[\\frac{\\alpha K\\indices{^r_r}}{2} - \\frac{(\\beta^r)^2 b}{r}- \\frac{\\partial_r a}{a} \\beta^r \\right]\n\\end{align}\n\n\\subsection{Spherical-G-BSSN with 1+log and $\\Gamma$ driver}\nAnother possible way to describe this system is writing the equations in terms of BSSN form. This makes every equations\nin hyperbolic form which do not require to solve elliptic equations.\n\nWe follow the usual treatment in BSSN variable. Also, we still keep HPC-SS metric which is described previous section\n\nLet \\apost s consider usual BSSN form (make conformal transformation $\\hat{\\gamma} \\rightarrow e^{4\\phi} \\gamma$ i.e.\n\\begin{align}\n\\phi = \\frac{1}{12} \\ln(\\gamma / \\hat{\\gamma})\n\\end{align}\nIt is common to define a new variable $\\chi = e^{-2 \\phi}$ instead of using the conformal factor $\\phi$. (Perhaps, we get similar result..) Evolution equation for $\\chi$ is\n\\begin{align}\n\\partial_t \\chi = \\beta^r \\partial_r \\chi - \\frac{1}{3} \\chi \\left[ \\alpha K - \\partial_r \\beta^r - \\beta^r \\left(\\frac{\\partial_r (a b^2)}{2 a b^2} + \\frac{2}{r}\\right) \\right]\n\\end{align}\nWe also use traceless part of the extrinsic curvature $\\hat{A}_{ij}$. In SS, we have $\\hat{A}^r_r$ and $\\hat{A}^\\theta_\\theta$. Note that as $\\hat{A}_{ij}$ is traceless $\\hat{A}^r_r+2\\hat{A}^\\theta_\\theta=0$. Evolution equations for spatial metric $\\gamma$ give\n\\begin{align}\n\\partial_t a &= \\beta^r \\partial_r a + 2 a \\partial_r \\beta^r - \\frac{2a}{3}\\left[ \\partial_r \\beta^r +\\beta^r \\left(\\frac{\\partial_r (a b^2)}{2 a b^2} + \\frac{2}{r}\\right)\\right] -2 \\alpha a \\hat{A}^r_r \\\\\n\\partial_t b &= \\beta^r \\partial_r b + 2 b \\frac{\\beta^r}{r} - \\frac{2b}{3} \\left[\\partial_r \\beta^r + \\beta^r \\left(\\frac{\\partial_r (a b^2)}{2 a b^2} + \\frac{2}{r}\\right)\\right] + \\alpha b \\hat{A}^r_r\n\\end{align}\nEvolution equation for trace of extrinsic curvature $K$ is\n\\begin{align}\n\\partial_t K &= \\beta^r \\partial_r K - \\frac{\\chi^2}{\\alpha} \\left[\\partial_r^2 \\alpha - \\partial_r \\left(\\frac{\\partial_r a}{2a} - \\frac{\\partial_r b}{b} +\\frac{\\partial_r \\chi}{\\chi} - \\frac{2}{r} \\right) \\right] \\nonumber \\\\\n&+ \\alpha \\left(\\frac{3}{2} (\\hat{A}^r_r)^2 + \\frac{1}{3} K^2 \\right) + 4 \\pi \\alpha (\\rho + S^r_r + S^\\theta_\\theta)\n\\end{align}\nWe have only one independent component of traceless part of the extrinsic curvature. Evolution equations for that is\n\\begin{align}\n\\partial_t \\hat{A}^r_r &= \\beta^r \\partial_r \\hat{A}^r_r - \\frac{\\chi^2}{\\alpha}\\left( \\left[\\partial_r^2 \\alpha - \\partial_r \\left(\\frac{\\partial_r a}{2a} - \\frac{\\partial_r \\chi}{\\chi} \\right) \\right] -\\frac{1}{3} \\left[\\partial_r^2 \\alpha - \\partial_r \\left(\\frac{\\partial_r a}{2a} - \\frac{\\partial_r b}{b} +\\frac{\\partial_r \\chi}{\\chi} - \\frac{2}{r} \\right) \\right] \\right)\\nonumber \\\\\n&+\\frac{\\alpha}{3}(2 R\\indices{^r_r} - R\\indices{^\\theta_\\theta}) + \\alpha K \\hat{A}^r_r - 16\\pi \\alpha ( S^r_r - S^\\theta_\\theta)\n\\end{align}\nFinally, we obtain the evolution equation for $\\hat{\\Delta}^r$ which is the radial component of conformal connection function which is defined by $\\hat{\\Delta}^i = \\hat{\\gamma}^{mn}( \\hat{\\Gamma}\\indices{^i_{mn}} - \\mathring{\\Gamma}\\indices{^i_{mn}})$ where $\\mathring{\\Gamma}\\indices{^i_{mn}}$ is defined by $\\mathring{\\gamma}\\indices{_{ij}}$ which is flat metric in spherical coordinate i.e. $\\mathring{\\gamma}=r^2 \\sin^2 \\theta$\n\\begin{align}\n\\partial_t \\hat{\\Delta}^r &= \\beta^r \\partial_r \\hat{\\Delta}^r - \\hat{\\Delta}^r \\partial_r \\beta^r + \\frac{1}{a} \\partial^2 \\beta^r + \\frac{2}{b} \\partial_r \\left(\\frac{\\beta^r}{r} \\right) \\nonumber \\\\\n&+\\frac{1}{3}\\left[\\frac{1}{a} \\left\\{\\partial_r^2 \\beta^r + \\partial_r \\beta^r  \\left(\\frac{\\partial_r (a b^2)}{2 a b^2} + \\frac{2}{r}\\right) + \\beta^r \\partial_r \\left(\\frac{\\partial_r (a b^2)}{2 a b^2} + \\frac{2}{r}\\right)\\right\\} + 2 \\hat{\\Delta}^r \\left\\{\\partial_r \\beta^r +\\beta^r \\left(\\frac{\\partial_r (a b^2)}{2 a b^2} + \\frac{2}{r}\\right)\\right\\}\\right]  \\nonumber \\\\\n&-\\frac{2}{a} (\\hat{A}^r_r \\partial_r \\alpha + \\alpha \\partial_r \\hat{A}^r_r) + 2 \\alpha \\left(\\hat{A}^r_r \\hat{\\Delta}^r + \\frac{3}{rb} \\hat{A}^r_r \\right) \\nonumber \\\\\n&+ \\frac{2\\alpha}{a} \\left[ \\partial_r \\hat{A}^r_r - \\frac{2}{3} \\partial_r K - \\frac{3\\hat{A}^r_r}{\\chi} \\partial_r \\chi + \\frac{3}{2} \\hat{A}^r_r \\left(\\frac{2}{r} + \\frac{\\partial_r b}{b} \\right) - 8 \\pi S_r \\right]\n\\end{align}\nWe also evaluate Hamiltonian and momentum constraints to monitor our numerical evolutions\n\\begin{align}\n\\mathcal{H} &= -\\frac{2}{arb} \\partial_r \\left(\\frac{\\partial_r (rb)}{a} \\right) + \\frac{1}{ar^2b^2} \\left[a-\\partial_r \\left(\\frac{rb \\partial_r (rb)}{a} \\right) \\right] - \\frac{3}{2} (\\hat{A}^r_r)^2 + \\frac{2}{3} K^2 - 16 \\pi \\rho = 0 \\\\\n\\mathcal{M} &= \\partial_r \\hat{A}^r_r - \\frac{2}{3} \\partial_r K - \\frac{3 \\hat{A}^r_r}{2\\chi}\\partial_r \\chi + \\frac{2}{3} \\hat{A}^r_r \\left(\\frac{2}{r} + \\frac{\\partial_r b}{b} \\right) - 8 \\pi S_r = 0\n\\end{align}\n\\subsubsection{Gauge Choice}\nIn addition to SS-GBSSN variables, we still have two more variables that need to be chosen. Here, we use 1+log condition for lapse and Gamma driver condition for shift.\nThe form of this slicing condition is\n\\begin{align}\n\\partial_t \\alpha = -2\\alpha K\n\\end{align}\nWe have only radial component for shift vector so Gamma driver condition is\n\\begin{align}\n\\partial_t B^r &= \\frac{3}{4} \\partial_t \\hat{\\Delta}^r \\\\\n\\partial_t \\beta^r &= B^r\n\\end{align}\nWe introduce an auxiliary variable $B^r$ to reduce derivative order of time from second to first\n\n%Another possible choice to set the lapse is demanding that the ingoing combination of tangent vectors $\\vec{\\partial}_t - \\vec{\\partial}_r$ be null. This gives a condition on the metric : $g_{tt} - 2 g_{tr} + g_{rr}=0$. This gives $\\alpha = a(1-\\beta)$\n\n\n%Further, a sufficient set of Einstein\\apost s equations for geometric variable $\\alpha$ and $a$ are given by the nontrivial component of momentum constraint\n%\\begin{align}\n%\\partial_t a = - 4 \\pi r \\alpha a^2 S\n%\\end{align}\n%and by the polar slicing condition which follows from the demand that metric have the spherically symmetric form for all time\n%\\begin{align}\n%\\partial_r (\\ln \\alpha) = a^2 \\left[4 \\pi r (Sv+P) + \\frac{m}{r^2} \\right]\n%\\end{align}\n%and from Hamiltonian constraint\n%\\begin{align}\n%\\partial_r a = a^3 \\left(4 \\pi r E - \\frac{m}{r^2} \\right)\n%\\end{align}\n\n%To solve these sets of equations on Schwarzschild background in KS, we consider following coordinate transformation in time \n%\\begin{align}\n%\\hat{t} = t + 2 M \\ln | \\frac{r}{2M} - 1 | + k\n%\\end{align}\n%where $k$ is arbitrary constant. So for arbitrary function $F$\n%\\begin{align}\n%\\frac{\\partial F}{\\partial t} = \\frac{\\partial \\hat{t}}{\\partial t} \\frac{\\partial F}{\\partial \\hat{t}} = \\left(1+\\frac{2MXv}{r-2M} \\right) \\frac{\\partial F}{\\partial \\hat{t}} = \\left(1+\\frac{2Mv}{r} \\right) \\frac{\\partial F}{\\partial \\hat{t}}\n%\\end{align}\n%We apply this rule to above equations for HPC\n\n\n%From the metric,\n%\\begin{align}\n%ds^2 = - \\alpha^2 dt^2 + a^2 dr^2 + r^2 d \\Omega^2\n%\\end{align}\n%Identify $a = \\sqrt{r/(r-2M)}$ which is usual Schwarzschild in Schwarzschild coordinate then Einstein\\apost s equations and energy conservation imply the TOV system of ODEs\n%\\begin{align}\n%\\frac{d m}{dr} &= 4 \\pi r^2 \\rho \\\\\n%\\frac{d P}{dr} &= - (\\rho + P) \\frac{M + 4 \\pi r^3 P}{r(r-2M)} \\\\\n%\\frac{d (\\ln \\alpha)}{d r} &= \\frac{M+4\\pi r^3 P}{r(r-2M)}\n%\\end{align}\n%Again $\\rho = \\rho_0 ( 1+ \\epsilon)$. Now consider this system in Kerr-Schild coordinate which provides horizon penetrating. Metric becomes from previous section\n%\\begin{align}\n%ds^2 = (- \\alpha^2 + a^2 \\beta^2) dt^2 + 2 a^2 \\beta dt dr + a^2 dr^2 + r^2 d \\Omega^2\n%\\end{align}\n%In this case, $\\alpha$, $a$, and $\\beta$ are function of $r$. Also we define \n\n\n\n%obtaining TOV equation. Here, we still have spherical symmetry and staticity so\n%\\begin{align}\n%\\frac{d}{dr} ( \\sqrt{-g} \\rho_0 u^1) &= 0 \\nonumber \\\\\n%\\frac{d}{dr} ( \\sqrt{-g} T^1_0 ) &= 0 \\nonumber \n%\\end{align}\n%where $T_{ab}=(\\rho + P) u_a u_b + Pg_{ab}$ or $T_{ab}=\\rho_0 h u_a u_b + Pg_{ab}$ where $h = 1+\\epsilon+p/\\rho_0$ which is specific entalpy\n\n\\subsection{Initial Data}\nOur initial NS model is approximated by solution of TOV. After the initial data calculation, an in-going velocity profile is added to drive the star to collapse. We follow the way is described in (https://arxiv.org/pdf/gr-qc/0107045.pdf). First, specifying the coordinate velocity\n\\begin{align}\nU \\equiv \\frac{dr}{dt} = \\frac{u^r}{u^r}\n\\end{align}\nof the star. In general, the profile take the algebraic form $U_g(x) = A_0 (x^3 - B_0 x)$ where $x \\equiv  r/R_{star}$ and $R_{star}$ is the radius of the TOV solution.\n\nIn this work, we set two profiles\n\\begin{align}\nU(x) =\n\\begin{cases}\nU_1(x) = U_{crit} ( x^3 - 3x) & x < x_{tlv} \\\\\n\\\\\nU_2(x) = 0 & \\textrm{otherwise} \\\\\n\\end{cases}\n\\end{align}\n$U_{crit}$ is the amplitude that occurs critical collapse, and $x_{tlv}$ the region that forms black hole. \n\nOur interest is interaction between BH inside of NS we set $x_{tlv}$ is small value such as 1\\% of size of star i.e. $x_{tlv} = 0.01$ since $x$ is normalized radius by star radius ($x_{tlv}$ must be smaller than $1$).\n\n%\\subsection{Analytic Case}\n\n%For code test and validation, we use well-known Michel problem\n\n\\end{document}\n", "meta": {"hexsha": "11ec75f37d71640d75313f984793bbddc10a0e81", "size": 29563, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Notes/PBH_NS-Notes.tex", "max_stars_repo_name": "hlim88/PBH-NS", "max_stars_repo_head_hexsha": "2bfee6270b4a78a9dcdd43cd1be0e128792c7bce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Notes/PBH_NS-Notes.tex", "max_issues_repo_name": "hlim88/PBH-NS", "max_issues_repo_head_hexsha": "2bfee6270b4a78a9dcdd43cd1be0e128792c7bce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Notes/PBH_NS-Notes.tex", "max_forks_repo_name": "hlim88/PBH-NS", "max_forks_repo_head_hexsha": "2bfee6270b4a78a9dcdd43cd1be0e128792c7bce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.4593128391, "max_line_length": 519, "alphanum_fraction": 0.6593715117, "num_tokens": 11152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.30287562875697027}}
{"text": "\\documentclass{article}\n\n\\usepackage{a4wide}\n\\usepackage{amsmath}\n\\usepackage{tikz}\n\\usepackage{tabularx}\n\\usepackage{fixltx2e}\n\\usepackage{color}\n\\usepackage{hyperref}\n\n\\title{Making a Cellular Potts Model of Collective Migration}\n\\author{Inge Wortel \\and Johannes Textor}\n\\date{May 1st, 2020}\n\n\\begin{document}\n\n\\maketitle\n\nIn this exercise, you are going to use the Cellular Potts modeling framework to create cells \\emph{in silico}. You will first learn how to use the model's many parameters to create cells of realistic shapes and motility patterns. Then you will go a step further and model several migrating cells that interact with each other.\n\n\\section*{Learning Goals}\n\\begin{itemize}\n\\item Understand how the different parameters of a Cellular Potts Model (CPM) interact with each other, and how this influences cell behavior. \n\\item Realize that it can be difficult to tune the parameters of a CPM.\n\\item Apply this knowledge to create different modes of cell migration in the CPM, and explain how this helps understand those migration modes.\n\\item Apply the CPM to investigate the dynamics of collective cell migration \\emph{in silico}.\n\\end{itemize}\n\nPlease go to {\\color{blue}\\href{http://computational-immunology.org/cpm/collective.html}{computational-immunology.org/cpm/collective.html}}. This is an implementation of a special version of the Cellular Potts Model in which cells can migrate \\cite{niculescu_crawling_2015}.\nNote that \\emph{this web page does not work properly in Internet Explorer}. It does work in either Firefox, Chrome, or Safari -- so we recommend using any of those browsers for this exercise.\n\n\\section*{Notes on the CPM} \n\n%At {\\color{blue}\\href{http://computational-immunology.org/talks/2018-10-02-nijmegen/}{computational-immunology.org/talks/2018-10-02-nijmegen/}}, you can check back the lecture slides on the CPM.\n\nRemember that in a CPM, copy attempts have a higher chance of succeeding if they lower the total energy $H$ of the system. In other words, $\\Delta H = H_\\text{after copy} - H_\\text{before copy}$ should be negative to guarantee that the copy attempt will work. Copy attempts with positive $\\Delta H$ can still succeed, but do so with a lower probability that depends on the temperature of the system. In general, the formula for $\\Delta H$ of a CPM looks something like this:\n\n\\begin{equation}\n\t\\Delta H = \\Delta H_\\text{adhesion} + \\Delta H_\\text{Volume} + \\Delta H_\\text{...}  + ...\n\\end{equation}\n\nThus, we build up $\\Delta H$ from all the different energetic factors we want the cell to consider -- and we can always add stuff to make the model more complex. But what parameters do we need to tune to get realistic cells? In the following exercises, you will get a feel for how you can model cell behavior with a CPM by tuning the parameters that control the energy $\\Delta H$. \n\n\\section*{Exercises} \n\n\\subsection*{A very basic CPM}\n\nIn this exercise, we will first examine a very basic CPM in which cells do not (yet) migrate.\nMake sure that the field is empty (hit refresh or \"remove all cells\"), and that the parameters\nhave the following values:\n\n\\begin{center}\n\\setlength{\\tabcolsep}{3pt}\n\\small\n\t\\begin{tabular}{l l l l l l l l l l }\n\t\tAdhesion\\textsubscript{cell-matrix} & Adhesion\\textsubscript{cell-cell} &\n\t\t\tVolume & $\\lambda$\\textsubscript{Volume} & \n\t\t\tPerimeter & $\\lambda$\\textsubscript{P} &\n\t\t\tMax\\textsubscript{Act} & $\\lambda$\\textsubscript{Act} &\n\t\t\tT & Framerate \\\\ \\hline\n\t\t20 & 0 & 500 & 50 & 340 & 0 & 0 & 0 & 20 & 1 \\\\\n\t\\end{tabular}\n\n\\end{center}\n\nWe will now investigate how the basic CPM parameters -- controlling adhesion, cell volume, and cell perimeter (circumference) -- influence behavior (this means you can ignore the $\\lambda$\\textsubscript{Act} and Max\\textsubscript{Act} parameters for now). This exercise is meant mostly to give you an idea of what the CPM parameters do, and the questions are to guide your thinking -- so you don't have to write everything down. Try to spend no longer than 30-40 minutes on this exercise before continuing to the next.\n\n\\begin{enumerate}\n\t\\item Make sure all the parameters are set as in the table above, click \"seed cell\" and then \"start\". What do you see? What kind of motion does this cell have?\n\t\\item Now set the Adhesion\\textsubscript{cell-matrix} to 0. What happens to the cell? Why do you think that happens? (Hint: look back to the description of the CPM and adhesion energy in the lecture...) Also try a negative value for Adhesion\\textsubscript{cell-matrix}. What is the meaning of positive or negative adhesion values here?\n\t\\item \\textit{(Optional)} Instead of setting the Adhesion\\textsubscript{cell-matrix} back to 20, try setting the Adhesion\\textsubscript{cell-cell} to -20 while having the Adhesion \\textsubscript{cell-matrix} still at 0. Does that have the effect that you expected? Why/why not do you think that is? Hint: try drawing a grid like you saw in the lecture for a copy attempt you are interested in. Do the two adhesion energies change in the same way for that copy attempt?\n\t\\item Return to the parameters in the table above. With these parameters, the cell is given an ideal volume (500 pixels), and a \"level of importance\" of this volume for the energy ($\\lambda$\\textsubscript{Volume}). Try making the cell bigger or smaller (what parameter should you change?). How can you make the volume unimportant for the energy -- and what happens then? What happens when you make $\\lambda$\\textsubscript{Volume} really large (say, 1000)?\n\t\\item So far, we have considered $\\Delta H$ with only terms for adhesion energy and cell volume. We will now investigate the effect of the cell perimeter (circumference). The cell already has a target perimeter (340), but this is currently not taken into account in the calculation of $\\Delta H$. For that, we need to make $\\lambda$\\textsubscript{P} non-zero. Try setting it to 2. What happens to the cell? Try making the cell \"membrane\" more or less ruffled. How would you do that?\n\\item Set the perimeter to 340 and $\\lambda$\\textsubscript{P} to 2. Now change the Adhesion\\textsubscript{cell-matrix} to 0 again. Does this have the same effect as it did in question 2? Why do you think that is?\n\\item \\textit{(Optional)} Play around with the volume and perimeter parameters for a while (using the adhesion parameters from the table, or try your own). How can you change the cell? Can you change the parameters independently of each other? And what happens if you change the temperature?\n\\end{enumerate} \n\n\n\\subsection*{Cell migration: the Act model}\n\nWe will now investigate the Act model, an extension of the CPM that allows the cells to migrate \\cite{niculescu_crawling_2015}. This model adds an extra term to the system energy, so that:\n\n\\begin{equation}\n\t\\Delta H = \\Delta H_\\text{adhesion} + \\Delta H_\\text{Volume} + \\Delta H_\\text{Perimeter} + \\Delta H_\\text{Act}\n\\end{equation}\n\nIn this model, pixels that were recently added to the cell remember their recent \"protrusive activity\". This makes them more likely to protrude again. This positive feedback is controlled by the energy term $\\Delta H_\\text{Act}$, which is negative (favourable!) when a recently active pixel tries to copy itself into a less active pixel. The Act model has two extra parameters: $\\lambda$\\textsubscript{Act}, which controls how important the positive feedback is relative to the other $\\Delta H$ energies, and Max\\textsubscript{Act}, which determines how long pixels \"remember\" that they were active. In this exercise, we will see what happens when we vary those two parameters of the model. In particular, we will see that we can reproduce two very different \"modes\" of migration: amoeboid and keratocyte-like (see lecture).\n\nBefore starting this exercise, please refresh the page and ensure that the parameters of the CPM are set as follows:\n\n\\begin{center}\n\\setlength{\\tabcolsep}{3pt}\n\\small\n\t\\begin{tabular}{l l l l l l l l l l }\n\t\tAdhesion\\textsubscript{cell-matrix} & Adhesion\\textsubscript{cell-cell} &\n\t\t\tVolume & $\\lambda$\\textsubscript{Volume} & \n\t\t\tPerimeter & $\\lambda$\\textsubscript{P} &\n\t\t\tMax\\textsubscript{Act} & $\\lambda$\\textsubscript{Act} &\n\t\t\tT & Framerate \\\\ \\hline\n\t\t20 & 0 & 500 & 50 & 340 & 2 & 20 & 0 & 20 & 1 \\\\\n\t\\end{tabular}\n\n\\end{center}\n\n\\begin{enumerate}\n\t\\item Seed a cell and click \"start\". You should now see colored pixels at the border of the cell, which indicate the \"activity\" that pixels remember (because we have set Max\\textsubscript{Act} to 20). Other than the color of the pixels, does the cell behave in a different way than with Max\\textsubscript{Act} = 0? Why/why not?\n\t\\item Set $\\lambda$\\textsubscript{Act} to 100. Would you describe this movement as random or persistent?\n\t\\item \\textit{(Optional)} What happens when you set $\\lambda$\\textsubscript{P} to 0 now? Why do you think that is? (Reset it to 2 before going to the next question)\n\t\\item What happens when you increase $\\lambda$\\textsubscript{Act} further? (Try steps of 100).\n\t\\item \\textit{(Optional)} If you increase $\\lambda$\\textsubscript{Act} to very high values (eg 1000), the cell is prone to breaking in pieces. Can you fix that by altering some other CPM parameter again? (Note: you may have to increase $\\lambda$\\textsubscript{Act} further when you have done this... Does that make sense to you?)\n\t\\item Reset $\\lambda$\\textsubscript{Act} to 0, change Max\\textsubscript{Act} to 80, and repeat questions 1,2, and 4 above. What do you see? \n\t\\item \\textit{(Optional)} If you have time, play around with different combinations of $\\lambda$\\textsubscript{Act} and Max\\textsubscript{Act}. Can you get a clue of what they are doing -- beyond the mathematical description given above?\n\t\\item \\textit{(Optional)} Try halving or doubling the cell's target volume. That won't work. What do you need to change to get the same behavior as before? What does that mean for your model (in other words: to what extent are your choices of parameters important for the behaviour you see? How worried should you be about getting parameters \"wrong\" and drawing the wrong conclusions?)? \n\t\\item The nice thing about computer models is that you know exactly which \"rules\" you put in, and therefore that those are the only rules that the cells will follow. However, the behavior that follows from those \"rules\" is not always obvious (that's why we run the simulation in the first place!). In fact, the most interesting computer models can sometimes produce behavior that you did not explicitly put in there. We call this \"emergent\" behavior. Can you think of an example of emergent behavior in the Act model? What does that tell you about migration in a living cell?\n\\end{enumerate} \n\n\n\\subsection*{Migration in a multicellular system}\n\nIn this last exercise, we will investigate what happens when there are many cells. Before starting, please refresh the page to clear the grid, and then ensure that the parameters have the following values:\n\n\\begin{center}\n\\setlength{\\tabcolsep}{3pt}\n\\small\n\t\\begin{tabular}{l l l l l l l l l l }\n\t\tAdhesion\\textsubscript{cell-matrix} & Adhesion\\textsubscript{cell-cell} &\n\t\t\tVolume & $\\lambda$\\textsubscript{Volume} & \n\t\t\tPerimeter & $\\lambda$\\textsubscript{P} &\n\t\t\tMax\\textsubscript{Act} & $\\lambda$\\textsubscript{Act} &\n\t\t\tT & Framerate \\\\ \\hline\n\t\t20 & 0 & 200 & 50 & 180 & 2 & 20 & 200 & 20 & 5 \\\\\n\t\\end{tabular}\n\n\\end{center}\n\nNote that the framerate is not actually a parameter of the model, but it specifies how often the program draws the updated grid (eg framerate of 5 means visualize only 1 in every 5 \"frames\" of the movie). Setting it to 5 will speed up the animation.\n\n\\begin{enumerate}\n\t\\item To seed many cells at once, click \"+100 cells\" (this will take a while...). What do you see?\n\t\\item Now, refresh the page, reset the parameters, increase Max\\textsubscript{Act} to 80, and wait for a while to let the cells adjust. What happens? How is this different from what you saw with Max\\textsubscript{Act} = 20?\n\t\\item Try other values of Max\\textsubscript{Act} in between 20 and 80. What happens as you gradually increase Max\\textsubscript{Act}?\n\t\\item \\textit{(Optional)} What happens when you set Adhesion\\textsubscript{cell-cell} to a negative value?\n\t\\item To what extent are your conclusions dependent on the density of cells on your grid? How could you test that?\n\\end{enumerate}\n\n\n\n\\bibliographystyle{abbrv}\n\\bibliography{ref.bib}\n\n\n\\end{document}\n\n\n", "meta": {"hexsha": "e3531ca058c00311ebce19e03b0caa046da161c6", "size": 12391, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "applications/ApplicationS1-teaching-exercise.tex", "max_stars_repo_name": "ingewortel/artistoo-supplements", "max_stars_repo_head_hexsha": "a00b9a80e30a9a3d459d464e2dc5eeae9e3cb5bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-24T17:02:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T17:02:59.000Z", "max_issues_repo_path": "docs/applications/ApplicationS1-teaching-exercise.tex", "max_issues_repo_name": "ingewortel/artistoo-supplements", "max_issues_repo_head_hexsha": "a00b9a80e30a9a3d459d464e2dc5eeae9e3cb5bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/applications/ApplicationS1-teaching-exercise.tex", "max_forks_repo_name": "ingewortel/artistoo-supplements", "max_forks_repo_head_hexsha": "a00b9a80e30a9a3d459d464e2dc5eeae9e3cb5bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 79.9419354839, "max_line_length": 824, "alphanum_fraction": 0.7615204584, "num_tokens": 3229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.30287562875697027}}
{"text": "\\section{Derivation of equations}\n\\subsection{Impurity centers in photorefractive crystals}\nImpurity centers have a big effect on the dynamic gratings formation in\nphotorefractive crystals. We will consider the following model of\nphotorefractive effect. Two coherent light beams are superimposed in a\nphotorefractive crystal and as result we have an interference pattern,\ni.e. spatial space distribution with are of high and low intensity of\nthe light inside photorefractive crystal. Photoelectrons are excited\nfrom  impurity centers $N_D$ \nin the areas of hight intensity. The photoelectrons migrate through\ncrystal by means of diffusion and trapped at donator cites $N_D^{+}$ in the\ncrystal. The process produces an inhomogeneous distribution of electric\ncharges and as result the electric space change field. The\nelectro-optic effect invokes the space distribution of refractive\nindex. \n\nThere are several parameters that are used for impurity centers\ndescription. The most important are the photoionization\ncross-section $s$ and the recombination constant $\\gamma_R$. The\nphotoionization \ncross-section $s$ is a characteristic of photoelectrons exciting\nprocess. The recombination constant $\\gamma_R$ is a characteristic of\nrecombination process.\n\nThe additional parameters that are used for impurity centers\ndescription are concentration of impurity centers $N_D$ and acceptors\n$N_A$. The necessity of $N_A$ introducing is the following. There are\nionized impurity centers at the dark conditions thus\n\\(\\left.N_D^{+}\\right|_{I=0} \\ne \n0\\). But the crystal is neutral itself, thus there have to be\nadditional impurity centers $N_A$ that compensate $N_D^{+}$ at the\ndark conditions \\(N_A = \\left.N_D^{+}\\right|_{I=0}\\).\n\nFig.~\\ref{fig:td_phr} shows two types\nof crystal that we consider. The first one is a photorefractive\ncrystal with one impurity center (left figure) and the second one with\n2 impurity center (right figure).\n\n\\input ./fig_td_phr.tex\n\nThe electric space change field $E_{sc}$ can be described by the following\nequation in the case of one impirity center:\n\\begin{eqnarray}\n\\label{eqEnd_1_phr}\n\\tau_{eff} \\frac {\\partial E_{sc}} {\\partial t} =\n- i E_D \\left(m + m_0\\right) \n- \\nonumber \\\\ \n- E_{sc} \n\\left( 1 - i \\frac{E_D}{E_q}\\right),\n\\end{eqnarray}\nwhere $E_D$ is the diffusion field, $E_q$ is the maximum\nsaturation field.  The $m_0$ describes is initial refractive index grating that\nalways presents in a photorefractive crystal.\n\nThe refractive index can be gotten from space charge field $E_{sc}$ \nwith Pockels equation\n\\begin{equation}\n\\delta \\varepsilon = \\alpha E_{sc},\n\\label{eqElectroOpt_phr}\n\\end{equation}\nwhere $\\alpha$ is the electro-optical coefficient.\n\nThere are several typical times that describe the system. The speed of\nphotoelectrons excitation is described by $tau_I$:\n\\[\n\\tau_I = \\frac{1}{s I_0 + \\gamma_R n_0},\n\\]\nwhere $I_0$ the light intensity, $n_0$ is the photoelectrons\ndensity at the conduction band:\n\\[\nn_0 = \\frac{s I (N_D - N_A)}{\\gamma_R N_A}.\n\\]\nThe photoelectrons recombination process is described by $tau_R$:\n\\[\n\\tau_R = \\frac{1}{\\gamma_R N_A}.\n\\]\nIn addition to $tau_I$ and $tau_R$ we introduce the Maxwell relaxation\ntime $\\tau_m$: \n\\[\n\\tau_m = \\frac{\\varepsilon}{4 \\pi \\mu n_0}\n\\]\nand a value $tau_D$ that describes the diffusion process \n\\[\n\\tau_D = \\frac{1}{K^2 D},\n\\]\nwhere $D$ is the coefficient of diffusion and $K$ is the propagation\nvector of refractive index grating. \n\nAt (\\ref{eqEnd_1_phr}) we introduced a time that describes the system\nintegrally:\n\\[\n\\tau_{eff} = \\tau_m \\frac{\\tau_R}{\\tau},\n\\]\nwhere for $\\tau$ we have:\n\\[\n\\frac{1}{\\tau} = \\frac{1}{\\tau_I} + \\frac{1}{\\tau_R} + \\frac{1}{\\tau_D}.\n\\]\n\nFor a crystal with 2 impurity centers the space charge field $E_{sc}$\nis a sum of two fields that describe influence of different impurity\ncenters: \n\\[\nE_{sc} =  E_{sc}^{(1)} + E_{sc}^{(2)},\n\\]\nFor main class of impurity centers $E_{sc}^{(1)}$ we have the following\nequation:  \n\\begin{eqnarray}\n\\label{eqEsc_1_End_2_phr}\n\\tau_{eff} \n\\frac {\\partial E_{sc}^{(1)}} {\\partial t} =\n- i E_D \\left(m + m_0^{(1)}\\right) \n- \\nonumber \\\\ \n- E_{sc}^{(1)} \n\\left( 1 - i \\frac{E_D}{E_q^{(1)}} \\right)\n -  E_{sc}^{(2)} \n\\left( 1+ i \\frac{E_D}{E_m^{(1)}} \n\\right),\n\\nonumber \\\\ \n\\left. {E_{sc}}^{(1)} \\right|_{t=0} = 0.\n\\end{eqnarray}\nFor the second one $E_{sc}^{(2)}$ we have the following:\n\\begin{eqnarray}\n\\label{eqEsc_2_End_2_phr}\n\\frac {\\partial E_{sc}^{(2)}} {\\partial t} =\n- \\frac{i \\left( m+ m_0^{(2)} \\right) E_m^{(2)}}{\\tau_m^{(2)}}\n- \\frac{E_{sc}^{(2)}}{\\tau_I^{(2)}},\n\\nonumber \\\\ \n\\left. {E_{sc}}^{(2)} \\right|_{t=0} = 0.\n\\end{eqnarray}\n\nWe introduced a new parameter $E_m^{(1,2)}$ at (\\ref{eqEsc_1_End_2_phr}) and\n(\\ref{eqEsc_2_End_2_phr}) that is defined by\n\\[\nE_m^{(1,2)} = \\frac{\\gamma_R^{(1,2)} N_{A_0}^{(1,2)}}{K \\mu}.\n\\] \n\n\\subsection{Problem statement}\n\n\\input ./fig_td1_dpcm.tex\n\nWe will consider a double phase conjugate mirror model. At the model\ntwo incoherent light beams drop on a photorefractive \ncrystal from different sides as it is shown at\nFig.~\\ref{fig:td1_dpcm}. As well as the light beams are incoherent\nthey can be considered independently.\n\n\\input ./fig_td2_dpcm.tex\n\nThe light field in photorefractive crystal is represented in the\nfollowing form (see Fig.~\\ref{fig:td2_dpcm}):\n\\[ \n\\begin{array}{l} \n\\vec{E}_1=\\vec{E}_{1s}+\\vec{E}_{1c}+\\vec{E}_{1f},\\\\ \n\\vec{E}_2=\\vec{E}_{2s}+\\vec{E}_{2c}+\\vec{E}_{2f}, \n\\end{array} \n\\] \nwhere $\\vec{E}_{1s}$ is the signal wave that has a structure of the\nlight beam drops on the crystal from the left side; $\\vec{E}_{1c}$ is the\nconjugated wave that has a structure of the\nlight beam drops on the crystal from the right side; $\\vec{E}_{1f}$ is\nthe rest that can be considered as a wave is scattered on the\ncrystal's inhomogeneities. The components of \n$\\vec{E}_2$ that propagates from right side of the crystal have the\nsame meaning.\n\nAssume\n\\[\n\\vec{E}_{1s}=A_{1s}(z,t)\\vec{e}_1(\\vec{r})e^{-i(\\vec{k}_1\\vec{r})},\n\\]\n\\[\n\\vec{E}_{1c}=A_{1c}(z,t)\\vec{e}_2^\\ast(\\vec{r})e^{i(\\vec{k}_2\\vec{r})}, \n\\]\n\\[\n\\vec{E}_{1f}=A_{1f}(z,t)\\vec{e}_{1f}(\\vec{r},t)e^{i(\\vec{k}_2\\vec{r})}, \n\\]\nwhere $\\vec{e}_1(\\vec{r})$ is the distribution for a wave drops on the\ncrystal from the left side; $\\vec{e}_2(\\vec{r})$ is the distribution for a\nwave drops on the crystal from the right side; $\\vec{e}_{1f}(\\vec{r})$\nis the distribution for stochastically scattered light.\n\nIt should be mentioned that gain for plane waves are different in\ndifferent directions. Thus the distribution function\n$\\vec{e}_{1f}(\\vec{r})$ has a maximum in maximum gain direction.\nWe assume that the initial light beams directions are chosen as the\nconjugated beams propagate in maximum gain direction. Therefore we\nchoose one propagation vector $\\vec{k}_2$ for both $\\vec{E}_{1c}$ and\n$\\vec{E}_{1f}$. \n\nEquations for $\\vec{E}_2$ are same:\n\\[\n\\vec{E}_{2s}=A_{2s}(z,t)\\vec{e}_2(\\vec{r})e^{-i(\\vec{k}_2\\vec{r})},\n\\]\n\\[\n\\vec{E}_{2c}=A_{2c}(z,t)\\vec{e}_1^\\ast(\\vec{r})e^{i(\\vec{k}_1\\vec{r})}, \n\\]\n\\[\n\\vec{E}_{2f}=A_{2f}(z,t)\\vec{e}_{2f}(\\vec{r},t)e^{i(\\vec{k}_1\\vec{r})}, \n\\]\n\nThe distribution functions $\\vec{e}_1(\\vec{r})$, $\\vec{e}_2(\\vec{r})$ and \n$\\vec{e}_{1f,2f}(\\vec{r})$ should be normalized:\n\\begin{eqnarray}\n\\int \\limits_{S} \\left( \\vec{e}_1 \\vec{e}_1^\\ast \\right) ds=1, \n\\int \\limits_{S} \\left( \\vec{e}_2 \\vec{e}_2^\\ast \\right) ds=1,\n\\nonumber \\\\\n\\left\\langle \\int \\limits_{S} \\left(\\vec{e}_{1f} \n\\vec{e}_{1f}^{\\ast} \\right) ds \\right\\rangle = 1,\n\\left\\langle \\int \\limits_{S} \\left(\\vec{e}_{2f} \n\\vec{e}_{2f}^{\\ast} \\right) ds \\right\\rangle = 1,\n\\label{eqNorm_dpcm} \n\\end{eqnarray}\nwhere $\\left\\langle\\right\\rangle$ means ensemble averaging. In addition \n\\begin{eqnarray} \n\\left\\langle e_{1f} \\right\\rangle = 0,\n\\left\\langle e_{2f} \\right\\rangle = 0.\n\\label{eqZeroF_dpcm} \n\\end{eqnarray}\nThe light beam from the left side of the crystal has the following form\n\\begin{equation} \n\\vec{E}_1=A_{1s}\\vec{e}_1 e^{-i(\\vec{k}_1 \\vec{r})} + \nA_{1c}\\vec{e}_2^\\ast e^{i(\\vec{k}_2 \\vec{r})} + \nA_{1f}\\vec{e}_{1f} e^{i(\\vec{k}_2 \\vec{r})} \n\\label{eqFieldLeft} \n\\end{equation} \nand for the beam from the right side\n\\begin{equation} \n\\vec{E}_2=A_{2s}\\vec{e}_2 e^{-i(\\vec{k}_2 \\vec{r})} + \nA_{2c}\\vec{e}_1^\\ast e^{i(\\vec{k}_1 \\vec{r})} + \nA_{2f}\\vec{e}_{2f} e^{i(\\vec{k}_1 \\vec{r})}. \n\\label{eqFieldRight} \n\\end{equation} \n\n\\subsection{Equations derivation}\n\nThe equations for refractive index gratings can be devided into to sub\nclasses. The first one is for a crystal with one impurity center:\n\\begin{eqnarray}  \n\\left(\\frac{\\partial}{\\partial{t}} \n+\\frac{1}{\\tau_{eff}}\n\\left(\n1 + i \\frac{E_D}{E_q}\n\\right)\n\\right){M} \n= \ni B \\Gamma \\frac{(A_{1s}^\\ast A_{1c}+A_{2s}^\\ast A_{2c})}{I_0}\n+ \\frac{M_0}{\\tau_{eff}}\n, \\nonumber \\\\ \n\\left(\\frac{\\partial}{\\partial{t}}\n+\\frac{1}{\\tau_{eff}}\n\\left(\n1 + i \\frac{E_D}{E_q}\n\\right)\n\\right){M_{1f}} = \ni C_1 \\Gamma \\frac{ A_{1s}^{\\ast} A_{1f}}{I_0}\n+ \\frac{M_{1f_0}}{\\tau_{eff}}\n, \\nonumber \\\\ \n\\left(\\frac{\\partial}{\\partial{t}} \n+\\frac{1}{\\tau_{eff}}\n\\left(\n1 + i \\frac{E_D}{E_q}\n\\right)\n\\right){M_{2f}} = \ni C_2 \\Gamma  \\frac{A_{2s}^{\\ast} A_{2f}}{I_0}\n+ \\frac{M_{2f_0}}{\\tau_{eff}}\n, \n\\label{eqGrating_1_dpcm} \n\\end{eqnarray} \nwhere\n\\[\nB = \\left.const\\right|_t,\nC_{1,2} = \\left.const\\right|_t,\nM_0 = \\left.const\\right|_t,\nM_{1f_0} = \\left.const\\right|_t,\nM_{2f_0} = \\left.const\\right|_t.\n\\] \n\nFor the second case (crystal with 2 impurity centers) we will write\nequations that are conjugated to \n(\\ref{eqM_2_dpcm}, \\ref{eqM1f_2_dpcm}, \n\\ref{eqM2f_2_dpcm}):\n\\begin{eqnarray}\n\\left(\\frac{\\partial}{\\partial{t}} \n+\\frac{1}{\\tau_{eff}}\n\\left(\n1 + i \\frac{E_D}{E_q}\n\\right)\n\\right){M^{(1)}} \n= \ni B \\Gamma \\frac{(A_{1s}^{\\ast} A_{1c}+A_{2s}^{\\ast} A_{2c})}{I_0}\n-\n\\nonumber \\\\\n-\\frac{1}{\\tau_{eff}}\n\\left(\n1 - i \\frac{E_D}{E_m^{(1)}}\n\\right) M^{(2)}\n+ \\frac{M_0^{(1)}}{\\tau_{eff}},\n\\nonumber \\\\\n\\left(\n\\frac{\\partial}{\\partial{t}} + \\frac{1}{\\tau_I^{(2)}}\n\\right) \n{M^{(2)}} \n= i \\frac{\\tau_{eff}}{\\tau_m^{(2)}}\n B \\Gamma^{(2)} \\frac{(A_{1s}^{\\ast} A_{1c}+A_{2s}^{\\ast} A_{2c})}{I_0}\n+ \\frac{M_0^{(2)}}{\\tau_{m}^{(2)}}\n,\n\\nonumber \\\\\n\\left(\\frac{\\partial}{\\partial{t}} \n+\\frac{1}{\\tau_{eff}}\n\\left(\n1 + i \\frac{E_D}{E_q}\n\\right)\n\\right){M_{1f}^{(1)}} \n= \ni C_1 \\Gamma \\frac{(A_{1s}^{\\ast} A_{1f})}{I_0}\n-\n\\nonumber \\\\\n- \\frac{1}{\\tau_{eff}}\n\\left(\n1 - i \\frac{E_D}{E_m^{(1)}}\n\\right) M_{1f}^{(2)}\n+ \\frac{M_{1f_0}^{(1)}}{\\tau_{eff}},\n\\nonumber \\\\\n\\left(\n\\frac{\\partial}{\\partial{t}} + \\frac{1}{\\tau_I^{(2)}}\n\\right) \n{M_{1f}^{(2)}} \n= i \\frac{\\tau_{eff}}{\\tau_m^{(2)}}\nC_1 \\Gamma^{(2)} \\frac{(A_{1s}^{\\ast} A_{1f})}{I_0}\n+ \\frac{M_{1f_0}^{(2)}}{\\tau_{m}^{(2)}}\n,\n\\nonumber \\\\\n\\left(\\frac{\\partial}{\\partial{t}} \n+\\frac{1}{\\tau_{eff}}\n\\left(\n1 + i \\frac{E_D}{E_q}\n\\right)\n\\right){M_{2f}^{(1)}} \n= \ni C_2 \\Gamma \\frac{(A_{2s}^{\\ast} A_{2f})}{I_0}\n-\n\\nonumber \\\\\n- \\frac{1}{\\tau_{eff}}\n\\left(\n1 - i \\frac{E_D}{E_m^{(1)}}\n\\right) M_{2f}^{(2)}\n+ \\frac{M_{2f_0}^{(1)}}{\\tau_{eff}},\n\\nonumber \\\\\n\\left(\n\\frac{\\partial}{\\partial{t}} + \\frac{1}{\\tau_I^{(2)}}\n\\right) \n{M_{2f}^{(2)}} \n= i \\frac{\\tau_{eff}}{\\tau_m^{(2)}}\nC_2 \\Gamma^{(2)} \\frac{(A_{2s}^{\\ast} A_{2f})}{I_0}\n+ \\frac{M_{2f_0}^{(2)}}{\\tau_{m}^{(2)}}\n.\n\\label{eqGrating_2_dpcm} \n\\end{eqnarray}\nWhere\n\\[\nB = \\left.const\\right|_t,\nC_{1,2} = \\left.const\\right|_t,\n\\]\n\\[\nM_0^{(1,2)} = \\left.const\\right|_t,\nM_{1f_0}^{(1,2)} = \\left.const\\right|_t,\nM_{2f_0}^{(1,2)} = \\left.const\\right|_t.\n\\] \n\nThe coefficients $B$ and $C_{1,2}$ at (\\ref{eqGrating_1_dpcm},\n\\ref{eqGrating_2_dpcm}) can be understood as overlap ratios. Thus they\ndefine the part of the crystal where interaction occurs. The the\ncoefficients should  satisfy the following conditions:\n$B < 1$ and $C_{1,2} < 1$.\n\nThe equations for scattered fields were gotten in our previouse paper\n\\cite{OurDPCM}. \n\nFor the left light beam's components we got the following result\n\\begin{eqnarray}\n\\frac{\\partial{A_{1s}}}{\\partial{z}} = \n- i D \\left\\{ \nA_{1c} M^{\\ast} + A_{1f} M_{1f}^{\\ast} \\right\\},\n\\nonumber \\\\\n\\frac{\\partial{A_{1c}}}{\\partial{z}} = - \ni D A_{1s} M,\n\\nonumber \\\\\n\\frac{\\partial{A_{1f}}}{\\partial{z}} = \n- i D A_{1s} M_{1f},\n\\label{eqAmpl_left_dpcm}\n\\end{eqnarray}\n\nFor the right light beam's components we got the following result\n\\begin{eqnarray}\n\\frac{\\partial{A_{2s}}}{\\partial{z}} = \n i D\n \\left\\{ \nA_{2c} M^{\\ast} + A_{2f} M_{2f}^{\\ast} \\right\\},\n\\nonumber \\\\\n\\frac{\\partial{A_{2c}}}{\\partial{z}} =  \ni D\nA_{2s} M,\n\\nonumber \\\\\n\\frac{\\partial{A_{2f}}}{\\partial{z}} = \ni D\nA_{2s} M_{2f},\n\\label{eqAmpl_right_dpcm}\n\\end{eqnarray}\n\nAt (\\ref{eqAmpl_right_dpcm}) and (\\ref{eqAmpl_left_dpcm}) we assumed\nthat $\\theta_1 =\\theta_2=\\theta$ thus\n$D=\\frac{\\omega}c\\frac 1 {2 \\cos \\theta}\\sqrt{\\frac\\mu\\epsilon}$.\n", "meta": {"hexsha": "7e54f5c7f2d1d73cd2843fa9ce8962c055979a3c", "size": 12640, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "old/dpcm/physrev/equation.tex", "max_stars_repo_name": "ivanmurashko/articles", "max_stars_repo_head_hexsha": "522db3ad21e96084490acd39a146a335763e5beb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-09-27T08:59:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-27T08:59:55.000Z", "max_issues_repo_path": "old/dpcm/physrev/equation.tex", "max_issues_repo_name": "ivanmurashko/articles", "max_issues_repo_head_hexsha": "522db3ad21e96084490acd39a146a335763e5beb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "old/dpcm/physrev/equation.tex", "max_forks_repo_name": "ivanmurashko/articles", "max_forks_repo_head_hexsha": "522db3ad21e96084490acd39a146a335763e5beb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6796116505, "max_line_length": 79, "alphanum_fraction": 0.6662974684, "num_tokens": 4851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.3028179895997181}}
{"text": "%$Author: jlconlin $\n%$Date: 2007-03-24 10:35:35 -0600 (Sat, 24 Mar 2007) $\n%$Revision: 33 $\n%$Id: ArnoldiMC.tex 33 2007-03-24 16:35:35Z jlconlin $\n\\documentclass[12pt]{article}\n\\usepackage{geometry}\n\\usepackage{amsmath}\n\\usepackage{setspace}\n\\usepackage[algo2e, ruled, linesnumbered]{algorithm2e}\n\\usepackage[usenames, dvipsnames]{color}\n\\usepackage{amsthm}\n\\usepackage{graphicx}\n\n\\SetKwComment{Comment}{$\\triangleright$ }{}\n\\dontprintsemicolon\n\n\\newtheorem{theorem}{Theorem}\n\\newtheorem{coro}[theorem]{Corollary}\n\n\\author{Jeremy Conlin}\n\\title{Arnoldi's Method in Monte Carlo}\n\n\\begin{document}\n\\maketitle\n\n\\begin{abstract}\nThis document was written to help the author understand Monte Carlo Arnoldi's method.  There are mistakes and many assumptions are not explicitly stated.  USE AT YOUR OWN RISK! No warranty expressed or implied.\n\\end{abstract}\n\n\\section{Iteration}\nOne Arnoldi Iteration begins with sampling the fission source and tracking those particles with Monte Carlo transport.  This should be the only portion of this method that uses Monte Carlo transport.  The remainder should be the same as the deterministic method.\n\n\\subsection{Monte Carlo Transport}\nThe Monte Carlo portion begins by sampling from a fission source.  In this formulation, the fission source is a histogram source where some bins may have negative values.  The number of neutrons sampled from this distribution is constant between Monte Carlo cycles (although it doesn't have to be).  \n\nAfter the neutrons are sampled, they are transported as in a traditional Monte Carlo Power Method calculation.  The neutrons create additional fission neutrons at every collision.  The number of fission neutrons added to the bank at each collision is dependent on the weight of the colliding neutron,\n\\begin{equation} \\label{eq:num-fission}\n    N = \\left\\lfloor\\omega\\left(\\frac{\\nu\\Sigma_f}{\\Sigma_t}\\right) + \\xi\\right\\rfloor\\,,\n\\end{equation}\nwhile the weight of the neutron is reduced as\n\\begin{equation}\n    \\omega = \\omega'\\left(\\frac{\\Sigma_s}{\\Sigma_t}\\right).\n\\end{equation}\n\nA neutron is transported until it leaves the slab geometry or its weight becomes too small ($\\omega < 0.2$) at which point, it plays Russian Roulette.  Currently, the survival probability is: $p_s = 0.8$, that is, 80\\% of the time, the particle will be killed.  The weight of a surviving particle is increased as\n\\begin{equation}\n    \\omega = \\omega'\\frac{1}{p_s}.\n\\end{equation}\n\n\\subsubsection{Negative Weight Neutrons}\nArnoldi's method cannot guarantee you won't get negative sources.  More often than not, you will have negative sources.  So how can we deal with this?  What exactly is a negative fission source?  The answer isn't as difficult as it might first seem.  A particle sampled from a negative source has a negative weight.  Every time a negative weight neutron makes a score, it subtracts from the tally.  \n\nWe can envision our transport as two independent Monte Carlo transport problems; one whose source is the positive portion of the PDF and the other source is the absolute value of the negative PDF.  Both sources are sampled, transported, tallied and binned.  The negative source is then subtracted from the positive source in each bin.  \n\nThe total number of particles transported is\n\\begin{equation}\n    h = N_p + N_n,\n\\end{equation}\nwhere $N_p$ is the number of neutrons from the positive PDF and $N_n$ is the number of neutrons from the negative PDF.  The ratio of the number of positive weight particles to negative weight particles is ratio of the probability of picking a positive weight particle to the probability of picking a negative weight particle,\n\\begin{equation}\\label{eq:PDFprob}\n    \\frac{N_p}{N_n} = \\frac{\\int{Q_p}}{\\int{Q_n}}\\,.\n\\end{equation}\n\nSo what do we do with negative weight particles?  Using Eq. \\ref{eq:num-fission} a negative weight particle will \\emph{never} add a neutron to the fission bank.  I suspect what we need to do is modify Eq. \\ref{eq:num-fission} to use the absolute value of the weight; \n\\begin{equation}\n    N = \\left\\lfloor|\\omega|\\left(\\frac{\\nu\\Sigma_f}{\\Sigma_t}\\right) + \\xi\\right\\rfloor\\,\n\\end{equation}\nI also need take into account the sign of the particle's weight (but not it's magnitude) when binning a fission bank.  \n\nSimilarly when I decide whether or not I should play Russian Roulette, I need to see if the absolute value of the weight is less than some cutoff.\n\\normalcolor\n\n\\subsection{``Matrix-ify'' Fission Bank}\nMonte Carlo transport returns a new fission bank---a collection of fission neutrons---that traditionally would have been used directly for the next cycle.  With Arnoldi's Method we need to take this fission bank and turn it into something like a vector.  This vector must be able to be multiplied by a scalar and added and subtracted to other vectors.\n\nWe have chosen to turn our fission banks into vectors by binning or making a histogram out of the fission neutrons.  The value or height in each bin represents the number of fission neutrons in each geometrical bin.  The histogram is normalized and the bin values become the elements of the vector.\n\n\\subsubsection{Fission Source Normalization}\nI don't understand why, but this is how you normalize the fission source, immediately after it has been binned, before you apply Arnoldi to it,\n\\begin{equation}\n    q_{k+1} = q_{k+1}\\frac{1}{N}\\int{\\left|q_k\\right|}.\n\\end{equation}\nBy normalizing in this way, the bins are the probabilities of a fission occurring in that bin \\emph{per source particle}.\n\n\\begin{figure}[h]\n    \\includegraphics[width=6in, keepaspectratio]{Whiteboard.jpg}\n\\end{figure}\n\n\\subsection{Orthogonalize} \\label{sec:Orthogonalize}\nIn the $k^{th}$ iteration, the operation \n\\begin{equation}\n    q_{k+1} = Aq_k,\n\\end{equation}\nis performed where $A$ is what I will call the Monte Carlo operator, and the $q$'s are fission sources.  We already have an orthonormal set of fission sources $\\{q_1, q_2, \\dots, q_k\\}$ which span the Krylov subspace.  For each of these previously generated sources, we perform two calculations,\n\\begin{subequations} \\label{eq:Orthogonalize}\n\\begin{gather} \n    h_{j,k} = \\left<q_j, Aq_k\\right> = \\left<q_j,q_{k+1}\\right> \\\\ \n    q_{k+1} = q_{k+1} - h_{j,k}*q_j,\n\\end{gather}\n\\end{subequations}\nto orthogonalize $q_{k+1}$ and also to create an upper hessenberg matrix, $h$, which has the same eigenvalues as the linear operator $A$ we are investigating.\n\nApplying Eqs. \\ref{eq:Orthogonalize} for every previously generated source ($q_j$) on the current source, $q_{k+1}$ will make $q_{k+1}$ orthogonal to all $q_j$'s.  Now all that remains is to normalize $q_{k+1}$ and add one more entry to our upper hessenberg matrix;\n\\begin{subequations}\\begin{gather}\n    h_{k+1,k} = \\left<q_{k+1},Aq_{k}\\right> = \\left<q_{k+1},q_{k+1}\\right> = \\left\\|q_{k+1}\\right\\|_2 \\\\\n    q_{k+1} = q_{k+1}/h_{k+1,k}.\n\\end{gather}\\end{subequations}\n\n\\subsection{Eigenvalues}\nThe Arnoldi formulation proves that our upper hessenberg matrix, $h$, and our matrix (or linear operator) of interest, $A$, are similar and therefore have the same eigenvalues.  Finding the eigenvalues of $h$ is easy because $h$ is small compared to $A$ and also because it is upper hessenberg.  Therefore, to find the eigenvalues of $A$, we create $h$ through the orthogonalization process defined in section \\ref{sec:Orthogonalize} and then use our favorite eigenvalue calculator.\n\n\\subsection{Eigenvectors}\nEven though $h$ and $A$ are similar, this doesn't guarantee they have the same eigenvectors.  In fact they won't because the dimension of the eigenvectors of $h$ will be much smaller than those of $A$.  \n\nThe eigenvectors of $A$ associated with the eigenvalues calculated from the similar matrix $h$, can be calculated as a linear combination of the orthonormal vectors, $q_j$.  The expansion coefficients for eigenvector $i$ are the elements of the $i^{th}$ eigenvector of $h$. \n\n\\subsection{Residual}\nThe residual norm gives some indication of how close we have converged upon our solution.  Saad (1992) shows that the residual norm is just the last component of the eigenvector $y_i^{(m)}$ multiplied by $h_{m+1,m}$.  This works well in the deterministic calculation, but I'm not sure it will works for all cases in the Monte Carlo calculation.\n\nSuppose, if you will, that you have a point source in a---nearly---infinite medium.  The orthonormal vectors calculated will have non-zero elements in the middle few bins, and zeros elsewhere.  When calculating the eigenvector of the Monte Carlo operator, the outer elements of the eigenvector will also be zero.  For an infinite medium problem, the residual will be zero immediately.  \n\nSaad does say that the residual norms are ``not always indicative of actual errors'', but ``are quite helpful in deriving stopping procedures.''  For Monte Carlo applications of Arnoldi's Method, it seems clear that this simple calculation of the residual may give incorrectly small values and we might stop prematurely.\n\n\\section{Uncertainty}\nOnce the eigenvalue has been found, we must be able to place an uncertainty about it.  Our Matrix-Vector product is stochastic and our uncertainty should be in a form of standard deviation.\n\n\\section{Restarting}\nOne can restart Arnoldi's method after some number of iterations to reduce the memory requirements and the number of orthogonalization steps.  After a predetermined number of iterations, the simulation is stopped, the eigenvector of interest is calculated and this eigenvector (e.g. fission source) is used as the initial guess for an entirely new Arnoldi process.\n\n\\section{Preliminary Results}\nI have a working version of Monte Carlo Arnoldi's method.  In this section, I present some arguments to give confidence to the results received.  \n\n\\subsection{Uncertainty}\nCurrently we have no direct way of determining the uncertainty of a Monte Carlo Arnoldi simulation.  To get a rough estimate, I ran 50 simulations and calculated their average and variance/standard deviation.  The geometry was discretized into 10 bins.  I ran this series of simulations five times with 1000 histories per iteration and five times with 10,000 histories per cycle.  With 1000 histories per iteration the standard deviation was 0.01; with 10,000 histories per cycle the standard deviation was 0.004.\n\n\\subsection{Residual}\nIn Arnoldi's method, we can calculate the residual norm, a simple measure of the convergence of the calculated eigenvalues to the true eigenvalues.  Once the residual is sufficiently small iteration stops.  In deterministic Arnoldi's method, this is a good way to determine stopping procedures. \n\nWhen investigating the Monte Carlo version of Arnoldi's method it would be nice to see the residual norm decrease as a function of Arnoldi iteration just as the deterministic does, but with the stochastic noise.  In Figure \\ref{fig:Residual} the residual norm for both deterministic and Monte Carlo simulations are shown.  The deterministic simulation is a $1000 \\times 1000$ diagonal matrix with the vector $[1,2,\\ldots, 1000]$ on the diagonal.  The Monte Carlo simulation had slab geometry with half-width 0.5 mfp and discretized into 10 spatial bins.  Although the residual of the Monte Carlo simulation doesn't decrease as much as the deterministic residual, it does have the same trend of decreasing.\n\nIn my (limited) experience, the dominant eigenvalue is determined to machine precision before the residual is sufficiently low.  I believe this is due to the stochastic nature of Monte Carlo methods.  The residual hovers around $10^{-3}$ until the Krylov subspace has been spanned and then immediately drops to $10^{-13}$ or smaller.  The maximum number of iterations before the subspace has been spanned is equal to the number of spatial bins.  A simulation with 100 spatial bins would span the Krylov subspace in at most 100 iterations, but the eigenvalue is found---to within machine precisions---in about 50 iterations.\n\\begin{figure}[h]\\centering\n    \\includegraphics[width=5in, keepaspectratio]{ArnoldiDtmResidual.pdf}\n    \\includegraphics[width=5in, keepaspectratio]{ArnoldiMCResidual.pdf}\n    \\caption{Residual norm as a function of the number of Arnoldi Iterations.  Top figure is Deterministic and the ``blips'' are when Arnoldi restarted.  The bottom figure is Monte Carlo.}\n    \\label{fig:Residual}\n\\end{figure}\n\n\n\\subsection{Eigenvalue and Timing Comparisons}\nComparing Monte Carlo Arnoldi's method to a traditional Power method is difficult.  First of all, we don't yet have a good way of determining the uncertainty in the eigenvalue for Arnoldi's method.  Second, it may be difficult to determine when the Power method has converged.  \n\nIn this illustration I have used 1000 histories per iteration/cycle.  As indicated previously, this is roughly an uncertainty of 0.01 in Arnoldi's method.  The Power method used 20 inactive cycles and the uncertainty was comparable with that of Arnoldi's method.  The geometry was slab geometry with varying half-width.  In both Arnoldi's method and the Power method, the fission source was discretized into 10 spatial bins.  I show the results in Table \\ref{tbl:Timing} where the results are compared with ``benchmark'' results from Martin and Duderstadt\\footnote{William R. Martin and James J. Duderstadt, \\emph{Nuclear Science an Engineering}, \\textbf{62}, 371-390 (1970)}.\n\n\\begin{table}[h]\\centering\n    \\caption{Eigenvalue and timing comparisons.}\n    \\label{tbl:Timing}\n    \\vspace{11pt}\n    \\begin{tabular}{|c|c|c|c|c|c|} \\hline\n        Half width [mfp] & M\\&D & MC Arnoldi & time [s] & MC Power & time [s] \\\\ \\hline\n        0.5  & 0.448278 & 0.4520 & 2.1 & 0.4492 $\\pm$ 0.011 & 4.8  \\\\ \\hline\n        1.0  & 0.643416 & 0.6438 & 2.5 & 0.6423 $\\pm$ 0.019 & 5.7  \\\\ \\hline\n        5.0  & 0.952601 & 0.9545 & 4.2 & 0.9581 $\\pm$ 0.024 & 8.6  \\\\ \\hline\n        10.0 & 0.985831 & 0.9899 & 4.8 & 0.9950 $\\pm$ 0.025 & 9.0  \\\\ \\hline\n        30.0 & ---      & 1.0049 & 4.7 & 1.0078 $\\pm$ 0.019 & 9.4  \\\\ \\hline\n    \\end{tabular}\n\\end{table}\n\nWith this comparison it seems that one can accurately calculate the eigenvalue using a Monte Carlo version of Arnoldi's method.  From these results, it looks like Arnoldi's method is faster than the Power method, however it will take a more careful and detailed tests to make a definite decision.\n\n\\subsection{Eigenvector}\nI am still working out the details of calculating the dominant eigenvector associated with the (correct) eigenvalue calculated.  In the tests shown in Table \\ref{tbl:Timing} I can get the correct shape---roughly cosine---for each test.  Sometimes the eigenvector comes out upside-down.  This isn't too much of a problem since we know the eigenvector is only unique times a multiplicative constant; this constant could be -1.  Almost always, the eigenvector is negative at the edges of the slab.  This is more cause for concern; we know the eigenvector (the flux) must be zero or positive everywhere.  What then is to be done with negative components of the eigenvector?  I have plotted two resulting eigenvectors in Figure \\ref{fig:Vector}, both were calculated with 10,000 histories per iteration.\n\n\n\\begin{figure}[h]\\centering\n    \\includegraphics[width=5in, keepaspectratio]{NegativeEigenvector.pdf}\n    \\includegraphics[width=5in, keepaspectratio]{PositiveEigenvector.pdf}\n    \\caption{Eigenvector from two separate Monte Carlo Arnoldi simulations showing potential problems.}\n    \\label{fig:Vector}\n\\end{figure}\n\n\n\\newpage\n\\section{Algorithms}\n\\begin{algorithm2e}\n    \\SetVline\n    \\caption{Deterministic Arnoldi Process (freely borrowed from Watkins(2002))}\\label{alg:DtmArm}\n    $q_1 = q/\\left\\|q\\right\\|_2$ \\;\n    \\For{$k=1,\\ldots,m-1$}{\n        $q_{k+1} \\gets Aq_k$\\;\n        \\For(\\Comment*[f]{Orthogonalize}){$j=1, \\ldots, k$}{ \n            $h_{jk} \\gets \\left<q_j,q_{k+1}\\right>$\\;\n            $q_{k+1} \\gets q_{k+1} - q_jh_{jk}$}\n        $h_{k+1,k} \\gets \\left\\|q_{k+1}\\right\\|_2$\\;\n        \\If(\\Comment*[f]{Span \\{$q_1, \\ldots, q_k$\\} is invariant under $A$}){$h_{k+1,k} = 0$}{\n            quit.}\n        $q_{k+1} \\gets q_{k+1}/h_{k+1,k}$\\;\n    }\n\\end{algorithm2e}\n\n\\begin{algorithm2e}\n    \\SetVline\n    \\caption{Deterministic Arnoldi Process, Python Style}\\label{alg:DtmArnPy}\n    \\For(\\Comment*[f]{$I$ = \\# of Arnoldi Iterations.}){$k=1, \\ldots, I+1$}{\n        $q \\gets AQ_{k-1}$\\Comment*[f]{$(k-1)^{\\textrm{st}}$ or last column of $Q$} \\;\n        \\For{$j=1, \\ldots, k+1$}{\n            $h_{j-1,k-1} = \\left<Q_{j-1},q\\right>$ \\Comment*[f]{$(j-1)^{\\textrm{st}}$ column of $Q$} \\;\n            $q \\gets q - Q_{j-1}*h_{j-1,k-1}$}\n        $h_{k,k-1} \\gets \\left\\|q\\right\\|_2$ \\;\n        $q = q/h_{k,k-1}$ \\;\n        \\If(\\Comment*[f]{Residual too small.}){$h_{k,k-1}*y_m < 10^{-10}$}{\n            quit\\Comment*[f]{See Saad 1992 p.175-76.}}\n        $Q = \\left[Q|q\\right]$ \\Comment*[f]{Append $q$ as last column of $Q$}}\n\\end{algorithm2e}\n\n\\begin{algorithm2e}\n    \\SetVline\n    \\caption{Monte Carlo Arnoldi Process}\\label{alg:MCArnoldi}\n    \\For{$k=1, \\ldots, iterations + 1$}{\n        $q = AQ_k = \\ldots$ \\Comment*[f]{Monte Carlo portion} \\;\n        $q = \\left(q/N\\right)\\int{\\left|Q\\right|}$ \\Comment*[f]{Monte Carlo normalization} \\;\n        \\For{$j=1, \\ldots, k+1$}{\n            $h_{j-1,k-1} = \\left<Q_{j-1},q\\right>$ \\;\n            $q = q - h_{j-1,k-1}*Q_{j-1}$}\n        $h_{k,k-1} = \\left\\|q\\right\\|_2$ \\Comment*[f]{Arnoldi normalization}\\;\n        $q = q/h_{k,k-1}$ \\;\n        Calculate eigenpairs\\;\n        Sort eigenpairs\\;\n        \\If(\\Comment*[f]{Residual too small.}){$h_{k,k-1}*y_m < 10^{-10}$}{\n            quit Arnoldi.  Start Power Method.\\Comment*[f]{See Saad 1992 p.175-76.}}\n        $Q = \\left[Q|q\\right]$ \\Comment*[f]{Append $q$ as last column of $Q$}}\n\\end{algorithm2e}\n\n\\end{document}\n", "meta": {"hexsha": "41c3ba82cf6ea26b2a9a6b1c38d83807a22d9969", "size": 17751, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Code/branches/Pre-Prospectus/python/Arnoldi/MonteCarlo/tex/ArnoldiMC.tex", "max_stars_repo_name": "jlconlin/PhDThesis", "max_stars_repo_head_hexsha": "8e704613721a800ce1c59576e94f40fa6f7cd986", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/branches/Pre-Prospectus/python/Arnoldi/MonteCarlo/tex/ArnoldiMC.tex", "max_issues_repo_name": "jlconlin/PhDThesis", "max_issues_repo_head_hexsha": "8e704613721a800ce1c59576e94f40fa6f7cd986", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/branches/Pre-Prospectus/python/Arnoldi/MonteCarlo/tex/ArnoldiMC.tex", "max_forks_repo_name": "jlconlin/PhDThesis", "max_forks_repo_head_hexsha": "8e704613721a800ce1c59576e94f40fa6f7cd986", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 75.5361702128, "max_line_length": 798, "alphanum_fraction": 0.7350571799, "num_tokens": 4987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.3028159001049494}}
{"text": "%\r\n%  THIS FILE IS COMMON\r\n%\r\n\\subsection{Bond Orders}\\label{bonds}\r\n\\index{Valency|ff}\\index{Lone pairs|(}\\index{Bond order}\\index{Wiberg indices}\r\nThree quantities can be derived~\\cite{bonds} from the density matrix for use in\r\ndiscussing bonding.  These are: atomic bond index, anisotropy, and  bond\r\norder. \r\n\r\nThe density matrix, $P$, can be decomposed into sub-matrices representing atoms\r\nor interactions between atoms.  The three  quantities just mentioned can then\r\nbe defined in terms of these sub-matrices.\r\n\r\n\\subsubsection{Atomic bond index}\r\nA measure of the valency of an atom.\r\n\\begin{equation}\r\nV_A=\\sum_{\\lambda\\in A}2P_{\\lambda\\lambda}-\\sum_{\\lambda\\in A}\\sum_{\\sigma\\in A}P_{\\lambda\\sigma}^2.\r\n\\end{equation}\r\nTypical valencies are: 1.0 for hydrogen, 2.0--2.4 for oxygen to 3.8--4.0 for\r\ncarbon. The maximum valency of an atom is equal to the number of atomic\r\norbitals, e.g.\\  1 or 4 (for a $sp^3$ system), or 9 (in MNDO-$d$). This maximum\r\nis only achieved when the orbital population is 1.00, and all off-diagonal\r\nterms on the atom are zero.\r\n\r\n\\subsubsection{Anisotropy}\r\nA measure of the number of lone-pairs on an atom.\r\n\\begin{equation}\r\nL_A=\\sum_{\\lambda\\in A}\\sum_{\\sigma\\in A}P_{\\lambda\\sigma}^2 - \\sum_{l=0}^{k}\r\n\\frac{1}{2l+1}(\\sum_{\\lambda=l^2+1}^{(l+1)^2}P_{\\lambda\\lambda})^2.\r\n\\end{equation}\r\nTypical numbers of lone-pairs are: 0 in, for example, hydrogen and carbon, 1 for\r\n nitrogen in amines, and 2 in oxygen.\r\n\r\nTo see how this expression is derived, consider an atom having valence orbitals\r\ndefined by angular quantum numbers $l=0,1,\\ldots,k$.  For H, $k=0$, for all\r\nother elements, $k=1$. In order to have spherical symmetry, all orbitals in any\r\nshell must be equally occupied. In addition, since the product of any two\r\ndifferent atomic orbitals is non-spherical, all off-diagonal density matrix\r\nterms on any one atom must be zero.\r\n\r\n\\index{Lone pairs|)}\r\nFor a spherical atom having the atomic populations $s^pp^qd^r$, the valency\r\nwould be:\r\n\\begin{equation}\r\nV_A=p^2+\\frac{q^2}{3}+\\frac{r^2}{5},\r\n\\end{equation}\r\nor, in general:\r\n\\begin{equation}\r\nV_A = \\sum_{l=0}^{k} \\label{eq:V_A}\r\n\\frac{1}{2l+1}(\\sum_{\\lambda=l^2+1}^{(l+1)^2}P_{\\lambda\\lambda})^2.\r\n\\end{equation}\r\nSince, in general, atoms are non-spherical, then:\r\n\\begin{equation} \r\nV_A=\\sum_{\\lambda\\in A}\\sum_{\\sigma\\in A}P_{\\lambda\\sigma}^2 \\label{eq:V_A2}.\r\n\\end{equation}\r\nThe difference between equations \\ref{eq:V_A} and \\ref{eq:V_A2} is a measure of how\r\nunspherical the atom is.\r\n\r\n\\subsubsection{Bond order}\r\nA measure of the number of bonds between atoms in a compound.\r\n\\begin{equation}\r\nB_{AB}=\\sum_{\\lambda\\in A}\\sum_{\\sigma\\in B}P_{\\lambda\\sigma}^2\r\n\\end{equation}\r\nTypical bond-orders are: 1.0, e.g.,  C-C in ethane; 2.0, e.g.,  C=C  in\r\nethylene; 3.0, e.g.,  C$\\equiv$C in acetylene.  Bond orders of less than about\r\n0.1--0.2 are indicative of ``no bond''.\r\n\r\nThe ideas here are an extension of Wiberg's indices~\\cite{wiberg}.\r\n\r\nGiven the normal semiempirical density matrix, it is easy to show that\r\n\\begin{equation}\r\nP^2=2P,\r\n\\end{equation}\r\nfrom which it follows that\r\n\\begin{equation}\r\nP_{\\lambda\\lambda}=1/2\\sum_{\\sigma}P_{\\lambda\\sigma}^2.\r\n\\end{equation}\r\nThis is the starting point for the derivation of\r\n\\begin{equation}\r\nV_A=\\sum_{B\\neq A}B_{AB},\r\n\\end{equation}\r\nfrom which the above definitions follow.\r\n\r\n\r\n", "meta": {"hexsha": "89dc0f7e6495a6200607302d6e965a6580295490", "size": 3347, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "manuals/MOPAC2000_manual/t_bonds.tex", "max_stars_repo_name": "openmopac/MOPAC-archive", "max_stars_repo_head_hexsha": "01510e44246de34a991529297a10bcf831336038", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-16T20:53:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T20:54:11.000Z", "max_issues_repo_path": "manuals/MOPAC2000_manual/t_bonds.tex", "max_issues_repo_name": "openmopac/MOPAC-archive", "max_issues_repo_head_hexsha": "01510e44246de34a991529297a10bcf831336038", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "manuals/MOPAC2000_manual/t_bonds.tex", "max_forks_repo_name": "openmopac/MOPAC-archive", "max_forks_repo_head_hexsha": "01510e44246de34a991529297a10bcf831336038", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.3764705882, "max_line_length": 101, "alphanum_fraction": 0.7134747535, "num_tokens": 1110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.3027389449109549}}
{"text": "\\section{Concepts}\n\n\\subsection{Overview}\nNumerical Analysis takes place within the context of a\ndiscrete computing machine with finite register sizes.  To\nbe specific, we can use the Intel 386/387 as the least\ncommon denominator for Modula-3.  Further, Modula-3 is\ncurrently implemented with a 32-bit Word and IEEE 32-bit and\n64-bit floating points numbers, which happen to mirror the\n386/387 hardware.  A large part of numerical analysis is\ntuning algorithms so that they are not tripped up by the\nfinite limitations of the hardware.\n\nFirst we must understand the number representations.  Then\nwe can discuss the typical errors which can arise.  Next we\nwill discuss ways around them.  Finally, we will layout an\napproach to numerical analysis routines.\n\n\\subsection{Arithmetic Logic Unit (ALU)}\nSee Craw87, pg 18.\n\nAn ALU is the integer heart of a typical CPU.  It handles\nraw machine word operations like:\n\\begin{itemize}\n   \\item  rotate\n   \\item  shift\n   \\item  bitset and reset\n   \\item  compare\n   \\item  test for sign\n   \\item  test for carry\n\\end{itemize}\n\nIt also does \"mathematical\" cardinal and integer operations\nlike:\n\\begin{itemize}\n   \\item  add\n   \\item  sub\n   \\item  mul\n   \\item  div\n\\end{itemize}\n     \nThe ALU's 32 bits are typically drawn as 0..31 bits, with\nthe most significant figure on the left.\n\n\\begin{center}\n\\begin{tabular}{|c|c|c|c|c|c|c|} \\hline\n    31 & 30 & 29 & $\\cdots$ & 2 & 1 & 0 \\\\ \\hline\n\\end{tabular}    \n\\end{center}\n\nThe raw values in the register are typically as given as\nbitstrings of \"0\" and \"1\".  Modula-3 conveniently allows\nthis to be shown as a literal, preceded by the radix marker\n\"2\\_\".  You don't have to show the 0's to the left of the\nmost significant 1, but it doesn't hurt.  Often for\nformatting, it is a good idea to left-pad with leading 0's\nto a given width:\n\n\\begin{tt} \\begin{verbatim}\n     2_1010101010101010101010101010101 (*all 32 bits used*)\n     2_10001010 (*just lowest 8 bits used*)\n     2_00001011 (*just lowest 4 bits are used*)\n\\end{verbatim} \\end{tt}\n\nIf you do nothing special, these literals will be fitted\ninto a full 32-bit INTEGER when they are assigned to a\nvariable.  But by defining types (and variables) with fewer\nbits, we could save space:\n\n\\begin{tt} \\begin{verbatim}\n     RECORD\n       i:=2_1010;                     (*32-bit INTEGER*)\n       j:BITS  4 FOR [0..15]:=2_1010; (* 4-bit CARDINAL*)\n       k:BITS 21 FOR [0..1000000];    (* 21-bit CARDINAL*)\n       l:BITS  7 FOR [-5..50];        (* 7-bit INTEGER*)\n     END;\n\\end{verbatim} \\end{tt}\n\nThis makes sense in a packed record, but probably not\nelsewhere.  For numerical analysis, Integer.i3 provides integers\nand cardinals of 8, 16, 32 bits.\n\nCompletely independent of the choice of bit lengths is the\nchoice of radix for representing literals.  While binary\nliterals help clarify some numerical code, other radixes\nmight help elsewhere.  Unlike many languages, Modula-3\nallows radixes from 2..16, e.g.,\n\\begin{tt} \\begin{verbatim}\n     8_03470\n     16_12AF1\n     3_012\n     11_12AB3\n\\end{verbatim} \\end{tt}\n\nWhile raw bits can be used to implement many data types,\nhere we are only concerned with numbers.  Unsigned numbers\nbuild up as binary numbers, for $0 \\dots (2^{32} - 1)$.  Signed numbers\nare represented in 2's complement form, for $-2^{31} \\dots (2^{31} -\n1)$.  See Craw87, pg 7 for details.\n\nThe critical thing to know about 2's complement is that the\n32nd bit is used to indicate sign.  Thus, it is not\navailable for use in building number magnitudes.  Modula-3\nreflects this by making {\\tt CARDINAL}  go $0 \\dots (2^{31} -1)$, \nmaking it a subtype of {\\tt INTEGER}.  What about unsigned numbers from\n$2^{31} \\dots (2^{32}-1)$?  You must use Word.T for those, and use the\nWord module's operations.  While these look like function\ncalls (and thus slow), they are really compiled inline as\nthe obvious assembler statisticements.\n\nWhat can go wrong?  Integer matrix is a sure thing, so long as\nyou don't overflow (e.g., go beyond $2^{31}-1$ for {\\tt CARDINAL}) or\nunderflow (e.g., go below $0$ for {\\tt CARDINAL}s or $-2^{32}$ for\n{\\tt INTEGER}s).  Modula-3 traps these conditions, but you should\nplan your algorithm to avoid the conditions.  Use multi-\nprecision packages if you need more resolution.\n\nFor m3na, we will use {\\tt CARDINAL}s when we mean counting\nnumbers (such as for array indices), and {\\tt INTEGER}s when we\nmean quantities which might be negative.\n\n\\subsection{Floating Point Unit (FPU)}\nSee Craw87, pp 20-30.\n\nThe 387 FPU provides IEEE 32-bit, 64-bit, and 80-bit reals.\nThese are structured as a sign bit, an exponent, and a\nsignificand (also known as mantissa):\n\\begin{verbatim}\n     32-bit\n          sign        =1 bit\n          exponent    =8 bits\n          significand =23 bits (really 24 due to hidden 1)\n          range       =+/- 3.39E38\n          precision   =+/-1.18E-38\n     \n     64-bit\n          sign        =1 bit\n          exponent    =11 bits\n          significand =52 (really 53 due to hidden 1)\n          range       =+/- 1.08E308\n          precision   =+/- 2.23E-308\n     \n     80-bit\n          sign        =1 bit\n          exponent    =15 bits\n          significand =64 bits\n          range       =+/- 1.19E4932\n          precision   =+/- 3.36E-4932\n\\end{verbatim}\n\nThere are several problems in using these finite\nrepresentations for real numbers.\n\\begin{description}\n\\item[Out of Range]\n     Suppose you want to represent one googol (1.0E100).  It\n     just can't be done in the 32-bit format.  That may seem\n     fanciful for practical problems, but intermediate\n     values (e.g., sums of squares) might go beyond the 32-\n     bit limits.\n\n\\item[Representation Error]\n     Many decimal numbers do not convert exactly to/from\n     binary.  You have to use a representation whose\n     precision is sufficient that this error is not a\n     problem.\n\n\\item[Truncation Error]\n     Suppose you add two numbers in 32-bit format: $a=1.0e6$ and $b=1.00123$.\n     \n     To get a valid addition, we would need to get both a\n     and b into the significand, both with the same\n     exponent: $(1.0+0.00000100123)*10^6 = 1.00000100123e6$.\n     There aren't enough bits in the significand to\n     represent this.  It gets truncated to: $1.000001e6$.\n     \n     What we need to know is how small one number can be\n     relative to another before part of the smaller gets\n     lopped off.  This small amount is usually known as\n     $\\epsilon$ (epsilon).  The value is differnet for various\n     representations, giving EPS32, EPS64, and EPS80.\n     These are calculated as:\n     \\begin{verbatim}\n          max = 2^sigbits\n          rel prec = 1/max = 2^(-sigbits)=~ sigbits * ln(2)/ln(10)\n          \n          32-bit: about 1.0E-7 = ESP32\n          64-bit: about 1.0E-17= EPS64\n          80-bit: about 1.0E-24= EPS80\n     \\end{verbatim}\n     \n     As a consequence, there is no point in trying to tune\n     an iteration solution beyond a certain point, e.g.:\n     \\begin{tt} \\begin{verbatim}\n         IF delta < value*EPS32 THEN\n            EXIT; (*can't do any better*)\n         ELSE\n            value:=value+delta; (*room for improvement*)\n         END;\n     \\end{verbatim} \\end{tt}\n     \n     Truncation can happen as in the above example with\n     addition and subtraction.  It can also happen with\n     multiplication.  This is particularly true for\n     intermediate values (such as squares).  It is worth\n     your while to arrange to normalize the calculation\n     toward 1.0 before doing multiplications.  Or use a\n     longer real format.\n\n\\item[Roundoff Error]\n     If you are in danger of truncating, you may round up or\n     down.  If the rounding is not done right, it will\n     introduce a bias into the calculation.\n     \n     Fortunately, Modula-3 reals are specified as IEEE\n     reals, which include extra digits to assure proper\n     rounding.\n\\end{description}\n\n\\subsection{32-bit vs 64-bit}\nIs REAL32 good enough?  NR92, pg 25, suggests it is, and in\nfact uses 32-bit reals for its printed algorithms.\n\nHowever, Gems90 uses 64-bit reals, despite operating in a\nspeed-driven environment with low end-result resolution\n(viewable by human eye).  Hopkins says:\n\\begin{quote}\n     \"Generally, if the real arithmetic has a mantissa of\n     less than about 30 bits, then a double precision\n     version of the library is produced.  In fact the double\n     precision [64-bit] version is by far the most common,\n     since most architectures which mimic IBM floating-point\n     hardware and the IEEE floating-point standard all\n     define the mantissa of real variables to be around 24\n     bits.  This accuracy is not sufficient for reliable\n     numerical computation.\"  Hopk88, pg 34.\n\\end{quote}\n\nFurther, the Modula-3 Math library is 64-bit.  Thus it\nappears the choice is REAL64.\n\n\\subsection{Timing}\nEach machine will have different timing for its hardware\nALU and FPU operations, and each compiler will have\ndifferent approaches for calling upon these operations (thus\nfurther diversifying timing).  However, it is probable that\nfor the class of problems we are addressing, we can\ndetermine the rough relative timing cost for operations.\n\nCraw87 provides timing data in the appendices.  While every\ncombination of source/dest is slightly different, we can use\nthe \"best-case\" for the register-to-memory operation as the\nexemplar.  If we normalize the cycles to let integer add (32\nbit) be \"1\", and round to integers, the ratios are:\n\\begin{verbatim}\n     iadd32         1\n     imul32         5\n     idiv32         6\n     fadd32         3\n     fadd64         4\n     fmul32         4\n     fmul64         5\n     fdiv32         12\n     fdiv64         13\n\\end{verbatim}\n\nIn other words, integers are a lot faster than floating-\npoint, and divide is the killer.  Interestingly, 64-bit is\nnot much worse than 32-bit.  Thus our choice of 64-bit as\nthe basic format is not all that extravagant.\n\n\n\\subsection{Development Approach}\nHere is our approach to developing routines:\n\\begin{enumerate}\n     \\item Pick an interesting topic.  If you aren't\n     interested, you won't stick with it long enough to do a\n     good job.\n     \n     \\item Gather relevant sources (e.g., texts, code\n     libraries, journal articles).  Determine an effective\n     user interface.  Determine test cases from known-good\n     sources such as matrix packages or handbooks.\n     \n     \\item Study the problem until you can explain the standard\n     implementation(s) line by line.  You may need to work\n     backwards and forwards from the mathematical formulas\n     to the code.  You typically need to work out simple\n     (but not too simple) examples, e.g., 4x4 matrix.\n     \n     \\item Study the iterative operations for truncation\n     conditions.  Do you need to renormalize the data toward\n     1.0?  Do EPS checks?  Use a longer real format?\n     \n     \\item Implement your version of the algorithm.\n     \\begin{enumerate}\n          \\item Test it for basic correctness against known\n          good values.  Don't worry about being off by a few\n          parts in a thousand.  At this stage you should be\n          concerned with wildly wrong results.  If it made\n          sense on paper, and you got it to compile, then\n          chances are it is a fencepost error (off-by-one)\n          in the iteration conditions.  Debug as needed.\n          \n          \\item Test for full accuracy against known-good\n          values.  Does your algorithm fall apart with big\n          or little numbers?  Is it erratic?  Check for\n          truncation errors and more fencepost errors.\n          Debug as needed.\n          \n          \\item Test for speed against published algorithms.\n          Use the Time module and multi-second runs.\n       \\end{enumerate}\n\\end{enumerate}\n\nWhen it comes time to worry about truncation errors and\ntiming, look for normalization toward the center of the\nrange.  The classic is the hypotenuse of a right triangle:\n\\begin{verbatim}\n          hyp:=sqrt(a^2 + b^2); (*where a>b*)\n          (*a^2 is in danger of producing an overflow\n            although the final result\n            is perfectly in the representable range.*)\n          \n          (*Instead, do:*)\n          r:=(b/a);\n          hyp:=abs(a)*sqrt(1.0+r*r);\n\\end{verbatim}\n\nWhen it comes time to worry about speed, consider:\n\\begin{enumerate}\n     \\item Precalculate anything you can:\n     \\begin{itemize}\n          \\item Compile-time constant propagation\n          \\item Runtime initialization\n          \\item Calltime initialization\n          \\item Outer loop instead of inner loop\n          \\item Common subexpressions\n      \\end{itemize}\n\n     \\item Unroll loops, especially if you know the algorithm will\n     only need a few iterations.\n\\end{enumerate}\n     \nDo you really need to do these things?  Modern compilers\nknow a great deal about such local optimizations.  If you\ncan do it and the code becomes more readable and more\nmaintainable, then do so.  But don't screw up clean code for\na few percent speedup.  You will still be debugging when a\nfaster computer shows up on your desk.  Instead use your\ntime looking for fundamentally better algorithms.  If you\nstill need speed, get out your assembler.\n", "meta": {"hexsha": "9a958b043d55a43793d20955d1512cda7f9422e1", "size": 13180, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "m3-libs/arithmetic/doc/concept.tex", "max_stars_repo_name": "jaykrell/cm3", "max_stars_repo_head_hexsha": "2aae7d9342b8e26680f6419f9296450fae8cbd4b", "max_stars_repo_licenses": ["BSD-4-Clause-UC", "BSD-4-Clause", "BSD-3-Clause"], "max_stars_count": 105, "max_stars_repo_stars_event_min_datetime": "2015-03-02T16:58:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T07:17:49.000Z", "max_issues_repo_path": "m3-libs/arithmetic/doc/concept.tex", "max_issues_repo_name": "jaykrell/cm3", "max_issues_repo_head_hexsha": "2aae7d9342b8e26680f6419f9296450fae8cbd4b", "max_issues_repo_licenses": ["BSD-4-Clause-UC", "BSD-4-Clause", "BSD-3-Clause"], "max_issues_count": 145, "max_issues_repo_issues_event_min_datetime": "2015-03-18T10:08:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T01:27:08.000Z", "max_forks_repo_path": "m3-libs/arithmetic/doc/concept.tex", "max_forks_repo_name": "jaykrell/cm3", "max_forks_repo_head_hexsha": "2aae7d9342b8e26680f6419f9296450fae8cbd4b", "max_forks_repo_licenses": ["BSD-4-Clause-UC", "BSD-4-Clause", "BSD-3-Clause"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2015-10-10T09:37:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T02:02:05.000Z", "avg_line_length": 37.4431818182, "max_line_length": 77, "alphanum_fraction": 0.6861911988, "num_tokens": 3479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.30271106987308793}}
{"text": "\\section{Analysis}\n\\label{sec:analysis}\nIn this section we analyze the structural properties of HINs and classification tasks. We first describe three classification tasks,\nwhich are used in our analysis. Then, we explain the concepts of \\chn\\ and \\cnn, and propose quantitative measures to \ncapture these properties.\n\n%In the end of section Introduction, we put forward three questions. Before we involve in the third one to predict whether transductive classification will work on a given HIN or not, we should first investigate the first two which would uncover the factors leading to a good transductive classification. Based on the aforementioned datasets: DBLP, Yago Movie and Freebase Movie, extensive experiments have been conducted, which provides sufficient grounds to our in-depth and logical analysis.\n\n\\subsection{Classification tasks}\n\n\\textbf{DBLP}\\footnote{http://dblp.uni-trier.de/} is a bibliographic information network. \nWe extracted a dataset from DBLP that contains 14,376 papers (P), 20 publication venues (V), 14,475 authors (A) and \n8,920 terms (T). \nThese form the objects of the HIN. \nThere are three types of links, which are authorship (A-P), publication (P-V), and keyword (P-T).\nThe task is to classify authors into their research areas. \nThe label set is \\{\\emph{database} (DB), \\emph{data mining} (DM), \\emph{artificial intelligence} (AI) and\n\\emph{information retrieval} (IR) \\}.\n%Both \\hpm\\ and \\gm\\ use \nWe use the set of meta-paths \\{APA, APAPA, APVPA, APTPA\\} \nas suggested in \\cite{DBLP:dblp_conf/kdd/SunNHYYY12}.\n%Four research areas: \\emph{database}, \\emph{data mining}, \\emph{artificial intelligence} and \\emph{information retrieval} are regarded as labels, and 4057 authors have been labeled by them. Links in the network are of three types: paper-author, paper-venue and paper-term. To classify authors, we use the meta path set $\\mathcal{PS}$ = \\{APA, APAPA, APVPA, APTPA\\} suggested in \\cite{DBLP:dblp_conf/kdd/SunNHYYY12} when applying HetPathMine and Grempt.\n\n\\textbf{Yago Movie} is a movie related HIN extracted from Yago. The dataset contains 1,465 movies (M), 4,019 actors (A), 1,093 directors (D) and 1,458 writers (W). There are three types of links: M-A, M-D, and M-W. \nAll of the extracted movies can be classified into one of three genres: \\emph{horror}, \\emph{action} and \\emph{adventure}.\nThe task is to label movies into their genres.\nWe use the meta-path set \\{MAM, MDM, MWM, MAMAM, MDMDM, MWMWM\\} as suggested\nin~\\cite{DBLP:dblp_conf/cikm/WanLKYGCH15}.\n\n%All the movies are labeled with regard to three genres: \\emph{horror}, \\emph{action} and \\emph{adventure}. In order to classify movies, similar to \\cite{DBLP:dblp_conf/cikm/WanLKYGCH15}, we employ the meta path set $\\mathcal{PS}$ = \\{MAM, MDM, MWM, MAMAM, MDMDM, MWMWM\\}.\n\n\\textbf{Freebase Movie} is another movie related HIN extracted from Freebase. \nIt consists of 3,492 movies (M), 33,401 actors (A), 2,502 directors (D) and 4,459 producers (P). \nThere are three types of links: M-A, M-D, and M-P.\nThe task is again to label movies into their genres. \nThe label set is \\{\\emph{action}, \\emph{adventure} and \\emph{crime}\\}.\nWe use the meta-path set \\{MAM, MDM, MPM, MAMAM, MDMDM, MPMPM\\}~\\cite{DBLP:dblp_conf/cikm/WanLKYGCH15}.\n\n\\subsection{Structural properties of an HIN}\n\nTransductive classification on networked data utilizes links and paths to evaluate the relatedness of objects.\nObjects that are highly related are assumed to share similar labels. \nIn a sense, links and paths are used to\npropagate labels from labeled objects\nto unlabeled ones. \nAlgorithms like \\gnm\\ use the HIN to propagate labels, while algorithms like \\hpm\\ and \\gm\\ use\nmeta-paths to derive TSSNs and propagate labels on those sub-networks. \nIn any case, the network structure (of the original HIN or of the derived TSSNs) is\nan important factor of the effectiveness of \\tcrs.\nIn particular, \nall these \\tcrs\\ share the following intrinsic assumption:\n\\begin{assumption}\n{\\bf The Connectivity Assumption}.\nThe structural connectivity between two objects (via links and paths) \nare highly correlated to whether the objects would share the same label. \n\\end{assumption}\nIn this section we address two interesting questions:\n\n{\\it Question 1}:\nDoes the connectivity assumption generally hold for HIN classification tasks?\n\n{\\it Question 2}:\nIf not, how to measure the validity of the connectivity assumption given a classification task?\n\n\nTo answer the first question, we conducted simple experiments on a number of classification tasks.\nFirst, we define {\\it true-labeling} using the notations of Definition~\\ref{def:labeling}:\n\n\\begin{definition}\n{\\bf True-labeling}.\nA labeling $\\hat{L}$ is a true-labeling if \n$\\forall x \\in \\mathcal{X}_i$, $\\hat{L}(x)$ is the true label (ground truth) of object $x$.\n\\end{definition}\nWe put a caret `$\\wedge$' on a labeling $L$ to indicate that it is a true-labeling.\nFor each of the three classification tasks DBLP, Yago Movie and Freebase Movie,\nwe find the true-labeling $\\hat{L}$.\nWe then cluster objects into the\nlabel-induced clustering $\\mathcal{C}_{\\hat{L}}$ (see Definition~\\ref{def:li-clustering}). \nEach cluster in $\\mathcal{C}_{\\hat{L}}$ thus contains all and only those objects of a given label.\n\n\\begin{table}\n\\caption{Similarity (NMI) of $\\mathcal{C}_{\\hat{L}}$ and $\\mathcal{C}_{\\mathit{NetClus}}$}\n\\centering\n\\small\n\\begin{tabular}{|c|c|c|c|} \\hline\n DBLP & Yago Movie & Freebase Movie \\\\ \\hline\n$0.707$ & $0.018$ & $0.027$ \\\\ \\hline\n\\end{tabular}\n\\label{table:global_nmi}\n\\end{table}\n\n\nNext, we apply NetClus~\\cite{DBLP:dblp_conf/kdd/SunYH09}, which is a clustering method\nthat clusters objects in an HIN based on network structure, to our HINs.\nFor each HIN, we compare the true-label-induced clustering $\\mathcal{C}_{\\hat{L}}$\n(which is based solely on object labels) with\nthe clustering $\\mathcal{C}_{\\mathit{NetClus}}$, given by NetClus (which is based solely on network structure).\nThe similarity of the two clusterings is measured by  \nnormalized mutual information (NMI).\nTable~\\ref{table:global_nmi} shows the results.\nWe see that for DBLP, the NMI is high, indicating that $\\mathcal{C}_{\\hat{L}}$ and $\\mathcal{C}_{\\mathit{NetClus}}$\nare highly similar. \nIn other words, objects that are highly connected (put in the same cluster by NetClus) tend to share the same label\n(put in the same cluster by the true-label-induced clustering).\nThe connectivity assumption is thus strongly valid. \nOn the other hand, for Yago Movie and Freebase Movie, the NMI's are very low, indicating that\nthe connectivity assumption does not hold in those cases.  \nThis analysis is consistent with the accuracies of the \\tcrs\\ when they are applied to the three\nclassification tasks (see Table~\\ref{tbl:xlong}).\nOur analysis leads to the following conclusion:\n\n\\begin{conclusion}\nThe connectivity assumption does not always hold across HIN classification tasks. When it does, \\tcrs\\ \nare very effective.\n\\end{conclusion}\n\nThe next question we address is how the validity of the connectivity assumption is evaluated.   \nWe propose to measure the correlation between {\\it structural connectivity of objects} and their {\\it label similarity} by \nthe concepts of \\chn\\ and \\cnn. \nIntuitively, given a classification task,\nan HIN is {\\it highly cohesive} if strong connectivity occurs mostly between objects of the same label;\nand that the HIN is {\\it highly connected} if objects of the same label exhibit strong connectivity.\nThe correlation between structural connectivity and label similarity is thus high if the HIN is highly cohesive and highly connected.\nIn the following discussion, we first assume that the true-labeling $\\hat{L}$ of a classification task is known.\nCohesiveness and \\cnn\\ are then defined based on a true-labeling. \nWe will discuss in Section~\\ref{sec:tester} how the two measures can be estimated when the true-labeling is not known in practice. \n\n\\subsection{Cohesiveness}\n\nGiven an HIN $G=(V,E)$,\nconsider the  task of classifying objects $x \\in \\mathcal{X}_i$ of type $T_i$ \nwith the label set $\\mathcal{L} = \\{l_1, ..., l_k\\}$.\nA \\tcr\\ propagates label from an object $x_u \\in \\mathcal{X}_i$ to another \nobject $x_v \\in \\mathcal{X}_i$. \nHow much this propagation is done depends on the structural connectivity (i.e., links and paths) between $x_u$ and $x_v$.\nFor example, \\hpm\\ and \\gm\\ use meta-paths to derive TSSNs (see Figure~\\ref{figure:subnetworks}),\nand for each TSSN $G_{\\mathcal{P}}$,  which is derived from a meta-path $\\mathcal{P}$, \nthe structural connectivity between $x_u$ and $x_v$ is measured using \\emph{PathSim} \\cite{DBLP:dblp_journals/pvldb/SunHYYW11}:\n\n{\\small\n\\begin{equation}\n\\nonumber\n\\label{eq:pathsim}\ns(x_u, x_v) = \\frac{2 \\times |\\{p_{x_u \\leadsto x_v}:p_{x_u \\leadsto x_v} \\in \\mathcal{P}\\}|}{|\\{p_{x_u \\leadsto x_u}:p_{x_u \\leadsto x_u} \\in \\mathcal{P}\\}|+|\\{p_{x_v \\leadsto x_v}:p_{x_v \\leadsto x_v} \\in \\mathcal{P}\\}|}.\n\\end{equation}}\n\nNow, let us consider the true-label-induced clustering $\\mathcal{C}_{\\hat{L}}$. \nFigure~\\ref{figure:special_network} shows an example clustering with 2 clusters (objects with true label `$\\Circle$' and those with\ntrue label `$\\Box$').\nAn edge, e.g., ($x_1$,$x_2$), is shown to indicate that two objects are structurally connected\n(e.g., they are connected by meta-paths). \nWe assume that each edge shown is associated with a weight, which reflects the strength of the connection\n(e.g., as measured using \\emph{PathSim}).\nWe call Figure~\\ref{figure:special_network} a {\\it structural connectivity graph}.\n\nNote that \\tcrs\\ that use meta-paths \n(such as \\hpm\\ and \\gm) \nmeasure the connectivity between two\nobjects based on how well the objects are connected by meta-paths. In this case, the structural connectivity graph can be\nseen as a composition (union) of the TSSNs derived from a given set of meta-paths. \nFor example, the structural connectivity graph of the movie HIN shown in Figure~\\ref{figure:subnetworks}(a)\nis the composition of the TSSNs shown in Figures~\\ref{figure:subnetworks}(c)-(e).\nIn particular, the edge connecting M1 and M2 in Figure~\\ref{figure:subnetworks}(c) indicates that\nM1 and M2 are structurally connected by a meta-path instance (M1-A1-M2).\nIf M1 is labeled,\nthe label will be propagated to M2 via the structural connection (M1,M2).\nWe will discuss how an overall \\chn\\ value is measured when the structural connectivity graph is a composition of \nmultiple TSSNs shortly. For the moment, let us assume that there is only one connectivity graph derived.\n\nAs mentioned, \nan HIN is highly cohesive if strong connectivity occurs mostly between objects of the same label.\nReferring to Figure~\\ref{figure:special_network}, that means \nintra-cluster edges are many-and-strong, while \ninter-cluster edges are few-and-weak.\nFigure~\\ref{figure:special_network} shows a very cohesive HIN because\nthere is only one edge ($x_1,y_1$) across the two clusters; most of the structural connections are between objects of the same label.\nWith this intuition, we quantitatively define \\chn\\ as follows.\n\n\n%By exploring the aforementioned questions, we next unveil factors influencing transductive classification in HINs.\n%\\begin{question}\n%In which kinds of heterogeneous information networks will transductive classification perform well?\n%\\end{question}\n%\n%Transductive classification on networked data depends on the network structure to propagate labels from labeled objects to unlabeled ones. Moreover, objects with the same label usually have features in common and they can be put in the same cluster. So it is natural to assume that if a network has very good clustering structure, then transductive classification will perform well. A good clustering structure refers to that objects with the same label are densely connected and form a cluster. Furthermore, no inter-cluster edge exists. Such structure will benefit transductive classification in that one labeled object is enough for each cluster to infer labels of all the unlabeled objects within the cluster. Based on the above analysis, we assume:\n%\n%\\begin{assumption}\n%When a heterogeneous information network intrinsically has good clustering structure, transductive classification will be effective.\n%\\end{assumption}\n%\n%To study the clustering property of the network, labels of objects are taken as the ground truth. We use label to mark the cluster an object belongs to and divide objects to be classified into different clusters. For example, action-genre movies are deemed in the same cluster, authors with research interest on data mining are in the same cluster, etc.\n%\n%We first validate the assumption by taking the HIN as a whole. Since the network is heterogeneous, traditional clustering methods will not work. We resort to NetClus \\cite{DBLP:dblp_conf/kdd/SunYH09}, a specialized clustering method for heterogeneous information network with star schema, to perform clustering. Normalized mutual information (NMI) is used as the measure. The result is shown in table \\ref{table:global_nmi}. It is obvious that DBLP network has a better clustering structure than other two datasets, which to some extent reflects our assumption.\n%\n\n%To further verify our assumption, we pay attention to meta path. Since meta path has been successfully used in transductive classification methods Grempt and HetPathMine, we can also employ it to measure the clustering property of an HIN. Similarly, given an HIN, we first induce several topology shrinking sub-networks by meta paths. Each sub-network will be homogeneous which contains only the objects of the type to be classified. For each sub-network, objects with the same label are considered in the same cluster. So clusters are same in these sub-networks. As we have mentioned above, if there are more edges within clusters and fewer edges between clusters, then transductive classification will perform well.\n%\n%After sub-networks have been derived, both HetPathMine and Grempt use \\emph{PathSim} \\cite{DBLP:dblp_journals/pvldb/SunHYYW11} to measure the similarity between any two objects $x_1$ and $x_2$ in the network. For a meta path $\\mathcal{P}$ induced sub-network, \\emph{PathSim} is defined as:\n%\n%{\\small\n%\\begin{equation}\n%\\nonumber\n%\\label{eq:pathsim}\n%s(x_1, x_2) = \\frac{2 \\times |\\{p_{x_1 \\leadsto x_2}:p_{x_1 \\leadsto x_2} \\in \\mathcal{P}\\}|}{|\\{p_{x_1 \\leadsto x_1}:p_{x_1 \\leadsto x_1} \\in \\mathcal{P}\\}|+|\\{p_{x_2 \\leadsto x_2}:p_{x_2 \\leadsto x_2} \\in \\mathcal{P}\\}|}\n%\\end{equation}}\n%\n%\\noindent where $p_{x_1 \\leadsto x_2}$ is a path instance between $x_1$ and $x_2$, $p_{x_1\\leadsto x_1}$ is that between $x_1$ and $x_1$, and $p_{x_2\\leadsto x_2}$ is that between $x_2$ and $x_2$. Then transductive classification is performed on each sub-network and finally integrated. Label propagation heavily depends the weights between objects, the larger the value, the more one will be influenced by the other. Inspired by this, we find that sometimes edge count is not enough to reflect how good transductive classification will be. Larger weights within clusters and smaller weights between clusters are also required. An example is shown in figure \\ref{figure:special_network}. There exist a number of intra-cluster edges in both clusters and only one inter-cluster edge between node $A$ and $B$. Suppose the weight on $e_{AB}$ is very large, then weights on other edges in both clusters will be very small. This means that $A$ and $B$ will be greatly influenced by each other. Assume $A$ has been influenced by $B$. After that, even though we know the label of node $C$, it can not propagate to other nodes within the cluster, because it is blocked by $A$.\n\n%\\comment{\n%\\begin{figure}[htbp]\n%\\centering\n%\\mbox{\n%  \\hspace{-0.6cm}\n%  \\begin{minipage}[t]{0.55\\linewidth}\n%     %\\centering\n%     \\includegraphics[width = \\linewidth]{figure/homo.pdf}\n%     \\caption{Topology shrinking sub-network}\n%     \\label{figure:homo}\n%  \\end{minipage}\n%  \\begin{minipage}[t]{0.55\\linewidth}\n%     %\\centering\n%     \\includegraphics[width = \\linewidth]{figure/edge_weights.pdf}\n%     \\caption{A special network}\n%     \\label{figure:special_network}\n%  \\end{minipage}\n%  }\n%\\end{figure}\n%}\n\\begin{figure}\n    \\centering\n        \\includegraphics[width = 0.5\\linewidth]{figure/weights_new.pdf}\n        \\caption{A structural connectivity graph}\n        \\label{figure:special_network}\n\\end{figure}\n\n%Combining intuition and characteristic of transductive classification, we propose that for any two clusters, if intra-cluster edges are dense and inter-cluster edges are sparse, transductive classification will perform well. Here, dense and sparse refer to two measures: the number of edges and the weights of edges. We have mentioned that an HIN can induce several sub-networks and these sub-networks have same clusters indicated by labels. Then we can measure the clustering property in a reverse order of cluster, sub-network and finally HIN.\n%\\begin{definition}\nGiven two clusters $C_1$ and $C_2$ in a true-label-induced clustering $\\mathcal{C}_{\\hat{L}}$,\nwith respect to a structural connectivity graph,\nlet $h_1$ ($h_2$) be the number of intra-cluster edges in $C_1$ ($C_2$) with a sum of edge weights\n$w_1$ ($w_2$). \nAlso, let $h_{1,2}$ be the number of inter-cluster edges between $C_1$ and $C_2$ with a \nsum of edge weights $w_{1,2}$.\nDefine,\n%\n%For any two clusters $C_1$ and $C_2$, $C_1$ has $h_1$ intra-cluster edges with total weights $w_1$, $C_2$ has $h_2$ intra-cluster edges with total weights $w_2$. There are $h_{1,2}$ inter-cluster edges between them with total weights $w_{1,2}$. Then\n%\\emph{intra-inter edge ratio} for each cluster is defined as \n\\begin{equation}\n\\label{eq:edge_ratio}\n\\rho(C_1) = \\frac{h_1}{h_{1,2}+h_1}, \\;\\;\\; \\rho(C_2) = \\frac{h_2}{h_{1,2}+h_2}, \\mbox{  and }\n\\end{equation}\n%\\emph{intra-inter edge weights ratio} for each cluster is defined as \n\\begin{equation}\n\\label{eq:weights_ratio}\n\\eta(C_1) = \\frac{w_1}{w_{1,2}+w_1}, \\;\\;\\; \\eta(C_2) = \\frac{w_2}{w_{1,2}+w_2}. \\mbox{        }\n\\end{equation}\n$\\rho(C_1)$ can be interpreted as, ``Among all the edges that connect some objects in $C_1$, the fraction of which that connect {\\it only}\nobjects in $C_1$.'' The other quantities can be interpreted similarly. \n%To facilitate label propagation, both ratios are expected to be large enough in both clusters. To avoid that one value is extremely large and others are small, \nWe further define the \\emph{pairwise cluster cohesiveness} of $C_1$ and $C_2$: \n\\begin{equation}\n\\label{eq:inter-cluster_cohesiveness}\n\\Upsilon(C_1, C_2) = \\rho(C_1) \\times \\rho(C_2) \\times \\eta(C_1) \\times \\eta(C_2).\n\\end{equation}\n%\\end{definition}\n\nFor a classification task with $k$ labels, \na labeling induces $k$ clusters $C_1, ..., C_k$.\nLet $b_i = |C_i|$.\nDefine the \\emph{cluster cohesiveness} of $C_i$ by\n\\begin{equation}\n\\label{eq:cluster_cohesiveness}\n\\Upsilon_{C_i} = \\frac{1}{k-1}\\sum_{j\\neq i}\\Upsilon(C_i, C_j).\n\\end{equation}\n%and the \\emph{cohesiveness vector} \nLet $\\bm{\\Upsilon} = (\\Upsilon_{C_1}, ..., \\Upsilon_{C_k})^\\mathrm{T}$. \n%$\\bm{\\Upsilon_{G_\\mathcal{P}}^\\prime} = (\\Upsilon_{C_1}, \\Upsilon_{C_2}, ..., \\Upsilon_{C_N})^\\mathrm{T}$. \nWe define the \\chn\\ of an HIN $G$ as the weighted average of the cluster cohesiveness:\n%Since $G_\\mathcal{P}$ consists of $N$ clusters, then we have \\emph{sub-network cluster cohesiveness vector} $\\bm{\\Upsilon_{G_\\mathcal{P}}^\\prime} = (\\Upsilon_{C_1}, \\Upsilon_{C_2}, ..., \\Upsilon_{C_N})^\\mathrm{T}$. \n%And \\emph{sub-network cohesiveness} is the weighted average for clusters:\n\\begin{equation}\n\\label{eq:subnetwork_cohesiveness}\n\\Upsilon_{G} = \\bm{\\beta}\\bm{\\Upsilon},\n\\end{equation}\nwhere $\\bm{\\beta} = (\\frac{b_1}{\\sum_{i=1}^k b_i}, \\frac{b_2}{\\sum_{i=1}^k b_i}, ..., \\frac{b_k}{\\sum_{i=1}^k b_i})$.\n\nIf we use a set of meta-paths $\\mathcal{P}_1, ..., \\mathcal{P}_r$ in \\tc, the structural connectivity graph can be seen as a composition of \na number of TSSNs $G_{\\mathcal{P}_j}$ (1 $\\leq j \\leq r$).\nIn this case, we evaluate the cohesiveness of each TSSN to obtain $\\Upsilon_{G_{\\mathcal{P}_j}}$,\nassign a weight $\\theta_j$ to each meta-path $\\mathcal{P}_j$, and the overall\ncohesiveness is given by the weighted average:\n\\begin{equation}\n\\Upsilon_{G} = \\sum_{j=1}^r \\theta_j \\Upsilon_{G_{\\mathcal{P}_j}}.\n\\end{equation}\nWe assume that the weights $\\theta_j$'s can be learned. \nDue to space limitation,\nreaders can refer to~\\cite{DBLP:dblp_conf/ecir/LuoGWL14,DBLP:dblp_conf/sdm/WanOKH15,DBLP:dblp_conf/cikm/WanLKYGCH15} for some example methods for learning meta-path weights.\n\nWe computed the \\chn\\ values of the three HIN classification tasks. Table~\\ref{table:chn} shows the results.\nWe see that  DBLP has a much higher \\chn\\ value ($\\Upsilon_{\\mathit{DBLP}}$ = 0.536) \ncompared with Yago ($\\Upsilon_{\\mathit{Yago}}$ = 0.209) and Freebase ($\\Upsilon_{\\mathit{Freebase}}$ = 0.185).\nAgain, this is consistent with our analysis that the connectivity assumption is more valid \nwith DBLP than with Yago or Freebase. \nIn Table~\\ref{table:chn}, we also show the \\chn\\ values of the TSSNs derived from various meta-paths. \nFor example, \nfor DBLP, the TSSN $G_{\\mathit{APA}}$, derived from the meta-path APA, is much more cohesive than\nthose given by other meta-paths. \nThe interpretation is that co-authorship (which is captured by the meta-path APA) \noccurs mostly between authors of the same area. \nOn the other hand, the small \\chn\\ value of $G_{\\mathit{APTPA}}$ indicates that\nauthors of different areas could share the same keywords in their papers. \nFor Yago Movie and Freebase Movie,\nthe meta-paths MDM and MDMDM derive the most cohesive TSSNs. \nYet, their \\chn\\ values are much smaller than that of APA,\nsuggesting that it is more difficult for \\tc\\ to achieve high accuracy in classifying movies.\n\n%Interestingly, these observations are consistent with those given in~\\cite{DBLP:dblp_conf/cikm/WanLKYGCH15},\n%which reveal that APA, MDM, and MDMDM are effective meta-paths in\n%classifying objects for the three classification tasks. \n\n\\begin{table}\n\\centering\n\\caption{Cohesiveness of HIN classification tasks}\n\\tiny\n\\begin{tabular}{|c|c|c|c|c|c|c|}  \\hline\n\\multicolumn{7}{|c|}{DBLP: $\\Upsilon_{\\mathit{DBLP}}$ = 0.536} \\\\ \\hline\n$\\mathcal{P}$ & APA & APAPA & APVPA & APTPA  & & \\\\ \\hline\n$\\Upsilon_{G_\\mathcal{P}}$ & $0.733$ & $0.483$ & $0.393$ & $0.016$ & & \\\\ \\hline \\hline\n\\multicolumn{7}{|c|}{Yago: $\\Upsilon_{\\mathit{Yago}}$ = 0.209} \\\\ \\hline\n$\\mathcal{P}$ & MAM & MDM & MWM & MAMAM  & MDMDM & MWMWM  \\\\ \\hline\n$\\Upsilon_{G_\\mathcal{P}}$ & $0.106$ & $0.313$ & $0.262$ & $0.065$ & $0.303$ & $0.214$  \\\\ \\hline \\hline\n\\multicolumn{7}{|c|}{Freebase: $\\Upsilon_{\\mathit{Freebase}}$ = 0.185 } \\\\ \\hline\n$\\mathcal{P}$ & MAM & MDM & MPM & MAMAM & MDMDM & MPMPM \\\\ \\hline\n$\\Upsilon_{G_\\mathcal{P}}$ & $0.107$ & $0.326$ & $0.174$ & $0.086$ & $0.346$ & $0.123$ \\\\ \\hline\n\\end{tabular}\n\\label{table:chn}\n\\end{table}\n\n\n%By meta paths, we can derive several topology shrinking sub-networks from an HIN. So it is natural to measure the clustering property of an HIN from that of derived sub-networks.\n%\n%\\begin{definition}\n%Given an HIN $G$ and $K$ meta paths, $K$ sub-networks can be induced, which share $N$ clusters $C_1$, $C_2$, $...$, $C_N$. Each cluster $C_i$ contains $b_i$ objects, $i = 1, 2, ..., N$. For an arbitrary cluster $C_i$, we use $\\bm{\\theta_i}$ = ($\\theta_{i_1}$, $\\theta_{i_2}, ..., \\theta_{i_K})^\\mathrm{T}$ to represent weights of $K$ sub-networks. Let $\\bm{\\Upsilon}$ = ($\\bm{\\Upsilon_{G_{\\mathcal{P}_1}}}$, $\\bm{\\Upsilon_{G_{\\mathcal{P}_2}}}$, ..., $\\bm{\\Upsilon_{G_{\\mathcal{P}_K}}})^\\mathrm{T}\\in R^{K \\times N}$, $\\bm{\\theta}$ = ($\\bm{\\theta_1}$, $\\bm{\\theta_2}$, ..., $\\bm{\\theta_N})\\in R^{K\\times N}$, then \\emph{HIN cluster cohesiveness vector} is defined as\n%\\begin{equation}\n%\\bm{\\Upsilon_G^\\prime} = (\\bm{\\theta_1^\\mathrm{T}}\\bm{\\Upsilon}[:,1], \\bm{\\theta_2^\\mathrm{T}}\\bm{\\Upsilon}[:,2], ..., \\bm{\\theta_N^\\mathrm{T}}\\bm{\\Upsilon}[:,N])^\\mathrm{T}\n%\\end{equation}\n%and \\emph{HIN cohesiveness} is the weighted average for clusters:\n%\\begin{equation}\n%\\label{eq:HIN_cohesiveness}\n%\\Upsilon_G = \\bm{\\beta^\\mathrm{T}}\\bm{\\Upsilon_G^\\prime}\n%\\end{equation}\n%where $\\bm{\\beta} = (\\frac{b_1}{\\sum_{i=1}^N b_i}, \\frac{b_2}{\\sum_{i=1}^N b_i}, ..., \\frac{b_N}{\\sum_{i=1}^N b_i})^\\mathrm{T}$.\n%\\end{definition}\n\n%\\begin{table}\n%\\centering\n%\\scriptsize\n%\\caption{DBLP sub-network cohesiveness}\n%\\label{table:DBLP_cohesiveness}\n%\\begin{tabular}{|c|c|c|c|} \\hline\n% APA & APAPA & APVPA & APTPA \\\\ \\hline\n%$0.733$ & $0.483$ & $0.393$ & $0.016$\\\\ \\hline\n%\\end{tabular}\n%\\centering\n%\\caption{Yago Movie sub-network cohesiveness}\n%\\label{table:yagomovie_cohesiveness}\n%\\begin{tabular}{|c|c|c|c|c|c|} \\hline\n% MAM & MDM & MWM & MAMAM & MDMDM & MWMWM\\\\ \\hline\n%$0.106$ & $0.313$ & $0.262$ & $0.065$ & $0.303$ & $0.214$\\\\ \\hline\n%\\end{tabular}\n%\\centering\n%\\caption{Freebase Movie sub-network cohesiveness}\n%\\label{table:freebasemovie_cohesiveness}\n%\\begin{tabular}{|c|c|c|c|c|c|} \\hline\n% MAM & MDM & MPM & MAMAM & MDMDM & MPMPM\\\\ \\hline\n%$0.107$ & $0.326$ & $0.174$ & $0.086$ & $0.346$ & $0.123$\\\\ \\hline\n%\\end{tabular}\n%\\centering\n%\\caption{HIN cohesiveness on three datasets}\n%\\label{table:hin_cohesiveness}\n%\\begin{tabular}{|c|c|c|c|} \\hline\n% DBLP & Yago Movie & Freebase Movie \\\\ \\hline\n%$0.536$ & $0.209$ & $0.185$ \\\\ \\hline\n%\\end{tabular}\n%\\end{table}\n\n%Based on meta path, \\emph{cohesiveness} is a new measure to how cohesive an HIN is. Experimental results are shown in table \\ref{table:hin_cohesiveness}. Obviously, DBLP has larger cohesiveness value than other two networks, so transductive classification performs better on it, which proves our assumption. Based on the above analysis, both NetClus and cohesiveness reflect DBLP has better clustering structure. Then we make a summary: \n%\n%\\textbf{Summary:} An HIN with better clustering structure will lead to better transductive classification.\n%\n%We also show cohesiveness value of each sub-network on three HINs in tables \\ref{table:DBLP_cohesiveness}, \\ref{table:yagomovie_cohesiveness} and \\ref{table:freebasemovie_cohesiveness}. We notice that sub-networks induced by APA, MDM and MDMDM are more cohesive. It reflects these meta paths are more effective, which coincides with the conclusion in \\cite{DBLP:dblp_conf/cikm/WanLKYGCH15}. \n\n%\\textcolor{blue}{Ben: The following is to be removed:\n%xxxxxxxxxxxxxx}\n%\n%Since sub-networks derived by APA, MDM and MDMDM have larger cohesiveness values, transductive classification should perform better on them. However, according to tables \\ref{table:accuracy:dblp_subnetworks}, \\ref{table:accuracy:yago_subnetworks} and \\ref{table:accuracy:freebase_subnetworks}, we notice that transductive classification on sub-networks derived by APVPA, MAM and MAMAM greatly outperforms that on other sub-networks. For meta paths APA, MDM and MDMDM, even though their induced sub-networks have larger cohesiveness values, transductive classification works poorly, which can be explained by the conclusion in \\cite{DBLP:dblp_conf/cikm/WanLKYGCH15} that the average percentage of reachable objects from a given object by a meta path, referring to \\emph{reach}, is too small. Furthemore, we perform \\emph{normalized cuts} \\cite{DBLP:dblp_conf/cvpr/ShiM97} on each sub-network and use NMI to be the measure. Tables \\ref{table:DBLP_nmi}, \\ref{table:yagomovie_nmi} and \\ref{table:freebasemovie_nmi} show the results. We observe that sub-network induced by APVPA is better clustered than sub-network corresponding to APA in DBLP. Also MDM and MDMDM are not always better than others. These observations further reflect the poor reach of meta paths APA, MDM and MDMDM.\n%\n%\\begin{table}\n%\\centering\n%\\scriptsize\n%\\caption{NMI on sub-networks of DBLP}\n%\\label{table:DBLP_nmi}\n%\\begin{tabular}{|c|c|c|c|} \\hline\n% APA & APAPA & APVPA & APTPA \\\\ \\hline\n%$0.025$ & $0.010$ & $0.654$ & $0.067$\\\\ \\hline\n%\\end{tabular}\n%\\centering\n%\\caption{NMI on sub-networks of Yago Movie}\n%\\label{table:yagomovie_nmi}\n%\\begin{tabular}{|c|c|c|c|c|c|} \\hline\n% MAM & MDM & MWM & MAMAM & MDMDM & MWMWM\\\\ \\hline\n%$0.010$ & $0.024$ & $0.004$ & $0.053$ & $0.019$ & $0.002$\\\\ \\hline\n%\\end{tabular}\n%\\centering\n%\\caption{NMI on sub-networks of Freebase Movie}\n%\\label{table:freebasemovie_nmi}\n%\\begin{tabular}{|c|c|c|c|c|c|} \\hline\n% MAM & MDM & MPM & MAMAM & MDMDM & MPMPM\\\\ \\hline\n%$0.186$ & $0.005$ & $0.003$ & $0.214$ & $0.014$ & $0.009$\\\\ \\hline\n%\\end{tabular}\n%\\end{table}\n%\n%\\begin{table}\n%\\centering\n%\\tiny\n%\\caption{Classification accuracy on sub-networks in DBLP}\n%\\label{table:accuracy:dblp_subnetworks}\n%\\resizebox{\\linewidth}{!}\n%{\n%%\\hspace{-0.5cm}\n%\\begin{tabular}{|c|c|c|c|c|} \\hline\n% percent of & \\multirow{2}{*}{APA} & \\multirow{2}{*}{APAPA} & \\multirow{2}{*}{APVPA} & \\multirow{2}{*}{APTPA}\\\\ \n%labeled authors&&&&\\\\\\hline\n%$0.1\\%$ & $33.0\\%$ & $33.7\\%$ & $81.7\\%$ & $30.0\\%$\\\\ \\hline\n%$0.2\\%$ & $37.3\\%$ & $38.1\\%$ & $89.0\\%$ & $31.7\\%$\\\\ \\hline\n%$0.3\\%$ & $39.6\\%$ & $41.5\\%$ & $89.8\\%$ & $33.3\\%$\\\\ \\hline\n%$0.4\\%$ & $41.8\\%$ & $42.7\\%$ & $90.3\\%$ & $34.4\\%$\\\\ \\hline\n%$0.5\\%$ & $42.8\\%$ & $44.0\\%$ & $91.1\\%$ & $35.3\\%$\\\\ \\hline\n%\\end{tabular}\n%}\n%\\caption{Classification accuracy on sub-networks in Yago Movie}\n%\\label{table:accuracy:yago_subnetworks}\n%\\resizebox{1.05\\linewidth}{!}\n%{\n%%\\hspace{-0.5cm}\n%\\begin{tabular}{|c|c|c|c|c|c|c|} \\hline\n% percent of & \\multirow{2}{*}{MAM} & \\multirow{2}{*}{MDM} & \\multirow{2}{*}{MWM} & \\multirow{2}{*}{MAMAM} & \\multirow{2}{*}{MDMDM} & \\multirow{2}{*}{MWMWM}\\\\ \n%labeled movies&&&&&&\\\\\\hline\n%$1\\%$ & $35.9\\%$ & $1.0\\%$ & $2.4\\%$ & $34.9\\%$ & $1.0\\%$ & $2.6\\%$ \\\\ \\hline\n%$2\\%$ & $39.1\\%$ & $2.1\\%$ & $4.6\\%$ & $39.1\\%$ & $2.0\\%$ & $4.7\\%$ \\\\ \\hline\n%$3\\%$ & $40.6\\%$ & $3.0\\%$ & $6.2\\%$ & $40.7\\%$ & $3.1\\%$ & $6.2\\%$ \\\\ \\hline\n%$4\\%$ & $40.8\\%$ & $3.9\\%$ & $7.6\\%$ & $41.0\\%$ & $3.9\\%$ & $7.5\\%$ \\\\ \\hline\n%$5\\%$ & $41.5\\%$ & $4.8\\%$ & $8.8\\%$ & $41.3\\%$ & $4.8\\%$ & $8.7\\%$ \\\\ \\hline\n%\\end{tabular}\n%}\n%\\caption{Classification accuracy on sub-networks in Freebase Movie}\n%\\label{table:accuracy:freebase_subnetworks}\n%\\resizebox{1.05\\linewidth}{!}\n%{\n%%\\hspace{-0.5cm}\n%\\begin{tabular}{|c|c|c|c|c|c|c|} \\hline\n% percent of & \\multirow{2}{*}{MAM} & \\multirow{2}{*}{MDM} & \\multirow{2}{*}{MPM} & \\multirow{2}{*}{MAMAM} & \\multirow{2}{*}{MDMDM} & \\multirow{2}{*}{MPMWPM}\\\\ \n%labeled movies&&&&&&\\\\\\hline\n%$1\\%$ & $63.5\\%$ & $1.4\\%$ & $9.2\\%$ & $63.7\\%$ & $1.2\\%$ & $9.6\\%$ \\\\ \\hline\n%$2\\%$ & $64.0\\%$ & $2.7\\%$ & $10.8\\%$ & $64.3\\%$ & $2.7\\%$ & $11.0\\%$ \\\\ \\hline\n%$3\\%$ & $64.5\\%$ & $3.8\\%$ & $12.3\\%$ & $65.2\\%$ & $3.8\\%$ & $12.1\\%$ \\\\ \\hline\n%$4\\%$ & $65.1\\%$ & $5.0\\%$ & $13.1\\%$ & $65.5\\%$ & $5.0\\%$ & $13.4\\%$ \\\\ \\hline\n%$5\\%$ & $65.7\\%$ & $6.1\\%$ & $14.1\\%$ & $66.0\\%$ & $6.1\\%$ & $14.4\\%$ \\\\ \\hline\n%\\end{tabular}\n%}\n%\\end{table}\n%From table \\ref{table:hin_cohesiveness}, we also find that the cohesiveness of Yago Movie is larger than that of Freebase Movie, but transductive classification performs better on Freebase Movie. Based on new observations, we conclude that cohesiveness is an important factor to transductive classification, but it is not the only one. Since \\emph{reach} can affect transductive classification, we propose another assumption.\n%\n%\\begin{assumption}\n%For a heterogeneous information network, if objects to be classified are more connected, transductive classification will perform better.\n%\\end{assumption}\n%\n%\\textcolor{blue}{xxxxxxxxxxx}\n\n\\subsection{Connectedness}\nWe say that an HIN is highly connected if objects of the same label exhibit {\\it strong connectivity}.\nWith respect to \\tc, this connectivity should facilitate label propagation from one object to another of the same class.\nTo illustrate the idea, consider Figure~\\ref{figure:compactness}, which shows two object clusters ($\\Circle$ and $\\Box$) in\na structural connectivity graph.\nWe see that objects in the $\\Box$ cluster are strongly connected in the sense that if\nan object in the cluster (say $y_1$) is labeled, the label can be propagated effectively to all other objects in the same cluster.\nThe $\\Circle$ cluster, on the other hand, is less connected. \nIn particular, if we consider only the intra-cluster edges of the $\\Circle$ cluster, the $\\Circle$ objects form two isolated components.\nIf object $x_1$ in component 1 is labeled, the label cannot be propagated to the objects in component 2 (e.g., $x_2$)\nwithout going through the $\\Box$ cluster.\nLabel propagation among the $\\Circle$ objects is thus less effective.\n\nWe measure the \\cnn\\ of a cluster $C$ by the number of disconnected components ($\\mathit{NDC}(C)$) in $C$ \nif only intra-cluster edges are considered.\nFor example, in Figure~\\ref{figure:compactness}, the NDC of the $\\Circle$ cluster is 2, while that of the $\\Box$ cluster is 1.\nThe larger $\\mathit{NDC}(C)$ is, the less is the \\cnn\\ of cluster $C$.\nWe normalize this measure to [0,1] and define {\\it cluster connectedness}, $\\Psi_C$:\n\n%We still divide objects to be classified into different clusters indicated by their labels. Intuitively, if objects within a cluster are connected, label propagation will be promoted. On the contrary, if objects within a cluster are scattered in many disconnected components, label propagation will be blocked between components, which hinders transductive classification. As shown in figure \\ref{figure:compactness}, cluster in black contains three components and each component is fully connected. Suppose the label of object B in component 2 is known, but it cannot be directly propagated to components 1 and 3 without going through A. It is more likely that objects in components 1 and 3 to be influenced by A but not B.\n\n\\begin{figure}\n    \\centering\n        \\includegraphics[width = 0.5\\linewidth]{figure/Q1_compactness_new.pdf}\n        \\caption{An example illustrating \\cnn}\n        \\label{figure:compactness} %% label for entire figure\n\\end{figure}\n\n%To measure the connectivity of an HIN, we still utilize meta paths to derive sub-networks which contain same clusters. Similar to cohesiveness, we first measure the connectivity of a cluster in a sub-network.\n\n%\\begin{definition}\n%For any cluster $C$ with $b$ objects, $count(C)$ represents the number of components within it. Obviously, $1\\leq count(C)\\leq b$. If $count(C) = 1$, all the objects are connected. If $count(C) = b$, all the objects are isolated. Intuitively, the connectivity of a cluster is inversely proportional to $count$ value. In addition, when two clusters have the same $count > 1$, it is reasonable to consider the one with more objects is more compact. Therefore, \\emph{cluster compactness} is defined to measure the connectivity of a cluster:\n\\begin{equation}\n\\label{eq:cluster_compactness}\n\\Psi_C=\\left\\{ \\begin{array}{ll}\n               1& \\mbox{ when } \\mathit{NDC}(C) = 1,\\\\\n               1-\\frac{\\mathit{NDC}(C)}{b}& \\mbox{ when } \\mathit{NDC}(C) > 1,\\\\\n              \\end{array}\n       \\right.\n\\end{equation}\n%\\end{definition}\nwhere $b$ is the number of objects in $C$.\n\nIf there are $k$ clusters $C_1, ..., C_k$, corresponding to  $k$ labels of a classification task, \nlet $\\bm{\\Psi} = (\\Psi_{C_1}, \\Psi_{C_2}, ..., \\Psi_{C_k})^\\mathrm{T}$. \nWe define the \\cnn\\ of an HIN $G$ as the weighted average of the cluster \\cnn:\n%\\begin{definition}\n%For a meta path $\\mathcal{P}$ induced sub-network $G_{\\mathcal{P}}$, suppose there are $N$ clusters $C_1, C_2, ..., C_N$. Each cluster $C_i$ contains $b_i$ objects, $i = 1, 2, ..., N$.\n%Since $G_\\mathcal{P}$ consists of $N$ clusters, then we have \\emph{sub-network cluster compactness vector} $\\bm{\\Psi_{G_\\mathcal{P}}^\\prime} = (\\Psi_{C_1}, \\Psi_{C_2}, ..., \\Psi_{C_N})^\\mathrm{T}$. \n%And \\emph{sub-network compactness} is the weighted average for clusters:\n\\begin{equation}\n\\Psi_G = \\bm{\\beta}\\bm{\\Psi},\n\\end{equation}\nwhere $\\bm{\\beta} = (\\frac{b_1}{\\sum_{i=1}^k b_i}, \\frac{b_2}{\\sum_{i=1}^k b_i}, ..., \\frac{b_k}{\\sum_{i=1}^k b_i})$.\n%\\end{definition}\n\nSimilar to our discussion of \\chn,\nif we use meta-paths $\\mathcal{P}_1, ..., \\mathcal{P}_r$ in \\tc, we evaluate \n $\\Psi_{G_{\\mathcal{P}_j}}$ for each TSSN $G_{\\mathcal{P}_j}$.\nThe overall\n\\cnn\\ of an HIN $G$ is the weighted average:\n\\begin{equation}\n\\Psi_{G} = \\sum_{j=1}^r \\theta_j \\Psi_{G_{\\mathcal{P}_j}},\n\\end{equation}\nwhere $\\theta_j$'s are the meta-path weights.\n\nTable~\\ref{table:cnn} shows the \\cnn\\ values of our classification tasks. \nThe \\cnn\\ of the TSSN derived from each meta-path considered is also shown.\nFrom the table, we see that DBLP has a much higher \\cnn\\ value (0.942) compared with\nYago (0.393) and Freebase (0.584). \nThis means that authors of the same area mostly form a single structurally connected component.\nThe label of one author can therefore be very effectively propagated to other authors of the same area via meta-paths. \nComparing the four meta-paths used in DBLP, we see that the \\cnn\\ values of APVPA and APTPA are even higher than that of APA.\nThe interpretation is that authors of the same area tend to attend the same conferences and use similar keywords in their papers,\nbut they do not necessarily co-author with each other. \nFor Yago Movie and Freebase Movie, we see that MAM and MAMAM give relatively high \\cnn\\ values,\nindicating that movies of the same genre tend to be starred by the same actors. \nHowever, the two movie HINs are generally much less connected than DBLP. \n\n\\begin{table}\n\\caption{Connectedness of HIN classification tasks}\n\\centering\n\\tiny\n\\begin{tabular}{|c|c|c|c|c|c|c|}  \\hline\n\\multicolumn{7}{|c|}{DBLP: $\\Psi_{\\mathit{DBLP}}$ = 0.942} \\\\ \\hline\n$\\mathcal{P}$ & APA & APAPA & APVPA & APTPA  & & \\\\ \\hline\n$\\Psi_{G_\\mathcal{P}}$ & $0.899$ & $0.920$ & $1.0$ & $1.0$ & & \\\\ \\hline \\hline\n\\multicolumn{7}{|c|}{Yago: $\\Psi_{\\mathit{Yago}}$ = 0.393} \\\\ \\hline\n$\\mathcal{P}$ & MAM & MDM & MWM & MAMAM  & MDMDM & MWMWM  \\\\ \\hline\n$\\Psi_{G_\\mathcal{P}}$ & $0.567$ & $0.253$ & $0.281$ & $0.690$ & $0.253$ & $0.285$  \\\\ \\hline \\hline\n\\multicolumn{7}{|c|}{Freebase: $\\Psi_{\\mathit{Freebase}}$ = 0.584 } \\\\ \\hline\n$\\mathcal{P}$ & MAM & MDM & MPM & MAMAM & MDMDM & MPMPM \\\\ \\hline\n$\\Psi_{G_\\mathcal{P}}$ & $0.970$ & $0.282$ & $0.350$ & $0.992$ & $0.282$ & $0.382$ \\\\ \\hline\n\\end{tabular}\n\\label{table:cnn}\n\\end{table}\n\nNow, let us study how \\chn\\ and \\cnn\\ \nare correlated to classification accuracy. We apply \\gm\\ on the three classification tasks.\nFor each one,\nwe further obtain the accuracy when only one meta-path (and its derived TSSN) is used.\nTable~\\ref{table:acc} shows the results.\nFor example,  if \\gm\\ uses only the meta-path APA to derive \nthe structural connectivity between objects in DBLP, the classification accuracy is 42.8\\%;\nIf all four meta-paths are considered, then \\gm\\ achieves an accuracy of 89.3\\%.\nNote that for DBLP, the training set is much smaller (0.5\\%) than that of Yago Movie and Freebase Movie (5\\%).\n\n\\begin{table}\n\\caption{Accuracies of applying \\gm\\ to HINs}\n\\centering\n\\tiny\n\\begin{tabular}{|c|c|c|c|c|c|c|}  \\hline\n\\multicolumn{7}{|c|}{DBLP: 0.5\\% labeled objects, classification accuracy = 89.3\\%}  \\\\ \\hline\n$\\mathcal{P}$ & APA & APAPA & APVPA & APTPA  & & \\\\ \\hline\nacc. &42.8\\% &44.0\\% & 91.1\\% & 35.3\\% & & \\\\ \\hline \\hline\n\\multicolumn{7}{|c|}{Yago: 5\\% labeled objects, classification accuracy = 49.2\\%}  \\\\ \\hline\n$\\mathcal{P}$ & MAM & MDM & MWM & MAMAM  & MDMDM & MWMWM  \\\\ \\hline\nacc. & $41.5\\%$ & $4.8\\%$ & $8.8\\%$ & $41.3\\%$ & $4.8\\%$ & $8.7\\%$  \\\\ \\hline \\hline\n\\multicolumn{7}{|c|}{Freebase: 5\\% labeled objects, classification accuracy = 65.4\\%}  \\\\ \\hline\n$\\mathcal{P}$ & MAM & MDM & MPM & MAMAM & MDMDM & MPMPM \\\\ \\hline\nacc. &  $65.7\\%$ & $6.1\\%$ & $14.1\\%$ & $66.0\\%$ & $6.1\\%$ & $14.4\\%$ \\\\ \\hline\n\\end{tabular}\n\\label{table:acc}\n\\end{table}\n\nFrom Tables~\\ref{table:chn}, \\ref{table:cnn}, \\ref{table:acc}, we draw the following observations:\n\n\\noindent{\\bf (1)} The \\chn\\ and \\cnn\\ of DBLP are both much higher than those of Yago and Freebase, and\nthe classification accuracy of DBLP (89.3\\%) is also much higher than those of Yago (49.2\\%) and Freebase (65.4\\%).\n\n\\noindent{\\bf (2)} For DBLP, the meta-path APVPA gives the highest accuracy (91.1\\%). This is because its TSSN is the most\nconnected (1.0) and is reasonably cohesive (0.393, which is higher than any \\chn\\ values in Yago or Freebase).\n\n\\noindent{\\bf (3)} The accuracy of the TSSN due to meta-path APTPA (35.3\\%) is much lower than that of APVPA (91.1\\%) although \nboth of them are perfect in their \\cnn\\ scores (1.0). The reason is that the \\chn\\ value of APTPA is\nextremely low (0.016). This indicates that, with APTPA, although a label propagates well among objects within the same\ncluster (high \\cnn), the label also propagates over to other clusters as well (very low \\chn).\n\n\\noindent{\\bf (4)} For Yago and Freebase, although MDM and MDMDM give relatively cohesive TSSNs ($\\Upsilon$: 0.303-0.346)\namong all meta-paths for the two tasks,\nthe TSSNs are highly disconnected ($\\Psi$: 0.253-0.282).\nThis explains why the classification accuracies using only MDM or MDMDM are so poor (6.1\\%).\n\nFrom these observations, we can conclude that  \\chn\\ and \\cnn\\ are highly correlated with classification accuracy. \nAlso, both factors are important to the successful application of \\tcrs.\n\n\n\n%\\begin{definition}\n%Given an HIN $G$ and $K$ meta paths, we first derive $K$ sub-networks which share $N$ clusters $C_1$, $C_2$, $...$, $C_N$. Each cluster $C_i$ contains $b_i$ objects, $i = 1, 2, ..., N$. For an arbitrary cluster $C_i$, we use $\\bm{\\theta_i} = (\\theta_{i_1}, \\theta_{i_2}, ..., \\theta_{i_K})^\\mathrm{T}$ to represent weights of $K$ sub-networks. Let $\\bm{\\Psi}$ = ($\\bm{\\Psi_{G_{\\mathcal{P}_1}}}$, $\\bm{\\Psi_{G_{\\mathcal{P}_2}}}$, ..., $\\bm{\\Psi_{G_{\\mathcal{P}_K}}})^\\mathrm{T}$$\\in R^{K \\times N}$, $\\bm{\\theta}$ = ($\\bm{\\theta_1}$, $\\bm{\\theta_2}$, ..., $\\bm{\\theta_N}$)$\\in R^{K\\times N}$, then \\emph{HIN cluster compactness vector} is defined as\n%\\begin{equation}\n%\\bm{\\Psi_G^\\prime} = (\\bm{\\theta_1^\\mathrm{T}}\\bm{\\Psi}[:,1], \\bm{\\theta_2^\\mathrm{T}}\\bm{\\Psi}[:,2], ..., \\bm{\\theta_N^\\mathrm{T}}\\bm{\\Psi}[:,N])^\\mathrm{T}\n%\\end{equation}\n%and \\emph{HIN compactness} is the weighted average for clusters:\n%\\begin{equation}\n%\\label{eq:HIN_compactness}\n%\\Psi_G = \\bm{\\beta^\\mathrm{T}}\\bm{\\Psi_G^\\prime}\n%\\end{equation}\n%where $\\bm{\\beta} = (\\frac{b_1}{\\sum_{i=1}^N b_i}, \\frac{b_2}{\\sum_{i=1}^N b_i}, ..., \\frac{b_N}{\\sum_{i=1}^N b_i})^\\mathrm{T}$.\n%\\end{definition}\n\n%\\emph{Compactness} reflects how connected a network is. The experimental results are shown in tables \\ref{table:DBLP_compactness}, \\ref{table:yagomovie_compactness}, \\ref{table:freebasemovie_compactness} and \\ref{table:hin_compactness}. We observe that \n%\\newline{\\small $\\bullet$} sub-networks derived by APVPA, MAM and MAMAM are more compact, thus transductive classification performs better on them.\n%\\newline{\\small $\\bullet$} For APTPA, even though the compactness is large, the cohesiveness is too small, which largely reduces classification accuracy.\n%\\newline{\\small $\\bullet$} DBLP has the largest compactness value, so transductive classification performs best on it.\n%\\newline{\\small $\\bullet$} Compactness of Freebase Movie is much larger than that of Yago Movie, which explains why transductive classification performs better in Freebase Movie.\n%\n%\\begin{table}\n%\\centering\n%\\scriptsize\n%\\caption{DBLP sub-network compactness}\n%\\label{table:DBLP_compactness}\n%\\begin{tabular}{|c|c|c|c|} \\hline\n% APA & APAPA & APVPA & APTPA \\\\ \\hline\n%$0.899$ & $0.920$ & $1.0$ & $1.0$\\\\ \\hline\n%\\end{tabular}\n%\\centering\n%\\caption{Yago Movie sub-network compactness}\n%\\label{table:yagomovie_compactness}\n%\\begin{tabular}{|c|c|c|c|c|c|} \\hline\n% MAM & MDM & MWM & MAMAM & MDMDM & MWMWM\\\\ \\hline\n%$0.567$ & $0.253$ & $0.281$ & $0.690$ & $0.253$ & $0.285$\\\\ \\hline\n%\\end{tabular}\n%\\centering\n%\\caption{Freebase Movie sub-network compactness}\n%\\label{table:freebasemovie_compactness}\n%\\begin{tabular}{|c|c|c|c|c|c|} \\hline\n% MAM & MDM & MPM & MAMAM & MDMDM & MPMPM\\\\ \\hline\n%$0.970$ & $0.282$ & $0.350$ & $0.992$ & $0.282$ & $0.382$\\\\ \\hline\n%\\end{tabular}\n%\\centering\n%\\caption{HIN compactness on three datasets}\n%\\label{table:hin_compactness}\n%\\begin{tabular}{|c|c|c|c|} \\hline\n% DBLP & Yago Movie & Freebase Movie \\\\ \\hline\n%$0.942$ & $0.393$ & $0.584$ \\\\ \\hline\n%\\end{tabular}\n%\\end{table}\n%\n%These observations prove assumption 2 and we summarize:\n%\n%\\textbf{Summary:} An HIN with compact connectivity will result in good performance of transductive classification. \n%\n%\\input{tex/question3.tex}\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "db74cc853ed5ceb18359b154410056692ce4fb59", "size": 44412, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/HINGCN/tex/analysis.tex", "max_stars_repo_name": "dingdanhao110/HINGCN", "max_stars_repo_head_hexsha": "281b73c03bd3b00e35bce4c5e1c27076233555e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paper/HINGCN/tex/analysis.tex", "max_issues_repo_name": "dingdanhao110/HINGCN", "max_issues_repo_head_hexsha": "281b73c03bd3b00e35bce4c5e1c27076233555e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/HINGCN/tex/analysis.tex", "max_forks_repo_name": "dingdanhao110/HINGCN", "max_forks_repo_head_hexsha": "281b73c03bd3b00e35bce4c5e1c27076233555e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 63.9942363112, "max_line_length": 1279, "alphanum_fraction": 0.7154823021, "num_tokens": 14308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.30271106987308793}}
{"text": "\\documentclass[12pt,english]{article}\n\n\\input{../fragments/preamble_one.tex}\n\\input{../fragments/preamble_two.tex}\n\n% Special String Shorthands\n\\input{../fragments/shorthand/short_text.tex}\n\\input{../fragments/shorthand/short_math.tex}\n\n% Numbers as Newcommands\n\\input{../fragments/stats/stats_one.tex}\n\n% Citation\n\\input{../fragments/cite/cite_preamble.tex}\n\\bibliography{../_bib/ref_one, ../_bib/ref_two, ../_bib/zotero}\n\n\\makeatother\n\n\\begin{document}\n\n\\title{Paper Name}\n\n\\author{Fan Wang\\thanks{Department of Economics, University of Houston (email: fwang26@uh.edu)}}\n\n\\maketitle\n\\begin{abstract}\n\\singlespacing This is my abstract \\end{abstract}\n\\vfill\n\\pagebreak{}\n\n\\section{Introduction}\n\nAccording to \\textcite{becker_human_1986}, ipsum dolor sit amet, consectetur adipiscing elit. Integer placerat nunc orci, id pellentesque lacus ullamcorper at. Mauris venenatis gravida magna non dapibus. Nullam vel consequat purus, id luctus dui. Suspendisse vel auctor nulla. Proin ipsum felis, efficitur eu eleifend vitae, efficitur pellentesque mauris \\autocite{case_lasting_2005, conti_understanding_2010}.\n\n\\section{Model}\n\nLet $\\tau$ be the fraction of poorest children receiving price discounts and $\\delta$ be the percentage price discount that children receive. $Z\\left(\\tau,\\delta\\right)$ is the total cost of a subsidy in grams of protein for 1970, 1972, 1974 and 1976 cohorts, given reference point distribution $\\Gamma$ for each cohort:\n\n\\begin{equation}\n\\label{eq:targetcost}\nZ\\left(\\tau,\\delta\\right) =\n\\sum\\limits_{\n\t\\substack{\n\t\\mathrm{cohort} \\\\ \\in{\\left\\{70,72,74,76\\right\\}}}\n\t}\n\\left\\{\\delta\\cdot\n\\int_{\\epsilon}\n\\int_{Y_{min}}^{F_{Y}^{-1}\\left(\\tau\\right)}\n\\int_{X}\nN\\Big(\n\\substack{\n\tY,X,\\epsilon; \\\\\n\t\\delta, \\Gamma_{\\mathrm{cohort}}\n}\n\\Big)f\\left(X|Y\\right)f\\left(Y\\right)f\\left(\\epsilon\\right)\\mathrm{d}X\\mathrm{d}Y\\mathrm{d}\\epsilon\\right\\}\n\\end{equation}\nAs described earlier, we fix the joint distribution of the state space variables across cohorts, and so only the reference point distribution $\\Gamma$ is cohort-specific in Equation \\ref{eq:targetcost}. We start $\\Gamma_{1970}$ as mentioned using the actual reference points in year 1970 from Atole villages, and solve for subsequent reference point distributions following Equation \\ref{eq:hmeasure}.\n\n\\section{Data}\n\nLet $\\tau$ be the fraction of poorest children receiving price discounts and $\\delta$ be the percentage price discount that children receive. $Z\\left(\\tau,\\delta\\right)$ is the total cost of a subsidy in grams of protein for 1970, 1972, 1974 and 1976 cohorts, given reference point distribution $\\Gamma$ for each cohort:\n\n\\begin{equation}\n\\label{eq:targetcost}\nZ\\left(\\tau,\\delta\\right) =\n\\sum\\limits_{\n\t\\substack{\n\t\\mathrm{cohort} \\\\ \\in{\\left\\{70,72,74,76\\right\\}}}\n\t}\n\\left\\{\\delta\\cdot\n\\int_{\\epsilon}\n\\int_{Y_{min}}^{F_{Y}^{-1}\\left(\\tau\\right)}\n\\int_{X}\nN\\Big(\n\\substack{\n\tY,X,\\epsilon; \\\\\n\t\\delta, \\Gamma_{\\mathrm{cohort}}\n}\n\\Big)f\\left(X|Y\\right)f\\left(Y\\right)f\\left(\\epsilon\\right)\\mathrm{d}X\\mathrm{d}Y\\mathrm{d}\\epsilon\\right\\}\n\\end{equation}\nAs described earlier, we fix the joint distribution of the state space variables across cohorts, and so only the reference point distribution $\\Gamma$ is cohort-specific in Equation \\ref{eq:targetcost}. We start $\\Gamma_{1970}$ as mentioned using the actual reference points in year 1970 from Atole villages, and solve for subsequent reference point distributions following Equation \\ref{eq:hmeasure}.\n\n\n\\section{Conclusion}\n\n\\pagebreak\n\\input{../fragments/cite/cite_end.tex}\n\\pagebreak\n\n\\appendix\n\\section{Data Figures and Tables}\n\n\n\\end{document}\n", "meta": {"hexsha": "6e29e7781cf5a793eb941a53437635a7d357a54d", "size": 3604, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "singlefile_article/article_fan.tex", "max_stars_repo_name": "guohui-jiang/Tex4Econ", "max_stars_repo_head_hexsha": "7bdbfb29e956d31239bd592b6392574e4aec5c15", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "singlefile_article/article_fan.tex", "max_issues_repo_name": "guohui-jiang/Tex4Econ", "max_issues_repo_head_hexsha": "7bdbfb29e956d31239bd592b6392574e4aec5c15", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "singlefile_article/article_fan.tex", "max_forks_repo_name": "guohui-jiang/Tex4Econ", "max_forks_repo_head_hexsha": "7bdbfb29e956d31239bd592b6392574e4aec5c15", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9368421053, "max_line_length": 410, "alphanum_fraction": 0.7566592675, "num_tokens": 1060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.30271106987308793}}
{"text": "\\documentclass[11pt]{article}\n\n%\n% Set the page size.\n%\n\\topmargin -0.5in \\headsep 0.251in\n\\hoffset -0.8in\n\\marginparwidth 0in \\marginparsep 0in\n\\textheight 9.5in \\textwidth 6.5in\n\\parindent 0pt\n\\parskip 8pt plus 1pt minus 1pt\n\\pagestyle{headings}\n\n\\begin{document}\n\n\\title{Proposal to add UV-plane model fitting to Difmap.}\n\n\\author{Martin Shepherd (mcs@phobos.caltech.edu)\\\\\n\tCopyright \\copyright 1994 California Institute of Technology}\n\n\\date{}\n\\maketitle\n\n\\clearpage\n\n\\section{Introduction}\n\nIt is common practice in VLBI to parameterize maps by fitting simple\nmodels directly to the source UV data. These models may be used as\nplausible starting models for self-calibration, or to augment the\nCLEAN/self-calibration mapping loop by removing the kinds of extended\nstructure that CLEAN has difficulty describing.\n\nAn existing program that has been used extensively in VLBI to fit\nmodels to UV data, is the modelfit program in the ``Caltech VLBI\nPackage'' \\cite{tjp91}. This program is capable of fitting models\ncomposed of aggregates of up to 15 simple components, each component\nbeing chosen from a list that includes delta-functions, elliptical\ngaussians and elliptical tapered-disks. The free parameters of the\nmodel are adjusted to minimize the value of $\\chi^{2}$ formed between\nthe UV-plane representation of the model and the measured amplitudes\nand closure-phases. The use of closure phases rather than raw phase\nmakes modelfit immune to station-based phase mis-calibrations.\nModelfit does have some faults. Its two least-squares minimization\nalgorithms are not optimal and for the best fits and fast convergence\nit relies on the coincidental match between the data and the arbitrary\niteration step sizes used. The use of closure-phases also requires\nlarge amounts of memory and CPU time, amounts that grow as the cube of\nthe number of stations in the data, times the number of integrations.\n\nWhile Difmap still used the same data format as the rest of the\nCaltech VLBI package, no real need for a new model fitting algorithm\nwas deemed necessary in Difmap. But now that Difmap uses FITS as its\ndata format, observations that make use of the multiple dimensions\nthat FITS allows but the Caltech merge format does not, can not be\nmodel fitted by the modelfit program. It is with this in mind that a\nnew model fitting algorithm to be incorporated in difmap is to be\nwritten.\n\n\\section{Requirements}\n\nGiven that a new model fitting implementation is required, it would be\nshort sighted to simply re-produce the algorithms used in the modelfit\nprogram without examining alternative techniques. One such technique\nwhich purportedly incorporates the strengths of both of the algorithms\nused in the modelfit program, and which has the extra advantage that\nstep sizes are automatically determined, is the Levenberg-Marquardt\nmethod. This is described in \\cite{nr} and will be adopted for the new\nimplementation.\n\nThe Levenberg-Marquardt technique requires equations for the partial\nderivatives of the UV-plane model representation with respect to all\nfree parameters, rather than determining them numerically as the\nmodelfit gradient search algorithm does. The next section derives\nthese equations.\n\nUnlike the modelfit program, the new algorithm will be designed to\nfit models directly to the measured real and imaginary parts of the\ncomplex visibilities. The advantage gained is mainly one of speed,\nmemory requirements and simplicity. In addition, the errors are more\nlikely to be Gaussian distributed than say those of the measured\namplitudes. The main disadvantage is that the program will not be\nimmune to station based phase mis-calibration. However fringe-fitting,\nself-calibration and phase-referencing techniques have improved to the\nextent that this should not be a significant problem.\n\nIt has been decided that the new algorithm will fit component\npositions in a Cartesian rather than a polar coordinate system,\nalthough initial guesses will still be presented in the established\npolar form. This removes the problem of what to do if the model\nfitting algorithm produces negative radii. The similar problem of what\nto do if the sizes or aspect ratios of components go out of bounds\nremains un-answered.\n\nA useful feature that does not exist in the modelfit program, is the\nestimation of the uncertainties in the fitted parameters. This is not\nas straight forward as might be expected, since the free parameters\ncan turn out to be correlated. The full generality of this problem\nwill be met in the new algorithm by optionally printing out the\ncovariance matrix, thus leaving the onus on the user to interpret the\nresults.\n\n\\section{Partial derivatives of UV plane models.}\n\nAdopting the Levenberg-Marquardt algorithm requires a knowledge of the\npartial derivatives of the functions being fitted, calculated\nseparately with respect to each free parameter. This section will\nserve to derive such equations.\n\nA single model component of flux $S$, placed at the center of the\nimage plane can be represented in the UV plane by a function of form:\n\n\\begin{equation}\nF(u,v) = S f(u,v)\n\\end{equation}\n\nWhere $(u,v)$ is a position in the UV plane. From the {\\em shift\ntheorem} of Fourier transforms we know that the same component whose\ncentroid has been shifted to a position $(x,y)$ in the image plane\nappears in the UV plane as:\n\n\\begin{equation}\nF(u,v) = S f(u,v) e^{2 \\pi i (u x + v y)}\n\\end{equation}\n\nBy the {\\em addition theorem} of Fourier transforms we also know that\nan aggregate model $M(u,v)$ can be formed from a sum of $n$ individual\ncomponents as:\n\n\\begin{equation}\nM(u,v) = \\sum^{n}_{i=1} S_{i} f_{i}(u,v) e^{2 \\pi i (u x_{i} + v y_{i})}\n\\end{equation}\n\nThe partial derivative of $M(u,v)$ with respect to a single\nfree-parameter $\\beta$ of the $k$'th component is then given by:\n\n\\begin{eqnarray}\n\\frac{\\partial}{\\partial \\beta_{k}} M(u,v) & = & \\frac{\\partial}{\\partial \\beta_{k}} \\sum^{n}_{i=1} S_{i} f_{i}(u,v) e^{2 \\pi i (u x_{i} + v y_{i})}\\\\\n%\n\\label{cmp_deriv}\n\\frac{\\partial}{\\partial \\beta_{k}} M(u,v) & = & \\frac{\\partial}{\\partial \\beta_{k}} [S_{k} f_{k}(u,v) e^{2 \\pi i (u x_{k} + v y_{k})}]\n\\end{eqnarray}\n\nGiven that for all model component types, $f(u,v)$ is independent of\nflux $S$ and shifted position $(x,y)$ we can determine the following\npartial derivatives for these parameters:\n\n\\begin{eqnarray}\n\\frac{\\partial}{\\partial x_{k}} M(u,v) & = & 2 \\pi i u F_{k}(u,v) \\\\\n%\n\\frac{\\partial}{\\partial y_{k}} M(u,v) & = & 2 \\pi i v F_{k}(u,v) \\\\\n%\n\\frac{\\partial}{\\partial S_{k}} M(u,v) & = & \\frac{1}{S_{k}} F_{k}(u,v)\n\\end{eqnarray}\n\nAll the supported model types can be represented by an azimuthally\nsymmetric function, which is stretched into an elliptical shape along\na specific direction. In the following equations the elliptical aspect\nwill be parameterized by the major-axis half-extent, $a$, the\ndirection of the major axis with respect to North, by the angle $\\phi$\nmeasured North through East, and by the minor-axis half-extent, $b$,\nor the alternative axial ratio $\\gamma = b/a$.\n\nFor the purpose of model fitting we will choose to allow $a$, $\\gamma$\nand $\\phi$ to be free parameters. The alternative choice of $a$,\n$b$ and $\\phi$ is less useful, because there is then no way for the\nuser to constrain components to have circular aspects, as required in\nsome specialized problems. To fit these parameters requires equations\nof the partial derivatives of components with respect to them, in\naddition to those above for $x$, $y$, and $S$.\n\nTo give the components the desired rotated elliptical aspect, the\nvalue of the function at $(x,y)$ in the image plane is assigned the\nvalue of the circularly symmetric function at radius:\n\n\\begin{equation}\nR_{xy} = \\sqrt{(x\\cos{\\phi}-y\\sin{\\phi})^{2}\\frac{1}{\\gamma^{2}} + (x\\sin{\\phi}+y\\cos{\\phi})^{2}}\n\\end{equation}\n\nThe Fourier transform of a circularly symmetric real function in the\nimage plane is another circularly symmetric function in the UV plane.\nAs in the image plane, the value of the rotated and stretched\nfunction at $(u,v)$ in the UV plane is that of the circularly\nsymmetric function measured at UV radius:\n\n\\begin{equation}\nR_{uv} = \\sqrt{(u\\cos{\\phi}-v\\sin{\\phi})^{2}\\gamma^{2}+(u\\sin{\\phi}+v\\cos{\\phi})^{2}}\n\\end{equation}\n\nSince each of the functions of interest multiplies this radius by\n$\\pi a$, the following parameter will also be defined:\n\n\\begin{equation}\n\\Gamma = \\pi a \\sqrt{(u\\cos{\\phi}-v\\sin{\\phi})^{2}\\gamma^{2}+(u\\sin{\\phi}+v\\cos{\\phi})^{2}}\n\\end{equation}\n\nPartial derivatives of individual components that depend on $\\Gamma$,\nwith respect to one of $a$, $\\gamma$, or $\\phi$ (denoted as $\\beta$) are\nthen given by: \n\n\\begin{equation}\n\\frac{\\partial}{\\partial \\beta_{k}} M(u,v) = \\frac{\\partial F_{k}(u,v)}{\\partial\\Gamma} \\times \\frac{\\partial\\Gamma}{\\partial\\beta_{k}}\n\\end{equation}\n\nIf the latter part is evaluated for each of the desired free\nparameters, this expands to:\n\n\\begin{eqnarray}\n%\n\\label{par_phi}\n\\frac{\\partial}{\\partial\\phi_{k}} M(u,v) & = & \\frac{\\partial\nF_{k}(u,v)}{\\partial\\Gamma} \\times \\frac{2\\pi^{2}a_{k}^{2}}{\\Gamma} (1-\\gamma_{k}^{2})\n(u\\cos{\\phi_{k}}-v\\sin{\\phi_{k}})(u\\sin{\\phi_{k}}+v\\cos{\\phi_{k}}) \\\\\n%\n\\frac{\\partial}{\\partial a_{k}} M(u,v) & = & \\frac{\\partial\nF_{k}(u,v)}{\\partial\\Gamma} \\times \\frac{\\Gamma}{a_{k}} \\\\\n%\n\\frac{\\partial}{\\partial \\gamma_{k}} M(u,v) & = & \\frac{\\partial\nF_{k}(u,v)}{\\partial\\Gamma} \\times \\frac{\\pi^{2}a_{k}^{2}\\gamma_{k}}{\\Gamma} \n(u\\cos{\\phi_{k}}-v\\sin{\\phi_{k}})^{2}\n\\end{eqnarray}\n\nFurther, since we know that neither the flux nor the position of the\ncomponents depends on $\\Gamma$, we can simplify the unknown\n$\\frac{\\partial F(u,v)}{\\partial\\Gamma}$ term to:\n\n\\begin{equation}\n\\frac{\\partial F(u,v)}{\\partial\\Gamma} = S e^{2 \\pi i (u x + v y)}\n\\frac{\\partial f(u,v)}{\\partial\\Gamma}\n\\end{equation}\n\nand thus only $\\frac{\\partial f(u,v)}{\\partial\\Gamma}$ need be\ncalculated individually for the different component types. This will\nbe done in the following sections.\n\n\\subsection{Gaussian components}\n\nThe equation for the value of a gaussian component at position $(u,v)$\nin the UV plane is given in \\cite{tjp91} as:\n\n\\begin{equation}\nf(u,v) = e^{-\\frac{\\Gamma^{2}}{4\\ln{2}}}\n\\end{equation}\n\nThis has a partial derivative {\\em wrt} $\\Gamma$ of:\n\n\\begin{equation}\n\\frac{\\partial}{\\partial\\Gamma} f(u,v) = -\\frac{2\\Gamma}{4\\ln{2}} f(u,v)\n\\end{equation}\n\n\\subsection{Uniformly Bright Disk components}\n\nThe equation for the value of a uniformly bright disk component at\nposition $(u,v)$ in the UV plane is given in \\cite{tjp91} as:\n\n\\begin{equation}\nf(u,v) = 2 \\frac{J_{1}(\\Gamma)}{\\Gamma}\n\\end{equation}\n\nUsing a standard derivative from \\cite{handbook}, the partial\nderivative of $f(u,v)$ {\\em wrt} $\\Gamma$ is:\n\n\\begin{equation}\n\\frac{\\partial}{\\partial\\Gamma} f(u,v) = -2 \\frac{J_{2}(\\Gamma)}{\\Gamma}\n\\end{equation}\n\n\\subsection{Optically Thin Sphere}\n\nThe equation for the value of a optically thin sphere component at\nposition $(u,v)$ in the UV plane is given in \\cite{tjp91} as:\n\n\\begin{equation}\nf(u,v) = \\frac{3}{\\Gamma^{3}}(\\sin{\\Gamma} - \\Gamma \\cos{\\Gamma})\n\\end{equation}\n\nThe partial derivative of this function {\\em wrt} $\\Gamma$ is:\n\n\\begin{equation}\n\\frac{\\partial}{\\partial\\Gamma} f(u,v) =\n\\frac{9\\cos{\\Gamma}}{\\Gamma^{3}} -\n\\frac{9\\sin{\\Gamma}}{\\Gamma^{4}} +\n\\frac{3\\sin{\\Gamma}}{\\Gamma^{2}}\n\\end{equation}\n\n\\subsection{Ring components}\n\nThe equation for the value of a ring component at position $(u,v)$ in\nthe UV plane is given in \\cite{tjp91} as:\n\n\\begin{equation}\nf(u,v) = J_{0}(\\Gamma)\n\\end{equation}\n\nUsing a standard derivative from \\cite{handbook}, the partial\nderivative of $f(u,v)$ {\\em wrt} $\\Gamma$ is:\n\n\\begin{equation}\n\\frac{\\partial}{\\partial\\Gamma} f(u,v) = -J_{1}(\\Gamma)\n\\end{equation}\n\n\\section{Alternative parameterizations.}\n\nThe above partial derivatives were coded up for use in a simple\nimplementation of the Levensburg-Marquardt non-linear least-squares\nalgorithm. It turned out that the parameterization of the elliptical\npart of the models had significant problems. In particular in\nequation~\\ref{par_phi} the partial derivative of the model {\\em wrt}\n$\\phi$ is zero when $\\gamma_{k}=1$. This means that the parameter can\nbe changed by an infinite amount without changing the model. This\nresults in zero column and row vectors in the Levensburg-Marquardt\nHessian matrix, which in turn results in a singular matrix when\ninverted.\n\nA better parameterization that is free of this problem was initially\nsuggested by Steve Myers and formalized by Tim Pearson. The essential\nparts of Tim Pearson's suggestion are included below.\n\n\\subsection{Reformulation of Model Fitting [Written by Tim Pearson]}\n\nI start from Martin's definition (11) of parameter $\\Gamma$ for an\nelliptical component with major axis $a$, minor axis $b= \\gamma a$,\nand position angle $\\phi$: \n\n\\begin{equation}\n\\Gamma = \\pi \\sqrt{a^2(u \\sin\\phi + v\\cos\\phi)^2 + b^2(u\\cos\\phi -\nv\\sin\\phi)^2}.\n\\end{equation}\n\nExpanding this expression and collecting terms,\n\n\\begin{equation}\n\\Gamma^2/\\pi = \\cos^2\\phi(a^2v^2 + b^2u^2) +\n               \\sin^2\\phi(a^2u^2 + b^2v^2) + 2uv\\cos\\phi\\sin\\phi(a^2-b^2).\n\\end{equation}\n\nApplying the double-angle formulae:\n\n\\begin{eqnarray}\n\\sin2z & = & 2\\sin z \\cos z, \\\\ \n\\cos2z & = & 2\\cos^2 z -1 = 1 - 2\\sin^2 z, \n\\end{eqnarray}\n\nwe obtain\n\n\\begin{eqnarray} \n\\Gamma^2/\\pi &=& (1 + \\cos 2\\phi)(a^2v^2 + b^2u^2)/2 + (1 - \\cos 2\\phi)(a^2u^2 + b^2v^2)/2 + uv \\sin 2\\phi (a^2 - b^2) \\\\\n%\n             &=& (a^2+b^2)(u^2+v^2)/2 + \\cos 2\\phi(a^2-b^2)(v^2 -u^2)/2 + uv\\sin 2\\phi (a^2 - b^2) \\\\\n%\n             &=& (v^2 -u^2) X + 2uv Y + (u^2+v^2) Z,\n\\end{eqnarray}\n\nwhere I have defined \n\n\\begin{eqnarray}\n X &=& (a^2 -b^2)\\cos 2\\phi /2,\\\\\n Y &=& (a^2 -b^2)\\sin 2\\phi /2,\\\\\n Z &=& (a^2+b^2)/2.\n\\end{eqnarray}\n\nA point in the $(X,Y,Z)$ system represents an ellipse. Circles ($a=b$)\nare on the line $X=Y=0$.\n\n\\subsection{Partial derivatives.}\n\nWe need the derivatives of\n\n\\begin{equation}\n\\Gamma = \\pi \\sqrt{(v^2 -u^2) X + 2uv Y + (u^2+v^2) Z}\n\\end{equation}\n\nwith respect to the model parameters $X,Y,Z$:\n\n\\begin{eqnarray}\n\\frac{\\partial\\Gamma}{\\partial X} &=& \\frac{\\pi^2}{2\\Gamma} (v^2 - u^2),\\\\\n\\frac{\\partial\\Gamma}{\\partial Y} &=& \\frac{\\pi^2}{2\\Gamma} (2uv),\\\\\n\\frac{\\partial\\Gamma}{\\partial Z} &=& \\frac{\\pi^2}{2\\Gamma} (v^2 + u^2).\n\\end{eqnarray}\n\n\\subsection{Disadvantages}\n\nUse of $(X,Y,Z)$ as variable parameters instead of $(a,\\gamma,\\phi)$\nhas the disadvantage that axial ratio and position angle cannot be\nconstrained. Fixing $Z$ is somewhat equivalent to fixing major\naxis. There are some non-physical domains in $X,Y,Z$ space, e.g.,\n$Z<0$.\n\n\\subsection{Advantages}\n\n$X,Y,Z$ all have the same dimensions so equal increments in each parameter\nare likely to affect $\\chi^2$ by similar amounts. Components can be\nconstrained to be circular by fixing $X=Y=0$. Note that convolving two\nelliptical gaussians is equivalent to adding their $X,Y,Z$ parameters---not\nthat this has any relevance to model fitting.\n\n\n\\begin{thebibliography}{xx}\n\\bibitem{handbook} Abramowitz, M. and Stegun, I.A (eds) 1972 {\\em\nHandbook of Mathematical functions} \\S~9.1.30, 9th printing, Dover publications\n\n\\bibitem{tjp91} Pearson, T.J. 1991 {\\em Introduction to the Caltech VLBI\nPrograms} \\S~7.2\n\n\\bibitem{nr} Press, W. H., Flannery, B. P., Teukolsky, S. A. and\nVetterling, W. T. 1989, {\\em Numerical Recipes}, Cambridge University\nPress.\n\\end{thebibliography}\n\\end{document}\n", "meta": {"hexsha": "6bd884072b12b1717f9746289ad3b988303433a0", "size": 15382, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/model.tex", "max_stars_repo_name": "sabourke/difmap", "max_stars_repo_head_hexsha": "390949f2a49070e52b5cc824ec8f5f37df735020", "max_stars_repo_licenses": ["ICU"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-05-27T20:09:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-06T14:56:50.000Z", "max_issues_repo_path": "doc/model.tex", "max_issues_repo_name": "sabourke/difmap", "max_issues_repo_head_hexsha": "390949f2a49070e52b5cc824ec8f5f37df735020", "max_issues_repo_licenses": ["ICU"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/model.tex", "max_forks_repo_name": "sabourke/difmap", "max_forks_repo_head_hexsha": "390949f2a49070e52b5cc824ec8f5f37df735020", "max_forks_repo_licenses": ["ICU"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-04-25T12:40:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-03T15:06:10.000Z", "avg_line_length": 37.608801956, "max_line_length": 150, "alphanum_fraction": 0.7275386816, "num_tokens": 4565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.30259327751118414}}
{"text": "\\section{Progressive Hierarchical Refinement}\n\\label{phr}\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=400pt]{images/phr_algorithm.pdf}\n    \\caption{Illustration of the progressive hierarchical refinement algorithm.}\n    \\label{fig:phr}\n\\end{figure}\nThis section further explains the algorithm used to construct bounding volume hierarchies. Bounding volume hierarchies are constructed using progressive hierarchical refinement (PHR) as proposed by Hendrich et al.\\cite{hendrich_parallel_2017}. As previously established, applying full sweep SAH to all scene primitives is magnitudes too slow. PHR tackles this problem by first constructing an auxiliary BVH, which then serves as a hierarchy to find much smaller sets of nodes on which full sweep SAH can be applied fairly inexpensively. The two resulting cuts are then refined, meaning that some nodes within those cuts are replaced by their children, if their bounding box surface area is above a certain threshold. Afterwards, the algorithm is applied recursively to the refined cuts until the full BVH is constructed. An illustration of that process can be seen in figure \\ref{fig:phr}.\n\n\\subsection{Auxiliary Bounding Volume Hierarchy}\n\\label{aux}\nAs the auxiliary BVH is only needed as a description of the scene's hierarchy, construction speed is the main priority. Multiple fast builders have been tested in the original paper\\cite{hendrich_parallel_2017}, but linear bounding volume hierarchies (\\acrshort{lbvh}) turned out to be the best choice. LBVH was first proposed by Lauterbach et al.\\cite{lauterbach09lbvh} as a top-down algorithm that assigns Morton codes to all primitives and then builds the tree as a binary radix tree. The algorithm itself has since been improved multiple times\\cite{karras12lbvh,apetrei14lbvh,chitalu20lbvh} making it one of the fastest approaches to date\\cite{meister21survey}. However, these approaches exploit the massive parallelism GPUs can provide by building the BVH in a bottom up fashion, which makes less sense on the limited amount of cores CPUs provide. Consequently, the approach used here is closer to the top-down algorithm proposed by Lauterbach et al.\\cite{lauterbach09lbvh} with a few adjustments. \n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=400pt]{images/morton_curve.pdf}\n    \\caption{Left shows 2D Morton curve using 2 bits per dimension. The table in the center shows the corresponding Morton codes and the right shows the resulting tree structure, equivalent to a binary radix tree.}\n    \\label{fig:morton}\n\\end{figure}\nConstruction of the auxiliary BVH starts off by sorting all primitives along a Morton curve\\cite{morton66curve}. This space filling curve subdivides the scene space into a uniform grid, resulting in Morton codes of fixed length (figure \\ref{fig:morton}). Computation of Morton codes is done fairly efficiently by interleaving successive bits of the primitives' quantized bounding box centroids.\n\nMorton codes are assigned in parallel by processing $[n/t]$ primitives per thread, with $n$ being the number of scene primitives and $t$ being the number of threads. Afterwards, the primitives are sorted according to their Morton code using a parallel bucket sort implementation. In each thread, $k=2^{12}$ empty buckets are created and filled with $[n/t]$ primitives. By using individual buckets for each thread, no further synchronization necessary for the bucketing. However, an atomic counter is used to keep track of the total number of primitives in each bucket across all threads, which is then used to find the intervals in the original array each bucket occupies. After bucketing is finished, all non-empty buckets with the same index are merged and directly written to the mentioned interval in the input array, before being sorted in place using Go's built-in sort function. This step is also done in parallel by utilizing the worker pattern to send buckets with the same index to each thread until all buckets have been processed.\n\nThe corresponding BVH can be constructed by recursively splitting the set of primitives at the highest bit within the current interval. This is done using a Go channel and entries representing a node in the finished tree. Each thread fetches such a node and finds the split in the corresponding array by applying linear search. If the node does not become a leaf, the resulting cuts are sent to the channel to be processed by idle threads.\n\nFinally, the bounding boxes of the tree are updated in parallel by starting at the tree's leaves and traversing towards the root. Whenever a thread visits a node, the bounding box is updated using the child or primitive bounding boxes. Then the parents atomic counter is incremented and if all children are set, the thread also processes the parent. Otherwise, the thread fetches an unprocessed leaf from a queue. The same procedure is executed when refitting the LBVH on scene changes. \n\\subsection{Algorithm}\n\\label{phr_algorithm}\nThe main progressive hierarchical refinement algorithm starts by identifying a set of nodes that separate root and leaves of the auxiliary LBVH. Nodes are selected in parallel using a priority queue. A thread pops an entry from that queue and compares its bounding volume surface area to a given threshold. If the surface area is below that threshold or the cut has reached its maximum size, the node is added to the initial cut. Otherwise, its children are inserted into the priority queue to be processed by another thread. The resulting cut is several magnitudes below the full primitive count and can be processed fairly inexpensively using full sweep SAH.\n\nCuts are split by evaluating an adapted version of the surface area heuristic for all three axis and choosing the split with the lowest cost. The cut becomes a leaf, if the cost of not splitting at all is the lowest. Each axis is evaluated by sorting nodes along given axis according to their bounding box centroid. The SAH cost for a split at the index $i$ in the sorted set is given as \n\\[C(i)=S_L(i)n_L(i)+S_R(i)n_R(i)\\]\nwhere $S_L(i)$ and $S_R(i)$ are the bounding boxes surface areas of the left and right subsets and $n_L(i)$ and $n_R(i)$ are the number of nodes in the corresponding subtrees. Note that this expression is very similar to the SAH cost presented in section \\ref{acceleration_structure_basics}. However, instead of using the number of primitives in the left and right cuts, the number of nodes is used. According to Hendrich et al.\\cite{hendrich_parallel_2017}, this improves the performance by a few percent, as the number of nodes better reflects the complexity of the given subtree.\n\nThe SAH evaluation algorithm first computes all right costs $S_R(i)n_R(i)$ by incrementally extending the split bounding box and storing the partial costs, which is more efficient than computing the full bounding box at each step. The full cost is then calculated in the same fashion, extending the bounding box from the left to solve $S_L(i)n_L(i)$. \n\nSplitting the cut reduces the number of nodes in each new cut and doing so multiple times would lead to a cut size of one. To keep cuts at a larger size for longer and to better utilize the hierarchical information the auxiliary BVH can provide, cuts are refined after splitting. Keeping cuts at a constant size, as proposed by Hunt et al.\\cite{hunt07lazybuild}, would become rather expensive towards the bottom of the tree due to the growing number of cuts. As a solution, Hendrich et al.\\cite{hendrich_parallel_2017} proposed an adaptive refinement approach based on the current depth in the tree. This approach makes cuts shrink towards the bottom of the tree, which balances the computational cost between different levels of the tree. The BVH quality is not worsened significantly by doing so, as the impact of SAH gets lower further down the tree. \n\nRefinement works by comparing node bounding box surface areas to an adaptive threshold. Nodes with a surface area below this threshold are kept within the cut. Otherwise, the node is replaced by its children. This adaptive threshold is given as \n\\[t_d = S /{2^{\\alpha d + \\delta}}\\]\nwith $S$ being the surface are of the scene bounding box and $d$ the current depth in the tree. The parameter $\\alpha$ describes how quickly cuts shrink towards the bottom and $\\delta$ determines the size of the initial cut for $d=0$. The setting of these parameters determines the build-trace trade-off of the algorithm and is elaborated further in section \\nameref{parameters}.\n\nConstruction of the BVH uses a similar setup as previously mentioned for the LBVH generation. A thread pool of $t$ threads pops entries from a channel, consisting of a cut and parent node index. The cut is split using the described method, the resulting cuts are refined and then fed back into the channel if the node did not become a leaf. Additionally, a higher branching factor can be specified to build a multi-BVH\\cite{wald08multibvh}. In that case, a thread keeps splitting the biggest resulting cut until enough children have been generated or no more splits exist. The effect of multi-BVHs on the rendering performance is evaluated in section \\ref{multi_bvh}.\n\n\\begin{figure}[H]\n    \\centering\n    \\subcaptionbox{Render}{\\includegraphics[width=0.3\\textwidth]{images/fireplace_render.png}}\n    \\hfill\n    \\subcaptionbox{LBVH}{\\includegraphics[width=0.3\\textwidth]{images/fireplace_lbvh.png}}\n    \\hfill\n    \\subcaptionbox{PHR-HQ}{\\includegraphics[width=0.3\\textwidth]{images/fireplace_phr.png}}\n    \\caption{Visualization of the number of traversal steps for primary rays using LBVH and PHR (red color corresponds to 100 traversal steps per ray).}\n    \\label{fig:noise}\n\\end{figure}\n\\subsection{Integration into Interactive Path Tracing}\n\\label{phr_in_interactive}\nAn approach for integrating progressive hierarchical refinement into interactive applications was mentioned in the original paper\\cite{hendrich_parallel_2017}, but its validation remained an open topic. The idea was to only build the auxiliary BVH once in the beginning and then refit it very efficiently between frames. Refitting is done by updating bounding boxes of all BVH nodes. The hierarchy of the structure stays unchanged during this procedure. As described in the end of section \\ref{aux}, this is done using a parallel recursive procedure that traverses the tree in a bottom-up fashion and merges child bounding boxes using an atomic counter for synchronization. Doing so is fairly efficient in comparison to a full BVH rebuild, however, refitting generally leads to some extend of BVH quality loss, especially for significant scene changes. Applying PHR to the refitted tree counteracts this loss by building a new BVH.\n\\cleardoublepage", "meta": {"hexsha": "51e5cc3c468de10dd898467194902a47c4fddc28", "size": 10741, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/ch04_2-phr.tex", "max_stars_repo_name": "ChSchmidt99/bachelorthesis", "max_stars_repo_head_hexsha": "4c427317c0334186eea8c587d56d0c176a4b04fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ch04_2-phr.tex", "max_issues_repo_name": "ChSchmidt99/bachelorthesis", "max_issues_repo_head_hexsha": "4c427317c0334186eea8c587d56d0c176a4b04fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ch04_2-phr.tex", "max_forks_repo_name": "ChSchmidt99/bachelorthesis", "max_forks_repo_head_hexsha": "4c427317c0334186eea8c587d56d0c176a4b04fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 185.1896551724, "max_line_length": 1042, "alphanum_fraction": 0.8034633647, "num_tokens": 2331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.30251010335578415}}
{"text": "\\documentclass[11pt,reqno]{beamer}\n\\usepackage[utf8x]{inputenc}\n\\usetheme{Dresden}\n\\usecolortheme{beaver}\n\\usepackage{amsmath}\n\\usepackage{physics}\n\\usepackage{amsfonts}\n\\usepackage{graphicx}\n\\usepackage{hyperref}\n\\usepackage{array}   % for \\newcolumntype macro\n\\newcolumntype{R}{>{$}r<{$}}\n\n\\setbeamertemplate{navigation symbols}{} \n\\title{Bond Graph Clinic: Part 2}\n\\subtitle{Constitutive Relations}\n\\author{Peter Cudmore}\n\n\\institute{Systems Biology Lab, The University of Melbourne}\n\n\\newcommand{\\D}[2]{\\frac{\\mathrm{d} #1}{\\mathrm{d} #2}}\n\\newcommand{\\e}{\\mathrm{e}}\n\\newcommand{\\I}{\\mathrm{i}}\n\\renewcommand{\\mod}[1]{\\left|#1\\right|}\n\\newcommand{\\DD}[2]{\\frac{\\mathrm{d}^2 #1}{\\mathrm{d} #2^2}}\n\\newcommand{\\bigO}[1]{\\text{O}\\left(#1\\right)}\n\\renewcommand{\\P}[2]{\\frac{\\partial #1}{\\partial #2}}\n\\renewcommand{\\Re}{\\operatorname{Re}}\n\\renewcommand{\\Im}{\\operatorname{Im}}\n\\newcommand{\\EX}{\\mathbb{E}}\n\\newcommand{\\df}[1]{\\mspace{2mu}  \\mathrm{d}#1}\n\\newcommand{\\reals}{\\mathbb{R}}\n\\newcommand{\\complex}{\\mathbb{C}}\n\\newcommand{\\conj}[1]{\\overline{#1}}\n\n\\begin{document}\n\t\\begin{frame}\n\t\\titlepage\n\t\\addtocounter{framenumber}{-1} \n\\end{frame}\n\\begin{frame}\n\\tableofcontents[hideallsubsections]\n\\end{frame}\n\\section{Previously...}\n\\begin{frame}\n\\frametitle{Network models of energetic systems}\n\t\\begin{figure}\n\t\\includegraphics{images/bondgraph.pdf}\n\\end{figure}\nLast week we showed Bond Graphs capture:\n\\begin{itemize}\n\t\\item Energy transferred between $B,C,D$ without loss via bonds.\n\t\\item Power transfer represented by conjugate variables $P_i=e_if_i$.\n\t\\item Subsystem dynamics through constitutive relations; $\\Phi_B(p,q,e,f) = 0$ for example.\n\\end{itemize}\n\\end{frame}\n\\section{Junction Structures}\n\\subsection{Two-Port Components}\n\\begin{frame}\n\\frametitle{Power Conservation Laws}\n\\begin{figure}\n\t\\includegraphics{images/twoport.pdf}\n\\end{figure}\nSuppose this network conserves power, then\n\\[\ne_1f_1 + e_2 f_2 = 0.\n\\]\nThat is; the power into $\\Phi$ must sum to zero.\nTwo solutions: $e_1 \\propto e_2$, or $e_1\\propto f_1$.\n\\end{frame}\n\\begin{frame}\n\\frametitle{Transformer}\n\\begin{figure}\n\t\\includegraphics{images/twoport-tf.pdf}\n\\end{figure}\n\\only<1>{\n\\begin{figure}\n\\begin{minipage}{0.4\\linewidth}\n\\includegraphics[width=0.8\\linewidth]{images/Transformer3d_col.png}\n\t\\end{minipage}\n\\begin{minipage}{0.4\\linewidth}\n\\raggedright\n\\includegraphics[width=0.8\\linewidth]{images/Lever_Principle_3D.png}\n\\end{minipage}\n\\caption{An \\href{https://en.wikipedia.org/wiki/Transformer}{electrical transformer} and  a \\href{https://en.wikipedia.org/wiki/Lever}{mechanical transformer} (ie, a lever)}\n\\end{figure}\nAlso includes: motors and generators, waterwheels, etc.\n}\n\\only<2-3>{\nFor transformers we require $e_2 = \\rho e_1$, so \n\t\\[\ne_1f_1 + e_2 f_2 = 0 \\implies e_1(f_1 +\\rho  f_2)= 0 \\implies \nf_2 = -\\frac{1}{\\rho}f_1\n\\]\nGiving a constitutive relation}\n\\only<2>{\n\\[\n\\Phi_\\text{TF} =\\left(\\begin{matrix}\ne_2 - \\rho e_1 \\\\\nf_2 +\\frac{1}{\\rho}f_1\n\\end{matrix} \\right)  = 0.\n\\]}\n\\only<3>{\n\t\\[\n\t\\Phi_\\text{TF} = \\left(\n\t\\begin{matrix}\n\t-\\rho & 0  &1 &  0 \\\\\n\t0&\\rho^{-1} &0  & 1 \n\t\\end{matrix}\\right)\n\t\\left(\\begin{matrix}\ne_1\\\\\nf_1\\\\\ne_2\\\\\nf_2\n\t\\end{matrix}\n\t\\right) = 0.\n\t\\]\n}\n\\end{frame}\n\\begin{frame}\n\\frametitle{Gyrator}\n\\begin{figure}\n\t\\includegraphics{images/twoport-gy.pdf}\n\\end{figure}\n\\only<1>{\n\\begin{figure}\n\t\\includegraphics[width=0.3\\linewidth]{images/Gyroscope.png}\n\t\\caption{\\href{https://en.wikipedia.org/wiki/Gyroscope}{A gyroscope}}\n\t\\end{figure}\nElectrical gyrators were proposed by Tellengen in 1948, but a passive implementation hasn't yet been found.\n}\n\\only<2-3>{\nFor gyrators we require $e_2 = \\rho f_1$, so\n\\[\ne_1f_1+e_2f_2 = 0 \\implies  f_1(e_1 -  \\rho f_2)=0 \\implies f_2 = -\\frac{1}{\\rho}e_1.\n\\]\nGiving a constitutive relation}\n\\only<2>{\n\\[\n\\Phi_\\text{GY} =\\left(\\begin{matrix}\ne_2 - \\rho f_1 \\\\\nf_2 +\\frac{1}{\\rho}e_1\n\\end{matrix} \\right)  = 0.\n\\]}\n\\only<3>{\n\\[\n\\Phi_\\text{GY} = \\left(\n\\begin{matrix}\n0 & -\\rho  &1 &  0 \\\\\n\\rho^{-1}&0 &0  & 1 \n\\end{matrix}\\right)\n\\left(\\begin{matrix}\ne_1\\\\\nf_1\\\\\ne_2\\\\\nf_2\n\\end{matrix}\n\\right) = 0.\n\\]\n}\n\n\\end{frame}\n\\subsection{N-port Components}\n\\begin{frame}\n\\frametitle{Network Conservation Laws}\n\\begin{figure}\n\t\\includegraphics{images/nport.pdf}\n\\end{figure}\nWe require nodes to capture the distribution of power across many subsystems. These junction nodes capture network conservation laws which must satisfy\n\\[\n0 = \\sum_{i=1}^j e_if_i.\n\\]\nThe two base cases are \\emph{common effort}, and \\emph{common flow}.\n\\end{frame}\n\\begin{frame}\n\\frametitle{0-Junction}\n\\begin{figure}\n\t\\includegraphics{images/nport-0.pdf}\n\\end{figure}\n\\only<1>{\nFor common effort junctions $e_i = e_k,\\ \\forall 1\\le i,k \\le j$. Hence\n\\[\n\\sum_{i=1}^j e_i f_i = 0 \\implies  \\sum_{i=1}^j f_i = 0\n\\]\n\\emph{This is Kirchoff's Current Law}\n}\n\\only<2>{\nThe constitutive relation is given by:\n\\[\n\\Phi_\\text{0} = \\left(\\begin{matrix}\ne_1 -e_2\\\\\n\\ldots\\\\\ne_{j-1} - e_j\\\\\nf_1 + f_2 + \\ldots + f_j \n\\end{matrix}\\right) = 0\n\\] \n}\n\\only<3>{\n\tThe constitutive relation is given by:\n\t\\[\n\t\\Phi_\\text{0} = \\left(\\begin{matrix}\n1 \t& 0\t\t   & -1\t\t& 0 \t& \t\\ldots &0 \\\\\n&\t \\ddots& & \\ddots  & \\\\\n\\ldots  & 0  & \t  1   & 0         & -1 &0\\\\\n      0 & 1 & \\ldots & & 0 &1\n\t\\end{matrix}\n\t\\right)\n\t\\left(\\begin{matrix}\ne_1\\\\f_1\\\\\\vdots\\\\ e_j\\\\f_j\n\t\\end{matrix}\\right)\n\t = 0\n\t\\] \n}\n\\end{frame}\n\\begin{frame}\n\\frametitle{1-Junction}\n\\begin{figure}\n\t\\includegraphics{images/nport-1.pdf}\n\\end{figure}\n\\only<1>{\nSimilarly for common flow junctions $f_i = f_k,\\ \\forall 1\\le i,k \\le j$. Hence\n\t\\[\n\t\\sum_{i=1}^j e_i f_i = 0 \\implies  \\sum_{i=1}^j e_i = 0\n\t\\]\n\t\\emph{This is Kirchhoff's Voltage Law}\n}\n\\only<2>{\n\tThe constitutive relation is given by:\n\t\\[\n\t\\Phi_\\text{1} = \\left(\\begin{matrix}\n\tf_1 -f_2\\\\\n\t\\ldots\\\\\n\tf_{j-1} - f_j\\\\\n\te_1 + e_2 + \\ldots + e_j \n\t\\end{matrix}\\right) = 0\n\t\\] \n}\n\\only<3>{\n\tThe constitutive relation is given by:\n\t\\[\n\t\\Phi_\\text{1} = \\left(\\begin{matrix}\n\t0 \t& 1\t\t   &0\t\t& -1 \t& \t\\ldots &0 \\\\\n&\t&\t \\ddots& & \\ddots   \\\\\n\t\\ldots  & & 0  & \t  1   & 0         & -1\\\\\n\t1 & 0 & \\ldots & & 1 &0\n\t\\end{matrix}\n\t\\right)\n\t\\left(\\begin{matrix}\n\te_1\\\\f_1\\\\\\vdots\\\\ e_j\\\\f_j\n\t\\end{matrix}\\right)\n\t= 0\n\t\\] \n}\\end{frame}\n\\section{Storage and I/O}\n\\subsection{Storage}\n\\begin{frame}\n\\frametitle{Physics review}\nEnergy stored is a function of local storage co-ordinates $q,p$\n\\[\nH(q, p) = E_0 + \\int P_\\text{in}\\df{t}.\n\\]\nThe canonical co-ordinates $q, p$ are taken such that $q \\in X$ where $X$ is some manifold, and $p\\in X^*$ where $X^*$ is the dual space of $X$. \n\\vspace{10pt}\n\nIn the case where $X = \\mathbb{R}^n$, the dual space $X^*$ is the set of column vectors acting on $X$.\nThat is if $q,x \\in \\mathbb{R}^n$ then there exists a dual vector (a linear functional) $p \\in X^*$ such that $p(q) = x^T\\cdot q$.\n\n\\vspace{10pt}\n\nAs an aside, in physics $p$ is often written as $\\bra{p}$, so that in the above example $\\bra{p}\\ket{q} = x^Tq$.\n\\end{frame}\n\n\\begin{frame}\n\\frametitle{Physics review (cont.)}\nIf $P_\\text{in} = ef$ then\n\\[\nH(q, p) = E_0 + \\int P_\\text{in}\\df{t} \\implies \\P{H}{q} \\df{q} + \\P{H}{p}\\df{p} = ef\\df{t}.\n\\]\nWe want to:\n\\begin{itemize}\n\t\\item associate $e$ with the tangent space of $X^*$, ideally by saying something like $e = \\D{p}{t}$ so that $e\\df{t} =\\df{p}$.\n\t\\item associate $f$ with the tangent space of $X$, ideally by saying that $f = \\D{q}{t}$ so that $f\\df{t} = \\df{q}$.\n\\end{itemize}\nWe can do this easily if we consider individual components whose stored energy depends only on generalised position or momentum, but not both.\n\\end{frame}\n\\begin{frame}\n\\frametitle{Kinetic Storage}\n\\begin{figure}\n\t\\includegraphics{images/oneport-L.pdf}\n\\end{figure}\nFor kinetic energy, the stored energy depends only on momentum, $\\P{H}{q} = 0$, so we can define $e\\df{t} = \\df{p}$.\n\\[\n\\P{H}{q} \\df{q} + \\P{H}{p}\\df{p} = ef\\df{t} \\implies  \\left(\\P{H}{p} - f\\right)\\df{p}= 0\n\\]\nHence we have a constitutive relation\n\\[\n\\Phi_L = \\P{H}{p} - f= 0, \\qquad  \\text{where}\\qquad \\dot{p} = e.\n\\]\n\\end{frame}\n\\begin{frame}\n\\frametitle{Kinetic Storage (cont.)}\n\\begin{figure}\n\t\\includegraphics{images/oneport-L.pdf}\n\\end{figure}\n\\only<1>{\nIn the case of linear kinetic storage; we have a Hamiltonian\n\\[\nH(q,p) = \\frac{1}{2L}p^2,\n\\]\nwhich is the energy stored in a $L$-henry inductor; in the linear motion of an $L$-kg object.\\\\\n\n\\vspace{10pt}\nThis gives rise to the familiar constitutive relation:\n\\[\n\\Phi_L = \\P{H}{p} - f = \\frac{1}{L}p - f\\qquad \\implies \\qquad Lf -  \\int e \\df{t} = 0.\n\\]}\n\\only<2>{\nThis gives rise to the familiar constitutive relation:\n\\[\n\\Phi_L = \\frac{1}{L}p - f\n\\]\nWhich, if we define the integration operator $\\mathcal{I}x = \\int_0^tx(t)\\df{t}$, then we have\n\\[\n\\Phi_L = \\left(\\mathcal{I}, -L\\right) \\left(\\begin{matrix} e\\\\f\\end{matrix}\\right) \\qquad \\overset{\\mathcal{L}}{\\implies}\\qquad\n\\hat{\\Phi}_L(s) = \\left(s^{-1}, -L\\right) \\left(\\begin{matrix} \\hat{e}\\\\\\hat{f}\\end{matrix}\\right) \n\\] \n}\n\\end{frame}\n\n\\begin{frame}\n\\frametitle{Potential Storage}\n\\begin{figure}\n\t\\includegraphics{images/oneport-C.pdf}\n\\end{figure}\nSimilarly for potential, the stored energy depends only on position, $\\P{H}{p} = 0$, so we define $f\\df{t} = \\df{q}$.\n\\[\n\\P{H}{q} \\df{q} + \\P{H}{p}\\df{p} = ef\\df{t} \\implies  \\left(\\P{H}{q} - e\\right)\\df{q}= 0\n\\]\nHence we have a constitutive relation:\n\\[\n\\Phi_C = \\P{H}{q} - e= 0, \\qquad  \\text{where}\\qquad \\dot{q} = f.\n\\]\n\\end{frame}\n\n\\begin{frame}\n\\frametitle{Potential Storage (cont.)}\n\\begin{figure}\n\t\\includegraphics{images/oneport-C.pdf}\n\\end{figure}\n\\only<1>{\nStorage of potential energy has more variety. In the linear case (represented by the $C$ node above) we have\n\\[\nH(q,p) =\\frac{1}{2C} q^2 \n\\]\nwhich is the power stored in a $C$-farad capacitor, the elastic energy stored in a spring displaced by $q$ from equilibrium, etc.\n\\[\n\\Phi_C = \\P{H}{q} - e= \\frac{1}{C}q - e \\qquad  \\implies \\qquad Ce - \\int f \\df{t} = 0\n\\]}\n\\only<2>{\nHence we have a constitutive relation:\n\\[\n\\Phi_C = \\frac{1}{C}q - e\n\\]\nWhich, if we define the differentiation operator $Dx = \\D{}{t} x(t) $, then we have\n\\[\n\\Phi_C = \\left(C, -D\\right) \\left(\\begin{matrix} e\\\\f\\end{matrix}\\right) \\qquad \\overset{\\mathcal{L}}{\\implies}\\qquad\n\\hat{\\Phi}_C(s) = \\left(C, -s\\right) \\left(\\begin{matrix} \\hat{e}\\\\\\hat{f}\\end{matrix}\\right) \n\\] \nup to a constant.\n}\n\\end{frame}\n\n\\subsection{Dissipative and Sources}\n\\begin{frame}\n\\frametitle{Linear Dissipation}\n\\begin{figure}\n\t\\includegraphics{images/oneport-R.pdf}\n\\end{figure}\nDissipation can be captured by introducing a Dirac structure $\\mathcal{D}(\\dot{q})$, and choosing $f = \\dot{q}$ such that\n\\[\n\\mathcal{D}(\\dot{q})\\df{q} = e\\df{q} \\implies \\Phi_R = e - \\mathcal{D}(f) =0\\]\nClearly picking $\\mathcal{D}(\\dot{q}) = R\\dot{q}$ gives both Ohms law and friction so that\n\\[\n\\Phi_R = e - Rf = 0\n\\]\n\\end{frame}\n\n\\begin{frame}\n\\frametitle{Effort and Flow sources}\n\n\\begin{figure}\n\t\\begin{minipage}{0.4\\textwidth}\n\t\\includegraphics{images/oneport-Se.pdf}\n\t\\end{minipage}\n\t\\begin{minipage}{0.4\\textwidth}\n\t\\includegraphics{images/oneport-Sf.pdf}\n\\end{minipage}\n\\end{figure}\nTo get power in and out of the system, we add control nodes. These impose a control value $u(t)$ on $e$ (for Se) or $f$ (for Sf), and leave the other variable free, under the assumption that there is enough power on tap to maintain the control value. \nFor the effort source Se we have\n\\[\n\\Phi_\\text{Se} = e - u.\n\\]\nand similarly for the flow source Sf\n\\[\n\\Phi_\\text{Sf} = f - u.\n\\]\n\\end{frame}\n\\section{An example...}\n\\begin{frame}\n\\frametitle{Table of Constitutive Relations}\n\\begin{small}\n\\begin{minipage}[c][\\textheight][t]{0.4\\textwidth}\n\\vspace{0.75cm}\n\\begin{tabular}{| l | c |}\n\tNode & Constitutive Relation\\\\\n\t\\hline\n\t& \\\\\n\tR & $\\Phi_\\text{R} = e -Rf$\\\\\n\tL & $\\Phi_\\text{L} = \\int e\\df{t} - Lf$\\\\\n\tC & $\\Phi_\\text{C} = Ce - \\int f \\df{t}$\\\\\n\tSe & $\\Phi_\\text{Se} = e - u$\\\\\n\tSf & $\\Phi_\\text{Sf} = f - u$\\\\\n\tTF & $\\Phi_\\text{TF} =\\left(\\begin{matrix}\n\te_2 - \\rho e_1 \\\\\n\tf_2 +\\frac{1}{\\rho}f_1\n\t\\end{matrix} \\right)$\\\\\n\tGY & $\\Phi_\\text{GY} =\\left(\\begin{matrix}\n\te_2 - \\rho f_1 \\\\\n\tf_2 +\\frac{1}{\\rho}e_1\n\t\\end{matrix} \\right)$\n\\end{tabular}\n\\end{minipage}\\hfill\n\\begin{minipage}[c][\\textheight][t]{0.45\\textwidth}\n\t\\vspace{0.75cm}\n\\begin{tabular}{| l | c |}\n\tNode & Constitutive Relation\\\\\n\t\\hline\n\t&\\\\\n\t0 &$\t\\Phi_\\text{0} = \\left(\\begin{matrix}\n\te_1 -e_2\\\\\n\t\\ldots\\\\\n\te_{j-1} - e_j\\\\\n\tf_1 + f_2 + \\ldots + f_j \n\t\\end{matrix}\\right)$\\\\\n\t&\n\t\\\\\n\t1&$\t\\Phi_\\text{1} = \\left(\\begin{matrix}\n\tf_1 -f_2\\\\\n\t\\ldots\\\\\n\tf_{j-1} - f_j\\\\\n\te_1 + e_2 + \\ldots + e_j \n\t\\end{matrix}\\right)$\n\\end{tabular}\n\\end{minipage}\n\\end{small}\n\\end{frame}\n\\begin{frame}\n\\frametitle{RLC Example}\n\\begin{small}\n\\begin{minipage}{0.4\\textwidth}\n\\begin{figure}\n\t\\includegraphics{images/rlc.pdf}\n\t\\caption{RLC Bond Graph}\n\\end{figure}\n\\end{minipage}\n\\begin{minipage}{0.55\\textwidth}\n\\begin{eqnarray}\n\\Phi_R &=& e_R - Rf_r\\\\\n\\Phi_C &=& Ce_C - \\int f_C\\df{t}\\\\\n\\Phi_L &=& \\int e_L \\df{t} - Lf_L\\\\\n\\Phi_1 &=& \\left(\\begin{matrix}\nf_\\text{in} - (-f_R)\\\\\nf_\\text{in} - (-f_C)\\\\\nf_\\text{in} - (-f_L)\\\\\ne_\\text{in} + e_R + e_C + e_L\n\\end{matrix}\\right)\n\\end{eqnarray}\n\\end{minipage}\n\n\n\\vspace{10pt}\n\n\\only<1>{Our goal is to find $\\Phi_\\text{RLC}(e_\\text{in},f_\\text{in}) = 0$; that is the equivalent relation for the entire network.}\n\\only<2>{Observing the first three rows of $\\Phi_1$, in combination with $\\Phi_R,\\Phi_C,\\Phi_L$ respectively; we have\n\t\\[\n\te_R = -Rf_\\text{in},\\qquad e_c = -\\frac{1}{C}\\int f_\\text{in}\\df{t}, \\qquad e_L = -\\frac{1}{L}\\D{f_\\text{in}}{t}\n\t\\]\n}\n\\only<3>{\nSubstituting into the fourth row of $\\Phi_1$ gives our result:\n\\[\n\\Phi_\\text{RLC} = e_\\text{in} - \\left(\\frac{1}{C}\\int f_\\text{in} \\df{t} + Rf_\\text{in} + \\frac{1}{L}\\D{f_\\text{in}}{t}\\right) = 0\n\\]\n}\n\\end{small}\n\\end{frame}\n\\end{document}", "meta": {"hexsha": "775ad85e03626efdda2cd84c4c4b7536c92b0350", "size": 13674, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/clinic_notes_2.tex", "max_stars_repo_name": "peter-cudmore/Bond-Graph-Clinic", "max_stars_repo_head_hexsha": "a17dad1e4e398e76a7b63410f6f7e9e09232608c", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-16T14:46:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-16T14:46:39.000Z", "max_issues_repo_path": "tex/clinic_notes_2.tex", "max_issues_repo_name": "peter-cudmore/Bond-Graph-Clinic", "max_issues_repo_head_hexsha": "a17dad1e4e398e76a7b63410f6f7e9e09232608c", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2018-02-20T04:29:37.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-29T02:19:02.000Z", "max_forks_repo_path": "tex/clinic_notes_2.tex", "max_forks_repo_name": "peter-cudmore/Bond-Graph-Clinic", "max_forks_repo_head_hexsha": "a17dad1e4e398e76a7b63410f6f7e9e09232608c", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5130784708, "max_line_length": 251, "alphanum_fraction": 0.6586222027, "num_tokens": 5405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165085228824, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.30251009483282487}}
{"text": "\\chapter{Theoretical Background}\n\nThis chapter explains the concepts needed to understand this thesis. The theory behind RL, ANN, DDPG and HER is explained.\n\n\\section{Reinforcement Learning}\n%% In context of machine learning (supervised,unsupervised)\n%% potential to be better than humans\n\nRL is one of the main learning concepts of Machine Learning next to Supervised Learning and Unsupervised Learning \\cite{machinelearning}.\n\\newline\nIn Supervised Learning some input data is given to the learning agent. The agent is expected to come up with some output which is then compared with the expected output. If the output given by the agent and the expected output matches, then the agent was correct. The agent is trained by calculating the error between expected output and actual output. An use case for Supervised Learning is sorting mails into regular mail and spam mail. The agent is given a mail and it should decide whether the mail is regular or spam based on the content. Supervised Learning is used for classification and regression problems \\cite{machinelearning}. It is mainly useful when the expected output is already known, so the learning agent can learn to do recognize these. \n\\newline\nIn Unsupervised Learning there is no expected output. The learning agent is fed with data so it can figure out interesting features and similarities between different data. Unsupervised Learning is often used to cluster data, often pictures, based on similarities \\cite{machinelearning}.\n\\newline\nIn RL the agent is learning through rewards that are given through interaction with an environment. The goal of a task is clear, but the path of actions to reach the goal is not trivial. RL is used to find the best action in each situation. It is often used for games because they are already set up to have a clear task and goal, but the optimal way to reach it is not clear. Games usually provide full information on the environment in contrast to the real world, therefore setting up the learning environment is simple. Also Supervised Learning is limited in performance because the agent can only learn to become as good the expected output that we set. So in games like chess, with Supervised Learning the agent can only become as good as the best players it learns from, but not better. It is limited by the skills of the best humans \\cite{nolimit}. However, RL is not restricted by these limitations. The agent can improve on its own only by exploring his options. In games like Go and Chess, engines that use RL have already far surpassed the best human players \\cite{alphazero}. \n\n\\vspace{0.5cm}\n\n%%general idea\nThis section will explain the theory behind RL. The post by Lilian Weng is recommended as a resource on more precise explanations on RL \\cite{rllilianweng}. RL is usually modeled as a Markov Decision Process. The Markov Decision Process for RL consists of following elements \\cite{rlwiki}:\n\n\\begin{itemize}\n\t\\item A set of states S\n\t\\item A set of actions A\n\t\\item The transition probability $P_a(s,s')$ from state s to s' under action a\n\t\\item The immediate reward $R_a(s,s')$ of that transition\n\t\\item rules that describe the agents observation\n\\end{itemize}\n\nThe agent and environment are in a state s. The agent chooses an action a from its set of possible actions A to interact with the environment. The environment reacts by transitioning to another state and returning a reward R and an observation to the agent. Depending on the model the transitions might be stochastic or deterministic. The aim of the agent is to earn the maximal total reward possible. In order to reach this aim, the agent interacts with the environment to gain knowledge about the environment through the gained rewards and observations. Through this process, the agent learns in which state which actions are better to gain more reward. This is illustrated by Figure \\ref{rl_general}.\n\n\\begin{figure} [h]\n\t\n\t\\centering\n\t\\includegraphics[width=1\\textwidth]{figures/rl_general.pdf}\n\t\\caption{Reinforcement Learning. An agent chooses an action to interact with the environment and gets a reward and an observation of his new state back. \n\t\t\\label{rl_general}\t\n\t\t\\cite{rl_general.jpg}\n\t}\n\\end{figure}\n\n\\vspace{0.5cm}\n\n%policy \nIn each state there is an action that the agent considers best due to its current knowledge about the expected rewards of each action. This set of actions is known as the policy \n$\\pi (s)$. \nThe goal of getting maximal reward can be interpreted as finding the best actions in each state that give the most reward, which is finding the optimal policy. The policy can also be either deterministic or stochastic, depending on the transition probability of the environment.\n\n\\vspace{0.5cm}\n\n%value function\nA value function is used to measure how good a state or action is. Two types of value functions are used for the states and the actions. the state value function is denoted as V(s). The value of a state is the expected reward when acting according to the policy \n$\\pi$ \\cite{rlwiki}.\nV(s) is defined as follows in equation \\ref{eq:state-value-function}.\n\n\\begin{equation}\n\\label{eq:state-value-function}\nV^\\pi (s) = \\mathbb{E} [R | s,\\pi]\n\\end{equation}\n\nThe actions value function is denoted as Q(s,a) and is defined In equation \\ref{eq:action-value-function}.\n\n\\begin{equation}\n\\label{eq:action-value-function}\nQ^\\pi (s,a) = \\mathbb{E} [R | s,a,\\pi]\n\\end{equation}\n\nWhen determining the value of a state or action, a discount factor $\\gamma$\nis used to discount future rewards towards immediate rewards. \nThe idea is that a state s is not only as good as the reward you get when transitioning to that state. Future rewards from states that are reachable from state s should also be considered. The value of a state consists of the reward that you get by transitioning to that state and the potential rewards that can be gained by transitioning from that state. \nSince future rewards are not as certain as immediate rewards, the discount factor is used. The farther a reward is in the future, the more it is discounted. \n%bellman equations\nThe Bellman equations described in equation \\ref{eq:V-bellman} and \\ref{eq:Q-bellman} are a set of equations that convert the value functions into the immediate and future reward and can be used to update the value-functions \\cite{rllilianweng}.\n\n\\begin{equation}\n\\label{eq:V-bellman}\nV_\\pi (s) = \\sum_{a \\in A}  \\pi(a|s) (R(s,a) + \\gamma \\sum_{s' \\in S} P_{ss'}^a V_\\pi (s'))\n\\end{equation}\n\n\\begin{equation}\n\\label{eq:Q-bellman}\nQ_\\pi (s,a) = R(s,a) + \\gamma \\sum_{s' \\in S} P_{ss'}^a \\sum_{a \\in A}  \\pi(a'|s') Q_\\pi(s',a')\n\\end{equation}\n\nThe goal is to find the actions that return the maximal reward. This is displayed by the Bellman optimality equations (\\ref{eq:V-optbellman},\\ref{eq:Q-optbellman}) \\cite{rllilianweng}:\n\n\\begin{equation}\n\\label{eq:V-optbellman}\nV_\\ast (s) = \\max_{a \\in A} (R(s,a) + \\gamma \\sum_{s' \\in S} P_{ss'}^a V_\\ast (s'))\n\\end{equation}\n\n\\begin{equation}\n\\label{eq:Q-optbellman}\nQ_\\ast (s,a) = R(s,a) + \\gamma \\sum_{s' \\in S} P_{ss'}^a \\max_{a \\in A} Q_\\ast(s',a')\n\\end{equation}\n\nTo calculate the optimal values of each state and action, Dynamic Programming could be used if the entire model is known. But even knowing the entire model is not good enough as usually the main issue lies in the huge state and action space, which makes it impossible to use Dynamic Programming. For RL, artificial neural networks (ANNs) can be used to approximate the value functions \\cite{neuralnetpath}. \n\nWhen following the current policy, the agent will earn the maximal reward that it could earn with current knowledge, but never more than that. To learn, the agent has to deviate from the policy and explore different actions and states. The question is how much deviation is necessary, as the agent also needs to exploit most of the policy path it has learned until now because following most of the policy has a higher probability of earning a high reward. This is known in RL as the exploration vs. exploitation problem. Usually there is a variable $\\epsilon$ that determines with which probability the agent will deviate from the policy. It is set rather low to let the agent exploit most of its policy. As an example, an approach is $\\epsilon$-greedy \\cite{egreedy}. With a high probability of $1-\\epsilon$ the agent will choose the policy and with a probability of $\\epsilon$ a random action is chosen. This ensures that the agent exploits most of the policy, but also explores more possible actions that might bring more reward. \n\n%%neuronal networks\n\\section{Artificial Neural Networks}\n\nANNs are inspired by the human brain. \n%\\nnbio, blablabla\nThe ANN consists of layers of neurons. Each neuron is connected to the next layer of neurons. There is one input layer and one output layer at the beginning and end of the layer of neurons. The layers between the input and output layers are called hidden layer. The hidden layer can consist of only one or more layers. The idea is to train the ANN to take inputs and produce outputs. To approximate the value functions the input would be states and actions, the output should be the correct and optimal values of these states and actions. An example of an ANN is shown in Figure \\ref{neuralnet}.\n\n\\begin{figure} [h]\n\t\\centering\n\t\\includegraphics[width=1\\textwidth]{figures/neural_network.pdf}\n\t\\caption{A neural network. \\cite{neural_networkpng}}\n\t\\label{neuralnet}\n\\end{figure}\n\n\\vspace{0.5cm}\n\nThe learning process of the neuronal network is as follows. Each neuron obtains inputs $x_i$ by the the outputs of the neurons in the layer before it. Each input value is weighted and then the sum of these weighted values is taken. A bias $b$ is also added to support the learning process. After using an activation function on the sum, the value is output to the next layer of neurons. The activation function is a simple function that either reduces the output of the neuron to 0 if the value is below a certain threshold, otherwise the value is output unfiltered.\nThe training process of the neuron can be seen in Figure \\ref{neuron}.\n%besser formulieren!\n\n\\begin{figure} [h]\t\n\t\\centering\n\t\\includegraphics[width=1\\textwidth]{figures/neuron.pdf}\n\t\\caption{A neuron and how its value is composed \\cite{neuron.jpeg}}\n\t\\label{neuron}\n\\end{figure}\n\n\\vspace{0.5cm}\n\nWhen the ANN outputs a value, a process called Backpropagation is used to improve the ANN \\cite{backprop}. When initializing the ANN, the actual right weights for the input values are unknown, so random values for the weights are used. Therefore, the output values will not be right. By using an error function, the amount of error can be computed. The amount of error can be used to figure out how much the weights have to be modified for the output to become right. Backpropagation is the process of going backwards through the ANN and improving the weights of the neurons that caused the output value to be wrong. By repeating the whole process, the weight of each neuron converges towards an optimal value. \n\n\\vspace{0.5cm}\n\n\\section{Deep Deterministic Policy Gradients}\n\nThe paper by Silver et al. is a recommended resource for more detailed explanations \\cite{ddpg}. This chapter will give a short summary of DDPG.\nThe algorithm DDPG learns concurrently a Q-function (the action-value function) and a policy. \\cite{ddpg}\nQ*(s,a) is used to find the the optimal action in each state.\nTo compute the Q-values for a discrete action space, the Q-values of each action could be calculated and compared to find the biggest value. But in a continuous action space it is not possible to calculate the Q-value for each action. DDPG uses the fact that the action space is continuous and so Q*(s,a) is expected to be differentiable in respect to the action argument. \\cite{ddpg}\nThis way it is possible to approximate the Q-values and policy.\n\n\\vspace{0.5cm}\n\nTo learn the Q-values, the Bellman equation for the action value is used. To approximate the Q-values, a mean squared Bellman error function is used.\nThe idea is that minimizing this function error is equal to approximating the current Q-values to the optimal Q-values.\n\n\\vspace{0.5cm}\n\nFor DDPG an experience replay buffer is also used. The replay buffer is a set of experiences. This can be used to replay old experiences. When only using new experiences, the ANN might be overfit to those experiences. Being overfit means that for some experiences the ANN will output very good results, but for most other experiences it will perform very bad. Experience replay is useful to prevent that. But a too large buffer can cause the learning process to slow down. The right balance has to be found.\n\nDDPG also uses target networks. Equation \\ref{eq:target} is called target \\cite{ddpg}.\n\n\\begin{equation}\n\\label{eq:target}\nr + \\gamma (1-d) \\max_{a'} Q_\\phi(s',a')\n\\end{equation}\n\nThe target is what is desired for the Q-function to approximate to.\nWhen minimizing the mean squared bellman error function, there is the problem that the target is also dependent on the parameters that are trained. When changing the parameters, the target would also change which is problematic. That is why the target network, a copy of the ANN is used. The update of the target network is delayed to avoid this conflict.\nTo find the optimal policy, simply gradient ascent can be used to find the maximal Q-values.\n\n\n\\section{Hindsight Experience Replay}\n\n%subsection curriculum learning ?\n\n%read paper, use it\nSparse rewards are a big issue in RL, especially in tasks for robotic arms often the rewards are sparse. Having sparse rewards means that most of the samples used for training will not successful and therefore will not bring any useful reward. For example, the task to move an object to a certain point would have a sparse reward for a robotic arm because very precise movements are needed which the robotic arm has to learn first.\n \n\\vspace{0.5cm}\n \nAndrychowicz et al. have shown that HER can be used to deal with this issue for robotic arms \\cite{herpaper}\nHER can learn efficiently from sparse rewards and can also be combined with any off-policy RL algorithm.\nThis technique is inspired by the ability of humans to learn from failures as least as much as from successes.\n\n\\vspace{0.5cm}\n\nHER works as follows. After an episode of gaining experiences, all transitions between the states in each training sample is stored in a replay buffer, but the goal that was not achieved is extended to a set with a goal that is reached. This can also be further extended to a set of more goals that can be achieved in the terminating state of the training sample. If the goal was to move an object to point x, but it was pushed to point y, the replay buffer would use the same transitions but change the the goal we wanted to achieve to y. So when replaying the same experience, the agent would be successful and earn an useful reward. This does not help the agent learn how to reach the goal it wanted to reach initially, but it learns how to reach other goals. Being able to reach those other already achieved goals might be beneficial in learning how to reach the goal it actually wanted to achieve. HER is mainly used for tasks with multiple goals, but it was shown that it also improves the training of tasks with only a single goal. \\cite{herpaper}\nInterestingly, Andrychowicz et al. have shown HER performs has problems when using shaped rewards. \\cite{herpaper}\n%add binary rewards at start of section ?. binary != shaped ?\n \n %add pseudocode ?\n", "meta": {"hexsha": "c7960e6b4c468a6a8d37da31ad7c28be2f6d581e", "size": 15494, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Thesis_AntonMai/chapters/theory.tex", "max_stars_repo_name": "3nt0n/bachelor_thesis", "max_stars_repo_head_hexsha": "ba4e1849ed5f2db1736002c5fc95ea47435a648f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Thesis_AntonMai/chapters/theory.tex", "max_issues_repo_name": "3nt0n/bachelor_thesis", "max_issues_repo_head_hexsha": "ba4e1849ed5f2db1736002c5fc95ea47435a648f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Thesis_AntonMai/chapters/theory.tex", "max_forks_repo_name": "3nt0n/bachelor_thesis", "max_forks_repo_head_hexsha": "ba4e1849ed5f2db1736002c5fc95ea47435a648f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 84.6666666667, "max_line_length": 1088, "alphanum_fraction": 0.7826255325, "num_tokens": 3603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.3024386177109419}}
{"text": "\n% ============================================================================\n\n\\subsection{Shared Bitmanip Extension Functionality}\n\\label{sec:scalar:bitmanip}\n\nMany of the primitive operations used in symmetric key cryptography\nand cryptographic hash functions are well supported by the\nRISC-V Bitmanip \\cite{riscv:bitmanip:repo} extension\n\\footnote{\nAt the time of writing, the Bitmanip extension is still undergoing\nstandardisation.\nPlease refer to the Bitmanip draft specification\n\\cite{riscv:bitmanip:draft}\ndirectly for the\nlatest information, as it may be slightly ahead of what is described\nhere.\n}.\nWe propose that the scalar cryptographic extension {\\em reuse} a\nsubset of the instructions from the Bitmanip extension directly.\nSpecifically, this would mean that\na core implementing\n{\\em either}\nthe scalar cryptographic extensions,\n{\\em or}\nthe Bitmanip extension,\n{\\em or}\nboth,\nwould be required to implement these instructions.\n\n%\n% TODO: Venn diagram of proposed instructions.\n%\n\nThe following subsections give the assembly syntax of instructions\nproposed for inclusion in the scalar crypto extension, along with a\nset of use-cases for common algorithms or primitive operations.\nFor information on the semantics of the instructions, we refer directly\nto the Bitmanip draft specification.\n\n\\subsubsection{Rotations}\n\\label{sec:scalar:bitmanip:rotate}\n\n\\begin{cryptobitmanipisa}\nRV32, RV64:                         RV64 only:\n    ror    rd, rs1, rs2                 rorw   rd, rs1, rs2\n    rol    rd, rs1, rs2                 rolw   rd, rs1, rs2\n    rori   rd, rs1, imm                 roriw  rd, rs1, imm\n\\end{cryptobitmanipisa}\n\nSee \\cite[Section 3.1.1]{riscv:bitmanip:draft} for details of\nthese instructions.\nStandard bitwise rotation is a primitive operation in many block ciphers and\nhash functions;\nit features particularly in the ARX (Add, Rotate, Xor) class of\nblock ciphers\n\\footnote{\\url{https://www.cosic.esat.kuleuven.be/ecrypt/courses/albena11/slides/nicky_mouha_arx-slides.pdf}}\nand stream ciphers.\n\nAlgorithms making use of 32-bit rotations:\nSHA256, AES (Shift Rows), ChaCha20, SM3.\n\nAlgorithms making use of 64-bit rotations:\nSHA512, SHA3.\n\n\\subsubsection{Bit \\& Byte Permutations}\n\\label{sec:scalar:bitmanip:grev}\n\n\\begin{cryptobitmanipisa}\nRV32:\n    rev.b   rd, rs1 // grevi rd, rs1,  7 - Reverse bits in bytes\n    rev8    rd, rs1 // grevi rd, rs1, 24 - Reverse bytes in 32-bit word\n\nRV64:\n    rev.b   rd, rs1 // grevi rd, rs1,  7 - Reverse bits in bytes\n    rev8    rd, rs1 // grevi rd, rs1, 56 - Reverse bytes in 64-bit word\n    rev8.w  rd, rs1 // grevi rd, rs1, 24 - Reverse bytes in 32-bit words\n\\end{cryptobitmanipisa}\n\nThe scalar cryptography extension provides the following instructions for\nmanipulating the bit and byte endianness of data.\nThey are all parameterisations of the Generalised Reverse with Immediate\n({\\tt grevi}) instruction.\nThe scalar cryptography extension requires {\\em only} the above instances\nof {\\tt grevi} be implemented, which can be invoked via their pseudo-ops.\n\nReversing bytes in words is very common in cryptography when setting a\nstandard endianness for input and output data.\nBit reversal within bytes is used for implementing the GHASH  component\nof Galois/Counter Mode (GCM)~\\cite{nist:gcm}.\n\nCores which also implement the Bit-manipulation extension {\\em must}\nimplement the complete {\\tt grevi} instruction, with all immediate values\nsupported.\nThe full specification of the {\\tt grevi} instruction is available in\n\\cite[Section 2.2.2]{riscv:bitmanip:draft}.\n\n\\begin{cryptobitmanipisa}\nRV32:\n    zip     rd, rs1 // shfli   rd, rs1, 15 - Bit interleave\n    unzip   rd, rs1 // unshfli rd, rs1, 15 - Bit de-interleave\n\\end{cryptobitmanipisa}\n\nThe {\\tt zip} and {\\tt unzip} pseudo-ops are specific instances of\nthe more general {\\tt shfli} and {\\tt unshfli} instructions.\nThe scalar cryptography extension requires {\\em only} the above instances\nof {\\tt [un]shfli} be implemented, which can be invoked via their\npseudo-ops.\nOnly RV32 implementations require these instructions.\nThey perform a bit-interleave (or de-interleave) operation, and are\nuseful for implementing the 64-bit rotations in the\nSHA3~\\cite{nist:fips:202} algorithm on\na 32-bit architecture\\footnote{\nIt is also useful for the ASCON cipher, which is a candidate in the\nNIST Lightweight Cryptography competition.\n}.\nOn RV64, the relevant operations in SHA3 can be done natively, so\n{\\tt zip} and {\\tt unzip} are not required.\n\nCores which also implement the Bit-manipulation extension {\\em must}\nimplement the complete {\\tt [un]shfli} instruction, with all immediate values\nsupported.\nThe full specification of the {\\tt shfli} instruction is available in\n\\cite[Section 2.2.3]{riscv:bitmanip:draft}.\n\n\\subsubsection{Carry-less Multiply}\n\n\\begin{cryptobitmanipisa}\nRV32, RV64:\n    clmul  rd, rs1, rs2\n    clmulh rd, rs1, rs2\n\\end{cryptobitmanipisa}\n\nSee \\cite[Section 2.6]{riscv:bitmanip:draft} for details of\nthis instruction.\nAs is mentioned there, obvious cryptographic use-cases for carry-less\nmultiply are for Galois Counter Mode (GCM) block cipher operations\n\\footnote{\\url{https://en.wikipedia.org/wiki/Galois/Counter_Mode}}.\nGCM is recommended by NIST as a block cipher mode of operation\n\\cite{nist:gcm}, and is the only {\\em required} mode for the TLS 1.3\nprotocol.\n\nSee Section \\ref{sec:scalar:timing} for additional implementation\nrequirements for this instruction, related to data independent\nexecution latency.\n\n\\subsubsection{Logic With Negate}\n\n\\begin{cryptobitmanipisa}\nRV32, RV64:\n    andn rd, rs1, rs2\n     orn rd, rs1, rs2\n    xnor rd, rs1, rs2\n\\end{cryptobitmanipisa}\n\nSee \\cite[Section 2.1.3]{riscv:bitmanip:draft} for details of\nthese instructions.\nThese instructions are useful inside hash functions, block ciphers and\nfor implementing software based side-channel countermeasures like masking.\nThe {\\tt andn} instruction is also useful for constant time word-select\nin systems without the ternary Bitmanip {\\tt cmov} instruction.\n\nUseful for:\nSHA3 Chi step,\nbit-sliced function implementations\nand\nsoftware based power/EM side-channel countermeasures based on masking.\n\n\\subsubsection{Packing}\n\n\\begin{cryptobitmanipisa}\nRV32, RV64:                         RV64: \n    pack   rd, rs1, rs2                 packw  rd, rs1, rs2\n    packu  rd, rs1, rs2                 packuw rd, rs1, rs2\n    packh  rd, rs1, rs2\n\\end{cryptobitmanipisa}\n\nSee \\cite[Section 2.1.4]{riscv:bitmanip:draft} for details of\nthese instructions.\nSome lightweight block ciphers\n(e.g., SPARX \\cite{DPUVGB:16})\nuse sub-word data types in their primitives.\nThe Bitmanip pack instructions are useful for performing rotations on\n16-bit data elements.\nThey are also useful for re-arranging halfwords within words, and\ngenerally getting data into the right shape prior to applying transforms.\nThis is particularly useful for cryptographic algorithms which pass inputs\naround as byte strings, but can operate on words made out of those byte\nstrings.\nThis occurs for AES when loading blocks and keys (which may not be\nword aligned) into registers to perform the round functions.\n\n\n\\subsubsection{Crossbar Permutation Instructions}\n\\label{sec:xperm}\n\n\\begin{cryptobitmanipisa}\nRV32, RV64:\n    xperm.n rd, rs1, rs2\n    xperm.b rd, rs1, rs2\n\\end{cryptobitmanipisa}\n\nSee \\cite[Section 2.2.4]{riscv:bitmanip:draft} for a complete\ndescription of this instruction.\n\nThe {\\tt xperm.n} instruction operates on nibbles.\nThe \\rsone register contains a vector of $\\XLEN/4$ $4$-bit elements.\nThe \\rstwo register contains a vector of $\\XLEN/4$ $4$-bit indexes.\nThe result is each element in \\rstwo replaced by the indexed element\nin \\rsone, or zero if the index into \\rstwo is out of bounds.\n\nThe {\\tt xperm.b} instruction operates on bytes.\nThe \\rsone register contains a vector of $\\XLEN/8$ $8$-bit elements.\nThe \\rstwo register contains a vector of $\\XLEN/8$ $8$-bit indexes.\nThe result is each element in \\rstwo replaced by the indexed element\nin \\rsone, or zero if the index into \\rstwo is out of bounds.\n\nThe instruction can be used to implement arbitrary bit\npermutations.\nFor cryptography, they can accelerate bit-sliced implementations,\npermutation layers of block ciphers, masking based countermeasures\nand SBox operations.\n\n%Figure \\ref{fig:example:xperm} shows example implementations of the\n%$4$-bit PRINCE SBox using the instructions.\nLightweight block ciphers using $4$-bit SBoxes include\nPRESENT\\cite{block:present},\nRectangle\\cite{block:rectangle},\nGIFT\\cite{block:gift},\nTwine\\cite{block:twine},\nSkinny, MANTIS\\cite{block:skinny},\nMidori \\cite{block:midori}.\n\nNational ciphers using $8$-bit SBoxes include\nCamellia\\cite{block:camellia} (Japan), \nAria\\cite{block:aria} (Korea),\nAES\\cite{nist:fips:197} (USA, Belgium),\nSM4\\cite{block:sm4:1} (China)\nand Kuznyechik (Russia).\nAll of these SBoxes can be implemented efficiently, in constant\ntime, using the {\\tt xperm.b} instruction\\footnote{\n    \\url{http://svn.clairexen.net/handicraft/2020/lut4perm/demo02.cc}\n}.\nNote that this technique is also suitable for masking based\nside-channel countermeasures.\n\n%\\begin{figure}[h]\n%\\begin{lstlisting}[style=ASM]\n%prince_sbox_rv64:\n%    li  t0, 0x4D5E087619CA23FB  // Load the prince block cipher SBox\n%    xperm.n a0, t0, a0          // a0.4[i] = t0.4[a0.4[i]]\n%    ret\n%\n%prince_sbox_rv32:\n%    li  t0, 0x4D5E0876  // Load last  8 elements of prince sbox\n%    li  t1, 0x19CA23FB  // Load first 8 elements of prince sbox\n%    li  t2, 0x88888888  // Bit mask for MS bits of index nibbles.\n%    xperm.n a1, t1, a0  // a1.4[i] = t1.4[a0.4[i]] if a0.4[i] < 8 else 0\n%    xor     a0, a0, t2  // Toggle MS bit of each nibble in input vector\n%    xperm.n a0, t0, a0  // a0.4[i] = t1.4[a0.4[i]] if a0.4[i] < 8 else 0\n%    or      a0, a0, a1  // Or results together.\n%    ret\n%\\end{lstlisting}\n%\\caption{\n%    Example implementations of the $4$-bit PRINCE\\cite{block:prince}\n%    block cipher SBox using the \\mnemonic{xperm.n} instruction.\n%}\n%\\label{fig:example:xperm}\n%\\end{figure}\n", "meta": {"hexsha": "9f9b487e72afc3b783d1e0fbc8c92f3d20eb3506", "size": 9990, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/old-tex/tex/sec-scalar-bitmanip.tex", "max_stars_repo_name": "dingiso/riscv-crypto", "max_stars_repo_head_hexsha": "608f550ea2a791fb091133fe6050321545dfc547", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 199, "max_stars_repo_stars_event_min_datetime": "2020-08-13T15:48:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:57:34.000Z", "max_issues_repo_path": "doc/old-tex/tex/sec-scalar-bitmanip.tex", "max_issues_repo_name": "dingiso/riscv-crypto", "max_issues_repo_head_hexsha": "608f550ea2a791fb091133fe6050321545dfc547", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 118, "max_issues_repo_issues_event_min_datetime": "2020-08-13T16:09:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T20:00:35.000Z", "max_forks_repo_path": "doc/old-tex/tex/sec-scalar-bitmanip.tex", "max_forks_repo_name": "dingiso/riscv-crypto", "max_forks_repo_head_hexsha": "608f550ea2a791fb091133fe6050321545dfc547", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 56, "max_forks_repo_forks_event_min_datetime": "2020-08-28T16:09:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T10:10:58.000Z", "avg_line_length": 37.0, "max_line_length": 109, "alphanum_fraction": 0.7432432432, "num_tokens": 2882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.30227283316687614}}
{"text": "% !TeX spellcheck = en_GB\n\\section{Surface, Thickness, Wind}\n\\label{sec:Geop}\n%A good overview gives the sea level pressure, \\SI{1000}-\\SI{500}{\\hPa} thickness map and winds at \\SI{250}{\\hPa}. \\Cref{fig:GeopJet} shows, that it combines several important features of the vertical distribution within the atmosphere, for example.\\\\\n%Black contour lines indicate sea level pressure in \\SI{}{\\hPa} and makes it possible to observe cyclones and anticyclones at the sea surface. \nA complementary view of the three-dimensional structure of the atmosphere is also presented:  \\SI{250}{\\hPa} wind speed (colour shading, \\SI{}{\\mPs}), mean sea level pressure (black contours, \\SI{}{\\hPa}), \\num{1000}--\\SI{500}{\\hPa} thickness (dashed contours) and the total precipitable water (black-white shading, \\SI{}{\\mm}). See \\Cref{fig:GP24_pres} for an example.\n% %%% Geopot Jet maps %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% \\input{images_tex/WeatherSit_GeopotJet}\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\\noindent \n\\\\\nThe dashed, coloured contours in \\Cref{fig:GP24_pres} show the vertical thickness between the \\SI{1000}{\\hPa} and \\SI{500}{\\hPa} surface, every \\SI{6}{\\deca\\meter}. The thickness between two pressure levels can be interpreted via the hypsometric equation (\\Cref{eq:hypsometric}), which equates the thickness to the mean temperature of the layer in question. In a relative sense, a larger thickness indicates a warmer air mass. In addition, strong horizontal gradients in the thickness field can be related to frontal boundaries. Specific to the discussion in this thesis, the thickness field also provides useful information regarding the form of precipitation (liquid, frozen).\n%This is a relation of the mean temperature of the air between two pressure levels. Thus, high values of thickness mean relative warm, moist air (red, dashed). This can then be associated to rain or snow in mid-latitudes, depending on cold or warm air advection.\n\\\\\n%Gray shaded areas describe total precipitable water in the atmosphere in \\SI{}{\\mm}. \nAnalysis of the mean sea level pressure can be used to identify cyclones (L) and anticyclones (H) at the surface as well as provide supplementary information regarding frontal boundaries (\\Cref{fig:GP24_pres}).\nThe total precipitable water is a measure of the column integrated moisture. It represents an instantaneous measure of moisture in time and space, which can be useful when assessing the amount of moisture that may fall as precipitation in future time steps.\nThe \\SI{250}{\\hPa} wind speeds are used to identify strong upper-level flow (i.e. the jet stream) and can be directly compared to the dynamic tropopause map (\\Cref{fig:DT24_pres}).\n% It is an indicator for the amount of moisture to supply rainfall, and will be used to identify where moisture was present.\n% \\\\\n% Colour shaded contours in \\Cref{fig:GeopJet} indicate the mid-latitudal jet streaks at \\SI{250}{\\hPa}. Warmer colour is associated with higher wind speeds at this level.  \n\n% %% Geopot Jet maps %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% \\input{images_tex/WeatherSit_GeopotJet}\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%", "meta": {"hexsha": "b95934e67329bdf5387217093be4446fb5675948", "size": 3201, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis_full/Weather_Situation/thickness_map.tex", "max_stars_repo_name": "franzihe/Latex_thesis", "max_stars_repo_head_hexsha": "128284a01155bdc28b3e9374e538a07a1e5722c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thesis_full/Weather_Situation/thickness_map.tex", "max_issues_repo_name": "franzihe/Latex_thesis", "max_issues_repo_head_hexsha": "128284a01155bdc28b3e9374e538a07a1e5722c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis_full/Weather_Situation/thickness_map.tex", "max_forks_repo_name": "franzihe/Latex_thesis", "max_forks_repo_head_hexsha": "128284a01155bdc28b3e9374e538a07a1e5722c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 128.04, "max_line_length": 678, "alphanum_fraction": 0.7197750703, "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3022728255546675}}
{"text": "\\begin{document}\n\\section{Difficulty from Replays}\n\nWe are able to extract data from replays, however, they are not linked to the beatmaps themselves. This means that it only has data of what keys and when did the player press it, there's no data on accuracy achieved.\n\nTo recap, we managed to decode the replay sent into the following format:\n\n$$ action_{replay} := \\lbrace(offset_1, action_1), (offset_2, action_2), ... , (offset_n, action_n)\\rbrace $$\n\nWhereby, \n$$n \\in \\lbrace-9, -8, ... , -2, -1, 1, 2, ... , 8, 9\\rbrace$$\n\n$offset$ is when the $action$ happens. For $action$, $-n$ means the key \\textbf{n} is released, $n$ means the key \\textbf{n} is pressed. In this section, we will be discussing how we can make this a suitable output for the neural network to predict.\n\n\\subsection{Mapping a Replay to Beatmap}\n\nIn this, we match all similar actions in their respective columns.\n\nThere are a few things we need to take note of when matching:\n\\begin{enumerate}\n\t\\item Not all $action_{beatmap}$ will have a matching $action_{replay}$\n\t\\item We put the threshold of this matching as $100ms$, i.e. $action_{beatmap}$ that doesn't have any $action_{replay}$ within $100ms$ will be regarded as a miss.\n\t\\item The nearest $action_{replay}$ will match the $action_{beatmap}$, not the earliest one.\n\t\\item We will deviate on how osu! calculate accuracy due to the above pointers, this allows us to calculate on a more common basis.\n\\end{enumerate}\n\nWe will expect the output of:\n\n$$ deviation := \\lbrace(offset_1, deviation_1), (offset_2, deviation_2), ..., (offset_n, deviation_n)\\rbrace $$\n\nWhere:\n$$ n = length(action_{beatmap}) $$\n\nAnd if there's no match, $deviation > 100$, this is to allow us to understand that it's a \\textbf{miss} instead of a $100ms$ hit.\n\nThis doesn't proportionally represent accuracy (which will be easier to understand), as its lower value represents a better judgement, so we will adjust to the following:\n$$ accuracy := \\lbrace(offset_1, accuracy_1), (offset_2, accuracy_2), ..., (offset_n, accuracy_n)\\rbrace $$\n\nWhere:\n$$ accuracy_n = 100 - {deviation_n} $$\n\nTherefore, a \\textbf{miss} would simply just be $accuracy = 0$ instead.\n\nSo accuracy will only span:\n$$ (Miss) 0 \\leq accuracy_n \\leq (Perfect) 1 $$\n$$ where, deviation_n \\in [0, 1, 2, ..., 99, 100] $$\n\n\\subsection{Replay Soloing}\n\nAs discussed in the preface, we need to resolve two issues. \\textbf{Multiple Replays} and \\textbf{Multiple Players}. We will expect an output similar to a replay, this is where the first major assumption kicks in.\n\n\\subsubsection{Assumption of the Top 50}\nIn this, we assume that if we took the \\textbf{median} all top 50 replays, we will end up with a replay that is all-encompassing.\n\nThis leads some problems:\n\n\\paragraph{Top Player Bias} The neural network will perform worse on easier maps $ \\approx 3.0 S.R. $ due to the median in easier maps being too consistently perfect, this leads to amplification of noise (in this case, chokes).\n\\paragraph{Population Interaction} This assumption will only hold if the beatmaps are old enough such that most of the general playerbase has played it, else it doesn't represent the population well enough due to low participation\n\\paragraph{Population Decay/Improvement} The beatmaps we check must be ranked within close proximity with each other, this is to avoid the Top 50 median from adjusting too much\n\n\\subsubsection{Assumption of the Player}\nIn this, instead of looking at it \\textbf{per beatmap}, we will do it \\textbf{per player}. This is much more consistent in data, however it's consistent \\textbf{for that player only}.\n\nIn this method, we grab the all replays that \\textbf{Player X} has played and compare them with each other. However this still leads to assumptions:\n\n\\begin{enumerate}\n\t\\item The player played all the beatmaps at a similar time, or the player never improved\n\t\\item The player is representative of the community (bias)\n\\end{enumerate}\n\nThe problem of the machine being \\textbf{biased} to only the player can be fixed if we ran an averaging function on the output with hundreds of other players.\n\n\\textbf{However,} due to how osu! sends API scores, I couldn't get more than \\textbf{50} scores \\textbf{per player}. This means that there will be no data for these replays.\n\n\\subsection{Choosing an Assumption}\n\nDespite this, we will work with \\textbf{Assumption of the Top 50} as it's reasonable enough, and it's easier.\n\nThis means that the median of all replays will be saved in a different data file with $<beatmap\\_id>.acrv$ extension. \\textit{(v represents virtual)}\n\n\\subsection{Virtual Player/Replay}\n\nThe median of the top 50 creates a \\textbf{virtual replay}, where we expect it to be a \\textbf{good enough} representation of a \\textbf{virtual player}. We can now pivot from this player as we calculate difficulty!\n\n\\subsection{Smoothing}\n\nAs expected, the median gathered will not be a smooth graph, we will smooth out with an \\textbf{moving aggregation of its mean with a window of 30}. This means that it'll grab 30 data points, front and back, and calculate its median, creating a new series/vector.\n\nAs player's deviations usually will not be consistent throughout, this will help hammer down large errors, while also affecting its neighbouring data points. In turn, this aids the machine to learn that the error may not only be the issue of that one note, but instead a group of it.\n\n\\end{document}\n", "meta": {"hexsha": "e0dcf1dcff66900889ce534c080907275bbd3373", "size": 5416, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "research_tex/process/difficulty_from_replays.tex", "max_stars_repo_name": "Eve-ning/ppshift_ml", "max_stars_repo_head_hexsha": "d693aaef9a224ad335a04867965f797fe887f1fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-15T10:56:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-15T10:56:09.000Z", "max_issues_repo_path": "research_tex/process/difficulty_from_replays.tex", "max_issues_repo_name": "Eve-ning/ppshift_ml", "max_issues_repo_head_hexsha": "d693aaef9a224ad335a04867965f797fe887f1fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "research_tex/process/difficulty_from_replays.tex", "max_forks_repo_name": "Eve-ning/ppshift_ml", "max_forks_repo_head_hexsha": "d693aaef9a224ad335a04867965f797fe887f1fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 58.8695652174, "max_line_length": 283, "alphanum_fraction": 0.7570162482, "num_tokens": 1377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3022728255546675}}
{"text": "\\documentclass{documentation}\n\n\\title{Densor Package}\n\n\\author{Joshua Maglione}\n\\address{Universit\\\"at Bielefeld}\n\\email{jmaglione@math.uni-bielefeld.de}\n\n\\author{James B. Wilson}\n\\address{Colorado State University}\n\\email{james.wilson@colostate.edu}\n\n\\version{1.0}\n\\date{\\today}\n\\copyrightyear{2016--2019}\n\n\\input{preamble.tex}\n\n%-----------------------------------------------------------------------------\n\\begin{document}\n\n\\frontmatter\n\n\\dominitoc\n\\maketitle\n\\tableofcontents\n\n\\mainmatter\n\n\\chapter{Introduction}\n\n\n\n\n\\chapter{Subspaces as closures}~\n\nThe subspaces in this section are given by Galois connections in \\cite{FMW:densors}*{Theorem~A}. \nCurrently, these are the only closures that are constructible in this package, and they are implemented for 3-tensors.\n\n\\index{DerivationClosure}\n\\begin{intrinsics}\nDerivationClosure(T, Delta) : TenSpc, AlgMat -> TenSpc\nDerivationClosure(T, Delta) : TenSpc, ModMatFld -> TenSpc\nDerivationClosure(T, Delta) : TenSpc, AlgMatLie -> TenSpc\nDerivationClosure(T, Delta) : TenSpc, [Mtrx] -> TenSpc\nDerivationClosure(T, Delta) : TenSpc, [AlgMatLie] -> TenSpc\n\\end{intrinsics}\n\nReturns the derivation closure of the given tensor space $T$, with frame $U_2\\times U_1\\rightarrowtail U_0$, with operators $\\Delta\\subseteq \\text{End}(U_2)\\times \\text{End}(U_1)\\times \\text{End}(U_0)$.\nIf a nontrivial subset of coordinates are fused, then \\texttt{DerivationClosure} accepts $\\Delta$ input from the smaller ambient space. \nFor example, if coordinates $2$ and $1$ are fused, then the input for $\\Delta$ can be in either $\\text{End}(U_2)\\times\\text{End}(U_1)\\times\\text{End}(U_0)$ or $\\text{End}(U_2)\\times\\text{End}(U_0)$.\nCurrently, this only works for tensor spaces of valence 3.\nThis is the subspace whose tensors' derivation algebra contains $\\Delta$.\n\n\\index{DerivationClosure}\n\\begin{intrinsics}\nDerivationClosure(T, t) : TenSpc, TenSpcElt -> TenSpc\n\\end{intrinsics}\n\nReturns the derivation closure of the given tensor space $T$, with frame $U_2\\times U_1\\rightarrowtail U_0$, whose operators are the derivation algebra of $t$. \nCurrently, this only works for tensor spaces of valence 3.\nThis is the subspace whose tensors' derivation algebra contains the derivation algebra of $t$.\n\n\\index{UniversalDensorSubspace}\n\\begin{intrinsics}\nUniversalDensorSubspace(t) : TenSpcElt -> TenSpc\n\\end{intrinsics}\n\nReturns the universal densor subspace of the given tensor $t : U_2\\times U_1 \\rightarrowtail U_0$ as a subspace of the universal tensor space of $t$, whose operators are the derivation algebra of $t$. \nCurrently, this only works for tensor spaces of valence 3.\nThis is equivalent to \\texttt{DerivationClosure(Parent(t), t)}. \nThis tensor subspace is stored with $t$ once computed.\n\n\\begin{example}[Rank1Densor]\n\nWe illustrate the fact that the tensor for (hyper-)matrix multiplication spans its densor, see \\cite{FMW:densors}*{Theorem~G}.\nWe will construct the derivation closure of $\\bra{t}:\\mathbb{M}_{2\\times 3}(\\mathbb{F}_3)\\times \\mathbb{M}_{3\\times 2}(\\mathbb{F}_3)\\rightarrowtail \\mathbb{M}_{2}(\\mathbb{F}_3)$, given by matrix multiplcation. \nThe derivation closure of $t$ in the universal tensor space $T$ is 1-dimensional.\n\\begin{code}\n> Fr := [ KMatrixSpace(GF(3),2,3), KMatrixSpace(GF(3),3,2),\n>     KMatrixSpace(GF(3),2,2) ];\n> F := func< x | x[1]*x[2] >;\n> t := Tensor(Fr, F);\n> t;\nTensor of valence 3, U2 x U1 >-> U0\nU2 : Full Vector space of degree 6 over GF(3)\nU1 : Full Vector space of degree 6 over GF(3)\nU0 : Full Vector space of degree 4 over GF(3)\n\\end{code}\n\nThe derivation algebra of $t$ is isomorphic to $(\\mathfrak{gl}_2(\\mathbb{F}_3)\\oplus \\mathfrak{gl}_3(\\mathbb{F}_3)\\oplus \\mathfrak{gl}_2(\\mathbb{F}_3))/\\mathbb{F}_3$.\nWe do not show this, but we verify that the dimensions match.\n\\begin{code}\n> D := DerivationAlgebra(t);\n> Dimension(D) eq 4+9+4-1;\ntrue\n\\end{code}\n\nNow we verify that $t$ spans its own densor.\n\\begin{code}\n> T := Parent(t);\n> T;\nTensor space of dimension 144 over GF(3) with valence 3\nU2 : Full Vector space of degree 6 over GF(3)\nU1 : Full Vector space of degree 6 over GF(3)\nU0 : Full Vector space of degree 4 over GF(3)\n> densor := DerivationClosure(T, D);\n> densor eq sub< T | t >;\ntrue\n\\end{code}\n\\end{example}\n\n\n\\index{NucleusClosure}\n\\begin{intrinsics}\nNucleusClosure(T, Delta, a, b) : TenSpc, AlgMat, RngIntElt, RngIntElt -> TenSpc\nNucleusClosure(T, Delta, a, b) : TenSpc, ModMatFld, RngIntElt, RngIntElt -> TenSpc\nNucleusClosure(T, Delta, a, b) : TenSpc, [Mtrx], RngIntElt, RngIntElt -> TenSpc\n\\end{intrinsics}\n\nReturns the nucleus closure of the tensor space $T$, with frame $U_2\\times U_1\\rightarrowtail U_0$, with operators $\\Delta\\subseteq \\text{End}(U_a)\\times \\text{End}(U_b)$.\nCurrently, this only works for tensor spaces of valence 3.\nThis returns the subspace whose tensors' $\\{a,b\\}$-nuclues contains $\\Delta$.\n\n\\index{NucleusClosure}\n\\begin{intrinsics}\nNucleusClosure(T, t, a, b) : TenSpc, TenSpcElt, RngIntElt, RngIntElt -> TenSpc\n\\end{intrinsics}\n\nReturns the nucleus closure of the tensor space $T$, with frame $U_2\\times U_1\\rightarrowtail U_0$, whose operators are the $\\{a,b\\}$-nucleus of $t$.\nCurrently, this only works for tensor spaces of valence 3.\nThis returns the subspace whose tensors' $\\{a,b\\}$-nuclues contains the $\\{a,b\\}$-nucleus of $t$.\n\n\\begin{example}[NucClosure]\n\nWe illustrate that if $t$ is the commutator tensor from the Heisenberg group, then the densor of $t$ is $\\text{Cen}(t)\\cdot t$, 1-dimensional over the centroid.\nFirst, we construct $t$ with frame $\\mathbb{F}_5^6\\times\\mathbb{F}_5^6\\rightarrowtail \\mathbb{F}_5^3$, so that $t$ is $\\mathbb{F}_5$-bilinear.\n\\begin{code}\n> H := ClassicalSylow(GL(3,125), 5);\n> t := pCentralTensor(H);\n> t;\nTensor of valence 3, U2 x U1 >-> U0\nU2 : Full Vector space of degree 6 over GF(5)\nU1 : Full Vector space of degree 6 over GF(5)\nU0 : Full Vector space of degree 3 over GF(5)\n\\end{code}\n\nBecause $t$ came from the Heisenberg group over $\\mathbb{F}_{5^3}$, the centroid of $t$ will be 3-dimensional (over $\\mathbb{F}_5$) and isomorphic to $\\mathbb{F}_{5^3}$.\nAfter computing the centroid of $t$, we will rewrite $t$ over the centroid $\\text{Cen}(t)$, so that $t$ is $\\mathbb{F}_{5^3}$-bilinear.\n\\begin{code}\n> C := Centroid(t);\n> C;\nMatrix Algebra of degree 15 and dimension 3 with 3 generators over GF(5)\n> s := TensorOverCentroid(t);\n> s;\nTensor of valence 3, U2 x U1 >-> U0\nU2 : Full Vector space of degree 2 over GF(5^3)\nU1 : Full Vector space of degree 2 over GF(5^3)\nU0 : Full Vector space of degree 1 over GF(5^3)\n\\end{code}\n\nNow we will compute the nucleus closure of both $s$ and $t$ at $\\{2,1\\}$.\nThe dimension of the closure of $s$ will be 1-dimensional, while the dimension of the closure for $t$ will not.\n\\begin{code}\n> NucleusClosure(Parent(s), s, 2, 1);\nTensor space of dimension 1 over GF(5^3) with valence 3\nU2 : Full Vector space of degree 2 over GF(5^3)\nU1 : Full Vector space of degree 2 over GF(5^3)\nU0 : Full Vector space of degree 1 over GF(5^3)\n> \n> NucleusClosure(Parent(t), t, 2, 1);\nTensor space of dimension 9 over GF(5) with valence 3\nU2 : Full Vector space of degree 6 over GF(5)\nU1 : Full Vector space of degree 6 over GF(5)\nU0 : Full Vector space of degree 3 over GF(5)\n\\end{code}\n\\end{example}\n\n\n\n\\backmatter\n\n\\begin{bibdiv}\n\\begin{biblist}\n\n\\bib{FMW:densors}{article}{\n   author={First, Uriya},\n   author={Maglione, Joshua},\n   author={Wilson, James B.},\n   title={Polynomial identity tensors and their invariants},\n   note={in preparation},\n}\n\n\\end{biblist}\n\\end{bibdiv}\n\n\\printindex\n\n\n\\end{document}\n", "meta": {"hexsha": "122f663753e6c84b55588ee7b8a5cf0dbc8ee23f", "size": 7520, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/Densor.tex", "max_stars_repo_name": "thetensor-space/Densor", "max_stars_repo_head_hexsha": "e41c9f7eb5b92ef912666e8003c0f2fc8e86012f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/Densor.tex", "max_issues_repo_name": "thetensor-space/Densor", "max_issues_repo_head_hexsha": "e41c9f7eb5b92ef912666e8003c0f2fc8e86012f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-02-21T00:42:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-21T06:42:52.000Z", "max_forks_repo_path": "doc/Densor.tex", "max_forks_repo_name": "thetensor-space/Densor", "max_forks_repo_head_hexsha": "e41c9f7eb5b92ef912666e8003c0f2fc8e86012f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4129353234, "max_line_length": 210, "alphanum_fraction": 0.7190159574, "num_tokens": 2454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.3022728255546675}}
{"text": "\\section{Dynamic and Intrinsic Reaction Coordinates}\\index{Coordinates!reaction}\r\n\\label{t_irc}\\index{Molecular dynamics}\\index{Time-dependent phenomena}\r\nThe Intrinsic Reaction Coordinate method pioneered and developed by Mark\r\nGordon, North Dakota State University,\\index{gordon@{\\bf Gordon, Mark}}   has\r\nbeen incorporated into MOPAC in a modified form.  As this facility is quite\r\ncomplicated all the keywords associated with  the IRC have been grouped\r\ntogether in this section (these can be seen later on  in this section).\r\n\\index{DRC|(} \\index{DRC!definition}\r\n\r\nThe Dynamic Reaction Coordinate is the path  followed  by  all  the atoms  in\r\na  system  assuming  conservation  of  energy;  i.e.,  as the potential energy\r\nchanges the kinetic energy of  the  system  changes  in exactly  the  opposite\r\nway  so  that  the  total  energy  (kinetic plus potential) is a constant.  It\r\nis equivalent to the molecular mechanics molecular dynamics calculation, except\r\nthat bond-breaking and bond-making are supported, as are all the electronic\r\nphenomena of the semiempirical methods.\r\n\r\nIf started at a  ground  state  geometry,  no \\index{Transition state!use with\r\nDRC} significant  motion should be seen.  Similarly, starting at a transition\r\nstate geometry should not produce  any  motion---after  all  it  is  a\r\nstationary point and during the lifetime of a calculation it is unlikely to\r\naccumulate enough momentum to travel far from the starting position.\r\n\r\nIn order to calculate the DRC path from a transition state,  either an\r\ninitial  deflection  is  necessary  or some initial momentum must be supplied.\r\n\r\nBecause of the time-dependent nature of the DRC  the  time  elapsed since the\r\nstart of the reaction is meaningful, and is printed.\r\n\r\n\\subsection*{Description}\r\nThe course of a molecular vibration can be followed by  calculating the\r\npotential  and  kinetic  energy  at  various  times.   Two  extreme conditions\r\ncan be identified:  (a) gas phase, in which the total  energy is a constant\r\nthrough time, there being no damping of the kinetic energy allowed, and (b)\r\nliquid phase, in which kinetic energy is always set  to zero, the motion of the\r\natoms being infinitely damped.\\index{Liquids}\r\n\r\nAll possible degrees of damping  are  allowed.   In  addition,  the facility\r\nexists  to  dump  energy into the system, appearing as kinetic energy.  As\r\nkinetic energy is a function of velocity, a vector quantity, the  energy\r\nappears  as  energy of motion in the direction in which the molecule would\r\nnaturally move.  If the system  is  a  transition  state, then  the  excess\r\nkinetic  energy  is added after the intrinsic kinetic energy has built up to at\r\nleast 0.2 kcal/mol.\\index{Kinetic energy!damping}\r\n\r\nFor ground-state systems, the excess energy sometimes  may  not  be added;  if\r\nthe  intrinsic kinetic energy never rises above 0.2 kcal/mol then the excess\r\nenergy will not be added.\r\n\r\n\r\n\\subsection*{Equations used}\r\nForce acting on any atom:\r\n$$ g(i) + g'(i)t + g''(i)t^2 = \\frac{dE}{dx(i)} +\r\n        \\frac{d^2E}{dx(i)^2} + \\frac{d^3E}{dx(i)^3} $$\r\nAcceleration due to force acting on each atom:\r\n$$ a(i) = \\frac{1}{M(i)} (g(i) + g'(i)t + g''(i)t^2) $$\r\nNew velocity:\r\n$$ V(o) + \\frac{1}{M(i)} \\left(\\Delta t g(i) + (1/2) \\Delta  t^2 g'(i) +\r\n(1/3) \\Delta t^3g''(i)\\right) $$\r\nor:\r\n$$ V(i) = V(i) + V'(i)t + V''(i)t^2 + V'''(i)t^3 $$\r\nThat is, the change in velocity is equal to the integral  over  the\r\ntime interval of the acceleration.\r\n\r\nNew position of atoms:\r\n$$ X(i) = X(o) + V(o)t + (1/2) V't^2 + (1/3) V''t^3 + (1/4) V'''t^4 $$\r\nThat is, the change in position is equal to the integral  over  the\r\ntime interval of the velocity.\r\n\r\nThe velocity vector is accurate to the extent that  it  takes  into account\r\nthe  previous velocity, the current acceleration, the predicted acceleration,\r\nand the change in predicted  acceleration  over  the  time interval.    Very\r\nlittle  error  is  introduced  due  to  higher  order contributions to the\r\nvelocity; those that do occur  are  absorbed  in  a re-normalization of the\r\nmagnitude of the velocity vector after each time interval.\r\n\r\nThe magnitude of $\\Delta t$, the time interval, is determined mainly by the\r\nfactor   needed   to   re-normalize  the  velocity  vector.   If  it  is\r\nsignificantly different from unity, $\\Delta t$ will be reduced; if  it  is\r\nvery close to unity, $\\Delta t$ will be increased.\r\n\r\nEven with all this, errors creep in and a system,  started  at  the transition\r\nstate,  is  unlikely  to  return precisely to the transition state  unless  an\r\nexcess  kinetic  energy  is  supplied,  for   example 0.2 kcal/mol.\r\n\r\nThe calculation  is  carried  out  in  Cartesian  coordinates,  and converted\r\ninto   internal  coordinates  for  display.   All  Cartesian coordinates must\r\nbe allowed to vary, in order to  conserve  angular  and translational\r\nmomentum.\\index{DRC!conservation of momentum}\r\n\r\n\\subsection*{IRC}\r\n\\index{IRC|(}\r\nThe Intrinsic Reaction Coordinate is the path followed by  all  the atoms  in\r\na  system  and assumes that  all kinetic energy is completely lost at every\r\npoint; i.e., as the potential energy changes  the  kinetic  energy generated\r\nis  annihilated  so  that  the  total  energy  (kinetic  plus potential) is\r\nalways equal to the potential energy only.\r\n\r\nThe IRC is intended for use in calculations in which the starting geometry is\r\nthat of the transition state.  A   normal  coordinate  is  chosen,  usually\r\nthe  reaction coordinate, and the system  is  displaced  in  either  the\r\npositive  or negative  direction  along  this  coordinate.   The  internal\r\nmodes are obtained by calculating the mass-weighted  Hessian  matrix  in  a\r\nforce calculation   and   translating  the  resulting  Cartesian  normal  mode\r\neigenvectors to conserve  momentum.   That  is,  the  initial  Cartesian\r\ncoordinates  are  displaced  by  a  small  amount  proportional  to  the\r\neigenvector coefficients plus a translational constant; the constant  is\r\nrequired  to  ensure that the total translational momentum of the system is\r\nconserved as zero.  At the present time there may be  small  residual\r\nrotational  components  which  are not annihilated; these are considered\r\nunimportant, and will not materially affect the calculation.\r\n\r\n\\subsection*{General description of the DRC and IRC}\r\nAs the IRC usually requires a normal coordinate, a  force  constant\r\ncalculation  normally  has to be done first.  If IRC is specified on its own, a\r\nnormal coordinate is not used and the IRC calculation is performed on the\r\nsupplied geometry.\r\n\r\nA recommended sequence of operations to start an IRC calculation is\r\nas follows:\r\n\\begin{enumerate}\r\n\\item Calculate the transition state geometry.  If  the  transition state  is\r\nnot first  optimized,  then  the  IRC  calculation  may  give  very misleading\r\nresults.  For example, if NH$_3$ inversion  is  defined as  the  planar\r\nsystem  but  without the N--H bond length being optimized, the first normal\r\ncoordinate might be for N--H  stretch rather  than  inversion.   In  that case\r\nthe IRC will relax the geometry to the optimized planar structure.\r\n\r\n\\index{ISOTOPE!use with IRC}\r\n\\index{FORCE!use with IRC}\r\n\\item Do a normal FORCE calculation, specifying \\comp{ISOTOPE} in  order  to\r\nsave  the  FORCE  matrices.   (Note: Do  not  attempt  to  run the IRC at this\r\npoint directly unless you have confidence that  the FORCE  calculation will\r\nwork as expected.  If the IRC calculation is run directly, specify\r\n\\comp{ISOTOPE} anyway:  that will save the FORCE matrix and if the\r\ncalculation  has  to  be  re-done  then  \\comp{RESTART} will work correctly.)\r\n\r\n\\item Using \\comp{IRC=$n$} and \\comp{RESTART}, run the IRC calculation.   If\r\n\\comp{RESTART} is specified with \\comp{IRC=$n$} then the restart is assumed to\r\nbe from the FORCE calculation.  If, in an \\comp{IRC} calculation,\r\n\\comp{RESTART}  is specified, and \\comp{IRC=$n$} is {\\em not} present,  then\r\nthe restart is  assumed to be from an earlier IRC calculation that was  shut\r\ndown  before  going  to completion.\r\n\\end{enumerate}\r\n\r\nA DRC calculation is simpler, in that a force calculation is  not  a\r\nprerequisite;  however,  most  calculations of interest normally involve use of\r\nan internal coordinate.  For this reason IRC=$n$  can  be  combined with  DRC\r\nto  give  a  calculation in which the initial motion (0.3kcal worth of kinetic\r\nenergy) is supplied by  the  IRC,  and  all  subsequent motion  obeys\r\nconservation of energy.  The DRC motion can be modified in three ways:\r\n\\begin{enumerate}\r\n\\item It is possible to calculate the reaction  path  followed  by  a system\r\nin  which  the  generated  kinetic energy decays with a finite half-life.  This\r\ncan  be  defined  by  DRC=$n.nnn$,  where $n.nnn$  is  the  half-life in\r\nfemtoseconds.  If $n.nn$ is 0.0 this corresponds  to  infinite  damping\r\nsimulating  the   IRC.    A limitation  of  the  program is that time only has\r\nmeaning when DRC is specified without a half-life.\r\n\r\n\\item Excess kinetic energy can be added to the calculation by use of\r\nKINETIC=$n.nn$.   After  the  kinetic  energy  has  built  up  to 0.2 kcal/mol\r\nor if IRC=$n$ is used then $n.nn$ kcal/mol of kinetic energy  is  added  to\r\nthe  system.   The excess kinetic energy appears as a velocity vector  in  the\r\nsame  direction  as  the initial motion.\r\n\r\n\\index{RESTART!use with IRC/DRC}\r\n\\item The RESTART file \\verb/<filename>.res/ can be edited to allow the user\r\nto  modify the velocity vector or starting geometry.  This file\r\nis formatted.\r\n\\end{enumerate}\r\n\r\nFrequently, the  DRC leads to a periodic, repeating orbit.   One  special\r\ntype---the  orbit in which the direction of motion is reversed so that the\r\nsystem retraces its own path---is sensed for  and  if  detected  the\r\ncalculation  is  stopped after exactly one cycle.  If the calculation is to be\r\ncontinued,  the  keyword  \\comp{GEO-OK}  will  allow  this  check  to  be\r\nby-passed.\r\n\r\n\\index{GNORM!use with IRC/DRC}  Sometimes the system will enter a stable state\r\nin which the geometry is always changing, but nothing new is occurring.  One\r\nexample would be a system which decomposed into fragments, and the fragments\r\nwere moving apart. If all forces acting on the atoms become small, then the\r\ncalculation will be stopped.  If the calculation should be continued, then\r\nspecify \\comp{GNORM=0 LET}.\r\n\r\nDue to the potentially very large output files  that  the  DRC  can generate,\r\nextra  keywords  are  provided  to allow selected points to be printed.  Two\r\ntypes of control are provided:  one controls which points to  print, the other\r\ncontrols what is printed.\r\n\r\nBy default, every point calculated is printed.  Often, this is not desirable,\r\nand three keywords are provided to allow printing to be done whenever the\r\nsystem changes by a preset amount.  These keywords are:\r\n\r\n\\begin{center}\r\n\\begin{tabular}{cll}\\hline\r\n          KeyWord &       Default         &   User Specification  \\\\ \\hline\r\n\\comp{X-PRIO}  &   0.05 \\AA ngstroms   &         \\comp{X-PRIORITY=$n.nn$}  \\\\\r\n\\comp{T-PRIO}  &   0.10 Femtoseconds   &      \\comp{T-PRIORITY=$n.nn$}  \\\\\r\n\\comp{H-PRIO}  &   0.10 kcal/mol      &      \\comp{H-PRIORITY=$n.nn$}\\\\ \\hline\r\n\\end{tabular}\r\n\\end{center}\r\n\r\nBy default, only the energies involved are printed (one line per point).  To\r\nallow the geometry to be printed, \\hyperref[pageref]{\\comp{LARGE} is provided}{, see\r\np.~}{ for more detail}{large}.  Using \\comp{LARGE} a wide range of control\r\nis provided over what is printed.\r\n\r\n\\subsection*{Option to allow only extrema to be output}\r\nIn the geometry specification, if an internal coordinate is  marked for\r\noptimization  then  when that internal coordinate passes through an extremum a\r\nmessage will be printed and the geometry output.\r\n\r\nDifficulties can  arise  from  the  way  internal  coordinates  are\r\nprocessed.   The  internal  coordinates are generated from the Cartesian\r\ncoordinates, so an internal coordinate supplied  may  have  an  entirely\r\ndifferent  meaning  on  output.  In particular the connectivity may have\r\nchanged.  For obvious reasons dummy atoms should  not  be  used  in  the\r\nsupplied  geometry  specification.   If  there  is  any  doubt about the\r\ninternal coordinates or if the starting geometry  contains  dummy  atoms then\r\nrun  a  \\comp{1SCF} calculation specifying \\comp{INT}.  This  will produce an\r\nARC file with the ``ideal'' numbering---the internal numbering system used  by\r\nMOPAC. \\ Use this ARC file to construct a data file suitable for the DRC or\r\nIRC.\\index{DRC!dummy atoms in}\\index{Dummy atoms!in DRC}\r\n\r\nNotes:\r\n\\begin{enumerate}\r\n\\item Any coordinates marked for optimization  will  result  in  only extrema\r\nbeing printed.\r\n\\item If extrema are being printed then kinetic energy  extrema  will also be\r\nprinted.\r\n\\end{enumerate}\r\n\r\n\\subsection*{Keywords for use with the IRC and DRC}\r\n\\index{IRC!keywords for}\r\n\\label{drckeys}\r\n\\begin{enumerate}\r\n\\item Setting up the transition state:  \\comp{NLLSQ}, \\comp{SIGMA}, or \\comp{TS}.\r\n\\item Constructing the FORCE matrix:  \\comp{FORCE} or \\comp{IRC=$n$},\r\n\\comp{ISOTOPE}, \\comp{LET}.\r\n\\item Starting an IRC:  \\comp{RESTART} and \\comp{IRC=$n$},  \\comp{X-PRIO}, \\comp{H-PRIO}.\r\n\\item Starting a DRC:  \\comp{DRC} or \\comp{DRC=$n.nn$}, \\comp{KINETIC=$n.nn$},\r\n\\comp{T-PRIO}, etc..\r\n\\item Starting a DRC from a transition state:   (\\comp{DRC}  or  \\comp{DRC=$n$})  and\r\n            \\comp{IRC=$n$}, \\comp{KINETIC=$n$}.\r\n\\item Restarting an IRC:  \\comp{RESTART} and \\comp{IRC}.\r\n\\item Restarting a DRC:  \\comp{RESTART} and (\\comp{DRC} or \\comp{DRC=$n.nn$}).\r\n\\item Restarting a DRC starting from a transition state:  \\comp{RESTART} and\r\n            (\\comp{DRC} or \\comp{DRC=$n.nn$}).\r\n\\end{enumerate}\r\nOther keywords, such as \\comp{T=$nnn$} or \\comp{GEO-OK} can be used any time.\r\n\r\n\r\n\\subsection*{Examples of DRC/IRC data}\r\nUse of the IRC/DRC facility is quite complicated.  In the following examples\r\nvarious `reasonable' options are illustrated for a calculation on water. It is\r\nassumed  that  an  optimized  transition-state  geometry  is available.\r\n\r\nExample  1:   Figure~\\ref{h2odrc} illustrates a  Dynamic  Reaction   Coordinate\r\ncalculation,  starting  at   the transition  state  for  water  inverting, the\r\ninitial motion being opposite to the transition normal mode, with 6kcal of\r\nexcess kinetic  energy  added  in. Every point calculated is to be printed\r\n(Note all coordinates are marked with a zero, and T-PRIO, H-PRIO and X-PRIO are\r\nall absent).  The results of  an  earlier calculation using the same keywords\r\nis assumed to exist. The earlier calculation would have constructed the force\r\nmatrix.   While the  total  cpu  time  is specified, it is in fact redundant in\r\nthat the calculation will run to completion in less than 600 seconds.\r\n\r\n\\index{IRC!example of}\r\n\\begin{figure}\r\n\\begin{makeimage}\r\n\\end{makeimage}\r\n\\begin{verbatim}\r\n KINETIC=6 RESTART  IRC=-1 DRC T=600\r\n WATER\r\n\r\n      H   0.000000 0   0.000000 0   0.000000 0  0 0 0\r\n      O   0.911574 0   0.000000 0   0.000000 0  1 0 0\r\n      H   0.911574 0 180.000000 0   0.000000 0  2 1 0\r\n      0   0.000000 0   0.000000 0   0.000000 0  0 0 0\r\n\\end{verbatim}\r\n\\caption{\\label{h2odrc} Example of DRC calculation}\r\n\\end{figure}\r\n\r\nExample 2:  Figure~\\ref{h2oirc} shows an Intrinsic Reaction Coordinate\r\ncalculation.  Here the restart  is from a previous IRC calculation which was\r\nstopped before the minimum was reached.  Recall that RESTART with IRC=$n$\r\nimplies  a  restart from  the FORCE calculation.  Since this is a restart from\r\nwithin an IRC calculation the keyword IRC=$n$ has been replaced by IRC. \\  IRC\r\non its  own (without the ``=$n$'') implies an IRC calculation from the starting\r\nposition---here the RESTART position---without initial\r\ndisplacement.\\index{IRC!example of restart}\r\n\r\n\\begin{figure}\r\n\\begin{makeimage}\r\n\\end{makeimage}\r\n\\begin{verbatim}\r\n RESTART  IRC  T=600\r\n WATER\r\n\r\n      H   0.000000 0   0.000000 0   0.000000 0  0 0 0\r\n      O   0.911574 0   0.000000 0   0.000000 0  1 0 0\r\n      H   0.911574 0 180.000000 0   0.000000 0  2 1 0\r\n      0   0.000000 0   0.000000 0   0.000000 0  0 0 0\r\n\\end{verbatim}\r\n\\caption{\\label{h2oirc} Example of IRC calculation}\r\n\\end{figure}\r\n\r\n\\subsection*{Output format for IRC and DRC}\r\nThe IRC and DRC can produce  several  different  forms  of  output. Because of\r\nthe large size of these outputs, users are recommended to use search functions\r\nto extract information.  To facilitate  this,  specific lines  have specific\r\ncharacters.  Thus, a search for the ``\\%'' symbol will summarize the energy\r\nprofile while a search  for ``AA'' will  yield  the coordinates of atom 1,\r\nwhenever it is printed.  The main flags to use in searches are:\r\n\r\n\\begin{description}\r\n\\item[\\comp{\\%}] Energies for all points calculated,    excluding extrema\r\n\\item[\\comp{\\%M}] Energies for all turning points\r\n\\item[\\comp{\\%MAX}] Energies for all maxima\r\n\\item[\\comp{\\%MIN}] Energies for all minima\r\n\\item[\\comp{\\%}] Energies for all points calculated\r\n\\item[\\comp{AA*}] Internal coordinates for atom 1 for every point\r\n\\item[\\comp{AE*}] Internal coordinates for atom 5 for every point\r\n\\item[\\comp{123AB*}] Internal coordinates for atom 2 for point 123\r\n\\end{description}\r\n\r\nAs the keywords for the IRC/DRC are interdependent,  the  following list of\r\nkeywords illustrates various options.\\index{DRC!keyword options}\r\n\\index{KINETIC}\r\n\r\n\\begin{description}\r\n\\item[\\comp{DRC}] The Dynamic Reaction Coordinate is calculated.\r\nEnergy is conserved, and no initial impetus.\r\n\\item[\\comp{DRC=0.5}] In the DRC kinetic energy is lost with a half-life of\r\n0.5 femtoseconds.\r\n\\item[\\comp{DRC=1.0}] Energy is put into a DRC with an half-life of\r\n-1.0 femtoseconds, i.e., the system gains   energy.\r\n\\item[\\comp{IRC}] The Intrinsic Reaction Coordinate is\r\ncalculated.  No initial impetus is given.\r\nEnergy not conserved.\r\n\\item[\\comp{IRC=4}] The IRC is run starting with an impetus in the\r\nnegative of the 4th normal mode direction. The\r\nimpetus is one quantum of vibrational energy.\r\n\\item[\\comp{IRC1 KINETIC=1}] The first normal mode is used in an IRC, with\r\nthe initial impetus being 1.0 kcal/mol.\r\n\\item[\\comp{DRC KINETIC=5}] In a DRC, after the velocity is defined, 5 kcal\r\nof kinetic energy is added in the direction of\r\nthe initial velocity.\r\n\\item[\\comp{IRC=1 DRC KINETIC=4}] After starting with a 4 kcal impetus in the\r\ndirection of the first normal mode, energy is\r\nconserved.\r\n\\item[\\comp{DRC VELOCITY KINETIC=10}] Follow a DRC trajectory which starts with an\r\ninitial velocity read in, normalized to a\r\nkinetic energy of 10 kcal/mol.\r\n\\end{description}\r\n\r\n\r\nInstead of every point being printed, the option  exists  to  print specific\r\npoints  determined  by the keywords \\comp{T-PRIORITY}, \\comp{X-PRIORITY} and\r\n\\comp{H-PRIORITY}.  If any one of these words is specified, then the calculated\r\npoints  are used to define quadratics in time for all variables normally\r\nprinted.  In addition, if the flag for the first atom is set to  ``T''  then\r\nall  kinetic  energy  turning  points  are printed.  If the flag for any other\r\ninternal coordinate is set to ``T'' then, when that coordinate  passes through\r\nan extremum, that point will be printed.  As with the PRIORITY's, the point\r\nwill be calculated via  a  quadratic  to  minimize  non-linear errors.\r\n\r\nN.B.:  Quadratics are unstable in the regions of inflection points; in  these\r\ncircumstances linear interpolation will be used.  A result of this is that\r\npoints printed in the  region  of  an  inflection  may  not correspond  exactly\r\nto those requested.  This is not an error and should not affect the quality of\r\nthe results.\r\n\r\n\\subsection*{Test of DRC---verification of trajectory path}\r\nIntroduction:  Unlike  a  single-geometry  calculation  or  even  a geometry\r\noptimization, verification of a DRC trajectory is not a simple task.  In this\r\nsection  a  rigorous  proof  of  the  DRC  trajectory  is presented;  it  can\r\nbe used both as a test of the DRC algorithm and as a teaching exercise.  Users\r\nof the DRC are asked to  follow  through  this proof in order to convince\r\nthemselves that the DRC works as it should.\r\n\r\n\\subsection*{The nitrogen molecule}\r\nFor the nitrogen molecule (using MNDO) the equilibrium  distance is  $1.103816$\r\n\\AA, the heat of formation is 8.25741 kcal/mol and the vibrational frequency is\r\n$2738.8$ cm$^{-1}$.   For  small  displacements, the  energy curve versus\r\ndistance is parabolic and the gradient curve is approximately linear, as is\r\nshown in Table~\\ref{n2}.         A  nitrogen molecule is thus a good\r\napproximation to a harmonic oscillator.\r\n\r\n% 40 lines, including this line\r\n\\begin{table}\r\n\\caption{\\label{n2}Stretching Curve for Nitrogen Molecule}\r\n\\begin{center}\r\n\\begin{tabular}{rrr}\r\n\\multicolumn{1}{c}{N--N DIST} & \\multicolumn{1}{c}{$\\Delta H_f$}  & \\multicolumn{1}{c}{GRADIENT}\\\\\r\n\\multicolumn{1}{c}{(\\AA ngstroms)} &\\multicolumn{1}{c}{(kcal/mol)} & \\multicolumn{1}{c}{(kcal/mol/\\AA ngstrom)}\\\\\r\n\\hline\r\n1.11800   &  8.69441  &   60.84599 \\\\\r\n1.11700   &  8.63563  &   56.70706 \\\\\r\n1.11600   &  8.58100  &   52.54555 \\\\\r\n1.11500   &  8.53054  &   48.36138 \\\\\r\n1.11400   &  8.48428  &   44.15447 \\\\\r\n1.11300   &  8.44224  &   39.92475 \\\\\r\n1.11200   &  8.40444  &   35.67214 \\\\\r\n1.11100   &  8.37091  &   31.39656 \\\\\r\n1.11000   &  8.34166  &   27.09794 \\\\\r\n1.10900   &  8.31672  &   22.77620 \\\\\r\n1.10800   &  8.29611  &   18.43125 \\\\\r\n1.10700   &  8.27986  &   14.06303 \\\\\r\n1.10600   &  8.26799  &    9.67146 \\\\\r\n1.10500   &  8.26053  &    5.25645 \\\\\r\n1.10400   &  8.25749  &    0.81794 \\\\\r\n1.10300   &  8.25890  &   -3.64427 \\\\\r\n1.10200   &  8.26479  &   -8.12993 \\\\\r\n1.10100   &  8.27517  &  -12.63945 \\\\\r\n1.10000   &  8.29007  &  -17.17278 \\\\\r\n1.09900   &  8.30952  &  -21.73002 \\\\\r\n1.09800   &  8.33354  &  -26.31123 \\\\\r\n1.09700   &  8.36215  &  -30.91650 \\\\\r\n1.09600   &  8.39538  &  -35.54591 \\\\\r\n1.09500   &  8.43325  &  -40.19953 \\\\\r\n1.09400   &  8.47579  &  -44.87745 \\\\\r\n1.09300   &  8.52301  &  -49.57974 \\\\\r\n1.09200   &  8.57496  &  -54.30648 \\\\\r\n1.09100   &  8.63164  &  -59.05775 \\\\\r\n1.09000   &  8.69308  &  -63.83363 \\\\\r\n\\end{tabular}\r\n\\end{center}\r\n\\end{table}\r\n\r\n\\subsubsection{Period of vibration}\r\nThe period of vibration (time taken for the oscillator to undertake one\r\ncomplete vibration, returning to its original position and velocity) can be\r\ncalculated in three ways.  Most direct is  the  calculation  from the  energy\r\ncurve; using the gradient constitutes a faster, albeit less direct, method,\r\nwhile calculating it from the vibrational  frequency  is very  fast  but\r\nassumes  that the vibrational spectrum has already been calculated.\r\n\r\n\\begin{enumerate}\r\n\r\n\\item From the energy curve. For a simple harmonic oscillator the period $r$ is\r\ngiven by: $$ r = 2 \\pi \\sqrt{\\frac{\\mu}{k}}  $$ where $k$ is the\r\nforce constant.  \\index{Reduced mass}\\index{Force constant} The\r\nreduced  mass, $\\mu$,  (in amu)   of   a   nitrogen  molecule  is\r\n$14.0067/2  =  7.00335$, and  the force-constant, $k$, can be\r\ncalculated from: $$E-c = (1/2) k(R-R_o)^2. $$ Given $R_o =\r\n1.1038$, $R = 1.092$, $c = 8.25741$ and $E = 8.57496$~kcal/mol\r\nthen:\r\n \\begin{eqnarray*}\r\nk &=& 2*0.31755/(0.0118)^2 \\; \\mbox{(per mole)}\\\\\r\nk &=& 4561.2 \\mbox{ kcal/mol/A$^2$  (per mole)}\\\\\r\nk &=& 1.9084*10^{30} \\; \\mbox{ ergs/cm$^2$ (per mole)}\\\\\r\nk &=& 31.69*10^5  \\; \\mbox{ dynes/cm (per molecule)}\\\\\r\n\\end{eqnarray*}\r\n\r\n(Experimentally, for N$_2$, k = $23*10^5$ dynes/cm )\r\n\r\nTherefore:\r\n$$ r = 2 \\times 3.14159 \\times \\sqrt{\\frac{7.0035}{1.9084\\times 10^{30}}}\r\n\\;{\\rm seconds} = 12.037 \\times 10^{-15}\\;{\\rm s} = 12.037\\;{\\rm fs}. $$\r\nIf the frequency is calculated using the other half of the curve ($R=1.118,\r\nE=8.69441$), then $k=12.333$ fs, or $k$, average, = 12.185 fs.\r\n\r\n\\item From the gradient curve. The force  constant  is  the  derivative  of\r\nthe  gradient  wrt distance:\r\n$$ k = \\frac{dG}{dx}. $$\r\nSince we are using discrete points,  the  force  constant  is  best\r\nobtained from finite differences:\r\n$$ k = \\frac{(G_2-G_1)}{(x_2-x_1)}. $$\r\nFor $x_2 = 1.1100$, $G_2 = 27.098$ and for $x_1 =  1.0980$,\r\n$G_1  =  -26.311$,\r\ngiving rise to $k = 4450.75$ kcal/mol/\\AA$^2$ and a period of $12.185$~fs.\r\n\r\n\\item From the vibrational frequency. Given a ``frequency'' (wavenumber) of\r\nvibration of N$_2$ of $\\bar{\\nu}=2738.8$   cm$^{-1}$,  the period of\r\noscillation, in seconds, is given directly by:\r\n$$ r = \\frac{1}{c\\bar{\\nu}} = \\frac{1}{2738.8 \\times 2.998 \\times 10^{10}} ,$$\r\nor as $12.179$ fs.\r\n\\end{enumerate}\r\n\r\nSummarizing, by three different methods the period  of  oscillation of N$_2$\r\nis calculated to be $12.1851$, $12.185$ and $12.179$~fs, average $12.183$~fs.\r\n\r\n\\subsubsection{Initial dynamics of \\mbox{N$_{2}$} with N--N distance = 1.094 \\AA}\r\nA useful check on the dynamics of N$_2$ is to  calculate  the  initial\r\nacceleration  of  the  two  nitrogen  atoms  after releasing them from a\r\nstarting interatomic separation of 1.094 \\AA.\r\n\r\nAt R(N-N) = 1.094 \\AA, $G = -44.877$~kcal/mol/\\AA\\ or $-18.777 \\times\r\n10^{19}$~erg/cm. Therefore acceleration, $f = -18.777 \\times 10^{19}\r\n/14.0067$~cm/sec/sec, or $-13.405 \\times 10^{18}$~cm/s$^2$, which is $ -13.405\r\n\\times 10^{15} \\times$ Earth surface gravity.\r\n\r\nDistance from equilibrium  $= 0.00980$ \\AA. After $0.1$ fs, velocity is\r\n$0.1\\times  10^{-15} (-13.405 \\times  10^{18})$ cm/sec or $1340.5$ cm/s.\r\n\r\nIn the  DRC  the  time-interval  between  points  calculated  is  a complicated\r\nfunction of the curvature of the local surface.  By default, the first\r\ntime-interval is 0.105fs, so the calculated velocity  at  this time should be\r\n$0.105/0.100 \\times 1340.5 = 1407.6$ cm/s, in the DRC calculation the predicted\r\nvelocity is $1407.6$ cm/s.\r\n\r\nThe option is provided to allow sampling of the system at  constant\r\ntime-intervals,  the  default being $0.1$~fs.  For the first few points the\r\ncalculated velocities are given in Table~\\ref{tdrc}.\r\n\r\n\\begin{table}\r\n\\caption{\\label{tdrc} Velocities in DRC for N$_2$ Molecule}\r\n\\begin{center}\r\n\\begin{tabular}{rrrr}\\\\ \\hline\r\n      Time  & Calculated &  Linear &    Diff. in \\\\\r\n            & Velocity  & Velocity &  Velocity \\\\ \\hline\r\n      0.000 &      0.0  &    0.0   &    0.0  \\\\\r\n      0.100 &   1340.6  & 1340.5   &   -0.1  \\\\\r\n      0.200 &   2678.0  & 2681.0   &   -3.0  \\\\\r\n      0.300 &   4007.0  & 4021.5   &  -14.5  \\\\\r\n      0.400 &   5325.3  & 5362.0   &  -36.7  \\\\\r\n      0.500 &   6628.4  & 6702.5   &  -74.1  \\\\\r\n      0.600 &   7912.7  & 8043.0   & -130.3  \\\\ \\hline\r\n\\end{tabular}\r\n\\end{center}\r\n\\end{table}\r\n\r\nAs the calculated velocity is  a  fourth-order  polynomial  of  the\r\nacceleration,   and  the  acceleration,  its  first,  second  and  third\r\nderivatives, are all changing, the predicted velocity rapidly becomes  a poor\r\nguide to future velocities.\r\n\r\nFor simple harmonic motion the velocity at any time is given by:\r\n$$ v = v_0 \\sin(2\\pi t/r). $$\r\nBy fitting the computed velocities to simple harmonic motion, a much better fit\r\nis obtained (Table~\\ref{tdrc2}).\r\n\r\n\\begin{table}\r\n\\caption{\\label{tdrc2} Modified  Velocities in DRC for N$_2$ Molecule}\r\n\\begin{center}\r\n\\begin{tabular}{rrrr} \\hline\r\n & Calculated & Simple Harmonic  &    Diff. \\\\\r\nTime  & Velocity  & 25325.Sin(0.5296t) &\\\\ \\hline\r\n            &           &                   &    \\\\\r\n     0.000  &     0.0   &       0.0         &    0.0  \\\\\r\n     0.100  &  1340.6   &    1340.6         &    0.0  \\\\\r\n     0.200  &  2678.0   &    2677.4         &   +0.6  \\\\\r\n     0.300  &  4007.0   &    4006.7         &   +0.3  \\\\\r\n     0.400  &  5325.3   &    5324.8         &   +0.5  \\\\\r\n     0.500  &  6628.4   &    6628.0         &   +0.4  \\\\\r\n     0.600  &  7912.7   &    7912.5         &    0.0  \\\\ \\hline\r\n\\end{tabular}\r\n\\end{center}\r\n\\end{table}\r\n\r\nThe repeat-time required for this  motion  is  $11.86$~fs,  in  good agreement\r\nwith  the  three  values calculated using static models.  The repeat time\r\nshould not be calculated from the time required to go from a minimum  to  a\r\nmaximum and then back to a minimum---only half a cycle. For all real systems\r\nthe potential energy is a skewed parabola, so  that the  potential energy\r\nslopes are different for both sides; a compression (as in this case) normally\r\nleads to a higher force-constant, and shorter apparent  repeat  time  (as in\r\nthis case).  Only the addition of the two half-cycles is meaningful.\r\n\r\n\\subsubsection{Conservation of normal coordinate}\r\nSo far this analysis has only considered a homonuclear diatomic.  A detailed\r\nanalysis  of  a  large  polyatomic  is  impractical,  and  for simplicity a\r\nmolecule of formaldehyde will be studied.\r\n\r\nIn polyatomics, energy can  transfer  between  modes.   This  is  a result  of\r\nthe non-parabolic nature of the potential surface.  For small displacements the\r\nsurface can be considered as  parabolic.   This  means that  for small\r\ndisplacements interconversion between modes should occur only very slowly.  Of\r\nthe six normal modes, mode 1, at 1209.5~cm$^{-1}$, the in-plane C--H asymmetric\r\nbend, is the most unsymmetric vibration, and is chosen to demonstrate\r\nconservation of vibrational purity.\r\n\r\nMode 1 has a  frequency  corresponding  to  3.46  kcal/mol  and  a predicted\r\nvibrational time of $27.58$~fs.  By direct calculation, using the DRC, the\r\ncycle time is $27.59$~fs.  The rate of decay of this mode  has  an estimated\r\nhalf-life of a few thousands femtoseconds.\r\n\r\n\\subsubsection{Rate of decay of starting mode}\r\nFor trajectories initiated by an IRC=$n$  calculation,  whenever  the\r\npotential  energy is a minimum the current velocity is compared with the\r\nsupplied velocity.  The square of the cosine of the  angle  between  the two\r\nvelocity vectors is a measure of the intensity of the original mode in the\r\ncurrent vibration.\r\n\r\n\\subsubsection{Half-Life for decay of initial mode}\r\nVibrational purity is assumed to decay according to  zero'th  order kinetics.\r\nThe  half-life is thus $-0.6931472t/\\log(<\\!\\psi^2\\!>^2)$~fs, where\r\n$<\\!\\psi^2\\!>^2$ is the square of  the overlap integral of the wavefunction for\r\nthe  original vibration with that of the current  vibration.   Due to the  very\r\nslow rate of decay of the starting mode, several half-life calculations\r\nshould  be  examined.   Only  when successive  half-lives  are  similar  should\r\nany confidence be placed in their value.\r\n\r\n\\subsubsection{DRC print options}\r\nThe amount of output in the DRC is  controlled  by  three  sets  of\r\noptions.  These sets are:\\index{H--PRIORITY}\r\n\\begin{itemize}\r\n\\item Equivalent Keywords \\comp{H-PRIORITY}, \\comp{T-PRIORITY}, and\r\n\\comp{X-PRIORITY}.\r\n\\item Potential Energy Turning Point option.\r\n\\item Geometry Maxima Turning Point options.\r\n\\end{itemize}\r\nIf \\comp{T-PRIORITY} is used then  turning  points  cannot  be  monitored.\r\n%Currently  \\comp{H-PRIORITY} and \\comp{X-PRIORITY} are not implemented,\r\n%but will be as soon as practical.\r\n\r\n\\index{``T'' - Optimization flag} To monitor geometry turning points, put  a\r\n``T'' in  place  of  the geometry optimization flag for the relevant geometric\r\nvariable. In the example shown in Figure~\\ref{t}, the geometry of formaldehyde\r\nwould first be optimized, then a \\comp{FORCE} calculation run, then a DRC\r\ncalculation started, using the first normal mode for the starting velocity.\r\nWhenever the C=O bond length becomes a maximum or a minimum, a message is\r\nprinted.\r\n\r\n\\begin{figure}\r\n\\begin{makeimage}\r\n\\end{makeimage}\r\n\\begin{verbatim}\r\n IRC=1 DRC T=20\r\n Formaldehyde\r\n Monitoring the C=O Bond-length turning points\r\n  O    0.0 0    0.0 0    0.000000 0   0 0 0\r\n  C    1.2 T    0.0 0    0.000000 0   1 0 0\r\n  H    1.0 1  120.0 1    0.000000 0   2 1 0\r\n  H    1.0 1  120.0 1  180.000000 0   2 1 3\r\n  0    0.0 0    0.0 0    0.000000 0   0 0 0\r\n\\end{verbatim}\r\n\\caption{\\label{t} Example of DRC calculation, monitoring a geometric variable}\r\n\\end{figure}\r\n\r\nTo monitor the potential energy turning points, put a ``T'' for  the flag for\r\natom 1 bond length (Do not forget to put in a bond-length (zero will do)!).\r\n\r\nTo monitor the geometry, use \\comp{LARGE=$n$}.  This will cause the geometry to\r\nbe printed once every $n$ steps.\r\n\r\nThe effect of using these flags together is as follows.\r\n\\begin{enumerate}\r\n\\item No options:  All calculated points will be printed.  No turning points\r\nwill be calculated.\r\n\r\n\\item Atom 1 bond length flagged with a ``T'': If  \\comp{T-PRIO},  etc.\\ are\r\nNOT  specified,  then  potential  energy turning points will be printed.\r\n\r\n\\item Internal coordinate flags set to ``T'':  If \\comp{T-PRIO}, etc.  are NOT\r\nspecified,  then geometry extrema will be printed.  If only one coordinate is\r\nflagged, then the turning point will be displayed in  chronologic  order; if\r\nseveral are flagged then all turning points occurring in a given time-interval\r\nwill  be  printed  as they  are  detected.   In  other  words,  some  may  be\r\nout of chronologic order.  Note that each coordinate flagged will give rise  to\r\na different geometry:  minimize flagged coordinates to minimize output.\r\n\r\n\\item Potential and geometric flags set:  The effect is equivalent to the sum\r\nof the first two options.\r\n\r\n\\item \\comp{T-PRIO} set:  No turning points will be  printed,  but  constant\r\ntime-slices  (by  default  $0.1$~fs)  will  be used to control the print.\r\n\\end{enumerate}\r\n\\index{DRC|)}\\index{IRC|)}\r\n", "meta": {"hexsha": "ab6da8ae8f1727fff7825be270934366b9b073f6", "size": 33301, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "manuals/MOPAC2000_manual/t_irc.tex", "max_stars_repo_name": "openmopac/MOPAC-archive", "max_stars_repo_head_hexsha": "01510e44246de34a991529297a10bcf831336038", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-16T20:53:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T20:54:11.000Z", "max_issues_repo_path": "manuals/MOPAC2000_manual/t_irc.tex", "max_issues_repo_name": "openmopac/MOPAC-archive", "max_issues_repo_head_hexsha": "01510e44246de34a991529297a10bcf831336038", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "manuals/MOPAC2000_manual/t_irc.tex", "max_forks_repo_name": "openmopac/MOPAC-archive", "max_forks_repo_head_hexsha": "01510e44246de34a991529297a10bcf831336038", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.3036253776, "max_line_length": 114, "alphanum_fraction": 0.7023512807, "num_tokens": 10034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.302036178416667}}
{"text": "\n\\section{The \\D{} Force Field}\n\\label{fieldintro}\n\nThe force field\\index{force field} is the set of functions needed to define the\ninteractions in a molecular system. These may have a wide variety of\nanalytical forms, with some basis in chemical physics, which must be\nparameterised to give the correct energy and forces. A huge variety of\nforms is possible and for this reason the \\D{} force field\\index{force field!DL\\_POLY} is designed\nto be adaptable. While it is not supplied with its own force field\\index{force field}\nparameters, many of the functions familiar to\nGROMOS\\index{GROMOS},\\index{force field!GROMOS}\n\\cite{gunsteren-87a} Dreiding\\index{force\nfield!Dreiding} \\cite{mayo-90a}, AMBER\\index{AMBER}\\index{force\nfield!AMBER} \\cite{weiner-86a} and\nOPLS\\index{force field!OPLS} \\cite{jorgensen-84a}\nusers have been \ncoded in the package, as well as less familiar forms. In addition\n\\D{} retains the possibility of the user defining additional\npotentials.\n\nIn \\D{} the total configuration energy of a molecular system may\nbe written as:\n\\begin{eqnarray}\nU(\\vek{r}_{1},\\vek{r}_{2},\\ldots,\\vek{r}_{N})&=&\n\\sum_{i_{bond}=1}^{N_{bond}}\nU_{bond}(i_{bond},\\vek{r}_{a},\\vek{r}_{b}) \\nonumber \\\\ & &\n+\\sum_{i_{angle}=1}^{N_{angle}}\nU_{angle}(i_{angle},\\vek{r}_{a},\\vek{r}_{b},\\vek{r}_{c})\\nonumber \\\\\n& & +\\sum_{i_{dihed}=1}^{N_{dihed}}\nU_{dihed}(i_{dihed},\\vek{r}_{a},\\vek{r}_{b},\\vek{r}_{c},\\vek{r}_{d})\n\\nonumber \\\\ & & +\\sum_{i_{inv}=1}^{N_{inv}} \nU_{inv}(i_{inv},\\vek{r}_{a},\\vek{r}_{b},\\vek{r}_{c},\\vek{r}_{d})\n\\nonumber \\\\ & & +\\sum_{i=1}^{N-1}\\sum_{j>i}^{N}\nU_{pair}(i,j,|\\vek{r}_{i}-\\vek{r}_{j}|) \\nonumber \\\\ & &\n+\\sum_{i=1}^{N-2}\\sum_{j>i}^{N-1}\\sum_{k>j}^{N}\nU_{3\\_body}(i,j,k,\\vek{r}_{i},\\vek{r}_{j},\\vek{r}_{k}) \\nonumber \\\\ & &\n+\\sum_{i=1}^{N-1}\\sum_{j>i}^{N}\nU_{Tersoff}(i,j,\\vek{r}_{i},\\vek{r}_{j},\\vek{R}^{N}) \\nonumber \\\\ & &\n+\\sum_{i=1}^{N-3}\\sum_{j>i}^{N-2}\\sum_{k>j}^{N-1}\\sum_{n>k}^{N}\nU_{4\\_body}(i,j,k,n,\\vek{r}_{i},\\vek{r}_{j},\\vek{r}_{k},\\vek{r}_{n})\n\\nonumber \\\\ & &\n+\\sum_{i=1}^{N}U_{Metal}(i,\\vek{r}_{i},\\vek{R}^{N}) \\nonumber\\\\ & &\n+\\sum_{i=1}^{N}U_{extn}(i,\\vek{r}_{i},\\vek{v}_{i})\n\\end{eqnarray}\nwhere $U_{bond},~U_{angle},~U_{dihed},~U_{inv}$, $U_{pair}$,\n$U_{3\\_body},~U_{Tersoff}$ \nand $U_{4\\_body}$ are empirical interaction functions\nrepresenting chemical bonds, valence angles\\index{potential!valence\nangle}, dihedral\\index{potential!dihedral} angles,\ninversion angles\\index{potential!inversion}, pair-body,\nthree-body\\index{potential!three-body},\nTersoff (many-body covalent)\\index{potential!Tersoff},\nand four-body\\index{potential!four-body} forces\nrespectively.  The first four are regarded by \\D{} as {\\em\nintra}-molecular interactions and the next five as {\\em\ninter}-molecular interactions. The term $U_{metal}$ is a\ndensity dependent (and therefore many-body) metal \npotential \\index{potential!metal}.\nThe final term $U_{extn}$ represents an\n{\\em external field} potential. \n\nThe position vectors\n$\\vek{r}_{a},\\vek{r}_{b},\\vek{r}_{c}$ and $\\vek{r}_{d}$ refer to the\npositions of the atoms specifically involved in a given interaction.\n(Almost universally, it is the {\\em differences} in position that\ndetermine the interaction.) A special vector $\\vek{R}^{N}$ is used to\nindicate a many-body dependence. The numbers $N_{bond},~N_{angle}$,\n$N_{dihed}$ and $N_{inv}$ refer to the total numbers of these\nrespective interactions present in the simulated system, and the\nindices $i_{bond},~i_{angle},~i_{inv}$ and $i_{dihed}$ uniquely specify an\nindividual interaction of each type.  It is important to note that\nthere is no global specification of the intramolecular interactions in\n\\D{} - all bonds, valence angles\\index{potential!valence angle} and dihedrals\\index{potential!dihedral} must be\nindividually cited.\n\nThe indices $i$, $j$ (and $k$, $n$) appearing in the pair-body (and\nthree\\index{potential!three-body} or four-body\\index{potential!four-body}) terms indicate the atoms involved in the interaction.\nThere is normally a very large number of these and they are therefore\nspecified according to atom {\\em types} rather than indices. In\n\\D{} it is assumed that the pair-body terms arise from van der\nWaals\\index{potential!van der Waals}\nand/or electrostatic (Coulombic)\\index{potential!electrostatic} forces. The former are regarded as\nshort ranged interactions and the latter as long ranged. Long ranged\nforces require special techniques to evaluate accurately (see section\n\\ref{coulomb}.)  In \\D{} the three-body\\index{potential!three-body} terms are restricted to valence\nangle\\index{potential!valence angle} and H-bond\\index{potential!bond}\nforms. The nonbonded\\index{potential!nonbonded},\nthree-body\\index{potential!three-body},\nfour-body\\index{potential!four-body} and Tersoff\n\\index{potential!Tersoff}, interactions are globally specified\naccording to the {\\em types} of atoms involved.  \\D{} also has the\nability to handle metals via density dependent functions (see\nbelow). Though essentially many-body potentials their particular form\nmeans they are handled in a manner very similar to pair potentials.\n\nIn \\D{} the intramolecular bonded terms are handled using\nbookkeeping arrays, which specify the atoms involved in a particular\ninteraction and point to the appropriate arrays of parameters that\ndefine the potential. The calculation of bonded forces therefore\nfollows the simple scheme: \n\n\\begin{enumerate} \n\\item Every atom in the simulated system is assigned a unique index number\nfrom $1$ to $N$; \n\\item Every intramolecular bonded term $U_{type}$ in\nthe system has a unique index number $i_{type}$: from $1$ to\n$N_{type}$ where $type$ represents a bond\\index{potential!bond}, angle or dihedral\\index{potential!dihedral}.  \n\\item A pointer array $key_{type}(n_{type},i_{type})$ carries the indices of\nthe specific atoms involved in the potential term labelled $i_{type}$.\nThe dimension $n_{type}$ will be $2,~3$ or $4$, if the term represents\na bond\\index{potential!bond}, valence angle\\index{potential!valence angle}, dihedral\\index{potential!dihedral}/inversion.  \n\\item The array $key_{type}(n_{type},i_{type})$ is used to identify\nthe atoms in a bonded\\index{potential!bond} term and the appropriate form of interaction and\nthus to calculate the energy and forces.  \n\\end{enumerate}\n\n\\D{} calculates the nonbonded\\index{potential!nonbonded} pair interactions using a\nVerlet\\index{algorithm!Verlet} neighbour list \\cite{allen-89a} which is reconstructed at\nintervals during the simulation. This list records the indices of all\n`secondary' atoms within a certain radius of each `primary' atom; the\nradius being the cut-off radius ($r_{cut}$) normally applied to the\nnonbonded\\index{potential!nonbonded} potential function, plus an additional increment ($\\Delta\nr_{cut}$). The neighbour list removes the need to scan over all atoms\nin the simulation at every timestep.  The larger radius\n($r_{cut}+\\Delta r_{cut}$) means the same list can be used for several\ntimesteps without requiring an update. The frequency at which the list\nmust be updated depends on the thickness of the region $\\Delta\nr_{cut}$. \\D{} has two methods for constructing the neighbour\nlist: the first is based on the Brode-Ahlrichs\\index{algorithm!Brode-Ahlrichs} scheme\n\\cite{brode-86a} and is used when $r_{cut}$ is large in comparison with\nthe simulation cell; the second uses the link-cell algorithm\n\\cite{hockney-81a} when $r_{cut}$ is relatively small. The potential\nenergy and forces arising from the nonbonded\\index{potential!nonbonded} interactions are\ncalculated using interpolation tables.\n\nA complication in the construction of the Verlet\\index{algorithm!Verlet}\nneighbour list for macromolecules is the concept of {\\em excluded atoms},\nwhich arises from the need to exclude certain atom pairs from the overall\nlist.  Which atom pairs need to be excluded is dependent on the precise nature\nof the force field\\index{force field} model, but as a minimum atom pairs\nlinked via extensible bonds\\index{potential!bond} or\nconstraints\\index{constraints!bond} and atoms (grouped in pairs) linked via\nvalence\\index{potential!valence angle} angles are probable candidates. The\nassumption behind this requirement is that atoms that are formally\nbonded\\index{potential!bond} in a chemical sense, should not participate in\nnonbonded\\index{potential!nonbonded} interactions with each other.  (However\nthis is not a universal requirement of all force fields\\index{force field}.)\nThe same considerations are needed in dealing with charged excluded atoms. \\D{}\nhas several subroutines available for constructing the\nVerlet\\index{algorithm!Verlet} neighbour list, while taking care of the\nexcluded atoms (see chapter \\ref{conex} for further information.)\n\nThree-\\index{potential!three-body} and\nfour-body\\index{potential!four-body}\nnonbonded\\index{potential!nonbonded} forces are assumed to be short\nranged and therefore calculated using the link-cell algorithm\n\\cite{hockney-81a}. They ignore the possibility of there being any\nexcluded interactions involving the atoms concerned. \n\nThroughout this section the description of the force field\\index{force\nfield} assumes the simulated system is described as an assembly of\natoms. This is for convenience only and readers should understand that\n\\D{} does recognise molecular entities, defined either through\nconstraint bonds\\index{constraints!bond} or rigid bodies. In the case\nof rigid bodies, the atomic forces are resolved into molecular forces\nand torques. These matters are discussed in greater detail later in\nsections \\ref{shake} and \\ref{rigid}).\n\n\\section{The Intramolecular Potential Functions}\n\\label{intramolecular}\nIn this section we catalogue and describe the forms of potential\nfunction available in \\D{}  The {\\bf key words} required to select\npotential forms are given in brackets () before each definition. The\nderivations of the atomic forces, virial and stress tensor are also\noutlined.\n\n\\subsection{Bond Potentials}\n\n\\begin{figure}[ht]\n\\begin{center}\n\\includegraphics[height=2cm]{bond.eps}\n\\caption{The interatomic bond vector.}\n\\end{center}\n\\end{figure}\n\nThe bond potentials\\index{potential!bond} describe {\\em explicit} bonds\\index{potential!bond} between specified\natoms. They are functions of the interatomic distance only. The\npotential functions available are as follows.\n\n\\begin{enumerate}\n\\item Harmonic bond: ({\\bf harm})\n\\begin{equation}\n U(r_{ij})=\\frac{1}{2}k(r_{ij}-r_{o})^2;\n\\end{equation}\n\\item Morse potential:  ({\\bf mors})\n\\begin{equation}\nU(r_{ij})=E_{o}[\\{1-\\exp(-k(r_{ij}-r_{o}))\\}^{2}-1];\n\\end{equation}\n\\item 12-6 potential bond: ({\\bf 12-6})\n\\begin{equation}\nU(r_{ij})=\\left(\\frac{A}{r_{ij}^{12}}\\right)-\\left(\\frac{B}{r_{ij}^{6}}\\right);\n\\end{equation}\n\\item Restrained harmonic:  ({\\bf rhrm})\n\\begin{eqnarray}\nU(r_{ij})&=&\\frac{1}{2}k(r_{ij}-r_{o})^2~~~~~~|r_{ij}-r_{o}|\\le\nr_{c};\\\\\nU(r_{ij})&=&\\frac{1}{2}kr_{c}^2+kr_{c}(|r_{ij}-r_{o}|-r_{c})~~~~~~|r_{ij}-r_{o}|>\nr_{c};\n\\end{eqnarray}\n\\item Quartic potential:  ({\\bf quar})\n\\begin{equation}\nU(r_{ij})=\\frac{k}{2}(r_{ij}-r_{o})^2+\\frac{k'}{3}(r_{ij}-r_{o})^3+\\frac{k''}{4}(r_{ij}-r_{o})^4.\n\\end{equation}\n\\item Buckingham potential: ({\\bf buck})\n\\begin{equation}\nU(r_{ij})=A~\\exp\\left(-\\frac{r_{ij}}{\\rho}\\right)-\\frac{C}{r_{ij}^{6}};\n\\end{equation}\n\\item Shifted finitely extendible non-linear elastic (FENE) potential \\cite{warner-72,bird-77,grest-86}:  ({\\bf fene})\n\\begin{equation}\nU(r_{ij}) = \\left\\{ \\begin{array} {l@{\\qquad:\\qquad}l}\n-0.5~k~R_{o}^{2}~ln\\left[1-\\left(\\frac{r_{ij}-\\Delta}{R_{o}}\\right)^{2}\\right] & r_{ij} < R_{o} + \\Delta \\\\\n\\infty & r_{ij} \\ge R_{o} + \\Delta \\end{array} \\right. \\label{FENE}\n\\end{equation}\nThe FENE potential is used to maintain the distance between\nconnected beads and to prevent chains from crossing each other. It\nis used in combination with the WCA (\\ref{wca}) potential to create\na potential well for the flexible bonds of a molecule, that\nmaintains the topology of the molecule.  This implementation allows\nfor a radius shift of up to half a $R_{o}$ ($|\\Delta| \\le\n0.5~R_{o}$) with a default of zero ($\\Delta_{default} = 0$).\n\\item Coulomb potential: ({\\bf coul})\n\\begin{equation}\nU(r_{ij})=\\frac{1}{4\\pi\\epsilon_{0}}\\frac{q_{i}q_{j}}{r_{ij}}\n\\end{equation}\nNote that the Coulombic bond potential is not normally required, as generally\nthe electrostatic interactions are handled as nonbonded terms elsewhere in the\nprogram. However, it is sometimes explicit in the description of the chemical\nbond in a way that is different from the default electrostatic treatment, and\nneeds to be introduced as an extra feature.\n\\end{enumerate}\nIn these formulae $r_{ij}$ is the distance between atoms labelled $i$\nand\n$j$:\n\\begin{equation}\nr_{ij}=|\\vek{r}_{j}-\\vek{r}_{i}|,\n\\end{equation}\nwhere $\\vek{r}_{\\ell}$ is the position vector of an atom labelled\n$\\ell$. \\footnote{Note: some \\D{} routines may use the convention that\n$\\vek{r_{ij}}=\\vek{r}_{i}-\\vek{r}_{j}$. Nobody's perfect.}\n\nThe force on the atom $j$ arising from a bond potential\\index{potential!bond} is obtained\nusing the general formula:\n\\begin{equation}\n\\vek{f}_{j}=-\\frac{1}{{r}_{ij}}\\left[\n\\frac{\\partial }{\\partial r_{ij}}U(r_{ij})\\right]\\vek{r}_{ij},\n\\end{equation}\nThe force $\\vek{f}_{i}$ acting on atom $i$ is the negative of this.\n\nThe contribution to be added to the atomic virial is given by\n\\begin{equation}\n{\\cal W}=-\\vek{r}_{ij}\\cdot \\vek{f}_{j},\n\\end{equation}\nwith only {\\em one} such contribution from each bond\\index{potential!bond}.\n\nThe contribution to be added to the atomic stress tensor is\ngiven by\n\\begin{equation}\n\\sigma^{\\alpha \\beta}=r_{ij}^{\\alpha}f_{j}^{\\beta},\n\\end{equation}\nwhere $\\alpha$ and $\\beta$ indicate the $x,y,z$ components. The atomic\nstress tensor derived in this way is symmetric.\n\nIn \\D{} bond forces are handled by the routine {\\sc bndfrc}.\n\n\\subsection{Distance Restraints}\n\nIn \\D{} distance restraints, in which the separation between two atoms,\nis maintained around some preset value $r_0$ is handled as a special\ncase of bond potentials. As a consequence distance restraints may be\napplied only between atoms in the same molecule.  Unlike with\napplication of the ``pure'' bond potentials\\index{potential!bond}, the electrostatic\\index{potential!electrostatic} and van\nder Waals\\index{potential!van der Waals} interactions between the pair of atoms are still evaluated\nwhen distance restraints are applied.  All the potential forms of the\nprevious section are as avaliable distance restraints\\index{distance restraints}, although they\nhave different key words:\n\n\\begin{enumerate}\n\\item Harmonic potential: ({\\bf -hrm})\n\\item Morse potential:  ({\\bf -mrs})\n\\item 12-6 potential bond: ({\\bf -126})\n\\item Restrained harmonic: ({\\bf -rhm})\n\\item Quartic potential:  ({\\bf -qur})\n\\item Buckingham potential: ({\\bf -bck})\n\\item FENE potential: ({\\bf -fen})\n\\item Coulombic bond: ({\\bf -cou})\n\\end{enumerate}\n\nIn \\D{} distance restraints\\index{distance restraints} are handled by the routine {\\sc bndfrc}.\n\n\\subsection{Valence Angle Potentials}\n\n\\begin{figure}[ht]\n\\begin{center}\n\\includegraphics[height=4cm]{angle.eps}\n\\caption{The valence angle and associated vectors}\n\\end{center}\n\\end{figure}\n\nThe valence angle\\index{potential!valence angle} potentials describe the bond bending terms between\nthe specified atoms. They should not be confused with the three body\\index{potential!three-body}\npotentials described later, which are defined by atom types rather\nthan indices.\n\\begin{enumerate}\n\\item Harmonic:  ({\\bf harm})\n\\begin{equation}\n U(\\theta_{jik})= {k\\over 2} (\\theta_{jik} - \\theta_0)^2;\n\\end{equation}\n\\item Quartic:  ({\\bf quar})\n\\begin{equation}\n U(\\theta_{jik})= {k\\over 2}(\\theta_{jik} - \\theta_0)^2 + {k'\\over\n3}(\\theta_{jik} -\n\\theta_0)^3 + {k''\\over 4}(\\theta_{jik} - \\theta_0)^4;\n\\end{equation}\n\\item Truncated harmonic:  ({\\bf thrm})\n\\begin{equation}\nU(\\theta_{jik})= {k\\over 2} (\\theta_{jik} - \\theta_0)^2\n\\exp[-(r_{ij}^8 + r_{ik}^8)/\\rho^8];\n\\end{equation}\n\\item Screened harmonic:  ({\\bf shrm})\n\\begin{equation}\n U(\\theta_{jik})= {k\\over 2} (\\theta_{jik} - \\theta_0)^2\n\\exp[-(r_{ij}/\\rho_1 + r_{ik}/\\rho_2)] ;\n\\end{equation}\n\\item Screened Vessal\\cite{vessal-94a}:  ({\\bf bvs1})\n\\begin{eqnarray}\nU(\\theta_{jik})&=& {k \\over 8(\\theta_{jik}-\\pi)^2}\\left\\{ \\left[\n(\\theta_0 -\\pi)^2 -(\\theta_{jik}-\\pi)^2\\right]^2\n\\right\\} \\nonumber \\\\\n& &  \\exp[-(r_{ij}/\\rho_1 + r_{ik}/\\rho_2)];\n\\end{eqnarray}\n\\item Truncated Vessal\\cite{smith-95a}: ({\\bf bvs2 })\n\\begin{eqnarray}\nU(\\theta_{jik})&=& k\\big[ \\theta_{jik}^a (\\theta_{jik}-\\theta_0)^2\n(\\theta_{jik}+\\theta_0-2\\pi)^2  - {a\\over 2} \\pi^{a-1}\\nonumber \\\\\n& & (\\theta_{jik}-\\theta_0)^2(\\pi - \\theta_0)^3\\big]\n\\exp[-(r_{ij}^8 + r_{ik}^8)/\\rho^8].\n\\end{eqnarray}\n\\item Harmonic cosine: ({\\bf hcos})\n\\begin{equation}\nU(\\theta_{jik})={k\\over 2}(cos(\\theta_{jik}) -cos(\\theta_{0}))^{2}\n\\end{equation}\n\\item Cosine: ({\\bf cos})\n\\begin{equation}\nU(\\theta_{jik})=A[1+cos(m\\theta_{jik}-\\delta)]\n\\end{equation}\n\\item MM3 stretch-bend: ({\\bf mmsb})\n\\begin{equation}\n U(\\theta_{jik})= A (\\theta_{jik} -\n \\theta_0)(r_{ij}-r_{ij}^o)(r_{ik}-r_{ik}^o)\n\\end{equation}\n\\item Compass stretch-stretch: ({\\bf stst})\n\\begin{equation}\nU_{jik}=A (r_{ij}-r_{ij}^o)(r_{ik}-r_{ik}^o)\n\\end{equation}\n\\item Compass stretch-bend: ({\\bf stbe})\n\\begin{equation}\n U(\\theta_{jik})= A (\\theta_{jik} -\\theta_0)(r_{ij}-r_{ij}^o)\n\\end{equation}\n\\item Compass all terms: ({\\bf cmps})\n\\begin{eqnarray}\n U(\\theta_{jik})&=& A (r_{ij}-r_{ij}^o)(r_{ik}-r_{ik}^o)+ \\nonumber \\\\\n& & (\\theta_{jik}-\\theta_0)(B(r_{ij}-r_{ij}^o)+C(r_{ik}-r_{ik}^o))\n\\end{eqnarray}\n\\end{enumerate}\nIn these formulae $\\theta_{jik}$ is the angle between bond vectors\n$\\vek{r}_{ij}$ and $\\vek{r}_{ik}$:\n\\begin{equation}\n\\theta_{jik}=cos^{-1}\\left\\{\\frac{\\vek{r}_{ij}\\cdot\\vek{r}_{ik}}\n{r_{ij}r_{ik}}\\right\\}\n\\end{equation}\n\nIn \\D{} the most general form for the valence\nangle\\index{potential!valence angle}\npotentials can be written as:\n\\begin{equation}\nU(\\theta_{jik},r_{ij},r_{ik})=A(\\theta_{jik})S(r_{ij})S(r_{ik})\n\\end{equation}\nwhere $A(\\theta)$ is a purely angular function and $S(r)$ is a\nscreening or truncation function. All the function arguments are\nscalars.  With this reduction the force on an atom derived from the\nvalence angle\\index{potential!valence angle} potential is given by:\n\\begin{equation}\nf_{\\ell}^{\\alpha}=-\\frac{\\partial}{\\partial\nr_{\\ell}^{\\alpha}}U(\\theta_{jik},r_{ij},r_{ik}),\n\\end{equation}\nwith atomic label $\\ell$ being one of $i,j,k$ and $\\alpha$ indicating the\n$x,y,z$ component. The derivative is\n\\begin{eqnarray}\n-\\frac{\\partial}{\\partial\nr_{\\ell}^{\\alpha}}U(\\theta_{jik},r_{ij},r_{ik})&=&\n-S(r_{ij})S(r_{ik})\\frac{\\partial}{\\partial\nr_{\\ell}^{\\alpha}}A(\\theta_{jik}) \\nonumber \\\\ & & -\nA(\\theta_{jik})S(r_{ik})(\\delta_{\\ell j}-\\delta_{\\ell i})\n\\frac{r_{ij}^{\\alpha}}{r_{ij}}\n\\frac{\\partial}{\\partial r_{ij}}S(r_{ij})\\nonumber \\\\\n& & - A(\\theta_{jik})S(r_{ij})(\\delta_{\\ell k}-\\delta_{\\ell i})\n\\frac{r_{ik}^{\\alpha}}{r_{ik}}\n\\frac{\\partial}{\\partial r_{ik}}S(r_{ik}),\n\\end{eqnarray}\nwith $\\delta_{ab}=1$ if $a=b$ and $\\delta_{ab}=0$ if $a\\ne b$. In the\nabsence of screening terms $S(r)$, this formula reduces to:\n\\begin{equation}\n-\\frac{\\partial}{\\partial\nr_{\\ell}^{\\alpha}}U(\\theta_{jik},r_{ij},r_{ik})=\n-\\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}}A(\\theta_{jik})\n\\end{equation}\nThe derivative of the angular function is\n\\begin{equation}\n-\\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}}A(\\theta_{jik})=\n\\left\\{\\frac{1}{\\sin(\\theta_{jik})}\\right\\}\n\\frac{\\partial}{\\partial \\theta_{jik}}A(\\theta_{jik})\n\\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}}\\left\\{\n\\frac{\\vek{r}_{ij}\\cdot\\vek{r}_{ik}}{r_{ij}r_{ik}}\\right\\},\n\\end{equation}\nwith\n\\begin{eqnarray}\n\\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}}\\left\\{\n\\frac{\\vek{r}_{ij}\\cdot\\vek{r}_{ik}}{r_{ij}r_{ik}}\\right\\}&=&\n(\\delta_{\\ell j}-\\delta_{\\ell i})\\frac{r_{ik}^{\\alpha}}{r_{ij}r_{ik}}+\n(\\delta_{\\ell k}-\\delta_{\\ell\ni})\\frac{r_{ij}^{\\alpha}}{r_{ij}r_{ik}}-\\nonumber \\\\ & &\n\\cos(\\theta_{jik})\n\\left\\{(\\delta_{\\ell j}-\\delta_{\\ell\ni})\\frac{r_{ij}^{\\alpha}}{r_{ij}^{2}}+\n(\\delta_{\\ell k}-\\delta_{\\ell\ni})\\frac{r_{ik}^{\\alpha}}{r_{ik}^{2}}\\right\\}\n\\end{eqnarray}\nThe atomic forces are then completely specified by the derivatives of\nthe particular functions $A(\\theta)$ and $S(r)$.\n\nThe contribution to be added to the atomic virial is given by\n\\begin{equation}\n{\\cal W}=-(\\vek{r}_{ij}\\cdot\\vek{f}_{j}+\\vek{r}_{ik}\\cdot\\vek{f}_{k})\n\\end{equation}\nIt is worth noting that in the absence of screening terms S(r), the\nvirial is zero \\cite{smith-93c}.\n\nThe contribution to be added to the atomic stress tensor\\index{stress tensor} is given by\n\\begin{equation}\n\\sigma^{\\alpha \\beta}=r_{ij}^{\\alpha}f_{j}^{\\beta}+\nr_{ik}^{\\alpha}f_{k}^{\\beta}\n\\end{equation}\nand the stress tensor\\index{stress tensor} is symmetric.\n\nIn \\D{} valence forces are handled by the routine {\\sc\nangfrc}.\n\n\\subsection{Angular Restraints}\n\nIn \\D{} angle restraints, in which the angle subtended by a triplet of\natoms, is maintained around some preset value $\\theta_0$ is handled as\na special case of angle potentials. As a consequence angle restraints\nmay be applied only between atoms in the same molecule.  Unlike with\napplication of the ``pure'' angle potentials, the electrostatic\\index{potential!electrostatic} and\nvan der Waals\\index{potential!van der Waals} interactions between the pair of atoms are still\nevaluated when distance restraints are applied.  All the potential\nforms of the previous section are available as angular restraints,\nalthough they have different key words:\n\n\\begin{enumerate}\n\\item Harmonic:  ({\\bf -hrm})\n\\item Quartic:  ({\\bf -qur})\n\\item Truncated harmonic:  ({\\bf -thm})\n\\item Screened harmonic:  ({\\bf -shm})\n\\item Screened Vessal\\cite{vessal-94a}:  ({\\bf -bv1})\n\\item Truncated Vessal\\cite{smith-95a}: ({\\bf -bv2})\n\\item Harmonic cosine: ({\\bf -hcs})\n\\item Cosine : ({\\bf -cos})\n\\item MM3 stretch-bend: ({\\bf -msb})\n\\item Compass stretch-stretch ({\\bf -sts})\n\\item Compass stretch-bend ({\\bf -stb})\n\\item Compass all terms ({\\bf -cmp})\n\\end{enumerate}\n\nIn \\D{} angular restraints\\index{angular restraints} are handled by the routine {\\sc angfrc}.\n\n\\subsection{Dihedral Angle Potentials}\n\n\\begin{figure}[ht]\n\\begin{center}\n\\includegraphics[height=4cm]{dihed.eps}\n\\caption{The dihedral angle and associated vectors}\n\\end{center}\n\\end{figure}\n\nThe dihedral angle\\index{potential!dihedral} potentials describe the interaction arising from\ntorsional forces in molecules. (They are sometimes referred to as\ntorsion potentials.) They require the specification of four atomic\npositions.  The potential functions available in \\D{} are as\nfollows.\n\\begin{enumerate}\n\\item Cosine potential: ({\\bf cos})\n\\begin{equation}\nU(\\phi_{ijkn})= A \\left [ 1 + \\cos (m\\phi_{ijkn} - \\delta)\\right] \n\\end{equation}\n\\item Harmonic: ({\\bf harm})\n\\begin{equation}\nU(\\phi_{ijkn})= {1\\over 2} k (\\phi_{ijkn} - \\phi_0)^2 \n\\end{equation}\n\\item Harmonic cosine: ({\\bf hcos})\n\\begin{equation}\nU(\\phi_{ijkn})={k\\over 2}(cos(\\phi_{ijkn}) -cos(\\phi_{0}))^{2}\n\\end{equation}\n\\item Triple cosine: ({\\bf cos3})\n\\begin{equation}\nU(\\phi)={1\\over 2}A_{1}(1+cos(\\phi))+{1\\over 2}A_{2}(1-cos(2\\phi))+\n{1\\over 2}A_{3}(1+cos(3\\phi))\n\\end{equation}\n\\item Ryckaert-Bellemans hydrocarbon potential: ({\\bf ryck})\n\\begin{equation}\nU(\\phi_{ijkn})=A(a_0+\\sum_{i=1}^{5}(a_i cos^i(\\phi))\n\\end{equation}\n\\item Ryckaert-Bellemans fluorinated potential: ({\\bf rbf})\n\\begin{equation}\nU(\\phi_{ijkn})=B(b_0+\\sum_{i=1}^{5}(b_i cos^i(\\phi))\n\\end{equation}\n\\item OPLS angle potential\n\\begin{equation} \nU(\\phi_{ijkn})=a_0+0.5*(a_1(1+cos(\\phi))+a_2(1-cos(2\\phi))+a_3(1+cos(3\\phi)))\n\\end{equation}\n\n\\end{enumerate}\nIn these formulae $\\phi_{ijkn}$ is the dihedral angle defined by\n\\begin{equation}\n\\phi_{ijkn}=\\cos^{-1}\\{B(\\vek{r}_{ij},\\vek{r}_{jk},\\vek{r}_{kn})\\},\n\\end{equation}\nwith\n\\begin{equation}\nB(\\vek{r}_{ij},\\vek{r}_{jk},\\vek{r}_{kn})=\n\\left\\{\\frac{\n(\\vek{r}_{ij}\\times\\vek{r}_{jk})\\cdot(\\vek{r}_{jk}\\times\\vek{r}_{kn})}\n{|\\vek{r}_{ij}\\times\\vek{r}_{jk}||\\vek{r}_{jk}\\times\\vek{r}_{kn}|}\n\\right\\}.\n\\end{equation}\nWith this definition, the sign of the dihedral\\index{potential!dihedral} angle is positive if\nthe\nvector product\n$(\\vek{r}_{ij}\\times\\vek{r}_{jk})\\times(\\vek{r}_{jk}\\times\\vek{r}_{kn})$\nis in the same direction as the bond\\index{potential!bond} vector $\\vek{r}_{jk}$ and\nnegative\nif in the opposite direction.\n\nThe force on an atom arising from the dihedral\\index{potential!dihedral} potential is given by\n\\begin{equation}\nf_{\\ell}^{\\alpha}=-\\frac{\\partial}{\\partial\nr_{\\ell}^{\\alpha}}U(\\phi_{ijkn}),\n\\end{equation}\nwith $\\ell$ being one of $i,j,k,n$ and $\\alpha$ one of $x,y,z$. This\nmay\nbe expanded into\n\\begin{equation}\n-\\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}}U(\\phi_{ijkn})=\n\\left\\{\\frac{1}{\\sin(\\phi_{ijkn})}\\right\\}\n\\frac{\\partial}{\\partial \\phi_{ijkn}}U(\\phi_{ijkn})\n\\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}}\nB(\\vek{r}_{ij},\\vek{r}_{jk},\\vek{r}_{kn}).\n\\end{equation}\nThe derivative of the function\n$B(\\vek{r}_{ij},\\vek{r}_{jk},\\vek{r}_{kn})$ is\n\\begin{eqnarray}\n& &\\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}}\nB(\\vek{r}_{ij},\\vek{r}_{jk},\\vek{r}_{kn})=\n\\frac{1}{|\\vek{r}_{ij}\\times\\vek{r}_{jk}||\\vek{r}_{jk}\\times\\vek{r}_{kn}|}\n\\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}} \n\\{(\\vek{r}_{ij}\\times\\vek{r}_{jk})\\cdot(\\vek{r}_{jk}\\times\\vek{r}_{kn})\\}\n\\\\\n& & \\phantom{xxxxxx}\n -\\frac{\\cos(\\phi_{ijkn})}{2}\\left\\{\n\\frac{1}{|\\vek{r}_{ij}\\times\\vek{r}_{jk}|^{2}}\n\\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}}\n|\\vek{r}_{ij}\\times\\vek{r}_{jk}|^{2}+\n\\frac{1}{|\\vek{r}_{jk}\\times\\vek{r}_{kn}|^{2}}\n\\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}}\n|\\vek{r}_{jk}\\times\\vek{r}_{kn}|^{2}\n\\right \\},\\nonumber\n\\end{eqnarray}\nwith\n\\begin{eqnarray}\n\\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}}\n\\{(\\vek{r}_{ij}\\times\\vek{r}_{jk})\\cdot(\\vek{r}_{jk}\\times\\vek{r}_{kn})\\}&=&\nr_{ij}^{\\alpha}([\\vek{r}_{jk}\\vek{r}_{jk}]_{\\alpha}(\\delta_{\\ell\nk}-\\delta_{\\ell n})+ [\\vek{r}_{jk}\\vek{r}_{kn}]_{\\alpha}(\\delta_{\\ell\nk}-\\delta_{\\ell j}))+\n\\nonumber \\\\ \\phantom{\\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}}}& & \nr_{jk}^{\\alpha}([\\vek{r}_{ij}\\vek{r}_{jk}]_{\\alpha}(\\delta_{\\ell\nn}-\\delta_{\\ell k})+ [\\vek{r}_{jk}\\vek{r}_{kn}]_{\\alpha}(\\delta_{\\ell\nj}-\\delta_{\\ell i}))+\n\\nonumber \\\\ \\phantom{\\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}}} & &\nr_{kn}^{\\alpha}([\\vek{r}_{ij}\\vek{r}_{jk}]_{\\alpha}(\\delta_{\\ell\nk}-\\delta_{\\ell j})+ [\\vek{r}_{jk}\\vek{r}_{jk}]_{\\alpha}(\\delta_{\\ell\ni}-\\delta_{\\ell j}))+\n\\nonumber \\\\ \\phantom{\\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}}} & &\n2r_{jk}^{\\alpha}[\\vek{r}_{ij}\\vek{r}_{kn}]_{\\alpha}(\\delta_{\\ell\nj}-\\delta_{\\ell k}),\n\\end{eqnarray}\n\\begin{eqnarray}\n\\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}}\n|\\vek{r}_{ij}\\times\\vek{r}_{jk}|^{2}&=&\n2r_{ij}^{\\alpha}([\\vek{r}_{jk}\\vek{r}_{jk}]_{\\alpha}(\\delta_{\\ell\nj}-\\delta_{\\ell i}) +[\\vek{r}_{ij}\\vek{r}_{jk}]_{\\alpha}(\\delta_{\\ell\nj}-\\delta_{\\ell k}))+\\nonumber \\\\ & &\n2r_{jk}^{\\alpha}([\\vek{r}_{ij}\\vek{r}_{ij}]_{\\alpha}(\\delta_{\\ell\nk}-\\delta_{\\ell j}) +[\\vek{r}_{ij}\\vek{r}_{jk}]_{\\alpha}(\\delta_{\\ell\ni}-\\delta_{\\ell j})),\n\\end{eqnarray}\n\\begin{eqnarray}\n\\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}}\n|\\vek{r}_{jk}\\times\\vek{r}_{kn}|^{2}&=&\n2r_{kn}^{\\alpha}([\\vek{r}_{jk}\\vek{r}_{jk}]_{\\alpha}(\\delta_{\\ell\nn}-\\delta_{\\ell k}) +[\\vek{r}_{jk}\\vek{r}_{kn}]_{\\alpha}(\\delta_{\\ell\nj}-\\delta_{\\ell k}))+\\nonumber \\\\ & &\n2r_{jk}^{\\alpha}([\\vek{r}_{kn}\\vek{r}_{kn}]_{\\alpha}(\\delta_{\\ell\nk}-\\delta_{\\ell j}) +[\\vek{r}_{jk}\\vek{r}_{kn}]_{\\alpha}(\\delta_{\\ell\nk}-\\delta_{\\ell n})).\n\\end{eqnarray}\n\\vskip 2mm\nWhere we have used the the following definition:\n\\begin{equation}\n[\\vek{a} ~\n\\vek{b}]_{\\alpha}=\\sum_{\\beta}(1-\\delta_{\\alpha\\beta})a^{\\beta}b^{\\beta}.\n\\end{equation}\nFormally, the contribution to be added to the atomic virial is given\nby\n\\begin{equation}\n{\\cal W}=-\\sum_{i=1}^{4}\\vek{r}_{i}\\cdot\\vek{f}_{i}\n\\end{equation}\nHowever it is possible to show (by tedious algebra using the above\nformulae, or more elegantly by thermodynamic arguments\n\\cite{smith-93c},) that the dihedral makes {\\em no} contribution to\nthe atomic virial.\n\nThe contribution to be added to the atomic stress tensor\\index{stress tensor} is given by\n\\begin{eqnarray}\n\\sigma^{\\alpha \\beta}&=&r_{ij}^{\\alpha}p_{i}^{\\beta}+\nr_{jk}^{\\alpha}p_{jk}^{\\beta}+r_{kn}^{\\alpha}p_{n}^{\\beta} \\\\ & &\n-\\frac{\\cos(\\phi_{ijkn})}{2}\\left \\{r_{ij}^{\\alpha}g_{i}^{\\beta}+\nr_{jk}^{\\alpha}g_{k}^{\\beta}+r_{jk}^{\\alpha}h_{j}^{\\beta}+r_{kn}^{\\alpha}h_{n}^{\\beta}\\right\\}\n,\\nonumber\n\\end{eqnarray}\nwith\n\\begin{eqnarray}\np_{i}^{\\alpha}&=&(r_{jk}^{\\alpha}[\\vek{r}_{jk}\\vek{r}_{kn}]_{\\alpha}-\nr_{kn}^{\\alpha}[\\vek{r}_{jk}\\vek{r}_{jk}]_{\\alpha})/\n(|\\vek{r}_{ij}\\times\\vek{r}_{jk}||\\vek{r}_{jk}\\times\\vek{r}_{kn}|)\\\\\np_{n}^{\\alpha}&=&(r_{jk}^{\\alpha}[\\vek{r}_{ij}\\vek{r}_{jk}]_{\\alpha}-\nr_{ij}^{\\alpha}[\\vek{r}_{jk}\\vek{r}_{jk}]_{\\alpha})/\n(|\\vek{r}_{ij}\\times\\vek{r}_{jk}||\\vek{r}_{jk}\\times\\vek{r}_{kn}|)\\\\\np_{jk}^{\\alpha}&=&(r_{ij}^{\\alpha}[\\vek{r}_{jk}\\vek{r}_{kn}]_{\\alpha}+\nr_{kn}^{\\alpha}[\\vek{r}_{ij}\\vek{r}_{jk}]_{\\alpha}-\n2r_{jk}^{\\alpha}[\\vek{r}_{ij}\\vek{r}_{kn}]_{\\alpha})/\n(|\\vek{r}_{ij}\\times\\vek{r}_{jk}||\\vek{r}_{jk}\\times\\vek{r}_{kn}|)\\\\\ng_{i}^{\\alpha}&=&2(r_{ij}^{\\alpha}[\\vek{r}_{jk}\\vek{r}_{jk}]_{\\alpha}-\nr_{jk}^{\\alpha}[\\vek{r}_{ij}\\vek{r}_{jk}]_{\\alpha})/\n|\\vek{r}_{ij}\\times\\vek{r}_{jk}|^{2}\\\\\ng_{k}^{\\alpha}&=&2(r_{jk}^{\\alpha}[\\vek{r}_{ij}\\vek{r}_{ij}]_{\\alpha}-\nr_{ij}^{\\alpha}[\\vek{r}_{ij}\\vek{r}_{jk}]_{\\alpha})/\n|\\vek{r}_{ij}\\times\\vek{r}_{jk}|^{2}\\\\\nh_{j}^{\\alpha}&=&2(r_{jk}^{\\alpha}[\\vek{r}_{kn}\\vek{r}_{kn}]_{\\alpha}-\nr_{kn}^{\\alpha}[\\vek{r}_{jk}\\vek{r}_{kn}]_{\\alpha})/\n|\\vek{r}_{jk}\\times\\vek{r}_{kn}|^{2}\\\\\nh_{n}^{\\alpha}&=&2(r_{kn}^{\\alpha}[\\vek{r}_{kn}\\vek{r}_{kn}]_{\\alpha}-\nr_{jk}^{\\alpha}[\\vek{r}_{jk}\\vek{r}_{kn}]_{\\alpha})/\n|\\vek{r}_{jk}\\times\\vek{r}_{kn}|^{2}\n\\end{eqnarray}\nThe sum of the diagonal elements of the stress tensor\\index{stress tensor} is zero (since\nthe virial is zero) and the matrix is symmetric.\n\nLastly, it should be noted that the above description does not take\ninto account the possible inclusion of distance-dependent 1-4\ninteractions, as permitted by some force fields\\index{force field}. Such interactions are\npermissible in \\D{} and are described in the section on pair\npotentials below. \\D{} also permits scaling of the 1-4\ninteractions by a numerical factor. 1-4 interactions do, of\ncourse, contribute to the atomic virial.\n\nIn \\D{} dihedral forces are handled by the routine {\\sc dihfrc}.\n\n\\subsection{Improper Dihedral Angle Potentials}\n\nImproper dihedrals\\index{potential!dihedral} are used to restrict the geometry of molecules and\nas such need not have a simple relation to conventional chemical\nbonding\\index{potential!bond}.  \\D{} makes no distinction between dihedral\\index{potential!dihedral} angle\nfunctions and improper dihedrals\\index{potential!improper dihedral} (both are calculated by the same\nsubroutines) and all the comments made in the preceeding section\napply.\n\nAn important example of the use of the improper\ndihedral\\index{potential!improper dihedral} is to\nconserve the structure of chiral centres in molecules modelled by\nunited-atom centres. For example $\\alpha$-amino acids such as alanine\n(CH$_{3}$CH(NH$_{2}$)COOH), in which it is common to represent the\nCH$_{3}$ and CH groups as single centres. Conservation of the\nchirality of the $\\alpha$ carbon is achieved by defining a harmonic\nimproper dihedral angle\\index{potential!dihedral} potential with an equilibrium angle of\n35.264$^{o}$.  The angle is defined by vectors $\\vek{r}_{12}$,\n$\\vek{r}_{23}$ and $\\vek{r}_{34}$, where the atoms 1,2,3 and 4 are\nshown in the following figure. The figure defines the D and L\nenantiomers consistent with the international (IUPAC) convention. When\ndefining the dihedral\\index{potential!dihedral}, the atom indices are entered in \\D{}\nin the order 1-2-3-4.\n\n\\begin{figure}[ht]\n\\begin{center}\n\\includegraphics[height=8cm]{isomers.eps}\n\\caption{The L and D enantiomers and defining vectors}\n\\end{center}\n\\end{figure}\n\nIn \\D{} improper dihedral forces\\index{potential!dihedral} are handled by the routine\n{\\sc dihfrc}.\n\n\\subsection{Inversion Angle Potentials}\n\n\\begin{figure}[ht]\n\\begin{center}\n\\includegraphics[height=4cm]{invers.eps}\n\\caption{The inversion angle and associated vectors}\n\\end{center}\n\\end{figure}\n\nThe inversion angle potentials\\index{potential!inversion} describe the interaction arising from a\nparticular geometry of three atoms around a central atom. The best\nknown example of this is the arrangement of hydrogen atoms around\nnitrogen in ammonia to form a trigonal pyramid. The hydrogens can\n`flip' like an inverting umbrella to an alternative structure, which\nin this case is identical, but in principle causes a change in\nchirality. The force restraining the ammonia to one structure can be\ndescribed as an inversion potential\\index{potential!inversion} (though it is usually augmented by\nvalence\\index{potential!valence angle} angle potentials also). The inversion angle is defined in the\nfigure above - {\\bf note that the inversion\\index{potential!inversion} angle potential is a sum of\nthe three possible inversion\\index{potential!inversion} angle terms.} It resembles a dihedral\\index{potential!dihedral}\npotential in that it requires the specification of four atomic\npositions.\n\nThe potential functions available in \\D{} are as\nfollows.\n\\begin{enumerate}\n\\item Harmonic: ({\\bf harm})\n\\begin{equation}\nU(\\phi_{ijkn})= {1\\over 2} k (\\phi_{ijkn} - \\phi_0)^2 \n\\end{equation}\n\\item Harmonic cosine: ({\\bf hcos})\n\\begin{equation}\nU(\\phi_{ijkn})={k\\over 2}(cos(\\phi_{ijkn}) -cos(\\phi_{0}))^{2}\n\\end{equation}\n\\item Planar potential: ({\\bf plan})\n\\begin{equation}\nU(\\phi_{ijkn})= A \\left [ 1 - \\cos (\\phi_{ijkn})\\right] \n\\end{equation}\n\\end{enumerate}\nIn these formulae $\\phi_{ijkn}$ is the inversion\\index{potential!inversion} angle defined by\n\\begin{equation}\n\\phi_{ijkn}=\\cos^{-1}\\left \\{\\frac{\\vek{r}_{ij}\\cdot\\vek{w}_{kn}}{r_{ij}w_{kn}}\\right \\},\n\\end{equation}\nwith\n\\begin{equation}\n\\vek{w}_{kn}=(\\vek{r}_{ij}\\cdot\\vek{\\hat{u}}_{kn})\\vek{\\hat{u}}_{kn}+\n(\\vek{r}_{ij}\\cdot\\vek{\\hat{v}}_{kn})\\vek{\\hat{v}}_{kn}\n\\end{equation}\nand the unit vectors\n\\begin{eqnarray}\n\\vek{\\hat{u}}_{kn}&=&(\\vek{\\hat{r}}_{ik}+\\vek{\\hat{r}}_{in})/\n|\\vek{\\hat{r}}_{ik}+\\vek{\\hat{r}}_{in}| \\nonumber  \\\\\n\\vek{\\hat{v}}_{kn}&=&(\\vek{\\hat{r}}_{ik}-\\vek{\\hat{r}}_{in})/\n|\\vek{\\hat{r}}_{ik}-\\vek{\\hat{r}}_{in}|.\n\\end{eqnarray}\nAs usual, $\\vek{r}_{ij}=\\vek{r}_{j}-\\vek{r}_{i}$ {\\em etc.} and the\nhat $\\vek{\\hat{r}}$ indicates a {\\em unit} vector in the direction of\n$\\vek{r}$. The total inversion\\index{potential!inversion} potential requires the calculation of\nthree such angles, the formula being derived from the above using the\ncyclic permutation of the indices $j\\rightarrow k \\rightarrow n\n\\rightarrow j$ {\\em etc}.\n\nEquivalently, the angle $\\phi_{ijkn}$ may be written as\n\\begin{equation}\n\\phi_{ijkn}=\\cos^{-1} \\left \\{ \\frac{\n[(\\vek{r}_{ij}\\cdot\\vek{\\hat{u}}_{kn})^{2}\n+(\\vek{r}_{ij}\\cdot\\vek{\\hat{v}}_{kn})^{2}]^{1/2}}{r_{ij}}\\right \\}\n\\end{equation}\n\nFormally, the force on an atom arising from the inversion\\index{potential!inversion} potential is given by\n\\begin{equation}\nf_{\\ell}^{\\alpha}=-\\frac{\\partial}{\\partial\nr_{\\ell}^{\\alpha}}U(\\phi_{ijkn}),\n\\end{equation}\nwith $\\ell$ being one of $i,j,k,n$ and $\\alpha$ one of $x,y,z$. This\nmay be expanded into\n\\begin{eqnarray}\n-\\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}}U(\\phi_{ijkn})&=&\n\\left\\{\\frac{1}{\\sin(\\phi_{ijkn})}\\right\\}\n\\frac{\\partial}{\\partial \\phi_{ijkn}}U(\\phi_{ijkn})\\times \\nonumber \\\\\n& & \\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}}\n\\left\\{\\frac{[(\\vek{r}_{ij}\\cdot\\vek{\\hat{u}}_{kn})^{2}\n+(\\vek{r}_{ij}\\cdot\\vek{\\hat{v}}_{kn})^{2}]^{1/2}}\n{r_{ij}}\\right \\}.\n\\end{eqnarray}\nFollowing through the (extremely tedious!) differentiation gives the result:\n\\begin{eqnarray}\nf_{\\ell}^{\\alpha} &=&\n\\left\\{\\frac{1}{\\sin(\\phi_{ijkn})}\\right\\}\n\\frac{\\partial}{\\partial \\phi_{ijkn}}U(\\phi_{ijkn})\\times \\\\\n& &\n\\left\\{-(\\delta_{\\ell j}-\\delta_{\\ell i})\\frac{cos(\\phi_{ijkn})}\n{r_{ij}^{2}}r_{ij}^{\\alpha} +\\frac{1}{r_{ij}w_{kn}}\\left [\n(\\delta_{\\ell j}-\\delta_{\\ell i}) \n\\{(\\vek{r}_{ij}\\cdot\\vek{\\hat{u}}_{kn})\\hat{u}_{kn}^{\\alpha}+\n(\\vek{r}_{ij}\\cdot\\vek{\\hat{v}}_{kn})\\hat{v}_{kn}^{\\alpha}\\} \n\\phantom{\\left\\{\\frac{a_{a}^{a}}{a_{a}^{a}}\\right\\}}\n\\right. \\right. \\nonumber \\\\\n& & + (\\delta_{\\ell k}-\\delta_{\\ell i})\n\\frac{\\vek{r}_{ij}\\cdot\\vek{\\hat{u}}_{kn}}{u_{kn}r_{ik}}\\left \\{\nr_{ij}^{\\alpha}-(\\vek{r}_{ij}\\cdot\\vek{\\hat{u}}_{kn})\\hat{u}_{kn}^{\\alpha}\n-(\\vek{r}_{ij}\\cdot\\vek{r}_{ik}-(\\vek{r}_{ij}\\cdot\\vek{\\hat{u}}_{kn})\n(\\vek{r}_{ik}\\cdot\\vek{\\hat{u}}_{kn}))\\frac{r_{ik}^{\\alpha}}{r_{ik}^{2}}\n\\right \\} \\nonumber \\\\\n& & + (\\delta_{\\ell k}-\\delta_{\\ell i})\n\\frac{\\vek{r}_{ij}\\cdot\\vek{\\hat{v}}_{kn}}{v_{kn}r_{ik}}\\left \\{\nr_{ij}^{\\alpha}-(\\vek{r}_{ij}\\cdot\\vek{\\hat{v}}_{kn})\\hat{v}_{kn}^{\\alpha}\n-(\\vek{r}_{ij}\\cdot\\vek{r}_{ik}-(\\vek{r}_{ij}\\cdot\\vek{\\hat{v}}_{kn})\n(\\vek{r}_{ik}\\cdot\\vek{\\hat{v}}_{kn}))\\frac{r_{ik}^{\\alpha}}{r_{ik}^{2}}\n\\right \\} \\nonumber \\\\\n& &+ (\\delta_{\\ell n}-\\delta_{\\ell i})\n\\frac{\\vek{r}_{ij}\\cdot\\vek{\\hat{u}}_{kn}}{u_{kn}r_{in}}\\left \\{\nr_{ij}^{\\alpha}-(\\vek{r}_{ij}\\cdot\\vek{\\hat{u}}_{kn})\\hat{u}_{kn}^{\\alpha}\n-(\\vek{r}_{ij}\\cdot\\vek{r}_{in}-(\\vek{r}_{ij}\\cdot\\vek{\\hat{u}}_{kn})\n(\\vek{r}_{in}\\cdot\\vek{\\hat{u}}_{kn}))\\frac{r_{in}^{\\alpha}}{r_{in}^{2}}\n\\right \\} \\nonumber \\\\\n& & \\left . \\left .- (\\delta_{\\ell n}-\\delta_{\\ell i})\n\\frac{\\vek{r}_{ij}\\cdot\\vek{\\hat{v}}_{kn}}{v_{kn}r_{in}}\\left \\{\nr_{ij}^{\\alpha}-(\\vek{r}_{ij}\\cdot\\vek{\\hat{v}}_{kn})\\hat{v}_{kn}^{\\alpha}\n-(\\vek{r}_{ij}\\cdot\\vek{r}_{in}-(\\vek{r}_{ij}\\cdot\\vek{\\hat{v}}_{kn})\n(\\vek{r}_{in}\\cdot\\vek{\\hat{v}}_{kn}))\\frac{r_{in}^{\\alpha}}{r_{in}^{2}}\n\\right \\} \\right ] \\right \\} \\nonumber \n\\end{eqnarray}\nThis general formula applies to all atoms $\\ell=i,j,k,n$. It must be\nremembered however, that these formulae apply to just\none of the three contributing terms (i.e. one angle $\\phi$) of the\nfull inversion\\index{potential!inversion} potential: specifically the inversion\\index{potential!inversion} angle pertaining\nto the out-of-plane vector $\\vek{r}_{ij}$. The contributions arising\nfrom the other vectors $\\vek{r}_{ik}$ and $\\vek{r}_{in}$ are obtained\nby the cyclic permutation of the indices in the manner described\nabove.  All these force contributions must be added to the final\natomic forces.\n\nFormally, the contribution to be added to the\natomic virial is given by\n\\begin{equation}\n{\\cal W}=-\\sum_{i=1}^{4}\\vek{r}_{i}\\cdot\\vek{f}_{i}\n\\end{equation}\n\nHowever it is possible to show by thermodynamic arguments ({\\em cf}\n\\cite{smith-93c},) or simply from the fact that the sum of forces on\natoms j,k and n is equal and opposite to the force on atom i, that the\ninversion potential makes\\index{potential!inversion} {\\em no} contribution to the atomic virial.\n\nIf the force components $f_{\\ell}^{\\alpha}$ for atoms $\\ell=i,j,k,n$ are\ncalculated using the above formulae, it is easily seen that\nthe contribution to be added to the atomic stress tensor\\index{stress tensor} is given by\n\\begin{equation}\n\\sigma^{\\alpha \\beta}=r_{ij}^{\\alpha}f_{j}^{\\beta}+\nr_{ik}^{\\alpha}f_{k}^{\\beta}+r_{in}^{\\alpha}f_{n}^{\\beta}\n\\end{equation}\nThe sum of the diagonal elements of the stress tensor\\index{stress tensor} is zero (since\nthe virial is zero) and the matrix is symmetric.\n\nIn \\D{} inversion\\index{potential!inversion} forces are handled by the routine {\\sc invfrc}.\n\n\\subsection{The Calcite Four-Body Potential}\n\\label{calcite}\n\\begin{figure}[ht]\n\\begin{center}\n\\includegraphics[height=4cm]{calcite.eps}\n\\caption{The vectors of the calcite potential}\n\\label{calcfig}\n\\end{center}\n\\end{figure}\n\\index{potential!calcite} This potential \\cite{rohl-03a} is designed to help\nmaintain the planar structure of the carbonate anion $[CO_{3}]^{2-}$ in a\nsimilar manner to the planar inversion potential described above. However it\nis {\\em not} an angular potential. It is dependent on the perpendicular\ndisplacement ($u$) of an atom $a$ from a plane defined by three other atoms\n$b$, $c$, and $d$ (see figure \\ref{calcfig}) and has the form\n\\begin{equation}\nU_{abcd}(u)=Au^{2}+Bu^{4} \\label{calcite1}\n\\end{equation}\nWhere the displacement $u$ is given by\n\\begin{equation}\nu=\\frac{\\vek{r}_{ab}\\cdot\\vek{r}_{bc}\\times\\vek{r}_{bd}}{|\\vek{r}_{bc}\\times\\vek{r}_{bd}|}.\\label{calcite2}\n\\end{equation}\nVectors $\\vek{r}_{ab}$,$\\vek{r}_{ac}$ and $\\vek{r}_{ad}$ define bonds between\nthe central atom $a$ and the peripheral atoms $b$, $c$ and $d$. Vectors\n$\\vek{r}_{bc}$ and $\\vek{r}_{bd}$ define the plane and are related to the bond\nvectors by:\n\\begin{eqnarray}\n\\vek{r}_{bc}&=&\\vek{r}_{ac}-\\vek{r}_{ab} \\nonumber \\\\\n\\vek{r}_{bd}&=&\\vek{r}_{ad}-\\vek{r}_{ab}.\n\\end{eqnarray}\nIt what follows it is convenient to define the vector product appearing in\nboth the numerator and denominator of equation (\\ref{calcite2}) as the vector\n$\\vek{w}_{cd}$ {\\em vis.}\n\\begin{equation}\n\\vek{w}_{cd}=\\vek{r}_{bc}\\times\\vek{r}_{bd}\n\\end{equation}\nWe also define the quantity $\\gamma(u)$ as\n\\begin{equation}\n\\gamma(u)=-(2Au+4Bu^{3}).\n\\end{equation}\nThe forces on the individual atoms due to the calcite potential are then given\nby \n\\begin{eqnarray}\n\\vek{f}_{a}&=&-\\gamma(u)\\hat{\\vek{w}}_{cd} \\nonumber \\\\\n\\vek{f}_{c}&=&\\phantom{+}\\vek{r}_{bd}\\times(\\vek{r}_{ab}-\nu\\hat{\\vek{w}}_{cd})\\gamma(u)/w_{cd} \\nonumber \\\\\n\\vek{f}_{d}&=&-\\vek{r}_{bc}\\times(\\vek{r}_{ab}-\nu\\hat{\\vek{w}}_{cd})\\gamma(u)/w_{cd} \\nonumber \\\\\n\\vek{f}_{b}&=&-(\\vek{f}_{a}+\\vek{f}_{c}+\\vek{f}_{d}),\n\\end{eqnarray}\nwhere $w_{cd}=|\\vek{w}_{cd}|$ and $\\hat{\\vek{w}}_{cd}=\\vek{w}_{cd}/w_{cd}$.\nThe virial contribution $\\psi_{abcd}(u)$ is given by\n\\begin{equation}\n\\psi_{abcd}(u)=2Au^{2}+4Bu^{4}\n\\end{equation}\nand the stress tensor contribution $\\sigma_{abcd}^{\\alpha\\beta}(u)$ by\n\\begin{equation}\n\\sigma_{abcd}^{\\alpha\\beta}(u)=\\frac{u\\gamma(u)}{\n  w_{cd}^{2}}w_{cd}^{\\alpha}w_{cd}^{\\beta}.\n\\end{equation}\n\nIn \\D{} the calcite\\index{potential!calcite} forces are handled by the routine\n{\\sc invfrc}, which is a convenient {\\em intramolecular} four-body force\nroutine. However it is manifestly {\\em not} an inversion potential as such.\n\n\\subsection{Tethering Forces}\n\n\\D{} also allows atomic sites to be tethered\\index{potential!tethered} to a fixed point in space, $\\vek{r}_0$ taken as their\nposition at the beginning of the simulation. This is also known as position restraining.\nThe specification, which comes as part of the molecular description,\nrequires a tether\\index{potential!tethered} potential type and the associated interaction parameters.\n\nNote, firstly, that application of tethering\\index{potential!tethered} potentials means that momentum will\nno longer be a conserved quantity of the simulation. Secondly, in constant\npressure simulations, where the MD cell changes size or shape, the reference position\nis scaled with the cell vectors.\n\nThe potential functions available in \\D{} are as\nfollows, in each case $r_{i0}$ is the distance of the atom from its position at $t=0$:\n\\begin{enumerate}\n\\item harmonic potential: ({\\bf harm})\n\\begin{equation}\nU(r_{i0}) = \\frac{1}{2}k(r_{i0})^2;\n\\end{equation}\n\\item restrained harmonic :({\\bf rhrm})\n\\begin{eqnarray}\nU(r_{i0})&=&\\frac{1}{2}k(r_{i0})^2~~~~~~r_{i0}\\le r_{c};\\\\\nU(r_{i0})&=&\\frac{1}{2}kr_{c}^2+kr_{c}(r_{i0}-r_{c})~~~~~~r_{i0}>r_{c};\n\\end{eqnarray}\n\\item Quartic potential: ({\\bf quar})\n\\begin{equation}\nU(r_{i0})=\\frac{k}{2}(r_{i0})^2+\\frac{k'}{3}(r_{i0})^3+\\frac{k''}{4}(r_{i0})^4.\n\\end{equation}\n\\end{enumerate}\n\nThe force on the atom $i$ arising from a tether\\index{potential!tethered} potential is obtained\nusing the general formula:\n\\begin{equation}\n\\vek{f}_{i}=-\\frac{1}{r_{i0}}\\left[\n\\frac{\\partial }{\\partial r_{i0}}U(r_{i0})\\right]\\vek{r}_{i0},\n\\end{equation}\n\nThe contribution to be added to the atomic virial is given by\n\\begin{equation}\n{\\cal W}=\\vek{r}_{i0}\\cdot \\vek{f}_{i},\n\\end{equation}\n\nThe contribution to be added to the atomic stress tensor\\index{stress tensor} is\ngiven by\n\\begin{equation}\n\\sigma^{\\alpha \\beta}=-r_{i0}^{\\alpha}f_{i}^{\\beta},\n\\end{equation}\nwhere $\\alpha$ and $\\beta$ indicate the $x,y,z$ components. The atomic\nstress tensor\\index{stress tensor} derived in this way is symmetric.\n\nIn \\D{} bond\\index{potential!bond} forces are handled by the routine {\\sc tethfrc}.\n\n\\subsection{Frozen Atoms}\n\\D{} also allows atoms to be completely immobilised ({\\em i.e.}\n``frozen'' at a fixed point in the MD cell). This is achieved by\nsetting all forces and velocities associated with that atom to zero\nduring each MD timestep.  Frozen atoms are signalled by assigning an\natom a non-zero value for the freeze parameter in the FIELD file.  \\D{}\ndoes not calculate contributions to the virial or the stress\ntensor\\index{stress tensor}\narising from the constraints required to freeze atomic positions. In\n\\D{} the frozen atom option cannot be used for sites in a rigid\nbody\\index{rigid body}. As with the tethering\\index{potential!tethered} potential, the reference position is scaled with\nthe cell vectors in constant pressure simulations.\n\nIn \\D{} the frozen atom option is handled by the subroutine {\\sc freeze}.\n\n\n\\section{The Intermolecular Potential Functions}\n\\label{intermolecular}\nIn this section we outline the pair-body, three-body\\index{potential!three-body} and four-body\\index{potential!four-body}\npotential functions available in \\D{}. An important distinction between\nthese and intramolecular\\index{potential!intramolecular} (bond) forces in \\D{} is that they are\nspecified by {\\em atom types} rather than atom indices.\n\n\\subsection{Short Ranged (van der Waals) Potentials}\n\\label{vdwpot}\n\nThe short ranged pair forces available in \\D{} are as\nfollows.\n\n\\begin{enumerate}\n\\item 12 - 6 potential: ({\\bf 12-6})\n\\begin{equation}\nU(r_{ij})=\\left(\\frac{A}{r_{ij}^{12}}\\right)-\\left(\\frac{B}{r_{ij}^{6}}\\right);\n\\end{equation}\n\\item Lennard-Jones: ({\\bf lj})\n\\begin{equation}\nU(r_{ij})=4\\epsilon\\left[\\left\n(\\frac{\\sigma}{r_{ij}}\\right)^{12}-\\left(\\frac{\\sigma}{r_{ij}}\\right)^{6}\\right\n];\n\\end{equation}\n\\item n - m potential \\cite{clarke-86a}: ({\\bf nm})\n\\begin{equation}\nU(r_{ij})=\\frac{E_{o}}{(n-m)}\\left[m\\left \n(\\frac{r_{o}}{r_{ij}}\\right)^{n}-n\\left(\\frac{r_{o}}{r_{ij}}\\right)^{m}\\right\n];\n\\end{equation}\n\\item Buckingham potential: ({\\bf buck})\n\\begin{equation}\nU(r_{ij})=A~\\exp\\left(-\\frac{r_{ij}}{\\rho}\\right)-\\frac{C}{r_{ij}^{6}};\n\\end{equation}\n\\item Born-Huggins-Meyer potential: ({\\bf bhm})\n\\begin{equation}\nU(r_{ij})=A~\\exp[B(\\sigma-r_{ij})]-\\frac{C}{r_{ij}^{6}}-\\frac{D}{r_{ij}^{8}};\n\\end{equation}\n\\item Hydrogen-bond (12 - 10) potential: ({\\bf hbnd})\n\\begin{equation}\nU(r_{ij})=\\left(\\frac{A}{r_{ij}^{12}}\\right)-\\left(\\frac{B}{r_{ij}^{10}}\\right);\n\\end{equation}\n\\item Shifted force n - m potential \\cite{clarke-86a}: ({\\bf snm})\n\\begin{eqnarray}\nU(r_{ij})&=&\\frac{\\alpha E_{o}}{(n-m)}\\left [\nm\\beta^{n}\\left \\{ \\left (\\frac{r_{o}}{r_{ij}}\\right )^{n}-\n\\left(\\frac{1}{\\gamma}\\right)^{n}\\right \\}-\nn\\beta^{m}\\left \\{ \\left (\\frac{r_{o}}{r_{ij}}\\right )^{m}-\n\\left(\\frac{1}{\\gamma}\\right)^{m}\\right \\} \\right ]\\nonumber \\\\\n& & +\\frac{nm\\alpha E_{o}}{(n-m)} \\left ( \\frac{r_{ij}-\\gamma r_{o}}{\\gamma r_{o}}\n\\right )\\left\\{\\left(\\frac{\\beta}{\\gamma}\\right\n)^{n}-\\left(\\frac{\\beta}{\\gamma}\\right )^{m}\\right \\}\n\\end{eqnarray}\nwith\n\\begin{eqnarray}\n\\gamma &=&\\frac{r_{cut}}{r_{o}} \\\\\n\\beta &=& \\gamma\\left ( \\frac{\\gamma^{m+1}-1}{\\gamma^{n+1}-1} \\right )\n^{\\frac{1}{n-m}} \\\\\n\\alpha&=&\\frac{(n-m)}{[n\\beta^{m}(1+(m/\\gamma-m-1)/\\gamma^{m})-\nm\\beta^{n}(1+(n/\\gamma-n-1)/\\gamma^{n})]}\n\\end{eqnarray}\nThis peculiar form has the advantage over the standard shifted n-m\npotential in that both $E_{o}$ and $r_{0}$ (well depth and location of\nminimum) retain their original values after the shifting process.\n\\item Morse potential:  ({\\bf mors})\n\\begin{equation}\nU(r_{ij})=E_{o}[\\{1-\\exp(-k(r_{ij}-r_{o}))\\}^{2}-1];\n\\end{equation}\n\\item Shifted Weeks-Chandler-Anderson (WCA) potential \\cite{weeks-71}:  ({\\bf wca})\n\\begin{equation}\nU(r_{ij}) = \\left\\{ \\begin{array} {l@{\\qquad:\\qquad}l}\n4\\epsilon\\left[\\left(\\frac{\\sigma}{r_{ij}-\\Delta}\\right)^{12}-\\left(\\frac{\\sigma}{r_{ij}-\\Delta}\\right)^{6}\\right]\n+\\epsilon & r_{ij} < 2^{1 \\over 6}~\\sigma + \\Delta \\\\\n0 & r_{ij} \\ge 2^{1 \\over 6}~\\sigma + \\Delta \\end{array} \\right. \\label{wca}\n\\end{equation}\nThe WCA potential is the Lennard-Jones potential truncated at the\nposition of the minimum and shifted to eliminate discontinuity\n(includes the effect of excluded volume).  It is usually used in\ncombination with the FENE (\\ref{FENE}) bond potential.  This\nimplementation allows for a radius shift of up to half a $\\sigma$\n($|\\Delta| \\le 0.5~\\sigma$) with a default of zero\n($\\Delta_{default} = 0$).\n\n\\item Gaussian potential ({\\bf gaus})\n\\begin{equation}\nU(r_{ij}) = \\sum_{n}^{3} A_{n}exp(-b_{b}r_{ij}^{2})\n\\end{equation}\nUp to 3 Gaussian terms are permitted, unrequired terms have $A_{n}=0$.\n\n\\item Tabulation: ({\\bf tab}). The potential is defined numerically only.\n\\end{enumerate}\n\nThe parameters defining these potentials are supplied to\n\\D{} at run time (see the description of the FIELD file in section\n\\ref{fieldfile}). Each atom type in the system is specified by a unique\neight-character label defined by the user. The pair potential is then\ndefined internally by the combination of two atom labels.\n\nAs well as the numerical parameters defining the potentials,\n\\D{} must also be provided with a cutoff radius $r_{cut}$,\nwhich sets a ranged limit on the computation of the interaction.\nTogether with the parameters, the cutoff is used by the subroutine\n{\\sc forgen} (or {\\sc forgen\\_rsq}) to construct an interpolation\narray {\\tt vvv} for the potential function over the ranged 0 to\n$r_{cut}$. A second array {\\tt ggg} is also calculated, which is\nrelated to the potential via the formula:\n\\begin{equation}\nG(r_{ij})=-r_{ij}\\frac{\\partial}{\\partial r_{ij}}U(r_{ij}),\n\\end{equation}\nand is used in the calculation of the forces. Both arrays are\ntabulated in units of energy.  The use of interpolation arrays, rather\nthan the explicit formulae, makes the routines for calculating the\npotential energy and atomic forces very general, and\nenables the use of user defined pair potential functions.\n\\D{} also allows the user to read in the interpolation arrays\ndirectly from a file (see the description of the TABLE file (section\n\\ref{tablefile}).  This is particularly useful if the pair potential\nfunction has no simple analytical description (e.g.  spline\npotentials).\n\nThe force on an atom $j$ derived from one of these potentials is\nformally calculated with the standard formula:\n\\begin{equation}\n\\vek{f}_{j}=-\\frac{1}{r_{ij}}\\left[\\frac{\\partial}{\\partial \nr_{ij}}U(r_{ij})\\right]\\vek{r}_{ij},\n\\end{equation}\nwhere $\\vek{r}_{ij}=\\vek{r}_{j}-\\vek{r}_{i}$. The force on atom $i$ is\nthe negative of this.\n\nThe contribution to be added to the atomic virial (for each pair\ninteraction) is\n\\begin{equation}\n{\\cal W}=-\\vek{r}_{ij}\\cdot\\vek{f}_{j}.\n\\end{equation}\n\nThe contribution to be added to the atomic stress tensor\\index{stress tensor} is\ngiven by\n\\begin{equation}\n\\sigma^{\\alpha \\beta}=r_{ij}^{\\alpha}f_{j}^{\\beta},\n\\end{equation}\nwhere $\\alpha$ and $\\beta$ indicate the $x,y,z$ components. The atomic\nstress tensor\\index{stress tensor} derived from the pair forces is symmetric.\n\nSince the calculation of pair potentials assumes a spherical cutoff\n($r_{cut}$) it is necessary to apply a {\\em long ranged\ncorrection}\\index{long ranged corrections!van der Waals} to\nthe system potential energy and virial. Explicit formulae are needed\nfor each case and are derived as follows. For two atom types $a$ and\n$b$, the correction for the potential energy is calculated via the\nintegral\n\\begin{equation}\nU_{corr}^{ab}=2\\pi\n\\frac{N_{a}N_{b}}{V}\\int_{r_{cut}}^{\\infty}g_{ab}(r)U_{ab}(r)r^{2}dr\n\\end{equation}\nwhere $N_{a},N_{b}$ are the numbers of atoms of types $a$ and $b$, $V$\nis the system volume and $g_{ab}(r)$ and $U_{ab}(r)$ are the\nappropriate pair correlation function and pair potential respectively.\nIt is usual to assume $g_{ab}(r)=1$ for $r>r_{cut}$. \\D{}\nsometimes makes the additional assumption that the repulsive part of\nthe short ranged potential is negligible beyond $r_{cut}$. \n\nThe correction for the system virial is\n\\begin{equation}\n{\\cal W}_{corr}^{ab}=-2\\pi\n\\frac{N_{a}N_{b}}{V}\\int_{r_{cut}}^{\\infty}g_{ab}(r)\\frac{\\partial}{\\partial\nr}U_{ab}(r)r^{3}dr,\n\\end{equation}\nwhere the same approximations are applied. Note that these formulae\nare based on the assumption that the system is reasonably isotropic\nbeyond the cutoff.\n\nIn \\D{} the short ranged forces are calculated by one of the\nroutines {\\sc srfrce, srfrce\\_rsq,} and {\\sc srfrceneu}. The long\nranged corrections are calculated by routine {\\sc lrcorrect}. The\ncalculation makes use of the Verlet\\index{algorithm!Verlet} neighbour list described above.\n\n\\subsection{Three Body Potentials}\n\nThe three-body\\index{potential!three-body} potentials in \\D{} are mostly\nvalence angle\\index{potential!valence angle} forms. (They are\nprimarily included to permit simulation of amorphous materials\ne.g. silicate glasses.) However, these have been extended to include\nthe Dreiding\\index{force field!Dreiding} \\cite{mayo-90a} hydrogen\nbond. The potential forms available are as follows.\n\n\\begin{enumerate}\n\\item Harmonic: ({\\bf harm})\n\\begin{equation}\nU(\\theta_{jik})= {k\\over 2} (\\theta_{jik} - \\theta_0)^2\n\\end{equation}\n\\item Truncated harmonic: ({\\bf thrm})\n\\begin{equation}\nU(\\theta_{jik})= {k\\over 2} (\\theta_{jik} - \\theta_0)^2\n\\exp[-(r_{ij}^8 + r_{ik}^8)/\\rho^8];\n\\end{equation}\n\\item Screened Harmonic: ({\\bf shrm})\n\\begin{equation}\n U(\\theta_{jik})= {k\\over 2} (\\theta_{jik} - \\theta_0)^2\n\\exp[-(r_{ij}/\\rho_1 + r_{ik}/\\rho_2)] ;\n\\end{equation}\n\\item Screened Vessal\\cite{vessal-94a}: ({\\bf bvs1})\n\\begin{eqnarray}\nU(\\theta_{jik})&=& {k \\over 8(\\theta_{jik}-\\pi)^2}\\left\\{ \\left[\n(\\theta_0 -\\pi)^2 -(\\theta_{jik}-\\pi)^2\\right]^2\n\\right\\} \\nonumber \\\\\n& & \\exp[-(r_{ij}/\\rho_1 + r_{ik}/\\rho_2)];\n\\end{eqnarray}\n\\item Truncated Vessal\\cite{smith-95a}: ({\\bf bvs2})\n\\begin{eqnarray}\n U(\\theta_{jik})&=& k\\big[ \\theta_{jik}^a (\\theta_{jik}-\\theta_0)^2\n(\\theta_{jik}+\\theta_0-2\\pi)^2  - {a\\over 2} \\pi^{a-1}\\nonumber \\\\\n& & (\\theta_{jik}-\\theta_0)^2(\\pi - \\theta_0)^3\\big]\n\\exp[-(r_{ij}^8 + r_{ik}^8)/\\rho^8].\n\\end{eqnarray}\n\\item Dreiding\\index{force field!Dreiding} hydrogen bond \\cite{mayo-90a}:\n({\\bf hbnd})\n \\begin{equation}\nU(\\theta_{jik})=D_{hb}cos^{4}(\\theta_{jik})[5(R_{hb}/r_{jk})^{12}-6(R_{hb}/r_{jk})^{10}]\n\\end{equation}\n\\end{enumerate}\nNote that for the hydrogen bond\\index{potential!bond}, the hydrogen atom {\\em must} be the\ncentral atom.  Several of these functions are identical to those\nappearing in the {\\em intra-}molecular valence\\index{potential!valence\nangle}angle descriptions\nabove. There are significant differences in implementation however,\narising from the fact that the three-body\\index{potential!three-body} potentials are regarded as\n{\\em inter-}molecular.  Firstly, the atoms involved are defined by\natom types, not specific indices.  Secondly, there are {\\em no}\nexcluded atoms arising from the three body terms\\index{potential!three-body}. (The inclusion of\npair potentials may in fact be essential to maintain the structure of\nthe system.)\n\nThe three body\\index{potential!three-body} potentials are very short\nranged, typically of order 3~$\\AA$. This property, plus the fact that\nthree body\\index{potential!three-body} potentials scale as $N^{3}$,\nwhere $N$ is the number of particles, makes it essential that these\nterms are calculated by the link-cell method \\cite{eastwood-80a}.\n\nThe calculation of the forces, virial and stress tensor\\index{stress tensor} as\ndescribed in the section valence angle\\index{potential!valence angle} potentials above.\n\n\\D{} applies no long ranged corrections to the three body\\index{potential!three-body} potentials.\nThe three body\\index{potential!three-body} forces are calculated by the routine {\\sc thbfrc}.\n\n\\subsection{The Tersoff Covalent Potential}\n\\label{tersoff}\n\nThe Tersoff\\index{potential!Tersoff} potential \\cite{tersoff-89a} is a\nspecial example of a density dependent potential, which has been\ndesigned to reproduce the properties of covalent bonding in systems\ncontaining carbon, silicon, germanium etc and alloys of these\nelements.  \nA special feature of the potential is that it allows bond breaking and\nassociated changes in bond hybridisation.\nThe potential has 11 atomic and 2 bi-atomic parameters.  The energy is\nmodelled as a sum of pair-like interactions where, however, the\ncoefficient of the attractive term in the pairlike potential (which\nplays the role of a bond order) depends on the local environment\ngiving a many-body potential.\n\nThe form of the Tersoff potential is:  ({\\bf ters})\n\\begin{equation}\nU_{ij} = f_{C}(r_{ij})~[f_{R}(r_{ij}) - \\gamma_{ij}~f_{A}(r_{ij})],\n\\end{equation}\nwhere\n\\begin{equation}\nf_{R}(r_{ij}) = A_{ij}~\\exp(- a_{ij}~r_{ij})~,~~\nf_{A}(r_{ij}) = B_{ij}~\\exp(- b_{ij}~r_{ij})\n\\end{equation}\n\\begin{equation}\nf_{C}(r_{ij}) = \\left\\{ \\begin{array} {l@{\\qquad:\\qquad}l}\n1 & r_{ij} < R_{ij} \\\\\n\\frac{1}{2} + \\frac{1}{2} \\cos [\\pi~(r_{ij}-R_{ij})/(S_{ij}-R_{ij})] & R_{ij} < r_{ij} < S_{ij} \\\\\n0 & r_{ij} > S_{ij}\n\\end{array} \\right.\n\\end{equation}\n\\begin{eqnarray}\n\\gamma_{ij} = \\chi_{ij}~(1 + {\\beta_{i}}^{\\eta_{i}}~{\\cal{L}}_{ij}^{\\eta_{i}})^{-1/2\\eta_{i}}~,~~\n{\\cal{L}}_{ij} = \\sum_{k \\neq i,j} f_{C}(r_{ik})~\\omega_{ik}~g(\\theta_{ijk}) \\nonumber \\\\\ng(\\theta_{ijk}) = 1 + c_{i}^2/d_{i}^2 - c_{i}^2/[d_{i}^2 + (h_{i} - \\cos\\theta_{ijk})^2]\n\\end{eqnarray}\nwith further mixed parameters defined as\n\\begin{eqnarray}\na_{ij} = (a_{i} + a_{j})/2&,&~b_{ij} = (b_{i} + b_{j})/2 \\nonumber \\\\\nA_{ij} = (A_{i} A_{j})^{1/2}&,&~B_{ij} = (B_{i} B_{j})^{1/2} \\\\\nR_{ij} = (R_{i} R_{j})^{1/2}&,&~S_{ij} = (S_{i} S_{j})^{1/2}~~.\n\\nonumber\n\\end{eqnarray}\nHere $i,~j$ and $k$ label the atoms in the system, $r_{ij}$ is the\nlength of the $ij$ bond, and $\\theta_{ijk}$ is the bond angle between\nbonds $ij$ and $ik$.  Single subscripted parameters (11), such as\n$a_{i}$ and $\\eta_{i}$, depend only on the type of atom.\n\nThe chemistry between different atom types is encapsulated in the two\nsets of bi-atomic parameters $\\chi_{ij}$ and $\\omega_{ij}$:\n\\begin{eqnarray}\n\\chi_{ii}~=~1&,&~\\chi_{ij}~=~\\chi_{ji} \\nonumber \\\\\n\\omega_{ii}~=~1&,&~\\omega_{ij}~=~\\omega_{ji}~~,\n\\end{eqnarray}\nwhich define only one independent parameter for each pair of atom\ntypes.  The $\\chi$ parameter is used to strengthen or weaken the\nheteropolar bonds, relative to the value obtained by simple\ninterpolation.  The $\\omega$ parameter is used to permit greater\nflexibility when dealing with more drastically different types of\natoms.\n\nThe force on an atom $\\ell$ derived from this potential is\nformally calculated with the formula:\n\\begin{equation}\nf_{\\ell}^{\\alpha} = -\\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}}\nE_{\\tt tersoff} = \\frac{1}{2} \\sum_{i \\neq j}\n-\\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}} U_{ij}~~,\n\\end{equation}\nwith atomic label $\\ell$ being one of $i,j,k$ and $\\alpha$\nindicating the $x,y,z$ component.  The derivative in the above formula\nexpands into\n\\begin{equation}\n-\\frac{\\partial U_{ij}}{\\partial r_{\\ell}^{\\alpha}} =\n-\\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}} f_{C}(r_{ij}) f_{R}(r_{ij}) +\n \\gamma_{ij} \\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}} f_{C}(r_{ij}) f_{A}(r_{ij}) +\n f_{C}(r_{ij}) f_{A}(r_{ij}) \\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}} \\gamma_{ij}~~,\n\\end{equation}\nwith the contributions from the first two terms being:\n\\begin{eqnarray}\n-\\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}} f_{C}(r_{ij}) f_{R}(r_{ij})&=&\n-\\left\\{ f_{C}(r_{ij}) \\frac{\\partial}{\\partial r_{ij}} f_{R}(r_{ij}) +\nf_{R}(r_{ij}) \\frac{\\partial}{\\partial r_{ij}} f_{C}(r_{ij}) \\right\\} \\times \\nonumber \\\\\n& & ~~\\left\\{ \\delta_{j \\ell} \\frac{r_{i \\ell}^{\\alpha}}{r_{i \\ell}} -\n\\delta_{i \\ell} \\frac{r_{\\ell j}^{\\alpha}}{r_{\\ell j}} \\right\\}\n\\end{eqnarray}\n\\begin{eqnarray}\n\\gamma_{ij} \\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}} f_{C}(r_{ij}) f_{A}(r_{ij})&=&\n\\gamma_{ij} \\left\\{ f_{C}(r_{ij}) \\frac{\\partial}{\\partial r_{ij}} f_{A}(r_{ij}) +\nf_{A}(r_{ij}) \\frac{\\partial}{\\partial r_{ij}} f_{C}(r_{ij}) \\right\\} \\times \\nonumber \\\\\n& & ~~~\\left\\{ \\delta_{j \\ell} \\frac{r_{i \\ell}^{\\alpha}}{r_{i \\ell}} -\n\\delta_{i \\ell} \\frac{r_{\\ell j}^{\\alpha}}{r_{\\ell j}} \\right\\}~~,\n\\end{eqnarray}\nand from the third (angular) term:\n\\begin{eqnarray}\nf_{C}(r_{ij}) f_{A}(r_{ij}) \\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}} \\gamma_{ij}&=&\nf_{C}(r_{ij}) f_{A}(r_{ij})~\\chi_{ij}~~\\times ~~~~~~~~~~~~~~~~~~~~~~~~~~ \\nonumber \\\\\n& & \\left( -\\frac{1}{2} \\right) \\left( 1 + {\\beta_{i}}^{\\eta_{i}}~{\\cal{L}}_{ij}^{\\eta_{i}}\n\\right)^{-\\frac{1}{2 \\eta_{i}} - 1} {\\beta_{i}}^{\\eta_{i}}~{\\cal{L}}_{ij}^{\\eta_{i}-1}\n\\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}} {\\cal{L}}_{ij}~~,\n\\end{eqnarray}\nwhere\n\\begin{equation}\n\\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}} {\\cal{L}}_{ij} =\n\\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}} \\sum_{k \\neq i,j}\n\\omega_{ik}~f_{C}(r_{ik})~g(\\theta_{ijk})~~.  \\nonumber\n\\end{equation}\nThe angular term can have three different contributions depending\non the index of the particle participating in the interaction:\n\\begin{eqnarray}\n\\ell~=~i~&:&~\\frac{\\partial}{\\partial r_{i}^{\\alpha}} {\\cal{L}}_{ij} = \\sum_{k \\neq i,j} \\omega_{ik}\n\\left[ g(\\theta_{ijk}) \\frac{\\partial}{\\partial r_{i}^{\\alpha}} f_{C}(r_{ik}) +\nf_{C}(r_{ik}) \\frac{\\partial}{\\partial r_{i}^{\\alpha}} g(\\theta_{ijk}) \\right]~~~~~~\\\\\n\\ell~=~j~&:&~\\frac{\\partial}{\\partial r_{j}^{\\alpha}} {\\cal{L}}_{ij} = \\sum_{k \\neq i,j} \\omega_{ik}\n~f_{C}(r_{ik}) \\frac{\\partial}{\\partial r_{j}^{\\alpha}} g(\\theta_{ijk}) \\\\\n\\ell~\\neq~i,j~&:&~\\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}} {\\cal{L}}_{ij} = \\omega_{i \\ell}\n\\left[ g(\\theta_{ij \\ell}) \\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}} f_{C}(r_{i \\ell}) +\nf_{C}(r_{i \\ell}) \\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}} g(\\theta_{ij \\ell}) \\right]~~.\n\\end{eqnarray}\nThe derivative of $g(\\theta_{ijk})$ is worked out in the following\nmanner:\n\\begin{equation}\n\\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}} g(\\theta_{ijk}) =\n\\frac{\\partial g(\\theta_{ijk})}{\\partial \\theta_{ijk}}~\n\\frac{-1}{\\sin \\theta_{ijk}}~\\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}}\n\\left\\{ \\frac{\\vek{r}_{ij} \\cdot \\vek{r}_{ik}} {r_{ij}~r_{ik}} \\right\\}~~,\n\\end{equation}\nwhere\n\\begin{eqnarray}\n\\frac{\\partial g(\\theta_{ijk})}{\\partial \\theta_{ijk}}&=&\n\\frac{2~c_{i}^2(h_{i} - \\cos \\theta_{ijk})~\\sin \\theta_{ijk}}\n{[d_{i}^2 + (h_{i} - \\cos \\theta_{ijk})^2]^2} \\\\\n\\frac{\\partial}{\\partial r_{\\ell}^{\\alpha}}\n\\left\\{\\frac{\\vek{r}_{ij}\\cdot\\vek{r}_{ik}}{r_{ij}r_{ik}}\\right\\}&=&\n(\\delta_{\\ell j}-\\delta_{\\ell i})\\frac{r_{ik}^{\\alpha}}{r_{ij}r_{ik}} +\n(\\delta_{\\ell k}-\\delta_{\\ell i})\\frac{r_{ij}^{\\alpha}}{r_{ij}r_{ik}} - \\nonumber \\\\\n& & \\cos(\\theta_{jik}) \\left\\{(\\delta_{\\ell j}-\\delta_{\\ell i})\\frac{r_{ij}^{\\alpha}}{r_{ij}^{2}}+\n(\\delta_{\\ell k}-\\delta_{\\ell i})\\frac{r_{ik}^{\\alpha}}{r_{ik}^{2}}\\right\\}~~.\n\\end{eqnarray}\n\nThe contribution to be added to the atomic virial can be derived\nas\n\\begin{eqnarray}\n{\\cal W} &=& 3V \\frac{\\partial E_{\\tt tersoff}}{\\partial V} =\n\\frac{3~V}{2} \\sum_{i \\neq j} \\frac{\\partial U_{ij}}{\\partial V} \\\\\n{\\cal W} &=& \\frac{1}{2} \\sum_{i} \\sum_{j \\neq i} \\left\\{ \\left[\n\\frac{\\partial}{\\partial r_{ij}} f_{C}(r_{ij}) f_{R}(r_{ij}) -\n\\gamma_{ij} \\frac{\\partial}{\\partial r_{ij}} f_{C}(r_{ij}) f_{A}(r_{ij})\n\\right] r_{ij} - \\right.~~~~\\nonumber \\\\\n& & ~~~~\\left( -\\frac{1}{2} \\right) f_{C}(r_{ij}) f_{A}(r_{ij})~\\chi_{ij}\n\\left( 1 + {\\beta_{i}}^{\\eta_{i}}~{\\cal{L}}_{ij}^{\\eta_{i}} \\right)^{-\\frac{1}{2 \\eta_{i}} - 1}\n{\\beta_{i}}^{\\eta_{i}}~{\\cal{L}}_{ij}^{\\eta_{i}-1} \\times \\\\\n& & \\left. ~~~~\\sum_{k \\neq i,j} \\omega_{ik}~g(\\theta_{ijk}) \\left[\n\\frac{\\partial}{\\partial r_{ik}} f_{C}(r_{ik}) \\right] r_{ik}~~ \\right\\}.\n\\nonumber\n\\end{eqnarray}\n\nThe contribution to be added to the atomic stress\ntensor\\index{stress tensor} is given by\n\\begin{equation}\n\\sigma^{\\alpha \\beta} = -r_{i}^{\\alpha} f_{i}^{\\beta}~~,\n\\end{equation}\nwhere $\\alpha$ and $\\beta$ indicate the $x,y,z$ components.  The\nstress tensor\\index{stress tensor} is symmetric.\n\nInterpolation arrays, {\\tt vmbp} and {\\tt gmbp} (set up in subroutine\n{\\sc tergen}) - similar to those in van der Waals\ninteractions \\ref{vdwpot} - are used in the calculation of the Tersoff\nforces, virial and stress.\n\nThe Tersoff\\index{potential!Tersoff} potentials are very short\nranged, typically of order $3$~\\AA.  This property, plus the fact\nthat Tersoff\\index{potential!Tersoff} potentials (two- and\nthree-body contributions) scale as $N^{3}$, where $N$ is the number\nof particles, makes it essential that these terms are calculated by\nthe link-cell method \\cite{eastwood-80a}.\n\n\\D{} applies no long ranged corrections to the\nTersoff\\index{potential!Tersoff} potentials.  In \\D{} Tersoff forces\nare handled by the routines {\\sc tersoff, terint} and {\\sc tersoff3}.\n\n\\subsection{Four Body Potentials}\n\nThe four-body\\index{potential!four-body} potentials in \\D{} are entirely inversion\\index{potential!inversion} angle forms,\nprimarily included to permit simulation of amorphous materials\n(particularly borate glasses). The potential forms available in \\D{} are\nas follows.\n\\begin{enumerate}\n\\item Harmonic: ({\\bf harm})\n\\begin{equation}\nU(\\phi_{ijkn})= {1\\over 2} k (\\phi_{ijkn} - \\phi_0)^2 \n\\end{equation}\n\\item Harmonic cosine: ({\\bf hcos})\n\\begin{equation}\nU(\\phi_{ijkn})={k\\over 2}(cos(\\phi_{ijkn}) -cos(\\phi_{0}))^{2}\n\\end{equation}\n\\item Planar potential: ({\\bf plan})\n\\begin{equation}\nU(\\phi_{ijkn})= A  [ 1 - \\cos (\\phi_{ijkn})] \n\\end{equation}\n\\end{enumerate}\nThese functions are identical to those appearing in the {\\em\nintra-}molecular\\index{potential!intramolecular} inversion angle descriptions above. There are\nsignificant differences in implementation however, arising from the\nfact that the four-body\\index{potential!four-body} potentials are regarded as {\\em\ninter-}molecular.  Firstly, the atoms involved are defined by atom\ntypes, not specific indices.  Secondly, there are {\\em no} excluded\natoms arising from the four-body\\index{potential!four-body} terms. (The inclusion of other\npotentials, for example pair potentials, may in fact be essential to\nmaintain the structure of the system.)\n\nThe four body\\index{potential!four-body} potentials are very short\nranged, typically of order 3~$\\AA$. This property, plus the fact that\nfour body\\index{potential!four-body} potentials scale as $N^{4}$,\nwhere $N$ is the number of particles, makes it essential that these\nterms are calculated by the link-cell method \\cite{eastwood-80a}.\n\nThe calculation of the forces, virial and stress tensor\\index{stress tensor}\ndescribed in the section on inversion angle\\index{potential!inversion} potentials above.\n\n\\D{} applies no long ranged corrections to the four body\\index{potential!four-body} potentials.\nThe four-body\\index{potential!four-body} forces are calculated by the routine {\\sc fbpfrc}.\n\n\\subsection{Metal Potentials}\n\\label{metals}\n\nThe metal potentials in \\D{} follow two similar but distinct formalisms.\nThe first of these is the embedded atom model (EAM)\n\\index{potential!embedded atom (EAM)} \n\\index{embedded atom potential|see{potential,embedded atom (EAM)}}\n\\cite{baskes-84a,baskes-86a} and the second is the Finnis-Sinclair\nmodel (FSM) \\index{potential!Finnis-Sinclair} \n\\index{Finnis-Sinclair potential|see{potential,Finnis-Sinclair}}\n\\cite{finnis-84a}. Both are density dependent potentials\nderived from density functional theory (DFT) and describe the bonding\nof a metal atom ultimately in terms of the local electronic density.\nThey are suitable for calculating the properties of metals\n\\index{potential!metal} and metal alloys.\n\nFor single component metals the two approaches are the same.  {\\bf\nHowever} they are subtly different in the way they are extended to\nhandle alloys (see below). It follows that EAM and FSM potentials\ncannot be mixed in a single simulation. Furthermore, even for FSM\npotentials possessing different analytical forms there is no agreed\nprocedure for mixing the parameters. The user is therefore strongly\nadvised to be consistent in the choice of potential when modelling\nalloys.\n\nThe general form of the EAM and FSM potentials is \\cite{friedel-52a}\n\\begin{equation}\nU_{metal} = {1 \\over 2} \\sum_{i=1}^{N} \\sum_{j \\ne i}^{N} V_{ij}(r_{ij}) +\n\\sum_{i=1}^{N} F(\\rho_{i})~~, \\label{um}\n\\end{equation}\nwhere $F(\\rho_{i})$ is a functional describing the energy of embedding\nan atom in the bulk density, $\\rho_{i}$, which is defined as\n\\begin{equation}\n\\rho_{i} = \\sum_{j=1, j \\ne i}^{N} \\rho_{ij}(r_{ij})~~. \\label{umd}\n\\end{equation}\nIt should be noted that the density is determined by the coordination\nnumber of the atom defined by {\\em pairs} of atoms.  This makes the\nmetal potential dependent on the local density (environmental).\n $V_{ij}(r_{ij})$ is a pair potential incorporating repulsive\nelectrostatic and overlap interactions.  $N$ is the number of\ninteracting particles in the MD box.\n\nThe types of metal potentials available in \\D{} are as follows:\n\\begin{enumerate}\n\\item EAM potential:  ({\\bf eam})\nThere \\index{potential!embedded atom (EAM)}\nare no explicit mathematical expressions for EAM potentials, so\nthis potential type is read exclusively in the form of interpolation\narrays from the TABEAM table file (as implemented in the {\\sc\nmettab} routine - Section \\ref{tabeam-file}.)  The rules\nfor combining the potentials from different metals to handle alloys\nare different from the FSM class of potentials (see below).\n\\item Finnis-Sinclair potential \\cite{finnis-84a}:  ({\\bf fnsc})\nThe Finnis-Sinclair \\index{potential!Finnis-Sinclair}\npotential is explicitly analytical.  It has the \nfollowing form:\n\\begin{eqnarray}\nV_{ij}(r_{ij}) &=& (r_{ij}-c)^{2} (c_{0}+c_{1}r_{ij}+c_{2}r_{ij}^{2}) \\nonumber \\\\\n\\rho_{ij}(r_{ij}) &=& (r_{ij}-d)^{2} + \\beta \\frac{(r_{ij}-d)^{3}}{d} \\\\\nF(\\rho_{i}) &=& -A \\sqrt{\\rho_{i}}~~, \\nonumber\n\\end{eqnarray}\nwith parameters: $c_{0}$, $c_{1}$, $c_{2}$, $c$, $A$, $d$, $\\beta$,\nboth $c$ and $d$ are cutoffs.  Since first being proposed a number of\nalternative analytical forms have been proposed, some of which are\ndescibed below.  The rules for combining different metal potentials to\nmodel alloys are different from the EAM potentials (see below).\n\\item Sutton-Chen potential \\cite{sutton-90a,rafii-tabar-91a,todd-93a}:\n({\\bf stch})\nThe Sutton Chen \\index{potential!Sutton-Chen}\n\\index{Sutton-Chen potential|see{potential,Sutton-Chen}}\npotential is an analytical potential in the FSM\nclass.  It has the form:\n\\begin{eqnarray}\nV_{ij}(r_{ij}) &=& \\epsilon \\left( \\frac{a}{r_{ij}} \\right)^{n} \\nonumber \\\\\n\\rho_{ij}(r_{ij}) &=& \\left( \\frac{a}{r_{ij}} \\right)^{m} \\\\\nF(\\rho_{i}) &=& -c \\epsilon \\sqrt{\\rho_{i}}~~, \\nonumber\n\\end{eqnarray}\nwith parameters: $\\epsilon$, $a$, $n$, $m$, $c$. \n\\item Gupta potential \\cite{cleri-93a}:  ({\\bf gupt})\nThe Gupta potential \\index{potential!Gupta}\n\\index{Gupta potential|see{potential,Gupta}}\nis another analytical potential in the FSM\nclass.  It has the form:\n\\begin{eqnarray}\nV_{ij}(r_{ij}) &=& A \\exp \\left(-p \\frac{r_{ij}-r_{0}}{r_{0}}\\right) \\nonumber \\\\\n\\rho_{ij}(r_{ij}) &=& \\exp \\left(-2 q_{ij} \\frac{r_{ij}-r_{0}}{r_{0}}\\right) \\\\\nF(\\rho_{i}) &=& -B \\sqrt{\\rho_{i}}~~, \\nonumber\n\\end{eqnarray}\nwith parameters: $A$, $r_{0}$, $p$, $B$, $q_{ij}$. {\\bf Note the\ndefinition of $A$ differs from the literature form by a factor of 2, to\ncomply with the general equation (\\ref{um})}.\n\\end{enumerate}\n\nAll of these metal potentials can be decomposed into pair\ncontributions and thus fit within the general tabulation scheme of \\D{},\nwhere they are treated as pair interactions (though note that the\nmetal cutoff, $r_{\\rm met}$ has nothing to do with short ranged cutoff,\n$r_{\\rm vdw}$).  \\D{} calculates this potential in two stages: the first\ncalculates the local density, $\\rho_{i}$, for each atom; and the\nsecond calculates the potential energy and forces.  Interpolation\narrays, {\\tt vmet}, {\\tt gmet} and {\\tt fmet} ({\\sc metgen},\n{\\sc mettab}) are used in both these stages in the same\nspirit as in the van der Waals interaction calculations.\n\nThe total force $\\vek{f}_{k}^{tot}$ on an atom $k$ derived from this\npotential is calculated in the standard way:\n\\begin{equation}\n\\vek{f}_{k}^{tot} = -\\vek{\\nabla}_{k} U_{metal}~~.\n\\end{equation}\nWe rewrite the EAM/FSM potential, (\\ref{um}), as\n\\begin{eqnarray}\nU_{metal} &=& U_{1} + U_{2} \\nonumber \\\\\nU_{1} &=& {1 \\over 2} \\sum_{i=1}^{N} \\sum_{j \\ne i}^{N} V_{ij}(r_{ij}) \\\\\nU_{2} &=& \\sum_{i=1}^{N} F(\\rho_{i})~~, \\nonumber\n\\end{eqnarray}\nwhere $\\vek{r}_{ij} = \\vek{r}_{j}-\\vek{r}_{i}$~.\nThe force on atom $k$ is the sum of the derivatives of $U_{1}$\nand $U_{2}$ with respect to $\\vek{r_{k}}$, which is recognisable as\na sum of pair forces:\n\\begin{enumerate}\n\\item EAM force\n\\begin{eqnarray}\n-\\frac{\\partial U_{1}}{\\partial \\vek{r_{k}}} &=& -{1 \\over 2} \\sum_{i=1}^{N} \\sum_{j \\ne i}^{N}\n\\frac{\\partial V_{ij}(r_{ij})}{\\partial r_{ij}} \\frac{\\partial r_{ij}}{\\partial \\vek{r_{k}}} =\n\\sum_{j=1,j \\ne k}^{N} \\frac{\\partial V_{kj}(r_{kj})}{\\partial r_{kj}} \\frac{\\vek{r_{kj}}}{r_{kj}} \\nonumber \\\\\n-\\frac{\\partial U_{2}}{\\partial \\vek{r_{k}}} &=& -\\sum_{i=1}^{N} \\frac{\\partial F}{\\partial \\rho_{i}}\n\\sum_{j \\ne i}^{N} \\frac{\\partial \\rho_{ij}(r_{ij})}{\\partial r_{ij}} \\frac{\\partial r_{ij}}{\\partial \\vek{r_{k}}} \\\\\n&=& -\\sum_{i=1,i \\ne k}^{N} \\frac{\\partial F}{\\partial \\rho_{i}} \\frac{\\partial \\rho_{ik}(r_{ik})}{\\partial r_{ik}}\n\\frac{\\partial r_{ik}}{\\partial \\vek{r_{k}}} - \\sum_{j=1,j \\ne k}^{N} \\frac{\\partial F}{\\partial \\rho_{k}}\n\\frac{\\partial \\rho_{kj}(r_{kj})}{\\partial r_{kj}} \\frac{\\partial r_{kj}}{\\partial \\vek{r_{k}}} \\nonumber \\\\\n&=& \\sum_{j=1,j \\ne k}^{N} \\left( \\frac{\\partial F}{\\partial \\rho_{k}} + \\frac{\\partial F}{\\partial \\rho_{j}} \\right)\n\\frac{\\partial \\rho_{kj}(r_{kj})}{\\partial r_{kj}} \\frac{\\vek{r_{kj}}}{r_{kj}}~~. \\nonumber\n\\end{eqnarray}\nIn \\D{} the generation of the force arrays from\ntabulated data (implemented in the {\\sc metal\\_deriv}\nroutine) is done using a five point interpolation precedure.\n\n\\item Finnis-Sinclair force\n\\begin{eqnarray}\n-\\frac{\\partial U_{1}}{\\partial \\vek{r_{k}}} &=& \\sum_{j=1,j \\ne k}^{N} \\left\\{\n2 (r_{kj}-c) (c_{0}+c_{1}r_{kj}+c_{2}r_{kj}^{2}) +\n(r_{kj}-c)^{2} (c_{1}+2c_{2}r_{kj}) \\right\\} \\frac{\\vek{r_{kj}}}{r_{kj}} \\nonumber \\\\\n-\\frac{\\partial U_{2}}{\\partial \\vek{r_{k}}} &=& -\\sum_{j=1,j \\ne k}^{N}\n{A \\over 2} \\left( \\frac{1}{\\sqrt{\\rho_{k}}} + \\frac{1}{\\sqrt{\\rho_{j}}} \\right) \n\\left\\{ 2(r_{kj}-d) + 3 \\beta \\frac{(r_{kj}-d)^{2}}{d} \\right\\} \\frac{\\vek{r_{kj}}}{r_{kj}}~~.\n\\end{eqnarray}\n\\item Sutton-Chen force\n\\begin{eqnarray}\n-\\frac{\\partial U_{1}}{\\partial \\vek{r_{k}}} &=& -\\sum_{j=1,j \\ne k}^{N} n \\epsilon\n\\left( \\frac{a}{r_{kj}} \\right)^{n} \\frac{\\vek{r_{kj}}}{r^{2}_{kj}} \\nonumber \\\\\n-\\frac{\\partial U_{2}}{\\partial \\vek{r_{k}}} &=& \\sum_{j=1,j \\ne k}^{N} \\frac{m c \\epsilon}{2}\n\\left( \\frac{1}{\\sqrt{\\rho_{k}}} + \\frac{1}{\\sqrt{\\rho_{j}}} \\right) \n\\left( \\frac{a}{r_{kj}} \\right)^{m} \\frac{\\vek{r_{kj}}}{r^{2}_{kj}}~~.\n\\end{eqnarray}\n\\item Gupta force\n\\begin{eqnarray}\n-\\frac{\\partial U_{1}}{\\partial \\vek{r_{k}}} &=& -\\sum_{j=1,j \\ne k}^{N} \\frac{A p}{r_{0}}\n\\exp \\left( -p \\frac{r_{kj}-r_{0}}{r_{0}} \\right) \\frac{\\vek{r_{kj}}}{r_{kj}} \\nonumber \\\\\n-\\frac{\\partial U_{2}}{\\partial \\vek{r_{k}}} &=& \\sum_{j=1,j \\ne k}^{N} \\frac{B q_{kj}}{r_{0}}\n\\left( \\frac{1}{\\sqrt{\\rho_{k}}} + \\frac{1}{\\sqrt{\\rho_{j}}} \\right) \n\\exp \\left( -2 q_{kj} \\frac{r_{kj}-r_{0}}{r_{0}} \\right) \\frac{\\vek{r_{kj}}}{r_{kj}}~~.\n\\end{eqnarray}\n\\end{enumerate}\n\nWith the metal forces thus defined the contribution to be added to the\natomic virial {\\em from each atom pair} is then\n\\begin{equation}\n{\\cal W} = -\\vek{r}_{ij} \\cdot \\vek{f}_{j}~~,\n\\end{equation}\nwhich equates to:\n\\begin{eqnarray}\n\\Psi &=& 3 V \\frac{\\partial U}{\\partial V} \\nonumber \\\\\n\\Psi &=& {3 \\over 2} V \\sum_{i=1}^{N} \\sum_{j \\ne i}^{N}\n\\frac{\\partial V_{ij}(r_{ij})}{\\partial r_{ij}} \\frac{\\partial r_{ij}}{\\partial V} +\n3 V \\sum_{i=1}^{N} \\frac{\\partial F(\\rho_{i})}{\\partial \\rho_{i}} \\frac{\\partial \\rho_{i}}{\\partial V}\n= \\Psi_{1} + \\Psi_{2} \\nonumber \\\\\n& & \\frac{\\partial r_{ij}}{\\partial V} = \\frac{\\partial V^{1/3}s_{ij}}{\\partial V} =\n{1 \\over 3} V^{-2/3}s_{ij} = \\frac{r_{ij}}{3 V} \\nonumber \\\\\n\\Psi_{1} &=& {1 \\over 2} \\sum_{i=1}^{N} \\sum_{j \\ne i}^{N} \\frac{\\partial V_{ij}(r_{ij})}{\\partial r_{ij}} r_{ij} \\\\\n& & \\frac{\\partial \\rho_{i}}{\\partial V} = \\frac{\\partial }{\\partial V} \\sum_{j=1, j \\ne i}^{N} \\rho_{ij}(r_{ij}) =\n\\sum_{j=1, j \\ne i}^{N} \\frac{\\partial \\rho_{ij}(r_{ij})}{\\partial r_{ij}} \\frac{\\partial r_{ij}}{\\partial V} =\n\\frac{1}{3 V} \\sum_{j=1, j \\ne i}^{N} \\frac{\\partial \\rho_{ij}(r_{ij})}{\\partial r_{ij}} r_{ij} \\nonumber \\\\\n\\Psi_{2} &=& {1 \\over 2} \\sum_{i=1}^{N} \\sum_{j \\ne i}^{N} \\left( \\frac{\\partial F(\\rho_{i})}{\\partial \\rho_{i}} +\n\\frac{\\partial F(\\rho_{j})}{\\partial \\rho_{j}} \\right) \\frac{\\partial \\rho_{ij}(r_{ij})}{\\partial r_{ij}} r_{ij}~~. \\nonumber\n\\end{eqnarray}\n\\begin{enumerate}\n\\item EAM virial \\\\\nThe same as above.\n\\item Finnis-Sinclair virial\n\\begin{eqnarray}\n\\Psi_{1} &=& {1 \\over 2} \\sum_{i=1}^{N} \\sum_{j \\ne i}^{N}\n\\left\\{ 2 (r_{ij}-c) (c_{0}+c_{1}r_{ij}+c_{2}r_{ij}^{2}) +\n(r_{ij}-c)^{2} (c_{1}+2c_{2}r_{ij}) \\right\\} r_{ij} \\nonumber \\\\\n\\Psi_{2} &=& {1 \\over 2} \\sum_{i=1}^{N} \\sum_{j \\ne i}^{N}\n{A \\over 2} \\left( \\frac{1}{\\sqrt{\\rho_{i}}} + \\frac{1}{\\sqrt{\\rho_{j}}} \\right) \n\\left\\{ 2(r_{ij}-d) + 3 \\beta \\frac{(r_{ij}-d)^{2}}{d} \\right\\} r_{ij}a~~.\n\\end{eqnarray}\n\\item Sutton-Chen virial\n\\begin{eqnarray}\n\\Psi_{1} &=& -{1 \\over 2} \\sum_{i=1}^{N} \\sum_{j \\ne i}^{N} n \\epsilon \\left( \\frac{a}{r_{ij}} \\right)^{n} \\nonumber \\\\\n\\Psi_{2} &=& {1 \\over 2} \\sum_{i=1}^{N} \\sum_{j \\ne i}^{N} \\frac{m c\n  \\epsilon}{2} \n\\left( \\frac{1}{\\sqrt{\\rho_{i}}} + \\frac{1}{\\sqrt{\\rho_{j}}} \\right) \n\\left( \\frac{a}{r_{ij}} \\right)^{m}~~.\n\\end{eqnarray}\n\\item Gupta virial\n\\begin{eqnarray}\n\\Psi_{1} &=& -{1 \\over 2} \\sum_{i=1}^{N} \\sum_{j \\ne i}^{N}\n\\frac{A p}{r_{0}} \\exp \\left( -p \\frac{r_{ij}-r_{0}}{r_{0}} \\right) r_{ij} \\nonumber \\\\\n\\Psi_{2} &=& {1 \\over 2} \\sum_{i=1}^{N} \\sum_{j \\ne i}^{N} \\frac{B q_{ij}}{r_{0}}\n\\left( \\frac{1}{\\sqrt{\\rho_{i}}} + \\frac{1}{\\sqrt{\\rho_{j}}} \\right) \n\\exp \\left( -2 q_{ij} \\frac{r_{ij}-r_{0}}{r_{0}} \\right) r_{ij}~~.\n\\end{eqnarray}\n\\end{enumerate}\n\nThe contribution to be added to the atomic stress tensor\\index{stress tensor} is\ngiven by\n\\begin{equation}\n\\sigma^{\\alpha \\beta} = r_{ij}^{\\alpha} f_{j}^{\\beta}~~,\n\\end{equation}\nwhere $\\alpha$ and $\\beta$ indicate the $x,y,z$ components.  The\natomic stress tensor is symmetric.\n\nThe long ranged correction\\index{long ranged corrections!metal}\nfor the \\D{} metal potential is in two parts.  Firstly, by analogy\nwith the short ranged potentials, the correction to the\nlocal density is\n\\begin{eqnarray}\n\\rho_{i} &=& \\sum_{j=1, j \\ne i}^{\\infty} \\rho_{ij}(r_{ij}) \\nonumber \\\\\n\\rho_{i} &=& \\sum_{j=1, j \\ne i}^{r_{ij}<r_{\\rm met}} \\rho_{ij}(r_{ij}) +\n\\sum_{j=1, j \\ne i}^{r_{ij} \\ge r_{\\rm met}} \\rho_{ij}(r_{ij}) =\n\\rho_{i}^{o} + \\delta \\rho_{i} \\\\\n\\delta \\rho_{i} &=& 4 \\pi \\bar{\\rho} \\int_{r_{\\rm met}}^{\\infty} \\rho_{ij}(r) dr~~,\n\\end{eqnarray}\nwhere $\\rho_{i}^{o}$ is the uncorrected local density and\n$\\bar{\\rho}$ is the {\\em mean particle density}.  Evaluating the\nintegral part of the above equation yields:\n\\begin{enumerate}\n\\item EAM density correction \\\\\nNo long ranged corrections apply beyond $r_{\\rm met}$.\n\\item Finnis-Sinclair density correction \\\\\nNo long ranged corrections apply beyond cutoffs $c$ and $d$.\n\\item Sutton-Chen density correction\n\\begin{eqnarray}\n\\delta \\rho_{i} = \\frac{4 \\pi \\bar{\\rho} a^{3}}{(m-3)}\n\\left( \\frac{a}{r_{\\rm met}} \\right)^{m-3}~~.\n\\end{eqnarray}\n\\item Gupta density correction\n\\begin{eqnarray}\n\\delta \\rho_{i} = \\frac{2 \\pi \\bar{\\rho} r_{0}}{q_{ij}}\n\\left[ r_{\\rm met}^{2} + 2 r_{\\rm met} \\left(\\frac{r_{0}}{q_{ij}}\\right) +\n2 \\left(\\frac{r_{0}}{q_{ij}}\\right)^{2} \\right]\n\\exp \\left( -2 q_{ij} \\frac{r_{\\rm met}-r_{0}}{r_{0}}\\right)~~.\n\\end{eqnarray}\n\\end{enumerate}\nThe density correction is applied immediately after the local\ndensity is calculated.  The pair term correction is obtained by\nanalogy with the short ranged potentials and is\n\\begin{eqnarray}\nU_{1} &=& {1 \\over 2} \\sum_{i=1}^{N} \\sum_{j \\ne i}^{\\infty} V_{ij}(r_{ij}) \\nonumber \\\\\nU_{1} &=& {1 \\over 2} \\sum_{i=1}^{N} \\sum_{j \\ne i}^{r_{ij}<r_{\\rm met}} V_{ij}(r_{ij}) +\n{1 \\over 2} \\sum_{i=1}^{N} \\sum_{j \\ne i}^{r_{ij} \\ge r_{\\rm met}} V_{ij}(r_{ij}) =\nU_{1}^{o} + \\delta U_{1} \\nonumber \\\\\n\\delta U_{1} &=& 2 \\pi N \\bar{\\rho} \\int_{r_{\\rm met}}^{\\infty} V_{ij}(r) r^{2} dr \\nonumber \\\\\nU_{2} &=& \\sum_{i=1}^{N} F(\\rho_{i}^{0} + \\delta \\rho_{i}) \\\\\nU_{2} &=& \\sum_{i=1}^{N} F(\\rho_{i}^{0}) +\n\\sum_{i=1}^{N} \\frac{\\partial F(\\rho_{i})_{0}}{\\partial \\rho_{i}} \\delta \\rho_{i}) =\nU_{2}^{0} + \\delta U_{2} \\nonumber \\\\\n\\delta U_{2} &=& 4 \\pi \\bar{\\rho} \\sum_{i=1}^{N} \\frac{\\partial F(\\rho_{i})_{0}}{\\partial \\rho_{i}}\n\\int_{r_{\\rm met}}^{\\infty} \\rho_{ij}(r) r^{2} dr~~. \\nonumber\n\\end{eqnarray}\n{\\bf Note}: that $\\delta U{2}$ is not required if\n$\\rho_{i}$ has already been corrected.  Evaluating the\nintegral part of the above equations yields:\n\\begin{enumerate}\n\\item EAM energy correction \\\\\nNo long ranged corrections apply beyond $r_{\\rm met}$.\n\\item Finnis-Sinclair energy correction \\\\\nNo long ranged corrections apply beyond cutoffs $c$ and $d$.\n\\item Sutton-Chen energy correction\n\\begin{eqnarray}\n\\delta U_{1} &=& \\frac{2 \\pi N \\bar{\\rho} \\epsilon a^{3}}{(n-3)}\n\\left( \\frac{a}{r_{\\rm met}} \\right)^{n-3} \\nonumber \\\\\n\\delta U_{2} &=& -\\frac{4 \\pi \\bar{\\rho} a^{3}}{(m-3)} \\left( \\frac{a}{r_{\\rm met}} \\right)^{n-3}\n\\left< \\frac{N c \\epsilon}{2\\sqrt{\\rho_{i}^{0}}} \\right>~~.\n\\end{eqnarray}\n\\item Gupta energy correction\n\\begin{eqnarray}\n\\delta U_{1} &=& \\frac{2 \\pi N \\bar{\\rho} A r_{0}}{p}\n\\left[ r_{\\rm met}^{2} + 2 r_{\\rm met} \\left(\\frac{r_{0}}{p}\\right) +\n2 \\left(\\frac{r_{0}}{p}\\right)^{2} \\right] \\times \\nonumber \\\\\n& & \\exp \\left( -p \\frac{r_{\\rm met}-r_{0}}{r_{0}}\\right) \\nonumber \\\\\n\\delta U_{2} &=& -\\frac{2 \\pi \\bar{\\rho} r_{0}}{q_{ij}}\n\\left[ r_{\\rm met}^{2} + 2 r_{\\rm met} \\left(\\frac{r_{0}}{q_{ij}}\\right) +\n2 \\left(\\frac{r_{0}}{q_{ij}}\\right)^{2} \\right] \\times \\\\\n& & \\exp \\left( -2 q_{ij} \\frac{r_{\\rm met}-r_{0}}{r_{0}}\\right)\n\\left< \\frac{N B}{2\\sqrt{\\rho_{i}^{0}}} \\right>~~. \\nonumber\n\\end{eqnarray}\n\\end{enumerate}\nTo estimate the virial correction we assume the corrected local\ndensities are constants (i.e. independent of distance - at least\nbeyond the ranged $r_{\\rm met}$).  This allows the virial correction to\nbe computed by the methods used in the short ranged potentials:\n\\begin{eqnarray}\n\\Psi_{1} &=& {1 \\over 2} \\sum_{i=1}^{N} \\sum_{j \\ne i}^{\\infty}\n\\frac{\\partial V_{ij}(r_{ij})}{\\partial r_{ij}} r_{ij} \\nonumber \\\\\n\\Psi_{1} &=& {1 \\over 2} \\sum_{i=1}^{N} \\sum_{j \\ne i}^{r_{ij}<r_{\\rm met}}\n\\frac{\\partial V_{ij}(r_{ij})}{\\partial r_{ij}} r_{ij} +\n{1 \\over 2} \\sum_{i=1}^{N} \\sum_{j \\ne i}^{r_{ij} \\ge r_{\\rm met}}\n\\frac{\\partial V_{ij}(r_{ij})}{\\partial r_{ij}} r_{ij} \\nonumber \\\\\n&=& \\Psi_{1}^{0} + \\delta \\Psi_{1} \\nonumber \\\\\n\\delta \\Psi_{1} &=& 2 \\pi N \\bar{\\rho} \\int_{r_{\\rm met}}^{\\infty}\n\\frac{\\partial V_{ij}(r)}{\\partial r_{ij}} r^{3} dr \\nonumber \\\\\n\\Psi_{2} &=& \\sum_{i=1}^{N} \\frac{\\partial F(\\rho_{i}}{\\partial \\rho_{i}}\n\\sum_{j \\ne i}^{\\infty} \\frac{\\partial \\rho_{ij}(r_{ij})}{\\partial r_{ij}} r_{ij} \\\\\n\\Psi_{2} &=& \\sum_{i=1}^{N} \\frac{\\partial F(\\rho_{i}}{\\partial \\rho_{i}}\n\\sum_{j \\ne i}^{r_{ij}<r_{\\rm met}} \\frac{\\partial \\rho_{ij}(r_{ij})}{\\partial r_{ij}} r_{ij} +\n\\sum_{i=1}^{N} \\frac{\\partial F(\\rho_{i}}{\\partial \\rho_{i}}\n\\sum_{j \\ne i}^{r_{ij} \\ge r_{\\rm met}} \\frac{\\partial \\rho_{ij}(r_{ij})}{\\partial r_{ij}} r_{ij} \\nonumber \\\\\n&=& \\Psi_{2}^{0} + \\delta \\Psi_{2} \\nonumber \\\\\n\\delta \\Psi_{2} &=& 4 \\pi \\bar{\\rho} \\sum_{i=1}^{N} \\frac{\\partial F(\\rho_{i})}{\\partial \\rho_{i}}\n\\int_{r_{\\rm met}}^{\\infty} \\frac{\\partial \\rho_{ij}(r)}{\\partial r} r^{3} dr~~. \\nonumber\n\\end{eqnarray}\nEvaluating the integral part of the above equations yields:\n\\begin{enumerate}\n\\item EAM virial correction \\\\\nNo long ranged corrections apply beyond $r_{\\rm met}$.\n\\item Finnis-Sinclair virial correction \\\\\nNo long ranged corrections apply beyond cutoffs $c$ and $d$.\n\\item Sutton-Chen virial correction\n\\begin{eqnarray}\n\\delta \\Psi_{1} &=& -n \\frac{2 \\pi N \\bar{\\rho} \\epsilon a^{3}}{(n-3)}\n\\left( \\frac{a}{r_{\\rm met}} \\right)^{n-3} \\nonumber \\\\\n\\delta \\Psi_{2} &=& m \\frac{4 \\pi \\bar{\\rho} a^{3}}{(m-3)} \\left( \\frac{a}{r_{\\rm met}} \\right)^{n-3}\n\\left< \\frac{N c \\epsilon}{2\\sqrt{\\rho_{i}^{0}}} \\right>~~.\n\\end{eqnarray}\n\\item Gupta virial correction\n\\begin{eqnarray}\n\\delta \\Psi_{1} &=& -\\frac{p}{r_{0}} \\frac{2 \\pi N \\bar{\\rho} A r_{0}}{p}\n\\left[ r_{\\rm met}^{3} + 3 r_{\\rm met}^{2} \\left(\\frac{r_{0}}{p}\\right) +\n6 r_{\\rm met} \\left(\\frac{r_{0}}{p}\\right)^{2} + 6 \\left(\\frac{r_{0}}{p}\\right)^{3} \\right] \\times \\nonumber \\\\\n& & \\exp \\left( -p \\frac{r_{\\rm met}-r_{0}}{r_{0}}\\right) \\nonumber \\\\\n\\delta \\Psi_{2} &=& \\frac{q_{ij}}{r_{0}} \\frac{2 \\pi \\bar{\\rho} r_{0}}{q_{ij}}\n\\left[ r_{\\rm met}^{3} + 3 r_{\\rm met}^{2} \\left(\\frac{r_{0}}{q_{ij}}\\right) +\n6 r_{\\rm met} \\left(\\frac{r_{0}}{q_{ij}}\\right)^{2} + 6 \\left(\\frac{r_{0}}{q_{ij}}\\right)^{3} \\right] \\times \\\\\n& & \\exp \\left( -2 q_{ij} \\frac{r_{\\rm met}-r_{0}}{r_{0}}\\right)\n\\left< \\frac{N B}{2\\sqrt{\\rho_{i}^{0}}} \\right>~~. \\nonumber\n\\end{eqnarray}\n\\end{enumerate}\n\nIn the energy and virial corrections we have used the approximation:\n\\begin{equation}\n\\sum_{i}^{N}\\rho_{i}^{-1/2} = \\frac{N}{<\\rho_{i}^{1/2}>}~~,\n\\end{equation}\nwhere $<\\rho_{i}^{1/2}>$ is regarded as a constant of the system.\n\nIn \\D{} the metal forces are handled by the routine {\\sc metfrc}.  The\nlocal density is calculated by the routines {\\sc metdens}, {\\sc\neamden} and {\\sc fsden}.  The long ranged corrections are calculated\nby {\\sc lrcmetal}.  Reading and generation of EAM table data from\nTABEAM is handled by {\\sc mettab} and {\\sc metal\\_deriv}.\n\n\\subsubsection*{Notes on the Treatment of Alloys}\n\\label{comment_on_alloys}\nThe distinction to be made between EAM and FSM potentials with regard to\nalloys concerns the mixing rules for unlike interactions.  Starting with\nequations (\\ref{um}) and (\\ref{umd}), it is clear that we require mixing\nrules for terms $V_{ij}(r_{ij})$ and $\\rho_{ij}(r_{ij})$ when atoms $i$\nand $j$ are of different kinds.  Thus two different metals $A$ and $B$ we\ncan distinguish 4 possible variants of each:\n\\[V^{AA}_{ij}(r_{ij}),~V^{BB}_{ij}(r_{ij}),~V^{AB}_{ij}(r_{ij}),\n~V^{BA}_{ij}(r_{ij})\\]\nand\n\\[\\rho^{AA}_{ij}(r_{ij}),~\\rho^{BB}_{ij}(r_{ij}),~\\rho^{AB}_{ij}(r_{ij}),\n~\\rho^{BA}_{ij}(r_{ij}).\\]\nThese forms recognise that the contribution of a type $A$ atom to\nthe potential of a type $B$ atom may be different from the\ncontribution of a type $B$ atom to the potential of a type $A$ atom.\n In both EAM \\cite{johnson-89a} and FSM \\cite{rafii-tabar-91a} cases it\nturns out that\n\\begin{equation}\nV^{AB}_{ij}(r_{ij})=V^{BA}_{ij}(r_{ij})~~,\n\\end{equation}\nthough the mixing rules are different in each case ({\\bf beware!}). \n\nWith regard to density, in the EAM case it is required that \n\\cite{johnson-89a}:\n\\begin{eqnarray}\n\\rho^{AB}_{ij}(r_{ij})=\\rho^{BB}_{ij}(r_{ij}) \\nonumber \\\\\n\\rho^{BA}_{ij}(r_{ij})=\\rho^{AA}_{ij}(r_{ij})~~,\n\\end{eqnarray}\nwhich means that an atom of type $A$ contributes the same density to\nthe environment of an atom of type $B$ as it does to an atom of type\n$A$, and {\\em vice versa}.\n\nFor the FSM case \\cite{rafii-tabar-91a} a different rule applies:\n\\begin{equation}\n\\rho^{AB}_{ij}(r_{ij})=(\\rho^{AA}_{ij}(r_{ij})\\rho^{BB}_{ij}(r_{ij}))^{1/2}\n\\end{equation}\nso that atoms of type $A$ and $B$ contribute the same densities to\neach other, but not to atoms of the same type.\n\nThus when specifying these potentials in the \\D{} FIELD file for\nan alloy composed of $n$ different metal atom types both EAM and FSM\nrequire the specification of $n(n+1)/2$ pair functions\n$V^{AB}_{ij}(r_{ij})$.  However, the EAM requires only $n$ density\nfunctions $\\rho^{AA}_{ij}(r_{ij})$, whereas the FSM class requires all\nthe cross functions $\\rho^{AB}_{ij}(r_{ij})$ or $n(n+1)/2$ in total.\nIn addition to the $n(n+1)/2$ pair functions and $n$ density functions\nthe EAM requires further specification of $n$ functional forms of the\ndensity dependence (i.e. the embedding function $F(\\rho_i)$ in (\\ref{um})).\n\nFor EAM potentials all the functions are supplied in tabular form via\nthe table file TABEAM (see section \\ref{tabeam-file}) to which \\D{} is\nredirected by the FIELD file data.  The FSM potentials are defined via\nthe necessary parameters in the FIELD file.\n\n\n\\subsection{External Fields}\n\nIn addition to the molecular force field, \\D{} allows the use of\nan {\\em external} force field\\index{force field}. Examples of field available include:\n\\begin{enumerate}\n\\item Electric field: ({\\bf elec})\n\\begin{equation} \\vek{F_i} = \\vek{F_i} + q_i. \\vek{H} \\end {equation}\n\\item Oscillating shear: ({\\bf oshm})\n\\begin{equation} \\vek{F}_{x}=A\\cos(2n\\pi.z/L_{z}) \\end{equation}\n\\item Continuous shear: ({\\bf shrx})\n\\begin{equation}\n\\vek{v}_{x}=\\frac{1}{2}A\\frac{|z|}{z}~~~~~~~~~~~~~:|z|>z_{0}\\end{equation}\n\\item Gravitational field: ({\\bf grav})\n\\begin{equation} \\vek{F_i} = \\vek{F_i} + m_i. \\vek{H} \\end {equation}\n\\item Magnetic field: ({\\bf magn})\n\\begin{equation} \\vek{F_i} = \\vek{F_i} + q_i.(\\vek{v_i}\\wedge \\vek{H})\n\\end {equation}\n\\item Containing sphere: ({\\bf sphr})\n\\begin{equation} \\vek{F}=A(R_{0}-r)^{-n}~~~~~~~~~~~~: r>R_{cut} \\end{equation}\n\\item Harmonic repulsive wall in z-direction: ({\\bf zbnd})\n\\begin{equation} \\vek{F}=A(z_{o}-z)~~~~~~~~~~~~: z>z_{o} \\end{equation}\n\\item Harmonic restraint zone in z-direction: ({\\bf zres})\n\\begin{equation}\n\\vek{F}_{z} = \\left\\{ \\begin{array} {l@{\\qquad:\\qquad}l}\nA~(z_{com}-z_{max}) & z_{com} > z_{max} \\\\\nA~(z_{min}-z_{com}) & z_{com} < z_{min}\n\\end{array} \\right.\n\\end{equation}\nwhere $z_{com}$ is the chosen molecule centre of mass.\n\\end{enumerate}\nIt is recommended that the use of an external field should be\naccompanied by a thermostat\\index{thermostat} (this does not apply to\nexamples 6 and 7, since these are conservative fields). The user is\nadvised to be careful with units!\n\nIn \\D{} external field forces\\index{force field} are handled by the routine {\\sc extnfld}.\n\n\\section{Long Ranged Electrostatic (Coulombic) Potentials\\index{potential!electrostatic}}\n\\label{coulomb}\n\n\\D{} incorporates several techniques for dealing with long\nranged electrostatic potentials\\index{potential!electrostatic}\n\\footnote{Unlike the other elements of the force field, the electrostatic \nforces are NOT specified in the input FIELD file, but by setting \nappropriate directives in the CONTROL  file. See section \n\\ref{controlfile}.}. These are as follows. \n\\begin{enumerate}\n\\item Atomistic and charge group implementation.\n\\item Direct Coulomb sum;\n\\item Truncated and shifted Coulomb sum;\n\\item Damped shifted force Coulomb sum;\n\\item Coulomb sum with distance dependent dielectric;\n\\item Ewald sum;\n\\item Smoothed Particle Mesh Ewald (SPME);\n\\item Hautman Klein Ewald for systems with 2D periodicity;\n\\item Reaction field;\n\\item Dynamical shell model;\n\\item Relaxed shell model.\n\\end{enumerate}\nSome of these techniques can be combined. For example 1, 3 and 4 can\nbe used in conjunction with 9. The Ewald sum\\index{Ewald!summation},\nSPME\\index{Ewald!SPME}\\index{SPME|see{Ewald,SPME}} and Hautman Klein\nEwald\\index{Ewald!Hautman Klein}\\index{Hautman Klein Ewald|see{Ewald,\nHautman Klein}}\nare restricted to periodic (or pseudo-periodic) systems only, though \\D{}\ncan handle a broad selection of periodic boundary\nconditions\\index{boundary conditions}, including cubic, orthorhombic,\nparallelepiped, truncated octahedral, hexagonal prism and rhombic\ndodecahedral. The Ewald sum\\index{Ewald!summation} is the method of\nchoice for periodic systems. The other techniques can be used with\neither periodic or non-periodic systems, though in the case of the\ndirect Coulomb sum\\index{direct Coulomb sum}, there are likely to be\nproblems with convergence.\n\n\\D{} will correctly handle the electrostatics of both molecular\nand atomic species. However it is assumed that the system is\nelectrically neutral. A warning message is printed if the system is\nfound to be charged, but otherwise the simulation proceeds as normal.\nNo correction for non-neutrality is applied, except in the case of the \nEwald based methods.\n\n\\subsection{Atomistic and Charge Group Implementation}\n\nThe Ewald sum\\index{Ewald!summation} is an accurate method for summing\nlong ranged\nCoulomb\\index{potential!electrostatic} potentials in periodic\nsystems. This can be a very cpu intensive calculation and the use of\nmore efficient, but less accurate methods, is common. Invariably this\ninvolves truncation of the potential at some finite distance $r_{\\rm\ncut}$. If an atomistic scheme is used for the truncation criterion\nthere is no guarantee that the interaction sphere will be neutral and\nspurious ``charging'' effects will almost certainly be seen in a\nsimulation.  This arises because the potential being truncated is\nlong ranged ($1/r$ for charge-charge interactions). However if the\ncutoff scheme is based on {\\em neutral} groups of atoms, then at\nworst, at long distance the interaction will be a dipole-dipole\ninteraction and vary as $1/r^3$. The truncation effects at the cutoff\nare therefore much less severe than if an atomistic scheme is used. In\n\\D{} the interaction is evaluated between all atoms of both groups if\nany site of the first group is within the cutoff distance of any site\nof the second group.  The groups are known interchangeably as ``charge\ngroups'' or ``neutral groups'' in the documentation - which serves as\na reminder that the advantages of using such a scheme are lost if the\ngroups carry an overall charge. There is no formal requirement in \\D{}\nthat the groups actually be electrically neutral.\n\nThe charge group scheme is more cpu intensive than a simple atomistic\ncutoff scheme as more computation is required to determine whether\nor not to include a set of interactions. However the size of the\nVerlet\\index{algorithm!Verlet} neighbourhood list (easily the largest array in \\D{}) is\nconsiderably smaller with a charge group scheme than an atomistic\nscheme as only a list of interacting groups need be stored as opposed\nto a list of interacting atoms.\n\n\\subsection{Direct Coulomb Sum}\n\nUse of the direct Coulomb sum\\index{direct Coulomb sum} is sometimes necessary for accurate\nsimulation of isolated (nonperiodic) systems. It is {\\em not}\nrecommended for periodic systems.\n\nThe interaction potential for two charged ions is\n\\begin{equation}\nU(r_{ij})=\\frac{1}{4\\pi\\epsilon_{0}}\\frac{q_{i}q_{j}}{r_{ij}}\n\\end{equation}\nwith $q_{\\ell}$ the charge on an atom labelled $\\ell$, and $r_{ij}$\nthe magnitude of the separation vector\n$\\vek{r}_{ij}=\\vek{r}_{j}-\\vek{r}_{i}$.\n\nThe force on an atom $j$ derived from this force is\n\\begin{equation}\n\\vek{f}_{j}=\\frac{1}{4\\pi\\epsilon_{0}}\\frac{q_{i}q_{j}}{r_{ij}^{3}}\\vek{r}_{ij}\n\\end{equation}\nwith the force on atom $i$ the negative of this.\n\nThe contribution to the atomic virial is\n\\begin{equation}\n{\\cal W}=-\\frac{1}{4\\pi\\epsilon_{0}}\\frac{q_{i}q_{j}}{r_{ij}}\n\\end{equation}\nwhich is simply the negative of the potential term.\n\nThe contribution to be added to the atomic stress tensor\\index{stress tensor} is\n\\begin{equation}\n\\sigma^{\\alpha \\beta}=r_{ij}^{\\alpha}f_{j}^{\\beta},\n\\end{equation}\nwhere $\\alpha,\\beta$ are $x,y,z$ components. The atomic stress\\index{stress tensor} tensor\nis symmetric.\n\nIn \\D{} these forces are handled by the routines {\\sc coul0}\nand {\\sc coul0neu}.\n\n\\subsection{Truncated and Shifted Coulomb Sum}\n\nThis form of the Coulomb sum has the advantage that it drastically\nreduces the ranged of electrostatic interactions, without giving rise\nto a violent step in the potential energy at the cutoff. Its main use\nis for preliminary preparation of systems and it is not recommended\nfor realistic models.\\index{direct Coulomb sum!truncated and shifted}\n\nThe form of the potential function is\n\\begin{equation}\nU(r_{ij})=\\frac{q_{i}q_{j}}{4\\pi\\epsilon_{0}}\\left\\{\\frac{1}{r_{ij}}-\n\\frac{1}{r_{cut}}\\right\\}\n\\end{equation}\nwith $q_{\\ell}$ the charge on an atom labelled $\\ell$, $r_{cut}$ the\ncutoff radius and $r_{ij}$ the magnitude of the separation vector\n$\\vek{r}_{ij}=\\vek{r}_{j}-\\vek{r}_{i}$.\n\nThe force on an atom $j$ derived from this potential, within the radius\n$r_{cut}$, is\n\\begin{equation}\n\\vek{f}_{j}=\\frac{1}{4\\pi\\epsilon_{0}}\\frac{q_{i}q_{j}}{r_{ij}^{3}}\\vek{r}_{ij}\n\\end{equation}\nwith the force on atom $i$ the negative of this.\n\nThe contribution to the atomic virial is\n\\begin{equation}\n{\\cal W}=-\\vek{r}_{ij}\\cdot\\vek{f}_{j}\n\\end{equation}\nwhich is {\\em not} the negative of the potential term in this case.\n\nThe contribution to be added to the atomic stress tensor is\ngiven by\n\\begin{equation}\n\\sigma^{\\alpha \\beta}=r_{ij}^{\\alpha}f_{j}^{\\beta},\n\\end{equation}\nwhere $\\alpha,\\beta$ are $x,y,z$ components. The atomic stress tensor\\index{stress tensor}\nis symmetric.\n\nIn \\D{} these forces are handled by the routine {\\sc coul1}.\n\n\\subsection{Damped Shifted Force Coulomb sum}\n\\label{wolf}\nA further refinement of the truncated and shifted Coulomb sum is to\ntruncate the $1/r$ potential at $r_{\\rm cut}$ and add a linear term to\nthe potential in order to make both the energy and the force zero at\nthe cutoff (the shifted force Coulombic potential). This is formally\nequivalent to surrounding each charge with a spherical charge of\nradius $r_{cut}$, which neutralises the charge content of the cutoff\nsphere. The potential is thus\n\n\\begin{equation}\nU(r_{ij}) = {q_i q_j \\over 4\\pi\\epsilon_0} \\left[ {1\\over r_{ij}} + \n{r_{ij}\\over r_{\\rm cut}^2} - {2\\over r_{\\rm cut}} \\right]\n\\end{equation}\nwith  the force on atom $j$ given by\n\\begin{equation}\n\\vek{f}_{j}=\\frac{q_{i}q_{j}}{4\\pi\\epsilon_{0}}\n\\left[ {1\\over r_{ij}^2} - {1\\over r_{\\rm cut}^2} \\right]\n\\frac{\\vek{r}_{ij}}{r_{ij}}\n\\end{equation}\nwith the force on atom $i$ the negative of this.\n\nThis removes the heating effects that arise from the discontinuity\nin the forces at the cutoff in the simple truncated and shifted\npotential. \n\nMore recently Wolf {\\em et al} \\cite{wolf-99a} took the shifted force\nCoulomb potential a step further by the introduction of an additional\n`damping' function to moderate the $1/r_{ij}$ dependence\n\\index{direct Coulomb sum!Wolf method}. This was\nreported to be a viable alternative to the Ewald summation that was\nparticularly effective for large systems.  The basic assumption is\nthat in condensed phase systems the electrostatic forces are\neffectively screened by charge ordering so that at long ranged any\ngiven charge `looks' like a neutral object. Meanwhile the force\nshifting is formally equivalent to surrounding each charge with a\nspherical charge that neutralises the charge content of the cutoff\nsphere, thus resembling the natural screening on a predetermined\ndistance scale ($r_{cut}$). The method thus assumes that these two\neffects are the same.\n\nThe Wolf {\\em et al} method \\cite{wolf-99a} was cast into a form\nsuitable for molecular dynamics by Fennell and Gezelter \\index{direct\nCoulomb sum!Fennel and Gezelter method} \\cite{fennell-06a}, which is\nthe form implemented in \\D{}. In this form damping function is the same\ncomplementary error function as appears in the Ewald sum (see section\n\\ref{ewaldsum}):\n\n\\begin{eqnarray}\nU(r_{ij})&=&\\frac{q_{i}q_{j}}{4\\pi\\epsilon_{0}}\n\\left [\\frac{erfc(\\alpha r_{ij})}{r_{ij}}-\\frac{erfc(\\alpha \n r_{cut})}{r_{cut}}+\n \\left(\\frac{erfc(\\alpha\n r_{cut})}{r_{cut}^{2}}+\\frac{2\\alpha}{\\pi^{1/2}}\n\\frac{exp(-\\alpha^{2}r_{cut}^{2})}{r_{cut}}\\right )(r_{ij}-r_{cut})\n\\right ] \\cdots \\nonumber \\\\\n & & \\cdots \\cdots \\cdots \\cdots \\cdots \\cdots \\cdots \\cdots \\cdots \n\\cdots \\cdots \\cdots \\cdots \\cdots \\cdots \\cdots \\cdots \\cdots \n(r_{ij}\\le r_{cut})\n\\end{eqnarray}\n\nThe corresponding force is given by\n\n\\begin{eqnarray}\n\\vek{f}_{j}&=&\\frac{q_{i}q_{j}}{4\\pi\\epsilon_{0}}\n\\left[\\frac{erfc(\\alpha r_{ij})}{r_{ij}^{2}}+\\frac{2\\alpha}{\\pi^{1/2}}\\frac{exp(-\\alpha^{2} r_{ij}^{2})}{r_{ij}}-\n \\frac{erfc(\\alpha r_{cut})}{r_{cut}^{2}}-\\frac{2\\alpha}{\\pi^{1/2}}\n\\frac{exp(-\\alpha^{2}r_{cut}^{2})}{r_{cut}}\\right ]\\frac{\\vek{r}_{ij}}{r_{ij}}\n \\cdots \\nonumber \\\\\n & & \\cdots \\cdots \\cdots \\cdots \\cdots \\cdots \\cdots \\cdots \\cdots \n\\cdots \\cdots \\cdots \\cdots \\cdots \\cdots \\cdots \\cdots \\cdots \n(r_{ij}\\le r_{cut})\n\\end{eqnarray}\nNote these formulae reduce to the basic shifted force Coulombic\npotential forms when the convergence parameter $\\alpha$ is zero.\n\nThe contribution to the atomic virial is\n\\begin{equation}\n{\\cal W}=-\\vek{r}_{ij}\\cdot\\vek{f}_{j}\n\\end{equation}\nwhich is {\\em not} the negative of the potential term.\n\nThe contribution to be added to the atomic stress tensor\\index{stress tensor} is given by\n\\begin{equation}\n\\sigma^{\\alpha \\beta}=r_{ij}^{\\alpha}f_{j}^{\\beta},\n\\end{equation}\nwhere $\\alpha,\\beta$ are $x,y,z$ components. The atomic stress tensor\nis symmetric.\n\nIn \\D{} these forces are handled by the routine {\\sc coul4}.\n\n\\subsection{Coulomb Sum with Distance Dependent Dielectric}\n\nAs with the previous case, this potential attempts to soften the\nimpact of truncating the direct Coulomb sum\n\\index{direct Coulomb sum!distance dependent dielectric}.\nIt also assumes that the electrostatic forces are effectively\n`screened' in real systems - an effect which is approximated by\nintroducing a dielectic term that increases with distance.\n\nThe interatomic potential for two charged ions is\n\\begin{equation}\nU(r_{ij})=\\frac{1}{4\\pi\\epsilon_{0}\\epsilon(r_{ij})}\\frac{q_{i}q_{j}}{r_{ij}}\n\\end{equation}\nwith $q_{\\ell}$ the charge on an atom labelled $\\ell$, and $r_{ij}$\nthe magnitude of the separation vector\n$\\vek{r}_{ij}=\\vek{r}_{j}-\\vek{r}_{i}$. $\\epsilon(r)$ is the\ndistance dependent dielectric\n\\index{direct Coulomb sum!distance dependent dielectric} \nfunction. In \\D{} it is assumed that this function has the form\n\\begin{equation}\n\\epsilon(r)=\\epsilon r\n\\end{equation}\nwhere $\\epsilon$ is a constant. Inclusion of this term effectively\naccelerates the rate of convergence of the Coulomb sum.\n\nThe force on an atom $j$ derived from this potential is\n\\begin{equation}\n\\vek{f}_{j}=\\frac{1}{2\\pi\\epsilon_{0}\\epsilon}\\frac{q_{i}q_{j}}{r_{ij}^{4}}\\vek{r}_{ij}\n\\end{equation}\nwith the force on atom $i$ the negative of this.\n\nThe contribution to the atomic virial is\n\\begin{equation}\n{\\cal W}=-\\vek{r}_{ij}\\cdot\\vek{f}_{j}\n\\end{equation}\nwhich is $-2$ times the potential term.\n\nThe contribution to be added to the atomic stress tensor\\index{stress tensor} is\ngiven by\n\\begin{equation}\n\\sigma^{\\alpha \\beta}=r_{ij}^{\\alpha}f_{j}^{\\beta},\n\\end{equation}\nwhere $\\alpha,\\beta$ are $x,y,z$ components. The atomic stress tensor\\index{stress tensor}\nis symmetric. \n\nIn \\D{} these forces are handled by the routines {\\sc coul2}\nand {\\sc coul2neu}.\n\nOne last point to note is that the reaction field method can also be\nimplemented with the damped shifted force Coulombic potential\ndescribed above (section \\ref{wolf}), so that polarisation of the long\nranged medium by the dipole of the cutoff sphere may be accounted for.\n\n\\subsection{Ewald Sum}\n\\label{ewaldsum}\n\nThe Ewald sum\\index{Ewald!summation} \\cite{allen-89a} is the best technique for\ncalculating electrostatic interactions in a periodic (or\npseudo-periodic) system.\n\nThe basic model for a neutral periodic system is a system of charged\npoint ions mutually interacting via the Coulomb potential. The Ewald\nmethod makes two amendments to this simple model.  Firstly each ion is\neffectively neutralised (at long range) by the superposition of a\nspherical gaussian\\index{constraints!Gaussian} cloud of opposite charge centred on the ion.  The\ncombined assembly of point ions and gaussian\\index{constraints!Gaussian} charges becomes the {\\em\nReal Space} part of the Ewald sum\\index{Ewald!summation}, which is now short ranged and\ntreatable by the methods described above (section \\ref{fieldintro}).\n\\footnote{Strictly speaking,\nthe real space sum ranges over all periodic images of the simulation\ncell, but in the \\D{} implementation, the parameters are chosen to\nrestrict the sum to the simulation cell and its nearest neighbours\ni.e. the {\\em minimum images} of the cell contents.} The second\nmodification is to superimpose a second set of gaussian charges, this\ntime with the same charges as the original point ions and again\ncentred on the point ions (so nullifying the effect of the first set\nof gaussians). The potential due to these gaussians\\index{constraints!Gaussian} is obtained from\nPoisson's equation and is solved as a Fourier series in {\\em\nReciprocal Space}.  The complete Ewald\\index{Ewald!summation} sum requires an additional\ncorrection, known as the self energy correction, which arises from a\ngaussian\\index{constraints!Gaussian} acting on its own site, and is constant.  Ewald's method\ntherefore replaces a potentially infinite sum in real space by two\nfinite sums: one in real space and one in reciprocal space; and the\nself energy correction.\n\nFor molecular systems, as opposed to systems comprised simply of point\nions, additional modifications are necessary to correct for the\nexcluded (intra-molecular) Coulombic interactions.  In the real space\nsum these are simply omitted. In reciprocal space however, the effects\nof individual gaussian\\index{constraints!Gaussian} charges cannot easily be extracted, and the\ncorrection is made in real space.  It amounts to removing terms\ncorresponding to the potential energy of an ion $\\ell$ due to the\ngaussian\\index{constraints!Gaussian} charge on a neighbouring ion $m$ (or {\\em vice versa}).\nThis correction appears as the third term in the full Ewald\\index{Ewald!summation} formula\nbelow.  The distinction between the error function $erf$ and the more\nusual complementary error function $erfc$ found in the real space sum,\nshould be noted.\n\nThe total electrostatic energy is given by the following formula.\n\\begin{eqnarray}\nU_{c}&=&\\frac{1}{2V_{o}\\epsilon_{0}}\n \\sum_{\\vek{k}\\neq\\vek{0}}^{\\vek{\\infty}}\n\\frac{\\exp(-k^{2}/4\\alpha^{2})}{k^{2}}\n|\\sum_{j}^{N}q_{j}\\exp(-i\\vek{k}\\cdot\\vek{r}_{j})|^{2}+\n\\frac{1}{4\\pi\\epsilon_{0}}\\sum_{n<j}^{N^{*}}\\frac{q_{j}q_{n}}{r_{nj}}\nerfc(\\alpha r_{nj}) \\nonumber\\\\\n& &-\\frac{1}{4\\pi\\epsilon_{0}}\n\\sum_{molecules}\\sum_{\\ell\\le m}^{M^{*}}q_{\\ell}q_{m}\\left\\{\\delta_{\\ell m}\n\\frac{\\alpha}{\\surd \\pi}+\\frac{erf(\\alpha r_{\\ell m})}{r_{\\ell\nm}^{1-\\delta_{\\ell m}}}\\right \\}\n-\\frac{1}{8\\epsilon}\\frac{1}{V_{o}\\alpha^{2}} \\left\n    \\{\\sum_{j}^{N}q_{j}\\right \\}^{2},\n\\end{eqnarray}\nwhere $N$ is the number of ions in the system and $N^{*}$ the same\nnumber discounting any excluded (intramolecular) interactions.\n$M^{*}$ represents the number of excluded atoms in a given molecule\nand includes the atomic self correction. The last term on the right is the\nFuchs correction for charged systems \\cite{fuchs-35a}.\n$V_{o}$ is the simulation cell volume and $\\vek{k}$ is a reciprocal\nlattice vector defined by\n\\begin{equation}\n\\vek{k}=\\ell \\vek{u} + m \\vek{v} + n \\vek{w} \\label{k-vector}\n\\end{equation}\nwhere $\\ell,m,n$ are integers and $\\vek{u},\\vek{v},\\vek{w}$ are the\n{\\em reciprocal space} basis vectors.  Both $V_{o}$ and\n$\\vek{u},\\vek{v},\\vek{w}$ are derived from the vectors\n($\\vek{a},\\vek{b},\\vek{c}$) defining the simulation cell. Thus\n\\begin{equation}\nV_{o}=|\\vek{a}\\cdot\\vek{b}\\times\\vek{c}|\n\\end{equation}\nand\n\\begin{eqnarray}\n\\vek{u}&=&2\\pi\\frac{\\vek{b}\\times\n\\vek{c}}{\\vek{a}\\cdot\\vek{b}\\times\\vek{c}}\n\\nonumber \\\\\n\\vek{v}&=&2\\pi\\frac{\\vek{c}\\times \\vek{a}}{\\vek{a}\\cdot\\vek{b}\\times\\vek{c}}\\\\\n\\vek{w}&=&2\\pi\\frac{\\vek{a}\\times\n\\vek{b}}{\\vek{a}\\cdot\\vek{b}\\times\\vek{c}}.\n\\nonumber \n\\end{eqnarray}\nWith these definitions, the Ewald formula above is applicable to\ngeneral periodic systems. (A small additional modification is necessary\nfor rhombic dodecahedral and truncated octahedral simulation cells\n\\cite{smith-93b}.)\n\nIn practice the convergence of the Ewald sum is controlled by three\nvariables: the real space cutoff $r_{cut}$; the convergence parameter\n$\\alpha$ and the largest reciprocal space vector $\\vek{k}_{max}$ used\nin the reciprocal space sum. These are discussed more fully in section\n\\ref{ewaldoptim}.  \\D{} can provide estimates if requested (see CONTROL\nfile description \\ref{controlfile}.\n\nThe force on an atom $j$ is obtained by differentiation and is\n\\begin{eqnarray}\n\\vek{f}_{j}&=&-\\frac{q_{j}}{V_{o}\\epsilon_{0}}\n \\sum_{\\vek{k}\\neq\\vek{0}}^{\\vek{\\infty}}\ni\\vek{k}\\exp(i\\vek{k}\\cdot\\vek{r}_{j})\\frac{\\exp(-k^{2}/4\\alpha^{2})}{k^{2}}\n\\sum_{n}^{N}q_{n}\\exp(-i\\vek{k}\\cdot\\vek{r}_{n})\\nonumber \\\\\n & &\\phantom{xxxxx} +\\frac{q_{j}}{4\\pi\\epsilon_{0}}\\sum_{n}^{N^{*}}\\frac{q_{n}}{r_{nj}^{3}}\n\\left\\{ erfc(\\alpha r_{nj})+\n\\frac{2\\alpha r_{nj}}{\\surd\\pi}\\exp(-\\alpha^{2}r_{nj}^{2})\\right \\} \\vek{r}_{nj}\\\\\n & &\\phantom{xxxxxxxxxx}\n-\\frac{q_{j}}{4\\pi\\epsilon_{0}}\\sum_{\\ell}^{M^{*}}\\frac{q_{\\ell}}{r_{\\ell j}^{3}}\n\\left\\{ erf(\\alpha r_{\\ell j})-\n\\frac{2\\alpha r_{\\ell j}}{\\surd\\pi}\\exp(-\\alpha^{2}r_{\\ell j}^{2})\\right\n\\}\\vek{r}_{\\ell j}\\nonumber\n\\end{eqnarray}\nThe electrostatic contribution to the system virial can be obtained as\nthe negative of the Coulombic energy. However in \\D{} this\nformal equality can be used as a check on the convergence of the Ewald\nsum\\index{Ewald!summation}. The actual electrostatic virial is obtained during the\ncalculation of the diagonal of the stress tensor\\index{stress tensor}.\n\nThe electrostatic contribution to the stress tensor is given by\n\\begin{eqnarray}\n\\mat{\\sigma}&=&\n\\frac{1}{2V_{o}\\epsilon_{0}}\n\\sum_{\\vek{k}\\neq\\vek{0}}^{\\vek{\\infty}}\n\\left\\{\\mat{1}-2\\left (\\frac{1}{4\\alpha^{2}}+\\frac{1}{k^{2}}\\right\n)\\mat{K}\\right \\}\n\\frac{\\exp(-k^{2}/4\\alpha^{2})}{k^{2}}\n|\\sum_{j}^{N}q_{j}\\exp(-i\\vek{k}\\cdot\\vek{r}_{j})|^{2} \\nonumber \\\\\n & &\\phantom{xxxxx}+\\frac{1}{4\\pi\\epsilon_{0}}\\sum_{j<n}^{N^{*}}\\frac{q_{j}q_{n}}{r_{nj}^{3}}\n\\left\\{ erfc(\\alpha r_{nj})+\n\\frac{2\\alpha r_{nj}}{\\surd\\pi}\\exp(-\\alpha^{2}r_{nj}^{2})\\right \\}\n\\mat{R_{nj}} \\\\\n & &\\phantom{xxxxxxxxxx}\n-\\frac{1}{4\\pi\\epsilon_{0}}\\sum_{j<\\ell}^{M^{*}}\\frac{q_{j}q_{\\ell}}{r_{\\ell j}^{3}}\n\\left\\{ erf(\\alpha r_{\\ell j})-\n\\frac{2\\alpha r_{\\ell j}}{\\surd\\pi}\\exp(-\\alpha^{2}r_{\\ell j}^{2})\\right\n\\}\\mat{R_{\\ell j}},\\nonumber\n\\end{eqnarray}\nwhere matrices $\\mat{K}$ and $\\mat{R_{\\ell j}}$ are defined as follows.\n\\begin{eqnarray}\nK^{\\alpha\\beta}&=&k^{\\alpha}k^{\\beta}\\\\\nR_{\\ell j}^{\\alpha\\beta}&=&r_{\\ell j}^{\\alpha}r_{\\ell j}^{\\beta}\n\\end{eqnarray}\n\nIn \\D{} the full Ewald\\index{Ewald!summation} sum is handled by several\nroutines: {\\sc ewald1} and {\\sc ewald1a} handle the reciprocal space\nterms; {\\sc ewald2, ewald2\\_2pt, ewald2\\_rsq} and {\\sc ewald4,\newald4\\_2pt} handle the real space terms (with the same\nVerlet\\index{Verlet neighbour list} neighbour list routines that are\nused to calculate the short ranged forces); and {\\sc ewald3} calculates\nthe self interaction corrections.  It should be noted that the Ewald\npotential and force interpolation arrays in \\D{} are {\\tt erc} and {\\tt\nfer} respectively.\n\n\\subsection{Smoothed Particle Mesh Ewald}\n\\label{spmesum}\n\nAs its name implies the Smoothed Particle Mesh Ewald (SPME)\n\\index{Ewald!SPME} method is a modification of the standard Ewald\nmethod. \\D{} implements the SPME method of Essmann {\\em et al.}\n\\cite{essmann-95a}. Formally this method is capable of treating van\nder Waals forces also, but in \\D{} it is confined to electrostatic\nforces only. The main difference from the standard Ewald method is in\nits treatment of the the reciprocal space terms. By means of an\ninterpolation procedure involving (complex) B-splines, the sum in\nreciprocal space is represented on a three dimensional rectangular\ngrid. In this form the Fast Fourier Transform (FFT) may be used to\nperform the primary mathematical operation, which is a 3D\nconvolution. The efficiency of these procedures greatly reduces the\ncost of the reciprocal space sum when the range of $\\vek{k}$ vectors\nis large. The method (briefly) is as follows (for full details see\n\\cite{essmann-95a}):\n\n\\begin{enumerate}\n\\item Interpolation of the $exp(-i\\vek{k}\\cdot\\vek{r}_{j})$ terms\n(given here for one dimension):\n\\begin{equation}\nexp(2\\pi i u_{j}k/L) \\approx b(k)\n\\sum_{\\ell=-\\infty}^{\\infty} M_{n}(u_{j}-\\ell) exp(2\\pi i k\\ell/K)\n\\end{equation}\nin which $k$ is the integer index of the $\\vek{k}$ vector in a\nprincipal direction, $K$ is the total number of grid points in the\nsame direction and $u_{j}$ is the fractional coordinate of ion $j$\nscaled by a factor $K$ (i.e. $u_{j}=K s_{j}^{x}$). Note that the\ndefinition of the B-splines implies a dependence on the integer $K$,\nwhich limits the formally infinite sum over $\\ell$.  The coefficients\n$M_{n}(u)$ are B-splines of order $n$ and the factor $b(k)$ is a\nconstant computable from the formula:\n\\begin{equation}\nb(k)=exp(2\\pi i (n-1)k/K)\\left \n[\\sum_{\\ell=0}^{n-2} M_{n}(\\ell+1) exp(2\\pi i k\\ell/K)\\right ]^{-1}\n\\end{equation}\n\\item Approximation of the structure factor $S(\\vek{k})$:\n\\begin{equation}\nS(\\vek{k}) \\approx b_{1}(k_{1}) b_{2}(k_{2}) b_{3}(k_{3})\nQ^{\\dagger}(k_{1},k_{2},k_{3})\n\\end{equation}\nwhere $Q^{\\dagger}(k_{1},k_{2},k_{3})$ is the discrete Fourier transform of\nthe {\\em charge array} $Q(\\ell_{1},\\ell_{2},\\ell_{3})$ defined as\n\\begin{equation}\nQ(\\ell_{1},\\ell_{2},\\ell_{3})=\\sum_{j=1}^{N}q_{j}\\sum_{n_{1},n_{2},n_{3}}\nM_{n}(u_{1j}-\\ell_{1}-n_{1}L_{1})\nM_{n}(u_{2j}-\\ell_{2}-n_{2}L_{2})\nM_{n}(u_{3j}-\\ell_{3}-n_{3}L_{3})\n\\end{equation}\n(in which the sums over $n_{1,2,3}$ etc are required to capture\ncontributions from all relevant periodic cell images, which in\npractice means the nearest images.)\n\\item Approximating the reciprocal space energy $U_{recip}$:\n\\begin{equation}\nU_{recip}=\\frac{1}{2V_{o}\\epsilon_{0}}\\sum_{k_{1},k_{2},k_{3}}\nG^{\\dagger}(k_{1},k_{2},k_{3})Q(k_{1},k_{2},k_{3})\n\\end {equation}\nin which $G^{\\dagger}$ is the discrete Fourier transform of the function\n\\begin{equation}\nG(k_{1},k_{2},k_{3})=\n\\frac{\\exp(-k^{2}/4\\alpha^{2})}{k^{2}}\nB(k_{1},k_{2},k_{3})\n(Q^{\\dagger}(k_{1},k_{2},k_{3}))^{*}\n\\end{equation}\nand where\n\\begin{equation}\nB(k_{1},k_{2},k_{3})=|b_{1}(k_{1})|^{2} |b_{2}(k_{2})|^{2}\n|b_{3}(k_{3})|^{2}\n\\end{equation}\nand $(Q^{\\dagger}(k_{1},k_{2},k_{3}))^{*}$ is the complex conjgate of\n$Q^{\\dagger}(k_{1},k_{2},k_{3})$. The function $G(k_{1},k_{2},k_{3})$ is thus\na relatively simple product of the gaussian screening term appearing\nin the conventional Ewald sum, the function $B(k_{1},k_{2},k_{3})$ and\nthe discrete Fourier transform of $Q(k_{1},k_{2},k_{3})$\n\\item Calculating the atomic forces, which are given formally by:\n\\begin{equation}\nf_{j}^{\\alpha}=-\\frac{\\partial U_{recip}}{\\partial r_{j}^{\\alpha}}\n=-\\frac{1}{V_{o}\\epsilon_{0}}\\sum_{k_{1},k_{2},k_{3}}\nG^{\\dagger}(k_{1},k_{2},k_{3})\n\\frac{\\partial Q(k_{1},k_{2},k_{3})}{\\partial r_{j}^{\\alpha}}\n\\end{equation}\n\\end{enumerate}\nFortunately, due to the recursive properties of the B-splines, these\nformulae are easily evaluated.\n\nThe virial and the stress tensor are calculated in the same manner as\nfor the conventional Ewald sum.\n\nThe \\D{} subroutines required to calculate the SPME contributions are:\\newline\n{\\sc bspgen}, which calculates the B-splines;\n{\\sc bspcoe}, which calculates B-spline coefficients;\n{\\sc spl\\_cexp}, which calculates the FFT and B-spline complex exponentials;\n{\\sc ewald\\_spme}, which calculates the reciprocal space contributions;\n{\\sc spme\\_for}, which calculates the reciprocal space forces; and\n{\\sc dlpfft3}, which calculates the 3D complex fast Fourier transform\n(default code only, Cray, SGI, IBM SP machines have their own FFT\nroutines, selected at compile time and the FFTW public FFT is also an option).\nThese subroutines calculate the reciprocal space components of the\nEwald sum only, the real-space calculations are performed by {\\sc\newald2}, {\\sc ewald3} and {\\sc ewald 4}, as for the normal Ewald sum.\nIn addition there are a few minor utility routines :\n{\\sc cpy\\_rtc} copies a real array to a complex array;\n{\\sc ele\\_prd} is an element-for-element product of two arrays;\n{\\sc scl\\_csum} is a  scalar sum of elements of a complex array; and\n{\\sc set\\_block} initialises an array to a preset value (usually zero).\n\n\\subsection{Hautman Klein Ewald (HKE)\\index{Ewald!Hautman Klein}}\n\nThe method of Hautman and Klein is an adaptation of the Ewald method\nfor systems which are periodic in two dimensions only\n\\cite{hautman-92a}. (\\D{} assumes this periodicity is in the XY plane.)\n\nThe HKE method gives the following formula for the electrostatic\nenergy of a system of $N$ (nonbonded) ions that is overall charge\nneutral\\footnote{The reader is warned that for the purpose of\ncompatibility with other \\D{} Ewald routines we have defined\n$\\alpha=0.5/\\alpha_{HK}$, where $\\alpha_{HK}$ is the $\\alpha$ parameter\ndefined by Hautman and Klein in \\cite{hautman-92a}.}:\n\n\\begin{eqnarray}\nU_{c} &=&\\frac{1}{4\\epsilon_{0}A}\\sum_{n=0}^{n_{max}}a_{n}\\sum_{i,j}^{N} \nq_{i}q_{j}z_{ij}^{2n}\\sum_{\\vek{g}\\ne \\vek{0}} f_{n}(g;\\alpha)\ng^{2n-1}exp(i\\vek{g}\\cdot s_{ij}) + \\nonumber \\\\\n & & \\frac{1}{8\\pi\\epsilon_{0}}\\sum_{i\\ne j}^{N}q_{i}q_{j}\\sum_{\\vek{L}}\n\\left ( \\frac{1}{r_{ij,L}}-\\sum_{n}^{n_{max}} a_{n}z_{ij}^{2n}\n\\frac{h_{n}(s_{ij,L};\\alpha)}{s_{ij,L}^{2n+1}}\\right )+\\nonumber \\\\\n & & \\frac{1}{8\\pi\\epsilon_{0}}\\sum_{i}^{N}q_{i}^{2}\\sum_{\\vek{L}}\n\\frac{(1-h_{0}(L;\\alpha))}{L}-\\frac{\\alpha}{\\epsilon_{0}\\pi^{3/2}}\\sum_{i}^{N}q_{i}^{2} \\label{hke}\n\\end{eqnarray}\nIn this formula $A$ is the system area (in the\nXY plane), $\\vek{L}$ is a 2D lattice vector representing the 2D\nperiodicity of the system, $s_{ij}$ is the in-plane (XY) component of\nthe interparticle distance $r_{ij}$ and $\\vek{g}$ is a reciprocal\nlattice vector. Thus\n\\begin{equation}\n\\vek{L}=\\ell_{1}\\vek{a}+\\ell_{2}\\vek{b},\n\\end{equation}\nwhere $\\ell_{1},\\ell_{2}$ are integers and vectors $\\vek{a}$ and\n$\\vek{b}$ are the lattice basis vectors. The reciprocal lattice vectors are:\n\\begin{equation}\n\\vek{g}=n_{1} \\vek{u} + n_{2} \\vek{v}\n\\end{equation}\nwhere $n_{1},n_{2}$ are integers $\\vek{u},\\vek{v}$ are reciprocal space\nvectors (defined in terms of the vectors $\\vek{a}$ and $\\vek{b}$):\n\\begin{eqnarray}\n\\vek{u}&=&2\\pi(b_{y},-b_{x})^{\\dagger}/(a_{x}b_{y}-a_{y}b_{x}) \\nonumber \\\\\n\\vek{v}&=&2\\pi(-a_{y},a_{x})^{\\dagger}/(a_{x}b_{y}-a_{y}b_{x}).\n\\end{eqnarray}\nThe functions $h_{n}(s;\\alpha)$ and $f_{n}(s;\\alpha)$ are the HKE\nconvergence functions, in real and reciprocal space respectively.\n(C.f. the complementary error and gaussian functions of the original\nEwald method.) However they occur to higher orders here, as indicated\nby the sum over subscript $n$, which corresponds to terms in a Taylor\nexpansion of $r^{-1}$ in $s$, the in-plane distance\n\\cite{hautman-92a}. Usually this sum is truncated at $n_{max}=1$, but\nin \\D{} can go as high as $n_{max}=3$.  In the HKE method the\nconvergence functions are defined as follows:\n\\begin{equation}\nh_{n}(s;\\alpha)/s^{2n+1}=\\frac{1}{a_{n}(2n)!}\\nabla^{2n}(h_{0}(s;\\alpha)/s)\n\\end{equation}\nwith \n\\begin{equation}\nh_{0}(s;\\alpha)=erf(\\alpha s)\n\\end{equation}\nand\n\\begin{equation}\nf_{n}(g;\\alpha)=\\frac{1}{a_{n}(2n)!}f_{0}(g;\\alpha)\n\\end{equation}\nwith\n\\begin{equation}\nf_{0}(g;\\alpha)=erfc(g/2\\alpha).\n\\end{equation}\nIn \\D{} the $h_{n}(s;\\alpha)/s^{2n+1}$ functions are derived by a\nrecursion algorithm, while the $f_{n}(g;\\alpha)$ functions are\nobtained by direct evaluation. The coefficients $a_{n}$ are given by\n\\begin{equation}\na_{n}=(-1)^{n}(2n)!/(2^{2n}(n!)^{2}).\n\\end{equation}\nAs pointed out by Hautman and Klein, the equation (\\ref{hke}) allows\nseparation of the $z_{ij}^{2n}$ components via the binomial expansion,\nwhich greatly simplifies the double sum over atoms\nin reciprocal space. Thus the reciprocal space part of equation\n(\\ref{hke}) becomes\n\\begin{equation}\nU_{recip}=\\frac{1}{4\\epsilon_{0}A}\\sum_{n=0}^{n_{max}} a_{n}\n\\sum_{\\vek{g}\\ne \\vek{0}} f_{n}(g;\\alpha)g^{2n-1}\n\\sum_{p=0}^{2n}(-1)^{p}C_{p}^{2n}Z_{p}(\\vek{g})Z_{2n-p}^{*}(\\vek{g})\n\\end{equation}\nwith $C_{p}^{2n}$ a binomial coefficient and\n\\begin{equation}\nZ_{p}(\\vek{g})=\\sum_{j=1}^{N}q_{j}z_{j}^{p}exp(i\\vek{g}\\cdot\n\\vek{s_{j}})\n\\end{equation}\nThe force on an ion is obtained by the usual differentiation, however\nin this case the z components have different expressions from the x\nand y.\n\\begin{eqnarray}\n-\\frac{\\partial U_{c}}{\\partial u_{j}} &=&\n\\frac{1}{4\\epsilon_{0}A}\\sum_{\\vek{g}\\ne \\vek{0}} \n\\sum_{n=0}^{n_{max}} a_{n}f_{n}(g;\\alpha)g^{2n-1}\n\\sum_{p=0}^{2n}(-1)^{p}C_{p}^{2n}\\left (\nZ_{p}(\\vek{g})\\frac{\\partial Z_{2n-p}^{*}(\\vek{g})}{\\partial u_{j}}+\nZ_{2n-p}^{*}(\\vek{g})\\frac{\\partial Z_{p}(\\vek{g})}{\\partial u_{j}}\n\\right ) \\nonumber \\\\\n & & +\\frac{q_{j}}{4\\pi \\epsilon_{0}}\\sum_{n=0}^{n_{max}}\\sum_{\\vek{L}} \\sum_{ij}^{N}\\,^{\\prime}a_{n}q_{i}\n\\frac{\\partial}{\\partial u_{j}}\\left ( z_{ij,L}^{2n}\n\\frac{h_{n}(s_{ij,L};\\alpha)}{s_{ij,L}^{2n+1}} \\right )\n\\end{eqnarray}\nwhere $u_{j}$ is one of $x_{j},y_{j},z_{j}$ and (noting for brevity\nthat $x$ and $y$ derivatives are similar)\n\\begin{eqnarray}\n\\frac{\\partial Z_{p}(\\vek{g})}{\\partial x_{j}}&=&ig_{x}q_{j}z_{j}^{p}\nexp(i\\vek{g}\\cdot\\vek{s_{j}}) \\nonumber \\\\\n\\frac{\\partial Z_{p}(\\vek{g})}{\\partial z_{j}}&=&pq_{j}z_{j}^{p-1}\nexp(i\\vek{g}\\cdot\\vek{s_{j}})\n\\end{eqnarray}\nand \n\\begin{eqnarray}\n\\frac{\\partial}{\\partial x_{j}}\\left ( z_{ij,L}^{2n} \n\\frac{h_{n}(s_{ij,L};\\alpha)}{s_{ij,L}^{2n+1}} \\right )&=&\ns_{ij,L}^{x}\\frac{z_{ij,L}^{2n} }{s_{ij,L}}\n\\frac{\\partial}{\\partial x_{j}}\\left\n(\\frac{h_{n}(s_{ij,L};\\alpha)}{s_{ij,L}^{2n+1}} \\right ) \n\\nonumber \\\\\n\\frac{\\partial}{\\partial z_{j}}\\left ( z_{ij,L}^{2n} \n\\frac{h_{n}(s_{ij,L};\\alpha)}{s_{ij,L}^{2n+1}} \\right )&=&\n2n z_{ij,L}^{2n-1} \\frac{h_{n}(s_{ij,L};\\alpha)}{s_{ij,L}^{2n+1}}. \n\\end{eqnarray}\nIn \\D{} the partial derivatives of\n$h_{n}(s_{ij,L};\\alpha)/s_{ij,L}^{2n+1}$\nare calculated by a recursion algorithm. Note that when $n=0$ there is\nno derivative w.r.t. $z$.\n\nThe virial and stress tensor terms in real space may be calculated\ndirectly from the pair forces and interatomic distances in the usual\nway, and need not be discussed further.  The calculation of the\nreciprocal space contributions (the terms involving the\n$f_{n}(g;\\alpha)$ functions) are more difficult. Firstly however we\nnote that the reciprocal space contributions to $\\sigma_{xz},\\sigma_{yz}$ and\n$\\sigma_{zz}$ may be obtained directly from the force calculations\nthus:\n\\begin{eqnarray}\n\t\\sigma^{recip}_{xz}&=&\\sum_{j} z_{j}f_{j}^{x} \\nonumber \\\\\n\t\\sigma^{recip}_{yz}&=&\\sum_{j} z_{j}f_{j}^{y} \\\\\n\t\\sigma^{recip}_{zz}&=&\\sum_{j} z_{j}f_{j}^{z} \\nonumber\n\\end{eqnarray}\nwhich renders the calculation of these components trivial. The \nremaining components are calculated from\n\\begin{eqnarray}\n\\sigma^{recip}_{uv}&=&U_{recip}\\delta_{uv}+\\frac{1}{4\\epsilon_{0}A}\n\\sum_{n=0}^{n_{max}} a_{n}\n\\sum_{\\vek{g}\\ne \\vek{0}} g_{u}g_{v}\\frac{g^{2n-2}}{a_{n}(2n)!} \\nonumber \\\\\n & & \\left\n (\\frac{(2n-1)f_{0}(g;\\alpha)}{g}-\\frac{1}{\\alpha\\surd{\\pi}}exp(-g^{2}/4\\alpha^{2})\\right\n )  \\\\\n & & \\sum_{p=0}^{2n}(-1)^{p}C_{p}^{2n}Z_{p}(\\vek{g})Z_{2n-p}^{*}(\\vek{g})\n\\nonumber \n\\end{eqnarray}\nwhere $u,v$ are one or both of the components $x,y$.  Note that,\nalthough it is possible to define these contributions to the stress\ntensor, it is not possible to calculate a pressure from them unless a\nfinite, arbitrary boundary is imposed on the z direction (which is an\nassumption applied in \\D{}, but without implications of periodicity in\nthe z-direction). The $x,y$ components define the surface tension\nhowever.\n\nFor bonded molecules, as with the standard 3D Ewald sum, it is\nnecessary to extract contributions associated with the excluded atom\npairs. In the \\D{} HKE implementation this amounts to an {\\em a\nposteriori} subtraction of the corresponding coulomb terms.\n\nIn \\D{} the HKE method is handled by several subroutines: {\\sc hkgen}\nconstructs the $h_{n}(s;\\alpha)$ convergence functions and their\nderivatives; {\\sc hkewald1} calculates the reciprocal space terms;\n{\\sc hkewald2} and {\\sc hkewald3} calculate the real space terms and\nthe bonded atom corrections respectively. {\\sc hkewald4} calculates\nthe primary interactions in the multiple timestep implementation.\n\n\\subsection{Reaction Field\\index{reaction field}}\n\nIn the reaction field\\index{reaction field} method it is assumed that\nany given molecule is surrounded by a spherical cavity of finite\nradius within which the electrostatic interactions are calculated\nexplicitly. Outside the cavity the system is treated as a\ndielectric\\index{direct Coulomb sum!distance dependent dielectric} \ncontinuum. The occurence of any net dipole within the cavity induces a\npolarisation in the dielectric, which in turn interacts with the given\nmolecule. The model allows the replacement of the infinite Coulomb sum\nby a finite sum plus the reaction field.\n\nThe reaction field model coded into \\D{} is the implementation of\nNeumann based on charge-charge interactions \\cite{neumann-85a}. In\nthis model, the total Coulombic potential is given by\n\\begin{equation}\nU_{c}=\\frac{1}{4\\pi\\epsilon_{0}}\\sum_{j<n}q_{j}q_{n}\n\\left [ \\frac{1}{r_{nj}}+\\frac{B_{0}r_{nj}^{2}}{2 R_{c}^{3}} \\right ]\n\\end{equation}\nwhere the second term on the right is the reaction field correction to\nthe explicit sum, with $R_{c}$ the radius of the cavity.  The constant\n$B_{0}$ is defined as\n\\begin{equation}\nB_{0}=\\frac{2(\\epsilon_{1}-1)}{(2\\epsilon_{1}+1)},\n\\end{equation}\nwith $\\epsilon_{1}$ the dielectric constant outside the cavity.\nThe effective pair potential is therefore\n\\begin{equation}\nU(r_{nj})=\\frac{1}{4\\pi\\epsilon_{0}} q_{j}q_{n}\n\\left [ \\frac{1}{r_{nj}}+\\frac{B_{0}r_{nj}^{2}}{2 R_{c}^{3}} \\right ].\n\\end{equation}\nThis expression unfortunately leads to large fluctuations in the system\nCoulombic energy, due to the large `step' in the function at the\ncavity boundary. In \\D{} this is countered by subtracting the value of\nthe potential at the cavity boundary from each pair contribution.  The\nterm subtracted is\n\\begin{equation}\n\\frac{1}{4\\pi\\epsilon_{0}} \\frac{q_{j}q_{n}}{R_{c}}\n\\left [ 1+\\frac{B_{0}}{2} \\right ].\n\\end{equation}\n\nThe effective pair force on an atom $j$ arising from another atom $n$\nwithin the cavity is given by\n\\begin{equation}\n\\vek{f}_{j}=\\frac{q_{j}q_{n}}{4\\pi\\epsilon_{0}}\\left [\n\\frac{1}{r_{nj}^{3}}-\\frac{B_{0}}{R_{c}^{3}}\\right ]\\vek{r}_{nj}.\n\\end{equation}\n\nThe contribution of each effective pair interaction to the atomic\nvirial is\n\\begin{equation}\n{\\cal W}=-\\vek{r}_{nj}\\cdot \\vek{f}_{j}\n\\end{equation}\nand the contribution to the atomic stress tensor\\index{stress tensor} is\n\\begin{equation}\n\\sigma^{\\alpha \\beta}=r_{nj}^{\\alpha}f_{j}^{\\beta}.\n\\end{equation}\n\nIn \\D{} the reaction field\\index{reaction field} is handled by the routines {\\sc\ncoul3} and {\\sc coul3neu}.\n\n\\subsection{Dynamical Shell Model}\n\nAn atom or ion is polarisable\\index{shell model polarisation} if it develops a dipole moment when\nplaced in an electric field. It is commonly expressed by the equation\n\\begin{equation}\n\\vek{\\mu}=\\alpha \\vek{E},\n\\end{equation}\nwhere $\\vek{\\mu}$ is the induced dipole and $\\vek{E}$ is the electric\nfield. The constant $\\alpha$ is the polarisability. \n\nThe dynamical shell model is a method of incorporating polarisability\ninto a molecular dynamics\\index{shell model polarisation!dynamical shell model} \nsimulation. The method used in \\D{}\nis that devised by Fincham {\\em et al} \\cite{fincham-93a} and is known\nas the adiabatic shell model. \n\nIn the {\\em static} shell model a\npolarisable\\index{shell model polarisation!dynamical shell model} atom is represented by a\nmassive core and massless shell, connected by a harmonic spring,\nhereafter called the core-shell unit. The core and shell carry\ndifferent electric charges, the sum of which equals the charge on the\noriginal atom. There is no electrostatic interaction (i.e. self\ninteraction) between the core and shell of the same atom.\nNon-Coulombic interactions arise from the shell alone.\n\nThe harmonic spring has a potential of the form\n\\begin{equation}\nV_{spring}(r_{ij})=\\frac{1}{2}k r_{ij}^{2}\n\\end{equation}\nSometimes an anharmonic spring is used, which is quartic in form:\n\\begin{equation}\nV_{spring}(r_{ij})=\\frac{1}{2}k r_{ij}^{2}+\\frac{1}{4}k_{4} r_{ij}^{4}.\n\\end{equation}\nNormally $k$ is much larger than $k_{4}$.\n\nThe effect of an electric field is to separate the core and shell, giving rise\nto a {\\em polarisation} dipole. The condition of static equilibrium gives the\npolarisability as:\n\\begin{equation}\n\\alpha=q_{s}^{2}/k\n\\end{equation}\nwhere $q_{s}$ is the shell charge and $k$ is the force constant of the\nharmonic spring.\n\nIn the adiabatic method, a fraction of the atomic mass is assigned to\nthe shell to permit a dynamical description. The fraction of mass is\nchosen to ensure that the natural frequency of vibration $\\nu$ of the\nharmonic spring (i.e.\n\\begin{equation}\n\\nu=\\frac{1}{2\\pi} \\left [ \\frac{k}{x(1-x)m} \\right ]^{1/2},\n\\end{equation}\nwith $m$ the atomic mass,) is well above the frequency of vibration of\nthe whole atom in the bulk system. Dynamically the core-shell unit\nresembles a diatomic molecule with a harmonic\nbond\\index{potential!bond}, however the high vibrational frequency of\nthe bond prevents effective exchange of kinetic energy between the\ncore-shell unit and the remaining system.  Therefore, from an initial\ncondition in which the core-shell units have negligible internal\nvibrational energy, the units will remain close to this condition\nthroughout the simulation. This is essential if the core shell unit is\nto maintain a net polarisation\\index{shell model polarisation}.  (In practice\nthere is a slow leakage of kinetic energy into the core-shell units,\nbut this should should not amount to more than a few percent of the\ntotal kinetic energy.)\n\nThe calculation of the virial and stress tensor\\index{stress tensor} in this model is based on\nthat for a diatomic molecule with charged atoms. The electrostatic and\nshort ranged forces are calculated as described above. The forces of\nthe harmonic springs are calculated as described for intramolecular\nharmonic bonds. The relationship between the kinetic energy and the\ntemperature is different however, as the core-shell unit is permitted\nonly three translational degrees of freedom, and the degrees of\nfreedom corresponding to rotation and vibration of the unit are\ndiscounted (the kinetic energy of these is regarded as zero).\n\nIn \\D{} the shell forces are handled by the routine {\\sc\nshlfrc}. The kinetic energy is calculated by {\\sc corshl} and the\nroutine {\\sc shqnch} performs the temperature scaling. The dynamical\nshell model\\index{shell model polarisation!dynamical shell model} is used in conjunction with the methods for long ranged\nforces described above.\n\\index{force field!DL\\_POLY|)}\n\n\\subsection{Relaxed Shell Model}\n\nThe relaxed shell model \\index{shell model polarisation!relaxed shell model} is\nbased on the same electrostatic principles as the dynamical shell\nmodel\\index{shell model polarisation!dynamical shell model} but in this case the\nshell is assigned a zero mass. This means the shell cannot be driven\ndynamically and instead the procedure is first to relax the shell to a\ncondition of zero (or at least negligible) force at the start of the\nintegration of the atomic motion and then integrate the motion of the\nfinite mass core by conventional molecular dynamics. The relaxation of\nthe shells in \\D{} is accomplished using conjugate\ngradients\\index{minimisation!conjugate gradients}. Since each timestep\nof the algorithm entails a minimisation operation the cost per\ntimestep for this algorithm is considerably more than the adiabatic\nshell model, however the integration timestep permitted is much larger\n(as much as a factor 10) so evolution through phase space is not\nnecessarily very different in cost. A description of the method is\npresented in \\cite{lindan-93a}.\n\n", "meta": {"hexsha": "e1053c1f8b4813e2065b45ac0b6f0425b3042ab4", "size": 131464, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "manual/forfield.tex", "max_stars_repo_name": "zzalscv2/DL_POLY_Classic", "max_stars_repo_head_hexsha": "f2712ca1cdddd154f621f9f5a3c2abac94e41e58", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "manual/forfield.tex", "max_issues_repo_name": "zzalscv2/DL_POLY_Classic", "max_issues_repo_head_hexsha": "f2712ca1cdddd154f621f9f5a3c2abac94e41e58", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "manual/forfield.tex", "max_forks_repo_name": "zzalscv2/DL_POLY_Classic", "max_forks_repo_head_hexsha": "f2712ca1cdddd154f621f9f5a3c2abac94e41e58", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.486562942, "max_line_length": 128, "alphanum_fraction": 0.6979477271, "num_tokens": 45580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.3020066913581039}}
{"text": "\\chapter{Schedule Properties and Argumentation}\n\\label{properties}\n\nSchedule properties such as feasibility are modelled using frameworks to explain the satisfaction of properties. The definitions of efficiency and fixed decision frameworks extend from the definition of the feasibility framework. In this chapter, this extension is interesting because, this can be generalised to reason about arbitrary number of properties, using a extended framework. We apply this generalisation to interval scheduling to illustrate applications of argumentation.\n\\linespace \nWe use stability over other notions of good extensions such as admissibility and completeness to accurately model schedule constraints. This is because we know that existing problems, such as the stable marriage problem can be modelling using stability \\cite{aa}.\n\n\\section{Frameworks}\n\\label{unionframeworks}\n\nIn order to reason about an arbitrary number of properties, we inductively construct the expressible properties over an extendable framework, denoted by $\\pair{Args}{\\rightsquigarrow_0}$. An arbitrary property $P_k$ is modelled by the framework $\\pair{Args}{\\rightsquigarrow_k}$. To be correct, we must preserve that extension $E$ is stable on $\\pair{Args}{\\rightsquigarrow_0\\cup\\rightsquigarrow_k}$ if $E$ is also stable on $\\pair{Args}{\\rightsquigarrow_0}$ and $P(S)$ holds. Let $\\rightsquigarrow,\\rightsquigarrow_1,\\rightsquigarrow_2\\subseteq Args^2$ be arbitrary frameworks.\n\n\\begin{definition}\n\tA framework $\\pair{Args}{\\rightsquigarrow}$ stability-models a schedule property $P$ iff for all extensions $E$ and corresponding schedules $S$, $E$ is stable on $\\pair{Args}{\\rightsquigarrow}$ $\\Leftrightarrow$ $P(S)$\n\\end{definition}\n\n\\begin{definition}\n\tA framework $\\pair{Args}{\\rightsquigarrow}$ conflict-models a schedule property $P$ iff for all extensions $E$ and corresponding schedules $S$, $E$ is conflict-free on $\\pair{Args}{\\rightsquigarrow}$ $\\Leftrightarrow$ $P(S)$\n\\end{definition}\n\nThese definitions are used to make concise proofs.\n\n\\begin{proposition}\n\t$\\rightsquigarrow_F$ stability-models feasibility \\cite{aes}.\n\\end{proposition}\n\n\\begin{proposition}\n\t$\\rightsquigarrow_S$ stability-models feasibility and efficiency \\cite{aes}.\n\\end{proposition}\n\n\\begin{proposition}\n\t$\\rightsquigarrow_D$ stability-models feasibility and satisfaction of fixed decisions \\cite{aes}.\n\\end{proposition}\n\n\\begin{definition}\n\t\\label{conflictmodellable}\n\t\n\tA schedule property $P$ is conflict-modellable iff there exists a framework that conflict-models $P$.\n\\end{definition}\n\n\\begin{definition}\n\t\\label{stablemodellable}\n\t\n\tA schedule property $P$ is stability-modellable iff there exists a framework that stability-models $P$.\n\\end{definition}\n\nDefinitions \\ref{conflictmodellable} and \\ref{stablemodellable} intuitively specifies that a property can be verified using AAFs. In context of schedules, stability-modellable constraints are useful because it shows an application of argumentation. However, a stability-modellable constraint is not equivalent to using any argumentation framework. For example, the constraint $a+b+c+d\\leq 2$ is not stability-modellable because stability does not count the number of conflicting attacks or unattacked arguments. But in value-based argumentation frameworks, it is possible to define an altered form of stability that is sensitive to attack weights. To find an extension in this weighted-stability, this problem can be reduced into a subset sum problem, which cannot be solved in polynomial time.\n\n\\begin{lemma}\n\t\\label{buildconflictfreeness}\n\t$E$ is conflict-free on $\\pair{Args}{\\rightsquigarrow_1}$ and on $\\pair{Args}{\\rightsquigarrow_2}$ iff $E$ is conflict-free on $\\pair{Args}{\\rightsquigarrow_1\\cup\\rightsquigarrow_2}$.\t\n\n\t\\begin{proof}\n\t\tTo prove the forward implication, assume $E$ is conflict-free on $\\pair{Args}{\\rightsquigarrow_1}$ and on $\\pair{Args}{\\rightsquigarrow_2}$. To aim for a contradiction, assume $E$ is not conflict-free on $\\pair{Args}{\\rightsquigarrow_1\\cup\\rightsquigarrow_2}$. Then there exists $e_1,e_2\\in E$ such that $e_1(\\rightsquigarrow_1\\cup\\rightsquigarrow_2)e_2$. Then $e_1\\rightsquigarrow_1 e_2$ or $e_1\\rightsquigarrow_2 e_2$. Both cases lead to a contradiction, so $E$ is conflict-free on $\\pair{Args}{\\rightsquigarrow_1\\cup\\rightsquigarrow_2}$.\n\t\t\\linespace\n\t\tTo prove the backward implication, assume $E$ is conflict-free on $\\pair{Args}{\\rightsquigarrow_1\\cup\\rightsquigarrow_2}$. To aim for a contradiction, assume $E$ is not conflict-free on $\\pair{Args}{\\rightsquigarrow_1}$. Then there exists $e_1,e_2\\in E$ such that $e_1\\rightsquigarrow_1 e_2$. Then $e_1(\\rightsquigarrow_1\\cup\\rightsquigarrow_2)e_2$, which contradicts the most recent assumption. Therefore, $E$ is conflict-free on $\\pair{Args}{\\rightsquigarrow_1}$, and also conflict-free on $\\pair{Args}{\\rightsquigarrow_2}$ by similar argument.\n\t\\end{proof}\n\\end{lemma}\n\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\begin{tikzpicture}\n\t\t\t\\node[node](a) at (0, 2){a};\n\t\t\t\\node[node, shaded](b) at (2, 2){b};\n\t\t\t\\node[node](c) at (2, 0){c};\n\t\t\t\\node[node, shaded](d) at (0, 0){d};\n\t\t\t\\draw[arrow](a) -- (c);\n\t\t\t\\draw[arrow](c) -- (b);\n\t\t\t\\draw[arrow](d) -- (a);\n\t\t\\end{tikzpicture}\\hspace{1cm}\n\t\t\\begin{tikzpicture}\n\t\t\t\\node[node](a) at (0, 2){a};\n\t\t\t\\node[node, shaded](b) at (2, 2){b};\n\t\t\t\\node[node](c) at (2, 0){c};\n\t\t\t\\node[node, shaded](d) at (0, 0){d};\n\t\t\t\\draw[arrow, dashed](b) -- (a);\n\t\t\t\\draw[arrow, dashed](c) -- (b);\n\t\t\t\\draw[arrow, dashed](c) -- (d);\n\t\t\\end{tikzpicture}\\hspace{1cm}\n\t\t\\begin{tikzpicture}\n\t\t\t\\node[node](a) at (0, 2){a};\n\t\t\t\\node[node, shaded](b) at (2, 2){b};\n\t\t\t\\node[node](c) at (2, 0){c};\n\t\t\t\\node[node, shaded](d) at (0, 0){d};\n\t\t\t\\draw[arrow](a) -- (c);\n\t\t\t\\draw[arrow](c) -- (b);\n\t\t\t\\draw[arrow](d) -- (a);\n\t\t\t\\draw[arrow, dashed](b) -- (a);\n\t\t\t\\draw[arrow, dashed](c) -- (b);\n\t\t\t\\draw[arrow, dashed](c) -- (d);\n\t\t\\end{tikzpicture}\n\t\\end{center}\n\t\\caption{Lemma \\ref{buildconflictfreeness} states that given a conflict-free extension over two attack sets on the same arguments, the extension is conflict-free on the merged framework. The figure illustrates this by merging the left and middle frameworks to produce the right framework.}\n\\end{figure}\n\n\\begin{lemma}\n\t\\label{buildstability}\n\tIf $E$ is stable on $\\pair{Args}{\\rightsquigarrow_1}$ and $E$ is conflict-free on $\\pair{Args}{\\rightsquigarrow_2}$, then $E$ is stable on $\\pair{Args}{\\rightsquigarrow_1\\cup\\rightsquigarrow_2}$.\n\t\n\t\\begin{proof}\n\t\tAssume $E$ is stable on $\\rightsquigarrow_1$ and $E$ is conflict-free on $\\rightsquigarrow_2$. By definition of stability, $\\forall a\\in Args\\setminus E\\ \\exists e\\in E\\ e\\rightsquigarrow_1 a$. Then $\\forall a\\in Args\\setminus E\\ \\exists e\\in E\\ e(\\rightsquigarrow_1\\cup\\rightsquigarrow_2)a$. So every argument not in $E$ is attacked by some argument in $E$. $E$ is conflict-free on $\\rightsquigarrow_1$ because $E$ is stable on $\\rightsquigarrow_1$. Since $E$ is conflict-free on $\\rightsquigarrow_1$ and on $\\rightsquigarrow_2$, we use Lemma \\ref{buildconflictfreeness} to show that $E$ is also conflict-free on $(\\rightsquigarrow_1\\cup\\rightsquigarrow_2)$. Therefore $E$ is stable on $\\pair{Args}{\\rightsquigarrow_1\\cup\\rightsquigarrow_2}$.\n\t\\end{proof}\n\\end{lemma}\n\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\begin{tikzpicture}\n\t\t\\node[node](a) at (0, 2){a};\n\t\t\\node[node](b) at (2, 2){b};\n\t\t\\node[node, shaded](c) at (2, 0){c};\n\t\t\\node[node, shaded](d) at (0, 0){d};\n\t\t\\draw[arrow](a) -- (c);\n\t\t\\draw[arrow](c) -- (b);\n\t\t\\draw[arrow](d) -- (a);\n\t\t\\end{tikzpicture}\\hspace{1cm}\n\t\t\\begin{tikzpicture}\n\t\t\\node[node](a) at (0, 2){a};\n\t\t\\node[node](b) at (2, 2){b};\n\t\t\\node[node, shaded](c) at (2, 0){c};\n\t\t\\node[node, shaded](d) at (0, 0){d};\n\t\t\\draw[arrow, dashed](b) -- (a);\n\t\t\\draw[arrow, dashed](b) -- (d);\n\t\t\\end{tikzpicture}\\hspace{1cm}\n\t\t\\begin{tikzpicture}\n\t\t\\node[node](a) at (0, 2){a};\n\t\t\\node[node](b) at (2, 2){b};\n\t\t\\node[node, shaded](c) at (2, 0){c};\n\t\t\\node[node, shaded](d) at (0, 0){d};\n\t\t\\draw[arrow](a) -- (c);\n\t\t\\draw[arrow](c) -- (b);\n\t\t\\draw[arrow](d) -- (a);\n\t\t\\draw[arrow, dashed](b) -- (a);\n\t\t\\draw[arrow, dashed](b) -- (d);\n\t\t\\end{tikzpicture}\n\t\\end{center}\n\t\\caption{Lemma \\ref{buildstability} allows stable extensions of attacks to grow with conflict-free attacks. The left framework is the base framework and the right framework is the extended framework.}\n\\end{figure}\n\n\\begin{lemma}\n\t\\label{reduceconflictfreeness}\n\tIf $E$ is stable on $\\pair{Args}{\\rightsquigarrow_1\\cup\\rightsquigarrow_2}$, then $E$ is conflict-free on $\\pair{Args}{\\rightsquigarrow_1}$.\n\t\n\t\\begin{proof}\n\t\tAssume $E$ is stable on $\\pair{Args}{\\rightsquigarrow_1\\cup\\rightsquigarrow_2}$. By definition of stability, $E$ is conflict-free on $\\pair{Args}{\\rightsquigarrow_1\\cup\\rightsquigarrow_2}$.  By Lemma \\ref{buildconflictfreeness}, $E$ is conflict-free on $\\pair{Args}{\\rightsquigarrow_1}$.\n\t\\end{proof}\n\\end{lemma}\n\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\begin{tikzpicture}\n\t\t\t\\node[node](a) at (0, 2){a};\n\t\t\t\\node[node](b) at (2, 2){b};\n\t\t\t\\node[node, shaded](c) at (2, 0){c};\n\t\t\t\\node[node, shaded](d) at (0, 0){d};\n\t\t\t\\draw[arrow](a) -- (c);\n\t\t\t\\draw[arrow](b) -- (a);\n\t\t\t\\draw[arrow](c) -- (b);\n\t\t\t\\draw[arrow](d) -- (a);\n\t\t\\end{tikzpicture}\\hspace{3cm}\n\t\t\\begin{tikzpicture}\n\t\t\t\\node[node](a) at (0, 2){a};\n\t\t\t\\node[node](b) at (2, 2){b};\n\t\t\t\\node[node, shaded](c) at (2, 0){c};\n\t\t\t\\node[node, shaded](d) at (0, 0){d};\n\t\t\t\\draw[arrow](a) -- (c);\n\t\t\t\\draw[arrow](c) -- (b);\n\t\t\\end{tikzpicture}\n\t\\end{center}\n\t\\caption{Lemma \\ref{reduceconflictfreeness} states that given a stable extension, removing attacks preserves the extension's conflict-freeness, as shown from left to right.}\n\\end{figure}\n\n\\begin{lemma}\n\t\\label{reducestability}\n\tIf $E$ is stable on $\\pair{Args}{\\rightsquigarrow_1\\cup\\rightsquigarrow_2}$ and $\\forall a\\in Args\\setminus E\\ (\\exists e\\in E\\ e\\rightsquigarrow_2 a)\\implies(\\exists e\\in E\\ e\\rightsquigarrow_1 a)$, then $E$ is stable on $\\pair{Args}{\\rightsquigarrow_1}$.\n\t\n\t\\begin{proof}\n\t\t\\begin{flalign*}\n\t\t\t&E\\text{ is stable on }\\pair{Args}{\\rightsquigarrow_1\\cup\\rightsquigarrow_2}&\\\\\n\t\t\t&\\land\\forall a\\in Args\\setminus E\\ (\\exists e\\in E\\ e\\rightsquigarrow_2 a)\\implies(\\exists e\\in E\\ e\\rightsquigarrow_1 a)\\\\\n\t\t\t\\implies&E\\text{ is conflict-free on }\\pair{Args}{\\rightsquigarrow_1\\cup\\rightsquigarrow_2}\\\\\n\t\t\t&\\land\\forall a\\in Args\\setminus E\\ \\exists e\\in E\\ e(\\rightsquigarrow_1\\cup\\rightsquigarrow_2)\\\\\n\t\t\t&\\land\\forall a\\in Args\\setminus E\\ (\\exists e\\in E\\ e\\rightsquigarrow_2 a)\\implies(\\exists e\\in E\\ e\\rightsquigarrow_1 a)\\\\\n\t\t\t&\\textit{definition of stability}\\\\\n\t\t\t\\implies&E\\text{ is conflict-free on }\\pair{Args}{\\rightsquigarrow_1}\\\\\n\t\t\t&\\land\\forall a\\in Args\\setminus E\\ \\exists e\\in E\\ (e\\rightsquigarrow_1 a\\lor e\\rightsquigarrow_2 a)\\\\\n\t\t\t&\\land\\forall a\\in Args\\setminus E\\ (\\exists e\\in E\\ e\\rightsquigarrow_2 a)\\implies(\\exists e\\in E\\ e\\rightsquigarrow_1 a)\\\\\n\t\t\t&\\textit{definition of $\\cup$}\\\\\n\t\t\t\\implies&E\\text{ is conflict-free on }\\pair{Args}{\\rightsquigarrow_1}\\\\\n\t\t\t&\\land\\forall a\\in Args\\setminus E\\ ((\\exists e\\in E\\ e\\rightsquigarrow_1 a)\\lor(\\exists e\\in E\\ e\\rightsquigarrow_2 a))\\\\\n\t\t\t&\\land\\forall a\\in Args\\setminus E\\ (\\exists e\\in E\\ e\\rightsquigarrow_2 a)\\implies(\\exists e\\in E\\ e\\rightsquigarrow_1 a)\\\\\n\t\t\t&\\textit{distribute $\\lor$ over $\\exists$}\\\\\n\t\t\t\\implies&E\\text{ is conflict-free on }\\pair{Args}{\\rightsquigarrow_1}\\\\\n\t\t\t&\\land\\forall a\\in Args\\setminus E\\ ((\\exists e\\in E\\ e\\rightsquigarrow_1 a)\\lor(\\exists e\\in E\\ e\\rightsquigarrow_1 a))\\\\\n\t\t\t&\\textit{substitute $\\rightsquigarrow_2$ to $\\rightsquigarrow_1$}\\\\\n\t\t\t\\implies&E\\text{ is conflict-free on }\\pair{Args}{\\rightsquigarrow_1}\\\\\n\t\t\t&\\textit{idempotency of $\\lor$}\\\\\n\t\t\t&\\land\\forall a\\in Args\\setminus E\\ \\exists e\\in E\\ e\\rightsquigarrow_1 a\\\\\n\t\t\t\\implies&E\\text{ is stable on }\\pair{Args}{\\rightsquigarrow_1}\\\\\n\t\t\t&\\textit{definition of stability}\n\t\t\\end{flalign*}\n\t\\end{proof}\n\\end{lemma}\n\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\begin{tikzpicture}\n\t\t\\node[node](a) at (0, 2){a};\n\t\t\\node[node](b) at (2, 2){b};\n\t\t\\node[node, shaded](c) at (2, 0){c};\n\t\t\\node[node, shaded](d) at (0, 0){d};\n\t\t\\draw[arrow, dashed](c) -- (a);\n\t\t\\draw[arrow](c) -- (b);\n\t\t\\draw[arrow](d) -- (a);\n\t\t\\draw[arrow, dashed](d) -- (b);\n\t\t\\end{tikzpicture}\\hspace{3cm}\n\t\t\\begin{tikzpicture}\n\t\t\\node[node](a) at (0, 2){a};\n\t\t\\node[node](b) at (2, 2){b};\n\t\t\\node[node, shaded](c) at (2, 0){c};\n\t\t\\node[node, shaded](d) at (0, 0){d};\n\t\t\\draw[arrow](c) -- (b);\n\t\t\\draw[arrow](d) -- (a);\n\t\t\\end{tikzpicture}\n\t\\end{center}\n\t\\caption{Lemma \\ref{reducestability} states that given a stable extension, removing attacks on multi-attacked arguments preserves the extension's stability, as shown from left to right.}\n\\end{figure}\n\n\\begin{theorem}[\\textbf{Union of modelling frameworks}]\n\t\\label{modelling}\n\tLet $P_0,...,P_K$ be schedule properties with $K$ properties. Let $P_{\\intset{i,j}}$ be an aggregate schedule property where for all schedules $S$, $P_{\\intset{i, j}}(S)\\iff\\forall k\\in\\intset{i,j}\\ P_k(S)$.\n\t\\linespace\n\tIf $\\rightsquigarrow_0$ stability-models $P_0$, and $\\forall k\\in\\intset{1,K}\\ \\rightsquigarrow_k$ conflict-models $P_k$, and for all extensions $E$, $\\forall a\\in Args\\setminus E\\ \\forall k\\in\\intset{1,K}\\ \\big((\\exists e\\in E\\ e\\rightsquigarrow_k a)\\implies(\\exists e\\in E\\ e\\rightsquigarrow_0 a)\\big)$, then $\\left(\\bigcup_{k=0}^K\\rightsquigarrow_k\\right)$ stability-models $P_{\\intset{0,K}}$.\n\t\n\t\\begin{proof}\n\t\tTake arbitrary $K\\in\\mathbb{N}$. To prove forward implication:\n\t\t\\begin{enumerate}\n\t\t\t\\item$\\rightsquigarrow_0$ stability-models $P_0$\\hfill given\n\t\t\t\\item$\\forall k\\in\\intset{1,K}\\ \\rightsquigarrow_k$ conflict-models $P_k$\\hfill given\n\t\t\t\\item$\\forall a\\in Args\\setminus E\\ \\forall k\\in\\intset{1,K}\\ \\big((\\exists e\\in E\\ e\\rightsquigarrow_k a)\\implies(\\exists e\\in E\\ e\\rightsquigarrow_0 a)\\big)$\\\\\\null\\hfill given\n\t\t\t\\item$E$ is stable on $\\pair{Args}{\\bigcup_{k=0}^K\\rightsquigarrow_k}$\\hfill assumption\n\t\t\t\\item$\\forall a\\in Arg\\setminus E\\ \\left(\\left(\\exists e\\in E\\ e\\left(\\bigcup_{k=0}^K\\rightsquigarrow_k\\right) a\\right)\\implies(\\exists e\\in E\\ e\\rightsquigarrow_0 a)\\right)$\\\\\\null\\hfill 3\n\t\t\t\\item$E$ is stable on $\\pair{Args}{\\rightsquigarrow_0}$\\hfill lemma \\ref{reducestability}, 4, 5\n\t\t\t\\item$P_0(S)$\\hfill 1, 6\n\t\t\t\\item Take arbitrary $k\\in\\intset{1,K}$\n\t\t\t\\begin{level}\n\t\t\t\t\\item$E$ is conflict-free on $\\pair{Args}{\\rightsquigarrow_k}$\\hfill lemma \\ref{reduceconflictfreeness}, 4\n\t\t\t\t\\item$P_k$(S)\\hfill 2, 9\n\t\t\t\\end{level}\n\t\t\t\\item$\\forall k\\in\\intset{1,K}\\ P_k(S)$\\hfill 8, 10\n\t\t\t\\item$P_{\\intset{0,K}}(S)$ \\hfill 7, 11\n\t\t\\end{enumerate}\n\t\n\t\tTo prove backward implication:\n\t\t\\begin{enumerate}\n\t\t\t\\item$\\rightsquigarrow_0$ stability-models $P_0$\\hfill given\n\t\t\t\\item$\\forall k\\in\\intset{1,K}\\ \\rightsquigarrow_k$ conflict-models $P_k$\\hfill given\n\t\t\t\\item$P_{\\intset{0,K}}(S)$\\hfill assumption\n\t\t\t\\item$P_0(S)$\\hfill 3\n\t\t\t\\item$E$ is stable on $\\pair{Args}{\\rightsquigarrow_0}$\\hfill 1, 4\n\t\t\t\\item Recursively over $k\\in\\intset{1,K}$\n\t\t\t\\begin{level}\n\t\t\t\t\\item $P_k(S)$\\hfill 3\n\t\t\t\t\\item $E$ is conflict-free on $\\pair{Arg}{\\rightsquigarrow_k}$\\hfill 2, 7\n\t\t\t\t\\item $E$ is stable on $\\pair{Arg}{\\bigcup_{k'=0}^k\\rightsquigarrow_{k'}}$\\hfill lemma \\ref{buildstability}, 5, 8\n\t\t\t\\end{level}\n\t\t\t\\item $E$ is stable on $\\pair{Arg}{\\bigcup_{k=0}^K\\rightsquigarrow_k}$\\hfill 6, 9\n\t\t\\end{enumerate}\n\t\\end{proof}\n\\end{theorem}\n\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\begin{tikzpicture}\n\t\t\t\\node[node, shaded](a) at (0, 1.5){a};\n\t\t\t\\node[node](b) at (1.5, 1.5){b};\n\t\t\t\\node[node, shaded](c) at (1.5, 0){c};\n\t\t\t\\node[node](d) at (0, 0){d};\n\t\t\t\\draw[arrow](a) -- (b);\n\t\t\t\\draw[arrow](b) -- (a);\n\t\t\t\\draw[arrow](c) -- (d);\n\t\t\t\\draw[arrow](d) -- (c);\n\t\t\t\\draw(-0.5,-0.5) rectangle (2,2);\n\t\t\t\\node at (0.8, -0.8){stability-models $P_0$};\n\t\t\\end{tikzpicture}\\raisebox{1.4cm}{\\huge{$\\land$}}\n\t\t\\begin{tikzpicture}\n\t\t\t\\node[node, shaded](a) at (0, 1.5){a};\n\t\t\t\\node[node](b) at (1.5, 1.5){b};\n\t\t\t\\node[node, shaded](c) at (1.5, 0){c};\n\t\t\t\\node[node](d) at (0, 0){d};\n\t\t\t\\draw[arrow](b) -- (c);\n\t\t\t\\draw(-0.5,-0.5) rectangle (2,2);\n\t\t\t\\node at (0.8, -0.8){conflict-models $P_1$};\n\t\t\\end{tikzpicture}\\raisebox{1.4cm}{\\huge{$\\land$ ... $\\land$}}\n\t\t\\begin{tikzpicture}\n\t\t\t\\node[node, shaded](a) at (0, 1.5){a};\n\t\t\t\\node[node](b) at (1.5, 1.5){b};\n\t\t\t\\node[node, shaded](c) at (1.5, 0){c};\n\t\t\t\\node[node](d) at (0, 0){d};\n\t\t\t\\draw[arrow](b) -- (d);\n\t\t\t\\draw(-0.5,-0.5) rectangle (2,2);\n\t\t\t\\node at (0.8, -0.8){conflict-models $P_K$};\n\t\t\\end{tikzpicture}\\linespace\n\t\t{\\huge{$\\Updownarrow$}}\n\t\t\\linespace\n\t\t\\begin{tikzpicture}\n\t\t\t\\node[node, shaded](a) at (0, 2){a};\n\t\t\t\\node[node](b) at (2, 2){b};\n\t\t\t\\node[node, shaded](c) at (2, 0){c};\n\t\t\t\\node[node](d) at (0, 0){d};\n\t\t\t\\draw[arrow](a) -- (b);\n\t\t\t\\draw[arrow](b) -- (a);\n\t\t\t\\draw[arrow](b) -- (c);\n\t\t\t\\draw[arrow](b) -- (d);\n\t\t\t\\draw[arrow](c) -- (d);\n\t\t\t\\draw[arrow](d) -- (c);\n\t\t\t\\draw(-0.5,-0.5) rectangle (2.5, 2.5);\n\t\t\t\\node at (1, -0.8){stability-models $P_{\\intset{0,K}}$};\n\t\t\\end{tikzpicture}\n\t\t\\vspace{-\\baselineskip}\n\t\\end{center}\n\t\\caption{Theorem \\ref{modelling} allows manipulation of an aggregate property, $P_{\\intset{0,K}}$ from carefully extending frameworks, while preserving stability. This theorem is a key statement in framing argumentation semantics for arbitrary scheduling problems.}\n\\end{figure}\n\nTheorem \\ref{modelling} cannot be applied to $\\rightsquigarrow_S$ or $\\rightsquigarrow_D$ because they remove attacks from the $\\rightsquigarrow_F$. The theorem does not capture removal of attacks from a commonly-extendable framework because there is ambiguity between the order of removal and insertion of attacks. Formally, $(\\rightsquigarrow\\cup \\rightsquigarrow^+)\\setminus \\rightsquigarrow^-\\neq (\\rightsquigarrow\\setminus\\rightsquigarrow^-)\\cup\\rightsquigarrow^+$ for arbitrary frameworks $\\rightsquigarrow,\\rightsquigarrow^-,\\rightsquigarrow^+$.\n\n\\section{Interval Scheduling}\n\\label{interval}\n\nMakespan schedules are extended to discrete time-indexed interval scheduling. We will show an application of Theorem \\ref{modelling} to interval scheduling. Let $T$ be the exclusive upper-bound of indexed time where $\\mathcal{T}=\\{0,...,T-1\\}$. The assignment matrix $\\mathbf{x}\\in\\mathcal{M}\\times\\mathcal{J}\\times\\mathcal{T}$ is extended such that $x_{i,j,t}=1$ iff job $j$ is starts work on machine $i$ at time $t$. Each machine job pair $\\pair{i}{j}$ has a start time $s_{i,j}\\in\\mathcal{T}^{mn}$ and finish time $f_{i,j}\\in\\{0,...,T\\}^{mn}$, where $j$ must be completed within the $[s_{i,j},f_{i,j})$ interval. The objective is to minimise the total completion time.\n\n\\begin{align*}\n\t\\min_{\\mathbf{x}}\\ &C_{\\max}\\text{ subject to:}\\\\\n\t\\forall i\\in\\mathcal{M}\\ \\forall j\\in\\mathcal{J}\\ \\forall t\\in\\mathcal{T}\\ &C_{\\max}\\geq x_{i,j,t}(t+p_j)\\\\\n\t\\forall j\\in\\mathcal{J}\\ &\\sum_{i\\in\\mathcal{M}}\\sum_{t\\in\\mathcal{T}}x_{i,j,t}=1&\\alpha\\\\\n\t\\forall i\\in\\mathcal{M}\\ \\forall t\\in\\mathcal{T}\\ &\\sum_{j\\in\\mathcal{J}}\\sum_{t'=\\max\\{t-p_j+1,0\\}}^t x_{i,j,t'}\\leq 1&\\beta\\\\\n\t\\forall i\\in\\mathcal{M}\\ \\forall j\\in\\mathcal{J}\\ \\forall t\\in\\{0,...,s_{i,j}-1\\}\\ &x_{i,j,t}=0&\\gamma\\\\\n\t\\forall i\\in\\mathcal{M}\\ \\forall j\\in\\mathcal{J}\\ \\forall t\\in\\{f_{i,j}-p_j+1,...,T-1\\}\\ &x_{i,j,t}=0&\\delta\\\\\n\t\\forall\\triple{i}{j}{t}\\in D^-\\ &x_{i,j,t}=0&\\varepsilon\\\\\n\t\\forall\\triple{i'}{j}{t'}\\in D^+\\ \\forall i\\in\\mathcal{M}\\setminus\\{i'\\}\\ \\forall t\\in\\mathcal{T}\\ &x_{i,j,t}=0&\\zeta\\\\\n\t\\forall\\triple{i}{j}{t'}\\in D^+\\ \\forall t\\in\\mathcal{T}\\ &&\\\\\n\tt\\leq t'-p_j\\lor t\\geq t'+p_j\\implies&x_{i,j,t}=0&\\eta\\\\\n\\end{align*}\n\n$\\alpha$ models feasibility, that all jobs must be allocated. $\\beta$ models that machines cannot process multiple jobs at the same time. $\\gamma$ and $\\delta$ models the restriction of start and end times respectively. $\\varepsilon$ and $\\zeta$ models negative and positive fixed decisions respectively. Equivalently, $\\zeta$ can be modelled by $\\forall\\triple{i}{j}{t'}\\in D^+\\ \\exists t\\in\\mathcal{T}\\ x_{i,j,t}=1$. $\\zeta$ is defined as such to simplify the proof that the union of these properties is modellable. $\\eta$ models enforces that $j$ is working on $i$ at $t$, but does not specify the when $j$ starts. Note that $\\gamma,\\delta,\\zeta$ and $\\eta$ can be modelled using $\\varepsilon$. We use more constants to give better explanations, because each constraint have different explanations. For argumentation, let $Args=\\mathcal{M}\\times\\mathcal{J}\\times\\mathcal{T}$.\n\n\\begin{figure}[H]\n\t\\begin{center}\n\t\t\\includegraphics[width=.8\\linewidth]{figures/interval.png}\t\n\t\\end{center}\n\t\\caption{An interval schedule, where black areas are assignments and the grey areas show invalid slots because of negative fixed decisions or other job assignees.}\n\\end{figure}\n\n\\begin{definition}\n\t\\label{intervalalpha}\n\t\n\tLet $\\rightsquigarrow_\\alpha$ be the base-feasibility framework such that $\\triple{i}{j}{t}\\rightsquigarrow_\\alpha\\triple{i'}{j'}{t'}\\Leftrightarrow i\\neq i'\\land j=j'\\land t\\neq t'$ \n\\end{definition}\n\n$\\rightsquigarrow_\\alpha$ can be interpreted as an generalisation of $\\rightsquigarrow_F$ with time.\n\n\\begin{lemma}\n\t\\label{stabilityalpha}\n\t$\\rightsquigarrow_\\alpha$ stability-models $\\alpha$.\n\t\n\t\\begin{proof}\n\t\tTo prove forward implication: $E$ is stable on $\\pair{Args}{\\rightsquigarrow_\\alpha}$. Take arbitrary $j\\in\\mathcal{J}$. To aim to contradict, assume $\\sum_{i\\in\\mathcal{M}}\\sum_{t\\in\\mathcal{T}}x_{i,j,t}>1$. Then $\\exists\\triple{i}{j}{t},\\triple{i'}{j}{t'}\\in E$ where $x_{i,j,t}=1$ and $x_{i',j,t'}=1$ such that $i\\neq i'$ or $t\\neq t'$. By definition of $\\rightsquigarrow_\\alpha$, $\\triple{i}{j}{t}\\rightsquigarrow_\\alpha\\triple{i'}{j}{t'}$. Hence $E$ is not conflict-free, then $E$ is not stable. By contradiction, $\\sum_{i\\in\\mathcal{M}}\\sum_{t\\in\\mathcal{T}}x_{i,j,t}\\leq 1$. To aim to contradict, assume $\\sum_{i\\in\\mathcal{M}}\\sum_{t\\in\\mathcal{T}}x_{i,j,t}=0$. Then $\\forall i\\in\\mathcal{M}\\ \\forall t\\in\\mathcal{T}\\ x_{i,j,t}=0$. Then $\\forall i\\in\\mathcal{M}\\ \\forall t\\in\\mathcal{T}\\ \\triple{i}{j}{t}\\not\\in E$. Then $E$ is not stable. By contradiction, $\\sum_{i\\in\\mathcal{M}}\\sum_{t\\in\\mathcal{T}}x_{i,j,t}>0$. Therefore $\\alpha$ holds.\n\t\t\\linespace\n\t\tTo prove backward implication: From $\\alpha$, there is exactly one $i\\in\\mathcal{M}$ and $t\\in\\mathcal{T}$ such that $x_{i,j,t}=1$. So $E$ is conflict free. Also, for all $j$, $\\triple{i}{j}{t}\\in E$ attacks every other $\\pair{i}{t}$, so $E$ is stable.\n\t\\end{proof}\n\\end{lemma}\n\n\\begin{definition}\n\t\\label{intervalbeta}\n\t\n\tLet $\\rightsquigarrow_\\beta$ be the sequential-feasibility framework such that $\\triple{i}{j}{t}\\rightsquigarrow_\\beta\\triple{i'}{j'}{t'}\\Leftrightarrow i=i'\\land(t'\\leq t\\leq t'+p_j'\\lor t\\leq t'<t+p_j)$.\n\\end{definition}\n\n\\begin{lemma}\n\t\\label{conflictfreenessbeta}\n\t$\\rightsquigarrow_\\beta$ conflict-models $\\beta$.\n\t\n\t\\begin{proof}\n\t\tTo show $E$ is conflict-free implies $\\beta$: Take arbitrary $i\\in\\mathcal{M}$, $t\\in\\mathcal{T}$. To aim for a contradiction, assume $\\sum_{j\\in\\mathcal{J}}\\sum_{t'\\in\\max\\{t-p_j+1,0\\}}x_{i,j,t'}\\geq 2$. Then there exists some $j_1,j_2\\in\\mathcal{J}$ and some $t_1,t_2\\in\\mathcal{T}$ such that $0\\leq t_1,t_2\\leq t$ and $x_{i,j_1,t_1}+x_{i,j_2,t_2}=2$. Then $\\triple{i}{j_1}{t_1}\\in E$ and $\\triple{i}{j_2}{t_2}\\in E$. By conduction of $\\beta$, then either $t_1\\leq t_2\\leq t_1+p_1$ or $t_2\\leq t_1\\leq t_2+p_2$. By definition of $\\rightsquigarrow_\\beta$, $\\triple{i}{j_1}{t_1}\\rightsquigarrow_\\beta\\triple{i}{j_2}{t_2}$. But this contradicts that $E$ is conflict-free. Therefore $\\beta$ holds.\n\t\t\\linespace\n\t\tTo show $\\beta$ implies $E$ is conflict-free: Assume $\\beta$ holds. Take arbitrary $i\\in\\mathcal{M}$, $t\\in\\mathcal{T}$. Then there does not exists overlapping jobs $j_1$ and $j_2$ such that $x_{i,j_1,t_1}+x_{i,j_2,t_2}=2$. Then $\\triple{i}{j_1}{t_1}\\not\\in E$ and $\\triple{i}{j_2}{t_2}\\not\\in E$. Therefore, $E$ is conflict-free.\n\t\\end{proof}\n\\end{lemma}\n\n\\begin{definition}\n\t\\label{intervalgamma}\n\t\n\tLet $\\rightsquigarrow_\\gamma$ be a start-feasibility framework such that\n\t\n\t$\\rightsquigarrow_\\gamma=\\{\\pair{\\triple{i}{j}{t}}{\\triple{i}{j}{t}}\\ |\\ i\\in\\mathcal{M},j\\in\\mathcal{J},0\\leq t<s_{i,j}\\}$.\n\\end{definition}\n\n\\begin{definition}\n\t\\label{intervaldelta}\n\tLet $\\rightsquigarrow_\\delta$ be a finish-feasibility framework such that\n\t\n\t$\\rightsquigarrow_\\delta=\\{\\pair{\\triple{i}{j}{t}}{\\triple{i}{j}{t}}\\ |\\ i\\in\\mathcal{M},j\\in\\mathcal{J},f_{i,j}-p_j<t<T\\}$.\n\\end{definition}\n\n\\begin{definition}\n\t\\label{intervalepsilon}\n\t\n\tLet $\\rightsquigarrow_\\varepsilon$ be the negative fixed decision feasibility framework such that\n\t\n\t$\\rightsquigarrow_\\varepsilon=\\{\\pair{\\triple{i}{j}{t}}{\\triple{i}{j}{t}}\\ |\\ \\pair{i}{j}\\in D^-,t\\in\\mathcal{T}\\}$.\n\\end{definition}\n\n\\begin{definition}\n\t\\label{intervalzeta}\n\t\n\tLet $\\rightsquigarrow_\\zeta$ be a positive fixed decision feasibility framework such that\n\t$\\rightsquigarrow_\\varepsilon=\\{\\pair{\\triple{i}{j}{t}}{\\triple{i}{j}{t}}\\ |\\ i\\in\\mathcal{M}, \\triple{i'}{j}{t'}\\in D^+, i\\neq i', t\\in\\mathcal{T}\\}$.\n\\end{definition}\n\n\\begin{definition}\n\t\\label{intervaleta}\n\t\n\tLet $\\rightsquigarrow_\\eta$ be a positive fixed decision feasibility framework such that\n\t$\\rightsquigarrow_\\varepsilon=\\{\\pair{\\triple{i}{j}{t}}{\\triple{i}{j}{t}}\\ |\\triple{i}{j}{t'}\\in D^+, t\\in\\mathcal{T}, t\\leq t'-p_j\\lor t\\geq t'+p_j\\}$.\n\\end{definition}\n\n\\begin{lemma}\n\t\\label{conflictfreenessset}\n\tLet $\\mathcal{A}\\subseteq Args$ be the set of arbitrary negative fixed decisions. A schedule $S$ satisfies these decisions if property $P_\\mathcal{A}$ holds. Formally $P_\\mathcal{A}\\iff\\forall a\\in\\mathcal{A}\\ x_a=0$. If $\\rightsquigarrow_\\mathcal{A}$ is defined by $\\rightsquigarrow_\\mathcal{A}=\\{\\pair{a}{a}\\ |\\ a\\in\\mathcal{A}\\}$, then $\\rightsquigarrow_\\mathcal{A}$ conflict-models $P_\\mathcal{A}$.\n\n\t\\begin{proof}\n\t\tTo prove forward implication: Assume $E$ is conflict free on $\\pair{Args}{\\rightsquigarrow_\\mathcal{A}}$. Take arbitrary $a\\in\\mathcal{A}$. To aim for a contradiction, assume $x_a=1$. Then $a\\in E$. By definition of $\\rightsquigarrow_\\mathcal{A}$, $a\\rightsquigarrow_\\mathcal{A} a$. But this contradicts $E$ is conflict-free so $x_a=0$. Therefore $P_\\mathcal{A}(S)$ holds.\n\t\t\\linespace\n\t\tTo prove backward implication: Assume $P_\\mathcal{A}(S)$ holds. Take arbitrary $a\\in\\mathcal{A}$. To aim for a contradiction, assume $a\\rightsquigarrow_\\mathcal{A}a$. Then $a\\in E$, so $x_a=1$. This contradicts $P_\\mathcal{A}(S)$, so $E$ is conflict-free.\n\t\\end{proof}\n\\end{lemma}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\begin{tikzpicture}\n\t\\node[node, shaded](a) at (0, 2){a};\n\t\\node[node](b) at (2, 2){b};\n\t\\node[node](c) at (2, 0){c};\n\t\\node[node](d) at (0, 0){d};\n\t\\draw[arrow](c) to [loop](c);\n\t\\draw[arrow](d) to [loop](d);\n\t\\draw(-1,-1) rectangle (3, 3);\n\t\\end{tikzpicture}\\raisebox{2cm}{conflict-models $P_\\mathcal{A}$ with $\\mathcal{A}=\\{c, d\\}$}\n\t\\caption{Self-attacking arguments cannot be members of stable extensions. Lemma \\ref{conflictfreenessset} exploits self-attacks to conflict-model negative fixed decisions.}\n\\end{figure}\n\n\\begin{lemma}\n\t\\label{intervalstabilitydependence}\n\tFor all extensions $E$, $\\forall a\\in Args\\setminus E\\ \\forall\\lambda\\in\\{\\beta,\\gamma,\\delta,\\varepsilon,\\zeta,\\eta\\}\\ \\big((\\exists e\\in E\\ e\\rightsquigarrow_\\lambda a)\\implies(\\exists e\\in E\\ e\\rightsquigarrow_\\alpha a)\\big)$.\n\t\n\t\\begin{proof}\n\t\tTake arbitrary extension $E$ and arbitrary $a\\in Args\\setminus E$. If $\\lambda\\neq\\beta$ and $\\exists e\\in E\\ e\\rightsquigarrow_\\lambda a$, then $a=e$ from the definition of $\\rightsquigarrow_\\lambda$. But $e\\not\\in Args\\setminus E$. By contradiction, $\\lambda=\\beta$.\n\t\t\\linespace\n\t\tIf $m=0$ or $T=0$, then $Args=\\varnothing$, so the proof is trivial.\n\t\t\\linespace\n\t\tIf $m=1$ and $T=1$, then by definition of $\\rightsquigarrow_\\beta$, $\\rightsquigarrow_\\beta=\\varnothing$. So $\\neg\\exists e\\in E\\ e\\rightsquigarrow_\\beta a$. As the condition does not hold, $\\exists e\\in E\\ e\\rightsquigarrow_\\alpha a$.\n\t\t\\linespace\n\t\tOtherwise, let $a=\\triple{i}{j}{t}$. Because $m>2$ or $T>2$, then there exists $i$ and $t$ such that $\\pair{i}{t}\\neq\\pair{i'}{t'}$. By definition of $\\rightsquigarrow_\\alpha$, $\\triple{i'}{j}{t'}\\rightsquigarrow_\\alpha a$.\n\t\\end{proof}\n\\end{lemma}\n\n\\begin{theorem}[\\textbf{Interval schedule feasibility is stability-modellable}]\n\t\\label{intervalfeasibilty}\n\t\n\tLet $\\Lambda(S)$ iff $\\forall\\lambda\\in\\{\\alpha,\\beta,\\gamma,\\delta,\\varepsilon,\\zeta,\\eta\\}\\ \\lambda(S)$. $\\Lambda$ is stability-modellable.\n\t\n\t\\begin{proof}\\ \n\t\t\\begin{enumerate}\n\t\t\t\\item $\\rightsquigarrow_\\gamma$ conflict-models $\\gamma$ \\hfill definition of $\\rightsquigarrow_\\gamma$, lemma \\ref{conflictfreenessset}\n\t\t\t\\item $\\rightsquigarrow_\\delta$ conflict-models $\\delta$ \\hfill definition of $\\rightsquigarrow_\\delta$, lemma \\ref{conflictfreenessset}\n\t\t\t\\item $\\rightsquigarrow_\\varepsilon$ conflict-models $\\varepsilon$ \\hfill definition of $\\rightsquigarrow_\\varepsilon$, lemma \\ref{conflictfreenessset}\n\t\t\t\\item $\\rightsquigarrow_\\zeta$ conflict-models $\\zeta$ \\hfill definition of $\\rightsquigarrow_\\zeta$, lemma \\ref{conflictfreenessset}\n\t\t\t\\item $\\rightsquigarrow_\\eta$ conflict-models $\\eta$ \\hfill definition of $\\rightsquigarrow_\\eta$, lemma \\ref{conflictfreenessset}\n\t\t\t\\item $\\left(\\bigcup_{\\lambda\\in\\{\\alpha,\\beta,\\gamma,\\delta,\\varepsilon,\\zeta,\\eta\\}}\\rightsquigarrow_\\lambda\\right)$ stability-models $\\Lambda$\\\\\\indent\\hfill lemma \\ref{stabilityalpha}, lemma \\ref{conflictfreenessbeta}, 1, 2, 3, 4, 5, lemma \\ref{intervalstabilitydependence}, theorem \\ref{modelling}\n\t\t\t\\item $\\Lambda$ is stability-modellable \\hfill 6\n\t\t\\end{enumerate}\n\t\\end{proof}\n\\end{theorem}\n\nWe have shown an application of argumentation to scheduling with Theorem \\ref{modelling}. Theorem \\ref{modelling} is relevant because we have shown that we can use argumentation with interval scheduling, as shown in Theorem \\ref{intervalfeasibilty}. Theorem \\ref{modelling} is key in extensions to scheduling.", "meta": {"hexsha": "686a6244200dd307871a7a887783b251557309a1", "size": 29803, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "backend/aes-master/report/interval.tex", "max_stars_repo_name": "AminKaramlou/AESWebApp", "max_stars_repo_head_hexsha": "606534731eb7793fc2980b7c2b8c37e3b26cbbd4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "backend/aes-master/report/interval.tex", "max_issues_repo_name": "AminKaramlou/AESWebApp", "max_issues_repo_head_hexsha": "606534731eb7793fc2980b7c2b8c37e3b26cbbd4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2020-07-19T01:11:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T21:15:53.000Z", "max_forks_repo_path": "backend/aes-master/report/interval.tex", "max_forks_repo_name": "AminKaramlou/AESWebApp", "max_forks_repo_head_hexsha": "606534731eb7793fc2980b7c2b8c37e3b26cbbd4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-09-23T21:18:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-31T07:32:52.000Z", "avg_line_length": 61.576446281, "max_line_length": 952, "alphanum_fraction": 0.6947287186, "num_tokens": 10835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.30199935764315144}}
{"text": "\\section{Conversions beween WPDSs and NWAs (namespace\n  \\texttt{opennwa::nwa\\_pds})}\n\\label{Se:Conversions}\n\n\nIt is possible to convert an NWA into a WALi WPDS and vice versa.\nHowever, the construction of an NWA from a WPDS is not the inverse\nof constructing a WPDS from an NWA, i.e., one cannot perform the two\nconversions in sequence and obtain the identity conversion.\n\nAt a high level, the WPDS to NWA conversion works by making the NWA encode both the state\nof the WPDS and its top-of-stack symbol. A WPDS rule of the form $\\langle\np,q_1 \\rangle \\hookrightarrow \\langle p,q_2 \\rangle$ leaves the stack height\nunchanged, and is thus associated with an internal NWA transition; in this\ncase, that transition goes from the state $(p,q_1)$ to $(p,q_2)$. The symbol\nof a transition is associated with the top-of-stack symbol of the source\nstate, so in this example, the symbol labeling that transition would be\n$q_1$. In other words, the WPDS rule $\\langle p,q_1 \\rangle \\hookrightarrow\n\\langle p,q_2 \\rangle$ is translated to the NWA internal transition\n$((p,q_1), q_1, (p,q_2))$.\nWPDS push rules correspond to NWA call transitions, and WPDS pop rules\ncorrespond to NWA return transitions.\\footnote{\nThis encoding is motivated by our uses of both WPDSs and NWAs in program\nanalysis. It is common for WPDSs to have just one state, $p$, and to use the\ntop-of-stack symbol to encode the ``current'' program point. Pushing\nsomething onto the stack corresponds to a call, and popping corresponds to a\nreturn. For NWAs, we use the states themselves to encode the current program\npoint. (The function that\nconverts a WPDS into an NWA supports multi-state WPDSs, however; a WPDS rule\nof the form $\\langle p_1,q_1 \\rangle \\hookrightarrow\n\\langle p_2,q_2 \\rangle$ is translated to the NWA internal transition\n$((p_1,q_1), q_1, (p_2,q_2))$.)}\n\nThe conversion in the other direction creates a WPDS with one primary state\nand one ``helper'' state for each NWA state that appears in the exit position\nof a return transition. The NWA's state is encoded by the symbol at the top of the WPDS's\nstack -- essentially the inverse of the encoding described in the previous\nparagraph. A slight complication arises in the case of return\ntransitions. The NWA is able to look at both the exit node and the call\npredecessor. In the WPDS this would correspond to looking at the top two stack\nsymbols -- but the WPDS is only allowed to look at the top \\emph{one}. Hence each NWA return transition becomes\ntwo WPDS rules: the first pops the top symbol (which corresponds to the\ncurrent NWA state) and remembers what it was using the helper state; the\nsecond rule looks at the call predecessor and the helper state to dispatch to\nthe corresponding return site.\n\nThe library also offers two kinds of variants of this conversion. First, there\nis a backwards variant that can be used for backwards dataflow-analysis\nproblems. Second, the resulting WPDS can stack either calls or returns. The\n``stacking-calls'' version turns a call transition $(c, \\sigma, e)$ into a\nWPDS rule $\\langle p, c\\rangle \\hookrightarrow \\langle p, e c\\rangle$ --\nleaving the call predecessor $c$ on the stack. (This is the translation\ndescribed in the previous paragraph.) The ``stacking-returns'' version\nhas, in general, several WPDS push rules for each NWA call transition. Each\npush rule leaves a potential return site on the stack. (For example, if there\nis a call transition $(c,\\sigma,e)$ and a return transition $(x, c, \\sigma',\nr)$, then the WPDS will have a rule $\\langle p,\nc\\rangle\\hookrightarrow\\langle p, e r\\rangle$.)\n\n\nThe following functions are in the namespace \\texttt{opennwa::nwa\\_pds}\nand, except for \\texttt{plusWpds()}, are declared in the header\n\\texttt{opennwa/nwa\\_pds/conversions.hpp}. The \\texttt{WPDS} type is\n\\texttt{wali::wpds::WPDS}, and is declared in \\texttt{wali/wpds/WPDS.hpp}.\n\n\n\\begin{functionlist}\n  \\functionDefEarly{void}{WpdsToNwa}{Nwa \\& out, const WPDS\\& pds}{}\n  \\functionDef{NwaRefPtr}{WpdsToNwa}{const WPDS\\& pds}{}\n    Converts \\texttt{pds} to an NWA, either storing the result in\n    \\texttt{nwa} or returning it.\n\n\\clearpage\n  \\functionDefFirstEarly{WPDS}{NwaToWpdsCalls}{Nwa const \\& nwa, WeightGen const \\& wg}{}\n  \\functionDefEarlyNoCloseParen{WPDS}{NwaToWpdsCalls}{\\parbox[t]{4in}{Nwa const \\& nwa, WeightGen const \\& wg,\\\\ref\\_ptr<Wrapper> wr)}}\n  \\functionDefEarly{WPDS}{NwaToBackwardsWpdsCalls}{Nwa const \\& nwa, WeightGen const \\& wg}{}\n  \\functionDefEarly{WPDS}{NwaToWpdsReturns}{Nwa const \\& nwa, WeightGen const \\& wg}{}\n  \\functionDef{WPDS}{NwaToBackwardsWpdsReturn}{Nwa const \\& nwa, WeightGen const \\& wg}{}\n    These functions each construct a WPDS that is equivalent to \\texttt{nwa} using the\n    appropriate method (backwards or forwards flow, and stacking calls or\n    stacking returns), returning the result. Uses \\texttt{wg} to determine\n    weights for the WPDS's transitions. The second variant of\n    \\texttt{NwaToWpdsCalls} takes a \\texttt{wali::wpds::Wrapper} reference\n    \\texttt{wr}, and the WPDS is constructed by passing \\texttt{wr} to the\n    constructor. This feature can be used, for instance, if you would like the\n    resulting WPDS to support witness tracing. (If \\texttt{wr} is\n    \\texttt{NULL}, then the second version is equivalent to the first.)\n\n  \\functionDefFirst{State}{getProgramControlLocation}{}{}\n    Returns the program state $p$ used as the primary WPDS state in the\n    result of the \\texttt{NwaToWpds*} variants.\n\n  \\functionDefFirst{State}{getControlLocation}{State exit, State call, State return}{}\n    Returns the WPDS state $p_{q_x}$ or $p_{q_3}$ used as a ``helper'' state\n    for return transitions from \\texttt{exit} to \\texttt{return} with\n    \\texttt{call} as a predecessor.\n\n  \\functionDefFirst{WPDS}{plusWpds}{Nwa const \\& nwa, const WPDS\\& base}{}\n    This function returns a WPDS that is the\n    product of the NWA \\texttt{nwa} and WPDS \\texttt{base}, as described in the ``Explicit\n    NWA plus PDS'' construction from \\cite[\\S6]{advancedquerying}. This\n    function is declared in the header\n    \\texttt{opennwa/nwa\\_pds/plusWpds.hpp}.\n\\end{functionlist}\n\n\n\\subsection{WPDS to NWA}\n\\label{Se:WpdsToNwa}\n\nThe \\texttt{WpdsToNwa} functions convert a WPDS into an NWA in a manner\nfaithful to the encoding sketched out in the introduction to this section.\n\nAssume that we have a WPDS $(P, \\Gamma, \\Delta )$ \nwhere $\\Delta = (\\Delta_0, \\Delta_1, \\Delta_2)$. This \nWPDS is converted into an NWA $(Q,\\Sigma,\\{\\},\\delta,\\{\\})$ using the following rules:\n\n\\begin{mathpar}\n{\\inferrule*[left=\\textsc{States}]\n  { p \\in P \\\\ q \\in \\Gamma }\n  { (p,q) \\in Q }\n}\n\\and\n{\\inferrule*[left=\\textsc{Alphabet}]\n  { q \\in \\Gamma }\n  { q \\in \\Sigma } \n}\n\\and \n\\\\\n{\\inferrule*[left=\\textsc{Internal}]\n  { \\langle p,q \\rangle \\hookrightarrow \\langle p',q' \\rangle \\in  \\Delta_1 }\n  { ( (p,q), q, (p',q') ) \\in \\delta_i  }\n}\n\\and\n{\\inferrule*[left=\\textsc{Call}]\n  { \\langle p,q_c \\rangle \\hookrightarrow \\langle  p',q_e \\hspace{.1cm} q_r \\rangle \\in \\Delta_2 }\n  { ( (p,q_c), q_c, (p',q_e) ) \\in \\delta_c }\n} \n\\and\n{\\inferrule*[left=\\textsc{Return}]\n  { \\langle p'',q_x \\rangle \\hookrightarrow \\langle p''',\\epsilon  \\rangle \\in \\Delta_0 \\\\\n     \\langle p,q_c \\rangle \\hookrightarrow \\langle p',q_e \\hspace{.1cm} q_r  \\rangle \\in \\Delta_2 }\n  { ( (p'',q_x), (p,q_c), q_x, (p''',q_r) ) \\in \\delta_r }\n}\n\\end{mathpar}\n\nNote that these rules generate an NWA return transition for each pair of WPDS pop\nand push rules; there is no constraint between the two rules.  This is\nbecause, with the exception of the ``revealed'' stack symbol $q_r$,\neverything that the push rule talks about concerns the call predecessor\n$(p,q_c)$ and entry node $(q', q_e)$; nothing that the pop rule talks about ---\n$p''$, $q_x$, or $p'''$ --- has any relation to those. (A consequence is that the\nnumber of NWA transitions may be quadratic in the number of\nWPDS rules.)\n\n\nIn the resulting NWA, $Q_0$ and $Q_f$ are empty; client code must set the initial and\nfinal states as appropriate (with \\texttt{addInitialState(State)} and\n\\texttt{addFinalState(State)}. The keys that are generated for the names of the\nNWA states are part of the interface of this function; they are generated by\n\\texttt{getKey(p, q)} where \\texttt{p} and \\texttt{q} are the keys of the\nWPDS state and stack symbol being converted.\n\nAll weights on WPDS rules are ignored, and do not survive in any way in the\nresulting NWA. The client information for all states in the resulting NWA are\nset to \\texttt{null}.\n\n\n\\begin{figure}[t]\n  \\centering\n    \\begin{itemize}\n      \\centering\n      \\item{ $\\langle p,main \\rangle \\hookrightarrow \\langle p,q_1 \\rangle$}\n      \\item{ $\\langle p,q_1 \\rangle \\hookrightarrow \\langle p,c_1 \\rangle$}\n      \\item{ $\\langle p,c_1 \\rangle \\hookrightarrow \\langle p,e \\hspace{.1cm} r_1 \\rangle$}\n      \\item{ $\\langle p,e \\rangle \\hookrightarrow \\langle p,q_2 \\rangle$}\n      \\item{ $\\langle p,q_2 \\rangle \\hookrightarrow \\langle p,q_3 \\rangle$}\n      \\item{ $\\langle p,q_3 \\rangle \\hookrightarrow \\langle p,x \\rangle$}\n      \\item{ $\\langle p,x \\rangle \\hookrightarrow \\langle p,\\epsilon \\rangle$}\n      \\item{ $\\langle p,r_1 \\rangle \\hookrightarrow \\langle p,q_4 \\rangle$}\n      \\item{ $\\langle p,q_4 \\rangle \\hookrightarrow \\langle p,q_5 \\rangle$}\n      \\item{ $\\langle p,q_5 \\rangle \\hookrightarrow \\langle p,c_2 \\rangle$}\n      \\item{ $\\langle p,c_2 \\rangle \\hookrightarrow \\langle p,e \\hspace{.1cm} r_2 \\rangle$}\n      \\item{ $\\langle p,r_2 \\rangle \\hookrightarrow \\langle p,q_6 \\rangle$}\n      \\item{ $\\langle p,q_6 \\rangle \\hookrightarrow \\langle p,exit \\rangle$}\n    \\end{itemize}\n  \\caption{An example WPDS.}\n  \\label{Fi:WpdsToNwa1}\n\\end{figure}\n\nFor example, the NWA created from the WPDS shown in\n\\figref{WpdsToNwa1} is shown in \\figref{WpdsToNwa2}.\n\n\\begin{figure}[t]\n  \\centering\n    \\nwaimage[1]{Figures/pds-equivalent}\n  \\caption{The NWA resulting from converting the WPDS in \\figref{WpdsToNwa1} into an NWA.}\n  \\label{Fi:WpdsToNwa2}\n\\end{figure}\n\n\n\n\\subsection{NWA to WPDS}\n\\label{Se:NWAtoPDS}\n\n\nAn NWA can also be converted into a WPDS. Weights for the rules of the\nresulting WPDS are provided using a mechanism described below.  In this way\nit is possible to use\nthe WPDS reachability queries that are a part of the main WALi library on\nNWAs.  As mentioned in the introduction to \\sectref{Conversions}, there are\nfour variations on the NWA-to-WPDS conversion: forward flow with call states\non the stack, backward flow with call states on the stack, forward flow with\nreturn states on the stack, and backward flow with return states on the\nstack. All four variations use \\texttt{WeightGen} to determine weights for\nWPDS rules.\n\n\\texttt{WeightGen} is an abstract class that client code must subclass to\ncalculate the weights of the rules in the generated WPDS.  It allows the\nunderlying NWA to be decoupled from the weight domain used in the WPDS.  See\n\\cite[\\S4-\\S5]{wali} for details about weight domains.\n\nThere is a trivial weight domain (containing $\\overline{1}$ and\n$\\overline{0}$ only) implemented in the class \\texttt{wali::Reach}, defined in\n\\texttt{wali/Reach.hpp}. A \\texttt{WeightGen} subclass that returns elements\nfrom this reachability domain is provided as the \\texttt{ReachGen} class,\ndefined in \\texttt{opennwa/WeightGen.hpp}. \\texttt{ReachGen} returns\n$\\overline{1}$ for all transitions.\n\nIn addition, we provide shortest-path weights and two variants on a\n\\texttt{WeightGen} subclass for them. The shortest path weights are\nimplemented in the class \\texttt{wali::ShortestPathSemiring} in\n\\texttt{wali/ShortestPathSemiring.hpp}; a semiring element of this class\nconsists of just a single integer. The two \\texttt{WeightGen} implementations\nwe provide (both defined in \\texttt{opennwa/WeightGen.hpp}) are\n\\texttt{ShortestPathGen} and \\texttt{ShortestWordGen}. Both set the weight of\neach WPDS rule to have a length 1 (note that this is different from the\nsemiring $\\overline{1}$ element), except that \\texttt{ShortestWordGen} uses\nlength 0 for rules that correspond to $\\varepsilon$ transitions. Thus\n\\texttt{ShortestPathGen} results in a WPDS with weights that describe the\nlength of the shortest \\emph{path} through the NWA, from the initial\nconfigurations, while \\texttt{ShortestWordGen} results in a WPDS with weights\nthat describe the length of the shortest \\emph{word}.\n\n\nThe following operations are virtual methods of \\texttt{WeightGen} intended to\nbe overridden:\n\n\\begin{functionlist} \n  \\functionDef{sem\\_elem\\_t}{WeightGen::getOne}{}{const = 0}  \\nopagebreak\n    Returns an instance of the $\\bar{1}$ element of the weight domain.\n\n  \\functionDefFirstNoCloseParen{sem\\_elem\\_t}{getWeight}{%\n      \\parbox[t]{4in}{\n        State source, ClientInfoRefPtr sourceInfo, \\\\  \n        Symbol symbol, Kind k, \\\\\n        State target, ClientInfoRefPtr targetInfo ) const}}  \\nopagebreak\n    Computes and returns the weight for the rule corresponding to the\n    transition from \\texttt{source} to \\texttt{target} (of\n    kind \\texttt{k})\n    labeled with symbol \\texttt{symbol}. By default, returns \\texttt{getOne()}.\n\n  \\functionDefFirstNoCloseParen{sem\\_elem\\_t}{getWildWeight}{%\n      \\parbox[t]{4in}{\n        State source, ClientInfoRefPtr sourceInfo, \\\\  \n        State target, ClientInfoRefPtr targetInfo ) const}}\n    Computes and returns the weight for the WPDS rule corresponding to the\n    transition from \\texttt{source} to \\texttt{target} labeled with the\n    meta-symbol \\wild. By default, returns \\texttt{getOne()}.\n\n  \\functionDefFirst{sem\\_elem\\_t}{getExitWeight}{State src, ClientInfoRefPtr srcInfo}{const}\n  This method computes the weight (in the desired semiring) for the return rule of\n  the WPDS corresponding to the exit \\texttt{src}.\n  Note: the value is generally the same as \\texttt{getOne()}, which is what the\n  default implementation returns.\n\n\\end{functionlist}\n\n\n\\subsubsection{Forwards flow stacking calls}\n\\label{Se:wpds-forwards-flow-stacking-calls}\n\n\\noindent The conversion is performed by:\n\n\n\n\\begin{mathpar}\n\n{\\inferrule*%%[left=\\textsc{States}]\n  { }\n  {p \\in P}\n}\n\\and \n{\\inferrule*\n  { (q_x,q_c,\\sigma,q_r) \\in \\delta_r }\n  { p_{q_x} \\in P }\n}\n\\and\n{\\inferrule*\n  { q \\in Q }\n  { q \\in \\Gamma }\n}\n\\and \n{\\inferrule*%%[left=\\textsc{Internal}]\n  { (q,\\sigma,q') \\in \\delta_i }\n  { \\langle p,q \\rangle \\stackrel{w_1}{\\hookrightarrow} \\langle p,q' \\rangle \\in \\Delta_1 }\n}\n\\and\n{\\inferrule*%%[left=\\textsc{Call}]\n  { (q_c,\\sigma, q_e) \\in \\delta_c }\n  {  \\langle p,q_c \\rangle \\stackrel{w_2}{\\hookrightarrow} \\langle p, q_e \\hspace{.1cm} q_c \\rangle\\in \\Delta_2 }\n}\n\\and\n{\\inferrule*%%[left=\\textsc{Return}]\n  { (q_x,q_c,\\sigma,q_r) \\in \\delta_r }\n  { \\langle p,q_x \\rangle \\stackrel{w_0}{\\hookrightarrow} \\langle p_{q_x},\\epsilon \\rangle \\in \\Delta_0 \\\\\n   \\langle p_{q_x},q_c \\rangle \\stackrel{w_3}{\\hookrightarrow} \\langle p,q_r \\rangle\\in \\Delta_1  }\n}\n\\end{mathpar}\n\\begin{align*}\n\\text{where }\nw_0 & = \\begin{cases}\n        \\mathtt{wg.getWildWeight}(q_x,CI_{q_x},q_r,CI_{q_r}), & \\text{if } \\sigma = \\text{\\wild} \\\\\n        \\mathtt{wg.getWeight}(q_x,CI_{q_x},\\sigma,\\mathtt{EXIT\\_TO\\_RET},q_r,CI_{q_r}), & \\text{otherwise}\n      \\end{cases}  \\\\\nw_1 &= \\begin{cases}\n         \\mathtt{wg.getWildWeight}(q,CI_q,q',CI_{q'}), & \\text{if } \\sigma = \\text{\\wild} \\\\\n         \\mathtt{wg.getWeight}(q,CI_q,\\sigma,\\mathtt{INTRA},q',CI_{q'}), & \\text{otherwise}\n      \\end{cases} \\\\\nw_2 &= \\begin{cases}\n         \\mathtt{wg.getWildWeight}(q_c,CI_{q_c},q_e,CI_{q_e}), & \\text{if } \\sigma = \\text{\\wild} \\\\\n         \\mathtt{wg.getWeight}(q_c,CI_{q_c},\\sigma,\\mathtt{CALL\\_TO\\_ENTRY},q_e,CI_{q_e}), & \\text{otherwise}\n      \\end{cases} \\\\\nw_3 &= \\mathtt{wg.getOne}() \n\\end{align*}\n\n\nFor example, the WPDS resulting from converting the NWA\nshown in \\figref{NwaToWpds1} into a WPDS is shown in\n\\figref{NwaToWpds4}. \\\\\n\n\n\\subsubsection{Backwards flow stacking calls}\n\nThe backwards-flow conversions are equivalent to calling\n\\texttt{wali::\\-nwa::\\-construct::\\-reverse} and then the corresponding forwards\nflow version. When reversing, call transitions become return transitions (and\nvice versa), and so call sites become return sites (and vice versa).\nReturn sites in the original automaton behave as call sites in the reversed\nautomaton, and thus this version of the NWA-to-WPDS conversion stacks return\nstates. (In\nother words, the \\texttt{Calls} and \\texttt{Returns} part of\n\\texttt{NwaTo\\-Backwards\\-WpdsCalls} and\n\\texttt{NwaTo\\-Backwards\\-WpdsReturns} refer to the behavior of the states in\nthe reversed automaton, not the role they play in the original.)\n\nFor example, the result of converting the NWA in\n\\figref{NwaToWpds1} into a backwards flow WPDS is shown in \\figref{NwaToWpds5}.\n\n\nFormally, the conversion is performed by:\n\n\n\\begin{mathpar}\n{\\inferrule*%%[left=\\textsc{States}]\n  { }\n  {p \\in P}\n}\n\\and \n{\\inferrule*\n  { (q_c,\\sigma,q_e) \\in \\delta_c }\n  { p_{q_e} \\in P }\n}\n\\and\n{\\inferrule*\n  { q \\in Q }\n  { q \\in \\Gamma }\n}\n\\and \n{\\inferrule*%%[left=\\textsc{Internal}]\n  { (q,\\sigma,q') \\in \\delta_i }\n  { \\langle p,q' \\rangle \\stackrel{w_1}{\\hookrightarrow} \\langle p,q \\rangle \\in \\Delta_1 }\n}\n\\and  \n{\\inferrule*%%[left=\\textsc{Call}]\n  { (q_c,\\sigma, q_e) \\in \\delta_c \\\\ (q_x,q_c,\\gamma,q_r) \\in \\delta_r }\n  { \\langle p,q_e \\rangle \\stackrel{w_0}{\\hookrightarrow} \\langle p_{q_e},\\epsilon \\rangle \\in \\Delta_0 \\\\\n    \\langle p_{q_e},q_r \\rangle \\stackrel{w_3}{\\hookrightarrow} \\langle p,q_c  \\rangle \\in \\Delta_1 }\n}\n\\and\n{\\inferrule*%%[left=\\textsc{Return}]\n  { (q_x,q_c,\\sigma,q_r) \\in \\delta_r }\n  {  \\langle p,q_r \\rangle \\stackrel{w_2}{\\hookrightarrow} \\langle p,q_x \\hspace{.1cm} q_r\n  \\rangle \\in \\Delta_2 }\n}\n\\end{mathpar}\n\\begin{align*}\n\\text{where }\nw_0 &= \\begin{cases}\n           \\mathtt{wg.getWildWeight}(q_c,CI_{q_c},q_e,CI_{q_e}), & \\text{if } \\sigma = \\text{\\wild} \\\\\n           \\mathtt{wg.getWeight}(q_c,CI_{q_c},\\sigma, \\mathtt{CALL\\_TO\\_ENTRY},q_e,CI_{q_e}), & \\text{otherwise}\n      \\end{cases} \\\\\nw_1 &= \\begin{cases}\n           \\mathtt{wg.getWildWeight}(q,CI_q,q',CI_{q'}), & \\text{if } \\sigma = \\text{\\wild} \\\\\n           \\mathtt{wg.getWeight}(q,CI_q,\\sigma, \\mathtt{INTRA},q',CI_{q'}), & \\text{otherwise}\n       \\end{cases} \\\\\nw_2 &= \\begin{cases}\n          \\mathtt{wg.getWildWeight}(q_x,CI_{q_x},q_r,CI_{q_r}), & \\text{if } \\sigma = \\text{\\wild} \\\\\n          \\mathtt{wg.getWeight}(q_x,CI_{q_x},\\sigma, \\mathtt{EXIT\\_TO\\_RET},q_r,CI_{q_r}), & \\text{otherwise}\n      \\end{cases} \\\\\nw_3 &= \\mathtt{wg.getOne}()\n\\end{align*}\n\n\n\\subsubsection{Forwards flow stacking returns}\n\nAs an example, converting the NWA in \\figref{NwaToWpds1} into a WPDS results\nin the WPDS shown in \\figref{NwaToWpds2}. \\\\\n\n\nThe conversion is performed by:\n\n\n\\begin{mathpar}\n{\\inferrule*%%[left=\\textsc{States}]\n  { }\n  {p \\in P}\n}\n\\and \n{\\inferrule*\n  { (q_x,q_c,\\sigma,q_r) \\in \\delta_r }\n  { p_{q_x} \\in P }\n}\n\\and\n{\\inferrule*\n  { q \\in Q }\n  { q \\in \\Gamma }\n}\n\\and \n{\\inferrule*%%[left=\\textsc{Internal}]\n  { (q,\\sigma,q') \\in \\delta_i }\n  { \\langle p,q  \\rangle \\stackrel{w_1}{\\hookrightarrow} \\langle p,q' \\rangle \\in \\Delta_1 }\n}\n\\and\n{\\inferrule*%%[left=\\textsc{Call}]\n  { (q_c,\\sigma, q_e) \\in \\delta_c \\\\ (q_x,q_c,\\gamma,q_r) \\in \\delta_r }\n  { \\langle p,q_c \\rangle \\stackrel{w_2}{\\hookrightarrow}  \\langle p, q_e \\hspace{.1cm} q_r \\rangle \\in \\Delta_2 }\n}\n\\and \n{\\inferrule*%%[left=\\textsc{Return}]\n  { (q_x,q_c,\\sigma,q_r) \\in \\delta_r }\n  { \\langle p,q_x \\rangle \\stackrel{w_0}{\\hookrightarrow} \\langle p_{q_x},\\epsilon \\rangle \\in  \\Delta_0 \\\\\n    \\langle  p_{q_x},q_r \\rangle \\stackrel{w_3}{\\hookrightarrow} \\langle p,q_r \\rangle \\in \\Delta_1 }\n}\n\\end{mathpar}\n\\begin{align*}\n\\text{where }\nw_0 &= \\mathtt{wg.getOne}() \\\\\nw_1 &= \\begin{cases}\n           \\mathtt{wg.getWildWeight}(q,CI_q,q',CI_{q'}), & \\text{if } \\sigma = \\text{\\wild} \\\\\n           \\mathtt{wg.getWeight}(q,CI_q,\\sigma, \\mathtt{INTRA},q',CI_{q'}), & \\text{otherwise}\n       \\end{cases} \\\\\nw_2 &= \\begin{cases}\n           \\mathtt{wg.getWildWeight}(q_c,CI_{q_c},q_e,CI_{q_e}), & \\text{if } \\sigma = \\text{\\wild} \\\\\n           \\mathtt{wg.getWeight}(q_c,CI_{q_c},\\sigma, \\mathtt{CALL\\_TO\\_ENTRY},q_e,CI_{q_e}), & \\text{otherwise}\n      \\end{cases} \\\\\nw_3 &= \\begin{cases}\n          \\mathtt{wg.getWildWeight}(q_x,CI_{q_x},q_r,CI_{q_r}), & \\text{if } \\sigma = \\text{\\wild} \\\\\n          \\mathtt{wg.getWeight}(q_x,CI_{q_x},\\sigma, \\mathtt{EXIT\\_TO\\_RET},q_r,CI_{q_r}), & \\text{otherwise}\n      \\end{cases} \n\\end{align*}\n\n\n\n\n\\subsubsection{Backwards flow stacking returns}\n\nAs an example, converting the NWA in\n\\figref{NwaToWpds1} into a backwards flow WPDS results in\nthe WPDS shown in \\figref{NwaToWpds3}. \\\\\n\n\n\\noindent The conversion is performed by:\n\n\n\n\\begin{mathpar}\n{\\inferrule*[left=\\textsc{States}]\n  { }\n  {p \\in P}\n}\n\\and \n{\\inferrule*\n  { (q_c,\\sigma,q_e) \\in \\delta_c }\n  { p_{q_e} \\in P }\n}\n\\and\n{\\inferrule*\n  { q \\in Q }\n  { q \\in \\Gamma }\n}\n\\and \n{\\inferrule*%%[left=\\textsc{Internal}]\n  { (q,\\sigma,q') \\in \\delta_i }\n  { \\langle  p,q' \\rangle \\stackrel{w_1}{\\hookrightarrow} \\langle p,q \\rangle \\in \\Delta_1 }\n}\n\\and\n{\\inferrule*%%[left=\\textsc{Call}]\n  { (q_c,\\sigma, q_e) \\in \\delta_c }\n  { \\langle  p,q_e \\rangle \\stackrel{w_0}{\\hookrightarrow} \\langle p_{q_e},\\epsilon \\rangle \\in \\Delta_0 \\\\\n    \\langle  p_{q_e},q_c \\rangle \\stackrel{w_3}{\\hookrightarrow} \\langle p,q_c \\rangle \\in \\Delta_1  }\n}\n\\and \n{\\inferrule*%%[left=\\textsc{Return}]\n  { (q_x,q_c,\\sigma,q_r) \\in \\delta_r }\n  { \\langle p,q_r \\rangle \\stackrel{w_2}{\\hookrightarrow} \\langle p,q_x \\hspace{.1cm} q_c  \\rangle \\in \\Delta_2 }\n}\n\\end{mathpar}\n\\begin{align*}\n\\text{where }\nw_0 &= \\mathtt{wg.getOne}() \\\\\nw_1 &= \\begin{cases}\n           \\mathtt{wg.getWildWeight}(q,CI_q,q',CI_{q'}), & \\text{if } \\sigma = \\text{\\wild} \\\\\n           \\mathtt{wg.getWeight}(q,CI_q,\\sigma, \\mathtt{INTRA},q',CI_{q'}), & \\text{otherwise}\n       \\end{cases} \\\\\nw_2 &= \\begin{cases}\n          \\mathtt{wg.getWildWeight}(q_x,CI_{q_x},q_r,CI_{q_r}), & \\text{if } \\sigma = \\text{\\wild} \\\\\n          \\mathtt{wg.getWeight}(q_x,CI_{q_x},\\sigma, \\mathtt{EXIT\\_TO\\_RET},q_r,CI_{q_r}), & \\text{otherwise}\n      \\end{cases} \\\\\nw_3 &= \\begin{cases}\n           \\mathtt{wg.getWildWeight}(q_c,CI_{q_c},q_e,CI_{q_e}), & \\text{if } \\sigma = \\text{\\wild} \\\\\n           \\mathtt{wg.getWeight}(q_c,CI_{q_c},\\sigma, \\mathtt{CALL\\_TO\\_ENTRY},q_e,CI_{q_e}), & \\text{otherwise}\n      \\end{cases} \n\\end{align*}\n\n\n\n\\begin{figure}[p]\n  \\centering\n  \\begin{minipage}{\\textwidth}\n    \\nwaimage[1]{Figures/pre-pds-nwa}\n    \\caption{An example NWA.}\n    \\label{Fi:NwaToWpds1}\n  \\end{minipage}\n  \\begin{minipage}{0.42\\textwidth}\n    \\begin{itemize}\n      \\centering\n      \\item{ $\\langle p,main \\rangle \\hookrightarrow \\langle p,q_1 \\rangle$}\n      \\item{ $\\langle p,q_1 \\rangle \\hookrightarrow \\langle p,c_1 \\rangle$}\n      \\item{ $\\langle p,e \\rangle \\hookrightarrow \\langle p,q_2 \\rangle$}\n      \\item{ $\\langle p,q_2 \\rangle \\hookrightarrow \\langle p,q_3 \\rangle$}\n      \\item{ $\\langle p,q_3 \\rangle \\hookrightarrow \\langle p,x \\rangle$}\n      \\item{ $\\langle p,r_1 \\rangle \\hookrightarrow \\langle p,q_4 \\rangle$}\n      \\item{ $\\langle p,q_4 \\rangle \\hookrightarrow \\langle p,q_5 \\rangle$}\n      \\item{ $\\langle p,q_5 \\rangle \\hookrightarrow \\langle p,c_2 \\rangle$}\n      \\item{ $\\langle p,r_2 \\rangle \\hookrightarrow \\langle p,q_6 \\rangle$}\n      \\item{ $\\langle p,q_6 \\rangle \\hookrightarrow \\langle p,exit \\rangle$}\n      \\item{ $\\langle p,c_1 \\rangle \\hookrightarrow \\langle p,e \\hspace{.1cm} c_1 \\rangle$}\n      \\item{ $\\langle p,c_2 \\rangle \\hookrightarrow \\langle p,e \\hspace{.1cm} c_2 \\rangle$}\n      \\item{ $\\langle p,x \\rangle \\hookrightarrow \\langle p_x, \\epsilon \\rangle$}\n      \\item{ $\\langle p_x,c_1 \\rangle \\hookrightarrow \\langle p,r_1 \\rangle$}\n      \\item{ $\\langle p,x \\rangle \\hookrightarrow \\langle p_x, \\epsilon \\rangle$}\n      \\item{ $\\langle p_x,c_2 \\rangle \\hookrightarrow \\langle p,r_2 \\rangle$}\n    \\end{itemize}\n    \\caption{The WPDS resulting from calling \\texttt{NwaToWpdsCalls} on \\figref{NwaToWpds1}}\n    \\label{Fi:NwaToWpds4}\n  \\end{minipage}\n  \\hspace{0.1\\textwidth}\n  \\begin{minipage}{0.42\\textwidth}\n    \\centering\n    \\begin{itemize}\n      \\centering\n      \\item{ $\\langle p,q_1 \\rangle \\hookrightarrow \\langle p,main \\rangle$}\n      \\item{ $\\langle p,c_1 \\rangle \\hookrightarrow \\langle p,q_1 \\rangle$}\n      \\item{ $\\langle p,q_2 \\rangle \\hookrightarrow \\langle p,e \\rangle$}\n      \\item{ $\\langle p,q_3 \\rangle \\hookrightarrow \\langle p,q_2 \\rangle$}\n      \\item{ $\\langle p,x \\rangle \\hookrightarrow \\langle p,q_3 \\rangle$}\n      \\item{ $\\langle p,q_4 \\rangle \\hookrightarrow \\langle p,r_1 \\rangle$}\n      \\item{ $\\langle p,q_5 \\rangle \\hookrightarrow \\langle p,q_4 \\rangle$}\n      \\item{ $\\langle p,c_2 \\rangle \\hookrightarrow \\langle p,q_5 \\rangle$}\n      \\item{ $\\langle p,q_6 \\rangle \\hookrightarrow \\langle p,r_2 \\rangle$}\n      \\item{ $\\langle p,exit \\rangle \\hookrightarrow \\langle p,q_6 \\rangle$}\n      \\item{ $\\langle p,r_1 \\rangle \\hookrightarrow \\langle p,x \\hspace{.1cm} r_1 \\rangle$}\n      \\item{ $\\langle p,r_2 \\rangle \\hookrightarrow \\langle p,x \\hspace{.1cm} r_2 \\rangle$}\n      \\item{ $\\langle p,e \\rangle \\hookrightarrow \\langle p_e, \\epsilon \\rangle$}\n      \\item{ $\\langle p_e,r_1 \\rangle \\hookrightarrow \\langle p,c_1 \\rangle$}\n      \\item{ $\\langle p,e \\rangle \\hookrightarrow \\langle p_e, \\epsilon \\rangle$}\n      \\item{ $\\langle p_e,r_2 \\rangle \\hookrightarrow \\langle p,c_2 \\rangle$}\n    \\end{itemize}\n    \\caption{The result of calling \\texttt{NwaToBackwardsWpdsCalls} on \\figref{NwaToWpds1}}\n    \\label{Fi:NwaToWpds5}\n  \\end{minipage}\n  \\begin{minipage}{0.42\\textwidth}\n    \\centering\n    \\begin{itemize}\n      \\centering\n      \\item{ $\\langle p,main \\rangle \\hookrightarrow \\langle p,q_1 \\rangle$}\n      \\item{ $\\langle p,q_1 \\rangle \\hookrightarrow \\langle p,c_1 \\rangle$}\n      \\item{ $\\langle p,e \\rangle \\hookrightarrow \\langle p,q_2 \\rangle$}\n      \\item{ $\\langle p,q_2 \\rangle \\hookrightarrow \\langle p,q_3 \\rangle$}\n      \\item{ $\\langle p,q_3 \\rangle \\hookrightarrow \\langle p,x \\rangle$}\n      \\item{ $\\langle p,r_1 \\rangle \\hookrightarrow \\langle p,q_4 \\rangle$}\n      \\item{ $\\langle p,q_4 \\rangle \\hookrightarrow \\langle p,q_5 \\rangle$}\n      \\item{ $\\langle p,q_5 \\rangle \\hookrightarrow \\langle p,c_2 \\rangle$}\n      \\item{ $\\langle p,r_2 \\rangle \\hookrightarrow \\langle p,q_6 \\rangle$}\n      \\item{ $\\langle p,q_6 \\rangle \\hookrightarrow \\langle p,exit \\rangle$}\n      \\item{ $\\langle p,c_1 \\rangle \\hookrightarrow \\langle p,e \\hspace{.1cm} r_1 \\rangle$}\n      \\item{ $\\langle p,c_2 \\rangle \\hookrightarrow \\langle p,e \\hspace{.1cm} r_2 \\rangle$}\n      \\item{ $\\langle p,x \\rangle \\hookrightarrow \\langle p_x, \\epsilon \\rangle$}\n      \\item{ $\\langle p_x,r_1 \\rangle \\hookrightarrow \\langle p,r_1 \\rangle$}\n      \\item{ $\\langle p,x \\rangle \\hookrightarrow \\langle p_x, \\epsilon \\rangle$}\n      \\item{ $\\langle p_x,r_2 \\rangle \\hookrightarrow \\langle p,r_2 \\rangle$}\n    \\end{itemize}\n    \\caption{The WPDS resulting from calling \\texttt{NwaToWpdsReturns} on \\figref{NwaToWpds1}}\n    \\label{Fi:NwaToWpds2}\n  \\end{minipage}\n  \\hspace{0.1\\textwidth}\n  \\begin{minipage}{0.42\\textwidth}\n    \\centering\n    \\begin{itemize}\n      \\centering\n      \\item{ $\\langle p,q_1 \\rangle \\hookrightarrow \\langle p,main \\rangle$}\n      \\item{ $\\langle p,c_1 \\rangle \\hookrightarrow \\langle p,q_1 \\rangle$}\n      \\item{ $\\langle p,q_2 \\rangle \\hookrightarrow \\langle p,e \\rangle$}\n      \\item{ $\\langle p,q_3 \\rangle \\hookrightarrow \\langle p,q_2 \\rangle$}\n      \\item{ $\\langle p,x \\rangle \\hookrightarrow \\langle p,q_3 \\rangle$}\n      \\item{ $\\langle p,q_4 \\rangle \\hookrightarrow \\langle p,r_1 \\rangle$}\n      \\item{ $\\langle p,q_5 \\rangle \\hookrightarrow \\langle p,q_4 \\rangle$}\n      \\item{ $\\langle p,c_2 \\rangle \\hookrightarrow \\langle p,q_5 \\rangle$}\n      \\item{ $\\langle p,q_6 \\rangle \\hookrightarrow \\langle p,r_2 \\rangle$}\n      \\item{ $\\langle p,exit \\rangle \\hookrightarrow \\langle p,q_6 \\rangle$}\n      \\item{ $\\langle p,r_1 \\rangle \\hookrightarrow \\langle p,x \\hspace{.1cm} c_1 \\rangle$}\n      \\item{ $\\langle p,r_2 \\rangle \\hookrightarrow \\langle p,x \\hspace{.1cm} c_2 \\rangle$}\n      \\item{ $\\langle p,e \\rangle \\hookrightarrow \\langle p_e, \\epsilon \\rangle$}\n      \\item{ $\\langle p_e,c_1 \\rangle \\hookrightarrow \\langle p,c_1 \\rangle$}\n      \\item{ $\\langle p,e \\rangle \\hookrightarrow \\langle p_e, \\epsilon \\rangle$}\n      \\item{ $\\langle p_e,c_2 \\rangle \\hookrightarrow \\langle p,c_2 \\rangle$}\n    \\end{itemize}\n    \\caption{The result of calling \\texttt{Nwa\\-To\\-Backwards\\-Wpds\\-Returns} on \\figref{NwaToWpds1}}\n    \\label{Fi:NwaToWpds3}\n  \\end{minipage}\n\\end{figure}\n", "meta": {"hexsha": "7cf4c7c2e85244bcf743fbc08853a960a017431e", "size": 28565, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Doc/opennwa/04-conversions.tex", "max_stars_repo_name": "jusito/WALi-OpenNWA", "max_stars_repo_head_hexsha": "2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2015-03-07T17:25:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T20:17:00.000Z", "max_issues_repo_path": "Doc/opennwa/04-conversions.tex", "max_issues_repo_name": "jusito/WALi-OpenNWA", "max_issues_repo_head_hexsha": "2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-03-03T05:58:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-03T12:26:10.000Z", "max_forks_repo_path": "Doc/opennwa/04-conversions.tex", "max_forks_repo_name": "jusito/WALi-OpenNWA", "max_forks_repo_head_hexsha": "2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2015-09-25T17:44:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-18T18:25:38.000Z", "avg_line_length": 44.4937694704, "max_line_length": 135, "alphanum_fraction": 0.690915456, "num_tokens": 9393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.30199935010637097}}
{"text": "% Machine Learning\nA machine is said to be learning from past Experiences(data feed in) with respect to some class of Tasks, if it's Performance in a given Task improves with the Experience.\n\nAccording to a famous person, Machine Learning is a system that can learn from example through self-improvement and without being explicitly coded by programmer. The breakthrough comes with the idea that a machine can singularly learn from the data (\\textit{i.e.} media database of real life objects, numbers dataset from algorithms, face images, job dtabase) to produce accurate results.\n\nMachine learning combines data with statistical tools to predict an output. This output is then used by corporate to makes actionable insights. Machine learning is closely related to data mining and Bayesian predictive modeling. The machine receives data as input, use an algorithm to formulate answers.\n\nA typical machine learning tasks are to provide a recommendation. For those who have a Netflix account, all recommendations of movies or series are based on the user's historical data. Tech companies are using unsupervised learning to improve the user experience with personalizing recommendation.\n\n\\subsection{Machine Learning vs. Traditional Programming}\nTraditional programming differs significantly from machine learning. In traditional programming, a programmer code all the rules in consultation with an expert in the industry for which software is being developed. Each rule is based on a logical foundation; the machine will execute an output following the logical statement. When the system grows complex, more rules need to be written. It can quickly become unsustainable to maintain.\n\nMachine learning is supposed to overcome this issue. The machine learns how the input and output data are correlated and it writes a rule. The programmers do not need to write new rules each time there is new data. The algorithms adapt in response to new data and experiences to improve efficacy over time.\n\n\\subsection{How does Machine learning work}\nMachine learning is the virtual brain where all the learning takes place. The way the machine learns is similar to the human being. Humans learn from experience. The more we know, the more easily we can predict. By analogy, when we face an unknown situation, the likelihood of success is lower than the known situation. Machines are trained the same. To make an accurate prediction, the machine sees an example. When we give the machine a similar example, it can figure out the outcome. However, like a human, if its feed a previously unseen example, the machine has difficulties to predict.\n\nThe core objective of machine learning is the learning and inference. First of all, the machine learns through the discovery of patterns. This discovery is made thanks to the data. One crucial part of the data scientist is to choose carefully which data to provide to the machine. The list of attributes used to solve a problem is called a feature vector. You can think of a feature vector as a subset of data that is used to tackle a problem.\n\nThe machine uses some fancy algorithms to simplify the reality and transform this discovery into a model. Therefore, the learning stage is used to describe the data and summarize it into a model.\n\nFor instance, the machine is trying to understand the relationship between the wage of an individual and the likelihood to go to a fancy restaurant. It turns out the machine finds a positive relationship between wage and going to a high-end restaurant: This is the model\n\n\\subsubsection{Inferring}\nWhen the model is built, it is possible to test how powerful it is on never-seen-before data. The new data are transformed into a features vector, go through the model and give a prediction. This is all the beautiful part of machine learning. There is no need to update the rules or train again the model. You can use the model previously trained to make inference on new data.\n\nThe life of Machine Learning programs is straightforward and can be summarized in the following points:\n\\begin{enumerate}\n\\item Define a question\n\\item Collect data\n\\item Visualize data\n\\item Train algorithm\n\\item Test the Algorithm\n\\item Collect feedback\n\\item Refine the algorithm\n\\item Loop 4-7 until the results are satisfying\n\\item Use the model to make a prediction\n\\end{enumerate}\n\nThere are two main types of Learning,\n\\subsubsection{Supervised learning}\nAn algorithm uses training data and feedback from humans to learn the relationship of given inputs to a given output. For instance, a practitioner can use marketing expense and weather forecast as input data to predict the sales of cans.\n\nYou can use supervised learning when the output data is known. The algorithm will predict new data.\n\nThere are two categories of supervised learning:\n\\paragraph{Classification}\nImagine you want to predict the gender of a customer for a commercial. You will start gathering data on the height, weight, job, salary, purchasing basket, etc. from your customer database. You know the gender of each of your customer, it can only be male or female. The objective of the classifier will be to assign a probability of being a male or a female (\\textit{i.e.}, the label) based on the information (\\textit{i.e.}, features you have collected). When the model learned how to recognize male or female, you can use new data to make a prediction. For instance, you just got new information from an unknown customer, and you want to know if it is a male or female. If the classifier predicts male = 70\\%, it means the algorithm is sure at 70\\% that this customer is a male, and 30\\% it is a female.\n\nThe label can be of two or more classes. The above example has only two classes, but if a classifier needs to predict object, it has dozens of classes (\\textit{e.g.} glass, table, shoes, etc. each object represents a class).\n\n\\paragraph{Regression}\nWhen the output is a continuous value, the task is a regression. For instance, a financial analyst may need to forecast the value of a stock based on a range of feature like equity, previous stock performances, macroeconomics index. The system will be trained to estimate the price of the stocks with the lowest possible error.\n\n\\subsubsection{Unsupervised learning}\nIn unsupervised learning, an algorithm explores input data without being given an explicit output variable (\\textit{e.g.} explores customer demographic data to identify patterns)\n\nYou can use it when you do not know how to classify the data, and you want the algorithm to find patterns and classify the data for you\n\nChallenges and Limitations of Machine learning\nThe primary challenge of machine learning is the lack of data or the diversity in the dataset. A machine cannot learn if there is no data available. Besides, a dataset with a lack of diversity gives the machine a hard time. A machine needs to have heterogeneity to learn meaningful insight. It is rare that an algorithm can extract information when there are no or few variations. It is recommended to have at least 20 observations per group to help the machine learn. This constraint leads to poor evaluation and prediction.\n\n\\subsection{Application}\nThere are plenty of application fields where ML is being used for better performance,\n\\subsubsection{Augmentation}\nMachine learning, which assists humans with their day-to-day tasks, personally or commercially without having complete control of the output. Such machine learning is used in different ways such as Virtual Assistant, Data analysis, software solutions. The primary user is to reduce errors due to human bias.\n\\subsubsection{Automation}\nMachine learning, which works entirely autonomously in any field without the need for any human intervention. For example, robots performing the essential process steps in manufacturing plants.\n\\subsubsection{Finance Industry}\nMachine learning is growing in popularity in the finance industry. Banks are mainly using ML to find patterns inside the data but also to prevent fraud.\n\\subsubsection{Government organization}\nThe government makes use of ML to manage public safety and utilities. Take the example of China with the massive face recognition. The government uses Artificial intelligence to prevent jaywalker.\n\\subsubsection{Healthcare industry}\nHealthcare was one of the first industry to use machine learning with image detection.\n\\subsubsection{Marketing}\nBroad use of AI is done in marketing thanks to abundant access to data. Before the age of mass data, researchers develop advanced mathematical tools like Bayesian analysis to estimate the value of a customer. With the boom of data, marketing department relies on AI to optimize the customer relationship and marketing campaign.\n\\subsubsection{Supply Chain}\nMachine learning gives terrific results for visual pattern recognition, opening up many potential applications in physical inspection and maintenance across the entire supply chain network.\n\nUnsupervised learning can quickly search for comparable patterns in the diverse dataset. In turn, the machine can perform quality inspection throughout the logistics hub, shipment with damage and wear.\n\nFor instance, IBM's Watson platform can determine shipping container damage. Watson combines visual and systems-based data to track, report and make recommendations in real-time.\n\nIn past year stock manager relies extensively on the primary method to evaluate and forecast the inventory. When combining big data and machine learning, better forecasting techniques have been implemented (an improvement of 20 to 30 \\% over traditional forecasting tools). In term of sales, it means an increase of 2 to 3 \\% due to the potential reduction in inventory costs.\n\n\\paragraph{Google Car}\nFor example, everybody knows the Google car \\textbf{Waymo}. The car is full of lasers on the roof which are telling it where it is regarding the surrounding area. It has radar in the front, which is informing the car of the speed and motion of all the cars around it. It uses all of that data to figure out not only how to drive the car but also to figure out and predict what potential drivers around the car are going to do. What's impressive is that the car is processing almost a gigabyte a second of data.\n\n\nFor our case we use logistic regression (discussed in Appendix app:4) and the algorithm is discussed in Proposal chapter \\ref{ch:3}.\n", "meta": {"hexsha": "b0c57a1d100be9cd0ec6a5d27dda0c82af296609", "size": 10360, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/thesis/doc_src/ml.tex", "max_stars_repo_name": "TheScienceUniverse/BlockChain", "max_stars_repo_head_hexsha": "03c33fabfa702fad7f6e3a9de5757a2ccda2d909", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/thesis/doc_src/ml.tex", "max_issues_repo_name": "TheScienceUniverse/BlockChain", "max_issues_repo_head_hexsha": "03c33fabfa702fad7f6e3a9de5757a2ccda2d909", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/thesis/doc_src/ml.tex", "max_forks_repo_name": "TheScienceUniverse/BlockChain", "max_forks_repo_head_hexsha": "03c33fabfa702fad7f6e3a9de5757a2ccda2d909", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 113.8461538462, "max_line_length": 806, "alphanum_fraction": 0.8090733591, "num_tokens": 2030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.30199935010637097}}
{"text": "\\documentclass[a4paper]{article}\n\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{hyperref}\n\\usepackage{graphicx}\n\\usepackage{geometry}\n\n\\geometry{\n    letterpaper,\n    left=   1.5in,\n    right=  1.5in,\n    top=    1.3in,\n    bottom= 1.4in\n}\n\n\\newcommand{\\partd}[2]{\\frac{\\partial #1}{\\partial #2}}\n\\newcommand{\\dih}{\\mathrel{\\rm dih}}\n\n\n\\parindent=0mm\n\\parskip=5pt\n\n\\title{A Tool for Formal Verification of Nonlinear Inequalities}\n\n\\author{Alexey Solovyev}\n\n% Document\n\\begin{document}\n% Title\n\\maketitle\n\n% Content\n\\tableofcontents\n\n\\pagebreak\n% References\n\\begin{thebibliography}{9}\n\\bibitem{HOL} HOL Light home page\\\\ \n  \\url{http://www.cl.cam.ac.uk/~jrh13/hol-light}\n\n\\bibitem{HOL-repo} HOL Light repository\\\\\n  \\url{https://github.com/jrh13/hol-light}\n\n\\bibitem{HOL-tutorial} HOL Light tutorial\\\\\n\t\\url{http://www.cl.cam.ac.uk/~jrh13/hol-light/tutorial_220.pdf}\n\n\\bibitem{flyspeck} The Flyspeck project\\\\\n\t\\url{https://github.com/flyspeck/flyspeck}\n\n\\bibitem{bernstein}C\\'esar Mu\\~noz and Anthony Narkawicz, {\\it Formalization of a Representation of Bernstein Polynomials and Applications to Global Optimization}, Journal of Automated Reasoning, DOI: 10.1007/s10817-012-9256-3\\\\\n\t\\url{http://shemesh.larc.nasa.gov/people/cam/Bernstein/}\n\\end{thebibliography}\n\n% Introduction\n\\section{Introduction}\nThis document describes a tool for verification of nonlinear inequalities in HOL Light proof assistant~\\cite{HOL, HOL-tutorial}. This tool was developed as a part of the Flyspeck project (a formal proof of the Kepler conjecture)~\\cite{flyspeck}. The tool is capable to verify multivariate nonlinear strict inequalities on rectangular domains. More specifically, the tool can handle inequalities in the form\n\\[\\forall {\\bf x} \\in D \\implies f({\\bf x}) < g({\\bf x}),\\]\nwhere $D = \\{(x_1, \\ldots, x_n)\\ |\\ a_i \\le x_i \\le b_i\\}$ and $f$, $g$ are functions which may include all usual arithmetic operations, square roots, arccosines, and arctangents. The maximal number of variables is 8. Future releases of the tool will include all elementary functions and will have no restriction on the number of variables. Moreover, it will be possible to verify inequalities on non-rectangular domains.\n\nInternally, the tool uses interval arithmetic with Taylor approximations (with second-order error terms).\n\nThe document is organized as follows. The next section describes the installation process. Then a quick introduction of tool functions is presented. After that, a more detailed description of tool functions is given and special options are described. The last two sections describe several examples and test cases.\n\n\n% Installation\n\\section{Installation}\nFirst of all, if you don't have OCaml and HOL Light installed, then you need to install them. The verification tool was tested with Ocaml 3.09.3 and Ocaml 3.12.1 and with one of the latest versions of HOL Light (r149 in the HOL Light repository).  HOL Light installation instructions can be found in John Harrison's HOL Light tutorial~\\cite{HOL-tutorial}.\n\nAlternatively, one can download and run the following script written by Alex Krauss: \\url{https://bitbucket.org/akrauss/hol-light-workbench}. This script will download and install the latest version of HOL Light and other necessary programs.\n\nThe installation of the tool for verification of nonlinear inequalities is very simple. Download the distribution from\n\n\\vspace{-5pt}\n\\url{http://code.google.com/p/flyspeck/downloads/list}\n\n\\vspace{-5pt}\nor get the latest version from the Flyspeck repository with the shell command\n\n\\vspace{-5pt}\n\\verb|svn co http://flyspeck.googlecode.com/svn/trunk/formal_ineqs|\n\n\nThe tool can be placed in any directory on your computer. It is important to inform HOL Light about tool's location. It can be done with the following OCaml command:\n\n\\verb|load_path := \"path to the tool directory\" :: !load_path;;|\n\nAfter the path is set, the tool can be loaded with the command\n\n\\verb|needs \"verifier/m_verifier_main.hl\";;|\n\nThe tool loads the standard HOL Light library \\verb|Multivariate/realanalysis.ml|. The loading process of this library could take pretty long time, so it is recommended to use a checkpointed version of HOL Light with preloaded multivariate analysis libraries.\n\nBefore loading the tool, it is also possible to change some global options. These options are described in section \\ref{global}.\n\n\n% Examples\n\\section{Quick Start}\n\nThe polynomial inequality\n\\begin{multline*}\n-\\frac{1}{\\sqrt{3}} \\le x \\le \\sqrt{2},\\ -\\sqrt{\\pi} \\le y \\le 1\n\\implies x^2 y - x y^4 + y^6 + x^4 - 7 > -7.17995\n\\end{multline*}\ncan be verified with the following script\n\n\\begin{verbatim}\n(* make sure that load_path contains the path to formal_ineqs *)\nneeds \"verifier/m_verifier_main.hl\";;\nopen M_verifier_main;;\n\nlet ineq = \n  `-- &1 / sqrt(&3) <= x /\\ x <= sqrt(&2) /\\ \n   -- sqrt(pi) <= y /\\ y <= &1\n   ==> x pow 2 * y - x * y pow 4 + y pow 6 - &7 + x pow 4 > -- #7.17995`;;\n\nlet th, stats = verify_ineq default_params 5 ineq;;\n\\end{verbatim}\n\nThe first parameter of the verification function \\verb|verify_ineq| contains verification options. We use default values given by the constant \\verb|default_params|. Available options are described in section \\ref{verification}.\n\nThe second parameter specifies the precision of formal floating point operations. This parameter determines the maximal number of significant digits of any result returned by a formal floating point operation. Here, digits are not decimal. Internally all natural numbers are represented using a fixed base (see section \\ref{global} for more details). This base is relatively large (the default value is 100) to speed up arithmetic operations. Actual precision of formal floating point operations depends on the precision parameter and on the base of the internal representation of natural numbers. If the base value is 100 and the precision parameter is 5 as in the example above, then the precision of formal floating point operations is 10 decimal digits: $100^5 = 10^{10}$. Note that the verification of the example will fail if the precision parameter is 4 or less. On the other hand, if the precision parameter is 10, the verification will succeed but it will take a little more time.\n\nThe third parameter is the inequality itself given as a HOL Light term. The format of this term is simple: it is an implication with bounds of variables in the antecedent and an inequality in the consequent. The bounds of all variables should be in the form $\\text{\\it a constant expression} <= x$ or $x <= \\text{\\it a constant expression}$. For each variable, upper and lower bounds must be given. The inequality must be a strict inequality ($<$ or $>$). The inequality may include \\verb|sqrt|, \\verb|atn|, and \\verb|acs| functions. The constant \\verb|pi| ($\\pi$) is also allowed.\n\nThe verification function returns a HOL Light theorem and a record with some verification information which includes verification time.\n\n\n% Verification Functions\n\\section{Verification Functions}\\label{verification}\nThe main verification function \\verb|verify_ineq| is contained in \\verb|M_verifier_main| module defined in \\verb|verifier/m_verifier_main.hl|. The function has 3 arguments and its type is\n\\begin{verbatim}\nverify_ineq : verification_parameters -> int -> term -> thm * verification_stats\n\\end{verbatim}\n\nThe first parameter contains verification options defined in the following record\n\\begin{verbatim}\ntype verification_parameters =\n{\n  (* If true, then monotonicity properties can be used *)\n  (* to reduce the dimension of a problem *)\n  allow_derivatives : bool;\n  (* If true, then convexity can be used *)\n  (* to reduce the dimension of a problem *)\n  convex_flag : bool;\n  (* If true, then verification on internal subdomains can be skipped *)\n  (* for a monotone function *)\n  mono_pass_flag : bool;\n  (* If true, then raw interval arithmetic can be used *)\n  (* (without Taylor approximations) *)\n  raw_intervals_flag : bool;\n  (* If true, then an informal procedure is used to determine *)\n  (* the optimal precision for the formal verification *)\n  adaptive_precision : bool;\n  (* This parameter might be used in cases when the certificate search *)\n  (* procedure returns a wrong result due to rounding errors *)\n  (* (this parameter will be eliminated when the search procedure is corrected) *)\n  eps : float;\n};;\n\\end{verbatim}\nA detailed description of these parameter is omitted in this document. In most cases, it is enough to use the constant \\verb|default_params| which turns all verification flags on and sets \\verb|eps = 0|. In rare cases, it is necessary to adjust \\verb|eps| to get a result. This can be done with the command\n\\begin{verbatim}\nverify_ineq {default_params with eps = 1e-10} 5 ineq_tm;;\n\\end{verbatim}\n\nThe second parameter of the verification function specifies the precision of formal floating point operations. This parameter determines the maximal number of significant digits of any result returned by a formal floating point operation. Here, digits are not decimal. Internally all natural numbers are represented using a fixed base (see section \\ref{global} for more details). This base is relatively large (the default value is 100) to speed up arithmetic operations. Actual precision of formal floating point operations depends on the precision parameter and on the base of the internal representation of natural numbers. In many cases, if the verification function fails, it is enough to increase the precision parameter to get a result.\n\nThe third parameter of the verification function is a HOL Light term which specifies an inequality itself. The format of this term is the following:\n\\begin{verbatim}\nbounds of variables ==> an inequality\n\\end{verbatim}\nThe bounds of all variables should be in the form $\\text{\\it a constant expression} <= x$ or $x <= \\text{\\it a constant expression}$. For each variable, upper and lower bounds must be provided. The order in which the bounds are given is irrelevant. Bounds of variables may be connected with \\verb|/\\| or with \\verb|==>|. The inequality must be a strict inequality ($<$ or $>$). The inequality may include \\verb|sqrt|, \\verb|atn|, and \\verb|acs| functions. The constant \\verb|pi| ($\\pi$) is also allowed.\n\nThe verification function returns a theorem and some verification information defined in the record\n\\begin{verbatim}\ntype verification_stats =\n{\n  total_time : float;\n  formal_verification_time : float;\n  certificate : Verifier.certificate_stats;\n};;\n\\end{verbatim}\nThe field \\verb|total_time| contains total verification time. The field \\verb|formal_verification_time| contains time taken by the formal verification procedure only (this time doesn't include time for constructing a solution certificate and for other preparations). The last field \\verb|certificate| contains information about a solution certificate.\n\nThe conclusion of the returned theorem is not exactly the same as the third parameter of the verification function: the order of bounds of variables may be altered and variables which are not used in the inequality are eliminated. For example, commands\n\\begin{verbatim}\nlet th1, _ = verify_ineq default_params 3 \n  `&1 <= y /\\ y <= &2 /\\ &1 <= x /\\ x <= &3 ==> x + y < &6`;;\nlet th2, _ = verify_ineq default_params 3 \n  `&1 <= y /\\ y <= &2 /\\ &1 <= x /\\ x <= &3 ==> y < &3`;;\n\\end{verbatim}\nreturn\n\\begin{verbatim}\nth1 = |- (&1 <= x /\\ x <= &3) /\\ &1 <= y /\\ y <= &2 ==> x + y < &6\nth2 = |- &1 <= y /\\ y <= &2 ==> y < &3\n\\end{verbatim}\n\n\n\n% Options\n\\section{Global Options}\\label{global}\nThe options which affect the arithmetic operations with natural and floating point numbers must be set before the verification tool is loaded. After the verification tool is loaded, arithmetic options may not be changed. To set arithmetic options, load the file \\verb|arith_options.hl| located in the root directory of the tool. The available options are listed below.\n\n\\begin{enumerate}\n% base\n\\item[\\bf base] Determines the base for representing natural numbers. Default HOL Light \nrepresentation of natural numbers is binary (i.e., its base is 2). A higher base increases speed of arithmetic operations but it also requires more memory to remember additional theorems. The default value of the base is \\verb|100|. To set a new base, use the command\n\n\\verb|Arith_options.base := 200;;|\n\n% min_exp\n\\item[\\bf min\\_exp] Determines the minimal exponent in the representation of floating point numbers. Each floating point number is represented as a triple $(s, n, e)$ where $s$ is a boolean value which determines the sign of the number, $n$ and $e$ are natural numbers which represent the mantissa and the exponent. The value corresponding to $(s, n, e)$ is given by\n\n\\[f = (-1)^{\\text{if $s$ then $1$ else $0$}} \\times n \\times b^{e - min\\_exp}\\]\nwhere $b$ is the base of the representation of natural numbers.\n\n% cached\n\\item[\\bf cached] If this value is true, then results of all natural number operations are cached. The default value is \\verb|true|.\n\n% float_cached\n\\item[\\bf float\\_cached] If this value is true, then results of all floating point operations are cached. The default value is \\verb|true|.\n\n% init_cache_size\n\\item[\\bf init\\_cache\\_size] Determines the initial size of the cache for results of arithmetic operations. The default value is \\verb|10000|.\n\n% max_cache_size\n\\item[\\bf max\\_cache\\_size] Determines the maximal size of the cache for results of arithmetic operations. The default value is \\verb|20000|. Note: each cached operation has its own cache.\n\n\\end{enumerate}\n\nThe file \\verb|verifier_options.hl| contains the option \\verb|info_print_level| which controls the amount of information printed by a verification process. This option can be changed at any time:\n\n\\verb|Verifier_options.info_print_level := 0;;|\n\nPossible values are: 0~(no information is printed); 1~(all essential information is printed); 2~(all information is printed). The default value is 1.\n\nThe next example shows how to change default options:\n\\begin{verbatim}\n(* The arithmetic options must be set before loading the verification tool *)\nneeds \"arith_options.hl\";;\n\n(* Increase the arithmetic base *)\nArith_options.base := 200;;\n\n(* Increase the cache size *)\nArith_options.max_cache_size = 40000;;\n\n(* Load the verification tool *)\nneeds \"verifier/m_verifier_main.hl\";;\n\n(* The verification option can be changed at any time *)\nVerifier_options.info_print_level := 2;;\n\nopen M_verifier_main;;\n\\end{verbatim}\n\n% Additional Examples\n\\section{Additional Examples}\nThe verification tool distribution contains several example files. The file \\verb|examples_poly.hl| contains polynomial inequalities from the paper \\cite{bernstein}. The command\n\n\\verb|needs \"examples_poly.hl\";;|\n\nwill load this file and run all polynomial inequality tests. To run all tests again, type \\verb|run_tests();;|\n\nTo run a specific test, type \\verb|run_{test_name}();;| where \\verb|{test_name}| is one of the following: \\verb|schwefel|, \\verb|rd|, \\verb|caprasse|, \\verb|lv|, \\verb|butcher|, \\verb|magnetism|, \\verb|heart|.\n\nHere is the list of all examples.\n\\begin{itemize}\n% schwefel\n\\item[\\bf schwefel]\n\\begin{eqnarray*}\n&-5.8806 \\times 10^{-10} < (x_1 - x_2^2)^2 + (x_2 - 1)^2 + (x_1 - x_3^2)^2 + (x_3 - 1)^2\\\\\n&(x_1, x_2, x_3) \\in [(-10,-10,-10),(10,10,10)]\n\\end{eqnarray*}\n\n% rd\n\\item[\\bf rd] \n\\begin{eqnarray*}\n&-36.7126907 < -x_1 + 2 x_2 - x_3 - 0.835634534\\, x_2 (1 + x_2)\\\\\n&(x_1, x_2, x_3) \\in [(-5,-5,-5),(5,5,5)]\n\\end{eqnarray*}\n\n% caprasse\n\\item[\\bf caprasse]\n\\begin{eqnarray*}\n&-3.1801 < -x_1 x_3^3 + 4 x_2 x_3^2 x_4 + 4 x_1 x_3 x_4^2 + 2 x_2 x_4^3 + 4 x_1 x_3 + 4 x_3^2 - 10 x_2 x_4 - 10 x_4^2 + 2\\\\\n&(x_1, x_2, x_3, x_4) \\in [(-0.5,-0.5,-0.5,-0.5),(0.5,0.5,0.5,0.5)]\n\\end{eqnarray*}\n\n% lv\n\\item[\\bf lv]\n\\begin{eqnarray*}\n&-20.801 < x_1 x_2^2 + x_1 x_3^2 + x_1 x_4^2 - 1.1 x_1 + 1\\\\\n&(x_1, x_2, x_3, x_4) \\in [(-2,-2,-2,-2), (2,2,2,2)]\n\\end{eqnarray*}\n\n% butcher\n\\item[\\bf butcher]\n\\begin{eqnarray*}\n&-1.44 < x_6 x_2^2 + x_5 x_3^2 - x_1 x_4^2 + x_4^2 - \\frac{1}{3} x_1 + \\frac{4}{3} x_4\\\\\n&(x_1, x_2, x_3, x_4, x_5, x_6) \\in [(-1,-0.1, -0.1, -1, -0.1, -0.1), (0,0.9,0.5,-0.1,-0.05,-0.03)]\n\\end{eqnarray*}\n\n% magnetsim\n\\item[\\bf magnetism]\n\\begin{eqnarray*}\n&-0.25001 < x_1^2 + 2 x_2^2 + 2 x_3^2 + 2 x_4^2 + 2 x_5^2 + 2 x_6^2 + 2 x_7^2 - x_1\\\\\n&(x_1,x_2,x_3,x_4,x_5,x_6,x_7) \\in [(-1,-1,-1,-1,-1,-1,-1), (1,1,1,1,1,1,1)]\n\\end{eqnarray*}\n\n% heart\n\\item[\\bf heart]\n\\begin{equation*}\n\\begin{split}\n&-1.7435 < -x_1 x_6^3 + 3 x_1 x_6 x_7^2 - x_3 x_7^3 + 3 x_3 x_7 x_6^2 - x_2 x_5^3 + 3 x_2 x_5 x_8^2 - x_4 x_8^3 + 3 x_4 x_8 x_5^2 - 0.9563453\\\\\n&(x_1,x_2,x_3,x_4,x_5,x_6,x_7,x_8) \\in [(-0.1, 0.4, -0.7, -0.7, 0.1, -0.1, -0.3, -1.1),\\\\ &\\phantom{(x_1,x_2,x_3,x_4,x_5,x_6,x_7,x_8) \\in [ }(0.4, 1, -0.4, 0.4, 0.2, 0.2, 1.1, -0.3)]\n\\end{split}\n\\end{equation*}\n\\end{itemize}\n\nThe file \\verb|examples_flyspeck.hl| contains some inequalities from the Flyspeck project~\\cite{flyspeck}. The command\n\n\\verb|needs \"examples_flyspeck.hl\";;|\n\nwill load this file and run some easy inequality tests. To rerun these tests, use the command \\verb|test_easy();;|. To run more difficult tests, type \\verb|test_medium();;| or \\verb|test_hard();;|.\n(Warning: medium tests require about 30 minutes, hard tests require more than 5 hours.)\n\nSome Flyspeck inequalities are listed below.\n\\begin{eqnarray*}\n\\Delta(x_1,\\ldots,x_6) &= &x_1 x_4(-x_1 + x_2 + x_3 - x_4 + x_5 + x_6)\\\\\n&& + x_2 x_5(x_1 - x_2 + x_3 + x_4 - x_5 + x_6)\\\\\n&& + x_3 x_6(x_1 + x_2 - x_3 + x_4 + x_5 - x_6)\\\\\n&& - x_2 x_3 x_4 - x_1 x_3 x_5 - x_1 x_2 x_6 - x_4 x_5 x_6,\\\\[6pt]\n\\Delta_4 &=& \\partd{\\Delta}{x_4},\\\\[6pt]\n\\dih_x(x_1,\\ldots,x_6) &=& \\frac{\\pi}{2} - \\arctan\\left(\\frac{-\\Delta_4(x_1,\\ldots,x_6)}{\\sqrt{4 x_1 \\Delta(x_1,\\ldots,x_6)}}\\right),\\\\[6pt]\n\\dih_y(y_1,\\ldots,y_6) &=& \\dih_x(y_1^2, \\ldots, y_6^2).\n\\end{eqnarray*}\n\n\\begin{itemize}\n% 1\n\\item[\\bf 4717061266]\n\\begin{eqnarray*}\n\\Delta(x_1, x_2, x_3, x_4, x_5, x_6) > 0,\\quad 4 \\le x_i \\le 6.3504\n\\end{eqnarray*}\n\n% 2\n\\item[\\bf 7067938795]\n\\begin{eqnarray*}\n&\\dih_x (x_1, \\ldots, x_6) - \\pi/2 + 0.46 < 0,\\\\\n&4 \\le x_{1,2,3} \\le 6.3504,\\ x_4 = 4,\\ 3.01^2 \\le x_{5,6} \\le 3.24^2\n\\end{eqnarray*}\n\n% 3\n\\item[\\bf 3318775219]\n\\begin{eqnarray*}\n&\\begin{split}\n0 < &\\dih_y (y_1, \\ldots, y_6) - 1.629 + 0.414 (y_2 + y_3 + y_5 + y_6 - 8.0)\\\\\n\t&- 0.763 (y_4 - 2.52) - 0.315 (y_1 - 2.0),\n\\end{split}\\\\\n&2 \\le y_i \\le 2.52\n\\end{eqnarray*}\n\n\\end{itemize}\n\n% Test Results\n\\section{Test Results}\nThis section contains time test results for inequalities described in the previous section. All tests were performed on Intel Core i5, 2.67GHz running Ubuntu 9.10 inside Virtual Box 4.2.0 on a Windows 7 host; the Ocaml version was 3.09.3; the base of arithmetic was 200; the caching was turned on.\n\n\\begin{center}\nPolynomial inequalities\n\n\\begin{tabular}{l@{\\quad} r r r r r}\n%{r@{\\quad}rl}\n\\hline\n\\multicolumn{1}{l}{\\rule{0pt}{12pt}Inequality ID}&\n\\multicolumn{1}{l}{\\phantom{x}\\# variables}&\n\\multicolumn{1}{l}{\\phantom{x}precision}&\n\\multicolumn{1}{l}{\\phantom{x}total time (s)}&\n\\multicolumn{1}{l}{\\phantom{x}formal verification (s)}\\\\\n\\hline\\rule{0pt}{12pt}%\nschwefel\t& 3\t& 5\t\t& 26.329 &\t19.145 \\\\\nrd\t\t\t& 3 & 5\t\t& 1.593 &\t0.017 \\\\\ncaprasse\t& 4 & 5\t\t& 8.057\t&\t1.286 \\\\\nlv\t\t\t& 4\t& 5\t\t& 1.875 &\t0.030 \\\\\nbutcher\t\t& 6 & 5\t\t& 3.609 &\t0.035 \\\\\nmagnetism\t& 7 & 5\t\t& 7.007 &\t1.347 \\\\\nheart\t\t& 8 & 5\t\t& 17.298 &\t1.277 \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\n\\begin{center}\nFlyspeck inequalities\n\n\\begin{tabular}{l@{\\quad} r r r r r}\n%{r@{\\quad}rl}\n\\hline\n\\multicolumn{1}{l}{\\rule{0pt}{12pt}Inequality ID}&\n\\multicolumn{1}{l}{\\phantom{x}precision}&\n\\multicolumn{1}{l}{\\phantom{x}total time (s)}&\n\\multicolumn{1}{l}{\\phantom{x}formal verification (s)}\\\\\n\\hline\\rule{0pt}{12pt}%\n2485876245a\t& 4 & 5.530 & 0.058 \\\\\n4559601669b & 4 & 4.679 & 0.048 \\\\\n4717061266  & 4 & 27.1 & 0.250 \\\\\n5512912661  & 4 & 8.860 & 0.086 \\\\\n6096597438a & 4 & 0.071 & 0.071 \\\\\n6843920790  & 4 & 2.824 & 0.076 \\\\\nSDCCMGA b   & 4 & 9.012 & 0.949 \\\\\nTSKAJXY-TADIAMB\\footnotemark[1] & 4 & 75.9 & 21.2 \\\\\n7067938795  & 4 & 431   & 387 \\\\\n5490182221  & 4 & 1726  & 1533 \\\\\n3318775219  & 4 & 17091 & 15226 \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\footnotetext[1]{Reduced to a polynomial inequality}\n\n\\end{document}\n\n\n\n", "meta": {"hexsha": "5604823e1c90f5b25b4937f4c2cb9b904be6893e", "size": 20177, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/FormalVerifier.tex", "max_stars_repo_name": "monadius/formal_ineqs", "max_stars_repo_head_hexsha": "2c92cd529cc6310738e71f38f8ced40566cb05d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 125, "max_stars_repo_stars_event_min_datetime": "2016-03-22T22:29:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T05:43:43.000Z", "max_issues_repo_path": "docs/FormalVerifier.tex", "max_issues_repo_name": "monadius/formal_ineqs", "max_issues_repo_head_hexsha": "2c92cd529cc6310738e71f38f8ced40566cb05d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2015-10-13T17:38:34.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-26T19:54:19.000Z", "max_forks_repo_path": "docs/FormalVerifier.tex", "max_forks_repo_name": "monadius/formal_ineqs", "max_forks_repo_head_hexsha": "2c92cd529cc6310738e71f38f8ced40566cb05d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2017-06-21T08:48:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-13T02:07:27.000Z", "avg_line_length": 47.6997635934, "max_line_length": 989, "alphanum_fraction": 0.7217624027, "num_tokens": 6360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.30199935010637097}}
{"text": "\\documentclass[11pt]{amsart}\n\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{tikz}\n\\usepackage{pgfplots}\n\\usepackage{xcolor}\n\n\\usetikzlibrary{\n  arrows,\n  calc,\n  decorations.markings,\n  decorations.pathreplacing,\n  dsp,\n  fit,\n  positioning\n}\n\\input{../util/airfoils.tex}\n\\input{../util/wing.tex}\n\\input{../util/coordinate_systems.tex}\n\\input{../util/control.tex}\n\n\\newcommand{\\aero}{\\mathrm{aero}}\n\\newcommand{\\airgrid}{\\mathrm{air-grid}}\n\\newcommand{\\app}{a}\n\\newcommand{\\climb}{\\mathrm{climb}}\n\\newcommand{\\cmd}{\\mathrm{cmd}}\n\\newcommand{\\cutin}{\\mathrm{cut-in}}\n\\newcommand{\\cutout}{\\mathrm{cut-out}}\n\\newcommand{\\cw}{\\mathrm{cw}}\n\\newcommand{\\eff}{\\mathrm{eff}}\n\\newcommand{\\extra}{\\mathrm{extra}}\n\\newcommand{\\figureeight}{\\mathrm{figure-eight}}\n\\newcommand{\\grav}{\\mathrm{grav}}\n\\newcommand{\\groundinverter}{\\mathrm{ground\\;inv.}}\n\\newcommand{\\hover}{\\mathrm{hover}}\n\\newcommand{\\kiteinverter}{\\mathrm{kite\\;inv.}}\n\\newcommand{\\kite}{\\mathrm{kite}}\n\\newcommand{\\lp}{\\mathrm{loop}}\n\\newcommand{\\mx}{\\mathrm{max}}\n\\newcommand{\\mn}{\\mathrm{min}}\n\\newcommand{\\motor}{\\mathrm{motor}}\n\\newcommand{\\nominal}{\\mathrm{nom}}\n\\newcommand{\\path}{\\mathrm{path}}\n\\newcommand{\\prop}{\\mathrm{prop}}\n\\newcommand{\\shaftgrid}{\\mathrm{shaft-grid}}\n\\newcommand{\\swept}{\\mathrm{swept}}\n\\newcommand{\\tether}{\\mathrm{tether}}\n\\newcommand{\\total}{\\mathrm{tot}}\n\\newcommand{\\wind}{\\mathrm{wind}}\n\\newcommand{\\mass}{\\mathrm{mass}}\n\\newcommand{\\power}{\\mathrm{power}}\n\\newcommand{\\powertrain}{\\mathrm{powertrain}}\n\\newcommand{\\motorout}{\\mathrm{motor-out}}\n\n\\definecolor{matlab1}{rgb}{0, 0.4470, 0.7410}\n\\definecolor{matlab2}{rgb}{0.8500, 0.3250, 0.0980}\n\\definecolor{matlab3}{rgb}{0.9290, 0.6940, 0.1250}\n\\definecolor{matlab4}{rgb}{0.4940, 0.1840, 0.5560}\n\\definecolor{matlab5}{rgb}{0.4660, 0.6740, 0.1880}\n\\definecolor{matlab6}{rgb}{0.3010, 0.7450, 0.9330}\n\\definecolor{matlab7}{rgb}{0.6350, 0.0780, 0.1840}\n\n\\title{Limits on kite mass}\n\\author{Makani Technologies LLC}\n\\date{October 6, 2016}\n\n\\begin{document}\n\\maketitle\n\n% \\section*{Nomenclature}\n\n% \\begin{tabular}{ll}\n%   $m_{\\kite}$       & Kite mass \\\\\n%   $m_{\\total}$      & Combined kite and tether mass \\\\\n%   $m_{\\eff}$        & Effective mass ($m_{\\eff} = m_{\\kite} + m_{\\tether}/3)$ for modeling dynamics \\\\\n%   $\\mathit{TWR}$    & Thrust-to-weight ratio \\\\\n%   $\\eta_{\\airgrid}$ & Efficiency of power conversion from the grid to aerodynamic power \\\\\n\n% \\end{tabular}\n\n\\section{Vertical take-off and landing}\n\nThe relationship between the required grid power for hover and mass\nis:\n%\n\\begin{equation}\n  \\label{eqn:hover_power}\n  P_{\\hover} = \\frac{1}{\\eta_{\\shaftgrid} \\cdot \\mathit{FM}}\n               \\sqrt{\\frac{(\\mathit{TWR} \\cdot m_{\\total} g)^3}\n                          {2 \\rho_{\\mn} f N_{\\prop} A_{\\prop}}}\n\\end{equation}\n%\nwhere $\\mathit{FM}$ is the figure-of-merit of the propellers,\n$\\mathit{TWR}$ is the thrust-to-weight ratio, $f$ is the fraction of\nmotors available in a motor-out situation, and $m_{\\total}$ is the\ncombined kite and tether mass.\\footnote{The strict limits that\n  vertical take-off and landing places on mass and power have\n  been covered extensively in other documents\n  \\cite{tvanalsenoy_power_train}}\n\nBecause of the significant cost of the ground-side inverter and other\npower components, which scales approximately linearly with power,\nvertical take-off and landing (VTOL) systems likely do not make\neconomic sense unless $P_{\\hover} \\le P_{\\mx}$.  This constraint may\nbe relaxed somewhat for multi-kite systems, if it is only necessary to\nhover a single kite at a time.  In this case, the kite is likely\nlimited by the available shaft power from the motors.  In a\nwell-designed system, the available shaft power from the motors should\nbe approximately, $P_{\\mx} / \\eta_{\\shaftgrid}$, where $P_{\\mx}$ is\nthe per-kite rated power, so that the power system is fully utilized\nduring generation.  In this case, the constraint imposed by VTOL is:\n$\\eta_{\\shaftgrid}^2 P_{\\hover} / f \\le P_{\\mx}$.  Note that the extra\nfactor of $\\eta_{\\shaftgrid} / f$ accounts for the fact that\nEq. \\ref{eqn:hover_power} is written in terms of ground power, and\nalso that it is necessary to acccount for the motor-out fraction again\nin a shaft power limited system.\n\nFor a single kite M600-like system, assuming $P_{\\mx} = 600$ kW,\n$\\eta_{\\shaftgrid} = 0.83$, $\\mathit{FM} = 0.68$, $\\rho_{\\mn} = 0.95$\nkg/m$^3$, $A_{\\prop} = 3.8$ m$^2$, and $\\mathit{TWR} = 1.3$,\n$f = 3/4$, this sets a reasonable mass limit of $m_{\\total} < 1338$\nkg.  For a multi-kite M600-like system, with equivalent parameters,\nthe mass limit is $m_{\\total} < 1416$ kg.  If the motor-out fraction\nis increased to $f = 7/8$, then the single- and multi-kite limits are\n1409 kg and 1652 kg, respectively.  Above these mass limits, VTOL\nbecomes expensive quickly, scaling as\n$P_{\\hover} \\propto (m/m_{\\nominal})^{3/2}$.\n\nIt is of course possible to increase the VTOL lifting ability through\nsignificant design changes to the M600.  The most significant\nparameter to change is rotor disk area.  In particular,\nEq. \\ref{eqn:hover_power} can be used to solve for the rotor disk area\nthat meets a given power requirement.  Later in this paper, limits on\nthe power density of a kite system will be derived, so it is actually\nmore useful to reexpress Eq. \\ref{eqn:hover_power} as a relationship\nbetween maximum power density and disk mass loading:\n%\n\\begin{equation}\n  \\label{eqn:hover_power2}\n  \\left(\\frac{P_{\\mx}}{m_{\\total}}\\right)^2 >\n  k \\left(\\frac{m_{\\total}}{N_{\\prop} A_{\\prop}}\\right)\n\\end{equation}\n%\nAssuming the same values as above, the proportionality constant here\nis $k \\approx 6400$ W$^2$-m$^2$/kg$^3$.  To get a feel for the range\nof values this constant could take across kite systems, the value\nwithout motor-out capability is $k \\approx 2700$ W$^2$-m$^2$/kg$^3$.\n\n\\section{Crosswind flight}\n\nCrosswind flight does not place as strict of a limit on mass as VTOL;\nhowever it still imposes mass limitations stricter than what would be\nrequired for traditional flight vehicles.  The main consequences of\nincreased mass in crosswind flight are 1) an increase in power\nrequired to maintain a minimum airspeed during climb, 2) an increase\nin minimum turning radius, and 3) an increase in power and tension\nvariations around a loop.  Each of these consequences are analyzed in\ndetail below.\n\n\\subsection{Minimum airspeed climb}\n\nA reasonable requirement for a kite system is to be able to maintain\nthe minimum allowed airspeed, $v_{\\app,\\mn}$, while climbing up the loop\nwith low or zero wind.  Assuming a circular flight path, this results\nin the power requirement for climbing of\n%\n\\begin{equation}\n  P_{\\climb} = \\frac{m_{\\eff} g_{\\parallel} v_{\\app,\\mn}}{\\eta_{\\airgrid}}\n\\end{equation}\n%\nwhich may be converted to a limitation on the maximum reasonable\neffective mass:\n%\n\\begin{equation}\n  \\label{eqn:mass_minimum_airspeed_climb}\n  m_{\\eff} < \\frac{\\eta_{\\airgrid} P_{\\mx}}{g_{\\parallel} v_{\\app,\\mn}}\n\\end{equation}\n%\nFor an M600-like system, assuming $P_{\\mx} = 600$ kW,\n$\\eta_{\\airgrid} = 0.67$, a flight path elevation angle of\n25$^{\\circ}$, and $v_{\\app,\\mn} = 30$ m/s, the maximum reasonable\neffective mass is $m_{\\eff} = 1507$ kg.\\footnote{TODO: Add drag to\n  calculation.}\n\n\\begin{figure}[h]\n\\begin{center}\n  \\begin{tikzpicture}\n    \\begin{scope}[scale=2]]\n      % Downstrokes.\n      \\draw[arrows={latex-}] ({sqrt(2) + 1}, 0) arc (0:135:1);\n      \\draw                  ({sqrt(2) + 1}, 0) arc (0:-135:1);\n\n      \\draw[arrows={latex-}] ({-(sqrt(2) + 1)}, 0) arc (180:45:1);\n      \\draw                  ({-(sqrt(2) + 1)}, 0) arc (180:315:1);\n\n      % Upstrokes.\n      \\draw[arrows={-latex}] ({-sqrt(2)/2}, {-sqrt(2)/2}) --\n      ({ sqrt(2)/2}, { sqrt(2)/2});\n      \\draw[arrows={-latex}] ({ sqrt(2)/2}, {-sqrt(2)/2}) --\n      ({-sqrt(2)/2}, { sqrt(2)/2});\n\n      \\draw ({-sqrt(2) - 0.1}, 0) -- ({-sqrt(2) + 0.1}, 0);\n      \\draw ({-sqrt(2)}, -0.1) -- ({-sqrt(2)}, 0.1);\n\n      \\draw ({sqrt(2) - 0.1}, 0) -- ({sqrt(2) + 0.1}, 0);\n      \\draw ({sqrt(2)}, -0.1) -- ({sqrt(2)}, 0.1);\n\n      \\draw[dashed] (0, 0) -- ({sqrt(2)}, 0);\n    \\end{scope}\n\n    \\draw[arrows={latex-latex}] (1, 0) arc (0:45:1);\n    \\path (1, 0) arc (0:22.5:1) node[above right] {$\\psi_{\\climb}$};\n\n    \\draw [decorate, decoration={brace, amplitude=5pt}]\n      ({-sqrt(2)*2}, 0) -- ({-sqrt(2)*2 - 1}, {sqrt(3)})\n      node[midway, below left] {$R_{\\path}$};\n\n    \\draw [decorate, decoration={brace, amplitude=5pt}]\n      (0, 0) -- ({-(sqrt(2) * 2)}, 0)\n      node[midway, below=0.2] {$\\delta$};\n\n  \\end{tikzpicture}\n  \\caption{Figure-eight flight path.}\n\\end{center}\n\\end{figure}\n\nOne concept that attempts to relax the constraints imposed by a\nminimum airspeed climb is to fly figure-eights where the upstrokes are\nthe long paths between downstrokes.  Now the power to climb is reduced\nby the sine of the climb angle:\n%\n\\begin{equation}\n  \\label{eqn:mass_minimum_airspeed_climb2}\n  P_{\\climb} = \\frac{m_{\\eff} g_{\\parallel} v_{\\app,\\mn} \\sin \\psi_{\\climb}}\n                    {\\eta_{\\airgrid}}\n\\end{equation}\n%\nUnfortunately, the figure-eight pattern has significant negative\neffects on power generation.  One effect is that it pushes part of the\npath off-downwind.  Specifically, the center of each of the loops of\nthe eight will be approximately\n$\\delta = R_{\\path} / \\sin \\psi_{\\climb}$ off-downwind.  Thus, there\nwill be a power loss roughly proportional to\n%\n\\begin{equation}\n  \\eta_{\\figureeight} \\sim \\cos^3 (\\sin^{-1}(\\sin \\gamma / \\sin \\psi_{\\climb}))\n\\end{equation}\n%\nwhere $\\gamma$ is the half-cone angle of the flight path.  Even for\nmoderate climb angles, say $\\psi_{\\climb} = 45^{\\circ}$, these losses\nare substantial, $\\eta_{\\figureeight} \\sim 0.67$ assuming\n$\\gamma = 20^{\\circ}$ \\footnote{For single kite systems, the required\n  low elevation angle of the flight path puts a strict limit on the\n  maximum half-cone angle.  This can be relaxed somewhat for\n  multi-kite systems.}.  And the estimated efficiency drops off\nquickly with shallower climb angles, $\\eta_{\\figureeight} = 0.38$ at\n$\\psi_{\\climb} = 30^{\\circ}$.  A second slightly harder to quantify\neffect is that the figure-eight will take longer to fly than the\nequivalent set of two independent circles, which also reduces power\nefficiency.\n\nNonetheless, flying figure-eights does offer an approach to increasing\nthe maximum mass calculated with\nEq. \\ref{eqn:mass_minimum_airspeed_climb} by a factor of, very\nroughly, 1.5, while sacrificing some power efficiency.  For an\nM600-like system flying figure-eights, the maximum reasonable\neffective mass is, again very roughly, 2300 kg.\n\nEquations \\ref{eqn:mass_minimum_airspeed_climb} and\n\\ref{eqn:mass_minimum_airspeed_climb2} set a fairly strict limit on\nthe power density of kite systems, which is independent of system\nscale.  Using the same parameters used above for the M600 system,\nwhich should apply equally well to a generic kite system, the power\ndensity for a kite system flying a circular path must be greater than\n400 W/kg, and the power density for a kite system flying a\nfigure-eight must be greater than roughly 265 W/kg.\n\n\\subsection{Turning radius}\n\nThe ability of a kite to turn around a tight circular path is\ninversely proportional to its mass.  Higher masses will eventually\nforce either a larger path radius or an excessively large roll angle.\nA larger path radius leads to a longer, draggier, and heavier tether\nas well as larger swings in tension and power.  Similarly, an\nexcessively large roll angle has negative consequences due to the\nreduced projected wing area normal to the wind.\n\nTo quantify these effects, it is useful to derive the exact\nrelationship between wing mass and turning radius.  This relationship\ncan be found by balancing forces in the stability axes' y-z plane.  To\nsimplify the calculation, the tether is appoximated as a straight line\nfrom the ground-station to the bridle point.  Other effects on the\ntether such as the catenary from gravity are ignored.\n\n\\begin{figure}[h]\n\\begin{center}\n  \\begin{tikzpicture}[scale=0.5]\n    \\begin{scope}[shift={(-5, 0)}, scale=0.3, rotate=-10]\n      \\DrawWingFront[]\n      \\draw[line width=1.5pt, -latex] (4, 1) -- (9, 1) node[midway, above] {$-Y$};\n      \\draw[line width=1.5pt, -latex] (0, 5) -- (0, 12) node[midway, right] {$L$};\n      \\draw (-5.86, -0.13) -- (0, -4.92);\n      \\draw (5.86, -0.13) -- (0, -4.92);\n      \\draw[dashed] (0, -4.92) -- (0, -15);\n    \\end{scope}\n    \\node at (-5, -3) {$\\phi_t$};\n    \\draw[line width=1.5pt, -latex] (-5.25, -1.45) --\n    (-3.5, -4.3) node[midway, above right] {$t$};\n    \\draw[line width=1.5pt, -latex] (-3.5, -1) -- (-2, -2)\n    node[below right] {$W$};\n    \\draw (-5.25, -1.45) -- (0, -10) node[midway, above right] {$l_t$};\n    %\\draw[dashed] (-5.25, -1.45) -- (-0.975, 1.175);\n    \\node at (-0.5, -8.5) {$\\gamma$};\n    \\draw[dashed] (0, -10) -- (0, -5);\n    %\\draw[dashed] (-5, 0) -- (-10, 0) node[near end, above] {$-\\phi$};\n    %\\draw[line width=1.5pt, -latex] (-7, 0) -- (-9, 0) node[midway, below]\n    %{$mv^2/R$};\n    \\DrawCoordinateSystem{shift={(0, -10)}, scale=1}\n                         {$x_{\\cw}$}{$y_{\\cw}$}{$z_{\\cw}$}\n  \\end{tikzpicture}\n  \\caption{Diagram of force balance in the stability axes' y-z plane.}\n\\end{center}\n\\end{figure}\n\nIt is easiest to conduct the force balance along axes that are\nparallel and perpendicular to the tether.  Because the wing is forced\nto fly on the surface of a sphere with radius equal to the tether\nlength, $l_t$, the acceleration parallel to the tether is\n$a_{\\parallel} = v_i^2/l_t$.  The lift, pylon side force, and weight\neach have components along the direction perpendicular to the tether.\nTogether, these create an acceleration perpendicular to the tether\ngiven by\n%\n\\begin{equation}\nm_{\\eff} a_{\\bot} = L \\sin \\phi_t - Y \\cos \\phi_t -\nW_{\\cw, x} \\cos \\gamma - W_{\\cw, z} \\sin \\gamma\n\\end{equation}\n%\nHere $m_{\\eff}$ is the effective mass of the kite, which is given by\n$m_{\\eff} = m_{\\kite} + m_{\\mathrm{tether}} / 3$.  The extra term from\nthe tether mass comes from calculating the acceleration of a point\nmass at the end of a rigid rod due to a force applied at the point\nmass.  Also, a few small approximations were made such as ignoring\nforces from motor thrust, ignoring the component of drag along the\nstability z-axis, and ignoring the cosine term from projecting the\nlift vector onto the stability z-axis.\n\nThe acceleration projected onto the crosswind flight plane is the\nacceleration relevant for following a circular path.  The parallel and\nperpendicular accelerations can be combined, projected onto the\ncrosswind $x$-axis as follows:\n%\n\\begin{align}\n  \\label{eqn:full_curvature}\n  \\frac{m_{\\eff} v_i^2}{r} =&\\;\n    \\frac{m_{\\eff} v_i^2}{l_t} \\sin \\gamma +\n    \\frac{1}{2} \\rho A v_{\\app}^2 \\left(C_L \\sin \\phi_t - C_Y \\cos \\phi_t \\right) \\cos \\gamma \\\\ \\notag\n  & - m (g_{\\cw,x} \\cos \\gamma +\n  g_{\\cw,z} \\sin \\gamma) \\cos \\gamma\n\\end{align}\n%\nFor the purposes of this discussion, Eq. \\ref{eqn:full_curvature} may\nbe simplified for the turn about the bottom of the loop, directly\ndownwind, while ignoring some of the smaller terms:\n%\n\\begin{equation}\n  r \\approx \\frac{m_{\\eff} v_i^2}\n                 {\\frac{1}{2} \\rho A v_{\\app}^2 C_L \\sin \\phi_t \\cos \\gamma -\n                 m g_{\\parallel} \\cos^2 \\gamma}\n\\end{equation}\n\n\nThe tether roll angle, $\\phi_t$, is the primary control variable for\nturning the kite around the path.  It is also possible to use $C_L$ or\n$C_Y$ to turn, but these variables significantly affect power\nproduction, so they are likely set by other considerations.  At the\nabsolute minimum, it is necessary to be able to set $\\phi_t$ such that\n$r = R_{\\path}$ to fly a circle.  However, to be able to {\\it control}\nthe kite it is necessary to have an available-to-desired centripetal\nforce ratio, $\\mathit{CFR}$, greater than one, a similar concept to a\nthrust-to-weight ratio.  Thus, the constraint is that there is some\n$\\phi_t$ such that $1/r > \\mathit{CFR} / R_{\\path}$.  A realistic\ncentripetal force ratio may be $\\mathit{CFR} \\sim 1.5$.  The above\nconsiderations result in the following constraint on path radius:\n%\n\\begin{equation}\n  R_{\\path} > \\mathit{CFR} \\cdot\n              \\frac{m v_{i,\\mn}^2}\n                   {\\frac{1}{2} \\rho v_{i,\\mn}^2 C_L A \\sin \\phi_{t,\\mx} \\cos \\gamma_{\\mx} -\n                    m g_{\\parallel} \\cos^2 \\gamma_{\\mx}}\n\\end{equation}\n%\nNote that the apparent wind speed was replaced by an inertial speed\nbecause it should still be possible to turn without wind!\n\nThe constraint on path radius can be converted to a constraint on\nminimum tether length for a given kite mass:\n%\n\\begin{equation}\n  l_{t,\\mn} > l_{t_0} \\frac{m}{m_0 - m}\n\\end{equation}\n%\nwhere the characteristic tether length $l_{t_0}$ is:\n%\n\\begin{equation}\n  l_{t_0} = \\mathit{CFR} \\cdot\n  \\frac{m_{\\eff} v_{i,\\mn}^2}{m g_{\\parallel} \\sin(\\gamma_{\\mx}) \\cos^2(\\gamma_{\\mx})}\n\\end{equation}\n%\nand the characteristic mass $m_0$ is:\n%\n\\begin{equation}\n  \\label{eqn:characteristic_mass}\n  m_0 = \\frac{\\frac{1}{2} \\rho v_{i,\\mn}^2 A C_L \\sin(\\gamma_{\\mx} + \\phi_{\\mx})}\n             {g_{\\parallel} \\cos(\\gamma_{\\mx})}\n\\end{equation}\n\nClearly, this gives an absolute hard limit on mass of $m < m_0$.  This\nlimit can be tightened somewhat by additionally specifying that the\nderivative of the {\\it minimum} tether length with respect to\neffective mass should not grow faster than the derivative of the\ntether length with respect to effective mass:\n%\n\\begin{equation}\n  m < m_0 - \\sqrt{\\frac{l_{t_0} m_0 \\lambda_t}{3}}\n\\end{equation}\n%\nwhere $\\lambda_t$ is the linear mass density of the tether.\n\nFor an M600-like system, assuming $\\mathit{CFR} = 1.5$, $\\rho = 0.95$\nkg/m$^3$, $v_{i,\\mn} = 30$ m/s, $\\gamma_{\\mx} = 20^{\\circ}$,\n$\\phi_{\\mx} = 30^{\\circ}$, $\\lambda_t = 1$ kg/m, and a flight path\nelevation angle of $25^{\\circ}$, $m_0 \\approx 2700$ kg and\n$l_{t_0} \\approx 540$ m. This implies that $m_{\\kite} < 2000$ kg.\nAnd, ideally $m_{\\kite}$ should be significantly less to avoid a\nrunaway in mass.\n\nEquation \\ref{eqn:characteristic_mass} sets a fairly strict limit on\nwing mass loading, which is independent of system scale.\nSpecifically, to be able to fly in a circle on a reasonable length\ntether, a kite system must have a wing mass loading of less than 60\nkg/m$^2$.\n\n\\subsection{Tension and power variation}\nThis section is not finished yet.\n\n% \\section{Designing a kite}\n\n\n% \\begin{table}[h]\n%   \\begin{tabular}{cccc}\n%     \\hline\n%     \\hline\n%     Parameter               & Symbol               & Value              & Units \\\\\n%     \\hline\n%     Min. power density      & $\\rho_{\\power}$      & 400                & W/kg \\\\\n%     Max. wing mass loading  & $\\sigma_{\\mass}$     & 60                 & kg/m$^2$ \\\\\n%     M600 powertrain density & $\\rho_{\\powertrain}$ & $1.25 \\times 10^3$ & W/kg \\\\\n%     \\hline\n%     \\hline\n%   \\end{tabular}\n% \\end{table}\n\n% Choose a rated power: $P_{\\mx} = 600$ kW.\n\n% Use the minimum power density to find the maximum effective mass: $P_{\\mx} / \\rho_{\\power} = 1500$ kg.\n\n% Select a lower mass for margin: $m_{\\eff, \\mx} = 1200$ kg.\n\n% Estimate the amount of kite mass: $m_{\\kite, \\mx} = 1100$ kg.\n\n% Estimate the total mass: $m_{\\total, \\mx} = 1400$ kg.\n\n% Use Eq. \\ref{} to estimate total rotor area: $N_{\\prop} A_{\\prop} > 48.8$ m$^2$.\n\n% For current motors, $P_{\\mx} = 600$ kW implies $N_{\\prop} = 8$.\n\n% Thus, $A_{\\prop} = 6.1$ m$^2$ and $R_{\\prop} = 1.4$ m.\n\n% Use maximum wing mass loading to determine a minimum wing area:\n% $m_{\\kite, \\mx} / \\sigma_{\\mass} = 18$ m$^2$.\n\n% Select a higher area for margin: $A_{\\kite} = 25$ m$^2$.\n\n\n\\section{Conclusions}\n\n\\begin{itemize}\n\n\\item For a system with the same aerodynamic and geometric properties\n  as the M600, VTOL imposes a {\\it total} mass limit of 1200 kg; the\n  minimum airspeed climb imposes an {\\it effective} mass limit of 1500\n  kg (this increases to 2300 kg for a figure-eight flight path); and\n  the turning radius imposes a {\\it kite} mass limit of 2000 kg.\n\n\\item According to the minimum airspeed climb criterion, a kite that\n  flies circles must have a power density, referenced to {\\it\n    effective} mass, of greater than 400 W/kg.  A kite that flies\n  figure-eights may relax this to roughly 265 W/kg.  A kite with a\n  ground-based power system (i.e. pumping kite) can relax these limits\n  even further, potentially to 200 W/kg for figure-eights, due to a\n  more efficient power conversion process. These limits are\n  essentially independent of scale.\n\n\\item Given that the specific power of our powertrains is ~1.25 kW/kg,\n  approximately 1/3 to 1/2 of the system weight will be the\n  powertrain, independent of scale.  For an M600-like VTOL system,\n  this leaves $\\sim 500$ kg for structure, servos, etc.\n\n\\item After a power density is selected, which meets the limit above,\n  Eq. \\ref{eqn:hover_power2} may be used to size the total rotor area.\n\n\\item According to the turning radius criterion, a kite must have a\n  wing mass loading, referenced to {\\it kite} mass, of less than 60\n  kg/m$^2$.  Again, this limit is independent of scale.\n\n\\item At the 600 kW scale, designing a system that supports VTOL will\n  require substantially reducing the maximum tension.  Because of the\n  square-cube law, larger scales will likely require significant\n  topology changes (e.g. more bridling, tailless variants, or\n  multi-kites) coupled with a reduction in maximum tension.\n\\end{itemize}\n\n\n\\begin{thebibliography}{1}\n\\bibitem{tvanalsenoy_power_train} Alsenoy, Thomas.\n  ``Airborne wind powertrain trade-off study.''\n  \\texttt{Drive > Makani Teams > Engineering > 01\\_System\\_Engineering > Papers (internal)}. 2016.\n\\end{thebibliography}\n\n\\end{document}\n", "meta": {"hexsha": "f62cfe0f752323360150f67bc4feabaf6489ecce", "size": 21646, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "documentation/control/system/kite_mass_limits.tex", "max_stars_repo_name": "leozz37/makani", "max_stars_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1178, "max_stars_repo_stars_event_min_datetime": "2020-09-10T17:15:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:59:35.000Z", "max_issues_repo_path": "documentation/control/system/kite_mass_limits.tex", "max_issues_repo_name": "leozz37/makani", "max_issues_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-22T05:22:35.000Z", "max_forks_repo_path": "documentation/control/system/kite_mass_limits.tex", "max_forks_repo_name": "leozz37/makani", "max_forks_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 107, "max_forks_repo_forks_event_min_datetime": "2020-09-10T17:29:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T09:00:14.000Z", "avg_line_length": 40.6116322702, "max_line_length": 104, "alphanum_fraction": 0.6881178971, "num_tokens": 6857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3019993425695905}}
{"text": "%!TEX root = ../main.tex\n\n\\chapter{FFTbor}\n\\label{ch:fftbor}\n\n\\lhead{FFTbor: Coarse-Grained Energy Landscapes}\n\n\\section{Introduction}\n\\label{sec:fftbor:intro}\n\nIn this chapter, we present the \\fftbor algorithm and accompanying software.\n\\fftbor is a novel algorithm developed with the intent of efficiently computing\nthe Boltzmann probability of those structures which, for a given input RNA\nsequence \\seq, differ by $k$ base pairs. By leveraging polynomial interpolation\nvia the \\fft, this algorithm runs in \\On{4} time and\n\\On{2} space, a significant improvement over its predecessor. The accompanying\nsoftware which implements this algorithm has been used to evaluate the\ncorrelation between kinetic folding speed and landscape ruggedness.\n\n\\subsection{Organization}\n\\label{subsec:fftbor:org}\n\nThis chapter is organized in the following fashion. First, we provide\nbackground on\nthe problem which \\fftbor aims to address, as well as a brief overview of\nexisting approaches. We follow by a formal explanation of the problem, and\nproceed to describe how the energy landscape is partitioned into discrete bins.\nWe then develop the recursions for the parameterized partition function using\nthe Nussinov-Jacobson energy model, which allows us to highlight the novel aspects\nof the algorithm. After developing the recursions, we indicate how they can be\nreformulated as a polynomial whose coefficients $z_k=\\bfZ{k}{1,n}$. We then\ndescribe how the \\fft can be employed to efficiently compute the coefficients\n$z_k$, finishing our description of the underlying algorithm. Then we proceed\nto present an application of \\fftbor, in the area of RNA folding kinetics.\n\n\\section{Background}\n\\label{sec:fftbor:bkgrnd}\n\nIn \\citep{freyhult.b07}, a dynamic programming algorithm\n\\rnabor---pronounced {\\em RNA neighbor}---was developed which simultaneously\ncomputes for\neach integer $k$, the Boltzmann probability $\\pk = \\frac{\\bfZ{k}{}}{\\fullZ}$\nof the subensemble of structures\nwhose \\bpd to a given {\\em initial}, or\n{\\em reference}, structure \\strSt is $k$.\n\\footnote{As later\nexplained, \\fullZ denotes the partition function, defined as the sum of\nall Boltzmann factors \\boltzf{\\str}, over all secondary structures \\str\nof a given RNA sequence, and $R$ denotes the universal\ngas constant and $T$ absolute temperature. Similarly \\bfZ{k}{} denotes the\nsum of all Boltzmann factors of all structures \\str, whose \\bpd\nto the initial structure \\strSt is exactly $k$.}\n\\rnabor stores the value of the (partial)\npartition functions \\bfZ{k}{i,j} for all $1 \\leq i \\leq j \\leq n$ and\n$0 \\leq k \\leq n$, each of which requires quadratic time to compute.\nThus it follows that \\rnabor runs in time \\On{5} and space\n\\On{3}, which severely limits its applicability to genomic annotation.\nThis restriction is somewhat mitigated by the fact that\nin \\citep{cloteloulorenz}, we showed how to use sampling\n\\citep{ding.nar03} to efficiently approximate\n\\rnabor in cubic time \\On{3} and quadratic space \\On{2},\n{\\em provided} that the starting structure \\strSt is the \\mfe\n(MFE) structure. We expect that a more efficient version of\n\\rnabor could be used in applications in genomics and synthetic\nbiology, to detect potential conformational switches---\nRNA sequences containing two or more (distinct) metastable structures.\n\nIn this chapter, we describe a radically different algorithm, \\fftbor\n\\citep{senter.po12},\nprounounced {\\em FFT neighbor},\nthat uses polynomial interpolation to compute the\ncoefficients $p_0,\\ldots,p_{n-1}$ of the polynomial defined in\n\\eqnref{fftbor:pOfX},\nwhere \\pk is defined by $\\pk = \\frac{\\bfZ{k}{}}{\\fullZ}$.\nDue to severe numerical instability issues in both the Lagrange\ninterpolation formula and in Gaussian elimination, we employ\nthe \\fft (FFT) to compute the \\idft (DFT) on values $y_0,\\ldots,y_{n-1}$,\nwhere $y_k = p(\\omega^k)$ and\n$\\omega = \\pRoU$ is the principal \\nRoU and\n$p(x)$ is defined in \\eqnref{fftbor:pOfX}. This\ngives rise to an improved version of \\rnabor, denoted \\fftbor,\nwhich runs in time \\On{4} and space \\On{2}.\n\n\\section{Formalization of the problem}\n\\label{sec:fftbor:formal}\n\n\\fftbor aims to compute the coefficients $p_0,\\dots,p_{n-1}$ of the polynomial\n\n\\begin{align}\n\\label{eq:fftbor:pOfX}\np(x) = p_0 + p_1 x + p_2 x^2 + \\dots + p_{n-1} x^{n-1},\n\\end{align}\n\nwhere \\pk is defined as $\\pk = \\frac{\\bfZ{k}{}}{\\fullZ}$. We employ the \\fft to compute\nthe \\idft on values $y_0,\\dots,y_{n-1}$, where\n$y_k = p(\\omega^k)$ and $\\omega = \\pRoU$ is the principal \\nRoU and $p(x)$ is defined in\n\\eqnref{fftbor:pOfX}. By leveraging\n\\nRoUs in conjunction with the \\idft the we subvert numeric instability\nissues observed with both Lagrange interpolation and Gaussian elimination.\n\nConsider an RNA sequence $\\seq = \\seqN$, where\n$s_i \\in \\{\\text{A,\\,U,\\,G,\\,C}\\}$, i.e. a sequence of nucleotides. We can describe a\nsecondary structure \\str which is compatible with \\seq as a collection of\nbase pair tuples $(i,j)$, where $1 \\le i \\le i+\\theta < j \\le n$ and\n$\\theta \\ge 0$ (generally taken to be $3$), the minimum number of unpaired bases\nin a hairpin loop due to steric constraints.\n\nTo more simply develop the underlying recursions for \\fftbor, we introduce a\nnumber of constraints on the base pairs within \\str. Firstly, we require that\neach base pair is either a Watson-Crick or G-U wobble, i.e. base pair $(i,j)$\nfor sequence \\seq has corresponding nucleotides $(s_i,s_j)$, which are\nrestricted to the set\n\n\\begin{align}\n\\label{eq:fftbor:validBP}\n\\bpSet =\n\\{\\text{(A,\\,U),\\,(U,\\,A),\\,(G,\\,C),\\,(C,\\,G),\\,(G,\\,U),\\,(U,\\,G)}\\}.\n\\end{align}\n\nWith\nthis constraint satisfied we say that \\str is {\\em compatible} with \\seq, and\nfor the remainder of this chapter will only consider those structures which are\ncompatible with \\seq.\nSecondly, we insist that given two base pairs $(i,j), (x,y)$ from \\str,\n$i=x \\iff j=y$ (bases have at most one partner). Finally, we require that\n$i<x<j \\iff i<y<j$ (no pseudoknots are allowed). While pseudoknots have been\nshown to be present in some biologically relevant RNAs, their inclusion greatly\ncomplicates the recursive decomposition of the structure, and thus it is common\nto ignore them. As a result, sequences known to contain\npseudoknots---such as RNase P \\citep{haas:1991vl}---are\nnot well suited for \\fftbor, and whenever possible investigators should take\ncare to consider the likely structure for their sequences before proceeding with\ncomputational analysis.\n\nProvided two secondary structures \\strST, we can define a notion of\ndistance between them. There are a number of different definitions of distance\nused across the literature; we will use {\\em \\bpd} for \\fftbor.\n\\Bpd is defined as the symmetric difference between the sets\n\\strST:\n\n\\begin{align}\n\\label{eq:fftbor:dBP}\n\\dBP{\\str}{\\strT} = |\\str \\cup \\strT| - |\\str \\cap \\strT|.\n\\end{align}\n\nGiven this definition of distance, two structures \\str and \\strT are said to\nbe \\kNbrs if $\\dBP{\\str}{\\strT} = k$. It is important to note that\nthe notion of \\bpd is also applicable to restrictions of secondary structures\non the subsequence $\\seq_{i,j}$,\ni.e. $\\str_{[i,j]} = \\{ (x,y) \\,:\\, i \\leq  x < y \\leq j,  (x,y) \\in \\str \\}$.\n\nFor a restriction of base pairs for a given structure $\\str_{[i,j]}$,\n$\\strT_{[i,j]}$ is said to be a \\kNbr of $\\str_{[i,j]}$ if\n\n\\begin{align}\n\\label{eq:fftbor:dBPonRestriction}\n\\dBP{\\str_{[i,j]}}{\\strT_{[i,j]}} =\n|\\{ (x,y): i \\leq x<y\\leq j,\n(x,y) \\in \\str - \\strT \\text{or} (x,y) \\in \\strT - \\str \\}| = k.\n\\end{align}\n\n\\section{Derivation of the \\fftbor algorithm}\n\\label{sec:fftbor:math}\n\nGiven an RNA sequence $\\seq=\\seqN$ and compatible secondary structure\n\\strSt, let \\bfZ{k}{} denote the sum of the Boltzmann factors\n\\boltzf{\\str} of all \\kNbrs \\str of \\strSt; i.e.\n\n\\begin{align}\n\\bfZ{k}{} = \\bfZ{k}{1,n} =\n\\sum_{\\mathclap{\\substack{\\str \\text{ such that } \\rule[-.5ex]{0pt}{0pt} \\\\\n \\dBP{\\str}{\\strSt}=k}}}\\;\n\\boltzF{\\str}\n\\end{align}\n\nwhere $E(\\str)$ denotes the Turner (nearest neighbor)\nenergy \\citep{xia:RNA}\nof \\str, $R = \\kmolk{0.00198}$ denotes the universal\ngas constant and $T$ denotes absolute temperature. From this, it follows that\nthe full partition function is defined as\n\n\\begin{align}\n\\label{eq:fftbor:partFunc}\n\\fullZ = \\bfZ{}{1,n} = \\sum_{k=0}^n \\bfZ{k}{1,n}\n\\end{align}\n\nsince the \\bpd between \\strSt and \\str is at most\n\n\\begin{align}\n\\label{eq:fftbor:maxDist}\n\\dBP{\\strSt}{\\str} \\leq |\\strSt| + \\lfloor \\frac{n-\\theta}{2} \\rfloor \\leq n.\n\\end{align}\n\nWe can then define the Boltzmann probability of all \\kNbrs of \\strSt as\n\n\\begin{align}\n\\label{eq:fftbor:probK}\np(k) =\\frac{\\bfZ{k}{1,n}}{\\bfZ{}{1,n}}.\n\\end{align}\n\nBy visualizing the probabilities \\pk as a function of $k$, we generate a\ncoarse-grained view of the one-dimensional energy landscape of \\seq with\nrespect to \\strSt. When \\strSt is taken to be the \\mfes for example, one would\nanticipate to see a peak at $k=0$, with additional peaks implying additional\nmetastable structures; local energy minima which could suggest an energetic\ntrap while folding.\n\n\\subsection{Definition of the partition function\n\\texorpdfstring{\\bfZ{k}{1,n}}{}}\n\\label{subsec:fftbor:recursions}\n\nFor the rest of the chapter, we consider both \\seq as well as the\nsecondary structure \\strSt on \\seq to be fixed. We now recall the\nrecursions from Freyhult et al. \\citep{Freyhult.ab05} to determine\nthe partition function \\bfZ{k}{i,j} with\nrespect to the Nussinov-Jacobson\nenergy $E_0$ model \\citep{nussinovjacobson}, defined by\n$-1$ times the number of base pairs; i.e. $E_0(S) = -1 \\cdot |S|$.\nAlthough we describe here the recursions for the Nussinov-Jacobson\nmodel, for the sake of\nsimplicity of exposition, both \\rnabor\n\\citep{Freyhult.ab05} as well as our current software \\fftbor,\nconcern the Turner energy model (described in \\Secref{sec:fftbor:turner}), consisting of free energy parameters for\nstacked bases, hairpins, bulges, internal loops and multiloops.\n\n% The full\n% recursions for \\fftbor are described for the\n% the Turner energy model in the appendix.\n\nThe base case for \\bfZ{k}{i,j} is given by\n\n\\begin{align}\n\\label{eq:fftbor:initZpart1}\n\\bfZ{0}{i,j} = 1, \\text{ for } i \\le j,\n\\end{align}\n\nsince the only $0$-neighbor to a structure \\strSt\nis the structure \\strSt itself, and\n\n\\begin{align}\n\\label{eq:fftbor:initZpart2}\n\\bfZ{k}{i,j} = 0, \\text{ for } k > 0, i \\le j \\leq i + \\theta,\n\\end{align}\n\nsince the empty structure is the only possible structure for a\nsequence shorter than $\\theta + 2$ nucleotides, and so there are no\n\\kNbrs for $k>0$. The recursion used to compute\n\\bfZ{k}{i,j} for $k > 0$ and $j > i+\\theta$ is\n\n\\begin{align}\n\\label{eq:fftbor:bfZkij}\n\\bfZ{k}{i,j} = \\bfZ{k-b_0}{i,j-1}\\enspace +\n\\sum_{\\substack{(s_r,s_j) \\in \\bpSet, \\\\ i \\leq r<j}}\\qquad\n\\sum_{\\mathclap{w+w'=k-b(r)}}\\enspace\n\\exp(-E_0(r,j)/RT) \\cdot \\bfZ{w}{i,r-1} \\bfZ{w'}{r+1,j-1},\n\\end{align}\n\nwhere $E_0(r,j) = -1$ if positions $r,j$ can pair in sequence \\seq,\nand otherwise $E_0(r,j) = +\\infty$. Additionally,\n$b_0 = 1$ if $j$ is base-paired\nin $\\strSt_{[i,j]}$ and $0$ otherwise, and\n$b(r)=\\dBP{\\strSt_{[i,j]}}{\\strSt_{[i,r-1]} \\cup \\strSt_{[r+1,j-1]} \\cup\\{(r,j)\\}}$.\nThis holds since in a secondary\nstructure $\\strT_{[i,j]}$ on \\seqIJ that is a \\kNbr of\n$\\strSt_{[i,j]}$,\neither nucleotide $j$ is unpaired in $[i,j]$ or it is\npaired to a nucleotide $r$ such that $i \\leq r < j$. In this\nlatter case it is enough to study the smaller sequence segments\n$[i,r-1]$ and $[r+1,j-1]$ noting that, except for $(r,j)$,\nbase pairs outside of these regions are not allowed, since there\nare no pseudoknots. In addition,\nfor $\\dBP{\\strSt_{[i,j]}}{\\strT_{[i,j]}} = k$ to hold,\nit is necessary for $w+w' = k -b(r)$ to hold, where $w =\n\\dBP{\\strSt_{[i,r-1]}}{\\strT_{[i,r-1]}}$ and $w' =\n\\dBP{\\strSt_{[r+1,j-1]}}{\\strT_{[r+1,j-1]}}$, since $b(r)$ is the\nnumber of base pairs that differ between $\\strSt_{[i,j]}$ and a\nstructure $\\strT_{[i,j]}$, due to the introduction of the base pair\n$(r,j)$.\n\nGiven RNA sequence \\seq and compatible initial structure \\strSt,\nwe define the {\\em polynomial}\n\n\\begin{align}\n\\label{eq:fftbor:zOfX}\n\\fullZx = \\sum_{k=0}^n z_k x^k\n\\end{align}\n\nwhere coefficients $z_k=\\bfZ{k}{1,n}$. Moreover, because of\n\\eqnref{fftbor:maxDist} and the fact that the minimum number of\nunpaired bases in a hairpin loop $\\theta$ is $3$, we know that $z_n=0$,\nso that \\fullZx is a polynomial of degree strictly less than $n$.\nIf we evaluate the polynomial \\fullZx for $n$ distinct values\n\n\\begin{align}\n\\label{eq:fftbor:solutionsForAlpha}\n\\emZof{}{a_1} = y_1, \\dots, \\emZof{}{a_n} = y_n,\n\\end{align}\n\nthen the Lagrange polynomial interpolation formula guarantees that\n$\\fullZx = \\sum_{k=1}^n y_k P_k(x)$, where the polynomials $P_k(x)$ have degree\nat most $n-1$ and are given by the Lagrange formula\n\n\\begin{align}\n\\label{eq:fftbor:lagrangeInterpolation}\nP_k(x) = \\frac{\\prod_{i\\ne k} (x-x_i)}{\\prod_{i \\ne k} (x_k-x_i)}.\n\\end{align}\n\nSince the polynomials $P_k(x)$ can be explicitly computed, it follows that\nwe can compute the coefficients $z_k$ of polynomial \\fullZx. As we describe\nbelow, the evaluation of \\fullZx for a fixed value of $x$ can be done in\ntime \\On{3} and space \\On{2}.  It follows that the coefficients\n$z_k=\\bfZ{k}{1,n}$ can be computed after\n$n$ evaluations of \\fullZx, where the space for each evaluation of \\fullZx\nis re-used; hence these evaluations can be performed in time \\On{4} and space\n\\On{2}. Finally,\nLagrange interpolation is clearly computable in time \\On{3}.\nAlthough this approach is theoretically sound, there are severe\nnumerical stability issues related to the interpolation method\n\\citep{highambarycentricinterpolation},\nthe choice of values $a_1,\\dots,a_{n}$ in the interpolation,\nand floating point arithmetic (round-off error) related to the\nastronomically large values of the partition functions\n\\bfZ{k}{1,n}, for $0 \\leq k < n$. After many unsuccessful\napproaches including scaling we obtained excellent results by\ninterpolating the polynomial $p(x)$, defined in \\eqnref{fftbor:pOfX},\nrather than the polynomial \\fullZx, defined in \\eqnref{fftbor:zOfX},\nand performing interpolation with the \\fft (FFT) \\citep{cormen}\nwhere \\alphaN are\nchosen to be \\nRoUs,\n$\\alpha_k = \\kRoU$.\nOne\nadvantage of the FFT is that interpolation can be performed in $O(n \\log n)$\ntime, rather than the cubic time required by using the Lagrange formula\nshown in \\eqnref{fftbor:lagrangeInterpolation} or by Gaussian elimination. Fewer\nnumerical operations implies increased numerical stability in our application.\n\n\\subsection{Recursions to compute the polynomial\n\\texorpdfstring{\\emZ{i,j}}{}}\n\\label{subsec:fftbor:polynomial}\n\nGiven an initial secondary structure \\strSt of a\ngiven RNA sequence \\seq, our goal is to compute\n\n\\begin{align}\n\\label{eq:fftbor:defZofK}\n\\bfZ{k}{1,n} = \\sum_{\\mathclap{\\substack{\\str \\text{ such that }\\\\ \\dBP{\\str}{\\strSt}=k}}}\\;\n\\boltzNuss{\\str}\n\\end{align}\n\nwhere \\str can be any structure compatible with \\seq.\nAs previously mentioned, the recurrence relation for \\rnabor\nwith respect to the Nussinov energy model $E_0$ is\n\n\\begin{align}\n\\label{eq:fftbor:rnaborNuss}\n\\bfZ{k}{i,j} = \\bfZ{k-b_0}{i,j-1}\\enspace +\n\\sum_{\\substack{(s_r,s_j) \\in \\bpSet, \\\\ i \\le r<j}}\n\\left(\n\\boltzNuss{r,j}\\enspace \\sum_{\\mathclap{w+w'=k-b(r)}}\\quad\n\\bfZ{w}{i,r-1} \\bfZ{w'}{r+1,j-1}\n\\right)\n\\end{align}\n\nwhere $E_0(r,j)=-1$ if $r$ and $j$ can base-pair and otherwise\n$+\\infty$, and\n$b_0 = 1$ if $j$ is base paired in $\\strSt_{[i,j]}$ and $0$ otherwise, and\n$b(r)=\\dBP{\\strSt_{[i,j]}}{\\strSt_{[i,r-1]} \\cup \\strSt_{[r+1,j-1]} \\cup\\{(r,j)\\}}$.\nThe following theorem shows that an analogous recursion can be used to compute\nthe {\\em polynomial} $\\emZ{i,j}$ defined by\n\n\\begin{align}\n\\label{eq:fftbor:polynomialZij}\n\\emZ{i,j} = \\sum_{k=0}^n z_k(i,j)\\,x^k\n\\end{align}\n\nwhere\n\n\\begin{align}\nz_k(i,j)\\>=\\>\n\\bfZ{k}{i,j}\\enspace=\\enspace\n\\sum_{\\mathclap{\\substack{\\str \\text{ such that } \\\\\n\\dBP{\\str}{\\strSt_{[i,j]}}=k}}}\\enspace\n\\boltzNuss{\\str}.\n\\end{align}\n\nHere, in the summation, \\str runs over structures on \\seqIJ, which\nare \\kNbrs of the restriction $\\strSt_{[i,j]}$ of initial structure\n\\strSt to interval $[i,j]$, and\n$E_0(S)=-1 \\cdot |S|$ denotes the Nussinov-Jacobson energy of \\str.\n\n\\begin{theorem}\n\\label{thm:fftbor:recursions}\nLet \\seqN be a given RNA sequence.\nFor any integers $1 \\leq i \\leq j \\leq n$, let\n\n\\begin{align}\n\\emZ{i,j} = \\sum_{k=0}^n z_k\\,x^k\n\\end{align}\n\nwhere\n\n\\begin{align}\nz_k(i,j) = \\bfZ{k}{i,j}.\n\\end{align}\n\nThen for $i\\leq j \\leq i+\\theta$, $\\emZ{i,j}=1$ and for\n$j>i+\\theta$ we have the recurrence relation\n\n\\begin{align}\n\\label{eq:fftbor:fftborNussPoly}\n\\emZ{i,j} = \\emZ{i,j-1} \\cdot x^{b_0} +\n\\sum_{\\substack{(s_r,s_j) \\in \\bpSet, \\\\ i\\le r<j}}\n\\left(\n\\boltzNuss{r,j} \\cdot \\emZ{i,r-1} \\cdot \\emZ{r+1,j-1} \\cdot x^{b(r)}\n\\right).\n\\end{align}\n\nwhere $b_0 = 1$ if $j$ is base-paired in $\\strSt_{[i,j]}$ and $0$ otherwise, and\n$b(r) =\n\\dBP{\\strSt_{[i,j]}}{\\strSt_{[i,r-1]} \\cup \\strSt_{[r+1,j-1]} \\cup \\{(r,j)\\}}$.\n\\end{theorem}\n\n\\begin{proof}\nFirst, some notation is necessary.\nRecall that if $F$ is an arbitrary\npolynomial [resp. analytic] function, then $[x^k]F(x)$\ndenotes the coefficient of $x^k$ [resp. the $k$th Taylor coefficient in the\nTaylor expansion of $F(x)$]. For instance, in\n\\eqnref{fftbor:pOfX}, $[x^k]p(x) = \\pk$, and in\n\\eqnref{fftbor:zOfX}, $[x^k]\\fullZx = z_k$.\n\nBy definition, it is clear that $\\emZ{i,j}=1$ if $i \\leq j \\leq i + \\theta$,\nwhere we recall that $\\theta = 3$ is the minimum number of unpaired bases in\na hairpin loop. For $j > i + \\theta$, we have\n\n\\begin{align}\n\\begin{split}\n[x^k] \\emZ{i,j} &= z_k(i,j) = \\bfZ{k}{i,j} \\\\\n&= \\bfZ{k-b_0}{i,j-1} +\n\\sum_{r=i}^{j-1}\\hspace{2.25em} \\sum_{\\mathclap{k_0+k_1=k-b(r)}}\\hspace{1.5em}\n\\left( \\boltzNuss{r,j} \\cdot \\bfZ{k_0}{i,r-1} \\cdot \\bfZ{k_1}{r+1,j-1} \\right) \\\\\n&= [x^{k-b_0}] \\emZ{i,j-1} \\\\\n&+ \\sum_{r=i}^{j-1}\\hspace{2.25em} \\sum_{\\mathclap{k_0+k_1=k-b(r)}}\\hspace{1.5em}\n\\left( \\boltzNuss{r,j} \\cdot \\left( [x^{k_0}] \\emZ{i,r-1} \\right) \\cdot\n\\left( [x^{k_1}] \\emZ{r+1,j-1} \\right) \\right) \\\\\n&= [x^{k-b_0}] \\emZ{i,j-1} \\\\\n&+ \\sum_{r=i}^{j-1}\\hspace{2.25em} \\sum_{\\mathclap{k_0+k_1=k-b(r)}}\\hspace{1.5em}\n\\left( \\boltzNuss{r,j} \\cdot [x^{k_0+k_1}]\n\\left( \\emZ{i,r-1} \\cdot \\emZ{r+1,j-1} \\right) \\right).\\\\\n\\end{split}\n\\end{align}\n\nBy induction, the proof of the theorem now follows.\n\\end{proof}\n\nNotice that if one were to compute all terms of the polynomial $\\emZ{1,n}$\nby explicitly performing polynomial multiplications,\nthen the computation would require \\On{5} time and \\On{3} space.\nInstead of explicitly performing polynomial expansion in {\\em variable} $x$,\nwe instantiate $x$ to a fixed complex number $\\alpha \\in \\mathbb{C}$, and apply\nthe following recursion for this instantiation:\n\n\\begin{align}\n\\label{eq:fftbor:fftborNussPolyAlpha}\n\\emZof{i,j}{\\alpha} = \\emZof{i,j-1}{\\alpha} \\cdot \\alpha^{b_0} +\n\\sum_{\\substack{(s_r,s_j) \\in \\bpSet, \\\\ i \\le r<j}}\n\\left(\n\\boltzNuss{r,j} \\cdot\n\\emZof{i,r-1}{\\alpha} \\cdot \\emZof{r+1,j-1}{\\alpha} \\cdot \\alpha^{b(r)}\n\\right).\n\\end{align}\n\nIn this fashion, we can compute $\\emZof{}{\\alpha}=\\emZof{1,n}{\\alpha}$ in\n\\On{3} time and \\On{2} space. For $n$ distinct complex values\n\\alphaN, we can compute and save only the\nvalues $\\emZof{}{\\alpha_0},\\dots,\\emZof{}{\\alpha_{n-1}}$, each time re-using the\n\\On{2} space for the next computation of $\\emZof{}{\\alpha_k}$. It follows that\nthe computation resources used to determine the (column) vector\n\n\\begin{align}\n\\label{eq:fftbor:yColumn}\n\\bfY = (y_0,\\dots,y_{n-1})^{\\text T} =\n\\left(\n\\begin{array}{l}\ny_0 \\\\\ny_1 \\\\\n\\vdots \\\\\ny_{n-1} \\\\\n\\end{array}\n\\right)\n\\end{align}\n\nwhere\n$y_0=\\emZof{}{\\alpha_0},\\dots,y_{n-1}=\\emZof{}{\\alpha_{n-1}}$ is thus quartic time \\On{4} and quadratic space \\On{2}.\n\n\\subsection{Polynomial interpolation to evaluate\n\\texorpdfstring{\\emZ{i,j}}{}}\n\\label{subsec:fftbor:fft}\n\nLet $\\omega = \\pRoU$ be the principal \\nRoU.\nRecall that the Vandermonde matrix $V_n$ is defined to be the\n$n \\times n$ matrix, whose $i,j$ entry is $\\omega^{i \\cdot j}$; i.e.\n\n\\begin{align}\n\\label{eq:fftbor:vandermonde}\nV_n =\n\\left(\n\\begin{array}{rrrrr}\n1 & 1 & 1 & \\dots & 1 \\\\\n1 & \\omega & \\omega^2 & \\dots & \\omega^{n-1} \\\\\n1 & \\omega^2 & \\omega^4 & \\dots & \\omega^{2(n-1)} \\\\\n1 & \\omega^3 & \\omega^6 & \\dots & \\omega^{3(n-1)} \\\\\n\\vdots & \\vdots & \\vdots & \\vdots & \\vdots \\\\\n1 & \\omega^{n-1} & \\omega^{2(n-1)} & \\dots & \\omega^{(n-1)(n-1)} \\\\\n\\end{array}\n\\right)\n\\end{align}\n\nThe \\fft is defined to be the $O(n \\log n)$\nalgorithm to compute the Discrete Fourier Transform (DFT), defined\nas the matrix product $\\bfY = V_n {\\bf A}$:\n\n\\begin{align}\n\\label{eq:fftbor:dftMatrix}\n\\left(\n\\begin{array}{l}\ny_0 \\\\\ny_1 \\\\\ny_2 \\\\\n\\vdots \\\\\ny_{n-1} \\\\\n\\end{array}\n\\right)\n= V_n \\cdot\n\\left(\n\\begin{array}{l}\na_0 \\\\\na_1 \\\\\na_2 \\\\\n\\vdots \\\\\na_{n-1} \\\\\n\\end{array}\n\\right)\n\\end{align}\n\nOn page $837$ of \\citep{cormen}, it is shown that the\n$(i,j)$ entry of $V_n^{-1}$ is $\\frac{\\omega^{-j i}}{n}$\nand that\n\n\\begin{align}\n\\label{eq:fftbor:aFromY}\na_j = \\frac{1}{n} \\sum_{k=0}^{n-1} y_k\\,\\omega^{-kj}\n\\end{align}\n\nfor $j=0,\\dots,n-1$.\n\nSince we defined \\bfY in \\eqnref{fftbor:yColumn} by $\\bfY =\n(y_0,\\dots,y_{n-1})^{\\text T}$, where\n$y_0=\\emZof{}{\\alpha_0},\\dots,y_{n-1}=\\emZof{}{\\alpha_{n-1}}$\nand $\\alpha_k = \\omega^k \\kRoU$, it follows that the coefficients\n$z_k=\\bfZ{k}{1,n}$ in the polynomial\n$\\fullZx = z_0 + z_1 x + \\dots + z_{n-1} x^{n-1}$ defined in\n\\eqnref{fftbor:zOfX} can be computed, at least in principle,\nby using the \\fft. It turns out, however, that the values of\n\\bfZ{k}{1,n} are so astronomically large, that the ensuing numerical\ninstability makes even this approach infeasible for values of $n$\nthat exceed $56$ (data not shown).\nNevertheless, our approach can be modified as follows.\nDefine \\bfY by $\\bfY = (y_1,\\dots,y_n)^{\\text T}$, where\n$y_1=\\frac{\\emZof{}{\\alpha_1}}{\\fullZ},\\dots,\ny_{n}=\\frac{\\emZof{}{\\alpha_n}}{\\fullZ}$, and\n\\fullZ is the partition function defined in \\eqnref{fftbor:partFunc}.\nUsing the \\fft to compute the \\idft, it follows from\n\\eqnref{fftbor:aFromY} that we can compute the probabilities $p_0,\\dots,p_{n-1}$\nthat are coefficients of the polynomial\n$p(x) = p_0 + p_1 x + \\dots + p_{n-1}x^{n-1}$\ndefined in \\eqnref{fftbor:pOfX}. For genomics applications, we are\nonly interested in the $m$ most significant digits of each \\pk, as described\nin the pseudocode on the following page.\n\\medskip\n\n\\begin{figure}[!ht]\n% \\hrule \\rule[0ex]{0pt}{0pt}\n\\begin{center}\n{\\large Pseudocode for \\fftbor} \\\\\n\\end{center}\n\\begin{tabular*}{\\textwidth}{ll}\n{\\sc Purpose:} & Computes the $m$ most significant digits\nof probabilities $\\pk = \\rfrac{\\bfZ{k}{1,n}}{\\fullZ}$ \\rule[-1.5ex]{0pt}{0pt} \\\\\n{\\sc Input:} & RNA sequence $\\seq = \\seqN$, secondary\nstructure \\strSt of \\seq, integer $m$ \\rule[-1.5ex]{0pt}{0pt} \\\\\n{\\sc Output:} & Probabilities $\\pk = \\rfrac{\\bfZ{k}{1,n}}{\\fullZ}$ to $m$ significant digits for $k=0,\\dots,n-1$ \\rule[-1.75em]{0pt}{0pt} \\\\\n\\hline \\rule[0ex]{0pt}{0pt}\n\\end{tabular*}\n\\begin{algorithmic}[1]\n\\Function{FFTbor}{\\seq, \\strSt, $m$}\n\\State $n \\gets \\textit{length}(\\seq)$\n\\For{$k \\gets 0, n-1$}\n\\Comment{Compute all \\nRoUs}\n\\State $\\omega_k \\gets \\exp(\\frac{2 \\pi i k}{n})$\n\\EndFor\n\\For{$k \\gets 0, n-1$}\n\\Comment{Note that $\\emZof{}{\\omega_0} = \\fullZ$}\n\\State $y_k \\gets 10^m \\cdot \\frac{\\emZof{}{\\omega_k}}{\\emZof{}{\\omega_0}}$\n\\EndFor\n\\For{$k \\gets 0, n-1$}\n\\Comment{Compute IDFT from \\eqnref{fftbor:aFromY}}\n\\State $a_k \\gets \\frac{1}{n} \\sum_{j=0}^{n-1} y_j\\, \\omega^{-kj}$\n\\State $\\pk \\gets 10^{-m} \\cdot \\lfloor a_k \\rfloor$\n\\Comment{Truncate to $m$ significant digits}\n\\EndFor\n\\State \\textbf{return} $p_0,\\dots,p_{n-1}$\n\\Comment{Return all \\pk for $0 \\leq k < n$,\nfrom \\eqnref{fftbor:probK}}\n\\EndFunction\n\\rule[-0.35ex]{0pt}{0pt}\n\\end{algorithmic}\n\\caption[Pseudocode for \\fftbor]{The function {\\sc FFTbor} computes the $m$ most significant digits\nof $p_0,\\dots,p_{n-1}$, where $\\pk = \\frac{\\bfZ{k}{}}{\\fullZ}$. This algorithm\noperates in \\On{4} time and \\On{2} space, a significant improvement over its\npredecessor \\rnabor.}\n\\label{fig:fftbor:algo}\n\\rule[0ex]{0pt}{1.5em} \\hrule\n\\end{figure}\n\n\\section{Benchmarking and performance considerations}\n\\label{sec:fftbor:benchmarking}\n\nIn this subsection, we show that we need only evaluate the polynomial\n\\fullZx, as defined in\n\\eqnref{fftbor:zOfX}, for $n/2$ of the \\nRoUs.\n It is first necessary to recall the definition of complex\nconjugate.\nRecall that the complex conjugate of $z$ is denoted by $\\overline{z}$;\ni.e. if $z=\\aPbi$ where $a,b \\in \\mathbb{R}$ are real numbers and\n$i = \\sqrt{-1}$,  then $\\overline{z} = \\aMbi$.\n\n\\begin{lemma}\n\\label{lem:fftbor:compconj}\n\nIf \\fullZx is the complex polynomial defined in\n\\eqnref{fftbor:zOfX}, then for any \\nRoU\n $\\alpha$, it is the case that $\\emZof{}{\\overline{\\alpha}} =\n\\overline{\\emZof{}{\\alpha}}$. In other words, if $\\alpha$ is a \\nRoU\n of the form \\aPbi, where $a,b \\in \\mathbb{R}$ and $b>0$, and\nif $\\emZof{}{\\aPbi} = A + Bi$ where $A,B \\in \\mathbb{R}$, then it is the case that\n\n\\begin{align}\n\\emZof{}{\\aMbi} = A - Bi.\n\\end{align}\n\nThis comes from the well known fact that\n$\\emZof{}{\\overline{\\alpha}} = \\overline{\\emZof{}{\\alpha}}$\nfor any polynomial with real coefficients.\n\\end{lemma}\n\nLemma \\ref{lem:fftbor:compconj} immediately entails that we need only to evaluate \\fullZx on $n/2$\nmany of the \\nRoUs---namely, those of the form\n\\aPbi, where $b \\geq 0$. The remaining values of \\fullZx are obtained by\ntaking conplex conjugates of the first $n/2$ values. This, along with a\nprecomputation of powers of the \\nRoUs, leads to an\nenormous performance speed-up in our implementation of \\fftbor.\n\n\\section{Coarse-grained kinetics with \\fftbor}\n\\label{sec:fftbor:kinetics}\n\nThe output of \\fftbor, as shown in\n\\Figref{fftbor:tppDistributions}, is a probability distribution,\nwhere the $x$-axis represents the \\bpd from an arbitrary,\nbut fixed secondary structure \\strSt, and the $y$-axis represents the\nBoltzmann probability $p(k) = \\frac{\\bfZ{k}{}}{\\fullZ}$ that a secondary structure\nhas \\bpd $k$ from \\strSt. Arguably, this probability distribution\nis an accurate one-dimensional projection of the rugged, high dimensional energy\nlandscape near structure \\strSt,\nof the sort artistically rendered in the well-known\nenergy landscape depicted in Figure 1 of \\citep{wolynes.ptam05}.\nA hypothesis behind theoretical work in biomolecular folding theory in\n\\citep{bryngelson.p95}\nis that kinetic folding slows down as the energy landscape becomes more\n{\\em rugged}. This is borne out in our computational experiments for RNA\nusing \\fftbor, as reported\nin \\Figref{fftbor:tppDistributions}.\n\nWe randomly chose two TPP \\rb\naptamers from the seed alignment for\nRfam family RF$00059$. The first sequence from {\\em B. bacteriovorus} has EMBL accession code\nBX$842649.1$ $277414$--$277318$ and is composed of the $97$ nt sequence\n\\seqsplit{%\n  ACCUGACGCUAGGGGUGUUGGUGAAUUCACCGACUGAGAAUAACCCUUU%\n  GAACCUGAUAGAGAUAAUGCUCGCGCAGGGAAGCAAGAAUAGAAAGAU%\n}. The second sequence from the marine metagenome has\nEMBL accession code AACY$022101973.1$ $389$--$487$ and is composed of the $99$\nnt sequence\n\\seqsplit{%\n  UAUAAGUCCAAGGGGUGCCAAUUGGCUGAGAUGGUUUUAACCAAUCCCUU%\n  UGAACCUGAUCCGGUUAAUACCGGCGUAGGAAUGGAUUUUCUCUACAGC%\n}.\nRfam consensus and \\mfess for both sequences are\ndepicted in \\Figref{fftbor:tppConsensusAndMfe}.\nDespite the fact that there is no sequence similarity according to\npairwise BLAST \\citep{blast}, this figure clearly demonstrates that\nconsensus and\n\\mfess closely resemble each other, and that the\nstructures of both TPP \\rb aptamers are quite similar, with the\nexception of the leftmost hairpin loop [resp. multiloop].\nThe MFE structures differ\nfrom the consensus structures principally by the addition of base pairs not\ndetermined by covariation in the Rfam alignment.\nIndeed, if we let $\\str_0,\\,\\str_1$\ndenote the Rfam consensus structure [resp. MFE structure] for the $97$ nt\nsequence with EMBL accession code BX$842649.1$ $277414$--$277318$, then\n$\\str_0 \\setminus \\str_1$ has $4$ base pairs, and $\\str_1 \\setminus \\str_0$\n has $7$\nbase pairs. If we let $\\strT_0,\\,\\strT_1$\ndenote the Rfam consensus structure [resp. MFE structure] for the $99$ nt\nsequence with EMBL accession code\nAACY$022101973.1$ $389$--$487$, then\n$\\strT_0 \\setminus \\strT_1$ has $1$ base pair, and $\\strT_1 \\setminus \\strT_0$ has $5$\nbase pairs.\n\n\\begin{figure}[!ht]\n\\centering\n\\includegraphics[width=.9\\textwidth]{Figures/FFTbor/tppConsensusAndMfe.pdf}\n\\caption[Rfam consensus structures (Rfam) and \\mfe (MFE)\nsecondary structures for two thiamine pyrophosphate (TPP) \\rb aptamers]{Rfam consensus structures (Rfam) and \\mfe (MFE)\nsecondary structures for two thiamine pyrophosphate (TPP) \\rb aptamers,\nchosen at random from RF$00059$ Rfam family seed alignment\n\\citep{Gardner.nar11}. Using pairwise BLAST \\citep{blast}, there is no\nsequence similarity, although the secondary structures are very similar,\nas shown in this figure. From left to right:\n{\\em (A)} MFE structure for BX$842649.1$ $277414$--$277318$.\n{\\em (B)} Rfam consensus structure for BX$842649.1$ $277414$--$277318$.\n{\\em (C)} MFE structure for AACY$022101973.1$ $389$--$487$.\n{\\em (D)} Rfam consensus structure for AACY$022101973.1$ $389$--$487$.\n}\n\\label{fig:fftbor:tppConsensusAndMfe}\n\\end{figure}\n\nWe ran \\fftbor on each of the TPP \\rb aptamer\nsequences, with the MFE structure of each\nsequence taken as the initial structure \\strSt for that sequence. For the\nfirst sequence, BX$842649.1$ $277414$--$277318$, the \\fftbor output\nsuggests that there are low energy structures\nat a distance from the MFE structure, which might compete with the MFE\nstructure and hence slow the kinetics of folding. In contrast, for the\nsecond sequence, AACY$022101973.1$ $389$--$487$, the \\fftbor output suggests\nthat there are no such competing low energy structures, hence\nthe second sequence should fold more quickly than the first.\n\n\\begin{figure}[!ht]\n\\centering\n\\includegraphics[width=.45\\textwidth]{Figures/FFTbor/FFTbor_BX842649_1.pdf}\n\\quad\n\\includegraphics[width=.45\\textwidth]{Figures/FFTbor/FFTbor_AACY022101973_1.pdf}\n\\caption[Output from \\fftbor on two randomly selected\nthiamine pyrophosphate \\rb (TPP) aptamers]{Output from \\fftbor on two randomly selected\nthiamine pyrophosphate \\rb (TPP) aptamers, taken from the Rfam database\n\\citep{Gardner.nar11}. The $x$-axis represents \\bpd from the\n\\mfes for each given sequence; the $y$-axis represents\nBoltzmann probabilities $p(k) = \\frac{\\bfZ{k}{}}{\\fullZ}$, where\n\\bfZ{k}{} denotes the sum of Boltzmann factors or all secondary structures,\nwhose \\bpd from the MFE structure is exactly $k$.\n{\\em (Left)}\nThe $97$ nt sequence BX$842649.1$ $277414$--$277318$ appears to have a rugged energy\nlandscape near its \\mfes, with distinct\nlow energy structures that may compete with the MFE structure during the\nfolding process.\n{\\em (Right)}\nThe $99$ nt sequence, AACY$022101973.1$ $389$--$487$ appears to have a smooth energy\nlandscape near its MFE structure, with no distinct low energy structures\nto might compete with the MFE structure.\nBased on the \\fftbor output or {\\em structural profile} near MFE\nstructure \\strSt, one might expect\nfolding time for the first sequence to increase due to competition from\nmetastable structures, while one might expect the second sequence to have\nrapid folding time.\nComputational Monte Carlo folding experiments bear out this fact.\n\\kinfold \\citep{flamm} simulations clearly show that the second\nsequence folds\nat least four times more quickly than the first sequence. See section\n\\ref{sec:fftbor:kinetics} for\ndetails.}\n\\label{fig:fftbor:tppDistributions}\n\\end{figure}\n\nTo test the hypothesis that folding is slower for rugged energy landscapes,\nwe ran the kinetic folding software, \\kinfold \\citep{flamm},\non each of the two TPP \\rb aptamer sequences,\nBX$842649.1$ $277414$--$277318$ and AACY$022101973.1$ $389$--$487$,\nto determine the \\mfpt (MFPT) to\nfold into the MFE structure, when starting from the empty structure.\nIn this computational\nexperiment, we took MFPT to be the average number of Monte Carlo steps\ntaken by \\kinfold---each step consisting of the addition or removal\nof a single base pair---to fold the\nempty structure into the MFE\nstructure, where the average was taken over $30$ runs, with an absolute\nmaximum number of Monte Carlo steps taken to be $500,000$.\nThe first sequence, BX$842649.1$ $277414$--$277318$, converged within $500,000$\nsteps only for $20$ out of $30$ runs. Assigning the maximum step count of\n$500,000$ for the $10$ runs that did not converge, we found a \\mfpt\nof $311,075.06$ steps for this sequence.\nThe second sequence, AACY$022101973.1$ $389$--$487$, converged within $500,000$\nsteps in $29$ out of $30$ runs, and we found a \\mfpt of\n$61,575.69$ steps for this sequence. From computational experiments of this\ntype, it is suggestive that \\fftbor may prove useful in synthetic\nbiology,\nwhere one would like to design rapidly folding RNA molecules that\nfold into a designated target structure.\n\nIn order to more systematically determine the relation between kinetic\nfolding speed and the ruggedness of an energy landscape near the MFE structure,\nwe need to numerically quantify ruggedness. To this end, in the following\nwe define the notion of \\ebpd to a designated\nstructure. Let \\strSt be an arbitrary secondary structure of the RNA sequence\n$\\seq = \\seqN$.\nThe expected \\bpd to \\strSt is defined by\n\n\\begin{align}\nE[ \\{ \\dBP{\\str}{\\strSt} : \\str \\in \\mathbb{S}(\\seqN)\\} ] =\n\\sum_{\\str} P(\\str) \\cdot \\dBP{\\str}{\\strSt}\n\\end{align}\n\nwhere\n$\\mathbb{S}(\\seqN)$ denotes the set of secondary structures for\n$\\seq = \\seqN$, $P(\\str) = \\frac{\\boltzf{\\str}}{\\fullZ}$ is the Boltzmann\nprobability of \\str, and\n\\dBP{\\str}{\\strSt} denotes \\bpd between \\str and \\strSt.\nIf we run \\fftbor on an input sequence \\seq and secondary structure\n\\strSt, then clearly\n$E[ \\{ \\dBP{\\str}{\\strSt} : \\str \\in \\mathbb{S}(\\seqN)\\} ] =\n\\sum_{k} k \\cdot p(k)$, where $p(k)=\\frac{\\bfZ{k}{}}{\\fullZ}$, obtained from the\nprogram output.  If \\strSt is the empty structure, then \\fftbor output\nis simply the probability distribution of the number of base pairs per\nsecondary structure, taken over the Boltzmann ensemble of all structures.\n\nFor the benchmarking assay, we took all $61$ selenocysteine insertion sequence\n(SECIS) sequences from the seed alignment of Rfam family RF$00031$\n\\citep{Gardner.nar11}. Average length was $64.32 \\pm 2.83$ nt.\nFor each sequence, we ran both \\fftbor (when starting\nfrom the empty structure rather than the MFE structure) and a Monte Carlo\nfolding algorithm, developed by E. Freyhult and P. Clote (unpublished).\nUsing the Monte Carlo algorithm, we\ndetermined the \\mfpt (MFPT), defined as the average\ntaken over $50$ runs, of the number of Monte Carlo steps taken to fold\nthe empty structure into the MFE structure, where an absolute upper bound\nof $5$ million steps was allowed in the simulation.\n\nSurprisingly, we found that there is a significant\ncorrelation of $0.4847$ with one-tailed\n$p$-value of $0.0002$ between the\nstandard deviation of the \\fftbor output (when starting from the\nempty structure) and logarithm base $10$ of the \\mfpt.\nAs described above, \\fftbor output is simply\nthe probability distribution\nfor the number of base pairs per structure, taken over the ensemble\nof all secondary structure for the input RNA\nsequence. The standard deviation of this probability distribution corresponds\nto a notion of the width of the distribution. It is possible that those\nsequences having distributions tightly centered around the\nmean have faster folding times than those with a wider distribution\ndue to other local minima causing the RNA to get trapped while folding.\n\\medskip\n\n\\begin{table}[!ht]\n\\centering\n\\begin{tabularx}{\\linewidth}{c *{6}{R}}\n  \\toprule\n  ~ & \\small{$\\mu$} & \\small{$\\sigma$} & \\small{$\\rfrac{\\sigma}{\\mu}$} & \\small{$n$} & \\small{MFE} & \\small{$\\log_{10}(\\text{MFPT})$} \\\\\n  \\cmidrule(l){2-7}\n  \\small{$\\mu$} & $1$ & & & & \\\\\n  \\small{$\\sigma$} & $-0.4372$ & $1$ & & & \\\\\n  \\small{$\\rfrac{\\sigma}{\\mu}$} & $-0.6914$ & $0.9437$ & $1$ & & & \\\\\n  \\small{$n$} & $0.7077$ & $-0.1590$ & $-0.3646$ & $1$ & &  \\\\\n  \\small{MFE} & $-0.5695$ & $0.7395$ & $0.7596$ & $-0.3685$ & $1$ & \\\\\n  \\small{$\\log_{10}(\\text{MFPT})$} & $-0.0363$ & $0.4844$ & $0.3762$ & $0.4059$ & $0.3990$ & $1$ \\\\\n  % puts data.chomp.split(/\\\\/).map { |line| line.split(\"&\")[1..-1].map { |item| item.gsub(/\\s+/, \"\") }.reject { |item| item.empty? }.map { |number| \"%.4f\" % number.to_f }.join(\" & \") + \" \\\\\\\\\" }.join(?\\n)\n  \\bottomrule\n\\end{tabularx}\n\\caption[Pearson correlation between various aspects of selenocysteine\ninsertion sequences from the seed alignment of Rfam family\nRF$00031$]{\\small Pearson correlation between various aspects of selenocysteine\ninsertion sequences from the seed alignment of Rfam family\nRF$00031$ \\citep{Gardner.nar11}.\nFor each of the $61$ RNA sequences, we ran \\fftbor, starting\nfrom empty initial structure \\strSt, and we ran a Monte Carlo\nfolding algorithm, developed by E. Freyhult and P. Clote (unpublished).\nUsing the Monte Carlo algorithm, we\ndetermined the \\mfpt (MFPT), defined as the average\ntaken over $50$ runs, of the number of Monte Carlo steps taken to fold\nthe empty structure into the MFE structure, where an absolute upper bound\nof $5$ million steps was allowed in the simulation.  From the output of\n\\fftbor, we computed\n{\\em 1})\\, the mean number ($\\mu$) of base pairs per structure, taken over\nthe ensemble of all secondary structures for the given sequence;\n{\\em 2})\\, the standard deviation ($\\sigma$) of the number of base pairs per\nstructure;\n{\\em 3})\\, the coefficient of variation $\\frac{\\sigma}{\\mu}$;\n{\\em 4})\\, the RNA sequence length $n$; and\n{\\em 5})\\, the \\mfe (MFE).\nAdditionally, we computed the logarithm base $10$ of \\mfpt\n($\\log_{10}(\\text{MFPT})$), taken over $50$ Monte Carlo runs per sequence\n(log base $10$ of the standard deviation of number of Monte Carlo\nsteps per run was approximately\n9\\% of $\\log_{10}(\\text{MFPT})$ on average). The table shows the correlation between each of these aspects.\nSome correlations are obvious---for example,\n{\\em i})\\;\nthe standard deviation $\\sigma$ is highly correlated with the\ncoefficient of variation $\\frac{\\sigma}{\\mu}$;\n{\\em ii})\\;\nthe mean $\\mu$ is negatively correlated with the\ncoefficient of variation $\\frac{\\sigma}{\\mu}$;\n{\\em iii})\\;\nthe mean $\\mu$ is negatively correlated with the\n\\mfe (MFE) --- if most low energy structures in the ensemble\nhave many base pairs, then it is likely that the \\mfe is very\nlow (i.e. since MFE is negative, the absolute value of MFE increases); and\n{\\em iv})\\;\nsequence length is negatively correlated with MFE --- as sequence length\nincreases, the \\mfe (MFE) decreases.\nHowever, it may appear surprising that\n{\\em v})\\; the\nmean $\\mu$ number of base pairs per structure is independent of MFPT\n(correlation $-0.0363$), although\n{\\em vi})\\; MFE is correlated with MFPT\n(correlation $0.3990$) --- i.e. from {\\em (iii)},\nlower MFE is correlated with a larger average $\\mu$ number of base pairs per\nstructure, from ({\\em vi})\nhigher MFE is correlated with longer folding time, but\nfrom ({\\em v}) the average $\\mu$  number of base pairs per structure is\nindependent of folding time.\nThe most important insight from this table is that\n{\\em vii})\\;\nstandard deviation $\\sigma$ is correlated with \\mfpt---the correlation is statistically significant, with one-tailed\n$p$-value of $0.0002$.}\n\\label{table:correlationFFTborEmpty}\n\\end{table}\n\n\\begin{figure}[!ht]\n\\centering\n\\includegraphics[width=.3\\textwidth]{Figures/FFTbor/AB030643_1_4176-4241.pdf}\n\\includegraphics[width=.3\\textwidth]{Figures/FFTbor/AL645723_11_192421-192359.pdf}\n\\includegraphics[width=.3\\textwidth]{Figures/FFTbor/FFTborOutputFromEmptyStrForTPPriboswitches.pdf}\n\\caption[Example of the graphical output of \\fftbor, when the empty structure is chosen as initial structure \\strSt]{This figure represents the\ngraphical output of \\fftbor, when the empty structure is chosen as\ninitial structure \\strSt.\nThe $x$-axis represents the number of base pairs per structure,\ntaken over the ensemble of all secondary structures for the given RNA\nsequence; the $y$-axis represents Boltzmann probability\n$p(k) = \\frac{\\bfZ{k}{}}{\\fullZ}$,\nwhere \\fullZ is the partition function for all secondary structures\nhaving exactly $k$ base pairs.\n{\\em (Left)}\nFor the {\\em M. musculus} selenocysteine (SECIS) element AB$030643.1$ $4176$--$4241$ from Rfam family\nRF$00031$, the standard deviation $\\sigma$ of the number of base pairs,\ntaken over the ensemble of all secondary structures, is\n$0.7276$, while the logarithm base $10$ of the \\mfpt ($\\log_{10}(\\text{MFPT})$)\nis $4.75$.\n{\\em (Center)}\nFor the {\\em M. musculus} selenocysteine (SECIS) element\nAL$645723.11$ $192421$--$192359$ from Rfam family\nRF$00031$, the standard deviation $\\sigma$ of the number of base pairs,\ntaken over the ensemble of all secondary structures, is\n$2.6794$, while $\\log_{10}(\\text{MFPT})$ is $5.69$.\nAmong the $61$ sequences in the seed alignment of RF$00031$,\nAB$030643.1$ $4176$--$4241$ was the fastest folder, while\nAL$645723.11$ $192421$--$192359$ was the slowest folder.\n{\\em (Right)}\nSuperimposition of output of \\fftbor for two TPP \\rb aptamers: the\n$97$ nt sequence BX$842649.1$ $277414$--$277318$ from {\\em B. bacteriovorus} and the\n$99$ nt sequence AACY$022101973.1$ $389$--$487$ from the marine metagenome, both obtained when\ntaking the empty structure for the initial structure \\strSt.\nThe mean $\\mu$ for the \\fftbor structural profile near the empty\nstructure is $23.0203$  [resp. $27.5821$], the\nstandard deviation $\\sigma$ for the \\fftbor structural profile\nis $2.2253$  [resp. $1.9857$], and the \\kinfold MFPT is\n$311,075.06$ [resp. $61,575.69$] for the TPP \\rb aptamer\nBX$842649.1$ $277414$--$277318$ [resp. AACY$022101973.1$ $389$--$487$].\nThe right panel of this figure should be compared with Figure\n\\ref{fig:fftbor:tppDistributions}.\nThese anecdotal results bear up the correlation between standard deviation\n$\\sigma$ and $\\log_{10}(\\text{MFPT})$ described in Table \\ref{table:correlationFFTborEmpty}.\n}\n\\label{fig:fftbor:correlationFFTborEmpty}\n\\end{figure}\n\nIn the right panel of \\Figref{fftbor:correlationFFTborEmpty}, we\napplied \\fftbor to each of the two randomly chosen TPP \\rb\naptamers BX$842649.1$ $277414$--$277318$ from {\\em B. bacteriovorus}\nand AACY$022101973.1$ $389$--$487$ from the marine metagenome, starting\nfrom the empty reference structure $\\strSt=\\varnothing$.\nThe mean for the \\fftbor structural profile near the empty\nstructure is $\\mu_1=23.0203$  [resp. $\\mu_2=27.5821$], the\nstandard deviation $\\sigma$ for the \\fftbor structural profile\nis $\\sigma_1=2.2253$  [resp. $\\sigma_2=1.9857$], and the \\kinfold MFPT is\n$311,075.06$ [resp. $61,575.69$] for the TPP \\rb aptamer\nBX$842649.1$ $277414$--$277318$ [resp. AACY$022101973.1$ $389$--$487$]. This\nanecdotal evidence supports the hypothesis that small standard deviation\nin \\fftbor distribution is correlated with fast folding.\n\nWe randomized the TPP \\rbs BX$842649.1$ $277414$--$277318$ and\nAACY$022101973.1$ $389$--$487$ by using our implementation of the\nAltschul-Erikson dinucleotide shuffle algorithm\n\\citep{altschulErikson:dinucleotideShuffle}, and then applied \\fftbor to these\nsequences, starting from the empty structure.  The mean $\\mu_1$ and standard\ndeviation $\\sigma_1$ for the \\fftbor distribution for randomized BX$842649.1$ are\nrespectively $\\mu_1=19.93$ and $\\sigma_1=2.88$, while those for randomized\nAACY$022101973.1$ are $\\mu_2=24.39$ and $\\sigma_2=24.00$. Running \\kinfold, with a\nmaximum of $500,000$ steps with $30$ replicates (as explained in the text), we\nfound\nthat for randomized BX$842649$, all $30$ runs converged yielding a \\mfpt\n(MFPT) of $13,022.58$ with standard deviation of $15,221.78$. In contrast for\nrandomized AACY$022101973.1$, only $15$ out of $30$ runs converged within $500,000$ steps,\nand discounting these nonconvergent data, we obtain an average \\mfpt\n(MFPT) of $94,446.93$ with standard deviation of $157,107.43$. This additional\ntest provides more anecdotal evidence supporting our hypothesis that small\nstandard deviation $\\sigma$ in \\fftbor probability density is correlated with fast folding, as measured by MFPT.\n\nThis notion of correlation between the coarse-grained energy landscape and\nkinetics is what motivates the work described in Chapters \\ref{ch:ffttwo}\nand \\ref{ch:hermes}, where a more detailed explanation of kinetics is provided,\nand additional evidence is provided to support this claim.\n\n\\section{Performance characteristics of \\fftbor and \\rnabor}\n\\label{sec:fftbor:speed}\n\nAs visible from the defining recursions, the algorithmic time complexity of\n\\rnabor is \\On{5} and space complexity is \\On{3}, where $n$ is\nthe length of input RNA sequence. In contrast, the time complexity of\n\\fftbor is \\On{4} and space complexity is \\On{2}.\nWhile \\fftbor saves an order of magnitude in performance and memory,\n\\rnabor has the benefit of producing suboptimal structures $\\text{MFE}_k$\nfor all $0 \\leq k \\leq n$, whose free energy is minimal across all structures\nhaving \\bpd $k$ from input structures \\strSt.\n\\Figref{fftbor:benchmarking} displays run time curves for both\n\\rnabor and \\fftbor, when the initial structure \\strSt is\ntaken to be either the empty structure or the \\mfe\n(MFE) structure.\n\nHere, we compare the run time of \\rnabor \\citep{freyhult.b07} and\nthe (unparallelized version of) \\fftbor, using\na Dell Power Edge $1950$, $2$ x Intel Xeon E$5430$ Quad\ncore with $2.80$ GHz and $16$ GB RAM. For $n = 20,40,60,\\dots,300$, in step\nsize of $20$ nt, we generated $n$ random RNA sequences of length $n$ with equal\nprobability for each nucleotide A,C,G,U (i.e. a 0th order Markov chain).\nFor values of $n \\leq 200$, $100$ random sequences of length\n$n$ were generated, while for values of $220 \\leq n \\leq 300$, only\n$10$ sequences of length $n$ were generated.\nRNA sequences larger than $300$ nt were not tested,\ndue to \\On{3} memory constraints required by \\rnabor.\nFor each RNA sequence, \\rnabor and \\fftbor were both run,\neach starting with empty initial structure \\strSt, and also\nwith initial sequence \\strSt taken to be the MFE structure.\nEach data point in the table comprises the average run time for three\nindependent evaluations.\n\n\\begin{figure}[!ht]\n\\centering\n\\includegraphics[width=.9\\textwidth]{Figures/FFTbor/rnaborfftborRunTimeEvan.pdf}\n\\caption[Run times in seconds for \\rnabor and \\fftbor, on random RNA\nof length $20$--$300$ in step size of $20$ nt]{Run times in seconds for \\rnabor and \\fftbor, on random RNA\nof length $20,40,60,\\dots,300$ in step size of $20$ nt. Each algorithm\nwas run with the empty initial structure \\strSt, see rows\n\\rnabor (empty), \\fftbor (empty), and with the \\mfes as the initial structure\n\\strSt, see rows\n\\rnabor (MFE) and \\fftbor (MFE). Note that for both \\rnabor\nand \\fftbor, the run time increases when \\strSt is the MFE structure,\nrather than the empty structure. Notice the radical improvement in the\nrun time of \\fftbor over that of \\rnabor.\n}\n\\label{fig:fftbor:benchmarking}\n\\end{figure}\n\n\\subsection{OpenMP parallelization of \\fftbor}\n\\label{subsec:fftbor:openmp}\n\nOpenMP is a simple and flexible\nmulti-platform shared-memory parallel programming environment, that supports\nparallelizations of C/C++ code---see \\url{http://openmp.org/}.\nUsing OpenMP primitives, we created multiple threads to evaluate the polynomial\n\\fullZx on different \\nRoUs. \\Figref{fftbor:benchmarkingParallel}\npresents benchmarks, executed on\na $24$-core AMD Opteron $6172$ with $2.10$GHz and $64$GB RAM, for the speedup\nof \\fftbor as a function of the number of cores.\nThe data in Table \\ref{table:fftborBenchmarkingParallel} describes average\nrun time in seconds ($\\pm$ one standard deviation) for running \\fftbor\non random RNA of length $200,250,300,400,450,500$ with either $1$ or $2$ cores.\n\\Figref{fftbor:benchmarkingParallel}\npresents similar data for running\n\\fftbor on $2,3,6,4,12,15,20$ cores.\n\\medskip\n\n\\begin{table}[!ht]\n\\centering\n\\begin{tabularx}{\\linewidth}{c *{2}{R}}\n\\toprule\n\\small{$n$} & \\small{Single core} & \\small{Two cores} \\\\\n\\cmidrule(lr){1-3}\n$200$ & $123.2 \\pm 16.2$ & $61.8 \\pm 8.0$ \\\\\n$250$ & $331.1 \\pm 27.2$ & $166.1 \\pm 13.7$ \\\\\n$300$ & $723.4 \\pm 59.9$ & $365.2 \\pm 30.1$ \\\\\n$350$ & $1,380.8 \\pm 95.2$ & $698.4 \\pm 46.9$ \\\\\n$400$ & $2,239.1 \\pm 210.9$ & $1,129.5 \\pm 104.3$ \\\\\n$450$ & $3,635.0 \\pm 857.4$ & $1,980.9 \\pm 126.5$ \\\\\n$500$ & $5,076.7 \\pm 1,292.1$ & $3,389.8 \\pm 788.4$ \\\\\n\\bottomrule\n\\end{tabularx}\n\\caption[Table showing parallel run times in seconds\nfor \\fftbor, using OpenMP]{Table showing parallel run times in seconds\nfor \\fftbor, using OpenMP---\\url{http://openmp.org/}.\nFor each sequence length $200,\\dots,500$,\nfive random RNAs were generated using equal probability for each nucleotide\nA,C,G,U. Run time in seconds, plus or minus one standard deviation, are\ngiven for a $24$-core\nAMD Opteron $6172$ running at $2.10$GHz with $64$GB RAM, with only $1$ [resp. $2$] cores\nused.}\n\\label{table:fftborBenchmarkingParallel}\n\\end{table}\n\n\\begin{figure}[!ht]\n\\centering\n\\includegraphics[width=.75\\textwidth]{Figures/FFTbor/fftborParallelRunTimes.pdf}\n\\caption[]{Graph showing parallel run time of \\fftbor as a function of\nsequence length, running on an AMD Opteron $6172$ running at $2.10$GHz with $64$GB RAM,\nusing respectively $1,2,3,4,6,9,12,15,20$ cores.\n}\n\\label{fig:fftbor:benchmarkingParallel}\n\\end{figure}\n", "meta": {"hexsha": "332e9280fc9b7881107dd93d0506620336b6c44f", "size": 49308, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapters/FFTbor.tex", "max_stars_repo_name": "evansenter/thesis", "max_stars_repo_head_hexsha": "5345bfafcc63947471c0d3a6c427286c05a743f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapters/FFTbor.tex", "max_issues_repo_name": "evansenter/thesis", "max_issues_repo_head_hexsha": "5345bfafcc63947471c0d3a6c427286c05a743f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapters/FFTbor.tex", "max_forks_repo_name": "evansenter/thesis", "max_forks_repo_head_hexsha": "5345bfafcc63947471c0d3a6c427286c05a743f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.6740478299, "max_line_length": 205, "alphanum_fraction": 0.7248316703, "num_tokens": 16047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3019659168629792}}
{"text": "\\paragraph{}\nIn order to speed up the testing of the program, some basic test scenarios have been defined in order to provide a known system that can be loaded into the application during testing in order to speed up the testing process.\n\\vspace{12pt}\n\\begin{enumerate}\n\\item \\textbf{(Ref: TS1)} Single Body with no velocity.\n  \\begin{itemize}\n  \\item Should stay completely stationary.\n  \\item \\textbf{IDT:} 0.1 (Simulation Delta Time)\n  \\item \\textbf{UGC:} 0.1 (Gravitational Constant)\n  \\item \\textbf{BC:} 1 (Body Count)\n    \\begin{itemize}\n    \\item \\textbf{Mass:} 1, \\textbf{Radius:} 1, \\textbf{Pos X:} 0 \\textbf{Y:} 0, \\textbf{Vel X:} 0 \\textbf{Y:} 0\n    \\end{itemize}\n  \\end{itemize}\n\n\\vspace{12pt}  \n\\item \\textbf{(Ref: TS2)} Two body orbital system, orbital velocity.\n  \\begin{itemize}\n  \\item Outer body has the velocity required for a circular orbit around the central body.\n  \\item This is calculated using $v_{circular}=\\sqrt{\\frac{G(M+m)}{r}}$.\n  \\item Orbital period can be found using $T=\\sqrt{\\frac{4\\pi^2r^3}{Gm}}$.\n  \\item It should take $628.3$ seconds or $6283$ Iterations to complete one orbit. ($T/IDT$)\n  \\item \\textbf{IDT:} 0.1\n  \\item \\textbf{UGC:} 0.1\n  \\item \\textbf{BC:} 2\n    \\begin{itemize}\n    \\item \\textbf{Mass:} 1000, \\textbf{Radius:} 10, \\textbf{Pos X:} 0 \\textbf{Y:} 0, \\textbf{Vel X:} 0 \\textbf{Y:} 0\n    \\item \\textbf{Mass:} 0.1, \\textbf{Radius:} 1, \\textbf{Pos X:} 100 \\textbf{Y:} 0, \\textbf{Vel X:} 0 \\textbf{Y:} 1.00005\n    \\end{itemize}\n  \\end{itemize}\n  \n\\vspace{12pt}  \n\\item \\textbf{(Ref: TS3)} Two body collision test, no gravity.\n  \\begin{itemize}\n  \\item Both bodies start with velocity which will lead to a collision.\n  \\item Gravitational constant is 0 to keep the velocity constant.\n  \\item Bodies merge according to $p=mv$, $m_n=m_1+m_2$, $v_n=(p_1+p_2)/m_n$.\n  \\item New radius is calculated by adding together circular areas $\\pi r^2$.\n  \\item \\textbf{IDT:} 0.1\n  \\item \\textbf{UGC:} 0.0\n  \\item \\textbf{BC:} 2\n    \\begin{itemize}\n    \\item \\textbf{Mass:} 1, \\textbf{Radius:} 1, \\textbf{Pos X:} -10 \\textbf{Y:} 0, \\textbf{Vel X:} 1 \\textbf{Y:} 0\n    \\item \\textbf{Mass:} 1, \\textbf{Radius:} 1, \\textbf{Pos X:} 10 \\textbf{Y:} 0, \\textbf{Vel X:} -1 \\textbf{Y:} 0\n    \\end{itemize}\n  \\end{itemize}\n  \n\\vspace{12pt}  \n\\item \\textbf{(Ref: TS4)} Defines a superstructure.\n  \\begin{itemize}\n  \\item Starts the simulation with a superstructure, variable body count.\n  \\item Relies on a separate variable to set body count.\n  \\item \\textbf{IDT:} 0.1\n  \\item \\textbf{UGC:} 0.1\n  \\item \\textbf{BC:} Variable\n    \\begin{itemize}\n    \\item \\textbf{Superstructure}\n      \\begin{itemize}\n      \\item \\textbf{Bodies:} Variable\n      \\item \\textbf{Central Mass:} $\\num{1e5}$\n      \\item \\textbf{Outer Mass:} 0.1\n      \\item \\textbf{Central Radius:} 10\n      \\item \\textbf{Outer Radius:} 0.1\n      \\item \\textbf{Central Pos X:} 0\n      \\item \\textbf{Central Pos Y:} 0\n      \\item \\textbf{Central Vel X:} 0\n      \\item \\textbf{Central Vel Y:} 0\n      \\item \\textbf{Central Spacing:} 50\n      \\item \\textbf{System Radius:} 1000\n      \\end{itemize}\n    \\end{itemize}\n  \\end{itemize}\n  \n\\vspace{12pt}\n\\item \\textbf{(Ref: TS5)} Body travels beyond simulation limits.\n  \\begin{itemize}\n  \\item Should be destroyed once beyond simulation bounds.\n  \\item \\textbf{IDT:} 0.1 (Simulation Delta Time)\n  \\item \\textbf{UGC:} 0.1 (Gravitational Constant)\n  \\item \\textbf{BC:} 1 (Body Count)\n    \\begin{itemize}\n    \\item \\textbf{Mass:} 1, \\textbf{Radius:} 1, \\textbf{Pos X:} $\\num{9.999e15}$ \\textbf{Y:} 0, \\textbf{Vel X:} $\\num{1e8}$ \\textbf{Y:} 0\n    \\end{itemize}\n  \\end{itemize}\n  \n\\vspace{12pt}\n\\item \\textbf{(Ref: TS6)} Body travelling faster than the speed of light.\n  \\begin{itemize}\n  \\item Should be destroyed on iteration.\n  \\item \\textbf{IDT:} 0.1\n  \\item \\textbf{UGC:} 0.1 \n  \\item \\textbf{BC:} 1\n    \\begin{itemize}\n    \\item \\textbf{Mass:} 1, \\textbf{Radius:} 1, \\textbf{Pos X:} 0 \\textbf{Y:} 0, \\textbf{Vel X:} $\\num{3.00e8}$ \\textbf{Y:} 0\n    \\end{itemize}\n  \\end{itemize}  \n  \n\\pagebreak\n\\item \\textbf{(Ref: TS7)} Grid of bodies for testing coordinate mapping and rendering precision.\n  \\begin{itemize}\n  \\item All bodies are fixed, velocity is ignored and not calculated.\n  \\item Bodies in center are positioned at 10 and 100 positions respectively.\n  \\item To the right of the system exists 4 bodies spaced an order of magnitude apart in order to show the loss of rendering precision.\n  \\item \\textbf{IDT:} 0.1\n  \\item \\textbf{UGC:} 0.1 \n  \\item \\textbf{BC:} 20\n    \\begin{itemize}\n    \\item \\textbf{Mass:} 0.001, \\textbf{Radius:} 1, \\textbf{Pos X:} 10 \\textbf{Y:} 0\n    \\item \\textbf{Mass:} 0.001, \\textbf{Radius:} 1, \\textbf{Pos X:} -10 \\textbf{Y:} 0\n    \\item \\textbf{Mass:} 0.001, \\textbf{Radius:} 1, \\textbf{Pos X:} 0 \\textbf{Y:} 10\n    \\item \\textbf{Mass:} 0.001, \\textbf{Radius:} 1, \\textbf{Pos X:} 0 \\textbf{Y:} -10\n    \\item \\textbf{Mass:} 0.001, \\textbf{Radius:} 1, \\textbf{Pos X:} -10 \\textbf{Y:} -10\n    \\item \\textbf{Mass:} 0.001, \\textbf{Radius:} 1, \\textbf{Pos X:} 10 \\textbf{Y:} -10\n    \\item \\textbf{Mass:} 0.001, \\textbf{Radius:} 1, \\textbf{Pos X:} -10 \\textbf{Y:} 10\n    \\item \\textbf{Mass:} 0.001, \\textbf{Radius:} 1, \\textbf{Pos X:} 10 \\textbf{Y:} 10\n    \\item \\textbf{Mass:} 0.001, \\textbf{Radius:} 1, \\textbf{Pos X:} 100 \\textbf{Y:} 0\n    \\item \\textbf{Mass:} 0.001, \\textbf{Radius:} 1, \\textbf{Pos X:} -100 \\textbf{Y:} 0\n    \\item \\textbf{Mass:} 0.001, \\textbf{Radius:} 1, \\textbf{Pos X:} 0 \\textbf{Y:} 100\n    \\item \\textbf{Mass:} 0.001, \\textbf{Radius:} 1, \\textbf{Pos X:} 0 \\textbf{Y:} -100\n    \\item \\textbf{Mass:} 0.001, \\textbf{Radius:} 1, \\textbf{Pos X:} -100 \\textbf{Y:} -100\n    \\item \\textbf{Mass:} 0.001, \\textbf{Radius:} 1, \\textbf{Pos X:} 100 \\textbf{Y:} -100\n    \\item \\textbf{Mass:} 0.001, \\textbf{Radius:} 1, \\textbf{Pos X:} -100 \\textbf{Y:} 100\n    \\item \\textbf{Mass:} 0.001, \\textbf{Radius:} 1, \\textbf{Pos X:} 100 \\textbf{Y:} 100\n    \\item \\textbf{Mass:} 0.001, \\textbf{Radius:} 1, \\textbf{Pos X:} $\\num{1e5}$ \\textbf{Y:} 0\n    \\item \\textbf{Mass:} 0.001, \\textbf{Radius:} 1, \\textbf{Pos X:} $\\num{1e6}$ \\textbf{Y:} 0\n    \\item \\textbf{Mass:} 0.001, \\textbf{Radius:} 1, \\textbf{Pos X:} $\\num{1e7}$ \\textbf{Y:} 0\n    \\item \\textbf{Mass:} 0.001, \\textbf{Radius:} 1, \\textbf{Pos X:} $\\num{1e8}$ \\textbf{Y:} 0\n    \\end{itemize}\n  \\end{itemize}\n  \n  \n\\pagebreak\n\\item \\textbf{(Ref: TS8)} Three body system, Sun - Planet - Moon.\n  \\begin{itemize}\n  \\item An outer body orbits a massive central body.\n  \\item Another body orbits the outer body.\n  \\item \\textbf{IDT:} 0.1\n  \\item \\textbf{UGC:} 0.1 \n  \\item \\textbf{BC:} 3\n    \\begin{itemize}\n    \\item \\textbf{Mass:} 200, \\textbf{Radius:} 5, \\textbf{Pos X:} 0 \\textbf{Y:} 0, \\textbf{Vel X:} 0 \\textbf{Y:} 0\n    \\item \\textbf{Mass:} 1, \\textbf{Radius:} 0.5, \\textbf{Pos X:} 20 \\textbf{Y:} 0, \\textbf{Vel X:} 0 \\textbf{Y:} 1.00005\n    \\item \\textbf{Mass:} 0.001, \\textbf{Radius:} 0.1, \\textbf{Pos X:} 20 \\textbf{Y:} 1, \\textbf{Vel X:} 0.316 \\textbf{Y:} 1.00005\n    \\end{itemize}\n  \\end{itemize}\n  \n\\vspace{12pt}\n\\item \\textbf{(Ref: TS9)} Simple two body system.\n  \\begin{itemize}\n  \\item This system is simple enough to be easy to create a trace table for.\n  \\item The central body is fixed, making it much faster to run calculations.\n  \\item A large time-step is used in order to make the numbers easier to handle.\n  \\item \\textbf{IDT:} 2\n  \\item \\textbf{UGC:} 0.1 \n  \\item \\textbf{BC:} 2\n    \\begin{itemize}\n    \\item \\textbf{Mass:} 99, \\textbf{Radius:} 1, \\textbf{Pos X:} 0 \\textbf{Y:} 0, \\textbf{Fixed}\n    \\item \\textbf{Mass:} 1, \\textbf{Radius:} 1, \\textbf{Pos X:} 10 \\textbf{Y:} 0, \\textbf{Vel X:} 0 \\textbf{Y:} 1\n    \\end{itemize}\n  \\end{itemize}  \n  \n\\pagebreak  \n\\item \\textbf{(Ref: TS10)} Defines a simple two body system using a superstructure.\n  \\begin{itemize}\n  \\item Creates a superstructure with the generation of a single body constrained to 100.\n  \\item \\textbf{IDT:} 0.1\n  \\item \\textbf{UGC:} 0.1\n  \\item \\textbf{BC:} 2\n    \\begin{itemize}\n    \\item \\textbf{Superstructure}\n      \\begin{itemize}\n      \\item \\textbf{Bodies:} 1\n      \\item \\textbf{Central Mass:} $\\num{1e5}$\n      \\item \\textbf{Outer Mass:} 0.1\n      \\item \\textbf{Central Radius:} 10\n      \\item \\textbf{Outer Radius:} 0.1\n      \\item \\textbf{Central Pos X:} 0\n      \\item \\textbf{Central Pos Y:} 0\n      \\item \\textbf{Central Vel X:} 0\n      \\item \\textbf{Central Vel Y:} 0\n      \\item \\textbf{Central Spacing:} 100.0\n      \\item \\textbf{System Radius:} 100.001\n      \\end{itemize}\n    \\end{itemize}\n  \\end{itemize}\n  \n\\vspace{12pt}  \n\\item (Ref: TS11) Stable three body system.\n  \\begin{itemize}\n  \\item This system is a three-body system which remains stable. (Unless perturbed.)\n  \\item The outer bodies have velocity such that they precess around each other.\n  \\item Their presence applies an equal force to both sides of the central body, thus balancing to 0.\n  \\item Any change will send the system into chaotic motion.\n  \\item \\textbf{IDT:} 0.01\n  \\item \\textbf{UGC:} 0.1 \n  \\item \\textbf{BC:} 3\n    \\begin{itemize}\n    \\item \\textbf{Mass:} 1, \\textbf{Radius:} 1, \\textbf{Pos X:} 0 \\textbf{Y:} 0, \\textbf{Vel X:} 0 \\textbf{Y:} 0\n    \\item \\textbf{Mass:} 1, \\textbf{Radius:} 1, \\textbf{Pos X:} 10 \\textbf{Y:} 0, \\textbf{Vel X:} 0 \\textbf{Y:} 0.11\n    \\item \\textbf{Mass:} 1, \\textbf{Radius:} 1, \\textbf{Pos X:} -10 \\textbf{Y:} 0, \\textbf{Vel X:} 0 \\textbf{Y:} -0.11\n    \\end{itemize}\n  \\end{itemize}\n  \n\\pagebreak \n\\item (Ref: TS12) Many Body System\n  \\begin{itemize}\n  \\item This system contains several bodies which will very clearly show the interactions occurring correctly between every body.\n  \\item \\textbf{IDT:} 0.01\n  \\item \\textbf{UGC:} 10\n  \\item \\textbf{BC:} 6\n    \\begin{itemize}\n    \\item \\textbf{Mass:} 1, \\textbf{Radius:} 1, \\textbf{Pos X:} 10 \\textbf{Y:} 2, \\textbf{Vel X:} 0 \\textbf{Y:} 0\n    \\item \\textbf{Mass:} 1, \\textbf{Radius:} 1, \\textbf{Pos X:} -4 \\textbf{Y:} 4, \\textbf{Vel X:} 0 \\textbf{Y:} 0\n    \\item \\textbf{Mass:} 1, \\textbf{Radius:} 1, \\textbf{Pos X:} -18 \\textbf{Y:} 16, \\textbf{Vel X:} 0 \\textbf{Y:} 0\n    \\item \\textbf{Mass:} 1, \\textbf{Radius:} 1, \\textbf{Pos X:} -8 \\textbf{Y:} -12, \\textbf{Vel X:} 0 \\textbf{Y:} 0\n    \\item \\textbf{Mass:} 1, \\textbf{Radius:} 1, \\textbf{Pos X:} 6 \\textbf{Y:} -13, \\textbf{Vel X:} 0 \\textbf{Y:} 0\n    \\item \\textbf{Mass:} 1, \\textbf{Radius:} 1, \\textbf{Pos X:} 8 \\textbf{Y:} 11, \\textbf{Vel X:} 0 \\textbf{Y:} 0\n    \\end{itemize}\n  \\end{itemize}\n\\end{enumerate}", "meta": {"hexsha": "566dd2c4d81532bebea3f90cb5c745a1320421e7", "size": 10451, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/tex/sections/design/testscenarios.tex", "max_stars_repo_name": "btheobald/compa2", "max_stars_repo_head_hexsha": "aa9d5b966fb4c6a4e836e481d9df1bd297de3140", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-02-11T20:01:26.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-30T16:16:02.000Z", "max_issues_repo_path": "doc/tex/sections/design/testscenarios.tex", "max_issues_repo_name": "btheobald/compa2", "max_issues_repo_head_hexsha": "aa9d5b966fb4c6a4e836e481d9df1bd297de3140", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/tex/sections/design/testscenarios.tex", "max_forks_repo_name": "btheobald/compa2", "max_forks_repo_head_hexsha": "aa9d5b966fb4c6a4e836e481d9df1bd297de3140", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.5045454545, "max_line_length": 224, "alphanum_fraction": 0.6436704622, "num_tokens": 4391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3019659168629792}}
{"text": "\\section{Results}\n\\label{chp:study:sec:results}\nIn this chapter we present the results of the executed study which we base the later discussion upon.\nSpecifically, we state the calculated metrics of the two runs.\n\nFirst we look at the metrics of the first run in which we use the crowdsourced dataset $D_{crowd}$.\nHere all three models achieve mostly similar metrics when classifying $D_{crowd_{test}}$.\nAll metrics are listed in \\cref{tab:study:results:first_run} for each model.\n\\begin{table}[htpb]\n    \\centering\n    \\begin{tabular}{l | l l l l }\n        \\toprule\n         Model & Precision & Recall & $F_1$ Score & Average Precision \\\\\n        \\midrule\n        \\ac{BERT} & $0.36$ & $0.82$ & $0.51$ & $0.50$\\\\\n        \\ac{DistilBERT} & $0.31$ & $0.79$ & $0.45$ & $0.47$\\\\\n        \\ac{ERNIE2.0} & $0.48$ & $0.52$ & $0.50$ & $0.47$\\\\\n        \\bottomrule\n    \\end{tabular}\n    \\caption[Study Results on Crowdsourced Dataset]{The results for the crowdsourced dataset $D_{crowd_{test}}$.}\\label{tab:study:results:first_run}\n\\end{table}\n\nAs we describe in \\cref{chp:study:sec:execution}, we performed a second run similar to the first one.\nThe only difference is that the more extensive dataset $D_{all_{train}}$ was used for the training and $D_{all_{test}}$ to calculate the resulting metrics correspondingly.\nThe results of this second run are shown in \\cref{tab:study:results:second_run}.\n\\begin{table}[htpb]\n    \\centering\n    \\begin{tabular}{l | l l l l }\n        \\toprule\n         Model & Precision & Recall & $F_1$ Score & Average Precision \\\\\n        \\midrule\n        \\ac{BERT} & $0.45$ & $0.53$ & $0.48$ & $0.46$\\\\\n        \\ac{DistilBERT} & $0.33$ & $0.71$ & $0.48$ & $0.46$\\\\\n        \\ac{ERNIE2.0} & $0.35$ & $0.85$ & $0.50$ & $0.43$\\\\\n        \\bottomrule\n    \\end{tabular}\n    \\caption[Study Results on Complete Dataset]{The results for the dataset $D_{all_{test}}$.}\\label{tab:study:results:second_run}\n\\end{table}\n", "meta": {"hexsha": "9c478d4b6b12af591bb06ef5ab67fbbfaaa90bbe", "size": 1925, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/05_study/sections/results.tex", "max_stars_repo_name": "HaaLeo/vague-requirements-thesis", "max_stars_repo_head_hexsha": "f9bb53c6f17c2cd1731531ad2a68dd53d72e52e9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/05_study/sections/results.tex", "max_issues_repo_name": "HaaLeo/vague-requirements-thesis", "max_issues_repo_head_hexsha": "f9bb53c6f17c2cd1731531ad2a68dd53d72e52e9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/05_study/sections/results.tex", "max_forks_repo_name": "HaaLeo/vague-requirements-thesis", "max_forks_repo_head_hexsha": "f9bb53c6f17c2cd1731531ad2a68dd53d72e52e9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.358974359, "max_line_length": 171, "alphanum_fraction": 0.6509090909, "num_tokens": 625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.4610167793123158, "lm_q1q2_score": 0.30191745877161336}}
{"text": "\\section{Delegation}\n\\label{sec:delegation}\n\nAn agent owning a key that can sign new blocks can delegate its signing rights\nto another key by means of \\textit{delegation certificates}. These certificates\nare included in the ledger, and therefore also included in the body of the\nblocks in the blockchain.\n\nThere are several restrictions on a certificate posted on the blockchain:\n\\begin{enumerate}\n\\item Only genesis keys can delegate.\n\\item Certificates must be properly signed by the delegator.\n\\item Any given key can delegate at most once per-epoch.\n\\item Any given key can issue at most one certificate in a given slot.\n\\item The epochs in the certificates must refer to the current or to the next\n  epoch. We do not want to allow certificates from past epochs so that a\n  delegation certificate cannot be replayed. On the other hand if we allow\n  certificates with arbitrary future epochs, then a malicious key can issue a\n  delegation certificate per-slot, setting the epoch to a sufficiently large\n  value. This will cause a blow up in the size of the ledger state since we\n  will not be able to clean $\\var{eks}$ (we only clean past epochs). Also note\n  that we do not check the relation between the certificate epoch and the slot\n  in which the certificate becomes active. This would bring additional\n  complexity without any obvious benefit.\n\\item Certificates do not become active immediately, but they require a certain\n  number of slots till they become stable in all the nodes.\n\\end{enumerate}\nThese conditions are formalized in \\cref{fig:rules:delegation-scheduling}.\nRule~\\ref{eq:rule:delegation-scheduling} determines when a certificate can\nbecome ``scheduled''. The definitions used in these rules are presented in\n\\cref{fig:defs:delegation-scheduling}, and the types of the system induced by\n$\\trans{sdeleg}{\\wcard}$ are presented in\n\\cref{fig:ts-types:delegation-scheduling}. Here and in the remaining rules we\nwill be using $k$ as an abstract constant that gives us the chain stability\nparameter.\n\n\\begin{figure}[htb]\n  \\emph{Abstract types}\n  \\begin{equation*}\n    \\begin{array}{r@{~\\in~}lr}\n      c & \\DCert & \\text{delegation certificate}\\\\\n      \\var{vk_g} & \\VKeyGen & \\text{genesis verification key}\\\\\n    \\end{array}\n  \\end{equation*}\n\n  \\emph{Derived types}\n  \\begin{equation*}\n    \\begin{array}{r@{~\\in~}l@{\\qquad=\\qquad}r@{~\\in~}lr}\n      \\var{e} & \\Epoch & n & \\mathbb{N} & \\text{epoch}\\\\\n      \\var{s} & \\Slot & s & \\mathbb{N} & \\text{slot}\\\\\n      \\var{d} & \\SlotCount & s & \\mathbb{N} & \\text{slot}\n    \\end{array}\n  \\end{equation*}\n\n  \\emph{Constraints}\n  \\begin{align*}\n    \\VKeyGen \\subseteq \\VKey\n  \\end{align*}\n\n  \\emph{Abstract functions}\n  \\begin{equation*}\n    \\begin{array}{r@{~\\in~}lr}\n      \\fun{dbody} & \\DCert \\to (\\VKey \\times \\Epoch)\n      & \\text{body of the delegation certificate}\\\\\n      \\fun{dwit} & \\DCert \\to (\\VKeyGen \\times \\Sig)\n      & \\text{witness for the delegation certificate}\\\\\n      \\fun{dwho} & \\DCert \\mapsto (\\VKeyGen \\times \\VKey)\n      & \\text{who delegates to whom in the certificate}\\\\\n      \\fun{depoch} & \\DCert \\mapsto \\Epoch\n      & \\text{certificate epoch}\\\\\n      \\var{k} & \\mathbb{N} & \\text{chain stability parameter}\n    \\end{array}\n  \\end{equation*}\n  \\caption{Delegation scheduling definitions}\n  \\label{fig:defs:delegation-scheduling}\n\\end{figure}\n\n\\begin{figure}[htb]\n  \\emph{Delegation scheduling environments}\n  \\begin{equation*}\n    \\DSEnv =\n    \\left(\n      \\begin{array}{r@{~\\in~}lr}\n        \\mathcal{K} & \\powerset{\\VKeyGen} & \\text{allowed delegators}\\\\\n        \\var{e} & \\Epoch & \\text{epoch}\\\\\n        \\var{s} & \\Slot & \\text{slot}\\\\\n      \\end{array}\n    \\right)\n  \\end{equation*}\n\n  \\emph{Delegation scheduling states}\n  \\begin{equation*}\n    \\DSState\n    = \\left(\n      \\begin{array}{r@{~\\in~}lr}\n        \\var{sds} & \\seqof{(\\Slot \\times (\\VKeyGen \\times \\VKey))} & \\text{scheduled delegations}\\\\\n        \\var{eks} & \\powerset{(\\Epoch \\times \\VKeyGen)} & \\text{key-epoch delegations}\n      \\end{array}\n    \\right)\n  \\end{equation*}\n\n  \\emph{Delegation scheduling transitions}\n  \\begin{equation*}\n    \\var{\\_} \\vdash\n    \\var{\\_} \\trans{sdeleg}{\\_} \\var{\\_}\n    \\subseteq \\powerset (\\DSEnv \\times \\DSState \\times \\DCert \\times \\DSState)\n  \\end{equation*}\n  \\caption{Delegation scheduling transition-system types}\n  \\label{fig:ts-types:delegation-scheduling}\n\\end{figure}\n\n\\begin{figure}[htb]\n  \\begin{equation}\n    \\label{eq:sdeleg-bootstrap}\n    \\inference\n    {\n      \\var{sds_0} \\leteq \\epsilon\n      &\n      \\var{eks_0} \\leteq \\emptyset\n    }\n    {\n      {\\left(\\begin{array}{l}\n       \\mathcal{K}\\\\\n        e\\\\\n        s\n      \\end{array}\\right)}\n      \\vdash\n      \\trans{sdeleg}{}\n      \\left(\n        \\begin{array}{l}\n          \\var{sds_0}\\\\\n          \\var{eks_0}\n        \\end{array}\n      \\right)\n    }\n  \\end{equation}\n  \\nextdef\n  \\begin{equation}\n    \\label{eq:rule:delegation-scheduling}\n    \\inference\n    {\n      (\\var{vk_s},~ \\sigma) \\leteq \\dwit{c}\n      & \\verify{vk_s}{\\serialised{\\dbody{c}}}{\\sigma} & vk_s \\in \\mathcal{K}\\\\ ~ \\\\\n      (\\var{vk_s},~ \\var{vk_d}) \\leteq \\dwho{c} & e_d \\leteq \\depoch{c}\n      & (e_d,~ \\var{vk_s}) \\notin \\var{eks} & 0 \\leq e_d - e \\leq 1 \\\\ ~ \\\\\n      d \\leteq 2 \\cdot k & (s + d,~ (\\var{vk_s},~ \\wcard)) \\notin \\var{sds}\\\\\n    }\n    {\n      {\\left(\\begin{array}{l}\n       \\mathcal{K}\\\\\n        e\\\\\n        s\n      \\end{array}\\right)}\n      \\vdash\n      {\n        \\left(\n          \\begin{array}{l}\n            \\var{sds}\\\\\n            \\var{eks}\n          \\end{array}\n        \\right)\n      }\n      \\trans{sdeleg}{c}\n      {\n        \\left(\n          \\begin{array}{l}\n            \\var{sds}; (s + d,~ (\\var{vk_s},~ \\var{vk_d}))\\\\\n            \\var{eks} \\cup \\{(e_d,~ \\var{vk_s})\\}\n          \\end{array}\n        \\right)\n      }\n    }\n  \\end{equation}\n  \\caption{Delegation scheduling rules}\n  \\label{fig:rules:delegation-scheduling}\n\\end{figure}\n\n\\clearpage\n\nThe rules in Figure~\\ref{fig:rules:delegation} model the activation of\ndelegation certificates. Once a scheduled certificate becomes active\n(see~\\cref{sec:delegation-interface-rules}), the delegation map is changed by\nit only if:\n\\begin{itemize}\n\\item The delegating key ($\\var{vk_s}$) did not activate a delegation\n  certificate in a slot greater or equal than the certificate slot ($s$). This\n  check is performed to avoid having the constraint that the delegation\n  certificates have to be activated in slot order.\n\\item The key being delegated to ($\\var{vk_d}$) has not been delegated by\n  another key (injectivity constraint).\n\\end{itemize}\nThe reason why we check that the delegation map is injective is to avoid a\npotential risk (during the OBFT era) in which a malicious node gets control of\na genesis key $\\var{vk_m}$ that issued the maximum number of blocks in a given\nwindow. By delegating to another key $\\var{vk_d}$, which was already delegated to\nby some other key $\\var{vk_g}$, the malicious node could prevent $\\var{vk_g}$\nfrom issuing blocks. Even though the delegation certificates take several slots\nto become effective, the malicious node could calculate when the certificate\nwould become active, and issue a delegation certificate at the right time.\n\nAs an additional advantage, by having an injective delegation map, we are able\nto simplify our specification when it comes to counting the blocks issued by\n(delegates of) genesis keys.\n\nNote also, that we could not impose the injectivity constraint in\nRule~\\ref{eq:rule:delegation-scheduling} since we do not have information about\nthe delegations that will become effective. We could of course detect a\nviolation in the injectivity constraint when scheduling a delegation\ncertificate, but this will lead to a complex computation and larger state in\nsaid rule.\n\nFinally, note that we do not want to reject a scheduled delegation that would\nviolate the injectivity constraint (since delegation might not have been\nscheduled by the node issuing the block). Instead, we simply ignore the\ndelegation certificate (Rule~\\ref{eq:rule:delegation-nop}).\n\n\\begin{figure}[htb]\n  \\begin{align*}\n    & \\unionoverrideRight \\in (A \\mapsto B) \\to (A \\mapsto B) \\to (A \\mapsto B)\n    & \\text{union override}\\\\\n    & d_0 \\unionoverrideRight d_1 = d_1 \\cup (\\dom d_1 \\subtractdom d_0)\n  \\end{align*}\n  \\caption{Functions used in delegation rules}\n  \\label{fig:funcs:delegation}\n\\end{figure}\n\n\\begin{figure}[htb]\n  \\emph{Delegation environments}\n  \\begin{equation*}\n    \\DEnv =\n    \\left(\n      \\begin{array}{r@{~\\in~}lr}\n        \\mathcal{K} & \\powerset{\\VKeyGen} & \\text{allowed delegators}\n      \\end{array}\n    \\right)\n  \\end{equation*}\n\n  \\emph{Delegation states}\n  \\begin{align*}\n    & \\DState\n      = \\left(\n        \\begin{array}{r@{~\\in~}lr}\n          \\var{dms} & \\VKeyGen \\mapsto \\VKey & \\text{delegation map}\\\\\n          \\var{dws} & \\VKeyGen \\mapsto \\Slot & \\text{when last delegation occurred}\\\\\n        \\end{array}\\right)\n  \\end{align*}\n  \\emph{Delegation transitions}\n  \\begin{equation*}\n    \\_ \\vdash \\_ \\trans{adeleg}{\\_} \\_ \\in\n    \\powerset (\\DEnv \\times \\DState \\times (\\Slot \\times (\\VKeyGen \\times \\VKey)) \\times \\DState)\n    \\end{equation*}\n  \\caption{Delegation transition-system types}\n  \\label{fig:ts-types:delegation}\n\\end{figure}\n\n\\begin{figure}[htb]\n  \\begin{equation}\n    \\label{eq:adeleg-bootstrap}\n    \\inference\n    {\n      \\var{dms_0} \\leteq \\Set{k \\mapsto k}{k \\in \\mathcal{K}} &\n      \\var{dws_0} \\leteq \\Set{k \\mapsto 0}{k \\in \\mathcal{K}}\n    }\n    {\n      \\left(\n        \\mathcal{K}\n      \\right)\n      \\vdash\n      \\trans{adeleg}{}\n      \\left(\n        \\begin{array}{l}\n          \\var{dms_0}\\\\\n          \\var{dws_0}\n        \\end{array}\n      \\right)\n    }\n  \\end{equation}\n  \\nextdef\n  \\begin{equation}\\label{eq:rule:delegation-change}\n    \\inference\n    {\n      \\var{vk_d} \\notin \\range~\\var{dms} & (\\var{vk_s} \\mapsto s_p \\in \\var{dws} \\Rightarrow s_p < s)\n    }\n    {\n      \\left(\\mathcal{K}\\right)\n      \\vdash\n      \\left(\n      \\begin{array}{r}\n        \\var{dms}\\\\\n        \\var{dws}\n      \\end{array}\n      \\right)\n      \\trans{adeleg}{(s,~ (vk_s,~ vk_d))}\n      \\left(\n      \\begin{array}{lcl}\n        \\var{dms} & \\unionoverrideRight & \\{\\var{vk_s} \\mapsto \\var{vk_d}\\}\\\\\n        \\var{dws} & \\unionoverrideRight & \\{\\var{vk_s} \\mapsto s \\}\n      \\end{array}\n      \\right)\n    }\n  \\end{equation}\n  \\nextdef\n  \\begin{equation}\\label{eq:rule:delegation-nop}\n    \\inference\n    {\\var{vk_d} \\in \\range~\\var{dms} \\vee (\\var{vk_s} \\mapsto s_p  \\in \\var{dws}  \\wedge s \\leq s_p)\n    }\n    {\n      \\left(\\mathcal{K}\\right)\n      \\vdash\n      \\left(\n      \\begin{array}{r}\n        \\var{dms}\\\\\n        \\var{dws}\n      \\end{array}\n      \\right)\n      \\trans{adeleg}{(s,~ (\\var{vk_s},~ \\var{vk_d}))}\n      \\left(\n      \\begin{array}{lcl}\n        \\var{dms}\\\\\n        \\var{dws}\n      \\end{array}\n      \\right)\n    }\n  \\end{equation}\n  \\caption{Delegation inference rules}\n  \\label{fig:rules:delegation}\n\\end{figure}\n\n\\clearpage\n\n\\subsection{Delegation sequences}\n\\label{sec:delegation-sequences}\n\nThis section presents the rules that model the effect that sequences of\ndelegations have on the ledger.\n\n\\begin{figure}[htb]\n  \\begin{equation}\n    \\inference\n    {\n      {\\begin{array}{l}\n         \\var{delegEnv}\n      \\end{array}}\n      \\vdash\n      \\trans{\\hyperref[eq:sdeleg-bootstrap]{sdeleg}}{}\n      \\var{delegSt}\n    }\n    {\n      {\\begin{array}{l}\n         \\var{delegEnv}\n      \\end{array}}\n      \\vdash\n      \\trans{sdelegs}{}\n      \\var{delegSt}\n    }\n  \\end{equation}\n  \\nextdef\n  \\begin{equation}\n    \\label{eq:rule:delegation-scheduling-seq-base}\n    \\inference\n    {}\n    {\n      \\var{delegEnv}\n      \\vdash\n      \\var{delegSt}\n      \\trans{sdelegs}{\\epsilon}\n      \\var{delegSt}\n    }\n  \\end{equation}\n  \\nextdef\n  \\begin{equation}\n    \\label{eq:rule:delegation-scheduling-seq-ind}\n    \\inference\n    {\n      \\var{delegEnv}\n      \\vdash\n      \\var{delegSt}\n      \\trans{sdelegs}{\\Gamma}\n      \\var{delegSt'}\n      &\n      \\var{delegEnv}\n      \\vdash\n      \\var{delegSt'}\n      \\trans{\\hyperref[fig:rules:delegation-scheduling]{sdeleg}}{c}\n      \\var{delegSt''}\n    }\n    {\n      \\var{delegEnv}\n      \\vdash\n      \\var{delegSt}\n      \\trans{sdelegs}{\\Gamma; c}\n      \\var{delegSt''}\n    }\n  \\end{equation}\n  \\caption{Delegation scheduling sequence rules}\n  \\label{fig:rules:delegation-scheduling-seq}\n\\end{figure}\n\n\\begin{figure}\n  \\begin{equation}\n    \\inference\n    {\n      {\\begin{array}{l}\n         \\var{delegEnv}\n      \\end{array}}\n      \\vdash\n      \\trans{\\hyperref[eq:adeleg-bootstrap]{adeleg}}{}\n      \\var{delegSt}\n    }\n    {\n      {\\begin{array}{l}\n         \\var{delegEnv}\n      \\end{array}}\n      \\vdash\n      \\trans{adelegs}{}\n      \\var{delegSt}\n    }\n  \\end{equation}\n  \\nextdef\n  \\begin{equation}\n    \\label{eq:rule:delegation-seq-base}\n    \\inference\n    {}\n    {\n      \\var{delegEnv}\n      \\vdash\n      \\var{delegSt}\n      \\trans{adelegs}{\\epsilon}\n      \\var{delegSt}\n    }\n  \\end{equation}\n  \\nextdef\n  \\begin{equation}\n    \\label{eq:rule:delegation-seq-ind}\n    \\inference\n    {\n      \\var{delegEnv}\n      \\vdash\n      \\var{delegSt}\n      \\trans{adelegs}{\\Gamma}\n      \\var{delegSt'}\n      &\n      \\var{delegEnv}\n      \\vdash\n      \\var{delegSt'}\n      \\trans{\\hyperref[fig:rules:delegation]{adeleg}}{c}\n      \\var{delegSt''}\n    }\n    {\n      \\var{delegEnv}\n      \\vdash\n      \\var{delegSt}\n      \\trans{adelegs}{\\Gamma; c}\n      \\var{delegSt''}\n    }\n  \\end{equation}\n  \\caption{Delegations sequence rules}\n  \\label{fig:rules:delegation-seq}\n\\end{figure}\n\n\\subsection{Deviation from the \\texttt{cardano-sl} implementation}\n\\label{sec:delegation:deviation-cardano-sl-imp}\n\nIn the \\texttt{cardano-sl} implementation, the block issuer needs to include a\ndelegation certificate in the block, which witness the fact that a genesis key\ngave the issuer the rights of issuing blocks on behalf of this genesis key. The\nreasons why this was implemented in this way in \\texttt{cardano-sl} are not\nclear, since the delegation certificates are posted on the chain, so the ledger\nstate contains the information about who delegates to whom. Hence in the\ncurrent specification we use a heavyweight delegation scheme, i.e. where the\ncertificates are posted on the chain, but an implementation of this rules that\naims at being compatible with the implementation in \\texttt{cardano-sl} has to\ntake the fact that delegation certificates are also present in a block into\naccount.\n", "meta": {"hexsha": "ec19f618fea59ac6ad7021b648004bf82edfe97b", "size": 14379, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "byron/ledger/formal-spec/delegation.tex", "max_stars_repo_name": "ilap/cardano-ledger-specs", "max_stars_repo_head_hexsha": "6474f68b24d05175fc3fd44a9bdfa95bda703a25", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 108, "max_stars_repo_stars_event_min_datetime": "2019-03-24T02:26:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-30T05:27:16.000Z", "max_issues_repo_path": "byron/ledger/formal-spec/delegation.tex", "max_issues_repo_name": "ilap/cardano-ledger-specs", "max_issues_repo_head_hexsha": "6474f68b24d05175fc3fd44a9bdfa95bda703a25", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1266, "max_issues_repo_issues_event_min_datetime": "2019-03-18T20:23:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-04T12:50:51.000Z", "max_forks_repo_path": "byron/ledger/formal-spec/delegation.tex", "max_forks_repo_name": "ilap/cardano-ledger-specs", "max_forks_repo_head_hexsha": "6474f68b24d05175fc3fd44a9bdfa95bda703a25", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 86, "max_forks_repo_forks_event_min_datetime": "2019-03-29T06:53:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-04T17:17:15.000Z", "avg_line_length": 30.2715789474, "max_line_length": 101, "alphanum_fraction": 0.6380833159, "num_tokens": 4518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.301870442443736}}
{"text": "\\documentclass[prb,preprint]{revtex4-1} \n% The line above defines the type of LaTeX document.\n% Note that AJP uses the same style as Phys. Rev. B (prb).\n\n% The % character begins a comment, which continues to the end of the line.\n\n\\usepackage{amsmath}  % needed for \\tfrac, \\bmatrix, etc.\n\\usepackage{amsfonts} % needed for bold Greek, Fraktur, and blackboard bold\n\\usepackage{graphicx}\n\\usepackage{amssymb} % needed for figures\n\n\\DeclareMathOperator{\\dd}{d\\!}\n\\DeclareMathOperator{\\ddd}{\\mathrm{d}}\n\n\\begin{document}\n\n% Be sure to use the \\title, \\author, \\affiliation, and \\abstract macros\n% to format your title page.  Don't use lower-level macros to  manually\n% adjust the fonts and centering.\n\n\\title{Demystifying the Lagrangian of classical mechanics} %Derivation and Motivation of the Lagrangian of Classical Mechanics\n% In a long title you can use \\\\ to force a line break at a certain location.\n\n\\author{Gerd Wagner}\n\\email{gerdhwagner@t-online.de} % optional\n\\affiliation{Mayener Str. 131, 56070 Koblenz, Germany} % optional second address\n% If there were a second author at the same address, we would put another \n% \\author{} statement here.  Don't combine multiple authors in a single\n% \\author statement.\n%\\affiliation{mailing address}\n% Please provide a full mailing address here.\n\n\\author{Matthew W. Guthrie}\n\\email{matthew.guthrie@ucf.edu}\n\\affiliation{Department of Physics, University of Central Florida, Orlando, FL 32816}\n\n% See the REVTeX documentation for more examples of author and affiliation lists.\n\n\\date{\\today}\n\n\\begin{abstract} \nThe Lagrangian formulation of classical mechanics is extremely useful for a vast array of physics problems encountered in the undergraduate and graduate physics curriculum. Unfortunately, many treatments of this topic lack explanations of the most basic details that make Lagrangian mechanics so practical. In this paper, we detail the steps taken to arrive at the principle of stationary action, the Euler-Lagrange equations, and the Lagrangian of classical mechanics. These steps are: 1) the calculation of the minimal distance between two points in a plane, to introduce the variational principle and to derive the Euler-Lagrange equation; 2) a straightforward reformulation of Newton's second law in the form of Euler-Lagrange equations and formulation of the principle of stationary action; and 3) proving that Euler-Lagrange equations are independent of arbitrary coordinate transformations and motivating that this independence is desirable for classical mechanics. This paper is targeted toward the advanced undergraduate student who, like our own experiences, struggles with details which are not seen as crucial to the utilization of the tools developed by Lagrangian mechanics, and is especially frustrated by the question ``\\textit{why} is the Lagrangian always kinetic minus potential energy?'' We answer this question in a simple and approachable manner.\n\\end{abstract}  \n\n\n\n\\maketitle\n\n\n\n\\section{Introduction}\\label{introduction}\n\nLagrangian formulation of mechanics is a powerful description of classical mechanics. To some students, Lagrangian mechanics can be seemingly separate from the more familiar Newtonian formulation. Many undergraduate students who are taking a classical mechanics course have difficulties understanding how and why the Lagrangian formulation is an equivalent description of motion. Significant learning difficulty arises from the presentation of the material when students first encounter Lagrangian mechanics. Lagrangian mechanics presents an entirely new way for students to think about physics and this shift in thinking can be difficult. Often through a lack of class time to cover material, many of the treatments of the subject in university courses and popular textbooks relies on incomplete arguments, especially when considering the Lagrangian ($L$) itself. It is difficult to understand why the Lagrangian takes the intriguing form $L=T-V$, the difference between a particle's kinetic ($T$) and potential ($V$) energies (which are functions of position \\boldmath$r$\\unboldmath, velocity \\boldmath$\\dot{r}$\\unboldmath, and time $t$). \n\nThe most popular undergraduate level treatments of the Lagrangian simply accept the definition as it is given and move on to using it to solve problems. Taylor~\\cite[p.~238]{taylor2005classical} includes the explicit statement that the reader is ``certainly entitled to ask why the quantity $T-U$ should be of any interest''\\footnote{Taylor uses $U$ for the potential energy function.} and continues to say that ``there seems to be no simple answer to this question except that it is.'' Marion ~\\cite[p.~198-199]{marion1970classical} and Folwes and Cassiday~\\cite[p.~393]{fowles1999analytical} merely define the Lagrangian and move to its utility. Gregory~\\cite[p.~348]{gregory2006classical} explains the Lagrangian in further detail, including a detailed derivation, although the information is presented over multiple sections and chapters with numerous digressions.\n\nIn our treatment presented in this paper, the Lagrangian formalism arises naturally through an introductory example from geometry. We then utilize the formalism to reformulate Newton's second law in the form of the Euler-Lagrange equation. To motivate the new formulation of Newton's second law, we prove the invariance of the Euler-Lagrange equation under arbitrary coordinate transformations. To make clear why this property is important for physics, we remind the reader that the laws of nature do not depend on the coordinates we use to describe them. On the other hand, physicists cannot formulate laws without coordinates and physical equations usually look different in different coordinates\\footnote{Coordinate-free laws of physics do exist (see Maxwell's equations written in the language of differential forms or Einstein's equations). However, these formulations are not very useful until a coordinate system is chosen.}. This is why the relation of physical theories to coordinates should be as well defined and restricted as possible. The Lagrangian formalism fulfills this demand through the Euler-Lagrange equations being independent of coordinate transformations. Lagrangian functionals do depend on coordinates but in the simplest way physicists can think of: they transform like scalars.\n\nThinking about the relation of the laws of physics to coordinates proved fruitful in the past.\nProbably the most famous example is Einstein's first paper on special relativity~\\cite{EinsteinSpecialRelativity}.\nIn this paper we follow this tradition, reformulating Newton's second law in the form of Euler-Lagrange equations. As a result, the Lagrangian of classical mechanics appears naturally without requiring further motivation or derivation. \n\n\n\\section{The Lagrangian formalism and the minimal distance between two points in a plane}\\label{distance}\n\nThis section is adapted from many sources, chiefly Goldstein's Classical Mechanics textbook~\\cite{goldstein2002classical}. Because it is a simple introduction to both the functional that we will derive to be the Lagrangian, and to techniques in the calculus of variations (a pre-requisite topic to understanding the Lagrangian formalism), we aim to show that the minimal distance between two points in a plane is a straight line. \n%This same derivation is often used to motivate and introduce the calculus of variations which is a pre-requisite topic to understand the Lagrangian formalism.\n\\footnote{Some limitations are: we limit ourselves to lines that can be written as one dimensional functions $y=f(x)$ while curves in two dimensions would be more general. We assume the shortest distance must be a differentiable function (although continuous would be sufficient). Foremost, we satisfy ourselves with finding a condition that makes the curve only stationary instead of minimal.}\n\nThe arc length $S$ of a function $y(x)$ between two points $(x_1,y_1)$ and $(x_2,y_2)$ is given by\n\n\\begin{equation}\nS=\\int\\limits_{x_1}^{x_2}\\sqrt{\\dd x^2 + \\dd y^2}.\n\\end{equation}\nFactoring a $\\dd x$ from the radical results in the following equation\n\\begin{equation}\nS= \\int\\limits_{x_1}^{x_2}\\sqrt{1 + \\left(\\frac{\\dd y}{\\dd x}\\right)^2} \\dd x,\n\\end{equation}\nand defining $y' := \\frac{\\dd y}{\\dd x}$ gives a convenient representation for the equation representing the arc length of $y(x)$ as a function of how $y$ changes over its length, %``changes'' is not the best terminology.\n\n\\begin{equation}\nS = \\int\\limits_{x_1}^{x_2}\\sqrt{1 + y'^2} \\dd x.\n\\end{equation}\nWe generalize this formula by writing\n\\begin{equation}\nS=\\int\\limits_{x_1}^{x_2} G(y,y',x) \\dd x .\n\\end{equation}\nAlthough in our example $G = \\sqrt{1 + y'^2}$ only depends on $y'$ and not explicitly on $y$ or $x$, we can also assume dependence on $y$ and $x$. %This is to say that later back replacements of $G$ by $\\sqrt{1 + y'^2}$ will still be possible.\nIf formulas we derive for $G$ contain derivatives of $G$ with respect to $y$ or $x$, we just replace these terms with zero as the derivative of a function with respect to a variable it does not depend on is always zero.\n\n% Former version:\n% and making the assumption that $G = \\sqrt{1 + y'^2}$ only depends on $y'$ and not on $y$ or $x$. We further do as if $G$ would depend on more variables than it actually does. This does no harm to later back replacements of $G$ either. Should formulas we derive for $G$ contain derivatives of $G$ with respect to these new variables, we just replace these terms with zero as the derivative of a function with respect to a variable it does not depend on is always zero. %I'm struggling to find a situation where this would happen (but it is of course mathematically true)\n\nTo find the function $y(x)$ that minimizes $S$, we make the simplifying assumption that it is sufficient to find the $y(x)$ that makes $S$ stationary. In other words, we assume that S has exactly one minimum.\nTo do this, we consider small but arbitrary variations $\\delta y$ of $y$ and try to find a condition that causes $\\delta S$ to vanish. \nDuring this, the endpoints $(x_1,y_1)$ and $(x_2,y_2)$ are kept fixed; therefore the variations $\\delta y$ have the property $\\delta y(x_1) = \\delta y(x_2) = 0$. \nAs a result,\n\n\\begin{equation}\n\\delta S = \\int\\limits_{x_1}^{x_2} \\left(\\frac{\\partial G}{\\partial y} \\delta y\n+ \\frac{\\partial G}{\\partial y'} \\delta y' \\right) \\dd x.\n\\end{equation}\nUsing $\\delta y' = y_2' - y_1' = \\frac{\\ddd }{\\dd x}(y_2 - y_1) = \\frac{\\ddd}{\\dd x} \\delta y$ and integration by parts for the second term, we find\n\\begin{equation}\n\\delta S = \\int\\limits_{x_1}^{x_2} \\left( \\frac{\\partial G}{\\partial y} \\delta y\n- \\frac{\\ddd}{\\dd x}\\frac{\\partial G}{\\partial y'} \\delta y \\right) \\dd x\n+ \\left[\\frac{\\partial G}{\\partial y'} \\delta y \\right]_{x_1}^{x_2}.\n\\end{equation}\nThe last term vanishes because $\\delta y(x_1) = \\delta y(x_2) = 0$, and we are left with\n\\begin{equation}\n\\delta S = \\int\\limits_{x_1}^{x_2} \\left( \\frac{\\partial G}{\\partial y}\n- \\frac{\\ddd}{\\dd x}\\frac{\\partial G}{\\partial y'} \\right) \\delta y \\; \\dd x.\n\\end{equation}\nFor $S$ to be stationary, $\\delta S$ must vanish. Since $\\delta y$ is arbitrary the condition must be\n\\begin{equation}\\label{e-l}\n\\frac{\\partial G}{\\partial y} - \\frac{\\ddd}{\\dd x}\\frac{\\partial G}{\\partial y'} = 0.\n\\end{equation}\nThis equation is called an Euler-Lagrange equation. The procedure of looking for a condition to make $S$ stationary under a function $G(y,y',x)$ is called the Lagrangian formalism. If we substitute $G = \\sqrt{1+y'^2}$ into equation \\eqref{e-l}, we see that $y'$ must be constant and thus $y(x)$ is a straight line connecting $(x_1,y_1)$ and $(x_2,y_2)$.\n\n\n\n\\section{Application to Newtonian mechanics} \\label{application}\nAs we discussed in section \\ref{introduction}% and will motivate through section \\ref{invariance}\n, it is desirable to write Newton's law $F=ma$ in the form of an Euler-Lagrange equation. Doing so will provide us with a function like $G$ from the previous section, only now the function will have important physical implications. This function is called the Lagrangian of classical mechanics.\n\nTo proceed, we rearrange Newton's second law\n\n\\begin{equation}\n0 = ma - F.\n\\end{equation}\nThe first term can be rewritten as follows:\n\\begin{equation}\nma = m \\ddot{r} = \\frac{\\ddd}{\\dd t} (m \\dot{r})\n= \\frac{\\ddd}{\\dd t} \\frac{\\partial}{\\partial \\boldmath\\dot{r}\\unboldmath} \\left(\\frac{1}{2} m \\dot{r}^2 \\right)\n= \\frac{\\ddd}{\\dd t} \\frac{\\partial T}{\\partial \\dot{r}},\n\\end{equation}\nwhere $T:=\\frac{1}{2} m \\dot{r}^2$ is the classical kinetic energy of the system. For the second term, we assume the force $F$ to be conservative. Consequently, there exists a potential $V$ such that\n\\begin{equation}\nF = - \\frac{\\partial V}{\\partial r} = \\frac{\\partial (-V)}{\\partial r}.\n\\end{equation}\nUsing both rewritten terms, Newton's law becomes\n\\begin{equation}\n0 = \\frac{\\ddd}{\\dd t} \\frac{\\partial T}{\\partial \\dot{r}} - \\frac{\\partial (-V)}{\\partial r}.\n\\end{equation}\nIf we assume that $\\partial T/ \\partial r = 0$ and $\\partial V / \\partial \\dot{r} = 0$, which is nearly always true in Newtonian mechanics, we can convert the equation to\n\\begin{equation}\\label{e-lwithtv}\n0 = \\frac{\\ddd}{\\dd t} \\frac{\\partial (T-V)}{\\partial \\dot{r}} - \\frac{\\partial (T-V)}{\\partial r}.\n\\end{equation}\n\n\\section{Invariance of the Euler-Lagrange equation under coordinate transformations} \\label{invariance}\n\nThis section was inspired by the first chapter of Hagen (2009)~\\cite{hagen2009path}.\nLet $y=f(Y,x)$ be an invertible and differentiable coordinate transformation.\n\\footnote{The most effective tool in a physicist's toolbox when solving physics problems is picking an appropriate coordinate system.\nA pendulum in Euclidean $(x,y)$ coordinates makes analyzing the problem cumbersome, but in circular $(r,\\theta)$ coordinates, analysis becomes simple. \nTranslating from the coordinate system of the problem statement to the coordinate system that best simplifies the system usually provides great insight, but translating back to the coordinate system of the problem statement is still necessary to solve the problem.}\n%This means for any $x$ the transformation $f$ is supposed to be an invertible and differentiable function of the new coordinate $Y$.\n%The dependence on $x$ is optional, which is to say that we also well allow transformations $f$ that are only functions of $Y$.\n%\nWe define the transformed function $\\widetilde{G}$ through $G$ by\n\\begin{equation} \\label{lagrangian-transform}\n\\widetilde{G}(Y,Y',x) := G(f,f',x).\n\\end{equation}\nUsing the derivation from section \\ref{distance}, we find that making $S = \\int\\limits_{x_1}^{x_2} \\widetilde{G}(Y,Y',x) \\dd x$ stationary requires the Euler-Lagrange equation\n\n\\begin{equation}\n\\frac{\\partial \\widetilde{G}}{\\partial Y}\n- \\frac{\\ddd}{\\dd x}\\frac{\\partial \\widetilde{G}}{\\partial Y'} = 0\n\\end{equation}\nbe satisfied. This result is again reached by considering a small but arbitrary variation $\\delta Y$ which again vanishes at its endpoints.\n\nLikewise, the variation of the same $S$ can be expressed by\n\\begin{equation}\n\\delta S = \\int\\limits_{x_1}^{x_2} \\left( \\frac{\\partial G}{\\partial f} \\delta f\n+ \\frac{\\partial G}{\\partial f'} \\delta f' \\right) \\dd x\n\\end{equation}\nwhere $\\delta f$ is given by $\\delta f = \\frac{\\partial f}{\\partial Y} \\delta Y$.\n\n\nUsing $\\delta f' = f_2' - f_1' = \\frac{\\ddd}{\\dd x}(f_2 - f_1) = \\frac{\\dd}{\\dd x} \\delta f$ and integration by parts for the second term we find\n\\begin{equation}\n\\delta S = \\int\\limits_{x_1}^{x_2} \\left( \\frac{\\partial G}{\\partial f}\n- \\frac{\\ddd}{\\dd x} \\frac{\\partial G}{\\partial f'} \\right) \\delta f \\, \\dd x \\;\n+ \\; \\left[\\frac{\\partial G}{\\partial f'} \\delta f \\right]_{x_1}^{x_2}.\n\\end{equation}\nAs $\\delta Y$ goes to $0$ at the endpoints, so does $\\delta f$ which causes the last term to vanish. From the arbitrariness of $\\delta Y$ follows the arbitrariness of $\\delta f$. The only mechanism for $\\delta S$ to vanish is\n\n\\begin{equation}\n0 = \\frac{\\partial G}{\\partial f} - \\frac{\\ddd}{\\dd x} \\frac{\\partial G}{\\partial f'}\n= \\frac{\\partial G}{\\partial y} - \\frac{\\ddd}{\\dd x} \\frac{\\partial G}{\\partial y'}.\n\\end{equation}\nThis shows that the Euler-Lagrange equation takes the same form under any coordinate transformation as long as the transformation of the function $G$ is given by $\\widetilde{G}(Y,Y',x) := G(f,f',x)$. Functions that behave this way under coordinate transformations as $G$ are called scalar functions, especially in physical contexts.\n%Can we give an example of a scalar function in undergraduate level mechanics? \"Such as the gravitational potential or temperature over an object\"\n\\footnote{An example for a scalar is air temperature.\nTo analyze this example we consider two coordinate systems with coordinates $x$ and $X$ and their transformation $x=f(X)$.\nIf $T=T(x)$ denotes temperature in the first coordinate system then as an analogue to definition \\eqref{lagrangian-transform} we define the temperature in the second coordinate system by\n\\begin{equation} \\label{definitionOfTemperatureTransform}\n  \\tilde{T}(X) := T(f(x))\n\\end{equation}\n\nNow the physical fact that temperature is the same in both coordinate systems leads to the condition $\\tilde{T}(X) = T(x)$ which by using definition \\eqref{definitionOfTemperatureTransform} can be turned into $T(f(x)) = T(x)$.\nScalars that fulfill this condition are called invariant with respect to the transformation $f$.\n\nAn interesting point of the temperature example is that this condition becomes invalid if one of the two coordinate systems moves with a velocity that is not negligible compared to the average motion of the air molecules while the other stays relative to the air at rest.\n}\nIn section \\ref{lagrangian-def}, $G$ will be interpreted as the Lagrangian we mentioned in section \\ref{introduction}. As we now see, $G$ does indeed have the transformation properties we claimed in section \\ref{introduction}.\n\n\\section{Definition of the Lagrangian}\\label{lagrangian-def} %We can easily remove this section header if a reviewer suggests it, though for now I think defining the Lagrangian is important enough to warrant it\n\nLooking back at the original Euler-Lagrange equation \\eqref{e-l} and the transformed version of equation \\eqref{e-lwithtv}, let time $t$ take the place of a general independent variable $x$, position $r$ take the place of a general coordinate $y$, and $T-V$ take the place of $G$, we arrive at the following results:\n\nNewton's second law takes the form\n\\begin{equation}\n0 = \\frac{\\ddd}{\\dd t} \\frac{\\partial L}{\\partial \\dot{r}} - \\frac{\\partial L}{\\partial r},\n\\end{equation}\nwhere\n\\begin{equation}\n L := T-V.\n\\end{equation}\nThis $L$ is precisely the Lagrangian from classical mechanics. It is not some divinely sanctioned quantity; it is just Newtonian mechanics under a simple change of variable.\n\nUsing this representation of $L$ allows the Lagrangian formulation of mechanics to be derived by requiring that the trajectory $r(t)$ which a particle takes between two endpoints $(t_1,r_1)$ and $(t_2,r_2)$ makes the integral\n\\begin{equation}\\label{eqref:action}\nS=\\int\\limits_{t_1}^{t_2} L \\; \\dd t\n\\end{equation}\nstationary. From this, the equations of motion for the particle follow, being the particle's Euler-Lagrange equation. This is called the principle of stationary action in physics\\footnote{The principle of stationary action is also sometimes called the principle of \\emph{least} action. This can be confusing because the Euler-Lagrange equation finds instances where action is stationary (e.g. a saddle point or even maximized)~\\cite{gray2007action}.}.\n\nIt is unnecessary to speciously explain the form of the classical Lagrangian as having an innate property of interest. We have shown that the Lagrangian takes its classical form\n\\begin{equation}\n  L = T-V\n\\end{equation}\nout of convenience.\n\nSince $F=ma$ is formulated in Cartesian coordinates, the Lagrangian $L$ we derived is formulated in Cartesian coordinates, as well. The transformation law \\eqref{lagrangian-transform} we found for $G$ provides us with a well defined method for the transformation of $L$ to other coordinate systems. The equations of motion which are now Euler-Lagrange equations are likewise the same in any coordinate system.  This way the relation of Newton's law to coordinates is restricted and well defined in the sense we mentioned in section \\ref{introduction}. %$L$ has the dimension of energy, thus $S$ has dimensions of energy times time, a quantity also called action.\n\n\n\n\\section{Conclusion and Outlook}\n\nAlthough the principle of stationary action is a new interpretation of classical mechanics, it nonetheless leads to the same equations of motion as Newtonian physics. In sections \\ref{distance} and \\ref{invariance} we explored the mathematical structure of the Lagrangian formalism and, because of its transformation properties, found it desirable for classical mechanics. This motivated and enabled us to give comprehensive derivations of the Lagrangian of classical mechanics $L=T-V$ and the principle of stationary action. We hope that this has been useful for clarifying at least one aspect of the Lagrangian formulation of classical mechanics for students who are curious about the subject.\n\n\nAlthough the transformation properties of the Lagrangian and the Euler-Lagrange equations are already reason enough to formulate physical laws using the principle of stationary action, these are by far not the only reasons. The principle of stationary action has enormous analytical capabilities which lie far beyond those of Newtonian mechanics. As an outlook we mention some of these analytical capabilities.\n\n\\subsection{Conservation laws~\\cite{KleinertConservation}}\nThe principle of stationary action allows derivation of conservation laws from transformation properties of the Lagrangian. From this, energy, momentum, angular momentum, and other quantities that may be conserved, are given formulations which depend only on the Lagrangian, coordinates, and time. Thus, concepts like energy, momentum, and angular momentum gain well-defined meaning for any physical system that has a Lagrangian. Since every physical theory can be described by the principle of stationary action (for examples see section \\ref{field.theory}), the concepts of energy, momentum, angular momentum, and other conserved quantities are consistently defined for all of these theories.\n\n\\subsection{Quantum mechanics~\\cite{Schwabl}}\nThe rules of quantum mechanics are mostly based on Hamiltonian physics and Poisson brackets which are both continuations of the principle of stationary action. A recent and in-depth discussion of an Lagrangian underlying the Schr{\\\"o}dinger equation can be found in Deriglazov's paper~\\cite{Deriglazov}.\n\n\n\\subsection{Field theory~\\cite{Sterman,Dirac}} \\label{field.theory}\nThe principle of stationary action can be and has been extensively continued to field theories. For example, Maxwell's equations can be derived from a principle of stationary action in electrodynamics. There, Maxwell's equations play a similar role as Newton's laws did in this paper.\n\nMost physical theories are field theories, and as a result the widest variety of Lagrangians are field Lagrangians. The most popular field theories apart from electrodynamics are\n\\begin{itemize}\n  \\item The Dirac Lagrangian for the relativistic field of fermions.\n  \\item The Klein-Gordon Lagrangian for the relativistic field of bosons.\n  \\item The Schr{\\\"o}dinger Lagrangian for non-relativistic quantum mechanics.\n  \\item The Lagrangian of the Standard Model of particle physics.\n  \\item The general relativity Lagrangian for Einstein's theory of general relativity.\n\\end{itemize}\n\n\n\\subsection{Constrained motion~\\cite{Kuypers}}\nThe simplest example of a problem of constrained motion is that of particle on an inclined plane in a uniform gravitational field. There are, of course, situations with more complex constraints than an inclined plane. In these cases it can be difficult to find the equations of motion for the particle through using Newton's laws. At this point, the transformation law we derived in section \\ref{invariance} becomes very helpful: assume there is a transformation of coordinates that well suits the constraints to the coordinates in which the Lagrangian is formulated. Once that is done, formula \\eqref{lagrangian-transform} can be used to rewrite the Lagrangian in the coordinates that suit the constraints. The equations of the constrained motion are then the Euler-Lagrange equations of the transformed Lagrangian.\n\n\\acknowledgments{We would like to thank the many friends and teachers who helped us clarify numerous points in this manuscript and encouraged the curiosity that sparked this writing. Namely, John Jaszczak, Zhongzhou Chen, Tony Szedlak, David McGhan, and Chris Riley.}\n\n\\bibliographystyle{aipauth4-1}\n\\bibliography{lagrange}\n\n% \\begin{thebibliography}{9}\n\n% \\bibitem{taylor} John R. Taylor, Classical Mechanics, 2005, page 238\n\n% \\bibitem{marion} Jerry B. Marion, Classical Dynamics of Particles and Systems, 1970, page 198-199 \n\n% \\bibitem{fowles} Grant R. Fowles, Analytical Mechanics, 1999, page 393 \n\n% \\bibitem{gregory} R. Douglas Gregory, Classical Mechanics, 2006, page 348\n\n% %\\bibitem{Klopper} Juan Klopper, Understanding the Euler Lagrange Equation, \\url{https://www.youtube.com/watch?v=08vJyA-XD3Q}\n\n% \\bibitem{Goldstein} Goldstein et.al., Classical mechanics 3 ed, Chapter 2.2.\n\n% \\bibitem{Kleinert} Hagen Kleinert, Path Integrals in Quantum Mechanics, Statistics, Polymer Physics, and Financial Markets, 2004, page 5, \\url{https://books.google.com/books?id=dJ3FCgAAQBAJ}\n\n% \\bibitem{action-not-least} Edwin Taylor and C.G. Gray, When Action is Not Least, doi: 10.1119/1.2710480\n\n% %\\bibitem{Guthrie} Matt Guthrie, The Origin of the Lagrangian, \\url{https://web2.ph.utexas.edu/~mwguthrie/t.lagrangian.pdf}\n\n\n% Citations for conclusion subsections:\n\n% \\bibitem{Kleinert-conservation} Hagen Kleinert, Particles and Quantum Fields, 2015, Section 8 , \\url{https://books.google.de/books?id=d1-2DAAAQBAJ}\n\n% \\bibitem{Schwabl} Franz Schwabl, Quantum Mechanics, 2007, 4th edition, Sections 2.5 and 2.6, \\url{https://books.google.de/books?id=pTHb4NK2eZcC&printsec}\n\n% \\bibitem{Sterman} George Sterman, An Introduction to Quantum Field Theory, 1993, Sections 1.1 - 1.4, 5.3, 5.4, \\url{https://books.google.de/books?id=rB_wdTnfTmoC}\n\n% \\bibitem{Dirac} P. A. M. Dirac, General theroy of relativitiy, 1975/1996, Sections 26 - 30, \\url{https://books.google.de/books?id=qkWPDAAAQBAJ}\n\n% \\bibitem{Kuypers} Friedhelm Kuypers, Klassische Mechanik, 2016, Section 3, \\url{https://books.google.de/books?id=dJ4CDAAAQBAJ}\n\n\n% \\end{thebibliography}\n\n\n\n\\end{document}\n", "meta": {"hexsha": "88c142a7dd114b69ae0a91823f1e7f8e39122bad", "size": 26733, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Lagrange.tex", "max_stars_repo_name": "mwguthrie/lagrangian", "max_stars_repo_head_hexsha": "ac16747a58b967399ed0f66ae4de661a26bc7194", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lagrange.tex", "max_issues_repo_name": "mwguthrie/lagrangian", "max_issues_repo_head_hexsha": "ac16747a58b967399ed0f66ae4de661a26bc7194", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lagrange.tex", "max_forks_repo_name": "mwguthrie/lagrangian", "max_forks_repo_head_hexsha": "ac16747a58b967399ed0f66ae4de661a26bc7194", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 85.6826923077, "max_line_length": 1368, "alphanum_fraction": 0.7715183481, "num_tokens": 6802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3016898078197093}}
{"text": "\\subsubsection{Domain specific features}\n\\label{sec:methods_features_domain}\n\nThe objective of including domain specific features is to add into the\nsecondary model data that is intrinsically representative of the underlying\ntechnology and market behavior. This subsection shows and explains the\ntransformations incurred to the listed features in \\ref{sec:material_data_bitcoin_features}.\n\n\\paragraph{Addresses:} this group is composed of: \\emph{total-addresses},\n\\emph{new-addresses}, \\emph{active-addresses}, \\emph{total-addresses},\n\\emph{sending-addresses}, \\emph{receiving-addresses}. We can split these\nfeatures into two groups, in figure \\ref{fig:total_addresses} the evolution of\ntotal registered addresses in the network is plotted. A logarithm transformation\nis show as well in green to stabilize its variance and range. Then, in figure\n\\ref{fig:addresses} we see the evolution of the other features. The reader may\nobserve the strong correlation between these four indexes and validate the\nobservation by inspecting figure \\ref{fig:addresses_correlation} which shows the\ncorrelation matrix between these four attributes. Because of that, only\n\\emph{active-addresses} will be used to train the model. We computed the\nfractional differentiation optimum $d$ value for the latter index and turned out\nto be 0.1. \n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=\\textwidth]{methods/images/total_addresses.png}\n    \\caption{Evolution of total registered addresses over time.}\n    \\label{fig:total_addresses}\n\\end{figure}\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=\\textwidth]{methods/images/addresses.png}\n    \\caption{Evolution of \\emph{new-addresses}, \\emph{active-addresses}, \\emph{total-addresses},\n\\emph{sending-addresses} and \\emph{receiving-addresses} over time.}\n    \\label{fig:addresses}\n\\end{figure}\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=0.7\\textwidth]{methods/images/addresses_correlation_mat.png}\n    \\caption{Correlation matrix of \\emph{new-addresses}, \\emph{active-addresses}, \\emph{total-addresses},\n\\emph{sending-addresses} and \\emph{receiving-addresses}.}\n    \\label{fig:addresses_correlation}\n\\end{figure}\n\n\\paragraph{Blocks:} in this group There are: \\emph{blocks-mined},\n\\emph{block-interval-mean}, \\emph{block-interval-median}, \\emph{block-size-mean}\nand \\emph{block-size-total}. The first three exhibit a quite similar tendency\n(see figure \\ref{fig:blocks_produced_blocks_mined}) which is aligned with what\nthey mean: \\emph{blocks-mined} describes the number of blocks added to the\nblockchain and the other two are centrality measures of the production rate. The\ncorrelation matrix confirms it, see figure \\ref{fig:blocks_production_blocks_mined_corr}.\nOnly \\emph{blocks-mined} will be used to avoid adding redundant information.\nOn the other hand, we have the \\emph{block-size-mean} and\n\\emph{block-size-total} which are expressed in bytes. Both indexes are expected\nto be correlated and \\ref{fig:block_size} shows their evolution over time. A\nfractional differentiation transformation is not enough to stabilize the series\nand a logarithmic transformation is applied which results in\n\\ref{fig:block_size_log}. Only the logarithm of \\emph{block-size-total} will be\nused to train the model between these two.\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=\\textwidth]{methods/images/block_production_blocks_mined.png}\n    \\caption{Evolution of \\emph{block-interval-mean} and \\emph{block-interval-median} are tracked on the left y-axis. \\emph{blocks-mined} is tracked on the right y-axis.}\n    \\label{fig:blocks_produced_blocks_mined}\n\\end{figure}\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=0.7\\textwidth]{methods/images/block_production_blocks_mined_corr.png}\n    \\caption{Correlation matrix of \\emph{blocks-mined}, \\emph{block-interval-mean} and \\emph{block-interval-median}.}\n    \\label{fig:blocks_production_blocks_mined_corr}\n\\end{figure}\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=\\textwidth]{methods/images/block_size.png}\n    \\caption{Evolution of \\emph{block-size-mean} (in blue and tracked on the left y axis) and \\emph{block-size-total} (in red and tracked on the right y axis) over time.}\n    \\label{fig:block_size}\n\\end{figure}\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=\\textwidth]{methods/images/block_size_log.png}\n    \\caption{Same features as in \\ref{fig:block_size} but with a logarithmic transformation. Due to the change of scale, both features are tracked on the same left y axis.}\n    \\label{fig:block_size_log}\n\\end{figure}\n\n\\paragraph{Fees:} there are two features related to fees: \\emph{fees-total} and\n\\emph{fees-mean}. They both remain relatively stable with very low values but \nthere are high valued outliers that get out of range rapidly. Fractional\ndifferentiation was tried but ended up in very low values of $d$ that made no\nsignificant change.  A logarithmic transformation is applied to account the explosive change in local variance when\nthese outliers occur. Note also that because some values in the series are zero,\na $1$ is added to the logarithm argument to avoid having minus infinity in the\nseries after the transformation. For illustration purposes, figure\n\\ref{fig:total_fees} is shown.\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=\\textwidth]{methods/images/total_fees.png}\n    \\caption{Evolution of \\emph{fees-total} (in blue) and its the logarithmic transformation (in red) over time. The left y axis tracks the linear scale and the right y axis tracks the logarithmic scale.}\n    \\label{fig:total_fees}\n\\end{figure}\n\n\\paragraph{General indicators:} in this group we have \\emph{sopr}, \\emph{ratio},\n\\emph{daysTillHalving}, \\emph{price-drawdown-from-ath}, \\emph{market-cap} and\n\\emph{circulating-supply}. The relationship between \\emph{market-cap} and \n\\emph{ratio} was already explained in section \\ref{sec:intro_domain} when\nreferring to the stock to flow model so it will be omitted in this case. We will\njust mention that \\emph{market-cap} will suffer a logarithmic transformation to\nstabilize its range. \\emph{sopr} and \\emph{price-drawdown-from-ath} are indexes\nso no further transformation is required (see figures \\ref{fig:sopr} and\n\\ref{fig:price-drawdown-from-ath}). Moreover, the \\emph{circulating-supply}\nvalues are in the order of millions and evolves asymptotically to 18 millions as\nthe issuance model expects it to be. In particular, we will create a derivative\nindex from the supply computed as the differentiated series of circulating\nsupply logarithm which shows the speed of issuance (see figure \\ref{fig:circulating_supply_rate}).\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=\\textwidth]{methods/images/sopr.png}\n    \\caption{Evolution of \\emph{sopr} over time.}\n    \\label{fig:sopr}\n\\end{figure}\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=\\textwidth]{methods/images/price-drawdown-from-ath.png}\n    \\caption{Evolution of \\emph{price-drawdown-from-ath} over time. In vertical\n    dashed red lines the halving dates are displayed}\n    \\label{fig:price-drawdown-from-ath}\n\\end{figure}\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=\\textwidth]{methods/images/circulating_supply_rate.png}\n    \\caption{Evolution of the logarithm of issuance over time. In vertical\n    dashed red lines the halving dates are displayed.}\n    \\label{fig:circulating_supply_rate}\n\\end{figure}\n\n\n\\paragraph{Transactions:} in this group we have \\emph{transaction-size-total},\n\\emph{transaction-rate}, \\emph{transaction-count}, \\emph{transaction-size-mean},\n\\emph{transfer-volume-mean} and \\emph{transfer-volume-median}. As it can be seen\nin figure \\ref{fig:transaction_corr}, the three indexes\n\\emph{transaction-size-total}, \\emph{transaction-rate}, and \n\\emph{transaction-count} are highly correlated so only one will be taken as\ninput to the model, in particular the \\emph{transaction-rate}. A note about this\nindex can be done when looking at the histogram which seems to be bimodal. A\nderivative index is created from it which groups the values into their deciles\nand aims to reduce the high frequency changes in the transaction rate that\naffect the signal on a daily basis. Figure \\ref{fig:transaction_rate} shows it\nin detail. Moving to \\emph{transaction-size-mean} the index exhibits some\nfrequent spikes but those are within range and there is no clear trend so the\nfeature remains as is (\\ref{fig:transaction_size_mean}). Central transfer volume\nfeatures (\\emph{transfer-volume-mean} and \\emph{transfer-volume-median}) exhibit\na high volatility in the first issuance period and then it is more and more\nstable. A logarithmic transformation is applied to both and even though they\ntry to predict the same, their tendencies are different in values and capture\ndifferently the local volatility so both will be preserved (\n\\ref{fig:transfer_volume_central}). Similarly to the processing done to the\nothers, the \\emph{transfer-volume-total} is transformed with a logarithm (\n\\ref{fig:transfer-volume-total}).\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=0.7\\textwidth]{methods/images/transaction_corr.png}\n    \\caption{Correlation matrix between the transaction related features}\n    \\label{fig:transaction_corr}\n\\end{figure}\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=\\textwidth]{methods/images/transaction_rate.png}\n    \\caption{Left: \\emph{transaction-rate} (in blue) and decile index of the same feature (in red) over time. Right: histogram of \\emph{transaction-rate}.}\n    \\label{fig:transaction_rate}\n\\end{figure}\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=\\textwidth]{methods/images/transaction_mean_size.png}\n    \\caption{Evolution of \\emph{transaction-size-mean} over time.}\n    \\label{fig:transaction_size_mean}\n\\end{figure}\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=\\textwidth]{methods/images/transfer_volume_central.png}\n    \\caption{Evolution of the logarithm of \\emph{transfer-volume-mean} and \\emph{transfer-volume-median}.}\n    \\label{fig:transfer_volume_central}\n\\end{figure}\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=\\textwidth]{methods/images/transfer_volume_total.png}\n    \\caption{Evolution of the logarithm of \\emph{transfer-volume-total} over time.}\n    \\label{fig:transfer-volume-total}\n\\end{figure}\n\n\\paragraph{Unspent / spent transactions:} under this final group we can find:\n\\emph{utx-os-created} \\emph{utx-os-spent}, \\emph{utxo-value-spent-mean},\n\\emph{utxo-value-spent-median} and \\emph{utxo-value-created-mean}. Following the\nsame procedure as with the others, a correlation matrix between these features\nis created and shown in figure \\ref{fig:utxo_corr}. We can find two pairs of\nhighly correlated features: \\emph{utx-os-created} with \\emph{utx-os-spent}, and\n\\emph{utxo-value-created-mean} with \\emph{utxo-value-spent-mean}. Note that\n\\emph{utxo-value-spent-median} is mildly correlated with the others (0.48 and\n0.49 respectively) which makes this feature to be kept. Provided that\n\\emph{utx-os-created} is a super set of \\emph{utx-os-spent}, the former will be\npreferred (see figure \\ref{fig:utxo_created}). The same reasoning applies to\n \\emph{utxo-value-created-mean} (see figure \\ref{fig:mean_utxo_created}).\n\n\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=0.7\\textwidth]{methods/images/utxo_corr.png}\n    \\caption{Correlation matrix between unspent / spent transaction features.}\n    \\label{fig:utxo_corr}\n\\end{figure}\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=\\textwidth]{methods/images/utxo_created.png}\n    \\caption{Evolution \\emph{utx-os-created} (in blue) and its logarithmic transform (in green) over time.}\n    \\label{fig:utxo_created}\n\\end{figure}\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=\\textwidth]{methods/images/utxo_value_spent.png}\n    \\caption{Left: evolution of \\emph{utxo-value-created-mean} (blue) and its logarithmic transformation (in green) over time. Right: evolution of \\emph{utxo-value-created-median} (blue) and its logarithmic transformation (in green) over time.}\n    \\label{fig:utxo_value_spent}\n\\end{figure}\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[width=\\textwidth]{methods/images/mean_utxo_created.png}\n    \\caption{Evolution of \\emph{utxo-value-created-mean} (in blue) and its logarithmic transformation (in green) over time.}\n    \\label{fig:mean_utxo_created}\n\\end{figure}", "meta": {"hexsha": "987c845f0c83b0451f45c3544b04c6e86f72731b", "size": 12461, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/methods/features/domain.tex", "max_stars_repo_name": "agalbachicar/swing_for_the_fences", "max_stars_repo_head_hexsha": "3871e88884a90e5c9dd80d71b20b811485007273", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/methods/features/domain.tex", "max_issues_repo_name": "agalbachicar/swing_for_the_fences", "max_issues_repo_head_hexsha": "3871e88884a90e5c9dd80d71b20b811485007273", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/methods/features/domain.tex", "max_forks_repo_name": "agalbachicar/swing_for_the_fences", "max_forks_repo_head_hexsha": "3871e88884a90e5c9dd80d71b20b811485007273", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.0696721311, "max_line_length": 244, "alphanum_fraction": 0.7734531739, "num_tokens": 3292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.3016898078197093}}
{"text": "\\documentclass[pdf]{beamer}\n\\usepackage{amsmath}\n\\usepackage{graphicx}\n\\usepackage{hyperref}\n\\usepackage{listings}\n\\usepackage{tcolorbox}\n\\usepackage[all]{xy}\n\n\\mode<presentation>{}\n\n% ------------------------------------------------------------------------------\n% Theme\n\n\\usetheme[usetitleprogressbar, nosmallcapitals, protectframetitle, usetotalslideindicator]{m}\n\n\\lstloadlanguages{Haskell}\n\\lstnewenvironment{code}\n    {\\lstset{}%\n      \\csname lst@SetFirstLabel\\endcsname}\n    {\\csname lst@SaveFirstLabel\\endcsname}\n    \\lstset{\n      basicstyle=\\ttfamily\\footnotesize,\n      flexiblecolumns=false,\n      basewidth={0.5em,0.45em},\n      literate={+}{{$+$}}1 {/}{{$/$}}1 {*}{{$*$}}1\n               {\\\\\\\\}{{\\char`\\\\\\char`\\\\}}1\n               {=>}{{$\\Rightarrow$}}2\n               {forall}{{$\\forall$}}2\n               {->}{{$\\rightarrow$}}2\n               {<-}{{$\\leftarrow$}}2\n               {>>}{{>>}}3 {>>=}{{>>=}}3,\n      commentstyle={\\ttfamily\\color{gray}},\n      language=haskell\n    }\n    \n% ------------------------------------------------------------------------------\n% Presentation\n\n\\title{Finally \\texttt{mtl}!}\n\\date{\\today}\n\\author{Joseph Tel Abrahamson / @sdbo / \\texttt{github.com/tel} }\n\n\\renewcommand{\\to}{\\ensuremath{\\rightarrow}}\n\\DeclareMathOperator{\\ty}{\\texttt{ :: }}\n\n\\begin{document}\n\n\\maketitle\n\n\\begin{frame}\n  \\frametitle{Synopsis}\n  \\begin{itemize}\n  \\item What is ``Finally Tagless''? What's important about it?\n  \\item What is the ``Monad Transformer Library'', \\texttt{mtl}?\n  \\item \\texttt{mtl} is a ``finally tagless'' effect library---and that's quite\n    nice!\n  \\end{itemize}\n\\end{frame}\n\n\\section{A tale of three DSLs}\n\n\\begin{frame}[fragile]\n  \\frametitle{Hutton's Razor}\n\\begin{lstlisting}\ndata AddLang\n  = AddLangIntLit Integer\n  | Add AddLang AddLang\n  deriving ( Show, Eq )\n\ninterpAddLang :: AddLang -> Integer\ninterpAddLang = \\case\n  AddLangIntLit i -> i\n  Add l r  -> interpAddLang l + interpAddLang r\n\naddLangExp :: AddLang\naddLangExp = Add (AddLangIntLit 1) (AddLangIntLit 3)\n\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}[fragile]\n  \\frametitle{Hutton's Backup Razor}\n\\begin{lstlisting}\ndata MultLang\n  = MultLangIntLit Integer\n  | Mult MultLang MultLang\n  deriving ( Show, Eq )\n\ninterpMultLang :: MultLang -> Integer\ninterpMultLang = \\case\n  MultLangIntLit i -> i\n  Mult l r -> interpMultLang l * interpMultLang r\n\nmultLangExp :: MultLang\nmultLangExp = Mult (MultLangIntLit 1) (MultLangIntLit 3)\n\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}[fragile]\n  \\frametitle{Hutton's Travel Kit}\n\\begin{lstlisting}\ndata RingLang\n  = RingLangIntLit Integer\n  | RingAdd  RingLang RingLang\n  | RingMult RingLang RingLang\n  deriving ( Show, Eq )\n\ninterpRingLang :: RingLang -> Integer\ninterpRingLang = \\case\n  RingLangIntLit i -> i\n  RingAdd  l r -> interpRingLang l + interpRingLang r\n  RingMult l r -> interpRingLang l * interpRingLang r\n\nringLangExp :: RingLang\nringLangExp = RingMult (RingAdd (RingLangIntLit 3) \n                                (RingLangIntLit 2)) \n                       (RingLangIntLit 3)\n\\end{lstlisting}\n\\end{frame}\n\n\\section{What's wrong with this picture?}\n\n\\begin{frame}[fragile]\n  \\frametitle{D. R. Y.}\n\\begin{lstlisting}\ndata RingLang\n  = RingLangIntLit Integer\n  | RingAdd  RingLang RingLang\n  | RingMult RingLang RingLang\n  deriving ( Show, Eq )\n\ninterpRingLang :: RingLang -> Integer\ninterpRingLang = \\case\n  RingLangIntLit i -> i\n  RingAdd  l r -> interpRingLang l + interpRingLang r\n  RingMult l r -> interpRingLang l * interpRingLang r\n\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}[fragile]\n  \\frametitle{D. R. Y.}\n\\begin{lstlisting}\n\n  = RingLangIntLit Integer\n  | RingAdd  RingLang RingLang\n  | RingMult RingLang RingLang\n\n\n\n\n  RingLangIntLit i -> i\n  RingAdd  l r -> interpRingLang l + interpRingLang r\n  RingMult l r -> interpRingLang l * interpRingLang r\n\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}[fragile]\n  \\frametitle{D. R. Y.}\n\\begin{lstlisting}\n\n\n  | RingAdd  RingLang RingLang\n  | RingMult RingLang RingLang\n\n\n\n\n\n  RingAdd  l r -> interpRingLang l + interpRingLang r\n  RingMult l r -> interpRingLang l * interpRingLang r\n\\end{lstlisting}\n\\end{frame}\n\n\\plain{Nooooooooooooooooooooo- oooooooooooooooooo!}\n\n\\begin{frame}\n  \\frametitle{Let's use category theory!}\n  \\begin{displaymath}\n    \\xymatrix{\n      \\mathtt{AddLang} & \\bullet \\ar[rdd]_{???} & & \\ar[ldd]^{???} \\bullet & \\mathtt{MultLang} \\\\\n      & & & & \\\\\n      & & \\bullet & & \\\\\n      & & \\mathtt{RingLang} & & \\\\\n    }\n  \\end{displaymath}\n\\end{frame}\n\n\\section{Once more, with feeling!}\n\n\\begin{frame}[fragile]\n  \\frametitle{Routine recursion scheme surgery}\n\\begin{lstlisting}[p]\nnewtype Fix f = Fix { unFix :: f (Fix f) }\n\nfixFold :: Functor f => (f a -> a) -> (Fix f -> a)\nfixFold phi = go where go = phi . fmap go . unFix\n\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}[fragile]\n  \\frametitle{Routine recursion scheme surgery}\n\\begin{lstlisting}\n{-# LANGUAGE UndecidableInstances #-}\n\nderiving instance Show (f (Fix f)) => Show (Fix f)\nderiving instance Eq   (f (Fix f)) => Eq   (Fix f)\n\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}[fragile]\n  \\frametitle{Routine recursion scheme surgery}\n\\begin{lstlisting}\n{-# LANGUAGE DeriveFunctor #-}\n\ndata AddF  x = AddI  Integer | AddF  x x deriving ( Show, Eq, Functor )\ndata MultF x = MultI Integer | MultF x x deriving ( Show, Eq, Functor )\n\ntype AddLang'  = Fix AddF\ntype MultLang' = Fix MultF\n\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}[fragile]\n  \\frametitle{Routine recursion scheme surgery}\n\\begin{lstlisting}\naddLangExp' :: AddLang'\naddLangExp' = Fix (AddF (Fix (AddI 1)) (Fix (AddI 3)))\n\nmultLangExp' :: MultLang'\nmultLangExp' = Fix (MultF (Fix (MultI 1)) (Fix (MultI 3)))\n\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}[fragile]\n  \\frametitle{Routine recursion scheme surgery}\n\\begin{lstlisting}\n-- Smart constructors! Yessssssss!\naddI :: Integer -> AddLang'\naddI = Fix . AddI\n\nmultI :: Integer -> MultLang'\nmultI = Fix . MultI\n\naddAdd :: AddLang' -> AddLang' -> AddLang'\naddAdd l r = Fix (AddF l r)\n\nmultMult :: MultLang' -> MultLang' -> MultLang'\nmultMult l r = Fix (MultF l r)\n\naddLangExp' :: AddLang'\naddLangExp' = addAdd (addI 1) (addI 3)\n\nmultLangExp' :: MultLang'\nmultLangExp' = multMult (multI 1) (multI 3)\n\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}[fragile]\n  \\frametitle{Routine recursion scheme surgery}\n\\begin{lstlisting}\ninterpAddF :: AddF Integer -> Integer\ninterpAddF = \\case\n  AddI i   -> i\n  AddF l r -> l + r\n\ninterpMultF :: MultF Integer -> Integer\ninterpMultF = \\case\n  MultI i   -> i\n  MultF l r -> l * r\n\ninterpAddLang' :: AddLang' -> Integer\ninterpAddLang' = fixFold interpAddF\n\ninterpMultLang' :: MultLang' -> Integer\ninterpMultLang' = fixFold interpMultF\n\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}[fragile]\n  \\frametitle{Routine recursion scheme surgery}\n\\begin{lstlisting}\n{-# LANGUAGE TypeOperators #-}\n\ndata (f :+: g) x \n  = Inl (f x) \n  | Inr (g x) \n  deriving ( Eq, Show, Functor )\n\n-- Natural :+: eliminator\nfoldSum :: (f a -> a) -> (g a -> a) -> ((f :+: g) a -> a)\nfoldSum falg galg = \\case\n  Inl fa -> falg fa\n  Inr ga -> galg ga\n\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}[fragile]\n  \\frametitle{The prize!}\n\\begin{lstlisting}\ntype RingLang' = Fix (AddF :+: MultF)\n\n-- More smart constructors!\nringI :: Integer -> AddLang'\nringI = Fix . Inl . AddI  -- why not via MultI?\n\nringAdd :: AddLang' -> AddLang' -> AddLang'\nringAdd l r = Fix (Inl (AddF l r))\n\nringMult :: MultLang' -> MultLang' -> MultLang'\nringMult l r = Fix (Inr (MultF l r))\n\nringLangExp' :: RingLang'\nringLangExp' = ringMult (ringAdd (ringI 3) (ringI 2)) (ringI 3)\n\ninterpRingLang' :: RingLang' -> Integer\ninterpRingLang' = fixFold (foldSum interpAddF interpMultF)\n\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}[fragile]\n\\begin{lstlisting}\nPrelude> interpRingLang' ringLangExp'\n\n\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}[fragile]\n\\begin{lstlisting}\nPrelude> interpRingLang' ringLangExp'\n15\n\\end{lstlisting}\n\\end{frame}\n\n\\plain{Yessssssss! HASKELL! \\\\ \\textbackslash{}textbackslash o/}\n\n\\begin{frame}\n  \\frametitle{D. R. Y. Stats}\n  \\begin{center}\n    40 additions, 3 new PRAGMAs\n    \n    \\pause\n\n    Used \\texttt{Fix} in anger\n  \\end{center}\n\\end{frame}\n\n\\plain{Yessssssss! HASKELL! \\\\ (+1 Functional Programming)}\n\n\\begin{frame}\n  \\frametitle{In all seriousness...}\n  Generalizing \\lstinline{:+:}\n\n  Wouter Swierstra, \\textit{Data types \\`a la carte}.\n\n  Really cool.\n\\end{frame}\n\n\\section{Data types \\`a la Carette, Kiselyov, and Shan}\n\n\\begin{frame}\n  Let's try this again...\n\\end{frame}\n\n\\begin{frame}[fragile]\n  \\frametitle{Design by wishful thinking}\n\\begin{lstlisting}\nclass Adds v where\n  add :: v -> v -> v\n\nclass Multiplies v where\n  mult :: v -> v -> v\n\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}[fragile]\n\\begin{lstlisting}\ninstance Adds Integer where add = (+)\ninstance Multiplies Integer where mult = (*)\n\naddsExp :: Integer\naddsExp = add 1 3\n\nmultsExp :: Integer\nmultsExp = mult 1 3\n\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}[fragile]\n\\begin{lstlisting}\nclass FromInteger v where\n  i :: Integer -> v\n\ninstance FromInteger Integer where\n  i = id\n\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}[fragile]\n\\begin{lstlisting}\naddsExp :: (FromInteger v, Adds v) => v\naddsExp = add (i 1) (i 3)\n\nmultsExp :: (FromInteger v, Multiplies v) => v\nmultsExp = mult (i 1) (i 3)\n\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}[fragile]\n\\begin{lstlisting}\n{-# LANGUAGE ConstraintKinds #-}\n\ntype Rings v = (FromInteger v, Adds v, Multiplies v)\n\nringsExp :: Rings v => v\nringsExp = mult (add (i 3) (i 2)) (i 3)\n\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}[fragile]\n\\begin{lstlisting}\nPrelude> ringsExp\n\n\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}[fragile]\n\\begin{lstlisting}\nPrelude> ringsExp\n15\n\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}[fragile]\n\\begin{lstlisting}\nPrelude> ringsExp :: Integer\n15\n\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}[fragile]\n  \\frametitle{But then!}\n\\begin{lstlisting}\ninstance FromInteger RingLang where i    = RingLangIntLit\ninstance Adds        RingLang where add  = RingAdd\ninstance Multiplies  RingLang where mult = RingMult\n\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}[fragile]\n\\begin{lstlisting}\nPrelude> ringsExp :: RingLang\n\n\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}[fragile]\n\\begin{lstlisting}\nPrelude> ringsExp :: RingLang\nRingMult (RingAdd (RingLangIntLit 3) \n                  (RingLangIntLit 2)) \n         (RingLangIntLit 3)\n\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}\n  \\frametitle{Recap}\n  \\begin{itemize}\n  \\pause\n  \\item One-line composabiity\n  \\pause\n  \\item Needn't mention concrete data types or \\lstinline{Inl}/\\lstinline{Inr}\n    \\pause\n    \\begin{itemize}\n    \\item ``tagless''\n    \\end{itemize}\n  \\pause\n  \\item But if we have them, we can still recover ``raw'' ASTs\n  \\end{itemize}\n\\end{frame}\n\n\\section{\"Does is scale?\"}\n\n\\begin{frame}\n  Yes.\n\\end{frame}\n\n\\section{The \"Monad Transformer Library\"}\n\n\\begin{frame}\n  Or: ``Haskell2010 Composable Effects Through Prolog Technology''\n\\end{frame}\n\n\\begin{frame}\n  Or: ``Haskell2010 Composable Effects Through Typeclass Technology''\n\\end{frame}\n\n\\begin{frame}[fragile]\n\\begin{lstlisting}\nimport Control.Monad.State\n\ninc :: MonadState Int m => m Int\ninc = do\n  count <- get\n  set (count + 1)\n  return count\n\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}[fragile]\n\\begin{lstlisting}\n-- let's get a concrete stack from `transformers`\nimport Control.Monad.Trans.State (runState)\n\nPrelude> flip runState 0 inc \n(1, 1)\n\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}[fragile]\n\\begin{lstlisting}\n-- let's get a concrete stack from `transformers`\nimport Control.Monad.Trans.State (runState)\n\nPrelude> flip runState 0 (inc :: StateT Int Identity Int)\n(1, 1)\n\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}\n  Solve your monad stacks at compile time! \\pause Not runtime\\pause, nor write-time.\n\\end{frame}\n\n\\section{Complaints}\n\n\\begin{frame}[fragile]\n  \\frametitle{Just a few points in the lattice}\n\\begin{lstlisting}\nMonadTrans (ContT r) Source\t \nMonad (ContT r m) Source\t \nFunctor (ContT r m) Source\t \nApplicative (ContT r m) Source\t \nMonadIO m => MonadIO (ContT r m) Source\t \n\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}[fragile]\n  \\frametitle{All points in the lattice}\n\\begin{lstlisting}\nMonadCont (ContT r m) Source\t \n\\end{lstlisting}\n  \\pause\n\\begin{lstlisting}\nMonadCont m => MonadCont (MaybeT m) Source\t \nMonadCont m => MonadCont (ListT m) Source\t \nMonadCont m => MonadCont (IdentityT m) Source\t \n(Monoid w, MonadCont m) => MonadCont (WriterT w m) Source\t \n(Monoid w, MonadCont m) => MonadCont (WriterT w m) Source\t \n(Error e, MonadCont m) => MonadCont (ErrorT e m) Source\t \nMonadCont m => MonadCont (ExceptT e m) Source\t \nMonadCont m => MonadCont (StateT s m) Source\t \nMonadCont m => MonadCont (StateT s m) Source\t \nMonadCont m => MonadCont (ReaderT r m) Source\t \n(Monoid w, MonadCont m) => MonadCont (RWST r w s m) Source\t \n(Monoid w, MonadCont m) => MonadCont (RWST r w s m) Source\n...\n-- This gets quite complex\n\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}\n  \\frametitle{All points in the lattice}\n  But this is just the name of the game! Effects don't commute.\n\\end{frame}\n\n\\begin{frame}[fragile,fragile]\n  \\frametitle{Lose control of ordering}\n\\begin{lstlisting}\nop :: (MonadError e m, MonadState s m) => m ()\n\\end{lstlisting}\n  \\pause\n\\begin{lstlisting}\nop ==> StateT s (Either e) ()\nop ==> EitherT e (State s) ()\n\\end{lstlisting}\n  \\pause\nNo right answer!\n\\end{frame}\n\n\\begin{frame}\n  \\frametitle{Loose control of ordering}\n  This is why we have laws.\n  \\pause\n  Combining laws ``correctly'' \\textit{is} hard.\n\\end{frame}\n\n\\begin{frame}[fragile]\n  \\frametitle{Loose control of ordering}\n\\begin{lstlisting}\nclass (MonadState s m, MonadError e m) => MonadParser s e m where {}\n\\end{lstlisting}\n\\end{frame}\n\n\\begin{frame}[fragile]\n  \\frametitle{Tight denotation of semantics}\n\\begin{lstlisting}\n-- Tighten to your domain\nclass MonadParser m where\n  type family Char m :: *\n  type family Error m :: *\n\n  peekChar :: m (Char m)\n  getChar  :: m (Char m)\n  \n  failParse :: Error m -> m a\n\\end{lstlisting}\n\\end{frame}\n\n\\section{Thanks!}\n\n\\begin{frame}\n  \\frametitle{Tweet at me!}\n  \\begin{center}\n    @sdbo\n  \\end{center}\n\\end{frame}\n\n\\end{document}\n\n%%% Local Variables: \n%%% coding: utf-8\n%%% mode: latex\n%%% TeX-engine: xetex\n%%% End: ", "meta": {"hexsha": "dfa4f63c5999f796ce3f8bd56c7555008a6f5f85", "size": 14195, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "speakers/tel/mtl.tex", "max_stars_repo_name": "nuttycom/lambdaconf-2015-upstream", "max_stars_repo_head_hexsha": "1c768a5d0d86b7391635c54ff5c951dd786113ad", "max_stars_repo_licenses": ["Artistic-2.0"], "max_stars_count": 100, "max_stars_repo_stars_event_min_datetime": "2015-05-19T21:02:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-09T01:30:39.000Z", "max_issues_repo_path": "speakers/tel/mtl.tex", "max_issues_repo_name": "rtfeldman/lambdaconf-2015", "max_issues_repo_head_hexsha": "62396a8656df5e1e11a92c0fcfbb9398a10fd956", "max_issues_repo_licenses": ["Artistic-2.0"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2015-05-12T00:22:15.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-31T00:51:49.000Z", "max_forks_repo_path": "speakers/tel/mtl.tex", "max_forks_repo_name": "rtfeldman/lambdaconf-2015", "max_forks_repo_head_hexsha": "62396a8656df5e1e11a92c0fcfbb9398a10fd956", "max_forks_repo_licenses": ["Artistic-2.0"], "max_forks_count": 63, "max_forks_repo_forks_event_min_datetime": "2015-05-06T23:17:26.000Z", "max_forks_repo_forks_event_max_datetime": "2017-04-09T06:48:05.000Z", "avg_line_length": 22.460443038, "max_line_length": 97, "alphanum_fraction": 0.6772807327, "num_tokens": 4557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3016898078197092}}
{"text": "% !TEX root = ../thesis.texSecondly\n%\n\\chapter{Conclusion}\n\\label{sec:conclusion}\nIn this thesis we present an zero-knowledge image retrieval system employing a \\acrlong{fcn} for efficient object detection. With a set of transformed samples derived from a query image we fine-tune the underlying \\gls{resnet}. Training is done without a training progress dependent abort condition. The linear classifier is converted to a convolution to predict sparse class probabilities on images of varying size. Using these probability maps we predict the existence of alike objects in images. We yield these patches and thereby we retrieve object instances from image set related to the training samples.\n\nWith our results on \\textsc{Pascal}-Part and the application on art historical images we provide evidence that this approach can carry out image retrieval in unlabeled, context-less images using a small number of examples, ultimately only a single one. On the one hand, the tests on \\textsc{Pascal}-Part verify the supposition, that providing the network with more positives image samples drastically improves its detection results, on the other hand we showed that under our test settings, results quickly converged over an increasing number of examples.\\\\\nAlthough we prove the methods effectiveness we recognize multiple drawbacks. Firstly the time complexity \\tref{sec:results:time} restricts its use on small datasets of images and makes instance retrieval somewhat cumbersome. Secondly our region scoring method throughout under-scales object boxes thus serving more as a translation prediction.\\\\\nThe approach could be continued and improved on multiple different ways. Of most importance is the unanswered question, how to use the image representation provided by the deep filter of a \\gls{cnn} to bootstrap an approximate object detector without having to actually iteratively train the network. We could not test any approaches in this domain and as such can not predict a possible solution.\\\\\nTo fasten the approach it may be possible to formulate the complete pipeline inside the neural network, reducing time costs. Taking densities of regions is nothing else than average pooling and thus could be done within the network after convolutional upsampling.\n\nAll code is made publicly available under \\url{https://github.com/mrtukkin/bachelor-thesis}.\n", "meta": {"hexsha": "62eb14b7f87d272c0914aa560b8d7653e6bae2b8", "size": 2356, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/chapter-conclusion.tex", "max_stars_repo_name": "mrtukkin/ba_latex", "max_stars_repo_head_hexsha": "56538f1d84d23b6ba8cc7044a4dbb4317d281582", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/chapter-conclusion.tex", "max_issues_repo_name": "mrtukkin/ba_latex", "max_issues_repo_head_hexsha": "56538f1d84d23b6ba8cc7044a4dbb4317d281582", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/chapter-conclusion.tex", "max_forks_repo_name": "mrtukkin/ba_latex", "max_forks_repo_head_hexsha": "56538f1d84d23b6ba8cc7044a4dbb4317d281582", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 181.2307692308, "max_line_length": 610, "alphanum_fraction": 0.8196095076, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3016898078197092}}
{"text": "\\documentclass{article}\n\n\\usepackage{xstring}\n\\usepackage{calc}\n\\usepackage{xintexpr}\n\\usepackage{arrayjobx}\n\\usepackage{tikz}\n\\usetikzlibrary{matrix}\n\\usepackage{etoolbox}\n\n\\title{Advent of Code - Day 8}\n\\author{Sansero}\n\\date{July 2020}\n\n\\newcommand\\imgwidth{25}\n\\newcommand\\imgheight{6}\n\\newcommand\\pixelcount{0}\n\n\\renewcommand\\pixelcount{\\the\\numexpr \\imgwidth * \\imgheight}\n\n\\typeout{moin}\n\n\\newread\\file\n\\openin\\file=input.txt\n\\read\\file to \\input % Reads a line of the file into \\input  \n\\closein\\file \n\n\\typeout{Loaded file}\n\n\\newarray\\bitmap\n\\expandarrayelementtrue\n\n\\newcommand\\updatelayer[1]{\n    \\foreach \\i in {1,...,\\pixelcount}{\n        \\StrMid{#1}{\\i}{\\i}[\\char]\n        \\IfEq{\\char}{0}{\n            \\updatearray{\\i}{0}\n        }{\n            \\IfEq{\\char}{1}{\n                \\updatearray{\\i}{1}\n            }{\n                \\IfEq{\\char}{2}{\n                    \\updatearray{\\i}{2}\n                }{}\n            }\n        }\n    }\n}\n\n\\newcommand\\updatearray[2]{\n    \\checkbitmap(#1)\n    \\ifemptydata\n        \\bitmap(#1)={#2}\n    \\else\n        \\if 2\\cachedata \\bitmap(#1)={#2} \\fi\n    \\fi\n}\n\n\n\n\\newcount\\minzero\n\\newcount\\minlayer\n\\minzero=\\pixelcount\n\\newcount\\onetimestwo\n\\newcount\\ones\n\\newcount\\twos\n\\newcount\\layernr\n\n\\newcount\\counter\n\\counter=0\n\\loop\n    \\typeout{\\the\\counter}\n    \\StrLeft{\\input}{\\pixelcount}[\\layer]\n    \\StrGobbleLeft{\\input}{\\pixelcount}[\\input]\n    \\StrLen{\\layer}[\\layerlength]\n    \\ifnum \\layerlength=\\pixelcount\n        \\updatelayer{\\layer}\n        \\StrCount{\\layer}{0}[\\zerocount]\n        \\ifnum \\zerocount<\\minzero\n            \\StrCount{\\layer}{1}[\\onecount]\n            \\StrCount{\\layer}{2}[\\twocount]\n            \\minzero=\\zerocount\n            \\minlayer=\\layernr\n            \\ones=\\onecount\n            \\twos=\\twocount\n            \\onetimestwo=\\the\\numexpr \\onecount * \\twocount \\relax\n        \\fi\n    \\fi\n    \\advance \\counter \\pixelcount\n    \\advance \\layernr 1\n\\ifx\\input\\empty\n\\else\n\\repeat\n\n\\begin{document}\n\n\\maketitle\n\n\\section{Part 1}\n\nError detection. Get the layer with the fewest zeros\n\nLayer: \\the\\minlayer\n\nZeros: \\the\\minzero\n\n$1*2$: \\the\\onetimestwo\n\nOnes: \\the\\ones\n\nTwos: \\the\\twos\n\n\\section{Part 2}\n\nThe final image\n\n% 0: black\n% 1: white\n% 2: transparent\n\n\\begin{tikzpicture}[]\n  \\tikzstyle{every node}=[minimum size=3mm]\n  \\tikzset{pre/.style={draw,fill=black, text=white}}\n  \\let\\mymatrixcontent\\empty\n  \\foreach \\i in {0,...,\\the\\numexpr \\imgheight -1} {%\n      \\foreach \\y in {1,...,\\imgwidth} {%\n        \\checkbitmap(\\the\\numexpr \\i*\\imgwidth + \\y)%\n        \\if 0\\cachedata\n            \\edef\\x{\n            \\noexpand\\gappto\\noexpand\\mymatrixcontent{ \\noexpand\\node[pre, fill=black, text=black]{0}; \\&}}\\x\n        \\else\n            \\if 1\\cachedata\n                \\edef\\x{\n                \\noexpand\\gappto\\noexpand\\mymatrixcontent{ \\noexpand\\node[pre, fill=white]{1}; \\&}}\\x\n            \\else\n                \\if 2\\cachedata\n                    \\edef\\x{\n                    \\noexpand\\gappto\\noexpand\\mymatrixcontent{ \\noexpand\\node[pre, fill=blue]{2}; \\&}}\\x\n                \\else\n                    \\edef\\x{\n                    \\noexpand\\gappto\\noexpand\\mymatrixcontent{ \\noexpand\\node[pre, fill=red]{e}; \\&}}\\x\n                \\fi\n            \\fi\n        \\fi\n      }\n      \\gappto\\mymatrixcontent{\\\\}%\n  }\n\n  \\matrix[matrix of math nodes,%\n      nodes = {pre},%\n      ampersand replacement=\\&] {%\n    \\mymatrixcontent\n  };\n\\end{tikzpicture}\n\n\\end{document}\n", "meta": {"hexsha": "bf30f6be4f4c11331c92017e7baf12e42fc5300f", "size": 3439, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "2019/8/task.tex", "max_stars_repo_name": "SanseroGames/adventofcode", "max_stars_repo_head_hexsha": "23768aa85c2e809acbf53a35d9ad81885fcb5fa1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-15T16:47:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-15T16:47:41.000Z", "max_issues_repo_path": "2019/8/task.tex", "max_issues_repo_name": "SanseroGames/adventofcode", "max_issues_repo_head_hexsha": "23768aa85c2e809acbf53a35d9ad81885fcb5fa1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2019/8/task.tex", "max_forks_repo_name": "SanseroGames/adventofcode", "max_forks_repo_head_hexsha": "23768aa85c2e809acbf53a35d9ad81885fcb5fa1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9044585987, "max_line_length": 109, "alphanum_fraction": 0.5812736261, "num_tokens": 1156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.3016052195465316}}
{"text": "% \\newcommand{\\nconfirmed}{500}\n\\newcommand{\\dantodo}[1]{{\\color{blue}#1}}\n\n\\section{Method}\n\\label{sec:method}\n\n\\subsection{Rotation period measurement}\n\nSince the \\nconfirmed\\ comoving stars identified in TGAS and confirmed with RV\nfollow-up we consider here are all \\Kepler\\ targets with precise light curves\ncovering around 4 years, we measured photometric rotation periods for these\nstars.\nWe applied three different methods to the light curves: a Lomb-Scargle\nperiodogram method, an autocorrelation method and a Gaussian process method.\nThe exact implementations of the Lomb-Scargle and Gaussian process methods\nwere also used in the \\citet{Angus2017} rotation period study.\nIn that work we found that the Gaussian process method produces slightly more\naccurate rotation periods than the periodogram method and substantially more\naccurate periods than the autocorrelation method for \\kepler\\ data.\nHowever, we also found that each rotation period measurement method is very\nsensitive to the exact implementations, for example any choices of heuristics\nor priors affected the resulting rotation periods for an ensemble of light\ncurves.\nFor this reason we use all three methods here to ensure that our results are\nnot significantly altered by method choice.\nWe describe the implementation of each method below.\n\nTo measure periods using a Lomb-Scargle periodogram we first applied a\nhigh-pass filter to the light curves to remove long-term trends.\nWe used the {\\tt scipy} 3rd order Butterworth filter with a 35 day cut-off,\nattenuating signals with periods greater than this threshold.\nFor each simulated light curve, we computed a LS periodogram\\footnote{LS\nperiodograms were calculated using the {\\tt scipy} Lomb-Scargle algorithm}\nover a grid of 10,000 periods, evenly spaced in frequency, between 1 and 100\ndays.\nWe adopted the period of the highest peak in the periodogram as the measured\nrotation period.\nThe uncertainties on the rotation periods were calculated using the\nfollowing equation for the standard deviation of the frequency\n\\citep{Horne1986, Kovacs1981}:\n\\begin{equation}\n    \\sigma_{\\nu} = \\frac{3\\pi\\sigma_N}{2N^{1/2}TA},\n\\end{equation}\nwhere $A$ is the amplitude of the signal of highest power, $\\sigma_N$ is the\nvariance of the time series, with the signal of highest power removed, $N$\nis the number of observations and $T$ is the timespan of the data.\nThese formal uncertainties are only valid in the case that the noise is white,\nthe data are evenly sampled and there is only one signal present.\nSince there are multiple signals present in these light curves, this formal\nuncertainty is an underestimate of the true uncertainty.\n\n\\racomment{Add section on ACF method.}\n\nThe implementation of the Gaussian process method we use here is described and\ndiscussed in detail in \\citet{Angus2017}.\nGiven its success in \\citet{Angus2017}, we chose to use the same kernel\nfunction:\n\\begin{equation}\n\\label{eq:QP}\nk_{i,j} = A \\exp \\left[-\\frac{(x_i - x_j)^2}{2l^2} -\n    \\Gamma^2 \\sin^2\\left(\\frac{\\pi(x_i - x_j)}{P}\\right) \\right] + \\sigma^2\n    \\delta_{ij},\n\\end{equation}\nwhere $A$ is the covariance amplitude, $l$ is the length-scale of overall\ncovariance decay, $\\Gamma$ is the parameter controlling\nthe intra-period variation (large $\\Gamma$ permits more zero-crossings), $P$\nis the rotation period and $\\sigma$ is the additional white noise needed to\naccount for errorbar uncertainties.\nThe priors on each of these parameters takes a relatively simple functional\nform, except for the period prior which is built from an initial\nautocorrelation function guess.\nThese priors are fully described in \\citet{Angus2017} and we will not go into\nfurther detail here.\n\nThe rotation periods measured using these three methods are in good agreement:\nN\\% of periods agree to within 10\\%.\n\n\\subsection{Age prediction}\n\nSince we are assuming that the comoving stars are coeval we expect their\nrotation periods to reflect this.\nTo quantify the rate of age-matches,\n\n\\subsection{Inferring intrinsic dispersion in the gyrochronology\nrelations}\n", "meta": {"hexsha": "23919bc256d14dbcf35c9087b799e34dbb2ba4a5", "size": 4053, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/method.tex", "max_stars_repo_name": "RuthAngus/teacups", "max_stars_repo_head_hexsha": "299863eb2e579cb71efce3769cf13b38eb460fd5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paper/method.tex", "max_issues_repo_name": "RuthAngus/teacups", "max_issues_repo_head_hexsha": "299863eb2e579cb71efce3769cf13b38eb460fd5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/method.tex", "max_forks_repo_name": "RuthAngus/teacups", "max_forks_repo_head_hexsha": "299863eb2e579cb71efce3769cf13b38eb460fd5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.1279069767, "max_line_length": 78, "alphanum_fraction": 0.7929928448, "num_tokens": 973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.30150691009141295}}
{"text": "\\chapter[Bremsstrahlung]{Bremsstrahlung}\n \n\n The class G4eBremsstrahlung calculates the continuous energy loss\n  due to {\\em sub-cutoff} photons and\n simulates the 'discrete' part of the interaction ,\nthe bremsstrahlung  by $e^-/e^+$ . The formulae used here\n are the very similar to those used in GEANT3 (\\cite{ebrem.geant3}).\n The only {\\em important} difference is that in GEANT4 both of the LPM \neffect and dielectric supression of the bremsstrahlung \n(\\cite{ebrem.galitsky},\\cite{ebrem.anthony}) have been implemented,\nwhile GEANT3 contains the latter only (using the name Migdal correction\nfor it) .\n\n\\section{Cross section and energy loss}\n\nLet's call $d\\sigma(Z,T,k)/dk$ the differential cross-section for\nproduction of a photon of energy $k$ by an electron of kinetic energy\n$T$ in the field of an atom of charge $Z$, and\n$k_c$ the energy cut-off below which the soft photons are treated\nas continuous energy loss .\nThen the mean value of the energy lost by the electron due\nto soft photons is\n\\begin{equation}\n  E_{Loss}^{brem} (Z,T,k_c ) =\n\\int_{0}^{k_ c}k\\frac{d \\sigma (Z,T,k)}{dk}dk\n\\end{equation}\nwhereas the total cross-section for the emission of\na photon of energy larger than $k_c$ is\n\\begin{equation}\n \\sigma_{brem} (Z,T,k_c ) = \\int_{k_c}^{T}\\frac{d \\sigma (Z,T,k)}{dk} dk\n\\end{equation}\nMany theories of the bremsstrahlung process exist, each with its own\nlimitations and regions of applicability. Perhaps the best synthesis\nof these theories can be found in the paper of S.M. Seltzer and M.J.\nBerger \\cite{ebrem.seltzer}. The authors give a tabulation of the\nbremsstrahlung cross-section $d\\sigma/dk$ differential in the photon\nenergy $k$, for electrons with kinetic energies $T$ from 1 keV to 10\nGeV. For electron energies above 10 GeV the screened Bethe-Heitler\ndifferential cross-section can be used\n(\\cite{ebrem.egs4}  \ntogether with the dielectric supression\ncorrection (\\cite{ebrem.messel} , \\cite{ebrem.migdal} ) .\n  This correction      \n decreases the differential cross-section at photon\nenergies below a certain fraction of the incident electron energy\n($d\\sigma/dk$ decreases significantly if $ k/T \\leq 10^{-4}$.)\n\n\\subsection{Parameterisation of energy loss and total cross-section}\nUsing the tabulated cross-section values of Seltzer and Berger together\nwith the corrected Bethe-Heitler formula (which so includes the \n dilelectric supression,too) we have computed\n$\\sigma(Z,T,k_c ) $\nand we have used these computed values as ``data points''\nin the fitting procedure.\nCalculating the ``low energy'' ($T\\leq 10$ GeV) data we have applied the\ndielectric supression to the results of Seltzer and Berger.\nWe have chosen the parameterisations:\n\\begin{equation}\n\\label{ebrem.a}\n\\sigma (Z,T,k_c ) =\\frac{Z(Z+\\xi_{\\sigma} )(T+m)^2}\n     {T(T+2m)}[ \\ln (T/k_c )]^\\alpha F_{\\sigma} (Z,X,Y)\n\\mbox{\\quad(barn)}\\\\\n\\end{equation}\nand\n\\begin{equation}\n\\label{ebrem.b}\nE_{Loss}^{brem} (Z,T,k_c ) =\\frac{Z(Z+ \\xi_l)(T+m)^2 }\n      {(T+2m)}\\left[\\frac{k_c C_ M }{T}\\right]^\\beta\n      F_{l} (Z,X,Y) \\mbox{\\quad(GeV barn)}\n\\end{equation}\nwhere  $m$ is the mass of the electron,\n\\[\n\\begin{array}{lll}\nX = \\ln(E/m), & Y = \\ln (v_{\\sigma} E/k_c) &\n\\mbox{\\quad for the total cross-section }\\sigma \\\\\nX = \\ln(T/m), & Y = \\ln(k_c/v_lE)       &\n\\mbox{\\quad for the energy loss }  E_{Loss}^{brem}  \\\\\n\\end{array}\n\\]\nwith $E=T+m$.\nThe constants $\\xi_{\\sigma},\\ \\xi_l,\\ \\alpha,\\ \\beta,\\ v_{\\sigma},\\ v_l$\nare parameters to be fitted.\n\\begin{eqnarray*}\nC_M &=&\\frac{1}{1+\\frac{n r_0 \\lambda r^2  (T+m)^2}{\\pi k^2_c}}\n\\end{eqnarray*}\nis the Midgal correction factor, with\n\\begin{description}\n\\item $r_o$  classical electron radius;\n\\item $\\lambda$  reduced electron Compton wavelength;\n\\item $n$  electron density in the medium.\n\\end{description}\nThe factors $(T+m)^2/T(T+2m)$ and $(T+m)^2/(T+2m)$ come from\nthe scaled cross-section computed by Seltzer and Berger:\n\\[\nf(k/T) = \\frac{\\beta^2}{Z^2 }k\\frac{d \\sigma}{dk}\n       = \\frac{T(T+2m)} {(T+m)^2 Z^2}  k \\frac{d \\sigma}{dk}\n\\]\n\nThe functions $F_i(Z,X,Y)$ ($ i=\\sigma,l $) have the form\n\\begin{equation}\n F_i(Z,X,Y) = F_{i0}(X,Y)+ZF_{i1}(X,Y)\n\\end{equation}\nwhere $F_{ij}(X,Y)$ are polynomials of the variables $X,Y$\n\\begin{eqnarray}\nF_{i0}(X,Y) & = &  (C_1+C_2X+\\ldots+C_6X^5)+(C_7+C_8X+\\ldots+C_{12}X^5)Y\n                                                             \\nonumber \\\\\n          &   & +(C_{13}+C_{14}X+\\ldots + C_{18}X^5)Y^2+\\ldots \\nonumber \\\\\n          &   & +(C_{31}+C_{32}X+\\ldots+C_{36}X^5)Y^5        \\nonumber \\\\\n          &   & \\mbox{\\hspace{11cm}}  Y\\leq 0      \\nonumber \\\\\n          & = &  (C_1+C_2X+\\ldots+C_6X^5)+(C_7+C_8X+\\ldots+C_{12}X^5)\n                                                             \\nonumber \\\\\n          &   & +(C_{37}+C_{38}X+\\ldots+C_{42}X^5)Y^2+\\ldots+ \\nonumber \\\\\n          &   &  (C_{55}+C_{56}X+\\ldots+C_{60}X^5)Y^5        \\nonumber \\\\\n          &   & \\mbox{\\hspace{11cm}}  Y > 0        \\nonumber \\\\\nF_{i1}(X,Y) & = &  (C_{61}+C_{62}X+\\ldots+C_{65}X^4)\n                +(C_{66}+C_{67}X+\\ldots+C_{70}X^4)Y          \\nonumber \\\\\n          &   & +(C_{71}+C_{72}X+\\ldots+C_{75}X^4)Y^2+\\ldots \\nonumber \\\\\n          &   & +(C_{81}+C_{82}X+\\ldots+C_{85}X^4) Y^4       \\nonumber \\\\\n          &   &   \\mbox{\\hspace{11cm}}  Y\\leq 0    \\nonumber \\\\\n          & = &  (C_{61}+C_{62}X+\\ldots+C_{65}X^4)\n                +(C_{66}+C_{67}X+\\ldots+C_{70}X^4)Y          \\nonumber \\\\\n          &   & +(C_{86}+C_{87}X+\\ldots+C_{90}X^4)Y^2+\\ldots \\nonumber \\\\\n          &   & +(C_{96}+C_{97}X+\\ldots+C_{100}X^4)Y^4       \\nonumber  \\\\\n          &   &  \\mbox{\\hspace{11cm}}  Y>0         \\nonumber \\\\\n           \\nonumber\n\\end{eqnarray} \n$F_{ij}(X,Y)$ denotes in fact a function constructed from two\npolynomials\n\\[\nF_{ij}(X,Y) = \\left \\{\n\\begin{array}{ll}\nF_{ij}^{neg}(X,Y) & \\mbox{for\\hspace{0.5cm}} Y\\leq 0 \\\\\nF_{ij}^{pos}(X,Y) & \\mbox{for\\hspace{0.5cm}} Y>0\n\\end{array} \\right .\n\\]\nwhere the polynomials $F_{ij}$ fulfil the conditions\n\\[\nF_{ij}^{neg}(X,Y)_{Y=0} = F_{ij}^{pos}(X,Y)_{Y=0}   \\hspace{2cm}\n\\left ( \\frac{\\partial F_{ij}^{neg}}{\\partial Y} \\right )_{Y=0} =\n\\left ( \\frac{\\partial P_{ij}^{pos}}{\\partial Y} \\right )_{Y=0}\n\\]\nWe have computed 4000 ``data points'' in the range\n\\[\nZ = 6  ;  13  ;  29  ;  47  ;  74  ;  92  \\hspace{1cm}\n10 \\: \\mbox{keV} \\leq T \\leq 10 \\: \\mbox{TeV}  \\hspace{1cm}\n10 \\: \\mbox{keV} \\leq k_c \\leq T\n\\]\nand we have performed a least-squares fit to determine the parameters.\n\nThe values of the parameters ($\\xi_{\\sigma}$, $\\alpha$,\n$v_{\\sigma}$, $C_i $ for $\\sigma$ and\n$\\xi_l$, $\\beta$, $V_l$, $C$ for $E_{Loss}^{brem}$)\ncan be found in the code of the class itself.\n\nThe errors of the parameterisations (\\ref{ebrem.a}) and (\\ref{ebrem.b})\ncan be estimated as\n\n\\begin{eqnarray*}\n\\frac{\\Delta\\sigma} {\\sigma} & = & \\left \\{\n\\begin{array}{llr}\n        12-15\\%    & \\mbox{for    } & T \\leq 1 MeV \\\\\n        \\leq 5-6\\% & \\mbox{for    } & 1 MeV < T \\leq 10 TeV\n\\end{array}\n\\right . \\\\[1cm]\n\\frac{\\Delta E_{Loss}^{brem}}\n     {E_{Loss}^{brem}} & = & \\left \\{\n\\begin{array}{llr}\n        10-15\\%    & \\mbox{for    } & T \\leq1 MeV  \\\\\n        5-6\\%      & \\mbox{for    } & 1 MeV < T \\leq 100 GeV\\\\\n        10\\%       & \\mbox{for    } & 100 GeV < T \\leq10 TeV\n\\end{array}\n\\right .\n\\end{eqnarray*}\n\n\nThe energy loss due to soft photon bremsstrahlung is tabulated at\ninitialisation time as a function of the medium and of the energy.  \n\nThe mean free path for discrete bremsstrahlung is tabuled at initialisation\ntime as a function\nof the medium and of the energy, too.  \n\n\\subsection{Corrections for $e^+ e^-$ differences}\n\nThe radiative energy loss for electrons or positrons is:\n\n\\begin{eqnarray*}\n-\\frac{1}{\\rho} \\left ( \\frac{dE}{dx} \\right )_{rad}^{\\pm} & = &\n\\frac{N_{Av} \\alpha r_e^2}{A} (T+m) Z^2 \\Phi_{rad}^{\\pm}(Z,T) \\\\\n\\Phi^{\\pm}_{rad}(Z,T) & = & \\frac{1}{\\alpha r_{e}^2 Z^2 (T+m)}\n\\int^{T}_{0}{k\\frac{d\\sigma^{\\pm}}{dk}dk}\n\\end{eqnarray*}\n\nReference \\cite{ebrem.kim} says that: \\\\\n{\\it ``The differences between the radiative loss of positrons\nand electrons are considerable and cannot be disregarded.\n\n[...] The ratio of the radiative energy loss for positrons\nto that for electrons obeys a simple scaling law, [...] is a\nfunction only of the quantity $T/Z^2$''}\n\nIn other words:\n\n\\begin{eqnarray*}\n\\eta & = & \\frac{\\Phi_{rad}^{+}(Z,T)}{\\Phi_{rad}^{-}(Z,T)} =\n\\eta \\left (\\frac{T}{Z^2}\\right )\n\\end{eqnarray*}\n\nThe authors have calculated this function in the range $10^{-7}\n\\leq \\frac{T}{Z^2} \\leq 0.5$ (here the kinetic energy T is\nexpressed in MeV). Their {\\it data} can be fairly accurately\nreproduced using a parametrisation:\n\n\\begin{eqnarray*}\n\\eta & = & \\left \\{\n\\begin{array}{llr}\n0 & \\mbox{if   } & x \\leq -8 \\\\\n\\frac{1}{2} + \\frac{1}{\\pi} \\arctan \\left( a_1 x + a_3 x^3\n+ a_5 x^5 \\right ) & \\mbox{if  } & -8 < x < 9 \\\\\n1 & \\mbox{if   } & x \\geq 9\n\\end{array}\n\\right .\n\\end{eqnarray*}\n\nwhere:\n\n\\begin{eqnarray*}\nx & = & \\log \\left ( C \\frac{T}{Z^2} \\right ) \\mbox{(T in GeV)} \\\\\nC & = & 7.5221 \\times 10^{6} \\\\\na_1 & = & 0.415 \\\\\na_3 & = & 0.0021 \\\\\na_5 & = & 0.00054\n\\end{eqnarray*}\n\nThis $e^+ e^-$ energy loss difference is not a pure low-energy\nphenomenon (at least for high Z), as it can be seen from\nTables~\\ref{ebrem.c}.\n\n\\begin{table}[hbt]\n\\begin{centering}\n\\begin{tabular}{rr|r|r} \\hline\n\\multicolumn{1}{c}{$\\frac{T}{Z^2} (GeV)$}\n& \\multicolumn{1}{c|}{T}\n& \\multicolumn{1}{c|}{$\\eta$}\n& \\multicolumn{1}{c}{$\\left ( \\frac{rad. \\ loss}{total \\ loss}\n\\right )_{e^-}$} \\\\[3mm] \\hline\n$10^{-9}$ & $\\sim 7 keV$ & $\\sim 0.1$ & $\\sim 0\\%$ \\\\\n$10^{-8}$ & $67 keV $ & $\\sim 0.2$ & $\\sim 1\\%$ \\\\\n$2 \\times 10^{-7}$ & $1.35 MeV$ & $\\sim 0.5$ & $\\sim 15\\%$ \\\\\n$2 \\times 10^{-6}$ & $13.5 MeV$ & $\\sim 0.8$ & $\\sim 60\\%$ \\\\\n$2 \\times 10^{-5}$ & $135. MeV$ & $\\sim 0.95$ & $> 90\\%$ \\\\ \\hline\n\\end{tabular}\n\\caption{ratio of the $e^+ e^-$ radiative energy loss in lead\n(Z=82).}\n\\label{ebrem.c}\n\\end{centering}\n\\end{table}\n\nThe scaling holds for the ratio of the total radiative energy\nlosses, but it is significantly broken for the photon spectrum\nin the screened case.\nIn case of a point Coulomb charge the\nscaling would hold also for the spectrum.\nThe scaling can be expressed by:\n\n\\begin{eqnarray*}\n\\frac{\\Phi^+}{\\Phi^-} = \\eta \\left ( \\frac{T}{Z^2} \\right )\n& \\hspace{3cm} &\n\\frac{\\frac{d\\sigma^+}{dk}}{\\frac{d\\sigma^-}{dk}} =\n\\mbox{does not scale}\n\\end{eqnarray*}\n\nIf we consider the photon spectrum from bremsstrahlung reported\nin \\cite{ebrem.kim} we see that:\n\n\\begin{eqnarray*}\n\\frac{d\\sigma^{\\pm}}{dk} = S^{\\pm} \\left( \\frac{k}{T} \\right )\n\\hspace{2cm}\n\\frac{S^{+}(k)}{S^{-}(k)} \\leq 1 & \\hspace{1cm} & S^{+}(1) = 0\n\\hspace{2cm} S^{-}(1)  >  0\n\\end{eqnarray*}\n\nWe further assume that:\n\n\\begin{eqnarray}\n\\frac{d\\sigma^+}{dk} = f(\\epsilon) \\frac{d\\sigma^-}{dk}\n& \\hspace{2cm} &\n\\epsilon = \\frac{k}{T}\n\\label{ebrem.d}\n\\end{eqnarray}\n\nIn order to satisfy approximately the scaling law for the ratio\nof the total radiative energy loss, we require for $f(\\epsilon)$:\n\n\\begin{eqnarray}\n\\int^{1}_{0}{f(\\epsilon)d\\epsilon} & = & \\eta\n\\label{ebrem.e}\n\\end{eqnarray}\n\nFrom the photon spectra we require:\n\n\\begin{eqnarray}\n\\left .\n\\begin{array}{l}\nf(0) = 1 \\\\\nf(1) = 0\n\\end{array}\n\\right \\} \\hspace{2cm} \\mbox{for all $Z,T$}\n\\label{ebrem.f}\n\\end{eqnarray}\n\nWe have chosen a simple function $f$:\n\n\\begin{eqnarray}\nf(\\epsilon) & = & C (1-\\epsilon)^{\\alpha} \\hspace{3cm} C,\\alpha > 0\n\\label{ebrem.g}\n\\end{eqnarray}\n\nfrom the conditions (\\ref{ebrem.e}), (\\ref{ebrem.f}) we get:\n\n\\begin{eqnarray*}\nC & = & 1 \\\\\n\\alpha & = & \\frac{1}{\\eta} - 1 \\hspace{2cm}\n\\mbox{($\\alpha > 0$ because $\\eta < 1$)} \\\\\nf(\\epsilon) & = & (1-\\epsilon)^{\\frac{1}{\\eta}-1}\n\\end{eqnarray*}\n\nWe have defined weight factors $F_{l}$ and $F_{\\sigma}$ for the\npositron continuous energy loss and discrete bremsstrahlung cross\nsection:\n\n\\begin{eqnarray}\nF_{l} = \\frac{1}{\\epsilon_{0}} \\int^{\\epsilon_{0}}_{0}\n{f(\\epsilon)d\\epsilon} & \\hspace{3cm} &\nF_{\\sigma} = \\frac{1}{1-\\epsilon_{0}} \\int^{1}_{\\epsilon_{0}}\n{f(\\epsilon)d\\epsilon}\n\\label{ebrem.h}\n\\end{eqnarray}\n\nwhere $\\epsilon_{0} = \\frac{k_c}{T}$ and $k_c$ is the photon\ncut . In this scheme the positron energy loss and\ndiscrete bremsstrahlung can be calculated as:\n\n\\begin{eqnarray*}\n\\left ( - \\frac{dE}{dx} \\right )^{+} = F_{l}\n\\left ( - \\frac{dE}{dx} \\right )^{-} & \\hspace{2cm} &\n\\sigma^{+}_{brems} = F_{\\sigma} \\sigma^{-}_{brems}\n\\end{eqnarray*}\n\nAs in this approximation the photon spectra are identical, the\nsame sampling is used for generating $e^- e^+$ bremsstrahlung.\nThe following relations hold:\n\n\\begin{eqnarray*}\nF_{\\sigma} & = & \\eta (1-\\epsilon_{0})^{\\frac{1}{\\eta}-1}\n< \\eta \\\\\n\\epsilon_{0} F_{l} + (1-\\epsilon_{0}) F_{\\sigma} & = & \\eta\n\\hspace{6cm} \\mbox{from the def (\\ref{ebrem.h})} \\\\\n\\Rightarrow F_{l} & = & \\eta \\frac{1-(1-\\epsilon_{0})^{\\frac{1}\n{\\eta}})}{\\epsilon_{0}} > \\eta \\frac{1-(1-\\epsilon_{0})}\n{\\epsilon_{0}} = \\eta  \\hspace{1cm}\n\\Rightarrow   \\left \\{\n\\begin{array}{l}\nF_{l} > \\eta \\\\\nF_{\\sigma} < \\eta\n\\end{array} \\right .\n\\end{eqnarray*}\n\nwhich is consistent with the spectra.\n\nThe effect of this $e^- e^+$ bremsstrahlung difference can be also\nseen in e.m. shower development, when the primary energy is not too\nhigh. \n\n\\subsection{LPM effect}\n\nThe LPM effect (see e.g in \\cite{ebrem.galitsky},\\cite{ebrem.anthony} )\n is the supression of the photon production due to the\nmultiple scattering of the electrons.If an electron multiple scatters\nwhile traversing the co called formation zone, the bremsstrahlung\namplitude from before and after the scattering can interfere, reducing the\namplitude for bremsstrahlung photon emission (similar supression occurs \nfor pair production,too). The supression becomes significant for photon\nenergies below a certain value, given by\n\\begin{equation}\n\\label{ebrem.k}\n \\frac{k}{E} < \\frac{E}{E_{LPM}}\n\\end{equation}\n , where\n\\[\n\\begin{array}{ll}\nk    & \\mbox{photon energy} \\\\\nE    & \\mbox{electron energy} \\\\\nE_{LPM} & \\mbox{characteristic energy for LPM effect (depend on the medium).} \n\\end{array}\n\\]\n\nThe value of the LPM characteristic energy can be written as\n\n\\begin{equation}\n\\label{ebrem.l}\n  E_{LPM} = \\frac{\\alpha m^2 X_0}{4 h c}\n\\end{equation}\n\n , where\n\\[\n\\begin{array}{ll}\n\\alpha  & \\mbox{fine structure constant} \\\\\nm       & \\mbox{electron mass} \\\\\nX_0     & \\mbox{radiation length in the material} \\\\\nh       & \\mbox{Planck constant} \\\\\nc       & \\mbox{velocity of light in vacuum.}\n\\end{array} \n\\]\n\n The LPM supression of the photon spectrum is given by the formula\n\n\\begin{equation}\n\\label{ebrem.m}\n  S_{LPM} = \\sqrt{\\frac{E_{LPM} \\cdot k}{E^2}}\n\\end{equation}\n\n, while the dielectric supression (included already in the parametrisations) \ncan be written as\n\n\\begin{equation}\n\\label{ebrem.n}\n  S_p = \\frac{k^2}{k^2 + C_p \\cdot E^2}\n\\end{equation}\n\n , where the quantity $C_p$ is given by\n\n\\begin{equation}\n\\label{ebrem.o}\n   C_p = \\frac{r^2_0 \\lambda^2_e n}{\\pi}\n\\end{equation}\n\nIn eq. \\ref{ebrem.o} the parameters are\n\\[\n\\begin{array}{ll}\nr_0     & \\mbox{classical electron radius} \\\\\n\\lambda_e & \\mbox{electron Compton wawelength} \\\\\nn       & \\mbox{electrondensity in the material.}\n\\end{array}\n\\]\n\n Both of the supression effects reduce the effective formation length\nof the photon , so the supressions {\\em do not simply multiply.} For the\ntotal supression S the following equation holds (see \\cite{ebrem.galitsky})\n\\begin{equation}\n\\label{ebrem.p}\n  \\frac{1}{S} = 1 + \\frac{1}{S_p} + \\frac{S}{S^2_{LPM}}\n\\end{equation}\n which can be solved easily for $S$\n\\begin{equation}\n\\label{ebrem.q}\n  S = \\frac{\\sqrt{S^4_{LPM}\\cdot (1 + \\frac{1}{S_p})^2 + 4 \\cdot S^2_{LPM}}\n      -S^2_{LPM} \\cdot (1 + \\frac{1}{S_p})}{2}\n\\end{equation}\n \n The implementation of the LPM effect has been done in the following way:\nThe cross section and energy loss should be modified by applying the\n (energy and material dependent ) factor $\\frac{S}{S_p}$ . This is done\nat initialisation time for the energy loss by computing the correction\nfactor\n\\begin{equation}\n\\label{ebrem.r}\n   f_c = \\frac{\\int_0^{k_cut} n_\\gamma (k) \\cdot \\frac{S}{S_p} dk}\n              {\\int_0^{k_cut} n_\\gamma (k) dk}\n\\end{equation}\n , wherea $n_\\gamma (k)$ is the photon specrum .\n The total cross section given by the parametrization \\ref{ebrem.a} has\nnot been modified , the algorithm of the photon generation takes care\nof the LPM effect.\n\n\\section{Simulation of the discrete bremsstrahlung}\n\nThe photon energy is sampled according to the Seltzer and Berger\nbremsstrahlung spectrum~\\cite{ebrem.seltzer}.\n Seltzer and Berger have calculated the\nspectra for materials with atomic numbers Z = 6,13,29,47,74,92\nin the electron (kinetic) energy range  1 keV - 10 GeV. Their tabulated\nresults have been used as input in a parametrising-fitting procedure.\nThe functional form of the parameterisation for the quantity:\n\n\\[\nS(x) = C k \\frac{d \\sigma}{d k}\n\\]\n\ncan be written as\n\\begin{equation}\n\\label{eq:phys341-1}\nS(x) = \\left \\{\n\\begin{array}{ll}\n(1-a_{h} \\epsilon )F_{1}(\\delta) + b_{h} \\epsilon^{2} F_{2} (\\delta)\n& T \\geq 1 MeV \\\\\n1 + a_{l} x + b_{l} x^{2} & T < 1 MeV\n\\end{array} \\right .\n\\end{equation}\nwhere:\n\\[\n\\begin{array}{lcllcl} \nC & & \\mbox{normalisation constant} &\nk & & \\mbox{photon energy} \\\\ [1mm]\nT, E & & \\mbox{kinetic and total energy of the primary electron} &\nx & = & \\frac{k}{T} \\\\ [2mm]\n\\epsilon & = & \\frac{k}{E} = x \\frac{T}{E}\n\\end{array}\n\\]\n\nThe $F_{i}(\\delta)$ screening functions depend on the screening variable:\n\\[\n\\begin{array}{lcll}\n\\delta & = & \\frac{136 m_{e}}{Z^{1/3} E} \\frac{\\epsilon}{1-\\epsilon} \\\\\nF_{1}(\\delta) & = & F_{0} (42.392 - 7.796 \\delta +1.961 \\delta^{2} - F)\n& \\delta \\leq 1 \\\\\nF_{2}(\\delta) & = & F_{0} (41.734 - 6.484 \\delta +1.250 \\delta^{2} - F)\n& \\delta \\leq 1 \\\\\nF_{1}(\\delta) & = & F_{2}(\\delta) =\nF_{0} (42.24 - 8.368 \\ln(\\delta + 0.952) -F) & \\delta > 1 \\\\\nF_{0} & = & \\frac{1}{42.392-F} \\\\\nF & = & 4 \\ln Z - 0.55 (\\ln Z)^{2}\n\\end{array}\n\\]\n\n$a_{h,l}$ and $b_{h,l}$ are parameters to be fitted.\n\nThe `high energy' (T $>$  1 MeV) formula comes from the\nCoulomb-corrected, sceened Bethe-Heitler formula (see e.g.\n\\cite{ebrem.williams,ebrem.butcher,ebrem.egs4}). However, there are two things in eq.\n(\\ref{eq:phys341-1}) which make a difference:\n\n\\begin{enumerate}\n\\item $a_{h}, b_{h}$ depend on T and on the atomic number Z ( in the case\nof the Bethe-Heitler spectrum $a_{h} = 1$, $b_{h} =0.75$);\n\\item the function $F$ is not the same than that in the Bethe-Heitler\ncross-section, this function gives a better behaviour in the\nhigh frequency limit, i.e. when $k \\rightarrow T$  ($x \\rightarrow 1$).\n\\end{enumerate}\n\nThe T and Z dependence of the parameters are described by the equations:\n\n\\begin{eqnarray*}\na_{h} & = & 1 + \\frac{a_{h1}}{u}+\\frac{a_{h2}}{u^{2}}+\\frac{a_{h3}}{u^{3}} \\\\\nb_{h} & = & 0.75+\\frac{b_{h1}}{u}+\\frac{b_{h2}}{u^{2}}+\\frac{b_{h3}}{u^{3}} \\\\\na_{l} & = & a_{l0} + a_{l1} u + a_{l2} u^{2} \\\\\nb_{l} & = & b_{l0} + b_{l1} u + b_{l2} u^{2} \\\\\n\\mbox{with} \\\\\nu & = & \\ln \\left ( \\frac{T}{m_{e}} \\right )\n\\end{eqnarray*}\n\nthe $a_{hi}, b_{hi}, a_{li}, b_{li}$ parameters are polynomials of second order\nin the variable:\n\n\\[\nv = [Z (Z+1)]^{1/3}\n\\]\n\nIt can be seen relatively easily that for the limiting case $T \\rightarrow\n\\infty$, $a_{h} \\rightarrow 1, b_{h} \\rightarrow 0.75$,\nso eq. (\\ref{eq:phys341-1}) gives the Bethe-Heitler cross section.\n\nThere are altogether 36 linear parameter in the formulae , their\nvalues are given in the code. The parameterisation reproduces\nthe Seltzer-Berger tables within a few \\% (2-3 \\% on average,\nthe maximum error being less than 10-12 \\%), the tables, on the other hand,\nagree well with the experimental data and theoretical (low- and high-energy)\nresults (less than 10 \\% below 50 MeV, less than 5 \\% above 50 MeV).\n\nApart from the normalisation the cross section differential in photon\nenergy can be written as:\n\\[\n\\frac{d \\sigma}{d k} = \\frac{1}{\\ln \\frac{1}{x_{c}}} \\frac{1}{x}\ng(x) = \\frac{1}{\\ln \\frac{1}{x_{c}}} \\frac{1}{x} \\frac{S(x)}{S_{max}}\n\\]\n\nwhere $x_{c} = k_{c}/T$, $k_{c}$ is the photon cut-off energy below\nwhich the bremsstrahlung is treated as a continuous energy loss\n. Using this decomposition of\nthe cross section and two random numbers $r_{1}$, $r_{2}$ uniformly\ndistributed in $]0,1[$, the sampling of $x$ is done as follows:\n\\begin{enumerate}\n\\item sample $x$ from\n\\[\n\\frac{1}{\\ln \\frac{1}{x_{c}}} \\frac{1}{x} \\mbox{\\hspace{1cm}setting\\hspace{1cm}}\nx = e^{r_{1} \\ln x_{c}}\n\\]\n\n\\item calculate the rejection function $g(x)$ and:\n\\begin{itemize}\n\\item if $r_{2} > g(x)$ reject $x$ and go back to 1;\n\\item if $r_{2} \\leq g(x)$ accept $x$.\n\\end{itemize}\n\\end{enumerate}\n\nTo apply the dielectric supression  \\cite{ebrem.migdal}\n  all it has to be done is to\nmultiply the rejection function by the supression factor , which is \nequivalent to the expression \\ref{ebrem.n}:\n\n\\[\nC_M (\\epsilon)  =\\frac{1 + C_0 / \\epsilon_c^2}\n               {1 + C_0 / \\epsilon^2}\n\\]\n where\n\\[\nC_0 =\\frac{nr_0 \\lambda^2 }{\\pi}, \\hspace{1cm} \\epsilon_c = \\frac{k_{c}}{E}\n\\]\n\\begin{itemize}\n\\item[$n$]           electron density in the medium\n\\item[$r_0$]         classical electron radius\n\\item[$\\lambda$]    reduced Compton wavelength of the electron.\n\\end{itemize}\nThis correction decreases the cross-section for low photon energy.\n\n After having $\\epsilon$ sampled , the supression factor $f_{LPM}=\\frac{S}{S_p}$ is\nused as a rejection function in order to take into account the LPM effect , too.\nHere the supression factor is compared to a random number $r$ uniformly\ndistributed in the interval $(0,1)$. If  $f_{LPM} \\geq r$ the simulation\nis continuing otherwise the bremsstrahlung process is finished \n{\\em without photon production } .It can be seen easily that this procedure\ntakes into account the LPM supression correctly.\n\n\nAfter the successful sampling of $\\epsilon$,  the\npolar angles of the radiated photon are generated with respect to the parent\nelectron's momentum. It is difficult to find in the literature\nsimple formulas for this angle. For example the double differential\ncross section reported by Tsai~\\cite{ebrem.tsai1,ebrem.tsai2} is the\nfollowing:\n\\begin{eqnarray*}\n\\frac{d \\sigma}{dkd \\Omega}\n& = & \\frac{2 \\alpha^{2}e^{2}}{\\pi k m^{4}}\n  \\left\\{ \\left[ \\frac{2\\epsilon-2}{(1+u^2)^2}+\n\\frac{12u^2(1-\\epsilon)}{(1+u^2)^4}\\right]\n      Z(Z+1)  \\right. \\\\\n&   & \\mbox{} + \\left. \\left[ \\frac{2-2\\epsilon-\\epsilon^{2}}{(1+u^2)^2}-\n      \\frac{4u^2(1-\\epsilon)}{(1+u^2)^4}\n      \\right]\n      \\left[ X-2Z^{2}f_{c}((\\alpha Z)^{2})\\right]\n      \\right\\} \\\\\nu & = & \\frac{E \\theta}{m} \\\\\nX & = & \\int_{t_{min}}^{m^{2}(1+u^{2})^{2}}\n{\\left [ G_{Z}^{el}(t) + G_{Z}^{in}(t) \\right ] \\frac{t-t_{min}}\n{t^{2}} dt} \\\\\nG_{Z}^{el, in}(t) & & \\mbox{atomic form factors} \\\\\nt_{min} & = & \\left [ \\frac{k m^{2} (1+u^{2})}{2 E (E-k)} \\right ] ^{2}\n = \\left [ \\frac{\\epsilon m^{2} (1+u^{2})}{2 E (1-\\epsilon)} \\right ] ^{2}\n\\end{eqnarray*}\n\nThis distribution is complicated to sample, and it is anyway only an\napproximation to within few percent, if nothing else, due to\nthe presence of the atomic form-factors.\nThe angular dependence is contained in the\nvariable $u = E \\theta m^{-1}$. For a given value\nof $u$ the dependence of the shape of the function on $Z$, $E$,\n$\\epsilon = k/E$ is very weak.\nThus, the distribution can be approximated by a function\n\\begin{equation}\nf(u) = C \\left( u e^{-au} + d u e^{-3au} \\right)\n\\end{equation}\nwhere\n\\[\nC = \\frac{9a^{2}}{9 + d} \\hspace{1cm} a = 0.625 \\hspace{1cm}\nd = 0.13 \\: \\left ( 0.8+\\frac{1.3}{Z} \\right ) \\left (100+\\frac{1}{E} \\right )\n(1+\\epsilon)\n\\]\nwhere $E$ is in GeV. While this approximation is good at high energies,\nit becomes less accurate around few MeV. However in that region the\nionisation losses dominate over the radiative losses.\n\nThe sampling of the function $f(u)$ can be done in the following way\n($r_{i},\\: i=1,2,3$ are uniformly distributed random numbers\nin [0,1]):\n\\begin{enumerate}\n\\item Choose between $u e^{-au}$ and $d u e^{-3au}$:\n\\[\nb = \\left \\{ \\begin{array}{ll}\na & \\mbox{if\\hspace{0.5cm}}r_{1} < 9/(9+d) \\\\\n3a & \\mbox{if\\hspace{0.5cm}}r_{1} \\geq 9/(9+d)\n\\end{array} \\right .\n\\]\n\\item Sample $u e^{-bu}$:\n\\[\nu=-\\frac{\\log ( r_{2} r_{3}) }{b}\n\\]\n\\item check that:\n\\[\nu \\leq u_{max} = \\frac{E \\pi}{m}\n\\]\notherwise go back to 1.\n\\end{enumerate}\n\nThe probability of failing in the last test is reported in\ntable~\\ref{tb:phys341-1}.\n\n\\begin{table}\n\\begin{centering}\n\\begin{tabular}{|l|l|}\n\\multicolumn{2}{c}{$\\displaystyle\nP = \\int^{\\infty}_{u_{max}}{f(u) \\: du} \\hfill $} \\\\ [0.5cm]\n\\hline\nE (MeV) & P(\\%) \\\\ \\hline\n0.511 & 3.4 \\\\\n0.6 &  2.2 \\\\\n0.8 & 1.2 \\\\\n1.0 & 0.7 \\\\\n2.0 & $<$ 0.1 \\\\ \\hline\n\\end{tabular}\n\\caption{Angular sampling efficiency}\n\\label{tb:phys341-1}\n\\end{centering}\n\\end{table}\n\n\nThe function $f(u)$ can be used also to describe\nthe angular distribution of the photon in $\\mu$ bremsstrahlung and to\ndescribe the angular distribution in photon pair production.\n\nThe azimuthal angle, $\\Phi$, is generated isotropically.\nThis information is used to calculate the momentum vector of the radiated\nphoton, to transform it to the global  coordinate system. \nAlso, the momentum of the parent electron is updated.\n\n\\section{Status of this document}\n\n   9.10.98  created by L. Urb\\'an.\n  \n\\begin{thebibliography}{99}\n\n\\bibitem[GEANT3]{ebrem.geant3}\n  GEANT3 manual ,CERN Program Library Long Writeup W5013 (October 1994).\n\\bibitem[Gal64]{ebrem.galitsky}\n  V.M.Galitsky and I.I.Gurevich. Nuovo Cimento 32 (1964) 1820.\n\\bibitem[Ant97]{ebrem.anthony}\n  P.L. Anthony et al. SLAC-PUB-7413/LBNL-40054 (February 1997)\n\\bibitem[Sel85]{ebrem.seltzer}\n  S.M.Seltzer and M.J.Berger. Nucl.Inst.Meth. 80 (1985) 12.\n\\bibitem[Mess70]{ebrem.messel}\n  H.Messel and D.F.Crawford. Pergamon Press,Oxford,1970.\n\\bibitem[EGS4]{ebrem.egs4} W.R. Nelson et al.:The EGS4 Code System.\n   {\\em SLAC-Report-265 , December 1985 }\n\\bibitem[Mig56]{ebrem.migdal}\n   A.B. Migdal. Phys.Rev. 103. (1956) 1811.\n\\bibitem[Kim86]{ebrem.kim} \n   L. Kim et al. Phys. Rev. A33 (1986) 3002.\n\\bibitem[Tsai74]{ebrem.tsai1}\n   Y-S. Tsai . Rev. Mod. Phys. 46. (1974) 815.\n\\bibitem[Tsai77]{ebrem.tsai2}\n   Y-S. Tsai . Rev. Mod. Phys. 49. (1977) 421.\n\\bibitem[Will60]{ebrem.williams}\n   R. W. Williams . Fundamental Formulas of Physics, vol.2. Dover Pubs.Inc,1960.\n\\bibitem[Butc60]{ebrem.butcher}\n   J. C. Butcher and H. Messel. Nucl.Phys. 20. (1960) 15.\n\n\\end{thebibliography}\n\n", "meta": {"hexsha": "7de218b39f3a961fc3b98c81cb88c4e41015ddc6", "size": 26232, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "geant4/electromagnetic/standard/ebrem.tex", "max_stars_repo_name": "berghaus/cernlib-docs", "max_stars_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-24T12:30:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-24T12:30:01.000Z", "max_issues_repo_path": "geant4/electromagnetic/standard/ebrem.tex", "max_issues_repo_name": "berghaus/cernlib-docs", "max_issues_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geant4/electromagnetic/standard/ebrem.tex", "max_forks_repo_name": "berghaus/cernlib-docs", "max_forks_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5612648221, "max_line_length": 85, "alphanum_fraction": 0.6477965843, "num_tokens": 9626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.30150691009141295}}
{"text": "\n\\chapter{IDL Routines}\n\\label{ch_mrsp_idl}\n%\\chapterhead{IDL Routines}\n\\markright{IDL Routines}\n\n\n\\section{Introduction}\nA set of routines has been developed in IDL. Starting IDL using the script program {\\em isap.pro} allows the user \nto get the interactive sparse data analysis  environment, and all routines described in the following can be called. \nAn online help facility is also available by invoking the {\\em isaph} program under IDL. See Chapter~\\ref{ch_install} for more\ndetails on the software installation.\n  \n\\section{Functions for polarized spherical maps}\n\\index{polar}\n\n\\subsection{Reading a polarized spherical map from a file : mrsp\\_read}\n\\index{IDL routines!mrsp\\_read}\n\\index{polar!read polarized map}\nRead a polarized spherical map in Healpix format.\n{\\bf\n\\begin{center}\n     USAGE: map = mrsp\\_read( file, noverb=noverb )\n\\end{center}}\nwhere\n\\begin{itemize}\n\\item {\\em file} : Input string, name of the file to be read. The pathname can be included in the string, by default 'file.fits' is equivalemt to './file.fits'\n\\item {\\em noverb} : scalar, prevent the printing on the screen of the format (RING or NESTED) of the read map and the number of pixels.\n\\item {\\em map} : Output 3D IDL array of Healpix map read. The map is setted to the NESTED format after reading.\n\\end{itemize}\n\n\\subsubsection*{Examples:} \n\\begin{itemize}\n\\item map = mrsp\\_read( 'my\\_file\\_healpix\\_pola.fits', noverb=noverb ) \\\\\nRead the map stored into the file 'my\\_file\\_healpix\\_pola.fits' and load it into map.\n\\end{itemize}\n\n\n\n\\subsection{Writing a polarized spherical map into a file : mrsp\\_write}\n\\index{IDL routines!mrsp\\_write}\n\\index{polar!write polarized map}\nWrite a polarized spherical map in Healpix format.\n{\\bf\n\\begin{center}\n     USAGE: mrsp\\_write, file, map, ring=ring\n\\end{center}}\nwhere\n\\begin{itemize}\n\\item {\\em file} : Input string, name of the file to be writen. The pathname can be included in the string, by default 'file.fits' is equivalemt to './file.fits'\n\\item {\\em map} : Input 3D IDL array of Healpix map to be writen. The map is assumed to be in the NESTED format.\n\\item {\\em ring} : scalar, if set convert the Healpix map data to the RING format for the writing.\n\\end{itemize}\n\n\n\n\\subsection{Conversion of a polarized spherical map from TQU scheme to TEB scheme : mrsp\\_tqu2teb}\n\\index{IDL routines!mrsp\\_tqu2teb}\n\\index{polar!conversion tqu2teb}\nConvert a polarized map in Healpix nested format from TQU scheme to TEB scheme.\n{\\bf\n\\begin{center}\n     USAGE: mrsp\\_tqu2teb, map\\_tqu, map\\_teb\n\\end{center}}\nwhere\n\\begin{itemize}\n\\item {\\em map\\_tqu} : Input 3D IDL array of healpix polarized map in TQU scheme.\n\\item {\\em map\\_teb} : Output 3D IDL array of healpix polarized map in TEB scheme.\n\\end{itemize}\n\n\n\n\\subsection{Conversion of a polarized spherical map from TEB scheme to TQU scheme : mrsp\\_teb2tqu}\n\\index{IDL routines!mrsp\\_teb2tqu}\n\\index{polar!conversion tqu2teb}\nConvert a polarized map in Healpix nested format from TEB scheme to TQU scheme.\n{\\bf\n\\begin{center}\n     USAGE: mrsp\\_teb2tqu, map\\_teb, map\\_tqu\n\\end{center}}\nwhere\n\\begin{itemize}\n\\item {\\em map\\_teb} : Input 3D IDL array of healpix polarized map in TEB scheme.\n\\item {\\em map\\_tqu} : Output 3D IDL array of healpix polarized map in TQU scheme.\n\\end{itemize}\n\n\n\n\\subsection{Resizing a polarized spherical map: mrsp\\_resize}\n\\index{IDL routines!mrsp\\_resize}\n\\index{polar!polarized map resizing}\nResize a polarized map in Healpix nested format.\n{\\bf\n\\begin{center}\n     USAGE: resize\\_map = mrsp\\_resize( map, nside=nside, ViaAlm=ViaAlm, teb=teb )\n\\end{center}}\nwhere\n\\begin{itemize}\n\\item {\\em map} : Input 3D IDL array of healpix polarized map in TQU scheme to be transformed.\n\\item {\\em resize\\_map} : Output 3D IDL array of healpix polarized map in TQU scheme. Healpix input map and output resized map are in nested format.\n\\item {\\em nside} : int, the new nside parameter of the output healpix resized map.\n\\item {\\em ViaAlm} : scalar, if set use alm transform for the resizing, otherwise, use interpolation. \nIgnored if nside keyword value is lower than imag nside.\n\\item {\\em teb} : scalar, if set specifies that the input and output images are in TEB scheme.\n\\end{itemize}\n\n\\subsubsection*{Examples:} \n\\begin{itemize}\n\\item map2 = mrsp\\_resize( map, nside = 256, /ViaAlm ) \\\\\nresize an Healpix map.\n\\end{itemize}\n\n\n\n\n\n\\section{General transform/reconstruction routines}\n\n\\subsection{Transformations of a polarized spherical map : mrsp\\_trans}\n\\index{IDL routines!mrsp\\_trans}\n\\index{polar!transforms of polarized image}\nCompute a transform (E-B mode decomposition, wavelet with spline, Meyer or needelet filters, curvelet, \\ldots) \non a polarized map on the sphere in the Healpix representation (nested data representation) in TQU scheme.\\\\ \\\\\nThe transform can be:\n\\begin{enumerate}\n\\item A E/B decomposition using the spin\\_2 transform.\n\\item An orthogonal wavelet on each T,Q,U component.\n\\item A pyramidal isotropic wavelet on each T,Q,U component.\n\\item An undecimated wavelet transform on each component.\n\\item A decimated modulus-Phase wavelet transform.\n\\item A undecimated modulus-Phase wavelet transform.\n\\item A curvelet transform.\n\\end{enumerate}\n{\\bf\n\\begin{center}\n     USAGE: mrsp\\_trans, Imag, Trans, NbrScale=NbrScale, lmax=lmax, MeyerWave=MeyerWave, ebdec=ebdec, Cur=Cur, uwt=uwt, owt=owt, mpdwt=mpdwt, mpuwt=mpuwt, PyrWT=PyrWT, \n     DifInSH=DifInSH, Overlap=Overlap, FirstBlockSize=FirstBlockSize\n\\end{center}}\nwhere\n\\begin{itemize}\n\\item {\\em Imag} : Input 3D IDL array of healpix polarized map in TQU scheme. Input image to be transformed.\n\\item {\\em Trans} : Output IDL structure with the following fields:\n\\begin{itemize}\n\\item {\\em NbrScale} : int, number of scales.\n\\item {\\em nside} : int, Healpix nside parameter.\n\\item {\\em lmax} : int, maximum l value in the Spherical Harmonic Space.\n\\item {\\em npix} : long, number of pixels of the input image.\n\\item {\\em MeyerWave} : int, 1 if the keyword MeyerWave used, otherwise 0.\n\\item {\\em DifInSH} : int, 1 if the keyword DifInSH used, otherwise 0.\n\\item {\\em pyrtrans} : int, 1 if a pyramidal decomposition has been applied, otherwise 0.\n\\item {\\em ebdec} : int, 1 if an EB decomposiiton has been applied, otherwise 0.\n\\item {\\em DEC1} : IDL structure, first component transformation (depends on the chosen transform).\n\\item {\\em DEC2} : IDL structure, second component transformation (depends on the chosen transform).\n\\item {\\em DEC3} : IDL structure, third component transformation (depends on the chosen transform).\n\\item {\\em TransChoice} : string, code of the chosen transform.\n\\item {\\em TabCodeTransform} : string array, array of transforms codes. TabCodeTransform = ['T\\_EBDEC', 'T\\_OWT', 'T\\_PyrWT', 'T\\_UWT', 'T\\_MPDWT', 'T\\_MPUWT', 'T\\_CUR']\n\\item {\\em TransName} : string, transform's name.\n\\item {\\em TransTypeName} : string array, array of transforms names. \nTransTypeName = ['EBDEC','Bi-Orthogonal WT', 'Pyramidal WT', 'Undecimated WT', 'Module-Phase Decimated Transform', 'Module-Phase Undecimated Transform', 'Curvelet']\n\\end{itemize}\n\\item {\\em NbrScale} : int, number of scales of the wavelet transforms.\n\\item {\\em ebdec} : scalar, if set an E/B decomposition is applied before the chosen multiscale decomposition. \nIf no transform is selected, it will be the default transformation.\n\\item {\\em Cur} : scalar, if set perform a curvelet transform.\n\\item {\\em uwt} : scalar, if set perform an undecimated isotropic wavelet transform.\n\\item {\\em PyrWT} : scalar, if set perform a pyramidal isotropic wavelet transform.\n\\item {\\em owt} : scalar, if set perform a bi-orthogonal wavelet transform on each face.\n\\item {\\em mpdwt} : scalar, if set perform a decimated module-phase wavelet transform.\n\\item {\\em mpuwt} : scalar, if set perform a undecimated module-phase wavelet transform.\n\\item {\\em Overlap} : int, if equal to 1 if blocks are overlapping, only used with curvelet transform.\n\\item {\\em FirstBlockSize} : int, block size in the ridgelet transform at the finest scale (default is 16), only used with curvelet transform.\n\\item {\\em lmax} : int, maximum l value in the Spherical Harmonic Space (for isoptropic wavelet transform only).\n\\item {\\em DifInSH} : Input keyword parameter. If set, the wavelet coefficients are computed as the difference between two resolutions in the spherical harmonics representation. \nOtherwise, the wavelet coefficients are computed as the difference between two resolutions in direct space. Only used with keyword uwt or PyrWT.\n\\item {\\em MeyerWave} : If set, use Meyer wavelets and set the keyword DifInSH. Only used with keyword uwt or PyrWT.\n\\end{itemize}\n\n\\subsubsection*{Examples:} \n\\begin{itemize}\n\\item mrsp\\_trans, Imag, WT, NbrScale=5, /uwt \\\\\nCompute the undecimated wavelet transform of the map Imag with five scales. The result is stored in WT.\n\\end{itemize}\n\n\n\n\\subsection{Reconstructions of a polarized spherical map : mrsp\\_rec}\n\\index{IDL routines!mrsp\\_rec}\n\\index{polar!inverse transform of polarized image}\nCompute a inverse transform (wavelet, curvelet, \\ldots) to get a polarized map on the sphere in the Healpix representation \n(nested data representation) in TQU scheme from its decomposition obtained by mrsp\\_trans.\\\\ \\\\\nThe transform can be:\n\\begin{enumerate}\n\\item A E/B decomposition using the spin\\_2 transform.\n\\item An orthogonal wavelet on each T,Q,U component.\n\\item A pyramidal isotropic wavelet on each T,Q,U component.\n\\item An undecimated wavelet transform on each component.\n\\item A decimated modulus-Phase wavelet transform.\n\\item A undecimated modulus-Phase wavelet transform.\n\\item A curvelet transform.\n\\end{enumerate}\n{\\bf\n\\begin{center}\n     USAGE: mrsp\\_rec, Trans, Rec\n\\end{center}}\nwhere\n\\begin{itemize}\n\\item {\\em Trans} : Input IDL structure, see mrsp\\_trans for more details.\n\\item {\\em Rec} : Output 3D IDL array of healpix polarized map in TQU scheme. Reconstructed image.\n\\end{itemize}\n\n\\subsubsection*{Examples:} \n\\begin{itemize}\n\\item mrsp\\_trans, Imag, WT, NbrScale=5, /uwt \\\\\nCompute the undecimated wavelet transform of the map Imag with five scales. The result is stored in WT.\n\\item mrsp\\_rec, WT, RecIma \\\\\nReconstruct the image.\n\\end{itemize}\n\n\n\n\\section{Spin-2 spherical harmonic transform}\n \n\\subsection{ALM transform of a polarized spherical map : mrsp\\_almtrans}\n\\index{IDL routines!mrsp\\_almtrans}\n\\index{polar!polar ALM transform}\nComputes the spherical harmonic transform of a polarized TQU map using the Healpix representation (nested data).\n{\\bf\n\\begin{center}\n     USAGE: mrsp\\_almtrans, Imag, Trans, lmax=lmax, tab=tab, complex=complex, norm=norm, fast=fast\n\\end{center}}\nwhere\n\\begin{itemize}\n\\item {\\em Imag} : Input 3D IDL array of healpix polarized map in TQU scheme to be transformed.\n\\item {\\em Trans} : Output IDL structure with the following fields:\n\\begin{itemize}\n\\item {\\em ALM} : array of the ALM coefficients\n\\begin{center}\nALM = fltarray[*,2,3] list of the real part (ALM[*,0,*]) and imaginary part (ALM[*,1,*]) of the ALM. \nThis is the default storage, ALM[*,*,0] is ALM T, ALM[*,*,1] is ALM E and ALM[*,*,2] is ALM B\\\\\nALM = cfarr[*,3] list of the ALM in complex values format if the keyword complex is set. \nALM[*,0] is ALM T, ALM[*,1] is ALM E and ALM[*,2] is ALM B\\\\\nALM = fltarray[NbrMaxM, NbrMaxL, 2, 3] table of the real part (ALM[*,*,0,*]) and imaginary part (ALM[*,*,1,*]) \nof the ALM if the keyword tab is set. ALM[*,*,*,0] is ALM T, ALM[*,*,*,1] is ALM E and ALM[*,*,*,2] is ALM B\\\\\nALM = cfarr[NbrMaxM, NbrMaxL, 3] table of the ALM in complex values format if the keywords complex and tab \nare both setted. ALM[*,*,0] is ALM T, ALM[*,*,1] is ALM E and ALM[*,*,2] is ALM B\\\\\nBy default, NbrMaxM = NbrMaxL = lmax+1\n\\end{center}\n\\item {\\em complex\\_alm} : int, 0 (default value) if ALM array contains real and imaginary part separated. \n1 if ALM is a complex array.\n\\item {\\em PixelType} : int, 0 for a Healpix input map (1 for GLESP but not used).\n\\item {\\em tab} : int, 0 for default ALM representation as a list (i.e. 1D IDL array) and 1 for 2D \nrepresentation as a table (i.e. l for the first dimension and m for the second).\n\\item {\\em nside} : int, Healpix nside parameter.\n\\item {\\em lmax} : int, maximum l value in the Spherical Harmonic Space.\n\\item {\\em npix} : long, number of pixels of the input image.\n\\item {\\em TabNbrM} : int array[NbrMaxL], max number of m value for a given l, only used if keyword tab is set otherwise, 0.\n\\item {\\em index} : long array, indicies of the ALM coefficients, used only if keyword tab is not set.\n\\item {\\em NormVal} : float, normalization value applied to the alm coefficients (only if keyword norm used).\n\\item {\\em norm} : int, 0 if no normalization has been aplied, else 1.\n\\end{itemize}\n\\item {\\em lmax} : int, Number of spherical harmonics computed in the decomposition. For a Healpix map, default is \n3*nside and should be between 2*nside and 4*nside.\n\\item {\\em tab} : scalar, if set, ALM coefficients in Trans.alm are stored in a 2D array: Trans.alm[m,l] where m = 0..Trans.TabNbrM[l]-1  and l = 0..lmax-1\n\\item {\\em complex} : scalar, if set Trans.alm will contain complex values instead of the real and imaginary parts.\n\\item {\\em norm} : scalar, if set, a normalization is performed to the alm coefficients.\n\\end{itemize}\n\n\\subsubsection*{Example:} \n\\begin{itemize}\n\\item mrsp\\_almtrans, Imag, Output \\\\\nCompute the spherical harmonics transform of a polarized image, the result is stored in Output.\n\\end{itemize}\n\n\n\n\\subsection{ALM inverse transform of a polarized spherical map : mrsp\\_almrec}\n\\index{IDL routines!mrsp\\_almrec}\n\\index{polar!polar ALM inverse transform}\nComputes the inverse spherical harmonic transform of a polarized TQU map using using the Healpix representation (nested data).\n{\\bf\n\\begin{center}\n     USAGE: mrsp\\_almrec, Trans, imag, pixel\\_window=pixel\\_window\n\\end{center}}\nwhere\n\\begin{itemize}\n\\item {\\em Trans} : Input IDL structure of ALM coefficients, see mrsp\\_almtrans above for details.\n\\item {\\em Imag} : Output 3D IDL array of healpix polarized map in TQU scheme. Image reconstructed in Healpix nested representation.\n\\item {\\em pixel\\_window} : scalar, if set the image is convolved by the healpix pixel window (only for Healpix map).\n\\end{itemize}\n\n\n\\subsubsection*{Example:} \n\\begin{itemize}\n\\item mrsp\\_almtrans, PolaImag, Output \\\\\nCompute the spherical harmonics transform of a polarized image, the result is stored in Output.\n\\item mrsp\\_almrec, Output, PolaRec \\\\\nReconstruct the image.\n\\end{itemize}\n\n\n\n\\subsection{Power spectrum and cross spectrum exctraction from polarized ALM~: mrsp\\_alm2spec}\n\\index{IDL routines!mrsp\\_alm2spec}\n\\index{polar!spectrum exctraction from polarized ALM}\nComputes the power spectrums and cross spectrums of a polarized map from the polarized ALM coefficients.\n{\\bf\n\\begin{center}\n     USAGE: spec = mrsp\\_alm2spec( ALM, StdPS=StdPS )\n\\end{center}}\nwhere\n\\begin{itemize}\n\\item {\\em ALM} : Input IDL structure of ALM polarized coefficients, see mrsp\\_almtrans above for details.\n\\item {\\em spec} : Output 2D IDL float array[ALM.lmax+1,6], the TT, EE, BB, TE, TB, EB spectrums. P[k,i] = Mean( SPECTRUM[*,l,i] ) \\quad i=0...5.\n\\item {\\em StdPS} : Output 2D IDL float array[ALM.lmax+1,6]: estimated standard deviation of the spectrums coefficients.\n\\end{itemize}\n\n\\subsubsection*{Example:} \n\\begin{itemize}\n\\item mrsp\\_almtrans, Imag, Output \\\\\nCompute the spherical harmonics transform of a polarized image, the result is stored in Output.\n\\item spec = mrsp\\_alm2spec( Output, StdPS=StdPS ) \\\\\nCompute the spectrums of the image and it's associated standard deviation.\n\\end{itemize}\n\n\n\\subsection{Power spectrum and cross spectrum exctraction from a polarized image : mrsp\\_spec}\n\\index{IDL routines!mrsp\\_spec}\n\\index{polar!spectrum exctraction from a polarized image}\nComputes the power spectrums and cross spectrums of a polarized map, using the HEALPix representation (nested data representation by default). \nBy default a normalisation is applied on the ALM coefficents.\n{\\bf\n\\begin{center}\n     USAGE: spec = mrsp\\_spec( Imag, nonorm=nonorm, teb=teb, NormVal=NormVal, StdPS=StdPS, lmax=lmax )\n\\end{center}}\nwhere\n\\begin{itemize}\n\\item {\\em Imag} : Input 3D IDL array of healpix polarized map in TQU scheme. Input image whose power spectrum will be extracted.\n\\item {\\em spec} : Output 2D IDL float array[ALM.lmax+1,6], the TT, EE, BB, TE, TB, EB spectrums. P[k,i] = Mean( SPECTRUM[*,l,i] ) \\quad i=0...5.\n\\item {\\em Lmax} : int, number of spherical harmonics computed in the decomposition and size of the computed spectrum (Lmax+1). Default is 3*nside and should be between 2*nside and 4*nside.\n\\item {\\em nonorm} : scalar, if set no normalisation is applied on the ALM computed.\n\\item {\\em StdPS} : Output 2D IDL float array[ALM.lmax+1,6]: estimated standard deviation of the spectrums coefficients.\n\\item {\\em NormVal} : float, normalization value applied to the alm coefficients.\n\\item {\\em teb} : scalar, if set specifies that the input map is in TEB scheme.\n\\end{itemize}\n\n\\subsubsection*{Example:} \n\\begin{itemize}\n\\item P = mrsp\\_spec( Imag ) \\\\\nCompute the spectrum of the polarized image.\n\\end{itemize}\n\n\n\n\\section{Polarized Wavelets}\n\\subsection{Undecimated Isotropic Wavelet Transform of a polarized spherical map : mrsp\\_wttrans}\n\\index{IDL routines!mrsp\\_wttrans}\n\\index{polar!undecimated wavelet transform of polarized image}\nComputes the undecimated isotropic wavelet transform of polarized maps on the sphere in TQU scheme, \nusing the Healpix representation (nested data representation). The wavelet function is zonal and its \nspherical harmonics coefficients $a_{l,0}$ follow a cubic box-spline profile. If the keyword DifInSH is \nset, the wavelet coefficients are derived in the Spherical Harmonic Space, otherwise (default) they \nare derived in the direct space.\n{\\bf\n\\begin{center}\n     USAGE: mrsp\\_wttrans, Imag, Trans, NbrScale=NbrScale, lmax=lmax, DifInSH=DifInSH, MeyerWave=MeyerWave\n\\end{center}}\nwhere\n\\begin{itemize}\n\\item {\\em Imag} : Input 3D IDL array of healpix polarized map in TQU scheme. Input image to be transformed.\n\\item {\\em Trans} : Output IDL structure with the following fields:\n\\begin{itemize}\n\\item {\\em NbrScale} : int, number of scales.\n\\item {\\em nside} : int, Healpix nside parameter.\n\\item {\\em lmax} : int, maximum l value in the Spherical Harmonic Space.\n\\item {\\em npix} : long, number of pixels of the input image.\n\\item {\\em MeyerWave} : int, 1 if the keyword MeyerWave used, otherwise 0\n\\item {\\em DifInSH} : int, 1 if the keyword DifInSH used, otherwise 0\n\\item {\\em Coef} : fltarr[npix,NbrScale,3] wavelet transform of the data. Coef[*,*,0] = wavelet transform on T, Coef[*,*,1] = wavelet transform on E, Coef[*,*,2] = wavelet transform on B\n\\begin{center}\nCoef[*,0,*] = wavelet coefficients of the finest scale (highest frequencies).\\\\\nCoef[*,NbrScale-1,*] = coarsest scale (lowest frequencies). \n\\end{center}\n\\end{itemize}\n\\item {\\em NbrScale} : int, optional input parameter specifying the number of scales (default is 4).\n\\item {\\em Lmax} : int, optional input parameter specifying the maximum multipole number $l$ in the spherical harmonics decomposition \n(default is $3\\times \\textrm{nside}$, should be between $2\\times \\textrm{nside}$ and $4\\times \\textrm{nside}$).\n\\item {\\em DifInSH} : Input keyword parameter. If set, the wavelet coefficients are computed as the difference between two resolutions in the spherical harmonics representation. \nOtherwise, the wavelet coefficients are computed as the difference between two resolutions in direct space.\n\\item {\\em MeyerWave} : If set, use Meyer wavelets and set the keyword DifInSH.\n\\end{itemize}\n\n\\subsubsection*{Example:} \n\\begin{itemize}\n\\item mrsp\\_wttrans, Imag, Output, NbrScale=5 \\\\\nCompute the isotropic wavelet transform of the map Imag with five scales. The result is stored in Output.\n\\end{itemize}\n\n\n\n\\subsection{Undecimated Isotropic Wavelet Reconstruction of a polarized spherical map : mrsp\\_wtrec}\n\\index{IDL routines!mrsp\\_wtrec}\n\\index{polar!undecimated wavelet reconstruction of polarized image}\nReconstructs a polarized maps on the sphere in TQU scheme using the Healpix representation (nested data representation) \nfrom its wavelet coefficients obtained with the undecimated isotropic wavelet transform on the sphere, described right above.\n{\\bf\n\\begin{center}\n     USAGE: mrsp\\_wtrec, Trans, Rec, filter=filter\n\\end{center}}\nwhere\n\\begin{itemize}\n\\item {\\em Trans}: Input IDL structures with the following fields:  \n\\begin{itemize}\n\\item {\\em NbrScale} : int, number of scales.\n\\item {\\em nside} : int, Healpix nside parameter.\n\\item {\\em lmax} : int, maximum l value in the Spherical Harmonic Space.\n\\item {\\em npix} : long, number of pixels of the input image.\n\\item {\\em MeyerWave} : int, 1 if the keyword MeyerWave used, otherwise 0\n\\item {\\em DifInSH} : int, 1 if the keyword DifInSH used, otherwise 0\n\\item {\\em Coef} : fltarr[npix,NbrScale,3] wavelet transform of the data. Coef[*,*,0] = wavelet transform on T, Coef[*,*,1] = wavelet transform on E, Coef[*,*,2] = wavelet transform on B\n\\begin{center}\nCoef[*,0,*] = wavelet coefficients of the finest scale (highest frequencies).\\\\\nCoef[*,NbrScale-1,*] = coarsest scale (lowest frequencies). \n\\end{center}\n\\end{itemize}\n\\item {\\em Rec} : Output 3D IDL array of healpix polarized map in TQU scheme. Reconstructed image from the wavelet coefficients. \n\\item {\\em filter} : Input keyword parameter. Use filters for the reconstructions. If this keyword is not set, the reconstructed image is obtained \nby a simple addition of all wavelet scales. Automaticaly applied if keyword MeyerWave or DifInSH were set at the wavelet decomposition.\n\\end{itemize}\n\n\\subsubsection*{Examples:} \n\\begin{itemize}\n\\item mrsp\\_wttrans, Imag, Output, NbrScale=5 \\\\\nCompute the isotropic wavelet transform of the map Imag with five scales. The result is stored in Output.\n\\item mrsp\\_wtrec, Output, map \\\\\nReconstruct the map. \n\\end{itemize}\n\n\n\n\n\n\\subsection{Extract a scale from a polar decomposition : mrsp\\_wtget}\n\\index{IDL routines!mrsp\\_wtget}\n\\index{polar!polar wavelet extraction}\nReturn a band of a transform for Healpix polarized map (wavelet, curvelet\\ldots) obtained by the command mrsp\\_trans.\n{\\bf\n\\begin{center}\n     USAGE:  Scale = mrsp\\_wtget( Trans, Component, ScaleNumber, BandNumber=BandNumber, NormVal=NormVal )\n\\end{center}}\nwhere\n\\begin{itemize}\n\\item {\\em Trans} : Input IDL structure, see mrsp\\_trans for more details.\n\\item {\\em ScaleNumber} : int, scale number of the band to be extracted. The scale number must be between 0 and Trans.NbrScale-1.\n\\item {\\em Component} : int, choice of the component, 0 is for T, 1 for E and 2 for B.\n\\item {\\em NormVal} : float, optional normalization value of the band (for isotropic wavelet transform).\n\\item {\\em BandNumber} : int, ridgelet band number (for curvelet transform).\n\\item {\\em Scale} : return value IDL array of the band extracted. See more details on the 1D versions of the functions. \nNo band is extracted from Modulus-Phases transforms (return 0). For a E/B decomposition, it will be either the T map, the E map or the B map.\n\\end{itemize}\n\n\n\n\\subsection{Put a scale into a polar decomposition : mrsp\\_wtput}\n\\index{IDL routines!mrsp\\_wtput}\n\\index{polar!polar wavelet insertion}\nPut a band into a transform for Healpix polarized map (wavelet, curvelet\\ldots) obtained by the command mrsp\\_trans.\n{\\bf\n\\begin{center}\n     USAGE:   mrsp\\_wtput, Trans, Scale, Component, ScaleNumber, BandNumber=BandNumber\n\\end{center}}\nwhere\n\\begin{itemize}\n\\item {\\em Trans} : Input IDL structure, see mrsp\\_trans for more details.\n\\item {\\em Scale} : Input IDL array of the band inserted. See more details on the 1D versions of the functions. \nNo band is inserted into Modulus-Phases transforms. For a E/B decomposition, it will be either the T map, the E map or the B map.\n\\item {\\em ScaleNumber} : int, scale number of the band to be extracted. The scale number must be between 0 and Trans.NbrScale-1.\n\\item {\\em Component} : int, choice of the component, 0 is for T, 1 for E and 2 for B.\n\\item {\\em BandNumber} : int, ridgelet band number (for curvelet transform).\n\\end{itemize}\n\n\n\n\\section{Denoising}\n\\subsection{Wavelet filtering of a polarized spherical map : mrsp\\_wtfilter}\n\\index{IDL routines!mrsp\\_wtfilter}\n\\index{polar!polar wavelet filtering}\nWavelet denoising of a polarized image on the sphere using Healpix representation in TQU scheme (nested pixel representation). \nBy default Gaussian noise is considered. If the keyword SigmaNoise is not set, then the noise standard deviation is automatically \nestimated. If the keyword MAD is set, then a correlated Gaussian noise is considered and the noise level at each scale is derived \nfrom the Median Absolution Deviation (MAD) method. If the keyword KillLastScale is set, the coarsest resolution is set to zero. \nThe thresholded wavelet coefficients can be obtained using the keyword Trans. If the input keyword niter is set, then an iterative \nalgorithm is applied and if the pos keyword is also set, then a positivity constraint is added.\n{\\bf\n\\begin{center}\n     USAGE:  mrsp\\_wtfilter, Imag, Filter, NbrScale=NbrScale, NSigma=NSigma, SigmaNoise=SigmaNoise, KillLastScale=KillLastScale, \n     pos=pos, mad=mad, Trans=Trans, niter=niter, FirstScale=FirstScale, Use\\_FdrAll=Use\\_FdrAll, soft=soft, fdr=fdr, lmax=lmax, \n     FilterLast=FilterLast, mask=mask \n\\end{center}}\nwhere\n\\begin{itemize}\n\\item {\\em Imag} : Input 3D IDL array of healpix polarized map in TQU scheme. Input image to be filtered.\n\\item {\\em Filter} : Output 3D IDL array of healpix polarized map in TQU scheme containing the filtered map.\n\\item {\\em NbrScale} : int, number of scales (default is 4).\n\\item {\\em NSigma} : float, level of thresholding (default is 3).\n\\item {\\em SigmaNoise} : float, noise standard deviation. Default is automatically estimated.\n\\item {\\em mad} : scalar, if set the noise level is derived at each scale using the MAD of the wavelet coefficient.\n\\item {\\em KillLastScale} : scalar, if set the last scale is set to zero.\n\\item {\\em niter} : int, number of iterations used in the reconstruction.\n\\item {\\em pos} : scalar, if set the solution is assumed to be positive.\n\\item {\\em FirstScale} : int, consider only scales larger than FirstScale. Default is 1 (i.e. all scales are used).\n\\item {\\em Soft} : scalar, if set use soft thresholding instead of hard thresholding.\n\\item {\\em fdr} : float between 0 (default) and 1 (max, if greater or equal to 1, set to 0.05), used to estimate a threshold level \ninstead of a NSigma threshold, threshold is applied from scale j=FirstScale to the last.\n\\item {\\em Use\\_FdrAll} : same as fdr but applied to all scales.\n\\item {\\em FilterLast} : scalar, if set the last scale is filtered.\n\\item {\\em mask} : IDL array of healpix map, input mask applied.\n\\item {\\em lmax} : int, maximum l value in the Spherical Harmonic Space.\n\\item {\\em Trans} : IDL structure: Thresholded wavelet decomposition of the input image.\n\\end{itemize}\n\n\n\\subsubsection*{Example:} \n\\begin{itemize}\n\\item mrsp\\_wtfilter, Imag, Filter, NbrScale=5, Nsigma=5 \\\\\nWavelet filtering with five scales and a 5 sigma threshold.\n\\end{itemize}\n\n\n\\subsection{Thresholding in polarized wavelet or curvelet space  : mrsp\\_threshold}\n\\index{IDL routines!mrsp\\_threshold}\n\\index{polar!polar curvelet filtering}\n\nThreshold the decomposition coefficients of a polarized healpix map. This routine works with several decompositions (see mrsp\\_trans).\n{\\bf\n\\begin{center}\n     USAGE:  mrsp\\_threshold, Trans, NSigma=Nsigma, Mad=Mad, KillLastScale=KillLastScale\n\\end{center}}\nwhere\nwhere\n\\begin{itemize}\n\\item {\\em Trans} : IDL structures obtained from the {\\em mrsp\\_trans} routine.\n\\item {\\em Nsigma}: Level of thresholding (default is 3)\n\\item {\\em KillLastScale}: if set, the last scale is set to zero\n\\end{itemize}\n\n\\subsubsection*{Examples:} \n Compute the undecimated wavelet transform of a vector field I with five scales (needlet filters).  The result is stored in WT, then wavelet coefficients are threshold at 2 sigma, and the filtered polarized map is reconstructed.\n\\begin{itemize}\n\\item  mrsp\\_trans, I, WT, NbrScale=5, /UWT, /NeedletWave\n\\item  mrsp\\_threshold, WT, NSigma=2\n\\item  mrsp\\_rec, WT, RecPola\n\\end{itemize}\nCompute the curvelet transform of a vector field I with five scales.  The result is stored in C, then curvelet coefficients are threshold at 5 sigma, and the filtered polarized map \nis reconstructed.\n\\begin{itemize}\n\\item  mrsp\\_trans, I, C, NbrScale=5, /Cur\n\\item  mrsp\\_threshold, C, NSigma=5\n\\item  mrsp\\_rec, C, RecPola\n\\end{itemize}\n", "meta": {"hexsha": "1783d11514a1492ddcb4f8a1993e058025c6d621", "size": 28544, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/doc/doc_isap/mrsp_idl.tex", "max_stars_repo_name": "sfarrens/cosmostat", "max_stars_repo_head_hexsha": "a475315cda06dca346095a1e83cb6ad23979acae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/doc/doc_isap/mrsp_idl.tex", "max_issues_repo_name": "sfarrens/cosmostat", "max_issues_repo_head_hexsha": "a475315cda06dca346095a1e83cb6ad23979acae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/doc/doc_isap/mrsp_idl.tex", "max_forks_repo_name": "sfarrens/cosmostat", "max_forks_repo_head_hexsha": "a475315cda06dca346095a1e83cb6ad23979acae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.9714285714, "max_line_length": 228, "alphanum_fraction": 0.7523122197, "num_tokens": 8250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3015069033065496}}
{"text": "\\chapter{Introduction} \\label{ch:introduction}\n\nA type system is a delicate balance between expressivity and well-behavedness.\nMore expressivity allows for more programs to be well typed,\nwhile paradoxically allowing less code to be written,\nbecause some of the onus of ensuring a program is valid is shifted\nfrom the programmer to the process of type checking.\nOn the other hand, too much expressivity can destroy\ndesirable metatheoretical properties of the type system ---\nstrings get be treated as integers, booleans can be called like functions,\nand the language falls to chaos and ruin.\n\nThe balancing act is particularly perilous for type systems\nused by proof assistants for mechanized theorem proving,\nbecause a lack of expressivity can make it too much of a burden to be practically useful,\nwhile it's all to easy to add some convenient, seemingly innocuous feature\nthat turns out to dismantle the logic of the system,\nrendering it unusable for proving.\n\nThis thesis deals with dependent type theory, which is commonly used for theorem proving,\ntogether with sized types, a feature for inductively defined types\nused to increase the expressivity of recursive functions,\nand shows that dependent types can be extended with state-of-the-art sized types\nwithout sacrificing key metatheoretical properties.\n\n\\section{Background}\n\nBefore we begin, I briefly summarize why dependent types are used for theorem proving,\nas well as what sized types have to offer in the context of programming with dependent types.\n\n\\subsection{Theorem proving with dependent types} \\label{tt}\n\nMany contemporary proof assistants are founded on the Curry--Howard correspondence,\nwhere propositions correspond to types,\nproofs of these propositions to terms of those types,\nand proof verification to type checking.\nDifferent type theories correspond to different logical systems;\ndependent type theories, in particular, correspond to predicate logics.\nThe primary feature of dependent type theory is the dependent function type,\nbecause it encodes universal quantification by allowing types to \\emph{depend on} terms:\nthe type $\\funtype{x}{A}{\\app{P}{x}}$ can be interpreted as the statement\n``for all objects $x$ in $A$, $P$ holds of $x$'',\nwith the consequent $\\app{P}{x}$ depending on the term $x$.\nOther logical constructs can be encoded as well, for example:\n\n\\begin{itemize}\n  \\item Falsehood ($\\bot$) as $\\funtype{P}{\\Prop}{P}$,\n    (where $\\Prop$ is the type of all propositions),\n    the statement that \\emph{all} propositions hold;\n  \\item Implication as $\\funtype{\\any}{A}{B}$\n    (or $\\arr*{A}{B}$ for short),\n    where $B$ holds only when given a proof of $A$;\n  \\item Negation as $\\arr*{A}{\\bot}$,\n    or that proving $A$ will yield a falsehood; and\n  \\item Truthhood as $\\funtype{P}{\\Prop}{\\arr*{P}{P}}$\\punctstack{,}%\n    \\footnote{This encoding is slightly simpler than\n    the negation of falsehood $\\arr*{\\bot}{\\bot}$,\n    particularly when written out in full.}\n    which is trivially inhabited by the identity function\n    $\\fun{P}{\\Prop}{\\fun{p}{P}{p}}$;\n\\end{itemize}\nand many other logical connectives such as existential quantification, conjunction, disjunction, and equality.\n\nA key metatheoretical property that a type theory must satisfy\nfor its interpretation as a logical system to be valid is \\emph{consistency}:\nfalsehood cannot be proven.\nIn other words, there must not be any term whose type is $\\funtype{P}{\\Prop}{P}$.\nOtherwise, any proposition would be provable,\nincluding those we know to be obviously untrue,\nsuch as $0 = 1$.\n\nThe two most important components of a formal description of a dependent type theory\nare its typing judgement, whose rules describe when a term has a certain type,\nand its equality judgement(s), whose rules describe when two terms are equal.\nThe latter is relevant in dependent types because they allow determining that,\nfor instance, a proof of \\mbox{$\\app{P}{(1 + 1)}$}\nis in fact also a proof of $\\app{P}{2}$.\nNaturally, equality is sometimes described in terms of reduction judgements,\ngoverned by the rules of computation.\nThis means that, in contrast to nondependent type systems,\nwhether type checking always terminates depends on whether the language is normalizing.\nThe issue gets even more complicated with more complex forms of reduction like recursion.\n\n\\subsection{Recursive programming with sized types} \\label{ss}\n\nInductively defined data and recursive functions on them\nare indispensable tools of programming,\nallowing the expression of a variety of constructs, programs,\nand in the case of dependent types, their properties.\nA crucial restriction on recursive functions\nin proof assistants such as Agda, Coq, Idris, Lean, and more\nis that recursive functions must be \\emph{guarded by destructors}\\index{guardedness}\nand only recur on structurally smaller arguments~\\citep{guard}.\nThis guardedness check is statically done before or during type checking and,\nto vastly simplify, ensures that recursive calls occur only on syntactic subarguments:\nif the original argument is some natural $\\app{\\succ*}{n}$ that is the successor of $n$,\nthen the function recurs only on $n$;\nif it's some cons list $\\app{\\cons*}{\\hd}{\\tl}$\nconsisting of an element and the rest of the list $\\tl$,\nthen it recurs only on $\\tl$; and so on.\n\nAlthough this is usually referred to as a syntactic termination check,\nand termination is essential in ensuring decidability of type checking,\nthe key desired property is rather consistency.\nIndeed, a type theory may be consistent yet nonnormalizing\n(as is the case with an impredicative\\index{impredicativity},\ndefinitionally proof-irrelevant $\\Prop$ universe~\\citep{impred-proof-irrel}),\nbut unrestricted recursion easily proves an inconsistency:\nthe recursive function $f$ defined by $\\fun{P}{\\Prop}{\\app{f}{P}}$,\nfor instance, can be assigned type $\\funtype{P}{\\Prop}{P}$,\nin addition to being nonterminating.\n\nWhile the guardedness check, being based on the elimination principles of inductive types,\nyields terminating functions and a consistent type theory,\nit has known disadvantages:\n\n\\begin{itemize}\n  \\item Calling some other function on a subargument prior to a recursive call is disallowed,\n    even if that function doesn't change the structure of that subargument,\n    because the input of the recursive call is no longer exactly the syntactic subargument.\n    For instance, a recursive function on lists cannot first map over the sublist,\n    even though the usual mapping function doesn't change the length of a list\n    and therefore presents no threat to termination.\n  \\item Some proof assistants (Coq, for one) will inline functions and even unfold recursive functions\n    so that the guardedness check has more information\n    and that more recursive functions pass the check.\n    However, this too has its disadvantages:\n    \\begin{itemize}\n      \\item Programs become nonmodular and noncompositional:\n        not only do recursive functions that require inlining\n        depend on the implementation of inlined functions,\n        they may also depend on their specific implementation details,\n        and even a minor syntactic change otherwise equivalent to the original\n        can break guardedness~\\citep{CIC-hat-minus}.\n      \\item As aptly summarized by \\citet{coqterm},\n        \\begin{quote}\n        \\begin{singlespace}\n        \\textit{{\\rm [\\ldots]} unfold{\\rm [ing]} all the definitions used in the body of the function, do{\\rm [ing]} reductions, e.t.c.\n        {\\rm [\\ldots]} makes typechecking extremely slow at times.\n        Also, the unfoldings can cause the code to bloat by orders of magnitude and become impossible to debug.}\n        \\end{singlespace}\n        \\end{quote}\n    \\end{itemize}\n\\end{itemize}\n\nIn cases where the guardedness check fails on terminating functions,\nthe programmer can refactor the function to recur on a different, related argument,\nsuch as the length of a list in the example above,\nbut this requires additional work and may bloat programs\nwith extra code solely for satisfying the guardedness check\nthat detracts from the programs' original intent.\nAlternatives to the syntactic guardedness check that avoid these issues are type-based checks,\nwhere the type system itself is augmented so that successful type checking\nimmediately guarantees termination and consistency.\n\nThe one this thesis focuses on is \\emph{sized typing}\\punctstack{,}%\n\\footnote{The other common one uses \\emph{guarded types}~\\citep{guarded-types}.}\nwhere inductive types are annotated with size information,\nand constructors construct constructions whose size is larger than that of their subarguments.\nIn short, the notion of a ``smaller'' subargument is encoded within the types,\nno longer requiring syntactic analysis to determine.\nFinally, a recursive function is well typed only if it recurs on an argument\nwhose size is smaller than that of the original argument.\n\nBecause well-typedness is the only required condition,\ncalling some other function before a recursive call is allowed\nas long as that function is \\emph{size preserving}\\index{size preservation}.\nFor the list mapping example above,\nthis means that if the sublist of elements of type $\\tau$ has size $s$,\nthen the mapping function must have type $\\arr*{\\List{\\tau}{s}}{\\List{\\tau}{s}}$.\nNotice that the implementation of the mapping function isn't required,\nmerely its type, restoring modularity and compositionality.\n\nThis thesis then introduces Sizey \\textsc{mc}Type Theory (\\lang),\na sized dependent type theory that I prove to be logically consistent\nand therefore suitable for both recursive programming and theorem proving.\n\n\\section{Overview}\n\nBut what need is there for yet another sized type system?\nSince \\citet{hughes}, there has been a little over two decades' worth of past work on sized types.\n\\citet{flationary} notes that it has been the topic of at least five dissertations.\nThis chapter alone names a dozen different type systems with sized types.\nThere have been many advancements along the way,\nbut none quite satisfactory to close the matter,\nespecially when it comes to dependent types.\n\n\\lang and this thesis as a whole does not aim to resolve\nall of the remaining problems of sized types left open by these past works.\nInstead, the purpose is threefold:\n\n\\begin{itemize}\n  \\item To fill an existing gap in sized dependent type theories.\n    Two modern sized type features are higher-rank and bounded size quantification,\n    and there exist a few dependent type theories with one or the other,\n    but not both, to my knowledge.\n    On the other hand, they are currently in Agda's implementation of sized types.\n    By proving the consistency of \\lang, a novel type theory with these two features,\n    I bring the theoretical state-of-the-art closer to practice. \\\\\n  \\item To demonstrate the viability of using a syntactic model to prove consistency\n    of a sized type theory.\n    Doing so from scratch through a set-theoretic model is notoriously difficult,\n    and often requires sacrifices to and constraints on the type theory;\n    see Sacchini's dissertation~\\citep{CIC-hat-minus} or \\CIChatstar~\\citep{CIC-hat-star},\n    for instance.\n    Instead, a syntactic model relies on the consistency of the language in which I'm modelling,\n    allowing me to focus on only the interesting parts of the sized type theory\n    rather than on consistency as a whole.\n  \\item To reopen the discussion on sized dependent types.\n    Since the discovery of the inconsistency of Agda's sized types~\\citep{infinity},\n    progress appears to have stagnated a little.\n    In \\cref{ch:discussion}, I examine these difficulties as they might apply to \\lang\n    and its interpretation in the syntactic model.\n\\end{itemize}\n\nIn this section I describe and justify the design of\nthe dependent types and the sized types of \\lang,\nexplain how a syntactic model is used to prove its consistency,\nand briefly outline the structure of the proof.\n\n\\subsection{Dependent types}\n\nAs a simple but expressive foundation for dependent types,\nI start with the Generalized Calculus of Constructions (\\GCC)\\index{Calculus of Constructions!Generalized \\textasciitilde} \\citep{GCC-Coquand},\nwhich has the following features:\n\n\\begin{itemize}\n  \\item \\textbf{Dependent function types}, as is standard in the Calculus of Constructions (CC)~\\citep{CoC}\\index{Calculus of Constructions};\n  \\item \\textbf{Definitions}, \\ie locally-named expressions;\n  \\item \\textbf{Universes \\ala Russell}\\index{universes \\ala Russell}, where the types of types are themselves terms\n    (as opposed to universes \\ala Tarski\\index{universes \\ala Tarski}, where their \\emph{encodings} are terms);\n  \\item An \\textbf{impredicative universe}\\index{impredicativity} $\\Prop$ such that function types into types in $\\Prop$\n    are themselves in $\\Prop$;\n  \\item A \\textbf{cumulative hierarchy of universes}\\index{cumulativity} such that $\\Type{i}: \\Type{i+1}$,\n    any term in $\\Type{i}$ is also in $\\Type{j}$ given \\emph{universe levels}\\index{universe level} $i \\leq j$,\n    and there is a subtyping relation\\index{subtyping} on types induced by this inclusion; and\n  \\item \\textbf{Untyped definitional equality} stating when two terms are judgementally equal to one another.\n\\end{itemize}\n\nThese features cover many modern proof assistants.\nTo name a few, in terms of universes,\nCoq and Arend have all of the above;\nLean lacks cumulativity; and\nAgda and \\Fstar lack cumulativity and an impredicative universe.\nOn the other hand, these proof assistants all have some form of\n\\emph{universe level polymorphism},\nbut this is much more complex and largely orthogonal to sized types\nand the syntactic model.\n\nPerhaps the most contentious design decision so far is the use of untyped equality,\nas can be found in Coq, over typed equality, as can be found in Agda.\nWhile typed equality is considered to ``have clearer mathematical semantics''~\\citep{typed-NbE},\nits judgement depends on the typing judgement;\nmeanwhile, since types can depend on terms,\ntyping itself depends on equality to check whether one type can be used in place of another.\nAs we'll see in \\cref{sec:syntactic-model},\nthese mutually-defined judgements would greatly complicate the proofs for the syntactic model,\nso I settle for untyped equality instead.\n\nOn top of \\GCC, I add two inductive definitions featured in Martin--L\\\"of type theory (MLTT)~\\citep{MLTT}\\index{Martin--L\\\"of type theory}:\nthe \\emph{Peano naturals} and \\emph{well-founded trees}\\punctstack{,}%\n\\footnote{The types of well-founded trees are also known as \\emph{W types}.}\naugmented with sizes.\nAs the simplest nontrivial inductive,\nthe naturals make it easy to demonstrate intuitive uses of sized inductives.\nOn the other hand, well-founded trees are an example of \\emph{generalized} inductives,\nwith recursive arguments that are functions that return well-founded trees.\nThey can encode all (nonnested) inductives,\nas well as their induction principles \\citep{whynotW} if there are dependent pair types\nand a \\emph{propositional equality}\\index{propositional equality} type.\nI don't add inductive types in general in their place\nbecause the syntactic baggage that comes with handling the generalization\nobscures the intuition behind sized inductive types and the syntactic model,\nwhile it's easy to see how one \\emph{could} go from the naturals and well-founded trees\nto inductive types in general.\n\n\\subsection{Sized types}\\label{sec:sized-types}\n\nSized types begin with explicit size quantification $\\Funtype{\\alpha}{\\tau}$,\nsize abstraction $\\Fun{\\alpha}{e}$, and size application $\\App{e}{s}$.\nSizes themselves consist of size variables, a \\emph{base size},\nand a \\emph{size successor operator}.\nThis is the standard for size expressions in sized type systems.\nSome augment the size grammar with addition of or scalar multiplication of size variables,\nfor instance, increasing expressivity at the expense of added complexity in size checking.\nTo keep things simple, I don't include these features and stick to successor sizes.\nSize expressions here are \\emph{not} terms,\nand their quantifications, abstractions, and applications\nare syntactically distinct from those of terms,\nsimilar to how, in nondependent polymorphic type systems,\ntypes are distinct from terms.\n\nHaving explicit sizes differs from some most prior sized type systems where,\nextending the type polymorphism analogy,\nthere is only implicit \\emph{rank-1} or\n\\emph{prenex} size quantification:\nsize quantifications never appear inside of a type,\nand in fact all size abstractions and applications are fully inferred.\nExplicit sizes, in contrast, let us express\n\\emph{higher-rank} size quantification,\nwhich allow for more expressiveness:\nfor instance, supposing we have cons lists parametrized over some sized type $\\tau$,\none could write a size-preserving mapping function over a list\nthat leaves the size of its elements untouched.\nThe type of such a function might be\n\n\\vspace{-0.25\\baselineskip}\n$$\\Funtype{\\alpha}{\\arr*{(\\Funtype{\\beta}{\\arr*{\\App{\\tau}{\\beta}}{\\App{\\tau}{\\beta}}})}{\\app{\\List*}{(\\App{\\tau}{\\alpha})}}{\\app{\\List*}{(\\App{\\tau}{\\alpha})}}}.$$\n\nAlong with higher-rank sizes, I also include \\emph{bounded} size quantification $\\Funtype<{\\alpha}{s}{\\tau}$\nand abstraction $\\Fun<{\\alpha}{s}{e}$.\nAn order on sizes is induced by these bound instantiations and the successor operator;\nthis order has nothing to do with subtyping,\nand in particular we do \\emph{not} have subtyping relations between\n$\\N{\\alpha}$ and $\\N{\\sss{\\alpha}}$, for instance.\nFixpoint expressions recur on smaller sizes according to the order,\nsummarized by the below typing rule.\n%\n\\begin{mathpar}\n\\inferrule[]{\n  \\check{\\Phi, \\alpha; \\Gamma, f: \\Funtype<{\\beta}{\\alpha}{\\subst{\\tau}{\\alpha}{\\beta}}}{e}{\\tau}\n}{\n  \\infer{\\Phi; \\Gamma}{\\fix{f}{\\alpha}{\\tau}{e}}{\\Funtype{\\alpha}{\\tau}}\n}\n\\end{mathpar}\n\nBounded sizes were originally introduced to avoid inconsistencies\nfrom pattern-matching on sizes~\\citep{MiniAgda}.\nAlthough \\lang has no pattern-matching mechanism,\nthis style of recursion is more elegant because it corresponds neatly to well-founded induction on sizes,\nand because it does away with complex \\emph{semi-continuity} or approximative \\emph{polarity}\nrequirements on fixpoints' types that would otherwise be needed for consistency.\nIndeed, to \\citet{flationary},\n\n\\begin{quote}\n\\begin{singlespace}\n\\textit{A technical condition like semi-continuity can kill a system\nas a candidate for the foundation of logics and programming\n{\\rm [\\ldots]} Most systems for type-based termination replace semi-continuity by a rough approximation,\ntrading expressivity for simplicity}.\n\\end{singlespace}\n\\end{quote}\n\nIn summary, the sized type features I include are:\n\n\\begin{itemize}[noitemsep]\n  \\item \\textbf{Explicit size} quantification $\\Funtype{\\alpha}{\\tau}$,\n    abstraction $\\Fun{\\alpha}{e}$, and\n    application $\\App{e}{s}$;\n  \\item A \\textbf{simple size grammar} with size variables $\\alpha$, a base size $\\circ$, and successors $\\sss{s}$;\n  \\item \\textbf{Higher-rank sizes}, \\eg $\\arr*{(\\Funtype{\\alpha}{\\tau})}{\\sigma}$;\n  \\item \\textbf{Bounded size} quantification $\\Funtype<{\\alpha}{s}{\\tau}$ and\n  abstraction $\\Fun<{\\alpha}{s}{e}$.\n\\end{itemize}\n\nNotably, these are all features found in Agda's implementation of sized types.\nOn the other hand, \\lang excludes Agda's \\emph{infinite size}\\index{infinite size}\nthat is strictly larger than all sizes,\nsince this property is known to be inconsistent in Agda.\nA demonstration of the inconsistency of a hypothetical infinite size in \\lang\nis given in \\cref{sec:infinity}.\nOn the other hand, the lack of an infinite size prevents\ncertain infinitary constructs from being expressed;\n\\cref{sec:examples:limitations} gives a concrete example.\n\n\\subsection{Syntactic model}\\label{sec:syntactic-model}\n\nTo show that \\lang is consistent and therefore a suitable type theory for proofs,\nI define for it a \\emph{syntactic model}\\index{syntactic model}~\\citep{syntactic-models}.\nThis involves defining a translation from \\lang into some target type theory\nin whose consistency we have more confidence---in this case,\nthe \\emph{Extensional Calculus of Inductive Constructions}\\index{Calculus of Inductive Constructions!Extensional \\textasciitilde}\n(\\CICE)~\\citep{CICE}.\nIt, too, has a cumulative hierarchy of universes \\ala Russell and an impredicative universe,\naugmented with inductive types and \\emph{equality reflection}\\index{equality reflection},\nwhere a definitional equality between terms can be derived from a propositional one between them.\nThe most notable difference from \\lang, aside from these features and sized types,\nis that \\CICE uses a typed, declarative equality rather than an untyped, algorithmic equality\nto better accommodate equality reflection.\nFor concision and to avoid confusion, I henceforth refer to the former as \\emph{equivalence}\\index{equivalence},\nand to the latter as \\emph{conversion}\\index{conversion}.\n\nThis translation from \\lang to \\CICE must be \\emph{type preserving}\\index{type preservation}%\n\\footnote{This terminology comes from compilation;\nin the context of syntactic modelling,\nthis is known as \\emph{soundness} with respect to the translation target.}:\nif some term $e$ is well typed under some environments $\\Phi; \\Gamma$ with some type $\\tau$,\nthen the translated term $\\compile{e}$ must also be well typed\nunder the translated environment $\\compile{\\Phi}, \\compile{\\Gamma}$\nwith the translated type $\\compile{\\tau}$.\nBy the consistency of \\CICE and a type-preserving translation to it,\nwe prove the consistency of \\lang.\n\n\\begin{postulate}[Consistency of \\CICE]\\label{fact:consistency-cice}\nThere exists no term $\\eT$ such that\n\\mbox{$\\type{\\mt}{\\eT}{\\funtypeT{\\PT}{\\PropT}{\\PT}}$}.\n\\end{postulate}\n\n\\begin{theorem}[Consistency of \\lang]\\label{thm:overview:consistency}\nSuppose $\\compile{\\bot} = \\funtypeT{\\PT}{\\PropT}{\\PT}$.\nThen there exists no term $e$ such that \\mbox{$\\type{\\mt \\mathbin{;} \\mt}{e}{\\bot}$}.\n\\end{theorem}\n\\begin{proof}\nSuppose that there were such a term $e$.\nBy the type-preserving translation, we would have that\n$\\type{\\mt}{\\compile{e}}{\\funtypeT{\\PT}{\\PropT}{\\PT}}$ holds.\nHowever, this contradicts \\cref{fact:consistency-cice},\nso there must not be such a term.\n\\end{proof}\n\nWhat remains, then, is to define $\\bot$ and an appropriate translation from \\lang to \\CICE\nsuch that $\\compile{\\bot} = \\funtypeT{\\PT}{\\PropT}{\\PT}$,\nand to show that this translation is type preserving.\nI define my translation by induction on the typing derivations of \\lang\nrather than merely over its syntax,\nensuring that only well-typed terms need to be considered.\n\nType preservation of the translation is proven by induction on not only the typing derivations,\nbut also the derivations of the judgements on which the typing rules depend.\nIn particular, typing depends on subtyping\\index{subtyping} $\\preccurlyeq$,\nwhich in turn depends on \\emph{$\\alpha$-cumulativity}\\index{$\\alpha$-cumulativity}\n$\\sqsubseteq$~\\citep{MetaCoq}\nand on the reflexive, transitive closure of reduction $\\rhd^*$.\nFinally, this closure of reduction depends on the reduction rules $\\rhd$,\nmost of which are defined by substitution.\nBelow are the relevant rules showing these dependencies and an example reduction rule.\nThese judgements will be explained in detail shortly in the next chapter;\nI present them here only to motivate the proof structure.\n%\n\\begin{mathpar}\n\\inferrule[]{\n  \\dots \\\\\\\\\n  \\infer{\\Phi; \\Gamma}{e}{\\sigma} \\\\\\\\\n  \\subtype{\\Phi; \\Gamma}{\\sigma}{\\tau}\n}{\n  \\check{\\Phi; \\Gamma}{e}{\\tau}\n}\n\n\\inferrule[]{\n  \\acum{\\sigma_1}{\\sigma_2} \\\\\\\\\n  \\red*{\\Phi; \\Gamma}{\\tau_1}{\\sigma_1} \\\\\\\\\n  \\red*{\\Phi; \\Gamma}{\\tau_2}{\\sigma_2}\n}{\n  \\subtype{\\Phi; \\Gamma}{\\tau_1}{\\tau_2}\n}\n\n\\inferrule[]{\n  \\red{\\Phi; \\Gamma}{e_1}{e_2}\n}{\n  \\red*{\\Phi; \\Gamma}{e_1}{e_2}\n}\n\n\\inferrule[]{~}{\n  \\red{\\Phi; \\Gamma}{\\app{(\\fun{x}{\\tau}{e})}{e'}}{\\subst{e}{x}{e'}}\n}\n\\end{mathpar}\n\nWe therefore need some lemmas showing that the translation respects\nsubstitution, reduction, the closure of reduction, $\\alpha$-cumulativity, and subtyping\nto prove type preservation.\nIn short, substitution satisfies a \\emph{compositionality}\\index{compositionality} principle,\nreduction of terms are equivalent by the \\CICE equivalence judgement\n$\\defeq{\\GammaT}{\\eT_1}{\\eT_2}{\\tauT}$,\nand $\\alpha$-cumulative terms and subtypes are correspondingly \\CICE subtypes.\nI summarize them here, omitting some hypotheses and sublemmas,\nsolely to outline the proof architecture,\nwhich roughly follows the structure of type-preserving compilation by~\\citet{wjb}.\n\n\\begin{lemma}[Compositionality]\\label{lem:overview:compositionality}\\hfill\n\\begin{enumerate}[noitemsep]\n  \\item $\\compile{\\subst{e}{x}{e'}} = \\subst{\\compile{e}}{x}{\\compile{e'}}$.\n  \\item $\\compile{\\subst{e}{\\alpha}{s}} = \\subst{\\compile{e}}{\\alpha}{\\compile{s}}$\n\\end{enumerate}\n\\end{lemma}\n\n\\begin{proof}\nBy induction on the derivation of $\\type{\\Phi; \\Gamma}{e}{\\tau}$.\n\\end{proof}\n\n\\begin{lemma}[Preservation of reduction]\\label{lem:overview:pres-red}\nIf $\\red{\\Phi; \\Gamma}{e}{e'}$ and\n$\\type{\\compile{\\Phi}\\compile{\\Gamma}}{\\compile{e}}{\\tauT}$\nthen $\\defeq{\\compile{\\Phi}\\compile{\\Gamma}}{\\compile{e}}{\\compile{e'}}{\\tauT}$.\n\\end{lemma}\n\n\\begin{proof}\nBy cases on the derivation of $\\red{\\Phi; \\Gamma}{e}{e'}$,\nusing inversion on the derivation of $\\type{\\compile{\\Phi}\\compile{\\Gamma}}{\\compile{e}}{\\compile{\\tau}}$,\n\\cref{lem:overview:compositionality},\nand an application of equality reflection in the case for reduction of fixpoints.\n\\end{proof}\n\n\\begin{lemma}[Preservation of reflexive, transitive closure of reduction]\\label{lem:overview:pres-red*}\nIf $\\red*{\\Phi; \\Gamma}{e}{e'}$ and\n$\\type{\\compile{\\Phi}\\compile{\\Gamma}}{\\compile{e}}{\\tauT}$\nthen $\\defeq{\\compile{\\Phi}\\compile{\\Gamma}}{\\compile{e}}{\\compile{e'}}{\\tauT}$.\n\\end{lemma}\n\n\\begin{proof}\nBy induction on the derivation of $\\red*{\\Phi; \\Gamma}{e}{e'}$,\nusing \\cref{lem:overview:pres-red},\nsubject reduction of \\lang,\nand subject equivalence of \\CICE.\n\\end{proof}\n\n\\begin{lemma}[Preservation of $\\alpha$-cumulativity]\\label{lem:overview:pres-acum}\nIf $\\acum{\\tau_1}{\\tau_2}$ and\n$\\type{\\compile{\\Phi}\\compile{\\Gamma}}{\\compile{\\tau_i}}{\\UT_i}$\nthen $\\subtype{\\compile{\\Phi}\\compile{\\Gamma}}{\\compile{\\tau_1}}{\\compile{\\tau_2}}$.\n\\end{lemma}\n\n\\begin{proof}\nBy induction on the derivation of $\\acum{\\tau_1}{\\tau_2}$,\nusing inversion on the derivations of $\\type{\\Phi; \\Gamma}{\\tau_i}{U_i}$ and\n$\\type{\\compile{\\Phi}\\compile{\\Gamma}}{\\compile{\\tau_i}}{\\UT_i}$.\n\\end{proof}\n\n\\begin{lemma}[Preservation of subtyping]\\label{lem:overview:pres-subtyping}\nIf $\\subtype{\\Phi; \\Gamma}{\\tau_1}{\\tau_2}$\nand $\\type{\\compile{\\Phi}\\compile{\\Gamma}}{\\compile{\\tau_i}}{\\compile{U}}$\nthen $\\subtype{\\compile{\\Phi}\\compile{\\Gamma}}{\\compile{\\tau_1}}{\\compile{\\tau_2}}$.\n\\end{lemma}\n\n\\begin{proof}\nBy cases on the derivation of $\\subtype{\\Phi; \\Gamma}{\\tau_1}{\\tau_2}$,\nusing \\cref{lem:overview:pres-red*}, \\cref{lem:overview:pres-acum},\nsubject reduction of \\lang,\nand subject equivalence of \\CICE.\n\\end{proof}\n\n\\begin{theorem}[Type preservation]\\label{lem:overview:pres-typing}\\hfill\n\\begin{enumerate}[noitemsep]\n  \\item If $\\wf{\\Phi}{\\Gamma}$ then $\\wf{}{\\compile{\\Phi}\\compile{\\Gamma}}$.\n  \\item If $\\type{\\Phi; \\Gamma}{e}{\\tau}$ then $\\type{\\compile{\\Phi}\\compile{\\Gamma}}{\\compile{e}}{\\compile{\\tau}}$.\n\\end{enumerate}\n\\end{theorem}\n\n\\begin{proof}\nBy mutual induction on the derivations of $\\wf{\\Phi}{\\Gamma}$ and $\\type{\\Phi; \\Gamma}{e}{\\tau}$,\nusing \\cref{lem:overview:pres-subtyping}.\n\\end{proof}\n\nThe most important properties required of \\lang are subject reduction\\index{subject reduction},\nused in \\cref{lem:overview:pres-subtyping},\nand confluence\\index{confluence}, which is used to show that subtyping is transitive,\nwhich in turn is used to prove the inversion principles for the typing judgement.\n\nThis proof structure is possible by virtue of the non-mutuality of the judgements of \\lang\ndue to the use of untyped conversion\\index{conversion} (and hence untyped reduction).\nIf it were instead typed, then it would mutually depend on typing and subtyping as well,\nand proving the above lemmas would require a seven-part mutual induction on the derivations.\n\n\\section{Related Work}\n\nThe history and development of sized types spans over two decades of past work,\nand that of dependent types far more than that.\nI therefore mention here only past work that are directly relevant\nor that I refer to again in later chapters.\n\n\\subsection{Dependent type theories}\n\n\\GCC\\index{Calculus of Constructions!Generalized \\textasciitilde}\nwas originally proposed by \\citet{GCC-Coquand},\nadding a universe hierarchy to CC\\index{Calculus of Constructions} with untyped equality\nand using \\rref{cum} for cumulativity\\index{cumulativity}.\nThe \\emph{Extended Calculus of Constructions}\\index{Calculus of Constructions!Extended \\textasciitilde}\n(ECC) by \\citet{ECC} adds a dependent pair type\nand uses a subtyping relation instead for cumulativity;\n\\rref{untyped-subtype-prop, untyped-subtype-pi} are the most notable subtyping rules.\n\n\\vspace{-\\baselineskip}\n\\begin{mathpar}\n\\inferrule[\\rlabel*{cum}]{\n  \\type{\\Gamma}{e}{\\Type{i}}\n}{\n  \\type{\\Gamma}{e}{\\Type{i+1}}\n}\n\\and\n\\inferrule[\\rlabel{$\\preccurlyeq$-prop}{untyped-subtype-prop}]{~}{\n  \\subtype{\\Gamma}{\\Prop}{\\Type{i}}\n}\n\\and\n\\inferrule[\\rlabel{$\\preccurlyeq$-pi}{untyped-subtype-pi}]{\n  \\Gamma \\vdash \\sigma_1 \\approx \\sigma_2 \\\\\n  \\subtype{\\Gamma, \\annot{x}{\\sigma_2}}{\\tau_1}{\\tau_2}\n}{\n  \\subtype{\\Gamma}{\\funtype{x}{\\sigma_1}{\\tau_1}}{\\funtype{x}{\\sigma_2}{\\tau_2}}\n}\n\\end{mathpar}\n\n\\citet{universes} introduce ways of adding universe polymorphism to \\GCC\nas well as to a version of \\GCC with definitions.\nFor the purposes of this thesis, I use \\GCC to refer to the type theory\nwith subtyping and definitions.\n\nThe \\emph{Calculus of Inductive Constructions}\\index{Calculus of Inductive Constructions} (CIC) \\citep{CIC}\nadds inductive types to CC,\nwhile the \\emph{Predicative Calculus of Inductive Constructions}\\index{Calculus of Inductive Constructions!Predicative \\textasciitilde} (pCIC)\nfurther adds definitions and a cumulative universe hierarchy via subtyping\\punctstack{.}%\n\\footnote{More precisely, pCIC refers to Coq's core CIC with the cumulative universe hierarchy\nand without an \\emph{impredicative $\\Set$} universe from version 8 onwards \\citep[Chapter~4]{Coq-manual}.\nThe Coq Reference Manual from version 8.5 onwards refers to it simply as CIC,\nas do many others, \\eg \\citet{CIC-unifier}.\nI prefer to use the specific name pCIC,\nsince most seem to use CIC to refer to whatever Coq's core calculus happens to be based on at the moment,\nwhich is currently pCuIC.}\n\\citet{pCIC} give a set-theoretic model for a variant of pCIC with typed equality.\nThe \\emph{Predicative Calculus of Cumulative Inductive Constructions}\n\\index{Predicative Calculus of Cumulative Inductive Constructions} (pCuIC) \\citep{pCuIC}\nfurther extends pCIC with additional cumulativity\\index{cumulativity} between inductive types,\nalso providing a set-theoretic model,\nand it serves as the modern core calculus of Coq.\nClosely related is the MetaCoq project~\\citep{MetaCoq}\\index{MetaCoq},\nwhich mechanizes pCuIC and various of its metatheorems within Coq itself,\nwith additional alternate untyped equality and subtyping judgements,\nsince Coq's implementation of definitional equality is untyped.\n\n\\citet{CCE} adds a propositional equality type with\nequality reflection\\index{equality reflection} to \\GCC with \\rref{cum} in \\CCE,\nalthough transitivity of definitional equality only holds for well-typed terms,\nand gives a syntactic model in an extension of CIC.\nFollowing that, \\citet{CICE} improve upon the translation,\nusing ECC with a propositional equality type, typed equality,\nand two extensional axioms,\ntranslating from this type theory with equality reflection (ETT) to one without (ITT).\nThey implement the translation in Template Coq \\citep{TemplateCoq},\nextending it to include inductive types.\n\nIn contrast to these type systems based on CC,\nMLTT\\index{Martin--L\\\"of type theory} is a dependent type theory\nwith a noncumulative universe hierarchy without $\\Prop$,\ntyped equality, and some basic types: the empty type, the unit type,\ndependent pair types, disjoint sum types, and a propositional equality type,\nas well as the types of naturals and well-founded trees as mentioned.\nThey can all be implemented as inductive types in pCIC.\n\nThe source language \\lang and target language \\CICE in this thesis aren't exactly\na single type theory from the literature augmented with sized types.\nIn short, \\lang is based on \\GCC but with MetaCoq's alternate subtyping rules\nand augmented with naturals and well-founded trees,\nwhile \\CICE is based on pCIC with extensionality inspired by ETT.\n\n\\subsection{Sized type systems}\n\nSized dependent type systems date all the way back to \\CCR by \\citet{CCR},\nalthough its sized types are formulated quite differently from ``modern'' sized types.\nThe first sized dependent type theory recognized as such is \\CIChat by \\citet{CIC-hat},\nwhich adds prenex sizes\nand a size inference algorithm to CIC.\nIn the intervening years, several nondependent sized type systems were developed,\nnotably the ML-like type system by \\citet{hughes} (independently of \\CCR),\n\\lambdahat~\\citep{lambda-hat, lambda-hat-diss},\n\\Fhat~\\citep{F-hat}, and\n\\Fhattimes~\\citep{F-hat-times},\nall of which focus on prenex, fully-inferrable sizes.\n\\Fhatomega~\\citep{Abel-diss}, on the other hand,\nhas higher-rank, explicitly-quantified sizes.\nOther sized type systems and more extensive discussions can be found in dissertations by\n\\citet{lambda-hat-diss} and \\citet{Abel-diss}.\n\n\\begin{table}[h]\n\\centering\n\\iffalse\n\\begin{tabular}{l c c c l}\nType system & Explicit sizes? & Higher-rank? & Bounded? & Size algebra \\\\\n\\hline\n\\citet{hughes} & \\crossmark & \\crossmark & \\crossmark & $\\sss{s}, s + s, n \\times s$ \\\\\n\\lambdahat~\\citep{lambda-hat, lambda-hat-diss} & \\crossmark & \\crossmark & \\crossmark & $\\sss{s}$ \\\\\n\\Fhat~\\citep{F-hat} & \\crossmark & \\crossmark & \\crossmark & $\\sss{s}$ \\\\\n\\Fhattimes~\\citep{F-hat-times} & \\crossmark & \\crossmark & \\crossmark & $\\sss{s}, s + s$ \\\\\n\\Fhatomega~\\citep{Abel-diss} & \\checkmark* & \\checkmark* & \\crossmark & $\\sss{s}$ \\\\\n\\Fcopomega~\\citep{F-omega-cop} & \\checkmark* & \\checkmark* & \\checkmark* & $\\sss{s}$ \\\\\n\\end{tabular}\n\\fi\n\n\\begin{tabular}{l c c c c}\nType theory & Explicit sizes? & Higher-rank? & Bounded? & Consistent? \\\\\n\\hline\n\\CIChat~\\citep{CIC-hat} & \\crossmark & \\crossmark & \\crossmark & \\interromark \\\\\n\\CIChatminus~\\citep{CIC-hat-minus-nat, CIC-hat-minus} & \\crossmark & \\crossmark & \\crossmark & \\checkmark* \\\\\n\\CChatomega~\\citep{CC-hat-omega} & \\crossmark & \\crossmark & \\crossmark & \\checkmark* \\\\\n\\CIChatl~\\citep{CIC-hat-l} & \\crossmark & \\crossmark & \\crossmark & \\checkmark* \\\\\n\\CIChatsub~\\citep{CIC-hat-sub} & \\crossmark & \\crossmark & \\checkmark* & \\checkmark* \\\\\n\\CIChatstar~\\citep{CIC-hat-star} & \\crossmark & \\crossmark & \\crossmark & \\interromark \\\\\n\\citet{NbE} & \\checkmark* & \\checkmark* & \\crossmark & \\checkmark* \\\\\nMiniAgda~\\citep{MiniAgda, flationary} & \\checkmark* & \\checkmark* & \\checkmark* & \\crossmark \\\\\n\\textbf{\\lang} & \\checkmark* & \\checkmark* & \\checkmark* & \\checkmark*%\n\\textsuperscript{\\labelcref{foot:CICE-consistency}}\n\\end{tabular}\n\\caption{Sized dependent type theories and their properties}\n\\label{tab:sized-types}\n\\end{table}\n\n\\cref{tab:sized-types} lists the sized dependent type theories that follow \\CIChat,\nalong with the main features I focus on:\nexplicit, higher-rank, bounded size quantification,\nand with whether the type theory has been proven consistent.\nThe type theory of MiniAgda, on which the sized types implemented in Agda are based,\nis the only prior one with all three sized type features,\nbut is known to be inconsistent~\\citep{infinity}.\n(Interestingly, \\Fcopomega~\\citep{F-omega-cop}, which extends System F$_\\omega$ with (co)inductive types and sized types,\nhas all three properties \\emph{and} has been proven to be strongly normalizing.)\nOne of the goals of \\lang, as mentioned, is to fill in this gap\nwith a consistent sized dependent type theory with all of the desired features.\nHowever, it's missing two properties that all of these type theories do have:\ninductive types in the ``correct'' universes\n(as we'll see shortly, the type of naturals and well-founded trees\nare one universe higher than is conventional),\nand the existence of an infinite size.\n\n% TODO: fix manual footnote number\n\\footnotetext[6]{\\label{foot:CICE-consistency} Under the postulate that \\CICE is consistent.}\n\n\\begin{center}\n\\mbox{* * *}\n\\end{center}\n\\vspace*{-0.5\\baselineskip}\n\n\\noindent In the upcoming \\cref{ch:sized-dep-types}, I describe the syntax and judgements of \\lang in detail\nand provide example programs in \\lang that use sized types.\nNext, in \\cref{ch:model} I describe \\CICE and define the translation from \\lang to \\CICE.\nFollowing that, in \\cref{ch:proofs} I prove various necessary metatheoretical properties\nincluding confluence and subject reduction,\nand elaborate on the proof of type preservation and its associated lemmas.\nI conclude in \\cref{ch:discussion}, discussing some of the shortcomings of \\lang,\nnamely the universe levels of the inductive types and\ndecreased expressivity arising from removing the infinite size,\nas well directions for future investigation.", "meta": {"hexsha": "9310089c156eeb05350a94c1a405b4771c0bffd7", "size": 37382, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/introduction.tex", "max_stars_repo_name": "ionathanch/msc-thesis", "max_stars_repo_head_hexsha": "8fe15af8f9b5021dc50bcf96665e0988abf28f3c", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/introduction.tex", "max_issues_repo_name": "ionathanch/msc-thesis", "max_issues_repo_head_hexsha": "8fe15af8f9b5021dc50bcf96665e0988abf28f3c", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/introduction.tex", "max_forks_repo_name": "ionathanch/msc-thesis", "max_forks_repo_head_hexsha": "8fe15af8f9b5021dc50bcf96665e0988abf28f3c", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.3489010989, "max_line_length": 164, "alphanum_fraction": 0.7630945375, "num_tokens": 9717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.30145794895083694}}
{"text": "%---------------------------------------------------------------------\n%  Writeup of the improved search of Run II data for single top quark\n%  production at DZero.\n%  Started: Oct 2006\n%  Authors: The Single Top Working Group\n%---------------------------------------------------------------------\n%\n\\section{Signal Acceptances}\n\\label{signal-acceptances}\n\nThe signal acceptance is defined as:\n$$\n\\cal{A} = \\frac{\\cal{B}}{N_{\\rm initial}}\n\\displaystyle \\sum_{N_{\\rm selected}} \\varepsilon_{\\rm trigger}\n\\varepsilon_{\\rm corrections} \\varepsilon_{\\rm TRF}\n$$\n\\noindent where $\\cal{B}$ is the branching fraction for the MC\nsample, see Table~\\ref{mcstats}, $N_{\\rm initial}$ is the initial\nnumber of events in each MC sample (also shown in\nTable~\\ref{mcstats}), $N_{\\rm selected}$ is the number of MC events\nremaining after selection, and the $\\varepsilon$'s are efficiency\ncorrection factors to account for differences between data and MC from\nthe trigger, particle ID, the $b$-tagging tag-rate functions, and so\nforth (see Section~\\ref{mc-modeling}).\n\nTable~\\ref{acceptances} shows the percentage of each single top quark\nsignal that remain after selection, and after $b$-tagged jets have\nbeen required. We can compare the acceptances obtained in this\nanalysis with the published one~\\cite{run2-d0-plb}. In that analysis,\nwe kept 2.6\\% of the s-channel events before tagging (with 2--4 jets)\nin the electron channel and 2.5\\% in the muon channel. In this\nanalysis, we keep 2.8\\% and 2.2\\% in the electron and muon channels\nrespectively (2--4 jets). In the t-channel, in the published analysis\nwe kept 2.6\\% and 2.4\\% in the electron and muon channels, and now we\nare keeping 2.5\\% and 2.0\\%. After $b$~tagging, before we kept 1.3\\%\nof the electron events and 1.3\\% of the muon events in the s-channel;\nwe now keep 1.8\\% and 1.4\\% respectively. In the t-channel after\n$b$~tagging, we kept before 0.9\\% in each of the electron and muon\nchannels. We now keep 1.2\\% and 0.9\\% of these tagged events.  The\nhigher acceptances now are from the use of the more efficient neural\nnetwork $b$-tagging algorithm, and probably also from the lower\nreconstruction threshold for jets.\n\n% The following is commented out until the comparison is updated to\n% be for their latest results.\n%\n%We can also compare these acceptances to those obtained by CDF in\n%their most recent analysis. For s-channel and t-channel combined,\n%electron and muon channels combined, and events with exactly two jets\n%with one or both $b$~tagged, they keep 1.4\\% of the expected\n%signal. For the same requirements, we also keep 1.4\\% of the expected\n%signal. In addition we have available to analyze the acceptances in\n%the 1, 3, and 4-jets channels, and the untagged 2, 3, and 4-jets\n%channels, which CDF have not yet included in their results.\n\n\\vspace{0.2in}\n\\begin{table}[!h!tbp]\n\\begin{center}\n\\begin{minipage}{6.5in}\n\\begin{ruledtabular}\n\\begin{tabular}{l||ccccc|ccccc}\n\\multicolumn{11}{c}{\\hspace{1in}\\underline{Signal Acceptances}}\\vspace{0.1in} \\\\\n& \\multicolumn{5}{c|}{Electron Channel} & \\multicolumn{5}{c}{Muon Channel} \\\\\n                     & 1 jet & 2 jets & 3 jets & 4 jets & 5+ jets\n                     & 1 jet & 2 jets & 3 jets & 4 jets & 5 jets \\\\\n\\hline\nBefore $b$ tagging   &        &        &        &        &        &        &        &        &        &        \\\\\n~~$tb$               & 0.55\\% & 1.77\\% & 0.83\\% & 0.23\\% & 0.06\\% & 0.33\\% & 1.36\\% & 0.69\\% & 0.19\\% & 0.05\\% \\\\\n~~$tqb$              & 0.52\\% & 1.49\\% & 0.79\\% & 0.25\\% & 0.07\\% & 0.36\\% & 1.17\\% & 0.64\\% & 0.20\\% & 0.05\\% \\\\\nZero $b$-tagged jets &        &        &        &        &        &        &        &        &        &        \\\\\n~~$tb$               & 0.32\\% & 0.65\\% & 0.31\\% & 0.09\\% & 0.02\\% & 0.18\\% & 0.48\\% & 0.25\\% & 0.07\\% & 0.02\\% \\\\\n~~$tqb$              & 0.34\\% & 0.86\\% & 0.41\\% & 0.12\\% & 0.03\\% & 0.23\\% & 0.66\\% & 0.32\\% & 0.09\\% & 0.02\\% \\\\\nOne $b$-tagged jet   &        &        &        &        &        &        &        &        &        &        \\\\\n~~$tb$               & 0.24\\% & 0.82\\% & 0.39\\% & 0.11\\% & 0.03\\% & 0.15\\% & 0.64\\% & 0.32\\% & 0.09\\% & 0.02\\% \\\\\n~~$tqb$              & 0.18\\% & 0.61\\% & 0.34\\% & 0.11\\% & 0.03\\% & 0.13\\% & 0.50\\% & 0.28\\% & 0.09\\% & 0.02\\% \\\\\nTwo $b$-tagged jets  &        &        &        &        &        &        &        &        &        &        \\\\\n~~$tb$               &  ---   & 0.29\\% & 0.14\\% & 0.04\\% & 0.02\\% &  ---   & 0.24\\% & 0.12\\% & 0.03\\% & 0.01\\% \\\\\n~~$tqb$              &  ---   & 0.02\\% & 0.05\\% & 0.02\\% & 0.01\\% &  ---   & 0.01\\% & 0.04\\% & 0.02\\% & 0.01\\%\n\\end{tabular}\n\\end{ruledtabular}\n\\vspace{-0.1in}\n\\caption[acceptances]{Acceptances after selection.}\n\\label{acceptances}\n\\end{minipage}\n\\end{center}\n\\end{table}\n\n", "meta": {"hexsha": "afc7c6595278bfcd9e190e657ec7195059ec4e9b", "size": 4761, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "STnote/acceptancesF06.tex", "max_stars_repo_name": "tgadf/thesis", "max_stars_repo_head_hexsha": "19d4a6bc7f7ac8660fce582322703d50e0d6bd31", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "STnote/acceptancesF06.tex", "max_issues_repo_name": "tgadf/thesis", "max_issues_repo_head_hexsha": "19d4a6bc7f7ac8660fce582322703d50e0d6bd31", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "STnote/acceptancesF06.tex", "max_forks_repo_name": "tgadf/thesis", "max_forks_repo_head_hexsha": "19d4a6bc7f7ac8660fce582322703d50e0d6bd31", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 54.1022727273, "max_line_length": 113, "alphanum_fraction": 0.5639571519, "num_tokens": 1727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.30145794895083694}}
{"text": "%#!pdflatex Naruse_Esurf_2020.tex\r\n\\section{Discussion}\r\n\r\n\\subsection{Performance of inverse model}\r\nThe performance of the inverse model for turbidity currents is evaluated using the test data set, implying that this model can accurately reconstruct the flow characteristics of the turbidity currents from the spatial distribution of the thickness and grain size of turbidites (Figs. \\ref{fig:test_scatter_plot} and \\ref{fig:test_histogram_deviation}). The biases in the values reconstructed from the true input parameters are also very small and thus should not pose a serious issue when the method is applied to actual field data.  \r\n\r\nThe inverse model not only reconstructed the initial conditions of turbidity currents accurately, but also the predicted time evolution of the flow behavior was sufficiently accurately and precisely. In the results of the forward model calculations using the predicted model input parameters that are relatively deviate from the true values (Table \\ref{table:example_time_evolution}), the time evolution of the velocity and the thickness of the flow does not deviate significantly from the results using the true values (Fig. \\ref{fig:test_example_time_evolution}).\r\n\r\nTurbidity currents have a mechanism called the self-acceleration, which is caused by erosion and associated increase of the flow density \\citep{parker1986self,Naruse2007,Sequeiros2009}. Therefore, even slight differences in the initial conditions of the flow can lead to very different results of the time evolution of the flow parameters. However, the results of this test imply that the accuracy of the inverse analysis in this study is enough to prevent to cause such a drastic change in the flow behavior.\r\n\r\nThe relationship between turbidity currents and characteristics of turbidites is nonlinear. Especially when the flow is self-accelerating, a small difference in the initial conditions can result in very different sedimentary characteristics. This means that it is easy to find the initial conditions of the flow by inverse analysis, because even if the characteristics of the deposits are very different, the initial conditions of the flow should not be so different. Thus, the inverse results in this case are expected to be robust even if there are some measurement errors in characteristics of deposits. In other words, there is a tradeoff between the robustness of the forward and inverse modeling.\r\n\r\nThis property of the inversion can be understood when we consider the opposite case. If the initial conditions of the flow are different but the characteristics of the turbidites are exactly the same, it is impossible to estimate the flow conditions from the turbidites. The inverse analysis of hydraulic conditions is possible because the depositional characteristics are sensitive to conditions of turbidity currents. The self-acceleration of turbidity flow is an extreme example of the sensitivity of turbidites to the flow initial conditions.\r\n\r\n\\subsection{Applicability to field-scale problems}\r\nTo apply this method to outcrops, the extent of the area that should be surveyed to collect data and the interval between outcrops should be determined. The tests with different sizes of sampling windows suggest that the survey region should be located more than 10 km from the proximal region (Fig. \\ref{fig:training_different_number_length}). The loss function (i.e., the MSE of the estimates of the parameters) decreases as the length of the sampling window increases, and the best result is obtained at the 10 km-long window. Regarding the interval of the outcrops, the test results of sampling rates of more than 1.0\\% with interpolation for data at non-sampled grids are not inferior to the full sample. Since the training data used in this study are computed on 5 m-spaced grids, extracting data from these grids with a 1.0\\% probability is equivalent to conducting an inverse analysis from outcrop data that are distributed at 0.5 km intervals on average. Although the RMSEs of the model prediction certainly increase when the sampling rate decreases below 1.0 \\%, the RMSE values does not drastically worsen until 0.5 \\%. Therefore, even if the outcrop spacing is about 1 km, it should be possible to obtain a reasonable estimates of the flow characteristics.\r\n\r\nThese requirements for accurate inversion are attainable in the actual field. For example, \\citet{Hirayama1977} correlated individual turbidites of the Pleistocene Otadai Formation distributed in the Boso Peninsula, Japan, on the basis of the key tuff beds. Their correlation covered a region over 30 km long with 33 outcrops. Thus, the average interval between outcrops was approximately 1 km. \\citet{Amy2006} correlated individual beds in the Miocene Marnoso Arenacea Formation, Italy, using the Contessa MegaBed and an overlying ``columbine'' marker bed as the key beds. Their correlation covers 109 sections of approximately 30 m thick succession and extends over 120 km in a direction parallel to flow. Other studies in various regions (e.g., the Arnott Sandstone in France) also reported the correlation of individual turbidites in similar scale and frequency \\citep{HESSE1974,Tokuhashi1979,Tokuhashi1989,Amy2000,Amy2004}. Furthermore, \\citet{Bartolini1972} surveyed the Western Alboran Basin Plain, Mediterranean Sea, and discovered an individual turbidite on the sea floor at 49 cores over approximately 30 km. The records of cores in similar scale and intervals have also been reported by other studies of the modern submarine fans in different areas \\citep{BORNHOLD1971, Pilkey1980}. In summary, although the method proposed in this study requires fairly high resolution data of turbidite individual beds correlated over a long distance, such conditions in ancient geological records as well as modern seafloor surveys can be achieved.\r\n\r\nBesides these outcrop conditions, measurement errors in the field are another important factor for application. The test results suggest that the proposed inverse model of this study is very robust against random noise; random errors in the measured data have little effect on the results (Fig. \\ref{fig:test_noise}). Therefore, even if localized and small-scale scouring and sedimentation occur due to some processes such as bottom currents after the deposition of a turbidite, results of inverse analysis will not be seriously affected. However, if deposits of multiple events are amalgamated to form a single thick massive sandstone, the hydraulic conditions reconstructed from the bed should be considerably different from the actual conditions. To avoid this situation, it is important to identify the erosional surface inside the bed carefully at the actual outcrop. In addition, it is safer not to analyze massive sandstones that are more than several meters thick, because they are likely to be amalgamated deposits.\r\n\r\nPerhaps the most significant drawback to analyze actual turbidites is the assumption about the topography of the upstream submarine canyon. In this study, we tested doubling the length of the upstream slope and found that the predicted values for the concentration that were different from the original values (Fig. \\ref{fig:test_slope_length}). In case of actual analysis, the upstream topography can be set correctly if the modern submarine fan is analyzed. Regarding ancient turbidites, however, some assumptions about the length and scale of the submarine canyons are necessary without measurements. In this case, it is recommended to set up various lengths of submarine canyons within a reasonable range, and to examine the degree to which these assumptions affect the inverse analysis results carefully. Nevertheless, it is worth noting that the test results were reasonable for velocity (Fig. \\ref{fig:test_slope_length}), even if the assumption about the length of upstream slope was substantially different. This suggests that the inverse model proposed in this study can generally reconstruct the behavior of turbidity currents in sedimentary basins, even if the development process of turbidity currents upstream is different.\r\n\r\n\r\n\\subsection{Comparison with previous methodologies}\r\nIn existing inverse analysis methods of turbidity currents, the difference in depositional characteristics between the outputs of the forward model and the field observation is quantified as the objective function, and the initial and the boundary conditions of the forward model are determined by conducting optimization calculations to minimize the objective function \\cite[e.g.,]{Nakao2017}. This is because models of turbidity currents are generally nonlinear and are difficult to linearize, especially when considering the entrainment of the basal sediment \\citep{parker1986self}. Although the actual computational load depends on the choice of algorithm, this type of optimization calculation generally consists of multiple steps, and each step depends on the results of the previous calculation. Thus, the entire optimization procedure is difficult to parallelize. For instance, the kriging-based surrogate management method \\citep{lesshafft2011towards} or the genetic algorithm \\citep{Nakao2017} have been used to optimize the objective function for inversion of turbidity currents. In these methods, multiple calculations are conducted in each calculation step (generation), and the distribution of the objective function in the parametric space is iteratively estimated. Although the computations within each generation can be parallelized in this kind of algorithms, the next generation's computation depends on the results of the previous generation's computation, and therefore, the entire computation process cannot be parallelized. Thus, if the computational load of the forward model is high, the inverse analysis takes an unrealistic amount of time. \r\n\r\n\\citet{Parkinson2017} applied the adjoint method with the gradient-based optimization algorithm. Although the differentiation of the layer-averaged model by the adjoint method greatly reduces the load of the gradient calculation, this approach still requires an iterative calculation for optimization. Thus, the sediment entrainment process is omitted from their model. Their model does not consider resuspension (entrainment) process of sediment, whereas suspended sand in turbidity currents is maintained by balancing the effects of particle settling and diffusion from the bottom (i.e. entrainment). Their model only considers advection and settling of particles, so that the suspended sediment quickly settles and be lost over short distances at realistic flow thicknesses and concentrations. The only way to transport large amounts of suspended sediment for long distance and to deposit thick turbidites without resuspension is to make the flow extremely thick or to suppose unusually high velocity or concentration. This is the reason for that the extremely thick flow depth (more than 3000 m) was obtained in their results. Their inversion method requires iterations that cannot be parallelized, so that the forward model needs to be simplified for this purpose. In addition, gradient-based optimization tends to have problems with initial value dependency and escaping from local optimal solutions. For this reason, the results of their inverse analysis of turbidites were quite unrealistic. In contrast, we were able to adopt \"full model\" that incorporate the entrainment process of suspended sand into our model without any problems. As a result, our inversion did not produce any anomalous reconstructions even though most of our test data exhibit thickness and grain size distributions similar to realistic turbidites. This strongly suggests the robustness of our inverse model and its applicability to real turbidites.\r\n\r\nAnother potential approach to optimization is the Markov Chain Monte Carlo (MCMC) method, but even with this method, repetition of the forward model calculation is unavoidable, since MCMC usually requires repetition of calculations of objective function, which cannot be parallelized, more than the order of $10^4$ time. The layer-averaged model of unsteady turbidity currents is probably not suitable for the forward models due to their computational load.\r\n\r\nThe approach proposed in this study is obviously superior to existing methods in terms of applicability to the field, as it allows computationally demanding models to be applied as forward models. The general relationship between the bed and the input parameters is learned by NN rather than adjusting the input parameters of the numerical model to reproduce the characteristics of specific individual beds. The objective function used in the training of this NN is not the difference between the features of the sediment, but the precision of the inverse analysis results themselves. The most computationally demanding part of the inverse analysis method proposed here is the generation of the training data for the NN. However, since the computations of the forward models are completely independent of each other, the generation of the training data can be conducted in parallel. Thus, our method enables us to easily prepare a large number of training data by using PC clusters, even for very computationally demanding forward models. In addition, the number of calculations required for training is not as high as other methods, specifically only approximately 3,000. It is also advantageous that the proposed method enables us to perform various tests for robustness or precision of inversion before application to field examples, because the NN outputs results of inverse analysis extremely fast. For these reasons, we consider that this study successfully generated an inverse model using the layer-averaged model for unsteady turbidity currents that can be applied to the field. \r\n\r\n\\subsection{Limitations and future tasks}\r\n\r\nThe inverse model proposed in this study has several limitations. Inevitably, the accuracy of the inverse analysis is governed by the validity of the forward model that generates the training data. The present implementation of the inverse model uses the one dimensional layer-averaged model as the forward model, but this model is likely to be applicable only to sedimentary basins that are laterally constrained or to the inside of the submarine channels. The layer-averaged model of \\citet{parker1986self} used in this study has been widely accepted, but various doubts have been recently raised such as the formulation of entrainment rates of basal sediment \\citep{Dorrell2018} and ambient seawater \\citep{Luchi2018}. The assumption of a lock exchange condition for the occurrence of turbidity currents may not be appropriate in some situations. \r\n\r\nAlthough \\citet{Luchi2018} suggested that the a single layer model may not be sufficient for considering behavior of turbidity currents maintained over long distances, it is expected that such turbidity currents do not leave turbidites and create a bypassing zone. Otherwise, the concentration in the lower layers of turbidity currents decrease, and therefore the currents stop within a relatively short distance. Thus, a two-layer model of turbidity currents is not always necessary for inversion of bed-scale turbidites. However, modeling of continuos sustained turbidity currents is necessary for inverse analysis of the development of submarine fans and channel-levee systems in a larger scale. \r\n\r\nIt is relatively easy to solve these problems described above. Without changing the framework of the proposed method, we can adapt to any situation by changing the forward model to generate the training data. For processes such as sediment transport, it is easy to revise the model to incorporate the state-of-the-art knowledge. By adopting computationally demanding models, inverse analysis using 2-D and 3-D forward models may be possible. In Future research, these issues should be addressed, and the methodology to actual field examples should be applied.\r\n\r\nThe analysis of ancient turbidites is an important issue in the future. However, even if ancient turbidites are analyzed, it is not possible to verify that the results obtained are correct, because the hydraulic conditions for ancient turbidity currents are unknown. Another way to verify the validity of the method is to reconstruct the hydraulic conditions of experimental turbidity currents from the turbidites deposited in the flume, and compare them with the measured values. The turbidity currents measured in the modern submarine canyons and their deposits would be another candidate to be used for the model verification.\r\n", "meta": {"hexsha": "483fd35fdc1ee7b8c8574b9c4a978f8723cf3408", "size": 16630, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/discussion.tex", "max_stars_repo_name": "narusehajime/nninv1d", "max_stars_repo_head_hexsha": "697743346c7e24a8f06d676e2e9f3330aee93afe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tex/discussion.tex", "max_issues_repo_name": "narusehajime/nninv1d", "max_issues_repo_head_hexsha": "697743346c7e24a8f06d676e2e9f3330aee93afe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/discussion.tex", "max_forks_repo_name": "narusehajime/nninv1d", "max_forks_repo_head_hexsha": "697743346c7e24a8f06d676e2e9f3330aee93afe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 386.7441860465, "max_line_length": 1932, "alphanum_fraction": 0.8254960914, "num_tokens": 3210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5888891451980404, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.30134435392787945}}
{"text": "\\documentclass[a4paper,11pt]{article}\n%\\documentclass[a4paper,11pt]{scrartcl}\n\n\n\n\\input{../preambles/preamble}\n\\input{../preambles/unicode}\n\n\\setmainlanguage{english}\n\\setotherlanguages{german,greek,russian}\n\n\\input{../preambles/math-single}\n\\input{../preambles/math-brac}\n\\input{../preambles/math-thm}\n\\input{../preambles/phys-chem}\n\n\\setromanfont[Mapping=tex-text]{Linux Libertine O}\n% \\setsansfont[Mapping=tex-text]{DejaVu Sans}\n% \\setmonofont[Mapping=tex-text]{DejaVu Sans Mono}\n\n\\usepackage[style=authoryear-icomp,\n\t\t\tbackend=biber]{biblatex}\n\\addbibresource{../singular-dynamics.bib}\n\n\\title{Notes on Lagrangian Singular Dynamics}\n\\author{Yi-Fan Wang (王\\ 一帆)}\n%\\date{}\n\n\\begin{document}\n\\maketitle\n\n\\section{Classical formalism}\n\nLagrangian with velocity\n\\begin{equation}\nL^\\text{v} \\coloneqq \\fat{L}{\\dot{q} = v}\n\\end{equation}\nEquations of motion\n\\begin{equation}\n\\sum_j M_{ij}\\dot{v}_j = K^\\text{v}_i,\\quad\n\\dot{q}_i = v_i.\n\\end{equation}\nwhere\n\\begin{equation}\n\\rfun{M_{ij}}{q,v} \\coloneqq \\frpa{^2 L}{v_i\\,\\partial v_j}.\n\\end{equation}\n\n% Adding\n% \\begin{equation}\n% p_i \\coloneqq \\frpa{L^\\text{v}}{v_i}.% \\eqqcolon \\rfun{\\ol{p}_i}{q,v}.\n% \\end{equation}\n% Variation of\n% \\begin{equation}\n% \\sfun{S}{q, p; v} \\coloneqq \\int\\dd t\\,\\sbr{L^\\text{v} + \\sum_i \n% p_i\\rbr{\\dot{q}_i - v_i}}.\n% \\end{equation}\n% gives the \\emph{extended Euler--Lagrange equations}\n% \\begin{equation}\n% \\dot{q}_i = v_i,\\quad\n% \\dot{p}_i = \\frpa{L^\\text{v}}{q_i},\\quad\n% p_i = \\frpa{L^\\text{v}}{v_i}.\n% \\end{equation}\n% \n% Extended Hamiltonian\n% \\begin{equation}\n% \\rfun{H^\\text{v}}{q, p; v} \\coloneqq \\sum_i p_i v_i - L^\\text{v}.\n% \\end{equation}\n% Identities\n% \\begin{equation}\n% \\frpa{H^\\text{v}}{q_i} \\equiv - \\frpa{L^\\text{v}}{q_i},\\quad\n% \\frpa{H^\\text{v}}{p_i} \\equiv v_i,\\quad\n% \\frpa{H^\\text{v}}{v_i} \\equiv p_i - \\frpa{L^\\text{v}}{v_i}.\n% \\end{equation}\n% Variation of\n% \\begin{equation}\n% \\sfun{S}{q, p; v} \\coloneqq \\int\\dd t\\,\\sbr{\\sum_i \n% p_i \\dot{q}_i - H^\\text{v}}\n% \\end{equation}\n% gives the \\emph{extended canonical equations}\n% \\begin{equation}\n% \\dot{q}_i = \\sbr{q_i, H^\\text{v}}_\\text{P},\\quad\n% \\dot{p}_i = \\sbr{p_i, H^\\text{v}}_\\text{P},\\quad\n% \\frpa{H^\\text{v}}{v_i} = 0,\n% \\end{equation}\n% where the \\emph{Poisson bracket} is defined as\n% \\begin{equation}\n% \\sbr{f^\\text{v}, g^\\text{v}}_\\text{P} \\coloneqq \n% \\sum_i\\rbr{\\frpa{f^\\text{v}}{q_i}\\frpa{g^\\text{v}}{p_i} -\n% \\frpa{f^\\text{v}}{p_i}\\frpa{g^\\text{v}}{q_i}}.\n% \\end{equation}\n% \n% $v_a = \\rfun{\\ol{v}_a}{q,p;\\cbr{v_\\alpha}}$ can be solved, $a = 1, 2, \\ldots, \n% r_M$; $v_\\alpha$ \n% cannot be solved, $\\alpha = r_M + 1, \\ldots, n$, where $r_M = \\rank M$.\n% \n% (need to show $v_a = \\rfun{\\ol{v}_a}{q,p_a}$)\n% \n% \\emph{Primary constraints in the standard form}\n% \\begin{equation}\n% \\rfun{\\Phi_\\alpha}{q, p} \\coloneqq\n% \\fat{\\frpa{H^\\text{v}}{v_\\alpha}}{\\cbr{v_\\alpha = \\ol{v}_\\alpha}} \\equiv\n% p_\\alpha - \\rfun{\\ol{p}_\\alpha}{q, \\cbr{p_a}},\n% \\end{equation}\n% where\n% \\begin{equation}\n% \\rfun{\\ol{p}_\\alpha}{q, \\cbr{p_a}} \n% \\coloneqq \\fat{\\frpa{L^\\text{v}}{v_\\alpha}}{\\cbr{v_a = \\ol{v}_a}}.\n% \\end{equation}\n% \n% \n% \\emph{Total Hamiltonian}\n% \\begin{equation}\n% H^\\text{t} \\coloneqq \\fat{H^\\text{v}}{\\cbr{v_a = \\ol{v}_a}} \\equiv\n% \\rfun{H^\\text{v}}{q, p; \\cbr{\\rfun{\\ol{v}^a}{q, p_a; \\cbr{v_\\alpha}}, \n% v_\\alpha}}.\n% \\end{equation}\n% \n% \\emph{Subspace of primary constraints}\n% \\begin{equation}\n% \\Gamma_\\text{P} = \\cbr{ \\rbr{q, p}\\, |\\, \\rfun{\\Phi_\\alpha}{q, p} = 0, \n% \\forall \\alpha}\n% \\end{equation}\n% \n% Since\n% \\begin{equation}\n% \\frpa{H^\\text{t}}{v_\\alpha} =\n% \\fat{\\frpa{H^\\text{v}}{v_\\alpha}}{\\cbr{v_a = \\ol{v}_a}} = \\Phi_\\alpha\n% \\equiv p_\\alpha - \\rfun{\\ol{p}_\\alpha}{q, \\cbr{p_a}},\n% \\end{equation}\n% $H^\\text{t}$ is linear in $v_\\alpha$. One writes\n% \\begin{equation}\n% \\rfun{H^\\text{t}}{q, \\cbr{p_a}; \\cbr{p_\\alpha}, \\cbr{v_\\alpha}} = \\rfun{H}{q, \n% \\cbr{p_a}} + \\sum_\\alpha v_\\alpha \\Phi_\\alpha,\n% \\end{equation}\n% where $H$ is the \\emph{canonical Hamiltonian} or simply \\emph{Hamiltonian}.\n% \n% \\paragraph{Proposition}\n% $H$ is independent of $\\cbr{p_\\alpha}$.\n% \n% \\paragraph{Proposition}\n% Canonical equations with primary constraints\n% \\begin{align}\n% \\dot{q}_i &= \\sbr{q_i, H}_\\text{P} + \\sum_\\beta v_\\beta \n% \\sbr{q_i, \\phi_\\beta}_\\text{P},\n% \\label{eq:q-i-primary}\\\\\n% \\dot{p}_i &= \\sbr{p_i, H}_\\text{P} + \\sum_\\beta v_\\beta \n% \\sbr{p_i, \\phi_\\beta}_\\text{P}, \\\\\n% \\rfun{\\Phi_\\alpha}{q, p} &= 0,\n% \\end{align}\n% where $v_\\beta$'s are undetermined. Note that \\cref{eq:q-i-primary} for $i = \n% \\alpha$ holds identically: $\\dot{q}_\\alpha = \\dot{q}_\\alpha$.\n% \n% Weak equality: $f_1 \\approx f_2$ iff $\\fat{f_1}{\\Gamma_\\text{P}} = \n% \\fat{f_2}{\\Gamma_\\text{P}}$.\n% \n% \\paragraph{Proposition} if $f$ and $g$ are two functions over the phase space \n% $\\Gamma$, and $f \\approx h$, then\n% \\begin{align}\n% \\frpa{}{q_i} \\rbr{f-\\sum_\\beta \\phi_\\beta \\frpa{f}{p_\\beta}} &\\approx \n% \\frpa{}{q_i} \\rbr{h-\\sum_\\beta \\phi_\\beta \\frpa{h}{p_\\beta}}, \\\\\n% \\frpa{}{p_i} \\rbr{f-\\sum_\\beta \\phi_\\beta \\frpa{f}{p_\\beta}} &\\approx \n% \\frpa{}{p_i} \\rbr{h-\\sum_\\beta \\phi_\\beta \\frpa{h}{p_\\beta}}.\n% \\end{align}\n% \n% \\paragraph{Corollary}\n% $\\forall H_1 \\approx H$,\n% \\begin{equation}\n% \\dot{q}_i \\approx \\sbr{q_i, H}_\\text{P},\\qquad\n% \\dot{p}_i \\approx \\sbr{p_i, H}_\\text{P}.\n% \\end{equation}\n% \n% Primary and second constraints $\\phi^{(1,)}_\\mu$, $\\phi^{(2,)}_\\omega$; first \n% and second class constraints $\\phi^{(,1)}_u$, $\\phi^{(,2)}_w$.\n\n\n\n\\section{Examples}\n\n%\\begin{equation}\n%L^\\text{v} = \\frac{1}{2} \\sum_{i,j}\\rfun{W_{ij}}{q} v_i v_j + \\sum_i \n%\\rfun{\\eta_i}{q} \n%v_i - \\rfun{V}{q}.\n%\\end{equation}\n\n%\\begin{equation}\n%p_i = \\frpa{L^\\text{v}}{v_i} = \\sum_{i,j} W_{ij} v_j + \\eta_i.\n%\\end{equation}\n\n%Let\n%\\begin{align}\n%\\sum_j W_{ij} e_j^{(a)} &= \\lambda^{(a)} e_i \\neq 0, \\\\\n%\\sum_j W_{ij} e_j^{(\\alpha)} &= 0.\n%\\end{align}\n\n\\subsection{Toy examples}\n\n\\subsubsection*{Example 0}\n\\cite[sec.\\ 1.2]{Gitman1990}\n\\begin{equation}\nL = \\frac{1}{2}\\rbr{\\dot{x}-y}^2\n\\end{equation}\n\n\n\\subsubsection*{Example 1}\n\\begin{equation}\nL = \\frac{1}{2} \\dot{x}^2 + \\dot{x} y - \\frac{1}{2}\\rbr{x-y}^2.\n\\end{equation}\n\n% One has\n% \\begin{equation}\n% L^\\text{v} = \\frac{1}{2} v_x^2 + v_x y - \\frac{1}{2} \\rbr{x-y}^2,\n% \\end{equation}\n% so that\n% \\begin{equation}\n% p_x = \\frpa{L^\\text{v}}{v_x} = v_x + y, \\qquad p_y = 0,\n% \\end{equation}\n% thus\n% \\begin{equation}\n% \\ol{v}_x = p_x - y.\n% \\end{equation}\n% So that $v_y$ is the primary inexpressible velocity.\n% \n% The extended Hamiltonian reads\n% \\begin{equation}\n% \\rfun{H^\\text{v}}{q, p; v} = v_x p_x + v_y p_y - \\frac{1}{2} v_x^2 - v_x y \n% + \\frac{1}{2}\\rbr{x-y}^2,\n% \\end{equation}\n% whilst the total Hamiltonian is\n% \\begin{equation}\n% \\rfun{H^\\text{t}}{q, p; \\ol{v}_x, v_y} = \\frac{1}{2}\\rbr{p_x - y}^2 + \n% \\frac{1}{2} \\rbr{x-y}^2 + v_y p_y.\n% \\end{equation}\n\n\\subsubsection*{Example 2}\n\n\\begin{equation}\nL = \\frac{1}{2}\\dot{x}^2 + \\dot{x} y + \\frac{1}{2}\\rbr{x-y}^2\n\\end{equation}\n\n% Primary constraint\n% \\begin{equation}\n% p_y = 0;\n% \\end{equation}\n% total Hamiltonian\n% \\begin{equation}\n% H^\\text{t} = \\frac{1}{2}p_x^2 - p_x y - \\frac{1}{2} x^2 + xy + v_y p_y.\n% \\end{equation}\n\n\\subsection*{Example 3}\n\n\\begin{equation}\nL = \\frac{1}{2} \\rbr{\\dot{q}_2 - \\ee^{q_1}}^2 + \\frac{1}{2} \\rbr{\\dot{q}_3 - \nq_2}^2.\n\\end{equation}\n\n\n\n\\subsection{Parametrised systems}\n\n\\subsubsection*{Non-relativistic point particle}\n\n\\cite[sec.\\ 3.1.1]{Kiefer2012}\n\\begin{equation}\n\\sfun{S}{\\rfun{q}{t}} \\coloneqq \\int_{t_0}^{t_1}\\dd t\\,\\rfun{L}{q, \\frde{q}{t}}\n\\end{equation}\n\n\n\n\\subsubsection*{Relativistic charged point particle}\n\n\\cite[sec.\\ 16]{Landau1975},\n\\cite[sec.\\ 3.1.2]{Kiefer2012}\n\\begin{equation}\nS \\coloneqq \\int_\\gamma -m\\,\\dd s + e \\rfun{A_\\mu}{x} \\,\\dd x^\\mu\n\\eqqcolon \\int_{\\tau_0}^{\\tau_1} \\dd \\tau\\, L,\\\\\n\\label{eq:point-charged-action}\n\\end{equation}\nwhere the Lagrangian reads\n\\begin{equation}\nL = -m \\sqrt{-\\eta_{\\mu\\nu} \\dot{x}^\\mu \\dot{x}^\\nu } + q \\dot{x}^\\mu \n\\rfun{A_\\mu}{x}.\n\\end{equation}\n\n\\begin{equation}\nM_{\\mu\\nu} \\coloneqq \\frpa{^2 L}{\\dot{x}^\\mu\\,\\partial \\dot{x}^\\nu} = \nm\\frac{-\\eta_{\\mu\\nu}\\eta_{\\alpha\\beta} + \\eta_{\\mu\\alpha}\\eta_{\\nu\\beta}}% \n{\\rbr{-\\eta_{\\rho\\sigma}\\dot{x}^\\rho \\dot{x}^\\sigma}^{3/2}} \\dot{x}^\\alpha \n\\dot{x}^\\beta,\n\\end{equation}\nwhich has one and only one zero eigenvector\n\\begin{equation}\n\\dot{x}^\\mu M_{\\mu\\nu} = 0.\n\\end{equation}\n\nEuler--Lagrange derivatives\n\\begin{equation}\nE_\\mu = \\rbr{\\frpa{}{x^\\mu}-\\frde{}{\\tau}\\frpa{}{\\dot{x}^\\mu}} L\n\\equiv K_\\mu - M_{\\mu\\nu}\\ddot{x}^\\nu,\n\\label{eq:point-charged-eld}\n\\end{equation}\nwhere\n\\begin{equation}\nK_\\mu \\coloneqq -q F_{\\mu\\nu} \\dot{x}^\\nu,\n\\end{equation}\nand\n\\begin{equation}\nF_{\\mu\\nu} \\coloneqq \\partial_\\mu A_\\nu - \\partial_\\nu A_\\mu.\n\\end{equation}\n\nContracting the zero eigenvector with \\cref{eq:point-charged-eld} yields\n\\begin{equation}\n\\dot{x}^\\mu E_\\mu = \\dot{x}^\\mu K_\\mu - \\dot{x}^\\mu M_{\\mu\\nu} \\ddot{x}^\\nu\n\\equiv 0,\n\\end{equation}\nso that it generates a gauge identity, and no further constraint exists. Thus \nthe system has a symmetry\n\\begin{equation}\n\\dva x^\\mu = \\dot{x}^\\mu \\dva \\lambda.\n\\end{equation}\n\n\\subsubsection*{Relativistic point particle with einbein}\n\n\\cite[sec.\\ 2.1]{Blumenhagen2013}\n\\begin{equation}\nL \\coloneqq \\frac{1}{2} \\rbr{e^{-1}\\eta_{\\mu\\nu}\\dot{x}^\\mu \\dot{x}^\\nu - m^2 e}\n\\label{eq:point-aux-lagrangian}\n\\end{equation}\n\nEuler--Lagrange derivatives\n\\begin{align}\nE_\\mu &\\coloneqq \\rbr{\\frpa{}{x^\\mu}-\\frde{}{\\tau}\\frpa{}{\\dot{x}^\\mu}}L \n= e^{-1}\\eta_{\\mu\\nu} \\rbr{\\frac{\\dot{e}}{e}\\dot{x}^\\nu - \\ddot{x}^\\nu}, \\\\\nE_e &\\coloneqq \\rbr{\\frpa{}{e}-\\frde{}{\\tau}\\frpa{}{\\dot{e}}}L\n= -\\frac{1}{2}\\rbr{\\frac{1}{e^2}\\eta_{\\mu\\nu}\\dot{x}^\\mu\\dot{x}^\\nu + m^2},\n\\end{align}\nand collectively $E^{(0)} = \\begin{pmatrix} E_\\mu & E_e \n\\end{pmatrix}^\\intercal$.\n\n\\begin{equation}\nM^{(0)} \\coloneqq M =\n\\begin{pmatrix}\ne^{-1}\\eta_{\\mu\\nu} & 0^\\mu \\\\\n0^\\nu & 0\n\\end{pmatrix},\n\\end{equation}\nso that the system is singular, with $w^{(0)} = \\rbr{0^\\mu; 1}$.\n\nOne can choose $u^{(0)} = \\rbr{0^\\mu; e^2}$, so that\n\\begin{align}\n\\phi^{(0)} &\\coloneqq u^{(0)}\\cdot E^{(0)} = e^2 E_e \\\\\n&= -\\frac{1}{2}\\rbr{\\eta_{\\mu\\nu}\\dot{x}^\\mu\\dot{x}^\\nu + m^2 e^2},\n\\end{align}\nand thus\n\\begin{align}\nE^{(1)}_1 &\\coloneqq \\dot{\\phi}^{(0)} = e\\rbr{2\\dot{e} E_e + e\\dot{E}_e} \\\\\n&= - m^2 e\\dot{e}-\\eta_{\\mu\\nu}\\dot{x}^\\mu\\ddot{x}^\\nu.\n\\end{align}\nCollectively, $E^{(1)} = \\begin{pmatrix} \\rbr{E^{(0)}}^\\intercal & E^{(1)}_1\n\\end{pmatrix}^\\intercal$.\n\nStraightforwardly,\n\\begin{equation}\nM^{(1)} =\n\\begin{pmatrix}\ne^{-1}\\eta_{\\mu\\nu} & 0^\\mu \\\\\n0^\\nu & 0 \\\\\n\\eta_{\\mu\\nu}\\dot{x}^\\mu & 0\n\\end{pmatrix},\n\\end{equation}\nand the new zero eigenvector $w^{(1)} = \\rbr{e\\dot{x}^\\mu; 0, -1}$.\n\nOne finds that\n\\begin{align}\nw^{(1)} \\cdot E^{(1)} &= e\\dot{x}^\\mu E_\\mu - E^{(1)}_1 =\ne\\rbr{\\dot{x}^\\mu E_\\mu - 2 \\dot{e} E_e - e\\dot{E}_e} \\\\\n&= \\eta_{\\mu\\nu} \\frac{\\dot{e}}{e} \\dot{x}^\\mu \\dot{x}^\\nu  + m^2 e \\dot{e}\n= -2e \\dot{e} E_e,\n\\end{align}\nso that a gauge identity\n\\begin{equation}\nG \\coloneqq \\dot{x}^\\mu E_\\mu - e \\dot{E}_e \\equiv 0\n\\end{equation}\nis obtained.\n\n\\begin{equation}\nG\\epsilon = E_\\mu \\dot{x}^\\mu \\epsilon + E_e \\rbr{\\dot{e} \\epsilon + e \n\\dot{\\epsilon}} - \\frde{}{\\tau}\\rbr{e E_e \\epsilon},\n\\end{equation}\nso that\n\\begin{align}\n\\dva x^\\mu &= \\dot{x}^\\mu \\epsilon, \\\\\n\\dva e &= \\dot{e} \\epsilon + e \\dot{\\epsilon}.\n\\end{align}\n\n\n\n\n\n\n\\subsubsection{Neutral scalar field}\n\\cite[sec.\\ 3.3]{Kiefer2012}\n\n\\subsection{Maxwell--Proca theory}\n\n\\begin{equation}\n\\Ld = -\\frac{1}{4} F_{\\mu\\nu} F^{\\mu\\nu} - \\frac{1}{2}m^2 A_\\mu A^\\mu + A_\\mu \nJ^\\mu\n\\end{equation}\nwhere $m > 0$ corresponds to the Proca theory \\cite[sec.\\ 2.3]{Gitman1990}, and \n$m = 0$ the Maxwell theory \\cite[sec.\\ 3.3.3]{Rothe2010}, \\cite[sec.\\ \n2.4]{Gitman1990}.\n\n\\begin{equation}\n\\Ld \\equiv \\frac{1}{2}\\rbr{-\\eta^{\\alpha\\beta}\\eta^{\\mu\\nu} + \\eta^{\\alpha\\nu} \n\\eta^{\\beta^\\mu}}\\rbr{\\partial_\\mu A_\\alpha}\\rbr{\\partial_\\nu A_\\beta}\n- \\frac{1}{2} m^2 \\eta^{\\alpha\\beta} A_\\alpha A_\\beta + A_\\alpha J^\\alpha\n\\end{equation}\n\n\n\\begin{align}\nE^\\alpha &= \\rbr{\\frpa{}{A_\\alpha} - \\partial_\\mu \\frpa{}{\\rbr{\\partial_\\mu \nA_\\alpha}}}\\Ld \\nonumber \\\\\n&= -m^2 A_\\beta \\eta^{\\alpha\\beta} + J^\\alpha -\\rbr{-\\eta^{\\alpha\\beta} \n\\eta^{\\mu\\nu} + \\eta^{\\alpha\\nu} \\eta^{\\beta^\\mu}}\n\\partial_\\mu \\partial_\\nu A_\\beta.\n\\end{align}\n\n\n\n%\\subsection{Dirac field}\n\n%\\subsection{Gauge theories}\n\n%\\subsubsection{Spinor electrodynamics}\n\n%\\subsubsection{Yang--Mills theory}\n\n%\\subsubsection{Yang--Mills--Higgs theory}\n\n\\subsection{String theories}\n\n\\subsubsection*{Nambu--Gotō action}\n\nGeneralising the kinetic part of \\eqref{eq:point-charged-action}, one has\n\\begin{equation}\nS_\\text{NG} \\coloneqq -T \\int_\\Sigma \\dd A\n\\eqqcolon -T \\int_\\Sigma\\dd^2\\sigma \\Ld,\n\\end{equation}\nwhere the Lagrangian density\n\\begin{equation}\n\\Ld = \\sqrt{-\\Gamma},\\quad\n\\Gamma \\coloneqq \\det \\Gamma_{\\alpha\\beta},\\quad\n\\Gamma_{\\alpha\\beta} \\coloneqq \\frpa{X^\\nu}{\\sigma^\\alpha} \n\\frpa{X_\\nu}{\\sigma^\\alpha}.\n\\end{equation}\n\n\nHistorically \\cite{Nambu1970,Goto1971}; Reference e.g.\\ \n\\cite{Blumenhagen2013}\n\\cite[sec.\\ 3.2]{Kiefer2012}\n\n\\subsubsection*{Polyakov action}\n\nGeneralising \\eqref{eq:point-aux-lagrangian}\n\\begin{equation}\n\\sfun{S_\\text{P}}{X^\\mu, h_{\\alpha\\beta}} = -\\frac{T}{2}\\int_\\Sigma \\Ld,\n\\end{equation}\nwhere\n\\begin{equation}\n\\Ld \\coloneqq \\sqrt{-h} h^{\\alpha\\beta}\\Gamma_{\\alpha\\beta}.\n\\end{equation}\n\n\n\nHistorically \\cite{Brink1976,Deser1976,Polyakov1981};\nReference\n\\cite[sec.\\ 3.2]{Kiefer2012}\n\n\n\\begin{equation}\n\\sqrt{}\n\\end{equation}\n\n\n\n\\subsection{Gravitation theories}\n\n\\subsubsection*{Closed Friedmann universe}\nThis part adapts \\cite[sec.\\ 8.1.2]{Kiefer2012}.\n\nThe total action reads\n\\begin{equation}\nS \\coloneqq S_\\text{EG} + S_\\phi,\n\\end{equation}\nwhere $S_\\text{EG}$ follows \\eqref{eq:action-einstein-gravity}, and\n\\begin{equation}\nS_\\phi \\coloneqq \\int_\\mscrM\\dd^4 x\\, \\sqrt{-g}\\,\n\\rbr{-\\frac{1}{2} g^{\\mu\\nu} \\rbr{\\nabla_\\mu\\phi} \\rbr{\\nabla_\\nu\\phi}\n-m^2\\phi^2}.\n\\end{equation}\n\nAdapting\n\\begin{equation}\n\\dd s^2 = -\\rfun{N^2}{t}\\,\\dd t^2 + \\rfun{a^2}{t}\\,\\dd\\Omega_3^2,\n\\end{equation}\nwhere\n\\begin{equation}\n\\d\\Omega_3^2 = \\dd\\chi^2+\\sin^2\\chi\\,\\rbr{\\dd\\theta^2+\\sin^2\\theta\\,\\dd\\phi^2}.\n\\end{equation}\nOne has\n\\begin{equation}\n\\sqrt{-g} = N a^3 \\sin^2\\chi\\,\\sin\\theta,\\qquad\n\\sqrt{h} = a^3\\sin^2\\chi\\,\\sin\\theta;\n\\end{equation}\nwhereas\n\\begin{equation}\nR = \\frac{6}{N^2}\\rbr{-\\frac{\\dot{N}\\dot{a}}{Na} + \\frac{\\ddot{a}}{a} + \n\\rbr{\\frac{\\dot{a}}{a}}^2} + \\frac{6}{a^2},\\qquad\nK = \\frac{3\\dot{a}}{Na}.\n\\end{equation}\n\n\\begin{equation}\nS_\\text{EG} = \\frac{A_3}{16\\pp\\nG} \\rbr{\\int_{t_1}^{t_2} \\dd t\nNa^3\\rbr{R - 2\\Lambda} - \\sbr{\\frac{6\\dot{a}a^2}{N}}_{t_1}^{t_2}},\n\\end{equation}\nwhere\n\\begin{equation}\nA_3 = \\int \\sin^2\\chi\\,\\sin\\theta\\,\\dd\\chi\\,\\dd\\theta\\,\\dd\\phi = 2\\pp^2.\n\\end{equation}\nThe term proportional to $\\ddot{a}/a$ in the integrand can be integrated by\nparts\n\\begin{equation}\n\\int_{t_1}^{t_2} \\dd t\\,Na^3 \\frac{6}{N^2} \\frac{\\ddot{a}}{a}\n= 6\\rbr{\\sbr{\\frac{\\dot{a}a^2}{N}}_{t_1}^{t_2} - \\int_{t_1}^{t_2}\\dd t\n\\,\\dot{a}\\frde{}{t}\\frac{a^2}{N^2}},\n\\end{equation}\nin which the first term cancels the Gibbons--Hawking--York term. One has\n\\begin{equation}\nS_\\text{EG} = \\frac{3\\pp}{4\\nG}\\int_{t_1}^{t_2} \\dd t\\,\n\\rbr{-\\frac{a}{N}\\dot{a}^2 + N a - \\frac{\\Lambda}{3}N a^3}.\n\\end{equation}\n\nThe matter part of the action reads\n\\begin{equation}\nS_\\phi = \\pp^2 \\int_{t_1}^{t_2}\\dd t\\,\na^3 \\rbr{\\frac{1}{N}\\dot{\\phi}^2 - m^2N\\phi^2}.\n\\end{equation}\n\nOne derives the Euler--Lagrange derivatives\n\\begin{align}\nE_N &= \\frac{3\\pp}{4\\nG}\\rbr{\\frac{a\\dot{a}^2}{N^2}+a-\\frac{\\Lambda a^3}{3}}\n-\\pp^2 a^3 \\rbr{\\frac{\\dot{\\phi}^2}{N^2} - m^2 N \\phi^2} ,\\\\\nE_a &= \\frac{3\\pp}{4\\nG}\\rbr{-\\frac{\\dot{a}^2}{N}+N-\\Lambda Na^2\n+\\frac{2a\\ddot{a}}{N} - \\frac{2a\\dot{a}\\dot{N}}{N^2}}\n+3\\pp^2a^2\\rbr{\\frac{\\dot{\\phi}^2}{N} - m^2 N \\phi^2},\\\\\nE_\\phi &= 2\\pp^2 \\rbr{-m^2 N a^3 \\phi - \\frac{3 a^2 \\dot{a}\\dot{\\phi}}{N}\n-\\frac{a^3\\ddot{\\phi}}{N} + \\frac{a^3\\dot{\\phi}\\dot{N}}{N^2}},\n\\end{align}\nand the primary mass matrix reads\n\\begin{equation}\n\\mbfM^{(0)} = \\begin{pmatrix}\n0 & 0 & 0 \\\\ 0 & -\\frac{3\\pp}{2\\nG}\\frac{a}{N} & 0 \\\\\n0 & 0 & 2\\pp^2\\frac{a^3}{N},\n\\end{pmatrix}\n\\end{equation}\nso that the system is singular, with $w^{(0)} = \\begin{pmatrix}\n1 & 0 & 0\\end{pmatrix} \\eqqcolon u^{(0)}$.\n\nTherefore, the only primary constraint\n\\begin{equation}\n\\phi^{(0)} \\coloneqq u^{(0)}\\cdot E^{(0)} = E_N,\n\\end{equation}\nand\n\\begin{align}\nE^{(1)} &\\coloneqq \\dot{\\phi}^{(0)} = \\dot{E}_N \\\\\n&= \\frac{3\\pp}{4\\nG}\\dot{a} \n\\rbr{\\frac{\\dot{a}^2}{N^2}+2\\frac{a\\ddot{a}}{N^2} \n-\\frac{2a\\dot{a}\\dot{N}}{N^3}+1-\\Lambda a^2}\\nonumber \\\\\n&- \\pp^2 a^2\n\\rbr{3\\frac{\\dot{a}\\dot{\\phi}^2}{N^2} +2\\frac{a\\dot{\\phi}\\ddot{\\phi}}{N^2}\n-2\\frac{a\\dot{N}\\dot{\\phi}^2}{N^3}-m^2\\phi\n\\rbr{3N\\phi\\dot{a}+a\\phi\\dot{N}+2aN\\dot{\\phi}}}.\n\\end{align}\nThe secondary mass matrix\n\\begin{equation}\n\\mbfM^{(1)} = \\begin{pmatrix}\n0 & 0 & 0 \\\\ 0 & -\\frac{3\\pp}{2\\nG}\\frac{a}{N} & 0 \\\\\n0 & 0 & 2\\pp^2\\frac{a^3}{N} \\\\\n0 & -\\frac{3\\pp}{2\\nG}\\frac{a\\dot{a}}{N^2} & 2\\pp^2\\frac{a^3\\dot{\\phi}}{N^2},\n\\end{pmatrix}\n\\end{equation}\nand an additional left zero\n\\begin{equation}\nw^{(1)} \\coloneqq \\begin{pmatrix}\n0 & \\dot{a} & \\dot{\\phi} & -N\n\\end{pmatrix}\n\\eqqcolon v^{(1)}\n\\end{equation}\nis obtained, resulting in a gauge identity\n\\begin{equation}\n0 \\equiv G = \\dot{a} E_a + \\dot{\\phi} E_\\phi - N\\dot{E}_N,\n\\end{equation}\nwhich terminates the algorithm. The gauge transformation reads\n\\begin{equation}\n\\dva N = -\\dot{N}\\epsilon - N\\dot{\\epsilon},\\qquad\n\\dva a = \\dot{a}\\epsilon,\\qquad \\dva \\phi = \\dot{\\phi}\\epsilon.\n\\end{equation}\n\n\n\n\n\n\n\n\\subsubsection{Einstein gravity}\n\n\\begin{equation}\nS_\\text{EG} = S_\\text{EH} + S_\\text{GHY},\n\\label{eq:action-einstein-gravity}\n\\end{equation}\nwhere the Einstein--Hilbert action\n\\begin{equation}\nS_\\text{EH} = \\frac{1}{16\\pp\\nG}\\int_\\mscrM\\dd^4 x\\,\\sqrt{-g}\\, \n\\rbr{R-2\\mitLambda},\n\\end{equation}\nand the Gibbons--Hawking--York action\n\\begin{equation}\nS_\\text{GHY} = -\\frac{1}{8\\pp\\nG}\\int_{\\partial\\mscrM}\\dd^3 x\\,\\sqrt{h}\\, K,\n\\end{equation}\nwhich is named after \\cite{Gibbons1977,York1972} but actually already\nmentioned in \\cite{Einstein1916}. See \\cite{Dyer2009} for a brief review.\n\n\n\n\\printbibliography\n\n\\end{document}\n", "meta": {"hexsha": "60d35ab2ac717e113a984cc0cebf51f35e62ec47", "size": 18056, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "notes/lagrangian/lagrangian.tex", "max_stars_repo_name": "cmp0xff/singular-dynamics", "max_stars_repo_head_hexsha": "3eae6f0462c21894efa73ccdc4e1ecde80f5c623", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notes/lagrangian/lagrangian.tex", "max_issues_repo_name": "cmp0xff/singular-dynamics", "max_issues_repo_head_hexsha": "3eae6f0462c21894efa73ccdc4e1ecde80f5c623", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notes/lagrangian/lagrangian.tex", "max_forks_repo_name": "cmp0xff/singular-dynamics", "max_forks_repo_head_hexsha": "3eae6f0462c21894efa73ccdc4e1ecde80f5c623", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3009404389, "max_line_length": 80, "alphanum_fraction": 0.6280460789, "num_tokens": 8055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.30134434654370224}}
{"text": " %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\chapter{Faceted Embedding Model}\\label{chap:faceted}\nTo further understand the effect of each entity type on the meaning of a word and as an effort to make the dimension of entity embeddings more interpretable, we experiment with creating embeddings with separable parts. By studying these models we gain some insights about the significance of each entity type for vector representations of words and explore if an embedding can be efficiently divided based on these types. In order to create these faceted models, we modify the well-established word- and graph-embedding techniques. In Section~\\ref{sec:faceted_overview}, an overview of the objectives is given. In Section~\\ref{sec:faceted_glove}, the first model based on the GloVe model is proposed. For the faceted GloVe, we experiment with different cost functions, to obtain good performance. In Section~\\ref{sec:faceted_word2vec}, a faceted model based on word2vec is introduced, which takes the edges of a co-occurrence graph as input. Since the graph-based embeddings have the best performance for entity-based embeddings, we experiment with DeepWalk to generate similar embeddings for the faceted model in Section~\\ref{sec:faceted_deepwalk}. For all models, the modifications to the original techniques and training procedures are discussed. \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Overview and Objectives}\\label{sec:faceted_overview}\nWord embedding are in general very ambiguous, it is unknown what each value in the vector representation indicate, if each value corresponds to a distinct attribute of the word or shows to what degree each word belongs to a certain group. We introduce faceted embedding models to address this problems, where we divide the word embedding into components that show a pre-defined attribute of each word, namely its relation to entities with specific type. \n\\begin{figure}\n\\centering \n\\resizebox{0.97\\textwidth}{0.16\\textwidth}{      \n\\input{images/facetted_pipeline.tex}\n}\n\\caption{Pipeline for generating faceted embeddings. The first step is the annotation of the raw text with POS tagging, entity recognition, and disambiguation. A co-occurrence graph is extracted, which is used as input for node embedding or variation of word embedding methods.   }\n\\label{fig:facetted_pipeline}\n\\end{figure}\nSince we are looking at entity-based relations, the corpus should be annotated with named entities. A general pipeline of the approach is shown in Figure~\\ref{fig:facetted_pipeline}, where the entity recognition and disambiguation is applied to the input text that  is used to extract a co-occurrence graph. The graph representation of the corpus is then used by graph-based embeddings or variations of common word embedding techniques to generate a typed embedding, in which instead of capturing the semantic of a word in relation to the entire vocabulary (as normal word embeddings do), we capture the semantic in relation to entities of a specific type. The entity-entity relations are very important for the generation of faceted models, hence, unlike the entity-based embedding in Chapter~\\ref{chap:entity}, applying the normal word embeddings with a word-based window would not capture the relations that these models need to reflect and extraction of a co-occurrence is graph is a mandatory step. This process is repeated for all entity types available for the model, which results in multiple embeddings, each specific to a type. These embeddings can be concatenated to generate a final embedding or used separately based on the use-case scenario. \\\\\nIdeally, a faceted model is able to capture surrounding relations for each type separately in different components of the vector, where the relation to entities that co-occur with a word would be captured by the corresponding component. An illustration of a faceted embedding for the entity \\emph{``Donald Trump''} is shown in Figure~\\ref{fig:faceted_emb}. The center word is the entity \\emph{``Donald Trump''} marked in red and each type is annotated with a different color in the text. Any word that is not an entity or a date is considered a term. Each component is responsible for mapping the entity \\emph{``Donald Trump''} in the neighbourhood of entities of a specific type that co-occur with it. \\\\\n\\begin{figure}\n\\centering \n\\resizebox{0.97\\textwidth}{0.3\\textwidth}{      \n\\input{images/facetted_emb.tex}\n}\n\\caption{Faceted embedding of the entity \\emph{``Donald Trump''} for a short paragraph. Each part of the embedding corresponds to the relation of the center word to that specific type. Each entity type is illustrated with matching color in text and embedding. }\n\\label{fig:faceted_emb}\n\\end{figure} \n\\noindent\nSome of the potential advantages and motivations for analysing each part separately are as follows: \n\\begin{compactitem}\n\\item \\emph{Interpretability of relations:} Since each part of the embedding vector encodes relations to one of the entity types, e.g., the actors part only encodes the actors in the context of a word. Through these separate components, the relations between two words or entities become more interpretable. Any similarity measure to compare two word vectors can be applied to each component separately. Thus, the similarity between words can be broken down into their different attributes. If two entities are closer in location space and farther in actor space, it is possible that they are situated close locally, but are not related to the same people. \\\\\n\n\\item \\emph{Change in meaning:} Exploring and visualizing different components of an embedding over time gives us insights into how that entity has evolved over time, with respect to that component. When applied to a corpus with a temporal aspect, like news articles, faceted models can illustrate how a word changes its meaning in relation to different types. For example, \\emph{``Donald Trump''} is mentioned frequently in location context with \\emph{``Iran''} during the discussion for the nuclear deal, but some time after the abandonment of the deal the topic fades away and \\emph{``Donald Trump''}  is mentioned more often in relation to other countries. This information can be extracted from the location subspace of the word embedding. Consequently, the values for the location part of the embedding will bring the word vector closer to any other entity that is also frequently mentioned with the Iran deal during the nuclear discussions, e.g., \\emph{``Khamenei''} (Iran's supreme leader). Even if \\emph{``Khamenei''} is not directly mentioned with \\emph{``Donald Trump''}, they are mentioned in the same context location-wise, and, therefore, are mapped to points close to each other in the location domain. If embeddings are reconstructed for a time span after the nuclear abandonment, the two mentioned entities should become less similar in location aspect. Although the same experiment can be done on normal embeddings, where all the words are treated equally, the distinguishable components give us additional insights as to what aspect has invoked the change.\\\\\n\n\\item \\emph{Interpretability of evaluation tasks:} Separable parts also play a role in interpretability of evaluation tasks. We experiment with using only a specific component in our evaluations, in Chapter~\\ref{chap:eval}, to find out which type of entity surrounding a word is more influential for a certain task.\\\\\n\n\\item \\emph{Flexible neighbourhood search:} With faceted models, the search for a similar word or entity becomes more flexible. Same as the embedding space, the search space can be divided into various types, where one can look for neighbours in a specific context. The type-specific information can be used in the search, where one can query for entities that are closer to a certain word in the temporal or location aspect. For example, \\emph{``Washington''} as a political person should appear more often with the same actors and has a different actor dimension than the city of \\emph{``Washington DC''}. The standard embedding treats all words equally and therefore, cannot reflect this type of similarity. Since the component for different types are independent and can be combined in an arbitrary way, a combination of different components can tailor search results further and create a type-specific search. \n\\end{compactitem}\nTo achieve this type of embeddings, we define faceted embeddings as word embeddings, where each dimension represents the relation of the embedded word to a specific type of entities surrounding it. Which types are considered during training is arbitrary, but for the purpose of this work, we choose to contain actors, locations, organisations, dates, and terms, since these types are available by the LOAD model. An example of such an embedding vector ($w$) for a corpus containing types of actor (ACT), location (LOC), organisation (ORG), date (DAT) and term (TER) is shown below: \\\\\n\\mathleft\n\\begin{equation}\nw=\\left[ \\underbrace { \\begin{matrix}{ a }_{ 1,1 } ... { a }_{ 1,M } \\end{matrix} } |\\underbrace { \\begin{matrix}{ a }_{ 1,M+1 } ... { a }_{ 1,2M } \\end{matrix} } |\\underbrace { \\begin{matrix}{ a }_{ 1,2M+1 } ... { a }_{ 1,3M } \\end{matrix} } |\\underbrace { \\begin{matrix}{ a }_{ 1,3M+1 } ... { a }_{ 1,4M } \\end{matrix} } |\\underbrace { \\begin{matrix}{ a }_{ 14M+1 } ... { a }_{ 1,5M } \\end{matrix} }  \\right] \n\\label{eq:concat_vec}\n\\end{equation}\n$$ \\quad  \\mathrm{ACT} \\quad  \\qquad  \\mathrm{LOC}\\qquad \\qquad \\mathrm{ORG}\\qquad \\quad \\qquad \\mathrm{DAT}\\qquad \\quad  \\qquad  \\mathrm{TER}\\qquad \\qquad$$\n\\mathcenter\nProvided that the most common dimension for word embeddings are between $100$ to $300$, to maintain the same order of dimension in faceted embeddings, all the different parts have the same dimension but in a lower magnitude ($20$ to $50$). These small embeddings are concatenated to create the final embedding, where each part is independent of the rest and is usually trained separately.\\\\\nWith these independent components, the embeddings stand to be more interpretable. Although a model that divides the embedding space into entity types has not been studied, some work has been done to make the vector representations more interpretable. In the work of Frauqui et al. transformation of word vectors into sparse (and optionally binary) vectors is proposed~\\brackettext{\\cite{DBLP:journals/corr/FaruquiTYDS15}}. Each vector is projected into an over-complete binary vector, where each dimension represents a feature similar to ones used in traditional NLP systems but found automatically during training. However, since their dimensions are binary valued, there is no notion of the extent to which a word participates in a particular dimension. Later, a model based on rotating the word vectors was introduced in order to improve the interpretability.~\\brackettext{\\cite{DBLP:conf/emnlp/ParkBO17}}. Recently, a neural network-based approach to the problem was introduced by using sparse auto-encoders~\\brackettext{\\cite{DBLP:conf/aaai/SubramanianPJBH18}}. Although these works shine some light on the potential meaning of each dimension, they focus purely on terms and share the problems of all term-based models. whereas, we generate embeddings that each part reflects the word relation to entities of a certain type and is based not only on terms but entities of different types. \\\\\nAs explained in Chapter~\\ref{chap:background}, the aim of the word embedding is to reduce the high dimensional space of text and embed words into a meaningful space, where words with similar meaning are mapped to points close to each other. In the case of faceted embeddings, it is as if we are dividing the textual space into all possible entity types, where each subspace contains only entities of a specific type. To put it differently, the space of all words $V$ is represented as $V=A\\bigcup  L\\bigcup  O\\bigcup  D\\bigcup \\overline {N} $, where $A$,$L$,$O$,$D$ are the sets of all actors, locations, organisations and, dates, respectively. The set $ T=\\overline{N}$ denotes all the words which are not a named entity (terms). The goal is to map each word in the vocabulary into all the subspaces, where words that co-occur with the same entities of a specific type are mapped closer together in that particular subspace. Since all the subspaces are independent of each other (e.g., the space of all actors does not have any of the location entities inside it), each embedding learned on the different subspace is also independent. Hence, it is perfectly reasonable that two words are close in one subspace and far in another. The independence of type also allows for arbitrary combination and independent analysis of learned components after training. \\\\\nIn the remainder of this chapter, we aim to introduce faceted models as a general framework for learning embeddings with known types and separable components. To create such embeddings, we propose three approaches, two of which are based on word embedding models and one use the graph embedding techniques. It is worth noting that while we used word embedding methods, the models are modified to take a graph structure as input rather than raw text. Our three models are constructed as follows: \n\\begin{compactenum}\n\\item By modifying the cost function of the GloVe model to train a separate embedding for each entity type on an annotated corpus. Although the original GloVe uses the word co-occurrence matrix as input, we transform the model to use the adjacency matrix of a co-occurrence graph. \n\\item By using a variation of the word2vec model, which supports an arbitrary definition of context for each word to train an embedding for each entity type. \n\\item By Modifying the graph embedding model DeepWalk to generate embeddings based on neighbours of a specific type. \n\\end{compactenum}\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Faceted GloVe}\\label{sec:faceted_glove}\nIn the previous chapter, we indicated that the LOAD edge weight captures the corpus relations similar to the co-occurrence matrix and that meaning components can be extracted from them. In this chapter, we use this knowledge to create faceted embeddings from the weighted adjacency matrix of the LOAD graph. In the first section, the construction of a weighted adjacency matrix is explained followed by the model definition. We denote the faceted GloVe model by $f$GLV, where \\emph{``f''} indicates the faceted model. The proposed model contains two type of cost functions, that are discussed separately in Sections~\\ref{sec:normal_cost} and~\\ref{sec:unified_cost}. \\\\\nThe complete training task can be formulated in four steps: \n \\begin{enumerate}        \n \\item Extraction of co-occurrence matrices for different types, explained in Section~\\ref{sec:adj_matrix}. \n \\item For each type, a GloVe based embedding is learned using either a separate or unified cost function, discussed separately in Section~\\ref{sec:normal_cost} and~\\ref{sec:unified_cost}. \n \\item The context embedding is kept and the focal embedding is either disregarded or added with focal addition, discussed in Section~\\ref{sec:faceted_embeddings}.\n \\item The results of the third step are different embeddings for each type, which can be concatenated to generate the final faceted embedding. \n \\end{enumerate}\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Weighted adjacency matrix}\\label{sec:adj_matrix}\nTo learn embeddings, a weighted adjacency matrix for each type of entity and term is needed (ACT, LOC, TER, ORG, DAT). Matrices are constructed based on the weighted edge list of the co-occurrence graph, where the weights can be co-occurrence counts (identical to the GloVe model) or, any other distance measure defined by the graph. For example, the weighted adjacency matrix for actors contains the edges that have an actor as start nodes and any other type as the end node. Since in this thesis we use undirected co-occurrence graphs, the same edge exists in the opposite direction. For instance, an edge between an actor and a term is repeated twice and will be used once to create the actor matrix and once to create the term matrix. A visual construction of the matrices is shown in Figure~\\ref{fig:co-matrix}, where the entries of the matrices are edge weights between words.  \n\\begin{figure}\n%\\[\\mathrm{ACT}=\n%\\begin{blockarray}{cccccccc}\n% &\\mathrm{TER}_1  & \\color{myblue}{ \\mathrm{ORG}_1 } &  \\mathrm{TER}_2  & \\mathrm{ACT}_1 & \\mathrm{DAT}_1 & \\mathrm{LOC}_1 & ... \\\\\n%\\begin{block}{c(ccccccc)}\n%  \\mathrm{ACT}_1 &m_{00} & \\color{myblue}{ m_{01}}  &  m_{02} & m_{03} & m_{04} &m_{00}& ... \\\\\n%  \\mathrm{ACT}_2 & m_{10} & \\color{myblue}{ m_{11} } &  m_{12} & m_{13} & m_{14} &m_{15}& ... \\\\\n%  \\mathrm{ACT}_3 & m_{20} &  \\color{myblue}{m_{21} } &  m_{22} & m_{23} & m_{24} &m_{25}& ... \\\\\n%  .. & ... &  \\color{myblue}{...}  &  ... & ... & ... &...& ... \\\\\n%\\end{block}\n%\\end{blockarray}\n% \\]\n%\\[\\mathrm{ORG}=\n%\\begin{blockarray}{cccccccc}\n% &\\mathrm{TER}_1  & \\color{myblue}{ \\mathrm{ORG}_1} &  \\mathrm{TER}_2  & \\mathrm{ACT}_1 & \\mathrm{DAT}_1 & \\mathrm{LOC}_1 & ... \\\\\n%\\begin{block}{c(ccccccc)}\n%  \\mathrm{ORG}_1 &m_{00} & \\color{myblue}{ m_{01}}  &  m_{02} & m_{03} & m_{04} &m_{00}& ... \\\\\n%  \\mathrm{ORG}_2 & m_{10} & \\color{myblue}{ m_{11} } &  m_{12} & m_{13} & m_{14} &m_{15}& ... \\\\\n%  \\mathrm{ORG} _3& m_{20} &  \\color{myblue}{m_{21} } &  m_{22} & m_{23} & m_{24} &m_{25}& ... \\\\\n%  .. & ... &  \\color{myblue}{...}  &  ... & ... & ... &...& ... \\\\\n%\\end{block}\n%\\end{blockarray}\n% \\]\n% \\[\\mathrm{DAT}=\n%\\begin{blockarray}{cccccccc}\n% &TER1  & \\color{myblue}{ \\mathrm{ORG}_1} &  \\mathrm{TER}_2  & \\mathrm{ACT}_1 & \\mathrm{DAT}_1 & \\mathrm{LOC}_1 & ... \\\\\n%\\begin{block}{c(ccccccc)}\n%  \\mathrm{DAT}_1 &m_{00} & \\color{myblue}{ m_{01}}  &  m_{02} & m_{03} & m_{04} &m_{00}& ... \\\\\n%  \\mathrm{DAT}_2 & m_{10} & \\color{myblue}{ m_{11} } &  m_{12} & m_{13} & m_{14} &m_{15}& ... \\\\\n%  \\mathrm{DAT}_3 & m_{20} &  \\color{myblue}{m_{21} } &  m_{22} & m_{23} & m_{24} &m_{25}& ... \\\\\n%  .. & ... &  \\color{myblue}{...}  &  ... & ... & ... &...& ... \\\\\n%\\end{block}\n%\\end{blockarray}\n% \\]\n\\centering \n\\resizebox{0.97\\textwidth}{0.26\\textwidth}{      \n\\input{images/adj_matrix.tex}\n}\n \\caption{Faceted weighted adjacency matrix. For each type of entity a weighted adjacency matrix is created, which contains all entities of that type on rows and all words in the vocabulary in columns.}\n \\label{fig:co-matrix}\n\\end{figure}\nThe columns marked in blue in matrices $\\mathrm{ACT}\\in R^{|V_{\\mathrm{ACT}}|\\times |V|}$ , $ORG\\in R^{|V_{\\mathrm{ORG}}|\\times |V|}$  and $\\mathrm{DAT}\\in R^{|V_{\\mathrm{DAT}}|\\times |V|}$ are used to learn the actor, organisation, and date part of the ORG$1$embedding, respectively. The complete vocabulary is divided into words belonging into each entity type. As a result, if $V$ is the complete vocabulary and $A$,$L$ $O$, $D$, and $T$ are the set of all actors, location, organization, dates, and terms in the graph, we will have $V=A \\bigcup L \\bigcup O \\bigcup D \\bigcup T$. The model will learn embeddings for all entities in the row and all entities in the column of the matrix. In case of a symmetric co-occurrence matrix, the model learns the same embedding twice. Nevertheless, in our case the matrices are not symmetric, because the size of the vocabulary for each entity type differs. This asymmetry leads to a definition of a new cost functions that are explained in following sections. \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Cost function of faceted embeddings}\n\\label{sec:faceted_embeddings}\nFor each different adjacency matrix, different embeddings need to be learned. To train all embeddings, two methods are proposed. First, training a network for each type separately and concatenating the outputs to generate the faceted embeddings. Second, train all the embeddings at once in a single network with a unified cost function. We refer to separate and unified cost function as $f$GLV$_{sep}$ and $f$GLV$_{uni}$, respectively.  the second method, despite the compactness, is slower than optimising separate cost functions. It is worth noting that the switching between the training method has no effect on the quality of embeddings, only the training time. For the sake of completeness however, we present both methods. Below we consider some alteration to the cost function of the original GloVe, which are considered to make faceted embedding possible. Below we list the modifications needed for the both cost functions: \n\\begin{figure}\n{\\small \n\\tikzset{every picture/.style={line width=0.75pt}} %set default line width to 0.75pt        \n\\input{images/focal_addtion.tex}\n}\n\\caption{Selectional addition of focal and context embedding in case of actor embeddings. ACT$_1$ is shown as an example, where embeddings in focal and context matrices are combined to make the final embedding. Focal embeddings are only added to the corresponding actors in the context matrix.} \\label{fig:focal_addition}\n\\end{figure}\n\\begin{compactitem}\n\\item \\emph{Asymmetry of context and focal embeddings:} Similar to the GloVe model, embeddings for both context and focal words are learned, but the focal embedding can no longer be naively summed up with the context. Instead, the focal embeddings can either be disregarded completely or added in a new way. For this purpose, we propose \\emph{selectional addition}, where the focal embedding of a certain type is only added to the corresponding embedding in the context. As an example, take the adjacency matrices in Section~\\ref{sec:adj_matrix} as our input, then for the matrix ACT,  focal embedding will learn to encode each row, while the context will encode the columns. The rows of the matrix will represent embeddings of all the actors with respect to the whole vocabulary. We are interested in column embeddings that encode the actor part for all the words in our vocabulary, which is the purpose of this model. Focal embedding also contains information about the whole vocabulary, but only for the focal words (actors), adding back this information in terms of selectional addition is beneficial to the model. The selectional addition adds the focal embedding of a type only to the respective entities of that type in the context matrix. The rest of embeddings remain intact, because a corresponding embedding column for them in the focal matrix does not exist. A visualization of the focal addition for type actor can be seen in Figure~\\ref{fig:focal_addition}.\\\\\n\n\\item \\emph{Final concatenation:} The output of the model is separate embeddings for each entity type. These vectors can later be combined to generate the complete faceted embedding. As the embeddings are independent, the combination can be arbitrary with only the desired components kept. \\\\\n\n\\item \\emph{Weighting function:} The weighting function is the weighting function for the GloVe model. The faceted model is valid with or without the use of a weighting function, but since the weights of a co-occurrence graph are highly unbalanced, without a weighting function, very large weights will overpower the smaller ones and reduce performance. Therefore cutting off the weights at a certain threshold can to some extent balance out this effect. The hyperparameters of the weighting function should be tuned based on the dataset.\\\\\n\n\\item \\emph{Normalization:} In an attempt to boost performance, weights of the graph were normalized using logarithmic normalization. With normalization, we reduce the range of values, in which the weights fluctuate. Moreover, the gradient descent algorithm can converge more smoothly to the functions minimum. Unfortunately, adding the normalization for the GloVe model made the problem ill-conditioned, so the algorithm could not converge to a solution and, therefore, is dismissed. The reason for this could be that the logarithmic normalization  might result in negative values for values between $0$ and $1$. In the cost function, a second $\\log$ is applied to the inputs, and since the $\\log$ of a negative number is undefined, it would result in undefined gradient updates and untrainable weights. Other than log normalization, a linear transformation like \\emph{min-max normalization} was also experimented. Min-max normalization forces all weights to be between $0$ and $1$ and is calculated with Equation~\\ref{eq:minmaxNom}, where $e=(e_1,...,e_n)$ is the set of input weights and $z_i$ are the $i$th normalized outputs. Unfortunately, adding this form of normalization does not improve the results and is also removed from the final model.\n\\begin{equation}\nz_{ i }=\\frac { e_{ i }-min(e) }{ max(e)-min(e) } \n\\label{eq:minmaxNom}\n\\end{equation}\n\n\\item \\emph{Adding $1$ to the logarithm:} The cost function applies a logarithm to the weights. For an edge weight of $1$ the $\\log(1)=0$, but the weight of $1$ should not indicate that there is no relationship between them. Therefore, we tested the model with the addition of $1$ to the $\\log$ of weights, to adjust for this effect. With this change, the cost function of the GloVe model is changed to Equation~\\ref{eq:log_plus}. Although in some cases this change improved the model performance, in other cases it generated poor results and was also removed from the model.\n\\begin{equation}\nJ_e=\\sum _{ j=1 }^{ |V| }{}\\sum _{ i=1 }^{ |V_f| }{ f({ X }_{ ij } } )(w_{ i }^{ T }\\tilde{  w_{ j } } +b_{ i }+\\tilde{  b_{ j } } -(log{ X }_{ ij }+1))^2\n\\label{eq:log_plus}\n\\end{equation}\n\\end{compactitem}\nAll the discussed alterations to the original cost function of the GloVe can be applied to both unified and separate cost function. In the following, we discuss the two cost functions for the faceted GloVe and explain their difference. \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Separate cost functions}\n\\label{sec:normal_cost}\n\nThe general cost function for a single network is the one used for the GloVe model with minor modifications.\nAs noted in the previous section, context and focal embeddings are no longer symmetric, since the size of context vocabulary is different from the focal. \nBy limiting the focal words to a certain type we try to infer the impact of that type on all the words and generate type-specific embeddings. Accordingly, the context embedding in each case reflects these type-specific properties for all words. Biases for focal and context embeddings are longer be symmetric as well. Therefore, the GloVe cost function is re-written to Equation~\\ref{eq:sep_cost}, where $V_f$ is the size of the focal vocabulary. The function $f$ is the weighting function, which is  applied to the edge weight $e_{ij}$ between nodes $i$ and $j$. $w_i$ is focal embedding for the start node and $w_j$ is the context embedding for the end node. \n\\begin{equation}\nJ_e=\\sum _{ j=1 }^{ |V| }{}\\sum _{ i=1 }^{ |V_f| }{ f({ e }_{ ij } } )(w_{ i }^{ \\top }\\tilde{  w_{ j } } +b_{ i }+\\tilde{  b_{ j } } -log{ e }_{ ij })^2\n\\label{eq:sep_cost}\n\\end{equation}\nEquation~\\ref{eq:sep_cost}, minimizes the distance between the dot product of embeddings for start and end node of an edge with log of their edge weight. This cost function has to be minimized separately for each entity type, where the focal vocabulary changes to reflect the type being learned. Thus, the training will contain a separate training phases for each type and a final concatenation. \\\\\nThe Figure~\\ref{fig:separate_cost}, shows visual illustration of training with separate cost function. Two networks are shown as an example, where a single edge affects embeddings of the type associated with the focal (start node), while the edge in the opposite direction affects the embedding associated with the context (end node). Each network is trained separately and a final embedding concatenation of all context embeddings of different types. \n\\begin{figure}\n{\\small \n\\tikzset{every picture/.style={line width=0.75pt}} %set default line width to 0.75pt        \n\\input{images/separate_cost.tex}\n}\n\\caption{Faceted embedding with separate cost functions. Contains training of five different networks (two are shown in the figure) for a single input. The target word is TER$_1$, which is being trained against all actors, organisations, locations, dates and terms. The final embedding is created by concatenating the columns in context embedding matrices that are associated with TER$_1$.} \\label{fig:separate_cost}\n\\end{figure}\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Unified cost function  }\n\\label{sec:unified_cost}\nThe unified cost function is simply the summation of all the separate cost functions in the previous section, where $K$ is the set of all possible types, shown in Equation~\\ref{eq:unified_cost}.\n\\begin{equation}\nJ=\\sum _{ k=1 }^{ |K| }{J_k}=\\sum _{ k=1 }^{ |K| }{}\\sum _{ j=1 }^{ |V| }{}\\sum _{ i=1 }^{ |V_f| }{ f({ e }_{ ij } } )(w_{ i }^{ \\top }\\tilde{  w_{ j } } +b_{ i }+\\tilde{  b_{ j } } -log{ e }_{ ij })^2\n\\label{eq:unified_cost}\n\\end{equation}\nAs a result, all embeddings can be generated with a single network. For a better understanding of the difference between the methods a visual comparison is shown in Figures~\\ref{fig:separate_cost} and~\\ref{fig:unified_cost} for a loss on a single input. Each input is an edge with its corresponding weight, if the input has the starting node of type actor, the rest of the layers related to other types of embeddings will be frozen during training and only the weights for the actor network will be updated. Hence, it is as if all the networks were trained separately.  \\\\\nIn Figure~\\ref{fig:unified_cost}, we show an illustration of training the unified cost function. As a result of unification of the five different cost functions, one network with five times more parameters is trained, where each input edge only affects weights of the network associated with the focal word (start node). Therefore, an edge between an actor and term does not affect location related embeddings. Since edges are undirected, the edge in the opposite direction will be fed as an input to the term network and hence, no information is lost. \n\\begin{figure}\n{\\small \n\\tikzset{every picture/.style={line width=0.75pt}} %set default line width to 0.75pt   \n\\input{images/unified_cost.tex}\n\\caption{Faceted embedding with unified cost function. Training for a single input is shown using only one network. The target word is TER$_1$, which is being trained against all actors, organisations, locations, dates and terms. While training, weights related to actors are only updated if the input edge weight has the start node type of an actor. Meanwhile, rest of the weights related to other entity-types are freezed. The final embedding is created by concatenating columns in context embedding matrices that are associated with TER$_1$.} \\label{fig:unified_cost}\n}\n\\end{figure}\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Vectorized faceted embeddings}\nIn order to speed up the model and use batch gradient descent we need to vectorize the cost function. In the following, we go through the vectorization process for embeddings with separate costs. The same idea can also be applied during the training of the unified cost function.\nIf we consider $W$ as the matrix of all focal embeddings and $\\tilde{ W }$ as the matrix of all context embeddings stacked row-wise, then we can vectorize the model according to Equation~\\ref{eq:vectorized}. \n\\begin{equation}\nJ=(W \\hat{  W }^{ \\top } +B+\\tilde{ B } -log{ X })^{ 2 }\n\\label{eq:vectorized}\n\\end{equation}\n%The original GloVe model contains:\n%\\begin{itemize}\n%\\item $W \\in R^{V \\times M} $ for focal embeddings.\n% \\item $\\tilde{ W }  \\in R^{V \\times M} $ for context embeddings.\n%\\item $B,\\tilde{B} \\in R^{V \\times 1}$ biases for focal and context embeddings. \n%\\item $X \\in R^{V\\times V} $ co-occurrence matrix of the whole vocabulary. \n%\\end{itemize}\nUnlike the original GloVe model, dimensions of  $W$ and $\\tilde{ W } $ are no longer equal as our weighted adjacency matrix is no longer symmetric $X \\in R^{|V_f|\\times |V|} $.  $V_f$ is the set of all focal words, which is defined by the input. If actors are the focal words then $V_f$ is the set of all actors in the vocabulary. Parameters of the model are as follows: \n\\begin{itemize}\n\\item $W \\in R^{|V_f| \\times M} $ for focal embeddings.\n \\item $\\tilde{ W }  \\in R^{|V| \\times M} $ for context embeddings.\n\\item $B,\\tilde{B} \\in R^{|V_f| \\times 1}$ biases for focal and context embeddings.\n\\item $X \\in R^{|V_f|\\times |V|} $ co-occurrence matrix of the whole vocabulary. \n\\end{itemize}\nBiases have to be added row-wise to matrices to preserve the original cost function~\\ref{eq:glove_cost}. Consequently, biases are transformed to column vectors in the size of the focal vocabulary. A comparison between parameter matrices of the original GloVe model ($J_g$) and faceted cost function ($J_f$) is shown below, where the size of the vocabulary is indicated by $|V|=v$ and size of the focal vocabulary by $|V_f|=v_f$.\\\\\n\\[J_{g}=\\stackrel{\\mbox{$W(v\\times M)$ }}{%\n    \\begin{bmatrix}\n    a_{11} & a_{12}  \\cdots  a_{1M} \\\\\n    a_{21} & a_{22}  \\cdots  a_{2M} \\\\\n    \\vdots & \\vdots  \\ddots  \\vdots \\\\\n    a_{v1} & a_{v2}  \\cdots  a_{vM}\n    \\end{bmatrix}%\n  } .\n  \\stackrel{\\mbox{$\\tilde{W}^T(M \\times v)$ }}{%\n    \\begin{bmatrix}\n    a_{11} & a_{12}  \\cdots  a_{1v} \\\\\n    a_{21} & a_{22}  \\cdots  a_{2v} \\\\\n    \\vdots & \\vdots  \\ddots  \\vdots \\\\\n    a_{M1} & a_{M2}  \\cdots  a_{Mv}\n    \\end{bmatrix}%\n  } +\n  \\stackrel{B( v \\times 1)}{%\n    \\begin{bmatrix}\n    e_1 \\\\\n    e_2 \\\\\n    \\vdots \\\\\n    e_{v}\n    \\end{bmatrix}%\n   }\n   +\n  \\stackrel{\\tilde{B |V|\\times 1)}}{%\n    \\begin{bmatrix}\n    e_1 \\\\\n    e_2 \\\\\n    \\vdots \\\\\n    e_{v}\n    \\end{bmatrix}%\n   }-\n   \\stackrel{\\mbox{$logX(v \\times v)$ }}{%\n    \\begin{bmatrix}\n    a_{11} & a_{12}  \\cdots  a_{1v} \\\\\n    a_{21} & a_{22}  \\cdots  a_{2v} \\\\\n    \\vdots & \\vdots  \\ddots  \\vdots \\\\\n    a_{v1} & a_{v2}  \\cdots  a_{vv}\n    \\end{bmatrix}%\n  }\n\\]\n\\\\\n\\[J_{f} =\\stackrel{\\mbox{$W( v_{f}\\times M)$ }}{%\n    \\begin{bmatrix}\n    a_{11} & a_{12}  \\cdots  a_{1M} \\\\\n    a_{21} & a_{22}  \\cdots  a_{2M} \\\\\n    \\vdots & \\vdots  \\ddots  \\vdots \\\\\n    a_{v1} & a_{v2}  \\cdots  a_{v\n_{e}M}\n    \\end{bmatrix}%\n  } .\n  \\stackrel{\\mbox{$\\tilde{W}^T(M \\times |V|)$ }}{%\n    \\begin{bmatrix}\n    a_{11} & a_{12}  \\cdots  a_{1v} \\\\\n    a_{21} & a_{22} \\cdots  a_{2v} \\\\\n    \\vdots & \\vdots \\ddots \\vdots \\\\\n    a_{M1} & a_{M2}  \\cdots  a_{Mv}\n    \\end{bmatrix}%\n  } +\n  \\stackrel{B( v_{f}\\times 1)}{%\n    \\begin{bmatrix}\n    e_1 \\\\\n    e_2 \\\\\n    \\vdots \\\\\n    e_{v_{f}}\n    \\end{bmatrix}%\n   }\n   +\n  \\stackrel{\\tilde{B}(v_{f}\\times 1)}{%\n    \\begin{bmatrix}\n    e_1 \\\\\n    e_2 \\\\\n    \\vdots \\\\\n    e_{v_{f}}\n    \\end{bmatrix}%\n   }-\n   \\stackrel{\\mbox{$logX( v_{f}\\ \\times v)$ }}{%\n    \\begin{bmatrix}\n    a_{11} & a_{12}  \\cdots  a_{1v} \\\\\n    a_{21} & a_{22}  \\cdots  a_{2v} \\\\\n    \\vdots & \\vdots  \\ddots  \\vdots \\\\\n    a_{v1} & a_{v2}  \\cdots  a_{v_{f}v}\n    \\end{bmatrix}%\n  }\n\\]\n\n\\section{Faceted Word2vec}\\label{sec:faceted_word2vec}\nWord embeddings are used as input features in many NLP tasks. Although methods like word2vec capture semantic features well, they often lack task-specific features. Thus, many studies focus on modifying and tweaking the existing methods for certain tasks, such as text classification~\\brackettext{\\cite{DBLP:conf/coling/LiuHGWTL18}}, semantic relation classification~\\brackettext{\\cite{DBLP:conf/conll/HashimotoSMT15}} and dependency parsing~\\brackettext{\\cite{DBLP:conf/acl/BansalGL14}}. Because with faceted embedding we also aim to modify existing methods to match our specific task, we looked at a wide range of litreture on modifications of word embedding methods to match a specific context definition. In $2014$, Levy and Goldberg proposed a method to generalize the skip-gram achitecure of word2vec to include arbitrary contexts and used it to create dependency based embeddings~\\brackettext{\\cite{DBLP:conf/acl/LevyG14}}. We use the idea behind this model to define our own context for the skip-gram model, which allows us to learn separate components of the faceted embedding. In this section, first, we give a brief description of embeddings with arbitrary contexts by Levy and Goldberg. Then, we look at our definition of context and modifications to the original model. Finally, we use this knowledge to generate the algorithm for faceted word2vec. The model proposed by Levy and Goldberg uses the skip-gram architecture, thus, we also generate the faceted word2vec based on skip-gram and do not use the CBOW architecture.\\\\\nFor creating the faceted model using embeddings with arbitrary contexts, we follow these four steps: \n\\begin{enumerate}        \n \\item Extraction of type-specific edge lists from the co-occurrence graph, discussed in Section~\\ref{sec:edges_as_pairs}.\n \\item Training a low dimensional embedding for each type-specific edge list using the method proposed by  Levy and Goldberg, where focal context pairs are edges of the graph~\\brackettext{\\cite{DBLP:conf/acl/LevyG14}}, discussed in Section~\\ref{sec:arbitarty_context}.\n \\item Disregarding focal embeddings and keeping only context embeddings, as it represents the relation of a word to entities of a specific type. \n \\item Concatenating context embedding of all types to create the final embedding. \n \\end{enumerate}\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Embeddings with arbitrary contexts}\\label{sec:arbitarty_context}\nThe general principle behind skip-gram is to bring words that appear in similar contexts in the text, closer in embedding space, where the contexts of a word are the words surrounding it. Therefore, the context vocabulary $C$ is identical to the complete word vocabulary $V$. In other words, the focal words and their context share the same vocabulary. Nonetheless, for embeddings with arbitrary contexts, this restriction is not required. The context does not need to correspond to words and can be defined based on the use-case, which is an important attribute for the faceted model. The negative sampling objective of word2vec, shown in Equation~\\ref{eq:w2v_negative}, assumes a dataset $Q$ of focal and context pairs $(f,c)$ from a large body of text and samples negative examples form $\\overline{Q}$ (the noise distribution). The model assigns a low score to the random negative samples and a high score to the real focal and context pairs. Since the input of the model is word pairs, it can be constructed in an arbitrary way. Levy and Goldberg specifically look at contexts, based on the syntactic relations, where the context is defined by the type of the dependency relation between the head and the modifier. They scan the text once and create focal and context pairs based on specific dependency relations and then use the generated pairs as positive inputs. For each $(f,c) \\in Q$, $n$ samples $(f,c_1),\\dots,(f,c_n)$ are constructed as negative examples, where $c_j$ is drawn according to its unigram distribution raised to the power of $\\frac{3}{4}$~\\brackettext{\\cite{DBLP:conf/acl/LevyG14}}. Their framework is not only limited to dependency relations but also allows for various context definitions~\\brackettext{\\cite{SCHOL:website/Levy2014}}. Following their example, we can define a type-specific context to generate faceted embeddings. We denoted the faceted word2vec model by $f$W2V, where $f$ indicates the faceted model. In the following section, we show how the edges of co-occurrence graphs are used as focal and context pairs for our study.\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Edges of co-occurrence graphs as focal and context pairs}\\label{sec:edges_as_pairs}\nWe take advantage of the definition of arbitrary context and define our context based on the types of entities surrounding a word. Our goal is to create embeddings, such that each part corresponds to the relation of the focal word to the specific type of entities as context. A co-occurrence graph extracted from annotated text can help us achieve just that. To obtain each componnent of the embedding we define a type-specific edge list, in a similar fashion as type-specific adjacency matrices for faceted GloVe, where the start nodes are entities of a specific type and end nodes can be any term or entity from the vocabulary. More formally, in the heterogeneous graph $G=(V,E)$, where $V=A\\bigcup  L\\bigcup  \\bigcup  O\\bigcup  D\\bigcup T $ is the set of all nodes with types actors, locations, organisations, dates, and any non-entity word (term) and $E$ is the set of all weighted edges, we extract five edge lists where the start node is one of the types in set $V$. An example of edge lists is shown in Figure~\\ref{fig:facettedword2vec}. As demonstrated in Figure~\\ref{fig:facettedword2vec}, we have a different edge list for each type that are treated as a focal and context pairs $(f,c)$ for the input of skip-gram with arbitrary contexts. Context word can be any node $c \\in V$ and focal word $f$ has specific type, e.g, $f \\in A$ for generating actor component of the embedding. Thus, the focal and context vocabulary are not equal, as the focal vocabulary is always a subset of the context ($A \\subset  V$). \n\\begin{figure}\n\\centering \n\\resizebox{0.80\\textwidth}{0.28\\textwidth}{      \n\\input{images/facettedword2vec.tex}\n}\n\\caption{An example of creating type specific edge lists for a graph with node type: actor (A), location (L), organisation (L), date (D), and term (T).}\n\\label{fig:facettedword2vec}\n\\end{figure} \nBased on each edge list the model learns a separate embedding, with entities of a certain type as focal words and the rest of the vocabulary as context. As a result, each context embedding encodes the relation of the complete vocabulary with a certain type. For example, if we look at the context embedding for actors, it encodes the relation of the words in the vocabulary to all the actors. Naturally, if a word does not have an edge to any actor it will not be present in the context embeddings. For such cases, it makes sense to set the actor component of that word equal to a vector of zeros. For example, in Figure~\\ref{fig:facettedword2vec}, $T_2$ will only have a non-zero date component and the rest are set to zero. This approach has some drawbacks, as the cosine similarity between a vector of zero and any other vector is undefined. Therefore, if a component of a vector is set to zero, that word becomes incomparable to all other words in that sub-space. It also causes  problems for clustering algorithms that require a distance measure between the points, if the cosine similarity is undefined, then we are unable to compare the words and form clusters. To solve this issue, we add a small number $0.0001$ to the vectors of all zero, mapping all the words to the same point, while keeping the component small. Moreover, clustering algorithms are able to compute the distance between the word vectors in the sub-spaces. This approach also has some unwanted implications,  if components of two words are identical, their cosine similarity is always one. Thus, any two words that do not have relations to entities of a particular type are considered similar in that subspace, which is not always the case. For example, in Figure~\\ref{fig:facettedword2vec}, $T_2$ and $L_2$ both have the same organisation component, as they are not connected to any organisation node. The absence of an edge to an organisation does not necessary mean that $T_2$ and $L_2$ should be similar in organisation space, which is what the model would imply. \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Faceted DeepWalk}\\label{sec:faceted_deepwalk}\n\nAnother way to achieve the faceted model is by embedding the nodes of a co-occurrence matrix, where node embedding algorithm preserves the neighbourhood of a specific For this purpose, we alter the DeepWalk model to meet our needs, and introduce a \\emph{type-restricted random walk}.\\\\\nIn $2017$, \\emph{metapath2vec} was proposed by Dong et al. to study representation learning in heterogeneous graphs with multiple edge and node types, such as coauthor relationships graphs~\\brackettext{\\cite{DBLP:conf/kdd/DongCS17}}. Metapath2vec learns a low dimensional representation of the graph using random walks that are restricted to the only transition between particular types of nodes and edges. They also introduce a heterogeneous skip-gram which maximizes the probability of having the heterogeneous context for a given node~\\brackettext{\\cite{DBLP:journals/tkde/CaiZC18}}. For learning the faceted embeddings, however, we take a more straightforward approach. We take advantage of the weighted random walks used in Chapter~\\ref{chap:entity} to generate entity embeddings, to introduce a new type-restricted random walk. With the help of this customized random walk,  we restrict the context of a word to certain entity type. \nIn general, faceted DeepWalk model consists of three steps: \n\\begin{enumerate}\n\\item Generating type specific corpus based on type-restricted fixed length random walks starting from all the nodes in the graphs.\n\\item Applying the skip-gram model on the random walk corpora. \n\\item Concatenating the resulting embedding for each type to achieve the final faceted model.  \n\\end{enumerate}\n\\emph{Type-restricted random walk:} Formally, a type-restricted random walk in graph $G=(V,E)$ is denoted in the form of $v_1 \\rightarrow v_2 \\rightarrow v_3\\rightarrow \\dots \\rightarrow v_n$, where the nodes $v_i$ belong to a certain node type. In each step, the random walker is only allowed to visit the next node if it satisfies the type restriction. For example, in a graph, where $V=A\\bigcup  L\\bigcup  O\\bigcup  D\\bigcup  T$, to sample only locations related to a node, we perform a location-restricted random walk. Consequently, the transition probability for the restricted type $L$ between node $i$ and $j$, in a weighted graph, is defined in Equation~\\ref{eq:transition_type_restricted}, where $e_{i,j}$ is the edge weight between the two nodes $i$ and $j$. Given that we are removing the possibility of transitioning to any type other than the pre-defined one, the probabilities are normalized by the summation of edge weights that have that specific type as their end node. If such random walk is repeated for each node, the generated random walk corpus would reflect the separation of context needed to train the faceted models.\n\\begin{equation}\nP_{ i,j }=\\left\\{ \n\\begin{matrix}\n \\frac { f(e_{ i,j }) }{ \\sum _{ k\\in L,f(e_{ k })\\in E_{ i } }^{  }{ f(e_{ k }) }  }  & \\mathrm{if}\\quad j\\in L \\\\\n0 & \\mathrm{if}\\quad j\\notin L\n\\end{matrix} \n\\right. \n\\label{eq:transition_type_restricted}\n\\end{equation} \n\\noindent\nFunction $f$, in Equation~\\ref{eq:transition_type_restricted}, is the edge normalization function. Similar to our approach for entity embeddings, we use two normalization functions: \\\\\n\\begin{enumerate}\n\\item  $f=\\mathrm{id}$, identity function or no normalization. We denote these models by $f$DW$_{id}$, where $id$ shows the identity mapping. \\\\\n\\item  $f=\\log$, logarithmic normalization. These models are denoted by  $f$DW$_{log}$.\\\\\n\\end{enumerate}\n\\noindent\nAn example of the type-restricted random walk for type location is illustrated in Figure~\\ref{fig:facetteddeepwalk}. Any nodes in the random walk have to be a location to be visited, otherwise, it is disregarded. Hence, by creating a type specific corpus with the type-restricted random walk, we can train a skip-gram model that learns the representation of all nodes with regards to a single entity type. By repeating this process for all node types and concatenating the results we achieve the faceted model.\n\\begin{figure}\n\\centering \n\\resizebox{0.60\\textwidth}{0.27\\textwidth}{      \n\\input{images/facted_deepwalk.tex}\n}\n\\caption{An example of type restricted random walk of length $2$ for node types location and starting node $A_1$.}\n\\label{fig:facetteddeepwalk}\n\\end{figure} \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Similarity Between Embeddings}\nIn the previous chapter, we presented cosine similarity as the main similarity measure between word vectors. To take advantage of the separation in dimensions for faceted embedding, an additional vector multiplication for cosine similarity is defined, resulting into two types of similarity:  \n\\begin{itemize}\n\\item \\emph{Full similarity:} Using the full dimensions of vectors for computing the cosine similarity or the dot product between two words. The full embedding vector contains the concatenation of entity types available in the data. \n\\item \\emph{Partial similarity:} Using components based on query words. For example, if the similarity between an actor and a term is requested, only components related to actors and terms in both embeddings are kept to compute the cosine similarity. This method is used to test whether a particular dimensions keeps the most informative information about a type or not. Partial similarity can also be viewed as looking at the similarity between two word vectors in a chosen subspace. For example, looking only at cosine similarity between the organisation component of two embeddings will show how close they are in the organisation subspace. \n\\end{itemize}\n\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Summary of Faceted Embeddings}\\label{sec:faceted_summary}\nIn this chapter, we introduced three models for learning faceted embeddings with separable components, where each component defines the relation of a word to entities of a specific type. We modified the existing word embedding and graph embedding techniques to obtain a more flexible definition of context for a word, where for each component the context is limited to entities of a certain type. As input for all models, we used the co-occurrence graph extracted on annotated text, which contains the entity-entity relations and captures their co-occurrence with terms. From the word embedding methods, we modify GloVe and word2vec and from the graph-embedding models, we chose DeepWalk with type-restricted random walks. In Chapter~\\ref{chap:eval}, we evaluate the faceted models against the well-established word embedding methods on various term-based evaluation tasks and discuss their advantages and drawbacks.\n\n", "meta": {"hexsha": "fe4c34d1723c88cb2b19a01be6401491e5d9110a", "size": 50599, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Sources/Facetted.tex", "max_stars_repo_name": "satya77/Thesis_Entity_Embeddings", "max_stars_repo_head_hexsha": "283568d8ad5e388a3b598dbdeaa62f06382bfe92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-14T19:48:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-14T19:48:53.000Z", "max_issues_repo_path": "Sources/Facetted.tex", "max_issues_repo_name": "satya77/Thesis_Entity_Embeddings", "max_issues_repo_head_hexsha": "283568d8ad5e388a3b598dbdeaa62f06382bfe92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sources/Facetted.tex", "max_forks_repo_name": "satya77/Thesis_Entity_Embeddings", "max_forks_repo_head_hexsha": "283568d8ad5e388a3b598dbdeaa62f06382bfe92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 139.391184573, "max_line_length": 2066, "alphanum_fraction": 0.7479199194, "num_tokens": 12461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.30111393716375856}}
{"text": "%% METHODS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{The automatic state decomposition algorithm}\n\\label{section:methods}\n\n% TODO:\n%  - caption for algorithm flowchart\n%  - citation for why conformational averaging is bad\n\nBased on the theory above, we provide a list of practical considerations for an automatic state decomposition algorithm and then present an algorithm that meets the criteria proposed below.\nThe algorithm operates on an ensemble of molecular dynamics trajectories where conformations (the Cartesian coordinates of all atoms of the macromolecule) have been stored at regular intervals.\nIn this work, we apply the method to a set of \\emph{equilibrium} trajectories at the temperature of interest, but the algorithm can in principle be applied to trajectories generated from \\emph{biased} initial conditions, provided the unbiased transition probabilities between regions of configuration space can be computed.\nWe stress that the algorithm presented here is simply a first attempt at a truly general and automatic algorithm for use with biomacromolecules. \n\n\\subsection{Practical considerations for an automatic state decomposition algorithm.}\n\\label{section:methods:desiderata}\n\nThere are several desirable properties that a state decomposition should possess to be both useful and practical:\n\\begin{enumerate}\n  \\item It is not uncommon for simulations conducted on supercomputers such as Blue Gene \\cite{fitch:2003a,germain:2005a}, distributed computing platforms such as Folding@Home \\cite{pande:2000a,pande:2003a}, or even computer clusters to generate datasets that may contain $10^5$ to $10^7$ configurations in up to $10^4$ trajectories, therefore prohibiting the use of any algorithm with a time complexity greater than $\\mathcal{O}(N \\log N)$ in the number of configurations.\n  \\item Molecules may have symmetries under permutation of atoms, such as aromatic rings, the protons on methyl groups, and the oxygens of carboxylate groups that should be accounted for in some way.\n  \\item The state decomposition algorithm should produce a decomposition for which dynamics appears to be Markovian at the shortest possible lag time $\\tau$, so as to produce the most useful model.\n  \\item The resulting model should not generate so many states so that the elements of the transition matrix will be statistically unreliable.\n\\end{enumerate}\n\n\\subsection{Sketch of the method.}\n\\label{section:methods:sketch}\n\n\\begin{figure}[tb]\n  \\begin{center}\n    \\resizebox{3.375in}{!}{\\includegraphics{chapters/automatic-state-decomposition/figures/flowchartsmall.pdf}}    \n  \\end{center}\n  \\caption{{\\bf Flowchart of the automatic state decomposition algorithm.}}\n  \\label{figure:methods-flowchart}\n\\end{figure}\n\nA state decomposition algorithm intended to produce the most \\emph{useful} models, as discussed in Section \\ref{section:theory:requirements-for-markovian-behavior} above, would generate models that minimize the internal equilibration time $\\tau_\\mathrm{int}$, the minimum time for which the model behaves in a Markovian fashion.\nUnfortunately, $\\tau_\\mathrm{int}$ is difficult to determine directly, so we are instead forced to identify some surrogate quantity whose maximization will hopefully lead to improved separation between fast intrastate and slow interstate timescales.\nFollowing the approach of Ref.\\ \\cite{huisinga:2005a}, we define a measure of the \\emph{metastability} $Q$ of a partitioning into $L$ \\emph{macrostates} as the sum of the self-transition probabilities for a given lag time $\\tau$:\n\\begin{eqnarray}\nQ &\\equiv& \\sum_{i=1}^L T_{ii}(\\tau) \\label{equation:metastability}\n\\end{eqnarray}\nFor $\\tau = 0$, $Q = L$, and decays to unity as $\\tau$ grows large enough for the self-transition probabilities $T_{ii}$ to reach the equilibrium probabilities of each macrostate.\nPoor partitionings into weakly metastable states will result in a small $Q$, as trajectories started in some states will rapidly exit; conversely, good partitionings into strongly metastable states will result in a large $Q$, as trajectories will remain in each macrostate for long times.\nIn the absence of statistical uncertainty, $Q$ is bounded from above by the sum of the $L$ largest eigenvalues of the true dynamical propagator for the system \\cite{huisinga:2005a}.\n\nThe goal of our algorithm is to identify a partitioning into $L$ contiguous macrostates that maximizes the metastability $Q$.\nWhile in principle, the boundaries between these macrostates can be varied directly to optimize $Q$, in analogy to variational transition state theory \\cite{truhlar:1996a}, a complicated parameterization may be necessary to describe the potentially highly convoluted hypersurfaces separating the states, and $Q$ may have multiple maxima in these parameters.\nInstead, we choose an approach based on \\emph{splitting} the conformation space into a large number of small contiguous \\emph{microstates} and then \\emph{lumping} these microstates into macrostates in such a way that maximizes the metastability.\n% During this process, we choose some lag time $\\tau$ that is less than or equal to the fastest timescale of interest.\n\nThis approach is very similar to the approach of Sch\\\"{u}tte and coworkers described in Ref.\\ \\cite{schuette:1999a}, but with a substantial difference.\nIn their work, each degree of freedom of the molecule (such as a torsion angle) is subdivided independently to produce a multidimensional grid.\nAs the number of states is exponential in the number of degrees of freedom, this approach quickly becomes intractable for macromolecules that possess large numbers of degrees of freedom, even if the sparsity of the transition matrix is taken into account.\nInstead, we choose to let the data define the low-dimensional manifold of configuration space accessible to the macromolecule, and we can apply any clustering algorithm that is no worse than $\\mathcal{O}(N \\log N)$ in the number of configurations to decompose the sampled conformation space into a set of $K$ contiguous microstates.\nThis step corresponds to the first \\emph{split} step in Figure \\ref{figure:methods-flowchart}.\n\nOnce the conformation space is divided into $K$ microstates, we \\emph{lump} the microstates together to produce $L < K$ macrostates with high metastability, $Q$.\nThis corresponds to the first \\emph{lump} step in Figure \\ref{figure:methods-flowchart}.  \n% As described in Section \\ref{section:theory:construction-from-simulation-data}, we can calculate a transition probability matrix for any decomposition of configuration space.\n% The \\emph{lump} step illustrated in Figure \\ref{figure:methods-flowchart} combines the $K$ microstates into $L$ macrostates, calculates the new transition matrix between the macrostates, and chooses a lumping with high metastability.\nThe difficulty here is that the uncertainty in the metastability of a partitioning can be large if any macrostate contains very few configurations.\nSince a macrostate may consist of a single microstate, the microstates must be large enough for the self-transition elements to be statistically well-determined.\n%The difficulty here is that if the microstates are too small, the number of observed transitions from each microstate will be small, and the elements of the microstate transition matrix will be dominated by statistical uncertainty.\n%To avoid this, the microstates must be large enough for the transition matrix to be well-determined.\nThis comes at a price: with large microstates, the procedure may have difficulty accurately determining the boundaries between macrostates because the resolution of partitioning is limited by the finite extent of the microstates.\n%Additionally, the choice of decomposition into microstates is arbitrary, whereas we would like the state decomposition algorithm to give us the same set of macrostates regardless of how it was initialized.\nAdditionally, the choice of decomposition into microstates is arbitrary, whereas we would like the state decomposition algorithm to produce equivalent sets of macrostates regardless of how good the initial partitioning was.\n\nTo overcome these difficulties, we \\emph{iterate} the aforementioned procedure.\nAfter microstates are combined into macrostates, each macrostate is again fragmented into a new set of microstates (the second \\emph{split} step in Figure \\ref{figure:methods-flowchart}).\nThe refined set of all microstates is then lumped to form refined macrostates (the second \\emph{lump} step in Figure \\ref{figure:methods-flowchart}).\nIn this way, the boundaries between macrostates are iteratively refined, and regions incorrectly lumped in previous iterations may be split off and lumped with the correct macrostate in subsequent iterations.\nAt convergence, the same set of macrostates will simply be split and lumped back together in the same way --- no further shuffling of conformations between macrostates will occur.\n\nThere is unfortunately no unambiguous way to choose the number of states $L$.\nIf there is a clean separation of timescales, examination of the eigenvalue spectrum of the microstate transition matrix may suggest an appropriate value of $L$ \\cite{schuette:2002b}.\nIn a hierarchical system, there will be many gaps in the eigenvalue spectrum and many of choices of $L$ will lead to good Markovian models of varying complexity.\nThere is, however, a tradeoff between the number of states and the amount of data needed to obtain a model with the same statistical precision.\nIt may be necessary to apply the algorithm with multiple choices of $L$ to produce a model sufficient for resolving the timescales of interest.\n\n%In a strongly hierarchical system, where there are several ranges of timescales well-separated from each other, there are many potential choices of $L$ that will lead to good Markovian models.\n%In this case, several models of varying complexity can be made.\n%For systems without strong separations of timescales, we find that the few fastest timescales are poorly described, but the slowest timescales are generally well-captured, and so $L$ should be chosen somewhat larger than the number of desired states.\n%(For a more complete discussion, see [CITE ZIB WORK ON TIMESCALES AND CHOICE OF L].)\n%In any case, $L$ must be chosen large enough such that the fastest implied timescales of the model (as revealed by the eigenvalue decomposition of the transition matrix) are comparable to or faster than the timescales of interest.\n%Alternatively, $L$ could be chosen to provide a level of complexity of interest.\n%Finally, there is a tradeoff between the number of states and the amount of data needed to accurately characterize the transition matrix --- more data will be needed to characterize models with more states, but this does depend on the particular details of the system.\n\n\\subsection{Implementation.}\n\\label{section:methods:implementation}\n\nThere are a number of implementation choices to be made in the algorithm given above, and here we briefly summarize and justify our selections.\n\nFor the split step, we choose to apply $K$-medoid clustering \\cite{hastie:2001a} because of its $\\mathcal{O}(KN)$ time complexity (where $K$ can be taken to be constant) and ease of parallelization.\nAdditionally, $K$-medoid clustering has an advantage over the more popular $K$-means clustering \\cite{macqueen:1967} in this application, as it does not require averaging over conformations, which may produce nonsensical constructs when drastically different conformations are included in the average.\nSplitting by $K$-medoid clustering is initiated from a random choice of $K$ unique conformations to function as \\emph{generators}.\nAll conformations are assigned to the microstate identified by the generator they are closest to by some distance metric (defined below).\nNext, an attempt is made to update the generator of each microstate.\n$K$ members of the microstate, drawn at random, are evaluated to see if they reduce the intrastate variance of some distance metric from the generator.\nIf so, the configuration for which the intrastate variance is minimal is assigned as the new generator.\nAll conformations are then reassigned to the closest generator, and the process of updating the generators is repeated.\nIn standard $K$-medoid applications, this procedure is iterated to convergence, but since the purpose of the splitting phase is simply to divide the sampled manifold of configuration space into contiguous states, ensuring that each state is significantly populated, only five iterations of this procedure were used.\n\nFor the distance metric, we selected the root-mean squared deviation (RMSD), computed after a minimizing rigid body translation and rotation using the rapid algorithm of Theobald \\cite{theobald:2005a}.\nIn the first splitting iteration, only C$_\\alpha$ atoms were used to compute the RMSD due to the expense of having to cluster all conformations in the dataset; in subsequent iterations, all heavy atoms (excepting those indistinguishable by symmetry) were used, as well as sidechain polar hydrogens.\nThis metric was chosen because it possesses all the qualities of a proper distance metric \\cite{steipe:2002a}, accounts for both local similarities between pairs of conformations as well as global ones, and runs in time proportional to the number of atoms, as opposed to a metric such as distance matrix error (DME or dRMSD), which scales as the square of the number of atoms.  \n%Atoms related by a symmetry relation are interchangeable in the conformation, so the distance metric shouldn't differentiate these conformations.\nIn molecules with additional symmetry, the distance metric can be adjusted accordingly.\nOur choice of distance metric is not the only one that would suffice; any distance metric which can distinguish between kinetically distinct conformations is sufficient for this algorithm.\nFor example, backbone RMSD would ignore potentially relevant sidechain kinetics.\n\nLumping to $L$ states so as to maximize the metastability $Q$ of the macrostates proceeds in two stages.\nIn the first stage, information on the metastable state structure contained in the slowest eigenvectors \\cite{schuette-thesis,huisinga-thesis,deuflhard:2000a,schuette:2002b} is used to construct an initial guess at the optimal lumping.\nBecause the eigenvectors contain statistical noise, this initial guess may not actually be optimal; because of this, we include a second stage that uses a Monte Carlo simulated annealing (MCSA) optimization algorithm to attempt to further improve the metastability.\nThough the MCSA algorithm could in principle be used without the first stage to find optimal lumpings, we find its convergence is greatly accelerated by use of the initial guess.\n\nIn the first stage, a transition matrix among microstates is computed (using Eq.\\ \\ref{equation:transition-element-correlation-functions}) taking advantage of both stationarity and time-reversibility for a short lag time $\\tau$, typically the shortest interval at which configurations were stored.\n%Each eigenvector, considered in order from largest non-unit eigenvalue to smallest, specifies that a single macrostate is to be further subdivided into two new macrostates.\nMotivated by the Perron cluster cluster analysis (PCCA) algorithm of Deuflhard \\emph{et al.\\ } \\cite{deuflhard:2000a}, an initial guess for the optimal lumping of microstates to macrostates is generated using the \\emph{left} eigenvectors\\footnote{The left eigenvector $\\bfm{v}_k$ is simply related to the right eigenvector $\\bfm{u}_k$ by $(\\bfm{v}_k)_i = p_{\\mathrm{eq},i}^{-1} \\, (\\bfm{u}_k)_i$ \\cite{oppenheim:1977a}.} associated with the largest eigenvalues of the microstate transition matrix.\n% If we group together microstates with similar left eigenvector components from the set of eigenvectors associated with the longest timescales, these microstates should interconvert on shorter timescales, and therefore the metastability of the partitioning will be high \\cite{schuette-thesis,huisinga-thesis,deuflhard:2000a,schuette:2002b}.\nWe begin by assigning all microstates to a single macrostate.\nFor each eigenvalue, the corresponding eigenvector contains information about an aggregate transition between the set of microstates with positive eigenvector components and the set with negative components, with a timescale determined by the eigenvalue; equilibration within each set must occur on a faster timescale, provided the eigenvalues are non-degenerate.\nWe can therefore use this information to identify one macrostate to divide in two.\nWe select the macrostate with the largest $L_1$ norm of the vector formed from the eigenvector components that belong to that macrostate, after subtracting the mean of this vector, as the state to split.\nIn Ref.\\ \\cite{deuflhard:2000a}, the sign structure alone was used to split these sets, but we find it more stable to split about the mean.\nThis procedure is performed for eigenvectors $k = 2,\\ldots,L$ in order, which should correspond to the slowest processes in the system, generating a total of $L$ macrostates.\n\n%However, simply grouping states together based on eigenvector components often did not result in a lumping with maximum metastability $Q$ or preserved timescales.\nDue to statistical noise in the eigenvectors and near-degeneracy in the eigenvalues, this procedure does not always result in the lumping with the maximal metastability $Q$.\nTherefore, in the second stage, the metastability was maximized using a Monte Carlo simulated annealing (MCSA) algorithm, using the eigenvector-generated lumping as an initial seed.\nIn each step of the Monte Carlo procedure, a microstate was selected with uniform probability and assigned to a random macrostate.\nIf this proposed move would leave a macrostate empty or did not change the partitioning, it was rejected immediately.\nThe proposed partitioning was accepted with probability $\\min \\{1, e^{\\beta \\Delta Q} \\}$, where the metastability $Q$ of the proposed lumping was rapidly computed by combining elements of the matrix of inter-microstate transition counts.\nThe effective inverse temperature parameter $\\beta$ was set to be equal to the step number, and the MCSA procedure run for 20 000 steps.\nTwenty independent MCSA runs were initiated from the initial eigenvector-based partitioning, and the partitioning with the highest metastability sampled in any run was selected to define the lumping into macrostates.\n\nIt should be noted that the metastability $Q$ is not the only surrogate that could be optimized in order to produce a useful state decomposition.\nMany choices may be possible, especially when one considers the problem of lumping as an attempt to preserve the $L$ longest timescales (determined by the eigenvalues of the transition matrix near unity) present in the microstate transition matrix.\nOne could choose to maximize the fastest eigenvalue or timescale of the lumped transition matrix, the product of eigenvalues (which would give more weight to faster timescales), or even a weighted sum of the eigenvalues, where the weights might be due to the equilibrium importance of the eigenmode in dynamics or in modeling a process of interest.\nUnfortunately, these quantities all necessitate computing some eigenvalues or the determinant of the lumped transition matrix for every proposed lumping to be evaluated by the MCSA algorithm, which would add significant computational burden.\nAlternatively, other quantities could be computed from the transition matrix directly, such as the state lifetimes estimated from the self-transition probabilities as $\\tau_{L,i} = (1 - T_{ii})^{-1}$.\nHowever, the combination of computational and theoretical convenience makes the use of metastability a natural choice here.\n\nFor the remaining iterations, the $K$-medoid clustering is repeated independently on each macrostate.\nWe set a minimum expected microstate size (estimated by the population of the macrostate divided by $K$) to ensure statistical reliability of the transition probability matrix.\nThis is set to 100 configurations (unless otherwise noted), though a more useful criteria may be to set a minimum number of statistically independent visits to the state.\nEach macrostate is split into a number of states such that the expected microstate population (assuming even division into microstates) is no smaller than this threshold, or a maximum of 10 microstates.\nThe lumping step is then repeated on all resulting microstates.\nThe entire procudure of splitting and lumping was repeated for a total of 10 iterations, which for the applications considered here was sufficient for convergence of the slowest timescales.\n\n\\subsection{Validation.}\n\\label{section:methods:validation}\n\nTo validate the model, we examine the largest implied timescales as a function of lag time, as computed for the eigenvalues of the transition matrix by Eq.\\ \\ref{equation:implied-timescales}.\nIn particular, we attempt to determine the minimum lag time after which the implied timescales appear to be independent of lag time to within the estimated statistical uncertainty (see Section \\ref{section:theory:validation}).\nTo estimate the statistical uncertainty of these implied timescales, we perform a bootstrapping procedure \\cite{efron:1979a} on the pool of independent trajectories.\nForty bootstrap samples of a number of trajectories equal to the number of independent trajectories in the dataset pool are generated, drawn with replacement from the pool of trajectories, except for alanine dipeptide, where 100 bootstrap samples were used.\nThe implied timescales are computed for each sample, and the set of computed timescales is used to estimate a confidence interval.\nIn figures, uncertainties will always be shown as 68\\% symmetric confidence intervals about the mean of the bootstrap sample, while uncertainties in quantities printed as $a \\pm b$ will indicate variances about the mean.\n\n\n\n\n\n", "meta": {"hexsha": "3e30165d4fee2c6f11a368996060d09b49981293", "size": 21911, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/automatic-state-decomposition/methods.tex", "max_stars_repo_name": "jchodera/jdcthesis", "max_stars_repo_head_hexsha": "bc238b4023fa0ee3433d711188c59f3cf791eb90", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/automatic-state-decomposition/methods.tex", "max_issues_repo_name": "jchodera/jdcthesis", "max_issues_repo_head_hexsha": "bc238b4023fa0ee3433d711188c59f3cf791eb90", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/automatic-state-decomposition/methods.tex", "max_forks_repo_name": "jchodera/jdcthesis", "max_forks_repo_head_hexsha": "bc238b4023fa0ee3433d711188c59f3cf791eb90", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 132.7939393939, "max_line_length": 497, "alphanum_fraction": 0.80986719, "num_tokens": 4672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.30111393716375856}}
{"text": "% !TEX root =  paper.tex\n\\section{Method}\n\n\\begin{figure*}[htbp]\n\t\\begin{center}\n\t\t\\includegraphics[width=0.24\\linewidth]{./figures/methods/multicut_input.png}\n\t\t\\includegraphics[width=0.24\\linewidth]{./figures/methods/pre-multicut.png}\n\t\t\\includegraphics[width=0.24\\linewidth]{./figures/methods/multicut-graph.png}\n\t\t\\includegraphics[width=0.24\\linewidth]{./figures/methods/post-multicut.png}\n\t\\end{center}\n\t\\caption{Outline of our approach, from left to right: result of the pixel-based segmentation and agglomeration algorithm; segments of several selected neurons from the initial segmentation; extracted skeletonized 3D network of those segments; improved 3D reconstruction of the selected segments after graph construction and partitioning with constraints.}\n\t\\label{fig:overview}\n\\end{figure*}\n\n\n\\begin{figure}[t]\n\t\\centering\n\t\\includegraphics[width=0.82\\linewidth]{./figures/skeleton1.png}\n\t\\includegraphics[width=0.82\\linewidth]{./figures/skeleton2.png}\n\t\\includegraphics[width=0.82\\linewidth]{./figures/skeleton3.png}\n\t\\caption{Example skeletons (in black) extracted from segments using the TEASER algorithm.}\n\t\\label{fig:skeletonization}\n\\end{figure}\n\nThere are two types of errors that can occur in connectomics segmentation.\nThe first, called a split error, occurs when there are two segments that should have been merged. The second, called a merge error, happens when one segment should be split into two. Generally, it is much more difficult to correct merge errors than to correct split errors,\nas the space of possible split proposals grows quickly~\\cite{parag2015properties}.\nThus, most reconstruction approaches are tuned towards over-segmentation with many more split than merge errors. Our method takes as input over-segmentations of EM image volumes generated by state-of-the-art connectomics reconstruction pipelines (Sec.~\\ref{sec:neuroproof}). Our goal is to identify locations of split errors and merge the corresponding segments automatically.\n\nFrom the input segmentation we generate a graph $G$ with nodes $N$ and edges $E$ with weights $w_e$. The nodes correspond to label segments from the segmentation with edges between segments considered for merging. Ideally, our graph has edges corresponding to all of the segments that were erroneously split. To compute this graph we generate a skeleton for every segment in the pixel-based segmentation (Fig.~\\ref{fig:overview}). The skeletonized 3D network is a simplified representation of the overall branching structure of the neurons. From these skeletons we identify potential merge locations and produce the corresponding edges for the graph. To find actual merges we run a classification CNN to generate edge weights corresponding to merge probabilities. We then use a multicut algorithm to generate a partition on the graph where nodes in the same partition are assigned the same output label in the improved segmentation. We will now discuss the three major components to our framework (graph creation, edge weights assignment, and graph partitioning) in more detail.\n\n%\\subsection{Graph Creation}\n\n%We generate nodes $N$ and edges $E$ to apply a graph-based optimization strategy for segmentation.\n%In addition, these edges receive non-negative weights.\n\n\\subsection{Node Generation}\n%\\subsubsection{Node Generation}\n\\label{sec:skeletonization}\n\nThe simplest node generation strategy creates one node for every unique segment label in the input volume. However, some of the millions of labels in the volume correspond to very small structures that are likely the result of segmentation errors, typically in regions with noisy raw image data. It is difficult to extract useful shape features from these segments because of their small, often random, shape. We prune these nodes from the graph by removing all segments with fewer than a threshold $t_{seg} = 20,000$ voxels. This removed on average 56\\% of the segments in our  datasets (Sec.~\\ref{sec:dataset}). Despite the large number of segments, these regions only take up 1.6\\% of the total volume on average.\n\n\\subsection{Edge Generation}\n\nA typical approach for generating edges produces one between all adjacent segments. Two segments $l_1$ and $l_2$ are considered adjacent if there is a pair of adjacent voxels with one labeled $l_1$ and the other labeled $l_2$.\nFor example, pixel-based agglomeration methods such as NeuroProof~\\cite{10.1371/journal.pone.0125825} and GALA~\\cite{nunez2014graph} consider all pairs of adjacent segments for merging.\nHowever, this method produces too many edges in the graph for graph-based optimization approaches. We identify a smaller number of pairs of segments to consider as graph edges using the following approach.\n\nFirst, we extract a skeleton from each segment in the label volume using the TEASER algorithm~\\cite{sato2000teasar,zhao2014automatic}. Fig.~\\ref{fig:skeletonization} shows an example of three extracted skeletons (in black). These skeletons consist of a sequence of \\textit{joints}, i.e., locations that are locally a maximum distance from the segment boundary, with line segments connecting successive joints. We prune the joints that are within $t_{jnt} = 50$ voxels of each other to reduce unnecessary branching. We refer to joints that have only one connected neighbor as \\textit{endpoints}. Many of the segments that are erroneously split have nearby endpoints  (Fig.~\\ref{fig:merge_candidates}). We make use of this fact to find merge candidates with the following two-pass pruning algorithm.\n\nIn the first pass, we iterate over all endpoints $e$ belonging to a segment $S$ and create a set of segments $\\mathbb{S}_e^\\prime$ that includes all labels that are within $t_{low}$ voxels from $e$. Elements of $\\mathbb{S}_e^\\prime$ are candidates for merging. However, this first pass often leads to too many candidates, requiring an additional pass for further pruning. In the second pass, we consider all of the segments in $\\mathbb{S}_e^\\prime$ for every endpoint $e$. If a segment $S^\\prime \\in \\mathbb{S}_e^\\prime$ has an endpoint within $t_{high}$ voxels of $e$, the segment $S$ and $S^\\prime$ are considered for merging. We store the midpoints between the two endpoints as the center of the potential merges in the set $\\mathbb{S}_c$. This algorithm produces a set of segments to consider for merging. Only these pairs have a corresponding edge in the constructed graph.\n\n\n\n\\begin{figure}[t]\n\t\\centering\n\t\\includegraphics[width=0.92\\linewidth]{./figures/split_error1.png}\n\t\\includegraphics[width=0.92\\linewidth]{./figures/split_error2.png}\t\t\\includegraphics[width=0.85\\linewidth]{./figures/merge_candidate2.png}\n\t\\caption{Three erroneously split segments.}\n\t\\label{fig:merge_candidates}\n\\end{figure}\n\n\\subsection{Edge Weights Assignment}\nWe assign edge weights $w_e$ to each edge where the weight corresponds to the probability that two nodes belong to the same neuron.\nInstead of using handcrafted features to compute the similarity between adjacent nodes, we train a 3D CNN classifier to learn from the manually labeled oversegmentation input volume (Sec.~\\ref{sec:dataset}).\nIf the probability that the nodes belong to the same neuron is $p_e$, the edge weight $w_e = \\log{\\frac{p_e}{1 - p_e}} + \\log{\\frac{1 - \\beta}{\\beta}}$, where $\\beta$ is a tunable parameter that encourages over- or under-segmentation.\n%Our  edge weights  correspond to probabilities that two endpoints $e$ in $\\mathbb{S}_c$ belong to the same neuron and should be merged. \\hp{check}\n\n\\subsubsection{Classifier Input}\n\nWe extract a cubic region of interest (ROI) around each endpoint $e$ in $\\mathbb{S}_c$ as input to the CNN. The CNN receives three input channels for every voxel in the ROI around segments $l_1$ and $l_2$. The input in all of the channels is in the range $\\{-0.5, 0.5\\}$. The first channel is $0.5$ only if the corresponding voxel has label $l_1$. The second channel is $0.5$ only if the corresponding voxel has label $l_2$. The third channel is $0.5$ if the corresponding voxel is either $l_1$ or $l_2$.\n\n\\subsubsection{Network Architecture \\& Training}\n\n%Fig.~\\ref{fig:architecture} provides an overview of our CNN architecture.\nWe use the CNN architecture by Chatfield et al.~\\cite{chatfield2014return}. It consists of three layers of double convolutions followed by a max pooling step. The first two max pooling layers are anisotropic with pooling only in the $x$ and $y$ dimensions. The output of this final pooling step is flattened into a 1D vector that is input into two fully connected layers. The final layer produces probabilities with a sigmoid activation function~\\cite{funahashi1989approximate}. All of the other activation functions are LeakyReLU~\\cite{maas2013rectifier}.\n\nFor training we use a stochastic gradient descent optimizer with Nesterov's accelerated gradient~\\cite{nesterov1983method}. We employ dropouts of $0.2$ after every pooling layer and the first dense layer, and a dropout of $0.5$ after the final dense layer to prevent overfitting. We discuss all other network parameters in Sec.~\\ref{sec:network-parameters}.\n\n%\\begin{figure*}[t]\n%\t\\centering\n%\t\\includegraphics[width=0.85\\linewidth]{figures/architecture.png}\n%\t\\caption{The architecture for our classification CNN uses double convolutions followed by max pooling. The number of filters doubles each layer, with a final fully connected layer and sigmoid activation function.}\n%\t\\label{fig:architecture}\n%\\end{figure*}\n\n\\subsection{Graph Partitioning}\n\nAfter constructing the 3D graph we apply graph partitioning using multicut to compute the final segmentation. Using top-down graph partitioning allows us to apply biological constraints on the output. Neuroscientists know that neuronal connectivity graphs in the brain are acyclic (i.e., the graphs have a genus of zero). We enforce this constraint by finding a multicut partition of the graph that generates a \\textit{forest} of nodes, i.e., a set of trees where no segment has a cycle. To solve this constraing multicut problem we use the method by Keuper et al.~\\cite{keuper2015efficient} that produces a feasible solution by greedy additive edge contraction.", "meta": {"hexsha": "8cbee4ceaf7e7e307f3294e8b1a65c9284ccc1bc", "size": 10104, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "papers/cvpr2018/2_method.tex", "max_stars_repo_name": "romil797/ibex", "max_stars_repo_head_hexsha": "898134a96e299d8106d9deb7b217671c39bfeca2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "papers/cvpr2018/2_method.tex", "max_issues_repo_name": "romil797/ibex", "max_issues_repo_head_hexsha": "898134a96e299d8106d9deb7b217671c39bfeca2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "papers/cvpr2018/2_method.tex", "max_forks_repo_name": "romil797/ibex", "max_forks_repo_head_hexsha": "898134a96e299d8106d9deb7b217671c39bfeca2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 113.5280898876, "max_line_length": 1078, "alphanum_fraction": 0.7932501979, "num_tokens": 2372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.4726834766204329, "lm_q1q2_score": 0.301113930649264}}
{"text": "\\section{Alternatives} \\label{alternatives}\nIn this section we briefly discuss some other approaches we considered for the problem and the trade offs.\n\n\\subsection{Quorum Compatible}\nAs we mentioned in \\ref{safety}, we give up the pipeline of \\LBFT to preserve safety. Here we consider an alternative that preserves\nboth safety and pipeline.\n\n\\paragraph{Condition}\n\nConsider a reconfiguration transaction that changes from validators \\rust{N1} to validators \\rust{N2} and $f1=\\lceil|N1|/3\\rceil-1$,\n$f2=\\lceil|N2|/3\\rceil-1$ malicious power, $|N1|-f1$,  $|N2|-f2$ as quorum size respectively. We only allow reconfiguration if\n\n\\begin{equation}\n|N1 \\cap N2| > f1 + f2 + max(f1, f2)\n\\end{equation}\n\n\\paragraph{Analysis}\nWe have an important lemma in \\LBFT for safety: Under BFT assumption, for every two quorums of nodes, there exists an honest node that\nbelongs to both quorums.\n\nWith this approach, we restrict the changes between two configurations and we can prove quorums are interchangeable in both configurations,\nso that we implicitly maintain the safety property.\n\n\\subsection{Pipelined Configuration}\nThis is one step further on top of the quorum compatible approach. Instead of implicit compatible quorums, we require explicit two quorums\nto commit the reconfiguration transaction. We preserve the same safety lemma as above but doing it in a more explicit way.\n\nOne way to think about this is pipelining the reconfiguration like we pipeline blocks, reconfiguration $A\\rightarrow B$ takes effect\n(the next blocks on this branch need B’s quorum) right after the block and until a commit of another reconfiguration $B\\rightarrow X$.\n\n\\subsection{Comparison}\nWe assemble a comparison table for the three approaches we describe.\n\\begin{table*}[h]\n\\begin{tabular}{|c|c|c|c|}\n\n\\hline\n& Pipelining & Implementation Complexity & Flexibility\\\\\n\\hline \\hline\nBasic & No & Small & Most\\\\\nQuorum Compatible & Yes & Medium & Least\\\\\nPipelined Configuration & Yes & Big & Medium\\\\\n\\hline\n\n\\end{tabular}\n\\end{table*}\n\nBasic mechanim gives up pipelining/performance while provides more flexible configuration changes like protocol change, it also provides better\nisolation between different configurations.\n\nQuorum Compatible enables us with pipelining and is almost seamless to \\LBFT by strictly limit how configuration can change.\n\nPipelined configuration provides pipelining the same as Quorum Compatible with more flexible reconfiguration by supporting explicit multi quorums.\n\nAlso regardless of implicit or explicit quorums, to support pipelining configuration, we need to track configuraiton per block tree branch which\nadds complexity compared to one configuration per whole block tree in basic mechanism.\n\nWe chose the approach considered all above and think the performance gain of pipelining can not justify the added complexity and\nlost flexibility for now, but could leave for future work.\n", "meta": {"hexsha": "29506ec5912c6eaad22cff42ba9090cacff24fec", "size": 2896, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "documentation/tech-papers/lbft-reconfig/alternatives.tex", "max_stars_repo_name": "BlockSuite/libra", "max_stars_repo_head_hexsha": "27c125594ee82c8edb361f0c4cf79c9fa101dd68", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 16705, "max_stars_repo_stars_event_min_datetime": "2019-06-18T08:46:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-07T17:25:27.000Z", "max_issues_repo_path": "documentation/tech-papers/lbft-reconfig/alternatives.tex", "max_issues_repo_name": "BlockSuite/libra", "max_issues_repo_head_hexsha": "27c125594ee82c8edb361f0c4cf79c9fa101dd68", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6316, "max_issues_repo_issues_event_min_datetime": "2019-06-18T09:02:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-07T21:27:46.000Z", "max_forks_repo_path": "documentation/tech-papers/lbft-reconfig/alternatives.tex", "max_forks_repo_name": "BlockSuite/libra", "max_forks_repo_head_hexsha": "27c125594ee82c8edb361f0c4cf79c9fa101dd68", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2671, "max_forks_repo_forks_event_min_datetime": "2019-06-18T08:47:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-07T19:35:21.000Z", "avg_line_length": 49.0847457627, "max_line_length": 146, "alphanum_fraction": 0.7973066298, "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.30111393064926395}}
{"text": "\\section{Common base with SP}\n\\label{sec:common}\n\nThe \\emph{Simple propagation} (SP) algorithm, shown in Algorithm \\ref{alg:sp}, runs in a factorization ${\\cal F}$ finding all potentials $\\phi(W)$ with a special property called ``one in, one out''.\nNamely, given two sets of variables $X$ and $Y$, $\\phi(W)$ has one variable in $X-Y$ and another variable not in $X-Y$.\nSP returns a set of potentials that can be split into two disjoint subsets: one containing potentials $\\phi(W)$ where $W \\subseteq X$ and another ones with potentials $\\phi(W)$ where $W \\cap X = \\emptyset$.\n\n\\begin{algorithm}[htb]\n    \\caption{Simple Propagation.}\n    \\label{alg:sp}\n    \\begin{algorithmic}[1]\n        \\Procedure{SPropagation}{${\\cal F}$, $X$, $Y$}\n        \\While{$\\exists ~ \\phi(W) \\in {\\cal F}$ with $v \\notin X-Y$ and $v^\\prime \\in X-Y$}\\label{alg:sp_in_out}\n        \t\\State ${\\cal F}$ = \\Call{RemoveBarren}{$v$, ${\\cal F}$, $S$} \\label{alg:sp_barren}\n            \\State ${\\cal F}$ = \\Call{SumOut}{$v$, ${\\cal F}$} \\label{alg:sp_sum_out}\n        \\EndWhile\n    \\Return{${\\cal F}$}\n    \\EndProcedure\n    \\end{algorithmic}\n\\end{algorithm}\n\n\\begin{example}\nRun Algorithm \\ref{alg:sp} with ${\\cal F} ~=~ \\{P(a)$, $P(b|a)$, $P(c|a)$, $P(d|b,c)$, $P(e|d)$, $P(f|d,e)$, $P(g|e)$, $P(h|e)$, $P(i|d,g)$, $P(j|i)$, $P(k|j)$, $P(l|k)$, $P(m|h,l)\\}$, $X = \\{i,j,k,l,m\\}$, and $Y = \\{d\\}$.\nSP returns ${\\cal F} ~=~ \\{P(a)$, $P(b|a)$, $P(c|a)$, $P(n|c)$, $P(d=0|b,c)$, $P(j|i)$, $P(i,m|d=0,l)\\}$.\n\\label{ex:sp}\n\\end{example}\n\nIn Example \\ref{ex:sp}, it is worth noticing that the returned factorization ${\\cal F}$ can be split into two disjoin subsets: \n\\begin{align}\n\t\\{ P(j|i), P(i,m|d=0,l) \\}\n\t\\label{eq:1}\n\\end{align}\nand\n\\begin{align}\n\t\\{ P(a), P(b|a)\\}, P(c|a), P(c|a), P(n|c), P(d=0|b,c) \\}.\n\t\\label{eq:2}\n\\end{align}\n(\\ref{eq:1}) contains potentials with variables in $X$ and ({\\ref{eq:2}}) the potentials with no variables in $X$.\n\n\n\\section{Unifying Inference and Modeling}\n\\label{sec:new}\n\nSP can be used to perform BN inference.\nThe set of potentials ${\\cal F}_{SP}$ returned by Algorithm \\ref{alg:sp}, $\\Call{SPropagation}{{\\cal F},X,Y}$, contains all potentials relevant for a query $P(X|Y)$.\nAs shown in \\cite{butzetal16}, all potentials $\\phi(W) \\in {\\cal F}_{SP}$ where $W \\subseteq X$ has $W$ d-connected (not d-separated) to $X$.\n\n\\begin{algorithm}[htb]\n    \\caption{Inference.}\n    \\label{alg:sp_inf}\n    \\begin{algorithmic}[1]\n        \\Procedure{Inference}{${\\cal F}$, $X$, $Y$}\n    \\State ${\\cal F}_{SP}$ = $\\Call{SPropagation}{{\\cal F}, X, Y}$\n    %todo: discuss W \\subseteq X or W \\subseteq XY\n    \\State ${\\cal F}^\\prime$ = $\\{\\phi(W) ~|~ \\phi(W) \\in {\\cal F}_{SP}$ and $W \\subseteq X\\}$\n    \\State $P(X,Y)$ = $\\prod{\\phi \\in {\\cal F}^\\prime}$    \n    \\Return{$P(X,Y)/P(Y)$}\n    \\EndProcedure\n    \\end{algorithmic}\n\\end{algorithm}\n\n\\begin{example}\nGiven a query $P(i,j,k,l,m | d=0)$ posed to BN ${\\cal B}$ in Figure \\ref{fig:dag}, run Algorithm \\ref{alg:sp_inf} with ${\\cal F} ~=~ \\{P(a)$, $P(b|a)$, $P(c|a)$, $P(d|b,c)$, $P(e|d)$, $P(f|d,e)$, $P(g|e)$, $P(h|e)$, $P(i|d,g)$, $P(j|i)$, $P(k|j)$, $P(l|k)$, $P(m|h,l)\\}$, $X = \\{i,j,k,l,m\\}$, and $Y = \\{d\\}$.\n\\label{ex:sp_inf}\n\\end{example}\n\nThe important point in Example \\ref{ex:sp_inf} is the use of SP to perform the bulk of the work to answer the query $P(i,j,k,l,m | d=0)$.\n\nSP can be used to test independencies.\nThe set of potentials ${\\cal F}_{SP}$ returned by Algorithm \\ref{alg:sp}, $\\Call{SPropagation}{{\\cal F},X,Y}$, contains original CPTs from the BN for variables that are independent of $X$    relevant for a query $P(X|Y)$.\nAs shown in \\cite{butzetal16}, all potentials $\\phi(W) \\in {\\cal F}_{SP}$ where $W \\cap X = \\emptyset$ has $W$ d-separated from $X$.\nThus, to test the independence $I(X,Y,Z)$ we only need to check if $Z$ is a subset of the variables from the CPT $\\phi(W)$ where $W \\cap X = \\emptyset$.\n\n\\begin{algorithm}[h]\n    \\caption{Modeling.}\n    \\label{alg:sp_mod}\n    \\begin{algorithmic}[1]\n        \\Procedure{Modeling}{${\\cal F}$, $X$, $Y$, $Z$}\n    \\State ${\\cal F}_{SP}$ = $\\Call{SPropagation}{{\\cal F}, X, Y}$\n    \\State ${\\cal F}_{Rest}$ = $\\{P(v_i|P_i) ~|~ P(v_i|P_i) \\in {\\cal F}_{SP}$ and $F_i \\cap X = \\emptyset\\}$\n    \\State $\\bar{R}$ = $\\{v_i ~|~ P(v_i|P_i) \\in {\\cal F}_{Rest}\\}$    \n    \\Return{$Z \\subseteq \\bar{R}$}\n    \\EndProcedure\n    \\end{algorithmic}\n\\end{algorithm}\n\n\\begin{example}\nGiven a test of independence $I(ijklm, d, a)$ posed to BN ${\\cal B}$ in Figure \\ref{fig:dag}, run Algorithm \\ref{alg:sp_mod} with ${\\cal F} ~=~ \\{P(a)$, $P(b|a)$, $P(c|a)$, $P(d|b,c)$, $P(e|d)$, $P(f|d,e)$, $P(g|e)$, $P(h|e)$, $P(i|d,g)$, $P(j|i)$, $P(k|j)$, $P(l|k)$, $P(m|h,l)\\}$, $X = \\{i,j,k,l,m\\}$, $Y = \\{d\\}$, and $Z = \\{a\\}$.\n\\label{ex:sp_mod}\n\\end{example}\n\nThe important point in Example \\ref{ex:sp_mod} is the use of SP to perform the bulk of the work to test the independence $I(ijklm, d, a)$.\n", "meta": {"hexsha": "6a2d86efdfea0099d086c33e055c9007040edf90", "size": 4891, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "B - The Platform/Paper/sections/new_work.tex", "max_stars_repo_name": "andreeds/cs807-research-tasks", "max_stars_repo_head_hexsha": "6e05e548cfc76302af36cdb81096822b19c84c99", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "B - The Platform/Paper/sections/new_work.tex", "max_issues_repo_name": "andreeds/cs807-research-tasks", "max_issues_repo_head_hexsha": "6e05e548cfc76302af36cdb81096822b19c84c99", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "B - The Platform/Paper/sections/new_work.tex", "max_forks_repo_name": "andreeds/cs807-research-tasks", "max_forks_repo_head_hexsha": "6e05e548cfc76302af36cdb81096822b19c84c99", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.5913978495, "max_line_length": 333, "alphanum_fraction": 0.5890410959, "num_tokens": 1869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.30103805350185414}}
{"text": "% use paper, or submit\n% use 11 pt (preferred), 12 pt, or 10 pt only\n\n\\documentclass[letterpaper, preprint, paper,11pt]{AAS}\t% for preprint proceedings\n%\\documentclass[letterpaper, paper,11pt]{AAS}\t\t% for final proceedings (20-page limit)\n%\\documentclass[letterpaper, paper,12pt]{AAS}\t\t% for final proceedings (20-page limit)\n%\\documentclass[letterpaper, paper,10pt]{AAS}\t\t% for final proceedings (20-page limit)\n%\\documentclass[letterpaper, submit]{AAS}\t\t\t% to submit to JAS\n\n\\usepackage{bm}\n\\usepackage{amsmath}\n\\usepackage{subfigure}\n%\\usepackage[notref,notcite]{showkeys}  % use this to temporarily show labels\n\\usepackage[colorlinks=true, pdfstartview=FitV, linkcolor=black, citecolor= black, urlcolor= black]{hyperref}\n\\usepackage{overcite}\n\\usepackage{footnpag}\t\t\t      \t% make footnote symbols restart on each page\n\n\n% added by Sara\n\\usepackage{enumitem} % for bullet points\n%\\usepackage{graphicx} % for displaying images\n\\graphicspath{ {./Figures/} } % search path for images\n\\usepackage{booktabs} % for making tables in professional style with top and bottom border\n\\usepackage{textcomp} % for degree symbol\n%\\usepackage{fullpage} % for reducing page margins\n%\\usepackage{float}    % to keep figures with text\n%\\usepackage{afterpage} % used with \\afterpage{\\clearpage}... not sure if it's doing anything helpful\n\n\n\n\n\\PaperNumber{15-747}\n\n\n\\begin{document}\n\n\\title{Libration Point Orbit Rendezvous Using Linearized Relative Motion Dynamics and Nonlinear Differential Correction}\n\n\\author{Sara Case\\thanks{Department of Aerospace Engineering, University of Maryland, College Park}}\n\n\\maketitle{} \t\t\n\n\\begin{abstract}\nThis paper presents a technique for computing a rendezvous trajectory with a target satellite in a libration point orbit.  The chaser satellite completes the rendezvous by executing a series of impulsive maneuvers to travel between waypoints approaching the target satellite.  Linearized equations of relative motion of the chaser with respect to the target in the circular restricted three body problem are used to compute the required magnitude and direction of the maneuvers; these results are then refined using differential correction with the nonlinear equations of motion. The performance of this technique is discussed and several rendezvous strategies are evaluated.\n\\end{abstract}\n\n\\section{Introduction}\nLibration point orbit rendezvous is a critical component for many possible satellite mission architectures.  If a large satellite is launched in components and assembled in orbit, the individual components will need to rendezvous and dock prior to assembly.  If a valuable space asset such as a telescope requires an on-orbit repair, the satellite servicing mission will need to rendezvous with the object.  A libration point orbit is a potentially useful place to build a space station, and rendezvous capabilities will be important during the construction of the station as well as every crew and cargo mission to visit the station.\n\nThe history of satellites being deployed to libration point orbits dates back to 1978, when ISEE-3 was launched to the Sun-Earth L1 point. ACE, WIND, SOHO, and DSCOVR are currently orbiting the same point, with the LISA Pathfinder satellite set to join them in 2015.  Several spacecraft have been deployed to the Sun-Earth L2 point, and the ARTEMIS mission explored L1 and L2 in the Earth-Moon system.  Several additional libration point orbiting missions are currently planned, including the James Webb Space Telescope.  So far, all libration point missions have consisted of a single satellite that operates independently of any other satellite.  There has been research on deploying a formation of satellites to fly together around libration points, such as the Terrestrial Planet Finder mission.\\cite{beichman2004}  However, little research has been conducted regarding rendezvous with libration point orbiters. % TODO: (refer to a paper about building a space station at a libration point)\n\nSatellite rendezvous in low-Earth orbit is well-studied, due to many years of experience operating the International Space Station and other applications.  The Hill's/Clohessy-Wiltshire (HCW) equations are frequently used to closely approximate the relative motion of a chaser vehicle with respect to a target vehicle in a circular orbit.\\cite{clohessy1960}  These equations of relative motion are used to compute the approximate \\(\\Delta V\\) (instantaneous change in velocity) to travel between waypoints defining an approach trajectory.  However, for libration point orbits, the dynamical environment is quite different and the same equations of motion are not applicable.  % TODO: (cite rendezvous ISS paper) (mention r-bar, v-bar?)\n\nLuquette has developed linearized equations of relative motion for formation flying in libration point orbits.\\cite{luquette2004}   Lian et al.~have used these linearized dynamics to compute impulses for a chaser satellite to travel between waypoints in order to approach a target orbiting a libration point.\\cite{lian2011}  This paper discusses the results of applying this technique for a set of test cases, and presents an additional step in which the shooting method of differential correction is used to refine the computed \\(\\Delta V\\) for use with the nonlinear equations of motion. It is demonstrated that without the differential correction step, applying the \\(\\Delta V\\) computed using the linear equations of relative motion can lead to significant position errors when modeling the maneuver in a simulation using the nonlinear dynamics.\n\n\\section{Dynamics}\n\n\\subsection{Circular Restricted Three-Body Dynamics}\nThe circular restricted three body problem (CRTBP) deals with two larger objects orbiting each other in a circular orbit and a third object of infinitesimal mass.  Examples include the Trojan asteroids orbiting in the Sun-Jupiter system, or man-made satellites in the Earth-Moon system.  When dealing with the Sun-Earth system, the second body is often modeled by treating the Earth and Moon as a single object at the Earth-Moon barycenter; this is called the Sun-Earth/Moon system.\n\nThe nonlinear equations of motion for a satellite in the CRTBP are:\n\n\\begin{equation} \\label{eq:CRTBP}\n\t\\begin{aligned}\n\t\t\\ddot{x} &= x + 2\\dot{y} + \\frac{(1 - \\mu)(-\\mu - x)}{r_1^3} + \\frac{\\mu(1 - \\mu - x)}{r_2^3} \\\\\n\t\t\\ddot{y} &= y - 2\\dot{x} - \\frac{(1 - \\mu)y}{r_1^3} - \\frac{\\mu y}{r_2^3} \\\\\n\t\t\\ddot{z} &= \\frac{-(1 - \\mu)z}{r_1^3} - \\frac{\\mu z}{r_2^3}\n\t\\end{aligned}\n\\end{equation}\n\nwhere \\(\\mu\\) is the mass ratio of the primary bodies:\n\n\\begin{equation}\n\t\\mu = \\frac{M_2}{M_1 + M_2}\n\\end{equation}\n\nand \\(r_1\\) and \\(r_2\\) are the distances from the larger and smaller bodies to the target satellite:\n\n\\begin{equation}\n\t\\begin{aligned}\n\t\tr_1 &= \\| \\mathbf{x} - \\mathbf{X_1} \\| &= \\sqrt{(x-\\mathbf{X_1}_x)^2 + y^2 + z^2} \\\\\n\t\tr_2 &= \\| \\mathbf{x} - \\mathbf{X_2} \\| &= \\sqrt{(x-\\mathbf{X_2}_x)^2 + y^2 + z^2}\n\t\\end{aligned}\n\\end{equation}\n\nwhere \\(\\mathbf{X_1}\\) and \\(\\mathbf{X_2}\\) are the positions of the larger and smaller bodies along the X-axis of the rotating CRTBP frame:\n\n\\begin{equation}\n\t\\begin{aligned}\n\t\t\\mathbf{X_1} &= \\begin{bmatrix}\n\t\t\t-\\mu \\\\ 0 \\\\ 0 \n\t\t\\end{bmatrix} \\\\\n\t\t\\mathbf{X_2} &= \\begin{bmatrix}\n\t\t\t1 - \\mu \\\\ 0 \\\\ 0\n\t\t\\end{bmatrix}\n\t\\end{aligned}\n\\end{equation}\n\nWhen working in canonical units in the CRTBP, one distance unit is defined by the distance between the primary bodies, one mass unit is defined by the combined mass of the primary bodies, and one time unit is defined by the period of the primary bodies divided by 2\\(\\pi\\).  Finally, the gravitational constant G is also defined as one. Note that as a result, the rotation rate of the system \\(\\omega\\) also evaluates to one. A summary of the canonical units in the CRTBP is provided in Equation~\\eqref{eq:nondimen}.\n\n\\begin{equation} \\label{eq:nondimen}\n\\begin{aligned}\n\\mathrm{1 \\: DU} &= r_{12} = 1 \\\\           % note, \"\\:\" is a medium space\n\\mathrm{1 \\: MU} &= M_1 + M_2 = 1 \\\\\n\\mathrm{1 \\: TU} &= \\frac{P}{2\\pi} = 1 \\\\\n\\mathrm{G} &= 1 \\\\\n\\omega &= \\sqrt{GM/r^3} = 1\n\\end{aligned}\n\\end{equation}\n\n\\subsection{Linearized Relative Motion Dynamics}\nLuquette has derived linearized equations of relative motion of a chaser satellite with respect to a target satellite orbiting in the restricted three body problem (RTBP).\\cite{luquette2004} The RTBP is distinct from the CRTBP discussed above in that the RTBP provides the option to model the primary bodies in an elliptic orbit instead of a circular orbit around each other; the rotation rate of the system is therefore a function of time. Luquette provides the equations of relative motion in two reference frames: the inertial frame as well as the rotating (RTBP) frame.  These equations of motion are valid anywhere in the RTBP system; they are not assumed to be near any specific libration point.  They are also useful for analyzing relative motion around any type of libration point orbit, such as Lyapunov, halo, or Lissajous orbits. \n\nIn this work, the equations of motion as given in the rotating reference frame are used. These equations are functions of the offset state of the chaser vehicle with respect to the target vehicle in the rotating frame, the position of the target vehicle in the rotating frame with respect to the origin, the mass ratio of the primary bodies, and the rotation rate of the rotating frame.\n\n% TODO: Should I also include the inertial version of the relmo EOM's from Luquette?  I only used the rotating frame version, but maybe the inertial version should also be provided for completeness.  Could simply say that the inertial version doesn't have the \\(\\omega\\) terms and all the vectors are in the inertial frame instead of CRTBP.\n\nThe linearized equations of relative motion of a chaser satellite with respect to a target satellite, given in the RTBP reference frame, are:\n\n\\begin{equation} \\label{eq:RelmoDerivs}\n\t\\dot{\\boldsymbol{\\xi}}_R = \\mathbf{A}_R(t)\\boldsymbol{\\xi}_R\n\\end{equation}\n\nwhere \\(\\boldsymbol{\\xi}_R\\) is the offset state of the chaser vehicle with respect to the target vehicle in the rotating frame:\n\n\\begin{equation}  % Note, R is for \"rotating\" and C is for \"chaser\"\n\t\\boldsymbol{\\xi}_R = \\begin{bmatrix}\n\t\t\\mathbf{x}_c \\\\\n\t\t\\dot{\\mathbf{x}}_c\n\t\\end{bmatrix}_R\n\\end{equation}\n\nand  \\(\\mathbf{A}_R(t)\\) is the 6\\(\\times\\)6 linearized relative motion dynamics matrix in the rotating frame: % note, in the paper I'm citing, he says \\(-2 [\\boldsymbol{\\omega} \\times]^T\\), but in his PhD it just says \\(-2 [\\boldsymbol{\\omega} \\times]\\) which seems to be correct\n\n\\begin{equation} \\label{eq:RelmoDynMatrix}\n\t\\mathbf{A}_R(t) = \\begin{bmatrix}\n\t\t\\mathbf{0}          & \\mathbf{I_3} \\\\\n\t\t\\mathbf{\\Xi}_R(t) & -2 [\\boldsymbol{\\omega} \\times]\n\t\\end{bmatrix}\n\\end{equation}\n\nwhere\n\n\\begin{equation}\n\t\\mathbf{\\Xi}_R(t) = -(c_1 + c_2)\\mathbf{I_3} \n\t+ 3c_1\\mathbf{\\hat{r}_1}(t) \\mathbf{\\hat{r}_1}(t)^T \n\t+ 3c_2\\mathbf{\\hat{r}_2}(t) \\mathbf{\\hat{r}_2}(t)^T \n\t+ [\\boldsymbol{\\dot{\\omega}} \\times] \n\t- [\\boldsymbol{\\omega}\\times][\\boldsymbol{\\omega}\\times]\n\\end{equation}\n\nand\n\n\\begin{equation}\n\t\\begin{aligned}\n\t\tc_1 &= \\frac{1- \\mu}{r_1^3} \\\\\n\t\tc_2 &= \\frac{\\mu}{r_2^3}\n\t\\end{aligned}\n\\end{equation}\n\nNote that \\(\\boldsymbol{\\omega}\\) is the rotation rate of the rotating RTBP frame with respect to the inertial frame:\n\\begin{equation}\n\t\\boldsymbol{\\omega} = \\begin{bmatrix}\n\t\t0 \\\\ \n\t\t0 \\\\\n\t\t\\omega\n\t\\end{bmatrix}\n\\end{equation}\n\nThe notation  \\([\\boldsymbol{\\omega}\\times]\\) refers to the cross-product matrix of \\(\\boldsymbol{\\omega}\\):\n\\begin{equation}\n\t[\\boldsymbol{\\omega}\\times] = \\begin{bmatrix}\n\t\t0           & -\\omega & 0 \\\\ \n\t\t\\omega & 0             & 0 \\\\\n\t\t0           & 0             & 0\n\t\\end{bmatrix}\n\\end{equation}\n\nAlso note that if we assume that the rotation rate of the RTBP frame is constant (that is, assume we can use the CRTBP where the massive bodies are in circular orbits around each other), then the \\(\\boldsymbol{\\dot{\\omega}}\\) term cancels to zero.\n\nThese equations of motion do not include any model of solar radiation pressure (SRP) and assume that neither satellite is applying any propulsive thrusting force to perturb or change their orbits. \n\nIn order to integrate a chaser satellite's trajectory using the equations of relative motion given in Equation~\\eqref{eq:RelmoDerivs}, the integration state vector must contain the absolute state of the target satellite in the RTBP frame (with respect to the origin of the RTBP frame) and the relative state of the chaser satellite in the RTBP frame (with the origin located at the target satellite).  If using the CRTBP assumption, then the target satellite's state over time can be integrated using the classical CRTBP equations of motion as given in Equation~\\eqref{eq:CRTBP}, which must be done concurrently with the integration of the relative motion of the chaser so that the time-dependent linearized relative motion dynamics matrix \\(\\mathbf{A}_R(t)\\) given in Equation~\\eqref{eq:RelmoDynMatrix} can be computed. The CRTBP model is employed in the test cases presented in this work.\n\n\\section{Traveling Between Waypoints with Impulsive $\\Delta$V's}\nThe concept of waypoints can be used to divide a rendezvous approach trajectory into a series of shorter segments.  The starting and ending waypoints of a segment are defined with respect to the location of a target satellite.  When considering rendezvous with a satellite in a circular orbit, the HCW equations supply a linearized dynamics model for a chaser satellite with respect to a target satellite.  The inverse of the linear dynamics matrix is used to compute the velocity required to travel from one waypoint to the next within a specified amount of time.  This approach is applied in the CRTBP using the linear dynamics matrix presented in Equation~\\eqref{eq:RelmoDynMatrix} by following the procedure below. \n\n\\subsection{Using the Linearized Relative Motion Dynamics Matrix to Compute \\(\\Delta\\)V}\n\nThe linearized relative motion dynamics matrix given in Equation~\\eqref{eq:RelmoDynMatrix} can be used to numerically accumulate a State Transition Matrix (STM), \\(\\boldsymbol{\\Phi}\\), of the chaser satellite with respect to the target satellite over time:\n\n\\begin{equation} \\label{eq:STM}\n\t\\dot{\\boldsymbol{\\Phi}} = \\mathbf{A}_R(t)\\boldsymbol{\\Phi}\n\\end{equation}\n\nThe initial ``state vector\" for the STM passed to the integration process should be the \\(6\\times6\\) identity matrix, \\(\\mathbf{I_6}\\).  As above, the STM must be integrated concurrently with the target satellite's state because of the time-dependence in \\(\\mathbf{A}_R(t)\\).  When integrated from the initial state at time \\(t_i\\) to a future time \\(t_{i+1}\\), this accumulated State Transition Matrix represents the relative position and velocity of the chaser at time \\(t_{i+1}\\) with respect to its relative position and velocity at time \\(t_i\\).  More explicitly:\n\n% TODO!!!: need to make notation consistent; should it be r, v or x, xdot, or xi, xidot, or what\n\n\\begin{equation}\n\t\\begin{bmatrix}\n\t\t\\mathbf{r}_{i+1} \\\\\n\t\t\\mathbf{v}_{i+1}\n\t\\end{bmatrix}\n\t= \n\t\\begin{bmatrix}\n\t\t\\boldsymbol{\\Phi}_{11} & \\boldsymbol{\\Phi}_{12} \\\\\n\t\t\\boldsymbol{\\Phi}_{21} & \\boldsymbol{\\Phi}_{22}\n\t\\end{bmatrix}\n\t\\begin{bmatrix}\n\t\t\\mathbf{r}_i \\\\\n\t\t\\mathbf{v}_i\n\t\\end{bmatrix}\n\\end{equation}\n\nAnalogous to the use of the HCW equations in the two-body problem, this STM can be used to compute the required velocity \\(\\mathbf{v}_i^+\\) for a chaser satellite in a CRTBP system to travel from waypoint \\(\\mathbf{r}_i\\) to waypoint \\(\\mathbf{r}_{i+1}\\) in time \\( \\Delta t = t_{i+1} - t_i\\).  This approach was employed by Lian et al.~using the RTBP relative motion dynamics derived by Luquette (see Reference \\citenum{lian2011}). \n\n% TODO: maybe note: Lian et. al. used the equations with J2000 reference axes and equations of motion written in J2000, rather than the rotating frame (RTBP) version being used here.\n\n% TODO: cite additional Lian papers.\n\n\\begin{equation} \\label{eq:RequiredVelocity}\n\t\\mathbf{v}_i^+ = \\boldsymbol{\\Phi}_{12}^{-1}(\\mathbf{r}_{i+1} - \\boldsymbol{\\Phi}_{11}\\mathbf{r}_i)\n\\end{equation}\n\nThe instantaneous change in velocity (\\(\\Delta V\\)) for a maneuver at waypoint \\(\\mathbf{r}_i\\) is then simply the difference between the required (post-maneuver) velocity and the velocity that the chaser satellite had before the maneuver:\n\n\\begin{equation} \\label{eq:DeltaV}\n\t\\Delta \\mathbf{v}_i = \\mathbf{v}_i^+ - \\mathbf{v}_i^-\n\\end{equation}\n\n\\subsection{Shooting Method with Nonlinear Dynamics} \\label{sec:shooting}\nThe approach described above for computing \\(\\Delta V\\) is based on the linearized equations of relative motion developed by Luquette.  Of course, the true dynamical environment in the CRTBP is nonlinear, as seen in Equation~\\eqref{eq:CRTBP}. The linear-based approximation of \\(\\Delta V\\) can be corrected for use with this nonlinear propagation model using the shooting method of differential correction.  The linear-based approximated velocity is used as an initial guess for this iterative process.  Following the procedure below, each of the three components of the velocity vector is varied in order to achieve convergence in the CRTBP on the desired three-dimensional waypoint \\(\\mathbf{w}_{\\mathrm{desired}}\\) within some specified tolerance.\n\n\\begin{enumerate}[leftmargin=!,labelindent=12pt,itemindent=0pt, label=Step \\arabic*:]\n\t\n\t\\item Using the initial guess for the chaser relative velocity \\(\\mathbf{v}_i^+\\) from Equation~\\eqref{eq:RequiredVelocity}, propagate both the target and chaser satellite from time \\(t_i\\) to \\(t_{i+1}\\) using the nonlinear CRTBP equations of motion given in Equation~\\eqref{eq:CRTBP} and compute the nominally achieved waypoint \\(\\mathbf{w}\\).\n\t\n\t\\item Add to the x-component of the chaser's velocity a pre-chosen scalar value, called the perturbation.  Propagate both satellites from time \\(t_i\\) to \\(t_{i+1}\\) a second time using this perturbed velocity and compute the achieved waypoint \\(\\mathbf{w}'\\).\n\t\n\t\\item Compute the difference between \\(\\mathbf{w}\\) and \\(\\mathbf{w}'\\), \\(\\frac{d\\mathbf{w}}{dv_x}\\).\n\t\n\t\\item Reset the x-component of the velocity to its original value, and repeat steps 2 and 3 when perturbing the y-component of the velocity.\n\t\n\t\\item Reset the y-component of the velocity to its original value, and repeat steps 2 and 3 when perturbing the z-component of the velocity.\n\t\n\t\\item Gather the results into a partial derivatives matrix, \\(\\mathbf{M}\\):\n\t\n\t\\begin{equation} \\label{eq:ShootingMethodPartialDerivs}\n\t\t\\mathbf{M} = \\left[ \\frac{d\\mathbf{w}}{d\\mathbf{v}} \\right]\n\t\t= \\begin{bmatrix}\n\t\t\t\\frac{dw_x}{dv_x} & \\frac{dw_y}{dv_x} & \\frac{dw_z}{dv_x} \\\\[0.3em]\n\t\t\t\\frac{dw_x}{dv_y} & \\frac{dw_y}{dv_y} & \\frac{dw_z}{dv_y} \\\\[0.3em]\n\t\t\t\\frac{dw_x}{dv_z} & \\frac{dw_y}{dv_z} & \\frac{dw_z}{dv_z}\n\t\t\\end{bmatrix}\n\t\\end{equation}\n\t\n\t\\item Compute an updated estimate of the velocity required to travel to the desired location \\(\\mathbf{w}_{\\mathrm{desired}}\\):\n\t\n\t\\begin{equation} \\label{eq:ShootingMethodUpdate}\n\t\t\\mathbf{v}_i^+ = \\mathbf{v}_i^+ + [\\mathbf{M}]^{-1}(\\mathbf{w}_{\\mathrm{desired}} - \\mathbf{w})\n\t\\end{equation}\n\t\n\t\\item Repeat steps 1 through 7 until all three components of \\(\\mathbf{w}\\) converge to \\(\\mathbf{w}_{\\mathrm{desired}}\\) within some tolerance.\n\t\n\\end{enumerate}\n\n% TODO: (Need to go through all section 2 and section 3 equations/symbols and make symbol usage consistent.)\n\n\\subsection{Definition of Waypoint Reference Frames}\nIn this work, local RIC (Radial, In-track, Cross-track) and VNB (Velocity, Normal, Binormal) reference frames are defined with respect to the target satellite's orbit around its libration point. These local reference frames are used to define the locations of the rendezvous trajectory waypoints. Each of these frames will rotate once for each full orbit of the target around the libration point, with the origin of both frames located at the target satellite's position.\n\nThe two libration points of most interest for this work are \\(L_1\\) and \\(L_2\\).  The position of \\(L_1\\) in the CRTBP frame is found by computing the real root \\(l_1\\) of this polynomial in \\(x\\):\n\n\\begin{equation} \\label{eq:L1}\n\t(1 - \\mu)(p^3)(p^2 - 3p + 3) - \\mu(p^2 + p + 1)(1 - p)^3 = 0\n\\end{equation}\n\nwhere:\n\n\\begin{equation}\n\tp = 1 - \\mu - x\n\\end{equation}\n\nThe coordinates of \\(L_1\\) are then \\([l_1, 0, 0]\\) in the CRTBP frame.  Likewise, the position of \\(L_2\\) in the CRTBP frame is found by computing the real root \\(l_2\\) of this polynomial in \\(x\\):\n\n\\begin{equation} \\label{eq:L2}\n\t(1 - \\mu)(p^3)(p^2 + 3p + 3) - \\mu(p^2 + p + 1)(1 - p)(p + 1)^2 = 0\n\\end{equation}\n\nwhere:\n\n\\begin{equation}\n\tp = \\mu - 1 + x\n\\end{equation}\n\nThe coordinates of \\(L_2\\) are then \\([l_2, 0, 0]\\) in the CRTBP frame.\n\nThe local RIC and VNB reference frames are then defined with the origin of each of these frames located at the target satellite's position.  The RIC frame as has its first primary axis the vector pointing from the libration point radially out to the target satellite in the CRTBP frame.  For example, in the case of a target satellite orbiting \\(L_1\\), the fundamental \\(\\mathbf{\\hat{R}}\\), \\(\\mathbf{\\hat{I}}\\), and \\(\\mathbf{\\hat{C}}\\) axes of the RIC frame are defined as:\n\n\\begin{equation} \\label{eq:RIC}\n\t\\begin{aligned}\n\t\t\\mathbf{\\hat{R}} &= \\frac{\\mathbf{x} - \\mathbf{L}_1}{\\| \\mathbf{x} - \\mathbf{L}_1 \\|} \\\\\n\t\t\\mathbf{\\hat{C}} &= \\frac{\\mathbf{R} \\times \\mathbf{\\dot{x}}}{\\| \\mathbf{R} \\times \\mathbf{\\dot{x}} \\|} \\\\\n\t\t\\mathbf{\\hat{I}} \\, &= \\frac{\\mathbf{C} \\times \\mathbf{R}}{\\| \\mathbf{C} \\times \\mathbf{R} \\|}\n\t\\end{aligned}\n\\end{equation}\n\nwhere \\(\\mathbf{x}\\) and \\(\\mathbf{\\dot{x}}\\) are the target satellite's position and velocity vectors in the CRTBP frame.\n\nThe VNB frame has as its first primary axis the target satellite's velocity vector in the CRTBP frame.  In the case of a target satellite orbiting \\(L_1\\), the fundamental \\(\\mathbf{\\hat{V}}\\), \\(\\mathbf{\\hat{N}}\\), and \\(\\mathbf{\\hat{B}}\\) axes of the VNB frame are defined as:\n\n\\begin{equation} \\label{eq:VNB}\n\t\\begin{aligned}\n\t\t\\mathbf{\\hat{V}} &= \\frac{\\mathbf{\\dot{x}}}{\\| \\mathbf{\\dot{x}} \\|} \\\\\n\t\t\\mathbf{\\hat{N}} &= \\frac{\\mathbf{R} \\times \\mathbf{V}}{\\| \\mathbf{R} \\times \\mathbf{V} \\|}  \\\\\n\t\t\\mathbf{\\hat{B}} &= \\frac{\\mathbf{V} \\times \\mathbf{N}}{\\| \\mathbf{V} \\times \\mathbf{N} \\|} \n\t\\end{aligned}\n\\end{equation}\n\n\\section{Results}\n\n\\subsection{Performance of Linear \\(\\Delta\\)V Estimate and Shooting Method}\n\nTo begin evaluating the performance of the techniques presented above, consider the following scenario.  The target satellite is in a planar Lyapunov orbit around the Earth-Moon L1 point as shown in Figure~\\ref{fig:FullOrbit_1}.  The target satellite's initial conditions are presented in Table~\\ref{tab:IC_1} in canonical units.  For this test, the rendezvous starts with the target satellite at the location indicated by the asterisk on the CRTBP X-axis, that is, crossing the XZ-plane.\n\n\\begin{table}[htbp] \n\t\\fontsize{10}{10}\\selectfont\n\t\\caption{Initial Conditions of the Target Satellite in the CRTBP Frame}\n\t\\label{tab:IC_1}\n\t\\centering\n\t\\begin{tabular}{l l}\n\t\t\\hline \n\t\tParameter   & Value \\\\\n\t\t\\hline \n\t\tX (DU)                & 0.862307159058101 \\\\\n\t\tZ (DU)                & 0.0 \\\\\n\t\t\\(\\dot{Y}\\) (DU/TU)      & -0.187079489569182 \\\\\n\t\tPeriod (TU)           & 2.79101343456226 \\\\\n\t\t\\hline \n\t\\end{tabular}\n\\end{table}\n\n\\begin{figure}[htb]\n\t\\begin{center}\n\t\t\\includegraphics[width=0.9\\textwidth]{Target_Full_Orbit_1}\n\t\t\\caption{Target Satellite Orbit in Earth-Moon L1 CRTBP Frame}\n\t\t\\label{fig:FullOrbit_1}\n\t\\end{center}\n\\end{figure}\n\nTo convert between canonical and dimensional units, the relevant properties of the Earth-Moon CRTBP system are presented in Table~\\ref{tab:Environment_1}.   \n\n\\begin{table}[htbp] \n\t\\fontsize{10}{10}\\selectfont\n\t\\caption{Earth-Moon CRTBP Parameters}\n\t\\label{tab:Environment_1}\n\t\\centering\n\t\\begin{tabular}{l l}\n\t\t\\hline\n\t\tParameter   & Value \\\\\n\t\t\\hline\n\t\tEarth mass (kg) & 5.97219e24 \\\\\n\t\tMoon mass (kg) & 7.34767309e22 \\\\\n\t\tMass ratio \\(\\mu\\)      & 0.012277471 \\\\\n\t\tCombined mass (kg), or 1 MU & 6.045667e24 \\\\\n\t\t\\(r_{12}\\) (km), or 1 DU & 384400.0 \\\\\n\t\tTime Constant (s), or 1 TU & 375201.9 \\\\\n\t\tPeriod of Moon around Earth (s) & 2\\(\\pi\\)TU \\\\\n\t\t\\hline\n\t\\end{tabular}\n\\end{table}\n\nThree waypoints are defined for the chaser satellite to travel between on its rendezvous with the target, with a final waypoint located at the target satellite itself.  The waypoint locations are presented in Table~\\ref{tab:Waypoints_1} in the RIC reference frame.  The waypoints are converted into the CRTBP frame for the propagation.  Note that these waypoints represent an approach along the \\(\\mathbf{I}\\) axis of the RIC frame. \n\n\\begin{table}[htbp] \n\t\\fontsize{10}{10}\\selectfont\n\t\\caption{Waypoints in RIC Frame}\n\t\\label{tab:Waypoints_1}\n\t\\centering\n\t\\begin{tabular}{ccccc}\n\t\t\\hline\n\t\tWaypoint   & Time (days) & R (km) & I (km) & C (km) \\\\\n\t\t\\hline\n\t\t1 & 0.00 & 0.0 & 15.0 & 0.0 \\\\\n\t\t2 & 0.36 & 0.0 & 5.0 & 0.0 \\\\\n\t\t3 & 0.97 & 0.0 & 1.0 & 0.0 \\\\\n\t\t4 & 1.59 & 0.0 & 0.0 & 0.0 \\\\\n\t\t\\hline\n\t\\end{tabular}\n\\end{table} \n\nFigure~\\ref{fig:RIC_1} shows the result of propagating the target and chaser satellite through a rendezvous using these waypoints.  The integration is performed in the CRTBP frame, and the results are converted to the RIC frame for visualization, with the target satellite at the origin and the chaser satellite offset with respect to the target shown in kilometers.  The green curve shows the path of the chaser satellite when propagated using the linear relative motion dynamics as given in Equation~\\eqref{eq:RelmoDerivs}, with the application of impulsive \\(\\Delta V\\)'s as computed using Equation~\\eqref{eq:RequiredVelocity}.  The model employed to compute the impulsive maneuvers matches the linear propagation model, and so the chaser satellite travels precisely to each waypoint.  The red curve shows the result when the chaser satellite is propagated using the nonlinear CRTBP dynamics as shown in Equation~\\eqref{eq:CRTBP} when the nominal \\(\\Delta V\\)s (as computed using the linear model) are still applied.  It is easily seen that the nominally planned maneuvers do not bring the chaser exactly to the desired waypoints when propagating with the nonlinear model. In this test, the trajectory is then reset to start at the correct waypoint in order to visualize the trajectory for the next segment. Finally, the blue curve shows the result when the chaser satellite is propagated using the nonlinear CRTBP dynamics and the \\(\\Delta V\\)s have been corrected (or ``targeted\") through the iterative differential correction procedure described above.  The path does not precisely match the original green curve due to the different dynamical models in use; however, each waypoint is achieved successfully.  % TODO: (Also note that the image axes are not scaled equally.)\n\n\\begin{figure}[htb] \n\t\\begin{center}\n\t\t\\includegraphics[width=0.9\\textwidth]{RIC_1}\n\t\t\\caption{Relative Motion of a Chaser Satellite with respect to a Target}\n\t\t\\label{fig:RIC_1}\n\t\\end{center}\n\\end{figure} % TODO: add more context/description to the captions for the plots\n\nThe results for this case are also summarized in Table~\\ref{tab:Results_1}.  To compute the first \\(\\Delta V\\), the chaser satellite is assumed to start precisely at waypoint 1 with its pre-maneuver velocity at waypoint 1 equal to the target satellite's initial velocity in the CRTBP frame.  The final maneuver at waypoint 4 is computed to equalize the chaser's velocity with the target satellite's velocity for a completed rendezvous.\n\nWe can note that, while the difference in \\(\\Delta V\\) magnitude is quite small between the linear computation and the differentially corrected computation, on the order of millimeters/second, the angular difference between the two \\(\\Delta V\\) vectors is more significant, reaching almost 6\\textdegree \\- at waypoint 3.  These differences result in achieved position errors on the order of hundreds of meters at each waypoint when the linear approximation is applied in the nonlinear propagation model; the errors are reduced to the order of centimeters when the differential correction procedure is applied.\n\nRegarding the tuning parameters of the differential correction procedure, the perturbation value for the velocity components was set to 1e-5 DU/TU (or speed units, SU), which equals about 1.0 centimeters/second.  The tolerance on the achieved waypoints was set to 1e-9 DU, or about 0.38 meters.  \n\n% Python Configuration for these results:\n% halo_cases = ['EM']\n% clock_angles = np.array([0.0])\n%approach_cases = ['+R', '-R', '+I', '-I', '+C', '-C']\n%timescales = ['fast', 'medium', 'slow']\n%spacings = ['close', 'medium', 'far']\n% not used at this time: timescales, spacings\n%halo = halo_cases[0]\n%clock_angle = clock_angles[0]\n% approach = '+I'\n%timescale = timescales[0]\n%spacing = spacings[0]\n\n% TODO: say this, maybe: The maximum number of allowed iterations was set to 10, meaning that if the desired tolerance is not achieved within 10 iterations, the process will continue with the value achieved by the \\(10^{th}\\) iteration.  \n\n% TODO: discuss how many iterations were actually used.  \n\n% TODO: add this comment: (Note that we use the *new* achieved waypoint to re-compute the linear dV estimate for the next waypoint before then targeting the next waypoint)\n\n\\begin{table}[htbp] \n\t\\fontsize{10}{10}\\selectfont\n\t\\caption{\\(\\Delta\\)V and Position Error Summary at each Waypoint}\n\t\\label{tab:Results_1}\n\t\\centering\n\t\\begin{tabular}{c p{0.8 cm} p{1.2 cm} p{1 cm} p{1 cm} p{1.3cm} p{1.3cm}}\n\t\t\\hline\n\t\tWaypoint   & Linear \\(\\Delta V\\) & Corrected \\(\\Delta V\\) & \\(\\Delta V\\)  \\mbox{Angle} Difference & \\(\\|\\Delta V \\|\\) Difference & Position \\mbox{Error}, Linear \\(\\Delta V\\) & Position \\mbox{Error}, \\mbox{Corrected} \\(\\Delta V\\) \\\\\n\t\t& (m/s) & (m/s) & (deg) & (m/s) & (m) & (m) \\\\\n\t\t\\hline\n\t\t1 & 0.346 &\t0.345 &\t0.466 &\t-0.001 &\tN/A &\tN/A \\\\\n\t\t2 & 0.293 &\t0.295 &\t2.609 &   0.002 &\t91.394 &\t0.011 \\\\\n\t\t3 & 0.064 &\t0.059 &\t5.890 &\t-0.005 &\t470.653 &\t0.063 \\\\\n\t\t4 & 0.019 &\t0.018 &\t0.445 &\t-0.001 &\t107.663 &\t0.056 \\\\\n\t\tTotal & 0.722  & 0.717 & 9.410 & 0.008 & 669.709 & 0.131 \\\\\n\t\t\\hline\n\t\\end{tabular}\n\\end{table}\n\n% \\afterpage{\\clearpage}  %TODO: remove this line and others like this\n\n\\subsection{Rendezvous Initial Clock Angle}\n\nThis technique can be used to evaluate the relative \\(\\Delta V\\) cost of performing a rendezvous at different points along a target spacecraft's orbit.  The following orbital plots present twelve test cases that each begin with the target satellite at a different ``clock angle\" in its orbit; each test case is separated by one twelfth of an orbit in time, with the twelve starting positions indicated by the asterisks shown in Figure~\\ref{fig:FullOrbit_2}.\n\n\\begin{figure}[htb] \n\t\\begin{center}\n\t\t\\includegraphics[width=0.9\\textwidth]{Target_Full_Orbit_2}\n\t\t\\caption{Twelve Target Satellite Initial Conditions}\n\t\t\\label{fig:FullOrbit_2}\n\t\\end{center}\n\\end{figure}\n\nEach of these twelve rendezvous sequences are computed using the same waypoint locations along the \\(\\mathbf{I}\\) axis of the RIC frame as shown in Table~\\ref{tab:Waypoints_1}.  However, due to the differing local curvature of the target orbit at each of the twelve starting locations, the relative motion patterns in the RIC frame for each rendezvous are different, as shown in Figure~\\ref{fig:RIC_2}.  \n\n\\begin{figure}[htb] \n\t\\begin{center}\n\t\t\\includegraphics[width=0.9\\textwidth]{RIC_2}\n\t\t\\caption{Rendezvous using 12 Different Initial Clock Angles}\n\t\t\\label{fig:RIC_2}\n\t\\end{center}\n\\end{figure}\n\nWhen viewed using the CRTBP reference frame's rotating axes as in Figure~\\ref{fig:RLP_2}, it is more intuitively seen that each of these in-track rendezvous sequences approach the target satellite from a different direction in the CRTBP frame, due to the rotation of the RIC frame with the target satellite's orbit.\n\n\\clearpage\n\n\\begin{figure}[htb] \n\t\\begin{center}\n\t\t\\includegraphics[width=0.9\\textwidth]{RLP_2} % scale=0.5\n\t\t\\caption{Rendezvous using 12 Different Initial Clock Angles; CRTBP Axes}\n\t\t\\label{fig:RLP_2}\n\t\\end{center}\n\\end{figure}\n\nThe same rendezvous was then computed for 360 test cases with the initial conditions spaced evenly in time around the same libration point orbit, in order to examine the trends in total \\(\\Delta V\\) to complete the rendezvous as a function of the initial clock angle. The total \\(\\Delta V\\) is shown in Figure~\\ref{fig:DV_2} as a function of the initial clock angle; the magnitude of both the linear approximated \\(\\Delta V\\) and the nonlinear corrected \\(\\Delta V\\) are shown.  From this we can see that the total \\(\\Delta V\\) cost does not change dramatically when the initial clock angle is varied; however the peak costs are at initial clock angles of 0\\textdegree \\- and 180\\textdegree.  This trend is apparent in the linear approximation of the \\(\\Delta V\\) as well as in the corrected or ``targeted\" results; this means that the linear approximation may safely be used in this case to provide order-of-magnitude indications of the relative costs of the different rendezvous sequences.\n\n\\begin{figure}[htb] \n\t\\begin{center}\n\t\t\\includegraphics[width=0.8\\textwidth]{Total_DV_2_1degsteps} \n\t\t\\caption{Total Rendezvous \\(\\Delta\\)V for Different Initial Clock Angles}\n\t\t\\label{fig:DV_2}\n\t\\end{center}\n\\end{figure}\n\nAlthough the differences in the magnitude of the \\(\\Delta V\\) vector are not large when comparing the linear approximation to the nonlinear differential correction, the direction of the \\(\\Delta V\\) vector is sometimes quite different. The angle between these two \\(\\Delta V\\) vectors, summed up over each impulse of the rendezvous, is shown in Figure~\\ref{fig:DVAngle_2}.\n\n\\begin{figure}[htb] \n\t\\begin{center}\n\t\t\\includegraphics[width=0.8\\textwidth]{DV_Angle_Diff_2_1degsteps} \n\t\t\\caption{Total Rendezvous \\(\\Delta\\)V Angle Difference for Different Initial Clock Angles}\n\t\t\\label{fig:DVAngle_2}\n\t\\end{center}\n\\end{figure}\n\nThe total rendezvous position error, summed up over waypoints 2 through 4, is shown in Figure~\\ref{fig:PosErr_2} as a function of the initial clock angle.  The position error when the linear approximated \\(\\Delta V\\) is applied in the nonlinear model is on the order of 1 km, while the order of magnitude of the position error after the differential correction has been applied is 10 cm, which was about the tolerance level of the correction algorithm and could even be improved with more differential correction iterations.\n\n\\clearpage \n\n\\begin{figure}[htb] \n\t\\begin{center}\n\t\t\\includegraphics[width=0.8\\textwidth]{Log_Position_Error_2_1degsteps} \n\t\t\\caption{Total Rendezvous Position Error for Different Initial Clock Angles}\n\t\t\\label{fig:PosErr_2}\n\t\\end{center}\n\\end{figure}\n\n\\section{Conclusions}\nThis procedure and the types of metrics presented in the plots discussed above can be used to evaluate other rendezvous approach strategies, such as approaching the target satellite from a different direction, or with different waypoint spacing and time intervals, or in a different target orbit.\n\nGoing forward, there is much that can be done to further develop this procedure. The procedure should be tested against many more rendezvous scenarios, to identify when the procedure works well and when it may fail (in particular, it will be useful to characterize when the linear approximation is not good enough to compute a useful initial \\(\\Delta V\\) approximation). The nonlinear differential correction step of the procedure can be expanded to model not only the CRTBP dynamics, but the full planetary ephemeris model. These enhancements to the procedure will allow analysis to determine whether the linear approximation is generally accurate enough to establish the \\(\\Delta V\\) budget for a rendezvous sequence, or if the nonlinear differential correction step is necessary even early in the mission design process.\n\nThis procedure can be used to search for trends in rendezvous \\(\\Delta V\\) cost as a function of the total time of flight, approach direction, and the target orbit size and shape. The safety of a given rendezvous configuration can also be studied: for example, if a maneuver at one of the rendezvous waypoints is missed for some reason, is the configuration of the two satellites passively safe? As with low-Earth orbit rendezvous, this type of safety concern will be important to consider when designing rendezvous sequences.\n\n\n% Python Configuration for these results:\n%halo_cases = ['EM']\n%clock_angles = np.arange(0.0, 360.0, 30.0)  or np.arange(0.0, 360.0, 1.0), etc\n%halo = halo_cases[0]\n%clock_angle = clock_angles[0]\n%approach = '+I'\n%timescale = timescales[0]\n%spacing = spacings[0]\n\n% More TODO's:\n\n% Show cases where we approach from different directions (+/-R, +/-I, +/-C)\n\n% Evaluate relative cost of approaching in different ways\n\n% From ASC abstract: The robustness of the procedure, with respect to the convergence of the differential corrector using the initial guess from the linear model, also depends on properties of the rendezvous such as the time allowed and distance traveled between waypoints.\n\n% Distance (maybe percentage of orbit covered?) where this technique doesn't work\n\n% Seems like shorter times maybe gives better behavior of the linear dV estimate?  Longer time = more need to use the targeter?\n\n% What if naive initial guess was supplied?  would that require more iterations?\n\n% Show what happens if you miss a maneuver\n\n% Show what happens if you don't reset the linear approximated dV path back to the next waypoint\n\n% Kinda interesting to show in RLP, VNB\n\n% Maybe talk about measuring the \"excursion\" of the trajectory (perpendicular to the vector from one waypoint to the next)\n\n\n\\section{Acknowledgment}\nThe author wishes to thank Brent Barbee for his encouragement to pursue this topic of research.\n\n\n\\bibliographystyle{AAS_publication}   % Number the references.\n\\bibliography{references_Case}   % Use references.bib to resolve the labels.\n\n\\end{document}\n", "meta": {"hexsha": "f03f0f78dba8712ed8cc5f5cdd4a55779d9771a0", "size": 38029, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ASC 2015/Pre-print/LPORendezvous_Case_AAS_Preprint.tex", "max_stars_repo_name": "aerosara/thesis", "max_stars_repo_head_hexsha": "55bd84e8d4b4bffa8f7526bd5b94ddef80911f99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ASC 2015/Pre-print/LPORendezvous_Case_AAS_Preprint.tex", "max_issues_repo_name": "aerosara/thesis", "max_issues_repo_head_hexsha": "55bd84e8d4b4bffa8f7526bd5b94ddef80911f99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ASC 2015/Pre-print/LPORendezvous_Case_AAS_Preprint.tex", "max_forks_repo_name": "aerosara/thesis", "max_forks_repo_head_hexsha": "55bd84e8d4b4bffa8f7526bd5b94ddef80911f99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 67.5470692718, "max_line_length": 1778, "alphanum_fraction": 0.7458781456, "num_tokens": 10539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3010380535018541}}
{"text": "\\documentclass[12pt,a4paper]{article}\n\n\\usepackage[centertags,reqno]{amsmath}\n\\usepackage{verbatim}\n\n\\newcommand{\\OCCAL}{{\\sf\\bf OCCAL}}\n\\newcommand{\\REDUCE}{{\\sf\\bf REDUCE}}\n\\newcommand{\\R}{\\mbox{{\\sf\\bf R}}}\n\\newcommand{\\FORTRAN}{{\\sf FORTRAN}}\n\\newcommand{\\RATFOR}{{\\sf RATFOR}}\n\\newcommand{\\Pascal}{{\\sc Pascal}}\n\\newcommand{\\C}{{\\sf C}}\n\\newcommand{\\GENTRAN}{{\\sf GENTRAN}}\n\\newcommand{\\MULCON}{{\\sf MULCON}}\n\\newcommand{\\SCOPE}{{\\sf SCOPE}}\n\\newcommand{\\perl}{{\\sf perl}}\n\n\\renewcommand{\\and}{\\quad}\n\n\\newlength{\\dummy}\n\\settowidth{\\dummy}{Appendix~\\mbox{}}\n\\addtolength{\\dummy}{3mm}\n\n\\title{OCCAL\\\\\n       A mixed symbolic-numeric\\\\\n       Optimal Control CALculator}\n\n\\date{ }\n\n\\author{Rainer Sch\\\"opf\n        \\and\n        Peter Deuflhard\n        \\\\\n        Konrad-Zuse-Zentrum\\\\\n        f\\\"ur Informationstechnik Berlin\\\\\n        Heilbronner Str. 10\\\\\n        W-1000 Berlin 31\\\\\n        Federal Republic of Germany}\n\n\\begin{document}\n\n\\maketitle\n\n\\begin{abstract}\n\n  The numerical solution of optimal control problems by indirect\n  methods (such as multiple shooting or collocation) requires a\n  considerable amount of analytic calculation to establish a\n  numerically tractable system.  These analytic calculations, though\n  being rather tedious in realistic examples, are nowadays mostly\n  still done by hand---and thus prone to calculation errors.  The\n  paper aims at automating this analytic processing to a reasonable\n  extent by means of a modern symbolic manipulation language (here:\n  \\REDUCE).  In its present stage of development the package \\OCCAL{}\n  (mnemotechnically for \\underline{O}ptimal \\underline{C}ontrol\n  \\underline{CAL}culator) permits an interactive use, covering tasks\n  like automatic determination of control and, in case of a singular\n  control, of its order.\n%\n  In simpler problems, the present version of \\OCCAL{} automatically\n  produces the full subroutine input for a MULtiple shooting code\n  (\\MULCON) with adaptive numerical CONtinuation.\\\\\n%\n  In more complicated problems where singular sub-arcs may occur or\n  where the sequence of sub-arcs of the optimal trajectory is unclear\n  \\OCCAL{} is a significant help in reducing analytic pre-processing.\n  Examples illustrate the performance of \\OCCAL/\\MULCON.\n\n%  We describe \\OCCAL, a integrated symbolic-numeric calculus system\n%  for the treatment of optimal control problems. The system is not\n%  only able to do a lot of simple but tedious analytic calculations,\n%  but uses also advanced techniques to calculate as much as possible\n%  automatically. Optimized code for the numeric boundary value problem\n%  solver is generated as well.\n\\end{abstract}\n\\vspace*{0.5cm}\nPreprint SC 91-13\n\\newpage\n\n\\tableofcontents\n\n\\newpage\n\n\\section{Introduction}\n\nOptimal Control problems appear in a wide variety of important\nscientific and technical applications.  In spite of the rather high\nstandards of {\\em numerical\\/} algorithms for such problems\n\\cite{Bock1,Bock2,Bock3,bulirsch,DFK2} tackling such a problem is\nstill a complicated task.  The reason for that is that certain steps in\nthe analytical preparation of the calculation, which are simple in\nprinciple, may be very elaborate and can lead to rather complex\nexpressions.  Implementation of these into numerical code by hand is\ntiresome and error-prone.\n\nThe purpose of our system \\OCCAL{} to be presented here is to overcome\nthis tedious preparation phase. We intend to solve as many of the\narising problems as possible.\n\n%To this end we employ a combined symbolic-numeric system, where the\n%first step is to symbolically analyze the given problem, using the\nTo this end we employ a combined symbolic system that\nsymbolically analyzes the given problem, using the\nComputer Algebra System \\REDUCE.  In passing, this approach\nadditionally permits to generate {\\em optimized\\/} numerical\nsubprograms for use with existing numerical solvers for boundary value\nproblems. These are employed in the second step to obtain numerical\nsolutions.\n\nSymbolic computation (as most computations) is often applied to tasks\nthat are simple in principle, but tedious to carry out by hand.\nConsequently, often only some well defined steps in a calculation are\ndone with the help of a Computer Algebra System. The results are then\ntreated more or less by hand.\n\n%\\OCCAL{}, however is an integrated system in which the symbolic and\n%numeric processors interact with each other, thereby allowing\n%interchange of information between each other and with the user. The\n%advantage of this approach is obvious: at each point in a calculation,\n%the optimal method to solve the task at hand can be used. Examples of\n%this are differentiation of functions, which can be ill-behaved if\n%done numerically, or matrix computations, which can usually be done\n%much faster by a numerical processor. Additionally, the automatic\n%exchange of information reduces the number of errors the user may\n%introduce into the calculation.\n\nIt should be stressed at this point that the symbolic processor in\n\\OCCAL{} is not only used for the tasks mentioned as ``tedious, but\nsimple in principle''.  Nowadays, advanced symbolic techniques are\navailable, e.g., for the solution of systems of nonlinear equations or\nfor computations with inequalities. This can be used, for example, to\ndetermine the sign of a function of several variables over a given\nrange.\n\nThe need for these advanced methods within \\OCCAL{} has not only led\nto their improvement and adaptation to the problems at hand, but also\nto their inclusion into the recently released new version of the\nComputer Algebra System \\REDUCE. Therefore these techniques are now\navailable to a much greater community than before, and hopefully also\nfor a much wider area of applications.\n\nIn Section \\ref{sec:intro} below the typical structure of optimal\ncontrol problems is presented\\allowbreak---mainly to fix notations and to\nelucidate the kind of analytical work involved in the pre-numerical\nstage. On this basis those tasks that can be automated are listed in\ndetail in Section \\ref{sec:operation}---together with the\ncorresponding details of symbolic devices. Finally in Section\n\\ref{sec:examples} the performance of \\OCCAL{} in a few well-known\nexamples is documented.\n\nOf course, the full use of such a software system can only be\nestimated by actually trying it!\n\n\n\\section{A Short Introduction \\protect\\\\ to Optimal Control Problems}\n\n\\label{sec:intro}\n\nConsider a system that is described by a number of time-dependent\nstate variables $y$. Let $y\\in K \\subset C^{1}$, where $K$ is a\nsuitable class of continously differentiable functions, and $y\\colon\n[a,b]\\rightarrow \\R^{n}$.  This system is controlled by certain {\\em\ncontrol variables\\/} $u\\in C^{0}$ piecewise, $u\\colon [a,b]\\rightarrow\n\\R^{k}$, and governed by the following system of differential\nequations\n\\begin{equation}\n  y' = f(t,y,u), \\label{dyn-sys}\n\\end{equation}\nthe with separated boundary conditions $y(a)=y_{a}$ and\n\\begin{equation}\n  r(b,y(b)) =0, \\quad r\\colon \\R^{n+1}\\rightarrow \\R^{p},\n   \\quad  p\\leq n.\n\\end{equation}\nThe task is to minimize the integral\n\\begin{equation}\n  I[u] := \\int\\limits_{a}^{b} f_{0}(y,u,t) dt\n\\end{equation}\nover $K$.\n%We couple the differential equations and the boundary conditions\n%to the functional using Lagrange multipliers $\\lambda$:\n%\\begin{equation}\n%  \\hat I[u,y,y',\\lambda] := \\Phi(b,y(b)) + \\nu^{T} r\n%      + \\int_{a}^{b} \\left(\\sum_{i=1}^{n} \\lambda_{i} (y'_{i} -\n%      f_{i}(t,y,u)) \\right) dt\n%      \\label{full-func}\n%\\end{equation}\nSimilar to the calculus of variations there is the so-called {\\em\nHamiltonian\\/}\n\\begin{equation}\n  H(t,y,\\lambda,u) := \\sum_{i=1}^{n} \\lambda_{i} f_{i}(t,y,u)\n     +\\lambda_{0} f_{0}(t,y,u) \\label{Hamiltonian},\n\\end{equation}\nwhere $\\lambda(t) = (\\lambda_{1}(t),\\ldots,\\lambda_{n}(t))$\ndenotes the {\\em adjoint variables}.\n\nThe minimum principle of Pontrjagin states then that a necessary condition for\n$(y_{0}, u_{0})$ being a solution of the optimal control problem is\n\\begin{equation}\n  H(t,y_{0},\\lambda,u_{0}) = \\min_{v} H(t,y_{0},\\lambda,v) \\label{pontrjagin}\n\\end{equation}\nwith $v$ fulfilling the conditions.  Calculating the first variation\nleads to the so-called {\\em canonical equations\\/}\n\\begin{eqnarray}\n  y'_{i} &=& H_{\\lambda_{i}} = f_{i}(t,y,u), \\quad i = 1,\\ldots,n, \\nonumber\\\\\n  \\lambda'_{i} &=& - H_{y_{i}} = - \\frac{\\partial f_{0}}{\\partial y_{i}}(t,y,u)\n        - \\sum_{j=1}^{n} \\lambda_{i}\n          \\frac{\\partial f_{j}}{\\partial y_{i}}(t,y,u), \\quad i =\n          1,\\ldots,n.           \\label{can-eqs}\n\\end{eqnarray}\nWe number the control variables $u_{i}$ in such a way that the first\n$m$ components (denoted by $u^{(n)}$) appear nonlinearly in $f$, while\nthe others (denoted by $u^{(l)}$) appear only linearly, so that $f$\nsplits in the form\n\\begin{eqnarray}\n  f(t,y,u) &=:& g(t,y,u^{(n)}) + h(t,y,u^{(n)}) u^{(l)}\\:, \\nonumber \\\\\n    && u^{(n)} \\in \\R^{m}, u^{(l)} \\in \\R^{q}, \\quad m+q=k \\label{u-dist}\\:.\n\\end{eqnarray}\nThis splitting carries over to the Hamiltonian $H$ as well.  Since\n$u^{(l)}$ appears only linearly in $f$ and $H$ (cf.\\ (\\ref{u-dist}))\nminimization of $H$ can be done in two steps:\n\\begin{enumerate}\n  \\item Determination of $u^{(n)}$ from\n  \\begin{eqnarray}\n    && H_{u^{(n)}} = 0 \\nonumber \\\\\n    && H_{u^{(n)}u^{(n)}} \\mbox{ positive (semi-)definite} \\label{sys-nonlin}\n  \\end{eqnarray}\n  (Here $H_{u^{(n)}}$ denotes the Fr\\'echet derivatives.)  One obtains\n  an analytic expression $u^{(n)} = u^{(n)}(t,y,\\lambda)$ which can be\n  substituted into the original expressions (\\ref{can-eqs}). Thus\n  $u^{(n)}$ essentially drops out of the set of variables.\n  \\item Determination of $u^{(l)}$:\\\\\n        After substitution of $u^{(n)}$ the Hamiltonian can be written as\n        \\begin{equation}\n          H(t,y,\\lambda,u^{(n)}(t,y,\\lambda),u^{(l)})\n            =: H_{0}(t,y,\\lambda)\n            +  \\sum_{i=1}^{q} S_{i}(t,y,\\lambda) u_{m+i}\\:.\n        \\end{equation}\n        Obviously we have\n        \\begin{equation}\n          S_{i}(t,y,\\lambda) = H_{u_{m+i}}(t,y,\\lambda,u^{(n)}(t,y,\\lambda),u^{(l)})\n        \\end{equation}\n        with $i=1,\\ldots,q$. \n        The condition (\\ref{pontrjagin}) is then equivalent to\n        \\begin{equation}\n          S_{i}(t,y_{0},\\lambda) \\cdot u_{0}(t) = \\min_{v} S_{i}(t,y_{0},\\lambda) \\cdot v(t),\n        \\end{equation}\n      which is a linear optimization problem. \n      It is therefore necessary that the control variables $u^{(l)}$ are subject to\n      control constraints usually of the form\n        \\begin{eqnarray}\n          && \\alpha_{i} \\leq u_{i} \\leq \\beta_{i}, \\quad i=m+1,\\dots,k\n          \\nonumber \\\\\n          && \\alpha_{i}, \\beta_{i} \\in \\R.\n        \\end{eqnarray}\n      The further procedure\n      depends on which one of the following two cases holds:\n        \\begin{enumerate}\n          \\item $S_{i} \\not\\equiv 0$, i.e.\\ $S_{i}$ has only isolated zeros.\n               This is the case of a {\\em bang-bang control}.\n               From the minimum principle we deduce\n                 \\begin{equation}\n                   u_{m+i} = \\left\\{\\begin{array}{l@{\\quad}l}\n                                  \\alpha_{m+i} & \\mbox{for $S_{i} > 0$} \\\\\n                                  \\beta_{m+i} & \\mbox{for $S_{i} < 0$}\n                                \\end{array}\\right.\n                 \\end{equation}\n               The $S_{i}$ are called {\\em switching functions}. \n               A change of sign can only occur in the {\\em switching points\\/}\n               $\\tau^{i}$:\n                 \\begin{equation}\n                   S_{i}(\\tau^{i},y(\\tau^{i}),\\lambda(\\tau^{i})) = 0.\n                 \\end{equation}\n          \\item $S_{i} \\equiv 0$ within a non-empty interval. This is the so-called {\\em singular\\/} case.\n                Let us assume, for simplicity, that $q=1$, i.e.\\ there\n                is only one linear control $u$, and that there is only\n                one such interval.  Define the following functions\n                recursively by\n                 \\begin{eqnarray}\n                   S^{(0)}(t,y,\\lambda) &:=& S(t,y,\\lambda) \\\\\n                   S^{(k+1)}(t,y,\\lambda) &:=& \\frac{d\n                   S^{(k)}(t,y,\\lambda)}{dt} \\nonumber \\\\\n                        &=& S^{(k)}_{y} \\cdot \\dot{y} +\n                        S^{(k)}_{\\lambda} \\cdot \\dot{\\lambda} + S^{(k)}_{t}\\\\\n                        &=&  S^{(k)}_{y} \\cdot H_{\\lambda} -\n                             S^{(k)}_{\\lambda} \\cdot H_{y}  +  S^{(k)}_{t} \\nonumber\n                 \\end{eqnarray}\n                Define $m$ to be the smallest index such that\n                $\\partial S^{(m)}/\\partial u \\not\\equiv 0$. Then\n                theory \\cite{th1,th2,th3} shows that $m = 2r$ is an even\n                number. $r$ is called {\\em order\\/} of the singular\n                control.\n                \n                Since $u^{(l)}$ appears only linearly in $H_{y}$ and $H_{\\lambda}$ it follows\n                that $S^{(m)}$ is of the form\n                 \\begin{equation}\n                   S^{(m)}(t,y,\\lambda) = A(t,y,\\lambda) + B(t,y,\\lambda)\\cdot u(t).\n                 \\end{equation}\n                For $B(t,y,\\lambda)\\not=0$ the singular control can be\n                determined to be\n                 \\begin{equation}\n                   u_{0}(t,y,\\lambda) = - \\frac{A(t,y,\\lambda)}{B(t,y,\\lambda)} \\label{singular-control}\n                 \\end{equation}\n                In certain cases $u_{0}$ does not depend on the adjoint\n                variables $\\lambda$; this is called a {\\em feedback\n                control}.  For an optimal trajectory $y(t)$ and an\n                optimal control $u_{0}(t)$ of order $k = 2r$ holds the\n                {\\em generalized Legendre-Clebsch condition\\/} \\cite{th3}\n                  \\begin{equation}\n                    0 \\leq (-1)^{r} \\cdot \\frac{\\partial}{\\partial u}\n                     \\left(\\frac{d^{2r}}{dt^{2r}}H_{u}(t)\\right)\n                     =  (-1)^{r} \\cdot  B(t,y(t),\\lambda(t)),\n                  \\end{equation}\n                In the case of a feedback control a strict inequality holds.\n        \\end{enumerate}\n\\end{enumerate}\nFinally we can determine the boundary condition for the $\\lambda_{i}$ as\n\\begin{equation}\n  \\left. \\lambda_{i} \\right |_{b} = \\Phi_{y_{i}(b)} + \\nu^{T} r_{y_{i}(b)},\n\\end{equation}\nwhere the $\\nu$ are Lagrange multipliers.\n\n\\vspace*{3mm}\n\\noindent {\\bf Numerical solution by means of Multiple Shooting.}\\\\\nAfter $u^{(n)}$ has been substituted back into the canonical equations\n(\\ref{can-eqs}) we can proceed to a {\\em numerical\\/} solution of the\nresulting boundary value problem.  If there is a linear control\n$u^{(l)}$ we have to take the structure of the optimal control problem\ninto account, especially the number $m_{s}$ and position of the switching\npoints $\\tau_{j}$ defined by the equations\n\\begin{equation}\n  S_{i}(\\tau_{j},y(\\tau_{j}),\\lambda(\\tau_{j})) = 0,\\quad\n   j = 1,\\ldots,m_{s}.\n\\end{equation}\nSince the position of these points is in general not known beforehand,\nwe introduce them as additional parameters\n\\begin{displaymath}\n  \\tau_{1} < \\tau_{2} < \\ldots < \\tau_{m_{s}}\n\\end{displaymath}\nand transform every sub-interval into an interval of the same length,\ni.e.,\n\\begin{eqnarray}\n         [a,\\tau_{1}] \\rightarrow [0,1] \\colon\n                 \\bar t &:=& \\frac{t - a}{\\tau_{1} - a} \\nonumber\\\\ \\relax\n  [\\tau_{1},\\tau_{2}] \\rightarrow [1,2] \\colon\n                 \\bar t &:=& \\frac{t - \\tau_{1}}{\\tau_{2} - \\tau_{1}} + 1 \\nonumber\\\\ \\relax\n    \\vdots \\\\ \\relax\n  [\\tau_{m_{s}}, b] \\rightarrow [m_{s},m_{s}+1] \\colon\n                 \\bar t &:=& \\frac{t - \\tau_{m_{s}}}{b - \\tau_{m_{s}}} + m_{s} \\nonumber\\\\\n  y(t) \\rightarrow \\bar y(\\bar t),&& \\lambda(t) \\rightarrow \\bar\\lambda(\\bar t) \\nonumber\n\\end{eqnarray}\nThis leads to extra factors in the right hand side of the differential\nequations which then additionally depend on one parameter (for the\nborder intervals) or on two parameters (for the intermediate\nintervals). The parameters $\\tau_{1},\\ldots,\\tau_{m_{s}}$ are\ndetermined by the {\\em inner point conditions}\n\\begin{equation}\n  S_{i}(\\tau_{j},\\bar y(\\tau_{j}),\\bar \\lambda(\\tau_{j})) = 0,\\quad\n   j = 1,\\ldots,m_{s}.\n\\end{equation}\nIt may happen that the switching structure changes during the\nnumerical iteration. In that case the whole procedure has to be\nrestarted with the new structure taken into account.\n\nThus the problem has been reduced to a parameter dependent boundary\nvalue problem of the general form:\n\\begin{eqnarray}\n  y' &=& f(y;p) \\\\\n  r(y(a),\\ldots{},y(b);p) &=& 0.\n\\end{eqnarray}\n\nThe associated multiple shooting Jacobian then has the general block\nstructure\n\\begin{equation}\n  \\left[\n    \\begin{array}{cccccc}\n      G_{1} & - I & \\cdot & \\cdot & P_{1} \\\\\n      \\cdot & \\cdot & \\cdot & \\cdot & \\cdot \\\\\n      \\cdot & \\cdot & \\cdot & \\cdot & \\cdot \\\\\n      \\cdot & \\cdot & G_{m-1} & -I & P_{m-1} \\\\\n      R_{1} & \\cdot & R_{m-1} & R_{m} & P_{m}\n    \\end{array}\n  \\right] \\label{Jacobian}\n\\end{equation}\nin terms f the sub-matrices\n\\begin{eqnarray}\n  G_{j} &:=& \\left. W(t_{j+1},t_{j}) \\right|_{y(t|x_{j},p)} \\nonumber \\\\\n  R_{j} &:=& \\left. \\frac{\\partial r}{\\partial y(t_{j})} \\right|_{y(t|x_{j},p)} \\nonumber \\\\\n  P_{j} &:=& \\left. P(t_{j+1},t_{j}) \\right|_{y(t|x_{j},p)} \\\\\n  P_{m} &:=& \\left. \\frac{\\partial r}{\\partial p} \\right|_{y(t|x_{j},p)} \\nonumber.\n\\end{eqnarray}\nHere the matrices $W(t_{j+1},t_{j})$ are the {\\em Wronskian matrices}\n\\begin{equation}\n  W(t,t_{j}) = \\frac{\\partial y(t)}{\\partial y(t_{j})}\n\\end{equation}\nwhich are the solutions of the {\\em variational equation}\n\\begin{equation}\n  \\frac{dW(t,t_{j})}{dt} = f_{y}(y(t|x_{j},p);p) W(t,t_{j}),\\quad W(t_{j},t_{j}) = I,\n\\end{equation}\nand the {\\em sensitivity matrices\\/} $P_{j} = P(t_{j+1},t_{j})$ are\nthe solutions of the generalized variational equation\n\\begin{equation}\n  \\frac{dP(t,t_{j})}{dt} = f_{y}(y(t|x_{j},p);p) P(t,t_{j}) + f_{p}(y(t|x_{j},p);p)\n\\end{equation}\nwith initial value\n\\begin{equation}\n  P(t_{j},t_{j}) = 0.\n\\end{equation}\n\n\n\\section{Application of symbolic computation\\protect\\\\\n         to optimal control problems}\n\n\\label{sec:operation}\n\nSummarizing the calculation steps outlined in the previous section we\nhave the following sub-tasks\n\\begin{itemize}\n  \\item Calculation of Hamiltonian.\n  \\item Identification of nonlinear versus linear control.\n  \\item Determination of nonlinear control by solving the system (\\ref{sys-nonlin}).\n  \\item Substitution into differential equations (\\ref{can-eqs}).\n  \\item Determination of linear control.\n  \\item In the case of bang-bang control: determination of the switching points.\n  \\item In the case of singular control: determination of the order of the control\n        and test of the generalized Legendre-Clebsch condition.\n  \\item Generation of boundary conditions for the adjoint variables.\n  \\item Determination of the variational equations.\n  \\item Code generation (with optional optimization) for the differential equations,\n        the boundary conditions, and the variational equations.\n\\end{itemize}\nSome of these steps can easily be executed by {\\em any\\/} Computer\nAlgebra System (). Examples of this type of tasks are the computation of\nthe Hamiltonian (\\ref{Hamiltonian}), of the canonical equations\n(\\ref{can-eqs}), of the derivatives $H_{u^{(n)}}$ and $H_{u^{(n)}u^{(n)}}$,\nor the substitution of the solution $u^{(n)}$ into the Hamiltonian.\n\nThe \\OCCAL{} system, however, does much more than that. We head at\naccomplishing all the aforementioned tasks automatically, and have\nalready succeeded to a great extent.  Let us first give a short\noverview of the operation of our system.\n\nThe first thing for the user to do is to formulate his problem in a\nform that is suitable for processing with \\OCCAL.\nSince the symbolic program is written in \\REDUCE, input must be given\nin \\REDUCE's Algol-like syntax. Even though this syntax is not too\ndifficult to learn and understand, it is an unnecessary burden to the\nuser who is not necessarily familiar with this type of program.\n\nTherefore we decided to allow the input to be in a very natural,\nuser-friendly form, with automatic translation into \\REDUCE{} syntax.\nTo this end we developed a pre-processor, using the utility \\perl{}\n\\cite{perl}. We chose \\perl{} due to its wide-spread availability and\nexcellent string manipulation facilities that allowed us to implement\nthe program in about one day's time.\n\nThe basic idea is to provide an easy-to-understand input file format,\nwith keywords to identify the different sections, and some freedom for\nthe user to choose a formulation that is most suitable to his or her\nown way of thinking. Furthermore, we want to keep in mind the\npossibility of a future system where this input file is only an\nintermediate step in a much more sophisticated system with, e.g., a\ngraphical user interface. A description of the input file format is\ngiven in appendix~\\ref{app:perl-file}.\n\nThis pre-processing step does already some simple consistency checks:\nconstants, parameters and variables may be defined only once,\ndifferential equations may only be given for already defined dynamic\nvariables, and so on. If there was no error, it outputs a complete\ndefinition of the problem in \\REDUCE{} syntax to a file, taking care\nof arranging the statements in the correct order.  This file is\nthen read by the \\REDUCE{} program and processed symbolically.\n\nIt should be stressed that this output is well-readable: the\nexperienced user may want to intervene at that point instead of\nchanging the input file.\n\nIn the second step, the symbolic program tackles the tasks outlined\nabove.  First the Hamiltonian (\\ref{Hamiltonian}) is calculated. This\nobject is analyzed and the nonlinear and linear controls $u^{(n)}$ and\n$u^{(l)}$ identified. \n\nThe determination of the nonlinear control is done in three steps, of\nwhich only the first one is straightforward in general:\n\\begin{itemize}\n  \\item Calculation of $H_{u^{(n)}}$.\n        This involves only a series of symbolic differentiations, a\n        standard problem for any Computer Algebra System.\n  \\item Solution of the system of equations.\n        Here advanced symbolic techniques are used: algebraic\n        equations are solved using the methods of Groebner bases,\n        transcendental equations may be reduced to algebraic ones by a\n        suitable change of variables. For example, the transcendental\n        equation\n        \\begin{equation}\n          A \\sin u + B \\cos u = C \\label{sin-cos}\n        \\end{equation}\n        may be converted to a system of algebraic equations by substituting\n        \\begin{eqnarray*}\n          x = \\sin u \\\\\n          y = \\cos u\n        \\end{eqnarray*}\n      and adding the relation $x^{2}+y^{2}-1=0$.\n      \\typeout{******************************}\n      \\typeout{Einfuegen: test der direkten steuerung delta.}\n      \\typeout{******************************}\n  \\item Determination of the sign of $H_{u^{(n)}u^{(n)}}$.\n        This is done using new symbolic techniques developed at ZIB.\n        Two different methods are available: the simpler one of these\n        tries to deduce the sign of the expression at hand by breaking\n        it down into its parts and determining the sign of those.\n        Though this seems to be a rather simple algorithm, it is\n        nevertheless very powerful and can be applied to a wide range\n        of expressions.  If this is not sufficient, the user will be\n        queried for the missing information.\n%\n%        If this is not sufficient, a more complicated method can be\n%        used: given a function of several variables, and the domains of\n%        these variables, it determines the range of the function.\n\\end{itemize}\nFinally, the solution is substituted into the Hamiltonian and the\ndifferential equations. This uses again very much the standard\nfacilities of the \\REDUCE{} system for differentiation, substitution\nand extraction of parts of expressions.\n\nIf there is no linear control $u^{(l)}$, all that remains to do is to\nsolve the system of differential equations. To this end, \\OCCAL{}\ngenerates code for use with a numerical code for solving boundary\nvalue problems. The code generation step uses the \\GENTRAN{}\ntranslator for its work; this package has interfaces for \\FORTRAN,\n\\RATFOR, \\Pascal, and \\C{} programming languages.  \n\nIn our examples we use exclusively \\C; our numerical BVP solver is\n\\MULCON{} \\cite{mulcon} which was translated to \\C{}\nsemi-automatically, first using a FORTRAN-to-C translator and then\nbeautifying the automatically produced code by hand to make it better\nreadable.\n\nSeveral functions are generated in the target language:\n\\begin{itemize}\n  \\item Calculation of boundary values $r$.\n  \\item Calculation of differential equations $f$.\n  \\item Calculation of $f_{y}$ to solve the variational equation\n        (for Wronskian approximations $G_{j}$, $P_{j}$).\n  \\item Calculation of the matrices of boundary condition derivatives\n        $R_{1} = r_{y(a)}$ and $R_{m} = r_{y(b)}$.\n\\end{itemize}\nThese are exactly the functions that are needed to compute the\nJacobian (\\ref{Jacobian}).\n\n\\begin{figure}[bt]\n  \\setlength{\\unitlength}{0.5mm}\n  \\newcommand{\\smiley}{%\n    \\fbox{\\setlength{\\unitlength}{0.5pt}%\n          \\begin{picture}(30,40)\n            \\put(8,30){\\circle*{2}}\n            \\put(22,30){\\circle*{2}}\n            \\put(15,10){\\line(0,1){20}}\n            \\put(1,5){\\line(1,0){20}}\n          \\end{picture}}}\n\n  \\begin{center}\n  \\begin{picture}(120,170)(0,0)\n    \\put(10,140){\\framebox(40,25){User input}}\n    \\put(30,110){\\oval(45,15)}\n    \\put(10,110){\\makebox(40,0){\\small Pre-processor}}\n    \\put(30,070){\\oval(45,15)}\n    \\put(10,070){\\makebox(40,0){\\small Symbolic}}\n    \\put(10,010){\\framebox(40,25){\\small Numeric}}\n    \\put(80,100){\\dashbox(40,25){\\Large User\\ \\smiley}}\n   \\thicklines\n    \\put(97,127){\\vector(-3,2){44}}\n    \\put(97,097){\\vector(-3,-2){44}}\n    \\put(53,070){\\vector(+3,+2){44}}\n    \\put(29,138){\\vector(0,-1){19}}\n    \\put(31,138){\\vector(0,-1){19}}\n    \\put(29,100){\\vector(0,-1){20}}\n    \\put(31,100){\\vector(0,-1){20}}\n    \\put(29,060){\\vector(0,-1){24}}\n    \\put(31,060){\\vector(0,-1){24}}\n  \\end{picture}\n  \\end{center}\n  \\caption{An overview of the \\OCCAL\\ system}\n  \\label{fig:overview}\n\\end{figure}\n\nThe symbolic calculation of the matrix entries is of some importance\nfor the whole computation, since this avoids the (external) numerical\ndifferentiation of $f$ and $r$, which might well lead to problems in\nthe numerical calculation.  Furthermore, one may reorder the variables\nto take advantage of the possible block structure of $R_{1}$ and\n$R_{m}$.\n\nWithout further manipulation, the resulting code is generated directly\nfrom the expressions obtained in the previous phase, i.e.\\ in a fully\nexpanded form. This is, of course, non-optimal, except for really\nsimple cases.  Therefore several different optimization strategies can\nbe applied.\n\nWe developed a very simple one that separates the calculation of\nalgebraic and transcendental functions like $\\sqrt {x}$ or ${\\mathrm\ne}^{x}$, (so that their values are computed only once) and uses\nHorner's scheme to evaluate polynomials.  In the case of sparse\npolynomials in many variables, however, using Horner's scheme is not\nstraightforward, since it is not a priori clear how the variables\nshould be ordered. \n\nA more elaborate optimization scheme was developed and implemented by\n{\\sc van Hulzen et al.}\\ \\cite{scope}. It attempts to minimize the\nnumber of arithmetic operations. The optimizer performs heuristic\nsearches on arithmetic expressions, detecting and extracting common\nsubexpressions, and replacing them by temporary variable names.\n\nThe choice of optimization strategy depends mainly on the problem at\nhand. Complete optimization takes a considerable amount of computing\ntime, but this may be payed off by the generation of more efficient\nand better readable numerical code. For every new problem, it is\ntherefore necessary to exploit all possibilities to arrive at an\noptimal solution.\n\nIf, on the other hand, we have a problem with linear control $u^{(l)}$,\nthe next step is to try to solve the remaining linear optimization\nproblem. The present \\OCCAL{} system is not yet capable to distinguish\nbetween the singular and the bang-bang case. This is being worked on.\n\nFigure~\\ref{fig:overview} depicts the overall structure of the system.\n\n\n\\section{Examples}\n\n\\label{sec:examples}\n\nIn this section we present a few simple and well-known examples to\nillustrate the performance of our system,\n\n\\vspace*{3mm}\\noindent\n{\\bf Example 1: Turbo Generator \\cite{Wulkow}}.\n\nThis example is simple enough to do all necessary calculations by\nhand, and therefore well-suited to check the performance of \\OCCAL{}.\n\nWe will not discuss the technical background of the turbo generator as\na machine. Rather we concentrate on the mathematical model derived\nfrom these technical considerations.\n\nThe dynamic model of the turbo generator consists of the following system of\nordinary differential equations:\n\\begin{eqnarray}\n  \\dot x_{1} &=& x_{2} x_{4} \\nonumber \\\\\n  \\dot x_{2} &=& \\frac{1}{M} (u_{1} - s_{4} x_{1} x_{4} - s_{5} x_{1}\n                  x_{3} - \\kappa_{d} x_{2}) \\nonumber \\\\\n  \\dot x_{3} &=& u_{2} - A x_{3} + c x_{4} \\nonumber \\\\\n  \\dot x_{4} &=& - x_{1} x_{2}\n\\end{eqnarray}\nHere $x_{i}$ are the dynamic variables, $u_{i}$ the control variables,\n$s_{4}$, $s_{5}$, $\\kappa_{d}$, $A$, $M$, and $c$ are constants.  The\nstationary state of the machine is characterized by $x_{i} =\nx_{i}^{s}$ and $u_{i}=u_{i}^{s}$, with certain constants $x_{i}^{s}$,\n$u_{i}^{s}$.\n\nThe functional to be minimized describes the deviation from a\nstationary state\n\\begin{equation}\n  \\begin{split}\n  J_{1}(x,u) = \\int\\limits_{0}^{T} \n                (& \\alpha ((x_{1} - x_{1}^{s})^{2} +\n                          (x_{4} - x_{4}^{s})^{2}) +\n                  \\alpha_{2} x_{2}^{2} +\n                  \\alpha_{3} (x_{3} - x_{3}^{s})^{2} + \\\\\n              &    \\beta_{1} (u_{1} - u_{1}^{s})^{2} +\n                  \\beta_{2} (u_{2} - u_{2}^{s})^{2}) dt\n  \\end{split}\n\\end{equation}\nwith certain weight factors $\\alpha$, $\\alpha_{2}$, $\\alpha_{3}$,\n$\\beta_{1}$, and $\\beta_{2}$.  Boundary conditions are \n\\begin{eqnarray}\n  x(0) &=& (x_{1}^{s}, x_{2}^{s}, x_{3}^{s}, x_{4}^{s}) =: x_{0}^{t} \\\\\n  x(T) && \\mbox{free}\n\\end{eqnarray}\nThe control variables $u^{(n)} = (u_{1},u_{2})$ appear quadratically in\nthe Hamiltonian, which leads to a system of two linear equations with\na unique solution. After substituting the solution into the\ndifferential equations we end up with a boundary value problem with\nfour dynamical variables. Due to its simplicity, no optimization of\nthe code is necessary.\n\nA corresponding \\OCCAL{} sample session, the input file for \\OCCAL{}\nitself, the \\REDUCE{} input file generated from this by the\npre-processor, and the \\C{} source file are shown in \\ref{app-turbo}.\nIt can be seen that the intermediate \\REDUCE{} input file is\nwell-readable, so that the experienced user may want to edit this file\ndirectly. This example takes about $25$ seconds of real time on a\ntypical (Sun 4) workstation.\n\nThe file of generated \\C{} code shows several interesting points:\n\\begin{itemize}\n  \\item The constants defined in the CONSTANTS section of the input\n        file are rendered as \\C{} pre-processor macros.\n\n  \\item There are three \\C{} functions defined: for the boundary\n        values (\\verb|R1|), for the functions $f_{i}$ (\\verb|FCN1|),\n        and for the functions $f_{y}$ that are needed in the solution\n        of the variational equation (\\verb|DFCN1|).\n\n        The functions for the calculation of the matrices $R_{1}$ and\n        $R_{m}$ have been skipped in this example.\n  \\item The code optimization process introduces several intermediate\n        variables to reduce the number of operations in the program.\n        These are easily identified by their name which consists\n        always of the letter \\verb|G| (short for generated) followed\n        by a number. It is possible to choose other names as well.\n\\end{itemize}\n\nWith a rather simple main program to drive the calculation it is easy\nto reproduce the numerical results of \\cite{Wulkow}.\n\n\\vspace*{3mm}\n\n\\noindent\n{\\bf Example 2: Re-entry problem \\cite{SB}.}\n\n\nThis is a well-known test problem of somewhat higher degree of complexity.\nHere, the expressions arising from the calculation turn out\nto be rather lengthy.\n\nThe re-entry of an Apollo vehicle into the Earth's atmosphere is\ngoverned by the following system of differential equations:\n\\begin{eqnarray}\n  \\dot v &=& V(v,\\gamma,\\xi,u) = - \\frac{S \\rho v^{2}}{2m} C_{W}(u) -\n             \\frac{g \\sin \\gamma}{(1+\\xi)^{2}}\\\\\n  \\dot \\gamma &=& \\Gamma(v,\\gamma,\\xi,u) = \\frac{S \\rho v}{2m}\n             C_{A}(u) + \\frac {v \\cos \\gamma}{R(1+\\xi)}\n             - \\frac{g \\cos \\gamma}{v(1+\\xi)^{2}}\\\\\n  \\dot \\xi &=& \\Xi(v,\\gamma,\\xi,u) = \\frac{v\\sin\\gamma}{R} \\\\\n  \\dot \\zeta &=& Z(v,\\gamma,\\xi,u) = \\frac{v \\cos \\gamma}{1+xi}\n\\end{eqnarray}\nwhere $u$ is the control variable; and state variables are: $v$\n(tangential velocity), $\\gamma$ (flight path angle), $\\xi = h/R$\n(relative height over ground), $\\zeta$ (velocity over ground).\nMoreover, the expressions $\\rho = \\rho_{0} \\exp(-\\beta R \\xi)$ (),\n$C_{W}(u)$ (aerodynamical resistance), $C_{A}(u)$ (drag or lift\ncoefficient), $S$ (front area), and $m$ (mass of the vehicle) appear\nin the above equations..\n\nThe boundary values at the begin of the reentry into the atmosphere\nand at the time of landing are\n\\begin{alignat}{3}\n v(0) &= 0.36,& \\quad\n \\gamma(0) &= -8.1^{\\circ} \\frac{\\pi}{180^{\\circ}},& \\quad\n \\xi(0) &= \\frac{4}{R}\\\\\n v(T) &= 0.27,& \\quad\n \\gamma(T) &= 0,& \\quad\n \\xi(T) &= \\frac{2.5}{R}\n\\end{alignat}\nThe final time $T$ is free; $\\zeta$ is not considered for the\noptimization. The functional to be minimized is the heating of the\ncapsule, approximated by\n\\begin{equation}\n  J = \\int_{0}^{T} 10\\, v^{3} \\sqrt{\\rho} dt \\:.\n\\end{equation}\nThe problem has only one control variable, but equation\n(\\ref{sys-nonlin}) turns out to be transcendental, of the type\n(\\ref{sin-cos}) discussed earlier. It is possible, by a\nchange of variables, to turn it into a system of algebraic equations\nwhich can be solved by computing the Groebner base of the polynomials.\nThis is done automatically by the \\REDUCE{} equation solver. As a\nresult, we get two solutions, only one of which leads to a positive\ndefinite determinant. This can be determined automatically if the\nadditional information of the variable $v > 0$ is given to the system.\nOtherwise the user is prompted for the sign of $v$.\n\nThe further calculation then proceeds, in principle, just as in the\nprevious example. However, the expressions to be turned into numerical\ncode are quite large, so that we apply optimization techniques during\nthe code generation process. Of the two levels described above, the\n\\SCOPE{} package by van Hulzen \\cite{scope} is able to reduce the size\nof the \\C{} source code from $35$ kBytes ($808$ lines) to $12$ kBytes\n($378$ short lines). The simpler package which only extracts simple\ncommon subexpression reduces the size to $27$ kBytes ($570$ lines).\nUsing the latter, the calculation takes about $50$ seconds of real time\non a Sun 4 workstation.\n\n% Two examples including singular control\n% \n% \\cite{chemo,zellen} are two examples of optimal control problems with\n% non-regular control. The first of these is completely solvable\n% analytically in the absence of state constraints \\cite{chemo}.\n% \\OCCAL{} is not yet capable to do this completely since this solution\n% relies on heuristic methods which are very difficult to make into an\n% algorithm. Nevertheless, \\OCCAL{} goes very far and is able to\n% correctly determine the singular control.\n% \n% The second example shows other difficulties: due to the presence of a\n% lot of inequalities the calculation of the singular control can be\n% simplified significantly. However, dealing with inequalities is a weak\n% point in most Computer Algebra Systems (see also next section).\n\n\n\n\\section{Conclusion}\n\nAs documented above, \\OCCAL{} has reached a first stage of\ndevelopment where it can be successfully used to help in the solution\nof optimal control problems. The tasks already accomplished are:\n\\begin{itemize}\n  \\item Calculation of Hamiltonian.\n  \\item Determination of nonlinear and linear control.\n  \\item Code generation with optional optimization.\n\\end{itemize}\nNext steps of development will include the following features that we\nare planning to incorporate in the future:\n\\begin{itemize}\n  \\item Symbolic-numeric determination of nonlinear control: It is rather obvious\n        that not for all systems of equations an analytic solution can\n        be found. In these cases the algebraic equations have to be\n        coupled to the dynamical system (\\ref{dyn-sys}) and the whole\n        must be solved numerically.\n\n        The numeric treatment of algebro-differential equations is\n        being worked on.\n\n  \\item Determination of inequalities: The determination of the sign\n        of the determinant (\\ref{sys-nonlin}) is only a first simple\n        step in the treatment of inequalities. There are a number of\n        other places where inequalities arise, e.g., when inequalities\n        involving the state variables appear. This is especially\n        important in order to find the intervals where the switching\n        funtions vanish identically. \n\n  \\item Inclusion of state constraints: these may be very important as\n        they may determine the structure of the linear control (i.e.,\n        singular vs.\\ bang-bang). As far as inequalities are\n        concerned, this is related to the previous point, and has\n        probably to be treated in a common framework.\n\n  \\item Treatment of singular sub-arcs.\n\\end{itemize}\n\n\n\n\\noindent\n{\\bf Acknowledgments.} The authors wish to thank M.~Wulkow for several\nhelpful discussions.\n\n\n\n\\begin{thebibliography}{99}\n\n  \\bibitem{Bock1} H.~G.~Bock:\n  \\newblock Randwertproblemmethoden zur Parameteridentifizierung\n            in Systemen nichtlinearer Differentialgleichungen,\n  \\newblock Universit\\\"at Bonn, Dissertation (1985).\n\n  \\bibitem{Bock2} H.~G.~Bock:\n  \\newblock Numerical Solution of Nonlineaer Multipoint Boundary Value\n            Problems with Applications to Optimal Control,\n  \\newblock GAMM, Copenhagen 1977.\n\n  \\bibitem{Bock3} H.~G.~Bock:\n  \\newblock Numerische Berechnung zustandsbeschr\\\"ankter optimaler\n            Steuerungen mit der Mehrzielmethode,\n  \\newblock Carl-Cranz-Gesellschaft 1978.\n\n  \\bibitem{bulirsch} R.~Bulirsch:\n  \\newblock Variationsrechnung und optimale Steuerung.\n  \\newblock Lectures given at the Universit\\\"at zu K\\\"oln (1971).\n  \\newblock Unpublished.\n\n  \\bibitem{th1} R.~Bulirsch et al.~(eds.):\n  \\newblock Optimization and Optimal Control,\n  \\newblock LN Math.~477 (1975).\n\n  \\bibitem{th2} A.~E.~Bryson and Y.~C.~Ho:\n  \\newblock Applied optimal control,\n  \\newblock Ginn and Company,\n  \\newblock Waltham, Massachusetts (1969).\n\n  \\bibitem{mulcon} P.~Deuflhard, B.~Engquist (Ed.):\n  \\newblock Large Scale Scientific Computing,\n  \\newblock Birkhauser/Boston, Series ``Progress In Scientific Computing'',\n  \\newblock Vol.~7 (1987).\n\n  \\bibitem{DFK2} P.~Deuflhard, B.~Fiedler, P.~Kunkel:\n  \\newblock Efficient Numerical Pathfollowing Beyond Critical Points\n            in ODE models,\n  \\newblock in: \\cite{mulcon}, pp.~97--113 (1987).\n\n  \\bibitem{scope} J.~A.~van~Hulzen:\n  \\newblock Code optimization of multivariate polynomial schemes:\n            A pragmatic approach,\n  \\newblock Proceedings EUROCAL '83,\n  \\newblock Springer LNCS 162, pp.~286--300.\n\n  \\bibitem{th3} H.~Maurer, U.~Heidemann:\n  \\newblock Optimale Steuerprozesse mit Zustandsbeschr\\\"ankungen,\n  \\newblock in: \\cite{th1}.\n\n  \\bibitem{SB} J.~Stoer, R.~Bulirsch: \n  \\newblock Einf\\\"uhrung in die Numerische Mathematik II,\n  \\newblock Springer-Verlag,\n  \\newblock Berlin 1978,\n  \\newblock ISBN 3--540--08840--7.\n\n  \\bibitem{perl} L.~Wall, R.~L.~Schwartz:\n  \\newblock Programming \\perl,\n  \\newblock O'Reilly \\& Associates, Inc.,\n  \\newblock 1990.\n\n  \\bibitem{Wulkow} M.~Wulkow:\n  \\newblock Vergleich numerischer Verfahren zur Berechnung der\n  optimalen Steuerung eines Turbogenerators,\n  \\newblock Diploma Thesis, Univ.\\ M\\\"unster, 1987.\n\n%  \\bibitem{f2c} \n\n\\end{thebibliography}\n\n\\newpage\n\n\\appendix\n\n\\renewcommand{\\thesection}{Appendix~\\Alph{section}}\n\\renewcommand{\\thesubsection}{\\Alph{section}.\\arabic{subsection}}\n\n\\section[\\protect\\hspace*{\\dummy}An \\OCCAL{} sample session\\protect\\hspace*{-\\dummy}]%\n        {An \\OCCAL{} sample session}\n\n\\label{app-turbo}\nAs an example we treat the example of the turbo generator. We assume\nthat the following input file has been prepared.\\\\\n\\rule{\\textwidth}{0.6mm}\n\\begin{small}\n  \\verbatiminput{turbo.dsc}\n\\end{small}\n\\rule{\\textwidth}{0.6mm}\\\\[3mm]\nIt is further assumed that the name of this file ends in\n\\verb|.dsc|, e.g., \\verb|turbo.dsc|.\nType in:\n\\begin{verbatim}\noccal turbo\n\\end{verbatim}\n\\OCCAL{} displays\n\\begin{verbatim}\nParsing input file...done.\nStarting symbolic processor...\nREDUCE 3.4, 15-Jul-91 ...\n\n1:\n\n\\end{verbatim}\nand then a protocol of the following \\REDUCE{} statements that were\ngenerated by the pre-processor.\\\\\n\\rule{\\textwidth}{0.6mm}\n\\begin{small}\n  \\verbatiminput{turbo.red}\n\\end{small}\n\\rule{\\textwidth}{0.6mm}\\\\[3mm]\nAfter a while it displays\n\\begin{verbatim}\n============================================================\n That's all, folks!\n============================================================\n\\end{verbatim}\nand then\n\\begin{verbatim}\nQuitting\nOCCAL finished.\n\\end{verbatim}\nThere is now a file with name \\verb|turbo1.c|. We show its contents for illustration.\\\\\n\\rule{\\textwidth}{0.6mm}\n\\begin{small}\n  \\verbatiminput{turbo1.c}\n\\end{small}\n\\rule{\\textwidth}{0.6mm}\n\n\\newpage\n\n\\section[\\protect\\hspace*{\\dummy}Files for the reentry problem]%\n        {Files for the reentry problem}\n\n\\label{app-SB}\n\n\\small\n\n\\subsection{Problem description}\n\\verbatiminput{SB.dsc}\n\n\n\\subsection{\\REDUCE{} input file}\n\\verbatiminput{SB.red}\n\n\\newpage\n\n\\section[\\protect\\hspace*{\\dummy}Input file format for the pre-processor]%\n        {Input file format\\\\ for the pre-processor}\n\n\\label{app:perl-file}\n\nThe input file consists of a number of sections, each identified by a\nkeyword on a line of its own, and ended by an empty line. Possible\nkeywords are:\n\\begin{description}\n  \\item [COMMENT] Used only to explain what is going on. Everything up\n        to the next empty line is ignored.\n  \\item [NAME] A short name to identify the problem, used for file\n        names, etc.\n  \\item [TITLE] Description of the problem, can consist of several\n        lines of text.\n  \\item [CONSTANTS] Constants of the problem, i.e., identifiers whose\n        values do not change. Can only be set at compile time. A value\n        is mandatory.\n  \\item [PARAMETERS] Parameters whose values may be set at run time.\n        A value is optional.\n  \\item [DYNAMIC\\_VARIABLES] The dynamic variables, called $y_{i}$ in a\n        previous section, each on a line of its own.\n  \\item [CONTROL\\_VARIABLES] The control variables, called $u_{i}$ in\n        a previous section, each on a line of its own.\n  \\item [TIME\\_VARIABLE] The name of the independent variable.\n  \\item [BOUNDARIES] Two expressions in \\REDUCE{} syntax that denote\n        the boundaries of the interval. Must be delimited by a\n        semicolon.\n  \\item [FUNCTIONAL] The functional to be minimized.\n  \\item [DIFFERENTIAL\\_EQUATIONS] The dynamical system.\n  \\item [END\\_POINT\\_IS\\_FREE] Specifies that the right boundary is free\n        and to be calculated.\n  \\item [BOUNDARY\\_CONDITIONS] The boundary conditions at the points\n        specified in the BOUNDARIES section.\n  \\item [ABBREVIATIONS] Arbitrary \\REDUCE{} expressions, each\n        delimited by a semicolon. \n  \\item [RESTRICTIONS] Additional conditions, such as a variable being\n        bounded from below.\n  \\item [TARGET\\_LANGUAGE] The programming language in which the numerical\n        programs are generated. Possible are: \\C, \\FORTRAN, \\RATFOR, and \\Pascal.\n  \\item [TEMPVAR\\_PREFIX] The prefix used for constructing variable names during\n        code generation. Default is \\verb|ANS|.\n\\end{description}\nThe order of these sections is largely arbitrary, except for one\nrestriction: the dynamic variables need to be defined before the\ncorresponding differential equations.\n\n\n\\end{document}\n", "meta": {"hexsha": "01d43aec14d0f4cec5c993f85371be66740ebd82", "size": 44336, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "packages/occal/ocpaper.tex", "max_stars_repo_name": "arthurcnorman/general", "max_stars_repo_head_hexsha": "5e8fef0cc7999fa8ab75d8fdf79ad5488047282b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "packages/occal/ocpaper.tex", "max_issues_repo_name": "arthurcnorman/general", "max_issues_repo_head_hexsha": "5e8fef0cc7999fa8ab75d8fdf79ad5488047282b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "packages/occal/ocpaper.tex", "max_forks_repo_name": "arthurcnorman/general", "max_forks_repo_head_hexsha": "5e8fef0cc7999fa8ab75d8fdf79ad5488047282b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.5081495686, "max_line_length": 106, "alphanum_fraction": 0.6863045832, "num_tokens": 12488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073507867328, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.30103804543828233}}
{"text": "% STRAINS --------------------\n\\section{Discussion}\\label{sec:discussion:clustering}\n\nIn general, we observe two trends in our data. For the \\isols{} that get clustered into strains,\nour approach correctly identifies the \\spec{} with over 80-85\\% accuracy. This accuracy\nis sufficient to conduct sophisticated \\mst{} studies. Most of the strains discovered \nin the \\cplop{} data show high degree of purity, and even considering the presence of \na few large impure clusters, most of the clustered \\isols{} fall into strains of high purity.\n\n\nAt the same time, the pure strain-based approach suffers from a drop in the coverage as the size of a cluster grows. \nThis means that in general \\cplop{} \\isols{} tend to be very diverse\nand come from strains for which not enough DNA material has been collected and pyrosequenced.\nIdentifying the \\spec{} for \\isols{} that do not fall into strains/clusters using the pure strain-based\nmethod is impossible. In future work, our goal is to combine the \\kNN{}-based \\mst{} method\nof \\cite{DBLP:conf/bibm/McGovernDKBVG15} with the strain-based approach discussed in this paper\nto increase coverage while preserving the high \\mst{} accuracy.\n\n\n\n\n%%%%%%%\n\n\n%Considering how many \\isols{} end up in clusters of high purity, as \\autoref{fig:clust_purity_dist_3} shows, this occurrence appears to be infrequent.\n%Nevertheless, viewing the progression of graphs in \\autoref{fig:clust_pure} implies that the clusters morph and change into each other as we increase \\minneigh{}.\n\nOne factor explaining the large impure clusters is the possibility that these clusters represent what the  biologists call  ``transient'' strains, i.e., strains that  persist in more than one \\spec{}. \n%That is, certain strains might show up in many \\spec{} and not just relegated to one \\spec{}.\nSuch a characteristic can compound \\mst{} by making certain strains of \\ecoli{} less reliable as \\fib{} for identifying \\spec{}.\nIn \\autoref{fig:clust_purity_dist}, we see evidence of that and it is revealed in \\autoref{fig:clust_pure}.\nOne mitigation strategy may be to reduce the presence of these strains in the library holding the \\fib{}.\nAnother may be to fall back to an alternative \\mst{} technique that works with \\cplop{} when an unknown \\isol{} falls into an impure cluster.\nFinally, if a true transient strain is indeed discovered, and an \\isol{} is mapped to it, our \\mst{} procedure can simply acknowledge that the query \\isol{} belongs to a transient strain and provide information about the \\spec{} that show high frequency of \\ecoli{} incidence from this strain.\nIn order to handle the lack of complete clustering coverage --- when \\dbscan{} marks an \\isol{} as noise --- we propose a fallback method : the \\kraplong{}, described in \\autoref{chap:krap}.\n\n\n%It also is possible that a more complicated or biologically-motivated strategy may work best.\n%One avenue of validation we chose not to pursue was $k$-fold cross-validation.\n%Previous work \\cite{DBLP:conf/bibm/McGovernDKBVG15} has used it for validation.\n%Future work may include it, but large $k$ values are likely to partition the dataset into groups different enough to create widely varying clusterings.", "meta": {"hexsha": "6a1f31d15e60203165eff6a54b02e86b09cdbcfc", "size": 3186, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/clustering/discussion.tex", "max_stars_repo_name": "jmcgover/thesis", "max_stars_repo_head_hexsha": "25664684158d00864dbe697276d2691ba84461cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chapters/clustering/discussion.tex", "max_issues_repo_name": "jmcgover/thesis", "max_issues_repo_head_hexsha": "25664684158d00864dbe697276d2691ba84461cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/clustering/discussion.tex", "max_forks_repo_name": "jmcgover/thesis", "max_forks_repo_head_hexsha": "25664684158d00864dbe697276d2691ba84461cb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 77.7073170732, "max_line_length": 293, "alphanum_fraction": 0.7702448211, "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.30100165703060305}}
{"text": "\\documentclass{spec}\n\n\\usepackage{amsfonts,bm,amsmath}\n\\usepackage{verbatim}\n\\usepackage{algorithm, algpseudocode}\n\\usepackage{caption}\n\\usepackage{calc}\n\n\n\\input{nlls_header.tex}\n% data types for the derived types\n\\newcommand{\\scalarinteger}[1]{\\itt{#1} is a scalar of type {\\tt INTEGER} }\n\\newcommand{\\scalarlogical}[1]{\\itt{#1} is a scalar of type {\\tt LOGICAL} }\n\\newcommand{\\scalarcharacter}[2]{\n  \\itt{#1} is a scalar of type {\\tt CHARACTER} and length {\\tt #2} \n}\n\\newcommand{\\scalarreal}[1]{\\itt{#1} is a scalar of package type}\n\\newcommand{\\ronearrayinteger}[1]{is a rank-1 array of type {\\tt INTEGER} and size {\\tt #1} }\n\\newcommand{\\ronearrayreal}[2]{\\itt{#1} is a rank-1 array of package type and size {\\tt #2}\\ }\n% data types for the calling sequences\n\\newcommand{\\scalarintegerio}{is an \\intentout scalar of type {\\tt INTEGER} }\n\\newcommand{\\scalarintegerii}{is an \\intentin scalar of type {\\tt INTEGER} }\n\n\\newcommand{\\ronearrayrealii}[1]{is an \\intentin rank-1 array of package type and size {\\tt #1} }\n\\newcommand{\\ronearrayrealiiopt}[1]{is an optional \\intentin rank-1 array of package type and size {\\tt #1} }\n\\newcommand{\\ronearrayrealio}[1]{is an \\intentout rank-1 array of package type and size {\\tt #1} }\n% Fortran calling routine\n\\newcommand{\\mainroutine}{{\\tt nlls\\_solve}}\n\\newcommand{\\onestep}{{\\tt nlls\\_iterate}}\n% Fortran customization\n\\newcommand{\\ct}{\\%}\n\\newcommand{\\fortranonly}[1]{#1}\n\\newcommand{\\conly}[1]{}\n\\newcommand{\\vecentry}[2]{\\texttt{#1(#2)}}\n\\begin{document}\n\n\\hslheader\n\n\\hslsummary\n\n\\input{summary.tex}\n\n%!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\\hslattributes\n\\hslversions{\\versionum\\ (\\versiondate)}.\n\\hslIRDCZ Real (single, double).\n\\hsllanguage Fortran 2003 subset (F95+TR155581).\n\\hsldate January 2016.\n\\hslorigin The Numerical Analysis Group, Rutherford Appleton Laboratory.\n\\hslremark The development of this package was\npartially supported by EPSRC grant EP/M025179/1.\n\n%!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\\newpage\n\\hslhowto\n\n\\subsection{Calling sequences}\n\nAccess to the package requires a {\\tt USE} statement \\\\ \\\\\n\\indent\\hspace{5mm}{\\tt use ral\\_nlls\\_double}\n% \\noindent\n% If it is required to use more than one module at the same time, the derived\n% types  (see Section~\\ref{derived types})\n% must be renamed in one of the {\\tt USE} statements.\n\\medskip\n\n\\noindent The user can then call one of the procedures:\n\\vspace{-0.1cm}\n\\begin{description}\n\\item {\\tt NLLS\\_SOLVE}  solves the non-linear least squares problem (\\ref{eq:nlls_problem}).\n\\item {\\tt NLLS\\_ITERATE} performs one iteration for the non-linear least squares solver.\n\\end{description}\n\n%%%%%%%%%%%%%%%%%%%%%% derived types %%%%%%%%%%%%%%%%%%%%%%%%\n\n\\hsltypes\n\\label{derived types}\nFor each problem, the user must employ the derived types defined by the\nmodule to declare scalars of the types {\\tt NLLS\\_inform} and\n{\\tt NLLS\\_options}.  If {\\tt nlls\\_iterate} is to be used, then \na scalar of the type {\\tt NLLS\\_workspace} must also be defined.\nThe following pseudocode illustrates this.\n\\begin{verbatim}\n      use nlls_module\n      ...\n      type (NLLS_inform) :: inform\n      type (NLLS_options) :: options\n      type (NLLS_workspace) :: work ! needed if nlls_iterate to be called\n      ...\n\\end{verbatim}\nThe components of {\\tt NLLS\\_options} and {\\tt NLLS\\_inform} are explained\nin Sections~\\ref{typeoptions} and \\ref{typeinform}.\n\n\n%%%%%%%%%%%%%%%%%%%%%% argument lists %%%%%%%%%%%%%%%%%%%%%%%%\n\\hslarguments\n\\subsubsection{Optional arguments}\\label{Optional arguments}\n\nWe use square brackets {\\tt [ ]} to indicate \\optional\\ arguments.\nIn each\ncall, optional arguments follow the argument {\\tt inform}.  Since we\nreserve the right to add additional optional arguments in future\nreleases of the code, {\\bf we strongly recommend that all optional\narguments be called by keyword, not by position}.\n\n\\subsubsection{Integer and package types}\n%{\\tt INTEGER} denotes default {\\tt INTEGER} and\n%{\\tt INTEGER(long)} denotes {\\tt INTEGER(kind=selected\\_int\\_kind(18))}.\nThe term {\\bf package type} is used to mean\ndefault real if the single precision version is being used and\ndouble precision real for the double precision version.\n\n\\subsubsection{To solve the non-linear least squares problem}\n\\label{sec:solve}\n\nTo solve the non-linear least squares problem a call of the following form should be made:\n\n\\begin{verbatim}\n   call nlls_solve(n, m, X, eval_r, eval_J, eval_Hf, params, options, inform[, weights])\n\\end{verbatim}\n\n\\begin{description}\n\\itt{n} \\scalarintegerii that holds the number $n$ of\nvariables to be fitted; i.e., $n$ is the length of the unknown vector $\\bm x$. \n\\textbf{Restriction:} \\texttt{n}$>${\\tt 0}.\n\n\\itt{m} \\scalarintegerii that holds the number $m$ of\ndata points available; i.e., $m$ is the number of residuals $r_i$.\n\\textbf{Restriction:} \\texttt{m}$\\geq$\\texttt{n}\n\n\\itt{X} is an \\intentinout\\  rank-1 array of package type\nand size {\\tt n}.  On entry, it must hold the initial guess for $\\bm x$, and on\nsuccessful exit it holds the solution to the non-linear least squares problem.\n\n\\itt{eval\\_r} is a {\\tt PROCEDURE} that, given a point $\\iter{\\vx}$, returns the vector $\\vr(\\iter{\\vx})$.\nFurther details of the format required are given in Section~\\ref{sec::function_eval}.\n\n\\itt{eval\\_J} is a {\\tt PROCEDURE} that, given a point $\\iter{\\vx}$,\nreturns the $m \\times n$ Jacobian matrix, $\\iter{\\vJ}$, of $\\vr$ evaluated at $\\iter{\\vx}$.\nFurther details of the format required are given in Section~\\ref{sec::function_eval}.\n\n\\itt{eval\\_Hf} is a {\\tt PROCEDURE} that, given vectors $\\vx \\in \\mathbb{R}^n$\nand $\\vr \\in \\mathbb{R}^m$, returns the quantity $\\sum_{i=1}^m (\\vr)_i \\nabla^2 \\vr_i (\\vx)$.\nFurther details of the format required are given in Section~\\ref{sec::function_eval}.  If {\\tt NLLS\\_options\\%exact\\_second\\_derivative = .false.}, then this is not referenced.\n\n\\itt{params} is an \\intentin\\ scalar of class {\\tt params\\_base\\_type} that holds parameters to\nbe passed to the user-defined routines {\\tt eval\\_r}, {\\tt eval\\_J}, and {\\tt eval\\_Hf}.\nFurther details of its use are given in Section~\\ref{sec::function_eval}.\n\n\\itt{options}is an \\intentin\\  scalar  of type {\\tt NLLS\\_options}\n(see Section~\\ref{typeoptions}).\n\n\\itt{inform} is an \\intentinout\\ scalar of type\n{\\tt NLLS\\_inform}. Its components provide information about the execution\nof the subroutine, as explained in Section~\\ref{typeinform}.\n\n\\itt{weights} \\ronearrayrealiiopt{m}.  If present, {\\tt weights} holds the square-roots of the \ndiagonal entries of the weighting matrix, $\\vW$, in (\\ref{eq:nlls_problem}).  If absent, then the norm in (\\ref{eq:nlls_problem}) is taken to be the 2-norm, that is, $\\vW = I$.\n\n\\end{description}\n\n\\subsection{To iterate once}\n\\label{sec:iterate}\nAlternatively, the user may step through the solution process one iteration at\na time by making a call of the following form:\n\n\\begin{verbatim}\n   call nlls_iterate(n, m, X, w, eval_F, eval_J, eval_HF, params, options, inform[, weights])\n\\end{verbatim}\n\n\\begin{description}\n\n\\item[\\texttt{n}, \\texttt{m}, \\texttt{eval\\_F}, \\texttt{eval\\_J}, \\texttt{eval\\_HF}, \\texttt{params}, \\texttt{info} and \\texttt{options}] are as described in Section~\\ref{sec:solve}.\n\n\\itt{X} is an \\intentinout\\  rank-1 array of package type\nand size {\\tt n}.  On the first call, it must hold the initial guess for\n$\\bm x$. On return it holds the value of $\\bm x$ at the current iterate, and\nmust be passed unaltered to any subsequent call to \\texttt{nlls\\_iterate()}.\n\n\\itt{w} is an \\intentinout\\ scalar of type \\texttt{NLLS\\_workspace}. It is used\nto store the current state of the iteration and should not be altered by the\nuser.\n\n\\end{description}\n\nThe user may use the components \\texttt{info\\%convergence\\_normf} and\n\\texttt{info\\%convergence\\_normg} to determine whether the iteration has\nconverged.\n\n\\subsection{User-supplied function evaluation routines}\n\\label{sec::function_eval}\nTo evaluate the residual, Jacobian and Hessian at a point, the user\nmust supply subroutines that perform this operation that the package\n{\\tt ral\\_nlls} will call internally.\n\nIn order to pass user-defined data into the evaluation calls, {\\tt params\\_base\\_type} is extended to a {\\tt user\\_type}, as follows:\n\\begin{verbatim}\n   type, extends( params_base_type ) :: user_type\n      ! code declaring components of user_type\n   end type user_type\n\\end{verbatim}\nWe recommend this type is wrapped in a module with the user-defined routines\nfor evaluating the function, Jacobian, and Hessian.\n\nThe components of the extended type are accessed through a \\texttt{select type}\nconstruct:\n\\begin{verbatim}\n   select type(params)\n   type is(user_type)\n     ! code that accesses components of params that were defined within user_type\n   end select\n\\end{verbatim}\n\n\\subsubsection{For evaluating the function $\\vr(\\vx)$}\n\nA subroutine must be supplied to calculate $\\vr(\\vx)$ for a given vector $\\vx$. \nIt must implement the following interface:\n\n\\begin{verbatim}\nabstract interface\n   subroutine eval_r(n, m, params, x, r, status)\n      integer, intent(in) :: n\n      integer, intent(in) :: m\n      class(params_base_type), intent(in) :: params\n      double precision, dimension(n), intent(in) :: x\n      double precision, dimension(m), intent(out) :: r\n      integer, intent(inout) :: status\n   end subroutine eval_r\nend interface\n\\end{verbatim}\n\n\\input{eval_r.tex}\n\n\\subsubsection{For evaluating the function $\\vJ = \\nabla \\vr(\\vx)$}\nA subroutine must be supplied to calculate $\\vJ = \\nabla \\vr(\\vx)$ for a given vector $\\vx$. It\nmust implement the following interface:\n\n\\begin{verbatim}\nabstract interface\n   subroutine eval_J(n, m, params, x, J, status)\n      integer, intent(in) :: n\n      integer, intent(in) :: m\n      class(params_base_type), intent(in) :: params\n      double precision, dimension(n), intent(in)  :: x\n      double precision, dimension(n*m), intent(out) :: J\n      integer, intent(inout) :: status\n  end subroutine eval_J\nend interface\n\\end{verbatim}\n\n\\input{eval_j.tex}\n\n\\subsubsection{For evaluating the function $Hf = \\sum_{i=1}^m r_i(\\vx) \\vW \\nabla^2 r_i(\\vx)$}\nA subroutine must be supplied to calculate $Hf = \\sum_{i=1}^m (\\vr)_i \\nabla^2 r_i(\\vx)$ for given vectors $\\vx \\in \\mathbb{R}^n$ and $\\vr \\in \\mathbb{R}^m$; here \\((\\vr)_i\\) denotes the $i$th component of the vector $\\vr$. The subroutine must implement the following interface:\n\n\\begin{verbatim}\nabstract interface\n   subroutine eval_Hf_type(n, m, params, x, r, Hf, status)\n       integer, intent(in) :: n\n       integer, intent(in) :: m\n       class(params_base_type), intent(in) :: params\n       double precision, dimension(n), intent(in)  :: x\n       double precision, dimension(m), intent(in)  :: r\n       double precision, dimension(n*n), intent(out) :: Hf\n       integer, intent(inout) :: status\n     end subroutine eval_Hf_type\nend interface\n\\end{verbatim}\n\n\\input{eval_hf.tex}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n\\subsection{The options derived data type}\n\\label{typeoptions}\n\n\n\\input{options_type.tex}\n\n\\subsection{The derived data type for holding information}\n\\label{typeinform}\n\n\\input{info_type.tex}\n\n%%%%%%%%%%%%%%%%%%%%%% Warning and error messages %%%%%%%%%%%%%%%%%%%%%%%%\n\n\\hslerrors\n\nA successful return from a subroutine in the package is indicated by\n{\\tt NLLS\\_inform\\%status} having the value zero.\nA non-zero value is associated with an error message that by default will\nbe output on unit {\\tt NLLS\\_options\\%error}.\n\n\\input{errors.tex}\n\n\\hslgeneral\n\n\n\\hslio\n   Error messages on unit {\\tt NLLS\\_options\\%error} and warning\n   and diagnostic messages on unit \\newline{\\tt NLLS\\_options\\%out},\n   respectively. These have default value {\\tt 6};\n   printing of these messages is suppressed if the relevant unit number\n   is negative or if {\\tt NLLS\\_options\\%print\\_level} is negative.\n\\hslrestrictions {\\tt m$\\ge$n$\\ge$1}.\n\n\\hslmethod\n\\label{method}\n\n\\input{method.tex}\n% todo!\n\n\\hslexample\n\n\\input{example_text.tex}\n\n\\verbatiminput{../example/Fortran/nlls_example.f90}\n\n\n\\end{document}\n", "meta": {"hexsha": "5028cbffa788100f6f1903e30b13077910fa36a6", "size": 12003, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "libRALFit/doc/nlls_fortran.tex", "max_stars_repo_name": "andpic/RALFit", "max_stars_repo_head_hexsha": "d8bd77217b5163f79069eaf7c5238a854f4843e3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2018-04-02T12:24:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T00:11:45.000Z", "max_issues_repo_path": "libRALFit/doc/nlls_fortran.tex", "max_issues_repo_name": "andpic/RALFit", "max_issues_repo_head_hexsha": "d8bd77217b5163f79069eaf7c5238a854f4843e3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 95, "max_issues_repo_issues_event_min_datetime": "2016-09-13T15:16:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-23T14:08:27.000Z", "max_forks_repo_path": "libRALFit/doc/nlls_fortran.tex", "max_forks_repo_name": "andpic/RALFit", "max_forks_repo_head_hexsha": "d8bd77217b5163f79069eaf7c5238a854f4843e3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2018-04-02T12:24:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-23T17:12:42.000Z", "avg_line_length": 37.1609907121, "max_line_length": 278, "alphanum_fraction": 0.7123219195, "num_tokens": 3392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.30100165703060305}}
{"text": "\\chapter{EXAMINATION OF PREVIOUSLY-EXISTING GLOBAL DP LIBRARIES}\n\nThe first goal of this Thesis is to examine previously existing programming libraries and APIs that provide the application of Differential Privacy to a dataset. This has been achieved by many companies, such as Google and IBM, but also from research programs like ARX that study the benefits of data privacy. We separate those implementations regarding their output. The possible outputs of a mechanism that adds D.P. to a dataset can be:\n\\begin{itemize}\n    \\item An answer to a query, in a private manner.\n    \\item An anonymized dataset, that meets the criteria of D.P.\n\\end{itemize}\n\nIn the first category, we can distinguish libraries such as Google's and IBM's, that have functions which if applied on a dataset, and given a specific query, can return a single answer.\n\nIn the second one, we can find libraries such as the ARX tool, that given a dataset and a group of privacy settings (such as the amount of noise to be inserted), produces an anonymized version of a dataset, that has obviously reduced information in comparison to the original one, but is usable by the final user.\n\nIn this chapter, we are going to test those libraries by providing different kinds of datasets, in order to determine the advantages and the disadvantages of each category.\n\nWe are going to conduct all of our testings using noise generated by the \\emph{Laplace Mechanism}, thus we must first define its theoretical behavior.\n\n\n\n\\section{The Laplace Mechanism}\n\nThe Laplace Mechanism is used widely in applications of Differential Privacy regarding \\emph{numerical queries}, which are actually functions that match a query to a number, or a vector of numbers, thus answering to it. The mechanism uses noise produced by the Laplace probabilistic distribution, which is proportional to the query's sensitivity.\n\n\\subsection{Query Sensitivity}\nThe $l_1$ sensitivity of a query $f$, is defined as following:\n\n\\begin{align*}\n    \\Delta f = \\max_{\\{||x-y||_1 = 1\\}} ||f(x) - f(y)||_1\n\\end{align*} where $x,y \\in N^{|X|}$.\n\nThis quantity shows the effect by which a single participant's data can change in the worst case during the query $f$, and thus, the uncertainty that we must insert to to the response in order to protect them.\n\n\\subsection{The Laplace Distribution}\nThe Laplace Distribution with a scale $b$, is the distribution with probability density function: \n\\begin{align*}\nLap(x|b) = \\frac{1}{2b}exp(-\\frac{|x|}{b})\n\\end{align*}\n\nwho's variance is $\\sigma^2 = 2b^2$, and is actually a symmetric version of the exponential distribution.\n\n\\subsection{Use of Laplace in D.P.}\n\nIn order to be of use in our definition, the scale of the noise will be calibrated to the sensitivity of the query $f$, divided by epsilon. Thus, the noise used will be drawn from\n\n\\begin{align*}\nLap(\\frac{\\Delta f}{\\epsilon})\n\\end{align*}\n\nOf course, many other probabilistic distributions can be used to ensure differential privacy, but during our testings we prefer to use Laplace.\n\n\\section{Query Answering Libraries}\n\nWe are going to begin by testing libraries that belong in the first category, and specifically the \\emph{IBM's diffprivlib}, which is written in python, and is publicly available \\href{https://github.com/IBM/differential-privacy-library}{here}. The library includes a host of mechanisms, the building blocks of differential privacy, alongside a number of applications to machine learning and other data analytics tasks. A full explanation of the library's functionalities is available in [3]. We are going to focus our testings in the simple queries, such as the \\emph{mean value}, the \\emph{extreme values} and the \\emph{histograms} of a numerical dataset. The library consists of three modules:\n\n\\begin{itemize}\n    \\item \\textbf{Mechanisms}, as known from the theoretical foundations of D.P.\n    \\item \\textbf{Models}, especially machine learning models, that will not concern us during this thesis\n    \\item \\textbf{Tools} that will allow us to apply D.P. in datasets.\n\\end{itemize}\n\nWe are going to use the tools available, in order to apply differential privacy in a dataset of our own, guided of course by the mechanisms provided by diffprivlib. First, we are going to take a look at the dataset that we are going to use going forward.\n\n\n\\subsection{Setup of the mechanism}\n\nThe first step in order to test the library, is to setup the mechanism by defining its properties and parameters. \n\n\\subsubsection{Bounds' Selection}\n\nOne of the most important aspects for us if we want to apply DP algorithms, is to define the bounds, i.e. the range that a variable can be in. It would be very convenient in our case to just take the tuple of the smallest and the largest value in the column that we are interested in. However, in the real world, the person who asks the queries is not supposed to know this info about the dataset. Thus, since a solution is not provided by the library, we must define our own bounds by guessing the lowest and the highest values in the fields that we want to examine. \n\nThus, the user must have somewhat of a previous knowledge regarding the dataset, in order to decide the minimum and maximum value. Those values do not need to be precise, although the more close they are to real ones, the best the protocol will function. At the same time, we must be sure that during our selection we do not leave some of the dataset's values outside of the bounds, as they will be ignored in the final results. \n\n\n\\subsubsection{Privacy Budget}\n\nIn this form of D.P., someone trying to breach the users' privacy, could theoretically ask an infinite number of questions, and thus each time gain more and more information about their private data. In the same manner, an untrusted user of the library could ask the same question many times, aiming to determine how much noise is added each time, in order to find out the actual answer to the query, as the way that the noise is drawn is already known.\n\nIn order to eliminate this problem, a special parameter call the \\emph{privacy budget} is implemented. The library offers the ability to initialize this budget before asking any queries. During the queries, this budget is each time decreased, according to how much data the answer to the question reveals. For example, the answer to the \"mean value of the charges for a surgery\", costs less than the answer to the \"histogram values of heart transplant surgeries in the West coast\".\n\nThis parameter is implemented by the library as the budget accountant. This variable tracks the privacy spent, so that our system is not left exposed after lots of \"expensive queries\". The system will allow someone to ask one question that uses the whole privacy budget, or a series of questions whose total impact is less or equal to the initial budget.\n\n\\subsection{Testings' goal}\n\nWhen applying D.P. mechanisms to our data, we provide the privacy settings of our choice (epsilon variable), and obtain an answer to each of our questions. Thus, in our testings, our goal is to \\emph{determine the accuracy of the answers}, given a specific ε, or some other settings, and comparing them to the true answer, using some metrics. Those metrics are different for each query type. In this section we are going to focus on two types of queries: statistical, and histograms.\n\n\\subsection{General techniques}\nIn each one of our following testings, we are going to run the query \\emph{many times}. As we already know, D.P. relies on probabilistic algorithms that can some times produce extreme results. This may be rare, but we want our testings and conclusions to be accurate. So, we are going to run each query 100 times, and return as a result the mean value of those runs.\n\n\\subsection{Statistical Queries}\n\nThe first type of queries that we are going to test are those that answer questions like \"What is the mean cost of a surgery?\", or \"What is the largest fee paid by medicare for a transplant?\", known as statistical queries. \n\n\\subsubsection{Metrics used}\n\nIn the case of statistical queries, their answer is usually a real number, so in order to check their alteration with the true answer, we are going to take into account the \\emph{absolute difference between the truth and the query answer}. \n\n\\subsubsection{Bounds Definition}\n\nWe are considering fees for surgeries in our example, thus a logical lower bound would be 0\\$ (surgeries could be done pro bono too!), and an upper bound would be 1 million dollars. Either way, we are trying to be extreme with our picks, in order to not find ourselves in the unfortunate situation that a value taken into consideration by the DP query would be out of bounds.\n\n\\subsubsection{The identity of the testing Dataset}\n\nThe dataset chosen to test the library, is the publicly available \"Surgery Charges Across the U.S.\", that contains many different kinds of surgeries in a plethora of different hospitals. Our goal is to protect each hospital's data when it comes down to a specific surgery, while helping a patient choose one, depending on the charges that can be found all over the United States. The data provided in this dataset, is going to help a potential patient balance his need of top care, and the need to spend less money. The columns contained in the dataset are:\n\n\\begin{itemize}\n    \\item Surgery code and definition\n    \\item Provider hospital name\n    \\item Provider city\n    \\item Average total payments\n    \\item Average medicare payments\n\\end{itemize}\n\nWe are going to focus on the last two columns, in order to approximate the charges of a surgery. The above table gives us an image of the containers of the dataset.\n\nThe dataset contains a total of 200,000 entries, a more than satisfying number for running D.P. algorithms.\n\n\\begin{table}[!htb]\n\n    \\caption{\"Surgery Charges Across the U.S.\" dataset columns}\n    \\label{numbers}\n\n    \\begin{tabular}{| c | c | c | c | c| c |}\n      \\hline \n      ID & Surgery Type & Hospital Name & Hospital City & Total & Medicare \\\\\n      \\hline\n      1 & TRANSPLANT & MAYO CLINIC & PHOENIX & \\$240422.80 & \\$133509.55\\\\\n      \\hline\n      2 & ECMO &  GROSSMONT HOSP & LA MESA & \\$193617.86 & \\$192003.43 \\\\\n      \\hline\n      3 & CRANIOTOMY & STANFORD HOSP &  STANFORD & \\$32597.87 & \\$29347.12  \\\\\n      \\hline\n    \\end{tabular}\n\n\\end{table}\n\n\\subsubsection{General Dataset Utilities Queries}\n\nOur first experiment is just to ask for some of the utilities of the dataset, and specifically its cost column: the \\emph{mean value}, the \\emph{variance}, the \\emph{sum} and the \\emph{standard deviation} values of the surgeries' cost. \n\nAll of those queries can be executed using the following command (specifically for the mean value query):\n\\bigskip\n\n\\begin{lstlisting}[language=Python]\nmean_with_dp = dp.tools.mean(df[\"Average_Total_Payments\"].tolist())\n\\end{lstlisting}\n\\bigskip\n\nwhere the dataframe column is the one containing the cost of each surgery, and its values should be in a list in order for the library to function.\n\nBy running the above mentioned queries, we got the following results:\n\n\n\\begin{table}[!htb]\n    \\centering\n    \\caption{General Queries results for Surgeries Dataset}\n    \\label{numbers}\n\n    \\begin{tabular}{| c | c | c |}\n      \\hline \n      Query & True answer & Private Answer \\\\\n      \\hline\n      Mean value & 13168.5 & 13167.3 \\\\\n      \\hline\n      Sum & 262754253.1 &  262935459.3 \\\\\n      \\hline\n      Variance & 262754253.1 & 261940796.5\\\\\n      \\hline\n      Standard Deviation & 18855.1 & 25825.0\\\\\n      \\hline\n    \\end{tabular}\n\n\\end{table}\n\n\nThe answers are almost perfect, for example on the mean value, considering that the cost is thousands of dollars, and the error is just 1 dollar. The simplicity of the query just lies to the following instruction:\n\nHowever, this is just a simple example, executed only once, hence it can not provide us with safe conclusions for the library. In order to do so, we are going to run more complicated examples moving forward.\n\n\\subsubsection{Lowering the Dataset size}\n\nAs we mentioned above, the entries that the dataset contains are a very large number, and we know as a fact that D.P. functions well when this is the case. How is the library going to respond though if the dataset size is smaller? We are going to run for 4 different values of epsilon, and get the results for an increasing number of entries, starting from 10, and moving to 2000. Thus, the X axis of each plot represents the increasing dataset size, the Y axis the accuracy error, and each plot has a title of the epsilon setting used for the measurements. We can see the results in \\textbf{Figure 3.1} below.\n\n\\begin{figure}[!htb]\\centering\n    \\includegraphics[width=1\\textwidth]{images/increasing_ds_size.png}\n    \\caption{Accuracy Error for Increasing Dataset Sizes}\n\\end{figure}\n\n\nBy observing the plots, we can make a couple of conclusions:\n\n\\begin{itemize}\n    \\item \\emph{The smaller the epsilon gets, the bigger the accuracy error in the case of small datasets.} This, according to the definition makes sense, because small epsilon indicates higher privacy, thus for small datasets it can mean lower accuracy, due to the high amount of noise added.\n    \\item \\emph{The accuracy error stabilizes near 0 as the size of the dataset gets over 1000 entries.} Of course, depending to the epsilon value, this point could be earlier in the dataset sizes, as we observe for ε $= 1$. This again lays in the above mentioned property of the definition.\n\\end{itemize}\n\n\\subsubsection{Epsilon measurements}\n\nThe most important aspect when applying Differential Privacy to a dataset, is the selection of epsilon. This number is held accountable of the trade-off that DP offers: how much accuracy are we going to sacrifice in order to have less privacy loss, and vice versa. Given the library and our surgeries' costs dataset, we are going to measure the accuracy changes with the selection of different epsilon values.\n\nThe size of the dataset is too big, and thus the computation of the sensitivity will take too long. We assume that the data are somewhat equally distributed, thus we chose only 1\\% of the dataset (which is a significant number of members), to take part in our sensitivity calculations.\n\nIn order to observe if the library functions well, we are going to compare the results produced with the \\emph{theoretical bounds of the Laplace mechanism}. \n\nIn theory, the accuracy of an ε-differential private query, when using the Laplace distribution, is equal to the sensitivity of the query divided by epsilon, thus $$\\frac{\\Delta f}{\\epsilon}$$ where $\\Delta f$ denotes the sensitivity, and ε is our current privacy setting. \n\nSensitivity is defined as the maximum difference that can be found if we alter a single entry in the dataset. We are interested in global sensitivity in order to conduct our testings, and is defined as:\n    \\begin{align*}\n        \\Delta f = \\frac{upper - lower}{length(DB)}\n    \\end{align*} where upper and lower are the highest and lowest values of the column we are interested in our dataset, and length is the size of the database.\n    \n    \nIn order to compute the local sensitivity, we must check the maximum difference in the query result that occurs if we remove a single person from the database. We are going to define a function to do so, so we can check the theoretical bounds during our tests.\n\nThe results of those testings are shown in the \\textbf{Figure 3.2}.\n\n\\begin{figure}[!htb]\\centering\n    \\includegraphics[width=1\\textwidth]{images/epsilon_measurements.png}\n    \\caption{Real and Optimal Accuracy Error for Increasing epsilon values}\n\\end{figure}\n\nIt is clear that as we increase the epsilon value, the privacy loss gets bigger. On the other hand, if epsilon is too small, as we can see in the above plot, extreme errors in accuracy in our queries will emerge. \n\nThe optimal value of epsilon varies, there is no general rule for the perfect epsilon. It depends on many different aspects, such as:\n\n\\begin{itemize}\n    \\item The noise generated by the probabilistic mechanism used\n    \\item The implementation of the algorithm\n    \\item The size of the dataset\n    \\item The query itself.\n\\end{itemize}\n\nMoreover, the selection of epsilon depends on the dataset. For example, we might have a dataset that is extremely important to have minimal privacy loss. In that case, we will opt to use a rather small epsilon, thus we do not disclose the sensitive data included. An other dataset could be less sensitive, but the analyst might have a need for extreme accuracy every time, so the epsilon selected should be rather big.\n\nRegarding the comparison with the Laplace bounds, we can see that the library's query performs significantly well throughout the different epsilon values selected. This is due to the fact that IBM uses the same formula to compute the sensitivity, as well as a similar mechanism (Laplace truncated noise), in order to answer to our queries.\n\n\\subsection{Histogram Queries}\n\nHistogram graphs are a very handy way to visualize numerical data, compare different values of a specific field, and thus extract conclusions about the dataset. We are going to study the `diffprivlib`'s method of creating an histogram, and its accuracy when changing the epsilon factor.\n\nThe IBM DP library offers a differential private way to create histograms. The difference with the simple queries that we tested, is that now, \\emph{geometric truncated} noise is added in order to satisfy DP.\n\n\\subsubsection{Metrics Used}\nThe result of a histogram query on a dataset is a vector containing how many entries belong on a specific range. Thus, the comparison between 2 histograms can be held out by comparing those vectors. \n\nThere are plenty of metrics used to compare vectors, but we are going to focus on the \\emph{Euclidean Metric} and the \\emph{Kantorovich metric} (also known as Wasserstein or EMD metric). \n\nThe Euclidean metric is one of the most simple metrics, as it takes into account the distance between each pair of the two vectors. Thus, the distance of the vectors is defined by:\n\n\\begin{align*}\n    d = \\sqrt{\\sum_{i=1}^n (x_i - y_i) ^ 2}\n\\end{align*}\n\nwhere $n$ are the total elements of the vectors (must be of equal size), and $x$ and $y$ are the 2 vectors that we are comparing.\n\nThe Kantorovich metric is a more complex one, as it examines the cost to move a specific quantity of the one vector to the other, in order for the two to be similar, and thus figuring out their distance. For example, the Kant. distance is larger if we have the vectors $[0 0 0 1]$ and $[1 0 0 0]$ than having the vectors $[0 0 0 1]$ and $[0 0 1 0]$, as in the first case the first element of the histogram is moved 3 places in order to be similar to the second one. In order to determine the cost, a base metric is used, which in our case will be the euclidean.\n\nThe way that the metric works in a naive approach, is explained in \\textbf{Figure 3.3.}\n\n\\begin{figure}[!htb]\\centering\n    \\includegraphics[width=0.7\\textwidth]{images/emd.png}\n    \\caption{Kantorovich Metric Application on 2 histograms}\n\\end{figure}\n\nThis metric is much more suitable for D.P. as we are not just interested in the alteration of the results, but on the amount of alteration. If, for example, we are examining a histogram that contains the age of a hospital's patients, it is not the same for the private histogram to deem a 10 year old patient as 90 year old, than deeming him as 11. \n\nIn order for the Kantorovich metric to be computed, we must solve a Dynamic Programming Problem, and make complex calculations, which are beyond the subject of this thesis. There are many implementations of the metric, and since IBM's library is written in Python, we are going to use the QIF library from [13] which is also available as a Python library. \n\n\n\\subsubsection{Bounds Definition}\n\nIn the following testings we are examining salaries, thus we must set the lower and the higher bounds such as to support the most extreme salaries that could possibly be present in the dataset. Therefore, the lower bound is set to 0 dollars, and the higher to 500,000 dollars.\n\n\\subsubsection{The identity of the testing Dataset}\n\nDuring our histogram testings, we are going to use a different dataset, which contains  sensitive data regarding employee's salaries in the state of Baltimore, while stating other facts about the members of the dataset. \n\nThe columns contained are: \n\\begin{itemize}\n    \\item Name\n    \\item Job Title\n    \\item Annual earnings\n    \\item Gross earnings\n\\end{itemize}\n\nWe are going to focus on the last 2 columns, containing the employees' salaries. The dataset has 13000 entries, which are more than enough in order for our histograms to be realistic and accurate. The above table gives us an image of the containers of the dataset.\n\n\\begin{table}[!htb]\n    \\centering\n\n    \\caption{\"Baltimore State Employees Salaries\" dataset columns}\n    \\label{numbers}\n\n    \\begin{tabular}{| c | c | c | c |}\n      \\hline \n      Name & Job Title & Annual Earnings & Gross \\\\\n      \\hline\n      Aaron,Kareem D & Utilities Inst Repair I\t & 32470.0 & 25743.94 \\\\\n      \\hline\n      Abadir,Adam O\t & Police Officer &  60200.0 & 57806.13  \\\\\n      \\hline\n      Abbeduto,Mack & Council Technician & 53640.0 &  59361.55 \\\\\n      \\hline\n    \\end{tabular}\n\\end{table}\n\n\\subsubsection{Simple queries}\n\nAt first, we are going to run simple instances of histogram queries, so we can take a look at the amount of error that we expect moving forward, and also familiarize with the execution of the commands. To create a private histogram using the library, we must provide the bins. Those should be identical to our bounds, that we have earlier defined. While creating the non-private histograms we are going to use the same bounds, in order for our comparisons to make sense. The creation of the bins and the private histogram are achieved using the following Python instructions:\n\n\\bigskip\n\\begin{lstlisting}[basicstyle= \\footnotesize,\nlanguage=Python]\nbins = np.linspace(0, 300000, 20)[1:]\nresult = dp.tools.histogram(input_list, bins = bins, \n         epsilon = epsilon, range=bounds_range)[0]\n\\end{lstlisting}\n\\bigskip\n\nwhere epsilon is the float number selected as the epsilon parameters, and bounds range is the tuple of our dataset bounds.\n\nThe result of the execution of both the private and the non-private histogram queries for the annual earnings column are shown below, in the \\textbf{Figure 3.4}.\n\n\\begin{figure}[!htb]\\centering\n    \\includegraphics[width=1\\textwidth]{images/simple_hists.png}\n    \\caption{Private and Non-private histograms for the Salaries Dataset}\n\\end{figure}\n\nThe results are quite impressive. This is probably due to the large dataset size: we are not able to locate small changes. In order to do so, we are going to check our error using the accuracy error function that we have defined.\n\nWhile applying our metrics, the Euclidean error is $14.81$, and the Kantorovich error is $91.63$. The euclidean distance error determines how many entries were wrongly classified in a bin (in average), when the differentially private query was run. So, less than 20 people out of 13.000 were wrongly classified, whereas their privacy was secured. This is quite a good trade-off!\n\n\\subsubsection{Epsilon Measurements}\n\nOnce again, we are going to run the histogram queries for different values of epsilon, in order to check their behavior as the parameter increases. The results of the execution for the Euclidean metric are shown in the \\textbf{Figure 3.4}, and for the Kantorovich metric in the \\textbf{Figure 3.5}. \n\n\n\\begin{figure}[!htb]\\centering\n    \\includegraphics[width=1\\textwidth]{images/hist_metrics_euclidean.png}\n    \\caption{Euclidean Metric Error for increasing values of epsilon}\n\\end{figure}\n\n\\begin{figure}[!htb]\\centering\n    \\includegraphics[width=1\\textwidth]{images/hist_metrics_kantorovich.png}\n    \\caption{Kantorovich Metric Error for increasing values of epsilon}\n\\end{figure}\n\nWe observe that the error curves follow the same ratio as the previous ones, indicating what we already know, that the error decreases as the epsilon values increase. This is another case where the library produces accurate and definition-aware results. \n\n\\subsubsection{Histogram queries in theory}\nBased on [1] the histogram queries are very high sensitivity queries, thus a slight change to the bounds could be critical for their result. \n\nThe authors suggest that we use noise generated by the Laplace mechanism, but with a slight change. In detail they suggest the following:\n\n\\textit{\"In the special (but common) case in which the queries are structurally disjoint we can do much better — we do not necessarily have to let the noise scale with the number of queries. An example is the histogram query. In this type of query the universe $N^X$ is partitioned into cells, and the query asks how many database elements lie in each of the cells. Because the cells are disjoint, the addition or removal of a single database element can affect the count in exactly one cell, and the difference to that cell is bounded by 1, so histogram queries have sensitivity 1 and can be answered by adding independent draws from $Lap(\\frac{1}{\\epsilon})$ to the true count in each cell.\"}\n\\clearpage\n\n\\subsection{Conclusions}\n\nAfter a rather satisfying amount of testing in a large, real world dataset, we suggest that the IBM DP library has quite impressive results when it comes down to the trade-off between privacy and accuracy during both simple counting queries and histogram ones. However, we are cautious about 2 problems that were observed while using the library:\n\n\\begin{itemize}\n \\item \\emph{Bounds checking}. The user must define himself the bounds, a fact that causes for speculations on the variance of the values in the dataset. It would be convenient to take the lowest and highest value in the field that we are examining, in fact that is how IBM demonstrates those examples, but that violates the rule that prevents the user from having any info of the dataset before the DP processing.\n \n \\item \\emph{Non-DP preprocessing}. If we ask complicated queries (ex Surgeries performed in Stanford), the library does not offer a way to preprocess the data, thus we trust python in doing so, which results in a non-DP way of shrinking the dataset. The result obtained is of course differential private, but what happens if the dataset has only 1 record in it? That, while being a very extreme case, violates the definition of differential privacy.\n\\end{itemize}\n\nThe bounds' problem can be solved if the users have prior knowledge in the domain of the dataset, in order to safely define the bounds themselves. \n\nThe Non-DP preprossessing is a more tricky one, that needs special techniques in order to cover the edge case mentioned. However, we are going to check such techniques in the following section, which is based on returning the whole dataset after the application of D.P.\n\n", "meta": {"hexsha": "2d87774819ac705c1ba63ac68479328f52740356", "size": 26959, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis_paper/GDP/IBM.tex", "max_stars_repo_name": "nikosgalanis/bsc-thesis", "max_stars_repo_head_hexsha": "b5521e995f266ff1aeb9fecc220650483630dc04", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2021-07-29T15:24:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T13:57:07.000Z", "max_issues_repo_path": "thesis_paper/GDP/IBM.tex", "max_issues_repo_name": "nikosgalanis/bsc-thesis", "max_issues_repo_head_hexsha": "b5521e995f266ff1aeb9fecc220650483630dc04", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis_paper/GDP/IBM.tex", "max_forks_repo_name": "nikosgalanis/bsc-thesis", "max_forks_repo_head_hexsha": "b5521e995f266ff1aeb9fecc220650483630dc04", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 72.6657681941, "max_line_length": 696, "alphanum_fraction": 0.7708371972, "num_tokens": 6202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.30096313101869365}}
{"text": "\\documentclass[a4paper, 12pt]{article}\n\n\\usepackage[utf8]{inputenc}\n\\usepackage[T1]{fontenc}\n\\usepackage{bm}\t\t\t\t\t\t% Typesetting matrices\n\\usepackage{authblk}\t\t\t\t% Affiliation in title\n\\usepackage{amsmath}\t\t\t\t% All kinds of shit\n\\usepackage{amssymb}\t\t\t\t% For blackboard bold\n\\usepackage{commath}\t\t\t\t% Differetial operators\n\\usepackage{array}\t\t\t\t\t% Fancy tables\n\\usepackage{units}\t\t\t\t\t% Slanted fractions\n\\usepackage{enumitem}\t\t\t\t% Sep options\n\\usepackage{fouridx}\t\t\t\t% Pre-superscript\n\\usepackage{float}\t\t\t\t\t% Force float placement\n\\usepackage{graphicx}\t\t\t\t% For images etc.\n\\usepackage[hidelinks]{hyperref}\t% Clickable toc\n\\usepackage[usenames, dvipsnames]{xcolor}\n\\newcommand{\\comment}[1]{\\textcolor{RedOrange}{#1}}\n\n\\title{Summary of \\\\ TTK4130 Modeling and Simulation}\n\\author{Morten Fyhn Amundsen}\n\\affil{NTNU}\n\n\\begin{document}\n\\maketitle\n\\tableofcontents\n\\newpage\n\n\\newcommand{\\enforall}{\\enskip \\forall \\enskip}\n\\newcommand{\\residual}{\\operatornamewithlimits{Res}}\n\\newcommand{\\V}[1]{\\mathbf{#1}}\t\t\t\t\t\t\t% Bold vector\n\\newcommand{\\M}[1]{\\bm{#1}}\t\t\t\t\t\t\t\t% Matrix\n\\newcommand{\\I}{\\mathbf{I}}\t\t\t\t\t\t\t\t% Identity matrix\n\\newcommand{\\y}{\\V{y}}\t\t\t\t\t\t\t\t\t% y vector\n\\newcommand{\\ydot}{\\V{\\dot{y}}}\t\t\t\t\t\t\t% ydot vector\n\\newcommand{\\R}{\\M{R}}\t\t\t\t\t\t\t\t\t% Rotation matrix\n\\newcommand{\\T}{^{\\text{T}}}\t\t\t\t\t\t\t% Transpose\n\\newcommand{\\half}{\\nicefrac{1}{2}}\t\t\t\t\t\t% Slanted 1/2 fraction\n\\newcommand{\\nf}[2]{\\nicefrac{#1}{#2}}\t\t\t\t\t% Shorthand for slanted fractions\n\\newcommand{\\angvel}{\\boldsymbol{\\omega}}\n\\newcommand{\\gv}[1]{\\boldsymbol{#1}}\n\\newcommand{\\lagr}{\\mathcal{L}}\n\\newcommand{\\presuper}[1]{\\fourIdx{#1}{}{}{}}\n\n\\renewcommand{\\c}{\\operatorname{c}}\t\t\t\t\t\t% Shorthand for cos, used in large matrices\n\\newcommand{\\s}{\\operatorname{s}}\t\t\t\t\t\t% Ditto sin\n\\renewcommand{\\b}[1]{\\textbf{#1}}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Introduction}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nI can't be bothered to write much here. You know what you're doing.\n\n\\subsection{Todo}\n\\begin{itemize}\n\t\\item Force and torque matrices \\( \\M{F}^b_{bc} \\).\n\t\\item \\comment{p. 533}\n\\end{itemize}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Things that ought to be obvious}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\paragraph{Eigenvalues} Values of \\( \\lambda \\) such that: \\( \\det{\\lambda \\I - \\M{A}} = 0 \\).\n\\paragraph{Eigenvectors} Vectors \\( \\V{v} \\) such that: \\( (\\M{A} - \\lambda \\I)\\V{v} = 0 \\).\n\\paragraph{Differentiation of \\(x^2\\):} \\(\\od{x^2}{t} = 2 \\dot{x} x\\)\n\\paragraph{Relation of velocity to ang. vel.:} \\(v = r \\omega\\)\n\\paragraph{Matrix transposes:} \\( (\\M{A} + \\M{B})\\T = \\M{A}\\T + \\M{B}\\T, \\quad (\\M{AB})\\T = \\M{B}\\T \\M{A}\\T \\)\n\\paragraph{Inverse of \\(2 \\times 2\\) matrix:}\n\\[\n\\M{A}^{-1} = \n\\begin{pmatrix} a & b \\\\ c & d \\end{pmatrix}^{-1} =\n\\frac{1}{\\det \\M{A}} \\begin{pmatrix} d & -b \\\\ -c & a \\end{pmatrix}\n\\] \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Energy-flow modelling (19)}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nA modular, rather than monolithic approach to modelling a dynamic system. Modules are connected with one \\emph{potential} and one \\emph{flow} variable, similar to their physical connection. At a connection, potentials must be equal, and flows must sum to zero.\n\n\\begin{table}[H]\n\\small\n\\begin{tabular}{llll}\n\t\\b{Domain}  & \\b{Potential}           & \\b{Flow}                                 & \\b{Result} \\\\\n\t\\hline\n\tTranslation & Velocity [m/s]          & Force [N]                                & Power [W]  \\\\\n\tRotation    & Angular velocity [/s]   & Torque [Nm]                              & Power [W]  \\\\\n\tElectrical  & Voltage [V]             & Current [A]                              & Power [W]  \\\\\n\tMagnetic    & Mag.mot. force [A]      & Mag. flux rate [V]                       & Power [W]  \\\\\n\tHydraulic   & Pressure [Pa]           & Volume flow rate [m\\(^3\\)/s]             & Power [W]  \\\\\n\tThermal     & Temperature [K]         & Heat flow rate [J/Ks]                    & Power [W]  \\\\\n\tChemical    & Chem. potential [J/mol] & Molar flow rate [mol/s]                  & Power [W]\n\\end{tabular}\n\\end{table}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Energy (\\emph{Lyapunov}) functions and passivity (46)}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\paragraph{Energy functions} describe the change of internal `energy' in a system. \\emph{Decreasing energy implies stability.}\n\nThe time derivative of the energy function is\n\\begin{equation}\n\t\\dot{V} = \\pd{V}{t} + \\pd{V}{\\V{x}} \\V{f}(\\V{x}, \\V{u}, t).\n\\end{equation}\n\n\\paragraph{Passivity} describes whether a system produces energy to its surroundings.\n(Example: Power in a resistor: \\(P = u i = R i^2 \\implies P \\geq 0 \\implies\\) Passive!)\n\\begin{itemize}\n\t\\item Connected stable systems are not always stable...\n\t\\item Connected passive systems are always passive, and therefore stable!\n\\end{itemize}\nA system with input \\(u\\) and output \\(y\\) is passive if\n\\begin{equation}\n\t\\int_0^t y(\\tau) u(\\tau) \\dif \\tau \\geq - E_0 \\enforall t \\geq 0\n\\end{equation}\nfor all inputs.\n\n\\subsection{Positive realness of a transfer function (56)}\nA system is passive iff its transfer function is positive real.\n\\paragraph{Definition:} The t.f. \\(H(s)\\) (rational or not) is positive real if:\n\\begin{enumerate}\n\t\\item \\(H(s)\\) is analytic \\( \\enforall \\Re[s] > 0 \\)\n\t\\item \\(H(s)\\) is real for all positive and real \\(s\\).\n\t\\item \\(\\Re[H(s)] \\geq 0 \\enforall \\Re [s] > 0\\).\n\\end{enumerate}\nBut this is easier to use:\n\\paragraph{Theorem:} A rational, proper t.f. \\(H(s)\\) is positive real iff:\\footnote{if and only if}\n\\begin{enumerate}\n\t\\item \\( H(s) \\) has no poles in the right half plane.\n\t\\item \\( \\Re[H(\\jmath \\omega)] \\geq 0 \\enforall \\omega \\) such that \\( \\jmath \\omega \\) is not a pole of \\( H(s) \\).\n\t\\item If \\( \\jmath \\omega_0 \\) is a pole in \\( H(s) \\), it is a simple pole, and the residual in \\( s = \\jmath \\omega_0 \\) is positive and real, i.e.,\n\t\\[ \\residual_{s = \\jmath \\omega_0} H(s) = \\lim_{s \\to \\jmath \\omega_0} (s - \\jmath \\omega_0) H(s) > 0 \\] (And some stuff about poles at infinity.)\n\\end{enumerate}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Simulation (509)}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Notation (517)}\n\\begin{equation}\\label{eq:ivp}\n\t\\underbrace{\n\t\t\\underbrace{\n\t\t\t\\V{\\ydot} = \\V{f}(\\y, t)\n\t\t}_{\n\t\t\t\\text{ODE}\n\t\t}\n\t\t,\\quad \\y(t_0) = \\y_0\n\t}_{\\text{IVP}}\n\\end{equation}\nGiven this, we want to approximate \\( \\V{y}(t) \\).\n\n\\subsection{Error (517)}\nThe \\emph{local solution} \\( \\y_L(t_n; t) \\) is the exact solution of \\eqref{eq:ivp} with initial condition \\( \\y_n \\) at time \\( t_n \\):\n\\begin{equation}\n\t\\ydot_L(t_n; t) = \\V{f}[\\y_L(t_n; t)], \\quad \\y_L(t_n; t_n) = \\y_n\n\\end{equation}\nI.e., if the system really is in state \\( \\y_n \\) at time \\( t_n \\), the local solution is the true behaviour.\n\nThis lets us define the \\emph{local error}: the difference between the computed solution and the local solution at \\( t_{n+1} \\):\n\\begin{equation}\n\t\\V{e}_{n+1} = \\y_{n+1} - \\y_L(t_n; t_{n+1})\n\\end{equation}\n\nThe \\emph{global error} is the difference between the computed solution and the exact solution at \\( t_{n+1} \\):\n\\begin{equation}\n\t\\V{E}_{n+1} = \\y_{n+1} - \\y(t_{n+1})\n\\end{equation}\n\n\\subsection{Order of a one-step method (517)}\nA method is of order \\( p \\) if \\( \\V{e}_{n+1} = O(h^{p+1}) \\).\n\nGiven the IVP in \\eqref{eq:ivp} and a one-step method (of step length \\( h \\))\n\\begin{equation}\\label{eq:onestep}\n\t\\y_{n+1} = \\y_n + h \\phi(\\y_n, t_n),\n\\end{equation}\nif then\n\\begin{equation}\n\t\\y_{n+1} = \\y_n + h \\V{f}(\\y_n, t) + \\frac{h^2}{2} \\od{\\V{f}(\\y_n, t)}{t} + \\hdots + \\frac{h^p}{p!} \\od[p-1]{\\V{f}(\\y_n, t)}{t} + O(h^{p+1})\n\\end{equation}\nholds, the local error is \\( O(h^{p+1}) \\) and the method is of order \\( p \\).\n\n\\subsection{Linearisation (518)}\nThe linearisation of \\eqref{eq:ivp} around \\( \\y^* \\) is\n\\begin{equation}\n\t\\Delta \\ydot = \\M{J} \\Delta \\y,\n\\end{equation}\nwhere \\( \\M{J} \\) is\n\\begin{equation}\n\t\\M{J}\n\t= \\pd{\\V{f}(\\y,t)}{\\y} \\biggr\\rvert_{\\y = \\y^*}\n\t= \\left\\{ \\dpd{f_i(\\y,t)}{y_j} \\biggr\\rvert_{\\y = \\y^*} \\right\\}.\n\\end{equation}\n\n\\subsection{Stability (531)}\n\\subsubsection{Scalar test system}\nGiven the scalar test system\n\\begin{equation}\n\t\\dot{y} = \\lambda y\n\\end{equation}\nwe get\n\\begin{equation}\n\ty_{n+1} = R(h \\lambda) y_n\n\\end{equation}\nwhere \\( R(h \\lambda )\\) is the stability function of a numerical method.\n\\subsubsection{Requirement for stability}\nThe numerical solution \\( \\Delta \\y_n \\) of the linearised system is stable if:\n\\begin{equation}\n\t| R(h\\lambda_i) | \\leq 1\n\\end{equation}\nfor all eigenvalues \\( \\lambda_i \\) of \\( \\M{J} \\).\n\n\\subsection{Explicit Runge-Kutta methods (ERK) (526)}\nGiven the IVP in \\eqref{eq:ivp} and the generic one-step method in \\eqref{eq:onestep}, the general ERK is\n\\begin{equation}\n\t\\begin{aligned}\n\t\t\\V{k}_1 &= \\V{f}(\\y_n, \\enspace t_n) \\\\\n\t\t\\V{k}_2 &= \\V{f}(\\y_n + h a_{21}\\V{k}_1, \\enspace t_n + c_2 h) \\\\\n\t\t\\V{k}_3 &= \\V{f}(\\y_n + h (a_{31}\\V{k}_1 + a_{32} \\V{k}_2), \\enspace t_n + c_3 h) \\\\\n\t\t\t\t& \\enspace \\vdots \\\\\n\t\t\\V{k}_\\sigma &= \\V{f}(\\y_n + h (a_{\\sigma 1}\\V{k}_1 + \\hdots + a_{\\sigma,\\sigma-1}\\V{k}_{\\sigma-1}), \\enspace t_n + c_\\sigma h) \\\\\n\t\t\\y_{n+1} &= \\y_n + h (b_1 \\V{k}_1 + \\hdots + b_\\sigma \\V{k}_\\sigma).\n\t\\end{aligned}\n\\end{equation}\nThe weights can be arranged in a \\emph{Butcher array}:\n\\begin{equation}\n\\begin{array}{c|ccccc}\n0        &              &              &        &                      &          \\\\\nc_2      & a_{21}       &              &        &                      &          \\\\\nc_3      & a_{31}       & a_{32}       &        &                      &          \\\\\n\\vdots   & \\vdots       & \\vdots       & \\ddots &                      &          \\\\\nc_\\sigma & a_{\\sigma 1} & a_{\\sigma 2} & \\hdots & a_{\\sigma, \\sigma-1} &          \\\\ \\hline\n         & b_1          & b_2          & \\hdots & b_{\\sigma-1}         & b_\\sigma \\\\\n\\end{array}\n\\quad \\text{or} \\quad\n\\begin{array}{c|c}\n    \\V{c} & \\M{A}   \\\\ \\hline\n          & \\V{b}\\T \\\\\n\\end{array}\n\\end{equation}\nWhere \\( \\sigma \\) is the number of stages.\n\n\\subsubsection{ERK stability}\nThe stability function of an ERK is\n\\begin{equation}\n\tR_E(h\\lambda) = \\det \\left[ \\I -\\lambda h \\left( \\M{A} - \\V{1 b}\\T \\right) \\right]\n\\end{equation}\nwhere \\(\\M{A}\\) and \\(\\V{b}\\) are given by the Butcher array.\n\nFor ERKs of order \\( p = \\sigma \\leq 4 \\):\n\\begin{equation}\n\tR_E(h \\lambda) = 1 + h \\lambda + \\dots + \\frac{h^p \\lambda^p}{p!}\n\\end{equation}\nValid for Euler's method, Modified Euler, RK4, and at least one other. These are the methods that are actually used.\n\n\\subsubsection{Euler's method (Forward Euler)}\n\\begin{equation}\n\t\\y_{n+1} = \\y_n + h\\V{f}(\\y_n, t_n)\n\t\\iff\n\t\\begin{array}{c|c}\n\t\t0 &   \\\\ \\hline\n\t\t  & 1 \\\\\n\t\\end{array}\n\\end{equation}\n\n\\subsubsection{Improved Euler}\n\\begin{equation}\n\t\\begin{array}{rcl}\n\t\t\\V{k}_1  &=& \\V{f}(\\y_n, t_n) \\\\\n\t\t\\V{k}_2  &=& \\V{f}(\\y_n + h \\V{k}_1, t_n + h) \\\\\n\t\t\\y_{n+1} &=& \\y_n + \\frac{h}{2}(\\V{k}_1 + \\V{k}_2) \\\\\n\t\\end{array}\n\t\\iff\n\t\\begin{array}{c|cc}\n\t\t0 &       &       \\\\\n\t\t1 & 1     &       \\\\ \\hline\n\t\t  & \\half & \\half \\\\\n\t\\end{array}\n\\end{equation}\n\n\\subsubsection{Modified Euler (Explicit midpoint)}\n\\begin{equation}\n\t\\begin{array}{rcl}\n\t\t\\V{k}_1  &=& \\V{f}(\\y_n, t_n) \\\\\n\t\t\\V{k}_2  &=& \\V{f}(\\y_n + \\frac{h}{2}\\V{k}_1, t_n + \\frac{h}{2}) \\\\\n\t\t\\y_{n+1} &=& \\y_n + h\\V{k}_2 \\\\\n\t\\end{array}\n\t\\iff\n\t\\begin{array}{c|cc}\n\t\t0     &       &   \\\\\n\t\t\\half & \\half &   \\\\ \\hline\n\t\t      & 0     & 1 \\\\\n\t\\end{array}\n\\end{equation}\n\n\\subsubsection{Heun's method}\n\\begin{equation}\n\t\\begin{array}{c|ccc}\n\t\t0         &           &           &           \\\\\n\t\t\\nf{1}{3} & \\nf{1}{3} &           &           \\\\\n\t\t\\nf{2}{3} & 0         & \\nf{2}{3} &           \\\\\n\t\t\\hline\n\t\t          & \\nf{1}{4} & 0         & \\nf{3}{4} \\\\\n\t\\end{array}\n\\end{equation}\n\n\\subsubsection{Runge-Kutta 4}\n\\begin{equation}\n    \\begin{array}{c|cccc}\n\t\t0     &           &           &           &           \\\\\n\t\t\\half & \\half     &           &           &           \\\\\n\t\t\\half & 0         & \\nf{1}{2} &           &           \\\\\n\t\t1     & 0         & 0         & 1         &           \\\\ \\hline\n              & \\nf{1}{6} & \\nf{2}{6} & \\nf{2}{6} & \\nf{1}{6} \\\\\n    \\end{array}\n\\end{equation}\n\n\\subsection{Implicit Runge-Kutta methods (IRK) (534)}\nDefined as\n\\begin{equation}\n\\begin{aligned}\n\\V{k}_1      &= \\V{f}(\\y_n + h(a_{11}\\V{k}_1 + \\hdots + a_{1 \\sigma}\\V{k}_\\sigma), \\enspace t_n + c_1 h) \\\\\n             &  \\enskip \\vdots \\\\\n\\V{k}_\\sigma &= \\V{f}(\\y_n + h(a_{\\sigma 1}\\V{k}_1 + \\hdots + a_{\\sigma \\sigma}\\V{k}_\\sigma), \\enspace t_n + c_\\sigma h) \\\\\n\\y_{n+1}     &= \\y_n + h (b_1\\V{k}_1 + \\hdots + b_\\sigma\\V{k}_\\sigma)\n\\end{aligned}\n\\end{equation}\n\n\\begin{equation}\n\\begin{array}{c|ccccc}\nc_1      & a_{11}       & a_{12}       & \\dots  & \\dots               & a_{1\\sigma}      \\\\\nc_2      & a_{21}       & a_{22}       & \\dots  & \\dots               & a_{1\\sigma}      \\\\\n\\vdots   & \\vdots       & \\vdots       & \\ddots & \\ddots              & \\vdots           \\\\\nc_\\sigma & a_{\\sigma 1} & a_{\\sigma 2} & \\dots  & a_{\\sigma,\\sigma-1} & a_{\\sigma\\sigma} \\\\ \\hline\n         & b_1          & b_2          & \\dots & b_{\\sigma-1}         & b_\\sigma         \\\\\n\\end{array}\n\\quad \\text{or} \\quad\n\\begin{array}{c|c}\n    \\V{c} & \\M{A}   \\\\ \\hline\n          & \\V{b}\\T \\\\\n\\end{array}\n\\end{equation}\nIRKs efficiently solve stiff systems (i.e. systems with a large spread in eigenvalues). ERKs do not. Stability is generally the motivation for using IRKs, not accuracy.\n\n\\subsubsection{IRK stability}\nThe stability of an IRK is given by\n\\begin{align}\n\tR(h\\lambda)\t&= 1 + \\lambda h \\V{b}\\T ( \\I - h \\lambda \\M{A} )^{-1} \\V{1} \\\\\n\t\t\t\t&= \\frac{\n\t\t\t\t\t\\det \\left( \\I - \\lambda h \\left[ \\M{A} - \\V{1b}\\T \\right] \\right)\n\t\t\t\t\t}{\n\t\t\t\t\t\\det ( \\I - \\lambda h \\M{A} )\n\t\t\t\t\t}\n\\end{align}\n\n\\subsubsection{Implicit Euler (Radau IIA)}\n\\begin{equation}\n\t\\begin{array}{rcl}\n\t\t\\V{k}_1  &=& \\V{f}(\\y_n + h \\V{k}_1, t_{n+1}) \\\\\n\t\t\\y_{n+1} &=& \\y_n + h \\V{k}_1 \\\\\n\t\\end{array}\n\t\\iff\n\t\\begin{array}{c|c}\n\t\t1 & 1 \\\\ \\hline\n\t\t  & 1 \\\\\n\t\\end{array}\n\\end{equation}\nThis is stable for all eigenvalues \\emph{outside} a unit circle with center \\((1, 0)\\)!\n\n\\subsection{A- and L-stability (546)}\n\\paragraph{A-stability:} A method is A-stable if \\( |R(\\lambda h)| \\leq 1 \\enforall \\Re(\\lambda) \\leq 0 \\).\n\nThis implies that the method is stable for all stable test systems. Thus, it is also stable for systems with very fast dynamics compared to \\(h\\), but note that aliasing can occur. High frequency oscillations appear in the solution as oscillations slower than the Nyquist frequency \\( \\frac{\\pi}{h}\\).\n\nNote that no explicit methods are A-stable.\n\n\\paragraph{L-stability:} A method is L-stable if it is A-stable, and \\(\\lim_{\\omega \\rightarrow \\infty} |R(\\jmath \\omega h)| = 0\\) for all systems \\( \\dot{y} = \\lambda y \\) where \\( \\lambda = \\jmath \\omega \\).\n\nL-stable methods dampen out the inaccurate, fast dynamics that can occur with A-stable methods.\n\n\\subsection{Padé-approximations (548)}\nThe local solution of the test system \\( \\dot{y} = \\lambda y \\) over a time step, and the numerical solution of the same system, is\n\\begin{gather}\n\t\\dot{y}_L(t_n; t_{n+1}) = e^{\\lambda h} y_n \\\\\n\ty_{n+1} = R(\\lambda h) y_n\n\\end{gather}\nThe accuracy of the numerical solution depends on how well \\( R(\\lambda h) \\) approximates the exponential function.\n\nA Padé approximation \\( P^k_m(s) \\) is the best rational approximation of \\( e^s \\) with a numerator of order \\(k\\) and a denominator of order \\(m\\).\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Rotation matrices (218)}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Vectors (209)}\nThe vector\n\\begin{equation}\n\t\\vec{v} = v_1 \\vec{a_1} + v_2 \\vec{a_2} + v_3 \\vec{a_3}\n\\end{equation}\nhas `built in' information about its frame of reference (it is \\emph{coordinate free}). However, the coordinate vector\n\\begin{equation}\n\t\\V{u}^a =\n\t\\begin{pmatrix}\n\t\tu_1 & u_2 & u_3 \\\\\n\t\\end{pmatrix}\n\t\\T\n\\end{equation}\ndoes not, and we must indicate which frame of reference it is given in (frame \\(a\\) in this case).\n\n\\subsection{Skew-symmetric form (211)}\n\\begin{equation}\n\t\\V{u}^\\times :=\n\t\\begin{pmatrix}\n\t\t0    & -u_3 & u_2  \\\\\n\t\tu_3  & 0    & -u_1 \\\\\n\t\t-u_2 & u_1  & 0    \\\\\n\t\\end{pmatrix}\n\\end{equation}\n\n\\subsection{Vector cross product (211)}\n\\begin{equation}\n\t\\V{w} = \\V{u}^\\times \\V{v}\n\t\\iff\n\t\\vec{w} = \\vec{u} \\times \\vec{v}\n\\end{equation}\nAlternatively:\n\\begin{equation}\n\t\\V{w} = \\V{u}^\\times \\V{v} =\n\t\\begin{pmatrix}\n\t\tu_2 v_3 - u_3 v_2 \\\\\n\t\tu_3 v_1 - u_1 v_3 \\\\\n\t\tu_1 v_2 - u_2 v_1 \\\\\n\t\\end{pmatrix}\n\\end{equation}\n\n\\subsection{Properties of the rotation matrix (219)}\n\\paragraph{Notation:} \\( \\V{v}^a = \\begin{pmatrix} v_1^a & v_2^a & v_3^a \\end{pmatrix}\\T \\) is vector \\( \\V{v} \\) given in the coordinates of \\(a\\).\n\n\\begin{equation}\n\t\\begin{aligned}\n\t\t\\V{v}^a\t\t\t\t&= \\R_b^a \\V{v}^b \\\\\n\t\t\\R_a^b\t\t\t\t&= (\\R_b^a)^{-1} = (\\R_b^a)\\T \\\\\n\t\t\\R^a_c\t\t\t\t&= \\R^a_b \\R^b_c \\\\\n\t\t(\\V{u}^b)^\\times\t&= \\R^b_a (\\V{u}^a)^\\times \\R^a_b \\\\\n\t\\end{aligned}\n\\end{equation}\n\\paragraph{Definition:} A matrix \\(\\R\\) is a rotation matrix iff \\(\\R \\in SO(3)\\):\n\\begin{equation}\n\tSO(3) = \\lbrace \\R \\enspace |\n\t\\enspace \\R \\in \\mathbb{R}^{3 \\times 3},\n\t\\enspace \\R\\T\\R = \\I,\n\t\\enspace \\det \\R = 1 \\rbrace\n\\end{equation}\n\n\\subsection{Simple rotations (221)}\nA \\emph{simple rotation} is a rotation about a fixed axis. Rotation matrices for rotation around the \\( x \\), \\( y \\), and \\( z \\) axes, respectively, are as follows:\n\\begin{gather}\\label{eq:simplerot}\n\t\\R_x(\\phi) =\n\t\\begin{pmatrix}\n\t\t1 & 0         & 0          \\\\\n\t\t0 & \\cos \\phi & -\\sin \\phi \\\\\n\t\t0 & \\sin \\phi & \\cos \\phi  \\\\\n\t\\end{pmatrix} \\\\\n\t\\R_y(\\theta) =\n\t\\begin{pmatrix}\n\t\t\\cos \\theta  & 0 & \\sin \\theta \\\\\n\t\t0            & 1 & 0           \\\\\n\t\t-\\sin \\theta & 0 & \\cos \\theta \\\\\n\t\\end{pmatrix} \\\\\n\t\\R_z(\\psi) =\n\t\\begin{pmatrix}\n\t\t\\cos \\psi & -\\sin \\psi & 0 \\\\\n\t\t\\sin \\psi & \\cos \\psi  & 0 \\\\\n\t\t0         & 0          & 1 \\\\\n\t\\end{pmatrix}\n\\end{gather}\n\n\\subsection{Euler angles (224)}\nA parametrisation of rotation about three axes. Three parameters \\( \\psi, \\theta, \\phi \\). Singularities exist.\n\\paragraph{Roll, pitch, yaw:} A rotation \\( \\psi \\) about the \\( z \\)-axis, then \\( \\theta \\) about the (rotated) \\( y \\)-axis, then \\( \\phi \\) about the (also rotated) \\( x \\)-axis.\n\\begin{equation}\n\t\\begin{aligned}\n\t\t\\R^a_b &= \\R_z(\\psi) \\R_y(\\theta) \\R_{\\underline{x}}(\\phi) \\\\\n\t\t&=\n\t\t\\begin{pmatrix}\n\t\t\t\\c\\psi \\s\\theta & \\c\\psi \\s\\theta \\s\\phi - \\s\\psi \\c\\phi & \\s\\psi \\s\\phi + \\c\\psi \\s\\theta \\c\\phi \\\\\n\t\t\t\\s\\psi \\c\\theta & \\c\\psi \\c\\phi + \\s\\psi \\s\\theta \\s\\phi & \\s\\psi \\s\\theta \\c\\phi - \\c\\psi \\s\\phi \\\\\n\t\t\t-\\s\\theta       & \\c\\theta \\s\\phi                        & \\c\\theta \\c\\phi                        \\\\\n\t\t\\end{pmatrix}\n\t\\end{aligned}\n\\end{equation}\n\\paragraph{Classical Euler angles:} A rotation \\( \\psi \\) about the \\( z \\)-axis, then \\( \\theta \\) about the (rotated) \\( y \\)-axis, then \\( \\phi \\) about the (also rotated) \\( z \\)-axis.\n\\begin{equation}\n\t\\begin{aligned}\n\t\\R^a_b &= \\R_z(\\psi) \\R_y(\\theta) \\R_{\\underline{z}}(\\phi) \\\\\n\t&=\n\t\\begin{pmatrix}\n\t\t\\c\\psi \\c\\theta \\c\\phi - \\s\\psi \\s\\phi & -\\c\\psi \\c\\theta \\s\\phi - \\s\\psi \\c\\phi & \\c\\psi \\s\\theta \\\\\n\t\t\\s\\psi \\c\\theta \\c\\phi + \\c\\psi \\s\\phi & \\c\\psi \\c\\phi - \\s\\psi \\c\\theta \\s\\phi  & \\s\\psi \\s\\theta \\\\\n\t\t-\\s\\theta \\c\\phi                       & \\s\\theta \\s\\phi                         & \\c\\theta        \\\\\n\t\\end{pmatrix}\n\t\\end{aligned}\n\\end{equation}\n\n\\subsection{Angle-axis description of rotation (226)}\nDescribes a rotation by an axis of rotation \\( \\V{k} \\) about which we move by an angle \\( \\theta \\) (four parameters \\( k_1, k_2, k_3, \\theta \\)).\n\\begin{equation}\n\t\\R^a_b \\V{k} = \\V{k}, \\quad \\V{k}^a = \\V{k}^b = \\V{k}\n\\end{equation}\nWith this method, the rotation matrix becomes\n\\begin{equation}\n\t\\R^a_b = \\cos \\theta \\I\n\t+ \\sin \\theta (\\V{k}^a)^\\times\n\t+ (1-\\cos \\theta) \\V{k}^a(\\V{k}^a)\\T\n\\end{equation}\n\n\\subsection{Euler parameters (231)}\nThe parameters\n\\begin{equation}\n\t\\eta = \\cos \\frac{\\theta}{2}, \\quad\n\t\\gv{\\epsilon} = \\V{k} \\sin \\frac{\\theta}{2}\n\\end{equation}\nlead to the rotation matrix\n\\begin{equation}\n\t\\R_e(\\eta, \\gv{\\epsilon}) = \\I\n\t+ 2 \\eta \\gv{\\epsilon}^\\times\n\t+ 2 \\gv{\\epsilon}^\\times \\gv{\\epsilon}^\\times\n\t.\n\\end{equation}\nThis is nice, because:\n\\begin{itemize}[nosep]\n\t\\item No singularities!\n\t\\item No trigonometry!\n\t\\item \\( \\eta^2 + \\vec{\\epsilon} \\cdot \\vec{\\epsilon} = 1 \\): Easy to normalise (avoid roundoff errors).\n\\end{itemize}\n\n\\subsection{Homogenous transformation matrices (223)}\nThe position and orientation of frame \\( b \\) relative to frame \\( a \\) is given by the homogenous transformation matrix\n\\begin{equation}\n\t\\M{T}^a_b =\n\t\\begin{pmatrix}\n\t\t\\R^a_b  & \\V{r}^a_{ab} \\\\\n\t\t\\V{0}\\T & 1\n\t\\end{pmatrix}\n\t\\in SE(3)\n\\end{equation}\nwhere \\( \\V{r}^a_{ab} \\) is the position of frame \\( b \\) relative to frame \\( a \\), expressed in the coordinates of frame \\( a \\). (Position as in position of the origin.)\nThe set \\(SE(3)\\) is defined as:\n\\begin{equation}\n\tSE(3) = \\left\\lbrace \\M{T} \\enspace |\n\t\\enspace \\M{T} = \\begin{pmatrix} \\R & \\V{r} \\\\ \\V{0}\\T & 1 \\end{pmatrix},\n\t\\enspace \\R \\in SO(3),\n\t\\enspace \\V{r} \\in \\mathbb{R}^3\n\t\\right\\rbrace\n\\end{equation}\n\n\\subsection{Angular velocity (239)}\nThis is super funky and magical: The vector \\( \\angvel^a_{ab} \\) defined by satisfying\n\\begin{equation}\n\t( \\angvel^a_{ab} )^\\times =\n\t\\M{\\dot{R}}^a_b ( \\R^a_b )\\T\n\\end{equation}\nturns out to represent the angular velocity of \\( b \\) relative to \\( a \\).\n\nThen, the kinematic differential equations for the rotation matrix is given in two forms\n\\begin{equation}\n\t\\begin{aligned}\n\t\t\\M{\\dot{R}}^a_b &= (\\angvel^a_{ab})^\\times \\R^a_b \\\\\n\t\t\\M{\\dot{R}}^a_b &= \\R^a_b (\\angvel^b_{ab})^\\times\n\t\\end{aligned}\n\\end{equation}\n\n\\paragraph{Example} (See \\eqref{eq:simplerot} for the definition of \\( \\R_x \\).)\n\\begin{equation}\n\t\\M{\\dot{R}}_x(\\phi) \\R_x\\T(\\phi) =\n\t\\begin{pmatrix}\n\t\t0 & 0       & 0       \\\\\n\t\t0 & -\\s\\phi & -\\c\\phi \\\\\n\t\t0 &  \\c\\phi & -\\s\\phi \\\\\n\t\\end{pmatrix}\n\t\\dot{\\phi}\n\t\\underbrace{\n\t\t\\begin{pmatrix}\n\t\t\t1 &  0      & 0      \\\\\n\t\t\t0 &  \\c\\phi & \\s\\phi \\\\\n\t\t\t0 & -\\s\\phi & \\c\\phi \\\\\n\t\t\\end{pmatrix}\n\t}_{\\R_x\\T(\\phi)}\n\t=\n\t\\begin{pmatrix}\n\t\t0 & 0          & 0           \\\\\n\t\t0 & 0          & -\\dot{\\phi} \\\\\n\t\t0 & \\dot{\\phi} & 0           \\\\\n\t\\end{pmatrix}\n\\end{equation}\nwhich gives \\( \\angvel_x = \\begin{pmatrix} \\dot{\\phi} & 0 & 0 \\end{pmatrix}\\T \\).\nSimilarly, \\( \\angvel_y = \\begin{pmatrix} 0 & \\dot{\\theta} & 0 \\end{pmatrix}\\T \\)\nand \\( \\angvel_z = \\left( 0 \\enskip 0 \\enskip \\dot{\\psi} \\right) \\T \\)\n\n\\subsubsection{Simple rotation}\nAngular velocity \\( \\vec{\\omega}_{ab} \\) about the axis of rotation \\( \\vec{k} \\) is:\n\\begin{equation}\n\t\\vec{\\omega}_{ab} = \\dot{\\theta} \\vec{k}\n\\end{equation}\n\n\\subsubsection{Composite rotation}\nAngular velocity of a composite rotation matrix \\( \\R^a_d = \\R^a_b \\R^b_c \\R^c_d \\)  is\n\\begin{equation}\n\t\\vec{\\omega}_{ad} = \\vec{\\omega}_{ab} + \\vec{\\omega}_{bc} + \\vec{\\omega}_{cd}\n\\end{equation}\nwhich on coordinate form is\n\\begin{equation}\n\t\\begin{aligned}\n\t\t\\angvel^a_{ad} &= \\angvel^a_{ab} +        \\angvel^a_{bc} +        \\angvel^a_{cd} \\\\\n\t\t               &= \\angvel^a_{ab} + \\R^a_b \\angvel^b_{bc} + \\R^a_b \\R^b_c \\angvel^c_{cd} \\\\\n\t\\end{aligned}\n\\end{equation}\n\n\\subsubsection{Differentiation of vectors}\n\\begin{gather}\n\t\\V{\\dot{u}}^a = \\R^a_b \\left[ \\V{\\dot{u}}^b + (\\angvel^b_{ab})^\\times \\V{u}^b \\right] \\\\\n\t\\frac{\\fourIdx{a}{}{}{}\\dif}{\\dif t} \\vec{u} = \\frac{\\fourIdx{b}{}{}{}\\dif}{\\dif t} \\vec{u} + \\vec{\\omega}_{ab} \\times \\vec{u}\n\\end{gather}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Kinematic differential equations (244)}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nRotational deviation cannot be described by subtraction. Instead, it is described by\n\\begin{equation}\n\t\\widetilde{\\R}_a := \\R \\R_d\\T \\implies \\R = \\widetilde{\\R}_a \\R_d\n\t, \\quad \\widetilde{\\R}_a \\in SO(3)\n\\end{equation}\nwhere \\( \\R = \\R^a_b \\) is the orientation and \\( \\R_d \\) is the desired orientation.\n\nThen the kinematic differential equations for the deviation are\n\\begin{gather}\n\t\\widetilde{\\angvel}^a = \\angvel^a - \\angvel^a_d \\\\\n\t\\dod{}{t} \\widetilde{\\R}_a = \\left( \\widetilde{\\angvel}^a \\right)^\\times \\widetilde{\\R}_a\n\\end{gather}\n\n\\subsection{Rigid body kinematics (259)}\n\\subsubsection{Configuration}\n\\begin{figure}[H]\n\t\\centering\n\t\\includegraphics{rigid_body}\n\\end{figure}\n\nThe orientation \\(\\R^i_b\\) of a rigid body and the position \\(\\vec{r}_o\\) of a point \\(o\\) in the body, both in relation to a reference frame \\(i\\), define its configuration. The position of any point \\(p\\) in the body is given by\n\\begin{equation}\n\t\\vec{r}_p = \\vec{r}_o + \\vec{r}.\n\\end{equation}\nIn the reference frame, \\(\\vec{r}\\) is\n\\begin{equation}\n\t\\V{r}^i = \\R^i_b \\V{r}^b\n\\end{equation}\n\n\\subsubsection{Velocity}\nDefinition:\n\\begin{equation}\n\t\\vec{v}_o := \\frac{\\presuper{i}\\dif}{\\dif t} \\vec{r}_o, \\quad \n\t\\vec{v}_p := \\frac{\\presuper{i}\\dif}{\\dif t} \\vec{r}_p\n\\end{equation}\nAlternatively:\n\\begin{equation}\n\t\\vec{v}_p = \\vec{v}_o + \\frac{\\presuper{b} \\dif}{\\dif t} \\vec{r} + \\vec{\\omega}_{ib} \\times \\vec{r}\n\\end{equation}\n\n\\subsubsection{Acceleration}\nDefinition (translation):\n\\begin{equation}\n\t\\vec{a}_o := \\frac{\\presuper{i}\\dif\\,^2}{\\dif t^2} \\vec{r}_o, \\quad \n\t\\vec{a}_p := \\frac{\\presuper{i}\\dif\\,^2}{\\dif t^2} \\vec{r}_p\n\\end{equation}\nDefinition (rotation):\n\\begin{equation}\n\t\\vec{\\alpha}_{ib} := \\frac{\\presuper{i}\\dif\\,^2}{\\dif t^2} \\vec{\\omega}_{ib}\n\t= \\frac{\\presuper{b}\\dif\\,^2}{\\dif t^2} \\vec{\\omega}_{ib}\n\\end{equation}\nIn terms of accelerion, ang. acceleration and velocities:\n\\begin{multline}\n\t\t\\underbrace{\\vec{a}_p}_{\\text{Acceleration of \\(p\\)}} =\n\t\t\\underbrace{\\vec{a}_o}_{\\text{Acceleration of \\(o\\)}} +\n\t\t\\underbrace{\\frac{\\presuper{b}\\dif\\,^2}{\\dif t^2} \\vec{r}}_{\\text{Second derivative of \\(\\vec{r}\\) in \\(b\\)}} \\\\ +\n\t\t\\underbrace{2 \\vec{\\omega}_{ib} \\times \\frac{\\presuper{b}\\dif}{\\dif t} \\vec{r} }_{\\text{Coriolis acceleration}} +\n\t\t\\underbrace{\\vec{\\alpha}_{ib} \\times \\vec{r}}_{\\text{Transversal acceleration}} +\n\t\t\\underbrace{\\vec{\\omega}_{ib} \\times \\left( \\vec{\\omega}_{ib} \\times \\vec{r} \\right)}_{\\text{Centripetal acceleration}}\n\\end{multline}\nAlternatively:\n\\begin{equation}\n\t\\vec{a}_p =\n\t\\frac{\\presuper{b}\\dif}{\\dif t} \\vec{v}_o +\n\t\\vec{\\omega}_{ib} \\times \\vec{v}_o +\n\t\\frac{\\presuper{b}\\dif\\,^2}{\\dif t^2} \\vec{r} +\n\t2 \\vec{\\omega}_{ib} \\times \\frac{\\presuper{b}\\dif}{\\dif t} \\vec{r} +\n\t\\vec{\\alpha}_{ib} \\times \\vec{r} +\n\t\\vec{\\omega}_{ib} \\times \\left( \\vec{\\omega}_{ib} \\times \\vec{r} \\right)\n\\end{equation}\nAs well as:\n\\begin{equation}\n\t\\vec{v}_p = \\vec{v}_o + \\vec{\\omega}_{ib} \\times \\vec{r},\n\t\\quad \\vec{r} \\text{ fixed in } b\n\\end{equation}\n\n\\subsection{EoM for rigid body (269)}\n\\begin{equation}\n\t\\begin{aligned}\n\t\t\\vec{F}_{bc} &= m \\vec{a}_c \\\\\n\t\t\\vec{T}_{bc} &= \\vec{M}_{b/c} \\cdot \\vec{\\alpha}_{ib}\n\t\t+ \\vec{\\omega}_{ib} \\times ( \\vec{M}_{b/c} \\cdot \\vec{\\omega}_{ib}) \\\\\n\t\\end{aligned}\n\\end{equation}\nwhere\n\\begin{itemize}\n\t\\item \\( \\vec{F}_{bc} \\) is the force on body \\( b \\) acting through the centre of mass.\n\t\\item \\( \\vec{T}_{bc} \\) is the torque, or moment about the centre of mass.\n\t\\item \\( \\vec{M}_{b/c} \\) is the inertia dyadic of \\( b \\) about \\( c \\).\n\\end{itemize}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Lagrangian dynamics (313)}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Lagrange versus Newton-Euler (313)}\n\n\\begin{center}\n\t\\begin{tabular}{rl}\n\t\t\\b{Newton-Euler} & \\b{Lagrange} \\\\\n\t\t\\hline\n\t\tVectors & Algebra \\\\\n\t\tForces and moments & Energy and work \\\\\n\t\tMust consider all forces & Forces of constraint eliminated \\\\\n\t\tSomewhat complicated & Easier to do by hand \\\\\n\t\tSuitable for computers & Less suitable for computers \\\\\n\t\\end{tabular}\n\\end{center}\n\nNewton-Euler is based on Newton's (second) law and it's exention to rotational dynamics. Lagrangian equations of motion are instead based on algebraic operations on energy expressions, and are better suited for things related to energy conservation and passivity.\n\nLagrangean methods make sense when there are guiding forces involved.\n\n\\subsection{Lagrange EoM (315)}\nThe Lagrangian is\n\\begin{equation}\n\t\\lagr(\\V{q}, \\V{\\dot{q}}, t) = T(\\V{q}, \\V{\\dot{q}}, t) - U(\\V{q})\n\\end{equation}\nand the EoMs are\n\\begin{equation}\n\t\\od{}{t} \\left( \\dpd{\\lagr}{\\dot{q}_i} \\right) - \\pd{\\lagr}{q_i} = \\tau_i\n\\end{equation}\nwhere \\(\\tau_i\\) is the generalised actuator force.\n\n\\section{Reynolds' transport theorem (413)}\nTime-variant volume:\n\\begin{equation}\n\t\\od{}{t} \\iiint_{V_c(t)} \\phi(\\V{x}, t) \\dif V\n\t= \\iiint_{V_c(t)} \\pd{\\phi(\\V{x}, t)}{t} \\dif V\n\t+ \\iint_{\\partial V_c(t)} \\phi \\vec{v}_c \\cdot \\vec{n} \\dif A\n\\end{equation}\nMaterial volume:\n\\begin{equation}\n\t\\od{}{t} \\iiint_{V_m(t)} \\phi(\\V{x}, t) \\dif V\n\t= \\iiint_{V_m(t)} \\pd{\\phi(\\V{x}, t)}{t} \\dif V\n\t+ \\iint_{\\partial V_m(t)} \\phi \\vec{v} \\cdot \\vec{n} \\dif A\n\\end{equation}\nMaterial derivative:\n\\begin{equation}\n\t\\frac{\\Dif}{\\Dif t} \\iiint_{V_c(t)} \\phi(\\V{x}, t) \\dif V\n\t:= \\iiint_{V_c(t)} \\pd{\\phi(\\V{x}, t)}{t} \\dif V\n\t+ \\iint_{\\partial V_c(t)} \\phi \\vec{v} \\cdot \\vec{n} \\dif A\n\\end{equation}\nDifferential formulation, material form:\n\\begin{equation}\n\t\\frac{\\Dif}{\\Dif t} \\iiint_{V_c(t)} \\phi(\\V{x}, t) \\dif V\n\t= \\iiint_{V_c(t)} \\frac{\\Dif \\phi(\\V{x}, t)}{\\Dif t}\n\t+ \\phi(\\V{x}, t) \\left( \\vec{\\nabla} \\cdot \\vec{v} \\right) \\dif V\n\\end{equation}\nDifferential formulation, divergence form:\n\\begin{equation}\n\t\\frac{\\Dif}{\\Dif t} \\iiint_{V_c(t)} \\phi(\\V{x}, t) \\dif V\n\t= \\iiint_{V_c(t)} \\pd{\\phi(\\V{x}, t)}{t}\n\t+ \\vec{\\nabla} \\cdot \\left( \\phi(\\V{x}, t) \\vec{v} \\right) \\dif V\n\\end{equation}\nIntegral formulation:\n\\begin{equation}\n\t\\od{}{t} \\iiint_{V_f} \\phi(\\V{x}, t) \\dif V\n\t= \\frac{\\Dif}{\\Dif t} \\iiint_{V_f} \\phi(\\V{x}, t) \\dif V\n\t- \\iint_{\\partial V_f} \\phi \\vec{v} \\cdot \\vec{n} \\dif A\n\\end{equation}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Mass balance (417)}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nIntegral formulation:\n\\begin{equation}\n\t\\od{}{t} \\iiint_{V_f} \\rho(\\V{x}, t) \\dif V\n\t= - \\iint_{\\partial V_f} \\rho \\vec{v} \\cdot \\vec{n} \\dif A\n\\end{equation}\nDifferential formulation:\n\\begin{equation}\n\t\\pd{\\rho(\\V{x}, t)}{t}\n\t+ \\vec{\\nabla} \\cdot ( \\rho(\\V{x}, t) \\vec{v})\t\n\t= 0\n\\end{equation}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Some mechanics (141)}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\paragraph{Valve equation (141)}\n\\begin{equation}\n\tq = C_d A \\sqrt{\\frac{2}{\\rho} \\Delta p}\n\\end{equation}\n\n\\paragraph{Bulk modulus (151)}\n\\begin{equation}\n\t\\frac{\\dif \\rho}{\\rho} = \\frac{\\dif p}{\\beta}\n\\end{equation}\n\n\\paragraph{Spring}\n\\begin{gather}\n\tF = - k x \\\\\n\tE_{pot} = \\frac{1}{2} k x^2\n\\end{gather}\n\n\\end{document}", "meta": {"hexsha": "14fba672804355f3dae88a60dbc0095e08379c10", "size": 30884, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "TTK4130 Modelling and simulation/TTK4130-Summary.tex", "max_stars_repo_name": "jakoblover/ntnu-course-summaries", "max_stars_repo_head_hexsha": "8ba859de2349b93c5079ca10a4cf2ec49c1f5dc0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-05-30T09:19:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-11T02:42:40.000Z", "max_issues_repo_path": "TTK4130 Modelling and simulation/TTK4130-Summary.tex", "max_issues_repo_name": "jakoblover/ntnu-course-summaries", "max_issues_repo_head_hexsha": "8ba859de2349b93c5079ca10a4cf2ec49c1f5dc0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TTK4130 Modelling and simulation/TTK4130-Summary.tex", "max_forks_repo_name": "jakoblover/ntnu-course-summaries", "max_forks_repo_head_hexsha": "8ba859de2349b93c5079ca10a4cf2ec49c1f5dc0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7555012225, "max_line_length": 301, "alphanum_fraction": 0.5756054915, "num_tokens": 11361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.30096313101869365}}
{"text": "\n\\documentclass[10pt,mathserif]{beamer}\n\n\\usepackage{beamerthemesplit}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{amsthm,listings,cite}\n\\usepackage{graphicx}\n%\\usepackage[latin1]{inputenc}\n\n\n\n\\useoutertheme{infolines}\n\n\\title{SMT Solver Theory and Applications}\n\n\\author{Dionna Glaze}\n\n\\date{November 18, 2009}\n\n\\definecolor{blue}{rgb}{0,0,1.0}\n\\newcommand{\\blue}[1]{{\\color{blue}#1}}\n\\definecolor{green}{rgb}{0,1.0,0}\n\\newcommand{\\green}[1]{{\\color{green}#1}}\n\\definecolor{red}{rgb}{1.0,0,0}\n\\newcommand{\\red}[1]{{\\color{red}#1}}\n\\definecolor{grey}{rgb}{0.6,0.6,0.6}\n\\newcommand{\\grey}[1]{{\\color{grey}#1}}\n\n\\AtBeginSection[]\n{\n  \\begin{frame}<beamer>\n    \\frametitle{Outline}\n    \\tableofcontents[currentsection]\n  \\end{frame}\n}\n\n\n\\begin{document}\n\n\n\\frame{\\titlepage}\n\n\\frame{\n\\frametitle{Outline}\n\\tableofcontents\n}\n\n\\section{Vocabulary and Preliminaries}\n\n\\frame{\n\\frametitle{What is the SMT problem?}\nSMT stands for Satisfiability Modulo Theories, and is essentially a generalization of the SAT problem. \\\\\nWe say ``modulo theories'' because the Boolean predicates of SAT are now first order sentences in a logic.\n\\begin{itemize}\n\\item At least NP-complete and at most unbounded complexity problem with applications in AI, formal methods\n\\item Input usually given in SMT-LIB format (CNF with sugar)\n\\end{itemize}\n}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame{\n\\frametitle{Definitions}\n\\begin{itemize}\n \\item A theory $T$ is a set of first order sentences.\n \\item A formula $F$ is \\emph{$T$-satisfiable} or \\emph{$T$-consistent} if $F\\wedge T$ is satisfiable in the first order sense. Otherwise $F$ is \\emph{$T$-inconsistent}.\n \\item A partial assignment $M$ is a $T$-model of a formula $F$ if $M$ is a $T$-consistent partial assignment and $M\\models F$ (in the propositional sense).\n \\item For two formulas $F$ and $G$, we say $F \\models_T G$ if $F \\wedge \\neg G$ is $T$-inconsistent.\n \\item A \\emph{theory lemma} is a clause $C$ such that $\\emptyset \\models_T C$.\n \\item A \\emph{$T$-solver} is a decision$^*$ procedure that decides the $T$-satisfiability of conjunctions of ground literals.\n\\end{itemize}\n}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame{\n\\frametitle{A Short Look at DPLL}\nBased on the idea of unit propagation:\\\\\n$M\\parallel F, C\\vee l \\Rightarrow M l \\parallel F,C\\vee l \\mbox{ if }\\left\\{\\begin{array}{l}M\\models \\neg C \\\\ l \\mbox{ is undefined in } M\\end{array}\\right.$ \\\\\nconflict-driven backjumping: \\\\\n$M l^d N \\parallel F,C \\Rightarrow M l' \\parallel F,C \\mbox{ if }\\left\\{\\begin{array}{l}\nM l^d N \\models \\neg C \\mbox{ and there is}\\\\\n\\mbox{some clause } C'\\vee l'\\mbox { such that:} \\\\\n\\quad F,C\\models C'\\vee l' \\mbox{ and } M\\models \\neg C', \\\\\n\\quad l' \\mbox{ is undefined in } M, \\mbox{ and } \\\\\n\\quad l' \\mbox{ or } \\neg l' \\mbox{occurs in } F \\mbox{ or in } M l^d N                                                                         \n\\end{array}\\right.$ \\\\\nand conflict-driven learning: \\\\\n$M \\parallel F \\Rightarrow M \\parallel F, C \\mbox{ if }\\left\\{\\begin{array}{l}\\mbox{each atom of } C\\mbox{ occurs in }F \\mbox{ or in } M \\\\ F\\models C\\end{array}\\right.$\n}\n\n\\section{Previous Strategies}\n\n\\subsection{Eager Approaches}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame{\n\\frametitle{Propositional Translation}\nSatisfiability-preserving translation to a propositional CNF formula. \\\\\n\\pause\nPros:\n\\begin{itemize}\n \\item Easy to do translations.\n \\item Leverages the existant SAT-solving technology.\n\\end{itemize}\n\\pause\nCons:\n\\begin{itemize}\n \\item Not all theories can be translated this way.\n \\item Translation causes unacceptable blow-up in problem size.\n \\item Search starts only after entire problem is translated.\n \\item Size of the problem usually consumes all resources before starting the search.\n\\end{itemize}\n}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame{\n\\frametitle{Calling External SAT Solver}\nThe $T$-solver calls a SAT solver on the formula to get a (propositionally) satisfying assignment and checks its $T$-consistency. If inconsistent, the conflicting clause is added to the formula and sent back to the SAT solver. \\\\\n\\pause\nPros:\n\\begin{itemize}\n \\item Only have to write the $T$-solver.\n \\item Again leverages the existant SAT-solving technology.\n\\end{itemize}\n\\pause\nCons:\n\\begin{itemize}\n \\item Search must complete entirely before $T$-inconsistency is reported.\n \\item Search must start over at the beginning if last assignment failed.\n\\end{itemize}\n\n}\n\n\\subsection{Lazy Approaches}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame{\n\\frametitle{Incremental $T$-solving}\nCommunicates with the DPLL module to inform of $T$-inconsistency before an entire model is constructed, either at every decision or on every $k$ decisions. \\\\\n\\pause\nPros:\n\\begin{itemize}\n \\item Early pruning of search space.\n\\end{itemize}\n\\pause\nCons:\n\\begin{itemize}\n \\item Not always effective. The $T$-solver should be faster in processing one additional input literal than in reprocessing from scratch, but for some theories this is impossible.\n \\item Finding the ``sweet spot'', or the right $k$ for the best performance is guess work.\n\\end{itemize}\n}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame{\n\\frametitle{On-line SAT solving}\nBuilds off the incremental approach by allowing the $T$-solver to generate conflicting clauses to aid with backjumping. \\\\\n\\pause\nPros:\n\\begin{itemize}\n \\item Early pruning\n \\item More aggressive pruning.\n\\end{itemize}\n\\pause\nCons:\n\\begin{itemize}\n \\item Conflicting clauses hard to generate.\n\\end{itemize}\n}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame{\n\\frametitle{Theory Propagation}\nGuides the search process by taking the current partial assignment and deriving other subterms of the formula. $T$-solver is no longer a \\textit{validator} for the DPLL search. \\\\\n\\pause\nPros:\n\\begin{itemize}\n \\item Analagous to the importance of unit propagation in DPLL.\n \\item For many theories, this process exhaustively executed gives a great increase of performance. \n \\item Exhaustively executed, this eliminates the need for unit propagation on theory lemmas.\n\\end{itemize}\n\\pause\nCons:\n\\begin{itemize}\n \\item Conflict analysis highly non-trivial.\n \\item If not performed exhaustively, duplicate results are extraneously generated.\n\\end{itemize}\n\n}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{The DPLL(T) Framework}\n\\frame{\n\\frametitle{Transactions between DPLL and T-Solver}\nSufficient communication for an incremental on-line solver with theory propagation is given in the following set of messages:\n\\begin{itemize}\n \\item Notify $T$-Solver that a certain literal has been set to true.\n\\pause\n \\item Ask $T$-Solver to check the current partial assignment is $T$-inconsistent (with \\textit{strength}) and give an \\textit{explanation}.\n\\pause\n \\item Ask $T$-Solver to identify currently undefined input literals that are $T$-consequences of $M$.\n\\pause\n \\item Ask $T$-Solver to provide a justification for a $T$-entailment of a theory-propagated literal for conflict clause learning.\n\\pause\n \\item Ask $T$-Solver to undo the last $n$ notifications that a literal has been set to true.\n\\end{itemize}\n}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Useful Theories}\n\\frame{\n\\frametitle{Equality of Uninterpreted Functions (EUF)}\nFinds basic unsatisfiable errors such as\n\\begin{equation*}\n(f(f(a))\\neq b \\vee f(f(f(b)))\\neq b) \\wedge f(a) =a \\wedge a = b\n\\end{equation*}\nby using a congruence closure algorithm to create congruence classes and checking the results against a list of suspected equalities and disequalities, inconsistencies are found.\n}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame{\n\\frametitle{Difference Logic}\n(Still NP-Complete) subset of integer linear arithmetic problems where all constraints are of the form\n\\begin{equation*}\n x-y \\le c\n\\end{equation*}\nQuestions in bounded model checking of timed automata along with questions of circuit timing analysis can be answered with this logic.\\\\\n(Na\\\"ively solvable using an iterative Bellman-Ford method, but better negative-weight cycle detection algorithms are known.)\n}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame{\n\\frametitle{Bit-Vectors}\nNP-Complete theory that allows fixed-width bit vectors to have the following operators executed on them:\n\\begin{itemize}\n \\item Assignment $=$\n \\item Named selection $[i:j]$\n \\item Concatenation $::$\n \\item Arithmetic $\\{+,-,*,<\\}$ where $*$ is multiplication by a scalar\n \\item Bitwise operators $\\{{\\bf AND}, {\\bf OR}, {\\bf NOT}\\}$\n\\end{itemize}\n}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\frame{\n\\frametitle{Interpreted Sets and Bounded Quantification}\nAn expressive NP-Complete theory of heap-manipulating loop-free and procedure-free programs. Strategy for proving a program $T$ correct: compute $wp(T, true)$ and decide satisfiability of $\\neg wp(T,true)$, giving $\\neg wp(T,true)$ is unsatisfiable if and only if $T$ does not go wrong. \\\\\n\\begin{figure}\n{\\scriptsize\n\\begin{align*}\nT \\in Stmt ::= & Assert(\\varphi) \\,\\mid\\, Assume(\\varphi) \\,\\mid\\, \\\\\n\t       & x := new \\,\\mid\\, free(x) \\,\\mid\\, x := t \\,\\mid\\, \\\\\n               & f(x) := y \\,\\mid\\, T_1;T_2 \\,\\mid\\, T_1\\square T_2\n\\end{align*}\n\\begin{align*}\n\\begin{array}{lll}\nc &\\in Integer \\\\\nx &\\in Variable \\\\\nf &\\in Function \\\\\n\\varphi &\\in Formula &::= \\alpha \\,\\mid\\, \\varphi_1 \\wedge \\varphi_2 \\,\\mid\\, \\varphi_1 \\vee \\varphi_2 \\,\\mid\\, \\neg \\varphi \\\\\n\\alpha &\\in \\forall Formula &::= \\gamma \\,\\mid\\, \\alpha_1 \\wedge \\alpha_2 \\,\\mid\\, \\alpha_1 \\wedge \\alpha_2 \\,\\mid\\, \\forall x \\in S.\\alpha \\\\\n\\gamma &\\in GFormula &::= t_1 = t_2 \\,\\mid\\, t_1 < t_2 \\,\\mid\\, t_1\\xrightarrow{f} t_2\\xrightarrow{f} t_3 \\,\\mid\\, \\neg \\gamma \\\\\nt &\\in Term &::= c \\,\\mid\\, x \\,\\mid\\, t_1 - t_2 \\,\\mid\\, t_1 + t_2 \\,\\mid\\, f(t) \\,\\mid\\, ite(t = t', t_1,t_2) \\\\\nS &\\in Set &::= g^{-1}(t) \\,\\mid\\, Btwn(f,t_1,t_2)\n\\end{array}\n\\end{align*}\n}\n\\caption{Program statement syntax (top) and formula syntax (bottom)}\n\\label{fig:congruence_classes}\n\\end{figure}\n}\n\n\\section{Combining Theories}\n\\frame{\n\\frametitle{Nelson-Oppen Method}\nA solver for the union of theories $T_1$ and $T_2$ can be constructed using the Nelson-Oppen procedure if\n\\begin{itemize}\n \\item The two have disjoint signatures ($\\Sigma_1 \\cap \\Sigma_2 = \\{=\\}$)\n \\item Both are \\textit{stably infinite} (i.e., every satisfiable quantifier-free formula is satisfiable in an infinite model)\n\\end{itemize}\n\\pause\nThe procedure is based on the process of \\textit{purification}. \\\\\n\\pause\nFor $\\Gamma$ a set of literals of $\\Sigma_1\\cup \\Sigma_2$,  the purified form of $\\Gamma$ is $\\Gamma_1\\wedge\\Gamma_2$ such that \\\\\n\\begin{equation*}\n\\Gamma_i \\subseteq (\\Sigma_i \\cup \\alpha) \\text{ for } \\alpha = \\{{\\cal V}(\\Gamma_1)\\cap{\\cal V}(\\Gamma_2)\\}\n\\end{equation*}\n${\\cal V}(\\Gamma_i)$ is the set of variables in $\\Gamma_i$.\n}\n\n\\frame{\n\\frametitle{Nelson-Oppen Algorithm}\nRecall: $\\alpha = \\{{\\cal V}(\\Gamma_1)\\cap{\\cal V}(\\Gamma_2)\\}$ \\\\\nA partition $\\phi$ (conjuction of many equalities and disequalities) of $\\alpha$ is guessed and the individual solvers return if $\\Gamma_i\\wedge\\phi$ is satisfiable. \\\\\n\\pause\nTheoretically-based optimization: \\\\\nA theory is \\emph{convex} iff for for all finite sets $\\Gamma$ of literals and for all non-empty disjunctions $\\bigvee_{i\\in I}{u_i \\simeq v_i}$ of variables, \n\\begin{equation*}\n\\Gamma \\models_T \\bigvee_{i\\in I}{u_i\\simeq v_i} \\text{ iff } \\Gamma \\models_T u_i \\simeq v_i \\text{ for some } i\\in I\n\\end{equation*} \\\\\nIf the two theories are convex, then this guessing can be changed into deducing the correct partition by propagating equalities.\\\\\nLet $\\Gamma_2$ know if $T_1\\cup \\Gamma_1 \\models x \\simeq y$ and vice versa.\n}\n\n\\section{Reading}\n\n\\frame{\n\\frametitle{References}\n\\begin{itemize}\n\\item R. Nieuwenhuis and A. Oliveras: Solving SAT and SAT Modulo Theories: from an Abstract Davis-Putnam-Logemann-Loveland Procedure to DPLL(T)\n\\item R. Bruttomesso et al: A Lazy and Layered SMT(BV) Solver for Hard Industrial Verification Problems\n\\item S. Lahiri and S. Qadeer: Back to the Future: Revisiting Precise Program Verification using SMT Solvers\n\\item L. de Moura et al: A Tutorial on Satisfiability Modulo Theories\n\\end{itemize}\n}\n\n\\end{document}\n\n", "meta": {"hexsha": "b2ebb608bc0335eda1fa0d4bd5a1f4052feba01c", "size": 12286, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "smt-pl/smt_talk_pl.tex", "max_stars_repo_name": "deeglaze/deeglaze-talks", "max_stars_repo_head_hexsha": "f7502b2ea9e24a9bb619cf9e379f26f5e6ed6435", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-03-17T07:04:18.000Z", "max_stars_repo_stars_event_max_datetime": "2016-03-17T07:04:18.000Z", "max_issues_repo_path": "smt-pl/smt_talk_pl.tex", "max_issues_repo_name": "deeglaze/deeglaze-talks", "max_issues_repo_head_hexsha": "f7502b2ea9e24a9bb619cf9e379f26f5e6ed6435", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "smt-pl/smt_talk_pl.tex", "max_forks_repo_name": "deeglaze/deeglaze-talks", "max_forks_repo_head_hexsha": "f7502b2ea9e24a9bb619cf9e379f26f5e6ed6435", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1503267974, "max_line_length": 289, "alphanum_fraction": 0.6851701123, "num_tokens": 3569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.30096313101869365}}
{"text": "﻿\\documentclass[11pt]{article}\n\\usepackage{cite}\n\\usepackage{a4}\n\n\\usepackage[utf8]{inputenc}\n\\usepackage[english]{babel}\n\\usepackage{amsmath,amssymb,amsthm}\n\n\\usepackage{url}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% layout commands\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\newtheorem{thm}{Theorem}\n\\newcommand{\\prog}[3]{\\langle #1, #2, #3\\rangle}\n\\newcommand{\\slp}[1]{\\mathbb{#1}}\n\n\\newcommand{\\probleminput}[1]{\\noindent \\textsc{Input:} #1}\n\\newcommand{\\problemoutput}[1]{\\noindent \\textsc{Output:} #1}\n\\newcommand{\\problem}[3]{\n            \\noindent {\\sc Problem:} \\textbf{#1} \\newline\n            \\noindent {\\sc Input:} #2 \\newline\n            \\noindent {\\sc Output:} #3\n}\n\n\\begin{document}\n\\title{Computing All Squares in Compressed Texts}\n\\author{Lesha Khvorost\\thanks{The author acknowledges support from the Russian Foundation for Basic Research, grant\n10-01-00793.}\\\\\nUral Federal University\\\\\njaamal@mail.ru}\n\\date{}\n\\maketitle\n\n\\begin{abstract}\nWe consider the problem of computing all squares in a string represented by a straight-line program (SLP). An\ninstance of the problem is an SLP $\\slp{S}$ that derives some string $S$ and we seek a solution in the form of a table\nthat contains information about all squares in $S$ in a compressed form. We present an algorithm that solves the\nproblem in $O(|\\slp{S}|^4\\cdot \\log^2{|S|})$ time and requires $O(|\\slp{S}|\\cdot \\max\\{ |\\slp{S}|, \\log{|S|}\\})$ space,\nwhere $|\\slp{S}|$ (respectively $|S|$) is the size of the SLP $\\slp{S}$ (respectively the length of the string $S$).\n\\end{abstract} \n\n\\section{Introduction}\n\nVarious compressed representations of strings are known: straight-line programs (SLPs), collage-systems, string\nrepresentations using antidictionaries, etc. Nowadays text compression based on context-free grammars such as\nSLPs attracts much attention. The reason for this is not only that grammars provide well-structured compression but\nalso that the SLP-based compression is in a sense polynomially equivalent to the compression achieved by the Lempel-Ziv\nalgorithm that is widely used in practice. It means that, given a string $S$, there is a polynomial relation between\nthe size of an SLP that derives $S$ and the size of the dictionary stored by the Lempel-Ziv algorithm \\cite{18}.\n\nWhile compressed representations save storage space, there is a price to pay: some classical problems on strings\nbecome computationally hard when one deals with compressed data and measures algorithms' speed in terms of the\nsize of compressed representations. As examples we mention here the problems \\textbf{Hamming distance} \\cite{15} and\n\\textbf{Literal shuffle} \\cite{4}. On the other hand, there exist problems that admit algorithms working rather well on\ncompressed representations: \\textbf{Pattern matching} \\cite{15}, \\textbf{Longest common substring} \\cite{16}, \n\\textbf{Computing all palindromes} \\cite{16}. This dichotomy gives rise to the following research direction: to\nclassify important string problems by their behavior with respect to compressed data.\n\nThe \\textbf{Computing All Squares} (\\textbf{CAS}) problem is a well-known problem on strings. It is of importance, for\nexample, in molecular biology. Up to recently it is was not known whether or not \\textbf{CAS} admits an algorithm\npolynomial in the size of a compressed representation of a given string.\\footnote{A polynomial algorithm that solves\n\\textbf{CAS} for strings represented by Lempel-Ziv encodings was announced in~\\cite{8}. This representation is slightly\nmore general than that by SLPs. However no details of the algorithm have ever been published.} In general, a string can\nhave exponentially many squares with respect to the size of its compressed representation. For example, the string\n$a^n$ has $\\Theta(n^2)$ squares, while it is easy to build an SLP of size $O(\\log n)$ that derives $a^n$. So we must\nstore information about squares in a compressed form. Also this implies that we cannot search for squares consecutively\nby moving from one square to the ``next'' one. Squares should be somehow grouped in relatively large families that are\nto be discovered at once.\n\nWe formulate the \\textbf{CAS} problem in terms of SLPs as follows:\n\n\\problem{CAS}{an SLP $\\slp{S}$ that derives some text $S$;}{a data structure (a S-table) that contains\ninformation about all squares in $S$ in a compressed form.}\n\n\\begin{thm}\nThere is an algorithm that solves the \\textbf{CAS} problem using $O(|\\slp{S}|^4 \\cdot \\log^2{|S|})$ time and\n$O(|\\slp{S}| \\cdot \\max(|\\slp{S}|, \\log{|S|}))$ space.\n\\end{thm}\n\nWe would like to emphasize main features of the algorithm:\n\n\\begin{itemize}\n\\item This algorithm is divided into independent steps in contrast to classical algorithms in this area which\nconsecutively accumulate information about required objects. As a result it can be parallelized.\n\n\\item This algorithm presents a new technique for SLPs processing..\n\n\\item The algorithm is quite difficult for practical implementation. It is not excluded that constants hidden in the\n\"O\" notation are actually very big.\n\n\\item The present upper bound for the time complexity is rather high and is not matched by any lower bound. The question\nwhether the upper bound can be lowered to say, cubic in $|\\mathbb{S}|$ remains open.\n\\end{itemize}\n\n{\\small \n\t\\bibliography{cas_problem}{}\n\t\\bibliographystyle{plain}\n}\n\\end{document}", "meta": {"hexsha": "cdb0cad1b15911200bf3a25bf6011e6ad67d0867", "size": 5378, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "texfiles/Khvorost/cas_problem_ext_abstract/cas_problem_ext_abstract.tex", "max_stars_repo_name": "jaamal/overclocking", "max_stars_repo_head_hexsha": "b40db5a72710c691ca558e22626c5c382fd3677a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "texfiles/Khvorost/cas_problem_ext_abstract/cas_problem_ext_abstract.tex", "max_issues_repo_name": "jaamal/overclocking", "max_issues_repo_head_hexsha": "b40db5a72710c691ca558e22626c5c382fd3677a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-04-11T12:58:50.000Z", "max_issues_repo_issues_event_max_datetime": "2015-04-12T10:54:35.000Z", "max_forks_repo_path": "texfiles/Khvorost/cas_problem_ext_abstract/cas_problem_ext_abstract.tex", "max_forks_repo_name": "jaamal/overclocking", "max_forks_repo_head_hexsha": "b40db5a72710c691ca558e22626c5c382fd3677a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.78, "max_line_length": 120, "alphanum_fraction": 0.748977315, "num_tokens": 1389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.300963123711621}}
{"text": "\n\\subsection{The Problem}\n\nConsider passing a cell from its enclosing row, to its enclosing table, then down to its column. If there is only one cell sent along the path, we can statically allocate one attribute to hold the reference, e.g., \\code{Table.cell}, or, under our encoding, set of attributes, e.g., \\code{Table.cell_w}, \\code{Table.cell_h}, etc. However, a column should receive a statically unbounded number of cells: we cannot statically name the necessary intermediate attributes for passing all of these through any intermediate node along the path.\n\nThe traditional solution is to support \\emph{collections} that can contain multiple references; our challenge is in scheduling them. For simplicity, we restrict  collections to \\emph{only} contain references.\n\n\n\\subsection{Collection primitives}\n\nA collection should be creatable and queryable. Consider defining column $n$ of a table to have the maximal width of its corresponding cells. The column should contain a collection of (references to) its cells: from each row, it should extract cell $n$. We solve this in two steps: calculating the set of cells for each column and then query these sets for their maximum.\n\nOur example introduces several special forms:\n\n\\begin{itemize}\n\\item \\textbf{Type [ref $\\tau$]}: a homogenous collection of non-local nodes\n\\item \\textbf{reduce a in b where c : d}: is a nestable inorder reduction expresion over nodes in \\code{b}, introducing identifier \\code{a} to access an item. Note that the collection is either an input set of a local production such as \\code{Row*} or a computed collection such as \\code{cells}. Variable \\code{c} of type \\code{d} is local to the loop and may be accumulated over it. Finally, reductions are inorder \\emph{locally}; i.e., during a top down traversal, the operation on each node may be to compute the entire local reduction and, after completion, return control to continue the top-down traversal.\n\\item \\textbf{effects}: for reductions over a local production, attributes of child nodes may be (singly) assigned. \n\\item \\textbf{ id' := init .. f(id) ..}: accumulation or temporary variables are defined in the form of initial value \\code{init}, and, for the next element, as a function of the current one (or other current accumulator variables). Other expressions in the loop referencing \\code{id} observe the intermediate value, not the final accumulation. This is true even when a loop is split over multiple traversals (e.g., a loop counter reused for calculating different attributes).\n\\item \\textbf{ return' := init .. return .. }: reductions are expressions and thus have a value, denoted by special accumulator variable \\code{return}. \n\\item \\textbf{ [ a $|$ b ], [ a $@$ b ] }: an item may be inserted at the head of a collection or two collections appended. E.g., to place \\code{a} at the end of collection \\code{b}, use expression \\code{[b @ [a]]}.\n\\end{itemize}\n\n\nThis example is useful in several ways. First, we show it is useful for a loop to introduce a new variable binding (though, we note, only one such binding needs to be active in a runtime at any point in time). Second, nesting loop iterations is also useful. Finally, we can restrict our attention to collections of homogenous nodes (our technique can likely be extended for collections of different types of nodes, but, for simplicity and lack of motivation, we do not).\n\n\\subsection{Transformation Overview}\nOur transformation proceeds in several steps:\n\\begin{enumerate}\n\\item \\textbf{Collection rewriting.} The input is a grammar with collection creation, reductions, and references. The output is a grammar without collections. Instead, it uses special loop functions that are opaque to the scheduler. We also generate an auxilarlly data structure to provide the code generator so that it can reconstitute a scheduled sequence of statements into the appropriate loop nests.\n\nOur basic insight is that we can schedule homogenous collections as single nodes by hoisting the bodies of reductions to be top-level statements. Dependencies within an iteration are handled as usual, with the additional benefit of automatically \\emph{fissioning} loop bodies across multiple tree traversals. Loop-carried dependencies are handled by using an inorder traversal over a collection. The only subtlety is in handling temporary intermediate values in cases of loop fission.\n\\item \\textbf{Reference type and usage analysis}. Rewriting collections and loops reduces the output to a RAG, complete with nested references. As with our original first-class reference encoding, we perform a basic type analysis, from which, for every node type, we statically determine the extent of references. As before, we (temporarily) reject grammars with cycles in the static reference graph. %Later, after showing how to encode grammars over input graphs, we use a similar technique for lifting the cycle restriction here.\n\\item \\textbf{Reference rewriting.} Using the type and reference analysis, we rewrite reference passing and dereferencing into attribute passing and accessing, again using phantom variables and new operators (masked as functions) to separatley guide downstream scheduling and code generation. The output is a traditional attribute grammar, albeit with phantom annotations and special loop and reference functions opaque to \n\\item \\textbf{AG scheduling.} We reuse our basic AG scheduler.\n\\item \\textbf{Code generation.} Our code generator examines the computed schedule and precomputed auxillary information to generate code. Special functions for looping and collections have custom handling rather than normal function dispatch.\n\\end{enumerate}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\subsection{Collection Rewriting}\n\nWe must rewrite AG extensions for creating collections and operating over them. Our rewrite into traditional AGs is to reduce operations over collections into operations over a single node, which informs our various transformations. We consider each special form in turn:\n\n\\begin{itemize}\n\\item \\textbf{Kleene star productions. } We erase Kleene star repetitions so productions are over single non-terminals:\n$$Table \\rightarrow Row^{*} ~ Column^{*} \\Rightarrow Table \\rightarrow Row~Column$$\n\\item \\textbf{Kleene star references.} References over repeated reductions also lose their repetition. E.g.: $@Cell* \\Rightarrow @Cell$\n\\item \\textbf{Reduction expressions.} We recursively hoist reduction body statements to be top-level statements and introduce attributes to support the various loop variables. E.g., \n\n\\begin{lstlisting}[mathescape]\nreduce c in Column where i : int { $\\ldots$ c.n := i $\\ldots$ }\n\\end{lstlisting}\n\nbecomes \n\n\\begin{lstlisting}[mathescape]\nc := loopVar(@Column);\n$\\ldots$ c.n := loopBody(c, $f_b$, i) $\\ldots$\n\\end{lstlisting}\n\nwhere $f_b$ is a pure function over $i$ lifted from the original expression. The transformation also adds fresh fields $c$ and $i$ to the enclosing node type. \n\nWe syntactically encode the nesting structure by associating each body statement ($loopBody$) with its enclosing loop ($loopVar$) through the first par. Code generation  reconstitutes loop nests using this encoding. \n\\item \\textbf{Local vs. non-local reductions. } We distinguish between local vs. non-local reductions. For example, local collections support assignment to their attributes, as in the case of looping over a row to label each cell by increasing column number. Code generation for the loops is different, so we syntactically  propagate this distinction in our rewrite by including the reference creation in the loop variable creation. A full type analysis is unnecessary for this step as the mode is clear by examining the enclosing scope and node schema.\n\\end{itemize}\n\nEventual code generation must include loops, even if they are not visible to the scheduler, so we must somehow propagate the loop structure through the transformation. We already discussed reconstituting loop nests, so the only remaining issue is handling the erased Kleene stars.  For each node type $\\tau$, we keep a set $\\chi_{\\tau}$ indicating which children are collections. E.g., $\\chi_{\\text{Table}} = \\{Row, Column\\}$.\n\n\\subsection{Reference type and usage analysis.}\nOur support for references is the same as in the case of references without collections. \n\\subsection{Reference rewriting.}\nReference rewriting proceeds the same as in the case of references without collections.\n\\subsection{Scheduling.}\nScheduling proceeds with an attribute grammar schedule with no knowledge of our extensions.\n\n\\subsection{Code generation.}\nCode generation occurs much in the same way as with just the reference extension, but we use custom handling for \\code{lhs := loopVar(...)} and \\code{loopBody(...)} statements. The former, \\code{loopVar}, is unnecessary, so we elide it. Perhaps not immediately intuitive, the generated loop nest structure is not the same as that of the input due to the declarative nature of the input. What was 1 loop in the input may be multiple under the new schedule. \n\nConsider the following declarative loop to sum children and broadcast the sum to them:\n\n\\begin{lstlisting}[mathescape]\nmaxWidth := \n  reduce cell in Column*\n    return$`$ := 0 .. max(return, cell.minimumWidth)\n    cell.width := maxWidth\n\\end{lstlisting}\n\nImperative code might be scheduled to do this in two loops, perhaps in even two different traversals of the tree:\n\n\\begin{lstlisting}[mathescape]\nmaxWidth := 0;\nfor (cell in Column*) \n  maxWidth := max(maxWidth, cell.minimumWidth)\n$\\ldots$  \nfor (cell in Column*)\n    cell.width := maxWidth\n\\end{lstlisting}\n\n\nReconstituting loop nests is a parsing problem: we must place opening and closing braces, where an opening brace represents starting a loop. Parsing can be done in one linear left-to-right pass using a stack. Given the original loop nesting, there is some partial order $<$ where loop variable $a < b$ if a loop with index variable $a$ is enclosed by a loop with index variable $b$. Note that we do not need to create this operator during initial rewriting; it can be extracted from the loop encoding. We denote string $a_0 \\ldots a_j$ maximal if, for any $0 \\leq i < j$, $a_i < a_{i+1}$ and $\\neg \\exists b . a_i < b ~\\wedge~ b < a_{i+1}$. For every nesting of loops, let $path_{a}^{b}$ denote the maximal string between loops $a$ and $b$ (i.e., the nesting sequence of loops).\n\nFor each statement $lhs := loopBody(a, ...)$:\n\n\\begin{itemize}\n\\item $a = peak(stack)$: proceed.\n\\item $a < peak(stack)$: push string $path_{peak(stack)}^{a}$, emit the corresponding loop nestings ($|path_{peak(stack)}^{a}|$ of them), and then proceed.\n\\item $a \\not< peak(stack)$: close 1 level of nesting and pop the stack. Repeat entire process (do not proceed).\n\\end{itemize}\n\nStatements not involving loops (neither \\code{loopBody} nor \\code{loopVar}) are top-level statements; the stack is emptied and all loops are enclosed.\n\nA final subtlety is the use of intermediate variables in the case of loop fission. For example, we repeatedly count the step of an iteration using variable $i$: it might be accessed in statements in either split loop body, so must be available to both. We can either store these computations, or simpler for our implementation, recompute them. Our code generator thus checks the accessed set of local fields within each loop body and includes the computation of any used loop variables (this can be viewed as a time vs. memory exchange).\n\n\n%First, we eliminate collective operations. Consider collections over items such as \\code{Column*}. One option is rewriting the grammar to use \\emph{cons} lists, e.g., $A\\rightarrow B^{*}$ becomes $A\\rightarrow B_{List}$ and $B_{List} \\rightarrow B ~B{List}~ |~ B_{\\epsilon}$, where the initial, iteration, and termination code of a loop is split between $A$, $B_{List}$, and $B_{\\epsilon}$, respectively. This encoding does not support first-class collections and artificially restricts our ability to generate parallel schedules.  \n\n%We uniformly rewrite reductions over first-class and AST collections. AST collections, e.g., \\code{Column*}, are eliminated by rewriting to singletons, e.g., \\code{Column\\_Star}, and moving loop operations to these intermediate nodes. Class fields are duplicated. For purely scheduling, we might just rewrite \\code{Column*} to \\code{Column}, but propagating the use of a collection simplifies code generation. \n\n%All reductions are eliminated: reduction variables are hoisted to class variables and statements within a reduction are rewritten to use a \\code{loop} function. E.g., \\code{i` := 0 .. i .. } is hoisted out of the enclosing reduction and scheduled as \\code{i := loop(0)}, where the arguments to loop propagate any dependencies. For code generation, we must also propagate code for the iteration step. \n\n\\begin{figure}\n\\begin{lstlisting}[mathescape]\n//idealized declarative input: \n//  AG with reference passing, collections\n@Start Table $\\rightarrow$ Row* Column* { }\nCell $\\rightarrow$ { input width : int }\nRow $\\rightarrow$ Cell* { var cells : [ref Cell] }\nColumn $\\rightarrow$ { \n  var rows : [ref Row];\n  var n, width : int;\n  var cells : [ref Cell]; \n}\nTable { \n  reduce c in Column* where i : int {\n    i$'$ := 0 .. i + 1 ..;\n    c.n := i;\n    c.rows := @Row*;\n  } \n}\nRow { cells := @Cell*}\nColumn { \n  cells := reduce r in rows {\n    nCells$'$ := reduce c in r$\\rightarrow$cells where i : int {\n      i$'$ := 0 .. i + 1 ..;\n      return$'$ := \n        [] .. i = n ? [c | return] : return ..;\n    }\n    return$'$ := [] ..  [nCells @ return] ..;\n  }\n  width := reduce child in cells\n    return$'$ := 0 .. max(return, child$\\rightarrow$width) ..;\n}\n\\end{lstlisting}\n\n\\begin{lstlisting}[mathescape]\n//reduce collections and lift loops\n@Start Table $\\rightarrow$ Row Column { \n  var i : int \n  phantom var c : ref Column;\n}\nCell $\\rightarrow$ { input width : int }\nRow $\\rightarrow$ Cell { var cells : ref Cell }\nColumn $\\rightarrow$ {   \n  var rows : ref Row;\n  var n : int;\n  var cells : ref Cell;\n  var nCells : ref Cell;\n  var width : int; \n  var i : int;  \n  phantom var r : ref Row;\n  phantom var c : ref Cell;\n  phantom var child : ref Cell;\n}\nTable {  \n  c := loopVar(@Column);\n  i := loopBody(c, $f_{a}$, 0);\n  Column.n := loopBody(c, $f_b$, i);\n  Column.rows := loopBody(c, $f_c$, @Row);\n}\nRow { cells := @Cell }\nColumn { \n  r := loopVar(rows);\n  c := loopVar(r$\\rightarrow$cells);  \n  cells := loopBody(r, $f_d$, nCells);\n  nCells := loopBody(c, $f_e$, i, n, c);\n  i := loopBody(c, $f_f$, 0);\n  child := loopVar(cells);\n  width := loopBody(child, $f_g$, 0, child$\\rightarrow$width);  \n}\n$f_{a}$ = $\\lambda$i.i + 1\n$f_{b}$ = $\\lambda$i.i\n$f_{c}$ = $\\lambda$Row.Row\n$f_{d}$ = $\\lambda$cells,nCells.append(nCells, cells)\n$f_{e}$ = $\\lambda$i,n,c,nCells.i = n ? concat(c,nCells) : nCells\n$f_{f}$ = $\\lambda$i.i + 1\n$f_{g}$ = $\\lambda$c_width,width.max(width,c_width)\n\\end{lstlisting}\n\\end{figure}\n\n\\begin{figure}\n\\begin{lstlisting}[mathescape]\n//expand references\n@Start Table $\\rightarrow$ Row Column { \n  var i : int \n  phantom var c : ref Column;\n}\nCell $\\rightarrow$ { input width : int }\nRow $\\rightarrow$ Cell { \n  var cells : ref Cell;\n  phantom var cells$_{width}$ : int;\n}\nColumn $\\rightarrow$ {   \n  var rows : ref Row;\n  phantom var rows$_{cells}$, cells, nCells, r$_{cells}$, c, \n              child : ref Cell;\n  phantom var rows$_{cells{_{width}}}$, cells$_{width}$, nCells$_{width}$, \n              r$_{cells_{width}}$, c$_{width}$, child$_{width}$ : int;\n  var n, width, i : int;\n  phantom var r : ref Row;\n}\nTable {\n  c := loopVar(@($``\\&Column\"$));\n  i := loopBody(c, $f_a$, 0);\n  Column.n := loopBody(c, $f_b$, i);\n  Column.rows := loopBody(c, $f_c$, @($``\\&Row\"$));\n  Column.rows_cells := $\\O$(Row.cells);\n  Column.rows_cells_width := $\\O$(Row.cells_width);\n}\nRow { \n  cells := @($``\\&Cell\"$) \n  cells_width := $\\O$(Cell.width);\n}\nColumn { \n  r := loopVar(rows);\n  r_cells := $\\O$(rows_cells);\n  r_cells_width := $\\O$(rows_cells_width);  \n  c := loopVar($\\rightarrow$(r_cells));\n  c_width := $\\O$(r_cells_width);  \n  cells := loopBody(r, $f_d$, nCells);\n  cells_width := $\\O$(nCells_width);\n  nCells := loopBody(c, $f_e$, i, n, c);\n  nCells_width := $\\O$(c_width);\n  i := loopBody(c, $f_f$, 0);\n  child := loopVar(cells);\n  child_width := $\\O$(cells_width);\n  width := loopBody(child, $f_g$, 0, $\\rightarrow$(child_width));  \n}\n\\end{lstlisting}\n\n\\begin{lstlisting}[mathescape]\n//generated visits\nclass Pass0 : BottomUp {\n   void visit (Table n) { \n    i = 0;\n    for (Column column : n.ColumnStar) {\n      i = i + 1;\n      column.n = i;\n      column.rows = n.RowStar;\n    } } }\nclass Pass1 : TopDown {\n   void visit (Row n) { cells = n.CellStar; }\n   void visit (Column n) {\n    cells = new ArrayList<Cell>();\n    for (Row r : n.rows) {\n      nCells = new ArrayList<Cell>();\n      int i = 0;\n      for (Column c : r.cells) {\n        i = i + 1;\n        nCells = n.n == i++ ? [c | nCells] : nCells;        \n      }\n      cells = [nCells @ cells];\n    }\n    n.width = 0;\n    for (Cell child : n.cells)\n      n.width = Math.max(n.width, child.width); } }\n\\end{lstlisting}\n%$\\ldots$\n%(new Pass0()).visit(tree);\n%(new Pass1()).visit(tree);\n\\end{figure}\n\n\nNote that syntax nodes are not directly in dependencies. E.g., we do not use \\code{Column} as a parameter. Reductions over first-class collections must include the collection as a dependency. We distinguish these two forms as \\code{loopBody} and \\code{loopBody}, respectively.\n\n\n\\subsection{Eliminating References}\nWe repeat our transformation from the previous section to eliminating our use of references here.\n\n\n\n\n\\subsection{Primitives vs. Foreign Functions}\n\nAs a grammar is likely embedded in some generic \\emph{host} language, we might pass references through foreign functions. However, we can no longer schedule their use, and the host likewise would not know when reachable attributes are available. [[iffy..]]\n\n\n\\subsection{Rewrite rules}\n\n\n%\\input{rewritescollections}\n\\begin{figure*}\n\\caption{$GAG_{dyn~collect}$: Translation of an AG with first-class references and collections to $GAG_{dynamic}$ and extended code generation rules. \\textbf{[[TODO; previous version combined the two rewrites in one place, which was a mess]]} }\n\\label{fig:statrewrites}\n\\end{figure*}\n", "meta": {"hexsha": "309a39a9b4f91381e736fde958096e813b5fbc74", "size": 18244, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "compiler/attrib-gram-evaluator-swipl/Docs/DAGs/collections.tex", "max_stars_repo_name": "Superconductor/superconductor", "max_stars_repo_head_hexsha": "fdcef1258d9ede46636b0e1ebcfc2c5b473b4214", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 88, "max_stars_repo_stars_event_min_datetime": "2015-01-24T06:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:56:05.000Z", "max_issues_repo_path": "compiler/attrib-gram-evaluator-swipl/Docs/DAGs/collections.tex", "max_issues_repo_name": "mcanthony/superconductor", "max_issues_repo_head_hexsha": "fdcef1258d9ede46636b0e1ebcfc2c5b473b4214", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-01T06:14:12.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-01T06:14:12.000Z", "max_forks_repo_path": "compiler/attrib-gram-evaluator-swipl/Docs/DAGs/collections.tex", "max_forks_repo_name": "mcanthony/superconductor", "max_forks_repo_head_hexsha": "fdcef1258d9ede46636b0e1ebcfc2c5b473b4214", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2015-01-24T00:13:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-23T09:33:10.000Z", "avg_line_length": 59.4267100977, "max_line_length": 778, "alphanum_fraction": 0.7278009209, "num_tokens": 4509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.30092888987290134}}
{"text": "\\documentclass[12pt]{article}\n\n\\usepackage[utf8]{inputenc}\n\n\n\\usepackage{amsmath,amsthm,amssymb}\n\\usepackage{mathrsfs}\n\\usepackage{authblk}\n\n\\theoremstyle{plain}\n\\newtheorem{theorem}{Theorem}\n\\newtheorem{lemma}{Lemma}\n\\newtheorem{proposition}{Proposition}\n\\theoremstyle{definition}\n\\newtheorem{corollary}{Corollary}\n\\theoremstyle{remark}\n\\newtheorem{remark}{Remark}\n\\newtheorem*{remark*}{Remark}\n\n\\numberwithin{equation}{section}\n\n\\usepackage[margin=25mm]{geometry}\n\n\\usepackage{fancyhdr}\n\\rfoot{\\thepage}\n\n\\begin{document}\n\n\\title{Stable subspaces of positive maps of matrix algebras}\n\n\\author[1]{Marek Miller\\thanks{marek.miller@ift.uni.wroc.pl}}\n\\author[1]{Robert Olkiewicz\\thanks{robert.olkiewicz@ift.uni.wroc.pl}}\n\\affil[1]{Institute of Theoretical Physics, Uniwersytet Wroc{\\l}awski, Poland}\n\n\\date{}\n\n\\maketitle\n\n% Abstract and Introduction\n\\abstract{ \nWe study stable subspaces of positive extremal maps of finite dimensional\nmatrix algebras that preserve trace and matrix identity \n(so-called bistochastic maps).\nWe have established the existence of the isometric-sweeping\ndecomposition for such maps.\nAs the main result of the paper,\nwe have shown that all extremal bistochastic maps\nacting on the algebra of matrices of size 3x3\nfall into one of the three possible categories,\ndepending on the form of the stable subspace of\nthe isometric-sweeping decomposition.\nOur example of an extremal atomic positive map\nseems to be the first one that handles the case\nof that subspace being non-trivial.\nLastly, we compute the entanglement witness associated with the extremal map\nand specify a large family of entangled states detected by it.\n\n\\vspace{0.1cm}\n{\\scriptsize \\noindent \\textbf{Keywords.}\npositive maps, extremal, exposed, atomic,\nentanglement witness\n}\n\n{\\scriptsize \\noindent \\textbf{MSC2010 codes.}\n47H07  15B48  81P40}\n}\n\n\n\\section*{Introduction}\n\\label{sec:Introduction}\n\n\\paragraph{}\nPositive maps of operator algebras is an increasingly\npopular subject of research,\nboth as a mathematical theory interesting in itself,\nas well as a prominent domain of applications to quantum theory\n\\cite{stormer2013positive}.\nStarted in the pioneering work of Kadison\n\\cite{kadison1952generalized},\nand Stinespring\n\\cite{stinespring1955positive},\nthe theory reached its first major breakthrough,\nwhen St{\\o}rmer and Woronowicz presented a structure theorem\nfor positive maps of low dimensional matrix algebras\n\\cite{stormer1963positive,woronowicz1976positive}.\nIt is also necessary to mention the work of \\mbox{M.-D.\\,Choi} here,\nas the major contribution to the theory at every stage\n\\mbox{\\cite{choi1975completely,choi1980some,choi1977extremal}}.\nThe second turning point came in 1990s,\nwhen Peres and P.\\,M.\\,R.\\,Horodeckis pointed out at the intrinsic relation\nbetween separable states of composite quantum systems\nand positive maps of algebras of observables\n\\cite{peres1996separability,horodecki1996separability}.\nIt turns out that there is a one-to-one correspondence between\npositive maps and entanglement witnesses\n\\cite{chruscinski2014entanglement},\nand the Peres-Horodecki criterion,\nwhether a quantum state is separable,\nis computationally feasible as long as a structure theorem\nsimilar to that proven by St{\\o}rmer and Woronowicz holds true.\nUnfortunately,\nwhereas that correspondence does exists even for\nthe most general infinite-dimensional quantum systems\n\\mbox{\\cite{stormer2009separable,miller2014horodeckis}},\nhigher dimensional situation lacks\nthe complete description of positive maps\nand one needs a deeper understanding of their highly nontrivial structure.\nBecause the set of positive maps forms a convex cone,\nits elements can be characterised as convex combinations of extremal ones.\nThis is a consequence of the celebrated Krein-Milman theorem\n\\cite{krein1940extreme}, as for every positive number $r > 0$,\nthe set of positive maps such that their operator norm: $||S|| \\leq r$,\nis compact.\nThis is certainly true for maps on finite-dimensional matrix algebras,\nbut applies also to the general setting of von Neumann algebras \\cite{miller2014horodeckis}.\nDespite considerable effort,\nexamples of extremal positive maps,\neven in the low-dimensional case,\nare scarce\n\\cite{choi1977extremal,osaka1992class,ha2011entanglement,chruscinski2011exposed}.\nIn this paper, we deal exclusively with extremal maps as extreme points in\nthe cone of all positive maps on matrix algebras (see below).\n\n\nIn order to facilitate the further study of extremal positive maps,\nwe propose to take a closer look at their stable subspaces.\nIn general, by a 'stable subspace' of a positive map \n$S \\! : M_{n} \\rightarrow M_{n}$,\nwhere $M_{n}$ stands for the algebra of square complex matrices\nof size $n$,\nwe mean a particular subspace $K_{S} \\subset M_{n}$\n(in fact, a JB$^{*}$-algebra, see \n\\mbox{Corollary \\ref{cor:KisJordanAlgebra}} \nbelow),\nsuch that the map is a Jordan automorphism on $K_{S}$ and \n$S^{k} \\rightarrow 0$ strongly\non the orthogonal complement of $K_{S}$,\nas $k \\rightarrow \\infty$\n(see the more precise definition below).\nWe say that the map $S$ is strongly ergodic,\nif $K_{S}$ is isomorphic to the set of complex numbers.\nAdapting the previous results in this matter from\n\\cite{olkiewicz1999environment},\nwe establish the existence of the isometric-sweeping\ndecomposition for a positive map that preserves trace and\nthe matrix identity\n(so-called bistochastic maps).\nSuch decomposition says precisely that $S$ must be\na Jordan automorphism of $K_{S}$,\nand its powers tend strongly to $0$ for any matrix orthogonal to $K_{S}$.\nWhat is interesting in this respect,\nis that if we narrow our interest to the maps acting on $M_{3}$,\nit turns out that there are only three possible\nforms the algebra $K_{S}$ can have.\nMoreover, it seems that all previously known examples of extremal positive\nmaps of $M_{3}$ fall into only two of the three possible categories:\nin particular,\nit is easy to see that for a Jordan automorphism $S(A) = U^{*} A \\, U$,\nor $S(A) = U^{*} A^{t} \\, U$,\nwhere $U$ is unitary,\n$K_{S} = M_{3}$;\nwhereas the Choi map\n\\cite{osaka1992class,choi1977extremal}\nis strongly ergodic.\nThe remaining possibility among those three,\nnamely the two dimensional commutative subalgebra,\nrequires from us to expand on an example of a positive map\nthat cannot be classified as belonging to one of the types\npreviously encountered in the literature.\nOne of the main results of this paper is the proof\nthat the map provided by us as the example is indeed extremal and atomic\n\\cite{ha1998atomic}.\nMoreover, we show that the map is also exposed.\nThis fact gives immediately a useful entanglement witness\nthat the authors hope could serve as a prototypic case in further study \nof the entanglement of three-level quantum systems\n\\cite{bertlmann2005optimal,caves2000qutrit}.\n\nThe structure of the paper is as follows.\nIn Section \\ref{sec:Preliminaries},\nwe introduce some basic notions and notation.\nIn Section \\ref{sec:Decomposition},\nfollowing \\cite{olkiewicz1999environment},\nwe establish the existence of the isometric-sweeping\ndecomposition of bistochastic maps of finite dimensional\nmatrix algebra $M_{n}$.\nNext, in Section \\ref{sec:ExtremalMaps},\nwe provide the main result of this paper and prove that\nfor bistochastic map of $M_{3}$\nthe stable subspace of the decomposition takes only one of three\npossible forms.\nWe end the paper with an original example of an extremal positive map of \nthe algebra $M_{3}$;\nwe compute the entanglement witness associated with the extremal map\nand specify a large family of entangled states detected by it.\n\n\n\n\n% Preliminaries\n\\section{Preliminaries}\n\\label{sec:Preliminaries}\n\n\\paragraph{}\nLet $n \\in \\mathbb{N}$.\nThe complex linear space $\\mathbb{C}^{n}$ consists of column vectors:\n$\\eta, \\xi$, etc.; the respective row vectors are denoted\n$\\eta^{t}, \\xi^{t}$, etc.\nThe bar over a number, vector or a matrix always denotes\nthe element-wise complex conjugation: e.g. \n$\\overline{z}$, $\\overline{\\eta}$, $\\overline{A}$, etc.\nThe space $\\mathbb{C}^{n}$ is equipped with the inner product\n$\\langle \\eta, \\xi \\rangle = \\eta^{*} \\xi$,\nwhere $\\eta^{*} = \\overline{\\eta}^{\\,t}$,\nand $||\\eta||^{2} = \\eta^{*} \\eta$.\nTo avoid confusion when two different spaces,\nsay $\\mathbb{C}^{m}$ and $\\mathbb{C}^{n}$, are involved,\nwe distinguish vectors belonging to one of them with an arrow:\ne.g. $\\vec{\\eta}$, $\\vec{\\xi}$.\nLet $M_{n} = M_{n}(\\mathbb{C})$ be the algebra\nof square complex matrices of size $n$.\nWe will use letters $A, B, C$, etc. to specify a matrix of $M_{n}$.\nThe norm of $A$, denoted by $||A||$, is understood as the operator \nnorm of $A$ as a linear map acting on $\\mathbb{C}^{n}$.\nFor a vector $\\eta \\in \\mathbb{C}^{n}$, $\\eta \\neq 0$,\nby $P_{\\eta}$ or $P({\\eta}) \\in M_{n}$,\nwe denote the rank-one operator\n$P_{\\eta}  =  \\eta \\eta^{*}$.\nOf course, when $||\\eta|| = 1$, \n$P_{\\eta}$ is the orthogonal projection onto one-dimensional space\nspanned by $\\eta$.\nFor $A \\in M_{n}$, \nwe denote its trace by $\\text{Tr} A$;\nand by $A^{t}$ and $A^{*} = \\overline{A}^{\\,t}$ \nits transpose and conjugate transpose, respectively.\nWe say that a matrix $A$ is positive-semidefinite,\nor simply \\emph{positive},\nif $\\eta^{*} A \\eta \\geq 0$ for any $\\eta \\in \\mathbb{C}^{n}$\n(i.e. $A = A^{*}$ and $A$ has a non-negative spectrum).\n\nA linear map $S\\!: M_{n} \\rightarrow M_{n}$ is said to be positive,\nindicated as $S \\geq 0$,\nif for any $A \\in M_{n}$ such that $A \\geq 0$,\nwe have $S(A) \\geq 0$. \nFor a positive map $S$,\nits operator norm is given by $||S|| = S(\\mathbf{1})$,\nwhere $\\mathbf{1}_{n}$, or simply $\\mathbf{1}$,\nis the identity matrix of $M_{n}$.\nAny positive map is Hermitian,\ni.e.  $S(A^{*}) = S(A)^{*}$, for all $A \\in M_{n}$.\nThe identity map of $M_{n}$ is labelled $I_{n}$,\nor simply $I$.\nThe convex cone of all positive maps of $M_{n}$ is denoted\nby $\\mathcal{P}(M_{n})$.\nFor $k \\in \\mathbb{N}$, a map $S \\in \\mathcal{P}(M_{n})$,\nsuch that the map\n$I_{k} \\otimes S :  M_{k} \\! \\otimes \\! M_{n}\n \\rightarrow  M_{k} \\! \\otimes \\! M_{n}$\nis positive,\nis called $k$-positive.\nIf a map is a $k$-positive map for every $k$,\nit is called completely positive.\nSimilarly, a map is $k$-\\emph{co}positive,\nor completely copositive,\nif $I_{k} \\otimes (S \\circ t)$ is positive for\nsome $k$, or for every $k$, respectively,\nwhere $t \\! : A \\mapsto A^{t}$,\n$A \\in M_{n}$, is the transposition map.\nA positive map $S$ is called decomposable,\nif it can be written in the form\n$S(A) = \\Lambda_{1}(A) + \\Lambda_{2} (A^{t})$,\nwhere both maps $\\Lambda_{1}, \\Lambda_{2}$ are completely positive,\npossibly zero\n(see \\cite{choi1975completely} for more details on completely positive maps).\nIt is called atomic \\cite{ha1998atomic},\nif it cannot be written as a sum of 2-positive and 2-copositive maps.\nA positive map $S$ is extremal,\nif for any positive map $T: M_{n} \\rightarrow M_{n}$ such that\n$S - T \\in \\mathcal{P}(M_{n})$,\ni.e. $0 \\leq T \\leq S$,\nwe have $T = \\alpha S$ for some number $0 \\leq \\alpha \\leq 1$.\nWe denote the set of extremal maps of $\\mathcal{P}(M_{n})$\nby $\\text{Ext}(M_{n})$.\nIt is true that every positive map\ncan be written as a convex combination of extremal ones.\nNevertheless, it could be of use to specify a dense subset\nof $\\text{Ext}(M_{n})$,\nsuch that it is easier to handle its elements instead of\ngeneral extremal maps.\nHence, we say that a positive map $S$ of the matrix algebra\n$M_{n}$ is exposed\n\\cite{marciniak2013rank},\nif for all $T \\in \\mathcal{P}(M_{n})$ such that\n$\\text{Tr}\\, P_{\\xi} \\, T(P_{\\eta}) = 0$,\nwhere $\\mathbb{C}^{n} \\ni \\eta, \\xi \\neq 0$ is any pair for which\n$\\text{Tr}\\, P_{\\xi} \\, S(P_{\\eta}) = 0$,\nwe have that $T = \\alpha S$, $\\alpha \\geq 0$.\nDue to the Straszewicz theorem \\cite{straszewicz1935exponierte},\nthe set of exposed maps of $M_{n}$ is indeed dense in $\\text{Ext}(M_{n})$.\n\nBy a JB$^{*}$-algebra $K$ we understand a complex Banach space \nwhich is also a complex Jordan algebra.\nWe always assume that $\\mathbf{1} \\in K$.\nSee \n\\cite{hanche1984jordan}\nfor the overview of the theory of JB$^{*}$-algebras.\n\n% Isometric-sweeping of S\n\\section{Decomposition of bistochastic maps}\n\\label{sec:Decomposition}\n\n\\paragraph{}\nLet $S\\!: M_{n} \\rightarrow M_{n}$ be a positive map such that\n$S(\\mathbf{1}) = \\mathbf{1}$,\n$\\text{Tr} S(A) = \\text{Tr} A$,\nfor any $A \\in M_{n}$.\nWe call such a map \\emph{bistochastic}.\nIt is easy to see that $S$ is a contraction in\nthe Hilbert-Schmidt norm (\\emph{HS-norm}) on $M_{n}$,\ndefined as\n$||A||_{HS} = \\left( \\text{Tr} \\, A^{*} A \\right)^{1/2}$.\nIndeed,\nsince $S$ fulfils the Kadison-Schwarz inequality,\n\\begin{equation}\n\\label{eq:SchwarzInequality}\n    S(A^{*}) \\, S(A) \\: \\leq \\: S(A^{*} A),\n\\end{equation}\nfor any normal element $A \\in M_{n}$ (see Prop.\\,3.6 of \\cite{choi1980some}),\nassuming at first that $A = A^{*}$,\nwe have\n\\begin{equation}\n\\label{RandomLabel:712874}\n    || S(A) ||_{HS}^{2} \\: = \\: \\text{Tr} S(A)^{2}\n    \\: \\leq \\:  \\text{Tr} S(A^{2}) \\: = \\:\n        \\text{Tr} A^{2} \\: = \\: ||A||_{HS}^{2}.\n\\end{equation}\nBy representing a general element $A \\in M_{n}$ as a sum\n$A = A_{1} + i A_{2}$,\nwhere both $A_{1}, A_{2}$ are self-adjoint,\nand repeating essentially the same calculation as in\n\\eqref{RandomLabel:712874},\nwe obtain the assertion.\n\nNext,\nwe are going to define an isometric splitting of $S$,\ndrawing from the ideas presented in \\cite{olkiewicz1999environment}.\nBecause $S$ is a contraction in the HS-norm on the Hilbert space $M_{n}$,\nequipped with the Hilbert-Schmidt inner product,\nthat space can be decomposed into a direct sum of a space $K_{S}$,\ndefined as\n\\begin{equation}\n\\label{def:definitionofK}\n    K_{S} \\: = \\: \\left\\{\n        A \\in M_{n}: \\,\\,\n            || S^{k} A ||_{HS} = || S^{* k} A ||_{HS} = || A ||_{HS}, \\:\\:\n            \\forall k \\in \\mathbb{N}\n        \\right\\},\n\\end{equation}\nand its orthogonal complement $K_{S}^{\\perp}$.\nBy $S^{*}$, we denote the bistochastic map of $M_{n}$,\nwhich is the adjoint of $S$ as a linear operator on the Hilbert space $M_{n}$,\ni.e. $\\text{Tr}\\, S^{*} (A)\\, B = \\text{Tr} A \\, S(B)$,\nfor every $A, B \\in M_{n}$.\nIt is true that $A \\in K_{S}$,\nif and only if\n$S^{* k} S^{k} A = S^{k} S^{* k} A = A$,\nfor any $k \\in \\mathbb{N}$.\nThe following proposition,\ntaken with slight modification from\n\\cite{olkiewicz1999environment},\nputs together some of the characteristics of $K_{S}$.\n\n\\begin{proposition}\n\\label{prop:propertiesofK}\nSuppose $S$ is a bistochastic map of $M_{n}$,\nand the subspace $K_{S}$ is defined as in \\eqref{def:definitionofK}.\nThen:\n\n% Enumerate the list like: a), b), c) etc.\n\\let \\oldlabelenumi \\labelenumi\n\\renewcommand{\\labelenumi}{\\alph{enumi})}\n\\begin{enumerate}\n\\item $\\mathbf{1} \\in K_{S}$;\n\\item $A \\in K_{S}$ implies that $A^{*} \\in K_{S}$;\n\\item  $A  \\in K_{S}$ implies that\n$|A| = (A^{*}A)^{1/2} \\in K_{S}$;\n\\item if $A, B \\in K_{S}$, then $AB + BA \\in K_{S}$;\n\\item if $A = A^{*} \\in K_{S}$ and $A = \\sum_{i=1}^{k} \\lambda_{i} P_{i}$,\nwhere each $\\lambda_{i} \\neq 0$ is different,\nand each $P_{i}$ is a orthogonal projection in $M_{n}$,\nthen $P_{i} \\in K_{S}$ for any $i = 1,2,\\ldots,k$;\n\\item if $P \\in K_{S}$ is an orthogonal projection,\nthen $S(P)$ and $S^{*}(P)$ are orthogonal projections as well,\nand $\\mathrm{dim} \\, S(P) = \\mathrm{dim} \\, S^{*}(P) = \\mathrm{dim} \\, P$;\n\\item if $P, Q \\in K_{S}$ are orthogonal projections such that $P Q = 0$,\nthen $S(P) S(Q) = S^{*}(P) S^{*}(Q) = 0$.\n\\end{enumerate}\n% Return to the old enumaration style\n\\let \\labelenumi \\oldlabelenumi\n\\end{proposition}\n\n\\begin{proof}\na) obvious, since $S$ is bistochastic;\nb), c) as in Prop. 5\\,a) and 5\\,b) of \\cite{olkiewicz1999environment}.\n\nd)  Suppose at first that $A = A^{*} \\in K_{S}$.\nNow, $S^{*k} S^{k}(A) = S^{k} S^{*k}(A) = A$,\nand, as a result of the Kadison-Schwarz inequality applied to the map\n$S^{*k} S^{k}$,\n\\begin{equation}\nA^{2} \\: = \\: \\left( S^{*k} S^{k}(A) \\right) \\left( S^{*k} S^{k}(A) \\right)\n    \\: \\leq \\: S^{*k} S^{k}(A^{2}).\n\\end{equation}\nHence\n\\begin{equation}\n||A^{2}||_{HS} \\: \\leq \\: || S^{*k} S^{k}(A^{2}) ||_{HS} \\: \\leq \\:\n    || S^{k}(A^{2}) ||_{HS} \\: \\leq \\: ||A^{2}||_{HS},\n\\end{equation}\ni.e. $|| S^{k}(A^{2}) ||_{HS} = ||A^{2}||_{HS}$.\nBy a similar argument\n$|| S^{*k}(A^{2}) ||_{HS} = ||A^{2}||_{HS}$,\nand thus $A^{2} \\in K_{S}$.\nNow, for any $A, B \\in K_{S}$, such that $A = A^{*}$, $B = B^{*}$,\nwe have\n$AB + BA = (A + B)^{2} - A^{2} - B^{2} \\in K_{S}$.\nFor a general $A \\in K_{S}$, we write\n$A = A_{1} + i A_{2}$, where $A_{1}, A_{2}$ are both Hermitian.\nThen\n$A^{2} = A_{1}^{2} - A_{2}^{2} + i(A_{1} A_{2} + A_{2} A_{1}) \\in K_{S}$.\nIt is now evident that $AB+BA \\in K_{S}$ for general $A,B \\in K_{S}$.\n\ne) as in Prop. 5\\,d);\nf), g) as in Prop. 6\\,a) and 6\\,c) of\n\\cite{olkiewicz1999environment}.\n\\end{proof}\n\nFrom what has been said above, \nfollows immediately the next observation.\n\n\\begin{corollary}\n\\label{cor:KisJordanAlgebra}\nThe space $K_{S}$, with the matrix norm $|| \\cdot ||$,\nand the multiplication $A \\circ B = \\frac{1}{2}(AB + BA)$,\nis a JB$^{*}$-algebra.\nThe map $S$ is a Jordan automorphism on $K_{S}$ and \n\\begin{equation}\n\\label{eq:SGoesTo0OnKOrth}\n    \\lim \\limits_{k\\rightarrow \\infty} S^{k}(A)  \\: = \\:\n    \\lim \\limits_{k\\rightarrow \\infty} S^{*k}(A) \\: = \\: 0,\n\\end{equation}\nfor any $A \\in K_{S}^{\\perp}$.\n\\end{corollary}\n\n\\begin{proof}\nIt is obvious that $K_{S}$ is a complex Banach space. \nFrom Proposition \\ref{prop:propertiesofK}\\,b),\nwe have that $K_{S}$ is equipped with involution,\nand from point d) \nthat $K_{S}$ is a Jordan algebra.\nSince the map $S$ is invariant with respect to the subspaces\n$K_{S}$ and $K_{S}^{\\perp}$,\nand of course $M_{n} = K_{S} \\oplus K_{S}^{\\perp}$,\nwe see that $S$ splits into direct sum\n$S = S_{1} \\oplus S_{2}$,\nwhere $S_{1} = S_{| K_{S}}$, $S_{2} = S_{| K_{S}^{\\perp}}$.\nFrom Prop. 7a) of\n\\cite{olkiewicz1999environment},\nwe have that $S(A^{*} A) = S(A)^{*} S(A)$,\ni.e. $S$ is a Jordan homomorphism on $K_{S}$.\nMoreover,\nbecause $S^{*} S = S S^{*} = I$ on $K_{S}$,\nthe map $S_{1}$ is invertible,\nand thus it is a Jordan automorphism\n(see Definition 3.2.1(6) in \\cite{bratteli2003operator}).\nFrom the definition \\eqref{def:definitionofK} of the space $K_{S}$,\nfollows easily that \neq. \\eqref{eq:SGoesTo0OnKOrth} holds.\n\\end{proof}\n\n\\begin{theorem}\n\\label{thm:FromESbook}\nLet $K \\subset M_{n}$ be a JB$^{*}$-subalgebra of $M_{n}$.\nThere is a bistochastic map\n$S \\! : M_{n} \\rightarrow M_{n}$ such that $K = K_{S}$.\n\\end{theorem}\n\\begin{proof}\nWe consider the space $M_{n}$ to be a Hilbert space equipped\nwith the Hilbert-Schmidt inner product.\nLet $S\\!: M_{n} \\rightarrow K \\subset M_{n}$ be the \northogonal projection onto $K$.\nIt is evident that $S(\\mathbf{1}) = \\mathbf{1}$,\nand because $S = S^{*}$, \nthe map $S$ also preserves trace and\nthe space $K$ is a stable subspace for $S$,\nprovided $S$ is a positive map.\nLet then $A \\in M_{n}$ be a positive matrix.\nSince $K$ is JB$^{*}$-algebra,\n$(SA)^{*} \\in K$.\nBecause \n$|| A - SA ||_{HS} = || A - (SA)^{*} ||_{HS}$,\nand $SA$ is the best approximation of $A$ in the space $K$,\nwe have that $(SA)^{*} = SA$.\nWe write then $SA = B_{+} - B_{-}$,\nwhere both $B_{+}, B_{-}$ are positive and \n$B_{+} B_{-} = 0$.\nWe have assumed that $\\mathbf{1} \\in K$,\nand because $(SA)^{k} \\in K$ for any $k \\in \\mathbb{N}$,\nwe have that also the modulus $|S A| \\in K$\n(compare the explicit formula for\nthe square-root of a positive matrix in \\cite{bratteli2003operator}, p. 34).\nHence both $B_{+}, B_{-} \\in K$.\nWe compute\n\\begin{multline}\n|| A - SA ||_{HS}^{2} \\: = \\: \\text{Tr} \\, ( A - SA )^{2} \\: = \\:\n    \\text{Tr} \\, ( A - B_{+} + B_{-} )^{2} \\: = \\: \\\\\n    \\text{Tr} \\, ( A - B_{+} )^{2} + \n        2 \\, \\text{Tr} \\, ( A - B_{+} ) B_{-} + \\text{Tr} \\, B_{-}^{2}\n            \\: = \\: \\\\\n    || A - B_{+} ||_{HS}^{2} + \n        2 \\, \\text{Tr} \\,  A \\, B_{-}+ \\text{Tr} \\, B_{-}^{2} \n    \\: \\geq \\: || A - B_{+} ||_{HS}^{2}.\n\\end{multline}\nAgain, since $SA$ is the best approximation of $A$ in $K$,\nwe have $SA = B_{+}$, i.e. $SA \\geq 0$, which ends the proof.\n\\end{proof}\n\nFrom the above,\nwe know that $K_{S}$ has additional structure of a JB$^{*}$-algebra.\nWe will see in the following that,\nwith additional assumption imposed on S,\nthis algebra must necessarily\nhave a specific structure,\nat least for low dimensional matrices.\n\n\n\\section{Extremal positive maps}\n\\label{sec:ExtremalMaps}\n\n\\paragraph{}\nIn this section, we focus on maps of the algebra $M_{3}$.\nFor convenience, let us label four orthogonal projections:\n\\begin{equation}\n\\label{def:OrthogonalProjections}\n    P_{1} = \\begin{pmatrix}\n        1 & 0 & 0 \\\\\n        0 & 0 & 0 \\\\\n        0 & 0 & 0\n    \\end{pmatrix} , \\quad \\quad\n    P_{2} = \\begin{pmatrix}\n        0 & 0 & 0 \\\\\n        0 & 1 & 0 \\\\\n        0 & 0 & 0\n    \\end{pmatrix} , \\quad \\quad\n    P_{3} = \\begin{pmatrix}\n        0 & 0 & 0 \\\\\n        0 & 0 & 0 \\\\\n        0 & 0 & 1\n    \\end{pmatrix},\n\\end{equation}\nand $P_{12} = P_{1} + P_{2}$.\n\nIt is of importance to us that\nTheorems 5.3.8 and 6.2.3 of \\cite{hanche1984jordan}\nimply that every JB$^{*}$-algebra contained in $M_{3}$ is\nisomorphic to one of the following:\n$\\mathbb{C}\\mathbf{1}$, \n$\\mathbb{C} P_{12} \\oplus \\mathbb{C} P_{3}$,\n$\\mathbb{C} P_{1} \\oplus \\mathbb{C} P_{2} \\oplus \\mathbb{C} P_{3}$,\n$M_{2} \\oplus \\mathbb{C} P_{3}$,\n$M_{2}^{s} \\oplus P_{3}$, \n$M_{3}^{s}$,\nand\n$M_{3}$ itself,\nwhere $M_{n}^{s}$ is the Jordan algebra of symmetric matrices of \nsize $n$: $M_{2}^{s} = \\{ A \\in M_{n}: A = A^{t} \\}$.  \n\n\\begin{theorem}\n\\label{thm:ExposedMaps}\nLet $S\\!: M_{3} \\rightarrow M_{3}$ be an extremal bistochastic map.\nThen the JB$^{*}$-algebra $K_{S}$ is isomorphic to one of the following:\n$\\mathbb{C}\\mathbf{1}$, $\\mathbb{C} P_{12} \\oplus \\mathbb{C} P_{3}$,\nor\n$M_{3}$.\n\\end{theorem}\n\n\\begin{proof}\n1. We proof the assertion by excluding all other possible forms of\n$K_{S}$ in the first place.\nLet $K_{S}$ be one of the following JB$^{*}$-algebras:\n$\\mathbb{C} P_{1} \\oplus \\mathbb{C} P_{2} \\oplus \\mathbb{C} P_{3}$,\n$M_{2} \\oplus \\mathbb{C} P_{3}$,\n$M_{2}^{s} \\oplus P_{3}$, or $M_{3}^{s}$.\nThen $K_{S}$ contains the projections $P_{1}, P_{2}, P_{3}$,\nand because $S$ is a Jordan automorphism on $K_{S}$:\n\\begin{multline}\n    \\text{Tr} \\, S(P_{i}) S(P_{j}) = \\\\\n= \\frac{1}{2} \\text{Tr} \\, \\left( S(P_{i}) S(P_{j}) + S(P_{j}) S(P_{i}) \\right)=\n\\frac{1}{2} \\text{Tr} \\, S(P_{i} P_{j} + P_{j} P_{i})=\n\\text{Tr} \\, P_{i} P_{j} = \\delta_{ij},\n\\end{multline}\nwhere $i,j = 1,2,3$ and $\\delta_{ij}$ is the Kronecker delta.  \nHence, $\\left\\{S(P_{i})\\right\\}_{i=1}^{3}$ \nis a triple of rank-one, mutually orthogonal projections.\nThere is a unitary matrix $U \\in M_{3}$, such that\n$U^{*} S(P_{i}) U = P_{i}$, for $i = 1,2,3$. \nLet us define $\\tilde{S}(A) = U^{*} S(A) U$.\nThen $\\tilde{S}$ is an extremal \n\\cite[Lemma 3.1.2b, p.\\,27]{stormer2013positive}\nbistochastic map such that\n$\\tilde{S}(P_{i}) = P_{i}$, $i = 1,2,3$.\nBy \\cite[Theorem 4.1]{kye1995positive},\n$\\tilde{S}$ is decomposable,\nwhich contradicts either the fact that $S$ is extremal\nor $K_{S} \\neq M_{3}$.\n\n2.\nWhile it is easy to see that there are extremal maps for which\n$K_{S}=M_{3}$ (take e.g. $S(A) = U A U^{*}$ for a unitary matrix $U$),\nor $K_{S}=\\mathbb{C} \\mathbf{1}$\n(take the celebrated Choi map\n\\cite{choi1977extremal});\nit is not that straightforward to provide an example of\nan extremal bistochastic map which has\n$K_{S}= \\mathbb{C} P_{12} \\oplus \\mathbb{C} P_{3}$.\n\nLet then $S\\!: M_{3} \\rightarrow M_{3}$ be a linear map defined as\n\\begin{equation}\n\\label{eq:DefinitionOfS}\nS(A) \\:=\\: \\begin{pmatrix}\n        \\frac{1}{2}(a_{11} + a_{22}) & 0 & \\frac{1}{\\sqrt{2}} a_{13} \\\\\n        0 & \\frac{1}{2}(a_{11} + a_{22}) & \\frac{1}{\\sqrt{2}} a_{32} \\\\\n        \\frac{1}{\\sqrt{2}} a_{31} & \\frac{1}{\\sqrt{2}} a_{23} & a_{33}\n        \\end{pmatrix},\n\\end{equation}\nfor\n$A = \\left( a_{ij} \\right)_{i,j=1}^{3}\n        \\in M_{3}$.\nIf we use the notation\n$A = \\left( \\begin{smallmatrix}\n    B & \\vec{u} \\\\\n    \\vec{w}^{t} & z\n    \\end{smallmatrix} \\right)$,\nfor $B \\in M_{2}$,\n$\\vec{u},\\vec{w} \\in \\mathbb{C}^{2}$ are column vectors,\nand $z \\in \\mathbb{C}$,\nthe map $S$ acts by\n\\begin{equation}\n    S(A) \\:=\\: S \\begin{pmatrix}\n    B & \\vec{u} \\\\\n    \\vec{w}^{t} & z\n    \\end{pmatrix} \\: = \\:\n    \\begin{pmatrix}\n        \\frac{1}{2} (\\text{Tr} B) \\, \\mathbf{1}_{2} &\n            \\frac{1}{\\sqrt{2}}(\\hat{P}_{1} \\vec{u} + \\hat{P}_{2} \\vec{w}) \\\\\n        \\frac{1}{\\sqrt{2}}(\\hat{P}_{1} \\vec{w} + \\hat{P}_{2} \\vec{u})^{t} & z\n    \\end{pmatrix},\n\\end{equation}\nwhere\n$\\hat{P}_{1} = \\left( \\begin{smallmatrix} 1 & 0 \\\\ 0 & 0 \\end{smallmatrix} \\right)$,\n$\\hat{P}_{2} = \\left( \\begin{smallmatrix} 0 & 0 \\\\ 0 & 1 \\end{smallmatrix} \\right)$,\nand $\\mathbf{1}_{2}$ is the identity matrix of $M_{2}$.\nProvided the next Lemma \\ref{lem:SIsExtremal} is true, \nthis example ends the proof.\n\\end{proof}\n\n\n\\begin{lemma}\n\\label{lem:SIsExtremal}\n$S$ is an bistochastic, extremal and atomic map.\n\\end{lemma}\n\n\\begin{proof}\nIn order to prove that $S$ is a positive map,\nit is enough to show that for any $\\eta \\in \\mathbb{C}^{3}\\backslash\\{0\\}$, \n$SP_{\\eta} \\geq 0$,\nwhere $P_{\\eta}$ is a rank-one operator,\n$P_{\\eta} = \\eta \\eta^{*}$.\nLet us then take\n$\\eta = (\\eta_{1}, \\eta_{2}, \\eta_{3}) = (\\vec{\\eta}, \\eta_{3})$,\n$\\vec{\\eta} = (\\eta_{1}, \\eta_{2}) \\in \\mathbb{C}^{2}\\backslash\\{0\\}$,\n$\\eta_{3} \\in \\mathbb{C}$.\nWe have then\n\\begin{multline}\n SP_{\\eta} \\:=\\:  S \\begin{pmatrix}\n    \\vec{\\eta} \\vec{\\eta}^{\\,*} & \\overline{\\eta}_{3} \\vec{\\eta} \\\\\n    \\eta_{3} \\vec{\\eta}^{\\,*}   & |\\eta_{3}|^{2}\n \\end{pmatrix} \\: = \\: \\\\\n = \\begin{pmatrix}\n  \\frac{||\\vec{\\eta}||^{2}}{2} \\mathbf{1}_{2} &\n        \\frac{1}{\\sqrt{2}} \\left ( \\overline{\\eta}_{3} \\hat{P}_{1} \\vec{\\eta} +\n          \\eta_{3} \\hat{P}_{2} \\overline{\\vec{\\eta}} \\right) \\\\\n\\frac{1}{\\sqrt{2}} \\left ( \\overline{\\eta}_{3} \\hat{P}_{1} \\vec{\\eta} +\n          \\eta_{3} \\hat{P}_{2} \\overline{\\vec{\\eta}} \\right)^{*} &\n        |\\eta_{3}|^{2}\n \\end{pmatrix}.\n\\end{multline}\nIf $\\eta_{3} = 0$, then of course $SP_{\\eta} \\geq 0$.\nIn the case when $\\eta_{3} \\neq 0$,\ntaking the Schur complement\n(see \\cite[Theorem 1.12, p.34]{zhang2006schur}),\nwe have that $SP_{\\eta} \\geq 0$, if and only if\n\\begin{equation}\n\\label{ieq:SchurForS}\n   \\left ( \\overline{\\eta}_{3} \\hat{P}_{1} \\vec{\\eta} +\n    \\eta_{3} \\hat{P}_{2} \\overline{\\vec{\\eta}} \\right)\n   \\left ( \\overline{\\eta}_{3} \\hat{P}_{1} \\vec{\\eta} +\n    \\eta_{3} \\hat{P}_{2} \\overline{\\vec{\\eta}} \\right)^{*} \n    \\: \\leq \\:\n        |\\eta_{3}|^{2} \\, ||\\vec{\\eta}||^{2} \\, \\mathbf{1}_{2},\n\\end{equation}\nbut it is easy to see that this inequality is fulfilled:\n\\begin{multline}\n   \\left ( \\overline{\\eta}_{3} \\hat{P}_{1} \\vec{\\eta} +\n    \\eta_{3} \\hat{P}_{2} \\overline{\\vec{\\eta}} \\right)\n   \\left ( \\overline{\\eta}_{3} \\hat{P}_{1} \\vec{\\eta} +\n    \\eta_{3} \\hat{P}_{2} \\overline{\\vec{\\eta}} \\right)^{*} \\: \\leq \\:\n|| \\overline{\\eta}_{3} \\hat{P}_{1} \\vec{\\eta} +\n    \\eta_{3} \\hat{P}_{2}\\overline{\\vec{\\eta}} ||^{2} \\, \\mathbf{1}_{2}\n    \\: = \\: \\\\\n\\left( || \\overline{\\eta}_{3} \\hat{P}_{1} \\vec{\\eta} ||^{2} +\n    || \\eta_{3} \\hat{P}_{2} \\overline{\\vec{\\eta}} ||^{2} \\right) \\, \\mathbf{1}_{2} \n    \\: = \\:\n|\\eta_{3}|^{2} \\, ||\\vec{\\eta}||^{2} \\, \\mathbf{1}_{2}.\n\\end{multline}\nThus, $S$ is a bistochastic map.\nWe also have\n$K_{S}= \\mathbb{C} P_{12} \\oplus \\mathbb{C} P_{3}$.\nIndeed,\none computes immediately that for $A \\in M_{3}$:\n\\begin{equation}\n\\lim \\limits_{k \\rightarrow \\infty} S^{k}(A) \\:=\\:\n\\frac{1}{2} (\\text{Tr} \\, P_{12} A )\\, P_{12} +\n    (\\text{Tr} \\, P_{3} A)\\, P_{3} \\, \\in K_{S}.\n\\end{equation}\nFrom that and from the definition \\eqref{def:definitionofK},\nfollows the particular form of the JB$^{*}$-algebra $K_{S}$.\n\nWe are going to show now that $S$ is extremal.\nLet $S_{0}: M_{3} \\rightarrow M_{3}$ be a positive map such that\n$0 \\leq S_{0} \\leq S$.\nWe have $S_{0}(P_{3}) \\leq S(P_{3}) = P_{3}$,\nand hence $S_{0}(P_{3}) = \\alpha P_{3}$ for some $0 \\leq \\alpha \\leq 1$.\nRemembering about the embedding \\eqref{RandomLabel:450031},\nwe want to show that $S_{0}(A) \\in M_{2} \\! \\subset \\! M_{3}$\nfor any $A \\in M_{2} \\! \\subset \\! M_{3}$.\nLet $B \\in M_{2}$ and suppose at first that $B \\geq 0$.\nThen\n\\begin{equation}\n\\label{eq:SMapsM2intoM2}\n 0 \\:\\leq\\: S_{0} \\begin{pmatrix}\n               B & \\vec{0} \\\\ \\vec{0}^{t} & 0\n              \\end{pmatrix} \\: = \\:\n \\begin{pmatrix}\n  \\hat{S}_{0}(B) & \\vec{u} \\\\ \\vec{w}^{t} & r\n \\end{pmatrix},\n\\end{equation}\nfor some vectors $\\vec{u}, \\vec{w} \\in \\mathbb{C}^{2}$ and $r \\geq 0$.\nThe map $\\hat{S}_{0}:B \\mapsto \\hat{S}_{0}(B) \\in M_{2}$ must be a positive\nmap of $M_{2}$ such that $\\hat{S}_{0}(B) \\leq \\frac{1}{2} (\\text{Tr} B) \\mathbf{1}_{2}$.\nOn the other hand,\n\\begin{equation}\n 0 \\: \\leq \\:\n \\begin{pmatrix}\n  \\hat{S}_{0}(B) & \\vec{u} \\\\ \\vec{w}^{t} & r\n \\end{pmatrix} \\: \\leq \\:\n            S \\begin{pmatrix}\n               B & \\vec{0} \\\\ \\vec{0}^{t} & 0\n              \\end{pmatrix} \\: = \\:\n \\begin{pmatrix}\n  \\frac{1}{2} (\\text{Tr} B) \\, \\mathbf{1}_{2} & \\vec{0} \\\\ \\vec{0}^{t} & 0\n \\end{pmatrix},\n\\end{equation}\nand hence $r=0$, $\\vec{u}=\\vec{w}=\\vec{0}$.\nBecause any matrix $B \\in M_{2}$ is a complex combination of four positive\nmatrices, we have that indeed $S_{0}(A) \\in M_{2} \\! \\subset \\! M_{3}$\nfor any $A \\in M_{2} \\! \\subset \\! M_{3}$.\n\n\nLet $\\{e_{i}\\}_{i=1}^{3}$ be the standard orthonormal basis of $\\mathbb{C}^{3}$\nand $\\{ E_{jk} \\}_{j,k=1}^{3}$ be the set of matrix units in $M_{3}$,\n$E_{jk} = e_{j} e_{k}^{*}$.\nWe show that for $i = 1,2,3$ and $j=1,2$;\n$\\langle e_{i}, S_{0}(E_{j3}) e_{i} \\rangle = 0$,\nand $\\langle e_{1}, S_{0}(E_{j3}) e_{2} \\rangle = \n    \\langle e_{2}, S_{0}(E_{j3}) e_{1} \\rangle = 0$.\nFix $i,j$, and take \n$X = |z_{1}|^{2} P_{j} + z_{1} \\overline{z_{2}} E_{j3} +\n\\overline{z_{1}} z_{2} E_{3j} + |z_{2}|^{2} P_{3}$,\nfor some $z_{1}, z_{2} \\in \\mathbb{C}$.\nIt is evident that $X \\geq 0$. \nHence, since $S_{0}(E_{j3}) = S_{0}(E_{3j})^{*}$,\n\\begin{equation}\n0 \\: \\leq \\: \\langle e_{i}, S_{0}(X) e_{i} \\rangle \\: = \\:\n|z_{1}|^{2} \\, \\delta_{ij} +\n2 \\, \\text{Re} \\, z_{1} \\overline{z_{2}} \\,\n    \\langle e_{i}, S_{0}(E_{j3}) e_{i} \\rangle +\n|z_{2}|^{2} \\, \\delta_{i3},\n\\end{equation}\nwhere $\\delta_{ij}$ is the Kronecker delta.\nBecause the above equation is true for every $z_{1}, z_{2} \\in \\mathbb{C}$,\nand $j \\neq 3$,\nit follows that necessarily \n$\\langle e_{i}, S_{0}(E_{j3}) e_{i} \\rangle =0$. \nNow, since $X \\geq 0$, then so is $Y = P_{12} \\, S_{0}(X) P_{12}$.\nFrom what has been just shown, \n$Y_{jj} = |z_{1}|^{2}$,\nbut the second diagonal element of $Y$ equals 0, and\nhence $Y_{12} = Y_{21} = 0$,\nwhich means that\n$\\langle e_{1}, S_{0}(E_{j3}) e_{2} \\rangle\n    = \\langle e_{2}, S_{0}(E_{j3}) e_{1} \\rangle = 0$.\n\nTherefore, we can write that for any\n$A  =   \\left( \\begin{smallmatrix}\n    B & \\vec{u} \\\\\n    \\vec{w}^{t} & z\n    \\end{smallmatrix} \\right) \\in M_{3}$,\n\\begin{equation}\n    S_{0}(A) \\:=\\: S_{0} \\begin{pmatrix}\n    B & \\vec{u} \\\\\n    \\vec{w}^{t} & z\n    \\end{pmatrix} \\: = \\:\n    \\begin{pmatrix}\n        \\hat{S}_{0}(B) & S_{1} \\vec{u} + S_{2} \\vec{w} \\\\\n        (\\overline{S}_{1} \\vec{w} + \\overline{S}_{2} \\vec{u})^{t} & \\alpha z\n    \\end{pmatrix},\n\\end{equation}\nand $S_{1}, S_{2} \\in M_{2}$, with matrix elements given by\n\\begin{equation}\n(S_{1})_{ij} = \\langle e_{i}, S(E_{j3}) e_{3} \\rangle, \\quad \\quad\n(S_{2})_{ij} = \\langle e_{i}, S(E_{3j}) e_{3} \\rangle.\n\\end{equation}\n\nSuppose now that $\\alpha = 0$.\nThen, since $S_{0} P_{\\eta} \\geq 0$ for every\n$\\eta \\in \\mathbb{C}^{3}\\backslash\\{0\\}$,\nwe have that $S_{1} = S_{2} = 0$.\nBecause \n$0 \\leq (S - S_{0}) P(1,1,1)$,\n\\begin{equation}\n0 \\: \\leq \\: \\hat{S}_{0} \\begin{pmatrix}\n    1 & 1 \\\\ 1 & 1\n    \\end{pmatrix} \\: \\leq \\:\n    \\mathbf{1}_{2} - \\frac{1}{2} \\begin{pmatrix}\n                1 & 1 \\\\ 1 & 1\n                \\end{pmatrix} \\: = \\:\n    \\frac{1}{2}\n    \\begin{pmatrix}\n    1 & -1 \\\\ -1 & 1\n    \\end{pmatrix},\n\\end{equation}\ni.e. for some $\\beta \\geq 0$, \n$\n\\hat{S}_{0} \\left( \\begin{smallmatrix}\n    1 & 1 \\\\ 1 & 1\n    \\end{smallmatrix} \\right) =\n    \\beta \\left(\n    \\begin{smallmatrix}\n    1 & -1 \\\\ -1 & 1\n    \\end{smallmatrix} \\right)\n$.\nRepeating the same calculation, but this time for $P(i,i,1)$,\nwe obtain that for some $\\beta' \\geq 0$, \n$\n\\hat{S}_{0} \\left( \\begin{smallmatrix}\n    1 & 1 \\\\ 1 & 1\n    \\end{smallmatrix} \\right) =\n    \\beta' \\left(\n    \\begin{smallmatrix}\n    1 & 1 \\\\ 1 & 1\n    \\end{smallmatrix} \\right)\n$,\nand so \n$\n\\hat{S}_{0} \\left( \\begin{smallmatrix}\n    1 & 1 \\\\ 1 & 1\n    \\end{smallmatrix} \\right) = 0\n$.\nSimilarly,\n$\n\\hat{S}_{0} \\left( \\begin{smallmatrix}\n    1 & -1 \\\\ -1 & 1\n    \\end{smallmatrix} \\right) = 0\n$, and hence\n$\\hat{S}_{0}(\\mathbf{1}_{2}) = 0$, i.e. $\\hat{S}_{0} = 0$.\nTherefore,  we can assume in the following that $\\alpha > 0$.\n\nNext, by direct computation, one proves that for any\n$\\vec{\\eta} \\in \\mathbb{C}^{2}$:\n\\begin{equation}\n \\label{eq:ZeroTrace}\n \\text{Tr} \\, P(-2\\vec{\\upsilon}, ||\\vec{\\eta}||^{2}) \\, S P(\\vec{\\eta},1)\n     \\:=\\: 0,\n\\end{equation}\nwhere $\\vec{\\upsilon} =\n \\frac{1}{\\sqrt{2}} \\left(\n  \\hat{P}_{1} \\vec{\\eta} + \\hat{P}_{2} \\overline{\\vec{\\eta}}\n \\right)$,\n$||\\vec{\\upsilon}||^{2} = \\tfrac{||\\vec{\\eta}||^{2}}{2}$.\nBecause $0 \\leq S_{0} \\leq S$, the eq.\n\\eqref{eq:ZeroTrace} holds also for $S_{0}$.\nWriting out the equation, and assuming from now on that\n$||\\vec{\\eta}|| = 1$,\nwe get\n\\begin{equation}\n \\label{eq:ZeroTraceExplicit}\n 4 \\, \\vec{\\upsilon}^{\\,*} \\hat{S}_{0}(\\vec{\\eta} \\vec{\\eta}^{\\,*}) \\vec{\\upsilon} -\n 4 \\, \\text{Re} \\, \\vec{\\upsilon}^{\\,*} \\vec{\\upsilon}_{0} + \\alpha \\: = \\: 0,\n\\end{equation}\nwhere $\\vec{\\upsilon_{0}} = S_{1} \\vec{\\eta} + S_{2} \\overline{\\vec{\\eta}}$.\nTo keep the notation simple,\nwe remember that $\\vec{\\upsilon}$ and $\\vec{\\upsilon}_{0}$ depend on $\\vec{\\eta}$,\nwithout signifying it explicitly.\n\nSince $S_{0} P(\\vec{\\eta},1)$ is a positive matrix, \nusing again the Schur complement,\n$\\vec{\\upsilon}_{0} \\vec{\\upsilon}_{0}^{\\,*} \\leq  \\alpha \\hat{S}_{0}(\\vec{\\eta} \\vec{\\eta}^{\\,*})$,\nand thus\n$|\\vec{\\upsilon}^{\\,*} \\vec{\\upsilon}_{0}|^{2} \\leq\n  \\alpha \\vec{\\upsilon}^{\\,*} \\hat{S}_{0}(\\vec{\\eta} \\vec{\\eta}^{\\,*}) \\vec{\\upsilon}$.\nTherefore\n\\begin{equation}\n4 \\left( \\text{Im} \\, \\vec{\\upsilon}^{\\,*} \\vec{\\upsilon}_{0} \\right)^{2} +\n\\left( 2 \\, \\text{Re} \\, \\vec{\\upsilon}^{\\,*} \\vec{\\upsilon}_{0} - \\alpha \\right)^{2} \n \\: \\leq \\:\n4 \\alpha \\, \\vec{\\upsilon}^{\\,*} \\hat{S}_{0}(\\vec{\\eta} \\vec{\\eta}^{\\,*}) \\vec{\\upsilon}\n    - 4 \\alpha \\, \\text{Re} \\, \\vec{\\upsilon}^{\\,*} \\vec{\\upsilon}_{0} + \\alpha^{2}  = 0,\n\\end{equation}\ni.e. $\\vec{\\upsilon}^{\\,*} \\vec{\\upsilon}_{0} = \\frac{\\alpha}{2}$.\nSubstituting both $\\vec{\\upsilon}$ and $\\vec{\\upsilon}_{0}$,\nwe obtain:\n\\begin{equation}\n\\label{eq:ComplicatedForEtaPlus}\n\\vec{\\eta}^{\\,*} \\left( \\hat{P}_{1} S_{1} + S_{2}^{t} \\hat{P}_{2} \\right) \\vec{\\eta}\n    + \\vec{\\eta}^{\\,*} \\hat{P}_{1} S_{2} \\overline{\\vec{\\eta}} \n    + \\vec{\\eta}^{\\,t} \\hat{P}_{2} S_{1} \\vec{\\eta} \\: = \\: \\frac{\\alpha}{\\sqrt{2}}.\n\\end{equation}\nBecause this holds true for any $\\vec{\\eta} \\in \\mathbb{C}^{2}$,\nwe can repeat the whole argument,\nbut this time changing $\\vec{\\eta} \\mapsto i \\vec{\\eta}$,\nto obtain:\n\\begin{equation}\n\\label{eq:ComplicatedForEtaMinus}\n\\vec{\\eta}^{\\,*} \\left( \\hat{P}_{1} S_{1} + S_{2}^{t} \\hat{P}_{2} \\right) \\vec{\\eta}\n    - \\vec{\\eta}^{\\,*} \\hat{P}_{1} S_{2} \\overline{\\vec{\\eta}}\n    - \\vec{\\eta}^{\\,t} \\hat{P}_{2} S_{1} \\vec{\\eta} \\: = \\: \\frac{\\alpha}{\\sqrt{2}}.\n\\end{equation}\nAdding together \\eqref{eq:ComplicatedForEtaPlus} and \\eqref{eq:ComplicatedForEtaMinus},\nwe have\n$\n\\vec{\\eta}^{\\,*} \\left( \\hat{P}_{1} S_{1} + S_{2}^{t} \\hat{P}_{2} \\right) \\vec{\\eta} = \n    \\frac{\\alpha}{\\sqrt{2}},\n$\nfor any $\\vec{\\eta}$. \nHence \n\\begin{equation}\n\\label{eq:S1PlusS2EqualsOne}\n\\hat{P}_{1} S_{1} + S_{2}^{t} \\hat{P}_{2} \\: = \\:\n     \\frac{\\alpha}{\\sqrt{2}} \\mathbf{1}_{2}.\n\\end{equation}\nSubtracting \\eqref{eq:ComplicatedForEtaMinus} from \\eqref{eq:ComplicatedForEtaPlus},\nwe get\n\\begin{equation}\n    \\vec{\\eta}^{\\,*} \\hat{P}_{1} S_{2} \\overline{\\vec{\\eta}} \n    + \\vec{\\eta}^{\\,t} \\hat{P}_{2} S_{1} \\vec{\\eta} \\: = \\: 0.\n\\end{equation}\nLet  $\\vec{\\eta}$ be each of the following vectors:\n$(1,0)$, $(0,1)$,\n$(i,0)$, $(0,i)$,\n$(\\frac{1}{\\sqrt{2}},\\frac{1}{\\sqrt{2}})$, \n$(\\frac{1}{\\sqrt{2}},\\frac{i}{\\sqrt{2}})$,\nthen we can see that $\\hat{P}_{1} S_{2} = \\hat{P}_{2} S_{1} = 0$.\nCombining this with  \\eqref{eq:S1PlusS2EqualsOne}, \nwe obtain\n\\begin{equation}\nS_{1} = \\begin{pmatrix}\n    \\frac{\\alpha}{\\sqrt{2}} & z_{0} \\\\ 0 & 0 \n\\end{pmatrix}, \\quad\nS_{2} = \\begin{pmatrix}\n     0 & 0 \\\\ - z_{0} & \\frac{\\alpha}{\\sqrt{2}} \n\\end{pmatrix}, \\quad\nz_{0} \\in \\mathbb{C}.\n\\end{equation}\n\nPutting $\\vec{\\upsilon}^{\\,*} \\vec{\\upsilon}_{0} = \\frac{\\alpha}{2}$\ninto \\eqref{eq:ZeroTraceExplicit}, we get that\n$\n\\vec{\\upsilon}^{\\,*} \\hat{S}_{0}(\\vec{\\eta} \\vec{\\eta}^{\\,*}) \\vec{\\upsilon} = \n\\frac{\\alpha}{4}\n$.\nHence \n\\begin{equation}\n \\vec{\\upsilon}^{\\,*} \\left(\n    \\alpha \\, \\hat{S}_{0}(\\vec{\\eta} \\vec{\\eta}^{\\,*}) -\\vec{\\upsilon}_{0} \\vec{\\upsilon}_{0}^{\\,*}\n  \\right) \\vec{\\upsilon} \\: = \\: 0,\n\\end{equation}\nand since \n$\\vec{\\upsilon}_{0} \\vec{\\upsilon}_{0}^{\\,*} \\leq  \\alpha \\hat{S}_{0}(\\vec{\\eta} \\vec{\\eta}^{\\,*})$,\nit must be that\n$ \\alpha \\, \\hat{S}_{0}(\\vec{\\eta} \\vec{\\eta}^{\\,*}) \\vec{\\upsilon} =\n\\left( \\vec{\\upsilon}_{0}^{\\,*} \\vec{\\upsilon} \\right)  \\vec{\\upsilon}_{0}$,\nor simply\n$ \\hat{S}_{0}(\\vec{\\eta} \\vec{\\eta}^{\\,*}) \\vec{\\upsilon} = \\frac{1}{2} \\vec{\\upsilon}_{0}$.\nAgain, \nwe can repeat the whole argument,\nchanging $\\vec{\\eta} \\mapsto i \\vec{\\eta}$,\nadding the obtained result to and subtracting from the previous one, \nand we arrive at:\n\\begin{subequations}\n    \\begin{align}\n\\label{eq:SZeroIsAlmostOneA}\n\\eta_{1} \\, \\hat{S}_{0}(\\vec{\\eta} \\vec{\\eta}^{\\,*}) \\vec{e}_{1} \\: = \\: \n   \\left( \\frac{\\alpha}{2} \\eta_{1} + \\frac{\\sqrt{2}}{2} z_{0} \\eta_{2} \\right) \\, \\vec{e}_{1}, \\\\\n\\label{eq:SZeroIsAlmostOneB}\n\\overline{\\eta}_{2} \\, \\hat{S}_{0}(\\vec{\\eta} \\vec{\\eta}^{\\,*}) \\vec{e}_{2} \\: = \\: \n   \\left(- \\frac{\\sqrt{2}}{2} z_{0} \\overline{\\eta}_{1} + \\frac{\\alpha}{2} \\overline{\\eta}_{2} \\right) \n       \\, \\vec{e}_{2},\n    \\end{align}\n\\end{subequations}\nwhere $\\vec{\\eta} = (\\eta_{1}, \\eta_{2})$, and \n$\\vec{e}_{1} = (1,0), \\vec{e}_{2} = (0,1) \\in \\mathbb{C}^{2}$.\nTaking e.g. \\eqref{eq:SZeroIsAlmostOneA}\nand multiplying it by $\\overline{\\eta}_{1} \\vec{e}_{1}^{\\,*}$,\nwe have\n\\begin{equation}\n0 \\: \\leq \\:\n |\\eta_{1}|^{2} \\, \\vec{e}_{1}^{\\,*} \\, \\hat{S}_{0}(\\vec{\\eta} \\vec{\\eta}^{\\,*}) \\vec{e}_{1} \n \\: = \\: \n\\frac{\\alpha}{2} |\\eta_{1}|^{2} + \\frac{\\sqrt{2}}{2} z_{0} \\overline{\\eta}_{1} \\eta_{2},\n\\end{equation}\nfor every $\\vec{\\eta} \\in \\mathbb{C}^{2}$, $||\\vec{\\eta}|| =1$. \nTherefore $z_{0} = 0$, and \n$S_{1} = \\frac{\\alpha}{2} \\hat{P}_{1}$,\n$S_{2} = \\frac{\\alpha}{2} \\hat{P}_{2}$.\nAs a consequence of \n\\eqref{eq:SZeroIsAlmostOneA} and \\eqref{eq:SZeroIsAlmostOneB},\n$\\hat{S}_{0} (\\vec{\\eta} \\vec{\\eta}^{\\,*}) = \\frac{\\alpha}{2} \\mathbf{1}_{2}$\nfor every $\\vec{\\eta}$ such that $\\eta_{1} \\neq 0$ and $\\eta_{2} \\neq 0$.\nFor $0 \\!<\\!\\epsilon \\!<\\! 1$,\ntake $\\vec{\\eta}_{\\epsilon} = (\\sqrt{1 - \\epsilon^{2}}, \\epsilon)$.\nThen $\\hat{S}_{0} (\\hat{P}_{1}) = \n\\lim_{\\epsilon \\rightarrow 0} \\hat{S}_{0}\n    (\\vec{\\eta}_{\\epsilon} \\vec{\\eta}_{\\epsilon}^{\\,*}) =\n\\frac{\\alpha}{2} \\mathbf{1}_{2}$. \nSimilarly,\n$\\hat{S}_{0} (\\hat{P}_{2}) = \\frac{\\alpha}{2} \\mathbf{1}_{2}$,\nwhich results in \n$\\hat{S}_{0} (\\vec{\\eta} \\vec{\\eta}^{\\,*}) = \\frac{\\alpha}{2} \\mathbf{1}_{2}$\nfor every $\\vec{\\eta} \\in \\mathbb{C}^{2}$,\n$||\\vec{\\eta}|| = 1$.\nThis is sufficient to say that \n$\\hat{S}_{0}(B) = \\frac{\\alpha}{2} (\\text{Tr} B) \\mathbf{1}_{2}$\nfor any $B \\in M_{2}$.\nWe have shown that for an arbitrary positive map such that\n$0 \\leq S_{0} \\leq S$, \n$S_{0} = \\alpha S$ for $0 \\leq \\alpha \\leq 1$,\nwhich means that $S$ is an extremal positive map of $M_{3}$.\n\nIt is of interest to note that $S$ is not 2-positive.\nIndeed,\nwe can prove even more and say that \nthe map $S$ does not fulfil the Kadison-Schwarz inequality \nfor any matrix $B \\in M_{3}$\n(see Prop.\\,4.1 of \\cite{choi1980some}).\nTake the matrix\n$B = P_{12} + E_{32}$.\nThen it is easy to verify that \n$S(B^{*} B) - S(B)^{*} S(B)$\nis not positive.\nObviously, the map $S$ is\nnot 2-\\emph{co}positive either:\nto see this, take $B = P_{12} + E_{31}$.\nThat, together with the fact that $S$ is extremal,\nmakes the map atomic, and ends the proof.\n\\end{proof}\n\n\\begin{remark*}\nIn order to prove extremality of $S$,\nwe showed that $S_{0} = \\alpha S$,\nfor every $0 \\leq S_{0} \\leq S$.\nBut a only weaker assumption is in fact needed.\nIndeed, let us assume that $S_{0} \\in \\mathcal{P}(M_{3})$ and\n$\\text{Tr} P_{\\xi} \\, S_{0}(P_{\\eta}) = 0$,\nfor every $\\mathbb{C}^{3} \\ni \\xi,\\eta \\neq 0$\nsuch that $\\text{Tr} P_{\\xi} \\, S(P_{\\eta}) = 0$.\nThen $\\text{Tr} P_{12} \\, S_{0}(P_{3}) = 0$ and\n$\\text{Tr} P_{3} \\, S_{0}(P_{12}) = 0$.\nBecause $S_{0}$ is positive, so $S_{0}(P_{3}) = \\alpha P_{3}$\nand $S_{0}(P_{12}) \\in M_{2} \\! \\subset \\! M_{3}$.\nThen the rest of the proof goes exactly the same as in \nLemma \\ref{lem:SIsExtremal}, \nbeginning with \\eqref{eq:SMapsM2intoM2} onward.\nThis proofs that the map $S$\nis not only extremal, but also \\emph{exposed}.\n\\end{remark*}\n\nFor the map $S$ specified in \\eqref{eq:DefinitionOfS}, we have\n$K_{S}= \\mathbb{C} P_{12} \\oplus \\mathbb{C} P_{3}$.\nTo the best of the authors' knowledge,\nall the examples of the extremal maps of $M_{3}$\nthat are not completely or co-completely positive,\nwhich have been so far specified in the literature,\nhave $K_{S} = \\mathbb{C} \\, \\mathbf{1}$.\nThe map $S$ would be the first one\nwith a two-dimensional commutative stable algebra.\n\n\\vspace{0.5cm}\n\nGiven a positive map $S: M_{n} \\rightarrow M_{n}$,\nthe entanglement witness associated with $S$ is a matrix $W_{S}$\nof the tensor matrix algebra $M_{n^{2}} = M_{n} \\! \\otimes \\! M_{n}$,\ndefined by\n\\begin{equation}\n\\label{def:entanglement-witness}\n    W_{S} = \\sum \\limits_{i,j =1}^{n} E_{ij} \\otimes S(E_{ij}),\n\\end{equation}\nwhere $\\{ E_{ij}\\}_{i,j=1}^{n}$ are standard matrix units.\nThe theorem by Choi and Jamiołkowski \\cite{choi1975completely,jamiolkowski1974effective}\nstates that the matrix $W_{S}$ is a positive element of $M_{n^{2}}$,\nif and only if $S$ is completely positive.\nTherefore, for a positive, non-completely positive map $S$\nthere is at least one density matrix $\\rho \\in M_{n^{2}}$\nsuch that $\\text{Tr}\\, W_{S} \\rho < 0$.\nThis density matrix cannot be separable \\cite{werner1989quantum},\nand hence we say that the entanglement witness \\emph{detects} the\nentangled state $\\rho$. \n\nIt would be of interest to provide the explicit form of the entanglement\nwitness associated with the map $S$ of eq. \\eqref{eq:DefinitionOfS},\nand the family of states on the composite quantum system space\n$M_{9} = M_{3} \\! \\otimes \\! M_{3}$, detected by $S$.\nIt is easy to see, that in this case:\n\\begin{equation}\n\\label{WS-C}\n W_S =  \\left( \\begin{array}{ccc|ccc|ccc}\n \\frac{1}{2} &  \\cdot& \\cdot& \\cdot& \\cdot& \\cdot& \\cdot& \\cdot& \\frac{1}{\\sqrt{2}} \\\\\n \\cdot& \\frac{1}{2} &\\cdot& \\cdot& \\cdot& \\cdot& \\cdot& \\cdot& \\cdot\\\\\n \\cdot& \\cdot& \\cdot & \\cdot& \\cdot& \\cdot& \\cdot& \\cdot& \\cdot  \\\\ \\hline\n \\cdot& \\cdot& \\cdot& \\frac{1}{2} & \\cdot& \\cdot& \\cdot& \\cdot&  \\cdot \\\\\n \\cdot& \\cdot& \\cdot& \\cdot& \\frac{1}{2} & \\cdot& \\cdot& \\cdot&  \\cdot \\\\\n \\cdot& \\cdot& \\cdot& \\cdot& \\cdot& \\cdot& \\cdot & \\frac{1}{\\sqrt{2}}& \\cdot  \\\\ \\hline\n \\cdot& \\cdot& \\cdot & \\cdot& \\cdot& \\cdot& \\cdot& \\cdot& \\cdot  \\\\ \n \\cdot & \\cdot& \\cdot& \\cdot& \\cdot& \\frac{1}{\\sqrt{2}}& \\cdot& \\cdot& \\cdot \\\\\n \\frac{1}{\\sqrt{2}}& \\cdot& \\cdot& \\cdot& \\cdot & \\cdot& \\cdot& \\cdot& 1\n  \\end{array} \\right),\n\\end{equation}\nwhere dots mean matrix elements equal to zero.\n$W_{S}$ is not a positive matrix of $M_{9} = M_{3} \\! \\otimes \\! M_{3}$.\nLet $U \\in \\text{U}(9)$ be a unitary matrix such that\n$U^{*} W_{S} U = W_{S}^{(2)} \\oplus W_{S}^{(7)}$,\nwhere\n\\begin{equation}\n\\label{WS-DirectSum}\n W_{S}^{(2)} = \\left(\\begin{array}{cc}\n    0 & \\frac{1}{\\sqrt{2}}  \\\\ \\frac{1}{\\sqrt{2}}  & 0\n  \\end{array}\\right) \\in M_{2}, \\quad\n W_S^{(7)}\\ = \\  \\left( \\begin{array}{ccccccc}\n \\frac{1}{2} &  \\cdot& \\cdot& \\cdot& \\cdot& \\cdot& \\frac{1}{\\sqrt{2}} \\\\\n \\cdot& \\frac{1}{2} &\\cdot& \\cdot& \\cdot& \\cdot& \\cdot\\\\\n \\cdot& \\cdot& \\cdot & \\cdot& \\cdot& \\cdot& \\cdot \\\\ \n \\cdot& \\cdot& \\cdot& \\frac{1}{2} & \\cdot&  \\cdot& \\cdot \\\\\n \\cdot& \\cdot& \\cdot& \\cdot& \\frac{1}{2} & \\cdot& \\cdot \\\\\n \\cdot& \\cdot& \\cdot & \\cdot& \\cdot& \\cdot& \\cdot  \\\\ \n \\frac{1}{\\sqrt{2}}& \\cdot& \\cdot& \\cdot& \\cdot& \\cdot& 1\n  \\end{array} \\right) \\in M_{7}.\n\\end{equation}\nIt is evident that $W_{S}^{(7)} \\geq 0$. \nLet also $\\vec{v}$ be one of the eigenvectors of $W_{S}^{(2)}$: \n$\\vec{v} = \\frac{1}{\\sqrt{2}} (1,-1)^{t} \\in \\mathbb{C}^{2}$,\n$W_{S}^{(2)} \\vec{v} = - \\frac{1}{\\sqrt{2}} \\vec{v}$, and\n$P_{\\vec{v}} = \\vec{v} \\vec{v}^{*}$\nbe the orthogonal projection onto the space spanned by $\\vec{v}$.\nWe define\n$\\rho = \\frac{1}{2} U ( P_{\\vec{v}} \\oplus \\rho_{0} ) U^{*}$,\nfor a density matrix $\\rho_{0} \\in M_{7}$, \n$\\rho_{0} \\geq 0$, $\\text{Tr} \\rho_{0} = 1$, \nsuch that\n$\\text{Tr}\\, W_{S}^{(7)} \\rho_{0} < \\frac{1}{\\sqrt{2}}$.\nThen $\\rho \\geq 0$ and $\\text{Tr} \\rho = 1$,\ni.e. $\\rho$ is a density matrix.\nMoreover,\n\\begin{multline}\n\\label{RandomLabel:851252}\n    \\text{Tr}\\, W_{S} \\rho =\n\\frac{1}{2} \\text{Tr}\\, W_{S} U (P_{\\vec{v}} \\oplus \\rho_{0}) U^{*} =\n\\frac{1}{2} \\text{Tr}\\, (W_{S}^{(2)} \\oplus W_{S}^{(7)}) (P_{\\vec{v}} \\oplus \\rho_{0}) = \\\\ =\n\\frac{1}{2} \\text{Tr}\\, W_{S}^{(2)} P_{\\vec{v}} + \\frac{1}{2} \\text{Tr}\\, W_{S}^{(7)} \\rho_{0}\n< 0,\n\\end{multline}\nwhich means that $W_{S}$ detects the entangled state $\\rho$.\nIn particular, the state $\\rho$ given by\n\\begin{equation}\n\\label{PPTstate}\n \\rho =  \\frac{1}{7} \\left( \\begin{array}{ccc|ccc|ccc}\n 1 &  \\cdot& \\cdot& \\cdot& \\cdot& \\cdot& \\cdot& \\cdot& -1 \\\\\n \\cdot& \\cdot& \\cdot& \\cdot& \\cdot& \\cdot& \\cdot& \\cdot& \\cdot\\\\\n \\cdot& \\cdot& 1 & \\cdot& \\cdot& \\cdot& \\cdot& \\cdot& \\cdot  \\\\ \\hline\n \\cdot& \\cdot& \\cdot& \\cdot& \\cdot& \\cdot& \\cdot& \\cdot&  \\cdot \\\\\n \\cdot& \\cdot& \\cdot& \\cdot& 1 & \\cdot& \\cdot& \\cdot&  \\cdot \\\\\n \\cdot& \\cdot& \\cdot& \\cdot& \\cdot& 1 & \\cdot & -1 & \\cdot  \\\\ \\hline\n \\cdot& \\cdot& \\cdot & \\cdot& \\cdot& \\cdot& 1& \\cdot& \\cdot  \\\\ \n \\cdot & \\cdot& \\cdot& \\cdot& \\cdot& -1 & \\cdot& 1 & \\cdot \\\\\n -1 & \\cdot& \\cdot& \\cdot& \\cdot & \\cdot& \\cdot& \\cdot& 1\n  \\end{array} \\right)\n\\end{equation}\nis a PPT state, meaning that $(I \\otimes t)\\rho$ is still a density matrix,\nbut $\\text{Tr}\\, W_{S} \\rho = \\frac{2}{7} - \\frac{2\\sqrt{2}}{7} < 0$.\n\n\n\\paragraph{Acknowledgements.}\nThe authors would like to express their gratitude to Prof. Erling Størmer\nfor rightfully pointing out that the statement of Theorem \\ref{thm:FromESbook}\nis a direct consequence of Proposition 2.2.10 from\n\\cite{stormer2013positive}.\nMoreover, he helped us complete the list of all possible Jordan subalgebras\nof $M_{3}$, which has greatly simplified the proof \nof Theorem \\ref{thm:ExposedMaps}.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n%%% End of the paper %%%\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n% References\n\\bibliographystyle{abbrv}\n\\bibliography{./biblio}\n\n\n\\end{document}\n", "meta": {"hexsha": "b99f6302635dae7b30ba423b7ea80b57d6219759", "size": 46846, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chp/M3notes_eng.tex", "max_stars_repo_name": "gitmarek/phdthesis", "max_stars_repo_head_hexsha": "ab58eda980448ec2f577e77b555b19be42b59756", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chp/M3notes_eng.tex", "max_issues_repo_name": "gitmarek/phdthesis", "max_issues_repo_head_hexsha": "ab58eda980448ec2f577e77b555b19be42b59756", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chp/M3notes_eng.tex", "max_forks_repo_name": "gitmarek/phdthesis", "max_forks_repo_head_hexsha": "ab58eda980448ec2f577e77b555b19be42b59756", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0552396426, "max_line_length": 103, "alphanum_fraction": 0.6224224053, "num_tokens": 18102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3009288816037545}}
{"text": "% !TEX root=/home/tavant/these/manuscript/src/manuscript.tex\n\n\\section{Realistic heating and ionization}\n  \\label{sec-realistic_1D}\n  In the study of \\cref{{sec-1DPIC}}, the ionization and the heating mechanism are not self-consistent, but allowed us to obtain quickly a steady-state as in the simulations of \\cref{ch-1}.\n  We now study the impact of the wall absorption in a case of self-consistent heating and ionization.\n  The electrons are heated \"inductively\" with a radio-frequency (RF) electric field in the direction normal to the simulation grid \\cite{meige2006a, lucken2018, turner1993}.\n  The electrons are heated in the $y$ direction, and momentum is transferred to the $x$ and $z$ axis via electron-neutral collisions.\n  The heating electric field $\\vec{E_{rf}} = E_{rf} \\vec{e_y}$ is independent of $x$ in the simulation domain, its frequency is $13.56$\\,MHz, and its amplitude is adjusted in order to obtain the desired absorbed power $P_{abs} = < \\vec{J_e} \\cdot  \\vec{E_{rf}}>$.\n  \n\n\n  \\begin{table}[!htb]\n    \\ra{1.3}\n    \\centering\n    \\begin{tabular}{@{} r l l @{}}\n    \\toprule\n      Parameter & value & unit \\\\ \\midrule\n      Pressure & $0.1$ & mTorr\\\\\n      $P_{abs}$ & $0.25$ & W/m$^{-3}$\\\\\n      Length $L$&10&cm\\\\\n      \\bottomrule\n    \\end{tabular}\n    \\caption{Input parameters for the simulation using the self-consistent model.}\n    \\label{tab-PIC2}\n  \\end{table}\n\n  \\begin{figure}[!htbp]\n    \\center\n    \\includegraphics[width=0.9\\textwidth]{ICP_results.pdf}\n    \\caption{Results of the PIC simulation for the self-consistent model, using RF inductive heating.}\n    \\label{fig-icpresults}\n  \\end{figure}\n\n  \\Cref{fig-icpresults} presents the simulation results for the electron density, plasma potential and electron temperature using the parameters of \\Cref{tab-PIC2}.\n  We can see that the different variables (density, electron temperature and the plasma potential) are not much affected compared to the results of \\cref{sec-1DPIC}.\n\n  \\begin{figure}[!htbp]\n    \\centering\n    \\includegraphics[width=\\defaultwidth]{ICP_polyfit2.pdf}\n    \\caption{Estimation of the polytropic index in the sheath and in the whole domain in the PIC simulation using the self-consistent model.}\n    \\label{fig-icpfit}\n  \\end{figure}\n\n  \\Cref{fig-icpfit} presents the electron pressure as a function of the electron density measured in the simulation in log scale.\n  We see that the trend is not purely linear. Hence, the linear regression used in order to obtain the polytropic index is conducted twice\\string:\n  \\begin{itemize}\n    \\item In the whole domain\\string: $\\gamma=1.5$\n    \\item Only in the sheath\\string: $\\gamma=1.6$\n  \\end{itemize}\n  The linear relation conducted on the whole domain is less accurate than for the simulation result of \\cref{sec-1DPIC} ($R^2=0.992$).\n  However, we can see that the linear relation still describes quite well the electron evolution in the sheath.\n  The polytropic indexes obtained with the self-consistent model are close to the one of the simulation of \\cref{sec-1DPIC} at the same pressure.\n\n  \\begin{figure}[!htbp]\n    \\centering\n    \\includegraphics[width = 0.9\\textwidth]{FluidComparisonICP.pdf}\n    \\caption{Comparison of the electron temperature and plasma potential measured in the PIC simulation with the prediction of the fluid model with $\\gamma = 1.5$ (average index in the domain) and $\\gamma=1.6$ (index in the sheath).}\n    \\label{fig-comp2}\n  \\end{figure}\n\n  \\Cref{fig-comp2} shows the comparison of the electron temperature and the plasma potential in the PIC simulation using the self-consistent model with the prediction of the fluid model of \\cref{sec-fluid}.\n  We can see that the agreement between the PIC results and the fluid models is less satisfactory than in \\cref{fig-comp} but it is still significantly better than the isothermal model.\n  Hence, even with a self-consistent heating and ionization in the plasma, the polytropic model stands as a better model for the sheath and the pre-sheaths.\n", "meta": {"hexsha": "25ed1982043f4d9e6c0ad610bcd460d1aea60fe0", "size": 3983, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/Chapitre3/35bis-fluid_model_ionization.tex", "max_stars_repo_name": "antoinetavant/PhD_thesis_manuscript", "max_stars_repo_head_hexsha": "1fdaf99356f75abc488edf1f30b5dd65f22bcdca", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Chapitre3/35bis-fluid_model_ionization.tex", "max_issues_repo_name": "antoinetavant/PhD_thesis_manuscript", "max_issues_repo_head_hexsha": "1fdaf99356f75abc488edf1f30b5dd65f22bcdca", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Chapitre3/35bis-fluid_model_ionization.tex", "max_forks_repo_name": "antoinetavant/PhD_thesis_manuscript", "max_forks_repo_head_hexsha": "1fdaf99356f75abc488edf1f30b5dd65f22bcdca", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 61.2769230769, "max_line_length": 263, "alphanum_fraction": 0.7393924178, "num_tokens": 1083, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3009288816037545}}
{"text": "So far a number of algorithms for control, trajectory optimization, motion planning, perception, and localization/state estimation have been presented. Almost all of these instances share a common characteristic: they involve manipulation or observation of \\textit{continuous} variables. For example, motion planning and control algorithms manipulate the robot's physical state (i.e. position, velocity, orientation, configuration) which can take on a continuous range of values, and perception and localization tasks try to take (continuously valued) information from the environment and try to estimate the robot's physical state. \n\nHowever, for higher-level tasks it is often useful to represent the state of the robot or environment in terms of a discrete set of variables. For example, consider a robot whose task is to go from point A to point B, pick up a package, and then deliver it to point C. While the robot's physical (continuous) state is crucial for tasks such as controlling the robot to drive from A to B, it is also important to keep track of what portion of the overall plan that the robot is currently performing (is the robot currently traversing to B or C, has the package been successfully picked up, etc.). Additionally, it might be useful to keep track of other discrete valued states of the robot, such as if a sensor is functioning or not, or whether or not the robot is in the presence of a human (i.e. for safety).\nSimilar to dynamics/kinematics models for the robot's (continuous) physical state, \\textit{finite state machines}\\cite{KaelblingWhiteEtAl2011} are a useful framework for modeling discrete higher-level states of the robot and its environment.\n\n\\notessection{Finite State Machines}\nFinite state machines (FSMs) define a computational modeling framework for systems whose output depends on the entire history of their inputs, and where the number of possible states of the system is \\textit{finite}. This framework has been used in a wide variety of disciplines, including electrical engineering, linguistics, computer science, philosophy, biology, and more. FSMs can also be used in several different ways, including:\n\\begin{enumerate}\n    \\item {\\em to specify a desired program or behavior}, such as how a vending machine or ATM should function,\n    \\item {\\em to model behavior}, for example to analyze the behavior of a control system interacting with the environment,\n    \\item {\\em or for predicting behavior}, for example to predict what will happen in the future given some set of inputs to the system.\n\\end{enumerate}\n\nGenerally speaking, designing finite state machines for practical robotic systems can be extremely time consuming and challenging. In particular, choosing the appropriate set of states for a particular problem is required to ensure that the model is not overly complex, but the interactions and transitions between states can also be very hard to specify and can still lead to complex models. For example, consider the graphical representation of an example FSM for the popular open source flight software PX4 in Figure \\ref{fig:px4fsm}. Specifying the full behavior of the system can lead to a complex FSM, even if there are not very many states. In fact, this FSM is still under continuous development to improve the overall system behavior!\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.65\\textwidth]{tex/figs/ch19_figs/px4_state_machine.png}\n    \\caption{A graphical representation of a finite state machine example for the open source flight software PX4, \\texttt{https://px4.io/}. As can be seen, even for a relatively small number of states the FSM can become quite complex in order to model the full behavior of the system. Image retrieved from diydrones.com.}\n    \\label{fig:px4fsm}\n\\end{figure}\n\nMathematically, a finite state machine consists of:\n\\begin{enumerate}\n    \\item a \\textit{finite} set of states $S$,\n    \\item a set of inputs $I$,\n    \\item a set of outputs $O$,\n    \\item a next-state function $n(i_t, s_t) \\xrightarrow{} s_{t+1}$ that maps the input $i_t$ at time $t$ and current state $s_t$ to the next state $s_{t+1}$,\n    \\item an output function $o(i_t, s_t) \\xrightarrow{} o_t$,\n    \\item and an initial state $s_0$.\n\\end{enumerate}\nWhile FSMs can be defined through the mathematical notation above, it is often also useful to represent them graphically to get a more intuitive understanding of how the system will behave. In particular, the graph representation is defined with nodes of the graph representing each state in the set $S$. Each (directed) edge of the graph corresponds to a possible transition between states that is defined by a particular input. In other words, each directed edge is associated with a particular pair $(s, i)$. The outputs for a particular pair $(s,i)$ are also typically included along each directed edge. This is shown in more detail in Figure \\ref{fig:fsm}.\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=0.65\\textwidth]{tex/figs/ch19_figs/fsm.png}\n    \\caption{A graphical representation of a finite state machine with states $S = \\{s_0, s_1, s_2\\}$, inputs $I = \\{i_0,i_1,i_2\\}$ and outputs $O = \\{o_0, o_1\\}$. The directed edges correspond to the next-state functions and the output associated with each edge is defined by the output function. For example, in this FSM it can be seen that $n(i_1, s_0) \\xrightarrow{} s_1$ and $o(i_1, s_0) \\xrightarrow{} o_1$.}\n    \\label{fig:fsm}\n\\end{figure}\n\n\\begin{example}[Parking Gate Control] \\label{ex:parkinggate}\n\\theoremstyle{definition}\nConsider a parking gate control finite state machine where the goal is to raise the gate when a car arrives and then lower the gate when the car has passed. Assume sensors are available to tell if a car is at the gate and when the car has passed through the gate, and also the position of the gate. The control actions the gate can take are simply raising, lowering, or holding the gate position fixed. Technically, the position of the gate can vary continuously between the ``down'' and ``up'' positions, and the velocity can also vary continuously. However, in designing a finite state machine to define the overall logic/behavior for the parking gate, a higher-level abstraction of the set of gate states can be chosen as:\n\\begin{equation*}\nS = \\{\\text{down}, \\: \\text{raising}, \\:\\text{up},\\: \\text{lowering}\\}.\n\\end{equation*}\nThe set of inputs to the finite state machine come from the sensors, and can be chosen as:\n\\begin{equation*}\n\\begin{split}\nI = \\{&\\text{car waiting}, \\: \\text{no car waiting}, \\:\\text{car passed},\\: \\text{car not passed},\\: \\\\ &\\text{gate up}, \\: \\text{gate not up},\\: \\text{gate down},\\: \\text{gate not down} \\}.    \n\\end{split}\n\\end{equation*}\nFinally, the output of the finite state machine (defining the actions for the gate) are simply:\n\\begin{equation*}\nO = \\{\\text{lower}, \\: \\text{raise}, \\:\\text{hold}\\}.\n\\end{equation*}\n\nThe next-state function then defines the desired behavior for the parking gate. For example, suppose the current state $s_t = \\text{down}$ and the sensor measures that a car is waiting ($i_t = \\text{car waiting}$). Then, the desired behavior is to output the command $o_t = \\text{raise}$, and the next-state function would be:\n\\begin{equation*}\n    n(\\text{car waiting}, \\text{down}) \\xrightarrow{} \\text{raising}.\n\\end{equation*}\nSimilarly, suppose the gate was just raised for the car to pass such that $s_t = \\text{up}$, but that the sensor is giving input $i_t = \\text{car not passed}$. In this case the output would be $o_t = \\text{hold}$, and the next-state function would be:\n\\begin{equation*}\n    n(\\text{up}, \\text{car not passed}) \\xrightarrow{} \\text{up}.\n\\end{equation*}\nA graphical representation of the full car parking gate FSM is given in Figure \\ref{fig:parkinggate}.\n\\begin{figure}[ht]\n    \\centering\n    \\includegraphics[width=1\\textwidth]{tex/figs/ch19_figs/parkinggate_fsm.png}\n    \\caption{A graphical representation of the finite state machine for the parking gate controller discussed in Example \\ref{ex:parkinggate}.}\n    \\label{fig:parkinggate}\n\\end{figure}\n\\end{example}\n\n\\subsection{FSM Architectures}\nFinite state machines can become quite complex since for every new state added it is possible to define an exponentially increasing number of new transitions. Strategies for keeping the complexity of FSMs in check include analyzing for (and removing) redundant states, using hierarchical FSMs, and using compositions based on common patterns.\n\n\\subsubsection{Reducing Number of States}\nThere exist algorithms that can be used to identify and combine states in FSMs that would yield the same overall behavior. In particular, two states are equivalent if they have the same output and for all input combinations transition to the same or equivalent states.\n\nOne possible algorithm for reducing states in an FSM is as follows:\n\\begin{enumerate}\n    \\item Place all states into one set.\n    \\item Create a single partition based on the output behavior.\n    \\item Repeatedly partition further based on next state transitions until no further partitions is possible.\n\\end{enumerate}\nTo see this procedure in action, consider the following example:\n\\begin{example}[FSM State Reduction] \\label{ex:sequence}\n\\theoremstyle{definition}\nConsider a finite state machine that is used to detect the sequences 010 or 110. The FSM is shown in Table \\ref{tab:sequence}, where it can be seen that the states are the partial sequences $S = \\{0,1,00,01,10,11\\}$ and a reset state, the inputs are $I = \\{0,1\\}$, and the outputs are booleans $O = \\{\\text{True}, \\text{False} \\}$ for whether the sequence 010 or 110 has been created. For example, it can be seen that if the current partial sequence is 01 ($s_4$) and a 0 is input, the next state will be the reset state and the output will be True.\n\\begin{table}[ht]\n\\centering\n\\begin{tabular}{|l|\n>{\\columncolor[HTML]{C0C0C0}}l |l|\n>{\\columncolor[HTML]{C0C0C0}}l |l|}\n\\hline\nState, $s$ & $n(0,s)$ & $n(1,s)$ & $o(0,s)$ & $o(1,s)$ \\\\ \\hline\nReset      & 0        & 1        & False    & False    \\\\ \\hline\n0          & 00       & 01       & False    & False    \\\\ \\hline\n1          & 10       & 11       & False    & False    \\\\ \\hline\n00         & Reset    & Reset    & False    & False    \\\\ \\hline\n01         & Reset    & Reset    & True     & False    \\\\ \\hline\n10         & Reset    & Reset    & False    & False    \\\\ \\hline\n11         & Reset    & Reset    & True     & False    \\\\ \\hline\n\\end{tabular}\n\\caption{Finite state machine for a sequence detector that accepts digits 0 and 1 and outputs True if the sequences 010 or 110 is generated.}\n\\label{tab:sequence}\n\\end{table}\n\nNow, the FSM in Table \\ref{tab:sequence} can be simplified by removing redundant states! This is accomplished by first placing all of the states into a single set $\\{\\text{Reset}, 0, 1, 00, 01, 10, 11\\}$ and creating a partition based on the output behavior. In particular this will generate two sets:\n\\begin{equation*}\n\\begin{split}\n\\{\\text{Reset}, 0, 1, 00, 10\\}&: \\text{always leads to False output},\\\\\n\\{01,11\\}&: \\text{does not always lead to False output}.\n\\end{split}\n\\end{equation*}\nThese sets are then further partitioned based on the next-state function until no further partitions can be made. In the first step the set $\\{\\text{Reset}, 0, 1, 00, 10\\}$ is partitioned into:\n\\begin{equation*}\n\\begin{split}\n\\{\\text{Reset}, 00, 10\\}&: \\text{cannot transition to \\{01,11\\}},\\\\\n\\{0, 1\\} &: \\text{can transition to \\{01,11\\}}.\n\\end{split}\n\\end{equation*}\nand then $\\{\\text{Reset}, 00, 10\\}$ is partitioned as:\n\\begin{equation*}\n\\begin{split}\n\\{\\text{Reset}\\}&: \\text{can transition to \\{0, 1\\}},\\\\\n\\{00, 10\\}&: \\text{cannot transition to \\{0, 1\\}}.\n\\end{split}\n\\end{equation*}\nTherefore, instead of the original seven states (Reset, $0$, $1$, $00$, $01$, $10$, $11$) there are now only four ($\\{01,11\\}$, $\\{0, 1\\}$, Reset, $\\{00, 10\\}$).\nAn equivalent (same input/output behavior) but reduced finite state machine can now be defined, and is shown in Table \\ref{tab:sequence2}.\n\\begin{table}[ht]\n\\centering\n\\begin{tabular}{|l|\n>{\\columncolor[HTML]{C0C0C0}}l |l|\n>{\\columncolor[HTML]{C0C0C0}}l |l|}\n\\hline\nState, $s$                        & $n(0,s)$  & $n(1,s)$                          & $o(0,s)$ & $o(1,s)$ \\\\ \\hline\nReset                             & \\{0,1\\}   & \\{0,1\\}                           & False    & False    \\\\ \\hline\n\\{0,1\\}                           & \\{00,10\\} & \\cellcolor[HTML]{FFFFFF}\\{01,11\\} & False    & False    \\\\ \\hline\n\\cellcolor[HTML]{FFFFFF}\\{00,10\\} & Reset     & Reset                             & False    & False    \\\\ \\hline\n\\cellcolor[HTML]{FFFFFF}\\{01,11\\} & Reset     & Reset                             & True     & False    \\\\ \\hline\n\\end{tabular}\n\\caption{Reduced finite state machine for a sequence detector that accepts digits 0 and 1 and outputs True if the sequences 010 or 110 is generated.}\n\\label{tab:sequence2}\n\\end{table}\n\n\\subsubsection{Hierarchical FSMs}\nIn some cases there might be states that are not truly equivalent, but that might still be beneficial to group closely together. With this idea, the concepts of \\textit{super-states} (i.e. groups of closely related states) and \\textit{generalized transitions} (i.e. transitions between super-states) can be useful. This idea of creating super-states is analogous to graph clustering.\n\n\\subsubsection{Compositions}\nIndividual state machines can also be composed in a variety of ways depending on their input/output behavior, including \\textit{cascade} compositions, \\textit{parallel} compositions, and \\textit{feedback} compositions. Cascade compositions combine two FSMs in sequence where the output vocabulary of one matches the input vocabulary of the other. The new state of the combined machine is the concatenation of the states of the individual FSMs (see Figure \\ref{fig:cascade}). Parallel compositions run two FSMs side by side, using the same input. Both the state and output is then the concatenation of the two individual FSMs' state and output. Finally, feedback compositions use only a single FSM but only require a partial input and also reuse the output as input (requires the input and output vocabularies to be the same). \\begin{marginfigure}\n    \\centering\n    \\includegraphics[width=0.8\\textwidth]{tex/figs/ch19_figs/compositions.png}\n    \\caption{Cascade, parallel, and feedback compositions of finite state machines.}\n    \\label{fig:cascade}\n\\end{marginfigure}\n\n\n\n\\subsection{Implementation Details}\nThere are \\textit{numerous} ways that finite state machines could be implemented in practice. However, one common approach is to exploit Object Oriented Programming (OOP) by building the finite state machine as a class. In particular, the class would keep track of the state of the FSM in a class variable. The state update process could then occur through the use of if/else statements in an update class method, as well as the definition of the FSM output. An example implementation in Python of the parking gate controller FSM from Example \\ref{ex:parkinggate} is given below:\n\\begin{python}\nimport rospy as rp\nfrom std_msgs.msg import String\n\nclass ParkingGateFSM():\n    \"\"\"Simple FSM for parking gate control\"\"\"\n    def __init__(self):\n        rp.init_node('parking_gate', anonymous=True)\n        self.state = 'down'\n        self.cmd = rp.Publisher('/gate_cmd', String)\n        rp.Subscriber('/car_sensor', String, self.car_clbk)\n        rp.Subscriber('/gate_sensor', String, self.gate_clbk)\n\n    def car_clbk(self, data):\n        self.car_input = data\n\n    def gate_clbk(self, data):\n        self.gate_input = data\n\n    def run(self):\n        rate = rp.Rate(10) # 10 Hz\n        while not rp.is_shutdown():\n            if self.state == 'down':\n                if self.car_input == 'no_car_waiting':\n                    output = 'hold'\n                elif self.car_input == 'car_waiting':\n                    self.state = 'raising'\n                    output = 'raise'\n            elif self.state == 'raising':\n                if self.gate_input == 'gate_not_up':\n                    output = 'raise'\n                elif self.gate_input == 'gate_up':\n                    self.state = 'up'\n                    output = 'hold'\n            elif self.state == 'up':\n                if self.car_input == 'car_not_passed':\n                    output = 'hold'\n                elif self.car_input == 'car_passed':\n                    self.state = 'lowering'\n                    output = 'lower'\n            elif self.state == 'lowering':\n                if self.gate_input == 'gate_not_down':\n                    output = 'lower'\n                elif self.gate_input == 'gate_down':\n                    self.state = 'down'\n                    output = 'hold'\n            self.cmd.publish(output)\n            rate.sleep()\n\\end{python}\n\n\\subsection{Other Useful Tools}\nA useful tool for visualizing finite state machines in ROS is SMACH, which can be though of as an analogue to RViz. More information about SMACH and how it is used can be found on the ROS Wiki\\footnote{http://wiki.ros.org/smach}. \n\\end{example}", "meta": {"hexsha": "6b5d50ec36e0e0357e67cc1c5d6859c72ae234eb", "size": 17103, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/source/ch19.tex", "max_stars_repo_name": "StanfordASL/Principles-of-Robot-Autonomy", "max_stars_repo_head_hexsha": "852ce0fd1361d95576f72558d2c29d8610ced652", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-03-23T16:03:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T14:15:38.000Z", "max_issues_repo_path": "tex/source/ch19.tex", "max_issues_repo_name": "StanfordASL/Principles-of-Robot-Autonomy", "max_issues_repo_head_hexsha": "852ce0fd1361d95576f72558d2c29d8610ced652", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/source/ch19.tex", "max_forks_repo_name": "StanfordASL/Principles-of-Robot-Autonomy", "max_forks_repo_head_hexsha": "852ce0fd1361d95576f72558d2c29d8610ced652", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 79.9205607477, "max_line_length": 846, "alphanum_fraction": 0.7088814828, "num_tokens": 4324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832058771035, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.30092887333460744}}
{"text": "Our goal in this section is to build a flexible and computationally efficient\ntechnique for reliability analysis of electronic systems that are affected by\nprocess variation. The development is based on the general reliability model\n$R(\\cdot | \\vg)$ described in \\sref{reliability-model}, which is not aware of\nprocess variation yet. Note also that, in this section, we address not only\nprocess uncertainty but also aging uncertainty, which is introduced in\n\\sref{aging-variation}, since the latter can be more adequately mitigated when\nthe former is accounted for in reliability analysis.\n\n\\subsection{\\problemtitle}\n\nOur work in this context is motivated by the following two observations.\n\nFirst, as underscored throughout the thesis, temperature is the driving force of\nmany failure mechanisms. The most prominent examples include electromigration,\ntime-dependent dielectric breakdown, stress migration, and thermal cycling; the\ninterested reader is referred to \\cite{jedec2016} for an overview. All of these\nmechanisms have strong dependencies on temperature. At the same time,\ntemperature is closely related to process parameters---such as the effective\nchannel length and gate oxide thickness---and can vary dramatically when these\nparameters deviate from their nominal values. Despite these concerns, the\ncurrent state-of-the-art techniques for reliability analysis of electronic\nsystems lack a systematic treatment of process variation and, in particular, the\neffect of this variation on temperature, which is also the case in\n\\sref{reliability-model}.\n\nSecond, having established a reliability model $R(\\cdot | \\vg)$ of the system\nunder consideration, the major portion of the associated computation time is\nascribed to the evaluation of the parameterization \\vg rather than to the model\n\\perse, that is, for a given \\vg. For instance, \\vg often contains estimates of\nthe \\ac{MTTF} of each processing element for a range of stress levels. Thus, \\vg\ntypically involves computationally intensive simulations, including power\nanalysis paired with temperature analysis; see \\sref{reliability-model}.\n\nGuided by the aforementioned observations, we employ the \\ac{PC} decomposition\nin order to construct a lightweight surrogate for \\vg. It is worth emphasizing\nthat $R(\\cdot | \\vg)$ stays intact, which means that our approach does not\nimpose any restrictions on $R(\\cdot | \\vg)$. Hence, the designer can take\nadvantage of an arbitrary reliability model in a straightforward manner.\nNaturally, this also implies that modeling errors associated with the chosen\n$R(\\cdot | \\vg)$ can affect the quality of the results produced by our\ntechnique. Therefore, choosing an adequate reliability model for the problem at\nhand is the designer's responsibility.\n\n\\begin{remark} \\rlab{chaos-nested-uncertainty}\nIt is important to realize that there are two levels of probabilistic modeling\nhere. First, $R(\\cdot | \\vg)$ \\perse is a probabilistic model describing the\nlifetime \\life of the system. Second, the parameterization \\vg is another\nprobabilistic model characterizing the impact of uncertainty due to process\nvariation on the reliability model. Therefore, the overall model can be thought\nof as a probability distribution over probability distributions. Given an\noutcome of the fabrication process and thus \\vg, the system's lifetime remains\nrandom.\n\\end{remark}\n\nTo conclude, the quantity of interest \\g, which is an output of Stage~1 in\n\\fref{chaos-overview}, is the parameters \\vg of the reliability model under\nconsideration.\n\n\\subsection{Surrogate Construction}\n\nSimilarly to \\sref{chaos-dynamic-steady-analysis}, Stage~3 and Stage~4 of the\nframework require no particular attention in this section except for noting that\n\\rref{chaos-multidimensional-output} should be taken into consideration if the\nparameterization \\vg has multiple entries.\n\n\\conclusioncut\nIn conclusion, the proposed approach to reliability analysis is founded on the\nbasis of state-of-the-art reliability models, and it enriches their modeling\ncapabilities by seamlessly incorporating the deleterious impact of process\nvariation. In particular, the technique allows for a straightforward propagation\nof uncertainty from process parameters through temperature to the lifetime of\nthe system, which is an important application, since temperature is the driving\nforce of many failure mechanisms. In contrast to the straightforward use of\n\\ac{MC} sampling, the lightweight surrogates that we construct make the\nsubsequent analysis highly efficient from a computational perspective.\n", "meta": {"hexsha": "5f1d35735de76f3cbd40eba073bef443ffb3645d", "size": 4553, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "include/uncertainty/process/development/reliability-analysis.tex", "max_stars_repo_name": "IvanUkhov/thesis", "max_stars_repo_head_hexsha": "95a7e2ee7664b94156906322610555e36e53cfe0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/uncertainty/process/development/reliability-analysis.tex", "max_issues_repo_name": "IvanUkhov/thesis", "max_issues_repo_head_hexsha": "95a7e2ee7664b94156906322610555e36e53cfe0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/uncertainty/process/development/reliability-analysis.tex", "max_forks_repo_name": "IvanUkhov/thesis", "max_forks_repo_head_hexsha": "95a7e2ee7664b94156906322610555e36e53cfe0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.1298701299, "max_line_length": 80, "alphanum_fraction": 0.8141884472, "num_tokens": 949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.30091495364894943}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\subsection{Quantum noise}\n\n\\marginpar{Friday\\\\ 2021-12-3}\n\nThe measurement process can be thought of as ``counting photons'', \nalthough we cannot really determine their exact number,\nbut this is relevant since it means the measured intensity fluctuates with \\(\\sqrt{N}\\). \n\nIf \\(\\Delta N / \\Delta t\\) is constant (we get a fixed number of photons per unit time),\nwe have a \\textbf{Fock state} \\(\\hat{n} \\ket{n} = n \\ket{n}\\), an eigenvector of the \nphoton number operator \\(\\hat{n} = a ^\\dag a\\). \n\nIf this were the case, we would have no fluctuations in the readout. \nBut, besides the fact that photodetectors do not count photons, \nwe do not produce Fock states. \n\nIt is convenient to describe this process in the Heisenberg picture. \nIf we use it, the operators we use are all functions of \\(t\\) while the states are unchanged. \nThe state we will use will always just be the vacuum state \\(\\ket{0}\\). \n\nClassically, the output field will be given by a certain linear transformation of the \noutput field: \n%\n\\begin{align}\n\\vec{E} _{\\text{out}} (\\vec{x}, t) = \\mathscr{L} \\qty[ \\vec{E} _{\\text{in}}(\\vec{x}, t)]\n\\,,\n\\end{align}\n%\nbut this will also be what we do in our quantum-mechanical, Heisenberg-picture treatment. \n\nThe difficulty comes from the fact that there are actually many input fields: \nat various places, like the mirrors, we do not have ``nothing'' since there is \nalways at least the vacuum. \n\nThe transmissivity \\(\\tau \\) of a mirror is the ratio between the incoming and transmitted\nfield magnitudes. \nAll mirrors have a transmissivity \\(\\neq 0\\), so we always have a coupling to the vacuum \nstate on the other side of the mirror. \n\nIf there are losses, we cannot have a unitary process: so, \nthere will never be ``one-way'' losses, and a loss will always be associated \nwith an extraneous input from the environment. \n\nThe transmissivity and reflectivity satisfy \\(\\tau^2 + \\rho^2 = 1\\);\nthe transmissivity can be interpreted as a loss parameter, so if \\(\\tau = 0\\) \nall the field is reflected back into the system, but we will never have this condition. \n\nSo, if \\(A\\) is our input, some \\(\\tau A\\) is leaving our system; \nbecause of what we were saying above the field going back will not be just \\(\\rho A\\) but\ninstead \\(\\rho A + \\tau V\\), where \\(V\\) denotes the vacuum state on the other side of the port. \n\nA very important field is the one coming from the photodiode, which \nwill often look like a thermal state. \nHowever, its temperature will be very low compared to the laser light: \nthat is near-infrared, 100 to \\SI{1000}{THz}, corresponding to \\(\\gtrsim \\SI{700}{K}\\)\nof thermal temperature. \nSo, we can take it to be the vacuum. \n\nOnly about \\SI{.5}{\\percent} of the laser light at the beamsplitter reaches the \nphotodiode. \nTherefore, changing the field at the laser will have little effect on the diode; \non the other hand, \\SI{99.5}{\\percent} of the field from the photodiode will \ncome back to the laser. \n\nOnly in the eighties someone properly described an interferometer in QFT. \nBefore, people just used Poissonian statistics to calculate the quantum noise. \n\nThe first important insight is that we need to act on the field at the photodiode. \n\nLet us neglect the vector character of the field for simplicity; \nthe fields are all linearly polarized, and the quantum mechanics for the \nelectric and magnetic fields are the same.  \nThe field will be \n%\n\\begin{align}\n\\hat{E}(x, t) = \\sqrt{\\frac{2 \\pi \\hbar}{\\mathcal{A} c}} \\int_{- \\infty }^{\\infty } \\frac{ \\dd{\\omega }}{2 \\pi } \\sqrt{\\omega }\n\\qty( \\hat{a} (\\omega ) e^{- i \\omega (t - \\vec{x} \\cdot \\vec{\\epsilon} /c) } + \\hat{a} ^\\dag e^{i \\omega (t - \\vec{x} \\cdot \\vec{\\epsilon} /c)})\n\\,,\n\\end{align}\n%\nwhere we are fixing the propagation direction by fixing \\(k = \\omega / c\\); \nthe creation and annihilation operators will satisfy \n%\n\\begin{align}\n\\qty[ \\hat{a}(\\omega ),  \\hat{a} ^\\dag (\\omega ')] = 2 \\pi \\delta (\\omega - \\omega ')\n\\,.\n\\end{align}\n\nIf we apply the annihilation operator to the vacuum we get \\(\\hat{a} \\ket{0} = 0 \\ket{0}\\); \nsince the photon number operator is \\(\\hat{n} = \\hat{a} ^\\dag \\hat{a}\\)  we also have \n\\(\\hat{n}  \\ket{0} = 0 \\ket{0}\\). \n\nA \\textbf{coherent state} is an eigenstate of the annihilation operator: \\(\\hat{a} \\ket{\\alpha } = \\alpha \\ket{\\alpha }\\), \nwhere the eigenvalue \\(\\alpha \\) is a generic complex number. \nThis is ``close to classical'', it describes the output of a laser quite well, \nand it has Poissonian statistics. \n\nWhat is the distribution of the number of photons in a coherent state? \n%\n\\begin{align}\np(n) = \\abs{\\braket{n}{\\alpha }}^2 = e^{- \\abs{\\alpha }^2} \\frac{\\abs{\\alpha }^{2n}}{n!}\n\\,.\n\\end{align}\n\nThis is a Poissonian with average photon number \\(\\expval{n} = \\abs{\\alpha }^2\\). \n\nThe energy in the field is given by \\(E = \\hbar \\omega_0 n\\), so this value also corresponds\nto the mean energy in the field. \n\nIn the Heisenberg picture, one finds that the laser is mapping \\(\\hat{a} \\to \\hat{a} + \\alpha\\). \nIn a sense, all ``classical'' things are fixed complex numbers as opposed to operators. \n\nThe full operator is \\(\\hat{a} + h + \\alpha \\), where \\(\\hat{a}\\) describes the quantum fluctuations,\n\\(h\\) describes the GW signal, while \\(\\alpha \\)describes the laser. \n\nWe have not yet defined what is our canonical pair of observables. \nWe can write \n%\n\\begin{align}\n\\hat{E} (x, t) = \nE_1 (x, t) \\cos (\\omega_{0} t - kx)\n+\nE_2 (x, t) \\sin (\\omega_{0} t - kx)\n\\,.\n\\end{align}\n\nWhy are we picking a single frequency \\(\\omega_0 \\), while our field has many? \nIt is convenient since the laser frequency (\\(\\omega_0 \\)) is the main one, but there are also things fluctuating at all other frequencies. \nWe expect quantum fluctuations to have a white spectrum, so for those it is the same; however the sidebands from the GW signal will be close to \\(\\omega_0 \\). \n\nIn the photocurrent we measure, \\(I _{\\text{ph}} (t) = \\abs{E(x _{\\text{photodiode}}, t)}^2\\), we would have product terms between the laser frequency and the GW frequency. \n\nThe Fourier transform of the photocurrent allows us to compute a Power Spectral Density \\(S (I _{\\text{ph}}, \\omega )\\). \n\nThe Fourier transform looks like \n%\n\\begin{align}\n\\widetilde{I} _{\\text{ph}} (\\omega ) \\sim \\underbrace{\\abs{\\alpha }^2}_{\\omega_0 , \\omega_0 } + \\underbrace{\\Re(\\alpha \\hat{a})}_{\\omega_0 , \\omega  } +  \\underbrace{\\Re (\\alpha h)}_{\\omega_0 \\pm \\Omega , \\omega_0  } + \\underbrace{\\Re (h \\hat{a})}_{\\omega_0 \\pm \\Omega , \\omega}\n\\,.\n\\end{align}\n\nThe term which does not fluctuate, \\(\\abs{\\alpha }^2\\), is often called a DC component or DC offset: since we bandpass the photocurrent signal, any low-frequency component like that will vanish. \n\nThe noise term will oscillate at \\(\\omega_0 - \\omega = \\Omega \\); in the end the photocurrent we will actually have left after the bandpassing we get \n%\n\\begin{align}\n\\hat{I} _{\\text{ph}}(\\omega ) \\sim h(\\Omega ) + \\hat{a} (\\Omega )\n\\,.\n\\end{align}\n\nWhat we are basically doing is extracting out the fast-oscillating term, and we can focus on the slow, audio-band oscillations we care about. \n\nThe fluctuations in the photocurrent will contain the square moduli of the \\emph{quadratures} \\(E_1 \\) and \\(E_2 \\), which form a Heisenberg pair. \n\nHow do we actually manipulate the vacuum field at the photodiode? \nA squeezer is introduced, and it passes a polarizing beamsplitter, which is always either fully transmissive or fully reflective depending on the polarization of the light. \n\nThe unpolarized vacuum passes the polarizer in some fraction, but when it comes back it is fully reflected. \n\nThe squeezer emits little power, and some of it is in green light as opposed to infrared! \n\nThe power in the Fabry-Perot cavity is very high (\\(\\sim \\SI{200}{kW}\\)), but a small amount of squeezing power is enough to improve the sensitivity significantly. \n\n\\begin{figure}[ht]\n\\centering\n\\includegraphics[width=\\textwidth]{figures/husini}\n\\caption{Husini \\(Q\\)-function, \\(Q(\\beta ) = \\bra{\\beta } \\hat{\\rho} \\ket{\\beta } / \\pi \\), for squeezed vacuum states \\cite[eqs.\\ 3.112 and 7.82]{gerryIntroductoryQuantumOptics2004}. }\n\\label{fig:husini}\n\\end{figure}\n\n\\end{document}\n", "meta": {"hexsha": "f9f52bd87f1a477ffb7da820ee9172acab2fbea8", "size": 8187, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "phd_courses/experimental_gravitation_cosmology/dec03.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "phd_courses/experimental_gravitation_cosmology/dec03.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phd_courses/experimental_gravitation_cosmology/dec03.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 46.7828571429, "max_line_length": 278, "alphanum_fraction": 0.7096616587, "num_tokens": 2382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.3008393169684887}}
{"text": "\\documentstyle[11pt,reduce]{article}\n\\title{GROEBNER: A Package for Calculating Gr\\\"obner Bases, Version 3.0}\n\\date{}\n\\author{\nH. Melenk \\& W. Neun \\\\[0.05in]\nKonrad--Zuse--Zentrum \\\\\nf\\\"ur Informationstechnik Berlin \\\\\nTakustrasse 7 \\\\\nD--14195 Berlin--Dahlem \\\\\nGermany \\\\[0.05in]\nEmail:  melenk@zib.de \\\\[0.05in]\nand \\\\[0.05in]\nH.M. M\\\"oller \\\\[0.05in]\nFB Mathematik \\\\\nVogelpothsweg 87\\\\\nUniversit\\\"at Dortmund \\\\\nD--44221 Dortmund \\\\\nGermany\\\\[0.05in]\nEmail: moeller@math.uni--dortmund.de}\n\n\\begin{document}\n\\maketitle\n\n\\index{Gr\\\"obner Bases}\nGr\\\"obner bases are a valuable tool for solving problems in\nconnection with multivariate polynomials, such as solving systems of\nalgebraic equations and analyzing polynomial ideals. For a definition\nof Gr\\\"obner bases, a survey of possible applications and further\nreferences, see~\\cite{Buchberger:85}. Examples are given in \\cite{Boege:86},\nin \\cite{Buchberger:88} and also in the test file for this package.\n\n\\index{Groebner package} \\index{Buchberger's Algorithm}\nThe $groebner$ package calculates Gr\\\"obner bases using the\nBuchberger algorithm.  It can be used over a variety of different\ncoefficient domains, and for different variable and term orderings.\n\nThe current version of the package uses parts of a previous\nversion, written by  R. Gebauer, A.C. Hearn, H. Kredel and H. M.\nM\\\"oller. The algorithms implemented in the current version are\ndocumented in \\cite{Faugere:89}, \\cite{Gebauer:88},\n\\cite{Kredel:88a} and \\cite{Giovini:91}.\nThe operator $saturation$ has been implemented in July 2000 (Herbert Melenk).\n\\section{Background}\n\n\\subsection{Variables, Domains and Polynomials}\n\nThe various functions of the $groebner$ package manipulate\nequations and/or polynomials; equations are internally\ntransformed into  polynomials by forming the difference of\nleft-hand side and right-hand side, if equations are given.\n\nAll manipulations take place in a ring of polynomials in some\nvariables $x1, \\ldots , xn$ over a coefficient domain $d$:\n\\[ d [x1,\\ldots , xn], \\]\nwhere $d$ is a field or at least a ring without zero divisors.\nThe set of variables $x1,\\ldots ,xn$ can be given explicitly by the\nuser or it is extracted automatically from the\ninput expressions.\n\nAll \\REDUCE \\  kernels can play the role of ``variables'' in this context;\nexamples are\n\n%{\\small\n\\begin{verbatim}\nx y z22 sin(alpha) cos(alpha) c(1,2,3) c(1,3,2) farina4711\n\\end{verbatim}\n%}\n\nThe domain $d$ is the current \\REDUCE \\  domain with those kernels\nadjoined that are not members of the list of variables. So the\nelements of $d$ may be complicated polynomials themselves over\nkernels not in the list of variables; if, however, the variables are\nextracted automatically from the input expressions, $d$ is identical\nwith the current \\REDUCE \\  domain. It is useful to regard kernels not\nbeing members of the list of variables as ``parameters'', e.g.\n\\[\n\\begin{array}{c}\n a * x + (a - b) * y**2 \\;\\mbox{ with ``variables''}\\ \\{x,y\\} \\\\\n\\mbox{and ``parameters''  $\\;a\\;$ and $\\;b\\;$}\\;.\n\\end{array}\n\\]\n\nThe exponents of $groebner$ variables must be positive integers.\n\nA $groebner$ variable may not occur as a parameter (or part\nof a parameter) of a coefficient function. This condition is\ntested in the beginning of the $groebner$ calculation; if it is\nviolated, an error message occurs (with the variable name), and the\ncalculation is aborted. When the $groebner$ package is called by\n$solve$, the test is switched off internally.\n\nThe current version of the Buchberger algorithm has two internal\nmodes, a field mode and a ring mode. In the starting phase the\nalgorithm analyzes the domain type; if it recognizes $d$ as being a\nring it uses the ring mode, otherwise the field mode is needed.\nNormally field calculations occur only if all coefficients are numbers\nand if the current \\REDUCE \\  domain is a field (e.g. rational numbers,\nmodular numbers modulo a prime). In general, the ring mode is faster.\nWhen no specific\n\\REDUCE \\  domain is selected, the ring mode is used, even if the input\nformulas contain fractional coefficients: they are multiplied by their\ncommon denominators so that they become integer polynomials. Zeroes of the\ndenominators are included in the result list.\n\n\\subsection{Term Ordering} \\par\nIn the theory of Gr\\\"obner bases, the terms of polynomials are\nconsidered as ordered. Several order modes are available in\nthe current package, including the basic modes:\n\\index{lex ! term order} \\index{gradlex ! term order}\n\\index{revgradlex ! term order}\n\n\\begin{center}\n$lex$, $gradlex$, $revgradlex$\n\\end{center}\n\nAll orderings are based on an ordering among the variables. For\neach pair of variables $(a,b)$ an order relation must be defined, e.g.\n``$ a\\gg b $''. The greater sign $\\gg$  does not represent a numerical\nrelation among the variables; it can be interpreted only in terms of\nformula representation: ``$a$'' will be placed in front of ``$b$'' or\n``$a$''  is more complicated than ``$b$''.\n\nThe sequence of variables constitutes this order base. So the notion\nof\n\\[ \\{x1,x2,x3\\} \\]\n\nas a list of variables at the same time means\n\\[ x1 \\gg x2 \\gg x3 \\]\nwith respect to the term order.\n\nIf terms (products of powers of variables) are compared with $lex$,\nthat term is chosen which has a greater variable or a higher degree\nif the greatest variable is the first in both. With $gradlex$ the sum of\nall exponents (the total degree) is compared first, and if that does\nnot lead to a decision, the $lex$ method is taken for the final decision.\nThe $revgradlex$ method also compares the total degree first, but\nafterward it uses the $lex$ method in the reverse direction; this is the\nmethod originally used by Buchberger.\n\n\\example \\ with $\\{x,y,z\\}$: \\index{Groebner package ! example}\n\\[\n\\begin{array}{rlll}\n\\multicolumn{2}{l}{\\hspace*{-1cm}\\mbox{\\bf lex:}}\\\\\n x * y **3 & \\gg & y ** 48 & \\mbox{(heavier variable)} \\\\\n x**4 * y**2 & \\gg  & x**3 * y**10 & \\mbox{(higher degree in 1st\nvariable)} \\vspace*{2mm} \\\\\n\\multicolumn{2}{l}{\\hspace*{-1cm}\\mbox{\\bf gradlex:}} \\\\\n  y**3 * z**4 & \\gg & x**3 * y**3 & \\mbox{(higher total degree)} \\\\\n  x*z  &        \\gg & y**2  & \\mbox{(equal total degree)}\n\\vspace*{2mm}\\\\\n\\multicolumn{2}{l}{\\hspace*{-1cm}\\mbox{\\bf\nrevgradlex:}} \\\\\n y**3 * z**4 & \\gg &  x**3 * y**3 & \\mbox{(higher total degree)} \\\\\n x*z         & \\ll  &  y**2       & \\mbox{(equal total degree,} \\\\\n & & & \\mbox{so reverse order of lex)}\n\\end{array}\n\\]\n\nThe formal description of the term order modes is similar to\n\\cite{Kredel:88}; this description regards only the exponents of a term,\nwhich are written as vectors of integers with $0$ for exponents of a\nvariable which does not occur:\n\\[\n\\begin{array}{l}\n  (e) = (e1,\\ldots , en) \\;\\mbox{ representing }\\; x1**e1 \\ x2**e2 \\cdots\n  xn**en. \\\\\n  \\deg(e) \\; \\mbox{ is the sum over all elements of } \\;(e) \\\\\n  (e) \\gg (l) \\Longleftrightarrow (e)-(l)\\gg (0) = (0,\\ldots ,0)\n\\end{array}\n\\]\n\\[\n\\begin{array}{rll}\n\\multicolumn{1}{l}{\\hspace*{-.5cm}\\mbox{\\bf lex:}} \\\\\n  (e) > lex > (0) & \\Longrightarrow  & e_k > 0 \\mbox{ and } e_j =0\n\\mbox{ for }\\; j=1,\\ldots , k-1\\vspace*{2mm} \\\\\n\\multicolumn{1}{l}{\\hspace*{-.5cm}\\mbox{\\bf\ngradlex:}} \\\\\n  (e) >gl> (0)  & \\Longrightarrow  & \\deg(e)>0  \\mbox { or } (e) >lex>\n(0)\\vspace*{2mm} \\\\\n\\multicolumn{1}{l}{\\hspace*{-.5cm}\\mbox{\\bf\nrevgradlex:}}\\\\\n  (e) >rgl> (0) & \\Longrightarrow & \\deg(e)>0  \\mbox{ or }(e)  <lex<\n(0)\n\\end{array}\n\\]\n\nNote that the $lex$ ordering is identical to the standard \\REDUCE \\ \nkernel ordering, when $korder$ is set explicitly to the sequence of\nvariables.\n\n\\index{default ! term order}\n$lex$ is the default term order mode in the $groebner$ package.\n\nIt is beyond the scope of this manual to discuss the functionality of\nthe term order modes. See \\cite{Buchberger:88}.\n\nThe list of variables is declared as an optional parameter of the\n$torder$ statement (see below). If this declaration is missing\nor if the empty list has been used, the variables are extracted from\nthe expressions automatically and the \\REDUCE \\  system order defines\ntheir sequence; this can be influenced by setting an explicit order\nvia the $korder$ statement.\n\nThe result of a Gr\\\"obner calculation is algebraically correct only\nwith respect to the term order mode and the variable sequence\nwhich was in effect during the calculation. This is important if\nseveral calls to the $groebner$ package are done with the result of the\nfirst being the input of the second call. Therefore we recommend\nthat you declare the variable list and the order mode explicitly.\nOnce declared it remains valid until you enter a new $torder$\nstatement. The operator $gvars$ helps you extract the variables\nfrom a given set of polynomials, if an automatic reordering has been selected.\n\n\\subsection{The Buchberger Algorithm}\n\\index{Buchberger's Algorithm}\nThe Buchberger algorithm of the package is based on {\\sc\nGebauer/M\\\"oller} \\cite{Gebauer:88}.\nExtensions are documented in \\cite{Melenk:88} and \\cite{Giovini:91}.\n\n\\section{Loading of the Package}\nThe following command loads the package into\n\\REDUCE (this syntax may vary according to the implementation):\n\\begin{center}\nload\\_package groebner;\n\\end{center}\n\nThe package contains various operators, and switches for control\nover the reduction process. These are discussed in the following.\n\n\\section{The Basic Operators}\n\n\\subsection{Term Ordering Mode}\n\n\\begin{description}\n\\ttindex{torder}\n\\item [{\\it torder}]($vl$,$m$,$[p_1,p_2,\\ldots]$);\n\nwhere $vl$ is a variable list (or the empty list if\nno variables are declared explicitly),\n$m$ is the name of a term ordering mode $lex$, $gradlex$,\n$revgradlex$ (or another implemented mode) and\n$[p_1,p_2,\\ldots]$ are additional parameters for the\nterm ordering mode (not needed for the basic modes).\n\n$torder$ sets variable set and the term ordering mode.\nThe default mode is $lex$. The previous description is returned\nas a list with corresponding elements. Such a list can\nalternatively be passed as sole argument to $torder$.\n\nIf the variable list is empty or if the $torder$ declaration\nis omitted, the automatic variable extraction is activated.\n\n\\ttindex{gvars}\n\\item[{\\it gvars}] ({\\it\\{exp$1$, exp$2$, $ \\ldots$, exp$n$\\}});\n\n where $\\{exp1, exp2, \\ldots , expn\\}$ is a list of expressions or\nequations.\n\n$gvars$ extracts from the expressions $\\{exp1, exp2, \\ldots , expn\\}$\nthe kernels, which can play the role of variables for a Gr\\\"obner\ncalculation. This can be used e.g. in a $torder$ declaration.\n\\end{description}\n\n\\subsection{$groebner$: Calculation of a Gr\\\"obner Basis}\n\\begin{description}\n\\ttindex{groebner}\n\\item[{\\it groebner}] $\\{exp1, exp2, \\ldots , expm\\}; $\n\nwhere $\\{exp1, exp2, \\ldots , expm\\}$ is a list of\nexpressions or equations.\n\n$groebner$ calculates the Gr\\\"obner basis of the given set of\nexpressions with respect to the current $torder$ setting.\n\nThe Gr\\\"obner basis $\\{1\\}$ means that the ideal generated by the\ninput polynomials is the whole polynomial ring, or equivalently, that\nthe input polynomials have no zeroes in common.\n\nAs a side effect, the sequence of variables is stored as a \\REDUCE \\  list\nin the shared variable\n\\ttindex{gvarslast}\n\\begin{center}\n$gvarslast$.\n\\end{center}\n\nThis is important if the variables are reordered because of optimization:\nyou must set them afterwards explicitly as the current variable sequence\nif you want to use the Gr\\\"obner basis in the sequel, e.g. for a\n$preduce$ call. A basis has the property ``Gr\\\"obner'' only with respect\nto the variable sequences which had been active during its computation.\n\\end{description}\n\n\\example \\index{Groebner package ! example}\n\\begin{verbatim}\n   torder({},lex)$\n   groebner{3*x**2*y + 2*x*y + y + 9*x**2 + 5*x - 3,\n   2*x**3*y - x*y - y + 6*x**3 - 2*x**2 - 3*x + 3,\n   x**3*y + x**2*y + 3*x**3 + 2*x**2 };\n\n               2\n     {8*x - 2*y  + 5*y + 3,\n\n         3      2\n      2*y  - 3*y  - 16*y + 21}\n\\end{verbatim}\n\n\nThis example used the default system variable ordering, which was\n$\\{x,y\\}$. With the other variable ordering, a different basis results:\n\n\\begin{verbatim}\n   torder({y,x},lex)$\n   groebner{3*x**2*y + 2*x*y + y + 9*x**2 + 5*x - 3,\n   2*x**3*y - x*y - y + 6*x**3 - 2*x**2 - 3*x + 3,\n   x**3*y + x**2*y + 3*x**3 + 2*x**2 };\n\n               2\n     {2*y + 2*x  - 3*x - 6,\n\n         3      2\n      2*x  - 5*x  - 5*x}\n\\end{verbatim}\n\n\nAnother basis yet again results with a different term ordering:\n\\begin{verbatim}\n   torder({x,y},revgradlex)$\n   groebner{3*x**2*y + 2*x*y + y + 9*x**2 + 5*x - 3,\n   2*x**3*y - x*y - y + 6*x**3 - 2*x**2 - 3*x + 3,\n   x**3*y + x**2*y + 3*x**3 + 2*x**2 };\n\n    2\n{2*y  - 5*y - 8*x - 3,\n\n y*x - y + x + 3,\n\n    2\n 2*x  + 2*y - 3*x - 6}\n\n\\end{verbatim}\n\n\nThe operation of $groebner$ can be controlled by the following switches:\n\\begin{description}\n\\ttindex{groebopt}\n\\item[groebopt] -- If set $on$, the sequence of variables is optimized\nwith respect to execution speed; the algorithm involved is described\nin~\\cite{Boege:86}; note that the final list of variables is available in\n\\ttindex{gvarslast}\n$gvarslast$.\n\nAn explicitly declared dependency supersedes the variable optimization. For example\n\\begin{center}\n{\\it depend} $a$, $x$, $y$;\n\\end{center}\nguarantees that $a$ will be placed in front of $x$ and $y$. So\n$groebopt$ can be used even in cases where elimination of variables is desired.\n\nBy default $groebopt$ is $off$, conserving the original variable sequence.\n\n\\ttindex{groebfullreduction}\n\\item[$groebfullreduction$] -- If set $off$, the reduction steps during\nthe \\linebreak[4] $groebner$ operation are limited to the pure head\nterm reduction; subsequent terms are reduced otherwise.\n\nBy default $groebfullreduction$ is on.\n\n\\ttindex{gltbasis}\n\\item[$gltbasis$] -- If set on, the leading terms of the result basis are\nextracted. They are collected in a basis of monomials, which is\navailable as value of the global variable with the name $gltb$.\n\n\\item[$glterms$] -- If $\\{exp_1, \\ldots , exp_m\\} $ contain parameters\n(symbols which are not member of the variable list), the share variable\n{\\tt $glterms$} contains a list of expression which during the\ncalculation were assumed to be nonzero. A Gr\\\"obner basis\nis valid only under the assumption that all these expressions do not vanish.\n\n\\end{description}\n\nThe following switches control the print output of $groebner$; by\ndefault all these switches are set $off$ and nothing is printed.\n\\begin{description}\n\\ttindex{groebstat}\n\\item[$groebstat$] -- A summary of the computation is printed\nincluding the computing time, the number of intermediate\n$h$--polynomials and the counters for the hits of the criteria.\n\n\\ttindex{trgroeb}\n\\item[$trgroeb$] -- Includes $groebstat$ and the printing of the\nintermediate $h$-polynomials.\n\n\\ttindex{trgroebs}\n\\item[$trgroebs$] -- Includes $trgroeb$ and the printing of\nintermediate $s$--poly\\-nomials.\n\n\\ttindex{trgroeb1}\n\\item[$trgroeb1$] -- The internal pairlist is printed when modified.\n\\end{description}\n\n\\subsection{$Gzerodim$?: Test of $\\dim = 0$}\n\\begin{description}\n\\ttindex{gzerodim?}\n\\item[{\\it gzerodim}!?] $bas$ \\\\\nwhere {\\it bas} is a Gr\\\"obner basis in the current setting.\nThe result is {\\it nil}, if {\\it bas} is the\nbasis of an ideal of polynomials with more than finitely many common zeros.\nIf the ideal is zero dimensional, i. e. the polynomials of the ideal have only\nfinitely many zeros in common, the result is an integer $k$ which is the number\nof these common zeros (counted with multiplicities).\n\\end{description}\n\n\\subsection{$gdimension$, $gindependent$\\_$sets$: compute dimension and\nindependent variables}\nThe following operators can be used to compute the dimension\nand the independent variable sets of an ideal which has the\nGr\\\"obner basis {\\it bas} with arbitrary term order:\n\\begin{description}\n\\ttindex{gdimension}\\ttindex{gindependent\\_sets}\n\\ttindex{ideal dimension}\\ttindex{independent sets}\n\\item[$gdimension$]$bas$\n\\item[$gindependent$\\_$sets$]$bas$\n{\\it gindependent\\_sets} computes the maximal\nleft independent variable sets of the ideal, that are\nthe variable sets which play the role of free parameters in the\ncurrent ideal basis. Each set is a list which is a subset of the\nvariable list. The result is a list of these sets. For an\nideal with dimension zero the list is empty.\n{\\it gdimension} computes the dimension of the ideal,\nwhich is the maximum length of the independent sets.\n\\end{description}\n\nThe switch $groebopt$ plays no role in the algorithms $gdimension$ and\n$gindependent$\\_$sets$. It is set $off$ during the processing even if\nit is set $on$ before. Its state is saved during the processing.\n\nThe ``Kredel-Weispfenning\" algorithm is used (see \\cite{Kredel:88a},\nextended to general ordering in \\cite{BeWei:93}.\n\n\\subsection{Conversion of a Gr\\\"obner Basis}\n\n\\subsubsection{$glexconvert$: Conversion of an Arbitrary Gr\\\"obner Basis\nof a Zero Dimensional Ideal into a Lexical One}\n\\begin{description}\n\\ttindex{glexconvert}\n\\item[{\\it glexconvert}] $ \\left(\\{exp,\\ldots , expm\\} \\left[,\\{var1\n\\ldots , varn\\}\\right]\\left[,maxdeg=mx\\right]\\right.$ \\\\\n$\\left.\\left[,newvars=\\{nv1, \\ldots , nvk\\}\\right]\\right) $ \\\\\nwhere $\\{exp1, \\ldots , expm\\}$ is a Gr\\\"obner basis with\n$\\{var1, \\ldots , varn\\}$ as variables in the current term order mode,\n$mx$ is an integer, and\n$\\{nv1, \\ldots , nvk\\}$ is a subset of the basis variables.\nFor this operator the source and target variable sets must be specified\nexplicitly.\n\\end{description}\n\n$glexconvert$ converts a basis of a zero-dimensional ideal (finite number\nof isolated solutions) from arbitrary ordering into a basis under {\\it\nlex} ordering. During the call of $glexconvert$ the original ordering of\nthe input basis must be still active!\n\n$newvars$ defines the new variable sequence. If omitted, the\noriginal variable sequence is used. If only a subset of variables is\nspecified here, the partial ideal basis is evaluated. For the\ncalculation of a univariate polynomial, $new$\\-$vars$ should be a list\nwith one element.\n\n$maxdeg$ is an upper limit for the degrees. The algorithm stops with\nan error message, if this limit is reached.\n\nA warning occurs if the ideal is not zero dimensional.\n\n$glexconvert$ is an implementation of the FLGM algorithm by\n\\linebreak[4] {\\sc Faug{\\`e}re}, {\\sc Gianni}, {\\sc Lazard} and {\\sc\nMora} \\cite{Faugere:89}. Often, the calculation of a Gr\\\"obner basis\nwith a graded ordering and subsequent conversion to {\\it lex} is\nfaster than a direct {\\it lex} calculation. Additionally, $glexconvert$\ncan be used to transform a {\\it lex} basis into one with different\nvariable sequence, and it supports the calculation of a univariate\npolynomial. If the latter exists, the algorithm is even applicable in\nthe non zero-dimensional case, if such a polynomial exists.\nIf the polynomial does not exist, the algorithm computes  until $maxdeg$\nhas been reached.\n\\begin{verbatim}\n   torder({{w,p,z,t,s,b},gradlex)\n\n   g  :=  groebner  { f1 := 45*p + 35*s -165*b -36,\n         35*p + 40*z + 25*t - 27*s, 15*w + 25*p*s +30*z -18*t\n        -165*b**2, -9*w + 15*p*t  + 20*z*s,\n        w*p + 2*z*t - 11*b**3, 99*w - 11*s*b +3*b**2,\n        b**2 + 33/50*b + 2673/10000};\n\n  g := {60000*w + 9500*b + 3969,\n\n      1800*p - 3100*b - 1377,\n\n      18000*z + 24500*b + 10287,\n\n      750*t - 1850*b + 81,\n\n      200*s - 500*b - 9,\n             2\n      10000*b  + 6600*b + 2673}\n\n   glexconvert(g,{w,p,z,t,s,b},maxdeg=5,newvars={w});\n\n               2\n    100000000*w  + 2780000*w + 416421\n\n   glexconvert(g,{w,p,z,t,s,b},maxdeg=5,newvars={p});\n\n          2\n    6000*p  - 2360*p + 3051\n\n\\end{verbatim}\n\n\\subsubsection{$groebner$\\_$walk$: Conversion of a (General) Total Degree\nBasis into a Lex One}\nThe algorithm $groebner$\\_$walk$ convertes from an arbitrary polynomial\nsystem a $graduated$ basis of the given variable sequence to a $lex$ one\nof the same sequence. The job is done by computing a sequence\nof Gr\\\"obner bases of correspondig monomial ideals, lifting the original\nsystem each time. The algorithm has been described (more generally) by\n\\cite{AGK:961},\\cite{AGK:962},\\cite{AG:98} and \\cite{CKM:97}.\n$groebner\\_walk$ should be only called, if the direct calculation of a\n$lex$ Gr\\\"obner base does not work. The computation of $groebner\\_walk$\nincludes some overhead (e. g. the computation divides polynomials).\nNormally $torder$ must be called before to define the variables and the variable\nsorting. The reordering of variables makes no sense with $groebner$\\_$walk$;\nso do not call $groebner\\_walk$ with $groebopt$ $on$!\n\n\\begin{description}\n\\ttindex{groebner\\_walk}\n\\item[{\\it groebner\\_walk}] $g$\\\\\nwhere $g$ is a polynomial ideal basis computed under $gradlex$ or under\n$weighted$ with a one--element, non zero weight vector with only one\nelement, repeated for each variable. The result is a corresponding\n$lex$ basis (if that is computable), independet of the degree of the\nideal (even for non zero degree ideals).\nThe variabe $gvarslast$ is not set.\n\\end{description}\n\n\\subsection{$groebnerf$: Factorizing Gr\\\"obner Bases}\n\n\\subsubsection{Background}\nIf Gr\\\"obner bases are computed in order to solve systems of\nequations or to find the common roots of systems of polynomials,\nthe factorizing version of the Buchberger algorithm can be used.\nThe theoretical background is simple: if a polynomial $p$ can be\nrepresented as a product of two (or more) polynomials, e.g. $h= f*g$,\nthen $h$ vanishes if and only if one of the factors vanishes. So if\nduring the calculation of a Gr\\\"obner basis $h$ of the above form is\ndetected, the whole problem can be split into two (or more)\ndisjoint branches. Each of the branches is simpler than the complete\nproblem; this saves computing time and space. The result of this\ntype of computation is a list of (partial) Gr\\\"obner bases; the\nsolution set of the original problem is the union of the solutions of\nthe partial problems, ignoring the multiplicity of an individual\nsolution. If a branch results in a basis $\\{1\\}$, then there is no\ncommon zero, i.e. no additional solution for the original problem,\ncontributed by this branch.\n\n\\subsubsection{$groebnerf$ Call}\n\\ttindex{groebnerf}\nThe syntax of $groebnerf$ is the same as for $groebner$.\n\\[ \\mbox{\\it groebnerf}(\\{exp1, exp2, \\ldots , expm\\}\n         [,\\{\\},\\{nz1, \\ldots nzk\\}); \\]\nwhere $\\{exp1, exp2, \\ldots , expm\\} $ is a given list of expressions or\nequations, and $\\{nz1, \\ldots nzk\\}$ is\nan optional list of polynomials known to be non-zero.\n\n$groebnerf$ tries to separate polynomials into individual factors and\nto branch the computation in a recursive manner (factorization tree).\nThe result is a list of partial Gr\\\"obner bases. If no factorization can\nbe found or if all branches but one lead to the trivial basis $\\{1\\}$,\nthe result has only one basis; nevertheless it is a list of lists of\npolynomials. If no solution is found, the result will be $\\{\\{1\\}\\}$.\nMultiplicities (one factor with a higher power, the same partial basis\ntwice) are deleted as early as possible in order to speed up the\ncalculation. The factorizing is controlled by some switches.\n\nAs a side effect, the sequence of variables is stored as a \\REDUCE \\  list in\nthe shared variable\n\\begin{center}\ngvarslast .\n\\end{center}\nIf $gltbasis$ is on, a corresponding list of leading term bases is\nalso produced and is available in the variable $gltb$.\n\nThe third parameter of $groebnerf$ allows one to declare some polynomials\nnonzero. If any of these is found in a branch of the calculation\nthe branch is cancelled. This can be used to save a substantial amount\nof computing time. The second parameter must be included as an\nempty list if the third parameter is to be used.\n\n\\begin{verbatim}\n   torder({x,y},lex)$\n   groebnerf { 3*x**2*y + 2*x*y + y + 9*x**2 + 5*x = 3,\n               2*x**3*y - x*y - y + 6*x**3 - 2*x**2 - 3*x = -3,\n                x**3*y + x**2*y + 3*x**3 + 2*x**2 \\};\n\n\n       {{y - 3,x},\n\n                      2\n    {2*y + 2*x - 1,2*x  - 5*x - 5}}\n\\end{verbatim}\n\nIt is obvious here that the solutions of the equations can be read\noff immediately.\n\nAll switches from $groebner$ are valid for $groebnerf$ as well:\n\\ttindex{groebopt}  \\ttindex{gltbasis}\n\\ttindex{groebfullreduction} \\ttindex{groebstat} \\ttindex{trgroeb}\n\\ttindex{trgroebs} \\ttindex{trgroeb1}\n\\begin{center}\n\\begin{tabular}{l}\n$groebopt$ \\\\\n$gltbasis$ \\\\\n$groebfullreduction$ \\\\\n$groebstat$ \\\\\n$trgroeb$ \\\\\n$trgroebs$ \\\\\n$rgroeb1$\n\\end{tabular}\n\\end{center}\n\n\\subsubsection*{Additional switches for $groebnerf$:}\n\\begin{description}\n\n\\ttindex{trgroebr}\n\\item[$trgroebr$] -- All intermediate partial basis are printed when\ndetected.\n\nBy default $trgroebr$ is off.\n\\end{description}\n{\\it groebmonfac  groebresmax  groebrestriction} \\\\\n\\hspace*{.5cm} These variables are described in the following\nparagraphs.\n\n\\subsubsection{Suppression of Monomial Factors}\nThe factorization in $groebnerf$ is controlled by the following\n\\ttindex{groebmonfac}\nswitches and variables.  The variable $groebmonfac$ is connected to\nthe handling of ``monomial factors''.  A monomial factor is a product\nof variable powers occurring as a factor, e.g. $ x**2*y$  in  $x**3*y -\n2*x**2*y**2$.  A monomial factor represents a solution of the type\n``$ x = 0$  or  $y = 0$'' with a certain multiplicity.  With\n$groeb$\\-$nerf$ \\ttindex{groebnerf}\nthe multiplicity of monomial factors is lowered to the value of the\nshared variable\n\\ttindex{groebmonfac}\n\\begin{center}\n$groebmonfac$\n\\end{center}\nwhich by default is 1 (= monomial factors remain present, but their\nmultiplicity is brought down). With\n\\begin{center}\n$groebmonfac$ := 0\n\\end{center}\nthe monomial factors are suppressed completely.\n\n\\subsubsection{Limitation on the Number of Results}\nThe shared variable\n\\ttindex{groebresmax}\n\\begin{center}\n$groebresmax$\n\\end{center}\ncontrols the number of partial results. Its default value is 300. If\n$groebresmax$ partial results are calculated, the calculation is\nterminated. $groebresmax$ counts all branches, including those which\nare terminated (have been computed already), give no contribution to\nthe result (partial basis 1), or which are unified in the result with\nother (partial) bases. So the resulting number may be much smaller.\nWhen the limit of $groeresmax$ is reached, a warning\n\nGROEBRESMAX limit reached\n\nis issued; this warning in any case has to be taken as a serious one.\nFor \"normal\" calculations the $groebresmax$ limit is not reached.\n$groebresmax$ is a shared variable (with an integer value); it can be\nset in the algebraic mode to a different (positive integer) value.\n\n\\subsubsection{Restriction of the Solution Space}\nIn some applications only a subset of the complete solution set\nof a given set of equations is relevant, e.g. only\nnonnegative values or positive definite values for the variables.\nA significant amount of computing time can be saved if\nnonrelevant computation branches can be terminated early.\n\nPositivity: If a polynomial has no (strictly) positive zero, then\nevery system containing it has no nonnegative or strictly positive\nsolution. Therefore, the Buchberger algorithm tests the coefficients of\nthe polynomials for equal sign if requested. For example, in $13*x +\n15*y*z $ can be zero with real nonnegative values for $x, y$ and $z$\nonly if $x=0$ and $y=0$ or $ z=0$; this is a sort of ``factorization by\nrestriction''. A polynomial $13*x + 15*y*z + 20$ never can vanish\nwith nonnegative real variable values.\n\nZero point:  If any polynomial in an ideal has an absolute term, the ideal\ncannot have the origin point as a common solution.\n\nBy setting the shared variable\n\\ttindex{groebrestriction}\n\\begin{center} $groebrestriction$ \\end{center}\n$groebnerf$ is informed of the type of restriction the user wants to\nimpose on the solutions:\n\\begin{center}\n\\begin{tabular}{l}\n{\\it groebrestiction:=nonnegative;} \\\\\n\\hspace*{+.5cm} only nonnegative real solutions are of\ninterest\\vspace*{4mm} \\\\\n{\\it groebrestriction:=positive;} \\\\\n\\hspace*{+.5cm}only nonnegative and nonzero solutions are of\ninterest\\vspace*{4mm} \\\\\n{\\it groebrestriction:=zeropoint;} \\\\\n\\hspace*{+.5cm}only solution sets which contain the point\n$\\{0,0,\\ldots,0\\}$ are or interest.\n\\end{tabular}\n\\end{center}\n\nIf $groebnerf$ detects a polynomial which formally conflicts with the\nrestriction, it either splits the calculation into separate branches, or,\nif a violation of the restriction is determined, it cancels the actual\ncalculation branch.\n\n\\subsection{$greduce$, $preduce$: Reduction of Polynomials}\n\n\\subsubsection{Background} \\label{groebner:background}\nReduction of a polynomial ``$p$'' modulo a given sets of polynomials\n``$b$'' is done by the reduction algorithm incorporated in the\nBuchberger algorithm. Informally it can be described for\npolynomials over a field as follows:\n\\begin{center}\n\\begin{tabular}{l}\nloop1: \\hspace*{2mm}\\% head term elimination \\\\\n\\hspace*{-1cm} if there is one polynomial $b$ in $B$ such that the\nleading \\\\ term of $p$ is a multiple of the leading term of $P$ do \\\\\n$p := p - lt(p)/lt(b) * b$  (the leading term vanishes)\\\\\n\\hspace*{-1cm} do this loop as long as possible; \\\\\nloop2: \\hspace*{2mm} \\% elimination of subsequent terms \\\\\n\\hspace*{-1cm} for each term $s$ in $p$ do \\\\\nif there is one polynomial $b$ in $B$ such that $s$ is a\\\\\nmultiple of the leading term of $p$ do \\\\\n$p := p - s/lt(b) * b$ (the term $s$ vanishes) \\\\\n\\hspace*{-1cm}do this loop as long as possible;\n\\end{tabular}\n\\end{center}\n\nIf the coefficients are taken from a ring without zero divisors we\ncannot divide by each possible number like in the field case. But\nusing that in the field case,  $c*p $ is reduced to  $c*q $, if $ p $\nis reduced to $ q $, for arbitrary numbers $ c $,  the reduction for\nthe ring case uses the least $ c $ which makes the (field) reduction\nfor $ c*p $ integer. The result of this reduction is returned as\n(ring) reduction of $ p $ eventually after removing the content, i.e.\nthe greatest common divisor of the coefficients. The result of this\ntype of reduction is also called a pseudo reduction of $ p $.\n\n\\subsubsection{Reduction via Gr\\\"obner Basis Calculation}\n\\ttindex{greduce}\n\\[\n\\mbox{\\it greduce}(exp, \\{exp1, exp2, \\ldots , expm\\}]);\n\\]\nwhere {\\it exp} is an expression, and $\\{exp1, exp2,\\ldots , expm\\}$ is\na list of any number of expressions or equations.\n\n$greduce$ first converts the list of expressions $\\{exp1, \\ldots ,\nexpn\\}$ to a Gr\\\"obner basis, and then reduces the given expression\nmodulo that basis.  An error results if the list of expressions is\ninconsistent. The returned value is an expression representing the\nreduced polynomial. As a side effect, $greduce$ sets the variable {\\it\ngvarslast} in the same manner as $groebner$ does.\n\n\\subsubsection{Reduction with Respect to Arbitrary Polynomials}\n\\ttindex{preduce}\n\\[\n preduce(exp, \\{exp1, exp2,\\ldots , expm\\});\n\\]\nwhere $ expm $  is an expression, and $\\{exp1, exp2, \\ldots ,\nexpm \\}$ is a list of any number of expressions or equations.\n\n$preduce$ reduces the given expression modulo the set $\\{exp1,\n\\ldots , expm\\}$. If this set is a Gr\\\"obner basis, the obtained reduced\nexpression is uniquely determined. If not, then it depends on the\nsubsequence of the single reduction steps\n(see~\\ref{groebner:background}). $preduce$ does not check whether\n$\\{exp1, exp2, \\ldots , expm\\}$ is a Gr\\\"obner basis in the actual\norder. Therefore, if the expressions are a Gr\\\"obner basis calculated\nearlier with a variable sequence given explicitly or modified by\noptimization, the proper variable sequence and term order must\nbe activated first.\n\n\\example ($preduce$ called with a Gr\\\"obner basis):\n\\begin{verbatim}\n  torder({x,y},lex);\n  gb:=groebner{3*x**2*y + 2*x*y + y + 9*x**2 + 5*x - 3,\n               2*x**3*y - x*y - y + 6*x**3 - 2*x**2 - 3*x + 3,\n               x**3*y + x**2*y + 3*x**3 + 2*x**2}$\n  preduce (5*y**2 + 2*x**2*y + 5/2*x*y + 3/2*y\n             + 8*x**2 + 3/2*x - 9/2, gb);\n\n      2\n     y\n\\end{verbatim}\n\n\\subsubsection{$greduce$\\_$orders$: Reduction with several term orders}\nThe shortest polynomial with different polynomial term orders is computed\nwith the operator $greduce$\\_$orders$:\n \n\\begin{description}\n\\ttindex{$greduce$\\_$orders$}\n\\item[{\\it greduce\\_orders}]($exp$, \\{$exp1$, $exp2$, \\ldots , $expm$\\}\n[,\\{$v_1$,$v_2$ \\ldots $v_n$\\}]);\n\nwhere {\\it exp} is an expression and $\\{exp1, exp2,\\ldots , expm\\}$ is\na list of any number of expressions or equations. The list of variables\n$v_1,v_2 \\ldots v_n$ may be omitted; if set, the variables must be a list.\n\\end{description}\n \nThe expression {\\it exp} is reduced by {\\it greduce} with the orders\nin the shared variable {\\it gorders}, which must be a list of term\norders (if set). By default it is set to\n\n\\begin{center}\n$\\{revgradlex,gradlex,lex\\}$\n\\end{center}\n\nThe shortest polynomial is the result.\nThe order with the shortest polynomial is set to the shared variable\n{\\it gorder}. A Gr\\\"obner basis of the system \\{$exp1$, $exp2$, \\ldots ,\n$expm$\\} is computed for each element of $orders$.\nWith the default setting {\\it gorder} in most cases will be set\nto {\\it revgradlex}.\nIf the variable set is given, these variables are taken; otherwise all\nvariables of the system \\{$exp1$, $exp2$, \\ldots , $expm$\\} are\nextracted.\n \nThe Gr\\\"obner basis computations can take some time; if interrupted, the\nintermediate result of the reduction is set to the shared variable\n$greduce$\\_$result$, if one is done already. However, this is not\nnesessarily the minimal form.\n \nIf the variable {\\it gorders} should be set to orders with a parameter,\nthe term oder has to be replaced by a list; the first element is the\nterm oder selected, followed by its parameter(s), e.g.\n\n\\begin{center}\n$orders:=\\{\\{gradlexgradlex,2\\},\\{lexgradlex,2\\}\\}$\n\\end{center}\n\n\\subsubsection{Reduction Tree}\nIn some case not only are the results produced by $greduce$ and\n$preduce$ of interest, but the reduction process is of some value\ntoo. If the switch\n\\ttindex{groebprot}\n\\begin{center}\n$groebprot$\n\\end{center}\nis set on, $groebner$, $greduce$ and $preduce$ produce as a side effect\na trace of their work as a \\REDUCE \\  list of equations in the shared variable\n\\ttindex{groebprotfile}\n\\begin{center}\n$groebprotfile$.\n\\end{center}\nIts value is a list of equations with a variable ``candidate'' playing\nthe role of the object to be reduced. The polynomials are cited as\n``$poly1$'', ``$poly2$'', $\\ldots\\;$. If read as assignments, these equations\nform a program which leads from the reduction input to its result.\nNote that, due to the pseudo reduction with a ring as the coefficient\ndomain, the input coefficients may be changed by global factors.\n\n\\newpage\n\n\\example \\index{groebner package ! example}\n\n{\\it on groebprot} \\$ \\\\\n{\\it preduce} $ (5*y**2 + 2*x**2*y + 5/2*x*y + 3/2*y + 8*x**2 $ \\\\\n\\hspace*{+1cm} $+ 3/2*x - 9/2, gb);$\n\\begin{verbatim}\n      2\n     y\n\\end{verbatim}\n{\\it groebprotfile;}\n\\begin{verbatim}\n                  2         2                     2\n    {candidate=4*x *y + 16*x  + 5*x*y + 3*x + 10*y  + 3*y - 9,\n\n              2\n     poly1=8*x - 2*y  + 5*y + 3,\n\n              3      2\n     poly2=2*y  - 3*y  - 16*y + 21,\n     candidate=2*candidate,\n     candidate= - x*y*poly1 + candidate,\n     candidate= - 4*x*poly1 + candidate,\n     candidate=4*candidate,\n\n                   3\n     candidate= - y *poly1 + candidate,\n     candidate=2*candidate,\n\n                     2\n     candidate= - 3*y *poly1 + candidate,\n     candidate=13*y*poly1 + candidate,\n     candidate=candidate + 6*poly1,\n\n                     2\n     candidate= - 2*y *poly2 + candidate,\n     candidate= - y*poly2 + candidate,\n     candidate=candidate + 6*poly2}\n\n \\end{verbatim}\nThis means\n\\begin{eqnarray*}\n\\lefteqn{\n16 (5 y^2 + 2 x^2 y + \\frac{5}{2} x y + \\frac{3}{2} y\n+ 8 x^2+ \\frac{3}{2} x - \\frac{9}{2})=} \\\\ & &\n(-8 x y -32 x -2 y^3 -3 y^2 + 13 y + 6) \\mbox{poly1} \\\\\n& & \\; + (-2 y^2 -2 y + 6) \\mbox{poly2  } \\; + y^2.\n\\end{eqnarray*}\n\n\\subsection{Tracing with $groebnert$ and $preducet$}\nGiven a set of polynomials $\\{f_1,\\ldots ,f_k\\}$ and their Gr\\\"obner\nbasis $\\{g_1,\\ldots ,g_l\\}$, it is well known that there are matrices of\npolynomials $C_{ij}$ and $D_{ji}$ such that\n\\[\nf_i = \\displaystyle{\\sum\\limits_j} C_{ij} g_j \\;\\mbox{  and  } g_j =\n\\displaystyle{\\sum\\limits_i} D_{ji} f_i\n\\]\nand these relations are needed explicitly sometimes.\nIn {\\sc Buchberger} \\cite{Buchberger:85}, such cases are described in the\ncontext of linear polynomial equations. The standard technique for\ncomputing the above formulae is to perform\nGr\\\"obner reductions, keeping track of the\ncomputation in terms of the input data. In the current package such\ncalculations are performed with (an internally hidden) cofactor\ntechnique: the user has to assign unique names to the input\nexpressions and the  arithmetic combinations are done with the\nexpressions and with their names simultaneously. So the result is\naccompanied by an expression which relates it algebraically to the\ninput values.\n\n\\ttindex{groebnert} \\ttindex{preducet}\nThere are two complementary operators with this feature: $groebnert$\nand $preducet$; functionally they correspond to $groebner$ and $preduce$.\nHowever, the sets of expressions here {\\it {\\bf must be}} equations\nwith unique single identifiers on their left side and the {\\it lhs} are\ninterpreted as names of the expressions. Their results are\nsets of equations ($groebnert$) or equations ($preducet$), where\na {\\it lhs} is the computed value, while the {\\it rhs} is its equivalent\nin terms of the input names.\n\n\\example \\index{groebner package ! example}\n\nWe calculate the Gr\\\"obner basis for an ellipse (named ``$p1$'' ) and a\nline (named ``$p2$'' ); $p2$ is member of the basis immediately and so\nthe corresponding first result element is of a very simple form; the\nsecond member is a combination of $p1$ and $p2$ as shown on the\n{\\it rhs} of this equation:\n\n\\begin{verbatim}\ngb1:=groebnert {p1=2*x**2+4*y**2-100,p2=2*x-y+1};\n\ngb1 := {2*x - y + 1=p2,\n           2\n        9*y  - 2*y - 199= - 2*x*p2 - y*p2 + 2*p1 + p2}\n\\end{verbatim}\n\n\\example \\index{groebner package ! example}\n\nWe want to reduce the polynomial \\verb+ x**2+ {\\it  wrt}\nthe above Gr\\\"obner basis and need knowledge about the reduction\nformula. We therefore extract the basis polynomials from $gb1$,\nassign unique names to them (here $g1$, $g2$) and call $preducet$.\nThe polynomial to be reduced here is introduced with the name $Q$,\nwhich then appears on the {\\it rhs} of the result. If the name for the\npolynomial is omitted, its formal value is used on the right side too.\n\n\\begin{verbatim}\n  gb2 := for k := 1:length gb1 collect\n        mkid(g,k) = lhs part(gb1,k)$\n  preducet (q=x**2,gb2);\n\n - 16*y + 208= - 18*x*g1 - 9*y*g1 + 36*q + 9*g1 - g2\n\\end{verbatim}\n\nThis output means\n\\[\nx^2 = (\\frac{1}{2} x + \\frac{1}{4} y - \\frac{1}{4}) g1\n + \\frac{1}{36} g2 + (-\\frac{4}{9} y + \\frac{52}{9}).\n\\]\n\n\n\\example \\index{groebner package ! example}\n\nIf we reduce a polynomial which is member of the ideal, we\nconsequently get a result with {\\it lhs} zero:\n\\begin{verbatim}\n   preducet(q=2*x**2+4*y**2-100,gb2);\n\n   0= - 2*x*g1 - y*g1 + 2*q + g1 - g2\n\\end{verbatim}\n\nThis means\n\\[ q = ( x + \\frac{1}{2} y - \\frac{1}{2}) g1 + \\frac{1}{2} g2.\n\\]\n\nWith these operators the matrices $C_{ij}$ and $D_{ji}$ are available\nimplicitly, $D_{ji}$ as side effect of $groebnert$T, $c_{ij}$ by {\\it calls}\nof $preducet$ of $f_i$ {\\it wrt} $\\{g_j\\}$. The latter by definition will\nhave the {\\it lhs} zero and a {\\it rhs} with linear $f_i$.\n\nIf $\\{1\\}$ is the Gr\\\"obner basis, the $groebnert$ calculation gives\na ``proof'', showing,  how  $1$ can be computed as combination of the\ninput polynomials.\n\n\\paragraph{Remark:} Compared to the non-tracing algorithms, these\noperators are much more time consuming. So they are applicable\nonly on small sized problems.\n\n\\subsection{Gr\\\"obner Bases for Modules}\n\nGiven a polynomial ring, e.g. $r=z[x_1 \\cdots x_k]$ and\nan integer $n>1$: the vectors with $n$ elements of $r$\nform a $module$ under vector addition (= componentwise addition)\nand multiplication with elements of $r$. For a submodule\ngiven by a finite basis a Gr\\\"obner basis\ncan be computed, and the facilities of the $groebner$ package\ncan be used except the operators $groebnerf$ and $groesolve$.\n\nThe vectors are encoded using auxiliary variables which represent\nthe unit vectors in the module. E.g. using ${v_1,v_2,v_3}$ the\nmodule element $[x_1^2,0,x_1-x_2]$ is represented as\n$x_1^2 v_1 + x_1 v_3 - x_2 v_3$. The use of ${v_1,v_2,v_3}$\nas unit vectors is set up by assigning the set of auxiliary variables\nto the share variable $gmodule$, e.g.\n\\begin{verbatim}\n   gmodule := {v1,v2,v3};\n\\end{verbatim}\nAfter this declaration all monomials built from these variables\nare considered as an algebraically independent basis of a vector\nspace. However, you had best use them only linearly. Once $gmodule$\nhas been set, the auxiliary variables automatically will be\nadded to the end of each variable list (if they are not yet\nmember there).\nExample:\n\\begin{verbatim}\n   torder({x,y,v1,v2,v3},lex)$\n   gmodule := {v1,v2,v3}$\n   g:=groebner{x^2*v1 + y*v2,x*y*v1 - v3,2y*v1 + y*v3};\n\n       2\ng := {x *v1 + y*v2,\n\n              2\n      x*v3 + y *v2,\n\n       3\n      y *v2 - 2*v3,\n\n      2*y*v1 + y*v3}\n\n   preduce((x+y)^3*v1,g);\n\n             1   3         2\n - x*y*v2 - ---*y *v3 - 3*y *v2 + 3*y*v3\n             2\n\n\\end{verbatim}\n\nIn many cases a total degree oriented term order will be adequate\nfor computations in modules, e.g. for all cases where the\nsubmodule membership is investigated. However, arranging\nthe auxiliary variables in an elimination oriented term order\ncan give interesting results. E.g.\n\\begin{verbatim}\n   p1:=(x-1)*(x^2-x+3)$  p2:=(x-1)*(x^2+x-5)$\n   gmodule := {v1,v2,v3};\n   torder({v1,x,v2,v3},lex)$\n   gb:=groebner {p1*v1+v2,p2*v1+v3};\n\ngb := {30*v1*x - 30*v1 + x*v2 - x*v3 + 5*v2 - 3*v3,\n\n        2       2\n       x *v2 - x *v3 + x*v2 + x*v3 - 5*v2 - 3*v3}\n\n   g:=coeffn(first gb,v1,1);\n\ng := 30*(x - 1)\n\n   c1:=coeffn(first gb,v2,1);\n\nc1 := x + 5\n\n   c2:=coeffn(first gb,v3,1);\n\nc2 :=  - x - 3\n\n   c1*p1 + c2*p2;\n\n30*(x - 1)\n\n\\end{verbatim}\nHere two polynomials\nare entered as vectors $[p_1,1,0]$ and $[p_2,0,1]$. Using a term\nordering such that the first dimension ranges highest and the\nother components lowest, a classical cofactor computation is\nexecuted just as in the extended Euclidean algorithm.\nConsequently the leading polynomial in the resulting\nbasis shows the greatest common divisor of $p_1$ and $p_2$,\nfound as a coefficient of $v_1$ while the coefficients\nof $v_2$ and $v_3$ are the cofactors $c_1$ and $c_2$ of the polynomials\n$p_1$ and $p_2$ with the relation $gcd(p_1,p_2) = c_1p_1 + c_2p_2$.\n\n\\subsection{Additional Orderings}\nBesides the basic orderings, there are ordering options that are used for\nspecial purposes.\n\n\\subsubsection{Separating the Variables into Groups }\n\\index{grouped ordering}\nIt is often desirable to separate variables\nand formal parameters in a system of polynomials.\nThis can be done with a {\\it lex} Gr\\\"obner\nbasis.  That however may be hard to compute as it does more\nseparation than necessary. The following orderings group the\nvariables into two (or more) sets, where inside each set a classical\nordering acts, while the sets are handled via their total degrees,\nwhich are compared in elimination style. So the Gr\\\"obner basis will\neliminate the members of the first set, if algebraically possible.\n{\\it torder} here gets an additional parameter which describe the\ngrouping \\ttindex{torder}\n\\begin{center}{\\it\n\\begin{tabular}{l}\ntorder ($vl$,$gradlexgradlex$, $n$) \\\\\ntorder ($vl$,$gradlexrevgradlex$,$n$) \\\\\ntorder ($vl$,$lexgradlex$, $n$) \\\\\ntorder ($vl$,$lexrevgradlex$, $n$)\n\\end{tabular}}\n\\end{center}\nHere the integer $n$ is the number of variables in the first group\nand the names combine the local ordering for the first and second\ngroup, e.g.\n\\begin{center}\n\\begin{tabular}{llll}\n\\multicolumn{4}{l}{{\\it lexgradlex}, 3 for $\\{x_1,x_2,x_3,x_4,x_5\\}$:} \\\\\n\\multicolumn{4}{l}{$x_1^{i_1}\\ldots x_5^{i_5} \\gg x_1^{j_1}\\ldots\nx_5^{j_5}$} \\\\\nif & & & $(i_1,i_2,i_3) \\gg_{lex}(j_1,j_2,j_3)$ \\\\\n& or & & $(i_1,i_2,i_3) = (j_1,j_2,j_3)$ \\\\\n& & and & $(i_4,i_5) \\gg_{gradlex}(j_4,j_5)$\n\\end{tabular}\n\\end{center}\nNote that in the second place there is no {\\it lex} ordering available;\nthat would not make sense.\n\n\\subsubsection{Weighted Ordering}\n\\ttindex{torder} \\index{weighted ordering}\nThe statement\n\\begin{center}\n\\begin{tabular}{cl}\n{\\it torder} &($vl$,weighted, $\\{n_1,n_2,n_3  \\ldots$\\}) ; \\\\\n\\end{tabular}\n\\end{center}\nestablishes a graduated ordering, where the exponents are first\nmultiplied by the given weights. If there are less weight values than\nvariables, the weight 1 is added automatically. If the weighted\ndegree calculation is not decidable, a $lex$ comparison follows.\n\n\\subsubsection{Graded Ordering}\n\\ttindex{torder} \\index{graded ordering}\nThe statement\n\\begin{center}\n\\begin{tabular}{cl}\n{\\it torder} &($vl$,graded, $\\{n_1,n_2,n_3 \\ldots\\}$,$order_2$) ; \\\\\n\\end{tabular}\n\\end{center}\nestablishes a graduated ordering, where the exponents are first\nmultiplied by the given weights. If there are less weight values than\nvariables, the weight 1 is added automatically. If the weighted\ndegree calculation is not decidable, the term order $order_2$ specified\nin the following argument(s) is used.  The ordering $graded$ is designed\nprimarily for use with the operator $dd\\_groebner$.\n\n\\subsubsection{Matrix Ordering}\n\\ttindex{torder} \\index{matrix ordering}\nThe statement\n\\begin{center}\n\\begin{tabular}{cl}\n{\\it torder} &($vl$,matrix, $m$) ; \\\\\n\\end{tabular}\n\\end{center}\nwhere $m$ is a matrix with integer elements and row length which\ncorresponds to the variable number. The exponents of each monomial\nform a vector; two monomials are compared by multiplying their\nexponent vectors first with $m$ and comparing the resulting vector\nlexicographically. E.g. the unit matrix establishes the classical\n$lex$ term order mode, a matrix with a first row of ones followed\nby the rows of a unit matrix corresponds to the $gradlex$ ordering.\n\nThe matrix $m$ must have at least as many rows as columns; a non--square\nmatrix contains redundant rows. The matrix must have full rank, and\nthe top non--zero element of each column must be positive.\n\nThe generality of the matrix based term order has its price: the\ncomputing time spent in the term sorting is significantly higher\nthan with the specialized term orders. To overcome this problem,\nyou can compile a matrix term order ; the\ncompilation reduces the computing time overhead significantly.\nIf you set the switch $comp$ on, any new order matrix is compiled\nwhen any operator of the $groebner$ package accesses it for the\nfirst time. Alternatively you can compile a matrix explicitly\n\\begin{verbatim}\n    torder_compile(<n>,<m>);\n\\end{verbatim}\nwhere $<n>$ is a name (an identifier) and $<m>$ is a term order matrix.\n$torder\\_compile$ transforms the matrix into a LISP program, which\nis compiled by the LISP compiler when $comp$ is on or when you\ngenerate a fast loadable module. Later you can activate the new term\norder by using the name $<n>$ in a $torder$ statement as term ordering\nmode.\n\n\\subsection{Gr\\\"obner Bases for Graded Homogeneous Systems}\n\nFor a homogeneous system of polynomials under a term order\n{\\it graded}, {\\it gradlex}, {\\it revgradlex} or {\\it weighted}\na Gr\\\"obner Base can be computed with limiting the grade\nof the intermediate $s$--polynomials:\n\\begin{description}\n\\ttindex{dd\\_groebner}\n\\item [{\\it dd\\_groebner}]($d1$,$d2$,$\\{p_1,p_2,\\ldots\\}$);\n\\end{description}\nwhere $d1$ is a non--negative integer and $d2$ is an integer\n$>$ $d1$ or ``infinity\". A pair of polynomials is considered\nonly if the grade of the lcm of their head terms is between\n$d1$ and $d2$. See \\cite{BeWei:93} for the mathematical background.\nFor the term orders {\\it graded} or {\\it weighted} the (first) weight\nvector is used for the grade computation. Otherwise the total\ndegree of a term is used.\n\n\\section{Ideal Decomposition \\& Equation System Solving}\nBased on the elementary Gr\\\"obner operations, the $groebner$ package offers\nadditional operators, which allow the decomposition of an ideal or of a\nsystem of equations down to the individual solutions.\n\n\\subsection{Solutions Based on Lex Type Gr\\\"obner Bases}\n\n\\subsubsection{groesolve: Solution of a Set of Polynomial Equations}\n\\ttindex{groesolve} \\ttindex{groebnerf}\nThe $groesolve$ operator incorporates a macro algorithm;\nlexical Gr\\\"obner bases are computed by $groebnerf$ and decomposed\ninto simpler ones by ideal decomposition techniques; if algebraically\npossible, the problem is reduced to univariate polynomials which are\nsolved by $solve$; if $rounded$ is on, numerical approximations are\ncomputed for the roots of the univariate polynomials.\n\\[\n groesolve(\\{exp1, exp2, \\ldots , expm\\}[,\\{var1, var2, \\ldots ,\nvarn\\}]); \\]\nwhere $\\{exp1, exp2,\\ldots , expm\\}$ is a list of any number of\nexpressions or equations, $\\{var1, var2, \\ldots , varn\\}$ is an\noptional list of variables.\n\nThe result is a set of subsets. The subsets contain the solutions of the\npolynomial equations. If there are only finitely many solutions,\nthen each subset is a set of expressions of triangular type\n$\\{exp1, exp2,\\ldots , expn\\},$ where $exp1$ depends only on\n$var1,$ $exp2$ depends only on $var1$ and $var2$ etc. until $expn$ which\ndepends on $var1,\\ldots,varn.$ This allows a successive determination of\nthe solution components. If there are infinitely many solutions,\nsome subsets consist in less than $n$ expressions. By considering some\nof the variables as ``free parameters'',  these subsets are usually\nagain of triangular type.\n\n\\example (Intersections of a line with a circle):\n\\index{groebner package ! example}\n\n\\[ groesolve(\\{x**2 - y**2 - a, p*x+q*y+s\\},\\{x,y\\}); \\]\n\n\\begin{verbatim}\n                   2      2    2             2    2\n   {{x=(sqrt( - a*p  + a*q  + s )*q - p*s)/(p  - q ),\n                      2      2    2             2    2\n     y= - (sqrt( - a*p  + a*q  + s )*p - q*s)/(p  - q )},\n                      2      2    2             2    2\n    {x= - (sqrt( - a*p  + a*q  + s )*q + p*s)/(p  - q ),\n                   2      2    2             2    2\n     y=(sqrt( - a*p  + a*q  + s )*p + q*s)/(p  - q )}}\n\\end{verbatim}\n\nIf the system is zero--dimensional (has a number of isolated solutions),\nthe algorithm described in \\cite{Hillebrand:99} is used, if the decomposition\nleaves a polynomial with mixed leading term. Hillebrand has written the\narticle and M\\\"oller was the tutor of this job.\n\nThe reordering of the $groesolve$ variables is controlled by the\n\\REDUCE \\ switch $varopt$. If $varopt$ is $on$ (which is the default\nof $varopt$), the variable sequence is optimized (the variables are reordered).\nIf $varopt$ is $off$, the given variable sequence is taken (if no variables\nare given, the order of the \\REDUCE \\ system is taken instead). In general, the\nreordering of the variables makes the Gr\\\"obner basis computation\nsignificantly faster.\nA variable dependency, declare by one (or several) $depend$ statements,\nis regarded (if $varopt$ is $on$). The switch $groebopt$ has no meaning\nfor $groesolve$; it is stored during its processing.\n\n\\subsubsection{$groepostproc$: Postprocessing of a Gr\\\"obner Basis}\n\\ttindex{groepostproc}\nIn many cases, it is difficult to do the general Gr\\\"obner processing.\nIf a Gr\\\"obner basis with a {\\it lex} ordering is calculated already (e.g.,\nby very individual parameter settings), the solutions can be derived\nfrom it by a call to $groepostproc$. $groesolve$ is functionally\nequivalent to a call to $groebnerf$ and subsequent calls to\n$groepostproc$ for each partial basis.\n\\[\n groepostproc(\\{exp1, exp2, \\ldots , expm\\}[,\\{var1, var2, \\ldots ,\nvarn\\}]);\n\\]\nwhere $\\{exp1, exp2, \\ldots , expm\\}$ is a list of any number of\nexpressions, \\linebreak[4] $\\{var1, var2, \\ldots ,$ $ varn\\}$ is an\noptional list of variables. The expressions must be a {\\it lex} Gr\\\"obner\nbasis with the given variables; the ordering must be still active.\n\nThe result is the same as with $groesolve$.\n\n\\begin{verbatim}\ngroepostproc({x3**2 + x3 + x2 - 1,\n              x2*x3 + x1*x3 + x3 + x1*x2 + x1 + 2,\n              x2**2 + 2*x2 - 1,\n              x1**2 - 2},{x3,x2,x1});\n\n{{x3= - sqrt(2),\n\n  x2=sqrt(2) - 1,\n\n  x1=sqrt(2)},\n\n {x3=sqrt(2),\n\n  x2= - (sqrt(2) + 1),\n\n  x1= - sqrt(2)},\n\n      sqrt(4*sqrt(2) + 9) - 1\n {x3=-------------------------,\n                 2\n\n  x2= - (sqrt(2) + 1),\n\n  x1=sqrt(2)},\n\n       - (sqrt(4*sqrt(2) + 9) + 1)\n {x3=------------------------------,\n                   2\n\n  x2= - (sqrt(2) + 1),\n\n  x1=sqrt(2)},\n\n      sqrt( - 4*sqrt(2) + 9) - 1\n {x3=----------------------------,\n                  2\n\n  x2=sqrt(2) - 1,\n\n  x1= - sqrt(2)},\n\n       - (sqrt( - 4*sqrt(2) + 9) + 1)\n {x3=---------------------------------,\n                     2\n\n  x2=sqrt(2) - 1,\n\n  x1= - sqrt(2)}}\n\\end{verbatim}\n\n\\subsubsection{Idealquotient: Quotient of an Ideal and an Expression}\n\\ttindex{idealquotient} \\index{ideal quotient}\nLet $i$ be an ideal and $f$ be a polynomial in the same\nvariables. Then the algebraic quotient is defined by\n\\[\ni:f = \\{ p \\;| \\; p * f \\;\\mbox{    member of }\\; i\\}\\;.\n\\]\nThe ideal quotient $i:f$ contains $i$ and is obviously part of the\nwhole polynomial ring, i.e. contained in $\\{1\\}$. The case $i:f =\n\\{1\\}$ is equivalent to $f$ being a member of  $i$. The other extremal\ncase, $i:f=i$, occurs, when $f$ does not vanish at any general zero of $i$.\nThe explanation of the notion ``general zero'' introduced by van der\nWaerden, however, is beyond the aim of this manual. The operation\nof $groesolve$/$groepostproc$ is based on nested ideal quotient\ncalculations.\n\nIf $i$ is given by a basis and $f$ is given as an expression, the\nquotient can be calculated by\n\\[\nidealquotient (\\{exp1, \\ldots , expm\\}, exp); \\]\nwhere $\\{exp1, exp2, \\ldots , expm\\}$ is a list of any number of\nexpressions or equations, {\\it exp} is a single expression or equation.\n\n$idealquotient$ calculates the algebraic quotient of the ideal $i$\nwith the basis  $\\{exp1, exp2, \\ldots , expm\\}$ and {\\it exp} with\nrespect to  the variables given or extracted.  $\\{exp1, exp2, \\ldots ,\nexpm\\}$ is not necessarily a Gr\\\"obner basis.\nThe result is the Gr\\\"obner basis of the quotient.\n\n\\subsubsection{Saturation: Saturation of an Ideal and an Expression}\n\\ttindex{saturation}\nThe $saturation$ computes the quotient on an ideal and an arbitrary power\nof an expression $exp**n$ with arbitrary $n$. The call is\n\\[ saturation (\\{exp1, \\ldots , expm\\}, exp); \\]\nwhere $\\{exp1, exp2, \\ldots , expm\\}$ is a list of any number of\nexpressions or equations, {\\it exp} is a single expression or equation.\n\n$saturation$ calls $idealquotient$ several times, until the result is\nstable, and returns it.\n\n\\subsection{Operators for Gr\\\"obner Bases in all Term Orderings}\n\\index{Hilbert polynomial}\nIn some cases where no Gr\\\"obner\nbasis with lexical ordering can be calculated, a calculation with a total\ndegree ordering is still possible. Then the Hilbert polynomial gives\ninformation about the dimension of the solutions space and for finite\nsets of solutions univariate polynomials can be calculated. The solutions\nof the equation system then is contained in the cross product of all\nsolutions of all univariate polynomials.\n\n\\subsubsection{Hilbertpolynomial: Hilbert Polynomial of an Ideal}\n\\ttindex{Hilbertpolynomial}\nThis algorithm was contributed by {\\sc Joachim Hollman}, Royal\nInstitute of Technology, Stockholm (private communication).\n\n\\[\nhilbertpolynomial (\\{exp1, \\ldots , expm\\})\\;;\n\\]\nwhere $\\{exp1, \\ldots , expm\\}$ is a list of any number of expressions\nor equations.\n\n$hilertpolynomial$ calculates the Hilbert polynomial of the ideal\nwith basis $\\{exp1, \\ldots , expm\\}$ with respect to the\nvariables given or extracted provided the given term ordering is\ncompatible with the degree, such as the $gradlex$- or $revgradlex$-ordering.\nThe term ordering of the basis\nmust be active and $\\{exp1, \\ldots$, $ expm\\}$ should be a\nGr\\\"obner basis with respect to this ordering. The Hilbert polynomial\ngives information about the cardinality of solutions of the system\n$\\{exp1, \\ldots , expm\\}$: if the Hilbert polynomial is an\ninteger, the system has only a discrete set of solutions and the\npolynomial is identical with the number of solutions counted with\ntheir multiplicities. Otherwise the degree of the Hilbert\npolynomial is the dimension of the solution space.\n\nIf the Hilbert polynomial is not a constant, it is constructed with the\nvariable ``x'' regardless of whether $x$ is member of\n$\\{var1, \\ldots , varn\\}$ or not. The value of this polynomial at\nsufficiently large numbers  ``x'' is the difference\nof the dimension of the linear vector space of all polynomials of degree\n$ \\leq x $ minus the dimension of the subspace of all polynomials of\ndegree $\\leq x $ which belong also to the ideal.\n\n$x$ must be an undefined variable or the value of $x$ must be an undefined\nvariable; otherwise a warning is given and a new (generated) variable\nis taken instead.\n \n\\paragraph{Remark:} The number of zeros in an ideal and the\nHilbert polynomial depend only on the leading terms of the\nGr\\\"obner basis. So if a subsequent Hilbert calculation is planned, the\nGr\\\"obner calculation should be performed with $on$ $gltbasis$ and\nthe value of $gltb$ (or its elements in a $groebnerf$ context) should be\ngiven to $hilbertpolynomial$. In this manner, a lot of computing time can be\nsaved in the case of long calculations.\n\n\\section{Calculations ``by Hand''}\nThe following operators support explicit calculations with\npolynomials in a distributive representation at the \\REDUCE \\  top level.\nSo they allow one to do Gr\\\"obner type evaluations stepwise by\nseparate calls. Note that the normal \\REDUCE \\  arithmetic can be used\nfor arithmetic combinations of monomials and polynomials.\n\n\\subsection{Representing Polynomials in Distributive Form}\n\\ttindex{gsort}\n\\[ gsort p; \\]\nwhere $p$ is a polynomial or a list of polynomials.\n\nIf $p$ is a single polynomial, the result is a reordered version of $p$\nin the distributive representation according to the variables and the\ncurrent term order mode; if $p$ is a list, its members are converted\ninto distributive representation and the result is the list sorted by\nthe term ordering of the leading terms; zero polynomials are\neliminated from the result.\n\n\\begin{verbatim}\n     torder({alpha,beta,gamma},lex);\n\n     dip := gsort(gamma*(alpha-1)**2*(beta+1)**2);\n\n\n                2     2                2\n    dip := alpha *beta *gamma + 2*alpha *beta*gamma\n\n           2                     2\n    + alpha *gamma - 2*alpha*beta *gamma - 4*alpha*beta*gamma\n\n                           2\n     - 2*alpha*gamma + beta *gamma + 2*beta*gamma + gamma\n\n \\end{verbatim}\n\n\\subsection{Splitting of a Polynomial into Leading Term and Reductum}\n\\ttindex{gsplit}\n\\[ gsplit p; \\]\nwhere $p$ is a polynomial.\n\n$gsplit$ converts the polynomial $p$ into distributive representation\nand splits it into leading monomial and reductum. The result is a list\nwith two elements, the leading monomial and the reductum.\n\n\\begin{verbatim}\n   gslit dip;\n\n          2     2\n    {alpha *beta *gamma,\n\n            2                   2                     2\n     2*alpha *beta*gamma + alpha *gamma - 2*alpha*beta *gamma\n\n                         2\n     - 4*alpha*beta*gamma - 2*alpha*gamma + beta *gamma\n\n\n     + 2*beta*gamma + gamma}\n\n \\end{verbatim}\n\n\\subsection{Calculation of Buchberger's S-polynomial}\n\\ttindex{gspoly}\n\\[ gspoly (p1,p2); \\]\nwhere $p1$  and $p2$ are polynomials.\n\n$gspoly$ calculates the $s$-polynomial from $p1$  and $p2$;\n\nExample for a complete calculation (taken from {\\sc Davenport et al.}\n \\cite{Davenport:88a}):\n\\begin{verbatim}\n   torder({x,y,z},lex)$\n   g1  :=  x**3*y*z - x*z**2;\n   g2  :=  x*y**2*z - x*y*z;\n   g3  :=  x**2*y**2 - z;$\n\n   % first S-polynomial\n\n   g4  :=  gspoly(g2,g3);$\n\n           2        2\n    g4 := x *y*z - z\n\n    % next S-polynomial\n\n    p :=  gspoly(g2,g4); $\n\n          2          2\n    p := x *y*z - y*z\n\n    % and reducing, here only by g4\n\n    g5  :=  preduce(p,{g4});\n\n                2    2\n    g5 :=  - y*z  + z\n\n    % last S-polynomial}\n\n    g6  :=  gspoly(g4,g5);\n\n           2  2    3\n    g6 := x *z  - z\n\n    % and the final basis sorted descending\n\n    gsort{g2,g3,g4,g5,g6};\n\n      2  2\n    {x *y  - z,\n\n      2        2\n     x *y*z - z ,\n\n      2  2    3\n     x *z  - z ,\n\n        2\n     x*y *z - x*y*z,\n\n           2    2\n      - y*z  + z }\n \\end{verbatim}\n\n\\bibliography{groebner}\n\\bibliographystyle{plain}\n\\end{document}\n\n", "meta": {"hexsha": "7f832b3da6138e8c809a78167dd3068578f8a61c", "size": 60460, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "packages/groebner/groebner.tex", "max_stars_repo_name": "arthurcnorman/general", "max_stars_repo_head_hexsha": "5e8fef0cc7999fa8ab75d8fdf79ad5488047282b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "packages/groebner/groebner.tex", "max_issues_repo_name": "arthurcnorman/general", "max_issues_repo_head_hexsha": "5e8fef0cc7999fa8ab75d8fdf79ad5488047282b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "packages/groebner/groebner.tex", "max_forks_repo_name": "arthurcnorman/general", "max_forks_repo_head_hexsha": "5e8fef0cc7999fa8ab75d8fdf79ad5488047282b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7875, "max_line_length": 83, "alphanum_fraction": 0.7055573933, "num_tokens": 18074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.3008393169684887}}
{"text": "\\section{Methodology}\r\n\\label{methodology}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\subsection{Dataset}\r\nIn this work, our previously generated dataset~\\cite{Ijjeh2021} was used for training various deep learning models.\r\nFurther, the generated dataset resembles measurements acquired by SLDV in the transverse direction (perpendicular to the plate surface).\r\nThe dataset contains 475 simulated cases of full wavefield of propagating Lamb waves in a plate made of carbon fibre-reinforced polymer (CFRP).\r\nFurther, the simulated cases represent the interaction of Lamb waves with different delamination scenarios.\r\nIn which, each simulated case in the dataset computed from the wave propagation model is a 3D matrix, which holds the amplitudes of the propagating waves at location \\((x,y)\\) and time \\((t)\\).\r\nHence, these matrices can be seen as animated frames at discrete time \\(t_k\\) of propagating waves.\r\nMoreover, it should be mentioned that the simulated delaminations were located closer to the top surface of the plate.\r\nAccordingly, it is easier to detect delamination by using the simulated full wavefield on the top surface of the plate instead of the bottom surface.\r\nHowever, to train our various models we applied the difficult case in which the full wavefield was registered at the bottom surface of the plate.\r\nTo enhance the visualisation, the root mean square depicted in Eq.~\\ref{ref:rms} was applied for the full wavefield frames.\r\n\\begin{equation}\r\n\t\\hat{s}(x,y) = \\sqrt{\\frac{1}{N}\\sum_{k=1}^{N} s(x,y,t_k)^2}\r\n\t\\label{ref:rms}\r\n\\end{equation}\r\nwhere \\(N\\) refers to the number of sampling points 512,  and \\((x,y)\\) refers to the location.\r\nFigures~\\ref{fig:rmstop} and \\ref{fig:rmsbottom} show the result of applying RMS to the full wavefield from the top and bottom surface of the plate respectively.\r\nThe dataset consisting of RMS images which were used in this research paper is available online~\\cite{Kudela2020d}.\r\n\\begin{figure} [h!]\r\n\t\\centering\r\n\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n\t\t\\centering\r\n\t\t\\includegraphics[scale=.29]{RMS_flat_shell_Vz_27_500x500top.png}\r\n\t\t\\caption{top}\r\n\t\t\\label{fig:rmstop}\r\n\t\\end{subfigure}\r\n\t\\hfill\r\n\t\\begin{subfigure}[b]{0.47\\textwidth}\r\n\t\t\\centering\r\n\t\t\\includegraphics[scale=.29]{RMS_flat_shell_Vz_27_500x500bottom.png}\r\n\t\t\\caption{bottom}\r\n\t\t\\label{fig:rmsbottom}\r\n\t\\end{subfigure}\r\n\t\\caption{RMS of the full wavefield from the top surface of the plate (a) and the bottom surface of the plate (b).}\r\n\\label{fig:rms}\r\n\\end{figure} \r\n\\subsection{Data preprocessing}\r\nTo enhance the performance of the optimizer during the training process, the colour scale values were normalized to a range of (\\(0-1\\)) instead of the initial scale which was in a range of (\\(0 - 255\\)).\t\r\nFurthermore, we have applied data augmentation on the dataset by flipping the images horizontally, vertically and diagonally. \r\nAs a result, the dataset size increased four times -- \\(1900\\)  images were produced.\r\nWe have split the dataset into two portions:  \\(80\\%\\) for the training set and \\(20\\%\\) for the testing set.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nMoreover, a cross-validation (CV) method was applied to the training set to reduce the overfitting which happens when the model is able to fit on the training data, while it poorly fit on the new unseen data.\r\nIn other words, the model only learns the patterns of the training data therefore the model will not generalise well. \r\n%Figure.~\\ref{fig:Cross_validation} illustrates the K-fold CV technique.\r\n%In this technique, we have split the training set into \\(K\\) small sets (folds), hence the name K-folds. \r\n%Therefore, we iterate over the training set K iterations.\r\n%During each iteration, the model uses  \\(K-1\\) folds for training and the remaining fold is used for validation. \r\n%In our models, we have chosen \\(K=5\\), therefore, we have \\(5\\) iterations of training. \r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%For each iteration, we compute the performance of the model.\r\n%Finally, we compute the cross-validation performance for all iterations as illustrated in Eqn.~(\\ref{eq:cv_performance}) as a mean value over the K performance estimations of the validation fold set.\r\nThe main advantage of the K-fold CV method versus a regular train/test split is to reduce the overfitting by utilising data more efficiently as every data sample is used in both training and validation. \r\nTherefore, by using this technique, we aim to improve the ability of the model to generalise and reduce the overfitting.\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\\begin{equation}\r\n%Final \\ Performance = \\frac{1}{K}\\sum_{i=1}^{K}Performace\r\n%\\label{eq:cv_performance}\r\n%\\end{equation}\r\n%\\begin{figure}\r\n%\t\\centering\r\n%\t\\includegraphics[scale=1.0]{cross_validation.png}\r\n%\t\\caption{K-fold Cross validation, K=\\(5\\).}\r\n%\t\\label{fig:Cross_validation}\r\n%\\end{figure}\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n", "meta": {"hexsha": "6e51c253f58ce2203d743c5ca3522795254db09f", "size": 5037, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "reports/journal_papers/MSSP_2/Fully_Convolutional_Network_approach.tex", "max_stars_repo_name": "IFFM-PAS-MISD/aidd", "max_stars_repo_head_hexsha": "9fb0ad6d5e6d94531c34778a66127e5913a3830c", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-03T05:36:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T05:36:07.000Z", "max_issues_repo_path": "reports/journal_papers/MSSP_2/Fully_Convolutional_Network_approach.tex", "max_issues_repo_name": "IFFM-PAS-MISD/aidd", "max_issues_repo_head_hexsha": "9fb0ad6d5e6d94531c34778a66127e5913a3830c", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "reports/journal_papers/MSSP_2/Fully_Convolutional_Network_approach.tex", "max_forks_repo_name": "IFFM-PAS-MISD/aidd", "max_forks_repo_head_hexsha": "9fb0ad6d5e6d94531c34778a66127e5913a3830c", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 71.9571428571, "max_line_length": 209, "alphanum_fraction": 0.7115346436, "num_tokens": 1209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.30081976223479745}}
{"text": "\\section{Introduction}\n\n%\\begin{itemize}\n%\\item Tuning is important in deep learning and tuning is hard.\n%\\item People do (a) adaptive (b) method with knob. (Fix momentum and only investigate lr).\n%\\item momentum accelerates. better understanding the behavior of momentum is interesting better tuner with less tuning. We revisit mom sgd and found the robustness to lr and variation. As well as related to async. And derive simple theory to analyze. \n%\\item These properties makes mom sgd a good candidate for auto tuning. We investigate a quadratic model and propose an simple and easy to understand tuner. It is faster than Adam\n%\\item We also connect to async theory and develope component and better than others in asynchrony.  \n%\\end{itemize}\n\n\\outline{[Problem.]}\n%Deep learning involves the use of very large datasets to fit large, complex models.\nAccelerated forms of stochastic gradient descent (SGD), pioneered by\n\\citet{polyak1964some} and \\citet{nesterov1983method}, are the de-facto\ntraining algorithms for deep learning.\nTheir use requires a sane choice for their {\\em hyperparameters}: \ntypically a {\\em learning rate} and {\\em momentum parameter} \\citep{sutskever2013importance}.\n\\outline{[Hardness.]}\n%Hyperparameter tuning is often cited as being the number-one factor in extracting good performance from deep learning systems. \n%It is by far the most time consuming phase of developing a new deep learning model or system.\n%One could say that tuning is {\\em the hidden cost of modern machine learning},\nHowever, tuning hyperparameters is arguably the most time-consuming part of deep learning, with thousands of grad-student-hours sacrificed and many papers outlining best tuning practices written\n\\cite{bengio2012practical,orr2003neural,bengio2012deep,bottou2012stochastic}.\n\n\\outline{[previous approach]}\nDeep learning researchers have proposed a number of methods to deal with hyperparameter optimization. \nNa\\\"ive methods, like the grid-search,\nare prohibitively expensive for all but the smallest problems. \nSmart black-box methods \\cite{bergstra2012random,snoek2012practical}\ndo not explicitly take into account the problem specifics and spend time testing multiple configurations.\nAdaptive methods provide an attractive alternative.\nThey aim to tune a single run on the fly and have been largely successful in relieving practitioners of tuning the learning rate. \nAlgorithms like Adagrad \\cite{duchi2011adaptive}, RMSProp \\cite{tieleman2012lecture} and Adam \\cite{kingma2014adam} use the magnitude of gradient elements to tune learning rates {\\em individually for each variable}. A common limitation of state-of-the-art adaptive methods is that they do not tune their momentum.\n%Finally, methods like the one proposed by \\citet{schaul2013no} use simple models and simple measurements to tune a global learning rate for the standard SGD update.\n\n\\outline{[limitation of previous approach]}\nMomentum is a fundamental parameter at the heart of the acceleration process, lending its name to the most ubiquitous accelerated method \\cite{polyak1964some}, simply dubbed {\\em momentum}.\nClassic \\cite{polyak1964some} and recent results \\cite{sutskever2013importance} alike show that proper momentum tuning has a significant impact on training speed. \n%Unfortunately, there exists no method that automatically tunes its momentum parameter.\n%Large-scale systems pose extra tuning challenges.\n\\jianedits{Momentum becomes even more critical on distributed systems. \nRecently, \\citet{mitliagkas2016asynchrony} showed that, in asynchronous-parallelization~\\cite{recht2011hogwild,dean2012large,chilimbi2014project,hadjis2016omnivore},\na technique for efficient distributed training without synchronization locks, \n%introduces additional momentum-like dynamics to momentum SGD, and\none can manually reduce algorithmic momentum to accelerate convergence~\\cite{hadjis2016omnivore}.\nAs part of a collaboration with an industry affiliate and a big research lab, we verify that tuning momentum dramatically improves convergence on thousand-node scales.\nHowever, grid-searching momentum on very large cluster jobs becomes especially challenging.\nWe believe that better understanding of momentum and its rich properties is interesting in its own right and could yield a next generation of adaptive methods that perform {\\em automatic momentum tuning}. }\n%Increasing model and dataset sizes motivate parallelization \\cite{dean2012large,chilimbi2014project,hadjis2016omnivore,chen2016revisiting}.\n% Asynchronous methods \\cite{recht2011hogwild} provide efficient parallelization by training without locking or synchronization.\n%The exact effect of asynchrony on the optimization process has been a mystery, though empirical results have shown great successes \\cite{recht2011hogwild,dean2012large,chilimbi2014project,hadjis2016omnivore}.\n%Recent work by \\citet{mitliagkas2016asynchrony} reveals that asynchrony introduces additional momentum-like dynamics to the optimization process,\n%a statement that can be made {\\em exact} for the momentum SGD algorithm.\n%\\jianedits{Recent work by \\citet{mitliagkas2016asynchrony} reveals that asynchrony introduces additional momentum-like dynamics to momentum SGD, and one can manually reduce algorithmic momentum to accelerate convergence~\\cite{hadjis2016omnivore}}.\n\n%As part of a collaboration with an industry affiliate and a big research lab, we had the opportunity to verify this phenomenon on thousand-node scales.\n%Tuning the momentum value improves convergence speed,\n%however grid-searching momentum values at that scale becomes challenging.\n%Recent work \\cite{hadjis2016omnivore} uses this theoretical understanding to perform targeted, efficient hyperparameter searches.\n%We believe that better understanding of momentum and its rich properties is interesting in its own right and could yield a next generation of adaptive methods with {\\em automatic momentum tuning}.\n\n\n%%%%%%%% old un smoothed version %%%%%%%%%%%%%%%%%%\n%%Large-scale systems pose extra tuning challenges.\n%Momentum tuning becomes even more critical on large-scale, parallel systems.\n%%Increasing model and dataset sizes motivate parallelization \\cite{dean2012large,chilimbi2014project,hadjis2016omnivore,chen2016revisiting}.\n% Asynchronous methods \\cite{recht2011hogwild} provide efficient parallelization by training without locking or synchronization.\n%The exact effect of asynchrony on the optimization process has been a mystery, though empirical results have shown great successes \\cite{recht2011hogwild,dean2012large,chilimbi2014project,hadjis2016omnivore}.\n%%Recent work by \\citet{mitliagkas2016asynchrony} reveals that asynchrony introduces additional momentum-like dynamics to the optimization process,\n%%a statement that can be made {\\em exact} for the momentum SGD algorithm.\n%\\jianedits{Recent work by \\citet{mitliagkas2016asynchrony} reveals that asynchrony introduces additional momentum-like dynamics to momentum SGD, and one can manually reduce algorithmic momentum to accelerate convergence~\\cite{hadjis2016omnivore}}.\n%\n%As part of a collaboration with an industry affiliate and a big research lab, we had the opportunity to verify this phenomenon on thousand-node scales.\n%Tuning the momentum value improves convergence speed,\n%however grid-searching momentum values at that scale becomes challenging.\n%Recent work \\cite{hadjis2016omnivore} uses this theoretical understanding to perform targeted, efficient hyperparameter searches.\n%We believe that better understanding of momentum and its rich properties is interesting in its own right and could yield a next generation of adaptive methods that also perform {\\em automatic momentum tuning}.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\begin{wrapfigure}[11]{R}{0.46\\textwidth}\n\\vspace{-1.0em}\n\\begin{minipage}{1.0\\linewidth}\n\\begin{figure}[H]\n\t\\includegraphics[width=1.0\\linewidth]{experiment_results/spotlight.pdf}\n\t\\caption{\\tuner comparing to Adam.}\n\\end{figure}\n\\end{minipage}\n\\end{wrapfigure}\nWe revisit the basic SGD update that uses Polyak's momentum and a single learning rate for all variables.\nWe empirically show that, when hand-tuned, momentum SGD achieves faster convergence than Adam for a large class of models.\nWe then formulate the optimization update as a dynamical system and study certain robustness properties of the momentum operator.\nBuilding on our analysis, we design \\tuner, an automatic hyperparameter tuner for momentum SGD.\n\\tuner tunes the learning rate and momentum on the fly, and uses a novel {\\em closed-loop control architecture} to compensate for the added dynamics of asynchrony.\nSpecifically:\n\\begin{itemize}[leftmargin=2em]\n\\item\nThe momentum operator's spectral radius is constant in a large subset of the hyperparameter space we call {\\em the robust region}.\nThis is a known, but relatively obscure property.\nOur analysis in Section~\\ref{sec:momentum_operator} gives a novel interpretation:\nmomentum is robust to learning rate misspecification and curvature variation,\ntwo desirable properties for deep learning.\n%\\item \n%We analyze the momentum operator in Section~\\ref{sec:momentum_operator} with focus on its spectral radius. More specifically, the spectral radius can be constant under conditions.\n%We expose previously unknown insights from the simple property: \n%the momentum operator can yield constant convergence rates even when the learning rate is grossly mis-tuned.\n%Furthermore, constant convergence rates are empirically possible for some non-convex objectives,\n%where curvature dramatically varies spatially.%  (a factor of more than $1000\\times$ when momentum is set to $0.9$).\n\\item\nIn Section~\\ref{sec:sync_tuner}, we use these insights and a simple quadratic model analysis to design \\tuner, an automatic tuner for momentum SGD.\n\\tuner uses on-the-fly measurements from the gradients of the system to tune both learning rate and momentum.\n%\\item We use these insights and the analysis of a quadratic model to design\n%\\tuner in Section~\\ref{sec:sync_tuner}. To tune the learning rate and momentum, the tuner minimize the squared distance from the minimum of a local quadratic approximation at each step of the algorithm.\n%\\item In Section~\\ref{sec:async_tuner}, we present the first asynchrony-aware tuner. \n%We first provide a measurement component to estimate the total amount of momentum in a running system, including the extra momentum due to asynchrony.  \n%Then, we propose \\asynctuner, a closed-loop version of \\tuner, that uses the measurement component and a negative feedback loop to bring the total amount of momentum to the levels suggested by the tuning rule.\n%\\item \n%Furthermore, \\tuner is {\\em asynchrony-aware}. \n%It uses a {\\em novel momentum-measurement mechanism} that is part of a {\\em closed-loop} design to automatically tune the value of momentum when asynchrony introduces extra momentum dynamics.\n\\item In Section~\\ref{sec:async_tuner}, we present \\asynctuner \n%an asynchrony-aware tuner. \n\\jianedits{for asynchronous training}.\n\\jianedits{It} measures the total momentum in a running system, including any asynchrony-induced momentum. \nThis measurement is used in a negative feedback loop to control the value of algorithmic momentum.% on the fly.\n%With the estimates, it use a negative feedback loop to bring the total momentum to the level suggested by \\asynctuner.\n\n%\\item We present an analysis of the momentum operator in Section~\\ref{sec:momentum_operator}.\n%We focus on the fact that its spectral radius is constant in a certain robust region.\n%We expose previously unknown insights that stem from that simple property: \n%the momentum operator can yield constant convergence rates even when the learning rate is grossly mis-tuned.\n%Furthermore, constant convergence rates are possible for certain non-convex objectives,\n%where curvature can vary dramatically (a factor of more than $1000\\times$ when momentum is set to $0.9$).\n\\end{itemize}\n\n%Asynchronous methods \\cite{recht2011hogwild} provide very efficient parallelization by doing away with locking and synchronization.\n\n%and propose \\tuner, an automatic tuner for its hyperparameters.\n%A key component of \\tuner is principled momentum-tuning in both synchronous and asynchronous settings.\n%\\tuner is competitive or better that state-of-the-art adaptive methods and is asynchrony-aware by using a novel design based on measuring the level of momentum on the fly and using a closed-loop control module for momentum.\n\n%\\outline{[OUR RESULTS]}\n%We demonstrate experimentally, in Section~\\ref{sec:experiments}, that\n%for a large class of networks, hand-tuned momentum SGD is competitive with Adam ($0.88-1.82\\times$), even though it uses fixed hyperparameters throughout execution.\n%On ResNets, momentum SGD can achieve a $1.25-1.82\\times$ speedup over Adam.\n%\\tuner is competitive with, and sometimes better, than state-of-the-art adaptive methods. The speedup is over $2\\times$ on ResNets and $1.18\\times$ on LSTMs.\n%Other adaptive algorithms do not tune their momentum parameter and suffer, as a result, in asynchronous settings.\n%Hand-tuning momentum for Adam can improve its convergence rate by up to $2\\times$, when using $16$ asynchronous workers. \n%Finally, closing the momentum loop in \\tuner yields a speedup of $1.3-3\\times$, when using $16$ asynchronous workers.\n%Closed-loop \\tuner achieves a speedup of about $2.7\\times$ over Adam on 16 asynchronous workers.\n%\\begin{itemize}\n%\\item For a large class of networks, hand-tuned momentum SGD is competitive with Adam ($0.88-1.82\\times$), even though it uses fixed hyperparameters throughout execution.\n%On ResNets, momentum SGD can achieve a $1.25-1.82\\times$ speedup over Adam.\n%\\item \\tuner is competitive with, and sometimes better, than state-of-the-art adaptive methods. The speedup is over $2\\times$ on ResNets and $1.18\\times$ on LSTMs.\n%\\item  Other adaptive algorithms do not tune their momentum parameter and suffer, as a result, in asynchronous settings.\n%Hand-tuning momentum for Adam can improve its convergence rate by up to $2\\times$, when using $16$ asynchronous workers.\n%\\item  Closing the momentum loop in \\tuner yields a speedup of $1.3-3\\times$, when using $16$ asynchronous workers.\n%Closed loop \\tuner achieves a speedup of about $2.7\\times$ over Adam on 16 asynchronous workers.\n%\\end{itemize}\n\n\n\\outline{[empirical performance statement on \\tuner]}\nWe introduce our contributions in Sections~\\ref{sec:momentum_operator},\\ref{sec:sync_tuner},\\ref{sec:async_tuner}.\nIn Section~\\ref{sec:experiments}, we demonstrate empirically that \n\\tuner offers \\jianedits{competitive or significantly better performance} compared to:\n(i) hand-tuned momentum SGD (a speedup of up to 2.3x);\nand (ii) hand-tuned Adam (up to 2.8x speedup).\n\t\\jianedits{In an asynchronous setting, we demonstrate that Adam, the state-of-the-art adaptive method, suffers from lack of momentum tuning.}\n%Specifically, when we hand-tune Adam's momentum, its asynchronous performance improves by at least 2.5x.\nIn the same setting, the closed-loop control architecture speeds up \\tuner by up to 2x, \n%closing \\tuner's momentum loop improves its performance by 1.5x-3x.\n\\jianedits{allowing \\Asynctuner to outperform Adam with a more than 2.7x speedup}.\n\\jianedits{As a conclusion, we present related work in Section~\\ref{sec:related} and discussion in Section~\\ref{sec:discussion}.}\n%We conclude with related work in Section~\\ref{sec:related} and discussion in Section~\\ref{sec:discussion}\n\n%We introduce our contributions in Sections~\\ref{sec:momentum_operator},\\ref{sec:sync_tuner},\\ref{sec:async_tuner}.\n%Section~\\ref{sec:experiments} gives experimental validation of our claims and we conclude with related work in Section~\\ref{sec:related} and discussion in Section~\\ref{sec:discussion}.\n", "meta": {"hexsha": "e5b012ba9fa2e9ecc8b69f126405df11d238228a", "size": 15781, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "hazygroup.papers/trunk/yellowfin_nips2017/auto_ml/intro.tex", "max_stars_repo_name": "mitliagkas/dshs", "max_stars_repo_head_hexsha": "6d5262af72288dd06544c2d5831d0c198db251bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hazygroup.papers/trunk/yellowfin_nips2017/auto_ml/intro.tex", "max_issues_repo_name": "mitliagkas/dshs", "max_issues_repo_head_hexsha": "6d5262af72288dd06544c2d5831d0c198db251bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hazygroup.papers/trunk/yellowfin_nips2017/auto_ml/intro.tex", "max_forks_repo_name": "mitliagkas/dshs", "max_forks_repo_head_hexsha": "6d5262af72288dd06544c2d5831d0c198db251bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 89.1581920904, "max_line_length": 313, "alphanum_fraction": 0.8057157341, "num_tokens": 3605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.30081976223479745}}
{"text": "\\chapter{Discussion}\nThe findings of the study lead to the following points of general interest, beginning with the pairwise interactions. For the $T^p - T^-$ pairwise competition, the limitation of testosterone for $T^p$ and that of oxygen for $T^-$ has a major influence on competition and its outcomes. Increasing the limitation of a given resource for one cell relative to the other leads to the more-limited cell going extinct, regardless of specific identity. Only when the limitations are balanced between two types was coexistence observed. Resource levels can therefore act as control levers of the strength of competitive interactions between cell types and therefore determine the feasibility of coexistence. In addition to resource limitations, the relative initial seeding proportion of the cells can push the outcome in favour of the dominant cell. $T^-$ in conventional terms has an advantage due to its shorter doubling time and the requirement of one less resource. A model that doesn’t account for explicit resource dynamics and limitations might therefore predict that $T^-$ always wins. Although competition coefficients can be made to disfavour $T^-$ , justification for such an artefact isn’t straightforward, particularly compared to the emergence of coexistence we observed in our model due to resource limitation effects.\n\nSimilar to $T^p - T^-$, the relative limitation for a given resource of one cell over the other, as well as the relative seeding proportion of the cells, both influence the outcomes of the $T^+ - T^p$ pairwise competition. Resource limitations can in fact be directly compared here unlike $T^p - T^-$, as both the cell types share the same qualitative resource dependencies. $T^p$ has an advantage over $T^+$ with oxygen limitations as the latter requires the former for testosterone. However, with testosterone limitation, $T^p$ has a disadvantage relative to $T^+$ as it would be doubly growth-limited by both testosterone and $T^+$ density. Even though symmetric limitation of a resource across both the cell types produces a similar effect, the difference with testosterone is much more pronounced than with oxygen limitation, possibly indicating a stronger dependence on testosterone for these two cell types.\n\nThe general trend discussed above holds for the three-way competition as well. Due to the doubling time advantage of $T^-$ and homogeneous limitations across cell types, testosterone limitations on $T^p$ and $T^+$ have a higher influence on maintaining coexistence between the cells. In this context, it has been possible to identify zones of resource limitation for both testosterone and oxygen where the system goes from coexistence to $T^-$ domination. Strong testosterone limitation without a numerical advantage of higher initial seeding density for $T^p$ leads to $T^-$ domination with no influence from oxygen. Weak testosterone limitation with a numerical advantage for $T^p$ leads to coexistence with no influence of oxygen. Meanwhile, in the other cases where testosterone limitation is intermediate, the outcomes of competition are pushed either towards coexistence or $T^-$ dominance by the oxygen limitation.\n\nThis framework used for studying competition alone then helps us understand the outcomes of therapy in mechanistic terms. $T^p$ and $T^+$ are the only cell types to depend on testosterone and hence only they respond to abiraterone. SOC creates an additional limitation of testosterone by reducing the production rates and hence pushes these two cell types to extinction. AT would have no influence where $T^p$ and $T^+$ are pushed to extinction by competition alone and maximum influence when the tumour is dominated by $T^p$ and $T^+$. The resource limitations and seeding proportions therefore have an influence on the success of AT. The success of AT also depends crucially on the therapy window. Higher window would lead to better success, but at the increased physiological cost of maintaining a larger tumour. Meanwhile, with a smaller window achieving control would be more difficult and there would be a higher risk of competitive release. While this mechanistic information makes for a thorough understanding of the system from first principles, it also highlights the gap between the modelling approach and clinical reality. It is clear that application of such ecologically-aware treatment strategies would also require a quantum shift in the nature of information that can be realistically obtained from a cancer patient over meaningful timescales.\n\nInsofar as eliminating the treatment-resistant cell type, all the therapy strategies we tried have been a failure. But, some of this failure has been informative, and it has been possible to avoid or delay competitive release in some cases by maintaining a non-zero population of the responsive cell types $T^+$ and $T^p$. This is broadly in line with current thinking in the field regarding the goals of AT, which are more focused on achieving control than a complete cure. It is worth noting however, that the total tumour burden even when control was achieved was very close to the model’s maximum effective carrying capacity. This could point to an important gap in the conceptualisation of AT that does not include the physiological cost of control over cure. It may then be worth investigating if AT could also be designed to address ways of minimising this cost alongside tumour control.\n\nThis study has been an attempt at a proof of concept to illustrate how ecological dynamics within a cancer system can inform progression as well as therapeutic decisions and outcomes. Based on its results so far, the following lines of further development are worth highlighting:\n\\begin{enumerate}\n  \\item The exploration of combination therapy in this study has been limited. While the effects of docetaxel in the model were determined based on available experimental data, the ways in which it can be applied are still open modelling questions that can include the frequency of docetaxel, the magnitude of the dose, and the phase shift between abiraterone and docetaxel. Methods of combination therapy other than docetaxel are also known clinically (radiation, steroids, etc) and some of these can be incorporated into the framework of the current model to understand the dynamics of combination therapy better.\n  \\item The cell types considered here are an oversimplification of actual cells in a biological system, which are highly variable in their functions and phenotypes. Cancer systems in particular can show an even higher degree of such heterogeneity due to their higher mutation rates and genomic instability. Bringing this to bear on the modelling approach we have taken, exploring a heterogeneity of cellular response across cell types to resource availability would be of interest here due to its strong influence on the outcomes of somatic competition and its effect on therapy. This is how pairwise competition has been explored in this study, and its extension to three-way competition should be informative.\n  \\item In addition to heterogeneity, the cells can also switch their phenotype based on environmental conditions due to phenotypic plasticity. While some theoretical studies have explored the effect of mutational changes within the context of cell competition \\cite{Snippert}, phenotypic plasticity remains understudied. It is possible, however, that implementing plasticity or heterogeneous responses would be much easier with an individual based model, which opens up whole new possibilities of exploring the ecological dynamics of the system.\n  \\item An individual-based model also allows for the addition of spatial heterogeneity to the system, which is an important component of biological variation in cancer populations. Solid tumours in particular have well-known gradients of resources between the tumour core and edge \\cite{Fontaine}, which could again open up even more channels of investigation.\n\\end{enumerate}\n\nThese are possible ways in which the current study could be extended and broadened in scope. However, a more general comment on the modelling approach itself is also justified at this point.\n\nMathematical modelling is a really powerful tool in biology which helps in understanding a system without use of an actual system for the main experimentation. This can be very useful when experimenting on the actual system or biological model is not possible due to ethics, health risks, etc. However, one must keep in mind that all biological models are simplifications and involve many assumptions. Quoting \\cite{Box} ``All models are wrong, but some are useful\". There are no objective criteria for what makes a good model, or a fair set of prior assumptions. Every model makes assumptions that are manifestations of constraints inherent to the mathematical framework and data availability.\n\nThe concept of carrying capacity in a logistic or Lotka-Volterra system is a debated topic and even more so in cancer systems \\cite{McLeod,Deisboeck}. Our model also assumes a carrying capacity derived from a rather arbitrary equilibrium value, $y_i^*$, given in \\autoref{K_eq}. However, this arbitrariness is partially alleviated since this carrying capacity is not explicitly fixed and instead is dynamically affected by the current concentration of resources. Nevertheless, it still suffers from the same setbacks of any model that invokes a carrying capacity, which is both difficult to define biologically (especially for cancer populations characterised by ``uncontrolled\" growth) and usually impossible to separate from the intrinsic growth rate. This leads to the possibility that a modelling approach that does not involve the carrying capacity at all where the resource availability is directly linked to growth rate in a consumer-resource type model may be better suited to study cancer systems that are typically at the edge of resource availability. Furthermore, comparing the differences between such alternate modelling strategies could itself form an informative study of modelling assumptions and their impact on inferences.\n\nThe inherently exponential nature of the model made it very sensitive to parameter values and to small fluctuations in environmental conditions. This is borne out particularly clearly in how this system responds to the application of therapy almost instantaneously. The rapidity of these responses could likely hide subtler dynamics that may be more accessible to a different modelling approach that is designed to pick up on them.\n\nOur modelling approach has been more mechanistic in nature than data driven. We have started with parameters from fundamental processes governing the system for the overall behaviour to emerge out of it. A data driven model on the other hand, fits the parameters to clinical data. One could argue that such a data driven model reflects closer to reality since it follows the same dynamics, however, such models don’t give valuable insight into these fundamental processes and act as black boxes. It may then be useful to explore ways of integrating clinical data more closely into mechanistic models, potentially resulting in mechanistic insight that can be applied more directly to clinical practice.\n", "meta": {"hexsha": "fdb651d7aed7e58afef594e8f862c70799d16c65", "size": 11264, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "writing/MSThesis/chapters/Discussion.tex", "max_stars_repo_name": "Harshavardhan-BV/Cancer-compe-strat", "max_stars_repo_head_hexsha": "e4decacd5779e85a68c81d0ce3bedf42dea2964f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-18T15:54:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-18T15:54:26.000Z", "max_issues_repo_path": "writing/MSThesis/chapters/Discussion.tex", "max_issues_repo_name": "Harshavardhan-BV/Cancer-compe-strat", "max_issues_repo_head_hexsha": "e4decacd5779e85a68c81d0ce3bedf42dea2964f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "writing/MSThesis/chapters/Discussion.tex", "max_forks_repo_name": "Harshavardhan-BV/Cancer-compe-strat", "max_forks_repo_head_hexsha": "e4decacd5779e85a68c81d0ce3bedf42dea2964f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 388.4137931034, "max_line_length": 1360, "alphanum_fraction": 0.818359375, "num_tokens": 2118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3008197622347974}}
{"text": "\\documentclass{article}\n\n\\input{preamble-articles}\n\n\\title{Notes on the smash product}\n\\author{Floris van Doorn \\and Stefano Piceghello}\n\\date{\\today}\n\\usepackage{fullpage}\n\\newcommand{\\pmap}{\\to}\n\\newcommand{\\lpmap}{\\xrightarrow}\n\\newcommand{\\smsh}{\\wedge}\n\\renewcommand{\\phi}{\\varphi}\n\\renewcommand{\\epsilon}{\\varepsilon}\n\\newcommand{\\tr}{\\cdot}\n\\renewcommand{\\o}{\\ensuremath{\\circ}}\n\\newcommand{\\auxl}{\\mathsf{auxl}}\n\\newcommand{\\auxr}{\\mathsf{auxr}}\n\\newcommand{\\gluel}{\\mathsf{gluel}}\n\\newcommand{\\gluer}{\\mathsf{gluer}}\n\\newcommand{\\sy}{^{-1}}\n\\newcommand{\\const}{\\ensuremath{\\mathbf{0}}\\xspace}\n\\newcommand{\\alphabar}{\\overline{\\alpha}}\n\\newcommand{\\rhobar}{\\overline{\\rho}}\n\\newcommand{\\lambdabar}{\\overline{\\lambda}}\n\\newcommand{\\gammabar}{\\overline{\\gamma}}\n\\newcommand{\\zeroh}{\\mathsf{z}}\n\\newcommand{\\oneh}{\\mathsf{u}}\n\\newcommand{\\two}{\\mathsf{b}}\n\\newcommand{\\twist}{\\mathsf{tw}}\n\\newcommand{\\mc}{\\mathcal}\n\n\\begin{document}\n\n\\maketitle\n\n\\section{Pointed Types}\n\n\\begin{defn}\n  We work in the $(\\infty,1)$-category of pointed types.\n  \\begin{itemize}\n  \\item The objects are pointed types $A$, types together with a basepoint $a_0:A$.\n\\item 1-cells are pointed maps $f:A\\to B$ which are maps with a chosen path $f_0:f(a_0)=b_0$. We\n  write $A\\pmap B$ for pointed maps and $A\\pmap B\\pmap C$ means $A\\pmap (B\\pmap C)$.\n\\item 2-cells are pointed homotopies. A pointed homotopy $h:f\\sim g$ is a homotopy with a chosen 2-path\n  $h(a_0) \\tr g_0 = f_0$.\n\\item As 3-cells (or higher cells) we take equalities between 2-cells (or higher cells).\n\\end{itemize}\n\\end{defn}\n\n\\begin{rmk}\\label{rmk:pointed-types}\n  All types, maps and homotopies in these notes are pointed, unless explicitly mentioned\n  otherwise. Whenever we say that a diagram of $n$-cells commutes we mean it in the sense that there\n  is an $(n+1)$-cell witnessing it.\n\\item Pointed homotopies are equivalent to equalities of pointed types: $(f\\sim g)\\equiv (f=g)$. So\n  we could have chosen to define our 2-cells as equalities between 1-cells. We choose not to, since\n  the aforementioned equivalence requires function extensionality. In a type theory where function\n  extensionality does not compute (like Lean) it is better to define the type of pointed homotopies\n  manually so that the underlying homotopy of a 2-cell is definitionally equal to the homotopy we\n  started with. In diagrams, we will denote pointed homotopies by equalities, but we always mean\n  pointed homotopies.\n\\item The type $A\\to B$ of pointed maps from $A$ to $B$ is itself pointed, with as basepoint the\n  constant map $0\\equiv0_{A,B}:A\\to B$ which has as underlying function $\\lam{a:A}b_0$. We have the homotopies:\n  \\begin{align*}\n  \\zeroh_g &: 0 \\o g \\sim 0 & \\zeroh'_f &: f \\o 0 \\sim 0\\\\\n  \\oneh_f &: f \\o \\idfunc \\sim f & \\oneh'_g &: \\idfunc \\o g \\sim g\n  \\end{align*}\n  satisfying\n  \\begin{align*}\n  \\zeroh_{\\idfunc} &= \\oneh_0 & \\zeroh'_{\\idfunc} &= \\oneh'_0 \\\\\n  \\zeroh_0 &= \\zeroh'_0 & \\oneh_{\\idfunc} &= \\oneh'_{\\idfunc}\n  \\end{align*}\n\\item A pointed equivalence is a pointed map $f : A \\to B$ whose underlying map is an\n  equivalence. In this case, we can find a pointed map $f\\sy:B\\to A$ with pointed homotopies\n  $f\\o f\\sy\\sim0$ and $f\\sy\\o f\\sim0$.\n\\end{rmk}  \n\n\\begin{defn}\\label{def:b-and-tw}\nWe define the pointed equivalences:\n  \\[\\two : (\\bool \\to X) \\simeq X\\] where $\\bool$ is the type of booleans (pointed in $0_\\bool$) with underlying map defined with $\\two(f) \\defeq f(1_\\bool)$, and\n  \\[\\twist : (A \\to B \\to X) \\simeq (B \\to A \\to X)\\]\n  with underlying map defined with $\\twist(f) \\defeq \\lam{b}\\lam{a}f(a)(b)$.\n\\end{defn}\n\n\\begin{lem}\\label{lem:composition-pointed}\n  Given maps $f:A'\\pmap A$ and $g:B\\pmap B'$. Then there are maps\n  $(f\\pmap C):(A\\pmap C)\\pmap(A'\\pmap C)$ and $(C\\pmap g):(C\\pmap B)\\pmap(C\\pmap B')$ given by\n  precomposition with $f$, resp. postcomposition with $g$. The map $\\lam{g}C\\pmap g$ preserves the basepoint, giving rise to a map $$(C\\pmap ({-})):(B\\pmap B')\\pmap(C\\pmap B)\\pmap(C\\pmap B').$$\n  Also, the following square commutes:\n\\begin{center}\n\\begin{tikzcd}\n(A\\pmap B) \\arrow[r,\"A\\pmap g\"]\\arrow[d,\"f\\pmap B\"] & (A\\pmap B')\\arrow[d,\"f\\pmap B'\"] \\\\\n(A'\\pmap B) \\arrow[r,\"A'\\pmap g\"] & (A'\\pmap B')\n\\end{tikzcd}\n\\end{center}\n\n\\end{lem}\n\n\\section{Naturality and a version of the Yoneda lemma}\n\n\\begin{defn}\\label{def:naturality}\n\tA (1-coherent) \\emph{functor} $F$ between pointed types is a function $F_0:\\type^*\\to\\type^*$ with an action of morphisms $F_1 : (A \\to^* B) \\to (FA \\to^* FB)$ such that $F_1(g \\o f)\\sim F_1g \\o F_1 f$ and $F_1\\idfunc[A]\\sim\\idfunc[F_0A]$. We will write both $F_0$ and $F_1$ as $F$. A functor $F$ is \\emph{pointed} if $F\\unit$ is contractible. In this case $F0_{A,B}\\sim 0_{FA,FB}$.\n\tLet $F$, $G$ be functors of pointed types. Suppose that we have a transformation $\\theta_X : F(X) \\to G(X)$ for all pointed types $X$. \n\t% \\begin{center}\n\t% \\begin{tikzcd}\n\t% \tF(A)\n\t% \t\t\\arrow[r, \"F(f)\"]\n\t% \t\t\\arrow[d, swap, \"\\theta_A\"]\n\t% \t& F(B)\n\t% \t\t\\arrow[d, \"\\theta_B\"]\n\t% \t\\\\\n\t% \tG(A)\n\t% \t\t\\arrow[r, swap, \"G(f)\"]\n\t% \t& G(B)\n\t% \\end{tikzcd}\n\t% \\end{center}\n\tWe define the following notions of naturality for $\\theta$:\n\t\\begin{itemize}\n\t\t\\item \\textbf{naturality} will refer to a pointed homotopy\n\t\t\\[p_\\theta(f) : G(f) \\o \\theta_A \\sim \\theta_B \\o F(f)\\]\n\t\tfor every $f : A \\to B$ and \\textbf{weak naturality} to the underlying (non-pointed) homotopy;\n\t\t\\item \\textbf{pointed naturality} will refer to the same pointed homotopy, with the additional condition that $p_\\theta(0) = (p_\\theta)_0$, where\n\t\t\\[(p_\\theta)_0 : G(0) \\o \\theta_A \\sim 0 \\o \\theta_A \\sim 0 \\sim \\theta_B \\o 0 \\sim \\theta_B \\o F(0)\\]\n\t\tis the canonical proof of the pointed homotopy $G(0) \\o \\theta_A \\sim \\theta_B \\o F(0)$, whereas \\textbf{pointed weak naturality} will refer to the corresponding non-pointed condition.\n\t\\end{itemize}\n\\end{defn}\n\n\\begin{rmk}\n\tThe relation between the four notions of naturality is as expected: naturality implies weak naturality, and pointed implies simple. Weak naturality is generally ill-behaved: for example, weak naturality of $\\theta$ does not imply weak naturality of $\\theta \\to X$ or $X \\to \\theta$, whereas the implication holds for naturality.\n\\end{rmk}\n\n\\begin{rmk}\n\tThe equivalences $\\two$ and $\\twist$ as defined in \\autoref{def:b-and-tw} are natural in all their arguments and pointed natural in the last argument.\n\\end{rmk}\n\n\\begin{lem}[Yoneda]\\label{lem:yoneda}\n\tLet $A$, $B$ be pointed types, and assume, for all pointed types $X$, a pointed equivalence $\\phi_X : (B \\to X) \\simeq (A \\to X)$, natural in $X$, i.e. for all $f : X \\to X'$ there is a pointed homotopy \\[ p_\\phi(f) : (A \\to f) \\o \\phi_X \\sim \\phi_{X'} \\o (B \\to f) \\]\n%\t making the following diagram commute for all $f : X \\to X'$:\n%\t\\begin{center}\n%\t\\begin{tikzcd}\n%\t\t(B \\to X)\n%\t\t\t\\arrow[r, \"\\phi_X\"]\n%\t\t\t\\arrow[d, swap, \"f \\o -\"]\n%\t\t& (A \\to X)\n%\t\t\t\\arrow[d, \"f \\o -\"]\n%\t\t\\\\\n%\t\t(B \\to X')\n%\t\t\t\\arrow[r, swap,\"\\phi_{X'}\"]\n%\t\t& (A \\to X')\n%\t\\end{tikzcd}\n%\t\\end{center}\n\tThen there exists a pointed equivalence $\\psi_\\phi : A \\simeq B$.\n\\end{lem}\n\\begin{proof}\n\tWe define $\\psi_\\phi \\defeq \\phi_B(\\idfunc[B]) : A \\to B$ and $\\psi_\\phi\\sy \\defeq \\phi_A\\sy(\\idfunc[A]):B\\to A$. The given naturality square for $f \\defeq \\psi_\\phi\\sy$ yields $\\psi_\\phi\\sy \\o \\phi_B (\\idfunc[B]) \\judgeq \\psi_\\phi\\sy \\o \\psi_\\phi \\sim \\phi_A (\\psi_\\phi\\sy \\o \\idfunc[B]) \\judgeq \\phi_A (\\phi_A\\sy (\\idfunc[A])) \\sim \\idfunc[A]$, and similarly for the inverse composition.\n\\end{proof}\n\n\\begin{lem}\\label{lem:yoneda-pointed}\n\tAssume $A$, $B$, $\\phi_X$ and $p$ as in \\autoref{lem:yoneda}, and assume moreover that $\\phi$ is pointed natural. Then there is a pointed homotopy $(\\psi_\\phi \\to X) \\sim \\phi_X$.\n\\end{lem}\n\n\\begin{proof}\n\tLet $f : B \\to X$. The underlying homotopy is obtained by:\n\t\\begin{align*}\n\t\t(\\psi_\\phi \\to X)(f) &\\judgeq f \\o \\psi_\\phi\\\\\n\t\t&\\sim \\phi_X (f \\o \\idfunc) &&\\text{(by $p_\\phi(f)(\\idfunc)$)}\\\\\n\t\t&\\sim \\phi_X (f) &&\\text{(by $\\mapfunc{\\phi_X}(\\oneh_f)$)}\n\t\\end{align*}\n\tTo show that this is a pointed homotopy, we need to prove that the following diagram commutes:\n\t\\begin{center}\n\t\\begin{tikzcd}[column sep=4em]\n\t\t(\\psi_\\phi \\to X)(0)\n\t\t\t\\arrow[rr, equals, \"p_\\phi(0)(\\idfunc)\\tr\\mapfunc{\\phi_X}(\\oneh_0)\"]\n\t\t\t\\arrow[dr, equals, swap, \"\\zeroh_{\\psi_\\phi}\"]\n\t\t&&\\phi_X(0)\n\t\t\t\\arrow[dl, equals, \"(\\phi_X)_0\"]\n\t\t\\\\\n\t\t&0\n\t\\end{tikzcd}\n\t\\end{center}\n\twhere the top-left expression is definitionally equal to $0 \\o \\phi_X(\\idfunc)$, the horizontal path comes from the underlying homotopy and $(\\phi_X)_0$ is the canonical path from $\\phi_X(0)$ to $0$. Since $\\phi_X$ is pointed natural, we have that\n\t$p_{\\phi_X}(0)(\\idfunc) = (p_{\\phi_X})_0(\\idfunc)$, which, in this case, is the concatenation:\n\t\\begin{align*}\n\t0\\o \\phi_X(\\idfunc)\n\t&= 0 &&\\text{(by $\\zeroh_{q_X(\\idfunc)}$)}\\\\\n\t&= \\phi_X(0) &&\\text{(by $(\\phi_X)_0\\sy$)}\\\\\n\t&= \\phi_X(0\\o 1) &&\\text{(by $(\\mapfunc{\\phi_X}(\\zeroh_{\\idfunc}))\\sy$)}\n\t\\end{align*}\n\tThe diagram then commutes by cancellation of inverses and using that $\\zeroh_{\\idfunc} = \\oneh_0$.\n\\end{proof}\n\n\\section{Smash Product}\\label{sec:smash}\n\n\\begin{defn}\n  The smash of $A$ and $B$ is the HIT generated by the point constructor $(a,b)$ for $a:A$ and $b:B$\n  and two auxilliary points $\\auxl,\\auxr:A\\smsh B$ and path constructors $\\gluel_a:(a,b_0)=\\auxl$\n  and $\\gluer_b:(a_0,b)=\\auxr$ (for $a:A$ and $b:B$). $A\\smsh B$ is pointed with point $(a_0,b_0)$.\n\\end{defn}\n\\begin{rmk}\n  This definition of $A\\smsh B$ is basically the pushout of\n  $\\bool\\leftarrow A+B\\to A \\times B$.  A more traditional definition of $A\\smsh B$ is the pushout\n  $\\unit\\leftarrow A\\vee B\\to A \\times B$; here $\\vee$ denotes the wedge product, which can be\n  equivalently described as either the pushout $A\\leftarrow \\unit\\to B$ or\n  $\\unit\\leftarrow \\bool\\to A + B$. These two definitions of $A\\smsh B$ are equivalent, because in\n  the following diagram the top-left square and the top rectangle are pushout squares, hence the\n  top-right square is a pushout square by applying the pushout lemma. Another application of the\n  pushout lemma then states that the two definitions of $A\\smsh B$ are equivalent.\n\\begin{center}\n\\begin{tikzcd}\n\\bool \\arrow[r]\\arrow[d] & A+B     \\arrow[r]\\arrow[d] & \\bool \\arrow[d] \\\\\n\\unit \\arrow[r]          & A\\vee B \\arrow[r]\\arrow[d] & \\unit \\arrow[d] \\\\\n                     & A\\times B        \\arrow[r] & A\\smsh B\n\\end{tikzcd}\n\\end{center}\n\n\\end{rmk}\n\\begin{lem}\\label{lem:smash-general}\n\tThe smash product is functorial: if $f:A\\pmap A'$ and $g:B\\pmap B'$ then\n    $f\\smsh g:A\\smsh B\\pmap A'\\smsh B'$. We write $A\\smsh g$ or $f\\smsh B$ if one of the\n    functions is the identity function. Moreover, if $p:f\\sim f'$ and $q:g\\sim g'$ then $p\\smsh q:f\\smsh g\\sim f'\\smsh g'$; this operation preserves reflexivities, symmetries and transitivies. We will write $p \\smsh g$ or $f \\smsh q$ if one of the homotopies is reflexivity.\n%\tThe smash product satisfies the following properties.\n%  \\begin{itemize}\n%  \\item The smash product is functorial: if $f:A\\pmap A'$ and $g:B\\pmap B'$ then\n%    $f\\smsh g:A\\smsh B\\pmap A'\\smsh B'$. We write $A\\smsh g$ or $f\\smsh B$ if one of the\n%    functions is the identity function.\n%  \\item The smash product preserves composition, which gives rise to the interchange law:\n%    \\[i:(f' \\o f)\\smsh (g' \\o g) \\sim f' \\smsh g' \\o f \\smsh g\\]\n%  \\item If $p:f\\sim f'$ and $q:g\\sim g'$ then $p\\smsh q:f\\smsh g\\sim f'\\smsh g'$. This operation\n%    preserves reflexivities, symmetries and transitivies.\n%  \\item There are homotopies $f\\smsh0\\sim0$ and $0\\smsh g\\sim 0$ such that the following diagrams\n%    commute for given homotopies $p : f\\sim f'$ and $q : g\\sim g'$.\n%    \\begin{center}\n%\\begin{tikzcd}\n%f\\smsh 0 \\arrow[rr, equals,\"p\\smsh1\"]\\arrow[dr,equals] & &\n%f'\\smsh 0\\arrow[dl,equals] \\\\\n%& 0 &\n%\\end{tikzcd}\n%\\qquad\n%\\begin{tikzcd}\n%0\\smsh g\\arrow[rr, equals,\"1\\smsh q\"]\\arrow[dr,equals] & &\n%0\\smsh g'\\arrow[dl,equals] \\\\\n%& 0 &\n%\\end{tikzcd}\n%\\end{center}\n%\\end{itemize}\n\\end{lem}\n\n\\begin{lem}\\label{lem:interchange}\n\tThe smash product preserves composition, which gives rise to the interchange law:\n    \\[i:(f_2 \\o f_1)\\smsh (g_2 \\o g_1) \\sim f_2 \\smsh g_2 \\o f_1 \\smsh g_1\\]\n    for maps $A_1\\lpmap{f_1}A_2\\lpmap{f_2}A_3$ and $B_1\\lpmap{g_1}B_2\\lpmap{g_2}B_3$.\n\\end{lem}\n\\begin{proof}\n\tLet us denote the basepoints of $A_i$ and $B_i$ with $a_i$ and $b_i$ respectively. We first apply induction on the paths that all the maps in the statement respect the basepoint. We verify the underlying homotopy of $i$ by induction on terms $x$ of the domain $A_1 \\smsh B_1$ of the two maps; this can be defined on point constructors $(a,b)$, $\\auxl$ and $\\auxr$ to be the identity path. If $x$ varies over $\\gluel_a$, we need to fill the following square:\n\t\\begin{equation}\\label{eq:i-gluel}\n\t\\begin{tikzcd}\n\t\t(f_2(f_1(a)), b_3)\n\t\t\t\\arrow[r,equals,\"1\"]\n\t\t\t\\arrow[d,swap,equals,\"\\mapfunc{(f_2 \\o f_1)\\smsh (g_2 \\o g_1)}(\\gluel_a)\"]\n\t\t& (f_2(f_1(a)), b_3)\n\t\t\t\\arrow[d,equals,\"\\mapfunc{f_2 \\smsh g_2 \\o f_1 \\smsh g_1}(\\gluel_a)\"]\n\t\t\\\\\n\t\t\\auxl\n\t\t\t\\arrow[r,swap,equals,\"1\"]\n\t\t&\\auxl\n\t\\end{tikzcd}\n\t\\end{equation}\n\tThis reduces to proving that\n\t\\[\\mapfunc{(f_2(f_1(a)),-)}(g_2\\o g_1)_0 \\tr \\gluel_{f_2(f_1(a))} = \\mapfunc{(f_2(f_1(a)),-)}(\\mapfunc{g_2}{(g_1)}_0 \\tr {(g_2)}_0) \\tr \\gluel_{f_2(f_1(a))}\\]\n\tSince we assumed that ${(g_1)}_0$ and ${(g_2)}_0$ are the identity path, the claim is easily verified. The case for $x$ varying over $\\gluer_b$ is entirely analogous, giving the square:\n\t\\begin{equation}\\label{eq:i-gluer}\n\t\\begin{tikzcd}\n\t\t(a_3, g_2(g_1(b))\n\t\t\t\\arrow[r,equals,\"1\"]\n\t\t\t\\arrow[d,swap,equals,\"\\mapfunc{(f_2 \\o f_1)\\smsh (g_2 \\o g_1)}(\\gluer_b)\"]\n\t\t& (a_3, g_2(g_1(b))\n\t\t\t\\arrow[d,equals,\"\\mapfunc{f_2 \\smsh g_2 \\o f_1 \\smsh g_1}(\\gluer_b)\"]\n\t\t\\\\\n\t\t\\auxr\n\t\t\t\\arrow[r,swap,equals,\"1\"]\n\t\t&\\auxr\n\t\\end{tikzcd}\n\t\\end{equation}\n\tThe resulting homotopy is pointed, as $i(a_1,b_1) \\judgeq 1$ and the proofs that the two maps respect the basepoint are assumed to be the identity path.\n\\end{proof}\n\n\\begin{lem}\\label{lem:smash-zero}\n\tThere are homotopies \n\t\\begin{align*}\n\tt_g : 0\\smsh g\\sim 0 && t'_f : f\\smsh0\\sim0\n\t\\end{align*}\n\tsuch that the following diagrams\n    commute for given homotopies $p : g\\sim g'$ and $q : f\\sim f'$.\n    \\begin{equation}\\label{eq:t-triangles}\n\t\\begin{tikzcd}\n\t0\\smsh g\n\t\t\\arrow[rr, equals,\"1\\smsh p\"]\n\t\t\\arrow[dr,equals,swap,\"t_g\"]\n\t&& 0\\smsh g'\\arrow[dl,equals,\"t_{g'}\"]\n\t&f\\smsh 0\n\t\t\\arrow[rr, equals,\"q\\smsh 1\"]\n\t\t\\arrow[dr,equals,swap, \"t'_f\"]\n\t&& f'\\smsh 0\\arrow[dl,equals,\"t'_{f'}\"]\n\t\\\\\n\t& 0\n\t&&& 0\n\t\\end{tikzcd}\n%\t\\qquad\\qquad\n%\t\\begin{tikzcd}\n%\tf\\smsh 0\n%\t\t\\arrow[rr, equals,\"q\\smsh 1\"]\n%\t\t\\arrow[dr,equals,swap, \"t'_f\"]\n%\t&& f'\\smsh 0\\arrow[dl,equals,\"t'_{f'}\"]\n%\t\\\\\n%\t& 0\n%\t\\end{tikzcd}\n\t\\end{equation}\n\\end{lem}\n\\begin{proof}\n\tWe will define the homotopy $t_g : 0 \\smsh g$, with $0 : A_1 \\to A_2$ and $g : B_1 \\to B_2$ (with the notational convention for the basepoints as in \\autoref{lem:interchange}); the definition for $t'_f$ is analogous. First, we apply induction on the path that $g$ respects the basepoint. The underlying homotopy of $t_g$ is given by induction on terms $x : A_1 \\smsh B_1$. On point constructors, we define:\n\t\\begin{align*}\n\tt_g (a,b) &\\defeq \\gluer_{g(b)} \\tr \\gluer_{b_2}\\sy && : (a_2, g(b)) = (a_2, b_2)\\\\\n\tt_g (\\auxl) &\\defeq \\gluel_{a_2}\\sy && : \\auxl = (a_2, b_2)\\\\\n\tt_g (\\auxr) &\\defeq \\gluer_{b_2}\\sy && : \\auxr = (a_2, b_2)\n\t\\end{align*}\n\tIf $x$ varies over $\\gluel_a$, after some reductions, we need to fill the following square:\n\t\\begin{equation}\\label{eq:t-gluel}\n\t\\begin{tikzcd}[column sep=7em]\n\t\t(a_2, g(b_1))\n\t\t\t\\arrow[r,equals,\"\\gluer_{b_2} \\tr \\gluer_{b_2}\\sy\"]\n\t\t\t\\arrow[d,swap,equals, \"\\gluel_{a_2}\"]\n\t\t& (a_2, b_2)\n\t\t\t\\arrow[d,equals,\"1\"]\n\t\t\\\\\n\t\t\\auxl\n\t\t\t\\arrow[r,swap,equals, \"\\gluel_{a_2}\\sy\"]\n\t\t& (a_2, b_2)\n\t\\end{tikzcd}\n\t\\end{equation}\n\tSimilarly, if $x$ varies over $\\gluer_b$, we need to fill the following square:\n\t\\begin{equation}\\label{eq:t-gluer}\n\t\\begin{tikzcd}[column sep=7em]\n\t\t(a_2, g(b))\n\t\t\t\\arrow[r,equals,\"\\gluer_{g(b)} \\tr \\gluer_{b_2}\\sy\"]\n\t\t\t\\arrow[d,swap,equals, \"\\gluer_{g(b)}\"]\n\t\t& (a_2, b_2)\n\t\t\t\\arrow[d,equals,\"1\"]\n\t\t\\\\\n\t\t\\auxr\n\t\t\t\\arrow[r,swap,equals, \"\\gluer_{b_2}\\sy\"]\n\t\t& (a_2, b_2)\n\t\\end{tikzcd}\n\t\\end{equation}\n\tThe squares in (\\ref{eq:t-gluel}) and (\\ref{eq:t-gluer}) can both be filled by simple path algebra. The resulting homotopy is pointed, as $t_g(a_1,b_1)$ is equal to the identity path and the proof that $g$ respects the basepoint is also assumed to be the identity path. Finally, for $p : g \\sim g'$, the diagram on the left in (\\ref{eq:t-triangles}) commutes by induction on $p$.\n\\end{proof}\n\n\\begin{lem}\\label{lem:smash-coh}\n \tSuppose that we have maps $A_1\\lpmap{f_1}A_2\\lpmap{f_2}A_3$ and $B_1\\lpmap{g_1}B_2\\lpmap{g_2}B_3$\n \tand suppose that either $f_1$ or $f_2$ is constant. Then there are two homotopies\n  $(f_2 \\o f_1)\\smsh (g_2 \\o g_1)\\sim 0$, one which uses the interchange law and one which does not. These two homotopies are equal. Specifically, the following two diagrams commute:\n\t\\begin{center}\n\t\\begin{tikzcd}\n\t\t(f_2 \\o 0)\\smsh (g_2 \\o g_1)\n\t\t\t\\arrow[r, equals, \"i\"]\n\t\t\t\\arrow[dd, swap, equals, \"\\zeroh' \\smsh (g_2 \\o g_1)\"]\n\t\t&(f_2 \\smsh g_2)\\o (0 \\smsh g_1)\n\t\t\t\\arrow[d, equals, \"(f_2 \\smsh g_2) \\o t_{g_1}\"]\n\t\t\\\\\n\t\t& (f_2 \\smsh g_2)\\o 0\n\t\t\t\\arrow[d,equals, \"\\zeroh'\"]\n\t\t\\\\\n\t\t0\\smsh (g_2 \\o g_1)\n\t\t\t\\arrow[r,equals, swap, \"t_{g_2 \\o g_1}\"]\n\t\t& 0\n\t\\end{tikzcd}\n\t\\qquad\n\t\\begin{tikzcd}\n\t\t(0 \\o f_1)\\smsh (g_2 \\o g_1)\n\t\t\t\\arrow[r, equals, \"i\"]\n\t\t\t\\arrow[dd, swap, equals, \"\\zeroh \\smsh (g_2 \\o g_1)\"]\n\t\t& (0 \\smsh g_2)\\o (f_1 \\smsh g_1)\n\t\t\t\\arrow[d,equals, \"t_{g_2} \\o (f_1 \\smsh g_1)\"]\n\t\t\\\\\n\t\t& 0\\o (f_1 \\smsh g_1)\n\t\t\t\\arrow[d,equals, \"\\zeroh\"]\n\t\t\\\\\n\t\t0\\smsh (g_2 \\o g_1)\n\t\t\t\\arrow[r,swap, equals, \"t_{g_2 \\o g_1}\"]\n\t\t& 0\n\t\\end{tikzcd}\n\t\\end{center}\n\n\\end{lem}\n\\begin{proof}\n%  We will only do the case where $f_1\\jdeq 0$, i.e. fill the diagram on the left. The other case is similar (and slightly easier).\n\t\n\t\\textbf{Case $f_1\\judgeq 0$ (diagram on the left)}. First apply induction on the paths that $f_2$, $g_1$ and $g_2$\n  respect the basepoint. In this case $f_2\\o0$ is definitionally equal to $0$, and the canonical\n  proof that $f_2\\o 0\\sim0$ is (definitionally) equal to reflexivity. This means that the homotopy\n  $(f_2 \\o 0)\\smsh (g_2 \\o g_1)\\sim0\\smsh (g_2 \\o g_1)$ is also equal to reflexivity, and also the\n  path that $f_2 \\smsh g_2$ respects the basepoint is reflexivity, hence the homotopy\n  $(f_2 \\smsh g_2)\\o 0\\sim0$ is also reflexivity. This means we need to fill the following square:\n\t\\begin{center}\n\t\\begin{tikzcd}\n\t\t(f_2 \\o 0)\\smsh (g_2 \\o g_1)\n\t\t\t\\arrow[r, equals,\"i\"]\n\t\t\t\\arrow[d, swap, equals,\"1\"]\n\t\t& (f_2 \\smsh g_2)\\o (0 \\smsh g_1)\n\t\t\t\\arrow[d,equals,\"(f_2\\smsh g_2)\\o t_{g_1}\"]\n\t\t\\\\\n\t\t0 \\smsh (g_2 \\o g_1)\n\t\t\t\\arrow[r, swap, equals,\"t_{g_1 \\o g_2}\"]\n\t\t& 0\n\t\\end{tikzcd}\n\t\\end{center}\n  For the underlying homotopy, take $x : A_1\\smsh B_1$ and apply induction on $x$. Suppose\n  $x\\equiv(a,b)$ for $a:A_1$ and $b:B_1$. With the notational convention for basepoints as in \\autoref{lem:interchange}, we have to fill the square (we use that the paths that the maps respect the basepoints are reflexivity):\n  \\begin{equation}\\label{eq:pent-left-ab}\n    \\begin{tikzcd}[column sep=5em]\n\t(a_3,g_2(g_1(b)))\n      \t\\arrow[r, equals,\"1\"]\n      \t\\arrow[d,swap,equals,\"1\"]\n\t\t%\\arrow[d,equals,\"\\gluer_{g_2(g_1(b))}\\tr\\gluer_{g_2(g_1(b_1))}\\sy\"]\n\t& (a_3,g_2(g_1(b)))\n\t\t\\arrow[d,equals,\"\\mapfunc{f_2\\smsh g_2}(\\gluer_{g_1(b)}\\tr\\gluer_{b_2}\\sy)\"]\n\t\\\\\n\t(a_3,g_2(g_1(b)))\n\t\t\\arrow[r,swap,equals,\"\\gluer_{g_2(g_1(b))}\\tr\\gluer_{b_3}\\sy\"]\n\t& (a_3,b_3)\n    \\end{tikzcd}\n    \\end{equation}  \n   Now $\\mapfunc{h\\smsh k}(\\gluer_z)=\\gluer_{k(z)}$, so by general groupoid laws we see that the path on the bottom is equal to the path on the right, which means we can fill the square. For the other point constructors, the squares to fill are similar: if $x \\judgeq \\auxl$, we have:\n      \\begin{equation}\\label{eq:pent-left-auxl}\n    \\begin{tikzcd}[column sep=5em]\n      \\auxl \\arrow[r, equals,\"1\"]\n      \\arrow[d,swap,equals,\"1\"] &\n      \\auxl \\arrow[d,equals,\"\\mapfunc{f_2\\smsh g_2}(\\gluel_{a_2}\\sy)\"] \\\\\n      \\auxl \\arrow[r,swap, equals,\"\\gluel_{a_3}\\sy\"] &\n      (a_3,b_3)\n    \\end{tikzcd}\n \\end{equation}\n\twhich we can fill, as the path on the bottom is definitionally equal to $\\gluel_{a_3}\\sy$ (as we applied path induction on the path that $f_2$ respects the basepoint) and the path on the right  also reduces to $\\gluel_{a_3}\\sy$ using that $\\mapfunc{h\\smsh k}(\\gluel_z)=\\gluel_{h(z)}$. Similarly, we can fill the square for $x \\judgeq \\auxr$, which is:\n  \\begin{equation}\\label{eq:pent-left-auxr}\n    \\begin{tikzcd}[column sep=5em]\n      \\auxr \\arrow[r, equals,\"1\"]\n      \\arrow[d,swap,equals,\"1\"] &\n      \\auxr \\arrow[d,equals,\"\\mapfunc{f_2\\smsh g_2}(\\gluer_{b_2}\\sy)\"] \\\\\n      \\auxr \\arrow[r,swap, equals,\"\\gluer_{b_3}\\sy\"] &\n      (a_3,b_3)\n    \\end{tikzcd}\n  \\end{equation}\n\tIf $x$ varies over $\\gluel_a$, after some reductions, we need to fill the following cube, where the front and the back are the squares in (\\ref{eq:pent-left-ab}) for $(a,b_1)$ and (\\ref{eq:pent-left-auxl}) respectively; the left square is degenerate; the other three sides are the squares in the definition of $i$ and $t$ to show that they respect $\\gluel_a$ (given in (\\ref{eq:i-gluel}) and (\\ref{eq:t-gluel}) respectively), where we also apply $f_2 \\smsh g_2$ to the square on the right. We suppress in the diagram the arguments of $\\gluer$ in $\\gluer\\tr\\gluer\\sy$ (which match, so the concatenation results equal to the identity path).\n\t\\begin{equation}\\label{eq:pent-left-gluel}\n\t\\begin{tikzcd}[column sep=5em]\n\t& \\auxl\n\t\t\\arrow[rr, equals, \"1\"]\n\t\t\\arrow[dd, swap, equals, near end, \"1\"]\n\t&& \\auxl\n\t\t\\arrow[dd, equals, \"\\mapfunc{f_2\\smsh g_2} (\\gluel_{a_2}\\sy)\"]\n\t\\\\\n\t(a_3,b_3)\n\t\t\\arrow[ur, equals, \"\\gluel_{a_3}\"]\n\t\t\\arrow[dd, swap, equals, \"1\"]\n\t\t\\arrow[rr, equals, crossing over, near end, \"1\"]\n\t&& (a_3,b_3)\n\t\t\\arrow[ur, equals, near start, \"\\mapfunc{f_2\\smsh g_2}(\\gluel_{a_2})\"]\n\t\t%\\arrow[dd, equals, near start, \"\\mapfunc{f_2\\smsh g_2}(\\gluer\\tr\\gluer\\sy)\"]\n\t\\\\\n\t& \\auxl\n\t\t\\arrow[rr, swap, equals, near start, \"\\gluel_{a_3}\\sy\"]\n\t&& (a_3,b_3)\n\t\\\\\n\t(a_3,b_3)\n\t\t\\arrow[ur, equals, \"\\gluel_{a_3}\"]\n\t\t\\arrow[rr, swap, equals, \"\\gluer\\tr\\gluer\\sy\"]\n\t&& (a_3,b_3)\n\t\t\\arrow[ur, swap, equals, \"1\"] %1\n\t\t\\arrow[from=uu, equals, crossing over, very near start, \"\\mapfunc{f_2 \\smsh g_2}(\\gluer\\tr\\gluer\\sy)\"]\n\t\\end{tikzcd}\n\t\\end{equation}\n\tSimilarly, if $x$ varies over $\\gluer_b$, we need to fill the cube below: the front and the back are the squares in (\\ref{eq:pent-left-ab}) for $(a_1,b)$ and (\\ref{eq:pent-left-auxr}) respectively; the left square is again degenerate; the other three sides come from the fact that $i$ and $t$ respect $\\gluer_b$ (given in (\\ref{eq:i-gluer}) and (\\ref{eq:t-gluer}) respectively). Again, we omit the arguments of $\\gluer$ in $\\gluer\\tr\\gluer\\sy$ (in this case, not a priori judgementally equal).\n\t\\begin{equation}\\label{eq:pent-left-gluer}\n\t\\begin{tikzcd}[column sep=4em]\n\t& \\auxr\n\t\t\\arrow[rr, equals,\"1\"]\n\t\t\\arrow[dd, swap, equals, near end,\"1\"]\n\t&& \\auxr\n\t\t\\arrow[dd,equals,\"\\mapfunc{f_2\\smsh g_2}(\\gluer_{b_2}\\sy)\"]\n\t\\\\\n\t(a_3,g_2(g_1(b)))\n\t\t\\arrow[rr, equals, near end, crossing over, \"1\"]\n\t\t\\arrow[dd, swap, equals, \"1\"]\n\t\t\\arrow[ur, equals, \"\\gluer_{g_2(g_1(b))}\"]\n\t&& (a_3,g_2(g_1(b)))\n\t\t\\arrow[ur, equals, near start, \"\\mapfunc{f_2\\smsh g_2}(\\gluer_{g_1(b)})\"]\n\t\\\\\n\t& \\auxr\n\t\t\\arrow[rr, swap, equals, near start, \"\\gluer_{b_3}\\sy\"]\n\t&& (a_3,b_3)\n\t\\\\\n\t(a_3,g_2(g_1(b)))\n\t\t\\arrow[rr, swap, equals,\"\\gluer\\tr\\gluer\\sy\"]\n\t\t\\arrow[ur, equals, near end, \"\\gluer_{g_2(g_1(b))}\"]\n\t&& (a_3,b_3)\n\t\t\\arrow[from=uu, equals, crossing over, very near start, \"\\mapfunc{f_2\\smsh g_2}(\\gluer\\tr\\gluer\\sy)\"]\n\t\t\\arrow[ur, swap, equals, \"1\"]\n\t\\end{tikzcd}\n\t\\end{equation}\n  %After canceling applications of  $\\mapfunc{h\\smsh k}(\\gluer_z)=\\gluer_{k(z)}$ on various sides of the squares (TODO).\n  In order to fill the cubes in (\\ref{eq:pent-left-gluel}) and (\\ref{eq:pent-left-gluer}), we generalize the paths and fill the cubes by path induction. The cube in (\\ref{eq:pent-left-gluel}) can be generalized to a cube:\n  \\begin{center}\n  \t\\begin{tikzcd}[column sep=3em]\n\t& h(y)\n\t\t\\arrow[rr, equals,\"1\"]\n\t\t\\arrow[dd, swap, equals, near end,\"1\"]\n\t&& h(y)\n\t\t\\arrow[dd,equals,\"\\mapfunc{h}(p_l\\sy)\"]\n\t\\\\\n\th(x)\n\t\t\\arrow[rr, equals, near end, crossing over, \"1\"]\n\t\t\\arrow[dd, swap, equals, \"1\"]\n\t\t\\arrow[ur, equals, \"q_l\"]\n\t&& h(x)\n\t\t\\arrow[ur, equals, near start, \"\\mapfunc{h}(p_l)\"]\n\t\\\\\n\t& h(y)\n\t\t\\arrow[rr, swap, equals, near start, \"q_l\\sy\"]\n\t&& h(x)\n\t\\\\\n\th(x)\n\t\t\\arrow[rr, swap, equals,\"q_r\\tr q_r\\sy\"]\n\t\t\\arrow[ur, equals, \"q_l\"]\n\t&& h(x)\n\t\t\\arrow[from=uu, equals, crossing over, near start, \"\\mapfunc{h}(p_r\\tr p_r\\sy)\"]\n\t\t\\arrow[ur, swap, equals, \"1\"]\n\t\\end{tikzcd}\n\t\\end{center}\n\tfor $X$ and $X'$ pointed types; a map $h : X \\to X'$; terms $x$, $y$ $z : X$; paths $p_l : x = y$, $p_r : x = z$, $q_l : h(x) = h(y)$, $q_r : h(x) = h(z)$; and 2-paths $s_l : \\mapfunc{h}(p_l) = q_l$ (for the back and the top) and $s_r : \\mapfunc{h}(p_r) = q_r$ (for the right side). This cube is filled by path induction on $s_l$, $s_r$, $p_l$ and $p_r$. The cube in (\\ref{eq:pent-left-gluer}) can be generalized to a similar cube:\n\t \\begin{center}\n  \t\\begin{tikzcd}[column sep=3em]\n\t& h(y)\n\t\t\\arrow[rr, equals,\"1\"]\n\t\t\\arrow[dd, swap, equals, near end,\"1\"]\n\t&& h(y)\n\t\t\\arrow[dd,equals,\"\\mapfunc{h}(p_b)\"]\n\t\\\\\n\th(x)\n\t\t\\arrow[rr, equals, near end, crossing over, \"1\"]\n\t\t\\arrow[dd, swap, equals, \"1\"]\n\t\t\\arrow[ur, equals, \"q_l\"]\n\t&& h(x)\n\t\t\\arrow[ur, equals, near start, \"\\mapfunc{h}(p_l)\"]\n\t\\\\\n\t& h(y)\n\t\t\\arrow[rr, swap, equals, near start, \"q_b\"]\n\t&& h(z)\n\t\\\\\n\th(x)\n\t\t\\arrow[rr, swap, equals,\"q_l\\tr q_b\"]\n\t\t\\arrow[ur, equals, \"q_l\"]\n\t&& h(z)\n\t\t\\arrow[from=uu, equals, crossing over, near start, \"\\mapfunc{h}(p_l\\tr p_b)\"]\n\t\t\\arrow[ur, swap, equals, \"1\"]\n\t\\end{tikzcd}\n\t\\end{center}\n\tfor paths $p_l : x = y$, $p_b : y = z$, $q_l : h(x) = h(y)$, $q_b : h(y) = h(z)$ and for 2-paths $s_l : \\mapfunc{h}(p_l) = q_l$ (for the top) and $s_b : \\mapfunc{h}(p_b) = q_b$ (for the back).\n\t\n\t\\textbf{Case $f_2\\judgeq 0$ (diagram on the right)}.\t(TODO)\n\t\n  To show that this homotopy is pointed, (TODO)\n\n\\end{proof}\n\n\\begin{thm}\\label{thm:smash-functor-right}\nGiven pointed types $A$, $B$ and $C$, the functorial action of the smash product induces a map\n$$({-})\\smsh C:(A\\pmap B)\\pmap(A\\smsh C\\pmap B\\smsh C)$$\nwhich is natural in $A$, pointed natural in $B$ and dinatural in $C$.\n\\end{thm}\nThe naturality and dinaturality means that the following squares commute for $f : A' \\to A$ $g:B\\to B'$ and $h:C\\to C'$.\n\\begin{center}\n\\begin{tikzcd}[column sep=5em]\n(A\\pmap B) \\arrow[r,\"({-})\\smsh C\"]\\arrow[d,\"f\\pmap B\"] &\n(A\\smsh C\\pmap B\\smsh C)\\arrow[d,\"f\\smsh C\\pmap B\\smsh C\"] \\\\\n(A'\\pmap B) \\arrow[r,\"({-})\\smsh C\"] &\n(A'\\smsh C\\pmap B\\smsh C)\n\\end{tikzcd}\n\\qquad\n\\begin{tikzcd}[column sep=5em]\n(A\\pmap B) \\arrow[r,\"({-})\\smsh C\"]\\arrow[d,\"A\\pmap g\"] &\n(A\\smsh C\\pmap B\\smsh C)\\arrow[d,\"A\\smsh C\\pmap g\\smsh C\"] \\\\\n(A\\pmap B') \\arrow[r,\"({-})\\smsh C\"] &\n(A\\smsh C\\pmap B'\\smsh C)\n\\end{tikzcd}\n\\begin{tikzcd}[column sep=5em]\n(A\\pmap B) \\arrow[r,\"({-})\\smsh C\"]\\arrow[d,\"({-})\\smsh C'\"] &\n(A\\smsh C\\pmap B\\smsh C)\\arrow[d,\"A\\smsh C\\pmap B\\smsh h\"] \\\\\n(A\\smsh C'\\pmap B\\smsh C') \\arrow[r,\"A\\smsh h\\pmap B\\smsh C'\"] &\n(A\\smsh C\\pmap B\\smsh C')\n\\end{tikzcd}\n\\end{center}\n\\begin{proof}\nFirst note that $\\lam{f}f\\smsh C$ preserves the basepoint so that the map is indeed pointed.\n\nLet $k:A\\pmap B$. Then as homotopy the naturality in $A$ becomes\n$(k\\o f)\\smsh C=k\\smsh C\\o f\\smsh C$. To prove an equality between pointed maps, we need to give\na pointed homotopy, which is given by interchange. To show that this homotopy is pointed, we need to\nfill the following square (after reducing out the applications of function extensinality), which follows from \\autoref{lem:smash-coh}.\n\\begin{center}\n\\begin{tikzcd}\n(0 \\o f)\\smsh C \\arrow[r, equals]\\arrow[dd,equals] &\n(0 \\smsh C)\\o (f \\smsh C)\\arrow[d,equals] \\\\\n& 0 \\o (f \\smsh C)\\arrow[d,equals] \\\\\n0\\smsh C \\arrow[r,equals] &\n0\n\\end{tikzcd}\n\\end{center}\nThe naturality in $B$ is almost the same: for the underlying homotopy we need to show\n$i:(g \\o k)\\smsh C = g\\smsh C \\o k\\smsh C$. For the pointedness we need to fill the following\nsquare, which follows from the left pentagon in \\autoref{lem:smash-coh}.\n\\begin{center}\n\\begin{tikzcd}\n(g \\o 0)\\smsh C \\arrow[r, equals]\\arrow[dd,equals] &\n(g \\smsh C)\\o (0 \\smsh C)\\arrow[d,equals] \\\\\n& (g\\smsh C) \\o 0\\arrow[d,equals] \\\\\n0\\smsh C \\arrow[r,equals] &\n0\n\\end{tikzcd}\n\\end{center}\nTo show that this naturality is pointed, we need to show that if $g=0$ then this homotopy is the same as the concatenation $q_0$ of the following pointed homotopies:\n$$({-})\\smsh C \\circ (A \\to 0)\\sim ({-})\\smsh C \\circ 0 \\sim 0 \\sim 0 \\circ ({-})\\smsh C\\sim 0\\smsh B \\circ ({-})\\smsh C.$$\nTo show that the underlying homotopies are the same, we need to show that $i(0,f,\\idfunc[C],\\idfunc[C])$ is equal to the following concatenation of pointed homotopies\n$$q_0(f):(0\\circ f)\\smsh C\\sim 0\\smsh C \\sim 0 \\sim 0 \\circ f\\smsh C\\sim 0\\smsh B \\circ f\\smsh C,$$\nwhich is the right pentagon in \\autoref{lem:smash-coh}. \nTo show that these pointed homotopies respect the basepoint in the same way, we need to show that (TODO)\n``$R\\mathrel\\square(0\\smsh C \\circ t)\\cdot q_0=L$ where $L$ and $R$ are the left and right pentagons applied to $0$ and $\\square$ is whiskering.''\n\nThe dinaturality in $C$ is a bit harder. For the underlying homotopy we need to show\n$B\\smsh h\\o k\\smsh C=k\\smsh C'\\o A\\smsh h$. This follows by applying interchange twice:\n$$B\\smsh h\\o k\\smsh C\\sim(\\idfunc[B]\\o k)\\smsh(h\\o\\idfunc[C])\\sim(k\\o\\idfunc[A])\\smsh(\\idfunc[C']\\o h)\\sim k\\smsh C'\\o A\\smsh h.$$\nTo show that this homotopy is pointed, we need to fill the following square:\n\\begin{center}\n  \\begin{tikzcd}\n    B\\smsh h\\o 0\\smsh C \\arrow[r, equals]\\arrow[d,equals] &\n    (\\idfunc[B]\\o 0)\\smsh(h\\o\\idfunc[C]) \\arrow[r, equals]\\arrow[d,equals] &\n    (0\\o\\idfunc[A])\\smsh(\\idfunc[C']\\o h)\\arrow[r, equals]\\arrow[d,equals] &\n    0\\smsh C'\\o A\\smsh h\\arrow[d,equals] \\\\\n    B\\smsh h\\o 0 \\arrow[d,equals] &\n    0\\smsh(h\\o\\idfunc[C]) \\arrow[r, equals]\\arrow[d,equals] &\n    0\\smsh(\\idfunc[C']\\o h) \\arrow[d,equals] &\n    0\\o A\\smsh h\\arrow[d,equals] \\\\\n    B\\smsh h\\o 0 \\arrow[r, equals] &\n    0 \\arrow[r, equals] &\n    0 \\arrow[r, equals] &\n    0\n  \\end{tikzcd}\n\\end{center}\nThe left and the right squares are filled by \\autoref{lem:smash-coh}. The squares in the middle\nare filled by (corollaries of) \\autoref{lem:smash-general}.\n\\end{proof}\n\n\\section{Adjunction}\n\n\\begin{lem}\\label{lem:unit-counit}\n  There is a unit $\\eta_{A,B}\\equiv\\eta:A\\pmap B\\pmap A\\smsh B$ natural in $A$ and counit\n  $\\epsilon_{B,C}\\equiv\\epsilon : (B\\pmap C)\\smsh B \\pmap C$ dinatural in $B$ and pointed natural in $C$.\n  These maps satisfy the unit-counit laws:\n  $$(A\\to\\epsilon_{A,B})\\o \\eta_{A\\to B,A}\\sim \\idfunc[A\\to B]\\qquad\n  \\epsilon_{B,A\\smsh B}\\o \\eta_{A,B}\\smsh B\\sim\\idfunc[A\\smsh B].$$\n\\end{lem}\nNote: $\\eta$ is also dinatural in $B$, but we don't need this.\n\\begin{proof}\n  We define $\\eta ab=(a,b)$. We define the path that $\\eta a$ respects the basepoint as\n  $$(\\eta a)_0\\defeq\\gluel_a\\tr\\gluel_{a_0}\\sy:(a,b_0)=(a_0,b_0).$$ Also, $\\eta$ itself respects the basepoint. To show this, we need to give $\\eta_0:\\eta (a_0)\\sim 0$. The underlying maps are homotopic, by $$\\eta_0b\\defeq\\gluer_b\\cdot\\gluer_{b_0}\\sy:(a_0,b)=(a_0,b_0).$$ To show that\n  this homotopy is pointed, we need to show that the two given proofs of $(a_0,b_0)=(a_0,b_0)$ are\n  equal, but they are both equal to reflexivity:\n  $$\\eta_{00}:\\gluel_{a_0}\\tr\\gluel_{a_0}\\sy=1=\\gluer_{b_0}\\tr\\gluer_{b_0}\\sy.$$\n  This defines the unit. To show that it is natural in $A$, we need to give the following pointed homotopy $p_\\eta(f)$ for $f:A\\to A'$.\n  \\begin{center}\n\t\\begin{tikzcd}\n\tA \\arrow[r,\"\\eta\"]\\arrow[d,\"f\"] &\n\t(B\\pmap A \\smsh B)\\arrow[d,\"B\\to f\\smsh B\"] \\\\\n\tA' \\arrow[r,\"\\eta\"] &\n\t(B\\pmap A'\\smsh B)\n\t\\end{tikzcd}\n  \\end{center}\n  We may assume that $f_0$ is reflexivity. For the underlying homotopy we need to define for $a:A$ that $p_\\eta(f,a):\\eta(fa)\\sim f\\smsh B \\circ \\eta a$, which is another pointed homotopy. For $b:B$ we have $\\eta(fa,b)\\equiv(fa,b)\\equiv(f\\smsh B)(\\eta ab).$\n  The homotopy $p_\\eta(f,a)$ is pointed, since $$(f\\smsh B \\circ \\eta a)_0=\\apfunc{f\\smsh B}(\\gluel_a\\cdot\\gluel_{a_0}\\sy)=\\gluel_{fa}\\cdot\\gluel_{a_0'}\\sy=(\\eta(fa))_0.$$\n  Now we need to show that $p_\\eta(f)$ is pointed, for which we need to fill the following diagram.\n  \\begin{center}\n\t\\begin{tikzcd}\n\t\\eta(fa_0) \\arrow[equals,rr,\"{p_\\eta(f,a_0)}\"]\\arrow[dr,equals,\"{\\eta_0}\"] & &\n\tf\\smsh B \\circ \\eta a_0\\arrow[dl,equals,\"{f\\smsh B\\circ\\eta_0}\"] \\\\\n\t& 0_{B,A'\\smsh B} &\n\t\\end{tikzcd}\n  \\end{center}\n  These pointed homotopies have equal underlying homotopies, since for $b:B$ we have \n  $$p_\\eta(f,a_0,b)\\cdot\\apfunc{f\\smsh B}(\\eta_0 b)=1\\cdot\\apfunc{f\\smsh B}(\\gluer_b\\cdot\\gluer_{b_0}\\sy)=\\gluer_{b}\\cdot\\gluer_{b_0}\\sy=\\eta_0b.$$\n  The homotopies are pointed in the same way (TODO).\n\n  To define the counit, given $x:(B\\pmap C)\\smsh B$, we construct\n  $\\epsilon (x):C$ by induction on $x$. If $x\\jdeq(f,b)$ we set $\\epsilon(f,b)\\defeq f(b)$. If $x$\n  is either $\\auxl$ or $\\auxr$ then we set $\\epsilon (x)\\defeq c_0:C$. If $x$ varies over $\\gluel_f$\n  then we need to show that $f(b_0)=c_0$, which is true by $f_0$. If $x$ varies over $\\gluer_b$ we\n  need to show that $0(b)=c_0$ which is true by reflexivity. Now $\\epsilon_0\\defeq 1:\\epsilon(0_{B,C},b_0)=c_0$ shows that $\\epsilon$ is pointed.\n\n  Now we need to show that the counit is dinatural in $B$ and pointed natural in $C$. (TODO)\n\n  Finally, we need to show the unit-counit laws. For the underlying homotopy of the first one, let\n  $f:A\\to B$. We need to show that $p_f:\\epsilon\\o\\eta f\\sim f$. We define $p_f(a)=1:\\epsilon(f,a)=f(a)$. To show that $p_f$ is a pointed homotopy, we need to show that\n  $p_f(a_0)\\tr f_0=\\mapfunc{\\epsilon}(\\eta f)_0\\tr \\epsilon_0$, which reduces to\n  $f_0=\\mapfunc{\\epsilon}(\\gluel_f\\tr\\gluel_0\\sy)$, but we can reduce the right hand side: (note:\n  $0_0$ denotes the proof that $0(a_0)=b_0$, which is reflexivity)\n  $$\\mapfunc{\\epsilon}(\\gluel_f\\tr\\gluel_0\\sy)=\\mapfunc{\\epsilon}(\\gluel_f)\\tr(\\mapfunc{\\epsilon}(\\gluel_0))\\sy=f_0\\tr 0_0\\sy=f_0.$$\n  Now we need to show that $p$ itself respects the basepoint of $A\\to B$, i.e. that the composite\n  $\\epsilon\\o\\eta(0)\\sim\\epsilon\\o0\\sim0$ is equal to $p_{0_{A,B}}$. The underlying\n  homotopies are the same for $a : A$; on the one side we have\n  $\\mapfunc{\\epsilon}(\\gluer_{a}\\tr\\gluer_{a_0}\\sy)$ and on the other side we have reflexivity\n  (note: this typechecks since $0_{A,B}a\\equiv0_{A,B}a_0$). These paths are equal, since\n  $$\\mapfunc{\\epsilon}(\\gluer_{a}\\tr\\gluer_{a_0}\\sy)=\\mapfunc{\\epsilon}(\\gluer_{a})\\tr(\\mapfunc\\epsilon(\\gluer_{a_0}))\\sy=1\\cdot1\\sy\\equiv1.$$\n  Both pointed homotopies are pointed in the same way, which requires some path-algebra, and we skip the proof here.\n\n  For the underlying homotopy of the second unit-counit law, we need to show for $x:A\\smsh B$ that\n  $q(x):\\epsilon((\\eta\\smsh B)x)=x$, which we prove by induction to $x$. If $x\\equiv(a,b)$ then we can define $q(a,b)\\defeq1_{(a,b)}$. If $x$ is $\\auxl$ or $\\auxr$ then the left-hand side reduces to $(a_0,b_0)$, so we can define $q(\\auxl)\\defeq\\gluel_{a_0}$ and $q(\\auxr)\\defeq\\gluer_{b_0}$. The following computation shows that $q$ respects $\\gluel_a$:\n  $$\\apfunc{\\epsilon\\circ\\eta\\smsh B}(\\gluel_a)\\cdot\\gluel_{a_0}= \\apfunc{\\epsilon}(\\gluel_{\\eta a})\\cdot\\gluel_{a_0}=(\\eta a)_0\\cdot\\gluel_{a_0}=\\gluel_a\\cdot\\gluel_{a_0}\\sy\\cdot\\gluel_{a_0}=\\gluel_a.$$\n  To show that it respects $\\gluer_b$ we compute\n  $$\\apfunc{\\epsilon\\circ\\eta\\smsh B}(\\gluer_b)\\cdot\\gluer_{b_0}=\n  \\apfunc{\\epsilon({-},b)}(\\eta_0)\\cdot\\apfunc{\\epsilon}(\\gluer_b)\\cdot\\gluer_{b_0}=\n  \\apfunc{\\lam{f}fb}(\\eta_0)\\cdot\\gluer_{b_0}=\n  \\eta_0b\\cdot\\gluer_{b_0}=\n  %\\gluer_b\\cdot\\gluer_{b_0}\\sy\\cdot\\gluer_{b_0}=\n  \\gluer_b.$$\n  To show that $q$ is a pointed homotopy, we need to show that $(\\epsilon\\circ\\eta\\smsh B)_0=1$, For this we compute $$(\\epsilon\\circ\\eta\\smsh B)_0=\\apfunc{\\epsilon({-},b_0)}(\\eta_0)=\\eta_0b_0=\\gluer_{b_0}\\cdot\\gluer_{b_0}\\sy=1.$$\n\\end{proof}\n\n\\begin{defn}\nThe function $e\\jdeq e_{A,B,C}:(A\\pmap B\\pmap C)\\pmap(A\\smsh B\\pmap C)$ is defined as the composite\n$$(A\\pmap B\\pmap C)\\lpmap{({-})\\smsh B}(A\\smsh B\\pmap (B\\pmap C)\\smsh B)\\lpmap{A\\smsh B \\pmap\\epsilon}(A\\smsh B\\pmap C).$$\n\\end{defn}\n\n\\begin{lem}\n  The function $e$ is invertible, hence gives a pointed equivalence $$(A\\pmap B\\pmap C)\\simeq(A\\smsh B\\pmap C).$$\n\\end{lem}\n\\begin{proof}\n  Define\n  $$\\inv{e}_{A,B,C}:(A\\smsh B\\pmap C)\\lpmap{B\\pmap({-})}((B\\pmap A\\smsh B)\\pmap (B\\pmap\n  C))\\lpmap{\\eta\\pmap(B\\pmap C)}(A\\pmap B\\pmap C).$$ It is easy to show that $e$ and $\\inv{e}$ are\n  inverses as unpointed maps from the unit-counit laws (\\autoref{lem:unit-counit}) and naturality of $\\eta$ and $\\epsilon$.\n%   For $f : A\\pmap B\\pmap C$ we have\n%   \\begin{align*}\n%     \\inv{e}(e(f))&\\equiv(\\eta\\pmap(B\\pmap C))\\o (B\\pmap((A\\smsh B\\pmap\\epsilon)\\of\\smsh B))\\\\\n%                  &= (\\eta\\pmap(B\\pmap C))\\o (B\\pmap(A\\smsh B\\pmap\\epsilon))\\o(B\\pmapf\\smsh B)\\\\\n% %                 &= (\\eta\\pmap(B\\pmap C))\\o (B\\pmap(A\\smsh B\\pmap\\epsilon))\\o(B\\pmapf\\smsh B)\\\\\n%   \\end{align*}\n\\end{proof}\n\\begin{lem}\\label{lem:e-natural}\n\tThe function $e$ is natural in $A$, $B$ and pointed natural in $C$.\n\\end{lem}\n\\begin{proof}\n\t\\textbf{Naturality of $e$ in $A$}. Suppose that $f:A'\\pmap A$. Then the following diagram commutes. The left square commutes by naturality of $({-})\\smsh B$ in the first argument and the right square commutes because composition on the left commutes with composition on the right.\n\t\\begin{center}\n\t\\begin{tikzcd}\n\t\t(A\\pmap B\\pmap C) \\arrow[r,\"({-})\\smsh B\"]\\arrow[d,\"f\\pmap B\\pmap C\"] &\n\t\t(A\\smsh B\\pmap (B\\pmap C)\\smsh B) \\arrow[r,\"A\\smsh B\\pmap\\epsilon\"]\\arrow[d,\"f\\smsh B\\pmap\\cdots\"]  &\n\t\t(A\\smsh B\\pmap C)\\arrow[d,\"f\\smsh B\\pmap C\"] \\\\\n\t\t(A'\\pmap B\\pmap C) \\arrow[r,\"({-})\\smsh B\"] &\n\t\t(A'\\smsh B\\pmap (B\\pmap C)\\smsh B) \\arrow[r,\"A\\smsh B\\pmap\\epsilon\"] &\n\t\t(A'\\smsh B\\pmap C)\n\t\\end{tikzcd}\n\t\\end{center}\n\n\t\\textbf{Naturality of $e$ in $C$}. Suppose that $f:C\\pmap C'$. Then in the following diagram the left square commutes by naturality of $({-})\\smsh B$ in the second argument (applied to $B\\pmap f$) and the right square commutes by applying the functor $A\\smsh B \\pmap({-})$ to the naturality of $\\epsilon$ in the second argument.\n\t\\begin{center}\n\t\\begin{tikzcd}\n\t\t(A\\pmap B\\pmap C) \\arrow[r]\\arrow[d] &\n\t\t(A\\smsh B\\pmap (B\\pmap C)\\smsh B) \\arrow[r]\\arrow[d] &\n\t\t(A\\smsh B\\pmap C)\\arrow[d] \\\\\n\t\t(A\\pmap B\\pmap C') \\arrow[r] &\n\t\t(A\\smsh B\\pmap (B\\pmap C')\\smsh B) \\arrow[r] &\n\t\t(A\\smsh B\\pmap C')\n\t\\end{tikzcd}\n\t\\end{center}\nPointed naturality: TODO.\n\n\t\\textbf{Naturality of $e$ in $B$}. Suppose that $f:B'\\pmap B$. Here the diagram is a bit more\ncomplicated, since $({-})\\smsh B$ is dinatural (instead of natural) in $B$. Then we get the\nfollowing diagram. The front square commutes by naturality of $({-})\\smsh B$ in the second argument\n\t(applied to $f\\pmap C$). The top square commutes by naturality of $({-})\\smsh B$ in the third\nargument, the back square commutes because composition on the left commutes with composition on the\n\tright, and finally the right square commutes by applying the functor $A\\smsh B' \\pmap({-})$ to the\n\tnaturality of $\\epsilon$ in the first argument.\n\t\\begin{center}\n\t\\begin{tikzcd}[row sep=scriptsize, column sep=-4em]\n\t\t& (A\\smsh B\\pmap (B\\pmap C)\\smsh B) \\arrow[rr] \\arrow[dd] & & (A\\smsh B'\\pmap (B\\pmap C)\\smsh B)\\arrow[dd] \\\\\n\t\t(A\\pmap B\\pmap C) \\arrow[ur] \\arrow[rr, crossing over] \\arrow[dd] & & (A\\smsh B'\\pmap (B\\pmap C)\\smsh B') \\arrow[ur] \\\\\n\t\t& (A\\smsh B\\pmap C)\\arrow[rr] &  & (A\\smsh B'\\pmap C) \\\\\n\t\t(A\\pmap B'\\pmap C) \\arrow[rr] & & (A\\smsh B'\\pmap (B'\\pmap C)\\smsh B') \\arrow[ur] \\arrow[from=uu, crossing over]\n\t\\end{tikzcd}\n\t\\end{center}\n\n\\end{proof}\n\\begin{rmk}\n  Instead of showing that $e$ is natural, we could instead show that $e^{-1}$ is natural. In\n  that case we need to show that the map $A\\to({-}):(B\\to C)\\to(A\\to B)\\to(A\\to C)$ is natural in\n  $A$, $B$ and $C$. This might actually be easier, since we don't need to work with any higher\n  inductive type to prove that.\n\\end{rmk}\n\n\\section{Symmetric monoid product}\nWe aim to prove that the smash product is a (1-coherent) symmetric monoidal product [REF: Brunerie] for pointed types, i.e., that\n\\[(\\type^*,\\, \\bool,\\, \\smsh,\\, \\alpha,\\, \\lambda,\\, \\rho,\\, \\gamma)\\]\nis a symmetric monoidal category, with the type of booleans $\\bool$ (pointed in $0_\\bool$) as unit, and for suitable instances of $\\alpha$, $\\lambda$, $\\rho$ and $\\gamma$ witnessing associativity, left- and right unitality and the braiding for $\\smsh$ and satisfying appropriate coherence relations (associativity pentagon; unitors triangle; braiding-unitors triangle; associativity-braiding hexagon; double braiding).\n\nUsing \\autoref{lem:yoneda} (Yoneda) we can prove associativity, left- and right unitality and braiding equivalences for the smash product, in the following way.\n\n\\begin{defn}\\label{def:equiv-precursors}\n\tThe following pointed equivalences are defined for $A$, $B$, $C$ and $X$ pointed types:\n\t\\begin{itemize}\n\t\t\\item $\\alphabar_X : (A \\smsh (B \\smsh C) \\to X) \\simeq ((A \\smsh B) \\smsh C \\to X)$ as the composition of the equivalences:\n\t\t\t\\begin{align*}\n\t\t\t    A \\smsh (B \\smsh C)\\to X&\\simeq A \\to B\\smsh C\\to X && (e\\sy)\\\\\n\t\t\t    &\\simeq A \\to B\\to C\\to X && (A \\to e\\sy)\\\\\n\t\t\t    &\\simeq A \\smsh B\\to C\\to X && (e)\\\\\n\t\t    \t&\\simeq (A \\smsh B)\\smsh C\\to X. && (e)\n\t\t\t\\end{align*}\n\t\t\\item $\\lambdabar_X : (B \\to X) \\simeq (\\bool \\smsh B \\to X)$ as the composition of the equivalences:\n\t\t\t\\begin{align*}\n\t\t\t\tB \\to X &\\simeq \\bool \\to B \\to X && (\\two\\sy)\\\\\n\t\t\t\t&\\simeq \\bool \\smsh B \\to X && (e)\n\t\t\t\\end{align*}\n\t\t\\item $\\rhobar_X : (A \\to X) \\simeq (A \\smsh \\bool \\to X)$ as the composition of the equivalences:\n\t\t\t\\begin{align*}\n\t\t\t\tA \\to X &\\simeq A \\to \\bool \\to X && (A \\to \\two\\sy)\\\\\n\t\t\t\t&\\simeq A \\smsh \\bool \\to X && (e)\n\t\t\t\\end{align*}\n\t\t\\item $\\gammabar_X : (B \\smsh A \\to X) \\simeq (A \\smsh B \\to X)$ as the composition of the equivalences:\n\t\t\t\\begin{align*}\n\t\t\t\tB \\smsh A \\to X &\\simeq B \\to A \\to X && (e\\sy)\\\\\n\t\t\t\t&\\simeq A \\to B \\to X && (\\twist)\\\\\n\t\t\t\t&\\simeq A \\smsh B \\to X && (e)\n\t\t\t\\end{align*}\n\t\\end{itemize}\n\\end{defn}\n\n\\begin{rmk}\\label{rmk:alrg-pointed-natural}\n\tThe equivalences in \\autoref{def:equiv-precursors} are natural in all their arguments and pointed natural in $X$, by (pointed) naturality of $e$ (\\autoref{lem:e-natural} and \\autoref{lem:e-pointed-natural}), $c$ and $t$. In particular, we will use:\n\t\\begin{align*}\n\tf \\o \\alphabar(g) &\\sim \\alphabar(f \\o g) & f \\o \\lambdabar(g) &\\sim \\lambdabar(f \\o g)\\\\\n\tf \\o \\rhobar(g) &\\sim \\rhobar(f \\o g) & f \\o \\gammabar(g) &\\sim \\gammabar(f \\o g)\n\t\\end{align*}\n\\end{rmk}\n\n\\begin{defn}\\label{def:smash-alrg}\n\tWe define the following equivalences, natural in all their arguments, with inverses provided as in \\autoref{lem:yoneda}:\n\t\\begin{itemize}\n\t\t\\item $\\alpha\\defeq\\alphabar_{A \\smsh (B \\smsh C)}(\\idfunc) : (A \\smsh B) \\smsh C \\simeq A \\smsh (B \\smsh C)$ (associativity of the smash product), with inverse $\\alpha\\sy\\defeq\\alphabar\\sy_{(A \\smsh B) \\smsh C}(\\idfunc)$;\n\t\t\\item $\\lambda \\defeq \\lambdabar_B(\\idfunc) : \\bool \\smsh B \\simeq B$ and $\\rho \\defeq \\rhobar_A(\\idfunc) : A \\smsh \\bool \\simeq A$ (left- and right unitors for the smash product), with inverses $\\lambda\\sy\\defeq \\lambdabar_{\\bool\\smsh B}\\sy(\\idfunc)$ and $\\rho\\sy\\defeq \\rhobar_{A\\smsh \\bool}\\sy(\\idfunc)$, respectively;\n\t\t\\item $\\gamma \\defeq \\gammabar_{B\\smsh A} (\\idfunc) : A \\smsh B \\simeq B \\smsh A$ (braiding for the smash product), with inverse $\\gamma\\sy \\defeq \\gammabar_{A \\smsh B}\\sy (\\idfunc)$.\n\t\\end{itemize}\n\t$\\alpha$, $\\lambda$, $\\rho$ and $\\gamma$ are natural in all their arguments, as $\\alphabar$, $\\lambdabar$, $\\rhobar$ and $\\gammabar$ are.\n\\end{defn}\n\n\\begin{lem}\\label{lem:bar-homotopy}\n\tThere are pointed homotopies\n\t\\begin{align*}\n\t\\alphabar_X &\\sim \\alpha \\to X\n\t\t& \\lambdabar_X &\\sim \\lambda \\to X\n\t\\\\\n\t\\rhobar_X &\\sim \\rho \\to X\n\t\t& \\gammabar_X &\\sim \\gamma \\to X\n\t\\end{align*}\n\\end{lem}\n\n\\begin{proof}\n\tThis follows directly from \\autoref{lem:yoneda-pointed} and \\autoref{rmk:alrg-pointed-natural}.\n\\end{proof}\n\n\\begin{thm}[Associativity pentagon]\\label{thm:smash-associativity-pentagon}\n\tFor $A$, $B$, $C$ and $D$ pointed types, there is a pointed homotopy\n\t\\[\\alpha \\o \\alpha \\sim (A \\smsh \\alpha) \\o \\alpha \\o (\\alpha \\smsh D)\\]\n\tcorresponding to the commutativity of the following diagram:\n\t\\begin{center}\n\t\\begin{tikzcd}\n\t\t&((A \\smsh B) \\smsh (C \\smsh D))\n\t\t\t\\arrow[dr, \"\\alpha\"]\n\t\t\\\\\n\t\t(((A \\smsh B) \\smsh C) \\smsh D)\n\t\t\t\\arrow[ru, \"\\alpha\"]\n\t\t\t\\arrow[d, swap, \"\\alpha \\smsh D\"]\n\t\t&& (A \\smsh (B \\smsh (C \\smsh D)))\n\t\t\\\\\n\t\t((A \\smsh (B \\smsh C)) \\smsh D)\n\t\t\t\\arrow[rr, swap, \"\\alpha\"]\n\t\t&& (A \\smsh ((B \\smsh C) \\smsh D))\n\t\t\t\\arrow[u, swap, \"A \\smsh \\alpha\"]\n\t\\end{tikzcd}\n%\t\\begin{tikzcd}\n%\t\t(((A \\smsh B) \\smsh C) \\smsh D)\n%\t\t\t\\arrow[rr, \"\\alpha\"]\n%\t\t\t\\arrow[d, swap, \"\\alpha \\smsh D\"]\n%\t\t&& ((A \\smsh B) \\smsh (C \\smsh D))\n%\t\t\t\\arrow[d, \"\\alpha\"]\n%\t\t\\\\\n%\t\t((A \\smsh (B \\smsh C)) \\smsh D)\n%\t\t\t\\arrow[r, swap, \"\\alpha\"]\n%\t\t& (A \\smsh ((B \\smsh C) \\smsh D))\n%\t\t\t\\arrow[r, swap, \"A \\smsh \\alpha\"]\n%\t\t& (A \\smsh (B \\smsh (C \\smsh D)))\n%\t\\end{tikzcd}\n\t\\end{center}\n\\end{thm}\n\\begin{proof}\n\tWe articulate the proof in several steps. A map homotopic to both sides of the sought homotopy will be constructed via the equivalence\n\t\\begin{align*}\t\n\t\t\\alphabar^4 : (A \\smsh (B \\smsh (C \\smsh D)) \\to X) &\\simeq (((A \\smsh B) \\smsh C) \\smsh D \\to X)\n\t\t\\intertext{(natural in all its arguments), defined as the composite:}\n\t\tA \\smsh (B \\smsh (C \\smsh D)) \\to X\n\t\t&\\simeq A \\to B \\smsh (C \\smsh D) \\to X && \\text{($e\\sy$)}\\\\\n\t\t&\\simeq A \\to B \\to C \\smsh D \\to X &&\\text{($A \\to e\\sy$)}\\\\\n\t\t&\\simeq A \\to B \\to C \\to D \\to X &&\\text{($A \\to B \\to e\\sy$)}\\\\\n\t\t&\\simeq A \\smsh B \\to C \\to D \\to X &&\\text{($e$)}\\\\\n\t\t&\\simeq (A \\smsh B) \\smsh C \\to D \\to X &&\\text{($e$)}\\\\\n\t\t&\\simeq ((A \\smsh B) \\smsh C) \\smsh D \\to X && \\text{($e$)}\n\t\t\\intertext{giving $\\alphabar^4(\\idfunc) : ((A \\smsh B) \\smsh C) \\smsh D) \\simeq A \\smsh (B \\smsh (C \\smsh D))$. Moreover, in order to simplify the expressions of $\\alpha \\smsh D$ and $A \\smsh \\alpha$, we also define:}\n\t\t\\alphabar^R : ((A \\smsh (B \\smsh C)) \\smsh D \\to X) &\\simeq (((A \\smsh B) \\smsh C) \\smsh D \\to X)\n\t\t\\intertext{as the composite:}\n\t\t(A \\smsh (B \\smsh C)) \\smsh D \\to X\n\t\t&\\simeq A \\smsh (B \\smsh C) \\to D \\to X &&\\text{($e\\sy$)}\\\\\n\t\t&\\simeq (A \\smsh B) \\smsh C \\to D \\to X &&\\text{($\\alphabar$)}\\\\\n\t\t&\\simeq ((A \\smsh B) \\smsh C) \\smsh D \\to X &&\\text{($e$)}\n\t\t\\intertext{and}\n\t\t\\alphabar^L : (A \\smsh (B \\smsh (C \\smsh D)) \\to X) &\\simeq (A \\smsh ((B \\smsh C) \\smsh D) \\to X)\n\t\t\\intertext{as the composite:}\n\t\tA \\smsh (B \\smsh (C \\smsh D)) \\to X\n\t\t&\\simeq A \\to B \\smsh (C \\smsh D) \\to X &&\\text{($e\\sy$)}\\\\\n\t\t&\\simeq A \\to (B \\smsh C) \\smsh D \\to X &&\\text{($A \\to \\alphabar$)}\\\\\n\t\t&\\simeq A \\smsh ((B \\smsh C) \\smsh D) \\to X &&\\text{($e$)}\n\t\\end{align*}\n\talso natural in their arguments. Evaluating these equivalences to the identity function, we get new arrows that fit in the original diagram:\n\t\\begin{center}\n\t\\begin{tikzcd}\n\t\t&((A \\smsh B) \\smsh (C \\smsh D))\n\t\t\t\\arrow[dr, \"\\alpha\"]\n\t\t\\\\\n\t\t(((A \\smsh B) \\smsh C) \\smsh D)\n\t\t\t\\arrow[ru, \"\\alpha\"]\n\t\t\t\\arrow[d, swap, \"\\alpha \\smsh D\"]\n\t\t\t\\arrow[d, bend left=40, \"\\alphabar^R(\\idfunc)\"]\n\t\t\t\\arrow[rr, \"\\alphabar^4(\\idfunc)\"]\n\t\t&& (A \\smsh (B \\smsh (C \\smsh D)))\n\t\t\\\\\n\t\t((A \\smsh (B \\smsh C)) \\smsh D)\n\t\t\t\\arrow[rr, swap, \"\\alpha\"]\n\t\t&& (A \\smsh ((B \\smsh C) \\smsh D))\n\t\t\t\\arrow[u, swap, \"A \\smsh \\alpha\"]\n\t\t\t\\arrow[u, bend left=40, \"\\alphabar^L(\\idfunc)\"]\n\t\\end{tikzcd}\n\t\\end{center}\n\t\n\tThe theorem is then proved once we show the chain of homotopies:\n\t\\begin{equation}\\label{eq:alphafour}\n\t\\alpha \\o \\alpha\n\t\\sim \\alphabar^4(\\idfunc)\n\t\\sim \\alphabar^L(\\idfunc) \\o \\alpha \\o \\alphabar^R(\\idfunc)\n\t\\sim (A \\smsh \\alpha) \\o \\alpha \\o (\\alpha \\smsh D)\n\t\\end{equation}\n\t\n\tTo verify the first homotopy in (\\ref{eq:alphafour}), we see that:\n\t\\begin{align*}\n\t\t\\alpha \\o \\alpha\n\t\t&\\judgeq \\alphabar(\\idfunc) \\o \\alphabar(\\idfunc)\\\\\n\t\t&\\sim (\\alphabar \\o \\alphabar) (\\idfunc) &&\\text{(naturality of $\\alphabar$)}\\\\\n\t\t&\\judgeq (e \\o e \\o (A \\to e\\sy) \\o e\\sy \\o e \\o e \\o (A \\to e\\sy) \\o e\\sy)(\\idfunc)\\\\\n\t\t&\\sim (e \\o e \\o (A \\to e\\sy) \\o e \\o (A \\to e\\sy) \\o e\\sy)(\\idfunc) &&\\text{(cancelling)}\\\\\n\t\t&\\sim (e \\o e \\o e \\o (B \\to A \\to e\\sy) \\o (A \\to e\\sy) \\o e\\sy)(\\idfunc) &&\\text{(naturality of $e$)}\\\\\n\t\t&\\judgeq \\alphabar^4(\\idfunc)\n\t\\end{align*}\t\t\n\n\tThe second homotopy in (\\ref{eq:alphafour}) is verified by (right-to-left):\n\t\\begin{align*}\n\t\t\\alphabar^L(\\idfunc) \\o \\alpha \\o \\alphabar^R(\\idfunc)\n\t\t&\\judgeq \\alphabar^L(\\idfunc) \\o \\alphabar(\\idfunc) \\o \\alphabar^R(\\idfunc)\\\\\n\t\t&\\sim (\\alphabar^R \\o \\alphabar \\o \\alphabar^L)(\\idfunc) &&\\text{(nat. of $\\alphabar$ and $\\alphabar^R$)}\\\\\n\t\t&\\judgeq (e \\o \\alphabar \\o e\\sy \\o e \\o e \\o (A \\to e\\sy) \\o e\\sy \\o e \\o (A \\to \\alphabar) \\o e\\sy)(\\idfunc)\\\\\n\t\t&\\sim (e \\o \\alphabar \\o e \\o (A \\to e\\sy) \\o (A \\to \\alphabar) \\o e\\sy)(\\idfunc) &&\\text{(cancelling)}\\\\\n\t\t&\\sim (e \\o \\alphabar \\o e \\o (A \\to (e\\sy \\o \\alphabar)) \\o e\\sy)(\\idfunc) &&\\text{(funct. of $A\\to -$)}\\\\\n\t\t&\\judgeq (e \\o e \\o e \\o (A \\to e\\sy) \\o e\\sy \\o e \\\\\n\t\t&\\hspace{3em}\\o (A \\to (e\\sy \\o e \\o e \\o (B \\to e\\sy) \\o e\\sy)) \\o e\\sy)(\\idfunc)\\\\\n\t\t&\\sim (e \\o e \\o e \\o (A \\to ((B \\to e\\sy) \\o e\\sy)) \\o e\\sy)(\\idfunc) &&\\text{(cancelling)}\\\\\n\t\t&\\sim (e \\o e \\o e \\o (B \\to A \\to e\\sy) \\o (A \\to e\\sy) \\o e\\sy)(\\idfunc) &&\\text{(funct. of $A \\to -$)}\\\\\n\t\t&\\judgeq \\alphabar^4(\\idfunc)\n\t\\end{align*}\n\t\n\tIn order to prove the last homotopy in (\\ref{eq:alphafour}), it is sufficient to show that $\\alphabar^R(\\idfunc) \\sim \\alpha \\smsh D$ and that $\\alphabar^L(\\idfunc) \\sim A \\smsh \\alpha$. We have:\n\t\\begin{align*}\n\t\t\\alphabar^R(\\idfunc)\n\t\t&\\judgeq e(\\alphabar (e\\sy(\\idfunc)))\\\\\n\t\t&\\sim e (\\alphabar (\\eta))\\\\\n\t\t&\\sim e (\\eta \\o \\alphabar(\\idfunc)) &&\\text{(naturality of $\\alphabar$)}\\\\\n\t\t&\\judgeq \\epsilon \\o (\\eta \\o \\alpha) \\smsh D\\\\\n\t\t&\\sim \\epsilon \\o (\\eta \\smsh D) \\o (\\alpha \\smsh D) &&\\text{(distrib. of $\\smsh$)}\\\\\n\t\t&\\sim \\alpha \\smsh D &&\\text{(\\autoref{lem:unit-counit})}\n\t\\end{align*}\n\tand, lastly,\n\t\\begin{align*}\n\t\t\\alphabar^L(\\idfunc)\n\t\t&\\judgeq e(\\alphabar \\o e\\sy(\\idfunc))\\\\\n\t\t&\\sim e(\\alphabar \\o \\eta)\\\\\n\t\t&\\sim e((\\alpha \\to A \\smsh (B \\smsh (C \\smsh D))) \\o \\eta) &&\\text{(\\autoref{lem:bar-homotopy})}\\\\\n\t\t&\\sim e((B \\smsh (C \\smsh D) \\to A \\smsh \\alpha) \\o \\eta) &&\\text{(dinaturality of $\\eta$)}\\\\\n\t\t&\\sim (A \\smsh \\alpha) \\o e(\\eta) &&\\text{(naturality of $e$)}\\\\\n\t\t&\\sim A \\smsh \\alpha &&\\text{(\\autoref{lem:unit-counit})}\n\t\\end{align*}\n\tthus proving the desired homotopy.\n\\end{proof}\n\n\\begin{thm}[Unitors triangle]\\label{thm:smash-unitors-triangle}\n\tFor $A$ and $B$ pointed types, there is a pointed homotopy\n\t\\[(A \\smsh \\lambda) \\o \\alpha \\sim (\\rho \\smsh B)\\]\n\tcorresponding to the commutativity of the following diagram:\n\t\\begin{center}\n\t\\begin{tikzcd}\n\t((A \\smsh \\bool) \\smsh B)\n\t\t\\arrow[rr, \"\\alpha\"]\n\t\t\\arrow[dr, swap, \"\\rho \\smsh B\"]\n\t&& (A \\smsh (\\bool \\smsh B))\n\t\t\\arrow[dl, \"A \\smsh \\lambda\"]\n\t\\\\\n\t& (A \\smsh B)\n\t\\end{tikzcd}\n\t\\end{center}\n\\end{thm}\n\\begin{proof}\n\tBy an argument similar to the one for $\\alphabar^L$ and $\\alphabar^R$ in \\autoref{thm:smash-associativity-pentagon}, one can verify the homotopies $A \\smsh \\lambda \\sim (e \\o (A \\to \\lambdabar) \\o e\\sy)(\\idfunc)$ and $\\rho \\smsh B \\sim (e \\o \\rhobar \\o e)(\\idfunc)$, simplifying the expressions in the sought homotopy. Then:\n\t\\begin{align*}\n\t\t(A \\smsh \\lambda) \\o \\alpha\n\t\t&\\sim e(\\lambdabar \\o e\\sy(\\idfunc)) \\o \\alphabar(\\idfunc) &&\\text{(simplification)}\\\\\n\t\t&\\sim \\alphabar(e(\\lambdabar \\o e\\sy(\\idfunc)) &&\\text{(naturality of $\\alphabar$)}\\\\\n\t\t&\\judgeq e(e(e\\sy \\o e\\sy (e(\\lambdabar \\o e\\sy(\\idfunc)))))\\\\\n\t\t&\\sim e(e(e\\sy \\o \\lambdabar \\o e\\sy(\\idfunc))) &&\\text{(cancelling)}\\\\\n\t\t&\\judgeq e(e(e\\sy \\o e \\o \\two\\sy \\o e\\sy(\\idfunc)))\\\\\n\t\t&\\sim e(e(\\two\\sy \\o e\\sy(\\idfunc))) &&\\text{(cancelling)}\\\\\n\t\t&\\judgeq (e \\o \\rhobar \\o e\\sy)(\\idfunc)\\\\\n\t\t&\\sim \\rho \\smsh B &&\\text{(simplification)}\n\t\\end{align*}\n\tgives the desired homotopy.\n\\end{proof}\n\n\\begin{thm}[Braiding-unitors triangle]\\label{thm:smash-braiding-unitors}\n\tFor a pointed type $A$, there is a pointed homotopy\n\t\\[\\lambda \\o \\gamma \\sim \\rho\\]\n\tcorresponding to the commutativity of the following diagram:\n\t\\begin{center}\n\t\\begin{tikzcd}\n\t(A \\smsh \\bool)\n\t\t\\arrow[rr, \"\\gamma\"]\n\t\t\\arrow[dr, swap, \"\\rho\"]\n\t&& (\\bool \\smsh A)\n\t\t\\arrow[dl, \"\\lambda\"]\n\t\\\\\n\t& A\n\t\\end{tikzcd}\n\t\\end{center}\n\\end{thm}\n\\begin{proof}\n\tWe have:\n\t\\begin{align*}\n\t\t\\lambda \\o \\gamma\n\t\t&\\judgeq \\lambdabar(\\idfunc) \\o \\gammabar(\\idfunc)\\\\\n\t\t&\\sim (\\gammabar \\o \\lambdabar)(\\idfunc) &&\\text{(naturality of $\\gammabar$)}\\\\\n\t\t&\\judgeq (e \\o \\twist \\o e\\sy \\o e \\o \\two\\sy)(\\idfunc)\\\\\n\t\t&\\sim (e \\o \\twist \\o \\two\\sy)(\\idfunc) &&\\text{(cancelling)}\\\\\n\t\t&\\sim (e \\o (A \\to \\two\\sy))(\\idfunc)\\\\\n\t\t&\\judgeq \\rhobar(\\idfunc) \\judgeq \\rho\n\t\\end{align*}\t\t\n\twhere the last homotopy is given by $(A \\to c) \\o \\two \\sim \\twist : (\\bool \\to A \\to X) \\to (A \\to X)$.\n\\end{proof}\n\n\\begin{lem}\\label{lem:pentagon-c}\n\tThe following diagram commutes, for $A$, $B$, $C$ and $X$ pointed types:\n\t\\begin{center}\n\t\\begin{tikzcd}[column sep=7em]\n\t\t(B \\smsh C \\to A \\to X)\n\t\t\t\\arrow[r, \"e\\sy\"]\n\t\t\t\\arrow[dd, swap, \"\\twist\"]\n\t\t& (B \\to C \\to A \\to X)\n\t\t\t\\arrow[d, \"B \\to \\twist\"]\n\t\t\\\\\n\t\t& (B \\to A \\to C \\to X)\n\t\t\t\\arrow[d, \"\\twist\"]\n\t\t\\\\\n\t\t(A \\to B \\smsh C \\to X)\n\t\t\t\\arrow[r, swap, \"A \\to e\\sy\"]\n\t\t& (A \\to B \\to C \\to X)\n\t\\end{tikzcd}\n\t\\end{center}\n\\end{lem}\n\\begin{proof}\n\tUnfolding the definition of $e\\sy$, we get the diagram:\n\t\\begin{center}\n\t\\begin{tikzcd}[column sep=6em]\n\t\t(B \\smsh C \\to A \\to X)\n\t\t\t\\arrow[rr, bend left=10, \"e\\sy\"]\n\t\t\t\\arrow[r, swap, \"C\\to -\"]\n\t\t\t\\arrow[dd, swap, \"\\twist\"]\n\t\t& ((C \\to B \\smsh C) \\to C \\to A \\to X)\n\t\t\t\\arrow[r, swap, \"\\eta \\to C \\to A \\to X\"]\n\t\t\t\\arrow[d, swap, \"(C \\to B \\smsh C) \\to \\twist\"]\n\t\t& (B \\to C \\to A \\to X)\n\t\t\t\\arrow[d, \"B \\to \\twist\"]\n\t\t\\\\\n\t\t& ((C \\to B \\smsh C) \\to A \\to C \\to X)\n\t\t\t\\arrow[r, swap, \"\\eta \\to A \\to C \\to X\"]\n\t\t\t\\arrow[d, swap, \"\\twist\"]\n\t\t& (B \\to A \\to C \\to X)\n\t\t\t\\arrow[d, \"\\twist\"]\n\t\t\\\\\n\t\t(A \\to B \\smsh C \\to X)\n\t\t\t\\arrow[rr, swap, bend right=10, \"A \\to e\\sy\"]\n\t\t\t\\arrow[r, \"A \\to (C \\to -)\"]\n\t\t& (A \\to (C \\to B \\smsh C) \\to C \\to X)\n\t\t\t\\arrow[r, \"A \\to (\\eta \\to C \\to X)\"]\n\t\t& (A \\to B \\to C \\to X)\n\t\\end{tikzcd}\n\t\\end{center}\n\tThe square in the top right is by \\autoref{lem:composition-pointed}, the square on the bottom right is naturality of $\\twist$. The commutativity of the pentagon on the left is TODO (it is a diagram of a 1-coherent symmetric closed category).\n\\end{proof}\n\n\n\\begin{thm}[Associativity-braiding hexagon]\\label{thm:smash-associativity-braiding}\n\tFor pointed types $A$, $B$ and $C$, there is a pointed homotopy\n\t\\[\\alpha \\o \\gamma \\o \\alpha \\sim (B \\smsh \\gamma) \\o \\alpha \\o (\\gamma \\smsh C)\\]\n\tcorresponding to the commutativity of the following diagram:\n\t\\begin{center}\n\t\\begin{tikzcd}\n\t\t((A \\smsh B) \\smsh C)\n\t\t\t\\arrow[r, \"\\alpha\"]\n\t\t\t\\arrow[d, swap, \"\\gamma \\smsh C\"]\n\t\t&(A \\smsh (B \\smsh C))\n\t\t\t\\arrow[r, \"\\gamma\"]\n\t\t& ((B \\smsh C) \\smsh A)\n\t\t\t\\arrow[d, \"\\alpha\"]\n\t\t\\\\\n\t\t((B \\smsh A) \\smsh C))\n\t\t\t\\arrow[r, swap, \"\\alpha\"]\n\t\t& (B \\smsh (A \\smsh C))\n\t\t\t\\arrow[r, swap, \"B \\smsh \\gamma\"]\n\t\t& (B \\smsh (C \\smsh A))\n\t\\end{tikzcd}\n\t\\end{center}\n\\end{thm}\n\\begin{proof}\n\tThe proof is structured similarly to the one for \\autoref{thm:smash-associativity-pentagon}: the homotopies\n\t\\begin{align*}\n\tB \\smsh \\gamma &\\sim \\gammabar^L(\\idfunc) &\\text{with\\ \\ } \\gammabar^L &\\defeq e \\o (B \\to \\gammabar) \\o e\\sy\\\\\n\t\\gamma \\smsh C &\\sim \\gammabar^R(\\idfunc) &\\text{with\\ \\ } \\gammabar^R &\\defeq e \\o \\gammabar \\o e\\sy\n\t\\end{align*}\t\t\n\tcan be proven in exactly the same way and, using these simplifications, we will show that both sides of the sought homotopy are homotopic to the same equivalence. Indeed we have:\n\t\\begin{align*}\n\t\t\\alpha \\o \\gamma \\o \\alpha\n\t\t&\\judgeq \\alphabar(\\idfunc) \\o \\gammabar(\\idfunc) \\o \\alphabar(\\idfunc)\\\\\n\t\t&\\sim (\\alphabar \\o \\gammabar \\o \\alphabar)(\\idfunc) &&\\text{(naturality of $\\gammabar$ and $\\alphabar$)}\\\\\n\t\t&\\judgeq (e \\o e \\o (A \\to e\\sy) \\o e\\sy \\o e \\o \\twist \\o e\\sy \\o e \\o e \\o (B \\to e\\sy) \\o e\\sy)(\\idfunc)\\\\\n\t\t&\\sim (e \\o e \\o (A \\to e\\sy) \\o \\twist \\o e \\o (B \\to e\\sy) \\o e\\sy)(\\idfunc) &&\\text{(cancelling)}\\\\\n\t\t&\\sim (e \\o e \\o \\twist \\o (B \\to \\twist) \\o e\\sy \\o e \\o (B \\to e\\sy) \\o e\\sy)(\\idfunc) &&\\text{(\\autoref{lem:pentagon-c})}\\\\\n\t\t&\\sim (e \\o e \\o \\twist \\o (B \\to \\twist) \\o (B \\to e\\sy) \\o e\\sy)(\\idfunc) &&\\text{(cancelling)}\n\t\\end{align*}\n\tand\n\t\\begin{align*}\n\t\t(B \\smsh \\gamma) \\o \\alpha \\o (\\gamma \\smsh C)\n\t\t&\\sim \\gammabar^L(\\idfunc) \\o \\alphabar \\o \\gammabar^R(\\idfunc) &&\\text{(simplification)}\\\\\n\t\t&\\sim (\\gammabar^R \\o \\alphabar \\o \\gammabar^L)(\\idfunc) &&\\text{(nat. of $\\alphabar$ and $\\gammabar^R$)}\\\\\n\t\t&\\judgeq (e \\o \\gammabar \\o e\\sy \\o e \\o e \\o (B \\to e\\sy) \\o e\\sy \\o e \\o (B \\to \\gammabar) \\o e\\sy)(\\idfunc)\\\\\n\t\t&\\sim (e \\o \\gammabar \\o e \\o (B \\to e\\sy) \\o (B \\to \\gammabar) \\o e\\sy)(\\idfunc) &&\\text{(cancelling)}\\\\\n\t\t&\\sim (e \\o \\gammabar \\o e \\o (B \\to (e\\sy \\o \\gammabar)) \\o e\\sy)(\\idfunc) &&\\text{(funct. of $B \\to -$)}\\\\\n\t\t&\\judgeq (e \\o e \\o \\twist \\o e\\sy \\o e \\o (B \\to (e\\sy \\o e \\o \\twist \\o e\\sy)) \\o e\\sy)(\\idfunc)\\\\\n\t\t&\\sim (e \\o e \\o \\twist \\o (B \\to \\twist) \\o (B \\to e\\sy) \\o e\\sy)(\\idfunc) &&\\text{(cancelling)}\n\t\\end{align*}\n\tproving the commutativity of the diagram.\n\\end{proof}\n\n\\begin{thm}[Double braiding]\\label{thm:smash-double-braiding}\n\tFor $A$ and $B$ pointed types, there is a pointed homotopy\n\t\\[\\gamma \\o \\gamma \\sim \\idfunc\\]\n\tcorresponding to the commutativity of the following diagram:\n\t\\begin{center}\n\t\\begin{tikzcd}\n\t(A \\smsh B)\n\t\t\\arrow[r, \"\\gamma\"]\n\t\t\\arrow[dr, equals]\n\t& (B \\smsh A)\n\t\t\\arrow[d, \"\\gamma\"]\n\t\\\\\n\t& (A \\smsh B)\n\t\\end{tikzcd}\n\t\\end{center}\n\\end{thm}\n\\begin{proof}\n\tUsing that $\\twist \\o \\twist \\sim \\idfunc$, we get:\n\t\\begin{align*}\n\t\t\\gamma \\o \\gamma\n\t\t&\\judgeq \\gammabar(\\idfunc) \\o \\gammabar(\\idfunc)\\\\\n\t\t&\\sim (\\gammabar \\o \\gammabar)(\\idfunc) &&\\text{(naturality of $\\gammabar$)}\\\\\n\t\t&\\judgeq (e \\o \\twist \\o e\\sy \\o e \\o \\twist \\o e\\sy)(\\idfunc)\\\\\n\t\t&\\sim \\idfunc &&\\text{(cancelling)}\n\t\\end{align*}\n\tas desired.\n\\end{proof}\n\n\\begin{cor}\n\t$(\\type^*,\\, \\bool,\\, \\smsh,\\, \\alpha,\\, \\lambda,\\, \\rho,\\, \\gamma)$ has a structure of a symmetric monoidal category, for $\\alpha$, $\\lambda$, $\\rho$ and $\\gamma$ as in \\autoref{def:smash-alrg}.\n\\end{cor}\n\\begin{proof}\n\tFollows by the theorems in this section.\n\\end{proof}\n\n\\section{Discussion}\n\nMany results in \\autoref{sec:smash} about $({-}) \\smsh B$ can be generalized to arbitrary pointed $\\infty$-functors $\\type^*\\to\\type^*$. Internally in HoTT we cannot talk about $\\infty$-categories and $\\infty$-functors (as far as we know), and therefore we cannot express this internally. But we only need finitely many coherences, so that we can formulate these results internally for arbitrary functors with enough coherences. However, when we tried this, we run into the problem that we needed all (or at least, some) coherences in the definition of a tricategory and functor for tricategories, which are harder to check than the result we wanted to prove. Here we sketch this argument.\n\n$\\type^*$ is a pointed $(\\infty,1)$-category meaning it has an zero object $\\unit$, which is an object that is both (homotopy-)initial and (homotopy-)terminal. Given two pointed $(\\infty,1)$-categories $\\mc{A}$ and $\\mc{B}$, we call a map $F:\\mc{A}\\to\\mc{B}$ a 1-coherent functor if it satisfies all the coherences of a functor (i.e. an action on morphisms and a 2-cell stating that $F$ respects compositions and identities), a 2-coherent functor if it satisfies all the coherences of a bifunctor (a functor between bicategories) and a 3-coherent functor if it satisfies all the coherences of a trifunctor (a functor between tricategories).\n% Add reference:\n% @article{gurski2006algebraic,\n% title={An algebraic theory of tricategories},\n% author={Gurski, Nick},\n% year={2007},\n% url={http://gauss.math.yale.edu/~mg622/tricats.pdf}\n% }\n\nWe call $F:\\mc{A}\\to\\mc{B}$ pointed if it preserves the zero object, i.e. if $F\\unit=\\unit$. If $F$ is a pointed 1-coherent functor, we can then show that $F(0_{A,B})=0_{FA,FB}$, where $0_{A,B}$ is the zero morphism (the canonical morphism $A\\to\\unit\\to B$).\n\nIf $F$ is a pointed 2-coherent functor (or more precisely a 1-coherent functor which a coherence for the associativity 2-cell), then we can show that \\autoref{lem:smash-coh} holds for $F$. We can show that the two pentagons have the same filler if $F$ is a 3-coherent functor. \n\nNow we can also show \\autoref{thm:smash-functor-right} more generally, but we will only formulate that for functors between pointed types. If $F:\\type^*\\to\\type^*$ is a 2-coherent pointed functor, then it induces a map\n$(A\\to B)\\to(FA\\to FB)$ which is natural in $A$ and $B$. Moreover, if $F$ is 3-coherent then this is a pointed natural transformation in $B$.\n\n\\section{References}\n\\begin{itemize}\n\\item (TODO)\n\\item An algebraic theory of tricategories, Nick Gurski\n\\item Closed Categories, Samuel Eilenberg and G. Max Kelly (Chapter 2, Theorem 5.3, 1-categorical account of getting a monoidal category from a enriched adjunction in a closed category)\n\\item Permutative categories, multicategories, and algebraic K-theory, A D Elmendorf and M A Mandell (Lemma 4.20 gives a 1-categorical account that if C is a symmetric monoidal closed bicomplete 1-category, then the category of pointed objects is a symmetric monoidal closed bicomplete 1-category).\n\\item On embedding closed categories, B.J. Day and M.L. Laplaza (definition of symmetric closed category).\n\\item Maybe: Handbook of Categorical Algebra 2  Categories and Structures, F Borceux. (Bjorn used it to look things up about symmetric monoidal closed categories)\n\\end{itemize}\n\\end{document}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{thm}[Associativity]\\label{thm:smash-associativity}\n  The smash product is associative: there is an equivalence $\\alpha : (A \\smsh B) \\smsh C \\simeq A \\smsh (B \\smsh C)$ which is natural in $A$, $B$ and $C$.\n\\end{thm}\n\\begin{proof}\n  For a pointed type $X$, let $\\alphabar_X$ be the composite of the following equivalences:\n  \\begin{align*}\n    A \\smsh (B \\smsh C)\\to X&\\simeq A \\to B\\smsh C\\to X && (e\\sy)\\\\\n    &\\simeq A \\to B\\to C\\to X && (A \\to e\\sy)\\\\\n    &\\simeq A \\smsh B\\to C\\to X && (e)\\\\\n    &\\simeq (A \\smsh B)\\smsh C\\to X. && (e)\n  \\end{align*}\n  $\\alphabar_X$ is natural in $A,B,C,X$ by repeatedly applying \\autoref{lem:e-natural}. Let\n  $\\alpha\\defeq\\alphabar_{A \\smsh (B \\smsh C)}(\\idfunc)$ and\n  $\\alpha\\sy\\defeq\\alphabar\\sy_{(A \\smsh B) \\smsh C}(\\idfunc)$. These maps are inverses by \\autoref{lem:yoneda}; lastly, $\\alpha$ is natural in $A$, $B$\n  and $C$, since $\\alphabar_X$ is.\n\\end{proof}\n\n\\begin{thm}[Unitors]\\label{thm:smash-unitors}\n\tThe type of booleans $\\bool$ is a left- and right unit for the smash product: there are equivalences\n\t$\\lambda : (\\bool \\smsh B) \\simeq B$ and $\\rho : (A \\smsh \\bool) \\simeq A$, respectively natural in $B$ and in $A$.\n\\end{thm}\n\\begin{proof}\n\tWe define $\\lambdabar_X$ as the following composition of equivalences:\n\t\\begin{align*}\n\t\tB \\to X &\\simeq \\bool \\to B \\to X && (t\\sy)\\\\\n\t\t\t&\\simeq \\bool \\smsh B \\to X && (e)\n\t\t\\end{align*}\n\tand, similarly, $\\rhobar_X$ as the composition:\n\t\\begin{align*}\n\t\tA \\to X &\\simeq A \\to \\bool \\to X && (A \\to t\\sy)\\\\\n\t\t\t&\\simeq A \\smsh \\bool \\to X && (e)\n\t\\end{align*}\n\tfor any pointed type $X$, where $t : (\\bool \\to X) \\simeq X$ is the pointed equivalence with underlying function sending $f : \\bool \\to X$ to $f(1_\\bool) : X$. Both $\\lambdabar_X$ and $\\rhobar_X$ are natural in their arguments by multiple applications of \\autoref{lem:e-natural}. By an argument similar to \\autoref{thm:smash-associativity}, we can define $\\lambda \\defeq \\lambdabar_B(\\idfunc)$ and $\\rho \\defeq \\rhobar_A(\\idfunc)$ together with the corresponding inverses, yielding the sought natural equivalences.\n\\end{proof}\n\n\\begin{thm}[Braiding]\\label{thm:smash-braiding}\n\tThe smash product is symmetric, i.e. there are equivalences $\\gamma : A \\smsh B \\simeq B \\smsh A$, natural in $A$ and $B$.\n\\end{thm}\n\\begin{proof}\n\tWe define $\\gammabar_X$, for $X$ a pointed type, as the composition of the following equivalences:\n\t\\begin{align*}\n\t\tB \\smsh A \\to X &\\simeq B \\to A \\to X && (e\\sy)\\\\\n\t\t\t&\\simeq A \\to B \\to X && (c)\\\\\n\t\t\t&\\simeq A \\smsh B \\to X && (e)\n\t\\end{align*}\n\twhere $c : (A \\to B \\to X) \\simeq (B \\to A \\to X)$ is the obvious pointed equivalence, natural in $A$, $B$ and $X$. $\\gamma_X$ is then also natural in all its arguments, by myltiple applications of \\autoref{lem:e-natural}; then, as in \\autoref{thm:smash-associativity}, we can define $\\gamma \\defeq \\gammabar_{B\\smsh A} (\\idfunc)$ and $\\gamma\\sy \\defeq \\gammabar_{A \\smsh B}\\sy (\\idfunc)$\n\\end{proof}\n", "meta": {"hexsha": "a5cd15041e3d67edb2866c418084fe4e12c90f8a", "size": 65264, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Notes/smash.tex", "max_stars_repo_name": "cmu-phil/Spectral", "max_stars_repo_head_hexsha": "9075b67c497249c564a0848db3b2ea69b4612912", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 40, "max_stars_repo_stars_event_min_datetime": "2016-03-29T19:44:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-18T15:38:13.000Z", "max_issues_repo_path": "Notes/smash.tex", "max_issues_repo_name": "cmu-phil/Spectral", "max_issues_repo_head_hexsha": "9075b67c497249c564a0848db3b2ea69b4612912", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-09-15T23:06:07.000Z", "max_issues_repo_issues_event_max_datetime": "2017-09-15T23:06:07.000Z", "max_forks_repo_path": "Notes/smash.tex", "max_forks_repo_name": "cmu-phil/Spectral", "max_forks_repo_head_hexsha": "9075b67c497249c564a0848db3b2ea69b4612912", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2016-03-10T19:18:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-24T16:24:02.000Z", "avg_line_length": 50.3191981496, "max_line_length": 689, "alphanum_fraction": 0.6464360137, "num_tokens": 26112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3008197622347974}}
{"text": "%!TEX root = main.tex\n\nThis chapter contains a condensed version of several sections from~\\cite{DBLP:conf/tacas/DijkP16}.\n\n\\section{Bisimulation minimisation}\n\nOne core challenge in model checking is the state space explosion problem.\nThe space and time requirements of model checking\nincrease exponentially with the size of the models.\nBisimulation minimisation computes the smallest equivalent model (maximal bisimulation) under some notion of equivalence, which can significantly reduce the number of states.\nThis technique is also used to abstract models from internal behavior, when only observable behavior is relevant.\n\n\n\n\nThe maximal bisimulation of a model is typically computed using\npartition refinement.\nStarting with an initially coarse partition (e.g. all states are equivalent),\nthe partition is refined until states in each equivalence class can no longer be distinguished.\nThe result is the maximal bisimulation with respect to the initial partition.\n%\n%\n%\nAnother well-known method to deal with very large state spaces is symbolic model checking, where sets of states are represented by their characteristic function, which is efficiently stored using  binary decision diagrams (BDDs).\n\n\nOne particular application of symbolic bisimulation minimisation is as a bridge between symbolical models and explicit-state analysis algorithms.\nSuch models can have very large state spaces that are efficiently encoded using BDDs.\nIf the minimised model is sufficiently small, then it can be analyzed efficiently using explicit-state algorithms.\nThe symbolic representation of the maximal bisimulation, when effective, often tends to be much larger than the original model.\n\n\n\nBlom and Orzan~\\cite{DBLP:journals/entcs/BlomO03} introduced a signature-based method for partition refinement, which assigns states to equivalence classes according to a characterizing signature.\nThis method easily extends to various types of bisimulation.\nWimmer et al. \\cite{DBLP:conf/glvlsi/WimmerHB07,DBLP:conf/atva/WimmerHHSB06} implemented symbolic bisimulation minimisation based on the signatures introduced by Blom.\nTheir tool is called \\textsc{Sigref} and their work is the basis for \\textsc{SigrefMC}.\n\n\nTo take advantage of computer systems with multiple processors,\ndeveloping scalable parallel algorithms is the way forward.\nIn~\\cite{DBLP:conf/tacas/DijkP15}, \nwe implemented the multi-core BDD package Sylvan, applying parallelism to symbolic model checking.\n\\textsc{SigrefMC} is based on Sylvan to implement multi-core signature-based symbolic partition refinement.\n\n\n\n\\section{Definitions}\n\nWe recall the basic definitions of partitions, of LTSs, of CTMCs, of IMCs, and of various bisimulations as in~\\cite{DBLP:journals/entcs/BlomO03,DBLP:conf/fmco/HermannsK09,DBLP:conf/glvlsi/WimmerHB07,DBLP:conf/atva/WimmerHHSB06,atr16}.\n\n\n\n\n%\\subsection{Partitions}\n\n\\begin{definition}\nGiven a set $S$, a partition $\\pi$ of $S$ is a subset $\\pi\\subseteq 2^S$ such that\n$$\\bigcup_{C\\in \\pi} C=S \\qquad \\text{and}\\qquad \\forall C,C'\\in \\pi\\colon (C=C'\\vee C\\cap C'=\\emptyset).$$\n\\end{definition}\n\nIf $\\pi'$ and $\\pi$ are two partitions, then $\\pi'$ is a refinement of $\\pi$, written $\\pi'\\refines \\pi$, \n%and $\\pi$ is coarser than $\\pi'$, written $\\pi\\refinedby \\pi'$, \nif each block of $\\pi'$ is contained in a block of $\\pi$.\n%\n%\nThe elements of $\\pi$ are called equivalence classes or blocks.\n%\nEach equivalence relation $\\equiv$ is associated with a partition $\\pi=S/\\!\\equiv$.\nIn this paper, we use $\\pi$ and $\\equiv$ interchangeably.\n%\n\n\n\n%\\subsection{Transition systems}\n\n\\begin{definition}\nA labeled transition system (LTS) is a tuple $(S,\\act,\\rightarrow)$, consisting of a set of states $S$, a set of labels $\\act$ that may contain the non-observable action $\\tau$, and transitions $\\rightarrow\\,\\subseteq S\\times\\act\\times S$.\n\\end{definition}\n\nWe write $s\\overset{a}\\rightarrow t$ for $(s,a,t)\\!\\in\\,\\rightarrow$.\nand $s\\!\\stackrel{\\tau}{\\nrightarrow}$ when $s$ has no outgoing $\\tau$-transitions.\nWe use $\\overset{a*}\\rightarrow$ to denote the transitive reflexive closure of $\\overset{a}\\rightarrow$.\nGiven an equivalence relation $\\equiv$, we write $\\smash{\\stackrel[\\raisebox{1ex}{$\\scriptstyle\\equiv$}]{a}{\\rightarrow}}$ for $\\overset{a}\\rightarrow\\!\\cap\\!\\equiv$, i.e., transitions between equivalent states, called \\emph{inert} transitions.\nWe use $\\smash{\\stackrel[\\raisebox{1ex}{$\\scriptstyle\\equiv$}]{a*}{\\rightarrow}}$ \nfor the transitive reflexive closure of $\\smash{\\stackrel[\\raisebox{1ex}{$\\scriptstyle\\equiv$}]{a}{\\rightarrow}}$.\n\n\n\n\\begin{definition}\nA continuous-time Markov chain (CTMC) is a tuple $(S,\\Rightarrow)$, consisting of a set of states $S$ and Markovian transitions $\\Rightarrow\\,\\subseteq S\\times \\mathbb{R}^{> 0}\\times S$.\n%,and a labeling function $L\\colon S\\rightarrow 2^{AP}$, which assigns each state a set of atomic propositions from $AP$.\n\\end{definition}\n\n\nWe write $s\\overset{\\lambda}\\Rightarrow t$ for $(s,\\lambda,t)\\!\\in\\,\\Rightarrow$. The interpretation of %a Markovian transition \n$s\\overset{\\lambda}\\Rightarrow t$ is that the CTMC can switch from $s$ to $t$ within $d$ time units with probability $1\\!-\\!e^{-\\lambda\\cdot d}$.\n%\nFor a state $s$, let $\\textbf{R}(s)(s')=\\sum\\{\\lambda\\mid s\\overset{\\lambda}\\Rightarrow s'\\}$ be the rate to move from state $s$ to state $s'$,\nand let $\\textbf{R}(s)(C)=\\sum_{s'\\in C} \\textbf{R}(s)(s')$ be the cumulative rate to reach a set of states $C\\subseteq S$ from state $s$.\n\n\n\n\n\\begin{definition}\nAn interactive Markov chain (IMC) is a tuple ($S,\\act,\\rightarrow,\\Rightarrow)$, consisting of a set of states $S$, a set of labels $\\act$ that may contain the non-observable action $\\tau$, transitions $\\rightarrow\\,\\subseteq S\\times\\act\\times S$, and Markovian transitions $\\Rightarrow\\,\\subseteq S\\times\\mathbb{R}^{> 0}\\times S$. \n\\end{definition}\n\nAn IMC basically combines the features of an LTS and a CTMC.\n%\nOne feature of IMCs is the \\emph{maximal progress assumption}.\nInternal interactive transitions, i.e. $\\tau$-transitions, can be assumed to take place immediately, while the probability that a Markovian transition executes immediately is zero.\nTherefore, we may remove all Markovian transitions from states that have outgoing $\\tau$-transitions: $s\\stackrel{\\tau}{\\rightarrow}$ implies $\\textbf{R}(s)(S)=0$.\nWe call IMCs to which this operation has been applied \\emph{maximal-progress-cut} (mp-cut) IMCs.\n\n\n\n\n\n%\\subsection{Bisimulation}\n\\label{sec:bisim_lit}\n\n\\newcommand{\\eqs}[0]{\\ensuremath{\\equiv_{S}}}\n\\newcommand{\\eqb}[0]{\\ensuremath{\\equiv_{B}}}\n%$\\thicksim_s$\n\n%\n%A partition $\\pi$ of $S$ is a subset $\\pi\\subseteq 2^S$ such that $\\mathlarger{\\bigcup}_{C\\in\\pi}C=S$ and $\\forall C,C'\\in\\pi\\colon C=C'\\vee C\\cap C'=\\emptyset$.\n%\n%\n%\n%Every equivalence relation $\\mathcal{R}$ corresponds to a partition $\\pi$.\n%In the context of bisimulation, the equivalence classes are called {\\em blocks}.\n%We write $\\pi(s)$ to denote the block containing $s$ and \n%$\\pi(s,t)$ as shorthand for $\\pi(s)=\\pi(t)$, i.e., $\\mathcal{R}(s,t)$.\n%Unless otherwise stated,\n%we use $\\mathcal{R}$ and $\\pi$ interchangeably.\n\n%\\td{Perhaps modify use of $\\mathcal{R}$ and $\\pi$, since elsewhere we use $\\equiv$ for equivalence relations}\n\nFor LTSs, strong and branching bisimulation are typically defined as follows:\n\n\\begin{definition}%[strong bisimulation]\n\\label{def:stronglts}\nAn equivalence relation $\\eqs$ is a strong bisimulation on an LTS if for all states $s,t,s'$ with $s\\eqs t$ and for all $s\\overset{a}\\rightarrow s'$, there exists a state $t'$ with $t\\overset{a}\\rightarrow t'$ and $s'\\eqs t'$.\n\\end{definition}\n\n\\begin{definition}%[branching bisimulation]\n\\label{def:branchinglts}\nAn equivalence relation $\\eqb$ is a branching bisimulation on an LTS if for all states $s,t,s'$ with $s\\eqb t$ and for all $s\\overset{a}\\rightarrow s'$, either\n\\begin{compactitem}\n\\item $a=\\tau$ and $s'\\eqb t$, or\n\\item there exist states $t',t''$ with $t\\overset{\\tau*}\\rightarrow t'\\overset{a}\\rightarrow t''$ and $t\\eqb t'$ and $s'\\eqb t''$.\n\\end{compactitem}\n\\end{definition}\n\nFor CTMCs, strong bisimulation is defined as follows:\n\n\\begin{definition}\n\\label{def:strongctmc}\nAn equivalence relation $\\eqs$ is a strong bisimulation on a CTMC if for all $(s,t)\\in\\;\\eqs$ and for all classes $C\\in S/\\!\\eqs$, $\\textbf{R}(s)(C)=\\textbf{R}(t)(C)$.\n\\end{definition}\n\nFor mp-cut IMCs, strong and branching bisimulation are defined as follows:\n\n%\\begin{definition}\n%An equivalence relation $\\eqs$ is a strong bisimulation on an IMC if for all $(s,t)\\in\\eqs$ and for all equivalence classes $C$, the following holds:\n%\\begin{compactitem}\n%\\item $s\\overset{a}\\rightarrow s'$ implies $t\\overset{a}\\rightarrow t'$ for a $t'\\in S$ with $s'\\eqs t'$\n%\\item $s\\stackrel{\\tau}{\\nrightarrow}$ implies $\\textbf{R}(s)(C)=\\textbf{R}(t)(C)$\n%\\end{compactitem}\n%\\end{definition}\n%\n%\\begin{definition}\n%An equivalence relation $\\eqb$ is a branching bisimulation on an IMC if for all $(s,t)\\in\\eqb$ and for all equivalence classes $C$, the following holds:\n%\\begin{compactitem}\n%\\item $s\\overset{a}\\rightarrow s'$ implies\n%\\begin{compactitem}\n%\\item $a=\\tau$ and $s'\\eqb t$, or\n%\\item there are $t',t''\\in S$ with $t {\\stackrel[\\raisebox{1ex}{$\\scriptstyle\\eqb$}]{\\tau*}{\\rightarrow}} t'\\overset{a}\\rightarrow t''$ and  $s'\\eqb t''$.\n%\\end{compactitem}\n%\\item $s\\stackrel{\\tau}{\\nrightarrow}$ implies $\\exists t'\\in S\\colon t \\smash{\\stackrel[\\raisebox{1ex}{$\\scriptstyle\\eqb$}]{\\tau*}{\\rightarrow}} t'\\stackrel{\\tau}{\\nrightarrow}\\wedge\\;\\textbf{R}(s)(C)=\\textbf{R}(t')(C)$\n%\\end{compactitem}\n%\\end{definition}\n\n\n\n%For an mp-cut IMC, $s\\stackrel{\\tau}{\\rightarrow}$ implies $\\textbf{R}(s)=0$.\n%\\cite{atr16} defines and proves:\n\n\\begin{definition}\n\\label{def:strongimc}\nAn equivalence relation $\\eqs$ is a strong bisimulation on an mp-cut IMC if for all $(s,t)\\in\\eqs$ and for all classes $C\\in S/\\!\\eqs$\n\\begin{compactitem}\n%\\item $s\\overset{a}\\rightarrow s'$ for some $s'$ implies $t\\overset{a}\\rightarrow t'$ for some $t'\\in S$ with $(s',t')\\in\\,\\eqs$\n\\item $s\\overset{a}\\rightarrow s'$ for some $s'\\in C$ implies $t\\overset{a}\\rightarrow t'$ for some $t'\\in C$\n\\item $\\textbf{R}(s)(C)=\\textbf{R}(t)(C)$\n\\end{compactitem}\n\\end{definition}\n\n\\begin{definition}\n\\label{def:branchingimc}\nAn equivalence relation $\\eqb$ is a branching bisimulation on an mp-cut IMC if for all $(s,t)\\in\\eqb$ and for all classes $C\\in S/\\!\\eqb$\n\\begin{compactitem}\n\\item $s\\overset{a}\\rightarrow s'$ for some $s'\\in C$ implies\n\\begin{compactitem}\n\\item $a=\\tau$ and $(s,s')\\in\\,\\eqb$, or\n\\item there exist states $t',t''\\in S$ with $t \\overset{\\tau*}{\\rightarrow} t'\\overset{a}\\rightarrow t''$ and $(t,t')\\in\\,\\eqb$ and $t''\\in C$.\n\\end{compactitem}\n\\item $\\textbf{R}(s)(C)>0$ implies\n\\begin{compactitem}\n\\item $\\textbf{R}(s)(C)=\\textbf{R}(t')(C)$ for some $t'\\in S$ such that $t \\overset{\\tau*}{\\rightarrow} t'\\!\\stackrel{\\tau}{\\nrightarrow}$ and $(t,t')\\in\\,\\eqb$.\n\\end{compactitem}\n\\item $s\\!\\stackrel{\\tau}{\\nrightarrow}$ implies $t\\overset{\\tau*}{\\rightarrow} t'\\!\\stackrel{\\tau}{\\nrightarrow}$ for some $t'$\n\\end{compactitem}\n\\end{definition}\n\n\n%Branching bisimulation for IMCs is \\emph{divergence sensitive}.\n%If a state $s$ can do internal $\\tau$-transitions to a state without internal $\\tau$-transitions ($s\\smash{\\stackrel[\\raisebox{1ex}{$\\scriptstyle\\eqb$}]{\\tau*}{\\rightarrow}\\stackrel{\\tau}{\\nrightarrow}}$), it is said to be \\emph{time-convergent}, otherwise it is \\emph{time-divergent}.\n\n\n\n\n\\section{Signature-based Bisimulation}\n\\label{sec:sigref}\n\n%\\subsection{Signature-based partition refinement}\n\nBlom and Orzan~\\cite{DBLP:journals/entcs/BlomO03} introduced a signature-based approach to compute the maximal bisimulation of an LTS,\nwhich was further developed into a symbolic method by Wimmer et al.~\\cite{DBLP:conf/atva/WimmerHHSB06}.\n%The signatures are the same as the signatures defined above.\n%\n%\n%In the literature, signature-based partition refinement is a well-known method to compute the maximal bisimulation of a system.\nEach state is characterized by a \\emph{signature}, which is the same for all equivalent states in a bisimulation.\nThese signatures are used to refine a partition of the state space until a fixed point is reached, which is the maximal bisimulation.\n\n%In the current paper, we generalize this approach\n%%by redefining bisimulation based on the associated signature \n%and define a key property of the signature that causes partition refinement to result in the maximal bisimulation associated with that signature.\n\nIn the literature, multiple signatures are sometimes used that together fully characterize states, for example based on the state labels, based on the rates of continous-time transitions, and based on the enabled interactive transitions.\n%\n%\nIn the current paper, these multiple signatures are considered elements of a single signature that fully characterizes each state.\n\n\\begin{definition}\nA signature $\\sigma(\\pi)(s)$ is a tuple of functions $f_i(\\pi)(s)$, that together characterize each state $s$ with respect to a partition $\\pi$.\n\\end{definition}\n\nTwo signatures $\\sigma(\\pi)(s)$ and $\\sigma(\\pi)(t)$ are equivalent, if and only if for all $f_i$, $f_i(\\pi)(s)=f_i(\\pi)(t)$.\n%\n%\n\n\n\n\n\n\nThe signatures of five bisimulations from Section~\\ref{sec:bisim_lit} are known from the literature.\n%\n%\nFor all actions $a\\in\\act$ and equivalence classes $C\\in \\pi$, we define\n%\n%\\begin{align*}\n%\\textbf{T}({\\pi})(s)&=\\{(a,C)\\mid \\exists s'\\in C\\colon s\\overset{a}\\rightarrow s'\\} \\\\\n%\\textbf{B}({\\pi})(s)&=\\{(a,C)\\mid\\exists s'\\in C\\colon s\\smash{\\stackrel[\\raisebox{1ex}{$\\scriptstyle\\equiv$}]{\\tau*}{\\rightarrow}}\\overset{a}\\rightarrow s' \\wedge \\neg(a=\\tau\\wedge s\\in C)\\} \\\\\n%\\textbf{R}^s({\\pi})(s)&=C\\mapsto\\textbf{R}(s)(C) \\\\\n%\\textbf{R}^b({\\pi})(s)&=C\\mapsto\\max(\\{\\textbf{R}(s')(C)\\mid s\\stackrel[\\raisebox{1ex}{$\\scriptstyle\\equiv$}]{\\tau*}{\\rightarrow}s'\\stackrel{\\tau}{\\nrightarrow}\\})\n%\\end{align*}\n%\n%\n%\n\\begin{itemize}\n\\def\\arraystretch{1.1}\n\\item $\\textbf{T}({\\pi})(s)=\\{(a,C)\\mid \\exists s'\\in C\\colon s\\overset{a}\\rightarrow s'\\}$\n\\item $\\textbf{B}({\\pi})(s)=\\{(a,C)\\mid\\exists s'\\in C\\colon s\\smash\\taustarpi\\overset{a}\\rightarrow s' \\wedge \\neg(a=\\tau\\wedge s\\in C)\\}$\n\\item $\\textbf{R}^s({\\pi})(s)=C\\mapsto\\textbf{R}(s)(C)$\n\\item $\\textbf{R}^b({\\pi})(s)=C\\mapsto\\max(\\{\\textbf{R}(s')(C)\\mid \\exists s'\\colon s\\smash\\taustarpi s'\\!\\stackrel{\\tau}{\\nrightarrow}\\})$\n%\\item $\\textbf{D}(\\pi)(s)=\\exists s'\\colon s{\\stackrel{\\tau*}{\\rightarrow}s'\\stackrel{\\tau}{\\nrightarrow}}$\n\\end{itemize}\n%\n%\nThe five bisimulations are associated with the following signatures:\n%\n%The signatures for each type of bisimulation are as follows:\n%\n\\begin{center}\n{\n%\\noindent\n\\def\\arraystretch{1.1}\n%\\setlength\\tabcolsep{0.3em}\n%\\setlength\\tabcolsep{0em}\n\\begin{tabular}{@{}p{70mm}p{25mm}@{}l@{}}\nStrong bisimulation for an LTS & $(\\textbf{T})$ & \\cite{DBLP:conf/atva/WimmerHHSB06} \\\\\nBranching bisimulation for an LTS & $(\\textbf{B})$ & \\cite{DBLP:conf/atva/WimmerHHSB06} \\\\\nStrong bisimulation for a CTMC & $(\\textbf{R}^s)$ & \\cite{DBLP:conf/mmb/WimmerB10} \\\\\nStrong bisimulation for an mp-cut IMC & $(\\textbf{T}, \\textbf{R}^s)$ & \\cite{atr16} \\\\\nBranching bisimulation for an mp-cut IMC & $(\\textbf{B}, \\textbf{R}^b,s\\smash{\\stackrel{\\tau*}{\\rightarrow}\\stackrel{\\tau}{\\nrightarrow}})$ & \\cite{atr16} \\\\\n\\end{tabular}\n}\n\\end{center}\n\n%The function $\\textbf{T}_{\\eqs}(s)$ can be understood as describing the \\emph{signature} or \\emph{fingerprint} of state $s$ with respect to strong bisimulation, and $\\textbf{B}_{\\eqs}(s)$ with respect to branching bisimulation.\nFunctions $\\textbf{T}$ and $\\textbf{B}$ assign to each state $s$ all actions $a$ and equivalence classes $C\\in\\pi$, such that state $s$ can reach $C$ by an action $a$ either directly ($\\textbf{T}$) or via any number of inert $\\tau$-steps ($\\textbf{B}$).\n$\\textbf{R}^s$ equals $\\textbf{R}$ but with the domain restricted to the equivalence classes $C\\in\\pi$, and represents the cumulative rate with which state $s$ can go to states in $C$.\n%\n%\n$\\textbf{R}^b$ equals $\\textbf{R}^s$ for states $s\\!\\stackrel{\\tau}{\\nrightarrow}$, and takes the highest ``reachable rate'' for states with inert $\\tau$-transitions.\n%\nIn branching bisimulation for mp-cut IMCs, the ``highest reachable rate'' is by definition the rate that all states ${s\\!\\overset{\\tau}{\\nrightarrow}}$ in $C$ have.\n%\nThe element $s\\smash{\\stackrel{\\tau*}{\\rightarrow}\\stackrel{\\tau}{\\nrightarrow}}$ distinguishes time-convergent states from time-divergent states~\\cite{atr16}, and is independent of the partition.\n%\n%\n%This is For branching bisimulation, all internal $\\tau$-transitions that converge to a bisimilar state, converge to equivalent states (with the same Markovian rates), otherwise they would be external $\\tau$-transitions.\n%See further below why computing the maximum is a correct approach.\n\n\nFor the bisimulations of Definitions~\\ref{def:stronglts}--\\ref{def:branchingimc}, we state:\n\n\\begin{lemma}\n\\label{lem:parbi}\nA partition $\\pi$ is a bisimulation, if and only if for all $s$ and $t$ that are equivalent in $\\pi$, %$C\\in\\pi_B$, $\\forall s,t\\in C\\colon  \n$\\sigma(\\pi)(s)=\\sigma(\\pi)(t)$.\n%all equivalent states \n%have the same signature with respect to that equivalence relation.\n\\end{lemma}\n\nFor the above definitions it is fairly straightforward to prove that they are equivalent to the classical definitions of bisimulation.\nSee e.g.~\\cite{DBLP:journals/entcs/BlomO03,DBLP:conf/atva/WimmerHHSB06} for the bisimulations on LTSs and~\\cite{atr16} for the bisimulations on IMCs.\n\n\n\n\n\n\n\n\\section{Partition refinement}\nThe definition of signature-based partition refinement is as follows.\n\n\\begin{definition}[Partition refinement with full signatures]\n\\label{def:sigrefpi}\n%Bisimulation via signature refinement:\n\\setlength{\\abovedisplayskip}{0.4em}\n\\setlength{\\belowdisplayskip}{0pt}\n\\begin{align*}\n\\sigref(\\pi,\\sig) \\defeq\\, & \\{\\{t\\in S\\mid \\sig(\\pi)(s) = \\sig(\\pi)(t)\\}\\mid s\\in S\\} \\\\\n\\pi^0 \\defeq\\, & \\{S\\} \\\\\n\\pi^{n+1} \\defeq\\, & \\sigref(\\pi^n, \\sig) \\\\\n%\\pi^{\\infty} \\defeq\\, & \\pi \\colon \\sigref(\\pi, \\sig)=\\pi \\\\\n%\\pi^0 \\defeq\\, & \\{S\\} \\\\\n%\\pi^{n+1} \\defeq\\, & \\{\\{t\\in S\\mid \\sig(\\pi^n)(s) = \\sig(\\pi^n)(t)\\}\\mid s\\in S\\}\n\\end{align*}\n\\end{definition}\n%% fix double line after align*+definition\n\\vspace{-1.5em}\n\nThe algorithm iteratively refines the initial coarsest partition $\\{S\\}$ according to the signatures of the states, until some fixed point $\\pi^{n+1}=\\pi^{n}$ is obtained.\n%\nThis fixed point is the maximal bisimulation for ``monotone signatures'':\n\n\\begin{definition}\n%A signature $\\sig$ is monotone if\n%$\\forall \\pi'\\sqsupseteq \\pi\\colon \\forall s,t\\in S\\colon \\sig(\\pi')(s)=\\sig(\\pi')(t) \\implies \\sig(\\pi)(s)=\\sig(\\pi)(t)$.\nA signature is monotone if for all $\\pi,\\pi'$ with $\\pi'\\refines\\pi$, whenever $\\sig(\\pi')(s)=\\sig(\\pi')(t)$, also $\\sig(\\pi)(s)=\\sig(\\pi)(t)$. \n%all $s,t$ that have the same signature in $\\pi'$ also have the same signature in $\\pi$.\n\\end{definition}\nFor all monotone signatures, the $\\sigref$ operator is monotone: $\\pi\\refines\\pi'$ implies $\\sigref(\\pi,\\sigma)\\refines\\sigref(\\pi',\\sigma)$. \nHence, following Kleene's fixed point theorem, the procedure above reaches the greatest fixed point. \n\n%We present a variation of signature-based partition refinement.\nIn Definition~\\ref{def:sigrefpi}, the full signature is computed in every iteration.\nWe propose to apply partition refinement using parts of the signature. By definition,\n$\\sigma(\\pi)(s)=\\sigma(\\pi)(t)$ if and only if for all parts $f_i(\\pi)(s)=f_i(\\pi)(t)$.\n\n\\begin{definition}[Partition refinement with partial signatures]\n\\label{def:sigref2}\n\\setlength{\\abovedisplayskip}{0.4em}\n\\setlength{\\belowdisplayskip}{0pt}\n\\begin{align*}\n\\sigref(\\pi,f_i) \\defeq\\, & \\{\\{t\\in S\\mid f_i(\\pi)(s) = f_i(\\pi)(t) \\wedge s \\equiv_{\\pi} t \\}\\mid s\\in S\\} \\\\\n\\pi^0 \\defeq\\, & \\{S\\} \\\\\n\\pi^{n+1} \\defeq\\, & \\sigref(\\pi^n, f_i) \\qquad (\\textnormal{select $f_i\\in\\sig$})\\\\\n%\\pi^{\\infty} \\defeq\\, & \\pi \\colon \\forall f_i\\in \\sig\\colon \\sigref(\\pi, f_i)=\\pi \\\\\n\\end{align*}\n\\end{definition}\n%% fix double line after align*+definition\n\\vspace{-1.5em}\n\nWe always select some $f_i$ that refines the partition $\\pi$.\nA fixed point is reached only when no $f_i$ refines the partition further: $\\forall f_i\\in \\sig\\colon \\sigref(\\pi^n, f_i)=\\pi^n$.\nThe extra clause $s \\equiv_{\\pi} t$ ensures that every application of $\\sigref$ refines the partition.\n\n\\begin{theorem}If all parts $f_i$ are monotone, Def.~\\ref{def:sigref2} yields the greatest fixed point.\\end{theorem}\n\\begin{proof}\nThe procedure terminates since the chain is decreasing ($\\pi^{n+1}\\refines\\pi^n$), due to the added clause $s \\equiv_{\\pi} t$.\nWe reach some fixed point $\\pi^n$, since $\\forall f_i\\in \\sig\\colon \\sigref(\\pi^n, f_i)=\\pi^n$ implies $\\sigref(\\pi^n, \\sigma)=\\pi^n$.\nFinally, to prove that we get the {\\em greatest} fixed point, \nassume there exists another fixed point $\\xi=\\sigref(\\xi,\\sigma)$. Then also $\\xi=\\sigref(\\xi,f_i)$ for all $i$.\nWe prove that $\\xi\\refines \\pi^n$ by induction on $n$. Initially, $\\xi\\refines {S}=\\pi^0$. Assume $\\xi\\refines \\pi^n$, then\nfor the selected $i$, $\\xi=\\sigref(\\xi,f_i)\\refines \\sigref(\\pi^n,f_i)=\\pi^{n+1}$, using monotonicity of $f_i$. \n\\end{proof}\n\nThere are several advantages to this approach due to its flexibility.\nFirst, for any $f_i$ that is independent of the partition, refinement with respect to that $f_i$ only needs to be applied once.\nFurthermore, refinements can be applied according to different strategies.\nFor instance, for the strong bisimulation of an mp-cut IMC, one could refine w.r.t.\\ $\\textbf{T}$ until there is no more refinement, \nthen w.r.t.\\ $\\textbf{R}^s$ until there is no more refinement, \nthen repeat until neither $\\textbf{T}$ nor $\\textbf{R}^s$ refines the partition.\n%\n%\nFinally, computing the full signature is the most memory-intensive operation in symbolic signature-based partition refinement.\nIf the partial signatures are smaller than the full signature, then larger models can be minimised.\n", "meta": {"hexsha": "c5b039abed9e5377eed9ddd90243ccf403be9fa7", "size": 21969, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/background.tex", "max_stars_repo_name": "alaarman/sigrefmc", "max_stars_repo_head_hexsha": "5afc0cc5d7f45260f71279289f2c1db67bfb04e1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/background.tex", "max_issues_repo_name": "alaarman/sigrefmc", "max_issues_repo_head_hexsha": "5afc0cc5d7f45260f71279289f2c1db67bfb04e1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-20T13:11:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-20T13:11:59.000Z", "max_forks_repo_path": "doc/background.tex", "max_forks_repo_name": "alaarman/sigrefmc", "max_forks_repo_head_hexsha": "5afc0cc5d7f45260f71279289f2c1db67bfb04e1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-16T08:45:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-16T08:45:51.000Z", "avg_line_length": 52.8100961538, "max_line_length": 332, "alphanum_fraction": 0.7210614957, "num_tokens": 6677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.30081975438451036}}
{"text": "\\documentclass[11pt]{article}\n\n% Packages\n\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{graphicx}\n\n% Style\n\n\\newcommand{\\Keywords}[1]{\\vspace{12pt}\\par\\noindent\n{\\small{\\bf Keywords\\/}: #1}}\n\\renewcommand{\\thesection}{\\Roman{section}} \n\\renewcommand{\\thesubsection}{\\thesection.\\Alph{subsection}}\n\\renewcommand{\\thesubsubsection}{\\thesubsection.\\arabic{subsubsection}}\n\\renewcommand{\\thetable}{\\Roman{table}}\n\n% Helpers\n\n\\newcommand{\\E}[1]{\\times10^{#1}}\n\\newcommand{\\A}[0]{\\mathbb{A}}\n\\newcommand{\\F}[0]{\\mathbb{F}}\n\\newcommand{\\M}[0]{\\mathbb{M}}\n\\newcommand{\\SRC}[0]{\\mathbb{S}}\n\\newcommand{\\braket}[2]{\\left<#1\\middle|#2\\right>}\n\\newcommand{\\brabiket}[3]{\\left<{#1\\left|#2\\right|#3}\\right>}\n\\newcommand{\\iso}[2]{$^{#2}\\mathrm{#1}$}\n\\newcommand{\\tild}[0]{\\sim\\!\\!}\n\n\\begin{document}\n\n\\title{Analysis of local void coefficients of reactivity in the reduced moderation BWR}\n\\author{Jeffrey E. Seifried \\and Ehud Greenspan\\footnote{Email: gehud@nuc.berkeley.edu}\\\\\n\\em University of California Berkeley\\\\\n\\em Department of Nuclear Engineering\\\\\n\\em 4155 Etcheverry Hall, MC 1730\\\\\n\\em Berkeley, CA 94720, USA\n}\n\\date{}\n\\maketitle\n\n\\begin{abstract}\n    An expression is derived for attributing the reactivity response due to perturbations to spectral, spatial, and isotopic effects.\n    It is shown to be consistent at a global level with similar expressions derived in previous work, but can provide more detailed information on the physics phenomena contributing to the reactivity response of the perturbation.\n    Using this expression, the reactivity effect of local coolant density perturbations -- local VCR -- are studied for two reduced-moderation BWR core designs: the RBWR-Th and RBWR-AC as well as for a standard ABWR.\n    The RBWR core designs feature large axial variation in their neutron spectra.\n\n    The axial distribution of local VCR along the RBWR-Th seed and along the ABWR core were found to have the same general shape: negative throughout but most negative near the bottom and asymptotically approaching zero towards the top.\n    However, the RBWR-Th VCR is roughly 4 times more negative.\n    The RBWR-AC local VCR axial distribution varies greatly -- it is very close to zero in the seed regions and has a significant positive component in the central blanket.\n\n    Three effects were identified as contributing to the VCR due to a local water density change in the lower part of the RBWR-Th seed -- local spectrum hardening that tends to increase the local reproduction factor ($\\eta_r$) of each of the fuel isotopes; a redistribution of the local neutron absorption between the fuel isotopes resulting in a shift of absorptions from higher to lower isotopic reproduction factors and, hence, to a reactivity loss; and an axial flux tilt across the core from axial zones of higher $\\eta_r$ to axial zones of lower $\\eta_r$ which makes another negative contribution to the reactivity worth of the perturbation.\n\n    \\Keywords{coefficients of reactivity, attribution, feedback}\n\\end{abstract}\n\n\\pagebreak\n\n\\section{Introduction}\n\\label{sec:intro}\n\nCoefficients of reactivity are typically quantified for global perturbations such as a uniform $50K$ increase of fuel temperature or a $10\\%$ decrease in coolant flow-rate within a flow channel.\nSuch perturbations can be thought of as the simultaneous occurrence of a set of local perturbations which, for small enough perturbations, are independent of one another.\n\nIn certain core types, such as the Reduced moderation Boiling Water Reactor (RBWR) \\cite{ganda2012sst,takeda2007blt} core, local perturbations invoke either negative or positive reactivity responses depending on the axial location.\nEven when the global reactivity coefficient is slightly negative, there exists the possibility for instability in such cores.\nThe objective of this work is to attribute the cause of a local reactivity response to their underlying physical mechanisms.\nUnderstanding of these mechanisms provides useful insight which can guide an effective search for optimal core designs.\nThis work provides tools to conduct such an analysis and demonstrates their utility with three core designs.\n\nIn Section \\ref{sec:derive}, an expression is derived for attributing reactivity responses -- either global or local -- to the spatial, spectral, and isotopic dependence of neutron fission and capture reactions.\nSection \\ref{sec:equiv} demonstrates that, on a global basis, this expression is equivalent to those derived in previous work, but on a local (e.g., spatial, spectral, or, isotopic) basis, it is more informative.\nSection \\ref{sec:rbwrth} uses this new derivation and other tools to study local coolant void perturbations in the thorium-fueled RBWR (RBWR-Th) \\cite{ganda2012sst} unit cell, which is described in Section \\ref{sec:model}.\nSection \\ref{sec:other} performs similar analyses for the uranium-fueled RBWR (RBWR-AC) \\cite{takeda2007blt} and conventional Advanced Boiling Water Reactor (ABWR) unit cells \\cite{fennern2007asr}.\nFinally, the accuracy of estimating the reactivity response to global perturbations from the reactivity response to local perturbations is addressed in Section \\ref{sec:accuracy}.\n\n\\section{An Expression for Attributing Reactivity to System Components}\n\\label{sec:derive}\n\nFor infinite systems, the multiplication factor (k) is defined as:\n\\begin{equation}\n    k\\equiv \\frac{\\F}{\\A}\n\\end{equation}\nwhere $\\F$ and $\\A$ -- the fission neutron birth rate and neutron absorption rate, respectively -- are defined as:\n\\begin{equation}\n    \\begin{split}\n    \\F \\equiv \\int_V d\\vec{r} \\int_0^\\infty dE \\int_{4\\pi} d\\vec\\Omega \\; \\nu(\\vec r, E) \\Sigma_f(\\vec r, E) \\psi(\\vec r, E, \\vec\\Omega) \\\\\n    \\A \\equiv \\int_V d\\vec{r} \\int_0^\\infty dE \\int_{4\\pi} d\\vec\\Omega \\; \\Sigma_a(\\vec r, E) \\psi(\\vec r, E, \\vec\\Omega)\n    \\end{split}\n\\end{equation}\nwhere $\\nu$, $\\Sigma_f$, $\\Sigma_a$, and $\\psi$ are the number of neutrons born per fission, macroscopic fission and absorption cross sections, and neutron flux and $\\vec r$, $E$, and $\\vec\\Omega$ are the spatial, spectral, and directional neutron phase-space coordinates.\nReactivity ($\\rho$) is defined as:\n\\begin{equation}\n    \\rho \\equiv \\frac{k-1}{k} = 1-\\frac{\\A}{\\F}.\n\\end{equation}\n\nA coefficient of reactivity ($\\alpha$) measures the linear effect of a perturbation of a parameter ($p$) upon $\\rho$.\nIt can be estimated directly with finite difference using nominal and perturbed multiplication factors:\n\\begin{equation}\n    \\alpha \\equiv \\frac{\\partial\\rho}{\\partial p}\n    \\approx \\frac{\\Delta \\rho}{\\Delta p}\n    = \\frac{1}{\\Delta p} \\frac{\\Delta k}{k k^\\prime}\n    \\label{eqn:kdiff}\n\\end{equation}\nwhere $x^\\prime$ denotes a perturbed quantity $x$ and $\\Delta x = x^\\prime - x$.\nThis will be referred to as the k-difference approach.\nAlternatively, $\\alpha$ can be expanded in $\\F$ and $\\A$ with the product rule:\n\\begin{equation}\n    \\alpha = \\frac{\\partial\\rho}{\\partial\\F} \\frac{\\partial\\F}{\\partial p} + \\frac{\\partial\\rho}{\\partial\\A} \\frac{\\partial\\A}{\\partial p}.\n\\end{equation}\nIn this second approach, while derivatives of $\\rho$ can be evaluated analytically:\n\\begin{equation}\n    \\frac{\\partial\\rho}{\\partial\\F} = +\\frac{1}{k\\F} \\quad \\mathrm{and} \\quad \\frac{\\partial\\rho}{\\partial\\A} = -\\frac{1}{k\\A}\n    \\label{eqn:rhoAnal}\n\\end{equation}\nit is formally possible to quantify the derivatives of $\\F$ and $\\A$ using perturbation theory \\cite{greenspan1976dpt}:\n\\begin{equation}\n    \\begin{split}\n    \\frac{\\partial\\F}{\\partial p} = \\braket{\\frac{\\partial(\\nu\\Sigma_f)}{\\partial p}}{\\psi} - \\brabiket{\\psi^\\dagger}{\\frac{\\partial\\M}{\\partial p}}{\\psi} \\\\\n    \\M\\psi = \\SRC \\quad \\mathrm{and} \\quad \\M^\\dagger \\psi^\\dagger = \\SRC^\\dagger = \\frac{\\partial\\F}{\\partial\\psi}\n    \\end{split}\n    \\label{eqn:pertF}\n\\end{equation}\nand:\n\\begin{equation}\n    \\begin{split}\n    \\frac{\\partial\\A}{\\partial p} = \\braket{\\frac{\\partial(\\Sigma_a)}{\\partial p}}{\\psi} - \\brabiket{\\psi^\\dagger}{\\frac{\\partial\\M}{\\partial p}}{\\psi} \\\\\n    \\M\\psi = \\SRC \\quad \\mathrm{and} \\quad \\M^\\dagger \\psi^\\dagger = \\SRC^\\dagger = \\frac{\\partial\\A}{\\partial\\psi}\n    \\end{split}\n    \\label{eqn:pertA}\n\\end{equation}\nwhere $\\psi^\\dagger$, $\\M$, and $\\SRC$ are the adjoint flux, neutron transport operator, and neutron source term and the bra-ket notation is used for inner products.\nFor critical systems, the neutron source term is the fission source term divided by k.\nThe adjoint transport equations in Equations \\ref{eqn:pertF} and \\ref{eqn:pertA} must be solved using Generalized Perturbation Theory, for which shortcut estimators for the adjoint distribution like the Iterated Fission Probability \\cite[864-869]{henry1964nk} offer no assistance.\nSolution of these equations requires the two adjoint sources to first be estimated using ordinary transport and then multiple fixed-source adjoint transport calculations.\nThe task is difficult and computationally expensive to perform accurately and convenient tools do not currently exist.\nConsequently a direct perturbation approach, not based upon adjoint theory, is chosen for the present analysis.\n\nFor such a direct approach, second-order accuracy can be achieved by evaluating the derivatives of $\\rho$ in Equation \\ref{eqn:rhoAnal} at the nominal and perturbed states and taking the average (i.e., the trapezoidal rule) and derivatives in $\\F$ and $\\A$ can be estimated using finite difference:\n\\begin{equation}\n    \\alpha \\approx \\frac{1}{2} \\left(\\frac{1}{k^\\prime \\F^\\prime} + \\frac{1}{k\\F}\\right)\\frac{\\Delta \\F}{\\Delta p} - \\frac{1}{2} \\left(\\frac{1}{k^\\prime \\A^\\prime} + \\frac{1}{k\\A}\\right)\\frac{\\Delta \\A}{\\Delta p}\n\\end{equation}\n$\\Delta\\F$ and $\\Delta\\A$ are the total scalar differences in neutron birth and absorption rates; they are distributed over a multi-dimensional phase-space of geometric space, neutron energy, neutron direction, isotope, and reaction type.\nThey can be calculated from continuous integrals or summations over discrete regions ($\\xi$) of that phase-space.\nBecause the difference of a sum of elements can be written as the sum of differences of those elements, $\\Delta\\F$ and $\\Delta\\A$ can be expressed in a more illustrative form:\n\\begin{equation}\n    \\Delta \\F = \\sum_\\xi w_\\xi \\left(\\F_\\xi^\\prime - \\F_\\xi \\right) \\quad \\mathrm{and} \\quad \\Delta \\A = \\sum_\\xi w_\\xi \\left(\\A_\\xi^\\prime - \\A_\\xi\\right)\n\\end{equation}\nwhere $w_\\xi$ is the width of a discrete region of $\\xi$.\nWritten this way, distributions of $\\alpha$ over $\\xi$ can be found.\nEach region in phase-space can be said to have its own contribution ($\\alpha_\\xi$) to the overall coefficient of reactivity:\n\\begin{equation}\n    \\alpha = \\sum_\\xi w_\\xi \\alpha_\\xi\n\\end{equation}\nwhere:\n\\begin{equation}\n    \\alpha_\\xi \\approx \\frac{1}{2 \\Delta p} \\left[\\left(\\frac{1}{k^\\prime \\F^\\prime} + \\frac{1}{k\\F}\\right)\\Delta \\F_\\xi - \\left(\\frac{1}{k^\\prime \\A^\\prime} + \\frac{1}{k\\A}\\right)\\Delta \\A_\\xi \\right].\n    \\label{eqn:alpha2}\n\\end{equation}\nParticular insight can be gained by examining the $\\Delta \\F_\\xi$ and $\\Delta \\A_\\xi$ terms of Equation \\ref{eqn:alpha2} in isolation, in addition to the net of the two terms.\n\nIn later sections, $\\alpha_\\xi$ will be summed over all but a single dimension, providing its distribution over spatial ($\\alpha_r$), spectral ($\\alpha_E$), nuclear reaction ($\\alpha_x$), and isotopic ($\\alpha_i$) bins.\nFor example, the spatial distribution of $\\alpha$ can be calculated as:\n\\begin{equation}\n    \\alpha_r = \\sum_{E,x,i} \\alpha_\\xi  = \\sum_{E,x,i} \\alpha_{r,E,x,i}\n\\end{equation}\nThis $r/E/x/i$ subscript notation will also be used for other quantities which are distributed over $\\xi$.\n\n\\section{Equivalency with Absorption and Fission Normalization Derivations}\n\\label{sec:equiv}\n\nIn past work, expressions for attributing coefficients of reactivity have been derived using so called absorption and fission normalizations \\cite{ganda2010sst}.\nThis section shows that these two previous derivations for coefficients of reactivity ($\\alpha_\\A$ and $\\alpha_\\F$ respectively) are equivalent to the first-order portion of Equation \\ref{eqn:alpha2} ($\\alpha_1$) when each expression is summed over $\\xi$.\nBefore this comparison can be made, Equation \\ref{eqn:alpha2} is rearranged into a first-order term:\n\\begin{equation}\n    \\alpha_{\\xi,1} = \\frac{1}{\\Delta p} \\left[\\frac{\\Delta\\F_\\xi}{k^\\prime\\F} - \\frac{\\Delta\\A_\\xi}{k\\A}\\right]\n    \\label{eqn:alpha1}\n\\end{equation}\nand a second-order term:\n\\begin{equation}\n    \\alpha_{\\xi,2} = \\frac{1}{2\\Delta p} \\left[\\left(\\frac{\\Delta k}{k} - \\frac{\\Delta\\F}{\\F^\\prime}\\right)\\frac{\\Delta\\F_\\xi}{k^\\prime \\F} + \\left(\\frac{\\Delta\\F}{\\F^\\prime}\\right)\\frac{\\Delta\\A_\\xi}{k\\A}\\right].\n\\end{equation}\nThe $\\alpha_{\\xi,2}$ expression is said to be second-order because its terms contain products of differences terms.\n\nIn order to derive $\\alpha_\\A$, perturbed and nominal neutron birth rate distributions are first normalized by the rate of neutrons absorbed in the system and then subtracted:\n\\begin{equation}\n    \\Delta k_{\\xi,\\A} \\equiv \\frac{\\F_\\xi^\\prime}{\\A^\\prime} - \\frac{\\F_\\xi}{\\A} = k^\\prime \\frac{\\F_\\xi^\\prime}{\\F^\\prime} - k \\frac{\\F_\\xi}{\\F}.\n\\end{equation}\nNext, equal terms ($k \\frac{\\F_\\xi^\\prime}{\\F} = k^\\prime \\frac{\\F_\\xi^\\prime}{\\F^\\prime} \\frac{\\A^\\prime}{\\A}$) are added and subtracted:\n\\begin{equation}\n    \\begin{split}\n        \\Delta k_{\\xi,\\A}=\\left(k \\frac{\\F_\\xi^\\prime}{\\F} - k \\frac{\\F_\\xi}{\\F}\\right) + \\left(k^\\prime \\frac{\\F_\\xi^\\prime}{\\F^\\prime}\\frac{\\A}{\\A} - k^\\prime \\frac{\\F_\\xi^\\prime}{\\F^\\prime}\\frac{\\A^\\prime}{\\A}\\right) \\\\\n        = k \\frac{\\Delta\\F_\\xi}{\\F} - k^\\prime \\frac{\\F_\\xi^\\prime}{\\F^\\prime}\\frac{\\Delta\\A}{\\A}.\n    \\end{split}\n\\end{equation}\nFinally, upon invoking Equation \\ref{eqn:kdiff}, the absorption-normalized expression for attribution is found:\n\\begin{equation}\n    \\alpha_{\\xi,\\A} = \\frac{1}{\\Delta p} \\left[\\frac{\\Delta\\F_\\xi}{k^\\prime \\F} - \\frac{\\F_\\xi^\\prime}{\\F^\\prime} \\frac{\\Delta\\A}{k\\A}\\right].\n    \\label{eqn:alphaA}\n\\end{equation}\n\nIn order to derive $\\alpha_\\F$, perturbed and nominal neutron absorption rate distributions are first normalized by the rate of neutrons born in the system and then subtracted:\n\\begin{equation}\n    \\Delta \\rho_{\\xi,\\F} \\equiv -\\frac{\\A_\\xi^\\prime}{\\F^\\prime} + \\frac{\\A_\\xi}{\\F} = -\\frac{1}{k^\\prime}\\frac{\\A_\\xi^\\prime}{\\A^\\prime} + \\frac{1}{k}\\frac{\\A_\\xi}{\\A}.\n\\end{equation}\nNext, equal terms ($\\frac{1}{k} \\frac{\\A_\\xi^\\prime}{\\A} = \\frac{1}{k^\\prime}\\frac{\\A_\\xi^\\prime}{\\A^\\prime}\\frac{\\F^\\prime}{\\F}$) are added and subtracted:\n\\begin{equation}\n    \\begin{split}\n        \\Delta \\rho_{\\xi,\\F} = \\left(\\frac{1}{k^\\prime}\\frac{\\A_\\xi^\\prime}{\\A^\\prime}\\frac{\\F^\\prime}{\\F} - \\frac{1}{k^\\prime}\\frac{\\A_\\xi^\\prime}{\\A^\\prime}\\frac{\\F}{\\F}\\right) - \\left(\\frac{1}{k}\\frac{\\A_\\xi^\\prime}{\\A} - \\frac{1}{k}\\frac{\\A_\\xi}{\\A}\\right) \\\\\n        = \\frac{1}{k^\\prime}\\frac{\\A_\\xi^\\prime}{\\A^\\prime}\\frac{\\Delta\\F}{\\F} - \\frac{1}{k}\\frac{\\Delta\\A_\\xi}{\\A}.\n    \\end{split}\n\\end{equation}\nFinally, upon invoking Equation \\ref{eqn:kdiff}, the fission-normalized expression for attribution is found:\n\\begin{equation}\n    \\alpha_{\\xi,\\F} = \\frac{1}{\\Delta p}\\left[\\frac{\\A_\\xi^\\prime}{\\A^\\prime}\\frac{\\Delta\\F}{k^\\prime \\F} - \\frac{\\Delta\\A_\\xi}{k\\A}\\right].\n    \\label{eqn:alphaF}\n\\end{equation}\n\nWhile there are differences between the expressions for $\\alpha_{\\xi,\\A}$, $\\alpha_{\\xi,\\F}$, and $\\alpha_{\\xi,1}$ (Equations \\ref{eqn:alpha1}, \\ref{eqn:alphaA}, and \\ref{eqn:alphaF}, respectively), when each is summed over $\\xi$, the resulting expressions for $\\alpha_\\A$, $\\alpha_\\F$, and $\\alpha_1$ are identical to each other and equal to the result given by k-difference approach (Equation \\ref{eqn:kdiff}).\nAlthough the three approaches are globally equivalent, $\\alpha_{\\xi,\\A}$ cannot resolve contributions from $\\Delta\\A$ across $\\xi$ because it only accounts for the total absorption rate and not its distribution.\nLikewise, $\\alpha_{\\xi,\\F}$ cannot resolve contributions from $\\Delta\\F$ across $\\xi$ because it accounts for the total fission rate and not its distribution.\n$\\alpha_{\\xi,1}$ and $\\alpha_{\\xi,2}$, on the other hand, account for the local contribution of both absorption and fission changes so that correct sign and magnitude can be attributed to each component.\n\n\\section{Description of the RBWR-Th Unit Cell}\n\\label{sec:model}\n\nThe RBWR-Th \\cite{ganda2012sst} is a thorium fueled self-sustaining RBWR -- a design variant of the depleted uranium fueled self-sustaining RBWR-AC designed by HITACHI to fit within the ABWR pressure vessel \\cite{takeda2007blt}.\nThe RBWR-Th departs from the RBWR-AC in several ways: thorium is used as the fertile fuel instead of depleted uranium, the internal axial blanket is eliminated elongating the fissile region, and absorbers in the upper and lower reflectors are removed.\n\nAs the present study focuses on the axial variation of the void coefficient of reactivity, the RBWR-Th core is modeled with a single pin unit cell consisting of a $1.005cm$ OD fuel pin segmented into a $50cm$ long lower blanket, a $111cm$ long central seed, and a $70cm$ long upper blanket and arranged in a hexagonal lattice of pitch $1.135cm$.\nThe mixed oxide fuel is assumed to be at $90\\%$ of its nominal density ($0.061[a/b-cm]$) and is clad with $0.06cm$ thick metallic zirconium ($0.043[a/b-cm]$).\nFuel and clad are assumed to be at $900K$.\nLower and upper reflectors are modeled as pure water of a density corresponding to, respectively, the coolant inlet to and exit from the core.\nSide and top views of the unit cell are shown in Fig. \\ref{fig:xport}.\n\nBefore each cycle, blankets are charged with natural thoria and the seed is charged with the processed transthoria discharge harvested from the seed and blankets of the previous cycle.\nDuring this fuel processing, all actinides are recycled and fission products are discarded.\nAll analysis is performed at fuel cycle equilibrium, when the charge of each successive cycle is the same.\nTable \\ref{tab:iso} shows the isotopic composition of the seed fuel region which is used.\nMCNP6.1 is used for all neutron transport calculations \\cite{lanl2013mcnp6}.\n\nBecause accurate determination of the RBWR-Th core performance requires tight coupling between neutronics and thermal/hydraulics, a one-dimensional heat balance and drift-flux model is coupled with neutron transport calculations to ensure that the axial distributions of two-phase coolant density and fission power are self-consistent across $57$ axial regions \\cite{seifried2013aec}.\nEach fuel pin provides $20kW$ of thermal power to boil the light water coolant -- which enters the core at $7.25MPa$ and $278.5 ^\\circ C$ -- to an exit quality of $35\\%$ corresponding to a void fraction of $\\tild 80\\%$.\nFor this model, a modified version of the Liao, Parlos, Griffith void fraction correlation is used \\cite{shirvan2013bev}.\n\nFig. \\ref{fig:rho} and Fig. \\ref{fig:lhr} show the axial distribution of the water density and linear heat rate.\nThe region below $50cm$ is the lower blanket, above $161cm$ is the upper blanket, and in between is the seed.\nThe large differences in water density cause the neutron spectra to vary greatly along the core.\nFig. \\ref{fig:flx} shows a typical flux spectrum for the RBWR-Th and compares it with that of the RBWR-AC, the ABWR, and a typical Sodium Fast Reactor (SFR).\nThe RBWR cores have intermediate flux spectra which are not as soft as the ABWR and not as hard as the SFR.\n\n\\section{Local Void Coefficients of Reactivity in the RBWR-Th}\n\\label{sec:rbwrth}\n\nThe local void coefficient of reactivity, or local VCR, is the linear reactivity response to a localized perturbation in the coolant density.\nSuch perturbations are estimated with a $10\\%$ reduction in coolant density for a single axial region.\nThe coolant and fuel are segmented into $10$, $30$, and $15$ axial regions for the lower blanket, seed, and upper blanket regions, respectively.\nVCRs are reported in pcm per $1\\%$ increase in coolant void (or $1\\%$ decrease in coolant density).\n\nFirst, local VCRs are calculated using KPERT, a new tool in MCNP6.1 which is designed for efficient estimation of the reactivity response to perturbations \\cite{kiedrowski2011awt}.\nAlthough its accuracy can be limited for drastic perturbations, KPERT is very effective for quickly indicating trends and guiding attention to important spatial locations or isotopes.\nIn the same runtime required for a k-difference approach to calculate the reactivity effect of one perturbation, KPERT can simulate more than $50$.\nMCNP also has an older perturbation tool PERT which does not perform as well as KPERT.\nFig. \\ref{fig:verify} compares the k-difference estimates of the KPERT and PERT to direct k-difference calculations.\nWhile KPERT results lie just outside of the error bars, PERT predictions differ by $\\tild 1/3$ or more.\nThis is likely due to the large flux redistribution which occurs during the perturbation at position $b$, which KPERT can account for, but PERT cannot.\nThese conclusions were also found in other calculations.\n\nMore accurate and thorough direct analysis is then performed for coolant density perturbations at selected locations found of interest using the expressions for reactivity attribution derived in Sections \\ref{sec:derive} and \\ref{sec:equiv}.\nAdditional insight is gained by examining local reproduction factors (i.e., $\\eta_r \\equiv \\frac{\\F_r}{\\A_r}$) and utilization factors (i.e., $f_r \\equiv \\frac{\\A_r}{\\A}$).\nWith this set of analyses, the cause for negative and positive local VCRs can be attributed to underlying physics in the RBWR-Th core.\n\nFig. \\ref{fig:kpert} displays the local VCRs for the RBWR-Th core at Beginning Of Equilibrium Cycle calculated with KPERT.\nIt can be seen that local VCRs vary strongly along the core; they are negative along the seed region -- particularly so in its lower, softer spectrum part, while slightly positive in the blankets -- particularly adjacent to the seed.\nTwo local perturbations were selected for deeper analysis aimed at understanding the underlying physics: (a) the most positive local VCR within the lower blanket adjacent to the seed and ($b$) the most negative local VCR within the seed towards the inlet.\nPerturbation $b$ is discussed first.\n\n\\subsection{The Most Negative Local VCR Within the RBWR-Th}\n\\subsubsection{Comparison of Different Formulations for VCR for Spatial Components}\n\nUsing expressions for $\\alpha_\\A$ and $\\alpha_\\F$ (Equations \\ref{eqn:alphaA} and 21), the contribution of different axial zones to perturbation $b$'s VCR -- the VCR due to coolant density change in location $b$, were quantified and displayed in, respectively, Fig. \\ref{fig:alphaAR} and Fig. \\ref{fig:alphaFR}.\nIt is found that both $\\F$ and $\\A$ are depressed in the vicinity of the perturbation and $\\F$ and $\\A$ both shift away from the perturbation towards the outlet.\nThe first response will be shown due to localized spectral hardening resulting in a reduced fission probability and the second due to flux tilt caused by normalization by $\\A$ and $\\F$ rates.\n\nFig. \\ref{fig:alpha1R} and Fig. \\ref{fig:alpha2R} display the first- and second-order predictions for axial contributions to the overall local VCR from perturbation $b$, obtained using, respectively, Equations \\ref{eqn:alpha1} and \\ref{eqn:alpha2}.\nAs in case of $\\alpha_\\A$ and $\\alpha_\\F$, there are local spectral hardening effects and global flux tilt effects.\nSpectral hardening has a net negative reactivity effect due to a localized reduction in the reproduction factor.\nThis is illustrated in Fig. \\ref{fig:deltaEtaR} which plots the change in the location-dependent $\\eta_r$ due to perturbation $b$.\nThe flux tilt also results in a net negative effect due to a spatial shift in the local utilization factor shown in Fig. \\ref{fig:deltaEffR} as shown in Fig. \\ref{fig:etaR} $\\eta_r$ is highest near the core inlet where the flux spectrum is softest and decreases with elevation as the spectrum hardens with reduction in the coolant density.\nAs a result, $\\sum_r{\\eta_r\\Delta f_r}$ is negative.\nAlthough the two responses cannot be isolated, it is estimated that $60\\%$ of the total reactivity effect is from spectrum hardening ($\\sum_r{\\Delta\\eta_r f_r}$) and $40\\%$ is from the flux tilt ($\\sum_r{\\eta_r \\Delta f_r}$).\n\nThe k-difference approach estimates the overall local VCR for perturbation $b$ to be $-6.8 \\pm 0.5 [pcm/\\%-void]$.\nIn Table \\ref{tab:deltaAlpha} the deviations between this estimate those of $\\alpha_\\A$, $\\alpha_\\F$, $\\alpha_1$, and $\\alpha_2$ are tabulated.\nThe associated p-values (i.e., the probability of observing the deviation given that there is no true deviation) demonstrate that these deviations are completely insignificant (i.e., $p>>5\\%$), so all five approaches predict the same overall local VCR.\nThis conclusion was expected from inspection of the algebraic expressions.\n\nThe expressions do differ, however, in predicting the components (spatial, spectral, isotopic) of the reactivity.\nFor example, the contribution of the flux tilt in the upper region of the seed is positive as estimated with $\\alpha_\\A$ (Fig. \\ref{fig:alphaAR}), but negative as estimated with $\\alpha_\\F$ (Fig. \\ref{fig:alphaFR}).\n$\\alpha_1$ and $\\alpha_2$, however, show that the region has an increase in both absorption and fission, but contributes practically no net reactivity worth.\nThis comparison brings to light a shortcoming of the $\\alpha_\\A$ and $\\alpha_\\F$ expressions, for examining components of the reactivity.\n\nAlthough $\\alpha_2$ is believed to be more accurate in estimating components of reactivity than $\\alpha_1$ by virtue of its second-order terms, there currently is no benchmark to compare against.\nNonetheless, a comparison is made between the two expressions to quantify the magnitude of the second-order terms; the result is shown in Fig. \\ref{fig:deltaAlphaR}.\nRelative to $\\alpha_1$,  $\\alpha_2$ is estimating: 1) less positive and less negative contributions from changes in fission and absorption, respectively; 2) an enhanced, more negative contribution from the seed region; and 3) a reduced, less negative contribution from the blankets.\nAll following $\\alpha_\\xi$ values and distributions will be derived from the $\\alpha_2$ expression.\n\n\\subsubsection{Isotopic Contributions}\n\nThe spectral hardening effect is further explored by examining $\\alpha_\\xi$ in the proximity of perturbation $b$ (the five axial regions bordering it), but binned over isotope ($i$) instead of axial region.\nFig. \\ref{fig:alpha2I} displays these results for the isotopes which provide the largest reactivity worth.\nIt can be seen that fissile isotopes -- predominately \\iso{U}{233}, \\iso{U}{235} and \\iso{Pu}{239} -- contribute a net negative reactivity, while non-fissile isotopes -- predominately \\iso{Th}{232}, \\iso{U}{234}, and \\iso{U}{236} -- contribute a net positive reactivity.\nBoth classes of isotopes exhibit reductions in $\\F$ and $\\A$, but the reduction in $\\F$ of \\iso{U}{233} is the dominant.\nCoolant and clad materials do not play a significant role in the reactivity response to perturbation $b$, contributing less than $5\\%$ of the total worth.\n\nFig. \\ref{fig:deltaEtaI} shows that spectral hardening increases isotopic $\\eta_i$ values near perturbation $b$.\nIn order to understand the change in $\\eta_i$ of the mixture of fuel isotopes, the perturbation effect on isotopic $f_i$ must also be considered.\nFig. \\ref{fig:etaI} plots the $\\eta_i$ value for each isotope and Fig. \\ref{fig:deltaEffI} shows the changes in isotopic $f_i$ values which result from perturbation $b$, plotted over the same abscissa.\nEven though the perturbation increases the $\\eta_i$ values for every isotope, the net reactivity effect ($\\sum_i{\\Delta\\eta_i f_i} + \\sum_i{\\eta_i \\Delta f_i}$) is reduced by $185 \\pm 31 [pcm]$.\nThis is because the perturbation shifts absorptions from higher $\\eta_i$ (such as \\iso{U}{233}) to lower $\\eta_i$ such as \\iso{U}{234}).\nIf the effect of \\iso{U}{233} is excluded, the trend reverses and the change in the overall $\\eta_i$ becomes slightly positive. \n\nThe underlying mechanisms which cause negative reactivity due to spectral hardening and flux tilt are identical: $f_i$ values shift from a phase-space of higher to lower $\\eta_i$ values.\nFor the flux tilt response, that phase-space is axial position; for the spectral hardening response, the phase-space is isotopes in proximity to the perturbation.\nFurther insight can be obtained by studying the spectral characteristics of this latter response.\n\n\\subsubsection{Spectral Components}\n\nFig. \\ref{fig:deltaFlx} shows the spectral hardening due to perturbation $b$, considering only those five axial regions which border perturbation $b$.\nThe flux shifts to the energy range between $10 keV$ and $1 MeV$ from, epithermal energies -- due to a reduced moderating power, and from above $1 MeV$ due to a reduced local fission rate and due to enhanced inelastic scattering probability by the fuel.\nFig. \\ref{fig:alphaETh} and Fig. \\ref{fig:alphaEU} show the impact these spectral changes have upon $\\eta_E$ values for \\iso{Th}{232} and \\iso{U}{233} in proximity of perturbation $b$, as a function of the neutron energy. \\iso{Th}{232} contributes a large increase in reactivity due to, primarily, a reduction in resonance absorption.\nThe slight reduction in the \\iso{Th}{232} fast fission probability has only a very small negative effect on the reactivity coefficient.\nThe overall decrease in the neutron absorption probability due to local voiding is responsible for the net positive contribution to the reactivity worth of the other non-fissile isotopes as well.\n\nFig. \\ref{fig:alphaEU} shows the energy-dependent contributions of \\iso{U}{233} to the reactivity coefficient via the spectral effects on the absorption and fission probabilities.\nIt is observed that the spectrum hardening results in a significant increase in both the neutron absorption and neutron fission probabilities in, primarily, the epithermal energy range but the latter effect is dominant so the net reactivity worth is negative.\nThis trend also applies to each of the other fissile isotopes.\n\nFrom the perspective of $f_E$ and $\\eta_E$ values -- Fig. \\ref{fig:deltaFlx} shows that the perturbation shifts spectral $f_E$ from, primarily, epithermal but also thermal and MeV energies to sub-MeV energies.\nFrom examination of the energy dependence of the absorption cross section of the two most absorbing fuel isotopes in the RBWR-Th core displayed in Fig. \\ref{fig:xs} it is expected that this redistribution shifts the local absorptions from primarily \\iso{U}{233} to primarily \\iso{Th}{232} which has a significantly lower $\\eta_E$ value, thus reducing the local reactivity effect.\n\nIn summary, perturbation $b$ causes a spatial redistribution of power, which shifts flux away from axial regions with higher $\\eta_r$ values and towards those with lower $\\eta_r$ values.\nAdditionally, the perturbation causes localized spectral hardening which shifts absorption from isotopes with higher $\\eta_i$ values to those with lower $\\eta_i$ values, reducing the axial $\\eta_r$ value in the vicinity of the perturbation.\nWhile this spectral hardening also tends to increase localized $\\eta_r$ values somewhat, the absorption redistribution is a larger effect.\nBoth the flux tilt and spectral hardening responses bring a negative reactivity worth, for an overall strong negative local VCR.\n\n\\subsection{The Most Positive Local VCR Within the RBWR-Th}\n\nPerturbation $a$ is a reduction in the coolant density in axial zone a of the lower blanket that is close to the seed.\nThis voiding causes both a streaming response -- which has a very small reactivity effect -- and a flux tilt response -- which has a net positive reactivity worth.\nThe two responses can be resolved in Fig. \\ref{fig:deltaEffRb}, which shows the change in axial $f_r$ due to perturbation $a$.\n\nThe streaming response is characterized by a reduced albedo of the lower blanket to neutrons that are generated in the seed and happen to leak into the lower blanket; the voided coolant increases the number of seed-born neutrons that stream beyond perturbation $a$, causing $f_r$ to shift downwards.\nAs can be seen in Fig. \\ref{fig:etaR} the $\\eta_r$ within this region of the blanket is negligibly small compared to the rest of the system (it is a fertile blanket, after all), so the spatial shift in $f_r$ brings no significant reactivity change.\n\nThe flux tilt response is similar to that from perturbation $b$, except that the seed power shifts downwards instead of upwards (Fig. \\ref{fig:deltaEffR}).\nThe downwards flux tilt shifts local $f_r$ values from axial regions of lower to higher $\\eta_r$ values (Fig. \\ref{fig:etaR}).\nThe result is an increase in the effective $\\eta$ (i.e., $\\frac{\\sum_r{\\eta_r f_r}}{\\sum_r{f_r}}$) for the system and, hence, a reactivity gain.\nThe localized spectral hardening response which was seen in the RBWR-Th system can't quite be resolved within the statistical uncertainty.\nHowever, it is estimated that its contribution is negative and one-fifth the magnitude of the power-tilt response.\n\n\\section{Local Void Coefficients of Reactivity in the ABWR and RBWR-AC}\n\\label{sec:other}\n\nThe RBWR-Th inherits many of its core design features from the ABWR \\cite{fennern2007asr} and RBWR-AC \\cite{takeda2007blt}.\nFollowing is a comparative local VCR analysis of the three systems; it can provide useful information on the uniqueness of the RBWR-Th core design.\n\nFig. \\ref{fig:kpertAbwr} shows the axial distribution of ABWR local VCRs, as estimated with KPERT.\nComparing with Fig. \\ref{fig:kpert} it is seen that the ABWR and RBWR-Th local VCRs have the same general shape: (1) both are negative throughout the active length of the seed fuel; (2) local VCRs are most negative in the lower quadrant of the active length; and (3) local VCRs asymptotically approach zero towards the outlet.\nHowever, the RBWR-Th VCR gets to be $\\tild 4$ times more negative and this may be of practical concern as it may cause instabilities and make it difficult to achieve adequate cold shutdown margin.\nA recent study found \\cite{gorman2014tfr} that by replacing $1/4$ to $1/3$ of the thorium of the makeup fuel by depleted uranium it is possible to make the VCR comparable in magnitude to that of the ABWR.\n\nFig. \\ref{fig:kpertAc} plots the local VCR traverse for the RBWR-AC \\cite{takeda2007blt}, as estimated with KPERT.\nThis VCR distribution differs greatly from that of the RBWR-Th (Fig. \\ref{fig:kpert}) except for one feature: a sharp local minimum close to the bottom of each seed region.\nBut in the RBWR-AC the VCR does not have significant negative components; in fact, its average is close to a value of zero.\nThe RBWR-AC has large positive VCR values within the internal and upper blankets adjacent to the seeds but negative values at the bottom blanket.\nThe large VCR values in the RBWR-AC blankets are due to the use of depleted uranium fuel; \\iso{U}{238} has a larger fast fission cross section than \\iso{Th}{232} and its threshold energy is lower.\nThe most positive local perturbation $b$ at the bottom of the inner blanket is chosen for limited attribution analysis.\n\nFig. \\ref{fig:alphaAc} shows the contribution to local VCR from all axial fuel regions.\nThe axial variations are significantly more complicated than those in the RBWR-Th -- (Fig. \\ref{fig:alpha2R}).\nFig. \\ref{fig:spectralAc} shows the axial spectral hardening response; it has noticeable components from the RBWR-AC lower seed and internal blanket axial zones in the proximity of the perturbed zone.\nFig. \\ref{fig:tiltAc} shows that the axial extent of the flux tilt response is much wider -- from the bottom blanket to the upper seed.\nReduction in the coolant absorption probability contributes around one fifth of the reactivity effect.\n\nDue to the complicated reactivity responses, it is difficult to isolate the spectral hardening and flux tilt responses from one another.\nHowever, by summing over values in the two figures, it is estimated that localized spectral hardening is responsible for one-fifth of the local VCR and flux tilting contributes the other fourth-fifths.\n\nA more thorough analysis of the local VCRs in the RBWR-AC core using the analysis methodology developed in this study, along with prolonged runtimes to reduce counting uncertainty, could help identifying RBWR-AC core designs that feature negative void coefficient of reactivity.\n\n\\section{Accuracy of the Linear Combination of Local Perturbations}\n\\label{sec:accuracy}\n\nA primary assertion made in this work is that there is value in studying the reactivity response from local perturbations because their combined effect is a reasonable estimate of the global reactivity effect of the perturbations.\nIf this assertion is correct it is possible to construct a large number of global perturbations by linearly combining the effects of different combinations of local perturbations.\nThis section provides a simple sanity check by comparing the direct reactivity effect from a coolant flow-rate reduction with that estimated from linearly combining local void perturbations.\n\nThe direct estimate begins by iterating between neutron transport and thermal/hydraulic solutions until a tight convergence is obtained between the axial water density and axial power shape \\cite{seifried2013aec}.\nThis is performed at the nominal flow conditions and at a $10\\%$ reduced coolant flow-rate.\nMultiplication factors for the nominal and perturbed state are extracted and plugged into Equation \\ref{eqn:kdiff} for the coolant flow-rate coefficient of reactivity (FRCR).\nThe combined FRCR is calculated by taking the inner product of a system's local VCR traverse with the change in the void fraction traverse which results from the coolant flow-rate reduction and dividing by $10\\%$.\nThe latter will be referred to as the inner product approach.\nKPERT was used for estimating local VCR traverses.\nIts accuracy can be inferred from the results provided in Fig. \\ref{fig:verify}.\n\nFor the RBWR-Th the FRCR was calculated to be $-67.2 \\pm 0.1 [pcm/\\%]$ using the k-difference approach and $2.3 \\pm 0.8\\%$ (2.9 standard deviations) lower using the inner product approach.\nFor the RBWR-AC, the k-difference FRCR is $-2.7 \\pm 0.1 [pcm/\\%]$ while the inner product approach gave an estimate of $-1.8 \\pm 0.4 [pcm/\\%]$ that is $35 \\pm 20\\%$ too low.\nThis is probably due to strong non-linear effects in the strongly axially heterogeneous RBWR-AC core.\n\nFor typical core designs that feature a single seed zone agreement between the inner product and the k-difference approaches is quite good.\nBecause the inner product approach can provide estimates for a number of perturbations with the same runtime required for one k calculation, it is an efficient approach for scoping studies. \n\n\\section{Conclusions}\n\\label{sec:conclusion}\n\nThe expressions derived for estimating the reactivity effect of perturbations provide informative estimates of the total reactivity effect and of its components.\nThe methodology developed to quantify the spectral and flux tilt contributions to the reactivity effects of localized perturbations provide useful insight on the physics phenomena at play.\nAdditional useful insight is provided by quantifying the contribution to the reactivity effect of individual fuel isotopes and of the spectral and spatial components of this contribution.\nExpressions derived in past work by absorption and fission normalization yield the same total reactivities, but can provide misleading information on the contribution of different phase-space variables to the global reactivity.\n\nThe axial distribution of local VCR along the RBWR-Th seed and along the ABWR core have the same general shape: negative throughout but most negative in the lower quadrant of the active length; the local VCRs asymptotically approach zero towards the outlet.\nHowever, the RBWR-Th VCR gets to be $\\tild 4$ times more negative and this may be of practical concern as it may cause instabilities and make it difficult to achieve adequate cold shutdown margin.\nThe RBWR-AC local VCR axial distribution differs greatly from that of the other two core types -- it is very close to zero in the seed regions and has a significant positive component in the central blanket.\n\nThree types of spectral effects were identified contributing to the VCR due to a local water density change in the lower part of the RBWR-Th seed -- local spectrum hardening that tends to increase the local reproduction factor ($\\eta$) of each of the fuel isotopes; a redistribution of the local neutron absorption between the fuel isotopes resulting in a shift of absorptions from higher $\\eta_i$ to lower $\\eta_i$ isotopes and, hence, to a reactivity loss; and axial flux tilt across the core from axial zones of higher $\\eta_r$ to axial zones of lower $\\eta_r$ which makes another negative contribution to the reactivity worth of the perturbation.\nThe underlying mechanisms which cause negative reactivity due to the latter two effects are identical: $f_\\xi$ values shift from a phase-space $\\xi$ of higher $\\eta_\\xi$ to a phase-space of lower $\\eta_\\xi$ values.\n\nThe KPERT tool was found to be very effective at providing accurate estimates for the reactivity response from local perturbations.\nA limited check showed that linear superposition of the reactivity effect of local perturbations provides a good estimation of the global perturbation reactivity effect for the RBWR-Th.\nThis is also expected to be the case for the ABWR core but not for the RBWR-AC core which is more sensitive to axial power tilts due to its unique heterogeneity.\nA more thorough study to understand the shortcomings of the approach is warranted.\n\n\\section{Acknowledgements}\n\nThis research was performed using funding received from the U.S. Department of Energy Office of Nuclear Energy's Nuclear Energy University Programs.\nThis material is based upon work supported by the U.S. Department of Energy National Nuclear Security Administration under Award Number DE-NA0000979.\n\n\\appendix\n\\bibliographystyle{ans}\n\\bibliography{NSE14-104}\n\n\\clearpage\n\\begin{figure}[p]\n  \\centering\n  \\includegraphics[width=0.45\\textwidth, trim=0 0 0 0, clip]{./img/Th-xportSide.pdf}\n  \\hspace{0.1in}\n  \\includegraphics[width=0.45\\textwidth, trim=0 0 0 0, clip]{./img/Th-xportTop.pdf}\n  \\caption{The RBWR-Th single-pin unit cell shown (left) from the side and (right) from above. Figures are not to scale.}\n  \\label{fig:xport}\n\\end{figure}\n\n\\clearpage\n\\begin{table}[ht]\n    \\centering\n    \\caption{Isotopic composition of the seed fuel region for the RBWR-Th single-pin unit cell.}\n    \\label{tab:iso}\n    \\begin{tabular}{| c | c | c |} \\hline\n    \\textbf{Isotope} & \\textbf{Number Density} \\\\\n                     & \\textbf{$[a/b/cm]$}     \\\\ \\hline\n    \\iso{O}{16}      & $4.1259\\E{-2}$          \\\\ \\hline\n    \\iso{Th}{228}    & $7.5461\\E{-7}$          \\\\ \\hline\n    \\iso{Th}{229}    & $3.4110\\E{-7}$          \\\\ \\hline\n    \\iso{Th}{230}    & $7.9693\\E{-7}$          \\\\ \\hline\n    \\iso{Th}{232}    & $1.7153\\E{-2}$          \\\\ \\hline\n    \\iso{Pa}{231}    & $1.2033\\E{-5}$          \\\\ \\hline\n    \\iso{U}{232}     & $2.9986\\E{-5}$          \\\\ \\hline\n    \\iso{U}{233}     & $1.4777\\E{-3}$          \\\\ \\hline\n    \\iso{U}{234}     & $1.0605\\E{-3}$          \\\\ \\hline\n    \\iso{U}{235}     & $2.5392\\E{-4}$          \\\\ \\hline\n    \\iso{U}{236}     & $3.1760\\E{-4}$          \\\\ \\hline\n    \\iso{U}{238}     & $4.1905\\E{-7}$          \\\\ \\hline\n    \\iso{Np}{236}    & $4.7333\\E{-9}$          \\\\ \\hline\n    \\iso{Np}{237}    & $7.3786\\E{-5}$          \\\\ \\hline\n    \\iso{Pu}{238}    & $1.6406\\E{-4}$          \\\\ \\hline\n    \\iso{Pu}{239}    & $4.2105\\E{-5}$          \\\\ \\hline\n    \\iso{Pu}{240}    & $1.5521\\E{-5}$          \\\\ \\hline\n    \\iso{Pu}{241}    & $9.1368\\E{-6}$          \\\\ \\hline\n    \\iso{Pu}{242}    & $4.4926\\E{-6}$          \\\\ \\hline\n    \\iso{Pu}{244}    & $3.2513\\E{-9}$          \\\\ \\hline\n    \\iso{Am}{241}    & $4.2129\\E{-6}$          \\\\ \\hline\n    \\iso{Am}{242}    & $2.9638\\E{-7}$          \\\\ \\hline\n    \\iso{Am}{243}    & $1.8736\\E{-6}$          \\\\ \\hline\n    \\iso{Cm}{242}    & $3.0946\\E{-9}$          \\\\ \\hline\n    \\iso{Cm}{243}    & $1.5450\\E{-7}$          \\\\ \\hline\n    \\iso{Cm}{244}    & $2.6789\\E{-6}$          \\\\ \\hline\n    \\iso{Cm}{245}    & $1.8284\\E{-6}$          \\\\ \\hline\n    \\iso{Cm}{246}    & $1.5318\\E{-6}$          \\\\ \\hline\n    \\iso{Cm}{247}    & $2.5120\\E{-7}$          \\\\ \\hline\n    \\iso{Cm}{248}    & $2.5165\\E{-7}$          \\\\ \\hline\n    \\iso{Cf}{249}    & $6.0420\\E{-8}$          \\\\ \\hline\n    \\iso{Cf}{250}    & $9.3489\\E{-9}$          \\\\ \\hline\n    \\iso{Cf}{251}    & $1.0228\\E{-8}$          \\\\ \\hline\n    \\iso{Cf}{252}    & $8.4902\\E{-10}$         \\\\ \\hline\n    \\end{tabular}\n\\end{table}\n\n\\clearpage\n\\begin{figure}[p]\n  \\centering\n  \\includegraphics[width=\\textwidth, trim=0 0 0 0.275in, clip]{./img/Th-waterDensity.pdf}\n  \\caption{Axial distribution of the RBWR-Th water density.}\n  \\label{fig:rho}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}[p]\n  \\centering\n  \\includegraphics[width=\\textwidth, trim=0 0 0 0.275in, clip]{./img/Th-lhr.pdf}\n  \\caption{Axial distribution of the RBWR-Th linear heat rate.}\n  \\label{fig:lhr}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}[p]\n  \\centering\n  \\includegraphics[width=\\textwidth, trim=0 0 0 0.275in, clip]{./img/fluxSpectra.pdf}\n  \\caption{Comparison of normalized flux spectra for the RBWR-AC, RBWR-Th, a typical SFR, and the ABWR.}\n  \\label{fig:flx}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}[p]\n  \\centering\n  \\includegraphics[width=\\textwidth, trim=0 0 0 0.275in, clip]{./img/Th-Verify.pdf}\n  \\caption{Reactivity response from a 10\\% local voiding of coolant density, estimated with KPERT, PERT, and k-difference. The KPERT estimate for the perturbation at position $a$ exactly matches k-difference, so the markers overlap. Perturbations at positions $c$ and $d$ are not discussed in this work.}\n  \\label{fig:verify}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}[p]\n  \\centering\n  \\includegraphics[width=\\textwidth, trim=0 0 0 0.275in, clip]{./img/Th-KPERT.pdf}\n  \\caption{Axial traverse of RBWR-Th local VCRs estimated with KPERT. Perturbations $a$ and $b$ have the most positive and negative reactivity worths.}\n  \\label{fig:kpert}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}[p]\n  \\centering\n  \\includegraphics[width=\\textwidth, trim=0 0 0 0.275in, clip]{./img/Th-b-TraverseAlphaA.pdf}\n  \\caption{Absorption-normalized estimate ($\\alpha_\\A$) for the contribution from axial regions to the VCR due to local void perturbation $b$. Effectively shown are the changes in fission neutron births per neutron absorbed in the entire system.}\n  \\label{fig:alphaAR}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}[p]\n  \\centering\n  \\includegraphics[width=\\textwidth, trim=0 0 0 0.275in, clip]{./img/Th-b-TraverseAlphaF.pdf}\n  \\caption{Fission-normalized estimate ($\\alpha_\\F$) for the contribution from axial regions to the reactivity response to local void perturbation $b$. Effectively shown are the changes in neutron absorptions per fission neutron born in the entire system.}\n  \\label{fig:alphaFR}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}[p]\n  \\centering\n  \\includegraphics[width=\\textwidth, trim=0 0 0 0.275in, clip]{./img/Th-b-TraverseAlpha1.pdf}\n  \\caption{First-order estimate ($\\alpha_1$) of the contribution from axial regions to the reactivity response to local void perturbation $b$. Effectively shown are changes in fission neutron births, neutron absorptions, and their net sum.}\n  \\label{fig:alpha1R}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}[p]\n  \\centering\n  \\includegraphics[width=\\textwidth, trim=0 0 0 0.275in, clip]{./img/Th-b-TraverseAlpha2.pdf}\n  \\caption{Second-order estimate ($\\alpha_2$) of the contribution from axial regions to the reactivity response to local void perturbation $b$. Effectively shown are changes in fission neutron births, neutron absorptions, and their net sum.}\n  \\label{fig:alpha2R}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}[p]\n  \\centering\n  \\includegraphics[width=\\textwidth, trim=0 0 0 0.275in, clip]{./img/Th-b-TraverseDeltaEta.pdf}\n  \\caption{Change in the axial reproduction factor ($\\eta_r$) due to perturbation $b$. Voiding reduces $\\eta_r$ locally but otherwise does not affect $\\eta_r$ values.}\n  \\label{fig:deltaEtaR}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}[p]\n  \\centering\n  \\includegraphics[width=\\textwidth, trim=0 0 0 0.275in, clip]{./img/Th-b-TraverseDeltaEff.pdf}\n  \\caption{Change in the axial utilization factor ($f_r$) due to perturbation $b$. Voiding shifts $f_r$ from the perturbation vicinity to, primarily, upper part of the seed.}\n  \\label{fig:deltaEffR}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}[p]\n  \\centering\n  \\includegraphics[width=\\textwidth, trim=0 0 0 0.275in, clip]{./img/Th-b-TraverseEta.pdf}\n  \\caption{The RBWR-Th axial reproduction factor ($\\eta_r$) is highest near the coolant inlet and decreases with elevation due to coolant boiling.}\n  \\label{fig:etaR}\n\\end{figure}\n\n\\clearpage\n\\begin{table}[ht]\n    \\centering\n    \\caption{Deviations of estimates for the total reactivity worth of perturbation $b$, between predicted by each of the four perturbation expressions and the k-difference expression. p-values quantify the statistical significance of each deviation.}\n    \\label{tab:deltaAlpha}\n    \\begin{tabular}{| c | c | c |} \\hline\n    \\textbf{Expression} & \\textbf{Deviation from}     & \\textbf{p-value} \\\\\n                        & \\textbf{delta-k $[pcm/\\%]$} & \\textbf{$[\\%]$}  \\\\ \\hline\n    $\\alpha_\\A$         & $0.00 \\pm 1.1$              & $50$             \\\\ \\hline\n    $\\alpha_\\F$         & $0.00 \\pm 1.0$              & $50$             \\\\ \\hline\n    $\\alpha_1$          & $0.00 \\pm 1.4$              & $50$             \\\\ \\hline\n    $\\alpha_2$          & $0.05 \\pm 1.1$              & $52$             \\\\ \\hline\n    \\end{tabular}\n\\end{table}\n\n\\clearpage\n\\begin{figure}[p]\n  \\centering\n  \\includegraphics[width=\\textwidth, trim=0 0 0 0.275in, clip]{./img/Th-b-Traverse12Cmp.pdf}\n  \\caption{Difference between the second-order ($\\alpha_2$) and first-order ($\\alpha_1$) (calculated as $\\alpha_2-\\alpha_1$) estimates of the contribution from axial regions to the reactivity response to local void perturbation $b$. Due to the small difference between the two estimates, Monte Carlo counting uncertainties are relatively large.}\n  \\label{fig:deltaAlphaR}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}[p]\n  \\centering\n  \\includegraphics[width=\\textwidth, trim=0 0 0 0.275in, clip]{./img/Th-b-IsotopeAlpha2.pdf}\n  \\caption{Localized isotopic contribution to perturbation $b$'s local VCR. The net reactivity worths contributed by fissile isotopes are negative while those from non-fissile isotopes are positive.}\n  \\label{fig:alpha2I}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}[p]\n  \\centering\n  \\includegraphics[width=\\textwidth, trim=0 0 0 0, clip]{./img/Th-b-IsotopeDeltaEta.pdf}\n  \\caption{Localized change in isotopic reproduction factors $\\eta_i$ due to perturbation $b$. All values are positive.}\n  \\label{fig:deltaEtaI}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}[p]\n  \\centering\n  \\includegraphics[width=\\textwidth, trim=0 0 0 0.275in, clip]{./img/Th-b-IsotopeEta.pdf}\n  \\caption{Isotopic reproduction factors $\\eta_i$, in proximity to perturbation $b$.}\n  \\label{fig:etaI}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}[p]\n  \\centering\n  \\includegraphics[width=\\textwidth, trim=0 0 0 0.275in, clip]{./img/Th-b-IsotopeDeltaEff.pdf}\n  \\caption{Change in isotopic utilization factors $f_i$, in proximity to perturbation $b$.}\n  \\label{fig:deltaEffI}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}[p]\n  \\centering\n  \\includegraphics[width=\\textwidth, trim=0 0 0 0.2in, clip]{./img/Th-b-SpectraFlux.pdf}\n  \\caption{Localized change in flux spectrum due to perturbation $b$, normalized to an integral of unity.}\n  \\label{fig:deltaFlx}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}[p]\n  \\centering\n  \\includegraphics[width=\\textwidth, trim=0 0 0 0.275in, clip]{./img/Th-b-SpectraAlpha2-Th-232.pdf}\n  \\caption{Localized \\iso{Th}{232} energy-dependent contribution to perturbation $b$'s VCR. An overall positive reactivity response results from reduced resonance-energy absorptions.}\n  \\label{fig:alphaETh}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}[p]\n  \\centering\n  \\includegraphics[width=\\textwidth, trim=0 0 0 0.275in, clip]{./img/Th-b-SpectraAlpha2-U-233.pdf}\n  \\caption{Localized \\iso{U}{233} energy-dependent contribution to perturbation $b$'s VCR. An overall negative reactivity response is due to reduced thermal and epithermal fissions.}\n  \\label{fig:alphaEU}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}[p]\n  \\centering\n  \\includegraphics[width=\\textwidth, trim=0 0 0 0.275in, clip]{./img/XsAbsorption.pdf}\n  \\caption{Energy dependent absorption cross section of \\iso{Th}{232} and \\iso{U}{233}.}\n  \\label{fig:xs}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}[p]\n  \\centering\n  \\includegraphics[width=\\textwidth, trim=0 0 0 0.275in, clip]{./img/Th-a-TraverseDeltaEff.pdf}\n  \\caption{Change in the local utilization factor $f_r$ due to perturbation $a$. Voiding shifts $f_r$ from the top to the bottom of the core.}\n  \\label{fig:deltaEffRb}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}[p]\n  \\centering\n  \\includegraphics[width=\\textwidth, trim=0 0 0 0.275in, clip]{./img/ABWR-KPERT.pdf}\n  \\caption{Axial traverse of ABWR local VCRs estimated with KPERT. The overall shape is similar to that of the RBWR-Th seed region, shown in Fig. \\ref{fig:kpert}.}\n  \\label{fig:kpertAbwr}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}[p]\n  \\centering\n  \\includegraphics[width=\\textwidth, trim=0 0 0 0.275in, clip]{./img/AC-KPERT.pdf}\n  \\caption{Axial traverse of RBWR-AC local VCRs estimated with KPERT. Perturbations $a$ and $b$ result in the most negative and positive reactivity worth. The seed regions -- from $28$ to $47.3cm$ and from $99.3$ to $127.3cm$, are sandwiched between the three axial blanket regions.}\n  \\label{fig:kpertAc}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}[p]\n  \\centering\n  \\includegraphics[width=\\textwidth, trim=0 0 0 0.275in, clip]{./img/AC-TraverseAlpha2.pdf}\n  \\caption{Total contribution from axial fuel regions to the reactivity response to local void perturbation $b$.}\n  \\label{fig:alphaAc}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}[p]\n  \\centering\n  \\includegraphics[width=\\textwidth, trim=0 0 0 0.275in, clip]{./img/AC-TraverseDeltaEtaEff.pdf}\n  \\caption{Spectral hardening contribution ($\\sum_r{\\Delta\\eta_r f_r}$) from axial fuel regions to the reactivity response to local void perturbation $b$.}\n  \\label{fig:spectralAc}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}[p]\n  \\centering\n  \\includegraphics[width=\\textwidth, trim=0 0 0 0.275in, clip]{./img/AC-TraverseEtaDeltaEff.pdf}\n  \\caption{Flux tilt contribution ($\\sum_r{\\eta_r \\Delta f_r}$) from axial fuel regions to the reactivity response to local void perturbation $b$.}\n  \\label{fig:tiltAc}\n\\end{figure}\n\n\\end{document}\n", "meta": {"hexsha": "a01ba421ac0d10b1880fa0f0380f96ed26ba157a", "size": 54854, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "NSE14-104.tex", "max_stars_repo_name": "jeffseif/vcrPaper", "max_stars_repo_head_hexsha": "0c276bcbeb2483bdae06605f3208a17d7a4b4912", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NSE14-104.tex", "max_issues_repo_name": "jeffseif/vcrPaper", "max_issues_repo_head_hexsha": "0c276bcbeb2483bdae06605f3208a17d7a4b4912", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NSE14-104.tex", "max_forks_repo_name": "jeffseif/vcrPaper", "max_forks_repo_head_hexsha": "0c276bcbeb2483bdae06605f3208a17d7a4b4912", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 75.2455418381, "max_line_length": 650, "alphanum_fraction": 0.7427717213, "num_tokens": 15078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.30074784093814966}}
{"text": "\\chapter*{Overview of Scheme}\n\nThis paper gives an overview of \nthe small language of \\rsevenrs.\nThe purpose of this overview is to explain\nenough about the basic concepts of the language to facilitate\nunderstanding of the \\rsevenrs{} report, which is\norganized as a reference manual.  Consequently, this overview is\nnot a complete introduction to the language, nor is it precise\nin all respects or normative in any way.\n\n\\vest Following Algol, Scheme is a statically scoped programming\nlanguage.  Each use of a variable is associated with a lexically\napparent binding of that variable.\n\n\\vest Scheme has latent as opposed to manifest types.  Types\nare associated with objects (also called values) rather than\nwith variables.  (Some authors refer to languages with latent types as\nuntyped, weakly typed or dynamically typed languages.)  Other languages with\nlatent types are Python, Ruby, Smalltalk, and other dialects of Lisp.  Languages\nwith manifest types (sometimes referred to as strongly typed or\nstatically typed languages) include Algol 60, C, C\\#, Java, Haskell, and ML.\n\n\\vest All objects created in the course of a Scheme computation, including\nprocedures and continuations, have unlimited extent.\nNo Scheme object is ever destroyed.  The reason that\nimplementations of Scheme do not (usually!) run out of storage is that\nthey are permitted to reclaim the storage occupied by an object if\nthey can prove that the object cannot possibly matter to any future\ncomputation.  Other languages in which most objects have unlimited\nextent include C\\#, Java, Haskell, most Lisp dialects, ML, Python,\nRuby, and Smalltalk.\n\nImplementations of Scheme must be properly tail-recursive.\nThis allows the execution of an iterative computation in constant space,\neven if the iterative computation is described by a syntactically\nrecursive procedure.  Thus with a properly tail-recursive implementation,\niteration can be expressed using the ordinary procedure-call\nmechanics, so that special iteration constructs are useful only as\nsyntactic sugar.\n\n\\vest Scheme was one of the first languages to support procedures as\nobjects in their own right.  Procedures can be created dynamically,\nstored in data structures, returned as results of procedures, and so\non.  Other languages with these properties include Common Lisp,\nHaskell, ML, Ruby, and Smalltalk.\n\n\\vest One distinguishing feature of Scheme is that continuations, which\nin most other languages only operate behind the scenes, also have\n``first-class'' status.  First-class continuations are useful for implementing a\nwide variety of advanced control constructs, including non-local exits,\nbacktracking, and coroutines.\n\nIn Scheme, the argument expressions of a procedure call are evaluated\nbefore the procedure gains control, whether the procedure needs the\nresult of the evaluation or not.  C, C\\#, Common Lisp, Python,\nRuby, and Smalltalk are other languages that always evaluate argument\nexpressions before invoking a procedure.  This is distinct from the\nlazy-evaluation semantics of Haskell, or the call-by-name semantics of\nAlgol 60, where an argument expression is not evaluated unless its\nvalue is needed by the procedure.\n\nScheme's model of arithmetic provides a rich set of numerical types\nand operations on them.  Furthermore, it distinguishes \\textit{exact}\nand \\textit{inexact} numbers: Essentially, an exact number\nobject corresponds to a number exactly, and an inexact number\nis the result of a computation that involved rounding or other approximations.\n\n\\chapter{Basic types}\n\nScheme programs manipulate \\textit{objects}, which are also referred\nto as \\textit{values}.\nScheme objects are organized into sets of values called \\textit{types}.\nThis chapter gives an overview of the fundamentally important types of the\nScheme language.  \n\n\\begin{note}\n  As Scheme is latently typed, the use of the term \\textit{type} in\n  the Scheme context differs from the use of the term in the context of other\n  languages, particularly those with manifest typing.\n\\end{note}\n\n\\paragraph{Numbers}\n\nScheme supports a rich variety of numerical data types, including\nintegers of arbitrary precision, rational numbers, complex numbers, and\ninexact numbers of various kinds.  \n\n\\paragraph{Booleans}\n\nA boolean is a truth value, and can be either\ntrue or false.  In Scheme, the object for ``false'' is written\n\\schfalse{}.  The object for ``true'' is written \\schtrue{}.  In\nmost places where a truth value is expected, however, any object different from\n\\schfalse{} counts as true.\n\n\\paragraph{Pairs and lists}\n\nA pair is a data structure with two components.  The most common use\nof pairs is to represent (singly linked) lists, where the first\ncomponent (the ``car'') represents the first element of the list, and\nthe second component (the ``cdr'') the rest of the list.  Scheme also\nhas a distinguished empty list, which is the last cdr in a chain of\npairs that form a list.\n\n\\paragraph{Symbols}\n\nA symbol is an object representing a string,\nthe symbol's \\textit{name}.\nUnlike strings, two symbols whose names are spelled the same\nway are never distinguishable.  Symbols are useful for many applications;\nfor instance, they can be used the way enumerated values are used in\nother languages.\n\nIn \\rsevenrs, unlike \\rfivers, symbols and identifiers are case-sensitive.\n\n\\paragraph{Characters}\n\nScheme characters mostly correspond to textual characters.\nMore precisely, they are isomorphic to a subset of the \\textit{scalar values} of\nthe Unicode standard, with possible implementation-dependent extensions.\n\n\\paragraph{Strings}\n\nStrings are finite sequences of characters with fixed length and thus\nrepresent arbitrary Unicode texts.\n\n\\paragraph{Vectors}\n\nVectors, like lists, are linear data structures\nrepresenting finite sequences of arbitrary objects.\nWhereas the elements of a list are accessed\nsequentially through the chain of pairs representing it,\nthe elements of a vector are addressed by integer indices.\nThus, vectors are more appropriate than\nlists for random access to elements.\n\n\\paragraph{Bytevectors}\n\nBytevectors are similar to vectors, except that their contents\nare \\textit{bytes}, exact integers in the range 0 to 255 inclusive.\n\n\\paragraph{Procedures}\n\nProcedures are values in Scheme.\n\n\\paragraph{Records}\n\nRecords are structured values, and are\naggregations of zero or more \\textit{fields}, each of which holds a single location.\nRecords are organized into \\textit{record types}.\nA predicate, a constructor, and field accessors and\nmutators can be defined for each record type.\n\n\\paragraph{Ports}\n\nPorts represent input and output devices.  To Scheme, an input port is\na Scheme object that can deliver data upon command, while an output\nport is a Scheme object that can accept data.\n\n\\chapter{Expressions}\n\nThe most important elements of Scheme code are\n\\textit{expressions}.  Expressions can be\n\\textit{evaluated}, producing a \\textit{value} (actually, any number\nof values.)  The most\nfundamental expressions are literal expressions:\n\n\\begin{scheme}\n\\schtrue{} \\ev \\schtrue\n23 \\ev 23%\n\\end{scheme}\n\nThis notation means that the expression \\schtrue{} evaluates to\n\\schtrue{}, that is, the value for ``true'',  and that the expression\n{\\cf 23} evaluates to a number representing the number 23.\n\nCompound expressions are formed by placing parentheses around their\nsubexpressions.  The first subexpression identifies an operation; the\nremaining subexpressions are operands to the operation:\n%\n\\begin{scheme}\n(+ 23 42) \\ev 65\n(+ 14 (* 23 42)) \\ev 980%\n\\end{scheme}\n%\nIn the first of these examples, {\\cf +} is the name of\nthe built-in operation for addition, and {\\cf 23} and {\\cf 42} are the\noperands.  The expression {\\cf (+ 23 42)} reads as ``the sum of 23 and\n42''.  Compound expressions can be nested---the second example reads\nas ``the sum of 14 and the product of 23 and 42''.\n\nAs these examples indicate, compound expressions in Scheme are always\nwritten using the same prefix notation.  As\na consequence, the parentheses are needed to indicate structure.\nConsequently, ``superfluous'' parentheses, which are often permissible in\nmathematical notation and also in many programming languages, are not\nallowed in Scheme.\n\nAs in many other languages, whitespace (including line endings) is not\nsignificant when it separates subexpressions of an expression, and\ncan be used to indicate structure.\n\n\\chapter{Variables and binding}\n\nScheme\nallows identifiers to stand for locations containing values.\nThese identifiers are called variables.  In many cases, specifically\nwhen the location's value is never modified after its creation, it is\nuseful to think of the variable as standing for the value directly.\n\n\\begin{scheme}\n(let ((x 23)\n      (y 42))\n  (+ x y)) \\ev 65%\n\\end{scheme}\n\nIn this case, the expression starting with {\\cf let} is a binding\nconstruct.  The parenthesized structure following the {\\cf let} lists\nvariables alongside expressions: the variable {\\cf x} alongside {\\cf\n  23}, and the variable {\\cf y} alongside {\\cf 42}.  The {\\cf let}\nexpression binds {\\cf x} to 23, and {\\cf y} to 42.  These bindings are\navailable in the \\textit{body} of the {\\cf let} expression, {\\cf (+ x\n  y)}, and only there.\n\n\\chapter{Definitions}\n\nThe variables bound by a {\\cf let} expression\nare \\textit{local}, because their bindings are visible only in the\n{\\cf let}'s body.  Scheme also allows creating top-level bindings for\nidentifiers as follows:\n\n\\begin{scheme}\n(define x 23)\n(define y 42)\n(+ x y) \\ev 65%\n\\end{scheme}\n\n(These are actually ``top-level'' in the body of a top-level program or library.)\n\nThe first two parenthesized structures are \\textit{definitions}; they\ncreate top-level bindings, binding {\\cf x} to 23 and {\\cf y} to 42.\nDefinitions are not expressions, and cannot appear in all places\nwhere an expression can occur.  Moreover, a definition has no value.\n\nBindings follow the lexical structure of the program:  When several\nbindings with the same name exist, a variable refers to the binding\nthat is closest to it, starting with its occurrence in the program\nand going from inside to outside, and referring to an outermost\nbinding if no\nlocal binding can be found along the way:\n\n\\begin{scheme}\n(define x 23)\n(define y 42)\n(let ((y 43))\n  (+ x y)) \\ev 66\n\n(let ((y 43))\n  (let ((y 44))\n    (+ x y))) \\ev 67%\n\\end{scheme}\n\n\\chapter{Procedures}\n\nDefinitions can also be used to define\nprocedures:\n\n\\begin{scheme}\n(define (f x)\n  (+ x 42))\n\n(f 23) \\ev 65%\n\\end{scheme}\n\nA procedure is, slightly simplified, an abstraction of an\nexpression over objects.  In the example, the first definition defines a procedure\ncalled {\\cf f}.  (Note the parentheses around {\\cf f x}, which\nindicate that this is a procedure definition.)  The expression {\\cf (f\n  23)} is a procedure call meaning,\nroughly, ``evaluate {\\cf (+ x 42)} (the body of the procedure) with\n{\\cf x} bound to 23''.\n\nAs procedures are objects, they can be passed to other\nprocedures:\n%\n\\begin{scheme}\n(define (f x)\n  (+ x 42))\n\n(define (g p x)\n  (p x))\n\n(g f 23) \\ev 65%\n\\end{scheme}\n\nIn this example, the body of {\\cf g} is evaluated with {\\cf p}\nbound to {\\cf f} and {\\cf x} bound to 23, which is equivalent\nto {\\cf (f 23)}, which evaluates to 65.\n\nIn fact, many predefined operations of Scheme are provided not by\nsyntax, but by variables whose values are procedures.\nThe {\\cf +} operation, for example, which receives\nspecial syntactic treatment in many other languages, is just a regular\nidentifier in Scheme, bound to a procedure that adds numbers.  The\nsame holds for {\\cf *} and many others:\n\n\\begin{scheme}\n(define (h op x y)\n  (op x y))\n\n(h + 23 42) \\ev 65\n(h * 23 42) \\ev 966%\n\\end{scheme}\n\nProcedure definitions are not the only way to create procedures.  A\n{\\cf lambda} expression creates a new procedure as an object, with no\nneed to specify a name:\n\n\\begin{scheme}\n((lambda (x) (+ x 42)) 23) \\ev 65%\n\\end{scheme}\n\nThe entire expression in this example is a procedure call; {\\cf\n  (lambda (x) (+ x 42))}, evaluates to a procedure that takes a single\nnumber and adds 42 to it.\n\n\\chapter{Procedure calls and syntactic keywords}\n\nWhereas {\\cf (+ 23 42)}, {\\cf (f 23)}, and {\\cf ((lambda (x) (+ x 42))\n  23)} are all examples of procedure calls, {\\cf lambda} and {\\cf\n  let} expressions are not.  This is because {\\cf let}, even though\nit is an identifier, is not a variable, but is instead a \\textit{syntactic\n  keyword}.  A list that has a\nsyntactic keyword as its first subexpression obeys special rules determined by\nthe keyword.  The {\\cf define} identifier in a definition is also a\nsyntactic keyword.  Hence, definitions are also not procedure calls.\n\nThe rules for the {\\cf lambda} keyword specify that the first\nsublist is a list of parameters, and the remaining sublists are the body of\nthe procedure.  In {\\cf let} expressions, the first sublist is a list\nof binding specifications, and the remaining sublists constitute a body of\nexpressions.\n\nProcedure calls can be distinguished from these\n\\textit{expression types} by\nlooking for a syntactic keyword in the first position of a list:\nif the first position does not contain a syntactic keyword, the expression\nis a procedure call.  \nThe set of syntactic keywords of Scheme is\nfairly small, which usually makes this task fairly simple.\nIt is possible, however, to create new bindings for syntactic keywords.\n\n\\chapter{Assignment}\n\nScheme variables bound by definitions or {\\cf let} or {\\cf lambda}\nexpressions are not actually bound directly to the objects specified in the\nrespective bindings, but to locations containing these objects.  The\ncontents of these locations can subsequently be modified destructively\nvia \\textit{assignment}:\n%\n\\begin{scheme}\n(let ((x 23))\n  (set! x 42)\n  x) \\ev 42%\n\\end{scheme}\n\nIn this case, the body of the {\\cf let} expression consists of two\nexpressions which are evaluated sequentially, with the value of the\nfinal expression becoming the value of the entire {\\cf let}\nexpression.  The expression {\\cf (set! x 42)} is an assignment, saying\n``replace the object in the location referenced by {\\cf x} with 42''.\nThus, the previous value of {\\cf x}, 23, is replaced by 42.\n\n\\chapter{Derived syntax and macros}\n\nMany of the expression types specified \nas part of the \\rsevenrs{} small language\ncan be translated into more basic expression types.\nFor example, a {\\cf let} expression can be translated\ninto a procedure call and a {\\cf lambda} expression.  The following two\nexpressions are equivalent:\n%\n\\begin{scheme}\n(let ((x 23)\n      (y 42))\n  (+ x y)) \\ev 65\n\n((lambda (x y) (+ x y)) 23 42) \\lev 65%\n\\end{scheme}\n\nSyntax expressions like {\\cf let} expressions are called \\textit{derived}\nbecause their semantics can be\nderived from that of other kinds of expressions by a syntactic\ntransformation.  Some procedure definitions are also derived expressions.  The\nfollowing two definitions are equivalent:\n\n\\begin{scheme}\n(define (f x)\n  (+ x 42))\n\n(define f\n  (lambda (x)\n    (+ x 42)))%\n\\end{scheme}\n\nIn Scheme, it is possible for a program to create its own derived\nexpressions by binding syntactic keywords to macros:\n\n\\begin{scheme}\n(define-syntax def\n  (syntax-rules ()\n    ((def f (p ...) body)\n     (define (f p ...)\n       body))))\n\n(def f (x)\n  (+ x 42))%\n\\end{scheme}\n\nThe {\\cf define-syntax} construct specifies that a parenthesized\nstructure matching the pattern {\\cf (def f (p ...) body)}, where {\\cf\n  f}, {\\cf p}, and {\\cf body} are pattern variables, is translated to\n{\\cf (define (f p ...) body)}.  Thus, the {\\cf def} expression appearing in\nthe example gets translated to:\n\n\\begin{scheme}\n(define (f x)\n  (+ x 42))%\n\\end{scheme}\n\nThe ability to create new syntactic keywords makes Scheme extremely\nflexible and expressive, allowing many of the features\nbuilt into other languages to be implemented directly in Scheme:\nany Scheme programmer can add new expression types.\n\n\\chapter{Syntactic data and datum values}\n\n\\textit{Datum values} constitute a subset of Scheme objects.\nThese include booleans, numbers, characters, symbols,\nand strings as well as lists, vectors, and bytevectors whose elements are datum values.  Each\ndatum value can be represented textually as a\n\\textit{syntactic datum}, which can be written out\nand read back in without loss of information.\nThere is in general more than one syntactic datum corresponding to each datum value.\nMoreover, each datum value\ncan be trivially translated to a literal expression in a program by\nprepending a {\\cf\\singlequote} to a corresponding syntactic datum:\n\n\\begin{scheme}\n'23 \\ev 23\n'\\schtrue{} \\ev \\schtrue{}\n'foo \\ev foo\n'(1 2 3) \\ev (1 2 3)\n'\\#(1 2 3) \\ev \\#(1 2 3)%\n\\end{scheme}\n\nThe {\\cf\\singlequote} shown in the previous examples\nis not needed for representations of literal constants other than\nsymbols and lists.\nThe syntactic datum {\\cf foo} represents a\nsymbol with name ``foo'', and {\\cf 'foo} is a literal expression with\nthat symbol as its value.  {\\cf (1 2 3)} is a syntactic datum that \nrepresents a list with elements 1, 2, and 3, and {\\cf '(1 2 3)} is a literal\nexpression with this list as its value.  Likewise, {\\cf \\#(1 2 3)}\nis a syntactic datum that represents a vector with elements 1, 2 and 3, and\n{\\cf '\\#(1 2 3)} is the corresponding literal.\n\nSyntactic datums are a superset of Scheme expressions.  Thus, data\ncan be used to represent Scheme expressions as data objects.  In\nparticular, symbols can be used to represent identifiers.\n\n\\begin{scheme}\n'(+ 23 42) \\ev (+ 23 42)\n'(define (f x) (+ x 42)) \\lev (define (f x) (+ x 42))%\n\\end{scheme}\n\nThis facilitates writing programs that operate on Scheme source code,\nin particular interpreters and program transformers.\n\n\\chapter{Continuations}\n\nWhenever a Scheme expression is evaluated there is a\n\\textit{continuation} wanting the result of the\nexpression.  The continuation represents an entire (default) future\nfor the computation.  For example, informally the continuation of {\\cf 3}\nin the expression\n%\n\\begin{scheme}\n(+ 1 3)%\n\\end{scheme}\n%\nadds 1 to it.  Normally these ubiquitous continuations are hidden\nbehind the scenes and programmers do not think much about them.  On\nrare occasions, however, a programmer needs to deal with\ncontinuations explicitly.  The {\\cf call-with-current-continuation}\nprocedure allows\nScheme programmers to do that by creating a procedure that reinstates\nthe current continuation.  The {\\cf call-with-current-continuation}\nprocedure accepts a procedure, calls it immediately with an argument\nthat is an \\textit{escape procedure}.  This\nescape procedure can then be called with an argument that becomes the\nresult of the call to {\\cf call-with-current-continuation}.  That is,\nthe escape procedure abandons its own continuation, and reinstates the\ncontinuation of the call to {\\cf call-with-current-continuation}.\n\nIn the following example, an escape procedure representing the\ncontinuation that adds 1 to its argument is bound to {\\cf escape}, and\nthen called with 3 as an argument.  The continuation of the call to\n{\\cf escape} is abandoned, and instead the 3 is passed to the\ncontinuation that adds 1:\n%\n\\begin{scheme}\n(+ 1 (call-with-current-continuation\n       (lambda (escape)\n         (+ 2 (escape 3))))) \\lev 4%\n\\end{scheme}\n%\nAn escape procedure has unlimited extent: It can be called after the\ncontinuation it captured has been invoked, and it can be called\nmultiple times.  This makes {\\cf call-with-current-continuation}\nsignificantly more powerful than typical non-local control constructs\nsuch as exceptions in other languages.\n\n\\chapter{Libraries}\n\nScheme code can be organized in components called\n\\textit{libraries}.  Each library contains \ndefinitions and expressions.  It can import definitions\nfrom other libraries and export definitions to other libraries.\n\nThe following library called {\\cf (hello)} exports a definition called\n{\\cf hello-world},  and imports the base library\nand the display library.\nThe {\\cf hello-world} export is a procedure that displays {\\cf Hello World}\non a separate line:\n%\n\\begin{scheme}\n(define-library (hello)\n  (export hello-world)\n  (import (scheme base)\n          (scheme display))\n  (begin\n    (define (hello-world)\n      (display \"Hello World\")\n      (newline))))%\n\\end{scheme}\n\n\\chapter{Programs}\n\nLibraries are invoked by other libraries, but ultimately by a Scheme\n\\textit{program}.  Like a library, a\nprogram contains imports, definitions and expressions, and specifies\nan entry point for execution.  Thus a program defines, via\nthe transitive closure of the libraries it imports, a Scheme program.\n\nThe following program obtains the first argument from the command line\nvia the {\\cf command-line} procedure from the process-context\nlibrary.\nIt then opens the file using {\\cf with-input-from-file},\nwhich causes the file to be the current input port, and\narranges for it to be closed at the end.\nNext, it calls the {\\cf read-line} procedure to read a line of text\nfrom the file, and then {\\cf write-string} and {\\cf newline} to\noutput the line, then looping until the end of file:\n%\n\\begin{scheme}\n(import (scheme base)\n        (scheme file)\n        (scheme process-context))\n(with-input-from-file\n  (cadr (command-line))\n  (lambda ()\n    (let loop ((line (read-line)))\n      (unless (eof-object? line)\n        (write-string line)\n        (newline)\n        (loop (read-line))))))%\n\\end{scheme}\n\n\\chapter{The REPL}\n\nImplementations may provide an interactive session called a\n\\defining{REPL} (Read-Eval-Print Loop), where import declarations,\nexpressions and definitions can be\nentered and evaluated one at a time.  The REPL starts out\nwith the base library imported, and possibly other libraries.\nAn implementation may provide a mode of operation in which the REPL\nreads its input from a file.  Such a file is not, in general, the same\nas a program, because it can contain import declarations in places other than\nthe beginning.\n\nHere is a short REPL session.  The {\\cf >} character represents the REPL's\nprompt for input:\n\n\\begin{scheme}\n> ; A few simple things\n> (+ 2 2)\n4\n> (sin 4)\nUndefined variable: sin\n> (import (scheme inexact))\n> (sin 4)\n-0.756802495307928\n> (define sine sin)\n> (sine 4)\n-0.756802495307928\n> ; Guy Steele's three-part test\n> ; True is true ...\n> \\#t\n\\#t\n> ; 100!/99! = 100 ...\n> (define (fact n)\n    (if (= n 0) 1 (* n (fact (- n 1)))))\n> (/ (fact 100) (fact 99))\n100\n> ; If it returns the *right* complex number,\n> ; so much the better ...\n> (define (atanh x)\n    (/ (- (log (+ 1 x))\n          (log (- 1 x)))\n       2))\n> (atanh -2)\n-0.549306144334055+1.5707963267949i%\n\\end{scheme}\n\n%%% Local Variables: \n%%% mode: latex\n%%% End: \n", "meta": {"hexsha": "1887b94a3832d67e7ad3f25e29e791fd0b43fd46", "size": 22559, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "r7rs/overview-body.tex", "max_stars_repo_name": "schemedoc/rnrs-metadata", "max_stars_repo_head_hexsha": "2f998d354177dc41a8d3147fd15c056a14ffabda", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-04T17:38:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-04T17:38:19.000Z", "max_issues_repo_path": "r7rs/overview-body.tex", "max_issues_repo_name": "schemedoc/scheme-rnrs-metadata", "max_issues_repo_head_hexsha": "2f998d354177dc41a8d3147fd15c056a14ffabda", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-03-27T22:24:05.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-26T17:56:02.000Z", "max_forks_repo_path": "r7rs/overview-body.tex", "max_forks_repo_name": "schemedoc/scheme-rnrs-metadata", "max_forks_repo_head_hexsha": "2f998d354177dc41a8d3147fd15c056a14ffabda", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8079365079, "max_line_length": 93, "alphanum_fraction": 0.7543330821, "num_tokens": 5545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3006743513994525}}
{"text": "%!TEX root = ../thesis.tex\n%*******************************************************************************\n%****************************** Second Chapter *********************************\n%*******************************************************************************\n\n\\chapter{Preliminaries}\n\n\\ifpdf\n    \\graphicspath{{Chapter2/Figs/Raster/}{Chapter2/Figs/PDF/}{Chapter2/Figs/}}\n\\else\n    \\graphicspath{{Chapter2/Figs/Vector/}{Chapter2/Figs/}}\n\\fi\n\n\n\\section{Machine Learning}\n\\label{preliminaries:machine_learning}\n\nMachine learning is a field in computer science that we try teaching the computers to do tasks without explicitly programmed \\citep{samuel2000some, koza1996automated}. Machine learning is strongly associated with computational statistics, which explores data and builds algorithms that could find patterns in data and make predictions. More formal definition of the algorithms used in the machine learning is provided by Mitchell ``A computer program is said to learn from experience E with respect to some class of tasks T and performance measure P if its performance at tasks in T, as measured by P, improves with experience E`` \\citep{mitchell1997machine}.\n\nTypically, tasks in machine learning can be grouped into three wide categories \\citep{russell1995modern}:\n\n\\begin{itemize}\n\\item Supervised learning: the given data contains input values and their desired output values, the aim of algorithms in supervised learning is to find a general rule that maps inputs to outputs. In this thesis we are focus on the supervised learning approach for our fraud detection problem,\n\\item Unsupervised learning: there are no desired outputs in the dataset, it means that we give the learning algorithms freely to explore a hidden structure of the data,\n\\item Reinforcement learning: this kind of learning is slightly different with the above, reinforcement learning builds a dynamic environment then let a computer interacts with it to perform a certain goal, after each action a feedback is provided to the computer as a reward or a punishment.\n\\end{itemize}\n\n\nSupervised learning is a most common task in the world and can be seen as a function from labeled training data \\citep{mohri2012foundations}. Given a set of $N$ data points of a form ${(x_1, y_1), \\dots, (x_N, y_N)}$ such that $x_i$ is a attribute vector of the i-th data point and $y_i$ is its desired output, a supervised learning algorithm is a function $g: X \\rightarrow Y$, where $X$ is an input space (matrix of attribute vectors) and $Y$ is a output space (matrix of desired outputs). Typically the function $g$ is in a function space $G$, or we could represent $g$ as a scoring function $f: X \\times Y \\rightarrow \\mathbb{R}$ such that function $f$ will return the output value $y$ which has the highest score $g(x) = argmax_y f(x, y)$. For example, $g$ could be a conditional probability model $g(x) = P(y \\mid x)$, e.g. logistic regression \\citep{walker1967estimation, cox1958regression}, or $f$ could takes a form of a join t probability model $f(x, y) = P(x, y)$, e.g. naive Bayes \\citep{russell1995modern}.\n\nIn order to measure a performance of learning function, we could define a loss function $L: Y \\times Y \\rightarrow \\mathbb{R}$ and a risk $R(g)$ of learning function $g$ is defined as an expected loss of function $g$ which could be estimated by:\n\n\\begin{equation}\n\\widehat{R} (g) = \\dfrac{1}{N} \\sum_i L(y_i, g(x_i))\n\\end{equation}\n\n\\subsection*{Decision tree learning}\n\nA decision tree learning is one common approach in data mining \\citep{rokach2014data}, it aims to create a model that predicts values like making a decision from a tree-based analysis. An example is shown in the figure \\ref{img:titanic_survival_decision_tree} \\citep{decision_tree_learning}.\n\n\\begin{figure}\n\\includegraphics[scale=0.4]{Images/Titanic_Survival_Decison_Tree_SVG.png}\n\\centering\n\\caption{A tree showing survival of passengers on the Titanic}\n\\label{img:titanic_survival_decision_tree}\n\\end{figure}\n\nA tree learner could classify the data points by splitting the input dataset into subsets based on a given criterion. The splitting process at each node is repeated in a recursive procedure until all data points are classified. There are two kinds of decision trees:\n\n\\begin{itemize}\n\\item Regression tree: create a tree to predict the desired output as a real number,\n\\item Classification tree: an analysis aims to predict a categorical output.\n\\end{itemize}\n\nA term Classification and Regression Tree (CART) analysis is used to refer to both the above analysis \\citep{breiman1984classification}. There are many decision tree algorithms, including:\n\n\\begin{itemize}\n\\item ID3 (Iterative Dichotomiser 3) \\citep{quinlan1986induction},\n\\item C4.5: an extension of ID3 algorithm \\citep{quinlan2014c4}.\n\\end{itemize}\n\nAlgorithms for constructing decision trees use different metrics for measuring which is the best feature to split the dataset. These measures compute the homogeneity of the output values within the subsets, some common measures in decision tree learning is Entropy, Information Gain, and Gini.\n\n\n\\subsection*{Ensemble learning}\n\nIn machine learning, ensemble learning is a method combines multiple learning algorithms to obtain better accuracy than from any individual algorithms \\citep{opitz1999popular, rokach2010ensemble}. The term ensemble is usually reserved for methods that generate multiple hypotheses using the same base learner. There are three common types of ensemble learning, such as:\n\n\n\\subparagraph{Bootstrap aggregating (bagging)}\n\nAn ensemble technique is bootstrap aggregating which is usually called bagging (see figure \\ref{img:bagging_ensemble}), it combines multiple learnings via their equal weight votes. In order to support the model variance, bagging trains each model from a randomly drawn subset. And a famous example of bagging is the Random Forest algorithm which uses random decision trees as base learners.\n\n\n\\begin{figure}\n\\includegraphics[scale=0.4]{Images/bagging.jpg}\n\\centering\n\\caption{Bagging ensemble \\citep{raschka2015python}}\n\\label{img:bagging_ensemble}\n\\end{figure}\n\n\n\\subparagraph{Boosting}\n\nSimilar with the bagging ensemble, boosting is an incremental algorithm that will train each new model to underline the data points that previous models mis-classified (see figure \\ref{img:boosting_ensemble}). Boosting could have a better accuracy than bagging in some cases, however it also tends to overfit to the training data. A most common boosting algorithm is Adaboost \\citep{freund1999short}.\n\n\n\\begin{figure}\n\\includegraphics[scale=0.4]{Images/boosting.png}\n\\centering\n\\caption{Boosting ensemble \\citep{raschka2015python}}\n\\label{img:boosting_ensemble}\n\\end{figure}\n\n\n\\subparagraph{Stacking}\n\nSlightly different with these above techniques, stacking is a supervised learning algorithm that uses the predictions of several other learning algorithms as an input dataset to makes the final prediction (see figure \\ref{img:stacking_ensemble}). All of the other algorithms are trained using the given dataset independently, then a combiner algorithm is trained on that which can be any algorithm. Therefore, stacking can theoretically represent any of the ensemble techniques, although in practice we often use the Logistic Regression or Linear Regression as the combiner.\n\n\n\\begin{figure}\n\\includegraphics[scale=0.4]{Images/stacking.png}\n\\centering\n\\caption{Stacking ensemble \\citep{raschka2015python}}\n\\label{img:stacking_ensemble}\n\\end{figure}\n\n\n\\subsection*{Random Forest}\n\nRandom Forest \\citep{breiman2001random} or random decision forests \\citep{ho1995random, ho1998random} are an ensemble learning method for classification or regression that perform by constructing many trees, e.g. decision trees, then combine these results to makes final output values as a mode of the classes for classification tasks or a mean prediction for regression tasks. The Random Forest model based on two elements:\n\n\n\\begin{enumerate}\n\\item Base learner: each tree in the forest is the base learner, typically it is a weak learner with high variance,\n\\item Ensemble learning: combine the results of several weak learners to make a final prediction.\n\\end{enumerate}\n\n\nThe Decision Tree above that are grown very deep tend to overfit their training sets, i.e. have a low bias, but very high variance. We use the tree-based method as the base learner by its strength, and to handle its weakness we combine all of the predictions via ensemble learning. This method is called Random Forest, it can formulate the algorithm as the following statement: given a dataset $X = x_1, \\dots, x_n$ with $n$ data points and respectively desired output values $Y = y_1, \\dots, y_n$, bagging repeatedly $B$ times selects a random sample from the dataset $X$ then training trees on these samples.\n\n\n\\begin{algorithm}\n   \\caption{Tree bagging}\n    \\begin{algorithmic}\n      \\Function{bagging}{$X, Y, B$}\n\n        \\For{$b = 1$ to ${B}$}\n            \\State $(X_b, Y_b)$ is samples from $(X, Y)$ which have $n$ data points\n            \\State Train a classification or regression tree $f_b$ on $X_b, Y_b$\n        \\EndFor\n        \n       \\EndFunction\n\n\\end{algorithmic}\n\\end{algorithm}\n\n\nThe authors of Random Forest have proposed using an average function to makes the final prediction in regression tasks or takes the majority vote in classification tasks \\citep{breiman2001random}. However, there is no standard function as a combiner, thus we are free to choose the combination function. This bootstrapping procedure could decrease the variance of the model without increasing the bias. In order to estimate the uncertainty of the prediction, it could be computed as a standard deviation of the predictions from all the individual trees:\n\n\\begin{equation}\n\\sigma = \\sqrt{ \\dfrac{ \\sum_{b=1}^B ( f_b(x) - \\hat{f} ) }{ B - 1 } }\n\\end{equation}\n\nRandom Forest uses the above bagging algorithm with only one difference, it uses a modified tree that selects a random subset of the features to split a current subset data. Typically, the dataset has $p$ features then for a classification problem $\\sqrt{p}$ features will be used in each split and for regression problems the inventor recommends that we should use $p/3$ as the number of features \\citep{friedman2001elements}.\n\n\n\\section{Measurement}\n\\label{measurement_premilinaries}\n\nThe fraud detection problem is the classification task and in order to measure how well of the classifiers, there are many metrics could be used to evaluate the algorithms. In this section, we will review some common metrics which are typically used in classification tasks.\n\n\n\\subsection*{Accuracy}\n\nAccuracy is a measure of statistical variablity which represent a percentage of correct predictions on the total number of cases examined. In the fields of science and engineering, the accuracy of a measurement system is the degree of closeness of measurements of a quantity to that quantity's true value \\citep{bipm2008international}. Consider 2 sets with $n$ data points: the true labels from the given dataset $Y = {y_1, \\dots, y_n}$ and our predicted values $\\hat{Y} = {\\hat{y_1}, \\dots, \\hat{y_n}}$, the accuracy is:\n\n\\begin{equation}\naccuracy = \\dfrac{ 1 }{ n } \\sum_{i = 1}^n \\mbox{1\\hspace{-4.25pt}\\fontsize{12}{14.4}\\selectfont\\textrm{1}}_{ y_i = \\hat{y_i} }\n\\end{equation}\n\n\n\\subsection*{Precision and recall}\n\nIn pattern recognition, information retrieval and binary classification, precision and recall are two common metrics. Precision (also called positive predictive value) is the fraction of relevant data points among the given data points, and recall (also known as sensitivity) is the fraction of relevant data points that have been retrieved over the total amount of relevant data points (see figure \\ref{img:precision_and_recall}).\n\n\n\\begin{figure}\n\\includegraphics[scale=0.35]{Images/Precisionrecall.png}\n\\centering\n\\caption{Precision and recall \\citep{wiki2018precision_recall}}\n\\label{img:precision_and_recall}\n\\end{figure}\n\n\nIn the information retrieval contexts, precision and recall were defined by Perry, Kent \\& Berry (1955) \\citep{perry1955machine} as a set of retrieved elements and a set of relevant elements. Precision is the fraction of retrieved documents that are relevant to the query:\n\n\n\\begin{equation}\n\\text{precision} = \\dfrac{ \\mid {\\text{relevant elements}} \\cap {\\text{retrieved elements}} \\mid }{ \\mid {\\text{retrieved elements}} \\mid }\n\\end{equation}\n\n\nAnd the recall is the fraction of the relevant elements that are successfully retrieved:\n\n\n\\begin{equation}\n\\text{precision} = \\dfrac{ \\mid {\\text{relevant elements}} \\cap {\\text{retrieved elements}} \\mid }{ \\mid {\\text{relevant elements}} \\mid }\n\\end{equation}\n\n\nIn the classification tasks, considers four terms true positives (TP), true negatives (TN), false positives (FP), and false negatives (FN). Precision and recall are defined as \\citep{olson2008advanced}:\n\n\n\\begin{equation}\n\\text{precision} = \\dfrac{ TP }{ TP + FP }\n\\end{equation}\n\n\n\\begin{equation}\n\\text{recall} = \\dfrac{ TP }{ TP + FN }\n\\end{equation}\n\n\n\\subsection*{Receiver operating characteristic (ROC)}\n\nA receiver operating characteristic curve is a graphical plot which is created by plotting the true positive rate (TPR) against the false positive rate (FPR) at various threshold settings. ROC analysis provides tools to select a possible optimal threshold for models, an example ROC curve plot of three predictors of peptide cleaving in the proteasome is shown in figure \\ref{img:roc_curve}.\n\n\\begin{figure}\n\\includegraphics[scale=2.5]{Images/Roccurves.png}\n\\centering\n\\caption{ROC curve of three predictors of peptide cleaving in the proteasome \\citep{wiki2018roc}}\n\\label{img:roc_curve}\n\\end{figure}\n\n\n\\subsection*{Area under the ROC curve (AUC)}\n\nWe cannot compare classifiers base on the ROC because the ROC curve is just a graphical plot. In order to represent ROC performance as a single scala, a common method is to calculate the area under the ROC curve (AUC for short). Because the AUC is a size of the area of the unit square, therefore the AUC value will always be between 0 and 1. However, random guessing produces an area of 0.5, no realistic classifier should have an AUC less than 0.5 then it makes the baseline performance for all classifiers is 0.5. In summary, the AUC metric is a measure of how much the ROC curve is close to the point of perfect classification.\n\nThe AUC metric usually used in machine learning community for model comparison \\citep{hanley1983method}. However, in practice researchers recently noticed that AUC was quite noisy as a classification measure \\citep{hanczar2010small} and some other studies have other significant problems in model comparison \\citep{lobo2008auc, hand2009measuring}.\n\n\\subsection*{F-score}\n\n$F_1$ score (also F-score or F-measure) is a measure that considers both precision and recall by taking a harmonic average of these metrics.\n\n\n\\begin{equation}\nF_1 = 2 \\cdot \\dfrac{ \\text{precision} \\cdot \\text{recall} }{ \\text{precision} + \\text{recall} }\n\\end{equation}\n\n\nA general formula of F-score for any positive real $\\beta$ is:\n\n\n\\begin{equation}\nF_\\beta = (1 + \\beta^2) \\cdot \\dfrac{ \\text{precision} \\cdot \\text{recall} }{ (\\beta^2 \\cdot \\text{precision}) + \\text{recall} }\n\\end{equation}\n\n\nVan Rijsbergen et al. \\citep{van1979information} interpret $F_\\beta$ that \"measures the effectiveness of retrieval with respect to a user who attaches $\\beta$ times as much importance to recall as precision\". In practice, the F-score metric is often used in machine learning when the dataset is imbalanced because it isn't affected by the imbalance problem.", "meta": {"hexsha": "772ec5a8336cdc5d95eb472a3c75ab1ff5bc3aac", "size": 15624, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapter2/chapter2.tex", "max_stars_repo_name": "88d52bdba0366127fffca9dfa93895/thesis-master", "max_stars_repo_head_hexsha": "218b3b6a1a6dc02b19b360b5bf903612d34dd0d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-04T04:14:28.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-04T04:14:28.000Z", "max_issues_repo_path": "Chapter2/chapter2.tex", "max_issues_repo_name": "88d52bdba0366127fffca9dfa93895/thesis-master", "max_issues_repo_head_hexsha": "218b3b6a1a6dc02b19b360b5bf903612d34dd0d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter2/chapter2.tex", "max_forks_repo_name": "88d52bdba0366127fffca9dfa93895/thesis-master", "max_forks_repo_head_hexsha": "218b3b6a1a6dc02b19b360b5bf903612d34dd0d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 64.8298755187, "max_line_length": 1019, "alphanum_fraction": 0.7701612903, "num_tokens": 3728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3006743513994525}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n% \\marginpar{Friday\\\\ 2019-11-15, \\\\ compiled \\\\ \\today}\n% \\section*{Fri Nov 15 2019}\n\n% We start again from where we left off, with hydrogen recombination.\n\n% We want to estimate the moment at which hydrogen first formed, which marks the point at which electrons and photons interact efficently: before, they interacted with Compton scattering which is very efficient; after they interact with hydrogen atoms in a way that is very inefficient.\n\n% After this, then, we say that photons and matter are \\emph{decoupled}.\n\n% The scattering cross section (for Compton?) goes like the inverse square of the mass.\n\n% This means that the universe is not only \\emph{globally},  but also \\emph{locally} neutral.\n\n% This decoupling is what allows for star formation.\n% Also, this is when the CMB starts.\n% It is made of microwaves now, but it was higher earlier.\n\n% The phase space distribution of photons is scale-invariant since they have zero mass: so we can say that the photons' distribution \\emph{looks} thermal, but it is actually not technically since there are no interactions anymore.\n\n% However the photons travel freely and are perceived as thermal, and they give an almost perfect blackbody! The errorbars in a plot for it must be magnified by \\num{e4} in order to be seen.\n\n% Neutrality implies \\(n_e = n_p\\).\nLet us now introduce the total baryon density, \\(n_b\\).\nIn principle, we should account for Helium: as we will see, a couple of minutes after the Big Bang He-4 nuclei started to form, but they made up only something like \\(25\\%\\) of the mass, which means \\(6\\%\\) of the number density: so we ignore them and say that the number density of baryons is \n%\n\\begin{align}\n  n_b = n_p + n_H\n\\,.\n\\end{align}\n\n% Our ansatz for the Boltzmann equation is \\(\\mu_e + \\mu _p = \\mu _H\\) since photons have no chemical potential.\n\n% \\(i\\) denotes a generic one in \\(e\\), \\(p\\) and \\(H\\).\n% Then \n% %\n% \\begin{align}\n%   n_i = g_i\\qty(\\frac{m_i T}{2 \\pi })^{3/2} \\exp(\\frac{\\mu _i - m_i}{T})\n% \\,,\n% \\end{align}\n% %\n% we need to account for the chemical potential since it is the driver of this process.\nThe quantity we want to describe is how much hydrogen is still ionized: this is given by the ratio of the free electrons to the total baryons, \\(n_e / n_b\\). This is called the \\textbf{ionization fraction} \\(X_e\\), and is also equal to \\(n_p / n_b\\) since the universe must be locally neutral. \n\nWe expect to have \\(X_e = 1\\) in the early universe, and \\(X_e = 0\\) after the end of reionization.\n\nThis is a good model to keep in mind although it is not precisely correct, since simulations show that there will be some \\emph{residual ionization}: \\(X_e\\) only goes to around \\(\\num{e-4} \\divisionsymbol \\num{e-5}\\) at the end of reionization.\nAlso, in the modern universe a large fraction of the hydrogen has become ionized again, especially in the intergalactic medium; this is likely due to the energy injected into it by structure formation, which definitely breaks the approximation of global thermal and chemical equilibrium. \nThis is not a concern for us: here, we only wish to describe the processes in the interval \\(1000 \\lesssim z \\lesssim 2000\\). \n \n%  naively we'd expect it to get to 0, but actually there remains some residual ionization, some free protons and electrons.\n% How much is \\(n_e / n_b\\)? the same as \\(n_p / n_b\\). We call this quantity \\(X_e\\), the ionization number.\n% A proper calculation would account for the non-equilibrium contributions.\n% However, we estimate the process as being in equilibrium: this will underestimate the number of electrons.\n\n% Today, most of the hydrogen is ionized (there is a ***-Peterson effect which shows this): this means that matter and radiation interact again.\n\n% This is the second important time in the history of the universe.\n\n% Can we see the early stars? Not really, we see galaxies only up to \\(z \\sim 10\\), these stars would be at something like \\(z \\sim 30\\)\\dots\n% There might be more to this.\n\n% Inserting this and the Saha equation we get\n% So the number density of hydrogen atoms is given by: \n%\n% \\begin{align}\n%   n_H = g_H \\qty(\\frac{m_H T}{2 \\pi })^{3/2} \\exp(\\frac{\\mu_p - \\mu_e - m_p - m_e + B}{T})\n% \\,,\n% \\end{align}\n%\n% and we can simplify things since \\(m_p, m_H \\gg m_e, B\\), and substitute in the number densities for electrons and protons.\nThe binding energy of the hydrogen is \\(B=m_p+m_e-m_H=\\SI{13.6}{eV}\\), so instead of \\(m_H\\) we can write \\(m_H = m_p+m_e-B\\).\nLet us insert this expression and the Saha equation in the expression for the hydrogen number density; then we will recognize part of the expressions for the proton and electron number densities, which we can \n%\n\\begin{subequations}\n\\begin{align}\n  n_H &=  g_H \\qty(\\frac{m_H T}{2 \\pi })^{3/2} \\exp(\\frac{\\mu _H - m_H}{T})  \\\\\n  &= g_H \\qty(\\frac{m_H T}{2 \\pi })^{3/2} \\exp(\\frac{\\mu_e + \\mu _p - m_e - m_p + B}{T}) \\\\\n  &= \\underbrace{\\frac{g_H}{g_e g_p}}_{= 1} \\cancelto{}{\\qty(\\frac{m_H T}{2 \\pi })^{3/2}}\n  \\qty(\\frac{m_e T}{2 \\pi })^{-3/2}\n  \\cancelto{}{\\qty(\\frac{m_p T}{2 \\pi })^{-3/2}}\n  n_e n_p\n  \\exp(\\frac{B}{T}) \\\\\n  \\frac{n_H}{n_e n_p} &=  \\qty(\\frac{m_e T}{2 \\pi })^{-3/2} \\exp(\\frac{B}{T})  \\\\\n  \\frac{n_b - n_p}{n_p^2} &= \\qty(\\frac{m_e T}{2 \\pi })^{-3/2} \\exp(\\frac{B}{T}) \n\\,,\n\\end{align}\n\\end{subequations}\n%\nwhich we can manipulate, using the following identity: \n%\n\\begin{align}\n  \\frac{n_b - n_p}{n_p^2} = \\frac{n_b \\qty(1 - n_p/ n_b)}{n_b^2 X_e^2} = \\frac{1}{n_b} \\frac{1 - X_e}{X_e^2}\n\\,,\n\\end{align}\n%\nwhere we use \\(n_e = n_p\\) and the definition of \\(X_e = n_p / n_b\\). Then, we bring the \\(n_b\\) to the other side of the equation and multiply and divide by the photon number density, which is given by\n%\n\\begin{align} \\label{eq:n-gamma}\n  n_{\\gamma } = \\frac{2 \\zeta (3) T^3}{\\pi^2}\n\\,.\n\\end{align}\n\nWith this, we can insert the baryon fraction \\(\\eta_b\\) (which is conserved, so we can use its current value):\n%\n\\begin{subequations}\n\\begin{align}\n  \\frac{1- X_e}{X_e^2} &= \\underbrace{\\frac{n_b}{n_\\gamma }}_{\\eta_p} \n  n_\\gamma\n  \\qty(\\frac{m_e T}{2 \\pi })^{-3/2} \\exp(\\frac{B}{T})   \\\\\n  &= \\eta_0 \\frac{2 \\zeta (3)T^3}{\\pi^2} \\qty(\\frac{m_e T}{2 \\pi })^{-3/2} \\exp(\\frac{B}{T})   \\\\\n  &= \\eta_0  \\frac{4 \\sqrt{2} \\zeta (3)}{\\sqrt{\\pi }} \\qty(\\frac{T}{m_e})^{3/2} \\exp(\\frac{B}{T}) \\label{eq:saha-equation-ionization}\n\\,,\n\\end{align}\n\\end{subequations}\n%\nwhich we can solve numerically to find \\(X_e\\) as a function of temperature, or of redshift. The results are shown in figure \\ref{fig:ionization}. \n\n\\begin{figure}[ht]\n\\centering\n\\includegraphics[width=\\textwidth]{figures/ionization}\n\\caption{Ionization fraction as a function of redshift: a numerical solution of equation \\eqref{eq:saha-equation-ionization}.}\n\\label{fig:ionization}\n\\end{figure}\n\nLet us try to understand what is going on. Roughly speaking, we get intermediate values for \\(X_e\\), like \\(\\num{.5}\\), when the right-hand side is of order 1.\nIf the right-hand side only contained the terms \\((T/m_e)^{3/2}\\exp(B/T)\\) without any multiplicative factor in front (meaning, roughly, that we had \\(\\eta_0 \\sim 1\\)), then we would see recombination starting to occur already at \\(z \\sim 4000\\) (\\(T \\sim \\SI{1}{eV}\\)), and by \\(z \\sim 2000\\) if would almost be over.\nThe reason this does not happen is that \\(\\eta_0 \\) is \\emph{very small}: there are a lot of photons, many more than the baryons, which are ready to dissociate any atoms which start to form.\n\nSo, hydrogen is truly formed only when \\(T \\sim \\SI{0.3}{eV}\\), much lower than its ionization energy.\n\n\\todo[inline]{But even with \\(\\eta_0 \\sim 1\\) we get formation at \\(T \\sim \\SI{1}{eV}\\), an order of magnitude less than \\(B\\)! is there an intuitive argument as to why this is the case?}\n\nThe estimates we gave do depend on the value we assign to \\(\\Omega_{0b}\\) and \\(h\\), however within the currently accepted experimental ranges the main predictions do not vary substantially. \n\n% Approximately, it occurred somewhere around \\(z \\sim 1100\\) (we conventionally say that recombination happened when \\(X_e = 0.1\\)).\nThe process of recombination is gradual, but we can choose a conventional redshift as, for example, the time when we reach an arbitrary threshold like \\(X_e = \\num{.1}\\). \n\nThe interaction rate between photons and free electrons is \\(\\Gamma_{\\gamma } = n_e \\sigma_T c\\), where \\(\\sigma _T\\) is the Thompson cross section while \\(n_e\\) is the number density of free electrons, which can be estimated as \\(n_e = n_b X_e \\approx \\rho_C \\Omega_{b} X_e / m_p\\). \n% After recombination, we have the \\emph{last scattering}: the moment at which the CMB was formed.\nThen, we can estimate the moment of the last scattering by checking the decoupling condition: \\(\\Gamma _\\gamma < H\\). \nWith the numbers given earlier, we find \\(z \\sim 1120\\): a very good approximation to the currently accepted value \\(z \\sim 1089\\)!\n\n% One Nobel prize this year was awarded to Jim Peebles, a friend of Sabino's: together with his PhD supervisor Dicke, he was the first to calculate this stuff.\n\n% Peebles in 1964 (?) did this calculation both in GR and in Brahms-Dicke theory, a modified gravity theory.\n\n\\todo[inline]{Then Pacciani has an argument as to why \\(T \\sim a^{-2}\\) for matter, should this be included here? It basically comes from entropy conservation \\(\\dd{E} = - P \\dd{V}\\), the ideal gas law \\(P = n_b k_B T\\) and the equipartition theorem \\(E = \\frac{3}{2} n_b a^3 k_B T\\).}\n\n\\section{Primordial nucleosynthesis}\n\nAlready in the 1940s it was noticed by Alpher, Bethe as well as Gamow that the abundances of certain nuclides could not be explained if they were formed in stellar interiors alone. \nSpecifically, the issue is with the abundances of light elements: deuterium \\(\\ce{^{2}H}\\), as well as \\(\\ce{^{3}He}\\) and \\(\\ce{^{4}He}\\), while heavier nuclides (with mass number \\(A \\geq 7\\)) could not form in the early universe \\cite[sec.\\ 8.6.1]{colespCosmology2002}.\\footnote{Environments which allow their production (stellar interiors) have lower temperature but a higher density, since the main obstruction to their production is the absence of stable nuclides at \\(A = 5\\) and \\(A= 8\\) --- the environment needs to raise the odds of an unstable \\ce{^{8}Be} nuclide colliding with an \\(\\alpha \\) particle to form carbon before it decays.}\n\nThe most abundant of these light nuclides by far is \\ce{^{4}He}, whose mass fraction is denoted as \\(Y \\approx \\SI{25}{\\percent}\\), while its number fraction is approximately \\SI{6}{\\percent}. Our model will need to yield this many helium-4 nuclides after primordial nucleosynthesis. \n\nA mechanism for the synthesis of these light nuclides in the early universe is needed. \n% Let us describe the early universe, before the first nucleosynthesis.\n% Important papers in this topic are by G. Gamow, and by Alpher, Bethe and Gamow.\n\nWe shall model this mechanism, under the following assumptions (which are, as far as we know, roughly verified):\n%\n\\begin{enumerate}\n    \\item the universe passed through a very high temperature phase, with \\(T > \\SI{e12}{K}\\), during which thermal equilibrium held;\n    \\item the universe at this stage is described by General Relativity and the Standard Model of particle physics, and it is homogeneous and isotropic;\n    \\item the chemical potentials for the neutrinos \\(\\mu_{\\nu }\\) have certain upper bounds, such that the number of neutrino types is approximately 3; \n    \\item there is no matter-antimatter separation (as in, antimatter ``bubbles'');\n    \\item there are no strong magnetic fields;\n    \\item the number of exotic particles has a certain upper bound (it is small compared to the number of photons).\n\\end{enumerate}\n\n% There are magnetic fields in the universe, but they are not homogeneous and relatively weak.\n% Exotic particles are predicted by certain unification theories, they are generically defined as ones which we have not observed yet.\n\n% We have to explain the fact that we observe an excess of He-4 in the early universe: we define the yield \n%\n% \\begin{align}\n%   y \\equiv \\frac{m_{\\ce{He-4}}}{m_b} > \\num{.25}\n% \\,.\n% \\end{align}\n\n% In terms of particle number, the ratio is more like \\num{.06}. \n% We do not produce Carbon or anything higher than it: the process which forms it is inefficient at high temperature, low density like the early universe.\n% Higher \\(Z\\) elements are only produced in stars.\n\n% Helium-4 is produced but also destroyed by stars.\n\nThe main formation channels in the early universe are: \n%\n\\begin{enumerate}\n    \\item \\(n+p \\leftrightarrow d + \\gamma \\) (\\(d= \\ce{^{2}H}\\) denotes deuterium);\n    \\item \\(d + d \\leftrightarrow \\ce{^{3}He} + n\\);\n    \\item \\(\\ce{^{3}He} + d \\leftrightarrow \\ce{^{4}He} + p\\).\n\\end{enumerate}\n\nNote that these processes, unlike the stellar ones, do not involve the weak interaction: neutrons and protons do not turn into each other.\nIn stars, there are no free neutrons so this process is not possible.\n\nThe slowest process of the three is the first, since it is heavily affected by photons, which destroy deuterium.\nAfter we have produced deuterium, Helium-4 is readily produced.\n% We cannot treat this properly, we only give a story.\n\n% The binding energy of deuterium is around \\SI{2.2}{MeV}.\n\nIn order to find out how much deuterium we have, we need the proton-to-neutron ratio. \nWe are working at energies of around \\SI{1}{MeV}, so protons and neutrons are not relativistic anymore; \\emph{as long as they are in equilibrium} through weak processes both will obey Boltzmann statistics, so for \\(i = n, p\\): \n% his process takes place around three minutes after the beginning.\n%\n\\begin{align}\n  n_i = g_{i} \\qty(\\frac{m_i T}{2 \\pi })^{3/2} \\exp(\\frac{\\mu_i - m_i}{T})\n\\,,\n\\end{align}\n%\nmeaning that their number ratio is given by\\footnote{We are neglecting the chemical potentials since, as explained by \\textcite[sec.\\ 8.6.2]{colespCosmology2002}, as long as both weak and electromagnetic interactions are in chemical equilibrium the chemical potentials are forced to be zero by all the balance equations.}\n\\todo[inline]{The explanation in \\cite[]{colespCosmology2002} is not the same as the one given by \\textcite[]{paccianiAppuntiCorsoPhysical2018}\\dots I'm inclined to trust the former.}\n%\n\\begin{align}\n  \\frac{n_n}{n_p} \\sim \\exp(-\\frac{m_n - m_p}{T})\n\\,,\n\\end{align}\n%\nwhere \\(m_n - m_p \\approx \\SI{1.3}{MeV} \\approx \\SI{1.5e10}{K}\\).\n\nThe proton is the lightest baryon and is therefore stable; while the neutron is unstable: it can decay through the weak-interaction processes \n\\begin{enumerate}\n    \\item \\(n + \\nu _e \\leftrightarrow p + e^{-}\\);\n    \\item \\(n + e^{+} \\leftrightarrow p + \\overline{\\nu _e} \\);\n    \\item \\(n \\rightarrow p + e^{-} + \\overline{\\nu _e} \\).\n\\end{enumerate}\n\nThe neutron fraction keeps decreasing as \\(T\\) decreases and these processes keep happening, however as we have previously discussed at around \\(T_{d \\nu } \\sim \\SI{1}{MeV}\\) neutrinos decouple, at which point the first two back-and-forth reactions stop, and we are left with \\(n_n / n_p \\approx \\exp(- \\Delta m / T_{d \\nu }) \\approx \\num{.27}\\). \n% We can replace the temperature in the exponential by \\(T \\rightarrow T_{d_\\nu }\\), the decoupling temperature of the neutrinos, since that is the moment around which this happpens.\n\nWe define the number fraction of neutrons, which is approximately\n%\n\\begin{align}\n  X_n (t) \\equiv \\frac{n_n}{n_n+n_p} \\approx \\num{.21}\n\\,.\n\\end{align}\n\nThe third reaction, which is \\(\\beta^{-} \\) decay, keeps occurring since it does not require the presence of neutrinos, so after the decoupling of neutrinos the number fraction decays exponentially as:\n%\n\\begin{align}\n  X_n(t) = X_n(t_{d_\\nu }) \\exp( - \\frac{t - t_{d_\\nu }}{\\tau _n})\n\\,,\n\\end{align}\n%\nwhere \\(\\tau _n = \\log 2 \\tau_{1/2}\\), and the half-life of neutrons is given by \\(\\tau_{1/2} \\approx \\SI{10.5+-0.2}{min}\\).\nSo, each minute neutrons stay unbound some of them are decaying; the process of deuterium formation however is rather fast as we shall see, so not many of them are lost.\n\nLet us then move to deuterium formation: its binding energy is around \\(B_d = m_p + m_n - m_d \\approx \\SI{2.2}{MeV}\\).\nWe proceed exactly like we did with hydrogen: since \\(\\mu _p + \\mu _n = \\mu _d\\), the deuterium number density can be expressed as \n%\n\\begin{align}\nn_d &= g_d \\qty(\\frac{m_d T}{2 \\pi })^{3/2}  \\exp(\\frac{\\mu _d - m_d}{T})  \\\\\n&= \\frac{g_d}{g_p g_n} n_n n_p \\qty(\\frac{m_d}{m_n m_p})^{3/2} \\qty(\\frac{T}{2 \\pi })^{-3/2} \\exp( \\frac{B_d}{T}) \n\\,,\n\\end{align}\n%\nwhich, dividing through by \\(n_b\\) and using \\(g_d = 3\\) (since deuterium has spin 1) and \\(g_p = g_n = 2\\), can be expressed as:\n%\n\\begin{subequations}\n\\begin{align}\n  X_d &= \\frac{3}{4} n_b X_n X_p \\qty(\\frac{m_d}{m_nm_p})^{3/2} \\qty(\\frac{T}{2 \\pi })^{-3/2} \\exp(\\frac{B_d}{T}) \\\\\n  &= \\frac{3}{4} \\eta_0 X_n X_p \\qty(\\frac{m_d}{m_nm_p})^{3/2}\n  \\frac{2 \\zeta (3)}{\\pi^2} (2 \\pi T)^{3/2}  \\exp(\\frac{B_d}{T})  \n  \\marginnote{Substituted \\(n_b = \\eta_0 n_\\gamma \\).}\\\\\n  &\\approx \\frac{3}{4} \\eta_0 X_n (1-X_n) \\qty(\\frac{m_d}{m_nm_p})^{3/2} \\frac{2}{\\pi^2} (2 \\pi T)^{3/2} \\zeta (3)  \\exp(\\frac{B_d}{T})\n  \\marginnote{Approximated \\(X_p + X_n \\approx 1\\), ignoring heavier nuclides.}\n\\,,\n\\end{align}\n\\end{subequations}\n% \\todo[inline]{Check calculation.}\n\\todo[inline]{Does approximating \\(X_p + X_n \\approx 1\\) not ignore deuterium as well? Or rather: by the definition given before \\(X_n + X_p = 1\\) is exact, and if we do normalize by \\(n_n + n_p + n_d +\\dots\\) we should specify\\dots}\n%\nwhich describes the \\emph{deuterium bottleneck}: similarly to hydrogen recombination, the presence of many photons for each nuclide keeps compound particles from forming for quite a long time, and this precludes the formation of Helium.\n\n\\end{document}", "meta": {"hexsha": "63db93b6978399210b4e4ff7a34d65a38030c311", "size": 17757, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ap_first_semester/astrophysics_cosmology/15nov.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "ap_first_semester/astrophysics_cosmology/15nov.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ap_first_semester/astrophysics_cosmology/15nov.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 63.4178571429, "max_line_length": 647, "alphanum_fraction": 0.7083403728, "num_tokens": 5306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3006743513994525}}
{"text": "%!TEX ROOT=sample-thesis.tex\n%!TEX PROGRAM=xelatex\n\n\\chapter{List of Symbols}\n\n{\\renewcommand{\\arraystretch}{2}\n\\begin{tabular}{@{} >{\\bfseries\\boldmath }l @{\\hspace{1em}--\\hspace{1em}} l@{}}\n\n$\\theta$ & temperature\\\\\n\n$G$ & Gravitational acceleration $= \\SI{9.81}{\\meter\\per\\second}$\n\n\\end{tabular}\n}", "meta": {"hexsha": "9d526629684cb3d74f6522b59696e361bb0ecffc", "size": 301, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "symbollist.tex", "max_stars_repo_name": "liantze/UMSThesis", "max_stars_repo_head_hexsha": "c66f6ac3d8f9768aa4cf1587acc4d52b28a76284", "max_stars_repo_licenses": ["LPPL-1.3c"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "symbollist.tex", "max_issues_repo_name": "liantze/UMSThesis", "max_issues_repo_head_hexsha": "c66f6ac3d8f9768aa4cf1587acc4d52b28a76284", "max_issues_repo_licenses": ["LPPL-1.3c"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "symbollist.tex", "max_forks_repo_name": "liantze/UMSThesis", "max_forks_repo_head_hexsha": "c66f6ac3d8f9768aa4cf1587acc4d52b28a76284", "max_forks_repo_licenses": ["LPPL-1.3c"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5, "max_line_length": 79, "alphanum_fraction": 0.6744186047, "num_tokens": 110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3006743513994524}}
{"text": "\\documentclass[12pt]{article}\n\n\\usepackage{fullpage}\n\\usepackage{/home/nick/Documents/analysis}\n\\usepackage{listings}\n\\usepackage{verbatim}\n\n\\begin{document}\n\\title{FrameLab\\\\\\small{Software for framelet-based numerical analysis}}\n\\author{Nick Henscheid\\\\\\small{ University of Arizona Program in Applied Mathematics}}\n\\date{\\today}\n\\maketitle\n\n\\paragraph{Goals}\nThe idea of this project is to develop a complete software suite for computational imaging via framelets.  The code will be sorted into the following general categories: \n\n\\begin{enumerate}\n\\item Framelet expansion code \n\\begin{itemize}\n\\item Fast single and multilevel decomposition and reconstruction for 1D through 3D\n\\item Signal sparsity analysis, best basis selection?\n\\item Computing framelet coefficients \n\\end{itemize}\n\\item Numerical optimization code \n\\begin{itemize}\n\\item $l_1$ compressed sensing via ADMM/AL/DAL \n\\item Comparison of different algorithms?\n\\item $l_0$ code \n\\end{itemize}\n\\item Utilities \n\\begin{itemize}\n\\item Graphics and figure creation \n\\item Shrinkage designer \n\\item PDEs for image processing\n\\item Forward/adjoint operators for imaging \n\\item Classical signal processing \n\\end{itemize}\n\\item Applications \n\\begin{itemize}\n\\item CT \n\\item MRI \n\\item SPECT \n\\item Segmentation \n\\item Registration? \n\\item Deblurring \n\\item Deconvolution \n\\item Integral equations?\n\\item Matrix factorization?\n\\item Matrix completion \n\\item BM3D\n\\end{itemize}\n\\end{enumerate}\n\n\n\\section{Implementation Details}\n\n\\paragraph{Programming languages and interfaces}\nTo do: \n\\begin{itemize}\n\\item GPU interface to python?  pycuda?  (e.g. python alternative to mex)\n\\end{itemize}\n\n\\paragraph{Data Types}\n\n\n\n\\section{Framelet Expansions}\nThe first task to create/modify functions to perform framelet decomposition and reconstruction \n\n\n\\section{Optimization Methods}\n%\\lstinputlisting[numbers=left,language=Matlab,frame=single,caption={}Matlab function to solve the analysis-based sparse recovery problem via Augmented Lagrangian.]{../optimization/ALsolve.m}\n\n\n\\section{Imaging Systems}  \n\\subsection{2D Computed Tomography}\n\n\n\\subsection{3D Computed Tomography}\n\n \n\\section{Test Scripts}\n\\begin{enumerate}\n\\item testAdjoint.m\n\\item testBall.m\n\\item testCBCTCGLS.m \n\\item testCBCTInterp.m\n\\item testCBCTInterpAugmented.m\n\\item testCGLSClass.m\n\\item testConeBeamScanner.m\n\\item \n\\end{enumerate}\n\n\n\n\\end{document}", "meta": {"hexsha": "94694a474ad5a9f6c617cfcd63a7a079e6660958", "size": 2381, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/users.tex", "max_stars_repo_name": "nhenscheid/FrameLab", "max_stars_repo_head_hexsha": "dcc96cb950d15d9d4c40e4d2c451d5c9ff737ad8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/users.tex", "max_issues_repo_name": "nhenscheid/FrameLab", "max_issues_repo_head_hexsha": "dcc96cb950d15d9d4c40e4d2c451d5c9ff737ad8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/users.tex", "max_forks_repo_name": "nhenscheid/FrameLab", "max_forks_repo_head_hexsha": "dcc96cb950d15d9d4c40e4d2c451d5c9ff737ad8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-23T07:14:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-23T07:14:02.000Z", "avg_line_length": 24.8020833333, "max_line_length": 191, "alphanum_fraction": 0.7925241495, "num_tokens": 624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3006743436218155}}
{"text": "\\chapter{Inference of Guarded Recursion}\n\\todo{Should we mention somewhere that we don't plan on running these? And can\n  we even do that? What about evaluation in types?}\n\\label{cha:infer-guard-recurs}\nAs mentioned in Section~\\ref{sec:less-restr-prod}, we wish to extend Idris with\na less restrictive productivity checker using guarded recursion. However, as\nwe saw in Section~\\ref{sec:guarded-recursion}, defining guarded recursive\nprograms can be quite tedious and requires the user to thoroughly understand guarded\nrecursion in order to write provably productive programs. In this chapter, we propose a system\nwhere we can check the productivity of programs using guarded recursion with\nonly a minimal amount of user involvement. The main focus will be\nimplementation, showing how we have put theory into practice.\n\\section{Intuition}\n%##########\n% Type-directed (undersøg præcis hvad dette betyder) \n% Overgang fra teori til Idris - Hvilke praktiske hensyn tages der?\n% Fix-punktet - hvordan forstås det?\n% Kun eet ur!\n% Kausale og ikke-kausale funktioner\n%% Problemet bag: hvorfor er vi nødt til at skelne?\n% Eksempel på inferens\n%##########\nOur system is divided into two parts: (1) An inference system that builds a\nguarded recursive term from a user written term, and (2) an algorithm that\nchecks the structure of a term and its type according to the rules from \nFigure~\\ref{fig:guarded_recursion_rules_clocks}. While the general idea is that\nthese two parts work together, such that the inference system first builds a term\nfor the checking algorithm to check, it is our goal that these two should work\nas disjoint modules. This is important as we want our checking algorithm to be a\ngeneral-purpose guarded recursion checker, not just an algorithm for checking\nthe output of the inference system.\n\nFurthermore, it is important to note that our system is an extension of\nIdris. This means that we do not add or change any core elements of the language, and\ntherefore do not jeopardise or tamper with the correctness of the Idris type system.\n\n\\subsection{Practical Considerations}\nWhen realising a theoretical model such as guarded recursion in an existing\nsystem, there are practical considerations to be taken. Because of the way Idris\nis implemented, how we construe the theory might not be immediately obvious. In\nthe following we will lay out these practical considerations, and how they\nrelate to the theory.\n\n\\paragraph{Target}\nAs discussed in Chapter~\\ref{cha:idris}, an Idris program is represented in\nmultiple different ways throughout compilation. The time and representation on\nwhich to perform our analysis has great impact on how a solution\nunfolds.\n\nDiscarding the representations obviously not useful for this analysis (namely\nconcrete Idris, IBC, and binaries), we are left with two options: \\IdrisM and\nTT. As guarded recursion is a typing discipline our system needs access to\nthe types of any term, and since \\IdrisM does not contain all type information\nour analysis is performed on the core language, TT.\n\n\\paragraph{Parameters}\nIn Section~\\ref{sec:guarded-recursion} we discussed and used a guarded fixpoint\noperator. Due to the type of this operator, ($(\\later A \\rightarrow A)\n\\rightarrow A$), the recursive reference will always have a $\\later$-type. This\nmeans that any application of a recursive reference to an argument must be done\nusing $\\tensor ^{\\kappa}$\\todo{This operator must be given a human-readable name}.\n\nIdris, like many other languages, have named parameters which influence the type\nof a function. Looking at the rule for $\\tensor ^{\\kappa}$ in\nFigure~\\ref{fig:guarded_recursion_rules} we see that it does not take any type\nsubstitution into account unlike the rules for regular application in Idris from\nFigure~\\ref{fig:TT_typing_rules}. This means that we cannot use $\\tensor ^{\\kappa}$ for\nparameter application. To better understand this, consider the following example.\n\n\\begin{figure}[h]\n  \\begin{lstlisting}[mathescape]\nrepeat : $\\forall \\kappa$ ((a : Type) $\\rightarrow$ a $\\rightarrow$ Stream$^{\\kappa}$ a)\nrepeat = $\\Lambda\\kappa.$ fix$^{\\kappa}$($\\lambda{}$rec$.\\lambda{}$a$.\\lambda{}$n$.$ \n             StreamCons a n ((rec $\\tensor ^{\\kappa}$ (Next$^{\\kappa}$ a)) $\\tensor ^{\\kappa}$ (Next$^{\\kappa}$ n)))\n\\end{lstlisting}\n  \\caption{An infinite stream of the same element.}\n  \\label{fig:repeat_guarded_example}\n\\end{figure}\n\nIn Figure~\\ref{fig:repeat_guarded_example} an infinite stream \\texttt{repeat} is\ndefined. It simply just repeats the same element infinitely. Note that even\nthough this problem also applies to implicit arguments, all arguments in the\nexample are explicit for simplicity. This means that \\texttt{StreamCons} has\ntype \\texttt{(a : Type) $\\rightarrow$ a $\\rightarrow$ $\\later^{\\kappa}$ Stream$^{\\kappa}$ a $\\rightarrow$ Stream$^{\\kappa}$ a}.\n\nWhen checking if this implementation conforms to the guarded rules we have to\ncheck that \\texttt{(rec $\\tensor ^{\\kappa}$ (Next$^{\\kappa}$ a)) $\\tensor ^{\\kappa}$ (Next$^{\\kappa}$ n)} has type\n\\texttt{$\\later ^{\\kappa}$Stream$^{\\kappa}$a} we run into trouble. In order for this to hold,\naccording to the $\\tensor ^{\\kappa}$ rule, \\texttt{rec $\\tensor ^{\\kappa}$ (Next$^{\\kappa}$ a)} must have\ntype \\texttt{$\\later^{\\kappa}$(a $\\rightarrow$ Stream$^{\\kappa}$ a)}. As shown in\nFigure~\\ref{fig:repeat_typing} we cannot show this as \\texttt{rec} has a\ndifferent type in our environment to what we are trying to show.\n\n\\begin{figure}[h]\n\\[\n\\frac { \\begin{matrix} \\inference { \\frac { ? }{ \\Gamma '\\, \\vdash \\, rec\\, :\\, \\later\n        ^{\\kappa}(Type\\, \\rightarrow \\, a\\, \\rightarrow \\, Stream^{\\kappa}\\, a) } \\, \n      \\frac {\n        \\frac {  }{ \\Gamma '\\, \\vdash \\, a\\, :\\, Type } \n      }\n      { \\Gamma '\\, \\vdash \\,\n        Next^{\\kappa}\\, a\\, :\\, \\later ^{\\kappa}\\, Type }\n    }{ \\, \\Gamma '\\, \\vdash \\, rec\\,\n      \\tensor ^{\\kappa} \\, (Next^{\\kappa}\\, a)\\, :\\, \\later ^{\\kappa}(a\\, \\rightarrow \\, Stream^{\\kappa}\\,\n      a)\\ }  & \\inference { \\inference {  }{ \\Gamma '\\, \\vdash \\, n\\, :\\, a }  }{\n      \\Gamma '\\, \\vdash \\, Next^{\\kappa}\\, n\\, :\\, \\later ^{\\kappa} \\, a }  \\end{matrix} }{\n  \\Gamma '\\, \\vdash \\, (rec\\, \\tensor ^{\\kappa} \\, (Next^{\\kappa}\\, a))\\, \\tensor ^{\\kappa} \\,\n  (Next^{\\kappa}\\, n))\\, :\\, \\later ^{\\kappa} Stream^{\\kappa}\\, a }\n\\]\n\\[\n\\Gamma '\\, =\\, \\Gamma ,\\, rec\\, :\\, \\later ^{\\kappa}((a\\, :\\, Type)\\, \\rightarrow \\,\na\\, \\rightarrow \\, Stream^{\\kappa}\\, a),\\, a\\, :\\, Type,\\, n\\, :\\, a\n\\]\n  \\caption{Part of an attempt to type repeat.}\n  \\label{fig:repeat_typing}\n\\end{figure}\n\nOne way of solving this could be to have the $\\tensor ^{\\kappa}$-rule take substitution in\ntypes into account as seen in Figure~\\ref{fig:tensor_with_subst}. This, however,\nis not yet backed by the theory, and is therefore not an option.\n\n\\begin{figure}[h]\n\\[\n\\inference { \\Gamma \\, \\vdash \\, t\\, :\\, \\later^{\\kappa} ((a\\, :\\, A)\\,\n  \\rightarrow \\, B)\\quad \\Gamma \\, \\vdash \\, u\\, :\\, \\later^{\\kappa} A }{\n  \\Gamma \\, \\vdash \\, t\\, \\tensor ^{\\kappa} \\, u\\, :\\, \\later^{\\kappa} B[{ u\n  }/{ a }] } \n\\]\n  \\caption{Tensor with substitution in types.}\n  \\label{fig:tensor_with_subst}\n\\end{figure}\n\nInstead we change what is fixed by the fixpoint. We pull any parameter out,\nchanging the fixed type, such that \\texttt{rec} now has type \\texttt{$\\later\n  ^{\\kappa}$(a $\\rightarrow$ Stream$^{\\kappa}$ a)}. This gives us the definition seen in\nFigure~\\ref{fig:repeat_guarded_example_new}. Here the \\texttt{a} is fixed and\nnot part of the recursive reference. This allows us to type part of\n\\texttt{repeat} as exemplified in Figure~\\ref{fig:repeat_typing_new}.\n\n\\begin{figure}[h]\n  \\begin{lstlisting}[mathescape]\nrepeat : (a : Type) $\\rightarrow$ $\\forall \\kappa$ (a $\\rightarrow$ Stream$^{\\kappa}$ a)\nrepeat a = $\\Lambda \\kappa$ fix$^{\\kappa}$($\\lambda{}$rec$.\\lambda{}$n$.$ \n             StreamCons a n (rec $\\tensor ^{\\kappa}$ (Next$^{\\kappa}$$^{\\kappa}$ n)))\n\\end{lstlisting}\n  \\caption{Repeat with the type parameter fixed.}\n  \\label{fig:repeat_guarded_example_new}\n\\end{figure}\n\n\\begin{figure}[h]\n\\[\n\\frac { \\frac {  }{ \\Gamma '\\, \\vdash \\, rec\\, :\\, \\later ^{\\kappa}(a\\, \\rightarrow\n    \\, Stream^{\\kappa}\\, a) } \\, \\frac { \\Gamma '\\, \\vdash \\, n\\, :\\, a }{ \\Gamma '\\,\n    \\vdash \\, Next^{\\kappa}\\, n\\, :\\, \\later ^{\\kappa}\\, a }  }{ \\, \\Gamma '\\, \\vdash \\, rec\\,\n  \\tensor ^{\\kappa} \\, (Next^{\\kappa}\\, n)\\, :\\, \\later ^{\\kappa}Stream^{\\kappa}\\, a }\n\\]\n\\[\n \\Gamma '\\, =\\, \\Gamma ,\\, rec\\, :\\, \\later ^{\\kappa}(a\\, \\rightarrow \\, Stream^{\\kappa}\\,\n a),\\, a\\, :\\, Type,\\, n\\, :\\, a\n\\]\n\n  \\caption{Part of typing repeat with fixed type parameter.}\n  \\label{fig:repeat_typing_new}\n\\end{figure}\n\n\\paragraph{Multiple clauses}\nAnother problem occurs when we consider functions with multiple clauses,\ne.g. functions defined with pattern matching. To understand the problem we must\nfirst step out of the guarded recursive world for a moment and consider the\nfunction \\texttt{cycle} in Figure~\\ref{fig:cycle_non_guarded}. Note that it is\nnot a guarded recursive definition, but a standard Idris definition.\n\n\\begin{figure}[h]\n  \\begin{lstlisting}[mathescape]\ncycle : Nat $\\rightarrow$ Nat $\\rightarrow$ Stream Nat\ncycle Z m = Z :: (cycle m m)\ncycle (S n) m = (S n) :: (cycle n m)\n\\end{lstlisting}\n  \\caption{A function cycle in standard Idris}\n  \\label{fig:cycle_non_guarded}\n\\end{figure}\n\nWhen transforming this to a guarded recursive form we want to make the fixed\npoint over both clauses. An intuitive way to get around this could be to\nconvert the pattern matching match into case-expressions. This is not possible\nas TT does not have case-expressions, only top-level pattern\nmatching. Furthermore, a case-expression based solution would make even less\nsense when we consider dependent pattern matching, since we by removing the\ndependent pattern match change the type of the left hand side.\n\nInstead, we can define cycle as two functions: One with the fixed point, and one\nwith the pattern match, as seen in Figure~\\ref{fig:cycle_guarded}. This way, all\nclauses of \\texttt{cycle} are part of the same fixpoint. The recursive reference\n\\texttt{ref} is handed to \\texttt{cycle} as a parameter. Note that this way of\nhandling the fixed point also works for functions with only one clause.\n\n\\begin{figure}[h]\n\\begin{lstlisting}[mathescape]\ncycle : $\\later ^{\\kappa}$ (Nat $\\rightarrow$ Nat $\\rightarrow$ Stream$^{\\kappa}$ Nat) $\\rightarrow$ \n             Nat $\\rightarrow$ Nat $\\rightarrow$ Stream$^{\\kappa}$ Nat\ncycle rec    Z  m = \n         StreamCons Z     (rec $\\tensor ^{\\kappa}$ (Next$^{\\kappa}$ m)) $\\tensor ^{\\kappa}$ (Next$^{\\kappa}$ m)\ncycle rec (S n) m = \n         StreamCons (S n) (rec $\\tensor ^{\\kappa}$ (Next$^{\\kappa}$ n)) $\\tensor ^{\\kappa}$ (Next$^{\\kappa}$ m)\n\ncycle$'$ : $\\forall \\kappa$ (Nat $\\rightarrow$ Nat $\\rightarrow$ Stream$^{\\kappa}$ Nat)\ncycle$'$ = $\\Lambda \\kappa$ fix$^{\\kappa}$($\\lambda$rec.$\\lambda$n.$\\lambda$m. cycle rec n m)\n\\end{lstlisting}\n  \\caption{A guarded definition of cycle}\n  \\label{fig:cycle_guarded}\n\\end{figure}\n\nAgain, this solution has short comings. We fix the recursive\nreference as \\texttt{ref} and thereby also fix its type. This works out fine in\nthe simply typed case, but once we consider higher-order and especially\ndependent types we run into problems. If we consider the function prepend from\nFigure~\\ref{fig:guarded_prepend}, the \\texttt{n} in the type of \\texttt{rec} is\nfixed, e.g. in the second clause to \\texttt{S n}. Since \\texttt{xs} has type\n\\texttt{Vect n a}, this term is not well-typed.\n\n\\begin{figure}[h]\n\\begin{lstlisting}[mathescape]\nprepend : (Later' (Vect n a -> Stream a -> Stream a)) -> Vect n a -> Stream a -> Stream a\nprepend rec [] s = s \nprepend rec (x :: xs) s = StreamCons x (compose {n=Now} (compose {n=Now} rec (Next xs)) (Next s))\n\nprepend' : Forall (Vect n a -> Stream a -> Stream a)\nprepend' = LambdaKappa (fix(\\rec, xs, s => prepend rec xs s))\n\\end{lstlisting}\n  \\caption{A function prepending a vector on a stream.}\n  \\label{fig:guarded_prepend}\n\\end{figure}\\todo{Prettify and verify figure}\n\nTo circumvent this we eliminate the \\texttt{fix} operator all together according\nto the elimination rules in Figure~\\ref{fig:fix_elim_rules}. By eliminating the\nfixpoint, we no longer fix the type of the recursive reference. Because of the\ntype of the guarded fixed point operator, the type of \\texttt{rec} is\n$\\later^{\\kappa}$A, which is also the type of \\texttt{Next f}.\n\n\\begin{figure}[h]\n  \\[\n\\frac { \\Delta ,\\, \\kappa ; \\, \\Gamma \\, \\vdash \\, f\\, =\\, { fix }^{ \\kappa  }(\\lambda\n  rec.\\, e)\\, :\\, A }{ \\Delta ,\\, \\kappa \\, ; \\Gamma \\vdash \\, f\\, =\\, e[{ (Next^{ \\kappa\n    }\\, f) }/{ rec }]\\, :\\, A } fix_{E_1}\n\\]\n\n\\[\n\\frac { \\Delta \\, ; \\Gamma \\vdash \\, f\\, =\\, \\Lambda \\kappa .{ fix }^{ \\kappa  }(\\lambda\n  rec.\\, e)\\, :\\, \\forall \\kappa .A }{ \\Delta \\, ; \\Gamma \\vdash \\, f\\, =\\, \\Lambda\n  \\kappa .e[{ (Next^{ \\kappa  }\\, f[\\kappa ]) }/{ rec }]\\, :\\, \\forall \\kappa .A\n} fix_{E_2}\n\\]\n  \\caption{Rules for fix elimination}\n  \\label{fig:fix_elim_rules}\n\\end{figure}\n\n\\paragraph{Singleton Clock}\nTo simplify the implementation we have limited our system to only have one\nclock, rather than a clock environment. Either the clock is open, or the clock\nis closed. This changes the rules we discussed in\nSection~\\ref{sec:guarded-recursion}, as seen in\nFigure~\\ref{fig:gr_rules_sin_clock}\\todo{insert one clock rules}. Here\n$\\sqcup$ denotes the open clock, and $\\sqcap$ the closed. \\todo{Explain how we\n  came to these rules}\n\n\\begin{figure}[h]\n  \n  \\caption{Guarded Recursion rules with singleton clock.}\n  \\label{fig:gr_rules_sin_clock}\n\\end{figure}\n\nWhile deriving this rule set from the original one has not followed a specific\nmethodology, a general trend is:\n\n\\begin{itemize}\n\\item If a rule required a specific clock in the environment, it now requires an\n  open clock.\n\\item Side conditions talking about a specific clock being not being free in the\n  environment are transformed to that no free clocks are allowed in the\n  environment at all.\n\\end{itemize}\n\nNote that the $\\kappa$ has gone from a lot of the types and terms. This is\nbecause we no longer talk about specific clocks, but about the\nclock. I.e. $\\later$ is always on the same clock and as such there is no need to\nspecify which. Also note that the $\\kappa$ remains on some $\\forall \\kappa$ and\n$\\Lambda \\kappa$. While these still only mention the singleton clock, the\n$\\kappa$ is kept to disambiguate these from regular quantification and\nabstraction. \n\nThis change of course limits the set of programs for which we can infer guarded\nrecursion, and thereby ensure productivity. In Section~\\ref{cha:evaluation} we\ndiscuss how this limitation affects our system.\n\n\\paragraph{Modality of Functions}\nIn general, when defining a guarded recursive function, one has to consider how\nto quantify over clocks. For example, in the definition of \\texttt{repeat} from\nFigure~\\ref{fig:repeat_guarded_example_new} the clock quantification is on the\nentire type, where as in the definition of \\texttt{evens} from\nFigure~\\ref{fig:guarded_recursion_evens}, the clock quantification is on each\nindividual \\texttt{Stream}. As there we increase the number of arguments we also\nincrease the number of different way we could quantify the function, making it\nincreasingly difficult to infer how to place them.\n\nBecause of this we have simplified to the problem. A function is either\n\\emph{causal} or \\emph{not causal}. We call this the \\emph{modality} of a\nfunction. If a function is causal it means that the quantification is on the\nentire type. In this sense \\texttt{repeat} is said to be causal. If a function\nis not causal the quantification is on each individual guarded type, meaning\nthat \\texttt{evens} is \\emph{not} causal.\n\nWhile inferring the modality of a function is indeed be possible, simply by\ntrial and error, there might exist not guarded function with both a causal and\nnot causal guarded implementation. In such a situation the system would have no\nway of knowing which modality to assign the function.\n\nInstead of attempting to infer the modality, we let the user assign a modality\nto a function. By doing this we ensure that the system does not infer a function\nwith the wrong modality.\\todo{Explain what this means for recursive ref}\n\n\\section{Implementation}\nIn this section we go over how we have realized the above intuition into an\nactual Idris implementation. We start by presenting the overall additions to the\nIdris compiler environment, and then how the inference and checker systems have\nbeen implemented.\n\n\\paragraph{Guarded Recursion Library}\nThe first step to adding guarded recursion to Idris is to add the guarded\nrecursive types and functions. We have added these to the Idris built-in\nlibrary, and not as a part of the prelude. This is because the user should be\nable to check functions for productivity using our guarded recursion checker\nwithout having to rely on the standard library.  While most of the\nimplementations are straight forward, and can be found in Appendix\\todo{Add ref\n  to appendix. And add appendix!}, there are interesting parts to discuss. We\nhave added the notion of \\emph{how much later} something is, through the idea of\n\\texttt{Availability}, seen in Figure~\\ref{fig:availability}. This is, in\nconjunction with \\texttt{Later} done so that we can many $\\later$ applications\nas a single \\texttt{Later} applications.\n\n\\begin{figure}[h]\n  \\begin{lstlisting}[mathescape]\ndata Availability = Now | Tomorrow Availability\n\ndata Later' : Type -> Type where\n  Next : {a : Type} -> a -> Later' a\n\nLater : Availability -> Type -> Type\nLater Now a = a\nLater (Tomorrow n) a = Later' (Later n a)\n\\end{lstlisting}\n  \\caption{Availability.}\n  \\label{fig:availability}\n\\end{figure}\n\n\\paragraph{Guarded Names}\nAs we want to infer new types and terms, and not override the existing ones, we\nneed a system for creating a guarded name from an existing user written\nname. While this is fairly trivial, it is an important part of our system. We\nwill hence forth refer to these as the \\emph{guarded names} as oppose to their\noriginal \\emph{Idris names}. We will mark these guarded names with a subscript\n$g$, such that a name $Name$ becomes $_gName$.\n\nDuring compilation we keep a map from Idris names to their guarded names. This\nmeans that we can for any Idris name find their guarded name, and vice\nversa. This comes in handy when we infer the guarded terms.\n\n\\paragraph{Clocked Types}\nThese are made by inferring a new data declaration for any codata or corecord\ndeclaration. This new data declaration is simply constructed during the\nelaboration of the original and then elaborated by itself. This means that for\nany user written codata or corecord declaration a guarded version is an\nintrinsic part of the program. \n\nA such guarded version of a declaration is fairly straight forward. Guarded\nnames are given to the type and to all constructors. Any recursive reference in\nthe type of the constructor is placed under a $\\later$-type, in a similar\nfashion to how Idris already handles lazy evaluation. The type constructor\nremains unchanged. An example of this inferences for a codata declaration can be\nseen in Figure~\\ref{fig:guarded_stream_inf}. Note that the inferred declaration\nis a data declaration, not codata. This is because we do not need both Idris's\nbuilt in laziness (\\texttt{Inf}), and the guarded recursion laziness ($\\later$)\n\\todo{Explain why these are not the same}.\n\n\\begin{figure}[h]\n\\begin{lstlisting}[mathescape]\ncodata Stream : Type -> Type where\n  MkStream : a -> Stream a -> Stream a\n\ndata $_g$Stream : Type -> Type where\n  $_g$MkStream : a -> $\\later_g$Stream a -> $_g$Stream a\n\\end{lstlisting}\n  \\caption{Inference of the guarded stream declaration.}\n  \\label{fig:guarded_stream_inf}\n\\end{figure}\n\nIn the corecord case, we take a similar approach. However, instead of\nconstructors we have to guard projections. Again, any recursive projection is\nguarded such that $A \\rightarrow A$ becomes $A \\rightarrow \\later A$, and all\nprojections are given a guarded name. Figure~\\ref{fig:guarded_tree_inf} shows an\nexample of such an inference.\n\n\\begin{figure}[h]\n\\begin{lstlisting}[mathescape]\ncorecord Tree a where\n  left : Tree a -> Tree a\n  value : Tree a -> a\n  right : Tree a -> Tree a\n\nrecord $_g$Tree a where\n  $_g$left : $_g$Tree a -> $\\later_g$Tree a\n  $_g$value : $_g$Tree a -> a\n  $_g$right : $_g$Tree a -> $\\later_g$Tree a\n\\end{lstlisting}\n  \\caption{Inference of the guarded tree declaration.}\n  \\label{fig:guarded_tree_inf}\n\\end{figure}\n\nFurthermore, for each projection we also generate what we call a \\emph{forall\n  projection}, henceforth denoted as $_\\forall Name$. We use this for\nprojections on quantified types. Consider a coinductive type $A$ with a\nprojection $p$ of type $A \\rightarrow A$, and a variable $x$ of type $\\forall\n\\kappa.A$. In order to perform $p$ on $x$ and maintain the quantification in the\ntype, we must first apply the clock to $x$, apply $_gp$, and then abstract over the\nclock again using $\\Lambda \\kappa$. This gives us:\n\n\\[\n\\Lambda \\kappa . _gp (apply\\,x) : \\forall \\kappa . \\later A\n\\]\n\nThe type of the above is isomorphic with $\\forall \\kappa . A$ according to the\nisomorphism described by Rasmus M\\o gelberg\\,\\cite{Mogelberg:2014} seen in\nFigure~\\ref{fig:quantified_later_iso}. As a short for all of this we simply use\n$_\\forall p$ which has type $\\forall A \\rightarrow \\forall A$, giving us the\nsame result. As such these \\emph{forall projections} do not add anything new,\nthey are just a simpler way for us to perform projections on terms of quantified\ntype. The intuition is that because of Figure~\\ref{fig:quantified_later_iso} we\ncan perform projections on quantified types without having to worrying about\ntheir lateness. Because they are quantified over clocks, they are always available.\n\n\\begin{figure}[h]\n\\[\n\\forall \\kappa .A\\cong \\forall \\kappa .\\rhd ^\\kappa A\n\\]\n  \\caption{A type isomorphism describe by Rasmus M\\o gelberg\\,\\cite{Mogelberg:2014}.}\n  \\label{fig:quantified_later_iso}\n\\end{figure}\n\n\\subsection{Inference}\n% Regler - forklar (også notation)\n% Rekursive referencer\n% Eksempel - zeros?\n% Preprocessing\n% Renaming\n% Forskel på causal og non causal\n\n%(1) Gennemgang af interessante regler\n%(2) Eksempel\n%(3) Implementation details, e.g. when Next and tensor rules clash\n%%(3.1) Preprocessing, herunder renaming\n%%(3.2) Forskel på causal og non causal\n\nInference of guarded recursive TT terms from elaborated TT terms happens by a\nbottom-up, type-directed derivation according to the rules given in Figure~\\ref{fig:epsilon_rules}\\todo{Behøver vi tjekke :Type præmisserne her?}. Let\n$c$ be the singleton clock, $\\Gamma$ be a typing environment, $\\rho$ be a tuple matching an Idris name $n$ to a\nguarded name $_gn$ (and for projections, a name for its forall-projection, $_{\\forall}n$) and $\\phi$ be a (possibly empty) collection of such tuples:\n\\begin{align*}\n   c,\\,c^\\prime &::=\\,\\sqcup\\,|\\,\\sqcap \\\\\n   \\rho &::= (n,\\, _gn)\\,|\\,(n,\\, _gn,\\, _{\\forall}n)  \\\\\n   \\phi &::=\\,\\cdot\\,|\\,\\rho\\,\\phi \\\\\n   IE,\\,IE^\\prime &::= \\phi;\\,c;\\,\\Gamma\n\\end{align*}\nThe singleton clock can appear either as open ($\\sqcup$), closed ($\\sqcap$), or\nirrelevant ($c$). Then guarded recursive terms are derived in an inference environment $IE$, such that\n${IE\\vdash e : A \\overset{B}{\\Longrightarrow} IE^\\prime \\vdash e^\\prime : B}$ describes the\ntransformation ($\\overset{B}{\\Longrightarrow}$) of an elaborated TT term $e$ of type\n$A$ in $IE$ to a guarded recursive TT term $e^\\prime$ of type $B$ in\n$IE^\\prime$. The $B$ in $\\overset{B}{\\Longrightarrow}$ implies that the transformation\nis type-directed, since it denotes that the desired output type $B$ is input to\nthe transformation function.\n\nIn Figure~\\ref{fig:epsilon_rules}, the $\\Longrightarrow_{Next^\\kappa}$ rule follows directly from the $Next$ rule in Figure~\\ref{fig:guarded_recursion_rules_clocks}. The\n$\\Longrightarrow_{\\Lambda\\kappa}$ and $\\Longrightarrow_{apply^\\kappa}$ rules have a\nsimilar structure, but here the clock changes state from premise to conclusion\n(e.g. from open to closed). For handling guarded names, the\n$\\Longrightarrow_{\\phi}$ rule says that if some Idris name has type $A$, and its\nguarded version has type $A^\\prime$, then we can insert the guarded name in its\nplace. Note that the type $A^\\prime$ of the guarded name is not arbitrary, but follows the\nrules for causal and non-causal function types (see Section~\\todo{insert ref\n  here}). Renaming is important for the $\\Longrightarrow_{App}$ rule, since it\nis often used for the transformations required in the premises. This reasoning\nalso applies to the $\\Longrightarrow_{\\tensor^{\\kappa}_{n}}$ rule. Here,\nthe $n$ is a natural number denoting the required ``lateness'' of both input and\noutput, where $n \\ge 1$. Specifically, ${\\laterkappa_{\\!\\!1} B \\cong \\laterkappa B}, {\\laterkappa_{\\!\\!2}\n\\cong \\laterkappa\\laterkappa B}$ and so on. For trivial cases, the\n$\\Longrightarrow_{Refl}$ rule is used. \\todo{Say something about abstraction and\nlet-rules here, when they have been formulated.}\n\n\\begin{figure}\n\\textbf{The transformation to guarded recursive terms}$\\hfill \\boxed{IE\\vdash e : A \\overset{B}{\\Longrightarrow} IE^\\prime \\vdash e^\\prime : B}$\n\\input{figures/epsilon_next_rule.tex}\n\\input{figures/epsilon_lambdakappa_rule.tex}\n\\input{figures/epsilon_apply_rule.tex}\n\\input{figures/epsilon_renaming_rule.tex}\n\\input{figures/epsilon_app_rule.tex}\n\\input{figures/epsilon_tensor_rule.tex}\n\\input{figures/epsilon_refl_rule.tex}\n\\input{figures/epsilon_lambda_rule.tex}\n  \\caption{Rules for inferring guarded recursive terms.}\n  \\label{fig:epsilon_rules}\n\\end{figure}\n\n\\paragraph{An Example}\n\nFigure~\\ref{fig:epsilon_zeros} shows how a guarded recursive version of\n\\texttt{zeros} can be inferred using the rules presented in Figure~\\ref{fig:epsilon_rules}. The\nderivation proceeds by continually pushing type requirements down into the\nsyntax tree, until these can be resolved either trivially (using the\n$\\Longrightarrow_{Refl}$ rule), or by renaming (using the\n$\\Longrightarrow_{\\phi}$ rule). Note that all premises ensuring type consistency\nhave been omitted for brevity. A full example, along with a more advanced one,\ncan be found in Appendix~\\ref{app:infer-guard-recurs}.\\todo{Make this appendix}\n\\begin{figure}\n\\begin{lstlisting}[mathescape]\ncausal zeros : Stream Nat\nzeros = Z :: zeros\n\n$_g$zeros : $\\forall\\kappa.$ $_g$Stream Nat\n$_g$zeros = $\\Lambda\\kappa.$ Z $_g$:: (Next (apply $_g$zeros))\n\\end{lstlisting}\n  % \\[\n  % \\frac{x}{\\eps{IE}{Z :: zeros}{Stream Nat}{IE}{Z :: gzeros}{gStream Nat}}\n  % \\]\n\\input{figures/epsilon_zeros}\n  \\caption{Above: The user-provided program \\texttt{zeros}, along with the\n    inferred program $_g$\\texttt{zeros}. Below: Inferring $_g$\\texttt{zeros} from \\texttt{zeros} using the rules from\n  Figure~\\ref{fig:epsilon_rules}.}\n  \\label{fig:epsilon_zeros}\n\\end{figure}\n\n\\subsubsection{Implementing the Inference System}\n\n\\paragraph{Preprocessing} Two aspects of the inference system, renaming and\ndelaying the recursive reference, are mandatory, and these \nare therefore handled in a separate preprocessing step. Both must take modality\ninto account.\n\nRenaming, i.e. all applications of the $\\Longrightarrow_{\\phi}$ rule, is\nperformed by substituting all Idris names in $\\phi$ with their guarded\nversions. Special care must be taken when substituting names of projection\nfunctions, since the modality of the function in question, $f$, influences the choice\nof guarded name. If $f$ is causal, \n\nDelaying the recursive reference\n%Preprocessing\n%Modality and Recursive reference\n%When rules clash\n\n\\subsection{Checking}\nTo check that what we infer actually conforms to the guarded recursion rules, we\nhave implemented a checker. This algorithm simply checks a term to have a given\ntype within the rule from Figure~\\ref{fig:gr_rules_sin_clock}. To the algorithm\nless error prone it is implemented in the simplest fashion possible and as\nattempts to stick strictly to the typing rules. This means that the checking\nalgorithm is very simple, conservative, and rigid. It expect types and terms to\nbe of a specific structure, and it discards anything it can guarantee the\ncorrectness off. \n\nThe checker traverses a term, and unfolds them according to the rules. Any rules\nthat requires a type equality is done by asking the Idris type system for\nconversion equality, and if the type of a term is needed it is checked using the\nIdris type checker.\n\nThe structure of the code itself aims to take care of as much as the check using\npattern matching. While not always possible, ideally the conclusion of a rule\nshould be represented by a pattern match, and the premise(s) by a right-hand\nside. By doing this we can, through different patterns, be very selective about\nwhat is accepted by the checker and discard anything that does not match the\nconclusion of a rule.\n\nGetting more into the actual implementation the checking algorithm is a function\n\\texttt{check}, with the type signature seen in Figure~\\ref{fig:check_type}. The\nparameters are as follows:\\todo{Is this too low level?}\n\n\\begin{itemize}\n\\item \\texttt{Clock} is the clock under which we are checking the term. A clock\n  is simply either open or closed.\n\\item \\texttt{Env} is the local environment, usually generated from the\n  left-hand side of the clause being checked.\n\\item \\texttt{(Name, Type)} is name and the type of the recursive\n  reference. \n\\item \\texttt{Term} is the term being checked.\n\\item \\texttt{Type} is the type the term is being checked to have.\n\\item \\texttt{Idris Totality} is the result of the algorithm wrapped in the\n  Idris monad\\todo{Is the Idris monad explained at this point?}. \n\\end{itemize}\n\n\\begin{figure}[h]\n\\begin{lstlisting}\ncheck :: Clock -> \n         Env -> \n         (Name, Type) -> \n         Term -> \n         Type -> \n         Idris Totality\n\\end{lstlisting}  \n  \\caption{Checking algorithm type.}\n  \\label{fig:check_type}\n\\end{figure}\n\nThe majority of the conclusions of the rules can be reflected as patterns. If we\nwish to e.g. delay a term, the $Next_i$-rule requires that, (1) the clock is\nopen, (2) the term is on the form $Next t$, and (3) the type is on the form\n$\\later A$. These requirements are expressed as a pattern in\nFigure~\\ref{fig:next_pattern}. The view-patterns can be read as regular pattern\nmatch, such that \\texttt{next -> Extracted t} is \\texttt{Next t}. The premise\nfrom the rule is reflected on the right-hand side. simply check that given the\nsame environments \\texttt{t} has type \\texttt{a}.\n\n\\begin{figure}[h]\n\\begin{lstlisting}\ncheck Open g n (next -> Extracted t) (later -> Extracted a) \n     =\n     check Open g n t a\n\\end{lstlisting}\n  \\caption{$Next_{i}$ pattern. Note the use of view-patterns (the -> syntax).}\n  \\label{fig:next_pattern}\n\\end{figure}\n\n\\paragraph{No Free Clocks in Environment}\n% No free clocks in finished definitions.\n% Check everything in local environment with closed clock.\nSome rules have a side condition dictating that there must no free clocks in the\nvariable environment. These are checked by checking that every term in the\nvariable can be checked under a closed clock. This is the same as no clocks\nbeing free, because any term or type with a free clock would require the clock\nto be open in order to be well-formed. \n\\paragraph{Identifying the Recursive Reference}\n\\todo{This paragraph needs more implementation to be written}\n%##########\n% To faser: Inferens og check - bør kunne beskrives separat\n% Inferens - regler\n% Check - regler\n% Correctness claim - Hvordan kan vi være sikre på at vi inferer guarded\n% recursion?\n% Preservation of semantics - Har den infererede term samme semantik som\n% input-termen?\n% Tensor-regel og parametre\n%##########\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: \"../copatterns-thesis\"\n%%% End:\n", "meta": {"hexsha": "5920238503a399aef6c9d4b47f844566e46d6570", "size": 31754, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "sections/guarded_recursion_implementation.tex", "max_stars_repo_name": "sualitu/thesis", "max_stars_repo_head_hexsha": "22d2cb4f21dc7c2dab011da5bb560c003650a2bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sections/guarded_recursion_implementation.tex", "max_issues_repo_name": "sualitu/thesis", "max_issues_repo_head_hexsha": "22d2cb4f21dc7c2dab011da5bb560c003650a2bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sections/guarded_recursion_implementation.tex", "max_forks_repo_name": "sualitu/thesis", "max_forks_repo_head_hexsha": "22d2cb4f21dc7c2dab011da5bb560c003650a2bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.5535168196, "max_line_length": 169, "alphanum_fraction": 0.7322542042, "num_tokens": 8808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.3005898623496019}}
{"text": "\\chapter[Bremstrahlung]{Bremstrahlung}\n\nBremstrahlung dominates other muon interaction processes in the region of\ncatastrophic collisions ($v \\geq 0.1$ ); at \"moderate\" muon \nenergies - above knock onelectron production kinematic limit.\n\n\\section{Differential cross section }\n\nThe differential cross section for muon bremstrahlung (in units $cm^{2}/(g~GeV)$)\ncan be written as :\n\n\n\\begin{eqnarray}\n    \\frac{d \\sigma (E, \\epsilon, Z, A )} {d \\epsilon} &=&\n  \\frac{16}{3} \\alpha N_{A} (\\frac{m}{\\mu} r_{e} )^2 \\frac{1}{ \\epsilon A} Z\n  (Z \\Phi_{n}+ \\Phi_{e})(1-v+\\frac{3}{4}v^{2})   \\\\  \n    \\frac{d \\sigma (E, \\epsilon, Z, A )} {d \\epsilon} &=& 0 \\quad\n    if \\quad \\epsilon \\geq \\epsilon_{max} = E- \\mu  \\nonumber\n\\end{eqnarray}\n%\nwhere $\\mu$ and $m$ are the muon and  electron masses,\n$Z$ and $A$ are the atomic number and atomic weight of the material\nand $N_{A}$ is Avogadro's number.\n If we indicate with $E$ and $T$ the initial total and kinetic energy of muon,\n$\\epsilon$--emitted photon energy we have: $\\epsilon = E - E'$ and\nrelative energy transfer $v = \\epsilon /E$.\n\nFunctions $\\Phi_{n}$ and $\\Phi_{e}$ represent contribution \nof nuclear and electrons and can be expressed as :\n\n\\begin{eqnarray*}\n \\Phi_{n} &=& \\ln \\frac {BZ^{-1/3}(\\mu + \\delta (D_{n}' \\sqrt{e} -2))}\n    {D_{n}'(m+ \\delta \\sqrt{e}BZ^{-1/3})} ; \\\\\n   &=&  0 \\quad if \\quad negative;\n\\end{eqnarray*}\n\n\\begin{eqnarray*}\n  \\Phi_{e} &=& \\ln \\frac {B'Z^{-2/3} \\mu }\n   {(1+ \\frac{\\delta \\mu}{m^{2} \\sqrt{e}})(m+ \\delta \\sqrt{e} B'Z^{-2/3}) }  \\\\\n   &=&  0 \\quad if \\quad \\epsilon \\geq \\epsilon'_{max} = E/(1+ \\mu^{2}/2mE) \\\\\n   &=&  0 \\quad if \\quad negative    \n\\end{eqnarray*}\n%\n\\begin{eqnarray*}\n\\delta &=& \\mu^{2} \\epsilon /2EE' = \\mu^{2} v/2(E- \\epsilon) \\\\\nD'_{n} &=& D_{n}^{(1-1/Z)}, \\quad D_{n}= 1.54A^{0.27}  \\\\\nB &=& 183, \\quad B'=1429, \\quad \\sqrt{e}=1.648(721271).\n\\end{eqnarray*}\n%\nSpecial case for hydrogen ($Z$=1): $B = 202.4,\\: B' = 446, \\: D_{n}' = D_{n}$.\n\n\nFormulae are mostly taken from (\\cite{brem.kel95}) and (\\cite{brem.kel97}).\nThey include improved (in the region $v \\sim 1$ and low $Z$, \n in comparison with\n(\\cite{brem.petr68}) correction for nuclear size. Bremstrahlung on atomic \nelectrons (taking into account target recoil and atomic binding) is\nintroduced instead of a rough substitution $Z(Z+1) $. Also  (\\cite{brem.andr94})\ncorrection for processes with nuclear excitation is included here.\n\n\\subsection{Aplicability and restrictions of the method}\n\n1. $E \\gg \\mu $, ultrarelativistic approximation used in this method; \\\\\n2. $E \\leq 10^{20}$ eV, above LPM cross section suppression can be expected;\\\\\n3. $v \\geq 10^{-6}$ , below , Ter-Mikaelyan suppression can be expected.\nHowever, in this region cross section of muon bremstrahlung is many\norders of magnitude less then for other processes.\\\\\n4. Coulomb corrections is not included. However Bugaev's calculations\nshow that it is small for muon bremstrahlung.\n\n\\section{Continuous energy loss}\n\nThe restricted energy loss for muon bremsrahlung $(d E/ dx)_{rest}$\n with relative transfers $v = \\epsilon / (T+ \\mu) \\leq v_{cut}$\ncan be calculated as follows :\n$$\n\\frac{d E}{d x}\n= \\int_{0}^{\\epsilon_{cut}}  \\epsilon \\sigma (E,\\epsilon )  \\: d \\epsilon  =\n(T+ \\mu ) \\int_{0}^{v_{cut}}  v \\sigma (E, v )  \\: d v\n$$\n% \nIf user's cut $v_{cut} \\geq v_{max}=T/(T+ \\mu)$, total average \nenergy loss is calculated. Integration is done on the basis of Gauss quadratures, \nbinnig provides  the accuracy better\nthan about 0.03\\% for $T = 1$ GeV, $Z=1$ (rapidly improving with increasing $T$\nand $Z$).\n\n\n\\section{Total cross-section}\n\nThe integration of differential cross section  (1) over\n$d\\epsilon$ gives the total cross-section for muon bremstrahlung:\n\n\\begin{equation}\n\\sigma_{tot} (E, \\epsilon_{cut})\n= \\int_{\\epsilon_{cut}}^{\\epsilon_{max}}  \\sigma (E,\\epsilon )  \\: d \\epsilon  =\n \\int_{\\ln v_{cut}}^{\\ln v_{max}}  v \\sigma (E, v )  \\: d (\\ln v)\\:,\n\\end{equation}\nwhere $v_{max}=T/(T+ \\mu)$. If $v_{cut} \\geq v_{max}$ , $\\sigma_{tot}$ = 0.\n\n\\section{Sampling}\n\nRandom photon energy $\\epsilon_{p}$ is found from the numerical solution\nof the equation :\n$$ P \\:= \\int_{\\epsilon_{p}}^{\\epsilon_{max}}  \\sigma (E,\\epsilon,Z,A )  \\: d \\epsilon \\: \n / \\: \\int_{\\epsilon_{cut.}}^{\\epsilon_{max}}  \\sigma (E,\\epsilon,Z,A )  \\: d \\epsilon .\n$$\n%\nHere $P$ is random uniform probability, $\\epsilon_{max}=T$,\n$\\epsilon_{cut}=(T+\\mu) \\cdot v_{min.cut}$;\n$v_{min.cut}=10^{-5}$ being a relative transfer cut adopted \nin the algorithm.\n\nFor fast sampling, solution of (2) is tabulated at initialization \nfor a set of $Z,T,P$. In simulation, sampling subroutine returns random \n$\\epsilon_{p}$ corresponding to probability $P$,\ninterpolation in the table being used.\n\nTabulation subroutine uses function (1) for differential \ncross section. The table contains the values :\n\\begin{equation}\n x_{p} = \\ln (v_{p} / v_{max})/\\ln (v_{max}/v_{min.cut}),\n\\end{equation}\nwhere $v_{p}= \\epsilon_{p}/(T+ \\mu),\\: v_{max} = T/(T+ \\mu).$ \nThe table parameters are : $Z_{min}=1, \\: Z_{max}=128; \\:\nT_{min}=1$ GeV, $T_{max}=10^{6}$ GeV ;\n$P_{min}=10^{-5}, \\: P_{max}=1.$\n\nAtomic weight (which is the necessary parameters in (1)) is estimated\nhere with iterative solution of the known relation (approximate) :\n$$ A = Z (2+0.015 A^{2/3}),$$\nfor $Z=1$ it is used $A=1$ .\n%\nTo  find $x_{p}$ (and, respectively, $\\epsilon_{p}$) corresponding to \na given probability $P$, in sampling subroutine the linear\ninterpolation in $\\ln Z, \\: \\ln T$, and cubic (4 points Lagrange) interpolation \nin $\\ln P$ is realised. For $P \\leq P_{min}$ , linear interpolation \nin $(P,x)$ - coordinates is used, noticeably, $x = 0$ at $P = 0$.\nThen, random energy $\\epsilon_{p}$ is obtained from the inverse\ntransformation of (3) :\n%\n$$\\epsilon_{p} = (T+ \\mu ) v_{max} (v_{max}/v_{min})^{x_{p}} $$\n%\nThe algorithm with the parameters described above has been\ntested for various $Z$ and $T$. It provides the reproduction \nof the differential cross section with about 0.2 - 0.7 \\% \naccuracy for $T \\geq 10$ GeV, the average total energy loss \nbeing kept within 0.3\\%. Accuracy improves with the increase\nof $T$, satisfactory results are obtained also for\n$1 \\leq T \\leq 10$ GeV.\n\nIt is important to note that this sampling scheme allows\nto generate $\\epsilon_{p}$ for different user's cuts on $v$\ngrater then $v_{min.cut}$. \nTo realize such simulation, it is sufficient to\nre-define probability variable :\n%\n$$P' = P \\: \\sigma_{tot} \\: (v_{user.cut}) / \\sigma_{tot} (v_{min.cut})$$\n%\nand just use $P'$ in sampling subroutine.\nThus, time consuming re-calculation of 3-dimensional table\nis not required (only calculation \nof $\\sigma_{tot}(v_{user.cut})$ is needed).\n  \n\nAfter the successful sampling of $\\epsilon$,  the direction\n of the emitted photon is generated with respect to the direction of the\nincident particle. The azimuthal angle $\\phi$ is generated isotropically;\nthe polar angle\n$\\theta$ is calculated from the energy momentum conservation.\nThis information\nis used to calculate the energy and momentum of both scattered\nparticles and to transform them into the {\\em global} coordinate system.\n\n\\section{Status of this document}\n 9.10.98 created by R.Kokoulin and A.Rybin .\n\n\\begin{thebibliography}{99}\n\n\\bibitem[Keln95]{brem.kel95}\n  S.R.Kelner, R.P.Kokoulin, A.A.Petrukhin. Preprint MEPhI 024-95, Moscow, 1995.\n\\bibitem[Keln97]{brem.kel97}\n  S.R.Kelner, R.P.Kokoulin, A.A.Petrukhin. Phys. Atomic Nuclei, 60(1997)576.\n\\bibitem[Petr68]{brem.petr68}\n  A.A.Petrukhin, V.V.Shestakov. Canad.J.Phys., 46(1968)S377.\n\\bibitem[Andr94]{brem.andr94}\n  Yu.M.Andreyev, L.B.Bezrukov, E.V.Bugaev. Phys. Atomic Nuclei, 57(1994)2066.\n\\end{thebibliography}\n\n\n", "meta": {"hexsha": "95ac8112d3decd4a7f4b05789a658c6d72a70876", "size": 7648, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "geant4/electromagnetic/muons/mubrem.tex", "max_stars_repo_name": "berghaus/cernlib-docs", "max_stars_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-24T12:30:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-24T12:30:01.000Z", "max_issues_repo_path": "geant4/electromagnetic/muons/mubrem.tex", "max_issues_repo_name": "berghaus/cernlib-docs", "max_issues_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geant4/electromagnetic/muons/mubrem.tex", "max_forks_repo_name": "berghaus/cernlib-docs", "max_forks_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0418848168, "max_line_length": 90, "alphanum_fraction": 0.6779550209, "num_tokens": 2572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.30054634994029794}}
{"text": "\\documentclass[english]{../thermomemo/thermomemo}\n\\usepackage[utf8]{inputenc}\n\\usepackage{amsmath}\n\\usepackage{array}% improves tabular environment.\n\\usepackage{dcolumn}% also improves tabular environment, with decimal centring.\n\\usepackage{booktabs}\n\\usepackage{todonotes}\n\\usepackage{subcaption,caption}\n\\usepackage{xspace}\n\\usepackage{tikz}\n\\usetikzlibrary{arrows}\n\\usetikzlibrary{snakes}\n\\usepackage{verbatim}\n\\usepackage{hyperref}\n\\usepackage{xcolor}\n\\hypersetup{\n  colorlinks,\n  linkcolor={red!50!black},\n  citecolor={blue!50!black},\n  urlcolor={blue!80!black}\n}\n%\n% Egendefinerte\n%\n% Kolonnetyper for array.sty:\n\\newcolumntype{C}{>{$}c<{$}}\n\\newcolumntype{L}{>{$}l<{$}}\n%\n\\newcommand*{\\unit}[1]{\\ensuremath{\\,\\mathrm{#1}}}\n\\newcommand*{\\uunit}[1]{\\ensuremath{\\mathrm{#1}}}\n%\\newcommand*{\\od}[3][]{\\frac{\\mathrm{d}^{#1}#2}{\\mathrm{d}{#3}^{#1}}}% ordinary derivative\n\\newcommand*{\\od}[3][]{\\frac{\\dif^{#1}#2}{\\dif{#3}^{#1}}}% ordinary derivative\n\\newcommand*{\\pd}[3][]{\\frac{\\partial^{#1}#2}{\\partial{#3}^{#1}}}% partial derivative\n\\newcommand*{\\pdc}[3]{\\frac{\\partial^{2}#1}{\\partial{#2}\\partial{#3}}}% partial derivative\n\\newcommand*{\\pdt}[3][]{{\\partial^{#1}#2}/{\\partial{#3}^{#1}}}% partial\n                                % derivative for inline use.\n\\newcommand{\\pone}[3]{\\frac{\\partial #1}{\\partial #2}_{#3}}% partial\n                                % derivative with information of\n                                % constant variables\n\\newcommand{\\ponel}[3]{\\frac{\\partial #1}{\\partial #2}\\bigg|_{#3}} % partial derivative with informatio of constant variable. A line is added.\n\\newcommand{\\ptwo}[3]{\\frac{\\partial^{2} #1}{\\partial #2 \\partial\n    #3}} % partial differential in two different variables\n\\newcommand{\\pdn}[3]{\\frac{\\partial^{#1}#2}{\\partial{#3}^{#1}}}% partial derivative\n\n% Total derivative:\n\\newcommand*{\\ttd}[2]{\\frac{\\mathrm{D} #1}{\\mathrm{D} #2}}\n\\newcommand*{\\td}[2]{\\frac{\\mathrm{d} #1}{\\mathrm{d} #2}}\n\\newcommand*{\\ddt}{\\frac{\\partial}{\\partial t}}\n\\newcommand*{\\ddx}{\\frac{\\partial}{\\partial x}}\n% Vectors etc:\n% For Computer Modern:\n\n\\DeclareMathAlphabet{\\mathsfsl}{OT1}{cmss}{m}{sl}\n\\renewcommand*{\\vec}[1]{\\boldsymbol{#1}}%\n\\newcommand*{\\vektor}[1]{\\boldsymbol{#1}}%\n\\newcommand*{\\tensor}[1]{\\mathsfsl{#1}}% 2. order tensor\n\\newcommand*{\\matr}[1]{\\tensor{#1}}% matrix\n\\renewcommand*{\\div}{\\boldsymbol{\\nabla\\cdot}}% divergence\n\\newcommand*{\\grad}{\\boldsymbol{\\nabla}}% gradient\n% fancy differential from Claudio Beccari, TUGboat:\n% adjusts spacing automatically\n\\makeatletter\n\\newcommand*{\\dif}{\\@ifnextchar^{\\DIfF}{\\DIfF^{}}}\n\\def\\DIfF^#1{\\mathop{\\mathrm{\\mathstrut d}}\\nolimits^{#1}\\gobblesp@ce}\n\\def\\gobblesp@ce{\\futurelet\\diffarg\\opsp@ce}\n\\def\\opsp@ce{%\n  \\let\\DiffSpace\\!%\n  \\ifx\\diffarg(%\n    \\let\\DiffSpace\\relax\n  \\else\n    \\ifx\\diffarg[%\n      \\let\\DiffSpace\\relax\n    \\else\n      \\ifx\\diffarg\\{%\n        \\let\\DiffSpace\\relax\n      \\fi\\fi\\fi\\DiffSpace}\n\\makeatother\n%\n\\newcommand*{\\me}{\\mathrm{e}}% e is not a variable (2.718281828...)\n%\\newcommand*{\\mi}{\\mathrm{i}}%  nor i (\\sqrt{-1})\n\\newcommand*{\\mpi}{\\uppi}% nor pi (3.141592...) (works for for Lucida)\n%\n% lav tekst-indeks/subscript/pedex\n\\newcommand*{\\ped}[1]{\\ensuremath{_{\\text{#1}}}}\n\\newcommand*{\\ap}[1]{\\ensuremath{^{\\text{#1}}}}\n\\newcommand*{\\apr}[1]{\\ensuremath{^{\\mathrm{#1}}}}\n\\newcommand*{\\pedr}[1]{\\ensuremath{_{\\mathrm{#1}}}}\n%\n\\newcommand*{\\volfrac}{\\alpha}% volume fraction\n\\newcommand*{\\surften}{\\sigma}% coeff. of surface tension\n\\newcommand*{\\curv}{\\kappa}% curvature\n\\newcommand*{\\ls}{\\phi}% level-set function\n\\newcommand*{\\ep}{\\Phi}% electric potential\n\\newcommand*{\\perm}{\\varepsilon}% electric permittivity\n\\newcommand*{\\visc}{\\mu}% molecular (dymamic) viscosity\n\\newcommand*{\\kvisc}{\\nu}% kinematic viscosity\n\\newcommand*{\\cfl}{C}% CFL number\n\n\\newcommand*{\\cons}{\\vec U}\n\\newcommand*{\\flux}{\\vec F}\n\\newcommand*{\\dens}{\\rho}\n\\newcommand*{\\svol}{\\ensuremath v}\n\\newcommand*{\\temp}{\\ensuremath T}\n\\newcommand*{\\vel}{\\ensuremath u}\n\\newcommand*{\\mom}{\\dens\\vel}\n\\newcommand*{\\toten}{\\ensuremath E}\n\\newcommand*{\\inten}{\\ensuremath e}\n\\newcommand*{\\press}{\\ensuremath p}\n\\renewcommand*{\\ss}{\\ensuremath a}\n\\newcommand*{\\jac}{\\matr A}\n%\n\\newcommand*{\\abs}[1]{\\lvert#1\\rvert}\n\\newcommand*{\\bigabs}[1]{\\bigl\\lvert#1\\bigr\\rvert}\n\\newcommand*{\\biggabs}[1]{\\biggl\\lvert#1\\biggr\\rvert}\n\\newcommand*{\\norm}[1]{\\lVert#1\\rVert}\n%\n\\newcommand*{\\e}[1]{\\times 10^{#1}}\n\\newcommand*{\\ex}[1]{\\times 10^{#1}}%shorthand -- for use e.g. in tables\n\\newcommand*{\\exi}[1]{10^{#1}}%shorthand -- for use e.g. in tables\n\\newcommand*{\\nondim}[1]{\\ensuremath{\\mathit{#1}}}% italic iflg. ISO. (???)\n\\newcommand*{\\rey}{\\nondim{Re}}\n\\newcommand*{\\acro}[1]{\\textsc{\\MakeLowercase{#1}}}%acronyms etc.\n\\newcommand*{\\ousum}[2]{\\overset{#1}{\\underset{#2}{\\sum}}}\n\n\\newcommand{\\nto}{\\ensuremath{\\mbox{N}_{\\mbox{\\scriptsize 2}}}}\n\\newcommand{\\chfire}{\\ensuremath{\\mbox{CH}_{\\mbox{\\scriptsize 4}}}}\n%\\newcommand*{\\checked}{\\ding{51}}\n\\newcommand{\\coto}{\\ensuremath{\\text{CO}_{\\text{\\scriptsize 2}}}}\n\\newcommand{\\celsius}{\\ensuremath{^\\circ\\text{C}}}\n\\newcommand{\\clap}{Clapeyron~}\n\\newcommand{\\subl}{\\ensuremath{\\text{sub}}}\n\\newcommand{\\spec}{\\text{spec}}\n\\newcommand{\\sat}{\\text{sat}}\n\\newcommand{\\sol}{\\text{sol}}\n\\newcommand{\\liq}{\\text{liq}}\n\\newcommand{\\vap}{\\text{vap}}\n\\newcommand{\\amb}{\\text{amb}}\n\\newcommand{\\tr}{\\text{tr}}\n\\newcommand{\\crit}{\\text{crit}}\n\\newcommand{\\entr}{\\ensuremath{\\text{s}}}\n\\newcommand{\\fus}{\\text{fus}}\n\\newcommand{\\flash}[1]{\\ensuremath{#1\\text{-flash}}}\n\\newcommand{\\spce}[2]{\\ensuremath{#1\\, #2\\text{ space}}}\n\\newcommand{\\spanwagner}{\\text{Span--Wagner}}\n\\newcommand{\\triplepoint}{\\text{TP triple point}}\n\\newcommand{\\wrpt}{\\text{with respect to}\\xspace}\n\\newcommand{\\excess}{\\text{E}\\xspace}\n\\newcommand{\\comb}{\\text{comb}\\xspace}\n\\newcommand{\\FH}{\\text{FH}\\xspace}\n\\newcommand{\\SG}{\\text{SG}\\xspace}\n\\newcommand{\\NC}{\\text{NC}\\xspace}\n\\newcommand{\\NGr}{\\text{NG}\\xspace}\n\\newcommand{\\res}{\\text{R}\\xspace}\n\n\\title{UNIFAC excess gibbs mixing rules}\n\\author{Morten Hammer}\n\n\\graphicspath{{gfx/}}\n\n\\begin{document}\n\\frontmatter\n\\tableofcontents\n\\section{Introduction}\nThe UNIFAC (\\textit{UNI}QUAC \\textit{F}unctional-group \\textit{A}ctivity\n\\textit{C}oefficients) model \\cite{Fredenslund1975}, is a group\ncontribution model, and a further development of the UNIQUAC model\n\\cite{Abrams1975}. Being a group contribution model, it accounts for\nmolecular groups like $\\text{C-H}_2$ and $\\text{C-H}_3$,\nthat can be thought upon as monomers in a polymer.\n\nThe UNIFAC excess Gibbs mixing rule have found application in the\npredictive SRK, PSRK \\cite{Holderbaum1991}, model, and VTPR\n\\cite{Collinet2006}. It is also used as the universal mixing rule\n(UMR) \\cite{Voutsas2004} togther with t-mPR\n\\cite{Magoulas1990,Avlonitis1994}. The combined model is denoted\nUMR-PR.\n\n\\section{UNIFAC model}\nThe UNIFAC model \\cite{Fredenslund1975} is given as follows,\n\\begin{equation}\n  \\frac{A^\\res}{RT} = \\frac{A^\\excess}{RT} - \\frac{A^\\excess}{RT_0} = - \\ousum{\\NC}{i} n_i \\ousum{\\NGr}{k}  v_k^i Q_k(\\Lambda_k - \\Lambda_k^i).\n  \\label{eq:Ae}\n\\end{equation}\nThe symbols and formalism of Michelsen \\cite{Michelsen2007} is\nused. $A^\\excess/(RT_0)$ is the combinatorial term and is described in\na later sub section. It is assumed that $A^\\excess = G^\\excess$.\n\nThe different symbols are defined as follows,\n\\begin{align}\n  \\Lambda_k &= \\ln \\ousum{\\NGr}{j}  \\Theta_j \\tilde{E}_{jk},\\label{eq:Lambda_k}\\\\\n  \\Lambda_k^i &= \\ln \\ousum{\\NGr}{j}  \\Theta_j^i \\tilde{E}_{jk}, \\label{eq:Lambda_ki}\\\\\n  \\tilde{E}_{jk} &= \\exp \\left(-\\frac{\\tilde{U}_{jk}}{RT}\\right), \\label{eq:E_jk}\\\\\n  \\Theta_j &= \\frac{Q_j \\ousum{\\NC}{l}n_lv_j^l}{\\ousum{\\NC}{l}n_l\\ousum{\\NGr}{m}v_m^lQ_m}, \\label{eq:Theta_j}\\\\\n  \\Theta_j^i &= \\frac{Q_j v_j^i}{\\ousum{\\NGr}{k}v_k^iQ_k}. \\label{eq:Theta_ji}\n\\end{align}\nHere $Q_k$ is the group surface area of group $k$, and $v_k^i$ is the\nnumber of groups $k$ in molecule $i$. Both $Q_k$ and $v_k^i$ are\nconstants. $\\tilde{U}_{jk}$ is the interaction energy per unit surface\narea of the $j-k$ group interaction. $\\tilde{U}_{jk}$ can be a\nconstant, or a temperature function.\n\n\\subsection{Differentials}\nDifferentiating \\ref{eq:Ae} \\wrpt $n_\\alpha$ we get,\n\\begin{equation}\n  \\frac{1}{RT}\\pd{A^\\res}{n_\\alpha} = \\frac{A^\\res_\\alpha}{RT} = - \\ousum{\\NGr}{k}  v_k^\\alpha Q_k(\\Lambda_k - \\Lambda_k^\\alpha) - \\ousum{\\NC}{i} n_i \\ousum{\\NGr}{k}  v_k^i Q_k \\pd{\\Lambda_k}{n_\\alpha}.\n  \\label{eq:dAedna}\n\\end{equation}\nMichelsen \\cite[Chap.~5,Eq.~56]{Michelsen2007} show that\n\\begin{equation}\n  \\ousum{\\NC}{i} n_i \\ousum{\\NGr}{k}  v_k^i Q_k \\pd{\\Lambda_k}{n_\\alpha} = \\ousum{\\NGr}{j}v_j^\\alpha Q_j\\left(\\ousum{\\NGr}{k}\\frac{\\Theta_j \\tilde{E}_{jk}}{\\ousum{\\NGr}{l}\\Theta_l \\tilde{E}_{lk}} -1\\right).\n  \\label{eq:sumdLambdadna}\n\\end{equation}\nBut since second differentials are required, it do not help much for\nthe compositional differentials. Using\n\\begin{equation}\n  \\Lambda_k = \\ln \\ousum{\\NGr}{j}  \\Theta_j \\tilde{E}_{jk} = \\ln \\ousum{\\NC}{l}n_l \\ousum{\\NGr}{j} v_j^l Q_j \\tilde{E}_{jk} -\\ln \\ousum{\\NC}{l}n_l\\ousum{\\NGr}{m}v_m^lQ_m,\n\\end{equation}\nwe get\n\\begin{equation}\n  \\pd{\\Lambda_k}{n_\\alpha} = \\frac{\\ousum{\\NGr}{j} v_j^\\alpha Q_j \\tilde{E}_{jk}}{\\ousum{\\NC}{l}n_l \\ousum{\\NGr}{j} v_j^l Q_j \\tilde{E}_{jk}} - \\frac{\\ousum{\\NGr}{m}v_m^\\alpha Q_m}{\\ousum{\\NC}{l}n_l\\ousum{\\NGr}{m}v_m^lQ_m}.\n  \\label{eq:dLambdadna}\n\\end{equation}\nDifferentiating \\ref{eq:dAedna} further \\wrpt $n_\\beta$ we get,\n\\begin{align}\n  \\frac{A^\\res_{\\alpha\\beta}}{RT} &= - \\ousum{\\NGr}{k}  Q_k \\left(v_k^\\alpha  \\pd{\\Lambda_k}{n_\\beta} + v_k^\\beta \\pd{\\Lambda_k}{n_\\alpha}\\right) - \\ousum{\\NC}{i} n_i \\ousum{\\NGr}{k}  v_k^i Q_k \\ptwo{\\Lambda_k}{n_\\alpha}{n_\\beta}, \\label{eq:d2Aedna2}\\\\\n&= - \\ousum{\\NGr}{k}  Q_k \\left(v_k^\\alpha  \\pd{\\Lambda_k}{n_\\beta} + v_k^\\beta \\pd{\\Lambda_k}{n_\\alpha}\\right) - \\ousum{\\NGr}{k}  \\left(\\ousum{\\NC}{i} n_i v_k^i\\right) Q_k \\ptwo{\\Lambda_k}{n_\\alpha}{n_\\beta}.\n\\end{align}\nDifferentiating Equation \\ref{eq:dLambdadna} we get the second differential of $\\Lambda_k$,\n\\begin{equation}\n  \\ptwo{\\Lambda_k}{n_\\alpha}{n_\\beta} = -\\frac{\\left(\\ousum{\\NGr}{j} v_j^\\alpha Q_j \\tilde{E}_{jk}\\right) \\left(\\ousum{\\NGr}{j} v_j^\\beta Q_j \\tilde{E}_{jk}\\right)}{\\left(\\ousum{\\NC}{l}n_l \\ousum{\\NGr}{j} v_j^l Q_j \\tilde{E}_{jk}\\right)^2} + \\frac{\\left(\\ousum{\\NGr}{m}v_m^\\alpha Q_m\\right) \\left(\\ousum{\\NGr}{m}v_m^\\beta Q_m\\right)}{\\left(\\ousum{\\NC}{l}n_l\\ousum{\\NGr}{m}v_m^lQ_m\\right)^2}.\n  \\label{eq:ddLambdadnadnb}\n\\end{equation}\nWe immediately see that \\ref{eq:ddLambdadnadnb} give a symmetric matrix of the second differentials.\n\nDifferentiating \\ref{eq:Ae} \\wrpt $T$ we get,\n\\begin{align}\n  \\pd{\\left(\\frac{A^\\res}{RT}\\right)}{T} &= - \\ousum{\\NC}{i} n_i \\ousum{\\NGr}{k}  v_k^i Q_k\\left(\\pd{\\Lambda_k}{T} - \\pd{\\Lambda_k^i}{T}\\right), \\label{eq:dAedT} \\\\\n  \\pdn{2}{\\left(\\frac{A^\\res}{RT}\\right)}{T} &= - \\ousum{\\NC}{i} n_i \\ousum{\\NGr}{k}  v_k^i Q_k\\left(\\pdn{2}{\\Lambda_k}{T} - \\pdn{2}{\\Lambda_k^i}{T}\\right). \\label{eq:d2AedT2}\n\\end{align}\nHere,\n\\begin{align}\n  \\pd{\\Lambda_k}{T} &= \\frac{\\ousum{\\NC}{l}n_l \\ousum{\\NGr}{j} v_j^l Q_j \\pd{\\tilde{E}_{jk}}{T}}{\\ousum{\\NC}{l}n_l \\ousum{\\NGr}{j} v_j^l Q_j \\tilde{E}_{jk}},\\label{eq:dLkdT} \\\\\n  \\pd{\\Lambda_k^i}{T} &= \\frac{\\ousum{\\NGr}{j} Q_j v_j^i \\pd{\\tilde{E}_{jk}}{T}}{\\ousum{\\NGr}{j} Q_j v_j^i \\tilde{E}_{jk}},\\label{eq:dLikdT} \\\\\n  \\pdn{2}{\\Lambda_k}{T} &= \\frac{\\ousum{\\NC}{l}n_l \\ousum{\\NGr}{j} v_j^l Q_j \\pdn{2}{\\tilde{E}_{jk}}{T}}{\\ousum{\\NC}{l}n_l \\ousum{\\NGr}{j} v_j^l Q_j \\tilde{E}_{jk}} - \\left(\\pd{\\Lambda_k}{T}\\right)^2,\\label{eq:d2LkdT2} \\\\\n  \\pdn{2}{\\Lambda_k^i}{T} &= \\frac{\\ousum{\\NGr}{j} Q_j v_j^i \\pdn{2}{\\tilde{E}_{jk}}{T}}{\\ousum{\\NGr}{j} Q_j v_j^i \\tilde{E}_{jk}} - \\left(\\pd{\\Lambda_k^i}{T}\\right)^2.\\label{eq:d2LikdT2} \\\\\n\\end{align}\n\nDifferentiating Equation \\ref{eq:dAedna} we get\n\\begin{equation}\n  \\pd{\\left(\\frac{A^\\res_\\alpha}{RT}\\right)}{T} = - \\ousum{\\NGr}{k}  v_k^\\alpha Q_k\\left(\\pd{\\Lambda_k}{T} - \\pd{\\Lambda_k^\\alpha}{T}\\right) -  \\ousum{\\NGr}{k} \\left(\\ousum{\\NC}{i} n_i v_k^i\\right) Q_k \\ptwo{\\Lambda_k}{n_\\alpha}{T}. \\label{eq:d2AednadT}\n\\end{equation}\nThe cross differential of $\\Lambda_k$ is found by differentiating Equation \\ref{eq:dLambdadna} \\wrpt $T$,\n\\begin{equation}\n  \\ptwo{\\Lambda_k}{n_\\alpha}{T} = \\frac{\\ousum{\\NGr}{j} v_j^\\alpha Q_j \\pd{\\tilde{E}_{jk}}{T}}{\\ousum{\\NC}{l}n_l \\ousum{\\NGr}{j} v_j^l Q_j \\tilde{E}_{jk}} - \\frac{\\left(\\ousum{\\NGr}{j} v_j^\\alpha Q_j \\tilde{E}_{jk}\\right) \\left(\\ousum{\\NC}{l}n_l \\ousum{\\NGr}{j} v_j^l Q_j \\pd{\\tilde{E}_{jk}}{T}\\right)}{\\left(\\ousum{\\NC}{l}n_l \\ousum{\\NGr}{j} v_j^l Q_j \\tilde{E}_{jk}\\right)^2} .\n  \\label{eq:d2LambdadnadT}\n\\end{equation}\n\\subsection{The combinatorial term}\nThe combinatorial term is comprised of a Flory-Huggins (\\FH) and a\nStaverman-Guggenheim (\\SG) contribution,\n\n\\begin{align}\n  G^{\\excess,\\comb} &= G^{\\excess,\\FH} + G^{\\excess,\\SG},\\label{eq:comb}\\\\\n  G^{\\excess,\\FH} &= \\underset{i}{\\sum} x_i \\ln \\frac{\\phi_i}{x_i}, \\label{eq:fh}\\\\\n  G^{\\excess,\\SG} &= \\frac{z}{2} \\underset{i}{\\sum} x_i q_i \\ln \\frac{\\theta_i}{\\phi_i}\\label{eq:sg}.\n\\end{align}\nWhere $z=10$,\n\\begin{align}\n  \\phi_i &= \\frac{x_i r_i}{\\underset{j}{\\sum} x_j r_j},\\label{eq:phii}\\\\\n  \\theta_i &= \\frac{x_i q_i}{\\underset{j}{\\sum} x_j q_j}.\\label{eq:thetai}\\\\\n\\end{align}\n$r_i$ and $q_i$ are molecule paramaters and non of the parameters are temperature dependent. $r_i$ is the molecular van der Waals volume and $q_i$ is the molecular van der Waals surface area. They are calculated from the group paramaters as follows,\n\\begin{align}\n  r_i &= \\ousum{\\NGr}{k}v_k^i R_k,\\label{eq:ri}\\\\\n  q_i &= \\ousum{\\NGr}{k}v_k^i Q_k.\\label{eq:qi}\\\\\n\\end{align}\n\n\\subsubsection{Differentials of the Flory-Huggins combinatorial term}\nWriting Equation \\ref{eq:fh} as a function of mole numbers, we get,\n\\begin{align}\n  G^{\\excess,\\FH} &= \\ousum{\\NC}{i} n_i \\left(\\ln \\phi_i - \\ln n_i + \\ln \\ousum{\\NC}{j}n_j\\right), \\\\\n  &= \\ousum{\\NC}{i} n_i \\left(\\ln n_i r_i - \\ln \\ousum{\\NC}{j} n_j r_j - \\ln n_i + \\ln \\ousum{\\NC}{j}n_j\\right) = \\ousum{\\NC}{i} n_i \\ln r_i -n\\ln \\ousum{\\NC}{j}n_jr_j  + n\\ln n. \\label{eq:fhn}\n\\end{align}\nDifferentiating $G^{\\excess,\\FH}$ \\wrpt $n_\\alpha$ we get,\n\\begin{align}\n  G^{\\excess,\\FH}_\\alpha &= \\ln r_\\alpha -\\ln \\ousum{\\NC}{j}n_jr_j  + \\ln \\ousum{\\NC}{j}n_j + 1-\\frac{r_\\alpha\\ousum{\\NC}{i} n_i}{\\ousum{\\NC}{j}n_jr_j},\\\\\n  &= \\ln r_\\alpha -\\ln \\ousum{\\NC}{j}n_jr_j  + \\ln n + 1-\\frac{n r_\\alpha}{\\ousum{\\NC}{j}n_jr_j}, \\label{eq:dfhndna}\\\\\n  &= \\ln \\left(\\frac{n r_\\alpha}{\\ousum{\\NC}{j}n_jr_j}\\right) + 1-\\frac{n r_\\alpha}{\\ousum{\\NC}{j}n_jr_j}\\\\\n  &= \\ln \\left(\\frac{\\phi_\\alpha}{x_\\alpha}\\right) + 1-\\frac{\\phi_\\alpha}{x_\\alpha}\n\\end{align}\nDifferentiating \\ref{eq:dfhndna} \\wrpt $n_\\beta$ we get,\n\\begin{align}\n  G^{\\excess,\\FH}_{\\alpha\\beta} &= -\\frac{r_\\alpha + r_\\beta}{\\ousum{\\NC}{j}n_jr_j}  + \\frac{1}{n} + \\frac{n r_\\alpha r_\\beta}{\\left(\\ousum{\\NC}{j}n_jr_j\\right)^2}. \\label{eq:d2fhndnadnb}\n\\end{align}\n\\subsubsection{Differentials of the Staverman-Guggenheim combinatorial term}\nWriting Equation \\ref{eq:sg} as a function of mole numbers, we get,\n\\begin{align}\n  G^{\\excess,\\SG} &= \\frac{z}{2} \\ousum{\\NC}{i} n_i q_i \\left(\\ln \\theta_i - \\ln \\phi_i\\right),\\\\\n  &= \\frac{z}{2} \\ousum{\\NC}{i} n_i q_i \\left(\\ln \\frac{q_i}{r_i} - \\ln \\ousum{\\NC}{j} n_j q_j + \\ln \\ousum{\\NC}{j} n_j r_j \\right)\\label{eq:sgn}.\n\\end{align}\nDifferentiating $G^{\\excess,\\SG}$ \\wrpt $n_\\alpha$ we get,\n\\begin{align}\n  G^{\\excess,\\SG}_\\alpha &= \\frac{z}{2} q_\\alpha \\left( \\ln \\frac{q_\\alpha}{r_\\alpha} - \\ln \\ousum{\\NC}{j} n_j q_j + \\ln \\ousum{\\NC}{j} n_j r_j - 1 + \\frac{r_\\alpha \\ousum{\\NC}{i} n_i q_i}{q_\\alpha\\ousum{\\NC}{j} n_j r_j}\\right), \\label{eq:dsgnda}\\\\\n  &= \\frac{z}{2} q_\\alpha \\left( - \\ln \\left(\\frac{r_\\alpha \\ousum{\\NC}{j} n_j q_j}{q_\\alpha \\ousum{\\NC}{j} n_j r_j}\\right) - 1 + \\frac{r_\\alpha \\ousum{\\NC}{i} n_i q_i}{q_\\alpha\\ousum{\\NC}{j} n_j r_j}\\right),\\\\\n  &= \\frac{z}{2} q_\\alpha \\left( \\ln \\left(\\frac{\\theta_\\alpha}{\\phi_\\alpha}\\right) - 1 + \\frac{\\phi_\\alpha}{\\theta_\\alpha}\\right).\n\\end{align}\nDifferentiating \\ref{eq:dsgnda} \\wrpt $n_\\beta$ we get,\n\\begin{align}\n  G^{\\excess,\\SG}_{\\alpha\\beta} &= \\frac{z}{2} \\left( - \\frac{q_\\alpha q_\\beta}{\\ousum{\\NC}{j} n_j q_j} + \\frac{q_\\alpha r_\\beta + q_\\beta r_\\alpha}{\\ousum{\\NC}{j} n_j r_j} - \\frac{r_\\alpha r_\\beta \\ousum{\\NC}{i} n_i q_i}{\\left(\\ousum{\\NC}{j} n_j r_j\\right)^2}\\right). \\label{eq:dssgndadb}\n\\end{align}\n\\subsubsection{Comparing to combinatorial activity coefficient of Fredenslund et al.}\nFredenslund et al. \\cite{Fredenslund1975} uses the following expression for the activity combinatorial coefficient,\n\\begin{align}\n  \\ln \\gamma_{\\text{c}} &= \\ln \\frac{\\phi_i}{x_i} + \\frac{z}{2} q_i \\ln \\frac{\\theta_i}{\\phi_i} + l_i - \\frac{\\phi_i}{x_i}\\ousum{\\NC}{j} x_j l_j , \\label{eq:gamma_c} \\\\\n  l_i &= \\frac{z}{2} \\left(r_i - q_i\\right) - \\left(r_i - 1\\right) . \\label{eq:li}\n\\end{align}\nInserting for $l_i$ in the last term of Equation \\ref{eq:gamma_c}, we get,\n\\begin{align}\n  \\frac{\\phi_i}{x_i}\\ousum{\\NC}{j} x_j l_j &= \\frac{z\\phi_i}{2x_i}\\left(\\ousum{\\NC}{j} x_j r_j - \\ousum{\\NC}{j}x_jq_j\\right) - \\frac{\\phi_i}{x_i}\\left(\\ousum{\\NC}{j} x_j r_j - 1\\right), \\\\\n  &= \\frac{z}{2}\\left(r_i - \\frac{q_i\\phi_i}{\\theta_i}\\right) - r_i + \\frac{\\phi_i}{x_i}. \\label{eq:second_term}\n\\end{align}\nInserting Equation \\ref{eq:second_term} and Equation \\ref{eq:li} into Equation \\ref{eq:gamma_c} we get,\n\\begin{align}\n  \\ln \\gamma_{\\text{c}} &= \\ln \\frac{\\phi_i}{x_i} + 1 - \\frac{\\phi_i}{x_i} + \\frac{z}{2} q_i \\left(\\ln \\frac{\\theta_i}{\\phi_i} -1 + \\frac{\\phi_i}{\\theta_i}\\right).\n\\end{align}\nWe see that\n\\begin{equation}\n  \\ln \\gamma_{\\text{c}} = G^{\\excess,\\FH}_\\alpha + G^{\\excess,\\SG}_\\alpha.\n\\end{equation}\n\\section{UMR-PR model}\nThe UMR-PR model is developed by Voutsas et al \\cite{Voutsas2004}, and\nuses the UNIFAC mixing rules together with a volume translated\nPeng-Robinson EOS, t-mPR \\cite{Avlonitis1994}.\n\nUMR-PR applies the following covolume mixing rule,\n\\begin{align}\n  b &= \\underset{i}{\\sum} \\underset{j}{\\sum} x_i x_j b_{ij},\\\\\n  b_{ij} &= \\left[\\frac{b_i^{\\frac{1}{s}} + b_j^{\\frac{1}{s}}}{2}\\right]^s,\n  \\label{eq:bij}\n\\end{align}\nwith $s=2$.\n\nUMR-PR ignores the Flory-Huggins contribution, Equation \\ref{eq:fh},\nof the combinatorial term, Equation \\ref{eq:comb}.\n\nUMR-PR uses the original temperature independent UNIFAC parameters published by Hansen et al \\cite{Hansen1991} and Dortmund Data Bank, Wittig et al \\cite{Wittig2003}.\n\nData source:\n\\url{https://en.wikipedia.org/wiki/UNIFAC}\n\n\\url{http://www.ddbst.com/unifacga.html}\n\n\\url{http://www.aim.env.uea.ac.uk/aim/info/UNIFACgroups.html}\n\nThe volume correction temperature differentials used in UMR is not\ncontinous. This might be a good reason not to use the model.\n\n\n\\subsection{t-mPR model}\nt-mPR \\cite{Avlonitis1994} is an extension of the t-PR\n\\cite{Magoulas1990} to mixtures.\n\nThe t-mPR model take the following form,\n\\begin{equation}\n  \\label{eq:t-mPR}\n  P = \\frac{RT}{V+t-b} - \\frac{a}{(V+t)(V+t+b) + b(V+t-b)},\n\\end{equation}\nwhere,\n\\begin{equation}\n  \\label{eq:tmix}\n  t = t(\\vektor{x},T) = \\underset{i}{\\sum} x_i t_i(T).\n\\end{equation}\nWe see that by introducing $\\tilde{V} = V + t$, the relations for this\nequation of state can be related to the standard Peng-Robinson\nequation of state. The translation is slightly more complicated than\nthe P{\\'e}neloux \\cite{Peneloux1982} volume shift, due to the\ntemperature dependency, and the lack of correction to the covolume.\n\n\\section{PSRK model}\nPSRK \\cite{Holderbaum1991} uses SRK with Mathias-Copeman\n$\\alpha$-correlation \\cite{Mathias1983}, and a UNIFAC excess Gibbs\nenergy model. \n\nThe zero pressure limit, Equation \\ref{eq:zero_limit},\nis used when including the mixing rules into the SRK EOS.\n$h_{\\text{PSRK}}(\\beta_0) = 0.64663$ is used.\n\nThe zero pressure limit is used when including the excess Gibbs energy into the equation of state,\n\\begin{equation}\n  \\label{eq:zero_limit}\n  \\frac{a}{RTb} = \\underset{i}{\\sum} x_i \\frac{a_i}{RTb_i} - \\frac{1}{h(\\beta_0)}\\left(\\underset{i}{\\sum} x_i \\ln \\frac{b}{b_i} + \\frac{G^\\excess}{RT} \\right),\n\\end{equation}\nwhere $h(\\beta_0)$ is a constant that depend on the EOS. We have $h_{\\text{PR}}(\\beta_0) = 0.53$.\n\nThe linear mixing of the covolume is used in PSRK,\n\\begin{equation}\n  \\label{eq:linbmix}\n  b  = \\underset{i}{\\sum} x_i b_i.\n\\end{equation}\n\n\\textcolor{red}{Parameters: \\cite{Horstmann2005,Holderbaum1991,Horstmann2000,Fischer1996,Gmehling1997}}\n\n\\section{VTPR model}\nThe Volume-Translated-Peng-Robinson (VTPR) EOS \\cite{Collinet2006}, uses a constant volume correction for each component. The correction in volume therefore don't depend on temperature. The Twu, Bluck, Cunningham and Coon $\\alpha$-correlation \\cite{Twu1991} is used.\n\nFor the excess Gibbs energy, the UNIFAC model is used without the combinatorial term, Equation \\ref{eq:comb}. The infinite pressure limit is used when including the activity coefficient model into the EOS.\n\nCovolume mixing uses Equation \\ref{eq:bij} with $s=4/3$.\n\n\\textcolor{red}{Parameters: \\cite{Schmid2014}}\n\n\\section{The general mixing rule for the covolume}\nThe general mixing rules for the covolume take the following form,\n\\begin{align}\n  nB = n^2 b &= \\underset{i}{\\sum} \\underset{j}{\\sum} n_i n_j b_{ij}, \\label{eq:B}\\\\\n  b_{ij}^{\\frac{1}{s}} &= (1 - l_{ij}) \\frac{b_i^{\\frac{1}{s}} + b_j^{\\frac{1}{s}}}{2}.\n  \\label{eq:bij_mod}\n\\end{align}\nWhere $l_{ij}$ is assumed constant, symmetric, and have a default value of zero.\n\nDifferentiating and manipulating Equation \\ref{eq:B}, $B_{i}$ and\n$B_{ij}$ become,\n\\begin{align}\n  n B_i = &= 2\\underset{j}{\\sum} n_j b_{ij} -B, \\label{eq:Bi}\\\\\n  n B_{ij} = &= 2b_{ij} - B_i - B_j.\n  \\label{eq:Bij}\n\\end{align}\n\\clearpage\n\\bibliographystyle{plain}\n\\bibliography{../thermopack}\n\n\\end{document}\n", "meta": {"hexsha": "e65cadcd3f6e20efc5a4999ec5770ec963e87b93", "size": 21701, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/memo/UNIFAC/unifac.tex", "max_stars_repo_name": "SINTEF/Thermopack", "max_stars_repo_head_hexsha": "63c0dc82fe6f88dd5612c53a35f7fbf405b4f3f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2020-10-14T07:51:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T04:59:23.000Z", "max_issues_repo_path": "doc/memo/UNIFAC/unifac.tex", "max_issues_repo_name": "SINTEF/Thermopack", "max_issues_repo_head_hexsha": "63c0dc82fe6f88dd5612c53a35f7fbf405b4f3f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2020-10-26T11:43:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T22:06:30.000Z", "max_forks_repo_path": "doc/memo/UNIFAC/unifac.tex", "max_forks_repo_name": "SINTEF/Thermopack", "max_forks_repo_head_hexsha": "63c0dc82fe6f88dd5612c53a35f7fbf405b4f3f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2020-10-27T13:04:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T04:59:24.000Z", "avg_line_length": 50.2337962963, "max_line_length": 391, "alphanum_fraction": 0.6725496521, "num_tokens": 8529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3005463427108183}}
{"text": "\\chapter{Comparison with othert ISAs}\n\n\\hrulefill\n\n\\textbf{IMPORTANT NOTE:} Some of the discussions below refer to an older draft of the\nRISC-V Bitmanip extension and are now out-of-date.\n\n\\hrulefill\n\n\\section{Comparison with x86 Bit Manipulation ISAs}\n\\label{x86comp}\n\nThe following code snippets implement all instructions from the x86 bit manipulation\nISA extensions ABM, BMI1, BMI2, and TBM using RISC-V code that does not spill any\nregisters and thus could easily be implemented in a single instruction using macro-op\nfusion. (Some of them simply map directly to instructions in this spec and so no\nmacro-op fusion is needed.) Note that shorter RISC-V code sequences are\nsometimes possible if we allow spilling to temporary registers.\n\nABM added x86 encodings for POPCNT, LZCNT, and TZCNT.\\footnote{Depending on if\nyou ask Intel or AMD you will get different opinion regarding whether LZCNT\nand/or TZCNT are part of ABM or BMI1.} The difference between LZCNT and the\n80386 instruction BSR, and between TZCNT and the 80386 instruction BSF, is that\nthe new instructions return the operand size when the input operand is zero,\nwhile BSR and BSF were undefined in that case. The ABM instructions map 1:1 to\nBitmanip instructions. Table~\\ref{abm-comp} lists ABM instructions and regular\nx86 bit manipulation instructions.\n\n\\begin{table}[h]\n\\centering\n\\begin{tabular}{lrrl}\n\\multirow{2}{*}{x86 Instruction} & \\multicolumn{2}{c}{Bytes} & \\multirow{2}{*}{RISC-V Code} \\\\\n& x86 & RV & \\\\\n\\hline\nPOPCNT       &   5 &  4 & {\\tt cpop a0, a0} \\\\\n\\hline\nLZCNT / BSR  &   5 &  4 & {\\tt clz a0, a0} \\\\\n\\hline\nTZCNT / BSF  &   5 &  4 & {\\tt ctz a0, a0} \\\\\n\\hline\nBSWAP        &   3 &  4 & {\\tt bswap} \\\\\n\\hline\nROL          &   4 &  4 & {\\tt roli} \\\\\n\\hline\nROR          &   4 &  4 & {\\tt rori} \\\\\n\\hline\nBT           &   5 &  4 & {\\tt c.srl a0, N} \\\\\n             &     &    & {\\tt c.andi a0, 1} \\\\\n\\hline\nBTC          &   5 & 16 & {\\tt rori a0, N} \\\\\n             &     &    & {\\tt andi a1, a0, 1} \\\\\n             &     &    & {\\tt xori a0, a0, 1} \\\\\n             &     &    & {\\tt rori a0, XLEN-N} \\\\\n\\hline\nBTR          &   5 & 16 & {\\tt rori a0, N} \\\\\n             &     &    & {\\tt andi a1, a0, 1} \\\\\n             &     &    & {\\tt andi a0, a0, -2} \\\\\n             &     &    & {\\tt rori a0, XLEN-N} \\\\\n\\hline\nBTS          &   5 & 16 & {\\tt rori a0, N} \\\\\n             &     &    & {\\tt andi a1, a0, 1} \\\\\n             &     &    & {\\tt ori a0, a0, 1} \\\\\n             &     &    & {\\tt rori a0, XLEN-N} \\\\\n\\end{tabular}\n\\caption{Comparison of x86+ABM with Bitmanip}\n\\label{abm-comp}\n\\end{table}\n\nBMI1 adds some instructions for trailing bit manipulations, an add-complement instruction,\nand a bit field extract instruction that expects the length and start position packed in one\nregister operand. Our version expects the length in a0, start position in a1, and source\nvalue in a2. See Table~\\ref{bmi1-comp}.\n\n\\begin{table}[h]\n\\centering\n\\begin{tabular}{lrrl}\n\\multirow{2}{*}{x86 Instruction} & \\multicolumn{2}{c}{Bytes} & \\multirow{2}{*}{RISC-V Code} \\\\\n& x86 & RV & \\\\\n\\hline\nANDN    & 5 &  4 & {\\tt andn a0, a2, a1} \\\\\n\\hline\nBEXTR (regs)  & 5 & 12 & {\\tt c.add a0, a1} \\\\\n              &   &    & {\\tt slo a0, zero, a0} \\\\\n              &   &    & {\\tt c.and a0, a2} \\\\\n              &   &    & {\\tt srl a0, a0, a1} \\\\\n\\hline\nBLSI          & 5 &  6 & {\\tt neg a0, a1} \\\\\n              &   &    & {\\tt c.and a0, a1} \\\\\n\\hline\nBLSMSK        & 5 &  6 & {\\tt addi a0, a1, -1} \\\\\n              &   &    & {\\tt c.xor a0, a1} \\\\\n\\hline\nBLSR          & 5 &  6 & {\\tt addi a0, a1, -1} \\\\\n              &   &    & {\\tt c.and a0, a1} \\\\\n\\end{tabular}\n\\caption{Comparison of x86 BMI1 with Bitmanip}\n\\label{bmi1-comp}\n\\end{table}\n\nBMI2 adds a few \\texttt{*X} instructions that just perform the indicated\noperation without changing any flags. RISC-V does not use flags, so this\ninstructions trivially just map to their regular RISC-V counterparts. In\naddition to those instructions, BMI2 adds bit extract and deposit instructions\nand an instruction to clear high bits above a given bit index. See Table~\\ref{bmi2-comp}.\n\n\\begin{table}[h]\n\\centering\n\\begin{tabular}{lrrl}\n\\multirow{2}{*}{x86 Instruction} & \\multicolumn{2}{c}{Bytes} & \\multirow{2}{*}{RISC-V Code} \\\\\n& x86 & RV & \\\\\n\\hline\nBZHI     & 5 &  6 & {\\tt slo a0, zero, a2} \\\\\n         &   &    & {\\tt c.and a0, a1} \\\\\n\\hline\nPDEP     & 5 &  4 & {\\tt bdep} \\\\\n\\hline\nPEXT     & 5 &  4 & {\\tt bext} \\\\\n\\hline\nMULX     & 5 &  4 & {\\tt mul} \\\\\n\\hline\nRORX     & 6 &  4 & {\\tt rori} \\\\\n\\hline\nSARX     & 5 &  4 & {\\tt sra} \\\\\n\\hline\nSHRX     & 5 &  4 & {\\tt srl} \\\\\n\\hline\nSHLX     & 5 &  4 & {\\tt sll} \\\\\n\\end{tabular}\n\\caption{Comparison of x86 BMI2 with Bitmanip}\n\\label{bmi2-comp}\n\\end{table}\n\nFinally, TBM was a short-lived x86 ISA extension introduced by AMD in\nPiledriver processors, complementing the trailing bit manipulation instructions\nfrom BMI1. See Table~\\ref{tbm-comp}.\n\n\\begin{table}[h]\n\\centering\n\\begin{tabular}{lrrl}\n\\multirow{2}{*}{x86 Instruction} & \\multicolumn{2}{c}{Bytes} & \\multirow{2}{*}{RISC-V Code} \\\\\n& x86 & RV & \\\\\n\\hline\nBEXTR (imm)  & 7 &  4 & {\\tt c.slli a0, (32-START-LEN)} \\\\\n             &   &    & {\\tt c.srli a0, (32-LEN)} \\\\\n\\hline\nBLCFILL      & 5 &  6 & {\\tt addi a0, a1, 1} \\\\\n             &   &    & {\\tt c.and a0, a1} \\\\\n\\hline\nBLCI         & 5 &  8 & {\\tt addi a0, a1, 1} \\\\\n             &   &    & {\\tt c.not a0} \\\\\n             &   &    & {\\tt c.or a0, a1} \\\\\n\\hline\nBLCIC        & 5 & 10 & {\\tt addi a0, a1, 1} \\\\\n             &   &    & {\\tt andn a0, a1, a0} \\\\\n             &   &    & {\\tt c.not a0} \\\\\n\\hline\nBLCMSK       & 5 &  6 & {\\tt addi a0, a1, 1} \\\\\n             &   &    & {\\tt c.xor a0, a1} \\\\\n\\hline\nBLCS         & 5 &  6 & {\\tt addi a0, a1, 1} \\\\\n             &   &    & {\\tt c.or a0, a1} \\\\\n\\hline\nBLSFILL      & 5 &  6 & {\\tt addi a0, a1, -1} \\\\\n             &   &    & {\\tt c.or a0, a1} \\\\\n\\hline\nBLSIC        & 5 & 10 & {\\tt addi a0, a1, -1} \\\\\n             &   &    & {\\tt andn a0, a1, a0} \\\\\n             &   &    & {\\tt c.not a0} \\\\\n\\hline\nT1MSKC       & 5 & 10 & {\\tt addi a0, a1, +1} \\\\\n             &   &    & {\\tt andn a0, a1, a0} \\\\\n             &   &    & {\\tt c.not a0} \\\\\n\\hline\nT1MSK        & 5 &  8 & {\\tt addi a0, a1, -1} \\\\\n             &   &    & {\\tt andn a0, a0, a1} \\\\\n\\end{tabular}\n\\caption{Comparison of x86 TBM with Bitmanip}\n\\label{tbm-comp}\n\\end{table}\n\n\\section{Comparison with RI5CY Bit Manipulation ISA}\n\nThe following section compares Bitmanip with the RI5CY bit manipulation\ninstructions as documented in~\\cite{Ri5cy}. All RI5CY bit manipulation\ninstructions (or something very close to their behavior) can be emulated with\nBitmanip using 3 instructions or less.\n\n\\subsubsection{RI5CY Instructions {\\tt p.extract}, {\\tt p.extractu}, {\\tt p.extractr}, and {\\tt p.extractur}}\n\nThese four RI5CY instructions extract bit-fields. The non-{\\tt u}-versions sign-extend\nthe extracted bit-field. This operations can be performed with two shift-immediate\noperations. It even fits in a 32-bit word when using compressed instructions (requires\n{\\tt rd} $=$ {\\tt rs}).\n\n\\begin{verbatim}\n  p.extract rd, rs, len, pos:\n    slli rd, rs, (XLEN-pos-len)\n    srai rd, rd, (XLEN-len)\n\n  p.extractu rd, rs, len, pos:\n    slli rd, rs, (XLEN-pos-len)\n    srli rd, rd, (XLEN-len)\n\\end{verbatim}\n\nThe {\\tt r}-versions expect the bit-field size in bits 9:5 of the second source\nregister and the bit-field start in bits 4:0. Instead we use two registers,\n$\\texttt{rx} = XLEN-pos-len$ and $\\texttt{ry} = XLEN-len$.\n\n\\begin{verbatim}\n  p.extractr:\n    sll rd, rs, rx\n    sra rd, rd, ry\n\n  p.extractur:\n    sll rd, rs, rx\n    srl rd, rd, ry\n\\end{verbatim}\n\nAlternatively, instead of packing length and position into a register, we\ncan create a mask in a register and then use this mask with {\\tt bext}. This\nhas the advantage over the {\\tt sll}+{\\tt srl} sequence that the mask only needs\nto be generated once and can then be re-used many times, effectively implementing\n{\\tt p.extractur} in a single instruction.\n\n\\begin{verbatim}\n  p.extractur:\n    slo rMask, zero, rLen\n    sll rMask, rMask, rPos\n    bext rd, rs, rMask\n\\end{verbatim}\n\n{\\tt p.extractu} can be efficiently emulated with a single XBitfield {\\tt bfxp}\ninstruction (see Chapter~\\ref{bfxp}):\n\n\\begin{verbatim}\n  p.extract rd, rs, len, pos:\n    bfxp rd, rs, zero, pos, len, 0\n\\end{verbatim}\n\n\\subsubsection{RI5CY Instructions {\\tt p.insert} and {\\tt p.insertr}}\n\nThese instructions OR the destination register with the {\\tt len} LSB bits\nfrom the source register, shifted up by {\\tt pos} bits. This can easily\nbe achieved using three instructions and a temporary register {\\tt rt}:\n\n\\begin{verbatim}\n  p.insert rd, rs, len, pos, rt:\n    slli rt, rs, (XLEN-len)\n    srli rt, rt, (XLEN-len-pos)\n    or rd, rd, rt\n\\end{verbatim}\n\nThe {\\tt r}-version of the instruction expects {\\tt len} in bits 9:5 of the\nsecond source register and {\\tt pos} in bits 4:0. Instead we use two registers,\n$\\texttt{rx} = XLEN-pos-len$ and $\\texttt{ry} = XLEN-len$.\n\n\\begin{verbatim}\n  p.insertr:\n    slli rt, rs, ry\n    srli rt, rt, rx\n    or rd, rd, rt\n\\end{verbatim}\n\nAlternatively, instead of packing length and position into a register, we\ncan create a mask in a register and then use this mask with {\\tt bdep}. This\nhas the advantage over the {\\tt sll}+{\\tt srl} sequence that the mask only needs\nto be generated once and can then be re-used many times.\n\n\\begin{verbatim}\n  p.extractur:\n    slo rMask, zero, rLen\n    sll rMask, rMask, rPos\n    bdep rt, rs, rMask\n    or rd, rd, rt\n\\end{verbatim}\n\n{\\tt p.insert} can be efficiently emulated with a single XBitfield {\\tt bfxp}\ninstruction (see Chapter~\\ref{bfxp}), if target region in {\\tt rd} contains\nonly zeros ({\\tt bfxp} clears the target region before performing the OR):\n\n\\begin{verbatim}\n  p.insert rd, rs, len, pos:\n    bfxp rd, rs, rd, 0, len, pos\n\\end{verbatim}\n\n\\subsubsection{RI5CY Instructions {\\tt p.bclr} and {\\tt p.bclrr}}\n\nThese instructions clear {\\tt len} bits starting with bit {\\tt pos}. Using a\ntemporary register {\\tt rt}:\n\n\\begin{verbatim}\n  p.bclr rd, rs, len, pos, rt:\n    sloi rt, zero, len\n    slli rt, rt, pos\n    andn rd, rs, rt\n\\end{verbatim}\n\nOr using two registers {\\tt rLen} and {\\tt rPos}:\n\n\\begin{verbatim}\n  p.bclrr rd, rs, rLen, rPos, rt:\n    slo rt, zero, rLen\n    sll rt, rt, rPos\n    andn rd, rs, rt\n\\end{verbatim}\n\nIf the mask in {\\tt rt} can be pre-computed then a single {\\tt andn} instruction\ncan emulate {\\tt p.bclrr}, or a single {\\tt and}/{\\tt c.and} instruction if the\nmask is already inverted.\n\nOr using {\\tt bfxp} with $\\texttt{rd} = \\texttt{rs}$ (see Chapter~\\ref{bfxp}):\n\n\\begin{verbatim}\n  p.bclr rd, len, pos:\n    bfxp rd, zero, rd, 0, len, pos\n\\end{verbatim}\n\n\\subsubsection{RI5CY Instructions {\\tt p.bset} and {\\tt p.bsetr}}\n\nThese instructions set {\\tt len} bits starting with bit {\\tt pos}. They can be\nimplemented similar to {\\tt p.bclr} and {\\tt p.bclrr} by replacing {\\tt andn}\nwith {\\tt or}:\n\n\\begin{verbatim}\n  p.bset rd, rs, len, pos, rt:\n    sloi rt, zero, len\n    slli rt, rt, pos\n    or rd, rs, rt\n\n  p.bsetr rd, rs, rLen, rPos, rt:\n    slo rt, zero, rLen\n    sll rt, rt, rPos\n    or rd, rs, rt\n\\end{verbatim}\n\nIf the mask in {\\tt rt} can be pre-computed then a single {\\tt or}/{\\tt c.or} instruction\ncan emulate {\\tt p.bsetr}.\n\nOr using {\\tt bfxpc} with $\\texttt{rd} = \\texttt{rs}$ (see Chapter~\\ref{bfxp}):\n\n\\begin{verbatim}\n  p.bset rd, len, pos:\n    bfxpc rd, zero, rd, 0, len, pos\n\\end{verbatim}\n\n\\subsubsection{RI5CY Instructions {\\tt p.ff1}, {\\tt p.cnt}, and {\\tt p.ror}}\n\nThese instructions map directly to the Bitmanip instructions {\\tt ctz}, {\\tt cpop}, and {\\tt ror}.\n\n\\subsubsection{RI5CY Instructions {\\tt p.fl1}}\n\nThis instruction returns the index of the last set bit in {\\tt rs}. If {\\tt rs} is 0, {\\tt rd} will be 0.\n\nUsing the arguably more useful definition that the operation should return -1 when {\\tt rs} is 0:\n\n\\begin{verbatim}\n  p.fl1 rd, rs:\n    clz rd, rs\n    neg rd, rd\n    addi rd, rd, 31\n\\end{verbatim}\n\nConverting a -1 result to 0 to match the exact {\\tt p.fl1} behavior:\n\n\\begin{verbatim}\n    slt rt, rd, zero\n    add rd, rd, rt\n\\end{verbatim}\n\n\\subsubsection{RI5CY Instructions {\\tt p.clb}}\n\nThis instruction counts the number of consecutive 1s or 0s from MSB. If {\\tt rs} is 0, {\\tt rd} will be 0.\n\nUsing the arguably more useful definition that the operation should return XLEN when {\\tt rs} is 0 or -1,\nand assuming {\\tt rd} $\\ne$ {\\tt rs1}:\n\n\\begin{verbatim}\n  p.clb:\n    srai rd, rs, XLEN-1\n    xor rd, rd, rs\n    clz rd, rd\n\\end{verbatim}\n\nSimply add {\\tt andi rd, rd, XLEN-1} if {\\tt rd} should be 0 when {\\tt rs} is 0 or -1.\n\n\\section{Comparison with Cray XMT bit operations}\n\nCray XMT is the 3rd generation of the Cray MTA architecture, a supercomputer\nusing a barrel processor architecture. The Cray XMT instruction set contains\na few bit manipulation instructions~\\cite{CrayXMT}. In this section we compare\nthe Cray XMT bit manipulation instructions with Bitmanip.\n\n\\subsubsection{Bitwise boolean operations}\n\nCray XMT provides the following instructions for bitwise boolean operations:\n{\\tt BIT\\_AND}, {\\tt BIT\\_IMP}, {\\tt BIT\\_NAND}, {\\tt BIT\\_NIMP}, {\\tt\nBIT\\_NOR}, {\\tt BIT\\_OR}, {\\tt BIT\\_XNOR}, and {\\tt BIT\\_XOR}.\n\nThese can trivially emulated using basic RISC-V instructions. (Some of those\nXMT instructions have a direct RISC-V equivalent. The others can be emulated\nby combining the {\\tt not} pseudoinstruction with {\\tt and}, {\\tt or}, or {\\tt xor}.)\n\n\\subsubsection{Count Leading/Trailing Zeros/Ones}\n\nThe Cray XMT instructions {\\tt BIT\\_LEFT\\_ZEORS} and {\\tt BIT\\_RIGHT\\_ZEORS} are\nequivalent to the Bitmanip {\\tt clz} and {\\tt ctz} instructions.\n\nThe {\\tt BIT\\_LEFT\\_ONES} and {\\tt BIT\\_RIGHT\\_ONES} instructions can be emulated\nby combining the {\\tt not} pseudoinstruction with {\\tt clz} and {\\tt ctz}.\n\n\\subsubsection{Mask generation}\n\nThe Cray XMT instruction {\\tt BIT\\_MASK dest top bot} generates a bitmask\nthat has the bits in the range $[\\texttt{bot} \\dots \\texttt{top}]$ set\nand the rest cleared iff $\\texttt{bot} \\le \\texttt{top}$, and those\nbits cleared and the rest set otherwise.\n\nSimilar masks can be generated using two instructions in Bitmanip,\nusing the regular shift instructions and the ``shift ones'' instructions.\n\n\\subsubsection{Cmix equivalent}\n\nThe Cray XMT {\\tt BIT\\_MERGE} instruction is equivalent to the XTernarybits\n{\\tt cmix} instruction, or the {\\tt and-andn-or} MIX pattern.\n\n\\subsubsection{Population count}\n\nThe Cray XMT {\\tt BIT\\_TALLY} instruction and the Bitmanip {\\tt cpop}\ninstruction are equivalent.\n\n\\subsubsection{Parity instructions}\n\nThe Cray XMT {\\tt BIT\\_ODD\\_AND}, {\\tt BIT\\_ODD\\_NIMP}, {\\tt BIT\\_ODD\\_OR},\nand {\\tt BIT\\_ODD\\_XOR} instruction perform the indicated bitwise boolean\noperation and then compute the parity of the result.\n\nWith Bitmanip the parity can be calculated with {\\tt cpop dst, src} followed\nby {\\tt andi dst, dst, 1}.\n\n\\subsubsection{Bit pack/unpack instruction}\n\nThe Cray XMT {\\tt BIT\\_PACK} instruction and the Bitmanip {\\tt bext}\ninstruction are equivalent.\n\nThe Cray XMT {\\tt BIT\\_UNPACK\\_1}, {\\tt BIT\\_UNPACK\\_2}, {\\tt BIT\\_UNPACK\\_3},\ninstruction sequence, when used as intended, is equivalent to the Bitmanip\n{\\tt bdep} instruction.\n\n\\subsubsection{Bit matrix instructions}\n\nThe Cray XMT {\\tt BIT\\_MAT\\_} instructions treat a 64-bit value as a 8x8 bit\nmatrix.\n\n{\\tt BIT\\_MAT\\_TRANSPOSE} is used to transpose such a bit matrix. With\nBitmanip instructions on RV64 this bit permutation can be performed by\napplying the {\\tt zip} operation three times to the register holding the\nmatrix (see also~\\ref{transposebitboard}).\n\nThe Cray XMT instructions {\\tt BIT\\_MAT\\_OR} and {\\tt BIT\\_MAT\\_XOR} perform a\nmatrix-matrix multiply between such bit matrices, where AND replaces scalar\nmultiply and OR/XOR replaces scalar addition.\n\nBitmanip does not provide a similar operation. However, the two example\napplications given in the Cray XMT documentation~\\cite[p.~81]{CrayXMT}\nare reversing the byte order in a word and reversing the bit order in\neach byte. In Bitmanip those operations are performed by the {\\tt bswap}\nand the {\\tt brev.b} {\\tt grevi}-pseudoinstructions.\n\n", "meta": {"hexsha": "edbbadab1baa3880a461f0905d981cfd44574f97", "size": 16161, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "texsrc/compare.tex", "max_stars_repo_name": "tariqkurd-repo/riscv-bitmanip", "max_stars_repo_head_hexsha": "b2fd3b8d7d9e43054358b15b1d77011936addb65", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "texsrc/compare.tex", "max_issues_repo_name": "tariqkurd-repo/riscv-bitmanip", "max_issues_repo_head_hexsha": "b2fd3b8d7d9e43054358b15b1d77011936addb65", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "texsrc/compare.tex", "max_forks_repo_name": "tariqkurd-repo/riscv-bitmanip", "max_forks_repo_head_hexsha": "b2fd3b8d7d9e43054358b15b1d77011936addb65", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4584221748, "max_line_length": 109, "alphanum_fraction": 0.648969742, "num_tokens": 5315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.3005463427108183}}
{"text": "% The LaTeX below is mostly computer-generated (for reasons of speed); don't expect it to be very readable. Sorry.\n\r\n\\documentclass[paper=a4, fontsize=12pt]{scrartcl}%\r\n\\usepackage[T1]{fontenc}\r\n\\usepackage[english]{babel}\r\n\\usepackage{amsmath,amsfonts,amsthm,amssymb}\r\n\\usepackage{mathrsfs}\r\n\\usepackage{sectsty}\r\n\\usepackage{hyperref}\r\n\\usepackage{graphicx}\r\n\\usepackage{framed}\r\n\\usepackage{ifthen}\r\n\\usepackage{lastpage}\r\n\\usepackage[headsepline,footsepline,manualmark]{scrlayer-scrpage}\r\n\\usepackage[height=10in,a4paper,hmargin={1in,0.8in}]{geometry}\r\n\\usepackage[usenames,dvipsnames]{xcolor}\r\n\\usepackage{tikz}\r\n\\usepackage{verbatim}\r\n\\usepackage{amsmath}\r\n\\usepackage{amsfonts}\r\n\\usepackage{amssymb}%\r\n\\setcounter{MaxMatrixCols}{30}\r\n%TCIDATA{OutputFilter=latex2.dll}\r\n%TCIDATA{Version=5.50.0.2960}\r\n%TCIDATA{LastRevised=Thursday, March 04, 2021 01:48:08}\r\n%TCIDATA{<META NAME=\"GraphicsSave\" CONTENT=\"32\">}\r\n%TCIDATA{<META NAME=\"SaveForMode\" CONTENT=\"1\">}\r\n%TCIDATA{BibliographyScheme=Manual}\r\n%BeginMSIPreambleData\r\n\\providecommand{\\U}[1]{\\protect\\rule{.1in}{.1in}}\r\n%EndMSIPreambleData\r\n\\allsectionsfont{\\centering \\normalfont\\scshape}\r\n\\setlength\\parindent{20pt}\r\n\\newcommand{\\CC}{\\mathbb{C}}\r\n\\newcommand{\\RR}{\\mathbb{R}}\r\n\\newcommand{\\QQ}{\\mathbb{Q}}\r\n\\newcommand{\\NN}{\\mathbb{N}}\r\n\\newcommand{\\PP}{\\mathbb{P}}\r\n\\newcommand{\\KK}{\\mathbb{K}}\r\n\\newcommand{\\Z}[1]{\\mathbb{Z}/#1\\mathbb{Z}}\r\n\\newcommand{\\ZZ}{\\mathbb{Z}}\r\n\\newcommand{\\id}{\\operatorname{id}}\r\n\\newcommand{\\lcm}{\\operatorname{lcm}}\r\n\\newcommand{\\set}[1]{\\left\\{ #1 \\right\\}}\r\n\\newcommand{\\abs}[1]{\\left| #1 \\right|}\r\n\\newcommand{\\tup}[1]{\\left( #1 \\right)}\r\n\\newcommand{\\ive}[1]{\\left[ #1 \\right]}\r\n\\newcommand{\\floor}[1]{\\left\\lfloor #1 \\right\\rfloor}\r\n\\newcommand{\\underbrack}[2]{\\underbrace{#1}_{\\substack{#2}}}\r\n\\newcommand{\\powset}[2][]{\\ifthenelse{\\equal{#2}{}}{\\mathcal{P}\\left(#1\\right)}{\\mathcal{P}_{#1}\\left(#2\\right)}}\r\n\\newcommand{\\calF}{\\mathcal{F}}\r\n\\newcommand{\\horrule}[1]{\\rule{\\linewidth}{#1}}\r\n\\newcommand{\\nnn}{\\nonumber\\\\}\r\n\\iffalse\n\\newenvironment{proof}[1][Proof]{\\noindent\\textbf{#1.} }{\\ \\rule{0.5em}{0.5em}}\r\n\\newenvironment{question}[1][Question]{\\noindent\\textbf{#1.} }{\\ \\rule{0.5em}{0.5em}}\r\n\\newenvironment{teachingnote}[1][Teaching note]{\\noindent\\textbf{#1.} }{\\ \\rule{0.5em}{0.5em}}\r\n\\fi\n\\let\\sumnonlimits\\sum\n\\let\\prodnonlimits\\prod\n\\let\\cupnonlimits\\bigcup\n\\let\\capnonlimits\\bigcap\n\\renewcommand{\\sum}{\\sumnonlimits\\limits}\n\\renewcommand{\\prod}{\\prodnonlimits\\limits}\n\\renewcommand{\\bigcup}{\\cupnonlimits\\limits}\n\\renewcommand{\\bigcap}{\\capnonlimits\\limits}\n\\newtheoremstyle{plainsl}\r\n{8pt plus 2pt minus 4pt}\r\n{8pt plus 2pt minus 4pt}\r\n{\\slshape}\r\n{0pt}\r\n{\\bfseries}\r\n{.}\r\n{5pt plus 1pt minus 1pt}\r\n{}\r\n\\theoremstyle{plainsl}\n\\newtheorem{theorem}{Theorem}[section]\r\n\\newtheorem{proposition}[theorem]{Proposition}\r\n\\newtheorem{lemma}[theorem]{Lemma}\r\n\\newtheorem{corollary}[theorem]{Corollary}\r\n\\newtheorem{conjecture}[theorem]{Conjecture}\r\n\\theoremstyle{definition}\n\\newtheorem{definition}[theorem]{Definition}\r\n\\newtheorem{example}[theorem]{Example}\r\n\\newtheorem{exercise}[theorem]{Exercise}\r\n\\newtheorem{examples}[theorem]{Examples}\r\n\\newtheorem{algorithm}[theorem]{Algorithm}\r\n\\newtheorem{question}[theorem]{Question}\r\n\\theoremstyle{remark}\n\\newtheorem{remark}[theorem]{Remark}\r\n\\newenvironment{statement}{\\begin{quote}}{\\end{quote}}\r\n\\newenvironment{fineprint}{\\begin{small}}{\\end{small}}\r\n\\newcommand{\\myname}{Darij Grinberg}\r\n\\newcommand{\\myid}{00000000}\r\n\\newcommand{\\mymail}{dgrinber@umn.edu}\r\n\\newcommand{\\psetnumber}{2}\r\n\\ihead{Solutions to midterm \\#\\psetnumber}\r\n\\ohead{page \\thepage\\ of \\pageref{LastPage}}\r\n\\ifoot{\\myname, \\myid}\r\n\\ofoot{\\mymail}\r\n\\begin{document}\r\n\r\n\\title{ \\normalfont {\\normalsize \\textsc{University of Minnesota, School of\r\nMathematics} }\\\\[25pt] \\rule{\\linewidth}{0.5pt} \\\\[0.4cm] {\\huge Math 4281: Introduction to Modern Algebra, }\\\\Spring 2019: Midterm 2\\\\\\rule{\\linewidth}{2pt} \\\\[0.5cm] }\r\n\\author{Darij Grinberg}\r\n\\maketitle\r\n\r\n%----------------------------------------------------------------------------------------\r\n%\tEXERCISE 1\r\n%----------------------------------------------------------------------------------------\r\n\\rule{0pt}{0.3pt} \\\\[0.4cm]\r\n\r\n\\section{Exercise 1: Not-quite-all-rationals}\r\n\r\n\\subsection{Problem}\r\n\r\nFix an integer $m$. An \\textit{$m$-integer} shall mean a rational number $r$\r\nsuch that there exists a $k \\in\\mathbb{N}$ satisfying $m^{k} r \\in\\mathbb{Z}$.\r\n\r\nFor example\\footnote{You don't need to prove these.}:\r\n\r\n\\begin{itemize}\r\n\\item Each integer $r$ is an $m$-integer (since $m^{k} r \\in\\mathbb{Z}$ for $k\r\n= 0$).\r\n\r\n\\item The rational number $\\dfrac{5}{12}$ is a $6$-integer (since $6^{k}\r\n\\cdot\\dfrac{5}{12} \\in\\mathbb{Z}$ for $k = 2$), but neither a $2$-integer nor\r\na $3$-integer (since multiplying it by a power of $2$ will not ``get rid of''\r\nthe prime factor $3$ in the denominator, and vice versa\\footnote{You would\r\nhave to be more rigorous than this in your solution, if you were to make an\r\nargument like this.}).\r\n\r\n\\item The $1$-integers are the integers (since $1^{k} r = r$ for all $r$).\r\n\r\n\\item Every rational number $r$ is a $0$-integer (since $0^{k} r \\in\r\n\\mathbb{Z}$ for $k = 1$).\r\n\\end{itemize}\r\n\r\nLet $R_{m}$ denote the set of all $m$-integers. Prove the following:\r\n\r\n\\begin{enumerate}\r\n\\item[\\textbf{(a)}] The set $R_{m}$ (endowed with the usual addition, the\r\nusual multiplication, the usual integer $0$ as zero, and the usual integer $1$\r\nas unity) is a commutative ring. \\newline(You don't need to prove axioms like\r\ncommutativity of multiplication, since these follow from the corresponding\r\nfacts about rational numbers, which are well-known. You only need to check\r\nthat $R_{m}$ is closed under addition and multiplication\\footnote{This means\r\nthat every $a, b \\in R_{m}$ satisfy $a + b \\in R_{m}$ and $a b \\in R_{m}$.},\r\nand contains additive inverses of all its elements.)\r\n\r\n\\item[\\textbf{(b)}] Let $x\\in\\mathbb{Q}$ be nonzero. Then, $x\\in R_{m}$ if and\r\nonly if every prime $p$ satisfying $w_{p}\\left(  x\\right)  <0$ satisfies\r\n$p\\mid m$. Here, we are using the notation $w_{p}\\left(  r\\right)  $ defined\r\nin Exercise 3.4.1 of the\r\n\\href{http://www.cip.ifi.lmu.de/~grinberg/t/19s/notes.pdf}{class notes}.\r\n\\end{enumerate}\r\n\r\n\\subsection{Remark}\r\n\r\nRoughly speaking, an $m$-integer is a rational number that can be turned into\r\nan integer by multiplying it with $m$ several times. So a rational number,\r\nwritten as a reduced fraction, is an $m$-integer if and only if a sufficiently\r\nlarge power of $m$ can cancel all the primes in its denominator.\r\n\r\nThe ring $R_{m}$ is an example of a ring \\textquotedblleft between\r\n$\\mathbb{Z}$ and $\\mathbb{Q}$\\textquotedblright. It is commonly denoted by\r\n$\\mathbb{Z}\\left[  \\dfrac{1}{m}\\right]  $ and pronounced \\textquotedblleft%\r\n$\\mathbb{Z}$ adjoined $1$ over $m$\\textquotedblright.\r\n\r\nNote that $R_{1}=\\mathbb{Z}$ and $R_{0}=\\mathbb{Q}$, whereas $R_{2}%\r\n=R_{4}=R_{8}=\\cdots$ is the ring of all rational numbers that can be written\r\nin the form $a/2^{k}$ with $a\\in\\mathbb{Z}$ and $k\\in\\mathbb{N}$.\r\n\r\nThe ring $R_{10}$ is the ring of all\r\n\\textit{\\href{https://en.wikipedia.org/wiki/Decimal}{decimal fractions}} --\r\ni.e., of all rational numbers that can be written in decimal notation with\r\nonly finitely many digits after the comma.\r\n\r\n\\subsection{Solution}\r\n\r\nFor each rational number $r$, we have the following chain of logical\r\nequivalences:%\r\n\\begin{align}\r\n\\left(  r\\in R_{m}\\right)  \\  &  \\Longleftrightarrow\\ \\left(  r\\text{ is an\r\n}m\\text{-integer}\\right)  \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\left(  \\text{since }R_{m}\\text{\r\nis the set of all }m\\text{-integers}\\right) \\nonumber\\\\\r\n&  \\Longleftrightarrow\\ \\left(  \\text{there exists a }k\\in\\mathbb{N}\\text{\r\nsatisfying }m^{k}r\\in\\mathbb{Z}\\right)  \\label{sol.ring.m-int.equiv}%\r\n\\end{align}\r\n(by the definition of an $m$-integer).\r\n\r\n\\bigskip\r\n\r\n\\textbf{(a)} We begin by proving the following claims:\r\n\r\n\\begin{statement}\r\n\\textit{Claim 1:} We have $r\\in R_{m}$ for each integer $r$.\r\n\\end{statement}\r\n\r\n\\begin{statement}\r\n\\textit{Claim 2:} If $a\\in R_{m}$ and $b\\in R_{m}$, then $a+b\\in R_{m}$ and\r\n$a\\cdot b\\in R_{m}$.\r\n\\end{statement}\r\n\r\n\\begin{statement}\r\n\\textit{Claim 3:} If $a\\in R_{m}$, then $-a\\in R_{m}$.\r\n\\end{statement}\r\n\r\n[\\textit{Proof of Claim 1:} Let $r$ be an integer. Then, $\\underbrace{m^{0}%\r\n}_{=1}r=r\\in\\mathbb{Z}$. Hence, there exists a $k\\in\\mathbb{N}$ satisfying\r\n$m^{k}r\\in\\mathbb{Z}$ (namely, $k=0$). But (\\ref{sol.ring.m-int.equiv}) yields\r\nthe equivalence\r\n\\[\r\n\\left(  r\\in R_{m}\\right)  \\ \\Longleftrightarrow\\ \\left(  \\text{there exists a\r\n}k\\in\\mathbb{N}\\text{ satisfying }m^{k}r\\in\\mathbb{Z}\\right)  .\r\n\\]\r\nHence, $r\\in R_{m}$ (since there exists a $k\\in\\mathbb{N}$ satisfying\r\n$m^{k}r\\in\\mathbb{Z}$). This proves Claim 1.]\r\n\r\n[\\textit{Proof of Claim 2:} Let $a\\in R_{m}$ and $b\\in R_{m}$. We must show\r\nthat $a+b\\in R_{m}$ and $a\\cdot b\\in R_{m}$.\r\n\r\nBut (\\ref{sol.ring.m-int.equiv}) (applied to $r=a$) yields the equivalence\r\n\\[\r\n\\left(  a\\in R_{m}\\right)  \\ \\Longleftrightarrow\\ \\left(  \\text{there exists a\r\n}k\\in\\mathbb{N}\\text{ satisfying }m^{k}a\\in\\mathbb{Z}\\right)  .\r\n\\]\r\nHence, there exists a $k\\in\\mathbb{N}$ satisfying $m^{k}a\\in\\mathbb{Z}$ (since\r\n$a\\in R_{m}$). Consider this $k$, and denote it by $x$. Thus, $x\\in\\mathbb{N}$\r\nand $m^{x}a\\in\\mathbb{Z}$.\r\n\r\nFurthermore, (\\ref{sol.ring.m-int.equiv}) (applied to $r=b$) yields the\r\nequivalence\r\n\\[\r\n\\left(  b\\in R_{m}\\right)  \\ \\Longleftrightarrow\\ \\left(  \\text{there exists a\r\n}k\\in\\mathbb{N}\\text{ satisfying }m^{k}b\\in\\mathbb{Z}\\right)  .\r\n\\]\r\nHence, there exists a $k\\in\\mathbb{N}$ satisfying $m^{k}b\\in\\mathbb{Z}$ (since\r\n$b\\in R_{m}$). Consider this $k$, and denote it by $y$. Thus, $y\\in\\mathbb{N}$\r\nand $m^{y}b\\in\\mathbb{Z}$.\r\n\r\nNote that $m^{x}$ is an integer (since $m$ is an integer and $x\\in\\mathbb{N}%\r\n$). In other words, $m^{x}\\in\\mathbb{Z}$. Similarly, $m^{y}\\in\\mathbb{Z}$.\r\n\r\nNow,\r\n\\[\r\n\\underbrace{m^{x+y}}_{=m^{x}m^{y}}\\left(  a+b\\right)  =m^{x}m^{y}\\left(\r\na+b\\right)  =m^{x}m^{y}a+m^{x}m^{y}b=\\underbrace{m^{y}}_{\\in\\mathbb{Z}%\r\n}\\underbrace{m^{x}a}_{\\in\\mathbb{Z}}+\\underbrace{m^{x}}_{\\in\\mathbb{Z}%\r\n}\\underbrace{m^{y}b}_{\\in\\mathbb{Z}}\\in\\mathbb{Z}.\r\n\\]\r\nThus, there exists a $k\\in\\mathbb{N}$ satisfying $m^{k}\\left(  a+b\\right)\r\n\\in\\mathbb{Z}$ (namely, $k=x+y$). (Note that with a little bit more work, we\r\ncould have also shown this for $k=\\max\\left\\{  x,y\\right\\}  $ instead of\r\n$k=x+y$; we were just being lazy.)\r\n\r\nBut (\\ref{sol.ring.m-int.equiv}) (applied to $r=a+b$) yields the equivalence\r\n\\[\r\n\\left(  a+b\\in R_{m}\\right)  \\ \\Longleftrightarrow\\ \\left(  \\text{there exists\r\na }k\\in\\mathbb{N}\\text{ satisfying }m^{k}\\left(  a+b\\right)  \\in\r\n\\mathbb{Z}\\right)  .\r\n\\]\r\nHence, $a+b\\in R_{m}$ (since there exists a $k\\in\\mathbb{N}$ satisfying\r\n$m^{k}\\left(  a+b\\right)  \\in\\mathbb{Z}$).\r\n\r\nFurthermore,%\r\n\\[\r\n\\underbrace{m^{x+y}}_{=m^{x}m^{y}}\\left(  a\\cdot b\\right)  =m^{x}m^{y}\\left(\r\na\\cdot b\\right)  =\\underbrace{m^{x}a}_{\\in\\mathbb{Z}}\\underbrace{m^{y}b}%\r\n_{\\in\\mathbb{Z}}\\in\\mathbb{Z}.\r\n\\]\r\nThus, there exists a $k\\in\\mathbb{N}$ satisfying $m^{k}\\left(  a\\cdot\r\nb\\right)  \\in\\mathbb{Z}$ (namely, $k=x+y$).\r\n\r\nBut (\\ref{sol.ring.m-int.equiv}) (applied to $r=a\\cdot b$) yields the\r\nequivalence\r\n\\[\r\n\\left(  a\\cdot b\\in R_{m}\\right)  \\ \\Longleftrightarrow\\ \\left(  \\text{there\r\nexists a }k\\in\\mathbb{N}\\text{ satisfying }m^{k}\\left(  a\\cdot b\\right)\r\n\\in\\mathbb{Z}\\right)  .\r\n\\]\r\nHence, $a\\cdot b\\in R_{m}$ (since there exists a $k\\in\\mathbb{N}$ satisfying\r\n$m^{k}\\left(  a\\cdot b\\right)  \\in\\mathbb{Z}$).\r\n\r\nWe have now proven that $a+b\\in R_{m}$ and $a\\cdot b\\in R_{m}$. This proves\r\nClaim 2.]\r\n\r\n[\\textit{Proof of Claim 3:} Let $a\\in R_{m}$. We shall show that $-a\\in R_{m}$.\r\n\r\nWe could do this similarly to our proof of Claim 2, but let us take a shortcut\r\ninstead: We have $-1\\in R_{m}$ (by Claim 1, applied to $r=-1$). Hence, Claim 2\r\n(applied to $b=-1$) yields $a+\\left(  -1\\right)  \\in R_{m}$ and $a\\cdot\\left(\r\n-1\\right)  \\in R_{m}$. Now, $-a=a\\cdot\\left(  -1\\right)  \\in R_{m}$. This\r\nproves Claim 3.]\r\n\r\nNow, consider the set $R_{m}$. We have $0\\in R_{m}$ (by Claim 1, applied to\r\n$r=0$) and $1\\in R_{m}$ (by Claim 1, applied to $r=1$). Thus, the set $R_{m}$\r\ncontains the elements $0$ and $1$.\r\n\r\nFurthermore, every $a\\in R_{m}$ and $b\\in R_{m}$ satisfy $a+b\\in R_{m}$ (by\r\nClaim 2). Thus, we can define a binary operation $+$ on the set $R_{m}$ by\r\nrestricting the usual addition $+$ on $\\mathbb{Q}$ to the subset $R_{m}$.\r\n\r\nMoreover, every $a\\in R_{m}$ and $b\\in R_{m}$ satisfy $a\\cdot b\\in R_{m}$ (by\r\nClaim 2). Thus, we can define a binary operation $\\cdot$ on the set $R_{m}$ by\r\nrestricting the usual multiplication $\\cdot$ on $\\mathbb{Q}$ to the subset\r\n$R_{m}$.\r\n\r\nNow, the exercise demands us to prove that the set $R_{m}$ equipped with these\r\ntwo binary operations $+$ and $\\cdot$ and the two elements $0$ and $1$ is a\r\ncommutative ring. In order to do so, we must verify that the ring axioms and\r\nthe \\textquotedblleft Commutativity of multiplication\\textquotedblright\\ axiom\r\nare satisfied.\r\n\r\nBut all of these axioms, except for the \\textquotedblleft Existence of\r\nadditive inverses\\textquotedblright\\ axiom, are clearly satisfied because they\r\nare satisfied for $\\mathbb{Q}$ (and because our $R_{m}$ is a subset of\r\n$\\mathbb{Q}$, and because we endowed $R_{m}$ with operations $+$ and $\\cdot$\r\nthat are restrictions of the corresponding operations of $\\mathbb{Q}$). It\r\nthus remains to prove that the \\textquotedblleft Existence of additive\r\ninverses\\textquotedblright\\ axiom is satisfied.\r\n\r\nBut this is easy: If $a\\in R_{m}$, then $-a\\in R_{m}$ (by Claim 3), and thus\r\nthere exists an element $a^{\\prime}\\in R_{m}$ satisfying $a+a^{\\prime\r\n}=a^{\\prime}+a=0$ (namely, $a^{\\prime}=-a$).\r\n\r\nThus, we have proven that $R_{m}$ is a commutative ring. This solves part\r\n\\textbf{(a)} of the exercise.\r\n\r\n\\bigskip\r\n\r\n\\textbf{(b)} From (\\ref{sol.ring.m-int.equiv}) (applied to $r=x$), we obtain\r\nthe logical equivalence\r\n\\[\r\n\\left(  x\\in R_{m}\\right)  \\ \\Longleftrightarrow\\ \\left(  \\text{there exists a\r\n}k\\in\\mathbb{N}\\text{ satisfying }m^{k}x\\in\\mathbb{Z}\\right)  .\r\n\\]\r\nBut Exercise 3.4.2 \\textbf{(d)} in the\r\n\\href{http://www.cip.ifi.lmu.de/~grinberg/t/19s/notes.pdf}{class notes}\r\n(applied to $r=x$) yields the logical equivalence%\r\n\\begin{align*}\r\n&  \\ \\left(  \\text{there exists a }k\\in\\mathbb{N}\\text{ satisfying }m^{k}%\r\nx\\in\\mathbb{Z}\\right) \\\\\r\n&  \\Longleftrightarrow\\ \\left(  \\text{every prime }p\\text{ satisfying }%\r\nw_{p}\\left(  x\\right)  <0\\text{ satisfies }p\\mid m\\right)  .\r\n\\end{align*}\r\nHence, we have the following chain of equivalences:%\r\n\\begin{align*}\r\n\\left(  x\\in R_{m}\\right)  \\  &  \\Longleftrightarrow\\ \\left(  \\text{there\r\nexists a }k\\in\\mathbb{N}\\text{ satisfying }m^{k}x\\in\\mathbb{Z}\\right) \\\\\r\n&  \\Longleftrightarrow\\ \\left(  \\text{every prime }p\\text{ satisfying }%\r\nw_{p}\\left(  x\\right)  <0\\text{ satisfies }p\\mid m\\right)  .\r\n\\end{align*}\r\nThis solves part \\textbf{(b)} of the exercise.\r\n\r\n%----------------------------------------------------------------------------------------\r\n%\tEXERCISE 2\r\n%----------------------------------------------------------------------------------------\r\n\\rule{\\linewidth}{0.3pt} \\\\[0.4cm]\r\n\r\n\\section{Exercise 2: Rings with $x^{2} = x$}\r\n\r\n\\subsection{Problem}\r\n\r\nLet $\\mathbb{K}$ be a ring with the property that\r\n\\begin{equation}\r\nu^{2}=u\\qquad\\text{ for all }u\\in\\mathbb{K}. \\label{eq.exe.ring.xx=x.cond}%\r\n\\end{equation}\r\n\r\n\r\n(Examples of such rings are $\\mathbb{Z}/2$ as well as the \\textquotedblleft\r\npower set\\textquotedblright\\ ring $\\left(  \\mathcal{P}\\left(  S\\right)\r\n,\\triangle,\\cap,\\varnothing,S\\right)  $ constructed from any given set $S$.)\r\n\r\nProve the following:\r\n\r\n\\begin{enumerate}\r\n\\item[\\textbf{(a)}] We have $2x = 0$ for each $x \\in\\mathbb{K}$.\r\n\r\n\\item[\\textbf{(b)}] We have $-x = x$ for each $x \\in\\mathbb{K}$.\r\n\r\n\\item[\\textbf{(c)}] We have $xy = yx$ for all $x, y \\in\\mathbb{K}$. (In other\r\nwords, the ring $\\mathbb{K}$ is commutative.)\r\n\\end{enumerate}\r\n\r\n(As usual, ``$0$'' stands for the zero of the ring $\\mathbb{K}$.)\r\n\r\n[\\textbf{Hint:} For part \\textbf{(a)}, apply \\eqref{eq.exe.ring.xx=x.cond} to\r\n$u=x$ but also to $u=2x=x+x$, and see what comes out. For part \\textbf{(c)},\r\napply \\eqref{eq.exe.ring.xx=x.cond} to $u=x+y$.]\r\n\r\n\\subsection{Remark}\r\n\r\nRings $\\mathbb{K}$ satisfying \\eqref{eq.exe.ring.xx=x.cond} are known as\r\n\\textit{Boolean rings} (although some people do not require them to have a\r\nunity). Thus, the exercise proves various properties of Boolean rings,\r\nincluding the fact that they are always commutative.\r\n\r\nYou might wonder what happens if we replace \\eqref{eq.exe.ring.xx=x.cond} by\r\nthe requirement that\r\n\\begin{equation}\r\nu^{3}=u\\qquad\\text{ for all }u\\in\\mathbb{K}. \\label{eq.exe.ring.xx=x.cond3}%\r\n\\end{equation}\r\nThis no longer leads to $2x=0$ (nor to $3x=0$ as you might perhaps expect).\r\nInstead, it can be shown that $6x=0$ for all $x\\in\\mathbb{K}$. It can also be\r\nshown that it leads to $xy=yx$. See, for example,\r\n\\url{https://math.stackexchange.com/questions/67148} .\r\n\r\nMore generally, fix an integer $n\\geq2$, and replace\r\n\\eqref{eq.exe.ring.xx=x.cond} by the requirement that\r\n\\begin{equation}\r\nu^{n}=u\\qquad\\text{ for all }u\\in\\mathbb{K}. \\label{eq.exe.ring.xx=x.condn}%\r\n\\end{equation}\r\nThen, it still can be proven that $\\mathbb{K}$ is commutative! See\r\n\\url{https://mathoverflow.net/questions/29590/} for this result.\r\n\r\nEven more generally, we don't need to fix $n$ in advance! In other words,\r\ninstead of requiring \\eqref{eq.exe.ring.xx=x.cond} or\r\n\\eqref{eq.exe.ring.xx=x.cond3} or \\eqref{eq.exe.ring.xx=x.condn}, we merely\r\nrequire that for each $u\\in\\mathbb{K}$, there exists an integer $n\\geq2$\r\n(which may depend on $u$) such that $u^{n}=u$. This is a more general setting;\r\nnevertheless it still follows that $\\mathbb{K}$ is commutative! This is a\r\nresult of Jacobson; see \\cite{Rogers71} for a proof.\r\n\r\n\\subsection{Solution}\r\n\r\n\\textbf{(a)} \\textit{First solution to part \\textbf{(a)}:} Let $x\\in\r\n\\mathbb{K}$. Then, \\eqref{eq.exe.ring.xx=x.cond} (applied to $u=x$) yields\r\n$x^{2}=x$. But \\eqref{eq.exe.ring.xx=x.cond} (applied to $u=x+x$) yields\r\n$\\left(  x+x\\right)  ^{2}=x+x=2x$. Thus,%\r\n\\begin{align*}\r\n2x  &  =x+x=\\left(  x+x\\right)  ^{2}=\\left(  x+x\\right)  \\left(  x+x\\right) \\\\\r\n&  =\\underbrace{x\\left(  x+x\\right)  }_{\\substack{=xx+xx\\\\\\text{(by\r\ndistributivity)}}}+\\underbrace{x\\left(  x+x\\right)  }%\r\n_{\\substack{=xx+xx\\\\\\text{(by distributivity)}}}\\qquad\\left(  \\text{by\r\ndistributivity}\\right) \\\\\r\n&  =xx+xx+xx+xx=4\\underbrace{xx}_{=x^{2}=x}=4x.\r\n\\end{align*}\r\nSubtracting $2x$ from both sides of this equality, we obtain $0=4x-2x=2x$.\r\nHence, $2x=0$. This solves part \\textbf{(a)} of the exercise.\r\n\r\n\\textit{Second solution to part \\textbf{(a)}:} Let $x\\in\\mathbb{K}$. Then,\r\n\\eqref{eq.exe.ring.xx=x.cond} (applied to $u=x$) yields $x^{2}=x$. But\r\n\\eqref{eq.exe.ring.xx=x.cond} (applied to $u=-x$) yields $\\left(  -x\\right)\r\n^{2}=-x$. Hence,%\r\n\\[\r\n-x=\\left(  -x\\right)  ^{2}=\\left(  -x\\right)  \\left(  -x\\right)\r\n=-\\underbrace{\\left(  x\\cdot\\left(  -x\\right)  \\right)  }_{=-\\left(\r\nxx\\right)  }=-\\left(  -\\left(  xx\\right)  \\right)  =xx=x^{2}=x.\r\n\\]\r\nAdding $x$ to both sides of this equality, we find $\\left(  -x\\right)\r\n+x=x+x=2x$. Thus, $2x=\\left(  -x\\right)  +x=0$. This solves part \\textbf{(a)}\r\nof the exercise.\r\n\r\n\\bigskip\r\n\r\n\\textbf{(b)} \\textit{First solution to part \\textbf{(b)}:} Let $x\\in\r\n\\mathbb{K}$. Part \\textbf{(a)} of this exercise yields $2x=0$. Subtracting $x$\r\nfrom both sides of this equality, we obtain $2x-x=0-x=-x$. Hence,\r\n$-x=\\underbrace{2x}_{=x+x}-x=\\left(  x+x\\right)  -x=x$. This solves part\r\n\\textbf{(b)} of this exercise.\r\n\r\n\\textit{Second solution to part \\textbf{(b)}:} Let $x\\in\\mathbb{K}$. We have\r\nalready shown the equality $-x=x$ in our Second solution to part \\textbf{(a)}.\r\nThus, part \\textbf{(b)} of the exercise is solved.\r\n\r\n\\bigskip\r\n\r\n\\textbf{(c)} Let $x,y\\in\\mathbb{K}$. Then, \\eqref{eq.exe.ring.xx=x.cond}\r\n(applied to $u=x$) yields $x^{2}=x$. Also, \\eqref{eq.exe.ring.xx=x.cond}\r\n(applied to $u=y$) yields $y^{2}=y$. But \\eqref{eq.exe.ring.xx=x.cond}\r\n(applied to $u=x+y$) yields $\\left(  x+y\\right)  ^{2}=x+y$. Hence,%\r\n\\begin{align*}\r\nx+y  &  =\\left(  x+y\\right)  ^{2}=\\left(  x+y\\right)  \\left(  x+y\\right) \\\\\r\n&  =\\underbrace{x\\left(  x+y\\right)  }_{\\substack{=xx+xy\\\\\\text{(by\r\ndistributivity)}}}+\\underbrace{y\\left(  x+y\\right)  }%\r\n_{\\substack{=yx+yy\\\\\\text{(by distributivity)}}}\\qquad\\left(  \\text{by\r\ndistributivity}\\right) \\\\\r\n&  =\\underbrace{xx}_{=x^{2}=x}+xy+yx+\\underbrace{yy}_{=y^{2}=y}=x+xy+yx+y.\r\n\\end{align*}\r\nSubtracting $x+y$ from both sides of this equality, we obtain%\r\n\\[\r\n0=\\left(  x+xy+yx+y\\right)  -\\left(  x+y\\right)  =xy+yx.\r\n\\]\r\nThus, $xy=-yx$. But part \\textbf{(b)} of this exercise (applied to $yx$\r\ninstead of $x$) yields $-yx=yx$. Hence, $xy=-yx=yx$. This solves part\r\n\\textbf{(c)} of the exercise.\r\n\r\n%----------------------------------------------------------------------------------------\r\n%\tEXERCISE 3\r\n%----------------------------------------------------------------------------------------\r\n\\rule{\\linewidth}{0.3pt} \\\\[0.4cm]\r\n\r\n\\section{Exercise 3: A matrix of gcds}\r\n\r\n\\subsection{Problem}\r\n\r\nIn this exercise, we shall again use\r\n\\href{https://en.wikipedia.org/wiki/Iverson_bracket}{the \\textit{Iverson\r\nbracket notation}}:\r\n\r\nLet $n \\in\\mathbb{N}$. Let $G$ be the $n \\times n$-matrix\r\n\\[\r\n\\left(  \\gcd\\left(  i, j \\right)  \\right)  _{1 \\leq i \\leq n, \\ 1 \\leq j \\leq\r\nn } =\r\n\\begin{pmatrix}\r\n\\gcd\\left(  1, 1 \\right)  & \\gcd\\left(  1, 2 \\right)  & \\cdots & \\gcd\\left(\r\n1, n \\right) \\\\\r\n\\gcd\\left(  2, 1 \\right)  & \\gcd\\left(  2, 2 \\right)  & \\cdots & \\gcd\\left(\r\n2, n \\right) \\\\\r\n\\vdots & \\vdots & \\ddots & \\vdots\\\\\r\n\\gcd\\left(  n, 1 \\right)  & \\gcd\\left(  n, 2 \\right)  & \\cdots & \\gcd\\left(\r\nn, n \\right)\r\n\\end{pmatrix}\r\n.\r\n\\]\r\n\r\n\r\nLet $L$ be the $n \\times n$-matrix\r\n\\[\r\n\\left(  \\left[  j \\mid i \\right]  \\right)  _{1 \\leq i \\leq n, \\ 1 \\leq j \\leq\r\nn } =\r\n\\begin{pmatrix}\r\n\\left[  1 \\mid1 \\right]  & \\left[  2 \\mid1 \\right]  & \\cdots & \\left[  n \\mid1\r\n\\right] \\\\\r\n\\left[  1 \\mid2 \\right]  & \\left[  2 \\mid2 \\right]  & \\cdots & \\left[  n \\mid2\r\n\\right] \\\\\r\n\\vdots & \\vdots & \\ddots & \\vdots\\\\\r\n\\left[  1 \\mid n \\right]  & \\left[  2 \\mid n \\right]  & \\cdots & \\left[  n\r\n\\mid n \\right]\r\n\\end{pmatrix}\r\n.\r\n\\]\r\n\r\n\r\nLet $D$ be the $n \\times n$-matrix\r\n\\[\r\n\\left(  \\left[  i = j \\right]  \\phi\\left(  i \\right)  \\right)  _{1 \\leq i \\leq\r\nn, \\ 1 \\leq j \\leq n } =\r\n\\begin{pmatrix}\r\n\\phi\\left(  1 \\right)  & 0 & 0 & \\cdots & 0\\\\\r\n0 & \\phi\\left(  2 \\right)  & 0 & \\cdots & 0\\\\\r\n0 & 0 & \\phi\\left(  3 \\right)  & \\cdots & 0\\\\\r\n\\vdots & \\vdots & \\vdots & \\ddots & \\vdots\\\\\r\n0 & 0 & 0 & \\cdots & \\phi\\left(  n \\right)\r\n\\end{pmatrix}\r\n.\r\n\\]\r\n\r\n\r\nProve that\\footnote{We are using the standard notation $A^{T}$ for the\r\n\\textit{transpose} of a matrix $A$. This transpose is defined as follows: If\r\n$A = \\left(  a_{i, j} \\right)  _{1 \\leq i \\leq n, \\ 1 \\leq j \\leq m }$, then\r\n$A^{T} = \\left(  a_{j, i} \\right)  _{1 \\leq i \\leq m, \\ 1 \\leq j \\leq n }$.}\r\n$G = LDL^{T}$.\r\n\r\n\\subsection{Remark}\r\n\r\nAs the names suggest, the matrix $L$ is lower-triangular\\footnote{because two\r\npositive integers $i$ and $j$ satisfying $i<j$ always satisfy $\\left[  j\\mid\r\ni\\right]  =0$} (so that the matrix $L^{T}$ is upper-triangular), and the\r\nmatrix $D$ is diagonal. Thus, $G=LDL^{T}$ is an instance of an\r\n\\href{https://en.wikipedia.org/wiki/LU_decomposition#LDU_decomposition}{\\textit{LDU\r\ndecomposition}}.\r\n\r\nThe matrix $G$ is an example of what is called a \\textit{gcd-matrix} (duh);\r\nsee, e.g., \\url{https://math.stackexchange.com/questions/1278871} for some\r\nreferences on it.\r\n\r\n\\subsection{Solution}\r\n\r\nWe recall the following fundamental property of matrices in general:\r\n\r\n\\begin{lemma}\r\n\\label{lem.sol.matrix.gcd-LDU.row-mult}Let $n,m\\in\\mathbb{N}$. Let\r\n$\\mathbb{K}$ be a ring. Let $\\mathbf{D}=\\left(  \\left[  i=j\\right]\r\nd_{i}\\right)  _{1\\leq i\\leq n,\\ 1\\leq j\\leq n}$ be a diagonal matrix over\r\n$\\mathbb{K}$ (where $d_{1},d_{2},\\ldots,d_{n}$ are $n$ elements of\r\n$\\mathbb{K}$). Let $\\mathbf{A}=\\left(  a_{i,j}\\right)  _{1\\leq i\\leq n,\\ 1\\leq\r\nj\\leq m}$ be an arbitrary $n\\times m$-matrix over $\\mathbb{K}$. Then, the\r\nproduct $\\mathbf{D}\\mathbf{A}$ is simply given by\r\n\\begin{equation}\r\n\\mathbf{D}\\mathbf{A}=\\left(  d_{i}a_{i,j}\\right)  _{1\\leq i\\leq n,\\ 1\\leq\r\nj\\leq m}. \\label{eq.matrix.gcd-LDU.row-mult}%\r\n\\end{equation}\r\n(That is, multiplying a matrix $\\mathbf{A}$ by a diagonal matrix $\\mathbf{D}$\r\non the left is tantamount to rescaling each row of $\\mathbf{A}$ by the\r\ncorresponding diagonal entry of $\\mathbf{D}$.)\r\n\\end{lemma}\r\n\r\n\\begin{proof}\r\n[Proof of Lemma \\ref{lem.sol.matrix.gcd-LDU.row-mult}.]We have $\\mathbf{D}%\r\n=\\left(  \\left[  i=j\\right]  d_{i}\\right)  _{1\\leq i\\leq n,\\ 1\\leq j\\leq n}$\r\nand $\\mathbf{A}=\\left(  a_{i,j}\\right)  _{1\\leq i\\leq n,\\ 1\\leq j\\leq m}$.\r\nHence, the definition of the product of two matrices yields%\r\n\\begin{equation}\r\n\\mathbf{DA}=\\left(  \\sum_{k=1}^{n}\\left[  i=k\\right]  d_{i}a_{k,j}\\right)\r\n_{1\\leq i\\leq n,\\ 1\\leq j\\leq m}. \\label{pf.lem.sol.matrix.gcd-LDU.row-mult.1}%\r\n\\end{equation}\r\nNow, fix some $i\\in\\left\\{  1,2,\\ldots,n\\right\\}  $ and $j\\in\\left\\{\r\n1,2,\\ldots,m\\right\\}  $. Then,%\r\n\\begin{align*}\r\n\\sum_{k=1}^{n}\\left[  i=k\\right]  d_{i}a_{k,j}  &  =\\sum_{k\\in\\left\\{\r\n1,2,\\ldots,n\\right\\}  }\\left[  i=k\\right]  d_{i}a_{k,j}=\\underbrace{\\left[\r\ni=i\\right]  }_{\\substack{=1\\\\\\text{(since }i=i\\text{)}}}d_{i}a_{i,j}%\r\n+\\sum_{\\substack{k\\in\\left\\{  1,2,\\ldots,n\\right\\}  ;\\\\k\\neq i}%\r\n}\\underbrace{\\left[  i=k\\right]  }_{\\substack{=0\\\\\\text{(since }i\\neq\r\nk\\\\\\text{(because }k\\neq i\\text{))}}}d_{i}a_{k,j}\\\\\r\n&  \\qquad\\left(  \\text{here, we have split off the addend for }k=i\\text{ from\r\nthe sum}\\right) \\\\\r\n&  =d_{i}a_{i,j}+\\underbrace{\\sum_{\\substack{k\\in\\left\\{  1,2,\\ldots\r\n,n\\right\\}  ;\\\\k\\neq i}}0d_{i}a_{k,j}}_{=0}=d_{i}a_{i,j}.\r\n\\end{align*}\r\nNow, forget that we fixed $i$ and $j$. We thus have shown that $\\sum_{k=1}%\r\n^{n}\\left[  i=k\\right]  d_{i}a_{k,j}=d_{i}a_{i,j}$ for all $i\\in\\left\\{\r\n1,2,\\ldots,n\\right\\}  $ and $j\\in\\left\\{  1,2,\\ldots,m\\right\\}  $. Therefore,\r\nthe equality \\eqref{pf.lem.sol.matrix.gcd-LDU.row-mult.1} rewrites as\r\n$\\mathbf{D}\\mathbf{A}=\\left(  d_{i}a_{i,j}\\right)  _{1\\leq i\\leq n,\\ 1\\leq\r\nj\\leq m}$. This proves Lemma \\ref{lem.sol.matrix.gcd-LDU.row-mult}.\r\n\\end{proof}\r\n\r\nNow, let us return to solving the exercise.\r\n\r\nRecall that $L=\\left(  \\left[  j\\mid i\\right]  \\right)  _{1\\leq i\\leq\r\nn,\\ 1\\leq j\\leq n}$; thus, the definition of the transpose of a matrix yields\r\n$L^{T}=\\left(  \\left[  i\\mid j\\right]  \\right)  _{1\\leq i\\leq n,\\ 1\\leq j\\leq\r\nn}$. Also, recall that $D=\\left(  \\left[  i=j\\right]  \\phi\\left(  i\\right)\r\n\\right)  _{1\\leq i\\leq n,\\ 1\\leq j\\leq n}$. Hence,\r\n\\eqref{eq.matrix.gcd-LDU.row-mult} (applied to $\\mathbb{K}=\\mathbb{Z}$, $m=n$,\r\n$d_{i}=\\phi\\left(  i\\right)  $, $\\mathbf{D}=D$, $a_{i,j}=\\left[  i\\mid\r\nj\\right]  $ and $\\mathbf{A}=L^{T}$) yields%\r\n\\begin{equation}\r\nDL^{T}=\\left(  \\phi\\left(  i\\right)  \\cdot\\left[  i\\mid j\\right]  \\right)\r\n_{1\\leq i\\leq n,\\ 1\\leq j\\leq n}. \\label{sol.matrix.gcd-LDU.1}%\r\n\\end{equation}\r\n\r\n\r\nNow, we have $L=\\left(  \\left[  j\\mid i\\right]  \\right)  _{1\\leq i\\leq\r\nn,\\ 1\\leq j\\leq n}$ and $DL^{T}=\\left(  \\phi\\left(  i\\right)  \\cdot\\left[\r\ni\\mid j\\right]  \\right)  _{1\\leq i\\leq n,\\ 1\\leq j\\leq n}$. Thus, the\r\ndefinition of the product of two matrices yields%\r\n\\begin{equation}\r\nL\\left(  DL^{T}\\right)  =\\left(  \\sum_{k=1}^{n}\\left[  k\\mid i\\right]\r\n\\cdot\\phi\\left(  k\\right)  \\cdot\\left[  k\\mid j\\right]  \\right)  _{1\\leq i\\leq\r\nn,\\ 1\\leq j\\leq n}. \\label{sol.matrix.gcd-LDU.2}%\r\n\\end{equation}\r\n\r\n\r\nLet us now recall a basic property of the Iverson bracket: If $\\mathcal{A}$\r\nand $\\mathcal{B}$ are two logical statements, then\r\n\\begin{equation}\r\n\\left[  \\mathcal{A}\\wedge\\mathcal{B}\\right]  =\\left[  \\mathcal{A}\\right]\r\n\\cdot\\left[  \\mathcal{B}\\right]  . \\label{sol.matrix.gcd-LDU.iverAB}%\r\n\\end{equation}\r\nFurthermore, if $\\mathcal{A}$ and $\\mathcal{B}$ are two equivalent logical\r\nstatements, then%\r\n\\begin{equation}\r\n\\left[  \\mathcal{A}\\right]  =\\left[  \\mathcal{B}\\right]  .\r\n\\label{sol.matrix.gcd-LDU.iverA=B}%\r\n\\end{equation}\r\n\r\n\r\nNow, fix $i,j\\in\\left\\{  1,2,\\ldots,n\\right\\}  $. Hence, $i$ and $j$ are\r\npositive integers; thus, $\\gcd\\left(  i,j\\right)  $ is a positive integer as\r\nwell. Also, $\\gcd\\left(  i,j\\right)  \\mid i$, so that $\\gcd\\left(  i,j\\right)\r\n\\leq i$ (since $\\gcd\\left(  i,j\\right)  $ and $i$ are positive integers) and\r\ntherefore $\\gcd\\left(  i,j\\right)  \\leq i\\leq n$ (since $i\\in\\left\\{\r\n1,2,\\ldots,n\\right\\}  $).\r\n\r\nTheorem 2.14.6 in the\r\n\\href{http://www.cip.ifi.lmu.de/~grinberg/t/19s/notes.pdf}{class notes}\r\n(applied to $\\gcd\\left(  i,j\\right)  $ instead of $n$) yields%\r\n\\begin{equation}\r\n\\sum_{d\\mid\\gcd\\left(  i,j\\right)  }\\phi\\left(  d\\right)  =\\gcd\\left(\r\ni,j\\right)  . \\label{sol.matrix.gcd-LDU.sum-phi}%\r\n\\end{equation}\r\nHere, the summation sign \\textquotedblleft$\\sum_{d\\mid\\gcd\\left(  i,j\\right)\r\n}$\\textquotedblright\\ means a sum over all positive divisors $d$ of\r\n$\\gcd\\left(  i,j\\right)  $.\r\n\r\nAlso, fix $k\\in\\left\\{  1,2,\\ldots,n\\right\\}  $. Then, Theorem 2.9.15\r\n\\textbf{(a)} in the\r\n\\href{http://www.cip.ifi.lmu.de/~grinberg/t/19s/notes.pdf}{class notes}\r\n(applied to $k$, $i$ and $j$ instead of $a$, $b$ and $m$) shows that we have\r\nthe following logical equivalence:%\r\n\\[\r\n\\left(  k\\mid i\\text{ and }k\\mid j\\right)  \\Longleftrightarrow\\left(\r\nk\\mid\\gcd\\left(  i,j\\right)  \\right)  .\r\n\\]\r\nThus, the logical statements $\\left(  k\\mid\\gcd\\left(  i,j\\right)  \\right)  $\r\nand $\\left(  k\\mid i\\text{ and }k\\mid j\\right)  $ are equivalent. Hence,\r\n\\eqref{sol.matrix.gcd-LDU.iverA=B} (applied to $\\mathcal{A}=\\left(  k\\mid\r\n\\gcd\\left(  i,j\\right)  \\right)  $ and $\\mathcal{B}=\\left(  k\\mid i\\text{ and\r\n}k\\mid j\\right)  $) yields%\r\n\\begin{align}\r\n\\left[  k\\mid\\gcd\\left(  i,j\\right)  \\right]   &  =\\left[  k\\mid i\\text{ and\r\n}k\\mid j\\right]  =\\left[  \\left(  k\\mid i\\right)  \\wedge\\left(  k\\mid\r\nj\\right)  \\right] \\nonumber\\\\\r\n&  =\\left[  k\\mid i\\right]  \\cdot\\left[  k\\mid j\\right]\r\n\\label{sol.matrix.gcd-LDU.3}%\r\n\\end{align}\r\n(by \\eqref{sol.matrix.gcd-LDU.iverAB}, applied to $\\mathcal{A}=\\left(  k\\mid\r\ni\\right)  $ and $\\mathcal{B}=\\left(  k\\mid j\\right)  $).\r\n\r\nNow, forget that we fixed $k$. We thus have proven\r\n\\eqref{sol.matrix.gcd-LDU.3} for each $k\\in\\left\\{  1,2,\\ldots,n\\right\\}  $.\r\nNow,%\r\n\\begin{align}\r\n&  \\sum_{k=1}^{n}\\left[  k\\mid i\\right]  \\cdot\\phi\\left(  k\\right)\r\n\\cdot\\left[  k\\mid j\\right] \\nonumber\\\\\r\n&  =\\underbrace{\\sum_{k=1}^{n}}_{=\\sum_{k\\in\\left\\{  1,2,\\ldots,n\\right\\}  }%\r\n}\\underbrace{\\left[  k\\mid i\\right]  \\cdot\\left[  k\\mid j\\right]\r\n}_{\\substack{=\\left[  k\\mid\\gcd\\left(  i,j\\right)  \\right]  \\\\\\text{(by\r\n\\eqref{sol.matrix.gcd-LDU.3})}}}\\cdot\\phi\\left(  k\\right)  =\\sum_{k\\in\\left\\{\r\n1,2,\\ldots,n\\right\\}  }\\left[  k\\mid\\gcd\\left(  i,j\\right)  \\right]  \\cdot\r\n\\phi\\left(  k\\right) \\nonumber\\\\\r\n&  =\\sum_{\\substack{k\\in\\left\\{  1,2,\\ldots,n\\right\\}  ;\\\\k\\mid\\gcd\\left(\r\ni,j\\right)  }}\\underbrace{\\left[  k\\mid\\gcd\\left(  i,j\\right)  \\right]\r\n}_{\\substack{=1\\\\\\text{(since }k\\mid\\gcd\\left(  i,j\\right)  \\text{)}}%\r\n}\\cdot\\phi\\left(  k\\right)  +\\sum_{\\substack{k\\in\\left\\{  1,2,\\ldots\r\n,n\\right\\}  ;\\\\k\\nmid\\gcd\\left(  i,j\\right)  }}\\underbrace{\\left[  k\\mid\r\n\\gcd\\left(  i,j\\right)  \\right]  }_{\\substack{=0\\\\\\text{(since }k\\nmid\r\n\\gcd\\left(  i,j\\right)  \\text{)}}}\\cdot\\phi\\left(  k\\right) \\nonumber\\\\\r\n&  \\qquad\\left(\r\n\\begin{array}\r\n[c]{c}%\r\n\\text{since each }k\\in\\left\\{  1,2,\\ldots,n\\right\\}  \\text{ satisfies either\r\n}k\\mid\\gcd\\left(  i,j\\right) \\\\\r\n\\text{or }k\\nmid\\gcd\\left(  i,j\\right)  \\text{ (but not both)}%\r\n\\end{array}\r\n\\right) \\nonumber\\\\\r\n&  =\\sum_{\\substack{k\\in\\left\\{  1,2,\\ldots,n\\right\\}  ;\\\\k\\mid\\gcd\\left(\r\ni,j\\right)  }}\\phi\\left(  k\\right)  +\\underbrace{\\sum_{\\substack{k\\in\\left\\{\r\n1,2,\\ldots,n\\right\\}  ;\\\\k\\nmid\\gcd\\left(  i,j\\right)  }}0\\cdot\\phi\\left(\r\nk\\right)  }_{=0}=\\sum_{\\substack{k\\in\\left\\{  1,2,\\ldots,n\\right\\}\r\n;\\\\k\\mid\\gcd\\left(  i,j\\right)  }}\\phi\\left(  k\\right) \\nonumber\\\\\r\n&  =\\sum_{\\substack{d\\in\\left\\{  1,2,\\ldots,n\\right\\}  ;\\\\d\\mid\\gcd\\left(\r\ni,j\\right)  }}\\phi\\left(  d\\right)  \\label{sol.matrix.gcd-LDU.5}%\r\n\\end{align}\r\n(here, we have renamed the summation index $k$ as $d$).\r\n\r\nBut each positive divisor of $\\gcd\\left(  i,j\\right)  $ is $\\leq\\gcd\\left(\r\ni,j\\right)  $ and therefore $\\leq n$ (since $\\gcd\\left(  i,j\\right)  \\leq n$).\r\nThus, each positive divisor of $\\gcd\\left(  i,j\\right)  $ belongs to the set\r\n$\\left\\{  1,2,\\ldots,n\\right\\}  $. Hence, each positive divisor of\r\n$\\gcd\\left(  i,j\\right)  $ is a $d\\in\\left\\{  1,2,\\ldots,n\\right\\}  $\r\nsatisfying $d\\mid\\gcd\\left(  i,j\\right)  $. In other words,%\r\n\\[\r\n\\left\\{  \\text{positive divisors of }\\gcd\\left(  i,j\\right)  \\right\\}\r\n\\subseteq\\left\\{  d\\in\\left\\{  1,2,\\ldots,n\\right\\}  \\text{ such that }%\r\nd\\mid\\gcd\\left(  i,j\\right)  \\right\\}  .\r\n\\]\r\nCombining this with the relation%\r\n\\[\r\n\\left\\{  d\\in\\left\\{  1,2,\\ldots,n\\right\\}  \\text{ such that }d\\mid\\gcd\\left(\r\ni,j\\right)  \\right\\}  \\subseteq\\left\\{  \\text{positive divisors of }%\r\n\\gcd\\left(  i,j\\right)  \\right\\}\r\n\\]\r\n(which is obvious), we obtain%\r\n\\[\r\n\\left\\{  d\\in\\left\\{  1,2,\\ldots,n\\right\\}  \\text{ such that }d\\mid\\gcd\\left(\r\ni,j\\right)  \\right\\}  =\\left\\{  \\text{positive divisors of }\\gcd\\left(\r\ni,j\\right)  \\right\\}  .\r\n\\]\r\nThus, the summation sign \\textquotedblleft$\\sum_{\\substack{d\\in\\left\\{\r\n1,2,\\ldots,n\\right\\}  ;\\\\d\\mid\\gcd\\left(  i,j\\right)  }}$\\textquotedblright%\r\n\\ is equivalent to \\textquotedblleft$\\sum_{d\\mid\\gcd\\left(  i,j\\right)  }%\r\n$\\textquotedblright\\ (since the latter summation sign means a sum over all\r\npositive divisors of $\\gcd\\left(  i,j\\right)  $). Hence,\r\n\\eqref{sol.matrix.gcd-LDU.5} becomes%\r\n\\[\r\n\\sum_{k=1}^{n}\\left[  k\\mid i\\right]  \\cdot\\phi\\left(  k\\right)  \\cdot\\left[\r\nk\\mid j\\right]  =\\underbrace{\\sum_{\\substack{d\\in\\left\\{  1,2,\\ldots\r\n,n\\right\\}  ;\\\\d\\mid\\gcd\\left(  i,j\\right)  }}}_{=\\sum_{d\\mid\\gcd\\left(\r\ni,j\\right)  }}\\phi\\left(  d\\right)  =\\sum_{d\\mid\\gcd\\left(  i,j\\right)  }%\r\n\\phi\\left(  d\\right)  =\\gcd\\left(  i,j\\right)  \\qquad\\qquad\\left(  \\text{by\r\n\\eqref{sol.matrix.gcd-LDU.sum-phi}}\\right)  .\r\n\\]\r\n\r\n\r\nNow, forget that we fixed $i,j$. We thus have proven that\r\n\\[\r\n\\sum_{k=1}^{n}\\left[  k\\mid i\\right]  \\cdot\\phi\\left(  k\\right)  \\cdot\\left[\r\nk\\mid j\\right]  =\\gcd\\left(  i,j\\right)  \\qquad\\text{for all }i,j\\in\\left\\{\r\n1,2,\\ldots,n\\right\\}  .\r\n\\]\r\nIn other words,%\r\n\\[\r\n\\left(  \\sum_{k=1}^{n}\\left[  k\\mid i\\right]  \\cdot\\phi\\left(  k\\right)\r\n\\cdot\\left[  k\\mid j\\right]  \\right)  _{1\\leq i\\leq n,\\ 1\\leq j\\leq n}=\\left(\r\n\\gcd\\left(  i,j\\right)  \\right)  _{1\\leq i\\leq n,\\ 1\\leq j\\leq n}.\r\n\\]\r\nHence, \\eqref{sol.matrix.gcd-LDU.2} becomes%\r\n\\[\r\nL\\left(  DL^{T}\\right)  =\\left(  \\sum_{k=1}^{n}\\left[  k\\mid i\\right]\r\n\\cdot\\phi\\left(  k\\right)  \\cdot\\left[  k\\mid j\\right]  \\right)  _{1\\leq i\\leq\r\nn,\\ 1\\leq j\\leq n}=\\left(  \\gcd\\left(  i,j\\right)  \\right)  _{1\\leq i\\leq\r\nn,\\ 1\\leq j\\leq n}=G\r\n\\]\r\n(by the definition of $G$). Consequently, $G=L\\left(  DL^{T}\\right)  =LDL^{T}%\r\n$. The exercise is now solved.\r\n\r\n\\subsection{Remark}\r\n\r\nIf you know about determinants, you will easily see how to compute $\\det G$\r\nusing the claim of the exercise. (\\textbf{Hint:} Use the formula $\\det\\left(\r\nAB\\right)  =\\det A\\cdot\\det B$ that holds for any two $n\\times n$-matrices $A$\r\nand $B$ over any commutative ring $\\mathbb{K}$.)\r\n\r\n%----------------------------------------------------------------------------------------\r\n%\tEXERCISE 4\r\n%----------------------------------------------------------------------------------------\r\n\\rule{\\linewidth}{0.3pt} \\\\[0.4cm]\r\n\r\n\\section{Exercise 4: Idempotent and involutive elements}\r\n\r\n\\subsection{Problem}\r\n\r\nLet $\\mathbb{K}$ be a ring.\r\n\r\nAn element $a$ of $\\mathbb{K}$ is said to be \\textit{idempotent} if it\r\nsatisfies $a^{2} = a$.\r\n\r\nAn element $a$ of $\\mathbb{K}$ is said to be \\textit{involutive} if it\r\nsatisfies $a^{2} = 1$.\r\n\r\n\\begin{enumerate}\r\n\\item[\\textbf{(a)}] Let $a \\in\\mathbb{K}$. Prove that if $a$ is idempotent,\r\nthen $1 - 2a$ is involutive.\r\n\r\n\\item[\\textbf{(b)}] Now, assume that $2$ is \\textit{cancellable} in\r\n$\\mathbb{K}$; this means that if $u$ and $v$ are two elements of $\\mathbb{K}$\r\nsatisfying $2u=2v$, then $u=v$. Prove that the converse of the claim of part\r\n\\textbf{(a)} holds: If $a\\in\\mathbb{K}$ is such that $1-2a$ is involutive,\r\nthen $a$ is idempotent.\r\n\r\n\\item[\\textbf{(c)}] Now, let $\\mathbb{K}=\\mathbb{Z}/4$. Find an element\r\n$a\\in\\mathbb{K}$ such that $1-2a$ is involutive, but $a$ is not idempotent.\r\n\\end{enumerate}\r\n\r\n\\subsection{Remark}\r\n\r\nThe idempotent elements of $\\mathbb{R}$ are $0$ and $1$. The involutive\r\nelements of $\\mathbb{R}$ are $1$ and $-1$. A matrix ring like $\\mathbb{R}%\r\n^{n\\times n}$ usually has infinitely many idempotent elements (viz., all\r\nprojection matrices on subspaces of $\\mathbb{R}^{n}$) and infinitely many\r\ninvolutive elements (viz., all matrices $A$ satisfying $A^{2}=I_{n}$; for\r\ninstance, all reflections across hyperplanes are represented by such matrices).\r\n\r\nPart \\textbf{(a)} of this exercise assigns an involutive element to each\r\nidempotent element of $\\mathbb{K}$. If $2$ is invertible in $\\mathbb{K}$ (that\r\nis, if the element $2\\cdot1_{\\mathbb{K}}$ has a multiplicative inverse), then\r\nthis assignment is a bijection (as can be easily derived from part\r\n\\textbf{(b)}). Part \\textbf{(c)} shows that we cannot drop the\r\n\\textquotedblleft$2$ is cancellable\\textquotedblright\\ condition in part\r\n\\textbf{(b)}.\r\n\r\n\\subsection{Solution}\r\n\r\nUsing the ring axioms and the basic rules for rings, it is easy to see that\r\nevery $a\\in\\mathbb{K}$ satisfies%\r\n\\begin{equation}\r\n\\left(  1-2a\\right)  ^{2}=1-4a+4a^{2}. \\label{sol.ring.idp-inv.1}%\r\n\\end{equation}\r\n\r\n\r\n[Here is a more pedantic \\textit{proof} of this fact: Let $a\\in\\mathbb{K}$.\r\nFor any $b\\in\\mathbb{K}$, we have%\r\n\\begin{align*}\r\n\\left(  1+b\\right)  ^{2}  &  =\\left(  1+b\\right)  \\left(  1+b\\right)\r\n=\\underbrace{1\\left(  1+b\\right)  }_{=1+b}+\\underbrace{b\\left(  1+b\\right)\r\n}_{\\substack{=b\\cdot1+b\\cdot b\\\\\\text{(by distributivity)}}}\\qquad\\left(\r\n\\text{by distributivity}\\right) \\\\\r\n&  =1+b+\\underbrace{b\\cdot1}_{=b}+\\underbrace{b\\cdot b}_{=b^{2}}%\r\n=1+b+b+b^{2}=1+2b+b^{2}.\r\n\\end{align*}\r\nApplying this to $b=-2a$, we obtain%\r\n\\begin{align*}\r\n\\left(  1+\\left(  -2a\\right)  \\right)  ^{2}  &  =1+\\underbrace{2\\left(\r\n-2a\\right)  }_{=2\\cdot\\left(  -2\\right)  a}+\\underbrace{\\left(  -2a\\right)\r\n^{2}}_{\\substack{=\\left(  -2a\\right)  \\cdot\\left(  -2a\\right)  \\\\=\\left(\r\n-2\\right)  \\cdot\\left(  -2a\\right)  \\cdot a}}=1+\\underbrace{2\\cdot\\left(\r\n-2\\right)  }_{=-4}a+\\left(  -2\\right)  \\cdot\\underbrace{\\left(  -2a\\right)\r\n}_{=\\left(  -2\\right)  a}\\cdot a\\\\\r\n&  =1+\\underbrace{\\left(  -4\\right)  a}_{=-4a}+\\underbrace{\\left(  -2\\right)\r\n\\cdot\\left(  \\left(  -2\\right)  a\\right)  }_{=\\left(  \\left(  -2\\right)\r\n\\cdot\\left(  -2\\right)  \\right)  \\cdot a}\\cdot a=\\underbrace{1+\\left(\r\n-4a\\right)  }_{=1-4a}+\\underbrace{\\left(  \\left(  -2\\right)  \\cdot\\left(\r\n-2\\right)  \\right)  }_{=4}\\cdot\\underbrace{a\\cdot a}_{=a^{2}}\\\\\r\n&  =1-4a+4a^{2}.\r\n\\end{align*}\r\nIn view of $1+\\left(  -2a\\right)  =1-2a$, this rewrites as $\\left(\r\n1-2a\\right)  ^{2}=1-4a+4a^{2}$. Thus, \\eqref{sol.ring.idp-inv.1} is proven.]\r\n\r\n\\bigskip\r\n\r\n\\textbf{(a)} Assume that $a$ is idempotent. We must prove that $1-2a$ is involutive.\r\n\r\nWe have assumed that $a$ is idempotent. In other words, $a^{2}=a$ (by the\r\ndefinition of \\textquotedblleft idempotent\\textquotedblright). Thus,\r\n\\eqref{sol.ring.idp-inv.1} becomes $\\left(  1-2a\\right)  ^{2}%\r\n=1-4a+4\\underbrace{a^{2}}_{=a}=1-4a+4a=1$. In other words, $1-2a$ is\r\ninvolutive (by the definition of \\textquotedblleft\r\ninvolutive\\textquotedblright). This solves part \\textbf{(a)} of the exercise.\r\n\r\n\\bigskip\r\n\r\n\\textbf{(b)} Let $a\\in\\mathbb{K}$ be such that $1-2a$ is involutive. We must\r\nprove that $a$ is idempotent.\r\n\r\nWe know that $2$ is cancellable in $\\mathbb{K}$. In other words, if $u$ and\r\n$v$ are two elements of $\\mathbb{K}$ satisfying $2u=2v$, then\r\n\\begin{equation}\r\nu=v. \\label{sol.ring.idp-inv.b.u=v}%\r\n\\end{equation}\r\n\r\n\r\nWe have assumed that $1-2a$ is involutive. In other words, $\\left(\r\n1-2a\\right)  ^{2}=1$. Comparing this with \\eqref{sol.ring.idp-inv.1}, we\r\nobtain $1-4a+4a^{2}=1$. Hence, $4a^{2}=1-1+4a=4a$. This rewrites as\r\n$2\\cdot2a^{2}=2\\cdot2a$ (since $\\underbrace{2\\cdot2}_{=4}a^{2}=4a^{2}$ and\r\n$\\underbrace{2\\cdot2}_{=4}a=4a$). Hence, \\eqref{sol.ring.idp-inv.b.u=v}\r\n(applied to $u=2a^{2}$ and $v=2a$) yields $2a^{2}=2a$. Thus,\r\n\\eqref{sol.ring.idp-inv.b.u=v} (applied to $u=a^{2}$ and $v=a$) yields\r\n$a^{2}=a$. In other words, $a$ is idempotent. This solves part \\textbf{(b)} of\r\nthe exercise.\r\n\r\n\\bigskip\r\n\r\n\\textbf{(c)} We claim that $a=\\left[  2\\right]  _{4}$ is such an element.\r\nIndeed, $1-2\\cdot\\left[  2\\right]  _{4}$ is involutive\\footnote{Keep in mind\r\nthat the \\textquotedblleft$1$\\textquotedblright\\ here stands for the unity of\r\nthe ring $\\mathbb{K}=\\mathbb{Z}/4$; this is the residue class $\\left[\r\n1\\right]  _{4}$.} (since $\\underbrace{1}_{=\\left[  1\\right]  _{4}%\r\n}-\\underbrace{2\\cdot\\left[  2\\right]  _{4}}_{=\\left[  2\\cdot2\\right]\r\n_{4}=\\left[  4\\right]  _{4}=\\left[  0\\right]  _{4}}=\\left[  1\\right]\r\n_{4}-\\left[  0\\right]  _{4}=\\left[  1\\right]  _{4}$ and thus $\\left(\r\n1-2\\cdot\\left[  2\\right]  _{4}\\right)  ^{2}=\\left(  \\left[  1\\right]\r\n_{4}\\right)  ^{2}=\\left[  1^{2}\\right]  _{4}=\\left[  1\\right]  _{4}=1$), but\r\n$\\left[  2\\right]  _{4}$ is not idempotent (since $\\left(  \\left[  2\\right]\r\n_{4}\\right)  ^{2}=\\left[  2^{2}\\right]  _{4}=\\left[  4\\right]  _{4}\\neq\\left[\r\n2\\right]  _{4}$).\r\n\r\n%----------------------------------------------------------------------------------------\r\n%\tEXERCISE 5\r\n%----------------------------------------------------------------------------------------\r\n\\rule{\\linewidth}{0.3pt} \\\\[0.4cm]\r\n\r\n\\section{Exercise 5: The matrix approach to Fibonacci numbers}\r\n\r\n\\subsection{Problem}\r\n\r\nLet $A$ be the $2 \\times2$-matrix $%\r\n\\begin{pmatrix}\r\n0 & 1\\\\\r\n1 & 1\r\n\\end{pmatrix}\r\n$ over $\\mathbb{Z}$. Consider also the identity matrix $I_{2} \\in\\mathbb{Z}^{2\r\n\\times2}$.\r\n\r\nLet $\\mathcal{F}$ be the subset\r\n\\[\r\n\\left\\{  aA+bI_{2}\\mid a,b\\in\\mathbb{Z}\\right\\}  =\\left\\{\r\n\\begin{pmatrix}\r\nb & a\\\\\r\na & a+b\r\n\\end{pmatrix}\r\n\\mid a,b\\in\\mathbb{Z}\\right\\}\r\n\\]\r\nof the matrix ring $\\mathbb{Z}^{2\\times2}$.\r\n\r\n\\begin{enumerate}\r\n\\item[\\textbf{(a)}] Prove that $A^{2} = A + I_{2}$.\r\n\r\n\\item[\\textbf{(b)}] Prove that the set $\\mathcal{F}$ (equipped with the\r\naddition of matrices, the multiplication of matrices, the zero $0_{2 \\times2}$\r\nand the unity $I_{2}$) is a commutative ring. \\newline(Again, you don't need\r\nto check the ring axioms, as we already know that they hold for arbitrary\r\nmatrices and thus all the more for matrices in $\\mathcal{F}$. But you do need\r\nto check commutativity of multiplication in $\\mathcal{F}$, since it does not\r\nhold for arbitrary matrices. You also need to check that $\\mathcal{F}$ is\r\nclosed under addition and multiplication and has additive inverses.)\r\n\\end{enumerate}\r\n\r\nLet $\\left(  f_{0},f_{1},f_{2},\\ldots\\right)  $ be the Fibonacci sequence\r\n(which we have already encountered on\r\n\\href{http://www.cip.ifi.lmu.de/~grinberg/t/19s/hw5s.pdf}{homework set \\#5}).\r\nRecall that it is defined recursively by\r\n\\[\r\nf_{0}=0,\\qquad f_{1}=1,\\qquad\\text{and}\\qquad f_{n}=f_{n-1}+f_{n-2}\\text{ for\r\nall }n\\geq2.\r\n\\]\r\n\r\n\r\n\\begin{enumerate}\r\n\\item[\\textbf{(c)}] Prove that $A^{n} = f_{n} A + f_{n-1} I_{2}$ for all\r\npositive integers $n$.\r\n\r\n\\item[\\textbf{(d)}] Prove that $f_{n+m}=f_{n}f_{m+1}+f_{n-1}f_{m}$ for all\r\npositive integers $n$ and all $m\\in\\mathbb{N}$.\r\n\\end{enumerate}\r\n\r\nNow, define a further matrix $B \\in\\mathcal{F}$ by $B = \\left(  -1 \\right)  A\r\n+ 1I_{2} = I_{2} - A$.\r\n\r\n\\begin{enumerate}\r\n\\item[\\textbf{(e)}] Prove that $B^{2} = B + I_{2}$ and $B^{n} = f_{n} B +\r\nf_{n-1} I_{2}$ for all positive integers $n$.\r\n\r\n\\item[\\textbf{(f)}] Prove that $A^{n} - B^{n} = f_{n} \\left(  A - B \\right)  $\r\nfor all $n \\in\\mathbb{N}$.\r\n\r\n\\item[\\textbf{(g)}] Prove (again!) that $f_{d}\\mid f_{dn}$ for any nonnegative\r\nintegers $d$ and $n$.\r\n\\end{enumerate}\r\n\r\n[\\textbf{Hint:} One way to prove \\textbf{(d)} is by comparing the $\\left(  1,\r\n1 \\right)  $-th entries of the two (equal) matrices $A^{n} A^{m+1}$ and\r\n$A^{n+m+1}$, after first using part \\textbf{(c)} to expand these matrices.\r\n\r\nFor part \\textbf{(g)}, compare the $\\left(  1, 1 \\right)  $-th entries of the\r\nmatrices $A^{d} - B^{d}$ and $A^{dn} - B^{dn}$, after first proving that\r\n$A^{d} - B^{d} \\mid A^{dn} - B^{dn}$ in the commutative ring $\\mathcal{F}$.\r\nNote that divisibility is a tricky concept in general rings, but $\\mathcal{F}$\r\nis a commutative ring, which lets many arguments from the integer setting go\r\nthrough unchanged.]\r\n\r\n\\subsection{Remark}\r\n\r\nContrast the ring $\\mathcal{F}$ with the ring $\\mathbb{Z}\\left[  \\phi\\right]\r\n$ from Exercise 5 on\r\n\\href{http://www.cip.ifi.lmu.de/~grinberg/t/19s/hw5s.pdf}{homework set \\#5}.\r\nBoth of these rings, as we see, can be used to prove that $f_{d}\\mid f_{dn}$\r\nfor any nonnegative integers $d$ and $n$. It turns out that these rings have\r\nmore in common: they are isomorphic! More precisely, the map%\r\n\\begin{align*}\r\n\\mathbb{Z}\\left[  \\phi\\right]   &  \\rightarrow\\mathcal{F},\\\\\r\na+b\\phi &  \\mapsto bA+aI_{2}\\qquad\\left(  \\text{for }a,b\\in\\mathbb{Z}\\right)\r\n\\end{align*}\r\nis a ring isomorphism. This makes it less surprising that these rings can\r\nsubstitute for one another in proving $f_{d}\\mid f_{dn}$.\r\n\r\n\\subsection{Solution sketch}\r\n\r\nWe first recall that $\\mathcal{F}=\\left\\{  aA+bI_{2}\\mid a,b\\in\\mathbb{Z}%\r\n\\right\\}  $ (by the definition of $\\mathcal{F}$). Hence,%\r\n\\begin{equation}\r\naA+bI_{2}\\in\\mathcal{F}\\qquad\\text{for all }a,b\\in\\mathbb{Z}.\r\n\\label{sol.ring.fibonacci.F.aA+binF}%\r\n\\end{equation}\r\n\r\n\r\n\\bigskip\r\n\r\n\\textbf{(a)} This is an easy exercise in multiplying matrices: From $A=%\r\n\\begin{pmatrix}\r\n0 & 1\\\\\r\n1 & 1\r\n\\end{pmatrix}\r\n$, we obtain%\r\n\\[\r\nA^{2}=%\r\n\\begin{pmatrix}\r\n0 & 1\\\\\r\n1 & 1\r\n\\end{pmatrix}\r\n^{2}=%\r\n\\begin{pmatrix}\r\n0 & 1\\\\\r\n1 & 1\r\n\\end{pmatrix}%\r\n\\begin{pmatrix}\r\n0 & 1\\\\\r\n1 & 1\r\n\\end{pmatrix}\r\n=%\r\n\\begin{pmatrix}\r\n1 & 1\\\\\r\n1 & 2\r\n\\end{pmatrix}\r\n.\r\n\\]\r\nComparing this with%\r\n\\[\r\n\\underbrace{A}_{=%\r\n\\begin{pmatrix}\r\n0 & 1\\\\\r\n1 & 1\r\n\\end{pmatrix}\r\n}+\\underbrace{I_{2}}_{=%\r\n\\begin{pmatrix}\r\n1 & 0\\\\\r\n0 & 1\r\n\\end{pmatrix}\r\n}=%\r\n\\begin{pmatrix}\r\n0 & 1\\\\\r\n1 & 1\r\n\\end{pmatrix}\r\n+%\r\n\\begin{pmatrix}\r\n1 & 0\\\\\r\n0 & 1\r\n\\end{pmatrix}\r\n=%\r\n\\begin{pmatrix}\r\n1 & 1\\\\\r\n1 & 2\r\n\\end{pmatrix}\r\n,\r\n\\]\r\nwe obtain $A^{2}=A+I_{2}$. This solves part \\textbf{(a)} of the exercise.\r\n\r\n\\bigskip\r\n\r\n\\textbf{(b)} Let us show the following claims:\r\n\r\n\\begin{statement}\r\n\\textit{Claim 1:} We have $0_{2\\times2}\\in\\mathcal{F}$.\r\n\\end{statement}\r\n\r\n\\begin{statement}\r\n\\textit{Claim 2:} We have $I_{2}\\in\\mathcal{F}$.\r\n\\end{statement}\r\n\r\n\\begin{statement}\r\n\\textit{Claim 3:} For any $U,V\\in\\mathcal{F}$, we have $U+V\\in\\mathcal{F}$ and\r\n$UV\\in\\mathcal{F}$ and $UV=VU$.\r\n\\end{statement}\r\n\r\n\\begin{statement}\r\n\\textit{Claim 4:} For any $U\\in\\mathcal{F}$, we have $-U\\in\\mathcal{F}$.\r\n\\end{statement}\r\n\r\n[\\textit{Proof of Claim 1:} We have $\\underbrace{0A}_{=0_{2\\times2}%\r\n}+\\underbrace{0I_{2}}_{=0_{2\\times2}}=0_{2\\times2}$, so that $0_{2\\times\r\n2}=0A+0I_{2}\\in\\mathcal{F}$ (by \\eqref{sol.ring.fibonacci.F.aA+binF}, applied\r\nto $a=0$ and $b=0$). This proves Claim 1.]\r\n\r\n[\\textit{Proof of Claim 2:} We have $\\underbrace{0A}_{=0_{2\\times2}%\r\n}+\\underbrace{1I_{2}}_{=I_{2}}=I_{2}$, so that $I_{2}=0A+1I_{2}\\in\\mathcal{F}$\r\n(by \\eqref{sol.ring.fibonacci.F.aA+binF}, applied to $a=0$ and $b=1$). This\r\nproves Claim 2.]\r\n\r\n[\\textit{Proof of Claim 3:} Let $U,V\\in\\mathcal{F}$. We must prove that\r\n$U+V\\in\\mathcal{F}$ and $UV\\in\\mathcal{F}$ and $UV=VU$.\r\n\r\nWe have $V\\in\\mathcal{F}=\\left\\{  aA+bI_{2}\\mid a,b\\in\\mathbb{Z}\\right\\}\r\n=\\left\\{  cA+dI_{2}\\mid c,d\\in\\mathbb{Z}\\right\\}  $ (here, we have renamed the\r\nindices $a$ and $b$ as $c$ and $d$). In other words, there exist some\r\n$c,d\\in\\mathbb{Z}$ such that $V=cA+dI_{2}$. Consider these $c,d$.\r\n\r\nWe have $U\\in\\mathcal{F}=\\left\\{  aA+bI_{2}\\mid a,b\\in\\mathbb{Z}\\right\\}  $.\r\nIn other words, there exist some $a,b\\in\\mathbb{Z}$ such that $U=aA+bI_{2}$.\r\nConsider these $a,b$.\r\n\r\nFrom $a,b,c,d\\in\\mathbb{Z}$, we obtain $a+c\\in\\mathbb{Z}$ and $b+d\\in\r\n\\mathbb{Z}$ and $ad+bc+ac\\in\\mathbb{Z}$ and $ac+bd\\in\\mathbb{Z}$.\r\n\r\nWe have $a,b,c,d\\in\\mathbb{Z}$. Adding the equalities $U=aA+bI_{2}$ and\r\n$V=cA+dI_{2}$ together, we obtain%\r\n\\[\r\nU+V=\\left(  aA+bI_{2}\\right)  +\\left(  cA+dI_{2}\\right)  =\\left(  a+c\\right)\r\nA+\\left(  b+d\\right)  I_{2}\\in\\mathcal{F}%\r\n\\]\r\n(by \\eqref{sol.ring.fibonacci.F.aA+binF}, applied to $a+c$ and $b+d$ instead\r\nof $a$ and $b$).\r\n\r\nWe have $AA=A^{2}=A+I_{2}$ (by part \\textbf{(a)} of the exercise).\r\n\r\nMultiplying the equalities $U=aA+bI_{2}$ and $V=cA+dI_{2}$ together, we obtain%\r\n\\begin{align*}\r\nUV  &  =\\left(  aA+bI_{2}\\right)  \\left(  cA+dI_{2}\\right)  =ac\\underbrace{AA}%\r\n_{\\substack{=A+I_{2}}}+ad\\underbrace{AI_{2}}_{=A}+bc\\underbrace{I_{2}A}%\r\n_{=A}+bd\\underbrace{I_{2}I_{2}}_{=I_{2}}\\\\\r\n&  =ac\\left(  A+I_{2}\\right)  +adA+bcA+bdI_{2}=\\left(  ad+bc+ac\\right)\r\nA+\\left(  ac+bd\\right)  I_{2}\\in\\mathcal{F}%\r\n\\end{align*}\r\n(by \\eqref{sol.ring.fibonacci.F.aA+binF}, applied to $ad+bc+ac$ and $ac+bd$\r\ninstead of $a$ and $b$).\r\n\r\nMultiplying the equalities $V=cA+dI_{2}$ and $U=aA+bI_{2}$ together, we obtain%\r\n\\begin{align*}\r\nVU  &  =\\left(  cA+dI_{2}\\right)  \\left(  aA+bI_{2}\\right)  =\\underbrace{ca}%\r\n_{=ac}\\underbrace{AA}_{\\substack{=A+I_{2}}}+\\underbrace{cb}_{=bc}%\r\n\\underbrace{AI_{2}}_{=A}+\\underbrace{da}_{=ad}\\underbrace{I_{2}A}%\r\n_{=A}+\\underbrace{db}_{=bd}\\underbrace{I_{2}I_{2}}_{=I_{2}}\\\\\r\n&  =ac\\left(  A+I_{2}\\right)  +bcA+adA+bdI_{2}=\\left(  ad+bc+ac\\right)\r\nA+\\left(  ac+bd\\right)  I_{2}.\r\n\\end{align*}\r\nComparing this equality with $UV=\\left(  ad+bc+ac\\right)  A+\\left(\r\nac+bd\\right)  I_{2}$, we obtain $UV=VU$.\r\n\r\nThus, we have proven that $U+V\\in\\mathcal{F}$ and $UV\\in\\mathcal{F}$ and\r\n$UV=VU$. This proves Claim 3.]\r\n\r\n[\\textit{Proof of Claim 4:} Let $U\\in\\mathcal{F}$. We have $U\\in\r\n\\mathcal{F}=\\left\\{  aA+bI_{2}\\mid a,b\\in\\mathbb{Z}\\right\\}  $. In other\r\nwords, there exist some $a,b\\in\\mathbb{Z}$ such that $U=aA+bI_{2}$. Consider\r\nthese $a,b$. Hence,%\r\n\\[\r\n-\\underbrace{U}_{=aA+bI_{2}}=-\\left(  aA+bI_{2}\\right)  =\\left(  -a\\right)\r\nA+\\left(  -b\\right)  I_{2}\\in\\mathcal{F}%\r\n\\]\r\n(by \\eqref{sol.ring.fibonacci.F.aA+binF}, applied to $-a$ and $-b$ instead of\r\n$a$ and $b$). This proves Claim 4.]\r\n\r\nLet us now resume solving part \\textbf{(b)} of the exercise. Claim 3 shows\r\nthat for every $U,V\\in\\mathcal{F}$, we have $U+V\\in\\mathcal{F}$. Thus,\r\naddition of matrices defines a binary operation $+$ on $\\mathcal{F}$.\r\nFurthermore, Claim 3 shows that for every $U,V\\in\\mathcal{F}$, we have\r\n$UV\\in\\mathcal{F}$. Thus, multiplication of matrices defines a binary\r\noperation $\\cdot$ on $\\mathcal{F}$. Furthermore, $0_{2\\times2}\\in\\mathcal{F}$\r\n(by Claim 1) and $I_{2}\\in\\mathcal{F}$ (by Claim 2). Hence, we can endow the\r\nset $\\mathcal{F}$ with the binary operation $+$ (as addition), the binary\r\noperation $\\cdot$ (as multiplication), the element $0_{2\\times2}$ (as zero)\r\nand the element $I_{2}$ (as unity). Now, we must prove that the result is a\r\ncommutative ring.\r\n\r\nIndeed, let us first prove that $\\mathcal{F}$ is a ring. To that end, we shall\r\ncheck all the ring axioms:\r\n\r\n\\begin{itemize}\r\n\\item The \\textquotedblleft Existence of additive inverses\\textquotedblright%\r\n\\ axiom is satisfied, because for every $U\\in\\mathcal{F}$, there exists an\r\n$U^{\\prime}\\in\\mathcal{F}$ such that $U+U^{\\prime}=U^{\\prime}+U=0_{2\\times2}$.\r\n(Namely, we can set $U^{\\prime}=-U$, which is an element of $\\mathcal{F}$\r\nbecause of Claim 4.)\r\n\r\n\\item All the remaining ring axioms are satisfied, since they are particular\r\ncases of the rules for addition and multiplication of matrices. (For example,\r\nassociativity of multiplication holds in $\\mathcal{F}$ because it holds for\r\narbitrary matrices.)\r\n\\end{itemize}\r\n\r\n\\noindent Thus, $\\mathcal{F}$ is a ring. Furthermore, every $U,V\\in\r\n\\mathcal{F}$ satisfy $UV=VU$ (by Claim 3). Hence, the ring $\\mathcal{F}$ is\r\ncommutative. This solves part \\textbf{(b)} of the exercise.\r\n\r\n\\bigskip\r\n\r\n\\textbf{(c)} We shall solve part \\textbf{(c)} of the exercise by induction on\r\n$n$:\r\n\r\n\\textit{Induction base:} We have $A^{1}=f_{1}A+f_{1-1}I_{2}$ (since\r\n$\\underbrace{f_{1}}_{=1}A+\\underbrace{f_{1-1}}_{=f_{0}=0}I_{2}=1A+0I_{2}%\r\n=1A=A=A^{1}$). In other words, part \\textbf{(c)} of the exercise holds for\r\n$n=1$. This completes the induction base.\r\n\r\n\\textit{Induction step:} Let $k$ be a positive integer. Assume that part\r\n\\textbf{(c)} of the exercise holds for $n=k$. We must now prove that part\r\n\\textbf{(c)} of the exercise holds for $n=k+1$.\r\n\r\nWe have assumed that part \\textbf{(c)} of the exercise holds for $n=k$. In\r\nother words, $A^{k}=f_{k}A+f_{k-1}I_{2}$. But the recursive definition of the\r\nFibonacci sequence yields $f_{k+1}=f_{k}+f_{k-1}$. Now,%\r\n\\begin{align*}\r\nA^{k+1}  &  =A\\underbrace{A^{k}}_{=f_{k}A+f_{k-1}I_{2}}=A\\left(\r\nf_{k}A+f_{k-1}I_{2}\\right)  =f_{k}\\underbrace{AA}_{\\substack{=A^{2}%\r\n=A+I_{2}\\\\\\text{(by part \\textbf{(a)}}\\\\\\text{of the exercise)}}%\r\n}+f_{k-1}\\underbrace{AI_{2}}_{=A}=f_{k}\\left(  A+I_{2}\\right)  +f_{k-1}A\\\\\r\n&  =\\underbrace{\\left(  f_{k}+f_{k-1}\\right)  }_{=f_{k+1}}A+\\underbrace{f_{k}%\r\n}_{=f_{\\left(  k+1\\right)  -1}}I_{2}=f_{k+1}A+f_{\\left(  k+1\\right)  -1}I_{2}.\r\n\\end{align*}\r\nIn other words, part \\textbf{(c)} of the exercise holds for $n=k+1$. This\r\ncompletes the induction step. Hence, part \\textbf{(c)} of the exercise is\r\nproven by induction.\r\n\r\n\\bigskip\r\n\r\n\\textbf{(d)} Let $n$ be a positive integer. Let $m\\in\\mathbb{N}$. Part\r\n\\textbf{(c)} of the exercise (applied to $n+m+1$ instead of $n$) yields%\r\n\\begin{equation}\r\nA^{n+m+1}=f_{n+m+1}A+\\underbrace{f_{\\left(  n+m+1\\right)  -1}}_{=f_{n+m}}%\r\nI_{2}=f_{n+m+1}A+f_{n+m}I_{2}. \\label{sol.ring.fibonacci.F.d.1}%\r\n\\end{equation}\r\n\r\n\r\nBut part \\textbf{(c)} of the exercise (applied to $m+1$ instead of $n$) yields%\r\n\\[\r\nA^{m+1}=f_{m+1}A+\\underbrace{f_{\\left(  m+1\\right)  -1}}_{=f_{m}}I_{2}%\r\n=f_{m+1}A+f_{m}I_{2}.\r\n\\]\r\nFurthermore, part \\textbf{(c)} of the exercise yields%\r\n\\[\r\nA^{n}=f_{n}A+f_{n-1}I_{2}.\r\n\\]\r\nMultiplying the last two equalities, we obtain%\r\n\\begin{align*}\r\nA^{m+1}A^{n}  &  =\\left(  f_{m+1}A+f_{m}I_{2}\\right)  \\left(  f_{n}%\r\nA+f_{n-1}I_{2}\\right) \\\\\r\n&  =\\underbrace{f_{m+1}f_{n}}_{=f_{n}f_{m+1}}\\underbrace{AA}_{\\substack{=A^{2}%\r\n=A+I_{2}\\\\\\text{(by part \\textbf{(a)}}\\\\\\text{of the exercise)}}%\r\n}+f_{m+1}f_{n-1}\\underbrace{AI_{2}}_{=A}+f_{m}f_{n}\\underbrace{I_{2}A}%\r\n_{=A}+\\underbrace{f_{m}f_{n-1}}_{=f_{n-1}f_{m}}\\underbrace{I_{2}I_{2}}%\r\n_{=I_{2}}\\\\\r\n&  =f_{n}f_{m+1}\\left(  A+I_{2}\\right)  +f_{m+1}f_{n-1}A+f_{m}f_{n}%\r\nA+f_{n-1}f_{m}I_{2}\\\\\r\n&  =\\left(  f_{n}f_{m+1}+f_{m+1}f_{n-1}+f_{m}f_{n}\\right)  A+\\left(\r\nf_{n}f_{m+1}+f_{n-1}f_{m}\\right)  I_{2}.\r\n\\end{align*}\r\nComparing this with%\r\n\\begin{align*}\r\nA^{m+1}A^{n}  &  =A^{\\left(  m+1\\right)  +n}\\qquad\\left(  \\text{by the rules\r\nfor exponents in the ring }\\mathbb{Z}^{2\\times2}\\right) \\\\\r\n&  =A^{n+m+1}\\qquad\\left(  \\text{since }\\left(  m+1\\right)  +n=n+m+1\\right) \\\\\r\n&  =f_{n+m+1}A+f_{n+m}I_{2}\\qquad\\left(  \\text{by\r\n\\eqref{sol.ring.fibonacci.F.d.1}}\\right)  ,\r\n\\end{align*}\r\nwe obtain%\r\n\\begin{equation}\r\nf_{n+m+1}A+f_{n+m}I_{2}=\\left(  f_{n}f_{m+1}+f_{m+1}f_{n-1}+f_{m}f_{n}\\right)\r\nA+\\left(  f_{n}f_{m+1}+f_{n-1}f_{m}\\right)  I_{2}.\r\n\\label{sol.ring.fibonacci.F.d.3}%\r\n\\end{equation}\r\n\r\n\r\nWe now would certainly want to \\textquotedblleft compare the coefficients of\r\n$I_{2}$\\textquotedblright\\ in this equality, thus concluding that\r\n$f_{n+m}=f_{n}f_{m+1}+f_{n-1}f_{m}$. But why can we do this?\r\n\r\nThe simplest way to justify this is by comparing the $\\left(  1,1\\right)  $-th\r\nentries of both matrices. Indeed, for any $u,v\\in\\mathbb{Z}$, we have%\r\n\\[\r\nu\\underbrace{A}_{=%\r\n\\begin{pmatrix}\r\n0 & 1\\\\\r\n1 & 1\r\n\\end{pmatrix}\r\n}+v\\underbrace{I_{2}}_{=%\r\n\\begin{pmatrix}\r\n1 & 0\\\\\r\n0 & 1\r\n\\end{pmatrix}\r\n}=u%\r\n\\begin{pmatrix}\r\n0 & 1\\\\\r\n1 & 1\r\n\\end{pmatrix}\r\n+v%\r\n\\begin{pmatrix}\r\n1 & 0\\\\\r\n0 & 1\r\n\\end{pmatrix}\r\n=%\r\n\\begin{pmatrix}\r\nv & u\\\\\r\nu & u+v\r\n\\end{pmatrix}\r\n\\]\r\nand thus%\r\n\\begin{equation}\r\n\\left(  \\text{the }\\left(  1,1\\right)  \\text{-th entry of the matrix\r\n}uA+vI_{2}\\right)  =v. \\label{sol.ring.fibonacci.F.d.uv}%\r\n\\end{equation}\r\nApplying this equality to $u=f_{n+m+1}$ and $v=f_{n+m}$, we obtain%\r\n\\begin{equation}\r\n\\left(  \\text{the }\\left(  1,1\\right)  \\text{-th entry of the matrix\r\n}f_{n+m+1}A+f_{n+m}I_{2}\\right)  =f_{n+m}. \\label{sol.ring.fibonacci.F.d.r1}%\r\n\\end{equation}\r\nBut applying \\eqref{sol.ring.fibonacci.F.d.uv} to $u=f_{n}f_{m+1}%\r\n+f_{m+1}f_{n-1}+f_{m}f_{n}$ and $v=f_{n}f_{m+1}+f_{n-1}f_{m}$, we obtain%\r\n\\begin{align}\r\n&  \\left(  \\text{the }\\left(  1,1\\right)  \\text{-th entry of the matrix\r\n}\\left(  f_{n}f_{m+1}+f_{m+1}f_{n-1}+f_{m}f_{n}\\right)  A+\\left(  f_{n}%\r\nf_{m+1}+f_{n-1}f_{m}\\right)  I_{2}\\right) \\nonumber\\\\\r\n&  =f_{n}f_{m+1}+f_{n-1}f_{m}. \\label{sol.ring.fibonacci.F.d.r2}%\r\n\\end{align}\r\nBut the left hand sides of the equalities \\eqref{sol.ring.fibonacci.F.d.r1}\r\nand \\eqref{sol.ring.fibonacci.F.d.r2} are equal (because of\r\n\\eqref{sol.ring.fibonacci.F.d.3}). Thus, their right hand sides must also be\r\nequal. In other words, we have%\r\n\\[\r\nf_{n+m}=f_{n}f_{m+1}+f_{n-1}f_{m}.\r\n\\]\r\nThis solves part \\textbf{(d)} of the exercise.\r\n\r\n[\\textit{Remark:} There are many other ways to solve this part of the\r\nexercise. For example, if we rename $n$ as $n+1$, then it takes the more\r\nsymmetric form $f_{n+m+1}=f_{n+1}f_{m+1}+f_{n}f_{m}$; but this is a well-known\r\nidentity (see, e.g., Exercise 3 \\textbf{(e)} in\r\n\\href{http://www.cip.ifi.lmu.de/~grinberg/t/18s/mt1s.pdf}{UMN Spring 2018 Math\r\n4707 midterm \\#1}) and a particular case of \\cite[Theorem 2.26 \\textbf{(a)}%\r\n]{detnotes}. It can be easily proven by induction on $n$ (or on $m$). Binet's\r\nformula for the Fibonacci numbers also leads to a straightforward solution to\r\npart \\textbf{(d)} of the exercise.]\r\n\r\n\\bigskip\r\n\r\n\\textbf{(e)} First, we shall show that $B^{2}=B+I_{2}$. Indeed, $B=I_{2}-A$\r\nand thus%\r\n\\begin{align*}\r\nB^{2}  &  =\\left(  I_{2}-A\\right)  ^{2}=\\left(  I_{2}-A\\right)  \\left(\r\nI_{2}-A\\right)  =\\underbrace{I_{2}\\left(  I_{2}-A\\right)  }_{=I_{2}%\r\n-A}-\\underbrace{A\\left(  I_{2}-A\\right)  }_{=AI_{2}-AA}\\\\\r\n&  =I_{2}-A-\\left(  AI_{2}-AA\\right)  =I_{2}-A-\\underbrace{AI_{2}}%\r\n_{=A}+\\underbrace{AA}_{\\substack{=A^{2}=A+I_{2}\\\\\\text{(by part \\textbf{(a)}%\r\n}\\\\\\text{of the exercise)}}}\\\\\r\n&  =I_{2}-A-A+\\left(  A+I_{2}\\right)  =2I_{2}-A=\\underbrace{\\left(\r\nI_{2}-A\\right)  }_{=B}+I_{2}=B+I_{2}.\r\n\\end{align*}\r\n\r\n\r\nIt remains to prove that $B^{n}=f_{n}B+f_{n-1}I_{2}$ for all positive integers\r\n$n$.\r\n\r\nHere is the laziest (but perfectly legitimate) way of doing this: In our\r\nsolution to part \\textbf{(c)} of this exercise, we have proven that\r\n$A^{n}=f_{n}A+f_{n-1}I_{2}$ for all positive integers $n$. Our proof of this\r\nfact did not use anything specific about the matrix $A$, other than the fact\r\nthat $A$ satisfies $A^{2}=A+I_{2}$. Therefore, we can replace each appearance\r\nof \\textquotedblleft$A$\\textquotedblright\\ by \\textquotedblleft$B$%\r\n\\textquotedblright\\ in this proof, and thus obtain a proof of the fact that\r\n$B^{n}=f_{n}B+f_{n-1}I_{2}$ for all positive integers $n$ (because $B$\r\nsatisfies $B^{2}=B+I_{2}$). This completes the solution of part \\textbf{(e)}\r\nof the exercise.\r\n\r\n\\bigskip\r\n\r\n\\textbf{(f)} Let $n\\in\\mathbb{N}$. We must prove that $A^{n}-B^{n}%\r\n=f_{n}\\left(  A-B\\right)  $.\r\n\r\nIf $n=0$, then this is easy\\footnote{\\textit{Proof.} Assume that $n=0$. Thus,\r\n$A^{n}-B^{n}=\\underbrace{A^{0}}_{=I_{2}}-\\underbrace{B^{0}}_{=I_{2}}%\r\n=I_{2}-I_{2}=0_{2\\times2}$. On the other hand, from $n=0$, we obtain\r\n$f_{n}=f_{0}=0$ and thus $f_{n}\\left(  A-B\\right)  =0\\left(  A-B\\right)\r\n=0_{2\\times2}$. Comparing this with $A^{n}-B^{n}=0_{2\\times2}$, we obtain\r\n$A^{n}-B^{n}=f_{n}\\left(  A-B\\right)  $. Hence, we have proven that\r\n$A^{n}-B^{n}=f_{n}\\left(  A-B\\right)  $ under the assumption that $n=0$.}.\r\nHence, for the rest of this proof, we WLOG assume that $n\\neq0$. Thus, $n$ is\r\na positive integer (since $n\\in\\mathbb{N}$). Hence, part \\textbf{(c)} of this\r\nexercise yields $A^{n}=f_{n}A+f_{n-1}I_{2}$. But part \\textbf{(e)} of this\r\nexercise yields $B^{n}=f_{n}B+f_{n-1}I_{2}$. Subtracting the last two\r\nequalities, we obtain%\r\n\\[\r\nA^{n}-B^{n}=\\left(  f_{n}A+f_{n-1}I_{2}\\right)  -\\left(  f_{n}B+f_{n-1}%\r\nI_{2}\\right)  =f_{n}\\left(  A-B\\right)  .\r\n\\]\r\nThis solves part \\textbf{(f)} of the exercise.\r\n\r\n\\bigskip\r\n\r\n\\textbf{(g)} Given two elements $\\alpha$ and $\\beta$ of $\\mathcal{F}$, we say\r\nthat $\\alpha\\mid\\beta$ \\textit{in }$\\mathcal{F}$ if and only if there exists\r\nsome $\\gamma\\in\\mathcal{F}$ such that $\\beta=\\alpha\\gamma$. Thus, we have\r\ndefined divisibility in $\\mathcal{F}$. Basic properties of divisibility of\r\nintegers (such as Proposition 2.2.4 in\r\n\\href{http://www.cip.ifi.lmu.de/~grinberg/t/19s/notes.pdf}{the class notes})\r\nstill apply to divisibility in $\\mathcal{F}$ (with the same proofs), since\r\n$\\mathcal{F}$ is a \\textbf{commutative} ring.\r\n\r\nWe recall the following fact (Lemma 2.10.11 \\textbf{(a)} in\r\n\\href{http://www.cip.ifi.lmu.de/~grinberg/t/19s/notes.pdf}{the class notes}):\r\n\r\n\\begin{statement}\r\n\\textit{Claim 5:} Let $d\\in\\mathbb{N}$. Let $x$ and $y$ be integers. Then,\r\n$x-y\\mid x^{d}-y^{d}$.\r\n\\end{statement}\r\n\r\nThis fact has an analogue for elements of $\\mathcal{F}$ instead of integers:\r\n\r\n\\begin{statement}\r\n\\textit{Claim 6:} Let $d\\in\\mathbb{N}$. Let $x$ and $y$ be elements of\r\n$\\mathcal{F}$. Then, $x-y\\mid x^{d}-y^{d}$ in $\\mathcal{F}$.\r\n\\end{statement}\r\n\r\n[\\textit{Proof of Claim 6:} Both proofs we gave for Claim 5 in the class notes\r\ncan be modified in an obvious way to yield proofs of Claim 6, because\r\n$\\mathcal{F}$ is a \\textbf{commutative} ring.]\r\n\r\nNow, let $d$ and $n$ be nonnegative integers. We must prove that $f_{d}\\mid\r\nf_{dn}$.\r\n\r\nPart \\textbf{(f)} of this exercise (applied to $d$ instead of $n$) yields\r\n$A^{d}-B^{d}=f_{d}\\left(  A-B\\right)  $.\r\n\r\nPart \\textbf{(f)} of this exercise (applied to $dn$ instead of $n$) yields\r\n$A^{dn}-B^{dn}=f_{dn}\\left(  A-B\\right)  $.\r\n\r\nBut $A$ and $B$ are elements of $\\mathcal{F}$. Thus, their powers $A^{d}$,\r\n$B^{d}$, $A^{dn}$ and $B^{dn}$ are elements of $\\mathcal{F}$ as well (since\r\n$\\mathcal{F}$ is a ring). Hence, Claim 2 (applied to $n$, $A^{d}$ and $B^{d}$\r\ninstead of $d$, $x$ and $y$) yields $A^{d}-B^{d}\\mid\\left(  A^{d}\\right)\r\n^{n}-\\left(  B^{d}\\right)  ^{n}$ in $\\mathcal{F}$. In view of\r\n\\[\r\nA^{d}-B^{d}=f_{d}\\left(  A-B\\right)  \\qquad\\text{and}\\qquad\\left(\r\nA^{d}\\right)  ^{n}-\\left(  B^{d}\\right)  ^{n}=A^{dn}-B^{dn}=f_{dn}\\left(\r\nA-B\\right)  ,\r\n\\]\r\nthis rewrites as follows:%\r\n\\[\r\nf_{d}\\left(  A-B\\right)  \\mid f_{dn}\\left(  A-B\\right)  \\qquad\\text{in\r\n}\\mathcal{F}.\r\n\\]\r\n\r\n\r\nNow, it is tempting to \\textquotedblleft cancel\\textquotedblright\\ $A-B$ from\r\nthis divisibility, and conclude that $f_{d}\\mid f_{dn}$ in $\\mathbb{Z}$. To\r\njustify this rigorously, we proceed as follows:\r\n\r\nWe have $f_{d}\\left(  A-B\\right)  \\mid f_{dn}\\left(  A-B\\right)  $ in\r\n$\\mathcal{F}$. In other words, there exists a matrix $\\gamma\\in\\mathcal{F}$\r\nsuch that\r\n\\begin{equation}\r\nf_{dn}\\left(  A-B\\right)  =f_{d}\\left(  A-B\\right)  \\gamma\r\n\\label{sol.ring.fibonacci.F.g.2}%\r\n\\end{equation}\r\n(by the definition of divisibility in $\\mathcal{F}$). Consider this $\\gamma$.\r\n\r\nWe have $B=I_{2}-A$ and thus\r\n\\[\r\nA-B=A-\\left(  I_{2}-A\\right)  =2\\underbrace{A}_{=%\r\n\\begin{pmatrix}\r\n0 & 1\\\\\r\n1 & 1\r\n\\end{pmatrix}\r\n}-\\underbrace{I_{2}}_{=%\r\n\\begin{pmatrix}\r\n1 & 0\\\\\r\n0 & 1\r\n\\end{pmatrix}\r\n}=2%\r\n\\begin{pmatrix}\r\n0 & 1\\\\\r\n1 & 1\r\n\\end{pmatrix}\r\n-%\r\n\\begin{pmatrix}\r\n1 & 0\\\\\r\n0 & 1\r\n\\end{pmatrix}\r\n=%\r\n\\begin{pmatrix}\r\n-1 & 2\\\\\r\n2 & 1\r\n\\end{pmatrix}\r\n.\r\n\\]\r\nHence,%\r\n\\begin{equation}\r\n\\left(  \\text{the }\\left(  2,2\\right)  \\text{-th entry of the matrix\r\n}A-B\\right)  =1.\\label{sol.ring.fibonacci.F.g.3}%\r\n\\end{equation}\r\nSince matrices are scaled entrywise, we now have%\r\n\\begin{align}\r\n&  \\left(  \\text{the }\\left(  2,2\\right)  \\text{-th entry of the matrix\r\n}f_{dn}\\left(  A-B\\right)  \\right)  \\nonumber\\\\\r\n&  =f_{dn}\\cdot\\underbrace{\\left(  \\text{the }\\left(  2,2\\right)  \\text{-th\r\nentry of the matrix }A-B\\right)  }_{=1}=f_{dn}%\r\n.\\label{sol.ring.fibonacci.F.g.5}%\r\n\\end{align}\r\nOn the other hand, the matrices $A-B$ and $\\gamma$ belong to $\\mathcal{F}$;\r\nthus, their product $\\left(  A-B\\right)  \\gamma$ belongs to $\\mathcal{F}$ as\r\nwell, and therefore belongs to $\\mathbb{Z}^{2\\times2}$ (since $\\mathcal{F}%\r\n\\subseteq\\mathbb{Z}^{2\\times2}$). In other words, $\\left(  A-B\\right)  \\gamma$\r\nis a $2\\times2$-matrix with integer entries. Hence, each entry of $\\left(\r\nA-B\\right)  \\gamma$ is an integer, i.e., belongs to $\\mathbb{Z}$. Thus, in\r\nparticular,%\r\n\\[\r\n\\left(  \\text{the }\\left(  2,2\\right)  \\text{-th entry of the matrix }\\left(\r\nA-B\\right)  \\gamma\\right)  \\in\\mathbb{Z}.\r\n\\]\r\nNow, \\eqref{sol.ring.fibonacci.F.g.5} yields%\r\n\\begin{align*}\r\nf_{dn} &  =\\left(  \\text{the }\\left(  2,2\\right)  \\text{-th entry of the\r\nmatrix }\\underbrace{f_{dn}\\left(  A-B\\right)  }_{=f_{d}\\left(  A-B\\right)\r\n\\gamma}\\right)  \\\\\r\n&  =\\left(  \\text{the }\\left(  2,2\\right)  \\text{-th entry of the matrix\r\n}f_{d}\\left(  A-B\\right)  \\gamma\\right)  \\\\\r\n&  =f_{d}\\cdot\\left(  \\text{the }\\left(  2,2\\right)  \\text{-th entry of the\r\nmatrix }\\left(  A-B\\right)  \\gamma\\right)\r\n\\end{align*}\r\n(since matrices are scaled entrywise). This yields that $f_{d}\\mid f_{dn}$ (in\r\nthe classical sense of divisibility of integers), because we know that\r\n$\\left(  \\text{the }\\left(  2,2\\right)  \\text{-th entry of the matrix }\\left(\r\nA-B\\right)  \\gamma\\right)  \\in\\mathbb{Z}$. This solves part \\textbf{(g)} of\r\nthe exercise.\r\n\r\n[\\textit{Remark:} Once again, there are other ways to solve this part of the\r\nexercise. For example, it can be restated as \\textquotedblleft Prove that\r\n$f_{u}\\mid f_{v}$ whenever $u$ and $v$ are nonnegative integers satisfying\r\n$u\\mid v$\\textquotedblright; but in this form, it is clearly a particular case\r\nof \\cite[Theorem 2.26 \\textbf{(c)}]{detnotes}.]\r\n\r\n%----------------------------------------------------------------------------------------\r\n%\tEXERCISE 6\r\n%----------------------------------------------------------------------------------------\r\n\\rule{\\linewidth}{0.3pt} \\\\[0.4cm]\r\n\r\n\\section{Exercise 6: ISBNs vs. fat fingers}\r\n\r\n\\subsection{Problem}\r\n\r\nAn \\textit{ISBN} shall mean a $10$-tuple $\\left(  a_{1},a_{2},\\ldots\r\n,a_{10}\\right)  \\in\\left\\{  0,1,\\ldots,10\\right\\}  ^{10}$ such that\r\n\\[\r\n1a_{1}+2a_{2}+\\cdots+10a_{10}\\equiv0\\operatorname{mod}11.\r\n\\]\r\n\r\n\r\n\\noindent(For example, the $10$-tuple $\\left(  1, 1, \\ldots, 1 \\right)  $ is\r\nan ISBN.)\r\n\r\nProve the following:\r\n\r\n\\begin{enumerate}\r\n\\item[\\textbf{(a)}] If $\\mathbf{a} = \\left(  a_{1}, a_{2}, \\ldots, a_{10}\r\n\\right)  $ and $\\mathbf{b} = \\left(  b_{1}, b_{2}, \\ldots, b_{10} \\right)  $\r\nare two ISBNs that are equal in all but one entry (i.e., there exists some $k\r\n\\in\\left\\{  1, 2, \\ldots, 10 \\right\\}  $ such that $a_{i} = b_{i}$ for all $i\r\n\\neq k$), then $\\mathbf{a} = \\mathbf{b}$.\r\n\r\n\\item[\\textbf{(b)}] If an ISBN $\\mathbf{a} = \\left(  a_{1}, a_{2}, \\ldots,\r\na_{10} \\right)  $ is obtained from an ISBN $\\mathbf{b} = \\left(  b_{1}, b_{2},\r\n\\ldots, b_{10} \\right)  $ by swapping two entries (i.e., there exist $k,\r\n\\ell\\in\\left\\{  1, 2, \\ldots, 10 \\right\\}  $ such that $a_{k} = b_{\\ell}$ and\r\n$a_{\\ell}= b_{k}$ and $a_{i} = b_{i}$ for all $i \\notin\\left\\{  k,\r\n\\ell\\right\\}  $), then $\\mathbf{a} = \\mathbf{b}$.\r\n\\end{enumerate}\r\n\r\n\\subsection{Remark}\r\n\r\nWhat we called ISBN here is essentially the definition of an\r\n\\href{https://en.wikipedia.org/wiki/International_Standard_Book_Number#ISBN-10_check_digits}{ISBN-10}\r\n-- an international standard for book identifiers used from the 1970s until\r\n2007. For example, the ISBN-10 of the Graham/Knuth/Patashnik book ``Concrete\r\nMathematics'' is ``0-201-55802-5'', which corresponds to $\\left(  0, 2, 0, 1,\r\n5, 5, 8, 0, 2, 5 \\right)  $; you can check that this is indeed an ISBN\r\naccording to our definition.\r\n\r\n(An ``X'' in a real-life ISBN stands for an entry that is $10$.)\r\n\r\nAs this exercise shows, ISBNs have an error-detection property: If you make a\r\ntypo in a single digit or accidentally swap two digits, the result will not be\r\nan ISBN, so you will know that something has gone wrong. This helps you avoid\r\nordering the wrong book from a bookstore or library.\r\n\\href{https://en.wikipedia.org/wiki/Luhn_algorithm}{Credit card numbers have a\r\nsimilar error-detection feature}.\r\n\r\nThis is one of the simplest examples of an\r\n\\href{https://en.wikipedia.org/wiki/Error_correction_code}{error correction\r\ncode}. We may or may not see more of them in class. For now, you can think\r\nabout how to define ``ISBNs''\r\n\r\n\\begin{itemize}\r\n\\item in $\\left\\{  0, 1, \\ldots, 4 \\right\\}  ^{4}$;\r\n\r\n\\item in $\\left\\{  0, 1, \\ldots, 6 \\right\\}  ^{6}$;\r\n\r\n\\item in $\\left\\{  0, 1, \\ldots, 8 \\right\\}  ^{8}$ (this is harder!).\r\n\\end{itemize}\r\n\r\n\\subsection{Solution sketch}\r\n\r\nBefore we solve the exercise, let us prove a simple claim which our solution\r\nwill rest upon:\r\n\r\n\\begin{statement}\r\n\\textit{Claim 1:} Let $u$ and $v$ be two elements of $\\left\\{  -10,-9,\\ldots\r\n,10\\right\\}  $ such that $uv\\equiv0\\operatorname{mod}11$ and $u\\neq0$. Then,\r\n$v=0$.\r\n\\end{statement}\r\n\r\n[\\textit{Proof of Claim 1:} Assume the contrary. Thus, $v\\neq0$.\r\n\r\nWe have $u\\in\\left\\{  -10,-9,\\ldots,10\\right\\}  $, thus $-10\\leq u\\leq10$ and\r\ntherefore $\\left\\vert u\\right\\vert \\leq10$. In other words, $10\\geq\\left\\vert\r\nu\\right\\vert $.\r\n\r\nIf we had $11\\mid u$, then Proposition 2.2.3 \\textbf{(b)} in\r\n\\href{http://www.cip.ifi.lmu.de/~grinberg/t/19s/notes.pdf}{the class notes}\r\n(applied to $a=11$ and $b=u$) would yield $\\left\\vert 11\\right\\vert\r\n\\leq\\left\\vert u\\right\\vert $ (since $u\\neq0$); but this would contradict\r\n$\\left\\vert 11\\right\\vert =11>10\\geq\\left\\vert u\\right\\vert $. Hence, we\r\ncannot have $11\\mid u$. The same argument (applied to $v$ instead of $u$)\r\nshows that we cannot have $11\\mid v$ (since $v\\neq0$). Thus, neither $11\\mid\r\nu$ nor $11\\mid v$ holds.\r\n\r\nBut $11$ is a prime, and we have $11\\mid uv$ (since $uv\\equiv\r\n0\\operatorname{mod}11$). Thus, Theorem 2.13.6 in\r\n\\href{http://www.cip.ifi.lmu.de/~grinberg/t/19s/notes.pdf}{the class notes}\r\n(applied to $p=11$, $a=u$ and $b=v$) shows that $11\\mid u$ or $11\\mid v$. This\r\ncontradicts the fact that neither $11\\mid u$ nor $11\\mid v$ holds. This\r\ncontradiction shows that our assumption was false. Hence, Claim 1 is proven.]\r\n\r\n\\bigskip\r\n\r\n\\textbf{(a)} Let $\\mathbf{a}=\\left(  a_{1},a_{2},\\ldots,a_{10}\\right)  $ and\r\n$\\mathbf{b}=\\left(  b_{1},b_{2},\\ldots,b_{10}\\right)  $ be two ISBNs that are\r\nequal in all but one entry. We must prove that $\\mathbf{a}=\\mathbf{b}$.\r\n\r\nWe have assumed that $\\mathbf{a}$ and $\\mathbf{b}$ are equal in all but one\r\nentry. In other words, there exists some $k\\in\\left\\{  1,2,\\ldots,10\\right\\}\r\n$ such that\r\n\\begin{equation}\r\na_{i}=b_{i}\\qquad\\text{for all }i\\neq k. \\label{sol.ent.isbn.a.ass}%\r\n\\end{equation}\r\nConsider this $k$.\r\n\r\nWe have assumed that $\\mathbf{a}$ is an ISBN. In other words, $\\left(\r\na_{1},a_{2},\\ldots,a_{10}\\right)  \\in\\left\\{  0,1,\\ldots,10\\right\\}  ^{10}$\r\nand $1a_{1}+2a_{2}+\\cdots+10a_{10}\\equiv0\\operatorname{mod}11$.\r\n\r\nThus,%\r\n\\begin{equation}\r\n\\sum_{i\\in\\left\\{  1,2,\\ldots,10\\right\\}  }ia_{i}=1a_{1}+2a_{2}+\\cdots\r\n+10a_{10}\\equiv0\\operatorname{mod}11. \\label{sol.ent.isbn.a.sum-iai}%\r\n\\end{equation}\r\nSimilarly,%\r\n\\begin{equation}\r\n\\sum_{i\\in\\left\\{  1,2,\\ldots,10\\right\\}  }ib_{i}\\equiv0\\operatorname{mod}11.\r\n\\label{sol.ent.isbn.a.sum-ibi}%\r\n\\end{equation}\r\nBut%\r\n\\begin{align*}\r\n\\sum_{i\\in\\left\\{  1,2,\\ldots,10\\right\\}  }ia_{i}  &  =ka_{k}+\\sum\r\n_{\\substack{i\\in\\left\\{  1,2,\\ldots,10\\right\\}  ;\\\\i\\neq k}}i\\underbrace{a_{i}%\r\n}_{\\substack{=b_{i}\\\\\\text{(by \\eqref{sol.ent.isbn.a.ass})}}}\\\\\r\n&  \\qquad\\left(  \\text{here, we have split off the addend for }i=k\\text{ from\r\nthe sum}\\right) \\\\\r\n&  =ka_{k}+\\sum_{\\substack{i\\in\\left\\{  1,2,\\ldots,10\\right\\}  ;\\\\i\\neq\r\nk}}ib_{i},\r\n\\end{align*}\r\nso that \\eqref{sol.ent.isbn.a.sum-iai} rewrites as%\r\n\\begin{equation}\r\nka_{k}+\\sum_{\\substack{i\\in\\left\\{  1,2,\\ldots,10\\right\\}  ;\\\\i\\neq k}%\r\n}ib_{i}\\equiv0\\operatorname{mod}11. \\label{sol.ent.isbn.a.sum-iai2}%\r\n\\end{equation}\r\nFurthermore,%\r\n\\begin{align*}\r\n\\sum_{i\\in\\left\\{  1,2,\\ldots,10\\right\\}  }ib_{i}  &  =kb_{k}+\\sum\r\n_{\\substack{i\\in\\left\\{  1,2,\\ldots,10\\right\\}  ;\\\\i\\neq k}}ib_{i}\\\\\r\n&  \\qquad\\left(  \\text{here, we have split off the addend for }i=k\\text{ from\r\nthe sum}\\right)  ,\r\n\\end{align*}\r\nso that \\eqref{sol.ent.isbn.a.sum-ibi} rewrites as%\r\n\\[\r\nkb_{k}+\\sum_{\\substack{i\\in\\left\\{  1,2,\\ldots,10\\right\\}  ;\\\\i\\neq k}%\r\n}ib_{i}\\equiv0\\operatorname{mod}11.\r\n\\]\r\nSubtracting this congruence from the congruence\r\n\\eqref{sol.ent.isbn.a.sum-iai2}, we obtain\r\n\\[\r\n\\left(  ka_{k}+\\sum_{\\substack{i\\in\\left\\{  1,2,\\ldots,10\\right\\}  ;\\\\i\\neq\r\nk}}ib_{i}\\right)  -\\left(  kb_{k}+\\sum_{\\substack{i\\in\\left\\{  1,2,\\ldots\r\n,10\\right\\}  ;\\\\i\\neq k}}ib_{i}\\right)  \\equiv0-0=0\\operatorname{mod}11.\r\n\\]\r\nIn view of\r\n\\[\r\n\\left(  ka_{k}+\\sum_{\\substack{i\\in\\left\\{  1,2,\\ldots,10\\right\\}  ;\\\\i\\neq\r\nk}}ib_{i}\\right)  -\\left(  kb_{k}+\\sum_{\\substack{i\\in\\left\\{  1,2,\\ldots\r\n,10\\right\\}  ;\\\\i\\neq k}}ib_{i}\\right)  =ka_{k}-kb_{k}=k\\left(  a_{k}%\r\n-b_{k}\\right)  ,\r\n\\]\r\nthis rewrites as $k\\left(  a_{k}-b_{k}\\right)  \\equiv0\\operatorname{mod}11$.\r\n\r\nWe have $a_{k}\\in\\left\\{  0,1,\\ldots,10\\right\\}  $ (since $\\left(  a_{1}%\r\n,a_{2},\\ldots,a_{10}\\right)  \\in\\left\\{  0,1,\\ldots,10\\right\\}  ^{10}$) and\r\n$b_{k}\\in\\left\\{  0,1,\\ldots,10\\right\\}  $ (similarly). Hence, $a_{k}-b_{k}%\r\n\\in\\left\\{  -10,-9,\\ldots,10\\right\\}  $. Furthermore, $k\\in\\left\\{\r\n1,2,\\ldots,10\\right\\}  \\subseteq\\left\\{  -10,-9,\\ldots,10\\right\\}  $ and\r\n$k\\neq0$. Thus, Claim 1 (applied to $u=k$ and $v=a_{k}-b_{k}$) yields\r\n$a_{k}-b_{k}=0$. In other words, $a_{k}=b_{k}$.\r\n\r\nNow, \\eqref{sol.ent.isbn.a.ass} shows that any entry of the $10$-tuple\r\n$\\mathbf{a}$ is equal to the corresponding entry of the $10$-tuple\r\n$\\mathbf{b}$, except perhaps the $k$-th entry. But the equality $a_{k}=b_{k}$\r\nshows that the $k$-th entries of these two $10$-tuples $\\mathbf{a}$ and\r\n$\\mathbf{b}$ are also equal to each other. Thus, each entry of $\\mathbf{a}$ is\r\nequal to the corresponding entry of $\\mathbf{b}$. In other words,\r\n$\\mathbf{a}=\\mathbf{b}$. This solves part \\textbf{(a)} of the exercise.\r\n\r\n\\bigskip\r\n\r\n\\textbf{(b)} Let $\\mathbf{a}=\\left(  a_{1},a_{2},\\ldots,a_{10}\\right)  $ and\r\n$\\mathbf{b}=\\left(  b_{1},b_{2},\\ldots,b_{10}\\right)  $ be two ISBNs such that\r\n$\\mathbf{a}$ is obtained from $\\mathbf{b}$ by swapping two entries. We must\r\nprove that $\\mathbf{a}=\\mathbf{b}$.\r\n\r\nWe have assumed that $\\mathbf{a}$ is obtained from $\\mathbf{b}$ by swapping\r\ntwo entries. In other words, there exist $k,\\ell\\in\\left\\{  1,2,\\ldots\r\n,10\\right\\}  $ such that $a_{k}=b_{\\ell}$ and $a_{\\ell}=b_{k}$ and\r\n\\begin{equation}\r\na_{i}=b_{i}\\qquad\\text{for all }i\\notin\\left\\{  k,\\ell\\right\\}  .\r\n\\label{sol.ent.isbn.b.ass}%\r\n\\end{equation}\r\nConsider these $k,\\ell$.\r\n\r\nWe must prove that $\\mathbf{a}=\\mathbf{b}$. If $a_{k}=a_{\\ell}$, then this is\r\ntrue\\footnote{\\textit{Proof.} Assume that $a_{k}=a_{\\ell}$. Thus,\r\n$a_{k}=a_{\\ell}=b_{k}$ and $a_{\\ell}=a_{k}=b_{\\ell}$. Now, from\r\n\\eqref{sol.ent.isbn.b.ass}, we know that the equality $a_{i}=b_{i}$ holds for\r\nall $i\\notin\\left\\{  k,\\ell\\right\\}  $. But this equality also holds for $i=k$\r\n(since $a_{k}=b_{k}$) and for $i=\\ell$ (since $a_{\\ell}=b_{\\ell}$). Thus, this\r\nequality holds for all $i\\in\\left\\{  1,2,\\ldots,10\\right\\}  $. In other words,\r\n$\\mathbf{a}=\\mathbf{b}$, qed.}. Hence, for the rest of this solution, we WLOG\r\nassume that $a_{k}\\neq a_{\\ell}$. Thus, $k\\neq\\ell$, so that $k-\\ell\\neq0$.\r\n\r\nAlso, we have $a_{k}\\neq a_{\\ell}$. In view of $a_{k}=b_{\\ell}$ and $a_{\\ell\r\n}=b_{k}$, this rewrites as $b_{\\ell}\\neq b_{k}$.\r\n\r\nWe have assumed that $\\mathbf{a}$ is an ISBN. In other words, $\\left(\r\na_{1},a_{2},\\ldots,a_{10}\\right)  \\in\\left\\{  0,1,\\ldots,10\\right\\}  ^{10}$\r\nand $1a_{1}+2a_{2}+\\cdots+10a_{10}\\equiv0\\operatorname{mod}11$.\r\n\r\nThus,%\r\n\\begin{equation}\r\n\\sum_{i\\in\\left\\{  1,2,\\ldots,10\\right\\}  }ia_{i}=1a_{1}+2a_{2}+\\cdots\r\n+10a_{10}\\equiv0\\operatorname{mod}11. \\label{sol.ent.isbn.b.sum-iai}%\r\n\\end{equation}\r\nSimilarly,%\r\n\\begin{equation}\r\n\\sum_{i\\in\\left\\{  1,2,\\ldots,10\\right\\}  }ib_{i}\\equiv0\\operatorname{mod}11.\r\n\\label{sol.ent.isbn.b.sum-ibi}%\r\n\\end{equation}\r\nBut%\r\n\\begin{align*}\r\n\\sum_{i\\in\\left\\{  1,2,\\ldots,10\\right\\}  }ia_{i}  &  =k\\underbrace{a_{k}%\r\n}_{=b_{\\ell}}+\\ell\\underbrace{a_{\\ell}}_{=b_{k}}+\\sum_{\\substack{i\\in\\left\\{\r\n1,2,\\ldots,10\\right\\}  ;\\\\i\\notin\\left\\{  k,\\ell\\right\\}  }}i\\underbrace{a_{i}%\r\n}_{\\substack{=b_{i}\\\\\\text{(by \\eqref{sol.ent.isbn.b.ass})}}}\\\\\r\n&  \\qquad\\left(\r\n\\begin{array}\r\n[c]{c}%\r\n\\text{here, we have split off the addends for }i=k\\text{ and for }i=\\ell\\text{\r\nfrom the}\\\\\r\n\\text{sum (and these were indeed two different addends, since }k\\neq\r\n\\ell\\text{)}%\r\n\\end{array}\r\n\\right) \\\\\r\n&  =kb_{\\ell}+\\ell b_{k}+\\sum_{\\substack{i\\in\\left\\{  1,2,\\ldots,10\\right\\}\r\n;\\\\i\\notin\\left\\{  k,\\ell\\right\\}  }}ib_{i},\r\n\\end{align*}\r\nso that \\eqref{sol.ent.isbn.b.sum-iai} rewrites as%\r\n\\begin{equation}\r\nkb_{\\ell}+\\ell b_{k}+\\sum_{\\substack{i\\in\\left\\{  1,2,\\ldots,10\\right\\}\r\n;\\\\i\\notin\\left\\{  k,\\ell\\right\\}  }}ib_{i}\\equiv0\\operatorname{mod}11.\r\n\\label{sol.ent.isbn.b.sum-iai2}%\r\n\\end{equation}\r\nFurthermore,%\r\n\\begin{align*}\r\n\\sum_{i\\in\\left\\{  1,2,\\ldots,10\\right\\}  }ia_{i}  &  =kb_{k}+\\ell b_{\\ell\r\n}+\\sum_{\\substack{i\\in\\left\\{  1,2,\\ldots,10\\right\\}  ;\\\\i\\notin\\left\\{\r\nk,\\ell\\right\\}  }}ib_{i}\\\\\r\n&  \\qquad\\left(\r\n\\begin{array}\r\n[c]{c}%\r\n\\text{here, we have split off the addends for }i=k\\text{ and for }i=\\ell\\text{\r\nfrom the}\\\\\r\n\\text{sum (and these were indeed two different addends, since }k\\neq\r\n\\ell\\text{)}%\r\n\\end{array}\r\n\\right)  ,\r\n\\end{align*}\r\nso that \\eqref{sol.ent.isbn.b.sum-ibi} rewrites as%\r\n\\[\r\nkb_{k}+\\ell b_{\\ell}+\\sum_{\\substack{i\\in\\left\\{  1,2,\\ldots,10\\right\\}\r\n;\\\\i\\notin\\left\\{  k,\\ell\\right\\}  }}ib_{i}\\equiv0\\operatorname{mod}11.\r\n\\]\r\nSubtracting this congruence from the congruence\r\n\\eqref{sol.ent.isbn.b.sum-iai2}, we obtain\r\n\\[\r\n\\left(  kb_{\\ell}+\\ell b_{k}+\\sum_{\\substack{i\\in\\left\\{  1,2,\\ldots\r\n,10\\right\\}  ;\\\\i\\notin\\left\\{  k,\\ell\\right\\}  }}ib_{i}\\right)  -\\left(\r\nkb_{k}+\\ell b_{\\ell}+\\sum_{\\substack{i\\in\\left\\{  1,2,\\ldots,10\\right\\}\r\n;\\\\i\\notin\\left\\{  k,\\ell\\right\\}  }}ib_{i}\\right)  \\equiv\r\n0-0=0\\operatorname{mod}11.\r\n\\]\r\nIn view of\r\n\\begin{align*}\r\n\\left(  kb_{\\ell}+\\ell b_{k}+\\sum_{\\substack{i\\in\\left\\{  1,2,\\ldots\r\n,10\\right\\}  ;\\\\i\\notin\\left\\{  k,\\ell\\right\\}  }}ib_{i}\\right)  -\\left(\r\nkb_{k}+\\ell b_{\\ell}+\\sum_{\\substack{i\\in\\left\\{  1,2,\\ldots,10\\right\\}\r\n;\\\\i\\notin\\left\\{  k,\\ell\\right\\}  }}ib_{i}\\right)   &  =kb_{\\ell}+\\ell\r\nb_{k}-kb_{k}-\\ell b_{\\ell}\\\\\r\n&  =\\left(  k-\\ell\\right)  \\left(  b_{\\ell}-b_{k}\\right)  ,\r\n\\end{align*}\r\nthis rewrites as $\\left(  k-\\ell\\right)  \\left(  b_{\\ell}-b_{k}\\right)\r\n\\equiv0\\operatorname{mod}11$.\r\n\r\nBut $\\mathbf{b}$ is an ISBN; thus, $\\left(  b_{1},b_{2},\\ldots,b_{10}\\right)\r\n\\in\\left\\{  0,1,\\ldots,10\\right\\}  ^{10}$. Hence, $b_{k}\\in\\left\\{\r\n0,1,\\ldots,10\\right\\}  $ and $b_{\\ell}\\in\\left\\{  0,1,\\ldots,10\\right\\}  $.\r\nTherefore, $b_{\\ell}-b_{k}\\in\\left\\{  -10,-9,\\ldots,10\\right\\}  $.\r\nFurthermore, $k-\\ell\\in\\left\\{  -10,-9,\\ldots,10\\right\\}  $ (since both $k$\r\nand $\\ell$ belong to the set $\\left\\{  1,2,\\ldots,10\\right\\}  $) and\r\n$k-\\ell\\neq0$ (since $k\\neq\\ell$). Thus, Claim 1 (applied to $u=k-\\ell$ and\r\n$v=b_{\\ell}-b_{k}$) yields $b_{\\ell}-b_{k}=0$. In other words, $b_{\\ell}%\r\n=b_{k}$. This contradicts $b_{\\ell}\\neq b_{k}$. Thus, $\\mathbf{a}=\\mathbf{b}$\r\n(because \\textit{ex falso quodlibet})\\footnote{Of course, this shows that the\r\ncase we are considering doesn't ever happen -- i.e., our WLOG assumption left\r\nus only an impossible case to consider. But it was not clear a priori that\r\nthis case was impossible; we had to work to reach this conclusion.}. This\r\nsolves part \\textbf{(b)} of the exercise.\r\n\r\n\\begin{thebibliography}{99999999}                                                                                         %\r\n\r\n\r\n\\bibitem[Grinbe19]{detnotes}Darij Grinberg, \\textit{Notes on the combinatorial\r\nfundamentals of algebra}, 10 January 2019. \\newline%\r\n\\url{http://www.cip.ifi.lmu.de/~grinberg/primes2015/sols.pdf} \\newline The\r\nnumbering of theorems and formulas in this link might shift when the project\r\ngets updated; for a \\textquotedblleft frozen\\textquotedblright\\ version whose\r\nnumbering is guaranteed to match that in the citations above, see\r\n\\url{https://github.com/darijgr/detnotes/releases/tag/2019-01-10} .\r\n\r\n\\bibitem[Rogers71]{Rogers71}\\href{https://doi.org/10.1007/BF02993626}{Kenneth\r\nRogers, \\textit{An elementary proof of a theorem of Jacobson}, Abhandlungen\r\nAus Dem Mathematischen Seminar Der Universit\\\"{a}t Hamburg, \\textbf{35} (3-4),\r\n1971, pp. 223--229. doi:10.1007/bf02993626}.\r\n\r\n\\bibitem[Vorobi02]{Vorobi02}%\r\n\\href{https://doi.org/10.1007/978-3-0348-8107-4}{Nicolai N. Vorobiev,\r\n\\textit{Fibonacci Numbers}, Translated from the Russian by Mircea Martin,\r\nSpringer 2002 (translation of the 6th Russian edition)}.\r\n\\end{thebibliography}\r\n\r\n\r\n\\end{document}", "meta": {"hexsha": "9d3567a5620499305b13022ebf38d6b339664d3e", "size": 81243, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "mt2s.tex", "max_stars_repo_name": "darijgr/algebra19s", "max_stars_repo_head_hexsha": "16476909502a4566bd33b4f11ade52829ef9b16f", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-03-21T05:38:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-17T00:48:51.000Z", "max_issues_repo_path": "mt2s.tex", "max_issues_repo_name": "darijgr/algebra19s", "max_issues_repo_head_hexsha": "16476909502a4566bd33b4f11ade52829ef9b16f", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mt2s.tex", "max_forks_repo_name": "darijgr/algebra19s", "max_forks_repo_head_hexsha": "16476909502a4566bd33b4f11ade52829ef9b16f", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.3361125586, "max_line_length": 170, "alphanum_fraction": 0.6298388784, "num_tokens": 32258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.30049271898234176}}
{"text": "\\documentclass[twocolumn]{aastex62}\n\\usepackage{bm}\n\\usepackage{amsmath,amsfonts,amssymb}\n\\usepackage{color}\n%\\usepackage{layouts}\n\n\\usepackage{minted}\n\\usepackage{graphicx}\n%\\usepackage{subfig}\n\n\n\\newcommand\\teff{T_{\\rm eff}}\n\\newcommand\\logg{\\log{g}}\n\\newcommand\\feh{[\\rm{Fe}/\\rm{H}]}\n\n\\newcommand{\\project}[1]{\\textsl{#1}}\n\\newcommand{\\package}[1]{\\texttt{#1}}\n\\newcommand{\\acronym}[1]{{\\small{#1}}}\n\\newcommand{\\article}{\\emph{Article}}\n\n\\newcommand{\\Gaia}{\\project{Gaia}}\n\\newcommand{\\gaia}{\\project{gaia}}\n\\newcommand{\\Galah}{\\project{Galah}}\n\\newcommand{\\GALAH}{\\project{GALAH}}\n\\newcommand{\\APOGEE}{\\project{APOGEE}}\n\\newcommand{\\todo}[1]{\\textcolor{red}{#1}}\n\\newcommand{\\consider}[1]{\\textcolor{blue}{#1}}\n\n\n\\newcommand{\\vect}[1]{\\boldsymbol{\\mathbf{#1}}}\n\\renewcommand{\\vec}[1]{\\vect{#1}}\n\n\\newcommand{\\weight}{\\pi}\n\\newcommand{\\data}{\\textbf{Y}}\n\\newcommand{\\vecdata}{\\vec\\data}\n\\newcommand{\\vecdataunscaled}{\\vec{X}}\n\\newcommand{\\diag}[1]{\\textrm{diag}(#1)}\n\n\\newcommand{\\nextstep}{^\\textrm{(t+1)}}\n\\newcommand{\\thisstep}{^\\textrm{(t)}}\n\\newcommand{\\transpose}{^\\intercal}\n\\newcommand{\\eye}{\\textbf{I}}\n\n\\newcommand{\\factorloads}{\\textbf{L}}\n\\newcommand{\\factorscores}{\\textbf{S}}\n\\newcommand{\\specificvariance}{\\vec{D}}\n\n\\newcommand{\\scoremeans}{\\vec\\xi}\n\\newcommand{\\scorecovs}{\\vec\\Omega}\n\n\\newcommand{\\NumData}{N}\n\\newcommand{\\NumDimensions}{D}\n\\newcommand{\\numdata}{n}\n\\newcommand{\\numdimensions}{d}\n\\newcommand{\\NumLatentFactors}{J}\n\\newcommand{\\numlatentfactors}{j}\n\\newcommand{\\NumComponents}{K}\n\\newcommand{\\numcomponents}{k}\n\\newcommand{\\likelihood}{\\mathcal{L}}\n\\newcommand{\\ExperimentHash}{89dab}\n\\newcommand{\\EvaluationHash}{c7d68}\n\n\n\\newcommand{\\ExpThreeNumAbundances}{17}\n\n\n\\received{2019}\n\\revised{2019}\n\\accepted{2019}\n\n\\newcommand{\\vcpath}{vc.tex}\n\n\\IfFileExists{\\vcpath}{\\input{\\vcpath}}{\n    \\newcommand{\\giturl}{UNKNOWN}\n    \\newcommand{\\gitslug}{UNKNOWN}\n    \\newcommand{\\githash}{UNKNOWN}\n\t\\newcommand{\\gitdate}{UNKNOWN}\n\t\\newcommand{\\gitauthor}{UNKNOWN}\n}\n\n\n\n\\submitjournal{AAS Journals}\n\n\\shorttitle{A data-driven model of nucleosynthesis with chemical tagging in latent space}\n\\shortauthors{Casey et al.}\n\n\\begin{document}\n\n\\title{A data-driven model of nucleosynthesis with chemical tagging in a lower-dimensional latent space}\n\n\\correspondingauthor{Andrew R. Casey}\n\\email{andrew.casey@monash.edu}\n\n\n\\author[0000-0003-0174-0564]{Andrew R. Casey}\n\\affiliation{School of Physics \\& Astronomy, \n\t\t\t Monash University,\n\t\t\t Wellington Rd, Clayton 3800, Victoria, Australia}\n\\affiliation{Faculty of Information Technology, \n\t\t\t Monash University, \n\t\t\t Wellington Rd, Clayton 3800, Victoria, Australia}\n\t\t\t \n\\author[0000-0003-2952-859X]{John C. Lattanzio}\n\\affiliation{School of Physics \\& Astronomy, \n\t\t\t Monash University,\n\t\t\t Wellington Rd, Clayton 3800, Victoria, Australia}\n\n\\author[0000-0002-1716-690X]{Aldeida Aleti}\n\\affiliation{Faculty of Information Technology, \n\t\t\t Monash University, \n\t\t\t Wellington Rd, Clayton 3800, Victoria, Australia}\n\n\\author[0000-0002-0583-5918]{David L. Dowe}\n\\affiliation{Faculty of Information Technology, \n\t\t\t Monash University, \n\t\t\t Wellington Rd, Clayton 3800, Victoria, Australia}\n\n\\author[0000-0001-7516-4016]{Joss Bland-Hawthorn}\n\\affiliation{Sydney Institute for Astronomy, School of Physics,\n\t\t\t A28, The University of Sydney, NSW 2006, Australia}\n\\affiliation{Center of Excellence for Astrophysics in Three Dimensions (ASTRO-3D),\n\t\t\t Australia}\n\\affiliation{Miller Professor, Miller Institute, \n\t\t\t UC Berkeley, \n\t\t\t Berkeley, CA 94720, USA}\n\n\\author[0000-0002-4031-8553]{Sven Buder}\n\\affiliation{Research School of Astronomy and Astrophysics,\n\t\t\t Australian National University,\n\t\t\t Canberra, ACT 2611, Australia}\n\n\\author[0000-0003-3081-9319]{Geraint F. Lewis}\n\\affiliation{Sydney Institute for Astronomy, School of Physics,\n\t\t\t A28, The University of Sydney, NSW 2006, Australia}\n\n\\author[0000-0002-3430-4163]{Sarah L. Martell}\n\\affiliation{School of Physics,\n\t\t\t University of New South Wales, \n\t\t\t Sydney, NSW 2052, Australia}\n\t\n\\author[0000-0001-5344-8069]{Thomas Nordlander}\t\t\t \n\\affiliation{Research School of Astronomy and Astrophysics,\n\t\t\t Australian National University,\n\t\t\t Canberra, ACT 2611, Australia}\n\\affiliation{Center of Excellence for Astrophysics in Three Dimensions (ASTRO-3D), \n\t\t\t Australia}\n\t\t\t \n\\author[0000-0002-8165-2507]{Jeffrey D. Simpson}\n\\affiliation{School of Physics,\n\t\t\t University of New South Wales, \n\t\t\t Sydney, NSW 2052, Australia}\n\n\\author[0000-0002-0920-809X]{Sanjib Sharma}\t\t\t\t\t\t \n\\affiliation{Sydney Institute for Astronomy, School of Physics,\n\t\t\t A28, The University of Sydney, NSW 2006, Australia}\t\t\t\t\t\t \n\t\t\t\t\t\t \n\\author[0000-0003-1124-8477]{Daniel B. Zucker}\n\\affiliation{Department of Physics and Astronomy,\n\t\t\t Macquarie University, \n\t\t\t Sydney, NSW 2109, Australia}\n\t\t\t \n\n\\begin{abstract}\nChemical tagging seeks to identify unique star formation sites from\npresent-day stellar abundances.\nPrevious techniques have treated each abundance dimension as being\nstatistically independent, despite theoretical expectations that\nmany elements can be produced by more than one nucleosynthetic process.\nIn this work we introduce a data-driven model of nucleosynthesis \nwhere a set of latent factors (e.g., nucleosynthetic yields) contribute\nto all stars with different scores, and clustering (e.g., chemical tagging) \nis modelled by a mixture of multivariate Gaussians\nin a lower-dimensional latent space.\nWe use an exact method to simultaneously estimate the factor scores for\neach star, the partial assignment of each star\nto each cluster, and the latent factors common to all stars, even in the\npresence of missing data entries.\nWe use an information-theoretic Bayesian principle to estimate the number of\nlatent factors and clusters.\nUsing the second \\Galah\\ data release we find that five latent factors are\npreferred to explain $N =$ 1,072 stars with \\ExpThreeNumAbundances\\ chemical abundances. \nWe identify the rapid- and slow-neutron capture \nprocesses, as well as latent factors consistent with Fe-peak and \n$\\alpha$-element production, and another where only K and Zn dominate.\nWhen we consider $N \\sim$ 100,000 stars with missing abundances we find \nanother seven factors, as well as 16 components in latent space.\nDespite these components showing separation in chemistry that is explained\nthrough different yield contributions, none show significant structure in \ntheir positions or motions. We argue that more data, and joint priors \non cluster membership that are constrained by dynamical models, are necessary\nto realise chemical tagging at a galactic-scale.\nWe release accompanying software that scales well with the available data,\nallowing for model parameters to be optimised in seconds given a fixed number\nof latent factors, components, and $\\sim10^7$ abundance measurements.\n\\end{abstract}\n\n\\keywords{Bayesian statistics (1900), Chemical abundances (224), Galaxy chemical evolution (580)}\n\n\\section{Introduction} \\label{sec:intro}\n\nThe detailed chemical abundances that are observable in a star's photosphere provide a\nfossil record that carries with it information about where and when that star\nformed \\citep{Freeman;Bland-Hawthorn:2002}. While the photospheric abundances remain largely unchanged throughout\na star's lifetime \\citep[however see][]{Dotter:2017,Ness:2018b}, the dynamical \ndissipation timescale of open clusters in the Milky Way disc is of order a few \ngigayears \\citep{Portegies-Zwart:1998}. That makes chemical tagging an attractive \napproach to identify star formation sites long after those stars are no longer \ngravitationally bound to each other.\n\n\nGravitationally bound star clusters have been useful laboratories for\ntesting the limits and utility of chemical tagging. Although biases arise when\nonly considering star clusters that are still gravitationally bound, the chemical\nhomogeneity of open clusters provides an empirical measure of how similar stars\nwould need to be before they could be tagged as belonging to the same\nstar formation site \\citep{Bland-Hawthorn:2010b,Bland-Hawthorn:2010a,Mitschang:2014}. However, there are analysis\nissues in understanding how precisely those chemical abundances can be measured\n\\citep{Bovy:2016}, and how chemically similar stars can be that did not form \ntogether \\citep[doppleg\\\"angers;][]{Ness:2018}.\nIf open clusters were truely chemically homogeneous then under idealistic \nassumptions our ability to chemically tag the Milky Way would depend primarily\non the precision with which we can measure those chemical abundances in stars. \nData-driven approaches to modelling stellar spectra are\nimproving upon this precision \\citep{Ness:2015,Ness:2018a,Ness:2018b,\nCasey:2016,Casey:2017,Ho:2017b,Ho:2017a,Leung;Bovy:2018,Ting:2019}, but more work is\nneeded: astronomers have not yet developed unbiased estimators of chemical\nabundances that saturate the Cram\\'er-Rao bound \\citep{Cramer:1946,Rao:1945}.\n\n\nChemical tagging experiments require a catalogue of precise chemical abundance\nmeasurements for a large number of stars,\nwhere those chemical abundances trace different nucleosynthetic pathways.\nThis is the primary goal of the Galactic Archaeology with \\project{HERMES} (\\Galah) survey \\citep{DeSilva:2015,Martell:2017,Buder:2018},\na stellar spectroscopic survey that uses the High Efficiency and Resolution \nMulti-Element Spectrograph \\citep[\\project{HERMES};][]{Sheinis:2015} on the 3.9~m Anglo-Australian \nTelescope (AAT).  \\Galah\\ will observe up to $10^6$ stars in the \nMilky Way, and measure up to 30 chemical abundances for each star \\citep{Bland-Hawthorn:2016}. This includes\nlight odd-Z elements (e.g., Na, K), elements produced through\nalpha-particle capture (e.g., Mg, Ca, Ti), and elements produced\nthrough the slow (e.g., Ba) and rapid neutron-capture process\n(e.g., Eu). No other current or planned spectroscopic survey provides an equivalent set of\nchemical abundances for a comparable number of stars.\n\n\n\nGiven these data and the most favourable assumptions in chemical tagging \n-- that star clusters are truely chemically homogenous, that we can measure \nthose abundances with infinite precision, and that those abundances are \ndifferentiable between star clusters -- then chemical\ntagging becomes a clustering problem. All clustering techniques applied to \nchemical tagging thus far have assumed that the data dimensions are independent. That is to say\nthat adding a dimension of say [Ni/H] provides independent information\nthat could not have been predicted from other elemental abundances.\nTheory and observations agree that this cannot be true.\nNucleosynthetic processes produce multiple elements in varying\nquantities, and the effective dimensionality of stellar abundance datasets has been shown\nto be lower than the actual number of abundance dimensions \\citep{Ting:2012,Price-Jones:2018,Milosavljevic:2018}.\nAny clustering approach that treats each new elemental abundance as an \nindependent axis of information will therefore conclude with biased inferences\nabout the star formation history of our Galaxy. \n\n\nIt is not trivial to confidently estimate\nthe nucleosynthetic yields that have contributed to the chemical abundances of each star. There are\nqualitative statements that can be made for large numbers of stars, or particular\ntypes of stars, but quantifying the precise contribution of different processes\nto each star is an unsolved problem. For example, the so-called [$\\alpha$/Fe] `knee' in\nabundance ratios in the Milky Way can qualitatively be explained by \ncore-collapse supernovae being the predominant nucleosynthetic process in the\nearly Milky Way before Type Ia supernovae made a significant contribution, but \nefforts to date have not sought to try to explain the detailed abundances of \nstars as a contribution of yields from different systems \\citep[however see][]{West:2013}.\nThis is in part \nbecause of the challenging and degenerate nature of the problem as described, \nand is complicated by the differences in yield predictions that account from \nprescriptions used in different theoretical models.\n\n\nNew approaches to chemical tagging are clearly needed. Immediate advances would\ninclude methods that take the dependence among chemical elements into account\nwithin some generative model, or techniques that combine chemical abundances\nwith dynamical constraints to place joint prior probabilities on whether any\ntwo stars could have formed from the same star cluster, given some model of the\nMilky Way. \n\nIn this work we focus on the former.\nHere we present a new approach to chemical tagging that allows us to identify \nthe latent (unobserved) factors that contribute to the chemical abundances of \nall stars (e.g., nucleosynthetic yields) while simultaneously performing \nclustering in the latent space. Notwithstanding caveats that we will\ndiscuss in detail, this allows us to infer nucleosynthetic yields rather than\nstrictly prescribe them from models. Moreover, the scale of the clustering\nproblem reduces by a significant fraction because the clustering is performed in\na lower dimensional latent space instead of the higher dimensional data space.\nIn Section~\\ref{sec:methods} we describe the model and the methods we use to\nestimate the model parameters. Section~\\ref{sec:experiments} describe the \nexperiments performed using generated and real data sets. We discuss the results\nof these experiments in Section~\\ref{sec:discussion}, including the caveats with\nthe model as described. We conclude in Section~\\ref{sec:conclusions}.\n\n\n\n\\section{Methods} \\label{sec:methods}\n\nLatent factor analysis is a common statistical approach for describing correlated \nobservations with a lower number of latent variables \\citep[e.g.,][]{Thompson:2004}.\nRelated techniques include principal component analysis \\citep{Hotelling:1933} and its\nvariants \\citep{Tipping;Bishop:1999}, singular value decomposition \\citep{Golub:1970}, and other\nmatrix factorization methods. While factor analysis on its own is a useful\ndimensionality reduction tool to identify latent factors that contribute to\nthe chemical abundances of stars \\citep[e.g.,][]{Ting:2012,Price-Jones:2018,Milosavljevic:2018}, factor\nanalysis cannot describe clustering in the data (or latent) space. As a result,\nsome works have performed clustering and then required different latent factors for each (totally assigned) component \\citep[e.g.,][]{EdwardsDowe1998}.\nSimilarly, clustering techniques applied to chemical abundances to date \n\\citep[e.g.,][]{Hogg:2016} do not account for the lower effective dimensionality in\nelemental abundances.\n\nHere we expand on a variant of factor analysis known elsewhere as a mixture of common \nfactor analyzers \\citep{Baek:2010}, where the data are generated by a set of \nlatent factors that are common to all data, but the scoring (or extent) of those\nfactors is different for each data point, and the data can be modelled as a\nmixture of multivariate normal distributions in the latent space (factor scores).\nIn this work the data $\\vecdataunscaled$ is a \n$\\NumDimensions \\times \\NumData$ matrix where $\\NumData$ is the number of \nstars and $\\NumDimensions$ is the number of chemical abundances measured \nfor each star. We assume a generative model for the data \n\\begin{equation}\n\t\\vecdataunscaled = \\vec\\mu + \\factorloads\\factorscores + \\vec{e}\n\t\\label{eq:generative-model}\n\\end{equation}\n\n\\noindent{}where $\\factorloads$ is a $\\NumDimensions \\times \\NumLatentFactors$ \nmatrix of factor loads that is common to all data points, $\\NumLatentFactors$ is\nthe number of latent factors, and the factor scores \nfor the $\\numdata^\\mathrm{th}$ data point\n\\begin{equation}\n\t\\factorscores_\\numdata \\sim \\mathcal{N}(\\vec\\xi_\\numcomponents, \\vec\\Omega_\\numcomponents)\n\\end{equation}\n\\noindent{}are drawn from\\footnote{For clarifying nomenclature across disciplines, the terminology $z \\sim \\mathcal{N}(0, 1)$ indicates that the $z$ variable \\emph{is drawn from} a standard normal distribution.} the $\\numcomponents^\\mathrm{th}$ multivariate\nnormal distribution, where each $\\numcomponents^\\mathrm{th}$ component has a $\\NumLatentFactors$-dimensional mean and a dense $\\NumLatentFactors \\times \\NumLatentFactors$ covariance matrix.\nThe mean vector $\\vec\\mu$ describes the mean datum in each dimension.\nThe factor scores for all data points $\\factorscores$ is then a \n$\\NumLatentFactors \\times \\NumData$ matrix, where each data point has a partial\nassociation to the components in latent space. \nWe assume $\\vec{e} \\sim \\mathcal{N}\\left(\\vec{0}, \\textrm{diag}(\\specificvariance)\\right)$\nis independent of the latent space, and $\\specificvariance$ is a\nvector of variances in each $\\NumDimensions$ abundance dimensions.\nIn this model each data point can be represented as being drawn\nfrom a mixture of multivariate normal components, except the components\nare \\emph{clustered in the latent space} $\\factorscores$ and projected\ninto the data space by the factor loads $\\factorloads$. In a sense we\nare using latent factor analysis as a form of dimensionality reduction and\nsimultaneously performing clustering in latent space (Figure~\\ref{fig:schematic}).\n\n\nWe assume that the latent space is lower dimensionality than the\ndata space (i.e., $\\NumLatentFactors < \\NumDimensions$).\nWithin the context of stellar abundances, the factor loads\n$\\factorloads$ can be thought of as the \\emph{mean} yields\nof nucleosynthetic\nevents (e.g., $s$-process production from AGB stars averaged over\ninitial mass function and star formation history), and the\nfactor scores are analogous to the relative counts of those \nnucleosynthetic events. The clustering in factor scores\nachieves the same as a clustering procedure in data space,\nexcept we simultaneously estimate the latent processes that are\ncommon to all stars (the so-called factor loads, analogous to \nnucleosynthetic yields). Within this framework a rare nucleosynthetic event\ncan still be described as a `factor load' $\\factorloads_\\numlatentfactors$, \nbut its rarity would be represented by associated factor\nscores being zero for most stars and thus have no contribution\nto the observed abundances. In practice the factor loads can only be \nidentified up to orthogonality and cannot be expressly interpreted as\nnucleosynthetic yields because they have limited physical meaning\n(we discuss this further in Section~\\ref{sec:discussion}),\nbut this description of typical yields and relative event rates should\nhelp build intuition for the model parameters, and provide context\nwithin the astrophysical problem it is being applied.\n\n\n\\begin{figure*}\n\t\\includegraphics[width=\\textwidth]{experiments/schematic.png}\n\t\\caption{A schematic that visualises the model components.\n\t\t\t The data are shown on the left in greyscale, and magnified on the\n\t\t\t right where each star (row) is coloured by its identified\n\t\t\t component in latent space.\n\t\t\t For each chemical abundance (column) there is a mean value and\n\t\t\t variance that is independent of the latent space.\n\t\t\t The latent factors $\\factorloads$ are analogous to nucleosynthetic\n\t\t\t yields and are common to all stars. The factor scores $\\factorscores$\n\t\t\t have an entry for each yield, for each star (row). The latent scores are modelled\n\t\t\t by a mix of multivariate normal distributions of $\\NumComponents$\n\t\t\t components, which are coloured accordingly. The matrices of factor \n\t\t\t scores $\\factorscores$ and factor loads $\\factorloads$ are \n\t\t\t visualised at the bottom. For clarity here we show transposed\n\t\t\t matrices (e.g., see Eq. \\ref{eq:generative-model}).}\n\t\\label{fig:schematic}\n\\end{figure*}\n\n\nIncluding latent factors in the model description allows us to account for \nprocesses that affect multiple elemental abundances. In this way we are \naccounting for the fact that the data dimensions are not independent of\neach other. Another benefit is the scaling with computational cost. If we \nconsidered data sets of order $10^{7.5}$\nentries (e.g., 30 chemical abundances for $10^6$ stars) purely as a\nclustering problem, then even the most efficient clustering\nalgorithms would incur a significant cumulative computational \noverhead by searching the parameter space for the number of\nclusters, and the optimal model parameters given that number\nof components. However, because the mixture of factor analyzers\napproach assumes that there is a \\emph{lower dimensional latent \nspace} in which the data are clustered, and that clustering is \nprojected into real space by common factor loads, the \ndimensionality of the clustering problem is reduced from \n$N \\times D$ to $N \\times J$. This reduces computational cost through\nfaster execution of each optimization step, and on average fewer optimization steps\nneeded to reach a specified convergence threshold.\n\nFrom a statistical standpoint, the primary advantage to using\na mixture of factor analysers is that we can simultaneously\nestimate latent factors (e.g., infer nucleosynthetic \nyields) and perform clustering (e.g., chemical tagging) \nwithin a statistically consistent framework. That is to say\nthat we have a generative data-driven model that can \nquantitatively describe nucleosynthetic yields, and the\nfactor scores can explain the variance in turbulence and gas mixing,\nor star formation efficiency, and the parameters of this model\ncan be simultaneously estimated in a self-consistent way with\na single scalar-justified objective function.\n\nWithout loss of generality the density of the mean-subtracted \ndata $\\vecdataunscaled - \\vec\\mu$ (which we hereafter will refer to simply as $\\vecdata$) can be described as \n\\begin{equation}\n\tf(\\vecdata; \\vec\\Psi) = \\sum_{\\numcomponents=1}^{\\NumComponents}\\weight_\\numcomponents\\phi(\\vecdata;\\factorloads\\scoremeans_\\numcomponents, \\factorloads\\scorecovs_\\numcomponents\\factorloads\\transpose + \\diag{\\specificvariance})\n\\end{equation}\n\\noindent{}given $\\NumLatentFactors$ common factor loadings and $\\NumComponents$ components\nclustered in the latent (factor score) space. Here the parameter\nvector\n$\\vec\\Psi$ includes $\\{\\factorloads,\\vec\\pi,\\scoremeans,\\scorecovs,\\specificvariance\\}$, and $\\phi(\\vecdata; \\vec\\theta)$\ndescribes the density of a multivariate Gaussian distribution,\nand $\\weight_\\numcomponents$ describes the relative weighting of the $\\numcomponents^\\mathrm{th}$\ncomponent in latent space and $\\sum\\vec\\weight_{\\numcomponents} = 1$.\nThe log likelihood is then given by\n\\begin{equation}\n\t\\log\\mathcal{L}(\\vecdata|\\vec\\Psi) = \\sum_{\\numdata=1}^{\\NumData}\\log{f(\\vecdata;\\vec\\Psi)} \\quad . \\label{eq:log-likelihood}\n\\end{equation}\n\n\nThe model as described is indeterminate in that there is no unique \nsolution for the factor loads $\\factorloads$ and scores\n$\\factorscores$. These quantities can only be determined up until \northogonality in $\\factorloads$. However, as we will describe in Section \\ref{sec:expectation-maximization}, with suitable priors on $\\vec\\Psi$ \none can efficiently estimate the model parameters using the expectation-maximization\nalgorithm \\citep{Dempster:1977}. \n\n\\vspace{1em}\n\\subsection{Initialisation} \\label{sec:initialisation}\n\nHere we describe how the model parameters are initialised.\\footnote{This describes the default initialisation approach. Other approaches are available in the accompanying software.}\nTo initialise the factor loads $\\factorloads$ we start by randomly drawing a $\\NumDimensions \\times \\NumDimensions$ matrix from a Haar distribution \\citep{Haar:1933},\nwhich is uniform on the special orthogonal group $\\textrm{SO}(n)$ and therefore guaranteed to return an orthogonal\nmatrix with a determinant of unity \\citep{Stewart:1980}.\nWe denote the $\\NumLatentFactors \\times \\NumDimensions$ left-most region\\footnote{The region choice is arbitrary. All that is required is that the randomly-generated matrix have mutually orthogonal vectors.}\n of this\nmatrix to be our initial guess of $\\factorloads$, which provides a set of mutually\northogonal vectors.\n\nWe then initially assign each data point as belonging to one of the\n$\\NumComponents$ components using the \\texttt{k-means++} algorithm \\citep{Arthur:2007}\nin the latent space. Given the initial\nfactor loads and assignments, we then estimate the relative weights\n$\\vec\\pi$, the mean factor scores of each component $\\scoremeans$, and\nthe covariance matrix of factor scores of each component $\\scorecovs$.\nFinally, we initialise the specific variance $\\specificvariance$ in each\ndimension as the variance in each data dimension. Other initialisation \nmethods for the latent factors include singular value decomposition \\citep{Golub:1970}\nor generating random noise with orthogonal constraints, and random assignment\nis an alternative method that is available for initialising assignments.\n\nThroughout this work we repeat this initialisation procedure 25 times for\nevery trial of $\\NumLatentFactors$ and $\\NumComponents$ for a given data set. \nWe then run expectation-maximization (Section~\\ref{sec:expectation-maximization})\nfrom each initialisation until the log likelihood improves by less than $10^{-5}$\nper step, and we adopt the model with the highest log likelihood as the preferred \nmodel given that trial of $\\NumLatentFactors$, $\\NumComponents$, and the data. Although\nthis optimisation procedure is not convex, in practice it is normally sufficient to\ninitialise from many points to avoid local minima.\n\n\n\\subsection{Expectation-Maximization} \\label{sec:expectation-maximization}\n\nWe use the expectation-maximization algorithm to estimate the model parameters\n\\citep{Dempster:1977}. With each expectation step we evaluate the log likelihood \ngiven the model parameters\\footnote{When evaluating the log likelihood we use the precision (sparse inverse) matrix of the Cholesky decomposition of the covariance matrix for computational efficiency and stability.} $\\vec\\Psi$, the message length, and the $\\NumData \\times \\NumComponents$ responsibility \nmatrix $\\vec\\tau$ whose entries are the posterior probability that the \n$\\numdata$th data point is associated to the $\\numcomponents$th component, given \nthe data $\\vecdata$ and the current estimate of the parameter vector $\\vec\\Psi$:\n\\begin{equation}\n\t\\tau_{\\numdata\\numcomponents} = \\frac{\\weight_\\numcomponents\\phi(\\vecdata_\\numdata;\\factorloads\\scoremeans_\\numcomponents, \\factorloads\\scorecovs_\\numcomponents\\factorloads\\transpose + \\diag{\\specificvariance})}{\\sum_{g=1}^{G}\\weight_g\\phi(\\vecdata_\\numdata;\\factorloads\\scoremeans_g, \\factorloads\\scorecovs_g\\factorloads\\transpose + \\diag{\\specificvariance})} \\quad .\n\\end{equation}\n\nAt the maximization step we update our estimates of the parameters $\\vec\\Psi$,\nconditioned on the data $\\vecdata$ and the responsibility matrix $\\vec\\tau$.\nThe updated parameters estimates are found by setting the second derivative\nof the log likelihood (Eq.~\\ref{eq:log-likelihood}) to zero and solving for\nthe parameter values.\\footnote{Strictly this introduces a statistical inconsistency in that we should update our parameter estimates by setting the second derivative of our information-theoretic objective function (Eq.~\\ref{eq:message-length}) to zero instead of the log likelihood, but this inconsistency only becomes serious with small $N$ (e.g., $\\approx 30$) -- precisely the opposite situation of chemical tagging!}\nIn doing so this guarantees that every updated\nestimate of the model parameters is guaranteed to increase the log likelihood.\nAlthough there are no guarantees against converging on local minima, in \npractice it is sufficient to run expectation-maximization from multiple\ninitialisations (as we do) in order to ensure that the global minimum is reached.\nAt the maximization step we first update our estimate of the relative weights \n$\\vec\\weight\\nextstep$ given the responsibility matrix $\\vec\\tau$\n\\begin{equation}\n\t\\weight_\\numcomponents\\nextstep = \\frac{1}{\\NumData} \\sum_{\\numdata=1}^{\\NumData}\\tau_{\\numdata\\numcomponents}\n\\end{equation}\n\\noindent{}where the $\\vec{\\Psi}\\thisstep$ superscript refers to the current parameter estimates and $\\vec{\\Psi}\\nextstep$ refers to the updated estimate for the next iteration.\nThe updated estimates of the mean factor scores \n$\\scoremeans\\nextstep$ for each component are then given by\n\\begin{eqnarray}\n\t\\scoremeans_\\numcomponents\\nextstep = \\scoremeans_\\numcomponents\\thisstep + \\frac{\\vec{G}\\transpose(\\vecdata\\transpose - \\factorloads\\thisstep\\scoremeans_\\numcomponents\\thisstep)\\vec\\tau_\\numcomponents}{\\NumData\\weight_\\numcomponents\\nextstep}\n\\end{eqnarray}\n\\noindent{}where:\n\\begin{eqnarray}\n\t\\vec{W} &=& (\\scorecovs_\\numcomponents\\thisstep)^{-1} \\\\\n\t\\vec{V} &=& \\left(\\specificvariance\\thisstep\\right)^{-1} \\\\\n\t\\vec{C} &=& (\\vec{W} + (\\factorloads\\thisstep)\\transpose\\vec{V}\\factorloads\\thisstep)^{-1} \\\\\n\t\\vec{G} &=& \\left[\\vec{V} - \\vec{V}\\factorloads\\thisstep\\vec{C}\\left(\\vec{V}\\factorloads\\thisstep\\right)\\transpose\\right]\\factorloads\\thisstep\\scorecovs_k\\thisstep \\quad .\n\\end{eqnarray}\n\nThe covariance matrices of the components of factor scores $\\scorecovs\\nextstep$\nare updated next,\n\\begin{equation}\n\t\\scorecovs_\\numcomponents\\nextstep = \\left(\\eye - \\vec{G}\\transpose\\factorloads\\thisstep\\right)\\scorecovs_\\numcomponents\\thisstep + \\frac{\\vec{G}\\transpose\\vec{Z}\\left(\\vec{Z}\\vec\\tau_\\numcomponents\\transpose\\right)\\transpose\\vec{G}}{N\\weight_\\numcomponents\\nextstep}\n\\end{equation}\n\\noindent{}where\n\\begin{eqnarray}\n\t\\vec{Z} &=& \\vecdata\\transpose - \\factorloads\\thisstep\\scoremeans_\\numcomponents\\thisstep \\quad .\n\\end{eqnarray}\n\nAfter some linear algebra, updated estimates of the common factor loads $\\factorloads\\nextstep$\ncan be found from\n\\begin{equation}\n\t\\factorloads\\nextstep = \\factorloads_{a}\\left(\\factorloads_{b}^{-1}\\eye\\right)\n\\end{equation}\n\\noindent{}where:\n\\begin{eqnarray}\n\t\\factorloads_\\textrm{a} &=& \\sum_{\\numcomponents=1}^{\\NumComponents}\\left[ \\vec\\tau_\\numcomponents\\transpose\\vecdata\\left(\\scoremeans_\\numcomponents\\thisstep\\right)\\transpose + \n\t\\vec{G}\\transpose\\vec\\tau_\\numcomponents\\vec{Z}\\transpose\\vec{G}\\right] \\\\\n\t\\factorloads_\\textrm{b} &=& N\\sum_{\\numcomponents=1}^{\\NumComponents}\\left[\\weight_\\numcomponents\\nextstep\\left(\\scorecovs_\\numcomponents\\nextstep + \\scoremeans_\\numcomponents\\nextstep\\left(\\scoremeans_\\numcomponents\\nextstep\\right)\\transpose\\right)\\right] \\quad\n\\end{eqnarray}\n\n\nFinally, the updated estimate of the specific variances $\\specificvariance\\nextstep$ are given\nby\n\\begin{equation}\n\t\\specificvariance\\nextstep = \\frac{1}{\\NumData}\\left[\\sum^{\\NumComponents}_{\\numcomponents=1}\\vec\\tau_\\numcomponents\\transpose\\left(\\vecdata\\odot\\vecdata\\right) - \\sum_{j=1}^{J}\\left(\\factorloads\\nextstep\\factorloads_\\textrm{b}\\right)\\odot\\factorloads\\nextstep\\right]\n\\end{equation}\n\n\\noindent{}where $\\odot$ denotes the entry-wise product. \nThroughout this work we assume that the data are noiseless and\nwe do not add any observed errors to the constructed covariance matrices.\n\n\n\\subsection{Missing data}\n\nThe expectation-maximization procedure as described requires that there be no \nmissing data entries in order to update our estimates of the responsibility matrix $\\vec\\tau$\nand the model parameters $\\vec\\Psi$.\nIn practice, however, there will often be abundance measurements that are missing\nfor some subset of stars. There are many potential reasons for this, including\nastrophysical explanations (e.g., an absorption line was not present above the noise),\nobservational limitations (e.g., the signal-to-noise ratio was too low, or \ncontamination by a cosmic ray), or various other reasons that cannot be inferred\nfrom the available information.\n\nIn this work we will assume that any missing data measurements are\nmissing at random. The missing data points can then be treated as unknown\nparameters that must be solved for (and updated) at each iteration. Initially\nwe impute zeros for missing data entries in $\\vec\\data$, and at each iteration we update\nthese imputed value with our estimate of what the missing data values\nare given the current model parameters. This ensures that the log-likelihood increases\nwith each iteration. Similarly, with each update we inflate\nour estimates of the specific variances based on the fraction of missing\ndata points in each dimension\n\\begin{equation}\n\\specificvariance_d\\nextstep = \\specificvariance_d\\nextstep\\left(\\frac{N}{N-M}\\right)\n\\end{equation}\n\\noindent{}where $M$ is a the number of missing data entries in the $d$th dimension.\nIn Section \\ref{sec:toy-model-missing-data} we show with a toy model that the latent\nfactor loads and scores can be reliably estimated even in the presence of high fractions\nof missing data (e.g., 40\\%), conditioned on our assumption that the data are missing\nat random.\n\n\n\n\n\n\\subsection{Model Selection}\n\nThe expectation-maximization algorithm as described requires a specified \nnumber of latent factors $\\NumLatentFactors$ and $\\NumComponents$. In the next \nSection we describe a toy model using generated data where we will assume\nthat the true number of latent factors and components are not known. \nWe require some heuristic to decide how many latent factors and components are \npreferred given some data. An increasing number of factors\nand components will undoubtedly increase the log likelihood of the model given\nthe data, but the log likelihood does not account for the increased model \ncomplexity that is afforded by those additional latent factors and components.\n\n\nOne criterion commonly employed for evaluating a class of models is the \nBayesian Information Criterion \\citep[BIC;][]{Schwarz:1978}\n\\begin{equation}\n\t\\textrm{BIC} = Q\\log{N} - 2\\log\\mathcal{L}\\left(\\data|\\vec\\Psi\\right)\n\t \\label{eq:bic}\n\\end{equation} \n\\noindent{}where $Q$ is the number of parameters in this model\n\\begin{equation}\n\tQ = \\frac{\\NumLatentFactors}{2}\\left[2\\left(\\NumDimensions - \\NumLatentFactors\\right) + \\NumComponents\\left(3 + \\NumLatentFactors\\right)\\right] + \\NumComponents + \\NumDimensions - 1\n\\end{equation}\n\\noindent{}which includes $\\NumComponents - 1$ weights (as $\\sum\\weight_\\numcomponents = 1$), $\\NumDimensions$ specific variances, the $\\NumComponents\\NumLatentFactors - \\NumLatentFactors^2$ free parameters needed to uniquely define the mutually orthogonal factor loads matrix $\\factorloads$ \\citep{Baek:2010}, $\\NumComponents \\times \\NumLatentFactors$ parameters for the mean scores $\\scoremeans$, and $\\frac{\\NumComponents\\NumLatentFactors}{2}\\left(\\NumLatentFactors + 1\\right)$ parameters to encode the $\\NumComponents$ full ($\\NumLatentFactors \\times \\NumLatentFactors$) covariance matrices $\\scorecovs$.\n\nWhile the BIC does include a penalisation term for the number of\nparameters (which scales with $\\log{N}$), it does not describe for the\nincreased flexibility that is afforded by the addition of those parameters.\nFor example, adding one parameter\nto a model will increase the BIC by at most $\\log{N}$, but there are different\nways for a single parameter to be introduced. In a fictitious model $y=f(x)$\na parameter $b$ could be added that is a scalar multiple of $x$, or it could be\nintroduced as $x^b$. Despite the difference in model complexity, the same\npenalisation occurs in BIC. Even if the log likelihood were only to improve\nmarginally in both cases, the difference in model complexity is not captured\nby BIC. In other words, there are situations where we are more interested in\nbalancing the model complexity (or the expected Fisher information and similar\nproperties) with the goodness of fit, instead of penalising the number of \nparameters.\n\n\nFor these reasons we use the Minimum Message Length \\citep[MML;][]{Wallace:2005}\nprinciple as a criterion for model selection and evaluation. \nThe classically-described principle of MML is that the best explanation of the\ndata given a model is the one that leads to the shortest so-called two-part message~\\citep{Wallace:2005}, \nwhere a \\textit{message} takes into account both the complexity of the model \nand its explanatory power. The complexity of the model is described through\nthe first part of the message, and the second part of the message describes\nits explanatory power. The \\emph{length} of each message part is quantified\n(or estimated) using information theory, allowing for a fair evaluation between\ndifferent models of varying complexity or explanatory power. MML has been \nshown to perform well on a variety of empirical analyses \n\\citep[see, e.g.,][]{WallaceDowe1994b,viswanathan1999finding,EdwardsDowe1998,WallaceDowe2000,fitzgibbon2004minimum,Wallace:2005,dowe2007bayes,Dowe2008a,Dowe2011a}.\nArguments about the statistical consistency (i.e.,~as the number of data \npoints increases the distributions of the estimates become increasingly \nconcentrated near the true value) of MML are given in \\citet{DoweWallace1997a,Dowe2011a}.\nThe MML principle requires that we explicitly specify our prior beliefs on the\nmodel parameters, providing a Bayesian optimisation approach which can be\napplied across entire classes of models.\n\nThe \\textit{message} must encode two parts: the model, and the data given the\nmodel. The encoding of the message is based on Shannon's information theory~\\citep{Shannon:1948}. \nThe information gained from an event $e$ occurring, where $p(e)$ is the\nprobability of that event, is $I(e) = -\\log_{2}{p(e)}$. The information content\nis largest for improbable outcomes, and smallest for outcomes that we are \nalmost certain about. In other words, an outcome that has a probability close\nto unity has nearly zero information content because almost nothing new is learned from it,\nwhereas rarer events convey a much higher information content. \n\n\n\n\n\nIn practice calculating the message length can be a non-trivial task, \nespecially for models that are reasonably complex. This can make the strict MML\nprinciple intractable in many cases and necessitates\napproximations to the message length\n\\citep[however see][]{Wallace:1987,WallaceDowe1999a,Wallace:2005}. Using a Taylor expansion, a generalised\nscheme can be calculated to estimate the parameter vector $\\vec\\Psi$ that\nminimises the message length ${I}(\\vec\\Psi,\\vecdata)$ \\citep{Wallace:1987},\n\\begin{equation}\n\t{I}(\\vec\\Psi,\\vecdata) = \\frac{Q}{2}\\log\\kappa_Q - \\log\\left(\\frac{p(\\vec\\Psi)}{\\sqrt{|\\mathcal{F}(\\vec\\Psi)|}}\\right) - \\log\\mathcal{L}\\left(\\vecdata|\\vec\\Psi\\right) + \\frac{Q}{2} \\label{eq:mml} \n\\end{equation}\n\\noindent{}where $\\log\\likelihood(\\vecdata|\\vec\\Psi)$ is the familiar\nlog likelihood, $p(\\vec\\Psi)$ is the joint prior density on $\\vec\\Psi$,\n$\\mathcal{F}(\\vec\\Psi)$ is the matrix whose entries are the expected second order\npartial derivatives of the log likelihood,\ncommonly referred to as the expected Fisher information matrix,\n\\begin{equation}\n\t\\mathcal{F}(\\vec\\Psi) = -\\textrm{E}\\left[\\frac{\\partial^2}{\\partial\\vec\\Psi^2}\\log\\likelihood(\\vecdata|\\vec\\Psi)\\right]\n\\end{equation}\n\\noindent{}and as before $Q$ is the number of model parameters.\nContinuous parameters can only be stated to finite precision, which leads\nto the $\\frac{Q}{2}\\log\\kappa_Q$ term that gives a measure of the volume of the region of\nuncertainty in which the parameters $\\vec\\Psi$ are centred. The $\\log\\kappa_Q$\nterm can be reasonably approximated by\n\\begin{equation}\n\t\\log\\kappa_Q = -\\log{2\\pi} + \\frac{1}{Q}\\log{Q\\pi} - \\gamma - 1\n\\end{equation}\n\\noindent{}where $\\gamma$ is Euler's constant.\n\nLike the BIC, the message length is penalised by the number of model parameters\nthrough the $\\log\\kappa_Q$ term. However, the model complexity is also \ndescribed through the priors and the Fisher information matrix, which\ndescribes the curvature of the log likelihood with respect to the model\nparameters. For these reasons, MML provides a more accurate description of\nthe model complexity (or flexibility) because it naturally includes the \ncurvature of the log likelihood with respect to the model parameters\nrather than only penalising models based on the \\emph{number} of\nparameters.\n\n\n\nWe will describe the contributions to the message length in parts. We assume\nthe priors on the number of latent factors $\\NumLatentFactors$ and the\nnumber of components $\\NumComponents$ to be\n$p(\\NumLatentFactors) \\propto 2^{-\\NumLatentFactors}$ and\n$p(\\NumComponents) \\propto 2^{-\\NumComponents}$ respectively,\nsuch that fewer numbers are preferred. The optimal lossless message to \nencode each is \\citep[Sec. 6.8.2;][]{Knorr-Held:2000},\n\\begin{eqnarray}\n\tI(\\NumLatentFactors) &= -\\log{p(\\NumLatentFactors)} &= \\NumLatentFactors\\log{2} + \\textrm{constant} \\label{eq:prior_J} \\\\\n\tI(\\NumComponents) &= -\\log{p(\\NumComponents)} &= \\NumComponents\\log{2} + \\textrm{constant} \\label{eq:prior_K} \\quad .\n\\end{eqnarray}\nOnly $\\NumComponents - 1$ of the relative weights $\\vec\\weight$ need encoding because \n$\\sum_{\\numcomponents=1}^{\\NumComponents}\\weight_\\numcomponents = 1$. We assume a uniform prior on \nindividual weights,\n\\begin{equation}\n\tp(\\vec\\weight) = (\\NumComponents - 1)!\n\\end{equation}\n\\noindent{}and the Fisher information is\n\\begin{equation}\n\t\\mathcal{F}(\\vec\\weight) = \\frac{\\NumData^{\\NumComponents - 1}}{\\prod_{\\numcomponents=1}^{\\NumComponents}\\weight_\\numcomponents}\n\\end{equation}\n\\noindent{}which gives the message length of the relative weights $I(\\vec\\weight)$ to be\n\\begin{eqnarray}\n\tI(\\vec\\weight) &=& -\\log\\left(\\frac{p(\\vec\\weight)}{\\sqrt{|\\mathcal{F}(\\vec\\weight)|}}\\right) \\nonumber \\\\\n\t\t\t   &=& -\\log{p(\\vec\\weight)} - \\frac{1}{2}\\log{|\\mathcal{F}(\\vec\\weight)|} \\nonumber  \\\\\n\t\t\t   &=& -\\log(\\NumComponents - 1)! + \\frac{\\NumComponents - 1}{2}\\log{\\NumData} - \\frac{1}{2}\\sum_{\\numcomponents=1}^{\\NumComponents}\\log\\weight_\\numcomponents \\nonumber \\\\\n\tI(\\vec\\weight) &=& \\frac{1}{2}\\left(\\left(\\NumComponents - 1\\right)\\log\\NumData - \\sum_{\\numcomponents=1}^{\\NumComponents}\\log\\weight_\\numcomponents\\right) -\\log\\Gamma(\\NumComponents) \\quad . \\nonumber \\label{eq:prior_pi} \\\\\n\\end{eqnarray}\n\nWe assume uniform priors for the component means in latent space $\\scoremeans$, \nwhere the bounds are large enough outside the range of observable values such\nthat those priors are proper (integrable) -- a necessary condition for the MML principle -- \nand only add constant terms to the message length, which can be ignored. We assume \na conjugate inverted Wishart prior for the component covariance matrices\n$\\scorecovs$ \\citep{WallaceDowe1994b,WallaceDowe2000,Knorr-Held:2000},\n\\begin{equation}\n\tp(\\scoremeans_\\numcomponents,\\scorecovs_\\numcomponents) \\propto |\\scorecovs_\\numcomponents|^{\\frac{1}{2}(\\NumLatentFactors + 1)} \\quad .\n\\end{equation}\n\n\nWe approximate the determinate of the Fisher information of a multivariate normal $|\\mathcal{F}(\\scoremeans,\\scorecovs)|$\nas $|\\mathcal{F}(\\scoremeans)||\\mathcal{F}(\\scorecovs)|$ \\citep{Oliver:1996,Figueiredo:2002} where\n\\begin{equation}\n\t|\\mathcal{F}(\\scoremeans)| = (\\NumData\\weight_k)^\\NumLatentFactors|\\scorecovs_k|^{-1}\n\\end{equation}\n\\begin{equation}\n\t|\\mathcal{F}(\\scorecovs)| = (\\NumData\\weight_k)^{\\frac{1}{2}\\NumLatentFactors(\\NumLatentFactors+1)}2^{-\\NumLatentFactors}|\\scorecovs_k|^{-(\\NumData+1)}\n\\end{equation}\n\n\\noindent{}such that \n\n\\begin{eqnarray}\n\tI(\\scoremeans,\\scorecovs) &=& -\\sum_{\\numcomponents=1}^{\\NumComponents}\\log{p(\\scoremeans_k,\\scorecovs_k)} + \\frac{1}{2}\\sum_{\\numcomponents=1}^{\\NumComponents}\\log{|\\mathcal{F}(\\scoremeans_k,\\scorecovs_k)|} \\nonumber \\\\\n%\t&=& \\frac{1}{2}\\sum_{\\numcomponents=1}^{\\NumComponents}\\log\\left[(\\NumData\\weight_k)^{\\frac{1}{2}\\NumLatentFactors(\\NumLatentFactors+3)}2^{-\\NumData}|\\scorecovs_k|^{-(\\NumData + 2)}\\right] \\nonumber \\\\\n%\t&& \\cdots \\,\\, -\\sum_{\\numcomponents=1}^{\\NumComponents}\\log{|\\scorecovs_k|}^{\\frac{1}{2}(\\NumLatentFactors + 1)} \\\\\nI(\\scoremeans,\\scorecovs) &=& \\frac{1}{4}\\NumLatentFactors(\\NumLatentFactors+3)\\sum_{\\numcomponents=1}^\\NumComponents\\log{\\NumData\\weight_k} - \\frac{KD}{2}\\log{2} \\nonumber \\\\ \n&& \\cdots \\,\\, -\\frac{1}{2}(2\\NumLatentFactors+3)\\sum_{k=1}^{K}\\log{|\\scorecovs_k|}  \\quad . \\label{eq:prior_xi_omega} \n\\end{eqnarray}\n\nPrevious work on multiple latent factor analysis within the context of MML have\naddressed the indeterminacy between the factor loads and factor scores by\nplacing a joint prior on the \\emph{product} of factor loads and scores \\citep{WallaceMLF,EdwardsDowe1998,Wallace:2005}.\nAdopting the same prior density in our model is not practical because \nit would require the priors $p(\\scoremeans|\\vec\\tau,\\vec\\weight$) and $p(\\scorecovs|\\vec\\tau,\\vec\\weight$).\nThat is, we would require a prior density on both the means $\\scoremeans$\nand covariance matrices $\\scorecovs$ in latent space that requires knowledge\nabout the responsibility matrix $\\vec\\tau$ and relative weights $\\vec\\weight$ in order to estimate the effective scores\n$\\factorscores$ for each data point and calculate a joint prior on the product\nof the factor loads $\\factorloads$ and factor scores $\\factorscores$.\nInstead we address this indeterminacy\nby placing a prior on $\\factorloads$ that ensures it is mutually orthogonal.\nSpecifically, we adopt a Wishart distribution with scale matrix $\\vec{W}$\nand $D$ degrees of freedom for the\n$\\NumLatentFactors\\times\\NumLatentFactors$ matrix $\\vec{M} = \\factorloads\\transpose\\factorloads$.\nIn other words, $\\vec{M} \\sim W_\\NumLatentFactors(D,\\vec{W})$\nand $\\vec{W} = \\textrm{Cov}(\\factorloads\\transpose)$.\nThis\nWishart joint prior density gives highest support for mutually orthogonal vectors,\n\\begin{equation}\n\tp(\\factorloads) = \\frac{|\\factorloads\\transpose\\factorloads|^{\\frac{1}{2}(\\NumDimensions - \\NumLatentFactors - 1)}}{2^{\\frac{\\NumDimensions\\NumLatentFactors}{2}}|\\vec{W}|^{\\frac{\\NumDimensions}{2}}\\Gamma(\\frac{\\NumDimensions}{2})}\\exp\\left[-\\frac{1}{2}\\textrm{Tr}(\\vec{W}^{-1}\\factorloads\\transpose\\factorloads)\\right] \\quad .\n\\end{equation}\n\n\\begin{widetext}\n\\noindent{}Thus the message length to encode $\\factorloads$ is given by\n\\begin{eqnarray}\nI(\\factorloads)\t&=& \\frac{1}{2}\\textrm{Tr}(\\textrm{Cov}(\\factorloads\\transpose)^{-1}\\factorloads\\transpose\\factorloads) - \\frac{1}{2}(\\NumDimensions - \\NumLatentFactors - 1)\\log{|\\factorloads\\transpose\\factorloads|} + \\frac{1}{2}\\NumDimensions\\NumLatentFactors\\log{2} + \\frac{1}{2}\\NumDimensions\\log{|\\textrm{Cov(\\factorloads)}|} - \\Gamma\\left(\\frac{\\NumDimensions}{2}\\right) \\quad . \\label{eq:prior_L}\n\\end{eqnarray}\n%\\end{widetext}\nCombining equations \\ref{eq:prior_J}, \\ref{eq:prior_K}, \\ref{eq:prior_pi}, \\ref{eq:prior_xi_omega}, and \\ref{eq:prior_L} with equation \\ref{eq:mml} leads to the full message length:\n%\\begin{widetext}\n\\begin{eqnarray}\n\tI(\\vec\\Psi, \\vec\\data) &=& -\\log\\likelihood(\\vec\\data|\\vec\\Psi)\n +\\frac{1}{4}\\left(\\NumLatentFactors + 4\\right)\\left(\\NumLatentFactors - 1\\right)\\sum_{\\numcomponents=1}^\\NumComponents\\log\\weight_\\numcomponents + \\left(\\NumComponents - \\frac{1}{2}\\right)\\log{\\NumData}\n +\\frac{1}{2}\\NumDimensions\\log|\\textrm{Cov}\\left(\\factorloads\\transpose\\right)| \\nonumber \\\\\n  && \\cdots -\\frac{1}{2}\\left(D-J-1\\right)\\log|\\factorloads\\transpose\\factorloads| + \\textrm{Tr}\\left(\\textrm{Cov}\\left(\\factorloads\\transpose\\right)^{-1}\\factorloads\\transpose\\factorloads\\right) - \\left(\\NumLatentFactors + \\frac{3}{2}\\right)\\sum_{\\numcomponents=1}^\\NumComponents\\log|\\scorecovs_\\numcomponents|  -\\log\\Gamma\\left(\\NumComponents\\right) - \\Gamma\\left(\\frac{\\NumDimensions}{2}\\right) \\nonumber \\\\\n&& \\cdots +\\frac{Q}{2}\\log\\kappa_q +\\frac{1}{2}\\left[\\NumLatentFactors(\\NumDimensions + 2) + \\NumComponents(2-\\NumData)\\right]\\log{2}  \\quad . \\label{eq:message-length}\n \\end{eqnarray}\n \\newpage\n\\end{widetext}\n\n%\\begin{figure}\n%\t\\includegraphics[width=0.45\\textwidth]{experiments/exp1-gridsearch-ll-contours.pdf}\n%\t\\includegraphics[width=0.45\\textwidth]{experiments/exp1-gridsearch-bic-contours.pdf}\n%\t\\includegraphics[width=0.45\\textwidth]{experiments/exp1-gridsearch-mml-contours.pdf}\n%    \\caption{The top panel shows the negative log likelihood \n%\t\t\t $-\\log{\\mathcal{L}\\left(\\data|\\vec\\Psi\\right)}$ \n%\t\t\t evaluated at each combination of latent factors \n%\t\t\t $\\NumLatentFactors$ and number of clusters \n%\t\t\t $\\NumComponents$ using the generated data in our toy model.\n%\t\t\t The middle panel shows \n%\t\t\t the BIC (Eq.~\\ref{eq:bic}) for those \n%\t\t\t combinations, and the lower panel shows the \n%\t\t\t message length. The white marker indicates the\n%\t\t\t lowest value in each panel.\n%\t\t\t The black marker indicates the true value. \n%\t\t\t In the top panel a line connects these markers to guide the eye.}\n%    \\label{fig:experiment-1-gridsearch}\n%\\end{figure}\n\n\n\\section{Experiments} \\label{sec:experiments}\n\n\n\\subsection{A toy model} \\label{sec:exp-1}\n\nHere we introduce a toy model where we use generated data to verify that\nwe recover the true model parameters given some data, and to\nensure that the expectation-maximization method is yielding consistent results.\nWe generated a data set with ${\\NumData = 1}$00,000 data points, each with\n$\\NumDimensions = 15$ dimensions. We adopted a latent dimensional space of \n$\\NumLatentFactors = 5$ factor loads such that the vector $\\factorloads$ has\nshape $\\NumDimensions \\times \\NumLatentFactors$,\nwith $\\NumComponents = 10$ clusters in the latent space. \nWe generated the random factor loads in the same way that we initialise the optimisation (Section~\\ref{sec:initialisation}). The relative weights $\\vec\\weight$\nare drawn from a multinomial distribution and the means of the clusters\nin factor scores $\\scoremeans$ are drawn from a standard normal\ndistribution. The off-diagonal entries in the covariance matrices in factor scores $\\scorecovs$ are drawn from a gamma distribution $\\scorecovs_{\\numcomponents,i,i} \\sim \\vec\\Gamma\\left(1\\right)$. The variance in \neach dimension $\\specificvariance$ are also drawn $\\specificvariance \\sim \\vec\\Gamma\\left(1\\right)$.\nThe $\\numdata$th data point (which belongs to the $\\numcomponents$th cluster) is then\ngenerated by drawing $\\factorscores_{\\numdata} \\sim \\mathcal{N}(\\scoremeans_\\numcomponents,\\scorecovs_\\numcomponents)$, projecting by the factor loads $\\factorloads$, and adding variance $\\specificvariance$.\n\n\n\n\n\nWe treat the generated data set as if the number of latent factors\nand components are not known. Starting with $\\NumLatentFactors = 1$\nand $\\NumComponents = 1$, we trialled each permutation of $\\NumLatentFactors$ and $\\NumComponents$\nuntil $\\NumLatentFactors_\\textrm{max} = 10$\nand   $\\NumComponents_\\textrm{max} = 20$ (e.g., twice the true values of $\\NumLatentFactors_\\textrm{true}$ and $\\NumComponents_\\textrm{true}$).\n\n\n\n\\begin{figure*}\n\t\\centering\n\t\\begin{tabular}[b]{@{}p{0.45\\textwidth}@{}}\n\t\t\\centering\\includegraphics[width=\\linewidth]{experiments/eval-figs/eval-1-gridsearch-ll-contours.pdf} \\\\\n\t\\end{tabular}\n\t\\begin{tabular}[b]{@{}p{0.45\\textwidth}@{}}\n\t\t\\centering\\includegraphics[width=\\linewidth]{experiments/eval-figs/eval-2-gridsearch-ll-contours.pdf} \\\\\n\t\\end{tabular}\n\n\t\\begin{tabular}[b]{@{}p{0.45\\textwidth}@{}}\n\t\t\\centering\\includegraphics[width=\\linewidth]{experiments/eval-figs/eval-1-gridsearch-bic-contours.pdf} \\\\\n\t\\end{tabular}\n\t\\begin{tabular}[b]{@{}p{0.45\\textwidth}@{}}\n\t\t\\centering\\includegraphics[width=\\linewidth]{experiments/eval-figs/eval-2-gridsearch-bic-contours.pdf} \\\\\n\t\\end{tabular}\n\n\t\\begin{tabular}[b]{@{}p{0.45\\textwidth}@{}}\n\t\t\\centering\\includegraphics[width=\\linewidth]{experiments/eval-figs/eval-1-gridsearch-mml-contours.pdf} \\\\\n\t\\end{tabular}\n\t\\begin{tabular}[b]{@{}p{0.45\\textwidth}@{}}\n\t\t\\centering\\includegraphics[width=\\linewidth]{experiments/eval-figs/eval-2-gridsearch-mml-contours.pdf} \\\\\n\t\\end{tabular}\n    \\caption{Metrics from our grid search for the toy model for two sample sizes: \n    \t\t $N = 100,000$ (left) and $N = 5,000$ (right). \n    \t\t The top panels show the negative log likelihood\n\t\t\t $-\\log{\\mathcal{L}\\left(\\data|\\vec\\Psi\\right)}$ \n\t\t\t evaluated at each combination of latent factors \n\t\t\t $\\NumLatentFactors$ and number of clusters \n\t\t\t $\\NumComponents$ using the generated data in our toy model.\n\t\t\t The middle panels shows \n\t\t\t the BIC (Eq.~\\ref{eq:bic}) for those \n\t\t\t combinations, and the lower panel shows the \n\t\t\t message length. The white marker indicates the\n\t\t\t lowest value in each panel. A line connects to the true value (black point) to guide the eye.}\n    \\label{fig:experiment-1-gridsearch}\n    \\vspace{-10em}\n\\end{figure*}\n\n\n\nWe recorded the \\emph{negative} log likelihood, the BIC, and the message length\\footnote{Omitting constant terms such that negative message lengths are allowed.}  for each permutation of $\\NumLatentFactors$ and $\\NumComponents$.\nThese metrics are shown in Figure~\\ref{fig:experiment-1-gridsearch}.\nUnsurprisingly the negative log likelihood decreases with increasing numbers of latent\nfactors $\\NumLatentFactors$ and increasing numbers of components $\\NumComponents$.\nThe lowest BIC value and message length is found at $\\NumLatentFactors = 5$\nand $\\NumComponents = 10$, identical to the true values. \n\nWe repeated this toy model experiment using a smaller sample size ($N = 5,000$) to be more representative of the sample sizes in later \\Galah\\ experiments (Section~\\ref{sec:exp4}). The results of the grid search are also shown in Figure~\\ref{fig:experiment-1-gridsearch}. Here BIC estimates the true number of latent factors correctly, but tends to underestimate the true number of clusters, more so than the message length. Although the difference between the true number of components and that given by the shortest message length is not large, this does serve to illustrate that in this example a larger number of data points are required to `resolve' the true number of components in latent space.\n\n\nIt is clear from Figure~\\ref{fig:experiment-1-gridsearch} that a combination of latent factors\nand clustering in the latent space provides a better description of the (generated) data than a Gaussian mixture model without latent factors.\nAdding components to the model does improves the log likelihood, even with a single latent factor,\nbut the addition of just \\emph{one latent factor} improves the log likelihood more so than adding\n\\emph{twenty components}. Not much more can be said for this example because the true data generating process \nis known, but this toy model does illustrate how \nclustering in high dimensional data can be better described by latent factors with \nclustering in the lower dimensional latent space.\n\n\n\n\nSome technical background is warranted before we compare our estimated model\nparameters to the true values. We previously stated that the latent factors in this model are only\nidentifiable up to an orthogonal rotation. That is to say that\nif the data were truly generated by latent factors $\\factorloads_\\textrm{true}$,\nthen our estimates of those latent factors $\\factorloads_\\textrm{est}$ do not need\nto be identical to the true values. For example, the ordering of the estimated factors\ncould be different from the true factors, and the ordering of the dimensionality\nin latent space would then be accordingly different. Since no constraint is\nplaced on the ordering of the factor loads during expectation-maximization,\nthere is no assurance (or requirement) that our factor loads match the true factor loads.\n\n\n\n\nAnother possibility is that the estimated factor loads could be flipped in sign \nrelative to the true factor loads, and the scores would similarly be flipped. \nIn both of these situations (reordering or flipped signs) the log likelihood \ngiven the data and the estimated factor loads $\\factorloads_\\textrm{est}$ \nwould be identical to the log likelihood given the data and the true factor loads \n$\\factorloads_\\textrm{true}$\ndespite the difference in ordering and sign. The same can be said for any other\nscalar metric \\citep[e.g., Kullback-Leibler divergence;][]{Kullback:1951}.\nThese examples serve to illustrate a more \ngeneral property that the factor loads and factor scores can be orthogonally \nrotated by \\emph{any valid rotation matrix}\\footnote{Recall that a rotation matrix is valid if \n$\\vec{R}\\vec{R}\\transpose = \\vec{I}\\,\\,$.} $\\vec{R}$. The estimated factor loads \n$\\factorloads_\\textrm{est}$ could therefore appear very different from the true \nvalues, but they only differ by an orthogonal rotation. We discuss the impact of this limitation on real data in more detail in Section~\\ref{sec:discussion}. \n\n\n\n\n\n\nWe took the model with the preferred number of latent factors and components found\nfrom a grid search ($\\NumComponents = 10$, $\\NumLatentFactors = 5$; which are also\nthe true values) and applied an orthogonal rotation to the latent space to be as\nclose as possible to the true values. The rotation matrix $\\mathbf{R}$ was found\nby solving for $\\NumLatentFactors$ unknown angle parameters, each of which is used\nto construct a Givens rotation matrix \\citep{Givens:1958}, and then we take the product of those Givens\nmatrices to produce a valid rotation matrix $\\vec{R}$. This process reduces to Euler angle rotation in three or fewer dimensions.\nThis process rotates the latent space\n($\\factorloads$, $\\scoremeans$, $\\scorecovs$), but has no effect on the model's \npredictive power: the evaluated log likelihood or the Kullback-Leibler divergence \\citep{Kullback:1951} under the\nrotated model is indistinguishable from the unrotated model.\nIn Figure~\\ref{fig:exp1-compare} we show the estimated factor loads $\\factorloads$,\nfactor scores $\\factorscores$, and specific variances $\\specificvariance$ compared\nto the true values. The agreement is excellent in all model parameters.\n\n\n \n\n\n\n\n\\subsection{A toy model with data missing at random}\n\\label{sec:toy-model-missing-data}\n\nHere we repeat the toy model used in the previous experiment, but we discard an increasing fraction\nof the data and evaluate the performance and accuracy of our method in the presence\nof incomplete data. We considered missing data fractions from 1\\% to\n40\\%. In each case we treated the model parameters as unknown, assumed\nthe missing data points were missing at random, and initialised the\nmodel as per Section~\\ref{sec:exp-1}.\n\n\nIn Figure~\\ref{fig:exp1-missing-data} we show the results of this\nexperiment for our worst considered case, where 40\\% of the data\nentries are randomly discarded. We find that despite the high fraction\nof missing entries, our estimates of the model parameters remain unbiased\nin this example using a toy model. The corrections to our estimates of the\nspecific variances are sufficient, in that the specific variance in each\ndimension is not systematically under-estimated from the true values, \ndespite that 40\\% of the data entries are missing.\n\n\n\\subsection{The \\Galah\\ survey}\n\\label{sec:exp4}\n\nIn this experiment we perform blind chemical tagging using the \nphotospheric abundances released as part of the second \\Galah\\ \ndata release \\citep{Buder:2018}. This data set includes\nup to 23 chemical abundances reported for 342,682 stars.\nIn this example we chose to restrict ourselves to stars with a\ncomplete set of abundance measurements for a subset of those 23 elements\n(i.e., no missing data entries).\nFor example, here we will exclude\nlithium and carbon abundances because the\nphotospheric values will vary throughout a star's lifetime \\citep[e.g.,][]{Casey:2016b,Casey:2019}. This is true\nto a small degree for many elements \\citep[e.g.,][]{Dotter:2017},\nbut for the purposes of this experiment we assume that all other\nphotospheric abundances remain constant throughout a star's\nlifetime.\n\n\nWe first selected stars with \\texttt{flag\\_cannon = 0} to exclude\nstars where there is reason to suspect that the stellar parameters\n(e.g., $\\teff$, $\\logg$) are unreliable, and as a result the \ndetailed chemical abundances would be untrustworthy. We then took all\nstars with a signal-to-noise ratio exceeding 30 in the blue arm (\\texttt{snr\\_c1 > 30}), and\nstars with no erroneous flags in all of the following abundances: \nMg, Na, Al, Si, K, Ca, Sc, Ti, Mn, Fe, Ni, Cu, Zn, Y, Ba, La, and Eu.\nThese elements were chosen because they trace multiple nucleosynthetic pathways, and they are more commonly reported in the \\Galah\\ data release, allowing for a larger number of stars with a complete abundance inventory.\nThere are 2,566 stars that met these criteria. \n\n\n\nWe executed a grid search for the number of latent factors $\\NumLatentFactors$\nand the number of components $\\NumComponents$ that were preferred by the data.\nStarting with $\\NumLatentFactors = 1$ and $\\NumComponents = 1$, we trialled each\npermutation of $\\NumLatentFactors$ and $\\NumComponents$ up until $\\NumLatentFactors = 7$\nand $\\NumComponents = 5$. \nThe results of this grid search are shown in Figure~\\ref{fig:exp3-gridsearch},\nwhere we show the negative log likelihood, the BIC, and message length found for each permutation.\nThe behaviour of the BIC and the message length are very different here, unlike what was observed\nin our toy model. Here the BIC behaviour appears similar to the negative log likelihood in that the BIC\nprefers higher components and latent factors than the extent of the grid (e.g., $J > 7$ and $K > 5$). Indeed, if we were to trial higher values of $J$ and $K$ then the negative log likelihood would continue to increase.\nThe model with five latent factors and three components ($J = 6$, $K = 3$) is found to have the shortest message length, which we take as our preferred model for these data.\n\n\n\n\n\nEarlier we described how the latent factors we estimate can only be identified up until an orthogonal rotation. If we want to interpret the latent factors estimated from \\Galah\\ data, then we must specify\nsome target factor loads such that we can identify which factors are most similar to the yields we expect.\nWe specified the following target latent factors where:\n\\begin{itemize}\n\t\\item The first factor load should have non-zero entries in Eu and La (e.g., the $r$-process).\n\t\\item The second factor load should have non-zero entries in Ba, Y, and La (e.g., the $s$-process).\n\t\\item The third factor load should have non-zero entries in Fe-peak elements V, Mn, Fe, Ni, Zn, and Ti.\n\t\\item The fourth factor load should have non-zero entries in the odd-Z elements Na, Al, K, Sc, and Cu.\n\t\\item The fifth factor load should have non-zero entries in the $\\alpha$-element tracers Si, Ca, and Mg.\n%\t\\item The first factor load should have non-zero entries in Eu and La (e.g., the $r$-process).\n%\t\\item The second factor load should have non-zero entries in Ba, Y, and La (e.g., the $s$-process).\n%\t\\item The third factor load should have non-zero entries in Fe-peak elements Sc, V, Mn, Fe, Ni, Cu, and Zn.\n%\t\\item The fourth factor load should have non-zero entries in the $\\alpha$-element tracers Si, Ca, and Ti.\n%\t\\item The fifth factor load should have non-zero entries in the light odd-Z elements Na, Al, and K.\n\\end{itemize}\n\n\\begin{figure*}[t!]\n\t%\\includegraphics[width=\\textwidth]{experiments/exp1-compare-all.pdf}\n\t\\includegraphics[width=\\textwidth]{experiments/eval-figs/eval-1-compare-all.pdf}\n\t\\caption{The estimated factor loads $\\factorloads$ (left), factor scores $\\factorscores$ (middle),\n    \t\t and specific variances $\\specificvariance$ (right) compared to the \n\t\t \t true data generating values\n\t\t \t for Experiment~1 (Section~\\ref{sec:exp-1}). The agreement is excellent.}\n    \\label{fig:exp1-compare}\n\\end{figure*}\n\nWe initially set each non-zero entry in these target factor loads $\\factorloads_\\textrm{target}$ to $E^{-\\frac{1}{2}}$, where $E$ is the number of non-zero entries in that factor load, to ensure that $\\factorloads_\\textrm{target}$ is mutually orthogonal.\nWe solved for the $\\NumLatentFactors$ unknown angles to produce a valid rotation matrix $\\vec{R}$ that would make our estimated loads $\\factorloads$ as close as possible to the target loads $\\factorloads_\\textrm{target}$, and then applied that rotation to the model. The target loads and (rotated) estimated loads are shown in Figure~\\ref{fig:exp3-factor-loads}. Note that the purpose of this procedure is not to `find' the target loads that we expect, but to provide as little information needed in order to identify and describe all factor loads within an astrophysical context. This procedure still requires that the factors be mutually orthogonal and that they describe the data. For these reasons, we will not always recover the exact target loads we seek: we will only be able to identify factor loads that are closest to the target loads.\n\nThis is demonstrated in Figure~\\ref{fig:exp3-factor-loads}, where some estimated factor loads match\nclosely to the target load (e.g., $\\mathbf{L}_2$ which we identify as the s-process), and some barely\nmatch at all (e.g., $\\mathbf{L}_5$). Here we show the absolute entry of the factor loads because even\nif an entry is negative, the corresponding factor scores could also be negative, and their product will contribute to the observed abundances. For this reason the sign does not matter here.\n\nSome of these factor load entries may be non-zero because we require the latent factors to\nbe mutually orthogonal, and not because they truly contribute to the data. To try and\ndisentangle these possibilities, we calculate the fractional contribution that factor\nload makes to the observed abundances relative to other factor loads. We define the\nfractional contribution of the $j$th factor load to the $d$th\ndata dimension as:\n\\begin{equation}\n\t\\mathbf{C}_\\textrm{d,j} = \\frac{\\sum^{N}|\\factorloads_{j,d}\\factorscores_{n,j}|}{\\sum^J\\sum^{N}|\\factorloads_{j,d}\\factorscores_{n,j}|} \\quad .\n\\end{equation}\nThe fractional contributions to each element are shown in the right hand side of\nFigure~\\ref{fig:exp3-factor-loads}. We identify the first factor $\\mathbf{L}_1$ \nas being most similar to the r-process, and here it is the dominant contributor to Eu, a typical r-process tracer. Surprisingly we also find that this factor load is a reasonable contributor to the odd-Z element Sc. The specific scatter in Sc is 0.03~dex (Figure~\\ref{fig:exp3-specific-scatter}), suggesting that the Sc abundances are well-described by this latent factor model.\n \n\nThe second latent factor $\\mathbf{L}_2$ here is most representative of the slow neutron capture process (s-process), with dominant contributions to Ba, and Y. This factor has some support at other elements, notably K. $\\mathbf{L}_3$ is the primary contributor to nearly all Fe-peak elements, with close to negligible contributions from other factors. The exception here is Cu, where a near-equal contribution comes from $\\mathbf{L}_4$.\nThe fifth latent factor $\\mathbf{L}_5$ is the dominant contributor to the $\\alpha$-element tracers Si, Ca, and Ti, and surprisingly, Al. \nThe specific scatter after accounting for these latent factors is smallest\nfor Fe (0.01~dex) and largest for K (0.13~dex; Figure~\\ref{fig:exp3-specific-scatter}). The typical scatter in most elements is about 0.05~dex.\n\nIn Figure~\\ref{fig:exp3-latent-space} we show the inferred clustering in latent space,\nwhere the separation between components is arguably best seen in the splitting between $\\factorscores_6$ with respect to $\\factorscores_2$ or $\\factorscores_3$. When projected to data space (Figure~\\ref{fig:exp3-data-space}) the third component (light green) is seen to have relatively higher abundance ratios of [K,Ba,Zn/Fe] at a given [Fe/H]. This is consistent with the clustering in latent space.\n\n\n\\begin{figure*}[t!]\n\t%\\includegraphics[width=\\textwidth]{experiments/exp-missing-data-not-at-random-inflated-40percent.png}\n\t\\includegraphics[width=\\textwidth]{experiments/eval-figs/eval-3-missing-data-40.pdf}\n\t\\caption{The estimated factor loads $\\factorloads$ (left), factor scores $\\factorscores$ (middle),\n    \t\t and specific variances $\\specificvariance$ (right) compared to the \n\t\t \t true data generating values\n\t\t \t for Experiment~2 (Section~\\ref{sec:toy-model-missing-data}). Here 40\\% of the data are missing at random.\n\t\t\t The agreement remains excellent,\n\t\t\t despite the large fraction of missing data entries. Note that the scales on the top panels are 2-10 times larger than those in Figure~\\ref{fig:exp1-compare}.}\n    \\label{fig:exp1-missing-data}\n\\end{figure*}\n\n\n\\subsection{\\Galah\\ survey data with an increasing number of stars with missing data entries} \\label{sec:exp10}\nHere we extend our experiment in Section~\\ref{sec:exp4} to progressively\ninclude more stars, even though those stars have some abundance measurements\nmissing. \nSpecifically we started with the same subset of 1,072 stars in Section~\\ref{sec:exp4}\nand added a random set of stars that met our criteria of \\texttt{flag\\_cannon = 0} and\n\\texttt{snr\\_c1 > 40}. \n\n\nWe initially added 100 stars to give a sample of $N =$ 1,172, then repeated\nthe grid search for the number of latent factors and components, and recorded\nthe model with the lowest message length. We then repeated this\nprocedure using 1,000 stars ($N =$ 2,072), again with 10,000 ($N =$ 11,072),\nand finally using all 99,174 stars that met the criteria of \\texttt{flag\\_cannon = 0} and\n\\texttt{snr\\_c1 > 40} to give a total sample size of $N =$ 100,246 stars.\n\nFor sample sizes up to $N \\sim $2,000 we found that five latent factors were\npreferred, and these factors shared common features (Figure~\\ref{fig:exp10-comparison}).\nThis illustrates that the\nfirst\\footnote{`First' has no concept here in terms of factor load ordering, but\nfor the purposes of comparing inferred loads from different data sets we have ordered\nthe loads to be as close to those inferred in Section~\\ref{sec:exp4}.} set of inferred factor\nloads inferred from a smaller, complete data set, remain largely unchanged despite the increasing sample size and the increasing number of missing data entries.\nWhen the sample size reaches $N = $11,072 we find another three latent factors are\nrequired to best explain the data.\n\n\nWhen $N \\sim$ 100,000, the preferred number of latent factors rises to twelve ($J = 12$). Of note among these factors is $\\factorloads_9$, where\nno `target load' was prescribed\\footnote{Although no `target load' was prescribed here, this statement should be interpreted with caution because the mutual orthogonality constraint exists and the remaining factors do have target loads.}, and the non-zero entries mimic what might be expected from a \nlight s-process production. Similarly, $\\factorloads_{10}$ has near zero contributions\neverywhere except among the light elements Al, K, Ca, and Sc. \nWith this data set we find that $K = 16$ components are preferred in latent space. None of these components appear coherently structured in their positions or motions.\n\n\n\n\\begin{figure}\n%\t\\includegraphics[width=0.45\\textwidth]{experiments/exp3-\\ExperimentHash-gridsearch-ll.pdf}\n\t%\\includegraphics[width=0.45\\textwidth]{experiments/exp3-\\ExperimentHash-gridsearch-bic.pdf}\n\t%\\includegraphics[width=0.45\\textwidth]{experiments/exp3-\\ExperimentHash-gridsearch-mml.pdf}\n\n\t%TODO: Re-do this image and show the correct colorbar to be consistent with Fig 1\n\t\\includegraphics[width=0.45\\textwidth]{experiments/eval-figs/eval-4-\\EvaluationHash-gridsearch-mml.pdf}\n    \\caption{The top panel shows the negative log likelihood \n\t\t\t $-\\log{\\mathcal{L}\\left(\\data|\\vec\\Psi\\right)}$ \n\t\t\t evaluated at each combination of latent factors \n\t\t\t $\\NumLatentFactors$ and number of clusters \n\t\t\t $\\NumComponents$ using \\Galah\\ data in\n\t\t\t Experiment~3.  The middle panel shows \n\t\t\t the BIC for those combinations, and the lower panel shows the \n\t\t\t message length. The white marker indicates the\n\t\t\t lowest value in each panel, showing the\n\t\t\t preferred number of latent factors and components.}\n    \\label{fig:exp3-gridsearch}\n\\end{figure}\n\n\\begin{figure*}\n\t%\\includegraphics[width=\\textwidth]{experiments/exp3-\\ExperimentHash-latent-factors-and-contributions-with-targets.pdf}\n\t\\includegraphics[width=\\textwidth]{experiments/eval-figs/eval-4-\\EvaluationHash-latent-factors-and-contributions-with-targets.pdf}\n\t\\caption{Latent factors inferred from 1,072 stars in \\Galah\\\n\t\t\t \\citep[][thick lines]{Buder:2018} with \\ExpThreeNumAbundances\\ abundance measurements. Left panels show the absolute entries for each\n\t\t\t factor load, where the thin lines indicate the target latent factors (see Section~\\ref{sec:exp4}). On the right we show the absolute fractional contributions\n\t\t\t to each element, ordered by the loads that contribute most.}\n    \\label{fig:exp3-factor-loads}\n\\end{figure*}\n\n\n\\begin{figure}\n\t%\\includegraphics[width=0.45\\textwidth]{experiments/exp3-\\ExperimentHash-specific-scatter.pdf}\n\t\\includegraphics[width=0.45\\textwidth]{experiments/eval-figs/eval-4-\\EvaluationHash-specific-scatter.pdf}\n\t\\caption{Specific scatter (e.g., $\\sqrt{\\specificvariance}$) remaining in the \\Galah\\ data \\citep{Buder:2018}\n\t\t\t after accounting for the contributions by all\n\t\t\t latent factors.}\n    \\label{fig:exp3-specific-scatter}\n\\end{figure}\n\n\n\n\n\\begin{figure*}\n\t%\\includegraphics[width=\\textwidth]{experiments/exp3-\\ExperimentHash-latent-space.pdf}\n\t\\includegraphics[width=\\textwidth]{experiments/eval-figs/eval-4-\\EvaluationHash-latent-space.pdf}\n\t\\caption{The factor scores $\\factorscores$ estimated in Experiment~3 (Section~\\ref{sec:exp4} using $N =$ 1,072 stars in the \\Galah\\ data \\citep{Buder:2018} that have \\ExpThreeNumAbundances\\ abundance measurements. Here each star is coloured by its inferred $K$th component.}\n    \\label{fig:exp3-latent-space}\n\\end{figure*}\n\n\n\\begin{figure*}\n\t%\\includegraphics[width=\\textwidth]{experiments/exp3-\\ExperimentHash-data-space.pdf}\n\t\\includegraphics[width=\\textwidth]{experiments/eval-figs/eval-4-\\EvaluationHash-data-space.pdf}\n\t\\caption{Detailed chemical abundances from the $N =$ 1,072 stars in \\Galah\\ \\citep{Buder:2018} that have \\ExpThreeNumAbundances\\ chemical abundances (Section~\\ref{sec:exp4}). Each star is coloured by its $K$th inferred component from the lower-dimensional latent space, with the same colouring as per Figure~\\ref{fig:exp3-latent-space}.}\n    \\label{fig:exp3-data-space}\n\\end{figure*}\n\n\n\\begin{figure*}[t!]\n\t\\includegraphics[width=0.95\\textwidth]{experiments/exp10-comparison.pdf}\n\t\\caption{Latent factors found in Section~\\ref{sec:exp10} using different subsets\n\t         of \\Galah\\ data \\citep{Buder:2018}. The thin solid line shows the result from\n\t         Section~\\ref{sec:exp4} with $N=1,072$ stars with \\ExpThreeNumAbundances\\ abundances and no\n\t         missing data. Increasing thickness indicates larger samples, up to the solid thick line with $N \\sim$ 100,000 stars, where twelve latent factors are preferred.}\n    \\label{fig:exp10-comparison}\n\\end{figure*}\n\n\n\n\\section{Discussion} \\label{sec:discussion}\n\nWe have introduced a model to simultaneously account for the lower\neffective dimensionality of chemical abundance space, and perform clustering\nin that lower dimensional space. This provides a data-driven model of\nnucleosynthesis yields and chemical tagging that allows us to simultaneously\nestimate the latent factors that contribute to all stars, and cluster those \nstars by their relative contributions from each factor. The results are\nencouraging in that we find latent factors that are representative of the\nexpected yields from dominant nucleosynthetic channels. However, the model that\nwe describe is very likely \\emph{not} the correct model to use to represent \nchemical abundances of stars. Here we discuss the limitations of our model \nin detail.\n\n\nWe require latent factors to be mutually orthogonal in order to resolve\nan indeterminacy. This suggests an astrophysical context where \nthe mean nucleosynthetic yields (integrated over all stellar masses and star\nformation histories) of various nucleosynthetic processes (e.g., $r$-process, \n$s$-process) are mutually orthogonal to each other. Clearly this assumption \nis likely to be incorrect: the nuclear physics\nof one environment where elements are produced will be very different from\nothers, and there is no astrophysical constraint that those\nyields (or latent factors) should be mutually orthogonal.\nIn principle one could represent the latent factors using a hierarchical data-driven model where the yields contribute as a function of stellar mass, \nmetallicity, and other factors, but in principle to resolve the indeterminacy\n\\emph{in this model} would still require mutual orthogonality on the mean yields. Introducing a constraint on the factor scores that resolves this indeterminacy and allows for more flexible latent factors would be a worthy extension to this work.\n\n\nThe constraint of mutual orthogonality limits the inferences we want to make\nabout stellar nucleosynthetic yields. For example, after accounting for all\nknown sources of potassium production in the Milky Way, galactic chemical evolution\nmodels under-predict the level of K in the Milky Way by more than an\norder of magnitude \\citep{Kobayashi:2006}. From our inferences \nusing \\Galah\\ data, we find that $\\factorloads_1$ -- the factor we identify as the s-process --  is the dominant contributor to\npotassium. This latent factor persists even in the presence of missing data, and\na sample size two orders of magnitude larger.\nDoes this\nsuggest production of K is linked to the production of much heavier nuclei?\nIf our model could confidently and\nreliably associate the production of K with other elements or sites then it could help explain the peculiar abundances of stars enhanced in\nK and depleted in Mg \\citep{Mucciarelli:2012,Cohen:2012} -- a chemical\nabundance pattern that currently lacks explanation \\citep{Iliadis:2016,Kemp:2018}.\nIn the \\citet{Cohen:2012} sample their high [K/Fe] stars also tend\nto be high in heavier elements, but there\nare also numerous abundance correlations present.\nHowever, is the K contribution that we infer physically realistic,\nor is it a consequence of requiring that the latent factors are mutually\northogonal? Distinguishing these possibilities is non-trivial, which is in\npart why caution is warranted when trying to interpret latent factor models.\nIn this situation it is worth commenting that K has the largest specific\nscatter (Figure~\\ref{fig:exp3-specific-scatter}), suggesting that the contributions\nof K are perhaps not as well described by the latent factor model as other\nelements. This could in part be due to the non-trivial and significant effects\nthat the assumption of local thermodynamic equilibrium (LTE) has on our inferred K\nabundances. These non-LTE effects are of order $0.5$~dex and will be accounted for in the upcoming \\Galah\\ data release (S. Buder, private communication).\n\n\nA similar argument could be made for Sc, where $\\mathbf{L}_1$ -- a factor load we\nidentify as the r-process -- is the secondary contributor. Sc is under-produced in \ngalactic chemical evolution models relative to observations \\citep{Kobayashi:2006,Casey:2015}.\nBased on this work, is the production of Sc linked to the production of heavy nuclei? \nUnlike K, the specific scatter in Sc is remarkably low: just 0.03~dex, among the\nbest-described elements after Ti and Fe (0.01~dex). This would suggest that the\nlatent factor model is a very good description for the production of Sc, but it\ndoes not prove that it is \\emph{the} description for the production of Sc.\n\n\nThere are other issues in our model that relate to our assumption of mutual\northogonality. Even if nucleosynthetic yields were truely mutually orthogonal,\nthen the latent factors we infer are only \\emph{identifiable} up until an\northogonal basis. As we have seen in our experiments, the ordering and sign \nof the latent factors is not described \\emph{a priori}. This is both a feature\nand a bug: unrestricted ordering and signs allow for the model parameters to be\nestimated more efficiently because they can freely rotate as the model\nparameters are updated, but it does mean that we\nmust `assign' the latent factors we infer as being described by an astrophysical\nprocess (e.g., the first latent factor is r-process). A more general limitation\nof this is that the latent factors can be multiplied by some arbitrary rotation\nmatrix, leading to latent factor loads that are very different from what was\nestimated by the model, but still lead to the exact same data (or log likelihood,\nor Kullback-Liebler divergence, etc). As a consequence, we can only `identify'\nlatent factors up until this rotation. We have sought to address this by constructing\nrotation matrices where the entries for each latent factor correspond to our expectations\nfrom astrophysical processes (whilst remaining orthogonal), but here we are limited\nby what astrophysical processes we are \\emph{expecting} to find within the constraint\nof being mutually orthogonal.\n\n\nThis in part constrains our ability to identify new nucleosynthetic processes. For example,\nlet us consider a hypothetical situation where we would only expect there to be four \nnucleosynthetic processes that predominately contribute to the observed \\Galah\\ abundances,\nbut in practice we found that the data are best explained with\nfive latent factors. We construct a rotation matrix where the first four latent factors\ndescribe the nucleosynthetic processes we expect to find. What of the fifth latent\nfactor? We can constrain the possible values of the fifth latent factor conditioned on\nthe requirement that all factors remain mutually orthogonal, but one can imagine that\nsome (or perhaps many) elements have entries where the fifth latent factor can have\nnear-zero or zero entries. Even if the mean nucleosynthetic yields are mutually\northogonal, there are scenarios that one can imagine where there is a limited amount\nwe can say with confidence about that new nucleosynthetic process \\citep[see also][]{Milosavljevic:2018}.\n\n\nThere are similar limitations that arise due to our assumption about the clustering in latent space.\nThere is no justified reason why the factor scores should be well-described by multivariate normal\ndistributions. If the \\emph{true} underlying scores were not distributed as multivariate normals\nthen one can imagine similar outcomes when directly fitting data with a mixture of gaussian distributions:\nadditional components would be required to describe complex (non-gaussian) shapes in data space. \nThis situation of model mismatch is more extreme when fitting only data rather than the model\ndescribed here because some of the data complexity will be described by the orthogonal latent\nfactors. However, qualitatively the picture is the same: when the \\emph{true} underlying distribution\nin factor scores are not described by multivariate normals, additional components will likely be\nintroduced in order to describe non-gaussian features.\n\n\n\n\nNotwithstanding these issues, we have shown that a latent factor model which allows for clustering in latent space can adequately\ndescribe chemical abundance data. \nWe find five latent factors from a small subset of \\Galah\\ data with complete abundances, and\nthose latent factors can qualitatively be described within the context of astrophysical yields. \nThose latent factors are recovered in larger samples where the data are incomplete.\nThat did not have to be the case: the mutually orthogonal latent factors could be entirely \ndifferent from our expectations such that they did not have to match our expectations of\nnucleosynthetic yields. Indeed, the inferred factors -- even after a\nvalid rotation -- could have made no astrophysical sense whatsoever. For this reason it\nis encouraging that there is some interpretability in the latent factors. Indeed, in the elements where we find surprising associations (e.g., Sc and K), these are elements where galactic chemical evolution models are most discrepant from observations, even after accounting for systematic errors in abundance measurements (e.g., violations to the assumption of local thermodynamic equilibrium).\n\nIn the subset of \\Galah\\ data with complete abundances we find that three components are\npreferred. These components can be described as those with (1) low- and (2) high-[$\\alpha$/Fe] abundance ratios, and another (3) primarily differing in K, Ba, Zn, and V abundances at a given [Fe/H] and [$\\alpha$/Fe] abundance ratio. When we include $\\sim$100,000 stars with up to \\ExpThreeNumAbundances\\ abundances, and assume the incomplete abundances are missing at random, we find that 16 components in latent space are preferred to explain the data. By construction these  components\nare structured in their chemical abundances because of the projection from the latent\nspace, and by extension of each component having similar chemistry, each component\noccupies realistic locations in a Hertzsprung-Russell diagram. When we\nproject these component associations to the data space we find that none of the inferred\ncomponents are structured or coherent in their positions or motions. However, in this sample of stars there are no gravitationally bound clusters where a reasonable (e.g. $\\sim$30) number of stars have been observed. Clearly, more data would help to resolve a higher number of components.\n\nPerhaps it is not so discouraging that none of the inferred components are structured in their positions or motions because there are no gravitationally bound clusters in the data. But there is clearly more that can be done in chemical tagging. Some components we infer have stars with positions and galactic orbits that would imply that they cannot have formed in the same star cluster. In these situations there is likely significant value in including joint probabilities on whether two stars could be associated to the same star formation site based on their dynamic properties. Similarly, although stellar ages are historically difficult to estimate precisely, can this imprecise information help inform weak priors or probabilities of two stars having the same association? There is an incredible amount of dynamical information available from \\project{Gaia}, particularly for stars in the \\Galah\\ survey, and weakly informative priors might be sufficient to help improve the granularity of chemical tagging without being overly constraining on the dynamical and star formation history we seek to infer.\n\n\n\n\\section{Conclusions} \\label{sec:conclusions}\n\nWe have introduced a data-driven model of nucleosynthesis by incorporating \nlatent factors that are common to all stars, and allowing for clustering in the\nlower-dimensional latent space. This approach simultaneously allows us to efficiently\ntag stars based on their chemical abundances, and to infer the contributions that are\ncommon to all stars (e.g., nucleosynthetic yields). Experiments with generated data\ndemonstrate that MML is a useful principle for selecting the appropriate number of\nlatent factors and components. Experiments with \\Galah\\ data reveal latent factors\nthat are qualitatively and quantitatively similar to expected nucleosynthetic yields (e.g., products\nfrom the $s$-process, $r$-process, et cetera). Interestingly we find that deviations from\nexpected yields occur in elements where observations and galactic chemical evolution models\nare most discrepant (e.g., K, Sc). While we advise caution in directly interpreting\nthose latent factors as being nucleosynthetic yields, our\nmodel does provide the first data-driven approach to nucleosynthesis and chemical tagging. We advocate that more data, and the inclusion of weakly informative priors -- joint probabilities using astrometry and a simplified model of the Milky Way -- would help in realising the full potential of chemical tagging.\n\n\n\n\\acknowledgements\nWe acknowledge support from the Australian Research Council\nthrough Discovery Project DP160100637.\nThe \\Galah\\ survey is based on observations made at the Australian Astronomical Observatory, under programmes A/2013B/13,\nA/2014A/25, A/2015A/19, A/2017A/18. We acknowledge the traditional owners of the land on which the AAT stands, the Gamilaraay\npeople, and pay our respects to elders past and present.\nThis research has made use of NASA's Astrophysics Data System.\n\n\\software{\n\t\\package{Astropy} \\citep{astropy:v1,astropy:v2},\\,\\,\n    \\package{IPython} \\citep{ipython},\\,\\,\n    \\package{Jupyter Notebooks} \\citep{jupyter-notebooks},\\,\\,\n    \\package{matplotlib} \\citep{mpl},\\,\\,\n    \\package{numpy} \\citep{numpy},\\,\\,\n    \\package{scipy} \\citep{scipy},\\,\\,\n    \\package{TOPCAT} \\citep{Taylor:2005}\n}\n\n\n\n\\bibliographystyle{aasjournal}\n\\bibliography{mcfa}\n\n\n\\appendix\n\nDocumentation for the software that accompanies this paper is available at \\url{https://mcfa.rtfd.io}. \nBelow we provide code that generates ficticious data from a toy model and fits it.\\\\\n\n\\begin{minted}[mathescape,linenos,numbersep=5pt]{python}\nimport numpy as np\nfrom mcfa import (mcfa, grid_search, mpl_utils, utils)\n\nnp.random.seed(42)\n\ndo_grid_search = (np.random.uniform() > 0.5)\n\n# Generate data.\nX, true_theta = utils.generate_data(n_samples=1000,\n                                    n_features=15,\n                                    n_components=10,\n                                    n_latent_factors=5)\n\n# The data, X, has shape (1000, 15)\nassert X.shape == (1000, 15)\n\nif do_grid_search:\n    # Perform a grid search for the number of components and latent factors.\n    J_trial = np.arange(1, 11) # trial from 1 to 10 latent factors \n    K_trial = np.arange(1, 21) # trial from 1 to 20 components\n    J_grid, K_grid, converged, metrics = grid_search.grid_search(J_trial, K_trial, X)\n\n    # Return the model with the smallest message length\n    model = metrics[\"best_models\"][\"mml\"]\n\nelse:\n    # Or just fit the data given a number of components and latent factors.\n    model = mcfa.MCFA(n_components=10, n_latent_factors=5)\n    model.fit(X)\n\n# Fitting quantities have a _ suffix\ntau = model.tau_ # responsibility matrix\ntheta = dict(zip(model.parameter_names, model.theta_)) # model parameters\n\n# Plot the factors.\nfig_factors = mpl_utils.plot_factor_loads_and_contributions(model, X)\n\n# Plot latent space.\nfig_latent = mpl_utils.plot_latent_space(model, X)\n\n# Plot data space, coloured by most probable component.\nfig_data = mpl_utils.plot_data_space(model, X)\n\\end{minted}\n\n\n\\end{document}\n", "meta": {"hexsha": "f749bb36e54586e94ff18348a6e49541b2e40941", "size": 89532, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "article/mcfa.tex", "max_stars_repo_name": "andycasey/mcfa", "max_stars_repo_head_hexsha": "8c4135e665e47006e9ca725e8bfc67315508366e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-08-23T06:54:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-05T14:38:41.000Z", "max_issues_repo_path": "article/mcfa.tex", "max_issues_repo_name": "andycasey/mcfa", "max_issues_repo_head_hexsha": "8c4135e665e47006e9ca725e8bfc67315508366e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "article/mcfa.tex", "max_forks_repo_name": "andycasey/mcfa", "max_forks_repo_head_hexsha": "8c4135e665e47006e9ca725e8bfc67315508366e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 61.2813141684, "max_line_length": 1109, "alphanum_fraction": 0.7806035831, "num_tokens": 22657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.30049271898234176}}
{"text": "%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: \"../report\"\n%%% End:\n\nWe have been inspired by many other languages when designing and implementing Kite, most notably the Glasgow Haskell Compiler (GHC)\\footnote{\\url{http://www.haskell.org/ghc}}.\n\n\n\\subsection{Syntax and semantics}\nIn this section we will describe how to use the different features of Kite and how they work, i.e.\\ the syntax and semantics of the language.\n\n\\subsubsection{Basic types and declarations}\nBasic declaration of the variables in Kite, types are inferred by the analyzer:\n\n\\begin{kite}\none = 1\ntwo = 2.0\ntruth = True\nlist = [1, 2, 3, 4]\nchar = 'a'\npair = (1, 'a')\n\\end{kite}\n\nFunctional languages often make extensive use of lists, which is indeed also the case for Kite. A list is an ordered array of items that can be transformed in many different ways. We use a common short-hand method for describing a list of things, using square brackets \\code{[\\ ]}. For instance, a \\code{List(Int)} (pronounced ``List of Ints'') is denoted \\code{[Int]} and a list of a type variables $a$ is \\code{[a]}. Lists can be nested, allowing \\code{List(List(Int))} denoted \\code{[[Int]]}.\n\nThe pair type is also abbreviated using \\code{( , )}, for instance the type \\code{Pair(Int, Bool)} is written \\code{(Int, Bool)}\n\nStrings are represented as syntactic sugar for lists of characters. For\ninstance, \\code{['f', 'o', 'o']} has the sugared version \\code{\"foo\"}. This will be discussed later.\n\nBasic arithmetic operators:\n\\begin{kite}\n1 + 1  ----> 2\n10 % 2 ----> 0\n\\end{kite}\n\n\\begin{table}[H]\n  \\centering\n  \\begin{tabular}{ll}\n    \\textbf{Operation} & \\textbf{Meaning}   \\\\ \\hline\n    $\\code{x + y}$     & Addition         \\\\ \\hline\n    $\\code{x - y}$     & Subtraction        \\\\ \\hline\n    $\\code{x * y}$     & Multiplication     \\\\ \\hline\n    $\\code{x / y}$     & Division           \\\\ \\hline\n    $\\code{x**y}$      & Exponentiation     \\\\ \\hline\n    $\\code{x \\% m}$    & Remainder of x / y \\\\ \\hline\n  \\end{tabular}\n  \\caption{Basic arithmetic operators in Kite}\n\\label{tbl:kite-design-arith-op}\n\\end{table}\n\n\\clearpage\n\nAn example of two basic boolean operators:\n\\begin{kite}\n1 < 2  ----> True\n1 == 2 ----> False\n\\end{kite}\n\n\\begin{table}[H]\n  \\centering\n  \\begin{tabular}{ll}\n    \\textbf{Operation} & \\textbf{Meaning} \\\\ \\hline\n    $\\code{==}$ & Equal                   \\\\ \\hline\n    $\\code{/=}$ & Not equal               \\\\ \\hline\n    $\\code{<=}$ & Less than or equal than \\\\ \\hline\n    $\\code{>=}$ & Greater than or equal   \\\\ \\hline\n    $\\code{<}$  & Less than               \\\\ \\hline\n    $\\code{>}$  & Greater than            \\\\ \\hline\n  \\end{tabular}\n  \\caption{Basic boolean operators in Kite}\n\\label{tbl:kite-disign-bool-op}\n\\end{table}\n\n\\subsubsection{Function application}\n\\label{sec:kite-design-func-app}\nThe most general form of application is as follows:\n\\begin{kite}\nfunc (arg1, ..., argN)\n\\end{kite}\n\nWhere the function \\code{func}, having an arity of $n$, is applied to \\emph{n} arguments.\n\nA concrete example hereof is the application of \\code{union}, which has an arity of 2, to two lists:\n\\begin{kite}\nunion ([1,2],[2,3]) ----> [1,2,3]\n\\end{kite}\n\nBesides this form of application, it is also possible to use infix operators. The application of these is described in section~\\ref{sec:kite-design-sugar} and the declaration of these is described in the following section.\n\nFurthermore, Kite also allows for partial application, which is described in section~\\ref{sec:kite-design-partial-app}.\n\n\\subsubsection{Function declaration}\n\\label{sec:func-decl}\nEvery function in Kite is declared as an anonymous function:\n\n\\begin{kite}\n|param1, ..., paramN| -> {\n  expr1\n  ...\n  exprN\n}\n\\end{kite}\n\nA function (lambda expression) is defined as a list of arguments and a block. A block is defined as a list of expressions optionally separated by \\code{;}, where it is implicit that the last expression is returned as the result of the functions. A block introduces a new lexical scope, capturing its parent scope.\n\nThere are no named functions in Kite, but lambda expressions can be bound to identifers. A function is declared as follows:\n\n\\begin{kite}\nname :: ArgType -> ... -> ReturnType\nname = |arg1, ..., argN| -> { ... }\n\\end{kite}\n\nExample of a valid function declaration in Kite, taking one parameter of the type \\code{Int} and returning an \\code{Int}:\n\n\\begin{kite}\nfoo :: Int -> Int\nfoo = |a| -> {\n  a + 1\n}\n\\end{kite}\n\nAnother type of function declaration is the declaration of \\emph{infix operators}. This is generally done as follows:\n\\begin{kite}\n{name} :: ArgType1 -> ArgType2 -> ReturnType\n{name} = |arg1 , arg2| -> { ... }\n\\end{kite}\n\nAnd a specific example is our implementation of the conjunction of boolean expressions:\n\\begin{kite}\n{&&} :: Bool -> Bool -> Bool\n{&&} = |l, r| -> {\n  if l then r else False\n}\n\\end{kite}\n\nFinally, a runnable program must \\emph{always} include the \\code{main} function of type \\code{Void -> a}, which will be used as the entry point for execution:\n\n\\begin{kite}\nmain = |Void| -> { ... }\n\\end{kite}\n\nIn order to use the preprocessor to include another code file, use the \\code{\\#include} keyword:\n\\begin{kite}\n#include \"foo.kite\"\n\\end{kite}\n\n\\subsubsection{Type declaration}\n\nTop-level declaration can optionally have a corresponding type declared. This can greatly increase readability of declarations as the inferred type might not be immediately clear.\n\nAnnotations are declared using the '\\code{::}' operator. For instance the function \\code{length} can have its type explicitly annotated as follows:\n\n\\begin{kite}\nlength :: [a] -> Int\nlength = |xs| -> {\n  ...\n}\n\\end{kite}\n\nThe type-checker will validate that an annotated type is at least as general as the inferred type. This means that a type annotation of \\code{a} will match anything, and \\code{a -> a} will match \\code{Int -> Int} but not \\code{Int -> Bool}\n\nTypes can be grouped to denote a higher-order function, for instance the type of map \\code{(a -> b) -> [a] -> [b]} means that \\code{map} accepts a \\emph{function} as its first parameter, a list as its second and it produces a list.\n\n\\clearpage\n\n\\subsubsection{Syntactic sugar}\n\\label{sec:kite-design-sugar}\nBy using a sugaring module, Kite will be able to express certain functions more clearly and readable to the user. Syntactic sugar includes infix operators, multiple parameters on function calls, list of characters as strings and list comprehensions. Infix operators will allow infix use of binary functions (taking two parameters) in Kite. An example of infix operators is the basic $+$ arithmetic operation:\n\n\\begin{kite}\nfoo = 1 + 2\n\\end{kite}\n\nWhere the desugared version of the same expression is given as:\n\n\\begin{kite}\nfoo = ((+) (1)) (2)\n\\end{kite}\n\nAs Kite functions will only take one parameter, sugaring can simulate the use of multiple parameters in functions. Example hereof:\n\n\\begin{kite}\nfoo :: a -> a -> a\nfoo = |a, b| -> {\n  a + b\n}\n\\end{kite}\n\nWhich will be syntactic sugar for the following:\n\n\\begin{kite}\nfoo :: a -> a -> a\nfoo = |a| -> {\n  return |b| -> {\n    return ((+) (a)) (b)\n  }\n}\n\\end{kite}\n\n\\textbf{Parameterless functions} are also syntactic sugar. For instance the main function is often declared as follows:\n\n\\begin{kite}\nmain = -> {\n  ...\n}\n\\end{kite}\n\nThis is simply shorthand for\n\n\\begin{kite}\nmain = |Void| -> {\n  ...\n}\n\\end{kite}\n\nAs mentioned earlier, \\textbf{Strings} are syntactic sugar for list of characters, \\code{[Char]}, which will allow for easier representations of character lists. An example of a string:\n\n\\begin{kite}\nstr = \"Hello\"\n\\end{kite}\n\nWhere the corresponding desugar will be:\n\\begin{kite}\nstr = ['H', 'e', 'l', 'l', 'o']\n\\end{kite}\nNote the distinction between strings using double-quotes (\"...\") and characters using single-quotes ('...').\n\n\\label{sec:ex-listcomp}\n\\textbf{List comprehensions} are syntactic sugar for manipulating lists. An example of a list comprehension is:\n\n\\begin{kite}\nlist = [ x*y | x <- range(3,5), y <- range(4,6) | (x+y) >= 10, y > 4]\n\\end{kite}\n\nList comprehensions are composed of three elements: An \\emph{output expression}, one or more \\emph{draws} and optionally one or more \\emph{guards}.\n\nFirst, elements are drawn from the draws, which in the above example are \\code{x <- range(3,5)} and \\code{y <- range(4,6)}, yielding 9 potential elements to the output expression:\n\n\\begin{center}\n\\code{[[3,4],[3,5],[3,6],[4,4],[4,5],[4,6],[5,4],[5,5],[5,6]]}\n\\end{center}\n\nThese potential combinations are then filtered by the guards. The element \\code{[3,3]} will not pass the guards as $3+3$ is not larger than or equal to 10, nor is 3 larger than 4. The element \\code{[5,5]} will on the other hand pass the guards.\n\nFinally, all the combinations that pass the guards are subjected to the output expression. The element \\code{[5,5]} will thus become \\code{25} in the resulting list.\n\nThe desugared version of the given example will look as follows:\n\n\\begin{kite}\nlist =\nflatMap(|x| -> {\n  flatMap (|y| -> {\n    if (|x,y| -> {y > 4})(x,y) && (|x,y| -> {(x+y) >= 10})(x,y)\n       then [(|x,y| -> {x*y})(x,y)]\n       else []\n  } , range(4,6) )\n}, range(3,5) )\n\\end{kite}\n\nNote that list comprehensions uses functions defined in section~\\ref{foundation}, which will be discussed later.\n\n\\textbf{Infix functions} Kite allows for use of infix functions. Infix functions are syntactic sugar for prefix function calls, with some given parameters. Using '\\code{\\`}' (backtick) will imply the use of infix function calls\n\nA common example of infix function calls, is the \\code{elem}-function, which is defined as follows (from \\nameref{foundation}):\n\\begin{kite}\nelem :: a -> [a] -> Bool\nelem = |el| -> {\n  any ((el==))\n}\n\\end{kite}\n\nThe following Kite example will be an example of usage of \\code{elem}. \\code{elem} is here used as an infix function call.\n\\begin{kite}\nlist = [1, 2, 3]\n1 `elem list ----> True\n\\end{kite}\nThe resulting desugared version of same example will look as follows:\n\n\\begin{kite}\nlist = [1,2,3];\n((elem) (1)) (list); ----> True\n\\end{kite}\n\n\\subsubsection{Recursion}\nKite supports recursion, which allows functions to call themselves in programs. Basic recursion will have the following syntax:\n\\begin{kite}\nfoo :: Int -> Int\nfoo = |a| -> {\n  if a == 1 then 1\n  else a + foo(a - 1)\n}\n\\end{kite}\n\nKite also supports recursion in pattern matching, which will be discussed next.\n\n\\subsubsection{Conditionals}\n\\label{subsubsec:conditionals}\nKite features two conditional expressions; the if-expression and pattern matching.\n\nThe \\textbf{if-expression} is not to be confused with an if-statement, as our implementation is not a control flow statement. It will always return an expression, and the return-types of the consequent and alternative must be the same.\n\n\\begin{kite}\nif booleanExpr then consequenceExpr else alternativeExpr\n\\end{kite}\n\nA more advanced form of conditional is \\textbf{pattern matching}. It works by matching an expression to a list of cases, which can be either a normal expression or it can be a destruction\\footnote{Destructuring means breaking up a data structure into its parts by using pattern matching. Kite features a simple implementation of this in its \\code{match} expressions} of a list or a pair.\n\nBelow we show the matching of \\code{n} on 0, which is an expression, and \\code{otherwise}, which is written \\code{\"\\_\"}:\n\n\\begin{kite}\nfibo :: a -> b -> Int -> a\nfibo = |a, b, n| -> {\n  match n {\n    0 -> a,\n    _ -> fibo(b, (a + b), (n - 1))\n  }\n}\n\\end{kite}\n\nAn example of pattern matching on lists is our implementation of the function \\code{reverse} (\\ref{foundation}), which matches \\code{xs} with an expression, empty list, and the head and tail of \\code{xs}:\n\n\\begin{kite}\nreverse = |xs| -> {\n  match xs {\n    []    -> [],\n    x,xs  -> reverse (xs) ++ [x]\n  }\n}\n\\end{kite}\n\n\\newpage\n\nThe final case is matching on pairs. The example below shows the implementation of \\code{fst} (first) in Foundation (\\ref{foundation}):\n\\begin{kite}\nfst :: (a, b) -> a\nfst = |p| -> {\n  match p {\n    (a , b) -> a\n  }\n}\n\\end{kite}\n\n\\subsubsection{Higher-order functions}\nKite features higher-order functions (HoF), and the \\code{map} function is an example hereof. It takes a function as argument and applies it to every element of a list, and returns the resulting list:\n\n\\begin{kite}\nmap :: (a -> b) -> [a] -> [b]\nmap = |f, ls| -> {\n  match ls {\n    [] -> [],\n    x,xs -> f (x) : map (f, xs)\n  }\n}\n\\end{kite}\n\n\\subsubsection{Currying}\n\\label{subsubsec:currying}\nBeside every function in Kite being curried (which should be clear from the type-declarations), we have also implemented a \\code{curry} (and \\code{uncurry}) function, which given a function with a single pair as the argument, returns the same function taking two arguments corresponding to the values of the pair:\n\n\\begin{kite}\ncurry :: ((a, b) -> c) -> (a -> b -> c)\ncurry = |f| -> {\n  |a,b| -> {\n    f((a,b))\n  }\n}\n\\end{kite}\n\nUncurry, naturally does the opposite, meaning it takes a function taking two parameters and returns the same taking a single pair as an argument.\n\n\\begin{kite}\nuncurry :: (a -> b -> c) -> ((a, b) -> c)\nuncurry = |f| -> {\n  |p| -> {\n    match p {\n      (a, b) -> f(a,b)\n    }\n  }\n}\n\\end{kite}\n\nWe have chosen to include these two functions from~\\nameref{foundation} in this section as they reflect an essential part of Kite and functional programming languages in general.\n\n\\subsubsection{Partial application}\n\\label{sec:kite-design-partial-app}\nAn example of partial application is the function \\code{increment}, which partially applies addition to an infix operator:\n\n\\begin{kite}\nincrement :: Int -> Int\nincrement = (1+)\n\\end{kite}\n\nIncrement can then be applied to an integer:\n\n\\begin{kite}\nincrement(1) ----> 2\n\\end{kite}\n\nIt should be noted that the addition operator, \\code{+}, has type \\code{a\n  -> a -> a}. Thus, partial application yields \\code{a -> a} and since\nit is partially applied with an integer, the type of \\code{increment}\nbecomes \\code{Int -> Int}\n\nAnother example is partial application of functions in the more general form, as mentioned in section \\ref{sec:kite-design-func-app}. A function taking $n$ parameters can be partially applied to $k$ arguments, where $n > k > 0$\n\nHere the syntax is as follows:\n\\begin{kite}\nfunc(arg1, ..., argK)\n\\end{kite}\nWhich yields a function taking $n - k$ arguments.\n\n\\subsubsection{Error handling}\nKite supports termination of execution using the function \\code{panic}. Using \\code{panic} will stop the execution. It has the type signature \\code{String -> a}, thus being allowed anywhere.\n\nAn example of the \\code{panic} function in use:\n\\begin{kite}\nhead :: [a] -> a\nhead = |xs| -> {\n  match xs {\n    [] -> panic (\"can't take head of empty list\"),\n    x,xs -> x\n  }\n}\n\\end{kite}\nIf a user tries to take the head of an empty list, the execution of Kite will stop and the error message will be outputted.\n\n\n\\subsection{Foundation}\nAs mentioned earlier in section~\\ref{sec:requirements}, the \\code{Foundation} of Kite is a standard library implemented in Kite consisting of often used functions. Kite's Foundation is inspired by Haskell's \\code{Prelude}, and includes many functions found in\nPrelude.\n\nBelow are two examples from Foundation.\n\n\\subsubsection{List concatenation}\nList concatenation does as the name suggests, namely concatenating two lists into a single list:\n\n\\begin{kite}\n{++} :: [a] -> [a] -> [a]\n{++} = |l, r| -> {\n  match l {\n    [] -> r,\n    x,xs -> x : (xs ++ r)\n  }\n}\n\\end{kite}\n\nFor example, as strings are simply lists of characters, \\code{++} can be used as follows:\n\n\\begin{kite}\n\"Hello,\" ++ \" World!\" ----> \"Hello, World!\"\n\\end{kite}\n\n\\subsubsection{List indexing}\nLists in Kite are zero-indexed, meaning that the first element of a list is at 'index' zero. Indexing a list retrieves the $n$-th element of a list:\n\n\\begin{kite}\n{#} :: [a] -> Int -> a\n{#} = |xs, idx| -> {\n  match xs {\n    [] -> panic (\"list index too large\"),\n    x,xs -> if idx == 0 then x else xs # (idx - 1)\n  }\n}\n\\end{kite}\n\nA simple example of list indexing is as follows:\n\n\\begin{kite}\nteens = range(13,19)\nsweetSixteen = teens # 3 ----> 16\n\\end{kite}\n\nFor a full documentation of Foundation, please see section~\\ref{foundation}.\n", "meta": {"hexsha": "08f2572474b9066035de79b64bec781a5a8ecfbb", "size": 16154, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/sections/kite-design.tex", "max_stars_repo_name": "kite-lang/kite", "max_stars_repo_head_hexsha": "4140974b297330805e840b20a496e2a5f0be8e73", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2015-03-23T07:02:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-30T16:11:58.000Z", "max_issues_repo_path": "report/sections/kite-design.tex", "max_issues_repo_name": "kite-lang/kite", "max_issues_repo_head_hexsha": "4140974b297330805e840b20a496e2a5f0be8e73", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/sections/kite-design.tex", "max_forks_repo_name": "kite-lang/kite", "max_forks_repo_head_hexsha": "4140974b297330805e840b20a496e2a5f0be8e73", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0084210526, "max_line_length": 495, "alphanum_fraction": 0.6883124923, "num_tokens": 4510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3004927189823417}}
{"text": "% \\documentclass[aps,preprint,twocolumn,groupedaddress]{revtex4}\n\\documentclass[aps,preprint,groupedaddress]{revtex4-1}\n\\usepackage[dvips]{graphicx}\n\n\\pagenumbering{arabic}\n\n\\begin{document}\n\n\\title{Automatically tuned libraries for native-dimension tensor transpose algorithms}\n\n\\author{Jeff R. Hammond}\n\n% \\affiliation{The James Franck Institute, Department of Chemistry and Department of Computer Science, The University of Chicago, Chicago, IL 60637}\n\n\\date{Revised June 2008}%\\today}\n\n\\begin{abstract}\n\n\n\n\\end{abstract}\n\n\\maketitle\n\n\\section{Introduction}\n\nMany numerical algorithms, particularly those of quantum many-body theory, rely heavily upon procedures called tensor contractions.  Tensor contractions (TCs) are the multi-dimensional generalization of matrix multiplication (MM).  Whereas in MM, one has only a single internal (contracted) index and the two external indices of the matrix,\n\\begin{equation}\n C^{i}_{j} = \\sum_{k}~A^{i}_{k}~B^{k}_{j}\n\\end{equation}\na tensor contraction may have an arbitary number of both.  One simple example from quantum chemistry is\n\\begin{equation}\\label{eqn:V2T2a}\n R^{a,b}_{i,j} = \\sum_{c,d}~V^{a,b}_{c,d}~T^{c,d}_{i,j}.\n\\end{equation}\nWhile Eqn.~\\ref{eqn:V2T2a} is isomorphic to MM upon fusion of the three pairs of indices, other similar contractions with permuted indices are not.  An example of a TC that cannot be performed with MM alone is\n\\begin{equation}\\label{eqn:V2T2b}\n R^{a,b}_{i,j} = \\sum_{k,c}~\\tilde{V}^{k,b}_{c,j}~T^{a,c}_{i,k},\n\\end{equation}\npresuming that we are utilizing the straightforward layout of these objects in memory.  That the objects $R$ and $T$ in Eqns.~\\ref{eqn:V2T2a} and~\\ref{eqn:V2T2b} are the same, the best one can do is to choose a layout which is optimal for the most expensive TC and use a sub-optimal ordering for the other.  Alternatively, one can change the memory layout sub-optimally-ordered tensors via a transpose-like operation.  A much more complex approach is to use Morton-ordering~\\cite{Morton} (also known as Z-ordering), or more generally, hierarchical tiling~\\cite{HTiling}, to improve the performance of all tensor contractions, but then it is not possible to use existing implementations of MM, such as BLAS.\n\nThe complexity introduced by the transposition of indices in TCs presents a significant challenge to programmers.  If one hand-codes procedures which are not MM, then a significant performance loss is incured, as MM kernels are perhaps the most optimized in all numerical computation.  Alternatively, one can retain the use of fast MM kernels by realigning the memory layout such that operations like Eqn.~\\ref{eqn:V2T2b} can be performed with MM.\n\nThe transformation of Eqn.~\\ref{eqn:V2T2b} to a form which is consistent with matrix multiplication is as follows:\n\\begin{eqnarray}\\label{eqn:transform_V2T2b}\n T^{a,c}_{i,k} &\\rightarrow& T1(i,k,a,c) \\\\\n \\tilde{V}^{k,b}_{c,j} &\\rightarrow& V1(c,j,k,b) \\\\\n R^{a,b}_{i,j} &\\rightarrow& R1(i,j,a,b) \\\\\n T2(i,a,k,c) &=& T1(i,k,a,c) \\\\\n V2((k,b),(c,j)) &=& V1((c,j),(k,b)) \\\\\n V3(k,c,b,j) &=& V2(k,b,c,j) \\\\\n R2((i,a),(b,j)) &=& {\\rm SUM}[(k,c)]~V3((k,c),(b,j))*T2((i,a),(k,c)) \\\\\n R1(i,j,a,b) &=& R2(i,a,b,j)\n\\end{eqnarray}\nwhere the matrix dimensions used in the matrix transpose and multiplication calls are denoted with parentheses.  Row-major ordering (the last index is stride-1) is presumed throughout.\n\nFor a rank-$n$ tensor, there are $n!$ possible permutations of the indices, and writing fast code for each of these procedures by hand is impractical for $n>4$.  The automatic generation of code for these procedures is the subject of this chapter.\n\n\\section{Background}\n\nThe target application for this project was the coupled-cluster codes within TCE module of the quantum chemistry package NWChem~\\cite{NWChem}.  Because most of the code within the TCE module was written by a code generator, it employs a simple structure which is easily modified.  The TCE module also has few, if any, manually optimized procedures and thus suffers in performance with respect to the best hand-written packages.  In the particular case of tensor (array) permutation, four subroutine calls, \\texttt{tce\\_sortN} (\\texttt{N=2,4,6,8}), were used to perform every permutation.  Nearly identical sort-acculuate calls (\\texttt{tce\\_sortaccN}, \\texttt{N=2,4,6,8}) have use the same code except with ``\\texttt{+=}'' instead of ``\\texttt{=}''.  Replacing these procedure with faster ones would result in increased performance throughout the code.\n\nIs it not unreasonable to question the utility of optimizing permutations at all.  The permutation of a $n$-d array is an $N^n$ flop procedure, where $N$ is the rank of each dimension, whereas the the contraction of two $n$-d arrays over $k$ indices is an $N^{n+k}$ flop procedure.  However, the mop cost of both procedures is $C \\cdot N^n)$ where C is 2 for permutation (1 read, 1 write) and 3 for contraction (2 reads, 1 write).  On modern processors, mops are so expensive that some have said that flops can almost be ignored.  MM achieves a large percentage of machine peak by obscuring memory latency through data reuse, which is possible because flops/mops is large.  Since permutations are entirely memory bound, it is unreasonable to expect a large percentage of peak performance but at the same time, improper implementation of these procedures can be extraordinarily expensive.  Unlike MM, the flow of data during permutation is necessarily not optimal since at least half of the mops will not be stride-1.\n\nIf we assume flops are free and that performance is determined by the number and type of mops occuring, then permutation, not MM will be the more expensive procedure of the two.  Since theoretical analyses are rarely quantitative, the relative cost of the two procedures has been measured using profiling techniques.  Both the GNU profiler gprof~\\cite{GPROF} and TAU~\\cite{TAU} were used to profile the code to ensure correct measurements.\n\n\\section{Results}\n\nAll results are for a single water molecular at the equilibrium geometry.  Calculations were performed without point-group symmetry using spherical angular functions.  The tile size for the virtual orbitals (VO) was no greater than 32.  For the cc-pVDZ, cc-pVTZ and cc-pVQZ basis sets, there were 2, 4 and 8 VO tiles with average dimension 19, 26.5 and 27.5, respectively.  Using a larger tile size favors \\texttt{dgemm} performance, while smaller favors \\texttt{tce\\_sortN}.\n\n\\subsection{Profiling of CCSD within NWChem}\n\nFirst it was established empirically that the tensor transpose operation is a significant portion of the was time, as predicted by the aforementioned theoretical analysis.  In Table~\\ref{tab:profile1}, the results of profiling are given for computing the CCSD ground-state energy.  When computing the CCSD energy, the coupled-cluster equations (described in previous chapters) are solved iteratively.  The energy evaluation two orders less expensive than the iterative procedure and does not contribute significantly to the computational cost.  The data given in Table~\\ref{tab:profile1} shows that MM and transpose both contribute significantly to wall time.  However, the fraction of the wall time devoted to MM grows with the basis set, so it is not entirely clear that the optimality of the transpose will matter for larger systems.  It should be noted that the MM implementation used was from NETLIB.  A high-performance BLAS library such as GotoBLAS~\\cite{GotoBLAS} or ATLAS~\\cite{ATLAS} would greatly decrease the time spent on MM operations.\n\n\\begin{table}[!hp]\n\\caption{Profile (\\texttt{gprof}) of the NWChem TCE module CCSD code for computing the ground-state energy.} \\label{tab:profile1}\n% \\begin{ruledtabular}\n% \\begin{center}\n\\begin{tabular}{ccccc}\n\\hline\\hline\n& \\multicolumn{2}{c}{Matrix multiplication} & \\multicolumn{2}{c}{Tensor transpose} \\\\\n & \\multicolumn{2}{c}{dgemm} & \\multicolumn{2}{c}{tce\\_sort4 \\& tce\\_sortacc4} \\\\\n   \\cline{2-3} \\cline{4-5}\nBasis & Time (s) & \\% of Total & Time (s) & \\% of Total \\\\\n\\hline\ncc-pVDZ &   0.40 & 27.59 &   1.49 & 29.65 \\\\\ncc-pVTZ &   8.70 & 30.87 &  34.15 & 37.22 \\\\\ncc-pVQZ & 154.46 & 38.54 & 108.47 & 27.07 \\\\\n\\hline\\hline\n\\end{tabular}\n% \\end{center}\n% \\end{ruledtabular}\n\\end{table}\n\nAs should be clear from previous chapters, computating the ground-state energy is but one of many possible tasks for a coupled-cluster code.  In Table~\\ref{tab:profile2}, profiling information is given for the evaluation of all steps necessary to compute the hyperpolarizability using the method described in Chapter 8.  The number of difficult transposes required for the solution of the $\\Lambda^{(0)}$, $T^{(1)}$ and $\\Lambda^{(1)}$ equations is significantly larger than required just for $T^{(0)}$, which is affirmed by the data.  The relative amount of time spend in the transpose operations is approximately 50\\% greater than that spent in MM for the cc-pVQZ basis set, and while the overall trend in the basis set is the same as Table~\\ref{tab:profile1}, rate of which MM increases and transpose decrease is much less.\n\n\\begin{table}[!hp]\n\\caption{Profile (\\texttt{gprof}) of the NWChem TCE module CCSD code for computing the hyperpolarizability.} \\label{tab:profile2}\n% \\begin{ruledtabular}\n% \\begin{center}\n\\begin{tabular}{ccccc}\n\\hline\\hline\n & \\multicolumn{2}{c}{dgemm} & \\multicolumn{2}{c}{tce\\_sort4 \\& tce\\_sortacc4} \\\\\n   \\cline{2-3} \\cline{4-5}\nBasis & Time (s) & \\% of Total & Time (s) & \\% of Total \\\\\n\\hline\ncc-pVDZ &    5.78 & 28.18 &   11.08 & 54.03 \\\\\ncc-pVTZ &  111.10 & 28.44 &  192.45 & 49.26 \\\\\ncc-pVQZ & 1389.05 & 29.16 & 2137.17 & 44.87 \\\\\n\\hline\\hline\n\\end{tabular}\n% \\end{center}\n% \\end{ruledtabular}\n\\end{table}\n\n\\subsection{Autotuning transpose kernels}\n\nIt was determined that the primary reason transpose operations are slow is that they access memory in a less-than-optimal way, that is, strided access rather than sequential (stride-1) access.  While it is not possible to eliminate strided access, it is possible to minimize the cost of strided access by rearranging the loops such that the stride distance is minimal.  If the stride distance is small enough that cache reuse occurs, a significant performance increase will result.\n\nWhile it is possible to determine optimal loop ordering using mathematical analysis, a much cruder approach --- exhaustive sampling --- is sufficient in this case.  In addition, sampling includes all possible hardware-specific factors which may not be available for integration into a performance modeling used in the analytic approach.  To determine the optimal loop-ordering for the 4-d transpose problem, a code-generator was developed which would produce source code for all possible implementations (24) for each of the 24 transposes, for a total of 576 cases.  Source code was generated in both Fortran 77 and ANSI C since the former is known to be more amenable to compiler optimization, while the latter allows a more complete set of compiler pragmas and is the language of choice of people who would further hand-tune these kernels.  A master program was instrumented to compile the source code into binary form using a variety of possible compiler flags to determine the effect of available optimization options.  Some of the optimizations sampled for the Intel compilers were loop-unrolling, auto-vectorization and auto-parallelization; compiler pragmas were also explored as a means to explicitly control unrolling and vectorization.  The master program built a self-contained binary for each possible transpose which, when executed, performed the timing and printed a complete table of results then identified the optimal loop-ordering.  It also prints the compiler flags which were used to generate the code to prevent data rot.\n\nTable~\\ref{tab:spaghetty1} shows the best improvement obtained with the automatically-generated code as compared to the original implementation within NWChem.  Four cases were considered: regular 4-d arrays of rank 20, 32 and 60 plus an irregular array.  The speed-up for the rank 20 case is significantly better than the others because both the input and output array (1,250 KB each) fit into cache on the machine tested (Intel Core2Duo, 4 MB L3 cache).  For larger dimensions, the arrays do not fit into cache.  This clearly indicates that L3 cache-blocking will significantly improve the performance transpose, although finding the optimal code with that additional level of complexity becomes harder.  Instead of performing an exhaustive search over just the space of loop-orderings or compiler options, an exhaustive search for the cache-blocking case involves exploring the tensor product space of blocking sizes and loop-orderings for each level of blocking.  The dimensionality here is too large to consider by brute force, and a space-pruning algorithm must be employed to make the solution achievable in a reasonable amount of time.\n\n\\begin{table}[!hp]\n\\caption{Best improvement relative to the original implementation by the automatically-generated ANSI C implementation of the transpose operations for a 4-d array.  The Intel 10.1 compiler flags used were \\texttt{-O3 -xT -march=core2 -mtune=core2 -funroll-loops -align}.} \\label{tab:spaghetty1}\n% \\begin{ruledtabular}\n% \\begin{center}\n\\begin{tabular}{ccccc}\n\\hline\\hline\nTranspose & $20^4$ & $32^4$ & $60^4$ & irregular \\\\\n\\hline\n1234 & 7.250 & 2.500 & 1.946 & 3.769 \\\\\n1243 & 7.667 & 2.345 & 2.257 & 2.733 \\\\\n1324 & 5.000 & 1.828 & 1.861 & 2.667 \\\\\n1342 & 5.250 & 2.379 & 2.173 & 2.923 \\\\\n1423 & 7.000 & 2.448 & 2.272 & 2.929 \\\\\n1432 & 5.250 & 2.000 & 2.372 & 3.154 \\\\\n2134 & 5.250 & 2.000 & 1.967 & 2.583 \\\\\n2143 & 8.334 & 2.586 & 2.108 & 2.786 \\\\\n2314 & 5.250 & 2.000 & 2.028 & 2.583 \\\\\n2341 & 5.000 & 2.267 & 2.179 & 3.000 \\\\\n2413 & 7.000 & 2.571 & 2.390 & 2.857 \\\\\n2431 & 5.000 & 1.889 & 2.756 & 3.385 \\\\\n3124 & 5.250 & 1.862 & 1.966 & 2.538 \\\\\n3142 & 5.000 & 3.233 & 2.216 & 3.000 \\\\\n3214 & 5.250 & 2.143 & 2.104 & 2.833 \\\\\n3241 & 7.000 & 1.971 & 2.219 & 2.571 \\\\\n3412 & 5.000 & 1.838 & 2.208 & 2.692 \\\\\n3421 & 6.334 & 1.976 & 2.281 & 2.429 \\\\\n4123 & 6.333 & 2.655 & 2.228 & 2.875 \\\\\n4132 & 4.750 & 1.944 & 2.202 & 3.000 \\\\\n4213 & 5.250 & 2.821 & 2.326 & 2.786 \\\\\n4231 & 5.250 & 2.195 & 2.299 & 3.077 \\\\\n4312 & 4.750 & 1.973 & 2.120 & 3.308 \\\\\n4321 & 4.500 & 1.767 & 2.163 & 3.077 \\\\\n\\hline\\hline\n\\end{tabular}\\\\\nirregular $= 41\\times17\\times24\\times39$\n% \\end{center}\n% \\end{ruledtabular}\n\\end{table}\n\nIn addition to the 4-d case, exhaustive search was used to find the best implementation of the subset of 6-d transpose-accumulate operations used in CCSD(T).  Because of memory constraints imposed by the use triple-excitation amplitudes, dimensions of the arrays are much smaller.  Due to the smaller stride length, cache-blocking is less important and the performance improvement realized just by finding the optimal loop-ordering (among $6!=720$ possibilities) is quite good.  The performance improvement realized for the first-generation auto-tuning approach was between 3 and 4 times the original implementation, although preliminary results for a subsequent attempt were closer to 12 times.  This is the subject of ongoing research.\n\n\\section{Conclusions}\n\nTensor operations, which compose the overwhelming majority of quantum chemistry codes, require optimal implementations to take advantage of high-performance computers.  It was demonstrated that tensors transpose is a significant contribution to the wall time for coupled-cluster calculations and that a very simple approach decrease the time devoted to these operations by a factor of two.  The successful approach employed here did not employ cache-blocking or many other possible optimization techniques which will further improve the performance\n\nUltimately, this project demonstrates that the artificial seperation of transpose and MM in the implementation of tensor contractions is wholly inappropriate.  The original motivation for it was to take advantage of vendor-optimized BLAS libraries, but developments in autotuning over the past 10 years clearly indicate that it is possible to generate tensor contraction kernels directly.  The advantage is not only with respect to performance, but also in terms of mathematical elegance.  The many-body formalism of coupled-cluster theory is multidimensional and flattening the data structures used in such codes into matrices just to use BLAS should not be tolerated.\n\n\\begin{thebibliography}{99}\n\n\\bibitem{Morton}\nG. M. Morton, ``A Computer Oriented Geodetic Data Base and a New Technique in File Sequencing,'' IBM technical report (1966).\n\n\\bibitem{HTiling}\n% Hierarchical Tiling: A Methodology for High Performance\nL. Carter, J. Ferrante, S. Flynn Hummel, B. Alpern, and K.S. Gatlin, UCSD Tech Report CS96-508, November 1996;\n% Hierarchical Tiling for Improved Superscalar Performance\nL. Carter, J. Ferrante and S. Flynn Hummel, \\textit{Int. Par. Proc. Symp.}, April 1995;\n% Efficient Multiprocessor Parallelism via Hierarchical Tiling\nL. Carter, J. Ferrante and S. Flynn Hummel, \\textit{SIAM Conf. on Par. Proc. for Sci. Comp.}, February 1995.\n\n\\bibitem{NWChem}\nE. J. Bylaska, W. A. de Jong, N. Govind, K. Kowalski, T. P. Straatsma, M. Valiev, D. Wang, E. Apra, T. L. Windus, J. Hammond, P. Nichols, S. Hirata, M. T. Hackler, Y. Zhao, P.-D. Fan, R. J. Harrison, M. Dupuis, D. M. A. Smith, J. Nieplocha, V. Tipparaju, M. Krishnan, Q. Wu, T. Van Voorhis, A. A. Auer, M. Nooijen, E. Brown, G. Cisneros, G. I. Fann, H. Fruchtl, J. Garza, K. Hirao, R. Kendall, J. A. Nichols, K. Tsemekhman, K. Wolinski, J. Anchell, D. Bernholdt, P. Borowski, T. Clark, D. Clerc, H. Dachsel, M. Deegan, K. Dyall, D. Elwood, E. Glendening, M. Gutowski, A. Hess, J. Jaffe, B. Johnson, J. Ju, R. Kobayashi, R. Kutteh, Z. Lin, R. Littlefield, X. Long, B. Meng, T. Nakajima, S. Niu, L. Pollack, M. Rosing, G. Sandrone, M. Stave, H. Taylor, G. Thomas, J. van Lenthe, A. Wong, and Z. Zhang. ``NWChem, A Computational Chemistry Package for Parallel Computers, Version 5.1'' (2007), Pacific Northwest National Laboratory, Richland, Washington 99352-0999, USA.  A modified version.\n\n\\bibitem{GPROF}\ngprof.  Jay Fenlason and Richard Stallman.  Copyright 1988, 92, 97, 98, 99, 2000, 2003 Free Software Foundation, Inc.\n\n\\bibitem{TAU}\nTAU: The TAU Parallel Performance System.  S. Shende and A. D. Malony. \\textit{International Journal of High Performance Computing Applications}, Volume 20 Number 2 Summer 2006. Pages 287-331.\n\n\\bibitem{GotoBLAS}\n\\texttt{http://www.tacc.utexas.edu/resources/software/}\n\n\\bibitem{ATLAS}\n\\texttt{http://math-atlas.sourceforge.net/}\n\n% \\bibitem{QingdaTranspose}\n% Q. Lu, S. Krishnamoorthy and P. Sadayappan, ``Combining Analytical and Empirical Approaches in Tuning Matrix Transposition'', the \\textit{15th international conference on Parallel architectures and compilation techniques (PACT)}, 2006.\n\n\\end{thebibliography}\n\n\\end{document}\n", "meta": {"hexsha": "d3166764c8b657787aa6721b44be65762cee5a85", "size": 18889, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "papers/old/spaghetty_chapter_v1.tex", "max_stars_repo_name": "jeffhammond/spaghetty", "max_stars_repo_head_hexsha": "e2dbe2dd2621110b899b21dff590906a579e8bf5", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-01-05T16:13:08.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-05T16:13:08.000Z", "max_issues_repo_path": "papers/old/spaghetty_chapter_v1.tex", "max_issues_repo_name": "jeffhammond/spaghetty", "max_issues_repo_head_hexsha": "e2dbe2dd2621110b899b21dff590906a579e8bf5", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "papers/old/spaghetty_chapter_v1.tex", "max_forks_repo_name": "jeffhammond/spaghetty", "max_forks_repo_head_hexsha": "e2dbe2dd2621110b899b21dff590906a579e8bf5", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 92.5931372549, "max_line_length": 1542, "alphanum_fraction": 0.7541426227, "num_tokens": 5319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.3003371933871201}}
{"text": "\\chapter{Algorithm Selection Model Training Algorithms}\n\n\\section{Introduction}\nThis chapter explains the implementation details of the algorithms used in training the AS model, which are \\textit{pairwise random forest regression} (PRFR) and REINFORCE.\n\n\\section{Data Preparation}\n\\label{sec:dataprep}\n\nTable \\ref{tbl:graphs2015} displays the summary on GRAPHS-2015 dataset.\n\n\\begin{table}[H]\n\t\\centering\n\t\\begin{tabular}{|l|l|}\n\t\t\\hline\n\t\t\\textbf{Scenario ID} & GRAPHS-2015 \\\\ \\hline\n\t\t\\textbf{Source} & \\citet{graphs2015} \\\\ \\hline\n\t\t\\textbf{Number of problem instances} & 5725 \\\\ \\hline\n\t\t\\textbf{Number of features} & 35 \\\\ \\hline\n\t\t\\textbf{Number of algorithms} & 7 \\\\ \\hline\n\t\t\\multirow{7}{*}{\\textbf{Algorithm list}} & LAD \\\\ \\cline{2-2} \n\t\t& SupplementalLAD \\\\ \\cline{2-2} \n\t\t& VF2 \\\\ \\cline{2-2} \n\t\t& GLASGOW1 \\\\ \\cline{2-2} \n\t\t& GLASGOW2 \\\\ \\cline{2-2} \n\t\t& GLASGOW3 \\\\ \\cline{2-2} \n\t\t& GLASGOW4 \\\\ \\hline\n\t\t\\textbf{Performance measure} & Runtime (in milliseconds) \\\\ \\hline\n\t\\end{tabular}\n\t\\caption{GRAPHS-2015 dataset summary}\n\t\\label{tbl:graphs2015}\n\\end{table}\n\nOnly a subset of GRAPHS-2015 was used for training AS models. A technique called \\textit{presolving} is used to eliminate the quickly solvable problem instances, leaving the harder problem instances for AS. The steps on removing presolved instances from GRAPHS-2015 were discussed in PORTSUB study. The flow and code is shown in Figures \\ref{fig:presolver} and \\ref{fig:extracthard}.\n\n\\begin{figure}[H]\n\t\\centering\n\t\\scalebox{.85}{\\includegraphics{./img/presolver.png}}\n\t\\caption[Filtering presolved instances from GRAPHS-2015]{Filtering presolved instances from GRAPHS-2015. 2336 hard problems are left for AS.}\n\t\\label{fig:presolver}\n\\end{figure}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\scalebox{.60}{\\includegraphics{./img/extract_hard_instances.png}}\n\t\\caption{R script for extracting hard instances from GRAPHS-2015}\n\t\\label{fig:extracthard}\n\\end{figure}\n\n\\section{Pairwise Random Forest Regression}\nThe AS model used in PORTSUB study was trained using a supervised learning approach called PRFR. It works as follows: for each pair of algorithms in the algorithm portfolio, a model is trained to predict the performance difference between them. If the first algorithm is better than the second, the difference is positive, otherwise negative. The algorithm with the highest cumulative performance difference, i.e. the most positive difference over all other algorithms, is chosen to be run. \n\nThe LLAMA R package contains an implementation of pairwise random forest regression written by Lars Kotthoff, one of the PORTSUB authors. Its usage in R is shown on Figure \\ref{fig:prfr}\n\n\\begin{figure}[H]\n\t\\centering\n\t\\scalebox{.65}{\\includegraphics{./img/prfr.png}}\n\t\\caption{R script for building AS model trained using PRFR}\n\t\\label{fig:prfr}\n\\end{figure}\n\n\\section{REINFORCE}\n\nThe adaptation of REINFORCE algorithm to AS is composed of three main components:\n\n\\begin{enumerate}\n\t\\item \\textbf{Function approximator} \\\\\n\tAn AS model can learn how algorithms match to problems with certain features. Patterns in problem features can be captured by function approximation methods, which translate feature values into parameters. For example, a simple function approximator such as linear regressor parameterizes inputs into slope and offset coefficients. Neural networks, a universal function approximator, represent parameters as network weights. Function approximation assists in generalizing AS model learning through discovery of feature patterns across problem instances.\n\t\n\t\\item \\textbf{Policy function} \\\\\n\tA policy function takes function approximator parameters as input and computes a probability for each algorithm. Algorithm probabilities change with respect to problem features. The computed probabilities serve as the basis of selection among algorithms.   \n\t\n\t\\item \\textbf{Reward function} \\\\\n\tThe reward value is equivalent to the observed performance of the selected algorithm. It serves as feedback to the AS model to improve its capability in predicting optimal algorithms. Optionally, the reward value can be normalized or transformed to control how much the policy behavior should change with respect to feedback.  \n\\end{enumerate}\n\nFigure \\ref{fig:reinforce_flowchart} illustrates how an AS model is trained using \\textit{REINFORCE} algorithm. \n\n\\begin{figure}[H]\n\t\\centering\n\t\\scalebox{.65}{\\includegraphics{./img/REINFORCE_flowchart.png}}\n\t\\caption{Implementation of AS model trained using REINFORCE}\n\t\\label{fig:reinforce_flowchart}\n\\end{figure}\n\n\\begin{enumerate}\n\t\\item The GRAPHS-2015 dataset is loaded into R workspace. Hard problem instances are extracted, which consists of 2336 problem instances with 42 attributes used for training: 35 problem features plus runtime data of 7 algorithms.\n\t \n\t\\begin{figure}[H]\n\t\t\\centering\n\t\t\\scalebox{.75}{\\includegraphics{./img/problem_instance.png}}\n\t\t\\caption{Sample problem instance from GRAPHS-2015 dataset}\n\t\t\\label{fig:problem_instance}\n\t\\end{figure}\n\n\t\\item Problem features are normalized using \\textit{Z-score}. Normalization standardizes the range of data inputs which helps in resolving numerical issues when gradients are calculated during backpropagation. In effect, this speeds up neural network learning.\n\t\n\t\\begin{equation}\n\tz_{ij} = \\frac{x_{ij} - \\mu_j}{\\sigma_j}\n\t\\end{equation} \n\t\n\twhere:\n\t\n\t\\begin{table}[H]\n\t\t\\centering\n\t\t\\begin{tabular}{rl}\n\t\t\t$z_{ij} =$ & normalized feature value\\\\\n\t\t\t$x_{ij} =$ & feature value \\\\\n\t\t\t$\\mu_{j} =$ & mean of \\textit{jth} feature across \\textbf{P} problem instances \\\\\n\t\t\t$\\sigma_j =$ & standard deviation of \\textit{jth} feature across \\textbf{P} problem instances \\\\\n\t\t\t$\\mathit{i} =$ & \\textit{ith} instance from \\textbf{P} problem instances \\\\\n\t\t\t$\\mathit{j} =$ & \\textit{jth} feature out of 35 features \\\\\t\t\t\n\t\t\\end{tabular}\n\t\\end{table}\n\n\tThe algorithm runtime data is rescaled to simplify the reward value used for computing the performance gradient. This enables the AS model to learn the most important information during problem solving, which is the ranking of algorithm performance from best to worst. This information is more important than the knowledge of actual algorithm runtimes, as the objective of AS is mainly not to characterize individual algorithm performance, but to determine which algorithms work best on problems. Table \\ref{tbl:rewardscaling} shows how this study mapped algorithm ranking (determined by sorting runtime from shortest to longest) to reward values.\n\n\t\\begin{table}[H]\n\t\t\\centering\n\t\t\\begin{tabular}{|c|c|}\n\t\t\t\\hline\n\t\t\t\\multicolumn{1}{|l|}{\\textbf{Algorithm rank}} & \\multicolumn{1}{l|}{\\textbf{Assigned Reward Value}} \\\\ \\hline\n\t\t\t1 & 16 \\\\ \\hline\n\t\t\t2 & 4 \\\\ \\hline\n\t\t\t3 & 1 \\\\ \\hline\n\t\t\t4 & -4 \\\\ \\hline\n\t\t\t5 & -16 \\\\ \\hline\n\t\t\t6 & -64 \\\\ \\hline\n\t\t\t7 & -256 \\\\ \\hline\n\t\t\\end{tabular}\n\t\t\\caption{Algorithm ranking reward values}\n\t\t\\label{tbl:rewardscaling}\n\t\\end{table}\n\t\n\t\\item A neural network is trained to map problem features (input) to algorithm scores (output). It is composed of an input layer with 35 inputs, 3 hidden layers, and an output layer with 7 outputs. Algorithm scores represent selection preferences, i.e., the larger the score, the more often that algorithm is taken.\n\t\n\t\\item The algorithm scores are converted into probabilities using the softmax policy function. The probability assigned to an algorithm is proportional to its score, i.e., algorithms with the highest scores are given the highest probabilities of being selected. The softmax equation is given in the Equation below:\n\t\n\t\\begin{equation}\n\t\\pi(A | S_i, \\theta) = \\frac{\\exp{H_A(S_i, \\theta)}}{\\sum_{b=1}^{7}\\exp{H_b(S_i, \\theta)}}\n\t\\end{equation}\n\t\n\twhere:\n\t\n\t\\begin{table}[H]\n\t\t\\centering\n\t\t\\begin{tabular}{rl}\n\t\t\t$\\pi(A | S_i, \\theta) =$ & Probability of algorithm A \\\\\n\t\t\t$H_A(S_i, \\theta) =$ & Algorithm score of algorithm A \\\\\n\t\t\t$H_B(S_i, \\theta) =$ & Algorithm score of algorithm B \\\\\n\t\t\t$S_i =$ & features of problem instance \\textit{i} \\\\\n\t\t\t$\\theta =$ & neural network weights\n\t\t\\end{tabular}\n\t\\end{table}\n\n\t\\item An algorithm is randomly selected based from the probabilities generated from the softmax policy function.\n\t\n\t\\item The rescaled reward value corresponding to the selected algorithm is read from the dataset. This value, along with the probability of the selected algorithm, is used to calculate the performance gradient:\n\t\n\t\\begin{equation}\n\t\\nabla J(\\theta_t) = G_t\\ln{\\pi(A | S_i, \\theta_t)}\n\t\\end{equation}\n\t\n\twhere:\n\t\n\t\\begin{table}[H]\n\t\t\\centering\n\t\t\\begin{tabular}{rl}\n\t\t\t$\\nabla J(\\theta_t) =$ & performance gradient \\\\\n\t\t\t$G_t =$ & reward \\\\\n\t\t\t$\\pi(A | S_i, \\theta_t) =$ & Probability of selected algorithm\n\t\t\\end{tabular}\n\t\\end{table}\n\n\t\\item The performance gradient is used for backpropagation, a standard method of updating the weights of a neural network. Through this process, the neural network learns to adjust the algorithm scores in proportion to the reward value associated with the selected algorithm. \n\t\n\t\\begin{equation}\n\t\\theta_{t+1} \\gets \\theta_t + \\alpha \\nabla J(\\theta_t)\n\t\\end{equation}\n\t\n\twhere:\n\t\n\t\\begin{table}[H]\n\t\t\\centering\n\t\t\\begin{tabular}{rl}\n\t\t\t$\\theta_{t+1} =$ & Updated neural network weights \\\\\n\t\t\t$\\theta_t =$ & current neural network weights \\\\\n\t\t\t$\\alpha =$ & learning rate \\\\\n\t\t\t$\\nabla J(\\theta_t) =$ & performance gradient\n\t\t\\end{tabular}\n\t\\end{table}\n\\end{enumerate}\n\n\\section{Model Evaluation}\nThe performance of PRFR and REINFORCE are evaluated using 10-fold cross validation. The 2336 hard instances from GRAPHS-2015 are randomly partitioned into 10 subsets of approximately equal size. Of the 10 subsets, 9 are combined to form the training set for the AS models, while the remaining subset is formed as a test set. Mean MCP (Equation \\ref{eq:mcp}) is calculated on the test set to evaluate the AS model performance. This is repeated 10 times for all possible combinations of training and test sets. At the end of this process, the final mean MCP is calculated by averaging the mean MCPs from all test sets.\n\n\\section{R source code implementation}\nThe implementation of AS models in this study can be retrieved from here: \\url{https://github.com/kvrigor/algosel-rl}", "meta": {"hexsha": "90e9a7a94be734a33577069acdbb0cf8e93f13b2", "size": 10172, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/tex/ch4_asModel.tex", "max_stars_repo_name": "kvrigor/algosel-rl", "max_stars_repo_head_hexsha": "c8a32d071325ec455e4bf1019e94cce0c304ad3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-28T21:47:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-28T21:47:36.000Z", "max_issues_repo_path": "paper/tex/ch4_asModel.tex", "max_issues_repo_name": "kvrigor/algosel-rl", "max_issues_repo_head_hexsha": "c8a32d071325ec455e4bf1019e94cce0c304ad3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/tex/ch4_asModel.tex", "max_forks_repo_name": "kvrigor/algosel-rl", "max_forks_repo_head_hexsha": "c8a32d071325ec455e4bf1019e94cce0c304ad3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-18T06:06:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-18T06:06:01.000Z", "avg_line_length": 51.6345177665, "max_line_length": 648, "alphanum_fraction": 0.7508847818, "num_tokens": 2745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160664, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.30033718649661867}}
{"text": "\\section{Parameters}\n\\subsection{Non-age-stratified parameters}\n\n\\begin{longtable}[ht]{| >{\\raggedright}p{4cm} | >{\\raggedright}p{3cm} | p{6.8cm} |}\n    \\hline\n    Parameter & Value & Rationale \\\\\n    \\endfirsthead\n\t\\multicolumn{3}{c}{continuation of parameters table}\\\\\n    \\endhead\n    \\hline Incubation period & Calibration parameter, truncated normal distribution, mean 5.5 days & Estimates of the incubation period have included 5.1 days, 5.2 days and 4.8 days \\cite{RN7, RN12, RN8, RN10}. A systematic review \\cite{RN13} found that data are best fitted by a log-normal distribution (mean 5.8 days, CI 5.0 to 6.7, median 5.1 days). Our systematic review \\cite{RN17} found that estimates of the mean incubation period have varied from 3.6 to 7.4 days. \\\\\n    \\hline\n    Proportion of incubation period infectious & 50\\% &     Infectiousness is considered to be present throughout a considerable proportion of the incubation period, based on analyses of confirmed source-secondary pairs \\cite{RN23} and early findings that the incubation period was similar to the serial interval \\cite{RN7}. The study of source-secondary pairs was also the primary reference cited by a review of the infectious period that identified studies that quantified the pre-symptomatic period, which concluded that the median pre-symptomatic period could range from less than one to four days \\cite{RN14}. \\\\\n    \\hline\n    Active period (regardless of detection/isolation, for clinical strata 1 to 3) &\n    Calibration parameter, truncated normal distribution, mean 8 days &\n    This quantity is difficult to estimate, given that identified cases are typically quarantined. Studies in settings of high case ascertainment and an effective public health response have suggested a duration of greater than 5.5 days \\cite{RN10}. PCR positivity, which may continue for up to two to three weeks from the point of symptom onset \\cite{RN23} \\cite{RN14}, is difficult to interpret and does not necessarily indicate infectiousness. Consistent with these findings, the duration infectious for asymptomatic persons has been estimated at 6.5 to 9.5 days \\cite{RN14} (although in our model, this would include the pre-symptomatic infectious period). \\\\\n    \\hline\n    Proportion of infectious period before isolation or hospitalisation can occur & \n    0.333 &\n    Assumed \\\\\n    \\hline\n    Disease duration prior to admission for hospitalised patients not critically unwell (i.e. early active sojourn time, stratum 4) &\n    7.7 days &\n    Mean value from ISARIC cohort, as reported on 4\\textsuperscript{th} October 2020 in Table 6 \\cite{RN22}, and similar to the expected mean from earlier reports from ISARIC \\cite{RN16}. This cohort represents high-income countries better than low and middle-income countries, with the United Kingdom contributing data on the greatest number of patients, followed by France. Earlier estimates of this quantity from China included 4.4 days \\cite{RN7}. \\\\\n    \\hline\n    Duration of hospitalisation if not critically unwell (late active sojourn time, stratum 4) &\n    12.8 days &\n    Mean value from the ISARIC cohort, as reported on 4\\textsuperscript{th} October 2020 in Table 6 \\cite{RN22}. \\\\\n    \\hline\n    ICU duration (late active sojourn time, stratum 5) & 10.5 days &\n    Mean duration of stay in ICU/HDU from ISARIC cohort for patients with complete data, as reported on 10\\textsuperscript{th} October 2020 Table 6 \\cite{RN22}. Many other studies reporting on the average duration of ICU stay suffer from right-truncation issues, often estimating 7-10 days length of stay. \\\\\n    \\hline    \n    Duration of time prior to ICU for patients admitted to ICU & \n    10.5 days & \n    Calculated as the sum of the time from symptom onset to hospital admission (7.7 days above) plus the duration from hospital admission to ICU admission reported by October ISARIC report (2.8 days) \\cite{RN22}. \\\\\n    \\hline\n    Relative infectiousness of asymptomatic persons (per unit time with active disease) & 0.5 & Assumed \\\\\n    \\hline\n    Relative infectiousness of persons admitted to hospital or ICU & 0.2 & Assumed \\\\\n    \\hline\n    Relative infectiousness of identified persons in isolation & 0.2 & Assumed \\\\\n    \\hline\n    Proportion of hospitalised patients ever admitted to ICU & 0.17 & Assumed \\\\\n    \\hline\n\t\\caption{\\textbf{Universal (non-age-stratified) model parameters.} Point estimates are used as model parameters except where ranges are indicated in calibration parameter table below in calibration table.}\n\t\\title{Universal model parameters.}\n\t\\label{tab:params}\n\\end{longtable}\n", "meta": {"hexsha": "14f1e11df59c8e4a3af839e90788823bfabefd4c", "size": 4591, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/papers/covid_19/projects/victoria/parameters.tex", "max_stars_repo_name": "monash-emu/AuTuMN", "max_stars_repo_head_hexsha": "fa3b81ef54cf561e0e7364a48f4ff96585dc3310", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2020-03-11T06:15:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T03:38:35.000Z", "max_issues_repo_path": "docs/papers/covid_19/projects/victoria/parameters.tex", "max_issues_repo_name": "monash-emu/AuTuMN", "max_issues_repo_head_hexsha": "fa3b81ef54cf561e0e7364a48f4ff96585dc3310", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 96, "max_issues_repo_issues_event_min_datetime": "2020-01-29T05:10:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T01:48:46.000Z", "max_forks_repo_path": "docs/papers/covid_19/projects/victoria/parameters.tex", "max_forks_repo_name": "monash-emu/AuTuMN", "max_forks_repo_head_hexsha": "fa3b81ef54cf561e0e7364a48f4ff96585dc3310", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2020-04-24T00:38:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-19T16:19:03.000Z", "avg_line_length": 93.693877551, "max_line_length": 663, "alphanum_fraction": 0.7584404269, "num_tokens": 1165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.3003240773967616}}
{"text": "\\PassOptionsToPackage{dvipsnames}{xcolor}\n\\documentclass[12pt]{article}\n%\\documentclass[10pt,draft]{article}\n\\usepackage[utf8]{inputenc} % utf8 support\n\n% === Document Layout ===\n\\usepackage[hmargin=0.75in,vmargin=0.75in]{geometry}\n\\usepackage{indentfirst}\n\\usepackage{lipsum}\n\\usepackage{url}\n\\usepackage[\n    colorlinks,\n    linkcolor=red!50!black,\n    citecolor=blue!50!black,\n    urlcolor=blue!50!black\n]{hyperref}\n\\usepackage{amsmath}\n\\usepackage{pdfpages}\n\\usepackage{physics}\n\\usepackage{mathtools}\n\\usepackage{graphicx}\n\\usepackage{xcolor}\n\\usepackage{mathtools} % for the coloneq command\n\\usepackage{xparse}\n\\usepackage{ifthen} % For checking optional parameters\n\\usepackage{enumerate}\n\\usepackage{amsthm} % The AMS theorems package\n\\usepackage{amsthm}\n\\usepackage{caption}\n\\captionsetup{width=0.8\\textwidth}\n\\usepackage{subcaption}\n\\usepackage{float}\n\\usepackage{tabularx}\n\\usepackage{authblk} % For affiliations\n\\usepackage{amsfonts}\n\\usepackage{indentfirst}\n\\usepackage{amssymb} % for ordering symbols\n\\usepackage{colonequals} % for the \\ratio command\n\n% amsthm\n\\newtheorem{theorem}{Theorem}[section]\n\\newtheorem{lemma}[theorem]{Lemma}\n\\newtheorem{proposition}[theorem]{Proposition}\n\\newtheorem{corollary}[theorem]{Corollary}\n\\newtheorem{conjecture}[theorem]{Conjecture}\n\\theoremstyle{definition}\n\\newtheorem{definition}{Definition}[section]\n\\theoremstyle{remark}\n\\newtheorem{remark}{Remark}\n\n% === Bibliography ===\n\\usepackage[\n    backend=biber,\n    style=authoryear,\n    citestyle=authoryear,\n]{biblatex}\n\\addbibresource{references.bib}\n\n\\newcommand{\\speccite}[1]{\\citetitle{#1} \\parencite{#1}}\n\n\\newcommand{\\dt}[1]{\\frac{\\mathrm d #1}{\\mathrm d t}}\n\\usepackage{pgfplots}\n\\usepackage{tikz}\n\\usepackage{tikz-3dplot}\n\\usetikzlibrary{calc}\n\\tikzset{every picture/.style={baseline={(current bounding box.center)}}}\n\n\\author[1,2]{Thomas C. Fraser}\n\\affil[1]{Perimeter Institute for Theoretical Physics, Waterloo, Ontario, Canada, N2L 2Y5}\n\\affil[2]{Dept. of Physics and Astronomy, University of Waterloo, Waterloo, Ontario, Canada, N2L 3G1}\n\\date{\\today}\n\n\\title{On the Causality of Dynamical Systems}\n\n\\begin{document}\n\\maketitle\n\n\\section*{Comments}\n\nThese notes can be found at \\url{https://github.com/tcfraser/pearl_and_dynamic_causality}.\n\n\\section{Overview}\n\n\\begin{enumerate}\n    \\item Origins in early chaos theory\n    \\begin{itemize}\n        \\item Lorenz's system \\parencite{lorenz1963deterministic}\n        \\item Attractors\n        \\item Reconstructing attractors \\parencite{packard1980geometry}\n        \\item Takens' Theorem \\parencite{takens1981detecting}\n    \\end{itemize}\n    \\item Techniques for Dynamical causal discovery\n    \\begin{itemize}\n        \\item Convergent Cross-mapping (CCM) \\parencite{sugihara2012detecting}\n        \\item Topological Causality (TC) \\parencite{harnack2017topological}\n        \\item Dimensional Causality (DC) \\parencite{benkHo2018exact}\n    \\end{itemize}\n\\end{enumerate}\n\nThe \\textbf{dynamical systems} which will be considered here involved a finite number $n$ of variables $\\{X_1, X_2, \\ldots, X_n\\}$ evolving according to a system of deterministic, first-order, time-independent, oridinary differential equations (discrete or continuous in time).\n\\[ \\dt{X_j} = f_{j} (X_1(t), X_2(t), \\ldots X_n(t)) \\]\n\nThe solution to a dynamical system on a manifold $M$ (for example $\\mathbb R^n$) is specified by a \\textbf{flow}\n\\begin{equation}\n    \\Phi_{(\\cdot)}(\\cdot) : \\mathbb R \\times M \\to M,\n\\end{equation}\nwhere $\\Phi_t$ is a diffeomorphism of $M$ for all $t \\in \\mathbb R$ such that\n\\begin{equation}\n    \\forall V \\in M : \\Phi_{0} ( V ) = V, \\quad \\text{and} \\quad \\forall s,t \\in \\mathbb R: \\Phi_t \\circ \\Phi_s = \\Phi_{s+t}.\n\\end{equation}\n\n\\section{A Chaotic Origin Story}\n\n\\subsection{Lorenz's Discovery}\nIn \\speccite{lorenz1963deterministic}, \\citeauthor{lorenz1963deterministic} (this is Edward Norton Lorenz, not to be confused with the physicist Ludvig Lorenz, or the actor Edward Norton) presented a simplified dynamical model for atmospheric convection, which today is known as the Lorenz system:\n\\begin{align}\n    \\begin{split}\n        \\dt{X} &= \\sigma ( Y - X ), \\\\\n        \\dt{Y} &= X ( \\rho - Z ) - Y, \\\\\n        \\dt{Z} &= XY - \\beta Z.\n    \\end{split}\n\\end{align}\nThe Lorenz system was remarkable because despite its determinism and simplicity, it exhibits flows which are non-periodic, chaotic and yet bounded as in Figure~\\ref{lorenz_system}. Moreover, Lorenz identifies the non-linearity of the equations as being essential for these features postulates their ubiquity.\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[scale=0.35]{figures/lorenz_system.png}\n    \\caption{The strange attractor of the Lorenz system for $\\sigma = 10, \\beta = 8/3, \\rho = 28$ with $X(0) = 1.1, Y(0) = -1.9, Z(0) = 13.1$. Figure by \\href{https://www.researchgate.net/figure/A-trajectory-of-the-Lorenz-system-in-phase-space-revealing-the-strange-attractor-The_fig1_262074522}{P. T. Clemson}.}\n    \\label{lorenz_system}\n\\end{figure}\n\nLater in \\speccite{ruelle1971nature}, \\citeauthor{ruelle1971nature} develop a variety of mathematics to study such quasi-periodic behaviors and refers to them as \\textit{strange attractors}. Importantly, they conjectured that universally, strange attractors where the cause of turbulent behaviors seen in fluid flow. This conjecture received further support after \\speccite{gollub1975onset}.\n\n\\subsection{What are attractors anyway?}\nWhat exactly is notion of an \\textit{attractor}? Intuitively, attractors generalize the more familiar notions of stability for differential equations such as \\textit{stable fixed points} and \\textit{limit cycles} in the sense that an attractor $A$ is a compact subset such that points starting sufficiently close to $A$ will remain in a given neighborhood of $A$. For a detailed account of the various notions and formulations of an attractor, see \\speccite{milnor1985concept}. Nevertheless, the following definition will be adequate.\n\nAn \\textbf{attractor} is any $A \\subseteq M$ which is\n\\begin{enumerate}\n    \\item forward invariant\n        \\[ \\forall a \\in A, \\forall t \\geq 0 : \\Phi_{t} ( a ) \\in A, \\]\n    \\item admits an neighborhood $B(A)$, called the \\textbf{basin of attraction}, such for every open neighborhood $N$ of $A$, there is a sufficiently large $T$ such that\n        \\[ \\forall b \\in B(A), \\forall t \\geq T : \\Phi_{t} ( b ) \\in N, \\]\n    \\item and finally, there is no other proper subset $A' \\subset A$ satisfying the above.\n\\end{enumerate}\nNote that some alternative definitions demand that $A$ has non-zero measure (i.e. to eliminate stable fixed points) or that there exists a orbit of the flow that is dense inside $A$.\n\nWhat makes a strange attractor so \\textit{strange}? At the time, \\citeauthor{ruelle1971nature} never articulated a concrete definition for strange attractors, instead is was simply an attractor that was ``strange'' to them. Today, strange attractors are defined to be attractors whose dimension is not an integer, i.e. a fractal. Of course, the Lorenz attractor is a strange attractor in this sense as well, as proven in \\speccite{tucker2002rigorous}.\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[scale=0.6]{figures/strange_attractors.png}\n    \\caption{Some strange attractors. Figures from \\href{http://mathworld.wolfram.com/StrangeAttractor.html}{E. W. Weisstein}.}\n\\end{figure}\n\n\\subsection{Reconstructing Attractors}\nIn \\speccite{packard1980geometry}, \\citeauthor{packard1980geometry} were interested in problem of \\textit{dynamical reconstruction}: from experimental observations of a turbulent fluid flow, how does one show the existence of a low-dimensional chaotic dynamical system which explains the observed behaviors? Additionally, how does one determine the dimensionality of the underlying attractor? They demonstrate their ideas using another non-linear dynamical system studied by \\parencite{rossler1976equation}:\n\n\\begin{align}\n    \\label{rossler}\n    \\begin{split}\n        \\dt{X} &= - ( Y + Z ), \\\\\n        \\dt{Y} &= X + 0.2 Y, \\\\\n        \\dt{Z} &= 0.4 + XZ - 5.7 Z.\n    \\end{split}\n\\end{align}\n\nTheir reconstruction method relied directly on the intuition that in order to specify the state of an $n$-dimensional system at any given time, it is sufficient to known the values of \\textit{any} set of $n$ ``independent'' quantities. Moreover, they conjecture that the attractors associated with any such are all \\textit{diffeomorphically} equivalent. To support this claim, they compare various trajectories in $3$-dimensions of the Rossler system: $\\{ X(t), Y(t), Z(t)\\}$, $\\{ X(t), X(t - \\tau), X(t - 2 \\tau)\\}$ (this example is credited to Ruelle by the authors), and $\\{ X(t), \\dot X(t), \\ddot X(t) \\}$ (by making $\\tau$ very small and taking appropriate differences).\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[scale=0.25]{figures/rossler_reconstruction.png}\n    \\caption{The \\citeauthor{rossler1976equation} system flow projected onto the $X, Y$ plane and the induced flow of $(X, \\dot X, \\ddot X)$ projected onto the $X, \\dot X$ plane. Figure from \\parencite{packard1980geometry}.}\n\\end{figure}\n\nEvidently their heuristic seems to work and moreover it appears possible to reconstruct the dynamics from observing just a single coordinate. They further provide some tools for estimating the dimensionality of the attractor and how it relates to the number non-negative characteristic exponents.\n\n\\subsection{Takens' Theorem}\n\nShortly after this, in \\speccite{takens1981detecting}, \\citeauthor{takens1981detecting} formalized and proved the conjecture of \\parencite{packard1980geometry} which has come to be known as \\textit{Takens' Theorem}. The following is a summary of \\href{https://www.math.sciences.univ-nantes.fr/~vitturi/talks/PG%20Colloquia/Takens_theorem.pdf}{Marco Vitturi's slides} on the subject.\n\n\\textbf{Whitney Embedding Theorem:}\nLet $M$ be a compact manifold of (integer) dimension $d$. Then $M$ can be embedded smoothly in $\\mathbb{R}^{2n}$ (i.e. no self-intersections).\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[scale=0.1]{figures/klein_bottle.png}\n    \\caption{The Klein bottle can be embedded smoothly in $\\mathbb R^4$, but not in $\\mathbb R^3$.}\n\\end{figure}\n\n\\textbf{Takens' Theorem:}\nLet $M$ be a compact manifold of (integer) dimension $d$. Then for \\textit{generic} pairs $(\\phi, X)$, where\n\\begin{itemize}\n    \\item $\\phi : M \\to M$ is a $C^2$-diffeomorphism of $M$ in itself,\n    \\item $X : M \\to \\mathbb R$ is a $C^2$-differentiable function,\n\\end{itemize}\nthen the map $\\Omega_{\\phi, X} : M \\to \\mathbb R^{2d + 1}$ acting on $V \\in M$ defined by\n\\[ \\Omega_{\\phi, X}(V) = ( X(V), X(\\phi(V)), X(\\phi^2(V)), \\cdots, X(\\phi^{2d}(V))) \\]\nis an embedding of $M$ into $\\mathbb{R}^{2d+1}$ (i.e. injective and immersive).\n\nTakens' theorem when applied to the flow of a dynamical system in $\\mathbb R^n$ when $M$ is taken to be the attractor (assume manifold) $A$:\n\\begin{itemize}\n    \\item $\\phi = \\Phi_{-\\tau} : A \\to A$ for some $\\tau > 0$,\n    \\item $X : A \\to \\mathbb R$ any coordinate of the system on the attractor,\n    \\item the \\textbf{delay embedding} becomes\n        \\begin{align*}\n            \\Omega_{\\Phi_{-\\tau}, X}(V)\n            &= ( X(V), X(\\Phi_{-\\tau}(V)), X(\\Phi_{-2\\tau}(V)), \\cdots, X(\\Phi_{-m\\tau}(V))) \\\\\n            &= ( X(t), X(t - \\tau), X(t - 2 \\tau), \\cdots, X(t - m \\tau))\n        \\end{align*}\n    \\item where $m$ needs to be sufficiently large, i.e. $m \\geq 2 \\mathrm{dim} (A)$ is sufficient.\n    \\item Oftentimes a smaller $m$ will still produce an embedding, but Takens' theorem does not guarantee this.\n\\end{itemize}\nA similar result can be stated for reconstructing the orbit in $\\mathbb{R}^d$ instead of the entire attractor, you can use $m = d - 1$. Therefore a single variable contains all the information about the orbit:\n\\[ t \\mapsto ( X(t), X(t - \\tau), X(t - 2 \\tau), \\cdots, X(t - (d-1) \\tau)). \\]\n\nAn analogous version for the case of non-integer (Hausdorff) dimensions $d_A$ is due to \\speccite{sauer1991embedology}, where $m \\geq \\lceil 2 d_{A} \\rceil}$.\n\nTherefore, the attractor $A$ of the original system is diffeomorphic to the time-delayed attractors $A_X, A_Y$ and $A_Z$ where $A_X = \\Omega_{\\Phi_{-\\tau}, X}(A)$.\n\nEvidently, Takens' theorem reveals that the distinction between the kinematics and dynamics of a system is an arbitrary distinction as one can freely transform between the various phase-spaces in a diffeomorphic way. For similar instances of this arbitrary distinction, and more ideas on this subject, see \\speccite{spekkens2015paradigm}.\n\n\\section{Selected References on Dynamic Causality}\n\n\\subsection{Granger Causality}\n\nThere is a pervasive notion of causality used frequently in economic forecasting, but also in neurology and ecology, known as \\textit{Granger Causality} or sometimes \\textit{G-Causality} named after Clive Granger. For evidence, the library of software tools \\speccite{barnett2014mvgc} is highly cited.  Its origins can be traced back to a suggestion due to (Wiener, 1956) for using prediction as a proxy for causality, which was subsequently developed by Granger from 1963 to 1980. Granger was awarded the Novel Prize in Economics in 2003.\n\nIn \\speccite{granger1988some}, \\citeauthor{granger1988some} summarizes his notions of causality for time-series' which were based on two principles:\n\\begin{enumerate}\n    \\item The cause occurs before the effect.\n    \\item The causal series (say $Y(t)$) contains \\textit{special information} about the series being caused (say $X(t)$) that is not available in the any other available series (say $W(t)$).\n\\end{enumerate}\n\nConsider two sets of historical data:\n\\begin{align}\n    J_t &= \\{ (X(t-j), Y(t-j), W(t-j)) | j \\geq 0 \\} \\\\\n    J_t' &= \\{ (X(t-j), W(t-j)) | j \\geq 0 \\}.\n\\end{align}\nHis definitions pertain to the following: in the context of $W$, does $Y$ cause $X$?\n\nLetting $P(X | J)$ denote the conditional distribution of $X$ given $J$, if $P(X(t+1) | J_t) = P(X(t+1) | J_t')$ then $Y(t)$ does \\textit{not cause} $X(t)$, otherwise $Y(t)$ is a \\textit{prima facie cause} of $X(t)$ and becomes a cause with certainty is $J_t$ contains all the information in the universe. Granger acknowledges a number of criticisms in his works.\n\nMost relevant for the current discussion is the article \\speccite{lusch2016inferring}, which simulated network systems of Kuramoto oscillators and then used the MGVC toolbox to reconstruct the network structure. They write ``Our results show a significant systematic disparity between the original and inferred network, unless the true structure is extremely sparse or dense.''\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[scale=0.3]{figures/granger_reconstruction.png}\n    \\caption{The methodology used by \\speccite{lusch2016inferring}.}\n\\end{figure}\n\nClearly, Granger's notions of causality are inappropriate for the purposes of causal modeling, despite its widespread use.\n\n\\subsection{Convergent Cross Mapping (CCM)}\n\nThe seminal article titled \\speccite{sugihara2012detecting} has been widely cited in other articles on dynamical causality and throughout ecological and economic communities. Its essential accomplishment, in my opinion, was the realization that nonlinear dynamical systems exhibit a kind of nonseparability which must be dealt with first in order analyze the underlying causal relations and moreover that Takens' theorem resolves this nonseparability.\n\nIt opens with an discussion around the notions of ephemeral or ``mirage'' correlations. The following discrete-time non-linear dynamical system,\n\\begin{align}\n    \\label{ecosystems}\n    \\begin{split}\n        X(t+1) &= X(t) ( r_x - r_x X(t) - \\beta_{x,y} Y(t) ) \\\\\n        Y(t+1) &= Y(t) ( r_y - r_y Y(t) - \\beta_{y,x} X(t) )\n    \\end{split}\n\\end{align}\nexhibits periods of correlation, anticorrelation and no correlation.\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[scale=0.35]{figures/mirage_correlations.png}\n    \\caption{An illustration of mirage correlations from \\speccite{sugihara2012detecting}.}\n\\end{figure}\nTherefore, using correlation to infer causation is risky, especially in nonlinear dynamics. Moreover, this demonstrates why a lack of correlation does not imply a lack of causation because the former could simply be temporary. In other words, the principle of no fine-tuning only applies in the long term.\n\n\\citeauthor{sugihara2012detecting} attributes the inadequacy of Granger causality for dynamical systems to Takens' theorem. In particular, ``information about $X(t)$ that is relevant to predicting $Y$ is redundant in this system''. Stated another way, by algebraically rearranging Eq.~\\ref{ecosystems}, it is possible to write $Y(t+1)$ in terms of $Y(t)$ and $Y(t-1)$; thus Granger causality predicts $X$ does not cause $Y$! In \\speccite{harnack2017topological}, this nonseparability is referred to as an \\textit{entanglement} between $X$ and $Y$.\n\nThe essential idea of \\parencite{sugihara2012detecting} is that time-series variables $X$ and $Y$ are \\textit{causally linked} if they share a common attractor manifold $A$; therefore, each variable can identify the other. Convergent cross mapping (CCM) tests for causal influence from $X$ to $Y$ by measuring the extent to which the history of $Y$ can reliably estimate the states of $X$. For example, a fish time series $Y$ can be used to estimate the weather $X$, but not conversely, thus $X$ causes $Y$; this is counter to Granger causality.\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[scale=0.4]{figures/convergent_cross_mapping.png}\n    \\caption{The method of convergent cross mapping (CCM) due to \\speccite{sugihara2012detecting}.}\n\\end{figure}\n\n\\textbf{Sketching the CCM Algorithm:}\n\\begin{enumerate}\n    \\item Given two time series of length $L$,\n        \\[ \\{ X(1), X(2), \\ldots, X(L) \\} \\quad \\text{and} \\quad \\{ Y(1), Y(2), \\ldots, Y(L) \\}, \\]\n        here is how to estimate $Y(t)$ using $X$.\n    \\item Compute the time lagged coordinate\n        \\[ \\underline{X}(t) = ( X(t), X(t - \\tau), X(t - 2 \\tau), \\ldots, X(t-(d-1)\\tau)\\}. \\]\n    \\item Then find its $d+1$ nearest neighbors in $A_{X}$, denoted\n        \\[ (\\underline{X}(t_1), \\underline{X}(t_2), \\ldots, \\underline{X}(t_{d+1}) ), \\]\n        thus forming a $d$-dimensional simplex around $\\underline{X}(t)$.\n    \\item Construct the estimate $\\hat Y(t)$ for $Y(t)$ as\n        \\[ \\hat Y(t) | A_X = \\sum_{i=1}^{d+1} \\omega_{i} Y(t_i) \\]\n        where the weight $\\omega_{i}$ is based on the distance between $\\underline X(t)$ and $\\underline X(t_i)$.\n    \\item As the length $L$ increases, the attractor manifold is filled in more and more, and the nearest neighbors get closer and thus $\\hat Y(t) | A_X$ should converge to $Y(t)$ (if $Y$ has causal influence on $X$) and vice versa.\n\\end{enumerate}\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[scale=0.55]{figures/convergence.png}\n    \\caption{Empirical results for CCM on Eq.~\\ref{ecosystems}. (A) CCM where $\\beta_{y,x} > \\beta_{x,y}$; the asymmetry is reflected in the differing rates of convergence. (B) How the difference in cross-mapping estimates depends on $\\beta_{x,y}$ and $\\beta_{y,x}$.   (C,D) Estimates when $\\beta_{x,y} = 0$, i.e. when $Y$ has no effect on $X$. From \\speccite{sugihara2012detecting}.}\n\\end{figure}\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[scale=0.6]{figures/sardines_vs_anchovies.png}\n    \\caption{(C-F) CCM resolves a long-disputed causal relationship between populations of sardines and anchovies along with sea surface temperatures (SST) measured at Scripps Pier and Newport Pier in California; sardines and anchovies are not interacting, but share a common cause, namely SST. From \\speccite{sugihara2012detecting}.}\n\\end{figure}\n\nFuture work demonstrated that CCM successfully distinguishes between direct and indirect causation in causal chains \\parencite{ye2015distinguishing}.\n\n\\subsection{Topological Causality (TC)}\n\nIn \\speccite{harnack2017topological}, the concepts of CCM are expanded upon further.\n\\begin{align*}\n    \\dt{X_1} &= f_1 ( X_1, w_{12} \\mu_2 ( X_2 ) ) \\\\\n    \\dt{X_2} &= f_2 ( X_2, w_{21} \\mu_1 ( X_1 ) )\n\\end{align*}\nTheoretically, if the diffeomorphism between the attractor manifolds is differentiable, then it can be linearized at a fixed time $t$ (Jacobian matrix), denoted $M_{i\\to j}^{t}$. The \\textit{expansion} of this linear map, denoted\n\\[ e^{t}_{i \\to j} = \\prod_{k} \\mathrm{max} (1, \\sigma_{k} (M_{i\\to j}^{t})) \\]\nis conjectured to be inversely proportional to the strength of the causal influence $X_j \\to X_i$ ($\\sigma_{k}(M_{i \\to j}^{t})$ is the $k$-th singular value of $M_{i \\to j}^{t}$). Unlike vanilla CCM, TC computes a \\textit{graduated} measure causal influence which furthermore can be taken to be time-dependent.\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[scale=0.6]{figures/topological_causality.png}\n    \\caption{The intuition behind the inverse relationship between expansion and causal influence in \\speccite{harnack2017topological}.}\n\\end{figure}\n\n\\subsection{Dimensional Causality (DC)}\n\nThe latest development in the field of dynamic causality based on Takens' theorem is the article \\speccite{benkHo2018exact}, which presents a method called \\textit{Dimensional Causality} (DC). While recognizing the utility of the CCM \\parencite{sugihara2012detecting} and TC \\parencite{harnack2017topological} techniques for detecting directed and bidirected causal relationships, \\citeauthor{benkHo2018exact} identifies their inability to consistently and accurately identify latent common causes. To their best knowledge, ``the DC method is the first exact one which detects and distinguishes all possible causal relations of deterministic dynamical systems.''\n\nThe entire technique heavily relies on the ability to estimate the manifold of an attractor from observational data; the authors use the method in \\speccite{szepesvari2007manifold} which depends only on a single parameter $k$ related to the resolution.\n\nIn order to detect the causal structure underlying two variables $X, Y$, there are three attractor manifolds of interest $A_X, A_Y$ and $A_J$ where $J = X \\times Y$ is the joint system. In practice however, they construct the joint dynamics additively using $J' = a X + Y$ with suitably chosen irrational number (they use $a = \\sqrt{29/31}$ as its close to unity).\n\nIf the two variables are independent, the joint dimension will equal the sum of the dimensions of the independent systems.\n\\[ \\text{Independent case:}\\qquad  X \\perp Y \\iff D_X + D_Y = D_J \\]\nAny interdependence between $X$ and $Y$ will lead to subadditivity in the manifold dimensions.Whenever there is unidirectional causation $X \\to Y$, the information content in the consequent $Y$ is capable of determining the cause $X$, therefore the dimensions $D_X, D_Y$ unequivocally determine the direction of possible causal effect (see Figure~\\ref{dim_cause} (A)),\n\\[ \\text{Unidirectional case:}\\qquad X \\to Y \\iff D_X < D_Y = D_J \\]\nThe bidirected case follows naturally, as Takens' theorem proves $A_X$ and $A_Y$ are topologically equivalent and thus have the same dimension.\n\\[ \\text{Bidirectional case:}\\qquad X \\leftrightarrow Y \\iff D_X = D_Y = D_J \\]\nDetecting the presence of a common cause (without direct causal effect between $X$ and $Y$) is trickier to motivate.\n\\[ \\text{Common cause case:}\\qquad X \\nwarrow\\!\\nearrow Y \\iff \\mathrm{max}(D_X, D_Y) < D_J < D_X + D_Y \\]\n\nAlternatively, these relationships become clearer when you realize that the authors are using the Rényi information dimension to estimate the dimensions of the attractors:\n\\[ d_X = \\lim_{N \\to \\infty} \\frac{1}{\\log N} H ( [X]_N ) \\]\nwhere $H$ is the Shannon entropy and $[X]_N = \\lfloor NX \\rfloor  / N$ is the $N$-quantized discrete version of $X$. Elementary entropic inequalities give\n\\[ \\mathrm{max}(H(X), H(Y)) \\leq H(X, Y) \\leq H(X) + H(Y), \\]\nwhich translates to the common cause condition above.\n\nTo showcase their method, they consider the logistic map,\n\\[ X_j[t+1] = r X_j[t] ( 1 - \\sum_{l = 1}^{3} \\beta_{j l} X_l[t] ) \\]\nwith $j, l \\in \\{1,2,3\\}$ and $r = 3.99$. The various causal scenarios are implemented as follows:\n\\begin{align*}\n    \\beta_{\\to} = \\begin{bmatrix} 1 & 0 & 0 \\\\ 0.5 & 1 & 0 \\\\ 0 & 0 & 1 \\end{bmatrix} \\qquad\n    \\beta_{\\leftrightarrow} = \\begin{bmatrix} 1 & 0.5 & 0 \\\\ 0.5 & 1 & 0 \\\\ 0 & 0 & 1 \\end{bmatrix} \\qquad\n    \\beta_{\\nwarrow\\!\\nearrow} = \\begin{bmatrix} 1 & 0 & 0.5 \\\\ 0 & 1 & 0.5 \\\\ 0 & 0 & 1 \\end{bmatrix} \\qquad\n    \\beta_{\\perp} = \\begin{bmatrix} 1 & 0 & 0 \\\\ 0 & 1 & 0 \\\\ 0 & 0 & 1 \\end{bmatrix}\n\\end{align*}\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[scale=0.4]{figures/dimensional_causality.png}\n    \\caption{Dimensional Causality identifies a variety of causal structures. From \\speccite{benkHo2018exact}.}\n    \\label{dim_cause}\n\\end{figure}\n\nThe also demonstrate their method on empirically obtained data and get interesting results. See scanned notes for more comments.\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[scale=0.5]{figures/inter-hemispherical_interactions.png}\n    \\caption{An application of the technique of dimensional causality in \\speccite{benkHo2018exact}.}\n\\end{figure}\n\n\\section{Other Noteworthy Articles}\n\nIn \\speccite{wagner1999causality}, \\citeauthor{wagner1999causality} argues that a ``...notion of causality can only only be meaningfully defined for systems with \\textit{linear} interactions among their variables. For the vastly more important class of \\textit{nonlinear} systems, no such notion is likely to exist.'' \\\\\n\nIn \\speccite{white2011linking}, \\citeauthor{white2011linking} use the formalism of \\textit{settable systems}, a generalization of Pearl's Causal Models \\parencite{pearl2000causality}, to closely link the concepts of Granger causality to that of Pearl causality.\\\\\n\nAt a quick glance, \\speccite{blom2019beyond} appears to be doing a similar thing but for systems at a stable fixed point.\\\\\n\nAlso \\speccite{arbach2015dynamic}.\n\n\\nocite{*}\n\\printbibliography\n\\end{document}\n", "meta": {"hexsha": "092eef28660c3c0164025ea3a36e4dead613e57f", "size": 25978, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "notes.tex", "max_stars_repo_name": "tcfraser/pearl_and_dynamic_causality", "max_stars_repo_head_hexsha": "e7303e3e031a7474e330ffd5384de8cd4c610bdb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notes.tex", "max_issues_repo_name": "tcfraser/pearl_and_dynamic_causality", "max_issues_repo_head_hexsha": "e7303e3e031a7474e330ffd5384de8cd4c610bdb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notes.tex", "max_forks_repo_name": "tcfraser/pearl_and_dynamic_causality", "max_forks_repo_head_hexsha": "e7303e3e031a7474e330ffd5384de8cd4c610bdb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 66.6102564103, "max_line_length": 675, "alphanum_fraction": 0.7330818385, "num_tokens": 7604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.30027496073574594}}
{"text": "\\documentclass{amsart}[12pt]\n\\usepackage{amsmath, amsfonts, tikz, natbib, array}\n\\oddsidemargin=0in \\evensidemargin=0in\n\\textwidth=6.6in \\textheight=8.7in\n\n\\title{Differentiable mappings from Euclidean to spherical polygons}\n\\author{B R S Recht}\n\\date{May 2019}\n\n\\begin{document}\n\n\\maketitle\n\n-map projections\n-geodesic domes\n-dymaxion map\n-square-circle maps\n\nYadda yadda\\cite{kahn}\n\nIn the geodesic dome world, geometry is usually synthetic rather than\nanalytic. That is, geometric constructions are usually expressed in terms of\nstep-by-step geometric constructions rather than in equations and numeric\nvalues. See, for instance, \\cite{kenner}. Implementing a synthetic geometric\nconstruction on a computer can be a pain; analytic specifications are more\namenable to programming idioms.\n\n\\section{Definitions}\nLet $x,y$ be coordinates in $\\mathbb{R}^2$ (equivalently, $z = x + i y$ in\n$\\mathbb{C}$), and $u,v,w$ be coordinates in $\\mathbb{R}^3$.\nIf a point in $\\mathbb{R}^3$ is on the unit sphere,\nthen its coordinates satisfy $u^2 + v^2 + w^2 = 1$.\n\nUnless otherwise specified, the vertices of any given polygon are ordered in\ncountclockwise order.\n\n\\subsection{Spherical geometry}\nThere are a number of ways to numerically specify points on a sphere. By far\nthe most common is by latitude and longitude, which appear on every modern map\nof the Earth and some other planets. Latitude and longitude are\nfamiliar and convenient, but performing extended geometry calculations using\nlatitude and longitude is often complicated.\n\nDoing spherical geometry using a 3-component unit vector is more convenient\nin a number of ways: the equations are often simpler, and there are no\nsingularities at the poles. We'll also find that calculations using vectors\noften make clear symmetries that would be hidden by other forms. A unit sphere\ncan be defined as the set of all unit\nvectors in 3-space; i.e., vectors $\\mathbf v = [v_x, v_y, v_z]$ such that the\nvector norm $\\|\\mathbf v \\|=1$. Unit vectors are often denoted using a hat:\n$\\hat{\\mathbf v}$. We'll often find ourselves normalizing vectors,\nso we may supress the denominator with an ellipsis like so:\n\\begin{equation}\n  \\hat{\\mathbf v} = \\frac{\\mathbf{some+really+long+statement}}{\\|\\dots\\|}\n\\end{equation}\nIf a vector is an intermediate step to a normalized vector,\nwe may call it pre-normalized and denote it ${\\mathbf v}^*$,\nsuch that $\\hat{\\mathbf v} = \\frac{{\\mathbf v}^*}{ \\|{\\mathbf v}^*\\|}$\n\nThe shortest distance between two points in Euclidean space is a straight line.\nOn the sphere, the shortest distance is an arc of the great circle between those\npoints. The great circle is the intersection of the sphere and a plane passing\nthrough the origin. A plane through the origin can be specified as\n$\\hat{\\mathbf n} \\cdot \\mathbf v = 0$, where $\\hat{\\mathbf n}$ is a unit vector\nnormal to the plane; this vector $\\hat{\\mathbf n}$ can be used to specify a\ngreat circle. Given two points $\\mathbf{\\hat{v}_1, \\hat{v}_2}$ on the sphere,\nthe $\\hat{\\mathbf n}$ of the great circle between those two points is (up to\nnormalization) their cross product:\n\\begin{equation}\n  \\mathbf{\\hat{n}} =\n\\frac{\\mathbf{\\hat{v}}_1 \\times \\mathbf{\\hat{v}}_2}{\\|\\dots\\|}\n\\end{equation}\n\nSmall circles are the intersection of the sphere with a plane not through\nthe origin. All planes may be specified in Hessian normal form as\n$\\mathbf{\\hat{n}} \\cdot \\mathbf v = r$, where $r$ is the minimum distance\nbetween the plane and the origin. The intersection of the plane with the sphere\nis determined by $r$ as so:\n\n\\begin{itemize}\n  \\item $r = 0$: Great circle\n  \\item $r \\in (0,1)$: Small circle\n  \\item $r = 1$: Point\n  \\item $r > 1$: None\n\\end{itemize}\n\nThe following subsections give some formulas for measurements and constructions\nin Euclidean space and on the sphere. Since a sphere is locally Euclidean, the\nspherical formulas approach the Euclidean formulas when the measures are small.\nNote that some spherical formulas require normalized vectors,\ndenoted by the hat $\\mathbf{\\hat{v}}$.\n\n\\subsubsection{Distance}\nIn Euclidean space, the distance between two vertices $\\mathbf v_1$ and\n$\\mathbf v_2$ is given by the usual metric. On the sphere, distance is the\ncentral angle $\\theta$, which is given by many equivalent forms: the most\nnumerically stable one is the one using $\\arctan$ given below.\n\\begin{equation}\\begin{split}\n\\eta & = \\|\\mathbf v_1-\\mathbf v_2\\| \\\\\n\\theta & = \\arctan\\left(\n  \\frac{\\|\\mathbf{\\hat{v}}_1 \\times \\mathbf{\\hat{v}}_2\\|}\n  {\\mathbf{\\hat{v}}_1 \\cdot \\mathbf{\\hat{v}}_2}\\right)\n\\end{split}\\end{equation}\n\n\\subsubsection{Angle}\nThe angle on a surface at the vertex $v_1$ between $v_2$ and $v_3$ is a\nstandard expression for Euclidean space. For spheres, it is the dihedral angle\nbetween the planes defined from $v_1$ to $v_2$ and from $v_1$ to $v_3$.\n\\begin{equation}\n  \\cos\\phi_1 = \\mathbf{\\hat{c}}_{12} \\cdot \\mathbf{\\hat{c}}_{13}\n\\end{equation}\nwhere $\\mathbf{\\hat{c}}_{ij} = \\frac{\\mathbf{v}_i - \\mathbf{v}_j}{\\|\\dots\\|}$\nfor Euclidean space and $\\mathbf{\\hat{c}}_{ij} = \\frac{\\mathbf{\\hat{v}}_i\n\\times \\mathbf{\\hat{v}}_j}{\\|\\dots\\|}$ for spheres. (This formula also has\nequivalent forms using $\\sin$ and $\\tan$.)\n\n\\subsubsection{Area}\nThe area of an arbitrary polygon with vertices $v_i$ is given by the shoelace\nformula. $n$ is the number of vertices in the polygon and\n$i = 0 \\dots n-1$ is an index for each vertex. $i$ should be treated as if it's\nmod $n$, so that it loops around. This formula will give a result for skew\npolygons, but the areas of skew polygons are not well-defined.\n\\begin{equation}\nA = \\frac{1}{2} \\| \\sum \\mathbf v_i\\times \\mathbf v_{i+1} \\|\n\\end{equation}\nThe area of a spherical triangle is the solid angle $\\Omega$,\nand given by a more elaborate formula. \\cite{oosterom}\\cite{eriksson}\n\\begin{equation}\n\\tan(\\Omega/2) = \\frac{|\\mathbf{\\hat{v}_1} \\cdot\n       \\mathbf{\\hat{v}}_2 \\times \\mathbf{\\hat{v}}_3|}\n       {1+\\mathbf{\\hat{v}}_1\\cdot \\mathbf{\\hat{v}}_2+\\mathbf{\\hat{v}}_2\n       \\cdot \\mathbf{\\hat{v}}_3+\\mathbf{\\hat{v}}_3\\cdot \\mathbf{\\hat{v}}_1}\n\\end{equation}\n\n\\subsubsection{Means}\nWhen $n=2$ this formula gives the midpoint between $\\mathbf v_1$ and\n$\\mathbf v_2$. When $n=3$ it gives the centroid of the triangle with\nvertices $\\mathbf v_1, \\mathbf v_2$ and $\\mathbf v_3$.\n\\begin{equation}\\begin{split}\n\\mathbf v_\\mu & = \\frac{\\sum\\mathbf v_i}{n} \\\\\n\\mathbf{\\hat{v}}_\\mu & = \\frac{\\sum\\mathbf{\\hat{v}}_i}{\\|\\dots\\|}\n\\end{split}\\end{equation}\n\\subsubsection{Interpolation}\nInterpolation in Euclidean space is standard linear interpolation. On the\nsphere, interpolation is given by spherical linear interpolation, or slerp.\n\\begin{equation}\n\\mathrm{Lerp}(\\mathbf{v_1}, \\mathbf{v_2}; t) =\n       (1-t) \\mathbf{v_1} + t \\mathbf{v_2}\n\\end{equation}\n\\begin{equation}\n\\mathrm{Slerp}(\\mathbf{\\hat{v}_1}, \\mathbf{\\hat{v}_2}; t) =\n\\begin{cases}\\mathbf{\\hat{v}_1}\n  & \\text{if } \\mathbf{\\hat{v}_1} = \\mathbf{\\hat{v}_2}\\\\\n        \\frac{\\sin ((1-t)w)}{\\sin (w)} \\mathbf{\\hat{v}_1} +\n       \\frac{\\sin (tw)}{\\sin (w)} \\mathbf{\\hat{v}_2}\n  &\\text{otherwise}\n      \\end{cases}\n\\end{equation}\nwhere $w = \\arccos \\mathbf{\\hat{v}_1} \\cdot \\mathbf{\\hat{v}_2}$.\n\n\\subsubsection{Face normal}\nFor the purposes of this text, we define the normal to a (Euclidean) polygon as\nso, where $n$ is the number of vertices in the polygon and\n$i = 0 \\dots n-1$ is an index for each vertex:\n\\begin{equation}\n  \\hat{\\mathbf{n}} =\n  \\frac{\\sum^{n-1}_i \\mathbf{v}_i \\times \\mathbf{v}_{i+1}}{\\|\\dots\\|}\n\\end{equation}\n$i$ should be treated as if it's mod $n$, so that it loops around.\n(Note the similarity to the shoelace formula.)\nThis definition allows for a somewhat sensible extension to skew polygons:\nthe normal points in a generally reasonable direction for skew polygons.\nThe normal will be outward-facing if the points are ordered counterclockwise,\nand inward-facing if the points are ordered clockwise.\n\n\\subsubsection{Skewness}\nThere's no standard measure of polygon skewness, so this text uses an ad-hoc\nmeasure that seems to work well. This program measures the skewness of a polygon\nwith 4 or more vertices by this method: Let $\\mathbf x_i = \\mathbf{v}_i -\n\\bar{\\mathbf{v}}$, where $\\bar{\\mathbf{v}}$ is the (Euclidean) average of the\npoints. Calculate the SVD decomposition of the matrix that has $\\mathbf x_i$\nas rows (or columns). We only need the singular values: since we're in 3d\nspace, there will be 3 singular values. The \\textit{skewness} is the smallest\nsingular value divided by the sum of the  other two singular values.\nIf the polygon is flat, the skewness is 0.\n\n\\subsection{Triangle and quadrilateral coordinates}\n\n\\begin{figure}%[!htbp]\n\\begin{tikzpicture}\n  \\draw (0, 0) -- (1.7,3) -- (3.4, 0) -- (0, 0) ;\n  \\draw[fill] (1.7, 3) circle [radius=0.05] node[anchor=west] {\\tiny 1};\n  \\draw[fill] (0, 0) circle [radius=0.05] node[anchor=south] {\\tiny 2};\n  \\draw[fill] (3.4, 0) circle [radius=0.05] node[anchor=south] {\\tiny 3};\n  \\draw[fill] (2, 1) circle [radius=0.05];\n  \\draw[dotted] (0,0) -- (2,1) -- (1.7,3);\n  \\draw[dotted] (3.4, 0) -- (2,1);\n\n  \\draw (4, 0) -- (5.7,3) -- (7.4, 0) -- (4, 0) ;\n  \\draw[fill] (5.7, 3) circle [radius=0.05] node[anchor=west] {\\tiny 1};\n  \\draw[fill] (4, 0) circle [radius=0.05] node[anchor=south] {\\tiny 2};\n  \\draw[fill] (7.4, 0) circle [radius=0.05] node[anchor=south] {\\tiny 3};\n  \\draw[fill] (6, 1) circle [radius=0.05];\n\n  \\draw[dotted] (4.6, 1) node[anchor=east] {\\tiny 1,2}\n  -- (6.85,1) node[anchor=west] {\\tiny 1,3};\n  \\draw[dotted] (5.43, 0) node[anchor=north] {\\tiny 3,2}\n  -- (6.425, 1.75) node[anchor=west] {\\tiny 3,1};\n  \\draw[dotted] (6.56, 0) node[anchor=north] {\\tiny 2,3}\n  -- (5.3, 2.2) node[anchor=east] {\\tiny 2,1};\n\n\\end{tikzpicture}\n\\caption{Barycentric coordinates. Left: Area opposite of each vertex.\nRight: Intersection of lines parallel with triangle edges.}\n\\label{fig:bary}\n\\end{figure}\n\nThis text will use barycentric coordinates to express Euclidean triangles.\nBarycentric coordinates are real numbers $\\beta_1, \\beta_2, \\beta_3$ such that\n$\\sum^3_{i=1} \\beta_i = 1$. Given a triangle with vertices $\\mathbf v_1,\n\\mathbf v_2, \\mathbf v_3$, the corresponding vertex is given by $\\mathbf v =\n\\sum^3_{i=1} \\beta_i \\mathbf v_i$. Given $\\mathbf v$ and $\\mathbf v_i$,\n$\\beta_i$ can be found by e.g. solving the linear system of\n$\\beta_1 + \\beta_2 + \\beta_3 = 1$ and $\\mathbf v = \\sum^3_{i=1} \\beta_i \\mathbf\nv_i$. $\\beta_i$ are all positive on the interior of the triangle. If a point\nlies on an edge opposite vertex $i$, then $\\beta_i$ is zero.\n(If it lies beyond the edge, then $\\beta_i < 0$.)\n\nThere are two geometric interpretations of barycentric coordinates that will be\nuseful, as depicted in Figure \\ref{fig:bary}. One is that $\\beta_i$ is the area\nof the smaller triangle opposite $\\mathbf v_i$ divided by the area of the large\ntriangle.\nThe other is that if a line is placed passing through $\\mathbf v$ parallel to\nthe edge opposite vertex $i$, it will be at $\\beta_i$ of the distance between\nthe edge and its opposite vertex, with $\\beta_i = 0$ being on the edge itself.\nLet $\\mathbf v_{i,j}$ be the point where the line for $i$ meets the line between\nvertices $i$ and $j$: then the vertex lies $\\frac{\\beta_{j}}{1-\\beta{i}}$\nof the distance from $\\mathbf v_{i,j}$ to $\\mathbf v_{i,j+1}$. Symbolically,\n$\\mathbf v_{i,j} = \\mathrm{Lerp}(\\mathbf v_{j},\\mathbf v_i;\\beta_{i})$, and\n$\\mathbf v = \\mathrm{Lerp}(\\mathrm{Lerp}(\\mathbf v_{i-1}, \\mathbf v_i;\n\\beta_{i}), \\mathrm{Lerp}(\\mathbf v_{i+1}, \\mathbf v_i; \\beta_{i});\n\\frac{\\beta_{i-1}}{1-\\beta_{i}})$ for all $i$.\n\nGeneralized barycentric coordinates are defined similarly, but the requirement\nthat $\\sum^3_{i=1} \\beta_i = 1$ is dropped. For instance, generalized\nbarycentric coordinates on the unit sphere replace it with a requirement that\n$\\| \\sum^3_{i=1} \\beta_i \\mathbf v_i \\| = 1$. $\\sum^3_{i=1} \\beta_i$ would be\n$>1$ on the interior of the triangle, $=1$ on the edges,\nand $<1$ on the exterior.\n\nQuadrilaterals are instead specified by \\textit{$xy$ coordinates} where\n$x$ and $y$ are $\\in [-1, 1]$. Given a quadrilateral with vertices\n$\\mathbf v_1, \\mathbf v_2, \\mathbf v_3, \\mathbf v_4$, the transformation is:\n\\begin{equation}\\begin{split}\n\\mathbf v & = \\frac{(1-x)(1-y)}{4} \\mathbf v_1 +\n\\frac{(1+x)(1-y)}{4} \\mathbf v_2 +\n\\frac{(1+x)(1+y)}{4} \\mathbf v_3 +\n\\frac{(1-x)(1+y)}{4} \\mathbf v_4 \\\\\n&= \\frac{1}{4} (\\mathbf v_1 +\\mathbf v_2 +\\mathbf v_3 + \\mathbf v_4)\n+\\frac{x}{4}  (-\\mathbf v_1 +\\mathbf v_2 +\\mathbf v_3 - \\mathbf v_4)\n+\\frac{y}{4}  (-\\mathbf v_1 -\\mathbf v_2 +\\mathbf v_3 + \\mathbf v_4)\n+\\frac{x y}{4} (\\mathbf v_1 -\\mathbf v_2 +\\mathbf v_3 - \\mathbf v_4)\n\\end{split}\\end{equation}\nUnlike triangles, quadrilaterals may have points that do not share a common\nplane: they may be skew quadrilaterals. If the quadrilateral is a skew\nquadrilateral, $x$ and $y$ smoothly parameterize a surface over that skew\nquadrilateral. Like barycentric coordinates, these $xy$ coordinates can be\nexpressed in terms of nested linear interpolation:\n\\begin{equation}\\begin{split}\n\\mathbf v\n& = \\mathrm{Lerp}(\\mathrm{Lerp}(\\mathbf v_1,\\mathbf v_2;\\frac{x+1}{2}),\n\\mathrm{Lerp}(\\mathbf v_4,\\mathbf v_3;u);\\frac{y+1}{2}) \\\\\n& = \\mathrm{Lerp}(\\mathrm{Lerp}(\\mathbf v_1,\\mathbf v_4;\\frac{y+1}{2}),\n\\mathrm{Lerp}(\\mathbf v_2,\\mathbf v_3;v);\\frac{x+1}{2})\n\\end{split}\\end{equation}\n\n\\begin{figure}%[!htbp]\n\\begin{tikzpicture}\n  \\draw (0, 0) -- (4, 0) -- (4, 3) -- (1, 4) -- (0, 0);\n  \\draw[fill] (0, 0) circle [radius=0.05] node[anchor=east] {\\tiny 1};\n  \\draw[fill] (4, 0) circle [radius=0.05] node[anchor=west] {\\tiny 2};\n  \\draw[fill] (4, 3) circle [radius=0.05] node[anchor=west] {\\tiny 3};\n  \\draw[fill] (1, 4) circle [radius=0.05] node[anchor=east] {\\tiny 4};\n  \\draw[dotted] (2, 0) -- (2.5, 3.5);\n  \\draw[dotted] (0.5, 2) -- (4, 1.5);\n  \\draw[fill] (2.25, 1.75) circle [radius=0.05];\n\\end{tikzpicture}\n\\caption{$uv$ coordinates on quadrilateral, showing intersection of lines.}\n\\label{fig:uv}\n\\end{figure}\n\n$xy$ coordinates are not amenable to a generalization in exactly the way that\ngeneralized barycentric coordinates are, but some formulas can be expressed like\n\\begin{equation}\n  \\mathbf v = \\sum^4_{i=1} \\alpha_i \\mathbf v_i\n\\end{equation}\nwhere $\\alpha_i$ are not necessarily unique.\n\n\\subsection{Mappings between the hemisphere and the disk}\n\nFor simplicity, we'll use azimuthal maps\\cite{snyder}\n\n\\subsubsection{Azimuthal equal-area}\nPreserves areas\n\\begin{equation}\\begin{split}\n  \\left<x, y\\right> &= \\left<u, v\\right> \\sqrt{\\frac{2}{1-w}} \\\\\n  \\left<u, v, w\\right> &= \\left<\\sqrt{1- \\frac{x^2+y^2}{4}}x,\n    \\sqrt{1- \\frac{x^2+y^2}{4}}y, \\frac{x^2+y^2}{2}-1\\right>\n\\end{split}\\end{equation}\n\n\\subsubsection{Stereographic}\nThis and the following projections are perspective projections: they can be\nunderstood as the view of a sphere from a defined point in space.\nConformal\n\\begin{equation}\\begin{split}\n  \\left<x, y\\right> &= \\frac{\\left<u, v\\right>}{1-w} \\\\\n  \\left<u, v, w\\right> &= \\frac{\\left<2x, 2y, x^2+y^2-1\\right>}{1+x^2+y^2}\n\\end{split}\\end{equation}\n\n\\subsubsection{Gnomonic}\nIn general, the gnomonic projection is defined as:\n\\begin{itemize}\n\\item To sphere: $\\hat{\\mathbf v} = \\frac{\\mathbf p}{\\|\\mathbf p\\|}$\n\\item From sphere: $\\mathbf p = \\frac{r}\n  {\\hat{\\mathbf n} \\cdot \\hat{\\mathbf v}}\\hat{\\mathbf v}$\n\\end{itemize}\nwhere $\\mathbf p$ is a point on a plane given in Hessian normal\nform by $\\hat{\\mathbf n} \\cdot \\mathbf p = r$. Projection from Euclidean\nspace to the sphere is literally just normalizing the vector.\n\n\\subsubsection{Orthographic}\n\\begin{equation}\\begin{split}\n  \\left<x, y\\right> &= \\left<u, v\\right> \\\\\n  \\left<u, v, w\\right> &= \\left<x, y, \\sqrt{1-x^2-y^2}\\right>\n\\end{split}\\end{equation}\n\n\\subsection{Qualities of a mapping}\n\nDesireable qualities in a mapping include:\n\\begin{itemize}\n\\item Homeomorphism: The forward map and inverse map are both continuous.\n\\item Diffeomorphism: The forward map and inverse map are both differentiable.\nIn terms of appearance, smooth lines stay smooth.\n\\item Equal-Area: Relative areas are preserved.\n  Can be measured with the Jacobian determinant.\n\\item Conformal: Small circles are mapped to small circles\n(rather than ellipses or something else). Can be measured with the Jacobian matrix.\n\\item Equidistant: Mappings which preserve (proportional) distances. This isn't\npossible for the entire domain, but can be for certain cases, e.g. along the\nedges of the polygon/disk, or along lines between the vertices and the center.\n\\item Closed-form: Can be expressed in terms of a finite number of defined\nfunctions and operations.\nThis of course depends on which functions are acceptable.\n\\item Simple: How simple or complicated is the formula? This is,\nof course, somewhat subjective.\n\\end{itemize}\n\nThe Jacobian matrix of a mapping $f(x,y) = \\left<f_x(x,y), f_y(x,y)\\right>$\nbetween two subsets of $\\mathbb{R}^2 = \\mathbb{C}$ is a 2x2 matrix of\nderivatives:\n\\begin{equation}\n\\mathbf{J}_f =\n\\begin{bmatrix}\n    \\dfrac{\\partial f_x}{\\partial x} & \\dfrac{\\partial f_x}{\\partial y}\\\\\n    \\dfrac{\\partial f_y}{\\partial x} & \\dfrac{\\partial f_y}{\\partial y}\n\\end{bmatrix}.\n\\end{equation}\n\nThe Jacobian of the inverse map is just the inverse of the Jacobian matrix of the\nforward map, evaluated at the corresponding point: $\\mathbf{J}_{f^{-1}} (z)\n=\\mathbf{J}_{f}^{-1} \\left(f^{-1}(z)\\right)$. The inverse must exist,\nor else the mapping wouldn't be a homeomorphism.\n\nIf this matrix is of the form $\\begin{bmatrix} a & -b\\\\ b & a \\end{bmatrix}$\nfor all arguments, then the mapping is conformal. To measure deviations from\nconformality, define a quantity $\\chi$, the \"unconformality\", as\n\\begin{equation}\n\\chi = \\sqrt{\\left(\\dfrac{\\partial f_x}{\\partial x} -\n\\dfrac{\\partial f_y}{\\partial y}\\right)^2 +\n\\left(\\dfrac{\\partial f_x}{\\partial y} +\n\\dfrac{\\partial f_y}{\\partial x}\\right)^2}\n\\end{equation}\nIf this quantity is zero, the mapping is conformal at that point.\n\nIf the determinant of the Jacobian matrix (the Jacobian determinant) is constant,\nthe map is area-preserving, and it is equal to the ratio of the areas of the\ndomain and the codomain. In fact, the integral of the determinant over the whole\ndomain is equal to that ratio.\n\nFor mappings from $\\mathbb{R}^2$ to the unit sphere $S^2$, use the fact that\nthe composition of conformal mappings is a conformal mapping, and the\ncomposition of equal-area maps is an equal-area mapping. So to measure the\nconformality of a map $\\mathbb{R}^2 \\to S^2$, we instead measure the composition\nof that map with the stereographic projection from $S^2 \\to \\mathbb{R}^2$.\nSimilarly, for equal-area, measure the compisition of the map with the azimuthal\nequal-area projection. Take care to avoid any singularities or boundaries of the\nprojection. (There are more sophisticated differential-geometric methods that\ncould be used here, but this suffices and is easier to understand.)\n\n\\section{Mappings between Euclidean and general spherical polygons}\n\\subsection{Conformal}\nConformal mapping has deep connections to the theory of complex functions.\nThe Schwarz triangle maps conformally transform the upper half-plane to a\ntriangle whose edges are circular arcs. It it given by:\n\\begin{equation}\n   \\varphi(z) = z^{1-c} \\frac{_2 F_1(a',b';c',z)}{_2 F_1(a,b;c,z)}\n\\end{equation}\nwhere $_2 F_1(a,b;c,z)$ is the hypergeometric function and\n\\begin{equation}\\begin{split}\n   a & = \\frac{1 - \\alpha + \\beta - \\gamma}{2}\\\\\n   b & = \\frac{1 - \\alpha - \\beta - \\gamma}{2}\\\\\n   c & = 1 - \\alpha\\\\\n   a' &= \\frac{1 + \\alpha + \\beta - \\gamma}{2} = 1 + a - c\\\\\n   b' &= \\frac{1 + \\alpha - \\beta - \\gamma}{2} = 1 + b - c\\\\\n   c' &= 1 + \\alpha\n\\end{split}\\end{equation}\nand the angles at each vertex of the triangle are $\\pi \\alpha, \\pi \\beta,\n\\pi \\gamma$. If $\\alpha + \\beta + \\gamma < 1$, then the triangle is hyperbolic;\nif $=1$ it is Euclidean, and if $>1$ it is spherical. \\cite{nehari} Hyperbolic\ntriangles seem to be the most investigated cases in the literature, but here the\nother two cases are of interest.\n\nThe Schwarz triangle map maps the boundary of the half-plane (i.e. $\\mathbb{R}$)\nto the boundary of the triangle. The vertices are the points $z=0$, $1$, and\n$\\infty$ on that line. The map takes $z=0$ to $0$, $z=1$ to $\\phi(1) =\n\\frac{\\Gamma(c-a) \\Gamma(c-b) \\Gamma(2-c)}{\\Gamma(1-a) \\Gamma(1-b) \\Gamma(c)}$,\nand $z=\\infty$ to $\\phi(\\infty) = \\exp\\left(i \\pi \\alpha \\right)\n\\frac{\\Gamma(b) \\Gamma(c-a) \\Gamma(2-c)}{\\Gamma(c) \\Gamma(b-c+1) \\Gamma(1-a)}$\nunless $b=0$ (the planar case), then $\\phi(\\infty) = \\exp\\left(i \\pi \\alpha \\right)\n\\frac{\\Gamma(a) \\Gamma(2-c)}{\\Gamma(a-c+1)}$\n\nDenote the stereographic map from the plane to the sphere as $S(z)$. Then a\nconformal mapping between the upper half-plane and a spherical triangle is\ngiven by $S\\left(\\phi(z)\\frac{h}{\\phi(1)}\\right)$, where $h$ is a scaling factor\ngiven by\n\\begin{equation}\n  h = \\sqrt{ -\\frac{\\cos \\left(\\pi (\\alpha+\\beta)\\right)\n                    \\cos\\left(\\pi\\gamma\\right)}\n                   {\\cos \\left(\\pi (\\alpha-\\beta)\\right)\n                    \\cos\\left(\\pi\\gamma\\right)}}\n\\end{equation}\nThe derivation of $h$ can be performed using the spherical law of cosines.\n\nWhat remains is to find a conformal mapping between a Euclidean triangle and the\nhalf-plane. This is also expressed with $\\phi(z)$.\n\\begin{equation}\n  S\\left(\\phi_{\\alpha,\\beta,\\gamma}\n  \\left(\\phi_{\\alpha^*,\\beta^*,\\gamma^*}^{-1}(z)\\right)\n  \\frac{h_{\\alpha,\\beta,\\gamma}}{\\phi(1)_{\\alpha,\\beta,\\gamma}}\\right)\n\\end{equation}\nwhere $\\alpha,\\beta,\\gamma$ denotes the angles of the spherical triangle (over\n$\\pi$), and $\\alpha^*, \\beta^*, \\gamma^*$ denotes the angles of the Euclidean\ntriangle. (One choice to relate the two sets of angles is $\\alpha^* =\n\\frac{\\alpha}{\\alpha+\\beta+\\gamma}$ etc.) The spherical triangle can be\nrotated to the desired position on the sphere with an appropriate Mobius\ntransformation or rotation matrix. (Numerically, it may be helpful to use\nboth to avoid the point at infinity.)\n\nNo closed-form inverse $\\phi^{-1}(z)$ is known to the author, even though in the\nEuclidean case $b=0$ and the denominator of $\\phi(z)$ is 1. The function has\nbranch cuts on $(-\\infty,0]$ and $[1, \\infty)$, and points are transformed to\narbitrarily large values, so care must be taken performing the numerical\ninversion. A Mobius transformation can be used to estimate initial conditions,\nreplacing the triangle with an appropriate disk.\n\n\\subsection{Gnomonic}\nThe gnomonic projection was known to the ancient Greeks, and is the simplest\nof the transformations listed here. It has the nice property that all lines in\nEuclidean space are transformed into great circles on the sphere: that is,\ngeodesics stay geodesics, and polygons stay polygons. This is in fact the\nmotivation for the name ``geodesic dome'': Fuller used this projection to project\ntriangles on the sphere. This is referred to as Method 1 in geodesic dome\nterminology. The main downside is that the transformation causes shapes\nnear the corners to appear bunched up;\nthis is particularly bad for larger faces e.g. on the tetrahedron.\n\nProjection from Euclidean\nspace to the sphere is literally just normalizing the vector. For triangles:\n\\begin{equation}\n   \\mathbf v^* =\n   \\beta_1 \\mathbf v_1 + \\beta_2 \\mathbf v_2 + \\beta_3 \\mathbf v_3\n\\end{equation}\nFor quadrilaterals:\n\\begin{equation}\n   \\mathbf v^* = (1-x)(1-y) \\mathbf v_1 +\n   (1+x)(1-y) \\mathbf v_2 +\n   (1+x)(1+y) \\mathbf v_3 +\n   (1-x)(1+y) \\mathbf v_4\n \\end{equation}\nwhere $\\beta_i$ are (planar) barycentric coordinates and $x,y$ are\n$xy$ coordinates. The factor of $1/4$ is omitted for the quadrilateral\nform because the vector is going to be normalized anyways.\n\nThe triangular case can be thought of in terms of generalized\nbarycentric coordinates. If the generalized coordinates are\n$\\beta^\\prime_i$, then $\\beta^\\prime_i = \\frac{\\beta_1}\n{\\|\\beta_1 \\mathbf v_1 + \\beta_2 \\mathbf v_2 + \\beta_3 \\mathbf v_3\\|}$.\n\n\\subsection{Spherical areal}\nThis method applies to triangles only. Instead we look to the relation between\nbarycentric coordinates and area; we treat $\\beta_i$ as the proportion of\nspherical area in the triangle that is opposite the vertex $\\hat{\\mathbf v}_i$.\nLet $\\Omega$ be the spherical area (solid angle) of the spherical triangle and\n$\\Omega_i = \\beta_i\\Omega$ be the area of the smaller triangle opposite vertex\n$\\hat{\\mathbf v}_i$.\n\nThe formula to find $\\hat{\\mathbf v}$ given $\\beta_i$ more complicated,\nalthough it's also derived from the formula for solid angle given earlier.\n\\begin{equation}\n\\label{eq:sphareal}\n  \\begin{split}\n  \\mathbf G & \\hat{\\mathbf v} = \\mathbf h \\\\\n   \\mathbf G & = \\begin{bmatrix}\n   \\mathbf g_1 & \\mathbf g_2 & \\mathbf g_3 \\end{bmatrix} \\\\\n   \\mathbf h & = \\begin{bmatrix} h_1  & h_2 & h_3  \\end{bmatrix}^T \\\\\n   \\mathbf g_{i} & = \\left(1+\\cos \\Omega_{i}\\right) \\mathbf v_{i-1} \\times\n   \\mathbf v_{i+1} - \\sin\\Omega_{i}\\left(\\mathbf v_{i-1} +\n   \\mathbf v_{i+1}\\right)\\\\\n   h_i &= \\sin\\Omega_i\\left(1+\\mathbf v_{i-1}\\cdot\\mathbf v_{i+1}\\right)\n\\end{split}\\end{equation}\nThe subscripts loop around: 0 should be interpreted as 3, and 4 should be\ninterpreted as 1. To clarify, $\\mathbf G$ is the 3x3 matrix where the $i$th\ncolumn is $\\mathbf g_i$, and $\\mathbf h$ is the column vector where the\n$i$th element is $h_i$. The vector $\\hat{\\mathbf v}$\ncan be solved for using standard matrix methods.\n\n\\subsection{Great Circle}\n\\begin{figure}%[!htbp]\n\\begin{tikzpicture}\n  \\draw (2,2) circle [radius=2];\n\n  \\draw (0.6, 1) to [out=-25, in=205]\n  (3.4, 1) to [out=90, in=-35]\n  (2, 3.5) to [out=215, in=90]\n  (0.6, 1);\n  \\draw[fill] (2, 3.5) circle [radius=0.05] node[anchor=west] {\\tiny 1};\n  \\draw[fill] (0.6, 1) circle [radius=0.05] node[anchor=north] {\\tiny 2};\n  \\draw[fill] (3.4, 1) circle [radius=0.05] node[anchor=north] {\\tiny 3};\n  \\draw[dotted] (0.65, 1.5)  node[anchor=east] {\\tiny 1,2}\n  to [out=-15, in=195] (3.35, 1.5) node[anchor=west] {\\tiny 1,3};\n\n  \\draw[dotted] (1.8, 0.65) node[anchor=north] {\\tiny 3,2}\n  to [out=45, in=265] (2.9, 2.7) node[anchor=west] {\\tiny 3,1};\n  \\draw[dotted] (1.6, 3.1) node[anchor=east] {\\tiny 2,1}\n  to [out=-45, in=105] (2.9, 0.8) node[anchor=north] {\\tiny 2,3};\n\\end{tikzpicture}\n\\caption{Intersection of great circle arcs inside a spherical triangle,\nand the small spherical triangle formed by the arcs. Exaggerated so that the\nsmall triangle is visible; not to scale.}\n\\label{fig:intlines}\n\\end{figure}\nThis is Method 2 in geodesic dome terminology. Recall in our earlier discussion\nof barycentric coordinates that on a plane triangle, we can draw a line\ncorresponding to each $\\beta_i$, and those three lines meet at a point. On the\nsphere, if we make the same construction, the lines do not meet at a point\n(except on the edges), but instead intersect to form a small spherical\ntriangle. Take a point within that triangle as $\\mathbf v$.\nTypically the centroid is used, as it's easy to calculate,\nalthough we'll discuss another variation.\n\n(If there were any ambiguities, we used the program \\texttt{geodesic}\nfrom Antiprism\\cite{antiprism} as a reference implementation.)\n\nIn analytic terms, use Slerp to determine the points on each triangle edge.\nTake the cross product of the opposing pairs of points to determine the normal\nto the intersecting plane corresponding to each line. Take the cross product of\neach pair of normals to find a vector proportional to the point of\nintersection. (As the cross product is antisymmetric, be careful about order\nhere.) Then normalize each vector and take their centroid.\n\nIn terms of equations, Method 2 or the Great Circle Intersection\nmethod on a triangle is:\n\\begin{equation}\\begin{split}%??? does this reduce to slerp on the edges?\n\\mathbf v^* & = \\sum^3_{i=1} \\frac{\\mathbf h_i \\times \\mathbf h_{i+1}}\n{\\|\\mathbf h_i \\times \\mathbf h_{i+1}\\|} \\\\\n\\mathbf h_i & =\n\\mathrm{Slerp}(\\mathbf v_{i-1}, \\mathbf v_i; \\beta_{i})\n\\times\n\\mathrm{Slerp}(\\mathbf v_{i+1}, \\mathbf v_i; \\beta_{i})\n\\end{split}\\end{equation}\n\nThe above equation can be tweaked slightly by removing the step of normalizing\nthe vectors at the points of intersection. This still produces a point within\nthe triangle. This formula is a little more computationally efficient and\neasier to treat algebraically. Where $\\mathbf h_i$ is as before:\n\\begin{equation}\\label{eq:gct}%??? does this reduce to slerp on the edges?\n\\mathbf v^* = \\sum^3_{i=1} \\mathbf h_i \\times \\mathbf h_{i+1} \\\\\n\\end{equation}\n\nThis method can be extended to the Quadrilateral. Use Slerp to find points on\nopposing sides of the quadrilateral, use the cross product to find their\nnormal, and then use the cross product to find the point of intersection. Since\nwe draw two intersecting lines, there is only one point of intersection within\nthe quadrilateral. The formula is:\n\\begin{equation}\\label{eq:gcq}%??? does this reduce to slerp on the edges?\n\\mathbf v^* =\n(\\mathrm{Slerp}(\\mathbf v_1, \\mathbf v_2; \\frac{x+1}{2})\n\\times\n\\mathrm{Slerp}(\\mathbf v_4, \\mathbf v_3; \\frac{y+1}{2}))\n\\times\n(\\mathrm{Slerp}(\\mathbf v_1, \\mathbf v_4; \\frac{y+1}{2})\n\\times\n\\mathrm{Slerp}(\\mathbf v_2, \\mathbf v_3; \\frac{x+1}{2}))\n\\end{equation}\n\n\\subsection{Nested Slerp}\nThis is similar to the Great Circle method, except instead of using the great\ncircles to calculate the intersections of the lines, we use another spherical\nlinear interpolation to get a point near the intersection. We effectively use\nthe Lerp formulas from the section on coordinates, substituting Slerp for Lerp.\nUnlike Lerp, Slerp does not commute, so we take the different permutations of\nthe arguments and combine the different points that result.\n\nTriangular:\n\\begin{equation}\\label{eq:nst}\n\\mathbf v^* = \\sum^3_{i=3} \\mathrm{Slerp}(\n\\mathrm{Slerp}(\\mathbf v_{i-1}, \\mathbf v_i; \\beta_{i}),\n\\mathrm{Slerp}(\\mathbf v_{i+1}, \\mathbf v_i; \\beta_{i});\n\\frac{\\beta_{i-1}}{1-\\beta{i}})\n\\end{equation}\nQuadrilateral:%??? not symmetric?\n\\begin{equation}\\label{eq:nsq}\n  \\begin{split}\n\\mathbf v^* =& \\mathrm{Slerp}(\n\\mathrm{Slerp}(\\mathbf v_1, \\mathbf v_2; \\frac{x+1}{2}),\n\\mathrm{Slerp}(\\mathbf v_4, \\mathbf v_3; \\frac{x+1}{2}); \\frac{y+1}{2})\\\\\n&+ \\mathrm{Slerp}(\n\\mathrm{Slerp}(\\mathbf v_1, \\mathbf v_4; \\frac{y+1}{2}),\n\\mathrm{Slerp}(\\mathbf v_2, \\mathbf v_3; \\frac{y+1}{2}); \\frac{x+1}{2})\n\\end{split}\n\\end{equation}\n\n\\subsection{Naive Slerp}\nThe previously mentioned mappings are all somewhat complicated. Expansion of the\nformulas results in very lengthy equations. Applying a simplifying restriction\nallows us to produce a formula that is nearly as simple as the gnomonic mapping.\nThe restriction is that the polygons are equilateral. This may seem very\nrestrictive, but many of the applications of these mappings involve a regular\npolyhedron, e.g. the cube or the icosahedron, with equilateral faces.\n\nThe Naive Slerp method resembles a naive extension of spherical linear\ninterpolation (Slerp) to barycentric or $uv$ coordinates, thus the\nname. Let $\\cos(w) = \\mathbf v_i \\cdot \\mathbf v_{i+1}$ for all $i$. (As\nusual, the subscripts loop around.) For triangles:\n\\begin{equation}\n   \\mathbf v^* = \\sum_{i=1}^3\\frac{\\sin(w\\beta_i)}{\\sin(w)}  \\mathbf v_i\n\\end{equation}\nFor quadrilaterals:\n\\begin{equation}\\begin{split}\n     \\mathbf v^* & = \\sum_{i=1}^4\\frac{\\sin(w\\gamma_i)}{\\sin(w)} \\mathbf v_i \\\\\n\\gamma_1 & = \\frac{(1-x)(1-y)}{4} \\\\\n\\gamma_2 & = \\frac{(1+x)(1-y)}{4} \\\\\n\\gamma_3 & = \\frac{(1+x)(1+y)}{4} \\\\\n\\gamma_4 & = \\frac{(1-x)(1+y)}{4}\n\\end{split}\\end{equation}\nor\n\\begin{equation}\\begin{split}\n   \\mathbf v^* & = \\sum_{i=1}^4\\frac{s_i}{\\sin^2(w)}  \\mathbf v_i \\\\\ns_1 & = \\sin \\left(w\\frac{1-x}{2}\\right)\\sin \\left(w\\frac{1-y}{2}\\right) \\\\\ns_2 & = \\sin \\left(w\\frac{1+x}{2}\\right)\\sin \\left(w\\frac{1-y}{2}\\right) \\\\\ns_3 & = \\sin \\left(w\\frac{1+x}{2}\\right)\\sin \\left(w\\frac{1+y}{2}\\right) \\\\\ns_4 & = \\sin \\left(w\\frac{1-x}{2}\\right)\\sin \\left(w\\frac{1+y}{2}\\right)\n\\end{split}\\end{equation}\n\n\\subsection{Projection of $\\mathbf v^*$}\nThe nested slerp and naive slerp methods produce values that are normalized\nalong the edges. Because the projected edges already lie on the sphere, we have\nfreedom in how to adjust $\\mathbf v^*$ to lie on the sphere. The easiest is\njust to centrally project the vertices, that is, to normalize $\\mathbf v^*$\nlike we have been. Another option is to perform a parallel projection along the\nface normal, as defined earlier. We need the parallel distance $p$ from the\nvertex to the sphere surface in the direction of the face normal\n$\\hat{\\mathbf n}$, such that $\\hat{\\mathbf v} =\n\\mathbf v^* + p\\hat{\\mathbf n}$. $p$ is given by:\n\\begin{equation}\n   p = -\\mathbf v^* \\cdot \\hat{\\mathbf n} +\n   \\sqrt{1+\\mathbf v^* \\cdot \\hat{\\mathbf n}-\\mathbf v^* \\cdot \\mathbf v^*}\n\\end{equation}\n$p$ can also be approximated as $\\widetilde{p} = 1 - \\|\\mathbf v^*\\|\n\\leq p$, which is fewer operations and doesn't require\ncalculation of the face normal. Technically, you can project in almost any\ndirection, not just that of the face normal, but most other choices don't\nproduce a symmetric result.\n\nSometimes the best mapping comes from a compromise of the central and\nparallel projections. Choose a constant $k$, typically between 0 and 1, then:\n\\begin{equation}\n  \\hat{\\mathbf v} = \\frac{\\mathbf v^* + kp\\mathbf c}{\\|\\dots\\|}\n\\end{equation}\n$p$ may be replaced by $\\widetilde{p}$. If our goal is to optimize a\nmeasurement of the mapping, we can do a 1-variable optimization on $k$.\n\n\\section{Mappings between Euclidean and particular spherical rectangles}\n\n\\subsection{Nowell's cube mapping}\nOne mapping between the filled cube $[-1,1]^3$ and the filled sphere\n$\\mathbf{v} \\le 1$ is given by\n\\cite{nowellcu}\n\\begin{equation}\\begin{split}\nu &= x \\sqrt{1 - \\frac{y^2}{2}-\\frac{z^2}{2}+\\frac{y^2 z^2}{3}} \\\\\nv &= y \\sqrt{1 - \\frac{z^2}{2}-\\frac{x^2}{2}+\\frac{z^2 x^2}{3}} \\\\\nw &= z \\sqrt{1 - \\frac{x^2}{2}-\\frac{y^2}{2}+\\frac{x^2 y^2}{3}}\n\\end{split}\\end{equation}\nThis can be considered a map between a square face of the cube and a spherical\nsquare of area $\\frac{2 \\pi}{3}$ if one of the $x,y,z$ coordinates is held\nconstant at $\\pm 1$.\n\n\\subsection{Naive Slerp to a spherical rectangle}\nLet the target rectangle be defined by the points $(-a,-b,c), (a,-b,c), (a,b,c),\n(-a,b,c)$ where $a, b, c$ are in $[0,1]$ and $a^2 + b^2 + c^2 = 1$. The\nspherical center of this rectangle, and the face normal, is $(0,0,1)$. The naive\nslerp method from the standard square to this rectangle is expressible as so:\n\\begin{equation}\n  u^* &= \\frac{\\sin(\\frac{w_x}{2}x) \\cos(\\frac{w_y}{2}y) }\n    {\\sqrt{1-b^2}}\\\\\n  v^* &= \\frac{\\cos(\\frac{w_x}{2}x) \\sin(\\frac{w_y}{2}y) }\n    {\\sqrt{1-a^2}}\\\\\n  w^* &=c \\frac{\\cos(\\frac{w_x}{2}x) \\cos(\\frac{w_y}{2}y) }\n    {\\sqrt{1-a^2}\\sqrt{1-b^2}}\n\\end{equation}\nwhere $cos(w_x) = 1 - 2 a^2$ and $cos(w_y) = 1 - 2 b^2$.\n\nIn the case when $c=0$,\nand the spherical rectangle takes up an entire hemisphere, the formula further\nreduces to:\n\\begin{equation}\n  u^* &= \\frac{\\sin(\\frac{w_x}{2}x) \\cos(\\frac{w_y}{2}y) }\n    {a}\\\\\n  v^* &= \\frac{\\cos(\\frac{w_x}{2}x) \\sin(\\frac{w_y}{2}y) }\n    {b}\\\\\n  w^* &=0\n\\end{equation}\n\nIn the limit where $c=0$ and $b = 0$,\n\\begin{equation}\n  u^* &= \\sin(\\frac{\\pi}{2}x) \\\\\n  v^* &= y \\cos(\\frac{\\pi}{2}x) \\\\\n  w^* &= 0\n\\end{equation}\n\n\\subsection{Elliptical mapping to a spherical rectangle}\n$\\sin(k x)$ may be approximated as $\\sin(k)x$, where the two expressions are\nequal at $x=-1,0,1$. Similarly, $\\cos(k x)$ may be approximated as\n$\\sqrt{1 - \\sin^2(k) x^2}$. This approximation was applied in \\cite{reynolds} to\nproduce an approximate equal-area mapping, as it maintains the boundary of the\nshape where $x=\\pm1$ or $y=\\pm1$. Applying this approximation to the equation\nfor naive slerp on a spherical rectangle yields:\n\n\\begin{equation}\n  u^* &= ax \\frac{\\sqrt{1-b^2 y^2} }\n    {\\sqrt{1-b^2}}\\\\\n  v^* &= by \\frac{\\sqrt{1-a^2 x^2} }\n    {\\sqrt{1-a^2}}\\\\\n  w^* &=c \\frac{\\sqrt{1-a^2 x^2}\\sqrt{1-b^2 y^2} }\n    {\\sqrt{1-a^2}\\sqrt{1-b^2}}\n\\end{equation}\n\nIn the case when $c=0$, and the spherical rectangle takes up an entire\nhemisphere, the formula reduces to:\n\\begin{equation}\n  u^* &= x \\sqrt{1-b^2 y^2} \\\\\n  v^* &= y \\sqrt{1-a^2 x^2} \\\\\n  w^* &=0\n\\end{equation}\n\nWhen $a=b=\\frac{1}{\\sqrt{2}}$, this is the elliptical mapping from the square\nto the disk.\\cite{nowellsq}\\cite{fong17} Furthermore, when $c=b=0$,\n\\begin{equation}\n  u^* &= x  \\\\\n  v^* &= y \\sqrt{1 - x^2} \\\\\n  w^* &=0\n\\end{equation}\nwhich is the squelch mapping from the square to the disk in \\cite{fong17}.\n\n\\section{Qualities of mappings}\nJacobians, etc.\nTissot indicatrices?\n\n\\section{Applications}\n\\subsection{Cartographic use}\n\n\\subsection{Optimization of geodesic polyhedra}\n\n\\bibliographystyle{plain}\n\\bibliography{references}\n\n\\end{document}\n", "meta": {"hexsha": "a458c4545bd26ab9d353dce0757eefbd8c9bfd32", "size": 36568, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/euclidian_spherical_maps.tex", "max_stars_repo_name": "ye-man/antitile", "max_stars_repo_head_hexsha": "0cbccd8c7a43c50618cc223d45e915738b5943fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-06-03T07:28:10.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-15T10:16:56.000Z", "max_issues_repo_path": "docs/euclidian_spherical_maps.tex", "max_issues_repo_name": "ye-man/antitile", "max_issues_repo_head_hexsha": "0cbccd8c7a43c50618cc223d45e915738b5943fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/euclidian_spherical_maps.tex", "max_forks_repo_name": "ye-man/antitile", "max_forks_repo_head_hexsha": "0cbccd8c7a43c50618cc223d45e915738b5943fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-06-03T07:28:19.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-03T07:28:19.000Z", "avg_line_length": 46.4060913706, "max_line_length": 83, "alphanum_fraction": 0.7030463793, "num_tokens": 12116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.30013776264555886}}
{"text": "\\chapter{Summary}\n\nRecent advances in machine learning, neural network software frameworks, and \\ac{GPU} computing capacity have made it possible to design and teach very deep neural networks. \\acfp{CNN} have been long used for image processing, and lately, it has been shown that they can be adapted to human face detection and extraction of relevant low-dimensional facial data. An extension of a \\ac{CNN}, the \\acf{FCNN}, has been recently shown to be capable of doing dense pixel-to-pixel mappings. This mapping has been used, for example, to do dense semantic segmentations of images. To train \\acp{FCNN} in a supervised way, a large number of annotated input/output image pairs are needed. Nowadays, because of abundant processing and storage capacity in computing clusters, it is feasible to generate these kinds of input/output image pairs synthetically using rendering software. Also, data augmentation has been shown to expand the effective size of even small training datasets successfully.\n\nBecause the \\ac{FCNN} is an extension to the \\ac{CNN}, it is possible to train the former to do dense mapping of human faces. The downscaling part of the \\ac{FCNN} first detects the relevant features of the face and compresses them down to a lower dimensional presentation. The upscaling part of the \\ac{FCNN} then uses the representation to generate a segmentation and a dense mapping of the human face. One problem is to find a dense mapping that would represent the geometry of the face and that could be taught to a neural network. Another problem is to find training data of real-world images with the aforementioned mapping. Creating the mappings by hand would be very time-consuming as at least tens of thousands of training samples would be needed. On the contrary, generating a training dataset like this by rendering would be easy, as access to exact underlying geometry is available.\n\nThe main research goal of the thesis was to explore whether it is possible to train an \\ac{FCNN} using non-realistic synthetic data to do dense facial geometry tracking of real-world human faces. Subgoals included designing a method to generate the training data, making the network inpaint geometry under occlusions, making the network temporally stable when applied to video, and designing visualization methods for the generated mappings to ease the evaluation of the results.\n\nTo generate the synthetic training dataset, we used Blender to render 100 000 training samples of a randomized head mesh. One sample included an input image, a UV image, and a mask image. The input image had realistic backgrounds but non-realistic face materials. We decided to use the underlying UV mapping of the head model to render the UV image, which then represented the geometry mapping in our method. The mask image was used to segment the frontal face area out of the input image.\n\nWe based the design of our \\ac{FCNN} on the U-net network topology. Seven levels were used and skip connections were added between all corresponding down and upsampling parts. Convolution feature map sizes, convolution filter sizes, and activation functions were slightly adjusted to optimize results. In the end, as a loss function, we used a simple sum of L1 losses between UV, UV gradient and mask images. UV image gradients were used to speed converge and enforce the smoothness of the resulting UV mapping.\n\nData augmentation was implemented by applying the following to the input image: rotations, color channels shuffles, exposure and gamma changes, Gaussian noise, and texture based occlusions. Augmentation generated one additional mask image, the occluded mask, which was used in the loss function to aid occlusion detection.\n\nTo visualize the generated geometry mappings, we implemented four different visualizations: texture projection, inverse texture projection, grid lines projection, and grid points projection. These projections were used to assess the accuracy and stability of the geometry mapping, both in static images and in videos. In addition, we created a custom browser-based results evaluation page that used these visualization images and other illustrations to help assess the performance of the network.\n\nWhen given real-world human faces, our final \\ac{FCNN} was successful in doing the segmentation and geometry mapping, even though it had been trained on non-realistic synthetic data. The segmenting was, in most cases, good with sharp edges and geometry mapping worked well with non-extreme input images. Our data augmentation strategy successfully expanded the training dataset and prevented the network from overfitting. The occlusion augmentation method also enabled the network to inpaint geometry under obstructions that had not been in the training material, e.g., sunglasses or facial hair. When applied to a video, the temporal stability of the generated geometry was not bad but could be improved. Inpainted geometry was, most of the time, somewhat distorted and not temporally stable.\n\nFuture work could include 3D mesh generation from the UV mapping using, for example, morphable models and synthesis-by-analysis. Instead of doing a 2D-to-2D mapping and then 3D mesh reconstruction, it should be possible to train an \\ac{FCNN} to do straight 2D-to-3D volumetric mapping. The temporal stability of the generated geometry was not perfect, especially under occlusions, and could be improved.\n", "meta": {"hexsha": "7e9eb6ef703e062fcbcae99a2bc7938dfc6f63b1", "size": 5405, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/parts/7summary.tex", "max_stars_repo_name": "mikoro/master-thesis", "max_stars_repo_head_hexsha": "5af27c5e4186938b6f192a839f4d19370e21f917", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tex/parts/7summary.tex", "max_issues_repo_name": "mikoro/master-thesis", "max_issues_repo_head_hexsha": "5af27c5e4186938b6f192a839f4d19370e21f917", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/parts/7summary.tex", "max_forks_repo_name": "mikoro/master-thesis", "max_forks_repo_head_hexsha": "5af27c5e4186938b6f192a839f4d19370e21f917", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 270.25, "max_line_length": 982, "alphanum_fraction": 0.8142460685, "num_tokens": 1066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3000941796301025}}
{"text": "\\section{Recurrent Neural Networks}\n\\label{sec:rnn}\nRecurrent Neural Networks (RNNs) are one of the most commonly used typology of neural networks~\\cite{lecun2015deep}. In recent years, thanks to advancements in their architecture~\\cite{hochreiter1997long,chung2014empirical} and in computational power, they have become the standard to effectively model sequential data. They have been used successfully for tasks such as sentiment analysis~\\cite{tang2015document}, speech recognition~\\cite{graves2013speech}, image captioning~\\cite{karpathy2015deep}, predicting tourist paths~\\cite{palumbo2017predicting} and neural language models~\\cite{mikolov2010recurrent}. One of the typical applications of RNNs is language modeling, i.e. the task of learning a probabilistic model of text in order to generate new text by recursively predicting the next word in a sentence~\\cite{sutskever2011generating}. We use RNNs, more specifically Long-Short Term Memory (LSTM) cells~\\cite{hochreiter1997long}, in a similar vein to the language modeling problem, i.e. training the network to predict the next track in a playlist and sampling tracks from the learned probability model to generate predictions. In practice, rather than using only the track as input, we use a richer representation that also exploits the artist, the album, the title and, possibly, lyrics features (Figure~\\ref{fig:global_architecture}). \n\nIn the following sections, we describe in detail the input features as well as the generation strategy.\n\n\\begin{figure*}\n    \\centering\n    \\includegraphics[width=0.7\\textwidth, height=0.35\\textwidth]{figures/rnn.pdf}\n    \\caption{RNN architecture for playlist completion. The input vectors include word2vec embeddings for the track, the album, and the artist, a fastText embedding for the playlist title and numerous features extracted from the lyrics.}\n    \\label{fig:global_architecture}\n\\end{figure*}\n\n\\subsection{Input Vectors}\n\n\\subsubsection{Track, Album and Artist Embeddings}\n\\label{sec:track_embs}\nIn order to leverage the information in the dataset concerning tracks, artists and albums, we opt for an approach based on word2vec~\\cite{mikolov2013distributed} embeddings. More precisely, we train the word2vec model separately on sequences of tracks, albums and artists in the order of appearance in the playlist, obtaining three separated word2vec models encoding co-occurrence patterns of tracks, albums and artists respectively. Each word2vec model is based on the Skip-gram model with negative sampling using default hyper-parameters of the Gensim implementation~\\cite{rehurek_lrec}: embedding vector dimension is $d=100$, learning rate $\\alpha = 0.025$ linearly decaying up to $min_{\\alpha} = 0.0001$, window size $c = 5$, number of epochs is $\\eta = 5$.\n\nWe concatenate the three representations of the tracks, albums and artists, obtaining an input vector $x_{w2v}$ whose dimensionality is $|x_{w2v}| = 300$.\n\n\\subsubsection{Titles Embeddings}\n\\label{sec:title_embs}\nThe title of a playlist can potentially contain interesting information about the intention and the purpose of its creator. The title can suggest that the tracks in certain playlist are intended to suit a certain goal (e.g. \\textit{party}, \\textit{workout}), a mood (\\textit{sad songs}, \\textit{relaxing}), a genre (\\textit{country}, \\textit{reggae}), or a topic (\\textit{90's}, \\textit{Christmas}). Our intuition, supported by the experiments described later in this section, is that playlists with similar titles may contain similar tracks.\nThe title similarity could rely on pre-trained models and thesauri. However, we opted for computing a model that is specific for the playlist continuation task, using the sole data of the MPD.\n\nA playlist embedding $p_{w2v}$ is computed as the mean of the embeddings of the tracks composing the playlist, already generated in Section \\ref{sec:track_embs}. The playlist embeddings are then grouped in $n$ clusters, applying the K-means algorithm.\n\nWe empirically observed that, apart from very general clusters, we also created clusters containing specialized playlists, obtaining as a consequence groups of titles that belong to the same semantic area. For example, a cluster contains playlists like \\textit{Christmas feels}, \\textit{December} or with titles including the emoji of Santa Claus, while another group encompasses playlists like \\textit{country} and \\textit{Alabama}.\n\nEach cluster $c$ expresses a composed label, which is the concatenation of the titles of all the playlist $p \\in c$ separated by a blank space. These labels can be seen as a corpus of $n$ documents (one for each cluster) that is used as input for the fastText algorithm~\\cite{joulin2016fasttext}. Because this algorithm is able to represent textual information at the level of n-grams from 3 to 6 character, the Title2Rec model in output computes the embeddings of any playlist title, being this already seen in the dataset or totally unknown. Figure~\\ref{fig:t2r_pipeline} illustrates the process of the Title2Rec model generation.\n\n% source: https://docs.google.com/presentation/d/1KV4eFuYvFxS1Z25ZwOqu5TJ2zuBbeRAZAkR2Hbf8h_A/edit#slide=id.g3d7920112c_0_0\n\\begin{figure*}\n    \\centering\n    \\includegraphics[width=0.85\\textwidth]{figures/t2r.pdf}\n    \\caption{Pipeline for generating the title embedding model used in Title2Rec. The embeddings are computed through a fastText model trained on a corpus of concatenated titles of similar playlists.}\n    \\label{fig:t2r_pipeline}\n\\end{figure*}\n\n\\subsubsection{Lyrics Embeddings}\n\\label{sec:lyrics}\nSince playlists contain tracks that share semantic properties (such as the genre) and acoustic properties (such as the mood), we hypothesize their lyrics share features as well. To this end, we extract numerous features from the lyrics for a large set of tracks used in the MPD dataset ($v \\in \\mathbb{R}^{n}$) that describe different stylistic and linguistic dimensions of a song text:\n\\begin{itemize}\n  \\item \\textit{vocabulary} ($v \\in \\mathbb{R}$): as a measure of the vocabulary richness, we compute the type-token ratio of a song text.\n  \\item \\textit{style} ($v \\in \\mathbb{R}^{27}$): to estimate the linguistic style of a song text, we measure the line lengths (in characters and in tokens) and the frequencies of all major part-of-speech tags. We further count rhyme occurrences and \\qu{echoisms} (sung words like \\qu{laaalala} and \\qu{yeeeeeeeaaaaaaah}).\n  \\item \\textit{semantics} ($v \\in \\mathbb{R}^{60}$): we build a topic model with 60 topics on the song text bag of words using Latent Dirichlet Allocation~\\cite{LDA}. Each song text is then represented by its association to these topics.\n  \\item \\textit{orientation} ($v \\in \\mathbb{R}^{3}$): this dimension models how the song narrative (entities, events) is oriented with respect to the world. We encode a temporal dimension, i.e. whether the song mainly recounts past experiences or present/future ones, by representing the fraction of past tense verb forms to all verb forms as a feature.\n  \\item \\textit{emotion} ($v \\in \\mathbb{R}^{6}$): we model the subjectivity (subjective vs. objective) as well as the polarity (positive vs. negative) of the song text. Furthermore, the emotions conveyed are modelled in a common two-dimensional model that accounts for degrees of arousal and valence.\n  \\item \\textit{song structure} ($v \\in \\mathbb{R}^{4}$): as a proxy of the structure of the lyrics, we use the line lengths as well as the lengths of paragraphs in the song text.\n\\end{itemize}\n\nFor experimental purposes, we grouped the previous features in two additional categories:\n\\begin{itemize}\n    \\item \\textit{deterministic} ($v \\in \\mathbb{R}^{23}$): it encompasses all features generated in a deterministic way such as features related to the structure, the vocabulary, and the style of the lyrics. We excluded from this group the frequencies of part-of-speech tags, as they depend on the tagger used.\n    \\item \\textit{fuzzy} ($v \\in \\mathbb{R}^{18}$): it includes the features generated in a non-deterministic fashion such as orientation, emotion, and the frequencies of part-of-speech tags.\n\\end{itemize}\n\nAll features are scaled using a custom feature scaler that combines two elements: i) account for outliers by scaling the data non-linearly based on the percentile of the feature value distribution they belong to; ii) scale the data linearly to the same $[-1,1]$ interval that non-lyrics features live in.\n\nRetrieving lyrics for the MPD dataset is achieved by linking it to the WASABI corpus~\\cite{meseguerbrocal:hal-01589250}.\\footnote{\\url{https://wasabi.i3s.unice.fr}} The WASABI corpus is an ongoing resource that contains 2.1M song texts (of 77k artists), and for each song it provides the following information: the lyrics extracted from \\url{http://lyrics.wikia.com}, the synchronized lyrics (when available) from \\url{http://usdb.animux.de}, DBpedia abstracts and categories the song belongs to, genre, label, writer, release date, awards, producers, artist and/or band members, the stereo audio track from Deezer (when available), the unmixed audio tracks of the song, its ISRC, BPM, and duration. In total, we linked 416k tracks in MPD (out of 2.2M unique tracks) to WASABI tracks that contain the lyrics. While the linked tracks proportion with $\\sim$20\\% seems small, the linked tracks cover 53\\% of all 66M track occurrences in MPD because of the typical fat-tailed distribution, where some songs are extremely common while most titles occur only rarely in a playlist. Linking the lyrics was done in three levels of accuracy: direct Spotify URI matching gave us 155k links, exact artist and title matching provided 334k matches, and finally lower casing and deleting bracketed content (in song titles only) led to 51k matches. As the results overlap we ended up with 416k matched tracks in total. Some of our lyrics features are language-specific, so we decided to compute lyrics features exclusively on English song texts. This finally resulted in 367k English song texts we computed lyrical features on. Language detection is done with the \\textit{langdetect} package\\footnote{\\url{https://github.com/Mimino666/langdetect}} and datasets of MPD and WASABI are merged along the axes of their Spotify URIs, artist names, song title names, respectively.\n\n\\subsection{Learning Model}\nAs mentioned earlier, we address the problem of playlist continuation as a language modeling problem. More specifically, we train the RNN to predict the next track in a playlist, defining the targets $Y$ to be the inputs $X$ shifted in time, i.e. $X = \\{(\\hat{T{^j}}_0, \\hat{T{^j}}_1, \\dots, \\hat{T^{j}}_{N_j -1})\\}$ and $Y = \\{(T{^j}_1, T{^j}_2, \\dots, T^{j}_{N_j})\\}$ where $\\hat{T}$ represents a track and its metadata (artist, album, playlist title, lyrics features), $T$ represents a track id in a playlist, $j = 1, \\dots, M$ is a playlist index and $N_j$ is the length of the j-\\textit{th} playlist. In this way, we train the model to learn a probability distribution of the next track $P (T_N | \\hat{T}_{N-1}, \\hat{T}_{N-2}, \\dots, \\hat{T}_{0})$ given the previous ones, which is parametrized by the network outputs that are converted into probabilities by the final softmax layer (Figure~\\ref{fig:global_architecture}). The training algorithm attempts to minimize the cross-entropy loss function $L$, that measures the disagreement between the learned probability model and the observed probability model of the targets $Y$. The perplexity metric that is reported in the experiments (Section~\\ref{sec:rnn-opt}) corresponds to $ppl = 2^{L}$. In practice, rather than using probabilities, we use the `logits' $p_i$ where $i$ is a track index, un-normalized scores that are proportional to the probabilities. Different optimization algorithms to minimize the loss are empirically compared (Section~\\ref{sec:rnn-opt}).\n\n\\subsection{Generating predictions}\n\\label{sec:generation}\nWe experiment three different strategies to generate track predictions from the RNN. Given an input seed and the hidden state, the trained model outputs the logits $p_i$, i.e. un-normalized scores that are proportional to the probability that a given track appears after the sequence of seeds $s$. In details, we considered the following approaches, as depicted in Figure~\\ref{fig:predictions}.\n\\begin{description}\n    \\item[do\\_sample] It samples the track with the highest logit $p_i$, where $\\hat{i} = arg\\ max ({p_i})$, given the set of seeds $s$. It adds the sampled track $\\hat{i}$ to the seeds $s$, then it repeats the previous operations until 500 tracks are sampled.\n    \\item[do\\_rank] It ranks the tracks according to their logit value $p_i$, given all the seeds $s$, then it selects the top-500 tracks with the highest logit.\n    \\item[do\\_summed\\_rank] It computes the logits $p_i$ for every seed. It averages all the logits in the sequence obtaining $\\hat{p_i}$ and then it ranks the tracks according to the values of $\\hat{p_i}$.\n\\end{description}\n\n\\begin{figure}\n\t\\centering\n\t\\begin{subfigure}{0.4\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{figures/sample.pdf}\n\t\t\\caption{do\\_sample}\n\t\\end{subfigure}\n\t\\begin{subfigure}{0.4\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{figures/rank.pdf}\n\t\t\\caption{do\\_rank}\n\t\\end{subfigure}\n\t\\begin{subfigure}{0.4\\textwidth}\n\t\t\\includegraphics[width=\\textwidth]{figures/summed.pdf}\n\t\t\\caption{do\\_summed\\_rank}\n\t\\end{subfigure}\n\t\\caption{Three strategies for generating track predictions.}\n\t\\label{fig:predictions}\n\\end{figure}\n", "meta": {"hexsha": "6c45741717b1b7eec0715e642e40e568b47454c9", "size": 13500, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/sections/rnn.tex", "max_stars_repo_name": "D2KLab/recsys18_challenge", "max_stars_repo_head_hexsha": "5cd47d1b9df2a2bccad2889ba1d570d5a8dd0f8d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-11-09T14:04:04.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-29T15:56:45.000Z", "max_issues_repo_path": "paper/sections/rnn.tex", "max_issues_repo_name": "D2KLab/recsys18_challenge", "max_issues_repo_head_hexsha": "5cd47d1b9df2a2bccad2889ba1d570d5a8dd0f8d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paper/sections/rnn.tex", "max_forks_repo_name": "D2KLab/recsys18_challenge", "max_forks_repo_head_hexsha": "5cd47d1b9df2a2bccad2889ba1d570d5a8dd0f8d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-12-11T03:03:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T20:09:29.000Z", "avg_line_length": 146.7391304348, "max_line_length": 1857, "alphanum_fraction": 0.7804444444, "num_tokens": 3366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.3000243859514274}}
{"text": "% !TEX root = ./Basilisk-sunSafePoint-20180427.tex\n\n\n\\section{Module Functions}\n\\begin{itemize}\n\t\\item \\textbf{Compute the attitude tracking error}: Determines the shortest rotation to align $\\bm s$ and $\\hat{\\bm s}_{c}$, and computes the corresponding three-dimensional attitude difference\n\t\\item \\textbf{Control spacecraft rotation}: The reference frame is assumed to be non-accelerating and either zero (default) or a constant spin about the sun heading axis.\n\t\n\t\\item \\textbf{Robust to no sun heading information}: If the sun heading vector is not available, then the attitude feedback is turned off by zeroing $\\bm\\sigma_{B/R}$.  Instead of driving the body rates to zero, the body rates are driven to a prescribed $\\bm\\omega_{R/N}$ vector.  This allow the spacecraft to search for the sun and covers the case if some sun sensors are offline.  \n\t\n\t\\item \\textbf{Robust to collinear observation vector}:  The module must handle the cases where the commanded body relative vector and the sun direction vectors are nearly collinear. \n\\end{itemize}\n\n\\section{Module Assumptions and Limitations}\nThe module input vector $\\bm s$ can be a vector of any length except for a zero-length vector.  The commanded body-relative unit direction vector ${\\bm s}_{c}$ is assumed to be fixed relative to the body.  ", "meta": {"hexsha": "514141e4427057c9dc392422ac89ddf9b1eba718", "size": 1302, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/fswAlgorithms/attGuidance/sunSafePoint/_Documentation/secModelFunctions.tex", "max_stars_repo_name": "ian-cooke/basilisk_mag", "max_stars_repo_head_hexsha": "a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fswAlgorithms/attGuidance/sunSafePoint/_Documentation/secModelFunctions.tex", "max_issues_repo_name": "ian-cooke/basilisk_mag", "max_issues_repo_head_hexsha": "a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-03-13T20:52:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-13T20:52:22.000Z", "max_forks_repo_path": "src/fswAlgorithms/attGuidance/sunSafePoint/_Documentation/secModelFunctions.tex", "max_forks_repo_name": "ian-cooke/basilisk_mag", "max_forks_repo_head_hexsha": "a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 86.8, "max_line_length": 384, "alphanum_fraction": 0.7734254992, "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.3000243859514274}}
{"text": "% !TEX root=../report.tex\n\n\\section{Overview}\n\n\\statefultrue\n\n\n\\subsection{Language}\n\n\\begin{grammar}\n  Expressions\n    & e    &::= & \\lambda x:\\tau.\\ e   & – abstraction \\\\\n    &      &\\mid& e_1\\ e_2             & – application \\\\\n    &      &\\mid& x                    & – variable \\\\\n    &      &\\mid& c                    & – constant \\\\\n    &      &\\mid& l                    & – location \\\\\n  \\addlinespace\n    &      &\\mid& e_1 \\star e_2        & – operate \\\\\n    &      &\\mid& \\If{e_1}{e_2}{e_3}   & – branch \\\\\n    &      &\\mid& \\tuple{e_1, e_2}     & – pair \\\\\n    &      &\\mid& \\unit                & – unit \\\\\n  \\addlinespace\n    &      &\\mid& \\Ref e               & – reference \\\\\n    &      &\\mid& !e                   & – dereference \\\\\n    &      &\\mid& e_1 := e_2           & – assign \\\\\n    &      &\\mid& e_1; e_2             & – sequence \\\\\n  \\addlinespace\n    &      &\\mid& p                    & – pretask \\\\\n  \\addlinespace\n  Constants\n    & c    &::= & B                    & – boolean \\\\\n    &      &\\mid& I                    & – integer \\\\\n    &      &\\mid& S                    & – string \\\\\n  \\addlinespace\n  Pretasks\n    & p    &::= & \\Edit e              & – valued editor \\\\\n    &      &\\mid& \\Enter \\beta         & – unvalued editor \\\\\n    &      &\\mid& \\Update e            & – stored editor \\\\\n  \\addlinespace\n    &      &\\mid& \\Fail                & – fail task \\\\\n  \\addlinespace\n    &      &\\mid& e_1 \\Then e_2        & – step \\\\\n    &      &\\mid& e_1 \\Next e_2        & – user step \\\\\n  \\addlinespace\n    &      &\\mid& e_1 \\And e_2         & – composition \\\\\n  \\addlinespace\n    &      &\\mid& e_1 \\Or e_2          & – choice \\\\\n    &      &\\mid& e_1 \\Xor e_2         & – user choice \\\\\n\\end{grammar}\n\n\n\n\\newpage\n\\subsection{Typing}\n\n\\begin{grammar}\n  Types\n    & \\tau &::= & \\tau_1 \\to \\tau_2    & – function type \\\\\n    &      &\\mid& \\tau_1 \\times \\tau_2 & – product type \\\\\n    &      &\\mid& \\Unit                & – unit type \\\\\n    &      &\\mid& \\Reference \\tau      & – reference type \\\\\n    &      &\\mid& \\Task \\tau           & – task type \\\\\n    &      &\\mid& \\beta                & – basic type \\\\\n    &      &\\mid& \\alpha               & – universal type \\\\\n  Basic types\n    &\\beta &::= & \\Bool                & – boolean type \\\\\n    &      &\\mid& \\Int                 & – integer type \\\\\n    &      &\\mid& \\String              & – string type \\\\\n\\end{grammar}\n\n\\begin{equation*}\n  \\boxed{\\RelationT}\n\\end{equation*}\n\n\\begin{mathpar}\n  \\userule{T-Abs}\\\\\n  \\userule{T-If}\\\\\n  \\userule{T-App}\\\\\n  \\userule{T-Edit} \\qquad \\userule{T-Enter} \\qquad \\userule{T-Update} \\\\\n  \\userule{T-Fail} \\\\\n  \\userule{T-Then} \\\\\n  \\userule{T-Next} \\\\\n  \\userule{T-And} \\\\\n  \\userule{T-Or} \\\\\n  \\userule{T-Xor}\n\\end{mathpar}\n\n\n\n\\subsection{Evaluating}\n\n\\begin{grammar}\n  Values\n    & v    &::= & \\lambda x:\\tau.\\ e        & – abstraction \\\\\n    &      &\\mid& \\tuple{v_1, v_2}     & – pair value \\\\\n    &      &\\mid& \\unit                & – unit \\\\\n    &      &\\mid& c                    & – constant \\\\\n    &      &\\mid& l                    & – location \\\\\n    &      &\\mid& t                    & – task \\\\\n  Tasks\n    & t    &::= & \\Edit v              & – valued editor \\\\\n    &      &\\mid& \\Enter \\beta         & – unvalued editor \\\\\n    &      &\\mid& \\Update l            & – stored editor \\\\\n    &      &\\mid& \\Fail                & – fail task \\\\\n    &      &\\mid& t_1 \\Then e_2        & – step \\\\\n    &      &\\mid& t_1 \\Next e_2        & – user step \\\\\n    &      &\\mid& t_1 \\And t_2         & – composition \\\\\n    &      &\\mid& t_1 \\Or t_2          & – choice \\\\\n    &      &\\mid& t_1 \\Xor t_2         & – user choice \\\\\n\\end{grammar}\n\nNotes:\n\\begin{itemize}\n  \\item $\\Then$ and $\\Next$ are strict in their first argument, lazy in their second.\n    It doesn't matter what the continuation is.\n  \\item $\\And$ and $\\Or$ is strict in both arguments.\n    \\todo{Explain why?}\n  \\item $\\Xor$ is lazy in both arguments.\n    Evaluating one or both options of $e_1 \\Xor e_2$ before the user makes a choice will result in untimely reference updates.\n  % \\item Although internal steps should be evaluated without user interaction,\n  %   $t \\Then e$ \\emph{is} a task value, iff $\\Value(t) = \\nothing$.\n  %   Take for example $t = \\Enter \\Int$.\n\\end{itemize}\n\n\\begin{equation*}\n  \\boxed{\\RelationV}\n\\end{equation*}\n\n\\begin{mathpar}\n  \\userule{E-Edit} \\qquad \\userule{E-Enter} \\qquad \\userule{E-Update} \\\\\n  \\userule{E-Fail} \\\\\n  \\userule{E-Then} \\qquad \\userule{E-Next} \\\\\n  \\userule{E-And} \\\\\n  \\userule{E-Or} \\qquad \\userule{E-Xor}\n\\end{mathpar}\n(Standard constructs as defined by \\textcite{books/Pierce02TAPL})\n\n\n\n\\subsection{Observing}\n\n\\begin{flalign*}\n  \\begin{array}{lcl}\n    \\multicolumn{3}{l}{\\Value : \\mathrm{Tasks} \\rightharpoonup \\mathrm{Values}} \\\\\n    \\Value(\\Edit v)       &=& v \\\\\n    \\Value(\\Enter \\tau)   &=& \\bot \\\\\n    \\Value(\\Update l, s)  &=& s(l) \\\\\n    \\Value(\\Fail)         &=& \\bot \\\\\n    \\Value(t_1 \\Then e_2) &=& \\bot \\\\\n    \\Value(t_1 \\Next e_2) &=& \\bot \\\\\n    \\Value(t_1 \\And t_2)  &=& \\left\\{\n      \\begin{array}{ll}\n        \\tuple{v_1, v_2}  & \\when\\ \\Value(t_1) = v_1 \\land \\Value(t_2) = v_2 \\\\\n        \\bot              & \\otherwise\n      \\end{array}\n    \\right. \\\\\n    \\Value(t_1 \\Or t_2)   &=& \\left\\{\n      \\begin{array}{ll}\n        v_1               & \\when\\ \\Value(t_1) = v_1 \\\\\n        v_2               & \\when\\ \\Value(t_1) = \\bot \\lor \\Value(t_2) = v_2 \\\\\n        \\bot              & \\otherwise\n      \\end{array}\n    \\right. \\\\\n    \\Value(t_1 \\Xor t_2)  &=& \\bot\n  \\end{array} & &&\n\\end{flalign*}\n\n\\begin{flalign*}\n  \\begin{array}{lcl}\n    \\multicolumn{3}{l}{\\Value_{\\stride} : \\mathrm{Tasks} \\rightharpoonup \\mathrm{Boolean}} \\\\\n    \\Value_{\\stride}(\\Edit e)       &=& \\True \\\\\n    \\Value_{\\stride}(\\Enter \\tau)   &=& \\True \\\\\n    \\Value_{\\stride}(\\Fail)         &=& \\True \\\\\n    \\Value_{\\stride}(e_1 \\Then e_2) &=& \\neg\\Value(e_1)\\wedge\\Value_{\\stride}(e_1) \\\\\n    \\Value_{\\stride}(e_1 \\Next e_2) &=& \\Value(e_1)\\vee\\Value_{\\stride}(e_1)\\\\\n    \\Value_{\\stride}(e_1 \\And e_2)  &=& \\Value_{\\stride}(e_1)\\wedge \\Value_{\\stride}(e_2) \\\\\n    \\Value_{\\stride}(t_1 \\Or t_2)   &=& \\neg(\\Value(e_1)\\vee\\Value(e_2))\\wedge\\Value_{\\stride}(e_1)\\wedge\\Value_{\\stride}(e_2) \\\\\n    \\Value_{\\stride}(t_1 \\Xor t_2)  &=& \\True\n  \\end{array} & &&\n\\end{flalign*}\n\n\\begin{flalign*}\n  \\begin{array}{lcl}\n    \\multicolumn{3}{l}{\\Failing : \\mathrm{Tasks} \\to \\mathrm{Booleans}} \\\\\n    \\Failing(\\Edit v)       &=& \\False \\\\\n    \\Failing(\\Enter \\tau)   &=& \\False \\\\\n    \\Failing(\\Update l)     &=& \\False \\\\\n    \\Failing(\\Fail)         &=& \\True \\\\\n    \\Failing(t_1 \\Then e_2) &=& \\Failing(t_1) \\\\\n    \\Failing(t_1 \\Next e_2) &=& \\Failing(t_1) \\\\\n    \\Failing(t_1 \\And t_2)  &=& \\Failing(t_1) \\wedge \\Failing(t_2) \\\\\n    \\Failing(t_1 \\Or t_2)   &=& \\Failing(t_1) \\wedge \\Failing(t_2) \\\\\n    \\Failing(t_1 \\Xor t_2)  &=& \\False\n  \\end{array} & &&\n\\end{flalign*}\n\n\\todo{Is $\\Failing$ preserved by $\\stride$?}\n\n\\begin{flalign*}\n  \\begin{array}{lcl}\n    \\multicolumn{3}{l}{\\Inputs : \\mathrm{Tasks} \\to \\powerset(\\mathrm{Inputs})} \\\\\n    \\Inputs(\\Edit v:\\Task\\tau)       &=& \\set{v':\\tau, \\Empty} \\\\\n    \\Inputs(\\Enter \\tau)   &=& \\set{v':\\tau} \\\\\n    \\Inputs(\\Update l:\\Task\\tau)     &=& \\set{v':\\tau} \\\\\n    \\Inputs(\\Fail)         &=& \\set{} \\\\\n    \\Inputs(t_1 \\Then e_2) &=& \\Inputs(t_1) \\\\\n    \\Inputs(t_1 \\Next e_2) &=& \\Inputs(t_1) \\cup \\set{\\Continue\\mid \\Value{(t_1)}\\neq \\bot \\wedge \\neg\\Failing{(e_2 \\Value{(t_1)}\\stride)}} \\\\\n    \\Inputs(t_1 \\And t_2)  &=& \\set{\\First\\ i \\mid i \\in \\Inputs(t_1)} \\cup \\set{\\Second\\ i \\mid i \\in \\Inputs(t_2)} \\\\\n    \\Inputs(t_1 \\Or t_2)   &=& \\set{\\First\\ i \\mid i \\in \\Inputs(t_1)} \\cup \\set{\\Second\\ i \\mid i \\in \\Inputs(t_2)} \\\\\n    \\Inputs(e_1 \\Xor e_2)  &=& \\set{\\Pick \\Left, \\Pick \\Right}\n  \\end{array} & &&\n\\end{flalign*}\n\n\n\n\\newpage\n\\subsection{Normalising}\n\n\\begin{equation*}\n  \\boxed{\\RelationN}\n\\end{equation*}\n\n\\paragraph{Step}\n\\begin{mathpar}\n  \\userule{S-ThenStay} \\\\\n  \\userule{S-ThenFail} \\\\\n  \\userule{S-ThenCont}\n\\end{mathpar}\n\n\\paragraph{Choose}\n\\begin{mathpar}\n  \\userule{S-OrLeft} \\\\\n  \\userule{S-OrRight} \\\\\n  \\userule{S-OrNone}\n\\end{mathpar}\n\n\\paragraph{Congruence}\n\\begin{mathpar}\n  \\userule{S-Next} \\\\\n  \\userule{S-And}\n\\end{mathpar}\n\n\\paragraph{Ready}\n\\begin{mathpar}\n  \\userule{S-Edit} \\qquad \\userule{S-Fill} \\qquad \\userule{S-Update} \\\\\n  \\userule{S-Fail} \\qquad \\userule{S-Xor}\n\\end{mathpar}\n\n\\paragraph{Driving}\n\\begin{mathpar}\n  \\userule{S-Eval}\n\\end{mathpar}\n\n\\todo{Do we need to normalise \\refrule{S-And} further to a pair for nice equality properties or can we just use $\\Value(t)$ to check if we have a pair?}\n\n\n\n\\subsection{Handling}\n\n\\begin{grammar}\n  Inputs\n    & i    & ::=& a                    & – action \\\\\n    &      &\\mid& \\First i             & – pass to first \\\\\n    &      &\\mid& \\Second i            & – pass to second \\\\\n  Actions\n    & a    & ::=& v                    & – change editor to value \\\\\n    &      &\\mid& \\Empty               & – empty an editor \\\\\n    &      &\\mid& \\Continue            & – continue with next task \\\\\n    &      &\\mid& \\Pick r              & – pick route \\\\\n  Routes\n    & r    & ::=& \\Left r              & – go left \\\\\n    &      &\\mid& \\Right r             & – go right \\\\\n    &      &\\mid& \\Here                & – stay here \\\\\n\\end{grammar}\n\n\\begin{equation*}\n  \\boxed{\\RelationH}\n\\end{equation*}\n\n\\paragraph{Editing}\n\\begin{mathpar}\n  \\userule{H-Change} \\qquad \\userule{H-Empty} \\qquad \\userule{H-Fill} \\\\\n  \\userule{H-Update}\n\\end{mathpar}\n\n\\todo{\n  Should $\\Fail$ be a black hole or just go stuck?\n  Probably it should go stuck, than $\\Inputs(\\Fail)$ is empty!\n}\n\n\\paragraph{Continuing}\n\\begin{mathpar}\n  \\userule{H-PickLeft} \\qquad \\userule{H-PickRight} \\\\\n  \\userule{H-PickHere} \\qquad \\userule{H-Next}\n\\end{mathpar}\n\n\\todo{\n  There is a problem with routes and picking $\\Here$(ere):\n  It is an input you can always send, so it fucks up $\\Inputs$\\ldots\n  Should we only allow to pick $\\Left$ or $\\Right$ for the semantics?\n}\n\n\\paragraph{Passing}\n\\begin{mathpar}\n  \\userule{H-PassThen} \\qquad \\userule{H-PassNext} \\\\\n  \\userule{H-FirstAnd} \\qquad \\userule{H-SecondAnd} \\\\\n  \\userule{H-FirstOr}  \\qquad \\userule{H-SecondOr}\n\\end{mathpar}\n\n\n\n\\subsection{Driving}\n\n\\begin{equation*}\n  \\boxed{\\RelationD}\n\\end{equation*}\n\n\\begin{mathpar}\n  \\userule{D-Handle}\n\\end{mathpar}\n", "meta": {"hexsha": "a4bc4c878de772d2bc372420696aa7973b2db664", "size": 10344, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/report/overview.tex", "max_stars_repo_name": "mklinik/task-semantics", "max_stars_repo_head_hexsha": "e7b846338d5da59ed5d00aef81f9874cadbbdd9f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/report/overview.tex", "max_issues_repo_name": "mklinik/task-semantics", "max_issues_repo_head_hexsha": "e7b846338d5da59ed5d00aef81f9874cadbbdd9f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/report/overview.tex", "max_forks_repo_name": "mklinik/task-semantics", "max_forks_repo_head_hexsha": "e7b846338d5da59ed5d00aef81f9874cadbbdd9f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2242990654, "max_line_length": 152, "alphanum_fraction": 0.5141144625, "num_tokens": 3655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.30002115554253966}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n\\section{The standard electroweak model}\n\n\\subsection{Gauge theories}\n\n\\marginpar{Tuesday\\\\ 2021-12-7}\n\nYesterday we wrote the equation for a free fermion: \n%\n\\begin{align}\n\\xi_{R, L} ' = \\exp(- i \\vec{\\omega} \\cdot \\frac{\\vec{\\sigma}}{2} \\pm \\vec{u} \\cdot \\frac{\\vec{\\sigma}}{2}) \\xi _{R, L}\n\\,.\n\\end{align}\n\nThe Dirac equation tells us that these are coupled: \n%\n\\begin{align}\n\\left[\\begin{array}{cc}\n-m & E + \\vec{p} \\cdot \\vec{\\sigma} \\\\ \nE - \\vec{p} \\cdot \\vec{\\sigma} & m\n\\end{array}\\right]\n\\left[\\begin{array}{c}\n\\xi _R \\\\ \n\\xi _L\n\\end{array}\\right]\n= 0 \n\\,.\n\\end{align}\n\nFor nonzero mass these components are coupled, while in the zero-mass case they are decoupled and helicity is equal to chirality. \n\nHelicity is the eigenvalue under \\(\\hat{p} \\cdot \\vec{\\sigma}\\), chirality is the eigenvalue under \\(\\gamma^{5}\\). \n\n\\todo[inline]{What is the meaning of \\(\\gamma^{5}\\) in position space? Is it a parity transformation?}\n\nThe coupling of a fermion to an external EM field can be represented with \\(\\partial_{\\mu } \\to \\partial_{\\mu } + iq A_\\mu \\). \n\nThe SM Lagrangian can be written on a mug as  \n%\n\\begin{align}\n\\mathscr{L} = - \\frac{1}{4} F^{\\mu \\nu } F_{\\mu \\nu } \n+ i \\overline{\\psi} \\slashed{D} \\psi + \\text{h.c.}\n+ i \\psi_i y_{ij} \\psi_j \\phi  + \\text{h.c.}\n+ \\abs{\\slashed{D} \\phi }^2 - V(\\phi )\n\\,.\n\\end{align}\n\nWe have scalars \\(\\phi \\), fermions \\(\\psi \\) and spin-1 gauge fields \\(A_\\mu \\). \n\nFrom a Lagrangian \\(L (q, \\dot{q})\\) we get Lagrange equations \n%\n\\begin{align}\n\\dv{}{t} \\pdv{L}{\\dot{q}} - \\pdv{L}{q} = 0\n\\,.\n\\end{align}\n\nIf the Lagrangian is, say, \\(L = m \\dot{q}^2 / 2 - V(q)\\) we get Newton's law \\(m \\ddot{q} = - \\vec{\\nabla} V = F\\). \n\nThis is classical; in field theory we have Lagrangians in the form \n%\n\\begin{align}\n\\partial_{\\mu } \\pdv{\\mathscr{L}(\\phi , \\partial \\phi )}{ \\partial_{\\mu } \\phi _i} - \\pdv{\\mathscr{L}}{\\phi _i} = 0\n\\,.\n\\end{align}\n\nWe will write the Yukawa Lagrangian with terms like \\(\\psi \\phi \\), and the QED Lagrangian with terms like \\(\\psi A_\\mu \\). \n\nThe equation of motion for a scalar field is the Klein-Gordon equation: \\((\\partial_{\\mu } \\partial^{\\mu } + m^2) \\phi = 0\\). \nThe Lagrangian giving rise to this is \n%\n\\begin{align}\nL = \\frac{1}{2} \\partial_{\\mu } \\phi \\partial^{\\mu } \\phi - \\frac{1}{2} m \\phi^2\n\\,.\n\\end{align}\n\nWe have written the EOM for a free fermion, the Dirac equation \\(\\left(i \\gamma^{\\mu } \\partial_{\\mu } - m\\right) \\psi = 0\\); the Lagrangian giving it is the Dirac Lagrangian \n%\n\\begin{align}\n\\mathscr{L} = \\overline{\\psi} \\left(i \\gamma^{\\mu } \\partial_{\\mu } - m\\right) \\psi \n\\,.\n\\end{align}\n\nAgain, we have a mass-like term and a kinetic-like term.\n\nThe term \\(m \\overline{\\psi} \\psi\\) can be expanded into left and right components: \n%\n\\begin{align}\nm \\overline{\\psi} \\psi = m \\left( \\overline{\\psi}_R \\psi _L + \\overline{\\psi}_L \\psi _R\\right)\n\\,.\n\\end{align}\n\nWhat about the EM field? \\(A_\\mu \\) is gauge-dependent, but \n%\n\\begin{align}\nF_{\\mu \\nu } = 2 \\partial_{[\\mu  } A_{\\nu ]}\n\\,\n\\end{align}\n%\nis not. The Lagrangian giving Maxwell's equations in a vacuum (so, \\(\\square A^{\\mu } = 0\\) in the appropriate gauge) is \n%\n\\begin{align}\n\\mathscr{L} = - \\frac{1}{4} F_{\\mu \\nu } F^{\\mu \\nu }\n\\,.\n\\end{align}\n\nThe absence of a mass term means that the photon is massless. \n\nWhat about interactions? \nWe start from the Yukawa interaction between a fermion and a scalar. \nThe Lagrangian, for starters, must contain the free terms for both: \n%\n\\begin{align}\n\\mathscr{L} = \\underbrace{\\overline{\\psi} \\left(i \\gamma^{\\mu } \\partial_{\\mu } - m_\\psi \\right) \\psi + \\frac{1}{2} \\left( \\partial_{\\mu } \\phi \\partial^{\\mu } \\phi -  m_\\phi  \\phi^2 \\right) }_{\\text{free terms}} - \\underbrace{g \\overline{\\psi} \\psi \\phi}_{\\text{interaction}} \n\\,.\n\\end{align}\n\nThe pictorial way to represent this is to draw quadratic terms for fermions like straight lines with an arrow, scalar fields as dashed lines, and cubic interaction terms like vertices. \n\nWhat do fermion-photon interactions look like?  \n%\n\\begin{align}\n\\mathscr{L} _{\\text{QED}} = \\overline{\\psi} \\left(i \\gamma^{\\mu } \\partial_{\\mu } - m_\\psi \\right) \\psi - \\frac{1}{4} F^{\\mu \\nu } F_{\\mu \\nu } - q \\overline{\\psi} \\gamma^{\\mu } \\psi A_\\mu \n\\,.\n\\end{align}\n\nThe EOM for the electromagnetic field are  Maxwell's equations with an external current \\(j^{\\mu } = q \\overline{\\psi} \\gamma^{\\mu } \\psi \\). \n\nThis is the same Lagrangian we get if we do a minimal coupling substitution \\(\\partial \\to \\partial + iqA\\). \nIt is invariant under gauge transformations. \n\nThese diagrams can be used to compute scattering amplitudes perturbatively. \n\nThe way to get a cross-section is to multiply the square modulus of the amplitude by the phase space term. \nThe idea to get decay rates is similar. \n\nThe guiding principle to describe EW interactions is gauge invariance. \nThe Yukawa Lagrangian has global phase invariance; what happens if we try to make a transformation \\(\\psi \\to e^{- i q \\alpha (a)} \\psi \\)?\nThe term \\(q\\) is only introduced here for later convenience.\n\nThe timezone analogy for local gauge invariance! \nIf we have the freedom to choose a phase locally, we must have carriers of information moving at the maximum possible speed, otherwise processes would be disrupted.\n\nWe start with \\(U(1)\\) gauge invariance, as written above, but we will also need \\(SU(2)\\) invariance, written as \n%\n\\begin{align}\n\\exp(- ig \\vec{\\theta} \\cdot \\vec{T})\n\\,,\n\\end{align}\n%\nwhere \\(\\vec{T} = \\vec{\\sigma} / 2\\), but we write them differently to not confuse them with spacetime rotations. \n\nIntroducing gauge invariance for a term \\(\\overline{\\psi} \\left(i \\slashed{\\partial} - m \\right) \\psi \\) will take us to the QED Lagrangian.\n\nThe mass term is already invariant, the problem is the kinetic one. \nThe trick is to introduce a covariant derivative \n%\n\\begin{align}\n\\text{D}_\\mu = \\partial_{\\mu } + iq A_\\mu \n\\,.\n\\end{align}\n\nIf \\(\\psi \\to e^{-iq \\alpha (x)} \\psi \\), also \\(\\text{D}_\\mu \\psi \\to e^{-iq \\alpha (x)} \\text{D}_\\mu \\psi \\), as long as \\(A_\\mu \\) also transforms like \\(A_\\mu \\to A_\\mu + \\partial_{\\mu } \\alpha \\).\n\nThen, the Lagrangian \n%\n\\begin{align}\n\\mathscr{L} = \\overline{\\psi} \\left( i \\slashed{\\text{D}} - m \\right) \\psi  - \\frac{1}{4} F^{\\mu \\nu } F_{\\mu \\nu }\n\\,.\n\\end{align}\n\nA term like \\(m^2 A_{\\mu } A^{\\mu }\\) would violate gauge invariance, so this principle also gives an explanation as to why the photon is massless if we accept the gauge invariance principle. \n\nProtons and neutrons were thought to be part of a doublet under isospin SU(2) transformations. \n\nBut, we have interactions like protons and neutrons interacting with electrons and neutrinos. \nSo, one might think that electrons + neutrinos have isospin-like SU(2) symmetry as well. \n\nWe want to make the doublet \\(\\psi_1 , \\psi_2 \\) invariant under SU(2) transformations as written above: how do we do it? \nAgain, we redefine the derivative: \n%\n\\begin{align}\n\\partial_{\\mu } \\to \\text{D}_\\mu - ig \\vec{T} \\cdot \\vec{A}_\\mu \n\\,,\n\\end{align}\n%\nso we need to introduce three fields \\(\\vec{A}_\\mu \\). These are the gauge bosons related to SU(2) gauge invariance. \n\nThese now transform like \n%\n\\begin{align}\n\\vec{A}_\\mu \\to \\vec{A}_\\mu - \\partial_{\\mu } \\vec{\\theta}(x) + g \\vec{\\theta} \\times \\vec{A}_\\mu \n\\,.\n\\end{align}\n\nThe presence of this coupling means that the field is charged. \n\nThe field tensor here is \n%\n\\begin{align}\n\\vec{F}_{\\mu \\nu } = 2 \\partial_{[\\mu } A_{\\nu ]} + g \\vec{A}_\\mu \\times \\vec{A}_\\nu \n\\,.\n\\end{align}\n\nWe then get a Lagrangian like \n%\n\\begin{align}\n\\mathscr{L} = \\overline{\\psi} \\left( i \\gamma^{\\mu } \\text{D}_\\mu -m\\right) \\psi - \\frac{1}{4} \\vec{F}^{\\mu \\nu } \\cdot \\vec{F}_{\\mu \\nu }\n\\,.\n\\end{align}\n\nIn the \\(\\psi \\) term we have \\(\\psi \\psi \\) terms, as well as \\(\\psi \\psi A\\) interactions.  \nIn this \\(F^2\\) term we have quadratic, trilinear and quadrilinear terms in \\(A\\)! \n\nThe actual group for the EW theory is \\(SU(2)_L \\otimes U(1)_Y\\). \nThe simplest EW world contains \n\\begin{enumerate}\n    \\item 1 massive electron, with both right- and left-handed components;\n    \\item 1 massless \\(\\nu _e\\), with only the left-handed component;\n    \\item EM interactions (we want to have a diagram describing how the electron interacts with a massless photon); \n    \\item weak chiral interactions like \\(\\nu _L e_L W^{\\pm}\\), where \\(W^{\\pm}\\) is massive.\n\\end{enumerate}\n\nThe Higgs mechanism accomplishes this, and it also gives mass to fermions. \nIf neutrinos have Majorana masses, the Higgs mechanism cannot give them mass. \n\nLet us define a doublet \\(L=(e_L, \\nu _{e, L})\\), and a singlet \\(R = e_R\\). \nThe theory must then be invariant if we redefine \n%\n\\begin{align}\nL &\\to L' = \\exp(-i g \\vec{\\theta}(x) \\cdot \\vec{T}) L  \\\\\nR &\\to R' = R\n\\,.\n\\end{align}\n\nThe doublet \\(L\\) corresponds to the \\(T_3 = \\pm 1/2\\) quantum numbers, while \\(T_3 = 0\\) for the singlet. \n\nCould the three bosons be some combinations  of the photon and the two \\(W^{\\pm}\\) bosons? We know that the charge operator \\(Q\\) has eigenvalues \\(0\\), \\(-1\\)  for the doublet, but \\(\\Tr Q \\neq 0\\) while \\(\\Tr T_i = 0\\) for all \\(T_i\\). \n\nWhy would \\(Q\\) need to be able to be written as a function of the \\(T_i\\)? \nThe proper answer lies in Nöther's theorem. \n\nWe therefore introduce a further hypercharge symmmetry: \n%\n\\begin{align}\nL' &= \\exp(- i g' \\beta (x) \\frac{Y}{2}) L \\\\\nR' &= \\exp(- i g' \\beta (x) \\frac{Y}{2}) R\n\\,,\n\\end{align}\n%\nso that this generator commutes with the \\(T_i\\), and indeed \\([T_i, Y] = 0\\). The only way to have this is \\(Y \\propto Q - T_3\\), and indeed \\(Y = 2 (Q - T_3)\\). \n\nIn the end, the Lagrangian must be chargeless. \n\nThe full transformation is therefore \n%\n\\begin{align}\nL' = \\exp(-i g \\vec{\\theta}(x) \\cdot \\vec{T} - ig' \\beta (x) \\frac{Y}{2}) L \\\\\nR' = \\exp( - ig' \\beta (x) \\frac{Y}{2}) R\n\\,.\n\\end{align}\n\nThe procedure is then like before: we need to redefine the derivative, as \n%\n\\begin{align}\n\\text{D}_\\mu L =\\left(  \\partial_{\\mu } + i g \\vec{T} \\cdot \\vec{A}_\\mu - i g' \\frac{Y}{2} B_\\mu  \\right) L\n\\,,\n\\end{align}\n%\nso we have four fields, the three \\(\\vec{A}_\\mu \\) with their \\(\\vec{F}_{\\mu \\nu }\\) and \\(B_\\mu \\) with its \\(G_{\\mu \\nu }\\). \n\nThe Lagrangian will then read \n%\n\\begin{align}\n\\mathscr{L} = \n\\overline{L} i \\gamma^{\\mu } \\text{D}_\\mu L \n+ \n\\overline{R} i \\gamma^{\\mu } \\text{D}_\\mu R + \\text{kinetic}\n\\,,\n\\end{align}\n%\nbut we cannot write mass terms like \\(m \\overline{\\psi} \\psi \\), which would be \\(\\overline{L} R\\) or \\(L \\overline{R}\\): the matrix dimensions don't match up! \n\nSo, everything's massless: the Higgs mechanism comes to the rescue. \nIt gives masses to all the bosons except the photon, as well as giving mass to the leptons. \n\nSuppose we have a \\(U(1) \\otimes U(1)\\) symmetry, spontaneously broken to \\(U(1)\\). The thing we think of is a pencil about to fall on a table. \n\n\n\n\\end{document}\n", "meta": {"hexsha": "d278d68a61b9bd65ab6bc04d0473d1053024fc28", "size": 10862, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "phd_courses/theoretical_low_energy_astroparticle/dec07.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "phd_courses/theoretical_low_energy_astroparticle/dec07.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phd_courses/theoretical_low_energy_astroparticle/dec07.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 37.0716723549, "max_line_length": 277, "alphanum_fraction": 0.6624010311, "num_tokens": 3668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.30002115554253966}}
{"text": "\\documentclass[main.tex]{subfiles}\n\\begin{document}\n\n% \\marginpar{Thursday\\\\ 2019-11-21, \\\\ compiled \\\\ \\today}\n% \\section*{Thu Nov 21 2019}\n\n% We exponentiate the equation from before: \n% we get \nWe can approximate this as \n%\n\\begin{align}\n  X_d \\approx X_n (1 - X_n)\n  \\exp(-29.33 + \\frac{25.82}{T_9  } - \\frac{3}{2} \\log T_9 + \\log ( \\Omega_{0b} h^2 ))\n\\,,\n\\end{align}\n%\nwhere \\(T_9  =  T / \\SI{e9}{K}\\). \nThe factor \\(\\Omega_{0b} h^2\\) comes from the scaling of the baryon-to-photon ratio \\(\\eta\\) (equation \\eqref{eq:baryon-to-photon-ratio}).\n\n\\todo[inline]{\\textcite[]{paccianiAppuntiCorsoPhysical2018} says we use the exponential decay of the neutron population to find this formula: how does it come in, though?}\n\n% \\todo[inline]{What is going on? What is \\(T_{\\rho }\\)? }\n\n% We want to understand why there is so much He-4 in the universe, since it is destroyed in stars! \nAlmost all the deuterium which is formed then turns into \\ce{^{4}He}, so since those nuclei are as heavy as four neutrons, and two neutrons are needed to make each we can estimate that the helium mass fraction will be given by \\(Y \\approx 2 X_n \\approx \\num{.25}\\). \nThe calculation is quite rough, in order to do it properly we should use the Boltzmann equation. \n\n\\todo[inline]{Very rough calculation\\dots the corrective factor of \\num{.8} is kind of thrown in there, also I think using \\(\\exp(-1.5)\\) instead of \\(\\exp(-1.3)\\) helps nudging the number and hides just how rough this is}\n\n% \\todo[inline]{This is indirect evidence for dark energy: why?}\n\nThis provides an experimental bound for many parameters: the lifetime of the neutron, for example, cannot be much shorter since otherwise too many would have decayed before forming deuterium. \n\nThe reaction rate \\(\\Gamma \\) for weak interactions, as we have discussed earlier, is given by \\(\\Gamma \\sim G_F^2 T^5 \\approx T^{5} / \\tau _n\\), where the Fermi coupling constant \\(G_F\\) is connected to the lifetime of the neutron \\(\\tau_n\\) since that is also a weak-interaction process.\n\nThen, the moment of decoupling \\(\\Gamma \\sim H\\) also constrains \\(\\tau _n\\), since it happens at a temperature \\(T_{d \\nu } \\sim G_F^{-2/3} m_P^{-1/3} \\approx \\tau_n^{4/3} m_P^{-1/3}\\).\\footnote{One might think that the lifetime of the neutron would be a well-established result in Earthly particle physics, but in fact there is a conflict between two different kinds of measurements \\cite[]{wolchoverNeutronLifetimePuzzle}, so while the value is roughly known the error bars of these measurements do not overlap: this is the ``neutron lifetime puzzle''.}\n% Let us suppose we increase the lifetime of neutrons, \\(\\tau_{1/2}\\). \n% This changes the moment at which we reach equation \\(\\Gamma \\sim H\\). \n\nIncreasing the lifetime of neutrons decreases the amount of He-4 in the universe. \n\nWe know that the Hubble parameter is given by\n%\n\\begin{align}\n  H^2 = \\frac{8 \\pi G}{3} \\underbrace{\\frac{\\pi^2}{30} g_{*}(T) T^4}_{\\rho = \\rho _r}\n\\,,\n\\end{align}\n%\nso \\(H(T) \\sim \\sqrt{g_* (T)}\\): this means that if we add more particles to our model which are coupled in the \\(\\sim \\SI{}{MeV}\\) range, thus increasing \\(g_*\\) at that temperature, we also increase \\(H\\), which means that the moment at which \\(\\Gamma < H\\) comes about earlier, meaning that we get more Helium. \nThis is very useful constraint on our models; for instance, any dark matter particle we hypothesize needs to not ``break baryogenesis''.\n\n% If we fix the temperature, and change \\(g_{*}\\) (by adding degrees of freedom), then we get more He-4. \n\n% This gives us observational constraints on the additions of exotic particles to our theory, since that would change \\(g_{*}\\). \n% This bounds the number of neutrino families by \\num{3.} something, so there cannot be more than \\num{3} families of light neutrinos. \n\n% If gravitons are thermal, then they also contribute to radiation. \n\nDecreasing the baryon fraction \\(\\Omega_b\\) inhibits the production of deuterium, since then there are more photons to disassociate them. \nWe find that the model fits observation as long as \\(\\num{.011} h^{-2}\\leq \\Omega_{0b} \\leq \\num{.25} h^{-2}\\); most people agree that we are near the upper bound of this range.\n\nThere is also another parameter, \\(m_P \\sim G^{-1/2}\\): modified gravity theories often predict variations of the gravitational constant with time, but since this appears in our calculations we can constrain its value at that stage in the early universe.\n\n\\section{Dark Matter dynamics}\n\nWe have described how dark matter came to be accepted as a necessary component of the matter content of the universe, now we wish to understand what are its basic properties. \n\nObservationally, dark matter has no relevant electromagnetic interactions: in the low-redshift universe it only interacts gravitationally (it is \\emph{decoupled}), and is able to cluster.\n\nThis allows us to distinguish it from dark energy, which instead is uniformly distributed. \n\nModels of dark matter can be classified into \\textbf{Hot and Cold dark matter}: HDM and CDM. \nWe can also have \\emph{Warm} dark matter, which has intermediate properties.\n\nIn \\textbf{HDM}, particles decoupled while they were ultrarelativistic, so they have very high thermal motion.\nThey move fast, and tend to destroy gravitational potential wells in which they might settle by moving out of them, and thus decreasing the quantity of matter there. \nNeutrinos were thought to be Dark Matter, and would have been classified as HDM. \n\nThey do this on scales comparable to the maximum distance travelled by them: this is calculated as \\(vt\\), where \\(v\\) is their average thermal velocity, and \\(t\\) is the age of the universe. \n\nThis means that the structures formed in the presence of HDM are larger than \\(\\num{e15} M_{\\odot}\\); however this seems to conflict with observation, since we also see smaller structures!\nThe hypothesis is then that they were formed later, by fragmentation: this is known as the \\emph{top-down approach}. \n\nThe top-down approach, however, is falsified by the observation of high-redshift quasars combined with the scale of the anisotropies of the CMB: in order to account fo high-redshift small-scale structures (we have seen stars at \\(z \\sim 20\\)!) we would have to increase the amplitude of the anisotropies to a scale which is not compatible to the anisotropies we see in the CMB. \nThis does not mean that HDM cannot exist, but it cannot make up most of the observed DM density. \n\n\\textbf{CDM}, on the other hand, is dark matter which decoupled at a time when it was already nonrelativistic. \nA \\emph{bottom-up} approach to structure formation is compatible with the existence of CDM.\nThis is the kind of dark matter which appears in the currently-accepted \\(\\Lambda\\)CDM model of cosmology.\n\nAlthough it is the best model to date, there are also issues with CDM, which are current research topics.\nDark matter is distributed in \\emph{halos}, gravitationally-bound regions which contain dark matter and are currently decoupled from cosmic expansion.\n\nOne issue is that simulations predict small-scale halos in the larger ones, which are however not observed.\nAlso, the density profiles from simulations do not seem to match what is observed: they have a cusp in the center of the halo, while observations suggest that density profiles are flat in the center.\n\nThere are many proposed solutions to these problems: for example, dark matter could self-interact in ways other than gravitational, or it could be warm.\n\n% We also have a bottom-up approach, which is compatible with CDM. \n\n% Now, neutrinos are not useful for cosmology. \n\n% We have \\(\\Gamma \\sim T^{5}\\), and \\(\\Gamma = H\\): \n% \\(T^{5} / \\tau_{1/2} \\sim T^2\\) implies that \\(\\tau_{1/2} \\sim T^{3}\\). \n\n% The decouplig temperature for HDM is larger than the temperature at which they become nonrelativistic, which is of the order of the mass. \n\n% For CDM, instead, the decoupling temperature is \\emph{smaller} than the temperature at which they become relativistic. \n\n\\subsection{The Boltzmann equation and decoupling}\n\nIn order to understand how Dark Matter evolves, let us introduce the main equation used to analyze non-equilibrium phenomena: the \\textbf{Boltzmann equation}. It describes the evolution of the phase space distribution of particles, \\(f\\). Its compact form is:\n%\n\\begin{align}\n  \\mathbb{L} [f] = \\mathbb{C} [f]\n\\,,\n\\end{align}\n%\nwhere \\(\\mathbb{L}\\) is the \\emph{Liouville operator}, which is a total derivative of the phase space density with respect to changes in time, position as well as momentum; while \\(\\mathbb{C}\\) is the \\emph{collision operator}, which describes the effect (in terms of variation per unit time) on the phase space distribution of collisions between particles --- it is written in terms of scattering matrices. \n% where all the scattering operators live on the RHS. \nIn general, we should consider the phase space distribution of all the particle species, writing an equation for each of theses \\(f_i\\); now we will treat a single particle species for simplicity. \n\nThis basic form is quite general: it can be used both for a simple Newtonian calculation and to include general-relativistic and quantum-mechanical effects.\n\nWe start with the Newtonian description: the phase space has position, momentum and time as coordinates, and a density function \\(f(\\vec{q}, \\vec{p}, t)\\) is defined on it. \n\n% The Einstein equations are blind to the momentum distribution, since \\(T_{\\mu \\nu }\\) does not depend on the momentum.\n% We can say that all of the momentum has been marginalized. \n\nThe classical form of the Liouville operator is the \\emph{convective derivative},\n%\n\\begin{subequations}\n\\begin{align}\n  \\mathbb{L} = \\frac{D}{Dt} &= \\pdv{}{t} + \\dv{\\vec{x}}{t} \\cdot \\nabla_x + \\dv{\\vec{p}}{t} \\cdot \\nabla_p   \\\\\n  &= \\pdv{}{t} + \\vec{v} \\cdot \\nabla_x + \\frac{\\vec{F}}{m} \\cdot \\nabla_p \n\\,. \n\\end{align}\n\\end{subequations}\n\n% Applying this to a classical fluid yields the Navier-Stokes equations, as long as we distinguish the force term \\(\\vec{F}\\) into forces proportional to volume and forces proportional to area. \nThis equation describes motion in much more detail than, say, the Navier-Stokes equations, since it allows for arbitrary momentum \\emph{at each point} in space. \nWe can recover the N-S equations, as well as the energy and mass conservation equations, by taking \\emph{moments} of the Boltzmann equation: we multiply it by \\(m \\vec{v}\\), or \\(m v^2 / 2\\), or \\(m\\), and integrate in \\(\\dd[3]{p}\\).\n\nIn the Newtonian case, the force term \\(\\vec{F}\\) includes gravity, which in GR instead is ``geometrized'', meaning that it is included in the inertial motion of the particles. \nThe relativistic version of the Liouville operator is written in terms of position \\(x^{\\alpha }\\) and momentum \\(p^{\\alpha } = \\dv*{x^{\\alpha }}{\\lambda }\\)\n%\n\\begin{align}\n\\mathbb{L} \n&= \\dv{x^{\\alpha }}{\\lambda } \\pdv{}{x^{\\alpha }} \n+ \\dv{p^{\\alpha }}{\\lambda } \\pdv{}{p^{\\alpha }} \\\\ \n&= p^{\\alpha } \\partial_{\\alpha } - \\Gamma^{\\alpha }_{\\beta \\gamma } p^{\\beta } p^{\\gamma } \\pdv{}{p^{\\alpha }}\n\\,.\n\\end{align}\n\n\\todo[inline]{Is the momentum supposed to be dimensionless or not? Setting \\(\\dv*{x^{\\alpha }}{\\lambda } = p^{\\alpha }\\) as well as \\(p^2= m^2\\) seems contradictory\\dots}\n\nThis is because, since any particle must move along geodesics, \\(p^{\\alpha }\\) must satisfy the geodesic equation: \n%\n\\begin{align}\n\\frac{Dp^{\\alpha }}{Dt } =\n\\dv{p^{\\alpha }}{\\lambda } + \\Gamma^{\\alpha }_{\\beta \\gamma } p^{\\beta } p^{\\gamma }=0\n\\,.\n\\end{align}\n\n% We can then write down the Christoffel bit of the geodesic equation instead of the derivative \\(\\dv*{p^{\\alpha }}{\\lambda }\\).\nWe require that the particles are \\emph{on shell}:\n%\n\\begin{align}\n  g^{\\alpha \\beta } p_{\\alpha } p_{\\beta } = m^2\n\\,,\n\\end{align}\n%\nmeaning that we are neglecting the uncertainty principle and our discussion is relativistic but classical (not fully quantum-mechanical).\n\n% We want to describe the \\emph{abundance} of dark matter, in phase space: the number of DM particle per EM-interacting particle. \n\nLet us make this explicit, using the Christoffel symbols of the FLRW metric and assuming isotropy and homogeneity (which together imply that the phase space density \\(f\\) only depends on \\(t\\) and \\(p^{0} = E\\)): many terms vanish, and we are left with\n% Acting on \\(f\\), we get \n%\n\\begin{align}\n\\mathbb{L}[f]  \n= p^{0} \\partial_{t}f - \\Gamma^{0}_{ij} p^{i} p^{j} \\pdv{f}{E}\n= E \\partial_t f - \\frac{\\dot{a}}{a} \\abs{\\vec{p}}^2 \\pdv{f}{E}\n\\,,\n\\end{align}\n%\n% which we will not prove. \n% The derivative with respect to the momentum must be \\(\\partial_{p^{0}}\\),\n% \\todo[inline]{because of isotropy?}\nsince the relevant Christoffel symbols (in Cartesian coordinates) are \n%\n\\begin{align}\n  \\Gamma^{0}_{ij } = \\frac{\\dot{a}}{a} \\delta_{ij }\n\\,.\n\\end{align}\n\nSo, we can write the Boltzmann equation as \n%\n\\begin{align}\n\\pdv{f}{t} - \\frac{\\dot{a}}{a} \\frac{p^2}{E} \\pdv{f}{E} = \\frac{\\mathbb{C} [f]}{E}\n\\,.\n\\end{align}\n\n% so in the end the equation becomes: \n% %\n% \\begin{align}\n%   \\hat{\\mathbb{L}} = \\dot{n} + 3 \\frac{\\dot{a}}{a} n \n% \\,. \n% \\end{align}\n% %\n\n% % Conventionally we divide by \\(p^{0}\\): we get for the Boltzmann equation: \n% %\n% \\begin{align}\n%   \\pdv{f}{t} - \\frac{\\dot{a}}{a } \\frac{p^2}{E} \\pdv{f}{E} = \\frac{1}{E} \\hat{\\mathbb{C}} [f]\n% \\,.\n% \\end{align}\n\nLet us now do what is also done in the classical case and integrate in \\(\\dd[3]{\\vec{p}}\\): we will lose detail in the description but gain in computability.\nFirst, recall the definition of the number density from the phase space distribution:\n%\n\\begin{align}\n  n(t) = \\frac{g}{(2\\pi )^3} \\int  \\dd[3]{\\vec{p}} f(\\abs{\\vec{p}}, t) \n\\,,\n\\end{align}\n%\nwhich appears in the first term if we integrate the Boltzmann equation (also multiplying by \\(g / (2 \\pi )^3\\)):\n%\n\\begin{align}\n  \\pdv{n}{t} - \\frac{g}{(2 \\pi )^3} \\frac{\\dot{a}}{a } \\int  \\dd[3]{\\vec{p}} \\frac{p^2}{E} \\dv{f}{E} = \\frac{g }{(2\\pi )^3} \\int  \\dd[3]{p} \\frac{1}{E} \\mathbb{C} [f]  \n\\,.\n\\end{align}\n%\n% More properly, we are doing \\(\\mathbb{L} \\expval{f}\\). \n\nThe number density actually also appears in the second term: we can manipulate it as\n%\n\\begin{subequations}\n\\begin{align}\n  \\int \\dd[3]{p} \\frac{p^2}{E} \\pdv{f}{E} \n  &= 2 \\int \\dd[3]{p} p^2 \\pdv{f}{(E^2)} \n  = 2 \\int \\dd[3]{p} p^2 \\pdv{f}{(p^2)}  \\marginnote{\\(\\dd{(E^2)} = 2 E \\dd{E}\\) and similarly for \\(\\dd{(p^2)}\\).}\\\\\n  &= \\int \\dd[3]{p} p \\pdv[]{f}{p} \n  = 4 \\pi \\int_{0}^{ \\infty } \\dd{p} p^3 \\pdv{f}{p}  \\\\\n  &= \\eval{4 \\pi p^3 f}_{0}^{\\infty } - 4 \\pi \\int_{0}^{\\infty } \\dd{p} 3 p^2 f \n  = -3 \\int \\dd[3]{p} f = -3n \\frac{(2 \\pi )^3}{g}\n\\,.\n\\end{align}\n\\end{subequations}\n\nThe boundary term vanishes since at \\(0\\) we have \\(p=0\\), and at (momentum) infinity we have \\(f=0\\) (since otherwise the energy would diverge). We are also moving back and forth between integrals in \\(\\dd[3]{p}\\) and in \\(\\dd{p}\\) times \\(4 \\pi \\), which we can do because of isotropy.\n\nSo, we can see that the left-hand side is equal to \\(\\dot{n} + 3 \\dot{a}n/a \\), and we have the \\textbf{cosmological Boltzmann equation}\n%\n\\begin{align}\n  \\dot{n} + 3 \\frac{\\dot{a}}{a} n = \\frac{g}{(2 \\pi )^3} \\int \\dd[3]{p} \\frac{1}{E} \\hat{\\mathbb{C}} [f]\n\\,.\n\\end{align}\n\n% This is the cosmological version of the Boltzmann equation. \n\nRight away we can see that this makes sense in the decoupling limit: if there are no collisions the right-hand side must vanish, so we are left with \n%\n\\begin{align}\n\\dot{n} + 3 \\frac{\\dot{a}}{a} n = \\dv{}{t} \\qty(n a^3) = 0\n\\,,\n\\end{align}\n%\nmeaning that \\(n \\propto a^{-3}\\): this is the usual scaling of the number density, so our approach is working. \n\nNow we need to understand what the right-hand side looks if particle species are coupled. This is difficult in general, we will give an expression using ``bulk'' parameters:\n%\n\\begin{align}\n  \\frac{g}{(2 \\pi )^3} \\int \\frac{ \\dd[3]{p}}{E} \\hat{\\mathbb{C}}[f] \n  = \\Psi - \\Gamma_A n\n  = \\Psi - \\expval{\\sigma v } n^2\n\\,,\n\\end{align}\n%\nwhere \\(\\Psi \\) is the rate of creation of particles per unit volume, while \\(\\Gamma_A\\) is the rate of annihilation. Note that \\(\\Psi \\) has the dimensions \\SI{}{s^{-1} m^{-3}}, while \\(\\Gamma _A\\) has the dimensions \\SI{}{s^{-1}}, so it needs to be multiplied by \\(n\\) in order to be dimensionally consistent. \nPhysically speaking, the reason the term has that form is that the rate of annihilation must be proportional to the number density of particles there are at the moment.\n\nThe annihilation rate is found in terms of the cross section of the process, which we must average over all the momentum distribution of the particles: this is the reason for the appearance of \\(\\expval{\\sigma v}\\).\n\n% where we have \\(\\Gamma_A = \\expval{\\sigma v} n\\) times \\(n\\), where \\(\\Gamma \\) is the rate of annihilation. \n\nAt equilibrium, the left-hand side is equal to zero. The number density will be given by some equilibrium value, \\(n _{\\text{eq}}\\): inserting this in the right-hand side, which must also vanish, we find \\(\\Psi = \\expval{\\sigma v} n^2 _{\\text{eq}}\\).\nThis result can then be used in general: the right-hand side is written as \\(\\expval{\\sigma v} \\qty(n^2 _{\\text{eq}} - n^2)\\).\n\n\\end{document}", "meta": {"hexsha": "258e8ee5fe334939232c919fad21d345d21e44ea", "size": 17166, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ap_first_semester/astrophysics_cosmology/21nov.tex", "max_stars_repo_name": "jacopok/notes", "max_stars_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-10-10T13:10:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T14:52:50.000Z", "max_issues_repo_path": "ap_first_semester/astrophysics_cosmology/21nov.tex", "max_issues_repo_name": "jacopok/notes", "max_issues_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ap_first_semester/astrophysics_cosmology/21nov.tex", "max_forks_repo_name": "jacopok/notes", "max_forks_repo_head_hexsha": "805ebe1be49bbd14c6b46b24055f9fc7d1cd2586", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T16:11:07.000Z", "avg_line_length": 59.1931034483, "max_line_length": 556, "alphanum_fraction": 0.7059303274, "num_tokens": 5086, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3000211555425396}}
